From e5b00f9b1058437ebe02faebbdb5e75590659ec4 Mon Sep 17 00:00:00 2001 From: click Date: Tue, 17 Aug 2010 02:14:20 +0200 Subject: Buildsystem: Use "industry standard" foldernames on dpendencies + move/rename ace-folder (for future upgrades/changes). This does not break anything, it has been tested with compile etc. --HG-- branch : trunk rename : externals/CMakeLists.txt => dep/CMakeLists.txt rename : externals/PackageList.txt => dep/PackageList.txt rename : externals/SFMT/SFMT-alti.h => dep/SFMT/SFMT-alti.h rename : externals/SFMT/SFMT-params.h => dep/SFMT/SFMT-params.h rename : externals/SFMT/SFMT-sse2.h => dep/SFMT/SFMT-sse2.h rename : externals/SFMT/SFMT.c => dep/SFMT/SFMT.c rename : externals/SFMT/SFMT.h => dep/SFMT/SFMT.h rename : externals/ace/ACE.cpp => dep/acelite/ace/ACE.cpp rename : externals/ace/ACE.h => dep/acelite/ace/ACE.h rename : externals/ace/ACE.inl => dep/acelite/ace/ACE.inl rename : externals/ace/ACE.pc.in => dep/acelite/ace/ACE.pc.in rename : externals/ace/ACE_crc32.cpp => dep/acelite/ace/ACE_crc32.cpp rename : externals/ace/ACE_crc_ccitt.cpp => dep/acelite/ace/ACE_crc_ccitt.cpp rename : externals/ace/ACE_export.h => dep/acelite/ace/ACE_export.h rename : externals/ace/ARGV.cpp => dep/acelite/ace/ARGV.cpp rename : externals/ace/ARGV.h => dep/acelite/ace/ARGV.h rename : externals/ace/ARGV.inl => dep/acelite/ace/ARGV.inl rename : externals/ace/ATM_Acceptor.cpp => dep/acelite/ace/ATM_Acceptor.cpp rename : externals/ace/ATM_Acceptor.h => dep/acelite/ace/ATM_Acceptor.h rename : externals/ace/ATM_Acceptor.inl => dep/acelite/ace/ATM_Acceptor.inl rename : externals/ace/ATM_Addr.cpp => dep/acelite/ace/ATM_Addr.cpp rename : externals/ace/ATM_Addr.h => dep/acelite/ace/ATM_Addr.h rename : externals/ace/ATM_Addr.inl => dep/acelite/ace/ATM_Addr.inl rename : externals/ace/ATM_Connector.cpp => dep/acelite/ace/ATM_Connector.cpp rename : externals/ace/ATM_Connector.h => dep/acelite/ace/ATM_Connector.h rename : externals/ace/ATM_Connector.inl => dep/acelite/ace/ATM_Connector.inl rename : externals/ace/ATM_Params.cpp => dep/acelite/ace/ATM_Params.cpp rename : externals/ace/ATM_Params.h => dep/acelite/ace/ATM_Params.h rename : externals/ace/ATM_Params.inl => dep/acelite/ace/ATM_Params.inl rename : externals/ace/ATM_QoS.cpp => dep/acelite/ace/ATM_QoS.cpp rename : externals/ace/ATM_QoS.h => dep/acelite/ace/ATM_QoS.h rename : externals/ace/ATM_QoS.inl => dep/acelite/ace/ATM_QoS.inl rename : externals/ace/ATM_Stream.cpp => dep/acelite/ace/ATM_Stream.cpp rename : externals/ace/ATM_Stream.h => dep/acelite/ace/ATM_Stream.h rename : externals/ace/ATM_Stream.inl => dep/acelite/ace/ATM_Stream.inl rename : externals/ace/Acceptor.cpp => dep/acelite/ace/Acceptor.cpp rename : externals/ace/Acceptor.h => dep/acelite/ace/Acceptor.h rename : externals/ace/Activation_Queue.cpp => dep/acelite/ace/Activation_Queue.cpp rename : externals/ace/Activation_Queue.h => dep/acelite/ace/Activation_Queue.h rename : externals/ace/Activation_Queue.inl => dep/acelite/ace/Activation_Queue.inl rename : externals/ace/Active_Map_Manager.cpp => dep/acelite/ace/Active_Map_Manager.cpp rename : externals/ace/Active_Map_Manager.h => dep/acelite/ace/Active_Map_Manager.h rename : externals/ace/Active_Map_Manager.inl => dep/acelite/ace/Active_Map_Manager.inl rename : externals/ace/Active_Map_Manager_T.cpp => dep/acelite/ace/Active_Map_Manager_T.cpp rename : externals/ace/Active_Map_Manager_T.h => dep/acelite/ace/Active_Map_Manager_T.h rename : externals/ace/Active_Map_Manager_T.inl => dep/acelite/ace/Active_Map_Manager_T.inl rename : externals/ace/Addr.cpp => dep/acelite/ace/Addr.cpp rename : externals/ace/Addr.h => dep/acelite/ace/Addr.h rename : externals/ace/Addr.inl => dep/acelite/ace/Addr.inl rename : externals/ace/Arg_Shifter.cpp => dep/acelite/ace/Arg_Shifter.cpp rename : externals/ace/Arg_Shifter.h => dep/acelite/ace/Arg_Shifter.h rename : externals/ace/Argv_Type_Converter.cpp => dep/acelite/ace/Argv_Type_Converter.cpp rename : externals/ace/Argv_Type_Converter.h => dep/acelite/ace/Argv_Type_Converter.h rename : externals/ace/Argv_Type_Converter.inl => dep/acelite/ace/Argv_Type_Converter.inl rename : externals/ace/Array.h => dep/acelite/ace/Array.h rename : externals/ace/Array_Base.cpp => dep/acelite/ace/Array_Base.cpp rename : externals/ace/Array_Base.h => dep/acelite/ace/Array_Base.h rename : externals/ace/Array_Base.inl => dep/acelite/ace/Array_Base.inl rename : externals/ace/Array_Map.cpp => dep/acelite/ace/Array_Map.cpp rename : externals/ace/Array_Map.h => dep/acelite/ace/Array_Map.h rename : externals/ace/Array_Map.inl => dep/acelite/ace/Array_Map.inl rename : externals/ace/Assert.cpp => dep/acelite/ace/Assert.cpp rename : externals/ace/Assert.h => dep/acelite/ace/Assert.h rename : externals/ace/Asynch_Acceptor.cpp => dep/acelite/ace/Asynch_Acceptor.cpp rename : externals/ace/Asynch_Acceptor.h => dep/acelite/ace/Asynch_Acceptor.h rename : externals/ace/Asynch_Connector.cpp => dep/acelite/ace/Asynch_Connector.cpp rename : externals/ace/Asynch_Connector.h => dep/acelite/ace/Asynch_Connector.h rename : externals/ace/Asynch_IO.cpp => dep/acelite/ace/Asynch_IO.cpp rename : externals/ace/Asynch_IO.h => dep/acelite/ace/Asynch_IO.h rename : externals/ace/Asynch_IO_Impl.cpp => dep/acelite/ace/Asynch_IO_Impl.cpp rename : externals/ace/Asynch_IO_Impl.h => dep/acelite/ace/Asynch_IO_Impl.h rename : externals/ace/Asynch_IO_Impl.inl => dep/acelite/ace/Asynch_IO_Impl.inl rename : externals/ace/Asynch_Pseudo_Task.cpp => dep/acelite/ace/Asynch_Pseudo_Task.cpp rename : externals/ace/Asynch_Pseudo_Task.h => dep/acelite/ace/Asynch_Pseudo_Task.h rename : externals/ace/Atomic_Op.cpp => dep/acelite/ace/Atomic_Op.cpp rename : externals/ace/Atomic_Op.h => dep/acelite/ace/Atomic_Op.h rename : externals/ace/Atomic_Op.inl => dep/acelite/ace/Atomic_Op.inl rename : externals/ace/Atomic_Op_GCC_T.cpp => dep/acelite/ace/Atomic_Op_GCC_T.cpp rename : externals/ace/Atomic_Op_GCC_T.h => dep/acelite/ace/Atomic_Op_GCC_T.h rename : externals/ace/Atomic_Op_GCC_T.inl => dep/acelite/ace/Atomic_Op_GCC_T.inl rename : externals/ace/Atomic_Op_Sparc.c => dep/acelite/ace/Atomic_Op_Sparc.c rename : externals/ace/Atomic_Op_Sparc.h => dep/acelite/ace/Atomic_Op_Sparc.h rename : externals/ace/Atomic_Op_T.cpp => dep/acelite/ace/Atomic_Op_T.cpp rename : externals/ace/Atomic_Op_T.h => dep/acelite/ace/Atomic_Op_T.h rename : externals/ace/Atomic_Op_T.inl => dep/acelite/ace/Atomic_Op_T.inl rename : externals/ace/Auto_Event.cpp => dep/acelite/ace/Auto_Event.cpp rename : externals/ace/Auto_Event.h => dep/acelite/ace/Auto_Event.h rename : externals/ace/Auto_Event.inl => dep/acelite/ace/Auto_Event.inl rename : externals/ace/Auto_Functor.cpp => dep/acelite/ace/Auto_Functor.cpp rename : externals/ace/Auto_Functor.h => dep/acelite/ace/Auto_Functor.h rename : externals/ace/Auto_Functor.inl => dep/acelite/ace/Auto_Functor.inl rename : externals/ace/Auto_IncDec_T.cpp => dep/acelite/ace/Auto_IncDec_T.cpp rename : externals/ace/Auto_IncDec_T.h => dep/acelite/ace/Auto_IncDec_T.h rename : externals/ace/Auto_IncDec_T.inl => dep/acelite/ace/Auto_IncDec_T.inl rename : externals/ace/Auto_Ptr.cpp => dep/acelite/ace/Auto_Ptr.cpp rename : externals/ace/Auto_Ptr.h => dep/acelite/ace/Auto_Ptr.h rename : externals/ace/Auto_Ptr.inl => dep/acelite/ace/Auto_Ptr.inl rename : externals/ace/Barrier.cpp => dep/acelite/ace/Barrier.cpp rename : externals/ace/Barrier.h => dep/acelite/ace/Barrier.h rename : externals/ace/Barrier.inl => dep/acelite/ace/Barrier.inl rename : externals/ace/Base_Thread_Adapter.cpp => dep/acelite/ace/Base_Thread_Adapter.cpp rename : externals/ace/Base_Thread_Adapter.h => dep/acelite/ace/Base_Thread_Adapter.h rename : externals/ace/Base_Thread_Adapter.inl => dep/acelite/ace/Base_Thread_Adapter.inl rename : externals/ace/Based_Pointer_Repository.cpp => dep/acelite/ace/Based_Pointer_Repository.cpp rename : externals/ace/Based_Pointer_Repository.h => dep/acelite/ace/Based_Pointer_Repository.h rename : externals/ace/Based_Pointer_T.cpp => dep/acelite/ace/Based_Pointer_T.cpp rename : externals/ace/Based_Pointer_T.h => dep/acelite/ace/Based_Pointer_T.h rename : externals/ace/Based_Pointer_T.inl => dep/acelite/ace/Based_Pointer_T.inl rename : externals/ace/Basic_Stats.cpp => dep/acelite/ace/Basic_Stats.cpp rename : externals/ace/Basic_Stats.h => dep/acelite/ace/Basic_Stats.h rename : externals/ace/Basic_Stats.inl => dep/acelite/ace/Basic_Stats.inl rename : externals/ace/Basic_Types.cpp => dep/acelite/ace/Basic_Types.cpp rename : externals/ace/Basic_Types.h => dep/acelite/ace/Basic_Types.h rename : externals/ace/Basic_Types.inl => dep/acelite/ace/Basic_Types.inl rename : externals/ace/Bound_Ptr.h => dep/acelite/ace/Bound_Ptr.h rename : externals/ace/Bound_Ptr.inl => dep/acelite/ace/Bound_Ptr.inl rename : externals/ace/CDR_Base.cpp => dep/acelite/ace/CDR_Base.cpp rename : externals/ace/CDR_Base.h => dep/acelite/ace/CDR_Base.h rename : externals/ace/CDR_Base.inl => dep/acelite/ace/CDR_Base.inl rename : externals/ace/CDR_Size.cpp => dep/acelite/ace/CDR_Size.cpp rename : externals/ace/CDR_Size.h => dep/acelite/ace/CDR_Size.h rename : externals/ace/CDR_Size.inl => dep/acelite/ace/CDR_Size.inl rename : externals/ace/CDR_Stream.cpp => dep/acelite/ace/CDR_Stream.cpp rename : externals/ace/CDR_Stream.h => dep/acelite/ace/CDR_Stream.h rename : externals/ace/CDR_Stream.inl => dep/acelite/ace/CDR_Stream.inl rename : externals/ace/CE_Screen_Output.cpp => dep/acelite/ace/CE_Screen_Output.cpp rename : externals/ace/CE_Screen_Output.h => dep/acelite/ace/CE_Screen_Output.h rename : externals/ace/CMakeLists.txt => dep/acelite/ace/CMakeLists.txt rename : externals/ace/CORBA_macros.h => dep/acelite/ace/CORBA_macros.h rename : externals/ace/Cache_Map_Manager_T.cpp => dep/acelite/ace/Cache_Map_Manager_T.cpp rename : externals/ace/Cache_Map_Manager_T.h => dep/acelite/ace/Cache_Map_Manager_T.h rename : externals/ace/Cache_Map_Manager_T.inl => dep/acelite/ace/Cache_Map_Manager_T.inl rename : externals/ace/Cached_Connect_Strategy_T.cpp => dep/acelite/ace/Cached_Connect_Strategy_T.cpp rename : externals/ace/Cached_Connect_Strategy_T.h => dep/acelite/ace/Cached_Connect_Strategy_T.h rename : externals/ace/Caching_Strategies_T.cpp => dep/acelite/ace/Caching_Strategies_T.cpp rename : externals/ace/Caching_Strategies_T.h => dep/acelite/ace/Caching_Strategies_T.h rename : externals/ace/Caching_Strategies_T.inl => dep/acelite/ace/Caching_Strategies_T.inl rename : externals/ace/Caching_Utility_T.cpp => dep/acelite/ace/Caching_Utility_T.cpp rename : externals/ace/Caching_Utility_T.h => dep/acelite/ace/Caching_Utility_T.h rename : externals/ace/Capabilities.cpp => dep/acelite/ace/Capabilities.cpp rename : externals/ace/Capabilities.h => dep/acelite/ace/Capabilities.h rename : externals/ace/Capabilities.inl => dep/acelite/ace/Capabilities.inl rename : externals/ace/Cleanup.cpp => dep/acelite/ace/Cleanup.cpp rename : externals/ace/Cleanup.h => dep/acelite/ace/Cleanup.h rename : externals/ace/Cleanup.inl => dep/acelite/ace/Cleanup.inl rename : externals/ace/Cleanup_Strategies_T.cpp => dep/acelite/ace/Cleanup_Strategies_T.cpp rename : externals/ace/Cleanup_Strategies_T.h => dep/acelite/ace/Cleanup_Strategies_T.h rename : externals/ace/Codecs.cpp => dep/acelite/ace/Codecs.cpp rename : externals/ace/Codecs.h => dep/acelite/ace/Codecs.h rename : externals/ace/Codeset_IBM1047.cpp => dep/acelite/ace/Codeset_IBM1047.cpp rename : externals/ace/Codeset_IBM1047.h => dep/acelite/ace/Codeset_IBM1047.h rename : externals/ace/Codeset_Registry.cpp => dep/acelite/ace/Codeset_Registry.cpp rename : externals/ace/Codeset_Registry.h => dep/acelite/ace/Codeset_Registry.h rename : externals/ace/Codeset_Registry.inl => dep/acelite/ace/Codeset_Registry.inl rename : externals/ace/Codeset_Registry_db.cpp => dep/acelite/ace/Codeset_Registry_db.cpp rename : externals/ace/Codeset_Symbols.h => dep/acelite/ace/Codeset_Symbols.h rename : externals/ace/Condition_Recursive_Thread_Mutex.cpp => dep/acelite/ace/Condition_Recursive_Thread_Mutex.cpp rename : externals/ace/Condition_Recursive_Thread_Mutex.h => dep/acelite/ace/Condition_Recursive_Thread_Mutex.h rename : externals/ace/Condition_T.cpp => dep/acelite/ace/Condition_T.cpp rename : externals/ace/Condition_T.h => dep/acelite/ace/Condition_T.h rename : externals/ace/Condition_T.inl => dep/acelite/ace/Condition_T.inl rename : externals/ace/Condition_Thread_Mutex.cpp => dep/acelite/ace/Condition_Thread_Mutex.cpp rename : externals/ace/Condition_Thread_Mutex.h => dep/acelite/ace/Condition_Thread_Mutex.h rename : externals/ace/Condition_Thread_Mutex.inl => dep/acelite/ace/Condition_Thread_Mutex.inl rename : externals/ace/Configuration.cpp => dep/acelite/ace/Configuration.cpp rename : externals/ace/Configuration.h => dep/acelite/ace/Configuration.h rename : externals/ace/Configuration.inl => dep/acelite/ace/Configuration.inl rename : externals/ace/Configuration_Import_Export.cpp => dep/acelite/ace/Configuration_Import_Export.cpp rename : externals/ace/Configuration_Import_Export.h => dep/acelite/ace/Configuration_Import_Export.h rename : externals/ace/Connection_Recycling_Strategy.cpp => dep/acelite/ace/Connection_Recycling_Strategy.cpp rename : externals/ace/Connection_Recycling_Strategy.h => dep/acelite/ace/Connection_Recycling_Strategy.h rename : externals/ace/Connector.cpp => dep/acelite/ace/Connector.cpp rename : externals/ace/Connector.h => dep/acelite/ace/Connector.h rename : externals/ace/Containers.cpp => dep/acelite/ace/Containers.cpp rename : externals/ace/Containers.h => dep/acelite/ace/Containers.h rename : externals/ace/Containers.inl => dep/acelite/ace/Containers.inl rename : externals/ace/Containers_T.cpp => dep/acelite/ace/Containers_T.cpp rename : externals/ace/Containers_T.h => dep/acelite/ace/Containers_T.h rename : externals/ace/Containers_T.inl => dep/acelite/ace/Containers_T.inl rename : externals/ace/Copy_Disabled.cpp => dep/acelite/ace/Copy_Disabled.cpp rename : externals/ace/Copy_Disabled.h => dep/acelite/ace/Copy_Disabled.h rename : externals/ace/Countdown_Time.cpp => dep/acelite/ace/Countdown_Time.cpp rename : externals/ace/Countdown_Time.h => dep/acelite/ace/Countdown_Time.h rename : externals/ace/Countdown_Time.inl => dep/acelite/ace/Countdown_Time.inl rename : externals/ace/DEV.cpp => dep/acelite/ace/DEV.cpp rename : externals/ace/DEV.h => dep/acelite/ace/DEV.h rename : externals/ace/DEV.inl => dep/acelite/ace/DEV.inl rename : externals/ace/DEV_Addr.cpp => dep/acelite/ace/DEV_Addr.cpp rename : externals/ace/DEV_Addr.h => dep/acelite/ace/DEV_Addr.h rename : externals/ace/DEV_Addr.inl => dep/acelite/ace/DEV_Addr.inl rename : externals/ace/DEV_Connector.cpp => dep/acelite/ace/DEV_Connector.cpp rename : externals/ace/DEV_Connector.h => dep/acelite/ace/DEV_Connector.h rename : externals/ace/DEV_Connector.inl => dep/acelite/ace/DEV_Connector.inl rename : externals/ace/DEV_IO.cpp => dep/acelite/ace/DEV_IO.cpp rename : externals/ace/DEV_IO.h => dep/acelite/ace/DEV_IO.h rename : externals/ace/DEV_IO.inl => dep/acelite/ace/DEV_IO.inl rename : externals/ace/DLL.cpp => dep/acelite/ace/DLL.cpp rename : externals/ace/DLL.h => dep/acelite/ace/DLL.h rename : externals/ace/DLL_Manager.cpp => dep/acelite/ace/DLL_Manager.cpp rename : externals/ace/DLL_Manager.h => dep/acelite/ace/DLL_Manager.h rename : externals/ace/Date_Time.cpp => dep/acelite/ace/Date_Time.cpp rename : externals/ace/Date_Time.h => dep/acelite/ace/Date_Time.h rename : externals/ace/Date_Time.inl => dep/acelite/ace/Date_Time.inl rename : externals/ace/Default_Constants.h => dep/acelite/ace/Default_Constants.h rename : externals/ace/Dev_Poll_Reactor.cpp => dep/acelite/ace/Dev_Poll_Reactor.cpp rename : externals/ace/Dev_Poll_Reactor.h => dep/acelite/ace/Dev_Poll_Reactor.h rename : externals/ace/Dev_Poll_Reactor.inl => dep/acelite/ace/Dev_Poll_Reactor.inl rename : externals/ace/Dirent.cpp => dep/acelite/ace/Dirent.cpp rename : externals/ace/Dirent.h => dep/acelite/ace/Dirent.h rename : externals/ace/Dirent.inl => dep/acelite/ace/Dirent.inl rename : externals/ace/Dirent_Selector.cpp => dep/acelite/ace/Dirent_Selector.cpp rename : externals/ace/Dirent_Selector.h => dep/acelite/ace/Dirent_Selector.h rename : externals/ace/Dirent_Selector.inl => dep/acelite/ace/Dirent_Selector.inl rename : externals/ace/Dump.cpp => dep/acelite/ace/Dump.cpp rename : externals/ace/Dump.h => dep/acelite/ace/Dump.h rename : externals/ace/Dump_T.cpp => dep/acelite/ace/Dump_T.cpp rename : externals/ace/Dump_T.h => dep/acelite/ace/Dump_T.h rename : externals/ace/Dynamic.cpp => dep/acelite/ace/Dynamic.cpp rename : externals/ace/Dynamic.h => dep/acelite/ace/Dynamic.h rename : externals/ace/Dynamic.inl => dep/acelite/ace/Dynamic.inl rename : externals/ace/Dynamic_Message_Strategy.cpp => dep/acelite/ace/Dynamic_Message_Strategy.cpp rename : externals/ace/Dynamic_Message_Strategy.h => dep/acelite/ace/Dynamic_Message_Strategy.h rename : externals/ace/Dynamic_Message_Strategy.inl => dep/acelite/ace/Dynamic_Message_Strategy.inl rename : externals/ace/Dynamic_Service.cpp => dep/acelite/ace/Dynamic_Service.cpp rename : externals/ace/Dynamic_Service.h => dep/acelite/ace/Dynamic_Service.h rename : externals/ace/Dynamic_Service.inl => dep/acelite/ace/Dynamic_Service.inl rename : externals/ace/Dynamic_Service_Base.cpp => dep/acelite/ace/Dynamic_Service_Base.cpp rename : externals/ace/Dynamic_Service_Base.h => dep/acelite/ace/Dynamic_Service_Base.h rename : externals/ace/Dynamic_Service_Dependency.cpp => dep/acelite/ace/Dynamic_Service_Dependency.cpp rename : externals/ace/Dynamic_Service_Dependency.h => dep/acelite/ace/Dynamic_Service_Dependency.h rename : externals/ace/Encoding_Converter.cpp => dep/acelite/ace/Encoding_Converter.cpp rename : externals/ace/Encoding_Converter.h => dep/acelite/ace/Encoding_Converter.h rename : externals/ace/Encoding_Converter_Factory.cpp => dep/acelite/ace/Encoding_Converter_Factory.cpp rename : externals/ace/Encoding_Converter_Factory.h => dep/acelite/ace/Encoding_Converter_Factory.h rename : externals/ace/Env_Value_T.cpp => dep/acelite/ace/Env_Value_T.cpp rename : externals/ace/Env_Value_T.h => dep/acelite/ace/Env_Value_T.h rename : externals/ace/Env_Value_T.inl => dep/acelite/ace/Env_Value_T.inl rename : externals/ace/Event.cpp => dep/acelite/ace/Event.cpp rename : externals/ace/Event.h => dep/acelite/ace/Event.h rename : externals/ace/Event.inl => dep/acelite/ace/Event.inl rename : externals/ace/Event_Handler.cpp => dep/acelite/ace/Event_Handler.cpp rename : externals/ace/Event_Handler.h => dep/acelite/ace/Event_Handler.h rename : externals/ace/Event_Handler.inl => dep/acelite/ace/Event_Handler.inl rename : externals/ace/Event_Handler_T.cpp => dep/acelite/ace/Event_Handler_T.cpp rename : externals/ace/Event_Handler_T.h => dep/acelite/ace/Event_Handler_T.h rename : externals/ace/Event_Handler_T.inl => dep/acelite/ace/Event_Handler_T.inl rename : externals/ace/Exception_Macros.h => dep/acelite/ace/Exception_Macros.h rename : externals/ace/FIFO.cpp => dep/acelite/ace/FIFO.cpp rename : externals/ace/FIFO.h => dep/acelite/ace/FIFO.h rename : externals/ace/FIFO.inl => dep/acelite/ace/FIFO.inl rename : externals/ace/FIFO_Recv.cpp => dep/acelite/ace/FIFO_Recv.cpp rename : externals/ace/FIFO_Recv.h => dep/acelite/ace/FIFO_Recv.h rename : externals/ace/FIFO_Recv.inl => dep/acelite/ace/FIFO_Recv.inl rename : externals/ace/FIFO_Recv_Msg.cpp => dep/acelite/ace/FIFO_Recv_Msg.cpp rename : externals/ace/FIFO_Recv_Msg.h => dep/acelite/ace/FIFO_Recv_Msg.h rename : externals/ace/FIFO_Recv_Msg.inl => dep/acelite/ace/FIFO_Recv_Msg.inl rename : externals/ace/FIFO_Send.cpp => dep/acelite/ace/FIFO_Send.cpp rename : externals/ace/FIFO_Send.h => dep/acelite/ace/FIFO_Send.h rename : externals/ace/FIFO_Send.inl => dep/acelite/ace/FIFO_Send.inl rename : externals/ace/FIFO_Send_Msg.cpp => dep/acelite/ace/FIFO_Send_Msg.cpp rename : externals/ace/FIFO_Send_Msg.h => dep/acelite/ace/FIFO_Send_Msg.h rename : externals/ace/FIFO_Send_Msg.inl => dep/acelite/ace/FIFO_Send_Msg.inl rename : externals/ace/FILE.cpp => dep/acelite/ace/FILE.cpp rename : externals/ace/FILE.h => dep/acelite/ace/FILE.h rename : externals/ace/FILE.inl => dep/acelite/ace/FILE.inl rename : externals/ace/FILE_Addr.cpp => dep/acelite/ace/FILE_Addr.cpp rename : externals/ace/FILE_Addr.h => dep/acelite/ace/FILE_Addr.h rename : externals/ace/FILE_Addr.inl => dep/acelite/ace/FILE_Addr.inl rename : externals/ace/FILE_Connector.cpp => dep/acelite/ace/FILE_Connector.cpp rename : externals/ace/FILE_Connector.h => dep/acelite/ace/FILE_Connector.h rename : externals/ace/FILE_Connector.inl => dep/acelite/ace/FILE_Connector.inl rename : externals/ace/FILE_IO.cpp => dep/acelite/ace/FILE_IO.cpp rename : externals/ace/FILE_IO.h => dep/acelite/ace/FILE_IO.h rename : externals/ace/FILE_IO.inl => dep/acelite/ace/FILE_IO.inl rename : externals/ace/File_Lock.cpp => dep/acelite/ace/File_Lock.cpp rename : externals/ace/File_Lock.h => dep/acelite/ace/File_Lock.h rename : externals/ace/File_Lock.inl => dep/acelite/ace/File_Lock.inl rename : externals/ace/Filecache.cpp => dep/acelite/ace/Filecache.cpp rename : externals/ace/Filecache.h => dep/acelite/ace/Filecache.h rename : externals/ace/Flag_Manip.cpp => dep/acelite/ace/Flag_Manip.cpp rename : externals/ace/Flag_Manip.h => dep/acelite/ace/Flag_Manip.h rename : externals/ace/Flag_Manip.inl => dep/acelite/ace/Flag_Manip.inl rename : externals/ace/Framework_Component.cpp => dep/acelite/ace/Framework_Component.cpp rename : externals/ace/Framework_Component.h => dep/acelite/ace/Framework_Component.h rename : externals/ace/Framework_Component.inl => dep/acelite/ace/Framework_Component.inl rename : externals/ace/Framework_Component_T.cpp => dep/acelite/ace/Framework_Component_T.cpp rename : externals/ace/Framework_Component_T.h => dep/acelite/ace/Framework_Component_T.h rename : externals/ace/Free_List.cpp => dep/acelite/ace/Free_List.cpp rename : externals/ace/Free_List.h => dep/acelite/ace/Free_List.h rename : externals/ace/Functor.cpp => dep/acelite/ace/Functor.cpp rename : externals/ace/Functor.h => dep/acelite/ace/Functor.h rename : externals/ace/Functor.inl => dep/acelite/ace/Functor.inl rename : externals/ace/Functor_String.cpp => dep/acelite/ace/Functor_String.cpp rename : externals/ace/Functor_String.h => dep/acelite/ace/Functor_String.h rename : externals/ace/Functor_String.inl => dep/acelite/ace/Functor_String.inl rename : externals/ace/Functor_T.cpp => dep/acelite/ace/Functor_T.cpp rename : externals/ace/Functor_T.h => dep/acelite/ace/Functor_T.h rename : externals/ace/Functor_T.inl => dep/acelite/ace/Functor_T.inl rename : externals/ace/Future.cpp => dep/acelite/ace/Future.cpp rename : externals/ace/Future.h => dep/acelite/ace/Future.h rename : externals/ace/Future_Set.cpp => dep/acelite/ace/Future_Set.cpp rename : externals/ace/Future_Set.h => dep/acelite/ace/Future_Set.h rename : externals/ace/Get_Opt.cpp => dep/acelite/ace/Get_Opt.cpp rename : externals/ace/Get_Opt.h => dep/acelite/ace/Get_Opt.h rename : externals/ace/Get_Opt.inl => dep/acelite/ace/Get_Opt.inl rename : externals/ace/Global_Macros.h => dep/acelite/ace/Global_Macros.h rename : externals/ace/Guard_T.cpp => dep/acelite/ace/Guard_T.cpp rename : externals/ace/Guard_T.h => dep/acelite/ace/Guard_T.h rename : externals/ace/Guard_T.inl => dep/acelite/ace/Guard_T.inl rename : externals/ace/Handle_Gobbler.h => dep/acelite/ace/Handle_Gobbler.h rename : externals/ace/Handle_Gobbler.inl => dep/acelite/ace/Handle_Gobbler.inl rename : externals/ace/Handle_Ops.cpp => dep/acelite/ace/Handle_Ops.cpp rename : externals/ace/Handle_Ops.h => dep/acelite/ace/Handle_Ops.h rename : externals/ace/Handle_Set.cpp => dep/acelite/ace/Handle_Set.cpp rename : externals/ace/Handle_Set.h => dep/acelite/ace/Handle_Set.h rename : externals/ace/Handle_Set.inl => dep/acelite/ace/Handle_Set.inl rename : externals/ace/Hash_Cache_Map_Manager_T.cpp => dep/acelite/ace/Hash_Cache_Map_Manager_T.cpp rename : externals/ace/Hash_Cache_Map_Manager_T.h => dep/acelite/ace/Hash_Cache_Map_Manager_T.h rename : externals/ace/Hash_Cache_Map_Manager_T.inl => dep/acelite/ace/Hash_Cache_Map_Manager_T.inl rename : externals/ace/Hash_Map_Manager.h => dep/acelite/ace/Hash_Map_Manager.h rename : externals/ace/Hash_Map_Manager_T.cpp => dep/acelite/ace/Hash_Map_Manager_T.cpp rename : externals/ace/Hash_Map_Manager_T.h => dep/acelite/ace/Hash_Map_Manager_T.h rename : externals/ace/Hash_Map_Manager_T.inl => dep/acelite/ace/Hash_Map_Manager_T.inl rename : externals/ace/Hash_Map_With_Allocator_T.cpp => dep/acelite/ace/Hash_Map_With_Allocator_T.cpp rename : externals/ace/Hash_Map_With_Allocator_T.h => dep/acelite/ace/Hash_Map_With_Allocator_T.h rename : externals/ace/Hash_Map_With_Allocator_T.inl => dep/acelite/ace/Hash_Map_With_Allocator_T.inl rename : externals/ace/Hash_Multi_Map_Manager_T.cpp => dep/acelite/ace/Hash_Multi_Map_Manager_T.cpp rename : externals/ace/Hash_Multi_Map_Manager_T.h => dep/acelite/ace/Hash_Multi_Map_Manager_T.h rename : externals/ace/Hash_Multi_Map_Manager_T.inl => dep/acelite/ace/Hash_Multi_Map_Manager_T.inl rename : externals/ace/Hashable.cpp => dep/acelite/ace/Hashable.cpp rename : externals/ace/Hashable.h => dep/acelite/ace/Hashable.h rename : externals/ace/Hashable.inl => dep/acelite/ace/Hashable.inl rename : externals/ace/High_Res_Timer.cpp => dep/acelite/ace/High_Res_Timer.cpp rename : externals/ace/High_Res_Timer.h => dep/acelite/ace/High_Res_Timer.h rename : externals/ace/High_Res_Timer.inl => dep/acelite/ace/High_Res_Timer.inl rename : externals/ace/ICMP_Socket.cpp => dep/acelite/ace/ICMP_Socket.cpp rename : externals/ace/ICMP_Socket.h => dep/acelite/ace/ICMP_Socket.h rename : externals/ace/INET_Addr.cpp => dep/acelite/ace/INET_Addr.cpp rename : externals/ace/INET_Addr.h => dep/acelite/ace/INET_Addr.h rename : externals/ace/INET_Addr.inl => dep/acelite/ace/INET_Addr.inl rename : externals/ace/IOStream.cpp => dep/acelite/ace/IOStream.cpp rename : externals/ace/IOStream.h => dep/acelite/ace/IOStream.h rename : externals/ace/IOStream_T.cpp => dep/acelite/ace/IOStream_T.cpp rename : externals/ace/IOStream_T.h => dep/acelite/ace/IOStream_T.h rename : externals/ace/IOStream_T.inl => dep/acelite/ace/IOStream_T.inl rename : externals/ace/IO_Cntl_Msg.cpp => dep/acelite/ace/IO_Cntl_Msg.cpp rename : externals/ace/IO_Cntl_Msg.h => dep/acelite/ace/IO_Cntl_Msg.h rename : externals/ace/IO_Cntl_Msg.inl => dep/acelite/ace/IO_Cntl_Msg.inl rename : externals/ace/IO_SAP.cpp => dep/acelite/ace/IO_SAP.cpp rename : externals/ace/IO_SAP.h => dep/acelite/ace/IO_SAP.h rename : externals/ace/IO_SAP.inl => dep/acelite/ace/IO_SAP.inl rename : externals/ace/IPC_SAP.cpp => dep/acelite/ace/IPC_SAP.cpp rename : externals/ace/IPC_SAP.h => dep/acelite/ace/IPC_SAP.h rename : externals/ace/IPC_SAP.inl => dep/acelite/ace/IPC_SAP.inl rename : externals/ace/If_Then_Else.h => dep/acelite/ace/If_Then_Else.h rename : externals/ace/Init_ACE.cpp => dep/acelite/ace/Init_ACE.cpp rename : externals/ace/Init_ACE.h => dep/acelite/ace/Init_ACE.h rename : externals/ace/Intrusive_Auto_Ptr.cpp => dep/acelite/ace/Intrusive_Auto_Ptr.cpp rename : externals/ace/Intrusive_Auto_Ptr.h => dep/acelite/ace/Intrusive_Auto_Ptr.h rename : externals/ace/Intrusive_Auto_Ptr.inl => dep/acelite/ace/Intrusive_Auto_Ptr.inl rename : externals/ace/Intrusive_List.cpp => dep/acelite/ace/Intrusive_List.cpp rename : externals/ace/Intrusive_List.h => dep/acelite/ace/Intrusive_List.h rename : externals/ace/Intrusive_List.inl => dep/acelite/ace/Intrusive_List.inl rename : externals/ace/Intrusive_List_Node.cpp => dep/acelite/ace/Intrusive_List_Node.cpp rename : externals/ace/Intrusive_List_Node.h => dep/acelite/ace/Intrusive_List_Node.h rename : externals/ace/Intrusive_List_Node.inl => dep/acelite/ace/Intrusive_List_Node.inl rename : externals/ace/LOCK_SOCK_Acceptor.cpp => dep/acelite/ace/LOCK_SOCK_Acceptor.cpp rename : externals/ace/LOCK_SOCK_Acceptor.h => dep/acelite/ace/LOCK_SOCK_Acceptor.h rename : externals/ace/LSOCK.cpp => dep/acelite/ace/LSOCK.cpp rename : externals/ace/LSOCK.h => dep/acelite/ace/LSOCK.h rename : externals/ace/LSOCK.inl => dep/acelite/ace/LSOCK.inl rename : externals/ace/LSOCK_Acceptor.cpp => dep/acelite/ace/LSOCK_Acceptor.cpp rename : externals/ace/LSOCK_Acceptor.h => dep/acelite/ace/LSOCK_Acceptor.h rename : externals/ace/LSOCK_CODgram.cpp => dep/acelite/ace/LSOCK_CODgram.cpp rename : externals/ace/LSOCK_CODgram.h => dep/acelite/ace/LSOCK_CODgram.h rename : externals/ace/LSOCK_CODgram.inl => dep/acelite/ace/LSOCK_CODgram.inl rename : externals/ace/LSOCK_Connector.cpp => dep/acelite/ace/LSOCK_Connector.cpp rename : externals/ace/LSOCK_Connector.h => dep/acelite/ace/LSOCK_Connector.h rename : externals/ace/LSOCK_Connector.inl => dep/acelite/ace/LSOCK_Connector.inl rename : externals/ace/LSOCK_Dgram.cpp => dep/acelite/ace/LSOCK_Dgram.cpp rename : externals/ace/LSOCK_Dgram.h => dep/acelite/ace/LSOCK_Dgram.h rename : externals/ace/LSOCK_Dgram.inl => dep/acelite/ace/LSOCK_Dgram.inl rename : externals/ace/LSOCK_Stream.cpp => dep/acelite/ace/LSOCK_Stream.cpp rename : externals/ace/LSOCK_Stream.h => dep/acelite/ace/LSOCK_Stream.h rename : externals/ace/LSOCK_Stream.inl => dep/acelite/ace/LSOCK_Stream.inl rename : externals/ace/Lib_Find.cpp => dep/acelite/ace/Lib_Find.cpp rename : externals/ace/Lib_Find.h => dep/acelite/ace/Lib_Find.h rename : externals/ace/Local_Memory_Pool.cpp => dep/acelite/ace/Local_Memory_Pool.cpp rename : externals/ace/Local_Memory_Pool.h => dep/acelite/ace/Local_Memory_Pool.h rename : externals/ace/Local_Name_Space.cpp => dep/acelite/ace/Local_Name_Space.cpp rename : externals/ace/Local_Name_Space.h => dep/acelite/ace/Local_Name_Space.h rename : externals/ace/Local_Name_Space_T.cpp => dep/acelite/ace/Local_Name_Space_T.cpp rename : externals/ace/Local_Name_Space_T.h => dep/acelite/ace/Local_Name_Space_T.h rename : externals/ace/Local_Tokens.cpp => dep/acelite/ace/Local_Tokens.cpp rename : externals/ace/Local_Tokens.h => dep/acelite/ace/Local_Tokens.h rename : externals/ace/Local_Tokens.inl => dep/acelite/ace/Local_Tokens.inl rename : externals/ace/Lock.cpp => dep/acelite/ace/Lock.cpp rename : externals/ace/Lock.h => dep/acelite/ace/Lock.h rename : externals/ace/Lock.inl => dep/acelite/ace/Lock.inl rename : externals/ace/Lock_Adapter_T.cpp => dep/acelite/ace/Lock_Adapter_T.cpp rename : externals/ace/Lock_Adapter_T.h => dep/acelite/ace/Lock_Adapter_T.h rename : externals/ace/Lock_Adapter_T.inl => dep/acelite/ace/Lock_Adapter_T.inl rename : externals/ace/Log_Msg.cpp => dep/acelite/ace/Log_Msg.cpp rename : externals/ace/Log_Msg.h => dep/acelite/ace/Log_Msg.h rename : externals/ace/Log_Msg.inl => dep/acelite/ace/Log_Msg.inl rename : externals/ace/Log_Msg_Backend.cpp => dep/acelite/ace/Log_Msg_Backend.cpp rename : externals/ace/Log_Msg_Backend.h => dep/acelite/ace/Log_Msg_Backend.h rename : externals/ace/Log_Msg_Callback.cpp => dep/acelite/ace/Log_Msg_Callback.cpp rename : externals/ace/Log_Msg_Callback.h => dep/acelite/ace/Log_Msg_Callback.h rename : externals/ace/Log_Msg_IPC.cpp => dep/acelite/ace/Log_Msg_IPC.cpp rename : externals/ace/Log_Msg_IPC.h => dep/acelite/ace/Log_Msg_IPC.h rename : externals/ace/Log_Msg_NT_Event_Log.cpp => dep/acelite/ace/Log_Msg_NT_Event_Log.cpp rename : externals/ace/Log_Msg_NT_Event_Log.h => dep/acelite/ace/Log_Msg_NT_Event_Log.h rename : externals/ace/Log_Msg_UNIX_Syslog.cpp => dep/acelite/ace/Log_Msg_UNIX_Syslog.cpp rename : externals/ace/Log_Msg_UNIX_Syslog.h => dep/acelite/ace/Log_Msg_UNIX_Syslog.h rename : externals/ace/Log_Priority.h => dep/acelite/ace/Log_Priority.h rename : externals/ace/Log_Record.cpp => dep/acelite/ace/Log_Record.cpp rename : externals/ace/Log_Record.h => dep/acelite/ace/Log_Record.h rename : externals/ace/Log_Record.inl => dep/acelite/ace/Log_Record.inl rename : externals/ace/Logging_Strategy.cpp => dep/acelite/ace/Logging_Strategy.cpp rename : externals/ace/Logging_Strategy.h => dep/acelite/ace/Logging_Strategy.h rename : externals/ace/MEM_Acceptor.cpp => dep/acelite/ace/MEM_Acceptor.cpp rename : externals/ace/MEM_Acceptor.h => dep/acelite/ace/MEM_Acceptor.h rename : externals/ace/MEM_Acceptor.inl => dep/acelite/ace/MEM_Acceptor.inl rename : externals/ace/MEM_Addr.cpp => dep/acelite/ace/MEM_Addr.cpp rename : externals/ace/MEM_Addr.h => dep/acelite/ace/MEM_Addr.h rename : externals/ace/MEM_Addr.inl => dep/acelite/ace/MEM_Addr.inl rename : externals/ace/MEM_Connector.cpp => dep/acelite/ace/MEM_Connector.cpp rename : externals/ace/MEM_Connector.h => dep/acelite/ace/MEM_Connector.h rename : externals/ace/MEM_Connector.inl => dep/acelite/ace/MEM_Connector.inl rename : externals/ace/MEM_IO.cpp => dep/acelite/ace/MEM_IO.cpp rename : externals/ace/MEM_IO.h => dep/acelite/ace/MEM_IO.h rename : externals/ace/MEM_IO.inl => dep/acelite/ace/MEM_IO.inl rename : externals/ace/MEM_SAP.cpp => dep/acelite/ace/MEM_SAP.cpp rename : externals/ace/MEM_SAP.h => dep/acelite/ace/MEM_SAP.h rename : externals/ace/MEM_SAP.inl => dep/acelite/ace/MEM_SAP.inl rename : externals/ace/MEM_Stream.cpp => dep/acelite/ace/MEM_Stream.cpp rename : externals/ace/MEM_Stream.h => dep/acelite/ace/MEM_Stream.h rename : externals/ace/MEM_Stream.inl => dep/acelite/ace/MEM_Stream.inl rename : externals/ace/MMAP_Memory_Pool.cpp => dep/acelite/ace/MMAP_Memory_Pool.cpp rename : externals/ace/MMAP_Memory_Pool.h => dep/acelite/ace/MMAP_Memory_Pool.h rename : externals/ace/MMAP_Memory_Pool.inl => dep/acelite/ace/MMAP_Memory_Pool.inl rename : externals/ace/Makefile.in => dep/acelite/ace/Makefile.in rename : externals/ace/Malloc.cpp => dep/acelite/ace/Malloc.cpp rename : externals/ace/Malloc.h => dep/acelite/ace/Malloc.h rename : externals/ace/Malloc.inl => dep/acelite/ace/Malloc.inl rename : externals/ace/Malloc_Allocator.cpp => dep/acelite/ace/Malloc_Allocator.cpp rename : externals/ace/Malloc_Allocator.h => dep/acelite/ace/Malloc_Allocator.h rename : externals/ace/Malloc_Allocator.inl => dep/acelite/ace/Malloc_Allocator.inl rename : externals/ace/Malloc_Base.h => dep/acelite/ace/Malloc_Base.h rename : externals/ace/Malloc_T.cpp => dep/acelite/ace/Malloc_T.cpp rename : externals/ace/Malloc_T.h => dep/acelite/ace/Malloc_T.h rename : externals/ace/Malloc_T.inl => dep/acelite/ace/Malloc_T.inl rename : externals/ace/Managed_Object.cpp => dep/acelite/ace/Managed_Object.cpp rename : externals/ace/Managed_Object.h => dep/acelite/ace/Managed_Object.h rename : externals/ace/Managed_Object.inl => dep/acelite/ace/Managed_Object.inl rename : externals/ace/Manual_Event.cpp => dep/acelite/ace/Manual_Event.cpp rename : externals/ace/Manual_Event.h => dep/acelite/ace/Manual_Event.h rename : externals/ace/Manual_Event.inl => dep/acelite/ace/Manual_Event.inl rename : externals/ace/Map.h => dep/acelite/ace/Map.h rename : externals/ace/Map_Manager.cpp => dep/acelite/ace/Map_Manager.cpp rename : externals/ace/Map_Manager.h => dep/acelite/ace/Map_Manager.h rename : externals/ace/Map_Manager.inl => dep/acelite/ace/Map_Manager.inl rename : externals/ace/Map_T.cpp => dep/acelite/ace/Map_T.cpp rename : externals/ace/Map_T.h => dep/acelite/ace/Map_T.h rename : externals/ace/Map_T.inl => dep/acelite/ace/Map_T.inl rename : externals/ace/Mem_Map.cpp => dep/acelite/ace/Mem_Map.cpp rename : externals/ace/Mem_Map.h => dep/acelite/ace/Mem_Map.h rename : externals/ace/Mem_Map.inl => dep/acelite/ace/Mem_Map.inl rename : externals/ace/Memory_Pool.h => dep/acelite/ace/Memory_Pool.h rename : externals/ace/Message_Block.cpp => dep/acelite/ace/Message_Block.cpp rename : externals/ace/Message_Block.h => dep/acelite/ace/Message_Block.h rename : externals/ace/Message_Block.inl => dep/acelite/ace/Message_Block.inl rename : externals/ace/Message_Block_T.cpp => dep/acelite/ace/Message_Block_T.cpp rename : externals/ace/Message_Block_T.h => dep/acelite/ace/Message_Block_T.h rename : externals/ace/Message_Block_T.inl => dep/acelite/ace/Message_Block_T.inl rename : externals/ace/Message_Queue.cpp => dep/acelite/ace/Message_Queue.cpp rename : externals/ace/Message_Queue.h => dep/acelite/ace/Message_Queue.h rename : externals/ace/Message_Queue.inl => dep/acelite/ace/Message_Queue.inl rename : externals/ace/Message_Queue_NT.cpp => dep/acelite/ace/Message_Queue_NT.cpp rename : externals/ace/Message_Queue_NT.h => dep/acelite/ace/Message_Queue_NT.h rename : externals/ace/Message_Queue_NT.inl => dep/acelite/ace/Message_Queue_NT.inl rename : externals/ace/Message_Queue_T.cpp => dep/acelite/ace/Message_Queue_T.cpp rename : externals/ace/Message_Queue_T.h => dep/acelite/ace/Message_Queue_T.h rename : externals/ace/Message_Queue_Vx.cpp => dep/acelite/ace/Message_Queue_Vx.cpp rename : externals/ace/Message_Queue_Vx.h => dep/acelite/ace/Message_Queue_Vx.h rename : externals/ace/Message_Queue_Vx.inl => dep/acelite/ace/Message_Queue_Vx.inl rename : externals/ace/Method_Object.h => dep/acelite/ace/Method_Object.h rename : externals/ace/Method_Request.cpp => dep/acelite/ace/Method_Request.cpp rename : externals/ace/Method_Request.h => dep/acelite/ace/Method_Request.h rename : externals/ace/Metrics_Cache.h => dep/acelite/ace/Metrics_Cache.h rename : externals/ace/Metrics_Cache_T.cpp => dep/acelite/ace/Metrics_Cache_T.cpp rename : externals/ace/Metrics_Cache_T.h => dep/acelite/ace/Metrics_Cache_T.h rename : externals/ace/Metrics_Cache_T.inl => dep/acelite/ace/Metrics_Cache_T.inl rename : externals/ace/Min_Max.h => dep/acelite/ace/Min_Max.h rename : externals/ace/Module.cpp => dep/acelite/ace/Module.cpp rename : externals/ace/Module.h => dep/acelite/ace/Module.h rename : externals/ace/Module.inl => dep/acelite/ace/Module.inl rename : externals/ace/Monitor_Admin.cpp => dep/acelite/ace/Monitor_Admin.cpp rename : externals/ace/Monitor_Admin.h => dep/acelite/ace/Monitor_Admin.h rename : externals/ace/Monitor_Admin_Manager.cpp => dep/acelite/ace/Monitor_Admin_Manager.cpp rename : externals/ace/Monitor_Admin_Manager.h => dep/acelite/ace/Monitor_Admin_Manager.h rename : externals/ace/Monitor_Base.cpp => dep/acelite/ace/Monitor_Base.cpp rename : externals/ace/Monitor_Base.h => dep/acelite/ace/Monitor_Base.h rename : externals/ace/Monitor_Base.inl => dep/acelite/ace/Monitor_Base.inl rename : externals/ace/Monitor_Control_Action.cpp => dep/acelite/ace/Monitor_Control_Action.cpp rename : externals/ace/Monitor_Control_Action.h => dep/acelite/ace/Monitor_Control_Action.h rename : externals/ace/Monitor_Control_Types.cpp => dep/acelite/ace/Monitor_Control_Types.cpp rename : externals/ace/Monitor_Control_Types.h => dep/acelite/ace/Monitor_Control_Types.h rename : externals/ace/Monitor_Point_Registry.cpp => dep/acelite/ace/Monitor_Point_Registry.cpp rename : externals/ace/Monitor_Point_Registry.h => dep/acelite/ace/Monitor_Point_Registry.h rename : externals/ace/Monitor_Size.cpp => dep/acelite/ace/Monitor_Size.cpp rename : externals/ace/Monitor_Size.h => dep/acelite/ace/Monitor_Size.h rename : externals/ace/Msg_WFMO_Reactor.cpp => dep/acelite/ace/Msg_WFMO_Reactor.cpp rename : externals/ace/Msg_WFMO_Reactor.h => dep/acelite/ace/Msg_WFMO_Reactor.h rename : externals/ace/Msg_WFMO_Reactor.inl => dep/acelite/ace/Msg_WFMO_Reactor.inl rename : externals/ace/Multihomed_INET_Addr.cpp => dep/acelite/ace/Multihomed_INET_Addr.cpp rename : externals/ace/Multihomed_INET_Addr.h => dep/acelite/ace/Multihomed_INET_Addr.h rename : externals/ace/Multihomed_INET_Addr.inl => dep/acelite/ace/Multihomed_INET_Addr.inl rename : externals/ace/Mutex.cpp => dep/acelite/ace/Mutex.cpp rename : externals/ace/Mutex.h => dep/acelite/ace/Mutex.h rename : externals/ace/Mutex.inl => dep/acelite/ace/Mutex.inl rename : externals/ace/NT_Service.cpp => dep/acelite/ace/NT_Service.cpp rename : externals/ace/NT_Service.h => dep/acelite/ace/NT_Service.h rename : externals/ace/NT_Service.inl => dep/acelite/ace/NT_Service.inl rename : externals/ace/Name_Proxy.cpp => dep/acelite/ace/Name_Proxy.cpp rename : externals/ace/Name_Proxy.h => dep/acelite/ace/Name_Proxy.h rename : externals/ace/Name_Request_Reply.cpp => dep/acelite/ace/Name_Request_Reply.cpp rename : externals/ace/Name_Request_Reply.h => dep/acelite/ace/Name_Request_Reply.h rename : externals/ace/Name_Space.cpp => dep/acelite/ace/Name_Space.cpp rename : externals/ace/Name_Space.h => dep/acelite/ace/Name_Space.h rename : externals/ace/Naming_Context.cpp => dep/acelite/ace/Naming_Context.cpp rename : externals/ace/Naming_Context.h => dep/acelite/ace/Naming_Context.h rename : externals/ace/Naming_Context.inl => dep/acelite/ace/Naming_Context.inl rename : externals/ace/Netlink_Addr.cpp => dep/acelite/ace/Netlink_Addr.cpp rename : externals/ace/Netlink_Addr.h => dep/acelite/ace/Netlink_Addr.h rename : externals/ace/Netlink_Addr.inl => dep/acelite/ace/Netlink_Addr.inl rename : externals/ace/Node.cpp => dep/acelite/ace/Node.cpp rename : externals/ace/Node.h => dep/acelite/ace/Node.h rename : externals/ace/Notification_Queue.cpp => dep/acelite/ace/Notification_Queue.cpp rename : externals/ace/Notification_Queue.h => dep/acelite/ace/Notification_Queue.h rename : externals/ace/Notification_Queue.inl => dep/acelite/ace/Notification_Queue.inl rename : externals/ace/Notification_Strategy.cpp => dep/acelite/ace/Notification_Strategy.cpp rename : externals/ace/Notification_Strategy.h => dep/acelite/ace/Notification_Strategy.h rename : externals/ace/Notification_Strategy.inl => dep/acelite/ace/Notification_Strategy.inl rename : externals/ace/Null_Barrier.h => dep/acelite/ace/Null_Barrier.h rename : externals/ace/Null_Condition.h => dep/acelite/ace/Null_Condition.h rename : externals/ace/Null_Mutex.h => dep/acelite/ace/Null_Mutex.h rename : externals/ace/Null_Semaphore.h => dep/acelite/ace/Null_Semaphore.h rename : externals/ace/Numeric_Limits.h => dep/acelite/ace/Numeric_Limits.h rename : externals/ace/OS.cpp => dep/acelite/ace/OS.cpp rename : externals/ace/OS.h => dep/acelite/ace/OS.h rename : externals/ace/OS.inl => dep/acelite/ace/OS.inl rename : externals/ace/OS_Dirent.h => dep/acelite/ace/OS_Dirent.h rename : externals/ace/OS_Errno.cpp => dep/acelite/ace/OS_Errno.cpp rename : externals/ace/OS_Errno.h => dep/acelite/ace/OS_Errno.h rename : externals/ace/OS_Errno.inl => dep/acelite/ace/OS_Errno.inl rename : externals/ace/OS_Log_Msg_Attributes.cpp => dep/acelite/ace/OS_Log_Msg_Attributes.cpp rename : externals/ace/OS_Log_Msg_Attributes.h => dep/acelite/ace/OS_Log_Msg_Attributes.h rename : externals/ace/OS_Log_Msg_Attributes.inl => dep/acelite/ace/OS_Log_Msg_Attributes.inl rename : externals/ace/OS_Memory.h => dep/acelite/ace/OS_Memory.h rename : externals/ace/OS_NS_Thread.cpp => dep/acelite/ace/OS_NS_Thread.cpp rename : externals/ace/OS_NS_Thread.h => dep/acelite/ace/OS_NS_Thread.h rename : externals/ace/OS_NS_Thread.inl => dep/acelite/ace/OS_NS_Thread.inl rename : externals/ace/OS_NS_arpa_inet.cpp => dep/acelite/ace/OS_NS_arpa_inet.cpp rename : externals/ace/OS_NS_arpa_inet.h => dep/acelite/ace/OS_NS_arpa_inet.h rename : externals/ace/OS_NS_arpa_inet.inl => dep/acelite/ace/OS_NS_arpa_inet.inl rename : externals/ace/OS_NS_ctype.cpp => dep/acelite/ace/OS_NS_ctype.cpp rename : externals/ace/OS_NS_ctype.h => dep/acelite/ace/OS_NS_ctype.h rename : externals/ace/OS_NS_ctype.inl => dep/acelite/ace/OS_NS_ctype.inl rename : externals/ace/OS_NS_dirent.cpp => dep/acelite/ace/OS_NS_dirent.cpp rename : externals/ace/OS_NS_dirent.h => dep/acelite/ace/OS_NS_dirent.h rename : externals/ace/OS_NS_dirent.inl => dep/acelite/ace/OS_NS_dirent.inl rename : externals/ace/OS_NS_dlfcn.cpp => dep/acelite/ace/OS_NS_dlfcn.cpp rename : externals/ace/OS_NS_dlfcn.h => dep/acelite/ace/OS_NS_dlfcn.h rename : externals/ace/OS_NS_dlfcn.inl => dep/acelite/ace/OS_NS_dlfcn.inl rename : externals/ace/OS_NS_errno.cpp => dep/acelite/ace/OS_NS_errno.cpp rename : externals/ace/OS_NS_errno.h => dep/acelite/ace/OS_NS_errno.h rename : externals/ace/OS_NS_errno.inl => dep/acelite/ace/OS_NS_errno.inl rename : externals/ace/OS_NS_fcntl.cpp => dep/acelite/ace/OS_NS_fcntl.cpp rename : externals/ace/OS_NS_fcntl.h => dep/acelite/ace/OS_NS_fcntl.h rename : externals/ace/OS_NS_fcntl.inl => dep/acelite/ace/OS_NS_fcntl.inl rename : externals/ace/OS_NS_macros.h => dep/acelite/ace/OS_NS_macros.h rename : externals/ace/OS_NS_math.cpp => dep/acelite/ace/OS_NS_math.cpp rename : externals/ace/OS_NS_math.h => dep/acelite/ace/OS_NS_math.h rename : externals/ace/OS_NS_math.inl => dep/acelite/ace/OS_NS_math.inl rename : externals/ace/OS_NS_netdb.cpp => dep/acelite/ace/OS_NS_netdb.cpp rename : externals/ace/OS_NS_netdb.h => dep/acelite/ace/OS_NS_netdb.h rename : externals/ace/OS_NS_netdb.inl => dep/acelite/ace/OS_NS_netdb.inl rename : externals/ace/OS_NS_poll.cpp => dep/acelite/ace/OS_NS_poll.cpp rename : externals/ace/OS_NS_poll.h => dep/acelite/ace/OS_NS_poll.h rename : externals/ace/OS_NS_poll.inl => dep/acelite/ace/OS_NS_poll.inl rename : externals/ace/OS_NS_pwd.cpp => dep/acelite/ace/OS_NS_pwd.cpp rename : externals/ace/OS_NS_pwd.h => dep/acelite/ace/OS_NS_pwd.h rename : externals/ace/OS_NS_pwd.inl => dep/acelite/ace/OS_NS_pwd.inl rename : externals/ace/OS_NS_regex.cpp => dep/acelite/ace/OS_NS_regex.cpp rename : externals/ace/OS_NS_regex.h => dep/acelite/ace/OS_NS_regex.h rename : externals/ace/OS_NS_regex.inl => dep/acelite/ace/OS_NS_regex.inl rename : externals/ace/OS_NS_signal.cpp => dep/acelite/ace/OS_NS_signal.cpp rename : externals/ace/OS_NS_signal.h => dep/acelite/ace/OS_NS_signal.h rename : externals/ace/OS_NS_signal.inl => dep/acelite/ace/OS_NS_signal.inl rename : externals/ace/OS_NS_stdio.cpp => dep/acelite/ace/OS_NS_stdio.cpp rename : externals/ace/OS_NS_stdio.h => dep/acelite/ace/OS_NS_stdio.h rename : externals/ace/OS_NS_stdio.inl => dep/acelite/ace/OS_NS_stdio.inl rename : externals/ace/OS_NS_stdlib.cpp => dep/acelite/ace/OS_NS_stdlib.cpp rename : externals/ace/OS_NS_stdlib.h => dep/acelite/ace/OS_NS_stdlib.h rename : externals/ace/OS_NS_stdlib.inl => dep/acelite/ace/OS_NS_stdlib.inl rename : externals/ace/OS_NS_string.cpp => dep/acelite/ace/OS_NS_string.cpp rename : externals/ace/OS_NS_string.h => dep/acelite/ace/OS_NS_string.h rename : externals/ace/OS_NS_string.inl => dep/acelite/ace/OS_NS_string.inl rename : externals/ace/OS_NS_strings.cpp => dep/acelite/ace/OS_NS_strings.cpp rename : externals/ace/OS_NS_strings.h => dep/acelite/ace/OS_NS_strings.h rename : externals/ace/OS_NS_strings.inl => dep/acelite/ace/OS_NS_strings.inl rename : externals/ace/OS_NS_stropts.cpp => dep/acelite/ace/OS_NS_stropts.cpp rename : externals/ace/OS_NS_stropts.h => dep/acelite/ace/OS_NS_stropts.h rename : externals/ace/OS_NS_stropts.inl => dep/acelite/ace/OS_NS_stropts.inl rename : externals/ace/OS_NS_sys_mman.cpp => dep/acelite/ace/OS_NS_sys_mman.cpp rename : externals/ace/OS_NS_sys_mman.h => dep/acelite/ace/OS_NS_sys_mman.h rename : externals/ace/OS_NS_sys_mman.inl => dep/acelite/ace/OS_NS_sys_mman.inl rename : externals/ace/OS_NS_sys_msg.cpp => dep/acelite/ace/OS_NS_sys_msg.cpp rename : externals/ace/OS_NS_sys_msg.h => dep/acelite/ace/OS_NS_sys_msg.h rename : externals/ace/OS_NS_sys_msg.inl => dep/acelite/ace/OS_NS_sys_msg.inl rename : externals/ace/OS_NS_sys_resource.cpp => dep/acelite/ace/OS_NS_sys_resource.cpp rename : externals/ace/OS_NS_sys_resource.h => dep/acelite/ace/OS_NS_sys_resource.h rename : externals/ace/OS_NS_sys_resource.inl => dep/acelite/ace/OS_NS_sys_resource.inl rename : externals/ace/OS_NS_sys_select.cpp => dep/acelite/ace/OS_NS_sys_select.cpp rename : externals/ace/OS_NS_sys_select.h => dep/acelite/ace/OS_NS_sys_select.h rename : externals/ace/OS_NS_sys_select.inl => dep/acelite/ace/OS_NS_sys_select.inl rename : externals/ace/OS_NS_sys_sendfile.cpp => dep/acelite/ace/OS_NS_sys_sendfile.cpp rename : externals/ace/OS_NS_sys_sendfile.h => dep/acelite/ace/OS_NS_sys_sendfile.h rename : externals/ace/OS_NS_sys_sendfile.inl => dep/acelite/ace/OS_NS_sys_sendfile.inl rename : externals/ace/OS_NS_sys_shm.cpp => dep/acelite/ace/OS_NS_sys_shm.cpp rename : externals/ace/OS_NS_sys_shm.h => dep/acelite/ace/OS_NS_sys_shm.h rename : externals/ace/OS_NS_sys_shm.inl => dep/acelite/ace/OS_NS_sys_shm.inl rename : externals/ace/OS_NS_sys_socket.cpp => dep/acelite/ace/OS_NS_sys_socket.cpp rename : externals/ace/OS_NS_sys_socket.h => dep/acelite/ace/OS_NS_sys_socket.h rename : externals/ace/OS_NS_sys_socket.inl => dep/acelite/ace/OS_NS_sys_socket.inl rename : externals/ace/OS_NS_sys_stat.cpp => dep/acelite/ace/OS_NS_sys_stat.cpp rename : externals/ace/OS_NS_sys_stat.h => dep/acelite/ace/OS_NS_sys_stat.h rename : externals/ace/OS_NS_sys_stat.inl => dep/acelite/ace/OS_NS_sys_stat.inl rename : externals/ace/OS_NS_sys_time.cpp => dep/acelite/ace/OS_NS_sys_time.cpp rename : externals/ace/OS_NS_sys_time.h => dep/acelite/ace/OS_NS_sys_time.h rename : externals/ace/OS_NS_sys_time.inl => dep/acelite/ace/OS_NS_sys_time.inl rename : externals/ace/OS_NS_sys_uio.cpp => dep/acelite/ace/OS_NS_sys_uio.cpp rename : externals/ace/OS_NS_sys_uio.h => dep/acelite/ace/OS_NS_sys_uio.h rename : externals/ace/OS_NS_sys_uio.inl => dep/acelite/ace/OS_NS_sys_uio.inl rename : externals/ace/OS_NS_sys_utsname.cpp => dep/acelite/ace/OS_NS_sys_utsname.cpp rename : externals/ace/OS_NS_sys_utsname.h => dep/acelite/ace/OS_NS_sys_utsname.h rename : externals/ace/OS_NS_sys_wait.cpp => dep/acelite/ace/OS_NS_sys_wait.cpp rename : externals/ace/OS_NS_sys_wait.h => dep/acelite/ace/OS_NS_sys_wait.h rename : externals/ace/OS_NS_sys_wait.inl => dep/acelite/ace/OS_NS_sys_wait.inl rename : externals/ace/OS_NS_time.cpp => dep/acelite/ace/OS_NS_time.cpp rename : externals/ace/OS_NS_time.h => dep/acelite/ace/OS_NS_time.h rename : externals/ace/OS_NS_time.inl => dep/acelite/ace/OS_NS_time.inl rename : externals/ace/OS_NS_unistd.cpp => dep/acelite/ace/OS_NS_unistd.cpp rename : externals/ace/OS_NS_unistd.h => dep/acelite/ace/OS_NS_unistd.h rename : externals/ace/OS_NS_unistd.inl => dep/acelite/ace/OS_NS_unistd.inl rename : externals/ace/OS_NS_wchar.cpp => dep/acelite/ace/OS_NS_wchar.cpp rename : externals/ace/OS_NS_wchar.h => dep/acelite/ace/OS_NS_wchar.h rename : externals/ace/OS_NS_wchar.inl => dep/acelite/ace/OS_NS_wchar.inl rename : externals/ace/OS_NS_wctype.cpp => dep/acelite/ace/OS_NS_wctype.cpp rename : externals/ace/OS_NS_wctype.h => dep/acelite/ace/OS_NS_wctype.h rename : externals/ace/OS_NS_wctype.inl => dep/acelite/ace/OS_NS_wctype.inl rename : externals/ace/OS_QoS.cpp => dep/acelite/ace/OS_QoS.cpp rename : externals/ace/OS_QoS.h => dep/acelite/ace/OS_QoS.h rename : externals/ace/OS_String.h => dep/acelite/ace/OS_String.h rename : externals/ace/OS_TLI.cpp => dep/acelite/ace/OS_TLI.cpp rename : externals/ace/OS_TLI.h => dep/acelite/ace/OS_TLI.h rename : externals/ace/OS_TLI.inl => dep/acelite/ace/OS_TLI.inl rename : externals/ace/OS_Thread_Adapter.cpp => dep/acelite/ace/OS_Thread_Adapter.cpp rename : externals/ace/OS_Thread_Adapter.h => dep/acelite/ace/OS_Thread_Adapter.h rename : externals/ace/OS_main.cpp => dep/acelite/ace/OS_main.cpp rename : externals/ace/OS_main.h => dep/acelite/ace/OS_main.h rename : externals/ace/Obchunk.cpp => dep/acelite/ace/Obchunk.cpp rename : externals/ace/Obchunk.h => dep/acelite/ace/Obchunk.h rename : externals/ace/Obchunk.inl => dep/acelite/ace/Obchunk.inl rename : externals/ace/Object_Manager.cpp => dep/acelite/ace/Object_Manager.cpp rename : externals/ace/Object_Manager.h => dep/acelite/ace/Object_Manager.h rename : externals/ace/Object_Manager.inl => dep/acelite/ace/Object_Manager.inl rename : externals/ace/Object_Manager_Base.cpp => dep/acelite/ace/Object_Manager_Base.cpp rename : externals/ace/Object_Manager_Base.h => dep/acelite/ace/Object_Manager_Base.h rename : externals/ace/Obstack.h => dep/acelite/ace/Obstack.h rename : externals/ace/Obstack_T.cpp => dep/acelite/ace/Obstack_T.cpp rename : externals/ace/Obstack_T.h => dep/acelite/ace/Obstack_T.h rename : externals/ace/Obstack_T.inl => dep/acelite/ace/Obstack_T.inl rename : externals/ace/PI_Malloc.cpp => dep/acelite/ace/PI_Malloc.cpp rename : externals/ace/PI_Malloc.h => dep/acelite/ace/PI_Malloc.h rename : externals/ace/PI_Malloc.inl => dep/acelite/ace/PI_Malloc.inl rename : externals/ace/POSIX_Asynch_IO.cpp => dep/acelite/ace/POSIX_Asynch_IO.cpp rename : externals/ace/POSIX_Asynch_IO.h => dep/acelite/ace/POSIX_Asynch_IO.h rename : externals/ace/POSIX_CB_Proactor.cpp => dep/acelite/ace/POSIX_CB_Proactor.cpp rename : externals/ace/POSIX_CB_Proactor.h => dep/acelite/ace/POSIX_CB_Proactor.h rename : externals/ace/POSIX_Proactor.cpp => dep/acelite/ace/POSIX_Proactor.cpp rename : externals/ace/POSIX_Proactor.h => dep/acelite/ace/POSIX_Proactor.h rename : externals/ace/POSIX_Proactor.inl => dep/acelite/ace/POSIX_Proactor.inl rename : externals/ace/Pagefile_Memory_Pool.cpp => dep/acelite/ace/Pagefile_Memory_Pool.cpp rename : externals/ace/Pagefile_Memory_Pool.h => dep/acelite/ace/Pagefile_Memory_Pool.h rename : externals/ace/Pagefile_Memory_Pool.inl => dep/acelite/ace/Pagefile_Memory_Pool.inl rename : externals/ace/Pair.h => dep/acelite/ace/Pair.h rename : externals/ace/Pair_T.cpp => dep/acelite/ace/Pair_T.cpp rename : externals/ace/Pair_T.h => dep/acelite/ace/Pair_T.h rename : externals/ace/Pair_T.inl => dep/acelite/ace/Pair_T.inl rename : externals/ace/Parse_Node.cpp => dep/acelite/ace/Parse_Node.cpp rename : externals/ace/Parse_Node.h => dep/acelite/ace/Parse_Node.h rename : externals/ace/Ping_Socket.cpp => dep/acelite/ace/Ping_Socket.cpp rename : externals/ace/Ping_Socket.h => dep/acelite/ace/Ping_Socket.h rename : externals/ace/Ping_Socket.inl => dep/acelite/ace/Ping_Socket.inl rename : externals/ace/Pipe.cpp => dep/acelite/ace/Pipe.cpp rename : externals/ace/Pipe.h => dep/acelite/ace/Pipe.h rename : externals/ace/Pipe.inl => dep/acelite/ace/Pipe.inl rename : externals/ace/PrecompiledHeaders/WinAcePCH.cpp => dep/acelite/ace/PrecompiledHeaders/WinAcePCH.cpp rename : externals/ace/PrecompiledHeaders/WinAcePCH.h => dep/acelite/ace/PrecompiledHeaders/WinAcePCH.h rename : externals/ace/Priority_Reactor.cpp => dep/acelite/ace/Priority_Reactor.cpp rename : externals/ace/Priority_Reactor.h => dep/acelite/ace/Priority_Reactor.h rename : externals/ace/Proactor.cpp => dep/acelite/ace/Proactor.cpp rename : externals/ace/Proactor.h => dep/acelite/ace/Proactor.h rename : externals/ace/Proactor.inl => dep/acelite/ace/Proactor.inl rename : externals/ace/Proactor_Impl.cpp => dep/acelite/ace/Proactor_Impl.cpp rename : externals/ace/Proactor_Impl.h => dep/acelite/ace/Proactor_Impl.h rename : externals/ace/Process.cpp => dep/acelite/ace/Process.cpp rename : externals/ace/Process.h => dep/acelite/ace/Process.h rename : externals/ace/Process.inl => dep/acelite/ace/Process.inl rename : externals/ace/Process_Manager.cpp => dep/acelite/ace/Process_Manager.cpp rename : externals/ace/Process_Manager.h => dep/acelite/ace/Process_Manager.h rename : externals/ace/Process_Manager.inl => dep/acelite/ace/Process_Manager.inl rename : externals/ace/Process_Mutex.cpp => dep/acelite/ace/Process_Mutex.cpp rename : externals/ace/Process_Mutex.h => dep/acelite/ace/Process_Mutex.h rename : externals/ace/Process_Mutex.inl => dep/acelite/ace/Process_Mutex.inl rename : externals/ace/Process_Semaphore.cpp => dep/acelite/ace/Process_Semaphore.cpp rename : externals/ace/Process_Semaphore.h => dep/acelite/ace/Process_Semaphore.h rename : externals/ace/Process_Semaphore.inl => dep/acelite/ace/Process_Semaphore.inl rename : externals/ace/Profile_Timer.cpp => dep/acelite/ace/Profile_Timer.cpp rename : externals/ace/Profile_Timer.h => dep/acelite/ace/Profile_Timer.h rename : externals/ace/Profile_Timer.inl => dep/acelite/ace/Profile_Timer.inl rename : externals/ace/QoS/ACE_QoS_Export.h => dep/acelite/ace/QoS/ACE_QoS_Export.h rename : externals/ace/QoS/QoS_Decorator.cpp => dep/acelite/ace/QoS/QoS_Decorator.cpp rename : externals/ace/QoS/QoS_Decorator.h => dep/acelite/ace/QoS/QoS_Decorator.h rename : externals/ace/QoS/QoS_Manager.cpp => dep/acelite/ace/QoS/QoS_Manager.cpp rename : externals/ace/QoS/QoS_Manager.h => dep/acelite/ace/QoS/QoS_Manager.h rename : externals/ace/QoS/QoS_Session.h => dep/acelite/ace/QoS/QoS_Session.h rename : externals/ace/QoS/QoS_Session_Factory.cpp => dep/acelite/ace/QoS/QoS_Session_Factory.cpp rename : externals/ace/QoS/QoS_Session_Factory.h => dep/acelite/ace/QoS/QoS_Session_Factory.h rename : externals/ace/QoS/QoS_Session_Impl.cpp => dep/acelite/ace/QoS/QoS_Session_Impl.cpp rename : externals/ace/QoS/QoS_Session_Impl.h => dep/acelite/ace/QoS/QoS_Session_Impl.h rename : externals/ace/QoS/QoS_Session_Impl.inl => dep/acelite/ace/QoS/QoS_Session_Impl.inl rename : externals/ace/QoS/README => dep/acelite/ace/QoS/README rename : externals/ace/QoS/SOCK_Dgram_Mcast_QoS.cpp => dep/acelite/ace/QoS/SOCK_Dgram_Mcast_QoS.cpp rename : externals/ace/QoS/SOCK_Dgram_Mcast_QoS.h => dep/acelite/ace/QoS/SOCK_Dgram_Mcast_QoS.h rename : externals/ace/QoS/SOCK_Dgram_Mcast_QoS.inl => dep/acelite/ace/QoS/SOCK_Dgram_Mcast_QoS.inl rename : externals/ace/RB_Tree.cpp => dep/acelite/ace/RB_Tree.cpp rename : externals/ace/RB_Tree.h => dep/acelite/ace/RB_Tree.h rename : externals/ace/RB_Tree.inl => dep/acelite/ace/RB_Tree.inl rename : externals/ace/README => dep/acelite/ace/README rename : externals/ace/RW_Mutex.cpp => dep/acelite/ace/RW_Mutex.cpp rename : externals/ace/RW_Mutex.h => dep/acelite/ace/RW_Mutex.h rename : externals/ace/RW_Mutex.inl => dep/acelite/ace/RW_Mutex.inl rename : externals/ace/RW_Process_Mutex.cpp => dep/acelite/ace/RW_Process_Mutex.cpp rename : externals/ace/RW_Process_Mutex.h => dep/acelite/ace/RW_Process_Mutex.h rename : externals/ace/RW_Process_Mutex.inl => dep/acelite/ace/RW_Process_Mutex.inl rename : externals/ace/RW_Thread_Mutex.cpp => dep/acelite/ace/RW_Thread_Mutex.cpp rename : externals/ace/RW_Thread_Mutex.h => dep/acelite/ace/RW_Thread_Mutex.h rename : externals/ace/RW_Thread_Mutex.inl => dep/acelite/ace/RW_Thread_Mutex.inl rename : externals/ace/Reactor.cpp => dep/acelite/ace/Reactor.cpp rename : externals/ace/Reactor.h => dep/acelite/ace/Reactor.h rename : externals/ace/Reactor.inl => dep/acelite/ace/Reactor.inl rename : externals/ace/Reactor_Impl.cpp => dep/acelite/ace/Reactor_Impl.cpp rename : externals/ace/Reactor_Impl.h => dep/acelite/ace/Reactor_Impl.h rename : externals/ace/Reactor_Notification_Strategy.cpp => dep/acelite/ace/Reactor_Notification_Strategy.cpp rename : externals/ace/Reactor_Notification_Strategy.h => dep/acelite/ace/Reactor_Notification_Strategy.h rename : externals/ace/Reactor_Notification_Strategy.inl => dep/acelite/ace/Reactor_Notification_Strategy.inl rename : externals/ace/Reactor_Timer_Interface.cpp => dep/acelite/ace/Reactor_Timer_Interface.cpp rename : externals/ace/Reactor_Timer_Interface.h => dep/acelite/ace/Reactor_Timer_Interface.h rename : externals/ace/Reactor_Token_T.cpp => dep/acelite/ace/Reactor_Token_T.cpp rename : externals/ace/Reactor_Token_T.h => dep/acelite/ace/Reactor_Token_T.h rename : externals/ace/Read_Buffer.cpp => dep/acelite/ace/Read_Buffer.cpp rename : externals/ace/Read_Buffer.h => dep/acelite/ace/Read_Buffer.h rename : externals/ace/Read_Buffer.inl => dep/acelite/ace/Read_Buffer.inl rename : externals/ace/Recursive_Thread_Mutex.cpp => dep/acelite/ace/Recursive_Thread_Mutex.cpp rename : externals/ace/Recursive_Thread_Mutex.h => dep/acelite/ace/Recursive_Thread_Mutex.h rename : externals/ace/Recursive_Thread_Mutex.inl => dep/acelite/ace/Recursive_Thread_Mutex.inl rename : externals/ace/Recyclable.cpp => dep/acelite/ace/Recyclable.cpp rename : externals/ace/Recyclable.h => dep/acelite/ace/Recyclable.h rename : externals/ace/Recyclable.inl => dep/acelite/ace/Recyclable.inl rename : externals/ace/Refcountable.h => dep/acelite/ace/Refcountable.h rename : externals/ace/Refcountable_T.cpp => dep/acelite/ace/Refcountable_T.cpp rename : externals/ace/Refcountable_T.h => dep/acelite/ace/Refcountable_T.h rename : externals/ace/Refcountable_T.inl => dep/acelite/ace/Refcountable_T.inl rename : externals/ace/Refcounted_Auto_Ptr.cpp => dep/acelite/ace/Refcounted_Auto_Ptr.cpp rename : externals/ace/Refcounted_Auto_Ptr.h => dep/acelite/ace/Refcounted_Auto_Ptr.h rename : externals/ace/Refcounted_Auto_Ptr.inl => dep/acelite/ace/Refcounted_Auto_Ptr.inl rename : externals/ace/Registry.cpp => dep/acelite/ace/Registry.cpp rename : externals/ace/Registry.h => dep/acelite/ace/Registry.h rename : externals/ace/Registry_Name_Space.cpp => dep/acelite/ace/Registry_Name_Space.cpp rename : externals/ace/Registry_Name_Space.h => dep/acelite/ace/Registry_Name_Space.h rename : externals/ace/Remote_Name_Space.cpp => dep/acelite/ace/Remote_Name_Space.cpp rename : externals/ace/Remote_Name_Space.h => dep/acelite/ace/Remote_Name_Space.h rename : externals/ace/Remote_Tokens.cpp => dep/acelite/ace/Remote_Tokens.cpp rename : externals/ace/Remote_Tokens.h => dep/acelite/ace/Remote_Tokens.h rename : externals/ace/Remote_Tokens.inl => dep/acelite/ace/Remote_Tokens.inl rename : externals/ace/Reverse_Lock_T.cpp => dep/acelite/ace/Reverse_Lock_T.cpp rename : externals/ace/Reverse_Lock_T.h => dep/acelite/ace/Reverse_Lock_T.h rename : externals/ace/Reverse_Lock_T.inl => dep/acelite/ace/Reverse_Lock_T.inl rename : externals/ace/Rtems_init.c => dep/acelite/ace/Rtems_init.c rename : externals/ace/SOCK.cpp => dep/acelite/ace/SOCK.cpp rename : externals/ace/SOCK.h => dep/acelite/ace/SOCK.h rename : externals/ace/SOCK.inl => dep/acelite/ace/SOCK.inl rename : externals/ace/SOCK_Acceptor.cpp => dep/acelite/ace/SOCK_Acceptor.cpp rename : externals/ace/SOCK_Acceptor.h => dep/acelite/ace/SOCK_Acceptor.h rename : externals/ace/SOCK_Acceptor.inl => dep/acelite/ace/SOCK_Acceptor.inl rename : externals/ace/SOCK_CODgram.cpp => dep/acelite/ace/SOCK_CODgram.cpp rename : externals/ace/SOCK_CODgram.h => dep/acelite/ace/SOCK_CODgram.h rename : externals/ace/SOCK_CODgram.inl => dep/acelite/ace/SOCK_CODgram.inl rename : externals/ace/SOCK_Connector.cpp => dep/acelite/ace/SOCK_Connector.cpp rename : externals/ace/SOCK_Connector.h => dep/acelite/ace/SOCK_Connector.h rename : externals/ace/SOCK_Connector.inl => dep/acelite/ace/SOCK_Connector.inl rename : externals/ace/SOCK_Dgram.cpp => dep/acelite/ace/SOCK_Dgram.cpp rename : externals/ace/SOCK_Dgram.h => dep/acelite/ace/SOCK_Dgram.h rename : externals/ace/SOCK_Dgram.inl => dep/acelite/ace/SOCK_Dgram.inl rename : externals/ace/SOCK_Dgram_Bcast.cpp => dep/acelite/ace/SOCK_Dgram_Bcast.cpp rename : externals/ace/SOCK_Dgram_Bcast.h => dep/acelite/ace/SOCK_Dgram_Bcast.h rename : externals/ace/SOCK_Dgram_Bcast.inl => dep/acelite/ace/SOCK_Dgram_Bcast.inl rename : externals/ace/SOCK_Dgram_Mcast.cpp => dep/acelite/ace/SOCK_Dgram_Mcast.cpp rename : externals/ace/SOCK_Dgram_Mcast.h => dep/acelite/ace/SOCK_Dgram_Mcast.h rename : externals/ace/SOCK_Dgram_Mcast.inl => dep/acelite/ace/SOCK_Dgram_Mcast.inl rename : externals/ace/SOCK_IO.cpp => dep/acelite/ace/SOCK_IO.cpp rename : externals/ace/SOCK_IO.h => dep/acelite/ace/SOCK_IO.h rename : externals/ace/SOCK_IO.inl => dep/acelite/ace/SOCK_IO.inl rename : externals/ace/SOCK_Netlink.cpp => dep/acelite/ace/SOCK_Netlink.cpp rename : externals/ace/SOCK_Netlink.h => dep/acelite/ace/SOCK_Netlink.h rename : externals/ace/SOCK_Netlink.inl => dep/acelite/ace/SOCK_Netlink.inl rename : externals/ace/SOCK_SEQPACK_Acceptor.cpp => dep/acelite/ace/SOCK_SEQPACK_Acceptor.cpp rename : externals/ace/SOCK_SEQPACK_Acceptor.h => dep/acelite/ace/SOCK_SEQPACK_Acceptor.h rename : externals/ace/SOCK_SEQPACK_Acceptor.inl => dep/acelite/ace/SOCK_SEQPACK_Acceptor.inl rename : externals/ace/SOCK_SEQPACK_Association.cpp => dep/acelite/ace/SOCK_SEQPACK_Association.cpp rename : externals/ace/SOCK_SEQPACK_Association.h => dep/acelite/ace/SOCK_SEQPACK_Association.h rename : externals/ace/SOCK_SEQPACK_Association.inl => dep/acelite/ace/SOCK_SEQPACK_Association.inl rename : externals/ace/SOCK_SEQPACK_Connector.cpp => dep/acelite/ace/SOCK_SEQPACK_Connector.cpp rename : externals/ace/SOCK_SEQPACK_Connector.h => dep/acelite/ace/SOCK_SEQPACK_Connector.h rename : externals/ace/SOCK_SEQPACK_Connector.inl => dep/acelite/ace/SOCK_SEQPACK_Connector.inl rename : externals/ace/SOCK_Stream.cpp => dep/acelite/ace/SOCK_Stream.cpp rename : externals/ace/SOCK_Stream.h => dep/acelite/ace/SOCK_Stream.h rename : externals/ace/SOCK_Stream.inl => dep/acelite/ace/SOCK_Stream.inl rename : externals/ace/SPIPE.cpp => dep/acelite/ace/SPIPE.cpp rename : externals/ace/SPIPE.h => dep/acelite/ace/SPIPE.h rename : externals/ace/SPIPE.inl => dep/acelite/ace/SPIPE.inl rename : externals/ace/SPIPE_Acceptor.cpp => dep/acelite/ace/SPIPE_Acceptor.cpp rename : externals/ace/SPIPE_Acceptor.h => dep/acelite/ace/SPIPE_Acceptor.h rename : externals/ace/SPIPE_Addr.cpp => dep/acelite/ace/SPIPE_Addr.cpp rename : externals/ace/SPIPE_Addr.h => dep/acelite/ace/SPIPE_Addr.h rename : externals/ace/SPIPE_Addr.inl => dep/acelite/ace/SPIPE_Addr.inl rename : externals/ace/SPIPE_Connector.cpp => dep/acelite/ace/SPIPE_Connector.cpp rename : externals/ace/SPIPE_Connector.h => dep/acelite/ace/SPIPE_Connector.h rename : externals/ace/SPIPE_Connector.inl => dep/acelite/ace/SPIPE_Connector.inl rename : externals/ace/SPIPE_Stream.cpp => dep/acelite/ace/SPIPE_Stream.cpp rename : externals/ace/SPIPE_Stream.h => dep/acelite/ace/SPIPE_Stream.h rename : externals/ace/SPIPE_Stream.inl => dep/acelite/ace/SPIPE_Stream.inl rename : externals/ace/SSL/SSL_Asynch_BIO.cpp => dep/acelite/ace/SSL/SSL_Asynch_BIO.cpp rename : externals/ace/SSL/SSL_Asynch_BIO.h => dep/acelite/ace/SSL/SSL_Asynch_BIO.h rename : externals/ace/SSL/SSL_Asynch_Stream.cpp => dep/acelite/ace/SSL/SSL_Asynch_Stream.cpp rename : externals/ace/SSL/SSL_Asynch_Stream.h => dep/acelite/ace/SSL/SSL_Asynch_Stream.h rename : externals/ace/SSL/SSL_Asynch_Stream.inl => dep/acelite/ace/SSL/SSL_Asynch_Stream.inl rename : externals/ace/SSL/SSL_Context.cpp => dep/acelite/ace/SSL/SSL_Context.cpp rename : externals/ace/SSL/SSL_Context.h => dep/acelite/ace/SSL/SSL_Context.h rename : externals/ace/SSL/SSL_Context.inl => dep/acelite/ace/SSL/SSL_Context.inl rename : externals/ace/SSL/SSL_Export.h => dep/acelite/ace/SSL/SSL_Export.h rename : externals/ace/SSL/SSL_SOCK.cpp => dep/acelite/ace/SSL/SSL_SOCK.cpp rename : externals/ace/SSL/SSL_SOCK.h => dep/acelite/ace/SSL/SSL_SOCK.h rename : externals/ace/SSL/SSL_SOCK.inl => dep/acelite/ace/SSL/SSL_SOCK.inl rename : externals/ace/SSL/SSL_SOCK_Acceptor.cpp => dep/acelite/ace/SSL/SSL_SOCK_Acceptor.cpp rename : externals/ace/SSL/SSL_SOCK_Acceptor.h => dep/acelite/ace/SSL/SSL_SOCK_Acceptor.h rename : externals/ace/SSL/SSL_SOCK_Acceptor.inl => dep/acelite/ace/SSL/SSL_SOCK_Acceptor.inl rename : externals/ace/SSL/SSL_SOCK_Connector.cpp => dep/acelite/ace/SSL/SSL_SOCK_Connector.cpp rename : externals/ace/SSL/SSL_SOCK_Connector.h => dep/acelite/ace/SSL/SSL_SOCK_Connector.h rename : externals/ace/SSL/SSL_SOCK_Connector.inl => dep/acelite/ace/SSL/SSL_SOCK_Connector.inl rename : externals/ace/SSL/SSL_SOCK_Stream.cpp => dep/acelite/ace/SSL/SSL_SOCK_Stream.cpp rename : externals/ace/SSL/SSL_SOCK_Stream.h => dep/acelite/ace/SSL/SSL_SOCK_Stream.h rename : externals/ace/SSL/SSL_SOCK_Stream.inl => dep/acelite/ace/SSL/SSL_SOCK_Stream.inl rename : externals/ace/SSL/sslconf.h => dep/acelite/ace/SSL/sslconf.h rename : externals/ace/SString.cpp => dep/acelite/ace/SString.cpp rename : externals/ace/SString.h => dep/acelite/ace/SString.h rename : externals/ace/SString.inl => dep/acelite/ace/SString.inl rename : externals/ace/SStringfwd.h => dep/acelite/ace/SStringfwd.h rename : externals/ace/SUN_Proactor.cpp => dep/acelite/ace/SUN_Proactor.cpp rename : externals/ace/SUN_Proactor.h => dep/acelite/ace/SUN_Proactor.h rename : externals/ace/SV_Message.cpp => dep/acelite/ace/SV_Message.cpp rename : externals/ace/SV_Message.h => dep/acelite/ace/SV_Message.h rename : externals/ace/SV_Message.inl => dep/acelite/ace/SV_Message.inl rename : externals/ace/SV_Message_Queue.cpp => dep/acelite/ace/SV_Message_Queue.cpp rename : externals/ace/SV_Message_Queue.h => dep/acelite/ace/SV_Message_Queue.h rename : externals/ace/SV_Message_Queue.inl => dep/acelite/ace/SV_Message_Queue.inl rename : externals/ace/SV_Semaphore_Complex.cpp => dep/acelite/ace/SV_Semaphore_Complex.cpp rename : externals/ace/SV_Semaphore_Complex.h => dep/acelite/ace/SV_Semaphore_Complex.h rename : externals/ace/SV_Semaphore_Complex.inl => dep/acelite/ace/SV_Semaphore_Complex.inl rename : externals/ace/SV_Semaphore_Simple.cpp => dep/acelite/ace/SV_Semaphore_Simple.cpp rename : externals/ace/SV_Semaphore_Simple.h => dep/acelite/ace/SV_Semaphore_Simple.h rename : externals/ace/SV_Semaphore_Simple.inl => dep/acelite/ace/SV_Semaphore_Simple.inl rename : externals/ace/SV_Shared_Memory.cpp => dep/acelite/ace/SV_Shared_Memory.cpp rename : externals/ace/SV_Shared_Memory.h => dep/acelite/ace/SV_Shared_Memory.h rename : externals/ace/SV_Shared_Memory.inl => dep/acelite/ace/SV_Shared_Memory.inl rename : externals/ace/Sample_History.cpp => dep/acelite/ace/Sample_History.cpp rename : externals/ace/Sample_History.h => dep/acelite/ace/Sample_History.h rename : externals/ace/Sample_History.inl => dep/acelite/ace/Sample_History.inl rename : externals/ace/Sbrk_Memory_Pool.cpp => dep/acelite/ace/Sbrk_Memory_Pool.cpp rename : externals/ace/Sbrk_Memory_Pool.h => dep/acelite/ace/Sbrk_Memory_Pool.h rename : externals/ace/Sched_Params.cpp => dep/acelite/ace/Sched_Params.cpp rename : externals/ace/Sched_Params.h => dep/acelite/ace/Sched_Params.h rename : externals/ace/Sched_Params.inl => dep/acelite/ace/Sched_Params.inl rename : externals/ace/Select_Reactor.h => dep/acelite/ace/Select_Reactor.h rename : externals/ace/Select_Reactor_Base.cpp => dep/acelite/ace/Select_Reactor_Base.cpp rename : externals/ace/Select_Reactor_Base.h => dep/acelite/ace/Select_Reactor_Base.h rename : externals/ace/Select_Reactor_Base.inl => dep/acelite/ace/Select_Reactor_Base.inl rename : externals/ace/Select_Reactor_T.cpp => dep/acelite/ace/Select_Reactor_T.cpp rename : externals/ace/Select_Reactor_T.h => dep/acelite/ace/Select_Reactor_T.h rename : externals/ace/Select_Reactor_T.inl => dep/acelite/ace/Select_Reactor_T.inl rename : externals/ace/Semaphore.cpp => dep/acelite/ace/Semaphore.cpp rename : externals/ace/Semaphore.h => dep/acelite/ace/Semaphore.h rename : externals/ace/Semaphore.inl => dep/acelite/ace/Semaphore.inl rename : externals/ace/Service_Config.cpp => dep/acelite/ace/Service_Config.cpp rename : externals/ace/Service_Config.h => dep/acelite/ace/Service_Config.h rename : externals/ace/Service_Config.inl => dep/acelite/ace/Service_Config.inl rename : externals/ace/Service_Gestalt.cpp => dep/acelite/ace/Service_Gestalt.cpp rename : externals/ace/Service_Gestalt.h => dep/acelite/ace/Service_Gestalt.h rename : externals/ace/Service_Gestalt.inl => dep/acelite/ace/Service_Gestalt.inl rename : externals/ace/Service_Manager.cpp => dep/acelite/ace/Service_Manager.cpp rename : externals/ace/Service_Manager.h => dep/acelite/ace/Service_Manager.h rename : externals/ace/Service_Object.cpp => dep/acelite/ace/Service_Object.cpp rename : externals/ace/Service_Object.h => dep/acelite/ace/Service_Object.h rename : externals/ace/Service_Object.inl => dep/acelite/ace/Service_Object.inl rename : externals/ace/Service_Repository.cpp => dep/acelite/ace/Service_Repository.cpp rename : externals/ace/Service_Repository.h => dep/acelite/ace/Service_Repository.h rename : externals/ace/Service_Repository.inl => dep/acelite/ace/Service_Repository.inl rename : externals/ace/Service_Templates.h => dep/acelite/ace/Service_Templates.h rename : externals/ace/Service_Types.cpp => dep/acelite/ace/Service_Types.cpp rename : externals/ace/Service_Types.h => dep/acelite/ace/Service_Types.h rename : externals/ace/Service_Types.inl => dep/acelite/ace/Service_Types.inl rename : externals/ace/Shared_Memory.cpp => dep/acelite/ace/Shared_Memory.cpp rename : externals/ace/Shared_Memory.h => dep/acelite/ace/Shared_Memory.h rename : externals/ace/Shared_Memory_MM.cpp => dep/acelite/ace/Shared_Memory_MM.cpp rename : externals/ace/Shared_Memory_MM.h => dep/acelite/ace/Shared_Memory_MM.h rename : externals/ace/Shared_Memory_MM.inl => dep/acelite/ace/Shared_Memory_MM.inl rename : externals/ace/Shared_Memory_Pool.cpp => dep/acelite/ace/Shared_Memory_Pool.cpp rename : externals/ace/Shared_Memory_Pool.h => dep/acelite/ace/Shared_Memory_Pool.h rename : externals/ace/Shared_Memory_SV.cpp => dep/acelite/ace/Shared_Memory_SV.cpp rename : externals/ace/Shared_Memory_SV.h => dep/acelite/ace/Shared_Memory_SV.h rename : externals/ace/Shared_Memory_SV.inl => dep/acelite/ace/Shared_Memory_SV.inl rename : externals/ace/Shared_Object.cpp => dep/acelite/ace/Shared_Object.cpp rename : externals/ace/Shared_Object.h => dep/acelite/ace/Shared_Object.h rename : externals/ace/Shared_Object.inl => dep/acelite/ace/Shared_Object.inl rename : externals/ace/Sig_Adapter.cpp => dep/acelite/ace/Sig_Adapter.cpp rename : externals/ace/Sig_Adapter.h => dep/acelite/ace/Sig_Adapter.h rename : externals/ace/Sig_Handler.cpp => dep/acelite/ace/Sig_Handler.cpp rename : externals/ace/Sig_Handler.h => dep/acelite/ace/Sig_Handler.h rename : externals/ace/Sig_Handler.inl => dep/acelite/ace/Sig_Handler.inl rename : externals/ace/Signal.cpp => dep/acelite/ace/Signal.cpp rename : externals/ace/Signal.h => dep/acelite/ace/Signal.h rename : externals/ace/Signal.inl => dep/acelite/ace/Signal.inl rename : externals/ace/Singleton.cpp => dep/acelite/ace/Singleton.cpp rename : externals/ace/Singleton.h => dep/acelite/ace/Singleton.h rename : externals/ace/Singleton.inl => dep/acelite/ace/Singleton.inl rename : externals/ace/Sock_Connect.cpp => dep/acelite/ace/Sock_Connect.cpp rename : externals/ace/Sock_Connect.h => dep/acelite/ace/Sock_Connect.h rename : externals/ace/Stack_Trace.cpp => dep/acelite/ace/Stack_Trace.cpp rename : externals/ace/Stack_Trace.h => dep/acelite/ace/Stack_Trace.h rename : externals/ace/Static_Object_Lock.h => dep/acelite/ace/Static_Object_Lock.h rename : externals/ace/Stats.cpp => dep/acelite/ace/Stats.cpp rename : externals/ace/Stats.h => dep/acelite/ace/Stats.h rename : externals/ace/Stats.inl => dep/acelite/ace/Stats.inl rename : externals/ace/Strategies.h => dep/acelite/ace/Strategies.h rename : externals/ace/Strategies_T.cpp => dep/acelite/ace/Strategies_T.cpp rename : externals/ace/Strategies_T.h => dep/acelite/ace/Strategies_T.h rename : externals/ace/Strategies_T.inl => dep/acelite/ace/Strategies_T.inl rename : externals/ace/Stream.cpp => dep/acelite/ace/Stream.cpp rename : externals/ace/Stream.h => dep/acelite/ace/Stream.h rename : externals/ace/Stream.inl => dep/acelite/ace/Stream.inl rename : externals/ace/Stream_Modules.cpp => dep/acelite/ace/Stream_Modules.cpp rename : externals/ace/Stream_Modules.h => dep/acelite/ace/Stream_Modules.h rename : externals/ace/String_Base.cpp => dep/acelite/ace/String_Base.cpp rename : externals/ace/String_Base.h => dep/acelite/ace/String_Base.h rename : externals/ace/String_Base.inl => dep/acelite/ace/String_Base.inl rename : externals/ace/String_Base_Const.cpp => dep/acelite/ace/String_Base_Const.cpp rename : externals/ace/String_Base_Const.h => dep/acelite/ace/String_Base_Const.h rename : externals/ace/Svc_Conf.h => dep/acelite/ace/Svc_Conf.h rename : externals/ace/Svc_Conf.y => dep/acelite/ace/Svc_Conf.y rename : externals/ace/Svc_Conf_Lexer.cpp => dep/acelite/ace/Svc_Conf_Lexer.cpp rename : externals/ace/Svc_Conf_Lexer.h => dep/acelite/ace/Svc_Conf_Lexer.h rename : externals/ace/Svc_Conf_Param.h => dep/acelite/ace/Svc_Conf_Param.h rename : externals/ace/Svc_Conf_Token_Table.h => dep/acelite/ace/Svc_Conf_Token_Table.h rename : externals/ace/Svc_Conf_Tokens.h => dep/acelite/ace/Svc_Conf_Tokens.h rename : externals/ace/Svc_Conf_y.cpp => dep/acelite/ace/Svc_Conf_y.cpp rename : externals/ace/Svc_Handler.cpp => dep/acelite/ace/Svc_Handler.cpp rename : externals/ace/Svc_Handler.h => dep/acelite/ace/Svc_Handler.h rename : externals/ace/Synch.h => dep/acelite/ace/Synch.h rename : externals/ace/Synch_Options.cpp => dep/acelite/ace/Synch_Options.cpp rename : externals/ace/Synch_Options.h => dep/acelite/ace/Synch_Options.h rename : externals/ace/Synch_T.cpp => dep/acelite/ace/Synch_T.cpp rename : externals/ace/Synch_T.h => dep/acelite/ace/Synch_T.h rename : externals/ace/Synch_Traits.h => dep/acelite/ace/Synch_Traits.h rename : externals/ace/System_Time.cpp => dep/acelite/ace/System_Time.cpp rename : externals/ace/System_Time.h => dep/acelite/ace/System_Time.h rename : externals/ace/TLI.cpp => dep/acelite/ace/TLI.cpp rename : externals/ace/TLI.h => dep/acelite/ace/TLI.h rename : externals/ace/TLI.inl => dep/acelite/ace/TLI.inl rename : externals/ace/TLI_Acceptor.cpp => dep/acelite/ace/TLI_Acceptor.cpp rename : externals/ace/TLI_Acceptor.h => dep/acelite/ace/TLI_Acceptor.h rename : externals/ace/TLI_Connector.cpp => dep/acelite/ace/TLI_Connector.cpp rename : externals/ace/TLI_Connector.h => dep/acelite/ace/TLI_Connector.h rename : externals/ace/TLI_Connector.inl => dep/acelite/ace/TLI_Connector.inl rename : externals/ace/TLI_Stream.cpp => dep/acelite/ace/TLI_Stream.cpp rename : externals/ace/TLI_Stream.h => dep/acelite/ace/TLI_Stream.h rename : externals/ace/TLI_Stream.inl => dep/acelite/ace/TLI_Stream.inl rename : externals/ace/TP_Reactor.cpp => dep/acelite/ace/TP_Reactor.cpp rename : externals/ace/TP_Reactor.h => dep/acelite/ace/TP_Reactor.h rename : externals/ace/TP_Reactor.inl => dep/acelite/ace/TP_Reactor.inl rename : externals/ace/TSS_Adapter.cpp => dep/acelite/ace/TSS_Adapter.cpp rename : externals/ace/TSS_Adapter.h => dep/acelite/ace/TSS_Adapter.h rename : externals/ace/TSS_T.cpp => dep/acelite/ace/TSS_T.cpp rename : externals/ace/TSS_T.h => dep/acelite/ace/TSS_T.h rename : externals/ace/TSS_T.inl => dep/acelite/ace/TSS_T.inl rename : externals/ace/TTY_IO.cpp => dep/acelite/ace/TTY_IO.cpp rename : externals/ace/TTY_IO.h => dep/acelite/ace/TTY_IO.h rename : externals/ace/Task.cpp => dep/acelite/ace/Task.cpp rename : externals/ace/Task.h => dep/acelite/ace/Task.h rename : externals/ace/Task.inl => dep/acelite/ace/Task.inl rename : externals/ace/Task_Ex_T.cpp => dep/acelite/ace/Task_Ex_T.cpp rename : externals/ace/Task_Ex_T.h => dep/acelite/ace/Task_Ex_T.h rename : externals/ace/Task_Ex_T.inl => dep/acelite/ace/Task_Ex_T.inl rename : externals/ace/Task_T.cpp => dep/acelite/ace/Task_T.cpp rename : externals/ace/Task_T.h => dep/acelite/ace/Task_T.h rename : externals/ace/Task_T.inl => dep/acelite/ace/Task_T.inl rename : externals/ace/Test_and_Set.cpp => dep/acelite/ace/Test_and_Set.cpp rename : externals/ace/Test_and_Set.h => dep/acelite/ace/Test_and_Set.h rename : externals/ace/Thread.cpp => dep/acelite/ace/Thread.cpp rename : externals/ace/Thread.h => dep/acelite/ace/Thread.h rename : externals/ace/Thread.inl => dep/acelite/ace/Thread.inl rename : externals/ace/Thread_Adapter.cpp => dep/acelite/ace/Thread_Adapter.cpp rename : externals/ace/Thread_Adapter.h => dep/acelite/ace/Thread_Adapter.h rename : externals/ace/Thread_Adapter.inl => dep/acelite/ace/Thread_Adapter.inl rename : externals/ace/Thread_Control.cpp => dep/acelite/ace/Thread_Control.cpp rename : externals/ace/Thread_Control.h => dep/acelite/ace/Thread_Control.h rename : externals/ace/Thread_Control.inl => dep/acelite/ace/Thread_Control.inl rename : externals/ace/Thread_Exit.cpp => dep/acelite/ace/Thread_Exit.cpp rename : externals/ace/Thread_Exit.h => dep/acelite/ace/Thread_Exit.h rename : externals/ace/Thread_Hook.cpp => dep/acelite/ace/Thread_Hook.cpp rename : externals/ace/Thread_Hook.h => dep/acelite/ace/Thread_Hook.h rename : externals/ace/Thread_Manager.cpp => dep/acelite/ace/Thread_Manager.cpp rename : externals/ace/Thread_Manager.h => dep/acelite/ace/Thread_Manager.h rename : externals/ace/Thread_Manager.inl => dep/acelite/ace/Thread_Manager.inl rename : externals/ace/Thread_Mutex.cpp => dep/acelite/ace/Thread_Mutex.cpp rename : externals/ace/Thread_Mutex.h => dep/acelite/ace/Thread_Mutex.h rename : externals/ace/Thread_Mutex.inl => dep/acelite/ace/Thread_Mutex.inl rename : externals/ace/Thread_Semaphore.cpp => dep/acelite/ace/Thread_Semaphore.cpp rename : externals/ace/Thread_Semaphore.h => dep/acelite/ace/Thread_Semaphore.h rename : externals/ace/Thread_Semaphore.inl => dep/acelite/ace/Thread_Semaphore.inl rename : externals/ace/Throughput_Stats.cpp => dep/acelite/ace/Throughput_Stats.cpp rename : externals/ace/Throughput_Stats.h => dep/acelite/ace/Throughput_Stats.h rename : externals/ace/Time_Value.cpp => dep/acelite/ace/Time_Value.cpp rename : externals/ace/Time_Value.h => dep/acelite/ace/Time_Value.h rename : externals/ace/Time_Value.inl => dep/acelite/ace/Time_Value.inl rename : externals/ace/Timeprobe.cpp => dep/acelite/ace/Timeprobe.cpp rename : externals/ace/Timeprobe.h => dep/acelite/ace/Timeprobe.h rename : externals/ace/Timeprobe.inl => dep/acelite/ace/Timeprobe.inl rename : externals/ace/Timeprobe_T.cpp => dep/acelite/ace/Timeprobe_T.cpp rename : externals/ace/Timeprobe_T.h => dep/acelite/ace/Timeprobe_T.h rename : externals/ace/Timer_Hash.h => dep/acelite/ace/Timer_Hash.h rename : externals/ace/Timer_Hash_T.cpp => dep/acelite/ace/Timer_Hash_T.cpp rename : externals/ace/Timer_Hash_T.h => dep/acelite/ace/Timer_Hash_T.h rename : externals/ace/Timer_Heap.h => dep/acelite/ace/Timer_Heap.h rename : externals/ace/Timer_Heap_T.cpp => dep/acelite/ace/Timer_Heap_T.cpp rename : externals/ace/Timer_Heap_T.h => dep/acelite/ace/Timer_Heap_T.h rename : externals/ace/Timer_List.h => dep/acelite/ace/Timer_List.h rename : externals/ace/Timer_List_T.cpp => dep/acelite/ace/Timer_List_T.cpp rename : externals/ace/Timer_List_T.h => dep/acelite/ace/Timer_List_T.h rename : externals/ace/Timer_Queue.h => dep/acelite/ace/Timer_Queue.h rename : externals/ace/Timer_Queue_Adapters.cpp => dep/acelite/ace/Timer_Queue_Adapters.cpp rename : externals/ace/Timer_Queue_Adapters.h => dep/acelite/ace/Timer_Queue_Adapters.h rename : externals/ace/Timer_Queue_Adapters.inl => dep/acelite/ace/Timer_Queue_Adapters.inl rename : externals/ace/Timer_Queue_T.cpp => dep/acelite/ace/Timer_Queue_T.cpp rename : externals/ace/Timer_Queue_T.h => dep/acelite/ace/Timer_Queue_T.h rename : externals/ace/Timer_Queue_T.inl => dep/acelite/ace/Timer_Queue_T.inl rename : externals/ace/Timer_Queuefwd.h => dep/acelite/ace/Timer_Queuefwd.h rename : externals/ace/Timer_Wheel.h => dep/acelite/ace/Timer_Wheel.h rename : externals/ace/Timer_Wheel_T.cpp => dep/acelite/ace/Timer_Wheel_T.cpp rename : externals/ace/Timer_Wheel_T.h => dep/acelite/ace/Timer_Wheel_T.h rename : externals/ace/Token.cpp => dep/acelite/ace/Token.cpp rename : externals/ace/Token.h => dep/acelite/ace/Token.h rename : externals/ace/Token.inl => dep/acelite/ace/Token.inl rename : externals/ace/Token_Collection.cpp => dep/acelite/ace/Token_Collection.cpp rename : externals/ace/Token_Collection.h => dep/acelite/ace/Token_Collection.h rename : externals/ace/Token_Collection.inl => dep/acelite/ace/Token_Collection.inl rename : externals/ace/Token_Invariants.cpp => dep/acelite/ace/Token_Invariants.cpp rename : externals/ace/Token_Invariants.h => dep/acelite/ace/Token_Invariants.h rename : externals/ace/Token_Manager.cpp => dep/acelite/ace/Token_Manager.cpp rename : externals/ace/Token_Manager.h => dep/acelite/ace/Token_Manager.h rename : externals/ace/Token_Manager.inl => dep/acelite/ace/Token_Manager.inl rename : externals/ace/Token_Request_Reply.cpp => dep/acelite/ace/Token_Request_Reply.cpp rename : externals/ace/Token_Request_Reply.h => dep/acelite/ace/Token_Request_Reply.h rename : externals/ace/Token_Request_Reply.inl => dep/acelite/ace/Token_Request_Reply.inl rename : externals/ace/Tokenizer_T.cpp => dep/acelite/ace/Tokenizer_T.cpp rename : externals/ace/Tokenizer_T.h => dep/acelite/ace/Tokenizer_T.h rename : externals/ace/Trace.cpp => dep/acelite/ace/Trace.cpp rename : externals/ace/Trace.h => dep/acelite/ace/Trace.h rename : externals/ace/Truncate.h => dep/acelite/ace/Truncate.h rename : externals/ace/Typed_SV_Message.cpp => dep/acelite/ace/Typed_SV_Message.cpp rename : externals/ace/Typed_SV_Message.h => dep/acelite/ace/Typed_SV_Message.h rename : externals/ace/Typed_SV_Message.inl => dep/acelite/ace/Typed_SV_Message.inl rename : externals/ace/Typed_SV_Message_Queue.cpp => dep/acelite/ace/Typed_SV_Message_Queue.cpp rename : externals/ace/Typed_SV_Message_Queue.h => dep/acelite/ace/Typed_SV_Message_Queue.h rename : externals/ace/Typed_SV_Message_Queue.inl => dep/acelite/ace/Typed_SV_Message_Queue.inl rename : externals/ace/UNIX_Addr.cpp => dep/acelite/ace/UNIX_Addr.cpp rename : externals/ace/UNIX_Addr.h => dep/acelite/ace/UNIX_Addr.h rename : externals/ace/UNIX_Addr.inl => dep/acelite/ace/UNIX_Addr.inl rename : externals/ace/UPIPE_Acceptor.cpp => dep/acelite/ace/UPIPE_Acceptor.cpp rename : externals/ace/UPIPE_Acceptor.h => dep/acelite/ace/UPIPE_Acceptor.h rename : externals/ace/UPIPE_Acceptor.inl => dep/acelite/ace/UPIPE_Acceptor.inl rename : externals/ace/UPIPE_Addr.h => dep/acelite/ace/UPIPE_Addr.h rename : externals/ace/UPIPE_Connector.cpp => dep/acelite/ace/UPIPE_Connector.cpp rename : externals/ace/UPIPE_Connector.h => dep/acelite/ace/UPIPE_Connector.h rename : externals/ace/UPIPE_Connector.inl => dep/acelite/ace/UPIPE_Connector.inl rename : externals/ace/UPIPE_Stream.cpp => dep/acelite/ace/UPIPE_Stream.cpp rename : externals/ace/UPIPE_Stream.h => dep/acelite/ace/UPIPE_Stream.h rename : externals/ace/UPIPE_Stream.inl => dep/acelite/ace/UPIPE_Stream.inl rename : externals/ace/UTF16_Encoding_Converter.cpp => dep/acelite/ace/UTF16_Encoding_Converter.cpp rename : externals/ace/UTF16_Encoding_Converter.h => dep/acelite/ace/UTF16_Encoding_Converter.h rename : externals/ace/UTF16_Encoding_Converter.inl => dep/acelite/ace/UTF16_Encoding_Converter.inl rename : externals/ace/UTF32_Encoding_Converter.cpp => dep/acelite/ace/UTF32_Encoding_Converter.cpp rename : externals/ace/UTF32_Encoding_Converter.h => dep/acelite/ace/UTF32_Encoding_Converter.h rename : externals/ace/UTF8_Encoding_Converter.cpp => dep/acelite/ace/UTF8_Encoding_Converter.cpp rename : externals/ace/UTF8_Encoding_Converter.h => dep/acelite/ace/UTF8_Encoding_Converter.h rename : externals/ace/UUID.cpp => dep/acelite/ace/UUID.cpp rename : externals/ace/UUID.h => dep/acelite/ace/UUID.h rename : externals/ace/UUID.inl => dep/acelite/ace/UUID.inl rename : externals/ace/Unbounded_Queue.cpp => dep/acelite/ace/Unbounded_Queue.cpp rename : externals/ace/Unbounded_Queue.h => dep/acelite/ace/Unbounded_Queue.h rename : externals/ace/Unbounded_Queue.inl => dep/acelite/ace/Unbounded_Queue.inl rename : externals/ace/Unbounded_Set.cpp => dep/acelite/ace/Unbounded_Set.cpp rename : externals/ace/Unbounded_Set.h => dep/acelite/ace/Unbounded_Set.h rename : externals/ace/Unbounded_Set.inl => dep/acelite/ace/Unbounded_Set.inl rename : externals/ace/Unbounded_Set_Ex.cpp => dep/acelite/ace/Unbounded_Set_Ex.cpp rename : externals/ace/Unbounded_Set_Ex.h => dep/acelite/ace/Unbounded_Set_Ex.h rename : externals/ace/Unbounded_Set_Ex.inl => dep/acelite/ace/Unbounded_Set_Ex.inl rename : externals/ace/Value_Ptr.h => dep/acelite/ace/Value_Ptr.h rename : externals/ace/Vector_T.cpp => dep/acelite/ace/Vector_T.cpp rename : externals/ace/Vector_T.h => dep/acelite/ace/Vector_T.h rename : externals/ace/Vector_T.inl => dep/acelite/ace/Vector_T.inl rename : externals/ace/Version.h => dep/acelite/ace/Version.h rename : externals/ace/Versioned_Namespace.h => dep/acelite/ace/Versioned_Namespace.h rename : externals/ace/WFMO_Reactor.cpp => dep/acelite/ace/WFMO_Reactor.cpp rename : externals/ace/WFMO_Reactor.h => dep/acelite/ace/WFMO_Reactor.h rename : externals/ace/WFMO_Reactor.inl => dep/acelite/ace/WFMO_Reactor.inl rename : externals/ace/WIN32_Asynch_IO.cpp => dep/acelite/ace/WIN32_Asynch_IO.cpp rename : externals/ace/WIN32_Asynch_IO.h => dep/acelite/ace/WIN32_Asynch_IO.h rename : externals/ace/WIN32_Proactor.cpp => dep/acelite/ace/WIN32_Proactor.cpp rename : externals/ace/WIN32_Proactor.h => dep/acelite/ace/WIN32_Proactor.h rename : externals/ace/XML_Svc_Conf.cpp => dep/acelite/ace/XML_Svc_Conf.cpp rename : externals/ace/XML_Svc_Conf.h => dep/acelite/ace/XML_Svc_Conf.h rename : externals/ace/XTI_ATM_Mcast.cpp => dep/acelite/ace/XTI_ATM_Mcast.cpp rename : externals/ace/XTI_ATM_Mcast.h => dep/acelite/ace/XTI_ATM_Mcast.h rename : externals/ace/XTI_ATM_Mcast.inl => dep/acelite/ace/XTI_ATM_Mcast.inl rename : externals/ace/ace.rc => dep/acelite/ace/ace.rc rename : externals/ace/ace_message_table.bin => dep/acelite/ace/ace_message_table.bin rename : externals/ace/ace_wchar.cpp => dep/acelite/ace/ace_wchar.cpp rename : externals/ace/ace_wchar.h => dep/acelite/ace/ace_wchar.h rename : externals/ace/ace_wchar.inl => dep/acelite/ace/ace_wchar.inl rename : externals/ace/checked_iterator.h => dep/acelite/ace/checked_iterator.h rename : externals/ace/config-WinCE.h => dep/acelite/ace/config-WinCE.h rename : externals/ace/config-aix-5.x.h => dep/acelite/ace/config-aix-5.x.h rename : externals/ace/config-all.h => dep/acelite/ace/config-all.h rename : externals/ace/config-cray.h => dep/acelite/ace/config-cray.h rename : externals/ace/config-cxx-common.h => dep/acelite/ace/config-cxx-common.h rename : externals/ace/config-cygwin32.h => dep/acelite/ace/config-cygwin32.h rename : externals/ace/config-doxygen.h => dep/acelite/ace/config-doxygen.h rename : externals/ace/config-freebsd.h => dep/acelite/ace/config-freebsd.h rename : externals/ace/config-g++-common.h => dep/acelite/ace/config-g++-common.h rename : externals/ace/config-ghs-common.h => dep/acelite/ace/config-ghs-common.h rename : externals/ace/config-hpux-11.00.h => dep/acelite/ace/config-hpux-11.00.h rename : externals/ace/config-icc-common.h => dep/acelite/ace/config-icc-common.h rename : externals/ace/config-integritySCA.h => dep/acelite/ace/config-integritySCA.h rename : externals/ace/config-irix6.5.x-sgic++.h => dep/acelite/ace/config-irix6.5.x-sgic++.h rename : externals/ace/config-irix6.x-common.h => dep/acelite/ace/config-irix6.x-common.h rename : externals/ace/config-irix6.x-g++.h => dep/acelite/ace/config-irix6.x-g++.h rename : externals/ace/config-irix6.x-sgic++.h => dep/acelite/ace/config-irix6.x-sgic++.h rename : externals/ace/config-linux-common.h => dep/acelite/ace/config-linux-common.h rename : externals/ace/config-linux.h => dep/acelite/ace/config-linux.h rename : externals/ace/config-lite.h => dep/acelite/ace/config-lite.h rename : externals/ace/config-lynxos.h => dep/acelite/ace/config-lynxos.h rename : externals/ace/config-macosx-iphone-hardware.h => dep/acelite/ace/config-macosx-iphone-hardware.h rename : externals/ace/config-macosx-iphone-simulator.h => dep/acelite/ace/config-macosx-iphone-simulator.h rename : externals/ace/config-macosx-leopard.h => dep/acelite/ace/config-macosx-leopard.h rename : externals/ace/config-macosx-panther.h => dep/acelite/ace/config-macosx-panther.h rename : externals/ace/config-macosx-snowleopard.h => dep/acelite/ace/config-macosx-snowleopard.h rename : externals/ace/config-macosx-tiger.h => dep/acelite/ace/config-macosx-tiger.h rename : externals/ace/config-macosx.h => dep/acelite/ace/config-macosx.h rename : externals/ace/config-macros.h => dep/acelite/ace/config-macros.h rename : externals/ace/config-minimal.h => dep/acelite/ace/config-minimal.h rename : externals/ace/config-mvs.h => dep/acelite/ace/config-mvs.h rename : externals/ace/config-netbsd.h => dep/acelite/ace/config-netbsd.h rename : externals/ace/config-openbsd.h => dep/acelite/ace/config-openbsd.h rename : externals/ace/config-openvms.h => dep/acelite/ace/config-openvms.h rename : externals/ace/config-pharlap.h => dep/acelite/ace/config-pharlap.h rename : externals/ace/config-posix-nonetworking.h => dep/acelite/ace/config-posix-nonetworking.h rename : externals/ace/config-posix.h => dep/acelite/ace/config-posix.h rename : externals/ace/config-qnx-neutrino.h => dep/acelite/ace/config-qnx-neutrino.h rename : externals/ace/config-qnx-rtp-62x.h => dep/acelite/ace/config-qnx-rtp-62x.h rename : externals/ace/config-qnx-rtp-common.h => dep/acelite/ace/config-qnx-rtp-common.h rename : externals/ace/config-qnx-rtp-pre62x.h => dep/acelite/ace/config-qnx-rtp-pre62x.h rename : externals/ace/config-qnx-rtp.h => dep/acelite/ace/config-qnx-rtp.h rename : externals/ace/config-rtems.h => dep/acelite/ace/config-rtems.h rename : externals/ace/config-sco-5.0.0-nothread.h => dep/acelite/ace/config-sco-5.0.0-nothread.h rename : externals/ace/config-sco-5.0.0.h => dep/acelite/ace/config-sco-5.0.0.h rename : externals/ace/config-suncc-common.h => dep/acelite/ace/config-suncc-common.h rename : externals/ace/config-sunos5.10.h => dep/acelite/ace/config-sunos5.10.h rename : externals/ace/config-sunos5.11.h => dep/acelite/ace/config-sunos5.11.h rename : externals/ace/config-sunos5.4-g++.h => dep/acelite/ace/config-sunos5.4-g++.h rename : externals/ace/config-sunos5.4-sunc++-4.x.h => dep/acelite/ace/config-sunos5.4-sunc++-4.x.h rename : externals/ace/config-sunos5.5.h => dep/acelite/ace/config-sunos5.5.h rename : externals/ace/config-sunos5.6.h => dep/acelite/ace/config-sunos5.6.h rename : externals/ace/config-sunos5.7.h => dep/acelite/ace/config-sunos5.7.h rename : externals/ace/config-sunos5.8.h => dep/acelite/ace/config-sunos5.8.h rename : externals/ace/config-sunos5.9.h => dep/acelite/ace/config-sunos5.9.h rename : externals/ace/config-tandem-nsk-mips-v2.h => dep/acelite/ace/config-tandem-nsk-mips-v2.h rename : externals/ace/config-tandem-nsk-mips-v3.h => dep/acelite/ace/config-tandem-nsk-mips-v3.h rename : externals/ace/config-tandem.h => dep/acelite/ace/config-tandem.h rename : externals/ace/config-tru64.h => dep/acelite/ace/config-tru64.h rename : externals/ace/config-unixware-7.1.0.h => dep/acelite/ace/config-unixware-7.1.0.h rename : externals/ace/config-unixware-7.1.0.udk.h => dep/acelite/ace/config-unixware-7.1.0.udk.h rename : externals/ace/config-visualage.h => dep/acelite/ace/config-visualage.h rename : externals/ace/config-vxworks.h => dep/acelite/ace/config-vxworks.h rename : externals/ace/config-vxworks6.4.h => dep/acelite/ace/config-vxworks6.4.h rename : externals/ace/config-vxworks6.5.h => dep/acelite/ace/config-vxworks6.5.h rename : externals/ace/config-vxworks6.6.h => dep/acelite/ace/config-vxworks6.6.h rename : externals/ace/config-vxworks6.7.h => dep/acelite/ace/config-vxworks6.7.h rename : externals/ace/config-vxworks6.8.h => dep/acelite/ace/config-vxworks6.8.h rename : externals/ace/config-win32-borland.h => dep/acelite/ace/config-win32-borland.h rename : externals/ace/config-win32-cegcc.h => dep/acelite/ace/config-win32-cegcc.h rename : externals/ace/config-win32-common.h => dep/acelite/ace/config-win32-common.h rename : externals/ace/config-win32-dmc.h => dep/acelite/ace/config-win32-dmc.h rename : externals/ace/config-win32-ghs.h => dep/acelite/ace/config-win32-ghs.h rename : externals/ace/config-win32-interix.h => dep/acelite/ace/config-win32-interix.h rename : externals/ace/config-win32-mingw.h => dep/acelite/ace/config-win32-mingw.h rename : externals/ace/config-win32-msvc-10.h => dep/acelite/ace/config-win32-msvc-10.h rename : externals/ace/config-win32-msvc-7.h => dep/acelite/ace/config-win32-msvc-7.h rename : externals/ace/config-win32-msvc-8.h => dep/acelite/ace/config-win32-msvc-8.h rename : externals/ace/config-win32-msvc-9.h => dep/acelite/ace/config-win32-msvc-9.h rename : externals/ace/config-win32-msvc.h => dep/acelite/ace/config-win32-msvc.h rename : externals/ace/config-win32.h => dep/acelite/ace/config-win32.h rename : externals/ace/config.h.in => dep/acelite/ace/config.h.in rename : externals/ace/gethrtime.cpp => dep/acelite/ace/gethrtime.cpp rename : externals/ace/iosfwd.h => dep/acelite/ace/iosfwd.h rename : externals/ace/os_include/arpa/os_inet.h => dep/acelite/ace/os_include/arpa/os_inet.h rename : externals/ace/os_include/net/os_if.h => dep/acelite/ace/os_include/net/os_if.h rename : externals/ace/os_include/netinet/os_in.h => dep/acelite/ace/os_include/netinet/os_in.h rename : externals/ace/os_include/netinet/os_tcp.h => dep/acelite/ace/os_include/netinet/os_tcp.h rename : externals/ace/os_include/os_aio.h => dep/acelite/ace/os_include/os_aio.h rename : externals/ace/os_include/os_assert.h => dep/acelite/ace/os_include/os_assert.h rename : externals/ace/os_include/os_byteswap.h => dep/acelite/ace/os_include/os_byteswap.h rename : externals/ace/os_include/os_complex.h => dep/acelite/ace/os_include/os_complex.h rename : externals/ace/os_include/os_cpio.h => dep/acelite/ace/os_include/os_cpio.h rename : externals/ace/os_include/os_ctype.h => dep/acelite/ace/os_include/os_ctype.h rename : externals/ace/os_include/os_dirent.h => dep/acelite/ace/os_include/os_dirent.h rename : externals/ace/os_include/os_dlfcn.h => dep/acelite/ace/os_include/os_dlfcn.h rename : externals/ace/os_include/os_errno.h => dep/acelite/ace/os_include/os_errno.h rename : externals/ace/os_include/os_fcntl.h => dep/acelite/ace/os_include/os_fcntl.h rename : externals/ace/os_include/os_fenv.h => dep/acelite/ace/os_include/os_fenv.h rename : externals/ace/os_include/os_float.h => dep/acelite/ace/os_include/os_float.h rename : externals/ace/os_include/os_fmtmsg.h => dep/acelite/ace/os_include/os_fmtmsg.h rename : externals/ace/os_include/os_fnmatch.h => dep/acelite/ace/os_include/os_fnmatch.h rename : externals/ace/os_include/os_ftw.h => dep/acelite/ace/os_include/os_ftw.h rename : externals/ace/os_include/os_glob.h => dep/acelite/ace/os_include/os_glob.h rename : externals/ace/os_include/os_grp.h => dep/acelite/ace/os_include/os_grp.h rename : externals/ace/os_include/os_iconv.h => dep/acelite/ace/os_include/os_iconv.h rename : externals/ace/os_include/os_intrin.h => dep/acelite/ace/os_include/os_intrin.h rename : externals/ace/os_include/os_inttypes.h => dep/acelite/ace/os_include/os_inttypes.h rename : externals/ace/os_include/os_iso646.h => dep/acelite/ace/os_include/os_iso646.h rename : externals/ace/os_include/os_kstat.h => dep/acelite/ace/os_include/os_kstat.h rename : externals/ace/os_include/os_langinfo.h => dep/acelite/ace/os_include/os_langinfo.h rename : externals/ace/os_include/os_libgen.h => dep/acelite/ace/os_include/os_libgen.h rename : externals/ace/os_include/os_limits.h => dep/acelite/ace/os_include/os_limits.h rename : externals/ace/os_include/os_local.h => dep/acelite/ace/os_include/os_local.h rename : externals/ace/os_include/os_math.h => dep/acelite/ace/os_include/os_math.h rename : externals/ace/os_include/os_monetary.h => dep/acelite/ace/os_include/os_monetary.h rename : externals/ace/os_include/os_mqueue.h => dep/acelite/ace/os_include/os_mqueue.h rename : externals/ace/os_include/os_ndbm.h => dep/acelite/ace/os_include/os_ndbm.h rename : externals/ace/os_include/os_netdb.h => dep/acelite/ace/os_include/os_netdb.h rename : externals/ace/os_include/os_nl_types.h => dep/acelite/ace/os_include/os_nl_types.h rename : externals/ace/os_include/os_pdh.h => dep/acelite/ace/os_include/os_pdh.h rename : externals/ace/os_include/os_pdhmsg.h => dep/acelite/ace/os_include/os_pdhmsg.h rename : externals/ace/os_include/os_poll.h => dep/acelite/ace/os_include/os_poll.h rename : externals/ace/os_include/os_pthread.h => dep/acelite/ace/os_include/os_pthread.h rename : externals/ace/os_include/os_pwd.h => dep/acelite/ace/os_include/os_pwd.h rename : externals/ace/os_include/os_regex.h => dep/acelite/ace/os_include/os_regex.h rename : externals/ace/os_include/os_sched.h => dep/acelite/ace/os_include/os_sched.h rename : externals/ace/os_include/os_search.h => dep/acelite/ace/os_include/os_search.h rename : externals/ace/os_include/os_semaphore.h => dep/acelite/ace/os_include/os_semaphore.h rename : externals/ace/os_include/os_setjmp.h => dep/acelite/ace/os_include/os_setjmp.h rename : externals/ace/os_include/os_signal.h => dep/acelite/ace/os_include/os_signal.h rename : externals/ace/os_include/os_spawn.h => dep/acelite/ace/os_include/os_spawn.h rename : externals/ace/os_include/os_stdarg.h => dep/acelite/ace/os_include/os_stdarg.h rename : externals/ace/os_include/os_stdbool.h => dep/acelite/ace/os_include/os_stdbool.h rename : externals/ace/os_include/os_stddef.h => dep/acelite/ace/os_include/os_stddef.h rename : externals/ace/os_include/os_stdint.h => dep/acelite/ace/os_include/os_stdint.h rename : externals/ace/os_include/os_stdio.h => dep/acelite/ace/os_include/os_stdio.h rename : externals/ace/os_include/os_stdlib.h => dep/acelite/ace/os_include/os_stdlib.h rename : externals/ace/os_include/os_string.h => dep/acelite/ace/os_include/os_string.h rename : externals/ace/os_include/os_strings.h => dep/acelite/ace/os_include/os_strings.h rename : externals/ace/os_include/os_stropts.h => dep/acelite/ace/os_include/os_stropts.h rename : externals/ace/os_include/os_syslog.h => dep/acelite/ace/os_include/os_syslog.h rename : externals/ace/os_include/os_tar.h => dep/acelite/ace/os_include/os_tar.h rename : externals/ace/os_include/os_termios.h => dep/acelite/ace/os_include/os_termios.h rename : externals/ace/os_include/os_tgmath.h => dep/acelite/ace/os_include/os_tgmath.h rename : externals/ace/os_include/os_time.h => dep/acelite/ace/os_include/os_time.h rename : externals/ace/os_include/os_trace.h => dep/acelite/ace/os_include/os_trace.h rename : externals/ace/os_include/os_typeinfo.h => dep/acelite/ace/os_include/os_typeinfo.h rename : externals/ace/os_include/os_ucontext.h => dep/acelite/ace/os_include/os_ucontext.h rename : externals/ace/os_include/os_ulimit.h => dep/acelite/ace/os_include/os_ulimit.h rename : externals/ace/os_include/os_unistd.h => dep/acelite/ace/os_include/os_unistd.h rename : externals/ace/os_include/os_utime.h => dep/acelite/ace/os_include/os_utime.h rename : externals/ace/os_include/os_utmpx.h => dep/acelite/ace/os_include/os_utmpx.h rename : externals/ace/os_include/os_wchar.h => dep/acelite/ace/os_include/os_wchar.h rename : externals/ace/os_include/os_wctype.h => dep/acelite/ace/os_include/os_wctype.h rename : externals/ace/os_include/os_wordexp.h => dep/acelite/ace/os_include/os_wordexp.h rename : externals/ace/os_include/sys/os_ipc.h => dep/acelite/ace/os_include/sys/os_ipc.h rename : externals/ace/os_include/sys/os_loadavg.h => dep/acelite/ace/os_include/sys/os_loadavg.h rename : externals/ace/os_include/sys/os_mman.h => dep/acelite/ace/os_include/sys/os_mman.h rename : externals/ace/os_include/sys/os_msg.h => dep/acelite/ace/os_include/sys/os_msg.h rename : externals/ace/os_include/sys/os_pstat.h => dep/acelite/ace/os_include/sys/os_pstat.h rename : externals/ace/os_include/sys/os_resource.h => dep/acelite/ace/os_include/sys/os_resource.h rename : externals/ace/os_include/sys/os_select.h => dep/acelite/ace/os_include/sys/os_select.h rename : externals/ace/os_include/sys/os_sem.h => dep/acelite/ace/os_include/sys/os_sem.h rename : externals/ace/os_include/sys/os_shm.h => dep/acelite/ace/os_include/sys/os_shm.h rename : externals/ace/os_include/sys/os_socket.h => dep/acelite/ace/os_include/sys/os_socket.h rename : externals/ace/os_include/sys/os_stat.h => dep/acelite/ace/os_include/sys/os_stat.h rename : externals/ace/os_include/sys/os_statvfs.h => dep/acelite/ace/os_include/sys/os_statvfs.h rename : externals/ace/os_include/sys/os_sysctl.h => dep/acelite/ace/os_include/sys/os_sysctl.h rename : externals/ace/os_include/sys/os_sysinfo.h => dep/acelite/ace/os_include/sys/os_sysinfo.h rename : externals/ace/os_include/sys/os_time.h => dep/acelite/ace/os_include/sys/os_time.h rename : externals/ace/os_include/sys/os_timeb.h => dep/acelite/ace/os_include/sys/os_timeb.h rename : externals/ace/os_include/sys/os_times.h => dep/acelite/ace/os_include/sys/os_times.h rename : externals/ace/os_include/sys/os_types.h => dep/acelite/ace/os_include/sys/os_types.h rename : externals/ace/os_include/sys/os_uio.h => dep/acelite/ace/os_include/sys/os_uio.h rename : externals/ace/os_include/sys/os_un.h => dep/acelite/ace/os_include/sys/os_un.h rename : externals/ace/os_include/sys/os_utsname.h => dep/acelite/ace/os_include/sys/os_utsname.h rename : externals/ace/os_include/sys/os_wait.h => dep/acelite/ace/os_include/sys/os_wait.h rename : externals/ace/post.h => dep/acelite/ace/post.h rename : externals/ace/pre.h => dep/acelite/ace/pre.h rename : externals/ace/streams.h => dep/acelite/ace/streams.h rename : externals/ace/svc_export.h => dep/acelite/ace/svc_export.h rename : externals/bzip2/CMakeLists.txt => dep/bzip2/CMakeLists.txt rename : externals/bzip2/blocksort.c => dep/bzip2/blocksort.c rename : externals/bzip2/bzlib.c => dep/bzip2/bzlib.c rename : externals/bzip2/bzlib.h => dep/bzip2/bzlib.h rename : externals/bzip2/bzlib_private.h => dep/bzip2/bzlib_private.h rename : externals/bzip2/compress.c => dep/bzip2/compress.c rename : externals/bzip2/crctable.c => dep/bzip2/crctable.c rename : externals/bzip2/decompress.c => dep/bzip2/decompress.c rename : externals/bzip2/huffman.c => dep/bzip2/huffman.c rename : externals/bzip2/randtable.c => dep/bzip2/randtable.c rename : externals/g3dlite/AABox.cpp => dep/g3dlite/AABox.cpp rename : externals/g3dlite/Any.cpp => dep/g3dlite/Any.cpp rename : externals/g3dlite/BinaryFormat.cpp => dep/g3dlite/BinaryFormat.cpp rename : externals/g3dlite/BinaryInput.cpp => dep/g3dlite/BinaryInput.cpp rename : externals/g3dlite/BinaryOutput.cpp => dep/g3dlite/BinaryOutput.cpp rename : externals/g3dlite/Box.cpp => dep/g3dlite/Box.cpp rename : externals/g3dlite/CMakeLists.txt => dep/g3dlite/CMakeLists.txt rename : externals/g3dlite/Capsule.cpp => dep/g3dlite/Capsule.cpp rename : externals/g3dlite/CollisionDetection.cpp => dep/g3dlite/CollisionDetection.cpp rename : externals/g3dlite/CoordinateFrame.cpp => dep/g3dlite/CoordinateFrame.cpp rename : externals/g3dlite/Crypto.cpp => dep/g3dlite/Crypto.cpp rename : externals/g3dlite/Cylinder.cpp => dep/g3dlite/Cylinder.cpp rename : externals/g3dlite/G3D/AABox.h => dep/g3dlite/G3D/AABox.h rename : externals/g3dlite/G3D/Any.h => dep/g3dlite/G3D/Any.h rename : externals/g3dlite/G3D/AnyVal.h => dep/g3dlite/G3D/AnyVal.h rename : externals/g3dlite/G3D/AreaMemoryManager.h => dep/g3dlite/G3D/AreaMemoryManager.h rename : externals/g3dlite/G3D/Array.h => dep/g3dlite/G3D/Array.h rename : externals/g3dlite/G3D/AtomicInt32.h => dep/g3dlite/G3D/AtomicInt32.h rename : externals/g3dlite/G3D/BinaryFormat.h => dep/g3dlite/G3D/BinaryFormat.h rename : externals/g3dlite/G3D/BinaryInput.h => dep/g3dlite/G3D/BinaryInput.h rename : externals/g3dlite/G3D/BinaryOutput.h => dep/g3dlite/G3D/BinaryOutput.h rename : externals/g3dlite/G3D/BoundsTrait.h => dep/g3dlite/G3D/BoundsTrait.h rename : externals/g3dlite/G3D/Box.h => dep/g3dlite/G3D/Box.h rename : externals/g3dlite/G3D/Box2D.h => dep/g3dlite/G3D/Box2D.h rename : externals/g3dlite/G3D/BumpMapPreprocess.h => dep/g3dlite/G3D/BumpMapPreprocess.h rename : externals/g3dlite/G3D/Capsule.h => dep/g3dlite/G3D/Capsule.h rename : externals/g3dlite/G3D/CollisionDetection.h => dep/g3dlite/G3D/CollisionDetection.h rename : externals/g3dlite/G3D/Color1.h => dep/g3dlite/G3D/Color1.h rename : externals/g3dlite/G3D/Color1uint8.h => dep/g3dlite/G3D/Color1uint8.h rename : externals/g3dlite/G3D/Color3.h => dep/g3dlite/G3D/Color3.h rename : externals/g3dlite/G3D/Color3uint8.h => dep/g3dlite/G3D/Color3uint8.h rename : externals/g3dlite/G3D/Color4.h => dep/g3dlite/G3D/Color4.h rename : externals/g3dlite/G3D/Color4uint8.h => dep/g3dlite/G3D/Color4uint8.h rename : externals/g3dlite/G3D/Cone.h => dep/g3dlite/G3D/Cone.h rename : externals/g3dlite/G3D/ConvexPolyhedron.h => dep/g3dlite/G3D/ConvexPolyhedron.h rename : externals/g3dlite/G3D/CoordinateFrame.h => dep/g3dlite/G3D/CoordinateFrame.h rename : externals/g3dlite/G3D/Crypto.h => dep/g3dlite/G3D/Crypto.h rename : externals/g3dlite/G3D/Cylinder.h => dep/g3dlite/G3D/Cylinder.h rename : externals/g3dlite/G3D/EqualsTrait.h => dep/g3dlite/G3D/EqualsTrait.h rename : externals/g3dlite/G3D/G3D.h => dep/g3dlite/G3D/G3D.h rename : externals/g3dlite/G3D/G3DAll.h => dep/g3dlite/G3D/G3DAll.h rename : externals/g3dlite/G3D/G3DGameUnits.h => dep/g3dlite/G3D/G3DGameUnits.h rename : externals/g3dlite/G3D/GCamera.h => dep/g3dlite/G3D/GCamera.h rename : externals/g3dlite/G3D/GImage.h => dep/g3dlite/G3D/GImage.h rename : externals/g3dlite/G3D/GLight.h => dep/g3dlite/G3D/GLight.h rename : externals/g3dlite/G3D/GMutex.h => dep/g3dlite/G3D/GMutex.h rename : externals/g3dlite/G3D/GThread.h => dep/g3dlite/G3D/GThread.h rename : externals/g3dlite/G3D/GUniqueID.h => dep/g3dlite/G3D/GUniqueID.h rename : externals/g3dlite/G3D/HashTrait.h => dep/g3dlite/G3D/HashTrait.h rename : externals/g3dlite/G3D/Image1.h => dep/g3dlite/G3D/Image1.h rename : externals/g3dlite/G3D/Image1uint8.h => dep/g3dlite/G3D/Image1uint8.h rename : externals/g3dlite/G3D/Image3.h => dep/g3dlite/G3D/Image3.h rename : externals/g3dlite/G3D/Image3uint8.h => dep/g3dlite/G3D/Image3uint8.h rename : externals/g3dlite/G3D/Image4.h => dep/g3dlite/G3D/Image4.h rename : externals/g3dlite/G3D/Image4uint8.h => dep/g3dlite/G3D/Image4uint8.h rename : externals/g3dlite/G3D/ImageFormat.h => dep/g3dlite/G3D/ImageFormat.h rename : externals/g3dlite/G3D/Intersect.h => dep/g3dlite/G3D/Intersect.h rename : externals/g3dlite/G3D/KDTree.h => dep/g3dlite/G3D/KDTree.h rename : externals/g3dlite/G3D/Line.h => dep/g3dlite/G3D/Line.h rename : externals/g3dlite/G3D/LineSegment.h => dep/g3dlite/G3D/LineSegment.h rename : externals/g3dlite/G3D/Log.h => dep/g3dlite/G3D/Log.h rename : externals/g3dlite/G3D/Map2D.h => dep/g3dlite/G3D/Map2D.h rename : externals/g3dlite/G3D/Matrix.h => dep/g3dlite/G3D/Matrix.h rename : externals/g3dlite/G3D/Matrix2.h => dep/g3dlite/G3D/Matrix2.h rename : externals/g3dlite/G3D/Matrix3.h => dep/g3dlite/G3D/Matrix3.h rename : externals/g3dlite/G3D/Matrix4.h => dep/g3dlite/G3D/Matrix4.h rename : externals/g3dlite/G3D/MemoryManager.h => dep/g3dlite/G3D/MemoryManager.h rename : externals/g3dlite/G3D/MeshAlg.h => dep/g3dlite/G3D/MeshAlg.h rename : externals/g3dlite/G3D/MeshBuilder.h => dep/g3dlite/G3D/MeshBuilder.h rename : externals/g3dlite/G3D/NetAddress.h => dep/g3dlite/G3D/NetAddress.h rename : externals/g3dlite/G3D/NetworkDevice.h => dep/g3dlite/G3D/NetworkDevice.h rename : externals/g3dlite/G3D/ParseError.h => dep/g3dlite/G3D/ParseError.h rename : externals/g3dlite/G3D/PhysicsFrame.h => dep/g3dlite/G3D/PhysicsFrame.h rename : externals/g3dlite/G3D/Plane.h => dep/g3dlite/G3D/Plane.h rename : externals/g3dlite/G3D/PointHashGrid.h => dep/g3dlite/G3D/PointHashGrid.h rename : externals/g3dlite/G3D/PointKDTree.h => dep/g3dlite/G3D/PointKDTree.h rename : externals/g3dlite/G3D/Pointer.h => dep/g3dlite/G3D/Pointer.h rename : externals/g3dlite/G3D/PositionTrait.h => dep/g3dlite/G3D/PositionTrait.h rename : externals/g3dlite/G3D/PrecomputedRandom.h => dep/g3dlite/G3D/PrecomputedRandom.h rename : externals/g3dlite/G3D/Quat.h => dep/g3dlite/G3D/Quat.h rename : externals/g3dlite/G3D/Quat.inl => dep/g3dlite/G3D/Quat.inl rename : externals/g3dlite/G3D/Queue.h => dep/g3dlite/G3D/Queue.h rename : externals/g3dlite/G3D/Random.h => dep/g3dlite/G3D/Random.h rename : externals/g3dlite/G3D/Ray.h => dep/g3dlite/G3D/Ray.h rename : externals/g3dlite/G3D/Rect2D.h => dep/g3dlite/G3D/Rect2D.h rename : externals/g3dlite/G3D/ReferenceCount.h => dep/g3dlite/G3D/ReferenceCount.h rename : externals/g3dlite/G3D/RegistryUtil.h => dep/g3dlite/G3D/RegistryUtil.h rename : externals/g3dlite/G3D/Set.h => dep/g3dlite/G3D/Set.h rename : externals/g3dlite/G3D/SmallArray.h => dep/g3dlite/G3D/SmallArray.h rename : externals/g3dlite/G3D/Sphere.h => dep/g3dlite/G3D/Sphere.h rename : externals/g3dlite/G3D/Spline.h => dep/g3dlite/G3D/Spline.h rename : externals/g3dlite/G3D/Stopwatch.h => dep/g3dlite/G3D/Stopwatch.h rename : externals/g3dlite/G3D/System.h => dep/g3dlite/G3D/System.h rename : externals/g3dlite/G3D/Table.h => dep/g3dlite/G3D/Table.h rename : externals/g3dlite/G3D/TextInput.h => dep/g3dlite/G3D/TextInput.h rename : externals/g3dlite/G3D/TextOutput.h => dep/g3dlite/G3D/TextOutput.h rename : externals/g3dlite/G3D/ThreadSet.h => dep/g3dlite/G3D/ThreadSet.h rename : externals/g3dlite/G3D/Triangle.h => dep/g3dlite/G3D/Triangle.h rename : externals/g3dlite/G3D/UprightFrame.h => dep/g3dlite/G3D/UprightFrame.h rename : externals/g3dlite/G3D/Vector2.h => dep/g3dlite/G3D/Vector2.h rename : externals/g3dlite/G3D/Vector2.inl => dep/g3dlite/G3D/Vector2.inl rename : externals/g3dlite/G3D/Vector2int16.h => dep/g3dlite/G3D/Vector2int16.h rename : externals/g3dlite/G3D/Vector3.h => dep/g3dlite/G3D/Vector3.h rename : externals/g3dlite/G3D/Vector3.inl => dep/g3dlite/G3D/Vector3.inl rename : externals/g3dlite/G3D/Vector3int16.h => dep/g3dlite/G3D/Vector3int16.h rename : externals/g3dlite/G3D/Vector3int32.h => dep/g3dlite/G3D/Vector3int32.h rename : externals/g3dlite/G3D/Vector4.h => dep/g3dlite/G3D/Vector4.h rename : externals/g3dlite/G3D/Vector4.inl => dep/g3dlite/G3D/Vector4.inl rename : externals/g3dlite/G3D/Vector4int8.h => dep/g3dlite/G3D/Vector4int8.h rename : externals/g3dlite/G3D/WeakCache.h => dep/g3dlite/G3D/WeakCache.h rename : externals/g3dlite/G3D/Welder.h => dep/g3dlite/G3D/Welder.h rename : externals/g3dlite/G3D/WrapMode.h => dep/g3dlite/G3D/WrapMode.h rename : externals/g3dlite/G3D/constants.h => dep/g3dlite/G3D/constants.h rename : externals/g3dlite/G3D/debug.h => dep/g3dlite/G3D/debug.h rename : externals/g3dlite/G3D/debugAssert.h => dep/g3dlite/G3D/debugAssert.h rename : externals/g3dlite/G3D/debugPrintf.h => dep/g3dlite/G3D/debugPrintf.h rename : externals/g3dlite/G3D/enumclass.h => dep/g3dlite/G3D/enumclass.h rename : externals/g3dlite/G3D/fileutils.h => dep/g3dlite/G3D/fileutils.h rename : externals/g3dlite/G3D/filter.h => dep/g3dlite/G3D/filter.h rename : externals/g3dlite/G3D/format.h => dep/g3dlite/G3D/format.h rename : externals/g3dlite/G3D/g3dfnmatch.h => dep/g3dlite/G3D/g3dfnmatch.h rename : externals/g3dlite/G3D/g3dmath.h => dep/g3dlite/G3D/g3dmath.h rename : externals/g3dlite/G3D/g3dmath.inl => dep/g3dlite/G3D/g3dmath.inl rename : externals/g3dlite/G3D/platform.h => dep/g3dlite/G3D/platform.h rename : externals/g3dlite/G3D/prompt.h => dep/g3dlite/G3D/prompt.h rename : externals/g3dlite/G3D/serialize.h => dep/g3dlite/G3D/serialize.h rename : externals/g3dlite/G3D/splinefunc.h => dep/g3dlite/G3D/splinefunc.h rename : externals/g3dlite/G3D/stringutils.h => dep/g3dlite/G3D/stringutils.h rename : externals/g3dlite/G3D/uint128.h => dep/g3dlite/G3D/uint128.h rename : externals/g3dlite/G3D/units.h => dep/g3dlite/G3D/units.h rename : externals/g3dlite/G3D/vectorMath.h => dep/g3dlite/G3D/vectorMath.h rename : externals/g3dlite/Line.cpp => dep/g3dlite/Line.cpp rename : externals/g3dlite/LineSegment.cpp => dep/g3dlite/LineSegment.cpp rename : externals/g3dlite/Log.cpp => dep/g3dlite/Log.cpp rename : externals/g3dlite/Matrix3.cpp => dep/g3dlite/Matrix3.cpp rename : externals/g3dlite/Matrix4.cpp => dep/g3dlite/Matrix4.cpp rename : externals/g3dlite/MemoryManager.cpp => dep/g3dlite/MemoryManager.cpp rename : externals/g3dlite/Plane.cpp => dep/g3dlite/Plane.cpp rename : externals/g3dlite/Quat.cpp => dep/g3dlite/Quat.cpp rename : externals/g3dlite/Random.cpp => dep/g3dlite/Random.cpp rename : externals/g3dlite/Ray.cpp => dep/g3dlite/Ray.cpp rename : externals/g3dlite/ReferenceCount.cpp => dep/g3dlite/ReferenceCount.cpp rename : externals/g3dlite/RegistryUtil.cpp => dep/g3dlite/RegistryUtil.cpp rename : externals/g3dlite/Sphere.cpp => dep/g3dlite/Sphere.cpp rename : externals/g3dlite/System.cpp => dep/g3dlite/System.cpp rename : externals/g3dlite/TextInput.cpp => dep/g3dlite/TextInput.cpp rename : externals/g3dlite/TextOutput.cpp => dep/g3dlite/TextOutput.cpp rename : externals/g3dlite/Triangle.cpp => dep/g3dlite/Triangle.cpp rename : externals/g3dlite/UprightFrame.cpp => dep/g3dlite/UprightFrame.cpp rename : externals/g3dlite/Vector2.cpp => dep/g3dlite/Vector2.cpp rename : externals/g3dlite/Vector3.cpp => dep/g3dlite/Vector3.cpp rename : externals/g3dlite/Vector4.cpp => dep/g3dlite/Vector4.cpp rename : externals/g3dlite/debugAssert.cpp => dep/g3dlite/debugAssert.cpp rename : externals/g3dlite/fileutils.cpp => dep/g3dlite/fileutils.cpp rename : externals/g3dlite/format.cpp => dep/g3dlite/format.cpp rename : externals/g3dlite/g3dfnmatch.cpp => dep/g3dlite/g3dfnmatch.cpp rename : externals/g3dlite/g3dmath.cpp => dep/g3dlite/g3dmath.cpp rename : externals/g3dlite/prompt.cpp => dep/g3dlite/prompt.cpp rename : externals/g3dlite/stringutils.cpp => dep/g3dlite/stringutils.cpp rename : externals/gsoap/CMakeLists.txt => dep/gsoap/CMakeLists.txt rename : externals/gsoap/soapC.cpp => dep/gsoap/soapC.cpp rename : externals/gsoap/soapH.h => dep/gsoap/soapH.h rename : externals/gsoap/soapServer.cpp => dep/gsoap/soapServer.cpp rename : externals/gsoap/soapStub.h => dep/gsoap/soapStub.h rename : externals/gsoap/stdsoap2.cpp => dep/gsoap/stdsoap2.cpp rename : externals/gsoap/stdsoap2.h => dep/gsoap/stdsoap2.h rename : externals/jemalloc/CMakeLists.txt => dep/jemalloc/CMakeLists.txt rename : externals/jemalloc/arena.c => dep/jemalloc/arena.c rename : externals/jemalloc/base.c => dep/jemalloc/base.c rename : externals/jemalloc/chunk.c => dep/jemalloc/chunk.c rename : externals/jemalloc/chunk_dss.c => dep/jemalloc/chunk_dss.c rename : externals/jemalloc/chunk_mmap.c => dep/jemalloc/chunk_mmap.c rename : externals/jemalloc/chunk_swap.c => dep/jemalloc/chunk_swap.c rename : externals/jemalloc/ckh.c => dep/jemalloc/ckh.c rename : externals/jemalloc/ctl.c => dep/jemalloc/ctl.c rename : externals/jemalloc/extent.c => dep/jemalloc/extent.c rename : externals/jemalloc/hash.c => dep/jemalloc/hash.c rename : externals/jemalloc/huge.c => dep/jemalloc/huge.c rename : externals/jemalloc/jemalloc.c => dep/jemalloc/jemalloc.c rename : externals/jemalloc/jemalloc/internal/arena.h => dep/jemalloc/jemalloc/internal/arena.h rename : externals/jemalloc/jemalloc/internal/base.h => dep/jemalloc/jemalloc/internal/base.h rename : externals/jemalloc/jemalloc/internal/chunk.h => dep/jemalloc/jemalloc/internal/chunk.h rename : externals/jemalloc/jemalloc/internal/chunk_dss.h => dep/jemalloc/jemalloc/internal/chunk_dss.h rename : externals/jemalloc/jemalloc/internal/chunk_mmap.h => dep/jemalloc/jemalloc/internal/chunk_mmap.h rename : externals/jemalloc/jemalloc/internal/chunk_swap.h => dep/jemalloc/jemalloc/internal/chunk_swap.h rename : externals/jemalloc/jemalloc/internal/ckh.h => dep/jemalloc/jemalloc/internal/ckh.h rename : externals/jemalloc/jemalloc/internal/ctl.h => dep/jemalloc/jemalloc/internal/ctl.h rename : externals/jemalloc/jemalloc/internal/extent.h => dep/jemalloc/jemalloc/internal/extent.h rename : externals/jemalloc/jemalloc/internal/hash.h => dep/jemalloc/jemalloc/internal/hash.h rename : externals/jemalloc/jemalloc/internal/huge.h => dep/jemalloc/jemalloc/internal/huge.h rename : externals/jemalloc/jemalloc/internal/jemalloc_internal.h => dep/jemalloc/jemalloc/internal/jemalloc_internal.h rename : externals/jemalloc/jemalloc/internal/jemalloc_internal.h.in => dep/jemalloc/jemalloc/internal/jemalloc_internal.h.in rename : externals/jemalloc/jemalloc/internal/mb.h => dep/jemalloc/jemalloc/internal/mb.h rename : externals/jemalloc/jemalloc/internal/mutex.h => dep/jemalloc/jemalloc/internal/mutex.h rename : externals/jemalloc/jemalloc/internal/prof.h => dep/jemalloc/jemalloc/internal/prof.h rename : externals/jemalloc/jemalloc/internal/ql.h => dep/jemalloc/jemalloc/internal/ql.h rename : externals/jemalloc/jemalloc/internal/qr.h => dep/jemalloc/jemalloc/internal/qr.h rename : externals/jemalloc/jemalloc/internal/rb.h => dep/jemalloc/jemalloc/internal/rb.h rename : externals/jemalloc/jemalloc/internal/stats.h => dep/jemalloc/jemalloc/internal/stats.h rename : externals/jemalloc/jemalloc/internal/tcache.h => dep/jemalloc/jemalloc/internal/tcache.h rename : externals/jemalloc/jemalloc/internal/totally_not_p_r_n.h => dep/jemalloc/jemalloc/internal/totally_not_p_r_n.h rename : externals/jemalloc/jemalloc/jemalloc.h => dep/jemalloc/jemalloc/jemalloc.h rename : externals/jemalloc/jemalloc/jemalloc.h.in => dep/jemalloc/jemalloc/jemalloc.h.in rename : externals/jemalloc/jemalloc/jemalloc_defs.h => dep/jemalloc/jemalloc/jemalloc_defs.h rename : externals/jemalloc/jemalloc/jemalloc_defs.h.in => dep/jemalloc/jemalloc/jemalloc_defs.h.in rename : externals/jemalloc/mb.c => dep/jemalloc/mb.c rename : externals/jemalloc/mutex.c => dep/jemalloc/mutex.c rename : externals/jemalloc/prof.c => dep/jemalloc/prof.c rename : externals/jemalloc/stats.c => dep/jemalloc/stats.c rename : externals/jemalloc/tcache.c => dep/jemalloc/tcache.c rename : externals/libmpq/AUTHORS => dep/libmpq/AUTHORS rename : externals/libmpq/CMakeLists.txt => dep/libmpq/CMakeLists.txt rename : externals/libmpq/COPYING => dep/libmpq/COPYING rename : externals/libmpq/FAQ => dep/libmpq/FAQ rename : externals/libmpq/INSTALL => dep/libmpq/INSTALL rename : externals/libmpq/Makefile.am => dep/libmpq/Makefile.am rename : externals/libmpq/NEWS => dep/libmpq/NEWS rename : externals/libmpq/README => dep/libmpq/README rename : externals/libmpq/THANKS => dep/libmpq/THANKS rename : externals/libmpq/TODO => dep/libmpq/TODO rename : externals/libmpq/autogen.sh => dep/libmpq/autogen.sh rename : externals/libmpq/bindings/Makefile.am => dep/libmpq/bindings/Makefile.am rename : externals/libmpq/bindings/d/Makefile.am => dep/libmpq/bindings/d/Makefile.am rename : externals/libmpq/bindings/d/dsss.conf => dep/libmpq/bindings/d/dsss.conf rename : externals/libmpq/bindings/d/mpq.d => dep/libmpq/bindings/d/mpq.d rename : externals/libmpq/bindings/python/Makefile.am => dep/libmpq/bindings/python/Makefile.am rename : externals/libmpq/bindings/python/mpq-info => dep/libmpq/bindings/python/mpq-info rename : externals/libmpq/bindings/python/mpq.py => dep/libmpq/bindings/python/mpq.py rename : externals/libmpq/config.h => dep/libmpq/config.h rename : externals/libmpq/configure.ac => dep/libmpq/configure.ac rename : externals/libmpq/debian/changelog => dep/libmpq/debian/changelog rename : externals/libmpq/debian/compat => dep/libmpq/debian/compat rename : externals/libmpq/debian/control => dep/libmpq/debian/control rename : externals/libmpq/debian/copyright => dep/libmpq/debian/copyright rename : externals/libmpq/debian/libmpq-dev.dirs => dep/libmpq/debian/libmpq-dev.dirs rename : externals/libmpq/debian/libmpq-dev.install => dep/libmpq/debian/libmpq-dev.install rename : externals/libmpq/debian/libmpq0.dirs => dep/libmpq/debian/libmpq0.dirs rename : externals/libmpq/debian/libmpq0.docs => dep/libmpq/debian/libmpq0.docs rename : externals/libmpq/debian/libmpq0.install => dep/libmpq/debian/libmpq0.install rename : externals/libmpq/debian/python-mpq.install => dep/libmpq/debian/python-mpq.install rename : externals/libmpq/debian/rules => dep/libmpq/debian/rules rename : externals/libmpq/doc/Makefile.am => dep/libmpq/doc/Makefile.am rename : externals/libmpq/doc/man1/Makefile.am => dep/libmpq/doc/man1/Makefile.am rename : externals/libmpq/doc/man1/libmpq-config.1 => dep/libmpq/doc/man1/libmpq-config.1 rename : externals/libmpq/doc/man3/Makefile.am => dep/libmpq/doc/man3/Makefile.am rename : externals/libmpq/doc/man3/libmpq.3 => dep/libmpq/doc/man3/libmpq.3 rename : externals/libmpq/doc/man3/libmpq__archive_close.3 => dep/libmpq/doc/man3/libmpq__archive_close.3 rename : externals/libmpq/doc/man3/libmpq__archive_files.3 => dep/libmpq/doc/man3/libmpq__archive_files.3 rename : externals/libmpq/doc/man3/libmpq__archive_offset.3 => dep/libmpq/doc/man3/libmpq__archive_offset.3 rename : externals/libmpq/doc/man3/libmpq__archive_open.3 => dep/libmpq/doc/man3/libmpq__archive_open.3 rename : externals/libmpq/doc/man3/libmpq__archive_packed_size.3 => dep/libmpq/doc/man3/libmpq__archive_packed_size.3 rename : externals/libmpq/doc/man3/libmpq__archive_unpacked_size.3 => dep/libmpq/doc/man3/libmpq__archive_unpacked_size.3 rename : externals/libmpq/doc/man3/libmpq__archive_version.3 => dep/libmpq/doc/man3/libmpq__archive_version.3 rename : externals/libmpq/doc/man3/libmpq__block_close_offset.3 => dep/libmpq/doc/man3/libmpq__block_close_offset.3 rename : externals/libmpq/doc/man3/libmpq__block_open_offset.3 => dep/libmpq/doc/man3/libmpq__block_open_offset.3 rename : externals/libmpq/doc/man3/libmpq__block_read.3 => dep/libmpq/doc/man3/libmpq__block_read.3 rename : externals/libmpq/doc/man3/libmpq__block_unpacked_size.3 => dep/libmpq/doc/man3/libmpq__block_unpacked_size.3 rename : externals/libmpq/doc/man3/libmpq__file_blocks.3 => dep/libmpq/doc/man3/libmpq__file_blocks.3 rename : externals/libmpq/doc/man3/libmpq__file_compressed.3 => dep/libmpq/doc/man3/libmpq__file_compressed.3 rename : externals/libmpq/doc/man3/libmpq__file_encrypted.3 => dep/libmpq/doc/man3/libmpq__file_encrypted.3 rename : externals/libmpq/doc/man3/libmpq__file_imploded.3 => dep/libmpq/doc/man3/libmpq__file_imploded.3 rename : externals/libmpq/doc/man3/libmpq__file_number.3 => dep/libmpq/doc/man3/libmpq__file_number.3 rename : externals/libmpq/doc/man3/libmpq__file_offset.3 => dep/libmpq/doc/man3/libmpq__file_offset.3 rename : externals/libmpq/doc/man3/libmpq__file_packed_size.3 => dep/libmpq/doc/man3/libmpq__file_packed_size.3 rename : externals/libmpq/doc/man3/libmpq__file_read.3 => dep/libmpq/doc/man3/libmpq__file_read.3 rename : externals/libmpq/doc/man3/libmpq__file_unpacked_size.3 => dep/libmpq/doc/man3/libmpq__file_unpacked_size.3 rename : externals/libmpq/doc/man3/libmpq__strerror.3 => dep/libmpq/doc/man3/libmpq__strerror.3 rename : externals/libmpq/doc/man3/libmpq__version.3 => dep/libmpq/doc/man3/libmpq__version.3 rename : externals/libmpq/libmpq-config.in => dep/libmpq/libmpq-config.in rename : externals/libmpq/libmpq.pc.in => dep/libmpq/libmpq.pc.in rename : externals/libmpq/libmpq/Makefile.am => dep/libmpq/libmpq/Makefile.am rename : externals/libmpq/libmpq/common.c => dep/libmpq/libmpq/common.c rename : externals/libmpq/libmpq/common.h => dep/libmpq/libmpq/common.h rename : externals/libmpq/libmpq/crypt_buf.h => dep/libmpq/libmpq/crypt_buf.h rename : externals/libmpq/libmpq/explode.c => dep/libmpq/libmpq/explode.c rename : externals/libmpq/libmpq/explode.h => dep/libmpq/libmpq/explode.h rename : externals/libmpq/libmpq/extract.c => dep/libmpq/libmpq/extract.c rename : externals/libmpq/libmpq/extract.h => dep/libmpq/libmpq/extract.h rename : externals/libmpq/libmpq/huffman.c => dep/libmpq/libmpq/huffman.c rename : externals/libmpq/libmpq/huffman.h => dep/libmpq/libmpq/huffman.h rename : externals/libmpq/libmpq/mpq-internal.h => dep/libmpq/libmpq/mpq-internal.h rename : externals/libmpq/libmpq/mpq.c => dep/libmpq/libmpq/mpq.c rename : externals/libmpq/libmpq/mpq.h => dep/libmpq/libmpq/mpq.h rename : externals/libmpq/libmpq/pack_begin.h => dep/libmpq/libmpq/pack_begin.h rename : externals/libmpq/libmpq/pack_end.h => dep/libmpq/libmpq/pack_end.h rename : externals/libmpq/libmpq/platform.h => dep/libmpq/libmpq/platform.h rename : externals/libmpq/libmpq/wave.c => dep/libmpq/libmpq/wave.c rename : externals/libmpq/libmpq/wave.h => dep/libmpq/libmpq/wave.h rename : externals/libmpq/tools/Makefile.am => dep/libmpq/tools/Makefile.am rename : externals/libmpq/tools/crypt_buf_gen.c => dep/libmpq/tools/crypt_buf_gen.c rename : externals/libmpq/win/config.h => dep/libmpq/win/config.h rename : externals/libmpq/win/dirent.h => dep/libmpq/win/dirent.h rename : externals/libmpq/win/stdint.h => dep/libmpq/win/stdint.h rename : externals/mersennetwister/MersenneTwister.h => dep/mersennetwister/MersenneTwister.h rename : externals/sockets/Base64.cpp => dep/sockets/Base64.cpp rename : externals/sockets/CMakeLists.txt => dep/sockets/CMakeLists.txt rename : externals/sockets/Exception.cpp => dep/sockets/Exception.cpp rename : externals/sockets/Ipv4Address.cpp => dep/sockets/Ipv4Address.cpp rename : externals/sockets/Ipv6Address.cpp => dep/sockets/Ipv6Address.cpp rename : externals/sockets/Lock.cpp => dep/sockets/Lock.cpp rename : externals/sockets/Makefile => dep/sockets/Makefile rename : externals/sockets/Mutex.cpp => dep/sockets/Mutex.cpp rename : externals/sockets/Parse.cpp => dep/sockets/Parse.cpp rename : externals/sockets/ResolvServer.cpp => dep/sockets/ResolvServer.cpp rename : externals/sockets/ResolvSocket.cpp => dep/sockets/ResolvSocket.cpp rename : externals/sockets/Socket.cpp => dep/sockets/Socket.cpp rename : externals/sockets/SocketHandler.cpp => dep/sockets/SocketHandler.cpp rename : externals/sockets/StdoutLog.cpp => dep/sockets/StdoutLog.cpp rename : externals/sockets/StreamSocket.cpp => dep/sockets/StreamSocket.cpp rename : externals/sockets/TcpSocket.cpp => dep/sockets/TcpSocket.cpp rename : externals/sockets/Thread.cpp => dep/sockets/Thread.cpp rename : externals/sockets/UdpSocket.cpp => dep/sockets/UdpSocket.cpp rename : externals/sockets/Utility.cpp => dep/sockets/Utility.cpp rename : externals/sockets/include/Base64.h => dep/sockets/include/Base64.h rename : externals/sockets/include/Exception.h => dep/sockets/include/Exception.h rename : externals/sockets/include/File.h => dep/sockets/include/File.h rename : externals/sockets/include/IFile.h => dep/sockets/include/IFile.h rename : externals/sockets/include/ISocketHandler.h => dep/sockets/include/ISocketHandler.h rename : externals/sockets/include/Ipv4Address.h => dep/sockets/include/Ipv4Address.h rename : externals/sockets/include/Ipv6Address.h => dep/sockets/include/Ipv6Address.h rename : externals/sockets/include/ListenSocket.h => dep/sockets/include/ListenSocket.h rename : externals/sockets/include/Lock.h => dep/sockets/include/Lock.h rename : externals/sockets/include/Mutex.h => dep/sockets/include/Mutex.h rename : externals/sockets/include/Parse.h => dep/sockets/include/Parse.h rename : externals/sockets/include/ResolvServer.h => dep/sockets/include/ResolvServer.h rename : externals/sockets/include/ResolvSocket.h => dep/sockets/include/ResolvSocket.h rename : externals/sockets/include/SctpSocket.h => dep/sockets/include/SctpSocket.h rename : externals/sockets/include/Socket.h => dep/sockets/include/Socket.h rename : externals/sockets/include/SocketAddress.h => dep/sockets/include/SocketAddress.h rename : externals/sockets/include/SocketHandler.h => dep/sockets/include/SocketHandler.h rename : externals/sockets/include/StdLog.h => dep/sockets/include/StdLog.h rename : externals/sockets/include/StdoutLog.h => dep/sockets/include/StdoutLog.h rename : externals/sockets/include/StreamSocket.h => dep/sockets/include/StreamSocket.h rename : externals/sockets/include/TcpSocket.h => dep/sockets/include/TcpSocket.h rename : externals/sockets/include/Thread.h => dep/sockets/include/Thread.h rename : externals/sockets/include/UdpSocket.h => dep/sockets/include/UdpSocket.h rename : externals/sockets/include/Utility.h => dep/sockets/include/Utility.h rename : externals/sockets/include/socket_include.h => dep/sockets/include/socket_include.h rename : externals/sockets/include/sockets-config.h => dep/sockets/include/sockets-config.h rename : externals/sockets/network_kist.txt => dep/sockets/network_kist.txt rename : externals/sockets/socket_include.cpp => dep/sockets/socket_include.cpp rename : externals/utf8cpp/utf8.h => dep/utf8cpp/utf8.h rename : externals/utf8cpp/utf8/checked.h => dep/utf8cpp/utf8/checked.h rename : externals/utf8cpp/utf8/core.h => dep/utf8cpp/utf8/core.h rename : externals/utf8cpp/utf8/unchecked.h => dep/utf8cpp/utf8/unchecked.h rename : externals/zlib/CMakeLists.txt => dep/zlib/CMakeLists.txt rename : externals/zlib/adler32.c => dep/zlib/adler32.c rename : externals/zlib/compress.c => dep/zlib/compress.c rename : externals/zlib/crc32.c => dep/zlib/crc32.c rename : externals/zlib/crc32.h => dep/zlib/crc32.h rename : externals/zlib/deflate.c => dep/zlib/deflate.c rename : externals/zlib/deflate.h => dep/zlib/deflate.h rename : externals/zlib/example.c => dep/zlib/example.c rename : externals/zlib/gzclose.c => dep/zlib/gzclose.c rename : externals/zlib/gzguts.h => dep/zlib/gzguts.h rename : externals/zlib/gzlib.c => dep/zlib/gzlib.c rename : externals/zlib/gzread.c => dep/zlib/gzread.c rename : externals/zlib/gzwrite.c => dep/zlib/gzwrite.c rename : externals/zlib/infback.c => dep/zlib/infback.c rename : externals/zlib/inffast.c => dep/zlib/inffast.c rename : externals/zlib/inffast.h => dep/zlib/inffast.h rename : externals/zlib/inffixed.h => dep/zlib/inffixed.h rename : externals/zlib/inflate.c => dep/zlib/inflate.c rename : externals/zlib/inflate.h => dep/zlib/inflate.h rename : externals/zlib/inftrees.c => dep/zlib/inftrees.c rename : externals/zlib/inftrees.h => dep/zlib/inftrees.h rename : externals/zlib/minigzip.c => dep/zlib/minigzip.c rename : externals/zlib/trees.c => dep/zlib/trees.c rename : externals/zlib/trees.h => dep/zlib/trees.h rename : externals/zlib/uncompr.c => dep/zlib/uncompr.c rename : externals/zlib/zconf.h => dep/zlib/zconf.h rename : externals/zlib/zlib.h => dep/zlib/zlib.h rename : externals/zlib/zutil.c => dep/zlib/zutil.c rename : externals/zlib/zutil.h => dep/zlib/zutil.h rename : docs/AuctionHouseBot.txt => doc/AuctionHouseBot.txt rename : docs/EventAI.txt => doc/EventAI.txt rename : docs/HowToScript.txt => doc/HowToScript.txt rename : docs/TextTables.txt => doc/TextTables.txt rename : docs/UnixInstall.txt => doc/UnixInstall.txt rename : docs/gpl-2.0.txt => doc/gpl-2.0.txt --- CMakeLists.txt | 4 +- dep/CMakeLists.txt | 28 + dep/PackageList.txt | 45 + dep/SFMT/SFMT-alti.h | 156 + dep/SFMT/SFMT-params.h | 97 + dep/SFMT/SFMT-sse2.h | 121 + dep/SFMT/SFMT.c | 620 + dep/SFMT/SFMT.h | 157 + dep/acelite/CMakeLists.txt | 1 + dep/acelite/ace/ACE.cpp | 3517 +++++ dep/acelite/ace/ACE.h | 849 ++ dep/acelite/ace/ACE.inl | 348 + dep/acelite/ace/ACE.pc.in | 10 + dep/acelite/ace/ACE_crc32.cpp | 161 + dep/acelite/ace/ACE_crc_ccitt.cpp | 128 + dep/acelite/ace/ACE_export.h | 76 + dep/acelite/ace/ARGV.cpp | 383 + dep/acelite/ace/ARGV.h | 333 + dep/acelite/ace/ARGV.inl | 104 + dep/acelite/ace/ATM_Acceptor.cpp | 309 + dep/acelite/ace/ATM_Acceptor.h | 123 + dep/acelite/ace/ATM_Acceptor.inl | 43 + dep/acelite/ace/ATM_Addr.cpp | 522 + dep/acelite/ace/ATM_Addr.h | 197 + dep/acelite/ace/ATM_Addr.inl | 37 + dep/acelite/ace/ATM_Connector.cpp | 138 + dep/acelite/ace/ATM_Connector.h | 164 + dep/acelite/ace/ATM_Connector.inl | 132 + dep/acelite/ace/ATM_Params.cpp | 20 + dep/acelite/ace/ATM_Params.h | 214 + dep/acelite/ace/ATM_Params.inl | 235 + dep/acelite/ace/ATM_QoS.cpp | 631 + dep/acelite/ace/ATM_QoS.h | 115 + dep/acelite/ace/ATM_QoS.inl | 29 + dep/acelite/ace/ATM_Stream.cpp | 290 + dep/acelite/ace/ATM_Stream.h | 107 + dep/acelite/ace/ATM_Stream.inl | 133 + dep/acelite/ace/Acceptor.cpp | 1246 ++ dep/acelite/ace/Acceptor.h | 695 + dep/acelite/ace/Activation_Queue.cpp | 138 + dep/acelite/ace/Activation_Queue.h | 168 + dep/acelite/ace/Activation_Queue.inl | 31 + dep/acelite/ace/Active_Map_Manager.cpp | 9 + dep/acelite/ace/Active_Map_Manager.h | 116 + dep/acelite/ace/Active_Map_Manager.inl | 95 + dep/acelite/ace/Active_Map_Manager_T.cpp | 22 + dep/acelite/ace/Active_Map_Manager_T.h | 211 + dep/acelite/ace/Active_Map_Manager_T.inl | 311 + dep/acelite/ace/Addr.cpp | 71 + dep/acelite/ace/Addr.h | 103 + dep/acelite/ace/Addr.inl | 57 + dep/acelite/ace/Arg_Shifter.cpp | 229 + dep/acelite/ace/Arg_Shifter.h | 221 + dep/acelite/ace/Argv_Type_Converter.cpp | 196 + dep/acelite/ace/Argv_Type_Converter.h | 119 + dep/acelite/ace/Argv_Type_Converter.inl | 44 + dep/acelite/ace/Array.h | 29 + dep/acelite/ace/Array_Base.cpp | 235 + dep/acelite/ace/Array_Base.h | 256 + dep/acelite/ace/Array_Base.inl | 146 + dep/acelite/ace/Array_Map.cpp | 299 + dep/acelite/ace/Array_Map.h | 300 + dep/acelite/ace/Array_Map.inl | 133 + dep/acelite/ace/Assert.cpp | 24 + dep/acelite/ace/Assert.h | 40 + dep/acelite/ace/Asynch_Acceptor.cpp | 514 + dep/acelite/ace/Asynch_Acceptor.h | 281 + dep/acelite/ace/Asynch_Connector.cpp | 296 + dep/acelite/ace/Asynch_Connector.h | 171 + dep/acelite/ace/Asynch_IO.cpp | 1414 ++ dep/acelite/ace/Asynch_IO.h | 1761 +++ dep/acelite/ace/Asynch_IO_Impl.cpp | 117 + dep/acelite/ace/Asynch_IO_Impl.h | 816 + dep/acelite/ace/Asynch_IO_Impl.inl | 106 + dep/acelite/ace/Asynch_Pseudo_Task.cpp | 130 + dep/acelite/ace/Asynch_Pseudo_Task.h | 73 + dep/acelite/ace/Atomic_Op.cpp | 310 + dep/acelite/ace/Atomic_Op.h | 355 + dep/acelite/ace/Atomic_Op.inl | 582 + dep/acelite/ace/Atomic_Op_GCC_T.cpp | 29 + dep/acelite/ace/Atomic_Op_GCC_T.h | 136 + dep/acelite/ace/Atomic_Op_GCC_T.inl | 148 + dep/acelite/ace/Atomic_Op_Sparc.c | 187 + dep/acelite/ace/Atomic_Op_Sparc.h | 14 + dep/acelite/ace/Atomic_Op_T.cpp | 82 + dep/acelite/ace/Atomic_Op_T.h | 369 + dep/acelite/ace/Atomic_Op_T.inl | 340 + dep/acelite/ace/Auto_Event.cpp | 49 + dep/acelite/ace/Auto_Event.h | 73 + dep/acelite/ace/Auto_Event.inl | 12 + dep/acelite/ace/Auto_Functor.cpp | 39 + dep/acelite/ace/Auto_Functor.h | 127 + dep/acelite/ace/Auto_Functor.inl | 134 + dep/acelite/ace/Auto_IncDec_T.cpp | 34 + dep/acelite/ace/Auto_IncDec_T.h | 91 + dep/acelite/ace/Auto_IncDec_T.inl | 25 + dep/acelite/ace/Auto_Ptr.cpp | 21 + dep/acelite/ace/Auto_Ptr.h | 242 + dep/acelite/ace/Auto_Ptr.inl | 171 + dep/acelite/ace/Barrier.cpp | 196 + dep/acelite/ace/Barrier.h | 215 + dep/acelite/ace/Barrier.inl | 22 + dep/acelite/ace/Base_Thread_Adapter.cpp | 128 + dep/acelite/ace/Base_Thread_Adapter.h | 195 + dep/acelite/ace/Base_Thread_Adapter.inl | 48 + dep/acelite/ace/Based_Pointer_Repository.cpp | 119 + dep/acelite/ace/Based_Pointer_Repository.h | 94 + dep/acelite/ace/Based_Pointer_T.cpp | 121 + dep/acelite/ace/Based_Pointer_T.h | 205 + dep/acelite/ace/Based_Pointer_T.inl | 139 + dep/acelite/ace/Basic_Stats.cpp | 78 + dep/acelite/ace/Basic_Stats.h | 87 + dep/acelite/ace/Basic_Stats.inl | 53 + dep/acelite/ace/Basic_Types.cpp | 139 + dep/acelite/ace/Basic_Types.h | 962 ++ dep/acelite/ace/Basic_Types.inl | 954 ++ dep/acelite/ace/Bound_Ptr.h | 388 + dep/acelite/ace/Bound_Ptr.inl | 494 + dep/acelite/ace/CDR_Base.cpp | 802 + dep/acelite/ace/CDR_Base.h | 382 + dep/acelite/ace/CDR_Base.inl | 255 + dep/acelite/ace/CDR_Size.cpp | 262 + dep/acelite/ace/CDR_Size.h | 241 + dep/acelite/ace/CDR_Size.inl | 424 + dep/acelite/ace/CDR_Stream.cpp | 2063 +++ dep/acelite/ace/CDR_Stream.h | 1402 ++ dep/acelite/ace/CDR_Stream.inl | 1727 +++ dep/acelite/ace/CE_Screen_Output.cpp | 158 + dep/acelite/ace/CE_Screen_Output.h | 109 + dep/acelite/ace/CMakeLists.txt | 337 + dep/acelite/ace/CORBA_macros.h | 575 + dep/acelite/ace/Cache_Map_Manager_T.cpp | 420 + dep/acelite/ace/Cache_Map_Manager_T.h | 405 + dep/acelite/ace/Cache_Map_Manager_T.inl | 245 + dep/acelite/ace/Cached_Connect_Strategy_T.cpp | 734 + dep/acelite/ace/Cached_Connect_Strategy_T.h | 263 + dep/acelite/ace/Caching_Strategies_T.cpp | 59 + dep/acelite/ace/Caching_Strategies_T.h | 552 + dep/acelite/ace/Caching_Strategies_T.inl | 456 + dep/acelite/ace/Caching_Utility_T.cpp | 499 + dep/acelite/ace/Caching_Utility_T.h | 347 + dep/acelite/ace/Capabilities.cpp | 355 + dep/acelite/ace/Capabilities.h | 221 + dep/acelite/ace/Capabilities.inl | 52 + dep/acelite/ace/Cleanup.cpp | 181 + dep/acelite/ace/Cleanup.h | 160 + dep/acelite/ace/Cleanup.inl | 30 + dep/acelite/ace/Cleanup_Strategies_T.cpp | 95 + dep/acelite/ace/Cleanup_Strategies_T.h | 149 + dep/acelite/ace/Codecs.cpp | 234 + dep/acelite/ace/Codecs.h | 121 + dep/acelite/ace/Codeset_IBM1047.cpp | 309 + dep/acelite/ace/Codeset_IBM1047.h | 127 + dep/acelite/ace/Codeset_Registry.cpp | 111 + dep/acelite/ace/Codeset_Registry.h | 104 + dep/acelite/ace/Codeset_Registry.inl | 102 + dep/acelite/ace/Codeset_Registry_db.cpp | 33 + dep/acelite/ace/Codeset_Symbols.h | 220 + .../ace/Condition_Recursive_Thread_Mutex.cpp | 129 + dep/acelite/ace/Condition_Recursive_Thread_Mutex.h | 116 + dep/acelite/ace/Condition_T.cpp | 127 + dep/acelite/ace/Condition_T.h | 167 + dep/acelite/ace/Condition_T.inl | 51 + dep/acelite/ace/Condition_Thread_Mutex.cpp | 126 + dep/acelite/ace/Condition_Thread_Mutex.h | 190 + dep/acelite/ace/Condition_Thread_Mutex.inl | 74 + dep/acelite/ace/Configuration.cpp | 2152 +++ dep/acelite/ace/Configuration.h | 919 ++ dep/acelite/ace/Configuration.inl | 13 + dep/acelite/ace/Configuration_Import_Export.cpp | 670 + dep/acelite/ace/Configuration_Import_Export.h | 215 + dep/acelite/ace/Connection_Recycling_Strategy.cpp | 13 + dep/acelite/ace/Connection_Recycling_Strategy.h | 63 + dep/acelite/ace/Connector.cpp | 991 ++ dep/acelite/ace/Connector.h | 569 + dep/acelite/ace/Containers.cpp | 12 + dep/acelite/ace/Containers.h | 71 + dep/acelite/ace/Containers.inl | 25 + dep/acelite/ace/Containers_T.cpp | 1932 +++ dep/acelite/ace/Containers_T.h | 2068 +++ dep/acelite/ace/Containers_T.inl | 479 + dep/acelite/ace/Copy_Disabled.cpp | 23 + dep/acelite/ace/Copy_Disabled.h | 65 + dep/acelite/ace/Countdown_Time.cpp | 59 + dep/acelite/ace/Countdown_Time.h | 81 + dep/acelite/ace/Countdown_Time.inl | 20 + dep/acelite/ace/DEV.cpp | 43 + dep/acelite/ace/DEV.h | 78 + dep/acelite/ace/DEV.inl | 18 + dep/acelite/ace/DEV_Addr.cpp | 108 + dep/acelite/ace/DEV_Addr.h | 90 + dep/acelite/ace/DEV_Addr.inl | 51 + dep/acelite/ace/DEV_Connector.cpp | 53 + dep/acelite/ace/DEV_Connector.h | 110 + dep/acelite/ace/DEV_Connector.inl | 33 + dep/acelite/ace/DEV_IO.cpp | 131 + dep/acelite/ace/DEV_IO.h | 185 + dep/acelite/ace/DEV_IO.inl | 126 + dep/acelite/ace/DLL.cpp | 267 + dep/acelite/ace/DLL.h | 196 + dep/acelite/ace/DLL_Manager.cpp | 787 + dep/acelite/ace/DLL_Manager.h | 269 + dep/acelite/ace/Date_Time.cpp | 10 + dep/acelite/ace/Date_Time.h | 125 + dep/acelite/ace/Date_Time.inl | 219 + dep/acelite/ace/Default_Constants.h | 605 + dep/acelite/ace/Dev_Poll_Reactor.cpp | 2610 ++++ dep/acelite/ace/Dev_Poll_Reactor.h | 1208 ++ dep/acelite/ace/Dev_Poll_Reactor.inl | 134 + dep/acelite/ace/Dirent.cpp | 7 + dep/acelite/ace/Dirent.h | 122 + dep/acelite/ace/Dirent.inl | 99 + dep/acelite/ace/Dirent_Selector.cpp | 59 + dep/acelite/ace/Dirent_Selector.h | 75 + dep/acelite/ace/Dirent_Selector.inl | 19 + dep/acelite/ace/Dump.cpp | 141 + dep/acelite/ace/Dump.h | 172 + dep/acelite/ace/Dump_T.cpp | 48 + dep/acelite/ace/Dump_T.h | 83 + dep/acelite/ace/Dynamic.cpp | 34 + dep/acelite/ace/Dynamic.h | 75 + dep/acelite/ace/Dynamic.inl | 34 + dep/acelite/ace/Dynamic_Message_Strategy.cpp | 205 + dep/acelite/ace/Dynamic_Message_Strategy.h | 217 + dep/acelite/ace/Dynamic_Message_Strategy.inl | 75 + dep/acelite/ace/Dynamic_Service.cpp | 63 + dep/acelite/ace/Dynamic_Service.h | 89 + dep/acelite/ace/Dynamic_Service.inl | 39 + dep/acelite/ace/Dynamic_Service_Base.cpp | 106 + dep/acelite/ace/Dynamic_Service_Base.h | 73 + dep/acelite/ace/Dynamic_Service_Dependency.cpp | 51 + dep/acelite/ace/Dynamic_Service_Dependency.h | 70 + dep/acelite/ace/Encoding_Converter.cpp | 12 + dep/acelite/ace/Encoding_Converter.h | 70 + dep/acelite/ace/Encoding_Converter_Factory.cpp | 74 + dep/acelite/ace/Encoding_Converter_Factory.h | 54 + dep/acelite/ace/Env_Value_T.cpp | 12 + dep/acelite/ace/Env_Value_T.h | 166 + dep/acelite/ace/Env_Value_T.inl | 60 + dep/acelite/ace/Event.cpp | 93 + dep/acelite/ace/Event.h | 143 + dep/acelite/ace/Event.inl | 18 + dep/acelite/ace/Event_Handler.cpp | 394 + dep/acelite/ace/Event_Handler.h | 389 + dep/acelite/ace/Event_Handler.inl | 12 + dep/acelite/ace/Event_Handler_T.cpp | 125 + dep/acelite/ace/Event_Handler_T.h | 191 + dep/acelite/ace/Event_Handler_T.inl | 135 + dep/acelite/ace/Exception_Macros.h | 55 + dep/acelite/ace/FIFO.cpp | 78 + dep/acelite/ace/FIFO.h | 85 + dep/acelite/ace/FIFO.inl | 25 + dep/acelite/ace/FIFO_Recv.cpp | 88 + dep/acelite/ace/FIFO_Recv.h | 85 + dep/acelite/ace/FIFO_Recv.inl | 24 + dep/acelite/ace/FIFO_Recv_Msg.cpp | 67 + dep/acelite/ace/FIFO_Recv_Msg.h | 138 + dep/acelite/ace/FIFO_Recv_Msg.inl | 137 + dep/acelite/ace/FIFO_Send.cpp | 58 + dep/acelite/ace/FIFO_Send.h | 75 + dep/acelite/ace/FIFO_Send.inl | 24 + dep/acelite/ace/FIFO_Send_Msg.cpp | 80 + dep/acelite/ace/FIFO_Send_Msg.h | 91 + dep/acelite/ace/FIFO_Send_Msg.inl | 53 + dep/acelite/ace/FILE.cpp | 147 + dep/acelite/ace/FILE.h | 139 + dep/acelite/ace/FILE.inl | 18 + dep/acelite/ace/FILE_Addr.cpp | 124 + dep/acelite/ace/FILE_Addr.h | 89 + dep/acelite/ace/FILE_Addr.inl | 34 + dep/acelite/ace/FILE_Connector.cpp | 84 + dep/acelite/ace/FILE_Connector.h | 113 + dep/acelite/ace/FILE_Connector.inl | 35 + dep/acelite/ace/FILE_IO.cpp | 145 + dep/acelite/ace/FILE_IO.h | 170 + dep/acelite/ace/FILE_IO.inl | 152 + dep/acelite/ace/File_Lock.cpp | 72 + dep/acelite/ace/File_Lock.h | 170 + dep/acelite/ace/File_Lock.inl | 96 + dep/acelite/ace/Filecache.cpp | 746 + dep/acelite/ace/Filecache.h | 356 + dep/acelite/ace/Flag_Manip.cpp | 95 + dep/acelite/ace/Flag_Manip.h | 58 + dep/acelite/ace/Flag_Manip.inl | 26 + dep/acelite/ace/Framework_Component.cpp | 279 + dep/acelite/ace/Framework_Component.h | 210 + dep/acelite/ace/Framework_Component.inl | 39 + dep/acelite/ace/Framework_Component_T.cpp | 33 + dep/acelite/ace/Framework_Component_T.h | 71 + dep/acelite/ace/Free_List.cpp | 163 + dep/acelite/ace/Free_List.h | 150 + dep/acelite/ace/Functor.cpp | 43 + dep/acelite/ace/Functor.h | 523 + dep/acelite/ace/Functor.inl | 284 + dep/acelite/ace/Functor_String.cpp | 7 + dep/acelite/ace/Functor_String.h | 129 + dep/acelite/ace/Functor_String.inl | 56 + dep/acelite/ace/Functor_T.cpp | 49 + dep/acelite/ace/Functor_T.h | 158 + dep/acelite/ace/Functor_T.inl | 42 + dep/acelite/ace/Future.cpp | 434 + dep/acelite/ace/Future.h | 387 + dep/acelite/ace/Future_Set.cpp | 136 + dep/acelite/ace/Future_Set.h | 146 + dep/acelite/ace/Get_Opt.cpp | 734 + dep/acelite/ace/Get_Opt.h | 494 + dep/acelite/ace/Get_Opt.inl | 97 + dep/acelite/ace/Global_Macros.h | 1121 ++ dep/acelite/ace/Guard_T.cpp | 61 + dep/acelite/ace/Guard_T.h | 365 + dep/acelite/ace/Guard_T.inl | 170 + dep/acelite/ace/Handle_Gobbler.h | 68 + dep/acelite/ace/Handle_Gobbler.inl | 79 + dep/acelite/ace/Handle_Ops.cpp | 48 + dep/acelite/ace/Handle_Ops.h | 50 + dep/acelite/ace/Handle_Set.cpp | 565 + dep/acelite/ace/Handle_Set.h | 236 + dep/acelite/ace/Handle_Set.inl | 193 + dep/acelite/ace/Hash_Cache_Map_Manager_T.cpp | 232 + dep/acelite/ace/Hash_Cache_Map_Manager_T.h | 214 + dep/acelite/ace/Hash_Cache_Map_Manager_T.inl | 73 + dep/acelite/ace/Hash_Map_Manager.h | 31 + dep/acelite/ace/Hash_Map_Manager_T.cpp | 542 + dep/acelite/ace/Hash_Map_Manager_T.h | 1306 ++ dep/acelite/ace/Hash_Map_Manager_T.inl | 1246 ++ dep/acelite/ace/Hash_Map_With_Allocator_T.cpp | 35 + dep/acelite/ace/Hash_Map_With_Allocator_T.h | 112 + dep/acelite/ace/Hash_Map_With_Allocator_T.inl | 82 + dep/acelite/ace/Hash_Multi_Map_Manager_T.cpp | 605 + dep/acelite/ace/Hash_Multi_Map_Manager_T.h | 967 ++ dep/acelite/ace/Hash_Multi_Map_Manager_T.inl | 994 ++ dep/acelite/ace/Hashable.cpp | 36 + dep/acelite/ace/Hashable.h | 65 + dep/acelite/ace/Hashable.inl | 14 + dep/acelite/ace/High_Res_Timer.cpp | 530 + dep/acelite/ace/High_Res_Timer.h | 310 + dep/acelite/ace/High_Res_Timer.inl | 153 + dep/acelite/ace/ICMP_Socket.cpp | 186 + dep/acelite/ace/ICMP_Socket.h | 110 + dep/acelite/ace/INET_Addr.cpp | 1148 ++ dep/acelite/ace/INET_Addr.h | 390 + dep/acelite/ace/INET_Addr.inl | 255 + dep/acelite/ace/IOStream.cpp | 665 + dep/acelite/ace/IOStream.h | 512 + dep/acelite/ace/IOStream_T.cpp | 247 + dep/acelite/ace/IOStream_T.h | 297 + dep/acelite/ace/IOStream_T.inl | 123 + dep/acelite/ace/IO_Cntl_Msg.cpp | 51 + dep/acelite/ace/IO_Cntl_Msg.h | 112 + dep/acelite/ace/IO_Cntl_Msg.inl | 61 + dep/acelite/ace/IO_SAP.cpp | 142 + dep/acelite/ace/IO_SAP.h | 96 + dep/acelite/ace/IO_SAP.inl | 42 + dep/acelite/ace/IPC_SAP.cpp | 193 + dep/acelite/ace/IPC_SAP.h | 96 + dep/acelite/ace/IPC_SAP.inl | 40 + dep/acelite/ace/If_Then_Else.h | 89 + dep/acelite/ace/Init_ACE.cpp | 45 + dep/acelite/ace/Init_ACE.h | 70 + dep/acelite/ace/Intrusive_Auto_Ptr.cpp | 22 + dep/acelite/ace/Intrusive_Auto_Ptr.h | 165 + dep/acelite/ace/Intrusive_Auto_Ptr.inl | 147 + dep/acelite/ace/Intrusive_List.cpp | 157 + dep/acelite/ace/Intrusive_List.h | 144 + dep/acelite/ace/Intrusive_List.inl | 40 + dep/acelite/ace/Intrusive_List_Node.cpp | 27 + dep/acelite/ace/Intrusive_List_Node.h | 84 + dep/acelite/ace/Intrusive_List_Node.inl | 31 + dep/acelite/ace/LOCK_SOCK_Acceptor.cpp | 35 + dep/acelite/ace/LOCK_SOCK_Acceptor.h | 67 + dep/acelite/ace/LSOCK.cpp | 185 + dep/acelite/ace/LSOCK.h | 84 + dep/acelite/ace/LSOCK.inl | 43 + dep/acelite/ace/LSOCK_Acceptor.cpp | 143 + dep/acelite/ace/LSOCK_Acceptor.h | 95 + dep/acelite/ace/LSOCK_CODgram.cpp | 62 + dep/acelite/ace/LSOCK_CODgram.h | 109 + dep/acelite/ace/LSOCK_CODgram.inl | 30 + dep/acelite/ace/LSOCK_Connector.cpp | 59 + dep/acelite/ace/LSOCK_Connector.h | 91 + dep/acelite/ace/LSOCK_Connector.inl | 27 + dep/acelite/ace/LSOCK_Dgram.cpp | 71 + dep/acelite/ace/LSOCK_Dgram.h | 74 + dep/acelite/ace/LSOCK_Dgram.inl | 22 + dep/acelite/ace/LSOCK_Stream.cpp | 137 + dep/acelite/ace/LSOCK_Stream.h | 82 + dep/acelite/ace/LSOCK_Stream.inl | 25 + dep/acelite/ace/Lib_Find.cpp | 768 + dep/acelite/ace/Lib_Find.h | 131 + dep/acelite/ace/Local_Memory_Pool.cpp | 144 + dep/acelite/ace/Local_Memory_Pool.h | 133 + dep/acelite/ace/Local_Name_Space.cpp | 169 + dep/acelite/ace/Local_Name_Space.h | 132 + dep/acelite/ace/Local_Name_Space_T.cpp | 966 ++ dep/acelite/ace/Local_Name_Space_T.h | 280 + dep/acelite/ace/Local_Tokens.cpp | 1623 ++ dep/acelite/ace/Local_Tokens.h | 1121 ++ dep/acelite/ace/Local_Tokens.inl | 289 + dep/acelite/ace/Lock.cpp | 88 + dep/acelite/ace/Lock.h | 161 + dep/acelite/ace/Lock.inl | 12 + dep/acelite/ace/Lock_Adapter_T.cpp | 117 + dep/acelite/ace/Lock_Adapter_T.h | 123 + dep/acelite/ace/Lock_Adapter_T.inl | 16 + dep/acelite/ace/Log_Msg.cpp | 2676 ++++ dep/acelite/ace/Log_Msg.h | 777 + dep/acelite/ace/Log_Msg.inl | 235 + dep/acelite/ace/Log_Msg_Backend.cpp | 14 + dep/acelite/ace/Log_Msg_Backend.h | 88 + dep/acelite/ace/Log_Msg_Callback.cpp | 13 + dep/acelite/ace/Log_Msg_Callback.h | 69 + dep/acelite/ace/Log_Msg_IPC.cpp | 114 + dep/acelite/ace/Log_Msg_IPC.h | 81 + dep/acelite/ace/Log_Msg_NT_Event_Log.cpp | 170 + dep/acelite/ace/Log_Msg_NT_Event_Log.h | 72 + dep/acelite/ace/Log_Msg_UNIX_Syslog.cpp | 207 + dep/acelite/ace/Log_Msg_UNIX_Syslog.h | 77 + dep/acelite/ace/Log_Priority.h | 85 + dep/acelite/ace/Log_Record.cpp | 412 + dep/acelite/ace/Log_Record.h | 230 + dep/acelite/ace/Log_Record.inl | 121 + dep/acelite/ace/Logging_Strategy.cpp | 614 + dep/acelite/ace/Logging_Strategy.h | 214 + dep/acelite/ace/MEM_Acceptor.cpp | 266 + dep/acelite/ace/MEM_Acceptor.h | 192 + dep/acelite/ace/MEM_Acceptor.inl | 103 + dep/acelite/ace/MEM_Addr.cpp | 170 + dep/acelite/ace/MEM_Addr.h | 155 + dep/acelite/ace/MEM_Addr.inl | 111 + dep/acelite/ace/MEM_Connector.cpp | 149 + dep/acelite/ace/MEM_Connector.h | 179 + dep/acelite/ace/MEM_Connector.inl | 30 + dep/acelite/ace/MEM_IO.cpp | 574 + dep/acelite/ace/MEM_IO.h | 310 + dep/acelite/ace/MEM_IO.inl | 247 + dep/acelite/ace/MEM_SAP.cpp | 97 + dep/acelite/ace/MEM_SAP.h | 169 + dep/acelite/ace/MEM_SAP.inl | 64 + dep/acelite/ace/MEM_Stream.cpp | 47 + dep/acelite/ace/MEM_Stream.h | 158 + dep/acelite/ace/MEM_Stream.inl | 180 + dep/acelite/ace/MMAP_Memory_Pool.cpp | 593 + dep/acelite/ace/MMAP_Memory_Pool.h | 347 + dep/acelite/ace/MMAP_Memory_Pool.inl | 21 + dep/acelite/ace/Makefile.in | 5498 +++++++ dep/acelite/ace/Malloc.cpp | 186 + dep/acelite/ace/Malloc.h | 396 + dep/acelite/ace/Malloc.inl | 26 + dep/acelite/ace/Malloc_Allocator.cpp | 361 + dep/acelite/ace/Malloc_Allocator.h | 146 + dep/acelite/ace/Malloc_Allocator.inl | 16 + dep/acelite/ace/Malloc_Base.h | 168 + dep/acelite/ace/Malloc_T.cpp | 1260 ++ dep/acelite/ace/Malloc_T.h | 931 ++ dep/acelite/ace/Malloc_T.inl | 184 + dep/acelite/ace/Managed_Object.cpp | 25 + dep/acelite/ace/Managed_Object.h | 168 + dep/acelite/ace/Managed_Object.inl | 23 + dep/acelite/ace/Manual_Event.cpp | 48 + dep/acelite/ace/Manual_Event.h | 74 + dep/acelite/ace/Manual_Event.inl | 12 + dep/acelite/ace/Map.h | 32 + dep/acelite/ace/Map_Manager.cpp | 701 + dep/acelite/ace/Map_Manager.h | 720 + dep/acelite/ace/Map_Manager.inl | 729 + dep/acelite/ace/Map_T.cpp | 1343 ++ dep/acelite/ace/Map_T.h | 1611 ++ dep/acelite/ace/Map_T.inl | 415 + dep/acelite/ace/Mem_Map.cpp | 310 + dep/acelite/ace/Mem_Map.h | 232 + dep/acelite/ace/Mem_Map.inl | 238 + dep/acelite/ace/Memory_Pool.h | 31 + dep/acelite/ace/Message_Block.cpp | 1278 ++ dep/acelite/ace/Message_Block.h | 871 ++ dep/acelite/ace/Message_Block.inl | 508 + dep/acelite/ace/Message_Block_T.cpp | 54 + dep/acelite/ace/Message_Block_T.h | 88 + dep/acelite/ace/Message_Block_T.inl | 31 + dep/acelite/ace/Message_Queue.cpp | 28 + dep/acelite/ace/Message_Queue.h | 233 + dep/acelite/ace/Message_Queue.inl | 12 + dep/acelite/ace/Message_Queue_NT.cpp | 237 + dep/acelite/ace/Message_Queue_NT.h | 231 + dep/acelite/ace/Message_Queue_NT.inl | 131 + dep/acelite/ace/Message_Queue_T.cpp | 2991 ++++ dep/acelite/ace/Message_Queue_T.h | 1563 ++ dep/acelite/ace/Message_Queue_Vx.cpp | 368 + dep/acelite/ace/Message_Queue_Vx.h | 227 + dep/acelite/ace/Message_Queue_Vx.inl | 19 + dep/acelite/ace/Method_Object.h | 38 + dep/acelite/ace/Method_Request.cpp | 30 + dep/acelite/ace/Method_Request.h | 100 + dep/acelite/ace/Metrics_Cache.h | 140 + dep/acelite/ace/Metrics_Cache_T.cpp | 237 + dep/acelite/ace/Metrics_Cache_T.h | 243 + dep/acelite/ace/Metrics_Cache_T.inl | 240 + dep/acelite/ace/Min_Max.h | 70 + dep/acelite/ace/Module.cpp | 273 + dep/acelite/ace/Module.h | 215 + dep/acelite/ace/Module.inl | 65 + dep/acelite/ace/Monitor_Admin.cpp | 113 + dep/acelite/ace/Monitor_Admin.h | 109 + dep/acelite/ace/Monitor_Admin_Manager.cpp | 42 + dep/acelite/ace/Monitor_Admin_Manager.h | 70 + dep/acelite/ace/Monitor_Base.cpp | 402 + dep/acelite/ace/Monitor_Base.h | 152 + dep/acelite/ace/Monitor_Base.inl | 59 + dep/acelite/ace/Monitor_Control_Action.cpp | 45 + dep/acelite/ace/Monitor_Control_Action.h | 65 + dep/acelite/ace/Monitor_Control_Types.cpp | 81 + dep/acelite/ace/Monitor_Control_Types.h | 116 + dep/acelite/ace/Monitor_Point_Registry.cpp | 172 + dep/acelite/ace/Monitor_Point_Registry.h | 100 + dep/acelite/ace/Monitor_Size.cpp | 47 + dep/acelite/ace/Monitor_Size.h | 64 + dep/acelite/ace/Msg_WFMO_Reactor.cpp | 85 + dep/acelite/ace/Msg_WFMO_Reactor.h | 120 + dep/acelite/ace/Msg_WFMO_Reactor.inl | 35 + dep/acelite/ace/Multihomed_INET_Addr.cpp | 300 + dep/acelite/ace/Multihomed_INET_Addr.h | 199 + dep/acelite/ace/Multihomed_INET_Addr.inl | 15 + dep/acelite/ace/Mutex.cpp | 127 + dep/acelite/ace/Mutex.h | 192 + dep/acelite/ace/Mutex.inl | 175 + dep/acelite/ace/NT_Service.cpp | 618 + dep/acelite/ace/NT_Service.h | 439 + dep/acelite/ace/NT_Service.inl | 85 + dep/acelite/ace/Name_Proxy.cpp | 209 + dep/acelite/ace/Name_Proxy.h | 101 + dep/acelite/ace/Name_Request_Reply.cpp | 577 + dep/acelite/ace/Name_Request_Reply.h | 265 + dep/acelite/ace/Name_Space.cpp | 75 + dep/acelite/ace/Name_Space.h | 165 + dep/acelite/ace/Naming_Context.cpp | 649 + dep/acelite/ace/Naming_Context.h | 387 + dep/acelite/ace/Naming_Context.inl | 44 + dep/acelite/ace/Netlink_Addr.cpp | 68 + dep/acelite/ace/Netlink_Addr.h | 120 + dep/acelite/ace/Netlink_Addr.inl | 51 + dep/acelite/ace/Node.cpp | 46 + dep/acelite/ace/Node.h | 85 + dep/acelite/ace/Notification_Queue.cpp | 225 + dep/acelite/ace/Notification_Queue.h | 156 + dep/acelite/ace/Notification_Queue.inl | 50 + dep/acelite/ace/Notification_Strategy.cpp | 22 + dep/acelite/ace/Notification_Strategy.h | 75 + dep/acelite/ace/Notification_Strategy.inl | 31 + dep/acelite/ace/Null_Barrier.h | 59 + dep/acelite/ace/Null_Condition.h | 85 + dep/acelite/ace/Null_Mutex.h | 230 + dep/acelite/ace/Null_Semaphore.h | 105 + dep/acelite/ace/Numeric_Limits.h | 270 + dep/acelite/ace/OS.cpp | 53 + dep/acelite/ace/OS.h | 329 + dep/acelite/ace/OS.inl | 80 + dep/acelite/ace/OS_Dirent.h | 32 + dep/acelite/ace/OS_Errno.cpp | 47 + dep/acelite/ace/OS_Errno.h | 100 + dep/acelite/ace/OS_Errno.inl | 67 + dep/acelite/ace/OS_Log_Msg_Attributes.cpp | 9 + dep/acelite/ace/OS_Log_Msg_Attributes.h | 87 + dep/acelite/ace/OS_Log_Msg_Attributes.inl | 22 + dep/acelite/ace/OS_Memory.h | 344 + dep/acelite/ace/OS_NS_Thread.cpp | 5370 +++++++ dep/acelite/ace/OS_NS_Thread.h | 2024 +++ dep/acelite/ace/OS_NS_Thread.inl | 3648 +++++ dep/acelite/ace/OS_NS_arpa_inet.cpp | 53 + dep/acelite/ace/OS_NS_arpa_inet.h | 74 + dep/acelite/ace/OS_NS_arpa_inet.inl | 98 + dep/acelite/ace/OS_NS_ctype.cpp | 11 + dep/acelite/ace/OS_NS_ctype.h | 146 + dep/acelite/ace/OS_NS_ctype.inl | 231 + dep/acelite/ace/OS_NS_dirent.cpp | 274 + dep/acelite/ace/OS_NS_dirent.h | 153 + dep/acelite/ace/OS_NS_dirent.inl | 184 + dep/acelite/ace/OS_NS_dlfcn.cpp | 10 + dep/acelite/ace/OS_NS_dlfcn.h | 69 + dep/acelite/ace/OS_NS_dlfcn.inl | 286 + dep/acelite/ace/OS_NS_errno.cpp | 11 + dep/acelite/ace/OS_NS_errno.h | 102 + dep/acelite/ace/OS_NS_errno.inl | 83 + dep/acelite/ace/OS_NS_fcntl.cpp | 245 + dep/acelite/ace/OS_NS_fcntl.h | 79 + dep/acelite/ace/OS_NS_fcntl.inl | 23 + dep/acelite/ace/OS_NS_macros.h | 114 + dep/acelite/ace/OS_NS_math.cpp | 10 + dep/acelite/ace/OS_NS_math.h | 121 + dep/acelite/ace/OS_NS_math.inl | 17 + dep/acelite/ace/OS_NS_netdb.cpp | 475 + dep/acelite/ace/OS_NS_netdb.h | 146 + dep/acelite/ace/OS_NS_netdb.inl | 754 + dep/acelite/ace/OS_NS_poll.cpp | 10 + dep/acelite/ace/OS_NS_poll.h | 66 + dep/acelite/ace/OS_NS_poll.inl | 45 + dep/acelite/ace/OS_NS_pwd.cpp | 10 + dep/acelite/ace/OS_NS_pwd.h | 77 + dep/acelite/ace/OS_NS_pwd.inl | 120 + dep/acelite/ace/OS_NS_regex.cpp | 10 + dep/acelite/ace/OS_NS_regex.h | 65 + dep/acelite/ace/OS_NS_regex.inl | 39 + dep/acelite/ace/OS_NS_signal.cpp | 26 + dep/acelite/ace/OS_NS_signal.h | 233 + dep/acelite/ace/OS_NS_signal.inl | 243 + dep/acelite/ace/OS_NS_stdio.cpp | 426 + dep/acelite/ace/OS_NS_stdio.h | 557 + dep/acelite/ace/OS_NS_stdio.inl | 1213 ++ dep/acelite/ace/OS_NS_stdlib.cpp | 1211 ++ dep/acelite/ace/OS_NS_stdlib.h | 453 + dep/acelite/ace/OS_NS_stdlib.inl | 644 + dep/acelite/ace/OS_NS_string.cpp | 421 + dep/acelite/ace/OS_NS_string.h | 477 + dep/acelite/ace/OS_NS_string.inl | 560 + dep/acelite/ace/OS_NS_strings.cpp | 84 + dep/acelite/ace/OS_NS_strings.h | 86 + dep/acelite/ace/OS_NS_strings.inl | 59 + dep/acelite/ace/OS_NS_stropts.cpp | 193 + dep/acelite/ace/OS_NS_stropts.h | 170 + dep/acelite/ace/OS_NS_stropts.inl | 201 + dep/acelite/ace/OS_NS_sys_mman.cpp | 10 + dep/acelite/ace/OS_NS_sys_mman.h | 97 + dep/acelite/ace/OS_NS_sys_mman.inl | 301 + dep/acelite/ace/OS_NS_sys_msg.cpp | 10 + dep/acelite/ace/OS_NS_sys_msg.h | 77 + dep/acelite/ace/OS_NS_sys_msg.inl | 78 + dep/acelite/ace/OS_NS_sys_resource.cpp | 10 + dep/acelite/ace/OS_NS_sys_resource.h | 67 + dep/acelite/ace/OS_NS_sys_resource.inl | 98 + dep/acelite/ace/OS_NS_sys_select.cpp | 10 + dep/acelite/ace/OS_NS_sys_select.h | 77 + dep/acelite/ace/OS_NS_sys_select.inl | 80 + dep/acelite/ace/OS_NS_sys_sendfile.cpp | 53 + dep/acelite/ace/OS_NS_sys_sendfile.h | 66 + dep/acelite/ace/OS_NS_sys_sendfile.inl | 24 + dep/acelite/ace/OS_NS_sys_shm.cpp | 10 + dep/acelite/ace/OS_NS_sys_shm.h | 74 + dep/acelite/ace/OS_NS_sys_shm.inl | 76 + dep/acelite/ace/OS_NS_sys_socket.cpp | 159 + dep/acelite/ace/OS_NS_sys_socket.h | 296 + dep/acelite/ace/OS_NS_sys_socket.inl | 999 ++ dep/acelite/ace/OS_NS_sys_stat.cpp | 10 + dep/acelite/ace/OS_NS_sys_stat.h | 149 + dep/acelite/ace/OS_NS_sys_stat.inl | 295 + dep/acelite/ace/OS_NS_sys_time.cpp | 10 + dep/acelite/ace/OS_NS_sys_time.h | 55 + dep/acelite/ace/OS_NS_sys_time.inl | 75 + dep/acelite/ace/OS_NS_sys_uio.cpp | 130 + dep/acelite/ace/OS_NS_sys_uio.h | 80 + dep/acelite/ace/OS_NS_sys_uio.inl | 55 + dep/acelite/ace/OS_NS_sys_utsname.cpp | 244 + dep/acelite/ace/OS_NS_sys_utsname.h | 71 + dep/acelite/ace/OS_NS_sys_wait.cpp | 9 + dep/acelite/ace/OS_NS_sys_wait.h | 87 + dep/acelite/ace/OS_NS_sys_wait.inl | 105 + dep/acelite/ace/OS_NS_time.cpp | 636 + dep/acelite/ace/OS_NS_time.h | 294 + dep/acelite/ace/OS_NS_time.inl | 496 + dep/acelite/ace/OS_NS_unistd.cpp | 937 ++ dep/acelite/ace/OS_NS_unistd.h | 382 + dep/acelite/ace/OS_NS_unistd.inl | 1226 ++ dep/acelite/ace/OS_NS_wchar.cpp | 377 + dep/acelite/ace/OS_NS_wchar.h | 199 + dep/acelite/ace/OS_NS_wchar.inl | 87 + dep/acelite/ace/OS_NS_wctype.cpp | 11 + dep/acelite/ace/OS_NS_wctype.h | 71 + dep/acelite/ace/OS_NS_wctype.inl | 25 + dep/acelite/ace/OS_QoS.cpp | 476 + dep/acelite/ace/OS_QoS.h | 449 + dep/acelite/ace/OS_String.h | 32 + dep/acelite/ace/OS_TLI.cpp | 9 + dep/acelite/ace/OS_TLI.h | 285 + dep/acelite/ace/OS_TLI.inl | 390 + dep/acelite/ace/OS_Thread_Adapter.cpp | 153 + dep/acelite/ace/OS_Thread_Adapter.h | 71 + dep/acelite/ace/OS_main.cpp | 157 + dep/acelite/ace/OS_main.h | 310 + dep/acelite/ace/Obchunk.cpp | 36 + dep/acelite/ace/Obchunk.h | 77 + dep/acelite/ace/Obchunk.inl | 12 + dep/acelite/ace/Object_Manager.cpp | 971 ++ dep/acelite/ace/Object_Manager.h | 475 + dep/acelite/ace/Object_Manager.inl | 51 + dep/acelite/ace/Object_Manager_Base.cpp | 507 + dep/acelite/ace/Object_Manager_Base.h | 248 + dep/acelite/ace/Obstack.h | 31 + dep/acelite/ace/Obstack_T.cpp | 226 + dep/acelite/ace/Obstack_T.h | 134 + dep/acelite/ace/Obstack_T.inl | 19 + dep/acelite/ace/PI_Malloc.cpp | 165 + dep/acelite/ace/PI_Malloc.h | 213 + dep/acelite/ace/PI_Malloc.inl | 33 + dep/acelite/ace/POSIX_Asynch_IO.cpp | 2421 +++ dep/acelite/ace/POSIX_Asynch_IO.h | 1302 ++ dep/acelite/ace/POSIX_CB_Proactor.cpp | 185 + dep/acelite/ace/POSIX_CB_Proactor.h | 97 + dep/acelite/ace/POSIX_Proactor.cpp | 2069 +++ dep/acelite/ace/POSIX_Proactor.h | 659 + dep/acelite/ace/POSIX_Proactor.inl | 13 + dep/acelite/ace/Pagefile_Memory_Pool.cpp | 389 + dep/acelite/ace/Pagefile_Memory_Pool.h | 204 + dep/acelite/ace/Pagefile_Memory_Pool.inl | 54 + dep/acelite/ace/Pair.h | 32 + dep/acelite/ace/Pair_T.cpp | 16 + dep/acelite/ace/Pair_T.h | 129 + dep/acelite/ace/Pair_T.inl | 90 + dep/acelite/ace/Parse_Node.cpp | 928 ++ dep/acelite/ace/Parse_Node.h | 523 + dep/acelite/ace/Ping_Socket.cpp | 379 + dep/acelite/ace/Ping_Socket.h | 118 + dep/acelite/ace/Ping_Socket.inl | 13 + dep/acelite/ace/Pipe.cpp | 365 + dep/acelite/ace/Pipe.h | 165 + dep/acelite/ace/Pipe.inl | 188 + dep/acelite/ace/PrecompiledHeaders/WinAcePCH.cpp | 2 + dep/acelite/ace/PrecompiledHeaders/WinAcePCH.h | 17 + dep/acelite/ace/Priority_Reactor.cpp | 188 + dep/acelite/ace/Priority_Reactor.h | 100 + dep/acelite/ace/Proactor.cpp | 1176 ++ dep/acelite/ace/Proactor.h | 691 + dep/acelite/ace/Proactor.inl | 80 + dep/acelite/ace/Proactor_Impl.cpp | 21 + dep/acelite/ace/Proactor_Impl.h | 265 + dep/acelite/ace/Process.cpp | 1408 ++ dep/acelite/ace/Process.h | 641 + dep/acelite/ace/Process.inl | 421 + dep/acelite/ace/Process_Manager.cpp | 1029 ++ dep/acelite/ace/Process_Manager.h | 477 + dep/acelite/ace/Process_Manager.inl | 13 + dep/acelite/ace/Process_Mutex.cpp | 90 + dep/acelite/ace/Process_Mutex.h | 233 + dep/acelite/ace/Process_Mutex.inl | 118 + dep/acelite/ace/Process_Semaphore.cpp | 111 + dep/acelite/ace/Process_Semaphore.h | 159 + dep/acelite/ace/Process_Semaphore.inl | 66 + dep/acelite/ace/Profile_Timer.cpp | 443 + dep/acelite/ace/Profile_Timer.h | 139 + dep/acelite/ace/Profile_Timer.inl | 129 + dep/acelite/ace/QoS/ACE_QoS_Export.h | 46 + dep/acelite/ace/QoS/QoS_Decorator.cpp | 165 + dep/acelite/ace/QoS/QoS_Decorator.h | 179 + dep/acelite/ace/QoS/QoS_Manager.cpp | 41 + dep/acelite/ace/QoS/QoS_Manager.h | 74 + dep/acelite/ace/QoS/QoS_Session.h | 183 + dep/acelite/ace/QoS/QoS_Session_Factory.cpp | 105 + dep/acelite/ace/QoS/QoS_Session_Factory.h | 96 + dep/acelite/ace/QoS/QoS_Session_Impl.cpp | 718 + dep/acelite/ace/QoS/QoS_Session_Impl.h | 265 + dep/acelite/ace/QoS/QoS_Session_Impl.inl | 229 + dep/acelite/ace/QoS/README | 55 + dep/acelite/ace/QoS/SOCK_Dgram_Mcast_QoS.cpp | 258 + dep/acelite/ace/QoS/SOCK_Dgram_Mcast_QoS.h | 142 + dep/acelite/ace/QoS/SOCK_Dgram_Mcast_QoS.inl | 57 + dep/acelite/ace/RB_Tree.cpp | 1250 ++ dep/acelite/ace/RB_Tree.h | 904 ++ dep/acelite/ace/RB_Tree.inl | 1169 ++ dep/acelite/ace/README | 1787 +++ dep/acelite/ace/RW_Mutex.cpp | 55 + dep/acelite/ace/RW_Mutex.h | 141 + dep/acelite/ace/RW_Mutex.inl | 83 + dep/acelite/ace/RW_Process_Mutex.cpp | 54 + dep/acelite/ace/RW_Process_Mutex.h | 137 + dep/acelite/ace/RW_Process_Mutex.inl | 77 + dep/acelite/ace/RW_Thread_Mutex.cpp | 45 + dep/acelite/ace/RW_Thread_Mutex.h | 74 + dep/acelite/ace/RW_Thread_Mutex.inl | 19 + dep/acelite/ace/Reactor.cpp | 514 + dep/acelite/ace/Reactor.h | 880 ++ dep/acelite/ace/Reactor.inl | 498 + dep/acelite/ace/Reactor_Impl.cpp | 15 + dep/acelite/ace/Reactor_Impl.h | 569 + dep/acelite/ace/Reactor_Notification_Strategy.cpp | 38 + dep/acelite/ace/Reactor_Notification_Strategy.h | 66 + dep/acelite/ace/Reactor_Notification_Strategy.inl | 19 + dep/acelite/ace/Reactor_Timer_Interface.cpp | 16 + dep/acelite/ace/Reactor_Timer_Interface.h | 60 + dep/acelite/ace/Reactor_Token_T.cpp | 80 + dep/acelite/ace/Reactor_Token_T.h | 93 + dep/acelite/ace/Read_Buffer.cpp | 176 + dep/acelite/ace/Read_Buffer.h | 129 + dep/acelite/ace/Read_Buffer.inl | 32 + dep/acelite/ace/Recursive_Thread_Mutex.cpp | 125 + dep/acelite/ace/Recursive_Thread_Mutex.h | 197 + dep/acelite/ace/Recursive_Thread_Mutex.inl | 95 + dep/acelite/ace/Recyclable.cpp | 22 + dep/acelite/ace/Recyclable.h | 77 + dep/acelite/ace/Recyclable.inl | 20 + dep/acelite/ace/Refcountable.h | 32 + dep/acelite/ace/Refcountable_T.cpp | 25 + dep/acelite/ace/Refcountable_T.h | 67 + dep/acelite/ace/Refcountable_T.inl | 35 + dep/acelite/ace/Refcounted_Auto_Ptr.cpp | 18 + dep/acelite/ace/Refcounted_Auto_Ptr.h | 199 + dep/acelite/ace/Refcounted_Auto_Ptr.inl | 190 + dep/acelite/ace/Registry.cpp | 1129 ++ dep/acelite/ace/Registry.h | 562 + dep/acelite/ace/Registry_Name_Space.cpp | 296 + dep/acelite/ace/Registry_Name_Space.h | 140 + dep/acelite/ace/Remote_Name_Space.cpp | 380 + dep/acelite/ace/Remote_Name_Space.h | 147 + dep/acelite/ace/Remote_Tokens.cpp | 531 + dep/acelite/ace/Remote_Tokens.h | 322 + dep/acelite/ace/Remote_Tokens.inl | 48 + dep/acelite/ace/Reverse_Lock_T.cpp | 93 + dep/acelite/ace/Reverse_Lock_T.h | 139 + dep/acelite/ace/Reverse_Lock_T.inl | 19 + dep/acelite/ace/Rtems_init.c | 219 + dep/acelite/ace/SOCK.cpp | 185 + dep/acelite/ace/SOCK.h | 137 + dep/acelite/ace/SOCK.inl | 39 + dep/acelite/ace/SOCK_Acceptor.cpp | 406 + dep/acelite/ace/SOCK_Acceptor.h | 178 + dep/acelite/ace/SOCK_Acceptor.inl | 13 + dep/acelite/ace/SOCK_CODgram.cpp | 151 + dep/acelite/ace/SOCK_CODgram.h | 143 + dep/acelite/ace/SOCK_CODgram.inl | 19 + dep/acelite/ace/SOCK_Connector.cpp | 365 + dep/acelite/ace/SOCK_Connector.h | 321 + dep/acelite/ace/SOCK_Connector.inl | 38 + dep/acelite/ace/SOCK_Dgram.cpp | 747 + dep/acelite/ace/SOCK_Dgram.h | 239 + dep/acelite/ace/SOCK_Dgram.inl | 167 + dep/acelite/ace/SOCK_Dgram_Bcast.cpp | 380 + dep/acelite/ace/SOCK_Dgram_Bcast.h | 140 + dep/acelite/ace/SOCK_Dgram_Bcast.inl | 37 + dep/acelite/ace/SOCK_Dgram_Mcast.cpp | 932 ++ dep/acelite/ace/SOCK_Dgram_Mcast.h | 384 + dep/acelite/ace/SOCK_Dgram_Mcast.inl | 52 + dep/acelite/ace/SOCK_IO.cpp | 180 + dep/acelite/ace/SOCK_IO.h | 136 + dep/acelite/ace/SOCK_IO.inl | 123 + dep/acelite/ace/SOCK_Netlink.cpp | 113 + dep/acelite/ace/SOCK_Netlink.h | 106 + dep/acelite/ace/SOCK_Netlink.inl | 37 + dep/acelite/ace/SOCK_SEQPACK_Acceptor.cpp | 596 + dep/acelite/ace/SOCK_SEQPACK_Acceptor.h | 189 + dep/acelite/ace/SOCK_SEQPACK_Acceptor.inl | 13 + dep/acelite/ace/SOCK_SEQPACK_Association.cpp | 348 + dep/acelite/ace/SOCK_SEQPACK_Association.h | 202 + dep/acelite/ace/SOCK_SEQPACK_Association.inl | 177 + dep/acelite/ace/SOCK_SEQPACK_Connector.cpp | 442 + dep/acelite/ace/SOCK_SEQPACK_Connector.h | 331 + dep/acelite/ace/SOCK_SEQPACK_Connector.inl | 38 + dep/acelite/ace/SOCK_Stream.cpp | 40 + dep/acelite/ace/SOCK_Stream.h | 184 + dep/acelite/ace/SOCK_Stream.inl | 177 + dep/acelite/ace/SPIPE.cpp | 82 + dep/acelite/ace/SPIPE.h | 116 + dep/acelite/ace/SPIPE.inl | 18 + dep/acelite/ace/SPIPE_Acceptor.cpp | 337 + dep/acelite/ace/SPIPE_Acceptor.h | 168 + dep/acelite/ace/SPIPE_Addr.cpp | 167 + dep/acelite/ace/SPIPE_Addr.h | 122 + dep/acelite/ace/SPIPE_Addr.inl | 59 + dep/acelite/ace/SPIPE_Connector.cpp | 160 + dep/acelite/ace/SPIPE_Connector.h | 118 + dep/acelite/ace/SPIPE_Connector.inl | 14 + dep/acelite/ace/SPIPE_Stream.cpp | 104 + dep/acelite/ace/SPIPE_Stream.h | 171 + dep/acelite/ace/SPIPE_Stream.inl | 275 + dep/acelite/ace/SSL/SSL_Asynch_BIO.cpp | 253 + dep/acelite/ace/SSL/SSL_Asynch_BIO.h | 42 + dep/acelite/ace/SSL/SSL_Asynch_Stream.cpp | 1085 ++ dep/acelite/ace/SSL/SSL_Asynch_Stream.h | 466 + dep/acelite/ace/SSL/SSL_Asynch_Stream.inl | 13 + dep/acelite/ace/SSL/SSL_Context.cpp | 657 + dep/acelite/ace/SSL/SSL_Context.h | 394 + dep/acelite/ace/SSL/SSL_Context.inl | 125 + dep/acelite/ace/SSL/SSL_Export.h | 44 + dep/acelite/ace/SSL/SSL_SOCK.cpp | 72 + dep/acelite/ace/SSL/SSL_SOCK.h | 103 + dep/acelite/ace/SSL/SSL_SOCK.inl | 71 + dep/acelite/ace/SSL/SSL_SOCK_Acceptor.cpp | 250 + dep/acelite/ace/SSL/SSL_SOCK_Acceptor.h | 197 + dep/acelite/ace/SSL/SSL_SOCK_Acceptor.inl | 85 + dep/acelite/ace/SSL/SSL_SOCK_Connector.cpp | 425 + dep/acelite/ace/SSL/SSL_SOCK_Connector.h | 318 + dep/acelite/ace/SSL/SSL_SOCK_Connector.inl | 28 + dep/acelite/ace/SSL/SSL_SOCK_Stream.cpp | 630 + dep/acelite/ace/SSL/SSL_SOCK_Stream.h | 348 + dep/acelite/ace/SSL/SSL_SOCK_Stream.inl | 350 + dep/acelite/ace/SSL/sslconf.h | 57 + dep/acelite/ace/SString.cpp | 341 + dep/acelite/ace/SString.h | 303 + dep/acelite/ace/SString.inl | 299 + dep/acelite/ace/SStringfwd.h | 55 + dep/acelite/ace/SUN_Proactor.cpp | 324 + dep/acelite/ace/SUN_Proactor.h | 126 + dep/acelite/ace/SV_Message.cpp | 24 + dep/acelite/ace/SV_Message.h | 67 + dep/acelite/ace/SV_Message.inl | 37 + dep/acelite/ace/SV_Message_Queue.cpp | 44 + dep/acelite/ace/SV_Message_Queue.h | 105 + dep/acelite/ace/SV_Message_Queue.inl | 81 + dep/acelite/ace/SV_Semaphore_Complex.cpp | 259 + dep/acelite/ace/SV_Semaphore_Complex.h | 159 + dep/acelite/ace/SV_Semaphore_Complex.inl | 84 + dep/acelite/ace/SV_Semaphore_Simple.cpp | 237 + dep/acelite/ace/SV_Semaphore_Simple.h | 197 + dep/acelite/ace/SV_Semaphore_Simple.inl | 128 + dep/acelite/ace/SV_Shared_Memory.cpp | 88 + dep/acelite/ace/SV_Shared_Memory.h | 121 + dep/acelite/ace/SV_Shared_Memory.inl | 118 + dep/acelite/ace/Sample_History.cpp | 73 + dep/acelite/ace/Sample_History.h | 91 + dep/acelite/ace/Sample_History.inl | 26 + dep/acelite/ace/Sbrk_Memory_Pool.cpp | 124 + dep/acelite/ace/Sbrk_Memory_Pool.h | 118 + dep/acelite/ace/Sched_Params.cpp | 337 + dep/acelite/ace/Sched_Params.h | 232 + dep/acelite/ace/Sched_Params.inl | 134 + dep/acelite/ace/Select_Reactor.h | 69 + dep/acelite/ace/Select_Reactor_Base.cpp | 1137 ++ dep/acelite/ace/Select_Reactor_Base.h | 616 + dep/acelite/ace/Select_Reactor_Base.inl | 152 + dep/acelite/ace/Select_Reactor_T.cpp | 1598 ++ dep/acelite/ace/Select_Reactor_T.h | 718 + dep/acelite/ace/Select_Reactor_T.inl | 236 + dep/acelite/ace/Semaphore.cpp | 64 + dep/acelite/ace/Semaphore.h | 183 + dep/acelite/ace/Semaphore.inl | 119 + dep/acelite/ace/Service_Config.cpp | 610 + dep/acelite/ace/Service_Config.h | 692 + dep/acelite/ace/Service_Config.inl | 208 + dep/acelite/ace/Service_Gestalt.cpp | 1327 ++ dep/acelite/ace/Service_Gestalt.h | 530 + dep/acelite/ace/Service_Gestalt.inl | 78 + dep/acelite/ace/Service_Manager.cpp | 437 + dep/acelite/ace/Service_Manager.h | 120 + dep/acelite/ace/Service_Object.cpp | 183 + dep/acelite/ace/Service_Object.h | 206 + dep/acelite/ace/Service_Object.inl | 79 + dep/acelite/ace/Service_Repository.cpp | 630 + dep/acelite/ace/Service_Repository.h | 271 + dep/acelite/ace/Service_Repository.inl | 38 + dep/acelite/ace/Service_Templates.h | 29 + dep/acelite/ace/Service_Types.cpp | 461 + dep/acelite/ace/Service_Types.h | 221 + dep/acelite/ace/Service_Types.inl | 43 + dep/acelite/ace/Shared_Memory.cpp | 13 + dep/acelite/ace/Shared_Memory.h | 58 + dep/acelite/ace/Shared_Memory_MM.cpp | 111 + dep/acelite/ace/Shared_Memory_MM.h | 120 + dep/acelite/ace/Shared_Memory_MM.inl | 42 + dep/acelite/ace/Shared_Memory_Pool.cpp | 461 + dep/acelite/ace/Shared_Memory_Pool.h | 210 + dep/acelite/ace/Shared_Memory_SV.cpp | 88 + dep/acelite/ace/Shared_Memory_SV.h | 101 + dep/acelite/ace/Shared_Memory_SV.inl | 30 + dep/acelite/ace/Shared_Object.cpp | 54 + dep/acelite/ace/Shared_Object.h | 62 + dep/acelite/ace/Shared_Object.inl | 12 + dep/acelite/ace/Sig_Adapter.cpp | 80 + dep/acelite/ace/Sig_Adapter.h | 81 + dep/acelite/ace/Sig_Handler.cpp | 616 + dep/acelite/ace/Sig_Handler.h | 237 + dep/acelite/ace/Sig_Handler.inl | 15 + dep/acelite/ace/Signal.cpp | 221 + dep/acelite/ace/Signal.h | 267 + dep/acelite/ace/Signal.inl | 265 + dep/acelite/ace/Singleton.cpp | 548 + dep/acelite/ace/Singleton.h | 330 + dep/acelite/ace/Singleton.inl | 42 + dep/acelite/ace/Sock_Connect.cpp | 1594 ++ dep/acelite/ace/Sock_Connect.h | 107 + dep/acelite/ace/Stack_Trace.cpp | 723 + dep/acelite/ace/Stack_Trace.h | 107 + dep/acelite/ace/Static_Object_Lock.h | 78 + dep/acelite/ace/Stats.cpp | 421 + dep/acelite/ace/Stats.h | 222 + dep/acelite/ace/Stats.inl | 104 + dep/acelite/ace/Strategies.h | 33 + dep/acelite/ace/Strategies_T.cpp | 1502 ++ dep/acelite/ace/Strategies_T.h | 1076 ++ dep/acelite/ace/Strategies_T.inl | 230 + dep/acelite/ace/Stream.cpp | 633 + dep/acelite/ace/Stream.h | 241 + dep/acelite/ace/Stream.inl | 51 + dep/acelite/ace/Stream_Modules.cpp | 380 + dep/acelite/ace/Stream_Modules.h | 166 + dep/acelite/ace/String_Base.cpp | 663 + dep/acelite/ace/String_Base.h | 891 ++ dep/acelite/ace/String_Base.inl | 461 + dep/acelite/ace/String_Base_Const.cpp | 20 + dep/acelite/ace/String_Base_Const.h | 52 + dep/acelite/ace/Svc_Conf.h | 110 + dep/acelite/ace/Svc_Conf.y | 376 + dep/acelite/ace/Svc_Conf_Lexer.cpp | 676 + dep/acelite/ace/Svc_Conf_Lexer.h | 70 + dep/acelite/ace/Svc_Conf_Param.h | 142 + dep/acelite/ace/Svc_Conf_Token_Table.h | 84 + dep/acelite/ace/Svc_Conf_Tokens.h | 29 + dep/acelite/ace/Svc_Conf_y.cpp | 1998 +++ dep/acelite/ace/Svc_Handler.cpp | 529 + dep/acelite/ace/Svc_Handler.h | 345 + dep/acelite/ace/Synch.h | 65 + dep/acelite/ace/Synch_Options.cpp | 110 + dep/acelite/ace/Synch_Options.h | 163 + dep/acelite/ace/Synch_T.cpp | 22 + dep/acelite/ace/Synch_T.h | 42 + dep/acelite/ace/Synch_Traits.h | 152 + dep/acelite/ace/System_Time.cpp | 140 + dep/acelite/ace/System_Time.h | 99 + dep/acelite/ace/TLI.cpp | 273 + dep/acelite/ace/TLI.h | 116 + dep/acelite/ace/TLI.inl | 50 + dep/acelite/ace/TLI_Acceptor.cpp | 553 + dep/acelite/ace/TLI_Acceptor.h | 123 + dep/acelite/ace/TLI_Connector.cpp | 256 + dep/acelite/ace/TLI_Connector.h | 130 + dep/acelite/ace/TLI_Connector.inl | 48 + dep/acelite/ace/TLI_Stream.cpp | 229 + dep/acelite/ace/TLI_Stream.h | 141 + dep/acelite/ace/TLI_Stream.inl | 25 + dep/acelite/ace/TP_Reactor.cpp | 686 + dep/acelite/ace/TP_Reactor.h | 320 + dep/acelite/ace/TP_Reactor.inl | 119 + dep/acelite/ace/TSS_Adapter.cpp | 45 + dep/acelite/ace/TSS_Adapter.h | 61 + dep/acelite/ace/TSS_T.cpp | 709 + dep/acelite/ace/TSS_T.h | 271 + dep/acelite/ace/TSS_T.inl | 103 + dep/acelite/ace/TTY_IO.cpp | 705 + dep/acelite/ace/TTY_IO.h | 113 + dep/acelite/ace/Task.cpp | 299 + dep/acelite/ace/Task.h | 307 + dep/acelite/ace/Task.inl | 77 + dep/acelite/ace/Task_Ex_T.cpp | 114 + dep/acelite/ace/Task_Ex_T.h | 205 + dep/acelite/ace/Task_Ex_T.inl | 109 + dep/acelite/ace/Task_T.cpp | 108 + dep/acelite/ace/Task_T.h | 198 + dep/acelite/ace/Task_T.inl | 105 + dep/acelite/ace/Test_and_Set.cpp | 51 + dep/acelite/ace/Test_and_Set.h | 75 + dep/acelite/ace/Thread.cpp | 101 + dep/acelite/ace/Thread.h | 282 + dep/acelite/ace/Thread.inl | 286 + dep/acelite/ace/Thread_Adapter.cpp | 228 + dep/acelite/ace/Thread_Adapter.h | 100 + dep/acelite/ace/Thread_Adapter.inl | 13 + dep/acelite/ace/Thread_Control.cpp | 96 + dep/acelite/ace/Thread_Control.h | 102 + dep/acelite/ace/Thread_Control.inl | 46 + dep/acelite/ace/Thread_Exit.cpp | 123 + dep/acelite/ace/Thread_Exit.h | 111 + dep/acelite/ace/Thread_Hook.cpp | 33 + dep/acelite/ace/Thread_Hook.h | 65 + dep/acelite/ace/Thread_Manager.cpp | 2223 +++ dep/acelite/ace/Thread_Manager.h | 1267 ++ dep/acelite/ace/Thread_Manager.inl | 305 + dep/acelite/ace/Thread_Mutex.cpp | 62 + dep/acelite/ace/Thread_Mutex.h | 176 + dep/acelite/ace/Thread_Mutex.inl | 104 + dep/acelite/ace/Thread_Semaphore.cpp | 62 + dep/acelite/ace/Thread_Semaphore.h | 87 + dep/acelite/ace/Thread_Semaphore.inl | 12 + dep/acelite/ace/Throughput_Stats.cpp | 202 + dep/acelite/ace/Throughput_Stats.h | 86 + dep/acelite/ace/Time_Value.cpp | 359 + dep/acelite/ace/Time_Value.h | 397 + dep/acelite/ace/Time_Value.inl | 418 + dep/acelite/ace/Timeprobe.cpp | 15 + dep/acelite/ace/Timeprobe.h | 201 + dep/acelite/ace/Timeprobe.inl | 14 + dep/acelite/ace/Timeprobe_T.cpp | 427 + dep/acelite/ace/Timeprobe_T.h | 220 + dep/acelite/ace/Timer_Hash.h | 75 + dep/acelite/ace/Timer_Hash_T.cpp | 870 ++ dep/acelite/ace/Timer_Hash_T.h | 342 + dep/acelite/ace/Timer_Heap.h | 41 + dep/acelite/ace/Timer_Heap_T.cpp | 889 ++ dep/acelite/ace/Timer_Heap_T.h | 338 + dep/acelite/ace/Timer_List.h | 42 + dep/acelite/ace/Timer_List_T.cpp | 418 + dep/acelite/ace/Timer_List_T.h | 226 + dep/acelite/ace/Timer_Queue.h | 52 + dep/acelite/ace/Timer_Queue_Adapters.cpp | 361 + dep/acelite/ace/Timer_Queue_Adapters.h | 261 + dep/acelite/ace/Timer_Queue_Adapters.inl | 29 + dep/acelite/ace/Timer_Queue_T.cpp | 538 + dep/acelite/ace/Timer_Queue_T.h | 566 + dep/acelite/ace/Timer_Queue_T.inl | 222 + dep/acelite/ace/Timer_Queuefwd.h | 38 + dep/acelite/ace/Timer_Wheel.h | 42 + dep/acelite/ace/Timer_Wheel_T.cpp | 964 ++ dep/acelite/ace/Timer_Wheel_T.h | 226 + dep/acelite/ace/Token.cpp | 545 + dep/acelite/ace/Token.h | 376 + dep/acelite/ace/Token.inl | 176 + dep/acelite/ace/Token_Collection.cpp | 294 + dep/acelite/ace/Token_Collection.h | 243 + dep/acelite/ace/Token_Collection.inl | 17 + dep/acelite/ace/Token_Invariants.cpp | 356 + dep/acelite/ace/Token_Invariants.h | 245 + dep/acelite/ace/Token_Manager.cpp | 274 + dep/acelite/ace/Token_Manager.h | 150 + dep/acelite/ace/Token_Manager.inl | 25 + dep/acelite/ace/Token_Request_Reply.cpp | 186 + dep/acelite/ace/Token_Request_Reply.h | 270 + dep/acelite/ace/Token_Request_Reply.inl | 205 + dep/acelite/ace/Tokenizer_T.cpp | 242 + dep/acelite/ace/Tokenizer_T.h | 241 + dep/acelite/ace/Trace.cpp | 136 + dep/acelite/ace/Trace.h | 96 + dep/acelite/ace/Truncate.h | 517 + dep/acelite/ace/Typed_SV_Message.cpp | 30 + dep/acelite/ace/Typed_SV_Message.h | 107 + dep/acelite/ace/Typed_SV_Message.inl | 96 + dep/acelite/ace/Typed_SV_Message_Queue.cpp | 56 + dep/acelite/ace/Typed_SV_Message_Queue.h | 92 + dep/acelite/ace/Typed_SV_Message_Queue.inl | 80 + dep/acelite/ace/UNIX_Addr.cpp | 151 + dep/acelite/ace/UNIX_Addr.h | 117 + dep/acelite/ace/UNIX_Addr.inl | 57 + dep/acelite/ace/UPIPE_Acceptor.cpp | 129 + dep/acelite/ace/UPIPE_Acceptor.h | 99 + dep/acelite/ace/UPIPE_Acceptor.inl | 14 + dep/acelite/ace/UPIPE_Addr.h | 33 + dep/acelite/ace/UPIPE_Connector.cpp | 101 + dep/acelite/ace/UPIPE_Connector.h | 115 + dep/acelite/ace/UPIPE_Connector.inl | 34 + dep/acelite/ace/UPIPE_Stream.cpp | 234 + dep/acelite/ace/UPIPE_Stream.h | 140 + dep/acelite/ace/UPIPE_Stream.inl | 14 + dep/acelite/ace/UTF16_Encoding_Converter.cpp | 364 + dep/acelite/ace/UTF16_Encoding_Converter.h | 86 + dep/acelite/ace/UTF16_Encoding_Converter.inl | 76 + dep/acelite/ace/UTF32_Encoding_Converter.cpp | 254 + dep/acelite/ace/UTF32_Encoding_Converter.h | 67 + dep/acelite/ace/UTF8_Encoding_Converter.cpp | 92 + dep/acelite/ace/UTF8_Encoding_Converter.h | 72 + dep/acelite/ace/UUID.cpp | 506 + dep/acelite/ace/UUID.h | 282 + dep/acelite/ace/UUID.inl | 204 + dep/acelite/ace/Unbounded_Queue.cpp | 433 + dep/acelite/ace/Unbounded_Queue.h | 297 + dep/acelite/ace/Unbounded_Queue.inl | 27 + dep/acelite/ace/Unbounded_Set.cpp | 18 + dep/acelite/ace/Unbounded_Set.h | 103 + dep/acelite/ace/Unbounded_Set.inl | 49 + dep/acelite/ace/Unbounded_Set_Ex.cpp | 499 + dep/acelite/ace/Unbounded_Set_Ex.h | 376 + dep/acelite/ace/Unbounded_Set_Ex.inl | 23 + dep/acelite/ace/Value_Ptr.h | 167 + dep/acelite/ace/Vector_T.cpp | 154 + dep/acelite/ace/Vector_T.h | 316 + dep/acelite/ace/Vector_T.inl | 107 + dep/acelite/ace/Version.h | 9 + dep/acelite/ace/Versioned_Namespace.h | 51 + dep/acelite/ace/WFMO_Reactor.cpp | 2748 ++++ dep/acelite/ace/WFMO_Reactor.h | 1368 ++ dep/acelite/ace/WFMO_Reactor.inl | 1202 ++ dep/acelite/ace/WIN32_Asynch_IO.cpp | 3782 +++++ dep/acelite/ace/WIN32_Asynch_IO.h | 1937 +++ dep/acelite/ace/WIN32_Proactor.cpp | 804 + dep/acelite/ace/WIN32_Proactor.h | 325 + dep/acelite/ace/XML_Svc_Conf.cpp | 15 + dep/acelite/ace/XML_Svc_Conf.h | 65 + dep/acelite/ace/XTI_ATM_Mcast.cpp | 70 + dep/acelite/ace/XTI_ATM_Mcast.h | 137 + dep/acelite/ace/XTI_ATM_Mcast.inl | 65 + dep/acelite/ace/ace.rc | 38 + dep/acelite/ace/ace_message_table.bin | Bin 0 -> 28 bytes dep/acelite/ace/ace_wchar.cpp | 17 + dep/acelite/ace/ace_wchar.h | 385 + dep/acelite/ace/ace_wchar.inl | 183 + dep/acelite/ace/checked_iterator.h | 58 + dep/acelite/ace/config-WinCE.h | 229 + dep/acelite/ace/config-aix-5.x.h | 326 + dep/acelite/ace/config-all.h | 93 + dep/acelite/ace/config-cray.h | 205 + dep/acelite/ace/config-cxx-common.h | 86 + dep/acelite/ace/config-cygwin32.h | 216 + dep/acelite/ace/config-doxygen.h | 128 + dep/acelite/ace/config-freebsd.h | 215 + dep/acelite/ace/config-g++-common.h | 183 + dep/acelite/ace/config-ghs-common.h | 43 + dep/acelite/ace/config-hpux-11.00.h | 451 + dep/acelite/ace/config-icc-common.h | 113 + dep/acelite/ace/config-integritySCA.h | 229 + dep/acelite/ace/config-irix6.5.x-sgic++.h | 18 + dep/acelite/ace/config-irix6.x-common.h | 254 + dep/acelite/ace/config-irix6.x-g++.h | 15 + dep/acelite/ace/config-irix6.x-sgic++.h | 36 + dep/acelite/ace/config-linux-common.h | 464 + dep/acelite/ace/config-linux.h | 75 + dep/acelite/ace/config-lite.h | 164 + dep/acelite/ace/config-lynxos.h | 199 + dep/acelite/ace/config-macosx-iphone-hardware.h | 15 + dep/acelite/ace/config-macosx-iphone-simulator.h | 9 + dep/acelite/ace/config-macosx-leopard.h | 231 + dep/acelite/ace/config-macosx-panther.h | 182 + dep/acelite/ace/config-macosx-snowleopard.h | 17 + dep/acelite/ace/config-macosx-tiger.h | 213 + dep/acelite/ace/config-macosx.h | 182 + dep/acelite/ace/config-macros.h | 655 + dep/acelite/ace/config-minimal.h | 39 + dep/acelite/ace/config-mvs.h | 127 + dep/acelite/ace/config-netbsd.h | 165 + dep/acelite/ace/config-openbsd.h | 208 + dep/acelite/ace/config-openvms.h | 198 + dep/acelite/ace/config-pharlap.h | 91 + dep/acelite/ace/config-posix-nonetworking.h | 86 + dep/acelite/ace/config-posix.h | 73 + dep/acelite/ace/config-qnx-neutrino.h | 136 + dep/acelite/ace/config-qnx-rtp-62x.h | 131 + dep/acelite/ace/config-qnx-rtp-common.h | 50 + dep/acelite/ace/config-qnx-rtp-pre62x.h | 152 + dep/acelite/ace/config-qnx-rtp.h | 25 + dep/acelite/ace/config-rtems.h | 164 + dep/acelite/ace/config-sco-5.0.0-nothread.h | 12 + dep/acelite/ace/config-sco-5.0.0.h | 90 + dep/acelite/ace/config-suncc-common.h | 67 + dep/acelite/ace/config-sunos5.10.h | 66 + dep/acelite/ace/config-sunos5.11.h | 15 + dep/acelite/ace/config-sunos5.4-g++.h | 176 + dep/acelite/ace/config-sunos5.4-sunc++-4.x.h | 186 + dep/acelite/ace/config-sunos5.5.h | 432 + dep/acelite/ace/config-sunos5.6.h | 126 + dep/acelite/ace/config-sunos5.7.h | 78 + dep/acelite/ace/config-sunos5.8.h | 39 + dep/acelite/ace/config-sunos5.9.h | 18 + dep/acelite/ace/config-tandem-nsk-mips-v2.h | 394 + dep/acelite/ace/config-tandem-nsk-mips-v3.h | 464 + dep/acelite/ace/config-tandem.h | 191 + dep/acelite/ace/config-tru64.h | 151 + dep/acelite/ace/config-unixware-7.1.0.h | 406 + dep/acelite/ace/config-unixware-7.1.0.udk.h | 457 + dep/acelite/ace/config-visualage.h | 20 + dep/acelite/ace/config-vxworks.h | 57 + dep/acelite/ace/config-vxworks6.4.h | 350 + dep/acelite/ace/config-vxworks6.5.h | 25 + dep/acelite/ace/config-vxworks6.6.h | 34 + dep/acelite/ace/config-vxworks6.7.h | 23 + dep/acelite/ace/config-vxworks6.8.h | 21 + dep/acelite/ace/config-win32-borland.h | 174 + dep/acelite/ace/config-win32-cegcc.h | 113 + dep/acelite/ace/config-win32-common.h | 701 + dep/acelite/ace/config-win32-dmc.h | 108 + dep/acelite/ace/config-win32-ghs.h | 93 + dep/acelite/ace/config-win32-interix.h | 127 + dep/acelite/ace/config-win32-mingw.h | 105 + dep/acelite/ace/config-win32-msvc-10.h | 153 + dep/acelite/ace/config-win32-msvc-7.h | 124 + dep/acelite/ace/config-win32-msvc-8.h | 163 + dep/acelite/ace/config-win32-msvc-9.h | 153 + dep/acelite/ace/config-win32-msvc.h | 175 + dep/acelite/ace/config-win32.h | 55 + dep/acelite/ace/config.h.in | 2204 +++ dep/acelite/ace/gethrtime.cpp | 60 + dep/acelite/ace/iosfwd.h | 100 + dep/acelite/ace/os_include/arpa/os_inet.h | 74 + dep/acelite/ace/os_include/net/os_if.h | 112 + dep/acelite/ace/os_include/netinet/os_in.h | 179 + dep/acelite/ace/os_include/netinet/os_tcp.h | 46 + dep/acelite/ace/os_include/os_aio.h | 47 + dep/acelite/ace/os_include/os_assert.h | 46 + dep/acelite/ace/os_include/os_byteswap.h | 41 + dep/acelite/ace/os_include/os_complex.h | 42 + dep/acelite/ace/os_include/os_cpio.h | 42 + dep/acelite/ace/os_include/os_ctype.h | 48 + dep/acelite/ace/os_include/os_dirent.h | 110 + dep/acelite/ace/os_include/os_dlfcn.h | 101 + dep/acelite/ace/os_include/os_errno.h | 458 + dep/acelite/ace/os_include/os_fcntl.h | 106 + dep/acelite/ace/os_include/os_fenv.h | 42 + dep/acelite/ace/os_include/os_float.h | 42 + dep/acelite/ace/os_include/os_fmtmsg.h | 42 + dep/acelite/ace/os_include/os_fnmatch.h | 42 + dep/acelite/ace/os_include/os_ftw.h | 44 + dep/acelite/ace/os_include/os_glob.h | 42 + dep/acelite/ace/os_include/os_grp.h | 44 + dep/acelite/ace/os_include/os_iconv.h | 44 + dep/acelite/ace/os_include/os_intrin.h | 57 + dep/acelite/ace/os_include/os_inttypes.h | 46 + dep/acelite/ace/os_include/os_iso646.h | 42 + dep/acelite/ace/os_include/os_kstat.h | 43 + dep/acelite/ace/os_include/os_langinfo.h | 44 + dep/acelite/ace/os_include/os_libgen.h | 42 + dep/acelite/ace/os_include/os_limits.h | 143 + dep/acelite/ace/os_include/os_local.h | 44 + dep/acelite/ace/os_include/os_math.h | 44 + dep/acelite/ace/os_include/os_monetary.h | 44 + dep/acelite/ace/os_include/os_mqueue.h | 44 + dep/acelite/ace/os_include/os_ndbm.h | 44 + dep/acelite/ace/os_include/os_netdb.h | 100 + dep/acelite/ace/os_include/os_nl_types.h | 42 + dep/acelite/ace/os_include/os_pdh.h | 45 + dep/acelite/ace/os_include/os_pdhmsg.h | 41 + dep/acelite/ace/os_include/os_poll.h | 42 + dep/acelite/ace/os_include/os_pthread.h | 424 + dep/acelite/ace/os_include/os_pwd.h | 58 + dep/acelite/ace/os_include/os_regex.h | 48 + dep/acelite/ace/os_include/os_sched.h | 56 + dep/acelite/ace/os_include/os_search.h | 44 + dep/acelite/ace/os_include/os_semaphore.h | 77 + dep/acelite/ace/os_include/os_setjmp.h | 42 + dep/acelite/ace/os_include/os_signal.h | 249 + dep/acelite/ace/os_include/os_spawn.h | 46 + dep/acelite/ace/os_include/os_stdarg.h | 50 + dep/acelite/ace/os_include/os_stdbool.h | 42 + dep/acelite/ace/os_include/os_stddef.h | 75 + dep/acelite/ace/os_include/os_stdint.h | 141 + dep/acelite/ace/os_include/os_stdio.h | 87 + dep/acelite/ace/os_include/os_stdlib.h | 85 + dep/acelite/ace/os_include/os_string.h | 53 + dep/acelite/ace/os_include/os_strings.h | 52 + dep/acelite/ace/os_include/os_stropts.h | 114 + dep/acelite/ace/os_include/os_syslog.h | 42 + dep/acelite/ace/os_include/os_tar.h | 42 + dep/acelite/ace/os_include/os_termios.h | 46 + dep/acelite/ace/os_include/os_tgmath.h | 45 + dep/acelite/ace/os_include/os_time.h | 119 + dep/acelite/ace/os_include/os_trace.h | 44 + dep/acelite/ace/os_include/os_typeinfo.h | 39 + dep/acelite/ace/os_include/os_ucontext.h | 48 + dep/acelite/ace/os_include/os_ulimit.h | 42 + dep/acelite/ace/os_include/os_unistd.h | 196 + dep/acelite/ace/os_include/os_utime.h | 44 + dep/acelite/ace/os_include/os_utmpx.h | 44 + dep/acelite/ace/os_include/os_wchar.h | 57 + dep/acelite/ace/os_include/os_wctype.h | 45 + dep/acelite/ace/os_include/os_wordexp.h | 44 + dep/acelite/ace/os_include/sys/os_ipc.h | 74 + dep/acelite/ace/os_include/sys/os_loadavg.h | 41 + dep/acelite/ace/os_include/sys/os_mman.h | 122 + dep/acelite/ace/os_include/sys/os_msg.h | 55 + dep/acelite/ace/os_include/sys/os_pstat.h | 42 + dep/acelite/ace/os_include/sys/os_resource.h | 104 + dep/acelite/ace/os_include/sys/os_select.h | 61 + dep/acelite/ace/os_include/sys/os_sem.h | 90 + dep/acelite/ace/os_include/sys/os_shm.h | 48 + dep/acelite/ace/os_include/sys/os_socket.h | 307 + dep/acelite/ace/os_include/sys/os_stat.h | 157 + dep/acelite/ace/os_include/sys/os_statvfs.h | 42 + dep/acelite/ace/os_include/sys/os_sysctl.h | 41 + dep/acelite/ace/os_include/sys/os_sysinfo.h | 39 + dep/acelite/ace/os_include/sys/os_time.h | 56 + dep/acelite/ace/os_include/sys/os_timeb.h | 44 + dep/acelite/ace/os_include/sys/os_times.h | 44 + dep/acelite/ace/os_include/sys/os_types.h | 157 + dep/acelite/ace/os_include/sys/os_uio.h | 77 + dep/acelite/ace/os_include/sys/os_un.h | 52 + dep/acelite/ace/os_include/sys/os_utsname.h | 42 + dep/acelite/ace/os_include/sys/os_wait.h | 97 + dep/acelite/ace/post.h | 22 + dep/acelite/ace/pre.h | 24 + dep/acelite/ace/streams.h | 138 + dep/acelite/ace/svc_export.h | 44 + dep/bzip2/CMakeLists.txt | 22 + dep/bzip2/blocksort.c | 1094 ++ dep/bzip2/bzlib.c | 1572 ++ dep/bzip2/bzlib.h | 282 + dep/bzip2/bzlib_private.h | 509 + dep/bzip2/compress.c | 672 + dep/bzip2/crctable.c | 104 + dep/bzip2/decompress.c | 626 + dep/bzip2/huffman.c | 205 + dep/bzip2/randtable.c | 84 + dep/g3dlite/AABox.cpp | 366 + dep/g3dlite/Any.cpp | 1237 ++ dep/g3dlite/BinaryFormat.cpp | 81 + dep/g3dlite/BinaryInput.cpp | 568 + dep/g3dlite/BinaryOutput.cpp | 522 + dep/g3dlite/Box.cpp | 393 + dep/g3dlite/CMakeLists.txt | 37 + dep/g3dlite/Capsule.cpp | 179 + dep/g3dlite/CollisionDetection.cpp | 2455 +++ dep/g3dlite/CoordinateFrame.cpp | 436 + dep/g3dlite/Crypto.cpp | 70 + dep/g3dlite/Cylinder.cpp | 176 + dep/g3dlite/G3D/AABox.h | 272 + dep/g3dlite/G3D/Any.h | 570 + dep/g3dlite/G3D/AnyVal.h | 512 + dep/g3dlite/G3D/AreaMemoryManager.h | 93 + dep/g3dlite/G3D/Array.h | 1274 ++ dep/g3dlite/G3D/AtomicInt32.h | 164 + dep/g3dlite/G3D/BinaryFormat.h | 140 + dep/g3dlite/G3D/BinaryInput.h | 441 + dep/g3dlite/G3D/BinaryOutput.h | 421 + dep/g3dlite/G3D/BoundsTrait.h | 20 + dep/g3dlite/G3D/Box.h | 195 + dep/g3dlite/G3D/Box2D.h | 121 + dep/g3dlite/G3D/BumpMapPreprocess.h | 61 + dep/g3dlite/G3D/Capsule.h | 90 + dep/g3dlite/G3D/CollisionDetection.h | 1205 ++ dep/g3dlite/G3D/Color1.h | 144 + dep/g3dlite/G3D/Color1uint8.h | 91 + dep/g3dlite/G3D/Color3.h | 432 + dep/g3dlite/G3D/Color3uint8.h | 110 + dep/g3dlite/G3D/Color4.h | 338 + dep/g3dlite/G3D/Color4uint8.h | 115 + dep/g3dlite/G3D/Cone.h | 68 + dep/g3dlite/G3D/ConvexPolyhedron.h | 180 + dep/g3dlite/G3D/CoordinateFrame.h | 331 + dep/g3dlite/G3D/Crypto.h | 96 + dep/g3dlite/G3D/Cylinder.h | 92 + dep/g3dlite/G3D/EqualsTrait.h | 26 + dep/g3dlite/G3D/G3D.h | 162 + dep/g3dlite/G3D/G3DAll.h | 26 + dep/g3dlite/G3D/G3DGameUnits.h | 42 + dep/g3dlite/G3D/GCamera.h | 337 + dep/g3dlite/G3D/GImage.h | 607 + dep/g3dlite/G3D/GLight.h | 106 + dep/g3dlite/G3D/GMutex.h | 123 + dep/g3dlite/G3D/GThread.h | 121 + dep/g3dlite/G3D/GUniqueID.h | 69 + dep/g3dlite/G3D/HashTrait.h | 92 + dep/g3dlite/G3D/Image1.h | 81 + dep/g3dlite/G3D/Image1uint8.h | 80 + dep/g3dlite/G3D/Image3.h | 81 + dep/g3dlite/G3D/Image3uint8.h | 85 + dep/g3dlite/G3D/Image4.h | 86 + dep/g3dlite/G3D/Image4uint8.h | 85 + dep/g3dlite/G3D/ImageFormat.h | 419 + dep/g3dlite/G3D/Intersect.h | 55 + dep/g3dlite/G3D/KDTree.h | 1667 ++ dep/g3dlite/G3D/Line.h | 105 + dep/g3dlite/G3D/LineSegment.h | 115 + dep/g3dlite/G3D/Log.h | 109 + dep/g3dlite/G3D/Map2D.h | 667 + dep/g3dlite/G3D/Matrix.h | 634 + dep/g3dlite/G3D/Matrix2.h | 69 + dep/g3dlite/G3D/Matrix3.h | 366 + dep/g3dlite/G3D/Matrix4.h | 249 + dep/g3dlite/G3D/MemoryManager.h | 93 + dep/g3dlite/G3D/MeshAlg.h | 683 + dep/g3dlite/G3D/MeshBuilder.h | 82 + dep/g3dlite/G3D/NetAddress.h | 132 + dep/g3dlite/G3D/NetworkDevice.h | 738 + dep/g3dlite/G3D/ParseError.h | 59 + dep/g3dlite/G3D/PhysicsFrame.h | 74 + dep/g3dlite/G3D/Plane.h | 161 + dep/g3dlite/G3D/PointHashGrid.h | 917 ++ dep/g3dlite/G3D/PointKDTree.h | 1185 ++ dep/g3dlite/G3D/Pointer.h | 292 + dep/g3dlite/G3D/PositionTrait.h | 7 + dep/g3dlite/G3D/PrecomputedRandom.h | 110 + dep/g3dlite/G3D/Quat.h | 725 + dep/g3dlite/G3D/Quat.inl | 36 + dep/g3dlite/G3D/Queue.h | 364 + dep/g3dlite/G3D/Random.h | 139 + dep/g3dlite/G3D/Ray.h | 371 + dep/g3dlite/G3D/Rect2D.h | 417 + dep/g3dlite/G3D/ReferenceCount.h | 570 + dep/g3dlite/G3D/RegistryUtil.h | 97 + dep/g3dlite/G3D/Set.h | 186 + dep/g3dlite/G3D/SmallArray.h | 155 + dep/g3dlite/G3D/Sphere.h | 148 + dep/g3dlite/G3D/Spline.h | 367 + dep/g3dlite/G3D/Stopwatch.h | 144 + dep/g3dlite/G3D/System.h | 507 + dep/g3dlite/G3D/Table.h | 924 ++ dep/g3dlite/G3D/TextInput.h | 801 + dep/g3dlite/G3D/TextOutput.h | 249 + dep/g3dlite/G3D/ThreadSet.h | 87 + dep/g3dlite/G3D/Triangle.h | 160 + dep/g3dlite/G3D/UprightFrame.h | 83 + dep/g3dlite/G3D/Vector2.h | 454 + dep/g3dlite/G3D/Vector2.inl | 18 + dep/g3dlite/G3D/Vector2int16.h | 127 + dep/g3dlite/G3D/Vector3.h | 798 + dep/g3dlite/G3D/Vector3.inl | 249 + dep/g3dlite/G3D/Vector3int16.h | 127 + dep/g3dlite/G3D/Vector3int32.h | 128 + dep/g3dlite/G3D/Vector4.h | 716 + dep/g3dlite/G3D/Vector4.inl | 191 + dep/g3dlite/G3D/Vector4int8.h | 113 + dep/g3dlite/G3D/WeakCache.h | 122 + dep/g3dlite/G3D/Welder.h | 82 + dep/g3dlite/G3D/WrapMode.h | 93 + dep/g3dlite/G3D/constants.h | 129 + dep/g3dlite/G3D/debug.h | 66 + dep/g3dlite/G3D/debugAssert.h | 233 + dep/g3dlite/G3D/debugPrintf.h | 62 + dep/g3dlite/G3D/enumclass.h | 147 + dep/g3dlite/G3D/fileutils.h | 254 + dep/g3dlite/G3D/filter.h | 29 + dep/g3dlite/G3D/format.h | 44 + dep/g3dlite/G3D/g3dfnmatch.h | 83 + dep/g3dlite/G3D/g3dmath.h | 845 ++ dep/g3dlite/G3D/g3dmath.inl | 288 + dep/g3dlite/G3D/platform.h | 331 + dep/g3dlite/G3D/prompt.h | 67 + dep/g3dlite/G3D/serialize.h | 30 + dep/g3dlite/G3D/splinefunc.h | 118 + dep/g3dlite/G3D/stringutils.h | 140 + dep/g3dlite/G3D/uint128.h | 51 + dep/g3dlite/G3D/units.h | 126 + dep/g3dlite/G3D/vectorMath.h | 235 + dep/g3dlite/Line.cpp | 89 + dep/g3dlite/LineSegment.cpp | 236 + dep/g3dlite/Log.cpp | 146 + dep/g3dlite/Matrix3.cpp | 1927 +++ dep/g3dlite/Matrix4.cpp | 523 + dep/g3dlite/MemoryManager.cpp | 91 + dep/g3dlite/Plane.cpp | 149 + dep/g3dlite/Quat.cpp | 583 + dep/g3dlite/Random.cpp | 212 + dep/g3dlite/Ray.cpp | 218 + dep/g3dlite/ReferenceCount.cpp | 61 + dep/g3dlite/RegistryUtil.cpp | 290 + dep/g3dlite/Sphere.cpp | 223 + dep/g3dlite/System.cpp | 1746 +++ dep/g3dlite/TextInput.cpp | 1136 ++ dep/g3dlite/TextOutput.cpp | 452 + dep/g3dlite/Triangle.cpp | 186 + dep/g3dlite/UprightFrame.cpp | 132 + dep/g3dlite/Vector2.cpp | 224 + dep/g3dlite/Vector3.cpp | 507 + dep/g3dlite/Vector4.cpp | 520 + dep/g3dlite/debugAssert.cpp | 389 + dep/g3dlite/fileutils.cpp | 1165 ++ dep/g3dlite/format.cpp | 164 + dep/g3dlite/g3dfnmatch.cpp | 204 + dep/g3dlite/g3dmath.cpp | 108 + dep/g3dlite/prompt.cpp | 729 + dep/g3dlite/stringutils.cpp | 275 + dep/gsoap/CMakeLists.txt | 11 + dep/gsoap/soapC.cpp | 1645 ++ dep/gsoap/soapH.h | 239 + dep/gsoap/soapServer.cpp | 127 + dep/gsoap/soapStub.h | 184 + dep/gsoap/stdsoap2.cpp | 15198 +++++++++++++++++++ dep/gsoap/stdsoap2.h | 2360 +++ dep/jemalloc/CMakeLists.txt | 25 + dep/jemalloc/arena.c | 2446 +++ dep/jemalloc/base.c | 106 + dep/jemalloc/chunk.c | 150 + dep/jemalloc/chunk_dss.c | 268 + dep/jemalloc/chunk_mmap.c | 201 + dep/jemalloc/chunk_swap.c | 383 + dep/jemalloc/ckh.c | 601 + dep/jemalloc/ctl.c | 1482 ++ dep/jemalloc/extent.c | 41 + dep/jemalloc/hash.c | 2 + dep/jemalloc/huge.c | 298 + dep/jemalloc/jemalloc.c | 1349 ++ dep/jemalloc/jemalloc/internal/arena.h | 537 + dep/jemalloc/jemalloc/internal/base.h | 24 + dep/jemalloc/jemalloc/internal/chunk.h | 61 + dep/jemalloc/jemalloc/internal/chunk_dss.h | 29 + dep/jemalloc/jemalloc/internal/chunk_mmap.h | 20 + dep/jemalloc/jemalloc/internal/chunk_swap.h | 33 + dep/jemalloc/jemalloc/internal/ckh.h | 95 + dep/jemalloc/jemalloc/internal/ctl.h | 117 + dep/jemalloc/jemalloc/internal/extent.h | 49 + dep/jemalloc/jemalloc/internal/hash.h | 70 + dep/jemalloc/jemalloc/internal/huge.h | 38 + dep/jemalloc/jemalloc/internal/jemalloc_internal.h | 561 + .../jemalloc/internal/jemalloc_internal.h.in | 561 + dep/jemalloc/jemalloc/internal/mb.h | 108 + dep/jemalloc/jemalloc/internal/mutex.h | 61 + dep/jemalloc/jemalloc/internal/prof.h | 171 + dep/jemalloc/jemalloc/internal/ql.h | 83 + dep/jemalloc/jemalloc/internal/qr.h | 67 + dep/jemalloc/jemalloc/internal/rb.h | 973 ++ dep/jemalloc/jemalloc/internal/stats.h | 174 + dep/jemalloc/jemalloc/internal/tcache.h | 380 + dep/jemalloc/jemalloc/internal/totally_not_p_r_n.h | 60 + dep/jemalloc/jemalloc/jemalloc.h | 42 + dep/jemalloc/jemalloc/jemalloc.h.in | 42 + dep/jemalloc/jemalloc/jemalloc_defs.h | 102 + dep/jemalloc/jemalloc/jemalloc_defs.h.in | 101 + dep/jemalloc/mb.c | 2 + dep/jemalloc/mutex.c | 70 + dep/jemalloc/prof.c | 1328 ++ dep/jemalloc/stats.c | 717 + dep/jemalloc/tcache.c | 403 + dep/libmpq/AUTHORS | 10 + dep/libmpq/CMakeLists.txt | 34 + dep/libmpq/COPYING | 339 + dep/libmpq/FAQ | 68 + dep/libmpq/INSTALL | 182 + dep/libmpq/Makefile.am | 26 + dep/libmpq/NEWS | 76 + dep/libmpq/README | 34 + dep/libmpq/THANKS | 21 + dep/libmpq/TODO | 10 + dep/libmpq/autogen.sh | 19 + dep/libmpq/bindings/Makefile.am | 6 + dep/libmpq/bindings/d/Makefile.am | 6 + dep/libmpq/bindings/d/dsss.conf | 2 + dep/libmpq/bindings/d/mpq.d | 318 + dep/libmpq/bindings/python/Makefile.am | 5 + dep/libmpq/bindings/python/mpq-info | 16 + dep/libmpq/bindings/python/mpq.py | 322 + dep/libmpq/config.h | 74 + dep/libmpq/configure.ac | 84 + dep/libmpq/debian/changelog | 35 + dep/libmpq/debian/compat | 1 + dep/libmpq/debian/control | 50 + dep/libmpq/debian/copyright | 23 + dep/libmpq/debian/libmpq-dev.dirs | 6 + dep/libmpq/debian/libmpq-dev.install | 6 + dep/libmpq/debian/libmpq0.dirs | 1 + dep/libmpq/debian/libmpq0.docs | 6 + dep/libmpq/debian/libmpq0.install | 1 + dep/libmpq/debian/python-mpq.install | 1 + dep/libmpq/debian/rules | 112 + dep/libmpq/doc/Makefile.am | 5 + dep/libmpq/doc/man1/Makefile.am | 9 + dep/libmpq/doc/man1/libmpq-config.1 | 69 + dep/libmpq/doc/man3/Makefile.am | 31 + dep/libmpq/doc/man3/libmpq.3 | 207 + dep/libmpq/doc/man3/libmpq__archive_close.3 | 57 + dep/libmpq/doc/man3/libmpq__archive_files.3 | 50 + dep/libmpq/doc/man3/libmpq__archive_offset.3 | 51 + dep/libmpq/doc/man3/libmpq__archive_open.3 | 71 + dep/libmpq/doc/man3/libmpq__archive_packed_size.3 | 51 + .../doc/man3/libmpq__archive_unpacked_size.3 | 51 + dep/libmpq/doc/man3/libmpq__archive_version.3 | 48 + dep/libmpq/doc/man3/libmpq__block_close_offset.3 | 53 + dep/libmpq/doc/man3/libmpq__block_open_offset.3 | 65 + dep/libmpq/doc/man3/libmpq__block_read.3 | 78 + dep/libmpq/doc/man3/libmpq__block_unpacked_size.3 | 59 + dep/libmpq/doc/man3/libmpq__file_blocks.3 | 54 + dep/libmpq/doc/man3/libmpq__file_compressed.3 | 54 + dep/libmpq/doc/man3/libmpq__file_encrypted.3 | 54 + dep/libmpq/doc/man3/libmpq__file_imploded.3 | 54 + dep/libmpq/doc/man3/libmpq__file_number.3 | 52 + dep/libmpq/doc/man3/libmpq__file_offset.3 | 55 + dep/libmpq/doc/man3/libmpq__file_packed_size.3 | 55 + dep/libmpq/doc/man3/libmpq__file_read.3 | 77 + dep/libmpq/doc/man3/libmpq__file_unpacked_size.3 | 55 + dep/libmpq/doc/man3/libmpq__strerror.3 | 45 + dep/libmpq/doc/man3/libmpq__version.3 | 45 + dep/libmpq/libmpq-config.in | 57 + dep/libmpq/libmpq.pc.in | 10 + dep/libmpq/libmpq/Makefile.am | 23 + dep/libmpq/libmpq/common.c | 220 + dep/libmpq/libmpq/common.h | 61 + dep/libmpq/libmpq/crypt_buf.h | 217 + dep/libmpq/libmpq/explode.c | 602 + dep/libmpq/libmpq/explode.h | 87 + dep/libmpq/libmpq/extract.c | 361 + dep/libmpq/libmpq/extract.h | 106 + dep/libmpq/libmpq/huffman.c | 1101 ++ dep/libmpq/libmpq/huffman.h | 151 + dep/libmpq/libmpq/mpq-internal.h | 145 + dep/libmpq/libmpq/mpq.c | 1004 ++ dep/libmpq/libmpq/mpq.h | 101 + dep/libmpq/libmpq/pack_begin.h | 34 + dep/libmpq/libmpq/pack_end.h | 31 + dep/libmpq/libmpq/platform.h | 28 + dep/libmpq/libmpq/wave.c | 250 + dep/libmpq/libmpq/wave.h | 45 + dep/libmpq/tools/Makefile.am | 8 + dep/libmpq/tools/crypt_buf_gen.c | 85 + dep/libmpq/win/config.h | 81 + dep/libmpq/win/dirent.h | 230 + dep/libmpq/win/stdint.h | 247 + dep/mersennetwister/MersenneTwister.h | 405 + dep/sockets/Base64.cpp | 262 + dep/sockets/CMakeLists.txt | 21 + dep/sockets/Exception.cpp | 45 + dep/sockets/Ipv4Address.cpp | 192 + dep/sockets/Ipv6Address.cpp | 247 + dep/sockets/Lock.cpp | 52 + dep/sockets/Makefile | 136 + dep/sockets/Mutex.cpp | 77 + dep/sockets/Parse.cpp | 318 + dep/sockets/ResolvServer.cpp | 92 + dep/sockets/ResolvSocket.cpp | 426 + dep/sockets/Socket.cpp | 1726 +++ dep/sockets/SocketHandler.cpp | 1377 ++ dep/sockets/StdoutLog.cpp | 98 + dep/sockets/StreamSocket.cpp | 145 + dep/sockets/TcpSocket.cpp | 1681 ++ dep/sockets/Thread.cpp | 154 + dep/sockets/UdpSocket.cpp | 810 + dep/sockets/Utility.cpp | 960 ++ dep/sockets/include/Base64.h | 77 + dep/sockets/include/Exception.h | 55 + dep/sockets/include/File.h | 82 + dep/sockets/include/IFile.h | 71 + dep/sockets/include/ISocketHandler.h | 231 + dep/sockets/include/Ipv4Address.h | 95 + dep/sockets/include/Ipv6Address.h | 105 + dep/sockets/include/ListenSocket.h | 418 + dep/sockets/include/Lock.h | 58 + dep/sockets/include/Mutex.h | 68 + dep/sockets/include/Parse.h | 100 + dep/sockets/include/ResolvServer.h | 72 + dep/sockets/include/ResolvSocket.h | 105 + dep/sockets/include/SctpSocket.h | 108 + dep/sockets/include/Socket.h | 735 + dep/sockets/include/SocketAddress.h | 93 + dep/sockets/include/SocketHandler.h | 265 + dep/sockets/include/StdLog.h | 73 + dep/sockets/include/StdoutLog.h | 55 + dep/sockets/include/StreamSocket.h | 124 + dep/sockets/include/TcpSocket.h | 356 + dep/sockets/include/Thread.h | 100 + dep/sockets/include/UdpSocket.h | 215 + dep/sockets/include/Utility.h | 186 + dep/sockets/include/socket_include.h | 290 + dep/sockets/include/sockets-config.h | 90 + dep/sockets/network_kist.txt | 20 + dep/sockets/socket_include.cpp | 89 + dep/utf8cpp/utf8.h | 34 + dep/utf8cpp/utf8/checked.h | 323 + dep/utf8cpp/utf8/core.h | 358 + dep/utf8cpp/utf8/unchecked.h | 228 + dep/zlib/CMakeLists.txt | 30 + dep/zlib/adler32.c | 169 + dep/zlib/compress.c | 80 + dep/zlib/crc32.c | 442 + dep/zlib/crc32.h | 441 + dep/zlib/deflate.c | 1834 +++ dep/zlib/deflate.h | 342 + dep/zlib/example.c | 565 + dep/zlib/gzclose.c | 25 + dep/zlib/gzguts.h | 132 + dep/zlib/gzlib.c | 537 + dep/zlib/gzread.c | 653 + dep/zlib/gzwrite.c | 531 + dep/zlib/infback.c | 632 + dep/zlib/inffast.c | 340 + dep/zlib/inffast.h | 11 + dep/zlib/inffixed.h | 94 + dep/zlib/inflate.c | 1480 ++ dep/zlib/inflate.h | 122 + dep/zlib/inftrees.c | 330 + dep/zlib/inftrees.h | 62 + dep/zlib/minigzip.c | 440 + dep/zlib/trees.c | 1244 ++ dep/zlib/trees.h | 128 + dep/zlib/uncompr.c | 59 + dep/zlib/zconf.h | 428 + dep/zlib/zlib.h | 1613 ++ dep/zlib/zutil.c | 318 + dep/zlib/zutil.h | 274 + doc/AuctionHouseBot.txt | 236 + doc/EventAI.txt | 868 ++ doc/HowToScript.txt | 27 + doc/TextTables.txt | 87 + doc/UnixInstall.txt | 60 + doc/gpl-2.0.txt | 339 + docs/AuctionHouseBot.txt | 236 - docs/EventAI.txt | 868 -- docs/HowToScript.txt | 27 - docs/TextTables.txt | 87 - docs/UnixInstall.txt | 60 - docs/gpl-2.0.txt | 339 - externals/CMakeLists.txt | 28 - externals/PackageList.txt | 45 - externals/SFMT/SFMT-alti.h | 156 - externals/SFMT/SFMT-params.h | 97 - externals/SFMT/SFMT-sse2.h | 121 - externals/SFMT/SFMT.c | 620 - externals/SFMT/SFMT.h | 157 - externals/ace/ACE.cpp | 3517 ----- externals/ace/ACE.h | 849 -- externals/ace/ACE.inl | 348 - externals/ace/ACE.pc.in | 10 - externals/ace/ACE_crc32.cpp | 161 - externals/ace/ACE_crc_ccitt.cpp | 128 - externals/ace/ACE_export.h | 76 - externals/ace/ARGV.cpp | 383 - externals/ace/ARGV.h | 333 - externals/ace/ARGV.inl | 104 - externals/ace/ATM_Acceptor.cpp | 309 - externals/ace/ATM_Acceptor.h | 123 - externals/ace/ATM_Acceptor.inl | 43 - externals/ace/ATM_Addr.cpp | 522 - externals/ace/ATM_Addr.h | 197 - externals/ace/ATM_Addr.inl | 37 - externals/ace/ATM_Connector.cpp | 138 - externals/ace/ATM_Connector.h | 164 - externals/ace/ATM_Connector.inl | 132 - externals/ace/ATM_Params.cpp | 20 - externals/ace/ATM_Params.h | 214 - externals/ace/ATM_Params.inl | 235 - externals/ace/ATM_QoS.cpp | 631 - externals/ace/ATM_QoS.h | 115 - externals/ace/ATM_QoS.inl | 29 - externals/ace/ATM_Stream.cpp | 290 - externals/ace/ATM_Stream.h | 107 - externals/ace/ATM_Stream.inl | 133 - externals/ace/Acceptor.cpp | 1246 -- externals/ace/Acceptor.h | 695 - externals/ace/Activation_Queue.cpp | 138 - externals/ace/Activation_Queue.h | 168 - externals/ace/Activation_Queue.inl | 31 - externals/ace/Active_Map_Manager.cpp | 9 - externals/ace/Active_Map_Manager.h | 116 - externals/ace/Active_Map_Manager.inl | 95 - externals/ace/Active_Map_Manager_T.cpp | 22 - externals/ace/Active_Map_Manager_T.h | 211 - externals/ace/Active_Map_Manager_T.inl | 311 - externals/ace/Addr.cpp | 71 - externals/ace/Addr.h | 103 - externals/ace/Addr.inl | 57 - externals/ace/Arg_Shifter.cpp | 229 - externals/ace/Arg_Shifter.h | 221 - externals/ace/Argv_Type_Converter.cpp | 196 - externals/ace/Argv_Type_Converter.h | 119 - externals/ace/Argv_Type_Converter.inl | 44 - externals/ace/Array.h | 29 - externals/ace/Array_Base.cpp | 235 - externals/ace/Array_Base.h | 256 - externals/ace/Array_Base.inl | 146 - externals/ace/Array_Map.cpp | 299 - externals/ace/Array_Map.h | 300 - externals/ace/Array_Map.inl | 133 - externals/ace/Assert.cpp | 24 - externals/ace/Assert.h | 40 - externals/ace/Asynch_Acceptor.cpp | 514 - externals/ace/Asynch_Acceptor.h | 281 - externals/ace/Asynch_Connector.cpp | 296 - externals/ace/Asynch_Connector.h | 171 - externals/ace/Asynch_IO.cpp | 1414 -- externals/ace/Asynch_IO.h | 1761 --- externals/ace/Asynch_IO_Impl.cpp | 117 - externals/ace/Asynch_IO_Impl.h | 816 - externals/ace/Asynch_IO_Impl.inl | 106 - externals/ace/Asynch_Pseudo_Task.cpp | 130 - externals/ace/Asynch_Pseudo_Task.h | 73 - externals/ace/Atomic_Op.cpp | 310 - externals/ace/Atomic_Op.h | 355 - externals/ace/Atomic_Op.inl | 582 - externals/ace/Atomic_Op_GCC_T.cpp | 29 - externals/ace/Atomic_Op_GCC_T.h | 136 - externals/ace/Atomic_Op_GCC_T.inl | 148 - externals/ace/Atomic_Op_Sparc.c | 187 - externals/ace/Atomic_Op_Sparc.h | 14 - externals/ace/Atomic_Op_T.cpp | 82 - externals/ace/Atomic_Op_T.h | 369 - externals/ace/Atomic_Op_T.inl | 340 - externals/ace/Auto_Event.cpp | 49 - externals/ace/Auto_Event.h | 73 - externals/ace/Auto_Event.inl | 12 - externals/ace/Auto_Functor.cpp | 39 - externals/ace/Auto_Functor.h | 127 - externals/ace/Auto_Functor.inl | 134 - externals/ace/Auto_IncDec_T.cpp | 34 - externals/ace/Auto_IncDec_T.h | 91 - externals/ace/Auto_IncDec_T.inl | 25 - externals/ace/Auto_Ptr.cpp | 21 - externals/ace/Auto_Ptr.h | 242 - externals/ace/Auto_Ptr.inl | 171 - externals/ace/Barrier.cpp | 196 - externals/ace/Barrier.h | 215 - externals/ace/Barrier.inl | 22 - externals/ace/Base_Thread_Adapter.cpp | 128 - externals/ace/Base_Thread_Adapter.h | 195 - externals/ace/Base_Thread_Adapter.inl | 48 - externals/ace/Based_Pointer_Repository.cpp | 119 - externals/ace/Based_Pointer_Repository.h | 94 - externals/ace/Based_Pointer_T.cpp | 121 - externals/ace/Based_Pointer_T.h | 205 - externals/ace/Based_Pointer_T.inl | 139 - externals/ace/Basic_Stats.cpp | 78 - externals/ace/Basic_Stats.h | 87 - externals/ace/Basic_Stats.inl | 53 - externals/ace/Basic_Types.cpp | 139 - externals/ace/Basic_Types.h | 962 -- externals/ace/Basic_Types.inl | 954 -- externals/ace/Bound_Ptr.h | 388 - externals/ace/Bound_Ptr.inl | 494 - externals/ace/CDR_Base.cpp | 802 - externals/ace/CDR_Base.h | 382 - externals/ace/CDR_Base.inl | 255 - externals/ace/CDR_Size.cpp | 262 - externals/ace/CDR_Size.h | 241 - externals/ace/CDR_Size.inl | 424 - externals/ace/CDR_Stream.cpp | 2063 --- externals/ace/CDR_Stream.h | 1402 -- externals/ace/CDR_Stream.inl | 1727 --- externals/ace/CE_Screen_Output.cpp | 158 - externals/ace/CE_Screen_Output.h | 109 - externals/ace/CMakeLists.txt | 337 - externals/ace/CORBA_macros.h | 575 - externals/ace/Cache_Map_Manager_T.cpp | 420 - externals/ace/Cache_Map_Manager_T.h | 405 - externals/ace/Cache_Map_Manager_T.inl | 245 - externals/ace/Cached_Connect_Strategy_T.cpp | 734 - externals/ace/Cached_Connect_Strategy_T.h | 263 - externals/ace/Caching_Strategies_T.cpp | 59 - externals/ace/Caching_Strategies_T.h | 552 - externals/ace/Caching_Strategies_T.inl | 456 - externals/ace/Caching_Utility_T.cpp | 499 - externals/ace/Caching_Utility_T.h | 347 - externals/ace/Capabilities.cpp | 355 - externals/ace/Capabilities.h | 221 - externals/ace/Capabilities.inl | 52 - externals/ace/Cleanup.cpp | 181 - externals/ace/Cleanup.h | 160 - externals/ace/Cleanup.inl | 30 - externals/ace/Cleanup_Strategies_T.cpp | 95 - externals/ace/Cleanup_Strategies_T.h | 149 - externals/ace/Codecs.cpp | 234 - externals/ace/Codecs.h | 121 - externals/ace/Codeset_IBM1047.cpp | 309 - externals/ace/Codeset_IBM1047.h | 127 - externals/ace/Codeset_Registry.cpp | 111 - externals/ace/Codeset_Registry.h | 104 - externals/ace/Codeset_Registry.inl | 102 - externals/ace/Codeset_Registry_db.cpp | 33 - externals/ace/Codeset_Symbols.h | 220 - externals/ace/Condition_Recursive_Thread_Mutex.cpp | 129 - externals/ace/Condition_Recursive_Thread_Mutex.h | 116 - externals/ace/Condition_T.cpp | 127 - externals/ace/Condition_T.h | 167 - externals/ace/Condition_T.inl | 51 - externals/ace/Condition_Thread_Mutex.cpp | 126 - externals/ace/Condition_Thread_Mutex.h | 190 - externals/ace/Condition_Thread_Mutex.inl | 74 - externals/ace/Configuration.cpp | 2152 --- externals/ace/Configuration.h | 919 -- externals/ace/Configuration.inl | 13 - externals/ace/Configuration_Import_Export.cpp | 670 - externals/ace/Configuration_Import_Export.h | 215 - externals/ace/Connection_Recycling_Strategy.cpp | 13 - externals/ace/Connection_Recycling_Strategy.h | 63 - externals/ace/Connector.cpp | 991 -- externals/ace/Connector.h | 569 - externals/ace/Containers.cpp | 12 - externals/ace/Containers.h | 71 - externals/ace/Containers.inl | 25 - externals/ace/Containers_T.cpp | 1932 --- externals/ace/Containers_T.h | 2068 --- externals/ace/Containers_T.inl | 479 - externals/ace/Copy_Disabled.cpp | 23 - externals/ace/Copy_Disabled.h | 65 - externals/ace/Countdown_Time.cpp | 59 - externals/ace/Countdown_Time.h | 81 - externals/ace/Countdown_Time.inl | 20 - externals/ace/DEV.cpp | 43 - externals/ace/DEV.h | 78 - externals/ace/DEV.inl | 18 - externals/ace/DEV_Addr.cpp | 108 - externals/ace/DEV_Addr.h | 90 - externals/ace/DEV_Addr.inl | 51 - externals/ace/DEV_Connector.cpp | 53 - externals/ace/DEV_Connector.h | 110 - externals/ace/DEV_Connector.inl | 33 - externals/ace/DEV_IO.cpp | 131 - externals/ace/DEV_IO.h | 185 - externals/ace/DEV_IO.inl | 126 - externals/ace/DLL.cpp | 267 - externals/ace/DLL.h | 196 - externals/ace/DLL_Manager.cpp | 787 - externals/ace/DLL_Manager.h | 269 - externals/ace/Date_Time.cpp | 10 - externals/ace/Date_Time.h | 125 - externals/ace/Date_Time.inl | 219 - externals/ace/Default_Constants.h | 605 - externals/ace/Dev_Poll_Reactor.cpp | 2610 ---- externals/ace/Dev_Poll_Reactor.h | 1208 -- externals/ace/Dev_Poll_Reactor.inl | 134 - externals/ace/Dirent.cpp | 7 - externals/ace/Dirent.h | 122 - externals/ace/Dirent.inl | 99 - externals/ace/Dirent_Selector.cpp | 59 - externals/ace/Dirent_Selector.h | 75 - externals/ace/Dirent_Selector.inl | 19 - externals/ace/Dump.cpp | 141 - externals/ace/Dump.h | 172 - externals/ace/Dump_T.cpp | 48 - externals/ace/Dump_T.h | 83 - externals/ace/Dynamic.cpp | 34 - externals/ace/Dynamic.h | 75 - externals/ace/Dynamic.inl | 34 - externals/ace/Dynamic_Message_Strategy.cpp | 205 - externals/ace/Dynamic_Message_Strategy.h | 217 - externals/ace/Dynamic_Message_Strategy.inl | 75 - externals/ace/Dynamic_Service.cpp | 63 - externals/ace/Dynamic_Service.h | 89 - externals/ace/Dynamic_Service.inl | 39 - externals/ace/Dynamic_Service_Base.cpp | 106 - externals/ace/Dynamic_Service_Base.h | 73 - externals/ace/Dynamic_Service_Dependency.cpp | 51 - externals/ace/Dynamic_Service_Dependency.h | 70 - externals/ace/Encoding_Converter.cpp | 12 - externals/ace/Encoding_Converter.h | 70 - externals/ace/Encoding_Converter_Factory.cpp | 74 - externals/ace/Encoding_Converter_Factory.h | 54 - externals/ace/Env_Value_T.cpp | 12 - externals/ace/Env_Value_T.h | 166 - externals/ace/Env_Value_T.inl | 60 - externals/ace/Event.cpp | 93 - externals/ace/Event.h | 143 - externals/ace/Event.inl | 18 - externals/ace/Event_Handler.cpp | 394 - externals/ace/Event_Handler.h | 389 - externals/ace/Event_Handler.inl | 12 - externals/ace/Event_Handler_T.cpp | 125 - externals/ace/Event_Handler_T.h | 191 - externals/ace/Event_Handler_T.inl | 135 - externals/ace/Exception_Macros.h | 55 - externals/ace/FIFO.cpp | 78 - externals/ace/FIFO.h | 85 - externals/ace/FIFO.inl | 25 - externals/ace/FIFO_Recv.cpp | 88 - externals/ace/FIFO_Recv.h | 85 - externals/ace/FIFO_Recv.inl | 24 - externals/ace/FIFO_Recv_Msg.cpp | 67 - externals/ace/FIFO_Recv_Msg.h | 138 - externals/ace/FIFO_Recv_Msg.inl | 137 - externals/ace/FIFO_Send.cpp | 58 - externals/ace/FIFO_Send.h | 75 - externals/ace/FIFO_Send.inl | 24 - externals/ace/FIFO_Send_Msg.cpp | 80 - externals/ace/FIFO_Send_Msg.h | 91 - externals/ace/FIFO_Send_Msg.inl | 53 - externals/ace/FILE.cpp | 147 - externals/ace/FILE.h | 139 - externals/ace/FILE.inl | 18 - externals/ace/FILE_Addr.cpp | 124 - externals/ace/FILE_Addr.h | 89 - externals/ace/FILE_Addr.inl | 34 - externals/ace/FILE_Connector.cpp | 84 - externals/ace/FILE_Connector.h | 113 - externals/ace/FILE_Connector.inl | 35 - externals/ace/FILE_IO.cpp | 145 - externals/ace/FILE_IO.h | 170 - externals/ace/FILE_IO.inl | 152 - externals/ace/File_Lock.cpp | 72 - externals/ace/File_Lock.h | 170 - externals/ace/File_Lock.inl | 96 - externals/ace/Filecache.cpp | 746 - externals/ace/Filecache.h | 356 - externals/ace/Flag_Manip.cpp | 95 - externals/ace/Flag_Manip.h | 58 - externals/ace/Flag_Manip.inl | 26 - externals/ace/Framework_Component.cpp | 279 - externals/ace/Framework_Component.h | 210 - externals/ace/Framework_Component.inl | 39 - externals/ace/Framework_Component_T.cpp | 33 - externals/ace/Framework_Component_T.h | 71 - externals/ace/Free_List.cpp | 163 - externals/ace/Free_List.h | 150 - externals/ace/Functor.cpp | 43 - externals/ace/Functor.h | 523 - externals/ace/Functor.inl | 284 - externals/ace/Functor_String.cpp | 7 - externals/ace/Functor_String.h | 129 - externals/ace/Functor_String.inl | 56 - externals/ace/Functor_T.cpp | 49 - externals/ace/Functor_T.h | 158 - externals/ace/Functor_T.inl | 42 - externals/ace/Future.cpp | 434 - externals/ace/Future.h | 387 - externals/ace/Future_Set.cpp | 136 - externals/ace/Future_Set.h | 146 - externals/ace/Get_Opt.cpp | 734 - externals/ace/Get_Opt.h | 494 - externals/ace/Get_Opt.inl | 97 - externals/ace/Global_Macros.h | 1121 -- externals/ace/Guard_T.cpp | 61 - externals/ace/Guard_T.h | 365 - externals/ace/Guard_T.inl | 170 - externals/ace/Handle_Gobbler.h | 68 - externals/ace/Handle_Gobbler.inl | 79 - externals/ace/Handle_Ops.cpp | 48 - externals/ace/Handle_Ops.h | 50 - externals/ace/Handle_Set.cpp | 565 - externals/ace/Handle_Set.h | 236 - externals/ace/Handle_Set.inl | 193 - externals/ace/Hash_Cache_Map_Manager_T.cpp | 232 - externals/ace/Hash_Cache_Map_Manager_T.h | 214 - externals/ace/Hash_Cache_Map_Manager_T.inl | 73 - externals/ace/Hash_Map_Manager.h | 31 - externals/ace/Hash_Map_Manager_T.cpp | 542 - externals/ace/Hash_Map_Manager_T.h | 1306 -- externals/ace/Hash_Map_Manager_T.inl | 1246 -- externals/ace/Hash_Map_With_Allocator_T.cpp | 35 - externals/ace/Hash_Map_With_Allocator_T.h | 112 - externals/ace/Hash_Map_With_Allocator_T.inl | 82 - externals/ace/Hash_Multi_Map_Manager_T.cpp | 605 - externals/ace/Hash_Multi_Map_Manager_T.h | 967 -- externals/ace/Hash_Multi_Map_Manager_T.inl | 994 -- externals/ace/Hashable.cpp | 36 - externals/ace/Hashable.h | 65 - externals/ace/Hashable.inl | 14 - externals/ace/High_Res_Timer.cpp | 530 - externals/ace/High_Res_Timer.h | 310 - externals/ace/High_Res_Timer.inl | 153 - externals/ace/ICMP_Socket.cpp | 186 - externals/ace/ICMP_Socket.h | 110 - externals/ace/INET_Addr.cpp | 1148 -- externals/ace/INET_Addr.h | 390 - externals/ace/INET_Addr.inl | 255 - externals/ace/IOStream.cpp | 665 - externals/ace/IOStream.h | 512 - externals/ace/IOStream_T.cpp | 247 - externals/ace/IOStream_T.h | 297 - externals/ace/IOStream_T.inl | 123 - externals/ace/IO_Cntl_Msg.cpp | 51 - externals/ace/IO_Cntl_Msg.h | 112 - externals/ace/IO_Cntl_Msg.inl | 61 - externals/ace/IO_SAP.cpp | 142 - externals/ace/IO_SAP.h | 96 - externals/ace/IO_SAP.inl | 42 - externals/ace/IPC_SAP.cpp | 193 - externals/ace/IPC_SAP.h | 96 - externals/ace/IPC_SAP.inl | 40 - externals/ace/If_Then_Else.h | 89 - externals/ace/Init_ACE.cpp | 45 - externals/ace/Init_ACE.h | 70 - externals/ace/Intrusive_Auto_Ptr.cpp | 22 - externals/ace/Intrusive_Auto_Ptr.h | 165 - externals/ace/Intrusive_Auto_Ptr.inl | 147 - externals/ace/Intrusive_List.cpp | 157 - externals/ace/Intrusive_List.h | 144 - externals/ace/Intrusive_List.inl | 40 - externals/ace/Intrusive_List_Node.cpp | 27 - externals/ace/Intrusive_List_Node.h | 84 - externals/ace/Intrusive_List_Node.inl | 31 - externals/ace/LOCK_SOCK_Acceptor.cpp | 35 - externals/ace/LOCK_SOCK_Acceptor.h | 67 - externals/ace/LSOCK.cpp | 185 - externals/ace/LSOCK.h | 84 - externals/ace/LSOCK.inl | 43 - externals/ace/LSOCK_Acceptor.cpp | 143 - externals/ace/LSOCK_Acceptor.h | 95 - externals/ace/LSOCK_CODgram.cpp | 62 - externals/ace/LSOCK_CODgram.h | 109 - externals/ace/LSOCK_CODgram.inl | 30 - externals/ace/LSOCK_Connector.cpp | 59 - externals/ace/LSOCK_Connector.h | 91 - externals/ace/LSOCK_Connector.inl | 27 - externals/ace/LSOCK_Dgram.cpp | 71 - externals/ace/LSOCK_Dgram.h | 74 - externals/ace/LSOCK_Dgram.inl | 22 - externals/ace/LSOCK_Stream.cpp | 137 - externals/ace/LSOCK_Stream.h | 82 - externals/ace/LSOCK_Stream.inl | 25 - externals/ace/Lib_Find.cpp | 768 - externals/ace/Lib_Find.h | 131 - externals/ace/Local_Memory_Pool.cpp | 144 - externals/ace/Local_Memory_Pool.h | 133 - externals/ace/Local_Name_Space.cpp | 169 - externals/ace/Local_Name_Space.h | 132 - externals/ace/Local_Name_Space_T.cpp | 966 -- externals/ace/Local_Name_Space_T.h | 280 - externals/ace/Local_Tokens.cpp | 1623 -- externals/ace/Local_Tokens.h | 1121 -- externals/ace/Local_Tokens.inl | 289 - externals/ace/Lock.cpp | 88 - externals/ace/Lock.h | 161 - externals/ace/Lock.inl | 12 - externals/ace/Lock_Adapter_T.cpp | 117 - externals/ace/Lock_Adapter_T.h | 123 - externals/ace/Lock_Adapter_T.inl | 16 - externals/ace/Log_Msg.cpp | 2676 ---- externals/ace/Log_Msg.h | 777 - externals/ace/Log_Msg.inl | 235 - externals/ace/Log_Msg_Backend.cpp | 14 - externals/ace/Log_Msg_Backend.h | 88 - externals/ace/Log_Msg_Callback.cpp | 13 - externals/ace/Log_Msg_Callback.h | 69 - externals/ace/Log_Msg_IPC.cpp | 114 - externals/ace/Log_Msg_IPC.h | 81 - externals/ace/Log_Msg_NT_Event_Log.cpp | 170 - externals/ace/Log_Msg_NT_Event_Log.h | 72 - externals/ace/Log_Msg_UNIX_Syslog.cpp | 207 - externals/ace/Log_Msg_UNIX_Syslog.h | 77 - externals/ace/Log_Priority.h | 85 - externals/ace/Log_Record.cpp | 412 - externals/ace/Log_Record.h | 230 - externals/ace/Log_Record.inl | 121 - externals/ace/Logging_Strategy.cpp | 614 - externals/ace/Logging_Strategy.h | 214 - externals/ace/MEM_Acceptor.cpp | 266 - externals/ace/MEM_Acceptor.h | 192 - externals/ace/MEM_Acceptor.inl | 103 - externals/ace/MEM_Addr.cpp | 170 - externals/ace/MEM_Addr.h | 155 - externals/ace/MEM_Addr.inl | 111 - externals/ace/MEM_Connector.cpp | 149 - externals/ace/MEM_Connector.h | 179 - externals/ace/MEM_Connector.inl | 30 - externals/ace/MEM_IO.cpp | 574 - externals/ace/MEM_IO.h | 310 - externals/ace/MEM_IO.inl | 247 - externals/ace/MEM_SAP.cpp | 97 - externals/ace/MEM_SAP.h | 169 - externals/ace/MEM_SAP.inl | 64 - externals/ace/MEM_Stream.cpp | 47 - externals/ace/MEM_Stream.h | 158 - externals/ace/MEM_Stream.inl | 180 - externals/ace/MMAP_Memory_Pool.cpp | 593 - externals/ace/MMAP_Memory_Pool.h | 347 - externals/ace/MMAP_Memory_Pool.inl | 21 - externals/ace/Makefile.in | 5498 ------- externals/ace/Malloc.cpp | 186 - externals/ace/Malloc.h | 396 - externals/ace/Malloc.inl | 26 - externals/ace/Malloc_Allocator.cpp | 361 - externals/ace/Malloc_Allocator.h | 146 - externals/ace/Malloc_Allocator.inl | 16 - externals/ace/Malloc_Base.h | 168 - externals/ace/Malloc_T.cpp | 1260 -- externals/ace/Malloc_T.h | 931 -- externals/ace/Malloc_T.inl | 184 - externals/ace/Managed_Object.cpp | 25 - externals/ace/Managed_Object.h | 168 - externals/ace/Managed_Object.inl | 23 - externals/ace/Manual_Event.cpp | 48 - externals/ace/Manual_Event.h | 74 - externals/ace/Manual_Event.inl | 12 - externals/ace/Map.h | 32 - externals/ace/Map_Manager.cpp | 701 - externals/ace/Map_Manager.h | 720 - externals/ace/Map_Manager.inl | 729 - externals/ace/Map_T.cpp | 1343 -- externals/ace/Map_T.h | 1611 -- externals/ace/Map_T.inl | 415 - externals/ace/Mem_Map.cpp | 310 - externals/ace/Mem_Map.h | 232 - externals/ace/Mem_Map.inl | 238 - externals/ace/Memory_Pool.h | 31 - externals/ace/Message_Block.cpp | 1278 -- externals/ace/Message_Block.h | 871 -- externals/ace/Message_Block.inl | 508 - externals/ace/Message_Block_T.cpp | 54 - externals/ace/Message_Block_T.h | 88 - externals/ace/Message_Block_T.inl | 31 - externals/ace/Message_Queue.cpp | 28 - externals/ace/Message_Queue.h | 233 - externals/ace/Message_Queue.inl | 12 - externals/ace/Message_Queue_NT.cpp | 237 - externals/ace/Message_Queue_NT.h | 231 - externals/ace/Message_Queue_NT.inl | 131 - externals/ace/Message_Queue_T.cpp | 2991 ---- externals/ace/Message_Queue_T.h | 1563 -- externals/ace/Message_Queue_Vx.cpp | 368 - externals/ace/Message_Queue_Vx.h | 227 - externals/ace/Message_Queue_Vx.inl | 19 - externals/ace/Method_Object.h | 38 - externals/ace/Method_Request.cpp | 30 - externals/ace/Method_Request.h | 100 - externals/ace/Metrics_Cache.h | 140 - externals/ace/Metrics_Cache_T.cpp | 237 - externals/ace/Metrics_Cache_T.h | 243 - externals/ace/Metrics_Cache_T.inl | 240 - externals/ace/Min_Max.h | 70 - externals/ace/Module.cpp | 273 - externals/ace/Module.h | 215 - externals/ace/Module.inl | 65 - externals/ace/Monitor_Admin.cpp | 113 - externals/ace/Monitor_Admin.h | 109 - externals/ace/Monitor_Admin_Manager.cpp | 42 - externals/ace/Monitor_Admin_Manager.h | 70 - externals/ace/Monitor_Base.cpp | 402 - externals/ace/Monitor_Base.h | 152 - externals/ace/Monitor_Base.inl | 59 - externals/ace/Monitor_Control_Action.cpp | 45 - externals/ace/Monitor_Control_Action.h | 65 - externals/ace/Monitor_Control_Types.cpp | 81 - externals/ace/Monitor_Control_Types.h | 116 - externals/ace/Monitor_Point_Registry.cpp | 172 - externals/ace/Monitor_Point_Registry.h | 100 - externals/ace/Monitor_Size.cpp | 47 - externals/ace/Monitor_Size.h | 64 - externals/ace/Msg_WFMO_Reactor.cpp | 85 - externals/ace/Msg_WFMO_Reactor.h | 120 - externals/ace/Msg_WFMO_Reactor.inl | 35 - externals/ace/Multihomed_INET_Addr.cpp | 300 - externals/ace/Multihomed_INET_Addr.h | 199 - externals/ace/Multihomed_INET_Addr.inl | 15 - externals/ace/Mutex.cpp | 127 - externals/ace/Mutex.h | 192 - externals/ace/Mutex.inl | 175 - externals/ace/NT_Service.cpp | 618 - externals/ace/NT_Service.h | 439 - externals/ace/NT_Service.inl | 85 - externals/ace/Name_Proxy.cpp | 209 - externals/ace/Name_Proxy.h | 101 - externals/ace/Name_Request_Reply.cpp | 577 - externals/ace/Name_Request_Reply.h | 265 - externals/ace/Name_Space.cpp | 75 - externals/ace/Name_Space.h | 165 - externals/ace/Naming_Context.cpp | 649 - externals/ace/Naming_Context.h | 387 - externals/ace/Naming_Context.inl | 44 - externals/ace/Netlink_Addr.cpp | 68 - externals/ace/Netlink_Addr.h | 120 - externals/ace/Netlink_Addr.inl | 51 - externals/ace/Node.cpp | 46 - externals/ace/Node.h | 85 - externals/ace/Notification_Queue.cpp | 225 - externals/ace/Notification_Queue.h | 156 - externals/ace/Notification_Queue.inl | 50 - externals/ace/Notification_Strategy.cpp | 22 - externals/ace/Notification_Strategy.h | 75 - externals/ace/Notification_Strategy.inl | 31 - externals/ace/Null_Barrier.h | 59 - externals/ace/Null_Condition.h | 85 - externals/ace/Null_Mutex.h | 230 - externals/ace/Null_Semaphore.h | 105 - externals/ace/Numeric_Limits.h | 270 - externals/ace/OS.cpp | 53 - externals/ace/OS.h | 329 - externals/ace/OS.inl | 80 - externals/ace/OS_Dirent.h | 32 - externals/ace/OS_Errno.cpp | 47 - externals/ace/OS_Errno.h | 100 - externals/ace/OS_Errno.inl | 67 - externals/ace/OS_Log_Msg_Attributes.cpp | 9 - externals/ace/OS_Log_Msg_Attributes.h | 87 - externals/ace/OS_Log_Msg_Attributes.inl | 22 - externals/ace/OS_Memory.h | 344 - externals/ace/OS_NS_Thread.cpp | 5370 ------- externals/ace/OS_NS_Thread.h | 2024 --- externals/ace/OS_NS_Thread.inl | 3648 ----- externals/ace/OS_NS_arpa_inet.cpp | 53 - externals/ace/OS_NS_arpa_inet.h | 74 - externals/ace/OS_NS_arpa_inet.inl | 98 - externals/ace/OS_NS_ctype.cpp | 11 - externals/ace/OS_NS_ctype.h | 146 - externals/ace/OS_NS_ctype.inl | 231 - externals/ace/OS_NS_dirent.cpp | 274 - externals/ace/OS_NS_dirent.h | 153 - externals/ace/OS_NS_dirent.inl | 184 - externals/ace/OS_NS_dlfcn.cpp | 10 - externals/ace/OS_NS_dlfcn.h | 69 - externals/ace/OS_NS_dlfcn.inl | 286 - externals/ace/OS_NS_errno.cpp | 11 - externals/ace/OS_NS_errno.h | 102 - externals/ace/OS_NS_errno.inl | 83 - externals/ace/OS_NS_fcntl.cpp | 245 - externals/ace/OS_NS_fcntl.h | 79 - externals/ace/OS_NS_fcntl.inl | 23 - externals/ace/OS_NS_macros.h | 114 - externals/ace/OS_NS_math.cpp | 10 - externals/ace/OS_NS_math.h | 121 - externals/ace/OS_NS_math.inl | 17 - externals/ace/OS_NS_netdb.cpp | 475 - externals/ace/OS_NS_netdb.h | 146 - externals/ace/OS_NS_netdb.inl | 754 - externals/ace/OS_NS_poll.cpp | 10 - externals/ace/OS_NS_poll.h | 66 - externals/ace/OS_NS_poll.inl | 45 - externals/ace/OS_NS_pwd.cpp | 10 - externals/ace/OS_NS_pwd.h | 77 - externals/ace/OS_NS_pwd.inl | 120 - externals/ace/OS_NS_regex.cpp | 10 - externals/ace/OS_NS_regex.h | 65 - externals/ace/OS_NS_regex.inl | 39 - externals/ace/OS_NS_signal.cpp | 26 - externals/ace/OS_NS_signal.h | 233 - externals/ace/OS_NS_signal.inl | 243 - externals/ace/OS_NS_stdio.cpp | 426 - externals/ace/OS_NS_stdio.h | 557 - externals/ace/OS_NS_stdio.inl | 1213 -- externals/ace/OS_NS_stdlib.cpp | 1211 -- externals/ace/OS_NS_stdlib.h | 453 - externals/ace/OS_NS_stdlib.inl | 644 - externals/ace/OS_NS_string.cpp | 421 - externals/ace/OS_NS_string.h | 477 - externals/ace/OS_NS_string.inl | 560 - externals/ace/OS_NS_strings.cpp | 84 - externals/ace/OS_NS_strings.h | 86 - externals/ace/OS_NS_strings.inl | 59 - externals/ace/OS_NS_stropts.cpp | 193 - externals/ace/OS_NS_stropts.h | 170 - externals/ace/OS_NS_stropts.inl | 201 - externals/ace/OS_NS_sys_mman.cpp | 10 - externals/ace/OS_NS_sys_mman.h | 97 - externals/ace/OS_NS_sys_mman.inl | 301 - externals/ace/OS_NS_sys_msg.cpp | 10 - externals/ace/OS_NS_sys_msg.h | 77 - externals/ace/OS_NS_sys_msg.inl | 78 - externals/ace/OS_NS_sys_resource.cpp | 10 - externals/ace/OS_NS_sys_resource.h | 67 - externals/ace/OS_NS_sys_resource.inl | 98 - externals/ace/OS_NS_sys_select.cpp | 10 - externals/ace/OS_NS_sys_select.h | 77 - externals/ace/OS_NS_sys_select.inl | 80 - externals/ace/OS_NS_sys_sendfile.cpp | 53 - externals/ace/OS_NS_sys_sendfile.h | 66 - externals/ace/OS_NS_sys_sendfile.inl | 24 - externals/ace/OS_NS_sys_shm.cpp | 10 - externals/ace/OS_NS_sys_shm.h | 74 - externals/ace/OS_NS_sys_shm.inl | 76 - externals/ace/OS_NS_sys_socket.cpp | 159 - externals/ace/OS_NS_sys_socket.h | 296 - externals/ace/OS_NS_sys_socket.inl | 999 -- externals/ace/OS_NS_sys_stat.cpp | 10 - externals/ace/OS_NS_sys_stat.h | 149 - externals/ace/OS_NS_sys_stat.inl | 295 - externals/ace/OS_NS_sys_time.cpp | 10 - externals/ace/OS_NS_sys_time.h | 55 - externals/ace/OS_NS_sys_time.inl | 75 - externals/ace/OS_NS_sys_uio.cpp | 130 - externals/ace/OS_NS_sys_uio.h | 80 - externals/ace/OS_NS_sys_uio.inl | 55 - externals/ace/OS_NS_sys_utsname.cpp | 244 - externals/ace/OS_NS_sys_utsname.h | 71 - externals/ace/OS_NS_sys_wait.cpp | 9 - externals/ace/OS_NS_sys_wait.h | 87 - externals/ace/OS_NS_sys_wait.inl | 105 - externals/ace/OS_NS_time.cpp | 636 - externals/ace/OS_NS_time.h | 294 - externals/ace/OS_NS_time.inl | 496 - externals/ace/OS_NS_unistd.cpp | 937 -- externals/ace/OS_NS_unistd.h | 382 - externals/ace/OS_NS_unistd.inl | 1226 -- externals/ace/OS_NS_wchar.cpp | 377 - externals/ace/OS_NS_wchar.h | 199 - externals/ace/OS_NS_wchar.inl | 87 - externals/ace/OS_NS_wctype.cpp | 11 - externals/ace/OS_NS_wctype.h | 71 - externals/ace/OS_NS_wctype.inl | 25 - externals/ace/OS_QoS.cpp | 476 - externals/ace/OS_QoS.h | 449 - externals/ace/OS_String.h | 32 - externals/ace/OS_TLI.cpp | 9 - externals/ace/OS_TLI.h | 285 - externals/ace/OS_TLI.inl | 390 - externals/ace/OS_Thread_Adapter.cpp | 153 - externals/ace/OS_Thread_Adapter.h | 71 - externals/ace/OS_main.cpp | 157 - externals/ace/OS_main.h | 310 - externals/ace/Obchunk.cpp | 36 - externals/ace/Obchunk.h | 77 - externals/ace/Obchunk.inl | 12 - externals/ace/Object_Manager.cpp | 971 -- externals/ace/Object_Manager.h | 475 - externals/ace/Object_Manager.inl | 51 - externals/ace/Object_Manager_Base.cpp | 507 - externals/ace/Object_Manager_Base.h | 248 - externals/ace/Obstack.h | 31 - externals/ace/Obstack_T.cpp | 226 - externals/ace/Obstack_T.h | 134 - externals/ace/Obstack_T.inl | 19 - externals/ace/PI_Malloc.cpp | 165 - externals/ace/PI_Malloc.h | 213 - externals/ace/PI_Malloc.inl | 33 - externals/ace/POSIX_Asynch_IO.cpp | 2421 --- externals/ace/POSIX_Asynch_IO.h | 1302 -- externals/ace/POSIX_CB_Proactor.cpp | 185 - externals/ace/POSIX_CB_Proactor.h | 97 - externals/ace/POSIX_Proactor.cpp | 2069 --- externals/ace/POSIX_Proactor.h | 659 - externals/ace/POSIX_Proactor.inl | 13 - externals/ace/Pagefile_Memory_Pool.cpp | 389 - externals/ace/Pagefile_Memory_Pool.h | 204 - externals/ace/Pagefile_Memory_Pool.inl | 54 - externals/ace/Pair.h | 32 - externals/ace/Pair_T.cpp | 16 - externals/ace/Pair_T.h | 129 - externals/ace/Pair_T.inl | 90 - externals/ace/Parse_Node.cpp | 928 -- externals/ace/Parse_Node.h | 523 - externals/ace/Ping_Socket.cpp | 379 - externals/ace/Ping_Socket.h | 118 - externals/ace/Ping_Socket.inl | 13 - externals/ace/Pipe.cpp | 365 - externals/ace/Pipe.h | 165 - externals/ace/Pipe.inl | 188 - externals/ace/PrecompiledHeaders/WinAcePCH.cpp | 2 - externals/ace/PrecompiledHeaders/WinAcePCH.h | 17 - externals/ace/Priority_Reactor.cpp | 188 - externals/ace/Priority_Reactor.h | 100 - externals/ace/Proactor.cpp | 1176 -- externals/ace/Proactor.h | 691 - externals/ace/Proactor.inl | 80 - externals/ace/Proactor_Impl.cpp | 21 - externals/ace/Proactor_Impl.h | 265 - externals/ace/Process.cpp | 1408 -- externals/ace/Process.h | 641 - externals/ace/Process.inl | 421 - externals/ace/Process_Manager.cpp | 1029 -- externals/ace/Process_Manager.h | 477 - externals/ace/Process_Manager.inl | 13 - externals/ace/Process_Mutex.cpp | 90 - externals/ace/Process_Mutex.h | 233 - externals/ace/Process_Mutex.inl | 118 - externals/ace/Process_Semaphore.cpp | 111 - externals/ace/Process_Semaphore.h | 159 - externals/ace/Process_Semaphore.inl | 66 - externals/ace/Profile_Timer.cpp | 443 - externals/ace/Profile_Timer.h | 139 - externals/ace/Profile_Timer.inl | 129 - externals/ace/QoS/ACE_QoS_Export.h | 46 - externals/ace/QoS/QoS_Decorator.cpp | 165 - externals/ace/QoS/QoS_Decorator.h | 179 - externals/ace/QoS/QoS_Manager.cpp | 41 - externals/ace/QoS/QoS_Manager.h | 74 - externals/ace/QoS/QoS_Session.h | 183 - externals/ace/QoS/QoS_Session_Factory.cpp | 105 - externals/ace/QoS/QoS_Session_Factory.h | 96 - externals/ace/QoS/QoS_Session_Impl.cpp | 718 - externals/ace/QoS/QoS_Session_Impl.h | 265 - externals/ace/QoS/QoS_Session_Impl.inl | 229 - externals/ace/QoS/README | 55 - externals/ace/QoS/SOCK_Dgram_Mcast_QoS.cpp | 258 - externals/ace/QoS/SOCK_Dgram_Mcast_QoS.h | 142 - externals/ace/QoS/SOCK_Dgram_Mcast_QoS.inl | 57 - externals/ace/RB_Tree.cpp | 1250 -- externals/ace/RB_Tree.h | 904 -- externals/ace/RB_Tree.inl | 1169 -- externals/ace/README | 1787 --- externals/ace/RW_Mutex.cpp | 55 - externals/ace/RW_Mutex.h | 141 - externals/ace/RW_Mutex.inl | 83 - externals/ace/RW_Process_Mutex.cpp | 54 - externals/ace/RW_Process_Mutex.h | 137 - externals/ace/RW_Process_Mutex.inl | 77 - externals/ace/RW_Thread_Mutex.cpp | 45 - externals/ace/RW_Thread_Mutex.h | 74 - externals/ace/RW_Thread_Mutex.inl | 19 - externals/ace/Reactor.cpp | 514 - externals/ace/Reactor.h | 880 -- externals/ace/Reactor.inl | 498 - externals/ace/Reactor_Impl.cpp | 15 - externals/ace/Reactor_Impl.h | 569 - externals/ace/Reactor_Notification_Strategy.cpp | 38 - externals/ace/Reactor_Notification_Strategy.h | 66 - externals/ace/Reactor_Notification_Strategy.inl | 19 - externals/ace/Reactor_Timer_Interface.cpp | 16 - externals/ace/Reactor_Timer_Interface.h | 60 - externals/ace/Reactor_Token_T.cpp | 80 - externals/ace/Reactor_Token_T.h | 93 - externals/ace/Read_Buffer.cpp | 176 - externals/ace/Read_Buffer.h | 129 - externals/ace/Read_Buffer.inl | 32 - externals/ace/Recursive_Thread_Mutex.cpp | 125 - externals/ace/Recursive_Thread_Mutex.h | 197 - externals/ace/Recursive_Thread_Mutex.inl | 95 - externals/ace/Recyclable.cpp | 22 - externals/ace/Recyclable.h | 77 - externals/ace/Recyclable.inl | 20 - externals/ace/Refcountable.h | 32 - externals/ace/Refcountable_T.cpp | 25 - externals/ace/Refcountable_T.h | 67 - externals/ace/Refcountable_T.inl | 35 - externals/ace/Refcounted_Auto_Ptr.cpp | 18 - externals/ace/Refcounted_Auto_Ptr.h | 199 - externals/ace/Refcounted_Auto_Ptr.inl | 190 - externals/ace/Registry.cpp | 1129 -- externals/ace/Registry.h | 562 - externals/ace/Registry_Name_Space.cpp | 296 - externals/ace/Registry_Name_Space.h | 140 - externals/ace/Remote_Name_Space.cpp | 380 - externals/ace/Remote_Name_Space.h | 147 - externals/ace/Remote_Tokens.cpp | 531 - externals/ace/Remote_Tokens.h | 322 - externals/ace/Remote_Tokens.inl | 48 - externals/ace/Reverse_Lock_T.cpp | 93 - externals/ace/Reverse_Lock_T.h | 139 - externals/ace/Reverse_Lock_T.inl | 19 - externals/ace/Rtems_init.c | 219 - externals/ace/SOCK.cpp | 185 - externals/ace/SOCK.h | 137 - externals/ace/SOCK.inl | 39 - externals/ace/SOCK_Acceptor.cpp | 406 - externals/ace/SOCK_Acceptor.h | 178 - externals/ace/SOCK_Acceptor.inl | 13 - externals/ace/SOCK_CODgram.cpp | 151 - externals/ace/SOCK_CODgram.h | 143 - externals/ace/SOCK_CODgram.inl | 19 - externals/ace/SOCK_Connector.cpp | 365 - externals/ace/SOCK_Connector.h | 321 - externals/ace/SOCK_Connector.inl | 38 - externals/ace/SOCK_Dgram.cpp | 747 - externals/ace/SOCK_Dgram.h | 239 - externals/ace/SOCK_Dgram.inl | 167 - externals/ace/SOCK_Dgram_Bcast.cpp | 380 - externals/ace/SOCK_Dgram_Bcast.h | 140 - externals/ace/SOCK_Dgram_Bcast.inl | 37 - externals/ace/SOCK_Dgram_Mcast.cpp | 932 -- externals/ace/SOCK_Dgram_Mcast.h | 384 - externals/ace/SOCK_Dgram_Mcast.inl | 52 - externals/ace/SOCK_IO.cpp | 180 - externals/ace/SOCK_IO.h | 136 - externals/ace/SOCK_IO.inl | 123 - externals/ace/SOCK_Netlink.cpp | 113 - externals/ace/SOCK_Netlink.h | 106 - externals/ace/SOCK_Netlink.inl | 37 - externals/ace/SOCK_SEQPACK_Acceptor.cpp | 596 - externals/ace/SOCK_SEQPACK_Acceptor.h | 189 - externals/ace/SOCK_SEQPACK_Acceptor.inl | 13 - externals/ace/SOCK_SEQPACK_Association.cpp | 348 - externals/ace/SOCK_SEQPACK_Association.h | 202 - externals/ace/SOCK_SEQPACK_Association.inl | 177 - externals/ace/SOCK_SEQPACK_Connector.cpp | 442 - externals/ace/SOCK_SEQPACK_Connector.h | 331 - externals/ace/SOCK_SEQPACK_Connector.inl | 38 - externals/ace/SOCK_Stream.cpp | 40 - externals/ace/SOCK_Stream.h | 184 - externals/ace/SOCK_Stream.inl | 177 - externals/ace/SPIPE.cpp | 82 - externals/ace/SPIPE.h | 116 - externals/ace/SPIPE.inl | 18 - externals/ace/SPIPE_Acceptor.cpp | 337 - externals/ace/SPIPE_Acceptor.h | 168 - externals/ace/SPIPE_Addr.cpp | 167 - externals/ace/SPIPE_Addr.h | 122 - externals/ace/SPIPE_Addr.inl | 59 - externals/ace/SPIPE_Connector.cpp | 160 - externals/ace/SPIPE_Connector.h | 118 - externals/ace/SPIPE_Connector.inl | 14 - externals/ace/SPIPE_Stream.cpp | 104 - externals/ace/SPIPE_Stream.h | 171 - externals/ace/SPIPE_Stream.inl | 275 - externals/ace/SSL/SSL_Asynch_BIO.cpp | 253 - externals/ace/SSL/SSL_Asynch_BIO.h | 42 - externals/ace/SSL/SSL_Asynch_Stream.cpp | 1085 -- externals/ace/SSL/SSL_Asynch_Stream.h | 466 - externals/ace/SSL/SSL_Asynch_Stream.inl | 13 - externals/ace/SSL/SSL_Context.cpp | 657 - externals/ace/SSL/SSL_Context.h | 394 - externals/ace/SSL/SSL_Context.inl | 125 - externals/ace/SSL/SSL_Export.h | 44 - externals/ace/SSL/SSL_SOCK.cpp | 72 - externals/ace/SSL/SSL_SOCK.h | 103 - externals/ace/SSL/SSL_SOCK.inl | 71 - externals/ace/SSL/SSL_SOCK_Acceptor.cpp | 250 - externals/ace/SSL/SSL_SOCK_Acceptor.h | 197 - externals/ace/SSL/SSL_SOCK_Acceptor.inl | 85 - externals/ace/SSL/SSL_SOCK_Connector.cpp | 425 - externals/ace/SSL/SSL_SOCK_Connector.h | 318 - externals/ace/SSL/SSL_SOCK_Connector.inl | 28 - externals/ace/SSL/SSL_SOCK_Stream.cpp | 630 - externals/ace/SSL/SSL_SOCK_Stream.h | 348 - externals/ace/SSL/SSL_SOCK_Stream.inl | 350 - externals/ace/SSL/sslconf.h | 57 - externals/ace/SString.cpp | 341 - externals/ace/SString.h | 303 - externals/ace/SString.inl | 299 - externals/ace/SStringfwd.h | 55 - externals/ace/SUN_Proactor.cpp | 324 - externals/ace/SUN_Proactor.h | 126 - externals/ace/SV_Message.cpp | 24 - externals/ace/SV_Message.h | 67 - externals/ace/SV_Message.inl | 37 - externals/ace/SV_Message_Queue.cpp | 44 - externals/ace/SV_Message_Queue.h | 105 - externals/ace/SV_Message_Queue.inl | 81 - externals/ace/SV_Semaphore_Complex.cpp | 259 - externals/ace/SV_Semaphore_Complex.h | 159 - externals/ace/SV_Semaphore_Complex.inl | 84 - externals/ace/SV_Semaphore_Simple.cpp | 237 - externals/ace/SV_Semaphore_Simple.h | 197 - externals/ace/SV_Semaphore_Simple.inl | 128 - externals/ace/SV_Shared_Memory.cpp | 88 - externals/ace/SV_Shared_Memory.h | 121 - externals/ace/SV_Shared_Memory.inl | 118 - externals/ace/Sample_History.cpp | 73 - externals/ace/Sample_History.h | 91 - externals/ace/Sample_History.inl | 26 - externals/ace/Sbrk_Memory_Pool.cpp | 124 - externals/ace/Sbrk_Memory_Pool.h | 118 - externals/ace/Sched_Params.cpp | 337 - externals/ace/Sched_Params.h | 232 - externals/ace/Sched_Params.inl | 134 - externals/ace/Select_Reactor.h | 69 - externals/ace/Select_Reactor_Base.cpp | 1137 -- externals/ace/Select_Reactor_Base.h | 616 - externals/ace/Select_Reactor_Base.inl | 152 - externals/ace/Select_Reactor_T.cpp | 1598 -- externals/ace/Select_Reactor_T.h | 718 - externals/ace/Select_Reactor_T.inl | 236 - externals/ace/Semaphore.cpp | 64 - externals/ace/Semaphore.h | 183 - externals/ace/Semaphore.inl | 119 - externals/ace/Service_Config.cpp | 610 - externals/ace/Service_Config.h | 692 - externals/ace/Service_Config.inl | 208 - externals/ace/Service_Gestalt.cpp | 1327 -- externals/ace/Service_Gestalt.h | 530 - externals/ace/Service_Gestalt.inl | 78 - externals/ace/Service_Manager.cpp | 437 - externals/ace/Service_Manager.h | 120 - externals/ace/Service_Object.cpp | 183 - externals/ace/Service_Object.h | 206 - externals/ace/Service_Object.inl | 79 - externals/ace/Service_Repository.cpp | 630 - externals/ace/Service_Repository.h | 271 - externals/ace/Service_Repository.inl | 38 - externals/ace/Service_Templates.h | 29 - externals/ace/Service_Types.cpp | 461 - externals/ace/Service_Types.h | 221 - externals/ace/Service_Types.inl | 43 - externals/ace/Shared_Memory.cpp | 13 - externals/ace/Shared_Memory.h | 58 - externals/ace/Shared_Memory_MM.cpp | 111 - externals/ace/Shared_Memory_MM.h | 120 - externals/ace/Shared_Memory_MM.inl | 42 - externals/ace/Shared_Memory_Pool.cpp | 461 - externals/ace/Shared_Memory_Pool.h | 210 - externals/ace/Shared_Memory_SV.cpp | 88 - externals/ace/Shared_Memory_SV.h | 101 - externals/ace/Shared_Memory_SV.inl | 30 - externals/ace/Shared_Object.cpp | 54 - externals/ace/Shared_Object.h | 62 - externals/ace/Shared_Object.inl | 12 - externals/ace/Sig_Adapter.cpp | 80 - externals/ace/Sig_Adapter.h | 81 - externals/ace/Sig_Handler.cpp | 616 - externals/ace/Sig_Handler.h | 237 - externals/ace/Sig_Handler.inl | 15 - externals/ace/Signal.cpp | 221 - externals/ace/Signal.h | 267 - externals/ace/Signal.inl | 265 - externals/ace/Singleton.cpp | 548 - externals/ace/Singleton.h | 330 - externals/ace/Singleton.inl | 42 - externals/ace/Sock_Connect.cpp | 1594 -- externals/ace/Sock_Connect.h | 107 - externals/ace/Stack_Trace.cpp | 723 - externals/ace/Stack_Trace.h | 107 - externals/ace/Static_Object_Lock.h | 78 - externals/ace/Stats.cpp | 421 - externals/ace/Stats.h | 222 - externals/ace/Stats.inl | 104 - externals/ace/Strategies.h | 33 - externals/ace/Strategies_T.cpp | 1502 -- externals/ace/Strategies_T.h | 1076 -- externals/ace/Strategies_T.inl | 230 - externals/ace/Stream.cpp | 633 - externals/ace/Stream.h | 241 - externals/ace/Stream.inl | 51 - externals/ace/Stream_Modules.cpp | 380 - externals/ace/Stream_Modules.h | 166 - externals/ace/String_Base.cpp | 663 - externals/ace/String_Base.h | 891 -- externals/ace/String_Base.inl | 461 - externals/ace/String_Base_Const.cpp | 20 - externals/ace/String_Base_Const.h | 52 - externals/ace/Svc_Conf.h | 110 - externals/ace/Svc_Conf.y | 376 - externals/ace/Svc_Conf_Lexer.cpp | 676 - externals/ace/Svc_Conf_Lexer.h | 70 - externals/ace/Svc_Conf_Param.h | 142 - externals/ace/Svc_Conf_Token_Table.h | 84 - externals/ace/Svc_Conf_Tokens.h | 29 - externals/ace/Svc_Conf_y.cpp | 1998 --- externals/ace/Svc_Handler.cpp | 529 - externals/ace/Svc_Handler.h | 345 - externals/ace/Synch.h | 65 - externals/ace/Synch_Options.cpp | 110 - externals/ace/Synch_Options.h | 163 - externals/ace/Synch_T.cpp | 22 - externals/ace/Synch_T.h | 42 - externals/ace/Synch_Traits.h | 152 - externals/ace/System_Time.cpp | 140 - externals/ace/System_Time.h | 99 - externals/ace/TLI.cpp | 273 - externals/ace/TLI.h | 116 - externals/ace/TLI.inl | 50 - externals/ace/TLI_Acceptor.cpp | 553 - externals/ace/TLI_Acceptor.h | 123 - externals/ace/TLI_Connector.cpp | 256 - externals/ace/TLI_Connector.h | 130 - externals/ace/TLI_Connector.inl | 48 - externals/ace/TLI_Stream.cpp | 229 - externals/ace/TLI_Stream.h | 141 - externals/ace/TLI_Stream.inl | 25 - externals/ace/TP_Reactor.cpp | 686 - externals/ace/TP_Reactor.h | 320 - externals/ace/TP_Reactor.inl | 119 - externals/ace/TSS_Adapter.cpp | 45 - externals/ace/TSS_Adapter.h | 61 - externals/ace/TSS_T.cpp | 709 - externals/ace/TSS_T.h | 271 - externals/ace/TSS_T.inl | 103 - externals/ace/TTY_IO.cpp | 705 - externals/ace/TTY_IO.h | 113 - externals/ace/Task.cpp | 299 - externals/ace/Task.h | 307 - externals/ace/Task.inl | 77 - externals/ace/Task_Ex_T.cpp | 114 - externals/ace/Task_Ex_T.h | 205 - externals/ace/Task_Ex_T.inl | 109 - externals/ace/Task_T.cpp | 108 - externals/ace/Task_T.h | 198 - externals/ace/Task_T.inl | 105 - externals/ace/Test_and_Set.cpp | 51 - externals/ace/Test_and_Set.h | 75 - externals/ace/Thread.cpp | 101 - externals/ace/Thread.h | 282 - externals/ace/Thread.inl | 286 - externals/ace/Thread_Adapter.cpp | 228 - externals/ace/Thread_Adapter.h | 100 - externals/ace/Thread_Adapter.inl | 13 - externals/ace/Thread_Control.cpp | 96 - externals/ace/Thread_Control.h | 102 - externals/ace/Thread_Control.inl | 46 - externals/ace/Thread_Exit.cpp | 123 - externals/ace/Thread_Exit.h | 111 - externals/ace/Thread_Hook.cpp | 33 - externals/ace/Thread_Hook.h | 65 - externals/ace/Thread_Manager.cpp | 2223 --- externals/ace/Thread_Manager.h | 1267 -- externals/ace/Thread_Manager.inl | 305 - externals/ace/Thread_Mutex.cpp | 62 - externals/ace/Thread_Mutex.h | 176 - externals/ace/Thread_Mutex.inl | 104 - externals/ace/Thread_Semaphore.cpp | 62 - externals/ace/Thread_Semaphore.h | 87 - externals/ace/Thread_Semaphore.inl | 12 - externals/ace/Throughput_Stats.cpp | 202 - externals/ace/Throughput_Stats.h | 86 - externals/ace/Time_Value.cpp | 359 - externals/ace/Time_Value.h | 397 - externals/ace/Time_Value.inl | 418 - externals/ace/Timeprobe.cpp | 15 - externals/ace/Timeprobe.h | 201 - externals/ace/Timeprobe.inl | 14 - externals/ace/Timeprobe_T.cpp | 427 - externals/ace/Timeprobe_T.h | 220 - externals/ace/Timer_Hash.h | 75 - externals/ace/Timer_Hash_T.cpp | 870 -- externals/ace/Timer_Hash_T.h | 342 - externals/ace/Timer_Heap.h | 41 - externals/ace/Timer_Heap_T.cpp | 889 -- externals/ace/Timer_Heap_T.h | 338 - externals/ace/Timer_List.h | 42 - externals/ace/Timer_List_T.cpp | 418 - externals/ace/Timer_List_T.h | 226 - externals/ace/Timer_Queue.h | 52 - externals/ace/Timer_Queue_Adapters.cpp | 361 - externals/ace/Timer_Queue_Adapters.h | 261 - externals/ace/Timer_Queue_Adapters.inl | 29 - externals/ace/Timer_Queue_T.cpp | 538 - externals/ace/Timer_Queue_T.h | 566 - externals/ace/Timer_Queue_T.inl | 222 - externals/ace/Timer_Queuefwd.h | 38 - externals/ace/Timer_Wheel.h | 42 - externals/ace/Timer_Wheel_T.cpp | 964 -- externals/ace/Timer_Wheel_T.h | 226 - externals/ace/Token.cpp | 545 - externals/ace/Token.h | 376 - externals/ace/Token.inl | 176 - externals/ace/Token_Collection.cpp | 294 - externals/ace/Token_Collection.h | 243 - externals/ace/Token_Collection.inl | 17 - externals/ace/Token_Invariants.cpp | 356 - externals/ace/Token_Invariants.h | 245 - externals/ace/Token_Manager.cpp | 274 - externals/ace/Token_Manager.h | 150 - externals/ace/Token_Manager.inl | 25 - externals/ace/Token_Request_Reply.cpp | 186 - externals/ace/Token_Request_Reply.h | 270 - externals/ace/Token_Request_Reply.inl | 205 - externals/ace/Tokenizer_T.cpp | 242 - externals/ace/Tokenizer_T.h | 241 - externals/ace/Trace.cpp | 136 - externals/ace/Trace.h | 96 - externals/ace/Truncate.h | 517 - externals/ace/Typed_SV_Message.cpp | 30 - externals/ace/Typed_SV_Message.h | 107 - externals/ace/Typed_SV_Message.inl | 96 - externals/ace/Typed_SV_Message_Queue.cpp | 56 - externals/ace/Typed_SV_Message_Queue.h | 92 - externals/ace/Typed_SV_Message_Queue.inl | 80 - externals/ace/UNIX_Addr.cpp | 151 - externals/ace/UNIX_Addr.h | 117 - externals/ace/UNIX_Addr.inl | 57 - externals/ace/UPIPE_Acceptor.cpp | 129 - externals/ace/UPIPE_Acceptor.h | 99 - externals/ace/UPIPE_Acceptor.inl | 14 - externals/ace/UPIPE_Addr.h | 33 - externals/ace/UPIPE_Connector.cpp | 101 - externals/ace/UPIPE_Connector.h | 115 - externals/ace/UPIPE_Connector.inl | 34 - externals/ace/UPIPE_Stream.cpp | 234 - externals/ace/UPIPE_Stream.h | 140 - externals/ace/UPIPE_Stream.inl | 14 - externals/ace/UTF16_Encoding_Converter.cpp | 364 - externals/ace/UTF16_Encoding_Converter.h | 86 - externals/ace/UTF16_Encoding_Converter.inl | 76 - externals/ace/UTF32_Encoding_Converter.cpp | 254 - externals/ace/UTF32_Encoding_Converter.h | 67 - externals/ace/UTF8_Encoding_Converter.cpp | 92 - externals/ace/UTF8_Encoding_Converter.h | 72 - externals/ace/UUID.cpp | 506 - externals/ace/UUID.h | 282 - externals/ace/UUID.inl | 204 - externals/ace/Unbounded_Queue.cpp | 433 - externals/ace/Unbounded_Queue.h | 297 - externals/ace/Unbounded_Queue.inl | 27 - externals/ace/Unbounded_Set.cpp | 18 - externals/ace/Unbounded_Set.h | 103 - externals/ace/Unbounded_Set.inl | 49 - externals/ace/Unbounded_Set_Ex.cpp | 499 - externals/ace/Unbounded_Set_Ex.h | 376 - externals/ace/Unbounded_Set_Ex.inl | 23 - externals/ace/Value_Ptr.h | 167 - externals/ace/Vector_T.cpp | 154 - externals/ace/Vector_T.h | 316 - externals/ace/Vector_T.inl | 107 - externals/ace/Version.h | 9 - externals/ace/Versioned_Namespace.h | 51 - externals/ace/WFMO_Reactor.cpp | 2748 ---- externals/ace/WFMO_Reactor.h | 1368 -- externals/ace/WFMO_Reactor.inl | 1202 -- externals/ace/WIN32_Asynch_IO.cpp | 3782 ----- externals/ace/WIN32_Asynch_IO.h | 1937 --- externals/ace/WIN32_Proactor.cpp | 804 - externals/ace/WIN32_Proactor.h | 325 - externals/ace/XML_Svc_Conf.cpp | 15 - externals/ace/XML_Svc_Conf.h | 65 - externals/ace/XTI_ATM_Mcast.cpp | 70 - externals/ace/XTI_ATM_Mcast.h | 137 - externals/ace/XTI_ATM_Mcast.inl | 65 - externals/ace/ace.rc | 38 - externals/ace/ace_message_table.bin | Bin 28 -> 0 bytes externals/ace/ace_wchar.cpp | 17 - externals/ace/ace_wchar.h | 385 - externals/ace/ace_wchar.inl | 183 - externals/ace/checked_iterator.h | 58 - externals/ace/config-WinCE.h | 229 - externals/ace/config-aix-5.x.h | 326 - externals/ace/config-all.h | 93 - externals/ace/config-cray.h | 205 - externals/ace/config-cxx-common.h | 86 - externals/ace/config-cygwin32.h | 216 - externals/ace/config-doxygen.h | 128 - externals/ace/config-freebsd.h | 215 - externals/ace/config-g++-common.h | 183 - externals/ace/config-ghs-common.h | 43 - externals/ace/config-hpux-11.00.h | 451 - externals/ace/config-icc-common.h | 113 - externals/ace/config-integritySCA.h | 229 - externals/ace/config-irix6.5.x-sgic++.h | 18 - externals/ace/config-irix6.x-common.h | 254 - externals/ace/config-irix6.x-g++.h | 15 - externals/ace/config-irix6.x-sgic++.h | 36 - externals/ace/config-linux-common.h | 464 - externals/ace/config-linux.h | 75 - externals/ace/config-lite.h | 164 - externals/ace/config-lynxos.h | 199 - externals/ace/config-macosx-iphone-hardware.h | 15 - externals/ace/config-macosx-iphone-simulator.h | 9 - externals/ace/config-macosx-leopard.h | 231 - externals/ace/config-macosx-panther.h | 182 - externals/ace/config-macosx-snowleopard.h | 17 - externals/ace/config-macosx-tiger.h | 213 - externals/ace/config-macosx.h | 182 - externals/ace/config-macros.h | 655 - externals/ace/config-minimal.h | 39 - externals/ace/config-mvs.h | 127 - externals/ace/config-netbsd.h | 165 - externals/ace/config-openbsd.h | 208 - externals/ace/config-openvms.h | 198 - externals/ace/config-pharlap.h | 91 - externals/ace/config-posix-nonetworking.h | 86 - externals/ace/config-posix.h | 73 - externals/ace/config-qnx-neutrino.h | 136 - externals/ace/config-qnx-rtp-62x.h | 131 - externals/ace/config-qnx-rtp-common.h | 50 - externals/ace/config-qnx-rtp-pre62x.h | 152 - externals/ace/config-qnx-rtp.h | 25 - externals/ace/config-rtems.h | 164 - externals/ace/config-sco-5.0.0-nothread.h | 12 - externals/ace/config-sco-5.0.0.h | 90 - externals/ace/config-suncc-common.h | 67 - externals/ace/config-sunos5.10.h | 66 - externals/ace/config-sunos5.11.h | 15 - externals/ace/config-sunos5.4-g++.h | 176 - externals/ace/config-sunos5.4-sunc++-4.x.h | 186 - externals/ace/config-sunos5.5.h | 432 - externals/ace/config-sunos5.6.h | 126 - externals/ace/config-sunos5.7.h | 78 - externals/ace/config-sunos5.8.h | 39 - externals/ace/config-sunos5.9.h | 18 - externals/ace/config-tandem-nsk-mips-v2.h | 394 - externals/ace/config-tandem-nsk-mips-v3.h | 464 - externals/ace/config-tandem.h | 191 - externals/ace/config-tru64.h | 151 - externals/ace/config-unixware-7.1.0.h | 406 - externals/ace/config-unixware-7.1.0.udk.h | 457 - externals/ace/config-visualage.h | 20 - externals/ace/config-vxworks.h | 57 - externals/ace/config-vxworks6.4.h | 350 - externals/ace/config-vxworks6.5.h | 25 - externals/ace/config-vxworks6.6.h | 34 - externals/ace/config-vxworks6.7.h | 23 - externals/ace/config-vxworks6.8.h | 21 - externals/ace/config-win32-borland.h | 174 - externals/ace/config-win32-cegcc.h | 113 - externals/ace/config-win32-common.h | 701 - externals/ace/config-win32-dmc.h | 108 - externals/ace/config-win32-ghs.h | 93 - externals/ace/config-win32-interix.h | 127 - externals/ace/config-win32-mingw.h | 105 - externals/ace/config-win32-msvc-10.h | 153 - externals/ace/config-win32-msvc-7.h | 124 - externals/ace/config-win32-msvc-8.h | 163 - externals/ace/config-win32-msvc-9.h | 153 - externals/ace/config-win32-msvc.h | 175 - externals/ace/config-win32.h | 55 - externals/ace/config.h.in | 2204 --- externals/ace/gethrtime.cpp | 60 - externals/ace/iosfwd.h | 100 - externals/ace/os_include/arpa/os_inet.h | 74 - externals/ace/os_include/net/os_if.h | 112 - externals/ace/os_include/netinet/os_in.h | 179 - externals/ace/os_include/netinet/os_tcp.h | 46 - externals/ace/os_include/os_aio.h | 47 - externals/ace/os_include/os_assert.h | 46 - externals/ace/os_include/os_byteswap.h | 41 - externals/ace/os_include/os_complex.h | 42 - externals/ace/os_include/os_cpio.h | 42 - externals/ace/os_include/os_ctype.h | 48 - externals/ace/os_include/os_dirent.h | 110 - externals/ace/os_include/os_dlfcn.h | 101 - externals/ace/os_include/os_errno.h | 458 - externals/ace/os_include/os_fcntl.h | 106 - externals/ace/os_include/os_fenv.h | 42 - externals/ace/os_include/os_float.h | 42 - externals/ace/os_include/os_fmtmsg.h | 42 - externals/ace/os_include/os_fnmatch.h | 42 - externals/ace/os_include/os_ftw.h | 44 - externals/ace/os_include/os_glob.h | 42 - externals/ace/os_include/os_grp.h | 44 - externals/ace/os_include/os_iconv.h | 44 - externals/ace/os_include/os_intrin.h | 57 - externals/ace/os_include/os_inttypes.h | 46 - externals/ace/os_include/os_iso646.h | 42 - externals/ace/os_include/os_kstat.h | 43 - externals/ace/os_include/os_langinfo.h | 44 - externals/ace/os_include/os_libgen.h | 42 - externals/ace/os_include/os_limits.h | 143 - externals/ace/os_include/os_local.h | 44 - externals/ace/os_include/os_math.h | 44 - externals/ace/os_include/os_monetary.h | 44 - externals/ace/os_include/os_mqueue.h | 44 - externals/ace/os_include/os_ndbm.h | 44 - externals/ace/os_include/os_netdb.h | 100 - externals/ace/os_include/os_nl_types.h | 42 - externals/ace/os_include/os_pdh.h | 45 - externals/ace/os_include/os_pdhmsg.h | 41 - externals/ace/os_include/os_poll.h | 42 - externals/ace/os_include/os_pthread.h | 424 - externals/ace/os_include/os_pwd.h | 58 - externals/ace/os_include/os_regex.h | 48 - externals/ace/os_include/os_sched.h | 56 - externals/ace/os_include/os_search.h | 44 - externals/ace/os_include/os_semaphore.h | 77 - externals/ace/os_include/os_setjmp.h | 42 - externals/ace/os_include/os_signal.h | 249 - externals/ace/os_include/os_spawn.h | 46 - externals/ace/os_include/os_stdarg.h | 50 - externals/ace/os_include/os_stdbool.h | 42 - externals/ace/os_include/os_stddef.h | 75 - externals/ace/os_include/os_stdint.h | 141 - externals/ace/os_include/os_stdio.h | 87 - externals/ace/os_include/os_stdlib.h | 85 - externals/ace/os_include/os_string.h | 53 - externals/ace/os_include/os_strings.h | 52 - externals/ace/os_include/os_stropts.h | 114 - externals/ace/os_include/os_syslog.h | 42 - externals/ace/os_include/os_tar.h | 42 - externals/ace/os_include/os_termios.h | 46 - externals/ace/os_include/os_tgmath.h | 45 - externals/ace/os_include/os_time.h | 119 - externals/ace/os_include/os_trace.h | 44 - externals/ace/os_include/os_typeinfo.h | 39 - externals/ace/os_include/os_ucontext.h | 48 - externals/ace/os_include/os_ulimit.h | 42 - externals/ace/os_include/os_unistd.h | 196 - externals/ace/os_include/os_utime.h | 44 - externals/ace/os_include/os_utmpx.h | 44 - externals/ace/os_include/os_wchar.h | 57 - externals/ace/os_include/os_wctype.h | 45 - externals/ace/os_include/os_wordexp.h | 44 - externals/ace/os_include/sys/os_ipc.h | 74 - externals/ace/os_include/sys/os_loadavg.h | 41 - externals/ace/os_include/sys/os_mman.h | 122 - externals/ace/os_include/sys/os_msg.h | 55 - externals/ace/os_include/sys/os_pstat.h | 42 - externals/ace/os_include/sys/os_resource.h | 104 - externals/ace/os_include/sys/os_select.h | 61 - externals/ace/os_include/sys/os_sem.h | 90 - externals/ace/os_include/sys/os_shm.h | 48 - externals/ace/os_include/sys/os_socket.h | 307 - externals/ace/os_include/sys/os_stat.h | 157 - externals/ace/os_include/sys/os_statvfs.h | 42 - externals/ace/os_include/sys/os_sysctl.h | 41 - externals/ace/os_include/sys/os_sysinfo.h | 39 - externals/ace/os_include/sys/os_time.h | 56 - externals/ace/os_include/sys/os_timeb.h | 44 - externals/ace/os_include/sys/os_times.h | 44 - externals/ace/os_include/sys/os_types.h | 157 - externals/ace/os_include/sys/os_uio.h | 77 - externals/ace/os_include/sys/os_un.h | 52 - externals/ace/os_include/sys/os_utsname.h | 42 - externals/ace/os_include/sys/os_wait.h | 97 - externals/ace/post.h | 22 - externals/ace/pre.h | 24 - externals/ace/streams.h | 138 - externals/ace/svc_export.h | 44 - externals/bzip2/CMakeLists.txt | 22 - externals/bzip2/blocksort.c | 1094 -- externals/bzip2/bzlib.c | 1572 -- externals/bzip2/bzlib.h | 282 - externals/bzip2/bzlib_private.h | 509 - externals/bzip2/compress.c | 672 - externals/bzip2/crctable.c | 104 - externals/bzip2/decompress.c | 626 - externals/bzip2/huffman.c | 205 - externals/bzip2/randtable.c | 84 - externals/g3dlite/AABox.cpp | 366 - externals/g3dlite/Any.cpp | 1237 -- externals/g3dlite/BinaryFormat.cpp | 81 - externals/g3dlite/BinaryInput.cpp | 568 - externals/g3dlite/BinaryOutput.cpp | 522 - externals/g3dlite/Box.cpp | 393 - externals/g3dlite/CMakeLists.txt | 37 - externals/g3dlite/Capsule.cpp | 179 - externals/g3dlite/CollisionDetection.cpp | 2455 --- externals/g3dlite/CoordinateFrame.cpp | 436 - externals/g3dlite/Crypto.cpp | 70 - externals/g3dlite/Cylinder.cpp | 176 - externals/g3dlite/G3D/AABox.h | 272 - externals/g3dlite/G3D/Any.h | 570 - externals/g3dlite/G3D/AnyVal.h | 512 - externals/g3dlite/G3D/AreaMemoryManager.h | 93 - externals/g3dlite/G3D/Array.h | 1274 -- externals/g3dlite/G3D/AtomicInt32.h | 164 - externals/g3dlite/G3D/BinaryFormat.h | 140 - externals/g3dlite/G3D/BinaryInput.h | 441 - externals/g3dlite/G3D/BinaryOutput.h | 421 - externals/g3dlite/G3D/BoundsTrait.h | 20 - externals/g3dlite/G3D/Box.h | 195 - externals/g3dlite/G3D/Box2D.h | 121 - externals/g3dlite/G3D/BumpMapPreprocess.h | 61 - externals/g3dlite/G3D/Capsule.h | 90 - externals/g3dlite/G3D/CollisionDetection.h | 1205 -- externals/g3dlite/G3D/Color1.h | 144 - externals/g3dlite/G3D/Color1uint8.h | 91 - externals/g3dlite/G3D/Color3.h | 432 - externals/g3dlite/G3D/Color3uint8.h | 110 - externals/g3dlite/G3D/Color4.h | 338 - externals/g3dlite/G3D/Color4uint8.h | 115 - externals/g3dlite/G3D/Cone.h | 68 - externals/g3dlite/G3D/ConvexPolyhedron.h | 180 - externals/g3dlite/G3D/CoordinateFrame.h | 331 - externals/g3dlite/G3D/Crypto.h | 96 - externals/g3dlite/G3D/Cylinder.h | 92 - externals/g3dlite/G3D/EqualsTrait.h | 26 - externals/g3dlite/G3D/G3D.h | 162 - externals/g3dlite/G3D/G3DAll.h | 26 - externals/g3dlite/G3D/G3DGameUnits.h | 42 - externals/g3dlite/G3D/GCamera.h | 337 - externals/g3dlite/G3D/GImage.h | 607 - externals/g3dlite/G3D/GLight.h | 106 - externals/g3dlite/G3D/GMutex.h | 123 - externals/g3dlite/G3D/GThread.h | 121 - externals/g3dlite/G3D/GUniqueID.h | 69 - externals/g3dlite/G3D/HashTrait.h | 92 - externals/g3dlite/G3D/Image1.h | 81 - externals/g3dlite/G3D/Image1uint8.h | 80 - externals/g3dlite/G3D/Image3.h | 81 - externals/g3dlite/G3D/Image3uint8.h | 85 - externals/g3dlite/G3D/Image4.h | 86 - externals/g3dlite/G3D/Image4uint8.h | 85 - externals/g3dlite/G3D/ImageFormat.h | 419 - externals/g3dlite/G3D/Intersect.h | 55 - externals/g3dlite/G3D/KDTree.h | 1667 -- externals/g3dlite/G3D/Line.h | 105 - externals/g3dlite/G3D/LineSegment.h | 115 - externals/g3dlite/G3D/Log.h | 109 - externals/g3dlite/G3D/Map2D.h | 667 - externals/g3dlite/G3D/Matrix.h | 634 - externals/g3dlite/G3D/Matrix2.h | 69 - externals/g3dlite/G3D/Matrix3.h | 366 - externals/g3dlite/G3D/Matrix4.h | 249 - externals/g3dlite/G3D/MemoryManager.h | 93 - externals/g3dlite/G3D/MeshAlg.h | 683 - externals/g3dlite/G3D/MeshBuilder.h | 82 - externals/g3dlite/G3D/NetAddress.h | 132 - externals/g3dlite/G3D/NetworkDevice.h | 738 - externals/g3dlite/G3D/ParseError.h | 59 - externals/g3dlite/G3D/PhysicsFrame.h | 74 - externals/g3dlite/G3D/Plane.h | 161 - externals/g3dlite/G3D/PointHashGrid.h | 917 -- externals/g3dlite/G3D/PointKDTree.h | 1185 -- externals/g3dlite/G3D/Pointer.h | 292 - externals/g3dlite/G3D/PositionTrait.h | 7 - externals/g3dlite/G3D/PrecomputedRandom.h | 110 - externals/g3dlite/G3D/Quat.h | 725 - externals/g3dlite/G3D/Quat.inl | 36 - externals/g3dlite/G3D/Queue.h | 364 - externals/g3dlite/G3D/Random.h | 139 - externals/g3dlite/G3D/Ray.h | 371 - externals/g3dlite/G3D/Rect2D.h | 417 - externals/g3dlite/G3D/ReferenceCount.h | 570 - externals/g3dlite/G3D/RegistryUtil.h | 97 - externals/g3dlite/G3D/Set.h | 186 - externals/g3dlite/G3D/SmallArray.h | 155 - externals/g3dlite/G3D/Sphere.h | 148 - externals/g3dlite/G3D/Spline.h | 367 - externals/g3dlite/G3D/Stopwatch.h | 144 - externals/g3dlite/G3D/System.h | 507 - externals/g3dlite/G3D/Table.h | 924 -- externals/g3dlite/G3D/TextInput.h | 801 - externals/g3dlite/G3D/TextOutput.h | 249 - externals/g3dlite/G3D/ThreadSet.h | 87 - externals/g3dlite/G3D/Triangle.h | 160 - externals/g3dlite/G3D/UprightFrame.h | 83 - externals/g3dlite/G3D/Vector2.h | 454 - externals/g3dlite/G3D/Vector2.inl | 18 - externals/g3dlite/G3D/Vector2int16.h | 127 - externals/g3dlite/G3D/Vector3.h | 798 - externals/g3dlite/G3D/Vector3.inl | 249 - externals/g3dlite/G3D/Vector3int16.h | 127 - externals/g3dlite/G3D/Vector3int32.h | 128 - externals/g3dlite/G3D/Vector4.h | 716 - externals/g3dlite/G3D/Vector4.inl | 191 - externals/g3dlite/G3D/Vector4int8.h | 113 - externals/g3dlite/G3D/WeakCache.h | 122 - externals/g3dlite/G3D/Welder.h | 82 - externals/g3dlite/G3D/WrapMode.h | 93 - externals/g3dlite/G3D/constants.h | 129 - externals/g3dlite/G3D/debug.h | 66 - externals/g3dlite/G3D/debugAssert.h | 233 - externals/g3dlite/G3D/debugPrintf.h | 62 - externals/g3dlite/G3D/enumclass.h | 147 - externals/g3dlite/G3D/fileutils.h | 254 - externals/g3dlite/G3D/filter.h | 29 - externals/g3dlite/G3D/format.h | 44 - externals/g3dlite/G3D/g3dfnmatch.h | 83 - externals/g3dlite/G3D/g3dmath.h | 845 -- externals/g3dlite/G3D/g3dmath.inl | 288 - externals/g3dlite/G3D/platform.h | 331 - externals/g3dlite/G3D/prompt.h | 67 - externals/g3dlite/G3D/serialize.h | 30 - externals/g3dlite/G3D/splinefunc.h | 118 - externals/g3dlite/G3D/stringutils.h | 140 - externals/g3dlite/G3D/uint128.h | 51 - externals/g3dlite/G3D/units.h | 126 - externals/g3dlite/G3D/vectorMath.h | 235 - externals/g3dlite/Line.cpp | 89 - externals/g3dlite/LineSegment.cpp | 236 - externals/g3dlite/Log.cpp | 146 - externals/g3dlite/Matrix3.cpp | 1927 --- externals/g3dlite/Matrix4.cpp | 523 - externals/g3dlite/MemoryManager.cpp | 91 - externals/g3dlite/Plane.cpp | 149 - externals/g3dlite/Quat.cpp | 583 - externals/g3dlite/Random.cpp | 212 - externals/g3dlite/Ray.cpp | 218 - externals/g3dlite/ReferenceCount.cpp | 61 - externals/g3dlite/RegistryUtil.cpp | 290 - externals/g3dlite/Sphere.cpp | 223 - externals/g3dlite/System.cpp | 1746 --- externals/g3dlite/TextInput.cpp | 1136 -- externals/g3dlite/TextOutput.cpp | 452 - externals/g3dlite/Triangle.cpp | 186 - externals/g3dlite/UprightFrame.cpp | 132 - externals/g3dlite/Vector2.cpp | 224 - externals/g3dlite/Vector3.cpp | 507 - externals/g3dlite/Vector4.cpp | 520 - externals/g3dlite/debugAssert.cpp | 389 - externals/g3dlite/fileutils.cpp | 1165 -- externals/g3dlite/format.cpp | 164 - externals/g3dlite/g3dfnmatch.cpp | 204 - externals/g3dlite/g3dmath.cpp | 108 - externals/g3dlite/prompt.cpp | 729 - externals/g3dlite/stringutils.cpp | 275 - externals/gsoap/CMakeLists.txt | 11 - externals/gsoap/soapC.cpp | 1645 -- externals/gsoap/soapH.h | 239 - externals/gsoap/soapServer.cpp | 127 - externals/gsoap/soapStub.h | 184 - externals/gsoap/stdsoap2.cpp | 15198 ------------------- externals/gsoap/stdsoap2.h | 2360 --- externals/jemalloc/CMakeLists.txt | 25 - externals/jemalloc/arena.c | 2446 --- externals/jemalloc/base.c | 106 - externals/jemalloc/chunk.c | 150 - externals/jemalloc/chunk_dss.c | 268 - externals/jemalloc/chunk_mmap.c | 201 - externals/jemalloc/chunk_swap.c | 383 - externals/jemalloc/ckh.c | 601 - externals/jemalloc/ctl.c | 1482 -- externals/jemalloc/extent.c | 41 - externals/jemalloc/hash.c | 2 - externals/jemalloc/huge.c | 298 - externals/jemalloc/jemalloc.c | 1349 -- externals/jemalloc/jemalloc/internal/arena.h | 537 - externals/jemalloc/jemalloc/internal/base.h | 24 - externals/jemalloc/jemalloc/internal/chunk.h | 61 - externals/jemalloc/jemalloc/internal/chunk_dss.h | 29 - externals/jemalloc/jemalloc/internal/chunk_mmap.h | 20 - externals/jemalloc/jemalloc/internal/chunk_swap.h | 33 - externals/jemalloc/jemalloc/internal/ckh.h | 95 - externals/jemalloc/jemalloc/internal/ctl.h | 117 - externals/jemalloc/jemalloc/internal/extent.h | 49 - externals/jemalloc/jemalloc/internal/hash.h | 70 - externals/jemalloc/jemalloc/internal/huge.h | 38 - .../jemalloc/jemalloc/internal/jemalloc_internal.h | 561 - .../jemalloc/internal/jemalloc_internal.h.in | 561 - externals/jemalloc/jemalloc/internal/mb.h | 108 - externals/jemalloc/jemalloc/internal/mutex.h | 61 - externals/jemalloc/jemalloc/internal/prof.h | 171 - externals/jemalloc/jemalloc/internal/ql.h | 83 - externals/jemalloc/jemalloc/internal/qr.h | 67 - externals/jemalloc/jemalloc/internal/rb.h | 973 -- externals/jemalloc/jemalloc/internal/stats.h | 174 - externals/jemalloc/jemalloc/internal/tcache.h | 380 - .../jemalloc/jemalloc/internal/totally_not_p_r_n.h | 60 - externals/jemalloc/jemalloc/jemalloc.h | 42 - externals/jemalloc/jemalloc/jemalloc.h.in | 42 - externals/jemalloc/jemalloc/jemalloc_defs.h | 102 - externals/jemalloc/jemalloc/jemalloc_defs.h.in | 101 - externals/jemalloc/mb.c | 2 - externals/jemalloc/mutex.c | 70 - externals/jemalloc/prof.c | 1328 -- externals/jemalloc/stats.c | 717 - externals/jemalloc/tcache.c | 403 - externals/libmpq/AUTHORS | 10 - externals/libmpq/CMakeLists.txt | 34 - externals/libmpq/COPYING | 339 - externals/libmpq/FAQ | 68 - externals/libmpq/INSTALL | 182 - externals/libmpq/Makefile.am | 26 - externals/libmpq/NEWS | 76 - externals/libmpq/README | 34 - externals/libmpq/THANKS | 21 - externals/libmpq/TODO | 10 - externals/libmpq/autogen.sh | 19 - externals/libmpq/bindings/Makefile.am | 6 - externals/libmpq/bindings/d/Makefile.am | 6 - externals/libmpq/bindings/d/dsss.conf | 2 - externals/libmpq/bindings/d/mpq.d | 318 - externals/libmpq/bindings/python/Makefile.am | 5 - externals/libmpq/bindings/python/mpq-info | 16 - externals/libmpq/bindings/python/mpq.py | 322 - externals/libmpq/config.h | 74 - externals/libmpq/configure.ac | 84 - externals/libmpq/debian/changelog | 35 - externals/libmpq/debian/compat | 1 - externals/libmpq/debian/control | 50 - externals/libmpq/debian/copyright | 23 - externals/libmpq/debian/libmpq-dev.dirs | 6 - externals/libmpq/debian/libmpq-dev.install | 6 - externals/libmpq/debian/libmpq0.dirs | 1 - externals/libmpq/debian/libmpq0.docs | 6 - externals/libmpq/debian/libmpq0.install | 1 - externals/libmpq/debian/python-mpq.install | 1 - externals/libmpq/debian/rules | 112 - externals/libmpq/doc/Makefile.am | 5 - externals/libmpq/doc/man1/Makefile.am | 9 - externals/libmpq/doc/man1/libmpq-config.1 | 69 - externals/libmpq/doc/man3/Makefile.am | 31 - externals/libmpq/doc/man3/libmpq.3 | 207 - externals/libmpq/doc/man3/libmpq__archive_close.3 | 57 - externals/libmpq/doc/man3/libmpq__archive_files.3 | 50 - externals/libmpq/doc/man3/libmpq__archive_offset.3 | 51 - externals/libmpq/doc/man3/libmpq__archive_open.3 | 71 - .../libmpq/doc/man3/libmpq__archive_packed_size.3 | 51 - .../doc/man3/libmpq__archive_unpacked_size.3 | 51 - .../libmpq/doc/man3/libmpq__archive_version.3 | 48 - .../libmpq/doc/man3/libmpq__block_close_offset.3 | 53 - .../libmpq/doc/man3/libmpq__block_open_offset.3 | 65 - externals/libmpq/doc/man3/libmpq__block_read.3 | 78 - .../libmpq/doc/man3/libmpq__block_unpacked_size.3 | 59 - externals/libmpq/doc/man3/libmpq__file_blocks.3 | 54 - .../libmpq/doc/man3/libmpq__file_compressed.3 | 54 - externals/libmpq/doc/man3/libmpq__file_encrypted.3 | 54 - externals/libmpq/doc/man3/libmpq__file_imploded.3 | 54 - externals/libmpq/doc/man3/libmpq__file_number.3 | 52 - externals/libmpq/doc/man3/libmpq__file_offset.3 | 55 - .../libmpq/doc/man3/libmpq__file_packed_size.3 | 55 - externals/libmpq/doc/man3/libmpq__file_read.3 | 77 - .../libmpq/doc/man3/libmpq__file_unpacked_size.3 | 55 - externals/libmpq/doc/man3/libmpq__strerror.3 | 45 - externals/libmpq/doc/man3/libmpq__version.3 | 45 - externals/libmpq/libmpq-config.in | 57 - externals/libmpq/libmpq.pc.in | 10 - externals/libmpq/libmpq/Makefile.am | 23 - externals/libmpq/libmpq/common.c | 220 - externals/libmpq/libmpq/common.h | 61 - externals/libmpq/libmpq/crypt_buf.h | 217 - externals/libmpq/libmpq/explode.c | 602 - externals/libmpq/libmpq/explode.h | 87 - externals/libmpq/libmpq/extract.c | 361 - externals/libmpq/libmpq/extract.h | 106 - externals/libmpq/libmpq/huffman.c | 1101 -- externals/libmpq/libmpq/huffman.h | 151 - externals/libmpq/libmpq/mpq-internal.h | 145 - externals/libmpq/libmpq/mpq.c | 1004 -- externals/libmpq/libmpq/mpq.h | 101 - externals/libmpq/libmpq/pack_begin.h | 34 - externals/libmpq/libmpq/pack_end.h | 31 - externals/libmpq/libmpq/platform.h | 28 - externals/libmpq/libmpq/wave.c | 250 - externals/libmpq/libmpq/wave.h | 45 - externals/libmpq/tools/Makefile.am | 8 - externals/libmpq/tools/crypt_buf_gen.c | 85 - externals/libmpq/win/config.h | 81 - externals/libmpq/win/dirent.h | 230 - externals/libmpq/win/stdint.h | 247 - externals/mersennetwister/MersenneTwister.h | 405 - externals/sockets/Base64.cpp | 262 - externals/sockets/CMakeLists.txt | 21 - externals/sockets/Exception.cpp | 45 - externals/sockets/Ipv4Address.cpp | 192 - externals/sockets/Ipv6Address.cpp | 247 - externals/sockets/Lock.cpp | 52 - externals/sockets/Makefile | 136 - externals/sockets/Mutex.cpp | 77 - externals/sockets/Parse.cpp | 318 - externals/sockets/ResolvServer.cpp | 92 - externals/sockets/ResolvSocket.cpp | 426 - externals/sockets/Socket.cpp | 1726 --- externals/sockets/SocketHandler.cpp | 1377 -- externals/sockets/StdoutLog.cpp | 98 - externals/sockets/StreamSocket.cpp | 145 - externals/sockets/TcpSocket.cpp | 1681 -- externals/sockets/Thread.cpp | 154 - externals/sockets/UdpSocket.cpp | 810 - externals/sockets/Utility.cpp | 960 -- externals/sockets/include/Base64.h | 77 - externals/sockets/include/Exception.h | 55 - externals/sockets/include/File.h | 82 - externals/sockets/include/IFile.h | 71 - externals/sockets/include/ISocketHandler.h | 231 - externals/sockets/include/Ipv4Address.h | 95 - externals/sockets/include/Ipv6Address.h | 105 - externals/sockets/include/ListenSocket.h | 418 - externals/sockets/include/Lock.h | 58 - externals/sockets/include/Mutex.h | 68 - externals/sockets/include/Parse.h | 100 - externals/sockets/include/ResolvServer.h | 72 - externals/sockets/include/ResolvSocket.h | 105 - externals/sockets/include/SctpSocket.h | 108 - externals/sockets/include/Socket.h | 735 - externals/sockets/include/SocketAddress.h | 93 - externals/sockets/include/SocketHandler.h | 265 - externals/sockets/include/StdLog.h | 73 - externals/sockets/include/StdoutLog.h | 55 - externals/sockets/include/StreamSocket.h | 124 - externals/sockets/include/TcpSocket.h | 356 - externals/sockets/include/Thread.h | 100 - externals/sockets/include/UdpSocket.h | 215 - externals/sockets/include/Utility.h | 186 - externals/sockets/include/socket_include.h | 290 - externals/sockets/include/sockets-config.h | 90 - externals/sockets/network_kist.txt | 20 - externals/sockets/socket_include.cpp | 89 - externals/utf8cpp/utf8.h | 34 - externals/utf8cpp/utf8/checked.h | 323 - externals/utf8cpp/utf8/core.h | 358 - externals/utf8cpp/utf8/unchecked.h | 228 - externals/zlib/CMakeLists.txt | 30 - externals/zlib/adler32.c | 169 - externals/zlib/compress.c | 80 - externals/zlib/crc32.c | 442 - externals/zlib/crc32.h | 441 - externals/zlib/deflate.c | 1834 --- externals/zlib/deflate.h | 342 - externals/zlib/example.c | 565 - externals/zlib/gzclose.c | 25 - externals/zlib/gzguts.h | 132 - externals/zlib/gzlib.c | 537 - externals/zlib/gzread.c | 653 - externals/zlib/gzwrite.c | 531 - externals/zlib/infback.c | 632 - externals/zlib/inffast.c | 340 - externals/zlib/inffast.h | 11 - externals/zlib/inffixed.h | 94 - externals/zlib/inflate.c | 1480 -- externals/zlib/inflate.h | 122 - externals/zlib/inftrees.c | 330 - externals/zlib/inftrees.h | 62 - externals/zlib/minigzip.c | 440 - externals/zlib/trees.c | 1244 -- externals/zlib/trees.h | 128 - externals/zlib/uncompr.c | 59 - externals/zlib/zconf.h | 428 - externals/zlib/zlib.h | 1613 -- externals/zlib/zutil.c | 318 - externals/zlib/zutil.h | 274 - src/server/authserver/CMakeLists.txt | 8 +- src/server/collision/CMakeLists.txt | 10 +- src/server/game/CMakeLists.txt | 134 +- src/server/scripts/CMakeLists.txt | 6 +- src/server/shared/CMakeLists.txt | 30 +- src/server/worldserver/CMakeLists.txt | 16 +- src/tools/map_extractor/CMakeLists.txt | 6 +- src/tools/vmap3_assembler/CMakeLists.txt | 6 +- src/tools/vmap3_extractor/CMakeLists.txt | 6 +- 3483 files changed, 466739 insertions(+), 466738 deletions(-) create mode 100644 dep/CMakeLists.txt create mode 100644 dep/PackageList.txt create mode 100644 dep/SFMT/SFMT-alti.h create mode 100644 dep/SFMT/SFMT-params.h create mode 100644 dep/SFMT/SFMT-sse2.h create mode 100644 dep/SFMT/SFMT.c create mode 100644 dep/SFMT/SFMT.h create mode 100644 dep/acelite/CMakeLists.txt create mode 100644 dep/acelite/ace/ACE.cpp create mode 100644 dep/acelite/ace/ACE.h create mode 100644 dep/acelite/ace/ACE.inl create mode 100644 dep/acelite/ace/ACE.pc.in create mode 100644 dep/acelite/ace/ACE_crc32.cpp create mode 100644 dep/acelite/ace/ACE_crc_ccitt.cpp create mode 100644 dep/acelite/ace/ACE_export.h create mode 100644 dep/acelite/ace/ARGV.cpp create mode 100644 dep/acelite/ace/ARGV.h create mode 100644 dep/acelite/ace/ARGV.inl create mode 100644 dep/acelite/ace/ATM_Acceptor.cpp create mode 100644 dep/acelite/ace/ATM_Acceptor.h create mode 100644 dep/acelite/ace/ATM_Acceptor.inl create mode 100644 dep/acelite/ace/ATM_Addr.cpp create mode 100644 dep/acelite/ace/ATM_Addr.h create mode 100644 dep/acelite/ace/ATM_Addr.inl create mode 100644 dep/acelite/ace/ATM_Connector.cpp create mode 100644 dep/acelite/ace/ATM_Connector.h create mode 100644 dep/acelite/ace/ATM_Connector.inl create mode 100644 dep/acelite/ace/ATM_Params.cpp create mode 100644 dep/acelite/ace/ATM_Params.h create mode 100644 dep/acelite/ace/ATM_Params.inl create mode 100644 dep/acelite/ace/ATM_QoS.cpp create mode 100644 dep/acelite/ace/ATM_QoS.h create mode 100644 dep/acelite/ace/ATM_QoS.inl create mode 100644 dep/acelite/ace/ATM_Stream.cpp create mode 100644 dep/acelite/ace/ATM_Stream.h create mode 100644 dep/acelite/ace/ATM_Stream.inl create mode 100644 dep/acelite/ace/Acceptor.cpp create mode 100644 dep/acelite/ace/Acceptor.h create mode 100644 dep/acelite/ace/Activation_Queue.cpp create mode 100644 dep/acelite/ace/Activation_Queue.h create mode 100644 dep/acelite/ace/Activation_Queue.inl create mode 100644 dep/acelite/ace/Active_Map_Manager.cpp create mode 100644 dep/acelite/ace/Active_Map_Manager.h create mode 100644 dep/acelite/ace/Active_Map_Manager.inl create mode 100644 dep/acelite/ace/Active_Map_Manager_T.cpp create mode 100644 dep/acelite/ace/Active_Map_Manager_T.h create mode 100644 dep/acelite/ace/Active_Map_Manager_T.inl create mode 100644 dep/acelite/ace/Addr.cpp create mode 100644 dep/acelite/ace/Addr.h create mode 100644 dep/acelite/ace/Addr.inl create mode 100644 dep/acelite/ace/Arg_Shifter.cpp create mode 100644 dep/acelite/ace/Arg_Shifter.h create mode 100644 dep/acelite/ace/Argv_Type_Converter.cpp create mode 100644 dep/acelite/ace/Argv_Type_Converter.h create mode 100644 dep/acelite/ace/Argv_Type_Converter.inl create mode 100644 dep/acelite/ace/Array.h create mode 100644 dep/acelite/ace/Array_Base.cpp create mode 100644 dep/acelite/ace/Array_Base.h create mode 100644 dep/acelite/ace/Array_Base.inl create mode 100644 dep/acelite/ace/Array_Map.cpp create mode 100644 dep/acelite/ace/Array_Map.h create mode 100644 dep/acelite/ace/Array_Map.inl create mode 100644 dep/acelite/ace/Assert.cpp create mode 100644 dep/acelite/ace/Assert.h create mode 100644 dep/acelite/ace/Asynch_Acceptor.cpp create mode 100644 dep/acelite/ace/Asynch_Acceptor.h create mode 100644 dep/acelite/ace/Asynch_Connector.cpp create mode 100644 dep/acelite/ace/Asynch_Connector.h create mode 100644 dep/acelite/ace/Asynch_IO.cpp create mode 100644 dep/acelite/ace/Asynch_IO.h create mode 100644 dep/acelite/ace/Asynch_IO_Impl.cpp create mode 100644 dep/acelite/ace/Asynch_IO_Impl.h create mode 100644 dep/acelite/ace/Asynch_IO_Impl.inl create mode 100644 dep/acelite/ace/Asynch_Pseudo_Task.cpp create mode 100644 dep/acelite/ace/Asynch_Pseudo_Task.h create mode 100644 dep/acelite/ace/Atomic_Op.cpp create mode 100644 dep/acelite/ace/Atomic_Op.h create mode 100644 dep/acelite/ace/Atomic_Op.inl create mode 100644 dep/acelite/ace/Atomic_Op_GCC_T.cpp create mode 100644 dep/acelite/ace/Atomic_Op_GCC_T.h create mode 100644 dep/acelite/ace/Atomic_Op_GCC_T.inl create mode 100644 dep/acelite/ace/Atomic_Op_Sparc.c create mode 100644 dep/acelite/ace/Atomic_Op_Sparc.h create mode 100644 dep/acelite/ace/Atomic_Op_T.cpp create mode 100644 dep/acelite/ace/Atomic_Op_T.h create mode 100644 dep/acelite/ace/Atomic_Op_T.inl create mode 100644 dep/acelite/ace/Auto_Event.cpp create mode 100644 dep/acelite/ace/Auto_Event.h create mode 100644 dep/acelite/ace/Auto_Event.inl create mode 100644 dep/acelite/ace/Auto_Functor.cpp create mode 100644 dep/acelite/ace/Auto_Functor.h create mode 100644 dep/acelite/ace/Auto_Functor.inl create mode 100644 dep/acelite/ace/Auto_IncDec_T.cpp create mode 100644 dep/acelite/ace/Auto_IncDec_T.h create mode 100644 dep/acelite/ace/Auto_IncDec_T.inl create mode 100644 dep/acelite/ace/Auto_Ptr.cpp create mode 100644 dep/acelite/ace/Auto_Ptr.h create mode 100644 dep/acelite/ace/Auto_Ptr.inl create mode 100644 dep/acelite/ace/Barrier.cpp create mode 100644 dep/acelite/ace/Barrier.h create mode 100644 dep/acelite/ace/Barrier.inl create mode 100644 dep/acelite/ace/Base_Thread_Adapter.cpp create mode 100644 dep/acelite/ace/Base_Thread_Adapter.h create mode 100644 dep/acelite/ace/Base_Thread_Adapter.inl create mode 100644 dep/acelite/ace/Based_Pointer_Repository.cpp create mode 100644 dep/acelite/ace/Based_Pointer_Repository.h create mode 100644 dep/acelite/ace/Based_Pointer_T.cpp create mode 100644 dep/acelite/ace/Based_Pointer_T.h create mode 100644 dep/acelite/ace/Based_Pointer_T.inl create mode 100644 dep/acelite/ace/Basic_Stats.cpp create mode 100644 dep/acelite/ace/Basic_Stats.h create mode 100644 dep/acelite/ace/Basic_Stats.inl create mode 100644 dep/acelite/ace/Basic_Types.cpp create mode 100644 dep/acelite/ace/Basic_Types.h create mode 100644 dep/acelite/ace/Basic_Types.inl create mode 100644 dep/acelite/ace/Bound_Ptr.h create mode 100644 dep/acelite/ace/Bound_Ptr.inl create mode 100644 dep/acelite/ace/CDR_Base.cpp create mode 100644 dep/acelite/ace/CDR_Base.h create mode 100644 dep/acelite/ace/CDR_Base.inl create mode 100644 dep/acelite/ace/CDR_Size.cpp create mode 100644 dep/acelite/ace/CDR_Size.h create mode 100644 dep/acelite/ace/CDR_Size.inl create mode 100644 dep/acelite/ace/CDR_Stream.cpp create mode 100644 dep/acelite/ace/CDR_Stream.h create mode 100644 dep/acelite/ace/CDR_Stream.inl create mode 100644 dep/acelite/ace/CE_Screen_Output.cpp create mode 100644 dep/acelite/ace/CE_Screen_Output.h create mode 100644 dep/acelite/ace/CMakeLists.txt create mode 100644 dep/acelite/ace/CORBA_macros.h create mode 100644 dep/acelite/ace/Cache_Map_Manager_T.cpp create mode 100644 dep/acelite/ace/Cache_Map_Manager_T.h create mode 100644 dep/acelite/ace/Cache_Map_Manager_T.inl create mode 100644 dep/acelite/ace/Cached_Connect_Strategy_T.cpp create mode 100644 dep/acelite/ace/Cached_Connect_Strategy_T.h create mode 100644 dep/acelite/ace/Caching_Strategies_T.cpp create mode 100644 dep/acelite/ace/Caching_Strategies_T.h create mode 100644 dep/acelite/ace/Caching_Strategies_T.inl create mode 100644 dep/acelite/ace/Caching_Utility_T.cpp create mode 100644 dep/acelite/ace/Caching_Utility_T.h create mode 100644 dep/acelite/ace/Capabilities.cpp create mode 100644 dep/acelite/ace/Capabilities.h create mode 100644 dep/acelite/ace/Capabilities.inl create mode 100644 dep/acelite/ace/Cleanup.cpp create mode 100644 dep/acelite/ace/Cleanup.h create mode 100644 dep/acelite/ace/Cleanup.inl create mode 100644 dep/acelite/ace/Cleanup_Strategies_T.cpp create mode 100644 dep/acelite/ace/Cleanup_Strategies_T.h create mode 100644 dep/acelite/ace/Codecs.cpp create mode 100644 dep/acelite/ace/Codecs.h create mode 100644 dep/acelite/ace/Codeset_IBM1047.cpp create mode 100644 dep/acelite/ace/Codeset_IBM1047.h create mode 100644 dep/acelite/ace/Codeset_Registry.cpp create mode 100644 dep/acelite/ace/Codeset_Registry.h create mode 100644 dep/acelite/ace/Codeset_Registry.inl create mode 100644 dep/acelite/ace/Codeset_Registry_db.cpp create mode 100644 dep/acelite/ace/Codeset_Symbols.h create mode 100644 dep/acelite/ace/Condition_Recursive_Thread_Mutex.cpp create mode 100644 dep/acelite/ace/Condition_Recursive_Thread_Mutex.h create mode 100644 dep/acelite/ace/Condition_T.cpp create mode 100644 dep/acelite/ace/Condition_T.h create mode 100644 dep/acelite/ace/Condition_T.inl create mode 100644 dep/acelite/ace/Condition_Thread_Mutex.cpp create mode 100644 dep/acelite/ace/Condition_Thread_Mutex.h create mode 100644 dep/acelite/ace/Condition_Thread_Mutex.inl create mode 100644 dep/acelite/ace/Configuration.cpp create mode 100644 dep/acelite/ace/Configuration.h create mode 100644 dep/acelite/ace/Configuration.inl create mode 100644 dep/acelite/ace/Configuration_Import_Export.cpp create mode 100644 dep/acelite/ace/Configuration_Import_Export.h create mode 100644 dep/acelite/ace/Connection_Recycling_Strategy.cpp create mode 100644 dep/acelite/ace/Connection_Recycling_Strategy.h create mode 100644 dep/acelite/ace/Connector.cpp create mode 100644 dep/acelite/ace/Connector.h create mode 100644 dep/acelite/ace/Containers.cpp create mode 100644 dep/acelite/ace/Containers.h create mode 100644 dep/acelite/ace/Containers.inl create mode 100644 dep/acelite/ace/Containers_T.cpp create mode 100644 dep/acelite/ace/Containers_T.h create mode 100644 dep/acelite/ace/Containers_T.inl create mode 100644 dep/acelite/ace/Copy_Disabled.cpp create mode 100644 dep/acelite/ace/Copy_Disabled.h create mode 100644 dep/acelite/ace/Countdown_Time.cpp create mode 100644 dep/acelite/ace/Countdown_Time.h create mode 100644 dep/acelite/ace/Countdown_Time.inl create mode 100644 dep/acelite/ace/DEV.cpp create mode 100644 dep/acelite/ace/DEV.h create mode 100644 dep/acelite/ace/DEV.inl create mode 100644 dep/acelite/ace/DEV_Addr.cpp create mode 100644 dep/acelite/ace/DEV_Addr.h create mode 100644 dep/acelite/ace/DEV_Addr.inl create mode 100644 dep/acelite/ace/DEV_Connector.cpp create mode 100644 dep/acelite/ace/DEV_Connector.h create mode 100644 dep/acelite/ace/DEV_Connector.inl create mode 100644 dep/acelite/ace/DEV_IO.cpp create mode 100644 dep/acelite/ace/DEV_IO.h create mode 100644 dep/acelite/ace/DEV_IO.inl create mode 100644 dep/acelite/ace/DLL.cpp create mode 100644 dep/acelite/ace/DLL.h create mode 100644 dep/acelite/ace/DLL_Manager.cpp create mode 100644 dep/acelite/ace/DLL_Manager.h create mode 100644 dep/acelite/ace/Date_Time.cpp create mode 100644 dep/acelite/ace/Date_Time.h create mode 100644 dep/acelite/ace/Date_Time.inl create mode 100644 dep/acelite/ace/Default_Constants.h create mode 100644 dep/acelite/ace/Dev_Poll_Reactor.cpp create mode 100644 dep/acelite/ace/Dev_Poll_Reactor.h create mode 100644 dep/acelite/ace/Dev_Poll_Reactor.inl create mode 100644 dep/acelite/ace/Dirent.cpp create mode 100644 dep/acelite/ace/Dirent.h create mode 100644 dep/acelite/ace/Dirent.inl create mode 100644 dep/acelite/ace/Dirent_Selector.cpp create mode 100644 dep/acelite/ace/Dirent_Selector.h create mode 100644 dep/acelite/ace/Dirent_Selector.inl create mode 100644 dep/acelite/ace/Dump.cpp create mode 100644 dep/acelite/ace/Dump.h create mode 100644 dep/acelite/ace/Dump_T.cpp create mode 100644 dep/acelite/ace/Dump_T.h create mode 100644 dep/acelite/ace/Dynamic.cpp create mode 100644 dep/acelite/ace/Dynamic.h create mode 100644 dep/acelite/ace/Dynamic.inl create mode 100644 dep/acelite/ace/Dynamic_Message_Strategy.cpp create mode 100644 dep/acelite/ace/Dynamic_Message_Strategy.h create mode 100644 dep/acelite/ace/Dynamic_Message_Strategy.inl create mode 100644 dep/acelite/ace/Dynamic_Service.cpp create mode 100644 dep/acelite/ace/Dynamic_Service.h create mode 100644 dep/acelite/ace/Dynamic_Service.inl create mode 100644 dep/acelite/ace/Dynamic_Service_Base.cpp create mode 100644 dep/acelite/ace/Dynamic_Service_Base.h create mode 100644 dep/acelite/ace/Dynamic_Service_Dependency.cpp create mode 100644 dep/acelite/ace/Dynamic_Service_Dependency.h create mode 100644 dep/acelite/ace/Encoding_Converter.cpp create mode 100644 dep/acelite/ace/Encoding_Converter.h create mode 100644 dep/acelite/ace/Encoding_Converter_Factory.cpp create mode 100644 dep/acelite/ace/Encoding_Converter_Factory.h create mode 100644 dep/acelite/ace/Env_Value_T.cpp create mode 100644 dep/acelite/ace/Env_Value_T.h create mode 100644 dep/acelite/ace/Env_Value_T.inl create mode 100644 dep/acelite/ace/Event.cpp create mode 100644 dep/acelite/ace/Event.h create mode 100644 dep/acelite/ace/Event.inl create mode 100644 dep/acelite/ace/Event_Handler.cpp create mode 100644 dep/acelite/ace/Event_Handler.h create mode 100644 dep/acelite/ace/Event_Handler.inl create mode 100644 dep/acelite/ace/Event_Handler_T.cpp create mode 100644 dep/acelite/ace/Event_Handler_T.h create mode 100644 dep/acelite/ace/Event_Handler_T.inl create mode 100644 dep/acelite/ace/Exception_Macros.h create mode 100644 dep/acelite/ace/FIFO.cpp create mode 100644 dep/acelite/ace/FIFO.h create mode 100644 dep/acelite/ace/FIFO.inl create mode 100644 dep/acelite/ace/FIFO_Recv.cpp create mode 100644 dep/acelite/ace/FIFO_Recv.h create mode 100644 dep/acelite/ace/FIFO_Recv.inl create mode 100644 dep/acelite/ace/FIFO_Recv_Msg.cpp create mode 100644 dep/acelite/ace/FIFO_Recv_Msg.h create mode 100644 dep/acelite/ace/FIFO_Recv_Msg.inl create mode 100644 dep/acelite/ace/FIFO_Send.cpp create mode 100644 dep/acelite/ace/FIFO_Send.h create mode 100644 dep/acelite/ace/FIFO_Send.inl create mode 100644 dep/acelite/ace/FIFO_Send_Msg.cpp create mode 100644 dep/acelite/ace/FIFO_Send_Msg.h create mode 100644 dep/acelite/ace/FIFO_Send_Msg.inl create mode 100644 dep/acelite/ace/FILE.cpp create mode 100644 dep/acelite/ace/FILE.h create mode 100644 dep/acelite/ace/FILE.inl create mode 100644 dep/acelite/ace/FILE_Addr.cpp create mode 100644 dep/acelite/ace/FILE_Addr.h create mode 100644 dep/acelite/ace/FILE_Addr.inl create mode 100644 dep/acelite/ace/FILE_Connector.cpp create mode 100644 dep/acelite/ace/FILE_Connector.h create mode 100644 dep/acelite/ace/FILE_Connector.inl create mode 100644 dep/acelite/ace/FILE_IO.cpp create mode 100644 dep/acelite/ace/FILE_IO.h create mode 100644 dep/acelite/ace/FILE_IO.inl create mode 100644 dep/acelite/ace/File_Lock.cpp create mode 100644 dep/acelite/ace/File_Lock.h create mode 100644 dep/acelite/ace/File_Lock.inl create mode 100644 dep/acelite/ace/Filecache.cpp create mode 100644 dep/acelite/ace/Filecache.h create mode 100644 dep/acelite/ace/Flag_Manip.cpp create mode 100644 dep/acelite/ace/Flag_Manip.h create mode 100644 dep/acelite/ace/Flag_Manip.inl create mode 100644 dep/acelite/ace/Framework_Component.cpp create mode 100644 dep/acelite/ace/Framework_Component.h create mode 100644 dep/acelite/ace/Framework_Component.inl create mode 100644 dep/acelite/ace/Framework_Component_T.cpp create mode 100644 dep/acelite/ace/Framework_Component_T.h create mode 100644 dep/acelite/ace/Free_List.cpp create mode 100644 dep/acelite/ace/Free_List.h create mode 100644 dep/acelite/ace/Functor.cpp create mode 100644 dep/acelite/ace/Functor.h create mode 100644 dep/acelite/ace/Functor.inl create mode 100644 dep/acelite/ace/Functor_String.cpp create mode 100644 dep/acelite/ace/Functor_String.h create mode 100644 dep/acelite/ace/Functor_String.inl create mode 100644 dep/acelite/ace/Functor_T.cpp create mode 100644 dep/acelite/ace/Functor_T.h create mode 100644 dep/acelite/ace/Functor_T.inl create mode 100644 dep/acelite/ace/Future.cpp create mode 100644 dep/acelite/ace/Future.h create mode 100644 dep/acelite/ace/Future_Set.cpp create mode 100644 dep/acelite/ace/Future_Set.h create mode 100644 dep/acelite/ace/Get_Opt.cpp create mode 100644 dep/acelite/ace/Get_Opt.h create mode 100644 dep/acelite/ace/Get_Opt.inl create mode 100644 dep/acelite/ace/Global_Macros.h create mode 100644 dep/acelite/ace/Guard_T.cpp create mode 100644 dep/acelite/ace/Guard_T.h create mode 100644 dep/acelite/ace/Guard_T.inl create mode 100644 dep/acelite/ace/Handle_Gobbler.h create mode 100644 dep/acelite/ace/Handle_Gobbler.inl create mode 100644 dep/acelite/ace/Handle_Ops.cpp create mode 100644 dep/acelite/ace/Handle_Ops.h create mode 100644 dep/acelite/ace/Handle_Set.cpp create mode 100644 dep/acelite/ace/Handle_Set.h create mode 100644 dep/acelite/ace/Handle_Set.inl create mode 100644 dep/acelite/ace/Hash_Cache_Map_Manager_T.cpp create mode 100644 dep/acelite/ace/Hash_Cache_Map_Manager_T.h create mode 100644 dep/acelite/ace/Hash_Cache_Map_Manager_T.inl create mode 100644 dep/acelite/ace/Hash_Map_Manager.h create mode 100644 dep/acelite/ace/Hash_Map_Manager_T.cpp create mode 100644 dep/acelite/ace/Hash_Map_Manager_T.h create mode 100644 dep/acelite/ace/Hash_Map_Manager_T.inl create mode 100644 dep/acelite/ace/Hash_Map_With_Allocator_T.cpp create mode 100644 dep/acelite/ace/Hash_Map_With_Allocator_T.h create mode 100644 dep/acelite/ace/Hash_Map_With_Allocator_T.inl create mode 100644 dep/acelite/ace/Hash_Multi_Map_Manager_T.cpp create mode 100644 dep/acelite/ace/Hash_Multi_Map_Manager_T.h create mode 100644 dep/acelite/ace/Hash_Multi_Map_Manager_T.inl create mode 100644 dep/acelite/ace/Hashable.cpp create mode 100644 dep/acelite/ace/Hashable.h create mode 100644 dep/acelite/ace/Hashable.inl create mode 100644 dep/acelite/ace/High_Res_Timer.cpp create mode 100644 dep/acelite/ace/High_Res_Timer.h create mode 100644 dep/acelite/ace/High_Res_Timer.inl create mode 100644 dep/acelite/ace/ICMP_Socket.cpp create mode 100644 dep/acelite/ace/ICMP_Socket.h create mode 100644 dep/acelite/ace/INET_Addr.cpp create mode 100644 dep/acelite/ace/INET_Addr.h create mode 100644 dep/acelite/ace/INET_Addr.inl create mode 100644 dep/acelite/ace/IOStream.cpp create mode 100644 dep/acelite/ace/IOStream.h create mode 100644 dep/acelite/ace/IOStream_T.cpp create mode 100644 dep/acelite/ace/IOStream_T.h create mode 100644 dep/acelite/ace/IOStream_T.inl create mode 100644 dep/acelite/ace/IO_Cntl_Msg.cpp create mode 100644 dep/acelite/ace/IO_Cntl_Msg.h create mode 100644 dep/acelite/ace/IO_Cntl_Msg.inl create mode 100644 dep/acelite/ace/IO_SAP.cpp create mode 100644 dep/acelite/ace/IO_SAP.h create mode 100644 dep/acelite/ace/IO_SAP.inl create mode 100644 dep/acelite/ace/IPC_SAP.cpp create mode 100644 dep/acelite/ace/IPC_SAP.h create mode 100644 dep/acelite/ace/IPC_SAP.inl create mode 100644 dep/acelite/ace/If_Then_Else.h create mode 100644 dep/acelite/ace/Init_ACE.cpp create mode 100644 dep/acelite/ace/Init_ACE.h create mode 100644 dep/acelite/ace/Intrusive_Auto_Ptr.cpp create mode 100644 dep/acelite/ace/Intrusive_Auto_Ptr.h create mode 100644 dep/acelite/ace/Intrusive_Auto_Ptr.inl create mode 100644 dep/acelite/ace/Intrusive_List.cpp create mode 100644 dep/acelite/ace/Intrusive_List.h create mode 100644 dep/acelite/ace/Intrusive_List.inl create mode 100644 dep/acelite/ace/Intrusive_List_Node.cpp create mode 100644 dep/acelite/ace/Intrusive_List_Node.h create mode 100644 dep/acelite/ace/Intrusive_List_Node.inl create mode 100644 dep/acelite/ace/LOCK_SOCK_Acceptor.cpp create mode 100644 dep/acelite/ace/LOCK_SOCK_Acceptor.h create mode 100644 dep/acelite/ace/LSOCK.cpp create mode 100644 dep/acelite/ace/LSOCK.h create mode 100644 dep/acelite/ace/LSOCK.inl create mode 100644 dep/acelite/ace/LSOCK_Acceptor.cpp create mode 100644 dep/acelite/ace/LSOCK_Acceptor.h create mode 100644 dep/acelite/ace/LSOCK_CODgram.cpp create mode 100644 dep/acelite/ace/LSOCK_CODgram.h create mode 100644 dep/acelite/ace/LSOCK_CODgram.inl create mode 100644 dep/acelite/ace/LSOCK_Connector.cpp create mode 100644 dep/acelite/ace/LSOCK_Connector.h create mode 100644 dep/acelite/ace/LSOCK_Connector.inl create mode 100644 dep/acelite/ace/LSOCK_Dgram.cpp create mode 100644 dep/acelite/ace/LSOCK_Dgram.h create mode 100644 dep/acelite/ace/LSOCK_Dgram.inl create mode 100644 dep/acelite/ace/LSOCK_Stream.cpp create mode 100644 dep/acelite/ace/LSOCK_Stream.h create mode 100644 dep/acelite/ace/LSOCK_Stream.inl create mode 100644 dep/acelite/ace/Lib_Find.cpp create mode 100644 dep/acelite/ace/Lib_Find.h create mode 100644 dep/acelite/ace/Local_Memory_Pool.cpp create mode 100644 dep/acelite/ace/Local_Memory_Pool.h create mode 100644 dep/acelite/ace/Local_Name_Space.cpp create mode 100644 dep/acelite/ace/Local_Name_Space.h create mode 100644 dep/acelite/ace/Local_Name_Space_T.cpp create mode 100644 dep/acelite/ace/Local_Name_Space_T.h create mode 100644 dep/acelite/ace/Local_Tokens.cpp create mode 100644 dep/acelite/ace/Local_Tokens.h create mode 100644 dep/acelite/ace/Local_Tokens.inl create mode 100644 dep/acelite/ace/Lock.cpp create mode 100644 dep/acelite/ace/Lock.h create mode 100644 dep/acelite/ace/Lock.inl create mode 100644 dep/acelite/ace/Lock_Adapter_T.cpp create mode 100644 dep/acelite/ace/Lock_Adapter_T.h create mode 100644 dep/acelite/ace/Lock_Adapter_T.inl create mode 100644 dep/acelite/ace/Log_Msg.cpp create mode 100644 dep/acelite/ace/Log_Msg.h create mode 100644 dep/acelite/ace/Log_Msg.inl create mode 100644 dep/acelite/ace/Log_Msg_Backend.cpp create mode 100644 dep/acelite/ace/Log_Msg_Backend.h create mode 100644 dep/acelite/ace/Log_Msg_Callback.cpp create mode 100644 dep/acelite/ace/Log_Msg_Callback.h create mode 100644 dep/acelite/ace/Log_Msg_IPC.cpp create mode 100644 dep/acelite/ace/Log_Msg_IPC.h create mode 100644 dep/acelite/ace/Log_Msg_NT_Event_Log.cpp create mode 100644 dep/acelite/ace/Log_Msg_NT_Event_Log.h create mode 100644 dep/acelite/ace/Log_Msg_UNIX_Syslog.cpp create mode 100644 dep/acelite/ace/Log_Msg_UNIX_Syslog.h create mode 100644 dep/acelite/ace/Log_Priority.h create mode 100644 dep/acelite/ace/Log_Record.cpp create mode 100644 dep/acelite/ace/Log_Record.h create mode 100644 dep/acelite/ace/Log_Record.inl create mode 100644 dep/acelite/ace/Logging_Strategy.cpp create mode 100644 dep/acelite/ace/Logging_Strategy.h create mode 100644 dep/acelite/ace/MEM_Acceptor.cpp create mode 100644 dep/acelite/ace/MEM_Acceptor.h create mode 100644 dep/acelite/ace/MEM_Acceptor.inl create mode 100644 dep/acelite/ace/MEM_Addr.cpp create mode 100644 dep/acelite/ace/MEM_Addr.h create mode 100644 dep/acelite/ace/MEM_Addr.inl create mode 100644 dep/acelite/ace/MEM_Connector.cpp create mode 100644 dep/acelite/ace/MEM_Connector.h create mode 100644 dep/acelite/ace/MEM_Connector.inl create mode 100644 dep/acelite/ace/MEM_IO.cpp create mode 100644 dep/acelite/ace/MEM_IO.h create mode 100644 dep/acelite/ace/MEM_IO.inl create mode 100644 dep/acelite/ace/MEM_SAP.cpp create mode 100644 dep/acelite/ace/MEM_SAP.h create mode 100644 dep/acelite/ace/MEM_SAP.inl create mode 100644 dep/acelite/ace/MEM_Stream.cpp create mode 100644 dep/acelite/ace/MEM_Stream.h create mode 100644 dep/acelite/ace/MEM_Stream.inl create mode 100644 dep/acelite/ace/MMAP_Memory_Pool.cpp create mode 100644 dep/acelite/ace/MMAP_Memory_Pool.h create mode 100644 dep/acelite/ace/MMAP_Memory_Pool.inl create mode 100644 dep/acelite/ace/Makefile.in create mode 100644 dep/acelite/ace/Malloc.cpp create mode 100644 dep/acelite/ace/Malloc.h create mode 100644 dep/acelite/ace/Malloc.inl create mode 100644 dep/acelite/ace/Malloc_Allocator.cpp create mode 100644 dep/acelite/ace/Malloc_Allocator.h create mode 100644 dep/acelite/ace/Malloc_Allocator.inl create mode 100644 dep/acelite/ace/Malloc_Base.h create mode 100644 dep/acelite/ace/Malloc_T.cpp create mode 100644 dep/acelite/ace/Malloc_T.h create mode 100644 dep/acelite/ace/Malloc_T.inl create mode 100644 dep/acelite/ace/Managed_Object.cpp create mode 100644 dep/acelite/ace/Managed_Object.h create mode 100644 dep/acelite/ace/Managed_Object.inl create mode 100644 dep/acelite/ace/Manual_Event.cpp create mode 100644 dep/acelite/ace/Manual_Event.h create mode 100644 dep/acelite/ace/Manual_Event.inl create mode 100644 dep/acelite/ace/Map.h create mode 100644 dep/acelite/ace/Map_Manager.cpp create mode 100644 dep/acelite/ace/Map_Manager.h create mode 100644 dep/acelite/ace/Map_Manager.inl create mode 100644 dep/acelite/ace/Map_T.cpp create mode 100644 dep/acelite/ace/Map_T.h create mode 100644 dep/acelite/ace/Map_T.inl create mode 100644 dep/acelite/ace/Mem_Map.cpp create mode 100644 dep/acelite/ace/Mem_Map.h create mode 100644 dep/acelite/ace/Mem_Map.inl create mode 100644 dep/acelite/ace/Memory_Pool.h create mode 100644 dep/acelite/ace/Message_Block.cpp create mode 100644 dep/acelite/ace/Message_Block.h create mode 100644 dep/acelite/ace/Message_Block.inl create mode 100644 dep/acelite/ace/Message_Block_T.cpp create mode 100644 dep/acelite/ace/Message_Block_T.h create mode 100644 dep/acelite/ace/Message_Block_T.inl create mode 100644 dep/acelite/ace/Message_Queue.cpp create mode 100644 dep/acelite/ace/Message_Queue.h create mode 100644 dep/acelite/ace/Message_Queue.inl create mode 100644 dep/acelite/ace/Message_Queue_NT.cpp create mode 100644 dep/acelite/ace/Message_Queue_NT.h create mode 100644 dep/acelite/ace/Message_Queue_NT.inl create mode 100644 dep/acelite/ace/Message_Queue_T.cpp create mode 100644 dep/acelite/ace/Message_Queue_T.h create mode 100644 dep/acelite/ace/Message_Queue_Vx.cpp create mode 100644 dep/acelite/ace/Message_Queue_Vx.h create mode 100644 dep/acelite/ace/Message_Queue_Vx.inl create mode 100644 dep/acelite/ace/Method_Object.h create mode 100644 dep/acelite/ace/Method_Request.cpp create mode 100644 dep/acelite/ace/Method_Request.h create mode 100644 dep/acelite/ace/Metrics_Cache.h create mode 100644 dep/acelite/ace/Metrics_Cache_T.cpp create mode 100644 dep/acelite/ace/Metrics_Cache_T.h create mode 100644 dep/acelite/ace/Metrics_Cache_T.inl create mode 100644 dep/acelite/ace/Min_Max.h create mode 100644 dep/acelite/ace/Module.cpp create mode 100644 dep/acelite/ace/Module.h create mode 100644 dep/acelite/ace/Module.inl create mode 100644 dep/acelite/ace/Monitor_Admin.cpp create mode 100644 dep/acelite/ace/Monitor_Admin.h create mode 100644 dep/acelite/ace/Monitor_Admin_Manager.cpp create mode 100644 dep/acelite/ace/Monitor_Admin_Manager.h create mode 100644 dep/acelite/ace/Monitor_Base.cpp create mode 100644 dep/acelite/ace/Monitor_Base.h create mode 100644 dep/acelite/ace/Monitor_Base.inl create mode 100644 dep/acelite/ace/Monitor_Control_Action.cpp create mode 100644 dep/acelite/ace/Monitor_Control_Action.h create mode 100644 dep/acelite/ace/Monitor_Control_Types.cpp create mode 100644 dep/acelite/ace/Monitor_Control_Types.h create mode 100644 dep/acelite/ace/Monitor_Point_Registry.cpp create mode 100644 dep/acelite/ace/Monitor_Point_Registry.h create mode 100644 dep/acelite/ace/Monitor_Size.cpp create mode 100644 dep/acelite/ace/Monitor_Size.h create mode 100644 dep/acelite/ace/Msg_WFMO_Reactor.cpp create mode 100644 dep/acelite/ace/Msg_WFMO_Reactor.h create mode 100644 dep/acelite/ace/Msg_WFMO_Reactor.inl create mode 100644 dep/acelite/ace/Multihomed_INET_Addr.cpp create mode 100644 dep/acelite/ace/Multihomed_INET_Addr.h create mode 100644 dep/acelite/ace/Multihomed_INET_Addr.inl create mode 100644 dep/acelite/ace/Mutex.cpp create mode 100644 dep/acelite/ace/Mutex.h create mode 100644 dep/acelite/ace/Mutex.inl create mode 100644 dep/acelite/ace/NT_Service.cpp create mode 100644 dep/acelite/ace/NT_Service.h create mode 100644 dep/acelite/ace/NT_Service.inl create mode 100644 dep/acelite/ace/Name_Proxy.cpp create mode 100644 dep/acelite/ace/Name_Proxy.h create mode 100644 dep/acelite/ace/Name_Request_Reply.cpp create mode 100644 dep/acelite/ace/Name_Request_Reply.h create mode 100644 dep/acelite/ace/Name_Space.cpp create mode 100644 dep/acelite/ace/Name_Space.h create mode 100644 dep/acelite/ace/Naming_Context.cpp create mode 100644 dep/acelite/ace/Naming_Context.h create mode 100644 dep/acelite/ace/Naming_Context.inl create mode 100644 dep/acelite/ace/Netlink_Addr.cpp create mode 100644 dep/acelite/ace/Netlink_Addr.h create mode 100644 dep/acelite/ace/Netlink_Addr.inl create mode 100644 dep/acelite/ace/Node.cpp create mode 100644 dep/acelite/ace/Node.h create mode 100644 dep/acelite/ace/Notification_Queue.cpp create mode 100644 dep/acelite/ace/Notification_Queue.h create mode 100644 dep/acelite/ace/Notification_Queue.inl create mode 100644 dep/acelite/ace/Notification_Strategy.cpp create mode 100644 dep/acelite/ace/Notification_Strategy.h create mode 100644 dep/acelite/ace/Notification_Strategy.inl create mode 100644 dep/acelite/ace/Null_Barrier.h create mode 100644 dep/acelite/ace/Null_Condition.h create mode 100644 dep/acelite/ace/Null_Mutex.h create mode 100644 dep/acelite/ace/Null_Semaphore.h create mode 100644 dep/acelite/ace/Numeric_Limits.h create mode 100644 dep/acelite/ace/OS.cpp create mode 100644 dep/acelite/ace/OS.h create mode 100644 dep/acelite/ace/OS.inl create mode 100644 dep/acelite/ace/OS_Dirent.h create mode 100644 dep/acelite/ace/OS_Errno.cpp create mode 100644 dep/acelite/ace/OS_Errno.h create mode 100644 dep/acelite/ace/OS_Errno.inl create mode 100644 dep/acelite/ace/OS_Log_Msg_Attributes.cpp create mode 100644 dep/acelite/ace/OS_Log_Msg_Attributes.h create mode 100644 dep/acelite/ace/OS_Log_Msg_Attributes.inl create mode 100644 dep/acelite/ace/OS_Memory.h create mode 100644 dep/acelite/ace/OS_NS_Thread.cpp create mode 100644 dep/acelite/ace/OS_NS_Thread.h create mode 100644 dep/acelite/ace/OS_NS_Thread.inl create mode 100644 dep/acelite/ace/OS_NS_arpa_inet.cpp create mode 100644 dep/acelite/ace/OS_NS_arpa_inet.h create mode 100644 dep/acelite/ace/OS_NS_arpa_inet.inl create mode 100644 dep/acelite/ace/OS_NS_ctype.cpp create mode 100644 dep/acelite/ace/OS_NS_ctype.h create mode 100644 dep/acelite/ace/OS_NS_ctype.inl create mode 100644 dep/acelite/ace/OS_NS_dirent.cpp create mode 100644 dep/acelite/ace/OS_NS_dirent.h create mode 100644 dep/acelite/ace/OS_NS_dirent.inl create mode 100644 dep/acelite/ace/OS_NS_dlfcn.cpp create mode 100644 dep/acelite/ace/OS_NS_dlfcn.h create mode 100644 dep/acelite/ace/OS_NS_dlfcn.inl create mode 100644 dep/acelite/ace/OS_NS_errno.cpp create mode 100644 dep/acelite/ace/OS_NS_errno.h create mode 100644 dep/acelite/ace/OS_NS_errno.inl create mode 100644 dep/acelite/ace/OS_NS_fcntl.cpp create mode 100644 dep/acelite/ace/OS_NS_fcntl.h create mode 100644 dep/acelite/ace/OS_NS_fcntl.inl create mode 100644 dep/acelite/ace/OS_NS_macros.h create mode 100644 dep/acelite/ace/OS_NS_math.cpp create mode 100644 dep/acelite/ace/OS_NS_math.h create mode 100644 dep/acelite/ace/OS_NS_math.inl create mode 100644 dep/acelite/ace/OS_NS_netdb.cpp create mode 100644 dep/acelite/ace/OS_NS_netdb.h create mode 100644 dep/acelite/ace/OS_NS_netdb.inl create mode 100644 dep/acelite/ace/OS_NS_poll.cpp create mode 100644 dep/acelite/ace/OS_NS_poll.h create mode 100644 dep/acelite/ace/OS_NS_poll.inl create mode 100644 dep/acelite/ace/OS_NS_pwd.cpp create mode 100644 dep/acelite/ace/OS_NS_pwd.h create mode 100644 dep/acelite/ace/OS_NS_pwd.inl create mode 100644 dep/acelite/ace/OS_NS_regex.cpp create mode 100644 dep/acelite/ace/OS_NS_regex.h create mode 100644 dep/acelite/ace/OS_NS_regex.inl create mode 100644 dep/acelite/ace/OS_NS_signal.cpp create mode 100644 dep/acelite/ace/OS_NS_signal.h create mode 100644 dep/acelite/ace/OS_NS_signal.inl create mode 100644 dep/acelite/ace/OS_NS_stdio.cpp create mode 100644 dep/acelite/ace/OS_NS_stdio.h create mode 100644 dep/acelite/ace/OS_NS_stdio.inl create mode 100644 dep/acelite/ace/OS_NS_stdlib.cpp create mode 100644 dep/acelite/ace/OS_NS_stdlib.h create mode 100644 dep/acelite/ace/OS_NS_stdlib.inl create mode 100644 dep/acelite/ace/OS_NS_string.cpp create mode 100644 dep/acelite/ace/OS_NS_string.h create mode 100644 dep/acelite/ace/OS_NS_string.inl create mode 100644 dep/acelite/ace/OS_NS_strings.cpp create mode 100644 dep/acelite/ace/OS_NS_strings.h create mode 100644 dep/acelite/ace/OS_NS_strings.inl create mode 100644 dep/acelite/ace/OS_NS_stropts.cpp create mode 100644 dep/acelite/ace/OS_NS_stropts.h create mode 100644 dep/acelite/ace/OS_NS_stropts.inl create mode 100644 dep/acelite/ace/OS_NS_sys_mman.cpp create mode 100644 dep/acelite/ace/OS_NS_sys_mman.h create mode 100644 dep/acelite/ace/OS_NS_sys_mman.inl create mode 100644 dep/acelite/ace/OS_NS_sys_msg.cpp create mode 100644 dep/acelite/ace/OS_NS_sys_msg.h create mode 100644 dep/acelite/ace/OS_NS_sys_msg.inl create mode 100644 dep/acelite/ace/OS_NS_sys_resource.cpp create mode 100644 dep/acelite/ace/OS_NS_sys_resource.h create mode 100644 dep/acelite/ace/OS_NS_sys_resource.inl create mode 100644 dep/acelite/ace/OS_NS_sys_select.cpp create mode 100644 dep/acelite/ace/OS_NS_sys_select.h create mode 100644 dep/acelite/ace/OS_NS_sys_select.inl create mode 100644 dep/acelite/ace/OS_NS_sys_sendfile.cpp create mode 100644 dep/acelite/ace/OS_NS_sys_sendfile.h create mode 100644 dep/acelite/ace/OS_NS_sys_sendfile.inl create mode 100644 dep/acelite/ace/OS_NS_sys_shm.cpp create mode 100644 dep/acelite/ace/OS_NS_sys_shm.h create mode 100644 dep/acelite/ace/OS_NS_sys_shm.inl create mode 100644 dep/acelite/ace/OS_NS_sys_socket.cpp create mode 100644 dep/acelite/ace/OS_NS_sys_socket.h create mode 100644 dep/acelite/ace/OS_NS_sys_socket.inl create mode 100644 dep/acelite/ace/OS_NS_sys_stat.cpp create mode 100644 dep/acelite/ace/OS_NS_sys_stat.h create mode 100644 dep/acelite/ace/OS_NS_sys_stat.inl create mode 100644 dep/acelite/ace/OS_NS_sys_time.cpp create mode 100644 dep/acelite/ace/OS_NS_sys_time.h create mode 100644 dep/acelite/ace/OS_NS_sys_time.inl create mode 100644 dep/acelite/ace/OS_NS_sys_uio.cpp create mode 100644 dep/acelite/ace/OS_NS_sys_uio.h create mode 100644 dep/acelite/ace/OS_NS_sys_uio.inl create mode 100644 dep/acelite/ace/OS_NS_sys_utsname.cpp create mode 100644 dep/acelite/ace/OS_NS_sys_utsname.h create mode 100644 dep/acelite/ace/OS_NS_sys_wait.cpp create mode 100644 dep/acelite/ace/OS_NS_sys_wait.h create mode 100644 dep/acelite/ace/OS_NS_sys_wait.inl create mode 100644 dep/acelite/ace/OS_NS_time.cpp create mode 100644 dep/acelite/ace/OS_NS_time.h create mode 100644 dep/acelite/ace/OS_NS_time.inl create mode 100644 dep/acelite/ace/OS_NS_unistd.cpp create mode 100644 dep/acelite/ace/OS_NS_unistd.h create mode 100644 dep/acelite/ace/OS_NS_unistd.inl create mode 100644 dep/acelite/ace/OS_NS_wchar.cpp create mode 100644 dep/acelite/ace/OS_NS_wchar.h create mode 100644 dep/acelite/ace/OS_NS_wchar.inl create mode 100644 dep/acelite/ace/OS_NS_wctype.cpp create mode 100644 dep/acelite/ace/OS_NS_wctype.h create mode 100644 dep/acelite/ace/OS_NS_wctype.inl create mode 100644 dep/acelite/ace/OS_QoS.cpp create mode 100644 dep/acelite/ace/OS_QoS.h create mode 100644 dep/acelite/ace/OS_String.h create mode 100644 dep/acelite/ace/OS_TLI.cpp create mode 100644 dep/acelite/ace/OS_TLI.h create mode 100644 dep/acelite/ace/OS_TLI.inl create mode 100644 dep/acelite/ace/OS_Thread_Adapter.cpp create mode 100644 dep/acelite/ace/OS_Thread_Adapter.h create mode 100644 dep/acelite/ace/OS_main.cpp create mode 100644 dep/acelite/ace/OS_main.h create mode 100644 dep/acelite/ace/Obchunk.cpp create mode 100644 dep/acelite/ace/Obchunk.h create mode 100644 dep/acelite/ace/Obchunk.inl create mode 100644 dep/acelite/ace/Object_Manager.cpp create mode 100644 dep/acelite/ace/Object_Manager.h create mode 100644 dep/acelite/ace/Object_Manager.inl create mode 100644 dep/acelite/ace/Object_Manager_Base.cpp create mode 100644 dep/acelite/ace/Object_Manager_Base.h create mode 100644 dep/acelite/ace/Obstack.h create mode 100644 dep/acelite/ace/Obstack_T.cpp create mode 100644 dep/acelite/ace/Obstack_T.h create mode 100644 dep/acelite/ace/Obstack_T.inl create mode 100644 dep/acelite/ace/PI_Malloc.cpp create mode 100644 dep/acelite/ace/PI_Malloc.h create mode 100644 dep/acelite/ace/PI_Malloc.inl create mode 100644 dep/acelite/ace/POSIX_Asynch_IO.cpp create mode 100644 dep/acelite/ace/POSIX_Asynch_IO.h create mode 100644 dep/acelite/ace/POSIX_CB_Proactor.cpp create mode 100644 dep/acelite/ace/POSIX_CB_Proactor.h create mode 100644 dep/acelite/ace/POSIX_Proactor.cpp create mode 100644 dep/acelite/ace/POSIX_Proactor.h create mode 100644 dep/acelite/ace/POSIX_Proactor.inl create mode 100644 dep/acelite/ace/Pagefile_Memory_Pool.cpp create mode 100644 dep/acelite/ace/Pagefile_Memory_Pool.h create mode 100644 dep/acelite/ace/Pagefile_Memory_Pool.inl create mode 100644 dep/acelite/ace/Pair.h create mode 100644 dep/acelite/ace/Pair_T.cpp create mode 100644 dep/acelite/ace/Pair_T.h create mode 100644 dep/acelite/ace/Pair_T.inl create mode 100644 dep/acelite/ace/Parse_Node.cpp create mode 100644 dep/acelite/ace/Parse_Node.h create mode 100644 dep/acelite/ace/Ping_Socket.cpp create mode 100644 dep/acelite/ace/Ping_Socket.h create mode 100644 dep/acelite/ace/Ping_Socket.inl create mode 100644 dep/acelite/ace/Pipe.cpp create mode 100644 dep/acelite/ace/Pipe.h create mode 100644 dep/acelite/ace/Pipe.inl create mode 100644 dep/acelite/ace/PrecompiledHeaders/WinAcePCH.cpp create mode 100644 dep/acelite/ace/PrecompiledHeaders/WinAcePCH.h create mode 100644 dep/acelite/ace/Priority_Reactor.cpp create mode 100644 dep/acelite/ace/Priority_Reactor.h create mode 100644 dep/acelite/ace/Proactor.cpp create mode 100644 dep/acelite/ace/Proactor.h create mode 100644 dep/acelite/ace/Proactor.inl create mode 100644 dep/acelite/ace/Proactor_Impl.cpp create mode 100644 dep/acelite/ace/Proactor_Impl.h create mode 100644 dep/acelite/ace/Process.cpp create mode 100644 dep/acelite/ace/Process.h create mode 100644 dep/acelite/ace/Process.inl create mode 100644 dep/acelite/ace/Process_Manager.cpp create mode 100644 dep/acelite/ace/Process_Manager.h create mode 100644 dep/acelite/ace/Process_Manager.inl create mode 100644 dep/acelite/ace/Process_Mutex.cpp create mode 100644 dep/acelite/ace/Process_Mutex.h create mode 100644 dep/acelite/ace/Process_Mutex.inl create mode 100644 dep/acelite/ace/Process_Semaphore.cpp create mode 100644 dep/acelite/ace/Process_Semaphore.h create mode 100644 dep/acelite/ace/Process_Semaphore.inl create mode 100644 dep/acelite/ace/Profile_Timer.cpp create mode 100644 dep/acelite/ace/Profile_Timer.h create mode 100644 dep/acelite/ace/Profile_Timer.inl create mode 100644 dep/acelite/ace/QoS/ACE_QoS_Export.h create mode 100644 dep/acelite/ace/QoS/QoS_Decorator.cpp create mode 100644 dep/acelite/ace/QoS/QoS_Decorator.h create mode 100644 dep/acelite/ace/QoS/QoS_Manager.cpp create mode 100644 dep/acelite/ace/QoS/QoS_Manager.h create mode 100644 dep/acelite/ace/QoS/QoS_Session.h create mode 100644 dep/acelite/ace/QoS/QoS_Session_Factory.cpp create mode 100644 dep/acelite/ace/QoS/QoS_Session_Factory.h create mode 100644 dep/acelite/ace/QoS/QoS_Session_Impl.cpp create mode 100644 dep/acelite/ace/QoS/QoS_Session_Impl.h create mode 100644 dep/acelite/ace/QoS/QoS_Session_Impl.inl create mode 100644 dep/acelite/ace/QoS/README create mode 100644 dep/acelite/ace/QoS/SOCK_Dgram_Mcast_QoS.cpp create mode 100644 dep/acelite/ace/QoS/SOCK_Dgram_Mcast_QoS.h create mode 100644 dep/acelite/ace/QoS/SOCK_Dgram_Mcast_QoS.inl create mode 100644 dep/acelite/ace/RB_Tree.cpp create mode 100644 dep/acelite/ace/RB_Tree.h create mode 100644 dep/acelite/ace/RB_Tree.inl create mode 100644 dep/acelite/ace/README create mode 100644 dep/acelite/ace/RW_Mutex.cpp create mode 100644 dep/acelite/ace/RW_Mutex.h create mode 100644 dep/acelite/ace/RW_Mutex.inl create mode 100644 dep/acelite/ace/RW_Process_Mutex.cpp create mode 100644 dep/acelite/ace/RW_Process_Mutex.h create mode 100644 dep/acelite/ace/RW_Process_Mutex.inl create mode 100644 dep/acelite/ace/RW_Thread_Mutex.cpp create mode 100644 dep/acelite/ace/RW_Thread_Mutex.h create mode 100644 dep/acelite/ace/RW_Thread_Mutex.inl create mode 100644 dep/acelite/ace/Reactor.cpp create mode 100644 dep/acelite/ace/Reactor.h create mode 100644 dep/acelite/ace/Reactor.inl create mode 100644 dep/acelite/ace/Reactor_Impl.cpp create mode 100644 dep/acelite/ace/Reactor_Impl.h create mode 100644 dep/acelite/ace/Reactor_Notification_Strategy.cpp create mode 100644 dep/acelite/ace/Reactor_Notification_Strategy.h create mode 100644 dep/acelite/ace/Reactor_Notification_Strategy.inl create mode 100644 dep/acelite/ace/Reactor_Timer_Interface.cpp create mode 100644 dep/acelite/ace/Reactor_Timer_Interface.h create mode 100644 dep/acelite/ace/Reactor_Token_T.cpp create mode 100644 dep/acelite/ace/Reactor_Token_T.h create mode 100644 dep/acelite/ace/Read_Buffer.cpp create mode 100644 dep/acelite/ace/Read_Buffer.h create mode 100644 dep/acelite/ace/Read_Buffer.inl create mode 100644 dep/acelite/ace/Recursive_Thread_Mutex.cpp create mode 100644 dep/acelite/ace/Recursive_Thread_Mutex.h create mode 100644 dep/acelite/ace/Recursive_Thread_Mutex.inl create mode 100644 dep/acelite/ace/Recyclable.cpp create mode 100644 dep/acelite/ace/Recyclable.h create mode 100644 dep/acelite/ace/Recyclable.inl create mode 100644 dep/acelite/ace/Refcountable.h create mode 100644 dep/acelite/ace/Refcountable_T.cpp create mode 100644 dep/acelite/ace/Refcountable_T.h create mode 100644 dep/acelite/ace/Refcountable_T.inl create mode 100644 dep/acelite/ace/Refcounted_Auto_Ptr.cpp create mode 100644 dep/acelite/ace/Refcounted_Auto_Ptr.h create mode 100644 dep/acelite/ace/Refcounted_Auto_Ptr.inl create mode 100644 dep/acelite/ace/Registry.cpp create mode 100644 dep/acelite/ace/Registry.h create mode 100644 dep/acelite/ace/Registry_Name_Space.cpp create mode 100644 dep/acelite/ace/Registry_Name_Space.h create mode 100644 dep/acelite/ace/Remote_Name_Space.cpp create mode 100644 dep/acelite/ace/Remote_Name_Space.h create mode 100644 dep/acelite/ace/Remote_Tokens.cpp create mode 100644 dep/acelite/ace/Remote_Tokens.h create mode 100644 dep/acelite/ace/Remote_Tokens.inl create mode 100644 dep/acelite/ace/Reverse_Lock_T.cpp create mode 100644 dep/acelite/ace/Reverse_Lock_T.h create mode 100644 dep/acelite/ace/Reverse_Lock_T.inl create mode 100644 dep/acelite/ace/Rtems_init.c create mode 100644 dep/acelite/ace/SOCK.cpp create mode 100644 dep/acelite/ace/SOCK.h create mode 100644 dep/acelite/ace/SOCK.inl create mode 100644 dep/acelite/ace/SOCK_Acceptor.cpp create mode 100644 dep/acelite/ace/SOCK_Acceptor.h create mode 100644 dep/acelite/ace/SOCK_Acceptor.inl create mode 100644 dep/acelite/ace/SOCK_CODgram.cpp create mode 100644 dep/acelite/ace/SOCK_CODgram.h create mode 100644 dep/acelite/ace/SOCK_CODgram.inl create mode 100644 dep/acelite/ace/SOCK_Connector.cpp create mode 100644 dep/acelite/ace/SOCK_Connector.h create mode 100644 dep/acelite/ace/SOCK_Connector.inl create mode 100644 dep/acelite/ace/SOCK_Dgram.cpp create mode 100644 dep/acelite/ace/SOCK_Dgram.h create mode 100644 dep/acelite/ace/SOCK_Dgram.inl create mode 100644 dep/acelite/ace/SOCK_Dgram_Bcast.cpp create mode 100644 dep/acelite/ace/SOCK_Dgram_Bcast.h create mode 100644 dep/acelite/ace/SOCK_Dgram_Bcast.inl create mode 100644 dep/acelite/ace/SOCK_Dgram_Mcast.cpp create mode 100644 dep/acelite/ace/SOCK_Dgram_Mcast.h create mode 100644 dep/acelite/ace/SOCK_Dgram_Mcast.inl create mode 100644 dep/acelite/ace/SOCK_IO.cpp create mode 100644 dep/acelite/ace/SOCK_IO.h create mode 100644 dep/acelite/ace/SOCK_IO.inl create mode 100644 dep/acelite/ace/SOCK_Netlink.cpp create mode 100644 dep/acelite/ace/SOCK_Netlink.h create mode 100644 dep/acelite/ace/SOCK_Netlink.inl create mode 100644 dep/acelite/ace/SOCK_SEQPACK_Acceptor.cpp create mode 100644 dep/acelite/ace/SOCK_SEQPACK_Acceptor.h create mode 100644 dep/acelite/ace/SOCK_SEQPACK_Acceptor.inl create mode 100644 dep/acelite/ace/SOCK_SEQPACK_Association.cpp create mode 100644 dep/acelite/ace/SOCK_SEQPACK_Association.h create mode 100644 dep/acelite/ace/SOCK_SEQPACK_Association.inl create mode 100644 dep/acelite/ace/SOCK_SEQPACK_Connector.cpp create mode 100644 dep/acelite/ace/SOCK_SEQPACK_Connector.h create mode 100644 dep/acelite/ace/SOCK_SEQPACK_Connector.inl create mode 100644 dep/acelite/ace/SOCK_Stream.cpp create mode 100644 dep/acelite/ace/SOCK_Stream.h create mode 100644 dep/acelite/ace/SOCK_Stream.inl create mode 100644 dep/acelite/ace/SPIPE.cpp create mode 100644 dep/acelite/ace/SPIPE.h create mode 100644 dep/acelite/ace/SPIPE.inl create mode 100644 dep/acelite/ace/SPIPE_Acceptor.cpp create mode 100644 dep/acelite/ace/SPIPE_Acceptor.h create mode 100644 dep/acelite/ace/SPIPE_Addr.cpp create mode 100644 dep/acelite/ace/SPIPE_Addr.h create mode 100644 dep/acelite/ace/SPIPE_Addr.inl create mode 100644 dep/acelite/ace/SPIPE_Connector.cpp create mode 100644 dep/acelite/ace/SPIPE_Connector.h create mode 100644 dep/acelite/ace/SPIPE_Connector.inl create mode 100644 dep/acelite/ace/SPIPE_Stream.cpp create mode 100644 dep/acelite/ace/SPIPE_Stream.h create mode 100644 dep/acelite/ace/SPIPE_Stream.inl create mode 100644 dep/acelite/ace/SSL/SSL_Asynch_BIO.cpp create mode 100644 dep/acelite/ace/SSL/SSL_Asynch_BIO.h create mode 100644 dep/acelite/ace/SSL/SSL_Asynch_Stream.cpp create mode 100644 dep/acelite/ace/SSL/SSL_Asynch_Stream.h create mode 100644 dep/acelite/ace/SSL/SSL_Asynch_Stream.inl create mode 100644 dep/acelite/ace/SSL/SSL_Context.cpp create mode 100644 dep/acelite/ace/SSL/SSL_Context.h create mode 100644 dep/acelite/ace/SSL/SSL_Context.inl create mode 100644 dep/acelite/ace/SSL/SSL_Export.h create mode 100644 dep/acelite/ace/SSL/SSL_SOCK.cpp create mode 100644 dep/acelite/ace/SSL/SSL_SOCK.h create mode 100644 dep/acelite/ace/SSL/SSL_SOCK.inl create mode 100644 dep/acelite/ace/SSL/SSL_SOCK_Acceptor.cpp create mode 100644 dep/acelite/ace/SSL/SSL_SOCK_Acceptor.h create mode 100644 dep/acelite/ace/SSL/SSL_SOCK_Acceptor.inl create mode 100644 dep/acelite/ace/SSL/SSL_SOCK_Connector.cpp create mode 100644 dep/acelite/ace/SSL/SSL_SOCK_Connector.h create mode 100644 dep/acelite/ace/SSL/SSL_SOCK_Connector.inl create mode 100644 dep/acelite/ace/SSL/SSL_SOCK_Stream.cpp create mode 100644 dep/acelite/ace/SSL/SSL_SOCK_Stream.h create mode 100644 dep/acelite/ace/SSL/SSL_SOCK_Stream.inl create mode 100644 dep/acelite/ace/SSL/sslconf.h create mode 100644 dep/acelite/ace/SString.cpp create mode 100644 dep/acelite/ace/SString.h create mode 100644 dep/acelite/ace/SString.inl create mode 100644 dep/acelite/ace/SStringfwd.h create mode 100644 dep/acelite/ace/SUN_Proactor.cpp create mode 100644 dep/acelite/ace/SUN_Proactor.h create mode 100644 dep/acelite/ace/SV_Message.cpp create mode 100644 dep/acelite/ace/SV_Message.h create mode 100644 dep/acelite/ace/SV_Message.inl create mode 100644 dep/acelite/ace/SV_Message_Queue.cpp create mode 100644 dep/acelite/ace/SV_Message_Queue.h create mode 100644 dep/acelite/ace/SV_Message_Queue.inl create mode 100644 dep/acelite/ace/SV_Semaphore_Complex.cpp create mode 100644 dep/acelite/ace/SV_Semaphore_Complex.h create mode 100644 dep/acelite/ace/SV_Semaphore_Complex.inl create mode 100644 dep/acelite/ace/SV_Semaphore_Simple.cpp create mode 100644 dep/acelite/ace/SV_Semaphore_Simple.h create mode 100644 dep/acelite/ace/SV_Semaphore_Simple.inl create mode 100644 dep/acelite/ace/SV_Shared_Memory.cpp create mode 100644 dep/acelite/ace/SV_Shared_Memory.h create mode 100644 dep/acelite/ace/SV_Shared_Memory.inl create mode 100644 dep/acelite/ace/Sample_History.cpp create mode 100644 dep/acelite/ace/Sample_History.h create mode 100644 dep/acelite/ace/Sample_History.inl create mode 100644 dep/acelite/ace/Sbrk_Memory_Pool.cpp create mode 100644 dep/acelite/ace/Sbrk_Memory_Pool.h create mode 100644 dep/acelite/ace/Sched_Params.cpp create mode 100644 dep/acelite/ace/Sched_Params.h create mode 100644 dep/acelite/ace/Sched_Params.inl create mode 100644 dep/acelite/ace/Select_Reactor.h create mode 100644 dep/acelite/ace/Select_Reactor_Base.cpp create mode 100644 dep/acelite/ace/Select_Reactor_Base.h create mode 100644 dep/acelite/ace/Select_Reactor_Base.inl create mode 100644 dep/acelite/ace/Select_Reactor_T.cpp create mode 100644 dep/acelite/ace/Select_Reactor_T.h create mode 100644 dep/acelite/ace/Select_Reactor_T.inl create mode 100644 dep/acelite/ace/Semaphore.cpp create mode 100644 dep/acelite/ace/Semaphore.h create mode 100644 dep/acelite/ace/Semaphore.inl create mode 100644 dep/acelite/ace/Service_Config.cpp create mode 100644 dep/acelite/ace/Service_Config.h create mode 100644 dep/acelite/ace/Service_Config.inl create mode 100644 dep/acelite/ace/Service_Gestalt.cpp create mode 100644 dep/acelite/ace/Service_Gestalt.h create mode 100644 dep/acelite/ace/Service_Gestalt.inl create mode 100644 dep/acelite/ace/Service_Manager.cpp create mode 100644 dep/acelite/ace/Service_Manager.h create mode 100644 dep/acelite/ace/Service_Object.cpp create mode 100644 dep/acelite/ace/Service_Object.h create mode 100644 dep/acelite/ace/Service_Object.inl create mode 100644 dep/acelite/ace/Service_Repository.cpp create mode 100644 dep/acelite/ace/Service_Repository.h create mode 100644 dep/acelite/ace/Service_Repository.inl create mode 100644 dep/acelite/ace/Service_Templates.h create mode 100644 dep/acelite/ace/Service_Types.cpp create mode 100644 dep/acelite/ace/Service_Types.h create mode 100644 dep/acelite/ace/Service_Types.inl create mode 100644 dep/acelite/ace/Shared_Memory.cpp create mode 100644 dep/acelite/ace/Shared_Memory.h create mode 100644 dep/acelite/ace/Shared_Memory_MM.cpp create mode 100644 dep/acelite/ace/Shared_Memory_MM.h create mode 100644 dep/acelite/ace/Shared_Memory_MM.inl create mode 100644 dep/acelite/ace/Shared_Memory_Pool.cpp create mode 100644 dep/acelite/ace/Shared_Memory_Pool.h create mode 100644 dep/acelite/ace/Shared_Memory_SV.cpp create mode 100644 dep/acelite/ace/Shared_Memory_SV.h create mode 100644 dep/acelite/ace/Shared_Memory_SV.inl create mode 100644 dep/acelite/ace/Shared_Object.cpp create mode 100644 dep/acelite/ace/Shared_Object.h create mode 100644 dep/acelite/ace/Shared_Object.inl create mode 100644 dep/acelite/ace/Sig_Adapter.cpp create mode 100644 dep/acelite/ace/Sig_Adapter.h create mode 100644 dep/acelite/ace/Sig_Handler.cpp create mode 100644 dep/acelite/ace/Sig_Handler.h create mode 100644 dep/acelite/ace/Sig_Handler.inl create mode 100644 dep/acelite/ace/Signal.cpp create mode 100644 dep/acelite/ace/Signal.h create mode 100644 dep/acelite/ace/Signal.inl create mode 100644 dep/acelite/ace/Singleton.cpp create mode 100644 dep/acelite/ace/Singleton.h create mode 100644 dep/acelite/ace/Singleton.inl create mode 100644 dep/acelite/ace/Sock_Connect.cpp create mode 100644 dep/acelite/ace/Sock_Connect.h create mode 100644 dep/acelite/ace/Stack_Trace.cpp create mode 100644 dep/acelite/ace/Stack_Trace.h create mode 100644 dep/acelite/ace/Static_Object_Lock.h create mode 100644 dep/acelite/ace/Stats.cpp create mode 100644 dep/acelite/ace/Stats.h create mode 100644 dep/acelite/ace/Stats.inl create mode 100644 dep/acelite/ace/Strategies.h create mode 100644 dep/acelite/ace/Strategies_T.cpp create mode 100644 dep/acelite/ace/Strategies_T.h create mode 100644 dep/acelite/ace/Strategies_T.inl create mode 100644 dep/acelite/ace/Stream.cpp create mode 100644 dep/acelite/ace/Stream.h create mode 100644 dep/acelite/ace/Stream.inl create mode 100644 dep/acelite/ace/Stream_Modules.cpp create mode 100644 dep/acelite/ace/Stream_Modules.h create mode 100644 dep/acelite/ace/String_Base.cpp create mode 100644 dep/acelite/ace/String_Base.h create mode 100644 dep/acelite/ace/String_Base.inl create mode 100644 dep/acelite/ace/String_Base_Const.cpp create mode 100644 dep/acelite/ace/String_Base_Const.h create mode 100644 dep/acelite/ace/Svc_Conf.h create mode 100644 dep/acelite/ace/Svc_Conf.y create mode 100644 dep/acelite/ace/Svc_Conf_Lexer.cpp create mode 100644 dep/acelite/ace/Svc_Conf_Lexer.h create mode 100644 dep/acelite/ace/Svc_Conf_Param.h create mode 100644 dep/acelite/ace/Svc_Conf_Token_Table.h create mode 100644 dep/acelite/ace/Svc_Conf_Tokens.h create mode 100644 dep/acelite/ace/Svc_Conf_y.cpp create mode 100644 dep/acelite/ace/Svc_Handler.cpp create mode 100644 dep/acelite/ace/Svc_Handler.h create mode 100644 dep/acelite/ace/Synch.h create mode 100644 dep/acelite/ace/Synch_Options.cpp create mode 100644 dep/acelite/ace/Synch_Options.h create mode 100644 dep/acelite/ace/Synch_T.cpp create mode 100644 dep/acelite/ace/Synch_T.h create mode 100644 dep/acelite/ace/Synch_Traits.h create mode 100644 dep/acelite/ace/System_Time.cpp create mode 100644 dep/acelite/ace/System_Time.h create mode 100644 dep/acelite/ace/TLI.cpp create mode 100644 dep/acelite/ace/TLI.h create mode 100644 dep/acelite/ace/TLI.inl create mode 100644 dep/acelite/ace/TLI_Acceptor.cpp create mode 100644 dep/acelite/ace/TLI_Acceptor.h create mode 100644 dep/acelite/ace/TLI_Connector.cpp create mode 100644 dep/acelite/ace/TLI_Connector.h create mode 100644 dep/acelite/ace/TLI_Connector.inl create mode 100644 dep/acelite/ace/TLI_Stream.cpp create mode 100644 dep/acelite/ace/TLI_Stream.h create mode 100644 dep/acelite/ace/TLI_Stream.inl create mode 100644 dep/acelite/ace/TP_Reactor.cpp create mode 100644 dep/acelite/ace/TP_Reactor.h create mode 100644 dep/acelite/ace/TP_Reactor.inl create mode 100644 dep/acelite/ace/TSS_Adapter.cpp create mode 100644 dep/acelite/ace/TSS_Adapter.h create mode 100644 dep/acelite/ace/TSS_T.cpp create mode 100644 dep/acelite/ace/TSS_T.h create mode 100644 dep/acelite/ace/TSS_T.inl create mode 100644 dep/acelite/ace/TTY_IO.cpp create mode 100644 dep/acelite/ace/TTY_IO.h create mode 100644 dep/acelite/ace/Task.cpp create mode 100644 dep/acelite/ace/Task.h create mode 100644 dep/acelite/ace/Task.inl create mode 100644 dep/acelite/ace/Task_Ex_T.cpp create mode 100644 dep/acelite/ace/Task_Ex_T.h create mode 100644 dep/acelite/ace/Task_Ex_T.inl create mode 100644 dep/acelite/ace/Task_T.cpp create mode 100644 dep/acelite/ace/Task_T.h create mode 100644 dep/acelite/ace/Task_T.inl create mode 100644 dep/acelite/ace/Test_and_Set.cpp create mode 100644 dep/acelite/ace/Test_and_Set.h create mode 100644 dep/acelite/ace/Thread.cpp create mode 100644 dep/acelite/ace/Thread.h create mode 100644 dep/acelite/ace/Thread.inl create mode 100644 dep/acelite/ace/Thread_Adapter.cpp create mode 100644 dep/acelite/ace/Thread_Adapter.h create mode 100644 dep/acelite/ace/Thread_Adapter.inl create mode 100644 dep/acelite/ace/Thread_Control.cpp create mode 100644 dep/acelite/ace/Thread_Control.h create mode 100644 dep/acelite/ace/Thread_Control.inl create mode 100644 dep/acelite/ace/Thread_Exit.cpp create mode 100644 dep/acelite/ace/Thread_Exit.h create mode 100644 dep/acelite/ace/Thread_Hook.cpp create mode 100644 dep/acelite/ace/Thread_Hook.h create mode 100644 dep/acelite/ace/Thread_Manager.cpp create mode 100644 dep/acelite/ace/Thread_Manager.h create mode 100644 dep/acelite/ace/Thread_Manager.inl create mode 100644 dep/acelite/ace/Thread_Mutex.cpp create mode 100644 dep/acelite/ace/Thread_Mutex.h create mode 100644 dep/acelite/ace/Thread_Mutex.inl create mode 100644 dep/acelite/ace/Thread_Semaphore.cpp create mode 100644 dep/acelite/ace/Thread_Semaphore.h create mode 100644 dep/acelite/ace/Thread_Semaphore.inl create mode 100644 dep/acelite/ace/Throughput_Stats.cpp create mode 100644 dep/acelite/ace/Throughput_Stats.h create mode 100644 dep/acelite/ace/Time_Value.cpp create mode 100644 dep/acelite/ace/Time_Value.h create mode 100644 dep/acelite/ace/Time_Value.inl create mode 100644 dep/acelite/ace/Timeprobe.cpp create mode 100644 dep/acelite/ace/Timeprobe.h create mode 100644 dep/acelite/ace/Timeprobe.inl create mode 100644 dep/acelite/ace/Timeprobe_T.cpp create mode 100644 dep/acelite/ace/Timeprobe_T.h create mode 100644 dep/acelite/ace/Timer_Hash.h create mode 100644 dep/acelite/ace/Timer_Hash_T.cpp create mode 100644 dep/acelite/ace/Timer_Hash_T.h create mode 100644 dep/acelite/ace/Timer_Heap.h create mode 100644 dep/acelite/ace/Timer_Heap_T.cpp create mode 100644 dep/acelite/ace/Timer_Heap_T.h create mode 100644 dep/acelite/ace/Timer_List.h create mode 100644 dep/acelite/ace/Timer_List_T.cpp create mode 100644 dep/acelite/ace/Timer_List_T.h create mode 100644 dep/acelite/ace/Timer_Queue.h create mode 100644 dep/acelite/ace/Timer_Queue_Adapters.cpp create mode 100644 dep/acelite/ace/Timer_Queue_Adapters.h create mode 100644 dep/acelite/ace/Timer_Queue_Adapters.inl create mode 100644 dep/acelite/ace/Timer_Queue_T.cpp create mode 100644 dep/acelite/ace/Timer_Queue_T.h create mode 100644 dep/acelite/ace/Timer_Queue_T.inl create mode 100644 dep/acelite/ace/Timer_Queuefwd.h create mode 100644 dep/acelite/ace/Timer_Wheel.h create mode 100644 dep/acelite/ace/Timer_Wheel_T.cpp create mode 100644 dep/acelite/ace/Timer_Wheel_T.h create mode 100644 dep/acelite/ace/Token.cpp create mode 100644 dep/acelite/ace/Token.h create mode 100644 dep/acelite/ace/Token.inl create mode 100644 dep/acelite/ace/Token_Collection.cpp create mode 100644 dep/acelite/ace/Token_Collection.h create mode 100644 dep/acelite/ace/Token_Collection.inl create mode 100644 dep/acelite/ace/Token_Invariants.cpp create mode 100644 dep/acelite/ace/Token_Invariants.h create mode 100644 dep/acelite/ace/Token_Manager.cpp create mode 100644 dep/acelite/ace/Token_Manager.h create mode 100644 dep/acelite/ace/Token_Manager.inl create mode 100644 dep/acelite/ace/Token_Request_Reply.cpp create mode 100644 dep/acelite/ace/Token_Request_Reply.h create mode 100644 dep/acelite/ace/Token_Request_Reply.inl create mode 100644 dep/acelite/ace/Tokenizer_T.cpp create mode 100644 dep/acelite/ace/Tokenizer_T.h create mode 100644 dep/acelite/ace/Trace.cpp create mode 100644 dep/acelite/ace/Trace.h create mode 100644 dep/acelite/ace/Truncate.h create mode 100644 dep/acelite/ace/Typed_SV_Message.cpp create mode 100644 dep/acelite/ace/Typed_SV_Message.h create mode 100644 dep/acelite/ace/Typed_SV_Message.inl create mode 100644 dep/acelite/ace/Typed_SV_Message_Queue.cpp create mode 100644 dep/acelite/ace/Typed_SV_Message_Queue.h create mode 100644 dep/acelite/ace/Typed_SV_Message_Queue.inl create mode 100644 dep/acelite/ace/UNIX_Addr.cpp create mode 100644 dep/acelite/ace/UNIX_Addr.h create mode 100644 dep/acelite/ace/UNIX_Addr.inl create mode 100644 dep/acelite/ace/UPIPE_Acceptor.cpp create mode 100644 dep/acelite/ace/UPIPE_Acceptor.h create mode 100644 dep/acelite/ace/UPIPE_Acceptor.inl create mode 100644 dep/acelite/ace/UPIPE_Addr.h create mode 100644 dep/acelite/ace/UPIPE_Connector.cpp create mode 100644 dep/acelite/ace/UPIPE_Connector.h create mode 100644 dep/acelite/ace/UPIPE_Connector.inl create mode 100644 dep/acelite/ace/UPIPE_Stream.cpp create mode 100644 dep/acelite/ace/UPIPE_Stream.h create mode 100644 dep/acelite/ace/UPIPE_Stream.inl create mode 100644 dep/acelite/ace/UTF16_Encoding_Converter.cpp create mode 100644 dep/acelite/ace/UTF16_Encoding_Converter.h create mode 100644 dep/acelite/ace/UTF16_Encoding_Converter.inl create mode 100644 dep/acelite/ace/UTF32_Encoding_Converter.cpp create mode 100644 dep/acelite/ace/UTF32_Encoding_Converter.h create mode 100644 dep/acelite/ace/UTF8_Encoding_Converter.cpp create mode 100644 dep/acelite/ace/UTF8_Encoding_Converter.h create mode 100644 dep/acelite/ace/UUID.cpp create mode 100644 dep/acelite/ace/UUID.h create mode 100644 dep/acelite/ace/UUID.inl create mode 100644 dep/acelite/ace/Unbounded_Queue.cpp create mode 100644 dep/acelite/ace/Unbounded_Queue.h create mode 100644 dep/acelite/ace/Unbounded_Queue.inl create mode 100644 dep/acelite/ace/Unbounded_Set.cpp create mode 100644 dep/acelite/ace/Unbounded_Set.h create mode 100644 dep/acelite/ace/Unbounded_Set.inl create mode 100644 dep/acelite/ace/Unbounded_Set_Ex.cpp create mode 100644 dep/acelite/ace/Unbounded_Set_Ex.h create mode 100644 dep/acelite/ace/Unbounded_Set_Ex.inl create mode 100644 dep/acelite/ace/Value_Ptr.h create mode 100644 dep/acelite/ace/Vector_T.cpp create mode 100644 dep/acelite/ace/Vector_T.h create mode 100644 dep/acelite/ace/Vector_T.inl create mode 100644 dep/acelite/ace/Version.h create mode 100644 dep/acelite/ace/Versioned_Namespace.h create mode 100644 dep/acelite/ace/WFMO_Reactor.cpp create mode 100644 dep/acelite/ace/WFMO_Reactor.h create mode 100644 dep/acelite/ace/WFMO_Reactor.inl create mode 100644 dep/acelite/ace/WIN32_Asynch_IO.cpp create mode 100644 dep/acelite/ace/WIN32_Asynch_IO.h create mode 100644 dep/acelite/ace/WIN32_Proactor.cpp create mode 100644 dep/acelite/ace/WIN32_Proactor.h create mode 100644 dep/acelite/ace/XML_Svc_Conf.cpp create mode 100644 dep/acelite/ace/XML_Svc_Conf.h create mode 100644 dep/acelite/ace/XTI_ATM_Mcast.cpp create mode 100644 dep/acelite/ace/XTI_ATM_Mcast.h create mode 100644 dep/acelite/ace/XTI_ATM_Mcast.inl create mode 100644 dep/acelite/ace/ace.rc create mode 100644 dep/acelite/ace/ace_message_table.bin create mode 100644 dep/acelite/ace/ace_wchar.cpp create mode 100644 dep/acelite/ace/ace_wchar.h create mode 100644 dep/acelite/ace/ace_wchar.inl create mode 100644 dep/acelite/ace/checked_iterator.h create mode 100644 dep/acelite/ace/config-WinCE.h create mode 100644 dep/acelite/ace/config-aix-5.x.h create mode 100644 dep/acelite/ace/config-all.h create mode 100644 dep/acelite/ace/config-cray.h create mode 100644 dep/acelite/ace/config-cxx-common.h create mode 100644 dep/acelite/ace/config-cygwin32.h create mode 100644 dep/acelite/ace/config-doxygen.h create mode 100644 dep/acelite/ace/config-freebsd.h create mode 100644 dep/acelite/ace/config-g++-common.h create mode 100644 dep/acelite/ace/config-ghs-common.h create mode 100644 dep/acelite/ace/config-hpux-11.00.h create mode 100644 dep/acelite/ace/config-icc-common.h create mode 100644 dep/acelite/ace/config-integritySCA.h create mode 100644 dep/acelite/ace/config-irix6.5.x-sgic++.h create mode 100644 dep/acelite/ace/config-irix6.x-common.h create mode 100644 dep/acelite/ace/config-irix6.x-g++.h create mode 100644 dep/acelite/ace/config-irix6.x-sgic++.h create mode 100644 dep/acelite/ace/config-linux-common.h create mode 100644 dep/acelite/ace/config-linux.h create mode 100644 dep/acelite/ace/config-lite.h create mode 100644 dep/acelite/ace/config-lynxos.h create mode 100644 dep/acelite/ace/config-macosx-iphone-hardware.h create mode 100644 dep/acelite/ace/config-macosx-iphone-simulator.h create mode 100644 dep/acelite/ace/config-macosx-leopard.h create mode 100644 dep/acelite/ace/config-macosx-panther.h create mode 100644 dep/acelite/ace/config-macosx-snowleopard.h create mode 100644 dep/acelite/ace/config-macosx-tiger.h create mode 100644 dep/acelite/ace/config-macosx.h create mode 100644 dep/acelite/ace/config-macros.h create mode 100644 dep/acelite/ace/config-minimal.h create mode 100644 dep/acelite/ace/config-mvs.h create mode 100644 dep/acelite/ace/config-netbsd.h create mode 100644 dep/acelite/ace/config-openbsd.h create mode 100644 dep/acelite/ace/config-openvms.h create mode 100644 dep/acelite/ace/config-pharlap.h create mode 100644 dep/acelite/ace/config-posix-nonetworking.h create mode 100644 dep/acelite/ace/config-posix.h create mode 100644 dep/acelite/ace/config-qnx-neutrino.h create mode 100644 dep/acelite/ace/config-qnx-rtp-62x.h create mode 100644 dep/acelite/ace/config-qnx-rtp-common.h create mode 100644 dep/acelite/ace/config-qnx-rtp-pre62x.h create mode 100644 dep/acelite/ace/config-qnx-rtp.h create mode 100644 dep/acelite/ace/config-rtems.h create mode 100644 dep/acelite/ace/config-sco-5.0.0-nothread.h create mode 100644 dep/acelite/ace/config-sco-5.0.0.h create mode 100644 dep/acelite/ace/config-suncc-common.h create mode 100644 dep/acelite/ace/config-sunos5.10.h create mode 100644 dep/acelite/ace/config-sunos5.11.h create mode 100644 dep/acelite/ace/config-sunos5.4-g++.h create mode 100644 dep/acelite/ace/config-sunos5.4-sunc++-4.x.h create mode 100644 dep/acelite/ace/config-sunos5.5.h create mode 100644 dep/acelite/ace/config-sunos5.6.h create mode 100644 dep/acelite/ace/config-sunos5.7.h create mode 100644 dep/acelite/ace/config-sunos5.8.h create mode 100644 dep/acelite/ace/config-sunos5.9.h create mode 100644 dep/acelite/ace/config-tandem-nsk-mips-v2.h create mode 100644 dep/acelite/ace/config-tandem-nsk-mips-v3.h create mode 100644 dep/acelite/ace/config-tandem.h create mode 100644 dep/acelite/ace/config-tru64.h create mode 100644 dep/acelite/ace/config-unixware-7.1.0.h create mode 100644 dep/acelite/ace/config-unixware-7.1.0.udk.h create mode 100644 dep/acelite/ace/config-visualage.h create mode 100644 dep/acelite/ace/config-vxworks.h create mode 100644 dep/acelite/ace/config-vxworks6.4.h create mode 100644 dep/acelite/ace/config-vxworks6.5.h create mode 100644 dep/acelite/ace/config-vxworks6.6.h create mode 100644 dep/acelite/ace/config-vxworks6.7.h create mode 100644 dep/acelite/ace/config-vxworks6.8.h create mode 100644 dep/acelite/ace/config-win32-borland.h create mode 100644 dep/acelite/ace/config-win32-cegcc.h create mode 100644 dep/acelite/ace/config-win32-common.h create mode 100644 dep/acelite/ace/config-win32-dmc.h create mode 100644 dep/acelite/ace/config-win32-ghs.h create mode 100644 dep/acelite/ace/config-win32-interix.h create mode 100644 dep/acelite/ace/config-win32-mingw.h create mode 100644 dep/acelite/ace/config-win32-msvc-10.h create mode 100644 dep/acelite/ace/config-win32-msvc-7.h create mode 100644 dep/acelite/ace/config-win32-msvc-8.h create mode 100644 dep/acelite/ace/config-win32-msvc-9.h create mode 100644 dep/acelite/ace/config-win32-msvc.h create mode 100644 dep/acelite/ace/config-win32.h create mode 100644 dep/acelite/ace/config.h.in create mode 100644 dep/acelite/ace/gethrtime.cpp create mode 100644 dep/acelite/ace/iosfwd.h create mode 100644 dep/acelite/ace/os_include/arpa/os_inet.h create mode 100644 dep/acelite/ace/os_include/net/os_if.h create mode 100644 dep/acelite/ace/os_include/netinet/os_in.h create mode 100644 dep/acelite/ace/os_include/netinet/os_tcp.h create mode 100644 dep/acelite/ace/os_include/os_aio.h create mode 100644 dep/acelite/ace/os_include/os_assert.h create mode 100644 dep/acelite/ace/os_include/os_byteswap.h create mode 100644 dep/acelite/ace/os_include/os_complex.h create mode 100644 dep/acelite/ace/os_include/os_cpio.h create mode 100644 dep/acelite/ace/os_include/os_ctype.h create mode 100644 dep/acelite/ace/os_include/os_dirent.h create mode 100644 dep/acelite/ace/os_include/os_dlfcn.h create mode 100644 dep/acelite/ace/os_include/os_errno.h create mode 100644 dep/acelite/ace/os_include/os_fcntl.h create mode 100644 dep/acelite/ace/os_include/os_fenv.h create mode 100644 dep/acelite/ace/os_include/os_float.h create mode 100644 dep/acelite/ace/os_include/os_fmtmsg.h create mode 100644 dep/acelite/ace/os_include/os_fnmatch.h create mode 100644 dep/acelite/ace/os_include/os_ftw.h create mode 100644 dep/acelite/ace/os_include/os_glob.h create mode 100644 dep/acelite/ace/os_include/os_grp.h create mode 100644 dep/acelite/ace/os_include/os_iconv.h create mode 100644 dep/acelite/ace/os_include/os_intrin.h create mode 100644 dep/acelite/ace/os_include/os_inttypes.h create mode 100644 dep/acelite/ace/os_include/os_iso646.h create mode 100644 dep/acelite/ace/os_include/os_kstat.h create mode 100644 dep/acelite/ace/os_include/os_langinfo.h create mode 100644 dep/acelite/ace/os_include/os_libgen.h create mode 100644 dep/acelite/ace/os_include/os_limits.h create mode 100644 dep/acelite/ace/os_include/os_local.h create mode 100644 dep/acelite/ace/os_include/os_math.h create mode 100644 dep/acelite/ace/os_include/os_monetary.h create mode 100644 dep/acelite/ace/os_include/os_mqueue.h create mode 100644 dep/acelite/ace/os_include/os_ndbm.h create mode 100644 dep/acelite/ace/os_include/os_netdb.h create mode 100644 dep/acelite/ace/os_include/os_nl_types.h create mode 100644 dep/acelite/ace/os_include/os_pdh.h create mode 100644 dep/acelite/ace/os_include/os_pdhmsg.h create mode 100644 dep/acelite/ace/os_include/os_poll.h create mode 100644 dep/acelite/ace/os_include/os_pthread.h create mode 100644 dep/acelite/ace/os_include/os_pwd.h create mode 100644 dep/acelite/ace/os_include/os_regex.h create mode 100644 dep/acelite/ace/os_include/os_sched.h create mode 100644 dep/acelite/ace/os_include/os_search.h create mode 100644 dep/acelite/ace/os_include/os_semaphore.h create mode 100644 dep/acelite/ace/os_include/os_setjmp.h create mode 100644 dep/acelite/ace/os_include/os_signal.h create mode 100644 dep/acelite/ace/os_include/os_spawn.h create mode 100644 dep/acelite/ace/os_include/os_stdarg.h create mode 100644 dep/acelite/ace/os_include/os_stdbool.h create mode 100644 dep/acelite/ace/os_include/os_stddef.h create mode 100644 dep/acelite/ace/os_include/os_stdint.h create mode 100644 dep/acelite/ace/os_include/os_stdio.h create mode 100644 dep/acelite/ace/os_include/os_stdlib.h create mode 100644 dep/acelite/ace/os_include/os_string.h create mode 100644 dep/acelite/ace/os_include/os_strings.h create mode 100644 dep/acelite/ace/os_include/os_stropts.h create mode 100644 dep/acelite/ace/os_include/os_syslog.h create mode 100644 dep/acelite/ace/os_include/os_tar.h create mode 100644 dep/acelite/ace/os_include/os_termios.h create mode 100644 dep/acelite/ace/os_include/os_tgmath.h create mode 100644 dep/acelite/ace/os_include/os_time.h create mode 100644 dep/acelite/ace/os_include/os_trace.h create mode 100644 dep/acelite/ace/os_include/os_typeinfo.h create mode 100644 dep/acelite/ace/os_include/os_ucontext.h create mode 100644 dep/acelite/ace/os_include/os_ulimit.h create mode 100644 dep/acelite/ace/os_include/os_unistd.h create mode 100644 dep/acelite/ace/os_include/os_utime.h create mode 100644 dep/acelite/ace/os_include/os_utmpx.h create mode 100644 dep/acelite/ace/os_include/os_wchar.h create mode 100644 dep/acelite/ace/os_include/os_wctype.h create mode 100644 dep/acelite/ace/os_include/os_wordexp.h create mode 100644 dep/acelite/ace/os_include/sys/os_ipc.h create mode 100644 dep/acelite/ace/os_include/sys/os_loadavg.h create mode 100644 dep/acelite/ace/os_include/sys/os_mman.h create mode 100644 dep/acelite/ace/os_include/sys/os_msg.h create mode 100644 dep/acelite/ace/os_include/sys/os_pstat.h create mode 100644 dep/acelite/ace/os_include/sys/os_resource.h create mode 100644 dep/acelite/ace/os_include/sys/os_select.h create mode 100644 dep/acelite/ace/os_include/sys/os_sem.h create mode 100644 dep/acelite/ace/os_include/sys/os_shm.h create mode 100644 dep/acelite/ace/os_include/sys/os_socket.h create mode 100644 dep/acelite/ace/os_include/sys/os_stat.h create mode 100644 dep/acelite/ace/os_include/sys/os_statvfs.h create mode 100644 dep/acelite/ace/os_include/sys/os_sysctl.h create mode 100644 dep/acelite/ace/os_include/sys/os_sysinfo.h create mode 100644 dep/acelite/ace/os_include/sys/os_time.h create mode 100644 dep/acelite/ace/os_include/sys/os_timeb.h create mode 100644 dep/acelite/ace/os_include/sys/os_times.h create mode 100644 dep/acelite/ace/os_include/sys/os_types.h create mode 100644 dep/acelite/ace/os_include/sys/os_uio.h create mode 100644 dep/acelite/ace/os_include/sys/os_un.h create mode 100644 dep/acelite/ace/os_include/sys/os_utsname.h create mode 100644 dep/acelite/ace/os_include/sys/os_wait.h create mode 100644 dep/acelite/ace/post.h create mode 100644 dep/acelite/ace/pre.h create mode 100644 dep/acelite/ace/streams.h create mode 100644 dep/acelite/ace/svc_export.h create mode 100644 dep/bzip2/CMakeLists.txt create mode 100644 dep/bzip2/blocksort.c create mode 100644 dep/bzip2/bzlib.c create mode 100644 dep/bzip2/bzlib.h create mode 100644 dep/bzip2/bzlib_private.h create mode 100644 dep/bzip2/compress.c create mode 100644 dep/bzip2/crctable.c create mode 100644 dep/bzip2/decompress.c create mode 100644 dep/bzip2/huffman.c create mode 100644 dep/bzip2/randtable.c create mode 100644 dep/g3dlite/AABox.cpp create mode 100644 dep/g3dlite/Any.cpp create mode 100644 dep/g3dlite/BinaryFormat.cpp create mode 100644 dep/g3dlite/BinaryInput.cpp create mode 100644 dep/g3dlite/BinaryOutput.cpp create mode 100644 dep/g3dlite/Box.cpp create mode 100644 dep/g3dlite/CMakeLists.txt create mode 100644 dep/g3dlite/Capsule.cpp create mode 100644 dep/g3dlite/CollisionDetection.cpp create mode 100644 dep/g3dlite/CoordinateFrame.cpp create mode 100644 dep/g3dlite/Crypto.cpp create mode 100644 dep/g3dlite/Cylinder.cpp create mode 100644 dep/g3dlite/G3D/AABox.h create mode 100644 dep/g3dlite/G3D/Any.h create mode 100644 dep/g3dlite/G3D/AnyVal.h create mode 100644 dep/g3dlite/G3D/AreaMemoryManager.h create mode 100644 dep/g3dlite/G3D/Array.h create mode 100644 dep/g3dlite/G3D/AtomicInt32.h create mode 100644 dep/g3dlite/G3D/BinaryFormat.h create mode 100644 dep/g3dlite/G3D/BinaryInput.h create mode 100644 dep/g3dlite/G3D/BinaryOutput.h create mode 100644 dep/g3dlite/G3D/BoundsTrait.h create mode 100644 dep/g3dlite/G3D/Box.h create mode 100644 dep/g3dlite/G3D/Box2D.h create mode 100644 dep/g3dlite/G3D/BumpMapPreprocess.h create mode 100644 dep/g3dlite/G3D/Capsule.h create mode 100644 dep/g3dlite/G3D/CollisionDetection.h create mode 100644 dep/g3dlite/G3D/Color1.h create mode 100644 dep/g3dlite/G3D/Color1uint8.h create mode 100644 dep/g3dlite/G3D/Color3.h create mode 100644 dep/g3dlite/G3D/Color3uint8.h create mode 100644 dep/g3dlite/G3D/Color4.h create mode 100644 dep/g3dlite/G3D/Color4uint8.h create mode 100644 dep/g3dlite/G3D/Cone.h create mode 100644 dep/g3dlite/G3D/ConvexPolyhedron.h create mode 100644 dep/g3dlite/G3D/CoordinateFrame.h create mode 100644 dep/g3dlite/G3D/Crypto.h create mode 100644 dep/g3dlite/G3D/Cylinder.h create mode 100644 dep/g3dlite/G3D/EqualsTrait.h create mode 100644 dep/g3dlite/G3D/G3D.h create mode 100644 dep/g3dlite/G3D/G3DAll.h create mode 100644 dep/g3dlite/G3D/G3DGameUnits.h create mode 100644 dep/g3dlite/G3D/GCamera.h create mode 100644 dep/g3dlite/G3D/GImage.h create mode 100644 dep/g3dlite/G3D/GLight.h create mode 100644 dep/g3dlite/G3D/GMutex.h create mode 100644 dep/g3dlite/G3D/GThread.h create mode 100644 dep/g3dlite/G3D/GUniqueID.h create mode 100644 dep/g3dlite/G3D/HashTrait.h create mode 100644 dep/g3dlite/G3D/Image1.h create mode 100644 dep/g3dlite/G3D/Image1uint8.h create mode 100644 dep/g3dlite/G3D/Image3.h create mode 100644 dep/g3dlite/G3D/Image3uint8.h create mode 100644 dep/g3dlite/G3D/Image4.h create mode 100644 dep/g3dlite/G3D/Image4uint8.h create mode 100644 dep/g3dlite/G3D/ImageFormat.h create mode 100644 dep/g3dlite/G3D/Intersect.h create mode 100644 dep/g3dlite/G3D/KDTree.h create mode 100644 dep/g3dlite/G3D/Line.h create mode 100644 dep/g3dlite/G3D/LineSegment.h create mode 100644 dep/g3dlite/G3D/Log.h create mode 100644 dep/g3dlite/G3D/Map2D.h create mode 100644 dep/g3dlite/G3D/Matrix.h create mode 100644 dep/g3dlite/G3D/Matrix2.h create mode 100644 dep/g3dlite/G3D/Matrix3.h create mode 100644 dep/g3dlite/G3D/Matrix4.h create mode 100644 dep/g3dlite/G3D/MemoryManager.h create mode 100644 dep/g3dlite/G3D/MeshAlg.h create mode 100644 dep/g3dlite/G3D/MeshBuilder.h create mode 100644 dep/g3dlite/G3D/NetAddress.h create mode 100644 dep/g3dlite/G3D/NetworkDevice.h create mode 100644 dep/g3dlite/G3D/ParseError.h create mode 100644 dep/g3dlite/G3D/PhysicsFrame.h create mode 100644 dep/g3dlite/G3D/Plane.h create mode 100644 dep/g3dlite/G3D/PointHashGrid.h create mode 100644 dep/g3dlite/G3D/PointKDTree.h create mode 100644 dep/g3dlite/G3D/Pointer.h create mode 100644 dep/g3dlite/G3D/PositionTrait.h create mode 100644 dep/g3dlite/G3D/PrecomputedRandom.h create mode 100644 dep/g3dlite/G3D/Quat.h create mode 100644 dep/g3dlite/G3D/Quat.inl create mode 100644 dep/g3dlite/G3D/Queue.h create mode 100644 dep/g3dlite/G3D/Random.h create mode 100644 dep/g3dlite/G3D/Ray.h create mode 100644 dep/g3dlite/G3D/Rect2D.h create mode 100644 dep/g3dlite/G3D/ReferenceCount.h create mode 100644 dep/g3dlite/G3D/RegistryUtil.h create mode 100644 dep/g3dlite/G3D/Set.h create mode 100644 dep/g3dlite/G3D/SmallArray.h create mode 100644 dep/g3dlite/G3D/Sphere.h create mode 100644 dep/g3dlite/G3D/Spline.h create mode 100644 dep/g3dlite/G3D/Stopwatch.h create mode 100644 dep/g3dlite/G3D/System.h create mode 100644 dep/g3dlite/G3D/Table.h create mode 100644 dep/g3dlite/G3D/TextInput.h create mode 100644 dep/g3dlite/G3D/TextOutput.h create mode 100644 dep/g3dlite/G3D/ThreadSet.h create mode 100644 dep/g3dlite/G3D/Triangle.h create mode 100644 dep/g3dlite/G3D/UprightFrame.h create mode 100644 dep/g3dlite/G3D/Vector2.h create mode 100644 dep/g3dlite/G3D/Vector2.inl create mode 100644 dep/g3dlite/G3D/Vector2int16.h create mode 100644 dep/g3dlite/G3D/Vector3.h create mode 100644 dep/g3dlite/G3D/Vector3.inl create mode 100644 dep/g3dlite/G3D/Vector3int16.h create mode 100644 dep/g3dlite/G3D/Vector3int32.h create mode 100644 dep/g3dlite/G3D/Vector4.h create mode 100644 dep/g3dlite/G3D/Vector4.inl create mode 100644 dep/g3dlite/G3D/Vector4int8.h create mode 100644 dep/g3dlite/G3D/WeakCache.h create mode 100644 dep/g3dlite/G3D/Welder.h create mode 100644 dep/g3dlite/G3D/WrapMode.h create mode 100644 dep/g3dlite/G3D/constants.h create mode 100644 dep/g3dlite/G3D/debug.h create mode 100644 dep/g3dlite/G3D/debugAssert.h create mode 100644 dep/g3dlite/G3D/debugPrintf.h create mode 100644 dep/g3dlite/G3D/enumclass.h create mode 100644 dep/g3dlite/G3D/fileutils.h create mode 100644 dep/g3dlite/G3D/filter.h create mode 100644 dep/g3dlite/G3D/format.h create mode 100644 dep/g3dlite/G3D/g3dfnmatch.h create mode 100644 dep/g3dlite/G3D/g3dmath.h create mode 100644 dep/g3dlite/G3D/g3dmath.inl create mode 100644 dep/g3dlite/G3D/platform.h create mode 100644 dep/g3dlite/G3D/prompt.h create mode 100644 dep/g3dlite/G3D/serialize.h create mode 100644 dep/g3dlite/G3D/splinefunc.h create mode 100644 dep/g3dlite/G3D/stringutils.h create mode 100644 dep/g3dlite/G3D/uint128.h create mode 100644 dep/g3dlite/G3D/units.h create mode 100644 dep/g3dlite/G3D/vectorMath.h create mode 100644 dep/g3dlite/Line.cpp create mode 100644 dep/g3dlite/LineSegment.cpp create mode 100644 dep/g3dlite/Log.cpp create mode 100644 dep/g3dlite/Matrix3.cpp create mode 100644 dep/g3dlite/Matrix4.cpp create mode 100644 dep/g3dlite/MemoryManager.cpp create mode 100644 dep/g3dlite/Plane.cpp create mode 100644 dep/g3dlite/Quat.cpp create mode 100644 dep/g3dlite/Random.cpp create mode 100644 dep/g3dlite/Ray.cpp create mode 100644 dep/g3dlite/ReferenceCount.cpp create mode 100644 dep/g3dlite/RegistryUtil.cpp create mode 100644 dep/g3dlite/Sphere.cpp create mode 100644 dep/g3dlite/System.cpp create mode 100644 dep/g3dlite/TextInput.cpp create mode 100644 dep/g3dlite/TextOutput.cpp create mode 100644 dep/g3dlite/Triangle.cpp create mode 100644 dep/g3dlite/UprightFrame.cpp create mode 100644 dep/g3dlite/Vector2.cpp create mode 100644 dep/g3dlite/Vector3.cpp create mode 100644 dep/g3dlite/Vector4.cpp create mode 100644 dep/g3dlite/debugAssert.cpp create mode 100644 dep/g3dlite/fileutils.cpp create mode 100644 dep/g3dlite/format.cpp create mode 100644 dep/g3dlite/g3dfnmatch.cpp create mode 100644 dep/g3dlite/g3dmath.cpp create mode 100644 dep/g3dlite/prompt.cpp create mode 100644 dep/g3dlite/stringutils.cpp create mode 100644 dep/gsoap/CMakeLists.txt create mode 100644 dep/gsoap/soapC.cpp create mode 100644 dep/gsoap/soapH.h create mode 100644 dep/gsoap/soapServer.cpp create mode 100644 dep/gsoap/soapStub.h create mode 100644 dep/gsoap/stdsoap2.cpp create mode 100644 dep/gsoap/stdsoap2.h create mode 100644 dep/jemalloc/CMakeLists.txt create mode 100644 dep/jemalloc/arena.c create mode 100644 dep/jemalloc/base.c create mode 100644 dep/jemalloc/chunk.c create mode 100644 dep/jemalloc/chunk_dss.c create mode 100644 dep/jemalloc/chunk_mmap.c create mode 100644 dep/jemalloc/chunk_swap.c create mode 100644 dep/jemalloc/ckh.c create mode 100644 dep/jemalloc/ctl.c create mode 100644 dep/jemalloc/extent.c create mode 100644 dep/jemalloc/hash.c create mode 100644 dep/jemalloc/huge.c create mode 100644 dep/jemalloc/jemalloc.c create mode 100644 dep/jemalloc/jemalloc/internal/arena.h create mode 100644 dep/jemalloc/jemalloc/internal/base.h create mode 100644 dep/jemalloc/jemalloc/internal/chunk.h create mode 100644 dep/jemalloc/jemalloc/internal/chunk_dss.h create mode 100644 dep/jemalloc/jemalloc/internal/chunk_mmap.h create mode 100644 dep/jemalloc/jemalloc/internal/chunk_swap.h create mode 100644 dep/jemalloc/jemalloc/internal/ckh.h create mode 100644 dep/jemalloc/jemalloc/internal/ctl.h create mode 100644 dep/jemalloc/jemalloc/internal/extent.h create mode 100644 dep/jemalloc/jemalloc/internal/hash.h create mode 100644 dep/jemalloc/jemalloc/internal/huge.h create mode 100644 dep/jemalloc/jemalloc/internal/jemalloc_internal.h create mode 100644 dep/jemalloc/jemalloc/internal/jemalloc_internal.h.in create mode 100644 dep/jemalloc/jemalloc/internal/mb.h create mode 100644 dep/jemalloc/jemalloc/internal/mutex.h create mode 100644 dep/jemalloc/jemalloc/internal/prof.h create mode 100644 dep/jemalloc/jemalloc/internal/ql.h create mode 100644 dep/jemalloc/jemalloc/internal/qr.h create mode 100644 dep/jemalloc/jemalloc/internal/rb.h create mode 100644 dep/jemalloc/jemalloc/internal/stats.h create mode 100644 dep/jemalloc/jemalloc/internal/tcache.h create mode 100644 dep/jemalloc/jemalloc/internal/totally_not_p_r_n.h create mode 100644 dep/jemalloc/jemalloc/jemalloc.h create mode 100644 dep/jemalloc/jemalloc/jemalloc.h.in create mode 100644 dep/jemalloc/jemalloc/jemalloc_defs.h create mode 100644 dep/jemalloc/jemalloc/jemalloc_defs.h.in create mode 100644 dep/jemalloc/mb.c create mode 100644 dep/jemalloc/mutex.c create mode 100644 dep/jemalloc/prof.c create mode 100644 dep/jemalloc/stats.c create mode 100644 dep/jemalloc/tcache.c create mode 100644 dep/libmpq/AUTHORS create mode 100644 dep/libmpq/CMakeLists.txt create mode 100644 dep/libmpq/COPYING create mode 100644 dep/libmpq/FAQ create mode 100644 dep/libmpq/INSTALL create mode 100644 dep/libmpq/Makefile.am create mode 100644 dep/libmpq/NEWS create mode 100644 dep/libmpq/README create mode 100644 dep/libmpq/THANKS create mode 100644 dep/libmpq/TODO create mode 100644 dep/libmpq/autogen.sh create mode 100644 dep/libmpq/bindings/Makefile.am create mode 100644 dep/libmpq/bindings/d/Makefile.am create mode 100644 dep/libmpq/bindings/d/dsss.conf create mode 100644 dep/libmpq/bindings/d/mpq.d create mode 100644 dep/libmpq/bindings/python/Makefile.am create mode 100644 dep/libmpq/bindings/python/mpq-info create mode 100644 dep/libmpq/bindings/python/mpq.py create mode 100644 dep/libmpq/config.h create mode 100644 dep/libmpq/configure.ac create mode 100644 dep/libmpq/debian/changelog create mode 100644 dep/libmpq/debian/compat create mode 100644 dep/libmpq/debian/control create mode 100644 dep/libmpq/debian/copyright create mode 100644 dep/libmpq/debian/libmpq-dev.dirs create mode 100644 dep/libmpq/debian/libmpq-dev.install create mode 100644 dep/libmpq/debian/libmpq0.dirs create mode 100644 dep/libmpq/debian/libmpq0.docs create mode 100644 dep/libmpq/debian/libmpq0.install create mode 100644 dep/libmpq/debian/python-mpq.install create mode 100644 dep/libmpq/debian/rules create mode 100644 dep/libmpq/doc/Makefile.am create mode 100644 dep/libmpq/doc/man1/Makefile.am create mode 100644 dep/libmpq/doc/man1/libmpq-config.1 create mode 100644 dep/libmpq/doc/man3/Makefile.am create mode 100644 dep/libmpq/doc/man3/libmpq.3 create mode 100644 dep/libmpq/doc/man3/libmpq__archive_close.3 create mode 100644 dep/libmpq/doc/man3/libmpq__archive_files.3 create mode 100644 dep/libmpq/doc/man3/libmpq__archive_offset.3 create mode 100644 dep/libmpq/doc/man3/libmpq__archive_open.3 create mode 100644 dep/libmpq/doc/man3/libmpq__archive_packed_size.3 create mode 100644 dep/libmpq/doc/man3/libmpq__archive_unpacked_size.3 create mode 100644 dep/libmpq/doc/man3/libmpq__archive_version.3 create mode 100644 dep/libmpq/doc/man3/libmpq__block_close_offset.3 create mode 100644 dep/libmpq/doc/man3/libmpq__block_open_offset.3 create mode 100644 dep/libmpq/doc/man3/libmpq__block_read.3 create mode 100644 dep/libmpq/doc/man3/libmpq__block_unpacked_size.3 create mode 100644 dep/libmpq/doc/man3/libmpq__file_blocks.3 create mode 100644 dep/libmpq/doc/man3/libmpq__file_compressed.3 create mode 100644 dep/libmpq/doc/man3/libmpq__file_encrypted.3 create mode 100644 dep/libmpq/doc/man3/libmpq__file_imploded.3 create mode 100644 dep/libmpq/doc/man3/libmpq__file_number.3 create mode 100644 dep/libmpq/doc/man3/libmpq__file_offset.3 create mode 100644 dep/libmpq/doc/man3/libmpq__file_packed_size.3 create mode 100644 dep/libmpq/doc/man3/libmpq__file_read.3 create mode 100644 dep/libmpq/doc/man3/libmpq__file_unpacked_size.3 create mode 100644 dep/libmpq/doc/man3/libmpq__strerror.3 create mode 100644 dep/libmpq/doc/man3/libmpq__version.3 create mode 100644 dep/libmpq/libmpq-config.in create mode 100644 dep/libmpq/libmpq.pc.in create mode 100644 dep/libmpq/libmpq/Makefile.am create mode 100644 dep/libmpq/libmpq/common.c create mode 100644 dep/libmpq/libmpq/common.h create mode 100644 dep/libmpq/libmpq/crypt_buf.h create mode 100644 dep/libmpq/libmpq/explode.c create mode 100644 dep/libmpq/libmpq/explode.h create mode 100644 dep/libmpq/libmpq/extract.c create mode 100644 dep/libmpq/libmpq/extract.h create mode 100644 dep/libmpq/libmpq/huffman.c create mode 100644 dep/libmpq/libmpq/huffman.h create mode 100644 dep/libmpq/libmpq/mpq-internal.h create mode 100644 dep/libmpq/libmpq/mpq.c create mode 100644 dep/libmpq/libmpq/mpq.h create mode 100644 dep/libmpq/libmpq/pack_begin.h create mode 100644 dep/libmpq/libmpq/pack_end.h create mode 100644 dep/libmpq/libmpq/platform.h create mode 100644 dep/libmpq/libmpq/wave.c create mode 100644 dep/libmpq/libmpq/wave.h create mode 100644 dep/libmpq/tools/Makefile.am create mode 100644 dep/libmpq/tools/crypt_buf_gen.c create mode 100644 dep/libmpq/win/config.h create mode 100644 dep/libmpq/win/dirent.h create mode 100644 dep/libmpq/win/stdint.h create mode 100644 dep/mersennetwister/MersenneTwister.h create mode 100644 dep/sockets/Base64.cpp create mode 100644 dep/sockets/CMakeLists.txt create mode 100644 dep/sockets/Exception.cpp create mode 100644 dep/sockets/Ipv4Address.cpp create mode 100644 dep/sockets/Ipv6Address.cpp create mode 100644 dep/sockets/Lock.cpp create mode 100644 dep/sockets/Makefile create mode 100644 dep/sockets/Mutex.cpp create mode 100644 dep/sockets/Parse.cpp create mode 100644 dep/sockets/ResolvServer.cpp create mode 100644 dep/sockets/ResolvSocket.cpp create mode 100644 dep/sockets/Socket.cpp create mode 100644 dep/sockets/SocketHandler.cpp create mode 100644 dep/sockets/StdoutLog.cpp create mode 100644 dep/sockets/StreamSocket.cpp create mode 100644 dep/sockets/TcpSocket.cpp create mode 100644 dep/sockets/Thread.cpp create mode 100644 dep/sockets/UdpSocket.cpp create mode 100644 dep/sockets/Utility.cpp create mode 100644 dep/sockets/include/Base64.h create mode 100644 dep/sockets/include/Exception.h create mode 100644 dep/sockets/include/File.h create mode 100644 dep/sockets/include/IFile.h create mode 100644 dep/sockets/include/ISocketHandler.h create mode 100644 dep/sockets/include/Ipv4Address.h create mode 100644 dep/sockets/include/Ipv6Address.h create mode 100644 dep/sockets/include/ListenSocket.h create mode 100644 dep/sockets/include/Lock.h create mode 100644 dep/sockets/include/Mutex.h create mode 100644 dep/sockets/include/Parse.h create mode 100644 dep/sockets/include/ResolvServer.h create mode 100644 dep/sockets/include/ResolvSocket.h create mode 100644 dep/sockets/include/SctpSocket.h create mode 100644 dep/sockets/include/Socket.h create mode 100644 dep/sockets/include/SocketAddress.h create mode 100644 dep/sockets/include/SocketHandler.h create mode 100644 dep/sockets/include/StdLog.h create mode 100644 dep/sockets/include/StdoutLog.h create mode 100644 dep/sockets/include/StreamSocket.h create mode 100644 dep/sockets/include/TcpSocket.h create mode 100644 dep/sockets/include/Thread.h create mode 100644 dep/sockets/include/UdpSocket.h create mode 100644 dep/sockets/include/Utility.h create mode 100644 dep/sockets/include/socket_include.h create mode 100644 dep/sockets/include/sockets-config.h create mode 100644 dep/sockets/network_kist.txt create mode 100644 dep/sockets/socket_include.cpp create mode 100644 dep/utf8cpp/utf8.h create mode 100644 dep/utf8cpp/utf8/checked.h create mode 100644 dep/utf8cpp/utf8/core.h create mode 100644 dep/utf8cpp/utf8/unchecked.h create mode 100644 dep/zlib/CMakeLists.txt create mode 100644 dep/zlib/adler32.c create mode 100644 dep/zlib/compress.c create mode 100644 dep/zlib/crc32.c create mode 100644 dep/zlib/crc32.h create mode 100644 dep/zlib/deflate.c create mode 100644 dep/zlib/deflate.h create mode 100644 dep/zlib/example.c create mode 100644 dep/zlib/gzclose.c create mode 100644 dep/zlib/gzguts.h create mode 100644 dep/zlib/gzlib.c create mode 100644 dep/zlib/gzread.c create mode 100644 dep/zlib/gzwrite.c create mode 100644 dep/zlib/infback.c create mode 100644 dep/zlib/inffast.c create mode 100644 dep/zlib/inffast.h create mode 100644 dep/zlib/inffixed.h create mode 100644 dep/zlib/inflate.c create mode 100644 dep/zlib/inflate.h create mode 100644 dep/zlib/inftrees.c create mode 100644 dep/zlib/inftrees.h create mode 100644 dep/zlib/minigzip.c create mode 100644 dep/zlib/trees.c create mode 100644 dep/zlib/trees.h create mode 100644 dep/zlib/uncompr.c create mode 100644 dep/zlib/zconf.h create mode 100644 dep/zlib/zlib.h create mode 100644 dep/zlib/zutil.c create mode 100644 dep/zlib/zutil.h create mode 100644 doc/AuctionHouseBot.txt create mode 100644 doc/EventAI.txt create mode 100644 doc/HowToScript.txt create mode 100644 doc/TextTables.txt create mode 100644 doc/UnixInstall.txt create mode 100644 doc/gpl-2.0.txt delete mode 100644 docs/AuctionHouseBot.txt delete mode 100644 docs/EventAI.txt delete mode 100644 docs/HowToScript.txt delete mode 100644 docs/TextTables.txt delete mode 100644 docs/UnixInstall.txt delete mode 100644 docs/gpl-2.0.txt delete mode 100644 externals/CMakeLists.txt delete mode 100644 externals/PackageList.txt delete mode 100644 externals/SFMT/SFMT-alti.h delete mode 100644 externals/SFMT/SFMT-params.h delete mode 100644 externals/SFMT/SFMT-sse2.h delete mode 100644 externals/SFMT/SFMT.c delete mode 100644 externals/SFMT/SFMT.h delete mode 100644 externals/ace/ACE.cpp delete mode 100644 externals/ace/ACE.h delete mode 100644 externals/ace/ACE.inl delete mode 100644 externals/ace/ACE.pc.in delete mode 100644 externals/ace/ACE_crc32.cpp delete mode 100644 externals/ace/ACE_crc_ccitt.cpp delete mode 100644 externals/ace/ACE_export.h delete mode 100644 externals/ace/ARGV.cpp delete mode 100644 externals/ace/ARGV.h delete mode 100644 externals/ace/ARGV.inl delete mode 100644 externals/ace/ATM_Acceptor.cpp delete mode 100644 externals/ace/ATM_Acceptor.h delete mode 100644 externals/ace/ATM_Acceptor.inl delete mode 100644 externals/ace/ATM_Addr.cpp delete mode 100644 externals/ace/ATM_Addr.h delete mode 100644 externals/ace/ATM_Addr.inl delete mode 100644 externals/ace/ATM_Connector.cpp delete mode 100644 externals/ace/ATM_Connector.h delete mode 100644 externals/ace/ATM_Connector.inl delete mode 100644 externals/ace/ATM_Params.cpp delete mode 100644 externals/ace/ATM_Params.h delete mode 100644 externals/ace/ATM_Params.inl delete mode 100644 externals/ace/ATM_QoS.cpp delete mode 100644 externals/ace/ATM_QoS.h delete mode 100644 externals/ace/ATM_QoS.inl delete mode 100644 externals/ace/ATM_Stream.cpp delete mode 100644 externals/ace/ATM_Stream.h delete mode 100644 externals/ace/ATM_Stream.inl delete mode 100644 externals/ace/Acceptor.cpp delete mode 100644 externals/ace/Acceptor.h delete mode 100644 externals/ace/Activation_Queue.cpp delete mode 100644 externals/ace/Activation_Queue.h delete mode 100644 externals/ace/Activation_Queue.inl delete mode 100644 externals/ace/Active_Map_Manager.cpp delete mode 100644 externals/ace/Active_Map_Manager.h delete mode 100644 externals/ace/Active_Map_Manager.inl delete mode 100644 externals/ace/Active_Map_Manager_T.cpp delete mode 100644 externals/ace/Active_Map_Manager_T.h delete mode 100644 externals/ace/Active_Map_Manager_T.inl delete mode 100644 externals/ace/Addr.cpp delete mode 100644 externals/ace/Addr.h delete mode 100644 externals/ace/Addr.inl delete mode 100644 externals/ace/Arg_Shifter.cpp delete mode 100644 externals/ace/Arg_Shifter.h delete mode 100644 externals/ace/Argv_Type_Converter.cpp delete mode 100644 externals/ace/Argv_Type_Converter.h delete mode 100644 externals/ace/Argv_Type_Converter.inl delete mode 100644 externals/ace/Array.h delete mode 100644 externals/ace/Array_Base.cpp delete mode 100644 externals/ace/Array_Base.h delete mode 100644 externals/ace/Array_Base.inl delete mode 100644 externals/ace/Array_Map.cpp delete mode 100644 externals/ace/Array_Map.h delete mode 100644 externals/ace/Array_Map.inl delete mode 100644 externals/ace/Assert.cpp delete mode 100644 externals/ace/Assert.h delete mode 100644 externals/ace/Asynch_Acceptor.cpp delete mode 100644 externals/ace/Asynch_Acceptor.h delete mode 100644 externals/ace/Asynch_Connector.cpp delete mode 100644 externals/ace/Asynch_Connector.h delete mode 100644 externals/ace/Asynch_IO.cpp delete mode 100644 externals/ace/Asynch_IO.h delete mode 100644 externals/ace/Asynch_IO_Impl.cpp delete mode 100644 externals/ace/Asynch_IO_Impl.h delete mode 100644 externals/ace/Asynch_IO_Impl.inl delete mode 100644 externals/ace/Asynch_Pseudo_Task.cpp delete mode 100644 externals/ace/Asynch_Pseudo_Task.h delete mode 100644 externals/ace/Atomic_Op.cpp delete mode 100644 externals/ace/Atomic_Op.h delete mode 100644 externals/ace/Atomic_Op.inl delete mode 100644 externals/ace/Atomic_Op_GCC_T.cpp delete mode 100644 externals/ace/Atomic_Op_GCC_T.h delete mode 100644 externals/ace/Atomic_Op_GCC_T.inl delete mode 100644 externals/ace/Atomic_Op_Sparc.c delete mode 100644 externals/ace/Atomic_Op_Sparc.h delete mode 100644 externals/ace/Atomic_Op_T.cpp delete mode 100644 externals/ace/Atomic_Op_T.h delete mode 100644 externals/ace/Atomic_Op_T.inl delete mode 100644 externals/ace/Auto_Event.cpp delete mode 100644 externals/ace/Auto_Event.h delete mode 100644 externals/ace/Auto_Event.inl delete mode 100644 externals/ace/Auto_Functor.cpp delete mode 100644 externals/ace/Auto_Functor.h delete mode 100644 externals/ace/Auto_Functor.inl delete mode 100644 externals/ace/Auto_IncDec_T.cpp delete mode 100644 externals/ace/Auto_IncDec_T.h delete mode 100644 externals/ace/Auto_IncDec_T.inl delete mode 100644 externals/ace/Auto_Ptr.cpp delete mode 100644 externals/ace/Auto_Ptr.h delete mode 100644 externals/ace/Auto_Ptr.inl delete mode 100644 externals/ace/Barrier.cpp delete mode 100644 externals/ace/Barrier.h delete mode 100644 externals/ace/Barrier.inl delete mode 100644 externals/ace/Base_Thread_Adapter.cpp delete mode 100644 externals/ace/Base_Thread_Adapter.h delete mode 100644 externals/ace/Base_Thread_Adapter.inl delete mode 100644 externals/ace/Based_Pointer_Repository.cpp delete mode 100644 externals/ace/Based_Pointer_Repository.h delete mode 100644 externals/ace/Based_Pointer_T.cpp delete mode 100644 externals/ace/Based_Pointer_T.h delete mode 100644 externals/ace/Based_Pointer_T.inl delete mode 100644 externals/ace/Basic_Stats.cpp delete mode 100644 externals/ace/Basic_Stats.h delete mode 100644 externals/ace/Basic_Stats.inl delete mode 100644 externals/ace/Basic_Types.cpp delete mode 100644 externals/ace/Basic_Types.h delete mode 100644 externals/ace/Basic_Types.inl delete mode 100644 externals/ace/Bound_Ptr.h delete mode 100644 externals/ace/Bound_Ptr.inl delete mode 100644 externals/ace/CDR_Base.cpp delete mode 100644 externals/ace/CDR_Base.h delete mode 100644 externals/ace/CDR_Base.inl delete mode 100644 externals/ace/CDR_Size.cpp delete mode 100644 externals/ace/CDR_Size.h delete mode 100644 externals/ace/CDR_Size.inl delete mode 100644 externals/ace/CDR_Stream.cpp delete mode 100644 externals/ace/CDR_Stream.h delete mode 100644 externals/ace/CDR_Stream.inl delete mode 100644 externals/ace/CE_Screen_Output.cpp delete mode 100644 externals/ace/CE_Screen_Output.h delete mode 100644 externals/ace/CMakeLists.txt delete mode 100644 externals/ace/CORBA_macros.h delete mode 100644 externals/ace/Cache_Map_Manager_T.cpp delete mode 100644 externals/ace/Cache_Map_Manager_T.h delete mode 100644 externals/ace/Cache_Map_Manager_T.inl delete mode 100644 externals/ace/Cached_Connect_Strategy_T.cpp delete mode 100644 externals/ace/Cached_Connect_Strategy_T.h delete mode 100644 externals/ace/Caching_Strategies_T.cpp delete mode 100644 externals/ace/Caching_Strategies_T.h delete mode 100644 externals/ace/Caching_Strategies_T.inl delete mode 100644 externals/ace/Caching_Utility_T.cpp delete mode 100644 externals/ace/Caching_Utility_T.h delete mode 100644 externals/ace/Capabilities.cpp delete mode 100644 externals/ace/Capabilities.h delete mode 100644 externals/ace/Capabilities.inl delete mode 100644 externals/ace/Cleanup.cpp delete mode 100644 externals/ace/Cleanup.h delete mode 100644 externals/ace/Cleanup.inl delete mode 100644 externals/ace/Cleanup_Strategies_T.cpp delete mode 100644 externals/ace/Cleanup_Strategies_T.h delete mode 100644 externals/ace/Codecs.cpp delete mode 100644 externals/ace/Codecs.h delete mode 100644 externals/ace/Codeset_IBM1047.cpp delete mode 100644 externals/ace/Codeset_IBM1047.h delete mode 100644 externals/ace/Codeset_Registry.cpp delete mode 100644 externals/ace/Codeset_Registry.h delete mode 100644 externals/ace/Codeset_Registry.inl delete mode 100644 externals/ace/Codeset_Registry_db.cpp delete mode 100644 externals/ace/Codeset_Symbols.h delete mode 100644 externals/ace/Condition_Recursive_Thread_Mutex.cpp delete mode 100644 externals/ace/Condition_Recursive_Thread_Mutex.h delete mode 100644 externals/ace/Condition_T.cpp delete mode 100644 externals/ace/Condition_T.h delete mode 100644 externals/ace/Condition_T.inl delete mode 100644 externals/ace/Condition_Thread_Mutex.cpp delete mode 100644 externals/ace/Condition_Thread_Mutex.h delete mode 100644 externals/ace/Condition_Thread_Mutex.inl delete mode 100644 externals/ace/Configuration.cpp delete mode 100644 externals/ace/Configuration.h delete mode 100644 externals/ace/Configuration.inl delete mode 100644 externals/ace/Configuration_Import_Export.cpp delete mode 100644 externals/ace/Configuration_Import_Export.h delete mode 100644 externals/ace/Connection_Recycling_Strategy.cpp delete mode 100644 externals/ace/Connection_Recycling_Strategy.h delete mode 100644 externals/ace/Connector.cpp delete mode 100644 externals/ace/Connector.h delete mode 100644 externals/ace/Containers.cpp delete mode 100644 externals/ace/Containers.h delete mode 100644 externals/ace/Containers.inl delete mode 100644 externals/ace/Containers_T.cpp delete mode 100644 externals/ace/Containers_T.h delete mode 100644 externals/ace/Containers_T.inl delete mode 100644 externals/ace/Copy_Disabled.cpp delete mode 100644 externals/ace/Copy_Disabled.h delete mode 100644 externals/ace/Countdown_Time.cpp delete mode 100644 externals/ace/Countdown_Time.h delete mode 100644 externals/ace/Countdown_Time.inl delete mode 100644 externals/ace/DEV.cpp delete mode 100644 externals/ace/DEV.h delete mode 100644 externals/ace/DEV.inl delete mode 100644 externals/ace/DEV_Addr.cpp delete mode 100644 externals/ace/DEV_Addr.h delete mode 100644 externals/ace/DEV_Addr.inl delete mode 100644 externals/ace/DEV_Connector.cpp delete mode 100644 externals/ace/DEV_Connector.h delete mode 100644 externals/ace/DEV_Connector.inl delete mode 100644 externals/ace/DEV_IO.cpp delete mode 100644 externals/ace/DEV_IO.h delete mode 100644 externals/ace/DEV_IO.inl delete mode 100644 externals/ace/DLL.cpp delete mode 100644 externals/ace/DLL.h delete mode 100644 externals/ace/DLL_Manager.cpp delete mode 100644 externals/ace/DLL_Manager.h delete mode 100644 externals/ace/Date_Time.cpp delete mode 100644 externals/ace/Date_Time.h delete mode 100644 externals/ace/Date_Time.inl delete mode 100644 externals/ace/Default_Constants.h delete mode 100644 externals/ace/Dev_Poll_Reactor.cpp delete mode 100644 externals/ace/Dev_Poll_Reactor.h delete mode 100644 externals/ace/Dev_Poll_Reactor.inl delete mode 100644 externals/ace/Dirent.cpp delete mode 100644 externals/ace/Dirent.h delete mode 100644 externals/ace/Dirent.inl delete mode 100644 externals/ace/Dirent_Selector.cpp delete mode 100644 externals/ace/Dirent_Selector.h delete mode 100644 externals/ace/Dirent_Selector.inl delete mode 100644 externals/ace/Dump.cpp delete mode 100644 externals/ace/Dump.h delete mode 100644 externals/ace/Dump_T.cpp delete mode 100644 externals/ace/Dump_T.h delete mode 100644 externals/ace/Dynamic.cpp delete mode 100644 externals/ace/Dynamic.h delete mode 100644 externals/ace/Dynamic.inl delete mode 100644 externals/ace/Dynamic_Message_Strategy.cpp delete mode 100644 externals/ace/Dynamic_Message_Strategy.h delete mode 100644 externals/ace/Dynamic_Message_Strategy.inl delete mode 100644 externals/ace/Dynamic_Service.cpp delete mode 100644 externals/ace/Dynamic_Service.h delete mode 100644 externals/ace/Dynamic_Service.inl delete mode 100644 externals/ace/Dynamic_Service_Base.cpp delete mode 100644 externals/ace/Dynamic_Service_Base.h delete mode 100644 externals/ace/Dynamic_Service_Dependency.cpp delete mode 100644 externals/ace/Dynamic_Service_Dependency.h delete mode 100644 externals/ace/Encoding_Converter.cpp delete mode 100644 externals/ace/Encoding_Converter.h delete mode 100644 externals/ace/Encoding_Converter_Factory.cpp delete mode 100644 externals/ace/Encoding_Converter_Factory.h delete mode 100644 externals/ace/Env_Value_T.cpp delete mode 100644 externals/ace/Env_Value_T.h delete mode 100644 externals/ace/Env_Value_T.inl delete mode 100644 externals/ace/Event.cpp delete mode 100644 externals/ace/Event.h delete mode 100644 externals/ace/Event.inl delete mode 100644 externals/ace/Event_Handler.cpp delete mode 100644 externals/ace/Event_Handler.h delete mode 100644 externals/ace/Event_Handler.inl delete mode 100644 externals/ace/Event_Handler_T.cpp delete mode 100644 externals/ace/Event_Handler_T.h delete mode 100644 externals/ace/Event_Handler_T.inl delete mode 100644 externals/ace/Exception_Macros.h delete mode 100644 externals/ace/FIFO.cpp delete mode 100644 externals/ace/FIFO.h delete mode 100644 externals/ace/FIFO.inl delete mode 100644 externals/ace/FIFO_Recv.cpp delete mode 100644 externals/ace/FIFO_Recv.h delete mode 100644 externals/ace/FIFO_Recv.inl delete mode 100644 externals/ace/FIFO_Recv_Msg.cpp delete mode 100644 externals/ace/FIFO_Recv_Msg.h delete mode 100644 externals/ace/FIFO_Recv_Msg.inl delete mode 100644 externals/ace/FIFO_Send.cpp delete mode 100644 externals/ace/FIFO_Send.h delete mode 100644 externals/ace/FIFO_Send.inl delete mode 100644 externals/ace/FIFO_Send_Msg.cpp delete mode 100644 externals/ace/FIFO_Send_Msg.h delete mode 100644 externals/ace/FIFO_Send_Msg.inl delete mode 100644 externals/ace/FILE.cpp delete mode 100644 externals/ace/FILE.h delete mode 100644 externals/ace/FILE.inl delete mode 100644 externals/ace/FILE_Addr.cpp delete mode 100644 externals/ace/FILE_Addr.h delete mode 100644 externals/ace/FILE_Addr.inl delete mode 100644 externals/ace/FILE_Connector.cpp delete mode 100644 externals/ace/FILE_Connector.h delete mode 100644 externals/ace/FILE_Connector.inl delete mode 100644 externals/ace/FILE_IO.cpp delete mode 100644 externals/ace/FILE_IO.h delete mode 100644 externals/ace/FILE_IO.inl delete mode 100644 externals/ace/File_Lock.cpp delete mode 100644 externals/ace/File_Lock.h delete mode 100644 externals/ace/File_Lock.inl delete mode 100644 externals/ace/Filecache.cpp delete mode 100644 externals/ace/Filecache.h delete mode 100644 externals/ace/Flag_Manip.cpp delete mode 100644 externals/ace/Flag_Manip.h delete mode 100644 externals/ace/Flag_Manip.inl delete mode 100644 externals/ace/Framework_Component.cpp delete mode 100644 externals/ace/Framework_Component.h delete mode 100644 externals/ace/Framework_Component.inl delete mode 100644 externals/ace/Framework_Component_T.cpp delete mode 100644 externals/ace/Framework_Component_T.h delete mode 100644 externals/ace/Free_List.cpp delete mode 100644 externals/ace/Free_List.h delete mode 100644 externals/ace/Functor.cpp delete mode 100644 externals/ace/Functor.h delete mode 100644 externals/ace/Functor.inl delete mode 100644 externals/ace/Functor_String.cpp delete mode 100644 externals/ace/Functor_String.h delete mode 100644 externals/ace/Functor_String.inl delete mode 100644 externals/ace/Functor_T.cpp delete mode 100644 externals/ace/Functor_T.h delete mode 100644 externals/ace/Functor_T.inl delete mode 100644 externals/ace/Future.cpp delete mode 100644 externals/ace/Future.h delete mode 100644 externals/ace/Future_Set.cpp delete mode 100644 externals/ace/Future_Set.h delete mode 100644 externals/ace/Get_Opt.cpp delete mode 100644 externals/ace/Get_Opt.h delete mode 100644 externals/ace/Get_Opt.inl delete mode 100644 externals/ace/Global_Macros.h delete mode 100644 externals/ace/Guard_T.cpp delete mode 100644 externals/ace/Guard_T.h delete mode 100644 externals/ace/Guard_T.inl delete mode 100644 externals/ace/Handle_Gobbler.h delete mode 100644 externals/ace/Handle_Gobbler.inl delete mode 100644 externals/ace/Handle_Ops.cpp delete mode 100644 externals/ace/Handle_Ops.h delete mode 100644 externals/ace/Handle_Set.cpp delete mode 100644 externals/ace/Handle_Set.h delete mode 100644 externals/ace/Handle_Set.inl delete mode 100644 externals/ace/Hash_Cache_Map_Manager_T.cpp delete mode 100644 externals/ace/Hash_Cache_Map_Manager_T.h delete mode 100644 externals/ace/Hash_Cache_Map_Manager_T.inl delete mode 100644 externals/ace/Hash_Map_Manager.h delete mode 100644 externals/ace/Hash_Map_Manager_T.cpp delete mode 100644 externals/ace/Hash_Map_Manager_T.h delete mode 100644 externals/ace/Hash_Map_Manager_T.inl delete mode 100644 externals/ace/Hash_Map_With_Allocator_T.cpp delete mode 100644 externals/ace/Hash_Map_With_Allocator_T.h delete mode 100644 externals/ace/Hash_Map_With_Allocator_T.inl delete mode 100644 externals/ace/Hash_Multi_Map_Manager_T.cpp delete mode 100644 externals/ace/Hash_Multi_Map_Manager_T.h delete mode 100644 externals/ace/Hash_Multi_Map_Manager_T.inl delete mode 100644 externals/ace/Hashable.cpp delete mode 100644 externals/ace/Hashable.h delete mode 100644 externals/ace/Hashable.inl delete mode 100644 externals/ace/High_Res_Timer.cpp delete mode 100644 externals/ace/High_Res_Timer.h delete mode 100644 externals/ace/High_Res_Timer.inl delete mode 100644 externals/ace/ICMP_Socket.cpp delete mode 100644 externals/ace/ICMP_Socket.h delete mode 100644 externals/ace/INET_Addr.cpp delete mode 100644 externals/ace/INET_Addr.h delete mode 100644 externals/ace/INET_Addr.inl delete mode 100644 externals/ace/IOStream.cpp delete mode 100644 externals/ace/IOStream.h delete mode 100644 externals/ace/IOStream_T.cpp delete mode 100644 externals/ace/IOStream_T.h delete mode 100644 externals/ace/IOStream_T.inl delete mode 100644 externals/ace/IO_Cntl_Msg.cpp delete mode 100644 externals/ace/IO_Cntl_Msg.h delete mode 100644 externals/ace/IO_Cntl_Msg.inl delete mode 100644 externals/ace/IO_SAP.cpp delete mode 100644 externals/ace/IO_SAP.h delete mode 100644 externals/ace/IO_SAP.inl delete mode 100644 externals/ace/IPC_SAP.cpp delete mode 100644 externals/ace/IPC_SAP.h delete mode 100644 externals/ace/IPC_SAP.inl delete mode 100644 externals/ace/If_Then_Else.h delete mode 100644 externals/ace/Init_ACE.cpp delete mode 100644 externals/ace/Init_ACE.h delete mode 100644 externals/ace/Intrusive_Auto_Ptr.cpp delete mode 100644 externals/ace/Intrusive_Auto_Ptr.h delete mode 100644 externals/ace/Intrusive_Auto_Ptr.inl delete mode 100644 externals/ace/Intrusive_List.cpp delete mode 100644 externals/ace/Intrusive_List.h delete mode 100644 externals/ace/Intrusive_List.inl delete mode 100644 externals/ace/Intrusive_List_Node.cpp delete mode 100644 externals/ace/Intrusive_List_Node.h delete mode 100644 externals/ace/Intrusive_List_Node.inl delete mode 100644 externals/ace/LOCK_SOCK_Acceptor.cpp delete mode 100644 externals/ace/LOCK_SOCK_Acceptor.h delete mode 100644 externals/ace/LSOCK.cpp delete mode 100644 externals/ace/LSOCK.h delete mode 100644 externals/ace/LSOCK.inl delete mode 100644 externals/ace/LSOCK_Acceptor.cpp delete mode 100644 externals/ace/LSOCK_Acceptor.h delete mode 100644 externals/ace/LSOCK_CODgram.cpp delete mode 100644 externals/ace/LSOCK_CODgram.h delete mode 100644 externals/ace/LSOCK_CODgram.inl delete mode 100644 externals/ace/LSOCK_Connector.cpp delete mode 100644 externals/ace/LSOCK_Connector.h delete mode 100644 externals/ace/LSOCK_Connector.inl delete mode 100644 externals/ace/LSOCK_Dgram.cpp delete mode 100644 externals/ace/LSOCK_Dgram.h delete mode 100644 externals/ace/LSOCK_Dgram.inl delete mode 100644 externals/ace/LSOCK_Stream.cpp delete mode 100644 externals/ace/LSOCK_Stream.h delete mode 100644 externals/ace/LSOCK_Stream.inl delete mode 100644 externals/ace/Lib_Find.cpp delete mode 100644 externals/ace/Lib_Find.h delete mode 100644 externals/ace/Local_Memory_Pool.cpp delete mode 100644 externals/ace/Local_Memory_Pool.h delete mode 100644 externals/ace/Local_Name_Space.cpp delete mode 100644 externals/ace/Local_Name_Space.h delete mode 100644 externals/ace/Local_Name_Space_T.cpp delete mode 100644 externals/ace/Local_Name_Space_T.h delete mode 100644 externals/ace/Local_Tokens.cpp delete mode 100644 externals/ace/Local_Tokens.h delete mode 100644 externals/ace/Local_Tokens.inl delete mode 100644 externals/ace/Lock.cpp delete mode 100644 externals/ace/Lock.h delete mode 100644 externals/ace/Lock.inl delete mode 100644 externals/ace/Lock_Adapter_T.cpp delete mode 100644 externals/ace/Lock_Adapter_T.h delete mode 100644 externals/ace/Lock_Adapter_T.inl delete mode 100644 externals/ace/Log_Msg.cpp delete mode 100644 externals/ace/Log_Msg.h delete mode 100644 externals/ace/Log_Msg.inl delete mode 100644 externals/ace/Log_Msg_Backend.cpp delete mode 100644 externals/ace/Log_Msg_Backend.h delete mode 100644 externals/ace/Log_Msg_Callback.cpp delete mode 100644 externals/ace/Log_Msg_Callback.h delete mode 100644 externals/ace/Log_Msg_IPC.cpp delete mode 100644 externals/ace/Log_Msg_IPC.h delete mode 100644 externals/ace/Log_Msg_NT_Event_Log.cpp delete mode 100644 externals/ace/Log_Msg_NT_Event_Log.h delete mode 100644 externals/ace/Log_Msg_UNIX_Syslog.cpp delete mode 100644 externals/ace/Log_Msg_UNIX_Syslog.h delete mode 100644 externals/ace/Log_Priority.h delete mode 100644 externals/ace/Log_Record.cpp delete mode 100644 externals/ace/Log_Record.h delete mode 100644 externals/ace/Log_Record.inl delete mode 100644 externals/ace/Logging_Strategy.cpp delete mode 100644 externals/ace/Logging_Strategy.h delete mode 100644 externals/ace/MEM_Acceptor.cpp delete mode 100644 externals/ace/MEM_Acceptor.h delete mode 100644 externals/ace/MEM_Acceptor.inl delete mode 100644 externals/ace/MEM_Addr.cpp delete mode 100644 externals/ace/MEM_Addr.h delete mode 100644 externals/ace/MEM_Addr.inl delete mode 100644 externals/ace/MEM_Connector.cpp delete mode 100644 externals/ace/MEM_Connector.h delete mode 100644 externals/ace/MEM_Connector.inl delete mode 100644 externals/ace/MEM_IO.cpp delete mode 100644 externals/ace/MEM_IO.h delete mode 100644 externals/ace/MEM_IO.inl delete mode 100644 externals/ace/MEM_SAP.cpp delete mode 100644 externals/ace/MEM_SAP.h delete mode 100644 externals/ace/MEM_SAP.inl delete mode 100644 externals/ace/MEM_Stream.cpp delete mode 100644 externals/ace/MEM_Stream.h delete mode 100644 externals/ace/MEM_Stream.inl delete mode 100644 externals/ace/MMAP_Memory_Pool.cpp delete mode 100644 externals/ace/MMAP_Memory_Pool.h delete mode 100644 externals/ace/MMAP_Memory_Pool.inl delete mode 100644 externals/ace/Makefile.in delete mode 100644 externals/ace/Malloc.cpp delete mode 100644 externals/ace/Malloc.h delete mode 100644 externals/ace/Malloc.inl delete mode 100644 externals/ace/Malloc_Allocator.cpp delete mode 100644 externals/ace/Malloc_Allocator.h delete mode 100644 externals/ace/Malloc_Allocator.inl delete mode 100644 externals/ace/Malloc_Base.h delete mode 100644 externals/ace/Malloc_T.cpp delete mode 100644 externals/ace/Malloc_T.h delete mode 100644 externals/ace/Malloc_T.inl delete mode 100644 externals/ace/Managed_Object.cpp delete mode 100644 externals/ace/Managed_Object.h delete mode 100644 externals/ace/Managed_Object.inl delete mode 100644 externals/ace/Manual_Event.cpp delete mode 100644 externals/ace/Manual_Event.h delete mode 100644 externals/ace/Manual_Event.inl delete mode 100644 externals/ace/Map.h delete mode 100644 externals/ace/Map_Manager.cpp delete mode 100644 externals/ace/Map_Manager.h delete mode 100644 externals/ace/Map_Manager.inl delete mode 100644 externals/ace/Map_T.cpp delete mode 100644 externals/ace/Map_T.h delete mode 100644 externals/ace/Map_T.inl delete mode 100644 externals/ace/Mem_Map.cpp delete mode 100644 externals/ace/Mem_Map.h delete mode 100644 externals/ace/Mem_Map.inl delete mode 100644 externals/ace/Memory_Pool.h delete mode 100644 externals/ace/Message_Block.cpp delete mode 100644 externals/ace/Message_Block.h delete mode 100644 externals/ace/Message_Block.inl delete mode 100644 externals/ace/Message_Block_T.cpp delete mode 100644 externals/ace/Message_Block_T.h delete mode 100644 externals/ace/Message_Block_T.inl delete mode 100644 externals/ace/Message_Queue.cpp delete mode 100644 externals/ace/Message_Queue.h delete mode 100644 externals/ace/Message_Queue.inl delete mode 100644 externals/ace/Message_Queue_NT.cpp delete mode 100644 externals/ace/Message_Queue_NT.h delete mode 100644 externals/ace/Message_Queue_NT.inl delete mode 100644 externals/ace/Message_Queue_T.cpp delete mode 100644 externals/ace/Message_Queue_T.h delete mode 100644 externals/ace/Message_Queue_Vx.cpp delete mode 100644 externals/ace/Message_Queue_Vx.h delete mode 100644 externals/ace/Message_Queue_Vx.inl delete mode 100644 externals/ace/Method_Object.h delete mode 100644 externals/ace/Method_Request.cpp delete mode 100644 externals/ace/Method_Request.h delete mode 100644 externals/ace/Metrics_Cache.h delete mode 100644 externals/ace/Metrics_Cache_T.cpp delete mode 100644 externals/ace/Metrics_Cache_T.h delete mode 100644 externals/ace/Metrics_Cache_T.inl delete mode 100644 externals/ace/Min_Max.h delete mode 100644 externals/ace/Module.cpp delete mode 100644 externals/ace/Module.h delete mode 100644 externals/ace/Module.inl delete mode 100644 externals/ace/Monitor_Admin.cpp delete mode 100644 externals/ace/Monitor_Admin.h delete mode 100644 externals/ace/Monitor_Admin_Manager.cpp delete mode 100644 externals/ace/Monitor_Admin_Manager.h delete mode 100644 externals/ace/Monitor_Base.cpp delete mode 100644 externals/ace/Monitor_Base.h delete mode 100644 externals/ace/Monitor_Base.inl delete mode 100644 externals/ace/Monitor_Control_Action.cpp delete mode 100644 externals/ace/Monitor_Control_Action.h delete mode 100644 externals/ace/Monitor_Control_Types.cpp delete mode 100644 externals/ace/Monitor_Control_Types.h delete mode 100644 externals/ace/Monitor_Point_Registry.cpp delete mode 100644 externals/ace/Monitor_Point_Registry.h delete mode 100644 externals/ace/Monitor_Size.cpp delete mode 100644 externals/ace/Monitor_Size.h delete mode 100644 externals/ace/Msg_WFMO_Reactor.cpp delete mode 100644 externals/ace/Msg_WFMO_Reactor.h delete mode 100644 externals/ace/Msg_WFMO_Reactor.inl delete mode 100644 externals/ace/Multihomed_INET_Addr.cpp delete mode 100644 externals/ace/Multihomed_INET_Addr.h delete mode 100644 externals/ace/Multihomed_INET_Addr.inl delete mode 100644 externals/ace/Mutex.cpp delete mode 100644 externals/ace/Mutex.h delete mode 100644 externals/ace/Mutex.inl delete mode 100644 externals/ace/NT_Service.cpp delete mode 100644 externals/ace/NT_Service.h delete mode 100644 externals/ace/NT_Service.inl delete mode 100644 externals/ace/Name_Proxy.cpp delete mode 100644 externals/ace/Name_Proxy.h delete mode 100644 externals/ace/Name_Request_Reply.cpp delete mode 100644 externals/ace/Name_Request_Reply.h delete mode 100644 externals/ace/Name_Space.cpp delete mode 100644 externals/ace/Name_Space.h delete mode 100644 externals/ace/Naming_Context.cpp delete mode 100644 externals/ace/Naming_Context.h delete mode 100644 externals/ace/Naming_Context.inl delete mode 100644 externals/ace/Netlink_Addr.cpp delete mode 100644 externals/ace/Netlink_Addr.h delete mode 100644 externals/ace/Netlink_Addr.inl delete mode 100644 externals/ace/Node.cpp delete mode 100644 externals/ace/Node.h delete mode 100644 externals/ace/Notification_Queue.cpp delete mode 100644 externals/ace/Notification_Queue.h delete mode 100644 externals/ace/Notification_Queue.inl delete mode 100644 externals/ace/Notification_Strategy.cpp delete mode 100644 externals/ace/Notification_Strategy.h delete mode 100644 externals/ace/Notification_Strategy.inl delete mode 100644 externals/ace/Null_Barrier.h delete mode 100644 externals/ace/Null_Condition.h delete mode 100644 externals/ace/Null_Mutex.h delete mode 100644 externals/ace/Null_Semaphore.h delete mode 100644 externals/ace/Numeric_Limits.h delete mode 100644 externals/ace/OS.cpp delete mode 100644 externals/ace/OS.h delete mode 100644 externals/ace/OS.inl delete mode 100644 externals/ace/OS_Dirent.h delete mode 100644 externals/ace/OS_Errno.cpp delete mode 100644 externals/ace/OS_Errno.h delete mode 100644 externals/ace/OS_Errno.inl delete mode 100644 externals/ace/OS_Log_Msg_Attributes.cpp delete mode 100644 externals/ace/OS_Log_Msg_Attributes.h delete mode 100644 externals/ace/OS_Log_Msg_Attributes.inl delete mode 100644 externals/ace/OS_Memory.h delete mode 100644 externals/ace/OS_NS_Thread.cpp delete mode 100644 externals/ace/OS_NS_Thread.h delete mode 100644 externals/ace/OS_NS_Thread.inl delete mode 100644 externals/ace/OS_NS_arpa_inet.cpp delete mode 100644 externals/ace/OS_NS_arpa_inet.h delete mode 100644 externals/ace/OS_NS_arpa_inet.inl delete mode 100644 externals/ace/OS_NS_ctype.cpp delete mode 100644 externals/ace/OS_NS_ctype.h delete mode 100644 externals/ace/OS_NS_ctype.inl delete mode 100644 externals/ace/OS_NS_dirent.cpp delete mode 100644 externals/ace/OS_NS_dirent.h delete mode 100644 externals/ace/OS_NS_dirent.inl delete mode 100644 externals/ace/OS_NS_dlfcn.cpp delete mode 100644 externals/ace/OS_NS_dlfcn.h delete mode 100644 externals/ace/OS_NS_dlfcn.inl delete mode 100644 externals/ace/OS_NS_errno.cpp delete mode 100644 externals/ace/OS_NS_errno.h delete mode 100644 externals/ace/OS_NS_errno.inl delete mode 100644 externals/ace/OS_NS_fcntl.cpp delete mode 100644 externals/ace/OS_NS_fcntl.h delete mode 100644 externals/ace/OS_NS_fcntl.inl delete mode 100644 externals/ace/OS_NS_macros.h delete mode 100644 externals/ace/OS_NS_math.cpp delete mode 100644 externals/ace/OS_NS_math.h delete mode 100644 externals/ace/OS_NS_math.inl delete mode 100644 externals/ace/OS_NS_netdb.cpp delete mode 100644 externals/ace/OS_NS_netdb.h delete mode 100644 externals/ace/OS_NS_netdb.inl delete mode 100644 externals/ace/OS_NS_poll.cpp delete mode 100644 externals/ace/OS_NS_poll.h delete mode 100644 externals/ace/OS_NS_poll.inl delete mode 100644 externals/ace/OS_NS_pwd.cpp delete mode 100644 externals/ace/OS_NS_pwd.h delete mode 100644 externals/ace/OS_NS_pwd.inl delete mode 100644 externals/ace/OS_NS_regex.cpp delete mode 100644 externals/ace/OS_NS_regex.h delete mode 100644 externals/ace/OS_NS_regex.inl delete mode 100644 externals/ace/OS_NS_signal.cpp delete mode 100644 externals/ace/OS_NS_signal.h delete mode 100644 externals/ace/OS_NS_signal.inl delete mode 100644 externals/ace/OS_NS_stdio.cpp delete mode 100644 externals/ace/OS_NS_stdio.h delete mode 100644 externals/ace/OS_NS_stdio.inl delete mode 100644 externals/ace/OS_NS_stdlib.cpp delete mode 100644 externals/ace/OS_NS_stdlib.h delete mode 100644 externals/ace/OS_NS_stdlib.inl delete mode 100644 externals/ace/OS_NS_string.cpp delete mode 100644 externals/ace/OS_NS_string.h delete mode 100644 externals/ace/OS_NS_string.inl delete mode 100644 externals/ace/OS_NS_strings.cpp delete mode 100644 externals/ace/OS_NS_strings.h delete mode 100644 externals/ace/OS_NS_strings.inl delete mode 100644 externals/ace/OS_NS_stropts.cpp delete mode 100644 externals/ace/OS_NS_stropts.h delete mode 100644 externals/ace/OS_NS_stropts.inl delete mode 100644 externals/ace/OS_NS_sys_mman.cpp delete mode 100644 externals/ace/OS_NS_sys_mman.h delete mode 100644 externals/ace/OS_NS_sys_mman.inl delete mode 100644 externals/ace/OS_NS_sys_msg.cpp delete mode 100644 externals/ace/OS_NS_sys_msg.h delete mode 100644 externals/ace/OS_NS_sys_msg.inl delete mode 100644 externals/ace/OS_NS_sys_resource.cpp delete mode 100644 externals/ace/OS_NS_sys_resource.h delete mode 100644 externals/ace/OS_NS_sys_resource.inl delete mode 100644 externals/ace/OS_NS_sys_select.cpp delete mode 100644 externals/ace/OS_NS_sys_select.h delete mode 100644 externals/ace/OS_NS_sys_select.inl delete mode 100644 externals/ace/OS_NS_sys_sendfile.cpp delete mode 100644 externals/ace/OS_NS_sys_sendfile.h delete mode 100644 externals/ace/OS_NS_sys_sendfile.inl delete mode 100644 externals/ace/OS_NS_sys_shm.cpp delete mode 100644 externals/ace/OS_NS_sys_shm.h delete mode 100644 externals/ace/OS_NS_sys_shm.inl delete mode 100644 externals/ace/OS_NS_sys_socket.cpp delete mode 100644 externals/ace/OS_NS_sys_socket.h delete mode 100644 externals/ace/OS_NS_sys_socket.inl delete mode 100644 externals/ace/OS_NS_sys_stat.cpp delete mode 100644 externals/ace/OS_NS_sys_stat.h delete mode 100644 externals/ace/OS_NS_sys_stat.inl delete mode 100644 externals/ace/OS_NS_sys_time.cpp delete mode 100644 externals/ace/OS_NS_sys_time.h delete mode 100644 externals/ace/OS_NS_sys_time.inl delete mode 100644 externals/ace/OS_NS_sys_uio.cpp delete mode 100644 externals/ace/OS_NS_sys_uio.h delete mode 100644 externals/ace/OS_NS_sys_uio.inl delete mode 100644 externals/ace/OS_NS_sys_utsname.cpp delete mode 100644 externals/ace/OS_NS_sys_utsname.h delete mode 100644 externals/ace/OS_NS_sys_wait.cpp delete mode 100644 externals/ace/OS_NS_sys_wait.h delete mode 100644 externals/ace/OS_NS_sys_wait.inl delete mode 100644 externals/ace/OS_NS_time.cpp delete mode 100644 externals/ace/OS_NS_time.h delete mode 100644 externals/ace/OS_NS_time.inl delete mode 100644 externals/ace/OS_NS_unistd.cpp delete mode 100644 externals/ace/OS_NS_unistd.h delete mode 100644 externals/ace/OS_NS_unistd.inl delete mode 100644 externals/ace/OS_NS_wchar.cpp delete mode 100644 externals/ace/OS_NS_wchar.h delete mode 100644 externals/ace/OS_NS_wchar.inl delete mode 100644 externals/ace/OS_NS_wctype.cpp delete mode 100644 externals/ace/OS_NS_wctype.h delete mode 100644 externals/ace/OS_NS_wctype.inl delete mode 100644 externals/ace/OS_QoS.cpp delete mode 100644 externals/ace/OS_QoS.h delete mode 100644 externals/ace/OS_String.h delete mode 100644 externals/ace/OS_TLI.cpp delete mode 100644 externals/ace/OS_TLI.h delete mode 100644 externals/ace/OS_TLI.inl delete mode 100644 externals/ace/OS_Thread_Adapter.cpp delete mode 100644 externals/ace/OS_Thread_Adapter.h delete mode 100644 externals/ace/OS_main.cpp delete mode 100644 externals/ace/OS_main.h delete mode 100644 externals/ace/Obchunk.cpp delete mode 100644 externals/ace/Obchunk.h delete mode 100644 externals/ace/Obchunk.inl delete mode 100644 externals/ace/Object_Manager.cpp delete mode 100644 externals/ace/Object_Manager.h delete mode 100644 externals/ace/Object_Manager.inl delete mode 100644 externals/ace/Object_Manager_Base.cpp delete mode 100644 externals/ace/Object_Manager_Base.h delete mode 100644 externals/ace/Obstack.h delete mode 100644 externals/ace/Obstack_T.cpp delete mode 100644 externals/ace/Obstack_T.h delete mode 100644 externals/ace/Obstack_T.inl delete mode 100644 externals/ace/PI_Malloc.cpp delete mode 100644 externals/ace/PI_Malloc.h delete mode 100644 externals/ace/PI_Malloc.inl delete mode 100644 externals/ace/POSIX_Asynch_IO.cpp delete mode 100644 externals/ace/POSIX_Asynch_IO.h delete mode 100644 externals/ace/POSIX_CB_Proactor.cpp delete mode 100644 externals/ace/POSIX_CB_Proactor.h delete mode 100644 externals/ace/POSIX_Proactor.cpp delete mode 100644 externals/ace/POSIX_Proactor.h delete mode 100644 externals/ace/POSIX_Proactor.inl delete mode 100644 externals/ace/Pagefile_Memory_Pool.cpp delete mode 100644 externals/ace/Pagefile_Memory_Pool.h delete mode 100644 externals/ace/Pagefile_Memory_Pool.inl delete mode 100644 externals/ace/Pair.h delete mode 100644 externals/ace/Pair_T.cpp delete mode 100644 externals/ace/Pair_T.h delete mode 100644 externals/ace/Pair_T.inl delete mode 100644 externals/ace/Parse_Node.cpp delete mode 100644 externals/ace/Parse_Node.h delete mode 100644 externals/ace/Ping_Socket.cpp delete mode 100644 externals/ace/Ping_Socket.h delete mode 100644 externals/ace/Ping_Socket.inl delete mode 100644 externals/ace/Pipe.cpp delete mode 100644 externals/ace/Pipe.h delete mode 100644 externals/ace/Pipe.inl delete mode 100644 externals/ace/PrecompiledHeaders/WinAcePCH.cpp delete mode 100644 externals/ace/PrecompiledHeaders/WinAcePCH.h delete mode 100644 externals/ace/Priority_Reactor.cpp delete mode 100644 externals/ace/Priority_Reactor.h delete mode 100644 externals/ace/Proactor.cpp delete mode 100644 externals/ace/Proactor.h delete mode 100644 externals/ace/Proactor.inl delete mode 100644 externals/ace/Proactor_Impl.cpp delete mode 100644 externals/ace/Proactor_Impl.h delete mode 100644 externals/ace/Process.cpp delete mode 100644 externals/ace/Process.h delete mode 100644 externals/ace/Process.inl delete mode 100644 externals/ace/Process_Manager.cpp delete mode 100644 externals/ace/Process_Manager.h delete mode 100644 externals/ace/Process_Manager.inl delete mode 100644 externals/ace/Process_Mutex.cpp delete mode 100644 externals/ace/Process_Mutex.h delete mode 100644 externals/ace/Process_Mutex.inl delete mode 100644 externals/ace/Process_Semaphore.cpp delete mode 100644 externals/ace/Process_Semaphore.h delete mode 100644 externals/ace/Process_Semaphore.inl delete mode 100644 externals/ace/Profile_Timer.cpp delete mode 100644 externals/ace/Profile_Timer.h delete mode 100644 externals/ace/Profile_Timer.inl delete mode 100644 externals/ace/QoS/ACE_QoS_Export.h delete mode 100644 externals/ace/QoS/QoS_Decorator.cpp delete mode 100644 externals/ace/QoS/QoS_Decorator.h delete mode 100644 externals/ace/QoS/QoS_Manager.cpp delete mode 100644 externals/ace/QoS/QoS_Manager.h delete mode 100644 externals/ace/QoS/QoS_Session.h delete mode 100644 externals/ace/QoS/QoS_Session_Factory.cpp delete mode 100644 externals/ace/QoS/QoS_Session_Factory.h delete mode 100644 externals/ace/QoS/QoS_Session_Impl.cpp delete mode 100644 externals/ace/QoS/QoS_Session_Impl.h delete mode 100644 externals/ace/QoS/QoS_Session_Impl.inl delete mode 100644 externals/ace/QoS/README delete mode 100644 externals/ace/QoS/SOCK_Dgram_Mcast_QoS.cpp delete mode 100644 externals/ace/QoS/SOCK_Dgram_Mcast_QoS.h delete mode 100644 externals/ace/QoS/SOCK_Dgram_Mcast_QoS.inl delete mode 100644 externals/ace/RB_Tree.cpp delete mode 100644 externals/ace/RB_Tree.h delete mode 100644 externals/ace/RB_Tree.inl delete mode 100644 externals/ace/README delete mode 100644 externals/ace/RW_Mutex.cpp delete mode 100644 externals/ace/RW_Mutex.h delete mode 100644 externals/ace/RW_Mutex.inl delete mode 100644 externals/ace/RW_Process_Mutex.cpp delete mode 100644 externals/ace/RW_Process_Mutex.h delete mode 100644 externals/ace/RW_Process_Mutex.inl delete mode 100644 externals/ace/RW_Thread_Mutex.cpp delete mode 100644 externals/ace/RW_Thread_Mutex.h delete mode 100644 externals/ace/RW_Thread_Mutex.inl delete mode 100644 externals/ace/Reactor.cpp delete mode 100644 externals/ace/Reactor.h delete mode 100644 externals/ace/Reactor.inl delete mode 100644 externals/ace/Reactor_Impl.cpp delete mode 100644 externals/ace/Reactor_Impl.h delete mode 100644 externals/ace/Reactor_Notification_Strategy.cpp delete mode 100644 externals/ace/Reactor_Notification_Strategy.h delete mode 100644 externals/ace/Reactor_Notification_Strategy.inl delete mode 100644 externals/ace/Reactor_Timer_Interface.cpp delete mode 100644 externals/ace/Reactor_Timer_Interface.h delete mode 100644 externals/ace/Reactor_Token_T.cpp delete mode 100644 externals/ace/Reactor_Token_T.h delete mode 100644 externals/ace/Read_Buffer.cpp delete mode 100644 externals/ace/Read_Buffer.h delete mode 100644 externals/ace/Read_Buffer.inl delete mode 100644 externals/ace/Recursive_Thread_Mutex.cpp delete mode 100644 externals/ace/Recursive_Thread_Mutex.h delete mode 100644 externals/ace/Recursive_Thread_Mutex.inl delete mode 100644 externals/ace/Recyclable.cpp delete mode 100644 externals/ace/Recyclable.h delete mode 100644 externals/ace/Recyclable.inl delete mode 100644 externals/ace/Refcountable.h delete mode 100644 externals/ace/Refcountable_T.cpp delete mode 100644 externals/ace/Refcountable_T.h delete mode 100644 externals/ace/Refcountable_T.inl delete mode 100644 externals/ace/Refcounted_Auto_Ptr.cpp delete mode 100644 externals/ace/Refcounted_Auto_Ptr.h delete mode 100644 externals/ace/Refcounted_Auto_Ptr.inl delete mode 100644 externals/ace/Registry.cpp delete mode 100644 externals/ace/Registry.h delete mode 100644 externals/ace/Registry_Name_Space.cpp delete mode 100644 externals/ace/Registry_Name_Space.h delete mode 100644 externals/ace/Remote_Name_Space.cpp delete mode 100644 externals/ace/Remote_Name_Space.h delete mode 100644 externals/ace/Remote_Tokens.cpp delete mode 100644 externals/ace/Remote_Tokens.h delete mode 100644 externals/ace/Remote_Tokens.inl delete mode 100644 externals/ace/Reverse_Lock_T.cpp delete mode 100644 externals/ace/Reverse_Lock_T.h delete mode 100644 externals/ace/Reverse_Lock_T.inl delete mode 100644 externals/ace/Rtems_init.c delete mode 100644 externals/ace/SOCK.cpp delete mode 100644 externals/ace/SOCK.h delete mode 100644 externals/ace/SOCK.inl delete mode 100644 externals/ace/SOCK_Acceptor.cpp delete mode 100644 externals/ace/SOCK_Acceptor.h delete mode 100644 externals/ace/SOCK_Acceptor.inl delete mode 100644 externals/ace/SOCK_CODgram.cpp delete mode 100644 externals/ace/SOCK_CODgram.h delete mode 100644 externals/ace/SOCK_CODgram.inl delete mode 100644 externals/ace/SOCK_Connector.cpp delete mode 100644 externals/ace/SOCK_Connector.h delete mode 100644 externals/ace/SOCK_Connector.inl delete mode 100644 externals/ace/SOCK_Dgram.cpp delete mode 100644 externals/ace/SOCK_Dgram.h delete mode 100644 externals/ace/SOCK_Dgram.inl delete mode 100644 externals/ace/SOCK_Dgram_Bcast.cpp delete mode 100644 externals/ace/SOCK_Dgram_Bcast.h delete mode 100644 externals/ace/SOCK_Dgram_Bcast.inl delete mode 100644 externals/ace/SOCK_Dgram_Mcast.cpp delete mode 100644 externals/ace/SOCK_Dgram_Mcast.h delete mode 100644 externals/ace/SOCK_Dgram_Mcast.inl delete mode 100644 externals/ace/SOCK_IO.cpp delete mode 100644 externals/ace/SOCK_IO.h delete mode 100644 externals/ace/SOCK_IO.inl delete mode 100644 externals/ace/SOCK_Netlink.cpp delete mode 100644 externals/ace/SOCK_Netlink.h delete mode 100644 externals/ace/SOCK_Netlink.inl delete mode 100644 externals/ace/SOCK_SEQPACK_Acceptor.cpp delete mode 100644 externals/ace/SOCK_SEQPACK_Acceptor.h delete mode 100644 externals/ace/SOCK_SEQPACK_Acceptor.inl delete mode 100644 externals/ace/SOCK_SEQPACK_Association.cpp delete mode 100644 externals/ace/SOCK_SEQPACK_Association.h delete mode 100644 externals/ace/SOCK_SEQPACK_Association.inl delete mode 100644 externals/ace/SOCK_SEQPACK_Connector.cpp delete mode 100644 externals/ace/SOCK_SEQPACK_Connector.h delete mode 100644 externals/ace/SOCK_SEQPACK_Connector.inl delete mode 100644 externals/ace/SOCK_Stream.cpp delete mode 100644 externals/ace/SOCK_Stream.h delete mode 100644 externals/ace/SOCK_Stream.inl delete mode 100644 externals/ace/SPIPE.cpp delete mode 100644 externals/ace/SPIPE.h delete mode 100644 externals/ace/SPIPE.inl delete mode 100644 externals/ace/SPIPE_Acceptor.cpp delete mode 100644 externals/ace/SPIPE_Acceptor.h delete mode 100644 externals/ace/SPIPE_Addr.cpp delete mode 100644 externals/ace/SPIPE_Addr.h delete mode 100644 externals/ace/SPIPE_Addr.inl delete mode 100644 externals/ace/SPIPE_Connector.cpp delete mode 100644 externals/ace/SPIPE_Connector.h delete mode 100644 externals/ace/SPIPE_Connector.inl delete mode 100644 externals/ace/SPIPE_Stream.cpp delete mode 100644 externals/ace/SPIPE_Stream.h delete mode 100644 externals/ace/SPIPE_Stream.inl delete mode 100644 externals/ace/SSL/SSL_Asynch_BIO.cpp delete mode 100644 externals/ace/SSL/SSL_Asynch_BIO.h delete mode 100644 externals/ace/SSL/SSL_Asynch_Stream.cpp delete mode 100644 externals/ace/SSL/SSL_Asynch_Stream.h delete mode 100644 externals/ace/SSL/SSL_Asynch_Stream.inl delete mode 100644 externals/ace/SSL/SSL_Context.cpp delete mode 100644 externals/ace/SSL/SSL_Context.h delete mode 100644 externals/ace/SSL/SSL_Context.inl delete mode 100644 externals/ace/SSL/SSL_Export.h delete mode 100644 externals/ace/SSL/SSL_SOCK.cpp delete mode 100644 externals/ace/SSL/SSL_SOCK.h delete mode 100644 externals/ace/SSL/SSL_SOCK.inl delete mode 100644 externals/ace/SSL/SSL_SOCK_Acceptor.cpp delete mode 100644 externals/ace/SSL/SSL_SOCK_Acceptor.h delete mode 100644 externals/ace/SSL/SSL_SOCK_Acceptor.inl delete mode 100644 externals/ace/SSL/SSL_SOCK_Connector.cpp delete mode 100644 externals/ace/SSL/SSL_SOCK_Connector.h delete mode 100644 externals/ace/SSL/SSL_SOCK_Connector.inl delete mode 100644 externals/ace/SSL/SSL_SOCK_Stream.cpp delete mode 100644 externals/ace/SSL/SSL_SOCK_Stream.h delete mode 100644 externals/ace/SSL/SSL_SOCK_Stream.inl delete mode 100644 externals/ace/SSL/sslconf.h delete mode 100644 externals/ace/SString.cpp delete mode 100644 externals/ace/SString.h delete mode 100644 externals/ace/SString.inl delete mode 100644 externals/ace/SStringfwd.h delete mode 100644 externals/ace/SUN_Proactor.cpp delete mode 100644 externals/ace/SUN_Proactor.h delete mode 100644 externals/ace/SV_Message.cpp delete mode 100644 externals/ace/SV_Message.h delete mode 100644 externals/ace/SV_Message.inl delete mode 100644 externals/ace/SV_Message_Queue.cpp delete mode 100644 externals/ace/SV_Message_Queue.h delete mode 100644 externals/ace/SV_Message_Queue.inl delete mode 100644 externals/ace/SV_Semaphore_Complex.cpp delete mode 100644 externals/ace/SV_Semaphore_Complex.h delete mode 100644 externals/ace/SV_Semaphore_Complex.inl delete mode 100644 externals/ace/SV_Semaphore_Simple.cpp delete mode 100644 externals/ace/SV_Semaphore_Simple.h delete mode 100644 externals/ace/SV_Semaphore_Simple.inl delete mode 100644 externals/ace/SV_Shared_Memory.cpp delete mode 100644 externals/ace/SV_Shared_Memory.h delete mode 100644 externals/ace/SV_Shared_Memory.inl delete mode 100644 externals/ace/Sample_History.cpp delete mode 100644 externals/ace/Sample_History.h delete mode 100644 externals/ace/Sample_History.inl delete mode 100644 externals/ace/Sbrk_Memory_Pool.cpp delete mode 100644 externals/ace/Sbrk_Memory_Pool.h delete mode 100644 externals/ace/Sched_Params.cpp delete mode 100644 externals/ace/Sched_Params.h delete mode 100644 externals/ace/Sched_Params.inl delete mode 100644 externals/ace/Select_Reactor.h delete mode 100644 externals/ace/Select_Reactor_Base.cpp delete mode 100644 externals/ace/Select_Reactor_Base.h delete mode 100644 externals/ace/Select_Reactor_Base.inl delete mode 100644 externals/ace/Select_Reactor_T.cpp delete mode 100644 externals/ace/Select_Reactor_T.h delete mode 100644 externals/ace/Select_Reactor_T.inl delete mode 100644 externals/ace/Semaphore.cpp delete mode 100644 externals/ace/Semaphore.h delete mode 100644 externals/ace/Semaphore.inl delete mode 100644 externals/ace/Service_Config.cpp delete mode 100644 externals/ace/Service_Config.h delete mode 100644 externals/ace/Service_Config.inl delete mode 100644 externals/ace/Service_Gestalt.cpp delete mode 100644 externals/ace/Service_Gestalt.h delete mode 100644 externals/ace/Service_Gestalt.inl delete mode 100644 externals/ace/Service_Manager.cpp delete mode 100644 externals/ace/Service_Manager.h delete mode 100644 externals/ace/Service_Object.cpp delete mode 100644 externals/ace/Service_Object.h delete mode 100644 externals/ace/Service_Object.inl delete mode 100644 externals/ace/Service_Repository.cpp delete mode 100644 externals/ace/Service_Repository.h delete mode 100644 externals/ace/Service_Repository.inl delete mode 100644 externals/ace/Service_Templates.h delete mode 100644 externals/ace/Service_Types.cpp delete mode 100644 externals/ace/Service_Types.h delete mode 100644 externals/ace/Service_Types.inl delete mode 100644 externals/ace/Shared_Memory.cpp delete mode 100644 externals/ace/Shared_Memory.h delete mode 100644 externals/ace/Shared_Memory_MM.cpp delete mode 100644 externals/ace/Shared_Memory_MM.h delete mode 100644 externals/ace/Shared_Memory_MM.inl delete mode 100644 externals/ace/Shared_Memory_Pool.cpp delete mode 100644 externals/ace/Shared_Memory_Pool.h delete mode 100644 externals/ace/Shared_Memory_SV.cpp delete mode 100644 externals/ace/Shared_Memory_SV.h delete mode 100644 externals/ace/Shared_Memory_SV.inl delete mode 100644 externals/ace/Shared_Object.cpp delete mode 100644 externals/ace/Shared_Object.h delete mode 100644 externals/ace/Shared_Object.inl delete mode 100644 externals/ace/Sig_Adapter.cpp delete mode 100644 externals/ace/Sig_Adapter.h delete mode 100644 externals/ace/Sig_Handler.cpp delete mode 100644 externals/ace/Sig_Handler.h delete mode 100644 externals/ace/Sig_Handler.inl delete mode 100644 externals/ace/Signal.cpp delete mode 100644 externals/ace/Signal.h delete mode 100644 externals/ace/Signal.inl delete mode 100644 externals/ace/Singleton.cpp delete mode 100644 externals/ace/Singleton.h delete mode 100644 externals/ace/Singleton.inl delete mode 100644 externals/ace/Sock_Connect.cpp delete mode 100644 externals/ace/Sock_Connect.h delete mode 100644 externals/ace/Stack_Trace.cpp delete mode 100644 externals/ace/Stack_Trace.h delete mode 100644 externals/ace/Static_Object_Lock.h delete mode 100644 externals/ace/Stats.cpp delete mode 100644 externals/ace/Stats.h delete mode 100644 externals/ace/Stats.inl delete mode 100644 externals/ace/Strategies.h delete mode 100644 externals/ace/Strategies_T.cpp delete mode 100644 externals/ace/Strategies_T.h delete mode 100644 externals/ace/Strategies_T.inl delete mode 100644 externals/ace/Stream.cpp delete mode 100644 externals/ace/Stream.h delete mode 100644 externals/ace/Stream.inl delete mode 100644 externals/ace/Stream_Modules.cpp delete mode 100644 externals/ace/Stream_Modules.h delete mode 100644 externals/ace/String_Base.cpp delete mode 100644 externals/ace/String_Base.h delete mode 100644 externals/ace/String_Base.inl delete mode 100644 externals/ace/String_Base_Const.cpp delete mode 100644 externals/ace/String_Base_Const.h delete mode 100644 externals/ace/Svc_Conf.h delete mode 100644 externals/ace/Svc_Conf.y delete mode 100644 externals/ace/Svc_Conf_Lexer.cpp delete mode 100644 externals/ace/Svc_Conf_Lexer.h delete mode 100644 externals/ace/Svc_Conf_Param.h delete mode 100644 externals/ace/Svc_Conf_Token_Table.h delete mode 100644 externals/ace/Svc_Conf_Tokens.h delete mode 100644 externals/ace/Svc_Conf_y.cpp delete mode 100644 externals/ace/Svc_Handler.cpp delete mode 100644 externals/ace/Svc_Handler.h delete mode 100644 externals/ace/Synch.h delete mode 100644 externals/ace/Synch_Options.cpp delete mode 100644 externals/ace/Synch_Options.h delete mode 100644 externals/ace/Synch_T.cpp delete mode 100644 externals/ace/Synch_T.h delete mode 100644 externals/ace/Synch_Traits.h delete mode 100644 externals/ace/System_Time.cpp delete mode 100644 externals/ace/System_Time.h delete mode 100644 externals/ace/TLI.cpp delete mode 100644 externals/ace/TLI.h delete mode 100644 externals/ace/TLI.inl delete mode 100644 externals/ace/TLI_Acceptor.cpp delete mode 100644 externals/ace/TLI_Acceptor.h delete mode 100644 externals/ace/TLI_Connector.cpp delete mode 100644 externals/ace/TLI_Connector.h delete mode 100644 externals/ace/TLI_Connector.inl delete mode 100644 externals/ace/TLI_Stream.cpp delete mode 100644 externals/ace/TLI_Stream.h delete mode 100644 externals/ace/TLI_Stream.inl delete mode 100644 externals/ace/TP_Reactor.cpp delete mode 100644 externals/ace/TP_Reactor.h delete mode 100644 externals/ace/TP_Reactor.inl delete mode 100644 externals/ace/TSS_Adapter.cpp delete mode 100644 externals/ace/TSS_Adapter.h delete mode 100644 externals/ace/TSS_T.cpp delete mode 100644 externals/ace/TSS_T.h delete mode 100644 externals/ace/TSS_T.inl delete mode 100644 externals/ace/TTY_IO.cpp delete mode 100644 externals/ace/TTY_IO.h delete mode 100644 externals/ace/Task.cpp delete mode 100644 externals/ace/Task.h delete mode 100644 externals/ace/Task.inl delete mode 100644 externals/ace/Task_Ex_T.cpp delete mode 100644 externals/ace/Task_Ex_T.h delete mode 100644 externals/ace/Task_Ex_T.inl delete mode 100644 externals/ace/Task_T.cpp delete mode 100644 externals/ace/Task_T.h delete mode 100644 externals/ace/Task_T.inl delete mode 100644 externals/ace/Test_and_Set.cpp delete mode 100644 externals/ace/Test_and_Set.h delete mode 100644 externals/ace/Thread.cpp delete mode 100644 externals/ace/Thread.h delete mode 100644 externals/ace/Thread.inl delete mode 100644 externals/ace/Thread_Adapter.cpp delete mode 100644 externals/ace/Thread_Adapter.h delete mode 100644 externals/ace/Thread_Adapter.inl delete mode 100644 externals/ace/Thread_Control.cpp delete mode 100644 externals/ace/Thread_Control.h delete mode 100644 externals/ace/Thread_Control.inl delete mode 100644 externals/ace/Thread_Exit.cpp delete mode 100644 externals/ace/Thread_Exit.h delete mode 100644 externals/ace/Thread_Hook.cpp delete mode 100644 externals/ace/Thread_Hook.h delete mode 100644 externals/ace/Thread_Manager.cpp delete mode 100644 externals/ace/Thread_Manager.h delete mode 100644 externals/ace/Thread_Manager.inl delete mode 100644 externals/ace/Thread_Mutex.cpp delete mode 100644 externals/ace/Thread_Mutex.h delete mode 100644 externals/ace/Thread_Mutex.inl delete mode 100644 externals/ace/Thread_Semaphore.cpp delete mode 100644 externals/ace/Thread_Semaphore.h delete mode 100644 externals/ace/Thread_Semaphore.inl delete mode 100644 externals/ace/Throughput_Stats.cpp delete mode 100644 externals/ace/Throughput_Stats.h delete mode 100644 externals/ace/Time_Value.cpp delete mode 100644 externals/ace/Time_Value.h delete mode 100644 externals/ace/Time_Value.inl delete mode 100644 externals/ace/Timeprobe.cpp delete mode 100644 externals/ace/Timeprobe.h delete mode 100644 externals/ace/Timeprobe.inl delete mode 100644 externals/ace/Timeprobe_T.cpp delete mode 100644 externals/ace/Timeprobe_T.h delete mode 100644 externals/ace/Timer_Hash.h delete mode 100644 externals/ace/Timer_Hash_T.cpp delete mode 100644 externals/ace/Timer_Hash_T.h delete mode 100644 externals/ace/Timer_Heap.h delete mode 100644 externals/ace/Timer_Heap_T.cpp delete mode 100644 externals/ace/Timer_Heap_T.h delete mode 100644 externals/ace/Timer_List.h delete mode 100644 externals/ace/Timer_List_T.cpp delete mode 100644 externals/ace/Timer_List_T.h delete mode 100644 externals/ace/Timer_Queue.h delete mode 100644 externals/ace/Timer_Queue_Adapters.cpp delete mode 100644 externals/ace/Timer_Queue_Adapters.h delete mode 100644 externals/ace/Timer_Queue_Adapters.inl delete mode 100644 externals/ace/Timer_Queue_T.cpp delete mode 100644 externals/ace/Timer_Queue_T.h delete mode 100644 externals/ace/Timer_Queue_T.inl delete mode 100644 externals/ace/Timer_Queuefwd.h delete mode 100644 externals/ace/Timer_Wheel.h delete mode 100644 externals/ace/Timer_Wheel_T.cpp delete mode 100644 externals/ace/Timer_Wheel_T.h delete mode 100644 externals/ace/Token.cpp delete mode 100644 externals/ace/Token.h delete mode 100644 externals/ace/Token.inl delete mode 100644 externals/ace/Token_Collection.cpp delete mode 100644 externals/ace/Token_Collection.h delete mode 100644 externals/ace/Token_Collection.inl delete mode 100644 externals/ace/Token_Invariants.cpp delete mode 100644 externals/ace/Token_Invariants.h delete mode 100644 externals/ace/Token_Manager.cpp delete mode 100644 externals/ace/Token_Manager.h delete mode 100644 externals/ace/Token_Manager.inl delete mode 100644 externals/ace/Token_Request_Reply.cpp delete mode 100644 externals/ace/Token_Request_Reply.h delete mode 100644 externals/ace/Token_Request_Reply.inl delete mode 100644 externals/ace/Tokenizer_T.cpp delete mode 100644 externals/ace/Tokenizer_T.h delete mode 100644 externals/ace/Trace.cpp delete mode 100644 externals/ace/Trace.h delete mode 100644 externals/ace/Truncate.h delete mode 100644 externals/ace/Typed_SV_Message.cpp delete mode 100644 externals/ace/Typed_SV_Message.h delete mode 100644 externals/ace/Typed_SV_Message.inl delete mode 100644 externals/ace/Typed_SV_Message_Queue.cpp delete mode 100644 externals/ace/Typed_SV_Message_Queue.h delete mode 100644 externals/ace/Typed_SV_Message_Queue.inl delete mode 100644 externals/ace/UNIX_Addr.cpp delete mode 100644 externals/ace/UNIX_Addr.h delete mode 100644 externals/ace/UNIX_Addr.inl delete mode 100644 externals/ace/UPIPE_Acceptor.cpp delete mode 100644 externals/ace/UPIPE_Acceptor.h delete mode 100644 externals/ace/UPIPE_Acceptor.inl delete mode 100644 externals/ace/UPIPE_Addr.h delete mode 100644 externals/ace/UPIPE_Connector.cpp delete mode 100644 externals/ace/UPIPE_Connector.h delete mode 100644 externals/ace/UPIPE_Connector.inl delete mode 100644 externals/ace/UPIPE_Stream.cpp delete mode 100644 externals/ace/UPIPE_Stream.h delete mode 100644 externals/ace/UPIPE_Stream.inl delete mode 100644 externals/ace/UTF16_Encoding_Converter.cpp delete mode 100644 externals/ace/UTF16_Encoding_Converter.h delete mode 100644 externals/ace/UTF16_Encoding_Converter.inl delete mode 100644 externals/ace/UTF32_Encoding_Converter.cpp delete mode 100644 externals/ace/UTF32_Encoding_Converter.h delete mode 100644 externals/ace/UTF8_Encoding_Converter.cpp delete mode 100644 externals/ace/UTF8_Encoding_Converter.h delete mode 100644 externals/ace/UUID.cpp delete mode 100644 externals/ace/UUID.h delete mode 100644 externals/ace/UUID.inl delete mode 100644 externals/ace/Unbounded_Queue.cpp delete mode 100644 externals/ace/Unbounded_Queue.h delete mode 100644 externals/ace/Unbounded_Queue.inl delete mode 100644 externals/ace/Unbounded_Set.cpp delete mode 100644 externals/ace/Unbounded_Set.h delete mode 100644 externals/ace/Unbounded_Set.inl delete mode 100644 externals/ace/Unbounded_Set_Ex.cpp delete mode 100644 externals/ace/Unbounded_Set_Ex.h delete mode 100644 externals/ace/Unbounded_Set_Ex.inl delete mode 100644 externals/ace/Value_Ptr.h delete mode 100644 externals/ace/Vector_T.cpp delete mode 100644 externals/ace/Vector_T.h delete mode 100644 externals/ace/Vector_T.inl delete mode 100644 externals/ace/Version.h delete mode 100644 externals/ace/Versioned_Namespace.h delete mode 100644 externals/ace/WFMO_Reactor.cpp delete mode 100644 externals/ace/WFMO_Reactor.h delete mode 100644 externals/ace/WFMO_Reactor.inl delete mode 100644 externals/ace/WIN32_Asynch_IO.cpp delete mode 100644 externals/ace/WIN32_Asynch_IO.h delete mode 100644 externals/ace/WIN32_Proactor.cpp delete mode 100644 externals/ace/WIN32_Proactor.h delete mode 100644 externals/ace/XML_Svc_Conf.cpp delete mode 100644 externals/ace/XML_Svc_Conf.h delete mode 100644 externals/ace/XTI_ATM_Mcast.cpp delete mode 100644 externals/ace/XTI_ATM_Mcast.h delete mode 100644 externals/ace/XTI_ATM_Mcast.inl delete mode 100644 externals/ace/ace.rc delete mode 100644 externals/ace/ace_message_table.bin delete mode 100644 externals/ace/ace_wchar.cpp delete mode 100644 externals/ace/ace_wchar.h delete mode 100644 externals/ace/ace_wchar.inl delete mode 100644 externals/ace/checked_iterator.h delete mode 100644 externals/ace/config-WinCE.h delete mode 100644 externals/ace/config-aix-5.x.h delete mode 100644 externals/ace/config-all.h delete mode 100644 externals/ace/config-cray.h delete mode 100644 externals/ace/config-cxx-common.h delete mode 100644 externals/ace/config-cygwin32.h delete mode 100644 externals/ace/config-doxygen.h delete mode 100644 externals/ace/config-freebsd.h delete mode 100644 externals/ace/config-g++-common.h delete mode 100644 externals/ace/config-ghs-common.h delete mode 100644 externals/ace/config-hpux-11.00.h delete mode 100644 externals/ace/config-icc-common.h delete mode 100644 externals/ace/config-integritySCA.h delete mode 100644 externals/ace/config-irix6.5.x-sgic++.h delete mode 100644 externals/ace/config-irix6.x-common.h delete mode 100644 externals/ace/config-irix6.x-g++.h delete mode 100644 externals/ace/config-irix6.x-sgic++.h delete mode 100644 externals/ace/config-linux-common.h delete mode 100644 externals/ace/config-linux.h delete mode 100644 externals/ace/config-lite.h delete mode 100644 externals/ace/config-lynxos.h delete mode 100644 externals/ace/config-macosx-iphone-hardware.h delete mode 100644 externals/ace/config-macosx-iphone-simulator.h delete mode 100644 externals/ace/config-macosx-leopard.h delete mode 100644 externals/ace/config-macosx-panther.h delete mode 100644 externals/ace/config-macosx-snowleopard.h delete mode 100644 externals/ace/config-macosx-tiger.h delete mode 100644 externals/ace/config-macosx.h delete mode 100644 externals/ace/config-macros.h delete mode 100644 externals/ace/config-minimal.h delete mode 100644 externals/ace/config-mvs.h delete mode 100644 externals/ace/config-netbsd.h delete mode 100644 externals/ace/config-openbsd.h delete mode 100644 externals/ace/config-openvms.h delete mode 100644 externals/ace/config-pharlap.h delete mode 100644 externals/ace/config-posix-nonetworking.h delete mode 100644 externals/ace/config-posix.h delete mode 100644 externals/ace/config-qnx-neutrino.h delete mode 100644 externals/ace/config-qnx-rtp-62x.h delete mode 100644 externals/ace/config-qnx-rtp-common.h delete mode 100644 externals/ace/config-qnx-rtp-pre62x.h delete mode 100644 externals/ace/config-qnx-rtp.h delete mode 100644 externals/ace/config-rtems.h delete mode 100644 externals/ace/config-sco-5.0.0-nothread.h delete mode 100644 externals/ace/config-sco-5.0.0.h delete mode 100644 externals/ace/config-suncc-common.h delete mode 100644 externals/ace/config-sunos5.10.h delete mode 100644 externals/ace/config-sunos5.11.h delete mode 100644 externals/ace/config-sunos5.4-g++.h delete mode 100644 externals/ace/config-sunos5.4-sunc++-4.x.h delete mode 100644 externals/ace/config-sunos5.5.h delete mode 100644 externals/ace/config-sunos5.6.h delete mode 100644 externals/ace/config-sunos5.7.h delete mode 100644 externals/ace/config-sunos5.8.h delete mode 100644 externals/ace/config-sunos5.9.h delete mode 100644 externals/ace/config-tandem-nsk-mips-v2.h delete mode 100644 externals/ace/config-tandem-nsk-mips-v3.h delete mode 100644 externals/ace/config-tandem.h delete mode 100644 externals/ace/config-tru64.h delete mode 100644 externals/ace/config-unixware-7.1.0.h delete mode 100644 externals/ace/config-unixware-7.1.0.udk.h delete mode 100644 externals/ace/config-visualage.h delete mode 100644 externals/ace/config-vxworks.h delete mode 100644 externals/ace/config-vxworks6.4.h delete mode 100644 externals/ace/config-vxworks6.5.h delete mode 100644 externals/ace/config-vxworks6.6.h delete mode 100644 externals/ace/config-vxworks6.7.h delete mode 100644 externals/ace/config-vxworks6.8.h delete mode 100644 externals/ace/config-win32-borland.h delete mode 100644 externals/ace/config-win32-cegcc.h delete mode 100644 externals/ace/config-win32-common.h delete mode 100644 externals/ace/config-win32-dmc.h delete mode 100644 externals/ace/config-win32-ghs.h delete mode 100644 externals/ace/config-win32-interix.h delete mode 100644 externals/ace/config-win32-mingw.h delete mode 100644 externals/ace/config-win32-msvc-10.h delete mode 100644 externals/ace/config-win32-msvc-7.h delete mode 100644 externals/ace/config-win32-msvc-8.h delete mode 100644 externals/ace/config-win32-msvc-9.h delete mode 100644 externals/ace/config-win32-msvc.h delete mode 100644 externals/ace/config-win32.h delete mode 100644 externals/ace/config.h.in delete mode 100644 externals/ace/gethrtime.cpp delete mode 100644 externals/ace/iosfwd.h delete mode 100644 externals/ace/os_include/arpa/os_inet.h delete mode 100644 externals/ace/os_include/net/os_if.h delete mode 100644 externals/ace/os_include/netinet/os_in.h delete mode 100644 externals/ace/os_include/netinet/os_tcp.h delete mode 100644 externals/ace/os_include/os_aio.h delete mode 100644 externals/ace/os_include/os_assert.h delete mode 100644 externals/ace/os_include/os_byteswap.h delete mode 100644 externals/ace/os_include/os_complex.h delete mode 100644 externals/ace/os_include/os_cpio.h delete mode 100644 externals/ace/os_include/os_ctype.h delete mode 100644 externals/ace/os_include/os_dirent.h delete mode 100644 externals/ace/os_include/os_dlfcn.h delete mode 100644 externals/ace/os_include/os_errno.h delete mode 100644 externals/ace/os_include/os_fcntl.h delete mode 100644 externals/ace/os_include/os_fenv.h delete mode 100644 externals/ace/os_include/os_float.h delete mode 100644 externals/ace/os_include/os_fmtmsg.h delete mode 100644 externals/ace/os_include/os_fnmatch.h delete mode 100644 externals/ace/os_include/os_ftw.h delete mode 100644 externals/ace/os_include/os_glob.h delete mode 100644 externals/ace/os_include/os_grp.h delete mode 100644 externals/ace/os_include/os_iconv.h delete mode 100644 externals/ace/os_include/os_intrin.h delete mode 100644 externals/ace/os_include/os_inttypes.h delete mode 100644 externals/ace/os_include/os_iso646.h delete mode 100644 externals/ace/os_include/os_kstat.h delete mode 100644 externals/ace/os_include/os_langinfo.h delete mode 100644 externals/ace/os_include/os_libgen.h delete mode 100644 externals/ace/os_include/os_limits.h delete mode 100644 externals/ace/os_include/os_local.h delete mode 100644 externals/ace/os_include/os_math.h delete mode 100644 externals/ace/os_include/os_monetary.h delete mode 100644 externals/ace/os_include/os_mqueue.h delete mode 100644 externals/ace/os_include/os_ndbm.h delete mode 100644 externals/ace/os_include/os_netdb.h delete mode 100644 externals/ace/os_include/os_nl_types.h delete mode 100644 externals/ace/os_include/os_pdh.h delete mode 100644 externals/ace/os_include/os_pdhmsg.h delete mode 100644 externals/ace/os_include/os_poll.h delete mode 100644 externals/ace/os_include/os_pthread.h delete mode 100644 externals/ace/os_include/os_pwd.h delete mode 100644 externals/ace/os_include/os_regex.h delete mode 100644 externals/ace/os_include/os_sched.h delete mode 100644 externals/ace/os_include/os_search.h delete mode 100644 externals/ace/os_include/os_semaphore.h delete mode 100644 externals/ace/os_include/os_setjmp.h delete mode 100644 externals/ace/os_include/os_signal.h delete mode 100644 externals/ace/os_include/os_spawn.h delete mode 100644 externals/ace/os_include/os_stdarg.h delete mode 100644 externals/ace/os_include/os_stdbool.h delete mode 100644 externals/ace/os_include/os_stddef.h delete mode 100644 externals/ace/os_include/os_stdint.h delete mode 100644 externals/ace/os_include/os_stdio.h delete mode 100644 externals/ace/os_include/os_stdlib.h delete mode 100644 externals/ace/os_include/os_string.h delete mode 100644 externals/ace/os_include/os_strings.h delete mode 100644 externals/ace/os_include/os_stropts.h delete mode 100644 externals/ace/os_include/os_syslog.h delete mode 100644 externals/ace/os_include/os_tar.h delete mode 100644 externals/ace/os_include/os_termios.h delete mode 100644 externals/ace/os_include/os_tgmath.h delete mode 100644 externals/ace/os_include/os_time.h delete mode 100644 externals/ace/os_include/os_trace.h delete mode 100644 externals/ace/os_include/os_typeinfo.h delete mode 100644 externals/ace/os_include/os_ucontext.h delete mode 100644 externals/ace/os_include/os_ulimit.h delete mode 100644 externals/ace/os_include/os_unistd.h delete mode 100644 externals/ace/os_include/os_utime.h delete mode 100644 externals/ace/os_include/os_utmpx.h delete mode 100644 externals/ace/os_include/os_wchar.h delete mode 100644 externals/ace/os_include/os_wctype.h delete mode 100644 externals/ace/os_include/os_wordexp.h delete mode 100644 externals/ace/os_include/sys/os_ipc.h delete mode 100644 externals/ace/os_include/sys/os_loadavg.h delete mode 100644 externals/ace/os_include/sys/os_mman.h delete mode 100644 externals/ace/os_include/sys/os_msg.h delete mode 100644 externals/ace/os_include/sys/os_pstat.h delete mode 100644 externals/ace/os_include/sys/os_resource.h delete mode 100644 externals/ace/os_include/sys/os_select.h delete mode 100644 externals/ace/os_include/sys/os_sem.h delete mode 100644 externals/ace/os_include/sys/os_shm.h delete mode 100644 externals/ace/os_include/sys/os_socket.h delete mode 100644 externals/ace/os_include/sys/os_stat.h delete mode 100644 externals/ace/os_include/sys/os_statvfs.h delete mode 100644 externals/ace/os_include/sys/os_sysctl.h delete mode 100644 externals/ace/os_include/sys/os_sysinfo.h delete mode 100644 externals/ace/os_include/sys/os_time.h delete mode 100644 externals/ace/os_include/sys/os_timeb.h delete mode 100644 externals/ace/os_include/sys/os_times.h delete mode 100644 externals/ace/os_include/sys/os_types.h delete mode 100644 externals/ace/os_include/sys/os_uio.h delete mode 100644 externals/ace/os_include/sys/os_un.h delete mode 100644 externals/ace/os_include/sys/os_utsname.h delete mode 100644 externals/ace/os_include/sys/os_wait.h delete mode 100644 externals/ace/post.h delete mode 100644 externals/ace/pre.h delete mode 100644 externals/ace/streams.h delete mode 100644 externals/ace/svc_export.h delete mode 100644 externals/bzip2/CMakeLists.txt delete mode 100644 externals/bzip2/blocksort.c delete mode 100644 externals/bzip2/bzlib.c delete mode 100644 externals/bzip2/bzlib.h delete mode 100644 externals/bzip2/bzlib_private.h delete mode 100644 externals/bzip2/compress.c delete mode 100644 externals/bzip2/crctable.c delete mode 100644 externals/bzip2/decompress.c delete mode 100644 externals/bzip2/huffman.c delete mode 100644 externals/bzip2/randtable.c delete mode 100644 externals/g3dlite/AABox.cpp delete mode 100644 externals/g3dlite/Any.cpp delete mode 100644 externals/g3dlite/BinaryFormat.cpp delete mode 100644 externals/g3dlite/BinaryInput.cpp delete mode 100644 externals/g3dlite/BinaryOutput.cpp delete mode 100644 externals/g3dlite/Box.cpp delete mode 100644 externals/g3dlite/CMakeLists.txt delete mode 100644 externals/g3dlite/Capsule.cpp delete mode 100644 externals/g3dlite/CollisionDetection.cpp delete mode 100644 externals/g3dlite/CoordinateFrame.cpp delete mode 100644 externals/g3dlite/Crypto.cpp delete mode 100644 externals/g3dlite/Cylinder.cpp delete mode 100644 externals/g3dlite/G3D/AABox.h delete mode 100644 externals/g3dlite/G3D/Any.h delete mode 100644 externals/g3dlite/G3D/AnyVal.h delete mode 100644 externals/g3dlite/G3D/AreaMemoryManager.h delete mode 100644 externals/g3dlite/G3D/Array.h delete mode 100644 externals/g3dlite/G3D/AtomicInt32.h delete mode 100644 externals/g3dlite/G3D/BinaryFormat.h delete mode 100644 externals/g3dlite/G3D/BinaryInput.h delete mode 100644 externals/g3dlite/G3D/BinaryOutput.h delete mode 100644 externals/g3dlite/G3D/BoundsTrait.h delete mode 100644 externals/g3dlite/G3D/Box.h delete mode 100644 externals/g3dlite/G3D/Box2D.h delete mode 100644 externals/g3dlite/G3D/BumpMapPreprocess.h delete mode 100644 externals/g3dlite/G3D/Capsule.h delete mode 100644 externals/g3dlite/G3D/CollisionDetection.h delete mode 100644 externals/g3dlite/G3D/Color1.h delete mode 100644 externals/g3dlite/G3D/Color1uint8.h delete mode 100644 externals/g3dlite/G3D/Color3.h delete mode 100644 externals/g3dlite/G3D/Color3uint8.h delete mode 100644 externals/g3dlite/G3D/Color4.h delete mode 100644 externals/g3dlite/G3D/Color4uint8.h delete mode 100644 externals/g3dlite/G3D/Cone.h delete mode 100644 externals/g3dlite/G3D/ConvexPolyhedron.h delete mode 100644 externals/g3dlite/G3D/CoordinateFrame.h delete mode 100644 externals/g3dlite/G3D/Crypto.h delete mode 100644 externals/g3dlite/G3D/Cylinder.h delete mode 100644 externals/g3dlite/G3D/EqualsTrait.h delete mode 100644 externals/g3dlite/G3D/G3D.h delete mode 100644 externals/g3dlite/G3D/G3DAll.h delete mode 100644 externals/g3dlite/G3D/G3DGameUnits.h delete mode 100644 externals/g3dlite/G3D/GCamera.h delete mode 100644 externals/g3dlite/G3D/GImage.h delete mode 100644 externals/g3dlite/G3D/GLight.h delete mode 100644 externals/g3dlite/G3D/GMutex.h delete mode 100644 externals/g3dlite/G3D/GThread.h delete mode 100644 externals/g3dlite/G3D/GUniqueID.h delete mode 100644 externals/g3dlite/G3D/HashTrait.h delete mode 100644 externals/g3dlite/G3D/Image1.h delete mode 100644 externals/g3dlite/G3D/Image1uint8.h delete mode 100644 externals/g3dlite/G3D/Image3.h delete mode 100644 externals/g3dlite/G3D/Image3uint8.h delete mode 100644 externals/g3dlite/G3D/Image4.h delete mode 100644 externals/g3dlite/G3D/Image4uint8.h delete mode 100644 externals/g3dlite/G3D/ImageFormat.h delete mode 100644 externals/g3dlite/G3D/Intersect.h delete mode 100644 externals/g3dlite/G3D/KDTree.h delete mode 100644 externals/g3dlite/G3D/Line.h delete mode 100644 externals/g3dlite/G3D/LineSegment.h delete mode 100644 externals/g3dlite/G3D/Log.h delete mode 100644 externals/g3dlite/G3D/Map2D.h delete mode 100644 externals/g3dlite/G3D/Matrix.h delete mode 100644 externals/g3dlite/G3D/Matrix2.h delete mode 100644 externals/g3dlite/G3D/Matrix3.h delete mode 100644 externals/g3dlite/G3D/Matrix4.h delete mode 100644 externals/g3dlite/G3D/MemoryManager.h delete mode 100644 externals/g3dlite/G3D/MeshAlg.h delete mode 100644 externals/g3dlite/G3D/MeshBuilder.h delete mode 100644 externals/g3dlite/G3D/NetAddress.h delete mode 100644 externals/g3dlite/G3D/NetworkDevice.h delete mode 100644 externals/g3dlite/G3D/ParseError.h delete mode 100644 externals/g3dlite/G3D/PhysicsFrame.h delete mode 100644 externals/g3dlite/G3D/Plane.h delete mode 100644 externals/g3dlite/G3D/PointHashGrid.h delete mode 100644 externals/g3dlite/G3D/PointKDTree.h delete mode 100644 externals/g3dlite/G3D/Pointer.h delete mode 100644 externals/g3dlite/G3D/PositionTrait.h delete mode 100644 externals/g3dlite/G3D/PrecomputedRandom.h delete mode 100644 externals/g3dlite/G3D/Quat.h delete mode 100644 externals/g3dlite/G3D/Quat.inl delete mode 100644 externals/g3dlite/G3D/Queue.h delete mode 100644 externals/g3dlite/G3D/Random.h delete mode 100644 externals/g3dlite/G3D/Ray.h delete mode 100644 externals/g3dlite/G3D/Rect2D.h delete mode 100644 externals/g3dlite/G3D/ReferenceCount.h delete mode 100644 externals/g3dlite/G3D/RegistryUtil.h delete mode 100644 externals/g3dlite/G3D/Set.h delete mode 100644 externals/g3dlite/G3D/SmallArray.h delete mode 100644 externals/g3dlite/G3D/Sphere.h delete mode 100644 externals/g3dlite/G3D/Spline.h delete mode 100644 externals/g3dlite/G3D/Stopwatch.h delete mode 100644 externals/g3dlite/G3D/System.h delete mode 100644 externals/g3dlite/G3D/Table.h delete mode 100644 externals/g3dlite/G3D/TextInput.h delete mode 100644 externals/g3dlite/G3D/TextOutput.h delete mode 100644 externals/g3dlite/G3D/ThreadSet.h delete mode 100644 externals/g3dlite/G3D/Triangle.h delete mode 100644 externals/g3dlite/G3D/UprightFrame.h delete mode 100644 externals/g3dlite/G3D/Vector2.h delete mode 100644 externals/g3dlite/G3D/Vector2.inl delete mode 100644 externals/g3dlite/G3D/Vector2int16.h delete mode 100644 externals/g3dlite/G3D/Vector3.h delete mode 100644 externals/g3dlite/G3D/Vector3.inl delete mode 100644 externals/g3dlite/G3D/Vector3int16.h delete mode 100644 externals/g3dlite/G3D/Vector3int32.h delete mode 100644 externals/g3dlite/G3D/Vector4.h delete mode 100644 externals/g3dlite/G3D/Vector4.inl delete mode 100644 externals/g3dlite/G3D/Vector4int8.h delete mode 100644 externals/g3dlite/G3D/WeakCache.h delete mode 100644 externals/g3dlite/G3D/Welder.h delete mode 100644 externals/g3dlite/G3D/WrapMode.h delete mode 100644 externals/g3dlite/G3D/constants.h delete mode 100644 externals/g3dlite/G3D/debug.h delete mode 100644 externals/g3dlite/G3D/debugAssert.h delete mode 100644 externals/g3dlite/G3D/debugPrintf.h delete mode 100644 externals/g3dlite/G3D/enumclass.h delete mode 100644 externals/g3dlite/G3D/fileutils.h delete mode 100644 externals/g3dlite/G3D/filter.h delete mode 100644 externals/g3dlite/G3D/format.h delete mode 100644 externals/g3dlite/G3D/g3dfnmatch.h delete mode 100644 externals/g3dlite/G3D/g3dmath.h delete mode 100644 externals/g3dlite/G3D/g3dmath.inl delete mode 100644 externals/g3dlite/G3D/platform.h delete mode 100644 externals/g3dlite/G3D/prompt.h delete mode 100644 externals/g3dlite/G3D/serialize.h delete mode 100644 externals/g3dlite/G3D/splinefunc.h delete mode 100644 externals/g3dlite/G3D/stringutils.h delete mode 100644 externals/g3dlite/G3D/uint128.h delete mode 100644 externals/g3dlite/G3D/units.h delete mode 100644 externals/g3dlite/G3D/vectorMath.h delete mode 100644 externals/g3dlite/Line.cpp delete mode 100644 externals/g3dlite/LineSegment.cpp delete mode 100644 externals/g3dlite/Log.cpp delete mode 100644 externals/g3dlite/Matrix3.cpp delete mode 100644 externals/g3dlite/Matrix4.cpp delete mode 100644 externals/g3dlite/MemoryManager.cpp delete mode 100644 externals/g3dlite/Plane.cpp delete mode 100644 externals/g3dlite/Quat.cpp delete mode 100644 externals/g3dlite/Random.cpp delete mode 100644 externals/g3dlite/Ray.cpp delete mode 100644 externals/g3dlite/ReferenceCount.cpp delete mode 100644 externals/g3dlite/RegistryUtil.cpp delete mode 100644 externals/g3dlite/Sphere.cpp delete mode 100644 externals/g3dlite/System.cpp delete mode 100644 externals/g3dlite/TextInput.cpp delete mode 100644 externals/g3dlite/TextOutput.cpp delete mode 100644 externals/g3dlite/Triangle.cpp delete mode 100644 externals/g3dlite/UprightFrame.cpp delete mode 100644 externals/g3dlite/Vector2.cpp delete mode 100644 externals/g3dlite/Vector3.cpp delete mode 100644 externals/g3dlite/Vector4.cpp delete mode 100644 externals/g3dlite/debugAssert.cpp delete mode 100644 externals/g3dlite/fileutils.cpp delete mode 100644 externals/g3dlite/format.cpp delete mode 100644 externals/g3dlite/g3dfnmatch.cpp delete mode 100644 externals/g3dlite/g3dmath.cpp delete mode 100644 externals/g3dlite/prompt.cpp delete mode 100644 externals/g3dlite/stringutils.cpp delete mode 100644 externals/gsoap/CMakeLists.txt delete mode 100644 externals/gsoap/soapC.cpp delete mode 100644 externals/gsoap/soapH.h delete mode 100644 externals/gsoap/soapServer.cpp delete mode 100644 externals/gsoap/soapStub.h delete mode 100644 externals/gsoap/stdsoap2.cpp delete mode 100644 externals/gsoap/stdsoap2.h delete mode 100644 externals/jemalloc/CMakeLists.txt delete mode 100644 externals/jemalloc/arena.c delete mode 100644 externals/jemalloc/base.c delete mode 100644 externals/jemalloc/chunk.c delete mode 100644 externals/jemalloc/chunk_dss.c delete mode 100644 externals/jemalloc/chunk_mmap.c delete mode 100644 externals/jemalloc/chunk_swap.c delete mode 100644 externals/jemalloc/ckh.c delete mode 100644 externals/jemalloc/ctl.c delete mode 100644 externals/jemalloc/extent.c delete mode 100644 externals/jemalloc/hash.c delete mode 100644 externals/jemalloc/huge.c delete mode 100644 externals/jemalloc/jemalloc.c delete mode 100644 externals/jemalloc/jemalloc/internal/arena.h delete mode 100644 externals/jemalloc/jemalloc/internal/base.h delete mode 100644 externals/jemalloc/jemalloc/internal/chunk.h delete mode 100644 externals/jemalloc/jemalloc/internal/chunk_dss.h delete mode 100644 externals/jemalloc/jemalloc/internal/chunk_mmap.h delete mode 100644 externals/jemalloc/jemalloc/internal/chunk_swap.h delete mode 100644 externals/jemalloc/jemalloc/internal/ckh.h delete mode 100644 externals/jemalloc/jemalloc/internal/ctl.h delete mode 100644 externals/jemalloc/jemalloc/internal/extent.h delete mode 100644 externals/jemalloc/jemalloc/internal/hash.h delete mode 100644 externals/jemalloc/jemalloc/internal/huge.h delete mode 100644 externals/jemalloc/jemalloc/internal/jemalloc_internal.h delete mode 100644 externals/jemalloc/jemalloc/internal/jemalloc_internal.h.in delete mode 100644 externals/jemalloc/jemalloc/internal/mb.h delete mode 100644 externals/jemalloc/jemalloc/internal/mutex.h delete mode 100644 externals/jemalloc/jemalloc/internal/prof.h delete mode 100644 externals/jemalloc/jemalloc/internal/ql.h delete mode 100644 externals/jemalloc/jemalloc/internal/qr.h delete mode 100644 externals/jemalloc/jemalloc/internal/rb.h delete mode 100644 externals/jemalloc/jemalloc/internal/stats.h delete mode 100644 externals/jemalloc/jemalloc/internal/tcache.h delete mode 100644 externals/jemalloc/jemalloc/internal/totally_not_p_r_n.h delete mode 100644 externals/jemalloc/jemalloc/jemalloc.h delete mode 100644 externals/jemalloc/jemalloc/jemalloc.h.in delete mode 100644 externals/jemalloc/jemalloc/jemalloc_defs.h delete mode 100644 externals/jemalloc/jemalloc/jemalloc_defs.h.in delete mode 100644 externals/jemalloc/mb.c delete mode 100644 externals/jemalloc/mutex.c delete mode 100644 externals/jemalloc/prof.c delete mode 100644 externals/jemalloc/stats.c delete mode 100644 externals/jemalloc/tcache.c delete mode 100644 externals/libmpq/AUTHORS delete mode 100644 externals/libmpq/CMakeLists.txt delete mode 100644 externals/libmpq/COPYING delete mode 100644 externals/libmpq/FAQ delete mode 100644 externals/libmpq/INSTALL delete mode 100644 externals/libmpq/Makefile.am delete mode 100644 externals/libmpq/NEWS delete mode 100644 externals/libmpq/README delete mode 100644 externals/libmpq/THANKS delete mode 100644 externals/libmpq/TODO delete mode 100644 externals/libmpq/autogen.sh delete mode 100644 externals/libmpq/bindings/Makefile.am delete mode 100644 externals/libmpq/bindings/d/Makefile.am delete mode 100644 externals/libmpq/bindings/d/dsss.conf delete mode 100644 externals/libmpq/bindings/d/mpq.d delete mode 100644 externals/libmpq/bindings/python/Makefile.am delete mode 100644 externals/libmpq/bindings/python/mpq-info delete mode 100644 externals/libmpq/bindings/python/mpq.py delete mode 100644 externals/libmpq/config.h delete mode 100644 externals/libmpq/configure.ac delete mode 100644 externals/libmpq/debian/changelog delete mode 100644 externals/libmpq/debian/compat delete mode 100644 externals/libmpq/debian/control delete mode 100644 externals/libmpq/debian/copyright delete mode 100644 externals/libmpq/debian/libmpq-dev.dirs delete mode 100644 externals/libmpq/debian/libmpq-dev.install delete mode 100644 externals/libmpq/debian/libmpq0.dirs delete mode 100644 externals/libmpq/debian/libmpq0.docs delete mode 100644 externals/libmpq/debian/libmpq0.install delete mode 100644 externals/libmpq/debian/python-mpq.install delete mode 100644 externals/libmpq/debian/rules delete mode 100644 externals/libmpq/doc/Makefile.am delete mode 100644 externals/libmpq/doc/man1/Makefile.am delete mode 100644 externals/libmpq/doc/man1/libmpq-config.1 delete mode 100644 externals/libmpq/doc/man3/Makefile.am delete mode 100644 externals/libmpq/doc/man3/libmpq.3 delete mode 100644 externals/libmpq/doc/man3/libmpq__archive_close.3 delete mode 100644 externals/libmpq/doc/man3/libmpq__archive_files.3 delete mode 100644 externals/libmpq/doc/man3/libmpq__archive_offset.3 delete mode 100644 externals/libmpq/doc/man3/libmpq__archive_open.3 delete mode 100644 externals/libmpq/doc/man3/libmpq__archive_packed_size.3 delete mode 100644 externals/libmpq/doc/man3/libmpq__archive_unpacked_size.3 delete mode 100644 externals/libmpq/doc/man3/libmpq__archive_version.3 delete mode 100644 externals/libmpq/doc/man3/libmpq__block_close_offset.3 delete mode 100644 externals/libmpq/doc/man3/libmpq__block_open_offset.3 delete mode 100644 externals/libmpq/doc/man3/libmpq__block_read.3 delete mode 100644 externals/libmpq/doc/man3/libmpq__block_unpacked_size.3 delete mode 100644 externals/libmpq/doc/man3/libmpq__file_blocks.3 delete mode 100644 externals/libmpq/doc/man3/libmpq__file_compressed.3 delete mode 100644 externals/libmpq/doc/man3/libmpq__file_encrypted.3 delete mode 100644 externals/libmpq/doc/man3/libmpq__file_imploded.3 delete mode 100644 externals/libmpq/doc/man3/libmpq__file_number.3 delete mode 100644 externals/libmpq/doc/man3/libmpq__file_offset.3 delete mode 100644 externals/libmpq/doc/man3/libmpq__file_packed_size.3 delete mode 100644 externals/libmpq/doc/man3/libmpq__file_read.3 delete mode 100644 externals/libmpq/doc/man3/libmpq__file_unpacked_size.3 delete mode 100644 externals/libmpq/doc/man3/libmpq__strerror.3 delete mode 100644 externals/libmpq/doc/man3/libmpq__version.3 delete mode 100644 externals/libmpq/libmpq-config.in delete mode 100644 externals/libmpq/libmpq.pc.in delete mode 100644 externals/libmpq/libmpq/Makefile.am delete mode 100644 externals/libmpq/libmpq/common.c delete mode 100644 externals/libmpq/libmpq/common.h delete mode 100644 externals/libmpq/libmpq/crypt_buf.h delete mode 100644 externals/libmpq/libmpq/explode.c delete mode 100644 externals/libmpq/libmpq/explode.h delete mode 100644 externals/libmpq/libmpq/extract.c delete mode 100644 externals/libmpq/libmpq/extract.h delete mode 100644 externals/libmpq/libmpq/huffman.c delete mode 100644 externals/libmpq/libmpq/huffman.h delete mode 100644 externals/libmpq/libmpq/mpq-internal.h delete mode 100644 externals/libmpq/libmpq/mpq.c delete mode 100644 externals/libmpq/libmpq/mpq.h delete mode 100644 externals/libmpq/libmpq/pack_begin.h delete mode 100644 externals/libmpq/libmpq/pack_end.h delete mode 100644 externals/libmpq/libmpq/platform.h delete mode 100644 externals/libmpq/libmpq/wave.c delete mode 100644 externals/libmpq/libmpq/wave.h delete mode 100644 externals/libmpq/tools/Makefile.am delete mode 100644 externals/libmpq/tools/crypt_buf_gen.c delete mode 100644 externals/libmpq/win/config.h delete mode 100644 externals/libmpq/win/dirent.h delete mode 100644 externals/libmpq/win/stdint.h delete mode 100644 externals/mersennetwister/MersenneTwister.h delete mode 100644 externals/sockets/Base64.cpp delete mode 100644 externals/sockets/CMakeLists.txt delete mode 100644 externals/sockets/Exception.cpp delete mode 100644 externals/sockets/Ipv4Address.cpp delete mode 100644 externals/sockets/Ipv6Address.cpp delete mode 100644 externals/sockets/Lock.cpp delete mode 100644 externals/sockets/Makefile delete mode 100644 externals/sockets/Mutex.cpp delete mode 100644 externals/sockets/Parse.cpp delete mode 100644 externals/sockets/ResolvServer.cpp delete mode 100644 externals/sockets/ResolvSocket.cpp delete mode 100644 externals/sockets/Socket.cpp delete mode 100644 externals/sockets/SocketHandler.cpp delete mode 100644 externals/sockets/StdoutLog.cpp delete mode 100644 externals/sockets/StreamSocket.cpp delete mode 100644 externals/sockets/TcpSocket.cpp delete mode 100644 externals/sockets/Thread.cpp delete mode 100644 externals/sockets/UdpSocket.cpp delete mode 100644 externals/sockets/Utility.cpp delete mode 100644 externals/sockets/include/Base64.h delete mode 100644 externals/sockets/include/Exception.h delete mode 100644 externals/sockets/include/File.h delete mode 100644 externals/sockets/include/IFile.h delete mode 100644 externals/sockets/include/ISocketHandler.h delete mode 100644 externals/sockets/include/Ipv4Address.h delete mode 100644 externals/sockets/include/Ipv6Address.h delete mode 100644 externals/sockets/include/ListenSocket.h delete mode 100644 externals/sockets/include/Lock.h delete mode 100644 externals/sockets/include/Mutex.h delete mode 100644 externals/sockets/include/Parse.h delete mode 100644 externals/sockets/include/ResolvServer.h delete mode 100644 externals/sockets/include/ResolvSocket.h delete mode 100644 externals/sockets/include/SctpSocket.h delete mode 100644 externals/sockets/include/Socket.h delete mode 100644 externals/sockets/include/SocketAddress.h delete mode 100644 externals/sockets/include/SocketHandler.h delete mode 100644 externals/sockets/include/StdLog.h delete mode 100644 externals/sockets/include/StdoutLog.h delete mode 100644 externals/sockets/include/StreamSocket.h delete mode 100644 externals/sockets/include/TcpSocket.h delete mode 100644 externals/sockets/include/Thread.h delete mode 100644 externals/sockets/include/UdpSocket.h delete mode 100644 externals/sockets/include/Utility.h delete mode 100644 externals/sockets/include/socket_include.h delete mode 100644 externals/sockets/include/sockets-config.h delete mode 100644 externals/sockets/network_kist.txt delete mode 100644 externals/sockets/socket_include.cpp delete mode 100644 externals/utf8cpp/utf8.h delete mode 100644 externals/utf8cpp/utf8/checked.h delete mode 100644 externals/utf8cpp/utf8/core.h delete mode 100644 externals/utf8cpp/utf8/unchecked.h delete mode 100644 externals/zlib/CMakeLists.txt delete mode 100644 externals/zlib/adler32.c delete mode 100644 externals/zlib/compress.c delete mode 100644 externals/zlib/crc32.c delete mode 100644 externals/zlib/crc32.h delete mode 100644 externals/zlib/deflate.c delete mode 100644 externals/zlib/deflate.h delete mode 100644 externals/zlib/example.c delete mode 100644 externals/zlib/gzclose.c delete mode 100644 externals/zlib/gzguts.h delete mode 100644 externals/zlib/gzlib.c delete mode 100644 externals/zlib/gzread.c delete mode 100644 externals/zlib/gzwrite.c delete mode 100644 externals/zlib/infback.c delete mode 100644 externals/zlib/inffast.c delete mode 100644 externals/zlib/inffast.h delete mode 100644 externals/zlib/inffixed.h delete mode 100644 externals/zlib/inflate.c delete mode 100644 externals/zlib/inflate.h delete mode 100644 externals/zlib/inftrees.c delete mode 100644 externals/zlib/inftrees.h delete mode 100644 externals/zlib/minigzip.c delete mode 100644 externals/zlib/trees.c delete mode 100644 externals/zlib/trees.h delete mode 100644 externals/zlib/uncompr.c delete mode 100644 externals/zlib/zconf.h delete mode 100644 externals/zlib/zlib.h delete mode 100644 externals/zlib/zutil.c delete mode 100644 externals/zlib/zutil.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 1bd8488a1e7..5b240f8a4ba 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -44,7 +44,7 @@ include(CheckIncludeFiles) include(cmake/FindPlatform.cmake) include(cmake/FindPCHSupport.cmake) if(WIN32) - set(ACE_INCLUDE_DIR ${CMAKE_SOURCE_DIR}/externals) + set(ACE_INCLUDE_DIR ${CMAKE_SOURCE_DIR}/dep/acelite) endif() include(cmake/FindACE.cmake) include(cmake/FindMySQL.cmake) @@ -322,7 +322,7 @@ endif() # Enter the different builddirectories and start working # -add_subdirectory(externals) +add_subdirectory(dep) add_subdirectory(src) if( SQL ) add_subdirectory(sql) diff --git a/dep/CMakeLists.txt b/dep/CMakeLists.txt new file mode 100644 index 00000000000..d7a4737d778 --- /dev/null +++ b/dep/CMakeLists.txt @@ -0,0 +1,28 @@ +# Copyright (C) 2008-2010 Trinity +# +# This file is free software; as a special exception the author gives +# unlimited permission to copy and/or distribute it, with or without +# modifications, as long as this notice is preserved. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the +# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +if(CMAKE_SYSTEM_NAME MATCHES "Linux") + add_subdirectory(jemalloc) + set(JEMALLOC_LIB "jemalloc") +endif() + +if(CMAKE_SYSTEM_NAME MATCHES "Windows") + add_subdirectory(acelite) + add_subdirectory(zlib) + add_subdirectory(bzip2) +endif() + +add_subdirectory(g3dlite) +add_subdirectory(sockets) +add_subdirectory(gsoap) + +if(TOOLS) + add_subdirectory(libmpq) +endif() diff --git a/dep/PackageList.txt b/dep/PackageList.txt new file mode 100644 index 00000000000..bf14636223d --- /dev/null +++ b/dep/PackageList.txt @@ -0,0 +1,45 @@ +TrinityCore uses (parts of or in whole) the following opensource software : + +ACE (ADAPTIVE Communication Environment) + http://www.cs.wustl.edu/~schmidt/ACE.html + Version: 5.8.1 + +bzip2 (a freely available, patent free, high-quality data compressor) + http://www.bzip.org/ + Version: 1.0.5 + +G3D (a commercial-grade C++ 3D engine available as Open Source (BSD License) + http://g3d.sourceforge.net/ + Version: 6.09 + +jemalloc (a general-purpose scalable concurrent malloc-implementation) + http://www.canonware.com/jemalloc/ + Version: 1.0.0 + +libMPQ (a library for reading MPQ files) + https://libmpq.org/ + Version: 1.0.4 + +MersenneTwister (a very fast random number generator) + http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html + Version: 0.4.2 + +SFMT (SIMD-oriented Fast Mersenne Twister) + http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/index.html + Version: 1.3.3 + +sockets (a GPL licensed C++ class library wrapping the berkeley sockets C API) + http://www.alhem.net/Sockets/ + Version: UNKNOWN + +utf8-cpp (UTF-8 with C++ in a Portable Way) + http://utfcpp.sourceforge.net/ + Version: 2.3 + +vld (a free open-source memory leak detection system for Visual C++) + http://sites.google.com/site/dmoulding/vld + Version: 1.0 + +zlib (A Massively Spiffy Yet Delicately Unobtrusive Compression Library) + http://www.zlib.net/ + Version: 1.2.5 diff --git a/dep/SFMT/SFMT-alti.h b/dep/SFMT/SFMT-alti.h new file mode 100644 index 00000000000..df3186cbbd7 --- /dev/null +++ b/dep/SFMT/SFMT-alti.h @@ -0,0 +1,156 @@ +/** + * @file SFMT-alti.h + * + * @brief SIMD oriented Fast Mersenne Twister(SFMT) + * pseudorandom number generator + * + * @author Mutsuo Saito (Hiroshima University) + * @author Makoto Matsumoto (Hiroshima University) + * + * Copyright (C) 2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima + * University. All rights reserved. + * + * The new BSD License is applied to this software. + * see LICENSE.txt + */ + +#ifndef SFMT_ALTI_H +#define SFMT_ALTI_H + +inline static vector unsigned int vec_recursion(vector unsigned int a, + vector unsigned int b, + vector unsigned int c, + vector unsigned int d) + ALWAYSINLINE; + +/** + * This function represents the recursion formula in AltiVec and BIG ENDIAN. + * @param a a 128-bit part of the interal state array + * @param b a 128-bit part of the interal state array + * @param c a 128-bit part of the interal state array + * @param d a 128-bit part of the interal state array + * @return output + */ +inline static vector unsigned int vec_recursion(vector unsigned int a, + vector unsigned int b, + vector unsigned int c, + vector unsigned int d) { + + const vector unsigned int sl1 = ALTI_SL1; + const vector unsigned int sr1 = ALTI_SR1; +#ifdef ONLY64 + const vector unsigned int mask = ALTI_MSK64; + const vector unsigned char perm_sl = ALTI_SL2_PERM64; + const vector unsigned char perm_sr = ALTI_SR2_PERM64; +#else + const vector unsigned int mask = ALTI_MSK; + const vector unsigned char perm_sl = ALTI_SL2_PERM; + const vector unsigned char perm_sr = ALTI_SR2_PERM; +#endif + vector unsigned int v, w, x, y, z; + x = vec_perm(a, (vector unsigned int)perm_sl, perm_sl); + v = a; + y = vec_sr(b, sr1); + z = vec_perm(c, (vector unsigned int)perm_sr, perm_sr); + w = vec_sl(d, sl1); + z = vec_xor(z, w); + y = vec_and(y, mask); + v = vec_xor(v, x); + z = vec_xor(z, y); + z = vec_xor(z, v); + return z; +} + +/** + * This function fills the internal state array with pseudorandom + * integers. + */ +inline static void gen_rand_all(void) { + int i; + vector unsigned int r, r1, r2; + + r1 = sfmt[N - 2].s; + r2 = sfmt[N - 1].s; + for (i = 0; i < N - POS1; i++) { + r = vec_recursion(sfmt[i].s, sfmt[i + POS1].s, r1, r2); + sfmt[i].s = r; + r1 = r2; + r2 = r; + } + for (; i < N; i++) { + r = vec_recursion(sfmt[i].s, sfmt[i + POS1 - N].s, r1, r2); + sfmt[i].s = r; + r1 = r2; + r2 = r; + } +} + +/** + * This function fills the user-specified array with pseudorandom + * integers. + * + * @param array an 128-bit array to be filled by pseudorandom numbers. + * @param size number of 128-bit pesudorandom numbers to be generated. + */ +inline static void gen_rand_array(w128_t *array, int size) { + int i, j; + vector unsigned int r, r1, r2; + + r1 = sfmt[N - 2].s; + r2 = sfmt[N - 1].s; + for (i = 0; i < N - POS1; i++) { + r = vec_recursion(sfmt[i].s, sfmt[i + POS1].s, r1, r2); + array[i].s = r; + r1 = r2; + r2 = r; + } + for (; i < N; i++) { + r = vec_recursion(sfmt[i].s, array[i + POS1 - N].s, r1, r2); + array[i].s = r; + r1 = r2; + r2 = r; + } + /* main loop */ + for (; i < size - N; i++) { + r = vec_recursion(array[i - N].s, array[i + POS1 - N].s, r1, r2); + array[i].s = r; + r1 = r2; + r2 = r; + } + for (j = 0; j < 2 * N - size; j++) { + sfmt[j].s = array[j + size - N].s; + } + for (; i < size; i++) { + r = vec_recursion(array[i - N].s, array[i + POS1 - N].s, r1, r2); + array[i].s = r; + sfmt[j++].s = r; + r1 = r2; + r2 = r; + } +} + +#ifndef ONLY64 +#if defined(__APPLE__) +#define ALTI_SWAP (vector unsigned char) \ + (4, 5, 6, 7, 0, 1, 2, 3, 12, 13, 14, 15, 8, 9, 10, 11) +#else +#define ALTI_SWAP {4, 5, 6, 7, 0, 1, 2, 3, 12, 13, 14, 15, 8, 9, 10, 11} +#endif +/** + * This function swaps high and low 32-bit of 64-bit integers in user + * specified array. + * + * @param array an 128-bit array to be swaped. + * @param size size of 128-bit array. + */ +inline static void swap(w128_t *array, int size) { + int i; + const vector unsigned char perm = ALTI_SWAP; + + for (i = 0; i < size; i++) { + array[i].s = vec_perm(array[i].s, (vector unsigned int)perm, perm); + } +} +#endif + +#endif diff --git a/dep/SFMT/SFMT-params.h b/dep/SFMT/SFMT-params.h new file mode 100644 index 00000000000..661bbf26a28 --- /dev/null +++ b/dep/SFMT/SFMT-params.h @@ -0,0 +1,97 @@ +#ifndef SFMT_PARAMS_H +#define SFMT_PARAMS_H + +#if !defined(MEXP) +#ifdef __GNUC__ + #warning "MEXP is not defined. I assume MEXP is 19937." +#endif + #define MEXP 19937 +#endif +/*----------------- + BASIC DEFINITIONS + -----------------*/ +/** Mersenne Exponent. The period of the sequence + * is a multiple of 2^MEXP-1. + * #define MEXP 19937 */ +/** SFMT generator has an internal state array of 128-bit integers, + * and N is its size. */ +#define N (MEXP / 128 + 1) +/** N32 is the size of internal state array when regarded as an array + * of 32-bit integers.*/ +#define N32 (N * 4) +/** N64 is the size of internal state array when regarded as an array + * of 64-bit integers.*/ +#define N64 (N * 2) + +/*---------------------- + the parameters of SFMT + following definitions are in paramsXXXX.h file. + ----------------------*/ +/** the pick up position of the array. +#define POS1 122 +*/ + +/** the parameter of shift left as four 32-bit registers. +#define SL1 18 + */ + +/** the parameter of shift left as one 128-bit register. + * The 128-bit integer is shifted by (SL2 * 8) bits. +#define SL2 1 +*/ + +/** the parameter of shift right as four 32-bit registers. +#define SR1 11 +*/ + +/** the parameter of shift right as one 128-bit register. + * The 128-bit integer is shifted by (SL2 * 8) bits. +#define SR2 1 +*/ + +/** A bitmask, used in the recursion. These parameters are introduced + * to break symmetry of SIMD. +#define MSK1 0xdfffffefU +#define MSK2 0xddfecb7fU +#define MSK3 0xbffaffffU +#define MSK4 0xbffffff6U +*/ + +/** These definitions are part of a 128-bit period certification vector. +#define PARITY1 0x00000001U +#define PARITY2 0x00000000U +#define PARITY3 0x00000000U +#define PARITY4 0xc98e126aU +*/ + +#if MEXP == 607 + #include "SFMT-params607.h" +#elif MEXP == 1279 + #include "SFMT-params1279.h" +#elif MEXP == 2281 + #include "SFMT-params2281.h" +#elif MEXP == 4253 + #include "SFMT-params4253.h" +#elif MEXP == 11213 + #include "SFMT-params11213.h" +#elif MEXP == 19937 + #include "SFMT-params19937.h" +#elif MEXP == 44497 + #include "SFMT-params44497.h" +#elif MEXP == 86243 + #include "SFMT-params86243.h" +#elif MEXP == 132049 + #include "SFMT-params132049.h" +#elif MEXP == 216091 + #include "SFMT-params216091.h" +#else +#ifdef __GNUC__ + #error "MEXP is not valid." + #undef MEXP +#else + #undef MEXP +#endif + +#endif + +#endif /* SFMT_PARAMS_H */ diff --git a/dep/SFMT/SFMT-sse2.h b/dep/SFMT/SFMT-sse2.h new file mode 100644 index 00000000000..4e91d9c6121 --- /dev/null +++ b/dep/SFMT/SFMT-sse2.h @@ -0,0 +1,121 @@ +/** + * @file SFMT-sse2.h + * @brief SIMD oriented Fast Mersenne Twister(SFMT) for Intel SSE2 + * + * @author Mutsuo Saito (Hiroshima University) + * @author Makoto Matsumoto (Hiroshima University) + * + * @note We assume LITTLE ENDIAN in this file + * + * Copyright (C) 2006, 2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima + * University. All rights reserved. + * + * The new BSD License is applied to this software, see LICENSE.txt + */ + +#ifndef SFMT_SSE2_H +#define SFMT_SSE2_H + +PRE_ALWAYS static __m128i mm_recursion(__m128i *a, __m128i *b, __m128i c, + __m128i d, __m128i mask) ALWAYSINLINE; + +/** + * This function represents the recursion formula. + * @param a a 128-bit part of the interal state array + * @param b a 128-bit part of the interal state array + * @param c a 128-bit part of the interal state array + * @param d a 128-bit part of the interal state array + * @param mask 128-bit mask + * @return output + */ +PRE_ALWAYS static __m128i mm_recursion(__m128i *a, __m128i *b, + __m128i c, __m128i d, __m128i mask) { + __m128i v, x, y, z; + + x = _mm_load_si128(a); + y = _mm_srli_epi32(*b, SR1); + z = _mm_srli_si128(c, SR2); + v = _mm_slli_epi32(d, SL1); + z = _mm_xor_si128(z, x); + z = _mm_xor_si128(z, v); + x = _mm_slli_si128(x, SL2); + y = _mm_and_si128(y, mask); + z = _mm_xor_si128(z, x); + z = _mm_xor_si128(z, y); + return z; +} + +/** + * This function fills the internal state array with pseudorandom + * integers. + */ +inline static void gen_rand_all(void) { + int i; + __m128i r, r1, r2, mask; + mask = _mm_set_epi32(MSK4, MSK3, MSK2, MSK1); + + r1 = _mm_load_si128(&sfmt[N - 2].si); + r2 = _mm_load_si128(&sfmt[N - 1].si); + for (i = 0; i < N - POS1; i++) { + r = mm_recursion(&sfmt[i].si, &sfmt[i + POS1].si, r1, r2, mask); + _mm_store_si128(&sfmt[i].si, r); + r1 = r2; + r2 = r; + } + for (; i < N; i++) { + r = mm_recursion(&sfmt[i].si, &sfmt[i + POS1 - N].si, r1, r2, mask); + _mm_store_si128(&sfmt[i].si, r); + r1 = r2; + r2 = r; + } +} + +/** + * This function fills the user-specified array with pseudorandom + * integers. + * + * @param array an 128-bit array to be filled by pseudorandom numbers. + * @param size number of 128-bit pesudorandom numbers to be generated. + */ +inline static void gen_rand_array(w128_t *array, int size) { + int i, j; + __m128i r, r1, r2, mask; + mask = _mm_set_epi32(MSK4, MSK3, MSK2, MSK1); + + r1 = _mm_load_si128(&sfmt[N - 2].si); + r2 = _mm_load_si128(&sfmt[N - 1].si); + for (i = 0; i < N - POS1; i++) { + r = mm_recursion(&sfmt[i].si, &sfmt[i + POS1].si, r1, r2, mask); + _mm_store_si128(&array[i].si, r); + r1 = r2; + r2 = r; + } + for (; i < N; i++) { + r = mm_recursion(&sfmt[i].si, &array[i + POS1 - N].si, r1, r2, mask); + _mm_store_si128(&array[i].si, r); + r1 = r2; + r2 = r; + } + /* main loop */ + for (; i < size - N; i++) { + r = mm_recursion(&array[i - N].si, &array[i + POS1 - N].si, r1, r2, + mask); + _mm_store_si128(&array[i].si, r); + r1 = r2; + r2 = r; + } + for (j = 0; j < 2 * N - size; j++) { + r = _mm_load_si128(&array[j + size - N].si); + _mm_store_si128(&sfmt[j].si, r); + } + for (; i < size; i++) { + r = mm_recursion(&array[i - N].si, &array[i + POS1 - N].si, r1, r2, + mask); + _mm_store_si128(&array[i].si, r); + _mm_store_si128(&sfmt[j++].si, r); + r1 = r2; + r2 = r; + } +} + +#endif diff --git a/dep/SFMT/SFMT.c b/dep/SFMT/SFMT.c new file mode 100644 index 00000000000..d36465d9e14 --- /dev/null +++ b/dep/SFMT/SFMT.c @@ -0,0 +1,620 @@ +/** + * @file SFMT.c + * @brief SIMD oriented Fast Mersenne Twister(SFMT) + * + * @author Mutsuo Saito (Hiroshima University) + * @author Makoto Matsumoto (Hiroshima University) + * + * Copyright (C) 2006,2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima + * University. All rights reserved. + * + * The new BSD License is applied to this software, see LICENSE.txt + */ +#include +#include +#include "SFMT.h" +#include "SFMT-params.h" + +#if defined(__BIG_ENDIAN__) && !defined(__amd64) && !defined(BIG_ENDIAN64) +#define BIG_ENDIAN64 1 +#endif +#if defined(HAVE_ALTIVEC) && !defined(BIG_ENDIAN64) +#define BIG_ENDIAN64 1 +#endif +#if defined(ONLY64) && !defined(BIG_ENDIAN64) + #if defined(__GNUC__) + #error "-DONLY64 must be specified with -DBIG_ENDIAN64" + #endif +#undef ONLY64 +#endif +/*------------------------------------------------------ + 128-bit SIMD data type for Altivec, SSE2 or standard C + ------------------------------------------------------*/ +#if defined(HAVE_ALTIVEC) + #if !defined(__APPLE__) + #include + #endif +/** 128-bit data structure */ +union W128_T { + vector unsigned int s; + uint32_t u[4]; +}; +/** 128-bit data type */ +typedef union W128_T w128_t; + +#elif defined(HAVE_SSE2) + #include + +/** 128-bit data structure */ +union W128_T { + __m128i si; + uint32_t u[4]; +}; +/** 128-bit data type */ +typedef union W128_T w128_t; + +#else + +/** 128-bit data structure */ +struct W128_T { + uint32_t u[4]; +}; +/** 128-bit data type */ +typedef struct W128_T w128_t; + +#endif + +/*-------------------------------------- + FILE GLOBAL VARIABLES + internal state, index counter and flag + --------------------------------------*/ +/** the 128-bit internal state array */ +static w128_t sfmt[N]; +/** the 32bit integer pointer to the 128-bit internal state array */ +static uint32_t *psfmt32 = &sfmt[0].u[0]; +#if !defined(BIG_ENDIAN64) || defined(ONLY64) +/** the 64bit integer pointer to the 128-bit internal state array */ +static uint64_t *psfmt64 = (uint64_t *)&sfmt[0].u[0]; +#endif +/** index counter to the 32-bit internal state array */ +static int idx; +/** a flag: it is 0 if and only if the internal state is not yet + * initialized. */ +static int initialized = 0; +/** a parity check vector which certificate the period of 2^{MEXP} */ +static uint32_t parity[4] = {PARITY1, PARITY2, PARITY3, PARITY4}; + +/*---------------- + STATIC FUNCTIONS + ----------------*/ +inline static int idxof(int i); +inline static void rshift128(w128_t *out, w128_t const *in, int shift); +inline static void lshift128(w128_t *out, w128_t const *in, int shift); +inline static void gen_rand_all(void); +inline static void gen_rand_array(w128_t *array, int size); +inline static uint32_t func1(uint32_t x); +inline static uint32_t func2(uint32_t x); +static void period_certification(void); +#if defined(BIG_ENDIAN64) && !defined(ONLY64) +inline static void swap(w128_t *array, int size); +#endif + +#if defined(HAVE_ALTIVEC) + #include "SFMT-alti.h" +#elif defined(HAVE_SSE2) + #include "SFMT-sse2.h" +#endif + +/** + * This function simulate a 64-bit index of LITTLE ENDIAN + * in BIG ENDIAN machine. + */ +#ifdef ONLY64 +inline static int idxof(int i) { + return i ^ 1; +} +#else +inline static int idxof(int i) { + return i; +} +#endif +/** + * This function simulates SIMD 128-bit right shift by the standard C. + * The 128-bit integer given in in is shifted by (shift * 8) bits. + * This function simulates the LITTLE ENDIAN SIMD. + * @param out the output of this function + * @param in the 128-bit data to be shifted + * @param shift the shift value + */ +#ifdef ONLY64 +inline static void rshift128(w128_t *out, w128_t const *in, int shift) { + uint64_t th, tl, oh, ol; + + th = ((uint64_t)in->u[2] << 32) | ((uint64_t)in->u[3]); + tl = ((uint64_t)in->u[0] << 32) | ((uint64_t)in->u[1]); + + oh = th >> (shift * 8); + ol = tl >> (shift * 8); + ol |= th << (64 - shift * 8); + out->u[0] = (uint32_t)(ol >> 32); + out->u[1] = (uint32_t)ol; + out->u[2] = (uint32_t)(oh >> 32); + out->u[3] = (uint32_t)oh; +} +#else +inline static void rshift128(w128_t *out, w128_t const *in, int shift) { + uint64_t th, tl, oh, ol; + + th = ((uint64_t)in->u[3] << 32) | ((uint64_t)in->u[2]); + tl = ((uint64_t)in->u[1] << 32) | ((uint64_t)in->u[0]); + + oh = th >> (shift * 8); + ol = tl >> (shift * 8); + ol |= th << (64 - shift * 8); + out->u[1] = (uint32_t)(ol >> 32); + out->u[0] = (uint32_t)ol; + out->u[3] = (uint32_t)(oh >> 32); + out->u[2] = (uint32_t)oh; +} +#endif +/** + * This function simulates SIMD 128-bit left shift by the standard C. + * The 128-bit integer given in in is shifted by (shift * 8) bits. + * This function simulates the LITTLE ENDIAN SIMD. + * @param out the output of this function + * @param in the 128-bit data to be shifted + * @param shift the shift value + */ +#ifdef ONLY64 +inline static void lshift128(w128_t *out, w128_t const *in, int shift) { + uint64_t th, tl, oh, ol; + + th = ((uint64_t)in->u[2] << 32) | ((uint64_t)in->u[3]); + tl = ((uint64_t)in->u[0] << 32) | ((uint64_t)in->u[1]); + + oh = th << (shift * 8); + ol = tl << (shift * 8); + oh |= tl >> (64 - shift * 8); + out->u[0] = (uint32_t)(ol >> 32); + out->u[1] = (uint32_t)ol; + out->u[2] = (uint32_t)(oh >> 32); + out->u[3] = (uint32_t)oh; +} +#else +inline static void lshift128(w128_t *out, w128_t const *in, int shift) { + uint64_t th, tl, oh, ol; + + th = ((uint64_t)in->u[3] << 32) | ((uint64_t)in->u[2]); + tl = ((uint64_t)in->u[1] << 32) | ((uint64_t)in->u[0]); + + oh = th << (shift * 8); + ol = tl << (shift * 8); + oh |= tl >> (64 - shift * 8); + out->u[1] = (uint32_t)(ol >> 32); + out->u[0] = (uint32_t)ol; + out->u[3] = (uint32_t)(oh >> 32); + out->u[2] = (uint32_t)oh; +} +#endif + +/** + * This function represents the recursion formula. + * @param r output + * @param a a 128-bit part of the internal state array + * @param b a 128-bit part of the internal state array + * @param c a 128-bit part of the internal state array + * @param d a 128-bit part of the internal state array + */ +#if (!defined(HAVE_ALTIVEC)) && (!defined(HAVE_SSE2)) +#ifdef ONLY64 +inline static void do_recursion(w128_t *r, w128_t *a, w128_t *b, w128_t *c, + w128_t *d) { + w128_t x; + w128_t y; + + lshift128(&x, a, SL2); + rshift128(&y, c, SR2); + r->u[0] = a->u[0] ^ x.u[0] ^ ((b->u[0] >> SR1) & MSK2) ^ y.u[0] + ^ (d->u[0] << SL1); + r->u[1] = a->u[1] ^ x.u[1] ^ ((b->u[1] >> SR1) & MSK1) ^ y.u[1] + ^ (d->u[1] << SL1); + r->u[2] = a->u[2] ^ x.u[2] ^ ((b->u[2] >> SR1) & MSK4) ^ y.u[2] + ^ (d->u[2] << SL1); + r->u[3] = a->u[3] ^ x.u[3] ^ ((b->u[3] >> SR1) & MSK3) ^ y.u[3] + ^ (d->u[3] << SL1); +} +#else +inline static void do_recursion(w128_t *r, w128_t *a, w128_t *b, w128_t *c, + w128_t *d) { + w128_t x; + w128_t y; + + lshift128(&x, a, SL2); + rshift128(&y, c, SR2); + r->u[0] = a->u[0] ^ x.u[0] ^ ((b->u[0] >> SR1) & MSK1) ^ y.u[0] + ^ (d->u[0] << SL1); + r->u[1] = a->u[1] ^ x.u[1] ^ ((b->u[1] >> SR1) & MSK2) ^ y.u[1] + ^ (d->u[1] << SL1); + r->u[2] = a->u[2] ^ x.u[2] ^ ((b->u[2] >> SR1) & MSK3) ^ y.u[2] + ^ (d->u[2] << SL1); + r->u[3] = a->u[3] ^ x.u[3] ^ ((b->u[3] >> SR1) & MSK4) ^ y.u[3] + ^ (d->u[3] << SL1); +} +#endif +#endif + +#if (!defined(HAVE_ALTIVEC)) && (!defined(HAVE_SSE2)) +/** + * This function fills the internal state array with pseudorandom + * integers. + */ +inline static void gen_rand_all(void) { + int i; + w128_t *r1, *r2; + + r1 = &sfmt[N - 2]; + r2 = &sfmt[N - 1]; + for (i = 0; i < N - POS1; i++) { + do_recursion(&sfmt[i], &sfmt[i], &sfmt[i + POS1], r1, r2); + r1 = r2; + r2 = &sfmt[i]; + } + for (; i < N; i++) { + do_recursion(&sfmt[i], &sfmt[i], &sfmt[i + POS1 - N], r1, r2); + r1 = r2; + r2 = &sfmt[i]; + } +} + +/** + * This function fills the user-specified array with pseudorandom + * integers. + * + * @param array an 128-bit array to be filled by pseudorandom numbers. + * @param size number of 128-bit pseudorandom numbers to be generated. + */ +inline static void gen_rand_array(w128_t *array, int size) { + int i, j; + w128_t *r1, *r2; + + r1 = &sfmt[N - 2]; + r2 = &sfmt[N - 1]; + for (i = 0; i < N - POS1; i++) { + do_recursion(&array[i], &sfmt[i], &sfmt[i + POS1], r1, r2); + r1 = r2; + r2 = &array[i]; + } + for (; i < N; i++) { + do_recursion(&array[i], &sfmt[i], &array[i + POS1 - N], r1, r2); + r1 = r2; + r2 = &array[i]; + } + for (; i < size - N; i++) { + do_recursion(&array[i], &array[i - N], &array[i + POS1 - N], r1, r2); + r1 = r2; + r2 = &array[i]; + } + for (j = 0; j < 2 * N - size; j++) { + sfmt[j] = array[j + size - N]; + } + for (; i < size; i++, j++) { + do_recursion(&array[i], &array[i - N], &array[i + POS1 - N], r1, r2); + r1 = r2; + r2 = &array[i]; + sfmt[j] = array[i]; + } +} +#endif + +#if defined(BIG_ENDIAN64) && !defined(ONLY64) && !defined(HAVE_ALTIVEC) +inline static void swap(w128_t *array, int size) { + int i; + uint32_t x, y; + + for (i = 0; i < size; i++) { + x = array[i].u[0]; + y = array[i].u[2]; + array[i].u[0] = array[i].u[1]; + array[i].u[2] = array[i].u[3]; + array[i].u[1] = x; + array[i].u[3] = y; + } +} +#endif +/** + * This function represents a function used in the initialization + * by init_by_array + * @param x 32-bit integer + * @return 32-bit integer + */ +static uint32_t func1(uint32_t x) { + return (x ^ (x >> 27)) * (uint32_t)1664525UL; +} + +/** + * This function represents a function used in the initialization + * by init_by_array + * @param x 32-bit integer + * @return 32-bit integer + */ +static uint32_t func2(uint32_t x) { + return (x ^ (x >> 27)) * (uint32_t)1566083941UL; +} + +/** + * This function certificate the period of 2^{MEXP} + */ +static void period_certification(void) { + int inner = 0; + int i, j; + uint32_t work; + + for (i = 0; i < 4; i++) + inner ^= psfmt32[idxof(i)] & parity[i]; + for (i = 16; i > 0; i >>= 1) + inner ^= inner >> i; + inner &= 1; + /* check OK */ + if (inner == 1) { + return; + } + /* check NG, and modification */ + for (i = 0; i < 4; i++) { + work = 1; + for (j = 0; j < 32; j++) { + if ((work & parity[i]) != 0) { + psfmt32[idxof(i)] ^= work; + return; + } + work = work << 1; + } + } +} + +/*---------------- + PUBLIC FUNCTIONS + ----------------*/ +/** + * This function returns the identification string. + * The string shows the word size, the Mersenne exponent, + * and all parameters of this generator. + */ +const char *get_idstring(void) { + return IDSTR; +} + +/** + * This function returns the minimum size of array used for \b + * fill_array32() function. + * @return minimum size of array used for fill_array32() function. + */ +int get_min_array_size32(void) { + return N32; +} + +/** + * This function returns the minimum size of array used for \b + * fill_array64() function. + * @return minimum size of array used for fill_array64() function. + */ +int get_min_array_size64(void) { + return N64; +} + +#ifndef ONLY64 +/** + * This function generates and returns 32-bit pseudorandom number. + * init_gen_rand or init_by_array must be called before this function. + * @return 32-bit pseudorandom number + */ +uint32_t gen_rand32(void) { + uint32_t r; + + assert(initialized); + if (idx >= N32) { + gen_rand_all(); + idx = 0; + } + r = psfmt32[idx++]; + return r; +} +#endif +/** + * This function generates and returns 64-bit pseudorandom number. + * init_gen_rand or init_by_array must be called before this function. + * The function gen_rand64 should not be called after gen_rand32, + * unless an initialization is again executed. + * @return 64-bit pseudorandom number + */ +uint64_t gen_rand64(void) { +#if defined(BIG_ENDIAN64) && !defined(ONLY64) + uint32_t r1, r2; +#else + uint64_t r; +#endif + + assert(initialized); + assert(idx % 2 == 0); + + if (idx >= N32) { + gen_rand_all(); + idx = 0; + } +#if defined(BIG_ENDIAN64) && !defined(ONLY64) + r1 = psfmt32[idx]; + r2 = psfmt32[idx + 1]; + idx += 2; + return ((uint64_t)r2 << 32) | r1; +#else + r = psfmt64[idx / 2]; + idx += 2; + return r; +#endif +} + +#ifndef ONLY64 +/** + * This function generates pseudorandom 32-bit integers in the + * specified array[] by one call. The number of pseudorandom integers + * is specified by the argument size, which must be at least 624 and a + * multiple of four. The generation by this function is much faster + * than the following gen_rand function. + * + * For initialization, init_gen_rand or init_by_array must be called + * before the first call of this function. This function can not be + * used after calling gen_rand function, without initialization. + * + * @param array an array where pseudorandom 32-bit integers are filled + * by this function. The pointer to the array must be \b "aligned" + * (namely, must be a multiple of 16) in the SIMD version, since it + * refers to the address of a 128-bit integer. In the standard C + * version, the pointer is arbitrary. + * + * @param size the number of 32-bit pseudorandom integers to be + * generated. size must be a multiple of 4, and greater than or equal + * to (MEXP / 128 + 1) * 4. + * + * @note \b memalign or \b posix_memalign is available to get aligned + * memory. Mac OSX doesn't have these functions, but \b malloc of OSX + * returns the pointer to the aligned memory block. + */ +void fill_array32(uint32_t *array, int size) { + assert(initialized); + assert(idx == N32); + assert(size % 4 == 0); + assert(size >= N32); + + gen_rand_array((w128_t *)array, size / 4); + idx = N32; +} +#endif + +/** + * This function generates pseudorandom 64-bit integers in the + * specified array[] by one call. The number of pseudorandom integers + * is specified by the argument size, which must be at least 312 and a + * multiple of two. The generation by this function is much faster + * than the following gen_rand function. + * + * For initialization, init_gen_rand or init_by_array must be called + * before the first call of this function. This function can not be + * used after calling gen_rand function, without initialization. + * + * @param array an array where pseudorandom 64-bit integers are filled + * by this function. The pointer to the array must be "aligned" + * (namely, must be a multiple of 16) in the SIMD version, since it + * refers to the address of a 128-bit integer. In the standard C + * version, the pointer is arbitrary. + * + * @param size the number of 64-bit pseudorandom integers to be + * generated. size must be a multiple of 2, and greater than or equal + * to (MEXP / 128 + 1) * 2 + * + * @note \b memalign or \b posix_memalign is available to get aligned + * memory. Mac OSX doesn't have these functions, but \b malloc of OSX + * returns the pointer to the aligned memory block. + */ +void fill_array64(uint64_t *array, int size) { + assert(initialized); + assert(idx == N32); + assert(size % 2 == 0); + assert(size >= N64); + + gen_rand_array((w128_t *)array, size / 2); + idx = N32; + +#if defined(BIG_ENDIAN64) && !defined(ONLY64) + swap((w128_t *)array, size /2); +#endif +} + +/** + * This function initializes the internal state array with a 32-bit + * integer seed. + * + * @param seed a 32-bit integer used as the seed. + */ +void init_gen_rand(uint32_t seed) { + int i; + + psfmt32[idxof(0)] = seed; + for (i = 1; i < N32; i++) { + psfmt32[idxof(i)] = 1812433253UL * (psfmt32[idxof(i - 1)] + ^ (psfmt32[idxof(i - 1)] >> 30)) + + i; + } + idx = N32; + period_certification(); + initialized = 1; +} + +/** + * This function initializes the internal state array, + * with an array of 32-bit integers used as the seeds + * @param init_key the array of 32-bit integers, used as a seed. + * @param key_length the length of init_key. + */ +void init_by_array(uint32_t *init_key, int key_length) { + int i, j, count; + uint32_t r; + int lag; + int mid; + int size = N * 4; + + if (size >= 623) { + lag = 11; + } else if (size >= 68) { + lag = 7; + } else if (size >= 39) { + lag = 5; + } else { + lag = 3; + } + mid = (size - lag) / 2; + + memset(sfmt, 0x8b, sizeof(sfmt)); + if (key_length + 1 > N32) { + count = key_length + 1; + } else { + count = N32; + } + r = func1(psfmt32[idxof(0)] ^ psfmt32[idxof(mid)] + ^ psfmt32[idxof(N32 - 1)]); + psfmt32[idxof(mid)] += r; + r += key_length; + psfmt32[idxof(mid + lag)] += r; + psfmt32[idxof(0)] = r; + + count--; + for (i = 1, j = 0; (j < count) && (j < key_length); j++) { + r = func1(psfmt32[idxof(i)] ^ psfmt32[idxof((i + mid) % N32)] + ^ psfmt32[idxof((i + N32 - 1) % N32)]); + psfmt32[idxof((i + mid) % N32)] += r; + r += init_key[j] + i; + psfmt32[idxof((i + mid + lag) % N32)] += r; + psfmt32[idxof(i)] = r; + i = (i + 1) % N32; + } + for (; j < count; j++) { + r = func1(psfmt32[idxof(i)] ^ psfmt32[idxof((i + mid) % N32)] + ^ psfmt32[idxof((i + N32 - 1) % N32)]); + psfmt32[idxof((i + mid) % N32)] += r; + r += i; + psfmt32[idxof((i + mid + lag) % N32)] += r; + psfmt32[idxof(i)] = r; + i = (i + 1) % N32; + } + for (j = 0; j < N32; j++) { + r = func2(psfmt32[idxof(i)] + psfmt32[idxof((i + mid) % N32)] + + psfmt32[idxof((i + N32 - 1) % N32)]); + psfmt32[idxof((i + mid) % N32)] ^= r; + r -= i; + psfmt32[idxof((i + mid + lag) % N32)] ^= r; + psfmt32[idxof(i)] = r; + i = (i + 1) % N32; + } + + idx = N32; + period_certification(); + initialized = 1; +} diff --git a/dep/SFMT/SFMT.h b/dep/SFMT/SFMT.h new file mode 100644 index 00000000000..7c8b35e9e95 --- /dev/null +++ b/dep/SFMT/SFMT.h @@ -0,0 +1,157 @@ +/** + * @file SFMT.h + * + * @brief SIMD oriented Fast Mersenne Twister(SFMT) pseudorandom + * number generator + * + * @author Mutsuo Saito (Hiroshima University) + * @author Makoto Matsumoto (Hiroshima University) + * + * Copyright (C) 2006, 2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima + * University. All rights reserved. + * + * The new BSD License is applied to this software. + * see LICENSE.txt + * + * @note We assume that your system has inttypes.h. If your system + * doesn't have inttypes.h, you have to typedef uint32_t and uint64_t, + * and you have to define PRIu64 and PRIx64 in this file as follows: + * @verbatim + typedef unsigned int uint32_t + typedef unsigned long long uint64_t + #define PRIu64 "llu" + #define PRIx64 "llx" +@endverbatim + * uint32_t must be exactly 32-bit unsigned integer type (no more, no + * less), and uint64_t must be exactly 64-bit unsigned integer type. + * PRIu64 and PRIx64 are used for printf function to print 64-bit + * unsigned int and 64-bit unsigned int in hexadecimal format. + */ + +#ifndef SFMT_H +#define SFMT_H + +#include + +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) + #include +#elif defined(_MSC_VER) || defined(__BORLANDC__) + typedef unsigned int uint32_t; + typedef unsigned __int64 uint64_t; + #define inline __inline +#else + #include + #if defined(__GNUC__) + #define inline __inline__ + #endif +#endif + +#ifndef PRIu64 + #if defined(_MSC_VER) || defined(__BORLANDC__) + #define PRIu64 "I64u" + #define PRIx64 "I64x" + #else + #define PRIu64 "llu" + #define PRIx64 "llx" + #endif +#endif + +#if defined(__GNUC__) +#define ALWAYSINLINE __attribute__((always_inline)) +#else +#define ALWAYSINLINE +#endif + +#if defined(_MSC_VER) + #if _MSC_VER >= 1200 + #define PRE_ALWAYS __forceinline + #else + #define PRE_ALWAYS inline + #endif +#else + #define PRE_ALWAYS inline +#endif + +uint32_t gen_rand32(void); +uint64_t gen_rand64(void); +void fill_array32(uint32_t *array, int size); +void fill_array64(uint64_t *array, int size); +void init_gen_rand(uint32_t seed); +void init_by_array(uint32_t *init_key, int key_length); +const char *get_idstring(void); +int get_min_array_size32(void); +int get_min_array_size64(void); + +/* These real versions are due to Isaku Wada */ +/** generates a random number on [0,1]-real-interval */ +inline static double to_real1(uint32_t v) +{ + return v * (1.0/4294967295.0); + /* divided by 2^32-1 */ +} + +/** generates a random number on [0,1]-real-interval */ +inline static double genrand_real1(void) +{ + return to_real1(gen_rand32()); +} + +/** generates a random number on [0,1)-real-interval */ +inline static double to_real2(uint32_t v) +{ + return v * (1.0/4294967296.0); + /* divided by 2^32 */ +} + +/** generates a random number on [0,1)-real-interval */ +inline static double genrand_real2(void) +{ + return to_real2(gen_rand32()); +} + +/** generates a random number on (0,1)-real-interval */ +inline static double to_real3(uint32_t v) +{ + return (((double)v) + 0.5)*(1.0/4294967296.0); + /* divided by 2^32 */ +} + +/** generates a random number on (0,1)-real-interval */ +inline static double genrand_real3(void) +{ + return to_real3(gen_rand32()); +} +/** These real versions are due to Isaku Wada */ + +/** generates a random number on [0,1) with 53-bit resolution*/ +inline static double to_res53(uint64_t v) +{ + return v * (1.0/18446744073709551616.0L); +} + +/** generates a random number on [0,1) with 53-bit resolution from two + * 32 bit integers */ +inline static double to_res53_mix(uint32_t x, uint32_t y) +{ + return to_res53(x | ((uint64_t)y << 32)); +} + +/** generates a random number on [0,1) with 53-bit resolution + */ +inline static double genrand_res53(void) +{ + return to_res53(gen_rand64()); +} + +/** generates a random number on [0,1) with 53-bit resolution + using 32bit integer. + */ +inline static double genrand_res53_mix(void) +{ + uint32_t x, y; + + x = gen_rand32(); + y = gen_rand32(); + return to_res53_mix(x, y); +} +#endif diff --git a/dep/acelite/CMakeLists.txt b/dep/acelite/CMakeLists.txt new file mode 100644 index 00000000000..a4412d9721e --- /dev/null +++ b/dep/acelite/CMakeLists.txt @@ -0,0 +1 @@ +add_subdirectory(ace) diff --git a/dep/acelite/ace/ACE.cpp b/dep/acelite/ace/ACE.cpp new file mode 100644 index 00000000000..3dd5e2e6f9b --- /dev/null +++ b/dep/acelite/ace/ACE.cpp @@ -0,0 +1,3517 @@ +// $Id: ACE.cpp 91066 2010-07-12 11:05:04Z johnnyw $ + +#include "ace/ACE.h" + +#include "ace/Basic_Types.h" +#include "ace/Handle_Set.h" +#include "ace/Auto_Ptr.h" +#include "ace/SString.h" +#include "ace/Version.h" +#include "ace/Message_Block.h" +#include "ace/Log_Msg.h" +#include "ace/OS_NS_sys_select.h" +#include "ace/OS_NS_string.h" +#include "ace/OS_NS_strings.h" +#include "ace/OS_NS_signal.h" +#include "ace/OS_NS_stdio.h" +#include "ace/OS_NS_sys_resource.h" +#include "ace/OS_NS_sys_wait.h" +#include "ace/OS_NS_sys_time.h" +#include "ace/OS_NS_time.h" +#include "ace/OS_NS_sys_uio.h" +#include "ace/OS_NS_sys_stat.h" +#include "ace/OS_NS_ctype.h" +#include "ace/OS_NS_fcntl.h" +#include "ace/OS_TLI.h" +#include "ace/Truncate.h" + +#if defined (ACE_VXWORKS) && (ACE_VXWORKS < 0x620) +extern "C" int maxFiles; +#endif /* ACE_VXWORKS */ + +#if !defined (__ACE_INLINE__) +#include "ace/ACE.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_HAS_POLL) && defined (ACE_HAS_LIMITED_SELECT) +# include "ace/OS_NS_poll.h" +#endif /* ACE_HAS_POLL && ACE_HAS_LIMITED_SELECT */ + + +ACE_RCSID (ace, + ACE, + "$Id: ACE.cpp 91066 2010-07-12 11:05:04Z johnnyw $") + + +// Open versioned namespace, if enabled by the user. + ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +namespace ACE +{ + // private: + // Used internally so not exported. + + // Size of allocation granularity. + size_t allocation_granularity_ = 0; + + // Size of a VM page. + size_t pagesize_ = 0; + + // Are we debugging ACE? + // Keeps track of whether we're in some global debug mode. + char debug_; +} + + +int +ACE::out_of_handles (int error) +{ + // EMFILE is common to all platforms. + if (error == EMFILE || +#if defined (ACE_WIN32) + // On Win32, we need to check for ENOBUFS also. + error == ENOBUFS || +#elif defined (HPUX) + // On HPUX, we need to check for EADDRNOTAVAIL also. + error == EADDRNOTAVAIL || +#elif defined (linux) + // On linux, we need to check for ENOENT also. + error == ENOENT || + // For RedHat5.2, need to check for EINVAL too. + error == EINVAL || + // Without threads check for EOPNOTSUPP + error == EOPNOTSUPP || +#elif defined (sun) + // On sun, we need to check for ENOSR also. + error == ENOSR || + // Without threads check for ENOTSUP + error == ENOTSUP || +#elif defined (__FreeBSD__) + // On FreeBSD we need to check for EOPNOTSUPP (LinuxThreads) or + // ENOSYS (libc_r threads) also. + error == EOPNOTSUPP || + error == ENOSYS || +#elif defined (__OpenBSD__) + // OpenBSD appears to return EBADF. + error == EBADF || +#elif defined (__sgi) // irix + error == ENOTSUP || +#elif defined (DIGITAL_UNIX) // osf1 + error == ENOTSUP || +#endif /* ACE_WIN32 */ + error == ENFILE) + return 1; + else + return 0; +} + +u_int +ACE::major_version (void) +{ + return ACE_MAJOR_VERSION; +} + +u_int +ACE::minor_version (void) +{ + return ACE_MINOR_VERSION; +} + +u_int +ACE::beta_version (void) +{ + return ACE_BETA_VERSION; +} + +const ACE_TCHAR * +ACE::compiler_name (void) +{ +#ifdef ACE_CC_NAME + return ACE_CC_NAME; +#else + return ACE_TEXT (""); +#endif +} + +u_int +ACE::compiler_major_version (void) +{ +#ifdef ACE_CC_MAJOR_VERSION + return ACE_CC_MAJOR_VERSION; +#else + return 0; +#endif +} + +u_int +ACE::compiler_minor_version (void) +{ +#ifdef ACE_CC_MINOR_VERSION + return ACE_CC_MINOR_VERSION; +#else + return 0; +#endif +} + +u_int +ACE::compiler_beta_version (void) +{ +#ifdef ACE_CC_BETA_VERSION + return ACE_CC_BETA_VERSION; +#else + return 0; +#endif +} + +ACE_TCHAR +ACE::nibble2hex (u_int n) +{ + // Yes, this works for UNICODE + return ACE_TEXT ("0123456789abcdef")[n & 0x0f]; +} + +bool +ACE::debug (void) +{ + static const char* debug = ACE_OS::getenv ("ACE_DEBUG"); + return (ACE::debug_ != 0) ? ACE::debug_ : (debug != 0 ? (*debug != '0') : false); +} + +void +ACE::debug (bool onoff) +{ + ACE::debug_ = onoff; +} + +int +ACE::select (int width, + ACE_Handle_Set *readfds, + ACE_Handle_Set *writefds, + ACE_Handle_Set *exceptfds, + const ACE_Time_Value *timeout) +{ + int result = ACE_OS::select (width, + readfds ? readfds->fdset () : 0, + writefds ? writefds->fdset () : 0, + exceptfds ? exceptfds->fdset () : 0, + timeout); + if (result > 0) + { +# if !defined (ACE_WIN32) + // This isn't needed for Windows... it's a no-op anyway. + if (readfds) + readfds->sync ((ACE_HANDLE) width); + if (writefds) + writefds->sync ((ACE_HANDLE) width); + if (exceptfds) + exceptfds->sync ((ACE_HANDLE) width); +#endif /* ACE_WIN32 */ + } + return result; +} + +int +ACE::select (int width, + ACE_Handle_Set &readfds, + const ACE_Time_Value *timeout) +{ + int result = ACE_OS::select (width, + readfds.fdset (), + 0, + 0, + timeout); + +#if !defined (ACE_WIN32) + if (result > 0) + readfds.sync ((ACE_HANDLE) width); +#endif /* ACE_WIN32 */ + return result; +} + +int +ACE::terminate_process (pid_t pid) +{ +#if defined (ACE_HAS_PHARLAP) + ACE_UNUSED_ARG (pid); + ACE_NOTSUP_RETURN (-1); +#elif defined (ACE_WIN32) + // Create a handle for the given process id. + ACE_HANDLE process_handle = + ::OpenProcess (PROCESS_TERMINATE, + FALSE, // New handle is not inheritable. + pid); + + if (process_handle == ACE_INVALID_HANDLE + || process_handle == 0) + return -1; + else + { + // Kill the process associated with process_handle. + BOOL terminate_result = + ::TerminateProcess (process_handle, 0); + // Free up the kernel resources. + ACE_OS::close (process_handle); + return terminate_result ? 0 : -1; + } +#else + return ACE_OS::kill (pid, 9); +#endif /* ACE_HAS_PHARLAP */ +} + +int +ACE::process_active (pid_t pid) +{ +#if !defined(ACE_WIN32) + if (ACE_OS::kill (pid, 0) == 0) + return 1; + else if (errno == ESRCH) + return 0; + else + return -1; +#else + // Create a handle for the given process id. + ACE_HANDLE process_handle = + ::OpenProcess (PROCESS_QUERY_INFORMATION, FALSE, pid); + if (process_handle == ACE_INVALID_HANDLE || process_handle == 0) + return 0; + else + { + DWORD status; + int result = 1; + if (::GetExitCodeProcess (process_handle, + &status) == 0 + || status != STILL_ACTIVE) + result = 0; + + ::CloseHandle (process_handle); + return result; + } +#endif /* !ACE_WIN32 */ +} + +const ACE_TCHAR * +ACE::execname (const ACE_TCHAR *old_name) +{ +#if defined (ACE_WIN32) + const ACE_TCHAR *suffix = ACE_OS::strrchr (old_name, ACE_TEXT ('.')); + if (suffix == 0 || ACE_OS::strcasecmp (suffix, ACE_TEXT (".exe")) != 0) + { + ACE_TCHAR *new_name = 0; + + size_t size = + ACE_OS::strlen (old_name) + + ACE_OS::strlen (ACE_TEXT (".exe")) + + 1; + + ACE_NEW_RETURN (new_name, + ACE_TCHAR[size], + 0); + ACE_TCHAR *end = new_name; + + end = ACE_OS::strecpy (new_name, old_name); + + // Concatenate the .exe suffix onto the end of the executable. + // end points _after_ the terminating nul. + ACE_OS::strcpy (end - 1, ACE_TEXT (".exe")); + + return new_name; + } +#endif /* ACE_WIN32 */ + return old_name; +} + +u_long +ACE::hash_pjw (const char *str, size_t len) +{ + u_long hash = 0; + + for (size_t i = 0; i < len; i++) + { + const char temp = str[i]; + hash = (hash << 4) + (temp * 13); + + u_long g = hash & 0xf0000000; + + if (g) + { + hash ^= (g >> 24); + hash ^= g; + } + } + + return hash; +} + +u_long +ACE::hash_pjw (const char *str) +{ + return ACE::hash_pjw (str, ACE_OS::strlen (str)); +} + +#if defined (ACE_HAS_WCHAR) +u_long +ACE::hash_pjw (const wchar_t *str, size_t len) +{ + u_long hash = 0; + + for (size_t i = 0; i < len; i++) + { + // @@ UNICODE: Does this function do the correct thing with wchar's? + + const wchar_t temp = str[i]; + hash = (hash << 4) + (temp * 13); + + u_long g = hash & 0xf0000000; + + if (g) + { + hash ^= (g >> 24); + hash ^= g; + } + } + + return hash; +} + +u_long +ACE::hash_pjw (const wchar_t *str) +{ + return ACE::hash_pjw (str, ACE_OS::strlen (str)); +} +#endif /* ACE_HAS_WCHAR */ + +ACE_TCHAR * +ACE::strenvdup (const ACE_TCHAR *str) +{ + ACE_TRACE ("ACE::strenvdup"); + + return ACE_OS::strenvdup (str); +} + +/* + +Examples: + +Source NT UNIX +================================================================== +netsvc netsvc.dll libnetsvc.so +(PATH will be (LD_LIBRARY_PATH +evaluated) evaluated) + +libnetsvc.dll libnetsvc.dll libnetsvc.dll + warning +netsvc.so netsvc.so + warning libnetsvc.so + +..\../libs/netsvc ..\..\libs\netsvc.dll ../../libs/netsvc.so +(absolute path used) (absolute path used) + +*/ + +const ACE_TCHAR * +ACE::basename (const ACE_TCHAR *pathname, ACE_TCHAR delim) +{ + ACE_TRACE ("ACE::basename"); + const ACE_TCHAR *temp = ACE_OS::strrchr (pathname, delim); + + if (temp == 0) + return pathname; + else + return temp + 1; +} + +const ACE_TCHAR * +ACE::dirname (const ACE_TCHAR *pathname, ACE_TCHAR delim) +{ + ACE_TRACE ("ACE::dirname"); + static ACE_TCHAR return_dirname[MAXPATHLEN + 1]; + + const ACE_TCHAR *temp = ACE_OS::strrchr (pathname, delim); + + if (temp == 0) + { + return_dirname[0] = '.'; + return_dirname[1] = '\0'; + + return return_dirname; + } + else + { + // When the len is truncated, there are problems! This should + // not happen in normal circomstances + size_t len = temp - pathname + 1; + if (len > (sizeof return_dirname / sizeof (ACE_TCHAR))) + len = sizeof return_dirname / sizeof (ACE_TCHAR); + + ACE_OS::strsncpy (return_dirname, + pathname, + len); + return return_dirname; + } +} + +ssize_t +ACE::recv (ACE_HANDLE handle, + void *buf, + size_t len, + int flags, + const ACE_Time_Value *timeout) +{ + if (timeout == 0) + return ACE_OS::recv (handle, (char *) buf, len, flags); + else + { + int val = 0; + if (ACE::enter_recv_timedwait (handle, timeout, val) ==-1) + return -1; + else + { + ssize_t bytes_transferred = + ACE_OS::recv (handle, (char *) buf, len, flags); + ACE::restore_non_blocking_mode (handle, val); + return bytes_transferred; + } + } +} + +#if defined (ACE_HAS_TLI) + +ssize_t +ACE::t_rcv (ACE_HANDLE handle, + void *buf, + size_t len, + int *flags, + const ACE_Time_Value *timeout) +{ + if (timeout == 0) + return ACE_OS::t_rcv (handle, (char *) buf, len, flags); + else + { + int val = 0; + if (ACE::enter_recv_timedwait (handle, timeout, val) ==-1) + return -1; + else + { + ssize_t bytes_transferred = + ACE_OS::t_rcv (handle, (char *) buf, len, flags); + ACE::restore_non_blocking_mode (handle, val); + return bytes_transferred; + } + } +} + +#endif /* ACE_HAS_TLI */ + +ssize_t +ACE::recv (ACE_HANDLE handle, + void *buf, + size_t n, + const ACE_Time_Value *timeout) +{ + if (timeout == 0) + return ACE::recv_i (handle, buf, n); + else + { + int val = 0; + if (ACE::enter_recv_timedwait (handle, timeout, val) == -1) + return -1; + else + { + ssize_t bytes_transferred = ACE::recv_i (handle, buf, n); + ACE::restore_non_blocking_mode (handle, val); + return bytes_transferred; + } + } +} + +ssize_t +ACE::recvmsg (ACE_HANDLE handle, + struct msghdr *msg, + int flags, + const ACE_Time_Value *timeout) +{ + if (timeout == 0) + return ACE_OS::recvmsg (handle, msg, flags); + else + { + int val = 0; + if (ACE::enter_recv_timedwait (handle, timeout, val) == -1) + return -1; + else + { + ssize_t bytes_transferred = ACE_OS::recvmsg (handle, msg, flags); + ACE::restore_non_blocking_mode (handle, val); + return bytes_transferred; + } + } +} + +ssize_t +ACE::recvfrom (ACE_HANDLE handle, + char *buf, + int len, + int flags, + struct sockaddr *addr, + int *addrlen, + const ACE_Time_Value *timeout) +{ + if (timeout == 0) + return ACE_OS::recvfrom (handle, buf, len, flags, addr, addrlen); + else + { + int val = 0; + if (ACE::enter_recv_timedwait (handle, timeout, val) == -1) + return -1; + else + { + ssize_t bytes_transferred = + ACE_OS::recvfrom (handle, buf, len, flags, addr, addrlen); + ACE::restore_non_blocking_mode (handle, val); + return bytes_transferred; + } + } +} + +ssize_t +ACE::recv_n_i (ACE_HANDLE handle, + void *buf, + size_t len, + int flags, + size_t *bt) +{ + size_t temp; + size_t &bytes_transferred = bt == 0 ? temp : *bt; + ssize_t n; + + for (bytes_transferred = 0; + bytes_transferred < len; + bytes_transferred += n) + { + // Try to transfer as much of the remaining data as possible. + n = ACE_OS::recv (handle, + static_cast (buf) + bytes_transferred, + len - bytes_transferred, + flags); + // Check EOF. + if (n == 0) + return 0; + + // Check for other errors. + if (n == -1) + { + // Check for possible blocking. + if (errno == EWOULDBLOCK) + { + // Wait for the blocking to subside. + int const result = ACE::handle_read_ready (handle, 0); + + // Did select() succeed? + if (result != -1) + { + // Blocking subsided. Continue data transfer. + n = 0; + continue; + } + } + + // Other data transfer or select() failures. + return -1; + } + } + + return static_cast (bytes_transferred); +} + +ssize_t +ACE::recv_n_i (ACE_HANDLE handle, + void *buf, + size_t len, + int flags, + const ACE_Time_Value *timeout, + size_t *bt) +{ + size_t temp; + size_t &bytes_transferred = bt == 0 ? temp : *bt; + ssize_t n; + ssize_t result = 0; + int error = 0; + + int val = 0; + ACE::record_and_set_non_blocking_mode (handle, val); + + for (bytes_transferred = 0; + bytes_transferred < len; + bytes_transferred += n) + { + // Try to transfer as much of the remaining data as possible. + // Since the socket is in non-blocking mode, this call will not + // block. + n = ACE_OS::recv (handle, + static_cast (buf) + bytes_transferred, + len - bytes_transferred, + flags); + + // Check for errors. + if (n == 0 || + n == -1) + { + // Check for possible blocking. + if (n == -1 && + errno == EWOULDBLOCK) + { + // Wait upto for the blocking to subside. + int const rtn = ACE::handle_read_ready (handle, timeout); + + // Did select() succeed? + if (rtn != -1) + { + // Blocking subsided in period. Continue + // data transfer. + n = 0; + continue; + } + } + + // Wait in select() timed out or other data transfer or + // select() failures. + error = 1; + result = n; + break; + } + } + + ACE::restore_non_blocking_mode (handle, val); + + if (error) + return result; + else + return static_cast (bytes_transferred); +} + +#if defined (ACE_HAS_TLI) + +ssize_t +ACE::t_rcv_n_i (ACE_HANDLE handle, + void *buf, + size_t len, + int *flags, + size_t *bt) +{ + size_t temp; + size_t &bytes_transferred = bt == 0 ? temp : *bt; + ssize_t n; + + for (bytes_transferred = 0; + bytes_transferred < len; + bytes_transferred += n) + { + // Try to transfer as much of the remaining data as possible. + n = ACE_OS::t_rcv (handle, + (char *) buf + bytes_transferred, + len - bytes_transferred, + flags); + // Check EOF. + if (n == 0) + return 0; + + // Check for other errors. + if (n == -1) + { + // Check for possible blocking. + if (errno == EWOULDBLOCK) + { + // Wait for the blocking to subside. + int const result = ACE::handle_read_ready (handle, 0); + + // Did select() succeed? + if (result != -1) + { + // Blocking subsided. Continue data transfer. + n = 0; + continue; + } + } + + // Other data transfer or select() failures. + return -1; + } + } + + return bytes_transferred; +} + +ssize_t +ACE::t_rcv_n_i (ACE_HANDLE handle, + void *buf, + size_t len, + int *flags, + const ACE_Time_Value *timeout, + size_t *bt) +{ + size_t temp; + size_t &bytes_transferred = bt == 0 ? temp : *bt; + ssize_t n; + ssize_t result = 0; + int error = 0; + + int val = 0; + ACE::record_and_set_non_blocking_mode (handle, val); + + for (bytes_transferred = 0; + bytes_transferred < len; + bytes_transferred += n) + { + // Try to transfer as much of the remaining data as possible. + // Since the socket is in non-blocking mode, this call will not + // block. + n = ACE_OS::t_rcv (handle, + (char *) buf + bytes_transferred, + len - bytes_transferred, + flags); + + // Check for errors. + if (n == 0 || + n == -1) + { + // Check for possible blocking. + if (n == -1 && + errno == EWOULDBLOCK) + { + // Wait upto for the blocking to subside. + int const rtn = ACE::handle_read_ready (handle, timeout); + + // Did select() succeed? + if (rtn != -1) + { + // Blocking subsided in period. Continue + // data transfer. + n = 0; + continue; + } + } + + // Wait in select() timed out or other data transfer or + // select() failures. + error = 1; + result = n; + break; + } + } + + ACE::restore_non_blocking_mode (handle, val); + + if (error) + return result; + else + return bytes_transferred; +} + +#endif /* ACE_HAS_TLI */ + +ssize_t +ACE::recv_n_i (ACE_HANDLE handle, + void *buf, + size_t len, + size_t *bt) +{ + size_t temp; + size_t &bytes_transferred = bt == 0 ? temp : *bt; + ssize_t n; + + for (bytes_transferred = 0; + bytes_transferred < len; + bytes_transferred += n) + { + // Try to transfer as much of the remaining data as possible. + n = ACE::recv_i (handle, + static_cast (buf) + bytes_transferred, + len - bytes_transferred); + // Check EOF. + if (n == 0) + { + return 0; + } + // Check for other errors. + if (n == -1) + { + // Check for possible blocking. + if (errno == EWOULDBLOCK) + { + // Wait for the blocking to subside. + int const result = ACE::handle_read_ready (handle, 0); + + // Did select() succeed? + if (result != -1) + { + // Blocking subsided. Continue data transfer. + n = 0; + continue; + } + } + + // Other data transfer or select() failures. + return -1; + } + } + + return static_cast (bytes_transferred); +} + +ssize_t +ACE::recv_n_i (ACE_HANDLE handle, + void *buf, + size_t len, + const ACE_Time_Value *timeout, + size_t *bt) +{ + size_t temp; + size_t &bytes_transferred = bt == 0 ? temp : *bt; + ssize_t n; + ssize_t result = 0; + int error = 0; + + int val = 0; + ACE::record_and_set_non_blocking_mode (handle, val); + + for (bytes_transferred = 0; + bytes_transferred < len; + bytes_transferred += n) + { + // Try to transfer as much of the remaining data as possible. + // Since the socket is in non-blocking mode, this call will not + // block. + n = ACE::recv_i (handle, + static_cast (buf) + bytes_transferred, + len - bytes_transferred); + + // Check for errors. + if (n == 0 || + n == -1) + { + // Check for possible blocking. + if (n == -1 && + errno == EWOULDBLOCK) + { + // Wait upto for the blocking to subside. + int const rtn = ACE::handle_read_ready (handle, timeout); + + // Did select() succeed? + if (rtn != -1) + { + // Blocking subsided in period. Continue + // data transfer. + n = 0; + continue; + } + } + + // Wait in select() timed out or other data transfer or + // select() failures. + error = 1; + result = n; + break; + } + } + + ACE::restore_non_blocking_mode (handle, val); + + if (error) + return result; + else + return static_cast (bytes_transferred); +} + +// This is basically an interface to ACE_OS::readv, that doesn't use +// the struct iovec explicitly. The ... can be passed as an arbitrary +// number of (char *ptr, int len) tuples. However, the count N is the +// *total* number of trailing arguments, *not* a couple of the number +// of tuple pairs! + +ssize_t +ACE::recv (ACE_HANDLE handle, size_t n, ...) +{ + va_list argp; + int const total_tuples = static_cast (n / 2); + iovec *iovp = 0; +#if defined (ACE_HAS_ALLOCA) + iovp = (iovec *) alloca (total_tuples * sizeof (iovec)); +#else + ACE_NEW_RETURN (iovp, + iovec[total_tuples], + -1); +#endif /* !defined (ACE_HAS_ALLOCA) */ + + va_start (argp, n); + + for (int i = 0; i < total_tuples; i++) + { + iovp[i].iov_base = va_arg (argp, char *); + iovp[i].iov_len = va_arg (argp, int); + } + + ssize_t const result = ACE_OS::recvv (handle, iovp, total_tuples); +#if !defined (ACE_HAS_ALLOCA) + delete [] iovp; +#endif /* !defined (ACE_HAS_ALLOCA) */ + va_end (argp); + return result; +} + +ssize_t +ACE::recvv (ACE_HANDLE handle, + iovec *iov, + int iovcnt, + const ACE_Time_Value *timeout) +{ + if (timeout == 0) + return ACE_OS::recvv (handle, iov, iovcnt); + else + { + int val = 0; + if (ACE::enter_recv_timedwait (handle, timeout, val) == -1) + return -1; + else + { + ssize_t bytes_transferred = ACE_OS::recvv (handle, iov, iovcnt); + ACE::restore_non_blocking_mode (handle, val); + return bytes_transferred; + } + } +} + +ssize_t +ACE::recvv_n_i (ACE_HANDLE handle, + iovec *iov, + int iovcnt, + size_t *bt) +{ + size_t temp; + size_t &bytes_transferred = bt == 0 ? temp : *bt; + bytes_transferred = 0; + + for (int s = 0; s < iovcnt; ) + { + // Try to transfer as much of the remaining data as possible. + ssize_t n = ACE_OS::recvv (handle, iov + s, iovcnt - s); + // Check EOF. + if (n == 0) + return 0; + + // Check for other errors. + if (n == -1) + { + // Check for possible blocking. + if (errno == EWOULDBLOCK) + { + // Wait for the blocking to subside. + int const result = ACE::handle_read_ready (handle, 0); + + // Did select() succeed? + if (result != -1) + { + // Blocking subsided. Continue data transfer. + n = 0; + continue; + } + } + + // Other data transfer or select() failures. + return -1; + } + + for (bytes_transferred += n; + s < iovcnt + && n >= static_cast (iov[s].iov_len); + s++) + n -= iov[s].iov_len; + + if (n != 0) + { + char *base = static_cast (iov[s].iov_base); + iov[s].iov_base = base + n; + iov[s].iov_len = iov[s].iov_len - n; + } + } + + return ACE_Utils::truncate_cast (bytes_transferred); +} + +ssize_t +ACE::recvv_n_i (ACE_HANDLE handle, + iovec *iov, + int iovcnt, + const ACE_Time_Value *timeout, + size_t *bt) +{ + size_t temp; + size_t &bytes_transferred = bt == 0 ? temp : *bt; + bytes_transferred = 0; + ssize_t result = 0; + int error = 0; + + int val = 0; + ACE::record_and_set_non_blocking_mode (handle, val); + + for (int s = 0; s < iovcnt; ) + { + // Try to transfer as much of the remaining data as possible. + // Since the socket is in non-blocking mode, this call will not + // block. + ssize_t n = ACE_OS::recvv (handle, iov + s, iovcnt - s); + + // Check for errors. + if (n == 0 || n == -1) + { + // Check for possible blocking. + if (n == -1 && errno == EWOULDBLOCK) + { + // Wait upto for the blocking to subside. + int const rtn = ACE::handle_read_ready (handle, timeout); + + // Did select() succeed? + if (rtn != -1) + { + // Blocking subsided in period. Continue + // data transfer. + n = 0; + continue; + } + } + + // Wait in select() timed out or other data transfer or + // select() failures. + error = 1; + result = n; + break; + } + + for (bytes_transferred += n; + s < iovcnt + && n >= static_cast (iov[s].iov_len); + s++) + n -= iov[s].iov_len; + + if (n != 0) + { + char *base = reinterpret_cast (iov[s].iov_base); + iov[s].iov_base = base + n; + iov[s].iov_len = iov[s].iov_len - n; + } + } + + ACE::restore_non_blocking_mode (handle, val); + + if (error) + { + return result; + } + else + { + return ACE_Utils::truncate_cast (bytes_transferred); + } +} + +ssize_t +ACE::recv_n (ACE_HANDLE handle, + ACE_Message_Block *message_block, + const ACE_Time_Value *timeout, + size_t *bt) +{ + size_t temp; + size_t &bytes_transferred = bt == 0 ? temp : *bt; + bytes_transferred = 0; + + iovec iov[ACE_IOV_MAX]; + int iovcnt = 0; + + while (message_block != 0) + { + // Our current message block chain. + const ACE_Message_Block *current_message_block = message_block; + + while (current_message_block != 0) + { + size_t current_message_block_length = + current_message_block->length (); + char *this_rd_ptr = current_message_block->rd_ptr (); + + // Check if this block has any space for incoming data. + while (current_message_block_length > 0) + { + u_long const this_chunk_length = + ACE_Utils::truncate_cast ( + current_message_block_length); + + // Collect the data in the iovec. + iov[iovcnt].iov_base = this_rd_ptr; + iov[iovcnt].iov_len = this_chunk_length; + current_message_block_length -= this_chunk_length; + this_rd_ptr += this_chunk_length; + + // Increment iovec counter. + ++iovcnt; + + // The buffer is full make a OS call. @@ TODO find a way to + // find ACE_IOV_MAX for platforms that do not define it rather + // than simply setting ACE_IOV_MAX to some arbitrary value such + // as 16. + if (iovcnt == ACE_IOV_MAX) + { + size_t current_transfer = 0; + + ssize_t const result = ACE::recvv_n (handle, + iov, + iovcnt, + timeout, + ¤t_transfer); + + // Add to total bytes transferred. + bytes_transferred += current_transfer; + + // Errors. + if (result == -1 || result == 0) + return result; + + // Reset iovec counter. + iovcnt = 0; + } + } + + // Select the next message block in the chain. + current_message_block = current_message_block->cont (); + } + + // Selection of the next message block chain. + message_block = message_block->next (); + } + + // Check for remaining buffers to be sent. This will happen when + // ACE_IOV_MAX is not a multiple of the number of message blocks. + if (iovcnt != 0) + { + size_t current_transfer = 0; + + ssize_t const result = ACE::recvv_n (handle, + iov, + iovcnt, + timeout, + ¤t_transfer); + + // Add to total bytes transferred. + bytes_transferred += current_transfer; + + // Errors. + if (result == -1 || result == 0) + { + return result; + } + } + + // Return total bytes transferred. + return ACE_Utils::truncate_cast (bytes_transferred); +} + +ssize_t +ACE::send (ACE_HANDLE handle, + const void *buf, + size_t n, + int flags, + const ACE_Time_Value *timeout) +{ + if (timeout == 0) + return ACE_OS::send (handle, (const char *) buf, n, flags); + else + { + int val = 0; + if (ACE::enter_send_timedwait (handle, timeout, val) == -1) + return -1; + else + { + ssize_t const bytes_transferred = + ACE_OS::send (handle, (const char *) buf, n, flags); + ACE::restore_non_blocking_mode (handle, val); + return bytes_transferred; + } + } +} + +#if defined (ACE_HAS_TLI) + +ssize_t +ACE::t_snd (ACE_HANDLE handle, + const void *buf, + size_t n, + int flags, + const ACE_Time_Value *timeout) +{ + if (timeout == 0) + return ACE_OS::t_snd (handle, (const char *) buf, n, flags); + else + { + int val = 0; + if (ACE::enter_send_timedwait (handle, timeout, val) == -1) + return -1; + else + { + ssize_t const bytes_transferred = + ACE_OS::t_snd (handle, (const char *) buf, n, flags); + ACE::restore_non_blocking_mode (handle, val); + return bytes_transferred; + } + } +} + +#endif /* ACE_HAS_TLI */ + +ssize_t +ACE::send (ACE_HANDLE handle, + const void *buf, + size_t n, + const ACE_Time_Value *timeout) +{ + if (timeout == 0) + return ACE::send_i (handle, buf, n); + else + { + int val = 0; + if (ACE::enter_send_timedwait (handle, timeout, val) == -1) + return -1; + else + { + ssize_t const bytes_transferred = ACE::send_i (handle, buf, n); + ACE::restore_non_blocking_mode (handle, val); + return bytes_transferred; + } + } +} + +ssize_t +ACE::sendmsg (ACE_HANDLE handle, + const struct msghdr *msg, + int flags, + const ACE_Time_Value *timeout) +{ + if (timeout == 0) + return ACE_OS::sendmsg (handle, msg, flags); + else + { + int val = 0; + if (ACE::enter_send_timedwait (handle, timeout, val) == -1) + return -1; + else + { + ssize_t const bytes_transferred = + ACE_OS::sendmsg (handle, msg, flags); + ACE::restore_non_blocking_mode (handle, val); + return bytes_transferred; + } + } +} + +ssize_t +ACE::sendto (ACE_HANDLE handle, + const char *buf, + int len, + int flags, + const struct sockaddr *addr, + int addrlen, + const ACE_Time_Value *timeout) +{ + if (timeout == 0) + return ACE_OS::sendto (handle, buf, len, flags, addr, addrlen); + else + { + int val = 0; + if (ACE::enter_send_timedwait (handle, timeout, val) == -1) + return -1; + else + { + ssize_t const bytes_transferred = + ACE_OS::sendto (handle, buf, len, flags, addr, addrlen); + ACE::restore_non_blocking_mode (handle, val); + return bytes_transferred; + } + } +} + +ssize_t +ACE::send_n_i (ACE_HANDLE handle, + const void *buf, + size_t len, + int flags, + size_t *bt) +{ + size_t temp; + size_t &bytes_transferred = bt == 0 ? temp : *bt; + ssize_t n; + + for (bytes_transferred = 0; + bytes_transferred < len; + bytes_transferred += n) + { + // Try to transfer as much of the remaining data as possible. + n = ACE_OS::send (handle, + (char *) buf + bytes_transferred, + len - bytes_transferred, + flags); + // Check EOF. + if (n == 0) + return 0; + + // Check for other errors. + if (n == -1) + { + // Check for possible blocking. +#if defined (ACE_WIN32) + if (errno == EWOULDBLOCK) // If enobufs no need to loop +#else + if (errno == EWOULDBLOCK || errno == ENOBUFS) +#endif /* ACE_WIN32 */ + { + // Wait for the blocking to subside. + int const result = ACE::handle_write_ready (handle, 0); + + // Did select() succeed? + if (result != -1) + { + // Blocking subsided. Continue data transfer. + n = 0; + continue; + } + } + + // Other data transfer or select() failures. + return -1; + } + } + + return ACE_Utils::truncate_cast (bytes_transferred); +} + +ssize_t +ACE::send_n_i (ACE_HANDLE handle, + const void *buf, + size_t len, + int flags, + const ACE_Time_Value *timeout, + size_t *bt) +{ + size_t temp; + size_t &bytes_transferred = bt == 0 ? temp : *bt; + ssize_t n; + ssize_t result = 0; + int error = 0; + + int val = 0; + ACE::record_and_set_non_blocking_mode (handle, val); + + for (bytes_transferred = 0; + bytes_transferred < len; + bytes_transferred += n) + { + // Try to transfer as much of the remaining data as possible. + // Since the socket is in non-blocking mode, this call will not + // block. + n = ACE_OS::send (handle, + (char *) buf + bytes_transferred, + len - bytes_transferred, + flags); + + // Check for errors. + if (n == 0 || + n == -1) + { + // Check for possible blocking. + if (n == -1 && (errno == EWOULDBLOCK || errno == ENOBUFS)) + { + // Wait upto for the blocking to subside. + int const rtn = ACE::handle_write_ready (handle, timeout); + + // Did select() succeed? + if (rtn != -1) + { + // Blocking subsided in period. Continue + // data transfer. + n = 0; + continue; + } + } + + // Wait in select() timed out or other data transfer or + // select() failures. + error = 1; + result = n; + break; + } + } + + ACE::restore_non_blocking_mode (handle, val); + + if (error) + { + return result; + } + else + { + return ACE_Utils::truncate_cast (bytes_transferred); + } +} + +#if defined (ACE_HAS_TLI) + +ssize_t +ACE::t_snd_n_i (ACE_HANDLE handle, + const void *buf, + size_t len, + int flags, + size_t *bt) +{ + size_t temp; + size_t &bytes_transferred = bt == 0 ? temp : *bt; + ssize_t n; + + for (bytes_transferred = 0; + bytes_transferred < len; + bytes_transferred += n) + { + // Try to transfer as much of the remaining data as possible. + n = ACE_OS::t_snd (handle, + (char *) buf + bytes_transferred, + len - bytes_transferred, + flags); + // Check EOF. + if (n == 0) + return 0; + + // Check for other errors. + if (n == -1) + { + // Check for possible blocking. + if (errno == EWOULDBLOCK || errno == ENOBUFS) + { + // Wait for the blocking to subside. + int const result = ACE::handle_write_ready (handle, 0); + + // Did select() succeed? + if (result != -1) + { + // Blocking subsided. Continue data transfer. + n = 0; + continue; + } + } + + // Other data transfer or select() failures. + return -1; + } + } + + return bytes_transferred; +} + +ssize_t +ACE::t_snd_n_i (ACE_HANDLE handle, + const void *buf, + size_t len, + int flags, + const ACE_Time_Value *timeout, + size_t *bt) +{ + size_t temp; + size_t &bytes_transferred = bt == 0 ? temp : *bt; + ssize_t n; + ssize_t result = 0; + int error = 0; + + int val = 0; + ACE::record_and_set_non_blocking_mode (handle, val); + + for (bytes_transferred = 0; + bytes_transferred < len; + bytes_transferred += n) + { + // Try to transfer as much of the remaining data as possible. + // Since the socket is in non-blocking mode, this call will not + // block. + n = ACE_OS::t_snd (handle, + (char *) buf + bytes_transferred, + len - bytes_transferred, + flags); + + // Check for errors. + if (n == 0 || + n == -1) + { + // Check for possible blocking. + if (n == -1 && + errno == EWOULDBLOCK || errno == ENOBUFS) + { + // Wait upto for the blocking to subside. + int const rtn = ACE::handle_write_ready (handle, timeout); + + // Did select() succeed? + if (rtn != -1) + { + // Blocking subsided in period. Continue + // data transfer. + n = 0; + continue; + } + } + + // Wait in select() timed out or other data transfer or + // select() failures. + error = 1; + result = n; + break; + } + } + + ACE::restore_non_blocking_mode (handle, val); + + if (error) + return result; + else + return bytes_transferred; +} + +#endif /* ACE_HAS_TLI */ + +ssize_t +ACE::send_n_i (ACE_HANDLE handle, + const void *buf, + size_t len, + size_t *bt) +{ + size_t temp; + size_t &bytes_transferred = bt == 0 ? temp : *bt; + ssize_t n; + + for (bytes_transferred = 0; + bytes_transferred < len; + bytes_transferred += n) + { + // Try to transfer as much of the remaining data as possible. + n = ACE::send_i (handle, + (char *) buf + bytes_transferred, + len - bytes_transferred); + // Check EOF. + if (n == 0) + { + return 0; + } + + // Check for other errors. + if (n == -1) + { + // Check for possible blocking. + if (errno == EWOULDBLOCK || errno == ENOBUFS) + { + // Wait for the blocking to subside. + int const result = ACE::handle_write_ready (handle, 0); + + // Did select() succeed? + if (result != -1) + { + // Blocking subsided. Continue data transfer. + n = 0; + continue; + } + } + + // Other data transfer or select() failures. + return -1; + } + } + + return ACE_Utils::truncate_cast (bytes_transferred); +} + +ssize_t +ACE::send_n_i (ACE_HANDLE handle, + const void *buf, + size_t len, + const ACE_Time_Value *timeout, + size_t *bt) +{ + size_t temp; + size_t &bytes_transferred = bt == 0 ? temp : *bt; + ssize_t n; + ssize_t result = 0; + int error = 0; + + int val = 0; + ACE::record_and_set_non_blocking_mode (handle, val); + + for (bytes_transferred = 0; + bytes_transferred < len; + bytes_transferred += n) + { + // Try to transfer as much of the remaining data as possible. + // Since the socket is in non-blocking mode, this call will not + // block. + n = ACE::send_i (handle, + (char *) buf + bytes_transferred, + len - bytes_transferred); + + // Check for errors. + if (n == 0 || + n == -1) + { + // Check for possible blocking. + if (n == -1 && + (errno == EWOULDBLOCK || errno == ENOBUFS)) + { + // Wait upto for the blocking to subside. + int const rtn = ACE::handle_write_ready (handle, timeout); + + // Did select() succeed? + if (rtn != -1) + { + // Blocking subsided in period. Continue + // data transfer. + n = 0; + continue; + } + } + + // Wait in select() timed out or other data transfer or + // select() failures. + error = 1; + result = n; + break; + } + } + + ACE::restore_non_blocking_mode (handle, val); + + if (error) + { + return result; + } + else + { + return ACE_Utils::truncate_cast (bytes_transferred); + } +} + +// Send N char *ptrs and int lengths. Note that the char *'s precede +// the ints (basically, an varargs version of writev). The count N is +// the *total* number of trailing arguments, *not* a couple of the +// number of tuple pairs! + +ssize_t +ACE::send (ACE_HANDLE handle, size_t n, ...) +{ + va_list argp; + int total_tuples = static_cast (n / 2); + iovec *iovp; +#if defined (ACE_HAS_ALLOCA) + iovp = (iovec *) alloca (total_tuples * sizeof (iovec)); +#else + ACE_NEW_RETURN (iovp, + iovec[total_tuples], + -1); +#endif /* !defined (ACE_HAS_ALLOCA) */ + + va_start (argp, n); + + for (int i = 0; i < total_tuples; i++) + { + iovp[i].iov_base = va_arg (argp, char *); + iovp[i].iov_len = va_arg (argp, int); + } + + ssize_t result = ACE_OS::sendv (handle, iovp, total_tuples); +#if !defined (ACE_HAS_ALLOCA) + delete [] iovp; +#endif /* !defined (ACE_HAS_ALLOCA) */ + va_end (argp); + return result; +} + +ssize_t +ACE::sendv (ACE_HANDLE handle, + const iovec *iov, + int iovcnt, + const ACE_Time_Value *timeout) +{ + if (timeout == 0) + return ACE_OS::sendv (handle, iov, iovcnt); + else + { + int val = 0; + if (ACE::enter_send_timedwait (handle, timeout, val) == -1) + return -1; + else + { + ssize_t bytes_transferred = ACE_OS::sendv (handle, iov, iovcnt); + ACE::restore_non_blocking_mode (handle, val); + return bytes_transferred; + } + } +} + +ssize_t +ACE::sendv_n_i (ACE_HANDLE handle, + const iovec *i, + int iovcnt, + size_t *bt) +{ + size_t temp; + size_t &bytes_transferred = bt == 0 ? temp : *bt; + bytes_transferred = 0; + + iovec *iov = const_cast (i); + + for (int s = 0; + s < iovcnt; + ) + { + // Try to transfer as much of the remaining data as possible. + ssize_t n = ACE_OS::sendv (handle, iov + s, iovcnt - s); + + // Check EOF. + if (n == 0) + return 0; + + // Check for other errors. + if (n == -1) + { + // Check for possible blocking. + if (errno == EWOULDBLOCK || errno == ENOBUFS) + { + // Wait for the blocking to subside. + int const result = ACE::handle_write_ready (handle, 0); + + // Did select() succeed? + if (result != -1) + { + // Blocking subsided. Continue data transfer. + n = 0; + continue; + } + } + + // Other data transfer or select() failures. + return -1; + } + + for (bytes_transferred += n; + s < iovcnt + && n >= static_cast (iov[s].iov_len); + s++) + n -= iov[s].iov_len; + + if (n != 0) + { + char *base = reinterpret_cast (iov[s].iov_base); + iov[s].iov_base = base + n; + iov[s].iov_len = iov[s].iov_len - n; + } + } + + return ACE_Utils::truncate_cast (bytes_transferred); +} + +ssize_t +ACE::sendv_n_i (ACE_HANDLE handle, + const iovec *i, + int iovcnt, + const ACE_Time_Value *timeout, + size_t *bt) +{ + size_t temp; + size_t &bytes_transferred = bt == 0 ? temp : *bt; + bytes_transferred = 0; + ssize_t result = 0; + int error = 0; + + int val = 0; + ACE::record_and_set_non_blocking_mode (handle, val); + + iovec *iov = const_cast (i); + + for (int s = 0; + s < iovcnt; + ) + { + // Try to transfer as much of the remaining data as possible. + // Since the socket is in non-blocking mode, this call will not + // block. + ssize_t n = ACE_OS::sendv (handle, iov + s, iovcnt - s); + + // Check for errors. + if (n == 0 || + n == -1) + { + // Check for possible blocking. + if (n == -1 && + (errno == EWOULDBLOCK || errno == ENOBUFS)) + { + // Wait upto for the blocking to subside. + int const rtn = ACE::handle_write_ready (handle, timeout); + + // Did select() succeed? + if (rtn != -1) + { + // Blocking subsided in period. Continue + // data transfer. + n = 0; + continue; + } + } + + // Wait in select() timed out or other data transfer or + // select() failures. + error = 1; + result = n; + break; + } + + for (bytes_transferred += n; + s < iovcnt + && n >= static_cast (iov[s].iov_len); + s++) + n -= iov[s].iov_len; + + if (n != 0) + { + char *base = reinterpret_cast (iov[s].iov_base); + iov[s].iov_base = base + n; + iov[s].iov_len = iov[s].iov_len - n; + } + } + + ACE::restore_non_blocking_mode (handle, val); + + if (error) + { + return result; + } + else + { + return ACE_Utils::truncate_cast (bytes_transferred); + } +} + +ssize_t +ACE::write_n (ACE_HANDLE handle, + const ACE_Message_Block *message_block, + size_t *bt) +{ + size_t temp; + size_t &bytes_transferred = bt == 0 ? temp : *bt; + bytes_transferred = 0; + + iovec iov[ACE_IOV_MAX]; + int iovcnt = 0; + + while (message_block != 0) + { + // Our current message block chain. + const ACE_Message_Block *current_message_block = message_block; + + while (current_message_block != 0) + { + size_t current_message_block_length = + current_message_block->length (); + char *this_block_ptr = current_message_block->rd_ptr (); + + // Check if this block has any data to be sent. + while (current_message_block_length > 0) + { + u_long const this_chunk_length = + ACE_Utils::truncate_cast ( + current_message_block_length); + + // Collect the data in the iovec. + iov[iovcnt].iov_base = this_block_ptr; + iov[iovcnt].iov_len = this_chunk_length; + current_message_block_length -= this_chunk_length; + this_block_ptr += this_chunk_length; + + // Increment iovec counter. + ++iovcnt; + + // The buffer is full make a OS call. @@ TODO find a way to + // find ACE_IOV_MAX for platforms that do not define it rather + // than simply setting ACE_IOV_MAX to some arbitrary value such + // as 16. + if (iovcnt == ACE_IOV_MAX) + { + size_t current_transfer = 0; + + ssize_t const result = ACE::writev_n (handle, + iov, + iovcnt, + ¤t_transfer); + + // Add to total bytes transferred. + bytes_transferred += current_transfer; + + // Errors. + if (result == -1 || result == 0) + return result; + + // Reset iovec counter. + iovcnt = 0; + } + } + + // Select the next message block in the chain. + current_message_block = current_message_block->cont (); + } + + // Selection of the next message block chain. + message_block = message_block->next (); + } + + // Check for remaining buffers to be sent. This will happen when + // ACE_IOV_MAX is not a multiple of the number of message blocks. + if (iovcnt != 0) + { + size_t current_transfer = 0; + + ssize_t const result = ACE::writev_n (handle, + iov, + iovcnt, + ¤t_transfer); + + // Add to total bytes transferred. + bytes_transferred += current_transfer; + + // Errors. + if (result == -1 || result == 0) + return result; + } + + // Return total bytes transferred. + return ACE_Utils::truncate_cast (bytes_transferred); +} + +ssize_t +ACE::send_n (ACE_HANDLE handle, + const ACE_Message_Block *message_block, + const ACE_Time_Value *timeout, + size_t *bt) +{ + size_t temp; + size_t &bytes_transferred = bt == 0 ? temp : *bt; + bytes_transferred = 0; + + iovec iov[ACE_IOV_MAX]; + int iovcnt = 0; + + while (message_block != 0) + { + // Our current message block chain. + const ACE_Message_Block *current_message_block = message_block; + + while (current_message_block != 0) + { + char *this_block_ptr = current_message_block->rd_ptr (); + size_t current_message_block_length = + current_message_block->length (); + + // Check if this block has any data to be sent. + while (current_message_block_length > 0) + { + u_long const this_chunk_length = + ACE_Utils::truncate_cast ( + current_message_block_length); + + // Collect the data in the iovec. + iov[iovcnt].iov_base = this_block_ptr; + iov[iovcnt].iov_len = this_chunk_length; + current_message_block_length -= this_chunk_length; + this_block_ptr += this_chunk_length; + + // Increment iovec counter. + ++iovcnt; + + // The buffer is full make a OS call. @@ TODO find a way to + // find ACE_IOV_MAX for platforms that do not define it rather + // than simply setting ACE_IOV_MAX to some arbitrary value such + // as 16. + if (iovcnt == ACE_IOV_MAX) + { + size_t current_transfer = 0; + + ssize_t const result = ACE::sendv_n (handle, + iov, + iovcnt, + timeout, + ¤t_transfer); + + // Add to total bytes transferred. + bytes_transferred += current_transfer; + + // Errors. + if (result == -1 || result == 0) + return result; + + // Reset iovec counter. + iovcnt = 0; + } + } + + // Select the next message block in the chain. + current_message_block = current_message_block->cont (); + } + + // Selection of the next message block chain. + message_block = message_block->next (); + } + + // Check for remaining buffers to be sent. This will happen when + // ACE_IOV_MAX is not a multiple of the number of message blocks. + if (iovcnt != 0) + { + size_t current_transfer = 0; + + ssize_t const result = ACE::sendv_n (handle, + iov, + iovcnt, + timeout, + ¤t_transfer); + + // Add to total bytes transferred. + bytes_transferred += current_transfer; + + // Errors. + if (result == -1 || result == 0) + { + return result; + } + } + + // Return total bytes transferred. + return ACE_Utils::truncate_cast (bytes_transferred); +} + +ssize_t +ACE::readv_n (ACE_HANDLE handle, + iovec *iov, + int iovcnt, + size_t *bt) +{ + size_t temp; + size_t &bytes_transferred = bt == 0 ? temp : *bt; + bytes_transferred = 0; + + for (int s = 0; + s < iovcnt; + ) + { + ssize_t n = ACE_OS::readv (handle, + iov + s, + iovcnt - s); + + if (n == -1 || n == 0) + return n; + + for (bytes_transferred += n; + s < iovcnt + && n >= static_cast (iov[s].iov_len); + s++) + n -= iov[s].iov_len; + + if (n != 0) + { + char *base = reinterpret_cast (iov[s].iov_base); + iov[s].iov_base = base + n; + iov[s].iov_len = iov[s].iov_len - n; + } + } + + return ACE_Utils::truncate_cast (bytes_transferred); +} + +ssize_t +ACE::writev_n (ACE_HANDLE handle, + const iovec *i, + int iovcnt, + size_t *bt) +{ + size_t temp; + size_t &bytes_transferred = bt == 0 ? temp : *bt; + bytes_transferred = 0; + + iovec *iov = const_cast (i); + + for (int s = 0; + s < iovcnt; + ) + { + ssize_t n = ACE_OS::writev (handle, + iov + s, + iovcnt - s); + + if (n == -1 || n == 0) + { + return n; + } + + for (bytes_transferred += n; + s < iovcnt + && n >= static_cast (iov[s].iov_len); + s++) + n -= iov[s].iov_len; + + if (n != 0) + { + char *base = reinterpret_cast (iov[s].iov_base); + iov[s].iov_base = base + n; + iov[s].iov_len = iov[s].iov_len - n; + } + } + + return ACE_Utils::truncate_cast (bytes_transferred); +} + +int +ACE::handle_ready (ACE_HANDLE handle, + const ACE_Time_Value *timeout, + int read_ready, + int write_ready, + int exception_ready) +{ +#if defined (ACE_HAS_POLL) && defined (ACE_HAS_LIMITED_SELECT) + ACE_UNUSED_ARG (write_ready); + ACE_UNUSED_ARG (exception_ready); + + struct pollfd fds; + + fds.fd = handle; + fds.events = read_ready ? POLLIN : POLLOUT; + fds.revents = 0; + + int result = ACE_OS::poll (&fds, 1, timeout); +#else + ACE_Handle_Set handle_set; + handle_set.set_bit (handle); + + // Wait for data or for the timeout to elapse. + int select_width; +# if defined (ACE_WIN32) + // This arg is ignored on Windows and causes pointer truncation + // warnings on 64-bit compiles. + select_width = 0; +# else + select_width = int (handle) + 1; +# endif /* ACE_WIN64 */ + int result = ACE_OS::select (select_width, + read_ready ? handle_set.fdset () : 0, // read_fds. + write_ready ? handle_set.fdset () : 0, // write_fds. + exception_ready ? handle_set.fdset () : 0, // exception_fds. + timeout); + +#endif /* ACE_HAS_POLL && ACE_HAS_LIMITED_SELECT */ + + switch (result) + { + case 0: // Timer expired. + errno = ETIME; + /* FALLTHRU */ + case -1: // we got here directly - select() returned -1. + return -1; + case 1: // Handle has data. + /* FALLTHRU */ + default: // default is case result > 0; return a + // ACE_ASSERT (result == 1); + return result; + } +} + +int +ACE::enter_recv_timedwait (ACE_HANDLE handle, + const ACE_Time_Value *timeout, + int &val) +{ + int result = ACE::handle_read_ready (handle, + timeout); + + if (result == -1) + return -1; + + ACE::record_and_set_non_blocking_mode (handle, + val); + + return result; +} + +int +ACE::enter_send_timedwait (ACE_HANDLE handle, + const ACE_Time_Value *timeout, + int &val) +{ + int result = ACE::handle_write_ready (handle, + timeout); + + if (result == -1) + return -1; + + ACE::record_and_set_non_blocking_mode (handle, + val); + + return result; +} + +void +ACE::record_and_set_non_blocking_mode (ACE_HANDLE handle, + int &val) +{ + // We need to record whether we are already *in* nonblocking mode, + // so that we can correctly reset the state when we're done. + val = ACE::get_flags (handle); + + if (ACE_BIT_DISABLED (val, ACE_NONBLOCK)) + // Set the handle into non-blocking mode if it's not already in + // it. + ACE::set_flags (handle, ACE_NONBLOCK); +} + +void +ACE::restore_non_blocking_mode (ACE_HANDLE handle, + int val) +{ + if (ACE_BIT_DISABLED (val, + ACE_NONBLOCK)) + { + // Save/restore errno. + ACE_Errno_Guard error (errno); + // Only disable ACE_NONBLOCK if we weren't in non-blocking mode + // originally. + ACE::clr_flags (handle, ACE_NONBLOCK); + } +} + + +// Format buffer into printable format. This is useful for debugging. +// Portions taken from mdump by J.P. Knight (J.P.Knight@lut.ac.uk) +// Modifications by Todd Montgomery. + +size_t +ACE::format_hexdump (const char *buffer, + size_t size, + ACE_TCHAR *obuf, + size_t obuf_sz) +{ + ACE_TRACE ("ACE::format_hexdump"); + + u_char c; + ACE_TCHAR textver[16 + 1]; + + // We can fit 16 bytes output in text mode per line, 4 chars per byte. + size_t maxlen = (obuf_sz / 68) * 16; + + if (size > maxlen) + size = maxlen; + + size_t i; + + size_t const lines = size / 16; + for (i = 0; i < lines; i++) + { + size_t j; + + for (j = 0 ; j < 16; j++) + { + c = (u_char) buffer[(i << 4) + j]; // or, buffer[i*16+j] + ACE_OS::sprintf (obuf, + ACE_TEXT ("%02x "), + c); + obuf += 3; + if (j == 7) + { + ACE_OS::sprintf (obuf, + ACE_TEXT (" ")); + ++obuf; + } + textver[j] = ACE_OS::ace_isprint (c) ? c : '.'; + } + + textver[j] = 0; + + ACE_OS::sprintf (obuf, +#if !defined (ACE_WIN32) && defined (ACE_USES_WCHAR) + ACE_TEXT (" %ls\n"), +#else + ACE_TEXT (" %s\n"), +#endif + textver); + + while (*obuf != '\0') + ++obuf; + } + + if (size % 16) + { + for (i = 0 ; i < size % 16; i++) + { + c = (u_char) buffer[size - size % 16 + i]; + ACE_OS::sprintf (obuf, + ACE_TEXT ("%02x "), + c); + obuf += 3; + if (i == 7) + { + ACE_OS::sprintf (obuf, + ACE_TEXT (" ")); + ++obuf; + } + textver[i] = ACE_OS::ace_isprint (c) ? c : '.'; + } + + for (i = size % 16; i < 16; i++) + { + ACE_OS::sprintf (obuf, + ACE_TEXT (" ")); + obuf += 3; + if (i == 7) + { + ACE_OS::sprintf (obuf, + ACE_TEXT (" ")); + ++obuf; + } + textver[i] = ' '; + } + + textver[i] = 0; + ACE_OS::sprintf (obuf, +#if !defined (ACE_WIN32) && defined (ACE_USES_WCHAR) + ACE_TEXT (" %ls\n"), +#else + ACE_TEXT (" %s\n"), +#endif + textver); + } + return size; +} + +// Returns the current timestamp in the form +// "hour:minute:second:microsecond." The month, day, and year are +// also stored in the beginning of the date_and_time array. + +ACE_TCHAR * +ACE::timestamp (ACE_TCHAR date_and_time[], + size_t date_and_timelen, + bool return_pointer_to_first_digit) +{ + return ACE::timestamp (ACE_Time_Value::zero, + date_and_time, + date_and_timelen, + return_pointer_to_first_digit); +} + +// Returns the given timestamp in the form +// "hour:minute:second:microsecond." The month, day, and year are +// also stored in the beginning of the date_and_time array. + +ACE_TCHAR * +ACE::timestamp (const ACE_Time_Value& time_value, + ACE_TCHAR date_and_time[], + size_t date_and_timelen, + bool return_pointer_to_first_digit) +{ + //ACE_TRACE ("ACE::timestamp"); + + if (date_and_timelen < 35) + { + errno = EINVAL; + return 0; + } + +#if defined (WIN32) + if (time_value == ACE_Time_Value::zero) + { + // Emulate Unix. Win32 does NOT support all the UNIX versions + // below, so DO we need this ifdef. + static const ACE_TCHAR *day_of_week_name[] = + { + ACE_TEXT ("Sun"), + ACE_TEXT ("Mon"), + ACE_TEXT ("Tue"), + ACE_TEXT ("Wed"), + ACE_TEXT ("Thu"), + ACE_TEXT ("Fri"), + ACE_TEXT ("Sat") + }; + + static const ACE_TCHAR *month_name[] = + { + ACE_TEXT ("Jan"), + ACE_TEXT ("Feb"), + ACE_TEXT ("Mar"), + ACE_TEXT ("Apr"), + ACE_TEXT ("May"), + ACE_TEXT ("Jun"), + ACE_TEXT ("Jul"), + ACE_TEXT ("Aug"), + ACE_TEXT ("Sep"), + ACE_TEXT ("Oct"), + ACE_TEXT ("Nov"), + ACE_TEXT ("Dec") + }; + + SYSTEMTIME local; + ::GetLocalTime (&local); + + ACE_OS::sprintf (date_and_time, + ACE_TEXT ("%3s %3s %2d %04d %02d:%02d:%02d.%06d"), + day_of_week_name[local.wDayOfWeek], + month_name[local.wMonth - 1], + (int) local.wDay, + (int) local.wYear, + (int) local.wHour, + (int) local.wMinute, + (int) local.wSecond, + (int) (local.wMilliseconds * 1000)); + return &date_and_time[15 + (return_pointer_to_first_digit != 0)]; + } +#endif /* WIN32 */ + ACE_TCHAR timebuf[26]; // This magic number is based on the ctime(3c) man page. + ACE_Time_Value cur_time = + (time_value == ACE_Time_Value::zero) ? + ACE_Time_Value (ACE_OS::gettimeofday ()) : time_value; + time_t secs = cur_time.sec (); + + ACE_OS::ctime_r (&secs, + timebuf, + sizeof timebuf / sizeof (ACE_TCHAR)); + // date_and_timelen > sizeof timebuf! + ACE_OS::strsncpy (date_and_time, + timebuf, + date_and_timelen); + ACE_TCHAR yeartmp[5]; + ACE_OS::strsncpy (yeartmp, + &date_and_time[20], + 5); + ACE_TCHAR timetmp[9]; + ACE_OS::strsncpy (timetmp, + &date_and_time[11], + 9); + ACE_OS::sprintf (&date_and_time[11], +# if defined (ACE_USES_WCHAR) + ACE_TEXT ("%ls %ls.%06ld"), +# else + ACE_TEXT ("%s %s.%06ld"), +# endif /* ACE_USES_WCHAR */ + yeartmp, + timetmp, + cur_time.usec ()); + date_and_time[33] = '\0'; + return &date_and_time[15 + (return_pointer_to_first_digit != 0)]; +} + +// This function rounds the request to a multiple of the page size. + +size_t +ACE::round_to_pagesize (size_t len) +{ + ACE_TRACE ("ACE::round_to_pagesize"); + + if (ACE::pagesize_ == 0) + ACE::pagesize_ = ACE_OS::getpagesize (); + + return (len + (ACE::pagesize_ - 1)) & ~(ACE::pagesize_ - 1); +} + +size_t +ACE::round_to_allocation_granularity (size_t len) +{ + ACE_TRACE ("ACE::round_to_allocation_granularity"); + + if (ACE::allocation_granularity_ == 0) + ACE::allocation_granularity_ = ACE_OS::allocation_granularity (); + + return (len + (ACE::allocation_granularity_ - 1)) & ~(ACE::allocation_granularity_ - 1); +} + +ACE_HANDLE +ACE::handle_timed_complete (ACE_HANDLE h, + const ACE_Time_Value *timeout, + int is_tli) +{ + ACE_TRACE ("ACE::handle_timed_complete"); + +#if !defined (ACE_WIN32) && defined (ACE_HAS_POLL) && defined (ACE_HAS_LIMITED_SELECT) + + struct pollfd fds; + + fds.fd = h; + fds.events = POLLIN | POLLOUT; + fds.revents = 0; + +#else + ACE_Handle_Set rd_handles; + ACE_Handle_Set wr_handles; + rd_handles.set_bit (h); + wr_handles.set_bit (h); +#endif /* !ACE_WIN32 && ACE_HAS_POLL && ACE_HAS_LIMITED_SELECT */ + +#if defined (ACE_WIN32) + // Winsock is different - it sets the exception bit for failed connect, + // unlike other platforms, where the write bit is set for both success + // and fail. + ACE_Handle_Set ex_handles; + ex_handles.set_bit (h); +#endif /* ACE_WIN32 */ + + bool need_to_check = false; + bool known_failure = false; + +#if defined (ACE_WIN32) + int n = ACE_OS::select (0, // Ignored on Windows: int (h) + 1, + 0, + wr_handles, + ex_handles, + timeout); +#else +# if defined (ACE_HAS_POLL) && defined (ACE_HAS_LIMITED_SELECT) + + int n = ACE_OS::poll (&fds, 1, timeout); + +# else + int n = 0; + if (is_tli) + n = ACE_OS::select (int (h) + 1, + rd_handles, + wr_handles, + 0, + timeout); + else + n = ACE_OS::select (int (h) + 1, + 0, + wr_handles, + 0, + timeout); +# endif /* ACE_HAS_POLL && ACE_HAS_LIMITED_SELECT */ +#endif /* ACE_WIN32 */ + + // If we failed to connect within the time period allocated by the + // caller, then we fail (e.g., the remote host might have been too + // busy to accept our call). + if (n <= 0) + { + if (n == 0 && timeout != 0) + errno = ETIME; + return ACE_INVALID_HANDLE; + } + + // On Windows, a ready-for-write handle is successfully connected, and + // ready-for-exception is a failure. On fails, we need to grab the error + // code via getsockopt. + // On BSD sockets using select(), the handle becomes writable on + // completion either success or fail, so if the select() does not time + // out, we need to check for success/fail. + // It is believed that TLI sockets use the readable=fail, writeable=success + // but that hasn't been as well tested. +#if defined (ACE_WIN32) + ACE_UNUSED_ARG (is_tli); + + // On Win32, ex_handle set indicates a failure. We'll do the check + // to try and get an errno value, but the connect failed regardless of + // what getsockopt says about the error. + if (ex_handles.is_set (h)) + { + need_to_check = true; + known_failure = true; + } +#else + if (is_tli) +# if defined (ACE_HAS_POLL) && defined (ACE_HAS_LIMITED_SELECT) + need_to_check = (fds.revents & POLLIN) && !(fds.revents & POLLOUT); +# else + need_to_check = rd_handles.is_set (h) && !wr_handles.is_set (h); +# endif /* ACE_HAS_POLL && ACE_HAS_LIMITED_SELECT */ + + else +# if defined (ACE_HAS_POLL) && defined (ACE_HAS_LIMITED_SELECT) + need_to_check = (fds.revents & POLLIN); +# else + need_to_check = true; +# endif /* ACE_HAS_POLL && ACE_HAS_LIMITED_SELECT */ +#endif /* ACE_WIN32 */ + + if (need_to_check) + { +#if defined (SOL_SOCKET) && defined (SO_ERROR) + int sock_err = 0; + int sock_err_len = sizeof (sock_err); + int sockopt_ret = ACE_OS::getsockopt (h, SOL_SOCKET, SO_ERROR, + (char *)&sock_err, &sock_err_len); + if (sockopt_ret < 0) + { + h = ACE_INVALID_HANDLE; + } + + if (sock_err != 0 || known_failure) + { + h = ACE_INVALID_HANDLE; + errno = sock_err; + } +#else + char dummy; + + // The following recv() won't block provided that the + // ACE_NONBLOCK flag has not been turned off . + n = ACE::recv (h, &dummy, 1, MSG_PEEK); + + // If no data was read/peeked at, check to see if it's because + // of a non-connected socket (and therefore an error) or there's + // just no data yet. + if (n <= 0) + { + if (n == 0) + { + errno = ECONNREFUSED; + h = ACE_INVALID_HANDLE; + } + else if (errno != EWOULDBLOCK && errno != EAGAIN) + h = ACE_INVALID_HANDLE; + } +#endif + } + + // 1. The HANDLE is ready for writing and doesn't need to be checked or + // 2. recv() returned an indication of the state of the socket - if there is + // either data present, or a recv is legit but there's no data yet, + // the connection was successfully established. + return h; +} + +// Wait up to amount of time to accept a connection. + +int +ACE::handle_timed_accept (ACE_HANDLE listener, + ACE_Time_Value *timeout, + bool restart) +{ + ACE_TRACE ("ACE::handle_timed_accept"); + // Make sure we don't bomb out on erroneous values. + if (listener == ACE_INVALID_HANDLE) + return -1; + +#if defined (ACE_HAS_POLL) && defined (ACE_HAS_LIMITED_SELECT) + + struct pollfd fds; + + fds.fd = listener; + fds.events = POLLIN; + fds.revents = 0; + +#else + // Use the select() implementation rather than poll(). + ACE_Handle_Set rd_handle; + rd_handle.set_bit (listener); +#endif /* ACE_HAS_POLL && ACE_HAS_LIMITED_SELECT */ + + // We need a loop here if is enabled. + + for (;;) + { +#if defined (ACE_HAS_POLL) && defined (ACE_HAS_LIMITED_SELECT) + + int n = ACE_OS::poll (&fds, 1, timeout); + +#else + int select_width; +# if defined (ACE_WIN32) + // This arg is ignored on Windows and causes pointer truncation + // warnings on 64-bit compiles. + select_width = 0; +# else + select_width = int (listener) + 1; +# endif /* ACE_WIN32 */ + int n = ACE_OS::select (select_width, + rd_handle, 0, 0, + timeout); +#endif /* ACE_HAS_POLL && ACE_HAS_LIMITED_SELECT */ + + switch (n) + { + case -1: + if (errno == EINTR && restart) + continue; + else + return -1; + /* NOTREACHED */ + case 0: + if (timeout != 0 && *timeout == ACE_Time_Value::zero) + errno = EWOULDBLOCK; + else + errno = ETIMEDOUT; + return -1; + /* NOTREACHED */ + case 1: + return 0; + /* NOTREACHED */ + default: + errno = EINVAL; + return -1; + /* NOTREACHED */ + } + } +} + +// Make the current process a UNIX daemon. This is based on Stevens +// code from APUE. + +int +ACE::daemonize (const ACE_TCHAR pathname[], + bool close_all_handles, + const ACE_TCHAR program_name[]) +{ + ACE_TRACE ("ACE::daemonize"); +#if !defined (ACE_LACKS_FORK) + pid_t pid = ACE_OS::fork (); + + if (pid == -1) + return -1; + else if (pid != 0) + ACE_OS::exit (0); // Parent exits. + + // 1st child continues. + ACE_OS::setsid (); // Become session leader. + + ACE_OS::signal (SIGHUP, SIG_IGN); + + pid = ACE_OS::fork (program_name); + + if (pid != 0) + ACE_OS::exit (0); // First child terminates. + + // Second child continues. + + if (pathname != 0) + // change working directory. + ACE_OS::chdir (pathname); + + ACE_OS::umask (0); // clear our file mode creation mask. + + // Close down the I/O handles. + if (close_all_handles) + { + for (int i = ACE::max_handles () - 1; i >= 0; i--) + ACE_OS::close (i); + + int fd = ACE_OS::open ("/dev/null", O_RDWR, 0); + if (fd != -1) + { + ACE_OS::dup2 (fd, ACE_STDIN); + ACE_OS::dup2 (fd, ACE_STDOUT); + ACE_OS::dup2 (fd, ACE_STDERR); + + if (fd > ACE_STDERR) + ACE_OS::close (fd); + } + } + + return 0; +#else + ACE_UNUSED_ARG (pathname); + ACE_UNUSED_ARG (close_all_handles); + ACE_UNUSED_ARG (program_name); + + ACE_NOTSUP_RETURN (-1); +#endif /* ACE_LACKS_FORK */ +} + +pid_t +ACE::fork (const ACE_TCHAR *program_name, + int avoid_zombies) +{ + if (avoid_zombies == 0) + return ACE_OS::fork (program_name); + else + { + // This algorithm is adapted from an example in the Stevens book + // "Advanced Programming in the Unix Environment" and an item in + // Andrew Gierth's Unix Programming FAQ. It creates an orphan + // process that's inherited by the init process; init cleans up + // when the orphan process terminates. + // + // Another way to avoid zombies is to ignore or catch the + // SIGCHLD signal; we don't use that approach here. + + pid_t pid = ACE_OS::fork (); + if (pid == 0) + { + // The child process forks again to create a grandchild. + switch (ACE_OS::fork (program_name)) + { + case 0: // grandchild returns 0. + return 0; + case -1: // assumes all errnos are < 256 + ACE_OS::_exit (errno); + default: // child terminates, orphaning grandchild + ACE_OS::_exit (0); + } + } + + // Parent process waits for child to terminate. + ACE_exitcode status; + if (pid < 0 || ACE_OS::waitpid (pid, &status, 0) < 0) + return -1; + + // child terminated by calling exit()? + if (WIFEXITED ((status))) + { + // child terminated normally? + if (WEXITSTATUS ((status)) == 0) + return 1; + else + errno = WEXITSTATUS ((status)); + } + else + // child didn't call exit(); perhaps it received a signal? + errno = EINTR; + + return -1; + } +} + +int +ACE::max_handles (void) +{ + ACE_TRACE ("ACE::max_handles"); +#if defined (RLIMIT_NOFILE) && !defined (ACE_LACKS_RLIMIT) + rlimit rl; + int const r = ACE_OS::getrlimit (RLIMIT_NOFILE, &rl); +# if !defined (RLIM_INFINITY) + if (r == 0) + return rl.rlim_cur; +# else + if (r == 0 && rl.rlim_cur != RLIM_INFINITY) + return rl.rlim_cur; + // If == RLIM_INFINITY, fall through to the ACE_LACKS_RLIMIT sections +# endif /* RLIM_INFINITY */ +#endif /* RLIMIT_NOFILE && !ACE_LACKS_RLIMIT */ + +#if defined (_SC_OPEN_MAX) + return ACE_OS::sysconf (_SC_OPEN_MAX); +#elif defined (ACE_VXWORKS) && (ACE_VXWORKS < 0x620) + return maxFiles; +#elif defined (FD_SETSIZE) + return FD_SETSIZE; +#else + ACE_NOTSUP_RETURN (-1); +#endif /* _SC_OPEN_MAX */ +} + +// Set the number of currently open handles in the process. +// +// If NEW_LIMIT == -1 set the limit to the maximum allowable. +// Otherwise, set it to be the value of NEW_LIMIT. + +int +ACE::set_handle_limit (int new_limit, + int increase_limit_only) +{ + ACE_TRACE ("ACE::set_handle_limit"); + int cur_limit = ACE::max_handles (); + int max_limit = cur_limit; + + if (cur_limit == -1) + return -1; + +#if !defined (ACE_LACKS_RLIMIT) && defined (RLIMIT_NOFILE) + struct rlimit rl; + + ACE_OS::memset ((void *) &rl, 0, sizeof rl); + int r = ACE_OS::getrlimit (RLIMIT_NOFILE, &rl); + if (r == 0) + max_limit = rl.rlim_max; +#endif /* ACE_LACKS_RLIMIT */ + + if (new_limit == -1) + new_limit = max_limit; + + if (new_limit < 0) + { + errno = EINVAL; + return -1; + } + else if (new_limit > cur_limit) + { + // Increase the limit. +#if !defined (ACE_LACKS_RLIMIT) && defined (RLIMIT_NOFILE) + rl.rlim_cur = new_limit; + return ACE_OS::setrlimit (RLIMIT_NOFILE, &rl); +#elif defined (ACE_LACKS_RLIMIT_NOFILE) + return 0; +#else + // Must return EINVAL errno. + ACE_NOTSUP_RETURN (-1); +#endif /* ACE_LACKS_RLIMIT */ + } + else if (increase_limit_only == 0) + { + // Decrease the limit. +#if !defined (ACE_LACKS_RLIMIT) && defined (RLIMIT_NOFILE) + rl.rlim_cur = new_limit; + return ACE_OS::setrlimit (RLIMIT_NOFILE, &rl); +#else + // We give a chance to platforms without RLIMIT to work. + // Instead of ACE_NOTSUP_RETURN (0), just return 0 because + // new_limit is <= cur_limit, so it's a no-op. + return 0; +#endif /* ACE_LACKS_RLIMIT */ + } + + return 0; +} + +// Euclid's greatest common divisor algorithm. +u_long +ACE::gcd (u_long x, u_long y) +{ + while (y != 0) + { + u_long r = x % y; + x = y; + y = r; + } + + return x; +} + + +// Calculates the minimum enclosing frame size for the given values. +u_long +ACE::minimum_frame_size (u_long period1, u_long period2) +{ + // if one of the periods is zero, treat it as though it as + // uninitialized and return the other period as the frame size + if (0 == period1) + { + return period2; + } + if (0 == period2) + { + return period1; + } + + // if neither is zero, find the greatest common divisor of the two periods + u_long greatest_common_divisor = ACE::gcd (period1, period2); + + // explicitly consider cases to reduce risk of possible overflow errors + if (greatest_common_divisor == 1) + { + // periods are relative primes: just multiply them together + return period1 * period2; + } + else if (greatest_common_divisor == period1) + { + // the first period divides the second: return the second + return period2; + } + else if (greatest_common_divisor == period2) + { + // the second period divides the first: return the first + return period1; + } + else + { + // the current frame size and the entry's effective period + // have a non-trivial greatest common divisor: return the + // product of factors divided by those in their gcd. + return (period1 * period2) / greatest_common_divisor; + } +} + + +u_long +ACE::is_prime (const u_long n, + const u_long min_factor, + const u_long max_factor) +{ + if (n > 3) + for (u_long factor = min_factor; + factor <= max_factor; + ++factor) + if (n / factor * factor == n) + return factor; + + return 0; +} + +const ACE_TCHAR * +ACE::sock_error (int error) +{ +#if defined (ACE_WIN32) + static ACE_TCHAR unknown_msg[64]; + + switch (error) + { + case WSAVERNOTSUPPORTED: + return ACE_TEXT ("version of WinSock not supported"); + /* NOTREACHED */ + case WSASYSNOTREADY: + return ACE_TEXT ("WinSock not present or not responding"); + /* NOTREACHED */ + case WSAEINVAL: + return ACE_TEXT ("app version not supported by DLL"); + /* NOTREACHED */ + case WSAHOST_NOT_FOUND: + return ACE_TEXT ("Authoritive: Host not found"); + /* NOTREACHED */ + case WSATRY_AGAIN: + return ACE_TEXT ("Non-authoritive: host not found or server failure"); + /* NOTREACHED */ + case WSANO_RECOVERY: + return ACE_TEXT ("Non-recoverable: refused or not implemented"); + /* NOTREACHED */ + case WSANO_DATA: + return ACE_TEXT ("Valid name, no data record for type"); + /* NOTREACHED */ + /* + case WSANO_ADDRESS: + return "Valid name, no MX record"; + */ + case WSANOTINITIALISED: + return ACE_TEXT ("WSA Startup not initialized"); + /* NOTREACHED */ + case WSAENETDOWN: + return ACE_TEXT ("Network subsystem failed"); + /* NOTREACHED */ + case WSAEINPROGRESS: + return ACE_TEXT ("Blocking operation in progress"); + /* NOTREACHED */ + case WSAEINTR: + return ACE_TEXT ("Blocking call cancelled"); + /* NOTREACHED */ + case WSAEAFNOSUPPORT: + return ACE_TEXT ("address family not supported"); + /* NOTREACHED */ + case WSAEMFILE: + return ACE_TEXT ("no file handles available"); + /* NOTREACHED */ + case WSAENOBUFS: + return ACE_TEXT ("no buffer space available"); + /* NOTREACHED */ + case WSAEPROTONOSUPPORT: + return ACE_TEXT ("specified protocol not supported"); + /* NOTREACHED */ + case WSAEPROTOTYPE: + return ACE_TEXT ("protocol wrong type for this socket"); + /* NOTREACHED */ + case WSAESOCKTNOSUPPORT: + return ACE_TEXT ("socket type not supported for address family"); + /* NOTREACHED */ + case WSAENOTSOCK: + return ACE_TEXT ("handle is not a socket"); + /* NOTREACHED */ + case WSAEWOULDBLOCK: + return ACE_TEXT ("resource temporarily unavailable"); + /* NOTREACHED */ + case WSAEADDRINUSE: + return ACE_TEXT ("address already in use"); + /* NOTREACHED */ + case WSAECONNABORTED: + return ACE_TEXT ("connection aborted"); + /* NOTREACHED */ + case WSAECONNRESET: + return ACE_TEXT ("connection reset"); + /* NOTREACHED */ + case WSAENOTCONN: + return ACE_TEXT ("not connected"); + /* NOTREACHED */ + case WSAETIMEDOUT: + return ACE_TEXT ("connection timed out"); + /* NOTREACHED */ + case WSAECONNREFUSED: + return ACE_TEXT ("connection refused"); + /* NOTREACHED */ + case WSAEHOSTDOWN: + return ACE_TEXT ("host down"); + /* NOTREACHED */ + case WSAEHOSTUNREACH: + return ACE_TEXT ("host unreachable"); + /* NOTREACHED */ + case WSAEADDRNOTAVAIL: + return ACE_TEXT ("address not available"); + /* NOTREACHED */ + case WSAEISCONN: + return ACE_TEXT ("socket is already connected"); + /* NOTREACHED */ + case WSAENETRESET: + return ACE_TEXT ("network dropped connection on reset"); + /* NOTREACHED */ + case WSAEMSGSIZE: + return ACE_TEXT ("message too long"); + /* NOTREACHED */ + case WSAENETUNREACH: + return ACE_TEXT ("network is unreachable"); + /* NOTREACHED */ + case WSAEFAULT: + return ACE_TEXT ("bad address"); + /* NOTREACHED */ + case WSAEDISCON: + return ACE_TEXT ("graceful shutdown in progress"); + /* NOTREACHED */ + case WSAEACCES: + return ACE_TEXT ("permission denied"); + /* NOTREACHED */ + case WSAESHUTDOWN: + return ACE_TEXT ("cannot send after socket shutdown"); + /* NOTREACHED */ + case WSAEPROCLIM: + return ACE_TEXT ("too many processes"); + /* NOTREACHED */ + case WSAEALREADY: + return ACE_TEXT ("operation already in progress"); + /* NOTREACHED */ + case WSAEPFNOSUPPORT: + return ACE_TEXT ("protocol family not supported"); + /* NOTREACHED */ + case WSAENOPROTOOPT: + return ACE_TEXT ("bad protocol option"); + /* NOTREACHED */ + case WSATYPE_NOT_FOUND: + return ACE_TEXT ("class type not found"); + /* NOTREACHED */ + case WSAEOPNOTSUPP: + return ACE_TEXT ("operation not supported"); + /* NOTREACHED */ + case WSAEDESTADDRREQ: + return ACE_TEXT ("destination address required"); + /* NOTREACHED */ + default: + ACE_OS::sprintf (unknown_msg, ACE_TEXT ("unknown error: %d"), error); + return unknown_msg; + /* NOTREACHED */ + } +#else + ACE_UNUSED_ARG (error); + ACE_NOTSUP_RETURN (0); +#endif /* ACE_WIN32 */ +} + +bool +ACE::is_sock_error (int error) +{ +#if defined (ACE_WIN32) + switch (error) + { + case WSAVERNOTSUPPORTED: + case WSASYSNOTREADY: + case WSAEINVAL: + case WSAHOST_NOT_FOUND: + case WSATRY_AGAIN: + case WSANO_RECOVERY: + case WSANO_DATA: + /* + case WSANO_ADDRESS: + */ + case WSANOTINITIALISED: + case WSAENETDOWN: + case WSAEINPROGRESS: + case WSAEINTR: + case WSAEAFNOSUPPORT: + case WSAEMFILE: + case WSAENOBUFS: + case WSAEPROTONOSUPPORT: + case WSAEPROTOTYPE: + case WSAESOCKTNOSUPPORT: + case WSAENOTSOCK: + case WSAEWOULDBLOCK: + case WSAEADDRINUSE: + case WSAECONNABORTED: + case WSAECONNRESET: + case WSAENOTCONN: + case WSAETIMEDOUT: + case WSAECONNREFUSED: + case WSAEHOSTDOWN: + case WSAEHOSTUNREACH: + case WSAEADDRNOTAVAIL: + case WSAEISCONN: + case WSAENETRESET: + case WSAEMSGSIZE: + case WSAENETUNREACH: + case WSAEFAULT: + case WSAEDISCON: + case WSAEACCES: + case WSAESHUTDOWN: + case WSAEPROCLIM: + case WSAEALREADY: + case WSAEPFNOSUPPORT: + case WSAENOPROTOOPT: + case WSATYPE_NOT_FOUND: + case WSAEOPNOTSUPP: + return true; + } +#else + ACE_UNUSED_ARG (error); +#endif /* ACE_WIN32 */ + return false; +} + +char * +ACE::strndup (const char *str, size_t n) +{ + const char *t = str; + size_t len; + + // Figure out how long this string is (remember, it might not be + // NUL-terminated). + + for (len = 0; + len < n && *t++ != '\0'; + len++) + continue; + + char *s; + ACE_ALLOCATOR_RETURN (s, + (char *) ACE_OS::malloc (len + 1), + 0); + return ACE_OS::strsncpy (s, str, len + 1); +} + +#if defined (ACE_HAS_WCHAR) +wchar_t * +ACE::strndup (const wchar_t *str, size_t n) +{ + const wchar_t *t = str; + size_t len; + + // Figure out how long this string is (remember, it might not be + // NUL-terminated). + + for (len = 0; + len < n && *t++ != '\0'; + len++) + continue; + + wchar_t *s; + ACE_ALLOCATOR_RETURN (s, + static_cast ( + ACE_OS::malloc ((len + 1) * sizeof (wchar_t))), + 0); + return ACE_OS::strsncpy (s, str, len + 1); +} +#endif /* ACE_HAS_WCHAR */ + +char * +ACE::strnnew (const char *str, size_t n) +{ + const char *t = str; + size_t len; + + // Figure out how long this string is (remember, it might not be + // NUL-terminated). + + for (len = 0; + len < n && *t++ != L'\0'; + len++) + continue; + + char *s; + ACE_NEW_RETURN (s, + char[len + 1], + 0); + return ACE_OS::strsncpy (s, str, len + 1); +} + +#if defined (ACE_HAS_WCHAR) +wchar_t * +ACE::strnnew (const wchar_t *str, size_t n) +{ + const wchar_t *t = str; + size_t len; + + // Figure out how long this string is (remember, it might not be + // NUL-terminated). + + for (len = 0; + len < n && *t++ != ACE_TEXT_WIDE ('\0'); + len++) + continue; + + wchar_t *s; + ACE_NEW_RETURN (s, + wchar_t[len + 1], + 0); + return ACE_OS::strsncpy (s, str, len + 1); +} +#endif /* ACE_HAS_WCHAR */ + +const char * +ACE::strend (const char *s) +{ + while (*s++ != '\0') + continue; + + return s; +} + +#if defined ACE_HAS_WCHAR +const wchar_t * +ACE::strend (const wchar_t *s) +{ + while (*s++ != ACE_TEXT_WIDE ('\0')) + continue; + + return s; +} +#endif + +char * +ACE::strnew (const char *s) +{ + if (s == 0) + return 0; + char *t = 0; + ACE_NEW_RETURN (t, + char [ACE_OS::strlen (s) + 1], + 0); + if (t == 0) + return 0; + else + return ACE_OS::strcpy (t, s); +} + +#if defined (ACE_HAS_WCHAR) +wchar_t * +ACE::strnew (const wchar_t *s) +{ + if (s == 0) + return 0; + wchar_t *t = 0; + ACE_NEW_RETURN (t, + wchar_t[ACE_OS::strlen (s) + 1], + 0); + if (t == 0) + return 0; + else + return ACE_OS::strcpy (t, s); +} +#endif /* ACE_HAS_WCHAR */ + +// helper functions for ACE::wild_match() +namespace +{ + + inline bool equal_char (char a, char b, bool case_sensitive) + { + if (case_sensitive) + return a == b; + return ACE_OS::ace_tolower (a) == ACE_OS::ace_tolower (b); + } + + // precond: *p == '[' start of char class + // postcond: *p == ']' end of the char class + inline bool equal_class (char s, const char *&p, bool case_sensitive) + { + ++p; + bool negate = false; + if (*p == '!') + { + negate = true; + ++p; + } + // ] and - are regular in 1st position + for (bool first = true; *p && (first || *p != ']'); ++p) + { + if (!first && *p == '-' && p[1] != ']') + { + if (!p[1] || p[1] <= p[-1]) // invalid range + { + continue; + } + // Since we are in the POSIX locale, only the basic ASCII + // characters are allowed as the range endpoints. These characters + // are the same values in both signed and unsigned chars so we + // don't have to account for any "pathological cases." + for (char range = p[-1] + 1; range <= p[1]; ++range) + { + if (equal_char (s, range, case_sensitive)) + { + while (*++p != ']') {} + return !negate; + } + } + ++p; // consume the character 1 past the - + } + else if (equal_char (s, *p, case_sensitive)) + { + while (*++p != ']') {} + return !negate; + } + first = false; + } + return negate; + } +} + +bool +ACE::wild_match(const char *str, const char *pat, bool case_sensitive, + bool character_classes) +{ + if (str == pat) + return true; + if (pat == 0 || str == 0) + return false; + + bool star = false, escape = false; + const char *s = str; + const char *p = pat; + while (*s != '\0') + { + if (!escape && *p == '\\') + { + ++p; + escape = true; + } + else if (!escape && *p == '*') + { + star = true; + pat = p; + while (*++pat == '*') {} + + if (*pat == '\0') + return true; + p = pat; + } + else if (!escape && *p == '?') + { + ++s; + ++p; + } + else if (!escape && character_classes && *p == '[') + { + if (equal_class (*s, p, case_sensitive)) + { + ++p; + } + else + { + if (!star) + return false; + p = pat; + } + ++s; + } + else if (!equal_char (*s, *p, case_sensitive)) + { + if (!star) + return false; + ++s; + p = pat; + escape = false; + } + else + { + ++s; + ++p; + escape = false; + } + } + if (*p == '*') + while (*++p == '*') {} + + return *p == '\0'; +} + +// Close versioned namespace, if enabled by the user. +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/ACE.h b/dep/acelite/ace/ACE.h new file mode 100644 index 00000000000..56ce13cfd75 --- /dev/null +++ b/dep/acelite/ace/ACE.h @@ -0,0 +1,849 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file ACE.h + * + * $Id: ACE.h 88193 2009-12-16 09:14:06Z mcorino $ + * + * This file contains value added ACE functions that extend the + * behavior of the UNIX and Win32 OS calls. + * + * All these ACE static functions are consolidated in a single place + * in order to manage the namespace better. These functions are put + * here rather than in @c ACE_OS in order to separate concerns. + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_ACE_H +#define ACE_ACE_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/OS_NS_math.h" +#include "ace/Flag_Manip.h" +#include "ace/Handle_Ops.h" +#include "ace/Lib_Find.h" +#include "ace/Init_ACE.h" +#include "ace/Sock_Connect.h" +#include "ace/Default_Constants.h" + +#if defined (ACE_EXPORT_MACRO) +# undef ACE_EXPORT_MACRO +#endif +#define ACE_EXPORT_MACRO ACE_Export + +// Open versioned namespace, if enabled by the user. +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Forward declarations. +class ACE_Time_Value; +class ACE_Message_Block; +class ACE_Handle_Set; + +/** + * @namespace ACE + * + * @brief The namespace containing the ACE framework itself. + * + * The ACE namespace contains all types (classes, structures, + * typedefs, etc), and global functions and variables in the ACE + * framework. + */ +namespace ACE +{ + // = ACE version information. + /// e.g., the "5" in ACE 5.1.12. + extern ACE_Export u_int major_version (void); + + /// e.g., the "1" in ACE 5.1.12. + extern ACE_Export u_int minor_version (void); + + /// e.g., the "12" in ACE 5.1.12. + /// Returns 0 for "stable" (non-beta) releases. + extern ACE_Export u_int beta_version (void); + + // = C++ compiler version information. + /// E.g., the "SunPro C++" in SunPro C++ 4.32.0 + extern ACE_Export const ACE_TCHAR * compiler_name (void); + + /// E.g., the "4" in SunPro C++ 4.32.0 + extern ACE_Export u_int compiler_major_version (void); + + /// E.g., the "32" in SunPro C++ 4.32.0 + extern ACE_Export u_int compiler_minor_version (void); + + /// E.g., the "0" in SunPro C++ 4.32.0 + extern ACE_Export u_int compiler_beta_version (void); + + /// Check if error indicates the process being out of handles (file + /// descriptors). + extern ACE_Export int out_of_handles (int error); + + /// Simple wildcard matching function supporting '*' and '?' + /// return true if string s matches pattern. + /// If character_classes is true, '[' is treated as a wildcard character + /// as described in the fnmatch() POSIX API. The following POSIX "bracket + /// expression" features are not implemented: collating symbols, equivalence + /// class expressions, and character class expressions. The POSIX locale is + /// assumed. + extern ACE_Export bool wild_match(const char* s, const char* pattern, + bool case_sensitive = true, bool character_classes = false); + + /** + * @name I/O operations + * + * Notes on common parameters: + * + * @a handle is the connected endpoint that will be used for I/O. + * + * @a buf is the buffer to write from or receive into. + * + * @a len is the number of bytes to transfer. + * + * The @a timeout parameter in the following methods indicates how + * long to blocking trying to transfer data. If @a timeout == 0, + * then the call behaves as a normal send/recv call, i.e., for + * blocking sockets, the call will block until action is possible; + * for non-blocking sockets, @c EWOULDBLOCK will be returned if no + * action is immediately possible. + * + * If @a timeout != 0, the call will wait until the relative time + * specified in @a *timeout elapses. + * + * The "_n()" I/O methods keep looping until all the data has been + * transferred. These methods also work for sockets in non-blocking + * mode i.e., they keep looping on @c EWOULDBLOCK. @a timeout is + * used to make sure we keep making progress, i.e., the same timeout + * value is used for every I/O operation in the loop and the timeout + * is not counted down. + * + * The return values for the "*_n()" methods match the return values + * from the non "_n()" methods and are specified as follows: + * + * - On complete transfer, the number of bytes transferred is returned. + * - On timeout, -1 is returned, @c errno == @c ETIME. + * - On error, -1 is returned, @c errno is set to appropriate error. + * - On @c EOF, 0 is returned, @c errno is irrelevant. + * + * On partial transfers, i.e., if any data is transferred before + * timeout / error / @c EOF, @a bytes_transferred> will contain the + * number of bytes transferred. + * + * Methods with @a iovec parameter are I/O vector variants of the + * I/O operations. + * + * Methods with the extra @a flags argument will always result in + * @c send getting called. Methods without the extra @a flags + * argument will result in @c send getting called on Win32 + * platforms, and @c write getting called on non-Win32 platforms. + */ + //@{ + extern ACE_Export ssize_t recv (ACE_HANDLE handle, + void *buf, + size_t len, + int flags, + const ACE_Time_Value *timeout = 0); + +#if defined (ACE_HAS_TLI) + + extern ACE_Export ssize_t t_rcv (ACE_HANDLE handle, + void *buf, + size_t len, + int *flags, + const ACE_Time_Value *timeout = 0); + +#endif /* ACE_HAS_TLI */ + + extern ACE_Export ssize_t recv (ACE_HANDLE handle, + void *buf, + size_t len, + const ACE_Time_Value *timeout = 0); + + extern ACE_Export ssize_t recvmsg (ACE_HANDLE handle, + struct msghdr *msg, + int flags, + const ACE_Time_Value *timeout = 0); + + extern ACE_Export ssize_t recvfrom (ACE_HANDLE handle, + char *buf, + int len, + int flags, + struct sockaddr *addr, + int *addrlen, + const ACE_Time_Value *timeout = 0); + + ACE_NAMESPACE_INLINE_FUNCTION + ssize_t recv_n (ACE_HANDLE handle, + void *buf, + size_t len, + int flags, + const ACE_Time_Value *timeout = 0, + size_t *bytes_transferred = 0); + +#if defined (ACE_HAS_TLI) + + ACE_NAMESPACE_INLINE_FUNCTION + ssize_t t_rcv_n (ACE_HANDLE handle, + void *buf, + size_t len, + int *flags, + const ACE_Time_Value *timeout = 0, + size_t *bytes_transferred = 0); + +#endif /* ACE_HAS_TLI */ + + ACE_NAMESPACE_INLINE_FUNCTION + ssize_t recv_n (ACE_HANDLE handle, + void *buf, + size_t len, + const ACE_Time_Value *timeout = 0, + size_t *bytes_transferred = 0); + + /// Receive into a variable number of pieces. + /** + * Accepts a variable, caller-specified, number of pointer/length + * pairs. Arguments following @a n are char *, size_t pairs. + * + * @param handle The I/O handle to receive on + * @param n The total number of char *, size_t pairs following @a n. + * + * @return -1 on error, else total number of bytes received. + */ + extern ACE_Export ssize_t recv (ACE_HANDLE handle, size_t n, ...); + + extern ACE_Export ssize_t recvv (ACE_HANDLE handle, + iovec *iov, + int iovcnt, + const ACE_Time_Value *timeout = 0); + + ACE_NAMESPACE_INLINE_FUNCTION + ssize_t recvv_n (ACE_HANDLE handle, + iovec *iov, + int iovcnt, + const ACE_Time_Value *timeout = 0, + size_t *bytes_transferred = 0); + + extern ACE_Export ssize_t recv_n (ACE_HANDLE handle, + ACE_Message_Block *message_block, + const ACE_Time_Value *timeout = 0, + size_t *bytes_transferred = 0); + + extern ACE_Export ssize_t send (ACE_HANDLE handle, + const void *buf, + size_t len, + int flags, + const ACE_Time_Value *timeout = 0); + +#if defined (ACE_HAS_TLI) + + extern ACE_Export ssize_t t_snd (ACE_HANDLE handle, + const void *buf, + size_t len, + int flags, + const ACE_Time_Value *timeout = 0); + +#endif /* ACE_HAS_TLI */ + + extern ACE_Export ssize_t send (ACE_HANDLE handle, + const void *buf, + size_t len, + const ACE_Time_Value *timeout = 0); + + extern ACE_Export ssize_t sendmsg (ACE_HANDLE handle, + const struct msghdr *msg, + int flags, + const ACE_Time_Value *timeout = 0); + + extern ACE_Export ssize_t sendto (ACE_HANDLE handle, + const char *buf, + int len, + int flags, + const struct sockaddr *addr, + int addrlen, + const ACE_Time_Value *timeout = 0); + + ACE_NAMESPACE_INLINE_FUNCTION + ssize_t send_n (ACE_HANDLE handle, + const void *buf, + size_t len, + int flags, + const ACE_Time_Value *timeout = 0, + size_t *bytes_transferred = 0); + +#if defined (ACE_HAS_TLI) + + ACE_NAMESPACE_INLINE_FUNCTION + ssize_t t_snd_n (ACE_HANDLE handle, + const void *buf, + size_t len, + int flags, + const ACE_Time_Value *timeout = 0, + size_t *bytes_transferred = 0); + +#endif /* ACE_HAS_TLI */ + + ACE_NAMESPACE_INLINE_FUNCTION + ssize_t send_n (ACE_HANDLE handle, + const void *buf, + size_t len, + const ACE_Time_Value *timeout = 0, + size_t *bytes_transferred = 0); + + /// Varargs variant. + extern ACE_Export ssize_t send (ACE_HANDLE handle, size_t n, ...); + + extern ACE_Export ssize_t sendv (ACE_HANDLE handle, + const iovec *iov, + int iovcnt, + const ACE_Time_Value *timeout = 0); + + ACE_NAMESPACE_INLINE_FUNCTION + ssize_t sendv_n (ACE_HANDLE handle, + const iovec *iov, + int iovcnt, + const ACE_Time_Value *timeout = 0, + size_t *bytes_transferred = 0); + + /// Send all the @a message_blocks chained through their @c next and + /// @c cont pointers. This call uses the underlying OS gather-write + /// operation to reduce the domain-crossing penalty. + extern ACE_Export ssize_t send_n (ACE_HANDLE handle, + const ACE_Message_Block *message_block, + const ACE_Time_Value *timeout = 0, + size_t *bytes_transferred = 0); + + // = File system I/O functions (these don't support timeouts). + + ACE_NAMESPACE_INLINE_FUNCTION + ssize_t read_n (ACE_HANDLE handle, + void *buf, + size_t len, + size_t *bytes_transferred = 0); + + ACE_NAMESPACE_INLINE_FUNCTION + ssize_t write_n (ACE_HANDLE handle, + const void *buf, + size_t len, + size_t *bytes_transferred = 0); + + /// Write all the @a message_blocks chained through their @c next + /// and @c cont pointers. This call uses the underlying OS + /// gather-write operation to reduce the domain-crossing penalty. + extern ACE_Export ssize_t write_n (ACE_HANDLE handle, + const ACE_Message_Block *message_block, + size_t *bytes_transferred = 0); + + extern ACE_Export ssize_t readv_n (ACE_HANDLE handle, + iovec *iov, + int iovcnt, + size_t *bytes_transferred = 0); + + extern ACE_Export ssize_t writev_n (ACE_HANDLE handle, + const iovec *iov, + int iovcnt, + size_t *bytes_transferred = 0); + //@} + + /** + * Wait up to @a timeout amount of time to passively establish a + * connection. This method doesn't perform the @c accept, it just + * does the timed wait. + */ + extern ACE_Export int handle_timed_accept (ACE_HANDLE listener, + ACE_Time_Value *timeout, + bool restart); + + /** + * Wait up to @a timeout amount of time to complete an actively + * established non-blocking connection. If @a is_tli is non-0 then + * we are being called by a TLI wrapper (which behaves slightly + * differently from a socket wrapper). + */ + extern ACE_Export ACE_HANDLE handle_timed_complete ( + ACE_HANDLE listener, + const ACE_Time_Value *timeout, + int is_tli = 0); + + /** + * Reset the limit on the number of open handles. If @a new_limit + * == -1 set the limit to the maximum allowable. Otherwise, set + * the limit value to @a new_limit. If @a increase_limit_only is + * non-0 then only allow increases to the limit. + */ + extern ACE_Export int set_handle_limit (int new_limit = -1, + int increase_limit_only = 0); + + /** + * Returns the maximum number of open handles currently permitted in + * this process. This maximum may be extended using + * @c ACE::set_handle_limit. + */ + extern ACE_Export int max_handles (void); + + // = String functions + /** + * Return a dynamically allocated duplicate of @a str, substituting + * the environment variable if @c str[0] @c == @c '$'. Note that + * the pointer is allocated with @c ACE_OS::malloc and must be freed + * by @c ACE_OS::free. + */ + extern ACE_Export ACE_TCHAR *strenvdup (const ACE_TCHAR *str); + + /// Returns a pointer to the "end" of the string, i.e., the character + /// past the '\0'. + extern ACE_Export const char *strend (const char *s); + + /// This method is just like @c strdup, except that it uses + /// @c operator @c new rather than @c malloc. If @a s is NULL + /// returns NULL rather than segfaulting. + extern ACE_Export char *strnew (const char *s); + + /// Delete the memory allocated by @c strnew. + ACE_NAMESPACE_INLINE_FUNCTION void strdelete (char *s); + + /// Create a fresh new copy of @a str, up to @a n chars long. Uses + /// @c ACE_OS::malloc to allocate the new string. + extern ACE_Export char *strndup (const char *str, size_t n); + + /// Create a fresh new copy of @a str, up to @a n chars long. Uses + /// @c ACE_OS::malloc to allocate the new string. + extern ACE_Export char *strnnew (const char *str, size_t n); + + /// Determine if a specified pathname is "dot dir" (ie. "." or ".."). + ACE_NAMESPACE_INLINE_FUNCTION bool isdotdir (const char *s); + +#if defined (ACE_HAS_WCHAR) + extern ACE_Export const wchar_t *strend (const wchar_t *s); + + extern ACE_Export wchar_t *strnew (const wchar_t *s); + + ACE_NAMESPACE_INLINE_FUNCTION void strdelete (wchar_t *s); + + extern ACE_Export wchar_t *strndup (const wchar_t *str, size_t n); + + extern ACE_Export wchar_t *strnnew (const wchar_t *str, size_t n); + + ACE_NAMESPACE_INLINE_FUNCTION bool isdotdir (const wchar_t *s); + +#endif /* ACE_HAS_WCHAR */ + + /** + * On Windows, determines if a specified pathname ends with ".exe" + * (not case sensitive). If on Windows and there is no ".exe" suffix, + * a new ACE_TCHAR array is allocated and a copy of @c pathname with + * the ".exe" suffix is copied into it. In this case, the caller is + * responsible for calling delete [] on the returned pointer. + * + * @param pathname The name to check for a proper suffix. + * + * @retval @c pathname if there is a proper suffix for Windows. This is + * always the return value for non-Windows platforms. + * @retval If a suffix needs to be added, returns a pointer to new[] + * allocated memory containing the original @c pathname plus + * a ".exe" suffix. The caller is responsible for freeing the + * memory using delete []. + */ + extern ACE_Export const ACE_TCHAR *execname (const ACE_TCHAR *pathname); + + /** + * Returns the "basename" of a @a pathname separated by @a delim. + * For instance, the basename of "/tmp/foo.cpp" is "foo.cpp" when + * @a delim is @a '/'. + */ + extern ACE_Export const ACE_TCHAR *basename (const ACE_TCHAR *pathname, + ACE_TCHAR delim = + ACE_DIRECTORY_SEPARATOR_CHAR); + + /** + * Returns the "dirname" of a @a pathname. For instance, the + * dirname of "/tmp/foo.cpp" is "/tmp" when @a delim is @a '/'. If + * @a pathname has no @a delim ".\0" is returned. This method does + * not modify @a pathname and is not reentrant. + */ + extern ACE_Export const ACE_TCHAR *dirname (const ACE_TCHAR *pathname, + ACE_TCHAR delim = + ACE_DIRECTORY_SEPARATOR_CHAR); + + /** + * Returns the given timestamp in the form + * "hour:minute:second:microsecond." The month, day, and year are + * also stored in the beginning of the @a date_and_time array, which + * is a user-supplied array of size @a time_len> @c ACE_TCHARs. + * Returns 0 if unsuccessful, else returns pointer to beginning of the + * "time" portion of @a date_and_time. If @a + * return_pointer_to_first_digit is 0 then return a pointer to the + * space before the time, else return a pointer to the beginning of + * the time portion. + */ + extern ACE_Export ACE_TCHAR *timestamp (const ACE_Time_Value& time_value, + ACE_TCHAR date_and_time[], + size_t time_len, + bool return_pointer_to_first_digit = false); + + /** + * Returns the current timestamp in the form + * "hour:minute:second:microsecond." The month, day, and year are + * also stored in the beginning of the @a date_and_time array, which + * is a user-supplied array of size @a time_len> @c ACE_TCHARs. + * Returns 0 if unsuccessful, else returns pointer to beginning of the + * "time" portion of @a date_and_time. If @a + * return_pointer_to_first_digit is 0 then return a pointer to the + * space before the time, else return a pointer to the beginning of + * the time portion. + */ + extern ACE_Export ACE_TCHAR *timestamp (ACE_TCHAR date_and_time[], + size_t time_len, + bool return_pointer_to_first_digit = false); + + /** + * if @a avoid_zombies == 0 call @c ACE_OS::fork directly, else + * create an orphan process that's inherited by the init process; + * init cleans up when the orphan process terminates so we don't + * create zombies. Returns -1 on failure and either the child PID + * on success if @a avoid_zombies == 0 or 1 on success if @a + * avoid_zombies != 0 (this latter behavior is a known bug that + * needs to be fixed). + */ + extern ACE_Export pid_t fork ( + const ACE_TCHAR *program_name = ACE_TEXT (""), + int avoid_zombies = 0); + + /** + * Become a daemon process using the algorithm in Richard Stevens + * "Advanced Programming in the UNIX Environment." If + * @a close_all_handles is non-zero then all open file handles are + * closed. + */ + extern ACE_Export int daemonize ( + const ACE_TCHAR pathname[] = ACE_TEXT ("/"), + bool close_all_handles = ACE_DEFAULT_CLOSE_ALL_HANDLES, + const ACE_TCHAR program_name[] = ACE_TEXT ("")); + + // = Miscellaneous functions. + /// Rounds the request to a multiple of the page size. + extern ACE_Export size_t round_to_pagesize (size_t len); + + /// Rounds the request to a multiple of the allocation granularity. + extern ACE_Export size_t round_to_allocation_granularity (size_t len); + + // @@ UNICODE what about buffer? + /// Format buffer into printable format. This is useful for + /// debugging. + extern ACE_Export size_t format_hexdump (const char *buffer, size_t size, + ACE_TCHAR *obuf, size_t obuf_sz); + + /// Computes the hash value of {str} using the "Hash PJW" routine. + extern ACE_Export u_long hash_pjw (const char *str); + + /// Computes the hash value of {str} using the "Hash PJW" routine. + extern ACE_Export u_long hash_pjw (const char *str, size_t len); + +#if defined (ACE_HAS_WCHAR) + /// Computes the hash value of {str} using the "Hash PJW" routine. + extern ACE_Export u_long hash_pjw (const wchar_t *str); + + /// Computes the hash value of {str} using the "Hash PJW" routine. + extern ACE_Export u_long hash_pjw (const wchar_t *str, size_t len); +#endif /* ACE_HAS_WCHAR */ + + /// Computes CRC-CCITT for the string. + extern ACE_Export ACE_UINT16 crc_ccitt(const char *str); + + /// Computes CRC-CCITT for the buffer. + extern ACE_Export ACE_UINT16 crc_ccitt(const void *buf, size_t len, + ACE_UINT16 crc = 0); + + /// Computes CRC-CCITT for the @ len iovec buffers. + extern ACE_Export ACE_UINT16 crc_ccitt(const iovec *iov, int len, + ACE_UINT16 crc = 0); + + /// Computes the ISO 8802-3 standard 32 bits CRC for the string. + extern ACE_Export ACE_UINT32 crc32 (const char *str); + + /// Computes the ISO 8802-3 standard 32 bits CRC for the buffer. + extern ACE_Export ACE_UINT32 crc32 (const void *buf, size_t len, + ACE_UINT32 crc = 0); + + /// Computes the ISO 8802-3 standard 32 bits CRC for the + /// @ len iovec buffers. + extern ACE_Export ACE_UINT32 crc32 (const iovec *iov, int len, + ACE_UINT32 crc = 0); + + /// Euclid's greatest common divisor algorithm. + extern ACE_Export u_long gcd (u_long x, u_long y); + + /// Calculates the minimum enclosing frame size for the given values. + extern ACE_Export u_long minimum_frame_size (u_long period1, u_long period2); + + /** + * Function that can burn up noticeable CPU time: brute-force + * determination of whether number @a n is prime. Returns 0 if + * it is prime, or the smallest factor if it is not prime. + * @a min_factor and @a max_factor can be used to partition the work + * among threads. For just one thread, typical values are 2 and + * n/2. + */ + extern ACE_Export u_long is_prime (const u_long n, + const u_long min_factor, + const u_long max_factor); + + /// Map troublesome win32 errno values to values that standard C + /// strerr function understands. Thank you Microsoft. + extern ACE_Export int map_errno (int error); + + /// Returns a string containing the error message corresponding to a + /// WinSock error. This works around an omission in the Win32 API. + /// @internal + extern ACE_Export const ACE_TCHAR * sock_error (int error); + + /// Determins whether the given error code corresponds to to a + /// WinSock error. If so returns true, false otherwise. + /// @internal + extern ACE_Export bool is_sock_error (int error); + + /** + * Checks if process with {pid} is still alive. Returns 1 if it is + * still alive, 0 if it isn't alive, and -1 if something weird + * happened. + */ + extern ACE_Export int process_active (pid_t pid); + + /** + * Terminate the process abruptly with id @a pid. On Win32 platforms + * this uses {TerminateProcess} and on POSIX platforms is uses + * {kill} with the -9 (SIGKILL) signal, which cannot be caught or + * ignored. Note that this call is potentially dangerous to use + * since the process being terminated may not have a chance to + * cleanup before it shuts down. + */ + extern ACE_Export int terminate_process (pid_t pid); + + /** + * This method uses process id and object pointer to come up with a + * machine wide unique name. The process ID will provide uniqueness + * between processes on the same machine. The "this" pointer of the + * {object} will provide uniqueness between other "live" objects in + * the same process. The uniqueness of this name is therefore only + * valid for the life of {object}. + */ + ACE_NAMESPACE_INLINE_FUNCTION void unique_name (const void *object, + ACE_TCHAR *name, + size_t length); + + /// Computes the base 2 logarithm of {num}. + ACE_NAMESPACE_INLINE_FUNCTION u_long log2 (u_long num); + + /// Hex conversion utility. + extern ACE_Export ACE_TCHAR nibble2hex (u_int n); + + /// Convert a hex character to its byte representation. + ACE_NAMESPACE_INLINE_FUNCTION u_char hex2byte (ACE_TCHAR c); + + // = Set/get the debug level. + extern ACE_Export bool debug (void); + extern ACE_Export void debug (bool onoff); + + /// Wrapper facade for @c select that uses @c ACE_Handle_Sets. + extern ACE_Export int select (int width, + ACE_Handle_Set *readfds, + ACE_Handle_Set *writefds = 0, + ACE_Handle_Set *exceptfds = 0, + const ACE_Time_Value *timeout = 0); + + /// Wrapper facade for the most common use of @c select that uses + /// @c ACE_Handle_Sets. + extern ACE_Export int select (int width, + ACE_Handle_Set &readfds, + const ACE_Time_Value *timeout = 0); + + /// Timed wait for handle to get read ready. + ACE_NAMESPACE_INLINE_FUNCTION + int handle_read_ready (ACE_HANDLE handle, + const ACE_Time_Value *timeout); + + /// Timed wait for handle to get write ready. + ACE_NAMESPACE_INLINE_FUNCTION + int handle_write_ready (ACE_HANDLE handle, + const ACE_Time_Value *timeout); + + /// Timed wait for handle to get exception ready. + ACE_NAMESPACE_INLINE_FUNCTION + int handle_exception_ready (ACE_HANDLE handle, + const ACE_Time_Value *timeout); + + /// Timed wait for handle to get read, write, or exception ready. + extern ACE_Export int handle_ready (ACE_HANDLE handle, + const ACE_Time_Value *timeout, + int read_ready, + int write_ready, + int exception_ready); + + /// Wait for @a timeout before proceeding to a @c recv operation. + /// @a val keeps track of whether we're in non-blocking mode or + /// not. + extern ACE_Export int enter_recv_timedwait (ACE_HANDLE handle, + const ACE_Time_Value *timeout, + int &val); + + /// Wait for @a timeout before proceeding to a @c send operation. + /// @a val keeps track of whether we're in non-blocking mode or + /// not. + extern ACE_Export int enter_send_timedwait (ACE_HANDLE handle, + const ACE_Time_Value* timeout, + int &val); + + /// This makes sure that @a handle is set into non-blocking mode. + /// @a val keeps track of whether were in non-blocking mode or not. + extern ACE_Export void record_and_set_non_blocking_mode (ACE_HANDLE handle, + int &val); + + /// Cleanup after a timed operation, restore the appropriate + /// non-blocking status of @a handle. + extern ACE_Export void restore_non_blocking_mode (ACE_HANDLE handle, + int val); + + // private: + // These functions aren't meant to be used internally, so they are + // not exported. + + // + // = Recv_n helpers + // + + ACE_NAMESPACE_INLINE_FUNCTION ssize_t recv_i (ACE_HANDLE handle, + void *buf, + size_t len); + + extern ACE_Export ssize_t recv_n_i (ACE_HANDLE handle, + void *buf, + size_t len, + int flags, + size_t *bytes_transferred); + + extern ACE_Export ssize_t recv_n_i (ACE_HANDLE handle, + void *buf, + size_t len, + int flags, + const ACE_Time_Value *timeout, + size_t *bytes_transferred); + +#if defined (ACE_HAS_TLI) + + extern ACE_Export ssize_t t_rcv_n_i (ACE_HANDLE handle, + void *buf, + size_t len, + int *flags, + size_t *bytes_transferred); + + extern ACE_Export ssize_t t_rcv_n_i (ACE_HANDLE handle, + void *buf, + size_t len, + int *flags, + const ACE_Time_Value *timeout, + size_t *bytes_transferred); + +#endif /* ACE_HAS_TLI */ + + extern ACE_Export ssize_t recv_n_i (ACE_HANDLE handle, + void *buf, + size_t len, + size_t *bytes_transferred); + + extern ACE_Export ssize_t recv_n_i (ACE_HANDLE handle, + void *buf, + size_t len, + const ACE_Time_Value *timeout, + size_t *bytes_transferred); + + extern ACE_Export ssize_t recvv_n_i (ACE_HANDLE handle, + iovec *iov, + int iovcnt, + size_t *bytes_transferred); + + extern ACE_Export ssize_t recvv_n_i (ACE_HANDLE handle, + iovec *iov, + int iovcnt, + const ACE_Time_Value *timeout, + size_t *bytes_transferred); + + // + // = Send_n helpers + // + + ACE_NAMESPACE_INLINE_FUNCTION ssize_t send_i (ACE_HANDLE handle, + const void *buf, + size_t len); + + extern ACE_Export ssize_t send_n_i (ACE_HANDLE handle, + const void *buf, + size_t len, + int flags, + size_t *bytes_transferred); + + extern ACE_Export ssize_t send_n_i (ACE_HANDLE handle, + const void *buf, + size_t len, + int flags, + const ACE_Time_Value *timeout, + size_t *bytes_transferred); + +#if defined (ACE_HAS_TLI) + + extern ACE_Export ssize_t t_snd_n_i (ACE_HANDLE handle, + const void *buf, + size_t len, + int flags, + size_t *bytes_transferred); + + extern ACE_Export ssize_t t_snd_n_i (ACE_HANDLE handle, + const void *buf, + size_t len, + int flags, + const ACE_Time_Value *timeout, + size_t *bytes_transferred); + +#endif /* ACE_HAS_TLI */ + + extern ACE_Export ssize_t send_n_i (ACE_HANDLE handle, + const void *buf, + size_t len, + size_t *bytes_transferred); + + extern ACE_Export ssize_t send_n_i (ACE_HANDLE handle, + const void *buf, + size_t len, + const ACE_Time_Value *timeout, + size_t *bytes_transferred); + + extern ACE_Export ssize_t sendv_n_i (ACE_HANDLE handle, + const iovec *iov, + int iovcnt, + size_t *bytes_transferred); + + extern ACE_Export ssize_t sendv_n_i (ACE_HANDLE handle, + const iovec *iov, + int iovcnt, + const ACE_Time_Value *timeout, + size_t *bytes_transferred); + +} + +// Close versioned namespace, if enabled by the user. +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/ACE.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" + +#endif /* ACE_ACE_H */ diff --git a/dep/acelite/ace/ACE.inl b/dep/acelite/ace/ACE.inl new file mode 100644 index 00000000000..4be80bfb64c --- /dev/null +++ b/dep/acelite/ace/ACE.inl @@ -0,0 +1,348 @@ +// -*- C++ -*- +// +// $Id: ACE.inl 87366 2009-11-05 20:16:30Z olli $ + +#include "ace/OS_NS_unistd.h" +#include "ace/OS_NS_Thread.h" +#include "ace/OS_NS_ctype.h" +#include "ace/OS_NS_sys_socket.h" + +// Open versioned namespace, if enabled by the user. +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + + +// Wrappers for methods that have been moved to ACE_OS. + +ACE_INLINE ssize_t +ACE::read_n (ACE_HANDLE handle, + void *buf, + size_t len, + size_t *bytes_transferred) +{ + return ACE_OS::read_n (handle, + buf, + len, + bytes_transferred); +} + +ACE_INLINE ssize_t +ACE::write_n (ACE_HANDLE handle, + const void *buf, + size_t len, + size_t *bytes_transferred) +{ + return ACE_OS::write_n (handle, + buf, + len, + bytes_transferred); +} + +ACE_INLINE ssize_t +ACE::recv_n (ACE_HANDLE handle, + void *buf, + size_t len, + int flags, + const ACE_Time_Value *timeout, + size_t *bytes_transferred) +{ + if (timeout == 0) + return ACE::recv_n_i (handle, + buf, + len, + flags, + bytes_transferred); + else + return ACE::recv_n_i (handle, + buf, + len, + flags, + timeout, + bytes_transferred); +} + +#if defined (ACE_HAS_TLI) + +ACE_INLINE ssize_t +ACE::t_rcv_n (ACE_HANDLE handle, + void *buf, + size_t len, + int *flags, + const ACE_Time_Value *timeout, + size_t *bytes_transferred) +{ + if (timeout == 0) + return ACE::t_rcv_n_i (handle, + buf, + len, + flags, + bytes_transferred); + else + return ACE::t_rcv_n_i (handle, + buf, + len, + flags, + timeout, + bytes_transferred); +} + +#endif /* ACE_HAS_TLI */ + +ACE_INLINE ssize_t +ACE::recv_n (ACE_HANDLE handle, + void *buf, + size_t len, + const ACE_Time_Value *timeout, + size_t *bytes_transferred) +{ + if (timeout == 0) + return ACE::recv_n_i (handle, + buf, + len, + bytes_transferred); + else + return ACE::recv_n_i (handle, + buf, + len, + timeout, + bytes_transferred); +} + +ACE_INLINE ssize_t +ACE::recvv_n (ACE_HANDLE handle, + iovec *iov, + int iovcnt, + const ACE_Time_Value *timeout, + size_t *bytes_transferred) +{ + if (timeout == 0) + return ACE::recvv_n_i (handle, + iov, + iovcnt, + bytes_transferred); + else + return ACE::recvv_n_i (handle, + iov, + iovcnt, + timeout, + bytes_transferred); +} + +ACE_INLINE ssize_t +ACE::send_n (ACE_HANDLE handle, + const void *buf, + size_t len, + int flags, + const ACE_Time_Value *timeout, + size_t *bytes_transferred) +{ + if (timeout == 0) + return ACE::send_n_i (handle, + buf, + len, + flags, + bytes_transferred); + else + return ACE::send_n_i (handle, + buf, + len, + flags, + timeout, + bytes_transferred); +} + +#if defined (ACE_HAS_TLI) + +ACE_INLINE ssize_t +ACE::t_snd_n (ACE_HANDLE handle, + const void *buf, + size_t len, + int flags, + const ACE_Time_Value *timeout, + size_t *bytes_transferred) +{ + if (timeout == 0) + return ACE::t_snd_n_i (handle, + buf, + len, + flags, + bytes_transferred); + else + return ACE::t_snd_n_i (handle, + buf, + len, + flags, + timeout, + bytes_transferred); +} + +#endif /* ACE_HAS_TLI */ + +ACE_INLINE ssize_t +ACE::send_n (ACE_HANDLE handle, + const void *buf, + size_t len, + const ACE_Time_Value *timeout, + size_t *bytes_transferred) +{ + if (timeout == 0) + return ACE::send_n_i (handle, + buf, + len, + bytes_transferred); + else + return ACE::send_n_i (handle, + buf, + len, + timeout, + bytes_transferred); +} + +ACE_INLINE ssize_t +ACE::sendv_n (ACE_HANDLE handle, + const iovec *iov, + int iovcnt, + const ACE_Time_Value *timeout, + size_t *bytes_transferred) +{ + if (timeout == 0) + return ACE::sendv_n_i (handle, + iov, + iovcnt, + bytes_transferred); + else + return ACE::sendv_n_i (handle, + iov, + iovcnt, + timeout, + bytes_transferred); +} + +ACE_INLINE ssize_t +ACE::send_i (ACE_HANDLE handle, const void *buf, size_t len) +{ +#if defined (ACE_WIN32) || defined (HPUX) + return ACE_OS::send (handle, (const char *) buf, len); +#else + return ACE_OS::write (handle, (const char *) buf, len); +#endif /* ACE_WIN32 */ +} + +ACE_INLINE ssize_t +ACE::recv_i (ACE_HANDLE handle, void *buf, size_t len) +{ +#if defined (ACE_WIN32) || defined (ACE_OPENVMS) || defined (ACE_TANDEM_T1248_PTHREADS) + return ACE_OS::recv (handle, (char *) buf, len); +#else + return ACE_OS::read (handle, (char *) buf, len); +#endif /* ACE_WIN32 */ +} + +ACE_INLINE int +ACE::handle_read_ready (ACE_HANDLE handle, + const ACE_Time_Value *timeout) +{ + return ACE::handle_ready (handle, + timeout, + 1, + 0, + 0); +} + +ACE_INLINE int +ACE::handle_write_ready (ACE_HANDLE handle, + const ACE_Time_Value *timeout) +{ + return ACE::handle_ready (handle, + timeout, + 0, + 1, + 0); +} + +ACE_INLINE int +ACE::handle_exception_ready (ACE_HANDLE handle, + const ACE_Time_Value *timeout) +{ + return ACE::handle_ready (handle, + timeout, + 0, + 0, + 1); +} + +ACE_INLINE void +ACE::strdelete (char *s) +{ + delete [] s; +} + +#if defined (ACE_HAS_WCHAR) +ACE_INLINE void +ACE::strdelete (wchar_t *s) +{ + delete [] s; +} +#endif /* ACE_HAS_WCHAR */ + +ACE_INLINE bool +ACE::isdotdir (const char *s) +{ + return (s[0] == '.' && + ((s[1] == 0) || (s[1] == '.' && s[2] == 0))); +} + +#if defined (ACE_HAS_WCHAR) +ACE_INLINE bool +ACE::isdotdir (const wchar_t *s) +{ + return (s[0] == ACE_TEXT ('.') && + ((s[1] == 0) || (s[1] == ACE_TEXT ('.') && s[2] == 0))); +} +#endif /* ACE_HAS_WCHAR */ + +ACE_INLINE void +ACE::unique_name (const void *object, + ACE_TCHAR *name, + size_t length) +{ + ACE_OS::unique_name (object, name, length); +} + +ACE_INLINE u_long +ACE::log2 (u_long num) +{ + u_long log = 0; + + for (; num > 1; ++log) + num >>= 1; + + return log; +} + +ACE_INLINE int +ACE::map_errno (int error) +{ +#if defined (ACE_WIN32) + switch (error) + { + case WSAEWOULDBLOCK: + return EAGAIN; // Same as UNIX errno EWOULDBLOCK. + } +#endif /* ACE_WIN32 */ + + return error; +} + +ACE_INLINE u_char +ACE::hex2byte (ACE_TCHAR c) +{ + if (ACE_OS::ace_isdigit (c)) + return (u_char) (c - ACE_TEXT ('0')); + else if (ACE_OS::ace_islower (c)) + return (u_char) (10 + c - ACE_TEXT ('a')); + else + return (u_char) (10 + c - ACE_TEXT ('A')); +} + +// Close versioned namespace, if enabled by the user. +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/ACE.pc.in b/dep/acelite/ace/ACE.pc.in new file mode 100644 index 00000000000..90b2a9eebd7 --- /dev/null +++ b/dep/acelite/ace/ACE.pc.in @@ -0,0 +1,10 @@ +prefix=@prefix@ +exec_prefix=@exec_prefix@ +libdir=@libdir@ +includedir=@includedir@ + +Name: ACE +Description: ADAPTIVE Communication Environment +Version: @VERSION@ +Libs: -L${libdir} -lACE @LIBS@ +Cflags: -I${includedir} diff --git a/dep/acelite/ace/ACE_crc32.cpp b/dep/acelite/ace/ACE_crc32.cpp new file mode 100644 index 00000000000..70d93e6b598 --- /dev/null +++ b/dep/acelite/ace/ACE_crc32.cpp @@ -0,0 +1,161 @@ +// $Id: ACE_crc32.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/ACE.h" + +ACE_RCSID (ace, + ACE_crc32, + "$Id: ACE_crc32.cpp 80826 2008-03-04 14:51:23Z wotte $") + + +namespace +{ + /*****************************************************************/ + /* */ + /* CRC LOOKUP TABLE */ + /* ================ */ + /* The following CRC lookup table was generated automagically */ + /* by the Rocksoft^tm Model CRC Algorithm Table Generation */ + /* Program V1.0 using the following model parameters: */ + /* */ + /* Width : 4 bytes. */ + /* Poly : 0x04C11DB7L */ + /* Reverse : TRUE. */ + /* */ + /* For more information on the Rocksoft^tm Model CRC Algorithm, */ + /* see the document titled "A Painless Guide to CRC Error */ + /* Detection Algorithms" by Ross Williams */ + /* (ross@guest.adelaide.edu.au.). This document is likely to be */ + /* in the FTP archive "ftp.adelaide.edu.au/pub/rocksoft". */ + /* */ + /*****************************************************************/ + + const ACE_UINT32 crc_table[] = + { + 0x00000000L, 0x77073096L, 0xEE0E612CL, 0x990951BAL, + 0x076DC419L, 0x706AF48FL, 0xE963A535L, 0x9E6495A3L, + 0x0EDB8832L, 0x79DCB8A4L, 0xE0D5E91EL, 0x97D2D988L, + 0x09B64C2BL, 0x7EB17CBDL, 0xE7B82D07L, 0x90BF1D91L, + 0x1DB71064L, 0x6AB020F2L, 0xF3B97148L, 0x84BE41DEL, + 0x1ADAD47DL, 0x6DDDE4EBL, 0xF4D4B551L, 0x83D385C7L, + 0x136C9856L, 0x646BA8C0L, 0xFD62F97AL, 0x8A65C9ECL, + 0x14015C4FL, 0x63066CD9L, 0xFA0F3D63L, 0x8D080DF5L, + 0x3B6E20C8L, 0x4C69105EL, 0xD56041E4L, 0xA2677172L, + 0x3C03E4D1L, 0x4B04D447L, 0xD20D85FDL, 0xA50AB56BL, + 0x35B5A8FAL, 0x42B2986CL, 0xDBBBC9D6L, 0xACBCF940L, + 0x32D86CE3L, 0x45DF5C75L, 0xDCD60DCFL, 0xABD13D59L, + 0x26D930ACL, 0x51DE003AL, 0xC8D75180L, 0xBFD06116L, + 0x21B4F4B5L, 0x56B3C423L, 0xCFBA9599L, 0xB8BDA50FL, + 0x2802B89EL, 0x5F058808L, 0xC60CD9B2L, 0xB10BE924L, + 0x2F6F7C87L, 0x58684C11L, 0xC1611DABL, 0xB6662D3DL, + 0x76DC4190L, 0x01DB7106L, 0x98D220BCL, 0xEFD5102AL, + 0x71B18589L, 0x06B6B51FL, 0x9FBFE4A5L, 0xE8B8D433L, + 0x7807C9A2L, 0x0F00F934L, 0x9609A88EL, 0xE10E9818L, + 0x7F6A0DBBL, 0x086D3D2DL, 0x91646C97L, 0xE6635C01L, + 0x6B6B51F4L, 0x1C6C6162L, 0x856530D8L, 0xF262004EL, + 0x6C0695EDL, 0x1B01A57BL, 0x8208F4C1L, 0xF50FC457L, + 0x65B0D9C6L, 0x12B7E950L, 0x8BBEB8EAL, 0xFCB9887CL, + 0x62DD1DDFL, 0x15DA2D49L, 0x8CD37CF3L, 0xFBD44C65L, + 0x4DB26158L, 0x3AB551CEL, 0xA3BC0074L, 0xD4BB30E2L, + 0x4ADFA541L, 0x3DD895D7L, 0xA4D1C46DL, 0xD3D6F4FBL, + 0x4369E96AL, 0x346ED9FCL, 0xAD678846L, 0xDA60B8D0L, + 0x44042D73L, 0x33031DE5L, 0xAA0A4C5FL, 0xDD0D7CC9L, + 0x5005713CL, 0x270241AAL, 0xBE0B1010L, 0xC90C2086L, + 0x5768B525L, 0x206F85B3L, 0xB966D409L, 0xCE61E49FL, + 0x5EDEF90EL, 0x29D9C998L, 0xB0D09822L, 0xC7D7A8B4L, + 0x59B33D17L, 0x2EB40D81L, 0xB7BD5C3BL, 0xC0BA6CADL, + 0xEDB88320L, 0x9ABFB3B6L, 0x03B6E20CL, 0x74B1D29AL, + 0xEAD54739L, 0x9DD277AFL, 0x04DB2615L, 0x73DC1683L, + 0xE3630B12L, 0x94643B84L, 0x0D6D6A3EL, 0x7A6A5AA8L, + 0xE40ECF0BL, 0x9309FF9DL, 0x0A00AE27L, 0x7D079EB1L, + 0xF00F9344L, 0x8708A3D2L, 0x1E01F268L, 0x6906C2FEL, + 0xF762575DL, 0x806567CBL, 0x196C3671L, 0x6E6B06E7L, + 0xFED41B76L, 0x89D32BE0L, 0x10DA7A5AL, 0x67DD4ACCL, + 0xF9B9DF6FL, 0x8EBEEFF9L, 0x17B7BE43L, 0x60B08ED5L, + 0xD6D6A3E8L, 0xA1D1937EL, 0x38D8C2C4L, 0x4FDFF252L, + 0xD1BB67F1L, 0xA6BC5767L, 0x3FB506DDL, 0x48B2364BL, + 0xD80D2BDAL, 0xAF0A1B4CL, 0x36034AF6L, 0x41047A60L, + 0xDF60EFC3L, 0xA867DF55L, 0x316E8EEFL, 0x4669BE79L, + 0xCB61B38CL, 0xBC66831AL, 0x256FD2A0L, 0x5268E236L, + 0xCC0C7795L, 0xBB0B4703L, 0x220216B9L, 0x5505262FL, + 0xC5BA3BBEL, 0xB2BD0B28L, 0x2BB45A92L, 0x5CB36A04L, + 0xC2D7FFA7L, 0xB5D0CF31L, 0x2CD99E8BL, 0x5BDEAE1DL, + 0x9B64C2B0L, 0xEC63F226L, 0x756AA39CL, 0x026D930AL, + 0x9C0906A9L, 0xEB0E363FL, 0x72076785L, 0x05005713L, + 0x95BF4A82L, 0xE2B87A14L, 0x7BB12BAEL, 0x0CB61B38L, + 0x92D28E9BL, 0xE5D5BE0DL, 0x7CDCEFB7L, 0x0BDBDF21L, + 0x86D3D2D4L, 0xF1D4E242L, 0x68DDB3F8L, 0x1FDA836EL, + 0x81BE16CDL, 0xF6B9265BL, 0x6FB077E1L, 0x18B74777L, + 0x88085AE6L, 0xFF0F6A70L, 0x66063BCAL, 0x11010B5CL, + 0x8F659EFFL, 0xF862AE69L, 0x616BFFD3L, 0x166CCF45L, + 0xA00AE278L, 0xD70DD2EEL, 0x4E048354L, 0x3903B3C2L, + 0xA7672661L, 0xD06016F7L, 0x4969474DL, 0x3E6E77DBL, + 0xAED16A4AL, 0xD9D65ADCL, 0x40DF0B66L, 0x37D83BF0L, + 0xA9BCAE53L, 0xDEBB9EC5L, 0x47B2CF7FL, 0x30B5FFE9L, + 0xBDBDF21CL, 0xCABAC28AL, 0x53B39330L, 0x24B4A3A6L, + 0xBAD03605L, 0xCDD70693L, 0x54DE5729L, 0x23D967BFL, + 0xB3667A2EL, 0xC4614AB8L, 0x5D681B02L, 0x2A6F2B94L, + 0xB40BBE37L, 0xC30C8EA1L, 0x5A05DF1BL, 0x2D02EF8DL + }; + + /*****************************************************************/ + /* End of CRC Lookup Table */ + /*****************************************************************/ +} + +#define COMPUTE(var, ch) (var) = (crc_table[(var ^ ch) & 0xFF] ^ (var >> 8)) + +// Open versioned namespace, if enabled by the user. +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_UINT32 +ACE::crc32 (const char *string) +{ + ACE_UINT32 crc = 0xFFFFFFFF; + + for (const char *p = string; + *p != 0; + ++p) + { + COMPUTE (crc, *p); + } + + return ~crc; +} + +ACE_UINT32 +ACE::crc32 (const void *buffer, size_t len, ACE_UINT32 crc) +{ + crc = ~crc; + + for (const char *p = (const char *) buffer, + *e = (const char *) buffer + len; + p != e; + ++p) + { + COMPUTE (crc, *p); + } + + return ~crc; +} + +ACE_UINT32 +ACE::crc32 (const iovec *iov, int len, ACE_UINT32 crc) +{ + crc = ~crc; + + for (int i = 0; i < len; ++i) + { + for (const char *p = (const char *) iov[i].iov_base, + *e = (const char *) iov[i].iov_base + iov[i].iov_len; + p != e; + ++p) + COMPUTE (crc, *p); + } + + return ~crc; +} + +// Close versioned namespace, if enabled by the user. +ACE_END_VERSIONED_NAMESPACE_DECL + +#undef COMPUTE diff --git a/dep/acelite/ace/ACE_crc_ccitt.cpp b/dep/acelite/ace/ACE_crc_ccitt.cpp new file mode 100644 index 00000000000..ef7f5d65bd1 --- /dev/null +++ b/dep/acelite/ace/ACE_crc_ccitt.cpp @@ -0,0 +1,128 @@ +// $Id: ACE_crc_ccitt.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/ACE.h" + +ACE_RCSID (ace, + ACE_crc_ccitt, + "$Id: ACE_crc_ccitt.cpp 80826 2008-03-04 14:51:23Z wotte $") + +namespace +{ + /*****************************************************************/ + /* */ + /* CRC LOOKUP TABLE */ + /* ================ */ + /* The following CRC lookup table was generated automagically */ + /* by the Rocksoft^tm Model CRC Algorithm Table Generation */ + /* Program V1.0 using the following model parameters: */ + /* */ + /* Width : 2 bytes. */ + /* Poly : 0x1021 */ + /* Reverse : TRUE. */ + /* */ + /* For more information on the Rocksoft^tm Model CRC Algorithm, */ + /* see the document titled "A Painless Guide to CRC Error */ + /* Detection Algorithms" by Ross Williams */ + /* (ross@guest.adelaide.edu.au.). This document is likely to be */ + /* in the FTP archive "ftp.adelaide.edu.au/pub/rocksoft". */ + /* */ + /*****************************************************************/ + + const ACE_UINT16 crc_table[] = + { + 0x0000, 0x1189, 0x2312, 0x329B, 0x4624, 0x57AD, 0x6536, 0x74BF, + 0x8C48, 0x9DC1, 0xAF5A, 0xBED3, 0xCA6C, 0xDBE5, 0xE97E, 0xF8F7, + 0x1081, 0x0108, 0x3393, 0x221A, 0x56A5, 0x472C, 0x75B7, 0x643E, + 0x9CC9, 0x8D40, 0xBFDB, 0xAE52, 0xDAED, 0xCB64, 0xF9FF, 0xE876, + 0x2102, 0x308B, 0x0210, 0x1399, 0x6726, 0x76AF, 0x4434, 0x55BD, + 0xAD4A, 0xBCC3, 0x8E58, 0x9FD1, 0xEB6E, 0xFAE7, 0xC87C, 0xD9F5, + 0x3183, 0x200A, 0x1291, 0x0318, 0x77A7, 0x662E, 0x54B5, 0x453C, + 0xBDCB, 0xAC42, 0x9ED9, 0x8F50, 0xFBEF, 0xEA66, 0xD8FD, 0xC974, + 0x4204, 0x538D, 0x6116, 0x709F, 0x0420, 0x15A9, 0x2732, 0x36BB, + 0xCE4C, 0xDFC5, 0xED5E, 0xFCD7, 0x8868, 0x99E1, 0xAB7A, 0xBAF3, + 0x5285, 0x430C, 0x7197, 0x601E, 0x14A1, 0x0528, 0x37B3, 0x263A, + 0xDECD, 0xCF44, 0xFDDF, 0xEC56, 0x98E9, 0x8960, 0xBBFB, 0xAA72, + 0x6306, 0x728F, 0x4014, 0x519D, 0x2522, 0x34AB, 0x0630, 0x17B9, + 0xEF4E, 0xFEC7, 0xCC5C, 0xDDD5, 0xA96A, 0xB8E3, 0x8A78, 0x9BF1, + 0x7387, 0x620E, 0x5095, 0x411C, 0x35A3, 0x242A, 0x16B1, 0x0738, + 0xFFCF, 0xEE46, 0xDCDD, 0xCD54, 0xB9EB, 0xA862, 0x9AF9, 0x8B70, + 0x8408, 0x9581, 0xA71A, 0xB693, 0xC22C, 0xD3A5, 0xE13E, 0xF0B7, + 0x0840, 0x19C9, 0x2B52, 0x3ADB, 0x4E64, 0x5FED, 0x6D76, 0x7CFF, + 0x9489, 0x8500, 0xB79B, 0xA612, 0xD2AD, 0xC324, 0xF1BF, 0xE036, + 0x18C1, 0x0948, 0x3BD3, 0x2A5A, 0x5EE5, 0x4F6C, 0x7DF7, 0x6C7E, + 0xA50A, 0xB483, 0x8618, 0x9791, 0xE32E, 0xF2A7, 0xC03C, 0xD1B5, + 0x2942, 0x38CB, 0x0A50, 0x1BD9, 0x6F66, 0x7EEF, 0x4C74, 0x5DFD, + 0xB58B, 0xA402, 0x9699, 0x8710, 0xF3AF, 0xE226, 0xD0BD, 0xC134, + 0x39C3, 0x284A, 0x1AD1, 0x0B58, 0x7FE7, 0x6E6E, 0x5CF5, 0x4D7C, + 0xC60C, 0xD785, 0xE51E, 0xF497, 0x8028, 0x91A1, 0xA33A, 0xB2B3, + 0x4A44, 0x5BCD, 0x6956, 0x78DF, 0x0C60, 0x1DE9, 0x2F72, 0x3EFB, + 0xD68D, 0xC704, 0xF59F, 0xE416, 0x90A9, 0x8120, 0xB3BB, 0xA232, + 0x5AC5, 0x4B4C, 0x79D7, 0x685E, 0x1CE1, 0x0D68, 0x3FF3, 0x2E7A, + 0xE70E, 0xF687, 0xC41C, 0xD595, 0xA12A, 0xB0A3, 0x8238, 0x93B1, + 0x6B46, 0x7ACF, 0x4854, 0x59DD, 0x2D62, 0x3CEB, 0x0E70, 0x1FF9, + 0xF78F, 0xE606, 0xD49D, 0xC514, 0xB1AB, 0xA022, 0x92B9, 0x8330, + 0x7BC7, 0x6A4E, 0x58D5, 0x495C, 0x3DE3, 0x2C6A, 0x1EF1, 0x0F78 + }; + + /*****************************************************************/ + /* End of CRC Lookup Table */ + /*****************************************************************/ +} + +#define COMPUTE(var, ch) (var) = (crc_table[(var ^ ch) & 0xFF] ^ (var >> 8)) + +// Open versioned namespace, if enabled by the user. +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_UINT16 +ACE::crc_ccitt (const char *string) +{ + ACE_UINT16 crc = 0xFFFF; + + for (const char *p = string; + *p != 0; + ++p) + { + COMPUTE (crc, *p); + } + + return ~crc; +} + +ACE_UINT16 +ACE::crc_ccitt (const void *buffer, size_t len, ACE_UINT16 crc) +{ + crc = ~crc; + + for (const char *p = (const char *) buffer, + *e = (const char *) buffer + len; + p != e; + ++p) + { + COMPUTE (crc, *p); + } + + return ~crc; +} + +ACE_UINT16 +ACE::crc_ccitt (const iovec *iov, int len, ACE_UINT16 crc) +{ + crc = ~crc; + + for (int i = 0; i < len; ++i) + { + for (const char *p = (const char *) iov[i].iov_base, + *e = (const char *) iov[i].iov_base + iov[i].iov_len; + p != e; + ++p) + COMPUTE (crc, *p); + } + + return ~crc; +} + +// Close versioned namespace, if enabled by the user. +ACE_END_VERSIONED_NAMESPACE_DECL + +#undef COMPUTE diff --git a/dep/acelite/ace/ACE_export.h b/dep/acelite/ace/ACE_export.h new file mode 100644 index 00000000000..8ad2a33ebaf --- /dev/null +++ b/dep/acelite/ace/ACE_export.h @@ -0,0 +1,76 @@ +// -*- C++ -*- +// $Id: ACE_export.h 80826 2008-03-04 14:51:23Z wotte $ +// Definition for Win32 Export directives. +// This file is generated automatically by +// generate_export_file.pl +// ------------------------------ + +#ifndef ACE_EXPORT_H +#define ACE_EXPORT_H + +#include "ace/config-lite.h" + +#if defined (ACE_AS_STATIC_LIBS) + +# if !defined (ACE_HAS_DLL) +# define ACE_HAS_DLL 0 +# endif /* ! ACE_HAS_DLL */ +#else +# if !defined (ACE_HAS_DLL) +# define ACE_HAS_DLL 1 +# endif /* ! ACE_HAS_DLL */ +#endif /* ACE_AS_STATIC_LIB */ + +#if defined (ACE_HAS_DLL) +# if (ACE_HAS_DLL == 1) +# if defined (ACE_BUILD_DLL) +# define ACE_Export ACE_Proper_Export_Flag +# define ACE_SINGLETON_DECLARATION(T) ACE_EXPORT_SINGLETON_DECLARATION (T) +# define ACE_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) +# else +# define ACE_Export ACE_Proper_Import_Flag +# define ACE_SINGLETON_DECLARATION(T) ACE_IMPORT_SINGLETON_DECLARATION (T) +# define ACE_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) +# endif /* ACE_BUILD_DLL */ +# else +# define ACE_Export +# define ACE_SINGLETON_DECLARATION(T) +# define ACE_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) +# endif /* ! ACE_HAS_DLL == 1 */ +#else +# define ACE_Export +# define ACE_SINGLETON_DECLARATION(T) +# define ACE_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) +#endif /* ACE_HAS_DLL */ + +// Added by hand to help with ACE_OS namespace +#if defined (__TANDEM) && defined (USE_EXPLICIT_EXPORT) +#define ACE_NAMESPACE_STORAGE_CLASS ACE_EXPORT_MACRO extern +#else +#define ACE_NAMESPACE_STORAGE_CLASS extern ACE_EXPORT_MACRO +#endif + +#if defined (__ACE_INLINE__) +# if defined (_MSC_VER) || defined (__MINGW32__) || defined (CYGWIN32) || \ + (defined (__SUNPRO_CC) && __SUNPRO_CC >= 0x560) || \ + (defined (__HP_aCC) && (__HP_aCC >= 60500)) || \ + (defined (__sgi) && \ + defined (_COMPILER_VERSION) && _COMPILER_VERSION <= 730) +# define ACE_NAMESPACE_INLINE_FUNCTION inline +# else +# define ACE_NAMESPACE_INLINE_FUNCTION ACE_NAMESPACE_STORAGE_CLASS inline +# endif +# define ACE_INLINE_TEMPLATE_FUNCTION inline +#else +# define ACE_NAMESPACE_INLINE_FUNCTION ACE_NAMESPACE_STORAGE_CLASS +// Microsoft Visual C++ will accept 'extern'; others refuse. +# if defined (_MSC_VER) || defined (__BORLANDC__) +# define ACE_INLINE_TEMPLATE_FUNCTION ACE_Export +# else +# define ACE_INLINE_TEMPLATE_FUNCTION +# endif +#endif + +#endif /* ACE_EXPORT_H */ + +// End of auto generated file. diff --git a/dep/acelite/ace/ARGV.cpp b/dep/acelite/ace/ARGV.cpp new file mode 100644 index 00000000000..edfd4efa790 --- /dev/null +++ b/dep/acelite/ace/ARGV.cpp @@ -0,0 +1,383 @@ +// $Id: ARGV.cpp 81374 2008-04-16 13:07:47Z iliyan $ + +#ifndef ACE_ARGV_CPP +#define ACE_ARGV_CPP + +#include "ace/Log_Msg.h" +#include "ace/OS_NS_unistd.h" +#include "ace/OS_NS_string.h" +#include "ace/OS_Memory.h" + +#if !defined (__ACE_INLINE__) +#include "ace/ARGV.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID(ace, ARGV, "$Id: ARGV.cpp 81374 2008-04-16 13:07:47Z iliyan $") + +// Open versioned namespace, if enabled by the user. +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE (ACE_ARGV_Queue_Entry) +ACE_ALLOC_HOOK_DEFINE (ACE_ARGV) + +template +void +ACE_ARGV_Queue_Entry_T::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_ARGV_Queue_Entry_T::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("arg_ = %s"), this->arg_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("quote_arg_ = %d"), (int)this->quote_arg_)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +template +void +ACE_ARGV_T::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_ARGV_T::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("argc_ = %d"), this->argc_)); + + ACE_ARGV *this_obj = const_cast (this); + + for (int i = 0; i < this->argc_; i++) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("\nargv_[%i] = %s"), + i, + this_obj->argv ()[i])); + + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nbuf = %s\n"), this->buf_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n"))); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +// Creates this->argv_ out of this->buf_. New memory is allocated for +// each element of the array. This is used by the array-to-string +// style constructor and for creating this->argv_ when in iterative +// mode. + +template +int +ACE_ARGV_T::string_to_argv (void) +{ + ACE_TRACE ("ACE_ARGV_T::string_to_argv"); + + return ACE_OS::string_to_argv (this->buf_, + this->argc_, + this->argv_, + this->substitute_env_args_); +} + +template +ACE_ARGV_T::ACE_ARGV_T (const CHAR_TYPE buf[], + bool substitute_env_args) + : substitute_env_args_ (substitute_env_args), + iterative_ (false), + argc_ (0), + argv_ (0), + buf_ (0), + length_ (0), + queue_ () +{ + ACE_TRACE ("ACE_ARGV_T::ACE_ARGV_T CHAR_TYPE[] to CHAR_TYPE *[]"); + + if (buf == 0 || buf[0] == 0) + return; + + // Make an internal copy of the string. + ACE_NEW (this->buf_, + CHAR_TYPE[ACE_OS::strlen (buf) + 1]); + ACE_OS::strcpy (this->buf_, buf); + + // Create this->argv_. + if (this->string_to_argv () == -1) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("string_to_argv"))); +} + +template +ACE_ARGV_T::ACE_ARGV_T (CHAR_TYPE *argv[], + bool substitute_env_args, + bool quote_arg) + : substitute_env_args_ (substitute_env_args), + iterative_ (false), + argc_ (0), + argv_ (0), + buf_ (0), + length_ (0), + queue_ () +{ + ACE_TRACE ("ACE_ARGV_T::ACE_ARGV_T CHAR_TYPE*[] to CHAR_TYPE[]"); + + if (argv == 0 || argv[0] == 0) + return; + + this->argc_ = ACE_OS::argv_to_string (argv, + this->buf_, + substitute_env_args, + quote_arg); +} + +template +ACE_ARGV_T::ACE_ARGV_T (int argc, + CHAR_TYPE *argv[], + bool substitute_env_args, + bool quote_arg) + : substitute_env_args_ (substitute_env_args), + iterative_ (false), + argc_ (0), + argv_ (0), + buf_ (0), + length_ (0), + queue_ () +{ + ACE_TRACE ("ACE_ARGV_T::ACE_ARGV_T int,CHAR_TYPE*[] to CHAR_TYPE[]"); + + this->argc_ = ACE_OS::argv_to_string (argc, + argv, + this->buf_, + substitute_env_args, + quote_arg); +} + + +template +ACE_ARGV_T::ACE_ARGV_T (CHAR_TYPE *first_argv[], + CHAR_TYPE *second_argv[], + bool substitute_env_args, + bool quote_args) + : substitute_env_args_ (substitute_env_args), + iterative_ (false), + argc_ (0), + argv_ (0), + buf_ (0), + length_ (0), + queue_ () +{ + ACE_TRACE ("ACE_ARGV_T::ACE_ARGV_T CHAR_TYPE*[] + CHAR_TYPE *[] to CHAR_TYPE[]"); + + int first_argc = 0; + int second_argc = 0; + + CHAR_TYPE *first_buf = 0; + CHAR_TYPE *second_buf = 0; + + // convert the first argv to a string + if (first_argv != 0 && first_argv[0] != 0) + { + first_argc = ACE_OS::argv_to_string (first_argv, + first_buf, + substitute_env_args, + quote_args); + } + + // convert the second argv to a string + if (second_argv != 0 && second_argv[0] != 0) + { + second_argc = ACE_OS::argv_to_string (second_argv, + second_buf, + substitute_env_args, + quote_args); + } + + // Add the number of arguments in both the argvs. + this->argc_ = first_argc + second_argc; + + size_t buf_len = + ACE_OS::strlen (first_buf) + ACE_OS::strlen (second_buf) + 1; + + // Allocate memory to the lenght of the combined argv string. + ACE_NEW (this->buf_, + CHAR_TYPE[buf_len + 1]); + + // copy the first argv string to the buffer + ACE_OS::strcpy (this->buf_, first_buf); + + // concatenate the second argv string to the buffer + ACE_OS::strcat (this->buf_, second_buf); + + // Delete the first and second buffers + delete [] first_buf; + delete [] second_buf; +} + +template +ACE_ARGV_T::ACE_ARGV_T (bool substitute_env_args) + : substitute_env_args_ (substitute_env_args), + iterative_ (true), + argc_ (0), + argv_ (0), + buf_ (0), + length_ (0), + queue_ () +{ + ACE_TRACE ("ACE_ARGV_T::ACE_ARGV_T Iterative"); + + // Nothing to do yet -- the user puts in arguments via add () +} + +template +int +ACE_ARGV_T::add (const CHAR_TYPE *next_arg, bool quote_arg) +{ + // Only allow this to work in the "iterative" verion -- the + // ACE_ARGVs created with the one argument constructor. + if (!this->iterative_) + { + errno = EINVAL; + return -1; + } + + this->length_ += ACE_OS::strlen (next_arg); + if (quote_arg && ACE_OS::strchr (next_arg, ' ') != 0) + { + this->length_ += 2; + if (ACE_OS::strchr (next_arg, '"') != 0) + for (const CHAR_TYPE * p = next_arg; *p != '\0'; ++p) + if (*p == '"') ++this->length_; + } + else + { + quote_arg = false; + } + + // Put the new argument at the end of the queue. + if (this->queue_.enqueue_tail (ACE_ARGV_Queue_Entry_T (next_arg, quote_arg)) == -1) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("Can't add more to ARGV queue")), + -1); + + ++this->argc_; + + // Wipe argv_ and buf_ away so that they will be recreated if the + // user calls argv () or buf (). + if (this->argv_ != 0) + { + for (int i = 0; this->argv_[i] != 0; i++) + ACE_OS::free ((void *) this->argv_[i]); + + delete [] this->argv_; + this->argv_ = 0; + } + + delete [] this->buf_; + this->buf_ = 0; + + return 0; +} + +template +int +ACE_ARGV_T::add (CHAR_TYPE *argv[], bool quote_args) +{ + for (int i = 0; argv[i] != 0; i++) + if (this->add (argv[i], quote_args) == -1) + return -1; + + return 0; +} + +// Free up argv_ and buf_ + +template +ACE_ARGV_T::~ACE_ARGV_T (void) +{ + ACE_TRACE ("ACE_ARGV_T::~ACE_ARGV_T"); + + if (this->argv_ != 0) + for (int i = 0; this->argv_[i] != 0; i++) + ACE_OS::free ((void *) this->argv_[i]); + + delete [] this->argv_; + delete [] this->buf_; +} + +// Create buf_ out of the queue_. This is only used in the +// "iterative" mode. + +template +int +ACE_ARGV_T::create_buf_from_queue (void) +{ + ACE_TRACE ("ACE_ARGV_T::create_buf_from_queue"); + + // If the are no arguments, don't do anything + if (this->argc_ <= 0) + return -1; + + delete [] this->buf_; + + ACE_NEW_RETURN (this->buf_, + CHAR_TYPE[this->length_ + this->argc_], + -1); + + // Get an iterator over the queue + ACE_Unbounded_Queue_Iterator > iter (this->queue_); + + ACE_ARGV_Queue_Entry_T *arg = 0; + CHAR_TYPE *ptr = this->buf_; + size_t len; + + while (!iter.done ()) + { + // Get next argument from the queue. + iter.next (arg); + iter.advance (); + + if (arg->quote_arg_) + { + *ptr++ = '"'; + if (ACE_OS::strchr (arg->arg_, '"') != 0) + { + CHAR_TYPE prev = 0; + for (const CHAR_TYPE * p = arg->arg_; *p != '\0'; ++p) + { + if (*p == '"' && prev != '\\') *ptr++ = '\\'; + prev = *ptr++ = *p; + } + } + else + { + len = ACE_OS::strlen (arg->arg_); + // Copy the argument into buf_ + ACE_OS::memcpy ((void *) ptr, + (const void *) (arg->arg_), + len * sizeof (CHAR_TYPE)); + // Move the pointer down. + ptr += len; + } + *ptr++ = '"'; + } + else + { + len = ACE_OS::strlen (arg->arg_); + // Copy the argument into buf_ + ACE_OS::memcpy ((void *) ptr, + (const void *) (arg->arg_), + len * sizeof (CHAR_TYPE)); + // Move the pointer down. + ptr += len; + } + + // Put in an argument separating space. + *ptr++ = ' '; + } + + // Put in the NUL terminator + ptr[-1] = '\0'; + + return 0; +} + +// Close versioned namespace, if enabled by the user. +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_ARGV_CPP */ diff --git a/dep/acelite/ace/ARGV.h b/dep/acelite/ace/ARGV.h new file mode 100644 index 00000000000..66e71810a95 --- /dev/null +++ b/dep/acelite/ace/ARGV.h @@ -0,0 +1,333 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file ARGV.h + * + * $Id: ARGV.h 81156 2008-03-30 20:56:47Z iliyan $ + * + * @author Doug Schmidt + * @author Everett Anderson + */ +//========================================================================== + +#ifndef ACE_ARGUMENT_VECTOR_H +#define ACE_ARGUMENT_VECTOR_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Global_Macros.h" +#include "ace/Unbounded_Queue.h" + +// Open versioned namespace, if enabled by the user. +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_ARGV_Queue_Entry_T + * + * @brief An entry in the queue which keeps user supplied arguments. + */ +template +class ACE_ARGV_Queue_Entry_T +{ +public: + // = Initialization and termination. + /// Initialize a ACE_ARGV_Queue_Entry_T. + ACE_ARGV_Queue_Entry_T (void); + + /** + * Initialize a ACE_ARGV_Queue_Entry_T. + * + * @param arg Pointer to an argument + * + * @param quote_arg The argument @a arg need to be quoted + * while adding to the vector. + */ + ACE_ARGV_Queue_Entry_T (const CHAR_TYPE *arg, + bool quote_arg); + + /** + * Initialize a ACE_ARGV_Queue_Entry_T. + * + * @param entry Pointer to a queue entry + */ + ACE_ARGV_Queue_Entry_T (const ACE_ARGV_Queue_Entry_T &entry); + + /// We need this destructor to keep some compilers from complaining. + /// It's just a no-op, however. + ~ACE_ARGV_Queue_Entry_T (void); + + /// Dump the state of this object. + void dump (void) const; + + // Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + + /// Pointer to the argument. + const CHAR_TYPE * arg_; + + /// The argument need to be quoted while adding to the vector. + bool quote_arg_; +}; + +/** + * @class ACE_ARGV_T + * + * @brief Builds a counted argument vector (ala argc/argv) from either + * a string or a set of separate tokens. This class preserves whitespace + * within tokens only if the whitespace-containing token is enclosed in + * either single (') or double (") quotes. This is consistent with the + * expected behavior if an argument vector obtained using this class is + * passed to, for example, ACE_Get_Opt. + * + * This class can substitute environment variable values for tokens that + * are environment variable references (e.g., @c $VAR). This only works + * if the token is an environment variable reference and nothing else; it + * doesn't substitute environment variable references within a token. + * For example, @c $HOME/file will not substitute the value of the HOME + * environment variable. + */ +template +class ACE_ARGV_T +{ +public: + // = Initialization and termination. + /** + * Splits the specified string into an argument vector. Arguments in the + * string are delimited by whitespace. Whitespace-containing arguments + * must be enclosed in quotes, either single (') or double ("). + * + * @param buf A nul-terminated CHAR_TYPE array to split into arguments + * for the vector. + * + * @param substitute_env_args If non-zero, any token that is an + * environment variable reference (e.g., @c $VAR) will have + * its environment variable value in the resultant vector + * in place of the environment variable name. + */ + explicit ACE_ARGV_T (const CHAR_TYPE buf[], + bool substitute_env_args = true); + + /** + * Initializes the argument vector from a set of arguments. Any environment + * variable references are translated (if applicable) during execution of + * this method. In contrast with ACE_ARGV_T(CHAR_TYPE *[], bool, bool), this + * ctor does not require argv to be 0-terminated as the number of arguments + * is provided explicitely. + * + * @param argc The number of arguments in the argv array. + * + * @param argv An array of tokens to initialize the object with. All needed + * data is copied from @a argv during this call; the pointers + * in @a argv are not needed after this call, and the memory + * referred to by @a argv is not referenced by this object. + * + * @param substitute_env_args If non-zero, any element of @a argv that is + * an environment variable reference (e.g., @c $VAR) will have + * its environment variable value in the resultant vector + * in place of the environment variable name. + * + * @param quote_args If non-zero each argument @a argv[i] needs to + * be enclosed in double quotes ('"'). + */ + explicit ACE_ARGV_T (int argc, + CHAR_TYPE *argv[], + bool substitute_env_args = true, + bool quote_args = false); + + /** + * Initializes the argument vector from a set of arguments. Any environment + * variable references are translated (if applicable) during execution of + * this method. + * + * @param argv An array of tokens to initialize the object with. The + * array must be terminated with a 0 pointer. All needed + * data is copied from @a argv during this call; the pointers + * in @a argv are not needed after this call, and the memory + * referred to by @a argv is not referenced by this object. + * + * @param substitute_env_args If non-zero, any element of @a argv that is + * an environment variable reference (e.g., @c $VAR) will have + * its environment variable value in the resultant vector + * in place of the environment variable name. + * + * @param quote_args If non-zero each argument @a argv[i] needs to + * be enclosed in double quotes ('"'). + */ + explicit ACE_ARGV_T (CHAR_TYPE *argv[], + bool substitute_env_args = true, + bool quote_args = false); + + /** + * Initializes the argument vector from two combined argument vectors. + * + * @param first_argv An array of tokens to initialize the object with. + * The array must be terminated with a 0 pointer. + * @param second_argv An array of tokens that is concatenated with the + * the tokens in @a first_argv. The array must be + * terminated with a 0 pointer. + * @param substitute_env_args If non-zero, any element of @a first_argv + * or @a second_argv that is an environment variable + * reference (e.g., @c $VAR) will have its environment + * variable value in the resultant vector in place + * of the environment variable name. + * + * @param quote_args If non-zero each arguments @a first_argv[i] and + * @a second_argv[i] needs to be enclosed + * in double quotes ('"'). + */ + ACE_ARGV_T (CHAR_TYPE *first_argv[], + CHAR_TYPE *second_argv[], + bool substitute_env_args = true, + bool quote_args = false); + + /** + * Initialize this object so arguments can be added later using one + * of the add methods. This is referred to as the @i iterative method + * of adding arguments to this object. + */ + explicit ACE_ARGV_T (bool substitute_env_args = true); + + /// Destructor. + ~ACE_ARGV_T (void); + + /** @name Accessor methods + * + * These methods access the argument vector contained in this object. + */ + //@{ + /** + * Returns the specified element of the current argument vector. + * + * @param index Index to the desired element. + * + * @retval Pointer to the indexed string. + * @retval 0 if @a index is out of bounds. + */ + const CHAR_TYPE *operator[] (size_t index); + + /** + * Returns the current argument vector. The returned pointers are to data + * maintained internally to this class. Do not change or delete either the + * pointers or the memory to which they refer. + */ + CHAR_TYPE **argv (void); + + /// Returns the current number of arguments. + int argc (void) const; + + /** + * Returns a single string form of the current arguments. The returned + * pointer refers to memory maintained internally to this class. Do not + * change or delete it. + */ + const CHAR_TYPE *buf (void); + + //@} + + /// Dump the state of this object. + void dump (void) const; + + // Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + + /** + * Add another argument. This only works in the iterative mode. + * + * @note This method copies the specified pointer, but not the data + * contained in the referenced memory. Thus, if the content of + * the memory referred to by @a next_arg are changed after this + * method returns, the results are undefined. + * + * @param next_arg Pointer to the next argument to add to the vector. + * + * @param quote_arg The argument @a next_arg need to be quoted while + * adding to the vector. + * + * @retval 0 on success; -1 on failure. Most likely @c errno values are: + * - EINVAL: This object is not in iterative mode. + * - ENOMEM: Not enough memory available to save @a next_arg. + */ + int add (const CHAR_TYPE *next_arg, bool quote_arg = false); + + /** + * Add an array of arguments. This only works in the iterative mode. + * + * @note This method copies the specified pointers, but not the data + * contained in the referenced memory. Thus, if the content of + * the memory referred to by any of the @a argv elements is + * changed after this method returns, the results are undefined. + * + * @param argv Pointers to the arguments to add to the vector. + * @a argv must be terminated by a 0 pointer. + * + * @param quote_args If non-zero each argument @a argv[i] needs to + * be enclosed in double quotes ('"'). + * + * @retval 0 on success; -1 on failure. Most likely @c errno values are: + * - EINVAL: This object is not in iterative mode. + * - ENOMEM: Not enough memory available to save @a next_arg. + */ + int add (CHAR_TYPE *argv[], bool quote_args = false); + +private: + /// Copy constructor not implemented. + ACE_UNIMPLEMENTED_FUNC (ACE_ARGV_T (const ACE_ARGV_T&)) + + /// Assignment operator not implemented. + ACE_UNIMPLEMENTED_FUNC (ACE_ARGV_T operator= (const ACE_ARGV_T&)) + + /// Creates buf_ from the queue of added args, deletes previous buf_. + int create_buf_from_queue (void); + + /// Converts buf_ into the CHAR_TYPE *argv[] format. + int string_to_argv (void); + + /// Replace args with environment variable values? + bool substitute_env_args_; + + bool iterative_; + + /// Number of arguments in the ARGV array. + int argc_; + + /// The array of string arguments. + CHAR_TYPE **argv_; + + /// Buffer containing the contents. + CHAR_TYPE *buf_; + + /// Total length of the arguments in the queue, not counting + /// separating spaces + size_t length_; + + /// Queue which keeps user supplied arguments. This is only + /// active in the "iterative" mode. + ACE_Unbounded_Queue > queue_; +}; + +typedef ACE_ARGV_Queue_Entry_T ACE_ARGV_Queue_Entry; +typedef ACE_ARGV_T ACE_ARGV; + +// Close versioned namespace, if enabled by the user. +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/ARGV.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/ARGV.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("ARGV.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" +#endif /* ACE_ARGUMENT_VECTOR_H */ diff --git a/dep/acelite/ace/ARGV.inl b/dep/acelite/ace/ARGV.inl new file mode 100644 index 00000000000..fdc5b13d7c3 --- /dev/null +++ b/dep/acelite/ace/ARGV.inl @@ -0,0 +1,104 @@ +/* -*- C++ -*- */ +// $Id: ARGV.inl 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Global_Macros.h" + +// Open versioned namespace, if enabled by the user. +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template ACE_INLINE +ACE_ARGV_Queue_Entry_T::ACE_ARGV_Queue_Entry_T (void) + : arg_(0), + quote_arg_(false) +{ + // No-op +} + +template ACE_INLINE +ACE_ARGV_Queue_Entry_T::ACE_ARGV_Queue_Entry_T (const CHAR_TYPE *arg, + bool quote_arg) + : arg_(arg), + quote_arg_(quote_arg) +{ + // No-op +} + +template ACE_INLINE +ACE_ARGV_Queue_Entry_T::ACE_ARGV_Queue_Entry_T (const ACE_ARGV_Queue_Entry_T &entry) + : arg_(entry.arg_), + quote_arg_(entry.quote_arg_) +{ + // No-op +} + +template ACE_INLINE +ACE_ARGV_Queue_Entry_T::~ACE_ARGV_Queue_Entry_T (void) +{ + // No-op just to keep some compilers happy... +} + +// Return the number of args +template +ACE_INLINE int +ACE_ARGV_T::argc (void) const +{ + ACE_TRACE ("ACE_ARGV_T::argc"); + // Try to create the argv_ if it isn't there + ACE_ARGV_T *nonconst_this = + const_cast *> (this); + (void) nonconst_this->argv (); + return this->argc_; +} + +// Return the arguments in a space-separated string +template +ACE_INLINE const CHAR_TYPE * +ACE_ARGV_T::buf (void) +{ + ACE_TRACE ("ACE_ARGV_T::buf"); + + if (this->buf_ == 0 && this->iterative_) + this->create_buf_from_queue (); + + return (const CHAR_TYPE *) this->buf_; +} + +// Return the arguments in an entry-per-argument array + +template +ACE_INLINE CHAR_TYPE ** +ACE_ARGV_T::argv (void) +{ + ACE_TRACE ("ACE_ARGV_T::argv"); + + // Try to create the argv_ if it isn't there + if (this->argv_ == 0) + { + if (this->iterative_ && this->buf_ == 0) + this->create_buf_from_queue (); + + // Convert buf_ to argv_ + if (this->string_to_argv () == -1) + return (CHAR_TYPE **) 0; + } + + return (CHAR_TYPE **) this->argv_; +} + +// Subscript operator. + +template +ACE_INLINE const CHAR_TYPE * +ACE_ARGV_T::operator[] (size_t i) +{ + ACE_TRACE ("ACE_ARGV_T::operator[]"); + + // Don't go out of bounds. + if (i >= static_cast (this->argc_)) + return 0; + + return (const CHAR_TYPE *) this->argv ()[i]; +} + +// Close versioned namespace, if enabled by the user. +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/ATM_Acceptor.cpp b/dep/acelite/ace/ATM_Acceptor.cpp new file mode 100644 index 00000000000..7e835658f01 --- /dev/null +++ b/dep/acelite/ace/ATM_Acceptor.cpp @@ -0,0 +1,309 @@ +// $Id: ATM_Acceptor.cpp 84262 2009-01-29 10:34:33Z johnnyw $ + +#include "ace/ATM_Acceptor.h" + +ACE_RCSID(ace, ATM_Acceptor, "$Id: ATM_Acceptor.cpp 84262 2009-01-29 10:34:33Z johnnyw $") + +#if defined (ACE_HAS_ATM) + +#if defined (ACE_HAS_LINUX_ATM) +#include /**/ "linux/atmdev.h" +#endif /* ACE_HAS_LINUX_ATM */ + +#if !defined (__ACE_INLINE__) +#include "ace/ATM_Acceptor.inl" +#endif /* __ACE_INLINE__ */ + + +// Open versioned namespace, if enabled by the user. +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Put the actual definitions of the ACE_ATM_Request and +// ACE_ATM_Request_Queue classes here to hide them from clients... + +ACE_ALLOC_HOOK_DEFINE(ACE_ATM_Acceptor) + +ACE_ATM_Acceptor::ACE_ATM_Acceptor (void) +{ + ACE_TRACE ("ACE_ATM_Acceptor::ACE_ATM_Acceptor"); +} + +ACE_ATM_Acceptor::~ACE_ATM_Acceptor (void) +{ + ACE_TRACE ("ACE_ATM_Acceptor::~ACE_ATM_Acceptor"); +} + +int +ACE_ATM_Acceptor::get_local_addr (ACE_ATM_Addr &local_addr) +{ + ACE_TRACE ("ACE_ATM_Acceptor::get_local_addr"); + +#if defined (ACE_HAS_FORE_ATM_WS2) + unsigned long ret = 0; + DWORD deviceID = 0; + ATM_ADDRESS addr; + struct sockaddr_atm *laddr; + + if (::WSAIoctl ((int) ((ACE_SOCK_Acceptor *)this) -> get_handle (), + SIO_GET_ATM_ADDRESS, + (LPVOID) &deviceID, + sizeof (DWORD), + (LPVOID)&addr, + sizeof (ATM_ADDRESS), + &ret, + 0, + 0) == SOCKET_ERROR) { + ACE_OS::printf ("ATM_Acceptor (get_local_addr): WSIoctl: %d\n", + ::WSAGetLastError ()); + return -1; + } + + laddr = (struct sockaddr_atm *)local_addr.get_addr (); + ACE_OS::memcpy ((void *)& (laddr -> satm_number), + (void *)&addr, + ATM_ADDR_SIZE - 1); + + return 0; +#elif defined (ACE_HAS_FORE_ATM_XTI) + ACE_UNUSED_ARG (local_addr); + + return 0; +#elif defined (ACE_HAS_LINUX_ATM) + ATM_Addr *myaddr = (ATM_Addr *)local_addr.get_addr (); + int addrlen = sizeof (myaddr->sockaddratmsvc); + + if (ACE_OS::getsockname (acceptor_.get_handle (), + (struct sockaddr *) & (myaddr->sockaddratmsvc), + &addrlen) < 0) { + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ATM_Acceptor (get_local_addr): ioctl: %d\n"), + errno)); + return -1; + } + + return 0; +#else + ACE_UNUSED_ARG (local_addr); + + return 0; +#endif /* ACE_HAS_FORE_ATM_WS2 && ACE_HAS_FORE_ATM_XTI */ +} + +ACE_HANDLE +ACE_ATM_Acceptor::open (const ACE_Addr &remote_sap, + int backlog, + ACE_ATM_Params params) +{ + ACE_TRACE ("ACE_ATM_Acceptor::open"); +#if defined (ACE_HAS_FORE_ATM_XTI) + ACE_HANDLE handle = acceptor_.open (remote_sap, + params.get_reuse_addr (), + params.get_oflag (), + params.get_info (), + backlog, + params.get_device ()); + return (handle == ACE_INVALID_HANDLE ? -1 : 0); +#elif defined (ACE_HAS_FORE_ATM_WS2) + struct sockaddr_atm local_atm_addr; + ACE_HANDLE ret; + DWORD flags = 0; + + /* Create a local endpoint of communication */ + + // Only leaves can listen. + flags = ACE_FLAG_MULTIPOINT_C_LEAF | ACE_FLAG_MULTIPOINT_D_LEAF; + + if ((ret = ACE_OS::socket (AF_ATM, + SOCK_RAW, + ATMPROTO_AAL5, + 0, + 0, + flags)) + == ACE_INVALID_HANDLE) { + ACE_OS::printf ("Acceptor (open): socket %d\n", + ::WSAGetLastError ()); + return (ret); + } + + ((ACE_SOCK_Acceptor *)this) -> set_handle (ret); + + /* Set up the address information to become a server */ + ACE_OS::memset ((void *) &local_atm_addr, 0, sizeof local_atm_addr); + local_atm_addr.satm_family = AF_ATM; + local_atm_addr.satm_number.AddressType = SAP_FIELD_ANY_AESA_REST; + local_atm_addr.satm_number.Addr[ ATM_ADDR_SIZE - 1 ] + = ((ACE_ATM_Addr *)&remote_sap) -> get_selector (); + local_atm_addr.satm_blli.Layer2Protocol = SAP_FIELD_ANY; + local_atm_addr.satm_blli.Layer3Protocol = SAP_FIELD_ABSENT; + local_atm_addr.satm_bhli.HighLayerInfoType = SAP_FIELD_ABSENT; + + /* Associate address with endpoint */ + if (ACE_OS::bind (((ACE_SOCK_Acceptor *)this) -> get_handle (), + reinterpret_cast (&local_atm_addr), + sizeof local_atm_addr) == -1) { + ACE_OS::printf ("Acceptor (open): bind %d\n", ::WSAGetLastError ()); + return (ACE_INVALID_HANDLE); + } + + /* Make endpoint listen for service requests */ + if (ACE_OS::listen (( (ACE_SOCK_Acceptor *)this) -> get_handle (), + backlog) + == -1) { + ACE_OS::printf ("Acceptor (open): listen %d\n", ::WSAGetLastError ()); + return (ACE_INVALID_HANDLE); + } + + return 0; +#elif defined (ACE_HAS_LINUX_ATM) + //we need to set the qos before binding to the socket + //use remote_sap as local_sap + + ACE_ATM_Addr local_sap; + ATM_Addr *local_sap_addr = (ATM_Addr*)local_sap.get_addr (); + ACE_ATM_QoS def_qos; + ATM_QoS qos = def_qos.get_qos (); + + ACE_HANDLE handle; + if ((handle = ACE_OS::socket (params.get_protocol_family (), + params.get_type (), + params.get_protocol (), + params.get_protocol_info (), + params.get_sock_group (), + params.get_flags () + )) + == ACE_INVALID_HANDLE) { + ACE_DEBUG (LM_DEBUG, + ACE_TEXT ("Acceptor (socket): socket %d\n"), + errno); + return (ACE_INVALID_HANDLE); + } + + ((ACE_SOCK_Acceptor *)this) -> set_handle (handle); + if (ACE_OS::setsockopt (handle, + SOL_ATM, + SO_ATMQOS, + reinterpret_cast (&qos), + sizeof (qos)) < 0) { + ACE_OS::printf ("Acceptor (setsockopt): setsockopt:%d\n", + errno); + } + + struct atmif_sioc req; + struct sockaddr_atmsvc aux_addr[1024]; + + req.number = 0; + req.arg = aux_addr; + req.length = sizeof (aux_addr); + if (ACE_OS::ioctl (handle, + ATM_GETADDR, + &req) < 0) { + ACE_OS::perror ("Acceptor (setsockopt): ioctl:"); + } + else { + local_sap_addr->sockaddratmsvc = aux_addr[0]; + } + local_sap.set_selector (( (ACE_ATM_Addr*)&remote_sap)->get_selector ()); + + if (ACE_OS::bind (handle, + reinterpret_cast ( + &(local_sap_addr->sockaddratmsvc)), + sizeof (local_sap_addr->sockaddratmsvc) + ) == -1) { + ACE_DEBUG (LM_DEBUG, + ACE_TEXT ("Acceptor (open): bind %d\n"), + errno); + return -1; + } + // Make endpoint listen for service requests + if (ACE_OS::listen (handle, + backlog) + == -1) { + ACE_DEBUG (LM_DEBUG, + ACE_TEXT ("Acceptor (listen): listen %d\n"), + errno); + return -1; + } + + return 0; +#else + ACE_UNUSED_ARG (remote_sap); + ACE_UNUSED_ARG (backlog); + ACE_UNUSED_ARG (params); +#endif /* ACE_HAS_FORE_ATM_XTI/ACE_HAS_FORE_ATM_WS2/ACE_HAS_LINUX_ATM */ +} + +int +ACE_ATM_Acceptor::accept (ACE_ATM_Stream &new_sap, + ACE_Addr *remote_addr, + ACE_Time_Value *timeout, + bool restart, + bool reset_new_handle, + ACE_ATM_Params params, + ACE_ATM_QoS qos) +{ + ACE_TRACE ("ACE_ATM_Acceptor::accept"); +#if defined (ACE_HAS_FORE_ATM_XTI) + ATM_QoS optbuf = qos.get_qos (); + + return (acceptor_.accept (new_sap.get_stream (), + remote_addr, + timeout, + restart, + reset_new_handle, + params.get_rw_flag (), + params.get_user_data (), + &optbuf)); +#elif defined (ACE_HAS_FORE_ATM_WS2) + ACE_HANDLE n_handle; + ACE_HANDLE s_handle = ((ACE_SOCK_Acceptor *) this) -> get_handle (); + struct sockaddr_atm *cli_addr + = (struct sockaddr_atm *)remote_addr -> get_addr (); + int caddr_len = sizeof (struct sockaddr_atm); + + do { + n_handle = ACE_OS::accept (s_handle, + reinterpret_cast (cli_addr), + &caddr_len); + } while (n_handle == ACE_INVALID_HANDLE && errno == EINTR); + + ((ACE_ATM_Addr *)remote_addr) -> set (cli_addr, + ((ACE_ATM_Addr *)remote_addr) -> get_selector ()); + ((ACE_IPC_SAP *)&new_sap) -> set_handle (n_handle); + + return 0; +#elif defined (ACE_HAS_LINUX_ATM) + ACE_UNUSED_ARG (params); + + ACE_HANDLE s_handle = ((ACE_SOCK_Acceptor *) this) -> get_handle (); + struct atm_qos accept_qos = qos.get_qos (); + + if (ACE_OS::setsockopt (s_handle, + SOL_ATM, + SO_ATMQOS, + reinterpret_cast (&accept_qos), + sizeof (accept_qos)) < 0) { + ACE_OS::printf ("Acceptor (accept): error setting Qos"); + } + + return (acceptor_.accept (new_sap.get_stream (), + remote_addr, + timeout, + restart, + reset_new_handle)); +#else + ACE_UNUSED_ARG (new_sap); + ACE_UNUSED_ARG (remote_addr); + ACE_UNUSED_ARG (timeout); + ACE_UNUSED_ARG (restart); + ACE_UNUSED_ARG (reset_new_handle); + ACE_UNUSED_ARG (params); + ACE_UNUSED_ARG (qos); + return 0; +#endif /* ACE_HAS_FORE_ATM_XTI */ +} + +// Close versioned namespace, if enabled by the user. +ACE_END_VERSIONED_NAMESPACE_DECL + + +#endif /* ACE_HAS_ATM */ diff --git a/dep/acelite/ace/ATM_Acceptor.h b/dep/acelite/ace/ATM_Acceptor.h new file mode 100644 index 00000000000..1241a228caa --- /dev/null +++ b/dep/acelite/ace/ATM_Acceptor.h @@ -0,0 +1,123 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file ATM_Acceptor.h + * + * $Id: ATM_Acceptor.h 82723 2008-09-16 09:35:44Z johnnyw $ + * + * @author Joe Hoffert + */ +//============================================================================= + + +#ifndef ACE_ATM_ACCEPTOR_H +#define ACE_ATM_ACCEPTOR_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_ATM) + +#include "ace/ATM_Stream.h" +#include "ace/ATM_Params.h" +#include "ace/ATM_QoS.h" + +#if defined (ACE_HAS_LINUX_ATM) +#include /**/ "atm.h" +#endif /* ACE_HAS_LINUX_ATM */ + +#if defined (ACE_HAS_FORE_ATM_WS2) || defined (ACE_HAS_LINUX_ATM) +#include "ace/SOCK_Acceptor.h" +ACE_BEGIN_VERSIONED_NAMESPACE_DECL +typedef ACE_SOCK_Acceptor ATM_Acceptor; +ACE_END_VERSIONED_NAMESPACE_DECL +#elif defined (ACE_HAS_FORE_ATM_XTI) +#include "ace/TLI_Acceptor.h" +ACE_BEGIN_VERSIONED_NAMESPACE_DECL +typedef ACE_TLI_Acceptor ATM_Acceptor; +ACE_END_VERSIONED_NAMESPACE_DECL +#endif // ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM + +// Open versioned namespace, if enabled by the user. +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Forward declarations. +class ACE_Time_Value; + +/** + * @class ACE_ATM_Acceptor + * + * @brief Defines the member functions for ACE_ATM_Acceptor abstraction. + * + * This class wraps up the ACE_SOCK_Acceptor and ACE_TLI_Acceptor + * to make the mechanism for the ATM protocol transparent. + */ +class ACE_Export ACE_ATM_Acceptor +{ + +public: + // = Initialization and termination methods. + /// Default constructor. + ACE_ATM_Acceptor (void); + + ~ACE_ATM_Acceptor (); + + /// Initiate a passive mode connection. + ACE_ATM_Acceptor (const ACE_Addr &remote_sap, + int backlog = ACE_DEFAULT_BACKLOG, + ACE_ATM_Params params = ACE_ATM_Params()); + + /// Initiate a passive mode socket. + ACE_HANDLE open (const ACE_Addr &remote_sap, + int backlog = ACE_DEFAULT_BACKLOG, + ACE_ATM_Params params = ACE_ATM_Params()); + + /// Close down the acceptor and release resources. + int close (void); + + // = Passive connection acceptance method. + + /// Accept a new data transfer connection. A @a timeout of 0 means + /// block forever, a @a timeout of {0, 0} means poll. @a restart == 1 + /// means "restart if interrupted." + int accept (ACE_ATM_Stream &new_sap, + ACE_Addr *remote_addr = 0, + ACE_Time_Value *timeout = 0, + bool restart = true, + bool reset_new_handle = false, + ACE_ATM_Params params = ACE_ATM_Params(), + ACE_ATM_QoS qos = ACE_ATM_QoS()); + + /// Get the local address currently listening on + int get_local_addr( ACE_ATM_Addr &local_addr ); + + // = Meta-type info + typedef ACE_ATM_Addr PEER_ADDR; + typedef ACE_ATM_Stream PEER_STREAM; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + ATM_Acceptor acceptor_; +}; + +// Close versioned namespace, if enabled by the user. +ACE_END_VERSIONED_NAMESPACE_DECL + + +#if defined (__ACE_INLINE__) +#include "ace/ATM_Acceptor.inl" +#endif /* __ACE_INLINE__ */ + +#endif /* ACE_HAS_ATM */ +#include /**/ "ace/post.h" +#endif /* ACE_ATM_ACCEPTOR_H */ diff --git a/dep/acelite/ace/ATM_Acceptor.inl b/dep/acelite/ace/ATM_Acceptor.inl new file mode 100644 index 00000000000..fa60c4ad89a --- /dev/null +++ b/dep/acelite/ace/ATM_Acceptor.inl @@ -0,0 +1,43 @@ +// -*- C++ -*- +// +// $Id: ATM_Acceptor.inl 80826 2008-03-04 14:51:23Z wotte $ + +// Open versioned namespace, if enabled by the user. +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE void +ACE_ATM_Acceptor::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_ATM_Acceptor::dump"); +#endif /* ACE_HAS_DUMP */ +} + +ACE_INLINE +ACE_ATM_Acceptor::ACE_ATM_Acceptor (const ACE_Addr &remote_sap, + int backlog, + ACE_ATM_Params params) +{ + ACE_TRACE ("ACE_ATM_Acceptor::ACE_ATM_Acceptor"); + + //FUZZ: disable check_for_lack_ACE_OS + if (open (remote_sap, backlog, params) < 0) + //FUZZ: enable check_for_lack_ACE_OS + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_ATM_Acceptor::ACE_ATM_Acceptor"))); +} + +ACE_INLINE +int +ACE_ATM_Acceptor::close (void) +{ +#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2) || defined (ACE_HAS_LINUX_ATM) + return (acceptor_.close()); +#else + return 0; +#endif // ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM +} + +// Close versioned namespace, if enabled by the user. +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/ATM_Addr.cpp b/dep/acelite/ace/ATM_Addr.cpp new file mode 100644 index 00000000000..991498d6668 --- /dev/null +++ b/dep/acelite/ace/ATM_Addr.cpp @@ -0,0 +1,522 @@ +// $Id: ATM_Addr.cpp 84565 2009-02-23 08:20:39Z johnnyw $ + +// Defines the Internet domain address family address format. + +#include "ace/ATM_Addr.h" +#if defined (ACE_HAS_ATM) + +#include "ace/Log_Msg.h" + +#if defined (ACE_HAS_FORE_ATM_WS2) +#include /**/ "forews2.h" +#endif /* ACE_HAS_FORE_ATM_WS2 */ + +#if !defined (__ACE_INLINE__) +#include "ace/ATM_Addr.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID(ace, ATM_Addr, "$Id: ATM_Addr.cpp 84565 2009-02-23 08:20:39Z johnnyw $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_ATM_Addr) + +#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2) +#define BHLI_MAGIC "FORE_ATM" +// This is line rate in cells/s for an OC-3 MM interface. +const long ACE_ATM_Addr::LINE_RATE = 353207; +const int ACE_ATM_Addr::OPT_FLAGS_CPID = 0x1; +const int ACE_ATM_Addr::OPT_FLAGS_PMP = 0x2; +const int ACE_ATM_Addr::DEFAULT_SELECTOR = 0x99; +#elif defined (ACE_HAS_LINUX_ATM) +//pbrandao:for Linux: +//pbrandao:for now stick with current definitions +//pbrandao:see if later need to change +const long ACE_ATM_Addr::LINE_RATE = 353207; +const int ACE_ATM_Addr::OPT_FLAGS_CPID = 0; +const int ACE_ATM_Addr::OPT_FLAGS_PMP = 0; +const int ACE_ATM_Addr::DEFAULT_SELECTOR = 0x99; +#else +const long ACE_ATM_Addr::LINE_RATE = 0L; +const int ACE_ATM_Addr::OPT_FLAGS_CPID = 0; +const int ACE_ATM_Addr::OPT_FLAGS_PMP = 0; +const int ACE_ATM_Addr::DEFAULT_SELECTOR = 0x0; +#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ + +// Default constructor + +ACE_ATM_Addr::ACE_ATM_Addr (u_char selector) +#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2) + : ACE_Addr (AF_ATM, +#elif defined (ACE_HAS_LINUX_ATM) + : ACE_Addr (PF_ATMSVC, +#else + : ACE_Addr (AF_UNSPEC, +#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ + sizeof this->atm_addr_) +{ + // ACE_TRACE ("ACE_ATM_Addr::ACE_ATM_Addr"); + (void) ACE_OS::memset ((void *) &this->atm_addr_, + 0, + sizeof this->atm_addr_); + this->init (selector); +} + +// Copy constructor. + +ACE_ATM_Addr::ACE_ATM_Addr (const ACE_ATM_Addr &sap, + u_char selector) +#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2) + : ACE_Addr (AF_ATM, +#elif defined (ACE_HAS_LINUX_ATM) + : ACE_Addr (PF_ATMSVC, +#else + : ACE_Addr (AF_UNSPEC, +#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ + sizeof this->atm_addr_) +{ + ACE_TRACE ("ACE_ATM_Addr::ACE_ATM_Addr"); + this->set (sap, selector); +#if defined (ACE_HAS_LINUX_ATM) + this->atm_addr_.sockaddratmsvc.sas_family = PF_ATMSVC; + this->atm_addr_.atmsap.blli[0].l3_proto = ATM_L3_NONE; + this->atm_addr_.atmsap.blli[0].l2_proto = ATM_L2_NONE; + this->atm_addr_.atmsap.bhli.hl_type = ATM_HL_NONE; +#endif /* ACE_HAS_LINUX_ATM */ +} + +ACE_ATM_Addr::ACE_ATM_Addr (const ATM_Addr *sap, + u_char selector) +#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2) + : ACE_Addr (AF_ATM, +#elif defined (ACE_HAS_LINUX_ATM) + : ACE_Addr (PF_ATMSVC, +#else + : ACE_Addr (AF_UNSPEC, +#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ + sizeof this->atm_addr_) +{ + ACE_TRACE ("ACE_ATM_Addr::ACE_ATM_Addr"); + this->set (sap, selector); +} + + +ACE_ATM_Addr::ACE_ATM_Addr (const ACE_TCHAR sap[], + u_char selector) +#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2) + : ACE_Addr (AF_ATM, +#elif defined (ACE_HAS_LINUX_ATM) + : ACE_Addr (PF_ATMSVC, +#else + : ACE_Addr (AF_UNSPEC, +#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ + sizeof this->atm_addr_) +{ + ACE_TRACE ("ACE_ATM_Addr::ACE_ATM_Addr"); + this->set (sap, selector); +} + +ACE_ATM_Addr::~ACE_ATM_Addr (void) +{ +} + +// Return the address. + +void * +ACE_ATM_Addr::get_addr (void) const +{ + ACE_TRACE ("ACE_ATM_Addr::get_addr"); + return (void *) &this->atm_addr_; +} + +void +ACE_ATM_Addr::init (u_char selector) +{ +#if defined (ACE_HAS_FORE_ATM_XTI) + // Note: this approach may be FORE implementation-specific. When we + // bind with tag_addr ABSENT and tag_selector PRESENT, only the + // selector (i.e. address[19]) is used by the TP. The rest of the + // local address is filled in by the TP and can be obtained via the + // 'ret' parameter or with t_getname ()/t_getprotaddr (). + + atm_addr_.addressType = (u_int16_t) AF_ATM; + + atm_addr_.sap.t_atm_sap_addr.SVE_tag_addr = (int8_t) T_ATM_ABSENT; + atm_addr_.sap.t_atm_sap_addr.SVE_tag_selector = (int8_t) T_ATM_PRESENT; + + atm_addr_.sap.t_atm_sap_addr.address_format = (u_int8_t) T_ATM_ENDSYS_ADDR; + atm_addr_.sap.t_atm_sap_addr.address_length = ATMNSAP_ADDR_LEN; + atm_addr_.sap.t_atm_sap_addr.address[ATMNSAP_ADDR_LEN - 1] = selector; + + atm_addr_.sap.t_atm_sap_layer2.SVE_tag = (int8_t) T_ATM_ABSENT; + atm_addr_.sap.t_atm_sap_layer3.SVE_tag = (int8_t) T_ATM_ABSENT; + + atm_addr_.sap.t_atm_sap_appl.SVE_tag = (int8_t) T_ATM_PRESENT; + atm_addr_.sap.t_atm_sap_appl.ID_type = (u_int8_t) T_ATM_USER_APP_ID; + + ACE_OS::memcpy (atm_addr_.sap.t_atm_sap_appl.ID.user_defined_ID, + BHLI_MAGIC, + sizeof atm_addr_.sap.t_atm_sap_appl.ID); +#elif defined (ACE_HAS_FORE_ATM_WS2) + ACE_OS::memset ((void *)&atm_addr_, 0, sizeof atm_addr_); + atm_addr_.satm_number.Addr[ ATM_ADDR_SIZE - 1 ] = (char)selector; + atm_addr_.satm_family = AF_ATM; + atm_addr_.satm_number.AddressType = ATM_NSAP; + atm_addr_.satm_number.NumofDigits = ATM_ADDR_SIZE; + atm_addr_.satm_blli.Layer2Protocol = SAP_FIELD_ABSENT; + atm_addr_.satm_blli.Layer3Protocol = SAP_FIELD_ABSENT; + atm_addr_.satm_bhli.HighLayerInfoType = SAP_FIELD_ABSENT; + + // Need to know the correspondence. + //atm_addr_.sap.t_atm_sap_appl.SVE_tag = (int8_t) T_ATM_PRESENT; + //atm_addr_.sap.t_atm_sap_appl.ID_type = (u_int8_t) T_ATM_USER_APP_ID; + //ACE_OS::memcpy (atm_addr_.sap.t_atm_sap_appl.ID.user_defined_ID, + // BHLI_MAGIC, + // sizeof atm_addr_.sap.t_atm_sap_appl.ID); +#elif defined (ACE_HAS_LINUX_ATM) + atm_addr_.sockaddratmsvc.sas_family = AF_ATMSVC; + atm_addr_.sockaddratmsvc.sas_addr.prv[ATM_ESA_LEN - 1] = (char)selector; + atm_addr_.atmsap.blli[0].l3_proto = ATM_L3_NONE; + atm_addr_.atmsap.blli[0].l2_proto = ATM_L2_NONE; + atm_addr_.atmsap.bhli.hl_type = ATM_HL_NONE; +#else + ACE_UNUSED_ARG (selector); +#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ +} + +int +ACE_ATM_Addr::set (const ACE_ATM_Addr &sap, + u_char selector) +{ + ACE_TRACE ("ACE_ATM_Addr::set"); + + this->init (selector); + + this->ACE_Addr::base_set (sap.get_type (), + sap.get_size ()); + +#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2) + ACE_ASSERT (sap.get_type () == AF_ATM); +#elif defined (ACE_HAS_LINUX_ATM) + ACE_ASSERT (sap.get_type () == PF_ATMSVC); +#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 */ + + (void) ACE_OS::memcpy ((void *) &this->atm_addr_, + (void *) &sap.atm_addr_, + sizeof this->atm_addr_); + return 0; +} + +int +ACE_ATM_Addr::set (const ATM_Addr *sap, + u_char selector) +{ + ACE_TRACE ("ACE_ATM_Addr::set"); + + this->init (selector); + +#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2) + this->ACE_Addr::base_set (AF_ATM, +#elif defined (ACE_HAS_LINUX_ATM) + this->ACE_Addr::base_set (PF_ATMSVC, +#else + this->ACE_Addr::base_set (AF_UNSPEC, +#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 */ + sizeof (*sap)); + + (void) ACE_OS::memcpy ((void *) &this->atm_addr_, + (void *) sap, + sizeof this->atm_addr_); + return 0; +} + +int +ACE_ATM_Addr::set (const ACE_TCHAR address[], + u_char selector) +{ + ACE_TRACE ("ACE_ATM_Addr::set"); + int ret; + + this->init (selector); + +#if defined (ACE_HAS_FORE_ATM_XTI) + atm_addr_.sap.t_atm_sap_addr.SVE_tag_addr = + (int8_t) T_ATM_PRESENT; +#endif /* ACE_HAS_FORE_ATM_XTI */ + + ret = this -> string_to_addr (address); + this -> set_selector (selector); + return ret; +} + +// Transform the string into the current addressing format. + +int +ACE_ATM_Addr::string_to_addr (const ACE_TCHAR sap[]) +{ + ACE_TRACE ("ACE_ATM_Addr::string_to_addr"); + +#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2) + this->ACE_Addr::base_set (AF_ATM, +#elif defined (ACE_HAS_LINUX_ATM) + this->ACE_Addr::base_set (PF_ATMSVC, +#else + this->ACE_Addr::base_set (AF_UNSPEC, +#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ + sizeof this->atm_addr_); +#if defined (ACE_HAS_FORE_ATM_XTI) + struct hostent *entry; + struct atmnsap_addr *nsap; + + // Yow, someone gave us a NULL ATM address! + if (sap == 0) + { + errno = EINVAL; + return -1; + } + else if ((entry = gethostbyname_atmnsap ((ACE_TCHAR *)sap)) != 0) + { + ACE_OS::memcpy (atm_addr_.sap.t_atm_sap_addr.address, + entry->h_addr_list[0], + ATMNSAP_ADDR_LEN - 1); + } + else if ((nsap = atmnsap_addr (sap)) != 0) + { + ACE_OS::memcpy (atm_addr_.sap.t_atm_sap_addr.address, + nsap->atmnsap, + ATMNSAP_ADDR_LEN); + } + else { + errno = EINVAL; + return -1; + } +#elif defined (ACE_HAS_FORE_ATM_WS2) + DWORD dwValue; + HANDLE hLookup; + WSAQUERYSETW qsRestrictions; + CSADDR_INFO csaBuffer; + WCHAR tmpWStr[100]; + + MultiByteToWideChar (CP_ACP, MB_PRECOMPOSED, sap, -1, tmpWStr, 100); + + csaBuffer.LocalAddr.iSockaddrLength = sizeof (struct sockaddr_atm); + csaBuffer.LocalAddr.lpSockaddr = (struct sockaddr *)&atm_addr_; + csaBuffer.RemoteAddr.iSockaddrLength = sizeof (struct sockaddr_atm); + csaBuffer.RemoteAddr.lpSockaddr = (struct sockaddr *)&atm_addr_; + + qsRestrictions.dwSize = sizeof (WSAQUERYSETW); + qsRestrictions.lpszServiceInstanceName = 0; + qsRestrictions.lpServiceClassId = &FORE_NAME_CLASS; + qsRestrictions.lpVersion = 0; + qsRestrictions.lpszComment = 0; + qsRestrictions.dwNameSpace = FORE_NAME_SPACE; + qsRestrictions.lpNSProviderId = 0; + qsRestrictions.lpszContext = L""; + qsRestrictions.dwNumberOfProtocols = 0; + qsRestrictions.lpafpProtocols = 0; + qsRestrictions.lpszQueryString = tmpWStr; + qsRestrictions.dwNumberOfCsAddrs = 1; + qsRestrictions.lpcsaBuffer = &csaBuffer; + qsRestrictions.lpBlob = 0; //&blob; + + if (::WSALookupServiceBeginW (&qsRestrictions, LUP_RETURN_ALL, &hLookup) + == SOCKET_ERROR) { + ACE_OS::printf ("Error: WSALookupServiceBeginW failed! %d\n", + ::WSAGetLastError ()); + return -1; + } + + dwValue = sizeof (WSAQUERYSETW); + + if (::WSALookupServiceNextW (hLookup, 0, &dwValue, &qsRestrictions) + == SOCKET_ERROR) { + if (WSAGetLastError () != WSA_E_NO_MORE) { + ACE_OS::printf ("Error: WSALookupServiceNextW failed! %d\n", + ::WSAGetLastError ()); + return -1; + } + } + + if (WSALookupServiceEnd (hLookup) == SOCKET_ERROR) { + ACE_OS::printf ("Error : WSALookupServiceEnd failed! %d\n", + ::WSAGetLastError ()); + errno = EINVAL; + return -1; + } +#elif defined (ACE_HAS_LINUX_ATM) + if (sap == 0 || !ACE_OS::strcmp (sap,"")) { + errno = EINVAL; + return -1; + } + + if (text2atm ((ACE_TCHAR *)sap, + (struct sockaddr *)& (atm_addr_.sockaddratmsvc), + sizeof (atm_addr_.sockaddratmsvc), + T2A_SVC | T2A_NAME) < 0) { + ACE_DEBUG (LM_DEBUG, + "Error : text2atm failed!\n"); + errno = EINVAL; + return -1; + } +#else + ACE_UNUSED_ARG (sap); + + return 0; +#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ + +#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2) || defined (ACE_HAS_LINUX_ATM) + return 0; +#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 */ +} + +// Transform the current address into string format. + +int +ACE_ATM_Addr::addr_to_string (ACE_TCHAR addr[], + size_t addrlen) const +{ + ACE_TRACE ("ACE_ATM_Addr::addr_to_string"); + +#if defined (ACE_HAS_FORE_ATM_XTI) + ACE_TCHAR buffer[MAXNAMELEN + 1]; + struct atmnsap_addr nsap; + ACE_OS::memcpy (nsap.atmnsap, + atm_addr_.sap.t_atm_sap_addr.address, + ATMNSAP_ADDR_LEN); + ACE_OS::sprintf (buffer, + ACE_TEXT ("%s"), + atmnsap_ntoa (nsap)); + + size_t total_len = ACE_OS::strlen (buffer) + sizeof ('\0'); + + if (addrlen < total_len) + return -1; + else + ACE_OS::strcpy (addr, buffer); + + return 0; +#elif defined (ACE_HAS_FORE_ATM_WS2) + ACE_TCHAR buffer[MAXNAMELEN + 1]; + int i; + + if (addrlen < ATM_ADDR_SIZE + 1) + return -1; + + for (i = 0; i < ATM_ADDR_SIZE; i++) { + buffer[ i * 3 ] = '\0'; + ACE_OS::sprintf (buffer, ACE_TEXT ("%s%02x."), + buffer, + atm_addr_.satm_number.Addr[ i ]); + } + + buffer[ ATM_ADDR_SIZE * 3 - 1 ] = '\0'; + ACE_OS::strcpy (addr, buffer); + + return 0; +#elif defined (ACE_HAS_LINUX_ATM) + ACE_TCHAR buffer[MAX_ATM_ADDR_LEN + 1]; + int total_len; + if ((total_len = atm2text (buffer, + sizeof buffer, + (struct sockaddr *)& (atm_addr_.sockaddratmsvc), + A2T_PRETTY)) < 0) { + ACE_DEBUG ((LM_DEBUG,"ACE_ATM_Addr (addr_to_string): atm2text failed\n")); + return -1; + } + if (addrlen < (size_t)total_len) + return -1; + else + ACE_OS::strcpy (addr, + buffer); + + return 0; +#else + ACE_UNUSED_ARG (addr); + ACE_UNUSED_ARG (addrlen); + return -1; +#endif /* ACE_HAS_FORE_ATM_XTI && ACE_HAS_FORE_ATM_WS2 */ +} + +const ACE_TCHAR * +ACE_ATM_Addr::addr_to_string (void) const +{ + ACE_TRACE ("ACE_ATM_Addr::addr_to_string"); + + static ACE_TCHAR addr[MAXHOSTNAMELEN + 1]; + if (this->addr_to_string (addr, + MAXHOSTNAMELEN + 1) < 0) + return 0; + + return addr; +} + +// Set a pointer to the address. +void +ACE_ATM_Addr::set_addr (void *addr, int len) +{ + ACE_TRACE ("ACE_ATM_Addr::set_addr"); + +#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2) + this->ACE_Addr::base_set (AF_ATM, +#elif defined (ACE_HAS_LINUX_ATM) + this->ACE_Addr::base_set (PF_ATMSVC, +#else + this->ACE_Addr::base_set (AF_UNSPEC, +#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_WS2 */ + len); + ACE_OS::memcpy ((void *) &this->atm_addr_, + (void *) addr, len); +} + +// Compare two addresses for inequality. + +bool +ACE_ATM_Addr::operator != (const ACE_ATM_Addr &sap) const +{ + ACE_TRACE ("ACE_ATM_Addr::operator !="); + return ! ((*this) == sap); +} + +// Compare two addresses for equality. + +bool +ACE_ATM_Addr::operator == (const ACE_ATM_Addr &sap) const +{ + ACE_TRACE ("ACE_ATM_Addr::operator =="); + +#if defined (ACE_HAS_LINUX_ATM) + return (atm_equal ((const struct sockaddr *)& (this->atm_addr_.sockaddratmsvc), + (const struct sockaddr *)& (sap.atm_addr_.sockaddratmsvc), + 0, + 0) + && + sap_equal (& (this->atm_addr_.atmsap), + & (sap.atm_addr_.atmsap), + 0)); +#else + return ACE_OS::memcmp (&atm_addr_, + &sap.atm_addr_, + sizeof (ATM_Addr)) == 0; +#endif /* ACE_HAS_LINUX_ATM */ +} + +void +ACE_ATM_Addr::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_ATM_Addr::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + + ACE_TCHAR s[ACE_MAX_FULLY_QUALIFIED_NAME_LEN + 16]; + ACE_OS::sprintf (s, + ACE_TEXT ("%s"), + this->addr_to_string ()); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("%s"), s)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_ATM */ diff --git a/dep/acelite/ace/ATM_Addr.h b/dep/acelite/ace/ATM_Addr.h new file mode 100644 index 00000000000..7fa93f1492c --- /dev/null +++ b/dep/acelite/ace/ATM_Addr.h @@ -0,0 +1,197 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file ATM_Addr.h + * + * $Id: ATM_Addr.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Joe Hoffert + */ +//========================================================================== + +#ifndef ACE_ATM_ADDR_H +#define ACE_ATM_ADDR_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_ATM) + +#include /**/ "ace/ACE_export.h" +#include "ace/Addr.h" + +#if defined (ACE_HAS_FORE_ATM_XTI) +ACE_BEGIN_VERSIONED_NAMESPACE_DECL +typedef ATMSAPAddress ATM_Addr; +ACE_END_VERSIONED_NAMESPACE_DECL +#elif defined (ACE_HAS_FORE_ATM_WS2) +#define FORE_NAME_SPACE NS_ALL +ACE_BEGIN_VERSIONED_NAMESPACE_DECL +typedef struct sockaddr_atm ATM_Addr; +ACE_END_VERSIONED_NAMESPACE_DECL +#elif defined (ACE_HAS_LINUX_ATM) + +#include /**/ "atm.h" + +// Open versioned namespace, if enabled by the user. +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +//pbrandao:as Linux has this 2 structs separeted we "link it" here +typedef struct _linux_atm_addr +{ + struct sockaddr_atmsvc sockaddratmsvc; + struct atm_sap atmsap; +} ATM_Addr; +#else +typedef int ATM_Addr; +#endif /* ACE_HAS_FORE_ATM_XTI/ACE_HAS_FORE_ATM_WS2/ACE_HAS_LINUX_ATM */ + +/** + * @class ACE_ATM_Addr + * + * @brief Defines the ATM domain address family address format. + */ +class ACE_Export ACE_ATM_Addr : public ACE_Addr +{ +public: + // Constants used for ATM options + static const long LINE_RATE; + static const int OPT_FLAGS_CPID; + static const int OPT_FLAGS_PMP; + static const int DEFAULT_SELECTOR; + + // = Initialization methods. + /// Default constructor. + ACE_ATM_Addr (u_char selector = DEFAULT_SELECTOR); + + /// Copy constructor. + ACE_ATM_Addr (const ACE_ATM_Addr &, + u_char selector = DEFAULT_SELECTOR); + + /** + * Creates an ACE_ATM_Addr from an ATMSAPAddress structure. This + * is vendor specific (FORE systems). May need to change when other + * vendors are supported. + */ + ACE_ATM_Addr (const ATM_Addr *, + u_char selector = DEFAULT_SELECTOR); + + /** + * Initializes an ACE_ATM_Addr from the which can be + * "atm-address" (e.g., + * "47.0005.80.ffe100.0000.f20f.2200.0020480694f9.00") or "hostname" + * (e.g., "frisbee.cs.wustl.edu"). + */ + ACE_ATM_Addr (const ACE_TCHAR sap[], + u_char selector = DEFAULT_SELECTOR); + + /// Default dtor. + ~ACE_ATM_Addr (void); + + // = Initialization methods (useful after object construction). + /// Default initialization for non-address values (e.g., + /// t_atm_sap_addr.SVE_tag_addr, t_atm_sap_addr.SVE_tag_selector) + void init (u_char selector = DEFAULT_SELECTOR); + + /// Initializes from another ACE_ATM_Addr. + int set (const ACE_ATM_Addr &, + u_char selector = DEFAULT_SELECTOR); + + /** + * Initializes an ACE_ATM_Addr from an ATMSAPAddress/sockaddr_atm + * structure. This is vendor specific (FORE systems). May need to + * change when other vendors are supported. + */ + int set (const ATM_Addr *, + u_char selector = DEFAULT_SELECTOR); + + /** + * Initializes an ACE_ATM_Addr from the which can be + * "atm-address" (e.g., + * "47.0005.80.ffe100.0000.f20f.2200.0020480694f9.00") or "hostname" + * (e.g., "frisbee.cs.wustl.edu"). + */ + int set (const ACE_TCHAR sap[], + u_char selector = DEFAULT_SELECTOR); + + /** + * Initializes an ACE_ATM_Addr from the which can be + * "atm-address" (e.g., + * "47.0005.80.ffe100.0000.f20f.2200.0020480694f9.00") or "hostname" + * (e.g., "frisbee.cs.wustl.edu"). + */ + virtual int string_to_addr (const ACE_TCHAR sap[]); + + /** + * Return the character representation of the ATM address (e.g., + * "47.0005.80.ffe100.0000.f20f.2200.0020480694f9.00") storing it in + * the @a addr (which is assumed to be bytes long). This + * version is reentrant. Returns -1 if the of the @a addr + * is too small, else 0. + */ + virtual int addr_to_string (ACE_TCHAR addr[], + size_t addrlen) const; + + /** + * Return the character representation of the ATM address (e.g., + * "47.0005.80.ffe100.0000.f20f.2200.0020480694f9.00"). Returns -1 + * if the of the is too small, else 0.(This version + * is non-reentrant since it returns a pointer to a static data + * area.) + */ + const ACE_TCHAR *addr_to_string (void) const; + + /// Return a pointer to the underlying network address. + virtual void *get_addr (void) const; + + /// Set a pointer to the address. + virtual void set_addr (void *, int); + + /// Return the selector for network address. + u_char get_selector (void) const; + + /// Set the selector for the network address. + void set_selector (u_char selector); + + /** + * Compare two addresses for equality. The addresses are considered + * equal if they contain the same ATM address. Q: Is there any + * other check for equality needed for ATM? + */ + bool operator == (const ACE_ATM_Addr &SAP) const; + + /// Compare two addresses for inequality. + bool operator != (const ACE_ATM_Addr &SAP) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +// char *construct_options (ACE_HANDLE fd, +// int qos_kb, +// int flags, +// long *optsize); +// // Construct options for ATM connections + +private: + ATM_Addr atm_addr_; +}; + +// Close versioned namespace, if enabled by the user. +ACE_END_VERSIONED_NAMESPACE_DECL + + +#if defined (__ACE_INLINE__) +#include "ace/ATM_Addr.inl" +#endif /* __ACE_INLINE__ */ + +#endif /* ACE_HAS_ATM */ +#include /**/ "ace/post.h" +#endif /* ACE_ATM_ADDR_H */ diff --git a/dep/acelite/ace/ATM_Addr.inl b/dep/acelite/ace/ATM_Addr.inl new file mode 100644 index 00000000000..55f43d6613a --- /dev/null +++ b/dep/acelite/ace/ATM_Addr.inl @@ -0,0 +1,37 @@ +// -*- C++ -*- +// +// $Id: ATM_Addr.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE u_char +ACE_ATM_Addr::get_selector (void) const +{ + ACE_TRACE ("ACE_ATM_Addr::get_selector"); +#if defined (ACE_HAS_FORE_ATM_XTI) + return atm_addr_.sap.t_atm_sap_addr.address[ATMNSAP_ADDR_LEN - 1]; +#elif defined (ACE_HAS_FORE_ATM_WS2) + return atm_addr_.satm_number.Addr[ ATM_ADDR_SIZE - 1 ]; +#elif defined (ACE_HAS_LINUX_ATM) + return atm_addr_.sockaddratmsvc.sas_addr.prv[ATM_ESA_LEN - 1]; +#else + return 0; +#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ +} + +ACE_INLINE void +ACE_ATM_Addr::set_selector (u_char selector) +{ + ACE_TRACE ("ACE_ATM_Addr::set_selector"); +#if defined (ACE_HAS_FORE_ATM_XTI) + atm_addr_.sap.t_atm_sap_addr.address[ATMNSAP_ADDR_LEN - 1] = selector; +#elif defined (ACE_HAS_FORE_ATM_WS2) + atm_addr_.satm_number.Addr[ ATM_ADDR_SIZE - 1 ] = selector; +#elif defined (ACE_HAS_LINUX_ATM) + atm_addr_.sockaddratmsvc.sas_addr.prv[ATM_ESA_LEN - 1] = selector; +#else + ACE_UNUSED_ARG (selector); +#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/ATM_Connector.cpp b/dep/acelite/ace/ATM_Connector.cpp new file mode 100644 index 00000000000..c1ce226adce --- /dev/null +++ b/dep/acelite/ace/ATM_Connector.cpp @@ -0,0 +1,138 @@ +// ATM_Connector.cpp +// $Id: ATM_Connector.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/ATM_Connector.h" +#if defined (ACE_HAS_ATM) + +#include "ace/Handle_Set.h" + +ACE_RCSID(ace, ATM_Connector, "$Id: ATM_Connector.cpp 80826 2008-03-04 14:51:23Z wotte $") + +#if !defined (__ACE_INLINE__) +#include "ace/ATM_Connector.inl" +#endif /* __ACE_INLINE__ */ + +// Open versioned namespace, if enabled by the user. +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_ATM_Connector) + +ACE_ATM_Connector::ACE_ATM_Connector (void) +{ + ACE_TRACE ("ACE_ATM_Connector::ACE_ATM_Connector"); +} + +// Actively connect and produce a new ACE_ATM_Stream if things go well... +// Connect the to the , waiting up to +// amount of time if necessary. + +int +ACE_ATM_Connector::connect (ACE_ATM_Stream &new_stream, + const ACE_ATM_Addr &remote_sap, + ACE_ATM_Params params, + ACE_ATM_QoS options, + ACE_Time_Value *timeout, + const ACE_ATM_Addr &local_sap, + int reuse_addr, + int flags, + int perms) +{ + ACE_TRACE ("ACE_ATM_Connector::connect"); +#if defined (ACE_HAS_FORE_ATM_XTI) + return connector_.connect(new_stream.get_stream(), + remote_sap, + timeout, + local_sap, + reuse_addr, + flags, + perms, + params.get_device(), + params.get_info(), + params.get_rw_flag(), + params.get_user_data(), + &options.get_qos()); +#elif defined (ACE_HAS_FORE_ATM_WS2) + ACE_DEBUG(LM_DEBUG, + ACE_TEXT ("ATM_Connector(connect): set QoS parameters\n" )); + + ACE_HANDLE s = new_stream.get_handle(); + struct sockaddr_atm *saddr = ( struct sockaddr_atm *)remote_sap.get_addr(); + ACE_QoS cqos = options.get_qos(); + + ACE_QoS_Params qos_params = ACE_QoS_Params(0, + 0, + &cqos, + 0, + 0); + + ACE_DEBUG(LM_DEBUG, + ACE_TEXT ("ATM_Connector(connect): connecting...\n")); + + int result = ACE_OS::connect( s, + ( struct sockaddr *)saddr, + sizeof( struct sockaddr_atm ), + qos_params ); + + if ( result != 0 ) + ACE_OS::printf( "ATM_Connector(connect): connection failed, %d\n", + ::WSAGetLastError()); + + return result; +#elif defined (ACE_HAS_LINUX_ATM) + ACE_UNUSED_ARG (params); + ACE_UNUSED_ARG (timeout); + ACE_UNUSED_ARG (reuse_addr); + ACE_UNUSED_ARG (perms); + ACE_UNUSED_ARG (flags); + + ACE_HANDLE handle = new_stream.get_handle(); + ATM_QoS qos =options.get_qos(); + ATM_Addr *local_addr=(ATM_Addr*)local_sap.get_addr(), + *remote_addr=(ATM_Addr*)remote_sap.get_addr(); + + if (ACE_OS::setsockopt(handle, + SOL_ATM, + SO_ATMSAP, + reinterpret_cast (&(local_addr->atmsap)), + sizeof(local_addr->atmsap)) < 0) { + ACE_OS::printf( "ATM_Connector(connect): unable to set atmsap %d\nContinuing...", + errno); + } + if (ACE_OS::setsockopt(handle, + SOL_ATM, + SO_ATMQOS, + reinterpret_cast (&qos), + sizeof(qos)) < 0) { + ACE_DEBUG((LM_DEBUG,ACE_TEXT ("ATM_Connector(connect): unable to set qos %d\n"), + errno)); + return -1; + } + + int result = ACE_OS::connect(handle, + (struct sockaddr *)&(remote_addr->sockaddratmsvc), + sizeof( remote_addr->sockaddratmsvc)); + + if ( result != 0 ) + ACE_DEBUG(LM_DEBUG, + ACE_TEXT ("ATM_Connector(connect): connection failed, %d\n"), + errno); + + return result; +#else + ACE_UNUSED_ARG (new_stream); + ACE_UNUSED_ARG (remote_sap); + ACE_UNUSED_ARG (params); + ACE_UNUSED_ARG (options); + ACE_UNUSED_ARG (timeout); + ACE_UNUSED_ARG (local_sap); + ACE_UNUSED_ARG (reuse_addr); + ACE_UNUSED_ARG (flags); + ACE_UNUSED_ARG (perms); + return 0; +#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ +} + +// Close versioned namespace, if enabled by the user. +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_ATM */ diff --git a/dep/acelite/ace/ATM_Connector.h b/dep/acelite/ace/ATM_Connector.h new file mode 100644 index 00000000000..940fc5a307f --- /dev/null +++ b/dep/acelite/ace/ATM_Connector.h @@ -0,0 +1,164 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file ATM_Connector.h + * + * $Id: ATM_Connector.h 82723 2008-09-16 09:35:44Z johnnyw $ + * + * @author Joe Hoffert + */ +//============================================================================= + +#ifndef ACE_ATM_CONNECTOR_H +#define ACE_ATM_CONNECTOR_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_ATM) + +#include "ace/ATM_Stream.h" +#include "ace/ATM_Params.h" +#include "ace/ATM_QoS.h" + +#if defined (ACE_WIN32) || defined (ACE_HAS_LINUX_ATM) +#include "ace/SOCK_Connector.h" +ACE_BEGIN_VERSIONED_NAMESPACE_DECL +typedef ACE_SOCK_Connector ATM_Connector; +ACE_END_VERSIONED_NAMESPACE_DECL +#else +#include "ace/XTI_ATM_Mcast.h" +ACE_BEGIN_VERSIONED_NAMESPACE_DECL +typedef ACE_XTI_ATM_Mcast ATM_Connector; +// Open versioned namespace, if enabled by the user. +ACE_END_VERSIONED_NAMESPACE_DECL +#endif + +// Open versioned namespace, if enabled by the user. +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_ATM_Connector + * + * @brief Defines an active connection factory for the ACE_ATM C++ + * wrappers. + */ +class ACE_Export ACE_ATM_Connector +{ +public: + // = Initialization methods. + /// Default constructor. + ACE_ATM_Connector (void); + + /** + * Actively connect and produce a @a new_stream if things go well. + * The @a remote_sap is the address that we are trying to connect + * with. The are the parameters needed for either socket + * or XTI/ATM connections. The @a timeout is the amount of time to + * wait to connect. If it's 0 then we block indefinitely. If + * *timeout == {0, 0} then the connection is done using non-blocking + * mode. In this case, if the connection can't be made immediately + * the value of -1 is returned with @c errno == EWOULDBLOCK. If + * *timeout > {0, 0} then this is the maximum amount of time to wait before + * timing out. If the time expires before the connection is made + * @c errno == ETIME. The @a local_sap is the value of local address + * to bind to. If it's the default value of then + * the user is letting the OS do the binding. If @a reuse_addr == 1 + * then the is reused, even if it hasn't been cleanedup yet. + */ + ACE_ATM_Connector (ACE_ATM_Stream &new_stream, + const ACE_ATM_Addr &remote_sap, + ACE_ATM_Params params = ACE_ATM_Params(), + ACE_ATM_QoS options = ACE_ATM_QoS(), + ACE_Time_Value *timeout = 0, + const ACE_ATM_Addr &local_sap = ACE_ATM_Addr( "", 0 ), + int reuse_addr = 0, +#if defined (ACE_WIN32) + int flags = 0, +#else + int flags = O_RDWR, +#endif /* ACE_WIN32 */ + int perms = 0); + + /** + * Actively connect and produce a @a new_stream if things go well. + * The @a remote_sap is the address that we are trying to connect + * with. The are the parameters needed for either socket + * or XTI/ATM connections. The @a timeout is the amount of time to + * wait to connect. If it's 0 then we block indefinitely. If + * *timeout == {0, 0} then the connection is done using non-blocking + * mode. In this case, if the connection can't be made immediately + * the value of -1 is returned with @c errno == EWOULDBLOCK. If + * *timeout > {0, 0} then this is the maximum amount of time to wait before + * timing out. If the time expires before the connection is made + * @c errno == ETIME. The @a local_sap is the value of local address + * to bind to. If it's the default value of then + * the user is letting the OS do the binding. If @a reuse_addr == 1 + * then the is reused, even if it hasn't been cleanedup yet. + */ + int connect (ACE_ATM_Stream &new_stream, + const ACE_ATM_Addr &remote_sap, + ACE_ATM_Params params = ACE_ATM_Params(), + ACE_ATM_QoS options = ACE_ATM_QoS(), + ACE_Time_Value *timeout = 0, + const ACE_ATM_Addr &local_sap = ACE_ATM_Addr( "", + 0 ), + int reuse_addr = 0, +#if defined (ACE_WIN32) + int flags = 0, +#else + int flags = O_RDWR, +#endif /* ACE_WIN32 */ + int perms = 0); + + /** + * Try to complete a non-blocking connection. + * If connection completion is successful then @a new_stream contains + * the connected ACE_SOCK_Stream. If @a remote_sap is non-NULL then it + * will contain the address of the connected peer. + */ + int complete (ACE_ATM_Stream &new_stream, + ACE_ATM_Addr *remote_sap, + ACE_Time_Value *tv); + + /** + * Actively add a leaf to the root (i.e., point-to-multipoint). The + * @a remote_sap is the address of the leaf that we + * are trying to add. + */ + int add_leaf (ACE_ATM_Stream ¤t_stream, + const ACE_Addr &remote_sap, + ACE_ATM_QoS &qos); + + /// Resets any event associations on this handle + bool reset_new_handle (ACE_HANDLE handle); + + // = Meta-type info + typedef ACE_ATM_Addr PEER_ADDR; + typedef ACE_ATM_Stream PEER_STREAM; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + ATM_Connector connector_; +}; + +// Open versioned namespace, if enabled by the user. +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/ATM_Connector.inl" +#endif /* __ACE_INLINE__ */ + +#endif /* ACE_HAS_ATM */ +#include /**/ "ace/post.h" +#endif /* ACE_ATM_CONNECTOR_H */ diff --git a/dep/acelite/ace/ATM_Connector.inl b/dep/acelite/ace/ATM_Connector.inl new file mode 100644 index 00000000000..10d1623f6c3 --- /dev/null +++ b/dep/acelite/ace/ATM_Connector.inl @@ -0,0 +1,132 @@ +// -*- C++ -*- +// +// $Id: ATM_Connector.inl 84565 2009-02-23 08:20:39Z johnnyw $ + +// Open versioned namespace, if enabled by the user. +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE void +ACE_ATM_Connector::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_ATM_Connector::dump"); +#endif /* ACE_HAS_DUMP */ +} + +ACE_INLINE +ACE_ATM_Connector::ACE_ATM_Connector (ACE_ATM_Stream &new_stream, + const ACE_ATM_Addr &remote_sap, + ACE_ATM_Params params, + ACE_ATM_QoS options, + ACE_Time_Value *timeout, + const ACE_ATM_Addr &local_sap, + int reuse_addr, + int flags, + int perms) +{ + ACE_TRACE ("ACE_ATM_Connector::ACE_ATM_Connector"); + if ((ACE_HANDLE)this->connect (new_stream, + remote_sap, + params, + options, + timeout, + local_sap, + reuse_addr, + flags, + perms) == ACE_INVALID_HANDLE + && timeout != 0 && !(errno == EWOULDBLOCK || errno == ETIME)) + ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_ATM_Stream::ACE_ATM_Stream"))); +} + +// Try to complete a non-blocking connection. + +ACE_INLINE +int +ACE_ATM_Connector::complete (ACE_ATM_Stream &new_stream, + ACE_ATM_Addr *remote_sap, + ACE_Time_Value *tv) +{ + ACE_TRACE ("ACE_ATM_Connector::complete"); +#if defined (ACE_HAS_ATM) + return connector_.complete(new_stream.get_stream(), + remote_sap, + tv); +#else + ACE_UNUSED_ARG(new_stream); + ACE_UNUSED_ARG(remote_sap); + ACE_UNUSED_ARG(tv); + return 0; +#endif +} + +ACE_INLINE +int +ACE_ATM_Connector::add_leaf (ACE_ATM_Stream ¤t_stream, + const ACE_Addr &remote_sap, + ACE_ATM_QoS &qos) +{ + ACE_TRACE ("ACE_ATM_Connector::add_leaf"); +#if defined (ACE_HAS_FORE_ATM_XTI) + return connector_.add_leaf(current_stream.get_stream(), + remote_sap, + leaf_id, + timeout); +#elif defined (ACE_HAS_FORE_ATM_WS2) + struct sockaddr_atm *saddr = (struct sockaddr_atm *)remote_sap.get_addr(); + ACE_QoS cqos = qos.get_qos(); + int addr_len = sizeof( struct sockaddr_atm ); + + ACE_QoS_Params qos_params(0, + 0, + &cqos, + 0, + (JL_SENDER_ONLY)); + + ACE_OS::printf( "ATM_Connector::add_leaf: connecting...\n" ); + + ACE_HANDLE result = ACE_OS::join_leaf(current_stream.get_handle(), + (struct sockaddr *)saddr, + addr_len, + qos_params); + + if ( result == ACE_INVALID_HANDLE ) + ACE_OS::printf( "ATM_Connector(add_leaf): connection failed, %d\n", + ::WSAGetLastError()); + + return (result != ACE_INVALID_HANDLE); +#elif defined (ACE_HAS_LINUX_ATM) + ACE_OS::printf("ATM_Connector(add_leaf): not yet implemented in Linux\n"); + + ACE_UNUSED_ARG(current_stream); + ACE_UNUSED_ARG(remote_sap); + ACE_UNUSED_ARG(leaf_id); + ACE_UNUSED_ARG(timeout); + + return 0; +#else + ACE_UNUSED_ARG(current_stream); + ACE_UNUSED_ARG(remote_sap); + ACE_UNUSED_ARG(leaf_id); + ACE_UNUSED_ARG(timeout); + return 0; +#endif +} + +ACE_INLINE +bool +ACE_ATM_Connector::reset_new_handle (ACE_HANDLE handle) +{ +#if defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0) + // Reset the event association + return ::WSAEventSelect ((SOCKET) handle, + 0, + 0); +#else /* !defined ACE_HAS_WINSOCK2 */ + ACE_UNUSED_ARG (handle); + return false; +#endif /* ACE_WIN32 */ +} + +// Close versioned namespace, if enabled by the user. +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/ATM_Params.cpp b/dep/acelite/ace/ATM_Params.cpp new file mode 100644 index 00000000000..70a05f1d71b --- /dev/null +++ b/dep/acelite/ace/ATM_Params.cpp @@ -0,0 +1,20 @@ +// $Id: ATM_Params.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/ATM_Params.h" + +#if defined (ACE_HAS_ATM) + +ACE_RCSID(ace, ATM_Params, "$Id: ATM_Params.cpp 80826 2008-03-04 14:51:23Z wotte $") + +#if !defined (__ACE_INLINE__) +#include "ace/ATM_Params.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_ATM_Params) + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_ATM */ + diff --git a/dep/acelite/ace/ATM_Params.h b/dep/acelite/ace/ATM_Params.h new file mode 100644 index 00000000000..d1e8c923118 --- /dev/null +++ b/dep/acelite/ace/ATM_Params.h @@ -0,0 +1,214 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file ATM_Params.h + * + * $Id: ATM_Params.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Joe Hoffert + */ +//========================================================================== + + +#ifndef ACE_ATM_PARAMS_H +#define ACE_ATM_PARAMS_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_ATM) + +#include /**/ "ace/ACE_export.h" + +#if defined (ACE_HAS_FORE_ATM_XTI) +#include "ace/TLI.h" +#define ATM_PROTOCOL_DEFAULT 0 +typedef struct t_info Param_Info; +typedef struct netbuf Param_Udata; +#elif defined (ACE_HAS_FORE_ATM_WS2) +#include "ace/SOCK.h" +#define ATM_PROTOCOL_DEFAULT ATMPROTO_AAL5 +#define ACE_XTI_ATM_DEVICE "" +typedef int Param_Info; +typedef int Param_Udata; +#elif defined (ACE_HAS_LINUX_ATM) +#include /**/ "atm.h" +#define AF_ATM PF_ATMSVC +#define ACE_XTI_ATM_DEVICE "" +#define ATM_PROTOCOL_DEFAULT ATM_AAL5 +typedef int Param_Info; +typedef int Param_Udata; +#else +#define ACE_XTI_ATM_DEVICE "" +typedef int Param_Info; +typedef int Param_Udata; +#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_ATM_Params + * + * @brief Wrapper class that simplifies the information passed to the ATM + * enabled ACE_ATM_Connector class. + */ +class ACE_Export ACE_ATM_Params +{ +public: + /** + * Initialize the data members. This class combines options from + * ACE_SOCK_Connector (@a protocol_family, @a protocol, , + * @a protocol_info, , and @a flags) and + * ACE_TLI_Connector (, , , , and ) + * so that either mechanism can be used transparently for ATM. + */ + ACE_ATM_Params (int rw_flag = 1, + const char device[] = ACE_XTI_ATM_DEVICE, + Param_Info *info = 0, + Param_Udata *udata = 0, + int oflag = O_RDWR, + int protocol_family = AF_ATM, + int protocol = ATM_PROTOCOL_DEFAULT, + int type = +#if defined (ACE_HAS_LINUX_ATM) + SOCK_DGRAM, +#else + SOCK_RAW, +#endif /* ACE_HAS_LINUX_ATM */ + ACE_Protocol_Info *protocol_info = 0, + ACE_SOCK_GROUP g = 0, + u_long flags + = ACE_FLAG_MULTIPOINT_C_ROOT + | ACE_FLAG_MULTIPOINT_D_ROOT, // connector by default + int reuse_addr = 0); + + /// Destructor. + ~ACE_ATM_Params (); + + /// Get protocol family. + int get_protocol_family (void) const; + + /// Set protocol family. + void set_protocol_family (int); + + /// Get protocol. + int get_protocol (void) const; + + /// Set protocol. + void set_protocol (int); + + /// Get type. + int get_type (void) const; + + /// Set type. + void set_type (int); + + /// Get protocol info. + ACE_Protocol_Info *get_protocol_info( void ); + + /// Set protocol info. + void set_protocol_info( ACE_Protocol_Info *); + + /// Get socket group. + ACE_SOCK_GROUP get_sock_group( void ); + + /// Set socket group. + void set_sock_group( ACE_SOCK_GROUP ); + + /// Get socket flags. + u_long get_flags( void ); + + /// Set socket flags. + void set_flags( u_long ); + + /// Get reuse_addr flag. + int get_reuse_addr (void) const; + + /// Set reuse_addr flag. + void set_reuse_addr (int); + + /// Get device. + const char* get_device (void) const; + + /// Get info. + Param_Info* get_info (void) const; + + /// Set info. + void set_info (Param_Info *); + + /// Get r/w flag. + int get_rw_flag (void) const; + + /// Set r/w flag. + void set_rw_flag (int); + + /// Get user data. + Param_Udata* get_user_data (void) const; + + /// Set user data. + void set_user_data (Param_Udata*); + + /// Get open flag. + int get_oflag (void) const; + + /// Set open flag. + void set_oflag (int); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + /// Protocol family for sockets connections. + int protocol_family_; + + /// Protocol for sockets connections. + int protocol_; + + /// Type for opening sockets. + int type_; + + /// Information about the protocol. + ACE_Protocol_Info *protocol_info_; + + /// Socket group used (for sockets only). + ACE_SOCK_GROUP group_; + + /// Flags for sockets (for sockets only). + u_long flags_; + + /// Flag for reusing address for opening sockets. + int reuse_addr_; + + /// Device name for XTI/ATM connections. + const char *device_; + + /// Info for XTI/ATM connections. + Param_Info *info_; + + /// R/W flag for XTI/ATM connections. + int rw_flag_; + + /// User data for XTI/ATM connections. + Param_Udata *udata_; + + /// Open flag for XTI/ATM connections. + int oflag_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/ATM_Params.inl" +#endif /* __ACE_INLINE__ */ + +#endif /* ACE_HAS_ATM */ +#include /**/ "ace/post.h" +#endif /* ACE_ATM_PARAMS_H */ diff --git a/dep/acelite/ace/ATM_Params.inl b/dep/acelite/ace/ATM_Params.inl new file mode 100644 index 00000000000..de2a4d45127 --- /dev/null +++ b/dep/acelite/ace/ATM_Params.inl @@ -0,0 +1,235 @@ +// -*- C++ -*- +// +// $Id: ATM_Params.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE void +ACE_ATM_Params::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_ATM_Params::dump"); +#endif /* ACE_HAS_DUMP */ +} + +ACE_INLINE +ACE_ATM_Params::ACE_ATM_Params (int rw_flag, + const char device[], + Param_Info *info, + Param_Udata *udata, + int oflag, + int protocol_family, + int protocol, + int type, + ACE_Protocol_Info *protocol_info, + ACE_SOCK_GROUP g, + u_long flags, + int reuse_addr) + : protocol_family_(protocol_family), + protocol_(protocol), + type_(type), + protocol_info_(protocol_info), + group_(g), + flags_(flags), + reuse_addr_(reuse_addr), + device_(device), + info_(info), + rw_flag_(rw_flag), + udata_(udata), + oflag_(oflag) +{ + ACE_TRACE ("ACE_ATM_Params::ACE_ATM_Params"); +} + +// Default dtor. +ACE_INLINE +ACE_ATM_Params::~ACE_ATM_Params (void) +{ + ACE_TRACE ("ACE_ATM_Params::~ACE_ATM_Params"); +} + +ACE_INLINE +int +ACE_ATM_Params::get_protocol_family (void) const +{ + ACE_TRACE ("ACE_ATM_Params::get_protocol_family"); + return protocol_family_; +} + +ACE_INLINE +void +ACE_ATM_Params::set_protocol_family (int family) +{ + ACE_TRACE ("ACE_ATM_Params::set_protocol_family"); + protocol_family_ = family; +} + +ACE_INLINE +int +ACE_ATM_Params::get_protocol (void) const +{ + ACE_TRACE ("ACE_ATM_Params::get_protocol"); + return protocol_; +} + +ACE_INLINE +void +ACE_ATM_Params::set_protocol (int protocol) +{ + ACE_TRACE ("ACE_ATM_Params::set_protocol"); + protocol_ = protocol; +} + +ACE_INLINE +int +ACE_ATM_Params::get_type (void) const +{ + ACE_TRACE ("ACE_ATM_Params::get_type"); + return type_; +} + +ACE_INLINE +void +ACE_ATM_Params::set_type (int type) +{ + ACE_TRACE ("ACE_ATM_Params::set_type"); + type_ = type; +} + +ACE_INLINE +ACE_Protocol_Info* +ACE_ATM_Params::get_protocol_info( void ) +{ + ACE_TRACE ("ACE_ATM_Params::get_protocol_info"); + return protocol_info_; +} + +ACE_INLINE +void +ACE_ATM_Params::set_protocol_info( ACE_Protocol_Info *protocol_info ) +{ + ACE_TRACE ("ACE_ATM_Params::set_protocol_info"); + protocol_info_ = protocol_info; +} + +ACE_INLINE +ACE_SOCK_GROUP +ACE_ATM_Params::get_sock_group( void ) +{ + ACE_TRACE ("ACE_ATM_Params::get_sock_group"); + return group_; +} + +ACE_INLINE +void +ACE_ATM_Params::set_sock_group( ACE_SOCK_GROUP g ) +{ + ACE_TRACE ("ACE_ATM_Params::set_sock_group"); + group_ = g; +} + +ACE_INLINE +u_long +ACE_ATM_Params::get_flags( void ) +{ + ACE_TRACE ("ACE_ATM_Params::get_flags"); + return flags_; +} + +ACE_INLINE +void +ACE_ATM_Params::set_flags( u_long flags) +{ + ACE_TRACE ("ACE_ATM_Params::set_flags"); + flags_ = flags; +} + +ACE_INLINE +int +ACE_ATM_Params::get_reuse_addr (void) const +{ + ACE_TRACE ("ACE_ATM_Params::get_reuse_addr"); + return reuse_addr_; +} + +ACE_INLINE +void +ACE_ATM_Params::set_reuse_addr (int reuse_addr) +{ + ACE_TRACE ("ACE_ATM_Params::set_reuse_addr"); + reuse_addr_ = reuse_addr; +} + +ACE_INLINE +const char* +ACE_ATM_Params::get_device (void) const +{ + ACE_TRACE ("ACE_ATM_Params::get_device"); + return device_; +} + +ACE_INLINE +Param_Info* +ACE_ATM_Params::get_info (void) const +{ + ACE_TRACE ("ACE_ATM_Params::get_info"); + return info_; +} + +ACE_INLINE +void +ACE_ATM_Params::set_info (Param_Info* info) +{ + ACE_TRACE ("ACE_ATM_Params::set_info"); + info_ = info; +} + +ACE_INLINE +int +ACE_ATM_Params::get_rw_flag (void) const +{ + ACE_TRACE ("ACE_ATM_Params::get_rw_flag"); + return rw_flag_; +} + +ACE_INLINE +void +ACE_ATM_Params::set_rw_flag (int rw_flag) +{ + ACE_TRACE ("ACE_ATM_Params::set_rw_flag"); + rw_flag_ = rw_flag; +} + +ACE_INLINE +Param_Udata* +ACE_ATM_Params::get_user_data (void) const +{ + ACE_TRACE ("ACE_ATM_Params::get_user_data"); + return udata_; +} + +ACE_INLINE +void +ACE_ATM_Params::set_user_data (Param_Udata *udata) +{ + ACE_TRACE ("ACE_ATM_Params::set_user_data"); + udata_ = udata; +} + +ACE_INLINE +int +ACE_ATM_Params::get_oflag (void) const +{ + ACE_TRACE ("ACE_ATM_Params::get_oflag"); + return oflag_; +} + +ACE_INLINE +void +ACE_ATM_Params::set_oflag (int oflag) +{ + ACE_TRACE ("ACE_ATM_Params::set_oflag"); + oflag_ = oflag; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/ATM_QoS.cpp b/dep/acelite/ace/ATM_QoS.cpp new file mode 100644 index 00000000000..5f83d3a14d2 --- /dev/null +++ b/dep/acelite/ace/ATM_QoS.cpp @@ -0,0 +1,631 @@ +// $Id: ATM_QoS.cpp 84262 2009-01-29 10:34:33Z johnnyw $ + +#include "ace/ATM_QoS.h" + +ACE_RCSID(ace, ATM_QoS, "$Id: ATM_QoS.cpp 84262 2009-01-29 10:34:33Z johnnyw $") + +#if defined (ACE_HAS_ATM) + +#if !defined (__ACE_INLINE__) +#include "ace/ATM_QoS.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2) +#define BHLI_MAGIC "FORE_ATM" +// This is line rate in cells/s for an OC-3 MM interface. +const long ACE_ATM_QoS::LINE_RATE = 353207; +const int ACE_ATM_QoS::OPT_FLAGS_CPID = 0x1; +const int ACE_ATM_QoS::OPT_FLAGS_PMP = 0x2; +const int ACE_ATM_QoS::DEFAULT_SELECTOR = 0x99; +const int ACE_ATM_QoS::DEFAULT_PKT_SIZE = 8192; +#elif defined (ACE_HAS_LINUX_ATM) +//pbrandao:for Linux: +//pbrandao:for now stick with current definitions +//pbrandao:see if later need to change +const long ACE_ATM_QoS::LINE_RATE = 353207; +const int ACE_ATM_QoS::OPT_FLAGS_CPID = 0x1; +const int ACE_ATM_QoS::OPT_FLAGS_PMP = 0x2; +const int ACE_ATM_QoS::DEFAULT_SELECTOR = 0x99; +const int ACE_ATM_QoS::DEFAULT_PKT_SIZE = 8192; +#else +const long ACE_ATM_QoS::LINE_RATE = 0L; +const int ACE_ATM_QoS::OPT_FLAGS_CPID = 0; +const int ACE_ATM_QoS::OPT_FLAGS_PMP = 0; +const int ACE_ATM_QoS::DEFAULT_SELECTOR = 0x0; +const int ACE_ATM_QoS::DEFAULT_PKT_SIZE = 0; +#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ + +ACE_ALLOC_HOOK_DEFINE(ACE_ATM_QoS) + +ACE_ATM_QoS::ACE_ATM_QoS (int pktSize) +{ + ACE_TRACE ("ACE_ATM_QoS::ACE_ATM_QoS"); +#if defined (ACE_HAS_LINUX_ATM) + ACE_OS::memset(&qos_, 0, sizeof(qos_)); + qos_.aal = ATM_PROTOCOL_DEFAULT; + qos_.rxtp.traffic_class = ATM_ANYCLASS; + qos_.rxtp.max_sdu = pktSize; + qos_.txtp.traffic_class = ATM_ANYCLASS; + qos_.txtp.max_sdu = pktSize; +#else + ACE_UNUSED_ARG (pktSize); +#endif /* ACE_HAS_LINUX_ATM */ +} + +ACE_ATM_QoS::ACE_ATM_QoS(int rate, + int pktSize) +{ + ACE_TRACE( "ACE_ATM_QoS::ACE_ATM_QoS" ); +#if defined (ACE_HAS_FORE_ATM_WS2) + AAL_PARAMETERS_IE ie_aalparams; + ATM_TRAFFIC_DESCRIPTOR_IE ie_td; + ATM_BROADBAND_BEARER_CAPABILITY_IE ie_bbc; + ATM_QOS_CLASS_IE ie_qos; + Q2931_IE *ie_ptr; + int size; + + // Setting up cbr parameters ... + ie_aalparams.AALType = AALTYPE_5; + ie_aalparams.AALSpecificParameters.AAL5Parameters.ForwardMaxCPCSSDUSize + = pktSize; // was 1516; + ie_aalparams.AALSpecificParameters.AAL5Parameters.BackwardMaxCPCSSDUSize + = pktSize; // was 1516; + ie_aalparams.AALSpecificParameters.AAL5Parameters.Mode = AAL5_MODE_MESSAGE; + ie_aalparams.AALSpecificParameters.AAL5Parameters.SSCSType = AAL5_SSCS_NULL; + + size = sizeof(Q2931_IE_TYPE) + sizeof(ULONG) + sizeof(AAL_PARAMETERS_IE); + + ie_td.Forward.PeakCellRate_CLP0 = SAP_FIELD_ABSENT; + ie_td.Forward.PeakCellRate_CLP01 = rate; + ie_td.Forward.SustainableCellRate_CLP0 = SAP_FIELD_ABSENT; + ie_td.Forward.SustainableCellRate_CLP01 = SAP_FIELD_ABSENT; + ie_td.Forward.MaxBurstSize_CLP0 = SAP_FIELD_ABSENT; + ie_td.Forward.MaxBurstSize_CLP01 = SAP_FIELD_ABSENT; + ie_td.Forward.Tagging = SAP_FIELD_ABSENT; + + ie_td.Backward.PeakCellRate_CLP0 = SAP_FIELD_ABSENT; + ie_td.Backward.PeakCellRate_CLP01 = rate; + ie_td.Backward.SustainableCellRate_CLP0 = SAP_FIELD_ABSENT; + ie_td.Backward.SustainableCellRate_CLP01 = SAP_FIELD_ABSENT; + ie_td.Backward.MaxBurstSize_CLP0 = SAP_FIELD_ABSENT; + ie_td.Backward.MaxBurstSize_CLP01 = SAP_FIELD_ABSENT; + ie_td.Backward.Tagging = SAP_FIELD_ABSENT; + + ie_td.BestEffort = 0; // Note: this must be set to zero for CBR. + + size += sizeof( Q2931_IE_TYPE ) + + sizeof( ULONG ) + + sizeof( ATM_TRAFFIC_DESCRIPTOR_IE ); + + ie_bbc.BearerClass = BCOB_X; + ie_bbc.TrafficType = TT_CBR; + ie_bbc.TimingRequirements = TR_END_TO_END; + ie_bbc.ClippingSusceptability = CLIP_NOT; + ie_bbc.UserPlaneConnectionConfig = UP_P2P; + + size += sizeof( Q2931_IE_TYPE ) + + sizeof( ULONG ) + + sizeof( ATM_BROADBAND_BEARER_CAPABILITY_IE ); + + ie_qos.QOSClassForward = QOS_CLASS1; + ie_qos.QOSClassBackward = QOS_CLASS1; // This may not be really used + // since we do only simplex data xfer. + + size += sizeof(Q2931_IE_TYPE) + sizeof(ULONG) + sizeof(ATM_QOS_CLASS_IE); + + qos_.ProviderSpecific.buf = (char *) ACE_OS::malloc(size); + if (qos_.ProviderSpecific.buf == 0) { + ACE_ERROR((LM_ERROR, + ACE_TEXT ("ACE_ATM_QoS::ACE_ATM_QoS: Unable to allocate %d bytes for qos_.ProviderSpecific.buf\n"), + size)); + return; + } + qos_.ProviderSpecific.len = size; + ACE_OS::memset(qos_.ProviderSpecific.buf, 0, size); + + ie_ptr = (Q2931_IE *) qos_.ProviderSpecific.buf; + ie_ptr->IEType = IE_AALParameters; + ie_ptr->IELength = sizeof( Q2931_IE_TYPE ) + + sizeof( ULONG ) + + sizeof( AAL_PARAMETERS_IE ); + ACE_OS::memcpy(ie_ptr->IE, &ie_aalparams, sizeof(AAL_PARAMETERS_IE)); + + ie_ptr = (Q2931_IE *) ((char *)ie_ptr + ie_ptr->IELength); + ie_ptr->IEType = IE_TrafficDescriptor; + ie_ptr->IELength = sizeof( Q2931_IE_TYPE ) + + sizeof( ULONG ) + + sizeof( ATM_TRAFFIC_DESCRIPTOR_IE ); + ACE_OS::memcpy(ie_ptr->IE, &ie_td, sizeof(ATM_TRAFFIC_DESCRIPTOR_IE)); + + ie_ptr = (Q2931_IE *) ((char *)ie_ptr + ie_ptr->IELength); + ie_ptr->IEType = IE_BroadbandBearerCapability; + ie_ptr->IELength = sizeof( Q2931_IE_TYPE ) + + sizeof( ULONG ) + + sizeof( ATM_BROADBAND_BEARER_CAPABILITY_IE ); + ACE_OS::memcpy(ie_ptr->IE, + &ie_bbc, + sizeof(ATM_BROADBAND_BEARER_CAPABILITY_IE)); + + ie_ptr = (Q2931_IE *) ((char *)ie_ptr + ie_ptr->IELength); + ie_ptr->IEType = IE_QOSClass; + ie_ptr->IELength = sizeof( Q2931_IE_TYPE ) + + sizeof( ULONG ) + + sizeof( ATM_QOS_CLASS_IE ); + ACE_OS::memcpy(ie_ptr->IE, &ie_qos, sizeof(ATM_QOS_CLASS_IE)); + + // qos_.SendingFlowspec.TokenRate = 0xffffffff; + // qos_.SendingFlowspec.TokenBucketSize = 0xffffffff; + // qos_.SendingFlowspec.PeakBandwidth = 0xffffffff; + // qos_.SendingFlowspec.Latency = 0xffffffff; + // qos_.SendingFlowspec.DelayVariation = 0xffffffff; + // qos_.SendingFlowspec.ServiceType = SERVICETYPE_BESTEFFORT; + // This will most probably be ignored by the service provider. + // qos_.SendingFlowspec.MaxSduSize = 0xffffffff; + // qos_.SendingFlowspec.MinimumPolicedSize = 0xffffffff; + + // qos_.ReceivingFlowspec.TokenRate = 0xffffffff; + // qos_.ReceivingFlowspec.TokenBucketSize = 0xffffffff; + // qos_.ReceivingFlowspec.PeakBandwidth = 0xffffffff; + // qos_.ReceivingFlowspec.Latency = 0xffffffff; + // qos_.ReceivingFlowspec.DelayVariation = 0xffffffff; + // qos_.ReceivingFlowspec.ServiceType = SERVICETYPE_BESTEFFORT; + // This will most probably be ignored by the service provider. + // qos_.ReceivingFlowspec.MaxSduSize = 0xffffffff; + // qos_.ReceivingFlowspec.MinimumPolicedSize = 0; + + ACE_Flow_Spec send_fspec( 0xffffffff, + 0xffffffff, + 0xffffffff, + 0xffffffff, + 0xffffffff, + SERVICETYPE_BESTEFFORT, + // This will most probably ignored by SP. + 0xffffffff, + 0xffffffff, + 15, + ACE_DEFAULT_THREAD_PRIORITY ), + recv_fspec( 0xffffffff, + 0xffffffff, + 0xffffffff, + 0xffffffff, + 0xffffffff, + SERVICETYPE_BESTEFFORT, + // This will most probably ignored by SP. + 0xffffffff, + 0, + 15, + ACE_DEFAULT_THREAD_PRIORITY ); + + qos_.sending_flowspec (send_fspec); + qos_.receiving_flowspec (recv_fspec); +#elif defined (ACE_HAS_FORE_ATM_XTI) + ACE_UNUSED_ARG (rate); + ACE_UNUSED_ARG (pktSize); +#elif defined (ACE_HAS_LINUX_ATM) + ACE_OS::memset(&qos_, + 0, + sizeof(qos_)); + qos_.aal = ATM_PROTOCOL_DEFAULT; + qos_.rxtp.max_sdu = pktSize; + + if (rate > 0) { + qos_.rxtp.pcr = rate; + qos_.rxtp.traffic_class = ATM_CBR; + qos_.txtp.traffic_class = ATM_CBR; + qos_.txtp.pcr = rate; + } + else { + qos_.rxtp.traffic_class = ATM_UBR; + qos_.txtp.traffic_class = ATM_UBR; + } + + qos_.txtp.max_sdu = pktSize; +#else + ACE_UNUSED_ARG (rate); +#endif /* ACE_HAS_FORE_ATM_WS2 || ACE_HAS_FORE_ATM_XTI || ACE_HAS_LINUX_ATM */ +} + +void +ACE_ATM_QoS::set_cbr_rate (int rate, + int pktSize) +{ + ACE_TRACE ("ACE_ATM_QoS::set_cbr_rate"); +#if defined (ACE_HAS_FORE_ATM_WS2) + /* + AAL_PARAMETERS_IE ie_aalparams; + ATM_TRAFFIC_DESCRIPTOR_IE ie_td; + ATM_BROADBAND_BEARER_CAPABILITY_IE ie_bbc; + ATM_QOS_CLASS_IE ie_qos; + Q2931_IE *ie_ptr; + int size; + */ + + ACE_OS::printf( "ATM_QoS(set_cbr_rate): set rate to %d c/s\n", rate ); + + // Setting up cbr parameters ... + /* + FORE has changed this - we no longer specify QoS this way + ie_aalparams.AALType = AALTYPE_5; + ie_aalparams.AALSpecificParameters.AAL5Parameters.ForwardMaxCPCSSDUSize + = pktSize; // was 1516; + ie_aalparams.AALSpecificParameters.AAL5Parameters.BackwardMaxCPCSSDUSize + = pktSize; // was 1516; + ie_aalparams.AALSpecificParameters.AAL5Parameters.Mode = AAL5_MODE_MESSAGE; + ie_aalparams.AALSpecificParameters.AAL5Parameters.SSCSType = AAL5_SSCS_NULL; + + size = sizeof(Q2931_IE_TYPE) + sizeof(ULONG) + sizeof(AAL_PARAMETERS_IE); + + ie_td.Forward.PeakCellRate_CLP0 = SAP_FIELD_ABSENT; + ie_td.Forward.PeakCellRate_CLP01 = rate; + ie_td.Forward.SustainableCellRate_CLP0 = SAP_FIELD_ABSENT; + ie_td.Forward.SustainableCellRate_CLP01 = SAP_FIELD_ABSENT; + ie_td.Forward.MaxBurstSize_CLP0 = SAP_FIELD_ABSENT; + ie_td.Forward.MaxBurstSize_CLP01 = SAP_FIELD_ABSENT; + ie_td.Forward.Tagging = SAP_FIELD_ABSENT; + + ie_td.Backward.PeakCellRate_CLP0 = SAP_FIELD_ABSENT; + ie_td.Backward.PeakCellRate_CLP01 = rate; + ie_td.Backward.SustainableCellRate_CLP0 = SAP_FIELD_ABSENT; + ie_td.Backward.SustainableCellRate_CLP01 = SAP_FIELD_ABSENT; + ie_td.Backward.MaxBurstSize_CLP0 = SAP_FIELD_ABSENT; + ie_td.Backward.MaxBurstSize_CLP01 = SAP_FIELD_ABSENT; + ie_td.Backward.Tagging = SAP_FIELD_ABSENT; + + ie_td.BestEffort = 0; // Note: this must be set to zero for CBR. + + size += sizeof( Q2931_IE_TYPE ) + + sizeof( ULONG ) + + sizeof( ATM_TRAFFIC_DESCRIPTOR_IE ); + + ie_bbc.BearerClass = BCOB_X; + ie_bbc.TrafficType = TT_CBR; + ie_bbc.TimingRequirements = TR_END_TO_END; + ie_bbc.ClippingSusceptability = CLIP_NOT; + ie_bbc.UserPlaneConnectionConfig = UP_P2P; + + size += sizeof(Q2931_IE_TYPE) + + sizeof(ULONG) + + sizeof(ATM_BROADBAND_BEARER_CAPABILITY_IE); + + ie_qos.QOSClassForward = QOS_CLASS1; + ie_qos.QOSClassBackward = QOS_CLASS1; // This may not be really used + // since we only simplex data xfer. + + size += sizeof(Q2931_IE_TYPE) + sizeof(ULONG) + sizeof(ATM_QOS_CLASS_IE); + + qos_.ProviderSpecific.buf = (char *) ACE_OS::malloc(size); + if (qos_.ProviderSpecific.buf == 0) { + ACE_ERROR((LM_ERROR, + ACE_TEXT ("ACE_ATM_QoS::ACE_ATM_QoS: Unable to allocate %d bytes for qos_.ProviderSpecific.buf\n"), + size)); + return; + } + qos_.ProviderSpecific.len = size; + ACE_OS::memset(qos_.ProviderSpecific.buf, 0, size); + + ie_ptr = (Q2931_IE *) qos_.ProviderSpecific.buf; + ie_ptr->IEType = IE_AALParameters; + ie_ptr->IELength = sizeof( Q2931_IE_TYPE ) + + sizeof( ULONG ) + + sizeof( AAL_PARAMETERS_IE ); + ACE_OS::memcpy(ie_ptr->IE, &ie_aalparams, sizeof(AAL_PARAMETERS_IE)); + + ie_ptr = (Q2931_IE *) ((char *)ie_ptr + ie_ptr->IELength); + ie_ptr->IEType = IE_TrafficDescriptor; + ie_ptr->IELength = sizeof( Q2931_IE_TYPE ) + + sizeof( ULONG ) + + sizeof( ATM_TRAFFIC_DESCRIPTOR_IE ); + ACE_OS::memcpy(ie_ptr->IE, &ie_td, sizeof(ATM_TRAFFIC_DESCRIPTOR_IE)); + + ie_ptr = (Q2931_IE *) ((char *)ie_ptr + ie_ptr->IELength); + ie_ptr->IEType = IE_BroadbandBearerCapability; + ie_ptr->IELength = sizeof( Q2931_IE_TYPE ) + + sizeof( ULONG ) + + sizeof( ATM_BROADBAND_BEARER_CAPABILITY_IE ); + ACE_OS::memcpy( ie_ptr->IE, + &ie_bbc, + sizeof( ATM_BROADBAND_BEARER_CAPABILITY_IE )); + + ie_ptr = (Q2931_IE *) ((char *)ie_ptr + ie_ptr->IELength); + ie_ptr->IEType = IE_QOSClass; + ie_ptr->IELength = sizeof(Q2931_IE_TYPE) + sizeof(ULONG) + + sizeof(ATM_QOS_CLASS_IE); + ACE_OS::memcpy(ie_ptr->IE, &ie_qos, sizeof(ATM_QOS_CLASS_IE)); + */ + + const int BYTES_PER_ATM_CELL = 53; + ACE_OS::memset(&qos_, 0, sizeof(ATM_QoS)); + // Setting the token rate sets the minimum rate. 3 Mbits/sec seems too high. + // Certainly for Vaudeville audio, we only need about 1000 c/s which is + // 424000 bits/sec which is 53000 bytes/sec. + //qos_.SendingFlowspec.TokenRate = 3*(1024*128); // 3Mbits/sec + qos_.SendingFlowspec.TokenRate = 53000; // 1000 cells/sec + qos_.SendingFlowspec.TokenBucketSize = 32*1024; // our block size + //ourQos.SendingFlowspec.PeakBandwidth = ourQos.SendingFlowspec.TokenRate; + qos_.SendingFlowspec.ServiceType = SERVICETYPE_GUARANTEED; + // Peak bandwidth is in bytes/sec. The rate is specified in cells/sec so + // we need to convert from cells/sec to bytes/sec (i.e., multiply by 53). + qos_.SendingFlowspec.PeakBandwidth = rate * BYTES_PER_ATM_CELL; + qos_.SendingFlowspec.Latency = -1; // we don't care too much + qos_.SendingFlowspec.DelayVariation = -1; // we don't care too much + // no provider-specific data allowed on ATM + qos_.ProviderSpecific.buf=0; + qos_.ProviderSpecific.len=0; + // unidirectional P2MP; we don't need to setup the Receiving flowspec + + //qos_.SendingFlowspec.TokenRate = 0xffffffff; + //qos_.SendingFlowspec.TokenBucketSize = 0xffffffff; + //qos_.SendingFlowspec.PeakBandwidth = 0xffffffff; + //qos_.SendingFlowspec.Latency = 0xffffffff; + //qos_.SendingFlowspec.DelayVariation = 0xffffffff; + //qos_.SendingFlowspec.ServiceType = SERVICETYPE_BESTEFFORT; + // This will most probably be ignored by the service provider. + //qos_.SendingFlowspec.MaxSduSize = 0xffffffff; + //qos_.SendingFlowspec.MinimumPolicedSize = 0xffffffff; + + //qos_.ReceivingFlowspec.TokenRate = 0xffffffff; + //qos_.ReceivingFlowspec.TokenBucketSize = 0xffffffff; + //qos_.ReceivingFlowspec.PeakBandwidth = 0xffffffff; + //qos_.ReceivingFlowspec.Latency = 0xffffffff; + //qos_.ReceivingFlowspec.DelayVariation = 0xffffffff; + //qos_.ReceivingFlowspec.ServiceType = SERVICETYPE_BESTEFFORT; + // This will most probably be ignored by the service provider. + //qos_.ReceivingFlowspec.MaxSduSize = 0xffffffff; + //qos_.ReceivingFlowspec.MinimumPolicedSize = 0; + + /* + ACE_Flow_Spec send_fspec( 0xffffffff, + 0xffffffff, + 0xffffffff, + 0xffffffff, + 0xffffffff, + SERVICETYPE_BESTEFFORT, + // This will most probably ignored by SP. + 0xffffffff, + 0xffffffff, + 15, + ACE_DEFAULT_THREAD_PRIORITY ), + recv_fspec( 0xffffffff, + 0xffffffff, + 0xffffffff, + 0xffffffff, + 0xffffffff, + SERVICETYPE_BESTEFFORT, + // This will most probably ignored by SP. + 0xffffffff, + 0, + 15, + ACE_DEFAULT_THREAD_PRIORITY ); + + qos_.sending_flowspec( send_fspec ); + qos_.receiving_flowspec( recv_fspec ); + */ +#elif defined (ACE_HAS_FORE_ATM_XTI) + ACE_UNUSED_ARG (rate); + ACE_UNUSED_ARG (pktSize); +#elif defined (ACE_HAS_LINUX_ATM) + ACE_UNUSED_ARG (pktSize); + + qos_.rxtp.traffic_class = ATM_CBR; + qos_.rxtp.pcr = rate; + qos_.txtp.traffic_class = ATM_CBR; + qos_.txtp.pcr = rate; +#else + ACE_UNUSED_ARG (rate); +#endif /* ACE_HAS_FORE_ATM_WS2 || ACE_HAS_FORE_ATM_XTI || ACE_HAS_LINUX_ATM */ +} + +void +ACE_ATM_QoS::set_rate (ACE_HANDLE fd, + int rate, + int flags) +{ + ACE_TRACE ("ACE_ATM_QoS::set_rate"); +#if defined (ACE_HAS_FORE_ATM_WS2) || defined (ACE_HAS_LINUX_ATM) + set_cbr_rate( rate ); + + ACE_UNUSED_ARG( fd ); + ACE_UNUSED_ARG( flags ); +#elif defined (ACE_HAS_FORE_ATM_XTI) + long optlen = 0; + qos_.buf = construct_options(fd, + rate, + flags, + &optlen); + qos_.len = optlen; +#else + ACE_UNUSED_ARG (rate); +#endif /* ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM || ACE_HAS_FORE_ATM_XTI */ +} + +char* +ACE_ATM_QoS::construct_options (ACE_HANDLE fd, + int rate, + int flags, + long *len) +{ +#if defined (ACE_HAS_FORE_ATM_WS2) || defined (ACE_HAS_LINUX_ATM) + ACE_UNUSED_ARG (fd); + ACE_UNUSED_ARG (rate); + ACE_UNUSED_ARG (flags); + ACE_UNUSED_ARG (len); + return 0; +#elif defined (ACE_HAS_FORE_ATM_XTI) + struct t_opthdr *popt; + char *buf; + int qos_cells; + struct t_info info; + + if (ACE_OS::t_getinfo (fd, &info) == -1) + { + ACE_OS::t_error ("t_getinfo"); + return 0; + } + + buf = (char *) ACE_OS::malloc (info.options); + + if (buf == 0) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("Unable to allocate %d bytes for options\n"), + info.options), + 0); + + popt = (struct t_opthdr *) buf; + + if (flags & OPT_FLAGS_CPID) + { + // This constructs the T_ATM_ORIG_ADDR option, which is used to + // signal the UNI 3.1 Calling Party ID Information Element. + t_atm_addr *source_addr; + + popt->len = sizeof (struct t_opthdr) + sizeof (t_atm_addr); + popt->level = T_ATM_SIGNALING; + popt->name = T_ATM_ORIG_ADDR; + popt->status = 0; + + source_addr = + (t_atm_addr *)((char *) popt + sizeof (struct t_opthdr)); + + source_addr->address_format = T_ATM_ENDSYS_ADDR; + source_addr->address_length = ATMNSAP_ADDR_LEN; + + ATMSAPAddress local_addr; + struct t_bind boundaddr; + + boundaddr.addr.maxlen = sizeof(local_addr); + boundaddr.addr.buf = (char *) &local_addr; + + //if (ACE_OS::t_getprotaddr(fd, &boundaddr, 0) < 0) { + if (ACE_OS::t_getname(fd, + &boundaddr.addr, + LOCALNAME) < 0) + { + ACE_OS::t_error("t_getname (local_address)"); + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("Can't get local address!\n"))); + ACE_OS::free (buf); + return 0; + } + + ACE_OS::memcpy(source_addr->address, + local_addr.sap.t_atm_sap_addr.address, + ATMNSAP_ADDR_LEN); + + popt = T_OPT_NEXTHDR (buf, info.options , popt); + } + + // This constructs all options necessary (bearer cap., QoS, and + // Traffic Descriptor) to signal for a CBR connection with the + // specified QoS in kbit/sec., and/or specify a PMP connection. + + // For FORE 200e cards, the adapter shapes traffic to CBR with rate + // equal to PCR CLP=0+1 (traffic.forward.PCR_all_traffic) + + qos_cells = (rate * 1000) / (48*8); + + if ((qos_cells > 0 && qos_cells < LINE_RATE) + || (ACE_BIT_ENABLED (flags, OPT_FLAGS_PMP))) + { + struct t_atm_bearer *bearer; + struct t_atm_traffic *traffic; + + // T_ATM_BEARER_CAP: Broadband bearer capability + popt->len = sizeof (struct t_opthdr) + sizeof (struct t_atm_bearer); + popt->level = T_ATM_SIGNALING; + popt->name = T_ATM_BEARER_CAP; + popt->status = 0; + + bearer = (struct t_atm_bearer *)((char *) popt + + sizeof (struct t_opthdr)); + bearer->bearer_class = T_ATM_CLASS_X; + + if (qos_cells) + { + bearer->traffic_type = T_ATM_CBR; + bearer->timing_requirements = T_ATM_END_TO_END; + } + else + { + bearer->traffic_type = 0; // UBR + bearer->timing_requirements = 0; + } + bearer->clipping_susceptibility = T_ATM_NULL; + + if (ACE_BIT_ENABLED (flags, OPT_FLAGS_PMP)) + bearer->connection_configuration = T_ATM_1_TO_MANY; + else + bearer->connection_configuration = T_ATM_1_TO_1; + + popt = T_OPT_NEXTHDR (buf, info.options, popt); + + // T_ATM_TRAFFIC: traffic descriptor + popt->len = sizeof (struct t_opthdr) + sizeof (struct t_atm_traffic); + popt->level = T_ATM_SIGNALING; + popt->name = T_ATM_TRAFFIC; + popt->status = 0; + + traffic = (struct t_atm_traffic *)((char *) popt + + sizeof (struct t_opthdr)); + + traffic->forward.PCR_high_priority = T_ATM_ABSENT; + traffic->forward.PCR_all_traffic = qos_cells ? qos_cells : LINE_RATE; + traffic->forward.SCR_high_priority = T_ATM_ABSENT; + traffic->forward.SCR_all_traffic = T_ATM_ABSENT; + traffic->forward.MBS_high_priority = T_ATM_ABSENT; + traffic->forward.MBS_all_traffic = T_ATM_ABSENT; + traffic->forward.tagging = T_NO; + + traffic->backward.PCR_high_priority = T_ATM_ABSENT; + traffic->backward.PCR_all_traffic = + (ACE_BIT_ENABLED (flags, OPT_FLAGS_PMP)) + ? 0 : qos_cells ? qos_cells : LINE_RATE; + traffic->backward.SCR_high_priority = T_ATM_ABSENT; + traffic->backward.SCR_all_traffic = T_ATM_ABSENT; + traffic->backward.MBS_high_priority = T_ATM_ABSENT; + traffic->backward.MBS_all_traffic = T_ATM_ABSENT; + traffic->backward.tagging = T_NO; + + traffic->best_effort = qos_cells ? T_NO : T_YES; + + popt = T_OPT_NEXTHDR (buf, + info.options, + popt); + } + + if (qos_cells > 0 && qos_cells < LINE_RATE) + { + struct t_atm_qos *qos; + + // T_ATM_QOS: Quality of Service + popt->len = sizeof (struct t_opthdr) + sizeof (struct t_atm_qos); + popt->level = T_ATM_SIGNALING; + popt->name = T_ATM_QOS; + popt->status = 0; + + qos = (struct t_atm_qos *)((char *) popt + sizeof (struct t_opthdr)); + qos->coding_standard = T_ATM_ITU_CODING; + qos->forward.qos_class = T_ATM_QOS_CLASS_1; + qos->backward.qos_class = T_ATM_QOS_CLASS_1; + + popt = T_OPT_NEXTHDR (buf, info.options, popt); + } + + // Return actual size of options and option buffer to user. + *len = (char *) popt - buf; + + return buf; +#else + ACE_UNUSED_ARG (fd); + ACE_UNUSED_ARG (rate); + ACE_UNUSED_ARG (flag); + ACE_UNUSED_ARG (len); + return 0; +#endif /* ACE_HAS_FORE_ATM_WS2 */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_ATM */ + diff --git a/dep/acelite/ace/ATM_QoS.h b/dep/acelite/ace/ATM_QoS.h new file mode 100644 index 00000000000..4e35f3fddb4 --- /dev/null +++ b/dep/acelite/ace/ATM_QoS.h @@ -0,0 +1,115 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file ATM_QoS.h + * + * $Id: ATM_QoS.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Joe Hoffert + */ +//========================================================================== + + +#ifndef ACE_ATM_QoS_H +#define ACE_ATM_QoS_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined(ACE_LACKS_PRAGMA_ONCE) +#pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_ATM) + +#if defined (ACE_HAS_FORE_ATM_WS2) +ACE_BEGIN_VERSIONED_NAMESPACE_DECL +// just map to WS2 GQOS struct +typedef ACE_QoS ATM_QoS; +ACE_END_VERSIONED_NAMESPACE_DECL +#elif defined (ACE_HAS_FORE_ATM_XTI) +ACE_BEGIN_VERSIONED_NAMESPACE_DECL +typedef struct netbuf ATM_QoS; +ACE_END_VERSIONED_NAMESPACE_DECL +#elif defined (ACE_HAS_LINUX_ATM) +#include /**/ "atm.h" +#include "ace/ATM_Params.h" +ACE_BEGIN_VERSIONED_NAMESPACE_DECL +typedef struct atm_qos ATM_QoS; +ACE_END_VERSIONED_NAMESPACE_DECL +#else +ACE_BEGIN_VERSIONED_NAMESPACE_DECL +typedef int ATM_QoS; +ACE_END_VERSIONED_NAMESPACE_DECL +#endif /* ACE_HAS_FORE_ATM_WS2 || ACE_HAS_FORE_ATM_XTI || ACE_HAS_LINUX_ATM */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_ATM_QoS + * + * @brief Define the QoS parameters for ATM + * + * This class wraps up QoS parameters for both ATM/XTI and + * ATM/WinSock2 to make the mechanism for the ATM protocol + * transparent. + */ +class ACE_Export ACE_ATM_QoS +{ +public: + // Constants used for ATM options + static const long LINE_RATE; + static const int OPT_FLAGS_CPID; + static const int OPT_FLAGS_PMP; + static const int DEFAULT_SELECTOR; + static const int DEFAULT_PKT_SIZE; + + // = Initializattion and termination methods. + /// Default constructor. + ACE_ATM_QoS(int = DEFAULT_PKT_SIZE); + + /// Constructor with a CBR rate. + ACE_ATM_QoS(int, + int = DEFAULT_PKT_SIZE); + + ~ACE_ATM_QoS (); + + /// Set the rate. + void set_rate (ACE_HANDLE, + int, + int); + + /// Set CBR rate in cells per second. + void set_cbr_rate (int, + int = DEFAULT_PKT_SIZE); + + /// Get ATM_QoS struct. + ATM_QoS get_qos (void); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + /// Construct QoS options. + char* construct_options(ACE_HANDLE, + int, + int, + long*); + +private: + ATM_QoS qos_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/ATM_QoS.inl" +#endif /* __ACE_INLINE__ */ + +#endif /* ACE_HAS_ATM */ +#include /**/ "ace/post.h" +#endif /* ACE_ATM_QoS_H */ diff --git a/dep/acelite/ace/ATM_QoS.inl b/dep/acelite/ace/ATM_QoS.inl new file mode 100644 index 00000000000..52b5211190d --- /dev/null +++ b/dep/acelite/ace/ATM_QoS.inl @@ -0,0 +1,29 @@ +// -*- C++ -*- +// +// $Id: ATM_QoS.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE void +ACE_ATM_QoS::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_ATM_QoS::dump"); +#endif /* ACE_HAS_DUMP */ +} + +ACE_INLINE +ACE_ATM_QoS::~ACE_ATM_QoS () +{ + ACE_TRACE ("ACE_ATM_QoS::~ACE_ATM_QoS"); +} + +ACE_INLINE +ATM_QoS +ACE_ATM_QoS::get_qos (void) +{ + ACE_TRACE ("ACE_ATM_QoS::get_qos"); + return qos_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/ATM_Stream.cpp b/dep/acelite/ace/ATM_Stream.cpp new file mode 100644 index 00000000000..a9dc0461fa2 --- /dev/null +++ b/dep/acelite/ace/ATM_Stream.cpp @@ -0,0 +1,290 @@ +// $Id: ATM_Stream.cpp 84262 2009-01-29 10:34:33Z johnnyw $ + +#include "ace/ATM_Stream.h" + +ACE_RCSID (ace, ATM_Stream, "$Id: ATM_Stream.cpp 84262 2009-01-29 10:34:33Z johnnyw $") + +#if defined (ACE_HAS_ATM) + +#if !defined (__ACE_INLINE__) +#include "ace/ATM_Stream.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE (ACE_ATM_Stream) + +char* +ACE_ATM_Stream::get_peer_name (void) const +{ + ACE_TRACE ("ACE_ATM_Stream::get_peer_name"); +#if defined (ACE_HAS_FORE_ATM_XTI) + // // Use t_getprotaddr for XTI/ATM + // struct t_bind *localaddr + // = (struct t_bind *) ACE_OS::t_alloc (get_handle (), + // T_BIND, + // T_ADDR); + // struct t_bind *peeraddr + // = (struct t_bind *) ACE_OS::t_alloc (get_handle (), + // T_BIND, + // T_ADDR); + // ::t_getprotaddr (get_handle (), + // localaddr, + // peeraddr); + + // char* connected_name = (char*) ACE_OS::malloc (peeraddr->addr.len + 1); + // ACE_OS::strcpy (connected_name, + // peeraddr->addr.buf); + // ACE_OS::t_free ((char *) localaddr, + // T_BIND); + // ACE_OS::t_free ((char *) peeraddr, + // T_BIND); + // return (connected_name); + +#error "This doesn't seem to work. May need to jimmy-rig something with the" +#error "/etc/xti_hosts file - Ugh!" + + ACE_ATM_Addr sa; + struct netbuf name; + name.maxlen = sa.get_size (); + name.buf = (char *) sa.get_addr (); + ACE_OS::t_getname (this->get_handle (), &name, REMOTENAME); + // ACE_OS::ioctl (this->get_handle (), + // TI_GETPEERNAME, + // &name); + return (name.buf); + +#elif defined (ACE_HAS_FORE_ATM_WS2) + // Use getpeername for WinSock2. + struct sockaddr_atm name; + ACE_OS::memset (&name, 0, sizeof (name)); + int nameSize = sizeof (name); + + if (ACE_OS::getpeername (this->get_handle (), + (struct sockaddr *) &name, + &nameSize) != 0) { + return 0; + } + + char buffer[256]; + for (unsigned int index = 0; index < ATM_ADDR_SIZE - 1; index++) { + buffer[ index * 3 ] = '\0'; + ACE_OS::sprintf (buffer, "%s%02x.", buffer, name.satm_number.Addr[ index ]); + } + buffer[ (ATM_ADDR_SIZE - 1) * 3 ] = '\0'; + ACE_OS::sprintf (buffer, "%s%02x.", buffer, 0); + buffer[ ATM_ADDR_SIZE * 3 - 1 ] = '\0'; + for (index = 0; index < ACE_OS::strlen (buffer); ++index) + buffer[index] = ACE_OS::ace_tolower (buffer[index]); + + ifstream atm_hosts ("C:/WINNT/atmhosts"); + assert (atm_hosts.is_open ()); + + // Find the host address in the ATM hosts file and return the + // host name + char line[256]; + char *host_ptr, *host_name = 0; + ACE_NEW_RETURN (host_name, char[256], 0); + while (!atm_hosts.eof ()) { + atm_hosts.getline (line, 256); + // Convert the line to lower case to ease comparison + for (index = 0; index < ACE_OS::strlen (line); ++index) + line[index] = ACE_OS::ace_tolower (line[index]); + if (ACE_OS::strstr (line, buffer) != 0) + { + char *strtok_p; + // Grab the second token which is the host name + ACE_OS::strtok_r (line, " \t", &strtok_p); + host_ptr = ACE_OS::strtok (0, " \t", &strtok_p); + ACE_OS::strcpy (host_name, host_ptr); + break; + } + } + + return host_name; +#elif defined (ACE_HAS_LINUX_ATM) + ATM_Addr name; + int nameSize = sizeof (name.sockaddratmsvc); + + if (ACE_OS::getpeername (this->get_handle (), + (struct sockaddr *) & (name.sockaddratmsvc), + &nameSize) < 0) { + ACE_OS::perror ("ACE_ATM_Stream (get_peer_name) : "); + return 0; + } + + static ACE_TCHAR buffer[MAX_ATM_ADDR_LEN + 1]; + int total_len; + if ((total_len = atm2text (buffer,sizeof buffer, + (struct sockaddr *) & (name.sockaddratmsvc), + A2T_PRETTY|A2T_NAME)) < 0) { + ACE_DEBUG ((LM_DEBUG,ACE_TEXT ("ACE_ATM_Stream (get_peer_name) :%d"),errno)); + return 0; + } + + return (char*) buffer; +#else + return 0; +#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ +} + +ACE_HANDLE +ACE_ATM_Stream::get_handle (void) const +{ + ACE_TRACE ("ACE_ATM_Stream::get_handle"); +#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2) || defined (ACE_HAS_LINUX_ATM) + return stream_.get_handle (); +#else + return 0; +#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ +} + +int +ACE_ATM_Stream::get_vpi_vci (ACE_UINT16 &vpi, + ACE_UINT16 &vci) const +{ + ACE_TRACE ("ACE_ATM_Stream::get_vpi_vci"); +#if defined (ACE_HAS_FORE_ATM_XTI) + struct t_atm_conn_prop conn_prop; + char* connect_opts = (char *) &conn_prop; + int opt_size = sizeof (t_atm_conn_prop); + struct t_info info; + struct t_optmgmt opt_req, opt_ret; + + if (ACE_OS::t_getinfo (stream_.get_handle (), + &info) < 0) + { + ACE_OS::t_error ("t_getinfo"); + return -1; + } + + char *buf_req = (char *) ACE_OS::malloc (info.options); + if (buf_req == 0) + { + ACE_OS::fprintf (stderr, + "Unable to allocate %ld bytes for options\n", + info.options); + return -1; + } + + char *buf_ret = (char *) ACE_OS::malloc (info.options); + if (buf_ret == 0) + { + ACE_OS::fprintf (stderr, + "Unable to allocate %ld bytes for options\n", + info.options); + return -1; + } + + ACE_OS::memset (&opt_req, 0, sizeof (opt_req)); + ACE_OS::memset (&opt_ret, 0, sizeof (opt_ret)); + + struct t_opthdr *popt = (struct t_opthdr *) buf_req; + struct t_opthdr *popt_ret = (struct t_opthdr *) buf_ret; + + popt->len= sizeof (struct t_opthdr) + opt_size; + + // We are only concerned with SVCs so no other check or values are needed + // here. + popt->level = T_ATM_SIGNALING; + popt->name = T_ATM_CONN_PROP; + popt->status = 0; + + opt_req.opt.len = popt->len; + opt_req.opt.buf = (char *) popt; + opt_req.flags = T_CURRENT; + + popt = T_OPT_NEXTHDR (buf_req, + info.options, + popt); + opt_ret.opt.maxlen = info.options; + opt_ret.opt.buf = (char *) popt_ret; + + if (ACE_OS::t_optmgmt (stream_.get_handle (), + &opt_req, + &opt_ret) < 0) { + ACE_OS::t_error ("t_optmgmt"); + return -1; + } + + ACE_OS::memcpy (connect_opts, + (char *) popt_ret + sizeof (struct t_opthdr), + opt_size); + + ACE_OS::free (buf_ret); + ACE_OS::free (buf_req); + + vpi = conn_prop.vpi; + vci = conn_prop.vci; + return 0; +#elif defined (ACE_HAS_FORE_ATM_WS2) + ATM_CONNECTION_ID connID; + DWORD bytes = 0; + + if (::WSAIoctl ((int) this -> get_handle (), + SIO_GET_ATM_CONNECTION_ID, + 0, + 0, + (LPVOID) &connID, + sizeof (ATM_CONNECTION_ID), + &bytes, + 0, + 0) + == SOCKET_ERROR) { + ACE_OS::printf ("Error: WSAIoctl %d\n", WSAGetLastError ()); + } + + vpi = (ACE_UINT16) connID.VPI; + vci = (ACE_UINT16) connID.VCI; + + return 0; +#elif defined (ACE_HAS_LINUX_ATM) +#if defined (SO_ATMPVC) /* atm version>=0.62 */ + struct sockaddr_atmpvc mypvcaddr; + int addrpvclen = sizeof (mypvcaddr); + if (ACE_OS::getsockopt (stream_.get_handle (), + SOL_ATM, + SO_ATMPVC, + reinterpret_cast (&mypvcaddr), + &addrpvclen) < 0) { + ACE_DEBUG (LM_DEBUG, + ACE_TEXT ("ACE_ATM_Stream::get_vpi_vci: getsockopt %d\n"), + errno); + return -1; + } + vpi = (ACE_UINT16) mypvcaddr.sap_addr.vpi; + vci = (ACE_UINT16) mypvcaddr.sap_addr.vci; + + return 0; +#elif defined (SO_VCID) /* patch for atm version 0.59 */ + struct atm_vcid mypvcid; + int pvcidlen = sizeof (mypvcid); + if (ACE_OS::getsockopt (stream_.get_handle (), + SOL_ATM,SO_VCID, + reinterpret_cast (&mypvcid), + &pvcidlen) < 0) { + ACE_DEBUG (LM_DEBUG, + ACE_TEXT ("ACE_ATM_Stream::get_vpi_vci: getsockopt %d\n"), + errno); + return -1; + } + vpi = (ACE_UINT16) mypvcid.vpi; + vci = (ACE_UINT16) mypvcid.vci; + + return 0; +#else + ACE_DEBUG (LM_DEBUG, + ACE_TEXT ("ACE_ATM_Stream::get_vpi_vci: Not implemented in this ATM version. Update to >= 0.62\n Or patch 0.59")); + ACE_UNUSED_ARG (vci); + ACE_UNUSED_ARG (vpi); + + return -1; +#endif /* SO_ATMPVC || SO_VCID */ +#else + return -1; +#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_ATM */ diff --git a/dep/acelite/ace/ATM_Stream.h b/dep/acelite/ace/ATM_Stream.h new file mode 100644 index 00000000000..41ffb0da32e --- /dev/null +++ b/dep/acelite/ace/ATM_Stream.h @@ -0,0 +1,107 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file ATM_Stream.h + * + * $Id: ATM_Stream.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Joe Hoffert + */ +//============================================================================= + + +#ifndef ACE_ATM_STREAM_H +#define ACE_ATM_STREAM_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_ATM) + +#include "ace/ATM_Addr.h" +#include "ace/ATM_Params.h" + +#if defined (ACE_WIN32) +#include "ace/SOCK_Stream.h" +ACE_BEGIN_VERSIONED_NAMESPACE_DECL +typedef ACE_SOCK_Stream ATM_Stream; +ACE_END_VERSIONED_NAMESPACE_DECL +#else +#include "ace/TLI_Stream.h" +ACE_BEGIN_VERSIONED_NAMESPACE_DECL +typedef ACE_TLI_Stream ATM_Stream; +ACE_END_VERSIONED_NAMESPACE_DECL +#endif + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_ATM_Stream + * + * @brief Defines the member functions for ACE_ATM_Stream abstraction. + */ +class ACE_Export ACE_ATM_Stream +{ +public: + // = Initialization and termination methods. + /// Default constructor. + ACE_ATM_Stream (void); + + // = ATM-specific open and shutdown operations. + /// open the stream. + int open (ACE_ATM_Params params = ACE_ATM_Params()); + + /// Close down and release resources. + int close (void); + + /// Get the underlying handle. + ACE_HANDLE get_handle (void) const; + + /// Get the underlying stream. + ATM_Stream& get_stream (void); + + /// Get the name of the connected host. + char* get_peer_name (void) const; + + /// Get the VPI and VCI of the stream. + int get_vpi_vci (ACE_UINT16 &vpi, + ACE_UINT16 &vci) const; + + /// Recv an n byte buffer from the connected transport mechanism. + ssize_t recv (void *buf, + size_t n, + int *flags = 0) const; + + /// Send exactly n bytes to the connected transport mechanism. + ssize_t send_n (const void *buf, + size_t n, + int flags) const; + + // = Meta-type info + typedef ACE_ATM_Addr PEER_ADDR; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + /// Typedef'd to the appropriate stream mechanism above. + ATM_Stream stream_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/ATM_Stream.inl" +#endif /* __ACE_INLINE__ */ + +#endif /* ACE_HAS_ATM */ +#include /**/ "ace/post.h" +#endif /* ACE_ATM_STREAM_H */ diff --git a/dep/acelite/ace/ATM_Stream.inl b/dep/acelite/ace/ATM_Stream.inl new file mode 100644 index 00000000000..007e25832a5 --- /dev/null +++ b/dep/acelite/ace/ATM_Stream.inl @@ -0,0 +1,133 @@ +// -*- C++ -*- +// +// $Id: ATM_Stream.inl 84262 2009-01-29 10:34:33Z johnnyw $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE void +ACE_ATM_Stream::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_ATM_Stream::dump"); +#endif /* ACE_HAS_DUMP */ +} + +ACE_INLINE +ACE_ATM_Stream::ACE_ATM_Stream (void) +{ + ACE_TRACE ("ACE_ATM_Stream::ACE_ATM_Stream"); +} + +ACE_INLINE +int +ACE_ATM_Stream::open (ACE_ATM_Params params) +{ + ACE_TRACE ("ACE_ATM_Stream::open"); +#if defined (ACE_HAS_FORE_ATM_XTI) + ACE_HANDLE handle = stream_.open (params.get_device(), + params.get_oflag(), + params.get_info()); + return (handle == ACE_INVALID_HANDLE ? -1 : 0); +#elif defined (ACE_HAS_FORE_ATM_WS2) + params.set_flags( ACE_FLAG_MULTIPOINT_C_ROOT | ACE_FLAG_MULTIPOINT_D_ROOT ); + + int retval = stream_.open (params.get_type(), + params.get_protocol_family(), + params.get_protocol(), + params.get_protocol_info(), + params.get_sock_group(), + params.get_flags(), + params.get_reuse_addr()); + if (retval == -1) + return -1; + + struct sockaddr_atm sock_addr; + + ACE_OS::memset(&sock_addr, 0, sizeof(struct sockaddr_atm)); + sock_addr.satm_family = AF_ATM; + sock_addr.satm_number.AddressType=ADDR_ANY; + sock_addr.satm_number.NumofDigits = ATM_ADDR_SIZE; + sock_addr.satm_blli.Layer2Protocol = SAP_FIELD_ABSENT; + sock_addr.satm_blli.Layer3Protocol = SAP_FIELD_ABSENT; + sock_addr.satm_bhli.HighLayerInfoType = SAP_FIELD_ABSENT; + if (ACE_OS::bind(get_handle(), + (struct sockaddr FAR *)&sock_addr, + sizeof(struct sockaddr_atm)) < 0) + { + ACE_OS::printf("Error binding local address: %d",WSAGetLastError()); + return -1; + } + + return 0; +#else + ACE_UNUSED_ARG(params); + return 0; +#endif /* ACE_HAS_FORE_ATM_XTI */ +} + +ACE_INLINE +int +ACE_ATM_Stream::close (void) +{ + ACE_TRACE ("ACE_ATM_Stream::close"); +#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2) + return stream_.close (); +#else + return 0; +#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 */ +} + +ACE_INLINE +ATM_Stream& +ACE_ATM_Stream::get_stream (void) +{ + ACE_TRACE ("ACE_ATM_Stream::get_stream"); + return stream_; +} + +ACE_INLINE +ssize_t +ACE_ATM_Stream::recv (void *buf, + size_t n, + int *flags) const +{ + ACE_TRACE ("ACE_ATM_Stream::recv"); +#if defined (ACE_HAS_FORE_ATM_XTI) + return stream_.recv (buf, + n, + flags); +#elif defined (ACE_HAS_FORE_ATM_WS2) + return stream_.recv (buf, + n); +#else + ACE_UNUSED_ARG(buf); + ACE_UNUSED_ARG(n); + ACE_UNUSED_ARG(flags); + return 0; +#endif /* ACE_HAS_FORE_ATM_XTI */ +} + +ACE_INLINE +ssize_t +ACE_ATM_Stream::send_n (const void *buf, + size_t n, + int flags) const +{ + ACE_TRACE ("ACE_ATM_Stream::send_n"); +#if defined (ACE_HAS_FORE_ATM_XTI) + return stream_.send_n (buf, + n, + flags); +#elif defined (ACE_HAS_FORE_ATM_WS2) + return stream_.send_n (buf, + n, + flags); +#else + ACE_UNUSED_ARG(buf); + ACE_UNUSED_ARG(n); + ACE_UNUSED_ARG(flags); + return 0; +#endif /* ACE_HAS_FORE_ATM_XTI */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Acceptor.cpp b/dep/acelite/ace/Acceptor.cpp new file mode 100644 index 00000000000..e2e1ad7b8e7 --- /dev/null +++ b/dep/acelite/ace/Acceptor.cpp @@ -0,0 +1,1246 @@ +#ifndef ACE_ACCEPTOR_CPP +#define ACE_ACCEPTOR_CPP + +#include "ace/ACE.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Acceptor.h" +#include "ace/Handle_Set.h" +#include "ace/Svc_Handler.h" +#include "ace/WFMO_Reactor.h" +#include "ace/OS_NS_stdio.h" +#include "ace/OS_NS_string.h" +#include "ace/OS_NS_sys_select.h" + +ACE_RCSID (ace, + Acceptor, + "$Id: Acceptor.cpp 84935 2009-03-22 19:21:58Z schmidt $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Acceptor) + +template void +ACE_Acceptor::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Acceptor::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + this->peer_acceptor_.dump (); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +template +ACE_Acceptor::operator ACE_PEER_ACCEPTOR & () const +{ + ACE_TRACE ("ACE_Acceptor::operator ACE_PEER_ACCEPTOR &"); + return (ACE_PEER_ACCEPTOR &) this->peer_acceptor_; +} + +template ACE_PEER_ACCEPTOR & +ACE_Acceptor::acceptor (void) const +{ + ACE_TRACE ("ACE_Acceptor::acceptor"); + return const_cast (this->peer_acceptor_); +} + +// Returns ACE_HANDLE of the underlying Acceptor_Strategy. + +template ACE_HANDLE +ACE_Acceptor::get_handle (void) const +{ + ACE_TRACE ("ACE_Acceptor::get_handle"); + return this->peer_acceptor_.get_handle (); +} + +// Initialize the appropriate strategies for creation, passive +// connection acceptance, and concurrency, and then register +// with the Reactor and listen for connection requests at the +// designated . + +template int +ACE_Acceptor::open + (const ACE_PEER_ACCEPTOR_ADDR &local_addr, + ACE_Reactor *reactor, + int flags, + int use_select, + int reuse_addr) +{ + ACE_TRACE ("ACE_Acceptor::open"); + this->flags_ = flags; + this->use_select_ = use_select; + this->reuse_addr_ = reuse_addr; + this->peer_acceptor_addr_ = local_addr; + + // Must supply a valid Reactor to Acceptor::open()... + + if (reactor == 0) + { + errno = EINVAL; + return -1; + } + + if (this->peer_acceptor_.open (local_addr, reuse_addr) == -1) + return -1; + + // Set the peer acceptor's handle into non-blocking mode. This is a + // safe-guard against the race condition that can otherwise occur + // between the time when indicates that a passive-mode + // socket handle is "ready" and when we call . During this + // interval, the client can shutdown the connection, in which case, + // the call can hang! + if (this->accept_strategy_->acceptor ().enable (ACE_NONBLOCK) != 0) + return -1; + + // Initialize the concurrency strategy. + + if (con_s == 0) + { + ACE_NEW_RETURN (con_s, + CONCURRENCY_STRATEGY, + -1); + this->delete_concurrency_strategy_ = true; + } + this->concurrency_strategy_ = con_s; + + // Initialize the scheduling strategy. + + if (sch_s == 0) + { + ACE_NEW_RETURN (sch_s, + SCHEDULING_STRATEGY, + -1); + this->delete_scheduling_strategy_ = true; + } + this->scheduling_strategy_ = sch_s; + + this->use_select_ = use_select; + + return this->reactor ()->register_handler + (this, + ACE_Event_Handler::ACCEPT_MASK); +} + +// Simple constructor. + +template +ACE_Strategy_Acceptor::ACE_Strategy_Acceptor + (const ACE_TCHAR service_name[], + const ACE_TCHAR service_description[], + int use_select, + int reuse_addr) + : creation_strategy_ (0), + delete_creation_strategy_ (false), + accept_strategy_ (0), + delete_accept_strategy_ (false), + concurrency_strategy_ (0), + delete_concurrency_strategy_ (false), + scheduling_strategy_ (0), + delete_scheduling_strategy_ (false), + service_name_ (0), + service_description_ (0) +{ + ACE_TRACE ("ACE_Strategy_Acceptor::ACE_Strategy_Acceptor"); + + if (service_name != 0) + ACE_ALLOCATOR (this->service_name_, + ACE_OS::strdup (service_name)); + if (service_description != 0) + ACE_ALLOCATOR (this->service_description_, + ACE_OS::strdup (service_description)); + this->use_select_ = use_select; + this->reuse_addr_ = reuse_addr; +} + +template +ACE_Strategy_Acceptor::ACE_Strategy_Acceptor + (const ACE_PEER_ACCEPTOR_ADDR &addr, + ACE_Reactor *reactor, + ACE_Creation_Strategy *cre_s, + ACE_Accept_Strategy *acc_s, + ACE_Concurrency_Strategy *con_s, + ACE_Scheduling_Strategy *sch_s, + const ACE_TCHAR service_name[], + const ACE_TCHAR service_description[], + int use_select, + int reuse_addr) + : creation_strategy_ (0), + delete_creation_strategy_ (false), + accept_strategy_ (0), + delete_accept_strategy_ (false), + concurrency_strategy_ (0), + delete_concurrency_strategy_ (false), + scheduling_strategy_ (0), + delete_scheduling_strategy_ (false), + service_name_ (0), + service_description_ (0) +{ + ACE_TRACE ("ACE_Strategy_Acceptor::ACE_Strategy_Acceptor"); + + if (this->open (addr, + reactor, + cre_s, + acc_s, + con_s, + sch_s, + service_name, + service_description, + use_select, + reuse_addr) == -1) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_Strategy_Acceptor::ACE_Strategy_Acceptor"))); +} + +// Perform termination activities when is removed from the +// . + +template int +ACE_Strategy_Acceptor::handle_close (ACE_HANDLE, + ACE_Reactor_Mask) +{ + ACE_TRACE ("ACE_Strategy_Acceptor::handle_close"); + // Guard against multiple closes. + if (this->reactor () != 0) + { + ACE_HANDLE handle = this->get_handle (); + + if (this->delete_creation_strategy_) + delete this->creation_strategy_; + this->delete_creation_strategy_ = false; + this->creation_strategy_ = 0; + + if (this->delete_accept_strategy_) + delete this->accept_strategy_; + this->delete_accept_strategy_ = false; + this->accept_strategy_ = 0; + + if (this->delete_concurrency_strategy_) + delete this->concurrency_strategy_; + this->delete_concurrency_strategy_ = false; + this->concurrency_strategy_ = 0; + + if (this->delete_scheduling_strategy_) + delete this->scheduling_strategy_; + this->delete_scheduling_strategy_ = false; + this->scheduling_strategy_ = 0; + + // We must use the obtained *before* we deleted the + // accept_strategy_... + + this->reactor ()->remove_handler + (handle, + ACE_Event_Handler::ACCEPT_MASK | ACE_Event_Handler::DONT_CALL); + + // Set the Reactor to 0 so that we don't try to close down + // again. + this->reactor (0); + } + return 0; +} + +// Bridge method for creating a . The strategy for +// creating a are configured into the Acceptor via it's +// . The default is to create a new +// . However, subclasses can override this strategy to +// perform creation in any way that they like (such as +// creating subclass instances of , using a singleton, +// dynamically linking the handler, etc.). + +template int +ACE_Strategy_Acceptor::make_svc_handler (SVC_HANDLER *&sh) +{ + ACE_TRACE ("ACE_Strategy_Acceptor::make_svc_handler"); + return this->creation_strategy_->make_svc_handler (sh); +} + +// Bridge method for accepting the new connection into the +// . The default behavior delegates to the +// in the Acceptor_Strategy. + +template int +ACE_Strategy_Acceptor::accept_svc_handler + (SVC_HANDLER *svc_handler) +{ + ACE_TRACE ("ACE_Strategy_Acceptor::accept_svc_handler"); + return this->accept_strategy_->accept_svc_handler (svc_handler); +} + +// Bridge method for activating a with the appropriate +// concurrency strategy. The default behavior of this method is to +// activate the SVC_HANDLER by calling its open() method (which allows +// the SVC_HANDLER to define its own concurrency strategy). However, +// subclasses can override this strategy to do more sophisticated +// concurrency activations (such as creating the SVC_HANDLER as an +// "active object" via multi-threading or multi-processing). + +template int +ACE_Strategy_Acceptor::activate_svc_handler + (SVC_HANDLER *svc_handler) +{ + ACE_TRACE ("ACE_Strategy_Acceptor::activate_svc_handler"); + return this->concurrency_strategy_->activate_svc_handler + (svc_handler, + (void *) this); +} + +template +ACE_Strategy_Acceptor::~ACE_Strategy_Acceptor (void) +{ + ACE_TRACE ("ACE_Strategy_Acceptor::~ACE_Strategy_Acceptor"); + ACE_OS::free ((void *) this->service_name_); + ACE_OS::free ((void *) this->service_description_); + this->handle_close (); +} + +// Signal the server to shutdown gracefully. + +template int +ACE_Strategy_Acceptor::handle_signal (int, siginfo_t *, ucontext_t *) +{ + ACE_Reactor::instance()->end_reactor_event_loop (); + return 0; +} + +template int +ACE_Strategy_Acceptor::info (ACE_TCHAR **strp, + size_t length) const +{ + ACE_TRACE ("ACE_Strategy_Acceptor::info"); + + ACE_TCHAR buf[BUFSIZ]; + ACE_TCHAR service_addr_str[BUFSIZ]; + ACE_PEER_ACCEPTOR_ADDR addr; + + if (this->acceptor ().get_local_addr (addr) == -1) + return -1; + else if (addr.addr_to_string (service_addr_str, + sizeof service_addr_str) == -1) + return -1; + + // @@ Should add the protocol in... + ACE_OS::sprintf (buf, + ACE_TEXT ("%s\t %s #%s\n"), + this->service_name_ == 0 + ? ACE_TEXT ("") + : this->service_name_, + service_addr_str, + this->service_description_ == 0 + ? ACE_TEXT ("") + : this->service_description_); + + if (*strp == 0 && (*strp = ACE_OS::strdup (buf)) == 0) + return -1; + else + ACE_OS::strsncpy (*strp, buf, length); + return static_cast (ACE_OS::strlen (buf)); +} + +template int +ACE_Strategy_Acceptor::fini (void) +{ + ACE_TRACE ("ACE_Strategy_Acceptor::fini"); + return this->ACE_Strategy_Acceptor::handle_close (); +} + +ACE_ALLOC_HOOK_DEFINE(ACE_Oneshot_Acceptor) + +template void +ACE_Oneshot_Acceptor::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Oneshot_Acceptor::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nsvc_handler_ = %x"), this->svc_handler_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nrestart_ = %d"), this->restart_)); + this->peer_acceptor_.dump (); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("delete_concurrency_strategy_ = %d"), + delete_concurrency_strategy_)); + this->concurrency_strategy_->dump (); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +template int +ACE_Oneshot_Acceptor::open + (const ACE_PEER_ACCEPTOR_ADDR &local_addr, + ACE_Reactor *reactor, + ACE_Concurrency_Strategy *con_s) +{ + ACE_TRACE ("ACE_Oneshot_Acceptor::open"); + this->reactor (reactor); + + // Initialize the concurrency strategy. + + if (con_s == 0) + { + ACE_NEW_RETURN (con_s, + ACE_Concurrency_Strategy, + -1); + this->delete_concurrency_strategy_ = true; + } + this->concurrency_strategy_ = con_s; + + // Reuse the addr, even if it is already in use...! + return this->peer_acceptor_.open (local_addr, 1); +} + +template +ACE_Oneshot_Acceptor::ACE_Oneshot_Acceptor (void) + : delete_concurrency_strategy_ (false) +{ + ACE_TRACE ("ACE_Oneshot_Acceptor::ACE_Oneshot_Acceptor"); + this->reactor (0); +} + +template +ACE_Oneshot_Acceptor::ACE_Oneshot_Acceptor + (const ACE_PEER_ACCEPTOR_ADDR &local_addr, + ACE_Reactor *reactor, + ACE_Concurrency_Strategy *cs) + : delete_concurrency_strategy_ (false) +{ + ACE_TRACE ("ACE_Oneshot_Acceptor::ACE_Oneshot_Acceptor"); + if (this->open (local_addr, reactor, cs) == -1) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_Oneshot_Acceptor::ACE_Oneshot_Acceptor"))); +} + +template +ACE_Oneshot_Acceptor::~ACE_Oneshot_Acceptor (void) +{ + ACE_TRACE ("ACE_Oneshot_Acceptor::~ACE_Oneshot_Acceptor"); + this->handle_close (); +} + +template int +ACE_Oneshot_Acceptor::close (void) +{ + ACE_TRACE ("ACE_Oneshot_Acceptor::close"); + return this->handle_close (); +} + +template int +ACE_Oneshot_Acceptor::handle_close (ACE_HANDLE, + ACE_Reactor_Mask) +{ + ACE_TRACE ("ACE_Oneshot_Acceptor::handle_close"); + + // Guard against multiple closes. + if (this->delete_concurrency_strategy_) + { + delete this->concurrency_strategy_; + this->delete_concurrency_strategy_ = false; + this->concurrency_strategy_ = 0; + } + // Note that if we aren't actually registered with the + // ACE_Reactor then it's ok for this call to fail... + + if (this->reactor ()) + this->reactor ()->remove_handler + (this, + ACE_Event_Handler::ACCEPT_MASK | ACE_Event_Handler::DONT_CALL); + + if (this->peer_acceptor_.close () == -1) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("close\n"))); + return 0; +} + +template int +ACE_Oneshot_Acceptor::handle_timeout + (const ACE_Time_Value &tv, + const void *arg) +{ + ACE_TRACE ("ACE_Oneshot_Acceptor::handle_timeout"); + errno = ETIME; + + if (this->svc_handler_->handle_timeout (tv, arg) == -1) + this->svc_handler_->handle_close (this->svc_handler_->get_handle (), + ACE_Event_Handler::TIMER_MASK); + + // Since we aren't necessarily registered with the Reactor, don't + // bother to check the return value here... + if (this->reactor ()) + this->reactor ()->remove_handler (this, + ACE_Event_Handler::ACCEPT_MASK); + return 0; +} + +template int +ACE_Oneshot_Acceptor::cancel (void) +{ + ACE_TRACE ("ACE_Oneshot_Acceptor::cancel"); + return this->reactor () && this->reactor ()->cancel_timer (this); +} + +template int +ACE_Oneshot_Acceptor::register_handler + (SVC_HANDLER *svc_handler, + const ACE_Synch_Options &synch_options, + bool restart) +{ + ACE_TRACE ("ACE_Oneshot_Acceptor::register_handler"); + // Can't do this if we don't have a Reactor. + if (this->reactor () == 0) + { + errno = EINVAL; + return -1; + } + else + { + this->svc_handler_ = svc_handler; + this->restart_ = restart; + ACE_Time_Value *tv = (ACE_Time_Value *) synch_options.time_value (); + + if (tv != 0 + && this->reactor ()->schedule_timer (this, + synch_options.arg (), + *tv) == 0) + return -1; + else + return this->reactor ()->register_handler + (this, + ACE_Event_Handler::ACCEPT_MASK); + } +} + +// Bridge method for activating a with the appropriate +// concurrency strategy. The default behavior of this method is to +// activate the SVC_HANDLER by calling its open() method (which allows +// the SVC_HANDLER to define its own concurrency strategy). However, +// subclasses can override this strategy to do more sophisticated +// concurrency activations (such as creating the SVC_HANDLER as an +// "active object" via multi-threading or multi-processing). + +template int +ACE_Oneshot_Acceptor::activate_svc_handler + (SVC_HANDLER *svc_handler) +{ + ACE_TRACE ("ACE_Oneshot_Acceptor::activate_svc_handler"); + return this->concurrency_strategy_->activate_svc_handler + (svc_handler, + (void *) this); +} + +// Factors out the code shared between the and +// methods. + +template int +ACE_Oneshot_Acceptor::shared_accept + (SVC_HANDLER *svc_handler, + ACE_PEER_ACCEPTOR_ADDR *remote_addr, + ACE_Time_Value *timeout, + bool restart, + bool reset_new_handle) +{ + ACE_TRACE ("ACE_Oneshot_Acceptor::shared_accept"); + if (svc_handler == 0) + return -1; + + // Accept connection into the Svc_Handler. + else if (this->peer_acceptor_.accept (svc_handler->peer (), // stream + remote_addr, // remote address + timeout, // timeout + restart, // restart + reset_new_handle // reset new handle + ) == -1) + { + // Check whether we just timed out or whether we failed... + if (!(errno == EWOULDBLOCK || errno == ETIME)) + // Close down handler to avoid memory leaks. + svc_handler->close (CLOSE_DURING_NEW_CONNECTION); + return -1; + } + // Activate the using the designated concurrency + // strategy (note that this method becomes responsible for handling + // errors and freeing up the memory if things go awry...) + else + return this->activate_svc_handler (svc_handler); +} + +// Make a SVC_HANDLER, accept the connection into the SVC_HANDLER, and +// then activate the SVC_HANDLER. Note that SVC_HANDLER::open() +// decides what type of concurrency strategy to use. + +template int +ACE_Oneshot_Acceptor::accept + (SVC_HANDLER *svc_handler, + ACE_PEER_ACCEPTOR_ADDR *remote_addr, + const ACE_Synch_Options &synch_options, + bool restart, + bool reset_new_handle) +{ + ACE_TRACE ("ACE_Oneshot_Acceptor::accept"); + // Note that if timeout == ACE_Time_Value (x, y) where (x > 0 || y > + // 0) then this->connector_.connect() will block synchronously. If + // is set then we don't want this to happen (since we + // want the ACE_Reactor to do the timeout asynchronously). + // Therefore, we'll force this->connector_ to use ACE_Time_Value (0, + // 0) in this case... + + ACE_Time_Value *timeout; + int use_reactor = synch_options[ACE_Synch_Options::USE_REACTOR]; + + if (use_reactor) + timeout = (ACE_Time_Value *) &ACE_Time_Value::zero; + else + timeout = (ACE_Time_Value *) synch_options.time_value (); + + if (this->shared_accept (svc_handler, // stream + remote_addr, // remote address + timeout, // timeout + restart, // restart + reset_new_handle // reset new handler + ) == -1) + { + if (use_reactor && errno == EWOULDBLOCK) + // We couldn't accept right away, so let's wait in the + // . + this->register_handler (svc_handler, + synch_options, + restart); + return -1; + } + return 0; +} + +// Accepts one pending connection from a client (since we're the +// "oneshot" Acceptor). + +template int +ACE_Oneshot_Acceptor::handle_input (ACE_HANDLE) +{ + ACE_TRACE ("ACE_Oneshot_Acceptor::handle_input"); + int result = 0; + + // Cancel any timer that might be pending. + this->cancel (); + + // Try to find out if the implementation of the reactor that we are + // using requires us to reset the event association for the newly + // created handle. This is because the newly created handle will + // inherit the properties of the listen handle, including its event + // associations. + bool const reset_new_handle = this->reactor ()->uses_event_associations (); + + // There is a use-case whereby this object will be gone upon return + // from shared_accept - if the Svc_Handler deletes this Oneshot_Acceptor + // during the shared_accept/activation steps. So, do whatever we need + // to do with this object before calling shared_accept. + if (this->reactor ()) + this->reactor ()->remove_handler + (this, + ACE_Event_Handler::ACCEPT_MASK | ACE_Event_Handler::DONT_CALL); + + if (this->shared_accept (this->svc_handler_, // stream + 0, // remote address + 0, // timeout + this->restart_, // restart + reset_new_handle // reset new handle + ) == -1) + result = -1; + + return result; +} + +// Hook called by the explicit dynamic linking facility. + +template int +ACE_Oneshot_Acceptor::init (int, ACE_TCHAR *[]) +{ + ACE_TRACE ("ACE_Oneshot_Acceptor::init"); + return -1; +} + +template int +ACE_Oneshot_Acceptor::fini (void) +{ + ACE_TRACE ("ACE_Oneshot_Acceptor::fini"); + return this->handle_close (); +} + +template int +ACE_Oneshot_Acceptor::info (ACE_TCHAR **strp, + size_t length) const +{ + ACE_TRACE ("ACE_Oneshot_Acceptor::info"); + ACE_TCHAR buf[BUFSIZ]; + ACE_TCHAR addr_str[BUFSIZ]; + ACE_PEER_ACCEPTOR_ADDR addr; + + if (this->peer_acceptor_.get_local_addr (addr) == -1) + return -1; + else if (addr.addr_to_string (addr_str, sizeof addr_str) == -1) + return -1; + + ACE_OS::sprintf (buf, + ACE_TEXT ("%s\t %s %s"), + ACE_TEXT ("ACE_Oneshot_Acceptor"), + addr_str, + ACE_TEXT ("#oneshot acceptor factory\n")); + + if (*strp == 0 && (*strp = ACE_OS::strdup (buf)) == 0) + return -1; + else + ACE_OS::strsncpy (*strp, buf, length); + return static_cast (ACE_OS::strlen (buf)); +} + +template int +ACE_Oneshot_Acceptor::suspend (void) +{ + ACE_TRACE ("ACE_Oneshot_Acceptor::suspend"); + return this->reactor () && this->reactor ()->suspend_handler (this); +} + +template int +ACE_Oneshot_Acceptor::resume (void) +{ + ACE_TRACE ("ACE_Oneshot_Acceptor::resume"); + return this->reactor () && this->reactor ()->resume_handler (this); +} + +// Returns ACE_HANDLE of the underlying peer_acceptor. + +template ACE_HANDLE +ACE_Oneshot_Acceptor::get_handle (void) const +{ + ACE_TRACE ("ACE_Oneshot_Acceptor::get_handle"); + return this->peer_acceptor_.get_handle (); +} + +template ACE_PEER_ACCEPTOR & +ACE_Oneshot_Acceptor::acceptor (void) const +{ + ACE_TRACE ("ACE_Oneshot_Acceptor::acceptor"); + return (ACE_PEER_ACCEPTOR &) this->peer_acceptor_; +} + +template +ACE_Oneshot_Acceptor::operator ACE_PEER_ACCEPTOR & () const +{ + ACE_TRACE ("ACE_Oneshot_Acceptor::operator ACE_PEER_ACCEPTOR &"); + return (ACE_PEER_ACCEPTOR &) this->peer_acceptor_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_ACCEPTOR_CPP */ diff --git a/dep/acelite/ace/Acceptor.h b/dep/acelite/ace/Acceptor.h new file mode 100644 index 00000000000..64cf488b9d4 --- /dev/null +++ b/dep/acelite/ace/Acceptor.h @@ -0,0 +1,695 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Acceptor.h + * + * $Id: Acceptor.h 88800 2010-02-01 23:18:34Z shuston $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_ACCEPTOR_H +#define ACE_ACCEPTOR_H + +#include /**/ "ace/pre.h" + +#include "ace/Service_Object.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Strategies_T.h" +#include "ace/Synch_Options.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Acceptor + * + * @brief Abstract factory for creating a service handler + * (SVC_HANDLER), accepting into the SVC_HANDLER, and + * activating the SVC_HANDLER. + * + * Implements the basic strategy for passively establishing + * connections with clients. An ACE_Acceptor is parameterized + * by concrete types that conform to the interfaces of + * PEER_ACCEPTOR and SVC_HANDLER. The PEER_ACCEPTOR is + * instantiated with a transport mechanism that passively + * establishes connections. The SVC_HANDLER is instantiated + * with a concrete type that performs the application-specific + * service. An ACE_Acceptor inherits from ACE_Service_Object, + * which in turn inherits from ACE_Event_Handler. This enables + * the ACE_Reactor to dispatch the ACE_Acceptor's handle_input + * method when connection events occur. The handle_input method + * performs the ACE_Acceptor's default creation, connection + * establishment, and service activation strategies. These + * strategies can be overridden by subclasses individually or as + * a group. + */ +template +class ACE_Acceptor : public ACE_Service_Object +{ +public: + + // Useful STL-style traits. + typedef ACE_PEER_ACCEPTOR_ADDR addr_type; + typedef ACE_PEER_ACCEPTOR acceptor_type; + typedef SVC_HANDLER handler_type; + typedef typename SVC_HANDLER::stream_type stream_type; + + /// "Do-nothing" constructor. + ACE_Acceptor (ACE_Reactor * = 0, + int use_select = 1); + + /** + * Open the contained @c PEER_ACCEPTOR object to begin listening, and + * register with the specified reactor for accept events. An + * acceptor can only listen to one port at a time, so make sure to + * @c close() the acceptor before calling @c open() again. + * + * The @c PEER_ACCEPTOR handle is put into non-blocking mode as a + * safeguard against the race condition that can otherwise occur + * between the time when the passive-mode socket handle is "ready" + * and when the actual @c accept() call is made. During this + * interval, the client can shutdown the connection, in which case, + * the @c accept() call can hang. + * + * @param local_addr The address to listen at. + * @param reactor Pointer to the ACE_Reactor instance to register + * this object with. The default is the singleton. + * @param flags Flags to control what mode an accepted socket + * will be put into after it is accepted. The only + * legal value for this argument is @c ACE_NONBLOCK, + * which enables non-blocking mode on the accepted + * peer stream object in @c SVC_HANDLER. The default + * is 0. + * @param use_select Affects behavior when called back by the reactor + * when a connection can be accepted. If non-zero, + * this object will accept all pending connections, + * instead of just the one that triggered the reactor + * callback. Uses ACE_OS::select() internally to + * detect any remaining acceptable connections. + * The default is 1. + * @param reuse_addr Passed to the @c PEER_ACCEPTOR::open() method with + * @p local_addr. Generally used to request that the + * OS allow reuse of the listen port. The default is 1. + */ + ACE_Acceptor (const ACE_PEER_ACCEPTOR_ADDR &local_addr, + ACE_Reactor *reactor = ACE_Reactor::instance (), + int flags = 0, + int use_select = 1, + int reuse_addr = 1); + + /** + * Open the contained @c PEER_ACCEPTOR object to begin listening, and + * register with the specified reactor for accept events. An + * acceptor can only listen to one port at a time, so make sure to + * @c close() the acceptor before calling @c open() again. + * + * The @c PEER_ACCEPTOR handle is put into non-blocking mode as a + * safeguard against the race condition that can otherwise occur + * between the time when the passive-mode socket handle is "ready" + * and when the actual @c accept() call is made. During this + * interval, the client can shutdown the connection, in which case, + * the @c accept() call can hang. + * + * @param local_addr The address to listen at. + * @param reactor Pointer to the ACE_Reactor instance to register + * this object with. The default is the singleton. + * @param flags Flags to control what mode an accepted socket + * will be put into after it is accepted. The only + * legal value for this argument is @c ACE_NONBLOCK, + * which enables non-blocking mode on the accepted + * peer stream object in @c SVC_HANDLER. The default + * is 0. + * @param use_select Affects behavior when called back by the reactor + * when a connection can be accepted. If non-zero, + * this object will accept all pending connections, + * instead of just the one that triggered the reactor + * callback. Uses ACE_OS::select() internally to + * detect any remaining acceptable connections. + * The default is 1. + * @param reuse_addr Passed to the @c PEER_ACCEPTOR::open() method with + * @p local_addr. Generally used to request that the + * OS allow reuse of the listen port. The default is 1. + * + * @retval 0 Success + * @retval -1 Failure, @c errno contains an error code. + */ + virtual int open (const ACE_PEER_ACCEPTOR_ADDR &local_addr, + ACE_Reactor *reactor = ACE_Reactor::instance (), + int flags = 0, + int use_select = 1, + int reuse_addr = 1); + + /// Close down the Acceptor's resources. + virtual ~ACE_Acceptor (void); + + /// Return the underlying PEER_ACCEPTOR object. + virtual operator ACE_PEER_ACCEPTOR &() const; + + /// Return the underlying PEER_ACCEPTOR object. + virtual ACE_PEER_ACCEPTOR &acceptor (void) const; + + /// Returns the listening acceptor's {ACE_HANDLE}. + virtual ACE_HANDLE get_handle (void) const; + + /// Close down the Acceptor + virtual int close (void); + + /// In the event that an accept fails, this method will be called and + /// the return value will be returned from handle_input(). + virtual int handle_accept_error (void); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + // = The following three methods define the Acceptor's strategies + // for creating, accepting, and activating SVC_HANDLER's, + // respectively. + + /** + * Bridge method for creating a SVC_HANDLER. The default is to + * create a new {SVC_HANDLER} if {sh} == 0, else {sh} is unchanged. + * However, subclasses can override this policy to perform + * SVC_HANDLER creation in any way that they like (such as creating + * subclass instances of SVC_HANDLER, using a singleton, dynamically + * linking the handler, etc.). Returns -1 on failure, else 0. + */ + virtual int make_svc_handler (SVC_HANDLER *&sh); + + /** + * Bridge method for accepting the new connection into the + * @a svc_handler. The default behavior delegates to the + * PEER_ACCEPTOR::accept. + */ + virtual int accept_svc_handler (SVC_HANDLER *svc_handler); + + /** + * Bridge method for activating a {svc_handler} with the appropriate + * concurrency strategy. The default behavior of this method is to + * activate the SVC_HANDLER by calling its {open} method (which + * allows the SVC_HANDLER to define its own concurrency strategy). + * However, subclasses can override this strategy to do more + * sophisticated concurrency activations (such as making the + * SVC_HANDLER as an "active object" via multi-threading or + * multi-processing). + */ + virtual int activate_svc_handler (SVC_HANDLER *svc_handler); + + // = Demultiplexing hooks. + /// Perform termination activities when {this} is removed from the + /// {reactor}. + virtual int handle_close (ACE_HANDLE = ACE_INVALID_HANDLE, + ACE_Reactor_Mask = ACE_Event_Handler::ALL_EVENTS_MASK); + + /// Accepts all pending connections from clients, and creates and + /// activates SVC_HANDLERs. + virtual int handle_input (ACE_HANDLE); + + // = Dynamic linking hooks. + /// Default version does no work and returns -1. Must be overloaded + /// by application developer to do anything meaningful. + virtual int init (int argc, ACE_TCHAR *argv[]); + + /// Calls {handle_close}. + virtual int fini (void); + + /// Default version returns address info in {buf}. + virtual int info (ACE_TCHAR **buf, size_t) const; + +public: + // = Service management hooks. + /// This method calls {Reactor::suspend}. + virtual int suspend (void); + + /// This method calls {Reactor::resume}. + virtual int resume (void); + +protected: + /// Concrete factory for accepting connections from clients... + ACE_PEER_ACCEPTOR peer_acceptor_; + + /// Needed to reopen the socket if {accept} fails. + ACE_PEER_ACCEPTOR_ADDR peer_acceptor_addr_; + + /** + * Flags that indicate how {SVC_HANDLER}'s should be initialized + * prior to being activated. Right now, the only flag that is + * processed is {ACE_NONBLOCK}, which enabled non-blocking I/O on + * the {SVC_HANDLER} when it is opened. + */ + int flags_; + + /// Flag that indicates whether it shall use {select} in the + /// {accept}-loop. + int use_select_; + + /// Needed to reopen the socket if {accept} fails. + int reuse_addr_; +}; + +/** + * @class ACE_Strategy_Acceptor + * + * @brief Abstract factory for creating a service handler + * (SVC_HANDLER), accepting into the SVC_HANDLER, and activating + * the SVC_HANDLER. + * + * Implements a flexible and extensible set of strategies for + * passively establishing connections with clients. There are + * three main strategies: (1) creating a SVC_HANDLER, (2) + * passively accepting a new connection from a client into the + * SVC_HANDLER, and (3) activating the SVC_HANDLER with a + * particular concurrency mechanism. + */ +template +class ACE_Strategy_Acceptor + : public ACE_Acceptor +{ +public: + + // Useful STL-style traits. + typedef ACE_Creation_Strategy + creation_strategy_type; + typedef ACE_Accept_Strategy + accept_strategy_type; + typedef ACE_Concurrency_Strategy + concurrency_strategy_type; + typedef ACE_Scheduling_Strategy scheduling_strategy_type; + typedef ACE_Acceptor + base_type; + + // = Define some useful (old style) traits. + typedef ACE_Creation_Strategy CREATION_STRATEGY; + typedef ACE_Accept_Strategy ACCEPT_STRATEGY; + typedef ACE_Concurrency_Strategy CONCURRENCY_STRATEGY; + typedef ACE_Scheduling_Strategy SCHEDULING_STRATEGY; + + /// Default constructor. + ACE_Strategy_Acceptor (const ACE_TCHAR service_name[] = 0, + const ACE_TCHAR service_description[] = 0, + int use_select = 1, + int reuse_addr = 1); + + /** + * Initialize the appropriate strategies for creation, passive + * connection acceptance, and concurrency, and then register {this} + * with the Reactor and listen for connection requests at the + * designated {local_addr}. + */ + ACE_Strategy_Acceptor (const ACE_PEER_ACCEPTOR_ADDR &local_addr, + ACE_Reactor * = ACE_Reactor::instance (), + ACE_Creation_Strategy * = 0, + ACE_Accept_Strategy * = 0, + ACE_Concurrency_Strategy * = 0, + ACE_Scheduling_Strategy * = 0, + const ACE_TCHAR service_name[] = 0, + const ACE_TCHAR service_description[] = 0, + int use_select = 1, + int reuse_addr = 1); + + /** + * Open the contained @c PEER_ACCEPTOR object to begin listening, and + * register with the specified reactor for accept events. + * + * The @c PEER_ACCEPTOR handle is put into non-blocking mode as a + * safeguard against the race condition that can otherwise occur + * between the time when the passive-mode socket handle is "ready" + * and when the actual @c accept call is made. During this + * interval, the client can shutdown the connection, in which case, + * the {accept} call can hang. + * + * @param local_addr The address to listen at. + * @param reactor Pointer to the ACE_Reactor instance to register + * this object with. The default is the singleton. + * @param flags Flags to control what mode an accepted socket + * will be put into after it is accepted. The only + * legal value for this argument is @c ACE_NONBLOCK, + * which enables non-blocking mode on the accepted + * peer stream object in @c SVC_HANDLER. The default + * is 0. + * @param use_select Affects behavior when called back by the reactor + * when a connection can be accepted. If non-zero, + * this object will accept all pending connections, + * instead of just the one that triggered the reactor + * callback. Uses ACE_OS::select() internally to + * detect any remaining acceptable connections. + * The default is 1. + * @param reuse_addr Passed to the @c PEER_ACCEPTOR::open() method with + * @p local_addr. Generally used to request that the + * OS allow reuse of the listen port. The default is 1. + * + * @retval 0 Success + * @retval -1 Failure, @c errno contains an error code. + */ + virtual int open (const ACE_PEER_ACCEPTOR_ADDR &local_addr, + ACE_Reactor *reactor, + int flags = 0, + int use_select = 1, + int reuse_addr = 1); + + /** + * Initialize the appropriate strategies for creation, passive + * connection acceptance, and concurrency, and then register {this} + * with the Reactor and listen for connection requests at the + * designated {local_addr}. + */ + virtual int open (const ACE_PEER_ACCEPTOR_ADDR &, + ACE_Reactor * = ACE_Reactor::instance (), + ACE_Creation_Strategy * = 0, + ACE_Accept_Strategy * =0, + ACE_Concurrency_Strategy * = 0, + ACE_Scheduling_Strategy * = 0, + const ACE_TCHAR *service_name = 0, + const ACE_TCHAR *service_description = 0, + int use_select = 1, + int reuse_addr = 1); + + /// Close down the Strategy_Acceptor's resources. + virtual ~ACE_Strategy_Acceptor (void); + + /// Return the underlying PEER_ACCEPTOR object. + virtual operator ACE_PEER_ACCEPTOR &() const; + + /// Return the underlying PEER_ACCEPTOR object. + virtual ACE_PEER_ACCEPTOR &acceptor (void) const; + + /// Returns the listening acceptor's {ACE_HANDLE}. + virtual ACE_HANDLE get_handle (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + + // = Service management hooks. + + /// This method delegates to the {Scheduling_Strategy}'s {suspend} + /// method. + virtual int suspend (void); + + /// This method delegates to the {Scheduling_Strategy}'s {resume} + /// method. + virtual int resume (void); + +protected: + + /// Calls {handle_close} when dynamically unlinked. + virtual int fini (void); + + /// Default version returns address info in {buf}. + virtual int info (ACE_TCHAR **buf, size_t) const; + + // = The following three methods define the {Acceptor}'s strategies + // for creating, accepting, and activating {SVC_HANDLER}'s, + // respectively. + + /** + * Bridge method for creating a {SVC_HANDLER}. The strategy for + * creating a {SVC_HANDLER} are configured into the Acceptor via + * it's {creation_strategy_}. The default is to create a new + * {SVC_HANDLER} if {sh} == 0, else {sh} is unchanged. However, + * subclasses can override this policy to perform {SVC_HANDLER} + * creation in any way that they like (such as creating subclass + * instances of {SVC_HANDLER}, using a singleton, dynamically + * linking the handler, etc.). Returns -1 on failure, else 0. + */ + virtual int make_svc_handler (SVC_HANDLER *&); + + /** + * Bridge method for accepting the new connection into the + * {SVC_HANDLER}. The default behavior delegates to the + * {PEER_ACCEPTOR::accept} in the {Acceptor_Strategy}. + */ + virtual int accept_svc_handler (SVC_HANDLER *svc_handler); + + /** + * Bridge method for activating a {SVC_HANDLER} with the appropriate + * concurrency strategy. The default behavior of this method is to + * activate the {SVC_HANDLER} by calling its {open} method (which + * allows the {SVC_HANDLER} to define its own concurrency strategy). + * However, subclasses can override this strategy to do more + * sophisticated concurrency activations (such as creating the + * {SVC_HANDLER} as an "active object" via multi-threading or + * multi-processing). + */ + virtual int activate_svc_handler (SVC_HANDLER *svc_handler); + + // = Demultiplexing hooks. + /// Perform termination activities when {this} is removed from the + /// {Reactor}. + virtual int handle_close (ACE_HANDLE = ACE_INVALID_HANDLE, + ACE_Reactor_Mask = ACE_Event_Handler::ALL_EVENTS_MASK); + + /// Handle SIGINT. + virtual int handle_signal (int signum, siginfo_t *, ucontext_t *); + + // = These data members are "logically private" but are put in the + // protected part in case subclasses want to access them. + + // = Strategy objects. + + /// Creation strategy for an Acceptor. + CREATION_STRATEGY *creation_strategy_; + + /// true if {Acceptor} created the creation strategy and thus should + /// delete it, else false. + bool delete_creation_strategy_; + + /// Accept strategy for an {Acceptor}. + ACCEPT_STRATEGY *accept_strategy_; + + /// true if {Acceptor} created the accept strategy and thus should delete + /// it, else false. + bool delete_accept_strategy_; + + /// Concurrency strategy for an {Acceptor}. + CONCURRENCY_STRATEGY *concurrency_strategy_; + + /// true if {Acceptor} created the concurrency strategy and thus should + /// delete it, else false. + bool delete_concurrency_strategy_; + + /// Scheduling strategy for an {Acceptor}. + SCHEDULING_STRATEGY *scheduling_strategy_; + + /// true if {Acceptor} created the scheduling strategy and thus should + /// delete it, else false. + bool delete_scheduling_strategy_; + + // = Service information objects. + + /// Name of the service. + ACE_TCHAR *service_name_; + + /// Description of the service. + ACE_TCHAR *service_description_; + + /// Address that the {Strategy_Acceptor} uses to listen for + /// connections. + ACE_PEER_ACCEPTOR_ADDR service_addr_; +}; + +/** + * @class ACE_Oneshot_Acceptor + * + * @brief Generic factory for passively connecting clients and creating + * exactly one service handler of the type SVC_HANDLER specified in the + * template. + * + * This class works similarly to the regular ACE_Acceptor, but + * with the following differences: + * -# ACE_Oneshot_Acceptor doesn't automatically register itself with the + * ACE_Reactor; the caller is expected to call the accept() method + * directly. Since a later call to accept() may require a reactor, + * the constructor and open() methods both accept an ACE_Reactor pointer + * which is saved in case it's needed in accept(). + * -# ACE_Oneshot_Acceptor doesn't need an ACE_Creation_Strategy (because + * the user supplies the SVC_HANDLER) or an ACE_Accept_Strategy (because + * this class only accepts one connection and then removes all traces of + * itself from the ACE_Reactor if it was registered for asynchronous + * accepts). + * + * The usage model for ACE_Oneshot_Acceptor is: + * - Instantiate an object and establish its local address to listen at. + * This can be accomplished using either the address-accepting constructor + * (but there's no error indication) or the default constructor followed + * by a call to open(). + * - Call the accept() method. This will attempt to accept a connection + * immediately. If there is no immediately available connection to accept, + * behavior is governed by the ACE_Synch_Options argument passed to open(). + */ +template +class ACE_Oneshot_Acceptor : public ACE_Service_Object +{ +public: + + // Useful STL-style traits. + typedef ACE_PEER_ACCEPTOR_ADDR addr_type; + typedef ACE_PEER_ACCEPTOR acceptor_type; + typedef SVC_HANDLER handler_type; + typedef typename SVC_HANDLER::stream_type stream_type; + + /// Constructor. + ACE_Oneshot_Acceptor (void); + + /** + * Initialize the appropriate strategies for concurrency and then + * open the acceptor at the designated @a local_addr. Note + * that unlike ACE_Acceptor and ACE_Strategy_Acceptor, this + * method does NOT register this acceptor with the @a reactor at + * this point -- the @a reactor parameter is saved in case it's + * needed later. + */ + ACE_Oneshot_Acceptor (const ACE_PEER_ACCEPTOR_ADDR &local_addr, + ACE_Reactor *reactor = ACE_Reactor::instance (), + ACE_Concurrency_Strategy * = 0); + + /** + * Initialize the appropriate strategies for concurrency and then + * open the acceptor at the designated @a local_addr. Note + * that unlike ACE_Acceptor and ACE_Strategy_Acceptor, this + * method does NOT register this acceptor with the @a reactor at + * this point -- the @a reactor parameter is saved in case it's + * needed later. + */ + int open (const ACE_PEER_ACCEPTOR_ADDR &, + ACE_Reactor *reactor = ACE_Reactor::instance (), + ACE_Concurrency_Strategy * = 0); + + /// Close down the {Oneshot_Acceptor}. + virtual ~ACE_Oneshot_Acceptor (void); + + // = Explicit factory operation. + /// Create a {SVC_HANDLER}, accept the connection into the + /// {SVC_HANDLER}, and activate the {SVC_HANDLER}. + virtual int accept (SVC_HANDLER * = 0, + ACE_PEER_ACCEPTOR_ADDR *remote_addr = 0, + const ACE_Synch_Options &synch_options = ACE_Synch_Options::defaults, + bool restart = true, + bool reset_new_handle = false); + + /// Cancel a oneshot acceptor that was started asynchronously. + virtual int cancel (void); + + /// Return the underlying {PEER_ACCEPTOR} object. + virtual operator ACE_PEER_ACCEPTOR &() const; + + /// Return the underlying {PEER_ACCEPTOR} object. + virtual ACE_PEER_ACCEPTOR &acceptor (void) const; + + /// Close down the {Oneshot_Acceptor}. + virtual int close (void); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + /** + * Bridge method for activating a {svc_handler} with the appropriate + * concurrency strategy. Default behavior is to activate the + * {SVC_HANDLER} as a "passive object." However, subclasses can + * override this strategy to do more sophisticated concurrency + * activations (such as creating the {SVC_HANDLER} as an "active + * object" via multi-threading or multi-processing). + */ + virtual int activate_svc_handler (SVC_HANDLER *svc_handler); + + /// Factors out the code shared between the {accept} and + /// {handle_input} methods. + int shared_accept (SVC_HANDLER *svc_handler, + ACE_PEER_ACCEPTOR_ADDR *remote_addr, + ACE_Time_Value *timeout, + bool restart, + bool reset_new_handle); + + // = Demultiplexing hooks. + /// Returns the listening acceptor's {ACE_HANDLE}. + virtual ACE_HANDLE get_handle (void) const; + + /// Perform termination activities when {this} is removed from the + /// {reactor}. + virtual int handle_close (ACE_HANDLE = ACE_INVALID_HANDLE, + ACE_Reactor_Mask = ACE_Event_Handler::ALL_EVENTS_MASK); + + /// Accept one connection from a client and activates the + /// SVC_HANDLER. + virtual int handle_input (ACE_HANDLE); + + /// Called when an acceptor times out... + virtual int handle_timeout (const ACE_Time_Value &tv, + const void *arg); + + // = Dynamic linking hooks. + /// Default version does no work and returns -1. Must be overloaded + /// by application developer to do anything meaningful. + virtual int init (int argc, ACE_TCHAR *argv[]); + + /// Default version does no work and returns -1. Must be overloaded + /// by application developer to do anything meaningful. + virtual int fini (void); + + /// Default version returns address info in {buf}. + virtual int info (ACE_TCHAR **, size_t) const; + + // = Service management hooks. + /// Default version does no work and returns -1. Must be overloaded + /// by application developer to do anything meaningful. + virtual int suspend (void); + + /// Default version does no work and returns -1. Must be overloaded + /// by application developer to do anything meaningful. + virtual int resume (void); + +private: + /** + * Insert ourselves into the {ACE_Reactor} so that we can continue + * accepting this connection asynchronously. This method should NOT + * be called by developers directly. + */ + int register_handler (SVC_HANDLER *svc_handler, + const ACE_Synch_Options &options, + bool restart); + + /// Hold the svc_handler_ across asynchrony boundaries. + SVC_HANDLER *svc_handler_; + + /// Hold the restart flag across asynchrony boundaries. + bool restart_; + + /// Factory that establishes connections passively. + ACE_PEER_ACCEPTOR peer_acceptor_; + + /// Concurrency strategy for an Acceptor. + ACE_Concurrency_Strategy *concurrency_strategy_; + + /// true if Acceptor created the concurrency strategy and thus should + /// delete it, else false. + bool delete_concurrency_strategy_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Acceptor.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Acceptor.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" + +#endif /* ACE_ACCEPTOR_H */ diff --git a/dep/acelite/ace/Activation_Queue.cpp b/dep/acelite/ace/Activation_Queue.cpp new file mode 100644 index 00000000000..37be7a46a7a --- /dev/null +++ b/dep/acelite/ace/Activation_Queue.cpp @@ -0,0 +1,138 @@ +#include "ace/Activation_Queue.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Activation_Queue.inl" +#endif /* __ACE_INLINE__ */ + +#include "ace/Log_Msg.h" +#include "ace/Method_Request.h" +#include "ace/Malloc_Base.h" +#include "ace/Time_Value.h" + +ACE_RCSID (ace, + Activation_Queue, + "$Id: Activation_Queue.cpp 84565 2009-02-23 08:20:39Z johnnyw $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +void +ACE_Activation_Queue::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("delete_queue_ = %d\n"), + this->delete_queue_)); + ACE_DEBUG ((LM_INFO, ACE_TEXT ("queue_:\n"))); + if (this->queue_) + this->queue_->dump(); + else + //FUZZ: disable check_for_NULL + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(NULL)\n"))); + //FUZZ: enable check_for_NULL + + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +ACE_Activation_Queue::ACE_Activation_Queue (ACE_Message_Queue *new_queue, + ACE_Allocator *alloc, + ACE_Allocator *db_alloc) + : delete_queue_ (false) + , allocator_(alloc) + , data_block_allocator_(db_alloc) +{ + if (this->allocator_ == 0) + this->allocator_ = ACE_Allocator::instance (); + + if (new_queue) + this->queue_ = new_queue; + else + { + ACE_NEW (this->queue_, + ACE_Message_Queue); + this->delete_queue_ = true; + } +} + +void +ACE_Activation_Queue::queue (ACE_Message_Queue *q) +{ + // Destroy the internal queue if one exist. + if (this->delete_queue_) + { + // Destroy the current queue. + delete this->queue_; + + // Set the flag to false. NOTE that the delete_queue_ flag is a + // flag used to only indicate whether or not if an internal + // ACE_Message_Queue has been created, therefore, it will not + // affect the user if the user decided to replace the queue with + // their own queue no matter how many time they call on this + // function. + this->delete_queue_ = false; + } + + queue_ = q; +} + +ACE_Activation_Queue::~ACE_Activation_Queue (void) +{ + if (this->delete_queue_) + delete this->queue_; +} + +ACE_Method_Request * +ACE_Activation_Queue::dequeue (ACE_Time_Value *tv) +{ + ACE_Message_Block *mb = 0; + + // Dequeue the message. + if (this->queue_->dequeue_head (mb, tv) != -1) + { + // Get the next . + ACE_Method_Request *mr = + reinterpret_cast (mb->base ()); + // Delete the message block. + mb->release (); + return mr; + } + else + return 0; +} + +int +ACE_Activation_Queue::enqueue (ACE_Method_Request *mr, + ACE_Time_Value *tv) +{ + ACE_Message_Block *mb = 0; + + // We pass sizeof (*mr) here so that flow control will work + // correctly. Since we also pass note that no unnecessary + // memory is actually allocated -- just the size field is set. + ACE_NEW_MALLOC_RETURN (mb, + static_cast (this->allocator_->malloc (sizeof (ACE_Message_Block))), + ACE_Message_Block (sizeof (*mr), // size + ACE_Message_Block::MB_DATA, // type + 0, // cont + (char *) mr, // data + 0, // allocator + 0, // locking strategy + mr->priority (), // priority + ACE_Time_Value::zero, // execution time + ACE_Time_Value::max_time, // absolute time of deadline + this->data_block_allocator_, // data_block allocator + this->allocator_), // message_block allocator + -1); + + // Enqueue in priority order. + int const result = this->queue_->enqueue_prio (mb, tv); + + // Free ACE_Message_Block if enqueue_prio failed. + if (result == -1) + ACE_DES_FREE (mb, this->allocator_->free, ACE_Message_Block); + + return result; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Activation_Queue.h b/dep/acelite/ace/Activation_Queue.h new file mode 100644 index 00000000000..ab58eedb586 --- /dev/null +++ b/dep/acelite/ace/Activation_Queue.h @@ -0,0 +1,168 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Activation_Queue.h + * + * $Id: Activation_Queue.h 91066 2010-07-12 11:05:04Z johnnyw $ + * + * @author Andres Kruse + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_ACTIVATION_QUEUE_H +#define ACE_ACTIVATION_QUEUE_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Message_Queue.h" +#include "ace/Copy_Disabled.h" +#include "ace/Condition_Thread_Mutex.h" + +/// Define to be compatible with the terminology in the POSA2 book! +#define ACE_Activation_List ACE_Activation_Queue + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +class ACE_Method_Request; + +/** + * @class ACE_Activation_Queue + * + * @brief + * Reifies a method into a request. Subclasses typically + * represent necessary state and behavior. + * + * Maintains a priority-ordered queue of ACE_Method_Request objects. + * A scheduler class (often derived from ACE_Task) subsequently removes + * each method request and invokes its @c call() method. + * + * This class is discussed in depth in the Active Object chapter + * of POSA2. In that book, it is referred to as an Activation List. + * + * @sa ACE_Method_Request + */ +class ACE_Export ACE_Activation_Queue : private ACE_Copy_Disabled +{ +public: + /// Constructor. + /** + * Initializes a new activation queue. + * + * @param new_queue The activation queue uses an ACE_Message_Queue to + * queue and order the method requests. If this argument + * is 0, a new ACE_Message_Queue is created for this + * object's use and will be deleted when this object is + * destroyed. If a non-zero pointer is supplied, the + * passed object will be used and will not be deleted when + * this object is destroyed. If an ACE_Task is being created + * to act as the scheduler, for instance, its + * ACE_Message_Queue pointer can be passed to this object. + * @param alloc Optional, the allocator to use when allocating + * ACE_Message_Block instances that wrap the method requests + * queued to this activation queue. Defaults to + * ACE_Allocator::instance(). + * @param db_alloc Optional, the allocator to use when allocating + * data blocks for the ACE_Message_Block instances that + * wrap the method requests queued to this activation queue. + * Defaults to ACE_Allocator::instance(). + */ + ACE_Activation_Queue (ACE_Message_Queue *new_queue = 0, + ACE_Allocator *alloc = 0, + ACE_Allocator *db_alloc = 0); + + /// Destructor. + virtual ~ACE_Activation_Queue (void); + + // = Activate Queue operations. + + /// Dequeue the next available ACE_Method_Request. + /** + * @param tv If 0, the method will block until a method request is + * available, else will wait until the absolute time specified + * in the referenced ACE_Time_Value. This method will return, + * earlier, however, if queue is closed, deactivated, or when + * a signal occurs. + * + * @retval Pointer to the dequeued ACE_Method_Request object. + * @retval 0 an error occurs; errno contains further information. If + * the specified timeout elapses, errno will be @c EWOULDBLOCK. + */ + ACE_Method_Request *dequeue (ACE_Time_Value *tv = 0); + + /// Enqueue the ACE_Method_Request in priority order. + /** + * The priority of the method request is obtained via the @c priority() + * method of the queued method request. Priority ordering is determined + * by the ACE_Message_Queue class; 0 is the lowest priority. + * + * @param new_method_request Pointer to the ACE_Method_Request object to + * queue. This object's @c priority() method is called to obtain + * the priority. + * @param tv If 0, the method will block until the method request can + * be queued, else will wait until the absolute time specified + * in the referenced ACE_Time_Value. This method will return, + * earlier, however, if queue is closed, deactivated, or when + * a signal occurs. + * + * @retval >0 The number of method requests on the queue after adding + * the specified request. + * @retval -1 if an error occurs; errno contains further information. If + * the specified timeout elapses, errno will be @c EWOULDBLOCK. + */ + int enqueue (ACE_Method_Request *new_method_request, ACE_Time_Value *tv = 0); + + /// Get the current number of method objects in the queue. + size_t method_count (void) const; + + /// Returns 1 if the queue is empty, 0 otherwise. + int is_empty (void) const; + + /// Returns 1 if the queue is full, 0 otherwise. + int is_full (void) const; + + /// Dump the state of an request. + void dump (void) const; + + /// Get a pointer to the underlying queue. + ACE_Message_Queue *queue (void) const; + + /// Set the pointer to the underlying queue. + void queue (ACE_Message_Queue *q); + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + + /// Stores the Method_Requests. + ACE_Message_Queue *queue_; + + /// Keeps track of whether we need to delete the queue. + bool delete_queue_; + +private: + + /// Allocation strategy of the queue. + ACE_Allocator *allocator_; + + /// Allocation strategy of the message blocks. + ACE_Allocator *data_block_allocator_; + +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Activation_Queue.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_ACTIVATION_QUEUE_H */ diff --git a/dep/acelite/ace/Activation_Queue.inl b/dep/acelite/ace/Activation_Queue.inl new file mode 100644 index 00000000000..4c0ffc049d3 --- /dev/null +++ b/dep/acelite/ace/Activation_Queue.inl @@ -0,0 +1,31 @@ +// -*- C++ -*- +// +// $Id: Activation_Queue.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE size_t +ACE_Activation_Queue::method_count (void) const +{ + return queue_->message_count (); +} + +ACE_INLINE int +ACE_Activation_Queue::is_full (void) const +{ + return queue_->is_full (); +} + +ACE_INLINE int +ACE_Activation_Queue::is_empty (void) const +{ + return queue_->is_empty (); +} + +ACE_INLINE ACE_Message_Queue * +ACE_Activation_Queue::queue (void) const +{ + return queue_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Active_Map_Manager.cpp b/dep/acelite/ace/Active_Map_Manager.cpp new file mode 100644 index 00000000000..6ec891b5d10 --- /dev/null +++ b/dep/acelite/ace/Active_Map_Manager.cpp @@ -0,0 +1,9 @@ +// $Id: Active_Map_Manager.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Active_Map_Manager.h" + +ACE_RCSID(ace, Active_Map_Manager, "$Id: Active_Map_Manager.cpp 80826 2008-03-04 14:51:23Z wotte $") + +#if !defined (__ACE_INLINE__) +#include "ace/Active_Map_Manager.inl" +#endif /* __ACE_INLINE__ */ diff --git a/dep/acelite/ace/Active_Map_Manager.h b/dep/acelite/ace/Active_Map_Manager.h new file mode 100644 index 00000000000..a6c167e5f88 --- /dev/null +++ b/dep/acelite/ace/Active_Map_Manager.h @@ -0,0 +1,116 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file Active_Map_Manager.h + * + * $Id: Active_Map_Manager.h 91066 2010-07-12 11:05:04Z johnnyw $ + * + * @author Irfan Pyarali + */ +//============================================================================= + + +#ifndef ACE_ACTIVE_MAP_MANAGER_H +#define ACE_ACTIVE_MAP_MANAGER_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Basic_Types.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Active_Map_Manager_Key + * + * @brief Key used in the Active Object Map. + * + * This key keeps information of the index and the generation + * count of the slot it represents. Since the index information + * is part of the key, lookups are super fast and predictable, + */ +class ACE_Export ACE_Active_Map_Manager_Key +{ +public: + /// Default constructor. + ACE_Active_Map_Manager_Key (void); + + /** + * Constructor given the @a slot_index and @a slot_generation number. + * This is useful once the user has somehow recovered the + * @a slot_index and @a slot_generation number from the client. + */ + ACE_Active_Map_Manager_Key (ACE_UINT32 slot_index, + ACE_UINT32 slot_generation); + + /// Get the slot_index. + ACE_UINT32 slot_index (void) const; + + /// Set the slot_index. + void slot_index (ACE_UINT32 i); + + /// Get the slot_generation number. + ACE_UINT32 slot_generation (void) const; + + /// Set the slot_generation number. + void slot_generation (ACE_UINT32 g); + + /// Size required to store information about active key. + static size_t size (void); + + /// Recover state of active key from @a data. User must make sure + /// that @a data encoded using the encode() method. + void decode (const void *data); + + /// Encode state of the active key into @a data. @a data must be as + /// big as the value returned from . + void encode (void *data) const; + + /// Compare keys. + bool operator== (const ACE_Active_Map_Manager_Key &rhs) const; + bool operator!= (const ACE_Active_Map_Manager_Key &rhs) const; + + // = This really should be protected but because of template + // friends, they are not. + + /// Increment the slot_generation number. + void increment_slot_generation_count (void); + +private: + + /** + * @brief Data for the Active Object Map Key. + * + * This separate structure makes it easier to manage copying + * the index and the generation to and from the user buffer. + * + */ + struct key_data + { + /// Slot index in the active map. + ACE_UINT32 slot_index_; + + /// Slot generation number of @c slot_index_ slot in the active map. + ACE_UINT32 slot_generation_; + }; + + /// Data for the Active Object Map Key. + key_data key_data_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Active_Map_Manager.inl" +#endif /* __ACE_INLINE__ */ + +// Include the templates here. +#include "ace/Active_Map_Manager_T.h" + +#include /**/ "ace/post.h" +#endif /* ACE_ACTIVE_MAP_MANAGER_H */ diff --git a/dep/acelite/ace/Active_Map_Manager.inl b/dep/acelite/ace/Active_Map_Manager.inl new file mode 100644 index 00000000000..df90ada6a00 --- /dev/null +++ b/dep/acelite/ace/Active_Map_Manager.inl @@ -0,0 +1,95 @@ +// -*- C++ -*- +// +// $Id: Active_Map_Manager.inl 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/OS_NS_string.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE +ACE_Active_Map_Manager_Key::ACE_Active_Map_Manager_Key (void) +{ + // If you change ~0, please change ACE_Map_Manager::free_list_id() + // accordingly. + this->key_data_.slot_index_ = (ACE_UINT32) ~0; + this->key_data_.slot_generation_ = 0; +} + +ACE_INLINE +ACE_Active_Map_Manager_Key::ACE_Active_Map_Manager_Key (ACE_UINT32 slot_index, + ACE_UINT32 slot_generation) +{ + this->key_data_.slot_index_ = slot_index; + this->key_data_.slot_generation_ = slot_generation; +} + +ACE_INLINE ACE_UINT32 +ACE_Active_Map_Manager_Key::slot_index (void) const +{ + return this->key_data_.slot_index_; +} + +ACE_INLINE ACE_UINT32 +ACE_Active_Map_Manager_Key::slot_generation (void) const +{ + return this->key_data_.slot_generation_; +} + +ACE_INLINE bool +ACE_Active_Map_Manager_Key::operator== (const ACE_Active_Map_Manager_Key &rhs) const +{ + return + this->key_data_.slot_index_ == rhs.key_data_.slot_index_ && + this->key_data_.slot_generation_ == rhs.key_data_.slot_generation_; +} + +ACE_INLINE bool +ACE_Active_Map_Manager_Key::operator!= (const ACE_Active_Map_Manager_Key &rhs) const +{ + return !this->operator== (rhs); +} + +ACE_INLINE void +ACE_Active_Map_Manager_Key::slot_index (ACE_UINT32 i) +{ + this->key_data_.slot_index_ = i; +} + +ACE_INLINE void +ACE_Active_Map_Manager_Key::slot_generation (ACE_UINT32 g) +{ + this->key_data_.slot_generation_ = g; +} + +ACE_INLINE void +ACE_Active_Map_Manager_Key::increment_slot_generation_count (void) +{ + ++this->key_data_.slot_generation_; +} + +/* static */ +ACE_INLINE size_t +ACE_Active_Map_Manager_Key::size (void) +{ + return sizeof (ACE_UINT32) + sizeof (ACE_UINT32); +} + +ACE_INLINE void +ACE_Active_Map_Manager_Key::decode (const void *data) +{ + // Copy the information from the user buffer into the key. + ACE_OS::memcpy (&this->key_data_, + data, + sizeof this->key_data_); +} + +ACE_INLINE void +ACE_Active_Map_Manager_Key::encode (void *data) const +{ + // Copy the key data to the user buffer. + ACE_OS::memcpy (data, + &this->key_data_, + sizeof this->key_data_); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Active_Map_Manager_T.cpp b/dep/acelite/ace/Active_Map_Manager_T.cpp new file mode 100644 index 00000000000..732cc295117 --- /dev/null +++ b/dep/acelite/ace/Active_Map_Manager_T.cpp @@ -0,0 +1,22 @@ +// $Id: Active_Map_Manager_T.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#ifndef ACE_ACTIVE_MAP_MANAGER_T_CPP +#define ACE_ACTIVE_MAP_MANAGER_T_CPP + +#include "ace/Active_Map_Manager_T.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (__ACE_INLINE__) +#include "ace/Active_Map_Manager_T.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Active_Map_Manager) + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_ACTIVE_MAP_MANAGER_T_CPP */ diff --git a/dep/acelite/ace/Active_Map_Manager_T.h b/dep/acelite/ace/Active_Map_Manager_T.h new file mode 100644 index 00000000000..80eaada26a1 --- /dev/null +++ b/dep/acelite/ace/Active_Map_Manager_T.h @@ -0,0 +1,211 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file Active_Map_Manager_T.h + * + * $Id: Active_Map_Manager_T.h 84316 2009-02-03 19:46:05Z johnnyw $ + * + * @author Irfan Pyarali + */ +//============================================================================= + + +#ifndef ACE_ACTIVE_MAP_MANAGER_T_H +#define ACE_ACTIVE_MAP_MANAGER_T_H +#include /**/ "ace/pre.h" + +#include "ace/Map_Manager.h" +#include "ace/Active_Map_Manager.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Null_Mutex.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Active_Map_Manager + * + * @brief Define a map abstraction that associates system generated + * keys with user specified values. + * + * Since the key is system generated, searches are very fast and + * take a constant amount of time. + */ +template +class ACE_Active_Map_Manager : public ACE_Map_Manager +{ +public: + + // = Traits. + typedef ACE_Active_Map_Manager_Key key_type; + typedef T mapped_type; + + typedef ACE_Map_Entry ENTRY; + typedef ACE_Map_Iterator ITERATOR; + typedef ACE_Map_Reverse_Iterator REVERSE_ITERATOR; + + typedef ENTRY entry; + typedef ITERATOR iterator; + typedef REVERSE_ITERATOR reverse_iterator; + + // = Initialization and termination methods. + /// Initialize a Active_Map_Manager with the ACE_DEFAULT_MAP_SIZE. + ACE_Active_Map_Manager (ACE_Allocator *alloc = 0); + + /// Initialize a Active_Map_Manager with @a size entries. + ACE_Active_Map_Manager (size_t size, + ACE_Allocator *alloc = 0); + + /// Close down a Active_Map_Manager and release dynamically + /// allocated resources. + ~ACE_Active_Map_Manager (void); + + /// Initialize a Active_Map_Manager with size @a length. + int open (size_t length = ACE_DEFAULT_MAP_SIZE, + ACE_Allocator *alloc = 0); + + /// Close down a Active_Map_Manager and release dynamically + /// allocated resources. + int close (void); + + /// Add @a value to the map, and the corresponding key produced by the + /// Active_Map_Manager is returned through @a key. + int bind (const T &value, + ACE_Active_Map_Manager_Key &key); + + /// Add @a value to the map. The user does not care about the + /// corresponding key produced by the Active_Map_Manager. + int bind (const T &value); + + /** + * Reserves a slot in the internal structure and returns the key and + * a pointer to the value. User should place their @a value into + * @a internal_value. This method is useful in reducing the number + * of copies required in some cases. Note that @a internal_value is + * only a temporary pointer and will change when the map resizes. + * Therefore, the user should use the pointer immediately and not + * hold on to it. + */ + int bind (ACE_Active_Map_Manager_Key &key, + T *&internal_value); + + /// Reassociate @a key with @a value. The function fails if @a key is + /// not in the map. + int rebind (const ACE_Active_Map_Manager_Key &key, + const T &value); + + /** + * Reassociate @a key with @a value, storing the old value into the + * "out" parameter @a old_value. The function fails if @a key is not + * in the map. + */ + int rebind (const ACE_Active_Map_Manager_Key &key, + const T &value, + T &old_value); + + /** + * Reassociate @a key with @a value, storing the old key and value + * into the "out" parameter @a old_key and @a old_value. The function + * fails if @a key is not in the map. + */ + int rebind (const ACE_Active_Map_Manager_Key &key, + const T &value, + ACE_Active_Map_Manager_Key &old_key, + T &old_value); + + /// Locate @a value associated with @a key. + int find (const ACE_Active_Map_Manager_Key &key, + T &value) const; + + /// Is @a key in the map? + int find (const ACE_Active_Map_Manager_Key &key) const; + + /** + * Locate @a value associated with @a key. The value is returned via + * @a internal_value and hence a copy is saved. Note that + * @a internal_value is only a temporary pointer and will change when + * the map resizes. Therefore, the user should use the pointer + * immediately and not hold on to it. + */ + int find (const ACE_Active_Map_Manager_Key &key, + T *&internal_value) const; + + // Creates a key. User should place their @a value into + // <*internal_value>. This method is useful in reducing the number + // of copies required in some cases. + + /// Remove @a key from the map. + int unbind (const ACE_Active_Map_Manager_Key &key); + + /// Remove @a key from the map, and return the @a value associated with + /// @a key. + int unbind (const ACE_Active_Map_Manager_Key &key, + T &value); + + /** + * Locate @a value associated with @a key. The value is returned via + * @a internal_value and hence a copy is saved. Note that + * @a internal_value is only a temporary pointer and will change when + * the map resizes or when this slot is reused. Therefore, the user + * should use the pointer immediately and not hold on to it. + */ + int unbind (const ACE_Active_Map_Manager_Key &key, + T *&internal_value); + + /// Return the current size of the map. + size_t current_size (void) const; + + /// Return the total size of the map. + size_t total_size (void) const; + + /// Returns a key that cannot be found in the map. + static const ACE_Active_Map_Manager_Key npos (void); + + /// Dump the state of an object. + void dump (void) const; + + // = STL styled iterator factory functions. + + /// Return forward iterator. + ACE_Map_Iterator begin (void); + ACE_Map_Iterator end (void); + + /// Return reverse iterator. + ACE_Map_Reverse_Iterator rbegin (void); + ACE_Map_Reverse_Iterator rend (void); + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + + /// Private base class + typedef ACE_Map_Manager ACE_AMM_BASE; + +private: + + // = Disallow these operations. + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Active_Map_Manager &)) + ACE_UNIMPLEMENTED_FUNC (ACE_Active_Map_Manager (const ACE_Active_Map_Manager &)) +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Active_Map_Manager_T.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Active_Map_Manager_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Active_Map_Manager_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" +#endif /* ACE_ACTIVE_MAP_MANAGER_T_H */ diff --git a/dep/acelite/ace/Active_Map_Manager_T.inl b/dep/acelite/ace/Active_Map_Manager_T.inl new file mode 100644 index 00000000000..647b55ebd56 --- /dev/null +++ b/dep/acelite/ace/Active_Map_Manager_T.inl @@ -0,0 +1,311 @@ +// -*- C++ -*- +// +// $Id: Active_Map_Manager_T.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template ACE_INLINE int +ACE_Active_Map_Manager::bind (ACE_Active_Map_Manager_Key &key, + T *&internal_value) +{ + ACE_UINT32 slot_index; + int result = this->next_free (slot_index); + + if (result == 0) + { + // Move from free list to occupied list + this->move_from_free_list_to_occupied_list (slot_index); + + // Reset the key. + this->search_structure_[slot_index].ext_id_.increment_slot_generation_count (); + this->search_structure_[slot_index].ext_id_.slot_index (slot_index); + + // Copy the key for the user. + key = this->search_structure_[slot_index].ext_id_; + + // This is where the user should place the value. + internal_value = &this->search_structure_[slot_index].int_id_; + + // Update the current size. + ++this->cur_size_; + } + + return result; +} + +template ACE_INLINE int +ACE_Active_Map_Manager::bind (const T &value, + ACE_Active_Map_Manager_Key &key) +{ + T *internal_value = 0; + int result = this->bind (key, + internal_value); + + if (result == 0) + { + // Store new value. + *internal_value = value; + } + + return result; +} + +template ACE_INLINE int +ACE_Active_Map_Manager::bind (const T &value) +{ + ACE_Active_Map_Manager_Key key; + return this->bind (value, key); +} + +template ACE_INLINE int +ACE_Active_Map_Manager::find (const ACE_Active_Map_Manager_Key &key, + T *&internal_value) const +{ + ACE_UINT32 slot_index = key.slot_index (); + ACE_UINT32 slot_generation = key.slot_generation (); + + if (slot_index > this->total_size_ || +#if defined (ACE_HAS_LAZY_MAP_MANAGER) + this->search_structure_[slot_index].free_ || +#endif /* ACE_HAS_LAZY_MAP_MANAGER */ + this->search_structure_[slot_index].ext_id_.slot_generation () != slot_generation || + this->search_structure_[slot_index].ext_id_.slot_index () == + (ACE_UINT32)this->free_list_id ()) + { + return -1; + } + else + { + // This is where the user value is. + internal_value = &this->search_structure_[slot_index].int_id_; + } + + return 0; +} + +template ACE_INLINE int +ACE_Active_Map_Manager::find (const ACE_Active_Map_Manager_Key &key) const +{ + T *internal_value = 0; + return this->find (key, + internal_value); +} + +template ACE_INLINE int +ACE_Active_Map_Manager::find (const ACE_Active_Map_Manager_Key &key, + T &value) const +{ + T *internal_value = 0; + int result = this->find (key, + internal_value); + + if (result == 0) + value = *internal_value; + + return result; +} + +template ACE_INLINE int +ACE_Active_Map_Manager::rebind (const ACE_Active_Map_Manager_Key &key, + const T &value) +{ + int result = this->find (key); + + if (result == 0) + { + // Store new value. + this->search_structure_[key.slot_index ()].int_id_ = value; + } + + return result; +} + +template ACE_INLINE int +ACE_Active_Map_Manager::rebind (const ACE_Active_Map_Manager_Key &key, + const T &value, + T &old_value) +{ + int result = this->find (key); + + if (result == 0) + { + // Copy old value. + old_value = this->search_structure_[key.slot_index ()].int_id_; + + // Store new value. + this->search_structure_[key.slot_index ()].int_id_ = value; + } + + return result; +} + +template ACE_INLINE int +ACE_Active_Map_Manager::rebind (const ACE_Active_Map_Manager_Key &key, + const T &value, + ACE_Active_Map_Manager_Key &old_key, + T &old_value) +{ + int result = this->find (key); + + if (result == 0) + { + // Copy old key. + old_key = this->search_structure_[key.slot_index ()].ext_id_; + + // Copy old value. + old_value = this->search_structure_[key.slot_index ()].int_id_; + + // Store new value. + this->search_structure_[key.slot_index ()].int_id_ = value; + } + + return result; +} + +template ACE_INLINE int +ACE_Active_Map_Manager::unbind (const ACE_Active_Map_Manager_Key &key, + T *&internal_value) +{ + int result = this->find (key, + internal_value); + + if (result == 0) + { + ACE_UINT32 slot_index = key.slot_index (); + +#if defined (ACE_HAS_LAZY_MAP_MANAGER) + + // + // In the case of lazy map managers, the movement of free slots + // from the occupied list to the free list is delayed until we + // run out of free slots in the free list. + // + + this->search_structure_[slot_index].free_ = 1; + +#else + + // Move from occupied list to free list. + this->move_from_occupied_list_to_free_list (slot_index); + +#endif /* ACE_HAS_LAZY_MAP_MANAGER */ + + // Reset the slot_index. This will tell us that this entry is free. + this->search_structure_[slot_index].ext_id_.slot_index (this->free_list_id ()); + + // Update the current size. + --this->cur_size_; + } + + return result; +} + +template ACE_INLINE int +ACE_Active_Map_Manager::unbind (const ACE_Active_Map_Manager_Key &key, + T &value) +{ + T *internal_value; + int result = this->unbind (key, + internal_value); + + if (result == 0) + { + // Copy old value. + value = *internal_value; + } + + return result; +} + +template ACE_INLINE int +ACE_Active_Map_Manager::unbind (const ACE_Active_Map_Manager_Key &key) +{ + T *internal_value; + return this->unbind (key, + internal_value); +} + +template ACE_INLINE +ACE_Active_Map_Manager::ACE_Active_Map_Manager (ACE_Allocator *alloc) + : ACE_AMM_BASE (alloc) +{ +} + +template ACE_INLINE +ACE_Active_Map_Manager::ACE_Active_Map_Manager (size_t size, + ACE_Allocator *alloc) + : ACE_AMM_BASE (size, + alloc) +{ +} + +template ACE_INLINE +ACE_Active_Map_Manager::~ACE_Active_Map_Manager (void) +{ +} + +template ACE_INLINE int +ACE_Active_Map_Manager::open (size_t length, + ACE_Allocator *alloc) +{ + return ACE_AMM_BASE::open (length, alloc); +} + +template ACE_INLINE int +ACE_Active_Map_Manager::close (void) +{ + return ACE_AMM_BASE::close (); +} + +template ACE_INLINE size_t +ACE_Active_Map_Manager::current_size (void) const +{ + return ACE_AMM_BASE::current_size (); +} + +template ACE_INLINE size_t +ACE_Active_Map_Manager::total_size (void) const +{ + return ACE_AMM_BASE::total_size (); +} + +/* static */ +template ACE_INLINE const ACE_Active_Map_Manager_Key +ACE_Active_Map_Manager::npos (void) +{ + return ACE_Active_Map_Manager_Key (~0, ~0); +} + +template ACE_INLINE void +ACE_Active_Map_Manager::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_AMM_BASE::dump (); +#endif /* ACE_HAS_DUMP */ +} + +template ACE_Map_Iterator +ACE_Active_Map_Manager::begin (void) +{ + return ACE_AMM_BASE::begin (); +} + +template ACE_INLINE ACE_Map_Iterator +ACE_Active_Map_Manager::end (void) +{ + return ACE_AMM_BASE::end (); +} + +template ACE_INLINE ACE_Map_Reverse_Iterator +ACE_Active_Map_Manager::rbegin (void) +{ + return ACE_AMM_BASE::rbegin (); +} + +template ACE_INLINE ACE_Map_Reverse_Iterator +ACE_Active_Map_Manager::rend (void) +{ + return ACE_AMM_BASE::rend (); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Addr.cpp b/dep/acelite/ace/Addr.cpp new file mode 100644 index 00000000000..af78d91b9ca --- /dev/null +++ b/dep/acelite/ace/Addr.cpp @@ -0,0 +1,71 @@ +// $Id: Addr.cpp 84619 2009-02-26 12:26:16Z johnnyw $ + +#include "ace/Addr.h" + +ACE_RCSID (ace, + Addr, + "$Id: Addr.cpp 84619 2009-02-26 12:26:16Z johnnyw $") + +#if !defined (__ACE_INLINE__) +#include "ace/Addr.inl" +#endif /* __ACE_INLINE__ */ + +#include "ace/Log_Msg.h" +#include "ace/os_include/sys/os_socket.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Note: this object requires static construction and destruction. +/* static */ +const ACE_Addr ACE_Addr::sap_any (AF_ANY, -1); + +ACE_ALLOC_HOOK_DEFINE(ACE_Addr) + + +// Initializes instance variables. Note that 0 is an unspecified +// protocol family type... + +ACE_Addr::ACE_Addr (int type, int size) : + addr_type_ (type), + addr_size_ (size) +{ +} + +ACE_Addr::~ACE_Addr (void) +{ +} + +void * +ACE_Addr::get_addr (void) const +{ + return 0; +} + +void +ACE_Addr::set_addr (void *, int) +{ +} + +// Initializes instance variables. + +void +ACE_Addr::base_set (int type, int size) +{ + this->addr_type_ = type; + this->addr_size_ = size; +} + +void +ACE_Addr::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Addr::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("addr_type_ = %d"), this->addr_type_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\naddr_size_ = %d"), this->addr_size_)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Addr.h b/dep/acelite/ace/Addr.h new file mode 100644 index 00000000000..e58ffe2c0f5 --- /dev/null +++ b/dep/acelite/ace/Addr.h @@ -0,0 +1,103 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Addr.h + * + * $Id: Addr.h 81030 2008-03-20 12:43:29Z johnnyw $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_ADDR_H +#define ACE_ADDR_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Addr + * + * @brief Defines the base class for the "address family independent" + * address format. + */ +class ACE_Export ACE_Addr +{ +public: + // = Initialization and termination methods. + /// Initializes instance variables. + ACE_Addr (int type = -1, int size = -1); + + /// Destructor. + virtual ~ACE_Addr (void); + + // = Get/set the size of the address. + + /// Return the size of the address. + int get_size (void) const; + + /// Sets the size of the address. + void set_size (int size); + + // = Get/set the type of the address. + + /// Get the type of the address. + int get_type (void) const; + + /// Set the type of the address. + void set_type (int type); + + /// Return a pointer to the address. + virtual void *get_addr (void) const; + + /// Set a pointer to the address. + virtual void set_addr (void *, int len); + + // = Equality/inequality tests + /// Check for address equality. + bool operator == (const ACE_Addr &sap) const; + + /// Check for address inequality. + bool operator != (const ACE_Addr &sap) const; + + /// Initializes instance variables. + void base_set (int type, int size); + + /// Wild-card address. + static const ACE_Addr sap_any; + + /// Returns a hash value. This should be overwritten by a subclass + /// that can produce a better hash value. + virtual unsigned long hash (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + /// e.g., AF_UNIX, AF_INET, AF_SPIPE, etc. + int addr_type_; + + /// Number of bytes in the address. + int addr_size_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Addr.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" + +#endif /* ACE_ADDR_H */ diff --git a/dep/acelite/ace/Addr.inl b/dep/acelite/ace/Addr.inl new file mode 100644 index 00000000000..0ff355eaeb7 --- /dev/null +++ b/dep/acelite/ace/Addr.inl @@ -0,0 +1,57 @@ +// -*- C++ -*- +// +// $Id: Addr.inl 87295 2009-11-02 14:45:59Z johnnyw $ + +// Return the address of the address. + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE bool +ACE_Addr::operator == (const ACE_Addr &sap) const +{ + return (sap.addr_type_ == this->addr_type_ && + sap.addr_size_ == this->addr_size_ ); +} + +ACE_INLINE bool +ACE_Addr::operator != (const ACE_Addr &sap) const +{ + return (sap.addr_type_ != this->addr_type_ || + sap.addr_size_ != this->addr_size_ ); +} + +/// Return the size of the address. +ACE_INLINE int +ACE_Addr::get_size (void) const +{ + return this->addr_size_; +} + +/// Sets the size of the address. +ACE_INLINE void +ACE_Addr::set_size (int size) +{ + this->addr_size_ = size; +} + +/// Return the type of the address. +ACE_INLINE int +ACE_Addr::get_type (void) const +{ + return this->addr_type_; +} + +/// Set the type of the address. +ACE_INLINE void +ACE_Addr::set_type (int type) +{ + this->addr_type_ = type; +} + +ACE_INLINE unsigned long +ACE_Addr::hash (void) const +{ + return 0; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Arg_Shifter.cpp b/dep/acelite/ace/Arg_Shifter.cpp new file mode 100644 index 00000000000..5a7182c3423 --- /dev/null +++ b/dep/acelite/ace/Arg_Shifter.cpp @@ -0,0 +1,229 @@ +#ifndef ACE_ARG_SHIFTER_T_CPP +#define ACE_ARG_SHIFTER_T_CPP + +#include "ace/Arg_Shifter.h" +#include "ace/OS_NS_string.h" +#include "ace/OS_NS_strings.h" +#include "ace/OS_Errno.h" +#include "ace/OS_Memory.h" + +ACE_RCSID (ace, + Arg_Shifter, + "$Id: Arg_Shifter.cpp 83749 2008-11-14 18:39:10Z johnnyw $") + + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template +ACE_Arg_Shifter_T::ACE_Arg_Shifter_T (int& argc, + const CHAR_TYPE** argv, + const CHAR_TYPE** temp) + : argc_ (argc), + total_size_ (argc), + temp_ (temp), + argv_ (argv), + current_index_ (0), + back_ (argc - 1), + front_ (0) +{ + this->init (); +} + +template +ACE_Arg_Shifter_T::ACE_Arg_Shifter_T (int& argc, + CHAR_TYPE** argv, + CHAR_TYPE** temp) + : argc_ (argc), + total_size_ (argc), + temp_ ((const CHAR_TYPE **) temp), + argv_ ((const CHAR_TYPE **) argv), + current_index_ (0), + back_ (argc - 1), + front_ (0) +{ + this->init (); +} + +template +void +ACE_Arg_Shifter_T::init (void) +{ + // If not provided with one, allocate a temporary array. + if (this->temp_ == 0) + ACE_NEW (this->temp_, + const CHAR_TYPE *[this->total_size_]); + + if (this->temp_ != 0) + { + // Fill the temporary array. + this->argc_ = 0; + for (int i = 0; i < this->total_size_; i++) + { + this->temp_[i] = this->argv_[i]; + this->argv_[i] = 0; + } + } + else + { + // Allocation failed, prohibit iteration. + this->current_index_ = this->argc_; + this->front_ = this->argc_; + } +} + +template +ACE_Arg_Shifter_T::~ACE_Arg_Shifter_T (void) +{ + // Delete the temporary vector. + delete [] temp_; +} + +template +const CHAR_TYPE * +ACE_Arg_Shifter_T::get_current (void) const +{ + const CHAR_TYPE * retval = 0; + + if (this->is_anything_left ()) + retval = this->temp_[current_index_]; + + return retval; +} + +template +const CHAR_TYPE * +ACE_Arg_Shifter_T::get_the_parameter (const CHAR_TYPE *flag) +{ + // the return 0's abound because this method + // would otherwise be a deep if { } else { } + + // check to see if any arguments still exist + if (!this->is_anything_left()) + return 0; + + // check to see if the flag is the argument + int const offset = this->cur_arg_strncasecmp (flag); + if (offset == -1) + return 0; + + if (offset == 0) + { + this->consume_arg (); + + if (!this->is_parameter_next()) + { + return 0; + } + } + // the parameter is in the middle somewhere... + return this->temp_[current_index_] + offset; +} + +template +int +ACE_Arg_Shifter_T::cur_arg_strncasecmp (const CHAR_TYPE *flag) +{ + // Check for a current argument + if (this->is_anything_left()) + { + size_t const flag_length = ACE_OS::strlen (flag); + + // Check for presence of the flag + if (ACE_OS::strncasecmp(this->temp_[current_index_], + flag, + flag_length) == 0) + { + if (ACE_OS::strlen(temp_[current_index_]) == flag_length) + { + // match and lengths are equal + return 0; + } + else + { + // matches, with more info to boot! + size_t const remaining = ACE_OS::strspn + (this->temp_[current_index_] + flag_length, + ACE_TEXT (" ")) + flag_length; + return static_cast (remaining); + } + } + } + // failure + return -1; +} + +template +int +ACE_Arg_Shifter_T::consume_arg (int number) +{ + int retval = 0; + + // Stick knowns at the end of the vector (consumed). + if (this->is_anything_left() >= number) + { + for (int i = 0, j = this->back_ - (number - 1); + i < number; + ++i, ++j, ++this->current_index_) + this->argv_[j] = this->temp_[this->current_index_]; + + this->back_ -= number; + retval = 1; + } + + return retval; +} + +template +int +ACE_Arg_Shifter_T::ignore_arg (int number) +{ + int retval = 0; + + // Keep unknowns at the head of the vector. + if (this->is_anything_left () >= number) + { + for (int i = 0; + i < number; + i++, this->current_index_++, this->front_++) + this->argv_[this->front_] = this->temp_[this->current_index_]; + + retval = 1; + this->argc_ += number; + } + + return retval; +} + +template +int +ACE_Arg_Shifter_T::is_anything_left (void) const +{ + return this->total_size_ - this->current_index_; +} + +template +int +ACE_Arg_Shifter_T::is_option_next (void) const +{ + return this->is_anything_left () && + this->temp_[this->current_index_][0] == '-'; +} + +template +int +ACE_Arg_Shifter_T::is_parameter_next (void) const +{ + return this->is_anything_left () + && this->temp_[this->current_index_][0] != '-'; +} + +template +int +ACE_Arg_Shifter_T::num_ignored_args (void) const +{ + return this->front_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_ATOMIC_OP_T_CPP */ diff --git a/dep/acelite/ace/Arg_Shifter.h b/dep/acelite/ace/Arg_Shifter.h new file mode 100644 index 00000000000..2e5f0b0f5e7 --- /dev/null +++ b/dep/acelite/ace/Arg_Shifter.h @@ -0,0 +1,221 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Arg_Shifter.h + * + * $Id: Arg_Shifter.h 83891 2008-11-28 11:01:50Z johnnyw $ + * + * @author Seth Widoff + */ +//============================================================================= + +#ifndef ACE_ARG_SHIFTER_H +#define ACE_ARG_SHIFTER_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Global_Macros.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Arg_Shifter_T + * + * @brief This ADT operates on a specified set of arguments (@a argv). + * As known arguments are scanned, they are shifted to the back of the + * @a argv vector, so deeper levels of argument parsing can locate the yet + * unprocessed arguments at the beginning of the vector. + * + * The @c ACE_Arg_Shifter copies the pointers of the @a argv vector + * into a temporary array. As the @c ACE_Arg_Shifter iterates over + * the copied vector, it places known arguments in the rear of the + * vector, leaving the unknown ones in the beginning. So, after having + * visited all the arguments in the temporary vector, @c ACE_Arg_Shifter + * has placed all the unknown arguments in their original order at + * the front of original @a argv. + */ +template +class ACE_Arg_Shifter_T +{ +public: + // = Initialization and termination methods. + /** + * Initialize the ACE_Arg_Shifter to the vector over which to + * iterate. Optionally, also provide the temporary array for + * use in shifting the arguments. If ACE_Arg_Shifter must allocate + * the temporary vector internally and dynamic allocation fails, the + * ACE_Arg_Shifter will set all indicators to end of the vector, + * forbidding iteration. Following iteration over @a argv, the + * @a argc value will be updated to contain the number of + * unconsumed arguments. + * @param argc The number of strings in @a argv. @a argc will be + * updated to reflect the number of unconsumed arguments. + * @param argv The argument vector to shift. The string pointers in + * the vector will be reordered to place the @a argc unconsumed + * arguments at the front of the vector. + * @param temp A vector of @c CHAR_TYPE pointers at least @a argc + * elements long. The vector will be used for argument shifting as + * the specified @a argv vector is consumed. The vector must not + * be modified while this object exists. If this argument is 0 + * (the default) the object will allocate and free the temporary + * vector transparently. + */ + ACE_Arg_Shifter_T (int& argc, + const CHAR_TYPE **argv, + const CHAR_TYPE **temp = 0); + + /// Same behavior as the preceding constructor, but without the + /// "const" qualifier. + ACE_Arg_Shifter_T (int& argc, + CHAR_TYPE **argv, + CHAR_TYPE **temp = 0); + + /// Destructor. + ~ACE_Arg_Shifter_T (void); + + /// Get the current head of the vector. + const CHAR_TYPE *get_current (void) const; + + /** + * If the @a flag matches the current_arg of arg shifter + * this method will attempt to return the associated + * parameter value + * + * Safe to call without checking that a current arg exists + * + * In the following examples, a pointer to the char* "value" is ret + * + * eg: main -foobar value, main -FooBar value + * main -FOOBARvalue + * + * all of the above will all match the @a flag == -FooBar + * and will return a char* to "value" + * + * main -foobar 4 would succeed and return a char* to "4" + * main -foobar -4 does not succeed (-4 is not a parameter) + * but instead, would return 0 + * + * 0 is returned: + * If the current argument does not match flag + * If there is no parameter found after a 'matched' flag + * + * If the flag is matched and the flag and parameter DO NOT RUN + * together, the flag is consumed, the parameter is returned, + * and the new current argument is the parameter value. + * ie '-foobarflag VALUE' leaves the new cur arg == "VALUE" + * + * If the flag is matched and the flag and parameter RUN + * together '-foobarflagVALUE', the flag is NOT consumed + * and the cur arg is left pointing to the entire flag/value pair + */ + const CHAR_TYPE *get_the_parameter (const CHAR_TYPE* flag); + + /** + * Check if the current argument matches (case insensitive) @a flag + * + * ------------------------------------------------------------ + * + * Case A: Perfect Match (case insensitive) + * 0 is returned. + * + * ie: when current_arg = "-foobar" or "-FOOBAR" or "-fooBAR" + * this->cur_arg_strncasecmp ("-FooBar); + * will return 0 + * + * ------------------------------------------------------------ + * + * Case B: Perfect Match (case insensitive) but the current_arg + * is longer than the flag. Returns a number equal to the index + * in the char* indicating the start of the extra characters + * + * ie: when current_arg = "-foobar98023" + * this->cur_arg_strncasecmp ("-FooBar); + * will return 7 + * + * Notice: this number will always be > 0 + * + * ------------------------------------------------------------ + * + * Case C: If neither of Case A or B is met (no match) + * then -1 is returned + */ + int cur_arg_strncasecmp (const CHAR_TYPE *flag); + + /// Consume @a number argument(s) by sticking them/it on the end of + /// the vector. + int consume_arg (int number = 1); + + /// Place @a number arguments in the same relative order ahead of the + /// known arguments in the vector. + int ignore_arg (int number = 1); + + /// Returns the number of args left to see in the vector. + int is_anything_left (void) const; + + /// Returns 1 if there's a next item in the vector and it begins with + /// '-'. + int is_option_next (void) const; + + /// Returns 1 if there's a next item in the vector and it doesn't + /// begin with '-'. + int is_parameter_next (void) const; + + /// Returns the number of irrelevant args seen. + int num_ignored_args (void) const; + +private: + /// Copy Constructor should not be used. + ACE_UNIMPLEMENTED_FUNC (ACE_Arg_Shifter_T (const ACE_Arg_Shifter_T&)) + + /// Assignment '=' operator should not be used. + ACE_UNIMPLEMENTED_FUNC (ACE_Arg_Shifter_T operator= (const ACE_Arg_Shifter_T&)) + + /// Refactor the constructor logic. + void init (void); + + /// The size of the argument vector. + int& argc_; + + /// The size of argv_. + int total_size_; + + /// The temporary array over which we traverse. + const CHAR_TYPE **temp_; + + /// The array in which the arguments are reordered. + const CHAR_TYPE **argv_; + + /// The element in we're currently examining. + int current_index_; + + /// The index of in which we'll stick the next unknown + /// argument. + int back_; + + /// The index of in which we'll stick the next known + /// argument. + int front_; +}; + +typedef ACE_Arg_Shifter_T ACE_Arg_Shifter; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Arg_Shifter.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Arg_Shifter.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" + +#endif /* ACE_ARG_SHIFTER_H */ diff --git a/dep/acelite/ace/Argv_Type_Converter.cpp b/dep/acelite/ace/Argv_Type_Converter.cpp new file mode 100644 index 00000000000..1ebeeb4cc30 --- /dev/null +++ b/dep/acelite/ace/Argv_Type_Converter.cpp @@ -0,0 +1,196 @@ +// $Id: Argv_Type_Converter.cpp 85772 2009-06-23 20:14:18Z mitza $ + +#include "ace/Argv_Type_Converter.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Argv_Type_Converter.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID (ace, + Argv_Type_Converter, + "$Id: Argv_Type_Converter.cpp 85772 2009-06-23 20:14:18Z mitza $") + +#include "ace/OS_NS_string.h" +#include "ace/OS_Errno.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +#if defined (ACE_USES_WCHAR) +ACE_Argv_Type_Converter::ACE_Argv_Type_Converter (int &argc, wchar_t** argv) + : saved_argc_ (argc), + char_argv_ (0), + wchar_argv_ (argv), + before_pass_argc_ (argc), + original_type_ (true), + wchar_passed_ (false), + char_passed_ (false) +{ + this->initialize (); + + for (int i = 0; i < argc; ++i) + this->char_argv_[i] = ACE_OS::strdup (ACE_TEXT_ALWAYS_CHAR (argv[i])); +} +#endif // ACE_USES_WCHAR + + +ACE_Argv_Type_Converter::ACE_Argv_Type_Converter (int &argc, char **argv) + : saved_argc_(argc), + char_argv_(argv) +#if defined (ACE_USES_WCHAR) + , wchar_argv_(0), + before_pass_argc_(argc), + original_type_(false), + wchar_passed_(false), + char_passed_(false) +{ + this->initialize(); + + for (int i = 0; i < argc; ++i) + this->wchar_argv_[i] = ACE_OS::strdup (ACE_TEXT_ANTI_TO_TCHAR (argv[i])); +} +#else +{ +} +#endif // ACE_USES_WCHAR + +ACE_Argv_Type_Converter::~ACE_Argv_Type_Converter (void) +{ +#if defined (ACE_USES_WCHAR) + // selectively delete the 'copy' of argv + if (this->original_type_) + { + // if original type is wchar_t + if (this->char_passed_) + this->align_wchar_with_char (); + + for (int i = 0; i < this->before_pass_argc_; ++i) + ACE_OS::free (this->char_argv_[i]); + + delete [] this->char_argv_; + } + else + { + // if original type is char + if (this->wchar_passed_) + this->align_char_with_wchar (); + + for (int i = 0; i < this->before_pass_argc_; ++i) + ACE_OS::free (this->wchar_argv_[i]); + + delete [] this->wchar_argv_; + } +#endif // ACE_USES_WCHAR +} + +#if defined (ACE_USES_WCHAR) +void +ACE_Argv_Type_Converter::initialize (void) +{ + if (this->original_type_) + { + // Make a copy of argv in 'char'. type Create one more argv entry + // than original argc for the NULL. + ACE_NEW (char_argv_, + char *[this->saved_argc_ + 1]); + this->char_argv_[saved_argc_] = 0; // last entry of argv is + // always a NULL + } + else + { + // make a copy of argv in 'wchar_t' type + ACE_NEW (this->wchar_argv_, + wchar_t*[this->saved_argc_ + 1]); + this->wchar_argv_[saved_argc_] = 0; + } +} + + +void +ACE_Argv_Type_Converter::align_char_with_wchar (void) +{ + for (int wchar_argv_index = 0; wchar_argv_index < this->saved_argc_; + ++wchar_argv_index) + { + wchar_t *match_argv = this->wchar_argv_[wchar_argv_index]; + // if n'th entries of both argv lists are different + if (ACE_OS::strcmp (this->char_argv_[wchar_argv_index], + ACE_TEXT_ALWAYS_CHAR (match_argv)) != 0) + { + // loop through the wchar argv list entries that are after + // wchar_argv_index + for (int i = wchar_argv_index + 1; i < before_pass_argc_; ++i) + { + if (ACE_OS::strcmp (this->char_argv_[i], + ACE_TEXT_ALWAYS_CHAR (match_argv)) == 0) + { + // swap the pointers in the char argv list + char *temp = this->char_argv_[wchar_argv_index]; + this->char_argv_[wchar_argv_index] = this->char_argv_[i]; + this->char_argv_[i] = temp; + break; + } + } + } + } + + this->cleanup (); +} + +void +ACE_Argv_Type_Converter::align_wchar_with_char (void) +{ + for (int char_argv_index = 0; char_argv_index < saved_argc_; + ++char_argv_index) + { + char* match_argv = this->char_argv_[char_argv_index]; + // if n'th entries of both argv lists are different + if (ACE_OS::strcmp ( + ACE_TEXT_ALWAYS_CHAR (this->wchar_argv_[char_argv_index]), + match_argv) != 0) + { + // loop through the wchar argv list entries that are after + // wchar_argv_index + for (int i = char_argv_index + 1; i < this->before_pass_argc_; ++i) + { + if (ACE_OS::strcmp ( + ACE_TEXT_ALWAYS_CHAR(this->wchar_argv_[i]), + match_argv) == 0) { + // swap the pointers in the char argv list + wchar_t* temp = this->wchar_argv_[char_argv_index]; + this->wchar_argv_[char_argv_index] = this->wchar_argv_[i]; + this->wchar_argv_[i] = temp; + break; + } + } + } + } + + this->cleanup(); +} + +void +ACE_Argv_Type_Converter::cleanup (void) +{ + for (int i = this->saved_argc_; i < this->before_pass_argc_; ++i) + { + // Check whether it's ours to delete. + if (original_type_) + { + ACE_OS::free (this->char_argv_[i]); + this->char_argv_[i] = 0; + } + else + { + ACE_OS::free (this->wchar_argv_[i]); + this->wchar_argv_[i] = 0; + } + } + + this->before_pass_argc_ = this->saved_argc_; + + this->wchar_passed_ = false; + this->char_passed_ = false; +} +#endif // ACE_USES_WCHAR + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Argv_Type_Converter.h b/dep/acelite/ace/Argv_Type_Converter.h new file mode 100644 index 00000000000..d41d839b671 --- /dev/null +++ b/dep/acelite/ace/Argv_Type_Converter.h @@ -0,0 +1,119 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Argv_Type_Converter.h + * + * $Id: Argv_Type_Converter.h 83891 2008-11-28 11:01:50Z johnnyw $ + * + * @author Si Mong Park + */ +//============================================================================= + +#ifndef ACE_ARGV_TYPE_CONVERTER_H +#define ACE_ARGV_TYPE_CONVERTER_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" +#include "ace/OS_Memory.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Argv_Type_Converter + * + * @brief To convert 'char' input/command line parameter to 'wchar_t'. + * + * This class is to convert 'char' type command line parameter to + * wide-character (wchar_t) format and stores the copy of it. + * This is useful for all classes that use 'char**' argv but cannot + * be converted into 'ACE_TCHAR**' version. + * Note that the converted data will be lost upon destruction, so + * classes should use this class as their data member. + */ +class ACE_Export ACE_Argv_Type_Converter +{ +public: + + ACE_Argv_Type_Converter (int &argc, char** argv); + +#if defined (ACE_USES_WCHAR) + ACE_Argv_Type_Converter (int &argc, wchar_t** argv); +#endif // ACE_USES_WCHAR + + ~ACE_Argv_Type_Converter (void); + + /// Returns the pointer of converted command line. + ACE_TCHAR** get_TCHAR_argv (void); + + /// Returns the pointer of ASCII (char) command line. + char** get_ASCII_argv (void); + + /// Returns the number of sub parameters (argc). + int& get_argc (void); + +private: + + /// Copy Constructor should not be used. + ACE_Argv_Type_Converter (const ACE_Argv_Type_Converter&); + + /// Assignment '=' operator should not be used. + ACE_Argv_Type_Converter operator= (const ACE_Argv_Type_Converter&); + +#if defined (ACE_USES_WCHAR) + + /// Perform common initialization for two Ctor's. + void initialize (void); + + /// Align all entries in the char type argv list with wchar_t type + /// argv list. + void align_char_with_wchar (void); + + /// Align all entries in the wchar_t type argv list with char type + /// argv list. + void align_wchar_with_char (void); + + /// Clean up removed (comsumed) argv entries and reset the pass flags. + void cleanup (void); +#endif // ACE_USES_WCHAR + +private: + /// Original number of input parameter, same as 'argc'. + int &saved_argc_; + + /// Data member pointer that contains converted argv in ACE_ANTI_TCHAR. + char** char_argv_; + +#if defined (ACE_USES_WCHAR) + /// Data member pointer that contains converted argv in ACE_TCHAR. + wchar_t** wchar_argv_; + + /// argc value before any argv has been passed. + int before_pass_argc_; + + /// false represents original argv passed in is char, and true + /// represents wchar_t. + bool const original_type_; + + /// true indicates wchar_t type argv has been passed. + bool wchar_passed_; + + /// true indicates char type argv has been passed. + bool char_passed_; +#endif /* ACE_USES_WCHAR */ +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Argv_Type_Converter.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" + +#endif /* ACE_ARGV_TYPE_CONVERTER_H */ diff --git a/dep/acelite/ace/Argv_Type_Converter.inl b/dep/acelite/ace/Argv_Type_Converter.inl new file mode 100644 index 00000000000..e4b0ed5a059 --- /dev/null +++ b/dep/acelite/ace/Argv_Type_Converter.inl @@ -0,0 +1,44 @@ +// -*- C++ -*- +// +// $Id: Argv_Type_Converter.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE ACE_TCHAR** +ACE_Argv_Type_Converter::get_TCHAR_argv (void) +{ +#if defined (ACE_USES_WCHAR) + if (this->char_passed_) + { + this->align_wchar_with_char (); + } + + this->wchar_passed_ = true; + return this->wchar_argv_; +#else + return this->char_argv_; +#endif // ACE_USES_WCHAR +} + +ACE_INLINE char** +ACE_Argv_Type_Converter::get_ASCII_argv (void) +{ +#if defined (ACE_USES_WCHAR) + if (this->wchar_passed_) + { + this->align_char_with_wchar (); + } + + this->char_passed_ = true; +#endif // ACE_USES_WCHAR + + return this->char_argv_; +} + +ACE_INLINE int& +ACE_Argv_Type_Converter::get_argc (void) +{ + return this->saved_argc_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Array.h b/dep/acelite/ace/Array.h new file mode 100644 index 00000000000..3caaa7b719b --- /dev/null +++ b/dep/acelite/ace/Array.h @@ -0,0 +1,29 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file Array.h + * + * $Id: Array.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @deprecated + * + * @note This file has been deprecated and will soon go away. You + * should directly include "Containers_T.h" instead. + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_ARRAY_H +#define ACE_ARRAY_H +#include /**/ "ace/pre.h" + +#include "ace/Containers_T.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include /**/ "ace/post.h" +#endif /* ACE_ARRAY_H */ diff --git a/dep/acelite/ace/Array_Base.cpp b/dep/acelite/ace/Array_Base.cpp new file mode 100644 index 00000000000..49e42e1ad98 --- /dev/null +++ b/dep/acelite/ace/Array_Base.cpp @@ -0,0 +1,235 @@ +// $Id: Array_Base.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#ifndef ACE_ARRAY_BASE_CPP +#define ACE_ARRAY_BASE_CPP + +#include "ace/Array_Base.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (__ACE_INLINE__) +#include "ace/Array_Base.inl" +#endif /* __ACE_INLINE__ */ + +#include "ace/Malloc_Base.h" +#include "ace/os_include/os_errno.h" + +#include + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Dynamically initialize an array. +template +ACE_Array_Base::ACE_Array_Base (typename ACE_Array_Base::size_type size, + ACE_Allocator *alloc) + : max_size_ (size), + cur_size_ (size), + allocator_ (alloc) +{ + if (this->allocator_ == 0) + this->allocator_ = ACE_Allocator::instance (); + + if (size != 0) + { + ACE_ALLOCATOR (this->array_, + (T *) this->allocator_->malloc (size * sizeof (T))); + for (size_type i = 0; i < size; ++i) + new (&array_[i]) T; + } + else + this->array_ = 0; +} + +template +ACE_Array_Base::ACE_Array_Base (typename ACE_Array_Base::size_type size, + const T &default_value, + ACE_Allocator *alloc) + : max_size_ (size), + cur_size_ (size), + allocator_ (alloc) +{ + if (this->allocator_ == 0) + this->allocator_ = ACE_Allocator::instance (); + + if (size != 0) + { + ACE_ALLOCATOR (this->array_, + (T *) this->allocator_->malloc (size * sizeof (T))); + for (size_type i = 0; i < size; ++i) + new (&array_[i]) T (default_value); + } + else + this->array_ = 0; +} + +// The copy constructor (performs initialization). + +template +ACE_Array_Base::ACE_Array_Base (const ACE_Array_Base &s) + : max_size_ (s.size ()), + cur_size_ (s.size ()), + allocator_ (s.allocator_) +{ + if (this->allocator_ == 0) + this->allocator_ = ACE_Allocator::instance (); + + ACE_ALLOCATOR (this->array_, + (T *) this->allocator_->malloc (s.size () * sizeof (T))); + for (size_type i = 0; i < this->size (); ++i) + new (&this->array_[i]) T (s.array_[i]); +} + +// Assignment operator (performs assignment). + +template void +ACE_Array_Base::operator= (const ACE_Array_Base &s) +{ + // Check for "self-assignment". + + if (this != &s) + { + if (this->max_size_ < s.size ()) + { + // Need to reallocate memory. + + // Strongly exception-safe assignment. + // + // Note that we're swapping the allocators here, too. + // Should we? Probably. "*this" should be a duplicate of + // the "right hand side". + ACE_Array_Base tmp (s); + this->swap (tmp); + } + else + { + // Underlying array is large enough. No need to reallocate + // memory. + // + // "*this" still owns the memory for the underlying array. + // Do not swap out the allocator. + // + // @@ Why don't we just drop the explicit destructor and + // placement operator new() calls with a straight + // element-by-element assignment? Is the existing + // approach more efficient? + // -Ossama + + ACE_DES_ARRAY_NOFREE (this->array_, + s.size (), + T); + + this->cur_size_ = s.size (); + + for (size_type i = 0; i < this->size (); ++i) + new (&this->array_[i]) T (s.array_[i]); + } + } +} + +// Set an item in the array at location slot. + +template int +ACE_Array_Base::set (const T &new_item, + typename ACE_Array_Base::size_type slot) +{ + if (this->in_range (slot)) + { + this->array_[slot] = new_item; + return 0; + } + else + return -1; +} + +// Get an item in the array at location slot. + +template int +ACE_Array_Base::get (T &item, + typename ACE_Array_Base::size_type slot) const +{ + if (this->in_range (slot)) + { + // Copies the item. If you don't want to copy, use operator [] + // instead (but then you'll be responsible for range checking). + item = this->array_[slot]; + return 0; + } + else + return -1; +} + +template int +ACE_Array_Base::max_size (typename ACE_Array_Base::size_type new_size) +{ + if (new_size > this->max_size_) + { + T *tmp = 0; + + ACE_ALLOCATOR_RETURN (tmp, + (T *) this->allocator_->malloc (new_size * sizeof (T)), + -1); + for (size_type i = 0; i < this->cur_size_; ++i) + new (&tmp[i]) T (this->array_[i]); + + // Initialize the new portion of the array that exceeds the + // previously allocated section. + for (size_type j = this->cur_size_; j < new_size; ++j) + new (&tmp[j]) T; + + ACE_DES_ARRAY_FREE (this->array_, + this->max_size_, + this->allocator_->free, + T); + this->array_ = tmp; + this->max_size_ = new_size; + this->cur_size_ = new_size; + } + + return 0; +} + +template int +ACE_Array_Base::size (typename ACE_Array_Base::size_type new_size) +{ + int const r = this->max_size (new_size); + + if (r == 0) + this->cur_size_ = new_size; + + return r; +} + +template +void +ACE_Array_Base::swap (ACE_Array_Base & rhs) +{ + std::swap (this->max_size_ , rhs.max_size_); + std::swap (this->cur_size_ , rhs.cur_size_); + std::swap (this->array_ , rhs.array_); + std::swap (this->allocator_, rhs.allocator_); +} + +// **************************************************************** + +template int +ACE_Array_Iterator::next (T *&item) +{ + // ACE_TRACE ("ACE_Array_Iterator::next"); + + if (this->done ()) + { + item = 0; + return 0; + } + else + { + item = &array_[current_]; + return 1; + } +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_ARRAY_BASE_CPP */ diff --git a/dep/acelite/ace/Array_Base.h b/dep/acelite/ace/Array_Base.h new file mode 100644 index 00000000000..0d6620a6ca6 --- /dev/null +++ b/dep/acelite/ace/Array_Base.h @@ -0,0 +1,256 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Array_Base.h + * + * $Id: Array_Base.h 84477 2009-02-16 13:30:38Z johnnyw $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_ARRAY_BASE_H +#define ACE_ARRAY_BASE_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Global_Macros.h" +#include "ace/Malloc_Base.h" +#include /* For reverse_iterator adapters */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Forward declaration. +template class ACE_Array_Iterator; + +/** + * @class ACE_Array_Base + * + * @brief Implement a simple dynamic array + * + * This parametric class implements a simple dynamic array; + * resizing must be controlled by the user. No comparison or find + * operations are implemented. + */ +template +class ACE_Array_Base +{ +public: + + // Old/ACE-style traits. + typedef T TYPE; + typedef ACE_Array_Iterator ITERATOR; + + // STL-style typedefs/traits. + typedef T value_type; + typedef value_type * iterator; + typedef value_type const * const_iterator; + typedef value_type & reference; + typedef value_type const & const_reference; + typedef value_type * pointer; + typedef value_type const * const_pointer; + typedef ptrdiff_t difference_type; + typedef ACE_Allocator::size_type size_type; + + ACE_DECLARE_STL_REVERSE_ITERATORS + + // = Initialization and termination methods. + + /// Dynamically create an uninitialized array. + ACE_Array_Base (size_type size = 0, + ACE_Allocator * the_allocator = 0); + + /// Dynamically initialize the entire array to the . + ACE_Array_Base (size_type size, + T const & default_value, + ACE_Allocator * the_allocator = 0); + + /** + * The copy constructor performs initialization by making an exact + * copy of the contents of parameter , i.e., *this == s will + * return true. + */ + ACE_Array_Base (ACE_Array_Base const & s); + + /** + * Assignment operator performs an assignment by making an exact + * copy of the contents of parameter , i.e., *this == s will + * return true. Note that if the of is >= than + * we can copy it without reallocating. However, if + * is < we must delete the , + * reallocate a new , and then copy the contents of . + */ + void operator= (ACE_Array_Base const & s); + + /// Clean up the array (e.g., delete dynamically allocated memory). + ~ACE_Array_Base (void); + + // = Set/get methods. + + /// Set item in the array at location @a slot. Doesn't + /// perform range checking. + T & operator[] (size_type slot); + + /// Get item in the array at location @a slot. Doesn't + /// perform range checking. + T const & operator[] (size_type slot) const; + + /// Set an item in the array at location @a slot. Returns + /// -1 if @a slot is not in range, else returns 0. + int set (T const & new_item, size_type slot); + + /** + * Get an item in the array at location @a slot. Returns -1 if + * @a slot is not in range, else returns 0. Note that this function + * copies the item. If you want to avoid the copy, you can use + * the const operator [], but then you'll be responsible for range checking. + */ + int get (T & item, size_type slot) const; + + /// Returns the of the array. + size_type size (void) const; + + /** + * Changes the size of the array to match @a new_size. + * It copies the old contents into the new array. + * Return -1 on failure. + */ + int size (size_type new_size); + + /// Returns the of the array. + size_type max_size (void) const; + + /** + * Changes the size of the array to match @a new_size. + * It copies the old contents into the new array. + * Return -1 on failure. + * It does not affect new_size + */ + int max_size (size_type new_size); + + /** + * @name Forward Iterator Accessors + * + * Forward iterator accessors. + */ + //@{ + iterator begin (void); + iterator end (void); + const_iterator begin (void) const; + const_iterator end (void) const; + //@} + + /** + * @name Reverse Iterator Accessors + * + * Reverse iterator accessors. + */ + //@{ + reverse_iterator rbegin (void); + reverse_iterator rend (void); + const_reverse_iterator rbegin (void) const; + const_reverse_iterator rend (void) const; + //@} + + /// Swap the contents of this array with the given @a array in + /// an exception-safe manner. + void swap (ACE_Array_Base & array); + +protected: + + /// Returns 1 if @a slot is within range, i.e., 0 >= @a slot < + /// @c cur_size_, else returns 0. + bool in_range (size_type slot) const; + + /// Maximum size of the array, i.e., the total number of @c T elements + /// in @c array_. + size_type max_size_; + + /** + * Current size of the array. This starts out being == to + * . However, if we are assigned a smaller array, then + * will become less than . The purpose of + * keeping track of both sizes is to avoid reallocating memory if we + * don't have to. + */ + size_type cur_size_; + + /// Pointer to the array's storage buffer. + value_type * array_; + + /// Allocation strategy of the ACE_Array_Base. + ACE_Allocator * allocator_; + + friend class ACE_Array_Iterator; +}; + +// **************************************************************** + +/** + * @class ACE_Array_Iterator + * + * @brief Implement an iterator over an ACE_Array. + * + * This iterator is safe in the face of array element deletions. + * But it is NOT safe if the array is resized (via the ACE_Array + * assignment operator) during iteration. That would be very + * odd, and dangerous. + */ +template +class ACE_Array_Iterator +{ +public: + // = Initialization method. + ACE_Array_Iterator (ACE_Array_Base &); + + // = Iteration methods. + + /// Pass back the @a next_item that hasn't been seen in the Array. + /// Returns 0 when all items have been seen, else 1. + int next (T *&next_item); + + /// Move forward by one element in the Array. Returns 0 when all the + /// items in the Array have been seen, else 1. + int advance (void); + + /// Returns 1 when all items have been seen, else 0. + int done (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + /// Pointer to the current item in the iteration. + size_t current_; + + /// Pointer to the Array we're iterating over. + ACE_Array_Base &array_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Array_Base.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Array_Base.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Array_Base.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" + +#endif /* ACE_ARRAY_BASE_H */ diff --git a/dep/acelite/ace/Array_Base.inl b/dep/acelite/ace/Array_Base.inl new file mode 100644 index 00000000000..046c1bffc89 --- /dev/null +++ b/dep/acelite/ace/Array_Base.inl @@ -0,0 +1,146 @@ +// -*- C++ -*- +// +// $Id: Array_Base.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Clean up the array (e.g., delete dynamically allocated memory). +template ACE_INLINE +ACE_Array_Base::~ACE_Array_Base (void) +{ + ACE_DES_ARRAY_FREE (this->array_, + this->max_size_, + this->allocator_->free, + T); +} + +template +ACE_INLINE typename ACE_Array_Base::iterator +ACE_Array_Base::begin (void) +{ + return this->array_; +} + +template +ACE_INLINE typename ACE_Array_Base::iterator +ACE_Array_Base::end (void) +{ + return this->array_ + this->cur_size_; +} + +template +ACE_INLINE typename ACE_Array_Base::const_iterator +ACE_Array_Base::begin (void) const +{ + return this->array_; +} + +template +ACE_INLINE typename ACE_Array_Base::const_iterator +ACE_Array_Base::end (void) const +{ + return this->array_ + this->cur_size_; +} + +template +ACE_INLINE typename ACE_Array_Base::reverse_iterator +ACE_Array_Base::rbegin (void) +{ + return reverse_iterator (this->end ()); +} + +template +ACE_INLINE typename ACE_Array_Base::reverse_iterator +ACE_Array_Base::rend (void) +{ + return reverse_iterator (this->begin ()); +} + +template +ACE_INLINE typename ACE_Array_Base::const_reverse_iterator +ACE_Array_Base::rbegin (void) const +{ + return const_reverse_iterator (this->end ()); +} + +template +ACE_INLINE typename ACE_Array_Base::const_reverse_iterator +ACE_Array_Base::rend (void) const +{ + return const_reverse_iterator (this->begin ()); +} + +template ACE_INLINE typename ACE_Array_Base::size_type +ACE_Array_Base::size (void) const +{ + return this->cur_size_; +} + +template ACE_INLINE typename ACE_Array_Base::size_type +ACE_Array_Base::max_size (void) const +{ + return this->max_size_; +} + +template ACE_INLINE bool +ACE_Array_Base::in_range (typename ACE_Array_Base::size_type index) const +{ + return index < this->cur_size_; +} + +template ACE_INLINE T & +ACE_Array_Base::operator[] (typename ACE_Array_Base::size_type index) +{ + return this->array_[index]; +} + +template ACE_INLINE const T & +ACE_Array_Base::operator[] (typename ACE_Array_Base::size_type index) const +{ + return this->array_[index]; +} + +// **************************************************************** + +template ACE_INLINE void +ACE_Array_Iterator::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + // ACE_TRACE ("ACE_Array_Iterator::dump"); +#endif /* ACE_HAS_DUMP */ +} + +template ACE_INLINE +ACE_Array_Iterator::ACE_Array_Iterator (ACE_Array_Base &a) + : current_ (0), + array_ (a) +{ + // ACE_TRACE ("ACE_Array_Iterator::ACE_Array_Iterator"); +} + +template ACE_INLINE int +ACE_Array_Iterator::advance (void) +{ + // ACE_TRACE ("ACE_Array_Iterator::advance"); + + if (this->current_ < array_.size ()) + { + ++this->current_; + return 1; + } + else + { + // Already finished iterating. + return 0; + } +} + +template ACE_INLINE int +ACE_Array_Iterator::done (void) const +{ + ACE_TRACE ("ACE_Array_Iterator::done"); + + return this->current_ >= array_.size (); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Array_Map.cpp b/dep/acelite/ace/Array_Map.cpp new file mode 100644 index 00000000000..5530a8b54b6 --- /dev/null +++ b/dep/acelite/ace/Array_Map.cpp @@ -0,0 +1,299 @@ +// $Id: Array_Map.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#ifndef ACE_ARRAY_MAP_CPP +#define ACE_ARRAY_MAP_CPP + +#include "ace/Array_Map.h" + +#ifndef __ACE_INLINE__ +# include "ace/Array_Map.inl" +#endif /* !__ACE_INLINE__ */ + +#include "ace/checked_iterator.h" + +#include + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +#ifndef ACE_LACKS_MEMBER_TEMPLATES +template +template +ACE_Array_Map::ACE_Array_Map (InputIterator f, + InputIterator l) + : size_ (l - f) + , capacity_ (size_) + , nodes_ (size_ == 0 ? 0 : new value_type[size_]) +{ + (void) std::copy (f, + l, + ACE_make_checked_array_iterator (this->begin (), + this->size_)); + +// iterator n = this->begin (); + +// for (InputIterator i = f; i != l; ++i, ++n) +// *n = *i; +} +#else +template +ACE_Array_Map::ACE_Array_Map ( + typename ACE_Array_Map::const_iterator f, + typename ACE_Array_Map::const_iterator l) + : size_ (l - f) + , capacity_ (size_) + , nodes_ (size_ == 0 ? 0 : new value_type[size_]) +{ + (void) std::copy (f, + l, + ACE_make_checked_array_iterator (this->begin (), + this->size_)); + +// iterator n = this->begin (); + +// for (const_iterator i = f; i != l; ++i, ++n) +// *n = *i; +} +#endif /* !ACE_LACKS_MEMBER_TEMPLATES */ + +template +ACE_Array_Map::ACE_Array_Map ( + ACE_Array_Map const & map) + : size_ (map.size_) + , capacity_ (map.size_) + , nodes_ (size_ == 0 ? 0 : new value_type[size_]) +{ + std::copy (map.begin (), + map.end (), + ACE_make_checked_array_iterator (this->begin (), + this->size_)); + +// iterator f = map.begin (); +// iterator l = map.end (); +// iterator n = this->begin (); + +// for (iterator i = f; i != l; ++i, ++n) +// *n = *i; +} + +template +ACE_Array_Map::~ACE_Array_Map (void) +{ + delete[] this->nodes_; +} + +template +void +ACE_Array_Map::swap ( + ACE_Array_Map & map) +{ + std::swap (this->size_, map.size_); + std::swap (this->capacity_, map.capacity_); + std::swap (this->nodes_, map.nodes_); +} + +template +std::pair::iterator, bool> +ACE_Array_Map::insert ( + typename ACE_Array_Map::value_type const & x) +{ + // Linear insertion due to linear duplicate key search. + + bool inserted = false; + iterator i = this->find (x.first); + + if (i == this->end ()) + { + // Add the element to the array. + + size_type const old_size = this->size (); + this->grow (1); // Increase size by at least one. + + i = this->begin () + old_size; + *i = x; + + ++this->size_; + + inserted = true; + } + + return std::make_pair (i, inserted); +} + +#ifndef ACE_LACKS_MEMBER_TEMPLATES +template +template +void +ACE_Array_Map::insert (InputIterator f, InputIterator l) +{ + this->grow (l - f); // Preallocate storage. + + for (InputIterator i = f; i != l; ++i) + { + (void) this->insert (*i); + } +} +#else +template +void +ACE_Array_Map::insert ( + typename ACE_Array_Map::const_iterator f, + typename ACE_Array_Map::const_iterator l) +{ + this->grow (l - f); // Preallocate storage. + + for (const_iterator i = f; i != l; ++i) + { + (void) this->insert (*i); + } +} +#endif /* ACE_LACKS_MEMBER_TEMPLATES */ + +template +void +ACE_Array_Map::erase ( + typename ACE_Array_Map::iterator pos) +{ + iterator const first = this->begin (); + iterator const last = this->end (); + + if (pos >= first && pos < last) + { + if (pos != last - 1) + { + // Relocate the tail element to the location of the erased + // element to prevent introduction of "holes" in the + // underlying array. + *pos = *(last - 1); + } + + // Explicitly destroy the tail element by assigning a default + // constructed instance to it. Note that this also works for + // the case of a map of size 1. + *(last - 1) = value_type (); + + --this->size_; + } +} + +template +typename ACE_Array_Map::size_type +ACE_Array_Map::erase ( + typename ACE_Array_Map::key_type const & k) +{ + iterator pos = this->find (k); + + size_type const old_size = this->size_; + + this->erase (pos); + + return old_size - this->size_; +} + +template +void +ACE_Array_Map::erase ( + typename ACE_Array_Map::iterator first, + typename ACE_Array_Map::iterator last) +{ + if (this->begin () <= first && first < last && last < this->end ()) + for (iterator i = first; i != last; ++i) + this->erase (i); +} + +template +void +ACE_Array_Map::clear (void) +{ + this->size_ = 0; // No need to deallocate array nor destroy elements. +} + +template +typename ACE_Array_Map::iterator +ACE_Array_Map::find ( + typename ACE_Array_Map::key_type const & k) +{ + iterator const the_end = this->end (); + + EqualTo eq; + + for (iterator i = this->begin (); i != the_end; ++i) + if (eq (k, i->first)) + return i; + + return this->end (); +} + +template +typename ACE_Array_Map::const_iterator +ACE_Array_Map::find ( + typename ACE_Array_Map::key_type const & k) const +{ + const_iterator const the_end = this->end (); + + EqualTo eq; + + for (const_iterator i = this->begin (); i != the_end; ++i) + if (eq (k, i->first)) + return i; + + return this->end (); +} + +template +void +ACE_Array_Map::grow ( + typename ACE_Array_Map::size_type s) +{ + if (this->size () + s > this->capacity_) + { + // This implementation focuses more on static footprint than + // speed. + + // Strongly exception safe. + + ACE_Array_Map temp (this->size () + s); + + std::copy (this->begin (), + this->end (), + ACE_make_checked_array_iterator (temp.begin (), + temp.capacity_)); + + size_type const n = this->size (); // Do not swap out the size + // since we bypassed the + // temporary map's element + // counting code. + this->swap (temp); + + this->size_ = n; + } +} + +// --------------------------------------------------------------- + +template +bool +operator== (ACE_Array_Map const & lhs, + ACE_Array_Map const & rhs) +{ + // Do not include Array_Map capacity in comparison. It isn't useful + // in this case. + + return (lhs.size () == rhs.size () + && std::equal (lhs.begin (), + lhs.end (), + ACE_make_checked_array_iterator (rhs.begin (), + rhs.size ()))); +} + +template +bool +operator< (ACE_Array_Map const & lhs, + ACE_Array_Map const & rhs) +{ + return std::lexicographical_compare (lhs.begin (), lhs.end (), + rhs.begin (), rhs.end ()); +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_ARRAY_MAP_CPP */ diff --git a/dep/acelite/ace/Array_Map.h b/dep/acelite/ace/Array_Map.h new file mode 100644 index 00000000000..1515ea45529 --- /dev/null +++ b/dep/acelite/ace/Array_Map.h @@ -0,0 +1,300 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Array_Map.h + * + * $Id: Array_Map.h 84136 2009-01-12 11:01:17Z johnnyw $ + * + * Light weight array-based map with fast iteration but linear + * (i.e. O(n)) search times. STL-style interface is exposed. + * + * @note This class requires the STL generic algorithms and + * reverse_iterator adapter. + * + * @author Ossama Othman + */ +//============================================================================= + + +#ifndef ACE_ARRAY_MAP_H +#define ACE_ARRAY_MAP_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include +#include +#include + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Array_Map + * + * @brief Light weight array-based map with fast iteration, but linear + * (i.e. O(n)) search times. + * + * Map implementation that focuses on small footprint and fast + * iteration. Search times are, however, linear (O(n)) meaning that + * this map isn't suitable for large data sets that will be searched + * in performance critical areas of code. Iteration over large data + * sets, however, is faster than linked list-based maps, for example, + * since spatial locality is maximized through the use of contiguous + * arrays as the underlying storage. + * @par + * An @c ACE_Array_Map is a unique associative container, meaning that + * duplicate values may not be added to the map. It is also pair + * associative (value_type is a std::pair<>). It is not a sorted + * container. + * @par + * An STL @c std::map -like interface is exposed by this class + * portability. Furthermore, this map's iterators are compatible with + * STL algorithms. + * @par + * Requirements and Performance Characteristics + * - Internal Structure + * Array + * - Duplicates allowed? + * No + * - Random access allowed? + * Yes + * - Search speed + * O(n) + * - Insert/replace speed + * O(n), can be longer if the map has to resize + * - Iterator still valid after change to container? + * No + * - Frees memory for removed elements? + * Yes + * - Items inserted by + * Value + * - Requirements for key type + * -# Default constructor + * -# Copy constructor + * -# operator= + * -# operator== + * - Requirements for object type + * -# Default constructor + * -# Copy constructor + * -# operator= + */ +template > +class ACE_Array_Map +{ +public: + + // STL-style typedefs/traits. + typedef Key key_type; + typedef Value data_type; + typedef std::pair value_type; + typedef value_type * iterator; + typedef value_type const * const_iterator; + typedef value_type & reference; + typedef value_type const & const_reference; + typedef value_type * pointer; + typedef value_type const * const_pointer; + typedef ptrdiff_t difference_type; + typedef size_t size_type; + + ACE_DECLARE_STL_REVERSE_ITERATORS + + /// Default Constructor. + /** + * Create an empty map with a preallocated buffer of size @a s. + */ + ACE_Array_Map (size_type s = 0); + +#ifndef ACE_LACKS_MEMBER_TEMPLATES + template + ACE_Array_Map (InputIterator f, InputIterator l); +#else + ACE_Array_Map (const_iterator f, const_iterator l); +#endif /* !ACE_LACKS_MEMBER_TEMPLATES */ + + ACE_Array_Map (ACE_Array_Map const & map); + ACE_Array_Map & operator= (ACE_Array_Map const & map); + + /// Destructor. + ~ACE_Array_Map (void); + + /** + * @name Forward Iterator Accessors + * + * Forward iterator accessors. + */ + //@{ + iterator begin (void); + iterator end (void); + const_iterator begin (void) const; + const_iterator end (void) const; + //@} + + /** + * @name Reverse Iterator Accessors + * + * Reverse iterator accessors. + */ + //@{ + reverse_iterator rbegin (void); + reverse_iterator rend (void); + const_reverse_iterator rbegin (void) const; + const_reverse_iterator rend (void) const; + //@} + + /// Return current size of map. + /** + * @return The number of elements in the map. + */ + size_type size (void) const; + + /// Maximum number of elements the map can hold. + size_type max_size (void) const; + + /// Return @c true if the map is empty, else @c false. + bool is_empty (void) const; // ACE style + + /** + * Return @c true if the map is empty, else @c false. We recommend + * using @c is_empty() instead since it's more consistent with the + * ACE container naming conventions. + */ + bool empty (void) const; // STL style + + /// Swap the contents of this map with the given @a map in an + /// exception-safe manner. + void swap (ACE_Array_Map & map); + + /// Insert the value @a x into the map. + /** + * STL-style map insertion method. + * + * @param x @c std::pair containing key and datum. + * + * @return @c std::pair::second will be @c false if the map already + * contains a value with the same key as @a x. + */ + std::pair insert (value_type const & x); + +#ifndef ACE_LACKS_MEMBER_TEMPLATES + /// Insert range of elements into map. + template + void insert (InputIterator f, InputIterator l); +#else + /// Insert range of elements into map. + void insert (const_iterator f, const_iterator l); +#endif /* ACE_LACKS_MEMBER_TEMPLATES */ + + /// Remove element at position @a pos from the map. + void erase (iterator pos); + + /// Remove element corresponding to key @a k from the map. + /** + * @return Number of elements that were erased. + */ + size_type erase (key_type const & k); + + /// Remove range of elements [@a first, @a last) from the map. + /** + * @note [@a first, @a last) must be valid range within the map. + */ + void erase (iterator first, iterator last); + + /// Clear contents of map. + /** + * @note This a constant time (O(1)) operation. + */ + void clear (void); + + /** + * @name Search Operations + * + * Search the map for data corresponding to key @a k. + */ + //@{ + /** + * @return @c end() if data corresponding to key @a k is not in the + * map. + */ + iterator find (key_type const & k); + + /** + * @return @c end() if data corresponding to key @a k is not in the + * map. + */ + const_iterator find (key_type const & k) const; + //@} + + /// Count the number of elements corresponding to key @a k. + /** + * @return In the case of this map, the count will always be one if + * such exists in the map. + */ + size_type count (key_type const & k); + + /// Convenience array index operator. + /** + * Array index operator that allows insertion and retrieval of + * elements using an array index syntax, such as: + * @par + * map["Foo"] = 12; + */ + data_type & operator[] (key_type const & k); + +private: + + /// Increase size of underlying buffer by @a s. + void grow (size_type s); + +private: + + /// Number of elements in the map. + size_type size_; + + /// Current size of underlying array. + /** + * @note @c capacity_ is always greater than or equal to @c size_; + */ + size_type capacity_; + + /// Underlying array containing keys and data. + value_type * nodes_; + +}; + +// -------------------------------------------------------------- + +/// @c ACE_Array_Map equality operator. +template +bool operator== (ACE_Array_Map const & lhs, + ACE_Array_Map const & rhs); + +/// @c ACE_Array_Map lexicographical comparison operator. +template +bool operator< (ACE_Array_Map const & lhs, + ACE_Array_Map const & rhs); + +// -------------------------------------------------------------- + +ACE_END_VERSIONED_NAMESPACE_DECL + +#ifdef __ACE_INLINE__ +# include "ace/Array_Map.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +# include "ace/Array_Map.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Array_Map.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" + +#endif /* ACE_ARRAY_MAP_H */ diff --git a/dep/acelite/ace/Array_Map.inl b/dep/acelite/ace/Array_Map.inl new file mode 100644 index 00000000000..b053dc0a441 --- /dev/null +++ b/dep/acelite/ace/Array_Map.inl @@ -0,0 +1,133 @@ +// -*- C++ -*- +// +// $Id: Array_Map.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template +ACE_INLINE +ACE_Array_Map::ACE_Array_Map ( + typename ACE_Array_Map::size_type s) + : size_ (0) + , capacity_ (s) + , nodes_ (s == 0 ? 0 : new value_type[s]) +{ +} + +template +ACE_INLINE ACE_Array_Map & +ACE_Array_Map::operator= ( + ACE_Array_Map const & map) +{ + // Strongly exception-safe assignment. + + ACE_Array_Map temp (map); + this->swap (temp); + return *this; +} + +template +ACE_INLINE typename ACE_Array_Map::iterator +ACE_Array_Map::begin (void) +{ + return this->nodes_; +} + +template +ACE_INLINE typename ACE_Array_Map::iterator +ACE_Array_Map::end (void) +{ + return this->nodes_ + this->size_; +} + +template +ACE_INLINE typename ACE_Array_Map::const_iterator +ACE_Array_Map::begin (void) const +{ + return this->nodes_; +} + +template +ACE_INLINE typename ACE_Array_Map::const_iterator +ACE_Array_Map::end (void) const +{ + return this->nodes_ + this->size_; +} + +template +ACE_INLINE typename ACE_Array_Map::reverse_iterator +ACE_Array_Map::rbegin (void) +{ + return reverse_iterator (this->end ()); +} + +template +ACE_INLINE typename ACE_Array_Map::reverse_iterator +ACE_Array_Map::rend (void) +{ + return reverse_iterator (this->begin ()); +} + +template +ACE_INLINE typename ACE_Array_Map::const_reverse_iterator +ACE_Array_Map::rbegin (void) const +{ + return const_reverse_iterator (this->end ()); +} + +template +ACE_INLINE typename ACE_Array_Map::const_reverse_iterator +ACE_Array_Map::rend (void) const +{ + return const_reverse_iterator (this->begin ()); +} + +template +ACE_INLINE typename ACE_Array_Map::size_type +ACE_Array_Map::size (void) const +{ + return this->size_; +} + +template +ACE_INLINE typename ACE_Array_Map::size_type +ACE_Array_Map::max_size (void) const +{ + return size_type (-1) / sizeof (value_type); +} + +template +ACE_INLINE bool +ACE_Array_Map::is_empty (void) const +{ + return this->size_ == 0; +} + +// The following method is deprecated. + +template +ACE_INLINE bool +ACE_Array_Map::empty (void) const +{ + return this->is_empty (); +} + +template +ACE_INLINE typename ACE_Array_Map::size_type +ACE_Array_Map::count ( + typename ACE_Array_Map::key_type const & k) +{ + return + (this->find (k) == this->end () ? 0 : 1); // Only one datum per key. +} + +template +ACE_INLINE typename ACE_Array_Map::data_type & +ACE_Array_Map::operator[] ( + typename ACE_Array_Map::key_type const & k) +{ + iterator i = (this->insert (value_type (k, data_type ()))).first; + return (*i).second; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Assert.cpp b/dep/acelite/ace/Assert.cpp new file mode 100644 index 00000000000..4a71c9e5a9d --- /dev/null +++ b/dep/acelite/ace/Assert.cpp @@ -0,0 +1,24 @@ +// $Id: Assert.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Assert.h" +#include "ace/Log_Msg.h" + +ACE_RCSID(ace, Assert, "$Id: Assert.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// The following ASSERT macro is courtesy of Alexandre Karev +// . +void +__ace_assert(const char *file, int line, const ACE_TCHAR *expression) +{ + int error = ACE_Log_Msg::last_error_adapter (); + ACE_Log_Msg *log = ACE_Log_Msg::instance (); + + log->set (file, line, -1, error, log->restart (), + log->msg_ostream (), log->msg_callback ()); + + log->log (LM_ERROR, ACE_TEXT ("ACE_ASSERT: file %N, line %l assertion failed for '%s'.%a\n"), expression, -1); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Assert.h b/dep/acelite/ace/Assert.h new file mode 100644 index 00000000000..89363d4c69a --- /dev/null +++ b/dep/acelite/ace/Assert.h @@ -0,0 +1,40 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Assert.h + * + * $Id: Assert.h 82808 2008-09-23 11:27:27Z smcqueen $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_ASSERT_H +#define ACE_ASSERT_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#include /**/ "ace/config-all.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL +ACE_Export void __ace_assert(const char *file, int line, const ACE_TCHAR *expression); +ACE_END_VERSIONED_NAMESPACE_DECL + +#define ACE_TEST_ASSERT(X) \ + ((X) \ + ? static_cast(0) \ + : ACE_VERSIONED_NAMESPACE_NAME::__ace_assert(__FILE__, __LINE__, ACE_TEXT_CHAR_TO_TCHAR (#X))) + +#if defined (ACE_NDEBUG) +#define ACE_ASSERT(x) \ + (static_cast(0)) +#else +#define ACE_ASSERT(X) ACE_TEST_ASSERT(X) +#endif /* ACE_NDEBUG */ + +#include /**/ "ace/post.h" + +#endif /* ACE_ASSERT */ diff --git a/dep/acelite/ace/Asynch_Acceptor.cpp b/dep/acelite/ace/Asynch_Acceptor.cpp new file mode 100644 index 00000000000..3afb27c7b7d --- /dev/null +++ b/dep/acelite/ace/Asynch_Acceptor.cpp @@ -0,0 +1,514 @@ +/* -*- C++ -*- */ +// $Id: Asynch_Acceptor.cpp 85213 2009-04-29 16:34:20Z shuston $ + +#ifndef ACE_ASYNCH_ACCEPTOR_C +#define ACE_ASYNCH_ACCEPTOR_C + +#include "ace/Asynch_Acceptor.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_RCSID(ace, Asynch_Acceptor, "$Id: Asynch_Acceptor.cpp 85213 2009-04-29 16:34:20Z shuston $") + +#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) || defined (ACE_HAS_AIO_CALLS) +// This only works on platforms that support async i/o. + +#include "ace/OS_Errno.h" +#include "ace/OS_Memory.h" +#include "ace/OS_NS_sys_socket.h" +#include "ace/Log_Msg.h" +#include "ace/Message_Block.h" +#include "ace/INET_Addr.h" +#include "ace/SOCK_Stream.h" +#include "ace/Sock_Connect.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template +ACE_Asynch_Acceptor::ACE_Asynch_Acceptor (void) + : listen_handle_ (ACE_INVALID_HANDLE), + pass_addresses_ (false), + validate_new_connection_ (false), + reissue_accept_ (1), + bytes_to_read_ (0) +{ +} + +template +ACE_Asynch_Acceptor::~ACE_Asynch_Acceptor (void) +{ + // Close down the listen socket + if (this->listen_handle_ != ACE_INVALID_HANDLE) + { + ACE_OS::closesocket (this->listen_handle_); + this->listen_handle_ = ACE_INVALID_HANDLE; + } +} + +template int +ACE_Asynch_Acceptor::open (const ACE_INET_Addr &address, + size_t bytes_to_read, + bool pass_addresses, + int backlog, + int reuse_addr, + ACE_Proactor *proactor, + bool validate_new_connection, + int reissue_accept, + int number_of_initial_accepts) +{ + ACE_TRACE ("ACE_Asynch_Acceptor<>::open"); + + this->proactor (proactor); + this->pass_addresses_ = pass_addresses; + this->bytes_to_read_ = bytes_to_read; + this->validate_new_connection_ = validate_new_connection; + this->reissue_accept_ = reissue_accept; + this->addr_family_ = address.get_type (); + + // Create the listener socket + this->listen_handle_ = ACE_OS::socket (address.get_type (), SOCK_STREAM, 0); + if (this->listen_handle_ == ACE_INVALID_HANDLE) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_OS::socket")), + -1); + // Initialize the ACE_Asynch_Accept + if (this->asynch_accept_.open (*this, + this->listen_handle_, + 0, + this->proactor ()) == -1) + { + ACE_Errno_Guard g (errno); + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_Asynch_Accept::open"))); + ACE_OS::closesocket (this->listen_handle_); + this->listen_handle_ = ACE_INVALID_HANDLE; + return -1; + } + + if (reuse_addr) + { + // Reuse the address + int one = 1; + if (ACE_OS::setsockopt (this->listen_handle_, + SOL_SOCKET, + SO_REUSEADDR, + (const char*) &one, + sizeof one) == -1) + { + ACE_Errno_Guard g (errno); + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_OS::setsockopt"))); + ACE_OS::closesocket (this->listen_handle_); + this->listen_handle_ = ACE_INVALID_HANDLE; + return -1; + } + } + + // If port is not specified, bind to any port. + static ACE_INET_Addr sa (ACE_sap_any_cast (const ACE_INET_Addr &)); + + if (address == sa && + ACE::bind_port (this->listen_handle_, + INADDR_ANY, + address.get_type()) == -1) + { + ACE_Errno_Guard g (errno); + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE::bind_port"))); + ACE_OS::closesocket (this->listen_handle_); + this->listen_handle_ = ACE_INVALID_HANDLE; + return -1; + } + + // Bind to the specified port. + if (ACE_OS::bind (this->listen_handle_, + reinterpret_cast (address.get_addr ()), + address.get_size ()) == -1) + { + ACE_Errno_Guard g (errno); + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_OS::bind"))); + ACE_OS::closesocket (this->listen_handle_); + this->listen_handle_ = ACE_INVALID_HANDLE; + return -1; + } + + // Start listening. + if (ACE_OS::listen (this->listen_handle_, backlog) == -1) + { + ACE_Errno_Guard g (errno); + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_OS::listen"))); + ACE_OS::closesocket (this->listen_handle_); + this->listen_handle_ = ACE_INVALID_HANDLE; + return -1; + } + + // For the number of . + if (number_of_initial_accepts == -1) + number_of_initial_accepts = backlog; + + for (int i = 0; i < number_of_initial_accepts; i++) + { + // Initiate accepts. + if (this->accept (bytes_to_read) == -1) + { + ACE_Errno_Guard g (errno); + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_Asynch_Acceptor::accept"))); + ACE_OS::closesocket (this->listen_handle_); + this->listen_handle_ = ACE_INVALID_HANDLE; + return -1; + } + } + + return 0; +} + +template int +ACE_Asynch_Acceptor::set_handle (ACE_HANDLE listen_handle) +{ + ACE_TRACE ("ACE_Asynch_Acceptor<>::set_handle"); + + // Take ownership of the + this->listen_handle_ = listen_handle; + + // Reinitialize the ACE_Asynch_Accept + if (this->asynch_accept_.open (*this, + this->listen_handle_, + 0, + this->proactor ()) == -1) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_Asynch_Accept::open")), + -1); + return 0; +} + +template ACE_HANDLE +ACE_Asynch_Acceptor::get_handle (void) const +{ + return this->listen_handle_; +} + +template int +ACE_Asynch_Acceptor::accept (size_t bytes_to_read, const void *act) +{ + ACE_TRACE ("ACE_Asynch_Acceptor<>::accept"); + + ACE_Message_Block *message_block = 0; + // The space_needed calculation is drive by needs of Windows. POSIX doesn't + // need to extra 16 bytes, but it doesn't hurt. + size_t space_needed = sizeof (sockaddr_in) + 16; +#if defined (ACE_HAS_IPV6) + if (PF_INET6 == this->addr_family_) + space_needed = sizeof (sockaddr_in6) + 16; +#endif /* ACE_HAS_IPV6 */ + space_needed = (2 * space_needed) + bytes_to_read; + + // Create a new message block big enough for the addresses and data + ACE_NEW_RETURN (message_block, + ACE_Message_Block (space_needed), + -1); + + // Initiate asynchronous accepts + if (this->asynch_accept_.accept (*message_block, + bytes_to_read, + ACE_INVALID_HANDLE, + act, + 0, + ACE_SIGRTMIN, + this->addr_family_) == -1) + { + // Cleanup on error + message_block->release (); + return -1; + } + return 0; +} + +template void +ACE_Asynch_Acceptor::handle_accept (const ACE_Asynch_Accept::Result &result) +{ + ACE_TRACE ("ACE_Asynch_Acceptor<>::handle_accept"); + + // Variable for error tracking + int error = 0; + + // If the asynchronous accept fails. + if (!result.success () || result.accept_handle () == ACE_INVALID_HANDLE) + { + error = 1; + } + +#if defined (ACE_WIN32) + // In order to use accept handle with other Window Sockets 1.1 + // functions, we call the setsockopt function with the + // SO_UPDATE_ACCEPT_CONTEXT option. This option initializes the + // socket so that other Windows Sockets routines to access the + // socket correctly. + if (!error && + ACE_OS::setsockopt (result.accept_handle (), + SOL_SOCKET, + SO_UPDATE_ACCEPT_CONTEXT, + (char *) &this->listen_handle_, + sizeof (this->listen_handle_)) == -1) + { + error = 1; + } +#endif /* ACE_WIN32 */ + + // Parse address. + ACE_INET_Addr local_address; + ACE_INET_Addr remote_address; + if (!error && + (this->validate_new_connection_ || this->pass_addresses_)) + // Parse the addresses. + this->parse_address (result, + remote_address, + local_address); + + // Validate remote address + if (!error && + this->validate_new_connection_ && + (this->validate_connection (result, remote_address, local_address) == -1)) + { + error = 1; + } + + HANDLER *new_handler = 0; + if (!error) + { + // The Template method + new_handler = this->make_handler (); + if (new_handler == 0) + { + error = 1; + } + } + + // If no errors + if (!error) + { + // Update the Proactor. + new_handler->proactor (this->proactor ()); + + // Pass the addresses + if (this->pass_addresses_) + new_handler->addresses (remote_address, + local_address); + + // Pass the ACT + if (result.act () != 0) + new_handler->act (result.act ()); + + // Set up the handler's new handle value + new_handler->handle (result.accept_handle ()); + + // Initiate the handler + new_handler->open (result.accept_handle (), + result.message_block ()); + } + + // On failure, no choice but to close the socket + if (error && + result.accept_handle() != ACE_INVALID_HANDLE ) + ACE_OS::closesocket (result.accept_handle ()); + + // Delete the dynamically allocated message_block + result.message_block ().release (); + + // Start off another asynchronous accept to keep the backlog going, + // unless we closed the listen socket already (from the destructor), + // or this callback is the result of a canceled/aborted accept. + if (this->should_reissue_accept () && + this->listen_handle_ != ACE_INVALID_HANDLE +#if defined (ACE_WIN32) + && result.error () != ERROR_OPERATION_ABORTED +#else + && result.error () != ECANCELED +#endif + ) + this->accept (this->bytes_to_read_, result.act ()); +} + +template int +ACE_Asynch_Acceptor::validate_connection + (const ACE_Asynch_Accept::Result& /* result */, + const ACE_INET_Addr& /* remote */, + const ACE_INET_Addr& /* local */) +{ + // Default implementation always validates the remote address. + return 0; +} + +template int +ACE_Asynch_Acceptor::cancel (void) +{ + ACE_TRACE ("ACE_Asynch_Acceptor<>::cancel"); + + // All I/O operations that are canceled will complete with the error + // ERROR_OPERATION_ABORTED. All completion notifications for the I/O + // operations will occur normally. +#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) + return (int) ::CancelIo (this->listen_handle_); +#else + // Supported now + return this->asynch_accept_.cancel(); +#endif /* defined (ACE_HAS_WIN32_OVERLAPPED_IO) */ +} + +template void +ACE_Asynch_Acceptor::parse_address (const + ACE_Asynch_Accept::Result &result, + ACE_INET_Addr &remote_address, + ACE_INET_Addr &local_address) +{ + ACE_TRACE ("ACE_Asynch_Acceptor<>::parse_address"); + +#if defined (ACE_HAS_AIO_CALLS) + + // Use an ACE_SOCK to get the addresses - it knows how to deal with + // ACE_INET_Addr objects and get IPv4/v6 addresses. + ACE_SOCK_Stream str (result.accept_handle ()); + str.get_local_addr (local_address); + str.get_remote_addr (remote_address); + +#elif defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0) + + ACE_Message_Block &message_block = result.message_block (); + + sockaddr *local_addr = 0; + sockaddr *remote_addr = 0; + int local_size = 0; + int remote_size = 0; + // This matches setup in accept(). + size_t addr_size = sizeof (sockaddr_in) + 16; +#if defined (ACE_HAS_IPV6) + if (this->addr_family_ == PF_INET6) + addr_size = sizeof (sockaddr_in6) + 16; +#endif /* ACE_HAS_IPV6 */ + + ::GetAcceptExSockaddrs (message_block.rd_ptr (), + static_cast (this->bytes_to_read_), + static_cast (addr_size), + static_cast (addr_size), + &local_addr, + &local_size, + &remote_addr, + &remote_size); + + local_address.set (reinterpret_cast (local_addr), + local_size); + remote_address.set (reinterpret_cast (remote_addr), + remote_size); +#else + // just in case + errno = ENOTSUP; +#endif /* defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0) */ + return; +} + +template ACE_HANDLE +ACE_Asynch_Acceptor::handle (void) const +{ + return this->listen_handle_; +} + +template void +ACE_Asynch_Acceptor::handle (ACE_HANDLE h) +{ + ACE_Handler::handle (h); +} + +template ACE_Asynch_Accept & +ACE_Asynch_Acceptor::asynch_accept (void) +{ + return this->asynch_accept_; +} + +template HANDLER * +ACE_Asynch_Acceptor::make_handler (void) +{ + // Default behavior + HANDLER *handler = 0; + ACE_NEW_RETURN (handler, + HANDLER, + 0); + return handler; +} + +/* static */ +template size_t +ACE_Asynch_Acceptor::address_size (void) +{ + return sizeof (sockaddr) + sizeof (sockaddr_in); +} + +template bool +ACE_Asynch_Acceptor::pass_addresses (void) const +{ + return this->pass_addresses_; +} + +template void +ACE_Asynch_Acceptor::pass_addresses (bool new_value) +{ + this->pass_addresses_ = new_value; +} + +template bool +ACE_Asynch_Acceptor::validate_new_connection (void) const +{ + return this->validate_new_connection_; +} + +template void +ACE_Asynch_Acceptor::validate_new_connection (bool new_value) +{ + this->validate_new_connection_ = new_value; +} + +template int +ACE_Asynch_Acceptor::reissue_accept (void) const +{ + return this->reissue_accept_; +} + +template void +ACE_Asynch_Acceptor::reissue_accept (int new_value) +{ + this->reissue_accept_ = new_value; +} + +template size_t +ACE_Asynch_Acceptor::bytes_to_read (void) const +{ + return this->bytes_to_read_; +} + +template void +ACE_Asynch_Acceptor::bytes_to_read (size_t new_value) +{ + this->bytes_to_read_ = new_value; +} + +template int +ACE_Asynch_Acceptor::should_reissue_accept (void) +{ + return this->reissue_accept_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_WIN32 || ACE_HAS_AIO_CALLS */ +#endif /* ACE_ASYNCH_ACCEPTOR_C */ diff --git a/dep/acelite/ace/Asynch_Acceptor.h b/dep/acelite/ace/Asynch_Acceptor.h new file mode 100644 index 00000000000..29872d59482 --- /dev/null +++ b/dep/acelite/ace/Asynch_Acceptor.h @@ -0,0 +1,281 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file Asynch_Acceptor.h + * + * $Id: Asynch_Acceptor.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Irfan Pyarali (irfan@cs.wustl.edu) + */ +//============================================================================= + +#ifndef ACE_ASYNCH_ACCEPTOR_H +#define ACE_ASYNCH_ACCEPTOR_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) || defined (ACE_HAS_AIO_CALLS) +// This only works on platforms that support async i/o. + +#include "ace/Default_Constants.h" +#include "ace/Asynch_IO.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Forward declarations +class ACE_Message_Block; +class ACE_INET_Addr; + +/** + * @class ACE_Asynch_Acceptor + * + * @brief This class is an example of the Acceptor Pattern. This class + * will accept new connections and create new HANDLER to handle + * the new connections. + * + * Unlike the ACE_Acceptor, however, this class is designed to + * be used asynchronously. + */ +template +class ACE_Asynch_Acceptor : public ACE_Handler +{ +public: + /// A do nothing constructor. + ACE_Asynch_Acceptor (void); + + /// Virtual destruction + virtual ~ACE_Asynch_Acceptor (void); + + /** + * @c open starts one or more asynchronous accept requests on a + * @a address. Each accept operation may optionally read an + * initial buffer from the new connection when accepted. + * + * @param address The address to listen/accept connections on. + * If the address does not specify a port, a random + * port is selected and bound. + * @param bytes_to_read Optional, specifies the maximum number of bytes + * to read with the accept. The buffer for the initial + * data is allocated internally and passed to the + * @c ACE_Service_Handler::open() hook method. It is + * legitimate only during the @c open() method and must + * be copied if required after @c open() returns. + * This pre-read function works only on Windows. + * @param pass_addresses Optional, a non-zero value indicates that + * the local and peer addresses should be passed to the + * associated @c ACE_Service_Handler::addresses() method + * after any call to @c validate_new_connection() and prior + * to the @c open() hook method call. + * @param backlog Optional, defaulting to @c ACE_DEFAULT_ASYNCH_BACKLOG (which + * can be adjusted in your platform's @c config.h file). + * Specifies the listening backlog for the listening socket. + * @param reuse_addr Optional, indicates whether the @c SO_REUSEADDR + * option is set on the listening socket or not. + * @param proactor Optional, pointer to the @c ACE_Proactor to use for + * demultiplexing asynchronous accepts. If 0, the + * process's singleton @c ACE_Proactor is used. + * @param validate_new_connection Optional, if true, this object's + * @c validate_connection() method is called after + * the accept completes, but before the service handler's + * @c open() hook method is called. If @c + * validate_connection() returns -1, the newly-accepted + * socket is immediately closed, and the @c addresses() + * method is not called. + * @param reissue_accept Optional, if non-zero (the default), a new + * asynchronous accept operation is started after each + * completion, whether the completion is for success or + * failure, and whether or not a successfully-accepted + * connection is subsequently refused. + * @param number_of_initial_accepts Optional, the number of asynchronous + * accepts that are started immediately. If -1 (the + * default), the value of @a backlog is used. + * + * @note On Windows, the peer address is only available at the time + * the connection is accepted. Therefore, if you require the peer + * address on Windows, do not rely on the + * @c ACE_SOCK::get_remote_addr() method - it won't work. You must + * supply a non-zero value for @a pass_addresses and obtain the + * peer address in the @c ACE_Service_Handler::addresses() method. + * + * @see ACE_INET_Addr + * @see ACE_Service_Handler + */ + virtual int open (const ACE_INET_Addr &address, + size_t bytes_to_read = 0, + bool pass_addresses = false, + int backlog = ACE_DEFAULT_ASYNCH_BACKLOG, + int reuse_addr = 1, + ACE_Proactor *proactor = 0, + bool validate_new_connection = false, + int reissue_accept = 1, + int number_of_initial_accepts = -1); + + /// Get the underlying handle. + virtual ACE_HANDLE get_handle (void) const; + + /** + * Set the underlying listen handle. It is the user's responsibility + * to make sure that the old listen handle has been appropriately + * closed and the all outstanding asynchronous operations have + * either completed or have been canceled on the old listen handle. + */ + virtual int set_handle (ACE_HANDLE handle); + + /// This initiates a new asynchronous accept operation. + /** + * You need only call this method if the @a reissue_accept argument + * passed to @c open() was 0. + */ + virtual int accept (size_t bytes_to_read = 0, const void *act = 0); + + /** + * Cancels all pending accepts operations issued by this object. + * + * @note On Windows, only accept operations initiated by the calling thread + * are canceled. + */ + virtual int cancel (void); + + /** + * Template method to validate peer before service is opened. + * This method is called after a new connection is accepted if the + * @a validate_connection argument to @c open() was non-zero or + * the @c validate_new_connection() method is called to turn this + * feature on. The default implementation returns 0. Users can + * reimplement this method to perform validation of the peer + * using it's address, running an authentication procedure (such as + * SSL) or anything else necessary or desireable. The return value + * from this method determines whether or not ACE will continue + * opening the service or abort the connection. + * + * @param result Result of the connection acceptance. + * @param remote Peer's address. + * @param local Local address connection was accepted at. + * + * @retval -1 ACE_Asynch_Acceptor will close the connection, and + * the service will not be opened. + * @retval 0 Service opening will proceeed. + */ + virtual int validate_connection (const ACE_Asynch_Accept::Result& result, + const ACE_INET_Addr &remote, + const ACE_INET_Addr& local); + + /** + * Template method for deciding whether to reissue accept. + * + * This hook method is called after each accept completes to decide if + * another accept should be initiated. If the method returns a non-zero + * value, another accept is initiated. + * + * The default implemenation always returns the value passed as the + * @c open() method's @a reissue_accept argument. That value can also + * be changed using the @c reissue_accept() method. + */ + virtual int should_reissue_accept (void); + + // + // These are low level tweaking methods + // + + /// Get flag that indicates if parsing and passing of addresses to + /// the service_handler is necessary. + virtual bool pass_addresses (void) const; + + /// Set flag that indicates if parsing and passing of addresses to + /// the service_handler is necessary. + virtual void pass_addresses (bool new_value); + + /// Get flag that indicates if address validation is required. + virtual bool validate_new_connection (void) const; + + /// Set flag that indicates if address validation is required. + virtual void validate_new_connection (bool new_value); + + /// Get flag that indicates if a new accept should be reissued when a accept + /// completes. + virtual int reissue_accept (void) const; + + /// Set flag that indicates if a new accept should be reissued when a accept + /// completes. + virtual void reissue_accept (int new_value); + + /// Get bytes to be read with the call. + virtual size_t bytes_to_read (void) const; + + /// Set bytes to be read with the call. + virtual void bytes_to_read (size_t new_value); + + /// @deprecated address_size() assumes IPv4 use, so is not always valid. + /// This method will be removed after ACE 5.5. Internal uses have been + /// changes to base needed sizes on the addr_family_ member. + static size_t address_size (void); + +protected: + + /// This is called when an outstanding accept completes. + virtual void handle_accept (const ACE_Asynch_Accept::Result &result); + + /// Return the listen handle. + ACE_HANDLE handle (void) const; + /// Set the listen handle. + void handle (ACE_HANDLE h); + + /// This parses the address from read buffer. + void parse_address (const ACE_Asynch_Accept::Result &result, + ACE_INET_Addr &remote_address, + ACE_INET_Addr &local_address); + + /// Return the asynch accept object. + ACE_Asynch_Accept &asynch_accept (void); + + /** + * This is the template method used to create new handler. + * Subclasses must overwrite this method if a new handler creation + * strategy is required. + */ + virtual HANDLER *make_handler (void); + +private: + /// Handle used to listen for new connections. + ACE_HANDLE listen_handle_; + + /// Asynch_Accept used to make life easier :-) + ACE_Asynch_Accept asynch_accept_; + + /// Flag that indicates if parsing of addresses is necessary. + bool pass_addresses_; + + /// Flag that indicates if address validation is required. + bool validate_new_connection_; + + /// Flag that indicates if a new accept should be reissued when a + /// accept completes. + int reissue_accept_; + + /// Bytes to be read with the call. + size_t bytes_to_read_; + + /// Address family used to open this object. Obtained from @a address passed + /// to @c open(). + int addr_family_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Asynch_Acceptor.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Asynch_Acceptor.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#endif /* ACE_HAS_WIN32_OVERLAPPED_IO || ACE_HAS_AIO_CALLS */ +#include /**/ "ace/post.h" +#endif /* ACE_ASYNCH_ACCEPTOR_H */ diff --git a/dep/acelite/ace/Asynch_Connector.cpp b/dep/acelite/ace/Asynch_Connector.cpp new file mode 100644 index 00000000000..3d493069f00 --- /dev/null +++ b/dep/acelite/ace/Asynch_Connector.cpp @@ -0,0 +1,296 @@ +// $Id: Asynch_Connector.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#ifndef ACE_ASYNCH_CONNECTOR_CPP +#define ACE_ASYNCH_CONNECTOR_CPP + +#include "ace/Asynch_Connector.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if (defined (ACE_WIN32) || defined (ACE_HAS_AIO_CALLS)) && !defined(ACE_HAS_WINCE) +// This only works on platforms that support async I/O. + +#include "ace/OS_NS_sys_socket.h" +#include "ace/OS_Memory.h" +#include "ace/Flag_Manip.h" +#include "ace/Log_Msg.h" +#include "ace/Message_Block.h" +#include "ace/INET_Addr.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template +ACE_Asynch_Connector::ACE_Asynch_Connector (void) + : pass_addresses_ (false), + validate_new_connection_ (false) +{ +} + +template +ACE_Asynch_Connector::~ACE_Asynch_Connector (void) +{ + //this->asynch_connect_.close (); +} + +template int +ACE_Asynch_Connector::open (bool pass_addresses, + ACE_Proactor *proactor, + bool validate_new_connection) +{ + this->proactor (proactor); + this->pass_addresses_ = pass_addresses; + this->validate_new_connection_ = validate_new_connection; + + // Initialize the ACE_Asynch_Connect + if (this->asynch_connect_.open (*this, + ACE_INVALID_HANDLE, + 0, + this->proactor ()) == -1) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_Asynch_Connect::open")), + -1); + return 0; +} + +template int +ACE_Asynch_Connector::connect (const ACE_INET_Addr & remote_sap, + const ACE_INET_Addr & local_sap, + int reuse_addr, + const void *act) +{ + // Initiate asynchronous connect + if (this->asynch_connect_.connect (ACE_INVALID_HANDLE, + remote_sap, + local_sap, + reuse_addr, + act) == -1) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_Asynch_Connect::connect")), + -1); + return 0; +} + +template void +ACE_Asynch_Connector::handle_connect (const ACE_Asynch_Connect::Result &result) +{ + // Variable for error tracking + int error = 0; + + // If the asynchronous connect fails. + if (!result.success () || + result.connect_handle () == ACE_INVALID_HANDLE) + { + error = 1; + } + + if (result.error () != 0) + { + error = 1; + } + + // set blocking mode + if (!error && + ACE::clr_flags + (result.connect_handle (), ACE_NONBLOCK) != 0) + { + error = 1; + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_Asynch_Connector::handle_connect : Set blocking mode"))); + } + + // Parse the addresses. + ACE_INET_Addr local_address; + ACE_INET_Addr remote_address; + if (!error && + (this->validate_new_connection_ || this->pass_addresses_)) + this->parse_address (result, + remote_address, + local_address); + + // Call validate_connection even if there was an error - it's the only + // way the application can learn the connect disposition. + if (this->validate_new_connection_ && + this->validate_connection (result, remote_address, local_address) == -1) + { + error = 1; + } + + HANDLER *new_handler = 0; + if (!error) + { + // The Template method + new_handler = this->make_handler (); + if (new_handler == 0) + { + error = 1; + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_Asynch_Connector::handle_connect : Making of new handler failed"))); + } + } + + // If no errors + if (!error) + { + // Update the Proactor. + new_handler->proactor (this->proactor ()); + + // Pass the addresses + if (this->pass_addresses_) + new_handler->addresses (remote_address, + local_address); + + // Pass the ACT + if (result.act () != 0) + new_handler->act (result.act ()); + + // Set up the handler's new handle value + new_handler->handle (result.connect_handle ()); + + ACE_Message_Block mb; + + // Initiate the handler with empty message block; + new_handler->open (result.connect_handle (), mb); + } + + // On failure, no choice but to close the socket + if (error && + result.connect_handle() != ACE_INVALID_HANDLE) + ACE_OS::closesocket (result.connect_handle ()); +} + +template int +ACE_Asynch_Connector::validate_connection + (const ACE_Asynch_Connect::Result &, + const ACE_INET_Addr & /* remote_address */, + const ACE_INET_Addr & /* local_address */) +{ + // Default implementation always validates the remote address. + return 0; +} + +template int +ACE_Asynch_Connector::cancel (void) +{ + return this->asynch_connect_.cancel (); +} + +template void +ACE_Asynch_Connector::parse_address (const ACE_Asynch_Connect::Result &result, + ACE_INET_Addr &remote_address, + ACE_INET_Addr &local_address) +{ +#if defined (ACE_HAS_IPV6) + // Getting the addresses. + sockaddr_in6 local_addr; + sockaddr_in6 remote_addr; +#else + // Getting the addresses. + sockaddr_in local_addr; + sockaddr_in remote_addr; +#endif /* ACE_HAS_IPV6 */ + + // Get the length. + int local_size = sizeof (local_addr); + int remote_size = sizeof (remote_addr); + + // Get the local address. + if (ACE_OS::getsockname (result.connect_handle (), + reinterpret_cast (&local_addr), + &local_size) < 0) + ACE_ERROR ((LM_ERROR, + ACE_TEXT("%p\n"), + ACE_TEXT("ACE_Asynch_Connector:: failed"))); + + // Get the remote address. + if (ACE_OS::getpeername (result.connect_handle (), + reinterpret_cast (&remote_addr), + &remote_size) < 0) + ACE_ERROR ((LM_ERROR, + ACE_TEXT("%p\n"), + ACE_TEXT("ACE_Asynch_Connector:: failed"))); + + // Set the addresses. + local_address.set (reinterpret_cast (&local_addr), + local_size); + remote_address.set (reinterpret_cast (&remote_addr), + remote_size); + +#if 0 + // @@ Just debugging. + char local_address_buf [BUFSIZ]; + char remote_address_buf [BUFSIZ]; + + if (local_address.addr_to_string (local_address_buf, + sizeof local_address_buf) == -1) + ACE_ERROR ((LM_ERROR, + "Error:%m:can't obtain local_address's address string")); + + ACE_DEBUG ((LM_DEBUG, + "ACE_Asynch_Connector::parse_address : " + "Local address %s\n", + local_address_buf)); + + if (remote_address.addr_to_string (remote_address_buf, + sizeof remote_address_buf) == -1) + ACE_ERROR ((LM_ERROR, + "Error:%m:can't obtain remote_address's address string")); + + ACE_DEBUG ((LM_DEBUG, + "ACE_Asynch_Connector::parse_address : " + "Remote address %s\n", + remote_address_buf)); +#endif /* 0 */ + + return; +} + + +template ACE_Asynch_Connect & +ACE_Asynch_Connector::asynch_connect (void) +{ + return this->asynch_connect_; +} + +template HANDLER * +ACE_Asynch_Connector::make_handler (void) +{ + // Default behavior + HANDLER *handler = 0; + ACE_NEW_RETURN (handler, HANDLER, 0); + return handler; +} + +template bool +ACE_Asynch_Connector::pass_addresses (void) const +{ + return this->pass_addresses_; +} + +template void +ACE_Asynch_Connector::pass_addresses (bool new_value) +{ + this->pass_addresses_ = new_value; +} + +template bool +ACE_Asynch_Connector::validate_new_connection (void) const +{ + return this->validate_new_connection_; +} + +template void +ACE_Asynch_Connector::validate_new_connection (bool new_value) +{ + this->validate_new_connection_ = new_value; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_WIN32 || ACE_HAS_AIO_CALLS */ +#endif /* ACE_ASYNCH_CONNECTOR_CPP */ diff --git a/dep/acelite/ace/Asynch_Connector.h b/dep/acelite/ace/Asynch_Connector.h new file mode 100644 index 00000000000..7c7969cc20d --- /dev/null +++ b/dep/acelite/ace/Asynch_Connector.h @@ -0,0 +1,171 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file Asynch_Connector.h + * + * $Id: Asynch_Connector.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Alexander Libman + */ +//============================================================================= + +#ifndef ACE_ASYNCH_CONNECTOR_H +#define ACE_ASYNCH_CONNECTOR_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if (defined (ACE_WIN32) || defined (ACE_HAS_AIO_CALLS)) && !defined(ACE_HAS_WINCE) +// This only works on platforms that support async i/o. + +#include "ace/Asynch_IO.h" +#include "ace/INET_Addr.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Forward declarations +class ACE_Message_Block; + +/** + * @class ACE_Asynch_Connector + * + * @brief This class is an example of the Connector pattern. This class + * will establish new connections and create new HANDLER objects to handle + * the new connections. + * + * Unlike the ACE_Connector, however, this class is designed to + * be used asynchronously with the ACE Proactor framework. + */ + +template +class ACE_Asynch_Connector : public ACE_Handler +{ +public: + /// A do nothing constructor. + ACE_Asynch_Connector (void); + + /// Virtual destruction + virtual ~ACE_Asynch_Connector (void); + + /** + * This opens asynch connector + */ + virtual int open (bool pass_addresses = false, + ACE_Proactor *proactor = 0, + bool validate_new_connection = true); + + /// This initiates a new asynchronous connect + virtual int connect (const ACE_INET_Addr &remote_sap, + const ACE_INET_Addr &local_sap = + (const ACE_INET_Addr &)ACE_Addr::sap_any, + int reuse_addr = 1, + const void *act = 0); + + /** + * This cancels all pending accepts operations that were issued by + * the calling thread. + * + * @note On Windows, this method does not cancel connect operations + * issued by other threads. + * + * @note On POSIX, delegates cancelation to ACE_POSIX_Asynch_Connect. + */ + virtual int cancel (void); + + + /** + * Template method to validate peer before service is opened. + * This method is called when the connection attempt completes, + * whether it succeeded or failed, if the @a validate_connection + * argument to @c open() was non-zero or the @c validate_new_connection() + * method is called to turn this feature on. The default implementation + * returns 0. Users can (and probably should) reimplement this method + * to learn about the success or failure of the connection attempt. + * If the connection completed successfully, this method can be used to + * perform validation of the peer using it's address, running an + * authentication procedure (such as SSL) or anything else necessary or + * desireable. The return value from this method determines whether or + * not ACE will continue opening the service or abort the connection. + * + * @param result Result of the connection acceptance. Use + * result.success() to determine success or failure of + * the connection attempt. + * @param remote Peer's address. If the connection failed, this object + * is undefined. + * @param local Local address connection was completed from. If the + * connection failed, this object is undefined. + * + * @retval -1 ACE_Asynch_Connector will close the connection, and + * the service will not be opened. + * @retval 0 Service opening will proceeed. + * @return Return value is ignored if the connection attempt failed. + */ + virtual int validate_connection (const ACE_Asynch_Connect::Result& result, + const ACE_INET_Addr &remote, + const ACE_INET_Addr& local); + + // + // These are low level tweaking methods + // + + /// Set and get flag that indicates if parsing and passing of + /// addresses to the service_handler is necessary. + virtual bool pass_addresses (void) const; + virtual void pass_addresses (bool new_value); + + /// Set and get flag that indicates if address validation is + /// required. + virtual bool validate_new_connection (void) const; + virtual void validate_new_connection (bool new_value); + +protected: + + /// This is called when an outstanding accept completes. + virtual void handle_connect (const ACE_Asynch_Connect::Result &result); + + + /// This parses the address from read buffer. + void parse_address (const ACE_Asynch_Connect::Result &result, + ACE_INET_Addr &remote_address, + ACE_INET_Addr &local_address); + + /// Return the asynch Connect object. + ACE_Asynch_Connect & asynch_connect (void); + + /** + * This is the template method used to create new handler. + * Subclasses must overwrite this method if a new handler creation + * strategy is required. + */ + virtual HANDLER *make_handler (void); + +private: + + /// Asynch_Connect used to make life easier :-) + ACE_Asynch_Connect asynch_connect_; + + /// Flag that indicates if parsing of addresses is necessary. + bool pass_addresses_; + + /// Flag that indicates if address validation is required. + bool validate_new_connection_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Asynch_Connector.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Asynch_Connector.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#endif /* ACE_WIN32 || ACE_HAS_AIO_CALLS */ +#include /**/ "ace/post.h" +#endif /* ACE_ASYNCH_CONNECTOR_H */ diff --git a/dep/acelite/ace/Asynch_IO.cpp b/dep/acelite/ace/Asynch_IO.cpp new file mode 100644 index 00000000000..26bba31a3a9 --- /dev/null +++ b/dep/acelite/ace/Asynch_IO.cpp @@ -0,0 +1,1414 @@ +// $Id: Asynch_IO.cpp 82559 2008-08-07 20:23:07Z parsons $ + +#include "ace/Asynch_IO.h" + +ACE_RCSID(ace, Asynch_IO, "$Id: Asynch_IO.cpp 82559 2008-08-07 20:23:07Z parsons $") + +#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) || defined (ACE_HAS_AIO_CALLS) +// This only works on platforms with Asynchronous IO + +#include "ace/Proactor.h" +#include "ace/Message_Block.h" +#include "ace/INET_Addr.h" +#include "ace/Asynch_IO_Impl.h" +#include "ace/os_include/os_errno.h" +#include "ace/Truncate.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +size_t +ACE_Asynch_Result::bytes_transferred (void) const +{ + return this->implementation ()->bytes_transferred (); +} + +const void * +ACE_Asynch_Result::act (void) const +{ + return this->implementation ()->act (); +} + +int +ACE_Asynch_Result::success (void) const +{ + return this->implementation ()->success (); +} + +const void * +ACE_Asynch_Result::completion_key (void) const +{ + return this->implementation ()->completion_key (); +} + +unsigned long +ACE_Asynch_Result::error (void) const +{ + return this->implementation ()->error (); +} + +ACE_HANDLE +ACE_Asynch_Result::event (void) const +{ + return this->implementation ()->event (); +} + +unsigned long +ACE_Asynch_Result::offset (void) const +{ + return this->implementation ()->offset (); +} + +unsigned long +ACE_Asynch_Result::offset_high (void) const +{ + return this->implementation ()->offset_high (); +} + +int +ACE_Asynch_Result::priority (void) const +{ + return this->implementation ()->priority (); +} + +int +ACE_Asynch_Result::signal_number (void) const +{ + return this->implementation ()->signal_number (); +} + +ACE_Asynch_Result::ACE_Asynch_Result (ACE_Asynch_Result_Impl *implementation) + : implementation_ (implementation) +{ +} + +ACE_Asynch_Result::~ACE_Asynch_Result (void) +{ + // Proactor deletes the implementation when the finishes. +} + +ACE_Asynch_Result_Impl * +ACE_Asynch_Result::implementation (void) const +{ + return this->implementation_; +} + +// ********************************************************************* + +int +ACE_Asynch_Operation::open (ACE_Handler &handler, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor) +{ + return this->implementation ()->open (handler.proxy (), + handle, + completion_key, + proactor); +} + +int +ACE_Asynch_Operation::cancel (void) +{ + if (0 == this->implementation ()) + { + errno = EFAULT; + return -1; + } + return this->implementation ()->cancel (); +} + +ACE_Proactor * +ACE_Asynch_Operation::proactor (void) const +{ + if (0 == this->implementation ()) + { + errno = EFAULT; + return 0; + } + return this->implementation ()->proactor (); +} + +ACE_Asynch_Operation::ACE_Asynch_Operation (void) +{ +} + +ACE_Asynch_Operation::~ACE_Asynch_Operation (void) +{ +} + +ACE_Proactor * +ACE_Asynch_Operation::get_proactor (ACE_Proactor *user_proactor, + ACE_Handler &handler) const +{ + if (user_proactor == 0) + { + // Grab the singleton proactor if proactor> is zero + user_proactor = handler.proactor (); + if (user_proactor == 0) + user_proactor = ACE_Proactor::instance (); + } + + return user_proactor; +} + +// ************************************************************ + +ACE_Asynch_Read_Stream::ACE_Asynch_Read_Stream (void) + : implementation_ (0) +{ +} + +ACE_Asynch_Read_Stream::~ACE_Asynch_Read_Stream (void) +{ + // Delete the implementation. + delete this->implementation_; + this->implementation_ = 0; +} + +int +ACE_Asynch_Read_Stream::open (ACE_Handler &handler, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor) +{ + // Get a proactor for/from the user. + proactor = this->get_proactor (proactor, handler); + + // Now let us get the implementation initialized. + if ((this->implementation_ = proactor->create_asynch_read_stream ()) == 0) + return -1; + + // Call the method of the base class. + return ACE_Asynch_Operation::open (handler, + handle, + completion_key, + proactor); +} + +int +ACE_Asynch_Read_Stream::read (ACE_Message_Block &message_block, + size_t bytes_to_read, + const void *act, + int priority, + int signal_number) +{ + if (0 == this->implementation_) + { + errno = EFAULT; + return -1; + } + return this->implementation_->read (message_block, + bytes_to_read, + act, + priority, + signal_number); +} + +#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) +int +ACE_Asynch_Read_Stream::readv (ACE_Message_Block &message_block, + size_t bytes_to_read, + const void *act, + int priority, + int signal_number) +{ + if (0 == this->implementation_) + { + errno = EFAULT; + return -1; + } + return this->implementation_->readv (message_block, + bytes_to_read, + act, + priority, + signal_number); +} +#endif /* ACE_HAS_WIN32_OVERLAPPED_IO */ + +ACE_Asynch_Operation_Impl * +ACE_Asynch_Read_Stream::implementation (void) const +{ + return this->implementation_; +} + +// ************************************************************ + +size_t +ACE_Asynch_Read_Stream::Result::bytes_to_read (void) const +{ + return this->implementation ()->bytes_to_read (); +} + +ACE_Message_Block & +ACE_Asynch_Read_Stream::Result::message_block (void) const +{ + return this->implementation ()->message_block (); +} + +ACE_HANDLE +ACE_Asynch_Read_Stream::Result::handle (void) const +{ + return this->implementation ()->handle (); +} + +ACE_Asynch_Read_Stream::Result::Result (ACE_Asynch_Read_Stream_Result_Impl *implementation) + : ACE_Asynch_Result (implementation), + implementation_ (implementation) +{ +} + +ACE_Asynch_Read_Stream::Result::~Result (void) +{ + // Proactor will delete the implementation after is + // finished. +} + +ACE_Asynch_Read_Stream_Result_Impl * +ACE_Asynch_Read_Stream::Result::implementation (void) const +{ + return this->implementation_; +} + +// *************************************************** + +ACE_Asynch_Write_Stream::ACE_Asynch_Write_Stream (void) + : implementation_ (0) +{ +} + +ACE_Asynch_Write_Stream::~ACE_Asynch_Write_Stream (void) +{ + // Delete the implementation. + delete this->implementation_; + this->implementation_ = 0; +} + +int +ACE_Asynch_Write_Stream::open (ACE_Handler &handler, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor) +{ + // Get a proactor for/from the user. + proactor = this->get_proactor (proactor, handler); + + // Now let us get the implementation initialized. + if ((this->implementation_ = proactor->create_asynch_write_stream ()) == 0) + return -1; + + // Call the method of the base class. + return ACE_Asynch_Operation::open (handler, + handle, + completion_key, + proactor); +} + +int +ACE_Asynch_Write_Stream::write (ACE_Message_Block &message_block, + size_t bytes_to_write, + const void *act, + int priority, + int signal_number) +{ + if (0 == this->implementation_) + { + errno = EFAULT; + return -1; + } + return this->implementation_->write (message_block, + bytes_to_write, + act, + priority, + signal_number); +} + +#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) +int +ACE_Asynch_Write_Stream::writev (ACE_Message_Block &message_block, + size_t bytes_to_write, + const void *act, + int priority, + int signal_number) +{ + if (0 == this->implementation_) + { + errno = EFAULT; + return -1; + } + return this->implementation_->writev (message_block, + bytes_to_write, + act, + priority, + signal_number); +} +#endif /* ACE_HAS_WIN32_OVERLAPPED_IO */ + +ACE_Asynch_Operation_Impl * +ACE_Asynch_Write_Stream::implementation (void) const +{ + return this->implementation_; +} + +// ************************************************************ + +size_t +ACE_Asynch_Write_Stream::Result::bytes_to_write (void) const +{ + return this->implementation ()->bytes_to_write (); +} + +ACE_Message_Block & +ACE_Asynch_Write_Stream::Result::message_block (void) const +{ + return this->implementation ()->message_block (); +} + +ACE_HANDLE +ACE_Asynch_Write_Stream::Result::handle (void) const +{ + return this->implementation ()->handle (); +} + +ACE_Asynch_Write_Stream::Result::Result (ACE_Asynch_Write_Stream_Result_Impl *implementation) + : ACE_Asynch_Result (implementation), + implementation_ (implementation) +{ +} + +ACE_Asynch_Write_Stream::Result::~Result (void) +{ + // Proactor will delte the implementation when the call + // finishes. +} + +ACE_Asynch_Write_Stream_Result_Impl * +ACE_Asynch_Write_Stream::Result::implementation (void) const +{ + return this->implementation_; +} + +// ************************************************************ + +ACE_Asynch_Read_File::ACE_Asynch_Read_File (void) + : implementation_ (0) +{ +} + +ACE_Asynch_Read_File::~ACE_Asynch_Read_File (void) +{ + // Delete the implementation. + delete this->implementation_; + this->implementation_ = 0; +} + +int +ACE_Asynch_Read_File::open (ACE_Handler &handler, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor) +{ + // Get a proactor for/from the user. + proactor = this->get_proactor (proactor, handler); + + // Now let us get the implementation initialized. + if ((this->implementation_ = proactor->create_asynch_read_file ()) == 0) + return -1; + + // Call the method of the base class. + return ACE_Asynch_Operation::open (handler, + handle, + completion_key, + proactor); +} + +int +ACE_Asynch_Read_File::read (ACE_Message_Block &message_block, + size_t bytes_to_read, + unsigned long offset, + unsigned long offset_high, + const void *act, + int priority, + int signal_number) +{ + if (0 == this->implementation_) + { + errno = EFAULT; + return -1; + } + return this->implementation_->read (message_block, + bytes_to_read, + offset, + offset_high, + act, + priority, + signal_number); +} + +#if (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) +int +ACE_Asynch_Read_File::readv (ACE_Message_Block &message_block, + size_t bytes_to_read, + unsigned long offset, + unsigned long offset_high, + const void *act, + int priority, + int signal_number) +{ + if (0 == this->implementation_) + { + errno = EFAULT; + return -1; + } + return this->implementation_->readv (message_block, + bytes_to_read, + offset, + offset_high, + act, + priority, + signal_number); +} +#endif /* (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) */ + +ACE_Asynch_Operation_Impl * +ACE_Asynch_Read_File::implementation (void) const +{ + return this->implementation_; +} + +// ************************************************************ + +ACE_Asynch_Read_File::Result::Result (ACE_Asynch_Read_File_Result_Impl *implementation) + : ACE_Asynch_Read_Stream::Result (implementation), + implementation_ (implementation) +{ +} + +ACE_Asynch_Read_File::Result::~Result (void) +{ + // Proactor will delete the implementation when call + // completes. +} + +ACE_Asynch_Read_File_Result_Impl * +ACE_Asynch_Read_File::Result::implementation (void) const +{ + return this->implementation_; +} + +// ************************************************************ + +ACE_Asynch_Write_File::ACE_Asynch_Write_File (void) + : implementation_ (0) +{ +} + +ACE_Asynch_Write_File::~ACE_Asynch_Write_File (void) +{ + // Delete the implementation. + delete this->implementation_; + this->implementation_ = 0; +} + +int +ACE_Asynch_Write_File::open (ACE_Handler &handler, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor) +{ + // Get a proactor for/from the user. + proactor = this->get_proactor (proactor, handler); + + // Now let us get the implementation initialized. + if ((this->implementation_ = proactor->create_asynch_write_file ()) == 0) + return -1; + + // Call the method of the base class. + return ACE_Asynch_Operation::open (handler, + handle, + completion_key, + proactor); +} + +int +ACE_Asynch_Write_File::write (ACE_Message_Block &message_block, + size_t bytes_to_write, + unsigned long offset, + unsigned long offset_high, + const void *act, + int priority, + int signal_number) +{ + if (0 == this->implementation_) + { + errno = EFAULT; + return -1; + } + return this->implementation_->write (message_block, + bytes_to_write, + offset, + offset_high, + act, + priority, + signal_number); +} + +#if (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) +int +ACE_Asynch_Write_File::writev (ACE_Message_Block &message_block, + size_t bytes_to_write, + unsigned long offset, + unsigned long offset_high, + const void *act, + int priority, + int signal_number) +{ + if (0 == this->implementation_) + { + errno = EFAULT; + return -1; + } + return this->implementation_->writev (message_block, + bytes_to_write, + offset, + offset_high, + act, + priority, + signal_number); +} +#endif /* (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) */ + +ACE_Asynch_Operation_Impl * +ACE_Asynch_Write_File::implementation (void) const +{ + return this->implementation_; +} + +// ************************************************************ + +ACE_Asynch_Write_File::Result::Result (ACE_Asynch_Write_File_Result_Impl *implementation) + : ACE_Asynch_Write_Stream::Result (implementation), + implementation_ (implementation) +{ +} + +ACE_Asynch_Write_File::Result::~Result (void) +{ + // Proactor will delete the implementation when the call + // completes. +} + +ACE_Asynch_Write_File_Result_Impl * +ACE_Asynch_Write_File::Result::implementation (void) const +{ + return this->implementation_; +} + +// ********************************************************************* + +ACE_Asynch_Accept::ACE_Asynch_Accept (void) + : implementation_ (0) +{ +} + +ACE_Asynch_Accept::~ACE_Asynch_Accept (void) +{ + // Delete the implementation. + delete this->implementation_; + this->implementation_ = 0; +} + +int +ACE_Asynch_Accept::open (ACE_Handler &handler, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor) +{ + // Get a proactor for/from the user. + proactor = this->get_proactor (proactor, handler); + + // Now let us get the implementation initialized. + if ((this->implementation_ = proactor->create_asynch_accept ()) == 0) + return -1; + + // Call the method of the base class. + return ACE_Asynch_Operation::open (handler, + handle, + completion_key, + proactor); +} + +int +ACE_Asynch_Accept::accept (ACE_Message_Block &message_block, + size_t bytes_to_read, + ACE_HANDLE accept_handle, + const void *act, + int priority, + int signal_number, + int addr_family) +{ + if (0 == this->implementation_) + { + errno = EFAULT; + return -1; + } + return this->implementation_->accept (message_block, + bytes_to_read, + accept_handle, + act, + priority, + signal_number, + addr_family); +} + +ACE_Asynch_Operation_Impl * +ACE_Asynch_Accept::implementation (void) const +{ + return this->implementation_; +} + +// ************************************************************ + +size_t +ACE_Asynch_Accept::Result::bytes_to_read (void) const +{ + return this->implementation ()->bytes_to_read (); +} + +ACE_Message_Block & +ACE_Asynch_Accept::Result::message_block (void) const +{ + return this->implementation ()->message_block (); +} + +ACE_HANDLE +ACE_Asynch_Accept::Result::listen_handle (void) const +{ + return this->implementation ()->listen_handle (); +} + +ACE_HANDLE +ACE_Asynch_Accept::Result::accept_handle (void) const +{ + return this->implementation ()->accept_handle (); +} + +ACE_Asynch_Accept::Result::Result (ACE_Asynch_Accept_Result_Impl *implementation) + : ACE_Asynch_Result (implementation), + implementation_ (implementation) +{ +} + +ACE_Asynch_Accept::Result::~Result (void) +{ + // Proactor will delete the implementation when the call + // completes. +} + +ACE_Asynch_Accept_Result_Impl * +ACE_Asynch_Accept::Result::implementation (void) const +{ + return this->implementation_; +} + + + +// ********************************************************************* + +ACE_Asynch_Connect::ACE_Asynch_Connect (void) + : implementation_ (0) +{ +} + +ACE_Asynch_Connect::~ACE_Asynch_Connect (void) +{ + // Delete the implementation. + delete this->implementation_; + this->implementation_ = 0; +} + +int +ACE_Asynch_Connect::open (ACE_Handler &handler, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor) +{ + // Get a proactor for/from the user. + proactor = this->get_proactor (proactor, handler); + + // Now let us get the implementation initialized. + if ((this->implementation_ = proactor->create_asynch_connect ()) == 0) + return -1; + + // Call the method of the base class. + return ACE_Asynch_Operation::open (handler, + handle, + completion_key, + proactor); +} + +int +ACE_Asynch_Connect::connect (ACE_HANDLE connect_handle, + const ACE_Addr & remote_sap, + const ACE_Addr & local_sap, + int reuse_addr, + const void *act, + int priority, + int signal_number) +{ + if (0 == this->implementation_) + { + errno = EFAULT; + return -1; + } + return this->implementation_->connect (connect_handle, + remote_sap, + local_sap, + reuse_addr, + act, + priority, + signal_number); +} + +ACE_Asynch_Operation_Impl * +ACE_Asynch_Connect::implementation (void) const +{ + return this->implementation_; +} + +// ************************************************************ + +ACE_Asynch_Connect::Result::Result (ACE_Asynch_Connect_Result_Impl *implementation) + : ACE_Asynch_Result (implementation), + implementation_ (implementation) +{ +} + +ACE_Asynch_Connect::Result::~Result (void) +{ + // Proactor will delete the implementation when the call + // completes. +} + +ACE_HANDLE +ACE_Asynch_Connect::Result::connect_handle (void) const +{ + return this->implementation ()->connect_handle (); +} + + +ACE_Asynch_Connect_Result_Impl * +ACE_Asynch_Connect::Result::implementation (void) const +{ + return this->implementation_; +} + +// ************************************************************ + +ACE_Asynch_Transmit_File::ACE_Asynch_Transmit_File (void) + : implementation_ (0) +{ +} + +ACE_Asynch_Transmit_File::~ACE_Asynch_Transmit_File (void) +{ + // Delete the implementation. + delete this->implementation_; + this->implementation_ = 0; +} + +int +ACE_Asynch_Transmit_File::open (ACE_Handler &handler, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor) +{ + // Get a proactor for/from the user. + proactor = this->get_proactor (proactor, handler); + + // Now let us get the implementation initialized. + if ((this->implementation_ = proactor->create_asynch_transmit_file ()) == 0) + return -1; + + // Call the method of the base class. + return ACE_Asynch_Operation::open (handler, + handle, + completion_key, + proactor); +} + +int +ACE_Asynch_Transmit_File::transmit_file (ACE_HANDLE file, + Header_And_Trailer *header_and_trailer, + size_t bytes_to_write, + unsigned long offset, + unsigned long offset_high, + size_t bytes_per_send, + unsigned long flags, + const void *act, + int priority, + int signal_number) +{ + if (0 == this->implementation_) + { + errno = EFAULT; + return -1; + } + return this->implementation_->transmit_file (file, + header_and_trailer, + bytes_to_write, + offset, + offset_high, + bytes_per_send, + flags, + act, + priority, + signal_number); +} + +ACE_Asynch_Operation_Impl * +ACE_Asynch_Transmit_File::implementation (void) const +{ + return this->implementation_; +} + +// **************************************************************************** + +ACE_HANDLE +ACE_Asynch_Transmit_File::Result::socket (void) const +{ + return this->implementation ()->socket (); +} + +ACE_HANDLE +ACE_Asynch_Transmit_File::Result::file (void) const +{ + return this->implementation ()->file (); +} + +ACE_Asynch_Transmit_File::Header_And_Trailer * +ACE_Asynch_Transmit_File::Result::header_and_trailer (void) const +{ + return this->implementation ()->header_and_trailer (); +} + +size_t +ACE_Asynch_Transmit_File::Result::bytes_to_write (void) const +{ + return this->implementation ()->bytes_to_write (); +} + +size_t +ACE_Asynch_Transmit_File::Result::bytes_per_send (void) const +{ + return this->implementation ()->bytes_per_send (); +} + +unsigned long +ACE_Asynch_Transmit_File::Result::flags (void) const +{ + return this->implementation ()->flags (); +} + +ACE_Asynch_Transmit_File::Result::Result (ACE_Asynch_Transmit_File_Result_Impl *implementation) + : ACE_Asynch_Result (implementation), + implementation_ (implementation) +{ +} + +ACE_Asynch_Transmit_File::Result::~Result (void) +{ +} + +ACE_Asynch_Transmit_File_Result_Impl * +ACE_Asynch_Transmit_File::Result::implementation (void) const +{ + return this->implementation_; +} + +// ************************************************************ + +ACE_Asynch_Transmit_File::Header_And_Trailer::Header_And_Trailer (ACE_Message_Block *header, + size_t header_bytes, + ACE_Message_Block *trailer, + size_t trailer_bytes) + : header_ (header), + header_bytes_ (header_bytes), + trailer_ (trailer), + trailer_bytes_ (trailer_bytes) +{ +} + +ACE_Asynch_Transmit_File::Header_And_Trailer::~Header_And_Trailer (void) +{ +} + +void +ACE_Asynch_Transmit_File::Header_And_Trailer::header_and_trailer (ACE_Message_Block *header, + size_t header_bytes, + ACE_Message_Block *trailer, + size_t trailer_bytes) +{ + this->header (header); + this->header_bytes (header_bytes); + this->trailer (trailer); + this->trailer_bytes (trailer_bytes); +} + +ACE_Message_Block * +ACE_Asynch_Transmit_File::Header_And_Trailer::header (void) const +{ + return this->header_; +} + +void +ACE_Asynch_Transmit_File::Header_And_Trailer::header (ACE_Message_Block *message_block) +{ + this->header_ = message_block; +} + +size_t +ACE_Asynch_Transmit_File::Header_And_Trailer::header_bytes (void) const +{ + return this->header_bytes_; +} + +void +ACE_Asynch_Transmit_File::Header_And_Trailer::header_bytes (size_t bytes) +{ + this->header_bytes_ = bytes; +} + +ACE_Message_Block * +ACE_Asynch_Transmit_File::Header_And_Trailer::trailer (void) const +{ + return this->trailer_; +} + +void +ACE_Asynch_Transmit_File::Header_And_Trailer::trailer (ACE_Message_Block *message_block) +{ + this->trailer_ = message_block; +} + +size_t +ACE_Asynch_Transmit_File::Header_And_Trailer::trailer_bytes (void) const +{ + return this->trailer_bytes_; +} + +void +ACE_Asynch_Transmit_File::Header_And_Trailer::trailer_bytes (size_t bytes) +{ + this->trailer_bytes_ = bytes; +} + +ACE_LPTRANSMIT_FILE_BUFFERS +ACE_Asynch_Transmit_File::Header_And_Trailer::transmit_buffers (void) +{ + // If both are zero, return zero + if (this->header_ == 0 && this->trailer_ == 0) + { + return 0; + } + else + { + // Something is valid + + // If header is valid, set the fields + if (this->header_ != 0) + { + this->transmit_buffers_.Head = this->header_->rd_ptr (); +#if defined (ACE_WIN64) || defined (ACE_WIN32) + this->transmit_buffers_.HeadLength = + ACE_Utils::truncate_cast (this->header_bytes_); +#else + this->transmit_buffers_.HeadLength = this->header_bytes_; +#endif /* ACE_WIN64 || ACE_WIN32 */ + } + else + { + this->transmit_buffers_.Head = 0; + this->transmit_buffers_.HeadLength = 0; + } + + // If trailer is valid, set the fields + if (this->trailer_ != 0) + { + this->transmit_buffers_.Tail = this->trailer_->rd_ptr (); +#if defined(ACE_WIN64) || defined (ACE_WIN32) + this->transmit_buffers_.TailLength = + ACE_Utils::truncate_cast (this->trailer_bytes_); +#else + this->transmit_buffers_.TailLength = this->trailer_bytes_; +#endif /* ACE_WIN64 || ACE_WIN32 */ + } + else + { + this->transmit_buffers_.Tail = 0; + this->transmit_buffers_.TailLength = 0; + } + + // Return the transmit buffers + return &this->transmit_buffers_; + } +} + +// ********************************************************************* + +ACE_Handler::ACE_Handler (void) + : proactor_ (0), handle_ (ACE_INVALID_HANDLE) +{ + ACE_Handler::Proxy *p; + ACE_NEW (p, ACE_Handler::Proxy (this)); + this->proxy_.reset (p); +} + +ACE_Handler::ACE_Handler (ACE_Proactor *d) + : proactor_ (d), handle_ (ACE_INVALID_HANDLE) +{ + ACE_Handler::Proxy *p; + ACE_NEW (p, ACE_Handler::Proxy (this)); + this->proxy_.reset (p); +} + +ACE_Handler::~ACE_Handler (void) +{ + ACE_Handler::Proxy *p = this->proxy_.get (); + if (p) + p->reset (); +} + +void +ACE_Handler::handle_read_stream (const ACE_Asynch_Read_Stream::Result & /* result */) +{ +} + +void +ACE_Handler::handle_write_stream (const ACE_Asynch_Write_Stream::Result & /* result */) +{ +} + +void +ACE_Handler::handle_write_dgram (const ACE_Asynch_Write_Dgram::Result & /* result */) +{ +} + +void +ACE_Handler::handle_read_dgram (const ACE_Asynch_Read_Dgram::Result & /* result */) +{ +} + +void +ACE_Handler::handle_accept (const ACE_Asynch_Accept::Result & /* result */) +{ +} + +void +ACE_Handler::handle_connect (const ACE_Asynch_Connect::Result & /* result */) +{ +} + +void +ACE_Handler::handle_transmit_file (const ACE_Asynch_Transmit_File::Result & /* result */) +{ +} + +void +ACE_Handler::handle_read_file (const ACE_Asynch_Read_File::Result & /* result */) +{ +} + +void +ACE_Handler::handle_write_file (const ACE_Asynch_Write_File::Result & /* result */) +{ +} + +void +ACE_Handler::handle_time_out (const ACE_Time_Value & /* tv */, + const void * /* act */) +{ +} + +void +ACE_Handler::handle_wakeup (void) +{ +} + +ACE_Proactor * +ACE_Handler::proactor (void) +{ + return this->proactor_; +} + +void +ACE_Handler::proactor (ACE_Proactor *p) +{ + this->proactor_ = p; +} + +ACE_HANDLE +ACE_Handler::handle (void) const +{ + return this->handle_; +} + +void +ACE_Handler::handle (ACE_HANDLE h) +{ + this->handle_ = h; +} + +ACE_Refcounted_Auto_Ptr & +ACE_Handler::proxy (void) +{ + return this->proxy_; +} + +// ************************************************************ + +ACE_Service_Handler::ACE_Service_Handler (void) +{ +} + +ACE_Service_Handler::~ACE_Service_Handler (void) +{ +} + +void +ACE_Service_Handler::addresses (const ACE_INET_Addr & /* remote_address */, + const ACE_INET_Addr & /* local_address */ ) +{ +} + +void +ACE_Service_Handler::act (const void *) +{ +} + +void +ACE_Service_Handler::open (ACE_HANDLE, + ACE_Message_Block &) +{ +} + + +// ************************************************************ + +ACE_Asynch_Read_Dgram::ACE_Asynch_Read_Dgram (void) + : implementation_ (0) +{ +} + +ACE_Asynch_Read_Dgram::~ACE_Asynch_Read_Dgram (void) +{ + // Delete the implementation. + delete this->implementation_; + this->implementation_ = 0; +} + +int +ACE_Asynch_Read_Dgram::open (ACE_Handler &handler, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor) +{ + // Get a proactor for/from the user. + proactor = this->get_proactor (proactor, handler); + + // Now let us get the implementation initialized. + if ((this->implementation_ = proactor->create_asynch_read_dgram ()) == 0) + return -1; + + // Call the method of the base class. + return ACE_Asynch_Operation::open (handler, + handle, + completion_key, + proactor); +} + +ssize_t +ACE_Asynch_Read_Dgram::recv (ACE_Message_Block *message_block, + size_t &number_of_bytes_recvd, + int flags, + int protocol_family, + const void *act, + int priority, + int signal_number) +{ + if (0 == this->implementation_) + { + errno = EFAULT; + return -1; + } + return this->implementation_->recv (message_block, + number_of_bytes_recvd, + flags, + protocol_family, + act, + priority, + signal_number); +} + +ACE_Asynch_Operation_Impl * +ACE_Asynch_Read_Dgram::implementation (void) const +{ + return this->implementation_; +} + +// ************************************************************ + +int +ACE_Asynch_Read_Dgram::Result::remote_address (ACE_Addr& addr) const +{ + return this->implementation ()->remote_address (addr); +} + +ACE_Message_Block* +ACE_Asynch_Read_Dgram::Result::message_block (void) const +{ + return this->implementation ()->message_block (); +} + +int +ACE_Asynch_Read_Dgram::Result::flags (void) const +{ + return this->implementation ()->flags (); +} + +size_t +ACE_Asynch_Read_Dgram::Result::bytes_to_read (void) const +{ + return this->implementation ()->bytes_to_read (); +} + +ACE_HANDLE +ACE_Asynch_Read_Dgram::Result::handle (void) const +{ + return this->implementation ()->handle(); +} + +ACE_Asynch_Read_Dgram::Result::Result (ACE_Asynch_Read_Dgram_Result_Impl *implementation) +: ACE_Asynch_Result (implementation), + implementation_ (implementation) +{ +} + +ACE_Asynch_Read_Dgram::Result::~Result (void) +{ +} + +ACE_Asynch_Read_Dgram_Result_Impl * +ACE_Asynch_Read_Dgram::Result::implementation (void) const +{ + return this->implementation_; +} + +// ************************************************************ + + +ACE_Asynch_Write_Dgram::ACE_Asynch_Write_Dgram (void) + : implementation_ (0) +{ +} + +ACE_Asynch_Write_Dgram::~ACE_Asynch_Write_Dgram (void) +{ + // Delete the implementation. + delete this->implementation_; + this->implementation_ = 0; +} + +int +ACE_Asynch_Write_Dgram::open (ACE_Handler &handler, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor) +{ + // Get a proactor for/from the user. + proactor = this->get_proactor (proactor, handler); + + // Now let us get the implementation initialized. + if ((this->implementation_ = proactor->create_asynch_write_dgram ()) == 0) + return -1; + + // Call the method of the base class. + return ACE_Asynch_Operation::open (handler, + handle, + completion_key, + proactor); +} + +ssize_t +ACE_Asynch_Write_Dgram::send (ACE_Message_Block *message_block, + size_t &number_of_bytes_sent, + int flags, + const ACE_Addr& remote_addr, + const void *act, + int priority, + int signal_number) +{ + if (0 == this->implementation_) + { + errno = EFAULT; + return -1; + } + return this->implementation_->send (message_block, + number_of_bytes_sent, + flags, + remote_addr, + act, + priority, + signal_number); +} + +ACE_Asynch_Operation_Impl * +ACE_Asynch_Write_Dgram::implementation (void) const +{ + return this->implementation_; +} + +// ************************************************************ + +size_t +ACE_Asynch_Write_Dgram::Result::bytes_to_write (void) const +{ + return this->implementation ()->bytes_to_write (); +} + +ACE_Message_Block* +ACE_Asynch_Write_Dgram::Result::message_block () const +{ + return this->implementation ()->message_block (); +} + +int +ACE_Asynch_Write_Dgram::Result::flags (void) const +{ + return this->implementation ()->flags (); +} + +ACE_HANDLE +ACE_Asynch_Write_Dgram::Result::handle (void) const +{ + return this->implementation ()->handle (); +} + +ACE_Asynch_Write_Dgram_Result_Impl * +ACE_Asynch_Write_Dgram::Result::implementation (void) const +{ + return this->implementation_; +} + +ACE_Asynch_Write_Dgram::Result::Result (ACE_Asynch_Write_Dgram_Result_Impl *implementation) +: ACE_Asynch_Result (implementation), + implementation_ (implementation) +{ +} + +ACE_Asynch_Write_Dgram::Result::~Result (void) +{ +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_WIN32_OVERLAPPED_IO || ACE_HAS_AIO_CALLS */ diff --git a/dep/acelite/ace/Asynch_IO.h b/dep/acelite/ace/Asynch_IO.h new file mode 100644 index 00000000000..641e22a8de4 --- /dev/null +++ b/dep/acelite/ace/Asynch_IO.h @@ -0,0 +1,1761 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file Asynch_IO.h + * + * $Id: Asynch_IO.h 84837 2009-03-16 13:01:15Z johnnyw $ + * + * This works on Win32 (defined (ACE_WIN32) && !defined + * (ACE_HAS_WINCE)) platforms and on POSIX4 platforms with {aio_*} + * routines (defined (ACE_HAS_AIO_CALLS)) + * + * On Win32 platforms, the implementation of + * {ACE_Asynch_Transmit_File} and {ACE_Asynch_Accept} are only + * supported if ACE_HAS_WINSOCK2 is defined or you are on WinNT 4.0 + * or higher. + * + * @author Irfan Pyarali + * @author Tim Harrison + * @author Alexander Babu Arulanthu + * @author Roger Tragin + * @author Alexander Libman + */ +//============================================================================= + +#ifndef ACE_ASYNCH_IO_H +#define ACE_ASYNCH_IO_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +#pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) || defined (ACE_HAS_AIO_CALLS) + +#include "ace/Synch_Traits.h" +#if defined (ACE_HAS_THREADS) +# include "ace/Thread_Mutex.h" +#else +# include "ace/Null_Mutex.h" +#endif /* ACE_HAS_THREADS */ +#include "ace/Refcounted_Auto_Ptr.h" + +#include "ace/os_include/os_signal.h" +#include "ace/os_include/sys/os_socket.h" +#include "ace/os_include/sys/os_types.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +# if defined (ACE_HAS_WIN32_OVERLAPPED_IO) +typedef TRANSMIT_FILE_BUFFERS ACE_TRANSMIT_FILE_BUFFERS; +typedef LPTRANSMIT_FILE_BUFFERS ACE_LPTRANSMIT_FILE_BUFFERS; +typedef PTRANSMIT_FILE_BUFFERS ACE_PTRANSMIT_FILE_BUFFERS; + +# define ACE_INFINITE INFINITE +# define ACE_STATUS_TIMEOUT STATUS_TIMEOUT +# define ACE_WAIT_FAILED WAIT_FAILED +# define ACE_WAIT_TIMEOUT WAIT_TIMEOUT +# else /* ACE_HAS_WIN32_OVERLAPPED_IO */ +struct ACE_TRANSMIT_FILE_BUFFERS +{ + void *Head; + size_t HeadLength; + void *Tail; + size_t TailLength; +}; +typedef ACE_TRANSMIT_FILE_BUFFERS* ACE_PTRANSMIT_FILE_BUFFERS; +typedef ACE_TRANSMIT_FILE_BUFFERS* ACE_LPTRANSMIT_FILE_BUFFERS; + +# if !defined (ACE_INFINITE) +# define ACE_INFINITE LONG_MAX +# endif /* ACE_INFINITE */ +# define ACE_STATUS_TIMEOUT LONG_MAX +# define ACE_WAIT_FAILED LONG_MAX +# define ACE_WAIT_TIMEOUT LONG_MAX +# endif /* ACE_HAS_WIN32_OVERLAPPED_IO */ + +// Forward declarations +class ACE_Proactor; +class ACE_Handler; +class ACE_Message_Block; +class ACE_INET_Addr; +class ACE_Addr; + +// Forward declarations +class ACE_Asynch_Result_Impl; +class ACE_Time_Value; + +/** + * @class ACE_Asynch_Result + * + * @brief An interface base class which allows users access to common + * information related to an asynchronous operation. + * + * An interface base class from which you can obtain some basic + * information like the number of bytes transferred, the ACT + * associated with the asynchronous operation, indication of + * success or failure, etc. Subclasses may want to store more + * information that is particular to the asynchronous operation + * it represents. + */ +class ACE_Export ACE_Asynch_Result +{ + +public: + /// Number of bytes transferred by the operation. + size_t bytes_transferred (void) const; + + /// ACT associated with the operation. + const void *act (void) const; + + /// Did the operation succeed? + int success (void) const; + + /** + * This is the ACT associated with the handle on which the + * Asynch_Operation takes place. + * + * On WIN32, this returns the ACT associated with the handle when it + * was registered with the I/O completion port. + * + * @@ This is not implemented for POSIX4 platforms. Returns 0. + */ + const void *completion_key (void) const; + + /// Error value if the operation fails. + unsigned long error (void) const; + + /** + * On WIN32, this returns the event associated with the OVERLAPPED + * structure. + * + * This returns ACE_INVALID_HANDLE on POSIX4-Unix platforms. + */ + ACE_HANDLE event (void) const; + + /** + * This really makes sense only when doing file I/O. + * + * On WIN32, these are represented in the OVERLAPPED datastructure. + * + * @@ On POSIX4-Unix, offset_high should be supported using + * aiocb64. + */ + unsigned long offset (void) const; + unsigned long offset_high (void) const; + + /** + * Priority of the operation. + * + * On POSIX4-Unix, this is supported. Priority works like {nice} in + * Unix. Negative values are not allowed. 0 means priority of the + * operation same as the process priority. 1 means priority of the + * operation is one less than process. And so forth. + * + * On Win32, this is a no-op. + */ + int priority (void) const; + + /** + * POSIX4 real-time signal number to be used for the + * operation. {signal_number} ranges from ACE_SIGRTMIN to ACE_SIGRTMAX. By + * default, ACE_SIGRTMIN is used to issue {aio_} calls. This is a no-op + * on non-POSIX4 systems and returns 0. + */ + int signal_number (void) const; + + + /// Destructor. + virtual ~ACE_Asynch_Result (void); + +protected: + /// Constructor. This implementation will not be deleted. The + /// implementation will be deleted by the Proactor. + ACE_Asynch_Result (ACE_Asynch_Result_Impl *implementation); + + /// Get the implementation class. + ACE_Asynch_Result_Impl *implementation (void) const; + + /// Implementation class. + ACE_Asynch_Result_Impl *implementation_; +}; + +// Forward declarations +class ACE_Asynch_Operation_Impl; + +/** + * @class ACE_Asynch_Operation + * + * @brief This is an interface base class for all asynch + * operations. The resposiblility of this class is to forward + * all methods to its delegation/implementation class, e.g., + * ACE_WIN32_Asynch_Operation or ACE_POSIX_Asynch_Operation. + * + * There are some attributes and functionality which is common + * to all asychronous operations. The delegation classes of this + * class will factor out this code. + */ +class ACE_Export ACE_Asynch_Operation +{ + +public: + /** + * Initializes the factory with information which will be used with + * each asynchronous call. If ({handle} == ACE_INVALID_HANDLE), + * {ACE_Handler::handle} will be called on the {handler} to get the + * correct handle. + */ + int open (ACE_Handler &handler, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor); + + /** + * (Attempts to) cancel the asynchronous operation pending against + * the {handle} registered with this Operation. + * + * All completion notifications for the I/O operations will occur + * normally. + * + * = Return Values: + * + * -1 : Operation failed. (can get only in POSIX). + * 0 : All the operations were cancelled. + * 1 : All the operations were already finished in this + * handle. Unable to cancel them. + * 2 : Atleast one of the requested operations cannot be + * cancelled. + * + * There is slight difference in the semantics between NT and POSIX + * platforms which is given below. + * + * = Win32 : + * + * cancels all pending accepts operations that were issued by the + * calling thread. The function does not cancel asynchronous + * operations issued by other threads. + * All I/O operations that are canceled will complete with the + * error ERROR_OPERATION_ABORTED. + * + * = POSIX: + * + * Attempts to cancel one or more asynchronous I/O requests + * currently outstanding against the {handle} registered in this + * operation. + * For requested operations that are successfully canceled, the + * associated error status is set to ECANCELED. + */ + int cancel (void); + + + // = Access methods. + + /// Return the underlying proactor. + ACE_Proactor* proactor (void) const; + + /// Destructor. + virtual ~ACE_Asynch_Operation (void); + +protected: + /// Constructor. + ACE_Asynch_Operation (void); + + /// Return the underlying implementation class. + virtual ACE_Asynch_Operation_Impl *implementation (void) const = 0; + + /// Get a proactor for/from the user + ACE_Proactor *get_proactor (ACE_Proactor *user_proactor, + ACE_Handler &handler) const; +}; + +// Forward declarations +class ACE_Asynch_Read_Stream_Result_Impl; +class ACE_Asynch_Read_Stream_Impl; + +/** + * @class ACE_Asynch_Read_Stream + * + * @brief This class is a factory for starting off asynchronous reads + * on a stream. This class forwards all methods to its + * implementation class. + * + * Once {open} is called, multiple asynchronous {read}s can + * started using this class. An ACE_Asynch_Read_Stream::Result + * will be passed back to the {handler} when the asynchronous + * reads completes through the {ACE_Handler::handle_read_stream} + * callback. + */ +class ACE_Export ACE_Asynch_Read_Stream : public ACE_Asynch_Operation +{ + +public: + /// A do nothing constructor. + ACE_Asynch_Read_Stream (void); + + /// Destructor + virtual ~ACE_Asynch_Read_Stream (void); + + /** + * Initializes the factory with information which will be used with + * each asynchronous call. + * + * @param handler The ACE_Handler that will be called to handle completions + * for operations initiated using this factory. + * @param handle The handle that future read operations will use. + * If handle == @c ACE_INVALID_HANDLE, + * ACE_Handler::handle() will be called on @ handler + * to get the correct handle. + * + * @retval 0 for success. + * @retval -1 for failure; consult @c errno for further information. + */ + int open (ACE_Handler &handler, + ACE_HANDLE handle = ACE_INVALID_HANDLE, + const void *completion_key = 0, + ACE_Proactor *proactor = 0); + + /** + * Initiate an asynchronous read operation. + * + * @param message_block The ACE_Message_Block to receive the data. + * Received bytes will be placed in the block + * beginning at its current write pointer. + * If data is read, the message block's write + * pointer will be advanced by the number of + * bytes read. + * @param num_bytes_to_read The maximum number of bytes to read. + * @param act Asynchronous Completion Token; passed through to + * the completion handler in the Result object. + * @param priority Priority of the operation. On POSIX4-Unix, + * this is supported. Works like @c nice in Unix. + * Negative values are not allowed. 0 means + * priority of the operation same as the process + * priority. 1 means priority of the operation is + * one less than process priority, etc. + * Ignored on Windows. + * @param signal_number The POSIX4 real-time signal number to be used + * to signal completion of the operation. Values + * range from ACE_SIGRTMIN to ACE_SIGRTMAX. + * This argument is ignored on non-POSIX4 systems. + */ + int read (ACE_Message_Block &message_block, + size_t num_bytes_to_read, + const void *act = 0, + int priority = 0, + int signal_number = ACE_SIGRTMIN); + +#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) + /** + * Same as above but with scatter support, through chaining of composite + * message blocks using the continuation field. + */ + int readv (ACE_Message_Block &message_block, + size_t num_bytes_to_read, + const void *act = 0, + int priority = 0, + int signal_number = ACE_SIGRTMIN); +#endif /* defined (ACE_HAS_WIN32_OVERLAPPED_IO) */ + + /// Return the underlying implementation class. + // (this should be protected...) + virtual ACE_Asynch_Operation_Impl *implementation (void) const; + +protected: + /// Implementation class that all methods will be forwarded to. + ACE_Asynch_Read_Stream_Impl *implementation_; + +public: +/** + * @class Result + * + * @brief This is the class which will be passed back to the + * ACE_Handler::handle_read_stream when the asynchronous read completes. + * This class forwards all the methods to the implementation classes. + * + * This class has all the information necessary for the + * handler to uniquiely identify the completion of the + * asynchronous read. + */ + class ACE_Export Result : public ACE_Asynch_Result + { + + /// The concrete implementation result classes only construct this + /// class. + friend class ACE_POSIX_Asynch_Read_Stream_Result; + friend class ACE_WIN32_Asynch_Read_Stream_Result; + + public: + /// The number of bytes which were requested at the start of the + /// asynchronous read. + size_t bytes_to_read (void) const; + + /// Message block which contains the read data. + ACE_Message_Block &message_block (void) const; + + /// I/O handle used for reading. + ACE_HANDLE handle (void) const; + + /// Get the implementation class. + ACE_Asynch_Read_Stream_Result_Impl *implementation (void) const; + + protected: + /// Constructor. + Result (ACE_Asynch_Read_Stream_Result_Impl *implementation); + + /// Destructor. + virtual ~Result (void); + + /// The implementation class. + ACE_Asynch_Read_Stream_Result_Impl *implementation_; + }; +private: + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Asynch_Read_Stream &)) + ACE_UNIMPLEMENTED_FUNC (ACE_Asynch_Read_Stream (const ACE_Asynch_Read_Stream &)) +}; + +// Forward declarations +class ACE_Asynch_Write_Stream_Impl; +class ACE_Asynch_Write_Stream_Result_Impl; + +/** + * @class ACE_Asynch_Write_Stream + * + * @brief This class is a factory for initiating asynchronous writes + * on a connected TCP/IP stream. This class forwards all methods to its + * implementation class. + * + * Once open() is called, multiple asynchronous writes can be + * started using this class. An ACE_Asynch_Write_Stream::Result + * will be passed to the ACE_Handler::handle_write_stream() method on the + * opened ACE_Handler object when the asynchronous write completes. + */ +class ACE_Export ACE_Asynch_Write_Stream : public ACE_Asynch_Operation +{ + +public: + /// A do nothing constructor. + ACE_Asynch_Write_Stream (void); + + /// Destructor. + virtual ~ACE_Asynch_Write_Stream (void); + + /** + * Initializes the factory with information which will be used with + * each asynchronous operation. + * + * @param handler ACE_Handler to be notified when operations initiated + * via this factory complete. The handle_write_stream() + * method will be called on this object. + * @param handle The socket handle to initiate write operations on. + * If handle is @c ACE_INVALID_HANDLE, + * ACE_Handler::handle() will be called on handler to + * get the handle value. + * @param completion_key A token that is passed to the completion handler. + * @param proactor The ACE_Proactor object which will control operation + * completion and dispatching the results to handler. + * If this is 0, the process's singleton ACE_Proactor + * will be used. + * + * @retval 0 for success. + * @retval -1 for failure; consult @c errno for further information. + */ + int open (ACE_Handler &handler, + ACE_HANDLE handle = ACE_INVALID_HANDLE, + const void *completion_key = 0, + ACE_Proactor *proactor = 0); + + /** + * Initiates an asynchronous write on a socket. If the operation completes + * the ACE_Handler object registered in open() will receive a completion + * callback via its handle_write_stream() method. + * + * @param bytes_to_write The number of bytes to write. + * @param message_block The ACE_Message_Block containing data to write. + * Data is written to the socket beginning at the + * block's rd_ptr. Upon successful completion + * of the write operation, the message_block rd_ptr + * is updated to reflect the data that was written. + * @param act Token that is passed through to the completion + * handler. + * @param priority Priority of the operation. This argument only has + * an affect on POSIX4-Unix. Works like @c nice in + * Unix; negative values are not allowed. 0 means + * priority of the operation same as the process + * priority. 1 means priority of the operation is one + * less than the process, and so forth. + * @param signal_number The POSIX4 real-time signal number to be used + * for the operation. signal_number ranges from + * ACE_SIGRTMIN to ACE_SIGRTMAX. This argument is + * not used on other platforms. + * + * @retval 0 for success, and the handle_write_stream associated + * with the opened ACE_Handler will be called. An + * instance of ACE_Asynch_Write_Stream::Result will be + * passed to the completion handler. + * @retval -1 for failure; consult @c errno for further information. + */ + int write (ACE_Message_Block &message_block, + size_t bytes_to_write, + const void *act = 0, + int priority = 0, + int signal_number = ACE_SIGRTMIN); + +#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) + /** + * Same as above but with gather support, through chaining of composite + * message blocks using the continuation field. + */ + int writev (ACE_Message_Block &message_block, + size_t bytes_to_write, + const void *act = 0, + int priority = 0, + int signal_number = ACE_SIGRTMIN); +#endif /* defined (ACE_HAS_WIN32_OVERLAPPED_IO) */ + + /// Return the underlying implementation class. + /// @todo (this should be protected...) + virtual ACE_Asynch_Operation_Impl *implementation (void) const; + +protected: + /// Implementation class that all methods will be forwarded to. + ACE_Asynch_Write_Stream_Impl *implementation_; + +public: +/** + * @class Result + * + * @brief This is that class which will be passed back to the + * ACE_Handler when the asynchronous write completes. This class + * forwards all the methods to the implementation class. + * + * This class has all the information necessary for the + * handler to uniquiely identify the completion of the + * asynchronous write. + */ + class ACE_Export Result : public ACE_Asynch_Result + { + + /// The concrete implementation result classes only construct this + /// class. + friend class ACE_POSIX_Asynch_Write_Stream_Result; + friend class ACE_WIN32_Asynch_Write_Stream_Result; + + public: + /// The number of bytes which were requested at the start of the + /// asynchronous write. + size_t bytes_to_write (void) const; + + /// Message block that contains the data to be written. + ACE_Message_Block &message_block (void) const; + + /// I/O handle used for writing. + ACE_HANDLE handle (void) const; + + /// Get the implementation class. + ACE_Asynch_Write_Stream_Result_Impl *implementation (void) const; + + protected: + /// Constructor. + Result (ACE_Asynch_Write_Stream_Result_Impl *implementation); + + /// Destructor. + virtual ~Result (void); + + /// Implementation class. + ACE_Asynch_Write_Stream_Result_Impl *implementation_; + }; +private: + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Asynch_Write_Stream &)) + ACE_UNIMPLEMENTED_FUNC (ACE_Asynch_Write_Stream (const ACE_Asynch_Write_Stream &)) +}; + +// Forward declarations +class ACE_Asynch_Read_File_Impl; +class ACE_Asynch_Read_File_Result_Impl; + +/** + * @class ACE_Asynch_Read_File + * + * @brief This class is a factory for starting off asynchronous reads + * on a file. This class forwards all methods to its + * implementation class. + * + * Once open() is called, multiple asynchronous reads can + * started using this class. An ACE_Asynch_Read_File::Result + * will be passed back to the completion handler's + * ACE_Handler::handle_read_file() method when each asynchronous + * read completes. + * This class differs slightly from ACE_Asynch_Read_Stream as it + * allows the user to specify an offset for the read. + */ +class ACE_Export ACE_Asynch_Read_File : public ACE_Asynch_Read_Stream +{ + +public: + /// A do nothing constructor. + ACE_Asynch_Read_File (void); + + /// Destructor. + virtual ~ACE_Asynch_Read_File (void); + + /** + * Initializes the factory with information which will be used with + * each asynchronous operation. + * + * @param handler ACE_Handler to be notified when operations initiated + * via this factory complete. The + * ACE_Handler::handle_read_file() method will be + * called on this object. + * @param handle The file handle to initiate read operations on. + * If handle is @c ACE_INVALID_HANDLE, + * ACE_Handler::handle() will be called on handler to + * get the handle value. + * @param completion_key A token that is passed to the completion handler. + * @param proactor The ACE_Proactor object which will control operation + * completion and dispatching the results to handler. + * If this is 0, the process's singleton ACE_Proactor + * will be used. + * + * @retval 0 for success. + * @retval -1 for failure; consult @c errno for further information. + */ + int open (ACE_Handler &handler, + ACE_HANDLE handle = ACE_INVALID_HANDLE, + const void *completion_key = 0, + ACE_Proactor *proactor = 0); + + /** + * This starts off an asynchronous read. Upto {bytes_to_read} will + * be read and stored in the {message_block}. The read will start + * at {offset} from the beginning of the file. Priority of the + * operation is specified by {priority}. On POSIX4-Unix, this is + * supported. Works like {nice} in Unix. Negative values are not + * allowed. 0 means priority of the operation same as the process + * priority. 1 means priority of the operation is one less than + * process. And so forth. On Win32, this argument is a no-op. + * {signal_number} is the POSIX4 real-time signal number to be used + * for the operation. {signal_number} ranges from ACE_SIGRTMIN to + * ACE_SIGRTMAX. This argument is a no-op on non-POSIX4 systems. + */ + int read (ACE_Message_Block &message_block, + size_t bytes_to_read, + unsigned long offset = 0, + unsigned long offset_high = 0, + const void *act = 0, + int priority = 0, + int signal_number = ACE_SIGRTMIN); + +#if (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) + /** + * Same as above but with scatter support, through chaining of composite + * message blocks using the continuation field. + * @note In win32 Each data block payload must be at least the size of a system + * memory page and must be aligned on a system memory page size boundary + */ + int readv (ACE_Message_Block &message_block, + size_t bytes_to_read, + unsigned long offset = 0, + unsigned long offset_high = 0, + const void *act = 0, + int priority = 0, + int signal_number = ACE_SIGRTMIN); +#endif /* (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) */ + + /// Return the underlying implementation class. + // (this should be protected...) + virtual ACE_Asynch_Operation_Impl *implementation (void) const; + +protected: + /// Delegation/implementation class that all methods will be + /// forwarded to. + ACE_Asynch_Read_File_Impl *implementation_; + +public: +/** + * @class Result + * + * @brief This is that class which will be passed back to the + * {handler} when the asynchronous read completes. This class + * forwards all the methods to the implementation class. + * + * This class has all the information necessary for the + * {handler} to uniquiely identify the completion of the + * asynchronous read. + * This class differs slightly from + * ACE_Asynch_Read_Stream::Result as it calls back + * {ACE_Handler::handle_read_file} on the {handler} instead of + * {ACE_Handler::handle_read_stream}. No additional state is + * required by this class as ACE_Asynch_Result can store the + * {offset}. + */ + class ACE_Export Result : public ACE_Asynch_Read_Stream::Result + { + + /// The concrete implementation result classes only construct this + /// class. + friend class ACE_POSIX_Asynch_Read_File_Result; + friend class ACE_WIN32_Asynch_Read_File_Result; + + public: + /// Get the implementation class. + ACE_Asynch_Read_File_Result_Impl *implementation (void) const; + + protected: + /// Constructor. This implementation will not be deleted. + Result (ACE_Asynch_Read_File_Result_Impl *implementation); + + /// Destructor. + virtual ~Result (void); + + /// The implementation class. + ACE_Asynch_Read_File_Result_Impl *implementation_; + + private: + /// Here just to provide an dummpy implementation, since the + /// one auto generated by MSVC is flagged as infinitely recursive + void operator= (Result &) {} + }; +private: + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Asynch_Read_File &)) + ACE_UNIMPLEMENTED_FUNC (ACE_Asynch_Read_File (const ACE_Asynch_Read_File &)) +}; + +// Forward declarations +class ACE_Asynch_Write_File_Impl; +class ACE_Asynch_Write_File_Result_Impl; + +/** + * @class ACE_Asynch_Write_File + * + * @brief This class is a factory for starting off asynchronous writes + * on a file. This class forwards all methods to its + * implementation class. + * + * Once {open} is called, multiple asynchronous {write}s can be + * started using this class. A ACE_Asynch_Write_File::Result + * will be passed back to the {handler} when the asynchronous + * writes completes through the {ACE_Handler::handle_write_file} + * callback. + * This class differs slightly from ACE_Asynch_Write_Stream as + * it allows the user to specify an offset for the write. + */ +class ACE_Export ACE_Asynch_Write_File : public ACE_Asynch_Write_Stream +{ + +public: + /// A do nothing constructor. + ACE_Asynch_Write_File (void); + + /// Destructor. + virtual ~ACE_Asynch_Write_File (void); + + /** + * Initializes the factory with information which will be used with + * each asynchronous call. If ({handle} == ACE_INVALID_HANDLE), + * {ACE_Handler::handle} will be called on the {handler} to get the + * correct handle. + */ + int open (ACE_Handler &handler, + ACE_HANDLE handle = ACE_INVALID_HANDLE, + const void *completion_key = 0, + ACE_Proactor *proactor = 0); + + /** + * This starts off an asynchronous write. Upto {bytes_to_write} + * will be written from the {message_block}, starting at the + * block's {rd_ptr}. The write will go to the file, starting + * {offset} bytes from the beginning of the file. Priority of the + * operation is specified by {priority}. On POSIX4-Unix, this is + * supported. Works like {nice} in Unix. Negative values are not + * allowed. 0 means priority of the operation same as the process + * priority. 1 means priority of the operation is one less than + * process. And so forth. On Win32, this is a no-op. + * {signal_number} is the POSIX4 real-time signal number to be used + * for the operation. {signal_number} ranges from ACE_SIGRTMIN to + * ACE_SIGRTMAX. This argument is a no-op on non-POSIX4 systems. + */ + int write (ACE_Message_Block &message_block, + size_t bytes_to_write, + unsigned long offset = 0, + unsigned long offset_high = 0, + const void *act = 0, + int priority = 0, + int signal_number = ACE_SIGRTMIN); + +#if (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) + /** + * Same as above but with gather support, through chaining of composite + * message blocks using the continuation field. + * @note In win32 Each data block payload must be at least the size of a system + * memory page and must be aligned on a system memory page size boundary + */ + int writev (ACE_Message_Block &message_block, + size_t bytes_to_write, + unsigned long offset = 0, + unsigned long offset_high = 0, + const void *act = 0, + int priority = 0, + int signal_number = ACE_SIGRTMIN); +#endif /* (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) */ + + /// Return the underlying implementation class. + // (this should be protected...) + virtual ACE_Asynch_Operation_Impl *implementation (void) const; + +protected: + /// Implementation object. + ACE_Asynch_Write_File_Impl *implementation_; + +public: +/** + * @class Result + * + * @brief This is that class which will be passed back to the + * {handler} when the asynchronous write completes. This class + * forwards all the methods to the implementation class. + * + * This class has all the information necessary for the + * {handler} to uniquiely identify the completion of the + * asynchronous write. + * This class differs slightly from + * ACE_Asynch_Write_Stream::Result as it calls back + * {ACE_Handler::handle_write_file} on the {handler} instead + * of {ACE_Handler::handle_write_stream}. No additional state + * is required by this class as ACE_Asynch_Result can store + * the {offset}. + */ + class ACE_Export Result : public ACE_Asynch_Write_Stream::Result + { + + /// The concrete implementation result classes only construct this + /// class. + friend class ACE_POSIX_Asynch_Write_File_Result; + friend class ACE_WIN32_Asynch_Write_File_Result; + + public: + /// Get the implementation class. + ACE_Asynch_Write_File_Result_Impl *implementation (void) const; + + protected: + /// Constructor. This implementation will not be deleted. + Result (ACE_Asynch_Write_File_Result_Impl *implementation); + + /// Destructor. + virtual ~Result (void); + + /// The implementation class. + ACE_Asynch_Write_File_Result_Impl *implementation_; + + private: + /// Here just to provide an dummpy implementation, since the + /// one auto generated by MSVC is flagged as infinitely recursive + void operator= (Result &) {}; + }; +private: + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Asynch_Write_File &)) + ACE_UNIMPLEMENTED_FUNC (ACE_Asynch_Write_File (const ACE_Asynch_Write_File &)) +}; + +// Forward declarations +class ACE_Asynch_Accept_Result_Impl; +class ACE_Asynch_Accept_Impl; + +/** + * @class ACE_Asynch_Accept + * + * @brief This class is a factory for starting off asynchronous accepts + * on a listen handle. This class forwards all methods to its + * implementation class. + * + * Once {open} is called, multiple asynchronous {accept}s can + * started using this class. A ACE_Asynch_Accept::Result will + * be passed back to the {handler} when the asynchronous accept + * completes through the {ACE_Handler::handle_accept} + * callback. + */ +class ACE_Export ACE_Asynch_Accept : public ACE_Asynch_Operation +{ + +public: + /// A do nothing constructor. + ACE_Asynch_Accept (void); + + /// Destructor. + virtual ~ACE_Asynch_Accept (void); + + /** + * Initializes the factory with information which will be used with + * each asynchronous call. If ({handle} == ACE_INVALID_HANDLE), + * {ACE_Handler::handle} will be called on the {handler} to get the + * correct handle. + */ + int open (ACE_Handler &handler, + ACE_HANDLE handle = ACE_INVALID_HANDLE, + const void *completion_key = 0, + ACE_Proactor *proactor = 0); + + /** + * This starts off an asynchronous accept. The asynchronous accept + * call also allows any initial data to be returned to the + * handler specified to @c open(). + * @param message_block A message block to receive initial data, as well + * as the local and remote addresses when the + * connection is made. Since the block receives + * the addresses regardless of whether or not + * initial data is available or requested, the + * message block size must be at least + * @a bytes_to_read plus two times the size of + * the addresses used (IPv4 or IPv6). + * @param bytes_to_read The maximum number of bytes of initial data + * to read into @a message_block. + * @param accept_handle The handle that the new connection will be + * accepted on. If @c INVALID_HANDLE, a new + * handle will be created using @a addr_family. + * @param act Value to be passed in result when operation + * completes. + * @param priority Priority of the operation. On POSIX4-Unix, this + * is supported. Works like @c nice in Unix. + * Negative values are not allowed. 0 means + * priority of the operation same as the process + * priority. 1 means priority of the operation is + * one less than process. And so forth. + * On Win32, this argument is ignored. + * @param signal_number The POSIX4 real-time signal number to be used + * for the operation. Value range is from + * @c ACE_SIGRTMIN to @c ACE_SIGRTMAX. + * This argument is ignored on non-POSIX4 systems. + * @param addr_family The address family to use if @a accept_handle + * is @c ACE_INVALID_HANDLE and a new handle must + * be opened. Values are @c AF_INET and @c PF_INET6. + */ + int accept (ACE_Message_Block &message_block, + size_t bytes_to_read, + ACE_HANDLE accept_handle = ACE_INVALID_HANDLE, + const void *act = 0, + int priority = 0, + int signal_number = ACE_SIGRTMIN, + int addr_family = AF_INET); + + /// Return the underlying implementation class. + // (this should be protected...) + virtual ACE_Asynch_Operation_Impl *implementation (void) const; + +protected: + /// Delegation/implementation class that all methods will be + /// forwarded to. + ACE_Asynch_Accept_Impl *implementation_; + +public: +/** + * @class Result + * + * @brief This is that class which will be passed back to the + * {handler} when the asynchronous accept completes. + * + * This class has all the information necessary for the + * {handler} to uniquiely identify the completion of the + * asynchronous accept. + */ + class ACE_Export Result : public ACE_Asynch_Result + { + + /// The concrete implementation result classes only construct this + /// class. + friend class ACE_POSIX_Asynch_Accept_Result; + friend class ACE_WIN32_Asynch_Accept_Result; + + public: + /// The number of bytes which were requested at the start of the + /// asynchronous accept. + size_t bytes_to_read (void) const; + + /// Message block which contains the read data. + ACE_Message_Block &message_block (void) const; + + /// I/O handle used for accepting new connections. + ACE_HANDLE listen_handle (void) const; + + /// I/O handle for the new connection. + ACE_HANDLE accept_handle (void) const; + + /// Get the implementation. + ACE_Asynch_Accept_Result_Impl *implementation (void) const; + + protected: + /// Contructor. Implementation will not be deleted. + Result (ACE_Asynch_Accept_Result_Impl *implementation); + + /// Destructor. + virtual ~Result (void); + + /// Impelmentation class. + ACE_Asynch_Accept_Result_Impl *implementation_; + }; +private: + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Asynch_Accept &)) + ACE_UNIMPLEMENTED_FUNC (ACE_Asynch_Accept (const ACE_Asynch_Accept &)) +}; +// Forward declarations +class ACE_Asynch_Connect_Result_Impl; +class ACE_Asynch_Connect_Impl; + +/** + * @class ACE_Asynch_Connect + * + * @brief This class is a factory for starting off asynchronous connects + * This class forwards all methods to its implementation class. + * + * Once @c open is called, multiple asynchronous connect operationss can + * started using this class. A ACE_Asynch_Connect::Result will + * be passed back to the associated ACE_Handler when the asynchronous connect + * completes through the ACE_Handler::handle_connect() callback. + */ +class ACE_Export ACE_Asynch_Connect : public ACE_Asynch_Operation +{ + +public: + /// A do nothing constructor. + ACE_Asynch_Connect (void); + + /// Destructor. + virtual ~ACE_Asynch_Connect (void); + + /** + * Initializes the factory with information which will be used with + * each asynchronous call. + * + * @note @arg handle is ignored and should be @c ACE_INVALID_HANDLE. + */ + int open (ACE_Handler &handler, + ACE_HANDLE handle = ACE_INVALID_HANDLE, + const void *completion_key = 0, + ACE_Proactor *proactor = 0); + + /** + * This starts off an asynchronous Connect. + */ + int connect (ACE_HANDLE connect_handle, + const ACE_Addr & remote_sap, + const ACE_Addr & local_sap, + int reuse_addr, + const void *act=0, + int priority = 0, + int signal_number = ACE_SIGRTMIN); + + /// Return the underlying implementation class. + // (this should be protected...) + virtual ACE_Asynch_Operation_Impl *implementation (void) const; + +protected: + /// Delegation/implementation class that all methods will be + /// forwarded to. + ACE_Asynch_Connect_Impl *implementation_; + +public: +/** + * @class Result + * + * @brief This is that class which will be passed back to the + * handler when the asynchronous connect completes. + * + * This class has all the information necessary for the + * handler to uniquely identify the completion of the + * asynchronous connect. + */ + class ACE_Export Result : public ACE_Asynch_Result + { + + /// The concrete implementation result classes only construct this + /// class. + friend class ACE_POSIX_Asynch_Connect_Result; + friend class ACE_WIN32_Asynch_Connect_Result; + + public: + + /// I/O handle for the connection. + ACE_HANDLE connect_handle (void) const; + + /// Get the implementation. + ACE_Asynch_Connect_Result_Impl *implementation (void) const; + + protected: + /// Contructor. Implementation will not be deleted. + Result (ACE_Asynch_Connect_Result_Impl *implementation); + + /// Destructor. + virtual ~Result (void); + + /// Impelmentation class. + ACE_Asynch_Connect_Result_Impl *implementation_; + }; +private: + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Asynch_Connect &)) + ACE_UNIMPLEMENTED_FUNC (ACE_Asynch_Connect (const ACE_Asynch_Connect &)) +}; + +// Forward declarations +class ACE_Asynch_Transmit_File_Result_Impl; +class ACE_Asynch_Transmit_File_Impl; + +/** + * @class ACE_Asynch_Transmit_File + * + * @brief This class is a factory for starting off asynchronous + * transmit files on a stream. + * + * Once {open} is called, multiple asynchronous {transmit_file}s + * can started using this class. A + * ACE_Asynch_Transmit_File::Result will be passed back to the + * {handler} when the asynchronous transmit file completes + * through the {ACE_Handler::handle_transmit_file} callback. + * The transmit_file function transmits file data over a + * connected network connection. The function uses the operating + * system's cache manager to retrieve the file data. This + * function provides high-performance file data transfer over + * network connections. This function would be of great use in + * a Web Server, Image Server, etc. + */ +class ACE_Export ACE_Asynch_Transmit_File : public ACE_Asynch_Operation +{ + +public: + // Forward declarations + class Header_And_Trailer; + + /// A do nothing constructor. + ACE_Asynch_Transmit_File (void); + + /// Destructor. + virtual ~ACE_Asynch_Transmit_File (void); + + /** + * Initializes the factory with information which will be used with + * each asynchronous call. If ({handle} == ACE_INVALID_HANDLE), + * {ACE_Handler::handle} will be called on the {handler} to get the + * correct handle. + */ + int open (ACE_Handler &handler, + ACE_HANDLE handle = ACE_INVALID_HANDLE, + const void *completion_key = 0, + ACE_Proactor *proactor = 0); + + /** + * This starts off an asynchronous transmit file. The {file} is a + * handle to an open file. {header_and_trailer} is a pointer to a + * data structure that contains pointers to data to send before and + * after the file data is sent. Set this parameter to 0 if you only + * want to transmit the file data. Upto {bytes_to_write} will be + * written to the {socket}. If you want to send the entire file, + * let {bytes_to_write} = 0. {bytes_per_send} is the size of each + * block of data sent per send operation. Please read the Win32 + * documentation on what the flags should be. Priority of the + * operation is specified by {priority}. On POSIX4-Unix, this is + * supported. Works like {nice} in Unix. Negative values are not + * allowed. 0 means priority of the operation same as the process + * priority. 1 means priority of the operation is one less than + * process. And so forth. On Win32, this is a no-op. + * {signal_number} is the POSIX4 real-time signal number to be used + * for the operation. {signal_number} ranges from ACE_SIGRTMIN to + * ACE_SIGRTMAX. This argument is a no-op on non-POSIX4 systems. + */ + int transmit_file (ACE_HANDLE file, + Header_And_Trailer *header_and_trailer = 0, + size_t bytes_to_write = 0, + unsigned long offset = 0, + unsigned long offset_high = 0, + size_t bytes_per_send = 0, + unsigned long flags = 0, + const void *act = 0, + int priority = 0, + int signal_number = ACE_SIGRTMIN); + + /// Return the underlying implementation class. + // (this should be protected...) + virtual ACE_Asynch_Operation_Impl *implementation (void) const; + +protected: + /// The implementation class. + ACE_Asynch_Transmit_File_Impl *implementation_; + +public: +/** + * @class Result + * + * @brief This is that class which will be passed back to the + * {handler} when the asynchronous transmit file completes. + * + * This class has all the information necessary for the + * {handler} to uniquiely identify the completion of the + * asynchronous transmit file. + */ + class ACE_Export Result : public ACE_Asynch_Result + { + + /// The concrete implementation result classes only construct this + /// class. + friend class ACE_POSIX_Asynch_Transmit_File_Result; + friend class ACE_WIN32_Asynch_Transmit_File_Result; + + public: + /// Socket used for transmitting the file. + ACE_HANDLE socket (void) const; + + /// File from which the data is read. + ACE_HANDLE file (void) const; + + /// Header and trailer data associated with this transmit file. + Header_And_Trailer *header_and_trailer (void) const; + + /// The number of bytes which were requested at the start of the + /// asynchronous transmit file. + size_t bytes_to_write (void) const; + + /// Number of bytes per send requested at the start of the transmit + /// file. + size_t bytes_per_send (void) const; + + /// Flags which were passed into transmit file. + unsigned long flags (void) const; + + /// Get the implementation class. + ACE_Asynch_Transmit_File_Result_Impl *implementation (void) const; + + protected: + /// Constructor. + Result (ACE_Asynch_Transmit_File_Result_Impl *implementation); + + /// Destructor. + virtual ~Result (void); + + /// The implementation class. + ACE_Asynch_Transmit_File_Result_Impl *implementation_; + }; + +/** + * @class Header_And_Trailer + * + * @brief The class defines a data structure that contains pointers + * to data to send before and after the file data is sent. + * + * This class provides a wrapper over TRANSMIT_FILE_BUFFERS + * and provided a consistent use of ACE_Message_Blocks. + */ + class ACE_Export Header_And_Trailer + { + + public: + /// Constructor. + Header_And_Trailer (ACE_Message_Block *header = 0, + size_t header_bytes = 0, + ACE_Message_Block *trailer = 0, + size_t trailer_bytes = 0); + + /// Destructor + virtual ~Header_And_Trailer (void); + + /// This method allows all the member to be set in one fell swoop. + void header_and_trailer (ACE_Message_Block *header = 0, + size_t header_bytes = 0, + ACE_Message_Block *trailer = 0, + size_t trailer_bytes = 0); + + /// Get header which goes before the file data. + ACE_Message_Block *header (void) const; + + /// Set header which goes before the file data. + void header (ACE_Message_Block *message_block); + + /// Get size of the header data. + size_t header_bytes (void) const; + + /// Set size of the header data. + void header_bytes (size_t bytes); + + /// Get trailer which goes after the file data. + ACE_Message_Block *trailer (void) const; + + /// Set trailer which goes after the file data. + void trailer (ACE_Message_Block *message_block); + + /// Get size of the trailer data. + size_t trailer_bytes (void) const; + + /// Set size of the trailer data. + void trailer_bytes (size_t bytes); + + /// Conversion routine. + ACE_LPTRANSMIT_FILE_BUFFERS transmit_buffers (void); + + protected: + /// Header data. + ACE_Message_Block *header_; + + /// Size of header data. + size_t header_bytes_; + + /// Trailer data. + ACE_Message_Block *trailer_; + + /// Size of trailer data. + size_t trailer_bytes_; + + /// Target data structure. + ACE_TRANSMIT_FILE_BUFFERS transmit_buffers_; + }; +private: + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Asynch_Transmit_File &)) + ACE_UNIMPLEMENTED_FUNC (ACE_Asynch_Transmit_File (const ACE_Asynch_Transmit_File &)) +}; + + +// Forward declarations +class ACE_Asynch_Read_Dgram_Result_Impl; +class ACE_Asynch_Read_Dgram_Impl; +class ACE_Addr; + +/** + * @class ACE_Asynch_Read_Dgram + * + * @brief This class is a factory for starting off asynchronous reads + * on a UDP socket. This class forwards all methods to its + * implementation class. + * + * Once {open} is called, multiple asynchronous {read}s can be + * started using this class. An ACE_Asynch_Read_Dgram::Result + * will be passed back to the {handler} when the asynchronous + * reads completes through the {ACE_Handler::handle_read_dgram} + * callback. + */ +class ACE_Export ACE_Asynch_Read_Dgram : public ACE_Asynch_Operation +{ + +public: + /// A do nothing constructor. + ACE_Asynch_Read_Dgram (void); + + /// Destructor + virtual ~ACE_Asynch_Read_Dgram (void); + + /** + * Initializes the factory with information which will be used with + * each asynchronous call. If ({handle} == ACE_INVALID_HANDLE), + * {ACE_Handler::handle} will be called on the {handler} to get the + * correct handle. + */ + int open (ACE_Handler &handler, + ACE_HANDLE handle = ACE_INVALID_HANDLE, + const void *completion_key = 0, + ACE_Proactor *proactor = 0); + + /** This starts off an asynchronous read. Upto + * {message_block->total_size()} will be read and stored in the + * {message_block}. {message_block}'s {wr_ptr} will be updated to reflect + * the added bytes if the read operation is successfully completed. + * Return code of 1 means immediate success and {number_of_bytes_recvd} + * will contain number of bytes read. The {ACE_Handler::handle_read_dgram} + * method will still be called. Return code of 0 means the IO will + * complete proactively. Return code of -1 means there was an error, use + * errno to get the error code. + * + * Scatter/gather is supported on WIN32 by using the {message_block->cont()} + * method. Up to ACE_IOV_MAX {message_block}'s are supported. Upto + * {message_block->size()} bytes will be read into each {message block} for + * a total of {message_block->total_size()} bytes. All {message_block}'s + * {wr_ptr}'s will be updated to reflect the added bytes for each + * {message_block} + * + * Priority of the operation is specified by {priority}. On POSIX4-Unix, + * this is supported. Works like {nice} in Unix. Negative values are not + * allowed. 0 means priority of the operation same as the process + * priority. 1 means priority of the operation is one less than + * process. And so forth. On Win32, {priority} is a no-op. + * {signal_number} is the POSIX4 real-time signal number to be used + * for the operation. {signal_number} ranges from ACE_SIGRTMIN to + * ACE_SIGRTMAX. This argument is a no-op on non-POSIX4 systems. + */ + ssize_t recv (ACE_Message_Block *message_block, + size_t &number_of_bytes_recvd, + int flags, + int protocol_family = PF_INET, + const void *act = 0, + int priority = 0, + int signal_number = ACE_SIGRTMIN); + + /// Return the underlying implementation class. + // (this should be protected...) + virtual ACE_Asynch_Operation_Impl *implementation (void) const; + +protected: + /// Implementation class that all methods will be forwarded to. + ACE_Asynch_Read_Dgram_Impl *implementation_; + +public: +/** + * @class Result + * + * @brief This is the class which will be passed back to the + * {handler} when the asynchronous read completes. This class + * forwards all the methods to the implementation classes. + * + * This class has all the information necessary for the + * {handler} to uniquiely identify the completion of the + * asynchronous read. + */ + class ACE_Export Result : public ACE_Asynch_Result + { + + /// The concrete implementation result classes only construct this + /// class. + friend class ACE_POSIX_Asynch_Read_Dgram_Result; + friend class ACE_WIN32_Asynch_Read_Dgram_Result; + + public: + + /// The number of bytes which were requested at the start of the + /// asynchronous read. + size_t bytes_to_read (void) const; + + /// Message block which contains the read data + ACE_Message_Block *message_block (void) const; + + /// The flags used in the read + int flags (void) const; + + /// The address of where the packet came from + int remote_address (ACE_Addr& addr) const; + + /// I/O handle used for reading. + ACE_HANDLE handle (void) const; + + /// Get the implementation class. + ACE_Asynch_Read_Dgram_Result_Impl *implementation (void) const; + + protected: + /// Constructor. + Result (ACE_Asynch_Read_Dgram_Result_Impl *implementation); + + /// Destructor. + virtual ~Result (void); + + /// The implementation class. + ACE_Asynch_Read_Dgram_Result_Impl *implementation_; + }; +private: + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Asynch_Read_Dgram &)) + ACE_UNIMPLEMENTED_FUNC (ACE_Asynch_Read_Dgram (const ACE_Asynch_Read_Dgram &)) +}; + +// Forward declarations +class ACE_Asynch_Write_Dgram_Impl; +class ACE_Asynch_Write_Dgram_Result_Impl; + +/** + * @class ACE_Asynch_Write_Dgram + * + * @brief This class is a factory for starting off asynchronous writes + * on a UDP socket. This class forwards all methods to its + * implementation class. + * + * Once {open} is called, multiple asynchronous {writes}s can + * started using this class. An ACE_Asynch_Write_Dgram::Result + * will be passed back to the {handler} when the asynchronous + * write completes through the + * {ACE_Handler::handle_write_dgram} callback. + */ +class ACE_Export ACE_Asynch_Write_Dgram : public ACE_Asynch_Operation +{ + +public: + /// A do nothing constructor. + ACE_Asynch_Write_Dgram (void); + + /// Destructor. + virtual ~ACE_Asynch_Write_Dgram (void); + + /** + * Initializes the factory with information which will be used with + * each asynchronous call. If ({handle} == ACE_INVALID_HANDLE), + * {ACE_Handler::handle} will be called on the {handler} to get the + * correct handle. + */ + int open (ACE_Handler &handler, + ACE_HANDLE handle = ACE_INVALID_HANDLE, + const void *completion_key = 0, + ACE_Proactor *proactor = 0); + + /** This starts off an asynchronous send. Upto + * {message_block->total_length()} will be sent. {message_block}'s + * {rd_ptr} will be updated to reflect the sent bytes if the send operation + * is successfully completed. + * Return code of 1 means immediate success and {number_of_bytes_sent} + * is updated to number of bytes sent. The {ACE_Handler::handle_write_dgram} + * method will still be called. Return code of 0 means the IO will + * complete proactively. Return code of -1 means there was an error, use + * errno to get the error code. + * + * Scatter/gather is supported on WIN32 by using the {message_block->cont()} + * method. Up to ACE_IOV_MAX {message_block}'s are supported. Upto + * {message_block->length()} bytes will be sent from each {message block} + * for a total of {message_block->total_length()} bytes. All + * {message_block}'s {rd_ptr}'s will be updated to reflect the bytes sent + * from each {message_block}. + * + * Priority of the operation is specified by {priority}. On POSIX4-Unix, + * this is supported. Works like {nice} in Unix. Negative values are not + * allowed. 0 means priority of the operation same as the process + * priority. 1 means priority of the operation is one less than + * process. And so forth. On Win32, this argument is a no-op. + * {signal_number} is the POSIX4 real-time signal number to be used + * for the operation. {signal_number} ranges from ACE_SIGRTMIN to + * ACE_SIGRTMAX. This argument is a no-op on non-POSIX4 systems. + */ + ssize_t send (ACE_Message_Block *message_block, + size_t &number_of_bytes_sent, + int flags, + const ACE_Addr& remote_addr, + const void *act = 0, + int priority = 0, + int signal_number = ACE_SIGRTMIN); + + /// Return the underlying implementation class. + // (this should be protected...) + virtual ACE_Asynch_Operation_Impl *implementation (void) const; + +protected: + /// Implementation class that all methods will be forwarded to. + ACE_Asynch_Write_Dgram_Impl *implementation_; + +public: +/** + * @class Result + * + * @brief This is that class which will be passed back to the + * {handler} when the asynchronous write completes. This class + * forwards all the methods to the implementation class. + * + * This class has all the information necessary for the + * {handler} to uniquiely identify the completion of the + * asynchronous write. + */ + class ACE_Export Result : public ACE_Asynch_Result + { + + /// The concrete implementation result classes only construct this + /// class. + friend class ACE_POSIX_Asynch_Write_Dgram_Result; + friend class ACE_WIN32_Asynch_Write_Dgram_Result; + + public: + + /// The number of bytes which were requested at the start of the + /// asynchronous write. + size_t bytes_to_write (void) const; + + /// Message block which contains the sent data + ACE_Message_Block *message_block (void) const; + + /// The flags using in the write + int flags (void) const; + + /// I/O handle used for writing. + ACE_HANDLE handle (void) const; + + /// Get the implementation class. + ACE_Asynch_Write_Dgram_Result_Impl *implementation (void) const; + + protected: + /// Constructor. + Result (ACE_Asynch_Write_Dgram_Result_Impl *implementation); + + /// Destructor. + virtual ~Result (void); + + /// Implementation class. + ACE_Asynch_Write_Dgram_Result_Impl *implementation_; + }; +private: + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Asynch_Write_Dgram &)) + ACE_UNIMPLEMENTED_FUNC (ACE_Asynch_Write_Dgram (const ACE_Asynch_Write_Dgram &)) +}; + + +/** + * @class ACE_Handler + * + * @brief This base class defines the interface for receiving the + * results of asynchronous operations. + * + * Subclasses of this class will fill in appropriate methods. + */ +class ACE_Export ACE_Handler +{ +public: + /// A do nothing constructor. + ACE_Handler (void); + + /// A do nothing constructor which allows proactor to be set to \. + ACE_Handler (ACE_Proactor *p); + + /// Virtual destruction. + virtual ~ACE_Handler (void); + + /// This method will be called when an asynchronous read completes on + /// a stream. + virtual void handle_read_stream (const ACE_Asynch_Read_Stream::Result &result); + + /// This method will be called when an asynchronous write completes + /// on a UDP socket. + virtual void handle_write_dgram (const ACE_Asynch_Write_Dgram::Result &result); + + /// This method will be called when an asynchronous read completes on + /// a UDP socket. + virtual void handle_read_dgram (const ACE_Asynch_Read_Dgram::Result &result); + + /// This method will be called when an asynchronous write completes + /// on a stream. + virtual void handle_write_stream (const ACE_Asynch_Write_Stream::Result &result); + + /// This method will be called when an asynchronous read completes on + /// a file. + virtual void handle_read_file (const ACE_Asynch_Read_File::Result &result); + + /// This method will be called when an asynchronous write completes + /// on a file. + virtual void handle_write_file (const ACE_Asynch_Write_File::Result &result); + + /// This method will be called when an asynchronous accept completes. + virtual void handle_accept (const ACE_Asynch_Accept::Result &result); + + /// This method will be called when an asynchronous connect completes. + virtual void handle_connect (const ACE_Asynch_Connect::Result &result); + + /// This method will be called when an asynchronous transmit file + /// completes. + virtual void handle_transmit_file (const ACE_Asynch_Transmit_File::Result &result); + + /// Called when timer expires. {tv} was the requested time value and + /// {act} is the ACT passed when scheduling the timer. + virtual void handle_time_out (const ACE_Time_Value &tv, + const void *act = 0); + + /** + * This is method works with the {run_event_loop} of the + * ACE_Proactor. A special {Wake_Up_Completion} is used to wake up + * all the threads that are blocking for completions. + */ + virtual void handle_wakeup (void); + + /// Get the proactor associated with this handler. + ACE_Proactor *proactor (void); + + /// Set the proactor. + void proactor (ACE_Proactor *p); + + /** + * Get the I/O handle used by this {handler}. This method will be + * called by the ACE_Asynch_* classes when an ACE_INVALID_HANDLE is + * passed to {open}. + */ + virtual ACE_HANDLE handle (void) const; + + /// Set the ACE_HANDLE value for this Handler. + virtual void handle (ACE_HANDLE); + + /** + * @class Proxy + * + * @brief The Proxy class acts as a proxy for dispatch of completions + * to operations issued for the associated handler. It allows the handler + * to be deleted while operations are outstanding. The proxy must be used + * to get the ACE_Handler pointer for dispatching, and if it's 0, the + * handler is no longer valid and the result should not be dispatched. + */ + class ACE_Export Proxy + { + public: + Proxy (ACE_Handler *handler) : handler_ (handler) {}; + void reset (void) { this->handler_ = 0; }; + ACE_Handler *handler (void) { return this->handler_; }; + private: + ACE_Handler *handler_; + }; + typedef ACE_Refcounted_Auto_Ptr + Proxy_Ptr; + + Proxy_Ptr &proxy (void); + +protected: + /// The proactor associated with this handler. + ACE_Proactor *proactor_; + + /// The ACE_HANDLE in use with this handler. + ACE_HANDLE handle_; + + /// Refers to proxy for this handler. + ACE_Refcounted_Auto_Ptr proxy_; + + ACE_UNIMPLEMENTED_FUNC (ACE_Handler (const ACE_Handler &)) + ACE_UNIMPLEMENTED_FUNC (ACE_Handler operator= (const ACE_Handler &)) +}; + +// Forward declarations +class ACE_INET_Addr; + +// Forward declarations +template +class ACE_Asynch_Acceptor; + +/** + * @class ACE_Service_Handler + * + * @brief This base class defines the interface for the + * ACE_Asynch_Acceptor to call into when new connection are + * accepted. + * + * Subclasses of this class will fill in appropriate methods to + * define application specific behavior. + */ +class ACE_Export ACE_Service_Handler : public ACE_Handler +{ + + /// The Acceptor is the factory and therefore should have special + /// privileges. + friend class ACE_Asynch_Acceptor; + +public: + /// A do nothing constructor. + ACE_Service_Handler (void); + + /// Virtual destruction. + virtual ~ACE_Service_Handler (void); + + /** + * {open} is called by ACE_Asynch_Acceptor to initialize a new + * instance of ACE_Service_Handler that has been created after the + * new connection is accepted. The handle for the new connection is + * passed along with the initial data that may have shown up. + */ + virtual void open (ACE_HANDLE new_handle, + ACE_Message_Block &message_block); + + // protected: + // This should be corrected after the correct semantics of the + // friend has been figured out. + + /// Called by ACE_Asynch_Acceptor to pass the addresses of the new + /// connections. + virtual void addresses (const ACE_INET_Addr &remote_address, + const ACE_INET_Addr &local_address); + + /// Called by ACE_Asynch_Acceptor to pass the act. + virtual void act (const void *); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_WIN32 || ACE_HAS_AIO_CALLS*/ +#include /**/ "ace/post.h" +#endif /* ACE_ASYNCH_IO_H */ diff --git a/dep/acelite/ace/Asynch_IO_Impl.cpp b/dep/acelite/ace/Asynch_IO_Impl.cpp new file mode 100644 index 00000000000..b4b47eda55c --- /dev/null +++ b/dep/acelite/ace/Asynch_IO_Impl.cpp @@ -0,0 +1,117 @@ +// $Id: Asynch_IO_Impl.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Asynch_IO_Impl.h" + +#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) || defined (ACE_HAS_AIO_CALLS) +// This only works on Win32 platforms and on Unix platforms supporting +// aio calls. + +#if !defined (__ACE_INLINE__) +#include "ace/Asynch_IO_Impl.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_Asynch_Result_Impl::~ACE_Asynch_Result_Impl (void) +{ +} + +ACE_Asynch_Operation_Impl::~ACE_Asynch_Operation_Impl (void) +{ +} + +ACE_Asynch_Read_Stream_Impl::~ACE_Asynch_Read_Stream_Impl (void) +{ +} + +ACE_Asynch_Read_Stream_Result_Impl::~ACE_Asynch_Read_Stream_Result_Impl (void) +{ +} + +ACE_Asynch_Write_Stream_Impl::~ACE_Asynch_Write_Stream_Impl (void) +{ +} + +ACE_Asynch_Write_Stream_Result_Impl::~ACE_Asynch_Write_Stream_Result_Impl (void) +{ +} + +ACE_Asynch_Read_File_Impl::~ACE_Asynch_Read_File_Impl (void) +{ +} + +ACE_Asynch_Write_File_Impl::~ACE_Asynch_Write_File_Impl (void) +{ +} + +ACE_Asynch_Read_File_Result_Impl::~ACE_Asynch_Read_File_Result_Impl (void) +{ +} + +ACE_Asynch_Write_File_Result_Impl::~ACE_Asynch_Write_File_Result_Impl (void) +{ +} + +ACE_Asynch_Accept_Result_Impl::~ACE_Asynch_Accept_Result_Impl (void) +{ +} + +ACE_Asynch_Connect_Result_Impl::~ACE_Asynch_Connect_Result_Impl (void) +{ +} + +ACE_Asynch_Accept_Impl::~ACE_Asynch_Accept_Impl (void) +{ +} + +ACE_Asynch_Connect_Impl::~ACE_Asynch_Connect_Impl (void) +{ +} + +ACE_Asynch_Transmit_File_Impl::~ACE_Asynch_Transmit_File_Impl (void) +{ +} + +ACE_Asynch_Transmit_File_Result_Impl::~ACE_Asynch_Transmit_File_Result_Impl (void) +{ +} + +ACE_Asynch_Read_Dgram_Impl::~ACE_Asynch_Read_Dgram_Impl (void) +{ +} + +ACE_Asynch_Read_Dgram_Impl::ACE_Asynch_Read_Dgram_Impl (void) +{ +} + +ACE_Asynch_Write_Dgram_Impl::~ACE_Asynch_Write_Dgram_Impl (void) +{ +} + +ACE_Asynch_Write_Dgram_Impl::ACE_Asynch_Write_Dgram_Impl (void) +{ +} + +//*********************************************** + +ACE_Asynch_Read_Dgram_Result_Impl::~ACE_Asynch_Read_Dgram_Result_Impl (void) +{ +} + +ACE_Asynch_Read_Dgram_Result_Impl::ACE_Asynch_Read_Dgram_Result_Impl (void) +{ +} + +//*********************************************** + +ACE_Asynch_Write_Dgram_Result_Impl::~ACE_Asynch_Write_Dgram_Result_Impl (void) +{ +} + +ACE_Asynch_Write_Dgram_Result_Impl::ACE_Asynch_Write_Dgram_Result_Impl (void) +{ +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_WIN32_OVERLAPPED_IO || ACE_HAS_AIO_CALLS */ diff --git a/dep/acelite/ace/Asynch_IO_Impl.h b/dep/acelite/ace/Asynch_IO_Impl.h new file mode 100644 index 00000000000..06eb5c10a87 --- /dev/null +++ b/dep/acelite/ace/Asynch_IO_Impl.h @@ -0,0 +1,816 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file Asynch_IO_Impl.h + * + * $Id: Asynch_IO_Impl.h 80826 2008-03-04 14:51:23Z wotte $ + * + * + * This class contains asbtract base classes for all the concrete + * implementation classes for the various asynchronous operations + * that are used with the Praoctor. + * + * + * @author Irfan Pyarali (irfan@cs.wustl.edu) + * @author Tim Harrison (harrison@cs.wustl.edu) + * @author Alexander Babu Arulanthu + * @author Roger Tragin + * @author Alexander Libman + */ +//============================================================================= + +#ifndef ACE_ASYNCH_IO_IMPL_H +#define ACE_ASYNCH_IO_IMPL_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +#pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) || defined (ACE_HAS_AIO_CALLS) +// This only works on Win32 platforms and on Unix platforms supporting +// aio calls. + +#include "ace/Asynch_IO.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Forward declaration. +class ACE_Proactor_Impl; + +/** + * @class ACE_Asynch_Result_Impl + * + * @brief Abstract base class for the all the classes that provide + * concrete implementations for ACE_Asynch_Result. + * + */ +class ACE_Export ACE_Asynch_Result_Impl +{ +public: + virtual ~ACE_Asynch_Result_Impl (void); + + /// Number of bytes transferred by the operation. + virtual size_t bytes_transferred (void) const = 0; + + /// ACT associated with the operation. + virtual const void *act (void) const = 0; + + /// Did the operation succeed? + virtual int success (void) const = 0; + + /// This ACT is not the same as the ACT associated with the + /// asynchronous operation. + virtual const void *completion_key (void) const = 0; + + /// Error value if the operation fail. + virtual u_long error (void) const = 0; + + /// Event associated with the OVERLAPPED structure. + virtual ACE_HANDLE event (void) const = 0; + + /// This really make sense only when doing file I/O. + virtual u_long offset (void) const = 0; + virtual u_long offset_high (void) const = 0; + + /// Priority of the operation. + virtual int priority (void) const = 0; + + /** + * POSIX4 real-time signal number to be used for the + * operation. ranges from SIGRTMIN to SIGRTMAX. By + * default, SIGRTMIN is used to issue calls. This is a no-op + * on non-POSIX4 systems and returns 0. + */ + virtual int signal_number (void) const = 0; + + // protected: + // + // These two should really be protected. But sometimes it + // simplifies code to be able to "fake" a result. Use carefully. + /// This is called when the asynchronous operation completes. + virtual void complete (size_t bytes_transferred, + int success, + const void *completion_key, + u_long error = 0) = 0; + + /// Post @c this to the Proactor's completion port. + virtual int post_completion (ACE_Proactor_Impl *proactor) = 0; + +protected: + /// Do-nothing constructor. + ACE_Asynch_Result_Impl (void); +}; + +/** + * @class ACE_Asynch_Operation_Impl + * + * @brief Abstract base class for all the concrete implementation + * classes that provide different implementations for the + * ACE_Asynch_Operation. + */ +class ACE_Export ACE_Asynch_Operation_Impl +{ +public: + virtual ~ACE_Asynch_Operation_Impl (void); + + /** + * Initializes the factory with information which will be used with + * each asynchronous call. If @a handle == ACE_INVALID_HANDLE, + * ACE_Handler::handle() will be called on the proxied handler to get the + * correct handle. + */ + virtual int open (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor) = 0; + + /** + * This cancels all pending accepts operations that were issued by + * the calling thread. The function does not cancel asynchronous + * operations issued by other threads. + */ + virtual int cancel (void) = 0; + + // = Access methods. + + /// Return the underlying proactor. + virtual ACE_Proactor* proactor (void) const = 0; + +protected: + /// Do-nothing constructor. + ACE_Asynch_Operation_Impl (void); +}; + +/** + * @class ACE_Asynch_Read_Stream_Impl + * + * @brief Abstract base class for all the concrete implementation + * classes that provide different implementations for the + * ACE_Asynch_Read_Stream + * + */ +class ACE_Export ACE_Asynch_Read_Stream_Impl : public virtual ACE_Asynch_Operation_Impl +{ +public: + virtual ~ACE_Asynch_Read_Stream_Impl (void); + + /// This starts off an asynchronous read. Upto @a bytes_to_read will + /// be read and stored in the @a message_block. + virtual int read (ACE_Message_Block &message_block, + size_t bytes_to_read, + const void *act, + int priority, + int signal_number) = 0; + +#if (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) + /** + * Same as above but with scatter support, through chaining of composite + * message blocks using the continuation field. + */ + virtual int readv (ACE_Message_Block &message_block, + size_t bytes_to_read, + const void *act, + int priority, + int signal_number) = 0; +#endif /* (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) */ + +protected: + /// Do-nothing constructor. + ACE_Asynch_Read_Stream_Impl (void); +}; + +/** + * @class ACE_Asynch_Read_Stream_Result_Impl + * + * @brief Abstract base class for all the concrete implementation + * classes that provide different implementations for the + * ACE_Asynch_Read_Stream::Result class. + * + */ +class ACE_Export ACE_Asynch_Read_Stream_Result_Impl : public virtual ACE_Asynch_Result_Impl +{ +public: + virtual ~ACE_Asynch_Read_Stream_Result_Impl (void); + + /// The number of bytes which were requested at the start of the + /// asynchronous read. + virtual size_t bytes_to_read (void) const = 0; + + /// Message block which contains the read data. + virtual ACE_Message_Block &message_block (void) const = 0; + + /// I/O handle used for reading. + virtual ACE_HANDLE handle (void) const = 0; + +protected: + /// Do-nothing constructor. + ACE_Asynch_Read_Stream_Result_Impl (void); +}; + +/** + * @class ACE_Asynch_Write_Stream_Impl + * + * @brief Abstract base class for all the concrete implementation + * classes that provide different implementations for the + * ACE_Asynch_Write_Stream class. + * + */ +class ACE_Export ACE_Asynch_Write_Stream_Impl : public virtual ACE_Asynch_Operation_Impl +{ +public: + virtual ~ACE_Asynch_Write_Stream_Impl (void); + + /// This starts off an asynchronous write. Upto @a bytes_to_write + /// will be written from the @a message_block. + virtual int write (ACE_Message_Block &message_block, + size_t bytes_to_write, + const void *act, + int priority, + int signal_number) = 0; + +#if (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) + /** + * Same as above but with gather support, through chaining of composite + * message blocks using the continuation field. + */ + virtual int writev (ACE_Message_Block &message_block, + size_t bytes_to_write, + const void *act, + int priority, + int signal_number) = 0; +#endif /* (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) */ + +protected: + /// Do-nothing constructor. + ACE_Asynch_Write_Stream_Impl (void); +}; + +/** + * @class ACE_Asynch_Write_Stream_Result_Impl + * + * @brief Abstract base class for all the concrete implementation + * classes that provide different implementations for the + * ACE_Asynch_Write_Stream::Result. + * + */ +class ACE_Export ACE_Asynch_Write_Stream_Result_Impl : public virtual ACE_Asynch_Result_Impl +{ +public: + virtual ~ACE_Asynch_Write_Stream_Result_Impl (void); + + /// The number of bytes which were requested at the start of the + /// asynchronous write. + virtual size_t bytes_to_write (void) const = 0; + + /// Message block that contains the data to be written. + virtual ACE_Message_Block &message_block (void) const = 0; + + /// I/O handle used for writing. + virtual ACE_HANDLE handle (void) const = 0; + +protected: + /// Do-nothing constructor. + ACE_Asynch_Write_Stream_Result_Impl (void); +}; + +/** + * @class ACE_Asynch_Read_File_Impl + * + * @brief Abstract base class for all the concrete implementation + * classes that provide different implementations for the + * ACE_Asynch_Read_File::Result. + * + */ +class ACE_Export ACE_Asynch_Read_File_Impl : public virtual ACE_Asynch_Read_Stream_Impl +{ +public: + virtual ~ACE_Asynch_Read_File_Impl (void); + + /** + * This starts off an asynchronous read. Upto @a bytes_to_read will + * be read and stored in the @a message_block. The read will start + * at @a offset from the beginning of the file. + */ + virtual int read (ACE_Message_Block &message_block, + size_t bytes_to_read, + u_long offset, + u_long offset_high, + const void *act, + int priority, + int signal_number) = 0; + +#if (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) + /** + * Same as above but with scatter support, through chaining of composite + * message blocks using the continuation field. + * @note In win32 Each data block payload must be at least the size of a system + * memory page and must be aligned on a system memory page size boundary + */ + virtual int readv (ACE_Message_Block &message_block, + size_t bytes_to_read, + u_long offset, + u_long offset_high, + const void *act, + int priority, + int signal_number) = 0; +#endif /* (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) */ + + /// This starts off an asynchronous read. Upto @a bytes_to_read will + /// be read and stored in the @a message_block. + virtual int read (ACE_Message_Block &message_block, + size_t bytes_to_read, + const void *act, + int priority, + int signal_number) = 0; + +#if (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) + /** + * Same as above but with scatter support, through chaining of composite + * message blocks using the continuation field. + */ + virtual int readv (ACE_Message_Block &message_block, + size_t bytes_to_read, + const void *act, + int priority, + int signal_number) = 0; +#endif /* (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) */ + +protected: + /// Do-nothing constructor. + ACE_Asynch_Read_File_Impl (void); +}; + +/** + * @class ACE_Asynch_Read_File_Result_Impl + * + * @brief This is the abstract base class for all the concrete + * implementation classes for ACE_Asynch_Read_File::Result. + * + */ +class ACE_Export ACE_Asynch_Read_File_Result_Impl : public virtual ACE_Asynch_Read_Stream_Result_Impl +{ +public: + /// Destructor. + virtual ~ACE_Asynch_Read_File_Result_Impl (void); + +protected: + /// Do-nothing constructor. + ACE_Asynch_Read_File_Result_Impl (void); +}; + +/** + * @class ACE_Asynch_Write_File_Impl + * + * @brief Abstract base class for all the concrete implementation + * classes that provide different implementations for the + * ACE_Asynch_Write_File. + * + */ +class ACE_Export ACE_Asynch_Write_File_Impl : public virtual ACE_Asynch_Write_Stream_Impl +{ +public: + virtual ~ACE_Asynch_Write_File_Impl (void); + + /** + * This starts off an asynchronous write. Upto @a bytes_to_write + * will be write and stored in the @a message_block. The write will + * start at @a offset from the beginning of the file. + */ + virtual int write (ACE_Message_Block &message_block, + size_t bytes_to_write, + u_long offset, + u_long offset_high, + const void *act, + int priority, + int signal_number) = 0; + +#if (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) + /** + * Same as above but with gather support, through chaining of composite + * message blocks using the continuation field. + * @note In win32 Each data block payload must be at least the size of a system + * memory page and must be aligned on a system memory page size boundary + */ + virtual int writev (ACE_Message_Block &message_block, + size_t bytes_to_write, + u_long offset, + u_long offset_high, + const void *act, + int priority, + int signal_number) = 0; +#endif /* (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) */ + + /// This starts off an asynchronous write. Upto @a bytes_to_write + /// will be written from the @a message_block. + virtual int write (ACE_Message_Block &message_block, + size_t bytes_to_write, + const void *act, + int priority, + int signal_number) = 0; + +#if (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) + /** + * Same as above but with gather support, through chaining of composite + * message blocks using the continuation field. + */ + virtual int writev (ACE_Message_Block &message_block, + size_t bytes_to_write, + const void *act, + int priority, + int signal_number) = 0; +#endif /* (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) */ + +protected: + /// Do-nothing constructor. + ACE_Asynch_Write_File_Impl (void); +}; + +/** + * @class ACE_Asynch_Write_File_Result_Impl + * + * @brief This is the abstract base class for all the concrete + * implementation classes that provide different implementations + * for the ACE_Asynch_Write_File::Result. + * + */ +class ACE_Export ACE_Asynch_Write_File_Result_Impl : public virtual ACE_Asynch_Write_Stream_Result_Impl +{ +public: + virtual ~ACE_Asynch_Write_File_Result_Impl (void); + +protected: + /// Do-nothing constructor. + ACE_Asynch_Write_File_Result_Impl (void); +}; + +/** + * @class ACE_Asynch_Accept_Impl + * + * @brief Abstract base class for all the concrete implementation + * classes that provide different implementations for the + * ACE_Asynch_Accept. + * + */ +class ACE_Export ACE_Asynch_Accept_Impl : public virtual ACE_Asynch_Operation_Impl +{ +public: + virtual ~ACE_Asynch_Accept_Impl (void); + + /** + * This starts off an asynchronous accept. The asynchronous accept + * call also allows any initial data to be returned to the + * . Upto @a bytes_to_read will be read and stored in the + * @a message_block. The @a accept_handle will be used for the + * call. If (@a accept_handle == INVALID_HANDLE), a new + * handle will be created. + * + * @a message_block must be specified. This is because the address of + * the new connection is placed at the end of this buffer. + */ + virtual int accept (ACE_Message_Block &message_block, + size_t bytes_to_read, + ACE_HANDLE accept_handle, + const void *act, + int priority, + int signal_number, + int addr_family) = 0; + +protected: + /// Do-nothing constructor. + ACE_Asynch_Accept_Impl (void); +}; + +/** + * @class ACE_Asynch_Accept_Result_Impl + * + * @brief Abstract base class for all the concrete implementation + * classes that provide different implementations for the + * ACE_Asynch_Accept. + * + */ +class ACE_Export ACE_Asynch_Accept_Result_Impl : public virtual ACE_Asynch_Result_Impl +{ +public: + virtual ~ACE_Asynch_Accept_Result_Impl (void); + + /// The number of bytes which were requested at the start of the + /// asynchronous accept. + virtual size_t bytes_to_read (void) const = 0; + + /// Message block which contains the read data. + virtual ACE_Message_Block &message_block (void) const = 0; + + /// I/O handle used for accepting new connections. + virtual ACE_HANDLE listen_handle (void) const = 0; + + /// I/O handle for the new connection. + virtual ACE_HANDLE accept_handle (void) const = 0; + +protected: + /// Do-nothing constructor. + ACE_Asynch_Accept_Result_Impl (void); +}; + + +/** + * @class ACE_Asynch_Connect_Impl + * + * @brief Abstract base class for all the concrete implementation + * classes that provide different implementations for the + * ACE_Asynch_Connect. + * + */ +class ACE_Export ACE_Asynch_Connect_Impl : public virtual ACE_Asynch_Operation_Impl +{ +public: + virtual ~ACE_Asynch_Connect_Impl (void); + + /** + * This starts off an asynchronous connect + */ + virtual int connect (ACE_HANDLE connect_handle, + const ACE_Addr & remote_sap, + const ACE_Addr & local_sap, + int reuse_addr, + const void *act, + int priority, + int signal_number) = 0; + +protected: + /// Do-nothing constructor. + ACE_Asynch_Connect_Impl (void); +}; + +/** + * @class ACE_Asynch_Connect_Result_Impl + * + * @brief Abstract base class for all the concrete implementation + * classes that provide different implementations for the + * ACE_Asynch_Connect. + * + */ +class ACE_Export ACE_Asynch_Connect_Result_Impl : public virtual ACE_Asynch_Result_Impl +{ +public: + virtual ~ACE_Asynch_Connect_Result_Impl (void); + + /// I/O handle for the connection. + virtual ACE_HANDLE connect_handle (void) const = 0; + +protected: + /// Do-nothing constructor. + ACE_Asynch_Connect_Result_Impl (void); +}; + + +/** + * @class ACE_Asynch_Transmit_File_Impl + * + * @brief Abstract base class for all the concrete implementation + * classes that provide different implementations for the + * ACE_Asynch_Transmit_File. + * + */ +class ACE_Asynch_Transmit_File_Impl : public virtual ACE_Asynch_Operation_Impl +{ +public: + virtual ~ACE_Asynch_Transmit_File_Impl (void); + + /// This starts off an asynchronous transmit file. + virtual int transmit_file (ACE_HANDLE file, + ACE_Asynch_Transmit_File::Header_And_Trailer *header_and_trailer, + size_t bytes_to_write, + u_long offset, + u_long offset_high, + size_t bytes_per_send, + u_long flags, + const void *act, + int priority, + int signal_number) = 0; + +protected: + /// Do-nothing constructor. + ACE_Asynch_Transmit_File_Impl (void); +}; + +/** + * @class ACE_Asynch_Transmit_File_Result_Impl + * + * @brief Abstract base class for all the concrete implementation + * classes that provide different implementations for the + * ACE_Asynch_Transmit_File::Result. + * + */ +class ACE_Export ACE_Asynch_Transmit_File_Result_Impl : public virtual ACE_Asynch_Result_Impl +{ +public: + virtual ~ACE_Asynch_Transmit_File_Result_Impl (void); + + /// Socket used for transmitting the file. + virtual ACE_HANDLE socket (void) const = 0; + + /// File from which the data is read. + virtual ACE_HANDLE file (void) const = 0; + + /// Header and trailer data associated with this transmit file. + virtual ACE_Asynch_Transmit_File::Header_And_Trailer *header_and_trailer (void) const = 0; + + /// The number of bytes which were requested at the start of the + /// asynchronous transmit file. + virtual size_t bytes_to_write (void) const = 0; + + /// Number of bytes per send requested at the start of the transmit + /// file. + virtual size_t bytes_per_send (void) const = 0; + + /// Flags which were passed into transmit file. + virtual u_long flags (void) const = 0; + +protected: + /// Do-nothing constructor. + ACE_Asynch_Transmit_File_Result_Impl (void); +}; + + +/** + * @class ACE_Asynch_Read_Dgram_Impl + * + * @brief Abstract base class for all the concrete implementation + * classes that provide different implementations for the + * ACE_Asynch_Read_Dgram + * + */ +class ACE_Export ACE_Asynch_Read_Dgram_Impl : public virtual ACE_Asynch_Operation_Impl +{ +public: + virtual ~ACE_Asynch_Read_Dgram_Impl (void); + + /** This starts off an asynchronous read. Upto + * total_size()> will be read and stored in the + * @a message_block. @a message_block's will be updated to reflect + * the added bytes if the read operation is successful completed. + * Return code of 1 means immediate success and + * will contain number of bytes read. The + * method will still be called. Return code of 0 means the IO will + * complete proactively. Return code of -1 means there was an error, use + * errno to get the error code. + * + * Scatter/gather is supported on WIN32 by using the cont()> + * method. Up to ACE_IOV_MAX @a message_block's are supported. Upto + * size()> bytes will be read into each for + * a total of total_size()> bytes. All @a message_block's + * 's will be updated to reflect the added bytes for each + * @a message_block + * + * Priority of the operation is specified by @a priority. On POSIX4-Unix, + * this is supported. Works like in Unix. Negative values are not + * allowed. 0 means priority of the operation same as the process + * priority. 1 means priority of the operation is one less than + * process. And so forth. On Win32, @a priority is a no-op. + * @a signal_number is the POSIX4 real-time signal number to be used + * for the operation. @a signal_number ranges from ACE_SIGRTMIN to + * ACE_SIGRTMAX. This argument is a no-op on non-POSIX4 systems. + */ + virtual ssize_t recv (ACE_Message_Block *message_block, + size_t &number_of_bytes_recvd, + int flags, + int protocol_family, + const void *act, + int priority, + int signal_number) = 0; + +protected: + /// Do-nothing constructor. + ACE_Asynch_Read_Dgram_Impl (void); +}; + +/** + * @class ACE_Asynch_Read_Dgram_Result_Impl + * + * @brief Abstract base class for all the concrete implementation + * classes that provide different implementations for the + * ACE_Asynch_Read_Dgram::Result class. + * + */ +class ACE_Export ACE_Asynch_Read_Dgram_Result_Impl : public virtual ACE_Asynch_Result_Impl +{ +public: + virtual ~ACE_Asynch_Read_Dgram_Result_Impl (void); + + /// Message block which contains the read data + virtual ACE_Message_Block *message_block (void) const = 0; + + /// The number of bytes which were requested at the start of the + /// asynchronous read. + virtual size_t bytes_to_read (void) const = 0; + + /// The address of where the packet came from + virtual int remote_address (ACE_Addr& addr) const = 0; + + /// The flags used in the read + virtual int flags (void) const = 0; + + /// I/O handle used for reading. + virtual ACE_HANDLE handle (void) const = 0; + +protected: + /// Do-nothing constructor. + ACE_Asynch_Read_Dgram_Result_Impl (void); +}; + +/** + * @class ACE_Asynch_Write_Dgram_Impl + * + * @brief Abstract base class for all the concrete implementation + * classes that provide different implementations for the + * ACE_Asynch_Write_Dgram class. + * + */ +class ACE_Export ACE_Asynch_Write_Dgram_Impl : public virtual ACE_Asynch_Operation_Impl +{ +public: + virtual ~ACE_Asynch_Write_Dgram_Impl (void); + + /** This starts off an asynchronous send. Upto + * total_length()> will be sent. @a message_block's + * will be updated to reflect the sent bytes if the send operation + * is successful completed. + * Return code of 1 means immediate success and + * is updated to number of bytes sent. The + * method will still be called. Return code of 0 means the IO will + * complete proactively. Return code of -1 means there was an error, use + * errno to get the error code. + * + * Scatter/gather is supported on WIN32 by using the cont()> + * method. Up to ACE_IOV_MAX @a message_block's are supported. Upto + * length()> bytes will be sent from each + * for a total of total_length()> bytes. All + * @a message_block's 's will be updated to reflect the bytes sent + * from each @a message_block. + * + * Priority of the operation is specified by @a priority. On POSIX4-Unix, + * this is supported. Works like in Unix. Negative values are not + * allowed. 0 means priority of the operation same as the process + * priority. 1 means priority of the operation is one less than + * process. And so forth. On Win32, this argument is a no-op. + * @a signal_number is the POSIX4 real-time signal number to be used + * for the operation. @a signal_number ranges from ACE_SIGRTMIN to + * ACE_SIGRTMAX. This argument is a no-op on non-POSIX4 systems. + */ + virtual ssize_t send (ACE_Message_Block *message_block, + size_t &number_of_bytes_sent, + int flags, + const ACE_Addr &addr, + const void *act, + int priority, + int signal_number) = 0; + +protected: + /// Do-nothing constructor. + ACE_Asynch_Write_Dgram_Impl (void); +}; + +/** + * @class ACE_Asynch_Write_Dgram_Result_Impl + * + * @brief Abstract base class for all the concrete implementation + * classes that provide different implementations for the + * ACE_Asynch_Write_Dgram::Result class. + * + */ +class ACE_Export ACE_Asynch_Write_Dgram_Result_Impl : public virtual ACE_Asynch_Result_Impl +{ +public: + virtual ~ACE_Asynch_Write_Dgram_Result_Impl (void); + + /// The number of bytes which were requested at the start of the + /// asynchronous write. + virtual size_t bytes_to_write (void) const = 0; + + /// Message block which contains the sent data + virtual ACE_Message_Block *message_block (void) const = 0; + + /// The flags using in the write + virtual int flags (void) const = 0; + + /// I/O handle used for writing. + virtual ACE_HANDLE handle (void) const = 0; + +protected: + /// Do-nothing constructor. + ACE_Asynch_Write_Dgram_Result_Impl (void); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Asynch_IO_Impl.inl" +#endif /* __ACE_INLINE__ */ + +#endif /* ACE_HAS_WIN32_OVERLAPPED_IO || ACE_HAS_AIO_CALLS */ +#include /**/ "ace/post.h" +#endif /* ACE_ASYNCH_IO_IMPL_H */ diff --git a/dep/acelite/ace/Asynch_IO_Impl.inl b/dep/acelite/ace/Asynch_IO_Impl.inl new file mode 100644 index 00000000000..60dc69dfb31 --- /dev/null +++ b/dep/acelite/ace/Asynch_IO_Impl.inl @@ -0,0 +1,106 @@ +// -*- C++ -*- +// +// $Id: Asynch_IO_Impl.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE +ACE_Asynch_Result_Impl::ACE_Asynch_Result_Impl (void) +{ +} + +ACE_INLINE +ACE_Asynch_Operation_Impl::ACE_Asynch_Operation_Impl (void) +{ +} + +ACE_INLINE +ACE_Asynch_Read_Stream_Impl::ACE_Asynch_Read_Stream_Impl (void) + : ACE_Asynch_Operation_Impl () +{ +} + +ACE_INLINE +ACE_Asynch_Read_Stream_Result_Impl::ACE_Asynch_Read_Stream_Result_Impl (void) + : ACE_Asynch_Result_Impl () +{ +} + +ACE_INLINE +ACE_Asynch_Write_Stream_Impl::ACE_Asynch_Write_Stream_Impl (void) + : ACE_Asynch_Operation_Impl () +{ +} + +ACE_INLINE +ACE_Asynch_Write_Stream_Result_Impl::ACE_Asynch_Write_Stream_Result_Impl (void) + : ACE_Asynch_Result_Impl () +{ +} + +ACE_INLINE +ACE_Asynch_Read_File_Impl::ACE_Asynch_Read_File_Impl (void) + : ACE_Asynch_Operation_Impl (), + ACE_Asynch_Read_Stream_Impl () +{ +} + +ACE_INLINE +ACE_Asynch_Read_File_Result_Impl::ACE_Asynch_Read_File_Result_Impl (void) + : ACE_Asynch_Result_Impl (), + ACE_Asynch_Read_Stream_Result_Impl () +{ +} + +ACE_INLINE +ACE_Asynch_Write_File_Impl::ACE_Asynch_Write_File_Impl (void) + : ACE_Asynch_Operation_Impl (), + ACE_Asynch_Write_Stream_Impl () +{ +} + +ACE_INLINE +ACE_Asynch_Write_File_Result_Impl::ACE_Asynch_Write_File_Result_Impl (void) + : ACE_Asynch_Result_Impl (), + ACE_Asynch_Write_Stream_Result_Impl () +{ +} + +ACE_INLINE +ACE_Asynch_Accept_Impl::ACE_Asynch_Accept_Impl (void) + : ACE_Asynch_Operation_Impl () +{ +} + +ACE_INLINE +ACE_Asynch_Accept_Result_Impl::ACE_Asynch_Accept_Result_Impl (void) + : ACE_Asynch_Result_Impl () +{ +} + +ACE_INLINE +ACE_Asynch_Connect_Impl::ACE_Asynch_Connect_Impl (void) + : ACE_Asynch_Operation_Impl () +{ +} + +ACE_INLINE +ACE_Asynch_Connect_Result_Impl::ACE_Asynch_Connect_Result_Impl (void) + : ACE_Asynch_Result_Impl () +{ +} + + +ACE_INLINE +ACE_Asynch_Transmit_File_Impl::ACE_Asynch_Transmit_File_Impl (void) + : ACE_Asynch_Operation_Impl () +{ +} + +ACE_INLINE +ACE_Asynch_Transmit_File_Result_Impl::ACE_Asynch_Transmit_File_Result_Impl (void) + : ACE_Asynch_Result_Impl () +{ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Asynch_Pseudo_Task.cpp b/dep/acelite/ace/Asynch_Pseudo_Task.cpp new file mode 100644 index 00000000000..94f0d6980ed --- /dev/null +++ b/dep/acelite/ace/Asynch_Pseudo_Task.cpp @@ -0,0 +1,130 @@ +// $Id: Asynch_Pseudo_Task.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Asynch_Pseudo_Task.h" + +#include "ace/OS_NS_errno.h" +#include "ace/OS_NS_signal.h" + +ACE_RCSID(ace, Asynch_Pseudo_Task, "$Id: Asynch_Pseudo_Task.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_Asynch_Pseudo_Task::ACE_Asynch_Pseudo_Task () + : select_reactor_ (), // should be initialized before reactor_ + reactor_ (&select_reactor_, 0) // don't delete implementation +{ +} + +ACE_Asynch_Pseudo_Task::~ACE_Asynch_Pseudo_Task () +{ + this->stop (); +} + +int +ACE_Asynch_Pseudo_Task::start (void) +{ + if (this->reactor_.initialized () == 0) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("%N:%l:%p\n"), + ACE_TEXT ("start reactor is not initialized")), + -1); + + return this->activate () == -1 ? -1 : 0; // If started, return 0 +} + +int +ACE_Asynch_Pseudo_Task::stop (void) +{ + if (this->thr_count () == 0) // already stopped + return 0; + + if (this->reactor_.end_reactor_event_loop () == -1) + return -1; + + this->wait (); + this->reactor_.close (); + return 0; +} + +int +ACE_Asynch_Pseudo_Task::svc (void) +{ +#if !defined (ACE_WIN32) + + sigset_t RT_signals; + + sigemptyset (&RT_signals); + for (int si = ACE_SIGRTMIN; si <= ACE_SIGRTMAX; si++) + sigaddset (&RT_signals, si); + + if (ACE_OS::pthread_sigmask (SIG_BLOCK, &RT_signals, 0) != 0) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("Error:(%P | %t):%p\n"), + ACE_TEXT ("pthread_sigmask"))); +#endif + + reactor_.owner (ACE_Thread::self ()); + reactor_.run_reactor_event_loop (); + + return 0; +} + + + +int +ACE_Asynch_Pseudo_Task::register_io_handler (ACE_HANDLE handle, + ACE_Event_Handler *handler, + ACE_Reactor_Mask mask, + int flg_suspend) +{ + // Register the handler with the reactor. + if (-1 == this->reactor_.register_handler (handle, handler, mask)) + return -1; + + if (flg_suspend == 0) + return 0; + + // Suspend the handle now. Enable only when the accept is issued + // by the application. + if (this->reactor_.suspend_handler (handle) == -1) + { + ACE_ERROR + ((LM_ERROR, + ACE_TEXT ("%N:%l:%p\n"), + ACE_TEXT ("register_io_handler (suspended)"))); + this->reactor_.remove_handler (handle, ACE_Event_Handler::ALL_EVENTS_MASK + | ACE_Event_Handler::DONT_CALL); + return -1; + } + + return 0; +} + +int +ACE_Asynch_Pseudo_Task::remove_io_handler (ACE_HANDLE handle) +{ + return this->reactor_.remove_handler (handle, + ACE_Event_Handler::ALL_EVENTS_MASK + | ACE_Event_Handler::DONT_CALL); +} + +int +ACE_Asynch_Pseudo_Task::remove_io_handler (ACE_Handle_Set &set) +{ + return this->reactor_.remove_handler (set, ACE_Event_Handler::ALL_EVENTS_MASK + | ACE_Event_Handler::DONT_CALL); +} + +int +ACE_Asynch_Pseudo_Task::suspend_io_handler (ACE_HANDLE handle) +{ + return this->reactor_.suspend_handler (handle); +} + +int +ACE_Asynch_Pseudo_Task::resume_io_handler (ACE_HANDLE handle) +{ + return this->reactor_.resume_handler (handle); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Asynch_Pseudo_Task.h b/dep/acelite/ace/Asynch_Pseudo_Task.h new file mode 100644 index 00000000000..6e2c3a1d427 --- /dev/null +++ b/dep/acelite/ace/Asynch_Pseudo_Task.h @@ -0,0 +1,73 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Asynch_Pseudo_Task.h + * + * $Id: Asynch_Pseudo_Task.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Alexander Libman + */ +//============================================================================= + +#ifndef ACE_ASYNCH_PSEUDO_TASK_H +#define ACE_ASYNCH_PSEUDO_TASK_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +#pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Reactor.h" +#include "ace/Select_Reactor.h" +#include "ace/Task.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/* + * Specialization hook to replace the Reactor with the + * concrete Reactor implementation, e.g., select_st, + * select_mt etc. + */ +//@@ REACTOR_SPL_INCLUDE_FORWARD_DECL_ADD_HOOK + +/** + * @class ACE_Asynch_Pseudo_Task + * + */ +class ACE_Export ACE_Asynch_Pseudo_Task : public ACE_Task +{ +public: + ACE_Asynch_Pseudo_Task(); + virtual ~ACE_Asynch_Pseudo_Task(); + + int start (void); + int stop (void); + + int register_io_handler (ACE_HANDLE handle, + ACE_Event_Handler *handler, + ACE_Reactor_Mask mask, + int flg_suspend); + + int remove_io_handler (ACE_HANDLE handle); + int remove_io_handler (ACE_Handle_Set &set); + int resume_io_handler (ACE_HANDLE handle); + int suspend_io_handler (ACE_HANDLE handle); + +protected: + virtual int svc (void); + + /// Should be initialized before reactor_ + ACE_Select_Reactor select_reactor_; + + ACE_Reactor reactor_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" + +#endif /* ACE_ASYNCH_PSEUDO_TASK_H */ diff --git a/dep/acelite/ace/Atomic_Op.cpp b/dep/acelite/ace/Atomic_Op.cpp new file mode 100644 index 00000000000..10731e3c396 --- /dev/null +++ b/dep/acelite/ace/Atomic_Op.cpp @@ -0,0 +1,310 @@ +// $Id: Atomic_Op.cpp 89905 2010-04-16 13:04:47Z johnnyw $ + +#include "ace/Atomic_Op.h" +#include "ace/OS_NS_unistd.h" + +ACE_RCSID (ace, + Atomic_Op, + "$Id: Atomic_Op.cpp 89905 2010-04-16 13:04:47Z johnnyw $") + +#if !defined (__ACE_INLINE__) +#include "ace/Atomic_Op.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_HAS_BUILTIN_ATOMIC_OP) + +#if defined (ACE_INCLUDE_ATOMIC_OP_SPARC) +# include "ace/Atomic_Op_Sparc.h" +#endif /* ACE_INCLUDE_ATOMIC_OP_SPARC */ + +namespace { + +#if defined (_MSC_VER) +// Disable "no return value" warning, as we will be putting +// the return values directly into the EAX register. +#pragma warning (push) +#pragma warning (disable: 4035) +#endif /* _MSC_VER */ + +long +single_cpu_increment (volatile long *value) +{ +#if defined (ACE_HAS_INTEL_ASSEMBLY) + long tmp = 1; + unsigned long addr = reinterpret_cast (value); + asm( "xadd %0, (%1)" : "+r"(tmp) : "r"(addr) ); + return tmp + 1; +#elif !defined (ACE_HAS_SOLARIS_ATOMIC_LIB) && (defined (sun) || \ + (defined (__SUNPRO_CC) && (defined (__i386) || defined (__x86_64)))) + return ace_atomic_add_long ( + reinterpret_cast (value), 1); +#elif defined(__GNUC__) && defined(PPC) + long tmp; + asm("lwz %0,%1" : "=r" (tmp) : "m" (*value) ); + asm("addi %0,%0,1" : "+r" (tmp) ); + asm("stw %0,%1" : "+r" (tmp), "=m" (*value) ); + return tmp; +#else /* ACE_HAS_INTEL_ASSEMBLY*/ + ACE_UNUSED_ARG (value); + ACE_NOTSUP_RETURN (-1); +#endif /* ACE_HAS_INTEL_ASSEMBLY*/ +} + +long +single_cpu_decrement (volatile long *value) +{ +#if defined (ACE_HAS_INTEL_ASSEMBLY) + long tmp = -1; + unsigned long addr = reinterpret_cast (value); + asm( "xadd %0, (%1)" : "+r"(tmp) : "r"(addr) ); + return tmp - 1; +#elif !defined (ACE_HAS_SOLARIS_ATOMIC_LIB) && (defined (sun) || \ + (defined (__SUNPRO_CC) && (defined (__i386) || defined (__x86_64)))) + return ace_atomic_add_long ( + reinterpret_cast (value), -1); +#elif defined(__GNUC__) && defined(PPC) + long tmp; + asm("lwz %0,%1" : "=r" (tmp) : "m" (*value) ); + asm("addi %0,%0,-1" : "+r" (tmp) ); + asm("stw %0,%1" : "+r" (tmp), "=m" (*value) ); + return tmp; +#else /* ACE_HAS_INTEL_ASSEMBLY*/ + ACE_UNUSED_ARG (value); + ACE_NOTSUP_RETURN (-1); +#endif /* ACE_HAS_INTEL_ASSEMBLY*/ +} + +long +single_cpu_exchange (volatile long *value, long rhs) +{ +#if defined (ACE_HAS_INTEL_ASSEMBLY) + unsigned long addr = reinterpret_cast (value); + asm( "xchg %0, (%1)" : "+r"(rhs) : "r"(addr) ); + return rhs; +#elif !defined (ACE_HAS_SOLARIS_ATOMIC_LIB) && (defined (sun) || \ + (defined (__SUNPRO_CC) && (defined (__i386) || defined (__x86_64)))) + return ace_atomic_swap_long ( + reinterpret_cast (value), rhs); +#elif defined(__GNUC__) && defined(PPC) + long tmp; + asm("lwz %0,%1" : "=r" (tmp) : "m" (rhs) ); + asm("stw %0,%1" : "+r" (tmp), "=m" (*value) ); + return tmp; +#else /* ACE_HAS_INTEL_ASSEMBLY*/ + ACE_UNUSED_ARG (value); + ACE_UNUSED_ARG (rhs); + ACE_NOTSUP_RETURN (-1); +#endif /* ACE_HAS_INTEL_ASSEMBLY*/ +} + +long +single_cpu_exchange_add (volatile long *value, long rhs) +{ +#if defined (ACE_HAS_INTEL_ASSEMBLY) + unsigned long addr = reinterpret_cast (value); + asm( "xadd %0, (%1)" : "+r"(rhs) : "r"(addr) ); + return rhs; +#elif !defined (ACE_HAS_SOLARIS_ATOMIC_LIB) && (defined (sun) || \ + (defined (__SUNPRO_CC) && (defined (__i386) || defined (__x86_64)))) + return ace_atomic_swap_add_long ( + reinterpret_cast (value), rhs); +#elif defined(__GNUC__) && defined(PPC) + long tmp; + asm("add %0,%1,%2" : "=r" (tmp) : "r" (*value), "r" (rhs) ); + asm("stw %0,%1" : "+r" (tmp), "=m" (*value) ); + return tmp; +#elif defined (WIN32) && !defined (ACE_HAS_INTERLOCKED_EXCHANGEADD) +# if defined (_MSC_VER) + __asm + { + mov eax, rhs + mov edx, value + xadd [edx], eax + } + // Return value is already in EAX register. +# elif defined (__BORLANDC__) + _EAX = rhs; + _EDX = reinterpret_cast (value); + __emit__(0x0F, 0xC1, 0x02); // xadd [edx], eax + // Return value is already in EAX register. +# else /* _MSC_VER */ + ACE_UNUSED_ARG (value); + ACE_UNUSED_ARG (rhs); + ACE_NOTSUP_RETURN (-1); +# endif /* _MSC_VER */ +#else /* ACE_HAS_INTEL_ASSEMBLY*/ + ACE_UNUSED_ARG (value); + ACE_UNUSED_ARG (rhs); + ACE_NOTSUP_RETURN (-1); +#endif /* ACE_HAS_INTEL_ASSEMBLY*/ +} + +long +multi_cpu_increment (volatile long *value) +{ +#if defined (ACE_HAS_INTEL_ASSEMBLY) + long tmp = 1; + unsigned long addr = reinterpret_cast (value); + asm( "lock ; xadd %0, (%1)" : "+r"(tmp) : "r"(addr) ); + return tmp + 1; +#elif !defined (ACE_HAS_SOLARIS_ATOMIC_LIB) && (defined (sun) || \ + (defined (__SUNPRO_CC) && (defined (__i386) || defined (__x86_64)))) + return ace_atomic_add_long ( + reinterpret_cast (value), 1); +#else /* ACE_HAS_INTEL_ASSEMBLY*/ + ACE_UNUSED_ARG (value); + ACE_NOTSUP_RETURN (-1); +#endif /* ACE_HAS_INTEL_ASSEMBLY*/ +} + +long +multi_cpu_decrement (volatile long *value) +{ +#if defined (ACE_HAS_INTEL_ASSEMBLY) + long tmp = -1; + unsigned long addr = reinterpret_cast (value); + asm( "lock ; xadd %0, (%1)" : "+r"(tmp) : "r"(addr) ); + return tmp - 1; +#elif !defined (ACE_HAS_SOLARIS_ATOMIC_LIB) && (defined (sun) || \ + (defined (__SUNPRO_CC) && (defined (__i386) || defined (__x86_64)))) + return ace_atomic_add_long ( + reinterpret_cast (value), -1); +#else /* ACE_HAS_INTEL_ASSEMBLY*/ + ACE_UNUSED_ARG (value); + ACE_NOTSUP_RETURN (-1); +#endif /* ACE_HAS_INTEL_ASSEMBLY*/ +} + +long +multi_cpu_exchange (volatile long *value, long rhs) +{ +#if defined (ACE_HAS_INTEL_ASSEMBLY) + unsigned long addr = reinterpret_cast (value); + // The XCHG instruction automatically follows LOCK semantics + asm( "xchg %0, (%1)" : "+r"(rhs) : "r"(addr) ); + return rhs; +#elif !defined (ACE_HAS_SOLARIS_ATOMIC_LIB) && (defined (sun) || \ + (defined (__SUNPRO_CC) && (defined (__i386) || defined (__x86_64)))) + return ace_atomic_swap_long ( + reinterpret_cast (value), rhs); +#else /* ACE_HAS_INTEL_ASSEMBLY*/ + ACE_UNUSED_ARG (value); + ACE_UNUSED_ARG (rhs); + ACE_NOTSUP_RETURN (-1); +#endif /* ACE_HAS_INTEL_ASSEMBLY*/ +} + +long +multi_cpu_exchange_add (volatile long *value, long rhs) +{ +#if defined (ACE_HAS_INTEL_ASSEMBLY) + unsigned long addr = reinterpret_cast (value); + asm( "lock ; xadd %0, (%1)" : "+r"(rhs) : "r"(addr) ); + return rhs; +#elif !defined (ACE_HAS_SOLARIS_ATOMIC_LIB) && (defined (sun) || \ + (defined (__SUNPRO_CC) && (defined (__i386) || defined (__x86_64)))) + return ace_atomic_swap_add_long ( + reinterpret_cast (value), rhs); +#elif defined (WIN32) && !defined (ACE_HAS_INTERLOCKED_EXCHANGEADD) +# if defined (_MSC_VER) + __asm + { + mov eax, rhs + mov edx, value + lock xadd [edx], eax + } + // Return value is already in EAX register. +# elif defined (__BORLANDC__) + _EAX = rhs; + _EDX = reinterpret_cast (value); + __emit__(0xF0, 0x0F, 0xC1, 0x02); // lock xadd [edx], eax + // Return value is already in EAX register. +# else /* _MSC_VER */ + ACE_UNUSED_ARG (value); + ACE_UNUSED_ARG (rhs); + ACE_NOTSUP_RETURN (-1); +# endif /* _MSC_VER */ +#else /* ACE_HAS_INTEL_ASSEMBLY*/ + ACE_UNUSED_ARG (value); + ACE_UNUSED_ARG (rhs); + ACE_NOTSUP_RETURN (-1); +#endif /* ACE_HAS_INTEL_ASSEMBLY*/ +} + +#if defined (_MSC_VER) +#pragma warning (pop) +#endif /* _MSC_VER */ + +} // end namespace + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +long (*ACE_Atomic_Op::increment_fn_) (volatile long *) = multi_cpu_increment; +long (*ACE_Atomic_Op::decrement_fn_) (volatile long *) = multi_cpu_decrement; +long (*ACE_Atomic_Op::exchange_fn_) (volatile long *, long) = multi_cpu_exchange; +long (*ACE_Atomic_Op::exchange_add_fn_) (volatile long *, long) = multi_cpu_exchange_add; + +void +ACE_Atomic_Op::init_functions (void) +{ + if (ACE_OS::num_processors () == 1) + { + increment_fn_ = single_cpu_increment; + decrement_fn_ = single_cpu_decrement; + exchange_fn_ = single_cpu_exchange; + exchange_add_fn_ = single_cpu_exchange_add; + } + else + { + increment_fn_ = multi_cpu_increment; + decrement_fn_ = multi_cpu_decrement; + exchange_fn_ = multi_cpu_exchange; + exchange_add_fn_ = multi_cpu_exchange_add; + } +} + +void +ACE_Atomic_Op::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +long (*ACE_Atomic_Op::increment_fn_) (volatile long *) = multi_cpu_increment; +long (*ACE_Atomic_Op::decrement_fn_) (volatile long *) = multi_cpu_decrement; +long (*ACE_Atomic_Op::exchange_fn_) (volatile long *, long) = multi_cpu_exchange; +long (*ACE_Atomic_Op::exchange_add_fn_) (volatile long *, long) = multi_cpu_exchange_add; + +void +ACE_Atomic_Op::init_functions (void) +{ + if (ACE_OS::num_processors () == 1) + { + increment_fn_ = single_cpu_increment; + decrement_fn_ = single_cpu_decrement; + exchange_fn_ = single_cpu_exchange; + exchange_add_fn_ = single_cpu_exchange_add; + } + else + { + increment_fn_ = multi_cpu_increment; + decrement_fn_ = multi_cpu_decrement; + exchange_fn_ = multi_cpu_exchange; + exchange_add_fn_ = multi_cpu_exchange_add; + } +} + +void +ACE_Atomic_Op::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_BUILTIN_ATOMIC_OP */ diff --git a/dep/acelite/ace/Atomic_Op.h b/dep/acelite/ace/Atomic_Op.h new file mode 100644 index 00000000000..8ebc6c6d8b9 --- /dev/null +++ b/dep/acelite/ace/Atomic_Op.h @@ -0,0 +1,355 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Atomic_Op.h + * + * $Id: Atomic_Op.h 89936 2010-04-20 13:04:53Z johnnyw $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_ATOMIC_OP_H +#define ACE_ATOMIC_OP_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Thread_Mutex.h" + +// Include the templates here. +#include "ace/Atomic_Op_T.h" + +// Determine whether builtin atomic op support is +// available on this platform. +#if defined (ACE_HAS_THREADS) +# if defined (WIN32) +# if defined (ACE_HAS_INTRINSIC_INTERLOCKED) +# define ACE_HAS_BUILTIN_ATOMIC_OP +# endif /* ACE_HAS_INTRINSIC_INTERLOCKED */ +# if defined (ACE_HAS_INTERLOCKED_EXCHANGEADD) +# define ACE_HAS_BUILTIN_ATOMIC_OP +# else /* ACE_HAS_INTERLOCKED_EXCHANGEADD */ + // Inline assembly emulation of InterlockedExchangeAdd + // is currently only implemented for MSVC (x86 only) and Borland. +# if (defined (_MSC_VER) && defined (_M_IX86)) || defined (__BORLANDC__) +# define ACE_HAS_BUILTIN_ATOMIC_OP +# endif /* _MSC_VER || __BORLANDC__ */ +# endif /* ACE_HAS_INTERLOCKED_EXCHANGEADD */ +# elif defined (ACE_HAS_INTEL_ASSEMBLY) +# define ACE_HAS_BUILTIN_ATOMIC_OP +# elif defined (ACE_HAS_VXATOMICLIB) +# define ACE_HAS_BUILTIN_ATOMIC_OP +# elif defined (ACE_HAS_SOLARIS_ATOMIC_LIB) && !defined (ACE_HAS_BUILTIN_ATOMIC_OP) +# define ACE_HAS_BUILTIN_ATOMIC_OP +# endif /* WIN32 */ +#endif /* ACE_HAS_THREADS */ + +// If we have the GCC Atomic builtin support, use it +#if defined (ACE_HAS_GCC_ATOMIC_BUILTINS) && (ACE_HAS_GCC_ATOMIC_BUILTINS == 1) +# undef ACE_HAS_BUILTIN_ATOMIC_OP +#endif + +// Include the templates here. +#include "ace/Atomic_Op_GCC_T.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +#if defined (ACE_HAS_BUILTIN_ATOMIC_OP) + +/** + * @brief Specialization of ACE_Atomic_Op for platforms that + * support atomic integer operations. + * + * Specialization of ACE_Atomic_Op for platforms that support atomic + * integer operations. + */ +template<> +class ACE_Export ACE_Atomic_Op +{ +public: + /// Initialize @c value_ to 0. + ACE_Atomic_Op (void); + + /// Initialize @c value_ to c. + ACE_Atomic_Op (long c); + + /// Manage copying... + ACE_Atomic_Op (const ACE_Atomic_Op &c); + + /// Atomically pre-increment @c value_. + long operator++ (void); + + /// Atomically post-increment @c value_. + long operator++ (int); + + /// Atomically increment @c value_ by rhs. + long operator+= (long rhs); + + /// Atomically pre-decrement @c value_. + long operator-- (void); + + /// Atomically post-decrement @c value_. + long operator-- (int); + + /// Atomically decrement @c value_ by rhs. + long operator-= (long rhs); + + /// Atomically compare @c value_ with rhs. + bool operator== (long rhs) const; + + /// Atomically compare @c value_ with rhs. + bool operator!= (long rhs) const; + + /// Atomically check if @c value_ greater than or equal to rhs. + bool operator>= (long rhs) const; + + /// Atomically check if @c value_ greater than rhs. + bool operator> (long rhs) const; + + /// Atomically check if @c value_ less than or equal to rhs. + bool operator<= (long rhs) const; + + /// Atomically check if @c value_ less than rhs. + bool operator< (long rhs) const; + + /// Atomically assign rhs to @c value_. + ACE_Atomic_Op &operator= (long rhs); + + /// Atomically assign to @c value_. + ACE_Atomic_Op &operator= (const ACE_Atomic_Op &rhs); + + /// Explicitly return @c value_. + long value (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Explicitly return @c value_ (by reference). + volatile long &value_i (void); + + // ACE_ALLOC_HOOK_DECLARE; + // Declare the dynamic allocation hooks. + + /// Used during ACE object manager initialization to optimize the fast + /// atomic op implementation according to the number of CPUs. + static void init_functions (void); + +private: + + // This function cannot be supported by this template specialization. + // If you need access to an underlying lock, use the ACE_Atomic_Op_Ex + // template instead. + ACE_Thread_Mutex &mutex (void); + +private: + + /// Current object decorated by the atomic op. + volatile long value_; + + // Pointers to selected atomic op implementations. + static long (*increment_fn_) (volatile long *); + static long (*decrement_fn_) (volatile long *); + static long (*exchange_fn_) (volatile long *, long); + static long (*exchange_add_fn_) (volatile long *, long); +}; + +/** + * @brief Specialization of ACE_Atomic_Op for platforms that + * support atomic integer operations. + * + * Specialization of ACE_Atomic_Op for platforms that support atomic + * integer operations. + */ +template<> +class ACE_Export ACE_Atomic_Op +{ +public: + /// Initialize @c value_ to 0. + ACE_Atomic_Op (void); + + /// Initialize @c value_ to c. + ACE_Atomic_Op (unsigned long c); + + /// Manage copying... + ACE_Atomic_Op (const ACE_Atomic_Op &c); + + /// Atomically pre-increment @c value_. + unsigned long operator++ (void); + + /// Atomically post-increment @c value_. + unsigned long operator++ (int); + + /// Atomically increment @c value_ by rhs. + unsigned long operator+= (unsigned long rhs); + + /// Atomically pre-decrement @c value_. + unsigned long operator-- (void); + + /// Atomically post-decrement @c value_. + unsigned long operator-- (int); + + /// Atomically decrement @c value_ by rhs. + unsigned long operator-= (unsigned long rhs); + + /// Atomically compare @c value_ with rhs. + bool operator== (unsigned long rhs) const; + + /// Atomically compare @c value_ with rhs. + bool operator!= (unsigned long rhs) const; + + /// Atomically check if @c value_ greater than or equal to rhs. + bool operator>= (unsigned long rhs) const; + + /// Atomically check if @c value_ greater than rhs. + bool operator> (unsigned long rhs) const; + + /// Atomically check if @c value_ less than or equal to rhs. + bool operator<= (unsigned long rhs) const; + + /// Atomically check if @c value_ less than rhs. + bool operator< (unsigned long rhs) const; + + /// Atomically assign rhs to @c value_. + ACE_Atomic_Op &operator= (unsigned long rhs); + + /// Atomically assign to @c value_. + ACE_Atomic_Op &operator= (const ACE_Atomic_Op &rhs); + + /// Explicitly return @c value_. + unsigned long value (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Explicitly return @c value_ (by reference). + volatile unsigned long &value_i (void); + + // ACE_ALLOC_HOOK_DECLARE; + // Declare the dynamic allocation hooks. + + /// Used during ACE object manager initialization to optimize the fast + /// atomic op implementation according to the number of CPUs. + static void init_functions (void); + +private: + + /// This function cannot be supported by this template specialization. + /// If you need access to an underlying lock, use the ACE_Atomic_Op_Ex + /// template instead. + ACE_Thread_Mutex &mutex (void); + +private: + + /// Current object decorated by the atomic op. + volatile unsigned long value_; + + // Pointers to selected atomic op implementations. + static long (*increment_fn_) (volatile long *); + static long (*decrement_fn_) (volatile long *); + static long (*exchange_fn_) (volatile long *, long); + static long (*exchange_add_fn_) (volatile long *, long); +}; + +#endif /* !ACE_HAS_BUILTIN_ATOMIC_OP */ + +#if defined (ACE_HAS_GCC_ATOMIC_BUILTINS) && (ACE_HAS_GCC_ATOMIC_BUILTINS == 1) + +template<> +class ACE_Export ACE_Atomic_Op +: public ACE_Atomic_Op_GCC +{ +public: + ACE_Atomic_Op (void); + ACE_Atomic_Op (int c); + ACE_Atomic_Op (const ACE_Atomic_Op &c); + ACE_Atomic_Op &operator= (int rhs); +}; + +template<> +class ACE_Export ACE_Atomic_Op +: public ACE_Atomic_Op_GCC +{ +public: + ACE_Atomic_Op (void); + ACE_Atomic_Op (unsigned int c); + ACE_Atomic_Op (const ACE_Atomic_Op &c); + ACE_Atomic_Op &operator= (unsigned int rhs); +}; + +// If we have built in atomic op, use that, the assignment operator +// is faster for a long/unsinged long +template<> +class ACE_Export ACE_Atomic_Op +: public ACE_Atomic_Op_GCC +{ +public: + ACE_Atomic_Op (void); + ACE_Atomic_Op (long c); + ACE_Atomic_Op (const ACE_Atomic_Op &c); + ACE_Atomic_Op &operator= (long rhs); +}; + +template<> +class ACE_Export ACE_Atomic_Op +: public ACE_Atomic_Op_GCC +{ +public: + ACE_Atomic_Op (void); + ACE_Atomic_Op (unsigned long c); + ACE_Atomic_Op (const ACE_Atomic_Op &c); + ACE_Atomic_Op &operator= (unsigned long rhs); +}; + +#if !defined (ACE_LACKS_GCC_ATOMIC_BUILTINS_2) +template<> +class ACE_Export ACE_Atomic_Op +: public ACE_Atomic_Op_GCC +{ +public: + ACE_Atomic_Op (void); + ACE_Atomic_Op (short c); + ACE_Atomic_Op (const ACE_Atomic_Op &c); + ACE_Atomic_Op &operator= (short rhs); +}; + +template<> +class ACE_Export ACE_Atomic_Op +: public ACE_Atomic_Op_GCC +{ +public: + ACE_Atomic_Op (void); + ACE_Atomic_Op (unsigned short c); + ACE_Atomic_Op (const ACE_Atomic_Op &c); + ACE_Atomic_Op &operator= (unsigned short rhs); +}; +#endif + +#if !defined (ACE_LACKS_GCC_ATOMIC_BUILTINS_1) +template<> +class ACE_Export ACE_Atomic_Op +: public ACE_Atomic_Op_GCC +{ +public: + ACE_Atomic_Op (void); + ACE_Atomic_Op (bool c); + ACE_Atomic_Op (const ACE_Atomic_Op &c); + ACE_Atomic_Op &operator= (bool rhs); +}; +#endif + +#endif /* ACE_HAS_BUILTIN_ATOMIC_OP */ + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Atomic_Op.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /*ACE_ATOMIC_OP_H*/ diff --git a/dep/acelite/ace/Atomic_Op.inl b/dep/acelite/ace/Atomic_Op.inl new file mode 100644 index 00000000000..6dcade6c04d --- /dev/null +++ b/dep/acelite/ace/Atomic_Op.inl @@ -0,0 +1,582 @@ +// -*- C++ -*- +// +// $Id: Atomic_Op.inl 89905 2010-04-16 13:04:47Z johnnyw $ + +#if defined (ACE_HAS_INTRINSIC_INTERLOCKED) +# include "ace/os_include/os_intrin.h" +# pragma intrinsic (_InterlockedExchange, _InterlockedExchangeAdd, _InterlockedIncrement, _InterlockedDecrement) +#endif /* ACE_HAS_INTRINSIC_INTERLOCKED */ + +#if defined (ACE_HAS_VXATOMICLIB) +# include +#endif + +#if defined (ACE_HAS_SOLARIS_ATOMIC_LIB) +# include +#endif + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +#if defined (ACE_HAS_BUILTIN_ATOMIC_OP) + +ACE_INLINE +ACE_Atomic_Op::ACE_Atomic_Op (void) + : value_ (0) +{ +} + +ACE_INLINE +ACE_Atomic_Op::ACE_Atomic_Op (long c) + : value_ (c) +{ +} + +ACE_INLINE +ACE_Atomic_Op::ACE_Atomic_Op ( + const ACE_Atomic_Op &rhs) + : value_ (rhs.value_) +{ +} + +ACE_INLINE long +ACE_Atomic_Op::operator++ (void) +{ +#if defined (ACE_HAS_INTRINSIC_INTERLOCKED) + return ::_InterlockedIncrement (const_cast (&this->value_)); +#elif defined (WIN32) + return ::InterlockedIncrement (const_cast (&this->value_)); +#elif defined (ACE_HAS_VXATOMICLIB) + return ::vxAtomicInc (reinterpret_cast (const_cast (&this->value_))) + 1; +#elif defined (ACE_HAS_SOLARIS_ATOMIC_LIB) + return ::atomic_inc_ulong_nv (reinterpret_cast(&this->value_)); +#else /* WIN32 */ + return (*increment_fn_) (&this->value_); +#endif /* WIN32 */ +} + +ACE_INLINE long +ACE_Atomic_Op::operator++ (int) +{ + return ++*this - 1; +} + +ACE_INLINE long +ACE_Atomic_Op::operator-- (void) +{ +#if defined (ACE_HAS_INTRINSIC_INTERLOCKED) + return ::_InterlockedDecrement (const_cast (&this->value_)); +#elif defined (WIN32) + return ::InterlockedDecrement (const_cast (&this->value_)); +#elif defined (ACE_HAS_VXATOMICLIB) + return ::vxAtomicDec (reinterpret_cast (const_cast (&this->value_))) - 1; +#elif defined (ACE_HAS_SOLARIS_ATOMIC_LIB) + return ::atomic_dec_ulong_nv (reinterpret_cast(&this->value_)); +#else /* WIN32 */ + return (*decrement_fn_) (&this->value_); +#endif /* WIN32 */ +} + +ACE_INLINE long +ACE_Atomic_Op::operator-- (int) +{ + return --*this + 1; +} + +ACE_INLINE long +ACE_Atomic_Op::operator+= (long rhs) +{ +#if defined (ACE_HAS_INTRINSIC_INTERLOCKED) + return ::_InterlockedExchangeAdd (const_cast (&this->value_), + rhs) + rhs; +#elif defined (WIN32) && defined (ACE_HAS_INTERLOCKED_EXCHANGEADD) + return ::InterlockedExchangeAdd (const_cast (&this->value_), + rhs) + rhs; +#elif defined (ACE_HAS_VXATOMICLIB) + return ::vxAtomicAdd (reinterpret_cast (const_cast (&this->value_)), rhs) + rhs; +#elif defined (ACE_HAS_SOLARIS_ATOMIC_LIB) + return ::atomic_add_long_nv (reinterpret_cast(&this->value_), rhs); +#else /* WIN32 && ACE_HAS_INTERLOCKED_EXCHANGEADD */ + return (*exchange_add_fn_) (&this->value_, rhs) + rhs; +#endif /* WIN32 && ACE_HAS_INTERLOCKED_EXCHANGEADD */ +} + +ACE_INLINE long +ACE_Atomic_Op::operator-= (long rhs) +{ +#if defined (ACE_HAS_INTRINSIC_INTERLOCKED) + return ::_InterlockedExchangeAdd (const_cast (&this->value_), + -rhs) - rhs; +#elif defined (WIN32) && defined (ACE_HAS_INTERLOCKED_EXCHANGEADD) + return ::InterlockedExchangeAdd (const_cast (&this->value_), + -rhs) - rhs; +#elif defined (ACE_HAS_VXATOMICLIB) + return ::vxAtomicSub (reinterpret_cast (const_cast (&this->value_)), rhs) - rhs; +#elif defined (ACE_HAS_SOLARIS_ATOMIC_LIB) + return ::atomic_add_long_nv (reinterpret_cast(&this->value_), -rhs); +#else /* WIN32 && ACE_HAS_INTERLOCKED_EXCHANGEADD */ + return (*exchange_add_fn_) (&this->value_, -rhs) - rhs; +#endif /* WIN32 && ACE_HAS_INTERLOCKED_EXCHANGEADD */ +} + +ACE_INLINE bool +ACE_Atomic_Op::operator== (long rhs) const +{ + return (this->value_ == rhs); +} + +ACE_INLINE bool +ACE_Atomic_Op::operator!= (long rhs) const +{ + return (this->value_ != rhs); +} + +ACE_INLINE bool +ACE_Atomic_Op::operator>= (long rhs) const +{ + return (this->value_ >= rhs); +} + +ACE_INLINE bool +ACE_Atomic_Op::operator> (long rhs) const +{ + return (this->value_ > rhs); +} + +ACE_INLINE bool +ACE_Atomic_Op::operator<= (long rhs) const +{ + return (this->value_ <= rhs); +} + +ACE_INLINE bool +ACE_Atomic_Op::operator< (long rhs) const +{ + return (this->value_ < rhs); +} + +ACE_INLINE ACE_Atomic_Op & +ACE_Atomic_Op::operator= (long rhs) +{ +#if defined (ACE_HAS_INTRINSIC_INTERLOCKED) + ::_InterlockedExchange (const_cast (&this->value_), rhs); +#elif defined (WIN32) + ::InterlockedExchange (const_cast (&this->value_), rhs); +#elif defined (ACE_HAS_VXATOMICLIB) + ::vxAtomicSet (reinterpret_cast (const_cast (&this->value_)), rhs); +#elif defined (ACE_HAS_SOLARIS_ATOMIC_LIB) + ::atomic_swap_ulong (reinterpret_cast(&this->value_), rhs); +#else /* WIN32 */ + (*exchange_fn_) (&this->value_, rhs); +#endif /* WIN32 */ + return *this; +} + +ACE_INLINE ACE_Atomic_Op & +ACE_Atomic_Op::operator= ( + const ACE_Atomic_Op &rhs) +{ +#if defined (ACE_HAS_INTRINSIC_INTERLOCKED) + ::_InterlockedExchange (const_cast (&this->value_), rhs.value_); +#elif defined (WIN32) + ::InterlockedExchange (const_cast (&this->value_), rhs.value_); +#elif defined (ACE_HAS_VXATOMICLIB) + ::vxAtomicSet (reinterpret_cast (const_cast (&this->value_)), rhs.value_); +#elif defined (ACE_HAS_SOLARIS_ATOMIC_LIB) + ::atomic_swap_ulong (reinterpret_cast(&this->value_), rhs.value_); +#else /* WIN32 */ + (*exchange_fn_) (&this->value_, rhs.value_); +#endif /* WIN32 */ + return *this; +} + +ACE_INLINE long +ACE_Atomic_Op::value (void) const +{ + return this->value_; +} + +ACE_INLINE volatile long & +ACE_Atomic_Op::value_i (void) +{ + return this->value_; +} + + +ACE_INLINE +ACE_Atomic_Op::ACE_Atomic_Op (void) + : value_ (0) +{ +} + +ACE_INLINE +ACE_Atomic_Op::ACE_Atomic_Op (unsigned long c) + : value_ (c) +{ +} + +ACE_INLINE +ACE_Atomic_Op::ACE_Atomic_Op ( + const ACE_Atomic_Op &rhs) + : value_ (rhs.value_) +{ +} + +ACE_INLINE unsigned long +ACE_Atomic_Op::operator++ (void) +{ +#if defined (ACE_HAS_INTRINSIC_INTERLOCKED) + return static_cast (::_InterlockedIncrement (const_cast (reinterpret_cast(&this->value_)))); +#elif defined (WIN32) + return static_cast (::InterlockedIncrement (const_cast (reinterpret_cast(&this->value_)))); +#elif defined (ACE_HAS_VXATOMICLIB) + return static_cast (::vxAtomicInc (reinterpret_cast (const_cast (reinterpret_cast(&this->value_))))) + 1; +#elif defined (ACE_HAS_SOLARIS_ATOMIC_LIB) + return ::atomic_inc_ulong_nv (&this->value_); +#else /* WIN32 */ + return static_cast ((*increment_fn_) (reinterpret_cast (&this->value_))); +#endif /* WIN32 */ +} + +ACE_INLINE unsigned long +ACE_Atomic_Op::operator++ (int) +{ + return ++*this - 1; +} + +ACE_INLINE unsigned long +ACE_Atomic_Op::operator-- (void) +{ +#if defined (ACE_HAS_INTRINSIC_INTERLOCKED) + return static_cast (::_InterlockedDecrement (const_cast (reinterpret_cast(&this->value_)))); +#elif defined (WIN32) + return static_cast (::InterlockedDecrement (const_cast (reinterpret_cast(&this->value_)))); +#elif defined (ACE_HAS_VXATOMICLIB) + return static_cast (::vxAtomicDec (reinterpret_cast (const_cast (reinterpret_cast(&this->value_))))) - 1; +#elif defined (ACE_HAS_SOLARIS_ATOMIC_LIB) + return ::atomic_dec_ulong_nv (&this->value_); +#else /* WIN32 */ + return static_cast ((*decrement_fn_) (reinterpret_cast (&this->value_))); +#endif /* WIN32 */ +} + +ACE_INLINE unsigned long +ACE_Atomic_Op::operator-- (int) +{ + return --*this + 1; +} + +ACE_INLINE unsigned long +ACE_Atomic_Op::operator+= (unsigned long rhs) +{ +#if defined (ACE_HAS_INTRINSIC_INTERLOCKED) + return static_cast (::_InterlockedExchangeAdd (const_cast (reinterpret_cast (&this->value_)), + rhs)) + rhs; +#elif defined (WIN32) && defined (ACE_HAS_INTERLOCKED_EXCHANGEADD) + return static_cast (::InterlockedExchangeAdd (const_cast (reinterpret_cast (&this->value_)), + rhs)) + rhs; +#elif defined (ACE_HAS_VXATOMICLIB) + return static_cast (::vxAtomicAdd (reinterpret_cast (const_cast (reinterpret_cast(&this->value_))), rhs)) + rhs; +#elif defined (ACE_HAS_SOLARIS_ATOMIC_LIB) + return ::atomic_add_long_nv (&this->value_, rhs); +#else /* WIN32 && ACE_HAS_INTERLOCKED_EXCHANGEADD */ + return static_cast ((*exchange_add_fn_) (reinterpret_cast (&this->value_), rhs)) + rhs; +#endif /* WIN32 && ACE_HAS_INTERLOCKED_EXCHANGEADD */ +} + +ACE_INLINE unsigned long +ACE_Atomic_Op::operator-= (unsigned long rhs) +{ +#if defined (ACE_HAS_INTRINSIC_INTERLOCKED) + return static_cast (::_InterlockedExchangeAdd (const_cast (reinterpret_cast(&this->value_)), + -static_cast(rhs))) - rhs; +#elif defined (WIN32) && defined (ACE_HAS_INTERLOCKED_EXCHANGEADD) + return static_cast (::InterlockedExchangeAdd (const_cast (reinterpret_cast(&this->value_)), + -static_cast(rhs))) - rhs; +#elif defined (ACE_HAS_VXATOMICLIB) + return static_cast (::vxAtomicSub (reinterpret_cast (const_cast (reinterpret_cast(&this->value_))), rhs)) - rhs; +#elif defined (ACE_HAS_SOLARIS_ATOMIC_LIB) + return ::atomic_add_long_nv (&this->value_, -rhs); +#else /* WIN32 && ACE_HAS_INTERLOCKED_EXCHANGEADD */ + long l_rhs = static_cast (rhs); + return static_cast ((*exchange_add_fn_) (reinterpret_cast (&this->value_), -l_rhs)) - rhs; +#endif /* WIN32 && ACE_HAS_INTERLOCKED_EXCHANGEADD */ +} + +ACE_INLINE bool +ACE_Atomic_Op::operator== (unsigned long rhs) const +{ + return (this->value_ == rhs); +} + +ACE_INLINE bool +ACE_Atomic_Op::operator!= (unsigned long rhs) const +{ + return (this->value_ != rhs); +} + +ACE_INLINE bool +ACE_Atomic_Op::operator>= (unsigned long rhs) const +{ + return (this->value_ >= rhs); +} + +ACE_INLINE bool +ACE_Atomic_Op::operator> (unsigned long rhs) const +{ + return (this->value_ > rhs); +} + +ACE_INLINE bool +ACE_Atomic_Op::operator<= (unsigned long rhs) const +{ + return (this->value_ <= rhs); +} + +ACE_INLINE bool +ACE_Atomic_Op::operator< (unsigned long rhs) const +{ + return (this->value_ < rhs); +} + +ACE_INLINE ACE_Atomic_Op & +ACE_Atomic_Op::operator= (unsigned long rhs) +{ +#if defined (ACE_HAS_INTRINSIC_INTERLOCKED) + ::_InterlockedExchange (const_cast (reinterpret_cast (&this->value_)), rhs); +#elif defined (WIN32) + ::InterlockedExchange (const_cast (reinterpret_cast (&this->value_)), rhs); +#elif defined (ACE_HAS_VXATOMICLIB) + ::vxAtomicSet (reinterpret_cast (const_cast (reinterpret_cast (&this->value_))), rhs); +#elif defined (ACE_HAS_SOLARIS_ATOMIC_LIB) + ::atomic_swap_ulong (&this->value_, rhs); +#else /* WIN32 */ + (*exchange_fn_) (reinterpret_cast (&this->value_), rhs); +#endif /* WIN32 */ + return *this; +} + +ACE_INLINE ACE_Atomic_Op & +ACE_Atomic_Op::operator= ( + const ACE_Atomic_Op &rhs) +{ +#if defined (ACE_HAS_INTRINSIC_INTERLOCKED) + ::_InterlockedExchange (const_cast (reinterpret_cast (&this->value_)), rhs.value_); +#elif defined (WIN32) + ::InterlockedExchange (const_cast (reinterpret_cast (&this->value_)), rhs.value_); +#elif defined (ACE_HAS_VXATOMICLIB) + ::vxAtomicSet (reinterpret_cast (const_cast (reinterpret_cast (&this->value_))), rhs.value_); +#elif defined (ACE_HAS_SOLARIS_ATOMIC_LIB) + ::atomic_swap_ulong (&this->value_, rhs.value_); +#else /* WIN32 */ + (*exchange_fn_) (reinterpret_cast (&this->value_), rhs.value_); +#endif /* WIN32 */ + return *this; +} + +ACE_INLINE unsigned long +ACE_Atomic_Op::value (void) const +{ + return this->value_; +} + +ACE_INLINE volatile unsigned long & +ACE_Atomic_Op::value_i (void) +{ + return this->value_; +} + +#endif /* ACE_HAS_BUILTIN_ATOMIC_OP */ + +#if defined (ACE_HAS_GCC_ATOMIC_BUILTINS) && (ACE_HAS_GCC_ATOMIC_BUILTINS == 1) + +ACE_INLINE +ACE_Atomic_Op::ACE_Atomic_Op (void) : + ACE_Atomic_Op_GCC () +{ +} + +ACE_INLINE +ACE_Atomic_Op::ACE_Atomic_Op (int c) : + ACE_Atomic_Op_GCC(c) +{ +} + +ACE_INLINE +ACE_Atomic_Op::ACE_Atomic_Op (const ACE_Atomic_Op &c) : + ACE_Atomic_Op_GCC(c) +{ +} + +ACE_INLINE +ACE_Atomic_Op& +ACE_Atomic_Op::operator= (int rhs) +{ + ACE_Atomic_Op_GCC::operator= (rhs); + return *this; +} + + +ACE_INLINE +ACE_Atomic_Op::ACE_Atomic_Op (void) : + ACE_Atomic_Op_GCC() +{ +} + +ACE_INLINE +ACE_Atomic_Op::ACE_Atomic_Op (const ACE_Atomic_Op &c) : + ACE_Atomic_Op_GCC(c) +{ +} + +ACE_INLINE +ACE_Atomic_Op::ACE_Atomic_Op (unsigned int c) : + ACE_Atomic_Op_GCC(c) +{ +} + +ACE_INLINE +ACE_Atomic_Op& +ACE_Atomic_Op::operator= (unsigned int rhs) +{ + ACE_Atomic_Op_GCC::operator= (rhs); + return *this; +} + +ACE_INLINE +ACE_Atomic_Op::ACE_Atomic_Op (void) : + ACE_Atomic_Op_GCC() +{ +} + +ACE_INLINE +ACE_Atomic_Op::ACE_Atomic_Op (long c) : + ACE_Atomic_Op_GCC(c) +{ +} + +ACE_INLINE +ACE_Atomic_Op::ACE_Atomic_Op (const ACE_Atomic_Op &c) : + ACE_Atomic_Op_GCC(c) +{ +} + +ACE_INLINE +ACE_Atomic_Op& +ACE_Atomic_Op::operator= (long rhs) +{ + ACE_Atomic_Op_GCC::operator= (rhs); + return *this; +} + +ACE_INLINE +ACE_Atomic_Op::ACE_Atomic_Op (void) : + ACE_Atomic_Op_GCC () +{ +} + +ACE_INLINE +ACE_Atomic_Op::ACE_Atomic_Op (unsigned long c) : + ACE_Atomic_Op_GCC(c) +{ +} + +ACE_INLINE +ACE_Atomic_Op::ACE_Atomic_Op (const ACE_Atomic_Op &c) : + ACE_Atomic_Op_GCC(c) +{ +} + +ACE_INLINE +ACE_Atomic_Op& +ACE_Atomic_Op::operator= (unsigned long rhs) +{ + ACE_Atomic_Op_GCC::operator= (rhs); + return *this; +} + +#if !defined (ACE_LACKS_GCC_ATOMIC_BUILTINS_2) +ACE_INLINE +ACE_Atomic_Op::ACE_Atomic_Op (void) : + ACE_Atomic_Op_GCC() +{ +} + +ACE_INLINE +ACE_Atomic_Op::ACE_Atomic_Op (short c) : + ACE_Atomic_Op_GCC(c) +{ +} + +ACE_INLINE +ACE_Atomic_Op::ACE_Atomic_Op (const ACE_Atomic_Op &c) : + ACE_Atomic_Op_GCC(c) +{ +} + +ACE_INLINE +ACE_Atomic_Op& +ACE_Atomic_Op::operator= (short rhs) +{ + ACE_Atomic_Op_GCC::operator= (rhs); + return *this; +} + +ACE_INLINE +ACE_Atomic_Op::ACE_Atomic_Op (void) : + ACE_Atomic_Op_GCC () +{ +} + +ACE_INLINE +ACE_Atomic_Op::ACE_Atomic_Op (unsigned short c) : + ACE_Atomic_Op_GCC(c) +{ +} + +ACE_INLINE +ACE_Atomic_Op::ACE_Atomic_Op (const ACE_Atomic_Op &c) : + ACE_Atomic_Op_GCC(c) +{ +} + +ACE_INLINE +ACE_Atomic_Op& +ACE_Atomic_Op::operator= (unsigned short rhs) +{ + ACE_Atomic_Op_GCC::operator= (rhs); + return *this; +} +#endif + +#if !defined (ACE_LACKS_GCC_ATOMIC_BUILTINS_1) +ACE_INLINE +ACE_Atomic_Op::ACE_Atomic_Op (void) : + ACE_Atomic_Op_GCC () +{ +} + +ACE_INLINE +ACE_Atomic_Op::ACE_Atomic_Op (bool c) : + ACE_Atomic_Op_GCC(c) +{ +} + +ACE_INLINE +ACE_Atomic_Op::ACE_Atomic_Op (const ACE_Atomic_Op &c) : + ACE_Atomic_Op_GCC(c) +{ +} + +ACE_INLINE +ACE_Atomic_Op& +ACE_Atomic_Op::operator= (bool rhs) +{ + ACE_Atomic_Op_GCC::operator= (rhs); + return *this; +} +#endif + +#endif /* ACE_HAS_GCC_ATOMIC_BUILTINS==1 */ + +ACE_END_VERSIONED_NAMESPACE_DECL + diff --git a/dep/acelite/ace/Atomic_Op_GCC_T.cpp b/dep/acelite/ace/Atomic_Op_GCC_T.cpp new file mode 100644 index 00000000000..bbe6ec676ec --- /dev/null +++ b/dep/acelite/ace/Atomic_Op_GCC_T.cpp @@ -0,0 +1,29 @@ +// $Id: Atomic_Op_GCC_T.cpp 89345 2010-03-05 13:04:51Z johnnyw $ + +#include "ace/OS_NS_unistd.h" + +ACE_RCSID (ace, + Atomic_Op_GCC, + "$Id: Atomic_Op_GCC_T.cpp 89345 2010-03-05 13:04:51Z johnnyw $") + +#if defined (ACE_HAS_GCC_ATOMIC_BUILTINS) && (ACE_HAS_GCC_ATOMIC_BUILTINS == 1) + +#if !defined (__ACE_INLINE__) +#include "ace/Atomic_Op_GCC_T.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template +void +ACE_Atomic_Op_GCC::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_GCC_ATOMIC_BUILTINS */ diff --git a/dep/acelite/ace/Atomic_Op_GCC_T.h b/dep/acelite/ace/Atomic_Op_GCC_T.h new file mode 100644 index 00000000000..92bc771dda6 --- /dev/null +++ b/dep/acelite/ace/Atomic_Op_GCC_T.h @@ -0,0 +1,136 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Atomic_Op_GCC_T.h + * + * $Id: Atomic_Op_GCC_T.h 89339 2010-03-05 12:20:47Z johnnyw $ + * + * @author Johnny Willemsen +class ACE_Export ACE_Atomic_Op_GCC +{ +public: + /// Atomically pre-increment @c value_. + T operator++ (void); + + /// Atomically post-increment @c value_. + T operator++ (int); + + /// Atomically increment @c value_ by rhs. + T operator+= (T rhs); + + /// Atomically pre-decrement @c value_. + T operator-- (void); + + /// Atomically post-decrement @c value_. + T operator-- (int); + + /// Atomically decrement @c value_ by rhs. + T operator-= (T rhs); + + /// Atomically compare @c value_ with rhs. + bool operator== (T rhs) const; + + /// Atomically compare @c value_ with rhs. + bool operator!= (T rhs) const; + + /// Atomically check if @c value_ greater than or equal to rhs. + bool operator>= (T rhs) const; + + /// Atomically check if @c value_ greater than rhs. + bool operator> (T rhs) const; + + /// Atomically check if @c value_ less than or equal to rhs. + bool operator<= (T rhs) const; + + /// Atomically check if @c value_ less than rhs. + bool operator< (T rhs) const; + + /// Explicitly return @c value_. + T value (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Explicitly return @c value_ (by reference). + volatile T &value_i (void); + + // ACE_ALLOC_HOOK_DECLARE; + // Declare the dynamic allocation hooks. + +protected: + /// Atomically assign rhs to @c value_. + ACE_Atomic_Op_GCC &operator= (T rhs); + + /// Atomically assign to @c value_. + ACE_Atomic_Op_GCC &operator= (const ACE_Atomic_Op_GCC &rhs); + + /// Initialize @c value_ to 0. + ACE_Atomic_Op_GCC (void); + + /// Initialize @c value_ to c. + ACE_Atomic_Op_GCC (T c); + + /// Manage copying... + ACE_Atomic_Op_GCC (const ACE_Atomic_Op_GCC &c); + +private: + + // This function cannot be supported by this template specialization. + // If you need access to an underlying lock, use the ACE_Atomic_Op_Ex + // template instead. + ACE_Thread_Mutex &mutex (void); + +private: + + /// Current object decorated by the atomic op. + volatile T value_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Atomic_Op_GCC_T.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Atomic_Op_GCC_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Atomic_Op_GCC_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + + +#endif /* ACE_HAS_GCC_ATOMIC_BUILTINS */ + +#include /**/ "ace/post.h" +#endif /*ACE_ATOMIC_OP_GCC_T_H*/ diff --git a/dep/acelite/ace/Atomic_Op_GCC_T.inl b/dep/acelite/ace/Atomic_Op_GCC_T.inl new file mode 100644 index 00000000000..c6fe027022b --- /dev/null +++ b/dep/acelite/ace/Atomic_Op_GCC_T.inl @@ -0,0 +1,148 @@ +// -*- C++ -*- +// +// $Id: Atomic_Op_GCC_T.inl 89391 2010-03-08 13:53:30Z johnnyw $ + +#if defined (ACE_HAS_GCC_ATOMIC_BUILTINS) && (ACE_HAS_GCC_ATOMIC_BUILTINS == 1) + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template +ACE_INLINE +ACE_Atomic_Op_GCC::ACE_Atomic_Op_GCC (void) + : value_ (0) +{ +} + +template +ACE_INLINE +ACE_Atomic_Op_GCC::ACE_Atomic_Op_GCC (T c) + : value_ (c) +{ +} + +template +ACE_INLINE +ACE_Atomic_Op_GCC::ACE_Atomic_Op_GCC ( + const ACE_Atomic_Op_GCC &rhs) + : value_ (rhs.value_) +{ +} + +template +ACE_INLINE T +ACE_Atomic_Op_GCC::operator++ (void) +{ + return __sync_add_and_fetch (&this->value_, 1); +} + +template +ACE_INLINE T +ACE_Atomic_Op_GCC::operator++ (int) +{ + return __sync_fetch_and_add (&this->value_, 1); +} + +template +ACE_INLINE T +ACE_Atomic_Op_GCC::operator-- (void) +{ + return __sync_sub_and_fetch (&this->value_, 1); +} + +template +ACE_INLINE T +ACE_Atomic_Op_GCC::operator-- (int) +{ + return __sync_fetch_and_sub (&this->value_, 1); +} + +template +ACE_INLINE T +ACE_Atomic_Op_GCC::operator+= (T rhs) +{ + return __sync_add_and_fetch (&this->value_, rhs); +} + +template +ACE_INLINE T +ACE_Atomic_Op_GCC::operator-= (T rhs) +{ + return __sync_sub_and_fetch (&this->value_, rhs); +} + +template +ACE_INLINE bool +ACE_Atomic_Op_GCC::operator== (T rhs) const +{ + return (this->value_ == rhs); +} + +template +ACE_INLINE bool +ACE_Atomic_Op_GCC::operator!= (T rhs) const +{ + return (this->value_ != rhs); +} + +template +ACE_INLINE bool +ACE_Atomic_Op_GCC::operator>= (T rhs) const +{ + return (this->value_ >= rhs); +} + +template +ACE_INLINE bool +ACE_Atomic_Op_GCC::operator> (T rhs) const +{ + return (this->value_ > rhs); +} + +template +ACE_INLINE bool +ACE_Atomic_Op_GCC::operator<= (T rhs) const +{ + return (this->value_ <= rhs); +} + +template +ACE_INLINE bool +ACE_Atomic_Op_GCC::operator< (T rhs) const +{ + return (this->value_ < rhs); +} + +template +ACE_INLINE ACE_Atomic_Op_GCC & +ACE_Atomic_Op_GCC::operator= (T rhs) +{ + (void) __sync_lock_test_and_set (&this->value_, rhs); + return *this; +} + +template +ACE_INLINE ACE_Atomic_Op_GCC & +ACE_Atomic_Op_GCC::operator= ( + const ACE_Atomic_Op_GCC &rhs) +{ + (void) __sync_lock_test_and_set (&this->value_, rhs.value_); + return *this; +} + +template +ACE_INLINE T +ACE_Atomic_Op_GCC::value (void) const +{ + return this->value_; +} + +template +ACE_INLINE volatile T & +ACE_Atomic_Op_GCC::value_i (void) +{ + return this->value_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_GCC_ATOMIC_BUILTINS */ diff --git a/dep/acelite/ace/Atomic_Op_Sparc.c b/dep/acelite/ace/Atomic_Op_Sparc.c new file mode 100644 index 00000000000..842673e58cc --- /dev/null +++ b/dep/acelite/ace/Atomic_Op_Sparc.c @@ -0,0 +1,187 @@ +/* $Id: Atomic_Op_Sparc.c 80826 2008-03-04 14:51:23Z wotte $ + * + * This is a C file for a reason. The Sun C++ compiler does not accept + * inline assembler. + * + * Portions of this code are based on atomic operations found in the + * linux kernel source code. + */ + +#if defined (ACE_INCLUDE_ATOMIC_OP_SPARC) + +#if defined(__i386) && defined(__SUNPRO_C) +static void +__sunpro_asm_code() { + __asm("\n\ + .globl ace_atomic_add_long \n\ + .type ace_atomic_add_long,@function \n\ + .align 4 \n\ +ace_atomic_add_long: \n\ + movl 0x00000004(%esp), %edx \n\ + movl 0x00000008(%esp), %eax \n\ + lock; xadd %eax, (%edx) \n\ + addl 0x00000008(%esp), %eax \n\ + ret \n\ + "); + + __asm("\n\ + .globl ace_atomic_swap_long \n\ + .type ace_atomic_swap_long,@function \n\ + .align 4 \n\ +ace_atomic_swap_long: \n\ + movl 0x00000004(%esp), %edx \n\ + movl 0x00000008(%esp), %eax \n\ + xchg %eax, (%edx) \n\ + ret \n\ + "); + + __asm("\n\ + .globl ace_atomic_swap_add_long \n\ + .type ace_atomic_swap_add_long,@function \n\ + .align 4 \n\ +ace_atomic_swap_add_long: \n\ + movl 0x00000004(%esp), %edx \n\ + movl 0x00000008(%esp), %eax \n\ + lock; xadd %eax, (%edx) \n\ + ret \n\ + "); +} + +#elif defined(__x86_64) && defined(__SUNPRO_C) + +static void +__sunpro_asm_code() { + __asm("\n\ + .globl ace_atomic_add_long \n\ + .type ace_atomic_add_long,@function \n\ + .align 16 \n\ +ace_atomic_add_long: \n\ + movq %rsi, %rax \n\ + lock; xaddq %rax, (%rdi) \n\ + addq %rsi, %rax \n\ + ret \n\ + "); + + __asm("\n\ + .globl ace_atomic_swap_long \n\ + .type ace_atomic_swap_long,@function \n\ + .align 16 \n\ +ace_atomic_swap_long: \n\ + xchgq %rsi, (%rdi) \n\ + movq %rsi, %rax \n\ + ret \n\ + "); + + __asm("\n\ + .globl ace_atomic_swap_add_long \n\ + .type ace_atomic_swap_add_long,@function \n\ + .align 16 \n\ +ace_atomic_swap_add_long: \n\ + lock; xaddq %rsi, (%rdi) \n\ + movq %rsi, %rax \n\ + ret \n\ + "); +} + +#elif defined (__sparcv9) + +unsigned long +ace_atomic_add_long (volatile unsigned long *dest, long rhs) +{ + __asm ("restore\n" + "ldx [%o0], %o2\n" + ".again_add:\n" + "add %o2, %o1, %o3\n" + "casx [%o0], %o2, %o3\n" + "cmp %o2, %o3\n" + "bne,pn %xcc, .again_add\n" + "mov %o3, %o2\n" + "retl\n" + "add %o2, %o1, %o0\n"); +} + +unsigned long +ace_atomic_swap_long (volatile unsigned long *dest, unsigned long rhs) +{ + __asm ("restore\n" + "ldx [%o0], %o2\n" + ".again_swap:\n" + "mov %o1, %o3\n" + "casx [%o0], %o2, %o3\n" + "cmp %o2, %o3\n" + "bne,pn %xcc, .again_swap\n" + "mov %o3, %o2\n" + "retl\n" + "mov %o3, %o0\n"); +} + +unsigned long +ace_atomic_swap_add_long (volatile unsigned long *dest, long rhs) +{ + __asm ("restore\n" + "ldx [%o0], %o2\n" + ".again_swap_add:\n" + "mov %o2, %o4\n" + "add %o2, %o1, %o3\n" + "casx [%o0], %o2, %o3\n" + "cmp %o2, %o3\n" + "bne,pn %xcc, .again_swap_add\n" + "mov %o3, %o2\n" + "retl\n" + "mov %o4, %o0\n"); +} + +#else + +unsigned long +ace_atomic_add_long (volatile unsigned long *dest, long rhs) +{ + __asm ("restore\n" + "ld [%o0], %o2\n" + ".again_add:\n" + "add %o2, %o1, %o3\n" + "cas [%o0], %o2, %o3\n" + "cmp %o2, %o3\n" + "bne,pn %icc, .again_add\n" + "mov %o3, %o2\n" + "retl\n" + "add %o2, %o1, %o0\n"); +} + +unsigned long +ace_atomic_swap_long (volatile unsigned long *dest, unsigned long rhs) +{ + __asm ("restore\n" + "ld [%o0], %o2\n" + ".again_swap:\n" + "mov %o1, %o3\n" + "cas [%o0], %o2, %o3\n" + "cmp %o2, %o3\n" + "bne,pn %icc, .again_swap\n" + "mov %o3, %o2\n" + "retl\n" + "mov %o3, %o0\n"); +} + +unsigned long +ace_atomic_swap_add_long (volatile unsigned long *dest, long rhs) +{ + __asm ("restore\n" + "ld [%o0], %o2\n" + ".again_swap_add:\n" + "mov %o2, %o4\n" + "add %o2, %o1, %o3\n" + "cas [%o0], %o2, %o3\n" + "cmp %o2, %o3\n" + "bne,pn %icc, .again_swap_add\n" + "mov %o3, %o2\n" + "retl\n" + "mov %o4, %o0\n"); +} + +# endif /* __sparcv9 */ + +#elif !defined (__GNUC__) && !defined (__INTEL_COMPILER) +/* Make compilers stop complaining about an empty translation unit */ +static int shut_up_compiler = 0; +#endif /* ACE_INCLUDE_ATOMIC_OP_SPARC */ diff --git a/dep/acelite/ace/Atomic_Op_Sparc.h b/dep/acelite/ace/Atomic_Op_Sparc.h new file mode 100644 index 00000000000..75b9ad6eaa2 --- /dev/null +++ b/dep/acelite/ace/Atomic_Op_Sparc.h @@ -0,0 +1,14 @@ +/* -*- C++ -*- */ +// $Id: Atomic_Op_Sparc.h 80826 2008-03-04 14:51:23Z wotte $ + +#ifndef ACE_ATOMIC_OP_SPARC_H +#define ACE_ATOMIC_OP_SPARC_H + +extern "C" +{ + unsigned long ace_atomic_add_long (volatile unsigned long *dest, long rhs); + unsigned long ace_atomic_swap_long (volatile unsigned long *dest, unsigned long rhs); + unsigned long ace_atomic_swap_add_long (volatile unsigned long *dest, long rhs); +} + +#endif /* ACE_ATOMIC_OP_SPARC_H */ diff --git a/dep/acelite/ace/Atomic_Op_T.cpp b/dep/acelite/ace/Atomic_Op_T.cpp new file mode 100644 index 00000000000..fcaa529b8e6 --- /dev/null +++ b/dep/acelite/ace/Atomic_Op_T.cpp @@ -0,0 +1,82 @@ +#ifndef ACE_ATOMIC_OP_T_CPP +#define ACE_ATOMIC_OP_T_CPP + +#include "ace/Atomic_Op_T.h" + +#ifdef ACE_HAS_DUMP +# include "ace/Log_Msg.h" +#endif /* ACE_HAS_DUMP */ + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (__ACE_INLINE__) +#include "ace/Atomic_Op_T.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Atomic_Op_Ex) +ACE_ALLOC_HOOK_DEFINE(ACE_Atomic_Op) + +ACE_RCSID(ace, Atomic_Op_T, "$Id: Atomic_Op_T.cpp 85141 2009-04-22 08:48:30Z johnnyw $") + +// ************************************************* +template ACE_LOCK & +ACE_Atomic_Op_Ex::mutex (void) +{ + // ACE_TRACE ("ACE_Atomic_Op_Ex::mutex"); + return this->mutex_; +} + +template +void +ACE_Atomic_Op_Ex::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + // ACE_TRACE ("ACE_Atomic_Op_Ex::dump"); + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + this->mutex_.dump (); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP, this)); +#endif /* ACE_HAS_DUMP */ +} + +template +ACE_Atomic_Op_Ex::ACE_Atomic_Op_Ex (ACE_LOCK & mtx) + : mutex_ (mtx) + , value_ (0) +{ + // ACE_TRACE ("ACE_Atomic_Op_Ex::ACE_Atomic_Op_Ex"); +} + +template +ACE_Atomic_Op_Ex::ACE_Atomic_Op_Ex ( + ACE_LOCK & mtx, + typename ACE_Atomic_Op_Ex::arg_type c) + : mutex_ (mtx) + , value_ (c) +{ + // ACE_TRACE ("ACE_Atomic_Op_Ex::ACE_Atomic_Op_Ex"); +} + +// **************************************************************** + +template +ACE_Atomic_Op::ACE_Atomic_Op (void) + : impl_ (this->own_mutex_) +{ + // ACE_TRACE ("ACE_Atomic_Op::ACE_Atomic_Op"); +} + +template +ACE_Atomic_Op::ACE_Atomic_Op ( + typename ACE_Atomic_Op::arg_type c) + : impl_ (own_mutex_, c) +{ + // ACE_TRACE ("ACE_Atomic_Op::ACE_Atomic_Op"); +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_ATOMIC_OP_T_CPP */ diff --git a/dep/acelite/ace/Atomic_Op_T.h b/dep/acelite/ace/Atomic_Op_T.h new file mode 100644 index 00000000000..13bd7dbbf88 --- /dev/null +++ b/dep/acelite/ace/Atomic_Op_T.h @@ -0,0 +1,369 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Atomic_Op_T.h + * + * $Id: Atomic_Op_T.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_ATOMIC_OP_T_H +#define ACE_ATOMIC_OP_T_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template +struct ACE_Type_Traits +{ + typedef TYPE const & parameter_type; +}; + +template<> +struct ACE_Type_Traits +{ + typedef bool parameter_type; +}; + +template<> +struct ACE_Type_Traits +{ + typedef char parameter_type; +}; + +template<> +struct ACE_Type_Traits +{ + typedef signed char parameter_type; +}; + +template<> +struct ACE_Type_Traits +{ + typedef unsigned char parameter_type; +}; + +template<> +struct ACE_Type_Traits +{ + typedef short parameter_type; +}; + +template<> +struct ACE_Type_Traits +{ + typedef unsigned short parameter_type; +}; + +template<> +struct ACE_Type_Traits +{ + typedef int parameter_type; +}; + +template<> +struct ACE_Type_Traits +{ + typedef unsigned int parameter_type; +}; + +template<> +struct ACE_Type_Traits +{ + typedef long parameter_type; +}; + +template<> +struct ACE_Type_Traits +{ + typedef unsigned long parameter_type; +}; + +#ifndef ACE_LACKS_LONGLONG_T +template<> +struct ACE_Type_Traits +{ + typedef long long parameter_type; +}; +#endif /* !ACE_LACKS_LONGLONG_T */ + +#if !defined (ACE_LACKS_LONGLONG_T) \ + && !defined (ACE_LACKS_UNSIGNEDLONGLONG_T) +template<> +struct ACE_Type_Traits +{ + typedef unsigned long long parameter_type; +}; +#endif /* !ACE_LACKS_LONGLONG_T && !ACE_LACKS_UNSIGNEDLONGLONG_T */ + +template<> +struct ACE_Type_Traits +{ + typedef float parameter_type; +}; + +template<> +struct ACE_Type_Traits +{ + typedef double parameter_type; +}; + +template<> +struct ACE_Type_Traits +{ + typedef long double parameter_type; +}; + +template +struct ACE_Type_Traits +{ + typedef TYPE* parameter_type; +}; + +/** + * @class ACE_Atomic_Op_Ex + * + * @brief Transparently parameterizes synchronization into basic + * arithmetic operations. + * + * This class is described in an article in the July/August 1994 + * issue of the C++ Report magazine. It implements a + * templatized version of the Decorator pattern from the GoF book. + * + * ACE_Atomic_Op_Ex objects must be constructed with a reference + * to an existing lock. A single lock can be shared between + * multiple ACE_Atomic_Op_Ex objects. If you do not require this + * ability consider using the ACE_Atomic_Op class instead, which + * may be able to take advantage of platform-specific + * optimisations to provide atomic operations without requiring a + * lock. + */ +template +class ACE_Atomic_Op_Ex +{ +public: + + typedef typename ACE_Type_Traits::parameter_type arg_type; + + // = Initialization methods. + + /// Initialize @c value_ to 0. + ACE_Atomic_Op_Ex (ACE_LOCK & mtx); + + /// Initialize @c value_ to c. + ACE_Atomic_Op_Ex (ACE_LOCK & mtx, arg_type c); + + // = Accessors. + + /// Atomically pre-increment @c value_. + TYPE operator++ (void); + + /// Atomically post-increment @c value_. + TYPE operator++ (int); + + /// Atomically increment @c value_ by rhs. + TYPE operator+= (arg_type rhs); + + /// Atomically pre-decrement @c value_. + TYPE operator-- (void); + + /// Atomically post-decrement @c value_. + TYPE operator-- (int); + + /// Atomically decrement @c value_ by rhs. + TYPE operator-= (arg_type rhs); + + /// Atomically compare @c value_ with rhs. + bool operator== (arg_type rhs) const; + + /// Atomically compare @c value_ with rhs. + bool operator!= (arg_type rhs) const; + + /// Atomically check if @c value_ greater than or equal to rhs. + bool operator>= (arg_type rhs) const; + + /// Atomically check if @c value_ greater than rhs. + bool operator> (arg_type rhs) const; + + /// Atomically check if @c value_ less than or equal to rhs. + bool operator<= (arg_type rhs) const; + + /// Atomically check if @c value_ less than rhs. + bool operator< (arg_type rhs) const; + + /// Atomically assign rhs to @c value_. + ACE_Atomic_Op_Ex &operator= (arg_type rhs); + + /// Atomically assign to @c value_. + ACE_Atomic_Op_Ex &operator= ( + ACE_Atomic_Op_Ex const & rhs); + + /// Explicitly return @c value_. + TYPE value (void) const; + + /// Dump the state of an object. + void dump (void) const; + + // ACE_ALLOC_HOOK_DECLARE; + // Declare the dynamic allocation hooks. + + /// Manage copying... + ACE_Atomic_Op_Ex (ACE_Atomic_Op_Ex const &); + + /** + * Returns a reference to the underlying . This makes it + * possible to acquire the lock explicitly, which can be useful in + * some cases if you instantiate the with an + * ACE_Recursive_Mutex or ACE_Process_Mutex. @note the right + * name would be lock_, but HP/C++ will choke on that! + */ + ACE_LOCK & mutex (void); + + /** + * Explicitly return @c value_ (by reference). This gives the user + * full, unrestricted access to the underlying value. This method + * will usually be used in conjunction with explicit access to the + * lock. Use with care ;-) + */ + TYPE & value_i (void); + +private: + /// Type of synchronization mechanism. + ACE_LOCK & mutex_; + + /// Current object decorated by the atomic op. + TYPE value_; +}; + +/** + * @class ACE_Atomic_Op + * + * @brief Transparently parameterizes synchronization into basic + * arithmetic operations. + * + * This class is described in an article in the July/August 1994 + * issue of the C++ Report magazine. It implements a + * templatized version of the Decorator pattern from the GoF book. + * + * Certain platforms may provide a template specialization for + * ACE_Atomic_Op that provides optimized + * atomic integer operations without actually requiring a mutex. + */ +template +class ACE_Atomic_Op +{ +public: + + typedef typename ACE_Type_Traits::parameter_type arg_type; + + /// Initialize @c value_ to 0. + ACE_Atomic_Op (void); + + /// Initialize @c value_ to c. + ACE_Atomic_Op (arg_type c); + + /// Manage copying... + ACE_Atomic_Op (ACE_Atomic_Op const & c); + + /// Atomically assign rhs to @c value_. + ACE_Atomic_Op & operator= (arg_type rhs); + + /// Atomically assign to @c value_. + ACE_Atomic_Op & operator= ( + ACE_Atomic_Op const & rhs); + + /// Atomically pre-increment @c value_. + TYPE operator++ (void); + + /// Atomically post-increment @c value_. + TYPE operator++ (int); + + /// Atomically increment @c value_ by rhs. + TYPE operator+= (arg_type rhs); + + /// Atomically pre-decrement @c value_. + TYPE operator-- (void); + + /// Atomically post-decrement @c value_. + TYPE operator-- (int); + + /// Atomically decrement @c value_ by rhs. + TYPE operator-= (arg_type rhs); + + /// Atomically compare @c value_ with rhs. + bool operator== (arg_type rhs) const; + + /// Atomically compare @c value_ with rhs. + bool operator!= (arg_type rhs) const; + + /// Atomically check if @c value_ greater than or equal to rhs. + bool operator>= (arg_type rhs) const; + + /// Atomically check if @c value_ greater than rhs. + bool operator> (arg_type rhs) const; + + /// Atomically check if @c value_ less than or equal to rhs. + bool operator<= (arg_type rhs) const; + + /// Atomically check if @c value_ less than rhs. + bool operator< (arg_type rhs) const; + + /// Explicitly return @c value_. + TYPE value (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /** + * Returns a reference to the underlying . This makes it + * possible to acquire the lock explicitly, which can be useful in + * some cases if you instantiate the ACE_Atomic_Op with an + * ACE_Recursive_Mutex or ACE_Process_Mutex. + * + * @deprecated This member function is deprecated and so may go away in + * the future. If you need access to the underlying mutex, consider + * using the ACE_Atomic_Op_Ex template instead. + */ + ACE_LOCK & mutex (void); + + /** + * Explicitly return @c value_ (by reference). This gives the user + * full, unrestricted access to the underlying value. This method + * will usually be used in conjunction with explicit access to the + * lock. Use with care ;-) + */ + TYPE & value_i (void); + +private: + /// Type of synchronization mechanism. + ACE_LOCK own_mutex_; + + /// Underlying atomic op implementation. + ACE_Atomic_Op_Ex impl_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Atomic_Op_T.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Atomic_Op_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Atomic_Op_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" +#endif /*ACE_ATOMIC_OP_T_H*/ diff --git a/dep/acelite/ace/Atomic_Op_T.inl b/dep/acelite/ace/Atomic_Op_T.inl new file mode 100644 index 00000000000..ff051b0cbce --- /dev/null +++ b/dep/acelite/ace/Atomic_Op_T.inl @@ -0,0 +1,340 @@ +// -*- C++ -*- +// +// $Id: Atomic_Op_T.inl 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Guard_T.h" + +#include + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// +// ACE_Atomic_Op_Ex inline functions +// + +template +ACE_INLINE TYPE +ACE_Atomic_Op_Ex::operator++ (void) +{ + // ACE_TRACE ("ACE_Atomic_Op_Ex::operator++"); + ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, this->value_); + return ++this->value_; +} + +template +ACE_INLINE TYPE +ACE_Atomic_Op_Ex::operator+= ( + typename ACE_Atomic_Op_Ex::arg_type rhs) +{ + // ACE_TRACE ("ACE_Atomic_Op_Ex::operator+="); + ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, this->value_); + return this->value_ += rhs; +} + +template +ACE_INLINE TYPE +ACE_Atomic_Op_Ex::operator-- (void) +{ + // ACE_TRACE ("ACE_Atomic_Op_Ex::operator--"); + ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, this->value_); + return --this->value_; +} + +template +ACE_INLINE TYPE +ACE_Atomic_Op_Ex::operator-= ( + typename ACE_Atomic_Op_Ex::arg_type rhs) +{ + // ACE_TRACE ("ACE_Atomic_Op_Ex::operator-="); + ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, this->value_); + return this->value_ -= rhs; +} + +template +ACE_INLINE +ACE_Atomic_Op_Ex::ACE_Atomic_Op_Ex ( + ACE_Atomic_Op_Ex const & rhs) + : mutex_ (rhs.mutex_) + , value_ (rhs.value ()) // rhs.value() returns atomically +{ + // ACE_TRACE ("ACE_Atomic_Op_Ex::ACE_Atomic_Op_Ex"); +} + +template +ACE_INLINE TYPE +ACE_Atomic_Op_Ex::operator++ (int) +{ + // ACE_TRACE ("ACE_Atomic_Op_Ex::operator++"); + ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, this->value_); + return this->value_++; +} + +template +ACE_INLINE TYPE +ACE_Atomic_Op_Ex::operator-- (int) +{ + // ACE_TRACE ("ACE_Atomic_Op_Ex::operator--"); + ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, this->value_); + return this->value_--; +} + +template +ACE_INLINE bool +ACE_Atomic_Op_Ex::operator== ( + typename ACE_Atomic_Op_Ex::arg_type rhs) const +{ + // ACE_TRACE ("ACE_Atomic_Op_Ex::operator=="); + ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, false); + return this->value_ == rhs; +} + +template +ACE_INLINE bool +ACE_Atomic_Op_Ex::operator!= ( + typename ACE_Atomic_Op_Ex::arg_type rhs) const +{ + // ACE_TRACE ("ACE_Atomic_Op_Ex::operator!="); + return !(*this == rhs); +} + +template +ACE_INLINE bool +ACE_Atomic_Op_Ex::operator>= ( + typename ACE_Atomic_Op_Ex::arg_type rhs) const +{ + // ACE_TRACE ("ACE_Atomic_Op_Ex::operator>="); + ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, false); + return this->value_ >= rhs; +} + +template +ACE_INLINE bool +ACE_Atomic_Op_Ex::operator> ( + typename ACE_Atomic_Op_Ex::arg_type rhs) const +{ + // ACE_TRACE ("ACE_Atomic_Op_Ex::operator>"); + ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, false); + return this->value_ > rhs; +} + +template +ACE_INLINE bool +ACE_Atomic_Op_Ex::operator<= ( + typename ACE_Atomic_Op_Ex::arg_type rhs) const +{ + // ACE_TRACE ("ACE_Atomic_Op_Ex::operator<="); + ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, false); + return this->value_ <= rhs; +} + +template +ACE_INLINE bool +ACE_Atomic_Op_Ex::operator< ( + typename ACE_Atomic_Op_Ex::arg_type rhs) const +{ + // ACE_TRACE ("ACE_Atomic_Op_Ex::operator<"); + ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, false); + return this->value_ < rhs; +} + +template +ACE_INLINE ACE_Atomic_Op_Ex & +ACE_Atomic_Op_Ex::operator= ( + ACE_Atomic_Op_Ex const & rhs) +{ + // ACE_TRACE ("ACE_Atomic_Op_Ex::operator="); + + ACE_Atomic_Op_Ex tmp (rhs); + + ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, *this); + std::swap (this->value_, tmp.value_); + + return *this; +} + +template +ACE_INLINE TYPE +ACE_Atomic_Op_Ex::value (void) const +{ + // ACE_TRACE ("ACE_Atomic_Op_Ex::value"); + ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, this->value_); + return this->value_; +} + +template +ACE_INLINE TYPE & +ACE_Atomic_Op_Ex::value_i (void) +{ + // Explicitly return (by reference). This gives the user + // full, unrestricted access to the underlying value. This method + // will usually be used in conjunction with explicit access to the + // lock. Use with care ;-) + return this->value_; +} + +template +ACE_INLINE ACE_Atomic_Op_Ex & +ACE_Atomic_Op_Ex::operator= ( + typename ACE_Atomic_Op_Ex::arg_type rhs) +{ + // ACE_TRACE ("ACE_Atomic_Op_Ex::operator="); + ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, *this); + this->value_ = rhs; + return *this; +} + +// +// ACE_Atomic_Op inline functions +// + +template ACE_INLINE +ACE_Atomic_Op::ACE_Atomic_Op ( + ACE_Atomic_Op const & rhs) + : impl_ (own_mutex_, rhs.value ()) +{ + // ACE_TRACE ("ACE_Atomic_Op::ACE_Atomic_Op"); +} + + +template +ACE_INLINE ACE_Atomic_Op & +ACE_Atomic_Op::operator= ( + typename ACE_Atomic_Op::arg_type i) +{ + this->impl_ = i; + return *this; +} + +template +ACE_INLINE ACE_Atomic_Op & +ACE_Atomic_Op::operator= ( + ACE_Atomic_Op const & rhs) +{ + this->impl_ = rhs.impl_; + return *this; +} + +template +ACE_INLINE TYPE +ACE_Atomic_Op::operator++ (void) +{ + return ++this->impl_; +} + +template +ACE_INLINE TYPE +ACE_Atomic_Op::operator++ (int) +{ + return this->impl_++; +} + +template +ACE_INLINE TYPE +ACE_Atomic_Op::operator+= ( + typename ACE_Atomic_Op::arg_type rhs) +{ + return this->impl_ += rhs; +} + +template +ACE_INLINE TYPE +ACE_Atomic_Op::operator-- (void) +{ + return --this->impl_; +} + +template +ACE_INLINE TYPE +ACE_Atomic_Op::operator-- (int) +{ + return this->impl_--; +} + +template +ACE_INLINE TYPE +ACE_Atomic_Op::operator-= ( + typename ACE_Atomic_Op::arg_type rhs) +{ + return this->impl_ -= rhs; +} + +template +ACE_INLINE bool +ACE_Atomic_Op::operator== ( + typename ACE_Atomic_Op::arg_type rhs) const +{ + return this->impl_ == rhs; +} + +template +ACE_INLINE bool +ACE_Atomic_Op::operator!= ( + typename ACE_Atomic_Op::arg_type rhs) const +{ + return this->impl_ != rhs; +} + +template +ACE_INLINE bool +ACE_Atomic_Op::operator>= ( + typename ACE_Atomic_Op::arg_type rhs) const +{ + return this->impl_ >= rhs; +} + +template +ACE_INLINE bool +ACE_Atomic_Op::operator> ( + typename ACE_Atomic_Op::arg_type rhs) const +{ + return this->impl_ > rhs; +} + +template +ACE_INLINE bool +ACE_Atomic_Op::operator<= ( + typename ACE_Atomic_Op::arg_type rhs) const +{ + return this->impl_ <= rhs; +} + +template +ACE_INLINE bool +ACE_Atomic_Op::operator< ( + typename ACE_Atomic_Op::arg_type rhs) const +{ + return this->impl_ < rhs; +} + +template +ACE_INLINE TYPE +ACE_Atomic_Op::value (void) const +{ + return this->impl_.value (); +} + +template +ACE_INLINE void +ACE_Atomic_Op::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + this->impl_.dump (); +#endif /* ACE_HAS_DUMP */ + return; +} + +template +ACE_INLINE ACE_LOCK & +ACE_Atomic_Op::mutex (void) +{ + return this->own_mutex_; +} + +template +ACE_INLINE TYPE & +ACE_Atomic_Op::value_i (void) +{ + return this->impl_.value_i (); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Auto_Event.cpp b/dep/acelite/ace/Auto_Event.cpp new file mode 100644 index 00000000000..51efcf7605b --- /dev/null +++ b/dep/acelite/ace/Auto_Event.cpp @@ -0,0 +1,49 @@ +// $Id: Auto_Event.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Auto_Event.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Auto_Event.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID (ace, + Auto_Event, + "$Id: Auto_Event.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_Auto_Event::ACE_Auto_Event (int initial_state, + int type, + const char *name, + void *arg) + : ACE_Event (0, + initial_state, + type, + ACE_TEXT_CHAR_TO_TCHAR (name), + arg) +{ +} + +#if defined (ACE_HAS_WCHAR) +ACE_Auto_Event::ACE_Auto_Event (int initial_state, + int type, + const wchar_t *name, + void *arg) + : ACE_Event (0, + initial_state, + type, + ACE_TEXT_WCHAR_TO_TCHAR (name), + arg) +{ +} +#endif /* ACE_HAS_WCHAR */ + +void +ACE_Auto_Event::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_Event::dump (); +#endif /* ACE_HAS_DUMP */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Auto_Event.h b/dep/acelite/ace/Auto_Event.h new file mode 100644 index 00000000000..042f82ed2ff --- /dev/null +++ b/dep/acelite/ace/Auto_Event.h @@ -0,0 +1,73 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file Auto_Event.h + * + * $Id: Auto_Event.h 80826 2008-03-04 14:51:23Z wotte $ + * + * Moved from Synch.h. + * + * @author Douglas C. Schmidt + */ +//========================================================================== + +#ifndef ACE_AUTO_EVENT_H +#define ACE_AUTO_EVENT_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Event.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Auto_Event + * + * @brief Auto Events. + * + * Specialization of Event mechanism which wakes up one waiting + * thread on . All platforms support process-scope locking + * support. However, only Win32 platforms support global naming and + * system-scope locking support. + */ +class ACE_Export ACE_Auto_Event : public ACE_Event +{ +public: + /// Constructor which will create auto event + ACE_Auto_Event (int initial_state = 0, + int type = USYNC_THREAD, + const char *name = 0, + void *arg = 0); + +#if defined (ACE_HAS_WCHAR) + /// Constructor which will create auto event (wchar_t version) + ACE_Auto_Event (int initial_state, + int type, + const wchar_t *name, + void *arg = 0); +#endif /* ACE_HAS_WCHAR */ + + /// Default dtor. + ~ACE_Auto_Event (void); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks + ACE_ALLOC_HOOK_DECLARE; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Auto_Event.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_AUTO_EVENT_H */ diff --git a/dep/acelite/ace/Auto_Event.inl b/dep/acelite/ace/Auto_Event.inl new file mode 100644 index 00000000000..b614e0b0d77 --- /dev/null +++ b/dep/acelite/ace/Auto_Event.inl @@ -0,0 +1,12 @@ +// -*- C++ -*- +// +// $Id: Auto_Event.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE +ACE_Auto_Event::~ACE_Auto_Event (void) +{ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Auto_Functor.cpp b/dep/acelite/ace/Auto_Functor.cpp new file mode 100644 index 00000000000..9d0dc79aa52 --- /dev/null +++ b/dep/acelite/ace/Auto_Functor.cpp @@ -0,0 +1,39 @@ +// $Id: Auto_Functor.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#ifndef ACE_AUTO_FUNCTOR_CPP +#define ACE_AUTO_FUNCTOR_CPP + +#include "ace/Auto_Functor.h" + +#if !defined(__ACE_INLINE__) +# include "ace/Auto_Functor.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template +ACE_Utils::Auto_Functor::~Auto_Functor() +{ + reset(0); +} + +template void +ACE_Utils::Auto_Functor::reset(X * p) +{ + if(p_ != 0) + { + f_(p_); + } + p_ = p; +} + +templatevoid +ACE_Utils::Auto_Functor::reset(X * p, Functor f) +{ + reset(p); + f_ = f; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /*ACE_AUTO_FUNCTOR_CPP*/ diff --git a/dep/acelite/ace/Auto_Functor.h b/dep/acelite/ace/Auto_Functor.h new file mode 100644 index 00000000000..2c2b81eb265 --- /dev/null +++ b/dep/acelite/ace/Auto_Functor.h @@ -0,0 +1,127 @@ +// -*- C++ -*- +//============================================================================= +/** + * @file Auto_Functor.h + * + * $Id: Auto_Functor.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Carlos O'Ryan + */ +//============================================================================= +#ifndef ACE_AUTO_FUNCTOR_H +#define ACE_AUTO_FUNCTOR_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Global_Macros.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +namespace ACE_Utils +{ +/** + * @class Auto_Functor_Ref + * + * @brief Helper class to implement assignment and copy-construction + * as expected + */ +template +struct Auto_Functor_Ref +{ + X * p_; + Functor f_; + + Auto_Functor_Ref(X * p, Functor f); +}; + +/** + * @class Auto_Functor + * + * @brief Helper template to implement auto_ptr<>-like classes, but + * executing a functor in the destructor, instead of always + * deleting things. + * + * The functor is called in the destructor, and it must implement: + * + * Functor() throw();
+ * Functor(Functor const &) throw();
+ * Functor & operator=(Functor const &) throw();
+ * void operator()(X * p) throw();
+ * + */ +template +class Auto_Functor +{ +public: + typedef X element_type; + typedef Functor functor_type; + + /// Constructor + explicit Auto_Functor (X * p = 0, + Functor functor = Functor()); // throw() + + Auto_Functor (Auto_Functor & rhs); // throw() + + Auto_Functor& operator= (Auto_Functor & rhs); // throw() + +#if !defined(ACE_LACKS_MEMBER_TEMPLATES) + template + Auto_Functor(Auto_Functor& rhs); // throw() + + template + Auto_Functor& operator= (Auto_Functor& rhs); // throw() +#endif /* ACE_LACKS_MEMBER_TEMPLATES */ + + ~Auto_Functor(); // throw() + + X & operator*() const; // throw() + + X * operator->() const; // throw() + + X * get(); // throw() + + X * release(); // throw() + + void reset (X * p = 0); // throw() + + void reset (X * p, Functor f); // throw() + + Functor const & functor() const; // throw() + + Auto_Functor(Auto_Functor_Ref rhs); // throw() + + Auto_Functor & operator=(Auto_Functor_Ref rhs); // throw() + +#if !defined(ACE_LACKS_MEMBER_TEMPLATES) + template operator Auto_Functor_Ref(); // throw() + + template operator Auto_Functor(); // throw() +#else + operator Auto_Functor_Ref(); // throw() +#endif /* ACE_LACKS_MEMBER_TEMPLATES */ + +private: + X * p_; + + Functor f_; +}; + +} // namespace ACE_Utils + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined(__ACE_INLINE__) +# include "ace/Auto_Functor.inl" +#endif /* __ACE_INLINE__ */ + +#if defined(ACE_TEMPLATES_REQUIRE_SOURCE) +# include "ace/Auto_Functor.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#include /**/ "ace/post.h" +#endif /* ACE_AUTO_FUNCTOR_H*/ diff --git a/dep/acelite/ace/Auto_Functor.inl b/dep/acelite/ace/Auto_Functor.inl new file mode 100644 index 00000000000..d4cb2cc0473 --- /dev/null +++ b/dep/acelite/ace/Auto_Functor.inl @@ -0,0 +1,134 @@ +// -*- C++ -*- +// +// $Id: Auto_Functor.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template ACE_INLINE +ACE_Utils::Auto_Functor_Ref:: +Auto_Functor_Ref(X * p, Functor f) + : p_(p) + , f_(f) +{ +} + +template ACE_INLINE +ACE_Utils::Auto_Functor::Auto_Functor(X * p, Functor f) + : p_(p) + , f_(f) +{ +} + +template ACE_INLINE +ACE_Utils::Auto_Functor::Auto_Functor(Auto_Functor & rhs) + : p_(rhs.release()) + , f_(rhs.f_) +{ +} + +template +ACE_INLINE ACE_Utils::Auto_Functor& +ACE_Utils::Auto_Functor:: operator=(Auto_Functor & rhs) +{ + reset(rhs.release()); + f_ = rhs.f_; + return *this; +} + +#if !defined(ACE_LACKS_MEMBER_TEMPLATES) +template template ACE_INLINE +ACE_Utils::Auto_Functor::Auto_Functor(Auto_Functor& rhs) + : p_(rhs.release()) + , f_(rhs.f_) +{ +} + +template template +ACE_INLINE ACE_Utils::Auto_Functor& +ACE_Utils::Auto_Functor::operator=(Auto_Functor& rhs) +{ + reset(rhs.release()); + return *this; +} +#endif /* ACE_LACKS_MEMBER_TEMPLATES */ + +template ACE_INLINE X & +ACE_Utils::Auto_Functor::operator*() const +{ + return *p_; +} + +template +ACE_INLINE X * +ACE_Utils::Auto_Functor::operator->() const +{ + return p_; +} + +template +ACE_INLINE X * +ACE_Utils::Auto_Functor::get() +{ + return p_; +} + +template +ACE_INLINE X * +ACE_Utils::Auto_Functor::release() +{ + X * tmp = p_; + p_ = 0; + return tmp; +} + +template +ACE_INLINE Functor const & +ACE_Utils::Auto_Functor::functor() const +{ + return f_; +} + +template ACE_INLINE +ACE_Utils::Auto_Functor::Auto_Functor(Auto_Functor_Ref rhs) + : p_(rhs.p_) + , f_(rhs.f_) +{ +} + +template +ACE_INLINE ACE_Utils::Auto_Functor & +ACE_Utils::Auto_Functor::operator=(Auto_Functor_Ref rhs) +{ + if(rhs.p_ != p_) + { + reset(rhs.p_); + f_ = rhs.f_; + } + return *this; +} + +#if !defined(ACE_LACKS_MEMBER_TEMPLATES) + +template template ACE_INLINE +ACE_Utils::Auto_Functor::operator ACE_Utils::Auto_Functor_Ref() +{ + return ACE_Utils::Auto_Functor_Ref(release(), f_); +} + +template template ACE_INLINE +ACE_Utils::Auto_Functor::operator ACE_Utils::Auto_Functor() +{ + return ACE_Utils::Auto_Functor(release(), f_); +} + +#else + +templateACE_INLINE +ACE_Utils::Auto_Functor::operator ACE_Utils::Auto_Functor_Ref() +{ + return ACE_Utils::Auto_Functor_Ref(release(), f_); +} + +#endif /* ACE_LACKS_MEMBER_TEMPLATES */ + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Auto_IncDec_T.cpp b/dep/acelite/ace/Auto_IncDec_T.cpp new file mode 100644 index 00000000000..ccef122edcf --- /dev/null +++ b/dep/acelite/ace/Auto_IncDec_T.cpp @@ -0,0 +1,34 @@ +// $Id: Auto_IncDec_T.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#ifndef ACE_AUTO_INCDEC_T_CPP +#define ACE_AUTO_INCDEC_T_CPP + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Auto_IncDec_T.h" +#include "ace/Log_Msg.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Auto_IncDec_T.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Auto_IncDec) + +template void +ACE_Auto_IncDec::dump (void) const +{ +#if defined (ACE_HAS_DUMP) +// ACE_TRACE ("ACE_Auto_IncDec::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_AUTO_INCDEC_T_CPP */ diff --git a/dep/acelite/ace/Auto_IncDec_T.h b/dep/acelite/ace/Auto_IncDec_T.h new file mode 100644 index 00000000000..8fcdb0bcd76 --- /dev/null +++ b/dep/acelite/ace/Auto_IncDec_T.h @@ -0,0 +1,91 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Auto_IncDec_T.h + * + * $Id: Auto_IncDec_T.h 84675 2009-03-02 11:44:35Z johnnyw $ + * + * @author Edan Ayal + */ +//============================================================================= + + +#ifndef ACE_AUTO_INCDEC_T_H +#define ACE_AUTO_INCDEC_T_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Global_Macros.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Auto_IncDec + * + * @brief This class automatically increments and decrements a + * parameterized counter. + * + * This data structure is meant to be used within a method, + * function, or scope. The actual parameter given for the + * template parameter + * must provide at least operators ++ and --. + */ +template +class ACE_Auto_IncDec +{ +public: + + /// Implicitly increment the counter. + ACE_Auto_IncDec (ACE_SAFELY_INCREMENTABLE_DECREMENTABLE &counter); + + /// Implicitly decrement the counter. + ~ACE_Auto_IncDec (void); + + /// Dump the state of an object. + void dump (void) const; + +protected: + /// Reference to the counter + /// we're incrementing/decrementing. + ACE_SAFELY_INCREMENTABLE_DECREMENTABLE &counter_; + +private: + // = Prevent assignment and initialization. + ACE_UNIMPLEMENTED_FUNC (void operator= (const + ACE_Auto_IncDec &)) + ACE_UNIMPLEMENTED_FUNC (ACE_Auto_IncDec (const + ACE_Auto_IncDec &)) +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Auto_IncDec_T.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Auto_IncDec_T.cpp" +// On Win32 platforms, this code will be included as template source +// code and will not be inlined. Therefore, we first turn off +// ACE_INLINE, set it to be nothing, include the code, and then turn +// ACE_INLINE back to its original setting. All this nonsense is +// necessary, since the generic template code that needs to be +// specialized cannot be inlined, else the compiler will ignore the +// specialization code. Also, the specialization code *must* be +// inlined or the compiler will ignore the specializations. +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Auto_IncDec_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" + +#endif /* ACE_AUTO_INCDEC_T_H */ diff --git a/dep/acelite/ace/Auto_IncDec_T.inl b/dep/acelite/ace/Auto_IncDec_T.inl new file mode 100644 index 00000000000..e61980e7192 --- /dev/null +++ b/dep/acelite/ace/Auto_IncDec_T.inl @@ -0,0 +1,25 @@ +// -*- C++ -*- +// +// $Id: Auto_IncDec_T.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Implicitly and automatically increment the counter. + +template ACE_INLINE +ACE_Auto_IncDec::ACE_Auto_IncDec + (ACE_SAFELY_INCREMENTABLE_DECREMENTABLE &counter) + : counter_ (counter) +{ + ++this->counter_; +} + +// Implicitly and automatically decrement the counter. + +template ACE_INLINE +ACE_Auto_IncDec::~ACE_Auto_IncDec (void) +{ + --this->counter_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Auto_Ptr.cpp b/dep/acelite/ace/Auto_Ptr.cpp new file mode 100644 index 00000000000..791bd482a23 --- /dev/null +++ b/dep/acelite/ace/Auto_Ptr.cpp @@ -0,0 +1,21 @@ +// $Id: Auto_Ptr.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#ifndef ACE_AUTO_PTR_CPP +#define ACE_AUTO_PTR_CPP + +#include "ace/Auto_Ptr.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Auto_Ptr.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID(ace, Auto_Ptr, "$Id: Auto_Ptr.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Auto_Basic_Ptr) +ACE_ALLOC_HOOK_DEFINE(ACE_Auto_Basic_Array_Ptr) + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_AUTO_PTR_CPP */ diff --git a/dep/acelite/ace/Auto_Ptr.h b/dep/acelite/ace/Auto_Ptr.h new file mode 100644 index 00000000000..3183019aceb --- /dev/null +++ b/dep/acelite/ace/Auto_Ptr.h @@ -0,0 +1,242 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file Auto_Ptr.h + * + * $Id: Auto_Ptr.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Doug Schmidt + * @author Irfan Pyarali + * @author Jack Reeves + * @author Dr. Harald M. Mueller + */ +//============================================================================= + +#ifndef ACE_AUTO_PTR_H +#define ACE_AUTO_PTR_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (_MSC_VER) +// Suppress warning e.g. "return type for +// 'ACE_Auto_Array_Pointer::operator ->' is 'type *' (i.e., not a UDT +// or reference to a UDT. Will produce errors if applied using infix +// notation)" +# pragma warning(push) +# pragma warning(disable: 4284) +#endif /* _MSC_VER */ + + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Auto_Basic_Ptr + * + * @brief Implements the draft C++ standard auto_ptr abstraction. + * This class allows one to work on non-object (basic) types + */ +template +class ACE_Auto_Basic_Ptr +{ +public: + typedef X element_type; + + // = Initialization and termination methods + explicit ACE_Auto_Basic_Ptr (X * p = 0) : p_ (p) {} + + ACE_Auto_Basic_Ptr (ACE_Auto_Basic_Ptr & ap); + ACE_Auto_Basic_Ptr &operator= (ACE_Auto_Basic_Ptr & rhs); + ~ACE_Auto_Basic_Ptr (void); + + // = Accessor methods. + X &operator *() const; + X *get (void) const; + X *release (void); + void reset (X * p = 0); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + X *p_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if !defined (ACE_LACKS_AUTO_PTR) && \ + defined (ACE_HAS_STANDARD_CPP_LIBRARY) && \ + (ACE_HAS_STANDARD_CPP_LIBRARY != 0) +#include +#if defined (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB) && \ + (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB != 0) +using std::auto_ptr; +#endif /* ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB */ +#else /* ACE_HAS_STANDARD_CPP_LIBRARY */ + +/** + * @class auto_ptr + * + * @brief Implements the draft C++ standard auto_ptr abstraction. + */ +template +class auto_ptr : public ACE_Auto_Basic_Ptr +{ +public: + typedef X element_type; + + // = Initialization and termination methods + explicit auto_ptr (X * p = 0) : ACE_Auto_Basic_Ptr (p) {} + auto_ptr (auto_ptr & ap) : ACE_Auto_Basic_Ptr (ap.release ()) {} + + X *operator-> () const; +}; + +#endif /* ACE_HAS_STANDARD_CPP_LIBRARY */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @brief Implements the draft C++ standard auto_ptr abstraction. + * This version can be used instead of auto_ptr, and obviates + * the need for the ACE_AUTO_PTR_RESET macro on platforms like + * VC6 where the auto_ptr is broken. + */ +template +class ACE_Auto_Ptr : public ACE_Auto_Basic_Ptr +{ +public: + typedef X element_type; + + // = Initialization and termination methods + explicit ACE_Auto_Ptr (X * p = 0) : ACE_Auto_Basic_Ptr (p) {} + + X *operator-> () const; +}; + +/** + * @class ACE_Auto_Basic_Array_Ptr + * + * @brief Implements an extension to the draft C++ standard auto_ptr + * abstraction. This class allows one to work on non-object + * (basic) types that must be treated as an array, e.g., + * deallocated via "delete [] foo". + */ +template +class ACE_Auto_Basic_Array_Ptr +{ +public: + typedef X element_type; + + // = Initialization and termination methods. + explicit ACE_Auto_Basic_Array_Ptr (X * p = 0) : p_ (p) {} + + ACE_Auto_Basic_Array_Ptr (ACE_Auto_Basic_Array_Ptr & ap); + ACE_Auto_Basic_Array_Ptr &operator= (ACE_Auto_Basic_Array_Ptr & rhs); + ~ACE_Auto_Basic_Array_Ptr (void); + + // = Accessor methods. + X & operator* () const; + X & operator[] (int i) const; + X * get (void) const; + X * release (void); + void reset (X * p = 0); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + X * p_; +}; + +/** + * @class ACE_Auto_Array_Ptr + * + * @brief Implements an extension to the draft C++ standard auto_ptr + * abstraction. + */ +template +class ACE_Auto_Array_Ptr : public ACE_Auto_Basic_Array_Ptr +{ +public: + typedef X element_type; + + // = Initialization and termination methods. + explicit ACE_Auto_Array_Ptr (X *p = 0) + : ACE_Auto_Basic_Array_Ptr (p) {} + + X *operator-> () const; +}; + + +/** + * @brief Reset given @c auto_ptr element to new element. + * + * Some platforms have an older version of auto_ptr support, which + * lacks reset, and cannot be disabled easily. Portability to these + * platforms requires use of this function template. This function + * template also works for the @c ACE_Auto_{Basic_}Array_Ptr class + * template, as well. + */ +template +inline void +ACE_auto_ptr_reset (AUTO_PTR_TYPE & ap, + PTR_TYPE * p) +{ +#if defined (ACE_AUTO_PTR_LACKS_RESET) + // Allow compiler to adjust pointer to potential base class pointer + // of element type found in auto_ptr. + typename AUTO_PTR_TYPE::element_type * const tp = p; + if (tp != ap.get ()) + { + ap = AUTO_PTR_TYPE (tp); + } +#else + ap.reset (p); +#endif /* ACE_AUTO_PTR_LACKS_RESET */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +// Some platforms have an older version of auto_ptr +// support, which lacks reset, and cannot be disabled +// easily. Portability to these platforms requires +// use of the following ACE_AUTO_PTR_RESET macro. +// +// The TYPE macro parameter is no longer necessary but we leave it +// around for backward compatibility. This is also the reason why the +// ACE_auto_ptr_reset function template is not called +// ACE_AUTO_PTR_RESET. +# define ACE_AUTO_PTR_RESET(AUTOPTR,NEWPTR,TYPE) \ + ACE_auto_ptr_reset (AUTOPTR, NEWPTR); + +#if defined (__ACE_INLINE__) +#include "ace/Auto_Ptr.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Auto_Ptr.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Auto_Ptr.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#if defined (_MSC_VER) +// Restore the warning state to what it was before entry. +# pragma warning(pop) +#endif /* _MSC_VER */ + +#include /**/ "ace/post.h" +#endif /* ACE_AUTO_PTR_H */ diff --git a/dep/acelite/ace/Auto_Ptr.inl b/dep/acelite/ace/Auto_Ptr.inl new file mode 100644 index 00000000000..9ea47c3f208 --- /dev/null +++ b/dep/acelite/ace/Auto_Ptr.inl @@ -0,0 +1,171 @@ +// -*- C++ -*- +// +// $Id: Auto_Ptr.inl 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Global_Macros.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template ACE_INLINE void +ACE_Auto_Basic_Ptr::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Auto_Basic_Ptr::dump"); +#endif /* ACE_HAS_DUMP */ +} + +template ACE_INLINE void +ACE_Auto_Basic_Array_Ptr::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Auto_Basic_Array_Ptr::dump"); +#endif /* ACE_HAS_DUMP */ +} + +template ACE_INLINE +ACE_Auto_Basic_Ptr::ACE_Auto_Basic_Ptr (ACE_Auto_Basic_Ptr &rhs) + : p_ (rhs.release ()) +{ + ACE_TRACE ("ACE_Auto_Basic_Ptr::ACE_Auto_Basic_Ptr"); +} + +template ACE_INLINE X * +ACE_Auto_Basic_Ptr::get (void) const +{ + ACE_TRACE ("ACE_Auto_Basic_Ptr::get"); + return this->p_; +} + +template ACE_INLINE X * +ACE_Auto_Basic_Ptr::release (void) +{ + ACE_TRACE ("ACE_Auto_Basic_Ptr::release"); + X *old = this->p_; + this->p_ = 0; + return old; +} + +template ACE_INLINE void +ACE_Auto_Basic_Ptr::reset (X *p) +{ + ACE_TRACE ("ACE_Auto_Basic_Ptr::reset"); + if (this->get () != p) + delete this->get (); + this->p_ = p; +} + +template ACE_INLINE ACE_Auto_Basic_Ptr & +ACE_Auto_Basic_Ptr::operator= (ACE_Auto_Basic_Ptr &rhs) +{ + ACE_TRACE ("ACE_Auto_Basic_Ptr::operator="); + if (this != &rhs) + { + this->reset (rhs.release ()); + } + return *this; +} + +template ACE_INLINE +ACE_Auto_Basic_Ptr::~ACE_Auto_Basic_Ptr (void) +{ + ACE_TRACE ("ACE_Auto_Basic_Ptr::~ACE_Auto_Basic_Ptr"); + delete this->get (); +} + +template ACE_INLINE X & +ACE_Auto_Basic_Ptr::operator *() const +{ + ACE_TRACE ("ACE_Auto_Basic_Ptr::operator *()"); + return *this->get (); +} + +#if defined (ACE_LACKS_AUTO_PTR) || \ + !defined (ACE_HAS_STANDARD_CPP_LIBRARY) || \ + (ACE_HAS_STANDARD_CPP_LIBRARY == 0) + +template ACE_INLINE X * +auto_ptr::operator-> () const +{ + ACE_TRACE ("auto_ptr::operator->"); + return this->get (); +} + +#endif /* ACE_HAS_STANDARD_CPP_LIBRARY */ + +template ACE_INLINE X * +ACE_Auto_Ptr::operator-> () const +{ + ACE_TRACE ("ACE_Auto_Ptr::operator->"); + return this->get (); +} + +template ACE_INLINE X * +ACE_Auto_Basic_Array_Ptr::get (void) const +{ + ACE_TRACE ("ACE_Auto_Basic_Array_Ptr::get"); + return this->p_; +} + +template ACE_INLINE X * +ACE_Auto_Basic_Array_Ptr::release (void) +{ + ACE_TRACE ("ACE_Auto_Basic_Array_Ptr::release"); + X *old = this->p_; + this->p_ = 0; + return old; +} + +template ACE_INLINE void +ACE_Auto_Basic_Array_Ptr::reset (X *p) +{ + ACE_TRACE ("ACE_Auto_Basic_Array_Ptr::reset"); + if (this->get () != p) + delete [] this->get (); + this->p_ = p; +} + +template ACE_INLINE +ACE_Auto_Basic_Array_Ptr::ACE_Auto_Basic_Array_Ptr (ACE_Auto_Basic_Array_Ptr &rhs) + : p_ (rhs.release ()) +{ + ACE_TRACE ("ACE_Auto_Basic_Array_Ptr::ACE_Auto_Basic_Array_Ptr"); +} + +template ACE_INLINE ACE_Auto_Basic_Array_Ptr & +ACE_Auto_Basic_Array_Ptr::operator= (ACE_Auto_Basic_Array_Ptr &rhs) +{ + ACE_TRACE ("ACE_Auto_Basic_Array_Ptr::operator="); + if (this != &rhs) + { + this->reset (rhs.release ()); + } + return *this; +} + +template ACE_INLINE +ACE_Auto_Basic_Array_Ptr::~ACE_Auto_Basic_Array_Ptr (void) +{ + ACE_TRACE ("ACE_Auto_Basic_Array_Ptr::~ACE_Auto_Basic_Array_Ptr"); + delete [] this->get (); +} + +template ACE_INLINE X & +ACE_Auto_Basic_Array_Ptr::operator *() const +{ + return *this->get (); +} + +template ACE_INLINE X & +ACE_Auto_Basic_Array_Ptr::operator[](int i) const +{ + X *array = this->get (); + return array[i]; +} + +template ACE_INLINE X * +ACE_Auto_Array_Ptr::operator->() const +{ + return this->get (); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Barrier.cpp b/dep/acelite/ace/Barrier.cpp new file mode 100644 index 00000000000..29e7422600c --- /dev/null +++ b/dep/acelite/ace/Barrier.cpp @@ -0,0 +1,196 @@ +// $Id: Barrier.cpp 84282 2009-01-30 15:04:29Z msmit $ + +#include "ace/Barrier.h" + +#if defined (ACE_HAS_THREADS) + +#if !defined (__ACE_INLINE__) +#include "ace/Barrier.inl" +#endif /* __ACE_INLINE__ */ + +#include "ace/Guard_T.h" +#include "ace/OS_NS_errno.h" + +#if defined (ACE_HAS_DUMP) +# include "ace/Log_Msg.h" +#endif /* ACE_HAS_DUMP */ + +ACE_RCSID (ace, + Barrier, + "$Id: Barrier.cpp 84282 2009-01-30 15:04:29Z msmit $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Sub_Barrier) + +void +ACE_Sub_Barrier::dump (void) const +{ +#if defined (ACE_HAS_DUMP) +// ACE_TRACE ("ACE_Sub_Barrier::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + this->barrier_finished_.dump (); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("running_threads_ = %d\n"), this->running_threads_)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +ACE_Sub_Barrier::ACE_Sub_Barrier (unsigned int count, + ACE_Thread_Mutex &lock, + const ACE_TCHAR *name, + void *arg) + : barrier_finished_ (lock, name, arg), + running_threads_ (count) +{ +// ACE_TRACE ("ACE_Sub_Barrier::ACE_Sub_Barrier"); +} + +ACE_ALLOC_HOOK_DEFINE(ACE_Barrier) + +void +ACE_Barrier::dump (void) const +{ +#if defined (ACE_HAS_DUMP) +// ACE_TRACE ("ACE_Barrier::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + this->lock_.dump (); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("current_generation_ = %d"), this->current_generation_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ncount_ = %d"), this->count_)); + this->sub_barrier_1_.dump (); + this->sub_barrier_2_.dump (); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +ACE_Barrier::ACE_Barrier (unsigned int count, + const ACE_TCHAR *name, + void *arg) + : lock_ (name, (ACE_mutexattr_t *) arg), + current_generation_ (0), + count_ (count), + sub_barrier_1_ (count, lock_, name, arg), + sub_barrier_2_ (count, lock_, name, arg) +{ + ACE_TRACE ("ACE_Barrier::ACE_Barrier"); + this->sub_barrier_[0] = &this->sub_barrier_1_; + this->sub_barrier_[1] = &this->sub_barrier_2_; +} + +int +ACE_Barrier::wait (void) +{ + ACE_TRACE ("ACE_Barrier::wait"); + ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1); + + ACE_Sub_Barrier *sbp = + this->sub_barrier_[this->current_generation_]; + + // Check for shutdown... + if (sbp == 0) + { + errno = ESHUTDOWN; + return -1; + } + + int retval = 0; + + if (sbp->running_threads_ == 1) + { + // We're the last running thread, so swap generations and tell + // all the threads waiting on the barrier to continue on their + // way. + sbp->running_threads_ = this->count_; + // Swap generations. + this->current_generation_ = 1 - this->current_generation_; + sbp->barrier_finished_.broadcast (); + } + else + { + --sbp->running_threads_; + + // Block until all the other threads wait(). + while (sbp->running_threads_ != this->count_) + sbp->barrier_finished_.wait (); + + // We're awake and the count has completed. See if it completed + // because all threads hit the barrier, or because the barrier + // was shut down. + if (this->sub_barrier_[this->current_generation_] == 0) + { + errno = ESHUTDOWN; + retval = -1; + } + } + + return retval; +} + +int +ACE_Barrier::shutdown (void) +{ + ACE_TRACE ("ACE_Barrier::shutdown"); + ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1); + + ACE_Sub_Barrier *sbp = + this->sub_barrier_[this->current_generation_]; + + // Check for shutdown... + if (sbp == 0) + { + errno = ESHUTDOWN; + return -1; + } + + // Flag the shutdown + this->sub_barrier_[0] = 0; + this->sub_barrier_[1] = 0; + // Tell all the threads waiting on the barrier to continue on their way. + sbp->running_threads_ = this->count_; + sbp->barrier_finished_.broadcast (); + + return 0; +} + +ACE_ALLOC_HOOK_DEFINE(ACE_Thread_Barrier) + +ACE_Thread_Barrier::ACE_Thread_Barrier (unsigned int count, + const ACE_TCHAR *name) + : ACE_Barrier (count, name) +{ +// ACE_TRACE ("ACE_Thread_Barrier::ACE_Thread_Barrier"); +} + +void +ACE_Thread_Barrier::dump (void) const +{ +#if defined (ACE_HAS_DUMP) +// ACE_TRACE ("ACE_Thread_Barrier::dump"); + ACE_Barrier::dump (); +#endif /* ACE_HAS_DUMP */ +} + +#if 0 +ACE_ALLOC_HOOK_DEFINE(ACE_Process_Barrier) + +ACE_Process_Barrier::ACE_Process_Barrier (u_int count, + const ACE_TCHAR *name) + : ACE_Barrier (count, USYNC_PROCESS, name) +{ +// ACE_TRACE ("ACE_Process_Barrier::ACE_Process_Barrier"); +} + +void +ACE_Process_Barrier::dump (void) const +{ +#if defined (ACE_HAS_DUMP) +// ACE_TRACE ("ACE_Process_Barrier::dump"); + ACE_Barrier::dump (); +#endif /* ACE_HAS_DUMP */ +} +#endif /* 0 */ + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_THREADS */ diff --git a/dep/acelite/ace/Barrier.h b/dep/acelite/ace/Barrier.h new file mode 100644 index 00000000000..189ff07e4cc --- /dev/null +++ b/dep/acelite/ace/Barrier.h @@ -0,0 +1,215 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file Barrier.h + * + * $Id: Barrier.h 80826 2008-03-04 14:51:23Z wotte $ + * + * Moved from Synch.h. + * + * @author Douglas C. Schmidt + */ +//========================================================================== + +#ifndef ACE_BARRIER_H +#define ACE_BARRIER_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include /**/ "ace/config-all.h" + +// ACE platform supports some form of threading. +#if !defined (ACE_HAS_THREADS) + +#include "ace/OS_NS_errno.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Barrier + * + * @brief This is a no-op to make ACE "syntactically consistent." + */ +class ACE_Export ACE_Barrier +{ +public: + ACE_Barrier (unsigned int, const ACE_TCHAR * = 0, void * = 0) {} + ~ACE_Barrier (void) {} + int wait (void) { ACE_NOTSUP_RETURN (-1); } + void dump (void) const {} +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#else /* ACE_HAS_THREADS */ + +#include "ace/Condition_Thread_Mutex.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +struct ACE_Export ACE_Sub_Barrier +{ + // = Initialization. + ACE_Sub_Barrier (unsigned int count, + ACE_Thread_Mutex &lock, + const ACE_TCHAR *name = 0, + void *arg = 0); + + ~ACE_Sub_Barrier (void); + + /// True if this generation of the barrier is done. + ACE_Condition_Thread_Mutex barrier_finished_; + + /// Number of threads that are still running. + int running_threads_; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; +}; + +/** + * @class ACE_Barrier + * + * @brief Implements "barrier synchronization". + * + * This class allows number of threads to synchronize + * their completion of (one round of) a task, which is known as + * "barrier synchronization". After all the threads call + * on the barrier they are all atomically released and can begin a new + * round. + * + * This implementation uses a "sub-barrier generation numbering" + * scheme to avoid overhead and to ensure that all threads wait to + * leave the barrier correct. This code is based on an article from + * SunOpsis Vol. 4, No. 1 by Richard Marejka + * (Richard.Marejka@canada.sun.com). + */ +class ACE_Export ACE_Barrier +{ +public: + /// Initialize the barrier to synchronize @a count threads. + ACE_Barrier (unsigned int count, + const ACE_TCHAR *name = 0, + void *arg = 0); + + /// Default dtor. + ~ACE_Barrier (void); + + /// Block the caller until all @c count threads have called @c wait and + /// then allow all the caller threads to continue in parallel. + /// + /// @retval 0 after successfully waiting for all threads to wait. + /// @retval -1 if an error occurs or the barrier is shut + /// down (@sa shutdown ()). + int wait (void); + + /// Shut the barrier down, aborting the wait of all waiting threads. + /// Any threads waiting on the barrier when it is shut down will return with + /// value -1, errno ESHUTDOWN. + /// + /// @retval 0 for success, -1 if already shut down. + /// + /// @since ACE beta 5.4.9. + int shutdown (void); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + /// Serialize access to the barrier state. + ACE_Thread_Mutex lock_; + + /// Either 0 or 1, depending on whether we are the first generation + /// of waiters or the next generation of waiters. + int current_generation_; + + /// Total number of threads that can be waiting at any one time. + int count_; + + /** + * We keep two @c sub_barriers, one for the first "generation" of + * waiters, and one for the next "generation" of waiters. This + * efficiently solves the problem of what to do if all the first + * generation waiters don't leave the barrier before one of the + * threads calls wait() again (i.e., starts up the next generation + * barrier). + */ + ACE_Sub_Barrier sub_barrier_1_; + ACE_Sub_Barrier sub_barrier_2_; + ACE_Sub_Barrier *sub_barrier_[2]; + +private: + // = Prevent assignment and initialization. + void operator= (const ACE_Barrier &); + ACE_Barrier (const ACE_Barrier &); +}; + +#if 0 +/** + * @class ACE_Process_Barrier + * + * @brief Implements "barrier synchronization" using ACE_Process_Mutexes! + * + * This class is just a simple wrapper for ACE_Barrier that + * selects the USYNC_PROCESS variant for the locks. + */ +class ACE_Export ACE_Process_Barrier : public ACE_Barrier +{ +public: + /// Create a Process_Barrier, passing in the optional @a name. + ACE_Process_Barrier (unsigned int count, const ACE_TCHAR *name = 0); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; +}; +#endif /* 0 */ + +/** + * @class ACE_Thread_Barrier + * + * @brief Implements "barrier synchronization" using ACE_Thread_Mutexes! + * + * This class is just a simple wrapper for ACE_Barrier that + * selects the USYNC_THREAD variant for the locks. + */ +class ACE_Export ACE_Thread_Barrier : public ACE_Barrier +{ +public: + /// Create a Thread_Barrier, passing in the optional @a name. + ACE_Thread_Barrier (unsigned int count, const ACE_TCHAR *name = 0); + + /// Default dtor. + ~ACE_Thread_Barrier (void); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Barrier.inl" +#endif /* __ACE_INLINE__ */ + +#endif /* !ACE_HAS_THREADS */ + +#include /**/ "ace/post.h" +#endif /* ACE_BARRIER_H */ diff --git a/dep/acelite/ace/Barrier.inl b/dep/acelite/ace/Barrier.inl new file mode 100644 index 00000000000..10430d917a3 --- /dev/null +++ b/dep/acelite/ace/Barrier.inl @@ -0,0 +1,22 @@ +// -*- C++ -*- +// +// $Id: Barrier.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE +ACE_Sub_Barrier::~ACE_Sub_Barrier (void) +{ +} + +ACE_INLINE +ACE_Barrier::~ACE_Barrier (void) +{ +} + +ACE_INLINE +ACE_Thread_Barrier::~ACE_Thread_Barrier (void) +{ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Base_Thread_Adapter.cpp b/dep/acelite/ace/Base_Thread_Adapter.cpp new file mode 100644 index 00000000000..eac2c14903c --- /dev/null +++ b/dep/acelite/ace/Base_Thread_Adapter.cpp @@ -0,0 +1,128 @@ +// $Id: Base_Thread_Adapter.cpp 84340 2009-02-05 22:28:08Z stallions $ + +#include "ace/Base_Thread_Adapter.h" + +ACE_RCSID (ace, + Base_Thread_Adapter, + "$Id: Base_Thread_Adapter.cpp 84340 2009-02-05 22:28:08Z stallions $") + +#if !defined (ACE_HAS_INLINED_OSCALLS) +# include "ace/Base_Thread_Adapter.inl" +#endif /* ACE_HAS_INLINED_OSCALLS */ + +#if defined (ACE_HAS_TSS_EMULATION) +# include "ace/OS_NS_Thread.h" +#endif /* ACE_HAS_TSS_EMULATION */ + +#include "ace/Service_Config.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INIT_LOG_MSG_HOOK ACE_Base_Thread_Adapter::init_log_msg_hook_ = 0; +ACE_INHERIT_LOG_MSG_HOOK ACE_Base_Thread_Adapter::inherit_log_msg_hook_ = 0; +ACE_CLOSE_LOG_MSG_HOOK ACE_Base_Thread_Adapter::close_log_msg_hook_ = 0; +ACE_SYNC_LOG_MSG_HOOK ACE_Base_Thread_Adapter::sync_log_msg_hook_ = 0; +ACE_THR_DESC_LOG_MSG_HOOK ACE_Base_Thread_Adapter::thr_desc_log_msg_hook_ = 0; + +ACE_Base_Thread_Adapter::ACE_Base_Thread_Adapter ( + ACE_THR_FUNC user_func, + void *arg, + ACE_THR_C_FUNC entry_point, + ACE_OS_Thread_Descriptor *td +#if defined (ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS) + , ACE_SEH_EXCEPT_HANDLER selector + , ACE_SEH_EXCEPT_HANDLER handler +#endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */ + ) + : user_func_ (user_func) + , arg_ (arg) + , entry_point_ (entry_point) + , thr_desc_ (td) + , ctx_ (ACE_Service_Config::current()) +{ + ACE_OS_TRACE ("ACE_Base_Thread_Adapter::ACE_Base_Thread_Adapter"); + + if (ACE_Base_Thread_Adapter::init_log_msg_hook_ != 0) + (*ACE_Base_Thread_Adapter::init_log_msg_hook_) ( + this->log_msg_attributes_ +# if defined (ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS) + , selector + , handler +# endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */ + ); +#ifdef ACE_USES_GPROF + getitimer (ITIMER_PROF, &itimer_); +#endif // ACE_USES_GPROF +} + +ACE_Base_Thread_Adapter::~ACE_Base_Thread_Adapter (void) +{ +} + +void +ACE_Base_Thread_Adapter::inherit_log_msg (void) +{ + if (ACE_Base_Thread_Adapter::inherit_log_msg_hook_ != 0) + (*ACE_Base_Thread_Adapter::inherit_log_msg_hook_)( + this->thr_desc_, + this->log_msg_attributes_); + + // Initialize the proper configuration context for the new thread + // Placed here since inherit_log_msg() gets called from any of our + // descendants (before self-destructing) + ACE_Service_Config::current (this->ctx_); +} + +void +ACE_Base_Thread_Adapter::close_log_msg (void) +{ + if (ACE_Base_Thread_Adapter::close_log_msg_hook_ != 0) + (*ACE_Base_Thread_Adapter::close_log_msg_hook_) (); +} + +void +ACE_Base_Thread_Adapter::sync_log_msg (const ACE_TCHAR *prg) +{ + if (ACE_Base_Thread_Adapter::sync_log_msg_hook_ != 0) + (*ACE_Base_Thread_Adapter::sync_log_msg_hook_) (prg); +} + +ACE_OS_Thread_Descriptor * +ACE_Base_Thread_Adapter::thr_desc_log_msg (void) +{ + if (ACE_Base_Thread_Adapter::thr_desc_log_msg_hook_ != 0) + return (*ACE_Base_Thread_Adapter::thr_desc_log_msg_hook_) (); + return 0; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +// Run the thread entry point for the . This must +// be an extern "C" to make certain compilers happy... + +extern "C" ACE_THR_FUNC_RETURN +ACE_THREAD_ADAPTER_NAME (void *args) +{ + ACE_OS_TRACE ("ACE_THREAD_ADAPTER_NAME"); + +#if defined (ACE_HAS_TSS_EMULATION) + // As early as we can in the execution of the new thread, allocate + // its local TS storage. Allocate it on the stack, to save dynamic + // allocation/dealloction. + void *ts_storage[ACE_TSS_Emulation::ACE_TSS_THREAD_KEYS_MAX]; + ACE_TSS_Emulation::tss_open (ts_storage); +#endif /* ACE_HAS_TSS_EMULATION */ + + ACE_Base_Thread_Adapter * const thread_args = + static_cast (args); + +#ifdef ACE_USES_GPROF + setitimer (ITIMER_PROF, thread_args->timerval (), 0); +#endif // ACE_USES_GPROF + + // Invoke the user-supplied function with the args. + ACE_THR_FUNC_RETURN status = thread_args->invoke (); + + return status; +} + diff --git a/dep/acelite/ace/Base_Thread_Adapter.h b/dep/acelite/ace/Base_Thread_Adapter.h new file mode 100644 index 00000000000..b36d18e4f13 --- /dev/null +++ b/dep/acelite/ace/Base_Thread_Adapter.h @@ -0,0 +1,195 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Base_Thread_Adapter.h + * + * $Id: Base_Thread_Adapter.h 81239 2008-04-04 22:28:48Z iliyan $ + * + * @author Nanbor Wang + */ +//============================================================================= + +#ifndef ACE_BASE_THREAD_ADAPTER_H +#define ACE_BASE_THREAD_ADAPTER_H +#include /**/ "ace/pre.h" + +#include "ace/OS_Log_Msg_Attributes.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include /**/ "ace/ACE_export.h" +#include "ace/OS_Log_Msg_Attributes.h" + +#ifdef ACE_USES_GPROF +#include "os_include/sys/os_time.h" +#endif // ACE_USES_GPROF + +#if (defined (ACE_HAS_VERSIONED_NAMESPACE) && ACE_HAS_VERSIONED_NAMESPACE == 1) +# define ACE_THREAD_ADAPTER_NAME ACE_PREPROC_CONCATENATE(ACE_VERSIONED_NAMESPACE_NAME, _ace_thread_adapter) +#else +# define ACE_THREAD_ADAPTER_NAME ace_thread_adapter +#endif /* ACE_HAS_VERSIONED_NAMESPACE == 1 */ + +// Run the thread entry point for the ACE_Thread_Adapter. This must +// be an extern "C" to make certain compilers happy... + +extern "C" ACE_Export ACE_THR_FUNC_RETURN ACE_THREAD_ADAPTER_NAME (void *args); + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_OS_Thread_Descriptor + * + * @brief Parent class of all ACE_Thread_Descriptor classes. + * = + * Container for ACE_Thread_Descriptor members that are + * used in ACE_OS. + */ +class ACE_Export ACE_OS_Thread_Descriptor +{ +public: + /// Get the thread creation flags. + long flags (void) const; + +protected: + /// For use by ACE_Thread_Descriptor. + ACE_OS_Thread_Descriptor (long flags = 0); + + /** + * Keeps track of whether this thread was created "detached" or not. + * If a thread is *not* created detached then if someone calls + * , we need to join with that thread (and + * close down the handle). + */ + long flags_; +}; + + + +class ACE_Service_Gestalt; + + +/** + * @class ACE_Base_Thread_Adapter + * + * @brief Base class for all the Thread_Adapters. + * + * Converts a C++ function into a function that can be + * called from a thread creation routine + * (e.g., pthread_create() or _beginthreadex()) that expects an + * extern "C" entry point. This class also makes it possible to + * transparently provide hooks to register a thread with an + * ACE_Thread_Manager. + * This class is used in ACE_OS::thr_create(). In general, the + * thread that creates an object of this class is different from + * the thread that calls @c invoke() on this object. Therefore, + * the @c invoke() method is responsible for deleting itself. + */ +class ACE_Export ACE_Base_Thread_Adapter +{ +public: + + virtual ~ACE_Base_Thread_Adapter (void); + + /// Virtual method invoked by the thread entry point. + virtual ACE_THR_FUNC_RETURN invoke (void) = 0; + + /// Accessor for the C entry point function to the OS thread creation + /// routine. + ACE_THR_C_FUNC entry_point (void); + +#ifdef ACE_USES_GPROF + /// Accessor to the itimer_ + /// followed http://sam.zoy.org/writings/programming/gprof.html + struct itimerval* timerval (void); +#endif // ACE_USES_PROF + + /// Invoke the close_log_msg_hook, if it is present + static void close_log_msg (void); + + /// Invoke the sync_log_msg_hook, if it is present + static void sync_log_msg (const ACE_TCHAR *prog_name); + + /// Invoke the thr_desc_log_msg_hook, if it is present + static ACE_OS_Thread_Descriptor *thr_desc_log_msg (void); + +protected: + /// Constructor. + ACE_Base_Thread_Adapter (ACE_THR_FUNC user_func, + void *arg, + ACE_THR_C_FUNC entry_point = (ACE_THR_C_FUNC) ACE_THREAD_ADAPTER_NAME, + ACE_OS_Thread_Descriptor *td = 0 +# if defined (ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS) + , ACE_SEH_EXCEPT_HANDLER selector = 0 + , ACE_SEH_EXCEPT_HANDLER handler = 0 +# endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */ + ); + /// Inherit the logging features if the parent thread has an + /// ACE_Log_Msg. + void inherit_log_msg (void); + +private: + /// The hooks to inherit and cleanup the Log_Msg attributes + static ACE_INIT_LOG_MSG_HOOK init_log_msg_hook_; + static ACE_INHERIT_LOG_MSG_HOOK inherit_log_msg_hook_; + static ACE_CLOSE_LOG_MSG_HOOK close_log_msg_hook_; + static ACE_SYNC_LOG_MSG_HOOK sync_log_msg_hook_; + static ACE_THR_DESC_LOG_MSG_HOOK thr_desc_log_msg_hook_; + + /// Set the Log_Msg hooks + static void set_log_msg_hooks (ACE_INIT_LOG_MSG_HOOK init_hook, + ACE_INHERIT_LOG_MSG_HOOK inherit_hook, + ACE_CLOSE_LOG_MSG_HOOK close_hook, + ACE_SYNC_LOG_MSG_HOOK sync_hook, + ACE_THR_DESC_LOG_MSG_HOOK thr_desc); + + /// Allow the ACE_Log_Msg class to set its hooks. + friend class ACE_Log_Msg; + +protected: + /// Thread startup function passed in by the user (C++ linkage). + ACE_THR_FUNC user_func_; + + /// Argument to thread startup function. + void *arg_; + + /// Entry point to the underlying OS thread creation call (C + /// linkage). + ACE_THR_C_FUNC entry_point_; + + /** + * Optional thread descriptor. Passing this pointer in will force + * the spawned thread to cache this location in and wait + * until fills in all information in thread + * descriptor. + */ + ACE_OS_Thread_Descriptor *thr_desc_; + + /// The ACE_Log_Msg attributes. + ACE_OS_Log_Msg_Attributes log_msg_attributes_; + + /// That is usefull for gprof, define itimerval +#ifdef ACE_USES_GPROF + struct itimerval itimer_; +#endif // ACE_USES_GPROF + + /// Keep a reference to the configuration context that spawns the + /// thread so the child can inherit it. + ACE_Service_Gestalt * const ctx_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +# if defined (ACE_HAS_INLINED_OSCALLS) +# if defined (ACE_INLINE) +# undef ACE_INLINE +# endif /* ACE_INLINE */ +# define ACE_INLINE inline +# include "ace/Base_Thread_Adapter.inl" +# endif /* ACE_HAS_INLINED_OSCALLS */ + +#include /**/ "ace/post.h" +#endif /* ACE_BASE_THREAD_ADAPTER_H */ diff --git a/dep/acelite/ace/Base_Thread_Adapter.inl b/dep/acelite/ace/Base_Thread_Adapter.inl new file mode 100644 index 00000000000..3bac80246dd --- /dev/null +++ b/dep/acelite/ace/Base_Thread_Adapter.inl @@ -0,0 +1,48 @@ +// -*- C++ -*- +// +// $Id: Base_Thread_Adapter.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE long +ACE_OS_Thread_Descriptor::flags (void) const +{ + return flags_; +} + +ACE_INLINE +ACE_OS_Thread_Descriptor::ACE_OS_Thread_Descriptor (long flags) + : flags_ (flags) +{ +} + +ACE_INLINE void +ACE_Base_Thread_Adapter::set_log_msg_hooks ( + ACE_INIT_LOG_MSG_HOOK init_hook, + ACE_INHERIT_LOG_MSG_HOOK inherit_hook, + ACE_CLOSE_LOG_MSG_HOOK close_hook, + ACE_SYNC_LOG_MSG_HOOK sync_hook, + ACE_THR_DESC_LOG_MSG_HOOK thr_desc_hook) +{ + ACE_Base_Thread_Adapter::init_log_msg_hook_ = init_hook; + ACE_Base_Thread_Adapter::inherit_log_msg_hook_ = inherit_hook; + ACE_Base_Thread_Adapter::close_log_msg_hook_ = close_hook; + ACE_Base_Thread_Adapter::sync_log_msg_hook_ = sync_hook; + ACE_Base_Thread_Adapter::thr_desc_log_msg_hook_ = thr_desc_hook; +} + +ACE_INLINE ACE_THR_C_FUNC +ACE_Base_Thread_Adapter::entry_point (void) +{ + return this->entry_point_; +} + +#ifdef ACE_USES_GPROF +ACE_INLINE itimerval* +ACE_Base_Thread_Adapter::timerval (void) +{ + return &(this->itimer_); +} +#endif // ACE_USES_GPROF + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Based_Pointer_Repository.cpp b/dep/acelite/ace/Based_Pointer_Repository.cpp new file mode 100644 index 00000000000..4ebe8b82c7a --- /dev/null +++ b/dep/acelite/ace/Based_Pointer_Repository.cpp @@ -0,0 +1,119 @@ +// $Id: Based_Pointer_Repository.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Map_Manager.h" +#include "ace/Based_Pointer_Repository.h" +#include "ace/Guard_T.h" +#include "ace/Null_Mutex.h" +#include "ace/Synch_Traits.h" +#include "ace/RW_Thread_Mutex.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Based_Pointer_Repository_Rep + * + * @brief Implementation for the ACE_Based_Pointer_Repository. + * + * Every memory pool in ACE binds it's mapping base address and + * the mapped size to this repository every time it maps/remaps a + * new chunk of memory successfully. + */ +class ACE_Based_Pointer_Repository_Rep +{ +public: + // Useful typedefs. + typedef ACE_Map_Manager MAP_MANAGER; + typedef ACE_Map_Iterator MAP_ITERATOR; + typedef ACE_Map_Entry MAP_ENTRY; + + /// Keeps track of the mapping between addresses and their associated + /// values. + MAP_MANAGER addr_map_; + + /// Synchronize concurrent access to the map. + ACE_SYNCH_MUTEX lock_; +}; + +ACE_Based_Pointer_Repository::ACE_Based_Pointer_Repository (void) +{ + ACE_TRACE ("ACE_Based_Pointer_Repository::ACE_Based_Pointer_Repository"); + ACE_NEW (this->rep_, + ACE_Based_Pointer_Repository_Rep); +} + +ACE_Based_Pointer_Repository::~ACE_Based_Pointer_Repository (void) +{ + ACE_TRACE ("ACE_Based_Pointer_Repository::~ACE_Based_Pointer_Repository"); + delete this->rep_; +} + +// Search for appropriate base address in repository + +int +ACE_Based_Pointer_Repository::find (void *addr, void *&base_addr) +{ + ACE_TRACE ("ACE_Based_Pointer_Repository::find"); + ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, mon, this->rep_->lock_, -1); + ACE_Based_Pointer_Repository_Rep::MAP_ENTRY *ce = 0; + + for (ACE_Based_Pointer_Repository_Rep::MAP_ITERATOR iter (this->rep_->addr_map_); + iter.next (ce) != 0; + iter.advance ()) + // Check to see if is within any of the regions. + if (addr >= ce->ext_id_ + && addr < ((char *)ce->ext_id_ + ce->int_id_)) + { + // Assign the base address. + base_addr = ce->ext_id_; + return 1; + } + + // Assume base address 0 (e.g., if new'ed). + base_addr = 0; + return 0; +} + +// Bind a new entry to the repository or update the size of an +// existing entry. + +int +ACE_Based_Pointer_Repository::bind (void *addr, size_t size) +{ + ACE_TRACE ("ACE_Based_Pointer_Repository::bind"); + ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, mon, this->rep_->lock_, -1); + + return this->rep_->addr_map_.rebind (addr, size); +} + +// Unbind a base from the repository. + +int +ACE_Based_Pointer_Repository::unbind (void *addr) +{ + ACE_TRACE ("ACE_Based_Pointer_Repository::unbind"); + ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, mon, this->rep_->lock_, -1); + ACE_Based_Pointer_Repository_Rep::MAP_ENTRY *ce = 0; + + // Search for service handlers that requested notification. + + for (ACE_Based_Pointer_Repository_Rep::MAP_ITERATOR iter (this->rep_->addr_map_); + iter.next (ce) != 0; + iter.advance ()) + { + // Check to see if is within any of the regions and if + // so, unbind the key from the map. + if (addr >= ce->ext_id_ + && addr < ((char *)ce->ext_id_ + ce->int_id_)) + // Unbind base address. + return this->rep_->addr_map_.unbind (ce->ext_id_); + } + + return 0; +} + +#if defined (ACE_HAS_EXPLICIT_STATIC_TEMPLATE_MEMBER_INSTANTIATION) +template ACE_Singleton * + ACE_Singleton::singleton_; +#endif /* ACE_HAS_EXPLICIT_STATIC_TEMPLATE_MEMBER_INSTANTIATION */ + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Based_Pointer_Repository.h b/dep/acelite/ace/Based_Pointer_Repository.h new file mode 100644 index 00000000000..d549ce15326 --- /dev/null +++ b/dep/acelite/ace/Based_Pointer_Repository.h @@ -0,0 +1,94 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Based_Pointer_Repository.h + * + * $Id: Based_Pointer_Repository.h 84837 2009-03-16 13:01:15Z johnnyw $ + * + * @author Dietrich Quehl + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_BASED_POINTER_REPOSITORY_H +#define ACE_BASED_POINTER_REPOSITORY_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Singleton.h" +#include "ace/Synch_Traits.h" +#include "ace/os_include/os_stddef.h" + + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Forward decl., using the "Cheshire Cat" technique. +class ACE_Based_Pointer_Repository_Rep; + +/** + * @class ACE_Based_Pointer_Repository + * + * @brief Maps pointers to the base address of the region to which each + * pointer belongs. + */ +class ACE_Export ACE_Based_Pointer_Repository +{ +public: + // = Use ACE_Null_Mutex to allow locking while iterating. + + // = Initialization and termination methods. + ACE_Based_Pointer_Repository (void); + ~ACE_Based_Pointer_Repository (void); + + // = Search structure methods. + /** + * Return the appropriate @a base_addr region that contains @a addr. + * Returns 1 on success and 0 if the @a addr isn't contained in any + * @a base_addr region. + */ + int find (void *addr, + void *&base_addr); + + /// Bind a new entry to the repository or update the size of an + /// existing entry. Returns 0 on success and -1 on failure. + int bind (void *addr, + size_t size); + + /// Unbind from the repository the that @a addr is + /// contained within. + int unbind (void *addr); + +private: + + /// Use the "Cheshire-Cat" technique to hide the implementation in + /// order to avoid circular #include dependencies. + ACE_Based_Pointer_Repository_Rep *rep_; + +private: + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Based_Pointer_Repository &)) + ACE_UNIMPLEMENTED_FUNC (ACE_Based_Pointer_Repository (const ACE_Based_Pointer_Repository &)) +}; + +// ---------------------------------- + +/// Declare a process wide singleton +ACE_SINGLETON_DECLARE (ACE_Singleton, + ACE_Based_Pointer_Repository, + ACE_SYNCH_RW_MUTEX) + +/// Provide a Singleton access point to the based pointer repository. +typedef ACE_Singleton + ACE_BASED_POINTER_REPOSITORY; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" + +#endif /* ACE_BASED_POINTER_REPOSITORY_H */ diff --git a/dep/acelite/ace/Based_Pointer_T.cpp b/dep/acelite/ace/Based_Pointer_T.cpp new file mode 100644 index 00000000000..b85774db48d --- /dev/null +++ b/dep/acelite/ace/Based_Pointer_T.cpp @@ -0,0 +1,121 @@ +// $Id: Based_Pointer_T.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#ifndef ACE_BASED_POINTER_T_CPP +#define ACE_BASED_POINTER_T_CPP + +#include "ace/Based_Pointer_T.h" +#include "ace/Based_Pointer_Repository.h" +#include "ace/Log_Msg.h" + +# define ACE_TRACEX(X) ACE_Trace ____ (ACE_TEXT (X), __LINE__, ACE_TEXT (__FILE__)) + +#if !defined (__ACE_INLINE__) +#include "ace/Based_Pointer_T.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template +ACE_Based_Pointer::ACE_Based_Pointer (void) +{ + ACE_TRACE ("ACE_Based_Pointer::ACE_Based_Pointer"); +} + +template void +ACE_Based_Pointer_Basic::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Based_Pointer_Basic::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ntarget_ = %d\n"), this->target_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("base_offset_ = %d\n"), this->base_offset_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("computed pointer = %x\n"), + (CONCRETE *)(ACE_COMPUTE_BASED_POINTER (this)))); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +template +ACE_Based_Pointer::ACE_Based_Pointer (CONCRETE *initial) + : ACE_Based_Pointer_Basic (initial) +{ + ACE_TRACE ("ACE_Based_Pointer_Basic::ACE_Based_Pointer_Basic"); +} + +template +ACE_Based_Pointer::ACE_Based_Pointer (const void* base_addr, int) + : ACE_Based_Pointer_Basic (base_addr, 0) +{ + ACE_TRACE ("ACE_Based_Pointer_Basic::ACE_Based_Pointer_Basic"); +} + +template +ACE_Based_Pointer_Basic::ACE_Based_Pointer_Basic (void) + : target_ (0), + base_offset_ (0) +{ + ACE_TRACE ("ACE_Based_Pointer_Basic::ACE_Based_Pointer_Basic"); + void *base_addr = 0; + + // Find the base address associated with our pointer. Note + // that it's ok for to return 0, which simply indicates that + // the address is not in memory-mapped virtual address space. + ACE_BASED_POINTER_REPOSITORY::instance ()->find (this, + base_addr); + this->base_offset_ = (char *) this - (char *) base_addr; +} + +template +ACE_Based_Pointer_Basic::ACE_Based_Pointer_Basic (const void *base_addr, int) + : target_ (0), + base_offset_ (0) +{ + ACE_TRACE ("ACE_Based_Pointer_Basic::ACE_Based_Pointer_Basic"); + this->base_offset_ = (char *) this - (char *) base_addr; +} + +template +ACE_Based_Pointer_Basic::ACE_Based_Pointer_Basic (CONCRETE *rhs) + : target_ (0), + base_offset_ (0) +{ + ACE_TRACE ("ACE_Based_Pointer_Basic::ACE_Based_Pointer_Basic"); + + if (rhs == 0) + // Store a value of that indicate "NULL" pointer. + this->target_ = -1; + else + { + void *base_addr = 0; + + // Find the base address associated with the pointer. + // Note that it's ok for to return 0, which simply + // indicates that the address is not in memory-mapped virtual + // address space. + ACE_BASED_POINTER_REPOSITORY::instance ()->find (this, + base_addr); + this->base_offset_ = (char *) this - (char *) base_addr; + this->target_ = ((char *) rhs - (char *) base_addr); + } +} + +template +ACE_Based_Pointer_Basic::ACE_Based_Pointer_Basic (const ACE_Based_Pointer_Basic &) +{ + ACE_TRACE ("ACE_Based_Pointer_Basic::ACE_Based_Pointer_Basic"); + + ACE_ASSERT (0); // not implemented. +} + +template +ACE_Based_Pointer::ACE_Based_Pointer (const ACE_Based_Pointer &rhs) + : ACE_Based_Pointer_Basic (rhs) +{ + ACE_TRACE ("ACE_Based_Pointer::ACE_Based_Pointer"); + ACE_ASSERT (0); // not implemented. +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_BASED_POINTER_T_CPP */ diff --git a/dep/acelite/ace/Based_Pointer_T.h b/dep/acelite/ace/Based_Pointer_T.h new file mode 100644 index 00000000000..802e73ca0d3 --- /dev/null +++ b/dep/acelite/ace/Based_Pointer_T.h @@ -0,0 +1,205 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Based_Pointer_T.h + * + * $Id: Based_Pointer_T.h 81705 2008-05-15 14:02:02Z johnnyw $ + * + * @author Dietrich Quehl + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_BASED_POINTER_T_H +#define ACE_BASED_POINTER_T_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" +#include "ace/Basic_Types.h" + +#if defined (_MSC_VER) +// Suppress warning e.g. "return type for +// 'ACE_Based_Pointer::operator ->' is 'long *' (i.e., not a UDT +// or reference to a UDT. Will produce errors if applied using infix +// notation)" +#pragma warning(disable: 4284) +#endif /* _MSC_VER */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Based_Pointer_Basic + * + * @brief A proxy that keeps track of the relative offset of a "pointer" + * from its base address. + * This class makes it possible to transparently use "pointers" in + * shared memory as easily as programming with pointers to local + * memory. In particular, we don't need to ensure that the base + * addresses of all the pointers are mapped into separate + * processes at the same absolute memory base address. + */ +template +class ACE_Based_Pointer_Basic +{ +public: + /** + * This constructor initializes the by asking the + * Singleton for the base address of + * the memory region within which it is instantiated. Two results + * are possible: + * + * 1. An has stored a base address/size pair and the + * new based-pointer instance is located between the base address and + * the base address + size - 1. In this case, the repository + * returns the base address. + * + * 2. No suitable address/size pair was found. The repository + * assumes an address in the regular (not mapped) virtual address + * space of the process and returns 0. In this case, the + * based-pointer uses its address as an offset to it's base + * address 0. + */ + ACE_Based_Pointer_Basic (void); + + /** + * Initialize this object using the @a initial pointer. This + * constructor initializes the by asking the + * Singleton for the base address of + * the memory region within which it is instantiated. Three results + * are possible: + * + * 1. An has stored a base address/size pair and the + * new based-pointer instance is located between the base address and + * the base address + size - 1. In this case, the repository + * returns the base address. + * + * 2. No suitable address/size pair was found. The repository + * assumes an address in the regular (not mapped) virtual address + * space of the process and returns 0. In this case, the + * based-pointer uses its address as an offset to its base + * address 0. + * + * 3. If @a initial is 0 then set the value of to -1, which + * indicates a "NULL" pointer. + */ + ACE_Based_Pointer_Basic (CONCRETE *initial); + + /// Copy constructor. + ACE_Based_Pointer_Basic (const ACE_Based_Pointer_Basic &); + + /// Constructor for know base address. @a o is only used to + /// resolve overload ambiguity. + ACE_Based_Pointer_Basic (const void *base_addr, int o); + + /// Pseudo-assignment operator. + void operator = (CONCRETE *from); + + /// Pseudo-assignment operator. + void operator = (const ACE_Based_Pointer_Basic &); + + /// Dereference operator. + CONCRETE operator * (void) const; + + /// Less than operator. + bool operator < (const ACE_Based_Pointer_Basic &) const; + + /// Less than or equal operator. + bool operator <= (const ACE_Based_Pointer_Basic &) const; + + /// Greater than operator. + bool operator > (const ACE_Based_Pointer_Basic &) const; + + /// Greater than or equal operator. + bool operator >= (const ACE_Based_Pointer_Basic &) const; + + /// Equality operator. + bool operator == (const ACE_Based_Pointer_Basic &) const; + + /// Inequality operator. + bool operator != (const ACE_Based_Pointer_Basic &) const; + + /// Subscript operator. + CONCRETE operator [](int index) const; + + /// Increment operator. + void operator+= (int index); + + /// Returns the underlying memory address of the smart pointer. + operator CONCRETE *() const; + + /// Returns the underlying memory address of the smart pointer. + CONCRETE *addr (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + + /// Dump the state of the object. + void dump (void) const; + +protected: + ptrdiff_t target_; + + /// Keep track of our offset from the base pointer. + ptrdiff_t base_offset_; +}; + +/** + * @class ACE_Based_Pointer + * + * @brief A smart proxy that keeps track of the relative offset of a + * "pointer" from its base address. + * + * This class makes it possible to transparently use "pointers" in + * shared memory as easily as programming with pointers to local + * memory by overloading the C++ delegation operator ->(). + */ +template +class ACE_Based_Pointer : public ACE_Based_Pointer_Basic +{ +public: + // = Initialization method. + /// Constructor. See constructor for ACE_Based_Pointer_Basic for + /// details. + ACE_Based_Pointer (void); + + /// Initialize this object using the pointer. See + /// constructor for ACE_Based_Pointer_Basic for details. + ACE_Based_Pointer (CONCRETE *initial); + + /// Initialize this object with known @a base_addr. @a dummy is + /// a dummy value used to resolve overload ambiguity and it + /// otherwise ignored. + ACE_Based_Pointer (const void *base_addr, int dummy); + + /// Copy constructor (not implemented yet). + ACE_Based_Pointer (const ACE_Based_Pointer &); + + /// Assignment operator. + void operator = (const ACE_Based_Pointer &); + + /// Pseudo-assignment operator. + void operator = (CONCRETE *from); + + /// The C++ "delegation operator". + CONCRETE *operator-> (void); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Based_Pointer_T.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Based_Pointer_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Based_Pointer_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" + +#endif /* ACE_BASED_POINTER_T_H */ diff --git a/dep/acelite/ace/Based_Pointer_T.inl b/dep/acelite/ace/Based_Pointer_T.inl new file mode 100644 index 00000000000..ba6a5aa511b --- /dev/null +++ b/dep/acelite/ace/Based_Pointer_T.inl @@ -0,0 +1,139 @@ +// -*- C++ -*- +// +// $Id: Based_Pointer_T.inl 81705 2008-05-15 14:02:02Z johnnyw $ + +#define ACE_COMPUTE_BASED_POINTER(P) (((char *) (P) - (P)->base_offset_) + (P)->target_) +#include "ace/Global_Macros.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template ACE_INLINE CONCRETE * +ACE_Based_Pointer::operator->(void) +{ + ACE_TRACE ("ACE_Based_Pointer::operator->"); + return reinterpret_cast (ACE_COMPUTE_BASED_POINTER (this)); +} + +template ACE_INLINE void +ACE_Based_Pointer_Basic::operator = (CONCRETE *rhs) +{ + ACE_TRACE ("ACE_Based_Pointer_Basic::operator ="); + if (rhs == 0) + // Store a value of that indicate "NULL" pointer. + this->target_ = -1; + else + this->target_ = ((char *) rhs + - ((char *) this - this->base_offset_)); +} + +template ACE_INLINE void +ACE_Based_Pointer::operator = (CONCRETE *rhs) +{ + ACE_TRACE ("ACE_Based_Pointer::operator ="); + if (rhs == 0) + // Store a value of that indicate "NULL" pointer. + this->target_ = -1; + else + this->target_ = ((char *) rhs + - ((char *) this - this->base_offset_)); +} + +template ACE_INLINE CONCRETE +ACE_Based_Pointer_Basic::operator *(void) const +{ + ACE_TRACE ("ACE_Based_Pointer_Basic::operator *"); + return *reinterpret_cast (ACE_COMPUTE_BASED_POINTER (this)); +} + +template ACE_INLINE CONCRETE * +ACE_Based_Pointer_Basic::addr (void) const +{ + ACE_TRACE ("ACE_Based_Pointer_Basic::addr"); + + if (this->target_ == -1) + return 0; + else + return reinterpret_cast (ACE_COMPUTE_BASED_POINTER (this)); +} + +template ACE_INLINE +ACE_Based_Pointer_Basic::operator CONCRETE *() const +{ + ACE_TRACE ("ACE_Based_Pointer_Basic::operator CONCRETE *()"); + + return this->addr (); +} + +template ACE_INLINE CONCRETE +ACE_Based_Pointer_Basic::operator [] (int index) const +{ + ACE_TRACE ("ACE_Based_Pointer_Basic::operator []"); + CONCRETE *c = + reinterpret_cast (ACE_COMPUTE_BASED_POINTER (this)); + return c[index]; +} + +template ACE_INLINE void +ACE_Based_Pointer_Basic::operator += (int index) +{ + ACE_TRACE ("ACE_Based_Pointer_Basic::operator +="); + this->base_offset_ += (index * sizeof (CONCRETE)); +} + +template ACE_INLINE bool +ACE_Based_Pointer_Basic::operator == (const ACE_Based_Pointer_Basic &rhs) const +{ + ACE_TRACE ("ACE_Based_Pointer_Basic::operator =="); + return ACE_COMPUTE_BASED_POINTER (this) == ACE_COMPUTE_BASED_POINTER (&rhs); +} + +template ACE_INLINE bool +ACE_Based_Pointer_Basic::operator != (const ACE_Based_Pointer_Basic &rhs) const +{ + ACE_TRACE ("ACE_Based_Pointer_Basic::operator !="); + return !(*this == rhs); +} + +template ACE_INLINE bool +ACE_Based_Pointer_Basic::operator < (const ACE_Based_Pointer_Basic &rhs) const +{ + ACE_TRACE ("ACE_Based_Pointer_Basic::operator <"); + return ACE_COMPUTE_BASED_POINTER (this) < ACE_COMPUTE_BASED_POINTER (&rhs); +} + +template ACE_INLINE bool +ACE_Based_Pointer_Basic::operator <= (const ACE_Based_Pointer_Basic &rhs) const +{ + ACE_TRACE ("ACE_Based_Pointer_Basic::operator <="); + return ACE_COMPUTE_BASED_POINTER (this) <= ACE_COMPUTE_BASED_POINTER (&rhs); +} + +template ACE_INLINE bool +ACE_Based_Pointer_Basic::operator > (const ACE_Based_Pointer_Basic &rhs) const +{ + ACE_TRACE ("ACE_Based_Pointer_Basic::operator >"); + return ACE_COMPUTE_BASED_POINTER (this) > ACE_COMPUTE_BASED_POINTER (&rhs); +} + +template ACE_INLINE bool +ACE_Based_Pointer_Basic::operator >= (const ACE_Based_Pointer_Basic &rhs) const +{ + ACE_TRACE ("ACE_Based_Pointer_Basic::operator >="); + return ACE_COMPUTE_BASED_POINTER (this) >= ACE_COMPUTE_BASED_POINTER (&rhs); +} + +template ACE_INLINE void +ACE_Based_Pointer_Basic::operator= (const ACE_Based_Pointer_Basic &rhs) +{ + ACE_TRACE ("ACE_Based_Pointer_Basic::operator="); + *this = rhs.addr (); +} + +template ACE_INLINE void +ACE_Based_Pointer::operator= (const ACE_Based_Pointer &rhs) +{ + ACE_TRACE ("ACE_Based_Pointer::operator="); + *this = rhs.addr (); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Basic_Stats.cpp b/dep/acelite/ace/Basic_Stats.cpp new file mode 100644 index 00000000000..fe678333d89 --- /dev/null +++ b/dep/acelite/ace/Basic_Stats.cpp @@ -0,0 +1,78 @@ +// $Id: Basic_Stats.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Basic_Stats.h" +#include "ace/Log_Msg.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Basic_Stats.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID(ace, + Basic_Stats, + "$Id: Basic_Stats.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +void +ACE_Basic_Stats::accumulate (const ACE_Basic_Stats &rhs) +{ + if (rhs.samples_count_ == 0) + return; + + if (this->samples_count_ == 0) + { + this->min_ = rhs.min_; + this->min_at_ = rhs.min_at_; + + this->max_ = rhs.max_; + this->max_at_ = rhs.max_at_; + } + else + { + if (this->min_ > rhs.min_) + { + this->min_ = rhs.min_; + this->min_at_ = rhs.min_at_; + } + if (this->max_ < rhs.max_) + { + this->max_ = rhs.max_; + this->max_at_ = rhs.max_at_; + } + } + + this->samples_count_ += rhs.samples_count_; + this->sum_ += rhs.sum_; +} + +void +ACE_Basic_Stats::dump_results (const ACE_TCHAR *msg, ACE_UINT32 sf) const +{ +#ifndef ACE_NLOGGING + if (this->samples_count () == 0u) + { + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("%s : no data collected\n"), msg)); + return; + } + + ACE_UINT64 avg = this->sum_ / this->samples_count_; + + ACE_UINT64 l_min = this->min_ / sf; + ACE_UINT64 l_max = this->max_ / sf; + ACE_UINT64 l_avg = avg / sf; + + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("%s latency : %Q[%d]/%Q/%Q[%d] (min/avg/max)\n"), + msg, + l_min, this->min_at_, + l_avg, + l_max, this->max_at_)); + +#else + ACE_UNUSED_ARG (msg); + ACE_UNUSED_ARG (sf); +#endif /* ACE_NLOGGING */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Basic_Stats.h b/dep/acelite/ace/Basic_Stats.h new file mode 100644 index 00000000000..bff1ff29f65 --- /dev/null +++ b/dep/acelite/ace/Basic_Stats.h @@ -0,0 +1,87 @@ + +//============================================================================= +/** + * @file Basic_Stats.h + * + * $Id: Basic_Stats.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Carlos O'Ryan + */ +//============================================================================= + + +#ifndef ACE_BASIC_STATS_H +#define ACE_BASIC_STATS_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" +#include "ace/Basic_Types.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/// Collect basic stats about a series of samples +/** + * Compute the average and standard deviation (aka jitter) for an + * arbitrary number of samples, using constant space. + * Normally used for latency statistics. + */ +class ACE_Export ACE_Basic_Stats +{ +public: + /// Constructor + /** + * The number of samples is pre-allocated, and cannot changes once + * the class is initialized. + */ + ACE_Basic_Stats (void); + + /// The number of samples received so far + ACE_UINT32 samples_count (void) const; + + /// Record one sample. + void sample (ACE_UINT64 value); + + /// Update the values to reflect the stats in @a rhs. + void accumulate (const ACE_Basic_Stats &rhs); + + /// Dump all the samples + /** + * Prints out the results, using @a msg as a prefix for each message and + * scaling all the numbers by @a scale_factor. The latter is useful because + * high resolution timer samples are acquired in clock ticks, but often + * presented in microseconds. + */ + void dump_results (const ACE_TCHAR *msg, + ACE_UINT32 scale_factor) const; + + /// The number of samples + ACE_UINT32 samples_count_; + + /// The minimum value + ACE_UINT64 min_; + + /// The number of the sample that had the minimum value + ACE_UINT32 min_at_; + + /// The maximum value + ACE_UINT64 max_; + + /// The number of the sample that had the maximum value + ACE_UINT32 max_at_; + + /// The sum of all the values + ACE_UINT64 sum_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Basic_Stats.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_BASIC_STATS_H */ diff --git a/dep/acelite/ace/Basic_Stats.inl b/dep/acelite/ace/Basic_Stats.inl new file mode 100644 index 00000000000..e2f153884e3 --- /dev/null +++ b/dep/acelite/ace/Basic_Stats.inl @@ -0,0 +1,53 @@ +// -*- C++ -*- +// +// $Id: Basic_Stats.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE +ACE_Basic_Stats::ACE_Basic_Stats (void) + : samples_count_ (0) + , min_ (0) + , min_at_ (0) + , max_ (0) + , max_at_ (0) + , sum_ (0) +{ +} + +ACE_INLINE ACE_UINT32 +ACE_Basic_Stats::samples_count (void) const +{ + return this->samples_count_; +} + +ACE_INLINE void +ACE_Basic_Stats::sample (ACE_UINT64 value) +{ + ++this->samples_count_; + + if (this->samples_count_ == 1u) + { + this->min_ = value; + this->min_at_ = this->samples_count_; + this->max_ = value; + this->max_at_ = this->samples_count_; + } + else + { + if (this->min_ > value) + { + this->min_ = value; + this->min_at_ = this->samples_count_; + } + if (this->max_ < value) + { + this->max_ = value; + this->max_at_ = this->samples_count_; + } + } + + this->sum_ += value; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Basic_Types.cpp b/dep/acelite/ace/Basic_Types.cpp new file mode 100644 index 00000000000..42ae83c0b2a --- /dev/null +++ b/dep/acelite/ace/Basic_Types.cpp @@ -0,0 +1,139 @@ +#include "ace/Basic_Types.h" + +#if !defined (__ACE_INLINE__) +# include "ace/Basic_Types.inl" +#endif /* ! __ACE_INLINE__ */ + + +ACE_RCSID (ace, + Basic_Types, + "$Id: Basic_Types.cpp 80826 2008-03-04 14:51:23Z wotte $") + + +#if defined (ACE_LACKS_LONGLONG_T) && !defined (ACE_LACKS_UNSIGNEDLONGLONG_T) +# include "ace/Log_Msg.h" +# include "ace/OS_NS_stdio.h" +# include "ace/OS_NS_string.h" +# if !defined (ACE_LACKS_IOSTREAM_TOTALLY) +// FUZZ: disable check_for_streams_include +# include "ace/streams.h" +# endif /* ! ACE_LACKS_IOSTREAM_TOTALLY */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +void +ACE_U_LongLong::output (FILE *file) const +{ + if (h_ () > 0) + ACE_OS::fprintf (file, "0x%lx%0*lx", h_ (), 2 * sizeof l_ (), l_ ()); + else + ACE_OS::fprintf (file, "0x%lx", l_ ()); +} + + +ACE_TCHAR * +ACE_U_LongLong::as_string (ACE_TCHAR *output, + unsigned int base, + unsigned int uppercase) const +{ + if (*this == 0) + { + ACE_OS::strcpy(output, "0"); + } + else + { + switch(base) + { + case 8: + { + unsigned int index = 0; + int bshift = 31; + while(bshift >= 1) + { + unsigned int sval = (this->h_ () >> bshift) & 7; + if (sval > 0 || index != 0) + { + output[index] = sval + '0'; + ++index; + } + bshift -= 3; + } + bshift = 30; + while(bshift >= 0) + { + unsigned int sval = (this->l_ () >> bshift) & 7; + // Combine the last bit of hi with the first 3-bit digit + if (bshift == 30) + { + sval |= (this->h_ () & 1) << 2; + } + if (sval > 0 || index != 0) + { + output[index] = sval + '0'; + ++index; + } + bshift -= 3; + } + output[index] = '\0'; + break; + } + case 10: + { + ACE_OS::sprintf(output, "%.0f", *this / 1.0); + break; + } + case 16: + { + if (this->h_ () != 0) + { + ACE_OS::sprintf(output, + (uppercase ? "%lX%0*lX" : "%lx%0*lx"), + this->h_ (), 2 * sizeof this->l_ (), + this->l_ ()); + } + else + { + ACE_OS::sprintf(output, + (uppercase ? "%lX" : "%lx"), this->l_ ()); + + } + break; + } + default: + { + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("Unsupported base = %u\n"), base)); + output[0] = '\0'; + } + } + } + + return output; +} + + +# if !defined (ACE_LACKS_IOSTREAM_TOTALLY) +ostream& +operator<< (ostream& os, const ACE_U_LongLong& ll) +{ +#ifdef __TANDEM && (__CPLUSPLUS_VERSION >= 3) + unsigned long flags = os.flags(); +#else + unsigned long flags = os.setf(0); +#endif + char buffer[32]; + + if ((flags & ios::oct) != 0) + os << ll.as_string (buffer, 8); + else if ((flags & ios::hex) != 0) + os << ll.as_string (buffer, 16, (flags & ios::uppercase)); + else + os << ll.as_string (buffer); + return os; +} +# endif + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_LACKS_LONGLONG_T */ + diff --git a/dep/acelite/ace/Basic_Types.h b/dep/acelite/ace/Basic_Types.h new file mode 100644 index 00000000000..bc467fafb5c --- /dev/null +++ b/dep/acelite/ace/Basic_Types.h @@ -0,0 +1,962 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Basic_Types.h + * + * $Id: Basic_Types.h 91161 2010-07-21 18:25:12Z schmidt $ + * + * @author David L. Levine + * + * #defines the list of preprocessor macros below. The config.h file can + * pre-define any of these to short-cut the definitions. This is usually + * only necessary if the preprocessor does all of its math using integers. + * + * Sizes of built-in types: + * - ACE_SIZEOF_CHAR + * - ACE_SIZEOF_WCHAR + * - ACE_SIZEOF_SHORT + * - ACE_SIZEOF_INT + * - ACE_SIZEOF_LONG + * - ACE_SIZEOF_LONG_LONG + * - ACE_SIZEOF_VOID_P + * - ACE_SIZEOF_FLOAT + * - ACE_SIZEOF_DOUBLE + * - ACE_SIZEOF_LONG_DOUBLE + * + * Wrappers for built-in types of specific sizes: + * - ACE_USHORT16 (For backward compatibility. Use ACE_UINT16 instead.) + * - ACE_INT8 + * - ACE_UINT8 + * - ACE_INT16 + * - ACE_UINT16 + * - ACE_INT32 + * - ACE_UINT32 + * - ACE_UINT64 + * (@note ACE_INT64 is partly defined, there is no ACE_LongLong for + * platforms that don't have a native 8-byte integer type.) + * + * Byte-order (endian-ness) determination: + * ACE_BYTE_ORDER, to either ACE_BIG_ENDIAN or ACE_LITTLE_ENDIAN + * + * + */ +//============================================================================= + +#include "ace/config-lite.h" + +#ifndef ACE_BASIC_TYPES_H +# define ACE_BASIC_TYPES_H + +# include /**/ "ace/pre.h" + +# if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +# endif /* ACE_LACKS_PRAGMA_ONCE */ + +// Pull in definitions +# include "ace/os_include/os_limits.h" // Integer limits +# include "ace/os_include/os_float.h" // Floating point limits +# include "ace/os_include/os_stdlib.h" // Other types +# include "ace/os_include/os_stddef.h" // Get ptrdiff_t - see further comments below + +# if defined(ACE_LACKS_LONGLONG_T) +# include "ace/os_include/os_stdio.h" // For long long emulation +# endif /* ACE_LACKS_LONGLONG_T */ + +# include "ace/os_include/sys/os_types.h" + +# if !defined (ACE_LACKS_SYS_PARAM_H) +# include /**/ +# endif /* ACE_LACKS_SYS_PARAM_H */ + +# include "ace/ACE_export.h" + +# if !defined (ACE_LACKS_STDINT_H) +# include +# endif +# if !defined (ACE_LACKS_INTTYPES_H) +# include +# endif + +#ifdef ACE_LACKS_INTPTR_T +# include "ace/If_Then_Else.h" + +// This intptr_t typedef is here instead of +// since it depends on the template +// metaprogramming in . + +// We could compare ACE_SIZEOF_VOID_P against ACE_SIZEOF_LONG, etc. +// However, that depends on the ACE preprocessor symbol definitions in +// the platform-specific configuration header being correct. +// The template meta-programming approach we take below, +// i.e. determining the type at compile-time rather than at +// preprocessing-time, will work for all platforms, and does not +// depend on ACE developer-defined configuration parameters. + +typedef ACE::If_Then_Else< + (sizeof (void*) == sizeof (signed int)), + signed int, + ACE::If_Then_Else< + (sizeof (void*) == sizeof (signed long)), + signed long, +#ifdef ACE_LACKS_LONGLONG_T + void /* Unknown. Force an invalid type */ +#else + ACE::If_Then_Else< + (sizeof (void*) == sizeof (signed long long)), + signed long long, + void /* Unknown. Force an invalid type */ + >::result_type +#endif /* ACE_LACKS_LONGLONG_T */ + >::result_type + >::result_type intptr_t; + +typedef ACE::If_Then_Else< + (sizeof (void*) == sizeof (unsigned int)), + unsigned int, + ACE::If_Then_Else< + (sizeof (void*) == sizeof (unsigned long)), + unsigned long, +#ifdef ACE_LACKS_UNSIGNEDLONGLONG_T + void /* Unknown. Force an invalid type */ +#else + ACE::If_Then_Else< + (sizeof (void*) == sizeof (unsigned long long)), + unsigned long long, + void /* Unknown. Force an invalid type */ + >::result_type +#endif /* ACE_LACKS_UNSIGNEDLONGLONG_T */ + >::result_type + >::result_type uintptr_t; + +#endif /* ACE_LACKS_INTPTR_T */ + +// A char always has 1 byte, by definition. +# define ACE_SIZEOF_CHAR 1 + +// Unfortunately, there isn't a portable way to determine the size of a wchar. +// So we just define them on a platform basis. If the platform doesn't +// define it and it's an XPG4 system, assume wchar_t is 4 bytes. Some code +// uses ACE_SIZEOF_WCHAR in preprocessor statements, so sizeof() isn't valid. +// If the platform config doesn't set this, and this guess is wrong, +// Basic_Types_Test should catch the inconsistency. +# if defined (ACE_HAS_WCHAR) +# if !defined (ACE_SIZEOF_WCHAR) +# if defined (ACE_HAS_XPG4_MULTIBYTE_CHAR) +# define ACE_SIZEOF_WCHAR 4 +# else +// 0 so the Basic_Types test will catch this. +# define ACE_SIZEOF_WCHAR 0 +# endif /* ACE_HAS_XPG4_MULTIBYTE_CHAR */ +# endif /* !ACE_SIZEOF_WCHAR */ +# endif /* ACE_HAS_WCHAR */ + +// The number of bytes in a short. +# if !defined (ACE_SIZEOF_SHORT) +# if (USHRT_MAX) == 255U +# define ACE_SIZEOF_SHORT 1 +# elif (USHRT_MAX) == 65535U +# define ACE_SIZEOF_SHORT 2 +# elif (USHRT_MAX) == 4294967295U +# define ACE_SIZEOF_SHORT 4 +# elif (USHRT_MAX) == 18446744073709551615U +# define ACE_SIZEOF_SHORT 8 +# else +# error: unsupported short size, must be updated for this platform! +# endif /* USHRT_MAX */ +# endif /* !defined (ACE_SIZEOF_SHORT) */ + +// The number of bytes in an int. +# if !defined (ACE_SIZEOF_INT) +# if (UINT_MAX) == 65535U +# define ACE_SIZEOF_INT 2 +# elif (UINT_MAX) == 4294967295U +# define ACE_SIZEOF_INT 4 +# elif (UINT_MAX) == 18446744073709551615U +# define ACE_SIZEOF_INT 8 +# else +# error: unsupported int size, must be updated for this platform! +# endif /* UINT_MAX */ +# endif /* !defined (ACE_SIZEOF_INT) */ + +// The number of bytes in a long. +# if !defined (ACE_SIZEOF_LONG) +# if (ULONG_MAX) == 65535UL +# define ACE_SIZEOF_LONG 2 +# elif ((ULONG_MAX) == 4294967295UL) +# define ACE_SIZEOF_LONG 4 +# elif ((ULONG_MAX) == 18446744073709551615UL) +# define ACE_SIZEOF_LONG 8 +# else +# error: unsupported long size, must be updated for this platform! +# endif /* ULONG_MAX */ +# endif /* !defined (ACE_SIZEOF_LONG) */ + +// The number of bytes in a long long. +# if !defined (ACE_SIZEOF_LONG_LONG) +# if defined (ACE_LACKS_LONGLONG_T) +# define ACE_SIZEOF_LONG_LONG 8 +# elif defined (ULLONG_MAX) +# if ((ULLONG_MAX) == 4294967295ULL) +# define ACE_SIZEOF_LONG_LONG 4 +# elif ((ULLONG_MAX) == 18446744073709551615ULL) +# define ACE_SIZEOF_LONG_LONG 8 +# endif +# elif defined (ULONGLONG_MAX) +# if ((ULONGLONG_MAX) == 4294967295ULL) +# define ACE_SIZEOF_LONG_LONG 4 +# elif ((ULONGLONG_MAX) == 18446744073709551615ULL) +# define ACE_SIZEOF_LONG_LONG 8 +# endif +# endif +# // If we can't determine the size of long long, assume it is 8 +# // instead of erroring out. (Either ULLONG_MAX and ULONGLONG_MAX +# // may not be supported; or an extended C/C++ dialect may need to +# // be selected. If this assumption is wrong, it can be addressed +# // in the platform-specific config header. +# if !defined (ACE_SIZEOF_LONG_LONG) +# define ACE_SIZEOF_LONG_LONG 8 +# endif +# endif /* !defined (ACE_SIZEOF_LONG_LONG) */ + + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// The sizes of the commonly implemented types are now known. Set up +// typedefs for whatever we can. Some of these are needed for certain +// cases of ACE_UINT64, so do them before the 64-bit stuff. + +#if defined (ACE_INT8_TYPE) + typedef ACE_INT8_TYPE ACE_INT8; +#elif defined (ACE_HAS_INT8_T) + typedef int8_t ACE_INT8; +#elif !defined (ACE_LACKS_SIGNED_CHAR) + typedef signed char ACE_INT8; +#else + typedef char ACE_INT8; +#endif /* defined (ACE_INT8_TYPE) */ + +#if defined (ACE_UINT8_TYPE) + typedef ACE_UINT8_TYPE ACE_UINT8; +#elif defined (ACE_HAS_UINT8_T) + typedef uint8_t ACE_UINT8; +#else + typedef unsigned char ACE_UINT8; +#endif /* defined (ACE_UINT8_TYPE) */ + +#if defined (ACE_INT16_TYPE) + typedef ACE_INT16_TYPE ACE_INT16; +#elif defined (ACE_HAS_INT16_T) + typedef int16_t ACE_INT16; +#elif ACE_SIZEOF_SHORT == 2 + typedef short ACE_INT16; +#elif ACE_SIZEOF_INT == 2 + typedef int ACE_INT16; +#else +# error Have to add to the ACE_INT16 type setting +#endif /* defined (ACE_INT16_TYPE) */ + +#if defined (ACE_UINT16_TYPE) + typedef ACE_UINT16_TYPE ACE_UINT16; +#elif defined (ACE_HAS_UINT16_T) + typedef uint16_t ACE_UINT16; +#elif ACE_SIZEOF_SHORT == 2 + typedef unsigned short ACE_UINT16; +#elif ACE_SIZEOF_INT == 2 + typedef unsigned int ACE_UINT16; +#else +# error Have to add to the ACE_UINT16 type setting +#endif /* defined (ACE_UINT16_TYPE) */ + +#if defined (ACE_INT32_TYPE) + typedef ACE_INT32_TYPE ACE_INT32; +#elif defined (ACE_HAS_INT32_T) + typedef int32_t ACE_INT32; +#elif ACE_SIZEOF_INT == 4 + typedef int ACE_INT32; +#elif ACE_SIZEOF_LONG == 4 + typedef long ACE_INT32; +#else +# error Have to add to the ACE_INT32 type setting +#endif /* defined (ACE_INT32_TYPE) */ + +#if defined (ACE_UINT32_TYPE) + typedef ACE_UINT32_TYPE ACE_UINT32; +#elif defined (ACE_HAS_UINT32_T) + typedef uint32_t ACE_UINT32; +#elif ACE_SIZEOF_INT == 4 + typedef unsigned int ACE_UINT32; +#elif ACE_SIZEOF_LONG == 4 + typedef unsigned long ACE_UINT32; +#else +# error Have to add to the ACE_UINT32 type setting +#endif /* defined (ACE_UINT32_TYPE) */ + +#if defined (ACE_INT64_TYPE) + typedef ACE_INT64_TYPE ACE_INT64; +#elif defined (ACE_HAS_INT64_T) + typedef int64_t ACE_INT64; +#elif ACE_SIZEOF_LONG == 8 + typedef long ACE_INT64; +#elif !defined (ACE_LACKS_LONGLONG_T) && ACE_SIZEOF_LONG_LONG == 8 +# ifdef __GNUC__ + // Silence g++ "-pedantic" warnings regarding use of "long long" + // type. + __extension__ +# endif /* __GNUC__ */ + typedef long long ACE_INT64; +#endif /* defined (ACE_INT64_TYPE) */ + +#if !(defined (ACE_LACKS_LONGLONG_T) || defined (ACE_LACKS_UNSIGNEDLONGLONG_T)) +/* See matching #if around ACE_U_LongLong class declaration below */ + +# if defined (ACE_UINT64_TYPE) + typedef ACE_UINT64_TYPE ACE_UINT64; +# elif defined (ACE_HAS_UINT64_T) + typedef uint64_t ACE_UINT64; +# elif ACE_SIZEOF_LONG == 8 + typedef unsigned long ACE_UINT64; +# elif ACE_SIZEOF_LONG_LONG == 8 +# ifdef __GNUC__ + // Silence g++ "-pedantic" warnings regarding use of "long long" + // type. + __extension__ +# endif /* __GNUC__ */ + typedef unsigned long long ACE_UINT64; +# endif /* defined (ACE_UINT64_TYPE) */ +#endif /* !(ACE_LACKS_LONGLONG_T || ACE_LACKS_UNSIGNEDLONGLONG_T) */ + + +typedef ACE_UINT16 ACE_USHORT16; // @@ Backward compatibility. + +// Define a generic byte for use in codecs +typedef unsigned char ACE_Byte; + +// Define a pseudo wide character type when wchar is not supported so we +// can support basic wide character string operations. + +# if defined (ACE_HAS_WCHAR) || defined (ACE_HAS_XPG4_MULTIBYTE_CHAR) +# define ACE_WINT_T wint_t +# define ACE_WCHAR_T wchar_t +# else +# define ACE_WINT_T ACE_UINT16 +# define ACE_WCHAR_T ACE_UINT16 +# endif /* ACE_HAS_WCHAR */ + +// The number of bytes in a void *. +# ifndef ACE_SIZEOF_VOID_P +# define ACE_SIZEOF_VOID_P ACE_SIZEOF_LONG +# endif /* ACE_SIZEOF_VOID_P */ + +ACE_END_VERSIONED_NAMESPACE_DECL + +// Byte-order (endian-ness) determination. +# if defined (BYTE_ORDER) +# if (BYTE_ORDER == LITTLE_ENDIAN) +# define ACE_LITTLE_ENDIAN 0x0123 +# define ACE_BYTE_ORDER ACE_LITTLE_ENDIAN +# elif (BYTE_ORDER == BIG_ENDIAN) +# define ACE_BIG_ENDIAN 0x3210 +# define ACE_BYTE_ORDER ACE_BIG_ENDIAN +# else +# error: unknown BYTE_ORDER! +# endif /* BYTE_ORDER */ +# elif defined (_BYTE_ORDER) +# if (_BYTE_ORDER == _LITTLE_ENDIAN) +# define ACE_LITTLE_ENDIAN 0x0123 +# define ACE_BYTE_ORDER ACE_LITTLE_ENDIAN +# elif (_BYTE_ORDER == _BIG_ENDIAN) +# define ACE_BIG_ENDIAN 0x3210 +# define ACE_BYTE_ORDER ACE_BIG_ENDIAN +# else +# error: unknown _BYTE_ORDER! +# endif /* _BYTE_ORDER */ +# elif defined (__BYTE_ORDER) +# if (__BYTE_ORDER == __LITTLE_ENDIAN) +# define ACE_LITTLE_ENDIAN 0x0123 +# define ACE_BYTE_ORDER ACE_LITTLE_ENDIAN +# elif (__BYTE_ORDER == __BIG_ENDIAN) +# define ACE_BIG_ENDIAN 0x3210 +# define ACE_BYTE_ORDER ACE_BIG_ENDIAN +# else +# error: unknown __BYTE_ORDER! +# endif /* __BYTE_ORDER */ +# else /* ! BYTE_ORDER && ! __BYTE_ORDER */ + // We weren't explicitly told, so we have to figure it out . . . + // Note that Itanium hardware (IA64) can run in either byte order. It's + // selected by the OS when loading; Windows runs little, HP-UX runs big. +# if defined (i386) || defined (__i386__) || defined (_M_IX86) || \ + defined (vax) || defined (__alpha) || defined (__LITTLE_ENDIAN__) || \ + defined (ARM) || defined (_M_IA64) || defined (_M_AMD64) || \ + defined (__amd64) || \ + ((defined (__ia64__) || defined (__ia64)) && !defined (__hpux)) + // We know these are little endian. +# define ACE_LITTLE_ENDIAN 0x0123 +# define ACE_BYTE_ORDER ACE_LITTLE_ENDIAN +# else + // Otherwise, we assume big endian. +# define ACE_BIG_ENDIAN 0x3210 +# define ACE_BYTE_ORDER ACE_BIG_ENDIAN +# endif +# endif /* ! BYTE_ORDER && ! __BYTE_ORDER */ + +// Byte swapping macros to deal with differences between little endian +// and big endian machines. Note that "long" here refers to 32 bit +// quantities. +# define ACE_SWAP_LONG(L) ((ACE_SWAP_WORD ((L) & 0xFFFF) << 16) \ + | ACE_SWAP_WORD(((L) >> 16) & 0xFFFF)) +# define ACE_SWAP_WORD(L) ((((L) & 0x00FF) << 8) | (((L) & 0xFF00) >> 8)) + +# if defined (ACE_LITTLE_ENDIAN) +# define ACE_HTONL(X) ACE_SWAP_LONG (X) +# define ACE_NTOHL(X) ACE_SWAP_LONG (X) +# define ACE_IDL_NCTOHL(X) (X) +# define ACE_IDL_NSTOHL(X) (X) +# else +# define ACE_HTONL(X) X +# define ACE_NTOHL(X) X +# define ACE_IDL_NCTOHL(X) (X << 24) +# define ACE_IDL_NSTOHL(X) ((X) << 16) +# endif /* ACE_LITTLE_ENDIAN */ + +# if defined (ACE_LITTLE_ENDIAN) +# define ACE_HTONS(x) ACE_SWAP_WORD(x) +# define ACE_NTOHS(x) ACE_SWAP_WORD(x) +# else +# define ACE_HTONS(x) x +# define ACE_NTOHS(x) x +# endif /* ACE_LITTLE_ENDIAN */ + +#if defined (ACE_LACKS_LONGLONG_T) + // This throws away the high 32 bits. It's very unlikely that a + // pointer will be more than 32 bits wide if the platform does not + // support 64-bit integers. +# define ACE_LONGLONG_TO_PTR(PTR_TYPE, L) \ + reinterpret_cast (L.lo ()) +#elif defined (ACE_OPENVMS) && (!defined (__INITIAL_POINTER_SIZE) || (__INITIAL_POINTER_SIZE < 64)) +# define ACE_LONGLONG_TO_PTR(PTR_TYPE, L) \ + reinterpret_cast (static_cast (L)) +#else /* ! ACE_LACKS_LONGLONG_T */ +# define ACE_LONGLONG_TO_PTR(PTR_TYPE, L) \ + reinterpret_cast (static_cast (L)) +#endif /* ! ACE_LACKS_LONGLONG_T */ + +// If the platform lacks an unsigned long long, define one. +#if defined (ACE_LACKS_LONGLONG_T) || defined (ACE_LACKS_UNSIGNEDLONGLONG_T) +// Forward declaration for streams +# include "ace/iosfwd.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_U_LongLong + * + * @brief Unsigned long long for platforms that don't have one. + * + * Provide our own unsigned long long. This is intended to be + * use with ACE_High_Res_Timer, so the division operator assumes + * that the quotient fits into a u_long. + * Please note that the constructor takes (optionally) two values. + * The high one contributes 0x100000000 times its value. So, + * for example, (0, 2) is _not_ 20000000000, but instead + * 0x200000000. To emphasize this, the default values are expressed + * in hex, and output () dumps the value in hex. + */ + class ACE_Export ACE_U_LongLong + { + public: + // = Initialization and termination methods. +#if defined (ACE_LACKS_UNSIGNEDLONGLONG_T) + ACE_U_LongLong (const long long value = 0x0); +#else + ACE_U_LongLong (const ACE_UINT32 lo = 0x0, const ACE_UINT32 hi = 0x0); +#endif + ACE_U_LongLong (const ACE_U_LongLong &); + ACE_U_LongLong &operator= (const ACE_U_LongLong &); + ACE_U_LongLong &operator= (const ACE_INT32 &); + ACE_U_LongLong &operator= (const ACE_UINT32 &); + ~ACE_U_LongLong (void); + + // = Overloaded relation operators. + bool operator== (const ACE_U_LongLong &) const; + bool operator== (const ACE_UINT32) const; + bool operator!= (const ACE_U_LongLong &) const; + bool operator!= (const ACE_UINT32) const; + bool operator< (const ACE_U_LongLong &) const; + bool operator< (const ACE_UINT32) const; + bool operator<= (const ACE_U_LongLong &) const; + bool operator<= (const ACE_UINT32) const; + bool operator> (const ACE_U_LongLong &) const; + bool operator> (const ACE_UINT32) const; + bool operator>= (const ACE_U_LongLong &) const; + bool operator>= (const ACE_UINT32) const; + + ACE_U_LongLong operator+ (const ACE_U_LongLong &) const; + ACE_U_LongLong operator+ (const ACE_UINT32) const; + ACE_U_LongLong operator- (const ACE_U_LongLong &) const; + ACE_U_LongLong operator- (const ACE_UINT32) const; + ACE_U_LongLong operator* (const ACE_UINT32) const; + ACE_U_LongLong &operator*= (const ACE_UINT32); + + ACE_U_LongLong operator<< (const unsigned int) const; + ACE_U_LongLong &operator<<= (const unsigned int); + ACE_U_LongLong operator>> (const unsigned int) const; + ACE_U_LongLong &operator>>= (const unsigned int); + + double operator/ (const double) const; + + ACE_U_LongLong &operator+= (const ACE_U_LongLong &); + ACE_U_LongLong &operator+= (const ACE_UINT32); + ACE_U_LongLong &operator-= (const ACE_U_LongLong &); + ACE_U_LongLong &operator-= (const ACE_UINT32); + ACE_U_LongLong &operator++ (); + ACE_U_LongLong &operator-- (); + const ACE_U_LongLong operator++ (int); + const ACE_U_LongLong operator-- (int); + ACE_U_LongLong &operator|= (const ACE_U_LongLong); + ACE_U_LongLong &operator|= (const ACE_UINT32); + ACE_U_LongLong &operator&= (const ACE_U_LongLong); + ACE_U_LongLong &operator&= (const ACE_UINT32); + + // Note that the following take ACE_UINT32 arguments. These are + // typical use cases, and easy to implement. But, they limit the + // return values to 32 bits as well. There are no checks for + // overflow. + ACE_UINT32 operator/ (const ACE_UINT32) const; + ACE_UINT32 operator% (const ACE_UINT32) const; + + // The following only operate on the lower 32 bits (they take only + // 32 bit arguments). + ACE_UINT32 operator| (const ACE_INT32) const; + ACE_UINT32 operator& (const ACE_INT32) const; + + // The following operators convert their arguments to + // ACE_UINT32. So, there may be information loss if they are + // used. + ACE_U_LongLong operator* (const ACE_INT32) const; + ACE_U_LongLong &operator*= (const ACE_INT32); + ACE_UINT32 operator/ (const ACE_INT32) const; +# if ACE_SIZEOF_INT == 4 + ACE_UINT32 operator/ (const unsigned long) const; + ACE_UINT32 operator/ (const long) const; +# else /* ACE_SIZEOF_INT != 4 */ + ACE_UINT32 operator/ (const unsigned int) const; + ACE_UINT32 operator/ (const int) const; +# endif /* ACE_SIZEOF_INT != 4 */ + + // = Helper methods. + /// Outputs the value to the FILE, in hex. + void output (FILE * = stdout) const; + + ACE_TCHAR *as_string (ACE_TCHAR *string, + unsigned int base = 10, + unsigned int uppercase = 0) const; + + ACE_UINT32 hi (void) const; + ACE_UINT32 lo (void) const; + + void hi (const ACE_UINT32 hi); + void lo (const ACE_UINT32 lo); + +#if defined (ACE_LACKS_UNSIGNEDLONGLONG_T) + long long to_int64 (void) const; +# endif + + private: + +#if defined (ACE_LACKS_UNSIGNEDLONGLONG_T) + long long data_; +#else + public: + struct ace_hi_lo_correct_endian + { +# if defined (ACE_BIG_ENDIAN) + /// High 32 bits. + ACE_UINT32 hi_; + /// Low 32 bits. + ACE_UINT32 lo_; + +# else + + /// Low 32 bits. + ACE_UINT32 lo_; + /// High 32 bits. + ACE_UINT32 hi_; +# endif /* ! ACE_BIG_ENDIAN */ + }; + private: + union + { + struct ace_hi_lo_correct_endian data_; + + /// To ensure alignment on 8-byte boundary. + double for_alignment_; + }; + + // @note the following four accessors are inlined here in + // order to minimize the extent of the data_ struct. It's + // only used here; the .i and .cpp files use the accessors. + + /// Internal utility function to hide access through struct. + const ACE_UINT32 &h_ () const { return data_.hi_; } + + /// Internal utility function to hide access through struct. + ACE_UINT32 &h_ () { return data_.hi_; } + + /// Internal utility function to hide access through struct. + const ACE_UINT32 &l_ () const { return data_.lo_; } + + /// Internal utility function to hide access through struct. + ACE_UINT32 &l_ () { return data_.lo_; } + + // @note the above four accessors are inlined here in + // order to minimize the extent of the data_ struct. It's + // only used here; the .inl and .cpp files use the accessors. + + /// These functions are used to implement multiplication. + ACE_UINT32 ul_shift (ACE_UINT32 a, + ACE_UINT32 c_in, + ACE_UINT32 *c_out) const; + ACE_U_LongLong ull_shift (ACE_U_LongLong a, + ACE_UINT32 c_in, + ACE_UINT32 *c_out) const; + ACE_U_LongLong ull_add (ACE_U_LongLong a, + ACE_U_LongLong b, + ACE_UINT32 *carry) const; + ACE_U_LongLong ull_mult (ACE_U_LongLong a, + ACE_UINT32 b, + ACE_UINT32 *carry) const; +#endif // ACE_LACKS_UNSIGNEDLONGLONG_T + }; + + typedef ACE_U_LongLong ACE_UINT64; + +#if !defined (ACE_LACKS_IOSTREAM_TOTALLY) + ostream &operator<< (ostream &, const ACE_U_LongLong &); +#endif /* ! ACE_LACKS_IOSTREAM_TOTALLY */ + +ACE_END_VERSIONED_NAMESPACE_DECL + +# endif /* ACE_LACKS_LONGLONG_T */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Conversions from ACE_UINT64 to ACE_UINT32. ACE_CU64_TO_CU32 should +// be used on const ACE_UINT64's. +# if defined (ACE_LACKS_LONGLONG_T) || defined (ACE_LACKS_UNSIGNEDLONGLONG_T) +inline ACE_UINT32 +ACE_U64_TO_U32 (ACE_U_LongLong const & n) +{ + /** + * @note We could add a cast operator to ACE_U_LongLong but that may + * cause more problems than it solves. Force users to perform + * an explicit cast via ACE_{C}U64_TO_{C}U32. + */ + return n.lo (); +} + +inline ACE_UINT32 +ACE_CU64_TO_CU32 (ACE_U_LongLong const & n) +{ + return ACE_U64_TO_U32 (n); +} +# else /* ! ACE_LACKS_LONGLONG_T */ +inline ACE_UINT32 +ACE_U64_TO_U32 (ACE_UINT64 n) +{ + return static_cast (n); +} + +inline ACE_UINT32 +ACE_CU64_TO_CU32 (ACE_UINT64 n) +{ + return static_cast (n); +} +# endif /* ! ACE_LACKS_LONGLONG_T */ + +ACE_END_VERSIONED_NAMESPACE_DECL + +// 64-bit literals require special marking on some platforms. +# if defined (ACE_LACKS_LONGLONG_T) + // Can only specify 32-bit arguments. +# define ACE_UINT64_LITERAL(n) n ## UL + // This one won't really work, but it'll keep + // some compilers happy until we have better support +# define ACE_INT64_LITERAL(n) n ## L +# elif defined (ACE_WIN32) +# if defined (__MINGW32__) +# define ACE_UINT64_LITERAL(n) n ## ull +# define ACE_INT64_LITERAL(n) n ## ll +# else +# define ACE_UINT64_LITERAL(n) n ## ui64 +# define ACE_INT64_LITERAL(n) n ## i64 +# endif /* defined (__MINGW32__) */ +# elif defined (__TANDEM) +# define ACE_UINT64_LITERAL(n) n ## LL +# define ACE_INT64_LITERAL(n) n ## LL +# else /* ! ACE_WIN32 && ! ACE_LACKS_LONGLONG_T */ +# define ACE_UINT64_LITERAL(n) n ## ull +# define ACE_INT64_LITERAL(n) n ## ll +# endif /* ! ACE_WIN32 && ! ACE_LACKS_LONGLONG_T */ + +#if !defined (ACE_INT8_FORMAT_SPECIFIER_ASCII) +# if defined (PRId8) +# define ACE_INT8_FORMAT_SPECIFIER_ASCII "%" PRId8 +# else +# define ACE_INT8_FORMAT_SPECIFIER_ASCII "%d" +# endif /* defined (PRId8) */ +#endif /* ACE_INT8_FORMAT_SPECIFIER_ASCII */ + +#if !defined (ACE_INT8_FORMAT_SPECIFIER) +# if defined (PRId8) +# define ACE_INT8_FORMAT_SPECIFIER ACE_TEXT ("%") ACE_TEXT (PRId8) +# else +# define ACE_INT8_FORMAT_SPECIFIER ACE_TEXT (ACE_INT8_FORMAT_SPECIFIER_ASCII) +# endif /* defined (PRId8) */ +#endif /* ACE_INT8_FORMAT_SPECIFIER */ + +#if !defined (ACE_UINT8_FORMAT_SPECIFIER_ASCII) +# if defined (PRIu8) +# define ACE_UINT8_FORMAT_SPECIFIER_ASCII "%" PRIu8 +# else +# define ACE_UINT8_FORMAT_SPECIFIER_ASCII "%u" +# endif /* defined (PRIu8) */ +#endif /* ACE_UINT8_FORMAT_SPECIFIER */ + +#if !defined (ACE_UINT8_FORMAT_SPECIFIER) +# if defined (PRIu8) +# define ACE_UINT8_FORMAT_SPECIFIER ACE_TEXT ("%") ACE_TEXT (PRIu8) +# else +# define ACE_UINT8_FORMAT_SPECIFIER ACE_TEXT (ACE_UINT8_FORMAT_SPECIFIER_ASCII) +# endif /* defined (PRIu8) */ +#endif /* ACE_UINT8_FORMAT_SPECIFIER */ + +#if !defined (ACE_INT16_FORMAT_SPECIFIER_ASCII) +# if defined (PRId16) +# define ACE_INT16_FORMAT_SPECIFIER_ASCII "%" PRId16 +# else +# define ACE_INT16_FORMAT_SPECIFIER_ASCII "%d" +# endif /* defined (PRId16) */ +#endif /* ACE_INT16_FORMAT_SPECIFIER */ + +#if !defined (ACE_INT16_FORMAT_SPECIFIER) +# if defined (PRId16) +# define ACE_INT16_FORMAT_SPECIFIER ACE_TEXT ("%") ACE_TEXT (PRId16) +# else +# define ACE_INT16_FORMAT_SPECIFIER ACE_TEXT (ACE_INT16_FORMAT_SPECIFIER_ASCII) +# endif /* defined (PRId16) */ +#endif /* ACE_INT16_FORMAT_SPECIFIER */ + +#if !defined (ACE_UINT16_FORMAT_SPECIFIER_ASCII) +# if defined (PRIu16) +# define ACE_UINT16_FORMAT_SPECIFIER_ASCII "%" PRIu16 +# else +# define ACE_UINT16_FORMAT_SPECIFIER_ASCII "%u" +# endif /* defined (PRIu16) */ +#endif /* ACE_UINT16_FORMAT_SPECIFIER */ + +#if !defined (ACE_UINT16_FORMAT_SPECIFIER) +# if defined (PRIu16) +# define ACE_UINT16_FORMAT_SPECIFIER ACE_TEXT ("%") ACE_TEXT (PRIu16) +# else +# define ACE_UINT16_FORMAT_SPECIFIER ACE_TEXT (ACE_UINT16_FORMAT_SPECIFIER_ASCII) +# endif /* defined (PRIu16) */ +#endif /* ACE_UINT16_FORMAT_SPECIFIER */ + +#if !defined (ACE_INT32_FORMAT_SPECIFIER_ASCII) +# if defined (PRId32) +# define ACE_INT32_FORMAT_SPECIFIER_ASCII "%" PRId32 +# elif ACE_SIZEOF_INT == 4 +# define ACE_INT32_FORMAT_SPECIFIER_ASCII "%d" +# else +# define ACE_INT32_FORMAT_SPECIFIER_ASCII "%ld" +# endif /* defined (PRId32) */ +#endif /* ACE_INT32_FORMAT_SPECIFIER */ + +#if !defined (ACE_INT32_FORMAT_SPECIFIER) +# if defined (PRId32) +# define ACE_INT32_FORMAT_SPECIFIER ACE_TEXT ("%") ACE_TEXT (PRId32) +# else +# define ACE_INT32_FORMAT_SPECIFIER ACE_TEXT (ACE_INT32_FORMAT_SPECIFIER_ASCII) +# endif /* defined (PRId32) */ +#endif /* ACE_INT32_FORMAT_SPECIFIER */ + +#if !defined (ACE_UINT32_FORMAT_SPECIFIER_ASCII) +# if defined (PRIu32) +# define ACE_UINT32_FORMAT_SPECIFIER_ASCII "%" PRIu32 +# elif ACE_SIZEOF_INT == 4 +# define ACE_UINT32_FORMAT_SPECIFIER_ASCII "%u" +# else +# define ACE_UINT32_FORMAT_SPECIFIER_ASCII "%lu" +# endif /* defined (PRIu32) */ +#endif /* ACE_UINT32_FORMAT_SPECIFIER */ + +#if !defined (ACE_UINT32_FORMAT_SPECIFIER) +# if defined (PRIu32) +# define ACE_UINT32_FORMAT_SPECIFIER ACE_TEXT ("%") ACE_TEXT (PRIu32) +# else +# define ACE_UINT32_FORMAT_SPECIFIER ACE_TEXT (ACE_UINT32_FORMAT_SPECIFIER_ASCII) +# endif /* defined (PRIu32) */ +#endif /* ACE_UINT32_FORMAT_SPECIFIER */ + +#if !defined (ACE_INT64_FORMAT_SPECIFIER_ASCII) +# if defined (PRId64) +# define ACE_INT64_FORMAT_SPECIFIER_ASCII "%" PRId64 +# elif ACE_SIZEOF_LONG == 8 +# define ACE_INT64_FORMAT_SPECIFIER_ASCII "%ld" +# else +# define ACE_INT64_FORMAT_SPECIFIER_ASCII "%lld" +# endif /* defined (PRId64) */ +#endif /* ACE_INT64_FORMAT_SPECIFIER */ + +#if !defined (ACE_INT64_FORMAT_SPECIFIER) +# if defined (PRId64) +# define ACE_INT64_FORMAT_SPECIFIER ACE_TEXT ("%") ACE_TEXT (PRId64) +# else +# define ACE_INT64_FORMAT_SPECIFIER ACE_TEXT (ACE_INT64_FORMAT_SPECIFIER_ASCII) +# endif /* defined (PRId64) */ +#endif /* ACE_INT64_FORMAT_SPECIFIER */ + +#if !defined (ACE_UINT64_FORMAT_SPECIFIER_ASCII) +# if defined (PRIu64) +# define ACE_UINT64_FORMAT_SPECIFIER_ASCII "%" PRIu64 +# elif ACE_SIZEOF_LONG == 8 +# define ACE_UINT64_FORMAT_SPECIFIER_ASCII "%lu" +# else +# define ACE_UINT64_FORMAT_SPECIFIER_ASCII "%llu" +# endif /* defined (PRIu64) */ +#endif /* ACE_UINT64_FORMAT_SPECIFIER_ASCII */ + +#if !defined (ACE_UINT64_FORMAT_SPECIFIER) +# if defined (PRIu64) +# define ACE_UINT64_FORMAT_SPECIFIER ACE_TEXT ("%") ACE_TEXT (PRIu64) +# else +# define ACE_UINT64_FORMAT_SPECIFIER ACE_TEXT (ACE_UINT64_FORMAT_SPECIFIER_ASCII) +# endif /* defined (PRIu64) */ +#endif /* ACE_UINT64_FORMAT_SPECIFIER */ + +#if !defined (ACE_SSIZE_T_FORMAT_SPECIFIER_ASCII) +# if defined (ACE_WIN64) +# define ACE_SSIZE_T_FORMAT_SPECIFIER_ASCII "%I64d" +# else +# define ACE_SSIZE_T_FORMAT_SPECIFIER_ASCII "%d" +# endif /* ACE_WIN64 */ +#endif /* ACE_SSIZE_T_FORMAT_SPECIFIER */ + +#if !defined (ACE_SSIZE_T_FORMAT_SPECIFIER) +#define ACE_SSIZE_T_FORMAT_SPECIFIER ACE_TEXT (ACE_SSIZE_T_FORMAT_SPECIFIER_ASCII) +#endif /* ACE_SSIZE_T_FORMAT_SPECIFIER */ + +#if !defined (ACE_SIZE_T_FORMAT_SPECIFIER_ASCII) +# if defined (ACE_WIN64) +# define ACE_SIZE_T_FORMAT_SPECIFIER_ASCII "%I64u" +# else +# define ACE_SIZE_T_FORMAT_SPECIFIER_ASCII "%u" +# endif /* ACE_WIN64 */ +#endif /* ACE_SIZE_T_FORMAT_SPECIFIER */ + +#if !defined (ACE_SIZE_T_FORMAT_SPECIFIER) +#define ACE_SIZE_T_FORMAT_SPECIFIER ACE_TEXT (ACE_SIZE_T_FORMAT_SPECIFIER_ASCII) +#endif /* ACE_SIZE_T_FORMAT_SPECIFIER */ + +// Cast from UINT64 to a double requires an intermediate cast to INT64 +// on some platforms. +# if defined (ACE_LACKS_LONGLONG_T) + // Only use the low 32 bits. +# define ACE_UINT64_DBLCAST_ADAPTER(n) ACE_U64_TO_U32 (n) +# elif defined (ACE_LACKS_UNSIGNEDLONGLONG_T) +# define ACE_UINT64_DBLCAST_ADAPTER(n) ((n).to_int64 ()) +# elif defined (ACE_WIN32) +# define ACE_UINT64_DBLCAST_ADAPTER(n) static_cast<__int64> (n) +# else /* ! ACE_WIN32 && ! ACE_LACKS_LONGLONG_T */ +# define ACE_UINT64_DBLCAST_ADAPTER(n) (n) +# endif /* ! ACE_WIN32 && ! ACE_LACKS_LONGLONG_T */ + + +// The number of bytes in a float. +# ifndef ACE_SIZEOF_FLOAT +# if FLT_MAX_EXP == 128 +# define ACE_SIZEOF_FLOAT 4 +# elif FLT_MAX_EXP == 1024 +# define ACE_SIZEOF_FLOAT 8 +# else +# error: unsupported float size, must be updated for this platform! +# endif /* FLT_MAX_EXP */ +# endif /* ACE_SIZEOF_FLOAT */ + +// The number of bytes in a double. +# ifndef ACE_SIZEOF_DOUBLE +# if DBL_MAX_EXP == 128 +# define ACE_SIZEOF_DOUBLE 4 +# elif DBL_MAX_EXP == 1024 +# define ACE_SIZEOF_DOUBLE 8 +# else +# error: unsupported double size, must be updated for this platform! +# endif /* DBL_MAX_EXP */ +# endif /* ACE_SIZEOF_DOUBLE */ + +// The number of bytes in a long double. +# ifndef ACE_SIZEOF_LONG_DOUBLE +# if LDBL_MAX_EXP == 128 +# define ACE_SIZEOF_LONG_DOUBLE 4 +# elif LDBL_MAX_EXP == 1024 +# if defined (__powerpc64__) +# define ACE_SIZEOF_LONG_DOUBLE 16 +# else +# define ACE_SIZEOF_LONG_DOUBLE 8 +# endif +# elif LDBL_MAX_EXP == 16384 +# if defined (LDBL_DIG) && LDBL_DIG == 18 +# if defined (__ia64) || defined (__x86_64) +# define ACE_SIZEOF_LONG_DOUBLE 16 +# else /* ! __ia64 || __x86_64 */ +# define ACE_SIZEOF_LONG_DOUBLE 12 +# endif /* __ia64 */ +# else /* ! LDBL_DIG || LDBL_DIG != 18 */ +# define ACE_SIZEOF_LONG_DOUBLE 16 +# endif /* ! LDBL_DIG || LDBL_DIG != 18 */ +# else +# error: unsupported double size, must be updated for this platform! +# endif /* LDBL_MAX_EXP */ +# endif /* ACE_SIZEOF_LONG_DOUBLE */ + +// Max and min sizes for the ACE integer types. +#define ACE_CHAR_MAX 0x7F +#define ACE_CHAR_MIN -(ACE_CHAR_MAX)-1 +#define ACE_OCTET_MAX 0xFF +#define ACE_INT16_MAX 0x7FFF +#define ACE_INT16_MIN -(ACE_INT16_MAX)-1 +#define ACE_UINT16_MAX 0xFFFF +#define ACE_WCHAR_MAX ACE_UINT16_MAX +#define ACE_INT32_MAX 0x7FFFFFFF +#define ACE_INT32_MIN -(ACE_INT32_MAX)-1 +#define ACE_UINT32_MAX 0xFFFFFFFF +#define ACE_INT64_MAX ACE_INT64_LITERAL(0x7FFFFFFFFFFFFFFF) +#define ACE_INT64_MIN -(ACE_INT64_MAX)-1 + +#if defined (ACE_LACKS_UNSIGNEDLONGLONG_T) +// ACE_U_LongLong's constructor accepts a "long long" in this +// case. Set it to ACE_U_LongLong (-1) since the bit pattern for long +// long (-1) is the same as the maximum unsigned long long value. +# define ACE_UINT64_MAX ACE_U_LongLong (ACE_INT64_LITERAL (0xFFFFFFFFFFFFFFFF)) +#elif defined (ACE_LACKS_LONGLONG_T) +// ACE_U_LongLong's constructor accepts an ACE_UINT32 low and high +// pair of parameters. +# define ACE_UINT64_MAX ACE_U_LongLong (0xFFFFFFFFu, 0xFFFFFFFFu) +#else +# define ACE_UINT64_MAX ACE_UINT64_LITERAL (0xFFFFFFFFFFFFFFFF) +#endif /* ACE_LACKS_UNSIGNEDLONGLONG_T */ + +// These use ANSI/IEEE format. +#define ACE_FLT_MAX 3.402823466e+38F +#define ACE_FLT_MIN 1.175494351e-38F +#define ACE_DBL_MAX 1.7976931348623158e+308 +#define ACE_DBL_MIN 2.2250738585072014e-308 + +# if defined (__ACE_INLINE__) +# include "ace/Basic_Types.inl" +# endif /* __ACE_INLINE__ */ + +# include /**/ "ace/post.h" +#endif /* ACE_BASIC_TYPES_H */ diff --git a/dep/acelite/ace/Basic_Types.inl b/dep/acelite/ace/Basic_Types.inl new file mode 100644 index 00000000000..c6f0013d45e --- /dev/null +++ b/dep/acelite/ace/Basic_Types.inl @@ -0,0 +1,954 @@ +// -*- C++ -*- +// +// $Id: Basic_Types.inl 80826 2008-03-04 14:51:23Z wotte $ + +# if !defined (ACE_LACKS_LONGLONG_T) && defined (ACE_LACKS_UNSIGNEDLONGLONG_T) + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Implementation for ACE_U_LongLong when we have signed long long +// but no unsigned long long. + +ACE_INLINE +ACE_U_LongLong::ACE_U_LongLong (const long long value) + : data_ (value) +{ +} + +ACE_INLINE ACE_UINT32 +ACE_U_LongLong::hi (void) const +{ + return (data_ >> 32) & 0xFFFFFFFF; +} + +ACE_INLINE ACE_UINT32 +ACE_U_LongLong::lo (void) const +{ + return data_ & 0xFFFFFFFF; +} + +ACE_INLINE void +ACE_U_LongLong::hi (const ACE_UINT32 hi) +{ + data_ = hi; + data_ <<= 32; +} + +ACE_INLINE void +ACE_U_LongLong::lo (const ACE_UINT32 lo) +{ + data_ = lo; +} + +ACE_INLINE long long +ACE_U_LongLong::to_int64 (void) const +{ + return data_; +} + +ACE_INLINE +ACE_U_LongLong::~ACE_U_LongLong (void) +{ +} + +ACE_INLINE bool +ACE_U_LongLong::operator== (const ACE_U_LongLong &n) const +{ + return data_ == n.data_; +} + +ACE_INLINE bool +ACE_U_LongLong::operator== (const ACE_UINT32 n) const +{ + return data_ == n; +} + +ACE_INLINE bool +ACE_U_LongLong::operator!= (const ACE_U_LongLong &n) const +{ + return ! (*this == n); +} + +ACE_INLINE bool +ACE_U_LongLong::operator!= (const ACE_UINT32 n) const +{ + return ! (*this == n); +} + +ACE_INLINE bool +ACE_U_LongLong::operator< (const ACE_U_LongLong &n) const +{ + if (data_ > 0) + if (n.data_ > 0) + return data_ < n.data_; + else + return true; + else + if (n.data_ > 0) + return false; + else + return data_ < n.data_; +} + +ACE_INLINE bool +ACE_U_LongLong::operator< (const ACE_UINT32 n) const +{ + return operator< (static_cast (n)); +} + +ACE_INLINE bool +ACE_U_LongLong::operator<= (const ACE_U_LongLong &n) const +{ + if (data_ == n.data_) return true; + + return data_ < n.data_; +} + +ACE_INLINE bool +ACE_U_LongLong::operator<= (const ACE_UINT32 n) const +{ + return operator<= (static_cast (n)); +} + +ACE_INLINE bool +ACE_U_LongLong::operator> (const ACE_U_LongLong &n) const +{ + if (data_ > 0) + if (n.data_ > 0) + return data_ > n.data_; + else + return false; + else + if (n.data_ > 0) + return true; + else + return data_ > n.data_; +} + +ACE_INLINE bool +ACE_U_LongLong::operator> (const ACE_UINT32 n) const +{ + return operator> (static_cast (n)); +} + +ACE_INLINE bool +ACE_U_LongLong::operator>= (const ACE_U_LongLong &n) const +{ + if (data_ == n.data_) return true; + + return data_ > n.data_; +} + +ACE_INLINE bool +ACE_U_LongLong::operator>= (const ACE_UINT32 n) const +{ + return operator>= (static_cast (n)); +} + +ACE_INLINE +ACE_U_LongLong::ACE_U_LongLong (const ACE_U_LongLong &n) + : data_ (n.data_) +{ +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator= (const ACE_U_LongLong &n) +{ + data_ = n.data_; + + return *this; +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator= (const ACE_INT32 &rhs) +{ + if (rhs >= 0) + { + data_ = rhs; + data_ &= 0xFFFFFFFF; + } + else + { + // We do not handle the case where a negative 32 bit integer is + // assigned to this representation of a 64 bit unsigned integer. + // The "undefined behavior" behavior performed by this + // implementation is to simply set all bits to zero. + data_ = 0; + } + + return *this; +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator= (const ACE_UINT32 &rhs) +{ + data_ = rhs; + + return *this; +} + + +ACE_INLINE ACE_U_LongLong +ACE_U_LongLong::operator+ (const ACE_U_LongLong &n) const +{ + return data_ + n.data_; +} + +ACE_INLINE ACE_U_LongLong +ACE_U_LongLong::operator+ (const ACE_UINT32 n) const +{ + return operator+ (static_cast (n)); +} + +ACE_INLINE ACE_U_LongLong +ACE_U_LongLong::operator- (const ACE_U_LongLong &n) const +{ + return data_ - n.data_; +} + +ACE_INLINE ACE_U_LongLong +ACE_U_LongLong::operator- (const ACE_UINT32 n) const +{ + return operator- (static_cast (n)); +} + +ACE_INLINE ACE_U_LongLong +ACE_U_LongLong::operator<< (const u_int n) const +{ + return data_ << n; +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator<<= (const u_int n) +{ + data_ <<= n; + + return *this; +} + +ACE_INLINE ACE_U_LongLong +ACE_U_LongLong::operator>> (const u_int n) const +{ + return data_ >> n; +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator>>= (const u_int n) +{ + data_ >>= n; + + return *this; +} + +ACE_INLINE double +ACE_U_LongLong::operator/ (const double n) const +{ + return data_ / n; +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator+= (const ACE_U_LongLong &n) +{ + data_ += n.data_; + + return *this; +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator+= (const ACE_UINT32 n) +{ + return operator+= (static_cast (n)); +} + +ACE_INLINE ACE_U_LongLong +ACE_U_LongLong::operator* (const ACE_UINT32 n) const +{ + return data_ * n; +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator*= (const ACE_UINT32 n) +{ + data_ *= n; + + return *this; +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator-= (const ACE_U_LongLong &n) +{ + data_ -= n.data_; + + return *this; +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator-= (const ACE_UINT32 n) +{ + return operator-= (static_cast (n)); +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator++ () +{ + ++data_; + + return *this; +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator-- () +{ + --data_; + + return *this; +} + +ACE_INLINE const ACE_U_LongLong +ACE_U_LongLong::operator++ (int) +{ + // Post-increment operator should always be implemented in terms of + // the pre-increment operator to enforce consistent semantics. + ACE_U_LongLong temp (*this); + ++*this; + return temp; +} + +ACE_INLINE const ACE_U_LongLong +ACE_U_LongLong::operator-- (int) +{ + // Post-decrement operator should always be implemented in terms of + // the pre-decrement operator to enforce consistent semantics. + ACE_U_LongLong temp (*this); + --*this; + return temp; +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator|= (const ACE_U_LongLong n) +{ + data_ |= n.data_; + + return *this; +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator|= (const ACE_UINT32 n) +{ + return operator|= (static_cast (n)); +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator&= (const ACE_U_LongLong n) +{ + data_ &= n.data_; + + return *this; +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator&= (const ACE_UINT32 n) +{ + return operator&= (static_cast (n)); +} + +ACE_INLINE ACE_UINT32 +ACE_U_LongLong::operator/ (const ACE_UINT32 n) const +{ + return data_ / n; +} + +ACE_INLINE ACE_UINT32 +ACE_U_LongLong::operator% (const ACE_UINT32 n) const +{ + return data_ % n; +} + +ACE_INLINE ACE_UINT32 +ACE_U_LongLong::operator| (const ACE_INT32 n) const +{ + return data_ | n; +} + +ACE_INLINE ACE_UINT32 +ACE_U_LongLong::operator& (const ACE_INT32 n) const +{ + return data_ & n; +} + +ACE_INLINE ACE_U_LongLong +ACE_U_LongLong::operator* (const ACE_INT32 n) const +{ + return operator* ((ACE_UINT32) n); +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator*= (const ACE_INT32 n) +{ + return operator*= ((ACE_UINT32) n); +} + +ACE_INLINE ACE_UINT32 +ACE_U_LongLong::operator/ (const ACE_INT32 n) const +{ + return operator/ ((ACE_UINT32) n); +} + +#if ACE_SIZEOF_INT == 4 +ACE_INLINE ACE_UINT32 +ACE_U_LongLong::operator/ (const u_long n) const +{ + return operator/ ((ACE_UINT32) n); +} + +ACE_INLINE ACE_UINT32 +ACE_U_LongLong::operator/ (const long n) const +{ + return operator/ ((ACE_UINT32) n); +} + +#else /* ACE_SIZEOF_INT != 4 */ +ACE_INLINE ACE_UINT32 +ACE_U_LongLong::operator/ (const u_int n) const +{ + return operator/ ((ACE_UINT32) n); +} + +ACE_INLINE ACE_UINT32 +ACE_U_LongLong::operator/ (const int n) const +{ + return operator/ ((ACE_UINT32) n); +} +#endif + +ACE_END_VERSIONED_NAMESPACE_DECL + +#elif defined (ACE_LACKS_LONGLONG_T) + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE +ACE_U_LongLong::ACE_U_LongLong (const ACE_UINT32 lo, const ACE_UINT32 hi) +{ + h_ () = hi; + l_ () = lo; +} + +ACE_INLINE ACE_UINT32 +ACE_U_LongLong::hi (void) const +{ + return h_ (); +} + +ACE_INLINE ACE_UINT32 +ACE_U_LongLong::lo (void) const +{ + return l_ (); +} + +ACE_INLINE void +ACE_U_LongLong::hi (const ACE_UINT32 hi) +{ + h_ () = hi; +} + +ACE_INLINE void +ACE_U_LongLong::lo (const ACE_UINT32 lo) +{ + l_ () = lo; +} + +ACE_INLINE +ACE_U_LongLong::~ACE_U_LongLong (void) +{ +} + +ACE_INLINE bool +ACE_U_LongLong::operator== (const ACE_U_LongLong &n) const +{ + return h_ () == n.h_ () && l_ () == n.l_ (); +} + +ACE_INLINE bool +ACE_U_LongLong::operator== (const ACE_UINT32 n) const +{ + return h_ () == 0 && l_ () == n; +} + +ACE_INLINE bool +ACE_U_LongLong::operator!= (const ACE_U_LongLong &n) const +{ + return ! (*this == n); +} + +ACE_INLINE bool +ACE_U_LongLong::operator!= (const ACE_UINT32 n) const +{ + return ! (*this == n); +} + +ACE_INLINE bool +ACE_U_LongLong::operator< (const ACE_U_LongLong &n) const +{ + return h_ () < n.h_ () ? 1 + : h_ () > n.h_ () ? 0 + : l_ () < n.l_ (); +} + +ACE_INLINE bool +ACE_U_LongLong::operator< (const ACE_UINT32 n) const +{ + return operator< (static_cast (n)); +} + +ACE_INLINE bool +ACE_U_LongLong::operator<= (const ACE_U_LongLong &n) const +{ + return h_ () < n.h_ () ? 1 + : h_ () > n.h_ () ? 0 + : l_ () <= n.l_ (); +} + +ACE_INLINE bool +ACE_U_LongLong::operator<= (const ACE_UINT32 n) const +{ + return operator<= (static_cast (n)); +} + +ACE_INLINE bool +ACE_U_LongLong::operator> (const ACE_U_LongLong &n) const +{ + return h_ () > n.h_ () ? 1 + : h_ () < n.h_ () ? 0 + : l_ () > n.l_ (); +} + +ACE_INLINE bool +ACE_U_LongLong::operator> (const ACE_UINT32 n) const +{ + return operator> (static_cast (n)); +} + +ACE_INLINE bool +ACE_U_LongLong::operator>= (const ACE_U_LongLong &n) const +{ + return h_ () > n.h_ () ? 1 + : h_ () < n.h_ () ? 0 + : l_ () >= n.l_ (); +} + +ACE_INLINE bool +ACE_U_LongLong::operator>= (const ACE_UINT32 n) const +{ + return operator>= (static_cast (n)); +} + +ACE_INLINE +ACE_U_LongLong::ACE_U_LongLong (const ACE_U_LongLong &n) +{ + h_ () = n.h_ (); + l_ () = n.l_ (); +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator= (const ACE_U_LongLong &n) +{ + h_ () = n.h_ (); + l_ () = n.l_ (); + + return *this; +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator= (const ACE_INT32 &rhs) +{ + if (rhs >= 0) + { + l_ () = static_cast (rhs); + h_ () = 0; + } + else + { + // We do not handle the case where a negative 32 bit integer is + // assigned to this representation of a 64 bit unsigned integer. + // The "undefined behavior" behavior performed by this + // implementation is to simply set all bits to zero. + l_ () = 0; + h_ () = 0; + } + + return *this; +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator= (const ACE_UINT32 &rhs) +{ + l_ () = rhs; + h_ () = 0; + + return *this; +} + + +ACE_INLINE ACE_U_LongLong +ACE_U_LongLong::operator+ (const ACE_U_LongLong &n) const +{ + ACE_U_LongLong ret (l_ () + n.l_ (), h_ () + n.h_ ()); + if (ret.l_ () < n.l_ ()) /* carry */ ++ret.h_ (); + + return ret; +} + +ACE_INLINE ACE_U_LongLong +ACE_U_LongLong::operator+ (const ACE_UINT32 n) const +{ + return operator+ (static_cast (n)); +} + +ACE_INLINE ACE_U_LongLong +ACE_U_LongLong::operator- (const ACE_U_LongLong &n) const +{ + ACE_U_LongLong ret (l_ () - n.l_ (), h_ () - n.h_ ()); + if (l_ () < n.l_ ()) /* borrow */ --ret.h_ (); + + return ret; +} + +ACE_INLINE ACE_U_LongLong +ACE_U_LongLong::operator- (const ACE_UINT32 n) const +{ + return operator- (static_cast (n)); +} + +ACE_INLINE ACE_U_LongLong +ACE_U_LongLong::operator<< (const u_int n) const +{ + const ACE_UINT32 carry_mask = l_ () >> (32 - n); + ACE_U_LongLong ret (n < 32 ? l_ () << n : 0, + n < 32 ? (h_ () << n) | carry_mask : carry_mask); + + return ret; +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator<<= (const u_int n) +{ + const ACE_UINT32 carry_mask = l_ () >> (32 - n); + h_ () = n < 32 ? (h_ () << n) | carry_mask : carry_mask; + + // g++ 2.7.2.3/Solaris 2.5.1 doesn't modify l_ () if shifted by 32. + l_ () = n < 32 ? l_ () << n : 0; + + return *this; +} + +ACE_INLINE ACE_U_LongLong +ACE_U_LongLong::operator>> (const u_int n) const +{ + const ACE_UINT32 carry_mask = h_ () << (32 - n); + ACE_U_LongLong ret (n < 32 ? (l_ () >> n) | carry_mask : 0, + n < 32 ? h_ () >> n : 0); + + return ret; +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator>>= (const u_int n) +{ + const ACE_UINT32 carry_mask = h_ () << (32 - n); + l_ () = n < 32 ? (l_ () >> n) | carry_mask : carry_mask; + h_ () = n < 32 ? h_ () >> n : 0; + + return *this; +} + +ACE_INLINE double +ACE_U_LongLong::operator/ (const double n) const +{ + // See the derivation above in operator/ (const ACE_UINT32). + + return ((double) 0xffffffffu - n + 1.0) / n * h_ () + + (double) h_ () + (double) l_ () / n; +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator+= (const ACE_U_LongLong &n) +{ + h_ () += n.h_ (); + l_ () += n.l_ (); + if (l_ () < n.l_ ()) /* carry */ ++h_ (); + + return *this; +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator+= (const ACE_UINT32 n) +{ + return operator+= (static_cast (n)); +} + +#define ACE_HIGHBIT (~(~0UL >> 1)) + +ACE_INLINE ACE_UINT32 +ACE_U_LongLong::ul_shift (ACE_UINT32 a, ACE_UINT32 c_in, ACE_UINT32 *c_out) const +{ + const ACE_UINT32 b = (a << 1) | c_in; + *c_out = (*c_out << 1) + ((a & ACE_HIGHBIT) > 0); + + return b; +} + +ACE_INLINE ACE_U_LongLong +ACE_U_LongLong::ull_shift (ACE_U_LongLong a, + ACE_UINT32 c_in, + ACE_UINT32 *c_out) const +{ + ACE_U_LongLong b; + + b.l_ () = (a.l_ () << 1) | c_in; + c_in = ((a.l_ () & ACE_HIGHBIT) > 0); + b.h_ () = (a.h_ () << 1) | c_in; + *c_out = (*c_out << 1) + ((a.h_ () & ACE_HIGHBIT) > 0); + + return b; +} + +ACE_INLINE ACE_U_LongLong +ACE_U_LongLong::ull_add (ACE_U_LongLong a, ACE_U_LongLong b, ACE_UINT32 *carry) const +{ + ACE_U_LongLong r (0, 0); + ACE_UINT32 c1, c2, c3, c4; + + c1 = a.l_ () % 2; + c2 = b.l_ () % 2; + c3 = 0; + + r.l_ () = a.l_ ()/2 + b.l_ ()/2 + (c1+c2)/2; + r.l_ () = ul_shift (r.l_ (), (c1+c2)%2, &c3); + + c1 = a.h_ () % 2; + c2 = b.h_ () % 2; + c4 = 0; + + r.h_ () = a.h_ ()/2 + b.h_ ()/2 + (c1+c2+c3)/2; + r.h_ () = ul_shift (r.h_ (), (c1+c2+c3)%2, &c4); + + *carry = c4; + + return r; +} + +ACE_INLINE ACE_U_LongLong +ACE_U_LongLong::ull_mult (ACE_U_LongLong a, ACE_UINT32 b, ACE_UINT32 *carry) const +{ + register ACE_UINT32 mask = ACE_HIGHBIT; + const ACE_U_LongLong zero (0, 0); + ACE_U_LongLong accum (0, 0); + ACE_UINT32 c; + + *carry = 0; + if (b > 0) + do + { + accum = ull_shift (accum, 0U, carry); + if (b & mask) + accum = ull_add (accum, a, &c); + else + accum = ull_add (accum, zero, &c); + *carry += c; + mask >>= 1; + } + while (mask > 0); + + return accum; +} + +ACE_INLINE ACE_U_LongLong +ACE_U_LongLong::operator* (const ACE_UINT32 n) const +{ + ACE_UINT32 carry; // will throw the carry away + + return ull_mult (*this, n, &carry); +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator*= (const ACE_UINT32 n) +{ + ACE_UINT32 carry; // will throw the carry away + + return *this = ull_mult (*this, n, &carry); +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator-= (const ACE_U_LongLong &n) +{ + h_ () -= n.h_ (); + if (l_ () < n.l_ ()) /* borrow */ --h_ (); + l_ () -= n.l_ (); + + return *this; +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator-= (const ACE_UINT32 n) +{ + return operator-= (static_cast (n)); +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator++ () +{ + ++l_ (); + if (l_ () == 0) /* carry */ ++h_ (); + + return *this; +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator-- () +{ + if (l_ () == 0) /* borrow */ --h_ (); + --l_ (); + + return *this; +} + +ACE_INLINE const ACE_U_LongLong +ACE_U_LongLong::operator++ (int) +{ + // Post-increment operator should always be implemented in terms of + // the pre-increment operator to enforce consistent semantics. + ACE_U_LongLong temp (*this); + ++*this; + return temp; +} + +ACE_INLINE const ACE_U_LongLong +ACE_U_LongLong::operator-- (int) +{ + // Post-decrement operator should always be implemented in terms of + // the pre-decrement operator to enforce consistent semantics. + ACE_U_LongLong temp (*this); + --*this; + return temp; +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator|= (const ACE_U_LongLong n) +{ + l_ () |= n.l_ (); + h_ () |= n.h_ (); + + return *this; +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator|= (const ACE_UINT32 n) +{ + return operator|= (static_cast (n)); +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator&= (const ACE_U_LongLong n) +{ + l_ () &= n.l_ (); + h_ () &= n.h_ (); + + return *this; +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator&= (const ACE_UINT32 n) +{ + return operator&= (static_cast (n)); +} + +ACE_INLINE ACE_UINT32 +ACE_U_LongLong::operator/ (const ACE_UINT32 n) const +{ + // This takes advantage of the fact that the return type has only 32 + // bits. Replace 0x100000000 with 0xffffffff + 1 because the former + // has 33 bits. + // Quotient = (0x100000000u * hi_ + lo_) / n + // = ((0x100000000u - n + n) * hi_ + lo_) / n + // = ((0x100000000u - n) / n * hi_ + hi_ * n / n + lo_ / n + // = (0x100000000u - n) / n * hi_ + hi_ + lo_ / n + // = (0xffffffffu - n + 1) / n * hi_ + hi_ + lo_ / n + + return (0xffffffffu - n + 1) / n * h_ () + h_ () + l_ () / n; +} + +ACE_INLINE ACE_UINT32 +ACE_U_LongLong::operator% (const ACE_UINT32 n) const +{ + // Because the argument is an ACE_UINT32, the result can never be + // bigger than 32 bits. Replace 0x100000000 with 0xffffffff + 1 + // because the former has 33 bits. + // Mod = (0x100000000u * hi_ + lo_) % n + // = (0x100000000u % n * hi_ + lo_ % n) % n + // = ((0x100000000u - n) % n * hi_ + lo_ % n) % n + // = ((0xffffffffu - n + 1) % n * hi_ + lo_ % n) % n + + return ((0xffffffff - n + 1) % n * h_ () + l_ () % n) % n; +} + +ACE_INLINE ACE_UINT32 +ACE_U_LongLong::operator| (const ACE_INT32 n) const +{ + return l_ () | n; +} + +ACE_INLINE ACE_UINT32 +ACE_U_LongLong::operator& (const ACE_INT32 n) const +{ + return l_ () & n; +} + +ACE_INLINE ACE_U_LongLong +ACE_U_LongLong::operator* (const ACE_INT32 n) const +{ + return operator* ((ACE_UINT32) n); +} + +ACE_INLINE ACE_U_LongLong & +ACE_U_LongLong::operator*= (const ACE_INT32 n) +{ + return operator*= ((ACE_UINT32) n); +} + +ACE_INLINE ACE_UINT32 +ACE_U_LongLong::operator/ (const ACE_INT32 n) const +{ + return operator/ ((ACE_UINT32) n); +} + +#if ACE_SIZEOF_INT == 4 +ACE_INLINE ACE_UINT32 +ACE_U_LongLong::operator/ (const u_long n) const +{ + return operator/ ((ACE_UINT32) n); +} + +ACE_INLINE ACE_UINT32 +ACE_U_LongLong::operator/ (const long n) const +{ + return operator/ ((ACE_UINT32) n); +} + +#else /* ACE_SIZEOF_INT != 4 */ +ACE_INLINE ACE_UINT32 +ACE_U_LongLong::operator/ (const u_int n) const +{ + return operator/ ((ACE_UINT32) n); +} + +ACE_INLINE ACE_UINT32 +ACE_U_LongLong::operator/ (const int n) const +{ + return operator/ ((ACE_UINT32) n); +} +#endif /* ACE_SIZEOF_INT != 4 */ + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_LACKS_LONGLONG_T || ACE_LACKS_UNSIGNEDLONGLONG_T */ diff --git a/dep/acelite/ace/Bound_Ptr.h b/dep/acelite/ace/Bound_Ptr.h new file mode 100644 index 00000000000..5176ff9514a --- /dev/null +++ b/dep/acelite/ace/Bound_Ptr.h @@ -0,0 +1,388 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Bound_Ptr.h + * + * $Id: Bound_Ptr.h 82723 2008-09-16 09:35:44Z johnnyw $ + * + * @author Christopher Kohlhoff + * @author Boris Kolpackov + */ +//============================================================================= + +#ifndef ACE_BOUND_PTR_H +#define ACE_BOUND_PTR_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Auto_Ptr.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Bound_Ptr_Counter + * + * @brief An ACE_Bound_Ptr_Counter object encapsulates an + * object reference count. + * + * Do not use this class directly, use ACE_Strong_Bound_Ptr or + * ACE_Weak_Bound_Ptr instead. + */ +template +class ACE_Bound_Ptr_Counter +{ +public: + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + + ACE_Bound_Ptr_Counter (long init_obj_ref_count = 0); + ~ACE_Bound_Ptr_Counter (void); + + /// Create a ACE_Bound_Ptr_Counter and initialize the + /// reference count to indicate ownership by a strong pointer. + static ACE_Bound_Ptr_Counter *create_strong (void); + + /// Increase both the object and counter reference counts and return + /// the new object reference count. A return value of -1 indicates + /// that the object has already been destroyed. + static long attach_strong (ACE_Bound_Ptr_Counter *counter); + + /// Decreases both the object and counter reference counts and + /// deletes whichever has no more references. Returns the new object + /// reference count. + static long detach_strong (ACE_Bound_Ptr_Counter *counter); + + /// Create a ACE_Bound_Ptr_Counter and initialize the + /// reference count to indicate no ownership. + static ACE_Bound_Ptr_Counter *create_weak (void); + + /// Increase the counter reference count and return argument. + static void attach_weak (ACE_Bound_Ptr_Counter *counter); + + /// Decreases the counter reference count and deletes the counter if + /// it has no more references. + static void detach_weak (ACE_Bound_Ptr_Counter *counter); + + /// Determine whether the object has been deleted. + static bool object_was_deleted (ACE_Bound_Ptr_Counter *counter); + +private: + + /// Allocate a new ACE_Bound_Ptr_Counter instance, + /// returning NULL if it cannot be created. + static ACE_Bound_Ptr_Counter *internal_create (long init_obj_ref_count); + +private: + + /// Reference count of underlying object. Is set to -1 once the + /// object has been destroyed to indicate to all weak pointers that + /// it is no longer valid. + long obj_ref_count_; + + /// Reference count of this counter. + long self_ref_count_; + + /// Mutex variable to synchronize access to the reference counts. + ACE_LOCK lock_; +}; + +// Forward decl. +template class ACE_Weak_Bound_Ptr; + +/** + * @class ACE_Strong_Bound_Ptr + * + * @brief This class implements support for a reference counted + * pointer. + * + * Assigning or copying instances of an ACE_Strong_Bound_Ptr will + * automatically increment the reference count of the underlying object. + * When the last instance of an ACE_Strong_Bound_Ptr that references a + * particular object is destroyed or overwritten, it will invoke delete + * on its underlying pointer. + */ +template +class ACE_Strong_Bound_Ptr +{ +public: + /// Constructor that initializes an ACE_Strong_Bound_Ptr to point to the + /// object \ immediately. + explicit ACE_Strong_Bound_Ptr (X *p = 0); + + /// Constructor that initializes an ACE_Strong_Bound_Ptr by stealing + /// ownership of an object from an auto_ptr. + explicit ACE_Strong_Bound_Ptr (auto_ptr p); + + /// Copy constructor binds @c this and @a r to the same object. + ACE_Strong_Bound_Ptr (const ACE_Strong_Bound_Ptr &r); + + /// Constructor binds @c this and @a r to the same object. + ACE_Strong_Bound_Ptr (const ACE_Weak_Bound_Ptr &r); + + /// Copy constructor binds @c this and @a r to the same object if + /// Y* can be implicitly converted to X*. + template + ACE_Strong_Bound_Ptr (const ACE_Strong_Bound_Ptr &r) + : counter_ (r.counter_), + ptr_ (dynamic_cast(r.ptr_)) + { + // This ctor is temporarily defined here to increase our chances + // of being accepted by broken compilers. + // + COUNTER::attach_strong (this->counter_); + } + + /// Destructor. + ~ACE_Strong_Bound_Ptr (void); + + /// Assignment operator that binds @c this and @a r to the same object. + void operator = (const ACE_Strong_Bound_Ptr &r); + + /// Assignment operator that binds @c this and @a r to the same object. + void operator = (const ACE_Weak_Bound_Ptr &r); + + /// Assignment operator that binds @c this and @a r to the same object + /// if Y* can be implicitly converted to X*. + template + ACE_Weak_Bound_Ptr& + operator= (const ACE_Strong_Bound_Ptr &r) + { + // This operator is temporarily defined here to increase our chances + // of being accepted by broken compilers. + // + + // This will work if &r == this, by first increasing the ref count + + COUNTER *new_counter = r.counter_; + X* new_ptr = dynamic_cast (r.ptr_); + COUNTER::attach_strong (new_counter); + if (COUNTER::detach_strong (this->counter_) == 0) + delete this->ptr_; + this->counter_ = new_counter; + this->ptr_ = new_ptr; + + return *this; + } + + /// Equality operator that returns @c true if both + /// ACE_Strong_Bound_Ptr instances point to the same underlying + /// object. + /** + * @note It also returns @c true if both objects have just been + * instantiated and not used yet. + */ + bool operator == (const ACE_Strong_Bound_Ptr &r) const; + + /// Equality operator that returns true if the ACE_Strong_Bound_Ptr + /// and ACE_Weak_Bound_Ptr objects point to the same underlying + /// object. + /** + * @note It also returns @c true if both objects have just been + * instantiated and not used yet. + */ + bool operator == (const ACE_Weak_Bound_Ptr &r) const; + + /// Equality operator that returns @c true if the + /// ACE_Strong_Bound_Ptr and the raw pointer point to the same + /// underlying object. + bool operator == (X *p) const; + + /// Inequality operator, which is the opposite of equality. + bool operator != (const ACE_Strong_Bound_Ptr &r) const; + + /// Inequality operator, which is the opposite of equality. + bool operator != (const ACE_Weak_Bound_Ptr &r) const; + + /// Inequality operator, which is the opposite of equality. + bool operator != (X *p) const; + + /// Redirection operator + X *operator-> (void) const; + + /// Dereference operator + X &operator * (void) const; + + /// Get the pointer value. + X *get (void) const; + + /// Resets the ACE_Strong_Bound_Ptr to refer to a different + /// underlying object. + void reset (X *p = 0); + + /// Resets the ACE_Strong_Bound_Ptr to refer to a different + /// underlying object, ownership of which is stolen from the + /// auto_ptr. + void reset (auto_ptr p); + + /// Allows us to check for NULL on all ACE_Strong_Bound_Ptr + /// objects. + bool null (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + typedef X X_t; // This indirection is for Borland C++. + + friend class ACE_Weak_Bound_Ptr; + + template + friend class ACE_Strong_Bound_Ptr; + + /// The ACE_Bound_Ptr_Counter type. + typedef ACE_Bound_Ptr_Counter COUNTER; + + /// The reference counter. + COUNTER *counter_; + + /// The underlying object. + X *ptr_; +}; + +/** + * @class ACE_Weak_Bound_Ptr + * + * @brief This class implements support for a weak pointer that complements + * ACE_Strong_Bound_Ptr. + * + * Unlike ACE_Strong_Bound_Ptr, assigning or copying instances of an + * ACE_Weak_Bound_Ptr will not automatically increment the reference + * count of the underlying object. What ACE_Weak_Bound_Ptr does is + * preserve the knowledge that the object is in fact reference + * counted, and thus provides an alternative to raw pointers where + * non-ownership associations must be maintained. When the last + * instance of an ACE_Strong_Bound_Ptr that references a particular + * object is destroyed or overwritten, the corresponding + * ACE_Weak_Bound_Ptr instances are set to NULL. + */ +template +class ACE_Weak_Bound_Ptr +{ +public: + /// Constructor that initializes an ACE_Weak_Bound_Ptr to point to + /// the object \ immediately. + explicit ACE_Weak_Bound_Ptr (X *p = 0); + + /// Copy constructor binds @c this and @a r to the same object. + ACE_Weak_Bound_Ptr (const ACE_Weak_Bound_Ptr &r); + + /// Constructor binds @c this and @a r to the same object. + ACE_Weak_Bound_Ptr (const ACE_Strong_Bound_Ptr &r); + + /// Destructor. + ~ACE_Weak_Bound_Ptr (void); + + /// Assignment operator that binds @c this and @a r to the same object. + void operator = (const ACE_Weak_Bound_Ptr &r); + + /// Assignment operator that binds @c this and @a r to the same object. + void operator = (const ACE_Strong_Bound_Ptr &r); + + /// Equality operator that returns @c true if both + /// ACE_Weak_Bound_Ptr objects point to the same underlying object. + /** + * @note It also returns @c true if both objects have just been + * instantiated and not used yet. + */ + bool operator == (const ACE_Weak_Bound_Ptr &r) const; + + /// Equality operator that returns @c true if the ACE_Weak_Bound_Ptr + /// and ACE_Strong_Bound_Ptr objects point to the same underlying + /// object. + /** + * @note It also returns @c true if both objects have just been + * instantiated and not used yet. + */ + bool operator == (const ACE_Strong_Bound_Ptr &r) const; + + /// Equality operator that returns @c true if the ACE_Weak_Bound_Ptr + /// and the raw pointer point to the same underlying object. + bool operator == (X *p) const; + + /// Inequality operator, which is the opposite of equality. + bool operator != (const ACE_Weak_Bound_Ptr &r) const; + + /// Inequality operator, which is the opposite of equality. + bool operator != (const ACE_Strong_Bound_Ptr &r) const; + + /// Inequality operator, which is the opposite of equality. + bool operator != (X *p) const; + + /// Redirection operator. + /** + * It returns a temporary strong pointer and makes use of the + * chaining properties of operator-> to ensure that the underlying + * object does not disappear while you are using it. If you are + * certain of the lifetimes of the object, and do not want to incur + * the locking overhead, then use the unsafe_get method instead. + */ + ACE_Strong_Bound_Ptr operator-> (void) const; + + /// Obtain a strong pointer corresponding to this weak pointer. This + /// function is useful to create a temporary strong pointer for + /// conversion to a reference. + ACE_Strong_Bound_Ptr strong (void) const; + + /// Get the pointer value. Warning: this does not affect the + /// reference count of the underlying object, so it may disappear on + /// you while you are using it if you are not careful. + X *unsafe_get (void) const; + + /// Resets the ACE_Weak_Bound_Ptr to refer to a different underlying + /// object. + void reset (X *p = 0); + + /// Increment the reference count on the underlying object. + /** + * Returns the new reference count on the object. This function may + * be used to integrate the bound pointers into an external + * reference counting mechanism such as those used by COM or CORBA + * servants. + */ + long add_ref (void); + + /// Decrement the reference count on the underlying object, which is deleted + /// if the count has reached zero. + /** + * Returns the new reference count on the object. This function may + * be used to integrate the bound pointers into an external + * reference counting mechanism such as those used by COM or CORBA + * servants. + */ + long remove_ref (void); + + /// Allows us to check for NULL on all ACE_Weak_Bound_Ptr objects. + bool null (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + typedef X X_t; // This indirection is for Borland C++. + + friend class ACE_Strong_Bound_Ptr; + + /// The ACE_Bound_Ptr_Counter type. + typedef ACE_Bound_Ptr_Counter COUNTER; + + /// The reference counter. + COUNTER *counter_; + + /// The underlying object. + X *ptr_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include "ace/Bound_Ptr.inl" + +#include /**/ "ace/post.h" + +#endif /* ACE_BOUND_PTR_H */ diff --git a/dep/acelite/ace/Bound_Ptr.inl b/dep/acelite/ace/Bound_Ptr.inl new file mode 100644 index 00000000000..399a7bc9b23 --- /dev/null +++ b/dep/acelite/ace/Bound_Ptr.inl @@ -0,0 +1,494 @@ +/* -*- C++ -*- */ +// $Id: Bound_Ptr.inl 82723 2008-09-16 09:35:44Z johnnyw $ + +// Bound_Ptr.i + +#include "ace/Guard_T.h" +#if !defined (ACE_NEW_THROWS_EXCEPTIONS) +# include "ace/Log_Msg.h" +#endif /* ACE_NEW_THROWS_EXCEPTIONS */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template inline ACE_Bound_Ptr_Counter * +ACE_Bound_Ptr_Counter::internal_create (long init_obj_ref_count) +{ + ACE_Bound_Ptr_Counter *temp = 0; + ACE_NEW_RETURN (temp, + ACE_Bound_Ptr_Counter (init_obj_ref_count), + 0); + return temp; +} + +template inline ACE_Bound_Ptr_Counter * +ACE_Bound_Ptr_Counter::create_strong (void) +{ + // Set initial object reference count to 1. + ACE_Bound_Ptr_Counter *temp = internal_create (1); +#if defined (ACE_NEW_THROWS_EXCEPTIONS) + if (temp == 0) + ACE_throw_bad_alloc; +#else + ACE_ASSERT (temp != 0); +#endif /* ACE_NEW_THROWS_EXCEPTIONS */ + return temp; +} + + + +template inline long +ACE_Bound_Ptr_Counter::attach_strong (ACE_Bound_Ptr_Counter* counter) +{ + ACE_GUARD_RETURN (ACE_LOCK, guard, counter->lock_, -1); + + // Can't attach a strong pointer to an object that has already been deleted. + if (counter->obj_ref_count_ == -1) + return -1; + + long new_obj_ref_count = ++counter->obj_ref_count_; + ++counter->self_ref_count_; + + return new_obj_ref_count; +} + +template inline long +ACE_Bound_Ptr_Counter::detach_strong (ACE_Bound_Ptr_Counter* counter) +{ + ACE_Bound_Ptr_Counter *counter_del = 0; + long new_obj_ref_count; + + { + ACE_GUARD_RETURN (ACE_LOCK, guard, counter->lock_, -1); + + if ((new_obj_ref_count = --counter->obj_ref_count_) == 0) + // Change the object reference count to -1 to indicate that the + // object has been deleted, as opposed to a weak pointer that + // simply hasn't had any strong pointers created from it yet. + counter->obj_ref_count_ = -1; + + if (--counter->self_ref_count_ == 0) + // Since counter contains the lock held by the ACE_Guard, the + // guard needs to be released before freeing the memory holding + // the lock. So save the pointer to free, then release, then + // free. + counter_del = counter; + + } // Release the lock + + delete counter_del; + + return new_obj_ref_count; +} + +template inline ACE_Bound_Ptr_Counter * +ACE_Bound_Ptr_Counter::create_weak (void) +{ + // Set initial object reference count to 0. + + ACE_Bound_Ptr_Counter *temp = internal_create (0); +#if defined (ACE_NEW_THROWS_EXCEPTIONS) + if (temp == 0) + ACE_throw_bad_alloc; +#else + ACE_ASSERT (temp != 0); +#endif /* ACE_NEW_THROWS_EXCEPTIONS */ + return temp; +} + +template inline void +ACE_Bound_Ptr_Counter::attach_weak (ACE_Bound_Ptr_Counter* counter) +{ + ACE_GUARD (ACE_LOCK, guard, counter->lock_); + + ++counter->self_ref_count_; +} + +template inline void +ACE_Bound_Ptr_Counter::detach_weak (ACE_Bound_Ptr_Counter* counter) +{ + ACE_Bound_Ptr_Counter *counter_del = 0; + + { + ACE_GUARD (ACE_LOCK, guard, counter->lock_); + + if (--counter->self_ref_count_ == 0) + // Since counter contains the lock held by the ACE_Guard, the + // guard needs to be released before freeing the memory holding + // the lock. So save the pointer to free, then release, then + // free. + counter_del = counter; + + } // Release the lock + + delete counter_del; +} + +template inline bool +ACE_Bound_Ptr_Counter::object_was_deleted (ACE_Bound_Ptr_Counter *counter) +{ + ACE_GUARD_RETURN (ACE_LOCK, guard, counter->lock_, 0); + + return counter->obj_ref_count_ == -1; +} + +template inline +ACE_Bound_Ptr_Counter::ACE_Bound_Ptr_Counter (long init_obj_ref_count) + : obj_ref_count_ (init_obj_ref_count), + self_ref_count_ (1) +{ +} + +template inline +ACE_Bound_Ptr_Counter::~ACE_Bound_Ptr_Counter (void) +{ +} + +template inline +ACE_Strong_Bound_Ptr::ACE_Strong_Bound_Ptr (X *p) + : counter_ (COUNTER::create_strong ()), + ptr_ (p) +{ +} + +template inline +ACE_Strong_Bound_Ptr::ACE_Strong_Bound_Ptr (auto_ptr p) + : counter_ (COUNTER::create_strong ()), + ptr_ (p.release()) +{ +} + +template inline +ACE_Strong_Bound_Ptr::ACE_Strong_Bound_Ptr (const ACE_Strong_Bound_Ptr &r) + : counter_ (r.counter_), + ptr_ (r.ptr_) +{ + COUNTER::attach_strong (this->counter_); +} + +template inline +ACE_Strong_Bound_Ptr::ACE_Strong_Bound_Ptr (const ACE_Weak_Bound_Ptr &r) + : counter_ (r.counter_), + ptr_ (r.ptr_) +{ + // When creating a strong pointer from a weak one we can't assume that the + // underlying object still exists. Therefore we must check for a return value + // of -1, which indicates that the object has been destroyed. + if (COUNTER::attach_strong (this->counter_) == -1) + { + // Underlying object has already been deleted, so set this pointer to null. + this->counter_ = COUNTER::create_strong (); + this->ptr_ = 0; + } +} + +template inline +ACE_Strong_Bound_Ptr::~ACE_Strong_Bound_Ptr (void) +{ + if (COUNTER::detach_strong (this->counter_) == 0) + delete this->ptr_; +} + +template inline void +ACE_Strong_Bound_Ptr::operator = (const ACE_Strong_Bound_Ptr &rhs) +{ + // This will work if &r == this, by first increasing the ref count, but + // why go through all that? + if (&rhs == this) + return; + + COUNTER *new_counter = rhs.counter_; + X_t *new_ptr = rhs.ptr_; + COUNTER::attach_strong (new_counter); + if (COUNTER::detach_strong (this->counter_) == 0) + delete this->ptr_; + this->counter_ = new_counter; + this->ptr_ = new_ptr; +} + +template inline void +ACE_Strong_Bound_Ptr::operator = (const ACE_Weak_Bound_Ptr &rhs) +{ + // This will work if &r == this, by first increasing the ref count, but + // why go through all that? + if (&rhs == this) + return; + + COUNTER *new_counter = rhs.counter_; + X_t *new_ptr = rhs.ptr_; + + // When creating a strong pointer from a weak one we can't assume that the + // underlying object still exists. Therefore we must check for a return value + // of -1, which indicates that the object has been destroyed. + if (COUNTER::attach_strong (new_counter) == -1) + { + // Underlying object has already been deleted, so set this pointer to null. + new_counter = COUNTER::create_strong (); + new_ptr = 0; + } + + if (COUNTER::detach_strong (this->counter_) == 0) + delete this->ptr_; + this->counter_ = new_counter; + this->ptr_ = new_ptr; +} + +template inline bool +ACE_Strong_Bound_Ptr::operator== (const ACE_Strong_Bound_Ptr &r) const +{ + return this->ptr_ == r.ptr_; +} + +template inline bool +ACE_Strong_Bound_Ptr::operator== (const ACE_Weak_Bound_Ptr &r) const +{ + // Use the weak pointer's operator== since it will check for null. + return r == *this; +} + +template inline bool +ACE_Strong_Bound_Ptr::operator== (X *p) const +{ + return this->ptr_ == p; +} + +template inline bool +ACE_Strong_Bound_Ptr::operator!= (const ACE_Strong_Bound_Ptr &r) const +{ + return this->ptr_ != r.ptr_; +} + +template inline bool +ACE_Strong_Bound_Ptr::operator!= (const ACE_Weak_Bound_Ptr &r) const +{ + // Use the weak pointer's operator!= since it will check for null. + return r != *this; +} + +template inline bool +ACE_Strong_Bound_Ptr::operator!= (X *p) const +{ + return this->ptr_ != p; +} + +template inline X * +ACE_Strong_Bound_Ptr::operator-> (void) const +{ + return this->ptr_; +} + +template inline X & +ACE_Strong_Bound_Ptr::operator *() const +{ + return *this->ptr_; +} + +template inline X* +ACE_Strong_Bound_Ptr::get (void) const +{ + return this->ptr_; +} + +template inline bool +ACE_Strong_Bound_Ptr::null (void) const +{ + return this->ptr_ == 0; +} + +template inline void +ACE_Strong_Bound_Ptr::reset (X *p) +{ + COUNTER *old_counter = this->counter_; + X_t *old_ptr = this->ptr_; + this->counter_ = COUNTER::create_strong (); + this->ptr_ = p; + if (COUNTER::detach_strong (old_counter) == 0) + delete old_ptr; +} + +template inline void +ACE_Strong_Bound_Ptr::reset (auto_ptr p) +{ + COUNTER *old_counter = this->counter_; + X_t *old_ptr = this->ptr_; + this->counter_ = COUNTER::create_strong (); + this->ptr_ = p.release (); + if (COUNTER::detach_strong (old_counter) == 0) + delete old_ptr; +} + +template inline +ACE_Weak_Bound_Ptr::ACE_Weak_Bound_Ptr (X *p) + : counter_ (COUNTER::create_weak ()), + ptr_ (p) +{ +} + +template inline +ACE_Weak_Bound_Ptr::ACE_Weak_Bound_Ptr (const ACE_Weak_Bound_Ptr &r) + : counter_ (r.counter_), + ptr_ (r.ptr_) +{ + COUNTER::attach_weak (this->counter_); +} + +template inline +ACE_Weak_Bound_Ptr::ACE_Weak_Bound_Ptr (const ACE_Strong_Bound_Ptr &r) + : counter_ (r.counter_), + ptr_ (r.ptr_) +{ + COUNTER::attach_weak (this->counter_); +} + +template inline +ACE_Weak_Bound_Ptr::~ACE_Weak_Bound_Ptr (void) +{ + COUNTER::detach_weak (this->counter_); +} + +template inline void +ACE_Weak_Bound_Ptr::operator = (const ACE_Weak_Bound_Ptr &rhs) +{ + // This will work if &rhs == this, by first increasing the ref count + COUNTER *new_counter = rhs.counter_; + COUNTER::attach_weak (new_counter); + COUNTER::detach_weak (this->counter_); + this->counter_ = new_counter; + this->ptr_ = rhs.ptr_; +} + +template inline void +ACE_Weak_Bound_Ptr::operator = (const ACE_Strong_Bound_Ptr &rhs) +{ + // This will work if &rhs == this, by first increasing the ref count + COUNTER *new_counter = rhs.counter_; + COUNTER::attach_weak (new_counter); + COUNTER::detach_weak (this->counter_); + this->counter_ = new_counter; + this->ptr_ = rhs.ptr_; +} + +template inline bool +ACE_Weak_Bound_Ptr::operator== (const ACE_Weak_Bound_Ptr &r) const +{ + // A weak pointer must behave as though it is automatically set to null + // if the underlying object has been deleted. + if (COUNTER::object_was_deleted (this->counter_)) + return r.ptr_ == 0; + + return this->ptr_ == r.ptr_; +} + +template inline bool +ACE_Weak_Bound_Ptr::operator== (const ACE_Strong_Bound_Ptr &r) const +{ + // A weak pointer must behave as though it is automatically set to null + // if the underlying object has been deleted. + if (COUNTER::object_was_deleted (this->counter_)) + return r.ptr_ == 0; + + return this->ptr_ == r.ptr_; +} + +template inline bool +ACE_Weak_Bound_Ptr::operator== (X *p) const +{ + // A weak pointer must behave as though it is automatically set to null + // if the underlying object has been deleted. + if (COUNTER::object_was_deleted (this->counter_)) + return p == 0; + + return this->ptr_ == p; +} + +template inline bool +ACE_Weak_Bound_Ptr::operator!= (const ACE_Weak_Bound_Ptr &r) const +{ + // A weak pointer must behave as though it is automatically set to null + // if the underlying object has been deleted. + if (COUNTER::object_was_deleted (this->counter_)) + return r.ptr_ != 0; + + return this->ptr_ != r.ptr_; +} + +template inline bool +ACE_Weak_Bound_Ptr::operator!= (const ACE_Strong_Bound_Ptr &r) const +{ + // A weak pointer must behave as though it is automatically set to null + // if the underlying object has been deleted. + if (COUNTER::object_was_deleted (this->counter_)) + return r.ptr_ != 0; + + return this->ptr_ != r.ptr_; +} + +template inline bool +ACE_Weak_Bound_Ptr::operator!= (X *p) const +{ + // A weak pointer must behave as though it is automatically set to null + // if the underlying object has been deleted. + if (COUNTER::object_was_deleted (this->counter_)) + return p != 0; + + return this->ptr_ != p; +} + +template inline ACE_Strong_Bound_Ptr +ACE_Weak_Bound_Ptr::operator-> (void) const +{ + return ACE_Strong_Bound_Ptr (*this); +} + +template inline ACE_Strong_Bound_Ptr +ACE_Weak_Bound_Ptr::strong (void) const +{ + return ACE_Strong_Bound_Ptr (*this); +} + +template inline X* +ACE_Weak_Bound_Ptr::unsafe_get (void) const +{ + // We do not check if the object has been deleted, since this operation + // is defined to be unsafe! + return this->ptr_; +} + +template inline bool +ACE_Weak_Bound_Ptr::null (void) const +{ + // A weak pointer must behave as though it is automatically set to null + // if the underlying object has been deleted. + if (COUNTER::object_was_deleted (this->counter_)) + return true; + + return this->ptr_ == 0; +} + +template inline void +ACE_Weak_Bound_Ptr::reset (X *p) +{ + COUNTER *old_counter = this->counter_; + this->counter_ = COUNTER::create_weak (); + this->ptr_ = p; + COUNTER::detach_weak (old_counter); +} + +template inline long +ACE_Weak_Bound_Ptr::add_ref () +{ + return COUNTER::attach_strong (counter_); +} + +template inline long +ACE_Weak_Bound_Ptr::remove_ref () +{ + long new_obj_ref_count = COUNTER::detach_strong (counter_); + if (new_obj_ref_count == 0) + { + delete this->ptr_; + this->ptr_ = 0; + } + return new_obj_ref_count; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/CDR_Base.cpp b/dep/acelite/ace/CDR_Base.cpp new file mode 100644 index 00000000000..35393c3f577 --- /dev/null +++ b/dep/acelite/ace/CDR_Base.cpp @@ -0,0 +1,802 @@ +#include "ace/CDR_Base.h" + +#if !defined (__ACE_INLINE__) +# include "ace/CDR_Base.inl" +#endif /* ! __ACE_INLINE__ */ + +#include "ace/Message_Block.h" +#include "ace/OS_Memory.h" +#include "ace/OS_NS_string.h" + +ACE_RCSID (ace, + CDR_Base, + "$Id: CDR_Base.cpp 86825 2009-09-28 17:45:23Z johnnyw $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +#if defined (NONNATIVE_LONGDOUBLE) +static const ACE_INT16 max_eleven_bit = 0x3ff; +static const ACE_INT16 max_fifteen_bit = 0x3fff; +#endif /* NONNATIVE_LONGDOUBLE */ + +// +// See comments in CDR_Base.inl about optimization cases for swap_XX_array. +// + +void +ACE_CDR::swap_2_array (char const * orig, char* target, size_t n) +{ + // ACE_ASSERT(n > 0); The caller checks that n > 0 + + // We pretend that AMD64/GNU G++ systems have a Pentium CPU to + // take advantage of the inline assembly implementation. + + // Later, we try to read in 32 or 64 bit chunks, + // so make sure we don't do that for unaligned addresses. +#if ACE_SIZEOF_LONG == 8 && \ + !((defined(__amd64__) || defined (__x86_64__)) && defined(__GNUG__)) + char const * const o8 = ACE_ptr_align_binary (orig, 8); + while (orig < o8 && n > 0) + { + ACE_CDR::swap_2 (orig, target); + orig += 2; + target += 2; + --n; + } +#else + char const * const o4 = ACE_ptr_align_binary (orig, 4); + // this is an _if_, not a _while_. The mistmatch can only be by 2. + if (orig != o4) + { + ACE_CDR::swap_2 (orig, target); + orig += 2; + target += 2; + --n; + } +#endif + if (n == 0) + return; + + // + // Loop unrolling. Here be dragons. + // + + // (n & (~3)) is the greatest multiple of 4 not bigger than n. + // In the while loop ahead, orig will move over the array by 8 byte + // increments (4 elements of 2 bytes). + // end marks our barrier for not falling outside. + char const * const end = orig + 2 * (n & (~3)); + + // See if we're aligned for writting in 64 or 32 bit chunks... +#if ACE_SIZEOF_LONG == 8 && \ + !((defined(__amd64__) || defined (__x86_64__)) && defined(__GNUG__)) + if (target == ACE_ptr_align_binary (target, 8)) +#else + if (target == ACE_ptr_align_binary (target, 4)) +#endif + { + while (orig < end) + { +#if defined (ACE_HAS_INTEL_ASSEMBLY) + unsigned int a = + * reinterpret_cast (orig); + unsigned int b = + * reinterpret_cast (orig + 4); + asm ( "bswap %1" : "=r" (a) : "0" (a) ); + asm ( "bswap %1" : "=r" (b) : "0" (b) ); + asm ( "rol $16, %1" : "=r" (a) : "0" (a) ); + asm ( "rol $16, %1" : "=r" (b) : "0" (b) ); + * reinterpret_cast (target) = a; + * reinterpret_cast (target + 4) = b; +#elif defined(ACE_HAS_PENTIUM) \ + && (defined(_MSC_VER) || defined(__BORLANDC__)) \ + && !defined(ACE_LACKS_INLINE_ASSEMBLY) + __asm mov ecx, orig; + __asm mov edx, target; + __asm mov eax, [ecx]; + __asm mov ebx, 4[ecx]; + __asm bswap eax; + __asm bswap ebx; + __asm rol eax, 16; + __asm rol ebx, 16; + __asm mov [edx], eax; + __asm mov 4[edx], ebx; +#elif ACE_SIZEOF_LONG == 8 + // 64 bit architecture. + register unsigned long a = + * reinterpret_cast (orig); + + register unsigned long a1 = (a & 0x00ff00ff00ff00ffUL) << 8; + register unsigned long a2 = (a & 0xff00ff00ff00ff00UL) >> 8; + + a = (a1 | a2); + + * reinterpret_cast (target) = a; +#else + register ACE_UINT32 a = + * reinterpret_cast (orig); + register ACE_UINT32 b = + * reinterpret_cast (orig + 4); + + register ACE_UINT32 a1 = (a & 0x00ff00ffU) << 8; + register ACE_UINT32 b1 = (b & 0x00ff00ffU) << 8; + register ACE_UINT32 a2 = (a & 0xff00ff00U) >> 8; + register ACE_UINT32 b2 = (b & 0xff00ff00U) >> 8; + + a = (a1 | a2); + b = (b1 | b2); + + * reinterpret_cast (target) = a; + * reinterpret_cast (target + 4) = b; +#endif + orig += 8; + target += 8; + } + } + else + { + // We're out of luck. We have to write in 2 byte chunks. + while (orig < end) + { +#if defined (ACE_HAS_INTEL_ASSEMBLY) + unsigned int a = + * reinterpret_cast (orig); + unsigned int b = + * reinterpret_cast (orig + 4); + asm ( "bswap %1" : "=r" (a) : "0" (a) ); + asm ( "bswap %1" : "=r" (b) : "0" (b) ); + // We're little endian. + * reinterpret_cast (target + 2) + = (unsigned short) (a & 0xffff); + * reinterpret_cast (target + 6) + = (unsigned short) (b & 0xffff); + asm ( "shrl $16, %1" : "=r" (a) : "0" (a) ); + asm ( "shrl $16, %1" : "=r" (b) : "0" (b) ); + * reinterpret_cast (target + 0) + = (unsigned short) (a & 0xffff); + * reinterpret_cast (target + 4) + = (unsigned short) (b & 0xffff); +#elif defined (ACE_HAS_PENTIUM) \ + && (defined (_MSC_VER) || defined (__BORLANDC__)) \ + && !defined (ACE_LACKS_INLINE_ASSEMBLY) + __asm mov ecx, orig; + __asm mov edx, target; + __asm mov eax, [ecx]; + __asm mov ebx, 4[ecx]; + __asm bswap eax; + __asm bswap ebx; + // We're little endian. + __asm mov 2[edx], ax; + __asm mov 6[edx], bx; + __asm shr eax, 16; + __asm shr ebx, 16; + __asm mov 0[edx], ax; + __asm mov 4[edx], bx; +#elif ACE_SIZEOF_LONG == 8 + // 64 bit architecture. + register unsigned long a = + * reinterpret_cast (orig); + + register unsigned long a1 = (a & 0x00ff00ff00ff00ffUL) << 8; + register unsigned long a2 = (a & 0xff00ff00ff00ff00UL) >> 8; + + a = (a1 | a2); + + ACE_UINT16 b1 = static_cast (a >> 48); + ACE_UINT16 b2 = static_cast ((a >> 32) & 0xffff); + ACE_UINT16 b3 = static_cast ((a >> 16) & 0xffff); + ACE_UINT16 b4 = static_cast (a & 0xffff); + +#if defined(ACE_LITTLE_ENDIAN) + * reinterpret_cast (target) = b4; + * reinterpret_cast (target + 2) = b3; + * reinterpret_cast (target + 4) = b2; + * reinterpret_cast (target + 6) = b1; +#else + * reinterpret_cast (target) = b1; + * reinterpret_cast (target + 2) = b2; + * reinterpret_cast (target + 4) = b3; + * reinterpret_cast (target + 6) = b4; +#endif +#else + register ACE_UINT32 a = + * reinterpret_cast (orig); + register ACE_UINT32 b = + * reinterpret_cast (orig + 4); + + register ACE_UINT32 a1 = (a & 0x00ff00ff) << 8; + register ACE_UINT32 b1 = (b & 0x00ff00ff) << 8; + register ACE_UINT32 a2 = (a & 0xff00ff00) >> 8; + register ACE_UINT32 b2 = (b & 0xff00ff00) >> 8; + + a = (a1 | a2); + b = (b1 | b2); + + ACE_UINT32 c1 = static_cast (a >> 16); + ACE_UINT32 c2 = static_cast (a & 0xffff); + ACE_UINT32 c3 = static_cast (b >> 16); + ACE_UINT32 c4 = static_cast (b & 0xffff); + +#if defined(ACE_LITTLE_ENDIAN) + * reinterpret_cast (target) = c2; + * reinterpret_cast (target + 2) = c1; + * reinterpret_cast (target + 4) = c4; + * reinterpret_cast (target + 6) = c3; +#else + * reinterpret_cast (target) = c1; + * reinterpret_cast (target + 2) = c2; + * reinterpret_cast (target + 4) = c3; + * reinterpret_cast (target + 6) = c4; +#endif +#endif + + orig += 8; + target += 8; + } + } + + // (n & 3) == (n % 4). + switch (n&3) { + case 3: + ACE_CDR::swap_2 (orig, target); + orig += 2; + target += 2; + case 2: + ACE_CDR::swap_2 (orig, target); + orig += 2; + target += 2; + case 1: + ACE_CDR::swap_2 (orig, target); + } +} + +void +ACE_CDR::swap_4_array (char const * orig, char* target, size_t n) +{ + // ACE_ASSERT (n > 0); The caller checks that n > 0 + +#if ACE_SIZEOF_LONG == 8 + // Later, we read from *orig in 64 bit chunks, + // so make sure we don't generate unaligned readings. + char const * const o8 = ACE_ptr_align_binary (orig, 8); + // The mismatch can only be by 4. + if (orig != o8) + { + ACE_CDR::swap_4 (orig, target); + orig += 4; + target += 4; + --n; + } +#endif /* ACE_SIZEOF_LONG == 8 */ + + if (n == 0) + return; + + // + // Loop unrolling. Here be dragons. + // + + // (n & (~3)) is the greatest multiple of 4 not bigger than n. + // In the while loop, orig will move over the array by 16 byte + // increments (4 elements of 4 bytes). + // ends marks our barrier for not falling outside. + char const * const end = orig + 4 * (n & (~3)); + +#if ACE_SIZEOF_LONG == 8 + // 64 bits architecture. + // See if we can write in 8 byte chunks. + if (target == ACE_ptr_align_binary (target, 8)) + { + while (orig < end) + { + register unsigned long a = + * reinterpret_cast (orig); + register unsigned long b = + * reinterpret_cast (orig + 8); + +#if defined(ACE_HAS_INTEL_ASSEMBLY) + asm ("bswapq %1" : "=r" (a) : "0" (a)); + asm ("bswapq %1" : "=r" (b) : "0" (b)); + asm ("rol $32, %1" : "=r" (a) : "0" (a)); + asm ("rol $32, %1" : "=r" (b) : "0" (b)); +#else + register unsigned long a84 = (a & 0x000000ff000000ffL) << 24; + register unsigned long b84 = (b & 0x000000ff000000ffL) << 24; + register unsigned long a73 = (a & 0x0000ff000000ff00L) << 8; + register unsigned long b73 = (b & 0x0000ff000000ff00L) << 8; + register unsigned long a62 = (a & 0x00ff000000ff0000L) >> 8; + register unsigned long b62 = (b & 0x00ff000000ff0000L) >> 8; + register unsigned long a51 = (a & 0xff000000ff000000L) >> 24; + register unsigned long b51 = (b & 0xff000000ff000000L) >> 24; + + a = (a84 | a73 | a62 | a51); + b = (b84 | b73 | b62 | b51); +#endif + + * reinterpret_cast (target) = a; + * reinterpret_cast (target + 8) = b; + + orig += 16; + target += 16; + } + } + else + { + // We are out of luck, we have to write in 4 byte chunks. + while (orig < end) + { + register unsigned long a = + * reinterpret_cast (orig); + register unsigned long b = + * reinterpret_cast (orig + 8); + +#if defined(ACE_HAS_INTEL_ASSEMBLY) + asm ("bswapq %1" : "=r" (a) : "0" (a)); + asm ("bswapq %1" : "=r" (b) : "0" (b)); + asm ("rol $32, %1" : "=r" (a) : "0" (a)); + asm ("rol $32, %1" : "=r" (b) : "0" (b)); +#else + register unsigned long a84 = (a & 0x000000ff000000ffL) << 24; + register unsigned long b84 = (b & 0x000000ff000000ffL) << 24; + register unsigned long a73 = (a & 0x0000ff000000ff00L) << 8; + register unsigned long b73 = (b & 0x0000ff000000ff00L) << 8; + register unsigned long a62 = (a & 0x00ff000000ff0000L) >> 8; + register unsigned long b62 = (b & 0x00ff000000ff0000L) >> 8; + register unsigned long a51 = (a & 0xff000000ff000000L) >> 24; + register unsigned long b51 = (b & 0xff000000ff000000L) >> 24; + + a = (a84 | a73 | a62 | a51); + b = (b84 | b73 | b62 | b51); +#endif + + ACE_UINT32 c1 = static_cast (a >> 32); + ACE_UINT32 c2 = static_cast (a & 0xffffffff); + ACE_UINT32 c3 = static_cast (b >> 32); + ACE_UINT32 c4 = static_cast (b & 0xffffffff); + +#if defined (ACE_LITTLE_ENDIAN) + * reinterpret_cast (target + 0) = c2; + * reinterpret_cast (target + 4) = c1; + * reinterpret_cast (target + 8) = c4; + * reinterpret_cast (target + 12) = c3; +#else + * reinterpret_cast (target + 0) = c1; + * reinterpret_cast (target + 4) = c2; + * reinterpret_cast (target + 8) = c3; + * reinterpret_cast (target + 12) = c4; +#endif + orig += 16; + target += 16; + } + } + +#else /* ACE_SIZEOF_LONG != 8 */ + + while (orig < end) + { +#if defined (ACE_HAS_PENTIUM) && defined (__GNUG__) + register unsigned int a = + *reinterpret_cast (orig); + register unsigned int b = + *reinterpret_cast (orig + 4); + register unsigned int c = + *reinterpret_cast (orig + 8); + register unsigned int d = + *reinterpret_cast (orig + 12); + + asm ("bswap %1" : "=r" (a) : "0" (a)); + asm ("bswap %1" : "=r" (b) : "0" (b)); + asm ("bswap %1" : "=r" (c) : "0" (c)); + asm ("bswap %1" : "=r" (d) : "0" (d)); + + *reinterpret_cast (target) = a; + *reinterpret_cast (target + 4) = b; + *reinterpret_cast (target + 8) = c; + *reinterpret_cast (target + 12) = d; +#elif defined (ACE_HAS_PENTIUM) \ + && (defined (_MSC_VER) || defined (__BORLANDC__)) \ + && !defined (ACE_LACKS_INLINE_ASSEMBLY) + __asm mov eax, orig + __asm mov esi, target + __asm mov edx, [eax] + __asm mov ecx, 4[eax] + __asm mov ebx, 8[eax] + __asm mov eax, 12[eax] + __asm bswap edx + __asm bswap ecx + __asm bswap ebx + __asm bswap eax + __asm mov [esi], edx + __asm mov 4[esi], ecx + __asm mov 8[esi], ebx + __asm mov 12[esi], eax +#else + register ACE_UINT32 a = + * reinterpret_cast (orig); + register ACE_UINT32 b = + * reinterpret_cast (orig + 4); + register ACE_UINT32 c = + * reinterpret_cast (orig + 8); + register ACE_UINT32 d = + * reinterpret_cast (orig + 12); + + // Expect the optimizer reordering this A LOT. + // We leave it this way for clarity. + a = (a << 24) | ((a & 0xff00) << 8) | ((a & 0xff0000) >> 8) | (a >> 24); + b = (b << 24) | ((b & 0xff00) << 8) | ((b & 0xff0000) >> 8) | (b >> 24); + c = (c << 24) | ((c & 0xff00) << 8) | ((c & 0xff0000) >> 8) | (c >> 24); + d = (d << 24) | ((d & 0xff00) << 8) | ((d & 0xff0000) >> 8) | (d >> 24); + + * reinterpret_cast (target) = a; + * reinterpret_cast (target + 4) = b; + * reinterpret_cast (target + 8) = c; + * reinterpret_cast (target + 12) = d; +#endif + + orig += 16; + target += 16; + } + +#endif /* ACE_SIZEOF_LONG == 8 */ + + // (n & 3) == (n % 4). + switch (n & 3) { + case 3: + ACE_CDR::swap_4 (orig, target); + orig += 4; + target += 4; + case 2: + ACE_CDR::swap_4 (orig, target); + orig += 4; + target += 4; + case 1: + ACE_CDR::swap_4 (orig, target); + } +} + +// +// We don't benefit from unrolling in swap_8_array and swap_16_array +// (swap_8 and swap_16 are big enough). +// +void +ACE_CDR::swap_8_array (char const * orig, char* target, size_t n) +{ + // ACE_ASSERT(n > 0); The caller checks that n > 0 + + char const * const end = orig + 8*n; + while (orig < end) + { + swap_8 (orig, target); + orig += 8; + target += 8; + } +} + +void +ACE_CDR::swap_16_array (char const * orig, char* target, size_t n) +{ + // ACE_ASSERT(n > 0); The caller checks that n > 0 + + char const * const end = orig + 16*n; + while (orig < end) + { + swap_16 (orig, target); + orig += 16; + target += 16; + } +} + +void +ACE_CDR::mb_align (ACE_Message_Block *mb) +{ +#if !defined (ACE_CDR_IGNORE_ALIGNMENT) + char * const start = ACE_ptr_align_binary (mb->base (), + ACE_CDR::MAX_ALIGNMENT); +#else + char * const start = mb->base (); +#endif /* ACE_CDR_IGNORE_ALIGNMENT */ + mb->rd_ptr (start); + mb->wr_ptr (start); +} + +int +ACE_CDR::grow (ACE_Message_Block *mb, size_t minsize) +{ + size_t newsize = + ACE_CDR::first_size (minsize + ACE_CDR::MAX_ALIGNMENT); + + if (newsize <= mb->size ()) + return 0; + + ACE_Data_Block *db = + mb->data_block ()->clone_nocopy (0, newsize); + + if (db == 0) + return -1; + + // Do the equivalent of ACE_CDR::mb_align() here to avoid having + // to allocate an ACE_Message_Block on the stack thereby avoiding + // the manipulation of the data blocks reference count + size_t mb_len = mb->length (); + char *start = ACE_ptr_align_binary (db->base (), + ACE_CDR::MAX_ALIGNMENT); + + ACE_OS::memcpy (start, mb->rd_ptr (), mb_len); + mb->data_block (db); + + // Setting the data block on the mb resets the read and write + // pointers back to the beginning. We must set the rd_ptr to the + // aligned start and adjust the write pointer to the end + mb->rd_ptr (start); + mb->wr_ptr (start + mb_len); + + // Remove the DONT_DELETE flags from mb + mb->clr_self_flags (ACE_Message_Block::DONT_DELETE); + + return 0; +} + +size_t +ACE_CDR::total_length (const ACE_Message_Block* begin, + const ACE_Message_Block* end) +{ + size_t l = 0; + // Compute the total size. + for (const ACE_Message_Block *i = begin; + i != end; + i = i->cont ()) + l += i->length (); + return l; +} + +int +ACE_CDR::consolidate (ACE_Message_Block *dst, + const ACE_Message_Block *src) +{ + if (src == 0) + return 0; + + size_t const newsize = + ACE_CDR::first_size (ACE_CDR::total_length (src, 0) + + ACE_CDR::MAX_ALIGNMENT); + + if (dst->size (newsize) == -1) + return -1; + +#if !defined (ACE_CDR_IGNORE_ALIGNMENT) + // We must copy the contents of src into the new buffer, but + // respecting the alignment. + ptrdiff_t srcalign = + ptrdiff_t(src->rd_ptr ()) % ACE_CDR::MAX_ALIGNMENT; + ptrdiff_t dstalign = + ptrdiff_t(dst->rd_ptr ()) % ACE_CDR::MAX_ALIGNMENT; + ptrdiff_t offset = srcalign - dstalign; + if (offset < 0) + offset += ACE_CDR::MAX_ALIGNMENT; + dst->rd_ptr (static_cast (offset)); + dst->wr_ptr (dst->rd_ptr ()); +#endif /* ACE_CDR_IGNORE_ALIGNMENT */ + + for (const ACE_Message_Block* i = src; + i != 0; + i = i->cont ()) + { + // If the destination and source are the same, do not + // attempt to copy the data. Just update the write pointer. + if (dst->wr_ptr () != i->rd_ptr ()) + dst->copy (i->rd_ptr (), i->length ()); + else + dst->wr_ptr (i->length ()); + } + return 0; +} + +#if defined (NONNATIVE_LONGLONG) +bool +ACE_CDR::LongLong::operator== (const ACE_CDR::LongLong &rhs) const +{ + return this->h == rhs.h && this->l == rhs.l; +} + +bool +ACE_CDR::LongLong::operator!= (const ACE_CDR::LongLong &rhs) const +{ + return this->l != rhs.l || this->h != rhs.h; +} + +#endif /* NONNATIVE_LONGLONG */ + +#if defined (NONNATIVE_LONGDOUBLE) +ACE_CDR::LongDouble& +ACE_CDR::LongDouble::assign (const ACE_CDR::LongDouble::NativeImpl& rhs) +{ + ACE_OS::memset (this->ld, 0, sizeof (this->ld)); + + if (sizeof (rhs) == 8) + { +#if defined (ACE_LITTLE_ENDIAN) + static const size_t byte_zero = 1; + static const size_t byte_one = 0; + char rhs_ptr[16]; + ACE_CDR::swap_8 (reinterpret_cast (&rhs), rhs_ptr); +#else + static const size_t byte_zero = 0; + static const size_t byte_one = 1; + const char* rhs_ptr = reinterpret_cast (&rhs); +#endif + ACE_INT16 sign = static_cast ( + static_cast (rhs_ptr[0])) & 0x8000; + ACE_INT16 exponent = ((rhs_ptr[0] & 0x7f) << 4) | + ((rhs_ptr[1] >> 4) & 0xf); + const char* exp_ptr = reinterpret_cast (&exponent); + + // Infinity and NaN have an exponent of 0x7ff in 64-bit IEEE + if (exponent == 0x7ff) + { + exponent = 0x7fff; + } + else + { + exponent = (exponent - max_eleven_bit) + max_fifteen_bit; + } + exponent |= sign; + + // Store the sign bit and exponent + this->ld[0] = exp_ptr[byte_zero]; + this->ld[1] = exp_ptr[byte_one]; + + // Store the mantissa. In an 8 byte double, it is split by + // 4 bits (because of the 12 bits for sign and exponent), so + // we have to shift and or the rhs to get the right bytes. + size_t li = 2; + bool direction = true; + for (size_t ri = 1; ri < sizeof (rhs);) + { + if (direction) + { + this->ld[li] |= ((rhs_ptr[ri] << 4) & 0xf0); + direction = false; + ++ri; + } + else + { + this->ld[li] |= ((rhs_ptr[ri] >> 4) & 0xf); + direction = true; + ++li; + } + } +#if defined (ACE_LITTLE_ENDIAN) + ACE_OS::memcpy (rhs_ptr, this->ld, sizeof (this->ld)); + ACE_CDR::swap_16 (rhs_ptr, this->ld); +#endif + } + else + { + ACE_OS::memcpy(this->ld, + reinterpret_cast (&rhs), sizeof (rhs)); + } + return *this; +} + +ACE_CDR::LongDouble& +ACE_CDR::LongDouble::assign (const ACE_CDR::LongDouble& rhs) +{ + if (this != &rhs) + *this = rhs; + return *this; +} + +bool +ACE_CDR::LongDouble::operator== (const ACE_CDR::LongDouble &rhs) const +{ + return ACE_OS::memcmp (this->ld, rhs.ld, 16) == 0; +} + +bool +ACE_CDR::LongDouble::operator!= (const ACE_CDR::LongDouble &rhs) const +{ + return ACE_OS::memcmp (this->ld, rhs.ld, 16) != 0; +} + +ACE_CDR::LongDouble::operator ACE_CDR::LongDouble::NativeImpl () const +{ + ACE_CDR::LongDouble::NativeImpl ret = 0.0; + char* lhs_ptr = reinterpret_cast (&ret); + + if (sizeof (ret) == 8) + { +#if defined (ACE_LITTLE_ENDIAN) + static const size_t byte_zero = 1; + static const size_t byte_one = 0; + char copy[16]; + ACE_CDR::swap_16 (this->ld, copy); +#else + static const size_t byte_zero = 0; + static const size_t byte_one = 1; + const char* copy = this->ld; +#endif + ACE_INT16 exponent = 0; + char* exp_ptr = reinterpret_cast (&exponent); + exp_ptr[byte_zero] = copy[0]; + exp_ptr[byte_one] = copy[1]; + + ACE_INT16 sign = (exponent & 0x8000); + exponent &= 0x7fff; + + // Infinity and NaN have an exponent of 0x7fff in 128-bit IEEE + if (exponent == 0x7fff) + { + exponent = 0x7ff; + } + else + { + exponent = (exponent - max_fifteen_bit) + max_eleven_bit; + } + exponent = (exponent << 4) | sign; + + // Store the sign and exponent + lhs_ptr[0] = exp_ptr[byte_zero]; + lhs_ptr[1] = exp_ptr[byte_one]; + + // Store the mantissa. In an 8 byte double, it is split by + // 4 bits (because of the 12 bits for sign and exponent), so + // we have to shift and or the rhs to get the right bytes. + size_t li = 1; + bool direction = true; + for (size_t ri = 2; li < sizeof (ret);) { + if (direction) + { + lhs_ptr[li] |= ((copy[ri] >> 4) & 0xf); + direction = false; + ++li; + } + else + { + lhs_ptr[li] |= ((copy[ri] & 0xf) << 4); + direction = true; + ++ri; + } + } + +#if defined (ACE_LITTLE_ENDIAN) + ACE_CDR::swap_8 (lhs_ptr, lhs_ptr); +#endif + } + else + { + ACE_OS::memcpy(lhs_ptr, this->ld, sizeof (ret)); + } + + // This bit of code is unnecessary. However, this code is + // necessary to work around a bug in the gcc 4.1.1 optimizer. + ACE_CDR::LongDouble tmp; + tmp.assign (ret); + + return ret; +} +#endif /* NONNATIVE_LONGDOUBLE */ + +#if defined(_UNICOS) && !defined(_CRAYMPP) +// placeholders to get things compiling +ACE_CDR::Float::Float (void) +{ +} + +ACE_CDR::Float::Float (const float & /* init */) +{ +} + +ACE_CDR::Float & +ACE_CDR::Float::operator= (const float & /* rhs */) +{ + return *this; +} + +bool +ACE_CDR::Float::operator!= (const ACE_CDR::Float & /* rhs */) const +{ + return false; +} +#endif /* _UNICOS */ + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/CDR_Base.h b/dep/acelite/ace/CDR_Base.h new file mode 100644 index 00000000000..12b4a4953fd --- /dev/null +++ b/dep/acelite/ace/CDR_Base.h @@ -0,0 +1,382 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file CDR_Base.h + * + * $Id: CDR_Base.h 88488 2010-01-12 14:20:13Z olli $ + * + * ACE Common Data Representation (CDR) basic types. + * + * The current implementation assumes that the host has 1-byte, + * 2-byte and 4-byte integral types, and that it has single + * precision and double precision IEEE floats. + * Those assumptions are pretty good these days, with Crays being + * the only known exception. + * + * + * @author TAO version by + * @author Aniruddha Gokhale + * @author Carlos O'Ryan + * @author ACE version by + * @author Jeff Parsons + * @author Istvan Buki + */ +//============================================================================= + + +#ifndef ACE_CDR_BASE_H +#define ACE_CDR_BASE_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Basic_Types.h" +#include "ace/Default_Constants.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Stuff used by the ACE CDR classes. Watch these values... they're also used +// in the ACE_CDR Byte_Order enum below. +#if defined ACE_LITTLE_ENDIAN +# define ACE_CDR_BYTE_ORDER 1 +// little endian encapsulation byte order has value = 1 +#else /* ! ACE_LITTLE_ENDIAN */ +# define ACE_CDR_BYTE_ORDER 0 +// big endian encapsulation byte order has value = 0 +#endif /* ! ACE_LITTLE_ENDIAN */ + +class ACE_Message_Block; + +/** + * @class ACE_CDR + * + * @brief Keep constants and some routines common to both Output and + * Input CDR streams. + */ +class ACE_Export ACE_CDR +{ +public: + // = Constants defined by the CDR protocol. + // By defining as many of these constants as possible as enums we + // ensure they get inlined and avoid pointless static memory + // allocations. + + enum + { + // Note that some of these get reused as part of the standard + // binary format: unsigned is the same size as its signed cousin, + // float is LONG_SIZE, and double is LONGLONG_SIZE. + + OCTET_SIZE = 1, + SHORT_SIZE = 2, + LONG_SIZE = 4, + LONGLONG_SIZE = 8, + LONGDOUBLE_SIZE = 16, + + OCTET_ALIGN = 1, + SHORT_ALIGN = 2, + LONG_ALIGN = 4, + LONGLONG_ALIGN = 8, + /// @note the CORBA LongDouble alignment requirements do not + /// match its size... + LONGDOUBLE_ALIGN = 8, + + /// Maximal CDR 1.1 alignment: "quad precision" FP (i.e. "CDR::Long + /// double", size as above). + MAX_ALIGNMENT = 8, + + /// The default buffer size. + /** + * @todo We want to add options to control this + * default value, so this constant should be read as the default + * default value ;-) + */ + DEFAULT_BUFSIZE = ACE_DEFAULT_CDR_BUFSIZE, + + /// The buffer size grows exponentially until it reaches this size; + /// afterwards it grows linearly using the next constant + EXP_GROWTH_MAX = ACE_DEFAULT_CDR_EXP_GROWTH_MAX, + + /// Once exponential growth is ruled out the buffer size increases + /// in chunks of this size, note that this constants have the same + /// value right now, but it does not need to be so. + LINEAR_GROWTH_CHUNK = ACE_DEFAULT_CDR_LINEAR_GROWTH_CHUNK + }; + + /** + * @enum Byte_Order + * + * Defines values for the byte_order argument to ACE_OutputCDR and + * ACE_InputCDR. + */ + enum Byte_Order + { + /// Use big-endian order (also known as network byte order). + BYTE_ORDER_BIG_ENDIAN = 0, + /// Use little-endian order. + BYTE_ORDER_LITTLE_ENDIAN = 1, + /// Use whichever byte order is native to this machine. + BYTE_ORDER_NATIVE = ACE_CDR_BYTE_ORDER + }; + + /** + * Do byte swapping for each basic IDL type size. There exist only + * routines to put byte, halfword (2 bytes), word (4 bytes), + * doubleword (8 bytes) and quadword (16 byte); because those are + * the IDL basic type sizes. + */ + static void swap_2 (char const *orig, char *target); + static void swap_4 (char const *orig, char *target); + static void swap_8 (char const *orig, char *target); + static void swap_16 (char const *orig, char *target); + static void swap_2_array (char const *orig, + char *target, + size_t length); + static void swap_4_array (char const *orig, + char *target, + size_t length); + static void swap_8_array (char const *orig, + char *target, + size_t length); + static void swap_16_array (char const *orig, + char *target, + size_t length); + + /// Align the message block to ACE_CDR::MAX_ALIGNMENT, + /// set by the CORBA spec at 8 bytes. + static void mb_align (ACE_Message_Block *mb); + + /** + * Compute the size of the smallest buffer that can contain at least + * @a minsize bytes. + * To understand how a "best fit" is computed look at the + * algorithm in the code. + * Basically the buffers grow exponentially, up to a certain point, + * then the buffer size grows linearly. + * The advantage of this algorithm is that is rapidly grows to a + * large value, but does not explode at the end. + */ + static size_t first_size (size_t minsize); + + /// Compute not the smallest, but the second smallest buffer that + /// will fir @a minsize bytes. + static size_t next_size (size_t minsize); + + /** + * Increase the capacity of mb to contain at least @a minsize bytes. + * If @a minsize is zero the size is increased by an amount at least + * large enough to contain any of the basic IDL types. + * @retval -1 Failure + * @retval 0 Success. + */ + static int grow (ACE_Message_Block *mb, size_t minsize); + + /** + * Copy a message block chain into a single message block, + * preserving the alignment of the first message block of the + * original stream, not the following message blocks. + * @retval -1 Failure + * @retval 0 Success. + */ + static int consolidate (ACE_Message_Block *dst, + const ACE_Message_Block *src); + + static size_t total_length (const ACE_Message_Block *begin, + const ACE_Message_Block *end); + + /** + * @name Basic OMG IDL Types + * + * These types are for use in the CDR classes. The cleanest way to + * avoid complaints from all compilers is to define them all. + */ + //@{ + typedef bool Boolean; + typedef unsigned char Octet; + typedef char Char; + typedef ACE_WCHAR_T WChar; + typedef ACE_INT16 Short; + typedef ACE_UINT16 UShort; + typedef ACE_INT32 Long; + typedef ACE_UINT32 ULong; + typedef ACE_UINT64 ULongLong; + +# if (defined (_MSC_VER)) || (defined (__BORLANDC__)) + typedef __int64 LongLong; +# elif ACE_SIZEOF_LONG == 8 && !defined(_CRAYMPP) + typedef long LongLong; +# elif defined(__TANDEM) + typedef long long LongLong; +# elif ACE_SIZEOF_LONG_LONG == 8 && !defined (ACE_LACKS_LONGLONG_T) +# if defined (sun) && !defined (ACE_LACKS_U_LONGLONG_T) + // sun #defines u_longlong_t, maybe other platforms do also. + // Use it, at least with g++, so that its -pedantic doesn't + // complain about no ANSI C++ long long. + typedef longlong_t LongLong; +# else + typedef long long LongLong; +# endif /* sun */ +# else /* no native 64 bit integer type */ +# define NONNATIVE_LONGLONG + struct ACE_Export LongLong + { +# if defined (ACE_BIG_ENDIAN) + ACE_CDR::Long h; + ACE_CDR::Long l; +# else + ACE_CDR::Long l; + ACE_CDR::Long h; +# endif /* ! ACE_BIG_ENDIAN */ + + /** + * @name Overloaded Relation Operators. + * + * The canonical comparison operators. + */ + //@{ + bool operator== (const LongLong &rhs) const; + bool operator!= (const LongLong &rhs) const; + //@} + }; +# endif /* no native 64 bit integer type */ + +# if defined (NONNATIVE_LONGLONG) +# define ACE_CDR_LONGLONG_INITIALIZER {0,0} +# else +# define ACE_CDR_LONGLONG_INITIALIZER 0 +# endif /* NONNATIVE_LONGLONG */ + +# if ACE_SIZEOF_FLOAT == 4 + typedef float Float; +# else /* ACE_SIZEOF_FLOAT != 4 */ + struct Float + { +# if ACE_SIZEOF_INT == 4 + // Use unsigned int to get word alignment. + unsigned int f; +# else /* ACE_SIZEOF_INT != 4 */ + // Applications will probably have trouble with this. + char f[4]; +# if defined(_UNICOS) && !defined(_CRAYMPP) + Float (void); + Float (const float &init); + Float & operator= (const float &rhs); + bool operator!= (const Float &rhs) const; +# endif /* _UNICOS */ +# endif /* ACE_SIZEOF_INT != 4 */ + }; +# endif /* ACE_SIZEOF_FLOAT != 4 */ + +# if ACE_SIZEOF_DOUBLE == 8 + typedef double Double; +# else /* ACE_SIZEOF_DOUBLE != 8 */ + struct Double + { +# if ACE_SIZEOF_LONG == 8 + // Use u long to get word alignment. + unsigned long f; +# else /* ACE_SIZEOF_INT != 8 */ + // Applications will probably have trouble with this. + char f[8]; +# endif /* ACE_SIZEOF_INT != 8 */ + }; +# endif /* ACE_SIZEOF_DOUBLE != 8 */ + + // 94-9-32 Appendix A defines a 128 bit floating point "long + // double" data type, with greatly extended precision and four + // more bits of exponent (compared to "double"). This is an IDL + // extension, not yet standard. + +# if ACE_SIZEOF_LONG_DOUBLE == 16 + typedef long double LongDouble; +# define ACE_CDR_LONG_DOUBLE_INITIALIZER 0 +# define ACE_CDR_LONG_DOUBLE_ASSIGNMENT(LHS, RHS) LHS = RHS +# else +# define NONNATIVE_LONGDOUBLE +# define ACE_CDR_LONG_DOUBLE_INITIALIZER {{0}} +# define ACE_CDR_LONG_DOUBLE_ASSIGNMENT(LHS, RHS) LHS.assign (RHS) + struct ACE_Export LongDouble + { + // VxWorks' compiler (gcc 2.96) gets confused by the operator long + // double, so we avoid using long double as the NativeImpl. + // Linux's x86 long double format (12 or 16 bytes) is incompatible + // with Windows, Solaris, AIX, MacOS X and HP-UX (and probably others) + // long double format (8 or 16 bytes). If you need 32-bit Linux to + // inter-operate with 64-bit Linux you will want to define this + // macro to 0 so that "long double" is used. Otherwise, do not define + // this macro. +# if defined (ACE_CDR_IMPLEMENT_WITH_NATIVE_DOUBLE) && \ + (ACE_CDR_IMPLEMENT_WITH_NATIVE_DOUBLE == 1) + typedef double NativeImpl; +# else + typedef long double NativeImpl; +# endif /* ACE_CDR_IMPLEMENT_WITH_NATIVE_DOUBLE==1 */ + + char ld[16]; + + LongDouble& assign (const NativeImpl& rhs); + LongDouble& assign (const LongDouble& rhs); + + bool operator== (const LongDouble &rhs) const; + bool operator!= (const LongDouble &rhs) const; + + LongDouble& operator*= (const NativeImpl rhs) { + return this->assign (static_cast (*this) * rhs); + } + LongDouble& operator/= (const NativeImpl rhs) { + return this->assign (static_cast (*this) / rhs); + } + LongDouble& operator+= (const NativeImpl rhs) { + return this->assign (static_cast (*this) + rhs); + } + LongDouble& operator-= (const NativeImpl rhs) { + return this->assign (static_cast (*this) - rhs); + } + LongDouble& operator++ () { + return this->assign (static_cast (*this) + 1); + } + LongDouble& operator-- () { + return this->assign (static_cast (*this) - 1); + } + LongDouble operator++ (int) { + LongDouble ldv = *this; + this->assign (static_cast (*this) + 1); + return ldv; + } + LongDouble operator-- (int) { + LongDouble ldv = *this; + this->assign (static_cast (*this) - 1); + return ldv; + } + + operator NativeImpl () const; + }; +# endif /* ACE_SIZEOF_LONG_DOUBLE != 16 */ + + //@} + +#if !defined (ACE_CDR_GIOP_MAJOR_VERSION) +# define ACE_CDR_GIOP_MAJOR_VERSION 1 +#endif /*ACE_CDR_GIOP_MAJOR_VERSION */ + +#if !defined (ACE_CDR_GIOP_MINOR_VERSION) +# define ACE_CDR_GIOP_MINOR_VERSION 2 +#endif /* ACE_CDR_GIOP_MINOR_VERSION */ +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +# include "ace/CDR_Base.inl" +#endif /* __ACE_INLINE__ */ + + +#include /**/ "ace/post.h" + +#endif /* ACE_CDR_BASE_H */ diff --git a/dep/acelite/ace/CDR_Base.inl b/dep/acelite/ace/CDR_Base.inl new file mode 100644 index 00000000000..85373170af7 --- /dev/null +++ b/dep/acelite/ace/CDR_Base.inl @@ -0,0 +1,255 @@ +// -*- C++ -*- +// +// $Id: CDR_Base.inl 80826 2008-03-04 14:51:23Z wotte $ + +#if defined (ACE_HAS_INTRINSIC_BYTESWAP) +// Take advantage of MSVC++ byte swapping compiler intrinsics (found +// in ). +# pragma intrinsic (_byteswap_ushort, _byteswap_ulong, _byteswap_uint64) +#endif /* ACE_HAS_INTRINSIC_BYTESWAP */ + +#if defined (ACE_HAS_BSWAP_16) || defined (ACE_HAS_BSWAP_32) || defined (ACE_HAS_BSWAP_64) +# include "ace/os_include/os_byteswap.h" +#endif + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// +// The ACE_CDR::swap_X and ACE_CDR::swap_X_array routines are broken +// in 5 cases for optimization: +// +// * MSVC++ 7.1 or better +// => Compiler intrinsics +// +// * AMD64 CPU + gnu g++ +// => gcc amd64 inline assembly. +// +// * x86 Pentium CPU + gnu g++ +// (ACE_HAS_PENTIUM && __GNUG__) +// => gcc x86 inline assembly. +// +// * x86 Pentium CPU and (_MSC_VER) or BORLAND C++) +// (ACE_HAS_PENTIUM && ( _MSC_VER || __BORLANDC__ ) +// => MSC x86 inline assembly. +// +// * 64 bit architecture +// (ACE_SIZEOF_LONG == 8) +// => shift/masks using 64bit words. +// +// * default +// (none of the above) +// => shift/masks using 32bit words. +// +// +// Some things you could find useful to know if you intend to mess +// with this optimizations for swaps: +// +// * MSVC++ don't assume register values are conserved between +// statements. So you can clobber any register you want, +// whenever you want (well not *anyone* really, see manual). +// The MSVC++ optimizer will try to pick different registers +// for the C++ statements sorrounding your asm block, and if +// it's not possible will use the stack. +// +// * If you clobber registers with asm statements in gcc, you +// better do it in an asm-only function, or save/restore them +// before/after in the stack. If not, sorrounding C statements +// could end using the same registers and big-badda-bum (been +// there, done that...). The big-badda-bum could happen *even +// if you specify the clobbered register in your asm's*. +// Even better, use gcc asm syntax for detecting the register +// asigned to a certain variable so you don't have to clobber any +// register directly. +// + +ACE_INLINE void +ACE_CDR::swap_2 (const char *orig, char* target) +{ +#if defined (ACE_HAS_INTRINSIC_BYTESWAP) + // Take advantage of MSVC++ compiler intrinsic byte swapping + // function. + *reinterpret_cast (target) = + _byteswap_ushort (*reinterpret_cast (orig)); +#elif defined (ACE_HAS_BSWAP16) + *reinterpret_cast (target) = + bswap16 (*reinterpret_cast (orig)); +#elif defined (ACE_HAS_BSWAP_16) + *reinterpret_cast (target) = + bswap_16 (*reinterpret_cast (orig)); +#elif defined(ACE_HAS_INTEL_ASSEMBLY) + unsigned short a = + *reinterpret_cast (orig); + asm( "rolw $8, %0" : "=r" (a) : "0" (a) ); + *reinterpret_cast (target) = a; +#elif defined (ACE_HAS_PENTIUM) \ + && (defined(_MSC_VER) || defined(__BORLANDC__)) \ + && !defined(ACE_LACKS_INLINE_ASSEMBLY) + __asm mov ebx, orig; + __asm mov ecx, target; + __asm mov ax, [ebx]; + __asm rol ax, 8; + __asm mov [ecx], ax; +#else + register ACE_UINT16 usrc = * reinterpret_cast (orig); + register ACE_UINT16* udst = reinterpret_cast (target); + *udst = (usrc << 8) | (usrc >> 8); +#endif /* ACE_HAS_PENTIUM */ +} + +ACE_INLINE void +ACE_CDR::swap_4 (const char* orig, char* target) +{ +#if defined (ACE_HAS_INTRINSIC_BYTESWAP) + // Take advantage of MSVC++ compiler intrinsic byte swapping + // function. + *reinterpret_cast (target) = + _byteswap_ulong (*reinterpret_cast (orig)); +#elif defined (ACE_HAS_BSWAP32) + *reinterpret_cast (target) = + bswap32 (*reinterpret_cast (orig)); +#elif defined (ACE_HAS_BSWAP_32) + *reinterpret_cast (target) = + bswap_32 (*reinterpret_cast (orig)); +#elif defined(ACE_HAS_INTEL_ASSEMBLY) + // We have ACE_HAS_PENTIUM, so we know the sizeof's. + register unsigned int j = + *reinterpret_cast (orig); + asm ("bswap %1" : "=r" (j) : "0" (j)); + *reinterpret_cast (target) = j; +#elif defined(ACE_HAS_PENTIUM) \ + && (defined(_MSC_VER) || defined(__BORLANDC__)) \ + && !defined(ACE_LACKS_INLINE_ASSEMBLY) + __asm mov ebx, orig; + __asm mov ecx, target; + __asm mov eax, [ebx]; + __asm bswap eax; + __asm mov [ecx], eax; +#else + register ACE_UINT32 x = * reinterpret_cast (orig); + x = (x << 24) | ((x & 0xff00) << 8) | ((x & 0xff0000) >> 8) | (x >> 24); + * reinterpret_cast (target) = x; +#endif /* ACE_HAS_INTRINSIC_BYTESWAP */ +} + +ACE_INLINE void +ACE_CDR::swap_8 (const char* orig, char* target) +{ +#if defined (ACE_HAS_INTRINSIC_BYTESWAP) + // Take advantage of MSVC++ compiler intrinsic byte swapping + // function. + *reinterpret_cast (target) = + _byteswap_uint64 (*reinterpret_cast (orig)); +#elif defined (ACE_HAS_BSWAP64) + *reinterpret_cast (target) = + bswap64 (*reinterpret_cast (orig)); +#elif defined (ACE_HAS_BSWAP_64) + *reinterpret_cast (target) = + bswap_64 (*reinterpret_cast (orig)); +#elif (defined (__amd64__) || defined (__x86_64__)) && defined(__GNUG__) + register unsigned long x = + * reinterpret_cast (orig); + asm ("bswapq %1" : "=r" (x) : "0" (x)); + *reinterpret_cast (target) = x; +#elif defined(ACE_HAS_PENTIUM) && defined(__GNUG__) + register unsigned int i = + *reinterpret_cast (orig); + register unsigned int j = + *reinterpret_cast (orig + 4); + asm ("bswap %1" : "=r" (i) : "0" (i)); + asm ("bswap %1" : "=r" (j) : "0" (j)); + *reinterpret_cast (target + 4) = i; + *reinterpret_cast (target) = j; +#elif defined(ACE_HAS_PENTIUM) \ + && (defined(_MSC_VER) || defined(__BORLANDC__)) \ + && !defined(ACE_LACKS_INLINE_ASSEMBLY) + __asm mov ecx, orig; + __asm mov edx, target; + __asm mov eax, [ecx]; + __asm mov ebx, 4[ecx]; + __asm bswap eax; + __asm bswap ebx; + __asm mov 4[edx], eax; + __asm mov [edx], ebx; +#elif ACE_SIZEOF_LONG == 8 + // 64 bit architecture. + register unsigned long x = + * reinterpret_cast (orig); + register unsigned long x84 = (x & 0x000000ff000000ffUL) << 24; + register unsigned long x73 = (x & 0x0000ff000000ff00UL) << 8; + register unsigned long x62 = (x & 0x00ff000000ff0000UL) >> 8; + register unsigned long x51 = (x & 0xff000000ff000000UL) >> 24; + x = (x84 | x73 | x62 | x51); + x = (x << 32) | (x >> 32); + *reinterpret_cast (target) = x; +#else + register ACE_UINT32 x = + * reinterpret_cast (orig); + register ACE_UINT32 y = + * reinterpret_cast (orig + 4); + x = (x << 24) | ((x & 0xff00) << 8) | ((x & 0xff0000) >> 8) | (x >> 24); + y = (y << 24) | ((y & 0xff00) << 8) | ((y & 0xff0000) >> 8) | (y >> 24); + * reinterpret_cast (target) = y; + * reinterpret_cast (target + 4) = x; +#endif /* ACE_HAS_INTRINSIC_BYTESWAP */ +} + +ACE_INLINE void +ACE_CDR::swap_16 (const char* orig, char* target) +{ + swap_8 (orig + 8, target); + swap_8 (orig, target + 8); +} + +ACE_INLINE size_t +ACE_CDR::first_size (size_t minsize) +{ + if (minsize == 0) + return ACE_CDR::DEFAULT_BUFSIZE; + + size_t newsize = ACE_CDR::DEFAULT_BUFSIZE; + while (newsize < minsize) + { + if (newsize < ACE_CDR::EXP_GROWTH_MAX) + { + // We grow exponentially at the beginning, this is fast and + // reduces the number of allocations. + + // Quickly multiply by two using a bit shift. This is + // guaranteed to work since the variable is an unsigned + // integer. + newsize <<= 1; + } + else + { + // but continuing with exponential growth can result in over + // allocations and easily yield an allocation failure. + // So we grow linearly when the buffer is too big. + newsize += ACE_CDR::LINEAR_GROWTH_CHUNK; + } + } + return newsize; +} + +ACE_INLINE size_t +ACE_CDR::next_size (size_t minsize) +{ + size_t newsize = ACE_CDR::first_size (minsize); + + if (newsize == minsize) + { + // If necessary increment the size + if (newsize < ACE_CDR::EXP_GROWTH_MAX) + // Quickly multiply by two using a bit shift. This is + // guaranteed to work since the variable is an unsigned + // integer. + newsize <<= 1; + else + newsize += ACE_CDR::LINEAR_GROWTH_CHUNK; + } + + return newsize; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +// **************************************************************** diff --git a/dep/acelite/ace/CDR_Size.cpp b/dep/acelite/ace/CDR_Size.cpp new file mode 100644 index 00000000000..96970927037 --- /dev/null +++ b/dep/acelite/ace/CDR_Size.cpp @@ -0,0 +1,262 @@ +#include "ace/CDR_Size.h" +#include "ace/SString.h" +#include "ace/OS_Memory.h" +#include "ace/Truncate.h" + +#if !defined (__ACE_INLINE__) +# include "ace/CDR_Size.inl" +#endif /* ! __ACE_INLINE__ */ + +ACE_RCSID (ace, + CDR_Size, + "$Id: CDR_Size.cpp 82559 2008-08-07 20:23:07Z parsons $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_CDR::Boolean +ACE_SizeCDR::write_wchar (ACE_CDR::WChar x) +{ + // Note: translator framework is not supported. + // + if (ACE_OutputCDR::wchar_maxbytes () == 0) + { + errno = EACCES; + return (this->good_bit_ = false); + } + + if (static_cast (major_version_) == 1 + && static_cast (minor_version_) == 2) + { + ACE_CDR::Octet len = + static_cast (ACE_OutputCDR::wchar_maxbytes ()); + + if (this->write_1 (&len)) + { + if (ACE_OutputCDR::wchar_maxbytes () == sizeof(ACE_CDR::WChar)) + { + return + this->write_octet_array ( + reinterpret_cast (&x), + static_cast (len)); + } + else + { + if (ACE_OutputCDR::wchar_maxbytes () == 2) + { + ACE_CDR::Short sx = static_cast (x); + return + this->write_octet_array ( + reinterpret_cast (&sx), + static_cast (len)); + } + else + { + ACE_CDR::Octet ox = static_cast (x); + return + this->write_octet_array ( + reinterpret_cast (&ox), + static_cast (len)); + } + } + } + } + else if (static_cast (minor_version_) == 0) + { // wchar is not allowed with GIOP 1.0. + errno = EINVAL; + return (this->good_bit_ = false); + } + + if (ACE_OutputCDR::wchar_maxbytes () == sizeof (ACE_CDR::WChar)) + { + const void *temp = &x; + return this->write_4 (reinterpret_cast (temp)); + } + else if (ACE_OutputCDR::wchar_maxbytes () == 2) + { + ACE_CDR::Short sx = static_cast (x); + return this->write_2 (reinterpret_cast (&sx)); + } + + ACE_CDR::Octet ox = static_cast (x); + return this->write_1 (reinterpret_cast (&ox)); +} + +ACE_CDR::Boolean +ACE_SizeCDR::write_string (ACE_CDR::ULong len, + const ACE_CDR::Char *x) +{ + // Note: translator framework is not supported. + // + if (len != 0) + { + if (this->write_ulong (len + 1)) + return this->write_char_array (x, len + 1); + } + else + { + // Be nice to programmers: treat nulls as empty strings not + // errors. (OMG-IDL supports languages that don't use the C/C++ + // notion of null v. empty strings; nulls aren't part of the OMG-IDL + // string model.) + if (this->write_ulong (1)) + return this->write_char (0); + } + + return (this->good_bit_ = false); +} + +ACE_CDR::Boolean +ACE_SizeCDR::write_string (const ACE_CString &x) +{ + // @@ Leave this method in here, not the `.i' file so that we don't + // have to unnecessarily pull in the `ace/SString.h' header. + return this->write_string (static_cast (x.length ()), + x.c_str()); +} + +ACE_CDR::Boolean +ACE_SizeCDR::write_wstring (ACE_CDR::ULong len, + const ACE_CDR::WChar *x) +{ + // Note: translator framework is not supported. + // + if (ACE_OutputCDR::wchar_maxbytes () == 0) + { + errno = EACCES; + return (this->good_bit_ = false); + } + + if (static_cast (this->major_version_) == 1 + && static_cast (this->minor_version_) == 2) + { + if (x != 0) + { + //In GIOP 1.2 the length field contains the number of bytes + //the wstring occupies rather than number of wchars + //Taking sizeof might not be a good way! This is a temporary fix. + ACE_CDR::Boolean good_ulong = + this->write_ulong ( + ACE_Utils::truncate_cast ( + ACE_OutputCDR::wchar_maxbytes () * len)); + + if (good_ulong) + { + return this->write_wchar_array (x, len); + } + } + else + { + //In GIOP 1.2 zero length wstrings are legal + return this->write_ulong (0); + } + } + + else + if (x != 0) + { + if (this->write_ulong (len + 1)) + return this->write_wchar_array (x, len + 1); + } + else if (this->write_ulong (1)) + return this->write_wchar (0); + return (this->good_bit_ = false); +} + +ACE_CDR::Boolean +ACE_SizeCDR::write_1 (const ACE_CDR::Octet *) +{ + this->adjust (1); + return true; +} + +ACE_CDR::Boolean +ACE_SizeCDR::write_2 (const ACE_CDR::UShort *) +{ + this->adjust (ACE_CDR::SHORT_SIZE); + return true; +} + +ACE_CDR::Boolean +ACE_SizeCDR::write_4 (const ACE_CDR::ULong *) +{ + this->adjust (ACE_CDR::LONG_SIZE); + return true; +} + +ACE_CDR::Boolean +ACE_SizeCDR::write_8 (const ACE_CDR::ULongLong *) +{ + this->adjust (ACE_CDR::LONGLONG_SIZE); + return true; +} + +ACE_CDR::Boolean +ACE_SizeCDR::write_16 (const ACE_CDR::LongDouble *) +{ + this->adjust (ACE_CDR::LONGDOUBLE_SIZE, + ACE_CDR::LONGDOUBLE_ALIGN); + return true; +} + +ACE_CDR::Boolean +ACE_SizeCDR::write_wchar_array_i (const ACE_CDR::WChar *, + ACE_CDR::ULong length) +{ + if (length == 0) + return true; + + size_t const align = (ACE_OutputCDR::wchar_maxbytes () == 2) ? + ACE_CDR::SHORT_ALIGN : + ACE_CDR::OCTET_ALIGN; + + this->adjust (ACE_OutputCDR::wchar_maxbytes () * length, align); + return true; +} + + +ACE_CDR::Boolean +ACE_SizeCDR::write_array (const void *, + size_t size, + size_t align, + ACE_CDR::ULong length) +{ + if (length == 0) + return true; + + this->adjust (size * length, align); + return true; +} + +ACE_CDR::Boolean +ACE_SizeCDR::write_boolean_array (const ACE_CDR::Boolean*, + ACE_CDR::ULong length) +{ + this->adjust (length, 1); + return true; +} + +void +ACE_SizeCDR::adjust (size_t size) +{ + adjust (size, size); +} + +void +ACE_SizeCDR::adjust (size_t size, + size_t align) +{ +#if !defined (ACE_LACKS_CDR_ALIGNMENT) + const size_t offset = ACE_align_binary (size_, align) - size_; + size_ += offset; +#endif /* ACE_LACKS_CDR_ALIGNMENT */ + size_ += size; +} + +ACE_CDR::Boolean +operator<< (ACE_SizeCDR &ss, const ACE_CString &x) +{ + ss.write_string (x); + return ss.good_bit (); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/CDR_Size.h b/dep/acelite/ace/CDR_Size.h new file mode 100644 index 00000000000..a0b3c462ca8 --- /dev/null +++ b/dep/acelite/ace/CDR_Size.h @@ -0,0 +1,241 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file CDR_Size.h + * + * $Id: CDR_Size.h 80826 2008-03-04 14:51:23Z wotte $ + * + * + * ACE Common Data Representation (CDR) size-calculating stream. + * + * + * The current implementation assumes that the host has 1-byte, + * 2-byte and 4-byte integral types, and that it has single + * precision and double precision IEEE floats. + * Those assumptions are pretty good these days, with Crays beign + * the only known exception. + * + * + * @author Boris Kolpackov + * + */ +//============================================================================= + +#ifndef ACE_CDR_SIZE_H +#define ACE_CDR_SIZE_H + +#include /**/ "ace/pre.h" + +#include "ace/CDR_Base.h" +#include "ace/CDR_Stream.h" // for ACE_OutputCDR::from_* + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/SStringfwd.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_SizeCDR + * + * @brief A CDR stream for calculating size of the representation. + * + */ +class ACE_Export ACE_SizeCDR +{ +public: + /// Default constructor. + ACE_SizeCDR (ACE_CDR::Octet major_version = ACE_CDR_GIOP_MAJOR_VERSION, + ACE_CDR::Octet minor_version = ACE_CDR_GIOP_MINOR_VERSION); + + /// Returns @c false if an error has ocurred. + bool good_bit (void) const; + + + /// Reset current size. + void reset (void); + + + /// Return current size. + size_t total_length (void) const; + + + // Return 0 on failure and 1 on success. + //@{ @name Size-calculating pseudo-write operations + ACE_CDR::Boolean write_boolean (ACE_CDR::Boolean x); + ACE_CDR::Boolean write_char (ACE_CDR::Char x); + ACE_CDR::Boolean write_wchar (ACE_CDR::WChar x); + ACE_CDR::Boolean write_octet (ACE_CDR::Octet x); + ACE_CDR::Boolean write_short (ACE_CDR::Short x); + ACE_CDR::Boolean write_ushort (ACE_CDR::UShort x); + ACE_CDR::Boolean write_long (ACE_CDR::Long x); + ACE_CDR::Boolean write_ulong (ACE_CDR::ULong x); + ACE_CDR::Boolean write_longlong (const ACE_CDR::LongLong &x); + ACE_CDR::Boolean write_ulonglong (const ACE_CDR::ULongLong &x); + ACE_CDR::Boolean write_float (ACE_CDR::Float x); + ACE_CDR::Boolean write_double (const ACE_CDR::Double &x); + ACE_CDR::Boolean write_longdouble (const ACE_CDR::LongDouble &x); + + /// For string we offer methods that accept a precomputed length. + ACE_CDR::Boolean write_string (const ACE_CDR::Char *x); + ACE_CDR::Boolean write_string (ACE_CDR::ULong len, + const ACE_CDR::Char *x); + ACE_CDR::Boolean write_string (const ACE_CString &x); + ACE_CDR::Boolean write_wstring (const ACE_CDR::WChar *x); + ACE_CDR::Boolean write_wstring (ACE_CDR::ULong length, + const ACE_CDR::WChar *x); + //@} + + /// @note the portion written starts at and ends + /// at . + /// The length is *NOT* stored into the CDR stream. + //@{ @name Array write operations + ACE_CDR::Boolean write_boolean_array (const ACE_CDR::Boolean *x, + ACE_CDR::ULong length); + ACE_CDR::Boolean write_char_array (const ACE_CDR::Char *x, + ACE_CDR::ULong length); + ACE_CDR::Boolean write_wchar_array (const ACE_CDR::WChar* x, + ACE_CDR::ULong length); + ACE_CDR::Boolean write_octet_array (const ACE_CDR::Octet* x, + ACE_CDR::ULong length); + ACE_CDR::Boolean write_short_array (const ACE_CDR::Short *x, + ACE_CDR::ULong length); + ACE_CDR::Boolean write_ushort_array (const ACE_CDR::UShort *x, + ACE_CDR::ULong length); + ACE_CDR::Boolean write_long_array (const ACE_CDR::Long *x, + ACE_CDR::ULong length); + ACE_CDR::Boolean write_ulong_array (const ACE_CDR::ULong *x, + ACE_CDR::ULong length); + ACE_CDR::Boolean write_longlong_array (const ACE_CDR::LongLong* x, + ACE_CDR::ULong length); + ACE_CDR::Boolean write_ulonglong_array (const ACE_CDR::ULongLong *x, + ACE_CDR::ULong length); + ACE_CDR::Boolean write_float_array (const ACE_CDR::Float *x, + ACE_CDR::ULong length); + ACE_CDR::Boolean write_double_array (const ACE_CDR::Double *x, + ACE_CDR::ULong length); + ACE_CDR::Boolean write_longdouble_array (const ACE_CDR::LongDouble* x, + ACE_CDR::ULong length); + + /// + /// Adjust to @a size and count octets. + void adjust (size_t size); + + /// As above, but now the size and alignment requirements may be + /// different. + void adjust (size_t size, + size_t align); + +private: + /// disallow copying... + ACE_SizeCDR (const ACE_SizeCDR& rhs); + ACE_SizeCDR& operator= (const ACE_SizeCDR& rhs); + + ACE_CDR::Boolean write_1 (const ACE_CDR::Octet *x); + ACE_CDR::Boolean write_2 (const ACE_CDR::UShort *x); + ACE_CDR::Boolean write_4 (const ACE_CDR::ULong *x); + ACE_CDR::Boolean write_8 (const ACE_CDR::ULongLong *x); + ACE_CDR::Boolean write_16 (const ACE_CDR::LongDouble *x); + + /** + * write an array of @a length elements, each of @a size bytes and the + * start aligned at a multiple of . The elements are assumed + * to be packed with the right alignment restrictions. It is mostly + * designed for buffers of the basic types. + * + * This operation uses ; as explained above it is expected + * that using assignment is faster that for one element, + * but for several elements should be more efficient, it + * could be interesting to find the break even point and optimize + * for that case, but that would be too platform dependent. + */ + ACE_CDR::Boolean write_array (const void *x, + size_t size, + size_t align, + ACE_CDR::ULong length); + + + ACE_CDR::Boolean write_wchar_array_i (const ACE_CDR::WChar* x, + ACE_CDR::ULong length); + +private: + /// Set to false when an error ocurrs. + bool good_bit_; + + /// Current size. + size_t size_; + +protected: + /// GIOP version information + ACE_CDR::Octet major_version_; + ACE_CDR::Octet minor_version_; +}; + +// @@ This operator should not be inlined since they force SString.h +// to be included in this header. +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, + const ACE_CString &x); + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +# include "ace/CDR_Size.inl" +#else /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Not used by CORBA or TAO +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, + ACE_CDR::Char x); + +// CDR size-calculating output operators for primitive types + +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, + ACE_CDR::Short x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, + ACE_CDR::UShort x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, + ACE_CDR::Long x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, + ACE_CDR::ULong x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, + ACE_CDR::LongLong x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, + ACE_CDR::ULongLong x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR& ss, + ACE_CDR::LongDouble x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, + ACE_CDR::Float x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, + ACE_CDR::Double x); + +// CDR size-calculating output operator from helper classes + +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, + ACE_OutputCDR::from_boolean x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, + ACE_OutputCDR::from_char x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, + ACE_OutputCDR::from_wchar x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, + ACE_OutputCDR::from_octet x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, + ACE_OutputCDR::from_string x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, + ACE_OutputCDR::from_wstring x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, + const ACE_CDR::Char* x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, + const ACE_CDR::WChar* x); + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* __ACE_INLINE__ */ + + +#include /**/ "ace/post.h" + +#endif /* ACE_CDR_SIZE_H */ diff --git a/dep/acelite/ace/CDR_Size.inl b/dep/acelite/ace/CDR_Size.inl new file mode 100644 index 00000000000..4ea81523faf --- /dev/null +++ b/dep/acelite/ace/CDR_Size.inl @@ -0,0 +1,424 @@ +// -*- C++ -*- +// +// $Id: CDR_Size.inl 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/OS_NS_string.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE +ACE_SizeCDR::ACE_SizeCDR (ACE_CDR::Octet major_version, + ACE_CDR::Octet minor_version) + : good_bit_ (true), + size_ (0), + major_version_ (major_version), + minor_version_ (minor_version) +{ +} + +ACE_INLINE bool +ACE_SizeCDR::good_bit (void) const +{ + return this->good_bit_; +} + +ACE_INLINE void +ACE_SizeCDR::reset (void) +{ + this->size_ = 0; +} + +ACE_INLINE size_t +ACE_SizeCDR::total_length (void) const +{ + return this->size_; +} + + +// Encode the CDR stream. + +ACE_INLINE ACE_CDR::Boolean +ACE_SizeCDR::write_octet (ACE_CDR::Octet x) +{ + return this->write_1 (reinterpret_cast (&x)); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_SizeCDR::write_boolean (ACE_CDR::Boolean x) +{ + return (ACE_CDR::Boolean) this->write_octet (x ? (ACE_CDR::Octet) 1 : (ACE_CDR::Octet) 0); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_SizeCDR::write_char (ACE_CDR::Char x) +{ + // Note: translator framework is not supported. + // + return this->write_1 (reinterpret_cast (&x)); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_SizeCDR::write_short (ACE_CDR::Short x) +{ + return this->write_2 (reinterpret_cast (&x)); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_SizeCDR::write_ushort (ACE_CDR::UShort x) +{ + return this->write_2 (reinterpret_cast (&x)); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_SizeCDR::write_long (ACE_CDR::Long x) +{ + return this->write_4 (reinterpret_cast (&x)); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_SizeCDR::write_ulong (ACE_CDR::ULong x) +{ + return this->write_4 (reinterpret_cast (&x)); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_SizeCDR::write_longlong (const ACE_CDR::LongLong &x) +{ + return this->write_8 (reinterpret_cast (&x)); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_SizeCDR::write_ulonglong (const ACE_CDR::ULongLong &x) +{ + const void *temp = &x; + return this->write_8 (reinterpret_cast (temp)); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_SizeCDR::write_float (ACE_CDR::Float x) +{ + const void *temp = &x; + return this->write_4 (reinterpret_cast (temp)); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_SizeCDR::write_double (const ACE_CDR::Double &x) +{ + const void *temp = &x; + return this->write_8 (reinterpret_cast (temp)); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_SizeCDR::write_longdouble (const ACE_CDR::LongDouble &x) +{ + const void *temp = &x; + return this->write_16 (reinterpret_cast (temp)); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_SizeCDR::write_string (const ACE_CDR::Char *x) +{ + if (x != 0) + { + const ACE_CDR::ULong len = + static_cast (ACE_OS::strlen (x)); + return this->write_string (len, x); + } + return this->write_string (0, 0); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_SizeCDR::write_wstring (const ACE_CDR::WChar *x) +{ + if (x != 0) + { + ACE_CDR::ULong len = + static_cast (ACE_OS::strlen (x)); + return this->write_wstring (len, x); + } + return this->write_wstring (0, 0); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_SizeCDR::write_char_array (const ACE_CDR::Char *x, + ACE_CDR::ULong length) +{ + // Note: translator framework is not supported. + // + return this->write_array (x, + ACE_CDR::OCTET_SIZE, + ACE_CDR::OCTET_ALIGN, + length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_SizeCDR::write_wchar_array (const ACE_CDR::WChar* x, + ACE_CDR::ULong length) +{ + // Note: translator framework is not supported. + // + if (ACE_OutputCDR::wchar_maxbytes () == 0) + { + errno = EACCES; + return (ACE_CDR::Boolean) (this->good_bit_ = false); + } + if (ACE_OutputCDR::wchar_maxbytes () == sizeof (ACE_CDR::WChar)) + return this->write_array (x, + sizeof (ACE_CDR::WChar), + sizeof (ACE_CDR::WChar) == 2 + ? ACE_CDR::SHORT_ALIGN + : ACE_CDR::LONG_ALIGN, + length); + return this->write_wchar_array_i (x,length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_SizeCDR::write_octet_array (const ACE_CDR::Octet* x, + ACE_CDR::ULong length) +{ + return this->write_array (x, + ACE_CDR::OCTET_SIZE, + ACE_CDR::OCTET_ALIGN, + length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_SizeCDR::write_short_array (const ACE_CDR::Short *x, + ACE_CDR::ULong length) +{ + return this->write_array (x, + ACE_CDR::SHORT_SIZE, + ACE_CDR::SHORT_ALIGN, + length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_SizeCDR::write_ushort_array (const ACE_CDR::UShort *x, + ACE_CDR::ULong length) +{ + return this->write_array (x, + ACE_CDR::SHORT_SIZE, + ACE_CDR::SHORT_ALIGN, + length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_SizeCDR::write_long_array (const ACE_CDR::Long *x, + ACE_CDR::ULong length) +{ + return this->write_array (x, + ACE_CDR::LONG_SIZE, + ACE_CDR::LONG_ALIGN, + length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_SizeCDR::write_ulong_array (const ACE_CDR::ULong *x, + ACE_CDR::ULong length) +{ + return this->write_array (x, + ACE_CDR::LONG_SIZE, + ACE_CDR::LONG_ALIGN, + length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_SizeCDR::write_longlong_array (const ACE_CDR::LongLong *x, + ACE_CDR::ULong length) +{ + return this->write_array (x, + ACE_CDR::LONGLONG_SIZE, + ACE_CDR::LONGLONG_ALIGN, + length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_SizeCDR::write_ulonglong_array (const ACE_CDR::ULongLong *x, + ACE_CDR::ULong length) +{ + return this->write_array (x, + ACE_CDR::LONGLONG_SIZE, + ACE_CDR::LONGLONG_ALIGN, + length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_SizeCDR::write_float_array (const ACE_CDR::Float *x, + ACE_CDR::ULong length) +{ + return this->write_array (x, + ACE_CDR::LONG_SIZE, + ACE_CDR::LONG_ALIGN, + length); +} + + +ACE_INLINE ACE_CDR::Boolean +ACE_SizeCDR::write_double_array (const ACE_CDR::Double *x, + ACE_CDR::ULong length) +{ + return this->write_array (x, + ACE_CDR::LONGLONG_SIZE, + ACE_CDR::LONGLONG_ALIGN, + length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_SizeCDR::write_longdouble_array (const ACE_CDR::LongDouble* x, + ACE_CDR::ULong length) +{ + return this->write_array (x, + ACE_CDR::LONGDOUBLE_SIZE, + ACE_CDR::LONGDOUBLE_ALIGN, + length); +} + + +// **************************************************************** + + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_SizeCDR &ss, ACE_CDR::Char x) +{ + ss.write_char (x); + return (ACE_CDR::Boolean) ss.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_SizeCDR &ss, ACE_CDR::Short x) +{ + ss.write_short (x); + return (ACE_CDR::Boolean) ss.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_SizeCDR &ss, ACE_CDR::UShort x) +{ + ss.write_ushort (x); + return (ACE_CDR::Boolean) ss.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_SizeCDR &ss, ACE_CDR::Long x) +{ + ss.write_long (x); + return (ACE_CDR::Boolean) ss.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_SizeCDR &ss, ACE_CDR::ULong x) +{ + ss.write_ulong (x); + return (ACE_CDR::Boolean) ss.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_SizeCDR &ss, ACE_CDR::LongLong x) +{ + ss.write_longlong (x); + return (ACE_CDR::Boolean) ss.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_SizeCDR &ss, ACE_CDR::ULongLong x) +{ + ss.write_ulonglong (x); + return (ACE_CDR::Boolean) ss.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_SizeCDR &ss, ACE_CDR::LongDouble x) +{ + ss.write_longdouble (x); + return (ACE_CDR::Boolean) ss.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_SizeCDR &ss, ACE_CDR::Float x) +{ + ss.write_float (x); + return (ACE_CDR::Boolean) ss.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_SizeCDR &ss, ACE_CDR::Double x) +{ + ss.write_double (x); + return (ACE_CDR::Boolean) ss.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_SizeCDR &ss, const ACE_CDR::Char *x) +{ + ss.write_string (x); + return (ACE_CDR::Boolean) ss.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_SizeCDR &ss, const ACE_CDR::WChar *x) +{ + ss.write_wstring (x); + return (ACE_CDR::Boolean) ss.good_bit (); +} + +// The following use the helper classes +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_SizeCDR &ss, ACE_OutputCDR::from_boolean x) +{ + ss.write_boolean (x.val_); + return (ACE_CDR::Boolean) ss.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_SizeCDR &ss, ACE_OutputCDR::from_char x) +{ + ss.write_char (x.val_); + return (ACE_CDR::Boolean) ss.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_SizeCDR &ss, ACE_OutputCDR::from_wchar x) +{ + ss.write_wchar (x.val_); + return (ACE_CDR::Boolean) ss.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_SizeCDR &ss, ACE_OutputCDR::from_octet x) +{ + ss.write_octet (x.val_); + return (ACE_CDR::Boolean) ss.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_SizeCDR &ss, ACE_OutputCDR::from_string x) +{ + ACE_CDR::ULong len = 0; + + if (x.val_ != 0) + { + len = static_cast (ACE_OS::strlen (x.val_)); + } + + ss.write_string (len, x.val_); + return + (ACE_CDR::Boolean) (ss.good_bit () && (!x.bound_ || len <= x.bound_)); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_SizeCDR &ss, ACE_OutputCDR::from_wstring x) +{ + ACE_CDR::ULong len = 0; + + if (x.val_ != 0) + { + len = static_cast (ACE_OS::strlen (x.val_)); + } + + ss.write_wstring (len, x.val_); + return + (ACE_CDR::Boolean) (ss.good_bit () && (!x.bound_ || len <= x.bound_)); +} + + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/CDR_Stream.cpp b/dep/acelite/ace/CDR_Stream.cpp new file mode 100644 index 00000000000..74d33be5876 --- /dev/null +++ b/dep/acelite/ace/CDR_Stream.cpp @@ -0,0 +1,2063 @@ +#include "ace/CDR_Stream.h" +#include "ace/SString.h" +#include "ace/Auto_Ptr.h" +#include "ace/Truncate.h" + +#if !defined (__ACE_INLINE__) +# include "ace/CDR_Stream.inl" +#endif /* ! __ACE_INLINE__ */ + +ACE_RCSID (ace, + CDR_Stream, + "$Id: CDR_Stream.cpp 88653 2010-01-21 23:19:50Z sowayaa $") + +// **************************************************************** + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +size_t ACE_OutputCDR::wchar_maxbytes_ = sizeof (ACE_CDR::WChar); + +ACE_OutputCDR::ACE_OutputCDR (size_t size, + int byte_order, + ACE_Allocator *buffer_allocator, + ACE_Allocator *data_block_allocator, + ACE_Allocator *message_block_allocator, + size_t memcpy_tradeoff, + ACE_CDR::Octet major_version, + ACE_CDR::Octet minor_version) + : start_ ((size ? size : (size_t) ACE_CDR::DEFAULT_BUFSIZE) + ACE_CDR::MAX_ALIGNMENT, + ACE_Message_Block::MB_DATA, + 0, + 0, + buffer_allocator, + 0, + 0, + ACE_Time_Value::zero, + ACE_Time_Value::max_time, + data_block_allocator, + message_block_allocator), +#if !defined (ACE_LACKS_CDR_ALIGNMENT) + current_alignment_ (0), +#endif /* ACE_LACKS_CDR_ALIGNMENT */ + current_is_writable_ (true), + do_byte_swap_ (byte_order != ACE_CDR_BYTE_ORDER), + good_bit_ (true), + memcpy_tradeoff_ (memcpy_tradeoff), + major_version_ (major_version), + minor_version_ (minor_version), + char_translator_ (0), + wchar_translator_ (0) + +{ + ACE_CDR::mb_align (&this->start_); + this->current_ = &this->start_; + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + ACE_NEW (this->monitor_, + ACE::Monitor_Control::Size_Monitor); + this->monitor_->receive (this->total_length ()); +#endif /* ACE_HAS_MONITOR_POINTS==1 */ +} + +ACE_OutputCDR::ACE_OutputCDR (char *data, + size_t size, + int byte_order, + ACE_Allocator *buffer_allocator, + ACE_Allocator *data_block_allocator, + ACE_Allocator *message_block_allocator, + size_t memcpy_tradeoff, + ACE_CDR::Octet major_version, + ACE_CDR::Octet minor_version) + : start_ (size, + ACE_Message_Block::MB_DATA, + 0, + data, + buffer_allocator, + 0, + 0, + ACE_Time_Value::zero, + ACE_Time_Value::max_time, + data_block_allocator, + message_block_allocator), +#if !defined (ACE_LACKS_CDR_ALIGNMENT) + current_alignment_ (0), +#endif /* ACE_LACKS_CDR_ALIGNMENT */ + current_is_writable_ (true), + do_byte_swap_ (byte_order != ACE_CDR_BYTE_ORDER), + good_bit_ (true), + memcpy_tradeoff_ (memcpy_tradeoff), + major_version_ (major_version), + minor_version_ (minor_version), + char_translator_ (0), + wchar_translator_ (0) +{ + // We cannot trust the buffer to be properly aligned + ACE_CDR::mb_align (&this->start_); + this->current_ = &this->start_; + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + ACE_NEW (this->monitor_, + ACE::Monitor_Control::Size_Monitor); + this->monitor_->receive (this->total_length ()); +#endif /* ACE_HAS_MONITOR_POINTS==1 */ +} + +ACE_OutputCDR::ACE_OutputCDR (ACE_Data_Block *data_block, + int byte_order, + ACE_Allocator *message_block_allocator, + size_t memcpy_tradeoff, + ACE_CDR::Octet major_version, + ACE_CDR::Octet minor_version) + : start_ (data_block, + ACE_Message_Block::DONT_DELETE, + message_block_allocator), +#if !defined (ACE_LACKS_CDR_ALIGNMENT) + current_alignment_ (0), +#endif /* ACE_LACKS_CDR_ALIGNMENT */ + current_is_writable_ (true), + do_byte_swap_ (byte_order != ACE_CDR_BYTE_ORDER), + good_bit_ (true), + memcpy_tradeoff_ (memcpy_tradeoff), + major_version_ (major_version), + minor_version_ (minor_version), + char_translator_ (0), + wchar_translator_ (0) +{ + // We cannot trust the buffer to be properly aligned + ACE_CDR::mb_align (&this->start_); + this->current_ = &this->start_; + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + ACE_NEW (this->monitor_, + ACE::Monitor_Control::Size_Monitor); + this->monitor_->receive (this->total_length ()); +#endif /* ACE_HAS_MONITOR_POINTS==1 */ +} + +ACE_OutputCDR::ACE_OutputCDR (ACE_Message_Block *data, + int byte_order, + size_t memcpy_tradeoff, + ACE_CDR::Octet major_version, + ACE_CDR::Octet minor_version) + : start_ (data->data_block ()->duplicate ()), +#if !defined (ACE_LACKS_CDR_ALIGNMENT) + current_alignment_ (0), +#endif /* ACE_LACKS_CDR_ALIGNMENT */ + current_is_writable_ (true), + do_byte_swap_ (byte_order != ACE_CDR_BYTE_ORDER), + good_bit_ (true), + memcpy_tradeoff_ (memcpy_tradeoff), + major_version_ (major_version), + minor_version_ (minor_version), + char_translator_ (0), + wchar_translator_ (0) +{ + // We cannot trust the buffer to be properly aligned + ACE_CDR::mb_align (&this->start_); + this->current_ = &this->start_; + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + ACE_NEW (this->monitor_, + ACE::Monitor_Control::Size_Monitor); + this->monitor_->receive (this->total_length ()); +#endif /* ACE_HAS_MONITOR_POINTS==1 */ +} + +/*static*/ void +ACE_OutputCDR::wchar_maxbytes (size_t maxbytes) +{ + ACE_OutputCDR::wchar_maxbytes_ = maxbytes; +} + +/*static*/ size_t +ACE_OutputCDR::wchar_maxbytes () +{ + return ACE_OutputCDR::wchar_maxbytes_; +} + +int +ACE_OutputCDR::grow_and_adjust (size_t size, + size_t align, + char*& buf) +{ + if (!this->current_is_writable_ + || this->current_->cont () == 0 + || this->current_->cont ()->size () < size + ACE_CDR::MAX_ALIGNMENT) + { + // Calculate the new buffer's length; if growing for encode, we + // don't grow in "small" chunks because of the cost. + size_t cursize = this->current_->size (); + if (this->current_->cont () != 0) + cursize = this->current_->cont ()->size (); + size_t minsize = size; + +#if !defined (ACE_LACKS_CDR_ALIGNMENT) + minsize += ACE_CDR::MAX_ALIGNMENT; +#endif /* ACE_LACKS_CDR_ALIGNMENT */ + + // Make sure that there is enough room for bytes, but + // also make it bigger than whatever our current size is. + if (minsize < cursize) + minsize = cursize; + + size_t const newsize = ACE_CDR::next_size (minsize); + + this->good_bit_ = false; + ACE_Message_Block* tmp = 0; + ACE_NEW_RETURN (tmp, + ACE_Message_Block (newsize, + ACE_Message_Block::MB_DATA, + 0, + 0, + this->current_->data_block ()->allocator_strategy (), + 0, + 0, + ACE_Time_Value::zero, + ACE_Time_Value::max_time, + this->current_->data_block ()->data_block_allocator ()), + -1); + + // Message block initialization may fail while the construction + // succeds. Since as a matter of policy, ACE may throw no + // exceptions, we have to do a separate check like this. + if (tmp != 0 && tmp->size () < newsize) + { + delete tmp; + errno = ENOMEM; + return -1; + } + + this->good_bit_ = true; + +#if !defined (ACE_LACKS_CDR_ALIGNMENT) + // The new block must start with the same alignment as the + // previous block finished. + ptrdiff_t const tmpalign = + reinterpret_cast (tmp->rd_ptr ()) % ACE_CDR::MAX_ALIGNMENT; + ptrdiff_t const curalign = + static_cast (this->current_alignment_) % ACE_CDR::MAX_ALIGNMENT; + ptrdiff_t offset = curalign - tmpalign; + if (offset < 0) + offset += ACE_CDR::MAX_ALIGNMENT; + tmp->rd_ptr (static_cast (offset)); + tmp->wr_ptr (tmp->rd_ptr ()); +#endif /* ACE_LACKS_CDR_ALIGNMENT */ + + // grow the chain and set the current block. + tmp->cont (this->current_->cont ()); + this->current_->cont (tmp); + } + this->current_ = this->current_->cont (); + this->current_is_writable_ = true; + + return this->adjust (size, align, buf); +} + +ACE_CDR::Boolean +ACE_OutputCDR::write_wchar (ACE_CDR::WChar x) +{ + if (this->wchar_translator_ != 0) + return (this->good_bit_ = this->wchar_translator_->write_wchar (*this, x)); + if (ACE_OutputCDR::wchar_maxbytes_ == 0) + { + errno = EACCES; + return (this->good_bit_ = false); + } + if (static_cast (major_version_) == 1 + && static_cast (minor_version_) == 2) + { + ACE_CDR::Octet len = + static_cast (ACE_OutputCDR::wchar_maxbytes_); + if (this->write_1 (&len)) + { + if (ACE_OutputCDR::wchar_maxbytes_ == sizeof(ACE_CDR::WChar)) + return + this->write_octet_array ( + reinterpret_cast (&x), + static_cast (len)); + else + if (ACE_OutputCDR::wchar_maxbytes_ == 2) + { + ACE_CDR::Short sx = static_cast (x); + return + this->write_octet_array ( + reinterpret_cast (&sx), + static_cast (len)); + } + else + { + ACE_CDR::Octet ox = static_cast (x); + return + this->write_octet_array ( + reinterpret_cast (&ox), + static_cast (len)); + } + } + } + else if (static_cast (minor_version_) == 0) + { // wchar is not allowed with GIOP 1.0. + errno = EINVAL; + return (this->good_bit_ = false); + } + if (ACE_OutputCDR::wchar_maxbytes_ == sizeof (ACE_CDR::WChar)) + { + void const * const temp = &x; + return + this->write_4 (reinterpret_cast (temp)); + } + else if (ACE_OutputCDR::wchar_maxbytes_ == 2) + { + ACE_CDR::Short sx = static_cast (x); + return this->write_2 (reinterpret_cast (&sx)); + } + ACE_CDR::Octet ox = static_cast (x); + return this->write_1 (reinterpret_cast (&ox)); +} + +ACE_CDR::Boolean +ACE_OutputCDR::write_string (ACE_CDR::ULong len, + const ACE_CDR::Char *x) +{ + // @@ This is a slight violation of "Optimize for the common case", + // i.e. normally the translator will be 0, but OTOH the code is + // smaller and should be better for the cache ;-) ;-) + if (this->char_translator_ != 0) + return this->char_translator_->write_string (*this, len, x); + + if (len != 0) + { + if (this->write_ulong (len + 1)) + return this->write_char_array (x, len + 1); + } + else + { + // Be nice to programmers: treat nulls as empty strings not + // errors. (OMG-IDL supports languages that don't use the C/C++ + // notion of null v. empty strings; nulls aren't part of the OMG-IDL + // string model.) + if (this->write_ulong (1)) + return this->write_char (0); + } + + return (this->good_bit_ = false); +} + +ACE_CDR::Boolean +ACE_OutputCDR::write_string (const ACE_CString &x) +{ + // @@ Leave this method in here, not the `.i' file so that we don't + // have to unnecessarily pull in the `ace/SString.h' header. + return this->write_string (static_cast (x.length ()), + x.c_str()); +} + +ACE_CDR::Boolean +ACE_OutputCDR::write_wstring (ACE_CDR::ULong len, + const ACE_CDR::WChar *x) +{ + // @@ This is a slight violation of "Optimize for the common case", + // i.e. normally the translator will be 0, but OTOH the code is + // smaller and should be better for the cache ;-) ;-) + // What do we do for GIOP 1.2??? + if (this->wchar_translator_ != 0) + return this->wchar_translator_->write_wstring (*this, len, x); + if (ACE_OutputCDR::wchar_maxbytes_ == 0) + { + errno = EACCES; + return (this->good_bit_ = false); + } + + if (static_cast (this->major_version_) == 1 + && static_cast (this->minor_version_) == 2) + { + if (x != 0) + { + //In GIOP 1.2 the length field contains the number of bytes + //the wstring occupies rather than number of wchars + //Taking sizeof might not be a good way! This is a temporary fix. + ACE_CDR::Boolean good_ulong = + this->write_ulong ( + ACE_Utils::truncate_cast ( + ACE_OutputCDR::wchar_maxbytes_ * len)); + + if (good_ulong) + { + return this->write_wchar_array (x, len); + } + } + else + { + //In GIOP 1.2 zero length wstrings are legal + return this->write_ulong (0); + } + } + + else + if (x != 0) + { + if (this->write_ulong (len + 1)) + return this->write_wchar_array (x, len + 1); + } + else if (this->write_ulong (1)) + return this->write_wchar (0); + return (this->good_bit_ = false); +} + +ACE_CDR::Boolean +ACE_OutputCDR::write_octet_array_mb (const ACE_Message_Block* mb) +{ + // If the buffer is small and it fits in the current message + // block it is be cheaper just to copy the buffer. + for (const ACE_Message_Block* i = mb; + i != 0; + i = i->cont ()) + { + size_t const length = i->length (); + + // If the mb does not own its data we are forced to make a copy. + if (ACE_BIT_ENABLED (i->flags (), + ACE_Message_Block::DONT_DELETE)) + { + if (! this->write_array (i->rd_ptr (), + ACE_CDR::OCTET_SIZE, + ACE_CDR::OCTET_ALIGN, + static_cast (length))) + return (this->good_bit_ = false); + continue; + } + + if (length < this->memcpy_tradeoff_ + && this->current_->wr_ptr () + length < this->current_->end ()) + { + if (! this->write_array (i->rd_ptr (), + ACE_CDR::OCTET_SIZE, + ACE_CDR::OCTET_ALIGN, + static_cast (length))) + return (this->good_bit_ = false); + continue; + } + + ACE_Message_Block* cont = 0; + this->good_bit_ = false; + ACE_NEW_RETURN (cont, + ACE_Message_Block (i->data_block ()->duplicate ()), + false); + this->good_bit_ = true; + + if (this->current_->cont () != 0) + ACE_Message_Block::release (this->current_->cont ()); + cont->rd_ptr (i->rd_ptr ()); + cont->wr_ptr (i->wr_ptr ()); + + this->current_->cont (cont); + this->current_ = cont; + this->current_is_writable_ = false; +#if !defined (ACE_LACKS_CDR_ALIGNMENT) + this->current_alignment_ = + (this->current_alignment_ + cont->length ()) % ACE_CDR::MAX_ALIGNMENT; +#endif /* ACE_LACKS_CDR_ALIGNMENT */ + } + + return true; +} + +ACE_CDR::Boolean +ACE_OutputCDR::write_1 (const ACE_CDR::Octet *x) +{ + char *buf = 0; + if (this->adjust (1, buf) == 0) + { + *reinterpret_cast (buf) = *x; + return true; + } + + return false; +} + +ACE_CDR::Boolean +ACE_OutputCDR::write_2 (const ACE_CDR::UShort *x) +{ + char *buf = 0; + if (this->adjust (ACE_CDR::SHORT_SIZE, buf) == 0) + { +#if !defined (ACE_ENABLE_SWAP_ON_WRITE) + *reinterpret_cast (buf) = *x; + return true; +#else + if (!this->do_byte_swap_) + { + *reinterpret_cast (buf) = *x; + return true; + } + else + { + ACE_CDR::swap_2 (reinterpret_cast (x), buf); + return true; + } +#endif /* ACE_ENABLE_SWAP_ON_WRITE */ + } + + return false; +} + +ACE_CDR::Boolean +ACE_OutputCDR::write_4 (const ACE_CDR::ULong *x) +{ + char *buf = 0; + if (this->adjust (ACE_CDR::LONG_SIZE, buf) == 0) + { +#if !defined (ACE_ENABLE_SWAP_ON_WRITE) + *reinterpret_cast (buf) = *x; + return true; +#else + if (!this->do_byte_swap_) + { + *reinterpret_cast (buf) = *x; + return true; + } + else + { + ACE_CDR::swap_4 (reinterpret_cast (x), buf); + return true; + } +#endif /* ACE_ENABLE_SWAP_ON_WRITE */ + } + + return false; +} + +ACE_CDR::Boolean +ACE_OutputCDR::write_8 (const ACE_CDR::ULongLong *x) +{ + char *buf = 0; + + if (this->adjust (ACE_CDR::LONGLONG_SIZE, buf) == 0) + { +#if defined (__arm__) && !defined (ACE_HAS_IPHONE) + // Convert to Intel format (12345678 => 56781234) + const char *orig = reinterpret_cast (x); + char *target = buf; + register ACE_UINT32 x = + *reinterpret_cast (orig); + register ACE_UINT32 y = + *reinterpret_cast (orig + 4); + *reinterpret_cast (target) = y; + *reinterpret_cast (target + 4) = x; + return true; +#else +# if !defined (ACE_ENABLE_SWAP_ON_WRITE) + *reinterpret_cast (buf) = *x; + return true; +# else + if (!this->do_byte_swap_) + { + *reinterpret_cast (buf) = *x; + return true; + } + else + { + ACE_CDR::swap_8 (reinterpret_cast (x), buf); + return true; + } +# endif /* ACE_ENABLE_SWAP_ON_WRITE */ +#endif /* !__arm__ */ + } + + return false; +} + +ACE_CDR::Boolean +ACE_OutputCDR::write_16 (const ACE_CDR::LongDouble *x) +{ + char* buf = 0; + if (this->adjust (ACE_CDR::LONGDOUBLE_SIZE, + ACE_CDR::LONGDOUBLE_ALIGN, + buf) == 0) + { +#if !defined (ACE_ENABLE_SWAP_ON_WRITE) + *reinterpret_cast (buf) = *x; + return 1; +#else + if (!this->do_byte_swap_) + { + *reinterpret_cast (buf) = *x; + return true; + } + else + { + ACE_CDR::swap_16 (reinterpret_cast (x), buf); + return true; + } +#endif /* ACE_ENABLE_SWAP_ON_WRITE */ + } + + return false; +} + +ACE_CDR::Boolean +ACE_OutputCDR::write_wchar_array_i (const ACE_CDR::WChar *x, + ACE_CDR::ULong length) +{ + if (length == 0) + return true; + char* buf = 0; + size_t const align = (ACE_OutputCDR::wchar_maxbytes_ == 2) ? + ACE_CDR::SHORT_ALIGN : + ACE_CDR::OCTET_ALIGN; + + if (this->adjust (ACE_OutputCDR::wchar_maxbytes_ * length, align, buf) == 0) + { + if (ACE_OutputCDR::wchar_maxbytes_ == 2) + { + ACE_CDR::UShort *sb = reinterpret_cast (buf); + for (size_t i = 0; i < length; ++i) +#if !defined (ACE_ENABLE_SWAP_ON_WRITE) + sb[i] = static_cast (x[i]); +#else + if (!this->do_byte_swap_) + sb[i] = static_cast (x[i]); + else + { + ACE_CDR::UShort sx = static_cast (x[i]); + ACE_CDR::swap_2 (reinterpret_cast (&sx), &buf[i * 2]); + } +#endif /* ACE_ENABLE_SWAP_ON_WRITE */ + } + else + { + for (size_t i = 0; i < length; ++i) + buf[i] = static_cast (x[i]); + } + return this->good_bit_; + } + return false; +} + + +ACE_CDR::Boolean +ACE_OutputCDR::write_array (const void *x, + size_t size, + size_t align, + ACE_CDR::ULong length) +{ + if (length == 0) + return true; + char *buf = 0; + if (this->adjust (size * length, align, buf) == 0) + { +#if !defined (ACE_ENABLE_SWAP_ON_WRITE) + ACE_OS::memcpy (buf, x, size*length); + return true; +#else + if (!this->do_byte_swap_ || size == 1) + { + ACE_OS::memcpy (buf, x, size*length); + return true; + } + else + { + const char *source = reinterpret_cast (x); + switch (size) + { + case 2: + ACE_CDR::swap_2_array (source, buf, length); + return true; + case 4: + ACE_CDR::swap_4_array (source, buf, length); + return true; + case 8: + ACE_CDR::swap_8_array (source, buf, length); + return true; + case 16: + ACE_CDR::swap_16_array (source, buf, length); + return true; + default: + // TODO: print something? + this->good_bit_ = false; + return false; + } + } +#endif /* ACE_ENABLE_SWAP_ON_WRITE */ + } + this->good_bit_ = false; + return false; +} + + +ACE_CDR::Boolean +ACE_OutputCDR::write_boolean_array (const ACE_CDR::Boolean* x, + ACE_CDR::ULong length) +{ + // It is hard to optimize this, the spec requires that on the wire + // booleans be represented as a byte with value 0 or 1, but in + // memory it is possible (though very unlikely) that a boolean has + // a non-zero value (different from 1). + // We resort to a simple loop. + ACE_CDR::Boolean const * const end = x + length; + + for (ACE_CDR::Boolean const * i = x; + i != end && this->good_bit (); + ++i) + (void) this->write_boolean (*i); + + return this->good_bit (); +} + +char * +ACE_OutputCDR::write_long_placeholder (void) +{ + char *buf = 0; + if (this->adjust (ACE_CDR::LONG_SIZE, buf) == 0) + *reinterpret_cast (buf) = 0; + else + buf = 0; + return buf; +} + +char * +ACE_OutputCDR::write_short_placeholder (void) +{ + char *buf = 0; + if (this->adjust (ACE_CDR::SHORT_SIZE, buf) == 0) + *reinterpret_cast (buf) = 0; + else + buf = 0; + return buf; +} + +ACE_CDR::Boolean +ACE_OutputCDR::replace (ACE_CDR::Long x, char* loc) +{ + if (this->find (loc) == 0) + return false; + +#if !defined (ACE_ENABLE_SWAP_ON_WRITE) + *reinterpret_cast (loc) = x; +#else + if (!this->do_byte_swap_) + { + *reinterpret_cast (loc) = x; + } + else + { + ACE_CDR::swap_4 (reinterpret_cast (&x), loc); + } +#endif /* ACE_ENABLE_SWAP_ON_WRITE */ + + return true; +} + + +ACE_CDR::Boolean +ACE_OutputCDR::replace (ACE_CDR::Short x, char* loc) +{ + if (this->find (loc) == 0) + return false; + +#if !defined (ACE_ENABLE_SWAP_ON_WRITE) + *reinterpret_cast (loc) = x; +#else + if (!this->do_byte_swap_) + { + *reinterpret_cast (loc) = x; + } + else + { + ACE_CDR::swap_2 (reinterpret_cast (&x), loc); + } +#endif /* ACE_ENABLE_SWAP_ON_WRITE */ + + return true; +} + + +int +ACE_OutputCDR::consolidate (void) +{ + // Optimize by only doing something if we need to + if (this->current_ != &this->start_) + { + // Set the number of bytes in the top-level block, reallocating + // if necessary. The rd_ptr and wr_ptr remain at the original offsets + // into the buffer, even if it is reallocated. + // Return an error if the allocation failed. + size_t const newsize = + ACE_CDR::first_size (this->total_length () + + ACE_CDR::MAX_ALIGNMENT); + if (this->start_.size (newsize) < 0) + { + return -1; + } + + // Consolidate the chain into the first block. NOTE that + // ACE_CDR::consolidate can not be used since we don't want to + // overwrite what is already in the first block. We just append it since + // the read and write pointers weren't affected by the resizing above. + // We also don't have to worry about alignment since the start block is + // already aligned. + // NOTE also we know there is a continuation since we checked for it + // above. There is therefore no reason to check for a 0 continuation + // field here. + ACE_Message_Block *cont = this->start_.cont (); + for (const ACE_Message_Block* i = cont; i != 0; i = i->cont ()) + { + this->start_.copy (i->rd_ptr (), i->length ()); + } + + // Release the old blocks that were consolidated and reset the + // current_ and current_is_writable_ to reflect the single used block. + ACE_Message_Block::release (cont); + this->start_.cont (0); + this->current_ = &this->start_; + this->current_is_writable_ = true; + } + + return 0; +} + + +ACE_Message_Block* +ACE_OutputCDR::find (char* loc) +{ + ACE_Message_Block* mb = 0; + for (mb = &this->start_; mb != 0; mb = mb->cont ()) + { + if (loc <= mb->wr_ptr () && loc >= mb->rd_ptr ()) + { + break; + } + } + + return mb; +} + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + +void +ACE_OutputCDR::register_monitor (const char *id) +{ + this->monitor_->name (id); + this->monitor_->add_to_registry (); +} + +void +ACE_OutputCDR::unregister_monitor (void) +{ + this->monitor_->remove_from_registry (); +} + +#endif /* ACE_HAS_MONITOR_POINTS==1 */ + +// **************************************************************** + +ACE_InputCDR::ACE_InputCDR (const char *buf, + size_t bufsiz, + int byte_order, + ACE_CDR::Octet major_version, + ACE_CDR::Octet minor_version) + : start_ (buf, bufsiz), + do_byte_swap_ (byte_order != ACE_CDR_BYTE_ORDER), + good_bit_ (true), + major_version_ (major_version), + minor_version_ (minor_version), + char_translator_ (0), + wchar_translator_ (0) +{ + this->start_.wr_ptr (bufsiz); + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + ACE_NEW (this->monitor_, + ACE::Monitor_Control::Size_Monitor); + this->monitor_->receive (bufsiz); +#endif /* ACE_HAS_MONITOR_POINTS==1 */ +} + +ACE_InputCDR::ACE_InputCDR (size_t bufsiz, + int byte_order, + ACE_CDR::Octet major_version, + ACE_CDR::Octet minor_version) + : start_ (bufsiz), + do_byte_swap_ (byte_order != ACE_CDR_BYTE_ORDER), + good_bit_ (true), + major_version_ (major_version), + minor_version_ (minor_version), + char_translator_ (0), + wchar_translator_ (0) +{ +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + ACE_NEW (this->monitor_, + ACE::Monitor_Control::Size_Monitor); + this->monitor_->receive (bufsiz); +#endif /* ACE_HAS_MONITOR_POINTS==1 */ +} + +ACE_InputCDR::ACE_InputCDR (const ACE_Message_Block *data, + int byte_order, + ACE_CDR::Octet major_version, + ACE_CDR::Octet minor_version, + ACE_Lock* lock) + : start_ (0, ACE_Message_Block::MB_DATA, 0, 0, 0, lock), + good_bit_ (true), + major_version_ (major_version), + minor_version_ (minor_version), + char_translator_ (0), + wchar_translator_ (0) +{ +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + ACE_NEW (this->monitor_, + ACE::Monitor_Control::Size_Monitor); + this->monitor_->receive (this->start_.total_size ()); +#endif /* ACE_HAS_MONITOR_POINTS==1 */ + + this->reset (data, byte_order); +} + +ACE_InputCDR::ACE_InputCDR (ACE_Data_Block *data, + ACE_Message_Block::Message_Flags flag, + int byte_order, + ACE_CDR::Octet major_version, + ACE_CDR::Octet minor_version) + : start_ (data, flag), + do_byte_swap_ (byte_order != ACE_CDR_BYTE_ORDER), + good_bit_ (true), + major_version_ (major_version), + minor_version_ (minor_version), + char_translator_ (0), + wchar_translator_ (0) +{ +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + ACE_NEW (this->monitor_, + ACE::Monitor_Control::Size_Monitor); + this->monitor_->receive (data->size ()); +#endif /* ACE_HAS_MONITOR_POINTS==1 */ +} + +ACE_InputCDR::ACE_InputCDR (ACE_Data_Block *data, + ACE_Message_Block::Message_Flags flag, + size_t rd_pos, + size_t wr_pos, + int byte_order, + ACE_CDR::Octet major_version, + ACE_CDR::Octet minor_version) + : start_ (data, flag), + do_byte_swap_ (byte_order != ACE_CDR_BYTE_ORDER), + good_bit_ (true), + major_version_ (major_version), + minor_version_ (minor_version), + char_translator_ (0), + wchar_translator_ (0) +{ + // Set the read pointer + this->start_.rd_ptr (rd_pos); + + // Set the write pointer after doing a sanity check. + char* wrpos = this->start_.base () + wr_pos; + + if (this->start_.end () >= wrpos) + { + this->start_.wr_ptr (wr_pos); + } + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + ACE_NEW (this->monitor_, + ACE::Monitor_Control::Size_Monitor); + this->monitor_->receive (data->size ()); +#endif /* ACE_HAS_MONITOR_POINTS==1 */ +} + +ACE_InputCDR::ACE_InputCDR (const ACE_InputCDR& rhs, + size_t size, + ACE_CDR::Long offset) + : start_ (rhs.start_, + ACE_CDR::MAX_ALIGNMENT), + do_byte_swap_ (rhs.do_byte_swap_), + good_bit_ (true), + major_version_ (rhs.major_version_), + minor_version_ (rhs.minor_version_), + char_translator_ (rhs.char_translator_), + wchar_translator_ (rhs.wchar_translator_) +{ +#if !defined (ACE_LACKS_CDR_ALIGNMENT) + // Align the base pointer assuming that the incoming stream is also + // aligned the way we are aligned + char *incoming_start = ACE_ptr_align_binary (rhs.start_.base (), + ACE_CDR::MAX_ALIGNMENT); +#else + char *incoming_start = rhs.start_.base (); +#endif /* ACE_LACKS_CDR_ALIGNMENT */ + + const size_t newpos = + (rhs.start_.rd_ptr() - incoming_start) + offset; + + if (newpos <= this->start_.space () + && newpos + size <= this->start_.space ()) + { + this->start_.rd_ptr (newpos); + this->start_.wr_ptr (newpos + size); + } + else + { + this->good_bit_ = false; + } + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + ACE_NEW (this->monitor_, + ACE::Monitor_Control::Size_Monitor); + this->monitor_->receive (this->start_.total_size ()); +#endif /* ACE_HAS_MONITOR_POINTS==1 */ +} + +ACE_InputCDR::ACE_InputCDR (const ACE_InputCDR& rhs, + size_t size) + : start_ (rhs.start_, + ACE_CDR::MAX_ALIGNMENT), + do_byte_swap_ (rhs.do_byte_swap_), + good_bit_ (true), + major_version_ (rhs.major_version_), + minor_version_ (rhs.minor_version_), + char_translator_ (rhs.char_translator_), + wchar_translator_ (rhs.wchar_translator_) +{ +#if !defined (ACE_LACKS_CDR_ALIGNMENT) + // Align the base pointer assuming that the incoming stream is also + // aligned the way we are aligned + char *incoming_start = ACE_ptr_align_binary (rhs.start_.base (), + ACE_CDR::MAX_ALIGNMENT); +#else + char *incoming_start = rhs.start_.base (); +#endif /* ACE_LACKS_CDR_ALIGNMENT */ + + const size_t newpos = + rhs.start_.rd_ptr() - incoming_start; + + if (newpos <= this->start_.space () + && newpos + size <= this->start_.space ()) + { + // Notice that ACE_Message_Block::duplicate may leave the + // wr_ptr() with a higher value than what we actually want. + this->start_.rd_ptr (newpos); + this->start_.wr_ptr (newpos + size); + + ACE_CDR::Octet byte_order = 0; + (void) this->read_octet (byte_order); + this->do_byte_swap_ = (byte_order != ACE_CDR_BYTE_ORDER); + } + else + { + this->good_bit_ = false; + } + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + ACE_NEW (this->monitor_, + ACE::Monitor_Control::Size_Monitor); + this->monitor_->receive (this->start_.total_size ()); +#endif /* ACE_HAS_MONITOR_POINTS==1 */ +} + +ACE_InputCDR::ACE_InputCDR (const ACE_InputCDR& rhs) + : start_ (rhs.start_, + ACE_CDR::MAX_ALIGNMENT), + do_byte_swap_ (rhs.do_byte_swap_), + good_bit_ (true), + major_version_ (rhs.major_version_), + minor_version_ (rhs.minor_version_), + char_translator_ (rhs.char_translator_), + wchar_translator_ (rhs.wchar_translator_) +{ +#if !defined (ACE_LACKS_CDR_ALIGNMENT) + char *buf = ACE_ptr_align_binary (rhs.start_.base (), + ACE_CDR::MAX_ALIGNMENT); +#else + char *buf = rhs.start_.base (); +#endif /* ACE_LACKS_CDR_ALIGNMENT */ + + size_t rd_offset = rhs.start_.rd_ptr () - buf; + size_t wr_offset = rhs.start_.wr_ptr () - buf; + this->start_.rd_ptr (rd_offset); + this->start_.wr_ptr (wr_offset); + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + ACE_NEW (this->monitor_, + ACE::Monitor_Control::Size_Monitor); + this->monitor_->receive (this->start_.total_size ()); +#endif /* ACE_HAS_MONITOR_POINTS==1 */ +} + +ACE_InputCDR::ACE_InputCDR (ACE_InputCDR::Transfer_Contents x) + : start_ (x.rhs_.start_.data_block ()), + do_byte_swap_ (x.rhs_.do_byte_swap_), + good_bit_ (true), + major_version_ (x.rhs_.major_version_), + minor_version_ (x.rhs_.minor_version_), + char_translator_ (x.rhs_.char_translator_), + wchar_translator_ (x.rhs_.wchar_translator_) +{ + this->start_.rd_ptr (x.rhs_.start_.rd_ptr ()); + this->start_.wr_ptr (x.rhs_.start_.wr_ptr ()); + + ACE_Data_Block* db = this->start_.data_block ()->clone_nocopy (); + (void) x.rhs_.start_.replace_data_block (db); + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + ACE_NEW (this->monitor_, + ACE::Monitor_Control::Size_Monitor); + this->monitor_->receive (this->start_.total_size ()); +#endif /* ACE_HAS_MONITOR_POINTS==1 */ +} + +ACE_InputCDR& +ACE_InputCDR::operator= (const ACE_InputCDR& rhs) +{ + if (this != &rhs) + { + this->start_.data_block (rhs.start_.data_block ()->duplicate ()); + this->start_.rd_ptr (rhs.start_.rd_ptr ()); + this->start_.wr_ptr (rhs.start_.wr_ptr ()); + this->do_byte_swap_ = rhs.do_byte_swap_; + this->good_bit_ = true; + this->char_translator_ = rhs.char_translator_; + this->major_version_ = rhs.major_version_; + this->minor_version_ = rhs.minor_version_; + } + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + this->monitor_->receive (this->start_.total_size ()); +#endif /* ACE_HAS_MONITOR_POINTS==1 */ + + return *this; +} + +ACE_InputCDR::ACE_InputCDR (const ACE_OutputCDR& rhs, + ACE_Allocator* buffer_allocator, + ACE_Allocator* data_block_allocator, + ACE_Allocator* message_block_allocator) + : start_ (rhs.total_length () + ACE_CDR::MAX_ALIGNMENT, + ACE_Message_Block::MB_DATA, + 0, + 0, + buffer_allocator, + 0, + 0, + ACE_Time_Value::zero, + ACE_Time_Value::max_time, + data_block_allocator, + message_block_allocator), + do_byte_swap_ (rhs.do_byte_swap_), + good_bit_ (true), + major_version_ (rhs.major_version_), + minor_version_ (rhs.minor_version_), + char_translator_ (rhs.char_translator_), + wchar_translator_ (rhs.wchar_translator_) +{ + ACE_CDR::mb_align (&this->start_); + for (const ACE_Message_Block *i = rhs.begin (); + i != rhs.end (); + i = i->cont ()) + { + this->start_.copy (i->rd_ptr (), i->length ()); + } + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + ACE_NEW (this->monitor_, + ACE::Monitor_Control::Size_Monitor); + this->monitor_->receive (this->start_.total_size ()); +#endif /* ACE_HAS_MONITOR_POINTS==1 */ +} + +ACE_CDR::Boolean +ACE_InputCDR::skip_wchar (void) +{ + if (static_cast (major_version_) == 1 + && static_cast (minor_version_) == 2) + { + ACE_CDR::Octet len; + if (this->read_1 (&len)) + return this->skip_bytes (static_cast (len)); + } + else + { + ACE_CDR::WChar x; + void * const temp = &x; + if (ACE_OutputCDR::wchar_maxbytes_ == 2) + return this->read_2 (reinterpret_cast (temp)); + else + return this->read_4 (reinterpret_cast (temp)); + } + + return (this->good_bit_ = false); +} + +ACE_CDR::Boolean +ACE_InputCDR::read_wchar (ACE_CDR::WChar& x) +{ + if (this->wchar_translator_ != 0) + { + this->good_bit_ = this->wchar_translator_->read_wchar (*this,x); + return this->good_bit_; + } + if (ACE_OutputCDR::wchar_maxbytes_ == 0) + { + errno = EACCES; + return (this->good_bit_ = false); + } + + if (ACE_OutputCDR::wchar_maxbytes_ == sizeof (ACE_CDR::WChar)) + { + if (static_cast (major_version_) == 1 + && static_cast (minor_version_) == 2) + { + ACE_CDR::Octet len; + + if (this->read_1 (&len)) + return this->read_array + (reinterpret_cast (&x), + static_cast (len), + ACE_CDR::OCTET_ALIGN, + 1); + + else + return (this->good_bit_ = false); + } + + void * const temp = &x; + if (sizeof (ACE_CDR::WChar) == 2) + return this->read_2 (reinterpret_cast (temp)); + else + return this->read_4 (reinterpret_cast (temp)); + } + + if (static_cast (major_version_) == 1 + && static_cast (minor_version_) == 2) + { + ACE_CDR::Octet len; + + if (this->read_1 (&len)) + { + if (len == 2) + { + ACE_CDR::Short sx; + if (this->read_array + (reinterpret_cast (&sx), + static_cast (len), + ACE_CDR::OCTET_ALIGN, + 1)) + { + x = static_cast (sx); + return true; + } + } + else + { + ACE_CDR::Octet ox; + if (this->read_array + (reinterpret_cast (&ox), + static_cast (len), + ACE_CDR::OCTET_ALIGN, + 1)) + { + x = static_cast (ox); + return true; + } + } + } + } + else + { + if (ACE_OutputCDR::wchar_maxbytes_ == 2) + { + ACE_CDR::UShort sx; + if (this->read_2 (reinterpret_cast (&sx))) + { + x = static_cast (sx); + return true; + } + } + else + { + ACE_CDR::Octet ox; + if (this->read_1 (&ox)) + { + x = static_cast (ox); + return true; + } + + } + } + return (this->good_bit_ = false); +} + +ACE_CDR::Boolean +ACE_InputCDR::read_string (ACE_CDR::Char *&x) +{ + // @@ This is a slight violation of "Optimize for the common case", + // i.e. normally the translator will be 0, but OTOH the code is + // smaller and should be better for the cache ;-) ;-) + if (this->char_translator_ != 0) + { + this->good_bit_ = this->char_translator_->read_string (*this, x); + return this->good_bit_; + } + + ACE_CDR::ULong len = 0; + + if (!this->read_ulong (len)) + return false; + + // A check for the length being too great is done later in the + // call to read_char_array but we want to have it done before + // the memory is allocated. + if (len > 0 && len <= this->length()) + { + ACE_NEW_RETURN (x, + ACE_CDR::Char[len], + 0); + + ACE_Auto_Basic_Array_Ptr safe_data (x); + + if (this->read_char_array (x, len)) + { + (void) safe_data.release (); + return true; + } + } + else if (len == 0) + { + // Convert any null strings to empty strings since empty + // strings can cause crashes. (See bug 58.) + ACE_NEW_RETURN (x, + ACE_CDR::Char[1], + 0); + ACE_OS::strcpy (const_cast (x), ""); + return true; + } + + x = 0; + return (this->good_bit_ = false); +} + +ACE_CDR::Boolean +ACE_InputCDR::read_string (ACE_CString &x) +{ + ACE_CDR::Char * data = 0; + if (this->read_string (data)) + { + ACE_Auto_Basic_Array_Ptr safe_data (data); + x = data; + return true; + } + + x = ""; + return (this->good_bit_ = false); +} + +ACE_CDR::Boolean +ACE_InputCDR::read_wstring (ACE_CDR::WChar*& x) +{ + // @@ This is a slight violation of "Optimize for the common case", + // i.e. normally the translator will be 0, but OTOH the code is + // smaller and should be better for the cache ;-) ;-) + if (this->wchar_translator_ != 0) + { + this->good_bit_ = this->wchar_translator_->read_wstring (*this, x); + return this->good_bit_; + } + if (ACE_OutputCDR::wchar_maxbytes_ == 0) + { + errno = EACCES; + return (this->good_bit_ = false); + } + + ACE_CDR::ULong len = 0; + + if (!this->read_ulong (len)) + { + return false; + } + + // A check for the length being too great is done later in the + // call to read_char_array but we want to have it done before + // the memory is allocated. + if (len > 0 && len <= this->length ()) + { + ACE_Auto_Basic_Array_Ptr safe_data; + + if (static_cast (this->major_version_) == 1 + && static_cast (this->minor_version_) == 2) + { + len /= + ACE_Utils::truncate_cast ( + ACE_OutputCDR::wchar_maxbytes_); + + //allocating one extra for the null character needed by applications + ACE_NEW_RETURN (x, + ACE_CDR::WChar [len + 1], + false); + + ACE_auto_ptr_reset (safe_data, x); + + if (this->read_wchar_array (x, len)) + { + + //Null character used by applications to find the end of + //the wstring + //Is this okay with the GIOP 1.2 spec?? + x[len] = '\x00'; + + (void) safe_data.release (); + + return true; + } + } + else + { + ACE_NEW_RETURN (x, + ACE_CDR::WChar [len], + false); + + ACE_auto_ptr_reset (safe_data, x); + + if (this->read_wchar_array (x, len)) + { + (void) safe_data.release (); + + return true; + } + } + } + else if (len == 0) + { + // Convert any null strings to empty strings since empty + // strings can cause crashes. (See bug 58.) + ACE_NEW_RETURN (x, + ACE_CDR::WChar[1], + false); + x[0] = '\x00'; + return true; + } + + this->good_bit_ = false; + x = 0; + return false; +} + +ACE_CDR::Boolean +ACE_InputCDR::read_array (void* x, + size_t size, + size_t align, + ACE_CDR::ULong length) +{ + if (length == 0) + return true; + char* buf = 0; + + if (this->adjust (size * length, align, buf) == 0) + { +#if defined (ACE_DISABLE_SWAP_ON_READ) + ACE_OS::memcpy (x, buf, size*length); +#else + if (!this->do_byte_swap_ || size == 1) + ACE_OS::memcpy (x, buf, size*length); + else + { + char *target = reinterpret_cast (x); + switch (size) + { + case 2: + ACE_CDR::swap_2_array (buf, target, length); + break; + case 4: + ACE_CDR::swap_4_array (buf, target, length); + break; + case 8: + ACE_CDR::swap_8_array (buf, target, length); + break; + case 16: + ACE_CDR::swap_16_array (buf, target, length); + break; + default: + // TODO: print something? + this->good_bit_ = false; + return false; + } + } +#endif /* ACE_DISABLE_SWAP_ON_READ */ + return this->good_bit_; + } + return false; +} + +ACE_CDR::Boolean +ACE_InputCDR::read_wchar_array_i (ACE_CDR::WChar* x, + ACE_CDR::ULong length) +{ + if (length == 0) + return true; + char* buf = 0; + size_t const align = (ACE_OutputCDR::wchar_maxbytes_ == 2) ? + ACE_CDR::SHORT_ALIGN : + ACE_CDR::OCTET_ALIGN; + + if (this->adjust (ACE_OutputCDR::wchar_maxbytes_ * length, align, buf) == 0) + { + if (ACE_OutputCDR::wchar_maxbytes_ == 2) + { + ACE_CDR::UShort *sb = reinterpret_cast (buf); + for (size_t i = 0; i < length; ++i) +#if defined (ACE_DISABLE_SWAP_ON_READ) + x[i] = static_cast (sb[i]); +#else + if (!this->do_byte_swap_) + x[i] = static_cast (sb[i]); + else + { + ACE_CDR::UShort sx; + ACE_CDR::swap_2 (&buf[i * 2], reinterpret_cast (&sx)); + x[i] = static_cast (sx); + } +#endif /* ACE_DISABLE_SWAP_ON_READ */ + } + else + { + for (size_t i = 0; i < length; ++i) + x[i] = static_cast (buf[i]); + } + return this->good_bit_; + } + return false; +} + + +ACE_CDR::Boolean +ACE_InputCDR::read_boolean_array (ACE_CDR::Boolean *x, + ACE_CDR::ULong length) +{ + // Make sure the length of the array isn't greater than the length of + // the stream. + if (length > this->length ()) + { + this->good_bit_ = false; + return false; + } + + // It is hard to optimize this, the spec requires that on the wire + // booleans be represented as a byte with value 0 or 1, but in + // memory it is possible (though very unlikely) that a boolean has + // a non-zero value (different from 1). + // We resort to a simple loop. + for (ACE_CDR::ULong i = 0; i != length && this->good_bit_; ++i) + (void) this->read_boolean (x[i]); + + return this->good_bit_; +} + +ACE_CDR::Boolean +ACE_InputCDR::read_1 (ACE_CDR::Octet *x) +{ + if (this->rd_ptr () < this->wr_ptr ()) + { + *x = *reinterpret_cast (this->rd_ptr ()); + this->start_.rd_ptr (1); + return true; + } + + this->good_bit_ = false; + return false; +} + +ACE_CDR::Boolean +ACE_InputCDR::read_2 (ACE_CDR::UShort *x) +{ + char *buf = 0; + if (this->adjust (ACE_CDR::SHORT_SIZE, buf) == 0) + { +#if !defined (ACE_DISABLE_SWAP_ON_READ) + if (!this->do_byte_swap_) + *x = *reinterpret_cast (buf); + else + ACE_CDR::swap_2 (buf, reinterpret_cast (x)); +#else + *x = *reinterpret_cast (buf); +#endif /* ACE_DISABLE_SWAP_ON_READ */ + return true; + } + this->good_bit_ = false; + return false; +} + +ACE_CDR::Boolean +ACE_InputCDR::read_4 (ACE_CDR::ULong *x) +{ + char *buf = 0; + if (this->adjust (ACE_CDR::LONG_SIZE, buf) == 0) + { +#if !defined (ACE_DISABLE_SWAP_ON_READ) + if (!this->do_byte_swap_) + *x = *reinterpret_cast (buf); + else + ACE_CDR::swap_4 (buf, reinterpret_cast (x)); +#else + *x = *reinterpret_cast (buf); +#endif /* ACE_DISABLE_SWAP_ON_READ */ + return true; + } + this->good_bit_ = false; + return false; +} + +ACE_CDR::Boolean +ACE_InputCDR::read_8 (ACE_CDR::ULongLong *x) +{ + char *buf = 0; + + if (this->adjust (ACE_CDR::LONGLONG_SIZE, buf) == 0) + { +#if !defined (ACE_DISABLE_SWAP_ON_READ) +# if defined (__arm__) && !defined (ACE_HAS_IPHONE) + if (!this->do_byte_swap_) + { + // Convert from Intel format (12345678 => 56781234) + const char *orig = buf; + char *target = reinterpret_cast (x); + register ACE_UINT32 x = + *reinterpret_cast (orig); + register ACE_UINT32 y = + *reinterpret_cast (orig + 4); + *reinterpret_cast (target) = y; + *reinterpret_cast (target + 4) = x; + } + else + { + // Convert from Sparc format (12345678 => 43218765) + const char *orig = buf; + char *target = reinterpret_cast (x); + register ACE_UINT32 x = + *reinterpret_cast (orig); + register ACE_UINT32 y = + *reinterpret_cast (orig + 4); + x = (x << 24) | ((x & 0xff00) << 8) | ((x & 0xff0000) >> 8) | (x >> 24); + y = (y << 24) | ((y & 0xff00) << 8) | ((y & 0xff0000) >> 8) | (y >> 24); + *reinterpret_cast (target) = x; + *reinterpret_cast (target + 4) = y; + } +# else + if (!this->do_byte_swap_) + *x = *reinterpret_cast (buf); + else + ACE_CDR::swap_8 (buf, reinterpret_cast (x)); +# endif /* !__arm__ */ +#else + *x = *reinterpret_cast (buf); +#endif /* ACE_DISABLE_SWAP_ON_READ */ + return true; + } + + this->good_bit_ = false; + return false; +} + +ACE_CDR::Boolean +ACE_InputCDR::read_16 (ACE_CDR::LongDouble *x) +{ + char *buf = 0; + if (this->adjust (ACE_CDR::LONGDOUBLE_SIZE, + ACE_CDR::LONGDOUBLE_ALIGN, + buf) == 0) + { +#if !defined (ACE_DISABLE_SWAP_ON_READ) + if (!this->do_byte_swap_) + *x = *reinterpret_cast (buf); + else + ACE_CDR::swap_16 (buf, reinterpret_cast (x)); +#else + *x = *reinterpret_cast (buf); +#endif /* ACE_DISABLE_SWAP_ON_READ */ + return true; + } + + this->good_bit_ = false; + return false; +} + +ACE_CDR::Boolean +ACE_InputCDR::skip_string (void) +{ + ACE_CDR::ULong len = 0; + if (this->read_ulong (len)) + { + if (this->rd_ptr () + len <= this->wr_ptr ()) + { + this->rd_ptr (len); + return true; + } + this->good_bit_ = false; + } + return false; +} + +ACE_CDR::Boolean +ACE_InputCDR::skip_wstring (void) +{ + ACE_CDR::ULong len = 0; + ACE_CDR::Boolean continue_skipping = read_ulong (len); + + if (continue_skipping && len != 0) + { + if (static_cast (this->major_version_) == 1 + && static_cast (this->minor_version_) == 2) + continue_skipping = this->skip_bytes ((size_t)len); + else + while (continue_skipping && len--) + continue_skipping = this->skip_wchar (); + } + return continue_skipping; +} + +ACE_CDR::Boolean +ACE_InputCDR::skip_bytes (size_t len) +{ + if (this->rd_ptr () + len <= this->wr_ptr ()) + { + this->rd_ptr (len); + return true; + } + this->good_bit_ = false; + return false; +} + +int +ACE_InputCDR::grow (size_t newsize) +{ + if (ACE_CDR::grow (&this->start_, newsize) == -1) + return -1; + + ACE_CDR::mb_align (&this->start_); + this->start_.wr_ptr (newsize); + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + if (newsize > this->start_.total_size ()) + { + this->monitor_->receive (newsize); + } +#endif /* ACE_HAS_MONITOR_POINTS==1 */ + + return 0; +} + +void +ACE_InputCDR::reset (const ACE_Message_Block* data, + int byte_order) +{ + this->reset_byte_order (byte_order); + ACE_CDR::consolidate (&this->start_, data); + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + this->monitor_->receive (this->start_.total_size ()); +#endif /* ACE_HAS_MONITOR_POINTS==1 */ +} + +void +ACE_InputCDR::steal_from (ACE_InputCDR &cdr) +{ + this->do_byte_swap_ = cdr.do_byte_swap_; + this->start_.data_block (cdr.start_.data_block ()->duplicate ()); + + // If the message block had a DONT_DELETE flags, just clear it off.. + this->start_.clr_self_flags (ACE_Message_Block::DONT_DELETE); + this->start_.rd_ptr (cdr.start_.rd_ptr ()); + + this->start_.wr_ptr (cdr.start_.wr_ptr ()); + this->major_version_ = cdr.major_version_; + this->minor_version_ = cdr.minor_version_; + cdr.reset_contents (); + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + this->monitor_->receive (this->start_.total_size ()); +#endif /* ACE_HAS_MONITOR_POINTS==1 */ +} + +void +ACE_InputCDR::exchange_data_blocks (ACE_InputCDR &cdr) +{ + // Exchange byte orders + int const byte_order = cdr.do_byte_swap_; + cdr.do_byte_swap_ = this->do_byte_swap_; + this->do_byte_swap_ = byte_order; + + // Get the destination read and write pointers + size_t const drd_pos = + cdr.start_.rd_ptr () - cdr.start_.base (); + size_t const dwr_pos = + cdr.start_.wr_ptr () - cdr.start_.base (); + + // Get the source read & write pointers + size_t const srd_pos = + this->start_.rd_ptr () - this->start_.base (); + size_t const swr_pos = + this->start_.wr_ptr () - this->start_.base (); + + // Exchange data_blocks. Dont release any of the data blocks. + ACE_Data_Block *dnb = + this->start_.replace_data_block (cdr.start_.data_block ()); + cdr.start_.replace_data_block (dnb); + + // Exchange the flags information.. + ACE_Message_Block::Message_Flags df = cdr.start_.self_flags (); + ACE_Message_Block::Message_Flags sf = this->start_.self_flags (); + + cdr.start_.clr_self_flags (df); + this->start_.clr_self_flags (sf); + + cdr.start_.set_self_flags (sf); + this->start_.set_self_flags (df); + + // Reset the pointers to zero before it is set again. + cdr.start_.reset (); + this->start_.reset (); + + // Set the read and write pointers. + if (cdr.start_.size () >= srd_pos) + { + cdr.start_.rd_ptr (srd_pos); + } + + if (cdr.start_.size () >= swr_pos) + { + cdr.start_.wr_ptr (swr_pos); + } + + if (this->start_.size () >= drd_pos) + { + this->start_.rd_ptr (drd_pos); + } + + if (this->start_.size () >= dwr_pos) + { + this->start_.wr_ptr (dwr_pos); + } + + ACE_CDR::Octet const dmajor = cdr.major_version_; + ACE_CDR::Octet const dminor = cdr.minor_version_; + + // Exchange the GIOP version info + cdr.major_version_ = this->major_version_; + cdr.minor_version_ = this->minor_version_; + + this->major_version_ = dmajor; + this->minor_version_ = dminor; + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + this->monitor_->receive (this->start_.total_size ()); +#endif /* ACE_HAS_MONITOR_POINTS==1 */ +} + +ACE_Data_Block * +ACE_InputCDR::clone_from (ACE_InputCDR &cdr) +{ + this->do_byte_swap_ = cdr.do_byte_swap_; + + // Get the read & write pointer positions in the incoming CDR + // streams + char *rd_ptr = cdr.start_.rd_ptr (); + char *wr_ptr = cdr.start_.wr_ptr (); + + // Now reset the incoming CDR stream + cdr.start_.reset (); + + // As we have reset the stream, try to align the underlying message + // block in the incoming stream + ACE_CDR::mb_align (&cdr.start_); + + // Get the read & write pointer positions again + char *nrd_ptr = cdr.start_.rd_ptr (); + char *nwr_ptr = cdr.start_.wr_ptr (); + + // Actual length of the stream is.. + // @todo: This will look idiotic, but we dont seem to have much of a + // choice. How do we calculate the length of the incoming stream? + // Calling the method before calling reset () would give us the + // wrong length of the stream that needs copying. So we do the + // calulation like this + // (1) We get the and positions of the incoming + // stream. + // (2) Then we reset the stream and then align it. + // (3) We get the and positions again. (Points #1 + // thru #3 has been done already) + // (4) The difference in the and positions gives + // us the following, the actual bytes traversed by the and + // . + // (5) The bytes traversed by the is the actual length of + // the stream. + + // Actual bytes traversed + size_t rd_bytes = rd_ptr - nrd_ptr; + size_t wr_bytes = wr_ptr - nwr_ptr; + + ACE_CDR::mb_align (&this->start_); + + ACE_Data_Block *db = this->start_.data_block (); + + // If the size of the data that needs to be copied are higher than + // what is available, then do a reallocation. + if (wr_bytes > (this->start_.size () - ACE_CDR::MAX_ALIGNMENT)) + { + // @@NOTE: We need to probably add another method to the message + // block interface to simplify this + db = cdr.start_.data_block ()->clone_nocopy (); + + if (db == 0 || db->size ((wr_bytes) + + ACE_CDR::MAX_ALIGNMENT) == -1) + return 0; + + // Replace our data block by using the incoming CDR stream. + db = this->start_.replace_data_block (db); + + // Align the start_ message block. + ACE_CDR::mb_align (&this->start_); + + // Clear the DONT_DELETE flag if it has been set + this->start_.clr_self_flags (ACE_Message_Block::DONT_DELETE); + } + + // Now do the copy + (void) ACE_OS::memcpy (this->start_.wr_ptr (), + cdr.start_.rd_ptr (), + wr_bytes); + + // Set the read pointer position to the same point as that was in + // cdr. + this->start_.rd_ptr (rd_bytes); + this->start_.wr_ptr (wr_bytes); + + // We have changed the read & write pointers for the incoming + // stream. Set them back to the positions that they were before.. + cdr.start_.rd_ptr (rd_bytes); + cdr.start_.wr_ptr (wr_bytes); + + this->major_version_ = cdr.major_version_; + this->minor_version_ = cdr.minor_version_; + + // Copy the char/wchar translators + this->char_translator_ = cdr.char_translator_; + this->wchar_translator_ = cdr.wchar_translator_; + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + this->monitor_->receive (this->start_.total_size ()); +#endif /* ACE_HAS_MONITOR_POINTS==1 */ + + return db; +} + +ACE_Message_Block* +ACE_InputCDR::steal_contents (void) +{ + ACE_Message_Block* block = this->start_.clone (); + this->start_.data_block (block->data_block ()->clone ()); + + // If at all our message had a DONT_DELETE flag set, just clear it + // off. + this->start_.clr_self_flags (ACE_Message_Block::DONT_DELETE); + + ACE_CDR::mb_align (&this->start_); + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + this->monitor_->receive (this->start_.total_size ()); +#endif /* ACE_HAS_MONITOR_POINTS==1 */ + + return block; +} + +void +ACE_InputCDR::reset_contents (void) +{ + this->start_.data_block (this->start_.data_block ()->clone_nocopy ()); + + // Reset the flags... + this->start_.clr_self_flags (ACE_Message_Block::DONT_DELETE); + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + this->monitor_->receive (this->start_.total_size ()); +#endif /* ACE_HAS_MONITOR_POINTS==1 */ +} + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + +void +ACE_InputCDR::register_monitor (const char *id) +{ + this->monitor_->name (id); + this->monitor_->add_to_registry (); +} + +void +ACE_InputCDR::unregister_monitor (void) +{ + this->monitor_->remove_from_registry (); +} + +#endif /* ACE_HAS_MONITOR_POINTS==1 */ + +// -------------------------------------------------------------- + +ACE_Char_Codeset_Translator::~ACE_Char_Codeset_Translator (void) +{ +} + +// -------------------------------------------------------------- + +ACE_WChar_Codeset_Translator::~ACE_WChar_Codeset_Translator (void) +{ +} + +// -------------------------------------------------------------- + +ACE_CDR::Boolean +operator<< (ACE_OutputCDR &os, const ACE_CString &x) +{ + os.write_string (x); + return os.good_bit (); +} + +ACE_CDR::Boolean +operator>> (ACE_InputCDR &is, ACE_CString &x) +{ + is.read_string (x); + return is.good_bit (); +} + +#if defined (GEN_OSTREAM_OPS) + +std::ostream& +operator<< (std::ostream &os, ACE_OutputCDR::from_boolean x) +{ + return (x.val_ ? os << "true" : os << "false"); +} + +std::ostream& +operator<< (std::ostream &os, ACE_OutputCDR::from_char x) +{ + return os << '\'' << x.val_ << '\''; +} + +std::ostream& +operator<< (std::ostream &os, ACE_OutputCDR::from_wchar x) +{ + os.setf (ios_base::showbase); + os.setf (ios_base::hex, ios_base::basefield); + os << x.val_; + os.unsetf (ios_base::showbase); + os.setf (ios_base::dec, ios_base::basefield); + return os; +} + +std::ostream& +operator<< (std::ostream &os, ACE_OutputCDR::from_octet x) +{ + // Same format (hex) and no risk of overflow. + ACE_CDR::WChar w = static_cast (x.val_); + ACE_OutputCDR::from_wchar tmp (w); + return os << tmp; +} + +#endif /* GEN_OSTREAM_OPS */ + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/CDR_Stream.h b/dep/acelite/ace/CDR_Stream.h new file mode 100644 index 00000000000..0a200dc56dd --- /dev/null +++ b/dep/acelite/ace/CDR_Stream.h @@ -0,0 +1,1402 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file CDR_Stream.h + * + * $Id: CDR_Stream.h 84527 2009-02-19 14:01:42Z johnnyw $ + * + * ACE Common Data Representation (CDR) marshaling and demarshaling + * classes. + * + * This implementation was inspired in the CDR class in SunSoft's + * IIOP engine, but has a completely different implementation and a + * different interface too. + * + * The current implementation assumes that the host has 1-byte, + * 2-byte and 4-byte integral types, and that it has single + * precision and double precision IEEE floats. + * Those assumptions are pretty good these days, with Crays being + * the only known exception. + * + * Optimizations + * ------------- + * ACE_LACKS_CDR_ALIGNMENT + * @author Arvind S. Krishna + * + * CDR stream ignores alignment when marshaling data. Use this option + * only when ACE_DISABLE_SWAP_ON_READ can be enabled. This option requires + * ACE CDR engine to do both marshaling and demarshaling. + * + * + * @author TAO version by Aniruddha Gokhale + * @author Carlos O'Ryan + * @author ACE version by Jeff Parsons + * @author Istvan Buki + * @author Codeset translation by Jim Rogers + */ +//============================================================================= + +#ifndef ACE_CDR_STREAM_H +#define ACE_CDR_STREAM_H + +#include /**/ "ace/pre.h" + +#include "ace/CDR_Base.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/SStringfwd.h" +#include "ace/Message_Block.h" + +#if defined (GEN_OSTREAM_OPS) +#include "ace/streams.h" +#endif /* GEN_OSTREAM_OPS */ + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) +#include "Monitor_Size.h" +#endif /* ACE_HAS_MONITOR_POINTS==1 */ + + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +class ACE_Char_Codeset_Translator; +class ACE_WChar_Codeset_Translator; + +class ACE_InputCDR; + +/** + * @class ACE_OutputCDR + * + * @brief A CDR stream for marshalling data, most often for transmission to + * another system which may or may not have the same byte order. + * + * This class is based on the the CORBA spec for Java (98-02-29), + * java class omg.org.CORBA.portable.OutputStream. It diverts in + * a few ways: + * @li Operations taking arrays don't have offsets, because in C++ + * it is easier to describe an array starting from x+offset. + * @li Operations return an error status, because exceptions are + * not widely available in C++ (yet). + */ +class ACE_Export ACE_OutputCDR +{ +public: + /** + * The Codeset translators need access to some private members to + * efficiently marshal arrays + * For reading from an output CDR stream. + */ + friend class ACE_Char_Codeset_Translator; + friend class ACE_WChar_Codeset_Translator; + friend class ACE_InputCDR; + + /** + * Default constructor; allows one to set byte ordering, allocators, and + * tuning information. + * + * @param size Causes constructor to preallocate @a size bytes; if + * @a size is 0 it allocates the default size. + * + * @param byte_order The byte order that data will have within this + * object. Unless otherwise specified, the byte order + * will be the order native to the hardware this is + * executed on. To force the marshalled data to have + * a specific order, specify one of the values defined + * in ACE_CDR::Byte_Order. + * @note The @c ACE_ENABLE_SWAP_ON_WRITE config macro + * must be set for any local byte swapping to occur + * as data is inserted into an ACE_OutputCDR object. + */ + ACE_OutputCDR (size_t size = 0, + int byte_order = ACE_CDR::BYTE_ORDER_NATIVE, + ACE_Allocator* buffer_allocator = 0, + ACE_Allocator* data_block_allocator = 0, + ACE_Allocator* message_block_allocator = 0, + size_t memcpy_tradeoff = ACE_DEFAULT_CDR_MEMCPY_TRADEOFF, + ACE_CDR::Octet major_version = ACE_CDR_GIOP_MAJOR_VERSION, + ACE_CDR::Octet minor_version = ACE_CDR_GIOP_MINOR_VERSION); + + /// Build a CDR stream with an initial buffer, it will *not* remove + /// @a data, since it did not allocated it. It's important to be careful + /// with the alignment of @a data. + /** + * Create an output stream from an arbitrary buffer, care must be + * exercised with alignment, because this contructor will align if + * needed. In this case @a data will not point to the start of the + * output stream. @c begin()->rd_ptr() points to the start of the + * output stream. See @c ACE_ptr_align_binary() to properly align a + * pointer and use ACE_CDR::MAX_ALIGNMENT for the correct alignment. + */ + ACE_OutputCDR (char *data, + size_t size, + int byte_order = ACE_CDR::BYTE_ORDER_NATIVE, + ACE_Allocator* buffer_allocator = 0, + ACE_Allocator* data_block_allocator = 0, + ACE_Allocator* message_block_allocator = 0, + size_t memcpy_tradeoff = ACE_DEFAULT_CDR_MEMCPY_TRADEOFF, + ACE_CDR::Octet giop_major_version = ACE_CDR_GIOP_MAJOR_VERSION, + ACE_CDR::Octet giop_minor_version = ACE_CDR_GIOP_MINOR_VERSION); + + /// Build a CDR stream with an initial data block, it will *not* remove + /// , since it did not allocated it. It's important to be + // careful with the alignment of . + /** + * Create an output stream from an arbitrary data block, care must be + * exercised with alignment, because this contructor will align if + * needed. In this case @a data_block will not point to the + * start of the output stream. begin()->rd_ptr() points to the start + * off the output stream. See ACE_ptr_align_binary() to properly align a + * pointer and use ACE_CDR::MAX_ALIGNMENT for the correct alignment. + */ + ACE_OutputCDR (ACE_Data_Block *data_block, + int byte_order = ACE_CDR::BYTE_ORDER_NATIVE, + ACE_Allocator* message_block_allocator = 0, + size_t memcpy_tradeoff = ACE_DEFAULT_CDR_MEMCPY_TRADEOFF, + ACE_CDR::Octet giop_major_version = ACE_CDR_GIOP_MAJOR_VERSION, + ACE_CDR::Octet giop_minor_version = ACE_CDR_GIOP_MINOR_VERSION); + + /// Build a CDR stream with an initial Message_Block chain, it will + /// *not* remove @a data, since it did not allocate it. + ACE_OutputCDR (ACE_Message_Block *data, + int byte_order = ACE_CDR::BYTE_ORDER_NATIVE, + size_t memcpy_tradeoff = ACE_DEFAULT_CDR_MEMCPY_TRADEOFF, + ACE_CDR::Octet giop_major_version = ACE_CDR_GIOP_MAJOR_VERSION, + ACE_CDR::Octet giop_minor_version = ACE_CDR_GIOP_MINOR_VERSION); + + /// destructor + ~ACE_OutputCDR (void); + + /** + * Disambiguate overload when inserting booleans, octets, chars, and + * bounded strings. + */ + //@{ @name Helper classes + + struct ACE_Export from_boolean + { + explicit from_boolean (ACE_CDR::Boolean b); + ACE_CDR::Boolean val_; + }; + + struct ACE_Export from_octet + { + explicit from_octet (ACE_CDR::Octet o); + ACE_CDR::Octet val_; + }; + + struct ACE_Export from_char + { + explicit from_char (ACE_CDR::Char c); + ACE_CDR::Char val_; + }; + + struct ACE_Export from_wchar + { + explicit from_wchar (ACE_CDR::WChar wc); + ACE_CDR::WChar val_; + }; + + struct ACE_Export from_string + { + from_string (ACE_CDR::Char* s, + ACE_CDR::ULong b, + ACE_CDR::Boolean nocopy = 0); + from_string (const ACE_CDR::Char* s, + ACE_CDR::ULong b, + ACE_CDR::Boolean nocopy = 0); + ACE_CDR::Char *val_; + ACE_CDR::ULong bound_; + ACE_CDR::Boolean nocopy_; + }; + + struct ACE_Export from_wstring + { + from_wstring (ACE_CDR::WChar* ws, + ACE_CDR::ULong b, + ACE_CDR::Boolean nocopy = 0); + from_wstring (const ACE_CDR::WChar* ws, + ACE_CDR::ULong b, + ACE_CDR::Boolean nocopy = 0); + ACE_CDR::WChar *val_; + ACE_CDR::ULong bound_; + ACE_CDR::Boolean nocopy_; + }; + //@} + + /** + * @{ @name Write operations + * Return 0 on failure and 1 on success. + */ + ACE_CDR::Boolean write_boolean (ACE_CDR::Boolean x); + ACE_CDR::Boolean write_char (ACE_CDR::Char x); + ACE_CDR::Boolean write_wchar (ACE_CDR::WChar x); + ACE_CDR::Boolean write_octet (ACE_CDR::Octet x); + ACE_CDR::Boolean write_short (ACE_CDR::Short x); + ACE_CDR::Boolean write_ushort (ACE_CDR::UShort x); + ACE_CDR::Boolean write_long (ACE_CDR::Long x); + ACE_CDR::Boolean write_ulong (ACE_CDR::ULong x); + ACE_CDR::Boolean write_longlong (const ACE_CDR::LongLong &x); + ACE_CDR::Boolean write_ulonglong (const ACE_CDR::ULongLong &x); + ACE_CDR::Boolean write_float (ACE_CDR::Float x); + ACE_CDR::Boolean write_double (const ACE_CDR::Double &x); + ACE_CDR::Boolean write_longdouble (const ACE_CDR::LongDouble &x); + + /// For string we offer methods that accept a precomputed length. + ACE_CDR::Boolean write_string (const ACE_CDR::Char *x); + ACE_CDR::Boolean write_string (ACE_CDR::ULong len, + const ACE_CDR::Char *x); + ACE_CDR::Boolean write_string (const ACE_CString &x); + ACE_CDR::Boolean write_wstring (const ACE_CDR::WChar *x); + ACE_CDR::Boolean write_wstring (ACE_CDR::ULong length, + const ACE_CDR::WChar *x); + //@} + + /// @note the portion written starts at @a x and ends + /// at @a x + @a length. + /// The length is *NOT* stored into the CDR stream. + //@{ @name Array write operations + ACE_CDR::Boolean write_boolean_array (const ACE_CDR::Boolean *x, + ACE_CDR::ULong length); + ACE_CDR::Boolean write_char_array (const ACE_CDR::Char *x, + ACE_CDR::ULong length); + ACE_CDR::Boolean write_wchar_array (const ACE_CDR::WChar* x, + ACE_CDR::ULong length); + ACE_CDR::Boolean write_octet_array (const ACE_CDR::Octet* x, + ACE_CDR::ULong length); + ACE_CDR::Boolean write_short_array (const ACE_CDR::Short *x, + ACE_CDR::ULong length); + ACE_CDR::Boolean write_ushort_array (const ACE_CDR::UShort *x, + ACE_CDR::ULong length); + ACE_CDR::Boolean write_long_array (const ACE_CDR::Long *x, + ACE_CDR::ULong length); + ACE_CDR::Boolean write_ulong_array (const ACE_CDR::ULong *x, + ACE_CDR::ULong length); + ACE_CDR::Boolean write_longlong_array (const ACE_CDR::LongLong* x, + ACE_CDR::ULong length); + ACE_CDR::Boolean write_ulonglong_array (const ACE_CDR::ULongLong *x, + ACE_CDR::ULong length); + ACE_CDR::Boolean write_float_array (const ACE_CDR::Float *x, + ACE_CDR::ULong length); + ACE_CDR::Boolean write_double_array (const ACE_CDR::Double *x, + ACE_CDR::ULong length); + ACE_CDR::Boolean write_longdouble_array (const ACE_CDR::LongDouble* x, + ACE_CDR::ULong length); + + /// Write an octet array contained inside a MB, this can be optimized + /// to minimize copies. + ACE_CDR::Boolean write_octet_array_mb (const ACE_Message_Block* mb); + //@} + + /** + * @{ @name Placeholder/replace operations + * Facilitates writing a placeholder into a CDR stream to be replaced + * later with a different value. + * + * @note An example use for this facility is: + * @code + ACE_OutputCDR strm; + ... // insert values... + char *pos = strm.write_long_placeholder (); + ... // insert more values + ACE_CDR::Long real_val; // Somehow assign the "correct" value + strm.replace (real_val, pos); // Replace earlier placeholder + @endcode + */ + + /** + * Write a placeholder into the stream. The placeholder's pointer + * is returned so it may later be passed as the @a loc argument to + * replace (). + * These methods align the stream's write pointer properly prior to + * writing the placeholder. + * + * @retval Pointer to the placeholder; 0 if there is not enough space + * in the stream and memory could not be allocated. + */ + char* write_long_placeholder (void); + char* write_short_placeholder (void); + + /** + * Writes a new value into a specific location. This is commonly + * used to update a prior "placeholder" location in the stream. + * The specified location is assumed to have proper CDR alignment for the + * type to insert. This requirement is satisfied by using one of the + * placeholder-writing methods to align the stream for the anticipated + * value and obtain the correct location. + * Treatment of @a x with repect to byte swapping is the same as for when + * any value is inserted. + * + * @param x The value to insert into the specified location. + * @param loc The location at which to insert @a x. @a loc must be a valid + * position within the stream's current set of message blocks. + * + * @sa write_long_placeholder(), write_short_placeholder () + */ + ACE_CDR::Boolean replace (ACE_CDR::Long x, char* loc); + ACE_CDR::Boolean replace (ACE_CDR::Short x, char* loc); + //@} + + /** + * Return 0 on failure and 1 on success. + */ + //@{ @name Append contents of own CDR stream to another + ACE_CDR::Boolean append_boolean (ACE_InputCDR &); + ACE_CDR::Boolean append_char (ACE_InputCDR &); + ACE_CDR::Boolean append_wchar (ACE_InputCDR &); + ACE_CDR::Boolean append_octet (ACE_InputCDR &); + ACE_CDR::Boolean append_short (ACE_InputCDR &); + ACE_CDR::Boolean append_ushort (ACE_InputCDR &); + ACE_CDR::Boolean append_long (ACE_InputCDR &); + ACE_CDR::Boolean append_ulong (ACE_InputCDR &); + ACE_CDR::Boolean append_longlong (ACE_InputCDR &); + ACE_CDR::Boolean append_ulonglong (ACE_InputCDR &); + ACE_CDR::Boolean append_float (ACE_InputCDR &); + ACE_CDR::Boolean append_double (ACE_InputCDR &); + ACE_CDR::Boolean append_longdouble (ACE_InputCDR &); + + ACE_CDR::Boolean append_wstring (ACE_InputCDR &); + ACE_CDR::Boolean append_string (ACE_InputCDR &); + //@} + + /// Returns @c false if an error has ocurred. + /** + * @note The only expected error is to run out of memory. + */ + bool good_bit (void) const; + + /// Reuse the CDR stream to write on the old buffer. + void reset (void); + + /// Add the length of each message block in the chain. + size_t total_length (void) const; + + /** + * Return the start of the message block chain for this CDR stream. + * @note The complete CDR stream is represented by a chain of + * message blocks. + */ + const ACE_Message_Block *begin (void) const; + + /// Return the last message in the chain that is is use. + const ACE_Message_Block *end (void) const; + + /// Return the message block in chain. + const ACE_Message_Block *current (void) const; + + /// Replace the message block chain with a single message block. + /** + * Upon successful completion, there will be a single message block + * containing the data from the complete message block chain. + * + * @note The only expected error is to run out of memory. + */ + int consolidate (void); + + /** + * Access the underlying buffer (read only). @note This + * method only returns a pointer to the first block in the + * chain. + */ + const char *buffer (void) const; + + /** + * Return the size of first message block in the block chain. @note This + * method only returns information about the first block in the + * chain. + */ + size_t length (void) const; + + /** + * Utility function to allow the user more flexibility. + * Pads the stream up to the nearest -byte boundary. + * Argument MUST be a power of 2. + * Returns 0 on success and -1 on failure. + */ + int align_write_ptr (size_t alignment); + + /// Access the codeset translators. They can be null! + ACE_Char_Codeset_Translator *char_translator (void) const; + ACE_WChar_Codeset_Translator *wchar_translator (void) const; + + /// Set the char codeset translator. + void char_translator (ACE_Char_Codeset_Translator *); + /// Set the wchar codeset translator. + void wchar_translator (ACE_WChar_Codeset_Translator *); + + /// set the global size of serialized wchars. This may be different + /// than the size of a wchar_t. + static void wchar_maxbytes (size_t max_bytes); + + /// access the serialized size of wchars. + static size_t wchar_maxbytes (void); + + /** + * Return alignment of the wr_ptr(), with respect to the start of + * the CDR stream. This is not the same as the alignment of + * current->wr_ptr()! + */ + size_t current_alignment (void) const; + + void current_alignment (size_t current_alignment); + + /** + * Returns (in @a buf) the next position in the buffer aligned to + * @a size, it advances the Message_Block wr_ptr past the data + * (i.e., @a buf + @a size). If necessary it grows the Message_Block + * buffer. Sets the good_bit to false and returns a -1 on failure. + */ + int adjust (size_t size, + char *&buf); + + /// As above, but now the size and alignment requirements may be + /// different. + int adjust (size_t size, + size_t align, + char *&buf); + + /// Returns true if this stream is writing in non-native byte order + /// and false otherwise. For example, it would be true if either + /// ACE_ENABLE_SWAP_ON_WRITE is defined or a specific byte order was + /// specified for this stream. + bool do_byte_swap (void) const; + + /// Returns the byte order this stream is marshaling data in. Will be one + /// of the values in ACE_CDR::Byte_Order. + int byte_order (void) const; + + /// For use by a gateway, which creates the output stream for the + /// reply to the client in its native byte order, but which must + /// send the reply in the byte order of the target's reply to the + /// gateway. + void reset_byte_order (int byte_order); + + /// set GIOP version info + void set_version (ACE_CDR::Octet major, ACE_CDR::Octet minor); + + /// Set the underlying GIOP version.. + void get_version (ACE_CDR::Octet &major, ACE_CDR::Octet &minor); + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + /// Register and unregister our buffer size monitor. + void register_monitor (const char* id); + void unregister_monitor (void); +#endif /* ACE_HAS_MONITOR_POINTS==1 */ + +private: + + // Find the message block in the chain of message blocks + // that the provide location locates. + ACE_Message_Block* find (char* loc); + + /// disallow copying... + ACE_OutputCDR (const ACE_OutputCDR& rhs); + ACE_OutputCDR& operator= (const ACE_OutputCDR& rhs); + + ACE_CDR::Boolean write_1 (const ACE_CDR::Octet *x); + ACE_CDR::Boolean write_2 (const ACE_CDR::UShort *x); + ACE_CDR::Boolean write_4 (const ACE_CDR::ULong *x); + ACE_CDR::Boolean write_8 (const ACE_CDR::ULongLong *x); + ACE_CDR::Boolean write_16 (const ACE_CDR::LongDouble *x); + + /** + * write an array of @a length elements, each of @a size bytes and the + * start aligned at a multiple of . The elements are assumed + * to be packed with the right alignment restrictions. It is mostly + * designed for buffers of the basic types. + * + * This operation uses ; as explained above it is expected + * that using assignment is faster that for one element, + * but for several elements should be more efficient, it + * could be interesting to find the break even point and optimize + * for that case, but that would be too platform dependent. + */ + ACE_CDR::Boolean write_array (const void *x, + size_t size, + size_t align, + ACE_CDR::ULong length); + + + ACE_CDR::Boolean write_wchar_array_i (const ACE_CDR::WChar* x, + ACE_CDR::ULong length); + + + /** + * Grow the CDR stream. When it returns @a buf contains a pointer to + * memory in the CDR stream, with at least @a size bytes ahead of it + * and aligned to an boundary. It moved the to . + */ + int grow_and_adjust (size_t size, + size_t align, + char *&buf); + +private: + /// The start of the chain of message blocks. + ACE_Message_Block start_; + + /// The current block in the chain where we are writing. + ACE_Message_Block *current_; + +#if !defined (ACE_LACKS_CDR_ALIGNMENT) + /** + * The current alignment as measured from the start of the buffer. + * Usually this coincides with the alignment of the buffer in + * memory, but, when we chain another buffer this "quasi invariant" + * is broken. + * The current_alignment is used to readjust the buffer following + * the stolen message block. + */ + size_t current_alignment_; +#endif /* ACE_LACKS_CDR_ALIGNMENT */ + + /** + * Is the current block writable. When we steal a buffer from the + * user and just chain it into the message block we are not supposed + * to write on it, even if it is past the start and end of the + * buffer. + */ + bool current_is_writable_; + + /** + * If not zero swap bytes at writing so the created CDR stream byte + * order does *not* match the machine byte order. The motivation + * for such a beast is that in some setting a few (fast) machines + * can be serving hundreds of slow machines with the opposite byte + * order, so it makes sense (as a load balancing device) to put the + * responsibility in the writers. THIS IS NOT A STANDARD IN CORBA, + * USE AT YOUR OWN RISK + */ + bool do_byte_swap_; + + /// Set to false when an error ocurrs. + bool good_bit_; + + /// Break-even point for copying. + size_t const memcpy_tradeoff_; + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + ACE::Monitor_Control::Size_Monitor *monitor_; +#endif /* ACE_HAS_MONITOR_POINTS==1 */ + +protected: + /// GIOP version information + ACE_CDR::Octet major_version_; + ACE_CDR::Octet minor_version_; + + /// If not nil, invoke for translation of character and string data. + ACE_Char_Codeset_Translator *char_translator_; + ACE_WChar_Codeset_Translator *wchar_translator_; + + /** + * Some wide char codesets may be defined with a maximum number + * of bytes that is smaller than the size of a wchar_t. This means + * that the CDR cannot simply memcpy a block of wchars to and from + * the stream, but must instead realign the bytes appropriately. + * In cases when wchar i/o is not allowed, such as with GIOP 1.0, + * or not having a native wchar codeset defined, the maxbytes is + * set to zero, indicating no wchar data is allowed. + */ + static size_t wchar_maxbytes_; +}; + + +// **************************************************************** + +/** + * @class ACE_InputCDR + * + * @brief A CDR stream for demarshalling CDR-encoded data. + * + * This class is based on the the CORBA spec for Java (98-02-29), + * java class omg.org.CORBA.portable.InputStream. It diverts in a + * few ways: + * @li Operations to retrieve basic types take parameters by + * reference. + * @li Operations taking arrays don't have offsets, because in C++ + * it is easier to describe an array starting from x+offset. + * @li Operations return an error status, because exceptions are + * not widely available in C++ (yet). + */ +class ACE_Export ACE_InputCDR +{ +public: + // The translators need privileged access to efficiently demarshal + // arrays and such. + friend class ACE_Char_Codeset_Translator; + friend class ACE_WChar_Codeset_Translator; + + /** + * Create an input stream from an arbitrary buffer. The buffer must + * be properly aligned because this contructor will *not* work if + * the buffer is aligned unproperly.See ACE_ptr_align_binary() for + * instructions on how to align a pointer properly and use + * ACE_CDR::MAX_ALIGNMENT for the correct alignment. + */ + ACE_InputCDR (const char *buf, + size_t bufsiz, + int byte_order = ACE_CDR::BYTE_ORDER_NATIVE, + ACE_CDR::Octet major_version = ACE_CDR_GIOP_MAJOR_VERSION, + ACE_CDR::Octet minor_version = ACE_CDR_GIOP_MINOR_VERSION); + + /// Create an empty input stream. The caller is responsible for + /// putting the right data and providing the right alignment. + ACE_InputCDR (size_t bufsiz, + int byte_order = ACE_CDR::BYTE_ORDER_NATIVE, + ACE_CDR::Octet major_version = ACE_CDR_GIOP_MAJOR_VERSION, + ACE_CDR::Octet minor_version = ACE_CDR_GIOP_MINOR_VERSION); + + /// Create an input stream from an ACE_Message_Block + /** + * The alignment of the @a data block is carried into the new + * ACE_InputCDR object. This constructor either increments the + * @a data reference count, or copies the data (if it's a compound + * message block) so the caller can release the block immediately + * upon return. + */ + ACE_InputCDR (const ACE_Message_Block *data, + int byte_order = ACE_CDR::BYTE_ORDER_NATIVE, + ACE_CDR::Octet major_version = ACE_CDR_GIOP_MAJOR_VERSION, + ACE_CDR::Octet minor_version = ACE_CDR_GIOP_MINOR_VERSION, + ACE_Lock* lock = 0); + + /// Create an input stream from an ACE_Data_Block. The + /// indicates whether the @a data can be deleted by the CDR stream + /// or not + ACE_InputCDR (ACE_Data_Block *data, + ACE_Message_Block::Message_Flags flag = 0, + int byte_order = ACE_CDR::BYTE_ORDER_NATIVE, + ACE_CDR::Octet major_version = ACE_CDR_GIOP_MAJOR_VERSION, + ACE_CDR::Octet minor_version = ACE_CDR_GIOP_MINOR_VERSION); + + /// Create an input stream from an ACE_Data_Block. It also sets the + /// read and write pointers at the desired positions. This would be + /// helpful if the applications desires to create a new CDR stream + /// from a semi-processed datablock. + ACE_InputCDR (ACE_Data_Block *data, + ACE_Message_Block::Message_Flags flag, + size_t read_pointer_position, + size_t write_pointer_position, + int byte_order = ACE_CDR::BYTE_ORDER_NATIVE, + ACE_CDR::Octet major_version = ACE_CDR_GIOP_MAJOR_VERSION, + ACE_CDR::Octet minor_version = ACE_CDR_GIOP_MINOR_VERSION); + + /** + * These make a copy of the current stream state, but do not copy + * the internal buffer, so the same stream can be read multiple + * times efficiently. + */ + ACE_InputCDR (const ACE_InputCDR& rhs); + + ACE_InputCDR& operator= (const ACE_InputCDR& rhs); + + /// When interpreting indirected TypeCodes it is useful to make a + /// "copy" of the stream starting in the new position. + ACE_InputCDR (const ACE_InputCDR& rhs, + size_t size, + ACE_CDR::Long offset); + + /// This creates an encapsulated stream, the first byte must be (per + /// the spec) the byte order of the encapsulation. + ACE_InputCDR (const ACE_InputCDR& rhs, + size_t size); + + /// Create an input CDR from an output CDR. + ACE_InputCDR (const ACE_OutputCDR& rhs, + ACE_Allocator* buffer_allocator = 0, + ACE_Allocator* data_block_allocator = 0, + ACE_Allocator* message_block_allocator = 0); + + /// Helper class to transfer the contents from one input CDR to + /// another without requiring any extra memory allocations, data + /// copies or too many temporaries. + struct ACE_Export Transfer_Contents + { + Transfer_Contents (ACE_InputCDR &rhs); + + ACE_InputCDR &rhs_; + }; + /// Transfer the contents from to a new CDR + ACE_InputCDR (Transfer_Contents rhs); + + /// Destructor + ~ACE_InputCDR (void); + + /// Disambiguate overloading when extracting octets, chars, + /// booleans, and bounded strings + //@{ @name Helper classes + + struct ACE_Export to_boolean + { + explicit to_boolean (ACE_CDR::Boolean &b); + ACE_CDR::Boolean &ref_; + }; + + struct ACE_Export to_char + { + explicit to_char (ACE_CDR::Char &c); + ACE_CDR::Char &ref_; + }; + + struct ACE_Export to_wchar + { + explicit to_wchar (ACE_CDR::WChar &wc); + ACE_CDR::WChar &ref_; + }; + + struct ACE_Export to_octet + { + explicit to_octet (ACE_CDR::Octet &o); + ACE_CDR::Octet &ref_; + }; + + struct ACE_Export to_string + { + /** + * @deprecated The constructor taking a non-const string is now + * deprecated (C++ mapping 00-01-02), but we keep it + * around for backward compatibility. + */ + to_string (ACE_CDR::Char *&s, + ACE_CDR::ULong b); + to_string (const ACE_CDR::Char *&s, + ACE_CDR::ULong b); + const ACE_CDR::Char *&val_; + ACE_CDR::ULong bound_; + }; + + struct ACE_Export to_wstring + { + /// The constructor taking a non-const wstring is + /// now deprecated (C++ mapping 00-01-02), but we + /// keep it around for backward compatibility. + to_wstring (ACE_CDR::WChar *&ws, + ACE_CDR::ULong b); + to_wstring (const ACE_CDR::WChar *&ws, + ACE_CDR::ULong b); + const ACE_CDR::WChar *&val_; + ACE_CDR::ULong bound_; + }; + //@} + + /** + * Return @c false on failure and @c true on success. + */ + //@{ @name Read basic IDL types + ACE_CDR::Boolean read_boolean (ACE_CDR::Boolean& x); + ACE_CDR::Boolean read_char (ACE_CDR::Char &x); + ACE_CDR::Boolean read_wchar (ACE_CDR::WChar& x); + ACE_CDR::Boolean read_octet (ACE_CDR::Octet& x); + ACE_CDR::Boolean read_short (ACE_CDR::Short &x); + ACE_CDR::Boolean read_ushort (ACE_CDR::UShort &x); + ACE_CDR::Boolean read_long (ACE_CDR::Long &x); + ACE_CDR::Boolean read_ulong (ACE_CDR::ULong &x); + ACE_CDR::Boolean read_longlong (ACE_CDR::LongLong& x); + ACE_CDR::Boolean read_ulonglong (ACE_CDR::ULongLong& x); + ACE_CDR::Boolean read_float (ACE_CDR::Float &x); + ACE_CDR::Boolean read_double (ACE_CDR::Double &x); + ACE_CDR::Boolean read_longdouble (ACE_CDR::LongDouble &x); + + ACE_CDR::Boolean read_string (ACE_CDR::Char *&x); + ACE_CDR::Boolean read_string (ACE_CString &x); + ACE_CDR::Boolean read_wstring (ACE_CDR::WChar*& x); + //@} + + /** + * The buffer @a x must be large enough to contain @a length + * elements. + * Return @c false on failure and @c true on success. + */ + //@{ @name Read basic IDL types arrays + ACE_CDR::Boolean read_boolean_array (ACE_CDR::Boolean* x, + ACE_CDR::ULong length); + ACE_CDR::Boolean read_char_array (ACE_CDR::Char *x, + ACE_CDR::ULong length); + ACE_CDR::Boolean read_wchar_array (ACE_CDR::WChar* x, + ACE_CDR::ULong length); + ACE_CDR::Boolean read_octet_array (ACE_CDR::Octet* x, + ACE_CDR::ULong length); + ACE_CDR::Boolean read_short_array (ACE_CDR::Short *x, + ACE_CDR::ULong length); + ACE_CDR::Boolean read_ushort_array (ACE_CDR::UShort *x, + ACE_CDR::ULong length); + ACE_CDR::Boolean read_long_array (ACE_CDR::Long *x, + ACE_CDR::ULong length); + ACE_CDR::Boolean read_ulong_array (ACE_CDR::ULong *x, + ACE_CDR::ULong length); + ACE_CDR::Boolean read_longlong_array (ACE_CDR::LongLong* x, + ACE_CDR::ULong length); + ACE_CDR::Boolean read_ulonglong_array (ACE_CDR::ULongLong* x, + ACE_CDR::ULong length); + ACE_CDR::Boolean read_float_array (ACE_CDR::Float *x, + ACE_CDR::ULong length); + ACE_CDR::Boolean read_double_array (ACE_CDR::Double *x, + ACE_CDR::ULong length); + ACE_CDR::Boolean read_longdouble_array (ACE_CDR::LongDouble* x, + ACE_CDR::ULong length); + //@} + + /** + * Return @c false on failure and @c true on success. + */ + //@{ @name Skip elements + ACE_CDR::Boolean skip_boolean (void); + ACE_CDR::Boolean skip_char (void); + ACE_CDR::Boolean skip_wchar (void); + ACE_CDR::Boolean skip_octet (void); + ACE_CDR::Boolean skip_short (void); + ACE_CDR::Boolean skip_ushort (void); + ACE_CDR::Boolean skip_long (void); + ACE_CDR::Boolean skip_ulong (void); + ACE_CDR::Boolean skip_longlong (void); + ACE_CDR::Boolean skip_ulonglong (void); + ACE_CDR::Boolean skip_float (void); + ACE_CDR::Boolean skip_double (void); + ACE_CDR::Boolean skip_longdouble (void); + //@} + + /** + * The next field must be a string, this method skips it. It is + * useful in parsing a TypeCode. + * @return @c false on failure and @c true on success. + */ + ACE_CDR::Boolean skip_wstring (void); + ACE_CDR::Boolean skip_string (void); + + /// Skip @a n bytes in the CDR stream. + /** + * @return @c false on failure and @c true on success. + */ + ACE_CDR::Boolean skip_bytes (size_t n); + + /// returns @c false if a problem has been detected. + bool good_bit (void) const; + + /** + * @return The start of the message block chain for this CDR + * stream. + * + * @note In the current implementation the chain has length 1, but + * we are planning to change that. + */ + const ACE_Message_Block* start (void) const; + + // = The following functions are useful to read the contents of the + // CDR stream from a socket or file. + + /** + * Grow the internal buffer, reset @c rd_ptr to the first byte in + * the new buffer that is properly aligned, and set @c wr_ptr to @c + * rd_ptr @c + @c newsize + */ + int grow (size_t newsize); + + /** + * After reading and partially parsing the contents the user can + * detect a change in the byte order, this method will let him/her + * change it. + */ + void reset_byte_order (int byte_order); + + /// Re-initialize the CDR stream, copying the contents of the chain + /// of message_blocks starting from @a data. + void reset (const ACE_Message_Block *data, + int byte_order); + + /// Steal the contents from the current CDR. + ACE_Message_Block *steal_contents (void); + + /// Steal the contents of @a cdr and make a shallow copy into this + /// stream. + void steal_from (ACE_InputCDR &cdr); + + /// Exchange data blocks with the caller of this method. The read + /// and write pointers are also exchanged. + /** + * @note We now do only with the start_ message block. + */ + void exchange_data_blocks (ACE_InputCDR &cdr); + + /// Copy the data portion from the @a cdr to this cdr and return the + /// data content (ie. the ACE_Data_Block) from this CDR to the + /// caller. + /** + * @note The caller is responsible for managing the memory of the + * returned ACE_Data_Block. + */ + ACE_Data_Block* clone_from (ACE_InputCDR &cdr); + + /// Re-initialize the CDR stream, forgetting about the old contents + /// of the stream and allocating a new buffer (from the allocators). + void reset_contents (void); + + /// Returns the current position for the @c rd_ptr. + char* rd_ptr (void); + + /// Returns the current position for the @c wr_ptr. + char* wr_ptr (void); + + /// Return how many bytes are left in the stream. + size_t length (void) const; + + /** + * Utility function to allow the user more flexibility. + * Skips up to the nearest @a alignment-byte boundary. + * Argument MUST be a power of 2. + * + * @return 0 on success and -1 on failure. + */ + int align_read_ptr (size_t alignment); + + /// If @c true then this stream is writing in non-native byte order. + /// This is only meaningful if ACE_ENABLE_SWAP_ON_WRITE is defined. + bool do_byte_swap (void) const; + + /// If @c do_byte_swap() returns @c false, this returns + /// ACE_CDR_BYTE_ORDER else it returns !ACE_CDR_BYTE_ORDER. + int byte_order (void) const; + + /// Access the codeset translators. They can be nil! + ACE_Char_Codeset_Translator *char_translator (void) const; + ACE_WChar_Codeset_Translator *wchar_translator (void) const; + + /// Set the codeset translators. + void char_translator (ACE_Char_Codeset_Translator *); + void wchar_translator (ACE_WChar_Codeset_Translator *); + + /** + * Returns (in @a buf) the next position in the buffer aligned to + * @a size. It advances the Message_Block @c rd_ptr past the data + * (i.e., @c buf @c + @c size). Sets the good_bit to @c false and + * returns a -1 on failure. + */ + int adjust (size_t size, + char *&buf); + + /// As above, but now the size and alignment requirements may be + /// different. + int adjust (size_t size, + size_t align, + char *&buf); + + /// Set the underlying GIOP version.. + void set_version (ACE_CDR::Octet major, ACE_CDR::Octet minor); + + /// Set the underlying GIOP version.. + void get_version (ACE_CDR::Octet &major, ACE_CDR::Octet &minor); + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + /// Register and unregister our buffer size monitor. + void register_monitor (const char* id); + void unregister_monitor (void); +#endif /* ACE_HAS_MONITOR_POINTS==1 */ + +protected: + + /// The start of the chain of message blocks, even though in the + /// current version the chain always has length 1. + ACE_Message_Block start_; + + /// The CDR stream byte order does not match the one on the machine, + /// swapping is needed while reading. + bool do_byte_swap_; + + /// set to @c false when an error occurs. + bool good_bit_; + + /// The GIOP versions for this stream + ACE_CDR::Octet major_version_; + ACE_CDR::Octet minor_version_; + + /// If not nil, invoke for translation of character and string data. + ACE_Char_Codeset_Translator *char_translator_; + ACE_WChar_Codeset_Translator *wchar_translator_; + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + ACE::Monitor_Control::Size_Monitor *monitor_; +#endif /* ACE_HAS_MONITOR_POINTS==1 */ + +private: + + ACE_CDR::Boolean read_1 (ACE_CDR::Octet *x); + ACE_CDR::Boolean read_2 (ACE_CDR::UShort *x); + ACE_CDR::Boolean read_4 (ACE_CDR::ULong *x); + ACE_CDR::Boolean read_8 (ACE_CDR::ULongLong *x); + ACE_CDR::Boolean read_16 (ACE_CDR::LongDouble *x); + + // Several types can be read using the same routines, since TAO + // tries to use native types with known size for each CORBA type. + // We could use void* or char* to make the interface more + // consistent, but using native types let us exploit the strict + // alignment requirements of CDR streams and implement the + // operations using asignment. + + /** + * Read an array of @a length elements, each of @a size bytes and the + * start aligned at a multiple of . The elements are assumed + * to be packed with the right alignment restrictions. It is mostly + * designed for buffers of the basic types. + * + * This operation uses ; as explained above it is expected + * that using assignment is faster that for one element, + * but for several elements should be more efficient, it + * could be interesting to find the break even point and optimize + * for that case, but that would be too platform dependent. + */ + ACE_CDR::Boolean read_array (void* x, + size_t size, + size_t align, + ACE_CDR::ULong length); + + /** + * On those occasions when the native codeset for wchar is smaller than + * the size of a wchar_t, such as using UTF-16 with a 4-byte wchar_t, a + * special form of reading the array is needed. Actually, this should be + * a default translator. + */ + ACE_CDR::Boolean read_wchar_array_i (ACE_CDR::WChar * x, + ACE_CDR::ULong length); + + /// Move the rd_ptr ahead by @a offset bytes. + void rd_ptr (size_t offset); + + /// Points to the continuation field of the current message block. + char* end (void); +}; + +// **************************************************************** + +/** + * @class ACE_Char_Codeset_Translator + * + * @brief Codeset translation routines common to both Output and Input + * CDR streams. + * + * This class is a base class for defining codeset translation + * routines to handle the character set translations required by + * both CDR Input streams and CDR Output streams. + * + * Translators are reference counted. This allows for stateful as well + * as stateless translators. Stateless translators will be allocated + * once whereas CDR Streams own their own copy of a stateful translator. + */ +class ACE_Export ACE_Char_Codeset_Translator +{ +public: + virtual ~ACE_Char_Codeset_Translator (); + + /// Read a single character from the stream, converting from the + /// stream codeset to the native codeset + virtual ACE_CDR::Boolean read_char (ACE_InputCDR&, + ACE_CDR::Char&) = 0; + + /// Read a string from the stream, including the length, converting + /// the characters from the stream codeset to the native codeset + virtual ACE_CDR::Boolean read_string (ACE_InputCDR&, + ACE_CDR::Char *&) = 0; + + /// Read an array of characters from the stream, converting the + /// characters from the stream codeset to the native codeset. + virtual ACE_CDR::Boolean read_char_array (ACE_InputCDR&, + ACE_CDR::Char*, + ACE_CDR::ULong) = 0; + + /// Write a single character to the stream, converting from the + /// native codeset to the stream codeset + virtual ACE_CDR::Boolean write_char (ACE_OutputCDR&, + ACE_CDR::Char) = 0; + + /// Write a string to the stream, including the length, converting + /// from the native codeset to the stream codeset + virtual ACE_CDR::Boolean write_string (ACE_OutputCDR&, + ACE_CDR::ULong, + const ACE_CDR::Char*) = 0; + + /// Write an array of characters to the stream, converting from the + /// native codeset to the stream codeset + virtual ACE_CDR::Boolean write_char_array (ACE_OutputCDR&, + const ACE_CDR::Char*, + ACE_CDR::ULong) = 0; + + virtual ACE_CDR::ULong ncs () = 0; + virtual ACE_CDR::ULong tcs () = 0; +protected: + /// Children have access to low-level routines because they cannot + /// use read_char or something similar (it would recurse). + ACE_CDR::Boolean read_1 (ACE_InputCDR& input, + ACE_CDR::Octet *x); + ACE_CDR::Boolean write_1 (ACE_OutputCDR& output, + const ACE_CDR::Octet *x); + + /// Efficiently read @a length elements of size @a size each from + /// into ; the data must be aligned to . + ACE_CDR::Boolean read_array (ACE_InputCDR& input, + void* x, + size_t size, + size_t align, + ACE_CDR::ULong length); + + /** + * Efficiently write @a length elements of size @a size from into + * . Before inserting the elements enough padding is added + * to ensure that the elements will be aligned to in the + * stream. + */ + ACE_CDR::Boolean write_array (ACE_OutputCDR& output, + const void *x, + size_t size, + size_t align, + ACE_CDR::ULong length); + + /** + * Exposes the stream implementation of , this is useful in + * many cases to minimize memory allocations during marshaling. + * On success @a buf will contain a contiguous area in the CDR stream + * that can hold @a size bytes aligned to . + * Results + */ + int adjust (ACE_OutputCDR& out, + size_t size, + size_t align, + char *&buf); + + /// Used by derived classes to set errors in the CDR stream. + void good_bit (ACE_OutputCDR& out, bool bit); + + /// Obtain the CDR Stream's major & minor version values. + ACE_CDR::Octet major_version (ACE_InputCDR& input); + ACE_CDR::Octet minor_version (ACE_InputCDR& input); + ACE_CDR::Octet major_version (ACE_OutputCDR& output); + ACE_CDR::Octet minor_version (ACE_OutputCDR& output); +}; + +// **************************************************************** + +/** + * @class ACE_WChar_Codeset_Translator + * + * @brief Codeset translation routines common to both Output and Input + * CDR streams. + * + * This class is a base class for defining codeset translation + * routines to handle the character set translations required by + * both CDR Input streams and CDR Output streams. + */ +class ACE_Export ACE_WChar_Codeset_Translator +{ +public: + virtual ~ACE_WChar_Codeset_Translator (); + + virtual ACE_CDR::Boolean read_wchar (ACE_InputCDR&, + ACE_CDR::WChar&) = 0; + virtual ACE_CDR::Boolean read_wstring (ACE_InputCDR&, + ACE_CDR::WChar *&) = 0; + virtual ACE_CDR::Boolean read_wchar_array (ACE_InputCDR&, + ACE_CDR::WChar*, + ACE_CDR::ULong) = 0; + virtual ACE_CDR::Boolean write_wchar (ACE_OutputCDR&, + ACE_CDR::WChar) = 0; + virtual ACE_CDR::Boolean write_wstring (ACE_OutputCDR&, + ACE_CDR::ULong, + const ACE_CDR::WChar*) = 0; + virtual ACE_CDR::Boolean write_wchar_array (ACE_OutputCDR&, + const ACE_CDR::WChar*, + ACE_CDR::ULong) = 0; + + virtual ACE_CDR::ULong ncs () = 0; + virtual ACE_CDR::ULong tcs () = 0; +protected: + /// Children have access to low-level routines because they cannot + /// use read_char or something similar (it would recurse). + ACE_CDR::Boolean read_1 (ACE_InputCDR& input, + ACE_CDR::Octet *x); + ACE_CDR::Boolean read_2 (ACE_InputCDR& input, + ACE_CDR::UShort *x); + ACE_CDR::Boolean read_4 (ACE_InputCDR& input, + ACE_CDR::ULong *x); + ACE_CDR::Boolean write_1 (ACE_OutputCDR& output, + const ACE_CDR::Octet *x); + ACE_CDR::Boolean write_2 (ACE_OutputCDR& output, + const ACE_CDR::UShort *x); + ACE_CDR::Boolean write_4 (ACE_OutputCDR& output, + const ACE_CDR::ULong *x); + + /// Efficiently read @a length elements of size @a size each from + /// into ; the data must be aligned to . + ACE_CDR::Boolean read_array (ACE_InputCDR& input, + void* x, + size_t size, + size_t align, + ACE_CDR::ULong length); + + /** + * Efficiently write @a length elements of size @a size from into + * . Before inserting the elements enough padding is added + * to ensure that the elements will be aligned to in the + * stream. + */ + ACE_CDR::Boolean write_array (ACE_OutputCDR& output, + const void *x, + size_t size, + size_t align, + ACE_CDR::ULong length); + + /** + * Exposes the stream implementation of , this is useful in + * many cases to minimize memory allocations during marshaling. + * On success @a buf will contain a contiguous area in the CDR stream + * that can hold @a size bytes aligned to . + * Results + */ + int adjust (ACE_OutputCDR& out, + size_t size, + size_t align, + char *&buf); + + /// Used by derived classes to set errors in the CDR stream. + void good_bit (ACE_OutputCDR& out, bool bit); + + /// Obtain the CDR Stream's major & minor version values. + ACE_CDR::Octet major_version (ACE_InputCDR& input); + ACE_CDR::Octet minor_version (ACE_InputCDR& input); + ACE_CDR::Octet major_version (ACE_OutputCDR& output); + ACE_CDR::Octet minor_version (ACE_OutputCDR& output); + +}; + +// @@ These operators should not be inlined since they force SString.h +// to be included in this header. +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, + const ACE_CString &x); + +extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, + ACE_CString &x); + + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +# include "ace/CDR_Stream.inl" +#else /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Not used by CORBA or TAO +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, + ACE_CDR::Char x); +// CDR output operators for primitive types + +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, + ACE_CDR::Short x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, + ACE_CDR::UShort x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, + ACE_CDR::Long x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, + ACE_CDR::ULong x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, + ACE_CDR::LongLong x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, + ACE_CDR::ULongLong x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR& os, + ACE_CDR::LongDouble x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, + ACE_CDR::Float x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, + ACE_CDR::Double x); + +// CDR output operator from helper classes + +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, + ACE_OutputCDR::from_boolean x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, + ACE_OutputCDR::from_char x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, + ACE_OutputCDR::from_wchar x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, + ACE_OutputCDR::from_octet x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, + ACE_OutputCDR::from_string x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, + ACE_OutputCDR::from_wstring x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, + const ACE_CDR::Char* x); +extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, + const ACE_CDR::WChar* x); + +// Not used by CORBA or TAO +extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, + ACE_CDR::Char &x); +// CDR input operators for primitive types + +extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, + ACE_CDR::Short &x); +extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, + ACE_CDR::UShort &x); +extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, + ACE_CDR::Long &x); +extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, + ACE_CDR::ULong &x); +extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, + ACE_CDR::LongLong &x); +extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, + ACE_CDR::ULongLong &x); +extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, + ACE_CDR::LongDouble &x); +extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, + ACE_CDR::Float &x); +extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, + ACE_CDR::Double &x); + +// CDR input operator from helper classes + +extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, + ACE_InputCDR::to_boolean x); +extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, + ACE_InputCDR::to_char x); +extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, + ACE_InputCDR::to_wchar x); +extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, + ACE_InputCDR::to_octet x); +extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, + ACE_InputCDR::to_string x); +extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, + ACE_InputCDR::to_wstring x); +extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, + ACE_CDR::Char*& x); +extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, + ACE_CDR::WChar*& x); + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* __ACE_INLINE__ */ + +#if defined (GEN_OSTREAM_OPS) + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// ostream insertion operators for debugging code generated from IDL. All +// but these below are either in generated code itself or are unambiguous +// primitive types. + +ACE_Export std::ostream& operator<< (std::ostream &os, + ACE_OutputCDR::from_boolean x); + +ACE_Export std::ostream& operator<< (std::ostream &os, + ACE_OutputCDR::from_char x); + +ACE_Export std::ostream& operator<< (std::ostream &os, + ACE_OutputCDR::from_wchar x); + +ACE_Export std::ostream& operator<< (std::ostream &os, + ACE_OutputCDR::from_octet x); + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* GEN_OSTREAM_OPS */ + +#include /**/ "ace/post.h" + +#endif /* ACE_CDR_STREAM_H */ diff --git a/dep/acelite/ace/CDR_Stream.inl b/dep/acelite/ace/CDR_Stream.inl new file mode 100644 index 00000000000..2be60c154dd --- /dev/null +++ b/dep/acelite/ace/CDR_Stream.inl @@ -0,0 +1,1727 @@ +// -*- C++ -*- +// +// $Id: CDR_Stream.inl 84206 2009-01-21 02:49:26Z schmidt $ + +#include "ace/OS_NS_string.h" +#include "ace/OS_Memory.h" + +// **************************************************************** + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// implementing the special types +ACE_INLINE +ACE_OutputCDR::from_boolean::from_boolean (ACE_CDR::Boolean b) + : val_ (b) +{ +} + +ACE_INLINE +ACE_InputCDR::to_boolean::to_boolean (ACE_CDR::Boolean &b) + : ref_ (b) +{ +} + +ACE_INLINE +ACE_OutputCDR::from_octet::from_octet (ACE_CDR::Octet o) + : val_ (o) +{ +} + +ACE_INLINE +ACE_InputCDR::to_octet::to_octet (ACE_CDR::Octet &o) + : ref_ (o) +{ +} + +ACE_INLINE +ACE_OutputCDR::from_char::from_char (ACE_CDR::Char c) + : val_ (c) +{ +} + +ACE_INLINE +ACE_InputCDR::to_char::to_char (ACE_CDR::Char &c) + : ref_ (c) +{ +} + +ACE_INLINE +ACE_OutputCDR::from_wchar::from_wchar (ACE_CDR::WChar wc) + : val_ (wc) +{ +} + +ACE_INLINE +ACE_InputCDR::to_wchar::to_wchar (ACE_CDR::WChar &wc) + : ref_ (wc) +{ +} + +ACE_INLINE +ACE_OutputCDR::from_string::from_string (ACE_CDR::Char *s, + ACE_CDR::ULong b, + ACE_CDR::Boolean nocopy) + : val_ (s), + bound_ (b), + nocopy_ (nocopy) +{ +} + +ACE_INLINE +ACE_OutputCDR::from_string::from_string (const ACE_CDR::Char *s, + ACE_CDR::ULong b, + ACE_CDR::Boolean nocopy) + : val_ (const_cast (s)), + bound_ (b), + nocopy_ (nocopy) +{ +} + +ACE_INLINE +ACE_InputCDR::to_string::to_string (ACE_CDR::Char *&s, + ACE_CDR::ULong b) + : val_ (const_cast (s)), + bound_ (b) +{ +} + +ACE_INLINE +ACE_InputCDR::to_string::to_string (const ACE_CDR::Char *&s, + ACE_CDR::ULong b) + : val_ (s), + bound_ (b) +{ +} + +ACE_INLINE +ACE_OutputCDR::from_wstring::from_wstring (ACE_CDR::WChar *ws, + ACE_CDR::ULong b, + ACE_CDR::Boolean nocopy) + : val_ (ws), + bound_ (b), + nocopy_ (nocopy) +{ +} + +ACE_INLINE +ACE_OutputCDR::from_wstring::from_wstring (const ACE_CDR::WChar *ws, + ACE_CDR::ULong b, + ACE_CDR::Boolean nocopy) + : val_ (const_cast (ws)), + bound_ (b), + nocopy_ (nocopy) +{ +} + +ACE_INLINE +ACE_InputCDR::to_wstring::to_wstring (ACE_CDR::WChar *&ws, + ACE_CDR::ULong b) + : val_ (const_cast (ws)), + bound_ (b) +{ +} + +ACE_INLINE +ACE_InputCDR::to_wstring::to_wstring (const ACE_CDR::WChar *&ws, + ACE_CDR::ULong b) + : val_ (ws), + bound_ (b) +{ +} + +ACE_INLINE +ACE_InputCDR::Transfer_Contents::Transfer_Contents (ACE_InputCDR &rhs) + : rhs_ (rhs) +{ +} + +// **************************************************************** + +ACE_INLINE +ACE_OutputCDR::~ACE_OutputCDR (void) +{ + if (this->start_.cont () != 0) + { + ACE_Message_Block::release (this->start_.cont ()); + this->start_.cont (0); + } + + this->current_ = 0; + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + this->monitor_->remove_ref (); +#endif /* ACE_HAS_MONITOR_POINTS==1 */ +} + +ACE_INLINE void +ACE_OutputCDR::reset (void) +{ + this->current_ = &this->start_; + this->current_is_writable_ = true; + ACE_CDR::mb_align (&this->start_); + +#if !defined (ACE_LACKS_CDR_ALIGNMENT) + this->current_alignment_ = 0; +#endif /* ACE_LACKS_CDR_ALIGNMENT */ + + // It is tempting not to remove the memory, but we need to do so to + // release any potential user buffers chained in the continuation + // field. + + ACE_Message_Block * const cont = this->start_.cont (); + if (cont) + { + ACE_Message_Block::release (cont); + this->start_.cont (0); + } + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + this->monitor_->receive (this->start_.total_size ()); +#endif /* ACE_HAS_MONITOR_POINTS==1 */ +} + +// Encode the CDR stream. + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::write_octet (ACE_CDR::Octet x) +{ + return this->write_1 (&x); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::write_boolean (ACE_CDR::Boolean x) +{ + return + static_cast ( + this->write_octet ( + x + ? static_cast (1) + : static_cast (0))); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::write_char (ACE_CDR::Char x) +{ + if (this->char_translator_ == 0) + { + ACE_CDR::Octet temp = static_cast (x); + return this->write_1 (&temp); + } + return this->char_translator_->write_char (*this, x); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::write_short (ACE_CDR::Short x) +{ + ACE_CDR::UShort temp = static_cast (x); + return this->write_2 (&temp); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::write_ushort (ACE_CDR::UShort x) +{ + return this->write_2 (&x); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::write_long (ACE_CDR::Long x) +{ + ACE_CDR::ULong temp = static_cast (x); + return this->write_4 (&temp); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::write_ulong (ACE_CDR::ULong x) +{ + return this->write_4 (&x); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::write_longlong (const ACE_CDR::LongLong &x) +{ + void const * const temp = &x; + return this->write_8 (reinterpret_cast (temp)); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::write_ulonglong (const ACE_CDR::ULongLong &x) +{ + return this->write_8 (&x); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::write_float (ACE_CDR::Float x) +{ + void const * const temp = &x; + return this->write_4 (reinterpret_cast (temp)); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::write_double (const ACE_CDR::Double &x) +{ + void const * const temp = &x; + return this->write_8 (reinterpret_cast (temp)); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::write_longdouble (const ACE_CDR::LongDouble &x) +{ + return this->write_16 (&x); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::write_string (const ACE_CDR::Char *x) +{ + if (x) + { + ACE_CDR::ULong const len = + static_cast (ACE_OS::strlen (x)); + return this->write_string (len, x); + } + + return this->write_string (0, 0); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::write_wstring (const ACE_CDR::WChar *x) +{ + if (x) + { + ACE_CDR::ULong const len = + static_cast (ACE_OS::strlen (x)); + return this->write_wstring (len, x); + } + + return this->write_wstring (0, 0); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::write_char_array (const ACE_CDR::Char *x, + ACE_CDR::ULong length) +{ + if (this->char_translator_ == 0) + return this->write_array (x, + ACE_CDR::OCTET_SIZE, + ACE_CDR::OCTET_ALIGN, + length); + return this->char_translator_->write_char_array (*this, x, length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::write_wchar_array (const ACE_CDR::WChar* x, + ACE_CDR::ULong length) +{ + if (this->wchar_translator_) + return this->wchar_translator_->write_wchar_array (*this, x, length); + + if (ACE_OutputCDR::wchar_maxbytes_ == 0) + { + errno = EACCES; + return (ACE_CDR::Boolean) (this->good_bit_ = false); + } + + if (ACE_OutputCDR::wchar_maxbytes_ == sizeof (ACE_CDR::WChar)) + return this->write_array (x, + sizeof (ACE_CDR::WChar), + sizeof (ACE_CDR::WChar) == 2 + ? ACE_CDR::SHORT_ALIGN + : ACE_CDR::LONG_ALIGN, + length); + return this->write_wchar_array_i (x,length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::write_octet_array (const ACE_CDR::Octet* x, + ACE_CDR::ULong length) +{ + return this->write_array (x, + ACE_CDR::OCTET_SIZE, + ACE_CDR::OCTET_ALIGN, + length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::write_short_array (const ACE_CDR::Short *x, + ACE_CDR::ULong length) +{ + return this->write_array (x, + ACE_CDR::SHORT_SIZE, + ACE_CDR::SHORT_ALIGN, + length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::write_ushort_array (const ACE_CDR::UShort *x, + ACE_CDR::ULong length) +{ + return this->write_array (x, + ACE_CDR::SHORT_SIZE, + ACE_CDR::SHORT_ALIGN, + length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::write_long_array (const ACE_CDR::Long *x, + ACE_CDR::ULong length) +{ + return this->write_array (x, + ACE_CDR::LONG_SIZE, + ACE_CDR::LONG_ALIGN, + length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::write_ulong_array (const ACE_CDR::ULong *x, + ACE_CDR::ULong length) +{ + return this->write_array (x, + ACE_CDR::LONG_SIZE, + ACE_CDR::LONG_ALIGN, + length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::write_longlong_array (const ACE_CDR::LongLong *x, + ACE_CDR::ULong length) +{ + return this->write_array (x, + ACE_CDR::LONGLONG_SIZE, + ACE_CDR::LONGLONG_ALIGN, + length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::write_ulonglong_array (const ACE_CDR::ULongLong *x, + ACE_CDR::ULong length) +{ + return this->write_array (x, + ACE_CDR::LONGLONG_SIZE, + ACE_CDR::LONGLONG_ALIGN, + length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::write_float_array (const ACE_CDR::Float *x, + ACE_CDR::ULong length) +{ + return this->write_array (x, + ACE_CDR::LONG_SIZE, + ACE_CDR::LONG_ALIGN, + length); +} + + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::write_double_array (const ACE_CDR::Double *x, + ACE_CDR::ULong length) +{ + return this->write_array (x, + ACE_CDR::LONGLONG_SIZE, + ACE_CDR::LONGLONG_ALIGN, + length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::write_longdouble_array (const ACE_CDR::LongDouble* x, + ACE_CDR::ULong length) +{ + return this->write_array (x, + ACE_CDR::LONGDOUBLE_SIZE, + ACE_CDR::LONGDOUBLE_ALIGN, + length); +} + +ACE_INLINE bool +ACE_OutputCDR::good_bit (void) const +{ + return this->good_bit_; +} + +ACE_INLINE int +ACE_OutputCDR::adjust (size_t size, + size_t align, + char*& buf) +{ + if (!this->current_is_writable_) + return this->grow_and_adjust (size, align, buf); + +#if !defined (ACE_LACKS_CDR_ALIGNMENT) + size_t const offset = + ACE_align_binary (this->current_alignment_, align) + - this->current_alignment_; + + buf = this->current_->wr_ptr () + offset; +#else + buf = this->current_->wr_ptr (); +#endif /* ACE_LACKS_CDR_ALIGNMENT */ + + char * const end = buf + size; + + if (end <= this->current_->end () && + end >= buf) + { +#if !defined (ACE_LACKS_CDR_ALIGNMENT) + this->current_alignment_ += offset + size; +#endif /* ACE_LACKS_CDR_ALIGNMENT */ + this->current_->wr_ptr (end); + +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + this->monitor_->receive (this->total_length ()); +#endif /* ACE_HAS_MONITOR_POINTS==1 */ + + return 0; + } + + return this->grow_and_adjust (size, align, buf); +} + +ACE_INLINE int +ACE_OutputCDR::adjust (size_t size, char*& buf) +{ + return this->adjust (size, size, buf); +} + +ACE_INLINE void +ACE_OutputCDR::set_version (ACE_CDR::Octet major, ACE_CDR::Octet minor) +{ + this->major_version_ = major; + this->minor_version_ = minor; +} + +ACE_INLINE void +ACE_OutputCDR::get_version (ACE_CDR::Octet &major, ACE_CDR::Octet &minor) +{ + major = this->major_version_; + minor = this->minor_version_; +} + + +ACE_INLINE const ACE_Message_Block* +ACE_OutputCDR::begin (void) const +{ + return &this->start_; +} + +ACE_INLINE const ACE_Message_Block* +ACE_OutputCDR::end (void) const +{ + return this->current_->cont (); +} + +ACE_INLINE const ACE_Message_Block* +ACE_OutputCDR::current (void) const +{ + return this->current_; +} + +ACE_INLINE size_t +ACE_OutputCDR::total_length (void) const +{ + return ACE_CDR::total_length (this->begin (), this->end ()); +} + +ACE_INLINE const char* +ACE_OutputCDR::buffer (void) const +{ + return this->start_.rd_ptr (); +} + +ACE_INLINE size_t +ACE_OutputCDR::length (void) const +{ + return this->start_.length (); +} + +ACE_INLINE bool +ACE_OutputCDR::do_byte_swap (void) const +{ + return this->do_byte_swap_; +} + +ACE_INLINE int +ACE_OutputCDR::byte_order (void) const +{ + if (this->do_byte_swap ()) + return !ACE_CDR_BYTE_ORDER; + else + return ACE_CDR_BYTE_ORDER; +} + +ACE_INLINE void +ACE_OutputCDR::reset_byte_order (int byte_order) +{ + this->do_byte_swap_ = (byte_order != ACE_CDR_BYTE_ORDER); +} + +ACE_INLINE size_t +ACE_OutputCDR::current_alignment (void) const +{ +#if !defined (ACE_LACKS_CDR_ALIGNMENT) + return this->current_alignment_; +#else + // Default value set to 0 + return 0; +#endif /* ACE_LACKS_CDR_ALIGNMENT */ +} + +ACE_INLINE void +ACE_OutputCDR::current_alignment (size_t current_alignment) +{ +#if !defined (ACE_LACKS_CDR_ALIGNMENT) + this->current_alignment_ = current_alignment; +#else + ACE_UNUSED_ARG (current_alignment); +#endif /* ACE_LACKS_CDR_ALIGNMENT */ +} + +ACE_INLINE int +ACE_OutputCDR::align_write_ptr (size_t alignment) +{ +#if !defined (ACE_LACKS_CDR_ALIGNMENT) + char *dummy; + return this->adjust (0, alignment, dummy); +#else + ACE_UNUSED_ARG (alignment); + // A return value of -1 from this function is used + // to indicate failure, returning 0 + return 0; +#endif /* ACE_LACKS_CDR_ALIGNMENT */ +} + +ACE_INLINE ACE_Char_Codeset_Translator * +ACE_OutputCDR::char_translator (void) const +{ + return this->char_translator_; +} + +ACE_INLINE ACE_WChar_Codeset_Translator * +ACE_OutputCDR::wchar_translator (void) const +{ + return this->wchar_translator_; +} + +ACE_INLINE void +ACE_OutputCDR::char_translator (ACE_Char_Codeset_Translator * ctran) +{ + this->char_translator_ = ctran; +} + +ACE_INLINE void +ACE_OutputCDR::wchar_translator (ACE_WChar_Codeset_Translator * wctran) +{ + this->wchar_translator_ = wctran; +} + +// **************************************************************** + +ACE_INLINE +ACE_InputCDR::~ACE_InputCDR (void) +{ +#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) + this->monitor_->remove_ref (); +#endif /* ACE_HAS_MONITOR_POINTS==1 */ +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::read_octet (ACE_CDR::Octet& x) +{ + return this->read_1 (&x); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::read_boolean (ACE_CDR::Boolean& x) +{ + ACE_CDR::Octet tmp = 0; + (void) this->read_octet (tmp); + x = tmp ? true : false; + return (ACE_CDR::Boolean) this->good_bit_; +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::read_char (ACE_CDR::Char &x) +{ + if (this->char_translator_ == 0) + { + void *temp = &x; + return this->read_1 (reinterpret_cast (temp)); + } + return this->char_translator_->read_char (*this, x); +} + + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::read_short (ACE_CDR::Short &x) +{ + void *temp = &x; + return this->read_2 (reinterpret_cast (temp)); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::read_ushort (ACE_CDR::UShort &x) +{ + return this->read_2 (&x); +} + + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::read_long (ACE_CDR::Long &x) +{ + void *temp = &x; + return this->read_4 (reinterpret_cast (temp)); +} + + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::read_ulong (ACE_CDR::ULong &x) +{ + return this->read_4 (&x); +} + + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::read_longlong (ACE_CDR::LongLong &x) +{ + void *temp = &x; + return this->read_8 (reinterpret_cast (temp)); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::read_ulonglong (ACE_CDR::ULongLong &x) +{ + return this->read_8 (&x); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::read_float (ACE_CDR::Float &x) +{ + void *temp = &x; + return this->read_4 (reinterpret_cast (temp)); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::read_double (ACE_CDR::Double &x) +{ + void *temp = &x; + return this->read_8 (reinterpret_cast (temp)); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::read_longdouble (ACE_CDR::LongDouble &x) +{ + return this->read_16 (&x); +} + +ACE_INLINE size_t +ACE_InputCDR::length (void) const +{ + return this->start_.length (); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::read_char_array (ACE_CDR::Char* x, + ACE_CDR::ULong length) +{ + // Make sure the length of the array isn't greater than the length of + // the stream. + if (length > this->length ()) + { + this->good_bit_ = false; + return false; + } + + if (this->char_translator_ == 0) + return this->read_array (x, + ACE_CDR::OCTET_SIZE, + ACE_CDR::OCTET_ALIGN, + length); + return this->char_translator_->read_char_array (*this, x, length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::read_wchar_array (ACE_CDR::WChar* x, + ACE_CDR::ULong length) +{ + // Make sure the length of the array isn't greater than the length of + // the stream. + if (length * ACE_OutputCDR::wchar_maxbytes_ > this->length ()) + { + this->good_bit_ = false; + return false; + } + + if (this->wchar_translator_ != 0) + return this->wchar_translator_->read_wchar_array (*this, x, length); + if (ACE_OutputCDR::wchar_maxbytes_ != sizeof (ACE_CDR::WChar)) + return this->read_wchar_array_i (x, length); + return this->read_array (x, + sizeof (ACE_CDR::WChar), + sizeof (ACE_CDR::WChar) == 2 + ? ACE_CDR::SHORT_ALIGN + : ACE_CDR::LONG_ALIGN, + length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::read_octet_array (ACE_CDR::Octet* x, + ACE_CDR::ULong length) +{ + // Make sure the length of the array isn't greater than the length of + // the stream. + if (length * ACE_CDR::OCTET_SIZE > this->length ()) + { + this->good_bit_ = false; + return false; + } + + return this->read_array (x, + ACE_CDR::OCTET_SIZE, + ACE_CDR::OCTET_ALIGN, + length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::read_short_array (ACE_CDR::Short *x, + ACE_CDR::ULong length) +{ + // Make sure the length of the array isn't greater than the length of + // the stream. + if (length * ACE_CDR::SHORT_SIZE > this->length ()) + { + this->good_bit_ = false; + return false; + } + + return this->read_array (x, + ACE_CDR::SHORT_SIZE, + ACE_CDR::SHORT_ALIGN, + length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::read_ushort_array (ACE_CDR::UShort *x, + ACE_CDR::ULong length) +{ + // Make sure the length of the array isn't greater than the length of + // the stream. + if (length * ACE_CDR::SHORT_SIZE > this->length ()) + { + this->good_bit_ = false; + return false; + } + + return this->read_array (x, + ACE_CDR::SHORT_SIZE, + ACE_CDR::SHORT_ALIGN, + length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::read_long_array (ACE_CDR::Long *x, + ACE_CDR::ULong length) +{ + // Make sure the length of the array isn't greater than the length of + // the stream. + if (length * ACE_CDR::LONG_SIZE > this->length ()) + { + this->good_bit_ = false; + return false; + } + + return this->read_array (x, + ACE_CDR::LONG_SIZE, + ACE_CDR::LONG_ALIGN, + length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::read_ulong_array (ACE_CDR::ULong *x, + ACE_CDR::ULong length) +{ + // Make sure the length of the array isn't greater than the length of + // the stream. + if (length * ACE_CDR::LONG_SIZE > this->length ()) + { + this->good_bit_ = false; + return false; + } + + return this->read_array (x, + ACE_CDR::LONG_SIZE, + ACE_CDR::LONG_ALIGN, + length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::read_longlong_array (ACE_CDR::LongLong *x, + ACE_CDR::ULong length) +{ + // Make sure the length of the array isn't greater than the length of + // the stream. + if (length * ACE_CDR::LONGLONG_SIZE > this->length ()) + { + this->good_bit_ = false; + return false; + } + + return this->read_array (x, + ACE_CDR::LONGLONG_SIZE, + ACE_CDR::LONGLONG_ALIGN, + length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::read_ulonglong_array (ACE_CDR::ULongLong *x, + ACE_CDR::ULong length) +{ + // Make sure the length of the array isn't greater than the length of + // the stream. + if (length * ACE_CDR::LONGLONG_SIZE > this->length ()) + { + this->good_bit_ = false; + return false; + } + + return this->read_array (x, + ACE_CDR::LONGLONG_SIZE, + ACE_CDR::LONGLONG_ALIGN, + length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::read_float_array (ACE_CDR::Float *x, + ACE_CDR::ULong length) +{ + // Make sure the length of the array isn't greater than the length of + // the stream. + if (length * ACE_CDR::LONG_SIZE > this->length ()) + { + this->good_bit_ = false; + return false; + } + + return this->read_array (x, + ACE_CDR::LONG_SIZE, + ACE_CDR::LONG_ALIGN, + length); +} + + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::read_double_array (ACE_CDR::Double *x, + ACE_CDR::ULong length) +{ + // Make sure the length of the array isn't greater than the length of + // the stream. + if (length * ACE_CDR::LONGLONG_SIZE > this->length ()) + { + this->good_bit_ = false; + return false; + } + + return this->read_array (x, + ACE_CDR::LONGLONG_SIZE, + ACE_CDR::LONGLONG_ALIGN, + length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::read_longdouble_array (ACE_CDR::LongDouble* x, + ACE_CDR::ULong length) +{ + // Make sure the length of the array isn't greater than the length of + // the stream. + if (length * ACE_CDR::LONGDOUBLE_SIZE > this->length ()) + { + this->good_bit_ = false; + return false; + } + return this->read_array (x, + ACE_CDR::LONGDOUBLE_SIZE, + ACE_CDR::LONGDOUBLE_ALIGN, + length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::skip_octet (void) +{ + ACE_CDR::Octet x; + return this->read_1 (&x); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::skip_char (void) +{ + return this->skip_octet (); // sizeof (Char) == sizeof (Octet) +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::skip_boolean (void) +{ + return this->skip_octet () && this->good_bit_; +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::skip_ushort (void) +{ + ACE_CDR::UShort x; + return this->read_2 (&x); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::skip_short (void) +{ + return this->skip_ushort (); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::skip_ulong (void) +{ + ACE_CDR::ULong x; + return this->read_4 (&x); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::skip_long (void) +{ + return this->skip_ulong (); // sizeof (Long) == sizeof (ULong) +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::skip_ulonglong (void) +{ + ACE_CDR::ULongLong x; + return this->read_8 (&x); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::skip_longlong (void) +{ + return this->skip_ulonglong (); // sizeof (LongLong) == sizeof (ULongLong) +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::skip_float (void) +{ + return this->skip_ulong (); // sizeof(Float) == sizeof (ULong) +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::skip_double (void) +{ + return this->skip_ulonglong (); // sizeof(Double) == sizeof (ULongLong) +} + +ACE_INLINE ACE_CDR::Boolean +ACE_InputCDR::skip_longdouble (void) +{ + ACE_CDR::LongDouble x; + return this->read_16 (&x); +} + +ACE_INLINE char* +ACE_InputCDR::end (void) +{ + return this->start_.end (); +} + +ACE_INLINE void +ACE_InputCDR::rd_ptr (size_t offset) +{ + this->start_.rd_ptr (offset); +} + +ACE_INLINE char* +ACE_InputCDR::rd_ptr (void) +{ + return this->start_.rd_ptr (); +} + +ACE_INLINE char* +ACE_InputCDR::wr_ptr (void) +{ + return this->start_.wr_ptr (); +} + +ACE_INLINE int +ACE_InputCDR::adjust (size_t size, + size_t align, + char*& buf) +{ +#if !defined (ACE_LACKS_CDR_ALIGNMENT) + buf = ACE_ptr_align_binary (this->rd_ptr (), align); +#else + buf = this->rd_ptr (); +#endif /* ACE_LACKS_CDR_ALIGNMENT */ + + char * const end = buf + size; + if (end <= this->wr_ptr ()) + { + this->start_.rd_ptr (end); + return 0; + } + + this->good_bit_ = false; + return -1; +#if defined (ACE_LACKS_CDR_ALIGNMENT) + ACE_UNUSED_ARG (align); +#endif /* ACE_LACKS_CDR_ALIGNMENT */ +} + +ACE_INLINE int +ACE_InputCDR::adjust (size_t size, + char*& buf) +{ + return this->adjust (size, size, buf); +} + +ACE_INLINE const ACE_Message_Block* +ACE_InputCDR::start (void) const +{ + return &this->start_; +} + +ACE_INLINE bool +ACE_InputCDR::good_bit (void) const +{ + return this->good_bit_; +} + +// **************************************************************** + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_OutputCDR &os, ACE_CDR::Char x) +{ + os.write_char (x); + return (ACE_CDR::Boolean) os.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_OutputCDR &os, ACE_CDR::Short x) +{ + os.write_short (x); + return (ACE_CDR::Boolean) os.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_OutputCDR &os, ACE_CDR::UShort x) +{ + os.write_ushort (x); + return (ACE_CDR::Boolean) os.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_OutputCDR &os, ACE_CDR::Long x) +{ + os.write_long (x); + return (ACE_CDR::Boolean) os.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_OutputCDR &os, ACE_CDR::ULong x) +{ + os.write_ulong (x); + return (ACE_CDR::Boolean) os.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_OutputCDR &os, ACE_CDR::LongLong x) +{ + os.write_longlong (x); + return (ACE_CDR::Boolean) os.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_OutputCDR &os, ACE_CDR::ULongLong x) +{ + os.write_ulonglong (x); + return (ACE_CDR::Boolean) os.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_OutputCDR &os, ACE_CDR::LongDouble x) +{ + os.write_longdouble (x); + return (ACE_CDR::Boolean) os.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_OutputCDR &os, ACE_CDR::Float x) +{ + os.write_float (x); + return (ACE_CDR::Boolean) os.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_OutputCDR &os, ACE_CDR::Double x) +{ + os.write_double (x); + return (ACE_CDR::Boolean) os.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_OutputCDR &os, const ACE_CDR::Char *x) +{ + os.write_string (x); + return (ACE_CDR::Boolean) os.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_OutputCDR &os, const ACE_CDR::WChar *x) +{ + os.write_wstring (x); + return (ACE_CDR::Boolean) os.good_bit (); +} + +// The following use the helper classes +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_OutputCDR &os, ACE_OutputCDR::from_boolean x) +{ + (void) os.write_boolean (x.val_); + return (ACE_CDR::Boolean) os.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_OutputCDR &os, ACE_OutputCDR::from_char x) +{ + os.write_char (x.val_); + return (ACE_CDR::Boolean) os.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_OutputCDR &os, ACE_OutputCDR::from_wchar x) +{ + os.write_wchar (x.val_); + return (ACE_CDR::Boolean) os.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_OutputCDR &os, ACE_OutputCDR::from_octet x) +{ + os.write_octet (x.val_); + return (ACE_CDR::Boolean) os.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_OutputCDR &os, ACE_OutputCDR::from_string x) +{ + ACE_CDR::ULong len = 0; + + if (x.val_ != 0) + { + len = static_cast (ACE_OS::strlen (x.val_)); + } + + os.write_string (len, x.val_); + return + (ACE_CDR::Boolean) (os.good_bit () && (!x.bound_ || len <= x.bound_)); +} + +ACE_INLINE ACE_CDR::Boolean +operator<< (ACE_OutputCDR &os, ACE_OutputCDR::from_wstring x) +{ + ACE_CDR::ULong len = 0; + + if (x.val_ != 0) + { + len = static_cast (ACE_OS::strlen (x.val_)); + } + + os.write_wstring (len, x.val_); + return + (ACE_CDR::Boolean) (os.good_bit () && (!x.bound_ || len <= x.bound_)); +} + +// **************************************************************** + +ACE_INLINE ACE_CDR::Boolean +operator>> (ACE_InputCDR &is, ACE_CDR::Char &x) +{ + return is.read_char (x) && is.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator>> (ACE_InputCDR &is, ACE_CDR::Short &x) +{ + return is.read_short (x) && is.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator>> (ACE_InputCDR &is, ACE_CDR::UShort &x) +{ + return is.read_ushort (x) && is.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator>>(ACE_InputCDR &is, ACE_CDR::Long &x) +{ + return is.read_long (x) && is.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator>> (ACE_InputCDR &is, ACE_CDR::ULong &x) +{ + return is.read_ulong (x) && is.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator>> (ACE_InputCDR& is, ACE_CDR::LongLong &x) +{ + return is.read_longlong (x) && is.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator>> (ACE_InputCDR& is, ACE_CDR::ULongLong &x) +{ + return is.read_ulonglong (x) && is.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator>> (ACE_InputCDR& is, ACE_CDR::LongDouble &x) +{ + return is.read_longdouble (x) && is.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator>> (ACE_InputCDR &is, ACE_CDR::Float &x) +{ + return is.read_float (x) && is.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator>> (ACE_InputCDR &is, ACE_CDR::Double &x) +{ + return is.read_double (x) && is.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator>> (ACE_InputCDR &is, ACE_CDR::Char *&x) +{ + return is.read_string (x) && is.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator>> (ACE_InputCDR &is, ACE_CDR::WChar *&x) +{ + return is.read_wstring (x) && is.good_bit (); +} + +// The following use the helper classes +ACE_INLINE ACE_CDR::Boolean +operator>> (ACE_InputCDR &is, ACE_InputCDR::to_boolean x) +{ + return is.read_boolean (x.ref_); +} + +ACE_INLINE ACE_CDR::Boolean +operator>> (ACE_InputCDR &is, ACE_InputCDR::to_char x) +{ + return is.read_char (x.ref_) && is.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator>> (ACE_InputCDR &is, ACE_InputCDR::to_wchar x) +{ + return is.read_wchar (x.ref_) && is.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator>> (ACE_InputCDR &is, ACE_InputCDR::to_octet x) +{ + return is.read_octet (x.ref_) && is.good_bit (); +} + +ACE_INLINE ACE_CDR::Boolean +operator>> (ACE_InputCDR &is, ACE_InputCDR::to_string x) +{ + // check if the bounds are satisfied + return + (is.read_string (const_cast (x.val_)) + && is.good_bit () + && (!x.bound_ + || ACE_OS::strlen (x.val_) <= x.bound_)); +} + +ACE_INLINE ACE_CDR::Boolean +operator>> (ACE_InputCDR &is, ACE_InputCDR::to_wstring x) +{ + // check if the bounds are satisfied + return + (is.read_wstring (const_cast (x.val_)) + && is.good_bit () + && (!x.bound_ + || ACE_OS::strlen (x.val_) <= x.bound_)); +} + +// *************************************************************************** +// We must define these methods here because they use the "read_*" inlined +// methods of the ACE_InputCDR class +// *************************************************************************** + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::append_boolean (ACE_InputCDR &stream) +{ + ACE_CDR::Boolean x; + return stream.read_boolean (x) ? this->write_boolean (x) : false; +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::append_char (ACE_InputCDR &stream) +{ + ACE_CDR::Char x; + return stream.read_char (x) ? this->write_char (x) : false; +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::append_wchar (ACE_InputCDR &stream) +{ + ACE_CDR::WChar x; + return stream.read_wchar (x) ? this->write_wchar (x) : false; +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::append_octet (ACE_InputCDR &stream) +{ + ACE_CDR::Octet x; + return stream.read_octet (x) ? this->write_octet (x) : false; +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::append_short (ACE_InputCDR &stream) +{ + ACE_CDR::Short x; + return stream.read_short (x) ? this->write_short (x) : false; +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::append_ushort (ACE_InputCDR &stream) +{ + ACE_CDR::UShort x; + return stream.read_ushort (x) ? this->write_ushort (x) : false; +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::append_long (ACE_InputCDR &stream) +{ + ACE_CDR::Long x; + return stream.read_long (x) ? this->write_long (x) : false; +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::append_ulong (ACE_InputCDR &stream) +{ + ACE_CDR::ULong x; + return stream.read_ulong (x) ? this->write_ulong (x) : false; +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::append_longlong (ACE_InputCDR &stream) +{ + ACE_CDR::LongLong x; + return stream.read_longlong (x) ? this->write_longlong (x) : false; +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::append_ulonglong (ACE_InputCDR &stream) +{ + ACE_CDR::ULongLong x; + return stream.read_ulonglong (x) ? this->write_ulonglong (x) : false; +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::append_float (ACE_InputCDR &stream) +{ + ACE_CDR::Float x; + return stream.read_float (x) ? this->write_float (x) : false; +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::append_double (ACE_InputCDR &stream) +{ + ACE_CDR::Double x; + return stream.read_double (x) ? this->write_double (x) : false; +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::append_longdouble (ACE_InputCDR &stream) +{ + ACE_CDR::LongDouble x; + return stream.read_longdouble (x) ? this->write_longdouble (x) : false; +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::append_string (ACE_InputCDR &stream) +{ + ACE_CDR::Char *x = 0; + ACE_CDR::Boolean const flag = + (stream.read_string (x) ? this->write_string (x) : false); + delete [] x; + return flag; +} + +ACE_INLINE ACE_CDR::Boolean +ACE_OutputCDR::append_wstring (ACE_InputCDR &stream) +{ + ACE_CDR::WChar *x = 0; + ACE_CDR::Boolean const flag = + (stream.read_wstring (x) ? this->write_wstring (x) : false); + delete [] x; + return flag; +} + +ACE_INLINE void +ACE_InputCDR::reset_byte_order (int byte_order) +{ + this->do_byte_swap_ = (byte_order != ACE_CDR_BYTE_ORDER); +} + +ACE_INLINE bool +ACE_InputCDR::do_byte_swap (void) const +{ + return this->do_byte_swap_; +} + +ACE_INLINE int +ACE_InputCDR::byte_order (void) const +{ + return this->do_byte_swap () ? !ACE_CDR_BYTE_ORDER : ACE_CDR_BYTE_ORDER; +} + +ACE_INLINE int +ACE_InputCDR::align_read_ptr (size_t alignment) +{ +#if !defined (ACE_LACKS_CDR_ALIGNMENT) + char *buf = ACE_ptr_align_binary (this->rd_ptr (), + alignment); +#else + char *buf = this->rd_ptr (); +#endif /* ACE_LACKS_CDR_ALIGNMENT */ + + if (buf <= this->wr_ptr ()) + { + this->start_.rd_ptr (buf); + return 0; + } + + this->good_bit_ = false; + return -1; +} + +ACE_INLINE void +ACE_InputCDR::set_version (ACE_CDR::Octet major, ACE_CDR::Octet minor) +{ + this->major_version_ = major; + this->minor_version_ = minor; +} + +ACE_INLINE void +ACE_InputCDR::get_version (ACE_CDR::Octet &major, ACE_CDR::Octet &minor) +{ + major = this->major_version_; + minor = this->minor_version_; +} + +ACE_INLINE ACE_Char_Codeset_Translator * +ACE_InputCDR::char_translator (void) const +{ + return this->char_translator_; +} + +ACE_INLINE ACE_WChar_Codeset_Translator * +ACE_InputCDR::wchar_translator (void) const +{ + return this->wchar_translator_; +} + + +ACE_INLINE void +ACE_InputCDR::char_translator (ACE_Char_Codeset_Translator * ctran) +{ + this->char_translator_ = ctran; +} + +ACE_INLINE void +ACE_InputCDR::wchar_translator (ACE_WChar_Codeset_Translator * wctran) +{ + this->wchar_translator_ = wctran; +} + +// **************************************************************** + +ACE_INLINE ACE_CDR::Boolean +ACE_Char_Codeset_Translator::read_1 (ACE_InputCDR& input, + ACE_CDR::Octet *x) +{ + return input.read_1 (x); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_Char_Codeset_Translator::write_1 (ACE_OutputCDR& output, + const ACE_CDR::Octet *x) +{ + return output.write_1 (x); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_Char_Codeset_Translator::read_array (ACE_InputCDR& in, + void* x, + size_t size, + size_t align, + ACE_CDR::ULong length) +{ + return in.read_array (x, size, align, length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_Char_Codeset_Translator::write_array (ACE_OutputCDR& out, + const void *x, + size_t size, + size_t align, + ACE_CDR::ULong length) +{ + return out.write_array(x, size, align, length); +} + +ACE_INLINE int +ACE_Char_Codeset_Translator::adjust (ACE_OutputCDR& out, + size_t size, + size_t align, + char *&buf) +{ + return out.adjust(size, align, buf); +} + +ACE_INLINE void +ACE_Char_Codeset_Translator::good_bit (ACE_OutputCDR& out, bool bit) +{ + out.good_bit_ = bit; +} + +ACE_INLINE ACE_CDR::Octet +ACE_Char_Codeset_Translator::major_version (ACE_InputCDR& input) +{ + return input.major_version_; +} + +ACE_INLINE ACE_CDR::Octet +ACE_Char_Codeset_Translator::minor_version (ACE_InputCDR& input) +{ + return input.minor_version_; +} + +ACE_INLINE ACE_CDR::Octet +ACE_Char_Codeset_Translator::major_version (ACE_OutputCDR& output) +{ + return output.major_version_; +} + +ACE_INLINE ACE_CDR::Octet +ACE_Char_Codeset_Translator::minor_version (ACE_OutputCDR& output) +{ + return output.minor_version_; +} + +// **************************************************************** + +ACE_INLINE ACE_CDR::Boolean +ACE_WChar_Codeset_Translator::read_1 (ACE_InputCDR& input, + ACE_CDR::Octet *x) +{ + return input.read_1 (x); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_WChar_Codeset_Translator::read_2 (ACE_InputCDR& input, + ACE_CDR::UShort *x) +{ + return input.read_2 (x); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_WChar_Codeset_Translator::read_4 (ACE_InputCDR& input, + ACE_CDR::ULong *x) +{ + return input.read_4 (x); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_WChar_Codeset_Translator::write_1 (ACE_OutputCDR& output, + const ACE_CDR::Octet *x) +{ + return output.write_1 (x); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_WChar_Codeset_Translator::write_2 (ACE_OutputCDR& output, + const ACE_CDR::UShort *x) +{ + return output.write_2 (x); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_WChar_Codeset_Translator::write_4 (ACE_OutputCDR& output, + const ACE_CDR::ULong *x) +{ + return output.write_4 (x); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_WChar_Codeset_Translator::read_array (ACE_InputCDR& in, + void* x, + size_t size, + size_t align, + ACE_CDR::ULong length) +{ + return in.read_array (x, size, align, length); +} + +ACE_INLINE ACE_CDR::Boolean +ACE_WChar_Codeset_Translator::write_array (ACE_OutputCDR& out, + const void *x, + size_t size, + size_t align, + ACE_CDR::ULong length) +{ + return out.write_array(x, size, align, length); +} + +ACE_INLINE int +ACE_WChar_Codeset_Translator::adjust (ACE_OutputCDR& out, + size_t size, + size_t align, + char *&buf) +{ + return out.adjust(size, align, buf); +} + +ACE_INLINE void +ACE_WChar_Codeset_Translator::good_bit (ACE_OutputCDR& out, bool bit) +{ + out.good_bit_ = bit; +} + +ACE_INLINE ACE_CDR::Octet +ACE_WChar_Codeset_Translator::major_version (ACE_InputCDR& input) +{ + return input.major_version_; +} + +ACE_INLINE ACE_CDR::Octet +ACE_WChar_Codeset_Translator::minor_version (ACE_InputCDR& input) +{ + return input.minor_version_; +} + +ACE_INLINE ACE_CDR::Octet +ACE_WChar_Codeset_Translator::major_version (ACE_OutputCDR& output) +{ + return output.major_version_; +} + +ACE_INLINE ACE_CDR::Octet +ACE_WChar_Codeset_Translator::minor_version (ACE_OutputCDR& output) +{ + return output.minor_version_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/CE_Screen_Output.cpp b/dep/acelite/ace/CE_Screen_Output.cpp new file mode 100644 index 00000000000..dfd3d717a1f --- /dev/null +++ b/dep/acelite/ace/CE_Screen_Output.cpp @@ -0,0 +1,158 @@ +// $Id: CE_Screen_Output.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/CE_Screen_Output.h" +#if defined (ACE_HAS_WINCE) + +#include "ace/Log_Msg.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_CE_Screen_Output::ACE_CE_Screen_Output(HWND hEdit) +: handler_(hEdit) +, pFile_(0) +{ +} + +ACE_CE_Screen_Output::ACE_CE_Screen_Output() +: handler_(0) +, pFile_(0) +{ +} + +ACE_CE_Screen_Output::~ACE_CE_Screen_Output() +{ + if (pFile_ != 0) { + fclose(pFile_); + } +} + +void ACE_CE_Screen_Output::log(ACE_Log_Record &log_record) +{ + ACE_TCHAR verbose_msg[ACE_Log_Record::MAXVERBOSELOGMSGLEN]; + int result = log_record.format_msg (ACE_TEXT("WindozeCE"), // host name + 0, // verbose flag + verbose_msg); + + if (result == 0) + { + verbose_msg[ ACE_OS::strlen(verbose_msg) - 1 ] = 0; // CE does not like '\n' by itself. + *this << verbose_msg << endl; + } +} + +void ACE_CE_Screen_Output::SetOutputWindow(HWND hEdit) +{ + handler_ = hEdit; +} + +void ACE_CE_Screen_Output::clear() +{ + SetWindowText(handler_, 0); +} + +ACE_CE_Screen_Output& ACE_CE_Screen_Output::operator << (ACE_TCHAR* output) +{ + int length = GetWindowTextLength(handler_); + SendMessage(handler_, EM_SETSEL, length, length); + SendMessage(handler_, EM_REPLACESEL, 0, (LPARAM)output); + + if (pFile_ != 0) + { + fwprintf(pFile_, L"%s", output); + } + + return *this; +} + +ACE_CE_Screen_Output& ACE_CE_Screen_Output::operator << (const ACE_TCHAR* output) +{ + ACE_TCHAR* buffer = ACE_OS::strdup(output); + if (buffer != 0) + { + *this << buffer; + delete buffer; + } + return *this; +} + +ACE_CE_Screen_Output& ACE_CE_Screen_Output::operator << (ACE_ANTI_TCHAR* output) +{ + *this << ACE_TEXT_CHAR_TO_TCHAR(output); + return *this; +} + +ACE_CE_Screen_Output& ACE_CE_Screen_Output::operator << (const ACE_ANTI_TCHAR* output) +{ + *this << ACE_TEXT_CHAR_TO_TCHAR(output); + return *this; +} + +ACE_CE_Screen_Output& ACE_CE_Screen_Output::operator << (char output) +{ + *this << (int)output; + return *this; +} + +ACE_CE_Screen_Output& ACE_CE_Screen_Output::operator << (unsigned char output) +{ + *this << (int)output; + return *this; +} + +ACE_CE_Screen_Output& ACE_CE_Screen_Output::operator << (unsigned short output) +{ + ACE_TCHAR buffer[20]; + wsprintf(buffer, ACE_TEXT("%u"), output); + *this << buffer; + return *this; +} + +ACE_CE_Screen_Output& ACE_CE_Screen_Output::operator << (int output) +{ + ACE_TCHAR buffer[20]; + wsprintf(buffer, ACE_TEXT("%d"), output); + *this << buffer; + return *this; +} + +ACE_CE_Screen_Output& ACE_CE_Screen_Output::operator << (unsigned int output) +{ + ACE_TCHAR buffer[20]; + wsprintf(buffer, ACE_TEXT("%du"), output); + *this << buffer; + return *this; +} + +ACE_CE_Screen_Output& ACE_CE_Screen_Output::operator << (float output) +{ + ACE_TCHAR buffer[20]; + swprintf(buffer, ACE_TEXT("%f"), output); + *this << buffer; + return *this; +} + +ACE_CE_Screen_Output& ACE_CE_Screen_Output::operator << (long output) +{ + ACE_TCHAR buffer[20]; + wsprintf(buffer, ACE_TEXT("%l"), output); + *this << buffer; + return *this; +} + +ACE_CE_Screen_Output& ACE_CE_Screen_Output::operator << (unsigned long output) +{ + ACE_TCHAR buffer[20]; + wsprintf(buffer, ACE_TEXT("%lu"), output); + *this << buffer; + return *this; +} + +ACE_CE_Screen_Output& ACE_CE_Screen_Output::operator << (FILE* pFile) +{ + pFile_ = pFile; + return *this; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif // ACE_HAS_WINCE diff --git a/dep/acelite/ace/CE_Screen_Output.h b/dep/acelite/ace/CE_Screen_Output.h new file mode 100644 index 00000000000..ba2bc7c02b5 --- /dev/null +++ b/dep/acelite/ace/CE_Screen_Output.h @@ -0,0 +1,109 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file CE_Screen_Output.h + * + * $Id: CE_Screen_Output.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Si Mong Park + */ +//============================================================================= + +#ifndef ACE_CE_SCREEN_OUTPUT_H +#define ACE_CE_SCREEN_OUTPUT_H + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +#pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_WINCE) + +#include "ace/Log_Msg_Callback.h" +#include "ace/Log_Record.h" + +namespace +{ + const ACE_TCHAR endl[] = ACE_TEXT("\r\n"); + const ACE_TCHAR tab[] = ACE_TEXT("\t"); +} + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_CE_Screen_Output + * + * @brief Replacement of text output for Windows CE. + * + * This class allows standard text output to be displayed on + * text window for Windows CE. Generally, all ACE output will + * go through under CE if and only if user uses WindozeCE + * implementation by using main_ce instead of main. + * Also, for the easier debugging purpose, object pointer of + * this class can be gotten from ACE_Log_Msg::msg_callback() + * and then can be used directly by user just like cout stream. + */ +class ACE_Export ACE_CE_Screen_Output : public ACE_Log_Msg_Callback +{ +public: + + ACE_CE_Screen_Output (HWND hEdit); + + ACE_CE_Screen_Output (void); + + virtual ~ACE_CE_Screen_Output(); + + /// Implementation of pure virtual function from ACE_Log_Msg_Callback. + virtual void log (ACE_Log_Record &log_record); + + /// Interface to specify active window handle. + void SetOutputWindow (HWND hWnd); + + void clear (void); + + /// Stream insertion operator that performs actual print out. + /** + * @note This is the only one operator that performs output. All + * other perators convert the type and use this operator + * underneath. + */ + ACE_CE_Screen_Output& operator << (ACE_TCHAR*); + ACE_CE_Screen_Output& operator << (const ACE_TCHAR*); + + ACE_CE_Screen_Output& operator << (ACE_ANTI_TCHAR* output); + ACE_CE_Screen_Output& operator << (const ACE_ANTI_TCHAR* output); + + ACE_CE_Screen_Output& operator << (char output); + ACE_CE_Screen_Output& operator << (unsigned char output); + + ACE_CE_Screen_Output& operator << (unsigned short output); + + ACE_CE_Screen_Output& operator << (int output); + ACE_CE_Screen_Output& operator << (unsigned int output); + + ACE_CE_Screen_Output& operator << (float output); + + ACE_CE_Screen_Output& operator << (long output); + ACE_CE_Screen_Output& operator << (unsigned long output); + + ACE_CE_Screen_Output& operator << (FILE* pFile); + +private: + + ACE_CE_Screen_Output (ACE_CE_Screen_Output&); + +private: + + HWND handler_; + + /// FILE pointer that used to save output to file. This class does + /// not own the file handler pointer. + FILE* pFile_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif // ACE_HAS_WINCE +#endif // ACE_CE_SCREEN_OUTPUT_H diff --git a/dep/acelite/ace/CMakeLists.txt b/dep/acelite/ace/CMakeLists.txt new file mode 100644 index 00000000000..dd85300e7e7 --- /dev/null +++ b/dep/acelite/ace/CMakeLists.txt @@ -0,0 +1,337 @@ +# Copyright (C) 2008-2010 Trinity +# +# This file is free software; as a special exception the author gives +# unlimited permission to copy and/or distribute it, with or without +# modifications, as long as this notice is preserved. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the +# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +# NOTE: Do not use glob here, it would include files we don't want +set(ace_STAT_SRCS + PrecompiledHeaders/WinAcePCH.cpp + ACE.cpp + ACE_crc32.cpp + ACE_crc_ccitt.cpp + ace_wchar.cpp + Activation_Queue.cpp + Active_Map_Manager.cpp + Addr.cpp + Argv_Type_Converter.cpp + Assert.cpp + Asynch_IO.cpp + Asynch_IO_Impl.cpp + Asynch_Pseudo_Task.cpp + ATM_Acceptor.cpp + ATM_Addr.cpp + ATM_Connector.cpp + ATM_Params.cpp + ATM_QoS.cpp + ATM_Stream.cpp + Atomic_Op.cpp + Atomic_Op_Sparc.c + Auto_Event.cpp + Barrier.cpp + Base_Thread_Adapter.cpp + Based_Pointer_Repository.cpp + Basic_Stats.cpp + Basic_Types.cpp + Capabilities.cpp + CDR_Base.cpp + CDR_Size.cpp + CDR_Stream.cpp + Cleanup.cpp + Codecs.cpp + Codeset_IBM1047.cpp + Codeset_Registry.cpp + Codeset_Registry_db.cpp + Condition_Recursive_Thread_Mutex.cpp + Condition_Thread_Mutex.cpp + Configuration.cpp + Configuration_Import_Export.cpp + Connection_Recycling_Strategy.cpp + Containers.cpp + Copy_Disabled.cpp + Countdown_Time.cpp + Date_Time.cpp + DEV.cpp + DEV_Addr.cpp + DEV_Connector.cpp + DEV_IO.cpp + Dev_Poll_Reactor.cpp + Dirent.cpp + Dirent_Selector.cpp + DLL.cpp + DLL_Manager.cpp + Dump.cpp + Dynamic.cpp + Dynamic_Message_Strategy.cpp + Dynamic_Service_Base.cpp + Dynamic_Service_Dependency.cpp + Encoding_Converter.cpp + Encoding_Converter_Factory.cpp + Event.cpp + Event_Handler.cpp + FIFO.cpp + FIFO_Recv.cpp + FIFO_Recv_Msg.cpp + FIFO_Send.cpp + FIFO_Send_Msg.cpp + FILE.cpp + FILE_Addr.cpp + FILE_Connector.cpp + FILE_IO.cpp + File_Lock.cpp + Filecache.cpp + Flag_Manip.cpp + Framework_Component.cpp + Functor.cpp + Functor_String.cpp + Get_Opt.cpp + gethrtime.cpp + Handle_Ops.cpp + Handle_Set.cpp + Hashable.cpp + High_Res_Timer.cpp + ICMP_Socket.cpp + INET_Addr.cpp + Init_ACE.cpp + IO_Cntl_Msg.cpp + IO_SAP.cpp + IOStream.cpp + IPC_SAP.cpp + Lib_Find.cpp + Local_Memory_Pool.cpp + Local_Name_Space.cpp + Local_Tokens.cpp + Lock.cpp + Log_Msg.cpp + Log_Msg_Backend.cpp + Log_Msg_Callback.cpp + Log_Msg_IPC.cpp + Log_Msg_NT_Event_Log.cpp + Log_Msg_UNIX_Syslog.cpp + Log_Record.cpp + Logging_Strategy.cpp + LSOCK.cpp + LSOCK_Acceptor.cpp + LSOCK_CODgram.cpp + LSOCK_Connector.cpp + LSOCK_Dgram.cpp + LSOCK_Stream.cpp + Malloc.cpp + Malloc_Allocator.cpp + Manual_Event.cpp + MEM_Acceptor.cpp + MEM_Addr.cpp + MEM_Connector.cpp + MEM_IO.cpp + Mem_Map.cpp + MEM_SAP.cpp + MEM_Stream.cpp + Message_Block.cpp + Message_Queue.cpp + Message_Queue_NT.cpp + Message_Queue_Vx.cpp + Method_Request.cpp + MMAP_Memory_Pool.cpp + Monitor_Admin.cpp + Monitor_Admin_Manager.cpp + Monitor_Base.cpp + Monitor_Control_Action.cpp + Monitor_Control_Types.cpp + Monitor_Point_Registry.cpp + Monitor_Size.cpp + Msg_WFMO_Reactor.cpp + Multihomed_INET_Addr.cpp + Mutex.cpp + Name_Proxy.cpp + Name_Request_Reply.cpp + Name_Space.cpp + Naming_Context.cpp + Netlink_Addr.cpp + Notification_Queue.cpp + Notification_Strategy.cpp + NT_Service.cpp + Obchunk.cpp + Object_Manager.cpp + Object_Manager_Base.cpp + OS_Errno.cpp + OS_Log_Msg_Attributes.cpp + OS_main.cpp + OS_NS_arpa_inet.cpp + OS_NS_ctype.cpp + OS_NS_dirent.cpp + OS_NS_dlfcn.cpp + OS_NS_errno.cpp + OS_NS_fcntl.cpp + OS_NS_math.cpp + OS_NS_netdb.cpp + OS_NS_poll.cpp + OS_NS_pwd.cpp + OS_NS_regex.cpp + OS_NS_signal.cpp + OS_NS_stdio.cpp + OS_NS_stdlib.cpp + OS_NS_string.cpp + OS_NS_strings.cpp + OS_NS_stropts.cpp + OS_NS_sys_mman.cpp + OS_NS_sys_msg.cpp + OS_NS_sys_resource.cpp + OS_NS_sys_select.cpp + OS_NS_sys_sendfile.cpp + OS_NS_sys_shm.cpp + OS_NS_sys_socket.cpp + OS_NS_sys_stat.cpp + OS_NS_sys_time.cpp + OS_NS_sys_uio.cpp + OS_NS_sys_utsname.cpp + OS_NS_sys_wait.cpp + OS_NS_Thread.cpp + OS_NS_time.cpp + OS_NS_unistd.cpp + OS_NS_wchar.cpp + OS_QoS.cpp + OS_Thread_Adapter.cpp + OS_TLI.cpp + Pagefile_Memory_Pool.cpp + Parse_Node.cpp + PI_Malloc.cpp + Ping_Socket.cpp + Pipe.cpp + POSIX_Asynch_IO.cpp + POSIX_CB_Proactor.cpp + POSIX_Proactor.cpp + Priority_Reactor.cpp + Proactor.cpp + Proactor_Impl.cpp + Process.cpp + Process_Manager.cpp + Process_Mutex.cpp + Process_Semaphore.cpp + Profile_Timer.cpp + Reactor.cpp + Reactor_Impl.cpp + Reactor_Notification_Strategy.cpp + Reactor_Timer_Interface.cpp + Read_Buffer.cpp + Recursive_Thread_Mutex.cpp + Recyclable.cpp + Registry.cpp + Registry_Name_Space.cpp + Remote_Name_Space.cpp + Remote_Tokens.cpp + Rtems_init.c + RW_Mutex.cpp + RW_Process_Mutex.cpp + RW_Thread_Mutex.cpp + Sample_History.cpp + Sbrk_Memory_Pool.cpp + Sched_Params.cpp + Select_Reactor_Base.cpp + Semaphore.cpp + Service_Config.cpp + Service_Gestalt.cpp + Service_Manager.cpp + Service_Object.cpp + Service_Repository.cpp + Service_Types.cpp + Shared_Memory.cpp + Shared_Memory_MM.cpp + Shared_Memory_Pool.cpp + Shared_Memory_SV.cpp + Shared_Object.cpp + Sig_Adapter.cpp + Sig_Handler.cpp + Signal.cpp + SOCK.cpp + SOCK_Acceptor.cpp + SOCK_CODgram.cpp + Sock_Connect.cpp + SOCK_Connector.cpp + SOCK_Dgram.cpp + SOCK_Dgram_Bcast.cpp + SOCK_Dgram_Mcast.cpp + SOCK_IO.cpp + SOCK_Netlink.cpp + SOCK_SEQPACK_Acceptor.cpp + SOCK_SEQPACK_Association.cpp + SOCK_SEQPACK_Connector.cpp + SOCK_Stream.cpp + SPIPE.cpp + SPIPE_Acceptor.cpp + SPIPE_Addr.cpp + SPIPE_Connector.cpp + SPIPE_Stream.cpp + SString.cpp + Stack_Trace.cpp + Stats.cpp + String_Base_Const.cpp + SUN_Proactor.cpp + SV_Message.cpp + SV_Message_Queue.cpp + SV_Semaphore_Complex.cpp + SV_Semaphore_Simple.cpp + SV_Shared_Memory.cpp + Svc_Conf_Lexer.cpp + Svc_Conf_y.cpp + Synch_Options.cpp + System_Time.cpp + Task.cpp + Thread.cpp + Thread_Adapter.cpp + Thread_Control.cpp + Thread_Exit.cpp + Thread_Hook.cpp + Thread_Manager.cpp + Thread_Mutex.cpp + Thread_Semaphore.cpp + Throughput_Stats.cpp + Time_Value.cpp + Timeprobe.cpp + TLI.cpp + TLI_Acceptor.cpp + TLI_Connector.cpp + TLI_Stream.cpp + Token.cpp + Token_Collection.cpp + Token_Invariants.cpp + Token_Manager.cpp + Token_Request_Reply.cpp + TP_Reactor.cpp + Trace.cpp + TSS_Adapter.cpp + TTY_IO.cpp + UNIX_Addr.cpp + UPIPE_Acceptor.cpp + UPIPE_Connector.cpp + UPIPE_Stream.cpp + UTF16_Encoding_Converter.cpp + UTF32_Encoding_Converter.cpp + UTF8_Encoding_Converter.cpp + UUID.cpp + WFMO_Reactor.cpp + WIN32_Asynch_IO.cpp + WIN32_Proactor.cpp + XML_Svc_Conf.cpp + XTI_ATM_Mcast.cpp +) + +include_directories( + ${CMAKE_SOURCE_DIR}/dep/acelite + ${CMAKE_CURRENT_SOURCE_DIR}/PrecompiledHeaders + ${CMAKE_SOURCE_DIR}/dep/zlib +) + +# Needed for PCH support +set_source_files_properties(Atomic_Op_Sparc.c Rtems_init.c PROPERTIES LANGUAGE CXX) + +add_definitions(-DACE_BUILD_DLL) + +add_library(ace SHARED ${ace_STAT_SRCS}) + +add_native_precompiled_header(ace ${CMAKE_CURRENT_SOURCE_DIR}/PrecompiledHeaders/WinAcePCH) + +install(TARGETS ace RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}") diff --git a/dep/acelite/ace/CORBA_macros.h b/dep/acelite/ace/CORBA_macros.h new file mode 100644 index 00000000000..beab26b7f04 --- /dev/null +++ b/dep/acelite/ace/CORBA_macros.h @@ -0,0 +1,575 @@ +// -*- C++ -*- + +// ============================================================================ +/** + * @file CORBA_macros.h + * + * $Id: CORBA_macros.h 80826 2008-03-04 14:51:23Z wotte $ + * + * Writing code that is portable between platforms with or without + * native C++ exceptions is hard. The following macros offer some + * help on this task, mostly oriented to making the ORB code and the + * IDL generated code portable. + * + * @author Nanbor Wang + * @author Aniruddha Gokhale + * @author Carlos O'Ryan , et al. + */ +// ============================================================================ + +// Macros for handling CORBA exceptions. + +#ifndef ACE_CORBA_MACROS_H +#define ACE_CORBA_MACROS_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +# if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +# endif /* ACE_LACKS_PRAGMA_ONCE */ + +#define ACE_ENV_POLLUTE_NAMES + +#include "ace/Exception_Macros.h" + +// The Windows MFC exception mechanism requires that a caught CException +// (including the CMemoryException in use here) be freed using its Delete() +// method. Thus, when MFC is in use and we're catching exceptions as a result +// of new(), the exception's Delete() method has to be called. No other +// platform imposes this sort of restriction/requirement. The Windows +// config stuff (at least for MSVC/MFC) defines a ACE_del_bad_alloc macro +// that works with its ACE_bad_alloc macro to implement this cleanup +// requirement. Since no other platform requires this, define it as +// empty here. +#if !defined (ACE_del_bad_alloc) +# define ACE_del_bad_alloc +#endif + +#if !defined (ACE_LACKS_DEPRECATED_MACROS) + +// If you wish to you use these macros for emulating exceptions on +// platforms which lack native exception support, you need to do the +// following: +// 1. Define a class Exception. You can name it as you please. This class +// should be at the root of the inheritance hierarchy of all the +// exceptions used in your application. It should define at a minimum +// the following pure virtual methods: +// a) _downcast () - Which allows narrowing of the base exception type to a +// derived type. +// b) _raise() - Which throws an exception of type Exception. +// +// Classes which derive from these should implement these operations. +// +// 2. Define a class Environment. You can name it as you please. This class +// is an exception holder. This class is always on the stack. It should +// support at a minimum the following methods: +// a) exception() - Which returns the Exception held in the current +// Environment. +// b) exception (Exception* foo) - Which replaces/sets the Exception +// held in the current Environment with foo. +// b) clear() - Which resets a particular instance of Environment. +// c) A copy constructor and an assignment operator. +// +// Note that the above description assumes that you use the following +// macros only within a particular domain. For example, if your +// application has to interoperate across domains, then you need to define +// an exception adapter to translate exceptions from one domain to +// exceptions in the other. Please refer to Stroustrup's book on how to do +// this. If your use case is this complex, you would be better off with +// going with native exceptions rather than emulated exceptions, though +// the macros should still work if you defined your adapter class as +// ACE_EXCEPTION_TYPE. + + +// The following macros assume that an environment variable is passed +// in/out of each function that can throw an exception. The type of the +// environment variable is defined by ACE_ENV_TYPE. + +#if !defined (ACE_ENV_TYPE) +# define ACE_ENV_TYPE CORBA::Environment +#endif /* ACE_ENV_TYPE */ + +// The name of the variable is defined by ACE_TRY_ENV. Below is the name +// that we use by default. If you wish to change it you can redefine +// ACE_TRY_ENV to change the default name. Also ACE_ADOPT_ENV allows the +// use of non-standard name within a scope. + +#if !defined (ACE_TRY_ENV) +# define ACE_TRY_ENV _ACE_CORBA_Environment_variable +#endif /* ACE_TRY_ENV */ + +// The base type of Exception from which all the other exception types are +// derived. You can set this to any type as you please. By default, it is +// set to CORBA::Exception. + +#if !defined (ACE_EXCEPTION_TYPE) +# define ACE_EXCEPTION_TYPE CORBA::Exception +#endif /* ACE_EXCEPTION_TYPE */ + +// This method is used to get the default value of the Environment +// variable. In the case of TAO, this variable is part of the TSS ORB +// resources and the method TAO_default_environment() returns the +// Environment variable. + +#if !defined (ACE_DEFAULT_GET_ENV_METHOD) +# define ACE_DEFAULT_GET_ENV_METHOD TAO_default_environment +#endif /* ACE_DEFAULT_GET_ENV_METHOD */ + +// This is the exception caught by ACE_CATCHANY. +#if !defined (ACE_ANY_EXCEPTION) +# define ACE_ANY_EXCEPTION ex +#endif /* ACE_ANY_EXCEPTION */ + +// Declare a new environment variable on the stack. The type of the +// environment variable is determined by ACE_ENV_TYPE. +#if defined (ACE_USES_NATIVE_EXCEPTIONS) +// Don't instantiate an emulated exception environment at all when +// using native C++ exception support. It won't be used. +# define ACE_DECLARE_NEW_ENV +#else +# define ACE_DECLARE_NEW_ENV \ + ACE_ENV_TYPE ACE_TRY_ENV +#endif /* ACE_USES_NATIVE_EXCEPTIONS */ + +// Provided for backward compatibility purposes. Don't use it in new code. +// Use the definition above along with defining ACE_ENV_TYPE. + +#if defined (ACE_ENV_POLLUTE_NAMES) +# define ACE_DECLARE_NEW_CORBA_ENV ACE_DECLARE_NEW_ENV +#endif /* ACE_ENV_POLLUTE_NAMES */ + +#if defined (ACE_USES_NATIVE_EXCEPTIONS) +// ----------------------------------------------------------------- + +// Provided for backward compatibility purposes. Don't use it in new code. +#if defined (ACE_ENV_POLLUTE_NAMES) +# define ACE_ADOPT_CORBA_ENV(ENV) +#endif /* ACE_ENV_POLLUTE_NAMES */ + +#define ACE_ADOPT_ENV (ENV) + +// No need to check. Native exceptions handle the control flow +// automatically when an exception occurs. +# define ACE_CHECK + +// Used when the function requires a return value. +# define ACE_CHECK_RETURN(RETV) + +// ACE_THROW_INT should not be used by the user. +# define ACE_THROW_INT(EXCEPTION) \ + throw EXCEPTION + +// Throwing an exception is easy. These two macros should _NOT_ be +// used within try blocks. +# define ACE_THROW(EXCEPTION) \ + throw EXCEPTION + +// Throwing an exception when the function requires a return value. +# define ACE_THROW_RETURN(EXCEPTION,RETV) \ + throw EXCEPTION + +// For compilers with native exceptions, we can simply use try to try. ;-) +// do {} while (0) is required to avoid compilation warnings. +# define ACE_TRY \ + do \ + { \ + try \ + { +# define ACE_TRY_NEW_ENV \ + do \ + { \ + try \ + { +# define ACE_TRY_EX(LABEL) \ + do \ + { \ + try \ + { + +// No need to check for exceptions within try block for compilers with +// native exceptions. +# define ACE_TRY_CHECK +# define ACE_TRY_CHECK_EX(LABEL) + +// Likewise, throwing exceptions within try blocks is easy. +# define ACE_TRY_THROW(EXCEPTION) throw EXCEPTION +# define ACE_TRY_THROW_EX(EXCEPTION,LABEL) throw EXCEPTION + +// Same thing for catch. +# define ACE_CATCH(EXCEPTION,VAR) \ + } \ + catch (EXCEPTION & VAR) \ + { \ + ACE_UNUSED_ARG (VAR); + +# define ACE_CATCHANY \ + ACE_CATCH(ACE_EXCEPTION_TYPE, ACE_ANY_EXCEPTION) + +# define ACE_CATCHALL \ + } \ + catch (...) \ + { + +# if defined (ACE_HAS_DEPRECATED_ACE_RETHROW) +# define ACE_RETHROW throw +# endif /* ACE_HAS_DEPRECATED_ACE_RETHROW */ + +// Rethrowing the exception from catch blocks. +# define ACE_RE_THROW throw +# define ACE_RE_THROW_EX(LABEL) throw + +// Close the catch block. +# define ACE_ENDTRY \ + } \ + } while (0) + +#else /* ! ACE_USES_NATIVE_EXCEPTIONS */ +// ----------------------------------------------------------------- + +// When handling compilers without native exceptions, things get a bit +// hairy. Exceptions are simulated using ACE_ENV_TYPE. The trick here is to +// make sure the flow-of-control can simulate the case when native +// exceptions occur... + +#if defined (ACE_ENV_POLLUTE_NAMES) +# define ACE_ADOPT_CORBA_ENV(ENV) ACE_ENV_TYPE &ACE_TRY_ENV = ENV +#endif /* ACE_ENV_POLLUTE_NAMES */ + +# define ACE_ADOPT_ENV(ENV) ACE_ENV_TYPE &ACE_TRY_ENV = ENV + +// Follow every statement that could throw exceptions with ACE_CHECK or +// ACE_CHECK_RETURN. These two macros should _NOT_ be used within try +// blocks. Use ACE_TRY_CHECK or ACE_TRY_CHECK_EX instead. +# define ACE_CHECK \ + if (ACE_TRY_ENV . exception () != 0) \ + return +// When function requires a return value +# define ACE_CHECK_RETURN(RETV) \ + if (ACE_TRY_ENV . exception () != 0) \ + return RETV + +// ACE_THROW_INT should not be used by the user. +# define ACE_THROW_INT(EXCEPTION) ACE_TRY_ENV.exception (new EXCEPTION) + +// Throwing exceptions will inevitably cause a return from the current +// function. These two macros should _NOT_ be used within try blocks. Use +// ACE_TRY_THROW or ACE_TRY_THROW_EX instead. +# define ACE_THROW(EXCEPTION) \ + do \ + { \ + ACE_TRY_ENV.exception (new EXCEPTION); \ + return; \ + } while (0) + +# define ACE_THROW_RETURN(EXCEPTION,RETV) \ + do \ + { \ + ACE_TRY_ENV.exception (new EXCEPTION); \ + return RETV; \ + } while (0) + +// ACE_TRY sets up flags to control program flow. ACE_TRY_FLAG acts like a +// one-shot flip-flop. When an exception occurs (detected using +// ACE_TRY_CHECK,) ACE_TRY_FLAG will be reset and the control goes back +// into ACE_TRY_LABEL. Since ACE_TRY_FLAG is reset, the try block won't get +// executed again and the control proceeds to the following catch blocks. +// ACE_EXCEPTION_NOT_CAUGHT flag is used to prevent catching an exception +// twice. This macro assumes there's already an ACE_ENV_TYPE variable +// ACE_TRY_ENV defined (which should be the case normally) +# define ACE_TRY \ + do { \ + int ACE_TRY_FLAG = 1; \ + int ACE_EXCEPTION_NOT_CAUGHT = 1; \ + ACE_TRY_LABEL: \ + if (ACE_TRY_FLAG) \ + do { + +// ACE_TRY_NEW_ENV functions like the macro ACE_TRY but defines a new +// ACE_ENV_TYPE variable ACE_TRY_ENV. It is most often used in the outer +// most function where no ACE_TRY_ENV is available. +# define ACE_TRY_NEW_ENV \ + do { \ + ACE_DECLARE_NEW_ENV;\ + int ACE_TRY_FLAG = 1; \ + int ACE_EXCEPTION_NOT_CAUGHT = 1; \ + ACE_TRY_LABEL: \ + if (ACE_TRY_FLAG) \ + do { + +// ACE_TRY_EX works exactly like ACE_TRY macro except the label used in the +// try block is customizable to avoid name clashing. It should be used when +// nested try blocks or multiple try blocks are required, in the same +// function. +# define ACE_TRY_EX(LABEL) \ + do { \ + int ACE_TRY_FLAG = 1; \ + int ACE_EXCEPTION_NOT_CAUGHT = 1; \ + ACE_TRY_LABEL ## LABEL: \ + if (ACE_TRY_FLAG) \ + do { + +// Check for exceptions within try blocks. +# define ACE_TRY_CHECK \ + { \ + if (ACE_TRY_ENV.exception () != 0) \ + { \ + ACE_TRY_FLAG = 0; \ + goto ACE_TRY_LABEL; \ + } \ + } + +// Checking exception within EX try blocks. +# define ACE_TRY_CHECK_EX(LABEL) \ + { \ + if (ACE_TRY_ENV.exception () != 0) \ + { \ + ACE_TRY_FLAG = 0; \ + goto ACE_TRY_LABEL ## LABEL; \ + } \ + } + +// Throwing exception within TRY blocks. +# define ACE_TRY_THROW(EXCEPTION) \ + { \ + ACE_TRY_ENV.exception (new EXCEPTION); \ + ACE_TRY_FLAG = 0; \ + goto ACE_TRY_LABEL; \ + } + +# define ACE_TRY_THROW_EX(EXCEPTION,LABEL) \ + { \ + ACE_TRY_ENV.exception (new EXCEPTION); \ + ACE_TRY_FLAG = 0; \ + goto ACE_TRY_LABEL ## LABEL; \ + } + +// When exceptions occur or try block finishes execution without exception, +// control will continue in the catch block. This macro first checks if +// there's any uncaught exception left. If all the conditions are met, we +// have caught an exception. It then resets ACE_EXCEPTION_NOT_CAUGHT to +// prevent subsequent catch blocks from catching the same exception again, +// and extracts out the underlying exception in ACE_TRY_ENV. We also make a +// copy of ACE_TRY_ENV in ACE_CAUGHT_ENV, in case we want to rethrow the +// exception. ACE_TRY_ENV is cleared out after the exception is caught so +// you should not use ACE_TRY_ENV within the catch block(You should use the +// exception directly). +# define ACE_CATCH(TYPE,VAR) \ + } while (0); \ + do \ + if (ACE_TRY_ENV.exception () != 0 && ACE_EXCEPTION_NOT_CAUGHT && \ + TYPE::_downcast(ACE_TRY_ENV.exception ()) != 0) \ + { \ + ACE_ENV_TYPE ACE_CAUGHT_ENV = ACE_TRY_ENV;\ + ACE_EXCEPTION_NOT_CAUGHT = 0; \ + TYPE &VAR = *TYPE::_downcast (ACE_CAUGHT_ENV.exception ()); \ + ACE_UNUSED_ARG (VAR); \ + ACE_TRY_ENV.clear (); + +// ACE_CATCHANY uses ACE_CATCH to catch all exceptions derived from +// ACE_EXCEPTION_TYPE +# define ACE_CATCHANY ACE_CATCH (ACE_EXCEPTION_TYPE, ACE_ANY_EXCEPTION) + +// Since there's no other exception for compilers without exception +// support, we simply catch all ACE_EXCEPTION_TYPE exceptions for +// ACE_CATCHALL. +# define ACE_CATCHALL ACE_CATCHANY + +# if defined (ACE_HAS_DEPRECATED_ACE_RETHROW) +# define ACE_RETHROW \ + do \ + ACE_TRY_ENV = ACE_CAUGHT_ENV; \ + while (0) +# endif /* ACE_HAS_DEPRECATED_ACE_RETHROW */ + +// Rethrowing exception within catch blocks. Notice that we depend on the +// ACE_CHECK/ACE_CHECK_RETURN following the ACE_ENDTRY, or ACE_TRY_CHECK/ +// ACE_TRY_CHECK_EX following the ACE_ENDTRY when the catch block is within +// another try block, to do the "Right Thing[TM]." +# define ACE_RE_THROW \ + do {\ + ACE_TRY_ENV = ACE_CAUGHT_ENV; \ + goto ACE_TRY_LABEL; \ + } while (0) +# define ACE_RE_THROW_EX(LABEL) \ + do {\ + ACE_TRY_ENV = ACE_CAUGHT_ENV; \ + goto ACE_TRY_LABEL ## LABEL; \ + } while (0) + +// Close the try block. Since exceptions may not get caught, and exceptions +// can also be rethrown from the catch block, it's always a good idea to +// follow ACE_ENDTRY with ACE_CHECK or ACE_TRY_CHECK (depending on the +// context.) +# define ACE_ENDTRY \ + } while (0); \ + } while (0) + +#endif /* ! ACE_USES_NATIVE_EXCEPTIONS */ + +#endif /* !ACE_LACKS_DEPRECATED_MACROS */ + +// ACE_HAS_EXCEPTIONS is not the same as ACE_NEW_THROWS_EXCEPTIONS. +#if defined(ACE_NEW_THROWS_EXCEPTIONS) + +# if defined (ACE_HAS_NEW_NOTHROW) + +# define ACE_NEW_THROW_EX(POINTER,CONSTRUCTOR,EXCEPTION) \ + do { POINTER = new (ACE_nothrow) CONSTRUCTOR; \ + if (POINTER == 0) { throw EXCEPTION; } \ + } while (0) + +# else + +# define ACE_NEW_THROW_EX(POINTER,CONSTRUCTOR,EXCEPTION) \ + do { try { POINTER = new CONSTRUCTOR; } \ + catch (ACE_bad_alloc) { ACE_del_bad_alloc throw EXCEPTION; } \ + } while (0) + +# endif /* ACE_HAS_NEW_NOTHROW */ + +#else /* ! ACE_NEW_THROWS_EXCEPTIONS */ + +# define ACE_NEW_THROW_EX(POINTER,CONSTRUCTOR,EXCEPTION) \ + do { POINTER = new CONSTRUCTOR; \ + if (POINTER == 0) { throw EXCEPTION; } \ + } while (0) + +#endif /* ACE_NEW_THROWS_EXCEPTIONS */ + +# define ACE_GUARD_THROW_EX(MUTEX,OBJ,LOCK,EXCEPTION) \ + ACE_Guard< MUTEX > OBJ (LOCK); \ + if (OBJ.locked () == 0) throw EXCEPTION; + +# define ACE_READ_GUARD_THROW_EX(MUTEX,OBJ,LOCK,EXCEPTION) \ + ACE_Read_Guard< MUTEX > OBJ (LOCK); \ + if (OBJ.locked () == 0) throw EXCEPTION; + +# define ACE_WRITE_GUARD_THROW_EX(MUTEX,OBJ,LOCK,EXCEPTION) \ + ACE_Write_Guard< MUTEX > OBJ (LOCK); \ + if (OBJ.locked () == 0) throw EXCEPTION; + +#if !defined (ACE_LACKS_DEPRECATED_MACROS) + +//@{ +/** + * @name Native C++ exceptions portability macros. + * + * The following macros are used to write code portable between platforms + * with and without native C++ exception support. Their main goal is to + * hide the presence of the ACE_ENV_TYPE argument, but they collaborate + * with the ACE_TRY_* macros to emulate the try/catch blocks. + */ + +/// Define a macro to emit code only when ACE_ENV_TYPE is used +#if !defined (ACE_USES_NATIVE_EXCEPTIONS) || defined (ACE_ENV_BKWD_COMPAT) +# define ACE_ENV_EMIT_CODE(X) X +#else +# define ACE_ENV_EMIT_CODE(X) +#endif /* ACE_USES_NATIVE_EXCEPTIONS && ! ACE_ENV_BKWD_COMPAT */ + +/// Another macro to emit code only when ACE_ENV_TYPE is used +#if !defined (ACE_USES_NATIVE_EXCEPTIONS) || defined (ACE_ENV_BKWD_COMPAT) +# define ACE_ENV_EMIT_CODE2(X,Y) X,Y +#else +# define ACE_ENV_EMIT_CODE2(X,Y) +#endif /* ACE_USES_NATIVE_EXCEPTIONS && ! ACE_ENV_BKWD_COMPAT */ + +/// Helper macro +#define ACE_ENV_EMIT_DUMMY + +/// Declare a ACE_ENV_TYPE argument as the last argument of a +/// function +/** + * Normally this macro is used as follows: + * + * void my_funct (int x, int y ACE_ENV_ARG_DECL); + * + * Its purpose is to provide developers (and users) with a mechanism to + * write code that is portable to platforms with and without native C++ + * exceptions. + */ +#define ACE_ENV_ARG_DECL \ + ACE_ENV_EMIT_CODE2(ACE_ENV_EMIT_DUMMY, \ + ACE_ENV_TYPE &ACE_TRY_ENV) + +/// Declare a ACE_ENV_TYPE argument with the default value obtained from +/// the ORB/application. +/** + * It is similar to ACE_ENV_ARG_DECL. The name of the default environment + * getter method needs to be changed when switching ORBs or when used with + * another application. + */ +#define ACE_ENV_ARG_DECL_WITH_DEFAULTS \ + ACE_ENV_EMIT_CODE2(ACE_ENV_EMIT_DUMMY, \ + ACE_ENV_TYPE &ACE_TRY_ENV = \ + ACE_DEFAULT_GET_ENV_METHOD ()) + +/// Declare a ACE_ENV_TYPE argument that is not used by the +/// function definition. +/** + * Similar to ACE_ENV_ARG_DECL, but the formal parameter name is dropped to + * avoid warnings about unused parameters + */ +#define ACE_ENV_ARG_DECL_NOT_USED \ + ACE_ENV_EMIT_CODE2(ACE_ENV_EMIT_DUMMY, \ + ACE_ENV_TYPE &) + +/// Declare a ACE_ENV_TYPE argument for methods that do not take any other +/// parameters +#define ACE_ENV_SINGLE_ARG_DECL \ + ACE_ENV_EMIT_CODE(ACE_ENV_TYPE &ACE_TRY_ENV) + +/// Declare a ACE_ENV_TYPE argument with a default value for methods that +/// do not take any other parameters. The name of the default environment +/// getter method needs to be changed when switching ORBs or when used in +/// another application. +#define ACE_ENV_SINGLE_ARG_DECL_WITH_DEFAULTS \ + ACE_ENV_EMIT_CODE(ACE_ENV_TYPE &ACE_TRY_ENV = \ + ACE_DEFAULT_GET_ENV_METHOD ()) + +/// Declare a ACE_ENV_TYPE argument for methods which don't use it. +#define ACE_ENV_SINGLE_ARG_DECL_NOT_USED \ + ACE_ENV_EMIT_CODE(ACE_ENV_TYPE &) + +/// Use the ACE_ENV_TYPE argument in a nested call +#define ACE_ENV_ARG_PARAMETER \ + ACE_ENV_EMIT_CODE2(ACE_ENV_EMIT_DUMMY, \ + ACE_TRY_ENV) + +/// Use the ACE_ENV_TYPE argument in a nested call, assuming that the +/// called function takes only the ACE_TRY_ENV argument. +#define ACE_ENV_SINGLE_ARG_PARAMETER \ + ACE_ENV_EMIT_CODE(ACE_TRY_ENV) + +/// Eliminate unused argument warnings about ACE_TRY_ENV +#define ACE_ENV_ARG_NOT_USED \ + ACE_ENV_EMIT_CODE(ACE_UNUSED_ARG(ACE_TRY_ENV)) +//@} + +#if !defined (ACE_USES_NATIVE_EXCEPTIONS) +// This thing can be moved above when we drop ACE_ENV_BKWD_COMPAT. +# define ACE_ENV_RAISE(ex) ACE_TRY_ENV.exception (ex) +#else +# define ACE_ENV_RAISE(ex) (ex)->_raise () +#endif /* ACE_USES_NATIVE_EXCEPTIONS */ + +// ============================================================ + +// Print out a TAO exception. This is not CORBA compliant. +# define ACE_PRINT_TAO_EXCEPTION(EX,INFO) \ + EX._tao_print_exception (INFO) + +// Print out a CORBA exception. There is not portable way to +// dump a CORBA exception. If you are using other ORB implementation, +// redefine the macro to get what you want. +# if !defined ACE_PRINT_EXCEPTION +# define ACE_PRINT_EXCEPTION(EX,INFO) ACE_PRINT_TAO_EXCEPTION(EX,INFO) +# endif /* ACE_PRINT_EXCEPTION */ + +#endif /* !ACE_LACKS_DEPRECATED_MACROS */ + +#include /**/ "ace/post.h" + +#endif /* ACE_CORBA_MACROS_H */ diff --git a/dep/acelite/ace/Cache_Map_Manager_T.cpp b/dep/acelite/ace/Cache_Map_Manager_T.cpp new file mode 100644 index 00000000000..f87031eb0d7 --- /dev/null +++ b/dep/acelite/ace/Cache_Map_Manager_T.cpp @@ -0,0 +1,420 @@ +// $Id: Cache_Map_Manager_T.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#ifndef ACE_CACHE_MAP_MANAGER_T_CPP +#define ACE_CACHE_MAP_MANAGER_T_CPP + +#include "ace/Cache_Map_Manager_T.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +#pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Log_Msg.h" +#include "ace/Malloc_Base.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Cache_Map_Manager_T.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Cache_Map_Manager) + +ACE_ALLOC_HOOK_DEFINE(ACE_Cache_Map_Iterator) + +ACE_ALLOC_HOOK_DEFINE(ACE_Cache_Map_Reverse_Iterator) + +#define ACE_T1 class KEY, class VALUE, class CMAP_TYPE, class ITERATOR_IMPL, class REVERSE_ITERATOR_IMPL, class CACHING_STRATEGY, class ATTRIBUTES +#define ACE_T2 KEY, VALUE, CMAP_TYPE, ITERATOR_IMPL, REVERSE_ITERATOR_IMPL, CACHING_STRATEGY, ATTRIBUTES + +template +ACE_Cache_Map_Manager::ACE_Cache_Map_Manager (CACHING_STRATEGY &caching_s, + size_t size, + ACE_Allocator *alloc) + : caching_strategy_ (caching_s) +{ + if (this->open (size, alloc) == -1) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_Cache_Map_Manager::ACE_Cache_Map_Manager"))); + +} + +template +ACE_Cache_Map_Manager::~ACE_Cache_Map_Manager (void) +{ + this->close (); +} + +template int +ACE_Cache_Map_Manager::open (size_t length, + ACE_Allocator *alloc) +{ + return this->map_.open (length, + alloc); +} + +template int +ACE_Cache_Map_Manager::close (void) +{ + return this->map_.close (); +} + +template int +ACE_Cache_Map_Manager::bind (const KEY &key, + const VALUE &value) +{ + // Insert an entry which has the and the which + // is the combination of the and the attributes of the + // caching strategy. + CACHE_VALUE cache_value (value, + this->caching_strategy_.attributes ()); + + int bind_result = this->map_.bind (key, + cache_value); + + if (bind_result != -1) + { + + int result = this->caching_strategy_.notify_bind (bind_result, + cache_value.second ()); + + if (result == -1) + { + + this->map_.unbind (key); + + // Unless the notification goes thru the bind operation is + // not complete. + bind_result = -1; + + } + + } + + return bind_result; +} + + +template int +ACE_Cache_Map_Manager::rebind (const KEY &key, + const VALUE &value) +{ + CACHE_VALUE cache_value (value, + this->caching_strategy_.attributes ()); + + int rebind_result = this->map_.rebind (key, + cache_value); + + if (rebind_result != -1) + { + + int result = this->caching_strategy_.notify_rebind (rebind_result, + cache_value.second ()); + + if (result == -1) + { + + // Make sure the unbind operation is done only when the + // notification fails after a bind which is denoted by + // rebind_result = 0 + if (rebind_result == 0) + this->map_.unbind (key); + + // Unless the notification goes thru the rebind operation is + // not complete. + rebind_result = -1; + + } + + } + + return rebind_result; +} + + +template int +ACE_Cache_Map_Manager::rebind (const KEY &key, + const VALUE &value, + VALUE &old_value) +{ + CACHE_VALUE cache_value (value, + this->caching_strategy_.attributes ()); + + CACHE_VALUE old_cache_value (old_value, + this->caching_strategy_.attributes ()); + + int rebind_result = this->map_.rebind (key, + cache_value, + old_cache_value); + + if (rebind_result != -1) + { + + int result = this->caching_strategy_.notify_rebind (rebind_result, + cache_value.second ()); + + if (result == -1) + { + + // Make sure the unbind operation is done only when the + // notification fails after a bind which is denoted by + // rebind_result = 0 + if (rebind_result == 0) + this->map_.unbind (key); + + // Unless the notification goes thru the rebind operation is + // not complete. + rebind_result = -1; + + } + else + { + + old_value = old_cache_value.first (); + + } + + } + + return rebind_result; +} + +template int +ACE_Cache_Map_Manager::rebind (const KEY &key, + const VALUE &value, + KEY &old_key, + VALUE &old_value) +{ + CACHE_VALUE cache_value (value, + this->caching_strategy_.attributes ()); + + CACHE_VALUE old_cache_value (old_value, + this->caching_strategy_.attributes ()); + + int rebind_result = this->map_.rebind (key, + cache_value, + old_key, + old_cache_value); + + if (rebind_result != -1) + { + + int result = this->caching_strategy_.notify_rebind (rebind_result, + cache_value.second ()); + + if (result == -1) + { + + // Make sure the unbind operation is done only when the + // notification fails after a bind which is denoted by + // rebind_result = 0 + if (rebind_result == 0) + this->map_.unbind (key); + + // Unless the notification goes thru the rebind operation is + // not complete. + rebind_result = -1; + + } + else + { + + old_value = old_cache_value.first (); + + } + + } + + return rebind_result; +} + +template int +ACE_Cache_Map_Manager::trybind (const KEY &key, + VALUE &value) +{ + CACHE_VALUE cache_value (value, + this->caching_strategy_.attributes ()); + + int trybind_result = this->map_.trybind (key, + cache_value); + + if (trybind_result != -1) + { + + int result = this->caching_strategy_.notify_trybind (trybind_result, + cache_value.second ()); + + if (result == -1) + { + + // If the entry has got inserted into the map, it is removed + // due to failure. + if (trybind_result == 0) + this->map_.unbind (key); + + trybind_result = -1; + + } + else + { + + // If an attempt is made to bind an existing entry the value + // is overwritten with the value from the map. + if (trybind_result == 1) + value = cache_value.first (); + + } + + } + + return trybind_result; +} + +template int +ACE_Cache_Map_Manager::find (const KEY &key, + VALUE &value) +{ + // Lookup the key and populate the . + CACHE_VALUE cache_value; + + int find_result = this->map_.find (key, + cache_value); + + if (find_result != -1) + { + + int result = this->caching_strategy_.notify_find (find_result, + cache_value.second ()); + + // Unless the find and notification operations go thru, this + // method is not successful. + if (result == -1) + find_result = -1; + else + { + + // Since the has now changed after the + // notification, we need to bind to the map again. + int rebind_result = this->map_.rebind (key, + cache_value); + if (rebind_result == -1) + find_result = -1; + else + value = cache_value.first (); + + } + + } + + return find_result; +} + +template int +ACE_Cache_Map_Manager::find (const KEY &key) +{ + // Lookup the key and populate the . + CACHE_VALUE cache_value; + + int find_result = this->map_.find (key, + cache_value); + + if (find_result != -1) + { + + int result = this->caching_strategy_.notify_find (find_result, + cache_value.second ()); + + // Unless the find and notification operations go thru, this + // method is not successful. + if (result == -1) + find_result = -1; + else + { + + // Since the has now changed after the + // notification, we need to bind to the map again. + int rebind_result = this->map_.rebind (key, + cache_value); + + if (rebind_result == -1) + find_result = -1; + + } + + } + + return find_result; +} + + +template int +ACE_Cache_Map_Manager::unbind (const KEY &key) +{ + // Remove the entry from the cache. + CACHE_VALUE cache_value; + + int unbind_result = this->map_.unbind (key, + cache_value); + + if (unbind_result != -1) + { + + int result = this->caching_strategy_.notify_unbind (unbind_result, + cache_value.second ()); + + if (result == -1) + unbind_result = -1; + + } + + return unbind_result; +} + +template int +ACE_Cache_Map_Manager::unbind (const KEY &key, + VALUE &value) +{ + // Remove the entry from the cache. + CACHE_VALUE cache_value; + + int unbind_result = this->map_.unbind (key, + cache_value); + + if (unbind_result != -1) + { + + int result = this->caching_strategy_.notify_unbind (unbind_result, + cache_value.second ()); + + if (result == -1) + unbind_result = -1; + else + value = cache_value.first (); + + } + + return unbind_result; +} + +template void +ACE_Cache_Map_Manager::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + this->map_.dump (); + + this->caching_strategy_.dump (); +#endif /* ACE_HAS_DUMP */ +} + +#undef ACE_T1 +#undef ACE_T2 + +template +ACE_Cache_Map_Iterator::~ACE_Cache_Map_Iterator (void) +{ +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_CACHE_MAP_MANAGER_T_CPP */ diff --git a/dep/acelite/ace/Cache_Map_Manager_T.h b/dep/acelite/ace/Cache_Map_Manager_T.h new file mode 100644 index 00000000000..060a8b38aac --- /dev/null +++ b/dep/acelite/ace/Cache_Map_Manager_T.h @@ -0,0 +1,405 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Cache_Map_Manager_T.h + * + * $Id: Cache_Map_Manager_T.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Kirthika Parameswaran + */ +//============================================================================= + +#ifndef ACE_CACHE_MAP_MANAGER_T_H +#define ACE_CACHE_MAP_MANAGER_T_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Default_Constants.h" +#include "ace/Global_Macros.h" +#include "ace/Pair_T.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Forward declaration. +class ACE_Allocator; + +#define ACE_Cache_Map_Iterator ACMI +#define ACE_Cache_Map_Reverse_Iterator ACMRI + +template +class ACE_Cache_Map_Iterator; + +template +class ACE_Cache_Map_Reverse_Iterator; + +// For linkers that cant grok long names. +#define ACE_Cache_Map_Manager ACMM + +/** + * @class ACE_Cache_Map_Manager + * + * @brief Defines a abstraction that will purge entries from a map. + * + * The will manage the map it contains + * and provide purging on demand from the map. The strategy for + * caching is decided by the user and provided to the Cache + * Manager. The Cache Manager acts as a agent and communicates + * between the Map and the Strategy for purging entries from the + * map. + * No locking mechanism provided since locking at this level + * isn't efficient. Locking has to be provided by the + * application. + */ +template +class ACE_Cache_Map_Manager +{ +public: + + // = Traits. + typedef KEY key_type; + typedef VALUE mapped_type; + typedef CMAP_TYPE map_type; + typedef CACHING_STRATEGY caching_strategy_type; + + typedef ITERATOR_IMPL ITERATOR_IMPLEMENTATION; + typedef REVERSE_ITERATOR_IMPL REVERSE_ITERATOR_IMPLEMENTATION; + + friend class ACE_Cache_Map_Iterator; + friend class ACE_Cache_Map_Reverse_Iterator; + + // = ACE-style iterator typedefs. + typedef ACE_Cache_Map_Iterator + ITERATOR; + typedef ACE_Cache_Map_Reverse_Iterator + REVERSE_ITERATOR; + + // = STL-style iterator typedefs. + typedef ITERATOR + iterator; + typedef REVERSE_ITERATOR + reverse_iterator; + + /** + * The actual value mapped to the key in the map. The + * are used by the strategy and is transparent to the user of this + * class. + */ + typedef ACE_Pair CACHE_VALUE; + + // = Initialization and termination methods. + + /// Initialize a with and + /// @a size entries. + ACE_Cache_Map_Manager (CACHING_STRATEGY &caching_strategy, + size_t size = ACE_DEFAULT_MAP_SIZE, + ACE_Allocator *alloc = 0); + + /// Close down a and release dynamically allocated + /// resources. + virtual ~ACE_Cache_Map_Manager (void); + + /// Initialize a cache with size @a length. + int open (size_t length = ACE_DEFAULT_MAP_SIZE, + ACE_Allocator *alloc = 0); + + /// Close down a cache and release dynamically allocated resources. + int close (void); + + /** + * Associate @a key with @a value. If @a key is already in the CMAP_TYPE + * then the ENTRY is not changed. Returns 0 if a new entry is bound + * successfully, returns 1 if an attempt is made to bind an existing + * entry, and returns -1 if failures occur. + */ + int bind (const KEY &key, + const VALUE &value); + + /** + * Lookup entry in the cache. If it is not found, returns -1. + * If the @a key is located in the CMAP_TYPE object, the CACHING_STRATEGY is + * notified of it via notify_find (int result, ATTRIBUTES &attribute). + * If notify_find also returns 0 (success), then this function returns + * 0 (success) and sets the cached value in @a value. + */ + int find (const KEY &key, + VALUE &value); + + /** + * Lookup entry in the cache. If it is not found, returns -1. + * If the @a key is located in the CMAP_TYPE object, the CACHING_STRATEGY is + * notified of it via notify_find (int result, ATTRIBUTES &attribute). + * If notify_find also returns 0 (success), then this function returns + * 0 (success). + */ + int find (const KEY &key); + + /** + * Reassociate the @a key with @a value. If the @a key already exists + * in the cache then returns 1, on a new bind returns 0 and returns + * -1 in case of any failures. + */ + int rebind (const KEY &key, + const VALUE &value); + + /** + * Reassociate @a key with @a value, storing the old value into the + * "out" parameter @a old_value. The function fails if @a key is not + * in the cache for caches that do not allow user specified keys. + * However, for caches that allow user specified keys, if the key is + * not in the cache, a new @a key / @a value association is created. + */ + int rebind (const KEY &key, + const VALUE &value, + VALUE &old_value); + + /** + * Reassociate @a key with @a value, storing the old key and value + * into the "out" parameters @a old_key and @a old_value. The + * function fails if @a key is not in the cache for caches that do + * not allow user specified keys. However, for caches that allow + * user specified keys, if the key is not in the cache, a new + * @a key / @a value association is created. + */ + int rebind (const KEY &key, + const VALUE &value, + KEY &old_key, + VALUE &old_value); + + /** + * Associate @a key with @a value if and only if @a key is not in the + * cache. If @a key is already in the cache, then the @a value + * parameter is overwritten with the existing value in the + * cache. Returns 0 if a new @a key / @a value association is created. + * Returns 1 if an attempt is made to bind an existing entry. This + * function fails for maps that do not allow user specified keys. + */ + int trybind (const KEY &key, + VALUE &value); + + /// Remove @a key from the cache. + int unbind (const KEY &key); + + /// Remove @a key from the cache, and return the @a value associated with + /// @a key. + int unbind (const KEY &key, + VALUE &value); + + /// Remove entries from the cache depending upon the strategy. + int purge (void); + + /// Return the current size of the cache. + size_t current_size (void) const; + + /// Return the total size of the cache. + size_t total_size (void) const; + + /// Dumps the state of the object. + void dump (void) const; + + // = STL styled iterator factory functions. + + /// Return forward iterator. + ITERATOR begin (void); + ITERATOR end (void); + + /// Return reverse iterator. + REVERSE_ITERATOR rbegin (void); + REVERSE_ITERATOR rend (void); + + /// The map managed by the Cache_Map_Manager. + CMAP_TYPE &map (void); + + /// The caching strategy used on the cache. + CACHING_STRATEGY &caching_strategy (void); + +protected: + + /// The underlying map which needs to be cached. + CMAP_TYPE map_; + + /// The strategy to be followed for caching entries in the map. + CACHING_STRATEGY &caching_strategy_; + +private: + + // = Disallow these operations. + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Cache_Map_Manager &)) + ACE_UNIMPLEMENTED_FUNC (ACE_Cache_Map_Manager (const ACE_Cache_Map_Manager &)) + +}; + +/** + * @class ACE_Cache_Map_Iterator + * + * @brief Defines a iterator for the Cache_Map_Manager. + * + * Implementation to be provided by the iterator of the map + * managed by the ACE_Cache_Map_Manager. + */ +template +class ACE_Cache_Map_Iterator +{ + +public: + + // = Traits. + /// The actual value mapped to the key in the cache. The + /// are used by the strategy and is transperant to the cache user. + typedef ACE_Reference_Pair + value_type; + typedef ACE_Pair + CACHE_VALUE; + + // = Initialisation and termination methods. + + ACE_Cache_Map_Iterator (const IMPLEMENTATION &iterator_impl); + + /// Copy constructor. + ACE_Cache_Map_Iterator (const ACE_Cache_Map_Iterator &rhs); + + virtual ~ACE_Cache_Map_Iterator (void); + + // = Iteration methods. + + /// assignment operator. + ACE_Cache_Map_Iterator &operator= + (const ACE_Cache_Map_Iterator &rhs); + + /// Comparision operators. + bool operator== (const ACE_Cache_Map_Iterator &rhs) const; + bool operator!= (const ACE_Cache_Map_Iterator &rhs) const; + + /// Returns a reference to the internal element @c this is pointing + /// to. + ACE_Reference_Pair operator* (void) const; + + // = STL styled iteration, compare, and reference functions. + + /// Prefix advance + ACE_Cache_Map_Iterator &operator++ (void); + + /// Postfix advance. + ACE_Cache_Map_Iterator operator++ (int); + + /// Prefix reverse. + ACE_Cache_Map_Iterator &operator-- (void); + + /// Postfix reverse. + ACE_Cache_Map_Iterator operator-- (int); + + /// Returns the iterator of the internal map in the custody of the + /// Cache_Map_Manager. + IMPLEMENTATION &iterator_implementation (void); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + /// The actual iterator which iterates internally on the map + /// belonging to the Cache_Map_Manager. + IMPLEMENTATION iterator_implementation_; +}; + +/** + * @class ACE_Cache_Map_Reverse_Iterator + * + * @brief Defines a reverse iterator for the Cache_Map_Manager. + * + * Implementation to be provided by the reverse iterator of the map + * managed by thr Cache_Map_manager. + */ +template +class ACE_Cache_Map_Reverse_Iterator +{ +public: + + // = Traits. + /// The actual value mapped to the key in the cache. The + /// are used by the strategy and is transperant to the cache user. + typedef ACE_Reference_Pair value_type; + typedef ACE_Pair CACHE_VALUE; + + // = Initialisation and termination methods. + + ACE_Cache_Map_Reverse_Iterator (const REVERSE_IMPLEMENTATION &iterator_impl); + + /// Copy constructor. + ACE_Cache_Map_Reverse_Iterator (const ACE_Cache_Map_Reverse_Iterator &rhs); + + ~ACE_Cache_Map_Reverse_Iterator (void); + + // = Iteration methods. + + /// Assignment operator. + ACE_Cache_Map_Reverse_Iterator &operator= + (const ACE_Cache_Map_Reverse_Iterator &rhs); + + /// Comparision operators. + bool operator== (const ACE_Cache_Map_Reverse_Iterator &rhs) const; + bool operator!= (const ACE_Cache_Map_Reverse_Iterator &rhs) const; + + /// Returns a reference to the internal element @c this is pointing + /// to. + ACE_Reference_Pair operator* (void) const; + + // = STL styled iteration, compare, and reference functions. + + /// Prefix advance + ACE_Cache_Map_Reverse_Iterator &operator++ (void); + + /// Postfix advance. + ACE_Cache_Map_Reverse_Iterator operator++ (int); + + /// Prefix reverse. + ACE_Cache_Map_Reverse_Iterator &operator-- (void); + + /// Postfix reverse. + ACE_Cache_Map_Reverse_Iterator operator-- (int); + + /// Returns the iterator of the internal map in the custody of the + /// Cache_Map_Manager. + REVERSE_IMPLEMENTATION &iterator_implementation (void); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + /// The actual iterator which iterates internally on the map + /// belonging to the Cache_Map_Manager. + REVERSE_IMPLEMENTATION reverse_iterator_implementation_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Cache_Map_Manager_T.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Cache_Map_Manager_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Cache_Map_Manager_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" + +#endif /* ACE_CACHE_MAP_MANAGER_T_H */ diff --git a/dep/acelite/ace/Cache_Map_Manager_T.inl b/dep/acelite/ace/Cache_Map_Manager_T.inl new file mode 100644 index 00000000000..bcd48bd33e9 --- /dev/null +++ b/dep/acelite/ace/Cache_Map_Manager_T.inl @@ -0,0 +1,245 @@ +// -*- C++ -*- +// +//$Id: Cache_Map_Manager_T.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template ACE_INLINE int +ACE_Cache_Map_Manager::purge (void) +{ + return this->caching_strategy ().caching_utility ().clear_cache (this->map_, + this->caching_strategy ().purge_percent ()); +} + +template ACE_INLINE size_t +ACE_Cache_Map_Manager::current_size (void) const +{ + return this->map_.current_size (); +} + +template ACE_INLINE size_t +ACE_Cache_Map_Manager::total_size (void) const +{ + return this->map_.total_size (); +} + +template ACE_INLINE CMAP_TYPE & +ACE_Cache_Map_Manager::map (void) +{ + return this->map_; +} + +template ACE_INLINE CACHING_STRATEGY & +ACE_Cache_Map_Manager::caching_strategy (void) +{ + return this->caching_strategy_; +} + +template ACE_INLINE ACE_Cache_Map_Iterator +ACE_Cache_Map_Manager::begin (void) +{ + return ITERATOR (this->map_.begin ()); +} + +template ACE_INLINE ACE_Cache_Map_Iterator +ACE_Cache_Map_Manager::end (void) +{ + return ITERATOR (this->map_.end ()); +} + +template ACE_INLINE ACE_Cache_Map_Reverse_Iterator +ACE_Cache_Map_Manager::rbegin (void) +{ + return REVERSE_ITERATOR (this->map_.rbegin ()); +} +template ACE_INLINE ACE_Cache_Map_Reverse_Iterator +ACE_Cache_Map_Manager::rend (void) +{ + return REVERSE_ITERATOR (this->map_.rend ()); +} + +//////////////////////////////////////////////////////////////////////////////// + +template ACE_INLINE +ACE_Cache_Map_Iterator::ACE_Cache_Map_Iterator (const ACE_Cache_Map_Iterator &rhs) + : iterator_implementation_ (rhs.iterator_implementation_) +{ +} + +template ACE_INLINE ACE_Cache_Map_Iterator & +ACE_Cache_Map_Iterator::operator= (const ACE_Cache_Map_Iterator &rhs) +{ + this->iterator_implementation_ = rhs.iterator_implementation_; + return *this; +} + +template ACE_INLINE bool +ACE_Cache_Map_Iterator::operator== (const ACE_Cache_Map_Iterator &rhs) const +{ + return this->iterator_implementation_ == rhs.iterator_implementation_; +} + +template ACE_INLINE bool +ACE_Cache_Map_Iterator::operator!= (const ACE_Cache_Map_Iterator &rhs) const +{ + return this->iterator_implementation_ != rhs.iterator_implementation_; +} + +template ACE_INLINE ACE_Reference_Pair +ACE_Cache_Map_Iterator::operator* (void) const +{ + value_type retn ((*this->iterator_implementation_).ext_id_, + (*this->iterator_implementation_).int_id_.first ()); + return retn; +} + +template ACE_INLINE +ACE_Cache_Map_Iterator & +ACE_Cache_Map_Iterator::operator++ (void) +{ + ++this->iterator_implementation_; + return *this; +} + +template ACE_INLINE +ACE_Cache_Map_Iterator +ACE_Cache_Map_Iterator::operator++ (int) +{ + ACE_Cache_Map_Iterator retn = *this; + ++this->iterator_implementation_; + return retn; +} + +template ACE_INLINE +ACE_Cache_Map_Iterator & +ACE_Cache_Map_Iterator::operator-- (void) +{ + --this->iterator_implementation_; + return *this; +} + +template ACE_INLINE +ACE_Cache_Map_Iterator +ACE_Cache_Map_Iterator::operator-- (int) +{ + ACE_Cache_Map_Iterator retn = *this; + --this->iterator_implementation_; + return retn; +} + +template ACE_INLINE void +ACE_Cache_Map_Iterator::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + this->iterator_implementation_.dump (); +#endif /* ACE_HAS_DUMP */ +} + +template ACE_INLINE +ACE_Cache_Map_Iterator::ACE_Cache_Map_Iterator (const IMPLEMENTATION &iterator_impl) + : iterator_implementation_ (iterator_impl) +{ +} + +template ACE_INLINE IMPLEMENTATION & +ACE_Cache_Map_Iterator::iterator_implementation (void) +{ + return this->iterator_implementation_; +} + +//////////////////////////////////////////////////////////////////////////////// + +template ACE_INLINE +ACE_Cache_Map_Reverse_Iterator::ACE_Cache_Map_Reverse_Iterator (const ACE_Cache_Map_Reverse_Iterator &rhs) + : reverse_iterator_implementation_ (rhs.reverse_iterator_implementation_) +{ +} + +template ACE_INLINE +ACE_Cache_Map_Reverse_Iterator::~ACE_Cache_Map_Reverse_Iterator (void) +{ +} + +template ACE_INLINE ACE_Cache_Map_Reverse_Iterator & +ACE_Cache_Map_Reverse_Iterator::operator= (const ACE_Cache_Map_Reverse_Iterator &rhs) +{ + this->reverse_iterator_implementation_ = rhs.reverse_iterator_implementation_; + return *this; +} + +template ACE_INLINE bool +ACE_Cache_Map_Reverse_Iterator::operator== (const ACE_Cache_Map_Reverse_Iterator &rhs) const +{ + return this->reverse_iterator_implementation_ == rhs.reverse_iterator_implementation_; +} + +template ACE_INLINE bool +ACE_Cache_Map_Reverse_Iterator::operator!= (const ACE_Cache_Map_Reverse_Iterator &rhs) const +{ + return this->reverse_iterator_implementation_ != rhs.reverse_iterator_implementation_; +} + +template ACE_INLINE ACE_Reference_Pair +ACE_Cache_Map_Reverse_Iterator::operator* (void) const +{ + value_type retv ((*this->reverse_iterator_implementation_).ext_id_, + (*this->reverse_iterator_implementation_).int_id_.first ()); + return retv; +} + +template ACE_INLINE +ACE_Cache_Map_Reverse_Iterator & +ACE_Cache_Map_Reverse_Iterator::operator++ (void) +{ + ++this->reverse_iterator_implementation_; + return *this; +} + +template ACE_INLINE +ACE_Cache_Map_Reverse_Iterator +ACE_Cache_Map_Reverse_Iterator::operator++ (int) +{ + ACE_Cache_Map_Reverse_Iterator retn = *this; + ++this->reverse_iterator_implementation_; + return retn; +} + +template ACE_INLINE +ACE_Cache_Map_Reverse_Iterator & +ACE_Cache_Map_Reverse_Iterator::operator-- (void) +{ + --this->reverse_iterator_implementation_; + return *this; +} + +template ACE_INLINE +ACE_Cache_Map_Reverse_Iterator +ACE_Cache_Map_Reverse_Iterator::operator-- (int) +{ + ACE_Cache_Map_Reverse_Iterator retn = *this; + --this->reverse_iterator_implementation_; + return retn; +} + + +template ACE_INLINE void +ACE_Cache_Map_Reverse_Iterator::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + this->reverse_iterator_implementation_.dump (); +#endif /* ACE_HAS_DUMP */ +} + +template ACE_INLINE +ACE_Cache_Map_Reverse_Iterator::ACE_Cache_Map_Reverse_Iterator (const REVERSE_IMPLEMENTATION &iterator_impl) + : reverse_iterator_implementation_(iterator_impl) +{ +} + +template ACE_INLINE REVERSE_IMPLEMENTATION & +ACE_Cache_Map_Reverse_Iterator::iterator_implementation (void) +{ + return this->reverse_iterator_implementation_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Cached_Connect_Strategy_T.cpp b/dep/acelite/ace/Cached_Connect_Strategy_T.cpp new file mode 100644 index 00000000000..077c6d6a9ae --- /dev/null +++ b/dep/acelite/ace/Cached_Connect_Strategy_T.cpp @@ -0,0 +1,734 @@ +//$Id: Cached_Connect_Strategy_T.cpp 82771 2008-09-17 18:47:48Z johnnyw $ + +#ifndef ACE_CACHED_CONNECT_STRATEGY_T_CPP +#define ACE_CACHED_CONNECT_STRATEGY_T_CPP + +#include "ace/Cached_Connect_Strategy_T.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +#pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/ACE.h" +#include "ace/Service_Repository.h" +#include "ace/Service_Types.h" +#include "ace/Thread_Manager.h" +#include "ace/WFMO_Reactor.h" +#include "ace/Pair_T.h" + +#define ACE_T1 class SVC_HANDLER, ACE_PEER_CONNECTOR_1, class CACHING_STRATEGY, class ATTRIBUTES, class MUTEX +#define ACE_T2 SVC_HANDLER, ACE_PEER_CONNECTOR_2, CACHING_STRATEGY, ATTRIBUTES, MUTEX + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template +ACE_Cached_Connect_Strategy_Ex::ACE_Cached_Connect_Strategy_Ex +(CACHING_STRATEGY &caching_s, + ACE_Creation_Strategy *cre_s, + ACE_Concurrency_Strategy *con_s, + ACE_Recycling_Strategy *rec_s, + MUTEX *lock, + int delete_lock) + : CCSBASE (cre_s, con_s, rec_s, lock, delete_lock), + connection_cache_ (caching_s) +{ + if (this->open (cre_s, con_s, rec_s) == -1) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_Cached_Connect_Strategy_Ex\n"))); +} + +template +ACE_Cached_Connect_Strategy_Ex::~ACE_Cached_Connect_Strategy_Ex (void) +{ + cleanup (); +} + + +template int +ACE_Cached_Connect_Strategy_Ex::check_hint_i +(SVC_HANDLER *&sh, + const ACE_PEER_CONNECTOR_ADDR &remote_addr, + ACE_Time_Value *timeout, + const ACE_PEER_CONNECTOR_ADDR &local_addr, + bool reuse_addr, + int flags, + int perms, + ACE_Hash_Map_Entry, ACE_Pair > *&entry, + int &found) +{ + ACE_UNUSED_ARG (remote_addr); + ACE_UNUSED_ARG (timeout); + ACE_UNUSED_ARG (local_addr); + ACE_UNUSED_ARG (reuse_addr); + ACE_UNUSED_ARG (flags); + ACE_UNUSED_ARG (perms); + + found = 0; + + // Get the recycling act for the svc_handler + CONNECTION_CACHE_ENTRY *possible_entry = + (CONNECTION_CACHE_ENTRY *) sh->recycling_act (); + + // Check to see if the hint svc_handler has been closed down + if (possible_entry->ext_id_.recycle_state () == ACE_RECYCLABLE_CLOSED) + { + // If close, decrement refcount + if (possible_entry->ext_id_.decrement () == 0) + { + // If refcount goes to zero, close down the svc_handler + possible_entry->int_id_.first ()->recycler (0, 0); + possible_entry->int_id_.first ()->close (); + this->purge_i (possible_entry); + } + + // Hint not successful + found = 0; + + // Reset hint + sh = 0; + } + + // If hint is not closed, see if it is connected to the correct + // address and is recyclable + else if ((possible_entry->ext_id_.recycle_state () == ACE_RECYCLABLE_IDLE_AND_PURGABLE || + possible_entry->ext_id_.recycle_state () == ACE_RECYCLABLE_IDLE_BUT_NOT_PURGABLE) && + possible_entry->ext_id_.subject () == remote_addr) + { + // Hint successful + found = 1; + + // Tell the that it should prepare itself for + // being recycled. + this->prepare_for_recycling (sh); + + // + // Update the caching attributes directly since we don't do a + // find() on the cache map. + // + + // Indicates successful find. + int find_result = 0; + + int result = this->caching_strategy ().notify_find (find_result, + possible_entry->int_id_.second ()); + + if (result == -1) + return result; + } + else + { + // This hint will not be used. + possible_entry->ext_id_.decrement (); + + // Hint not successful + found = 0; + + // If is not connected to the correct address or is busy, + // we will not use it. + sh = 0; + } + + if (found) + entry = possible_entry; + + return 0; +} + +template int +ACE_Cached_Connect_Strategy_Ex::find_or_create_svc_handler_i +(SVC_HANDLER *&sh, + const ACE_PEER_CONNECTOR_ADDR &remote_addr, + ACE_Time_Value *timeout, + const ACE_PEER_CONNECTOR_ADDR &local_addr, + bool reuse_addr, + int flags, + int perms, + ACE_Hash_Map_Entry, ACE_Pair > *&entry, + int &found) +{ + REFCOUNTED_HASH_RECYCLABLE_ADDRESS search_addr (remote_addr); + + // Try to find the address in the cache. Only if we don't find it + // do we create a new and connect it with the server. + while (this->find (search_addr, entry) != -1) + { + // We found a cached svc_handler. + // Get the cached + sh = entry->int_id_.first (); + + // Is the connection clean? + int state_result = + ACE::handle_ready (sh->peer ().get_handle (), + &ACE_Time_Value::zero, + 1, // read ready + 0, // write ready + 1);// exception ready + + if (state_result == 1) + { + + if (sh->close () == -1) + return -1; + + sh = 0; + + // Cycle it once again.. + } + else if ((state_result == -1) && (errno == ETIME)) + { + // Found!!! + // Set the flag + found = 1; + + // Tell the that it should prepare itself for + // being recycled. + if (this->prepare_for_recycling (sh) == -1) + return -1; + + return 0; + } + else + { + return -1; + } + } + + // Not found... + + // Set the flag + found = 0; + + // We need to use a temporary variable here since we are not + // allowed to change because other threads may use this + // when we let go of the lock during the OS level connect. + // + // Note that making a new svc_handler, connecting remotely, + // binding to the map, and assigning of the hint and recycler + // should be atomic to the outside world. + SVC_HANDLER *potential_handler = 0; + + // Create a new svc_handler + if (this->make_svc_handler (potential_handler) == -1) + return -1; + + // Connect using the svc_handler. + if (this->cached_connect (potential_handler, + remote_addr, + timeout, + local_addr, + reuse_addr, + flags, + perms) == -1) + { + // Close the svc handler. + potential_handler->close (0); + + return -1; + } + else + { + // Insert the new SVC_HANDLER instance into the cache. + if (this->connection_cache_.bind (search_addr, + potential_handler, + entry) == -1) + { + // Close the svc handler and reset . + potential_handler->close (0); + + return -1; + } + + // Everything succeeded as planned. Assign to + // . + sh = potential_handler; + + // Set the recycler and the recycling act + + this->assign_recycler (sh, this, entry); + } + + return 0; +} + +template int +ACE_Cached_Connect_Strategy_Ex::cached_connect (SVC_HANDLER *&sh, + const ACE_PEER_CONNECTOR_ADDR &remote_addr, + ACE_Time_Value *timeout, + const ACE_PEER_CONNECTOR_ADDR &local_addr, + bool reuse_addr, + int flags, + int perms) +{ + // Actively establish the connection. This is a timed blocking + // connect. + if (this->new_connection (sh, + remote_addr, + timeout, + local_addr, + reuse_addr, + flags, + perms) == -1) + { + // If connect() failed because of timeouts, we have to reject + // the connection entirely. This is necessary since currently + // there is no way for the non-blocking connects to complete and + // for the to notify the cache of the completion of + // connect(). + + if (errno == EWOULDBLOCK || errno == ETIMEDOUT) + errno = ENOTSUP; + else if (ACE::out_of_handles (errno) || errno == EADDRINUSE) + { + // If the connect failed due to the process running out of + // file descriptors then, auto_purging of some connections + // are done from the CONNECTION_CACHE. This frees the + // descriptors which get used in the connect process and + // hence the same method is called again! + if (this->purge_connections () == -1) + return -1; + + // Try connecting again. + if (this->new_connection (sh, + remote_addr, + timeout, + local_addr, + reuse_addr, + flags, + perms) == -1) + { + if (errno == EWOULDBLOCK || errno == ETIMEDOUT) + errno = ENOTSUP; + return -1; + } + } + else + { + return -1; + } + } + + return 0; + +} + + +template int +ACE_Cached_Connect_Strategy_Ex::connect_svc_handler_i +(SVC_HANDLER *&sh, + const ACE_PEER_CONNECTOR_ADDR &remote_addr, + ACE_Time_Value *timeout, + const ACE_PEER_CONNECTOR_ADDR &local_addr, + bool reuse_addr, + int flags, + int perms, + int& found) +{ + CONNECTION_CACHE_ENTRY *entry = 0; + + // Check if the user passed a hint svc_handler + if (sh != 0) + { + int result = this->check_hint_i (sh, + remote_addr, + timeout, + local_addr, + reuse_addr, + flags, + perms, + entry, + found); + if (result != 0) + return result; + } + + // If not found + if (!found) + { + int result = this->find_or_create_svc_handler_i (sh, + remote_addr, + timeout, + local_addr, + reuse_addr, + flags, + perms, + entry, + found); + + if (result != 0) + return result; + + // Increment the refcount + entry->ext_id_.increment (); + } + + // For all successful cases: mark the in the cache + // as being . Therefore recyclable is BUSY. + entry->ext_id_.recycle_state (ACE_RECYCLABLE_BUSY); + + return 0; +} + + +template int +ACE_Cached_Connect_Strategy_Ex::cache_i (const void *recycling_act) +{ + // The wonders and perils of ACT + CONNECTION_CACHE_ENTRY *entry = (CONNECTION_CACHE_ENTRY *) recycling_act; + + // Mark the in the cache as not being . + // Therefore recyclable is IDLE. + entry->ext_id_.recycle_state (ACE_RECYCLABLE_IDLE_AND_PURGABLE); + + return 0; +} + +template int +ACE_Cached_Connect_Strategy_Ex::recycle_state_i (const void *recycling_act, + ACE_Recyclable_State new_state) +{ + // The wonders and perils of ACT + CONNECTION_CACHE_ENTRY *entry = (CONNECTION_CACHE_ENTRY *) recycling_act; + + // Mark the in the cache as not being . + // Therefore recyclable is IDLE. + entry->ext_id_.recycle_state (new_state); + + return 0; +} + +template ACE_Recyclable_State +ACE_Cached_Connect_Strategy_Ex::recycle_state_i (const void *recycling_act) const +{ + // The wonders and perils of ACT + CONNECTION_CACHE_ENTRY *entry = (CONNECTION_CACHE_ENTRY *) recycling_act; + + // Mark the in the cache as not being . + // Therefore recyclable is IDLE. + return entry->ext_id_.recycle_state (); +} + +template int +ACE_Cached_Connect_Strategy_Ex::purge_i (const void *recycling_act) +{ + // The wonders and perils of ACT + CONNECTION_CACHE_ENTRY *entry = (CONNECTION_CACHE_ENTRY *) recycling_act; + + return this->connection_cache_.unbind (entry); +} + + +template int +ACE_Cached_Connect_Strategy_Ex::mark_as_closed_i (const void *recycling_act) +{ + // The wonders and perils of ACT + CONNECTION_CACHE_ENTRY *entry = (CONNECTION_CACHE_ENTRY *) recycling_act; + + // Mark the in the cache as CLOSED. + entry->ext_id_.recycle_state (ACE_RECYCLABLE_CLOSED); + + return 0; +} + +template int +ACE_Cached_Connect_Strategy_Ex::cleanup_hint_i (const void *recycling_act, + void **act_holder) +{ + // Reset the <*act_holder> in the confines and protection of the + // lock. + if (act_holder) + *act_holder = 0; + + // The wonders and perils of ACT + CONNECTION_CACHE_ENTRY *entry = (CONNECTION_CACHE_ENTRY *) recycling_act; + + // Decrement the refcount on the . + int refcount = entry->ext_id_.decrement (); + + // If the svc_handler state is closed and the refcount == 0, call + // close() on svc_handler. + if (entry->ext_id_.recycle_state () == ACE_RECYCLABLE_CLOSED && + refcount == 0) + { + entry->int_id_.first ()->recycler (0, 0); + entry->int_id_.first ()->close (); + this->purge_i (entry); + } + + return 0; +} + +template int +ACE_Cached_Connect_Strategy_Ex::purge_connections (void) +{ + return this->connection_cache_.purge (); +} + +template CACHING_STRATEGY & +ACE_Cached_Connect_Strategy_Ex::caching_strategy (void) +{ + return this->connection_cache_.caching_strategy (); +} + +template int +ACE_Cached_Connect_Strategy_Ex::find (ACE_Refcounted_Hash_Recyclable &search_addr, + ACE_Hash_Map_Entry, ACE_Pair > *&entry) +{ + typedef ACE_Hash_Map_Bucket_Iterator, + ACE_Hash, + ACE_Equal_To, + ACE_Null_Mutex> + CONNECTION_CACHE_BUCKET_ITERATOR; + + CONNECTION_CACHE_BUCKET_ITERATOR iterator (this->connection_cache_.map (), + search_addr); + + CONNECTION_CACHE_BUCKET_ITERATOR end (this->connection_cache_.map (), + search_addr, + 1); + + for (; + iterator != end; + ++iterator) + { + REFCOUNTED_HASH_RECYCLABLE_ADDRESS &addr = (*iterator).ext_id_; + + if (addr.recycle_state () != ACE_RECYCLABLE_IDLE_AND_PURGABLE && + addr.recycle_state () != ACE_RECYCLABLE_IDLE_BUT_NOT_PURGABLE) + continue; + + if (addr.subject () != search_addr.subject ()) + continue; + + entry = &(*iterator); + + // + // Update the caching attributes directly since we don't do a + // find() on the cache map. + // + + // Indicates successful find. + int find_result = 0; + + int result = this->caching_strategy ().notify_find (find_result, + entry->int_id_.second ()); + + if (result == -1) + return result; + + return 0; + } + + return -1; +} + +template void +ACE_Cached_Connect_Strategy_Ex::cleanup (void) +{ + // Excluded other threads from changing the cache while we cleanup + ACE_GUARD (MUTEX, ace_mon, *this->lock_); + + // Close down all cached service handlers. + typename CONNECTION_CACHE::ITERATOR iter = this->connection_cache_.begin (); + while (iter != this->connection_cache_.end ()) + { + if ((*iter).second () != 0) + { + // save entry for future use + CONNECTION_CACHE_ENTRY *entry = (CONNECTION_CACHE_ENTRY *) + (*iter).second ()->recycling_act (); + + // close handler + (*iter).second ()->recycler (0, 0); + (*iter).second ()->close (); + + // remember next iter + typename CONNECTION_CACHE::ITERATOR next_iter = iter; + ++next_iter; + + // purge the item from the hash + this->purge_i (entry); + + // assign next iter + iter = next_iter; + } + else + ++iter; + } +} + +ACE_ALLOC_HOOK_DEFINE(ACE_Cached_Connect_Strategy_Ex) +///////////////////////////////////////////////////////////////////////// + +template +ACE_Bounded_Cached_Connect_Strategy::ACE_Bounded_Cached_Connect_Strategy +(size_t max_size, + CACHING_STRATEGY &caching_s, + ACE_Creation_Strategy *cre_s, + ACE_Concurrency_Strategy *con_s, + ACE_Recycling_Strategy *rec_s, + MUTEX *lock, + int delete_lock) + : CCSEBASE (caching_s, cre_s, con_s, rec_s, lock, delete_lock), + max_size_ (max_size) +{ +} + +template +ACE_Bounded_Cached_Connect_Strategy::~ACE_Bounded_Cached_Connect_Strategy(void) +{ +} + +template +int +ACE_Bounded_Cached_Connect_Strategy::find_or_create_svc_handler_i +(SVC_HANDLER *&sh, + const ACE_PEER_CONNECTOR_ADDR &remote_addr, + ACE_Time_Value *timeout, + const ACE_PEER_CONNECTOR_ADDR &local_addr, + bool reuse_addr, + int flags, + int perms, + ACE_Hash_Map_Entry, + ACE_Pair > *&entry, + int &found) +{ + + REFCOUNTED_HASH_RECYCLABLE_ADDRESS search_addr (remote_addr); + + // Try to find the address in the cache. Only if we don't find it + // do we create a new and connect it with the server. + while (this->find (search_addr, entry) != -1) + { + // We found a cached svc_handler. + // Get the cached + sh = entry->int_id_.first (); + + // Is the connection clean? + int state_result= ACE::handle_ready (sh->peer ().get_handle (), + &ACE_Time_Value::zero, + 1, // read ready + 0, // write ready + 1);// exception ready + + if (state_result == 1) + { + // The connection was disconnected during idle. + // close the svc_handler down. + if (sh->close () == -1) + { + ACE_ASSERT (0); + return -1; + } + sh = 0; + // and rotate once more... + } + else if ((state_result == -1) && (errno == ETIME)) + { + // Found!!! + // Set the flag + found = 1; + + // Tell the that it should prepare itself for + // being recycled. + if (this->prepare_for_recycling (sh) == -1) + { + ACE_ASSERT (0); + return -1; + } + + return 0; + } + else // some other return value or error... + { + ACE_ASSERT (0); // just to see it coming + + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("(%t)ACE_Bounded_Cached_Connect_Strategy<>::") + ACE_TEXT ("find_or_create_svc_handler_i - ") + ACE_TEXT ("error polling server socket state.\n"))); + + return -1; + } + } + + // Not found... + + // Set the flag + found = 0; + + // Check the limit of handlers... + if ((this->max_size_ > 0) && + (this->connection_cache_.current_size () >= this->max_size_)) + { + // Try to purge idle connections + if (this->purge_connections () == -1) + return -1; + + // Check limit again. + if (this->connection_cache_.current_size () >= this->max_size_) + // still too much! + return -1; + + // OK, we have room now... + } + + // We need to use a temporary variable here since we are not + // allowed to change because other threads may use this + // when we let go of the lock during the OS level connect. + // + // Note that making a new svc_handler, connecting remotely, + // binding to the map, and assigning of the hint and recycler + // should be atomic to the outside world. + SVC_HANDLER *potential_handler = 0; + + // Create a new svc_handler + if (this->make_svc_handler (potential_handler) == -1) + return -1; + + // Connect using the svc_handler. + if (this->cached_connect (potential_handler, + remote_addr, + timeout, + local_addr, + reuse_addr, + flags, + perms) == -1) + { + // Close the svc handler. + potential_handler->close (0); + return -1; + } + else + { + // Insert the new SVC_HANDLER instance into the cache. + if (this->connection_cache_.bind (search_addr, + potential_handler, + entry) == -1) + { + // Close the svc handler and reset . + potential_handler->close (0); + + return -1; + } + + // Everything succeeded as planned. Assign to + // . + sh = potential_handler; + + // Set the recycler and the recycling act + this->assign_recycler (sh, this, entry); + } + + return 0; +} + +ACE_ALLOC_HOOK_DEFINE(ACE_Bounded_Cached_Connect_Strategy) + +ACE_END_VERSIONED_NAMESPACE_DECL + +#undef ACE_T1 +#undef ACE_T2 + +#endif /* ACE_CACHED_CONNECT_STRATEGY_T_CPP */ diff --git a/dep/acelite/ace/Cached_Connect_Strategy_T.h b/dep/acelite/ace/Cached_Connect_Strategy_T.h new file mode 100644 index 00000000000..e95218f60fc --- /dev/null +++ b/dep/acelite/ace/Cached_Connect_Strategy_T.h @@ -0,0 +1,263 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Cached_Connect_Strategy_T.h + * + * $Id: Cached_Connect_Strategy_T.h 91077 2010-07-13 14:33:08Z johnnyw $ + * + * @author Kirthika Parameswaran + */ +//============================================================================= + +#ifndef CACHED_CONNECT_STRATEGY_T_H +#define CACHED_CONNECT_STRATEGY_T_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Strategies_T.h" +#include "ace/Hash_Cache_Map_Manager_T.h" +#include "ace/Caching_Strategies_T.h" +#include "ace/Functor_T.h" +#include "ace/Pair_T.h" + +// For linkers which cant grok long names... +#define ACE_Cached_Connect_Strategy_Ex ACCSE + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Cached_Connect_Strategy_Ex + * + * @brief A connection strategy which caches connections to peers + * (represented by SVC_HANDLER instances), thereby allowing + * subsequent re-use of unused, but available, connections. + * + * is intended to be used as a + * plug-in connection strategy for ACE_Strategy_Connector. + * It's added value is re-use of established connections and + * tweaking the role of the cache as per the caching strategy. + */ +template +class ACE_Cached_Connect_Strategy_Ex + : public ACE_Cached_Connect_Strategy +{ +public: + /// Constructor + ACE_Cached_Connect_Strategy_Ex ( + CACHING_STRATEGY &caching_s, + ACE_Creation_Strategy *cre_s = 0, + ACE_Concurrency_Strategy *con_s = 0, + ACE_Recycling_Strategy *rec_s = 0, + MUTEX *lock = 0, + int delete_lock = 0); + + /// Destructor + virtual ~ACE_Cached_Connect_Strategy_Ex (void); + + /// Explicit purging of connection entries from the connection cache. + virtual int purge_connections (void); + + /// Mark as closed (non-locking version). This is used during the cleanup of the + /// connections purged. + virtual int mark_as_closed_i (const void *recycling_act); + + /** + * Since g++ version < 2.8 arent happy with templates, this special + * method had to be devised to avoid memory leaks and perform + * cleanup of the . + */ + void cleanup (void); + + // = Typedefs for managing the map + typedef ACE_Refcounted_Hash_Recyclable + REFCOUNTED_HASH_RECYCLABLE_ADDRESS; + typedef ACE_Hash_Cache_Map_Manager, + ACE_Equal_To, + CACHING_STRATEGY, + ATTRIBUTES> + CONNECTION_CACHE; + typedef typename CONNECTION_CACHE::CACHE_ENTRY CONNECTION_CACHE_ENTRY; + typedef typename CONNECTION_CACHE::key_type KEY; + typedef typename CONNECTION_CACHE::mapped_type VALUE; + + typedef ACE_Recyclable_Handler_Cleanup_Strategy, + ACE_Hash_Map_Manager_Ex, + ACE_Hash, + ACE_Equal_To, + MUTEX> > + CLEANUP_STRATEGY; + + typedef ACE_Cached_Connect_Strategy + CCSBASE; + + // = Accessor. + CACHING_STRATEGY &caching_strategy (void); + +protected: + + /// Find an idle handle. + int find (ACE_Refcounted_Hash_Recyclable &search_addr, + ACE_Hash_Map_Entry, ACE_Pair > *&entry); + + /// Remove from cache (non-locking version). + virtual int purge_i (const void *recycling_act); + + /// Add to cache (non-locking version). + virtual int cache_i (const void *recycling_act); + + /// Get/Set recycle_state (non-locking version). + virtual int recycle_state_i (const void *recycling_act, + ACE_Recyclable_State new_state); + virtual ACE_Recyclable_State recycle_state_i (const void *recycling_act) const; + + /// Cleanup hint and reset @c *act_holder to zero if @a act_holder != 0. + virtual int cleanup_hint_i (const void *recycling_act, + void **act_holder); + + // = Helpers + int check_hint_i (SVC_HANDLER *&sh, + const ACE_PEER_CONNECTOR_ADDR &remote_addr, + ACE_Time_Value *timeout, + const ACE_PEER_CONNECTOR_ADDR &local_addr, + bool reuse_addr, + int flags, + int perms, + ACE_Hash_Map_Entry, ACE_Pair > *&entry, + int &found); + + virtual int find_or_create_svc_handler_i (SVC_HANDLER *&sh, + const ACE_PEER_CONNECTOR_ADDR &remote_addr, + ACE_Time_Value *timeout, + const ACE_PEER_CONNECTOR_ADDR &local_addr, + bool reuse_addr, + int flags, + int perms, + ACE_Hash_Map_Entry, ACE_Pair > *&entry, + int &found); + + virtual int connect_svc_handler_i (SVC_HANDLER *&sh, + const ACE_PEER_CONNECTOR_ADDR &remote_addr, + ACE_Time_Value *timeout, + const ACE_PEER_CONNECTOR_ADDR &local_addr, + bool reuse_addr, + int flags, + int perms, + int &found); + + /** + * Connection of the svc_handler with the remote host. This method + * also encapsulates the connection done with auto_purging under the + * hood. If the connect failed due to the process running out of + * file descriptors then, auto_purging of some connections are done + * from the CONNECTION_CACHE. This frees the descriptors which get + * used in the connect process and hence the connect operation can + * succeed. + */ + virtual int cached_connect (SVC_HANDLER *&sh, + const ACE_PEER_CONNECTOR_ADDR &remote_addr, + ACE_Time_Value *timeout, + const ACE_PEER_CONNECTOR_ADDR &local_addr, + bool reuse_addr, + int flags, + int perms); + + /// Table that maintains the cache of connected SVC_HANDLERs. + CONNECTION_CACHE connection_cache_; +}; + +///////////////////////////////////////////////////////////////////////////// + +// For linkers which cant grok long names... +#define ACE_Bounded_Cached_Connect_Strategy ABCCS + +/** + * @class ACE_Bounded_Cached_Connect_Strategy + * + * @brief + * A connection strategy which caches connections to peers + * (represented by SVC_HANDLER instances), thereby allowing + * subsequent re-use of unused, but available, connections. + * This strategy should be used when the cache is bounded by + * maximum size. + * + * Bounded_Cached_Connect_Strategy is intended to be used as a + * plug-in connection strategy for ACE_Strategy_Connector. + * It's added value is re-use of established connections and + * tweaking the role of the cache as per the caching strategy. + * Thanks to Edan Ayal for contributing this + * class and Susan Liebeskind for + * brainstorming about it. + */ +template +class ACE_Bounded_Cached_Connect_Strategy + : public ACE_Cached_Connect_Strategy_Ex +{ + + typedef ACE_Cached_Connect_Strategy_Ex + CCSEBASE; + + // = Typedefs for managing the map + typedef ACE_Refcounted_Hash_Recyclable + REFCOUNTED_HASH_RECYCLABLE_ADDRESS; + +public: + + /// Constructor + ACE_Bounded_Cached_Connect_Strategy (size_t max_size, + CACHING_STRATEGY &caching_s, + ACE_Creation_Strategy *cre_s = 0, + ACE_Concurrency_Strategy *con_s = 0, + ACE_Recycling_Strategy *rec_s = 0, + MUTEX *lock = 0, + int delete_lock = 0); + + /// Destructor + virtual ~ACE_Bounded_Cached_Connect_Strategy (void); + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + + virtual int find_or_create_svc_handler_i (SVC_HANDLER *&sh, + const ACE_PEER_CONNECTOR_ADDR &remote_addr, + ACE_Time_Value *timeout, + const ACE_PEER_CONNECTOR_ADDR &local_addr, + bool reuse_addr, + int flags, + int perms, + ACE_Hash_Map_Entry, + ACE_Pair > *&entry, + int &found); + +protected: + + /// Max items in the cache, used as a bound for the creation of svc_handlers. + size_t max_size_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Cached_Connect_Strategy_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Cached_Connect_Strategy_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" +#endif /* CACHED_CONNECT_STRATEGY_T_H */ diff --git a/dep/acelite/ace/Caching_Strategies_T.cpp b/dep/acelite/ace/Caching_Strategies_T.cpp new file mode 100644 index 00000000000..2b0fd4e764a --- /dev/null +++ b/dep/acelite/ace/Caching_Strategies_T.cpp @@ -0,0 +1,59 @@ +//$Id: Caching_Strategies_T.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#ifndef ACE_CACHING_STRATEGIES_T_CPP +#define ACECACHING_STRATEGIES_T_CPP + +#include "ace/Caching_Strategies_T.h" +#include "ace/Log_Msg.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Caching_Strategies_T.inl" +#endif /* __ACE_INLINE__ */ + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +#pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template +ACE_Caching_Strategy::~ACE_Caching_Strategy (void) +{ +} + +////////////////////////////////////////////////////////////////////////////////// + +template +ACE_LRU_Caching_Strategy::ACE_LRU_Caching_Strategy (void) + : timer_ (0), + purge_percent_ (10) +{ +} + +//////////////////////////////////////////////////////////////////////////////////////////////// + +template +ACE_LFU_Caching_Strategy::ACE_LFU_Caching_Strategy (void) + : purge_percent_ (10) +{ +} + +//////////////////////////////////////////////////////////////////////////////////////////////// + +template +ACE_FIFO_Caching_Strategy::ACE_FIFO_Caching_Strategy (void) + : order_ (0), + purge_percent_ (10) +{ +} + +//////////////////////////////////////////////////////////////////////////////////////////////// + +ACE_ALLOC_HOOK_DEFINE(ACE_LRU_Caching_Strategy) +ACE_ALLOC_HOOK_DEFINE(ACE_LFU_Caching_Strategy) +ACE_ALLOC_HOOK_DEFINE(ACE_FIFO_Caching_Strategy) +ACE_ALLOC_HOOK_DEFINE(ACE_Null_Caching_Strategy) + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_CACHING_STRATEGIES_T_CPP */ diff --git a/dep/acelite/ace/Caching_Strategies_T.h b/dep/acelite/ace/Caching_Strategies_T.h new file mode 100644 index 00000000000..e4b0817aa26 --- /dev/null +++ b/dep/acelite/ace/Caching_Strategies_T.h @@ -0,0 +1,552 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Caching_Strategies_T.h + * + * $Id: Caching_Strategies_T.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Kirthika Parameswaran + */ +//============================================================================= + +#ifndef ACE_CACHING_STRATEGIES_H +#define ACE_CACHING_STRATEGIES_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" +#include "ace/Caching_Utility_T.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined(_MSC_VER) +#pragma warning(disable:4503) +#endif /* _MSC_VER */ + +// For linkers that cant grok long names. +#define ACE_Caching_Strategy ACS + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Caching_Strategy + * + * @brief This class is an abstract base class for a caching strategy. + * + * This class consists of all the interfaces a caching strategy should + * have and is used in association with the + * ACE_Caching_Strategy_Adaptor. + */ +template +class ACE_Caching_Strategy +{ +public: + /// Destructor. + virtual ~ACE_Caching_Strategy (void); + + /// Accessor method for the timer attributes. + virtual ATTRIBUTES attributes (void) = 0; + + /// Get the percentage of entries to purge. + virtual double purge_percent (void) = 0; + + /// Set the percentage of entries to purge. + virtual void purge_percent (double percentage) = 0; + + // = Strategy related Operations + + /// This method acts as a notification about the CONTAINERs bind + /// method call. + virtual int notify_bind (int result, + const ATTRIBUTES &attr) = 0; + + /// This method acts as a notification about the CONTAINERs find + /// method call + virtual int notify_find (int result, + ATTRIBUTES &attr) = 0; + + /// This method acts as a notification about the CONTAINERs unbind + /// method call + virtual int notify_unbind (int result, + const ATTRIBUTES &attr) = 0; + + /// This method acts as a notification about the CONTAINERs trybind + /// method call + virtual int notify_trybind (int result, + ATTRIBUTES &attr) = 0; + + /// This method acts as a notification about the CONTAINERs rebind + /// method call + virtual int notify_rebind (int result, + const ATTRIBUTES &attr) = 0; + + /// Purge the cache. + virtual CACHING_UTILITY &caching_utility (void) = 0; + + /// Dumps the state of the object. + virtual void dump (void) const = 0; +}; + +////////////////////////////////////////////////////////////////////////// + +#define ACE_Caching_Strategy_Adapter ACSA + +/** + * @class ACE_Caching_Strategy_Adapter + * + * @brief This class follows the Adaptor pattern and is used to provide + * External Polymorphism by deriving from ACE_Caching_Strategy. + * + * This class simply delegates all requests to the + * IMPLEMNETATION object within. This class should be passed in + * place of the the abstract base ACE_Caching_Strategy class as + * part of the External Polymorphism pattern. + */ +template +class ACE_Caching_Strategy_Adapter + : public ACE_Caching_Strategy +{ + +public: + + /// Constructor. + ACE_Caching_Strategy_Adapter (IMPLEMENTATION *implementation = 0, + bool delete_implementation = false); + + /// Destructor. + ~ACE_Caching_Strategy_Adapter (void); + + /// Accessor method for the timer attributes. + ATTRIBUTES attributes (void); + + /// Get the percentage of entries to purge. + double purge_percent (void); + + /// Set the percentage of entries to purge. + void purge_percent (double percentage); + + // = Strategy related Operations + + /// This method acts as a notification about the CONTAINERs bind + /// method call. + int notify_bind (int result, + const ATTRIBUTES &attr); + + /// This method acts as a notification about the CONTAINERs find + /// method call + int notify_find (int result, + ATTRIBUTES &attr); + + /// This method acts as a notification about the CONTAINERs unbind + /// method call + int notify_unbind (int result, + const ATTRIBUTES &attr); + + /// This method acts as a notification about the CONTAINERs trybind + /// method call + int notify_trybind (int result, + ATTRIBUTES &attr); + + /// This method acts as a notification about the CONTAINERs rebind + /// method call + int notify_rebind (int result, + const ATTRIBUTES &attr); + + /// Accessor to the implementation. + IMPLEMENTATION &implementation (void); + + /// Purge the cache. + CACHING_UTILITY &caching_utility (void); + + /// Dumps the state of the object. + void dump (void) const; + +private: + + /// Implementation class. + IMPLEMENTATION *implementation_; + + /// Do we need to delete the implementation? + bool delete_implementation_; +}; + +////////////////////////////////////////////////////////////////////////// +#define ACE_LRU_Caching_Strategy ALRU + +/** + * @class ACE_LRU_Caching_Strategy + * + * @brief Defines a Least Recently Used strategy which will decide on + * the item to be removed from the cache. + * + * This is a strategy which makes use of a virtual timer which + * is updated whenever an item is inserted or looked up in the + * container. When the need of purging entries arises, the items + * with the lowest timer values are removed. + * Explanation of the template parameter list: + * CONTAINER is any map with entries of type . + * The ATTRIBUTES are the deciding factor for purging of entries + * and should logically be included with the VALUE. Some ways of + * doing this are: As being a member of the VALUE or VALUE being + * ACE_Pair. The CACHING_UTILITY is the + * class which can be plugged in and which decides the entries + * to purge. + */ +template +class ACE_LRU_Caching_Strategy +{ +public: + + // Traits. + typedef ATTRIBUTES CACHING_ATTRIBUTES; + + // = Initialisation and termination. + + /** + * The is the map in which the entries reside. The + * timer attribute is initialed to zero in this constructor. And + * the field denotes the percentage of the entries + * in the cache which can be purged automagically and by default is + * set to 10%. + */ + ACE_LRU_Caching_Strategy (void); + + // = Operations of the strategy. + + /// Accessor method for the timer attributes. + ATTRIBUTES attributes (void); + + /// Get the percentage of entries to purge. + double purge_percent (void); + + /// Set the percentage of entries to purge. + void purge_percent (double percentage); + + // = Strategy related Operations + + /// This method acts as a notification about the CONTAINERs bind + /// method call. + int notify_bind (int result, + const ATTRIBUTES &attr); + + /// This method acts as a notification about the CONTAINERs find + /// method call + int notify_find (int result, + ATTRIBUTES &attr); + + /// This method acts as a notification about the CONTAINERs unbind + /// method call + int notify_unbind (int result, + const ATTRIBUTES &attr); + + + /// This method acts as a notification about the CONTAINERs trybind + /// method call + int notify_trybind (int result, + ATTRIBUTES &attr); + + /// This method acts as a notification about the CONTAINERs rebind + /// method call + int notify_rebind (int result, + const ATTRIBUTES &attr); + + /// Purge the cache. + CACHING_UTILITY &caching_utility (void); + + /// Dumps the state of the object. + void dump (void) const; + +private: + + /// This element is the one which is the deciding factor for purging + /// of an ITEM. + ATTRIBUTES timer_; + + /// The level about which the purging will happen automagically. + double purge_percent_; + + /// This is the helper class which will decide and expunge entries + /// from the cache. + CACHING_UTILITY caching_utility_; +}; + +////////////////////////////////////////////////////////////////////////// +#define ACE_LFU_Caching_Strategy ALFU + +/** + * @class ACE_LFU_Caching_Strategy + * + * @brief Defines a Least Frequently Used strategy for which will decide on + * the item to be removed from the cache. + * + * A attribute is tagged to each item which increments whenever + * the item is bound or looked up in the cache. Thus it denotes + * the frequency of use. According to the value of the attribute + * the item is removed from the CONTAINER i.e cache. + * Explanation of the template parameter list: + * CONTAINER is any map with entries of type . + * The ATTRIBUTES are the deciding factor for purging of entries + * and should logically be included with the VALUE. Some ways of + * doing this are: As being a member of the VALUE or VALUE being + * ACE_Pair. The CACHING_UTILITY is the + * class which can be plugged in and which decides the entries + * to purge. + */ +template +class ACE_LFU_Caching_Strategy +{ + +public: + + // Traits. + typedef ATTRIBUTES CACHING_ATTRIBUTES; + + // = Initialisation and termination methods. + + /** + * The is the map in which the entries reside. The + * timer attribute is initialed to zero in this constructor. And + * the field denotes the percentage of the entries + * in the cache which can be purged automagically and by default is + * set to 10%. + */ + ACE_LFU_Caching_Strategy (void); + + // = Strategy methods. + + /// Access the attributes. + ATTRIBUTES attributes (void); + + /// Get the percentage of entries to purge. + double purge_percent (void); + + /// Set the percentage of entries to purge. + void purge_percent (double percentage); + + // = Strategy related Operations + + /// This method acts as a notification about the CONTAINERs bind + /// method call. + int notify_bind (int result, + const ATTRIBUTES &attr); + + /// Lookup notification. + int notify_find (int result, + ATTRIBUTES &attr); + + /// This method acts as a notification about the CONTAINERs unbind + /// method call + int notify_unbind (int result, + const ATTRIBUTES &attr); + + /// This method acts as a notification about the CONTAINERs trybind + /// method call + int notify_trybind (int result, + ATTRIBUTES &attr); + + /// This method acts as a notification about the CONTAINERs rebind + /// method call + int notify_rebind (int result, + const ATTRIBUTES &attr); + + /// Purge the cache. + CACHING_UTILITY &caching_utility (void); + + /// Dumps the state of the object. + void dump (void) const; + +private: + + /// The level about which the purging will happen automagically. + double purge_percent_; + + /// This is the helper class which will decide and expunge entries + /// from the cache. + CACHING_UTILITY caching_utility_; +}; + +///////////////////////////////////////////////////////////// +#define ACE_FIFO_Caching_Strategy AFIFO + +/** + * @class ACE_FIFO_Caching_Strategy + * + * @brief The First In First Out strategy is implemented wherein each + * item is ordered. + * + * The order tag of each item is used to decide the item to be + * removed from the cache. The items with least order are removed. + * Explanation of the template parameter list: + * CONTAINER is any map with entries of type . + * The ATTRIBUTES are the deciding factor for purging of entries + * and should logically be included with the VALUE. Some ways of + * doing this are: As being a member of the VALUE or VALUE being + * ACE_Pair. The CACHING_UTILITY is the + * class which can be plugged in and which decides the entries + * to purge. + */ +template +class ACE_FIFO_Caching_Strategy +{ + +public: + + typedef ATTRIBUTES CACHING_ATTRIBUTES; + + // = Initialisation and termination. + + /** + * The is the map in which the entries reside. The + * timer attribute is initialed to zero in this constructor. And + * the field denotes the percentage of the entries + * in the cache which can be purged automagically and by default is + * set to 10%. + */ + ACE_FIFO_Caching_Strategy (void); + + // = Strategy methods. + + /// Accessor method. + ATTRIBUTES attributes (void); + + /// Get the percentage of entries to purge. + double purge_percent (void); + + /// Set the percentage of entries to purge. + void purge_percent (double percentage); + + // = Strategy related Operations + + /// Notification for an item getting bound into the cache. + int notify_bind (int result, + const ATTRIBUTES &attr); + + /// This method acts as a notification about the CONTAINERs find + /// method call + int notify_find (int result, + ATTRIBUTES &attr); + + /// This method acts as a notification about the CONTAINERs unbind + /// method call + int notify_unbind (int result, + const ATTRIBUTES &attr); + + /// This method acts as a notification about the CONTAINERs trybind + /// method call + int notify_trybind (int result, + ATTRIBUTES &attr); + + /// Notification for an item getting bound again into the cache. + int notify_rebind (int result, + const ATTRIBUTES &attr); + + /// Purge the cache. + CACHING_UTILITY &caching_utility (void); + + /// Dumps the state of the object. + void dump (void) const; + +private: + + /// The order is the deciding factor for the item to be removed from + /// the cache. + ATTRIBUTES order_; + + /// The level about which the purging will happen automagically. + double purge_percent_; + + /// This is the helper class which will decide and expunge entries + /// from the cache. + CACHING_UTILITY caching_utility_; +}; + +////////////////////////////////////////////////////////////////////// +#define ACE_Null_Caching_Strategy ANULL + +/** + * @class ACE_Null_Caching_Strategy + * + * @brief The is a special caching strategy which doesnt have the purging + * feature. + * + * No purging provided. To be used when purging might be too expensive + * an operation. + */ +template +class ACE_Null_Caching_Strategy +{ + +public: + + // = Traits. + typedef ATTRIBUTES CACHING_ATTRIBUTES; + + // = Strategy methods. All are NO_OP methods!!! + + /// Accessor method. + ATTRIBUTES attributes (void); + + /// Get the percentage of entries to purge. + double purge_percent (void); + + /// Set the percentage of entries to purge. + void purge_percent (double percentage); + + // = Strategy related Operations + + /// Notification for an item getting bound into the cache. + int notify_bind (int result, + const ATTRIBUTES &attr); + + /// This method acts as a notification about the CONTAINERs find + /// method call + int notify_find (int result, + ATTRIBUTES &attr); + + /// This method acts as a notification about the CONTAINERs unbind + /// method call + int notify_unbind (int result, + const ATTRIBUTES &attr); + + /// This method acts as a notification about the CONTAINERs trybind + /// method call + int notify_trybind (int result, + ATTRIBUTES &attr); + + /// Notification for an item getting bound again into the cache. + int notify_rebind (int result, + const ATTRIBUTES &attr); + + /// Purge the cache. + CACHING_UTILITY &caching_utility (void); + + /// Dumps the state of the object. + void dump (void) const; + +private: + + /// This is the helper class which will decide and expunge entries + /// from the cache. + CACHING_UTILITY caching_utility_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Caching_Strategies_T.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Caching_Strategies_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Caching_Strategies_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" + +#endif /* ACE_CACHING_STRATEGIES_H */ diff --git a/dep/acelite/ace/Caching_Strategies_T.inl b/dep/acelite/ace/Caching_Strategies_T.inl new file mode 100644 index 00000000000..41fa2d30301 --- /dev/null +++ b/dep/acelite/ace/Caching_Strategies_T.inl @@ -0,0 +1,456 @@ +// -*-C++-*- +// +//$Id: Caching_Strategies_T.inl 80826 2008-03-04 14:51:23Z wotte $ + +////////////////////////////////////////////////////////////////////////////////// + +#include "ace/OS_Memory.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template ACE_INLINE +ACE_Caching_Strategy_Adapter::ACE_Caching_Strategy_Adapter (IMPLEMENTATION *implementation, + bool delete_implementation) + : implementation_ (implementation), + delete_implementation_ (delete_implementation) +{ + if (this->implementation_ == 0) + { + ACE_NEW (this->implementation_, + IMPLEMENTATION); + this->delete_implementation_ = true; + } +} + +template ACE_INLINE +ACE_Caching_Strategy_Adapter::~ACE_Caching_Strategy_Adapter (void) +{ + if (this->delete_implementation_) + { + delete this->implementation_; + this->delete_implementation_ = false; + this->implementation_ = 0; + } +} + +template ACE_INLINE ATTRIBUTES +ACE_Caching_Strategy_Adapter::attributes (void) +{ + return this->implementation_->attributes (); +} + +template ACE_INLINE double +ACE_Caching_Strategy_Adapter::purge_percent (void) +{ + return this->implementation_->purge_percent (); +} + +template ACE_INLINE void +ACE_Caching_Strategy_Adapter::purge_percent (double percentage) +{ + this->implementation_->purge_percent (percentage); +} + +template ACE_INLINE int +ACE_Caching_Strategy_Adapter::notify_bind (int result, + const ATTRIBUTES &attr) +{ + return this->implementation_->notify_bind (result, + attr); +} + +template ACE_INLINE int +ACE_Caching_Strategy_Adapter::notify_find (int result, + ATTRIBUTES &attr) +{ + return this->implementation_->notify_find (result, + attr); +} + +template ACE_INLINE int +ACE_Caching_Strategy_Adapter::notify_unbind (int result, + const ATTRIBUTES &attr) +{ + return this->implementation_->notify_unbind (result, + attr); +} + +template ACE_INLINE int +ACE_Caching_Strategy_Adapter::notify_trybind (int result, + ATTRIBUTES &attr) +{ + return this->implementation_->notify_trybind (result, + attr); +} + +template ACE_INLINE int +ACE_Caching_Strategy_Adapter::notify_rebind (int result, + const ATTRIBUTES &attr) +{ + return this->implementation_->notify_rebind (result, + attr); +} + +template ACE_INLINE IMPLEMENTATION & +ACE_Caching_Strategy_Adapter::implementation (void) +{ + return *this->implementation_; +} + +template ACE_INLINE CACHING_UTILITY & +ACE_Caching_Strategy_Adapter::caching_utility (void) +{ + return this->implementation_->caching_utility (); +} + +template ACE_INLINE void +ACE_Caching_Strategy_Adapter::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Caching_Strategy_Adapter::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +////////////////////////////////////////////////////////////////////////////////// + +template ACE_INLINE ATTRIBUTES +ACE_LRU_Caching_Strategy::attributes (void) +{ + return this->timer_; +} + +template ACE_INLINE double +ACE_LRU_Caching_Strategy::purge_percent (void) +{ + return this->purge_percent_; +} + +template ACE_INLINE void +ACE_LRU_Caching_Strategy::purge_percent (double percentage) +{ + this->purge_percent_ = percentage; +} + +template ACE_INLINE int +ACE_LRU_Caching_Strategy::notify_bind ( + int result, + const ATTRIBUTES & /* attr */) +{ + if (result == 0) + ++this->timer_; + + return result; +} + +template ACE_INLINE int +ACE_LRU_Caching_Strategy::notify_find ( + int result, + ATTRIBUTES &attr) +{ + if (result == 0) + { + attr = this->timer_; + ++this->timer_; + } + + return result; +} + +template ACE_INLINE int +ACE_LRU_Caching_Strategy::notify_unbind ( + int result, + const ATTRIBUTES & /* attr */) +{ + return result; +} + +template ACE_INLINE int +ACE_LRU_Caching_Strategy::notify_trybind ( + int result, + ATTRIBUTES & /* attr */) +{ + return result; +} + +template ACE_INLINE int +ACE_LRU_Caching_Strategy::notify_rebind ( + int result, + const ATTRIBUTES & /* attr */) +{ + if (result == 0) + ++this->timer_; + + return result; +} + +template ACE_INLINE CACHING_UTILITY & +ACE_LRU_Caching_Strategy::caching_utility (void) +{ + return this->caching_utility_; +} + +template ACE_INLINE void +ACE_LRU_Caching_Strategy::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_LRU_Caching_Strategy::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("timer_ = %d "), this->timer_)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +////////////////////////////////////////////////////////////////////////////////// + +template ACE_INLINE ATTRIBUTES +ACE_LFU_Caching_Strategy::attributes (void) +{ + return 0; +} + +template ACE_INLINE double +ACE_LFU_Caching_Strategy::purge_percent (void) +{ + return this->purge_percent_; +} + +template ACE_INLINE void +ACE_LFU_Caching_Strategy::purge_percent (double percentage) +{ + this->purge_percent_ = percentage; +} + +template ACE_INLINE int +ACE_LFU_Caching_Strategy::notify_bind (int result, + const ATTRIBUTES & /* attr */) +{ + + return result; +} + +template ACE_INLINE int +ACE_LFU_Caching_Strategy::notify_find (int result, + ATTRIBUTES &attr) +{ + if (result == 0) + ++attr; + + return result; +} + +template ACE_INLINE int +ACE_LFU_Caching_Strategy::notify_trybind (int result, + ATTRIBUTES & /* attr */) +{ + return result; +} + +template ACE_INLINE int +ACE_LFU_Caching_Strategy::notify_rebind (int result, + const ATTRIBUTES & /* attr */) +{ + return result; +} + +template ACE_INLINE int +ACE_LFU_Caching_Strategy::notify_unbind (int result, + const ATTRIBUTES & /* attr */) +{ + return result; +} + +template ACE_INLINE CACHING_UTILITY & +ACE_LFU_Caching_Strategy::caching_utility (void) +{ + return this->caching_utility_; +} + +template ACE_INLINE void +ACE_LFU_Caching_Strategy::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_LFU_Caching_Strategy::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +////////////////////////////////////////////////////////////////////////////////////// + +template ACE_INLINE ATTRIBUTES +ACE_FIFO_Caching_Strategy::attributes (void) +{ + return this->order_; +} + +template ACE_INLINE double +ACE_FIFO_Caching_Strategy::purge_percent (void) +{ + return this->purge_percent_; +} + +template ACE_INLINE void +ACE_FIFO_Caching_Strategy::purge_percent (double percentage) +{ + this->purge_percent_ = percentage; +} + +template ACE_INLINE int +ACE_FIFO_Caching_Strategy::notify_bind (int result, + const ATTRIBUTES &attr) +{ + ACE_UNUSED_ARG (attr); + + if (result == 0) + ++this->order_; + + return result; +} + +template ACE_INLINE int +ACE_FIFO_Caching_Strategy::notify_find (int result, + ATTRIBUTES &attr) +{ + ACE_UNUSED_ARG (attr); + + return result; +} + +template ACE_INLINE int +ACE_FIFO_Caching_Strategy::notify_unbind (int result, + const ATTRIBUTES &attr) +{ + ACE_UNUSED_ARG (attr); + + return result; +} + +template ACE_INLINE int +ACE_FIFO_Caching_Strategy::notify_trybind (int result, + ATTRIBUTES &attr) +{ + ACE_UNUSED_ARG (attr); + + return result; +} + +template ACE_INLINE int +ACE_FIFO_Caching_Strategy::notify_rebind (int result, + const ATTRIBUTES &attr) +{ + ACE_UNUSED_ARG (attr); + + if (result == 0) + ++this->order_; + + return result; +} + +template ACE_INLINE CACHING_UTILITY & +ACE_FIFO_Caching_Strategy::caching_utility (void) +{ + return this->caching_utility_; +} + +template ACE_INLINE void +ACE_FIFO_Caching_Strategy::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_FIFO_Caching_Strategy::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("order_ = %d "), this->order_)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +////////////////////////////////////////////////////////////////////////////////// + +template ACE_INLINE ATTRIBUTES +ACE_Null_Caching_Strategy::attributes (void) +{ + return 0; +} + +template ACE_INLINE double +ACE_Null_Caching_Strategy::purge_percent (void) +{ + return 0; +} + +template ACE_INLINE void +ACE_Null_Caching_Strategy::purge_percent (double percentage) +{ + ACE_UNUSED_ARG (percentage); +} + +template ACE_INLINE int +ACE_Null_Caching_Strategy::notify_bind (int result, + const ATTRIBUTES &attr) +{ + ACE_UNUSED_ARG (attr); + + return result; +} + +template ACE_INLINE int +ACE_Null_Caching_Strategy::notify_find (int result, + ATTRIBUTES &attr) +{ + ACE_UNUSED_ARG (attr); + + return result; +} + +template ACE_INLINE int +ACE_Null_Caching_Strategy::notify_unbind (int result, + const ATTRIBUTES &attr) +{ + ACE_UNUSED_ARG (attr); + + return result; +} + +template ACE_INLINE int +ACE_Null_Caching_Strategy::notify_trybind (int result, + ATTRIBUTES &attr) +{ + ACE_UNUSED_ARG (attr); + + return result; +} + +template ACE_INLINE int +ACE_Null_Caching_Strategy::notify_rebind (int result, + const ATTRIBUTES &attr) +{ + ACE_UNUSED_ARG (attr); + + return result; +} + +template ACE_INLINE CACHING_UTILITY & +ACE_Null_Caching_Strategy::caching_utility (void) +{ + return this->caching_utility_; +} + +template ACE_INLINE void +ACE_Null_Caching_Strategy::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Null_Caching_Strategy::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +////////////////////////////////////////////////////////////////////////////////// diff --git a/dep/acelite/ace/Caching_Utility_T.cpp b/dep/acelite/ace/Caching_Utility_T.cpp new file mode 100644 index 00000000000..a03a4575891 --- /dev/null +++ b/dep/acelite/ace/Caching_Utility_T.cpp @@ -0,0 +1,499 @@ +// $Id: Caching_Utility_T.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#ifndef ACE_CACHING_UTILITY_T_CPP +#define ACE_CACHING_UTILITY_T_CPP + +#include "ace/Caching_Utility_T.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +#pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Min_Max.h" +#include "ace/OS_Memory.h" +#include "ace/Recyclable.h" + +////////////////////////////////////////////////////////////////////////////// + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template +ACE_Pair_Caching_Utility::ACE_Pair_Caching_Utility (ACE_Cleanup_Strategy *cleanup_strategy, + int delete_cleanup_strategy) + : cleanup_strategy_ (cleanup_strategy), + delete_cleanup_strategy_ (delete_cleanup_strategy) +{ + if (cleanup_strategy == 0) + { + ACE_NEW (this->cleanup_strategy_, + CLEANUP_STRATEGY); + this->delete_cleanup_strategy_ = 1; + } +} + +template +ACE_Pair_Caching_Utility::~ACE_Pair_Caching_Utility (void) +{ + if (this->delete_cleanup_strategy_) + delete this->cleanup_strategy_; +} + +template int +ACE_Pair_Caching_Utility::clear_cache (CONTAINER &container, + double purge_percent) +{ + // Check that the purge_percent is non-zero. + if (purge_percent == 0) + return 0; + + // Get the number of entries in the container. + size_t current_map_size = container.current_size (); + + // Also whether the number of entries in the cache! + // Oops! then there is no way out but exiting. So return an error. + if (current_map_size == 0) + return 0; + + // Calculate the no of entries to remove from the cache depending + // upon the . + size_t const entries_to_remove + = ACE_MAX (static_cast (1), + static_cast (static_cast (purge_percent) + / 100 * current_map_size)); + KEY *key_to_remove = 0; + VALUE *value_to_remove = 0; + + for (size_t i = 0; i < entries_to_remove ; ++i) + { + this->minimum (container, + key_to_remove, + value_to_remove); + + // Simply verifying that the key is non-zero. + // This is important for strategies where the minimum + // entry cant be found due to constraints on the type of entry + // to remove. + if (key_to_remove == 0) + return 0; + + if (this->cleanup_strategy_->cleanup (container, + key_to_remove, + value_to_remove) == -1) + return -1; + + } + + return 0; +} + +template void +ACE_Pair_Caching_Utility::minimum (CONTAINER &container, + KEY *&key_to_remove, + VALUE *&value_to_remove) +{ + // Starting values. + ITERATOR iter = container.begin (); + ITERATOR end = container.end (); + ATTRIBUTES min = (*iter).int_id_.second (); + key_to_remove = &(*iter).ext_id_; + value_to_remove = &(*iter).int_id_; + + // The iterator moves thru the container searching for the entry + // with the lowest ATTRIBUTES. + for (++iter; + iter != end; + ++iter) + { + if (min > (*iter).int_id_.second ()) + { + // Ah! an item with lower ATTTRIBUTES... + min = (*iter).int_id_.second (); + key_to_remove = &(*iter).ext_id_; + value_to_remove = &(*iter).int_id_; + } + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +template +ACE_Recyclable_Handler_Caching_Utility::ACE_Recyclable_Handler_Caching_Utility (ACE_Cleanup_Strategy *cleanup_strategy, + int delete_cleanup_strategy) + : cleanup_strategy_ (cleanup_strategy), + delete_cleanup_strategy_ (delete_cleanup_strategy) +{ + if (cleanup_strategy == 0) + { + ACE_NEW (this->cleanup_strategy_, + CLEANUP_STRATEGY); + this->delete_cleanup_strategy_ = 1; + } +} + +template +ACE_Recyclable_Handler_Caching_Utility::~ACE_Recyclable_Handler_Caching_Utility (void) +{ + if (this->delete_cleanup_strategy_) + delete this->cleanup_strategy_; +} + +template int +ACE_Recyclable_Handler_Caching_Utility::clear_cache (CONTAINER &container, + double purge_percent) +{ + // Check that the purge_percent is non-zero. + if (purge_percent == 0) + return 0; + + // Get the number of entries in the container. + size_t current_map_size = container.current_size (); + + // Also whether the number of entries in the cache is just one! + // Oops! then there is no way out but exiting. So return an error. + // if (current_map_size <= 1) + if (current_map_size == 0) + return 0; + + // Calculate the no of entries to remove from the cache depending + // upon the . + size_t const entries_to_remove + = ACE_MAX (static_cast (1), + static_cast (static_cast (purge_percent) + / 100 * current_map_size)); + + KEY *key_to_remove = 0; + VALUE *value_to_remove = 0; + + for (size_t i = 0; i < entries_to_remove ; ++i) + { + this->minimum (container, + key_to_remove, + value_to_remove); + + // Simply verifying that the key is non-zero. + // This is important for strategies where the minimum + // entry cant be found due to constraints on the type of entry + // to remove. + if (key_to_remove == 0) + return 0; + + if (this->cleanup_strategy_->cleanup (container, + key_to_remove, + value_to_remove) == -1) + return -1; + } + + return 0; +} + +template void +ACE_Recyclable_Handler_Caching_Utility::minimum (CONTAINER &container, + KEY *&key_to_remove, + VALUE *&value_to_remove) +{ + // Starting values. + ITERATOR end = container.end (); + ITERATOR iter = container.begin (); + ATTRIBUTES min = (*iter).int_id_.second (); + key_to_remove = 0; + value_to_remove = 0; + // Found the minimum entry to be purged? + int found = 0; + + // The iterator moves thru the container searching for the entry + // with the lowest ATTRIBUTES. + for (; + iter != end; + ++iter) + { + // If the entry isnt IDLE_AND_PURGABLE continue until you reach + // the first entry which can be purged. This is the minimum with + // which you will compare the rest of the purgable entries. + if ((*iter).ext_id_.recycle_state () == ACE_RECYCLABLE_IDLE_AND_PURGABLE || + (*iter).ext_id_.recycle_state () == ACE_RECYCLABLE_PURGABLE_BUT_NOT_IDLE) + { + if (found == 0) + { + min = (*iter).int_id_.second (); + key_to_remove = &(*iter).ext_id_; + value_to_remove = &(*iter).int_id_; + found = 1; + } + else + { + // Ah! an entry with lower ATTTRIBUTES... + if (min > (*iter).int_id_.second ()) + { + min = (*iter).int_id_.second (); + key_to_remove = &(*iter).ext_id_; + value_to_remove = &(*iter).int_id_; + } + } + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +template +ACE_Refcounted_Recyclable_Handler_Caching_Utility::ACE_Refcounted_Recyclable_Handler_Caching_Utility (ACE_Cleanup_Strategy *cleanup_strategy, + int delete_cleanup_strategy) + : cleanup_strategy_ (cleanup_strategy), + delete_cleanup_strategy_ (delete_cleanup_strategy), + marked_as_closed_entries_ (0) +{ + if (cleanup_strategy == 0) + { + ACE_NEW (this->cleanup_strategy_, + CLEANUP_STRATEGY); + this->delete_cleanup_strategy_ = 1; + } +} + +template +ACE_Refcounted_Recyclable_Handler_Caching_Utility::~ACE_Refcounted_Recyclable_Handler_Caching_Utility (void) +{ + if (this->delete_cleanup_strategy_) + delete this->cleanup_strategy_; +} + +template int +ACE_Refcounted_Recyclable_Handler_Caching_Utility::clear_cache (CONTAINER &container, + double purge_percent) +{ + // Check that the purge_percent is non-zero. + if (purge_percent == 0) + return 0; + + // Get the number of entries in the container which can be considered for purging. + size_t const available_entries = + container.current_size () - this->marked_as_closed_entries_; + + // Also whether the number of entries in the cache zero. + // Oops! then there is no way out but exiting. + if (available_entries <= 0) + return 0; + + // Calculate the no of entries to remove from the cache depending + // upon the . + size_t entries_to_remove + = ACE_MAX (static_cast (1), + static_cast (static_cast (purge_percent) + / 100 * available_entries)); + + if (entries_to_remove >= available_entries || entries_to_remove == 0) + entries_to_remove = available_entries - 1; + + KEY *key_to_remove = 0; + VALUE *value_to_remove = 0; + + for (size_t i = 0; i < entries_to_remove ; ++i) + { + this->minimum (container, + key_to_remove, + value_to_remove); + + // Simply verifying that the key is non-zero. + // This is important for strategies where the minimum + // entry cant be found due to constraints on the type of entry + // to remove. + if (key_to_remove == 0) + return 0; + + if (this->cleanup_strategy_->cleanup (container, + key_to_remove, + value_to_remove) == -1) + return -1; + + ++this->marked_as_closed_entries_; + } + + return 0; +} + +template void +ACE_Refcounted_Recyclable_Handler_Caching_Utility::minimum (CONTAINER &container, + KEY *&key_to_remove, + VALUE *&value_to_remove) +{ + // Starting values. + ITERATOR end = container.end (); + ITERATOR iter = container.begin (); + ATTRIBUTES min = (*iter).int_id_.second (); + key_to_remove = 0; + value_to_remove = 0; + // Found the minimum entry to be purged? + int found = 0; + + // The iterator moves thru the container searching for the entry + // with the lowest ATTRIBUTES. + for (; + iter != end; + ++iter) + { + // If the entry isnt IDLE_AND_PURGABLE continue until you reach + // the first entry which can be purged. This is the minimum with + // which you will compare the rest of the purgable entries. + if ((*iter).ext_id_.recycle_state () == ACE_RECYCLABLE_IDLE_AND_PURGABLE || + (*iter).ext_id_.recycle_state () == ACE_RECYCLABLE_PURGABLE_BUT_NOT_IDLE) + { + if (found == 0) + { + min = (*iter).int_id_.second (); + key_to_remove = &(*iter).ext_id_; + value_to_remove = &(*iter).int_id_; + found = 1; + } + else + { + // Ah! an entry with lower ATTTRIBUTES... + if (min > (*iter).int_id_.second ()) + { + min = (*iter).int_id_.second (); + key_to_remove = &(*iter).ext_id_; + value_to_remove = &(*iter).int_id_; + } + } + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +template +ACE_Handler_Caching_Utility::ACE_Handler_Caching_Utility (ACE_Cleanup_Strategy *cleanup_strategy, + int delete_cleanup_strategy) + : cleanup_strategy_ (cleanup_strategy), + delete_cleanup_strategy_ (delete_cleanup_strategy) +{ + if (cleanup_strategy == 0) + { + ACE_NEW (this->cleanup_strategy_, + CLEANUP_STRATEGY); + this->delete_cleanup_strategy_ = 1; + } +} + +template +ACE_Handler_Caching_Utility::~ACE_Handler_Caching_Utility (void) +{ + if (this->delete_cleanup_strategy_) + delete this->cleanup_strategy_; +} + +template int +ACE_Handler_Caching_Utility::clear_cache (CONTAINER &container, + double purge_percent) +{ + // Check that the purge_percent is non-zero. + if (purge_percent == 0) + return 0; + + // Get the number of entries in the container. + size_t current_map_size = container.current_size (); + + // Also whether the number of entries in the cache is just one! + // Oops! then there is no way out but exiting. So return an error. + if (current_map_size == 0) + return 0; + + // Calculate the no of entries to remove from the cache depending + // upon the . + size_t entries_to_remove + = ACE_MAX (static_cast (1), + static_cast (static_cast (purge_percent) + / 100 * current_map_size)); + + KEY *key_to_remove = 0; + VALUE *value_to_remove = 0; + + for (size_t i = 0; i < entries_to_remove ; ++i) + { + this->minimum (container, + key_to_remove, + value_to_remove); + + if (this->cleanup_strategy_->cleanup (container, + key_to_remove, + value_to_remove) == -1) + return -1; + } + + return 0; +} + +template void +ACE_Handler_Caching_Utility::minimum (CONTAINER &container, + KEY *&key_to_remove, + VALUE *&value_to_remove) +{ + // Starting values. + ITERATOR iter = container.begin (); + ITERATOR end = container.end (); + ATTRIBUTES min = (*iter).int_id_->caching_attributes (); + key_to_remove = &(*iter).ext_id_; + value_to_remove = &(*iter).int_id_; + + // The iterator moves thru the container searching for the entry + // with the lowest ATTRIBUTES. + for (++iter; + iter != end; + ++iter) + { + if (min > (*iter).int_id_->caching_attributes () && + (*iter).int_id_->active () != 1) + { + // Ah! an item with lower ATTTRIBUTES... + min = (*iter).int_id_->caching_attributes (); + key_to_remove = &(*iter).ext_id_; + value_to_remove = &(*iter).int_id_; + } + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +template +ACE_Null_Caching_Utility::ACE_Null_Caching_Utility (ACE_Cleanup_Strategy *cleanup_strategy, + int delete_cleanup_strategy) + : cleanup_strategy_ (cleanup_strategy), + delete_cleanup_strategy_ (delete_cleanup_strategy) +{ + if (cleanup_strategy == 0) + { + ACE_NEW (this->cleanup_strategy_, + CLEANUP_STRATEGY); + this->delete_cleanup_strategy_ = 1; + } +} + +template +ACE_Null_Caching_Utility::~ACE_Null_Caching_Utility (void) +{ + if (this->delete_cleanup_strategy_) + delete this->cleanup_strategy_; +} + +template int +ACE_Null_Caching_Utility::clear_cache (CONTAINER &container, + double purge_percent) +{ + ACE_UNUSED_ARG (container); + ACE_UNUSED_ARG (purge_percent); + + return 0; +} + +template void +ACE_Null_Caching_Utility::minimum (CONTAINER &container, + KEY *&key_to_remove, + VALUE *&value_to_remove) +{ + ACE_UNUSED_ARG (container); + ACE_UNUSED_ARG (key_to_remove); + ACE_UNUSED_ARG (value_to_remove); +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_CACHING_UTILITY_T_CPP */ diff --git a/dep/acelite/ace/Caching_Utility_T.h b/dep/acelite/ace/Caching_Utility_T.h new file mode 100644 index 00000000000..5428682d099 --- /dev/null +++ b/dep/acelite/ace/Caching_Utility_T.h @@ -0,0 +1,347 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Caching_Utility_T.h + * + * $Id: Caching_Utility_T.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Kirthika Parameswaran + */ +//============================================================================= + +#ifndef ACE_CACHING_UTILITY_H +#define ACE_CACHING_UTILITY_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Global_Macros.h" +#include "ace/Cleanup_Strategies_T.h" + +// For linkers that cant grok long names. +#define ACE_Pair_Caching_Utility APUTIL + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Pair_Caching_Utility + * + * @brief Defines a helper class for the Caching Strategies. + * + * This class defines the methods commonly used by the different + * caching strategies. For instance: method which + * decides and purges the entry from the container. @note This + * class helps in the caching_strategies using a container + * containing entries of > + * kind. The attributes helps in deciding the entries to be + * purged. The Cleanup_Strategy is the callback class to which the + * entries to be cleaned up will be delegated. + */ +template +class ACE_Pair_Caching_Utility +{ +public: + + typedef ACE_Cleanup_Strategy CLEANUP_STRATEGY; + + /// Constructor. + ACE_Pair_Caching_Utility (ACE_Cleanup_Strategy *cleanup_strategy = 0, + int delete_cleanup_strategy = 0); + + /// Destructor. + ~ACE_Pair_Caching_Utility (void); + + /** + * Purge entries from the @a container. The Cleanup_Strategy will do the + * actual job of cleanup once the entries to be cleaned up are decided. + */ + int clear_cache (CONTAINER &container, + double purge_percent); + +protected: + + /// Find the entry with minimum caching attributes. + void minimum (CONTAINER &container, + KEY *&key_to_remove, + VALUE *&value_to_remove); + + /// The cleanup strategy which can be used to destroy the entries of + /// the container. + CLEANUP_STRATEGY *cleanup_strategy_; + + /// Whether the cleanup_strategy should be destroyed or not. + int delete_cleanup_strategy_; + + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Pair_Caching_Utility &)) + ACE_UNIMPLEMENTED_FUNC (ACE_Pair_Caching_Utility (const ACE_Pair_Caching_Utility &)) +}; + +//////////////////////////////////////////////////////////////////////////////// +#define ACE_Recyclable_Handler_Caching_Utility ARHUTIL + +/** + * @class ACE_Recyclable_Handler_Caching_Utility + * + * @brief Defines a helper class for the Caching Strategies. + * + * This class defines the methods commonly used by the different + * caching strategies. For instance: method which + * decides and purges the entry from the container. @note This + * class helps in the caching_strategies using a container + * containing entries of kind. The attributes + * helps in deciding the entries to be purged. The + * Cleanup_Strategy is the callback class to which the entries to + * be cleaned up will be delegated. + */ +template +class ACE_Recyclable_Handler_Caching_Utility +{ + +public: + + typedef ACE_Recyclable_Handler_Cleanup_Strategy CLEANUP_STRATEGY; + typedef ACE_Cleanup_Strategy CLEANUP_STRATEGY_BASE; + + /// Constructor. + ACE_Recyclable_Handler_Caching_Utility (ACE_Cleanup_Strategy *cleanup_strategy = 0, + int delete_cleanup_strategy = 0); + + /// Destructor. + ~ACE_Recyclable_Handler_Caching_Utility (void); + + /** + * Purge entries from the . The Cleanup_Strategy will do + * the actual job of cleanup once the entries to be cleaned up are + * decided. + */ + int clear_cache (CONTAINER &container, + double purge_percent); + +protected: + + /// Find the entry with minimum caching attributes. + void minimum (CONTAINER &container, + KEY *&key_to_remove, + VALUE *&value_to_remove); + + /// This is the default Cleanup Strategy for this utility. + CLEANUP_STRATEGY_BASE *cleanup_strategy_; + + /// Whether the cleanup_strategy should be destroyed or not. + int delete_cleanup_strategy_; + +private: + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Recyclable_Handler_Caching_Utility &)) + ACE_UNIMPLEMENTED_FUNC (ACE_Recyclable_Handler_Caching_Utility (const ACE_Recyclable_Handler_Caching_Utility &)) +}; + +/////////////////////////////////////////////////////////////////////////// +#define ACE_Refcounted_Recyclable_Handler_Caching_Utility ARRHUTIL + +/** + * @class ACE_Refcounted_Recyclable_Handler_Caching_Utility + * + * @brief Defines a helper class for the Caching Strategies. + * + * This class defines the methods commonly used by the different + * caching strategies. For instance: clear_cache () method which + * decides and purges the entry from the container. @note This + * class helps in the caching_strategies using a container + * containing entries of kind. The attributes helps in + * deciding the entries to be purged. The Cleanup_Strategy is the + * callback class to which the entries to be cleaned up will be + * delegated. + */ +template +class ACE_Refcounted_Recyclable_Handler_Caching_Utility +{ + +public: + + typedef ACE_Refcounted_Recyclable_Handler_Cleanup_Strategy CLEANUP_STRATEGY; + typedef ACE_Cleanup_Strategy CLEANUP_STRATEGY_BASE; + + /// Constructor. + ACE_Refcounted_Recyclable_Handler_Caching_Utility (ACE_Cleanup_Strategy *cleanup_strategy = 0, + int delete_cleanup_strategy = 0); + + /// Destructor. + ~ACE_Refcounted_Recyclable_Handler_Caching_Utility (void); + + /** + * Purge entries from the . The Cleanup_Strategy will do + * the actual job of cleanup once the entries to be cleaned up are + * decided. + */ + int clear_cache (CONTAINER &container, + double purge_percent); + +protected: + + /// Find the entry with minimum caching attributes. + void minimum (CONTAINER &container, + KEY *&key_to_remove, + VALUE *&value_to_remove); + + /// This is the default Cleanup Strategy for this utility. + CLEANUP_STRATEGY_BASE *cleanup_strategy_; + + /// Whether the cleanup_strategy should be destroyed or not. + int delete_cleanup_strategy_; + + /** + * This figure denotes the number of entries are there in the + * container which have been marked as closed already but might + * not have been unbound from the container. + */ + size_t marked_as_closed_entries_; + +private: + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Refcounted_Recyclable_Handler_Caching_Utility &)) + ACE_UNIMPLEMENTED_FUNC (ACE_Refcounted_Recyclable_Handler_Caching_Utility (const ACE_Refcounted_Recyclable_Handler_Caching_Utility &)) +}; + +//////////////////////////////////////////////////////////////////////////////////////// + +/** + * @class ACE_Handler_Caching_Utility + * + * @brief Defines a helper class for the Caching Strategies. + * + * This class defines the methods commonly used by the different + * caching strategies. For instance: method which + * decides and purges the entry from the container. @note This + * class helps in the caching_strategies using a container + * containing entries of kind where the HANDLER + * contains the caching attributes which help in deciding the + * entries to be purged. The Cleanup_Strategy is the callback + * class to which the entries to be cleaned up will be delegated. + */ +template +class ACE_Handler_Caching_Utility +{ +public: + + typedef ACE_Handler_Cleanup_Strategy CLEANUP_STRATEGY; + typedef ACE_Cleanup_Strategy CLEANUP_STRATEGY_BASE; + + /// Constructor. + ACE_Handler_Caching_Utility (ACE_Cleanup_Strategy *cleanup_strategy = 0, + int delete_cleanup_strategy = 0); + + /// Destructor. + ~ACE_Handler_Caching_Utility (void); + + /** + * Purge entries from the . The Cleanup_Strategy will do + * the actual job of cleanup once the entries to be cleaned up are + * decided. + */ + int clear_cache (CONTAINER &container, + double purge_percent); + +protected: + + /** + * Find the entry with minimum caching attributes. This is handler + * specific since this utility is to be used very specifically for + * handler who have caching_attributes for server side acched + * connection management. + */ + void minimum (CONTAINER &container, + KEY *&key_to_remove, + VALUE *&value_to_remove); + + /// The cleanup strategy which can be used to destroy the entries of + /// the container. + CLEANUP_STRATEGY_BASE *cleanup_strategy_; + + /// Whether the cleanup_strategy should be destroyed or not. + int delete_cleanup_strategy_; + +private: + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Handler_Caching_Utility &)) + ACE_UNIMPLEMENTED_FUNC (ACE_Handler_Caching_Utility (const ACE_Handler_Caching_Utility &)) +}; + +/////////////////////////////////////////////////////////////////////////// +#define ACE_Null_Caching_Utility ANUTIL +/** + * @class ACE_Null_Caching_Utility + * + * @brief Defines a dummy helper class for the Caching Strategies. + * + * This class defines the methods commonly used by the different + * caching strategies. For instance: method which + * decides and purges the entry from the container. @note This + * class is be used with the Null_Caching_Strategy. The + * Cleanup_Strategy is the callback class to which the entries to + * be cleaned up will be delegated. + */ +template +class ACE_Null_Caching_Utility +{ +public: + + typedef ACE_Null_Cleanup_Strategy CLEANUP_STRATEGY; + typedef ACE_Cleanup_Strategy CLEANUP_STRATEGY_BASE; + + /// Constructor. + ACE_Null_Caching_Utility (ACE_Cleanup_Strategy *cleanup_strategy = 0, + int delete_cleanup_strategy = 0); + + /// Destructor. + ~ACE_Null_Caching_Utility (void); + + /** + * Purge entries from the . The Cleanup_Strategy will do + * the actual job of cleanup once the entries to be cleaned up are + * decided. @note Here it is a no-op. + */ + int clear_cache (CONTAINER &container, + double purge_percent); + +protected: + + /** + * Find the entry with minimum caching attributes. This is handler + * specific since this utility is to be used very specifically for + * handler who have caching_attributes for server side acched + * connection management.@note Here it is a no-op. + */ + void minimum (CONTAINER &container, + KEY *&key_to_remove, + VALUE *&value_to_remove); + + /// The cleanup strategy which can be used to destroy the entries of + /// the container. + CLEANUP_STRATEGY_BASE *cleanup_strategy_; + + /// Whether the cleanup_strategy should be destroyed or not. + int delete_cleanup_strategy_; + +private: + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Null_Caching_Utility &)) + ACE_UNIMPLEMENTED_FUNC (ACE_Null_Caching_Utility (const ACE_Null_Caching_Utility &)) +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Caching_Utility_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Caching_Utility_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" + +#endif /* ACE_CACHING_UTILITY_H */ diff --git a/dep/acelite/ace/Capabilities.cpp b/dep/acelite/ace/Capabilities.cpp new file mode 100644 index 00000000000..5d46e75472a --- /dev/null +++ b/dep/acelite/ace/Capabilities.cpp @@ -0,0 +1,355 @@ +#include "ace/Capabilities.h" +#include "ace/OS_NS_ctype.h" +#include "ace/OS_Memory.h" +#include "ace/OS_NS_string.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Capabilities.inl" +#endif /* !__ACE_INLINE__ */ + +#include "ace/OS_NS_stdio.h" + +ACE_RCSID (ace, + Capabilities, + "$Id: Capabilities.cpp 80826 2008-03-04 14:51:23Z wotte $") + + +#define ACE_ESC ((ACE_TCHAR)0x1b) + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_CapEntry::~ACE_CapEntry (void) +{ +} + +ACE_Capabilities::ACE_Capabilities (void) + : caps_ () +{ +} + +ACE_Capabilities::~ACE_Capabilities (void) +{ + this->resetcaps (); +} + +const ACE_TCHAR * +ACE_Capabilities::parse (const ACE_TCHAR *buf, ACE_TString &cap) +{ + while (*buf != ACE_TEXT ('\0') && *buf != ACE_TEXT (',')) + { + if (*buf == ACE_TEXT ('\\')) + { + ++buf; + if (*buf == ACE_TEXT ('E') || *buf == ACE_TEXT ('e')) + { + cap += ACE_ESC; + ++buf; + continue; + } + else if (*buf == ACE_TEXT ('r')) + { + cap += ACE_TEXT ('\r'); + ++buf; + continue; + } + else if (*buf == ACE_TEXT ('n')) + { + cap += ACE_TEXT ('\n'); + ++buf; + continue; + } + else if (*buf == ACE_TEXT ('t')) + { + cap += ACE_TEXT ('\t'); + ++buf; + continue; + } + else if (*buf == ACE_TEXT ('\\')) + { + cap += *buf++; + continue; + } + if (ACE_OS::ace_isdigit(*buf)) + { + // @@ UNICODE Does this work with unicode? + int oc = 0; + for (int i = 0; + i < 3 && *buf && ACE_OS::ace_isdigit (*buf); + i++) + oc = oc * 8 + (*buf++ - ACE_TEXT ('0')); + + cap += (ACE_TCHAR) oc; + continue; + } + } + cap += *buf++; + } + return buf; +} + +const ACE_TCHAR * +ACE_Capabilities::parse (const ACE_TCHAR *buf, int &cap) +{ + int n = 0; + + while (*buf && ACE_OS::ace_isdigit (*buf)) + n = n * 10 + (*buf++ - ACE_TEXT ('0')); + + cap = n; + + return buf; +} + +void +ACE_Capabilities::resetcaps (void) +{ + for (CAPABILITIES_MAP::ITERATOR iter (this->caps_); + !iter.done (); + iter.advance ()) + { + CAPABILITIES_MAP::ENTRY *entry = 0; + iter.next (entry); + delete entry->int_id_; + } + + this->caps_.close (); + this->caps_.open (); +} + +int +ACE_Capabilities::fillent (const ACE_TCHAR *buf) +{ + this->resetcaps (); + while (*buf) + { + ACE_TString s; + int n; + ACE_TString name; + ACE_CapEntry *ce; + + // Skip blanks + while (*buf && ACE_OS::ace_isspace(*buf)) buf++; + // If we get end of line return + + if (*buf == ACE_TEXT ('\0')) + break; + + if (*buf == ACE_TEXT ('#')) + { + while (*buf && *buf != ACE_TEXT ('\n')) + buf++; + if (*buf == ACE_TEXT ('\n')) + buf++; + continue; + } + while(*buf && *buf != ACE_TEXT ('=') + && *buf!= ACE_TEXT ('#') + && *buf != ACE_TEXT (',')) + name += *buf++; + + // If name is null. + switch (*buf) + { + case ACE_TEXT ('='): + // String property + buf = this->parse (buf + 1, s); + ACE_NEW_RETURN (ce, + ACE_StringCapEntry (s), + -1); + if (this->caps_.bind (name, ce) == -1) + { + delete ce; + return -1; + } + break; + case ACE_TEXT ('#'): + // Integer property + buf = this->parse (buf + 1, n); + ACE_NEW_RETURN (ce, + ACE_IntCapEntry (n), + -1); + if (this->caps_.bind (name, ce) == -1) + { + delete ce; + return -1; + } + break; + case ACE_TEXT (','): + // Boolean + ACE_NEW_RETURN (ce, + ACE_BoolCapEntry (1), + -1); + if (this->caps_.bind (name, ce) == -1) + { + delete ce; + return -1; + } + break; + default: + return 0; + } + + if (*buf++ != ACE_TEXT (',')) + return -1; + } + + return 0; +} + +int +ACE_Capabilities::is_entry (const ACE_TCHAR *name, const ACE_TCHAR *line) +{ + for (;;) + { + // Skip blanks or irrelevant characters + while (*line && ACE_OS::ace_isspace(*line)) + ++line; + + // End of line reached + if (*line == ACE_TEXT ('\0')) + break; + + // Build the entry name + ACE_TString nextname; + while (*line && *line != ACE_TEXT ('|') && *line != ACE_TEXT (',')) + nextname += *line++; + + // We have found the required entry? + if (ACE_OS::strcmp (nextname.c_str (), name) == 0) + return 1; + + // Skip puntuaction char if neccesary. + if (*line == ACE_TEXT ('|') || *line == ACE_TEXT (',')) + ++line; + else + { + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("Invalid entry\n"))); + break; + } + } + return 0; +} + +int +ACE_Capabilities::getline (FILE *fp, ACE_TString &line) +{ + int ch; + + line.set (0, 0); + + while ((ch = ACE_OS::fgetc (fp)) != EOF && ch != ACE_TEXT ('\n')) + line += (ACE_TCHAR) ch; + + if (ch == EOF && line.length () == 0) + return -1; + else + return 0; +} + +int +ACE_Capabilities::getval (const ACE_TCHAR *keyname, ACE_TString &val) +{ + ACE_CapEntry* cap = 0; + if (this->caps_.find (keyname, cap) == -1) + return -1; + + ACE_StringCapEntry *scap = + dynamic_cast (cap); + if (scap == 0) + return -1; + + val = scap->getval (); + return 0; +} + +int +ACE_Capabilities::getval (const ACE_TCHAR *keyname, int &val) +{ + ACE_CapEntry *cap = 0; + if (this->caps_.find (keyname, cap) == -1) + return -1; + + ACE_IntCapEntry *icap = + dynamic_cast (cap); + if (icap != 0) + { + val = icap->getval (); + return 0; + } + + ACE_BoolCapEntry *bcap = + dynamic_cast (cap); + + if (bcap == 0) + return -1; + + val = bcap->getval (); + return 0; +} + +#if !defined (ACE_IS_SPLITTING) +static int +is_empty (const ACE_TCHAR *line) +{ + while (*line && ACE_OS::ace_isspace (*line)) + ++line; + + return *line == ACE_TEXT ('\0') || *line == ACE_TEXT ('#'); +} + +static int +is_line (const ACE_TCHAR *line) +{ + while (*line && ACE_OS::ace_isspace (*line)) + ++line; + + return *line != ACE_TEXT ('\0'); +} +#endif /* !ACE_IS_SPLITTING */ + +int +ACE_Capabilities::getent (const ACE_TCHAR *fname, const ACE_TCHAR *name) +{ + FILE *fp = ACE_OS::fopen (fname, ACE_TEXT ("r")); + + if (fp == 0) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("Can't open %s file\n"), + fname), + -1); + + int done; + ACE_TString line; + + while (0 == (done = (this->getline (fp, line) == -1)) + && is_empty (line.c_str ())) + continue; + + while (!done) + { + ACE_TString newline; + ACE_TString description; + + while (0 == (done = (this->getline (fp, newline) == -1))) + if (is_line (newline.c_str ())) + description += newline; + else + break; + + if (this->is_entry (name, line.c_str())) + { + ACE_OS::fclose (fp); + return this->fillent (description.c_str ()); + } + + line = newline; + while (!done && is_empty (line.c_str ())) + done = this->getline (fp, line) == -1; + } + + ACE_OS::fclose (fp); + return -1; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Capabilities.h b/dep/acelite/ace/Capabilities.h new file mode 100644 index 00000000000..f4c8b5cc6fb --- /dev/null +++ b/dep/acelite/ace/Capabilities.h @@ -0,0 +1,221 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file Capabilities.h + * + * $Id: Capabilities.h 91077 2010-07-13 14:33:08Z johnnyw $ + * + * @author Arturo Montes + */ +//============================================================================= + + +#ifndef ACE_CAPABILITIES_H +#define ACE_CAPABILITIES_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Null_Mutex.h" +#include "ace/Hash_Map_Manager_T.h" +#include "ace/Containers.h" +#include "ace/SString.h" +#include "ace/Functor_String.h" + +#if defined (ACE_IS_SPLITTING) +# include "ace/OS_NS_ctype.h" +#endif /* ACE_IS_SPLITTING */ + + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_CapEntry + * + * @brief This class is the base class for all ACE Capabilities entry + * subclasses. + * + * This class is not instantiable and does not provide accessors + * or methods. If you want to add a new kind of attribute subclass + * this class and dynamic_cast to proper subclass. + */ +class ACE_Export ACE_CapEntry +{ +public: + + virtual ~ACE_CapEntry (void); + +protected: + + enum + { + ACE_INTCAP = 0, + ACE_STRINGCAP = 1, + ACE_BOOLCAP = 2 + }; + + ACE_CapEntry (int captype); + +protected: + + int captype_; + +}; + +/** + * @class ACE_IntCapEntry + * + * @brief This class implement the ACE Integer Capability subclass. + * + * This is a container class for ACE Capabilities integer container + * values. + */ +class ACE_Export ACE_IntCapEntry : public ACE_CapEntry +{ +public: + ACE_IntCapEntry (int val); + int getval (void) const; + +protected: + int val_; +}; + +/** + * @class ACE_StringCapEntry + * + * @brief This class implement the ACE String Capability subclass. + * + * This is a container class for ACE Capabilities String container + * values. + */ +class ACE_Export ACE_StringCapEntry : public ACE_CapEntry +{ +public: + ACE_StringCapEntry (const ACE_TString &val); + ACE_TString getval (void) const; + +protected: + ACE_TString val_; +}; + +/** + * @class ACE_BoolCapEntry + * + * @brief This class implement the ACE Bool Capability subclass. + * + * This is a container class for ACE Capabilities bool container + * values. + */ +class ACE_Export ACE_BoolCapEntry : public ACE_CapEntry +{ +public: + ACE_BoolCapEntry (int val); + int getval (void) const; + +protected: + int val_; +}; + +/** + * @class ACE_Capabilities + * + * @brief + * This class implement the ACE Capabilities. + * + * This is a container class for ACE Capabilities + * values. Currently exist three different capability values: + * ACE_IntCapEntry (integer), ACE_BoolCapEntry (bool) and + * ACE_StringCapEntry (String). An ACE_Capabilities is a + * unordered set of pair = (String, ACE_CapEntry *). Where + * the first component is the name of capability and the second + * component is a pointer to the capability value container. A + * FILE is a container for ACE_Capabilities, the + * ACE_Capabilities has a name in the file, as a termcap file. + */ +class ACE_Export ACE_Capabilities +{ +public: + + typedef ACE_Hash_Map_Manager_Ex, ACE_Equal_To, ACE_Null_Mutex> CAPABILITIES_MAP; + + /// The Constructor + ACE_Capabilities (void); + + /// The Destructor + ~ACE_Capabilities(void); + +public: + + /// Get a string entry. + int getval (const ACE_TCHAR *ent, ACE_TString &val); + + /// Get an integer entry. + int getval (const ACE_TCHAR *ent, int &val); + + /// Get the ACE_Capabilities name from FILE fname and load the + /// associated capabitily entries in map. + int getent (const ACE_TCHAR *fname, const ACE_TCHAR *name); + +protected: + + /// Parse an integer property + const ACE_TCHAR *parse (const ACE_TCHAR *buf, int &cap); + + /// Parse a string property + const ACE_TCHAR *parse (const ACE_TCHAR *buf, ACE_TString &cap); + + /// Fill the ACE_Capabilities with description in ent. + int fillent(const ACE_TCHAR *ent); + + /// Parse a cap entry + int parseent (const ACE_TCHAR *name, ACE_TCHAR *line); + + /// Get a line from FILE input stream + int getline (FILE* fp, + ACE_TString &line); + + /// Is a valid entry + int is_entry (const ACE_TCHAR *name, const ACE_TCHAR *line); + + /// Reset the set of capabilities + void resetcaps (void); + +private: + + /// This is the set of ACE_CapEntry. + CAPABILITIES_MAP caps_; +}; + +#if defined (ACE_IS_SPLITTING) +int +is_empty (const ACE_TCHAR *line) +{ + while (*line && ACE_OS::ace_isspace (*line)) + ++line; + + return *line == ACE_TEXT ('\0') || *line == ACE_TEXT ('#'); +} + +int +is_line (const ACE_TCHAR *line) +{ + while (*line && ACE_OS::ace_isspace (*line)) + ++line; + + return *line != ACE_TEXT ('\0'); +} +#endif /* ACE_IS_SPLITTING */ + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Capabilities.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* __ACE_CAPABILITIES_H__ */ diff --git a/dep/acelite/ace/Capabilities.inl b/dep/acelite/ace/Capabilities.inl new file mode 100644 index 00000000000..37284b28696 --- /dev/null +++ b/dep/acelite/ace/Capabilities.inl @@ -0,0 +1,52 @@ +// -*- C++ -*- +// +// $Id: Capabilities.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE +ACE_CapEntry::ACE_CapEntry (int captype) + : captype_ (captype) +{ +} + +ACE_INLINE +ACE_IntCapEntry::ACE_IntCapEntry (int val) + : ACE_CapEntry (ACE_INTCAP), + val_ (val) +{ +} + +ACE_INLINE int +ACE_IntCapEntry::getval (void) const +{ + return val_; +} + +ACE_INLINE +ACE_StringCapEntry::ACE_StringCapEntry (const ACE_TString &val) + : ACE_CapEntry (ACE_STRINGCAP), + val_ (val) +{ +} + +ACE_INLINE ACE_TString +ACE_StringCapEntry::getval (void) const +{ + return val_; +} + +ACE_INLINE +ACE_BoolCapEntry::ACE_BoolCapEntry (int val) + : ACE_CapEntry (ACE_BOOLCAP), + val_(val) +{ +} + +ACE_INLINE int +ACE_BoolCapEntry::getval (void) const +{ + return val_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Cleanup.cpp b/dep/acelite/ace/Cleanup.cpp new file mode 100644 index 00000000000..5c7317ed4da --- /dev/null +++ b/dep/acelite/ace/Cleanup.cpp @@ -0,0 +1,181 @@ +// $Id: Cleanup.cpp 84201 2009-01-20 06:26:02Z johnnyw $ + +#include "ace/Cleanup.h" + +ACE_RCSID (ace, + Cleanup, + "$Id: Cleanup.cpp 84201 2009-01-20 06:26:02Z johnnyw $") + +#if !defined (ACE_HAS_INLINED_OSCALLS) +# include "ace/Cleanup.inl" +#endif /* ACE_HAS_INLINED_OSCALLS */ + +#include "ace/OS_Memory.h" +#include "ace/OS_NS_string.h" +#include "ace/os_include/os_typeinfo.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +void +ACE_Cleanup::cleanup (void *) +{ + delete this; +} + +ACE_Cleanup::~ACE_Cleanup (void) +{ +} + +/*****************************************************************************/ + +extern "C" void +ACE_CLEANUP_DESTROYER_NAME (ACE_Cleanup *object, void *param) +{ + object->cleanup (param); +} + +/*****************************************************************************/ + +ACE_Cleanup_Info_Node::ACE_Cleanup_Info_Node (void) + : object_ (0), + cleanup_hook_ (0), + param_ (0), + name_ (0) +{ +} + +ACE_Cleanup_Info_Node::ACE_Cleanup_Info_Node (void *object, + ACE_CLEANUP_FUNC cleanup_hook, + void *param, + const char *name) + : object_ (object), + cleanup_hook_ (cleanup_hook), + param_ (param), + name_ (name ? ACE_OS::strdup (name) : 0) +{ +} + +ACE_Cleanup_Info_Node::~ACE_Cleanup_Info_Node (void) +{ + if (this->name_) + ACE_OS::free ((void *) name_); +} + +bool +ACE_Cleanup_Info_Node::operator== (const ACE_Cleanup_Info_Node &o) const +{ + return o.object_ == this->object_ + && o.cleanup_hook_ == this->cleanup_hook_ + && o.param_ == this->param_; +} + +bool +ACE_Cleanup_Info_Node::operator!= (const ACE_Cleanup_Info_Node &o) const +{ + return !(*this == o); +} + + +/*****************************************************************************/ + +ACE_OS_Exit_Info::ACE_OS_Exit_Info (void) +{ +} + +ACE_OS_Exit_Info::~ACE_OS_Exit_Info (void) +{ +} + +int +ACE_OS_Exit_Info::at_exit_i (void *object, + ACE_CLEANUP_FUNC cleanup_hook, + void *param, + const char* name) +{ + // Return -1 and sets errno if unable to allocate storage. Enqueue + // at the head and dequeue from the head to get LIFO ordering. + ACE_Cleanup_Info_Node *new_node = 0; + + ACE_NEW_RETURN (new_node, + ACE_Cleanup_Info_Node (object, cleanup_hook, param, name), + -1); + + registered_objects_.push_front (new_node); + + return 0; +} + +bool +ACE_OS_Exit_Info::find (void *object) +{ + for (ACE_Cleanup_Info_Node *iter = registered_objects_.head (); + iter != 0; + iter = iter->next ()) + { + if (iter->object () == object) + { + // The object has already been registered. + return true; + } + } + + return false; +} + +bool +ACE_OS_Exit_Info::remove (void *object) +{ + ACE_Cleanup_Info_Node *node = 0; + for (ACE_Cleanup_Info_Node *iter = registered_objects_.head (); + iter != 0; + iter = iter->next ()) + { + if (iter->object () == object) + { + node = iter; + break; + } + } + + if (node) + { + registered_objects_.remove (node); + delete node; + return true; + } + + return false; +} + + +void +ACE_OS_Exit_Info::call_hooks (void) +{ + // Call all registered cleanup hooks, in reverse order of + // registration. + for (ACE_Cleanup_Info_Node *iter = registered_objects_.pop_front (); + iter != 0; + iter = registered_objects_.pop_front ()) + { + if (iter->cleanup_hook () == reinterpret_cast ( + ACE_CLEANUP_DESTROYER_NAME)) + { + // The object is an ACE_Cleanup. + ACE_CLEANUP_DESTROYER_NAME ( + reinterpret_cast (iter->object ()), + iter->param ()); + } + else if (iter->object () == &ace_exit_hook_marker) + { + // The hook is an ACE_EXIT_HOOK. + (* reinterpret_cast (iter->cleanup_hook ())) (); + } + else + { + (*iter->cleanup_hook ()) (iter->object (), iter->param ()); + } + delete iter; + } +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Cleanup.h b/dep/acelite/ace/Cleanup.h new file mode 100644 index 00000000000..bd750724fb3 --- /dev/null +++ b/dep/acelite/ace/Cleanup.h @@ -0,0 +1,160 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Cleanup.h + * + * $Id: Cleanup.h 84163 2009-01-15 07:57:27Z johnnyw $ + * + * @author Douglas C. Schmidt + * @author Jesper S. M|ller + * @author and a cast of thousands... + * + * Originally in OS.h. + */ +//============================================================================= + +#ifndef ACE_CLEANUP_H +# define ACE_CLEANUP_H + +# include /**/ "ace/pre.h" + +# include "ace/config-lite.h" + +# if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +# endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include /**/ "ace/ACE_export.h" + +# include "ace/Intrusive_List.h" +# include "ace/Intrusive_List_Node.h" + +#if (defined (ACE_HAS_VERSIONED_NAMESPACE) && ACE_HAS_VERSIONED_NAMESPACE == 1) +# include "ace/Global_Macros.h" +# define ACE_CLEANUP_DESTROYER_NAME ACE_PREPROC_CONCATENATE(ACE_VERSIONED_NAMESPACE_NAME, _ace_cleanup_destroyer) +#else +# define ACE_CLEANUP_DESTROYER_NAME ace_cleanup_destroyer +#endif /* ACE_HAS_VERSIONED_NAMESPACE == 1 */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Cleanup + * + * @brief Base class for objects that are cleaned by ACE_Object_Manager. + */ +class ACE_Export ACE_Cleanup +{ +public: + /// No-op constructor. + ACE_Cleanup (void); + + /// Destructor. + virtual ~ACE_Cleanup (void); + + /// Cleanup method that, by default, simply deletes itself. + virtual void cleanup (void *param = 0); +}; + +/// Adapter for cleanup, used by ACE_Object_Manager. +extern "C" ACE_Export +void ACE_CLEANUP_DESTROYER_NAME (ACE_Cleanup *, void *param = 0); + +/** + * @class ACE_Cleanup_Info_Node + * + * @brief For maintaining a list of ACE_Cleanup_Info items. + * + * For internal use by ACE_Object_Manager. + */ +class ACE_Cleanup_Info_Node : public ACE_Intrusive_List_Node +{ +public: + ACE_Cleanup_Info_Node (void); + ACE_Cleanup_Info_Node (void *object, + ACE_CLEANUP_FUNC cleanup_hook, + void *param, + const char *name); + ~ACE_Cleanup_Info_Node (void); + + /// Equality operator. + bool operator== (const ACE_Cleanup_Info_Node &o) const; + + /// Inequality operator. + bool operator!= (const ACE_Cleanup_Info_Node &o) const; + + void* object(void); + + ACE_CLEANUP_FUNC cleanup_hook (void); + + void *param (void); +private: + /// Point to object that gets passed into the . + void *object_; + + /// Cleanup hook that gets called back. + ACE_CLEANUP_FUNC cleanup_hook_; + + /// Parameter passed to the . + void *param_; + + /// Name of the cleanup object + const char *name_; +}; + +typedef ACE_Intrusive_List ACE_Cleanup_Info_Node_List; + +/** + * @class ACE_OS_Exit_Info + * + * @brief Hold Object Manager cleanup (exit) information. + * + * @internal + * + * For internal use by the ACE library, only. + */ +class ACE_Export ACE_OS_Exit_Info +{ +public: + /// Default constructor. + ACE_OS_Exit_Info (void); + + /// Destructor. + ~ACE_OS_Exit_Info (void); + + /// Use to register a cleanup hook. + int at_exit_i (void *object, ACE_CLEANUP_FUNC cleanup_hook, void *param, const char* name = 0); + + /// Look for a registered cleanup hook object. Returns true if already + /// registered, false if not. + bool find (void *object); + + /// Remove a registered cleanup hook object. Returns true if removed + /// false if not. + bool remove (void *object); + + /// Call all registered cleanup hooks, in reverse order of + /// registration. + void call_hooks (); + +private: + /** + * Keeps track of all registered objects. + */ + ACE_Cleanup_Info_Node_List registered_objects_; +}; + + +ACE_END_VERSIONED_NAMESPACE_DECL + +# if defined (ACE_HAS_INLINED_OSCALLS) +# if defined (ACE_INLINE) +# undef ACE_INLINE +# endif /* ACE_INLINE */ +# define ACE_INLINE inline +# include "ace/Cleanup.inl" +# endif /* ACE_HAS_INLINED_OSCALLS */ + +# include /**/ "ace/post.h" +#endif /* ACE_CLEANUP_H */ diff --git a/dep/acelite/ace/Cleanup.inl b/dep/acelite/ace/Cleanup.inl new file mode 100644 index 00000000000..196a9f4788f --- /dev/null +++ b/dep/acelite/ace/Cleanup.inl @@ -0,0 +1,30 @@ +// -*- C++ -*- +// +// $Id: Cleanup.inl 83956 2008-12-03 07:57:38Z johnnyw $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE +ACE_Cleanup::ACE_Cleanup (void) +{ +} + +ACE_INLINE void* +ACE_Cleanup_Info_Node::object(void) +{ + return this->object_; +} + +ACE_INLINE ACE_CLEANUP_FUNC +ACE_Cleanup_Info_Node::cleanup_hook (void) +{ + return this->cleanup_hook_; +} + +ACE_INLINE void * +ACE_Cleanup_Info_Node::param (void) +{ + return this->param_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Cleanup_Strategies_T.cpp b/dep/acelite/ace/Cleanup_Strategies_T.cpp new file mode 100644 index 00000000000..32965993774 --- /dev/null +++ b/dep/acelite/ace/Cleanup_Strategies_T.cpp @@ -0,0 +1,95 @@ +//$Id: Cleanup_Strategies_T.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#ifndef ACE_CLEANUP_STRATEGIES_T_CPP +#define ACE_CLEANUP_STRATEGIES_T_CPP + +#include "ace/Cleanup_Strategies_T.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +#pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +//////////////////////////////////////////////////////////////////////////// + +template +ACE_Cleanup_Strategy::~ACE_Cleanup_Strategy (void) +{ +} + +template int +ACE_Cleanup_Strategy::cleanup (CONTAINER &container, + KEY *key, + VALUE *) +{ + return container.unbind (*key); +} + +//////////////////////////////////////////////////////////////////////////// + +template int +ACE_Recyclable_Handler_Cleanup_Strategy::cleanup ( + CONTAINER &container, + KEY *key, + VALUE *) +{ + VALUE value; + + if (container.unbind (*key, value) == -1) + return -1; + + value.first ()->recycler (0, 0); + + value.first ()->close (); + + return 0; +} + +///////////////////////////////////////////////////////////////////////////// + +template int +ACE_Refcounted_Recyclable_Handler_Cleanup_Strategy::cleanup ( + CONTAINER &, + KEY *, + VALUE *value) +{ + return value->first ()->handle_close_i (); +} + +//////////////////////////////////////////////////////////////////////////// + +template int +ACE_Handler_Cleanup_Strategy::cleanup ( + CONTAINER &container, + KEY *key, + VALUE *value) +{ + // Remove the item from cache only if the handler isnt in use. + if ((*value)->active () == 0) + { + (*value)->close (); + + if (container.unbind (*key) == -1) + return -1; + + } + + return 0; +} + +//////////////////////////////////////////////////////////////////////////// + +template int +ACE_Null_Cleanup_Strategy::cleanup (CONTAINER &, + KEY *, + VALUE *) +{ + return 0; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_CLEANUP_STRATEGIES_T_CPP */ diff --git a/dep/acelite/ace/Cleanup_Strategies_T.h b/dep/acelite/ace/Cleanup_Strategies_T.h new file mode 100644 index 00000000000..ca51b47b10f --- /dev/null +++ b/dep/acelite/ace/Cleanup_Strategies_T.h @@ -0,0 +1,149 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Cleanup_Strategies_T.h + * + * $Id: Cleanup_Strategies_T.h 81388 2008-04-23 14:02:05Z johnnyw $ + * + * @author Kirthika Parameswaran + */ +//============================================================================= + + +#ifndef CLEANUP_STRATEGIES_H +#define CLEANUP_STRATEGIES_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +// For linkers that cant grok long names. +#define ACE_Cleanup_Strategy ACLE + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Cleanup_Strategy + * + * @brief Defines a default strategy to be followed for cleaning up + * entries from a map which is the container. + * + * By default the entry to be cleaned up is removed from the + * container. + */ +template +class ACE_Cleanup_Strategy +{ + +public: + + /// Destructor. + virtual ~ACE_Cleanup_Strategy (void); + + /// The method which will do the cleanup of the entry in the container. + virtual int cleanup (CONTAINER &container, KEY *key, VALUE *value); +}; + +////////////////////////////////////////////////////////////////////// +#define ACE_Recyclable_Handler_Cleanup_Strategy ARHCLE + +/** + * @class ACE_Recyclable_Handler_Cleanup_Strategy + * + * @brief Defines a strategy to be followed for cleaning up + * entries which are svc_handlers from a container. + * + * The entry to be cleaned up is removed from the container. + * Here, since we are dealing with svc_handlers specifically, we + * perform a couple of extra operations. @note To be used when + * the handler is recyclable. + */ +template +class ACE_Recyclable_Handler_Cleanup_Strategy : public ACE_Cleanup_Strategy +{ + +public: + + /// The method which will do the cleanup of the entry in the container. + virtual int cleanup (CONTAINER &container, KEY *key, VALUE *value); +}; + +////////////////////////////////////////////////////////////////////// +#define ACE_Refcounted_Recyclable_Handler_Cleanup_Strategy ARRHCLE + +/** + * @class ACE_Refcounted_Recyclable_Handler_Cleanup_Strategy + * + * @brief Defines a strategy to be followed for cleaning up + * entries which are svc_handlers from a container. + * + * The entry to be cleaned up is removed from the container. + * Here, since we are dealing with recyclable svc_handlers with + * addresses which are refcountable specifically, we perform a + * couple of extra operations and do so without any locking. + */ +template +class ACE_Refcounted_Recyclable_Handler_Cleanup_Strategy : public ACE_Cleanup_Strategy +{ +public: + /// The method which will do the cleanup of the entry in the container. + virtual int cleanup (CONTAINER &container, KEY *key, VALUE *value); +}; + +////////////////////////////////////////////////////////////////////// + +/** + * @class ACE_Handler_Cleanup_Strategy + * + * @brief Defines a strategy to be followed for cleaning up + * entries which are svc_handlers from a container. + * + * The entry to be cleaned up is removed from the container. + * Here, since we are dealing with svc_handlers specifically, we + * perform a couple of extra operations. @note This cleanup strategy + * should be used in the case when the handler has the caching + * attributes. + */ +template +class ACE_Handler_Cleanup_Strategy : public ACE_Cleanup_Strategy +{ +public: + /// The method which will do the cleanup of the entry in the container. + virtual int cleanup (CONTAINER &container, KEY *key, VALUE *value); +}; + +////////////////////////////////////////////////////////////////////// +#define ACE_Null_Cleanup_Strategy ANCLE + +/** + * @class ACE_Null_Cleanup_Strategy + * + * @brief Defines a do-nothing implementation of the cleanup strategy. + * + * This class simply does nothing at all! Can be used to nullify + * the effect of the Cleanup Strategy. + */ +template +class ACE_Null_Cleanup_Strategy : public ACE_Cleanup_Strategy +{ +public: + /// The dummy cleanup method. + virtual int cleanup (CONTAINER &container, KEY *key, VALUE *value); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Cleanup_Strategies_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Cleanup_Strategies_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" +#endif /* CLEANUP_STRATEGIES_H */ diff --git a/dep/acelite/ace/Codecs.cpp b/dep/acelite/ace/Codecs.cpp new file mode 100644 index 00000000000..71491fe1c44 --- /dev/null +++ b/dep/acelite/ace/Codecs.cpp @@ -0,0 +1,234 @@ +#include "ace/Codecs.h" +#include "ace/Log_Msg.h" +#include "ace/OS_Memory.h" +#include "ace/OS_NS_ctype.h" + +ACE_RCSID (ace, + Codecs, + "$Id: Codecs.cpp 80826 2008-03-04 14:51:23Z wotte $") + +namespace +{ + // Just in case ... +#undef alphabet +#undef pad +#undef max_columns + + // Symbols which form the Base64 alphabet (Defined as per RFC 2045) + ACE_Byte const alphabet[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + + // The padding character used in the encoding + ACE_Byte const pad = '='; + + // Number of columns per line of encoded output (Can have a maximum + // value of 76). + int const max_columns = 72; +} + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +bool ACE_Base64::init_ = false; + +ACE_Byte ACE_Base64::decoder_[256]; + +ACE_Byte ACE_Base64::member_[256]; + +ACE_Byte* +ACE_Base64::encode (const ACE_Byte* input, + const size_t input_len, + size_t* output_len, + bool is_chunked) +{ + if (!ACE_Base64::init_) + ACE_Base64::init(); + + if (!input) + return 0; + + ACE_Byte* result = 0; + + size_t length = ((input_len + 2) / 3) * 4; + size_t num_lines = length / max_columns + 1; + length += num_lines + 1; + ACE_NEW_RETURN (result, ACE_Byte[length], 0); + + int char_count = 0; + int bits = 0; + size_t pos = 0; + int cols = 0; + + for (size_t i = 0; i < input_len; ++i) + { + bits += input[i]; + ++char_count; + + if (char_count == 3) + { + result[pos++] = alphabet[bits >> 18]; + result[pos++] = alphabet[(bits >> 12) & 0x3f]; + result[pos++] = alphabet[(bits >> 6) & 0x3f]; + result[pos++] = alphabet[bits & 0x3f]; + cols += 4; + if (cols == max_columns) { + if (is_chunked) + result[pos++] = '\n'; + cols = 0; + } + bits = 0; + char_count = 0; + } + else + { + bits <<= 8; + } + } + + if (char_count != 0) + { + bits <<= (16 - (8 * char_count)); + result[pos++] = alphabet[bits >> 18]; + result[pos++] = alphabet[(bits >> 12) & 0x3f]; + cols += 2; + if (char_count == 1) + { + result[pos++] = pad; + result[pos++] = pad; + cols += 2; + } + else + { + result[pos++] = alphabet[(bits >> 6) & 0x3f]; + result[pos++] = pad; + cols += 2; + } + } + + if (cols > 0 && is_chunked) + result[pos++] = '\n'; + + result[pos] = 0; + *output_len = pos; + return result; +} + +size_t +ACE_Base64::length (const ACE_Byte* input) +{ + if (!ACE_Base64::init_) + ACE_Base64::init(); + + ACE_Byte* ptr = const_cast (input); + while (*ptr != 0 && + (member_[*(ptr)] == 1 || *ptr == pad + || ACE_OS::ace_isspace (*ptr))) + ++ptr; + size_t len = ptr - input; + len = ((len + 3) / 4) * 3 + 1 ; + return len; +} + +ACE_Byte* +ACE_Base64::decode (const ACE_Byte* input, size_t* output_len) +{ + if (!ACE_Base64::init_) + ACE_Base64::init(); + + if (!input) + return 0; + + size_t result_len = ACE_Base64::length (input); + ACE_Byte* result = 0; + ACE_NEW_RETURN (result, ACE_Byte[result_len], 0); + + ACE_Byte* ptr = const_cast (input); + while (*ptr != 0 && + (member_[*(ptr)] == 1 || *ptr == pad + || ACE_OS::ace_isspace (*ptr))) + ++ptr; + size_t input_len = ptr - input; + + int char_count = 0; + int bits = 0; + size_t pos = 0; + + size_t i = 0; + for (; i < input_len; ++i) + { + if (input[i] == pad) + break; + if (!ACE_Base64::member_[input[i]]) + continue; + bits += decoder_[input[i]]; + ++char_count; + + if (char_count == 4) + { + result[pos++] = static_cast (bits >> 16); + result[pos++] = static_cast ((bits >> 8) & 0xff); + result[pos++] = static_cast (bits & 0xff); + bits = 0; + char_count = 0; + } + else + { + bits <<= 6; + } + } + + int errors = 0; + if ( i == input_len) + { + if (char_count) + { + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("Decoding incomplete: atleast %d bits truncated\n"), + (4 - char_count) * 6)); + ++errors; + } + } + else + { + switch (char_count) + { + case 1: + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("Decoding incomplete: atleast 2 bits missing\n"))); + ++errors; + break; + case 2: + result[pos++] = static_cast (bits >> 10); + break; + case 3: + result[pos++] = static_cast (bits >> 16); + result[pos++] = static_cast ((bits >> 8) & 0xff); + break; + } + } + + if (errors) + { + delete[] result; + return 0; + } + result[pos] = 0; + *output_len = pos; + return result; +} + +void +ACE_Base64::init () +{ + if (!ACE_Base64::init_) + { + for (ACE_Byte i = 0; i < sizeof (alphabet); ++i) + { + ACE_Base64::decoder_[alphabet[i]] = i; + ACE_Base64::member_ [alphabet[i]] = 1; + } + ACE_Base64::init_ = true; + } + return; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Codecs.h b/dep/acelite/ace/Codecs.h new file mode 100644 index 00000000000..2c4227dd0ad --- /dev/null +++ b/dep/acelite/ace/Codecs.h @@ -0,0 +1,121 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Codecs.h + * + * $Id: Codecs.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Krishnakumar B + * + * Codecs is a generic wrapper for various encoding and decoding + * mechanisms. Currently it includes Base64 content transfer-encoding as + * specified by RFC 2045, Multipurpose Internet Mail Extensions (MIME) Part + * One: Format of Internet Message Bodies. + * + */ +//============================================================================= + +#ifndef ACE_CODECS_H +#define ACE_CODECS_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Basic_Types.h" +#include "ace/Global_Macros.h" + + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Base64 + * + * @brief Encode/Decode a stream of bytes according to Base64 encoding. + * + * This class provides methods to encode or decode a stream of bytes + * to/from Base64 encoding. It doesn't convert the input stream to a + * canonical form before encoding. + * + */ +class ACE_Export ACE_Base64 +{ +public: + + //@{ + + /** + * Encodes a stream of bytes to Base64 data + * + * @param input Binary data in byte stream. + * @param input_len Length of the byte stream. + * @param output_len Length of the encoded Base64 byte stream. + * @param is_chunked If true, terminate 72 character blocks with newline + * @return Encoded Base64 data in byte stream or NULL if input data cannot + * be encoded. + */ + + static ACE_Byte* encode (const ACE_Byte* input, + const size_t input_len, + size_t* output_len, + bool is_chunked = true); + /** + * Decodes a stream of Base64 to bytes data + * + * @param input Encoded Base64 data in byte stream. + * @param output_len Length of the binary byte stream. + * @return Binary data in byte stream or NULL if input data cannot + * be encoded. + */ + static ACE_Byte* decode (const ACE_Byte* input, + size_t* output_len); + + /** + * Return the length of the encoded input data + * + * @param input Encoded Base64 data in byte stream. + * @return Length of the encoded Base64 data. + * + */ + static size_t length (const ACE_Byte* input); + + //@} + +protected: + + // Prevent default construction. + ACE_Base64 (void) {} + +private: + + // Preventing copying and assignment. + ACE_Base64 (ACE_Base64 const &); + ACE_Base64 & operator= (ACE_Base64 const &); + + /// Initialize the tables for encoding/decoding. + static void init (void); + +private: + + /// Alphabet used for decoding i.e decoder_[alphabet_[i = 0..63]] = i + static ACE_Byte decoder_[]; + + /// Alphabet used to check valid range of encoded input i.e + /// member_[alphabet_[0..63]] = 1 + static ACE_Byte member_[]; + + /// Boolean to denote whether initialization is complete + static bool init_; + +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" + +#endif /* ACE_CODECS_H */ diff --git a/dep/acelite/ace/Codeset_IBM1047.cpp b/dep/acelite/ace/Codeset_IBM1047.cpp new file mode 100644 index 00000000000..91582cf4ef3 --- /dev/null +++ b/dep/acelite/ace/Codeset_IBM1047.cpp @@ -0,0 +1,309 @@ + +//============================================================================= +/** + * @file Codeset_IBM1047.cpp + * + * $Id: Codeset_IBM1047.cpp 81661 2008-05-09 12:05:34Z johnnyw $ + * + * Defines the arrays required to convert between ISO8859 (aka + * Latin/1) and IBM1047 (aka EBCDIC). + * + * + * @author Jim Rogers (jrogers@viasoft.com) + */ +//============================================================================= + + +#include "ace/Codeset_IBM1047.h" + +#if defined (ACE_HAS_EBCDIC) + +ACE_RCSID (ace, + Codeset_IBM1047, + "$Id: Codeset_IBM1047.cpp 81661 2008-05-09 12:05:34Z johnnyw $") + +#include "ace/OS_Memory.h" +#include "ace/OS_NS_string.h" + +namespace +{ + char const to_IBM1047[] = + { + "\x00\x01\x02\x03\x37\x2D\x2E\x2F\x16\x05\x25\x0B\x0C\x0D\x0E\x0F" // 00-0F + "\x10\x11\x12\x13\x3C\x3D\x32\x26\x18\x19\x3F\x27\x22\x1D\x35\x1F" // 10-1F + "\x40\x5A\x7F\x7B\x5B\x6C\x50\x7D\x4D\x5D\x5C\x4E\x6B\x60\x4B\x61" // 20-2F + "\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\x7A\x5E\x4C\x7E\x6E\x6F" // 30-3F + "\x7C\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xD1\xD2\xD3\xD4\xD5\xD6" // 40-4F + "\xD7\xD8\xD9\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xAD\xE0\xBD\x5F\x6D" // 50-5F + "\x79\x81\x82\x83\x84\x85\x86\x87\x88\x89\x91\x92\x93\x94\x95\x96" // 60-6F + "\x97\x98\x99\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xC0\x4F\xD0\xA1\x07" // 70-7F + "\x43\x20\x21\x1C\x23\xEB\x24\x9B\x71\x28\x38\x49\x90\xBA\xEC\xDF" // 80-8F + "\x45\x29\x2A\x9D\x72\x2B\x8A\x9A\x67\x56\x64\x4A\x53\x68\x59\x46" // 90-9F + "\xEA\xDA\x2C\xDE\x8B\x55\x41\xFE\x58\x51\x52\x48\x69\xDB\x8E\x8D" // A0-AF + "\x73\x74\x75\xFA\x15\xB0\xB1\xB3\xB4\xB5\x6A\xB7\xB8\xB9\xCC\xBC" // B0-BF + "\xAB\x3E\x3B\x0A\xBF\x8F\x3A\x14\xA0\x17\xCB\xCA\x1A\x1B\x9C\x04" // C0-CF + "\x34\xEF\x1E\x06\x08\x09\x77\x70\xBE\xBB\xAC\x54\x63\x65\x66\x62" // D0-DF + "\x30\x42\x47\x57\xEE\x33\xB6\xE1\xCD\xED\x36\x44\xCE\xCF\x31\xAA" // E0-EF + "\xFC\x9E\xAE\x8C\xDD\xDC\x39\xFB\x80\xAF\xFD\x78\x76\xB2\x9F\xFF" // F0-FF +}; + + char const from_IBM1047[] = + { + "\x00\x01\x02\x03\xCF\x09\xD3\x7F\xD4\xD5\xC3\x0B\x0C\x0D\x0E\x0F" // 00-0F + "\x10\x11\x12\x13\xC7\xB4\x08\xC9\x18\x19\xCC\xCD\x83\x1D\xD2\x1F" // 10-1F + "\x81\x82\x1C\x84\x86\x0A\x17\x1B\x89\x91\x92\x95\xA2\x05\x06\x07" // 20-2F + "\x20\xEE\x16\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\xC1\x1A" // 30-3F + "\x20\xA6\xE1\x80\xEB\x90\x9F\xE2\xAB\x8B\x9B\x2E\x3C\x28\x2B\x7C" // 40-4F + "\x26\xA9\xAA\x9C\xDB\xA5\x99\xE3\xA8\x9E\x21\x24\x2A\x29\x3B\x5E" // 50-5F + "\x2D\x2F\xDF\xDC\x9A\xDD\xDE\x98\x9D\xAC\xBA\x2C\x25\x5F\x3E\x3F" // 60-6F + "\xD7\x88\x94\xB0\xB1\xB2\xFC\xD6\xFB\x60\x3A\x23\x40\x27\x3D\x22" // 70-7F + "\xF8\x61\x62\x63\x64\x65\x66\x67\x68\x69\x96\xA4\xF3\xAF\xAE\xC5" // 80-8F + "\x8C\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x97\x87\xCE\x93\xF1\xFE" // 90-9F + "\xC8\x7E\x73\x74\x75\x76\x77\x78\x79\x7A\xEF\xC0\xDA\x5B\xF2\xF9" // A0-AF + "\xB5\xB6\xFD\xB7\xB8\xB9\xE6\xBB\xBC\xBD\x8D\xD9\xBF\x5D\xD8\xC4" // B0-BF + "\x7B\x41\x42\x43\x44\x45\x46\x47\x48\x49\xCB\xCA\xBE\xE8\xEC\xED" // C0-CF + "\x7D\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\xA1\xAD\xF5\xF4\xA3\x8F" // D0-DF + "\x5C\xE7\x53\x54\x55\x56\x57\x58\x59\x5A\xA0\x85\x8E\xE9\xE4\xD1" // E0-EF + "\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\xB3\xF7\xF0\xFA\xA7\xFF" // F0-FF + }; +} + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_IBM1047_ISO8859::ACE_IBM1047_ISO8859 (void) +{ +} + +ACE_IBM1047_ISO8859::~ACE_IBM1047_ISO8859 (void) +{ +} + +ACE_CDR::ULong +ACE_IBM1047_ISO8859::ncs () +{ + return 0x10020417; +} + +ACE_CDR::ULong +ACE_IBM1047_ISO8859::tcs () +{ + return 0x00010001; +} + +ACE_CDR::Boolean +ACE_IBM1047_ISO8859::read_char (ACE_InputCDR &in, + ACE_CDR::Char &x) +{ + if (this->read_1 (in, reinterpret_cast (&x))) + { + x = to_IBM1047[x]; + return 1; + } + return 0; +} + +ACE_CDR::Boolean +ACE_IBM1047_ISO8859::read_string (ACE_InputCDR& in, + ACE_CDR::Char *& x) +{ + ACE_CDR::ULong len; + + in.read_ulong (len); + + if (len > 0) + { + ACE_NEW_RETURN (x, + ACE_CDR::Char[len], + 0); + + if (this->read_char_array (in, x, len)) + return 1; + + delete [] x; + } + + x = 0; + return 0; +} + +ACE_CDR::Boolean +ACE_IBM1047_ISO8859::read_char_array (ACE_InputCDR& in, + ACE_CDR::Char* x, + ACE_CDR::ULong len) +{ + if (this->read_array (in, + x, + ACE_CDR::OCTET_SIZE, + ACE_CDR::OCTET_ALIGN, + len)) + { + for (ACE_CDR::ULong i = 0; i != len; ++i) + x[i] = to_IBM1047[x[i]]; + + return 1; + } + + return 0; +} + +ACE_CDR::Boolean +ACE_IBM1047_ISO8859::write_char (ACE_OutputCDR& out, + ACE_CDR::Char x) +{ + return + this->write_1 (out, + reinterpret_cast (&from_IBM1047[x])); +} + +ACE_CDR::Boolean +ACE_IBM1047_ISO8859::write_string (ACE_OutputCDR& out, + ACE_CDR::ULong len, + const ACE_CDR::Char* x) +{ + if (out.write_ulong (len + 1)) + return this->write_char_array (out, x, len + 1); + return 0; +} + +ACE_CDR::Boolean +ACE_IBM1047_ISO8859::write_char_array (ACE_OutputCDR& out, + const ACE_CDR::Char* x, + ACE_CDR::ULong len) +{ + char *buf = 0; + if (this->adjust (out, len, 1, buf) == 0) + { + ACE_OS::memcpy (buf, x, len); + + for (ACE_CDR::ULong i = 0; i != len; ++i) + buf[i] = from_IBM1047[buf[i]]; + + return 1; + } + + this->good_bit(out, 0); + return 0; +} + +// **************************************************************** + +ACE_ISO8859_IBM1047::ACE_ISO8859_IBM1047 (void) +{ +} + +ACE_ISO8859_IBM1047::~ACE_ISO8859_IBM1047 (void) +{ +} + +ACE_CDR::ULong +ACE_ISO8859_IBM1047::ncs () +{ + return 0x00010001; +} + +ACE_CDR::ULong +ACE_ISO8859_IBM1047::tcs () +{ + return 0x10020417; +} + +ACE_CDR::Boolean +ACE_ISO8859_IBM1047::read_char (ACE_InputCDR& in, + ACE_CDR::Char& x) +{ + if (this->read_1 (in, reinterpret_cast (&x))) + { + x = from_IBM1047[x]; + return 1; + } + return 0; +} + +ACE_CDR::Boolean +ACE_ISO8859_IBM1047::read_string (ACE_InputCDR &in, + ACE_CDR::Char *&x) +{ + ACE_CDR::ULong len; + + in.read_ulong (len); + + if (len > 0) + { + ACE_NEW_RETURN (x, + ACE_CDR::Char[len], + 0); + + if (this->read_char_array (in, x, len)) + return 1; + + delete [] x; + } + + x = 0; + return 0; +} + +ACE_CDR::Boolean +ACE_ISO8859_IBM1047::read_char_array (ACE_InputCDR &in, + ACE_CDR::Char *x, + ACE_CDR::ULong len) +{ + if (this->read_array (in, + x, + ACE_CDR::OCTET_SIZE, + ACE_CDR::OCTET_ALIGN, + len)) + { + for (ACE_CDR::ULong i = 0; i != len; ++i) + x[i] = from_IBM1047[x[i]]; + + return 1; + } + + return 0; +} + +ACE_CDR::Boolean +ACE_ISO8859_IBM1047::write_char (ACE_OutputCDR &out, + ACE_CDR::Char x) +{ + return + this->write_1 (out, + reinterpret_cast (&to_IBM1047[x])); +} + +ACE_CDR::Boolean +ACE_ISO8859_IBM1047::write_string (ACE_OutputCDR& out, + ACE_CDR::ULong len, + const ACE_CDR::Char* x) +{ + if (out.write_ulong (len + 1)) + return this->write_char_array (out, x, len + 1); + else + return 0; +} + +ACE_CDR::Boolean +ACE_ISO8859_IBM1047::write_char_array (ACE_OutputCDR &out, + const ACE_CDR::Char *x, + ACE_CDR::ULong len) +{ + char *buf = 0; + + if (this->adjust (out, len, 1, buf) == 0) + { + ACE_OS::memcpy (buf, x, len); + + for (ACE_CDR::ULong i = 0; i != len; ++i) + buf[i] = to_IBM1047[buf[i]]; + + return 1; + } + + this->good_bit (out, 0); + return 0; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_EBCDIC */ diff --git a/dep/acelite/ace/Codeset_IBM1047.h b/dep/acelite/ace/Codeset_IBM1047.h new file mode 100644 index 00000000000..3caa8881fbf --- /dev/null +++ b/dep/acelite/ace/Codeset_IBM1047.h @@ -0,0 +1,127 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Codeset_IBM1047.h + * + * $Id: Codeset_IBM1047.h 81388 2008-04-23 14:02:05Z johnnyw $ + * + * Declares the arrays required to convert between ISO8859 (aka + * Latin/1) and IBM1047 (aka EBCDIC). + * + * @author Jim Rogers (jrogers@viasoft.com) + */ +//============================================================================= + + +#ifndef ACE_CODESET_IMB1047_H +#define ACE_CODESET_IMB1047_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_EBCDIC) + +#include "ace/CDR_Stream.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// **************************************************************** + +/** + * @class ACE_IBM1047_ISO8859 + * + * @brief Codeset translation specialization. + * + * This class performs the codeset translation: + * - Native: IBM_1047 (i.e. EBCDIC) + * - Stream: ISO-8859 (i.e. Latin/1) + */ +class ACE_Export ACE_IBM1047_ISO8859 : public ACE_Char_Codeset_Translator +{ +public: + /// A do nothing constructor. + ACE_IBM1047_ISO8859 (void); + + /// Virtual destruction + virtual ~ACE_IBM1047_ISO8859 (void); + + // = Documented in $ACE_ROOT/ace/CDR_Stream.h + virtual ACE_CDR::Boolean read_char (ACE_InputCDR &, + ACE_CDR::Char &); + virtual ACE_CDR::Boolean read_string (ACE_InputCDR &, + ACE_CDR::Char *&); + virtual ACE_CDR::Boolean read_char_array (ACE_InputCDR &, + ACE_CDR::Char *, + ACE_CDR::ULong); + virtual ACE_CDR::Boolean write_char (ACE_OutputCDR &, + ACE_CDR::Char); + virtual ACE_CDR::Boolean write_string (ACE_OutputCDR &, + ACE_CDR::ULong, + const ACE_CDR::Char *); + virtual ACE_CDR::Boolean write_char_array (ACE_OutputCDR &, + const ACE_CDR::Char *, + ACE_CDR::ULong); + + /// Return the native codeset ID as defined in the OSF code and character + /// set registry, 0x10020417 + virtual ACE_CDR::ULong ncs (); + /// Return the translated codeset ID as defined in the OSF code and character + /// set registry, 0x00010001 + virtual ACE_CDR::ULong tcs (); +}; + +/** + * @class ACE_ISO8859_IBM1047 + * + * @brief Codeset translation specialization. + * + * This class performs the codeset translation: + * - Native: ISO-8859 (i.e. Latin/1) + * - Stream: IBM-1047 (i.e. EBCDIC) + */ +class ACE_Export ACE_ISO8859_IBM1047 : public ACE_Char_Codeset_Translator +{ +public: + /// A do nothing constructor. + ACE_ISO8859_IBM1047 (void); + + /// Virtual destruction + virtual ~ACE_ISO8859_IBM1047 (void); + + // = Documented in $ACE_ROOT/ace/CDR_Stream.h + virtual ACE_CDR::Boolean read_char (ACE_InputCDR &, + ACE_CDR::Char &); + virtual ACE_CDR::Boolean read_string (ACE_InputCDR &, + ACE_CDR::Char *&); + virtual ACE_CDR::Boolean read_char_array (ACE_InputCDR &, + ACE_CDR::Char *, + ACE_CDR::ULong); + virtual ACE_CDR::Boolean write_char (ACE_OutputCDR &, + ACE_CDR::Char); + virtual ACE_CDR::Boolean write_string (ACE_OutputCDR &, + ACE_CDR::ULong, + const ACE_CDR::Char *); + virtual ACE_CDR::Boolean write_char_array (ACE_OutputCDR &, + const ACE_CDR::Char *, + ACE_CDR::ULong); + + /// Return the native codeset ID as defined in the OSF code and character + /// set registry, 0x00010001 + virtual ACE_CDR::ULong ncs (); + /// Return the translated codeset ID as defined in the OSF code and character + /// set registry, 0x10020417 + virtual ACE_CDR::ULong tcs (); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_EBCDIC */ + +#include /**/ "ace/post.h" + +#endif /* ACE_CODESET_IMB1047_H */ diff --git a/dep/acelite/ace/Codeset_Registry.cpp b/dep/acelite/ace/Codeset_Registry.cpp new file mode 100644 index 00000000000..c23ef37231a --- /dev/null +++ b/dep/acelite/ace/Codeset_Registry.cpp @@ -0,0 +1,111 @@ +//============================================================================= +/** + * @file Codeset_Registry.cpp + * + * $Id: Codeset_Registry.cpp 80826 2008-03-04 14:51:23Z wotte $ + * + * emulated codset regstry functions + * + * + * @author Phil Mesnier + */ +//============================================================================= + +#include "ace/Codeset_Registry.h" +#include "ace/OS_Memory.h" +#include "ace/OS_NS_string.h" + +// $Id: Codeset_Registry.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#if !defined (__ACE_INLINE__) +#include "ace/Codeset_Registry.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID (ace, + Codeset_Registry, + "$Id: Codeset_Registry.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +int +ACE_Codeset_Registry::locale_to_registry_i (const ACE_CString &locale, + ACE_CDR::ULong &codeset_id, + ACE_CDR::UShort *num_sets, + ACE_CDR::UShort **char_sets) +{ + registry_entry const *element = 0; + for (size_t i = 0; element == 0 && i < num_registry_entries_; i++) + if (ACE_OS::strcmp (registry_db_[i].loc_name_, locale.c_str ()) == 0) + element = ®istry_db_[i]; + if (element == 0) + return 0; + codeset_id = element->codeset_id_; + if (num_sets != 0) + *num_sets = element->num_sets_; + if (char_sets != 0) + { + ACE_NEW_RETURN (*char_sets,ACE_CDR::UShort[element->num_sets_],0); + ACE_OS::memcpy (*char_sets, element->char_sets_, + element->num_sets_ * sizeof (ACE_CDR::UShort)); + } + return 1; +} + +int +ACE_Codeset_Registry::registry_to_locale_i (ACE_CDR::ULong codeset_id, + ACE_CString &locale, + ACE_CDR::UShort *num_sets, + ACE_CDR::UShort **char_sets) +{ + registry_entry const *element = 0; + for (size_t i = 0; element == 0 && i < num_registry_entries_; i++) + if (codeset_id == registry_db_[i].codeset_id_) + element = ®istry_db_[i]; + if (element == 0) + return 0; + locale.set (element->loc_name_); + if (num_sets != 0) + *num_sets = element->num_sets_; + if (char_sets != 0) + { + ACE_NEW_RETURN (*char_sets,ACE_CDR::UShort[element->num_sets_],0); + ACE_OS::memcpy (*char_sets, element->char_sets_, + element->num_sets_ * sizeof (ACE_CDR::UShort)); + } + return 1; +} + +int +ACE_Codeset_Registry::is_compatible_i (ACE_CDR::ULong codeset_id, + ACE_CDR::ULong other) +{ + registry_entry const *lhs = 0; + registry_entry const *rhs = 0; + for (size_t i = 0; (lhs == 0 || rhs == 0) && i < num_registry_entries_; i++) + { + if (codeset_id == registry_db_[i].codeset_id_) + lhs = ®istry_db_[i]; + if (other == registry_db_[i].codeset_id_) + rhs = ®istry_db_[i]; + } + + if (lhs == 0 || rhs == 0) + return 0; + + for (ACE_CDR::UShort l = 0; l < lhs->num_sets_; l++) + for (ACE_CDR::UShort r = 0; r < rhs->num_sets_; r++) + if (rhs->char_sets_[r] == lhs->char_sets_[l]) + return 1; + return 0; +} + +ACE_CDR::Short +ACE_Codeset_Registry::get_max_bytes_i (ACE_CDR::ULong codeset_id) +{ + for (size_t i = 0; i < num_registry_entries_; i++) + if (codeset_id == registry_db_[i].codeset_id_) + return registry_db_[i].max_bytes_; + return 0; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Codeset_Registry.h b/dep/acelite/ace/Codeset_Registry.h new file mode 100644 index 00000000000..e72c435f82b --- /dev/null +++ b/dep/acelite/ace/Codeset_Registry.h @@ -0,0 +1,104 @@ +// -*- C++ -*- +//============================================================================= +/** + * @file Codeset_Registry.h + * + * $Id: Codeset_Registry.h 81348 2008-04-14 09:00:32Z johnnyw $ + * + * ACE wrapper around access functions for the OSF's DCE codeset registry + * access functions + * + * For environments that intrinsicly support the DCE defined access functions, + * the methods in this class are simply wrappers. On other platforms, emulation + * is provided. The motivation for this class is to support interoperability + * via translators and the CDR streams, primarily in TAO, but this capability + * is not restricted to CORBA. + * + * The emulated functionality supports Open Group RFC #40, currently RFC 40.2, + * www.opengroup.org/tech/rfc/rfc40.2.html + * + * @author Phil Mesnier + */ +//============================================================================= + +#ifndef ACE_CODESET_REGISTRY_H +#define ACE_CODESET_REGISTRY_H + +#include /**/ "ace/pre.h" +#include "ace/SString.h" +#include "ace/CDR_Base.h" +#include "ace/Codeset_Symbols.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_DCE_CODESET_REGISTRY) +#include /**/ +#endif /* ACE_HAS_DCE_CODESET_REGISTRY */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +class ACE_Export ACE_Codeset_Registry +{ +public: + + /// Based on a locale string, find the registry value and optional codeset + /// collection. This wraps the dce_cs_loc_to_rgy function, or emulates it. + static int locale_to_registry (const ACE_CString &locale, + ACE_CDR::ULong &codeset_id, + ACE_CDR::UShort * = 0, + ACE_CDR::UShort ** = 0); + + /// Based on a registry value, find the locale string and optional codeset + /// collection. This wraps the dce_cs_rgy_to_loc function, or emulates it. + static int registry_to_locale (ACE_CDR::ULong codeset_id, + ACE_CString &locale, + ACE_CDR::UShort * = 0, + ACE_CDR::UShort ** = 0); + + /// Tell if two codesets are compatible. This wraps the + /// rpc_cs_char_set_compat_check function. + static int is_compatible (ACE_CDR::ULong codeset_id, + ACE_CDR::ULong other); + + /// Return the max number of bytes required to represent a single character. + /// This wraps the rpc_rgy_get_max_bytes function. + static ACE_CDR::Short get_max_bytes (ACE_CDR::ULong codeset_id); + + enum {max_charsets_ = 5}; +protected: + typedef struct { + const char * desc_; + const char * loc_name_; + ACE_CDR::ULong codeset_id_; + ACE_CDR::UShort num_sets_; + ACE_CDR::UShort char_sets_[max_charsets_]; + ACE_CDR::UShort max_bytes_; + } registry_entry; + +private: + static size_t const num_registry_entries_; + static registry_entry const registry_db_[]; + + static int locale_to_registry_i (const ACE_CString &locale, + ACE_CDR::ULong &codeset_id, + ACE_CDR::UShort * = 0, + ACE_CDR::UShort ** = 0); + static int registry_to_locale_i (ACE_CDR::ULong codeset_id, + ACE_CString &locale, + ACE_CDR::UShort * = 0, + ACE_CDR::UShort ** = 0); + static int is_compatible_i (ACE_CDR::ULong codeset_id, + ACE_CDR::ULong other); + static ACE_CDR::Short get_max_bytes_i (ACE_CDR::ULong codeset_id); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Codeset_Registry.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_CODESET_REGISTRY_H */ diff --git a/dep/acelite/ace/Codeset_Registry.inl b/dep/acelite/ace/Codeset_Registry.inl new file mode 100644 index 00000000000..4419cf5e7fc --- /dev/null +++ b/dep/acelite/ace/Codeset_Registry.inl @@ -0,0 +1,102 @@ +// -*- C++ -*- +//============================================================================= +/** + * @file Codeset_Registry.inl + * + * $Id: Codeset_Registry.inl 80826 2008-03-04 14:51:23Z wotte $ + * + * ACE wrapper around access functions for the OSF's DCE codeset registry + * access functions - the inline functions either call the system supplied + * DCE based codeset regsitry function, or calls the emulation + * + * + * @author Phil Mesnier + */ +//============================================================================= + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE +int +ACE_Codeset_Registry::locale_to_registry(const ACE_CString &locale, + ACE_CDR::ULong &codeset_id, + ACE_CDR::UShort *num_sets, + ACE_CDR::UShort **char_sets) +{ +#if defined (ACE_HAS_DCE_CODESET_REGISTRY) + error_status_t result; + dce_cs_loc_to_rgy (locale.c_str(), + &codeset_id, + num_sets, + char_sets, + &result); + return (result == dce_cs_c_ok) ? 1 : 0; +#else + return ACE_Codeset_Registry::locale_to_registry_i (locale, + codeset_id, + num_sets, + char_sets); +#endif /* ACE_HAS_DCE_CODESET_REGISTRY */ +} + +// based on a registry value, find the locale string and optional codeset +// collection. This wraps the dce_cs_rgy_to_loc function, or emulates it. +ACE_INLINE +int +ACE_Codeset_Registry::registry_to_locale(ACE_CDR::ULong codeset_id, + ACE_CString &locale, + ACE_CDR::UShort *num_sets, + ACE_CDR::UShort **char_sets) +{ +#if defined (ACE_HAS_DCE_CODESET_REGISTRY) + error_status_t result; + char *buffer; + dce_cs_rgy_to_loc (codeset_id, + &buffer, + num_sets, + char_sets, + &result); + locale.set(buffer); // does a copy :-( + free (buffer); + return (result == dce_cs_c_ok) ? 1 : 0; +#else + return ACE_Codeset_Registry::registry_to_locale_i (codeset_id, + locale, + num_sets, + char_sets); +#endif /* ACE_HAS_DCE_CODESET_REGISTRY */ +} + +// Tell if two codesets are compatible. This wraps the +// rpc_cs_char_set_compat_check function. +ACE_INLINE +int +ACE_Codeset_Registry::is_compatible (ACE_CDR::ULong codeset_id, + ACE_CDR::ULong other) +{ +#if defined (ACE_HAS_DCE_CODESET_REGISTRY) + error_status_t result; + rpc_cs_char_set_compat_check(codeset_id,other,&result); + return (result == rpc_s_ok) ? 1 : 0; +#else + return ACE_Codeset_Registry::is_compatible_i (codeset_id,other); +#endif /* ACE_HAS_DCE_CODESET_REGISTRY */ +} + +// Return the max number of bytes required to represent a single character. +// This wraps the rpc_rgy_get_max_bytes function. +ACE_INLINE +ACE_CDR::Short +ACE_Codeset_Registry::get_max_bytes (ACE_CDR::ULong codeset_id) +{ +#if defined (ACE_HAS_DCE_CODESET_REGISTRY) + error_status_t result; + short max_bytes; + rpc_rgy_get_max_bytes(codeset_id,&max_bytes,&result); + return (result == rpc_s_ok) ? (short)max_bytes : 0; +#else + return ACE_Codeset_Registry::get_max_bytes_i (codeset_id); +#endif /* ACE_HAS_DCE_CODESET_REGISTRY */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Codeset_Registry_db.cpp b/dep/acelite/ace/Codeset_Registry_db.cpp new file mode 100644 index 00000000000..32b38631c6f --- /dev/null +++ b/dep/acelite/ace/Codeset_Registry_db.cpp @@ -0,0 +1,33 @@ +/* $Id: Codeset_Registry_db.cpp 81756 2008-05-22 09:47:33Z johnnyw $ + * Codeset registry DB, generated Fri Feb 28 21:01:30 2003 + * source: code_set_registry1.2g.txt + * + * To populate the registry_db, construct a codeset registry text file based + * on the OSF's Character and Code Set Registry. See DCE RFC 40.1 for details + * on obtaining the full text for the current registry. Once you have composed + * a text file containing all the desired codeset information, build and run + * mkcsregdb. The source is in $ACE_ROOT/apps/mkcsregdb. It will generate a new + * copy of this file, with the registry_db_ array properly initialized. + */ + +#include "ace/Codeset_Registry.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_Codeset_Registry::registry_entry const +ACE_Codeset_Registry::registry_db_[] = +{ + {"ISO/IEC 10646-1:1993; UCS-2, Level 1","UCS-2",0x00010100,1,{0x1000},2}, + {"ISO 8859-1:1987; Latin Alphabet No. 1","ISO8859_1",0x00010001,1,{0x0011},1}, + {"IBM-1047 (CCSID 01047); Latin-1 Open System","EBCDIC",0x10020417,1,{0x0011},1}, + {"ISO/IEC 10646-1:1993; UCS-4, Level 1","UCS-4",0x00010104,1,{0x1000},4}, + {"ISO/IEC 10646-1:1993; UTF-16, UCS Transformation Format 16-bit form","UTF-16",0x00010109,1,{0x1000},2}, + {"X/Open UTF-8; UCS Transformation Format 8 (UTF-8)","UTF-8",0x05010001,1,{0x1000},6}, + {"ISO/IEC 8859-5:1988; Latin-Cyrillic Alphabet","ISO-8859-5",0x00010005,1,{0x0015},1}, + {"IBM-1251 (CCSID 01251); MS Windows Cyrillic","CP1251",0x100204e3,1,{0x0015},1}, + {"IBM-855 (CCSID 04951); Cyrillic Personal Computer","CP855",0x10021357,1,{0x0015},1} +}; + +size_t const ACE_Codeset_Registry::num_registry_entries_ = 9; + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Codeset_Symbols.h b/dep/acelite/ace/Codeset_Symbols.h new file mode 100644 index 00000000000..6ffe198c1a9 --- /dev/null +++ b/dep/acelite/ace/Codeset_Symbols.h @@ -0,0 +1,220 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Codeset_Symbols.h + * + * $Id: Codeset_Symbols.h 80826 2008-03-04 14:51:23Z wotte $ + * + * Symbolic names for codeset ids. + * + * @author Dale Wilson (wilson_d@ociweb.com) + */ +//============================================================================= +#ifndef CODESET_SYMBOLS_H +#define CODESET_SYMBOLS_H + +// These numbers are assigned by the OpenGroup, a database is +// available at +// +// ftp://ftp.opengroup.org/pub/code_set_registry/ +// +// Alas, the database is in a semi-regular text file -- difficult to use. +// The following C/C++-friendly version of the codeset ids was captured +// from Version 1.2g of the registry. +// +#define ACE_CODESET_ID_ISO_8859_1 0x00010001U +#define ACE_CODESET_ID_ISO_8859_2 0x00010002U +#define ACE_CODESET_ID_ISO_8859_3 0x00010003U +#define ACE_CODESET_ID_ISO_8859_4 0x00010004U +#define ACE_CODESET_ID_ISO_8859_5 0x00010005U +#define ACE_CODESET_ID_ISO_8859_6 0x00010006U +#define ACE_CODESET_ID_ISO_8859_7 0x00010007U +#define ACE_CODESET_ID_ISO_8859_8 0x00010008U +#define ACE_CODESET_ID_ISO_8859_9 0x00010009U +#define ACE_CODESET_ID_ISO_8859_10 0x0001000AU +#define ACE_CODESET_ID_ISO_8859_15 0x0001000FU +#define ACE_CODESET_ID_ISO_646 0x00010020U +#define ACE_CODESET_ID_ISO_UCS_2_LEVEL_1 0x00010100U +#define ACE_CODESET_ID_ISO_UCS_2_LEVEL_2 0x00010101U +#define ACE_CODESET_ID_ISO_UCS_2_LEVEL_3 0x00010102U +#define ACE_CODESET_ID_ISO_UCS_4_LEVEL_1 0x00010104U +#define ACE_CODESET_ID_ISO_UCS_4_LEVEL_2 0x00010105U +#define ACE_CODESET_ID_ISO_UCS_4_LEVEL_3 0x00010106U +#define ACE_CODESET_ID_ISO_UTF_8 0x00010108U +#define ACE_CODESET_ID_ISO_UTF_16 0x00010109U +#define ACE_CODESET_ID_JIS_X0201 0x00030001U +#define ACE_CODESET_ID_JIS_X0208_1978 0x00030004U +#define ACE_CODESET_ID_JIS_X0208_1983 0x00030005U +#define ACE_CODESET_ID_JIS_X0208_1990 0x00030006U +#define ACE_CODESET_ID_JIS_X0212 0x0003000AU +#define ACE_CODESET_ID_JIS_EUCJP 0x00030010U +#define ACE_CODESET_ID_KS_C5601 0x00040001U +#define ACE_CODESET_ID_KS_C5657 0x00040002U +#define ACE_CODESET_ID_KS_EUCKR 0x0004000AU +#define ACE_CODESET_ID_CNS_11643_1986 0x00050001U +#define ACE_CODESET_ID_CNS_11643_1992 0x00050002U +#define ACE_CODESET_ID_CNS_EUCTW_1991 0x0005000AU +#define ACE_CODESET_ID_CNS_EUCTW_1993 0x00050010U +#define ACE_CODESET_ID_TIS_620_25290X000B0001U +#define ACE_CODESET_ID_TTB_CCDC 0x000D0001U +#define ACE_CODESET_ID_OSF_JAPANESE_UJIS 0x05000010U +#define ACE_CODESET_ID_OSF_JAPANESE_SJIS_1 0x05000011U +#define ACE_CODESET_ID_OSF_JAPANESE_SJIS_2 0x05000012U +#define ACE_CODESET_ID_XOPEN_UTF_8 0x05010001U +#define ACE_CODESET_ID_JVC_EUCJP 0x05020001U +#define ACE_CODESET_ID_JVC_SJIS 0x05020002U +#define ACE_CODESET_ID_DEC_KANJI 0x10000001U +#define ACE_CODESET_ID_SUPER_DEC_KANJI 0x10000002U +#define ACE_CODESET_ID_DEC_SHIFT_JIS 0x10000003U +#define ACE_CODESET_ID_HP_ROMAN8 0x10010001U +#define ACE_CODESET_ID_HP_KANA8 0x10010002U +#define ACE_CODESET_ID_HP_ARABIC8 0x10010003U +#define ACE_CODESET_ID_HP_GREEK8 0x10010004U +#define ACE_CODESET_ID_HP_HEBREW8 0x10010005U +#define ACE_CODESET_ID_HP_TURKISH8 0x10010006U +#define ACE_CODESET_ID_HP15CN 0x10010007U +#define ACE_CODESET_ID_HP_BIG5 0x10010008U +#define ACE_CODESET_ID_HP_JAPANESE15__SJIS_ 0x10010009U +#define ACE_CODESET_ID_HP_SJISHI 0x1001000AU +#define ACE_CODESET_ID_HP_SJISPC 0x1001000BU +#define ACE_CODESET_ID_HP_UJIS 0x1001000CU +#define ACE_CODESET_ID_IBM_037 0x10020025U +#define ACE_CODESET_ID_IBM_273 0x10020111U +#define ACE_CODESET_ID_IBM_277 0x10020115U +#define ACE_CODESET_ID_IBM_278 0x10020116U +#define ACE_CODESET_ID_IBM_280 0x10020118U +#define ACE_CODESET_ID_IBM_282 0x1002011AU +#define ACE_CODESET_ID_IBM_284 0x1002011CU +#define ACE_CODESET_ID_IBM_285 0x1002011DU +#define ACE_CODESET_ID_IBM_290 0x10020122U +#define ACE_CODESET_ID_IBM_297 0x10020129U +#define ACE_CODESET_ID_IBM_300 0x1002012CU +#define ACE_CODESET_ID_IBM_301 0x1002012DU +#define ACE_CODESET_ID_IBM_420 0x100201A4U +#define ACE_CODESET_ID_IBM_424 0x100201A8U +#define ACE_CODESET_ID_IBM_437 0x100201B5U +#define ACE_CODESET_ID_IBM_500 0x100201F4U +#define ACE_CODESET_ID_IBM_833 0x10020341U +#define ACE_CODESET_ID_IBM_834 0x10020342U +#define ACE_CODESET_ID_IBM_835 0x10020343U +#define ACE_CODESET_ID_IBM_836 0x10020344U +#define ACE_CODESET_ID_IBM_837 0x10020345U +#define ACE_CODESET_ID_IBM_838 0x10020346U +#define ACE_CODESET_ID_IBM_839 0x10020347U +#define ACE_CODESET_ID_IBM_850 0x10020352U +#define ACE_CODESET_ID_IBM_852 0x10020354U +#define ACE_CODESET_ID_IBM_855 0x10020357U +#define ACE_CODESET_ID_IBM_856 0x10020358U +#define ACE_CODESET_ID_IBM_857 0x10020359U +#define ACE_CODESET_ID_IBM_861 0x1002035DU +#define ACE_CODESET_ID_IBM_862 0x1002035EU +#define ACE_CODESET_ID_IBM_863 0x1002035FU +#define ACE_CODESET_ID_IBM_864 0x10020360U +#define ACE_CODESET_ID_IBM_866 0x10020362U +#define ACE_CODESET_ID_IBM_868 0x10020364U +#define ACE_CODESET_ID_IBM_869 0x10020365U +#define ACE_CODESET_ID_IBM_870 0x10020366U +#define ACE_CODESET_ID_IBM_871 0x10020367U +#define ACE_CODESET_ID_IBM_874 0x1002036AU +#define ACE_CODESET_ID_IBM_875 0x1002036BU +#define ACE_CODESET_ID_IBM_880 0x10020370U +#define ACE_CODESET_ID_IBM_891 0x1002037BU +#define ACE_CODESET_ID_IBM_896 0x10020380U +#define ACE_CODESET_ID_IBM_897 0x10020381U +#define ACE_CODESET_ID_IBM_903 0x10020387U +#define ACE_CODESET_ID_IBM_904 0x10020388U +#define ACE_CODESET_ID_IBM_918 0x10020396U +#define ACE_CODESET_ID_IBM_921 0x10020399U +#define ACE_CODESET_ID_IBM_922 0x1002039AU +#define ACE_CODESET_ID_IBM_926 0x1002039EU +#define ACE_CODESET_ID_IBM_927 0x1002039FU +#define ACE_CODESET_ID_IBM_928 0x100203A0U +#define ACE_CODESET_ID_IBM_929 0x100203A1U +#define ACE_CODESET_ID_IBM_930 0x100203A2U +#define ACE_CODESET_ID_IBM_932 0x100203A4U +#define ACE_CODESET_ID_IBM_933 0x100203A5U +#define ACE_CODESET_ID_IBM_934 0x100203A6U +#define ACE_CODESET_ID_IBM_935 0x100203A7U +#define ACE_CODESET_ID_IBM_936 0x100203A8U +#define ACE_CODESET_ID_IBM_937 0x100203A9U +#define ACE_CODESET_ID_IBM_938 0x100203AAU +#define ACE_CODESET_ID_IBM_939 0x100203ABU +#define ACE_CODESET_ID_IBM_941 0x100203ADU +#define ACE_CODESET_ID_IBM_942 0x100203AEU +#define ACE_CODESET_ID_IBM_943 0x100203AFU +#define ACE_CODESET_ID_IBM_946 0x100203B2U +#define ACE_CODESET_ID_IBM_947 0x100203B3U +#define ACE_CODESET_ID_IBM_948 0x100203B4U +#define ACE_CODESET_ID_IBM_949 0x100203B5U +#define ACE_CODESET_ID_IBM_950 0x100203B6U +#define ACE_CODESET_ID_IBM_951 0x100203B7U +#define ACE_CODESET_ID_IBM_955 0x100203BBU +#define ACE_CODESET_ID_IBM_964 0x100203C4U +#define ACE_CODESET_ID_IBM_970 0x100203CAU +#define ACE_CODESET_ID_IBM_1006 0x100203EEU +#define ACE_CODESET_ID_IBM_1025 0x10020401U +#define ACE_CODESET_ID_IBM_1026 0x10020402U +#define ACE_CODESET_ID_IBM_1027 0x10020403U +#define ACE_CODESET_ID_IBM_1040 0x10020410U +#define ACE_CODESET_ID_IBM_1041 0x10020411U +#define ACE_CODESET_ID_IBM_1043 0x10020413U +#define ACE_CODESET_ID_IBM_1046 0x10020416U +#define ACE_CODESET_ID_IBM_1047 0x10020417U +#define ACE_CODESET_ID_IBM_1088 0x10020440U +#define ACE_CODESET_ID_IBM_1097 0x10020449U +#define ACE_CODESET_ID_IBM_1098 0x1002044AU +#define ACE_CODESET_ID_IBM_1112 0x10020458U +#define ACE_CODESET_ID_IBM_1114 0x1002045AU +#define ACE_CODESET_ID_IBM_1115 0x1002045BU +#define ACE_CODESET_ID_IBM_1122 0x10020462U +#define ACE_CODESET_ID_IBM_1250 0x100204E2U +#define ACE_CODESET_ID_IBM_1251 0x100204E3U +#define ACE_CODESET_ID_IBM_1252 0x100204E4U +#define ACE_CODESET_ID_IBM_1253 0x100204E5U +#define ACE_CODESET_ID_IBM_1254 0x100204E6U +#define ACE_CODESET_ID_IBM_1255 0x100204E7U +#define ACE_CODESET_ID_IBM_1256 0x100204E8U +#define ACE_CODESET_ID_IBM_1257 0x100204E9U +#define ACE_CODESET_ID_IBM_1380 0x10020564U +#define ACE_CODESET_ID_IBM_1381 0x10020565U +#define ACE_CODESET_ID_IBM_1383 0x10020567U +#define ACE_CODESET_ID_IBM_4396 0x1002112CU +#define ACE_CODESET_ID_IBM_4946 0x10021352U +#define ACE_CODESET_ID_IBM_4948 0x10021354U +#define ACE_CODESET_ID_IBM_4951 0x10021357U +#define ACE_CODESET_ID_IBM_4952 0x10021358U +#define ACE_CODESET_ID_IBM_4953 0x10021359U +#define ACE_CODESET_ID_IBM_4960 0x10021360U +#define ACE_CODESET_ID_IBM_4964 0x10021364U +#define ACE_CODESET_ID_IBM_4965 0x10021365U +#define ACE_CODESET_ID_IBM_5026 0x100213A2U +#define ACE_CODESET_ID_IBM_5031 0x100213A7U +#define ACE_CODESET_ID_IBM_5035 0x100213ABU +#define ACE_CODESET_ID_IBM_5048 0x100213B8U +#define ACE_CODESET_ID_IBM_5049 0x100213B9U +#define ACE_CODESET_ID_IBM_5067 0x100213CBU +#define ACE_CODESET_ID_IBM_8612 0x100221A4U +#define ACE_CODESET_ID_IBM_9025 0x10022341U +#define ACE_CODESET_ID_IBM_9026 0x10022342U +#define ACE_CODESET_ID_IBM_9030 0x10022346U +#define ACE_CODESET_ID_IBM_9056 0x10022360U +#define ACE_CODESET_ID_IBM_9066 0x1002236AU +#define ACE_CODESET_ID_IBM_9125 0x100223A5U +#define ACE_CODESET_ID_IBM_25426 0x10026352U +#define ACE_CODESET_ID_IBM_25432 0x10026358U +#define ACE_CODESET_ID_IBM_1042 0x10026412U +#define ACE_CODESET_ID_IBM_28709 0x10027025U +#define ACE_CODESET_ID_IBM_33624 0x10028358U +#define ACE_CODESET_ID_IBM_33722 0x100283BAU +#define ACE_CODESET_ID_HTCSJIS 0x10030001U +#define ACE_CODESET_ID_HTCUJIS 0x10030002U +#define ACE_CODESET_ID_FUJITSU_U90 0x10040001U +#define ACE_CODESET_ID_FUJITSU_S90 0x10040002U +#define ACE_CODESET_ID_FUJITSU_R90 0x10040003U +#define ACE_CODESET_ID_EBCDIC_ASCII_AND_JEF 0x10040004U +#define ACE_CODESET_ID_EBCDIC_KATAKANA_AND_JEF 0x10040005U +#define ACE_CODESET_ID_EBCDIC_JAPANESE_ENGLISH_AND_JEF 0x10040006U + +#define ACE_CODESET_ID_TAO_BACKWARD_COMPATIBLE 0xf54414F0U +#endif // CODESET_SYMBOLS_H diff --git a/dep/acelite/ace/Condition_Recursive_Thread_Mutex.cpp b/dep/acelite/ace/Condition_Recursive_Thread_Mutex.cpp new file mode 100644 index 00000000000..1f357589f55 --- /dev/null +++ b/dep/acelite/ace/Condition_Recursive_Thread_Mutex.cpp @@ -0,0 +1,129 @@ +// -*- C++ -*- + +/** + * @file Condition_Recursive_Thread_Mutex.cpp + * + * $Id: Condition_Recursive_Thread_Mutex.cpp 89127 2010-02-22 19:58:18Z schmidt $ + * + * Originally in Synch.cpp + * + * @author Douglas C. Schmidt + */ + +#include "ace/Condition_Recursive_Thread_Mutex.h" + +#if defined (ACE_HAS_THREADS) + +#if defined (ACE_HAS_DUMP) +# include "ace/Log_Msg.h" +#endif /* ACE_HAS_DUMP */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +int +ACE_Condition::remove (void) +{ + return ACE_OS::cond_destroy (&this->cond_); +} + +void +ACE_Condition::dump (void) const +{ +#if defined (ACE_HAS_DUMP) +// ACE_TRACE ("ACE_Condition::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + // No dump method for ACE_cond_t even in emulated mode. + // cond_.dump (); + this->mutex_.dump (); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n"))); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +ACE_Condition::~ACE_Condition (void) +{ + this->remove (); +} + +ACE_Condition::ACE_Condition (ACE_Recursive_Thread_Mutex &m) + : mutex_ (m) +{ + ACE_OS::cond_init (&this->cond_); +} + +int +ACE_Condition::wait (const ACE_Time_Value *abstime) +{ + return this->wait (this->mutex_, abstime); +} + +int +ACE_Condition::wait (ACE_Recursive_Thread_Mutex &mutex, + const ACE_Time_Value *abstime) +{ + ACE_recursive_mutex_state mutex_state_holder; + ACE_recursive_thread_mutex_t &recursive_mutex = mutex.lock (); + + if (ACE_OS::recursive_mutex_cond_unlock (&recursive_mutex, + mutex_state_holder) == -1) + return -1; + + // We wait on the condition, specifying the nesting mutex. For platforms + // with ACE_HAS_RECURSIVE_MUTEXES, this is the recursive mutex itself, + // and is the same as recursive_mutex, above. The caller should have been + // holding the lock on entry to this method, and it is still held. + // For other platforms, this is the nesting mutex that guards the + // ACE_recursive_mutex_t internals, and recursive_mutex_cond_unlock() + // returned with the lock held, but waiters primed and waiting to be + // released. At cond_wait below, the mutex will be released. + // On return, it will be reacquired. + int const result = abstime == 0 + ? ACE_OS::cond_wait (&this->cond_, + &mutex.get_nesting_mutex ()) + : ACE_OS::cond_timedwait (&this->cond_, + &mutex.get_nesting_mutex (), + const_cast (abstime)); + // We are holding the mutex, whether the wait succeeded or failed. + // Stash errno (in case it failed) and then we need to reset the + // recursive mutex state to what it was on entry to this method. + // Resetting it may require a wait for another thread to release + // the ACE_recursive_thread_mutex_t if this is a platform without + // ACE_HAS_RECURSIVE_MUTEXES, and recursive_mutex_cond_relock() takes + // care of that. + { + ACE_Errno_Guard error (errno); + ACE_OS::recursive_mutex_cond_relock (&recursive_mutex, + mutex_state_holder); + } + + return result; +} + +int +ACE_Condition::signal (void) +{ + return ACE_OS::cond_signal (&this->cond_); +} + +int +ACE_Condition::broadcast (void) +{ + return ACE_OS::cond_broadcast (&this->cond_); +} + +ACE_Recursive_Thread_Mutex & +ACE_Condition::mutex (void) +{ + return this->mutex_; +} + +ACE_Condition_Recursive_Thread_Mutex::ACE_Condition_Recursive_Thread_Mutex ( + ACE_Recursive_Thread_Mutex &m) : + ACE_Condition (m) +{ +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_THREADS */ diff --git a/dep/acelite/ace/Condition_Recursive_Thread_Mutex.h b/dep/acelite/ace/Condition_Recursive_Thread_Mutex.h new file mode 100644 index 00000000000..ac3177da8c8 --- /dev/null +++ b/dep/acelite/ace/Condition_Recursive_Thread_Mutex.h @@ -0,0 +1,116 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file Condition_Recursive_Thread_Mutex.h + * + * $Id: Condition_Recursive_Thread_Mutex.h 86731 2009-09-17 12:23:48Z johnnyw $ + * + * Moved from Synch.h. + * + * @author Douglas C. Schmidt + */ +//========================================================================== + +#ifndef ACE_CONDITION_RECURSIVE_THREAD_MUTEX_H +#define ACE_CONDITION_RECURSIVE_THREAD_MUTEX_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_HAS_THREADS) +# include "ace/Null_Condition.h" +#else /* ACE_HAS_THREADS */ +#include "ace/Recursive_Thread_Mutex.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template class ACE_Condition; + +/** + * @brief ACE_Condition template specialization written using + * @a ACE_Recursive_Thread_Mutex. This allows threads to block until + * shared data changes state using recursive mutexes. + */ +template<> +class ACE_Export ACE_Condition +{ +public: + /// Initialize the condition variable with a recursive mutex. + ACE_Condition (ACE_Recursive_Thread_Mutex &m); + + /// Implicitly destroy the condition variable. + ~ACE_Condition (void); + + /** + * Explicitly destroy the condition variable. Note that only one + * thread should call this method since it doesn't protect against + * race conditions. + */ + int remove (void); + + /** + * Block on condition, or until absolute time-of-day has passed. If + * abstime == 0 use "blocking" semantics. Else, if @a abstime + * != 0 and the call times out before the condition is signaled + * returns -1 and sets errno to ETIME. + */ + int wait (const ACE_Time_Value *abstime = 0); + + /** + * Block on condition or until absolute time-of-day has passed. If + * abstime == 0 use "blocking" wait() semantics on the recursive @a mutex + * passed as a parameter (this is useful if you need to store the + * in shared memory). Else, if != 0 and the + * call times out before the condition is signaled returns -1 + * and sets errno to ETIME. + */ + int wait (ACE_Recursive_Thread_Mutex &mutex, + const ACE_Time_Value *abstime = 0); + + /// Signal one waiting thread. + int signal (void); + + /// Signal *all* waiting threads. + int broadcast (void); + + /// Returns a reference to the underlying mutex; + ACE_Recursive_Thread_Mutex &mutex (void); + + /// Dump the state of an object. + void dump (void) const; + +private: + + // = Prevent assignment and copying. + void operator= (const ACE_Condition &); + ACE_Condition (const ACE_Condition &); + +private: + + /// A normal (i.e., non-recursive) condition variable. + ACE_cond_t cond_; + + /// Reference to the recursive mutex. + ACE_Recursive_Thread_Mutex &mutex_; + +}; + +class ACE_Export ACE_Condition_Recursive_Thread_Mutex + : public ACE_Condition +{ +public: + /// Initialize the condition variable with a recursive mutex. + ACE_Condition_Recursive_Thread_Mutex (ACE_Recursive_Thread_Mutex &m); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* !ACE_HAS_THREADS */ + +#include /**/ "ace/post.h" +#endif /* ACE_CONDITION_RECURSIVE_THREAD_MUTEX_H */ diff --git a/dep/acelite/ace/Condition_T.cpp b/dep/acelite/ace/Condition_T.cpp new file mode 100644 index 00000000000..ae75d9ff359 --- /dev/null +++ b/dep/acelite/ace/Condition_T.cpp @@ -0,0 +1,127 @@ +// $Id: Condition_T.cpp 89127 2010-02-22 19:58:18Z schmidt $ + +#ifndef ACE_CONDITION_T_CPP +#define ACE_CONDITION_T_CPP + +#include "ace/Condition_T.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_THREADS) + +#include "ace/Log_Msg.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Condition_T.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Condition) + +template void +ACE_Condition::dump (void) const +{ +#if defined (ACE_HAS_DUMP) +// ACE_TRACE ("ACE_Condition::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n"))); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +template +ACE_Thread_Condition::ACE_Thread_Condition (MUTEX &m, + const ACE_TCHAR *name, + void *arg) + : ACE_Condition (m, USYNC_THREAD, name, arg) +{ +// ACE_TRACE ("ACE_Thread_Condition::ACE_Thread_Condition"); +} + +template void +ACE_Thread_Condition::dump (void) const +{ +#if defined (ACE_HAS_DUMP) +// ACE_TRACE ("ACE_Thread_Condition::dump"); + + ACE_Condition::dump (); +#endif /* ACE_HAS_DUMP */ +} + +template +ACE_Condition::ACE_Condition (MUTEX &m, + int type, + const ACE_TCHAR *name, + void *arg) + : + mutex_ (m) +{ + // ACE_TRACE ("ACE_Condition::ACE_Condition"); + + if (ACE_OS::cond_init (&this->cond_, + (short) type, + name, + arg) != 0) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_Condition::ACE_Condition"))); +} + +template +ACE_Condition::~ACE_Condition (void) +{ + // ACE_TRACE ("ACE_Condition::~ACE_Condition"); + + if (this->remove () == -1) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_Condition::~ACE_Condition"))); +} + +template int +ACE_Condition::wait (void) +{ + // ACE_TRACE ("ACE_Condition::wait"); + return ACE_OS::cond_wait (&this->cond_, + &this->mutex_.lock ()); +} + +template int +ACE_Condition::wait (MUTEX &mutex, + const ACE_Time_Value *abstime) +{ +// ACE_TRACE ("ACE_Condition::wait"); + if (abstime == 0) + { + return ACE_OS::cond_wait (&this->cond_, + &mutex.lock ()); + } + else + { + ACE_Time_Value tv = *abstime; + return ACE_OS::cond_timedwait (&this->cond_, + &mutex.lock (), + &tv); + } +} + +// Peform an "alertable" timed wait. If the argument ABSTIME == 0 +// then we do a regular cond_wait(), else we do a timed wait for up to +// ABSTIME using the Solaris cond_timedwait() function. + +template int +ACE_Condition::wait (const ACE_Time_Value *abstime) +{ +// ACE_TRACE ("ACE_Condition::wait"); + return this->wait (this->mutex_, abstime); +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_THREADS */ + +#endif /* ACE_CONDITION_T_CPP */ diff --git a/dep/acelite/ace/Condition_T.h b/dep/acelite/ace/Condition_T.h new file mode 100644 index 00000000000..936ce821777 --- /dev/null +++ b/dep/acelite/ace/Condition_T.h @@ -0,0 +1,167 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file Condition_T.h + * + * $Id: Condition_T.h 81462 2008-04-28 11:39:40Z johnnyw $ + * + * Moved from Synch.h. + * + * @author Douglas C. Schmidt + */ +//========================================================================== + +#ifndef ACE_CONDITION_T_H +#define ACE_CONDITION_T_H + +#include /**/ "ace/pre.h" + +#include "ace/OS_NS_Thread.h" +#include "ace/Lock.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_THREADS) /* ACE platform supports some form of threading. */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +class ACE_Time_Value; + +/** + * @class ACE_Condition + * + * @brief ACE_Condition variable wrapper, which allows threads to block + * until shared data changes state. + * + * A condition variable enables threads to atomically block and + * test the condition under the protection of a mutual exclu- + * sion lock (mutex) until the condition is satisfied. That is, + * the mutex must have been held by the thread before calling + * wait or signal on the condition. If the condition is false, + * a thread blocks on a condition variable and atomically + * releases the mutex that is waiting for the condition to + * change. If another thread changes the condition, it may wake + * up waiting threads by signaling the associated condition + * variable. The waiting threads, upon awakening, reacquire the + * mutex and re-evaluate the condition. + * Note, you can only parameterize with + * @a ACE_Thread_Mutex, @a ACE_Recursive_Thread_Mutex, or @a ACE_Null_Mutex. + */ +template +class ACE_Condition +{ +public: + // = Initialiation and termination methods. + /// Initialize the condition variable. + ACE_Condition (MUTEX &m, int type = USYNC_THREAD, + const ACE_TCHAR *name = 0, void *arg = 0); + + /// Implicitly destroy the condition variable. + ~ACE_Condition (void); + + // = Lock accessors. + /** + * Block on condition, or until absolute time-of-day has passed. If + * @a abstime == 0 use "blocking" semantics. Else, if @a abstime + * != 0 and the call times out before the condition is signaled + * returns -1 and sets errno to ETIME. + */ + int wait (const ACE_Time_Value *abstime); + + /// Block on condition. + int wait (void); + + /** + * Block on condition or until absolute time-of-day has passed. If + * abstime == 0 use "blocking" wait() semantics on the + * passed as a parameter (this is useful if you need to store the + * in shared memory). Else, if != 0 and the + * call times out before the condition is signaled returns -1 + * and sets errno to ETIME. + */ + int wait (MUTEX &mutex, const ACE_Time_Value *abstime = 0); + + /// Signal one waiting thread. + int signal (void); + + /// Signal *all* waiting threads. + int broadcast (void); + + // = Utility methods. + /// Explicitly destroy the condition variable. + int remove (void); + + /// Returns a reference to the underlying mutex_; + MUTEX &mutex (void); + + /// Dump the state of an object. + void dump (void) const; + + // ACE_ALLOC_HOOK_DECLARE; + // Declare the dynamic allocation hooks. + +protected: + /// Condition variable. + ACE_cond_t cond_; + + /// Reference to mutex lock. + MUTEX &mutex_; + +private: + // = Prevent assignment and initialization. + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Condition &)) + ACE_UNIMPLEMENTED_FUNC (ACE_Condition (const ACE_Condition &)) +}; + +/** + * @class ACE_Thread_Condition + * + * @brief ACE_Condition variable wrapper that works within processes. + * + * A condition variable enables threads to atomically block and + * test the condition under the protection of a mutual exclu- + * sion lock (mutex) until the condition is satisfied. That is, + * the mutex must have been held by the thread before calling + * wait or signal on the condition. If the condition is false, + * a thread blocks on a condition variable and atomically + * releases the mutex that is waiting for the condition to + * change. If another thread changes the condition, it may wake + * up waiting threads by signaling the associated condition + * variable. The waiting threads, upon awakening, reacquire the + * mutex and re-evaluate the condition. + */ +template +class ACE_Thread_Condition : public ACE_Condition +{ +public: + // = Initialization method. + ACE_Thread_Condition (MUTEX &m, const ACE_TCHAR *name = 0, void *arg = 0); + + /// Dump the state of an object. + void dump (void) const; + + // ACE_ALLOC_HOOK_DECLARE; + // Declare the dynamic allocation hooks. +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Condition_T.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Condition_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Condition_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#endif /* ACE_HAS_THREADS */ + +#include /**/ "ace/post.h" +#endif /* ACE_CONDITION_T_H */ diff --git a/dep/acelite/ace/Condition_T.inl b/dep/acelite/ace/Condition_T.inl new file mode 100644 index 00000000000..e3b452734a2 --- /dev/null +++ b/dep/acelite/ace/Condition_T.inl @@ -0,0 +1,51 @@ +// -*- C++ -*- +// +// $Id: Condition_T.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template ACE_INLINE int +ACE_Condition::remove (void) +{ + // ACE_TRACE ("ACE_Condition::remove"); + + // cond_destroy() is called in a loop if the condition variable is + // BUSY. This avoids a condition where a condition is signaled and + // because of some timing problem, the thread that is to be signaled + // has called the cond_wait routine after the signal call. Since + // the condition signal is not queued in any way, deadlock occurs. + + int result = 0; + + while ((result = ACE_OS::cond_destroy (&this->cond_)) == -1 + && errno == EBUSY) + { + ACE_OS::cond_broadcast (&this->cond_); + ACE_OS::thr_yield (); + } + + return result; +} + +template ACE_INLINE MUTEX & +ACE_Condition::mutex (void) +{ + // ACE_TRACE ("ACE_Condition::mutex"); + return this->mutex_; +} + +template ACE_INLINE int +ACE_Condition::signal (void) +{ +// ACE_TRACE ("ACE_Condition::signal"); + return ACE_OS::cond_signal (&this->cond_); +} + +template ACE_INLINE int +ACE_Condition::broadcast (void) +{ +// ACE_TRACE ("ACE_Condition::broadcast"); + return ACE_OS::cond_broadcast (&this->cond_); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Condition_Thread_Mutex.cpp b/dep/acelite/ace/Condition_Thread_Mutex.cpp new file mode 100644 index 00000000000..c9f2620e432 --- /dev/null +++ b/dep/acelite/ace/Condition_Thread_Mutex.cpp @@ -0,0 +1,126 @@ +/* -*- C++ -*- */ +/** + * @file Condition_Thread_Mutex.cpp + * + * $Id: Condition_Thread_Mutex.cpp 80826 2008-03-04 14:51:23Z wotte $ + * + * Originally in Synch.cpp + * + * @author Douglas C. Schmidt + */ + +#include "ace/Condition_Thread_Mutex.h" + +#if defined (ACE_HAS_THREADS) + +#if !defined (__ACE_INLINE__) +#include "ace/Condition_Thread_Mutex.inl" +#endif /* __ACE_INLINE__ */ + +#include "ace/Log_Msg.h" + +ACE_RCSID(ace, Condition_Thread_Mutex, "$Id: Condition_Thread_Mutex.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Condition_Thread_Mutex) + +void +ACE_Condition_Thread_Mutex::dump (void) const +{ +#if defined (ACE_HAS_DUMP) +// ACE_TRACE ("ACE_Condition_Thread_Mutex::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n"))); +#if defined (ACE_WIN32) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("waiters = %d\n"), + this->cond_.waiters ())); +#endif /* ACE_WIN32 */ + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +ACE_Condition_Thread_Mutex::ACE_Condition_Thread_Mutex (ACE_Thread_Mutex &m, + const ACE_TCHAR *name, + void *arg) + : mutex_ (m), + removed_ (false) +{ +// ACE_TRACE ("ACE_Condition_Thread_Mutex::ACE_Condition_Thread_Mutex"); + if (ACE_OS::cond_init (&this->cond_, + (short) USYNC_THREAD, + name, + arg) != 0) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_Condition_Thread_Mutex::ACE_Condition_Thread_Mutex"))); +} + +ACE_Condition_Thread_Mutex:: +ACE_Condition_Thread_Mutex (ACE_Thread_Mutex &m, + ACE_Condition_Attributes &attributes, + const ACE_TCHAR *name, + void *arg) + : mutex_ (m), + removed_ (false) +{ +// ACE_TRACE ("ACE_Condition_Thread_Mutex::ACE_Condition_Thread_Mutex"); + if (ACE_OS::cond_init (&this->cond_, attributes.attributes_, + name, arg) != 0) + ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_Condition_Thread_Mutex::ACE_Condition_Thread_Mutex"))); +} + +ACE_Condition_Thread_Mutex::~ACE_Condition_Thread_Mutex (void) +{ +// ACE_TRACE ("ACE_Condition_Thread_Mutex::~ACE_Condition_Thread_Mutex"); + this->remove (); +} + +// Peform an "alertable" timed wait. If the argument == 0 +// then we do a regular , else we do a timed wait for up to +// using the function. + +int +ACE_Condition_Thread_Mutex::wait (void) +{ +// ACE_TRACE ("ACE_Condition_Thread_Mutex::wait"); + return ACE_OS::cond_wait (&this->cond_, &this->mutex_.lock_); +} + +int +ACE_Condition_Thread_Mutex::wait (ACE_Thread_Mutex &mutex, + const ACE_Time_Value *abstime) +{ +// ACE_TRACE ("ACE_Condition_Thread_Mutex::wait"); + return ACE_OS::cond_timedwait (&this->cond_, + &mutex.lock_, + const_cast (abstime)); +} + +int +ACE_Condition_Thread_Mutex::wait (const ACE_Time_Value *abstime) +{ +// ACE_TRACE ("ACE_Condition_Thread_Mutex::wait"); + return this->wait (this->mutex_, abstime); +} + +int +ACE_Condition_Thread_Mutex::signal (void) +{ +// ACE_TRACE ("ACE_Condition_Thread_Mutex::signal"); + return ACE_OS::cond_signal (&this->cond_); +} + +int +ACE_Condition_Thread_Mutex::broadcast (void) +{ +// ACE_TRACE ("ACE_Condition_Thread_Mutex::broadcast"); + return ACE_OS::cond_broadcast (&this->cond_); +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_THREADS */ diff --git a/dep/acelite/ace/Condition_Thread_Mutex.h b/dep/acelite/ace/Condition_Thread_Mutex.h new file mode 100644 index 00000000000..693ff0820aa --- /dev/null +++ b/dep/acelite/ace/Condition_Thread_Mutex.h @@ -0,0 +1,190 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file Condition_Thread_Mutex.h + * + * $Id: Condition_Thread_Mutex.h 80826 2008-03-04 14:51:23Z wotte $ + * + * Moved from Synch.h. + * + * @author Douglas C. Schmidt + */ +//========================================================================== + +#ifndef ACE_CONDITION_THREAD_MUTEX_H +#define ACE_CONDITION_THREAD_MUTEX_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_HAS_THREADS) +# include "ace/Null_Condition.h" +#else /* ACE_HAS_THREADS */ +// ACE platform supports some form of threading. + +#include "ace/Thread_Mutex.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +class ACE_Time_Value; + +class ACE_Export ACE_Condition_Attributes +{ +public: + /// Constructor + ACE_Condition_Attributes (int type = ACE_DEFAULT_SYNCH_TYPE); + + /// Destructor + ~ACE_Condition_Attributes (void); + +private: + friend class ACE_Condition_Thread_Mutex; + + /// The attributes + ACE_condattr_t attributes_; + +private: + // = Prevent assignment and initialization. + void operator= (const ACE_Condition_Attributes &); + ACE_Condition_Attributes (const ACE_Condition_Attributes &); +}; + +/** + * @class ACE_Condition_Thread_Mutex + * + * @brief ACE_Condition variable wrapper written using ACE_Mutexes This + * allows threads to block until shared data changes state. + * A condition variable enables threads to atomically block and + * test the condition under the protection of a mutual exclu- + * sion lock (mutex) until the condition is satisfied. That is, + * the mutex must have been held by the thread before calling + * wait or signal on the condition. If the condition is false, + * a thread blocks on a condition variable and atomically + * releases the mutex that is waiting for the condition to + * change. If another thread changes the condition, it may wake + * up waiting threads by signaling the associated condition + * variable. The waiting threads, upon awakening, reacquire the + * mutex and re-evaluate the condition. + * + * This should be an instantiation of ACE_Condition but problems + * with compilers precludes this... + */ +class ACE_Export ACE_Condition_Thread_Mutex +{ +public: + /// Initialize the condition variable. + ACE_Condition_Thread_Mutex (ACE_Thread_Mutex &m, + const ACE_TCHAR *name = 0, + void *arg = 0); + + /// Initialize the condition variable. + ACE_Condition_Thread_Mutex (ACE_Thread_Mutex &m, + ACE_Condition_Attributes &attributes, + const ACE_TCHAR *name = 0, + void *arg = 0); + + /// Implicitly destroy the condition variable. + ~ACE_Condition_Thread_Mutex (void); + + /** + * Explicitly destroy the condition variable. Note that only one + * thread should call this method since it doesn't protect against + * race conditions. + */ + int remove (void); + + /** + * Block on condition, or until absolute time-of-day has passed. If + * abstime == 0 use "blocking" semantics. Else, if @a abstime + * != 0 and the call times out before the condition is signaled + * returns -1 and sets errno to ETIME. + */ + int wait (const ACE_Time_Value *abstime); + + /// Block on condition. + int wait (void); + + /** + * Block on condition or until absolute time-of-day has passed. If + * abstime == 0 use "blocking" wait() semantics on the + * passed as a parameter (this is useful if you need to store the + * in shared memory). Else, if @a abstime != 0 and the + * call times out before the condition is signaled returns -1 + * and sets errno to ETIME. + */ + int wait (ACE_Thread_Mutex &mutex, const ACE_Time_Value *abstime = 0); + + /// Signal one waiting thread. + int signal (void); + + /// Signal *all* waiting threads. + int broadcast (void); + + /// Returns a reference to the underlying mutex; + ACE_Thread_Mutex &mutex (void); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + /// Condition variable. + ACE_cond_t cond_; + + /// Reference to mutex lock. + ACE_Thread_Mutex &mutex_; + + /// Keeps track of whether has been called yet to avoid + /// multiple calls, e.g., explicitly and implicitly in the + /// destructor. This flag isn't protected by a lock, so make sure + /// that you don't have multiple threads simultaneously calling + /// on the same object, which is a bad idea anyway... + bool removed_; + +private: + // = Prevent assignment and initialization. + void operator= (const ACE_Condition_Thread_Mutex &); + ACE_Condition_Thread_Mutex (const ACE_Condition_Thread_Mutex &); +}; + +#if 0 +// The following class is commented out since there doesn't +// appear to be a portable and robust means of implementing this +// functionality across platforms. If you know of a portable and +// robust way to implement this functionality please let us know. + +/** + * @class ACE_Process_Condition + * + * @brief ACE_Condition variable wrapper that works across processes. + */ +class ACE_Export ACE_Process_Condition +{ +public: + ACE_Process_Condition (MUTEX &m, const ACE_TCHAR *name = 0, void *arg = 0); + + /// Dump the state of an object. + void dump (void) const; + + // ACE_ALLOC_HOOK_DECLARE; + // Declare the dynamic allocation hooks. +}; +#endif /* 0 */ + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Condition_Thread_Mutex.inl" +#endif /* __ACE_INLINE__ */ + +#endif /* !ACE_HAS_THREADS */ + +#include /**/ "ace/post.h" +#endif /* ACE_CONDITION_THREAD_MUTEX_H */ diff --git a/dep/acelite/ace/Condition_Thread_Mutex.inl b/dep/acelite/ace/Condition_Thread_Mutex.inl new file mode 100644 index 00000000000..851269e4af6 --- /dev/null +++ b/dep/acelite/ace/Condition_Thread_Mutex.inl @@ -0,0 +1,74 @@ +// -*- C++ -*- +// +// $Id: Condition_Thread_Mutex.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE +ACE_Condition_Attributes::ACE_Condition_Attributes (int type) +{ + (void) ACE_OS::condattr_init (this->attributes_, type); +} + +ACE_INLINE +ACE_Condition_Attributes::~ACE_Condition_Attributes (void) +{ + ACE_OS::condattr_destroy (this->attributes_); +} + +ACE_INLINE int +ACE_Condition_Thread_Mutex::remove (void) +{ +// ACE_TRACE ("ACE_Condition_Thread_Mutex::remove"); + + // is called in a loop if the condition variable is + // BUSY. This avoids a condition where a condition is signaled and + // because of some timing problem, the thread that is to be signaled + // has called the cond_wait routine after the signal call. Since + // the condition signal is not queued in any way, deadlock occurs. + + int result = 0; + + if (!this->removed_) + { + this->removed_ = true; + + while ((result = ACE_OS::cond_destroy (&this->cond_)) == -1 + && errno == EBUSY) + { + ACE_OS::cond_broadcast (&this->cond_); + ACE_OS::thr_yield (); + } + } + return result; +} + +ACE_INLINE ACE_Thread_Mutex & +ACE_Condition_Thread_Mutex::mutex (void) +{ +// ACE_TRACE ("ACE_Condition_Thread_Mutex::mutex"); + return this->mutex_; +} + +#if 0 +template void +ACE_Process_Condition::dump (void) const +{ +#if defined (ACE_HAS_DUMP) +// ACE_TRACE ("ACE_Process_Condition::dump"); + + ACE_Condition::dump (); +#endif /* ACE_HAS_DUMP */ +} + +template +ACE_Process_Condition::ACE_Process_Condition (MUTEX &m, + const ACE_TCHAR *name, + void *arg) + : ACE_Condition (m, USYNC_PROCESS, name, arg) +{ +// ACE_TRACE ("ACE_Process_Condition::ACE_Process_Condition"); +} +#endif /* 0 */ + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Configuration.cpp b/dep/acelite/ace/Configuration.cpp new file mode 100644 index 00000000000..1914f2dc651 --- /dev/null +++ b/dep/acelite/ace/Configuration.cpp @@ -0,0 +1,2152 @@ +// $Id: Configuration.cpp 86348 2009-08-04 14:45:29Z shuston $ +#include "ace/Configuration.h" +#include "ace/Auto_Ptr.h" +#include "ace/SString.h" +#include "ace/OS_NS_string.h" +#include "ace/OS_NS_strings.h" +#include "ace/Tokenizer_T.h" + +// Can remove this when import_config and export_config are removed from +// ACE_Configuration. They're deprecated at ACE 5.2. +#include "ace/Configuration_Import_Export.h" + +#if !defined (ACE_LACKS_ACCESS) +# include "ace/OS_NS_unistd.h" +#endif /* ACE_LACKS_ACCESS */ + +#if !defined (__ACE_INLINE__) +#include "ace/Configuration.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_Section_Key_Internal::ACE_Section_Key_Internal (void) + : ref_count_ (0) +{ +} + +ACE_Section_Key_Internal::~ACE_Section_Key_Internal (void) +{ +} + +int +ACE_Section_Key_Internal::add_ref (void) +{ + ++ref_count_; + return 0; +} + +int +ACE_Section_Key_Internal::dec_ref (void) +{ + if (!--ref_count_) + delete this; + return 0; +} + +ACE_Configuration_Section_Key::ACE_Configuration_Section_Key (void) + : key_ (0) +{ +} + +ACE_Configuration_Section_Key::~ACE_Configuration_Section_Key (void) +{ + if (key_) + key_->dec_ref (); +} + +ACE_Configuration_Section_Key::ACE_Configuration_Section_Key (ACE_Section_Key_Internal* key) + : key_ (key) +{ + if (key_) + key_->add_ref (); +} + +ACE_Configuration_Section_Key::ACE_Configuration_Section_Key (const ACE_Configuration_Section_Key& rhs) + : key_ (rhs.key_) +{ + if (key_) + key_->add_ref (); +} + +ACE_Configuration_Section_Key& +ACE_Configuration_Section_Key::operator= (const ACE_Configuration_Section_Key& rhs) +{ + if (this != &rhs) + { + if (key_) + key_->dec_ref (); + + key_ = rhs.key_; + + if (key_) + key_->add_ref (); + } + return *this; +} + +////////////////////////////////////////////////////////////////////////////// + +ACE_TCHAR ACE_Configuration::NULL_String_ = '\0'; + +ACE_Configuration::ACE_Configuration (void) + : root_ () +{ +} + +ACE_Configuration::~ACE_Configuration (void) +{ +} + +ACE_Section_Key_Internal* +ACE_Configuration::get_internal_key (const ACE_Configuration_Section_Key& key) +{ + return key.key_; +} + +int +ACE_Configuration::expand_path (const ACE_Configuration_Section_Key& key, + const ACE_TString& path_in, + ACE_Configuration_Section_Key& key_out, + int create) +{ + // Make a copy of key + ACE_Configuration_Section_Key current_section = key; + ACE_Auto_Basic_Array_Ptr pData (path_in.rep ()); + ACE_Tokenizer parser (pData.get ()); + parser.delimiter_replace ('\\', '\0'); + parser.delimiter_replace ('/', '\0'); + + for (ACE_TCHAR *temp = parser.next (); + temp != 0; + temp = parser.next ()) + { + // Open the section + if (open_section (current_section, + temp, + create, + key_out)) + return -1; + + current_section = key_out; + } + + return 0; + +} + +// import_config and export_config are here for backward compatibility, +// and have been deprecated. +int +ACE_Configuration::export_config (const ACE_TCHAR* filename) +{ + ACE_Registry_ImpExp exporter (*this); + return exporter.export_config (filename); +} + +int +ACE_Configuration::import_config (const ACE_TCHAR* filename) +{ + ACE_Registry_ImpExp importer (*this); + return importer.import_config (filename); +} + +int +ACE_Configuration::validate_name (const ACE_TCHAR* name, int allow_path) +{ + // Invalid character set + const ACE_TCHAR* reject = + allow_path ? ACE_TEXT ("][") : ACE_TEXT ("\\]["); + + // Position of the first invalid character or terminating null. + size_t const pos = ACE_OS::strcspn (name, reject); + + // Check if it is an invalid character. + if (name[pos] != ACE_TEXT ('\0')) + { + errno = EINVAL; + return -1; + } + + // The first character can never be a path separator. + if (name[0] == ACE_TEXT ('\\')) + { + errno = EINVAL; + return -1; + } + + // Validate length. + if (pos == 0 || pos > 255) + { + errno = ENAMETOOLONG; + return -1; + } + + return 0; +} + +int +ACE_Configuration::validate_value_name (const ACE_TCHAR* name) +{ + if (name == 0 || *name == this->NULL_String_) + return 0; + + return this->validate_name (name); +} + +const ACE_Configuration_Section_Key& +ACE_Configuration::root_section (void) const +{ + return root_; +} + +/** + * Determine if the contents of this object is the same as the + * contents of the object on the right hand side. + * Returns 1 (True) if they are equal and 0 (False) if they are not equal + */ +bool +ACE_Configuration::operator== (const ACE_Configuration& rhs) const +{ + bool rc = true; + int sectionIndex = 0; + ACE_TString sectionName; + ACE_Configuration *nonconst_this = const_cast (this); + ACE_Configuration &nonconst_rhs = const_cast (rhs); + + const ACE_Configuration_Section_Key& rhsRoot = rhs.root_section (); + ACE_Configuration_Section_Key rhsSection; + ACE_Configuration_Section_Key thisSection; + + // loop through each section in this object + while ((rc) && (nonconst_this->enumerate_sections (this->root_, + sectionIndex, + sectionName) == 0)) + { + // find that section in the rhs object + if (nonconst_rhs.open_section (rhsRoot, + sectionName.c_str (), + 0, + rhsSection) != 0) + { + // If the rhs object does not contain the section then we are + // not equal. + rc = false; + } + else if (nonconst_this->open_section (this->root_, + sectionName.c_str (), + 0, + thisSection) != 0) + { + // if there is some error opening the section in this object + rc = false; + } + else + { + // Well the sections match + int valueIndex = 0; + ACE_TString valueName; + VALUETYPE valueType; + VALUETYPE rhsType; + + // Enumerate each value in this section + while ((rc) && nonconst_this->enumerate_values (thisSection, + valueIndex, + valueName, + valueType) == 0) + { + // look for the same value in the rhs section + if (nonconst_rhs.find_value (rhsSection, + valueName.c_str (), + rhsType) != 0) + { + // We're not equal if the same value cannot + // be found in the rhs object. + rc = false; + } + else if (valueType != rhsType) + { + // we're not equal if the types do not match. + rc = false; + } + else + { + // finally compare values. + if (valueType == STRING) + { + ACE_TString thisString, rhsString; + if (nonconst_this->get_string_value (thisSection, + valueName.c_str (), + thisString) != 0) + { + // we're not equal if we cannot get this string + rc = false; + } + else if (nonconst_rhs.get_string_value ( + rhsSection, + valueName.c_str (), + rhsString) != 0) + { + // we're not equal if we cannot get rhs string + rc = false; + } + rc = (thisString == rhsString); + } + else if (valueType == INTEGER) + { + u_int thisInt = 0; + u_int rhsInt = 0; + if (nonconst_this->get_integer_value ( + thisSection, + valueName.c_str (), + thisInt) != 0) + { + // we're not equal if we cannot get this int + rc = false; + } + else if (nonconst_rhs.get_integer_value ( + rhsSection, + valueName.c_str (), + rhsInt) != 0) + { + // we're not equal if we cannot get rhs int + rc = false; + } + rc = (thisInt == rhsInt); + } + else if (valueType == BINARY) + { + void* thisData = 0; + void* rhsData = 0; + size_t thisLength = 0; + size_t rhsLength = 0; + if (nonconst_this->get_binary_value (thisSection, + valueName.c_str (), + thisData, + thisLength) != 0) + { + // we're not equal if we cannot get this data + rc = false; + } + else if (nonconst_rhs.get_binary_value ( + rhsSection, + valueName.c_str (), + rhsData, + rhsLength) != 0) + { + // we're not equal if we cannot get this data + rc = false; + } + + rc = (thisLength == rhsLength); + // are the length's the same? + + if (rc) + { + unsigned char* thisCharData = + (unsigned char*)thisData; + unsigned char* rhsCharData = (unsigned char*)rhsData; + // yes, then check each element + for (size_t count = 0; + (rc) && (count < thisLength); + count++) + { + rc = (* (thisCharData + count) == * (rhsCharData + count)); + } + + delete [] thisCharData; + delete [] rhsCharData; + }// end if the length's match + } + // We should never have valueTypes of INVALID, therefore + // we're not comparing them. How would we since we have + // no get operation for invalid types. + // So, if we have them, we guess they are equal. + + }// end else if values match. + + ++valueIndex; + + }// end value while loop + + // look in the rhs for values not in this + valueIndex = 0; + while ((rc) && (nonconst_rhs.enumerate_values (rhsSection, + valueIndex, + valueName, + rhsType) == 0)) + { + // look for the same value in this section + if (nonconst_this->find_value (thisSection, + valueName.c_str (), + valueType) != 0) + { + // We're not equal if the same value cannot + // be found in the rhs object. + rc = false; + } + ++valueIndex; + }// end while for rhs values not in this. + + }// end else if sections match. + + ++sectionIndex; + + }// end section while loop + + // Finally, make sure that there are no sections in rhs that do not + // exist in this + sectionIndex = 0; + while ((rc) + && (nonconst_rhs.enumerate_sections (rhsRoot, + sectionIndex, + sectionName) == 0)) + { + // find the section in this + if (nonconst_this->open_section (this->root_, + sectionName.c_str (), + 0, + thisSection) != 0) + { + // if there is some error opening the section in this object + rc = false; + } + else if (nonconst_rhs.open_section (rhsRoot, + sectionName.c_str (), + 0, + rhsSection) != 0) + { + // If the rhs object does not contain the section then we + // are not equal. + rc = false; + } + ++sectionIndex; + } + return rc; +} + +bool +ACE_Configuration::operator!= (const ACE_Configuration& rhs) const +{ + return !(*this == rhs); +} + +////////////////////////////////////////////////////////////////////////////// + +#if defined (ACE_WIN32) && !defined (ACE_LACKS_WIN32_REGISTRY) + +static const int ACE_DEFAULT_BUFSIZE = 256; + +static const ACE_TCHAR *temp_name (const ACE_TCHAR *name) +{ + if (name && *name == ACE_Configuration::NULL_String_) + return 0; + return name; +} + +ACE_Section_Key_Win32::ACE_Section_Key_Win32 (HKEY hKey) + : hKey_ (hKey) +{ +} + +ACE_Section_Key_Win32::~ACE_Section_Key_Win32 (void) +{ + ::RegCloseKey (hKey_); +} + +////////////////////////////////////////////////////////////////////////////// + +bool +ACE_Configuration_Win32Registry::operator== (const ACE_Configuration_Win32Registry &rhs) const +{ + ACE_UNUSED_ARG (rhs); + return true; +} + +bool +ACE_Configuration_Win32Registry::operator!= (const ACE_Configuration_Win32Registry &rhs) const +{ + ACE_UNUSED_ARG (rhs); + return true; +} + +ACE_Configuration_Win32Registry::ACE_Configuration_Win32Registry (HKEY hKey) +{ + ACE_Section_Key_Win32 *temp = 0; + + ACE_NEW (temp, ACE_Section_Key_Win32 (hKey)); + + root_ = ACE_Configuration_Section_Key (temp); +} + + +ACE_Configuration_Win32Registry::~ACE_Configuration_Win32Registry (void) +{ +} + +int +ACE_Configuration_Win32Registry::open_section (const ACE_Configuration_Section_Key& base, + const ACE_TCHAR* sub_section, + int create, + ACE_Configuration_Section_Key& result) +{ + if (validate_name (sub_section, 1)) + return -1; + + HKEY base_key; + if (load_key (base, base_key)) + return -1; + + int errnum; + HKEY result_key; + if ((errnum = ACE_TEXT_RegOpenKeyEx (base_key, + sub_section, + 0, + KEY_ALL_ACCESS, + &result_key)) != ERROR_SUCCESS) + { + if (!create) + { + errno = errnum; + return -1; + } + + if ((errnum = ACE_TEXT_RegCreateKeyEx (base_key, + sub_section, + 0, + 0, + REG_OPTION_NON_VOLATILE, + KEY_ALL_ACCESS, + 0, + &result_key, + (PDWORD) 0 + )) != ERROR_SUCCESS) + { + errno = errnum; + return -1; + } + } + + ACE_Section_Key_Win32 *temp; + + ACE_NEW_RETURN (temp, ACE_Section_Key_Win32 (result_key), -1); + result = ACE_Configuration_Section_Key (temp); + return 0; +} + +int +ACE_Configuration_Win32Registry::remove_section (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* sub_section, + bool recursive) +{ + if (validate_name (sub_section)) + return -1; + + HKEY base_key; + if (load_key (key, base_key)) + return -1; + + if (recursive) + { + ACE_Configuration_Section_Key section; + if (open_section (key, sub_section, 0, section)) + return -1; + + HKEY sub_key; + if (load_key (section, sub_key)) + return -1; + + ACE_TCHAR name_buffer[ACE_DEFAULT_BUFSIZE]; + DWORD buffer_size = ACE_DEFAULT_BUFSIZE; + // Note we don't increment the index because the + // enumeration becomes invalid if we change the + // subkey, which we do when we delete it. By leaving + // it 0, we always delete the top entry + while (ACE_TEXT_RegEnumKeyEx (sub_key, + 0, + name_buffer, + &buffer_size, + 0, + 0, + 0, + 0) == ERROR_SUCCESS) + { + remove_section (section, name_buffer, true); + buffer_size = ACE_DEFAULT_BUFSIZE; + } + } + + int const errnum = ACE_TEXT_RegDeleteKey (base_key, sub_section); + if (errnum != ERROR_SUCCESS) + { + errno = errnum; + return -1; + } + + return 0; +} + +int +ACE_Configuration_Win32Registry::enumerate_values (const ACE_Configuration_Section_Key& key, + int index, + ACE_TString& name, + VALUETYPE& type) +{ + HKEY base_key; + if (load_key (key, base_key)) + return -1; + + ACE_TCHAR name_buffer[ACE_DEFAULT_BUFSIZE]; + DWORD buffer_size = ACE_DEFAULT_BUFSIZE; + DWORD value_type; + + int rc = ACE_TEXT_RegEnumValue (base_key, + index, + name_buffer, + &buffer_size, + 0, + &value_type, + 0, + 0); + if (rc == ERROR_NO_MORE_ITEMS) + return 1; + else if (rc != ERROR_SUCCESS) + { + errno = rc; + return -1; + } + + name = name_buffer; + + switch (value_type) + { + case REG_BINARY: + type = BINARY; + break; + case REG_SZ: + type = STRING; + break; + case REG_DWORD: + type = INTEGER; + break; + default: + type = INVALID; + } + + return 0; +} + +int +ACE_Configuration_Win32Registry::enumerate_sections (const ACE_Configuration_Section_Key& key, + int index, + ACE_TString& name) +{ + HKEY base_key; + if (load_key (key, base_key)) + return -1; + + ACE_TCHAR name_buffer[ACE_DEFAULT_BUFSIZE]; + DWORD buffer_size = ACE_DEFAULT_BUFSIZE; + int rc = ACE_TEXT_RegEnumKeyEx (base_key, + index, + name_buffer, + &buffer_size, + 0, + 0, + 0, + 0); + if (rc == ERROR_NO_MORE_ITEMS) + return 1; + else if (rc != ERROR_MORE_DATA && rc != ERROR_SUCCESS) + { + errno = rc; + return -1; + } + + name = name_buffer; + + return 0; +} + +int +ACE_Configuration_Win32Registry::set_string_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + const ACE_TString& value) +{ + const ACE_TCHAR *t_name = temp_name (name); + if (validate_value_name (t_name)) + return -1; + + HKEY base_key; + if (load_key (key, base_key)) + return -1; + + int errnum; + DWORD len = static_cast (value.length () + 1); + len *= sizeof (ACE_TCHAR); + if ((errnum = ACE_TEXT_RegSetValueEx (base_key, + t_name, + 0, + REG_SZ, + (BYTE *) value.fast_rep (), + len)) + != ERROR_SUCCESS) + { + errno = errnum; + return -1; + } + + return 0; +} + +int +ACE_Configuration_Win32Registry::set_integer_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + u_int value) +{ + const ACE_TCHAR *t_name = temp_name (name); + if (validate_value_name (t_name)) + return -1; + + HKEY base_key; + if (load_key (key, base_key)) + return -1; + + int errnum; + if ((errnum = ACE_TEXT_RegSetValueEx (base_key, + t_name, + 0, + REG_DWORD, + (BYTE *) &value, + sizeof (value))) != ERROR_SUCCESS) + { + errno = errnum; + return -1; + } + + return 0; +} + +int +ACE_Configuration_Win32Registry::set_binary_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + const void* data, + size_t length) +{ + const ACE_TCHAR *t_name = temp_name (name); + if (validate_value_name (t_name)) + return -1; + + HKEY base_key; + if (load_key (key, base_key)) + return -1; + + int errnum; + if ((errnum = ACE_TEXT_RegSetValueEx (base_key, + t_name, + 0, + REG_BINARY, + (BYTE *) data, + static_cast (length))) + != ERROR_SUCCESS) + { + errno = errnum; + return -1; + } + + return 0; +} + +int +ACE_Configuration_Win32Registry::get_string_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + ACE_TString& value) +{ + const ACE_TCHAR *t_name = temp_name (name); + if (validate_value_name (t_name)) + return -1; + + HKEY base_key; + if (load_key (key, base_key)) + return -1; + + // Get the size of the binary data from windows + int errnum; + DWORD buffer_length = 0; + DWORD type; + if ((errnum = ACE_TEXT_RegQueryValueEx (base_key, + t_name, + 0, + &type, + (BYTE *) 0, + &buffer_length)) != ERROR_SUCCESS) + { + errno = errnum; + return -1; + } + + if (type != REG_SZ) + { + errno = ERROR_INVALID_DATATYPE; + return -1; + } + + ACE_TCHAR *temp = 0; + ACE_NEW_RETURN (temp, + ACE_TCHAR[buffer_length], + -1); + + ACE_Auto_Basic_Array_Ptr buffer (temp); + + if ((errnum = ACE_TEXT_RegQueryValueEx (base_key, + t_name, + 0, + &type, + (BYTE *) buffer.get (), + &buffer_length)) != ERROR_SUCCESS) + { + errno = errnum; + return -1; + } + + value = buffer.get (); + return 0; +} + +int +ACE_Configuration_Win32Registry::get_integer_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + u_int& value) +{ + const ACE_TCHAR *t_name = temp_name (name); + if (validate_value_name (t_name)) + return -1; + + HKEY base_key; + if (load_key (key, base_key)) + return -1; + + int errnum; + DWORD length = sizeof (value); + DWORD type; + if ((errnum = ACE_TEXT_RegQueryValueEx (base_key, + t_name, + 0, + &type, + (BYTE *) &value, + &length)) != ERROR_SUCCESS) + { + errno = errnum; + return -1; + } + + if (type != REG_DWORD) + { + errno = ERROR_INVALID_DATATYPE; + return -1; + } + + return 0; +} + +int +ACE_Configuration_Win32Registry::get_binary_value ( + const ACE_Configuration_Section_Key &key, + const ACE_TCHAR *name, + void *&data, + size_t &length) +{ + const ACE_TCHAR *t_name = temp_name (name); + if (validate_value_name (t_name)) + return -1; + + HKEY base_key; + if (load_key (key, base_key)) + return -1; + + // Get the size of the binary data from windows + int errnum; + DWORD buffer_length = 0; + DWORD type; + if ((errnum = ACE_TEXT_RegQueryValueEx (base_key, + t_name, + 0, + &type, + (BYTE *) 0, + &buffer_length)) != ERROR_SUCCESS) + { + errno = errnum; + return -1; + } + + if (type != REG_BINARY) + { + errno = ERROR_INVALID_DATATYPE; + return -1; + } + + length = buffer_length; + + BYTE * the_data = 0; + ACE_NEW_RETURN (the_data, BYTE[length], -1); + ACE_Auto_Basic_Array_Ptr safe_data (the_data); + + if ((errnum = ACE_TEXT_RegQueryValueEx (base_key, + t_name, + 0, + &type, + the_data, + &buffer_length)) != ERROR_SUCCESS) + { + data = 0; + errno = errnum; + return -1; + } + + data = safe_data.release (); + + return 0; +} + +int +ACE_Configuration_Win32Registry::find_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + VALUETYPE& type_out) +{ + const ACE_TCHAR *t_name = temp_name (name); + if (validate_value_name (t_name)) + return -1; + + HKEY base_key; + if (load_key (key, base_key)) + return -1; + + DWORD buffer_length=0; + DWORD type; + int result=ACE_TEXT_RegQueryValueEx (base_key, + t_name, + 0, + &type, + 0, + &buffer_length); + if (result != ERROR_SUCCESS) + { + errno = result; + return -1; + } + + switch (type) + { + case REG_SZ: + type_out = STRING; + break; + case REG_DWORD: + type_out = INTEGER; + break; + case REG_BINARY: + type_out = BINARY; + break; + default: + return -1; // unknown type + } + + return 0; +} + +int +ACE_Configuration_Win32Registry::remove_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name) +{ + const ACE_TCHAR *t_name = temp_name (name); + if (validate_value_name (t_name)) + return -1; + + HKEY base_key; + if (load_key (key, base_key)) + return -1; + + int errnum; + if ((errnum = ACE_TEXT_RegDeleteValue (base_key, t_name)) != ERROR_SUCCESS) + { + errno = errnum; + return -1; + } + + return 0; +} + + +int +ACE_Configuration_Win32Registry::load_key (const ACE_Configuration_Section_Key& key, + HKEY& hKey) +{ + ACE_Section_Key_Win32* pKey = dynamic_cast (get_internal_key (key)); + if (!pKey) + return -1; + + hKey = pKey->hKey_; + return 0; +} + +HKEY +ACE_Configuration_Win32Registry::resolve_key (HKEY hKey, + const ACE_TCHAR* path, + int create) +{ + HKEY result = 0; + // Make a copy of hKey + int errnum; +#if defined (ACE_HAS_WINCE) + if ((errnum = RegOpenKeyEx (hKey, 0, 0, 0, &result)) != ERROR_SUCCESS) +#else + if ((errnum = RegOpenKey (hKey, 0, &result)) != ERROR_SUCCESS) +#endif // ACE_HAS_WINCE + { + errno = errnum; + return 0; + } + + // recurse through the path + ACE_TCHAR *temp_path = 0; + ACE_NEW_RETURN (temp_path, + ACE_TCHAR[ACE_OS::strlen (path) + 1], + 0); + ACE_Auto_Basic_Array_Ptr pData (temp_path); + ACE_OS::strcpy (pData.get (), path); + ACE_Tokenizer parser (pData.get ()); + parser.delimiter_replace ('\\', '\0'); + parser.delimiter_replace ('/', '\0'); + + for (ACE_TCHAR *temp = parser.next (); + temp != 0; + temp = parser.next ()) + { + // Open the key + HKEY subkey; + +#if defined (ACE_HAS_WINCE) + if ((errnum = ACE_TEXT_RegOpenKeyEx (result, + temp, + 0, + 0, + &subkey)) != ERROR_SUCCESS) +#else + if ((errnum = ACE_TEXT_RegOpenKey (result, + temp, + &subkey)) != ERROR_SUCCESS) +#endif // ACE_HAS_WINCE + { + // try creating it + if (!create || (errnum = ACE_TEXT_RegCreateKeyEx (result, + temp, + 0, + 0, + 0, + KEY_ALL_ACCESS, + 0, + &subkey, + (PDWORD) 0 + )) !=ERROR_SUCCESS) + { + errno = errnum; + // error + ::RegCloseKey (result); + return 0; + } + } + // release our open key handle + ::RegCloseKey (result); + result = subkey; + } + + return result; +} + +#endif /* ACE_WIN32 && !ACE_LACKS_WIN32_REGISTRY */ + +/////////////////////////////////////////////////////////////// + +ACE_Configuration_Value_IntId::ACE_Configuration_Value_IntId (void) + : type_ (ACE_Configuration::INVALID), + length_ (0) +{ + this->data_.ptr_ = 0; +} + +ACE_Configuration_Value_IntId::ACE_Configuration_Value_IntId (ACE_TCHAR* string) + : type_ (ACE_Configuration::STRING), + length_ (0) +{ + this->data_.ptr_ = string; +} + +ACE_Configuration_Value_IntId::ACE_Configuration_Value_IntId (u_int integer) + : type_ (ACE_Configuration::INTEGER), + length_ (0) +{ + this->data_.int_ = integer; +} + +ACE_Configuration_Value_IntId::ACE_Configuration_Value_IntId (void* data, size_t length) + : type_ (ACE_Configuration::BINARY), + length_ (length) +{ + this->data_.ptr_ = data; +} + +ACE_Configuration_Value_IntId::ACE_Configuration_Value_IntId (const ACE_Configuration_Value_IntId& rhs) + : type_ (rhs.type_), + data_ (rhs.data_), + length_ (rhs.length_) +{ +} + +ACE_Configuration_Value_IntId::~ACE_Configuration_Value_IntId (void) +{ +} + +ACE_Configuration_Value_IntId& ACE_Configuration_Value_IntId::operator= (const ACE_Configuration_Value_IntId& rhs) +{ + if (this != &rhs) + { + type_ = rhs.type_; + data_ = rhs.data_; + length_ = rhs.length_; + } + return *this; +} + +void +ACE_Configuration_Value_IntId::free (ACE_Allocator *alloc) +{ + if (this->type_ == ACE_Configuration::STRING + || this->type_ == ACE_Configuration::BINARY) + alloc->free (data_.ptr_); + // Do nothing in other cases... +} + +ACE_Configuration_ExtId::ACE_Configuration_ExtId (void) + : name_ (0) +{ +} + +ACE_Configuration_ExtId::ACE_Configuration_ExtId (const ACE_TCHAR* name) + : name_ (name) +{ +} + +ACE_Configuration_ExtId::ACE_Configuration_ExtId (const ACE_Configuration_ExtId& rhs) + : name_ (rhs.name_) +{ +} + +ACE_Configuration_ExtId::~ACE_Configuration_ExtId (void) +{ +} + +ACE_Configuration_ExtId& ACE_Configuration_ExtId::operator= (const ACE_Configuration_ExtId& rhs) +{ + if (this != &rhs) + name_ = rhs.name_; + + return *this; +} + +bool +ACE_Configuration_ExtId::operator== (const ACE_Configuration_ExtId& rhs) const +{ + return (ACE_OS::strcasecmp (name_, rhs.name_) == 0); +} + +bool +ACE_Configuration_ExtId::operator!= (const ACE_Configuration_ExtId& rhs) const +{ + return !this->operator== (rhs); +} + +u_long +ACE_Configuration_ExtId::hash (void) const +{ + ACE_TString temp (name_, 0, false); + return temp.hash (); +} + +void +ACE_Configuration_ExtId::free (ACE_Allocator *alloc) +{ + alloc->free ((void *) (name_)); +} + +/////////////////////////////////////////////////////////////////////// + +ACE_Configuration_Section_IntId::ACE_Configuration_Section_IntId (void) + : value_hash_map_ (0), + section_hash_map_ (0) +{ +} + +ACE_Configuration_Section_IntId::ACE_Configuration_Section_IntId (VALUE_MAP* value_hash_map, SUBSECTION_MAP* section_hash_map) + : value_hash_map_ (value_hash_map), + section_hash_map_ (section_hash_map) +{ +} + +ACE_Configuration_Section_IntId::ACE_Configuration_Section_IntId (const ACE_Configuration_Section_IntId& rhs) + : value_hash_map_ (rhs.value_hash_map_), + section_hash_map_ (rhs.section_hash_map_) +{ + +} + +ACE_Configuration_Section_IntId::~ACE_Configuration_Section_IntId () +{ +} + +ACE_Configuration_Section_IntId& +ACE_Configuration_Section_IntId::operator= (const ACE_Configuration_Section_IntId& rhs) +{ + if (this != &rhs) + { + value_hash_map_ = rhs.value_hash_map_; + section_hash_map_ = rhs.section_hash_map_; + } + return *this; +} + +void +ACE_Configuration_Section_IntId::free (ACE_Allocator *alloc) +{ + alloc->free ((void *) (value_hash_map_)); + alloc->free ((void *) (section_hash_map_)); +} + +ACE_Configuration_Section_Key_Heap::ACE_Configuration_Section_Key_Heap (const ACE_TCHAR* path) + : path_ (0), + value_iter_ (0), + section_iter_ (0) +{ + path_ = ACE_OS::strdup (path); +} + +ACE_Configuration_Section_Key_Heap::~ACE_Configuration_Section_Key_Heap () +{ + delete value_iter_; + delete section_iter_; + ACE_OS::free (path_); +} + +////////////////////////////////////////////////////////////////////////////// + +ACE_Configuration_Heap::ACE_Configuration_Heap (void) + : allocator_ (0), + index_ (0), + default_map_size_ (0) +{ + ACE_Configuration_Section_Key_Heap *temp = 0; + + ACE_NEW (temp, ACE_Configuration_Section_Key_Heap (ACE_TEXT (""))); + root_ = ACE_Configuration_Section_Key (temp); +} + +ACE_Configuration_Heap::~ACE_Configuration_Heap (void) +{ + if (allocator_) + allocator_->sync (); + + delete allocator_; +} + +int +ACE_Configuration_Heap::open (size_t default_map_size) +{ + if (this->allocator_ != 0) + { + errno = EBUSY; + return -1; + } + + default_map_size_ = default_map_size; + // Create the allocator with the appropriate options. + // The name used for the lock is the same as one used + // for the file. + ACE_NEW_RETURN (this->allocator_, + HEAP_ALLOCATOR (), + -1); + return create_index (); +} + + +int +ACE_Configuration_Heap::open (const ACE_TCHAR* file_name, + void* base_address, + size_t default_map_size) +{ + if (this->allocator_ != 0) + { + errno = EBUSY; + return -1; + } + + default_map_size_ = default_map_size; + + // Make sure that the file name is of the legal length. + if (ACE_OS::strlen (file_name) >= MAXNAMELEN + MAXPATHLEN) + { + errno = ENAMETOOLONG; + return -1; + } + + ACE_MMAP_Memory_Pool::OPTIONS options (base_address); + + // Create the allocator with the appropriate options. The name used + // for the lock is the same as one used for the file. + ACE_NEW_RETURN (this->allocator_, + PERSISTENT_ALLOCATOR (file_name, + file_name, + &options), + -1); + +#if !defined (ACE_LACKS_ACCESS) + // Now check if the backing store has been created successfully. + if (ACE_OS::access (file_name, F_OK) != 0) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("create_index\n")), + -1); +#endif /* ACE_LACKS_ACCESS */ + + return create_index (); +} + +int +ACE_Configuration_Heap::create_index (void) +{ + void *section_index = 0; + + // This is the easy case since if we find hash table in the + // memory-mapped file we know it's already initialized. + if (this->allocator_->find (ACE_CONFIG_SECTION_INDEX, section_index) == 0) + this->index_ = (SECTION_MAP *) section_index; + + // Create a new (because we've just created a new + // memory-mapped file). + else + { + size_t index_size = sizeof (SECTION_MAP); + section_index = this->allocator_->malloc (index_size); + + if (section_index == 0 + || create_index_helper (section_index) == -1 + || this->allocator_->bind (ACE_CONFIG_SECTION_INDEX, + section_index) == -1) + { + // Attempt to clean up. + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("create_index failed\n"))); + this->allocator_->remove (); + return -1; + } + // Add the root section + return new_section (ACE_TEXT (""), root_); + } + return 0; +} + +int +ACE_Configuration_Heap::create_index_helper (void *buffer) +{ + ACE_ASSERT (this->allocator_); + this->index_ = new (buffer) SECTION_MAP (this->allocator_); + return 0; +} + +int +ACE_Configuration_Heap::load_key (const ACE_Configuration_Section_Key& key, + ACE_TString& name) +{ + ACE_ASSERT (this->allocator_); + ACE_Configuration_Section_Key_Heap* pKey = + dynamic_cast (get_internal_key (key)); + + if (!pKey) + { + return -1; + } + + ACE_TString temp (pKey->path_, 0, false); + name.assign_nocopy (temp); + return 0; +} + + +int +ACE_Configuration_Heap::add_section (const ACE_Configuration_Section_Key& base, + const ACE_TCHAR* sub_section, + ACE_Configuration_Section_Key& result) +{ + ACE_ASSERT (this->allocator_); + ACE_TString section; + if (load_key (base, section)) + return -1; + + // Find the base section + ACE_Configuration_ExtId ExtId (section.fast_rep ()); + ACE_Configuration_Section_IntId IntId; + if (index_->find (ExtId, IntId, allocator_)) + return -1; + + // See if this section already exists + ACE_Configuration_ExtId SubSectionExtId (sub_section); + int ignored = 0; + + if (!IntId.section_hash_map_->find (SubSectionExtId, ignored, allocator_)) + { + // already exists! + errno = EEXIST; + return -1; + } + + // Create the new section name + // only prepend a separater if were not at the root + if (section.length ()) + section += ACE_TEXT ("\\"); + + section += sub_section; + + // Add it to the base section + ACE_TCHAR* pers_name = (ACE_TCHAR *) allocator_->malloc ((ACE_OS::strlen (sub_section) + 1) * sizeof (ACE_TCHAR)); + ACE_OS::strcpy (pers_name, sub_section); + ACE_Configuration_ExtId SSExtId (pers_name); + if (IntId.section_hash_map_->bind (SSExtId, ignored, allocator_)) + { + allocator_->free (pers_name); + return -1; + } + return (new_section (section, result)); +} + +int +ACE_Configuration_Heap::new_section (const ACE_TString& section, + ACE_Configuration_Section_Key& result) +{ + ACE_ASSERT (this->allocator_); + // Create a new section and add it to the global list + + // Allocate memory for items to be stored in the table. + size_t section_len = section.length () + 1; + ACE_TCHAR *ptr = (ACE_TCHAR*) this->allocator_->malloc (section_len * sizeof (ACE_TCHAR)); + + int return_value = -1; + + if (ptr == 0) + return -1; + else + { + // Populate memory with data. + ACE_OS::strcpy (ptr, section.fast_rep ()); + + void *value_hash_map = 0; + size_t map_size = sizeof (VALUE_MAP); + value_hash_map = this->allocator_->malloc (map_size); + + // If allocation failed ... + if (value_hash_map == 0) + return -1; + + // Initialize allocated hash map through placement new. + if (value_open_helper (default_map_size_, value_hash_map ) == -1) + { + this->allocator_->free (value_hash_map ); + return -1; + } + + // create the section map + void* section_hash_map = 0; + map_size = sizeof (SUBSECTION_MAP); + section_hash_map = this->allocator_->malloc (map_size); + + // If allocation failed + if (section_hash_map == 0) + return -1; + + // initialize allocated hash map through placement new + if (section_open_helper (default_map_size_, section_hash_map) == -1) + { + this->allocator_->free (value_hash_map ); + this->allocator_->free (section_hash_map); + return -1; + } + + ACE_Configuration_ExtId name (ptr); + ACE_Configuration_Section_IntId entry ((VALUE_MAP*) value_hash_map, + (SUBSECTION_MAP*) section_hash_map); + + // Do a normal bind. This will fail if there's already an + // entry with the same name. + return_value = this->index_->bind (name, entry, this->allocator_); + + if (return_value == 1 /* Entry already existed so bind failed. */ + || return_value == -1 /* Unable to bind for other reasons. */) + { + // Free our dynamically allocated memory. + this->allocator_->free (static_cast (ptr)); + return return_value; + } + + // If bind () succeed, it will automatically sync + // up the map manager entry. However, we must sync up our + // name/value memory. + this->allocator_->sync (ptr, section_len); + } + + // set the result + ACE_Configuration_Section_Key_Heap *temp; + ACE_NEW_RETURN (temp, + ACE_Configuration_Section_Key_Heap (ptr), + -1); + result = ACE_Configuration_Section_Key (temp); + return return_value; +} + +int +ACE_Configuration_Heap::value_open_helper (size_t hash_table_size, + void *buffer) +{ + ACE_ASSERT (this->allocator_); + new (buffer) VALUE_MAP (hash_table_size, this->allocator_); + return 0; +} + +int +ACE_Configuration_Heap::section_open_helper (size_t hash_table_size, + void *buffer) +{ + ACE_ASSERT (this->allocator_); + new (buffer) SUBSECTION_MAP (hash_table_size, this->allocator_); + return 0; +} + +int +ACE_Configuration_Heap::open_section (const ACE_Configuration_Section_Key& base, + const ACE_TCHAR* sub_section, + int create, + ACE_Configuration_Section_Key& result) +{ + ACE_ASSERT (this->allocator_); + if (validate_name (sub_section, 1)) // 1 == allow_path + return -1; + + result = base; + + for (const ACE_TCHAR* separator; + (separator = ACE_OS::strchr (sub_section, ACE_TEXT ('\\'))) != 0; + ) + { + ACE_TString simple_section (sub_section, separator - sub_section); + int ret_val = + open_simple_section (result, simple_section.c_str (), create, result); + if (ret_val) + return ret_val; + sub_section = separator + 1; + } + + return open_simple_section (result, sub_section, create, result); +} + +int +ACE_Configuration_Heap::open_simple_section (const ACE_Configuration_Section_Key& base, + const ACE_TCHAR* sub_section, + int create, + ACE_Configuration_Section_Key& result) +{ + ACE_TString section (0, 0, false); + + if (load_key (base, section)) + { + return -1; + } + + // Only add the \\ if were not at the root + if (section.length ()) + { + section += ACE_TEXT ("\\"); + } + + section += sub_section; + + // resolve the section + ACE_Configuration_ExtId ExtId (section.fast_rep ()); + ACE_Configuration_Section_IntId IntId; + + if (index_->find (ExtId, IntId, allocator_)) + { + if (!create) + { + errno = ENOENT; + return -1; + } + + return add_section (base, sub_section, result); + } + + ACE_Configuration_Section_Key_Heap *temp; + ACE_NEW_RETURN (temp, + ACE_Configuration_Section_Key_Heap (section.fast_rep ()), + -1); + result = ACE_Configuration_Section_Key (temp); + return 0; +} + +int +ACE_Configuration_Heap::remove_section (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* sub_section, + bool recursive) +{ + ACE_ASSERT (this->allocator_); + if (validate_name (sub_section)) + return -1; + + ACE_TString section; + if (load_key (key, section)) + return -1; + + // Find this key + ACE_Configuration_ExtId ParentExtId (section.fast_rep ()); + ACE_Configuration_Section_IntId ParentIntId; + if (index_->find (ParentExtId, ParentIntId, allocator_)) + return -1;// no parent key + + // Find this subkey + if (section.length ()) + section += ACE_TEXT ("\\"); + + section += sub_section; + ACE_Configuration_ExtId SectionExtId (section.fast_rep ()); + SECTION_HASH::ENTRY* section_entry = 0; + SECTION_HASH* hashmap = index_; + if (hashmap->find (SectionExtId, section_entry)) + return -1; + + if (recursive) + { + ACE_Configuration_Section_Key section; + if (open_section (key, sub_section, 0, section)) + return -1; + + int index = 0; + ACE_TString name; + while (!enumerate_sections (section, index, name)) + { + if (remove_section (section, name.fast_rep (), true)) + return -1; + + ++index; + } + } + + // Now make sure we dont have any subkeys + if (section_entry->int_id_.section_hash_map_->current_size ()) + { + errno = ENOTEMPTY; + return -1; + } + + // Now remove subkey from parent key + ACE_Configuration_ExtId SubSExtId (sub_section); + SUBSECTION_HASH::ENTRY* subsection_entry; + if (((SUBSECTION_HASH*)ParentIntId.section_hash_map_)-> + find (SubSExtId, subsection_entry)) + return -1; + + if (ParentIntId.section_hash_map_->unbind (SubSExtId, allocator_)) + return -1; + + subsection_entry->ext_id_.free (allocator_); + + // Remember the pointers so we can free them after we unbind + ACE_Configuration_ExtId ExtIdToFree (section_entry->ext_id_); + ACE_Configuration_Section_IntId IntIdToFree (section_entry->int_id_); + + // iterate over all values and free memory + VALUE_HASH* value_hash_map = section_entry->int_id_.value_hash_map_; + VALUE_HASH::ITERATOR value_iter = value_hash_map->begin (); + while (!value_iter.done ()) + { + VALUE_HASH::ENTRY* value_entry = 0; + if (!value_iter.next (value_entry)) + return 1; + + value_entry->ext_id_.free (allocator_); + value_entry->int_id_.free (allocator_); + + value_iter.advance (); + } + + // remove it + if (index_->unbind (SectionExtId, allocator_)) + return -1; + + value_hash_map->close (); + section_entry->int_id_.section_hash_map_->close (allocator_); + + // Free the memory + ExtIdToFree.free (allocator_); + IntIdToFree.free (allocator_); + + return 0; +} + +int +ACE_Configuration_Heap::enumerate_values (const ACE_Configuration_Section_Key& key, + int index, + ACE_TString& name, + VALUETYPE& type) +{ + ACE_ASSERT (this->allocator_); + ACE_Configuration_Section_Key_Heap* pKey = + dynamic_cast (get_internal_key (key)); + if (!pKey) + return -1; + + name = pKey->path_; + + // resolve the section + ACE_Configuration_ExtId ExtId (pKey->path_); + ACE_Configuration_Section_IntId IntId; + if (index_->find (ExtId, IntId, allocator_)) + return -1; + + // Handle iterator resets + if (index == 0) + { + ACE_Hash_Map_Manager_Ex, + ACE_Equal_To, + ACE_Null_Mutex>* hash_map = IntId.value_hash_map_; + delete pKey->value_iter_; + + ACE_NEW_RETURN (pKey->value_iter_, + VALUE_HASH::ITERATOR (hash_map->begin ()), + -1); + } + + // Get the next entry + ACE_Hash_Map_Entry* entry = 0; + + if (!pKey->value_iter_->next (entry)) + return 1; + + // Return the value of the iterator and advance it + name = entry->ext_id_.name_; + type = entry->int_id_.type_; + pKey->value_iter_->advance (); + + return 0; +} + +int +ACE_Configuration_Heap::enumerate_sections (const ACE_Configuration_Section_Key& key, + int index, + ACE_TString& name) +{ + ACE_ASSERT (this->allocator_); + // cast to a heap section key + ACE_Configuration_Section_Key_Heap* pKey = + dynamic_cast (get_internal_key (key)); + if (!pKey) + return -1; // not a heap key! + + // resolve the section + ACE_Configuration_ExtId ExtId (pKey->path_); + ACE_Configuration_Section_IntId IntId; + if (index_->find (ExtId, IntId, allocator_)) + return -1; // unknown section + + // Handle iterator resets + if (index == 0) + { + if (pKey->section_iter_) + delete pKey->section_iter_; + + ACE_NEW_RETURN (pKey->section_iter_, + SUBSECTION_HASH::ITERATOR (IntId.section_hash_map_->begin ()), + -1); + } + + // Get the next entry + ACE_Hash_Map_Entry* entry = 0; + if (!pKey->section_iter_->next (entry)) + return 1; + + // Return the value of the iterator and advance it + pKey->section_iter_->advance (); + name = entry->ext_id_.name_; + + return 0; +} + +int +ACE_Configuration_Heap::set_string_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + const ACE_TString& value) +{ + ACE_ASSERT (this->allocator_); + const ACE_TCHAR *t_name = name ? name : &this->NULL_String_; + if (validate_value_name (t_name)) + return -1; + + ACE_TString section; + if (load_key (key, section)) + return -1; + + ACE_Configuration_ExtId section_ext (section.fast_rep ()); + ACE_Configuration_Section_IntId section_int; + if (index_->find (section_ext, section_int, allocator_)) + return -1; + + // Get the entry for this item (if it exists) + VALUE_HASH::ENTRY* entry = 0; + ACE_Configuration_ExtId item_name (t_name); + if (section_int.value_hash_map_->VALUE_HASH::find (item_name, entry) == 0) + { + // found item, replace it + // Free the old value + entry->int_id_.free (allocator_); + // Allocate the new value in this heap + ACE_TCHAR* pers_value = + (ACE_TCHAR *) allocator_->malloc ((value.length () + 1) * sizeof (ACE_TCHAR)); + ACE_OS::strcpy (pers_value, value.fast_rep ()); + ACE_Configuration_Value_IntId new_value_int (pers_value); + entry->int_id_ = new_value_int; + } + else + { + // it doesn't exist, bind it + ACE_TCHAR* pers_name = + (ACE_TCHAR *) allocator_->malloc ((ACE_OS::strlen (t_name) + 1) * sizeof (ACE_TCHAR)); + ACE_OS::strcpy (pers_name, t_name); + ACE_TCHAR* pers_value = + (ACE_TCHAR *) allocator_->malloc ((value.length () + 1) * sizeof (ACE_TCHAR)); + ACE_OS::strcpy (pers_value, value.fast_rep ()); + ACE_Configuration_ExtId item_name (pers_name); + ACE_Configuration_Value_IntId item_value (pers_value); + if (section_int.value_hash_map_->bind (item_name, item_value, allocator_)) + { + allocator_->free (pers_value); + allocator_->free (pers_name); + return -1; + } + return 0; + } + + return 0; +} + +int +ACE_Configuration_Heap::set_integer_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + u_int value) +{ + ACE_ASSERT (this->allocator_); + const ACE_TCHAR *t_name = name ? name : &this->NULL_String_; + if (validate_value_name (t_name)) + return -1; + + // Get the section name from the key + ACE_TString section; + if (load_key (key, section)) + return -1; + + // Find this section + ACE_Configuration_ExtId section_ext (section.fast_rep ()); + ACE_Configuration_Section_IntId section_int; + if (index_->find (section_ext, section_int, allocator_)) + return -1; // section does not exist + + // Get the entry for this item (if it exists) + VALUE_HASH::ENTRY* entry = 0; + ACE_Configuration_ExtId item_name (t_name); + if (section_int.value_hash_map_->VALUE_HASH::find (item_name, entry) == 0) + { + // found item, replace it + ACE_Configuration_Value_IntId new_value_int (value); + entry->int_id_ = new_value_int; + } + else + { + // it doesn't exist, bind it + ACE_TCHAR* pers_name = + (ACE_TCHAR *) allocator_->malloc ((ACE_OS::strlen (t_name) + 1) * sizeof (ACE_TCHAR)); + ACE_OS::strcpy (pers_name, t_name); + ACE_Configuration_ExtId item_name (pers_name); + ACE_Configuration_Value_IntId item_value (value); + if (section_int.value_hash_map_->bind (item_name, item_value, allocator_)) + { + allocator_->free (pers_name); + return -1; + } + return 0; + } + + return 0; +} + +int +ACE_Configuration_Heap::set_binary_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + const void* data, + size_t length) +{ + ACE_ASSERT (this->allocator_); + const ACE_TCHAR *t_name = name ? name : &this->NULL_String_; + if (validate_value_name (t_name)) + return -1; + + // Get the section name from the key + ACE_TString section; + if (load_key (key, section)) + return -1; + + // Find this section + ACE_Configuration_ExtId section_ext (section.fast_rep ()); + ACE_Configuration_Section_IntId section_int; + if (index_->find (section_ext, section_int, allocator_)) + return -1; // section does not exist + + // Get the entry for this item (if it exists) + VALUE_HASH::ENTRY* entry = 0; + ACE_Configuration_ExtId item_name (t_name); + if (section_int.value_hash_map_->VALUE_HASH::find (item_name, entry) == 0) + { + // found item, replace it + // Free the old value + entry->int_id_.free (allocator_); + // Allocate the new value in this heap + ACE_TCHAR* pers_value = (ACE_TCHAR *) allocator_->malloc (length); + ACE_OS::memcpy (pers_value, data, length); + ACE_Configuration_Value_IntId new_value_int (pers_value, length); + entry->int_id_ = new_value_int; + } + else + { + // it doesn't exist, bind it + ACE_TCHAR* pers_name = + (ACE_TCHAR *) allocator_->malloc ((ACE_OS::strlen (t_name) + 1) * sizeof (ACE_TCHAR)); + ACE_OS::strcpy (pers_name, t_name); + ACE_TCHAR* pers_value = (ACE_TCHAR *) allocator_->malloc (length); + ACE_OS::memcpy (pers_value, data, length); + ACE_Configuration_ExtId item_name (pers_name); + ACE_Configuration_Value_IntId item_value (pers_value, length); + if (section_int.value_hash_map_->bind (item_name, item_value, allocator_)) + { + allocator_->free (pers_value); + allocator_->free (pers_name); + return -1; + } + return 0; + } + + return 0; +} + +int +ACE_Configuration_Heap::get_string_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + ACE_TString& value) +{ + ACE_ASSERT (this->allocator_); + const ACE_TCHAR *t_name = name ? name : &this->NULL_String_; + if (validate_value_name (t_name)) + return -1; + + // Get the section name from the key + ACE_TString section; + if (load_key (key, section)) + return -1; + + // Find this section + ACE_Configuration_ExtId ExtId (section.fast_rep ()); + ACE_Configuration_Section_IntId IntId; + if (index_->find (ExtId, IntId, allocator_)) + return -1; // section does not exist + + // See if it exists first + ACE_Configuration_ExtId VExtId (t_name); + ACE_Configuration_Value_IntId VIntId; + if (IntId.value_hash_map_->find (VExtId, VIntId, allocator_)) + return -1; // unknown value + + // Check type + if (VIntId.type_ != ACE_Configuration::STRING) + { + errno = ENOENT; + return -1; + } + + // everythings ok, return the data + value = static_cast (VIntId.data_.ptr_); + return 0; +} + +int +ACE_Configuration_Heap::get_integer_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + u_int& value) +{ + ACE_ASSERT (this->allocator_); + + const ACE_TCHAR *t_name = name ? name : &this->NULL_String_; + if (validate_value_name (t_name)) + return -1; + + // Get the section name from the key + ACE_TString section (0, 0, false); + + if (this->load_key (key, section) != 0) + { + return -1; + } + + // Find this section + ACE_Configuration_ExtId ExtId (section.fast_rep ()); + ACE_Configuration_Section_IntId IntId; + + if (index_->find (ExtId, IntId, allocator_) != 0) + { + return -1; // section does not exist + } + + + // See if it exists first + ACE_Configuration_ExtId VExtId (t_name); + ACE_Configuration_Value_IntId VIntId; + + if (IntId.value_hash_map_->find (VExtId, VIntId, allocator_) != 0) + { + return -1; // unknown value + } + + // Check type + if (VIntId.type_ != ACE_Configuration::INTEGER) + { + errno = ENOENT; + return -1; + } + + // Everythings ok, return the data + value = VIntId.data_.int_; + return 0; +} + +int +ACE_Configuration_Heap::get_binary_value ( + const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + void*& data, + size_t& length) +{ + ACE_ASSERT (this->allocator_); + const ACE_TCHAR *t_name = name ? name : &this->NULL_String_; + if (validate_value_name (t_name)) + return -1; + + // Get the section name from the key + ACE_TString section; + if (load_key (key, section)) + return -1; + + // Find this section + ACE_Configuration_ExtId ExtId (section.fast_rep ()); + ACE_Configuration_Section_IntId IntId; + if (index_->find (ExtId, IntId, allocator_)) + return -1; // section does not exist + + ACE_Configuration_ExtId VExtId (t_name); + ACE_Configuration_Value_IntId VIntId; + // See if it exists first + if (IntId.value_hash_map_->find (VExtId, VIntId, allocator_)) + return -1; // unknown value + + // Check type + if (VIntId.type_ != ACE_Configuration::BINARY) + { + errno = ENOENT; + return -1; + } + + // Make a copy + ACE_NEW_RETURN (data, char[VIntId.length_], -1); + ACE_OS::memcpy (data, VIntId.data_.ptr_, VIntId.length_); + length = VIntId.length_; + return 0; +} + +int +ACE_Configuration_Heap::find_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + VALUETYPE& type_out) +{ + ACE_ASSERT (this->allocator_); + const ACE_TCHAR *t_name = name ? name : &this->NULL_String_; + if (validate_value_name (t_name)) + return -1; + + // Get the section name from the key + ACE_TString section; + if (load_key (key, section)) + return -1; + + // Find this section + ACE_Configuration_ExtId ExtId (section.fast_rep ()); + ACE_Configuration_Section_IntId IntId; + if (index_->find (ExtId, IntId, allocator_)) + return -1; // section does not exist + + // Find it + ACE_Configuration_ExtId ValueExtId (t_name); + VALUE_HASH::ENTRY* value_entry = 0; + if (((VALUE_HASH *) IntId.value_hash_map_)->find (ValueExtId, value_entry)) + return -1; // value does not exist + + type_out = value_entry->int_id_.type_; + return 0; +} + +int +ACE_Configuration_Heap::remove_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name) +{ + ACE_ASSERT (this->allocator_); + const ACE_TCHAR *t_name = name ? name : &this->NULL_String_; + if (validate_value_name (t_name)) + return -1; + + // Get the section name from the key + ACE_TString section; + if (load_key (key, section)) + return -1; + + // Find this section + ACE_Configuration_ExtId ExtId (section.fast_rep ()); + ACE_Configuration_Section_IntId IntId; + if (index_->find (ExtId, IntId, allocator_)) + return -1; // section does not exist + + // Find it + ACE_Configuration_ExtId ValueExtId (t_name); + VALUE_HASH::ENTRY* value_entry = 0; + if (((VALUE_HASH *) IntId.value_hash_map_)->find (ValueExtId, value_entry)) + return -1; + + // free it + value_entry->ext_id_.free (allocator_); + value_entry->int_id_.free (allocator_); + + // Unbind it + if (IntId.value_hash_map_->unbind (ValueExtId, allocator_)) + return -1; + + return 0; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Configuration.h b/dep/acelite/ace/Configuration.h new file mode 100644 index 00000000000..3543619017e --- /dev/null +++ b/dep/acelite/ace/Configuration.h @@ -0,0 +1,919 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file Configuration.h + * + * $Id: Configuration.h 86348 2009-08-04 14:45:29Z shuston $ + * + * @author Chris Hafey + * + * The ACE configuration API provides a portable abstraction for + * program configuration similar to the Microsoft Windows registry. + * The API supports a tree based hierarchy of configuration sections. Each + * section contains other sections or values. Values may contain string, + * unsigned integer and binary data. + * + * @note These classes are not thread safe, if multiple threads use these + * classes, you are responsible for serializing access. + * + * For examples of using this class, see: + * -# The test code in ACE_wrappers/test + * -# wxConfigViewer, a Windows like Registry Editor for ACE_Configuration + * -# TAO's IFR, it makes extensive use of ACE_Configuration + * + * @todo Templatize this class with an ACE_LOCK to provide thread safety + */ +//============================================================================= + +#ifndef ACE_CONFIGURATION_H +#define ACE_CONFIGURATION_H +#include /**/ "ace/pre.h" + +#include "ace/SStringfwd.h" +#include "ace/Hash_Map_With_Allocator_T.h" +#include "ace/Malloc_T.h" +#include "ace/MMAP_Memory_Pool.h" +#include "ace/Local_Memory_Pool.h" +#include "ace/Synch_Traits.h" + + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +// configurable parameters + +#if !defined (ACE_CONFIG_SECTION_INDEX) +# define ACE_CONFIG_SECTION_INDEX "Config_Section_Index" +#endif /* ! ACE_CONFIG_SECTION_INDEX */ + +#if !defined (ACE_DEFAULT_CONFIG_SECTION_SIZE) +#define ACE_DEFAULT_CONFIG_SECTION_SIZE 16 +#endif /* ACE_DEFAULT_CONFIG_SECTION_SIZE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Section_Key_Internal + * + * @internal + * + * @brief A base class for internal handles to section keys for + * configuration implementations + * + * Implementations subclass this base class to represent a + * section key. + */ +class ACE_Export ACE_Section_Key_Internal +{ +public: + /// Virtual destructor, make sure descendants are virtual! + virtual ~ACE_Section_Key_Internal (void); + + /// Increment reference count + virtual int add_ref (void); + + /// Decrement reference count. Will delete this if count gets to 0 + virtual int dec_ref (void); +protected: + ACE_Section_Key_Internal (void); + ACE_Section_Key_Internal (const ACE_Section_Key_Internal& rhs); + ACE_Section_Key_Internal& operator= (ACE_Section_Key_Internal& rhs); + + u_int ref_count_; +}; + +/** + * @class ACE_Configuration_Section_Key + * + * @brief Reference counted wrapper for ACE_Section_Key_Internal. + * + * Reference counted wrapper class for the abstract internal + * section key. A user gets one of these to represent a section + * in the configuration database. + */ +class ACE_Export ACE_Configuration_Section_Key +{ + friend class ACE_Configuration; +public: + /// Default constructor. + ACE_Configuration_Section_Key (void); + + /// Constructor that initializes to a pointer to a concrete internal key. + /** + * @param key The section key to reference. Calls add_ref() with @a key. + */ + explicit ACE_Configuration_Section_Key (ACE_Section_Key_Internal *key); + + /// Copy constructor, increments the reference count on the key. + ACE_Configuration_Section_Key (const ACE_Configuration_Section_Key &rhs); + + /// Destructor, decrements reference count on the referenced key. + ~ACE_Configuration_Section_Key (void); + + /// Assignment operator, increments reference count for this object + /// and decrements it on @a rhs. + ACE_Configuration_Section_Key & + operator= (const ACE_Configuration_Section_Key &rhs); +private: + ACE_Section_Key_Internal *key_; +}; + +/** + * @class ACE_Configuration + * + * @internal + * + * @brief Base class for configuration databases + * + * This class provides an interface for configuration databases. A concrete + * class is required that implements the interface. + * + * @sa ACE_Configuration_Heap + * @sa ACE_Configuration_Win32Registry + */ +class ACE_Export ACE_Configuration +{ +public: + /// Enumeration for the various types of values we can store. + enum VALUETYPE + { + STRING, + INTEGER, + BINARY, + INVALID + }; + + /// Destructor + virtual ~ACE_Configuration (void); + + /// Obtain a reference to the root section of this configuration. + /* + * @return Reference to the configuration's root section. Note that + * it is a const reference. + */ + virtual const ACE_Configuration_Section_Key& root_section (void) const; + + /** + * Opens a named section in an existing section. + * + * @param base Existing section in which to open the named section. + * @param sub_section Name of the section to open. + * @param create If zero, the named section must exist. If non-zero, + * the named section will be created if it does not exist. + * @param result Reference; receives the section key for the new + * section. + * + * @retval 0 for success. + * @retval -1 for error; ACE_OS::last_error() retrieves error code. + */ + virtual int open_section (const ACE_Configuration_Section_Key &base, + const ACE_TCHAR *sub_section, + int create, + ACE_Configuration_Section_Key& result) = 0; + + /// Removes a named section. + /** + * @param key Section key to remove the named section from. + * @param sub_section Name of the section to remove. + * @param recursive If true, any subkeys below @a sub_section are + * removed as well. + * + * @retval 0 for success. + * @retval -1 for error; ACE_OS::last_error() retrieves error code. + */ + virtual int remove_section (const ACE_Configuration_Section_Key &key, + const ACE_TCHAR *sub_section, + bool recursive) = 0; + + /** + * Enumerates through the values in a section. + * + * @param key Section key to iterate through. + * @param index Iteration position. Must be zero on the first call to + * iterate through @a key. Increment @a index by one on each + * successive call to this method. + * @param name Receives the value's name. + * @param type Receives the value's data type. + * + * @note You may not delete or add values while enumerating. If the + * section is modified during enumeration, results are undefined; + * you must restart the enumeration from index 0. + * + * @retval 0 for success, @a name and @a type are valid. + * @retval 1 there are no more values in the section. + * @retval -1 for error; ACE_OS::last_error() retrieves error code. + */ + virtual int enumerate_values (const ACE_Configuration_Section_Key& key, + int index, + ACE_TString& name, + VALUETYPE& type) = 0; + + /** + * Enumerates through the subsections in a section. + * + * @param key Section key to iterate through. + * @param index Iteration position. Must be zero on the first call to + * iterate through @a key. Increment @a index by one on each + * successive call to this method. + * @param name Receives the subsection's name. + * + * @note You may not modify the @a key section while enumerating. If the + * section is modified during enumeration, results are undefined; + * you must restart the enumeration from index 0. + * + * @retval 0 for success, @a name has a valid name. + * @retval 1 there are no more subsections in the section. + * @retval -1 for error; ACE_OS::last_error() retrieves error code. + */ + virtual int enumerate_sections (const ACE_Configuration_Section_Key& key, + int index, ACE_TString& name) = 0; + + /// Sets a string-typed value. + /** + * @param key Configuration section to set the value in. + * @param name Name of the configuration value to set. If a value with + * the specified name exists, it is replaced. + * @param value The string to set the configuration value to. + * + * @retval 0 for success. + * @retval -1 for error; ACE_OS::last_error() retrieves error code. + */ + virtual int set_string_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + const ACE_TString& value) = 0; + + /// Sets a integer-typed value. + /** + * @param key Configuration section to set the value in. + * @param name Name of the configuration value to set. If a value with + * the specified name exists, it is replaced. + * @param value The integer to set the configuration value to. + * + * @retval 0 for success. + * @retval -1 for error; ACE_OS::last_error() retrieves error code. + */ + virtual int set_integer_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + u_int value) = 0; + + /// Sets a binary-typed value. + /** + * @param key Configuration section to set the value in. + * @param name Name of the configuration value to set. If a value with + * the specified name exists, it is replaced. + * @param data Pointer to the binary data for the value. + * @param length Number of bytes for the new value. + * + * @retval 0 for success. + * @retval -1 for error; ACE_OS::last_error() retrieves error code. + */ + virtual int set_binary_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + const void* data, + size_t length) = 0; + + /// Gets a string-typed value. + /** + * @param key Configuration section to get the value from. + * @param name Name of the configuration value to get. + * @param value Receives the configuration value if it exists and + * has type STRING. + * + * @retval 0 for success. + * @retval -1 for error; ACE_OS::last_error() retrieves error code. + */ + virtual int get_string_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + ACE_TString& value) = 0; + + /// Gets an integer-typed value. + /** + * @param key Configuration section to get the value from. + * @param name Name of the configuration value to get. + * @param value Receives the configuration value if it exists and + * has type INTEGER. + * + * @retval 0 for success. + * @retval -1 for error; ACE_OS::last_error() retrieves error code. + */ + virtual int get_integer_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + u_int& value) = 0; + + /// Gets a binary-typed value. + /** + * @param key Configuration section to get the value from. + * @param name Name of the configuration value to get. + * @param data Receives a pointer to memory holding the binary data + * for the value. This method allocates the memory pointed + * to using operator new[]. The caller is responsible for + * freeing the memory using operator delete[]. + * @param length Receives the number of bytes in the value. + * + * @retval 0 for success; caller is responsible for freeing the + * returned memory. + * @retval -1 for error; ACE_OS::last_error() retrieves error code. + */ + virtual int get_binary_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + void*& data, + size_t& length) = 0; + + /** + * Retrieves the type of a named configuration value. + * + * @param key Configuration section to look up the name in. + * @param name Name of the configuration value to get the type of. + * @param type Receives the data type of the named value, if it exists. + * + * @retval 0 for success. + * @retval -1 for error; ACE_OS::last_error() retrieves error code. + */ + virtual int find_value(const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + VALUETYPE& type) = 0; + + /// Removes a named value. + /** + * @param key Configuration section to remove the named value from. + * @param name Name of the configuration value to remove. + * + * @retval 0 for success. + * @retval -1 for error; ACE_OS::last_error() retrieves error code. + */ + virtual int remove_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name) = 0; + + /** + * Expands @a path_in to @a key_out from @a key. If create is true, + * the subsections are created. Returns 0 on success, non zero on + * error The path consists of sections separated by the backslash + * '\' or forward slash '/'. + * Returns 0 on success, -1 if + virtual ~ACE_Section_Key_Win32 (void); + + // Not used + ACE_Section_Key_Win32 (const ACE_Section_Key_Win32& rhs); + ACE_Section_Key_Win32& operator= (const ACE_Section_Key_Win32& rhs); +}; + +/** + * @class ACE_Configuration_Win32Registry + * + * @brief The win32 registry implementation of a configuration database + * + * The win32 implementation basically makes calls through to the + * registry functions. The API is very similar so very little + * work must be done + */ +class ACE_Export ACE_Configuration_Win32Registry : public ACE_Configuration +{ +public: + + /** + * Constructor for registry configuration database. hKey is the + * base registry key to attach to. This class takes ownership of + * hKey, it will invoke on it upon destruction. + */ + explicit ACE_Configuration_Win32Registry (HKEY hKey); + + /// Destructor + virtual ~ACE_Configuration_Win32Registry (void); + + virtual int open_section (const ACE_Configuration_Section_Key& base, + const ACE_TCHAR* sub_section, + int create, + ACE_Configuration_Section_Key& result); + + virtual int remove_section (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* sub_section, + bool recursive); + + virtual int enumerate_values (const ACE_Configuration_Section_Key& key, + int index, + ACE_TString& name, + VALUETYPE& type); + + virtual int enumerate_sections (const ACE_Configuration_Section_Key& key, + int index, + ACE_TString& name); + + virtual int set_string_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + const ACE_TString& value); + + virtual int set_integer_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + u_int value); + + virtual int set_binary_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + const void* data, + size_t length); + + virtual int get_string_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + ACE_TString& value); + + virtual int get_integer_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + u_int& value); + + virtual int get_binary_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + void*& data, + size_t& length); + + virtual int find_value(const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + VALUETYPE& type); + + /// Removes the the value @a name from @a key. returns non zero on error + virtual int remove_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name); + + /** + * This method traverses through . It is useful when + * you want the HKEY for a specific registry key, especially when + * initializing this implementation. Caller is responsible for + * closeing this key when it is no longer used. If create is 1 + * (default) the keys are create if they don't already exist. + * Returns 0 on error + */ + static HKEY resolve_key (HKEY hKey, + const ACE_TCHAR* path, + int create = 1); + virtual bool operator== (const ACE_Configuration_Win32Registry &rhs) const; + virtual bool operator!= (const ACE_Configuration_Win32Registry &rhs) const; + +protected: + + /// Gets the HKEY for a configuration section + int load_key (const ACE_Configuration_Section_Key& key, HKEY& hKey); + + // Not used + ACE_Configuration_Win32Registry (void); + ACE_Configuration_Win32Registry (const ACE_Configuration_Win32Registry& rhs); + ACE_Configuration_Win32Registry& operator= (const ACE_Configuration_Win32Registry& rhs); +}; +#endif /* ACE_WIN32 && !ACE_LACKS_WIN32_REGISTRY */ + +// ACE_Allocator version + +typedef ACE_Allocator_Adapter > + PERSISTENT_ALLOCATOR; +typedef ACE_Allocator_Adapter > + HEAP_ALLOCATOR; + +/** + * @class ACE_Configuration_ExtId + * + * @brief External ID for the section and value hash + * + * Contains a pointer to the section or value name. + */ +class ACE_Export ACE_Configuration_ExtId +{ +public: + /// Defeault ctor + ACE_Configuration_ExtId (void); + + /// Named constructor + explicit ACE_Configuration_ExtId (const ACE_TCHAR* name); + + /// Copy ctor + ACE_Configuration_ExtId (const ACE_Configuration_ExtId& rhs); + + /// destructor + ~ACE_Configuration_ExtId (void); + + /// Assignment operator + ACE_Configuration_ExtId& operator= (const ACE_Configuration_ExtId& rhs); + + /// Equality comparison operator (must match name_). + bool operator== (const ACE_Configuration_ExtId &rhs) const; + + /// Inequality comparison operator. + bool operator!= (const ACE_Configuration_ExtId &rhs) const; + + /// Frees the name of the value. needed since we don't know the + /// allocator name_ was created in + void free (ACE_Allocator *alloc); + + /// hash function is required in order for this class to be usable by + /// ACE_Hash_Map_Manager. + u_long hash (void) const; + + // = Data members. + + const ACE_TCHAR * name_; + + // Accessors + const ACE_TCHAR *name (void); +}; + +typedef ACE_Hash_Map_With_Allocator + SUBSECTION_MAP; +typedef ACE_Hash_Map_Manager_Ex, + ACE_Equal_To, + ACE_Null_Mutex> + SUBSECTION_HASH; + +/// @deprecated Deprecated typedef. Use the SUBSECTION_HASH::ENTRY trait instead. +typedef SUBSECTION_HASH::ENTRY SUBSECTION_ENTRY; + +/** + * @class ACE_Configuration_Value_IntId + * + * @brief The section hash table internal value class + * + * This class is present as the internal portion of a section's + * value hash table It may store string, integer or binary data. + */ +class ACE_Export ACE_Configuration_Value_IntId +{ +public: + /// Default constructor + ACE_Configuration_Value_IntId (void); + + /// String constructor, takes ownership of string + explicit ACE_Configuration_Value_IntId (ACE_TCHAR* string); + + /// Integer constructor + explicit ACE_Configuration_Value_IntId (u_int integer); + + /// Binary constructor, takes ownership of data + ACE_Configuration_Value_IntId (void* data, size_t length); + + /// Copy ctor + ACE_Configuration_Value_IntId (const ACE_Configuration_Value_IntId& rhs); + + /// Destructor + ~ACE_Configuration_Value_IntId (void); + + /// Assignment operator + ACE_Configuration_Value_IntId& operator= ( + const ACE_Configuration_Value_IntId& rhs); + + void free (ACE_Allocator *alloc); + + // = Data members. + + /** + * Points to the string value or binary data or IS the integer + * Length is only used when type_ == BINARY + */ + ACE_Configuration::VALUETYPE type_; + union { + void * ptr_; + u_int int_; + } data_; + size_t length_; +}; + +typedef ACE_Hash_Map_With_Allocator + VALUE_MAP; +typedef ACE_Hash_Map_Manager_Ex, + ACE_Equal_To, + ACE_Null_Mutex> + VALUE_HASH; + +// Deprecated typedef. Use the VALUE_HASH::ENTRY trait instead. +typedef VALUE_HASH::ENTRY VALUE_ENTRY; + +/** + * @class ACE_Configuration_Section_IntId + * + * @brief The internal ID for a section hash table + * + * Contains a hash table containing value name/values + */ +class ACE_Export ACE_Configuration_Section_IntId +{ +public: + /// Default ctor + ACE_Configuration_Section_IntId (void); + + /// Named ctor + ACE_Configuration_Section_IntId (VALUE_MAP* value_hash_map, + SUBSECTION_MAP* section_hash_map); + + /// Copy ctor + ACE_Configuration_Section_IntId (const ACE_Configuration_Section_IntId& rhs); + + /// Destructor + ~ACE_Configuration_Section_IntId (void); + + /// Assignment operator + ACE_Configuration_Section_IntId& operator= ( + const ACE_Configuration_Section_IntId& rhs); + + /// Frees the hash table and all its values + void free (ACE_Allocator *alloc); + + // = Data Members. + VALUE_MAP* value_hash_map_; + + SUBSECTION_MAP* section_hash_map_; +}; + +typedef ACE_Hash_Map_With_Allocator + SECTION_MAP; +typedef ACE_Hash_Map_Manager_Ex, + ACE_Equal_To, + ACE_Null_Mutex> + SECTION_HASH; + +// Deprecated typedef. Use the SECTION_HASH::ENTRY trait instead. +typedef SECTION_HASH::ENTRY SECTION_ENTRY; + +/** + * @class ACE_Configuration_Section_Key_Heap + * + * @brief Internal section key class for heap based configuration + * database. + * + * Contains a value iterator and full path name of section. + */ +class ACE_Export ACE_Configuration_Section_Key_Heap + : public ACE_Section_Key_Internal +{ +public: + /// Constructor based on the full path of the section + ACE_Configuration_Section_Key_Heap (const ACE_TCHAR* path); + + /// The path itself + ACE_TCHAR* path_; + + /// The value iterator + VALUE_HASH::ITERATOR* value_iter_; + + /// The sub section iterator + SUBSECTION_HASH::ITERATOR* section_iter_; +protected: + /// Destructor - will delete the iterators + virtual ~ACE_Configuration_Section_Key_Heap (void); + + // Not used + ACE_Configuration_Section_Key_Heap (const ACE_Configuration_Section_Key_Heap& rhs); + ACE_Configuration_Section_Key_Heap& operator= (const ACE_Configuration_Section_Key_Heap& rhs); +}; + +/** + * @class ACE_Configuration_Heap + * + * @brief The concrete implementation of a allocator based + * configuration database + * + * This class uses ACE's Allocators to manage a memory + * representation of a configuration database. A persistent heap + * may be used to store configurations persistently + * + * @note Before using this class you must call one of the open methods. + * + * @todo + * - Need to investigate what happens if memory mapped file gets mapped to + * a location different than it was created with. + */ +class ACE_Export ACE_Configuration_Heap : public ACE_Configuration +{ +public: + + /// Default ctor + ACE_Configuration_Heap (void); + + /// Destructor + virtual ~ACE_Configuration_Heap (void); + + /** + * Opens a configuration that allocates its memory from a memory-mapped file. + * This makes it possible to persist a configuration to permanent storage. + * This is not the same as exporting the configuration to a file; the + * memory-mapped file is not likely to be very readable by humans. + * + * @param file_name Name of the file to map into memory. + * + * @param base_address Address to map the base of @a file_name to. + * + * @param default_map_size Starting size for the internal hash tables that + * contain configuration information. + * + * @retval 0 for success. + * @retval -1 for error, with errno set to indicate the cause. If open() + * is called multiple times, errno will be @c EBUSY. + */ + int open (const ACE_TCHAR* file_name, + void* base_address = ACE_DEFAULT_BASE_ADDR, + size_t default_map_size = ACE_DEFAULT_CONFIG_SECTION_SIZE); + + /** + * Opens a configuration that allocates memory from the heap. + * + * @param default_map_size Starting size for the internal hash tables that + * contain configuration information. + * + * @retval 0 for success. + * @retval -1 for error, with errno set to indicate the cause. If open() + * is called multiple times, errno will be @c EBUSY. + */ + int open (size_t default_map_size = ACE_DEFAULT_CONFIG_SECTION_SIZE); + + virtual int open_section (const ACE_Configuration_Section_Key& base, + const ACE_TCHAR* sub_section, + int create, ACE_Configuration_Section_Key& result); + + virtual int remove_section (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* sub_section, + bool recursive); + + virtual int enumerate_values (const ACE_Configuration_Section_Key& key, + int index, + ACE_TString& name, + VALUETYPE& type); + + virtual int enumerate_sections (const ACE_Configuration_Section_Key& key, + int index, + ACE_TString& name); + + virtual int set_string_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + const ACE_TString& value); + + virtual int set_integer_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + u_int value); + + virtual int set_binary_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + const void* data, + size_t length); + + virtual int get_string_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + ACE_TString& value); + + virtual int get_integer_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + u_int& value); + + virtual int get_binary_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + void* &data, + size_t &length); + + virtual int find_value(const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name, + VALUETYPE& type); + + /// Removes the the value @a name from @a key. returns non zero on error + virtual int remove_value (const ACE_Configuration_Section_Key& key, + const ACE_TCHAR* name); + +private: + /// @a sub_section may not contain path separators + int open_simple_section (const ACE_Configuration_Section_Key &base, + const ACE_TCHAR *sub_section, + int create, ACE_Configuration_Section_Key &result); + /// Adds a new section + int add_section (const ACE_Configuration_Section_Key &base, + const ACE_TCHAR *sub_section, + ACE_Configuration_Section_Key &result); + + /// Helper for the method. + int create_index (void); + + /// Helper for create_index() method: places hash table into an + /// allocated space. + int create_index_helper (void *buffer); + + int value_open_helper (size_t hash_table_size, void *buffer); + + int section_open_helper (size_t hash_table_size, void *buffer); + + int load_key (const ACE_Configuration_Section_Key& key, ACE_TString& name); + + int new_section (const ACE_TString& section, + ACE_Configuration_Section_Key& result); + + ACE_Configuration_Heap (const ACE_Configuration_Heap& rhs); + ACE_Configuration_Heap& operator= (const ACE_Configuration_Heap& rhs); + + ACE_Allocator *allocator_; + SECTION_MAP *index_; + size_t default_map_size_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Configuration.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIGURATION_H */ diff --git a/dep/acelite/ace/Configuration.inl b/dep/acelite/ace/Configuration.inl new file mode 100644 index 00000000000..19c2c591bf4 --- /dev/null +++ b/dep/acelite/ace/Configuration.inl @@ -0,0 +1,13 @@ +// -*- C++ -*- +// +// $Id: Configuration.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE const ACE_TCHAR* +ACE_Configuration_ExtId::name (void) +{ + return name_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Configuration_Import_Export.cpp b/dep/acelite/ace/Configuration_Import_Export.cpp new file mode 100644 index 00000000000..ae489f05dfa --- /dev/null +++ b/dep/acelite/ace/Configuration_Import_Export.cpp @@ -0,0 +1,670 @@ +// $Id: Configuration_Import_Export.cpp 84565 2009-02-23 08:20:39Z johnnyw $ + +#include "ace/Configuration_Import_Export.h" +#include "ace/OS_Errno.h" +#include "ace/OS_NS_stdio.h" +#include "ace/OS_NS_ctype.h" +#include "ace/OS_NS_string.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_Config_ImpExp_Base::ACE_Config_ImpExp_Base (ACE_Configuration& config) + : config_ (config) +{ +} + +ACE_Config_ImpExp_Base::~ACE_Config_ImpExp_Base (void) +{ +} + +ACE_Registry_ImpExp::ACE_Registry_ImpExp (ACE_Configuration& config) + : ACE_Config_ImpExp_Base (config) +{ +} + +ACE_Registry_ImpExp::~ACE_Registry_ImpExp (void) +{ +} + +// Imports the configuration database from filename. +// No existing data is removed. +int +ACE_Registry_ImpExp::import_config (const ACE_TCHAR* filename) +{ + if (0 == filename) + { + errno = EINVAL; + return -1; + } + FILE* in = ACE_OS::fopen (filename, ACE_TEXT ("r")); + if (!in) + return -1; + + u_int buffer_size = 4096; + u_int read_pos = 0; + ACE_TCHAR *buffer = 0; + ACE_NEW_NORETURN (buffer, ACE_TCHAR[buffer_size]); + if (!buffer) + { + ACE_Errno_Guard guard (errno); + (void) ACE_OS::fclose (in); + return -1; + } + ACE_Configuration_Section_Key section; + ACE_TCHAR *end = 0; + + while (ACE_OS::fgets (buffer+read_pos, buffer_size - read_pos, in)) + { + // Check if we got all the line. + end = ACE_OS::strrchr (buffer + read_pos, + ACE_TEXT ('\n')); // look for end of line + if (!end) // we havn't reach the end of the line yet + { + // allocate a new buffer - double size the previous one + ACE_TCHAR *temp_buffer; + ACE_NEW_NORETURN (temp_buffer, ACE_TCHAR[buffer_size * 2]); + if (!temp_buffer) + { + ACE_Errno_Guard guard (errno); + delete [] buffer; + (void) ACE_OS::fclose (in); + return -1; + } + + // copy the beginnning of the line + ACE_OS::memcpy (temp_buffer, buffer, buffer_size); + read_pos = buffer_size - 1; + buffer_size *= 2; + delete [] buffer; + buffer = temp_buffer; + continue; + } + read_pos = 0; + + // Check for a comment + if (buffer[0] == ACE_TEXT (';') || buffer[0] == ACE_TEXT ('#')) + continue; + + if (buffer[0] == ACE_TEXT ('[')) + { + // We have a new section here, strip out the section name + end = ACE_OS::strrchr (buffer, ACE_TEXT (']')); + if (!end) + { + ACE_OS::fclose (in); + delete [] buffer; + return -3; + } + *end = 0; + + if (config_.expand_path (config_.root_section (), buffer + 1, section, 1)) + { + ACE_OS::fclose (in); + delete [] buffer; + return -3; + } + continue; + } // end if firs char is a [ + + if (buffer[0] == ACE_TEXT ('"')) + { + // we have a value + end = ACE_OS::strchr (buffer+1, '"'); + if (!end) // no closing quote, not a value so just skip it + continue; + + // null terminate the name + *end = 0; + ACE_TCHAR* name = buffer + 1; + end+=2; + // determine the type + if (*end == '\"') + { + // string type + // truncate trailing " + ++end; + ACE_TCHAR* trailing = ACE_OS::strrchr (end, '"'); + if (trailing) + *trailing = 0; + if (config_.set_string_value (section, name, end)) + { + ACE_OS::fclose (in); + delete [] buffer; + return -4; + } + } + else if (ACE_OS::strncmp (end, ACE_TEXT ("dword:"), 6) == 0) + { + // number type + ACE_TCHAR* endptr = 0; + unsigned long value = ACE_OS::strtoul (end + 6, &endptr, 16); + if (config_.set_integer_value (section, name, value)) + { + ACE_OS::fclose (in); + delete [] buffer; + return -4; + } + } + else if (ACE_OS::strncmp (end, ACE_TEXT ("hex:"), 4) == 0) + { + // binary type + size_t string_length = ACE_OS::strlen (end + 4); + // divide by 3 to get the actual buffer length + size_t length = string_length / 3; + size_t remaining = length; + u_char* data = 0; + ACE_NEW_RETURN (data, + u_char[length], + -1); + u_char* out = data; + ACE_TCHAR* inb = end + 4; + ACE_TCHAR* endptr = 0; + while (remaining) + { + u_char charin = (u_char) ACE_OS::strtoul (inb, &endptr, 16); + *out = charin; + ++out; + --remaining; + inb += 3; + } + if (config_.set_binary_value (section, name, data, length)) + { + ACE_OS::fclose (in); + delete [] data; + delete [] buffer; + return -4; + } + else + delete [] data; + } + else + { + // invalid type, ignore + continue; + } + }// end if first char is a " + else + { + // if the first character is not a ", [, ;, or # we may be + // processing a file in the old format. + // Try and process the line as such and if it fails, + // return an error + int rc = process_previous_line_format (buffer, section); + if (rc != 0) + { + ACE_OS::fclose (in); + delete [] buffer; + return rc; + } + } // end if maybe old format + } // end while fgets + + if (ferror (in)) + { + ACE_OS::fclose (in); + delete [] buffer; + return -1; + } + + ACE_OS::fclose (in); + delete [] buffer; + return 0; +} + +// This method exports the entire configuration database to . +// Once the file is opened this method calls 'export_section' passing +// the root section. +int +ACE_Registry_ImpExp::export_config (const ACE_TCHAR* filename) +{ + if (0 == filename) + { + errno = EINVAL; + return -1; + } + int result = -1; + + FILE* out = ACE_OS::fopen (filename, ACE_TEXT ("w")); + if (out) + { + result = this->export_section (config_.root_section (), + ACE_TEXT (""), + out); + // The data may have been buffered and will be flush on close, + // so we need to check that the close succeeds. + if (ACE_OS::fclose (out) < 0) + result = -7; + } + return result; +} + +// Method provided by derived classes in order to write one section +// to the file specified. Called by export_config when exporting +// the entire configuration object. + +int +ACE_Registry_ImpExp::export_section (const ACE_Configuration_Section_Key& section, + const ACE_TString& path, + FILE* out) +{ + // don't export the root + if (path.length ()) + { + // Write out the section header + ACE_TString header = ACE_TEXT ("["); + header += path; + header += ACE_TEXT ("]"); + header += ACE_TEXT ("\n"); + if (ACE_OS::fputs (header.fast_rep (), out) < 0) + return -1; + // Write out each value + int index = 0; + ACE_TString name; + ACE_Configuration::VALUETYPE type; + ACE_TString line; + ACE_TCHAR int_value[32]; + ACE_TCHAR bin_value[3]; + void* binary_data; + size_t binary_length; + ACE_TString string_value; + while (!config_.enumerate_values (section, index, name, type)) + { + line = ACE_TEXT ("\"") + name + ACE_TEXT ("\"="); + switch (type) + { + case ACE_Configuration::INTEGER: + { + u_int value; + if (config_.get_integer_value (section, name.fast_rep (), value)) + return -2; + ACE_OS::sprintf (int_value, ACE_TEXT ("%08x"), value); + line += ACE_TEXT ("dword:"); + line += int_value; + break; + } + case ACE_Configuration::STRING: + { + if (config_.get_string_value (section, + name.fast_rep (), + string_value)) + return -2; + line += ACE_TEXT ("\""); + line += string_value + ACE_TEXT ("\""); + break; + } +#ifdef _WIN32 + case ACE_Configuration::INVALID: + break; // JDO added break. Otherwise INVALID is processed + // like BINARY. If that's correct, please remove the + // break and these comments +#endif + case ACE_Configuration::BINARY: + { + // not supported yet - maybe use BASE64 codeing? + if (config_.get_binary_value (section, + name.fast_rep (), + binary_data, + binary_length)) + return -2; + line += ACE_TEXT ("hex:"); + unsigned char* ptr = (unsigned char*)binary_data; + while (binary_length) + { + if (ptr != binary_data) + { + line += ACE_TEXT (","); + } + ACE_OS::sprintf (bin_value, ACE_TEXT ("%02x"), *ptr); + line += bin_value; + --binary_length; + ++ptr; + } + delete [] (char*) binary_data; + break; + } + default: + return -3; + } + line += ACE_TEXT ("\n"); + if (ACE_OS::fputs (line.fast_rep (), out) < 0) + return -4; + ++index; + } + } + // Export all sub sections + int index = 0; + ACE_TString name; + ACE_Configuration_Section_Key sub_key; + ACE_TString sub_section; + while (!config_.enumerate_sections (section, index, name)) + { + ACE_TString sub_section (path); + if (path.length ()) + sub_section += ACE_TEXT ("\\"); + sub_section += name; + if (config_.open_section (section, name.fast_rep (), 0, sub_key)) + return -5; + if (export_section (sub_key, sub_section.fast_rep (), out)) + return -6; + ++index; + } + return 0; +} + +// +// This method read the line format origionally used in ACE 5.1 +// +int +ACE_Registry_ImpExp::process_previous_line_format (ACE_TCHAR* buffer, + ACE_Configuration_Section_Key& section) +{ + // Chop any cr/lf at the end of the line. + ACE_TCHAR *endp = ACE_OS::strpbrk (buffer, ACE_TEXT ("\r\n")); + if (endp != 0) + *endp = '\0'; + + // assume this is a value, read in the value name + ACE_TCHAR* end = ACE_OS::strchr (buffer, '='); + if (end) // no =, not a value so just skip it + { + // null terminate the name + *end = 0; + ++end; + // determine the type + if (*end == '\"') + { + // string type + if(config_.set_string_value (section, buffer, end + 1)) + return -4; + } + else if (*end == '#') + { + // number type + u_int value = ACE_OS::atoi (end + 1); + if (config_.set_integer_value (section, buffer, value)) + return -4; + } + } + return 0; +} // end read_previous_line_format + + +ACE_Ini_ImpExp::ACE_Ini_ImpExp (ACE_Configuration& config) + : ACE_Config_ImpExp_Base (config) +{ +} + +ACE_Ini_ImpExp::~ACE_Ini_ImpExp (void) +{ +} + +// Method to read file and populate object. +int +ACE_Ini_ImpExp::import_config (const ACE_TCHAR* filename) +{ + if (0 == filename) + { + errno = EINVAL; + return -1; + } + FILE* in = ACE_OS::fopen (filename, ACE_TEXT ("r")); + if (!in) + return -1; + + // @@ Make this a dynamic size! + ACE_TCHAR buffer[4096]; + ACE_Configuration_Section_Key section; + while (ACE_OS::fgets (buffer, sizeof buffer, in)) + { + ACE_TCHAR *line = this->squish (buffer); + // Check for a comment and blank line + if (line[0] == ACE_TEXT (';') || + line[0] == ACE_TEXT ('#') || + line[0] == '\0') + continue; + + if (line[0] == ACE_TEXT ('[')) + { + // We have a new section here, strip out the section name + ACE_TCHAR* end = ACE_OS::strrchr (line, ACE_TEXT (']')); + if (!end) + { + ACE_OS::fclose (in); + return -3; + } + *end = 0; + + if (config_.expand_path (config_.root_section (), + line + 1, + section, + 1)) + { + ACE_OS::fclose (in); + return -3; + } + + continue; + } + + // We have a line; name ends at equal sign. + ACE_TCHAR *end = ACE_OS::strchr (line, ACE_TEXT ('=')); + if (end == 0) // No '=' + { + ACE_OS::fclose (in); + return -3; + } + *end++ = '\0'; + ACE_TCHAR *name = this->squish (line); +#if 0 + if (ACE_OS::strlen (name) == 0) // No name; just an '=' + { + ACE_OS::fclose (in); + return -3; + } +#endif + // Now find the start of the value + ACE_TCHAR *value = this->squish (end); + size_t value_len = ACE_OS::strlen (value); + if (value_len > 0) + { + // ACE 5.2 (and maybe earlier) exported strings may be enclosed + // in quotes. If string is quote-delimited, strip the quotes. + // Newer exported files don't have quote delimiters. + if (value[0] == ACE_TEXT ('"') && + value[value_len - 1] == ACE_TEXT ('"')) + { + // Strip quotes off both ends. + value[value_len - 1] = '\0'; + ++value; + } + } + + if (config_.set_string_value (section, name, value)) + { + ACE_OS::fclose (in); + return -4; + } + } // end while fgets + + if (ferror (in)) + { + ACE_OS::fclose (in); + return -1; + } + + ACE_OS::fclose (in); + return 0; +} + +// This method exports the entire configuration database to . +// Once the file is opened this method calls 'export_section' passing +// the root section. +int +ACE_Ini_ImpExp::export_config (const ACE_TCHAR* filename) +{ + if (0 == filename) + { + errno = EINVAL; + return -1; + } + int result = -1; + + FILE* out = ACE_OS::fopen (filename, ACE_TEXT ("w")); + if (out) + { + result = this->export_section (config_.root_section (), + ACE_TEXT (""), + out); + // The data may have been buffered and will be flush on close, + // so we need to check that the close succeeds. + if (ACE_OS::fclose (out) < 0) + result = -7; + } + return result; +} + +// Method provided by derived classes in order to write one section to the +// file specified. Called by export_config when exporting the entire +// configuration objet + +int +ACE_Ini_ImpExp::export_section (const ACE_Configuration_Section_Key& section, + const ACE_TString& path, + FILE* out) +{ + // don't export the root + if (path.length ()) + { + // Write out the section header + ACE_TString header = ACE_TEXT ("["); + header += path; + header += ACE_TEXT ("]\n"); + if (ACE_OS::fputs (header.fast_rep (), out) < 0) + return -1; + // Write out each value + int index = 0; + ACE_TString name; + ACE_Configuration::VALUETYPE type; + ACE_TString line; + ACE_TCHAR int_value[32]; + ACE_TCHAR bin_value[3]; + void* binary_data; + size_t binary_length; + ACE_TString string_value; + while (!config_.enumerate_values (section, index, name, type)) + { + line = name + ACE_TEXT ("="); + switch (type) + { + case ACE_Configuration::INTEGER: + { + u_int value; + if (config_.get_integer_value (section, name.fast_rep (), value)) + return -2; + ACE_OS::sprintf (int_value, ACE_TEXT ("%08x"), value); + line += int_value; + break; + } + case ACE_Configuration::STRING: + { + if (config_.get_string_value (section, + name.fast_rep (), + string_value)) + return -2; + line += string_value; + break; + } +#ifdef _WIN32 + case ACE_Configuration::INVALID: + break; // JDO added break. Otherwise INVALID is processed + // like BINARY. If that's correct, please remove the + // break and these comments +#endif + case ACE_Configuration::BINARY: + { + // not supported yet - maybe use BASE64 codeing? + if (config_.get_binary_value (section, + name.fast_rep (), + binary_data, + binary_length)) + return -2; + line += ACE_TEXT ("\""); + unsigned char* ptr = (unsigned char*)binary_data; + while (binary_length) + { + if (ptr != binary_data) + { + line += ACE_TEXT (","); + } + ACE_OS::sprintf (bin_value, ACE_TEXT ("%02x"), *ptr); + line += bin_value; + --binary_length; + ++ptr; + } + line += ACE_TEXT ("\""); + delete [] (char *) binary_data; + break; + } + default: + return -3; + + }// end switch on type + + line += ACE_TEXT ("\n"); + if (ACE_OS::fputs (line.fast_rep (), out) < 0) + return -4; + ++index; + }// end while enumerating values + } + // Export all sub sections + int index = 0; + ACE_TString name; + ACE_Configuration_Section_Key sub_key; + ACE_TString sub_section; + while (!config_.enumerate_sections (section, index, name)) + { + ACE_TString sub_section (path); + if (path.length ()) + sub_section += ACE_TEXT ("\\"); + sub_section += name; + if (config_.open_section (section, name.fast_rep (), 0, sub_key)) + return -5; + if (export_section (sub_key, sub_section.fast_rep (), out)) + return -6; + ++index; + } + return 0; + +} + +// Method to squish leading and trailing whitespaces from a string. +// Whitespace is defined as: spaces (' '), tabs ('\t') or end-of-line +// (cr/lf). The terminating nul is moved up to expunge trailing +// whitespace and the returned pointer points at the first +// non-whitespace character in the string, which may be the nul +// terminator if the string is all whitespace. + +ACE_TCHAR * +ACE_Ini_ImpExp::squish (ACE_TCHAR *src) +{ + ACE_TCHAR *cp = 0; + + if (src == 0) + return 0; + + // Start at the end and work backwards over all whitespace. + for (cp = src + ACE_OS::strlen (src) - 1; + cp != src; + --cp) + if (!ACE_OS::ace_isspace (*cp)) + break; + cp[1] = '\0'; // Chop trailing whitespace + + // Now start at the beginning and move over all whitespace. + for (cp = src; ACE_OS::ace_isspace (*cp); ++cp) + continue; + + return cp; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Configuration_Import_Export.h b/dep/acelite/ace/Configuration_Import_Export.h new file mode 100644 index 00000000000..e93544bee29 --- /dev/null +++ b/dep/acelite/ace/Configuration_Import_Export.h @@ -0,0 +1,215 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file Configuration_Import_Export.h + * + * $Id: Configuration_Import_Export.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Jerry D. Odenwelder Jr. + * Chris Hafey + * + * Classes defined in this file provide the ability to import and export + * ACE Configuration objects to/from disk files. The base class + * ACE_Config_ImpExp_Base provides the common functionality and the derived + * classes implement the import/export functionality for the specific format. + * + * @todo + * - Add locking for thread safety. + * - Provide ability to read file in one format and write in another. + * - See todo's in each class + */ +//============================================================================= + +#ifndef ACE_CONFIGURATION_IMPORT_EXPORT_H +#define ACE_CONFIGURATION_IMPORT_EXPORT_H +#include /**/ "ace/pre.h" + +#include "ace/Configuration.h" +#include "ace/SString.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Config_ImpExp_Base + * + * @brief Base class for file import/export configuration. + * + * This class provides base functionality for configuration objects + * that are persisted in files. It takes an ACE_Configuration + * object that it populates with the data read. + * + */ +class ACE_Export ACE_Config_ImpExp_Base +{ +public: + /// Constructor taking the ACE_Configuration to import/export to + ACE_Config_ImpExp_Base (ACE_Configuration& config); + + /** + * Destructor + */ + virtual ~ACE_Config_ImpExp_Base (void); + + /** + * Imports the configuration database from @a filename. + * No existing data is removed. + */ + virtual int import_config (const ACE_TCHAR* filename) = 0; + + /** + * This method exports the entire configuration database to @a filename. + * Once the file is opened this method calls 'export_section' passing + * the root section. + */ + virtual int export_config (const ACE_TCHAR* filename) = 0; + +protected: + ACE_Configuration &config_; + +private: + ACE_Config_ImpExp_Base (const ACE_Config_ImpExp_Base&); + ACE_Config_ImpExp_Base& operator= (const ACE_Config_ImpExp_Base&); +}; + +/** + * @class ACE_Registry_ImpExp + * + * @brief Configuration object that imports/exports data to a file formatted + * using the Win32 Registry file export format. This format looks like + * [Section] + * "key"="String Data" + * "key"=dword: numeric data in hexidecimal format + * "key"=hex: binary data + * + * @todo + * - Add dynamic buffer when importing. currently it will not allow + * importing of values greater than a fixed ammount (4096 bytes) + * + */ +class ACE_Export ACE_Registry_ImpExp : public ACE_Config_ImpExp_Base +{ +public: + /// Construction + ACE_Registry_ImpExp (ACE_Configuration&); + + /// Destruction. + virtual ~ACE_Registry_ImpExp (void); + + /** + * Imports the configuration database from filename. + * No existing data is removed. + */ + virtual int import_config (const ACE_TCHAR* filename); + + /** + * This method exports the entire configuration database to @a filename. + * Once the file is opened this method calls export_section() passing + * the root section. + */ + virtual int export_config (const ACE_TCHAR* filename); + +private: + int export_section (const ACE_Configuration_Section_Key& section, + const ACE_TString& path, + FILE* out); + + int process_previous_line_format (ACE_TCHAR* buffer, + ACE_Configuration_Section_Key& section); + + ACE_Registry_ImpExp ( const ACE_Registry_ImpExp&); + ACE_Registry_ImpExp& operator= ( const ACE_Registry_ImpExp&); +}; + +/** + * @class ACE_Ini_ImpExp + * + * @brief Imports the configuration database from filename as strings. + * Allows non-typed values. (no #, dword: hex:, etc. prefixes) and + * skips whitespace (tabs and spaces) as in standard .ini and .conf + * files. Values (to right of equal sign) can be double quote + * delimited to embed tabs and spaces in the string. + * Caller must convert string to type. + * + * This method allows for lines in the .ini or .conf file like this: + * + * TimeToLive = 100 + * Delay = FALSE + * Flags = FF34 + * Heading = "ACE - Adaptive Communication Environment" + * + * (note leading whitespace (tabs) in examples below) + * + * SeekIndex = 14 + * TraceLevel = 6 # Can comment lines like this + * Justification = left_justified + * + * The caller can then retrieve the string with the regular + * function and convert the string to the + * desired data type. + * + * @todo + * - Strings with embedded newlines cause the import to fail + * - Strings with embedded quotes " cause the import to fail + * - Importing/exporting for values in the root section does not work + * - Add dynamic buffer when importing. currently it will not allow + * importing of values greater than a fixed ammount (4096 bytes) +*/ +class ACE_Export ACE_Ini_ImpExp : public ACE_Config_ImpExp_Base +{ +public: + /** + * Construction + */ + ACE_Ini_ImpExp (ACE_Configuration&); + + /** + * Destructor + */ + virtual ~ACE_Ini_ImpExp (void); + + /** + * Imports the configuration database from filename. + * No existing data is removed. + */ + virtual int import_config (const ACE_TCHAR* filename); + + /** + * This method exports the entire configuration database to @a filename. + * Once the file is opened this method calls export_section() passing + * the root section. + */ + virtual int export_config (const ACE_TCHAR* filename); + +private: + /** + * Method provided by derived classes in order to write one section + * to the file specified. Called by export_config() when exporting + * the entire configuration object. + */ + int export_section (const ACE_Configuration_Section_Key& section, + const ACE_TString& path, + FILE* out); + + /** + * Method to squish leading and trailing whitespaces in a string. + * Whitespace is defined as: spaces (' '), tabs ('\\t') or cr/lf. + * Returns a pointer to the first non-whitespace character in the + * buffer provided, or a pointer to the terminating null if the string + * is all whitespace. The terminating null is moved forward to the + * first character past the last non-whitespace. + */ + ACE_TCHAR *squish (ACE_TCHAR *src); + + ACE_Ini_ImpExp (const ACE_Ini_ImpExp&); + ACE_Ini_ImpExp& operator= (const ACE_Ini_ImpExp&); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIGURATION_IMPORT_EXPORT_H */ diff --git a/dep/acelite/ace/Connection_Recycling_Strategy.cpp b/dep/acelite/ace/Connection_Recycling_Strategy.cpp new file mode 100644 index 00000000000..78b08884340 --- /dev/null +++ b/dep/acelite/ace/Connection_Recycling_Strategy.cpp @@ -0,0 +1,13 @@ +#include "ace/Connection_Recycling_Strategy.h" + + +ACE_RCSID(ace, Connection_Recycling_Strategy, "$Id: Connection_Recycling_Strategy.cpp 80826 2008-03-04 14:51:23Z wotte $") + + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_Connection_Recycling_Strategy::~ACE_Connection_Recycling_Strategy (void) +{ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Connection_Recycling_Strategy.h b/dep/acelite/ace/Connection_Recycling_Strategy.h new file mode 100644 index 00000000000..75169638dcf --- /dev/null +++ b/dep/acelite/ace/Connection_Recycling_Strategy.h @@ -0,0 +1,63 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file Connection_Recycling_Strategy.h + * + * $Id: Connection_Recycling_Strategy.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Doug Schmidt + */ +//============================================================================= +#ifndef ACE_CONNECTION_RECYCLING_STRATEGY_H +#define ACE_CONNECTION_RECYCLING_STRATEGY_H +#include /**/ "ace/pre.h" + +#include "ace/Recyclable.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Connection_Recycling_Strategy + * + * @brief Defines the interface for a connection recycler. + */ +class ACE_Export ACE_Connection_Recycling_Strategy +{ +public: + /// Virtual Destructor + virtual ~ACE_Connection_Recycling_Strategy (void); + + /// Remove from cache. + virtual int purge (const void *recycling_act) = 0; + + /// Add to cache. + virtual int cache (const void *recycling_act) = 0; + + virtual int recycle_state (const void *recycling_act, + ACE_Recyclable_State new_state) = 0; + + /// Get/Set recycle_state. + virtual ACE_Recyclable_State recycle_state (const void *recycling_act) const = 0; + + /// Mark as closed. + virtual int mark_as_closed (const void *recycling_act) = 0; + + /// Mark as closed.(non-locking version) + virtual int mark_as_closed_i (const void *recycling_act) = 0; + + /// Cleanup hint and reset @a act_holder to zero if @a act_holder != 0. + virtual int cleanup_hint (const void *recycling_act, + void **act_holder = 0) = 0; + +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" + +#endif /*ACE_CONNECTION_RECYCLING_STRATEGY*/ diff --git a/dep/acelite/ace/Connector.cpp b/dep/acelite/ace/Connector.cpp new file mode 100644 index 00000000000..820ca875c16 --- /dev/null +++ b/dep/acelite/ace/Connector.cpp @@ -0,0 +1,991 @@ +// $Id: Connector.cpp 89510 2010-03-17 12:21:14Z vzykov $ + +#ifndef ACE_CONNECTOR_CPP +#define ACE_CONNECTOR_CPP + +#include "ace/Connector.h" +#include "ace/ACE.h" +#include "ace/OS_NS_stdio.h" +#include "ace/OS_NS_string.h" +#include "ace/os_include/os_fcntl.h" /* Has ACE_NONBLOCK */ + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Connector) + +template +ACE_NonBlocking_Connect_Handler::ACE_NonBlocking_Connect_Handler +(ACE_Connector_Base &connector, + SVC_HANDLER *sh, + long id) + : connector_ (connector) + , svc_handler_ (sh) + , cleanup_svc_handler_ (0) + , timer_id_ (id) +{ + ACE_TRACE ("ACE_NonBlocking_Connect_Handler::ACE_NonBlocking_Connect_Handler"); + + this->reference_counting_policy ().value + (ACE_Event_Handler::Reference_Counting_Policy::ENABLED); + + if (this->svc_handler_ != 0 && + this->svc_handler_->reference_counting_policy ().value () == + ACE_Event_Handler::Reference_Counting_Policy::ENABLED) + { + // If SVC_HANDLER is reference counted then NBCH holds a reference + // in cleanup_svc_handle_ which is both a pointer to SVC_HANDLER + // and a flag that triggers remove_reference in NBCH destructor. + this->cleanup_svc_handler_ = sh; + this->cleanup_svc_handler_->add_reference (); + } +} + +template +ACE_NonBlocking_Connect_Handler::~ACE_NonBlocking_Connect_Handler (void) +{ + if (this->cleanup_svc_handler_) + { + this->cleanup_svc_handler_->remove_reference (); + } +} + +template SVC_HANDLER * +ACE_NonBlocking_Connect_Handler::svc_handler (void) +{ + ACE_TRACE ("ACE_NonBlocking_Connect_Handler::svc_handler"); + return this->svc_handler_; +} + +template long +ACE_NonBlocking_Connect_Handler::timer_id (void) +{ + ACE_TRACE ("ACE_NonBlocking_Connect_Handler::timer_id"); + return this->timer_id_; +} + +template void +ACE_NonBlocking_Connect_Handler::timer_id (long id) +{ + ACE_TRACE ("ACE_NonBlocking_Connect_Handler::timer_id"); + this->timer_id_ = id; +} + +template void +ACE_NonBlocking_Connect_Handler::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_NonBlocking_Connect_Handler::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("svc_handler_ = %x"), this->svc_handler_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ntimer_id_ = %d"), this->timer_id_)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +template bool +ACE_NonBlocking_Connect_Handler::close (SVC_HANDLER *&sh) +{ + // Make sure that we haven't already initialized the Svc_Handler. + if (!this->svc_handler_) + return false; + + { + // Exclusive access to the Reactor. + ACE_GUARD_RETURN (ACE_Lock, + ace_mon, + this->reactor ()->lock (), + 0); + + // Double check. + if (!this->svc_handler_) + return false; + + // Remember the Svc_Handler. + sh = this->svc_handler_; + ACE_HANDLE h = sh->get_handle (); + this->svc_handler_ = 0; + + // Remove this handle from the set of non-blocking handles + // in the Connector. + this->connector_.non_blocking_handles ().remove (h); + + // Cancel timer. + if (this->reactor ()->cancel_timer (this->timer_id (), + 0, + 0) == -1) + return false; + + // Remove from Reactor. + if (this->reactor ()->remove_handler ( + h, + ACE_Event_Handler::ALL_EVENTS_MASK) == -1) + return false; + } + + return true; +} + + +template int +ACE_NonBlocking_Connect_Handler::handle_timeout +(const ACE_Time_Value &tv, + const void *arg) +{ + // This method is called if a connection times out before completing. + ACE_TRACE ("ACE_NonBlocking_Connect_Handler::handle_timeout"); + + SVC_HANDLER *svc_handler = 0; + int const retval = this->close (svc_handler) ? 0 : -1; + + // Forward to the SVC_HANDLER the that was passed in as a + // magic cookie during ACE_Connector::connect(). This gives the + // SVC_HANDLER an opportunity to take corrective action (e.g., wait + // a few milliseconds and try to reconnect again. + if (svc_handler != 0 && svc_handler->handle_timeout (tv, arg) == -1) + svc_handler->handle_close (svc_handler->get_handle (), + ACE_Event_Handler::TIMER_MASK); + + return retval; +} + + +template int +ACE_NonBlocking_Connect_Handler::handle_input (ACE_HANDLE) +{ + // Called when a failure occurs during asynchronous connection + // establishment. + ACE_TRACE ("ACE_NonBlocking_Connect_Handler::handle_input"); + + SVC_HANDLER *svc_handler = 0; + int const retval = this->close (svc_handler) ? 0 : -1; + + // Close Svc_Handler. + if (svc_handler != 0) + { + svc_handler->close (NORMAL_CLOSE_OPERATION); + } + + return retval; +} + +template int +ACE_NonBlocking_Connect_Handler::handle_output (ACE_HANDLE handle) +{ + // Called when a connection is establishment asynchronous. + ACE_TRACE ("ACE_NonBlocking_Connect_Handler::handle_output"); + + // Grab the connector ref before smashing ourselves in close(). + ACE_Connector_Base &connector = this->connector_; + SVC_HANDLER *svc_handler = 0; + int const retval = this->close (svc_handler) ? 0 : -1; + + if (svc_handler != 0) + { + connector.initialize_svc_handler (handle, svc_handler); + } + + return retval; +} + +template int +ACE_NonBlocking_Connect_Handler::handle_exception (ACE_HANDLE h) +{ + // On Win32, the except mask must also be set for asynchronous + // connects. + ACE_TRACE ("ACE_NonBlocking_Connect_Handler::handle_exception"); + return this->handle_output (h); +} + +template int +ACE_NonBlocking_Connect_Handler::resume_handler (void) +{ + return ACE_Event_Handler::ACE_EVENT_HANDLER_NOT_RESUMED; +} + +template void +ACE_Connector::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Connector::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nflags_ = %d"), this->flags_)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +template int +ACE_Connector::make_svc_handler (SVC_HANDLER *&sh) +{ + ACE_TRACE ("ACE_Connector::make_svc_handler"); + + if (sh == 0) + ACE_NEW_RETURN (sh, + SVC_HANDLER, + -1); + + // Set the reactor of the newly created to the same + // reactor that this is using. + sh->reactor (this->reactor ()); + return 0; +} + +template int +ACE_Connector::activate_svc_handler (SVC_HANDLER *svc_handler) +{ + ACE_TRACE ("ACE_Connector::activate_svc_handler"); + // No errors initially + int error = 0; + + // See if we should enable non-blocking I/O on the 's + // peer. + if (ACE_BIT_ENABLED (this->flags_, ACE_NONBLOCK) != 0) + { + if (svc_handler->peer ().enable (ACE_NONBLOCK) == -1) + error = 1; + } + // Otherwise, make sure it's disabled by default. + else if (svc_handler->peer ().disable (ACE_NONBLOCK) == -1) + error = 1; + + // We are connected now, so try to open things up. + if (error || svc_handler->open ((void *) this) == -1) + { + // Make sure to close down the to avoid descriptor + // leaks. + // The connection was already made; so this close is a "normal" + // close operation. + svc_handler->close (NORMAL_CLOSE_OPERATION); + return -1; + } + else + return 0; +} + +template ACE_PEER_CONNECTOR & +ACE_Connector::connector (void) const +{ + return const_cast (this->connector_); +} + +template int +ACE_Connector::connect_svc_handler +(SVC_HANDLER *&svc_handler, + const ACE_PEER_CONNECTOR_ADDR &remote_addr, + ACE_Time_Value *timeout, + const ACE_PEER_CONNECTOR_ADDR &local_addr, + int reuse_addr, + int flags, + int perms) +{ + ACE_TRACE ("ACE_Connector::connect_svc_handler"); + + return this->connector_.connect (svc_handler->peer (), + remote_addr, + timeout, + local_addr, + reuse_addr, + flags, + perms); +} + +template int +ACE_Connector::connect_svc_handler +(SVC_HANDLER *&svc_handler, + SVC_HANDLER *&sh_copy, + const ACE_PEER_CONNECTOR_ADDR &remote_addr, + ACE_Time_Value *timeout, + const ACE_PEER_CONNECTOR_ADDR &local_addr, + int reuse_addr, + int flags, + int perms) +{ + ACE_TRACE ("ACE_Connector::connect_svc_handler"); + + sh_copy = svc_handler; + return this->connector_.connect (svc_handler->peer (), + remote_addr, + timeout, + local_addr, + reuse_addr, + flags, + perms); +} + +template int +ACE_Connector::open (ACE_Reactor *r, int flags) +{ + ACE_TRACE ("ACE_Connector::open"); + this->reactor (r); + this->flags_ = flags; + return 0; +} + +template +ACE_Connector::ACE_Connector (ACE_Reactor *r, + int flags) +{ + ACE_TRACE ("ACE_Connector::ACE_Connector"); + (void) this->open (r, flags); +} + +template int +ACE_Connector::connect +(SVC_HANDLER *&sh, + const ACE_PEER_CONNECTOR_ADDR &remote_addr, + const ACE_Synch_Options &synch_options, + const ACE_PEER_CONNECTOR_ADDR &local_addr, + int reuse_addr, + int flags, + int perms) +{ + // Initiate connection to peer. + return this->connect_i (sh, + 0, + remote_addr, + synch_options, + local_addr, + reuse_addr, + flags, + perms); +} + +template int +ACE_Connector::connect +(SVC_HANDLER *&sh, + SVC_HANDLER *&sh_copy, + const ACE_PEER_CONNECTOR_ADDR &remote_addr, + const ACE_Synch_Options &synch_options, + const ACE_PEER_CONNECTOR_ADDR &local_addr, + int reuse_addr, + int flags, + int perms) +{ + // Initiate connection to peer. + return this->connect_i (sh, + &sh_copy, + remote_addr, + synch_options, + local_addr, + reuse_addr, + flags, + perms); +} + +template int +ACE_Connector::connect_i +(SVC_HANDLER *&sh, + SVC_HANDLER **sh_copy, + const ACE_PEER_CONNECTOR_ADDR &remote_addr, + const ACE_Synch_Options &synch_options, + const ACE_PEER_CONNECTOR_ADDR &local_addr, + int reuse_addr, + int flags, + int perms) +{ + ACE_TRACE ("ACE_Connector::connect_i"); + + // If the user hasn't supplied us with a we'll use the + // factory method to create one. Otherwise, things will remain as + // they are... + if (this->make_svc_handler (sh) == -1) + return -1; + + ACE_Time_Value *timeout = 0; + int const use_reactor = synch_options[ACE_Synch_Options::USE_REACTOR]; + + if (use_reactor) + timeout = const_cast (&ACE_Time_Value::zero); + else + timeout = const_cast (synch_options.time_value ()); + + int result; + if (sh_copy == 0) + result = this->connect_svc_handler (sh, + remote_addr, + timeout, + local_addr, + reuse_addr, + flags, + perms); + else + result = this->connect_svc_handler (sh, + *sh_copy, + remote_addr, + timeout, + local_addr, + reuse_addr, + flags, + perms); + + // Activate immediately if we are connected. + if (result != -1) + return this->activate_svc_handler (sh); + + // Delegate to connection strategy. + if (use_reactor && ACE_OS::last_error () == EWOULDBLOCK) + { + // If the connection hasn't completed and we are using + // non-blocking semantics then register + // ACE_NonBlocking_Connect_Handler with the ACE_Reactor so that + // it will call us back when the connection is complete or we + // timeout, whichever comes first... + int result; + + if (sh_copy == 0) + result = this->nonblocking_connect (sh, synch_options); + else + result = this->nonblocking_connect (*sh_copy, synch_options); + + // If for some reason the call failed, then + // will be set to the new error. If the call succeeds, however, + // we need to make sure that remains set to + // . + if (result == 0) + errno = EWOULDBLOCK; + } + else + { + // Save/restore errno. + ACE_Errno_Guard error (errno); + // Make sure to close down the service handler to avoid handle + // leaks. + if (sh_copy == 0) + { + if (sh) + sh->close (CLOSE_DURING_NEW_CONNECTION); + } + else if (*sh_copy) + (*sh_copy)->close (CLOSE_DURING_NEW_CONNECTION); + } + + return -1; +} + +template int +ACE_Connector::connect_n +(size_t n, + SVC_HANDLER *sh[], + ACE_PEER_CONNECTOR_ADDR remote_addrs[], + ACE_TCHAR *failed_svc_handlers, + const ACE_Synch_Options &synch_options) +{ + int result = 0; + + for (size_t i = 0; i < n; i++) + { + if (this->connect (sh[i], remote_addrs[i], synch_options) == -1 + && !(synch_options[ACE_Synch_Options::USE_REACTOR] + && errno == EWOULDBLOCK)) + { + result = -1; + if (failed_svc_handlers != 0) + // Mark this entry as having failed. + failed_svc_handlers[i] = 1; + } + else if (failed_svc_handlers != 0) + // Mark this entry as having succeeded. + failed_svc_handlers[i] = 0; + } + + return result; +} + +// Cancel a that was started asynchronously. +template int +ACE_Connector::cancel (SVC_HANDLER *sh) +{ + ACE_TRACE ("ACE_Connector::cancel"); + + ACE_Event_Handler *handler = + this->reactor ()->find_handler (sh->get_handle ()); + + if (handler == 0) + return -1; + + // find_handler() increments handler's refcount; ensure we decrement it. + ACE_Event_Handler_var safe_handler (handler); + + NBCH *nbch = + dynamic_cast (handler); + + if (nbch == 0) + return -1; + + SVC_HANDLER *tmp_sh = 0; + + if (nbch->close (tmp_sh) == false) + return -1; + + return 0; +} + +template int +ACE_Connector::nonblocking_connect +(SVC_HANDLER *sh, + const ACE_Synch_Options &synch_options) +{ + ACE_TRACE ("ACE_Connector::nonblocking_connect"); + + // Must have a valid Reactor for non-blocking connects to work. + if (this->reactor () == 0) + return -1; + + // Register the pending SVC_HANDLER so that it can be activated + // later on when the connection completes. + + ACE_HANDLE handle = sh->get_handle (); + long timer_id = -1; + ACE_Time_Value *tv = 0; + NBCH *nbch = 0; + + ACE_NEW_RETURN (nbch, + NBCH (*this, + sh, + -1), + -1); + + ACE_Event_Handler_var safe_nbch (nbch); + + // Exclusive access to the Reactor. + ACE_GUARD_RETURN (ACE_Lock, ace_mon, this->reactor ()->lock (), -1); + + // Register handle with the reactor for connection events. + ACE_Reactor_Mask mask = ACE_Event_Handler::CONNECT_MASK; + if (this->reactor ()->register_handler (handle, + nbch, + mask) == -1) + goto reactor_registration_failure; + + // Add handle to non-blocking handle set. + this->non_blocking_handles ().insert (handle); + + // If we're starting connection under timer control then we need to + // schedule a timeout with the ACE_Reactor. + tv = const_cast (synch_options.time_value ()); + if (tv != 0) + { + timer_id = + this->reactor ()->schedule_timer (nbch, + synch_options.arg (), + *tv); + if (timer_id == -1) + goto timer_registration_failure; + + // Remember timer id. + nbch->timer_id (timer_id); + } + + return 0; + + // Undo previous actions using the ol' "goto label and fallthru" + // trick... + timer_registration_failure: + + // Remove from Reactor. + this->reactor ()->remove_handler (handle, mask); + + // Remove handle from the set of non-blocking handles. + this->non_blocking_handles ().remove (handle); + + /* FALLTHRU */ + + reactor_registration_failure: + // Close the svc_handler + + sh->close (CLOSE_DURING_NEW_CONNECTION); + + return -1; +} + +template +ACE_Connector::~ACE_Connector (void) +{ + ACE_TRACE ("ACE_Connector::~ACE_Connector"); + + this->close (); +} + +template void +ACE_Connector::initialize_svc_handler +(ACE_HANDLE handle, + SVC_HANDLER *svc_handler) +{ + // Try to find out if the reactor uses event associations for the + // handles it waits on. If so we need to reset it. + bool reset_new_handle = + this->reactor ()->uses_event_associations (); + + if (reset_new_handle) + this->connector_.reset_new_handle (handle); + + // Transfer ownership of the ACE_HANDLE to the SVC_HANDLER. + svc_handler->set_handle (handle); + + ACE_PEER_CONNECTOR_ADDR raddr; + + // Check to see if we're connected. + if (svc_handler->peer ().get_remote_addr (raddr) != -1) + this->activate_svc_handler (svc_handler); + else // Somethings gone wrong, so close down... + { +#if defined (ACE_WIN32) + // Win32 (at least prior to Windows 2000) has a timing problem. + // If you check to see if the connection has completed too fast, + // it will fail - so wait 35 milliseconds to let it catch up. + ACE_Time_Value tv (0, ACE_NON_BLOCKING_BUG_DELAY); + ACE_OS::sleep (tv); + if (svc_handler->peer ().get_remote_addr (raddr) != -1) + this->activate_svc_handler (svc_handler); + else // do the svc handler close below... +#endif /* ACE_WIN32 */ + svc_handler->close (NORMAL_CLOSE_OPERATION); + } +} + +template void +ACE_Connector::reactor (ACE_Reactor *reactor) +{ + this->reactor_ = reactor; +} + +template ACE_Reactor * +ACE_Connector::reactor (void) const +{ + return this->reactor_; +} + +template ACE_Unbounded_Set & +ACE_Connector::non_blocking_handles (void) +{ + return this->non_blocking_handles_; +} + +template int +ACE_Connector::close (void) +{ + // If there are no non-blocking handle pending, return immediately. + if (this->non_blocking_handles ().size () == 0) + return 0; + + // Exclusive access to the Reactor. + ACE_GUARD_RETURN (ACE_Lock, ace_mon, this->reactor ()->lock (), -1); + + // Go through all the non-blocking handles. It is necessary to + // create a new iterator each time because we remove from the handle + // set when we cancel the Svc_Handler. + ACE_HANDLE *handle = 0; + while (1) + { + ACE_Unbounded_Set_Iterator + iterator (this->non_blocking_handles ()); + if (!iterator.next (handle)) + break; + + ACE_Event_Handler *handler = + this->reactor ()->find_handler (*handle); + if (handler == 0) + { + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%t: Connector::close h %d, no handler\n"), + *handle)); + // Remove handle from the set of non-blocking handles. + this->non_blocking_handles ().remove (*handle); + continue; + } + + // find_handler() incremented handler's refcount; ensure it's decremented + ACE_Event_Handler_var safe_handler (handler); + NBCH *nbch = dynamic_cast (handler); + if (nbch == 0) + { + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%t: Connector::close h %d handler %@ ") + ACE_TEXT ("not a legit handler\n"), + *handle, + handler)); + // Remove handle from the set of non-blocking handles. + this->non_blocking_handles ().remove (*handle); + continue; + } + SVC_HANDLER *svc_handler = nbch->svc_handler (); + + // Cancel the non-blocking connection. + this->cancel (svc_handler); + + // Close the associated Svc_Handler. + svc_handler->close (NORMAL_CLOSE_OPERATION); + } + + return 0; +} + +template int +ACE_Connector::fini (void) +{ + ACE_TRACE ("ACE_Connector::fini"); + + return this->close (); +} + +// Hook called by the explicit dynamic linking facility. + +template int +ACE_Connector::init (int, ACE_TCHAR *[]) +{ + ACE_TRACE ("ACE_Connector::init"); + return -1; +} + +template int +ACE_Connector::suspend (void) +{ + ACE_TRACE ("ACE_Connector::suspend"); + return -1; +} + +template int +ACE_Connector::resume (void) +{ + ACE_TRACE ("ACE_Connector::resume"); + return -1; +} + +template int +ACE_Connector::info (ACE_TCHAR **strp, size_t length) const +{ + ACE_TRACE ("ACE_Connector::info"); + ACE_TCHAR buf[BUFSIZ]; + + ACE_OS::sprintf (buf, + ACE_TEXT ("%s\t %s"), + ACE_TEXT ("ACE_Connector"), + ACE_TEXT ("# connector factory\n")); + + if (*strp == 0 && (*strp = ACE_OS::strdup (buf)) == 0) + return -1; + else + ACE_OS::strsncpy (*strp, buf, length); + return static_cast (ACE_OS::strlen (buf)); +} + +template int +ACE_Strategy_Connector::open (ACE_Reactor *r, + int flags) +{ + ACE_TRACE ("ACE_Strategy_Connector::open"); + return this->open (r, 0, 0, 0, flags); +} + +template int +ACE_Strategy_Connector::open +(ACE_Reactor *r, + ACE_Creation_Strategy *cre_s, + ACE_Connect_Strategy *conn_s, + ACE_Concurrency_Strategy *con_s, + int flags) +{ + ACE_TRACE ("ACE_Strategy_Connector::open"); + + this->reactor (r); + + // @@ Not implemented yet. + // this->flags_ = flags; + ACE_UNUSED_ARG (flags); + + // Initialize the creation strategy. + + // First we decide if we need to clean up. + if (this->creation_strategy_ != 0 && + this->delete_creation_strategy_ && + cre_s != 0) + { + delete this->creation_strategy_; + this->creation_strategy_ = 0; + this->delete_creation_strategy_ = false; + } + + if (cre_s != 0) + this->creation_strategy_ = cre_s; + else if (this->creation_strategy_ == 0) + { + ACE_NEW_RETURN (this->creation_strategy_, + CREATION_STRATEGY, + -1); + this->delete_creation_strategy_ = true; + } + + + // Initialize the accept strategy. + + if (this->connect_strategy_ != 0 && + this->delete_connect_strategy_ && + conn_s != 0) + { + delete this->connect_strategy_; + this->connect_strategy_ = 0; + this->delete_connect_strategy_ = false; + } + + if (conn_s != 0) + this->connect_strategy_ = conn_s; + else if (this->connect_strategy_ == 0) + { + ACE_NEW_RETURN (this->connect_strategy_, + CONNECT_STRATEGY, + -1); + this->delete_connect_strategy_ = true; + } + + // Initialize the concurrency strategy. + + if (this->concurrency_strategy_ != 0 && + this->delete_concurrency_strategy_ && + con_s != 0) + { + delete this->concurrency_strategy_; + this->concurrency_strategy_ = 0; + this->delete_concurrency_strategy_ = false; + } + + if (con_s != 0) + this->concurrency_strategy_ = con_s; + else if (this->concurrency_strategy_ == 0) + { + ACE_NEW_RETURN (this->concurrency_strategy_, + CONCURRENCY_STRATEGY, + -1); + this->delete_concurrency_strategy_ = true; + } + + return 0; +} + +template +ACE_Strategy_Connector::ACE_Strategy_Connector +(ACE_Reactor *reactor, + ACE_Creation_Strategy *cre_s, + ACE_Connect_Strategy *conn_s, + ACE_Concurrency_Strategy *con_s, + int flags) + : creation_strategy_ (0), + delete_creation_strategy_ (false), + connect_strategy_ (0), + delete_connect_strategy_ (false), + concurrency_strategy_ (0), + delete_concurrency_strategy_ (false) +{ + ACE_TRACE ("ACE_Connector::ACE_Strategy_Connector"); + + if (this->open (reactor, cre_s, conn_s, con_s, flags) == -1) + ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("ACE_Strategy_Connector::ACE_Strategy_Connector"))); +} + +template +ACE_Strategy_Connector::~ACE_Strategy_Connector (void) +{ + ACE_TRACE ("ACE_Strategy_Connector::~ACE_Strategy_Connector"); + + // Close down + this->close (); +} + +template int +ACE_Strategy_Connector::close (void) +{ + if (this->delete_creation_strategy_) + delete this->creation_strategy_; + this->delete_creation_strategy_ = false; + this->creation_strategy_ = 0; + + if (this->delete_connect_strategy_) + delete this->connect_strategy_; + this->delete_connect_strategy_ = false; + this->connect_strategy_ = 0; + + if (this->delete_concurrency_strategy_) + delete this->concurrency_strategy_; + this->delete_concurrency_strategy_ = false; + this->concurrency_strategy_ = 0; + + return SUPER::close (); +} + +template int +ACE_Strategy_Connector::make_svc_handler (SVC_HANDLER *&sh) +{ + return this->creation_strategy_->make_svc_handler (sh); +} + +template int +ACE_Strategy_Connector::connect_svc_handler +(SVC_HANDLER *&sh, + const ACE_PEER_CONNECTOR_ADDR &remote_addr, + ACE_Time_Value *timeout, + const ACE_PEER_CONNECTOR_ADDR &local_addr, + int reuse_addr, + int flags, + int perms) +{ + return this->connect_strategy_->connect_svc_handler (sh, + remote_addr, + timeout, + local_addr, + reuse_addr, + flags, + perms); +} + +template int +ACE_Strategy_Connector::connect_svc_handler +(SVC_HANDLER *&sh, + SVC_HANDLER *&sh_copy, + const ACE_PEER_CONNECTOR_ADDR &remote_addr, + ACE_Time_Value *timeout, + const ACE_PEER_CONNECTOR_ADDR &local_addr, + int reuse_addr, + int flags, + int perms) +{ + return this->connect_strategy_->connect_svc_handler (sh, + sh_copy, + remote_addr, + timeout, + local_addr, + reuse_addr, + flags, + perms); +} + +template int +ACE_Strategy_Connector::activate_svc_handler (SVC_HANDLER *svc_handler) +{ + return this->concurrency_strategy_->activate_svc_handler (svc_handler, this); +} + +template ACE_Creation_Strategy * +ACE_Strategy_Connector::creation_strategy (void) const +{ + return this->creation_strategy_; +} + +template ACE_Connect_Strategy * +ACE_Strategy_Connector::connect_strategy (void) const +{ + return this->connect_strategy_; +} + +template ACE_Concurrency_Strategy * +ACE_Strategy_Connector::concurrency_strategy (void) const +{ + return this->concurrency_strategy_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_CONNECTOR_C */ diff --git a/dep/acelite/ace/Connector.h b/dep/acelite/ace/Connector.h new file mode 100644 index 00000000000..d0b98cfa923 --- /dev/null +++ b/dep/acelite/ace/Connector.h @@ -0,0 +1,569 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Connector.h + * + * $Id: Connector.h 91058 2010-07-12 08:20:09Z johnnyw $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_CONNECTOR_H +#define ACE_CONNECTOR_H + +#include /**/ "ace/pre.h" + +#include "ace/Service_Object.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Strategies_T.h" +#include "ace/Synch_Options.h" +#include "ace/Unbounded_Set.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Connector_Base + * + * @brief This base interface allows ACE_NonBlocking_Connect_Handler + * to only care about the SVC_HANDLER template parameter of the + * ACE_Connector. Otherwise, ACE_NonBlocking_Connect_Handler would + * have to be configured with all the template parameters that + * ACE_Connector is configured with. + */ +template +class ACE_Connector_Base +{ +public: + + virtual ~ACE_Connector_Base (void) {} + + /// Initialize the Svc_Handler. + virtual void initialize_svc_handler (ACE_HANDLE handle, + SVC_HANDLER *svc_handler) = 0; + + /// Return the handle set representing the non-blocking connects in + /// progress. + virtual ACE_Unbounded_Set &non_blocking_handles (void) = 0; +}; + +/** + * @class ACE_NonBlocking_Connect_Handler + * + * @brief Performs non-blocking connects on behalf of the Connector. + */ +template +class ACE_NonBlocking_Connect_Handler : public ACE_Event_Handler +{ +public: + + /// Constructor. + ACE_NonBlocking_Connect_Handler (ACE_Connector_Base &connector, + SVC_HANDLER *, + long timer_id); + + /// Destructor. + ~ACE_NonBlocking_Connect_Handler (void); + + /// Close up and return underlying SVC_HANDLER through @c sh. + /** + * If the return value is true the close was performed succesfully, + * implying that this object was removed from the reactor and thereby + * (by means of reference counting decremented to 0) deleted. + * If the return value is false, the close was not successful. + * The @c sh does not have any connection to the return + * value. The argument will return a valid svc_handler object if a + * valid one exists within the object. Returning a valid svc_handler + * pointer also invalidates the svc_handler contained in this + * object. + */ + bool close (SVC_HANDLER *&sh); + + /// Get SVC_HANDLER. + SVC_HANDLER *svc_handler (void); + + /// Get handle. + ACE_HANDLE handle (void); + + /// Set handle. + void handle (ACE_HANDLE); + + /// Get timer id. + long timer_id (void); + + /// Set timer id. + void timer_id (long timer_id); + + /// Called by ACE_Reactor when asynchronous connections fail. + virtual int handle_input (ACE_HANDLE); + + /// Called by ACE_Reactor when asynchronous connections succeed. + virtual int handle_output (ACE_HANDLE); + + /// Called by ACE_Reactor when asynchronous connections suceeds (on + /// some platforms only). + virtual int handle_exception (ACE_HANDLE fd); + + /// This method is called if a connection times out before + /// completing. + virtual int handle_timeout (const ACE_Time_Value &tv, const void *arg); + + /// Should Reactor resume us if we have been suspended before the upcall? + virtual int resume_handler (void); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + + /// Connector base. + ACE_Connector_Base &connector_; + + /// Associated SVC_HANDLER. + SVC_HANDLER *svc_handler_; + + /// Same as svc_handler_ if svc_handler_ is reference counted. + SVC_HANDLER *cleanup_svc_handler_; + + /// Associated timer id. + long timer_id_; +}; + +/** + * @class ACE_Connector + * + * @brief Generic factory for actively connecting clients and creating + * service handlers (SVC_HANDLERs). + * + * Implements the strategy for actively establishing connections with + * clients. An ACE_Connector is parameterized by concrete types that + * conform to the interfaces of PEER_CONNECTOR and SVC_HANDLER. The + * PEER_CONNECTOR is instantiated with a transport mechanism that + * actively establishes connections. The SVC_HANDLER is instantiated + * with a concrete type that performs the application-specific + * service. Both blocking and non-blocking connects are supported. + * Further, non-blocking connects support timeouts. + */ +template +class ACE_Connector : public ACE_Connector_Base, public ACE_Service_Object +{ +public: + + // Useful STL-style traits. + typedef typename SVC_HANDLER::addr_type addr_type; + typedef ACE_PEER_CONNECTOR connector_type; + typedef SVC_HANDLER handler_type; + typedef typename SVC_HANDLER::stream_type stream_type; + typedef typename ACE_PEER_CONNECTOR::PEER_ADDR peer_addr_type; + typedef ACE_PEER_CONNECTOR_ADDR ACE_PEER_ADDR_TYPEDEF; + + /** + * Initialize a connector. @a flags indicates how SVC_HANDLER's + * should be initialized prior to being activated. Right now, the + * only flag that is processed is ACE_NONBLOCK, which enabled + * non-blocking I/O on the SVC_HANDLER when it is opened. + */ + ACE_Connector (ACE_Reactor *r = ACE_Reactor::instance (), + int flags = 0); + + /** + * Initialize a connector. @a flags indicates how SVC_HANDLER's + * should be initialized prior to being activated. Right now, the + * only flag that is processed is ACE_NONBLOCK, which enabled + * non-blocking I/O on the SVC_HANDLER when it is opened. + */ + virtual int open (ACE_Reactor *r = ACE_Reactor::instance (), + int flags = 0); + + /// Shutdown a connector and release resources. + virtual ~ACE_Connector (void); + + // = Connection establishment methods. + + /** + * Initiate connection of @a svc_handler to peer at @a remote_addr + * using @a synch_options. If the caller wants to designate the + * selected @a local_addr they can (and can also insist that the + * @a local_addr be reused by passing a value @a reuse_addr == + * 1). @a flags and @a perms can be used to pass any flags that are + * needed to perform specific operations such as opening a file + * within connect with certain permissions. If the connection fails + * the hook on the @a svc_handler will be called + * automatically to prevent resource leaks. + */ + virtual int connect (SVC_HANDLER *&svc_handler, + const ACE_PEER_CONNECTOR_ADDR &remote_addr, + const ACE_Synch_Options &synch_options = ACE_Synch_Options::defaults, + const ACE_PEER_CONNECTOR_ADDR &local_addr + = (peer_addr_type &) ACE_PEER_CONNECTOR_ADDR_ANY, + int reuse_addr = 0, + int flags = O_RDWR, + int perms = 0); + + /** + * This is a variation on the previous method. On cached + * connectors the @a svc_handler_hint variable can be used as a hint + * for future lookups. Since this variable is modified in the + * context of the internal cache its use is thread-safe. But the + * actual svc_handler for the current connection is returned in the + * second parameter @a svc_handler. If the connection fails the + * hook on the @a svc_handler will be called automatically to + * prevent resource leaks. + */ + virtual int connect (SVC_HANDLER *&svc_handler_hint, + SVC_HANDLER *&svc_handler, + const ACE_PEER_CONNECTOR_ADDR &remote_addr, + const ACE_Synch_Options &synch_options = ACE_Synch_Options::defaults, + const ACE_PEER_CONNECTOR_ADDR &local_addr + = (peer_addr_type &) ACE_PEER_CONNECTOR_ADDR_ANY, + int reuse_addr = 0, + int flags = O_RDWR, + int perms = 0); + + /** + * Initiate connection of @a n @a svc_handlers to peers at + * @a remote_addrs using @a synch_options. Returns -1 if failure + * occurs and 0 otherwise. If @a failed_svc_handlers is non-NULL, a + * 1 is placed in the corresponding index of @a failed_svc_handlers + * for each that failed to connect, else a 0 is + * placed in that index. + */ + virtual int connect_n (size_t n, + SVC_HANDLER *svc_handlers[], + ACE_PEER_CONNECTOR_ADDR remote_addrs[], + ACE_TCHAR *failed_svc_handlers = 0, + const ACE_Synch_Options &synch_options = + ACE_Synch_Options::defaults); + + /** + * Cancel the @a svc_handler that was started asynchronously. Note that + * this is the only case when the Connector does not actively close + * the @a svc_handler. It is left up to the caller of to + * decide the fate of the @a svc_handler. + */ + virtual int cancel (SVC_HANDLER *svc_handler); + + /// Close down the Connector. All pending non-blocking connects are + /// canceled and the corresponding svc_handler is closed. + virtual int close (void); + + /// Return the underlying PEER_CONNECTOR object. + virtual ACE_PEER_CONNECTOR &connector (void) const; + + /// Initialize Svc_Handler. + virtual void initialize_svc_handler (ACE_HANDLE handle, + SVC_HANDLER *svc_handler); + + /// Set Reactor. + virtual void reactor (ACE_Reactor *reactor); + + /// Get Reactor. + virtual ACE_Reactor *reactor (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + // = Helpful typedefs. + typedef ACE_NonBlocking_Connect_Handler NBCH; + + // = The following two methods define the Connector's strategies for + // creating, connecting, and activating SVC_HANDLER's, respectively. + + /** + * Bridge method for creating a SVC_HANDLER. The default is to + * create a new SVC_HANDLER only if @a sh == 0, else @a sh is + * unchanged. However, subclasses can override this policy to + * perform SVC_HANDLER creation in any way that they like (such as + * creating subclass instances of SVC_HANDLER, using a singleton, + * dynamically linking the handler, etc.). Returns -1 if failure, + * else 0. + */ + virtual int make_svc_handler (SVC_HANDLER *&sh); + + /** + * Bridge method for connecting the @a svc_handler to the + * @a remote_addr. The default behavior delegates to the + * . + */ + virtual int connect_svc_handler (SVC_HANDLER *&svc_handler, + const ACE_PEER_CONNECTOR_ADDR &remote_addr, + ACE_Time_Value *timeout, + const ACE_PEER_CONNECTOR_ADDR &local_addr, + int reuse_addr, + int flags, + int perms); + virtual int connect_svc_handler (SVC_HANDLER *&svc_handler, + SVC_HANDLER *&sh_copy, + const ACE_PEER_CONNECTOR_ADDR &remote_addr, + ACE_Time_Value *timeout, + const ACE_PEER_CONNECTOR_ADDR &local_addr, + int reuse_addr, + int flags, + int perms); + + /** + * Bridge method for activating a @a svc_handler with the appropriate + * concurrency strategy. The default behavior of this method is to + * activate the SVC_HANDLER by calling its method (which + * allows the SVC_HANDLER to define its own concurrency strategy). + * However, subclasses can override this strategy to do more + * sophisticated concurrency activations (such as creating the + * SVC_HANDLER as an "active object" via multi-threading or + * multi-processing). + */ + virtual int activate_svc_handler (SVC_HANDLER *svc_handler); + + /// Creates and registers ACE_NonBlocking_Connect_Handler. + int nonblocking_connect (SVC_HANDLER *, + const ACE_Synch_Options &); + + /// Implementation of the connect methods. + virtual int connect_i (SVC_HANDLER *&svc_handler, + SVC_HANDLER **sh_copy, + const ACE_PEER_CONNECTOR_ADDR &remote_addr, + const ACE_Synch_Options &synch_options, + const ACE_PEER_CONNECTOR_ADDR &local_addr, + int reuse_addr, + int flags, + int perms); + + /// Return the handle set representing the non-blocking connects in + /// progress. + ACE_Unbounded_Set &non_blocking_handles (void); + + // = Dynamic linking hooks. + /// Default version does no work and returns -1. Must be overloaded + /// by application developer to do anything meaningful. + virtual int init (int argc, ACE_TCHAR *argv[]); + + /// Calls handle_close() to shutdown the Connector gracefully. + virtual int fini (void); + + /// Default version returns address info in @a buf. + virtual int info (ACE_TCHAR **strp, size_t length) const; + + // = Service management hooks. + /// Default version does no work and returns -1. Must be overloaded + /// by application developer to do anything meaningful. + virtual int suspend (void); + + /// Default version does no work and returns -1. Must be overloaded + /// by application developer to do anything meaningful. + virtual int resume (void); + +private: + /// This is the peer connector factory. + ACE_PEER_CONNECTOR connector_; + + /** + * Flags that indicate how SVC_HANDLER's should be initialized + * prior to being activated. Right now, the only flag that is + * processed is ACE_NONBLOCK, which enabled non-blocking I/O on + * the SVC_HANDLER when it is opened. + */ + int flags_; + + /// Pointer to the Reactor. + ACE_Reactor *reactor_; + + /// Handle set representing the non-blocking connects in progress. + ACE_Unbounded_Set non_blocking_handles_; + +}; + +/** + * @class ACE_Strategy_Connector + * + * @brief Abstract factory for creating a service handler + * (SVC_HANDLER), connecting the SVC_HANDLER, and activating the + * SVC_HANDLER. + * + * Implements a flexible and extensible set of strategies for + * actively establishing connections with clients. There are + * three main strategies: (1) creating a SVC_HANDLER, (2) + * actively initiating a new connection from the client, + * and (3) activating the SVC_HANDLER with a + * particular concurrency mechanism after the connection is established. + */ +template +class ACE_Strategy_Connector + : public ACE_Connector +{ +public: + + // Useful STL-style traits. + typedef ACE_Creation_Strategy + creation_strategy_type; + typedef ACE_Connect_Strategy + connect_strategy_type; + typedef ACE_Concurrency_Strategy + concurrency_strategy_type; + typedef ACE_Connector + base_type; + + // = Define some useful (old style) traits. + typedef ACE_Creation_Strategy + CREATION_STRATEGY; + typedef ACE_Connect_Strategy + CONNECT_STRATEGY; + typedef ACE_Concurrency_Strategy + CONCURRENCY_STRATEGY; + typedef ACE_Connector + SUPER; + + /** + * Initialize a connector. @a flags indicates how SVC_HANDLER's + * should be initialized prior to being activated. Right now, the + * only flag that is processed is ACE_NONBLOCK, which enabled + * non-blocking I/O on the SVC_HANDLER when it is opened. + */ + ACE_Strategy_Connector (ACE_Reactor *r = ACE_Reactor::instance (), + ACE_Creation_Strategy * = 0, + ACE_Connect_Strategy * = 0, + ACE_Concurrency_Strategy * = 0, + int flags = 0); + + /** + * Initialize a connector. @a flags indicates how SVC_HANDLER's + * should be initialized prior to being activated. Right now, the + * only flag that is processed is ACE_NONBLOCK, which enabled + * non-blocking I/O on the SVC_HANDLER when it is opened. + * Default strategies would be created and used. + */ + virtual int open (ACE_Reactor *r, + int flags); + + /** + * Initialize a connector. @a flags indicates how SVC_HANDLER's + * should be initialized prior to being activated. Right now, the + * only flag that is processed is ACE_NONBLOCK, which enabled + * non-blocking I/O on the SVC_HANDLER when it is opened. + */ + virtual int open (ACE_Reactor *r = ACE_Reactor::instance (), + ACE_Creation_Strategy * = 0, + ACE_Connect_Strategy * = 0, + ACE_Concurrency_Strategy * = 0, + int flags = 0); + + /// Shutdown a connector and release resources. + virtual ~ACE_Strategy_Connector (void); + + /// Close down the Connector + virtual int close (void); + + // = Strategies accessors + virtual ACE_Creation_Strategy *creation_strategy (void) const; + virtual ACE_Connect_Strategy *connect_strategy (void) const; + virtual ACE_Concurrency_Strategy *concurrency_strategy (void) const; + +protected: + // = The following three methods define the 's strategies + // for creating, connecting, and activating SVC_HANDLER's, + // respectively. + + /** + * Bridge method for creating a SVC_HANDLER. The strategy for + * creating a SVC_HANDLER are configured into the Connector via + * it's . The default is to create a new + * SVC_HANDLER only if @a sh == 0, else @a sh is unchanged. + * However, subclasses can override this policy to perform + * SVC_HANDLER creation in any way that they like (such as + * creating subclass instances of SVC_HANDLER, using a singleton, + * dynamically linking the handler, etc.). Returns -1 if failure, + * else 0. + */ + virtual int make_svc_handler (SVC_HANDLER *&sh); + + /** + * Bridge method for connecting the new connection into the + * SVC_HANDLER. The default behavior delegates to the + * in the . + */ + virtual int connect_svc_handler (SVC_HANDLER *&sh, + const ACE_PEER_CONNECTOR_ADDR &remote_addr, + ACE_Time_Value *timeout, + const ACE_PEER_CONNECTOR_ADDR &local_addr, + int reuse_addr, + int flags, + int perms); + + /** + * Bridge method for connecting the new connection into the + * SVC_HANDLER. The default behavior delegates to the + * in the . + * @a sh_copy is used to obtain a copy of the @a sh pointer, but that + * can be kept in the stack; the motivation is a bit too long to + * include here, but basically we want to modify @a sh safely, using + * the internal locks in the Connect_Strategy, while saving a TSS + * copy in @a sh_copy, usually located in the stack. + */ + virtual int connect_svc_handler (SVC_HANDLER *&sh, + SVC_HANDLER *&sh_copy, + const ACE_PEER_CONNECTOR_ADDR &remote_addr, + ACE_Time_Value *timeout, + const ACE_PEER_CONNECTOR_ADDR &local_addr, + int reuse_addr, + int flags, + int perms); + + /** + * Bridge method for activating a SVC_HANDLER with the appropriate + * concurrency strategy. The default behavior of this method is to + * activate the SVC_HANDLER by calling its method (which + * allows the SVC_HANDLER to define its own concurrency strategy). + * However, subclasses can override this strategy to do more + * sophisticated concurrency activations (such as creating the + * SVC_HANDLER as an "active object" via multi-threading or + * multi-processing). + */ + virtual int activate_svc_handler (SVC_HANDLER *svc_handler); + + // = Strategy objects. + + /// Creation strategy for an Connector. + CREATION_STRATEGY *creation_strategy_; + + /// True if Connector created the creation strategy and thus should + /// delete it, else false. + bool delete_creation_strategy_; + + /// Connect strategy for a Connector. + CONNECT_STRATEGY *connect_strategy_; + + /// True if Connector created the connect strategy and thus should + /// delete it, else false. + bool delete_connect_strategy_; + + /// Concurrency strategy for a Connector. + CONCURRENCY_STRATEGY *concurrency_strategy_; + + /// True if Connector created the concurrency strategy and thus should + /// delete it, else false. + bool delete_concurrency_strategy_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Connector.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Connector.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" + +#endif /* ACE_CONNECTOR_H */ diff --git a/dep/acelite/ace/Containers.cpp b/dep/acelite/ace/Containers.cpp new file mode 100644 index 00000000000..244a9ad4b1b --- /dev/null +++ b/dep/acelite/ace/Containers.cpp @@ -0,0 +1,12 @@ +// $Id: Containers.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Containers.h" + +ACE_RCSID (ace, + Containers, + "$Id: Containers.cpp 80826 2008-03-04 14:51:23Z wotte $") + +#if !defined (__ACE_INLINE__) +#include "ace/Containers.inl" +#endif /* __ACE_INLINE__ */ + diff --git a/dep/acelite/ace/Containers.h b/dep/acelite/ace/Containers.h new file mode 100644 index 00000000000..ecff8e368e4 --- /dev/null +++ b/dep/acelite/ace/Containers.h @@ -0,0 +1,71 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Containers.h + * + * $Id: Containers.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_CONTAINERS_H +#define ACE_CONTAINERS_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template class ACE_Double_Linked_List; +template class ACE_Double_Linked_List_Iterator_Base; +template class ACE_Double_Linked_List_Iterator; +template class ACE_Double_Linked_List_Reverse_Iterator; + +/** + * @class ACE_DLList_Node + * + * @brief Base implementation of element in a DL list. Needed for + * ACE_Double_Linked_List. + */ +class ACE_Export ACE_DLList_Node +{ +public: + friend class ACE_Double_Linked_List; + friend class ACE_Double_Linked_List_Iterator_Base; + friend class ACE_Double_Linked_List_Iterator; + friend class ACE_Double_Linked_List_Reverse_Iterator; + + ACE_DLList_Node (void *i, + ACE_DLList_Node *n = 0, + ACE_DLList_Node *p = 0); + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + + void *item_; + + ACE_DLList_Node *next_; + ACE_DLList_Node *prev_; + +protected: + ACE_DLList_Node (void); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Containers.inl" +#endif /* __ACE_INLINE__ */ + +#include "ace/Containers_T.h" + +#include /**/ "ace/post.h" + +#endif /* ACE_CONTAINERS_H */ diff --git a/dep/acelite/ace/Containers.inl b/dep/acelite/ace/Containers.inl new file mode 100644 index 00000000000..8094672a8f6 --- /dev/null +++ b/dep/acelite/ace/Containers.inl @@ -0,0 +1,25 @@ +// -*- C++ -*- +// +// $Id: Containers.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE +ACE_DLList_Node::ACE_DLList_Node (void) + : item_ (0), + next_ (0), + prev_ (0) +{ +} + +ACE_INLINE +ACE_DLList_Node::ACE_DLList_Node (void *i, + ACE_DLList_Node *n, + ACE_DLList_Node *p) + : item_ (i), + next_ (n), + prev_ (p) +{ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Containers_T.cpp b/dep/acelite/ace/Containers_T.cpp new file mode 100644 index 00000000000..f4b6bd8a7f0 --- /dev/null +++ b/dep/acelite/ace/Containers_T.cpp @@ -0,0 +1,1932 @@ +// $Id: Containers_T.cpp 82588 2008-08-11 13:37:41Z johnnyw $ + +#ifndef ACE_CONTAINERS_T_CPP +#define ACE_CONTAINERS_T_CPP + +#include "ace/Log_Msg.h" +#include "ace/Malloc_Base.h" +#include "ace/OS_Memory.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Containers.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Containers_T.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Bounded_Stack) + +template void +ACE_Bounded_Stack::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Bounded_Stack::dump"); +#endif /* ACE_HAS_DUMP */ +} + +template +ACE_Bounded_Stack::ACE_Bounded_Stack (size_t size) + : size_ (size), + top_ (0) +{ + ACE_NEW (this->stack_, + T[size]); + ACE_TRACE ("ACE_Bounded_Stack::ACE_Bounded_Stack"); +} + +template +ACE_Bounded_Stack::ACE_Bounded_Stack (const ACE_Bounded_Stack &s) + : size_ (s.size_), + top_ (s.top_) +{ + ACE_NEW (this->stack_, + T[s.size_]); + + ACE_TRACE ("ACE_Bounded_Stack::ACE_Bounded_Stack"); + + for (size_t i = 0; i < this->top_; i++) + this->stack_[i] = s.stack_[i]; +} + +template void +ACE_Bounded_Stack::operator= (const ACE_Bounded_Stack &s) +{ + ACE_TRACE ("ACE_Bounded_Stack::operator="); + + if (&s != this) + { + if (this->size_ < s.size_) + { + delete [] this->stack_; + ACE_NEW (this->stack_, + T[s.size_]); + this->size_ = s.size_; + } + this->top_ = s.top_; + + for (size_t i = 0; i < this->top_; i++) + this->stack_[i] = s.stack_[i]; + } +} + +template +ACE_Bounded_Stack::~ACE_Bounded_Stack (void) +{ + ACE_TRACE ("ACE_Bounded_Stack::~ACE_Bounded_Stack"); + delete [] this->stack_; +} + +// ---------------------------------------- + +ACE_ALLOC_HOOK_DEFINE(ACE_Fixed_Stack) + +template void +ACE_Fixed_Stack::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Fixed_Stack::dump"); +#endif /* ACE_HAS_DUMP */ +} + +template +ACE_Fixed_Stack::ACE_Fixed_Stack (void) + : size_ (ACE_SIZE), + top_ (0) +{ + ACE_TRACE ("ACE_Fixed_Stack::ACE_Fixed_Stack"); +} + +template +ACE_Fixed_Stack::ACE_Fixed_Stack (const ACE_Fixed_Stack &s) + : size_ (s.size_), + top_ (s.top_) +{ + ACE_TRACE ("ACE_Fixed_Stack::ACE_Fixed_Stack"); + for (size_t i = 0; i < this->top_; i++) + this->stack_[i] = s.stack_[i]; +} + +template void +ACE_Fixed_Stack::operator= (const ACE_Fixed_Stack &s) +{ + ACE_TRACE ("ACE_Fixed_Stack::operator="); + + if (&s != this) + { + this->top_ = s.top_; + + for (size_t i = 0; i < this->top_; i++) + this->stack_[i] = s.stack_[i]; + } +} + +template +ACE_Fixed_Stack::~ACE_Fixed_Stack (void) +{ + ACE_TRACE ("ACE_Fixed_Stack::~ACE_Fixed_Stack"); +} + +//---------------------------------------- + +ACE_ALLOC_HOOK_DEFINE(ACE_Unbounded_Stack) + +template void +ACE_Unbounded_Stack::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + // ACE_TRACE ("ACE_Unbounded_Stack::dump"); +#endif /* ACE_HAS_DUMP */ +} + +template +ACE_Unbounded_Stack::ACE_Unbounded_Stack (ACE_Allocator *alloc) + : head_ (0), + cur_size_ (0), + allocator_ (alloc) +{ + // ACE_TRACE ("ACE_Unbounded_Stack::ACE_Unbounded_Stack"); + if (this->allocator_ == 0) + this->allocator_ = ACE_Allocator::instance (); + + ACE_NEW_MALLOC (this->head_, + (ACE_Node *) this->allocator_->malloc (sizeof (ACE_Node)), + ACE_Node); + this->head_->next_ = this->head_; +} + +template void +ACE_Unbounded_Stack::delete_all_nodes (void) +{ + // ACE_TRACE ("ACE_Unbounded_Stack::delete_all_nodes"); + + while (this->is_empty () == 0) + { + ACE_Node *temp = this->head_->next_; + this->head_->next_ = temp->next_; + ACE_DES_FREE_TEMPLATE (temp, this->allocator_->free, + ACE_Node, ); + } + + this->cur_size_ = 0; + + ACE_ASSERT (this->head_ == this->head_->next_ + && this->is_empty ()); +} + +template void +ACE_Unbounded_Stack::copy_all_nodes (const ACE_Unbounded_Stack &s) +{ + // ACE_TRACE ("ACE_Unbounded_Stack::copy_all_nodes"); + + ACE_ASSERT (this->head_ == this->head_->next_); + + ACE_Node *temp = this->head_; + + for (ACE_Node *s_temp = s.head_->next_; + s_temp != s.head_; + s_temp = s_temp->next_) + { + ACE_Node *nptr = temp->next_; + ACE_NEW_MALLOC (temp->next_, + (ACE_Node *) this->allocator_->malloc (sizeof (ACE_Node)), + ACE_Node (s_temp->item_, nptr)); + temp = temp->next_; + } + this->cur_size_ = s.cur_size_; +} + +template +ACE_Unbounded_Stack::ACE_Unbounded_Stack (const ACE_Unbounded_Stack &s) + : head_ (0), + cur_size_ (0), + allocator_ (s.allocator_) +{ + if (this->allocator_ == 0) + this->allocator_ = ACE_Allocator::instance (); + + ACE_NEW_MALLOC (this->head_, + (ACE_Node *) this->allocator_->malloc (sizeof (ACE_Node)), + ACE_Node); + this->head_->next_ = this->head_; + + // ACE_TRACE ("ACE_Unbounded_Stack::ACE_Unbounded_Stack"); + this->copy_all_nodes (s); +} + +template void +ACE_Unbounded_Stack::operator= (const ACE_Unbounded_Stack &s) +{ + // ACE_TRACE ("ACE_Unbounded_Stack::operator="); + + if (this != &s) + { + this->delete_all_nodes (); + this->copy_all_nodes (s); + } +} + +template +ACE_Unbounded_Stack::~ACE_Unbounded_Stack (void) +{ + // ACE_TRACE ("ACE_Unbounded_Stack::~ACE_Unbounded_Stack"); + + this->delete_all_nodes (); + ACE_DES_FREE_TEMPLATE (head_, + this->allocator_->free, + ACE_Node, + ); +} + +template int +ACE_Unbounded_Stack::push (const T &new_item) +{ + // ACE_TRACE ("ACE_Unbounded_Stack::push"); + + ACE_Node *temp = 0; + + ACE_NEW_MALLOC_RETURN (temp, + static_cast *> (this->allocator_->malloc (sizeof (ACE_Node))), + ACE_Node (new_item, this->head_->next_), + -1); + this->head_->next_ = temp; + ++this->cur_size_; + return 0; +} + +template int +ACE_Unbounded_Stack::pop (T &item) +{ + // ACE_TRACE ("ACE_Unbounded_Stack::pop"); + + if (this->is_empty ()) + return -1; + else + { + ACE_Node *temp = this->head_->next_; + item = temp->item_; + this->head_->next_ = temp->next_; + + ACE_DES_FREE_TEMPLATE (temp, + this->allocator_->free, + ACE_Node, + ); + --this->cur_size_; + return 0; + } +} + +template int +ACE_Unbounded_Stack::find (const T &item) const +{ + // ACE_TRACE ("ACE_Unbounded_Stack::find"); + // Set into the dummy node. + this->head_->item_ = item; + + ACE_Node *temp = this->head_->next_; + + // Keep looping until we find the item. + while (!(temp->item_ == item)) + temp = temp->next_; + + // If we found the dummy node then it's not really there, otherwise, + // it is there. + return temp == this->head_ ? -1 : 0; +} + +template int +ACE_Unbounded_Stack::insert (const T &item) +{ + // ACE_TRACE ("ACE_Unbounded_Stack::insert"); + + if (this->find (item) == 0) + return 1; + else + return this->push (item); +} + +template int +ACE_Unbounded_Stack::remove (const T &item) +{ + // ACE_TRACE ("ACE_Unbounded_Stack::remove"); + + // Insert the item to be founded into the dummy node. + this->head_->item_ = item; + + ACE_Node *curr = this->head_; + + while (!(curr->next_->item_ == item)) + curr = curr->next_; + + if (curr->next_ == this->head_) + return -1; // Item was not found. + else + { + ACE_Node *temp = curr->next_; + // Skip over the node that we're deleting. + curr->next_ = temp->next_; + --this->cur_size_; + ACE_DES_FREE_TEMPLATE (temp, + this->allocator_->free, + ACE_Node, + ); + return 0; + } +} + +//-------------------------------------------------- +ACE_ALLOC_HOOK_DEFINE(ACE_Double_Linked_List_Iterator_Base) + +template +ACE_Double_Linked_List_Iterator_Base::ACE_Double_Linked_List_Iterator_Base (const ACE_Double_Linked_List &dll) + : current_ (0), dllist_ (&dll) +{ + // Do nothing +} + +template +ACE_Double_Linked_List_Iterator_Base::ACE_Double_Linked_List_Iterator_Base (const ACE_Double_Linked_List_Iterator_Base &iter) + : current_ (iter.current_), + dllist_ (iter.dllist_) +{ + // Do nothing +} + + +template T * +ACE_Double_Linked_List_Iterator_Base::next (void) const +{ + return this->not_done (); +} + +template int +ACE_Double_Linked_List_Iterator_Base::next (T *&ptr) const +{ + ptr = this->not_done (); + return ptr ? 1 : 0; +} + + +template int +ACE_Double_Linked_List_Iterator_Base::done (void) const +{ + return this->not_done () ? 0 : 1; +} + +template T & +ACE_Double_Linked_List_Iterator_Base::operator* (void) const +{ + return *(this->not_done ()); +} + +// @@ Is this a valid retasking? Make sure to check with Purify and +// whatnot that we're not leaking memory or doing any other screwing things. +template void +ACE_Double_Linked_List_Iterator_Base::reset (ACE_Double_Linked_List &dll) +{ + current_ = 0; + dllist_ = &dll; +} + + template int +ACE_Double_Linked_List_Iterator_Base::go_head (void) +{ + this->current_ = static_cast (dllist_->head_->next_); + return this->current_ ? 1 : 0; +} + +template int +ACE_Double_Linked_List_Iterator_Base::go_tail (void) +{ + this->current_ = static_cast (dllist_->head_->prev_); + return this->current_ ? 1 : 0; +} + +template T * +ACE_Double_Linked_List_Iterator_Base::not_done (void) const +{ + if (this->current_ != this->dllist_->head_) + return this->current_; + else + return 0; +} + +template T * +ACE_Double_Linked_List_Iterator_Base::do_advance (void) +{ + if (this->not_done ()) + { + this->current_ = static_cast (this->current_->next_); + return this->not_done (); + } + else + return 0; +} + +template T * +ACE_Double_Linked_List_Iterator_Base::do_retreat (void) +{ + if (this->not_done ()) + { + this->current_ = static_cast (this->current_->prev_); + return this->not_done (); + } + else + return 0; +} + +template void +ACE_Double_Linked_List_Iterator_Base::dump_i (void) const +{ + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("current_ = %x"), this->current_)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +} + +//-------------------------------------------------- +ACE_ALLOC_HOOK_DEFINE(ACE_Double_Linked_List_Iterator) + +template +ACE_Double_Linked_List_Iterator::ACE_Double_Linked_List_Iterator (const ACE_Double_Linked_List &dll) + : ACE_Double_Linked_List_Iterator_Base (dll) +{ + this->current_ = static_cast (dll.head_->next_); + // Advance current_ out of the null area and onto the first item in + // the list +} + +template void +ACE_Double_Linked_List_Iterator::reset (ACE_Double_Linked_List &dll) +{ + this->ACE_Double_Linked_List_Iterator_Base ::reset (dll); + this->current_ = static_cast (dll.head_->next_); + // Advance current_ out of the null area and onto the first item in + // the list +} + +template int +ACE_Double_Linked_List_Iterator::first (void) +{ + return this->go_head (); +} + +template int +ACE_Double_Linked_List_Iterator::advance (void) +{ + return this->do_advance () ? 1 : 0; +} + +template T* +ACE_Double_Linked_List_Iterator::advance_and_remove (bool dont_remove) +{ + T* item = 0; + if (dont_remove) + this->do_advance (); + else + { + item = this->next (); + this->do_advance (); + // It seems dangerous to remove nodes in an iterator, but so it goes... + ACE_Double_Linked_List *dllist = + const_cast *> (this->dllist_); + dllist->remove (item); + } + return item; +} + +template void +ACE_Double_Linked_List_Iterator::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + this->dump_i (); +#endif /* ACE_HAS_DUMP */ +} + +// Prefix advance. + +template +ACE_Double_Linked_List_Iterator & +ACE_Double_Linked_List_Iterator::operator++ (void) +{ + this->do_advance (); + return *this; +} + + +// Postfix advance. + +template +ACE_Double_Linked_List_Iterator +ACE_Double_Linked_List_Iterator::operator++ (int) +{ + ACE_Double_Linked_List_Iterator retv (*this); + this->do_advance (); + return retv; +} + + +// Prefix reverse. + +template +ACE_Double_Linked_List_Iterator & +ACE_Double_Linked_List_Iterator::operator-- (void) +{ + this->do_retreat (); + return *this; +} + + +// Postfix reverse. + +template +ACE_Double_Linked_List_Iterator +ACE_Double_Linked_List_Iterator::operator-- (int) +{ + ACE_Double_Linked_List_Iterator retv (*this); + this->do_retreat (); + return retv; +} + + +//-------------------------------------------------- +ACE_ALLOC_HOOK_DEFINE(ACE_Double_Linked_List_Reverse_Iterator) + + template +ACE_Double_Linked_List_Reverse_Iterator::ACE_Double_Linked_List_Reverse_Iterator (ACE_Double_Linked_List &dll) + : ACE_Double_Linked_List_Iterator_Base (dll) +{ + this->current_ = static_cast (dll.head_->prev_); + // Advance current_ out of the null area and onto the last item in + // the list +} + +template void +ACE_Double_Linked_List_Reverse_Iterator::reset (ACE_Double_Linked_List &dll) +{ + this->ACE_Double_Linked_List_Iterator_Base ::reset (dll); + this->current_ = static_cast (dll.head_->prev_); + // Advance current_ out of the null area and onto the last item in + // the list +} + +template int +ACE_Double_Linked_List_Reverse_Iterator::first (void) +{ + return this->go_tail (); +} + +template int +ACE_Double_Linked_List_Reverse_Iterator::advance (void) +{ + return this->do_retreat () ? 1 : 0; +} + +template T* +ACE_Double_Linked_List_Reverse_Iterator::advance_and_remove (bool dont_remove) +{ + T* item = 0; + if (dont_remove) + { + this->do_retreat (); + } + else + { + item = this->next (); + this->do_retreat (); + // It seems dangerous to remove nodes in an iterator, but so it goes... + ACE_Double_Linked_List *dllist = + const_cast *> (this->dllist_); + dllist->remove (item); + } + return item; +} + +template void +ACE_Double_Linked_List_Reverse_Iterator::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + this->dump_i (); +#endif /* ACE_HAS_DUMP */ +} + +// Prefix advance. + +template +ACE_Double_Linked_List_Reverse_Iterator & +ACE_Double_Linked_List_Reverse_Iterator::operator++ (void) +{ + this->do_retreat (); + return *this; +} + + +// Postfix advance. + +template +ACE_Double_Linked_List_Reverse_Iterator +ACE_Double_Linked_List_Reverse_Iterator::operator++ (int) +{ + ACE_Double_Linked_List_Reverse_Iterator retv (*this); + this->do_retreat (); + return retv; +} + + +// Prefix reverse. + +template +ACE_Double_Linked_List_Reverse_Iterator & +ACE_Double_Linked_List_Reverse_Iterator::operator-- (void) +{ + this->do_advance (); + return *this; +} + + +// Postfix reverse. + +template +ACE_Double_Linked_List_Reverse_Iterator +ACE_Double_Linked_List_Reverse_Iterator::operator-- (int) +{ + ACE_Double_Linked_List_Reverse_Iterator retv (*this); + this->do_advance (); + return retv; +} + + +ACE_ALLOC_HOOK_DEFINE(ACE_Double_Linked_List) + + template +ACE_Double_Linked_List:: ACE_Double_Linked_List (ACE_Allocator *alloc) + : size_ (0), allocator_ (alloc) +{ + if (this->allocator_ == 0) + this->allocator_ = ACE_Allocator::instance (); + + ACE_NEW_MALLOC (this->head_, + (T *) this->allocator_->malloc (sizeof (T)), + T); + this->init_head (); +} + +template +ACE_Double_Linked_List::ACE_Double_Linked_List (const ACE_Double_Linked_List &cx) + : allocator_ (cx.allocator_) +{ + if (this->allocator_ == 0) + this->allocator_ = ACE_Allocator::instance (); + + ACE_NEW_MALLOC (this->head_, + (T *) this->allocator_->malloc (sizeof (T)), + T); + this->init_head (); + this->copy_nodes (cx); + this->size_ = cx.size_; +} + +template void +ACE_Double_Linked_List::operator= (const ACE_Double_Linked_List &cx) +{ + if (this != &cx) + { + this->delete_nodes (); + this->copy_nodes (cx); + } +} + +template +ACE_Double_Linked_List::~ACE_Double_Linked_List (void) +{ + this->delete_nodes (); + + ACE_DES_FREE (head_, + this->allocator_->free, + T); + + this->head_ = 0; +} + +template int +ACE_Double_Linked_List::is_empty (void) const +{ + return this->size () ? 0 : 1; +} + +template int +ACE_Double_Linked_List::is_full (void) const +{ + return 0; // We have no bound. +} + +template T * +ACE_Double_Linked_List::insert_tail (T *new_item) +{ + // Insert it before , i.e., at tail. + this->insert_element (new_item, 1); + return new_item; +} + +template T * +ACE_Double_Linked_List::insert_head (T *new_item) +{ + this->insert_element (new_item); // Insert it after , i.e., at head. + return new_item; +} + +template T * +ACE_Double_Linked_List::delete_head (void) +{ + if (this->is_empty ()) + return 0; + + T *temp = static_cast (this->head_->next_); + // Detach it from the list. + this->remove_element (temp); + return temp; +} + +template T * +ACE_Double_Linked_List::delete_tail (void) +{ + if (this->is_empty ()) + return 0; + + T *temp = static_cast (this->head_->prev_); + // Detach it from the list. + this->remove_element (temp); + return temp; +} + +template void +ACE_Double_Linked_List::reset (void) +{ + this->delete_nodes (); +} + +template int +ACE_Double_Linked_List::get (T *&item, size_t slot) +{ + ACE_Double_Linked_List_Iterator iter (*this); + + for (size_t i = 0; + i < slot && !iter.done (); + i++) + iter.advance (); + + item = iter.next (); + return item ? 0 : -1; +} + +template size_t +ACE_Double_Linked_List::size (void) const +{ + return this->size_; +} + +template void +ACE_Double_Linked_List::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + // Dump the state of an object. +#endif /* ACE_HAS_DUMP */ +} + +#if 0 +template T * +ACE_Double_Linked_List::find (const T &item) +{ + for (ACE_Double_Linked_List_Iterator iter (*this); + !iter.done (); + iter.advance ()) + { + T *temp = iter.next (); + + if (*temp == item) + return temp; + } + + return 0; +} + +template int +ACE_Double_Linked_List::remove (const T &item) +{ + T *temp = this->find (item); + + if (temp != 0) + return this->remove (temp); + else + return -1; +} +#endif /* 0 */ + +template int +ACE_Double_Linked_List::remove (T *n) +{ + return this->remove_element (n); +} + +template void +ACE_Double_Linked_List::delete_nodes (void) +{ + while (! this->is_empty ()) + { + T * temp = static_cast (this->head_->next_); + this->remove_element (temp); + ACE_DES_FREE (temp, + this->allocator_->free, + T); + } +} + +template void +ACE_Double_Linked_List::copy_nodes (const ACE_Double_Linked_List &c) +{ + for (ACE_Double_Linked_List_Iterator iter (c); + !iter.done (); + iter.advance ()) + { + T* temp = 0; + ACE_NEW_MALLOC (temp, + (T *)this->allocator_->malloc (sizeof (T)), + T (*iter.next ())); + this->insert_tail (temp); + } +} + +template void +ACE_Double_Linked_List::init_head (void) +{ + this->head_->next_ = this->head_; + this->head_->prev_ = this->head_; +} + +template int +ACE_Double_Linked_List::insert_element (T *new_item, + int before, + T *old_item) +{ + if (old_item == 0) + old_item = this->head_; + + if (before) + old_item = static_cast (old_item->prev_); + + new_item->next_ = old_item->next_; + new_item->next_->prev_ = new_item; + new_item->prev_ = old_item; + old_item->next_ = new_item; + ++this->size_; + return 0; // Well, what will cause errors here? +} + +template int +ACE_Double_Linked_List::remove_element (T *item) +{ + // Notice that you have to ensure that item is an element of this + // list. We can't do much checking here. + + if (item == this->head_ || item->next_ == 0 + || item->prev_ == 0 || this->size () == 0) // Can't remove head + return -1; + + item->prev_->next_ = item->next_; + item->next_->prev_ = item->prev_; + item->next_ = item->prev_ = 0; // reset pointers to prevent double removal. + --this->size_; + return 0; +} + +//-------------------------------------------------- +ACE_ALLOC_HOOK_DEFINE(ACE_Fixed_Set) + +template size_t +ACE_Fixed_Set::size (void) const +{ + ACE_TRACE ("ACE_Fixed_Set::size"); + return this->cur_size_; +} + +template void +ACE_Fixed_Set::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Fixed_Set::dump"); +#endif /* ACE_HAS_DUMP */ +} + +template +ACE_Fixed_Set::~ACE_Fixed_Set (void) +{ + ACE_TRACE ("ACE_Fixed_Set::~ACE_Fixed_Set"); + this->cur_size_ = 0; +} + +template +ACE_Fixed_Set::ACE_Fixed_Set (const ACE_Fixed_Set &fs) + : cur_size_ (fs.cur_size_) +{ + ACE_TRACE ("ACE_Fixed_Set::ACE_Fixed_Set"); + + for (size_t i = 0, j = 0; i < fs.max_size_ && j < this->cur_size_; ++i) + if (fs.search_structure_[i].is_free_ == 0) + this->search_structure_[j++] = fs.search_structure_[i]; +} + +template void +ACE_Fixed_Set::operator= (const ACE_Fixed_Set &fs) +{ + ACE_TRACE ("ACE_Fixed_Set::operator="); + + if (this != &fs) + { + this->cur_size_ = fs.cur_size_; + + for (size_t i = 0, j = 0; i < fs.max_size_ && j < this->cur_size_; ++i) + if (fs.search_structure_[i].is_free_ == 0) + this->search_structure_[j++] = fs.search_structure_[i]; + } +} + +template +ACE_Fixed_Set::ACE_Fixed_Set (void) + : cur_size_ (0), + max_size_ (ACE_SIZE) +{ + ACE_TRACE ("ACE_Fixed_Set::ACE_Fixed_Set"); + for (size_t i = 0; i < this->max_size_; i++) + this->search_structure_[i].is_free_ = 1; +} + +template int +ACE_Fixed_Set::find (const T &item) const +{ + ACE_TRACE ("ACE_Fixed_Set::find"); + + for (size_t i = 0, j = 0; i < this->max_size_ && j < this->cur_size_; ++i) + if (this->search_structure_[i].is_free_ == 0) + { + if (this->search_structure_[i].item_ == item) + return 0; + ++j; + } + + return -1; +} + +template int +ACE_Fixed_Set::insert (const T &item) +{ + ACE_TRACE ("ACE_Fixed_Set::insert"); + ssize_t first_free = -1; // Keep track of first free slot. + size_t i; + + for (i = 0; + i < this->max_size_ && first_free == -1; + ++i) + + // First, make sure we don't allow duplicates. + + if (this->search_structure_[i].is_free_ == 0) + { + if (this->search_structure_[i].item_ == item) + return 1; + } + else + first_free = static_cast (i); + + // If we found a free spot let's reuse it. + + if (first_free > -1) + { + this->search_structure_[first_free].item_ = item; + this->search_structure_[first_free].is_free_ = 0; + this->cur_size_++; + return 0; + } + else /* No more room! */ + { + errno = ENOMEM; + return -1; + } +} + +template int +ACE_Fixed_Set::remove (const T &item) +{ + ACE_TRACE ("ACE_Fixed_Set::remove"); + + for (size_t i = 0, j = 0; + i < this->max_size_ && j < this->cur_size_; + ++i) + if (this->search_structure_[i].is_free_ == 0) + { + if (this->search_structure_[i].item_ == item) + { + // Mark this entry as being free. + this->search_structure_[i].is_free_ = 1; + + --this->cur_size_; + return 0; + } + else + ++j; + } + + return -1; +} + +//-------------------------------------------------- +ACE_ALLOC_HOOK_DEFINE(ACE_Fixed_Set_Iterator_Base) + +template void +ACE_Fixed_Set_Iterator_Base::dump_i (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Fixed_Set_Iterator_Base::dump_i"); +#endif /* ACE_HAS_DUMP */ +} + +template +ACE_Fixed_Set_Iterator_Base::ACE_Fixed_Set_Iterator_Base (ACE_Fixed_Set &s) + : s_ (s), + next_ (-1), + iterated_items_ (0) +{ + ACE_TRACE ("ACE_Fixed_Set_Iterator_Base::ACE_Fixed_Set_Iterator_Base"); + this->advance (); +} + +template int +ACE_Fixed_Set_Iterator_Base::advance (void) +{ + ACE_TRACE ("ACE_Fixed_Set_Iterator_Base::advance"); + + if (this->iterated_items_ < this->s_.cur_size_) + { + for (++this->next_; + static_cast (this->next_) < this->s_.max_size_; + ++this->next_) + if (this->s_.search_structure_[this->next_].is_free_ == 0) + { + ++this->iterated_items_; + return 1; + } + } + else + ++this->next_; + + return 0; +} + +template int +ACE_Fixed_Set_Iterator_Base::first (void) +{ + ACE_TRACE ("ACE_Fixed_Set_Iterator_Base::first"); + + next_ = -1; + iterated_items_ = 0; + return this->advance (); +} + +template int +ACE_Fixed_Set_Iterator_Base::done (void) const +{ + ACE_TRACE ("ACE_Fixed_Set_Iterator_Base::done"); + + return ! (this->iterated_items_ < this->s_.cur_size_); +} + +template int +ACE_Fixed_Set_Iterator_Base::next_i (T *&item) +{ + ACE_TRACE ("ACE_Fixed_Set_Iterator_Base::next_i"); + + if (static_cast (this->next_) < this->s_.max_size_) + do + { + if (this->s_.search_structure_[this->next_].is_free_ == 0) + { + item = &this->s_.search_structure_[this->next_].item_; + this->advance (); + return 1; + } + } + while (this->advance () == 1); + + return 0; +} + +//-------------------------------------------------- +ACE_ALLOC_HOOK_DEFINE(ACE_Fixed_Set_Iterator) + +template void +ACE_Fixed_Set_Iterator::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + this->dump_i (); +#endif /* ACE_HAS_DUMP */ +} + +template +ACE_Fixed_Set_Iterator::ACE_Fixed_Set_Iterator (ACE_Fixed_Set &s) + : ACE_Fixed_Set_Iterator_Base (s) +{ + ACE_TRACE ("ACE_Fixed_Set_Iterator::ACE_Fixed_Set_Iterator"); +} + +template int +ACE_Fixed_Set_Iterator::next (T *&item) +{ + ACE_TRACE ("ACE_Fixed_Set_Iterator::next"); + return this->next_i (item); +} + +template int +ACE_Fixed_Set_Iterator::remove (T *&item) +{ + ACE_TRACE ("ACE_Fixed_Set_Iterator::remove"); + + if (this->s_.search_structure_[this->next_].is_free_ == 0) + { + item = &this->s_.search_structure_[this->next_].item_; + this->s_.remove (*item); + --(this->iterated_items_); + return 1; + } + + return 0; +} + +template T& +ACE_Fixed_Set_Iterator::operator* (void) +{ + T *retv = 0; + + if (this->s_.search_structure_[this->next_].is_free_ == 0) + retv = &this->s_.search_structure_[this->next_].item_; + + ACE_ASSERT (retv != 0); + + return *retv; +} + +//-------------------------------------------------- +ACE_ALLOC_HOOK_DEFINE(ACE_Fixed_Set_Const_Iterator) + +template void +ACE_Fixed_Set_Const_Iterator::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + this->dump_i (); +#endif /* ACE_HAS_DUMP */ +} + +template +ACE_Fixed_Set_Const_Iterator::ACE_Fixed_Set_Const_Iterator (const ACE_Fixed_Set &s) + : ACE_Fixed_Set_Iterator_Base (s) +{ + ACE_TRACE ("ACE_Fixed_Set_Const_Iterator::ACE_Fixed_Set_Const_Iterator"); +} + +template int +ACE_Fixed_Set_Const_Iterator::next (const T *&item) +{ + ACE_TRACE ("ACE_Fixed_Set_Const_Iterator::next"); + + return this->next_i (item); +} + +template const T& +ACE_Fixed_Set_Const_Iterator::operator* (void) const +{ + const T *retv = 0; + + if (this->s_.search_structure_[this->next_].is_free_ == 0) + retv = &this->s_.search_structure_[this->next_].item_; + + ACE_ASSERT (retv != 0); + + return *retv; +} + +//-------------------------------------------------- +ACE_ALLOC_HOOK_DEFINE(ACE_Bounded_Set) + +template void +ACE_Bounded_Set::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Bounded_Set::dump"); +#endif /* ACE_HAS_DUMP */ +} + +template +ACE_Bounded_Set::~ACE_Bounded_Set (void) +{ + ACE_TRACE ("ACE_Bounded_Set::~ACE_Bounded_Set"); + delete [] this->search_structure_; +} + +template +ACE_Bounded_Set::ACE_Bounded_Set (void) + : cur_size_ (0), + max_size_ (static_cast (ACE_Bounded_Set::DEFAULT_SIZE)) +{ + ACE_TRACE ("ACE_Bounded_Set::ACE_Bounded_Set"); + + ACE_NEW (this->search_structure_, + typename ACE_Bounded_Set::Search_Structure[this->max_size_]); + + for (size_t i = 0; i < this->max_size_; ++i) + this->search_structure_[i].is_free_ = 1; +} + +template size_t +ACE_Bounded_Set::size (void) const +{ + ACE_TRACE ("ACE_Bounded_Set::size"); + return this->cur_size_; +} + +template +ACE_Bounded_Set::ACE_Bounded_Set (const ACE_Bounded_Set &bs) + : cur_size_ (bs.cur_size_), + max_size_ (bs.max_size_) +{ + ACE_TRACE ("ACE_Bounded_Set::ACE_Bounded_Set"); + + ACE_NEW (this->search_structure_, + typename ACE_Bounded_Set::Search_Structure[this->max_size_]); + + for (size_t i = 0; i < this->cur_size_; i++) + this->search_structure_[i] = bs.search_structure_[i]; +} + +template void +ACE_Bounded_Set::operator= (const ACE_Bounded_Set &bs) +{ + ACE_TRACE ("ACE_Bounded_Set::operator="); + + if (this != &bs) + { + if (this->max_size_ < bs.cur_size_) + { + delete [] this->search_structure_; + ACE_NEW (this->search_structure_, + typename ACE_Bounded_Set::Search_Structure[bs.cur_size_]); + this->max_size_ = bs.cur_size_; + } + + this->cur_size_ = bs.cur_size_; + + for (size_t i = 0; i < this->cur_size_; i++) + this->search_structure_[i] = bs.search_structure_[i]; + } +} + +template +ACE_Bounded_Set::ACE_Bounded_Set (size_t size) + : cur_size_ (0), + max_size_ (size) +{ + ACE_TRACE ("ACE_Bounded_Set::ACE_Bounded_Set"); + ACE_NEW (this->search_structure_, + typename ACE_Bounded_Set::Search_Structure[size]); + + for (size_t i = 0; i < this->max_size_; i++) + this->search_structure_[i].is_free_ = 1; +} + +template int +ACE_Bounded_Set::find (const T &item) const +{ + ACE_TRACE ("ACE_Bounded_Set::find"); + + for (size_t i = 0; i < this->cur_size_; i++) + if (this->search_structure_[i].item_ == item + && this->search_structure_[i].is_free_ == 0) + return 0; + + return -1; +} + +template int +ACE_Bounded_Set::insert (const T &item) +{ + ACE_TRACE ("ACE_Bounded_Set::insert"); + int first_free = -1; // Keep track of first free slot. + size_t i; + + for (i = 0; i < this->cur_size_; i++) + // First, make sure we don't allow duplicates. + + if (this->search_structure_[i].item_ == item + && this->search_structure_[i].is_free_ == 0) + return 1; + else if (this->search_structure_[i].is_free_ && first_free == -1) + first_free = static_cast (i); + + if (first_free > -1) // If we found a free spot let's reuse it. + { + this->search_structure_[first_free].item_ = item; + this->search_structure_[first_free].is_free_ = 0; + return 0; + } + else if (i < this->max_size_) // Insert at the end of the active portion. + { + this->search_structure_[i].item_ = item; + this->search_structure_[i].is_free_ = 0; + this->cur_size_++; + return 0; + } + else /* No more room! */ + { + errno = ENOMEM; + return -1; + } +} + +template int +ACE_Bounded_Set::remove (const T &item) +{ + ACE_TRACE ("ACE_Bounded_Set::remove"); + for (size_t i = 0; i < this->cur_size_; i++) + if (this->search_structure_[i].item_ == item) + { + // Mark this entry as being free. + this->search_structure_[i].is_free_ = 1; + + // If we just unbound the highest entry, then we need to + // figure out where the next highest active entry is. + if (i + 1 == this->cur_size_) + { + while (i > 0 && this->search_structure_[--i].is_free_) + continue; + + if (i == 0 && this->search_structure_[i].is_free_) + this->cur_size_ = 0; + else + this->cur_size_ = i + 1; + } + return 0; + } + + return -1; +} + +ACE_ALLOC_HOOK_DEFINE(ACE_Bounded_Set_Iterator) + + template void +ACE_Bounded_Set_Iterator::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Bounded_Set_Iterator::dump"); +#endif /* ACE_HAS_DUMP */ +} + +template +ACE_Bounded_Set_Iterator::ACE_Bounded_Set_Iterator (ACE_Bounded_Set &s) + : s_ (s), + next_ (-1) +{ + ACE_TRACE ("ACE_Bounded_Set_Iterator::ACE_Bounded_Set_Iterator"); + this->advance (); +} + +template int +ACE_Bounded_Set_Iterator::advance (void) +{ + ACE_TRACE ("ACE_Bounded_Set_Iterator::advance"); + + for (++this->next_; + static_cast (this->next_) < this->s_.cur_size_ + && this->s_.search_structure_[this->next_].is_free_; + ++this->next_) + continue; + + return static_cast (this->next_) < this->s_.cur_size_; +} + +template int +ACE_Bounded_Set_Iterator::first (void) +{ + ACE_TRACE ("ACE_Bounded_Set_Iterator::first"); + + next_ = -1; + return this->advance (); +} + +template int +ACE_Bounded_Set_Iterator::done (void) const +{ + ACE_TRACE ("ACE_Bounded_Set_Iterator::done"); + + return static_cast (this->next_) >= + this->s_.cur_size_; +} + +template int +ACE_Bounded_Set_Iterator::next (T *&item) +{ + ACE_TRACE ("ACE_Bounded_Set_Iterator::next"); + if (static_cast (this->next_) < this->s_.cur_size_) + { + item = &this->s_.search_structure_[this->next_].item_; + return 1; + } + else + return 0; +} + +ACE_ALLOC_HOOK_DEFINE(ACE_DNode) + + template +ACE_DNode::ACE_DNode (const T &i, ACE_DNode *n, ACE_DNode *p) + : next_ (n), prev_ (p), item_ (i) +{ +} + +template +ACE_DNode::~ACE_DNode (void) +{ +} + +// **************************************************************** + +template void +ACE_Unbounded_Stack_Iterator::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + // ACE_TRACE ("ACE_Unbounded_Stack_Iterator::dump"); +#endif /* ACE_HAS_DUMP */ +} + +template +ACE_Unbounded_Stack_Iterator::ACE_Unbounded_Stack_Iterator (ACE_Unbounded_Stack &q) + : current_ (q.head_->next_), + stack_ (q) +{ + // ACE_TRACE ("ACE_Unbounded_Stack_Iterator::ACE_Unbounded_Stack_Iterator"); +} + +template int +ACE_Unbounded_Stack_Iterator::advance (void) +{ + // ACE_TRACE ("ACE_Unbounded_Stack_Iterator::advance"); + this->current_ = this->current_->next_; + return this->current_ != this->stack_.head_; +} + +template int +ACE_Unbounded_Stack_Iterator::first (void) +{ + // ACE_TRACE ("ACE_Unbounded_Stack_Iterator::first"); + this->current_ = this->stack_.head_->next_; + return this->current_ != this->stack_.head_; +} + +template int +ACE_Unbounded_Stack_Iterator::done (void) const +{ + ACE_TRACE ("ACE_Unbounded_Stack_Iterator::done"); + + return this->current_ == this->stack_.head_; +} + +template int +ACE_Unbounded_Stack_Iterator::next (T *&item) +{ + // ACE_TRACE ("ACE_Unbounded_Stack_Iterator::next"); + if (this->current_ == this->stack_.head_) + return 0; + else + { + item = &this->current_->item_; + return 1; + } +} + + +ACE_ALLOC_HOOK_DEFINE(ACE_Ordered_MultiSet) + + + template +ACE_Ordered_MultiSet::ACE_Ordered_MultiSet (ACE_Allocator *alloc) + : head_ (0) + , tail_ (0) + , cur_size_ (0) + , allocator_ (alloc) +{ + // ACE_TRACE ("ACE_Ordered_MultiSet::ACE_Ordered_MultiSet"); + + if (this->allocator_ == 0) + this->allocator_ = ACE_Allocator::instance (); +} + +template +ACE_Ordered_MultiSet::ACE_Ordered_MultiSet (const ACE_Ordered_MultiSet &us) + : head_ (0) + , tail_ (0) + , cur_size_ (0) + , allocator_ (us.allocator_) +{ + ACE_TRACE ("ACE_Ordered_MultiSet::ACE_Ordered_MultiSet"); + + if (this->allocator_ == 0) + this->allocator_ = ACE_Allocator::instance (); + + this->copy_nodes (us); +} + +template +ACE_Ordered_MultiSet::~ACE_Ordered_MultiSet (void) +{ + // ACE_TRACE ("ACE_Ordered_MultiSet::~ACE_Ordered_MultiSet"); + + this->delete_nodes (); +} + + +template void +ACE_Ordered_MultiSet::operator= (const ACE_Ordered_MultiSet &us) +{ + ACE_TRACE ("ACE_Ordered_MultiSet::operator="); + + if (this != &us) + { + this->delete_nodes (); + this->copy_nodes (us); + } +} + + +template int +ACE_Ordered_MultiSet::insert (const T &item) +{ + // ACE_TRACE ("ACE_Ordered_MultiSet::insert"); + + return this->insert_from (item, this->head_, 0); +} + +template int +ACE_Ordered_MultiSet::insert (const T &new_item, + ITERATOR &iter) +{ + // ACE_TRACE ("ACE_Ordered_MultiSet::insert using iterator"); + + return this->insert_from (new_item, iter.current_, &iter.current_); +} + +template int +ACE_Ordered_MultiSet::remove (const T &item) +{ + // ACE_TRACE ("ACE_Ordered_MultiSet::remove"); + + ACE_DNode *node = 0; + + int result = locate (item, 0, node); + + // if we found the node, remove from list and free it + if (node && (result == 0)) + { + if (node->prev_) + node->prev_->next_ = node->next_; + else + head_ = node->next_; + + if (node->next_) + node->next_->prev_ = node->prev_; + else + tail_ = node->prev_; + + --this->cur_size_; + + ACE_DES_FREE_TEMPLATE (node, + this->allocator_->free, + ACE_DNode, + ); + return 0; + } + + return -1; +} + +template int +ACE_Ordered_MultiSet::find (const T &item, + ITERATOR &iter) const +{ + // search an occurance of item, using iterator's current position as a hint + ACE_DNode *node = iter.current_; + int const result = locate (item, node, node); + + // if we found the node, update the iterator and indicate success + if (node && (result == 0)) + { + iter.current_ = node; + return 0; + } + + return -1; +} + + + +template void +ACE_Ordered_MultiSet::reset (void) +{ + ACE_TRACE ("reset"); + + this->delete_nodes (); +} + +template void +ACE_Ordered_MultiSet::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + // ACE_TRACE ("ACE_Ordered_MultiSet::dump"); + // + // ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + // ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nhead_ = %u"), this->head_)); + // ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nhead_->next_ = %u"), this->head_->next_)); + // ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ncur_size_ = %d\n"), this->cur_size_)); + // + // T *item = 0; + // size_t count = 1; + // + // for (ACE_Ordered_MultiSet_Iterator iter (*(ACE_Ordered_MultiSet *) this); + // iter.next (item) != 0; + // iter.advance ()) + // ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("count = %d\n"), count++)); + // + // ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +template int +ACE_Ordered_MultiSet::insert_from (const T &item, ACE_DNode *position, + ACE_DNode **new_position) +{ + // ACE_TRACE ("ACE_Ordered_MultiSet::insert_from"); + + // create a new node + ACE_DNode *temp = 0; + ACE_NEW_MALLOC_RETURN (temp, + static_cast*> (this->allocator_->malloc (sizeof (ACE_DNode))), + ACE_DNode (item), + -1); + // obtain approximate location of the node + int result = locate (item, position, position); + + // if there are nodes in the multiset + if (position) + { + switch (result) + { + // insert after the approximate position + case -1: + + // if there is a following node + if (position->next_) + { + // link up with the following node + position->next_->prev_ = temp; + temp->next_ = position->next_; + } + else + // appending to the end of the set + tail_ = temp; + + // link up with the preceeding node + temp->prev_ = position; + position->next_ = temp; + + break; + + // insert before the position + case 0: + case 1: + + // if there is a preceeding node + if (position->prev_) + { + // link up with the preceeding node + position->prev_->next_ = temp; + temp->prev_ = position->prev_; + } + else + // prepending to the start of the set + head_ = temp; + + // link up with the preceeding node + temp->next_ = position; + position->prev_ = temp; + + break; + + default: + return -1; + } + } + else + { + // point the head and tail to the new node. + this->head_ = temp; + this->tail_ = temp; + } + + ++this->cur_size_; + if (new_position) + *new_position = temp; + + return 0; +} + +template int +ACE_Ordered_MultiSet::locate (const T &item, ACE_DNode *start_position, + ACE_DNode *&new_position) const +{ + if (! start_position) + start_position = this->head_; + + // If starting before the item, move forward until at or just before + // item. + while (start_position && start_position->item_ < item && + start_position->next_) + start_position = start_position->next_; + + // If starting after the item, move back until at or just after item + while (start_position && item < start_position->item_ && + start_position->prev_) + start_position = start_position->prev_; + + // Save the (approximate) location in the passed pointer. + new_position = start_position; + + // Show the location is after (1), before (-1) , or at (0) the item + if (!new_position) + return 1; + else if (item < new_position->item_) + return 1; + else if (new_position->item_ < item) + return -1; + else + return 0; +} + +// Looks for first occurance of in the ordered set, using the +// passed starting position as a hint: if there is such an instance, +// it updates the new_position pointer to point to one such node and +// returns 0; if there is no such node, then if there is a node before +// where the item would have been, it updates the new_position pointer +// to point to this node and returns -1; if there is no such node, +// then if there is a node after where the item would have been, it +// updates the new_position pointer to point to this node (or 0 if +// there is no such node) and returns 1; + +template void +ACE_Ordered_MultiSet::copy_nodes (const ACE_Ordered_MultiSet &us) +{ + ACE_DNode *insertion_point = this->head_; + + for (ACE_DNode *curr = us.head_; + curr != 0; + curr = curr->next_) + this->insert_from (curr->item_, insertion_point, &insertion_point); +} + +template void +ACE_Ordered_MultiSet::delete_nodes (void) +{ + // iterate through list, deleting nodes + for (ACE_DNode *curr = this->head_; + curr != 0; + ) + { + ACE_DNode *temp = curr; + curr = curr->next_; + ACE_DES_FREE_TEMPLATE (temp, + this->allocator_->free, + ACE_DNode, + ); + } + + this->head_ = 0; + this->tail_ = 0; + this->cur_size_ = 0; +} + +ACE_ALLOC_HOOK_DEFINE(ACE_Ordered_MultiSet_Iterator) + +template +ACE_Ordered_MultiSet_Iterator::ACE_Ordered_MultiSet_Iterator (ACE_Ordered_MultiSet &s) + : current_ (s.head_), + set_ (s) +{ + // ACE_TRACE ("ACE_Ordered_MultiSet_Iterator::ACE_Ordered_MultiSet_Iterator"); +} + +template int +ACE_Ordered_MultiSet_Iterator::next (T *&item) const +{ + // ACE_TRACE ("ACE_Ordered_MultiSet_Iterator::next"); + if (this->current_) + { + item = &this->current_->item_; + return 1; + } + + return 0; +} + +template T& +ACE_Ordered_MultiSet_Iterator::operator* (void) +{ + //ACE_TRACE ("ACE_Ordered_MultiSet_Iterator::operator*"); + T *retv = 0; + + int const result = this->next (retv); + ACE_ASSERT (result != 0); + ACE_UNUSED_ARG (result); + + return *retv; +} + +ACE_ALLOC_HOOK_DEFINE (ACE_DLList_Node) + +template T * +ACE_DLList::insert_tail (T *new_item) +{ + ACE_DLList_Node *temp1 = 0; + ACE_NEW_MALLOC_RETURN (temp1, + static_cast (this->allocator_->malloc (sizeof (ACE_DLList_Node))), + ACE_DLList_Node (new_item), + 0); + ACE_DLList_Node *temp2 = ACE_DLList_Base::insert_tail (temp1); + return (T *) (temp2 ? temp2->item_ : 0); +} + +template T * +ACE_DLList::insert_head (T *new_item) +{ + ACE_DLList_Node *temp1 = 0; + ACE_NEW_MALLOC_RETURN (temp1, + (ACE_DLList_Node *) this->allocator_->malloc (sizeof (ACE_DLList_Node)), + ACE_DLList_Node (new_item), 0); + ACE_DLList_Node *temp2 = ACE_DLList_Base::insert_head (temp1); + return (T *) (temp2 ? temp2->item_ : 0); +} + +template T * +ACE_DLList::delete_head (void) +{ + ACE_DLList_Node *temp1 = ACE_DLList_Base::delete_head (); + T *temp2 = (T *) (temp1 ? temp1->item_ : 0); + ACE_DES_FREE (temp1, + this->allocator_->free, + ACE_DLList_Node); + + return temp2; +} + +template T * +ACE_DLList::delete_tail (void) +{ + ACE_DLList_Node *temp1 = ACE_DLList_Base::delete_tail (); + T *temp2 = (T *) (temp1 ? temp1->item_ : 0); + ACE_DES_FREE (temp1, + this->allocator_->free, + ACE_DLList_Node); + return temp2; +} + +// **************************************************************** + +// Compare this array with for equality. + +template bool +ACE_Array::operator== (const ACE_Array &s) const +{ + if (this == &s) + return true; + else if (this->size () != s.size ()) + return false; + + const size_t len = s.size (); + for (size_t slot = 0; slot < len; ++slot) + if ((*this)[slot] != s[slot]) + return false; + + return true; +} + +// **************************************************************** + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_CONTAINERS_T_CPP */ diff --git a/dep/acelite/ace/Containers_T.h b/dep/acelite/ace/Containers_T.h new file mode 100644 index 00000000000..3f5463fe3d6 --- /dev/null +++ b/dep/acelite/ace/Containers_T.h @@ -0,0 +1,2068 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Containers_T.h + * + * $Id: Containers_T.h 88975 2010-02-12 19:19:38Z johnnyw $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_CONTAINERS_T_H +#define ACE_CONTAINERS_T_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +// Need by ACE_DLList_Node. +#include "ace/Containers.h" + +// Shared with "ace/Unbounded_Set.h" +#include "ace/Node.h" + +// Backwards compatibility, please include "ace/Array_Base.h" directly. +#include "ace/Array_Base.h" + +// Backwards compatibility, please include "ace/Unbounded_Set.h" directly. +#include "ace/Unbounded_Set.h" + +// Backwards compatibility, please include "ace/Unbounded_Queue.h" directly. +#include "ace/Unbounded_Queue.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +class ACE_Allocator; + + +/** + * @class ACE_Bounded_Stack + * + * @brief Implement a generic LIFO abstract data type. + * + * This implementation of a Stack uses a bounded array + * that is allocated dynamically. The Stack interface + * provides the standard constant time push, pop, and top + * operations. + * + * Requirements and Performance Characteristics + * - Internal Structure + * Dynamic array + * - Duplicates allowed? + * Yes + * - Random access allowed? + * No + * - Search speed + * N/A + * - Insert/replace speed + * N/A + * - Iterator still valid after change to container? + * N/A + * - Frees memory for removed elements? + * No + * - Items inserted by + * Value + * - Requirements for contained type + * -# Default constructor + * -# Copy constructor + * -# operator= + * + */ +template +class ACE_Bounded_Stack +{ +public: + // = Initialization, assignment, and termination methods. + + /// Initialize a new empty stack with the provided size.. + /** + * Initialize and allocate space for a new Bounded_Stack with the provided + * size. + */ + ACE_Bounded_Stack (size_t size); + + /// Initialize the stack to be a copy of the stack provided. + /** + * Initialize the stack to be an exact copy of the Bounded_Stack provided + * as a parameter. + */ + ACE_Bounded_Stack (const ACE_Bounded_Stack &s); + + /// Assignment operator + /** + * Perform a deep copy operation using the Bounded_Stack parameter. If the + * capacity of the lhs isn't sufficient for the rhs, then the underlying data + * structure will be reallocated to accomadate the larger number of elements. + */ + void operator= (const ACE_Bounded_Stack &s); + + /// Perform actions needed when stack goes out of scope. + /** + * Deallocate the memory used by the Bounded_Stack. + */ + ~ACE_Bounded_Stack (void); + + // = Classic Stack operations. + + ///Add an element to the top of the stack. + /** + * Place a new item on top of the stack. Returns -1 if the stack + * is already full, 0 if the stack is not already full, and -1 if + * failure occurs. + */ + int push (const T &new_item); + + ///Remove an item from the top of stack. + /** + * Remove and return the top stack item. Returns -1 if the stack is + * already empty, 0 if the stack is not already empty, and -1 if + * failure occurs. + */ + int pop (T &item); + + ///Examine the contents of the top of stack. + /** + * Return top stack item without removing it. Returns -1 if the + * stack is already empty, 0 if the stack is not already empty, and + * -1 if failure occurs. + */ + int top (T &item) const; + + // = Check boundary conditions. + + /// Returns 1 if the container is empty, otherwise returns 0. + /** + * Performs constant time check to determine if the stack is empty. + */ + int is_empty (void) const; + + /// Returns 1 if the container is full, otherwise returns 0. + /** + * Performs constant time check to determine if the stack is at capacity. + */ + int is_full (void) const; + + /// The number of items in the stack. + /** + * Return the number of items currently in the stack. + */ + size_t size (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + /// Size of the dynamically allocated data. + size_t size_; + + /// Keeps track of the current top of stack. + size_t top_; + + /// Holds the stack's contents. + T *stack_; +}; + +//---------------------------------------- + + +/** + * @class ACE_Fixed_Stack + * + * @brief Implement a generic LIFO abstract data type. + * + * This implementation of a Stack uses a fixed array + * with the size fixed at instantiation time. + * + * Requirements and Performance Characteristics + * - Internal Structure + * Fixed array + * - Duplicates allowed? + * Yes + * - Random access allowed? + * No + * - Search speed + * N/A + * - Insert/replace speed + * N/A + * - Iterator still valid after change to container? + * N/A + * - Frees memory for removed elements? + * No + * - Items inserted by + * Value + * - Requirements for contained type + * -# Default constructor + * -# Copy constructor + * -# operator= + * + */ +template +class ACE_Fixed_Stack +{ +public: + // = Initialization, assignment, and termination methods. + /// Initialize a new stack so that it is empty. + /** + * Initialize an empty stack. + */ + ACE_Fixed_Stack (void); + + /// The copy constructor (performs initialization). + /** + * Initialize the stack and copy the provided stack into the current stack. + */ + ACE_Fixed_Stack (const ACE_Fixed_Stack &s); + + /// Assignment operator (performs assignment). + /** + * Perform a deep copy of the provided stack. + */ + void operator= (const ACE_Fixed_Stack &s); + + /// Perform actions needed when stack goes out of scope. + /** + * Destroy the stack. + */ + ~ACE_Fixed_Stack (void); + + // = Classic Stack operations. + + ///Constant time placement of element on top of stack. + /** + * Place a new item on top of the stack. Returns -1 if the stack + * is already full, 0 if the stack is not already full, and -1 if + * failure occurs. + */ + int push (const T &new_item); + + ///Constant time removal of top of stack. + /** + * Remove and return the top stack item. Returns -1 if the stack is + * already empty, 0 if the stack is not already empty, and -1 if + * failure occurs. + */ + int pop (T &item); + + ///Constant time examination of top of stack. + /** + * Return top stack item without removing it. Returns -1 if the + * stack is already empty, 0 if the stack is not already empty, and + * -1 if failure occurs. + */ + int top (T &item) const; + + // = Check boundary conditions. + + /// Returns 1 if the container is empty, otherwise returns 0. + /** + * Performs constant time check to see if stack is empty. + */ + int is_empty (void) const; + + /// Returns 1 if the container is full, otherwise returns 0. + /** + * Performs constant time check to see if stack is full. + */ + int is_full (void) const; + + /// The number of items in the stack. + /** + * Constant time access to the current size of the stack. + */ + size_t size (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + /// Size of the allocated data. + size_t size_; + + /// Keeps track of the current top of stack. + size_t top_; + + /// Holds the stack's contents. + T stack_[ACE_SIZE]; +}; + +//---------------------------------------- + +template class ACE_Ordered_MultiSet; +template class ACE_Ordered_MultiSet_Iterator; + +/** + * @class ACE_DNode + * + * @brief Implementation element in a bilinked list. + */ +template +class ACE_DNode +{ + friend class ACE_Ordered_MultiSet; + friend class ACE_Ordered_MultiSet_Iterator; + +public: + + /// This isn't necessary, but it keeps some compilers happy. + ~ACE_DNode (void); + +private: + + // = Initialization methods + ACE_DNode (const T &i, ACE_DNode *n = 0, ACE_DNode *p = 0); + + /// Pointer to next element in the list of {ACE_DNode}s. + ACE_DNode *next_; + + /// Pointer to previous element in the list of {ACE_DNode}s. + ACE_DNode *prev_; + + /// Current value of the item in this node. + T item_; +}; + + + +/** + * @class ACE_Unbounded_Stack + * + * @brief Implement a generic LIFO abstract data type. + * + * This implementation of an unbounded Stack uses a linked list. + * If you use the {insert} or {remove} methods you should keep + * in mind that duplicate entries aren't allowed. In general, + * therefore, you should avoid the use of these methods since + * they aren't really part of the ADT stack. The stack is implemented + * as a doubly linked list. + * + * Requirements and Performance Characteristics + * - Internal Structure + * Double linked list + * - Duplicates allowed? + * No + * - Random access allowed? + * No + * - Search speed + * Linear + * - Insert/replace speed + * Linear + * - Iterator still valid after change to container? + * Yes + * - Frees memory for removed elements? + * Yes + * - Items inserted by + * Value + * - Requirements for contained type + * -# Default constructor + * -# Copy constructor + * -# operator= + * + */ +template +class ACE_Unbounded_Stack +{ +public: + friend class ACE_Unbounded_Stack_Iterator; + + // Trait definition. + typedef ACE_Unbounded_Stack_Iterator ITERATOR; + + // = Initialization, assignment, and termination methods. + /// Initialize a new stack so that it is empty. Use user defined + /// allocation strategy if specified. + /** + * Initialize an empty stack using the user specified allocation strategy + * if provided. + */ + ACE_Unbounded_Stack (ACE_Allocator *the_allocator = 0); + + /// The copy constructor (performs initialization). + /** + * Initialize this stack to be an exact copy of {s}. + */ + ACE_Unbounded_Stack (const ACE_Unbounded_Stack &s); + + /// Assignment operator (performs assignment). + /** + * Perform a deep copy of the rhs into the lhs. + */ + void operator= (const ACE_Unbounded_Stack &s); + + /// Perform actions needed when stack goes out of scope. + /** + * Destroy the underlying list for the stack. + */ + ~ACE_Unbounded_Stack (void); + + // = Classic Stack operations. + + + ///Push an element onto the top of stack. + /** + * Place a new item on top of the stack. Returns -1 if the stack + * is already full, 0 if the stack is not already full, and -1 if + * failure occurs. + */ + int push (const T &new_item); + + ///Pop the top element of the stack. + /** + * Remove and return the top stack item. Returns -1 if the stack is + * already empty, 0 if the stack is not already empty, and -1 if + * failure occurs. + */ + int pop (T &item); + + ///Examine the top of the stack. + /** + * Return top stack item without removing it. Returns -1 if the + * stack is already empty, 0 if the stack is not already empty, and + * -1 if failure occurs. + */ + int top (T &item) const; + + // = Check boundary conditions. + + /// Returns 1 if the container is empty, otherwise returns 0. + /** + * Constant time check to see if the stack is empty. + */ + int is_empty (void) const; + + /// Returns 1 if the container is full, otherwise returns 0. + /** + * Always resturns 0 since the stack is unbounded. + */ + int is_full (void) const; + + // = Auxiliary methods (not strictly part of the Stack ADT). + + ///Linear Insert of an item. + /** + * Insert {new_item} into the Stack at the head (but doesn't allow + * duplicates). Returns -1 if failures occur, 1 if item is already + * present (i.e., no duplicates are allowed), else 0. + */ + int insert (const T &new_item); + + /// Remove @a item from the Stack. Returns 0 if it removes the item, + /// -1 if it can't find the item, and -1 if a failure occurs. + /** + * Linear remove operation. + */ + int remove (const T &item); + + /// Finds if @a item occurs the set. Returns 0 if finds, else -1. + /** + * Linear find operation. + */ + int find (const T &item) const; + + /// The number of items in the stack. + /** + * Constant time access to the current stack size. + */ + size_t size (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + /// Delete all the nodes in the stack. + void delete_all_nodes (void); + + /// Copy all nodes from {s} to {this}. + void copy_all_nodes (const ACE_Unbounded_Stack &s); + + /// Head of the linked list of Nodes. + ACE_Node *head_; + + /// Current size of the stack. + size_t cur_size_; + + /// Allocation strategy of the stack. + ACE_Allocator *allocator_; +}; + +/** + * @class ACE_Unbounded_Stack_Iterator + * + * @brief Implement an iterator over an unbounded Stack. + */ +template +class ACE_Unbounded_Stack_Iterator +{ +public: + // = Initialization method. + /// Move to the first element in the {stack}. + ACE_Unbounded_Stack_Iterator (ACE_Unbounded_Stack &stack); + + // = Iteration methods. + + /// Pass back the @a next_item that hasn't been seen in the Stack. + /// Returns 0 when all items have been seen, else 1. + int next (T *&next_item); + + /// Move forward by one element in the Stack. Returns 0 when all the + /// items in the Stack have been seen, else 1. + int advance (void); + + /// Move to the first element in the Stack. Returns 0 if the + /// Stack is empty, else 1. + int first (void); + + /// Returns 1 when all items have been seen, else 0. + int done (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + /// Pointer to the current node in the iteration. + ACE_Node *current_; + + /// Pointer to the Stack we're iterating over. + ACE_Unbounded_Stack &stack_; +}; + +template +class ACE_Double_Linked_List; + +/** + * @class ACE_Double_Linked_List_Iterator_Base + * + * @brief Implements a common base class for iterators for a double + * linked list ADT + */ +template +class ACE_Double_Linked_List_Iterator_Base +{ +public: + // = Iteration methods. + + /// Passes back the {entry} under the iterator. Returns 0 if the + /// iteration has completed, otherwise 1 + int next (T *&) const; + + /** + * @deprecated Return the address of next (current) unvisited item in + * the list. 0 if there is no more element available. + */ + T *next (void) const; + + /// Returns 1 when all items have been seen, else 0. + int done (void) const; + + /// STL-like iterator dereference operator: returns a reference + /// to the node underneath the iterator. + T & operator* (void) const ; + + /** + * Retasks the iterator to iterate over a new + * Double_Linked_List. This allows clients to reuse an iterator + * without incurring the constructor overhead. If you do use this, + * be aware that if there are more than one reference to this + * iterator, the other "clients" may be very bothered when their + * iterator changes. @@ Here be dragons. Comments? + */ + void reset (ACE_Double_Linked_List &); + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + // = Initialization methods. + + /// Constructor + ACE_Double_Linked_List_Iterator_Base (const ACE_Double_Linked_List &); + + /// Copy constructor. + ACE_Double_Linked_List_Iterator_Base (const + ACE_Double_Linked_List_Iterator_Base + &iter); + + // = Iteration methods. + /** + * Move to the first element of the list. Returns 0 if the list is + * empty, else 1. + * @note the head of the ACE_DLList is actually a null entry, so the + * first element is actually the 2n'd entry + */ + int go_head (void); + + /// Move to the last element of the list. Returns 0 if the list is + /// empty, else 1. + int go_tail (void); + + /** + * Check if we reach the end of the list. Can also be used to get + * the *current* element in the list. Return the address of the + * current item if there are still elements left , 0 if we run out + * of element. + */ + T *not_done (void) const ; + + /// Advance to the next element in the list. Return the address of the + /// next element if there are more, 0 otherwise. + T *do_advance (void); + + /// Retreat to the previous element in the list. Return the address + /// of the previous element if there are more, 0 otherwise. + T *do_retreat (void); + + /// Dump the state of an object. + void dump_i (void) const; + + /// Remember where we are. + T *current_; + + const ACE_Double_Linked_List *dllist_; +}; + +/** + * @class ACE_Double_Linked_List_Iterator + * + * @brief Implements an iterator for a double linked list ADT + * + * Iterate thru the double-linked list. This class provides + * an interface that let users access the internal element + * addresses directly. Notice {class T} must declare + * ACE_Double_Linked_List<T>, + * ACE_Double_Linked_List_Iterator_Base <T> and + * ACE_Double_Linked_List_Iterator as friend classes and class T + * should also have data members T* next_ and T* prev_. + */ +template +class ACE_Double_Linked_List_Iterator : public ACE_Double_Linked_List_Iterator_Base +{ +public: + // = Initialization method. + ACE_Double_Linked_List_Iterator (const ACE_Double_Linked_List &); + + /** + * Retasks the iterator to iterate over a new + * Double_Linked_List. This allows clients to reuse an iterator + * without incurring the constructor overhead. If you do use this, + * be aware that if there are more than one reference to this + * iterator, the other "clients" may be very bothered when their + * iterator changes. + * @@ Here be dragons. Comments? + */ + void reset (ACE_Double_Linked_List &); + + /// Move to the first element in the list. Returns 0 if the + /// list is empty, else 1. + int first (void); + + /// Move forward by one element in the list. Returns 0 when all the + /// items in the list have been seen, else 1. + int advance (void); + + /** + * Advance the iterator while removing the original item from the + * list. Return a pointer points to the original (removed) item. + * If @a dont_remove equals false, this function behaves like {advance} + * but return 0 (NULL) instead. + */ + T* advance_and_remove (bool dont_remove); + + // = STL-style iteration methods + + /// Prefix advance. + ACE_Double_Linked_List_Iterator & operator++ (void); + + /// Postfix advance. + ACE_Double_Linked_List_Iterator operator++ (int); + + /// Prefix reverse. + ACE_Double_Linked_List_Iterator & operator-- (void); + + /// Postfix reverse. + ACE_Double_Linked_List_Iterator operator-- (int); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; +}; + +/** + * @class ACE_Double_Linked_List_Reverse_Iterator + * + * @brief Implements a reverse iterator for a double linked list ADT + * + * Iterate backwards over the double-linked list. This class + * provide an interface that let users access the internal + * element addresses directly, which seems to break the + * encapsulation. Notice {class T} must declare + * ACE_Double_Linked_List<T>, + * ACE_Double_Linked_List_Iterator_Base <T> and + * ACE_Double_Linked_List_Iterator as friend classes and class T + * should also have data members T* next_ and T* prev_. + */ +template +class ACE_Double_Linked_List_Reverse_Iterator : public ACE_Double_Linked_List_Iterator_Base +{ +public: + // = Initialization method. + ACE_Double_Linked_List_Reverse_Iterator (ACE_Double_Linked_List &); + + /** + * Retasks the iterator to iterate over a new + * Double_Linked_List. This allows clients to reuse an iterator + * without incurring the constructor overhead. If you do use this, + * be aware that if there are more than one reference to this + * iterator, the other "clients" may be very bothered when their + * iterator changes. + * @@ Here be dragons. Comments? + */ + void reset (ACE_Double_Linked_List &); + + /// Move to the first element in the list. Returns 0 if the + /// list is empty, else 1. + int first (void); + + /// Move forward by one element in the list. Returns 0 when all the + /// items in the list have been seen, else 1. + int advance (void); + + /** + * Advance the iterator while removing the original item from the + * list. Return a pointer points to the original (removed) item. + * If @a dont_remove equals false, this function behaves like {advance} + * but return 0 (NULL) instead. + */ + T* advance_and_remove (bool dont_remove); + + // = STL-style iteration methods + + /// Prefix advance. + ACE_Double_Linked_List_Reverse_Iterator & operator++ (void); + + /// Postfix advance. + ACE_Double_Linked_List_Reverse_Iterator operator++ (int); + + /// Prefix reverse. + ACE_Double_Linked_List_Reverse_Iterator & operator-- (void); + + /// Postfix reverse. + ACE_Double_Linked_List_Reverse_Iterator operator-- (int); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; +}; + + +/** + * @class ACE_Double_Linked_List + * + * @brief A double-linked list implementation. + * + * This implementation of an unbounded double-linked list uses a + * circular linked list with a dummy node. It is pretty much + * like the {ACE_Unbounded_Queue} except that it allows removing + * of a specific element from a specific location. + * Notice that this class is an implementation of a very simple + * data structure. This is *NOT* a container class. You can use the + * class to implement other contains classes but it is *NOT* a + * general purpose container class. + * The parameter class *MUST* have members T* prev and T* next + * and users of this class are responsible to follow the general + * rules of using double-linked lists to maintaining the list + * integrity. + * If you need a double linked container class, use the DLList + * class which is a container but delegates to the Double_Linked_List + * class. + * + * Requirements and Performance Characteristics + * - Internal Structure + * Double Linked List + * - Duplicates allowed? + * Yes + * - Random access allowed? + * No + * - Search speed + * N/A + * - Insert/replace speed + * Linear + * - Iterator still valid after change to container? + * Yes + * - Frees memory for removed elements? + * No + * - Items inserted by + * Value + * - Requirements for contained type + * -# Default constructor + * -# Copy constructor + * -# operator= + * + */ +template +class ACE_Double_Linked_List +{ +public: + friend class ACE_Double_Linked_List_Iterator_Base; + friend class ACE_Double_Linked_List_Iterator; + friend class ACE_Double_Linked_List_Reverse_Iterator; + + // Trait definition. + typedef ACE_Double_Linked_List_Iterator ITERATOR; + typedef ACE_Double_Linked_List_Reverse_Iterator REVERSE_ITERATOR; + + // = Initialization and termination methods. + /// construction. Use user specified allocation strategy + /// if specified. + /** + * Initialize an empy list using the allocation strategy specified by the user. + * If none is specified, then use default allocation strategy. + */ + ACE_Double_Linked_List (ACE_Allocator *the_allocator = 0); + + /// Copy constructor. + /** + * Create a double linked list that is a copy of the provided + * parameter. + */ + ACE_Double_Linked_List (const ACE_Double_Linked_List &); + + /// Assignment operator. + /** + * Perform a deep copy of the provided list by first deleting the nodes of the + * lhs and then copying the nodes of the rhs. + */ + void operator= (const ACE_Double_Linked_List &); + + /// Destructor. + /** + * Clean up the memory allocated for the nodes of the list. + */ + ~ACE_Double_Linked_List (void); + + // = Check boundary conditions. + + /// Returns 1 if the container is empty, 0 otherwise. + /** + * Performs constant time check to determine if the list is empty. + */ + int is_empty (void) const; + + /// The list is unbounded, so this always returns 0. + /** + * Since the list is unbounded, the method simply returns 0. + */ + int is_full (void) const; + + // = Classic queue operations. + + /// Adds @a new_item to the tail of the list. Returns the new item + /// that was inserted. + /** + * Provides constant time insertion at the end of the list structure. + */ + T *insert_tail (T *new_item); + + /// Adds @a new_item to the head of the list.Returns the new item that + /// was inserted. + /** + * Provides constant time insertion at the head of the list. + */ + T *insert_head (T *new_item); + + /// Removes the head of the list and returns a pointer to that item. + /** + * Removes and returns the first {item} in the list. Returns + * internal node's address on success, 0 if the queue was empty. + * This method will *not* free the internal node. + */ + T* delete_head (void); + + /// Removes the tail of the list and returns a pointer to that item. + /** + * Removes and returns the last {item} in the list. Returns + * internal nodes's address on success, 0 if the queue was + * empty. This method will *not* free the internal node. + */ + T *delete_tail (void); + + // = Additional utility methods. + + ///Empty the list. + /** + * Reset the {ACE_Double_Linked_List} to be empty. + * Notice that since no one is interested in the items within, + * This operation will delete all items. + */ + void reset (void); + + /// Get the {slot}th element in the set. Returns -1 if the element + /// isn't in the range {0..{size} - 1}, else 0. + /** + * Iterates through the list to the desired index and assigns the provides pointer + * with the address of the node occupying that index. + */ + int get (T *&item, size_t slot = 0); + + /// The number of items in the queue. + /** + * Constant time call to return the current size of the list. + */ + size_t size (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Use DNode address directly. + /** + * Constant time removal of an item from the list using it's address. + */ + int remove (T *n); + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + /// Delete all the nodes in the list. + /** + * Removes and deallocates memory for all of the list nodes. + */ + void delete_nodes (void); + + /// Copy nodes from {rhs} into this list. + /** + * Copy the elements of the provided list by allocated new nodes and assigning + * them with the proper data. + */ + void copy_nodes (const ACE_Double_Linked_List &rhs); + + /// Setup header pointer. Called after we create the head node in ctor. + /** + * Initialize the head pointer so that the list has a dummy node. + */ + void init_head (void); + + ///Constant time insert a new item into the list structure. + /** + * Insert a @a new_item into the list. It will be added before + * or after @a old_item. Default is to insert the new item *after* + * {head_}. Return 0 if succeed, -1 if error occured. + */ + int insert_element (T *new_item, + int before = 0, + T *old_item = 0); + + ///Constant time delete an item from the list structure. + /** + * Remove @a item from the list. Return 0 if succeed, -1 otherwise. + * Notice that this function checks if item is {head_} and either its + * {next_} or {prev_} is NULL. The function resets item's {next_} and + * {prev_} to 0 to prevent clobbering the double-linked list if a user + * tries to remove the same node again. + */ + int remove_element (T *item); + + /// Head of the circular double-linked list. + T *head_; + + /// Size of this list. + size_t size_; + + /// Allocation Strategy of the queue. + ACE_Allocator *allocator_; +}; + + +template class ACE_DLList; +template class ACE_DLList_Iterator; +template class ACE_DLList_Reverse_Iterator; + +typedef ACE_Double_Linked_List ACE_DLList_Base; + +//typedef ACE_Double_Linked_List_Iterator +// ACE_DLList_Iterator_Base; +//typedef ACE_Double_Linked_List_Reverse_Iterator +// ACE_DLList_Reverse_Iterator_Base; +//@@ These two typedefs (inherited from James Hu's original design) +// have been removed because Sun CC 4.2 had problems with it. I guess +// having the DLList_Iterators inheriting from a class which is +// actually a typedef leads to problems. #define'ing rather than +// typedef'ing worked, but as per Carlos's reccomendation, I'm just +// replacing all references to the base classes with their actual +// type. Matt Braun (6/15/99) + +/** + * @class ACE_DLList + * + * @brief A double-linked list container class. + * + * ACE_DLList is a simple, unbounded container implemented using a + * double-linked list. It is critical to remember that ACE_DLList inherits + * from ACE_Double_Linked_List, wrapping each T pointer in a ACE_DLList_Node + * object which satisfies the next/prev pointer requirements imposed by + * ACE_Double_Linked_List. + * + * Each item inserted to an ACE_DLList is a pointer to a T object. The + * caller is responsible for lifetime of the T object. ACE_DLList takes no + * action on the T object; it is not copied on insertion and it is not + * deleted on removal from the ACE_DLList. + */ +template +class ACE_DLList : public ACE_DLList_Base +{ + friend class ACE_DLList_Node; + friend class ACE_Double_Linked_List_Iterator; + friend class ACE_DLList_Iterator; + friend class ACE_DLList_Reverse_Iterator; + +public: + + /// Delegates to ACE_Double_Linked_List. + void operator= (const ACE_DLList &l); + + /** + * @name Queue-like insert and delete methods + */ + //@{ + + /** + * Insert pointer for a new item at the tail of the list. + * + * @return Pointer to item inserted; 0 on error. + */ + T *insert_tail (T *new_item); + + /** + * Insert pointer for a new item at the head of the list. + * + * @return Pointer to item inserted; 0 on error. + */ + T *insert_head (T *new_item); + + /** + * Removes the item at the head of the list and returns its pointer. + * + * @return Pointer to previously inserted item; 0 if the list is empty, + * an error occurred, or the original pointer inserted was 0. + */ + T *delete_head (void); + + /** + * Removes the item at the tail of the list and returns its pointer. + * + * @return Pointer to previously inserted item; 0 if the list is empty, + * an error occurred, or the original pointer inserted was 0. + */ + T *delete_tail (void); + //@} + + /** + * Provide random access to any item in the list. + * + * @param item Receives a pointer to the T object pointer held at the + * specified position in the list. + * @param slot Position in the list to access. The first position is 0. + * + * @retval 0 Success; T pointer returned in item. + * @retval -1 Error, most likely slot is outside the range of the list. + */ + int get (T *&item, size_t slot = 0); + + /// Delegates to ACE_Double_Linked_List. + void dump (void) const; + + /// Delegates to ACE_Double_Linked_List. + int remove (ACE_DLList_Node *n); + + /** + * Constructor. + * + * @param the_allocator Allocator to use for allocating ACE_DLList_Node + * objects that wrap T objects for inclusion in the + * list. If 0, ACE_Allocator::instance() is used. + */ + ACE_DLList (ACE_Allocator *the_allocator = 0); + + /// Delegates to ACE_Double_Linked_List. + ACE_DLList (const ACE_DLList &l); + + /** + * Deletes all ACE_DLList_Node objects in the list starting from the head. + * No T objects referred to by the deleted ACE_DLList_Node objects are + * modified or freed. If you desire all of the T objects in the list to + * be deleted as well, code such as this should be used prior to destroying + * the ACE_DLList: + * @code + ACE_DLList list; + ... // insert dynamically allocated Items... + Item *p; + while ((p = list.delete_head()) != 0) + delete *p; + @endcode + */ + ~ACE_DLList (void); +}; + +/** + * @class ACE_DLList_Iterator + * + * @brief A double-linked list container class iterator. + * + * This implementation uses ACE_Double_Linked_List_Iterator to + * perform the logic behind this container class. It delegates + * all of its calls to ACE_Double_Linked_List_Iterator. + */ +template +class ACE_DLList_Iterator : public ACE_Double_Linked_List_Iterator +{ + + friend class ACE_DLList; + friend class ACE_DLList_Node; + +public: + + // = Initialization method. + ACE_DLList_Iterator (ACE_DLList &l); + + /** + * Retasks the iterator to iterate over a new + * Double_Linked_List. This allows clients to reuse an iterator + * without incurring the constructor overhead. If you do use this, + * be aware that if there are more than one reference to this + * iterator, the other "clients" may be very bothered when their + * iterator changes. + * @@ Here be dragons. Comments? + */ + void reset (ACE_DLList &l); + + // = Iteration methods. + /// Move forward by one element in the list. Returns 0 when all the + /// items in the list have been seen, else 1. + int advance (void); + + /// Pass back the {next_item} that hasn't been seen in the list. + /// Returns 0 when all items have been seen, else 1. + int next (T *&); + + /** + * @deprecated Delegates to ACE_Double_Linked_List_Iterator, except that + * whereas the Double_Linked_List version of next returns the node, this next + * returns the contents of the node + */ + T *next (void) const; + + /** + * Removes the current item (i.e., {next}) from the list. + * Note that DLList iterators do not support {advance_and_remove} + * directly (defined in its base class) and you will need to + * release the element returned by it. + */ + int remove (void); + + /// Delegates to ACE_Double_Linked_List_Iterator. + void dump (void) const; + +private: + ACE_DLList *list_; +}; + +/** + * @class ACE_DLList_Reverse_Iterator + * + * @brief A double-linked list container class iterator. + * + * This implementation uses ACE_Double_Linked_List_Iterator to + * perform the logic behind this container class. It delegates + * all of its calls to ACE_Double_Linked_List_Iterator. + */ +template +class ACE_DLList_Reverse_Iterator : public ACE_Double_Linked_List_Reverse_Iterator +{ + + friend class ACE_DLList; + friend class ACE_DLList_Node; + +public: + + // = Initialization method. + ACE_DLList_Reverse_Iterator (ACE_DLList &l); + + /** + * Retasks the iterator to iterate over a new + * Double_Linked_List. This allows clients to reuse an iterator + * without incurring the constructor overhead. If you do use this, + * be aware that if there are more than one reference to this + * iterator, the other "clients" may be very bothered when their + * iterator changes. + * @@ Here be dragons. Comments? + */ + void reset (ACE_DLList &l); + + // = Iteration methods. + /// Move forward by one element in the list. Returns 0 when all the + /// items in the list have been seen, else 1. + int advance (void); + + /// Pass back the {next_item} that hasn't been seen in the list. + /// Returns 0 when all items have been seen, else 1. + int next (T *&); + + /// @deprecated Delegates to ACE_Double_Linked_List_Iterator. + T *next (void) const; + + /// Removes the current item (i.e., {next}) from the list. + /// Note that DLList iterators do not support {advance_and_remove} + /// directly (defined in its base class) and you will need to + /// release the element returned by it. + int remove (void); + + /// Delegates to ACE_Double_Linked_List_Iterator. + void dump (void) const; + +private: + ACE_DLList *list_; +}; + +// Forward declaration. +template +class ACE_Fixed_Set; + +/** + * @class ACE_Fixed_Set_Iterator_Base + * + * @brief Implements a common base class for iterators for a unordered set. + */ +template +class ACE_Fixed_Set_Iterator_Base +{ +public: + // = Iteration methods. + + /// Pass back the {next_item} that hasn't been seen in the Set. + /// Returns 0 when all items have been seen, else 1. + int next (T *&next_item); + + /// Move forward by one element in the set. Returns 0 when all the + /// items in the set have been seen, else 1. + int advance (void); + + /// Move to the first element in the set. Returns 0 if the + /// set is empty, else 1. + int first (void); + + /// Returns 1 when all items have been seen, else 0. + int done (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + // = Initialization method. + ACE_Fixed_Set_Iterator_Base (ACE_Fixed_Set &s); + + /// Set we are iterating over. + ACE_Fixed_Set &s_; + + /// How far we've advanced over the set. + ssize_t next_; + + /// The number of non free items that the iterator had pointed at. + size_t iterated_items_; + + /// Dump the state of an object. + void dump_i (void) const; + + /// Pass back the {next_item} that hasn't been seen in the Set. + /// Returns 0 when all items have been seen, else 1. + int next_i (T *&next_item); +}; + +/** + * @class ACE_Fixed_Set_Iterator + * + * @brief Iterates through an unordered set. + * + * This implementation of an unordered set uses a fixed array. + * Allows deletions while iteration is occurring. + */ +template +class ACE_Fixed_Set_Iterator : public ACE_Fixed_Set_Iterator_Base +{ +public: + // = Initialization method. + ACE_Fixed_Set_Iterator (ACE_Fixed_Set &s); + + // = Iteration methods. + + /// Pass back the {next_item} that hasn't been seen in the Set. + /// Returns 0 when all items have been seen, else 1. + int next (T *&next_item); + + /// Dump the state of an object. + void dump (void) const; + + /// Remove the item where the itearetor is located at. + /// Returns 1 if it removes a item, else 0. + /// Pass back the removed {item}. + int remove (T *&item); + + /// STL-like iterator dereference operator: returns a reference + /// to the node underneath the iterator. + T & operator* (void); + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; +}; + +/** + * @class ACE_Fixed_Set_Const_Iterator + * + * @brief Iterates through a const unordered set. + * + * This implementation of an unordered set uses a fixed array. + */ +template +class ACE_Fixed_Set_Const_Iterator : public ACE_Fixed_Set_Iterator_Base +{ +public: + // = Initialization method. + ACE_Fixed_Set_Const_Iterator (const ACE_Fixed_Set &s); + + // = Iteration methods. + + /// Pass back the {next_item} that hasn't been seen in the Set. + /// Returns 0 when all items have been seen, else 1. + int next (const T *&next_item); + + /// Dump the state of an object. + void dump (void) const; + + /// STL-like iterator dereference operator: returns a reference + /// to the node underneath the iterator. + const T & operator* (void) const ; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; +}; + +/** + * @class ACE_Fixed_Set + * + * @brief Implement a simple unordered set of {T} with maximum {ACE_SIZE}. + * + * This implementation of an unordered set uses a fixed array. + * It does not allow duplicate members. The set provides linear insertion/deletion + * operations. + * + * Requirements and Performance Characteristics + * - Internal Structure + * Fixed array + * - Duplicates allowed? + * No + * - Random access allowed? + * No + * - Search speed + * Linear + * - Insert/replace speed + * Linear + * - Iterator still valid after change to container? + * Yes + * - Frees memory for removed elements? + * No + * - Items inserted by + * Value + * - Requirements for contained type + * -# Default constructor + * -# Copy constructor + * -# operator= + * -# operator== + * + */ +template +class ACE_Fixed_Set +{ +public: + friend class ACE_Fixed_Set_Iterator_Base; + friend class ACE_Fixed_Set_Iterator; + friend class ACE_Fixed_Set_Const_Iterator; + + // Trait definitions. + typedef ACE_Fixed_Set_Iterator ITERATOR; + typedef ACE_Fixed_Set_Const_Iterator CONST_ITERATOR; + + // = Initialization and termination methods. + /// Default Constructor. + /** + * Creates an empy set + */ + ACE_Fixed_Set (void); + + /// Copy constructor. + /** + * Initializes a set to be a copy of the set parameter. + */ + ACE_Fixed_Set (const ACE_Fixed_Set &); + + /// Assignment operator. + /** + * Deep copy of one set to another. + */ + void operator= (const ACE_Fixed_Set &); + + /// Destructor. + /** + * Destroys a set. + */ + ~ACE_Fixed_Set (void); + + // = Check boundary conditions. + + /// Returns 1 if the container is empty, otherwise returns 0. + /** + * Performs constant time check to determine if a set is empty. + */ + int is_empty (void) const; + + /// Returns 1 if the container is full, otherwise returns 0. + /** + * Performs a constant time check to see if the set is full. + */ + int is_full (void) const; + + // = Classic unordered set operations. + + ///Linear time insertion of an item unique to the set. + /** + * Insert @a new_item into the set (doesn't allow duplicates). + * Returns -1 if failures occur, 1 if item is already present, else + * 0. + */ + int insert (const T &new_item); + + ///Linear time removal operation of an item. + /** + * Remove first occurrence of {item} from the set. Returns 0 if + * it removes the item, -1 if it can't find the item, and -1 if a + * failure occurs. Removal doesn't reclaim memory for the @a item. + */ + int remove (const T &item); + + /// Finds if @a item occurs in the set. Returns 0 if finds, else -1. + /** + * Performs a linear find operation for the specified @a item. + */ + int find (const T &item) const; + + /// Size of the set. + /** + * Returns the current size of the set. + */ + size_t size (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + /// Holds the contents of the set. + struct + { + /// Item in the set. + T item_; + + /// Keeps track of whether this item is in use or not. + int is_free_; + } search_structure_[ACE_SIZE]; + + /// Current size of the set. + size_t cur_size_; + + /// Maximum size of the set. + size_t max_size_; +}; + +// Forward declaration. +template +class ACE_Bounded_Set; + +/** + * @class ACE_Bounded_Set_Iterator + * + * @brief Iterates through an unordered set. + * + * This implementation of an unordered set uses a Bounded array. + * Allows deletions while iteration is occurring. + */ +template +class ACE_Bounded_Set_Iterator +{ +public: + // = Initialization method. + ACE_Bounded_Set_Iterator (ACE_Bounded_Set &s); + + // = Iteration methods. + + /// Pass back the {next_item} that hasn't been seen in the Set. + /// Returns 0 when all items have been seen, else 1. + int next (T *&next_item); + + /// Move forward by one element in the set. Returns 0 when all the + /// items in the set have been seen, else 1. + int advance (void); + + /// Move to the first element in the set. Returns 0 if the + /// set is empty, else 1. + int first (void); + + /// Returns 1 when all items have been seen, else 0. + int done (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + /// Set we are iterating over. + ACE_Bounded_Set &s_; + + /// How far we've advanced over the set. + ssize_t next_; +}; + + +/** + * @class ACE_Bounded_Set + * + * @brief Implement a simple unordered set of {T} with maximum + * set at creation time. + * + * This implementation of an unordered set uses a Bounded array. + * This implementation does not allow duplicates. It provides + * linear insert/remove/find operations. Insertion/removal does not + * invalidate iterators, but caution should be taken to ensure + * expected behavior. Once initialized, the object has a maximum size + * which can only be increased by the assignment of another larger Bounded_Set. + * + * Requirements and Performance Characteristics + * - Internal Structure + * Bounded array which can grow via assignment + * - Duplicates allowed? + * No + * - Random access allowed? + * No + * - Search speed + * Linear + * - Insert/replace speed + * Linear + * - Iterator still valid after change to container? + * Yes + * - Frees memory for removed elements? + * No + * - Items inserted by + * Value + * - Requirements for contained type + * -# Default constructor + * -# Copy constructor + * -# operator= + * -# operator== + * + */ +template +class ACE_Bounded_Set +{ +public: + friend class ACE_Bounded_Set_Iterator; + + // Trait definition. + typedef ACE_Bounded_Set_Iterator ITERATOR; + + enum + { + DEFAULT_SIZE = 10 + }; + + // = Initialization and termination methods. + /// Construct a Bounded_Set using the default size. + /** + * The default constructor initializes the Bounded_Set to a maximum size + * specified by the DEFAULT_SIZE. + */ + ACE_Bounded_Set (void); + + /// Construct a Bounded_Set with the provided sizeB. + /** + * Initialize the Bounded_Set to have a maximum size equal to the size + * parameter specified. + */ + ACE_Bounded_Set (size_t size); + + /// Construct a Bounded_Set that is a copy of the provides Bounded_Set. + /** + * Initialize the Bounded_Set to be a copy of the Bounded_Set parameter. + */ + ACE_Bounded_Set (const ACE_Bounded_Set &); + + /// Assignment operator. + /** + * The assignment will make a deep copy of the Bounded_Set provided. If the + * rhs has more elements than the capacity of the lhs, then the lhs will be + * deleted and reallocated to accomadate the larger number of elements. + */ + void operator= (const ACE_Bounded_Set &); + + /// Destructor + /** + * Clean up the underlying dynamically allocated memory that is used by + * the Bounded_Set. + */ + ~ACE_Bounded_Set (void); + + // = Check boundary conditions. + + /// Returns 1 if the container is empty, otherwise returns 0. + /** + * A constant time check is performed to determine if the Bounded_Set is + * empty. + */ + int is_empty (void) const; + + /// Returns 1 if the container is full, otherwise returns 0. + /** + * Performs a constant time check to determine if the Bounded_Set is at + * capacity. + */ + int is_full (void) const; + + // = Classic unordered set operations. + + ///Inserts a new element unique to the set. + /** + * Insert @a new_item into the set (doesn't allow duplicates) in linear + * time. + * Returns -1 if failures occur, 1 if item is already present, else + * 0. + */ + int insert (const T &new_item); + + ///Finds the specified element and removes it from the set. + /** + * Remove first occurrence of @a item from the set. Returns 0 if it + * removes the item, -1 if it can't find the item, and -1 if a + * failure occurs. The linear remove operation does not reclaim the + * memory associated with the removed item. + */ + int remove (const T &item); + + /// Finds if @a item occurs in the set. Returns 0 if finds, else -1. + /** + * find preforms a linear search for {item} and returns 0 on successful + * find and -1 otherwise. + */ + int find (const T &item) const; + + /// Size of the set. + /** + * Returns a size_t representing the current size of the set. + */ + size_t size (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + struct Search_Structure + { + /// Item in the set. + T item_; + + /// Keeps track of whether this item is in use or not. + int is_free_; + }; + + /// Holds the contents of the set. + Search_Structure *search_structure_; + + /// Current size of the set. + size_t cur_size_; + + /// Maximum size of the set. + size_t max_size_; +}; + +/** + * @class ACE_Ordered_MultiSet_Iterator + * + * @brief Implement a bidirectional iterator over an ordered multiset. + * This class template requires that < operator semantics be + * defined for the parameterized type {T}, but does not impose + * any restriction on how that ordering operator is implemented. + */ +template +class ACE_Ordered_MultiSet_Iterator +{ +public: + friend class ACE_Ordered_MultiSet; + + // = Initialization method. + ACE_Ordered_MultiSet_Iterator (ACE_Ordered_MultiSet &s); + + // = Iteration methods. + + /// Pass back the {next_item} that hasn't been seen in the ordered multiset. + /// Returns 0 when all items have been seen, else 1. + int next (T *&next_item) const; + + /// Repositions the iterator at the first item in the ordered multiset + /// Returns 0 if the list is empty else 1. + int first (void); + + /// Repositions the iterator at the last item in the ordered multiset + /// Returns 0 if the list is empty else 1. + int last (void); + + /// Move forward by one element in the set. Returns 0 when all the + /// items in the set have been seen, else 1. + int advance (void); + + /// Move backward by one element in the set. Returns 0 when all the + /// items in the set have been seen, else 1. + int retreat (void); + + /// Returns 1 when all items have been seen, else 0. + int done (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Returns a reference to the internal element {this} is pointing to. + T& operator* (void); + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + + /// Pointer to the current node in the iteration. + ACE_DNode *current_; + + /// Pointer to the set we're iterating over. + ACE_Ordered_MultiSet &set_; +}; + + +/** + * @class ACE_Ordered_MultiSet + * + * @brief Implement a simple ordered multiset of {T} of unbounded size + * that allows duplicates. This class template requires that < + * operator semantics be defined for the parameterized type {T}, but + * does not impose any restriction on how that ordering operator is + * implemented. The set is implemented as a linked list. + * + * + * Requirements and Performance Characteristics + * - Internal Structure + * Double linked list + * - Duplicates allowed? + * Yes + * - Random access allowed? + * No + * - Search speed + * Linear + * - Insert/replace speed + * Linear + * - Iterator still valid after change to container? + * Yes + * - Frees memory for removed elements? + * Yes + * - Items inserted by + * Value + * - Requirements for contained type + * -# Default constructor + * -# Copy constructor + * -# operator= + * -# operator== + * -# operator< + * + * + */ +template +class ACE_Ordered_MultiSet +{ +public: + friend class ACE_Ordered_MultiSet_Iterator; + + // Trait definition. + typedef ACE_Ordered_MultiSet_Iterator ITERATOR; + + // = Initialization and termination methods. + /// Constructor. Use user specified allocation strategy + /// if specified. + /** + * Initialize the set using the allocation strategy specified. If none, use the + * default strategy. + */ + ACE_Ordered_MultiSet (ACE_Allocator *the_allocator = 0); + + /// Copy constructor. + /** + * Initialize the set to be a copy of the provided set. + */ + ACE_Ordered_MultiSet (const ACE_Ordered_MultiSet &); + + /// Destructor. + /** + * Delete the nodes of the set. + */ + ~ACE_Ordered_MultiSet (void); + + /// Assignment operator. + /** + * Delete the nodes in lhs, and copy the nodes from the rhs. + */ + void operator= (const ACE_Ordered_MultiSet &); + + // = Check boundary conditions. + + /// Returns 1 if the container is empty, otherwise returns 0. + /** + * Constant time check to determine if the set is empty. + */ + int is_empty (void) const; + + /// Size of the set. + /** + * Constant time check to determine the size of the set. + */ + size_t size (void) const; + + // = Classic unordered set operations. + + /// Insert @a new_item into the ordered multiset. + /// Returns -1 if failures occur, else 0. + /** + * Linear time, order preserving insert into the set beginning at the head. + */ + int insert (const T &new_item); + + ///Linear time insert beginning at the point specified by the provided iterator. + /** + * Insert @a new_item into the ordered multiset, starting its search at + * the node pointed to by the iterator, and if insertion was successful, + * updates the iterator to point to the newly inserted node. + * Returns -1 if failures occur, else 0. + */ + int insert (const T &new_item, ITERATOR &iter); + + /// Remove first occurrence of @a item from the set. Returns 0 if + /// it removes the item, -1 if it can't find the item. + /** + * Linear time search operation which removes the item from the set if found . + */ + int remove (const T &item); + + ///Linear find operation. + /** + * Finds first occurrence of @a item in the multiset, using the iterator's + * current position as a hint to improve performance. If find succeeds, + * it positions the iterator at that node and returns 0, or if it cannot + * locate the node, it leaves the iterator alone and just returns -1. + */ + int find (const T &item, ITERATOR &iter) const; + + /// Reset the ACE_Ordered_MultiSet to be empty. + /** + * Delete the nodes inside the set. + */ + void reset (void); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + + /** + * Insert @a item, starting its search at the position given, + * and if successful updates the passed pointer to point to + * the newly inserted item's node. + */ + int insert_from (const T &item, ACE_DNode *start_position, + ACE_DNode **new_position); + + /** + * Looks for first occurance of @a item in the ordered set, using the + * passed starting position as a hint: if there is such an instance, it + * updates the new_position pointer to point to this node and returns 0; + * if there is no such node, then if there is a node before where the + * item would have been, it updates the new_position pointer to point + * to this node and returns -1; if there is no such node, then if there + * is a node after where the item would have been, it updates the + * new_position pointer to point to this node (or 0 if there is no such + * node) and returns 1; + */ + int locate (const T &item, ACE_DNode *start_position, + ACE_DNode *&new_position) const; + + /// Delete all the nodes in the Set. + void delete_nodes (void); + + /// Copy nodes into this set. + void copy_nodes (const ACE_Ordered_MultiSet &); + + /// Head of the bilinked list of Nodes. + ACE_DNode *head_; + + /// Head of the bilinked list of Nodes. + ACE_DNode *tail_; + + /// Current size of the set. + size_t cur_size_; + + /// Allocation strategy of the set. + ACE_Allocator *allocator_; +}; + +// **************************************************************** + +/** + * @class ACE_Array + * + * @brief A dynamic array class. + * + * This class extends ACE_Array_Base, adding comparison operators. + * + * Requirements and Performance Characteristics + * - Internal Structure + * Dynamic array + * - Duplicates allowed? + * Yes + * - Random access allowed? + * Yes + * - Search speed + * N/A + * - Insert/replace speed + * O(1) + * - Iterator still valid after change to container? + * - In general, yes. + * - If array size is changed during iteration, no. + * - Frees memory for removed elements? + * No + * - Items inserted by + * Value + * - Requirements for contained type + * -# Default constructor + * -# Copy constructor + * -# operator= + * -# operator!= + * + * @sa ACE_Array_Base. This class inherits its operations and requirements. + */ +template +class ACE_Array : public ACE_Array_Base +{ +public: + // Define a "trait" + typedef T TYPE; + typedef ACE_Array_Iterator ITERATOR; + + /// Dynamically create an uninitialized array. + /** + * Initialize an empty array of the specified size using the provided + * allocation strategy. + */ + ACE_Array (size_t size = 0, + ACE_Allocator* alloc = 0); + + /// Dynamically initialize the entire array to the {default_value}. + /** + * Initialize an array the given size placing the default_value in each index. + */ + ACE_Array (size_t size, + const T &default_value, + ACE_Allocator* alloc = 0); + + ///Copy constructor. + /** + * The copy constructor performs initialization by making an exact + * copy of the contents of parameter {s}, i.e., *this == s will + * return true. + */ + ACE_Array (const ACE_Array &s); + + ///Assignment operator + /** + * Assignment operator performs an assignment by making an exact + * copy of the contents of parameter {s}, i.e., *this == s will + * return true. Note that if the {max_size_} of {array_} is >= than + * {s.max_size_} we can copy it without reallocating. However, if + * {max_size_} is < {s.max_size_} we must delete the {array_}, + * reallocate a new {array_}, and then copy the contents of {s}. + */ + void operator= (const ACE_Array &s); + + // = Compare operators + + ///Equality comparison operator. + /** + * Compare this array with {s} for equality. Two arrays are equal + * if their {size}'s are equal and all the elements from 0 .. {size} + * are equal. + */ + bool operator== (const ACE_Array &s) const; + + ///Inequality comparison operator. + /** + * Compare this array with {s} for inequality such that {*this} != + * {s} is always the complement of the boolean return value of + * {*this} == {s}. + */ + bool operator!= (const ACE_Array &s) const; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Containers_T.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Containers_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Containers_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" + +#endif /* ACE_CONTAINERS_T_H */ diff --git a/dep/acelite/ace/Containers_T.inl b/dep/acelite/ace/Containers_T.inl new file mode 100644 index 00000000000..912c9df8bb8 --- /dev/null +++ b/dep/acelite/ace/Containers_T.inl @@ -0,0 +1,479 @@ +// -*- C++ -*- +// +// $Id: Containers_T.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template ACE_INLINE int +ACE_Bounded_Stack::is_empty (void) const +{ + ACE_TRACE ("ACE_Bounded_Stack::is_empty"); + return this->top_ == 0; +} + +template ACE_INLINE int +ACE_Bounded_Stack::is_full (void) const +{ + ACE_TRACE ("ACE_Bounded_Stack::is_full"); + return this->top_ >= this->size_; +} + +template ACE_INLINE int +ACE_Bounded_Stack::push (const T &new_item) +{ + ACE_TRACE ("ACE_Bounded_Stack::push"); + if (this->is_full () == 0) + { + this->stack_[this->top_++] = new_item; + return 0; + } + else + return -1; +} + +template ACE_INLINE int +ACE_Bounded_Stack::pop (T &item) +{ + ACE_TRACE ("ACE_Bounded_Stack::pop"); + if (this->is_empty () == 0) + { + item = this->stack_[--this->top_]; + return 0; + } + else + return -1; +} + +template ACE_INLINE int +ACE_Bounded_Stack::top (T &item) const +{ + ACE_TRACE ("ACE_Bounded_Stack::top"); + if (this->is_empty () == 0) + { + item = this->stack_[this->top_ - 1]; + return 0; + } + else + return -1; +} + +template ACE_INLINE size_t +ACE_Bounded_Stack::size (void) const +{ + return this->size_; +} + +//---------------------------------------- + +template ACE_INLINE int +ACE_Fixed_Stack::is_empty (void) const +{ + ACE_TRACE ("ACE_Fixed_Stack::is_empty"); + return this->top_ == 0; +} + +template ACE_INLINE int +ACE_Fixed_Stack::is_full (void) const +{ + ACE_TRACE ("ACE_Fixed_Stack::is_full"); + return this->top_ >= this->size_; +} + +template ACE_INLINE int +ACE_Fixed_Stack::push (const T &new_item) +{ + ACE_TRACE ("ACE_Fixed_Stack::push"); + if (this->is_full () == 0) + { + this->stack_[this->top_++] = new_item; + return 0; + } + else + return -1; +} + +template ACE_INLINE int +ACE_Fixed_Stack::pop (T &item) +{ + ACE_TRACE ("ACE_Fixed_Stack::pop"); + if (this->is_empty () == 0) + { + item = this->stack_[--this->top_]; + return 0; + } + else + return -1; +} + +template ACE_INLINE int +ACE_Fixed_Stack::top (T &item) const +{ + ACE_TRACE ("ACE_Fixed_Stack::top"); + if (this->is_empty () == 0) + { + item = this->stack_[this->top_ - 1]; + return 0; + } + else + return -1; +} + +template ACE_INLINE size_t +ACE_Fixed_Stack::size (void) const +{ + return this->size_; +} + +template ACE_INLINE int +ACE_Unbounded_Stack::is_empty (void) const +{ + // ACE_TRACE ("ACE_Unbounded_Stack::is_empty"); + return this->head_ == this->head_->next_; +} + +template ACE_INLINE int +ACE_Unbounded_Stack::top (T &item) const +{ + ACE_TRACE ("ACE_Unbounded_Stack::top"); + if (this->is_empty () == 0) + { + item = this->head_->next_->item_; + return 0; + } + else + return -1; +} + +template ACE_INLINE int +ACE_Unbounded_Stack::is_full (void) const +{ + ACE_TRACE ("ACE_Unbounded_Stack::is_full"); + return 0; // ??? +} + +template ACE_INLINE size_t +ACE_Unbounded_Stack::size (void) const +{ + return this->cur_size_; +} + +// --- + + +// --- + +template ACE_INLINE int +ACE_Fixed_Set::is_empty (void) const +{ + ACE_TRACE ("ACE_Fixed_Set::is_empty"); + return this->cur_size_ == 0; +} + +template ACE_INLINE int +ACE_Fixed_Set::is_full (void) const +{ + ACE_TRACE ("ACE_Fixed_Set::is_full"); + return this->cur_size_ == this->max_size_; +} + +// --- + +template ACE_INLINE int +ACE_Bounded_Set::is_empty (void) const +{ + ACE_TRACE ("ACE_Bounded_Set::is_empty"); + return this->cur_size_ == 0; +} + +template ACE_INLINE int +ACE_Bounded_Set::is_full (void) const +{ + ACE_TRACE ("ACE_Bounded_Set::is_full"); + return this->cur_size_ == this->max_size_; +} + +// -- + +template ACE_INLINE int +ACE_Ordered_MultiSet_Iterator::first (void) +{ + ACE_TRACE ("ACE_Ordered_MultiSet_Iterator::first"); + current_ = set_.head_; + + return (current_ ? 1 : 0); +} + +template ACE_INLINE int +ACE_Ordered_MultiSet_Iterator::last (void) +{ + ACE_TRACE ("ACE_Ordered_MultiSet_Iterator::last"); + current_ = set_.tail_; + + return (current_ ? 1 : 0); +} + +template ACE_INLINE int +ACE_Ordered_MultiSet_Iterator::advance (void) +{ + ACE_TRACE ("ACE_Ordered_MultiSet_Iterator::advance"); + + current_ = current_ ? current_->next_ : 0; + + return (current_ ? 1 : 0); +} + +template ACE_INLINE int +ACE_Ordered_MultiSet_Iterator::retreat (void) +{ + ACE_TRACE ("ACE_Ordered_MultiSet_Iterator::retreat"); + + current_ = current_ ? current_->prev_ : 0; + + return (current_ ? 1 : 0); +} + +template ACE_INLINE int +ACE_Ordered_MultiSet_Iterator::done (void) const +{ + ACE_TRACE ("ACE_Ordered_MultiSet_Iterator::done"); + + return (current_ ? 0 : 1); +} + +template ACE_INLINE void +ACE_Ordered_MultiSet_Iterator::dump (void) const +{ +#if defined (ACE_HAS_DUMP) +// ACE_TRACE ("ACE_Ordered_MultiSet_Iterator::dump"); +#endif /* ACE_HAS_DUMP */ +} + + + +// -- + +template ACE_INLINE int +ACE_Ordered_MultiSet::is_empty (void) const +{ + ACE_TRACE ("ACE_Ordered_MultiSet::is_empty"); + return this->cur_size_ > 0 ? 0 : 1; +} + +template ACE_INLINE size_t +ACE_Ordered_MultiSet::size (void) const +{ +// ACE_TRACE ("ACE_Ordered_MultiSet::size"); + return this->cur_size_; +} + +// **************************************************************** + +template ACE_INLINE +ACE_Array::ACE_Array (size_t size, + ACE_Allocator *alloc) + : ACE_Array_Base (size, alloc) +{ +} + +template ACE_INLINE +ACE_Array::ACE_Array (size_t size, + const T &default_value, + ACE_Allocator *alloc) + : ACE_Array_Base (size, default_value, alloc) +{ +} + +// The copy constructor (performs initialization). + +template ACE_INLINE +ACE_Array::ACE_Array (const ACE_Array &s) + : ACE_Array_Base (s) +{ +} + +// Assignment operator (performs assignment). + +template ACE_INLINE void +ACE_Array::operator= (const ACE_Array &s) +{ + // Check for "self-assignment". + + if (this != &s) + this->ACE_Array_Base::operator= (s); +} + +// Compare this array with for inequality. + +template ACE_INLINE bool +ACE_Array::operator!= (const ACE_Array &s) const +{ + return !(*this == s); +} + +// **************************************************************** + + +// **************************************************************** + +template ACE_INLINE void +ACE_DLList::operator= (const ACE_DLList &l) +{ + *(ACE_DLList_Base *) this = l; +} + +template ACE_INLINE int +ACE_DLList::get (T *&item, size_t index) +{ + ACE_DLList_Node *node; + int result = ACE_DLList_Base::get (node, index); + if (result != -1) + item = (T *) node->item_; + return result; +} + +template ACE_INLINE void +ACE_DLList::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_DLList_Base::dump (); +#endif /* ACE_HAS_DUMP */ +} + +template ACE_INLINE int +ACE_DLList::remove (ACE_DLList_Node *n) +{ + int result = ACE_DLList_Base::remove (n); + ACE_DES_FREE (n, + this->allocator_->free, + ACE_DLList_Node); + return result; +} + +template ACE_INLINE +ACE_DLList::ACE_DLList (ACE_Allocator *alloc) + : ACE_DLList_Base (alloc) +{ +} + +template ACE_INLINE +ACE_DLList::ACE_DLList (const ACE_DLList &l) + : ACE_DLList_Base ((ACE_DLList &) l) +{ +} + +template ACE_INLINE +ACE_DLList::~ACE_DLList (void) +{ + while (this->delete_head ()) ; +} + +template ACE_INLINE int +ACE_DLList_Iterator::remove (void) +{ + ACE_DLList_Node *temp = this->ACE_Double_Linked_List_Iterator ::next (); + this->ACE_Double_Linked_List_Iterator ::advance (); + return list_->remove (temp); +} + +template ACE_INLINE +ACE_DLList_Iterator::ACE_DLList_Iterator (ACE_DLList &l) + : ACE_Double_Linked_List_Iterator ((ACE_DLList_Base &)l), + list_ (&l) +{ +} + +template ACE_INLINE void +ACE_DLList_Iterator::reset (ACE_DLList &l) +{ + list_ = &l; + this->ACE_Double_Linked_List_Iterator ::reset ((ACE_DLList_Base &)l); +} + +template ACE_INLINE int +ACE_DLList_Iterator::next (T *&ptr) +{ + ACE_DLList_Node *temp = + ACE_Double_Linked_List_Iterator ::next (); + if (temp) + ptr = (T *) temp->item_; + return temp ? 1 : 0; +} + +template ACE_INLINE T * +ACE_DLList_Iterator::next (void) const +{ + ACE_DLList_Node *temp = ACE_Double_Linked_List_Iterator ::next (); + return (T *) (temp ? temp->item_ : 0); +} + +template ACE_INLINE int +ACE_DLList_Iterator::advance (void) +{ + return this->ACE_Double_Linked_List_Iterator ::advance (); +} + +template ACE_INLINE void +ACE_DLList_Iterator::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_Double_Linked_List_Iterator ::dump (); +#endif /* ACE_HAS_DUMP */ +} + + +template ACE_INLINE int +ACE_DLList_Reverse_Iterator::remove (void) +{ + ACE_DLList_Node *temp = ACE_Double_Linked_List_Reverse_Iterator ::next (); + this->ACE_Double_Linked_List_Reverse_Iterator ::advance (); + return list_->remove (temp); +} + +template ACE_INLINE +ACE_DLList_Reverse_Iterator::ACE_DLList_Reverse_Iterator (ACE_DLList &l) + : ACE_Double_Linked_List_Reverse_Iterator ((ACE_DLList_Base &)l), + list_ (&l) +{ +} + +template ACE_INLINE void +ACE_DLList_Reverse_Iterator::reset (ACE_DLList &l) +{ + list_ = &l; + this->ACE_Double_Linked_List_Reverse_Iterator ::reset ((ACE_DLList_Base &)l); +} + +template ACE_INLINE int +ACE_DLList_Reverse_Iterator::advance (void) +{ + return ACE_Double_Linked_List_Reverse_Iterator ::advance (); +} + +template ACE_INLINE int +ACE_DLList_Reverse_Iterator::next (T *&ptr) +{ + ACE_DLList_Node *temp = + ACE_Double_Linked_List_Reverse_Iterator ::next (); + if (temp == 0) + return 0; + ptr = (T *) temp->item_; + return 1; +} + +template ACE_INLINE T * +ACE_DLList_Reverse_Iterator::next (void) const +{ + ACE_DLList_Node *temp = ACE_Double_Linked_List_Reverse_Iterator ::next (); + return (T *) (temp ? temp->item_ : 0); +} + + +template ACE_INLINE void +ACE_DLList_Reverse_Iterator::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_Double_Linked_List_Reverse_Iterator ::dump (); +#endif /* ACE_HAS_DUMP */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Copy_Disabled.cpp b/dep/acelite/ace/Copy_Disabled.cpp new file mode 100644 index 00000000000..6878311197d --- /dev/null +++ b/dep/acelite/ace/Copy_Disabled.cpp @@ -0,0 +1,23 @@ +/** + * @file Copy_Disabled.cpp + * + * $Id: Copy_Disabled.cpp 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Carlos O'Ryan + */ + +#include "ace/Copy_Disabled.h" + + +ACE_RCSID (ace, + Copy_Disabled, + "$Id: Copy_Disabled.cpp 80826 2008-03-04 14:51:23Z wotte $") + + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_Copy_Disabled::ACE_Copy_Disabled (void) +{ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Copy_Disabled.h b/dep/acelite/ace/Copy_Disabled.h new file mode 100644 index 00000000000..f7b40e26422 --- /dev/null +++ b/dep/acelite/ace/Copy_Disabled.h @@ -0,0 +1,65 @@ +// -*- C++ -*- + +//=========================================================================== +/** + * @file Copy_Disabled.h + * + * $Id: Copy_Disabled.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Carlos O'Ryan + */ +//=========================================================================== + +#ifndef ACE_COPY_DISABLED_H +#define ACE_COPY_DISABLED_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Copy_Disabled + * + * @brief Helper class to disable copy construction and assignment + * + * Classes used to control OS and other resources are not "canonical", + * i.e. they have their copy constructor and assignment operators + * disabled. + * This is often done by making the copy constructor and assignment + * operators private, effectively disallowing copying by clients of + * the class (including derived classes). If the copy constructor and + * assingment operators are left unimplemented then the class itself + * cannot make any copies of its instances, because it would result in + * link errors. + * + * To use this class simply use private inheritance: + * + * class Foo : private ACE_Copy_Disabled + * { + * // code here + * }; + * + */ +class ACE_Export ACE_Copy_Disabled +{ +public: + + /// Default constructor + ACE_Copy_Disabled (void); + +private: + ACE_Copy_Disabled (const ACE_Copy_Disabled &); + ACE_Copy_Disabled &operator= (const ACE_Copy_Disabled &); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" + +#endif /* ACE_COPY_DISABLED_H */ diff --git a/dep/acelite/ace/Countdown_Time.cpp b/dep/acelite/ace/Countdown_Time.cpp new file mode 100644 index 00000000000..d76a0fa4cf5 --- /dev/null +++ b/dep/acelite/ace/Countdown_Time.cpp @@ -0,0 +1,59 @@ +#include "ace/Countdown_Time.h" +#include "ace/OS_NS_sys_time.h" + +ACE_RCSID (ace, + Countdown_Time, + "$Id: Countdown_Time.cpp 85382 2009-05-19 06:52:56Z johnnyw $") + +#if !defined (__ACE_INLINE__) +#include "ace/Countdown_Time.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_Countdown_Time::ACE_Countdown_Time (ACE_Time_Value *max_wait_time) + : max_wait_time_ (max_wait_time), + stopped_ (false) +{ + this->start (); +} + +ACE_Countdown_Time::~ACE_Countdown_Time (void) +{ + this->stop (); +} + +void +ACE_Countdown_Time::start (void) +{ + if (this->max_wait_time_ != 0) + { + this->start_time_ = ACE_OS::gettimeofday (); + this->stopped_ = false; + } +} + +void +ACE_Countdown_Time::stop (void) +{ + if (this->max_wait_time_ != 0 && !this->stopped_) + { + ACE_Time_Value const elapsed_time = + ACE_OS::gettimeofday () - this->start_time_; + + if (elapsed_time >= ACE_Time_Value::zero && + *this->max_wait_time_ > elapsed_time) + { + *this->max_wait_time_ -= elapsed_time; + } + else + { + // Used all of timeout. + *this->max_wait_time_ = ACE_Time_Value::zero; + // errno = ETIME; + } + this->stopped_ = true; + } +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Countdown_Time.h b/dep/acelite/ace/Countdown_Time.h new file mode 100644 index 00000000000..b9c9a467f62 --- /dev/null +++ b/dep/acelite/ace/Countdown_Time.h @@ -0,0 +1,81 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Countdown_Time.h + * + * $Id: Countdown_Time.h 85365 2009-05-18 08:27:42Z johnnyw $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_COUNTDOWN_TIME_H +#define ACE_COUNTDOWN_TIME_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Time_Value.h" +#include "ace/Copy_Disabled.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Countdown_Time + * + * @brief Keeps track of the amount of elapsed time. + * + * This class has a side-effect on the @c max_wait_time -- every + * time the stop() method is called the @c max_wait_time is + * updated. + */ +class ACE_Export ACE_Countdown_Time : private ACE_Copy_Disabled +{ +public: + /// Cache the @a max_wait_time and call @c start(). + ACE_Countdown_Time (ACE_Time_Value *max_wait_time); + + /// Destructor, makes sure the max_wait_time that got passed as pointer + /// to the constructor is updated with the time elapsed. + ~ACE_Countdown_Time (void); + + /// Cache the current time and enter a start state. + void start (void); + + /// Subtract the elapsed time from max_wait_time_ and enter a stopped + /// state. + void stop (void); + + /// Calls stop and then start. max_wait_time_ is modified by the + /// call to stop. + void update (void); + + /// Returns true if we've already been stopped, else false. + bool stopped (void) const; + +private: + /// Maximum time we were willing to wait. + ACE_Time_Value *max_wait_time_; + + /// Beginning of the start time. + ACE_Time_Value start_time_; + + /// Keeps track of whether we've already been stopped. + bool stopped_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" + +#if defined (__ACE_INLINE__) +#include "ace/Countdown_Time.inl" +#endif /* __ACE_INLINE__ */ + +#endif /* ACE_COUNTDOWN_TIME_H */ diff --git a/dep/acelite/ace/Countdown_Time.inl b/dep/acelite/ace/Countdown_Time.inl new file mode 100644 index 00000000000..4a9eb8e0e43 --- /dev/null +++ b/dep/acelite/ace/Countdown_Time.inl @@ -0,0 +1,20 @@ +// -*- C++ -*- +// +// $Id: Countdown_Time.inl 85368 2009-05-18 10:23:19Z johnnyw $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE bool +ACE_Countdown_Time::stopped (void) const +{ + return stopped_; +} + +ACE_INLINE void +ACE_Countdown_Time::update (void) +{ + this->stop (); + this->start (); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/DEV.cpp b/dep/acelite/ace/DEV.cpp new file mode 100644 index 00000000000..42178a68e6b --- /dev/null +++ b/dep/acelite/ace/DEV.cpp @@ -0,0 +1,43 @@ +// $Id: DEV.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/DEV.h" + +#include "ace/OS_NS_unistd.h" + +#if !defined (__ACE_INLINE__) +#include "ace/DEV.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID(ace, DEV, "$Id: DEV.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_DEV) + +void +ACE_DEV::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_DEV::dump"); +#endif /* ACE_HAS_DUMP */ +} + +// This is the do-nothing constructor. + +ACE_DEV::ACE_DEV (void) +{ + ACE_TRACE ("ACE_DEV::ACE_DEV"); +} + +// Close the device + +int +ACE_DEV::close (void) +{ + ACE_TRACE ("ACE_DEV::close"); + int result = ACE_OS::close (this->get_handle ()); + this->set_handle (ACE_INVALID_HANDLE); + return result; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/DEV.h b/dep/acelite/ace/DEV.h new file mode 100644 index 00000000000..86f8d5dc863 --- /dev/null +++ b/dep/acelite/ace/DEV.h @@ -0,0 +1,78 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file DEV.h + * + * $Id: DEV.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Gerhard Lenzer + */ +//============================================================================= + + +#ifndef ACE_DEV_H +#define ACE_DEV_H +#include /**/ "ace/pre.h" + +#include "ace/IO_SAP.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/DEV_Addr.h" + +// The following is necessary since many C++ compilers don't support +// typedef'd types inside of classes used as formal template +// arguments... ;-(. Luckily, using the C++ preprocessor I can hide +// most of this nastiness! + +#if defined (ACE_HAS_TEMPLATE_TYPEDEFS) +#define ACE_DEV_CONNECTOR ACE_DEV_Connector +#define ACE_DEV_STREAM ACE_DEV_IO +#else /* TEMPLATES are broken (must be a cfront-based compiler...) */ +#define ACE_DEV_CONNECTOR ACE_DEV_Connector, ACE_DEV_Addr +#define ACE_DEV_STREAM ACE_DEV_IO, ACE_DEV_Addr +#endif /* ACE_TEMPLATE_TYPEDEFS */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_DEV + * + * @brief Defines the member functions for the base class of the + * ACE_DEV abstraction. + */ +class ACE_Export ACE_DEV : public ACE_IO_SAP +{ +public: + /// Close down the DEVICE + int close (void); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + + /** + * Disable signal @a signum + * This is here to prevent Win32 from + * disabling SPIPE using socket calls + */ + int disable (int signum) const ; + +protected: + /// Ensure that this class is an abstract base class + ACE_DEV (void); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/DEV.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_DEV_H */ diff --git a/dep/acelite/ace/DEV.inl b/dep/acelite/ace/DEV.inl new file mode 100644 index 00000000000..4d97a73d8e8 --- /dev/null +++ b/dep/acelite/ace/DEV.inl @@ -0,0 +1,18 @@ +// -*- C++ -*- +// +// $Id: DEV.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE int +ACE_DEV::disable (int signum) const +{ +#if defined (ACE_WIN32) + ACE_UNUSED_ARG (signum) ; + return 0 ; +#else /* ACE_WIN32 */ + return ACE_IO_SAP::disable (signum) ; +#endif /* ACE_WIN32 */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/DEV_Addr.cpp b/dep/acelite/ace/DEV_Addr.cpp new file mode 100644 index 00000000000..64bbb50873c --- /dev/null +++ b/dep/acelite/ace/DEV_Addr.cpp @@ -0,0 +1,108 @@ +// $Id: DEV_Addr.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/DEV_Addr.h" +#if !defined (__ACE_INLINE__) +#include "ace/DEV_Addr.inl" +#endif /* __ACE_INLINE__ */ + +#include "ace/Log_Msg.h" +#include "ace/OS_NS_string.h" + +ACE_RCSID (ace, + DEV_Addr, + "$Id: DEV_Addr.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_DEV_Addr) + +// Transform the current address into string format. + +int +ACE_DEV_Addr::addr_to_string (ACE_TCHAR *s, size_t len) const +{ + ACE_TRACE ("ACE_DEV_Addr::addr_to_string"); + + ACE_OS::strsncpy (s, this->devname_, len); + return 0; +} + +// Return a pointer to the address. + +void * +ACE_DEV_Addr::get_addr (void) const +{ + ACE_TRACE ("ACE_DEV_Addr::get_addr"); + + return (void *) &this->devname_; +} + +void +ACE_DEV_Addr::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_DEV_Addr::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("devname_ = %s"), this->devname_)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +// Do nothing constructor. + +ACE_DEV_Addr::ACE_DEV_Addr (void) + : ACE_Addr (AF_DEV, sizeof this->devname_) +{ + ACE_TRACE ("ACE_DEV_Addr::ACE_DEV_Addr"); + + (void) ACE_OS::memset ((void *) &this->devname_, + 0, sizeof this->devname_); +} + +int +ACE_DEV_Addr::set (const ACE_DEV_Addr &sa) +{ + this->base_set (sa.get_type (), sa.get_size ()); + + if (sa.get_type () == AF_ANY) + (void) ACE_OS::memset ((void *) &this->devname_, + 0, + sizeof this->devname_); + else + (void) ACE_OS::strsncpy (this->devname_, + sa.devname_, + ACE_DEV_Addr::DEVNAME_LENGTH); + return 0; +} + +// Copy constructor. + +ACE_DEV_Addr::ACE_DEV_Addr (const ACE_DEV_Addr &sa) + : ACE_Addr (AF_DEV, sizeof this->devname_) +{ + ACE_TRACE ("ACE_DEV_Addr::ACE_DEV_Addr"); + + this->set (sa); +} + +ACE_DEV_Addr::ACE_DEV_Addr (const ACE_TCHAR *devname) + : ACE_Addr (AF_DEV, sizeof this->devname_) +{ + ACE_TRACE ("ACE_DEV_Addr::ACE_DEV_Addr"); + + this->set (devname); +} + +ACE_DEV_Addr & +ACE_DEV_Addr::operator= (const ACE_DEV_Addr &sa) +{ + ACE_TRACE ("ACE_DEV_Addr::operator="); + + if (this != &sa) + this->set (sa); + + return *this; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/DEV_Addr.h b/dep/acelite/ace/DEV_Addr.h new file mode 100644 index 00000000000..49ec5023a7c --- /dev/null +++ b/dep/acelite/ace/DEV_Addr.h @@ -0,0 +1,90 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file DEV_Addr.h + * + * $Id: DEV_Addr.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Gerhard Lenzer and Douglas C. Schmidt + */ +//========================================================================== + +#ifndef ACE_DEV_ADDR_H +#define ACE_DEV_ADDR_H + +#include /**/ "ace/pre.h" + +#include "ace/Addr.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/os_dirent.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_DEV_Addr + * + * @brief Defines device address family address format. + */ +class ACE_Export ACE_DEV_Addr : public ACE_Addr +{ +public: + // = Initialization methods. + /// Default constructor. + ACE_DEV_Addr (void); + + /// Copy constructor. + ACE_DEV_Addr (const ACE_DEV_Addr &sa); + + /// Acts like a copy constructor. + int set (const ACE_DEV_Addr &sa); + + /// Create a ACE_DEV_Addr from a device name. + explicit ACE_DEV_Addr (const ACE_TCHAR *devname); + + /// Create a ACE_Addr from a ACE_DEV pathname. + void set (const ACE_TCHAR *devname); + + /// Assignment operator. + ACE_DEV_Addr &operator= (const ACE_DEV_Addr &); + + /// Return a pointer to the address. + virtual void *get_addr (void) const; + + /// Transform the current address into string format. + virtual int addr_to_string (ACE_TCHAR *addr, size_t) const; + + /// Compare two addresses for equality. + bool operator == (const ACE_DEV_Addr &SAP) const; + + /// Compare two addresses for inequality. + bool operator != (const ACE_DEV_Addr &SAP) const; + + /// Return the path name used for the rendezvous point. + const ACE_TCHAR *get_path_name (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + enum { DEVNAME_LENGTH = MAXPATHLEN + 1 }; + /// Name of the device. + ACE_TCHAR devname_[DEVNAME_LENGTH]; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/DEV_Addr.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" + +#endif /* ACE_DEV_ADDR_H */ diff --git a/dep/acelite/ace/DEV_Addr.inl b/dep/acelite/ace/DEV_Addr.inl new file mode 100644 index 00000000000..5c1da68d7e7 --- /dev/null +++ b/dep/acelite/ace/DEV_Addr.inl @@ -0,0 +1,51 @@ +// -*- C++ -*- +// +// $Id: DEV_Addr.inl 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/OS_NS_string.h" +#include "ace/Global_Macros.h" +#include "ace/os_include/sys/os_socket.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE void +ACE_DEV_Addr::set (const ACE_TCHAR *devname) +{ + ACE_TRACE ("ACE_DEV_Addr::set"); + + this->ACE_Addr::base_set + (AF_DEV, static_cast (ACE_OS::strlen (devname))); + ACE_OS::strsncpy (this->devname_, devname, ACE_DEV_Addr::DEVNAME_LENGTH); +} + +// Compare two addresses for equality. + +ACE_INLINE bool +ACE_DEV_Addr::operator == (const ACE_DEV_Addr &sap) const +{ + ACE_TRACE ("ACE_DEV_Addr::operator =="); + + return ACE_OS::strcmp (this->devname_, sap.devname_) == 0; +} + +// Compare two addresses for inequality. + +ACE_INLINE bool +ACE_DEV_Addr::operator != (const ACE_DEV_Addr &sap) const +{ + ACE_TRACE ("ACE_DEV_Addr::operator !="); + + return !((*this) == sap); // This is lazy, of course... ;-). +} + +// Return the path name used for the rendezvous point. + +ACE_INLINE const ACE_TCHAR * +ACE_DEV_Addr::get_path_name (void) const +{ + ACE_TRACE ("ACE_DEV_Addr::get_path_name"); + + return this->devname_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/DEV_Connector.cpp b/dep/acelite/ace/DEV_Connector.cpp new file mode 100644 index 00000000000..bdc2530acd8 --- /dev/null +++ b/dep/acelite/ace/DEV_Connector.cpp @@ -0,0 +1,53 @@ +// $Id: DEV_Connector.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/DEV_Connector.h" + +#include "ace/Handle_Ops.h" + +#if !defined (__ACE_INLINE__) +#include "ace/DEV_Connector.inl" +#endif /* __ACE_INLINE__ */ + + +ACE_RCSID (ace, + DEV_Connector, + "$Id: DEV_Connector.cpp 80826 2008-03-04 14:51:23Z wotte $") + + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_DEV_Connector) + +void +ACE_DEV_Connector::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_DEV_Connector::dump"); +#endif /* ACE_HAS_DUMP */ +} + +ACE_DEV_Connector::ACE_DEV_Connector (void) +{ + ACE_TRACE ("ACE_DEV_Connector::ACE_DEV_Connector"); +} + +int +ACE_DEV_Connector::connect (ACE_DEV_IO &new_io, + const ACE_DEV_Addr &remote_sap, + ACE_Time_Value *timeout, + const ACE_Addr &, + int, + int flags, + int perms) +{ + ACE_TRACE ("ACE_DEV_Connector::connect"); + + ACE_HANDLE handle = ACE::handle_timed_open (timeout, + remote_sap.get_path_name (), + flags, perms); + new_io.set_handle (handle); + new_io.addr_ = remote_sap; // class copy. + return handle == ACE_INVALID_HANDLE ? -1 : 0; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/DEV_Connector.h b/dep/acelite/ace/DEV_Connector.h new file mode 100644 index 00000000000..2f71f608882 --- /dev/null +++ b/dep/acelite/ace/DEV_Connector.h @@ -0,0 +1,110 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file DEV_Connector.h + * + * $Id: DEV_Connector.h 82723 2008-09-16 09:35:44Z johnnyw $ + * + * @author Gerhard Lenzer and Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_DEV_CONNECTOR_H +#define ACE_DEV_CONNECTOR_H +#include /**/ "ace/pre.h" + +#include "ace/DEV_IO.h" +#include "ace/Log_Msg.h" +#include "ace/os_include/os_fcntl.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_DEV_Connector + * + * @brief Defines an active connection factory for the ACE_DEV wrappers. + */ +class ACE_Export ACE_DEV_Connector +{ +public: + /// Default constructor. + ACE_DEV_Connector (void); + + /** + * Actively connect and produce a @a new_io if things go well. + * The @a remote_sap is the address that we are trying to connect + * with. The @a timeout is the amount of time to wait to connect. + * If it's 0 then we block indefinitely. If *timeout == {0, 0} then + * the connection is done using non-blocking mode. In this case, if + * the connection can't be made immediately the value of -1 is + * returned with @c errno == EWOULDBLOCK. If *timeout > {0, 0} then + * this is the maximum amount of time to wait before timing out. If the + * time expires before the connection is made @c errno == ETIME. The + * @a local_sap is the value of local address to bind to. If it's + * the default value of ACE_Addr::sap_any then the user is letting + * the OS do the binding. If @a reuse_addr == 1 then the + * is reused, even if it hasn't been cleanedup yet. + * The @a flags and @a perms arguments are passed down to the + * method. + */ + ACE_DEV_Connector (ACE_DEV_IO &new_io, + const ACE_DEV_Addr &remote_sap, + ACE_Time_Value *timeout = 0, + const ACE_Addr &local_sap = ACE_Addr::sap_any, + int reuse_addr = 0, + int flags = O_RDWR, + int perms = 0); + + /** + * Actively connect and produce a @a new_io if things go well. + * The @a remote_sap is the address that we are trying to connect + * with. The @a timeout is the amount of time to wait to connect. + * If it's 0 then we block indefinitely. If *timeout == {0, 0} then + * the connection is done using non-blocking mode. In this case, if + * the connection can't be made immediately the value of -1 is + * returned with @c errno == EWOULDBLOCK. If *timeout > {0, 0} then + * this is the maximum amount of time to wait before timing out. If the + * time expires before the connection is made @c errno == ETIME. The + * @a local_sap is the value of local address to bind to. If it's + * the default value of ACE_Addr::sap_any then the user is letting + * the OS do the binding. If @a reuse_addr == 1 then the + * is reused, even if it hasn't been cleanedup yet. + * The @a flags and @a perms arguments are passed down to the + * method. + */ + int connect (ACE_DEV_IO &new_io, + const ACE_DEV_Addr &remote_sap, + ACE_Time_Value *timeout = 0, + const ACE_Addr &local_sap = ACE_Addr::sap_any, + int reuse_addr = 0, + int flags = O_RDWR, + int perms = 0); + + /// Resets any event associations on this handle + bool reset_new_handle (ACE_HANDLE handle); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + + // = Meta-type info + typedef ACE_DEV_Addr PEER_ADDR; + typedef ACE_DEV_IO PEER_STREAM; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/DEV_Connector.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_DEV_CONNECTOR_H */ diff --git a/dep/acelite/ace/DEV_Connector.inl b/dep/acelite/ace/DEV_Connector.inl new file mode 100644 index 00000000000..a57a38b71f4 --- /dev/null +++ b/dep/acelite/ace/DEV_Connector.inl @@ -0,0 +1,33 @@ +// -*- C++ -*- +// +// $Id: DEV_Connector.inl 82723 2008-09-16 09:35:44Z johnnyw $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Creates a Local ACE_DEV. + +ACE_INLINE +ACE_DEV_Connector::ACE_DEV_Connector (ACE_DEV_IO &new_io, + const ACE_DEV_Addr &remote_sap, + ACE_Time_Value *timeout, + const ACE_Addr &local_sap, + int reuse_addr, + int flags, + int perms) +{ + ACE_TRACE ("ACE_DEV_Connector::ACE_DEV_Connector"); + if (this->connect (new_io, remote_sap, timeout, local_sap, + reuse_addr, flags, perms) == ACE_IO_SAP::INVALID_HANDLE + && timeout != 0 && !(errno == EWOULDBLOCK || errno == ETIME)) + ACE_ERROR ((LM_ERROR, ACE_TEXT ("address %s, %p\n"), + remote_sap.get_path_name (), ACE_TEXT ("ACE_DEV_IO"))); +} + +ACE_INLINE bool +ACE_DEV_Connector::reset_new_handle (ACE_HANDLE) +{ + // Nothing to do here since the handle is not a socket + return false; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/DEV_IO.cpp b/dep/acelite/ace/DEV_IO.cpp new file mode 100644 index 00000000000..b9a8e1f46b9 --- /dev/null +++ b/dep/acelite/ace/DEV_IO.cpp @@ -0,0 +1,131 @@ +// $Id: DEV_IO.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/DEV_IO.h" +#include "ace/Log_Msg.h" + +#if !defined (__ACE_INLINE__) +#include "ace/DEV_IO.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID(ace, DEV_IO, "$Id: DEV_IO.cpp 80826 2008-03-04 14:51:23Z wotte $") + + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_DEV_IO) + +// Return the local endpoint address. + +int +ACE_DEV_IO::get_local_addr (ACE_DEV_Addr &addr) const +{ + ACE_TRACE ("ACE_DEV_IO::get_local_addr"); + + addr = this->addr_; + return 0; +} + +// Return the address of the remotely connected peer (if there is +// one). + +int +ACE_DEV_IO::get_remote_addr (ACE_DEV_Addr &addr) const +{ + ACE_TRACE ("ACE_DEV_IO::get_remote_addr"); + addr = this->addr_; + return 0; +} + +void +ACE_DEV_IO::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_DEV_IO::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + this->addr_.dump (); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +// Simple-minded do nothing constructor. + +ACE_DEV_IO::ACE_DEV_IO (void) +{ + ACE_TRACE ("ACE_DEV_IO::ACE_DEV_IO"); +} + +// Send N char *ptrs and int lengths. Note that the char *'s precede +// the ints (basically, an varargs version of writev). The count N is +// the *total* number of trailing arguments, *not* a couple of the +// number of tuple pairs! + +ssize_t +ACE_DEV_IO::send (size_t n, ...) const +{ + ACE_TRACE ("ACE_DEV_IO::send"); + va_list argp; + int total_tuples = static_cast (n / 2); + iovec *iovp; +#if defined (ACE_HAS_ALLOCA) + iovp = (iovec *) alloca (total_tuples * sizeof (iovec)); +#else + ACE_NEW_RETURN (iovp, + iovec[total_tuples], + -1); +#endif /* !defined (ACE_HAS_ALLOCA) */ + + va_start (argp, n); + + for (int i = 0; i < total_tuples; i++) + { + iovp[i].iov_base = va_arg (argp, char *); + iovp[i].iov_len = va_arg (argp, int); + } + + ssize_t result = ACE_OS::writev (this->get_handle (), iovp, total_tuples); +#if !defined (ACE_HAS_ALLOCA) + delete [] iovp; +#endif /* !defined (ACE_HAS_ALLOCA) */ + va_end (argp); + return result; +} + +// This is basically an interface to ACE_OS::readv, that doesn't use the +// struct iovec explicitly. The ... can be passed as an arbitrary +// number of (char *ptr, int len) tuples. However, the count N is the +// *total* number of trailing arguments, *not* a couple of the number +// of tuple pairs! + +ssize_t +ACE_DEV_IO::recv (size_t n, ...) const +{ + ACE_TRACE ("ACE_DEV_IO::recv"); + va_list argp; + int total_tuples = static_cast (n / 2); + iovec *iovp; +#if defined (ACE_HAS_ALLOCA) + iovp = (iovec *) alloca (total_tuples * sizeof (iovec)); +#else + ACE_NEW_RETURN (iovp, + iovec[total_tuples], + -1); +#endif /* !defined (ACE_HAS_ALLOCA) */ + + va_start (argp, n); + + for (int i = 0; i < total_tuples; i++) + { + iovp[i].iov_base = va_arg (argp, char *); + iovp[i].iov_len = va_arg (argp, int); + } + + ssize_t result = ACE_OS::readv (this->get_handle (), iovp, total_tuples); +#if !defined (ACE_HAS_ALLOCA) + delete [] iovp; +#endif /* !defined (ACE_HAS_ALLOCA) */ + va_end (argp); + return result; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/DEV_IO.h b/dep/acelite/ace/DEV_IO.h new file mode 100644 index 00000000000..3b1c3deb334 --- /dev/null +++ b/dep/acelite/ace/DEV_IO.h @@ -0,0 +1,185 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file DEV_IO.h + * + * $Id: DEV_IO.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Gerhard Lenzer + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_DEV_IO_H +#define ACE_DEV_IO_H +#include /**/ "ace/pre.h" + +#include "ace/DEV.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_STREAM_PIPES) +# include "ace/OS_NS_stropts.h" +#endif /* ACE_HAS_STREAM_PIPES */ + +#include "ace/os_include/os_stdio.h" +#include "ace/os_include/sys/os_uio.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +class ACE_Time_Value; + +/** + * @class ACE_DEV_IO + * + * @brief Read/Write operations on Devices. + */ +class ACE_Export ACE_DEV_IO : public ACE_DEV +{ +public: + friend class ACE_DEV_Connector; + + /// Default constructor. + ACE_DEV_IO (void); + + // = Various send operations. + /// send upto @a n bytes in @a buf. + ssize_t send (const void *buf, size_t n) const; + + /// Recv upto @a n bytes in @a buf. + ssize_t recv (void *buf, size_t n) const; + + /// Send n bytes, keep trying until n are sent. + ssize_t send_n (const void *buf, + size_t n) const; + + /** + * @name I/O operations + * + * Notes on common parameters: + * + * @a buf is the buffer to write from or receive into. + * + * @a len is the number of bytes to transfer. + * + * The @a timeout parameter in the following methods indicates how + * long to blocking trying to transfer data. If @a timeout == 0, + * then the call behaves as a normal send/recv call, i.e., for + * blocking sockets, the call will block until action is possible; + * for non-blocking sockets, EWOULDBLOCK will be returned if no + * action is immediately possible. + * + * If @a timeout != 0, the call will wait until the relative time + * specified in *@a timeout elapses. + * + * The "_n()" I/O methods keep looping until all the data has been + * transferred. These methods also work for sockets in non-blocking + * mode i.e., they keep looping on EWOULDBLOCK. @a timeout is used + * to make sure we keep making progress, i.e., the same timeout + * value is used for every I/O operation in the loop and the timeout + * is not counted down. + * + * The return values for the "*_n()" methods match the return values + * from the non "_n()" methods and are specified as follows: + * + * - On complete transfer, the number of bytes transferred is returned. + * - On timeout, -1 is returned, errno == ETIME. + * - On error, -1 is returned, errno is set to appropriate error. + * - On EOF, 0 is returned, errno is irrelevant. + * + * On partial transfers, i.e., if any data is transferred before + * timeout/error/EOF, @a bytes_transferred will contain the number of + * bytes transferred. + */ + ssize_t recv_n (void *buf, + size_t n, + const ACE_Time_Value *timeout = 0, + size_t *bytes_transferred = 0) const; + +#if defined (ACE_HAS_STREAM_PIPES) + /// Recv bytes via STREAM pipes using "band" mode. + ssize_t recv (ACE_Str_Buf *cntl, + ACE_Str_Buf *data, + int *band, + int *flags) const; + + /// Send bytes via STREAM pipes using "band" mode. + ssize_t send (const ACE_Str_Buf *cntl, + const ACE_Str_Buf *data, + int band, + int flags) const; + + /// Recv @a cntl and @a data via STREAM pipes. + ssize_t recv (ACE_Str_Buf *cntl, + ACE_Str_Buf *data, + int *flags) const; + + /// Send @a cntl and @a data via STREAM pipes. + ssize_t send (const ACE_Str_Buf *cntl, + const ACE_Str_Buf *data, + int flags = 0) const; +#endif /* ACE_HAS_STREAM_PIPES */ + + /// Send iovecs via <::writev>. + ssize_t send (const iovec iov[], size_t n) const; + + /// Recv iovecs via <::readv>. + ssize_t recv (iovec iov[], size_t n) const; + + /** + * Send N char *ptrs and int lengths. Note that the char *'s + * precede the ints (basically, an varargs version of writev). The + * count N is the *total* number of trailing arguments, *not* a + * couple of the number of tuple pairs! + */ + ssize_t send (size_t n, ...) const; + + /** + * This is an interface to ::readv, that doesn't use the struct + * iovec explicitly. The ... can be passed as an arbitrary number + * of (char *ptr, int len) tuples. However, the count N is the + * *total* number of trailing arguments, *not* a couple of the + * number of tuple pairs! + */ + ssize_t recv (size_t n, ...) const; + + /// Send @a n bytes via Win32 WriteFile using overlapped I/O. + ssize_t send (const void *buf, size_t n, ACE_OVERLAPPED *overlapped) const; + + /// Recv @a n bytes via Win32 ReadFile using overlapped I/O. + ssize_t recv (void *buf, size_t n, ACE_OVERLAPPED *overlapped) const; + + /// Dump the state of an object. + void dump (void) const; + + // = The following two methods are no-ops to keep the + // ACE_Connector happy. + /// Return the local endpoint address. + int get_local_addr (ACE_DEV_Addr &) const; + + /// Return the address of the remotely connected peer (if there is + /// one). + int get_remote_addr (ACE_DEV_Addr &) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + + // = Meta-type info + typedef ACE_DEV_Addr PEER_ADDR; + +private: + /// Address of device we are connected to. + ACE_DEV_Addr addr_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/DEV_IO.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_DEV_IO_H */ diff --git a/dep/acelite/ace/DEV_IO.inl b/dep/acelite/ace/DEV_IO.inl new file mode 100644 index 00000000000..796d24e114a --- /dev/null +++ b/dep/acelite/ace/DEV_IO.inl @@ -0,0 +1,126 @@ +// -*- C++ -*- +// +// $Id: DEV_IO.inl 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/OS_NS_sys_uio.h" +#include "ace/OS_NS_unistd.h" +#include "ace/OS_Memory.h" + +#include "ace/ACE.h" + +// Send exactly N bytes from BUF to this device. Keeping trying until +// this many bytes are sent. + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE ssize_t +ACE_DEV_IO::send_n (const void *buf, size_t n) const +{ + ACE_TRACE ("ACE_DEV_IO::send_n"); + return ACE::write_n (this->get_handle (), buf, n); +} + +// Receive exactly N bytes from this file into BUF. Keep trying until +// this many bytes are received. + +ACE_INLINE ssize_t +ACE_DEV_IO::recv_n (void *buf, + size_t n, + const ACE_Time_Value *timeout, + size_t *bytes_transferred) const +{ + ACE_TRACE ("ACE_DEV_IO::recv_n"); +#if defined (ACE_WIN32) + ACE_UNUSED_ARG (timeout); + + return ACE::read_n (this->get_handle (), + buf, + n, + bytes_transferred); +#else + return ACE::recv_n (this->get_handle (), + buf, + n, + timeout, + bytes_transferred); +#endif /*ACE_WIN32*/ +} + +ACE_INLINE ssize_t +ACE_DEV_IO::send (const void *buf, size_t n) const +{ + ACE_TRACE ("ACE_DEV_IO::send"); + return ACE_OS::write (this->get_handle (), (const char *) buf, n); +} + +ACE_INLINE ssize_t +ACE_DEV_IO::recv (void *buf, size_t n) const +{ + ACE_TRACE ("ACE_DEV_IO::recv"); + return ACE_OS::read (this->get_handle (), (char *) buf, n); +} + +ACE_INLINE ssize_t +ACE_DEV_IO::send (const iovec iov[], size_t n) const +{ + ACE_TRACE ("ACE_DEV_IO::send"); + return ACE_OS::writev (this->get_handle (), iov, static_cast (n)); +} + +ACE_INLINE ssize_t +ACE_DEV_IO::recv (iovec iov[], size_t n) const +{ + ACE_TRACE ("ACE_DEV_IO::recv"); + return ACE_OS::readv (this->get_handle (), iov, static_cast (n)); +} + +ACE_INLINE ssize_t +ACE_DEV_IO::send (const void *buf, size_t n, + ACE_OVERLAPPED *overlapped) const +{ + ACE_TRACE ("ACE_DEV_IO::send"); + return ACE_OS::write (this->get_handle (), + (const char *) buf, n, + overlapped); +} + +ACE_INLINE ssize_t +ACE_DEV_IO::recv (void *buf, size_t n, + ACE_OVERLAPPED *overlapped) const +{ + ACE_TRACE ("ACE_DEV_IO::recv"); + return ACE_OS::read (this->get_handle (), (char *) buf, n, + overlapped); +} + +#if defined (ACE_HAS_STREAM_PIPES) +ACE_INLINE ssize_t +ACE_DEV_IO::recv (ACE_Str_Buf *cntl, ACE_Str_Buf *data, int *band, int *flags) const +{ + ACE_TRACE ("ACE_DEV_IO::recv"); + return ACE_OS::getpmsg (this->get_handle (), (strbuf *) cntl, (strbuf *) data, band, flags); +} + +ACE_INLINE ssize_t +ACE_DEV_IO::send (const ACE_Str_Buf *cntl, const ACE_Str_Buf *data, int band, int flags) const +{ + ACE_TRACE ("ACE_DEV_IO::send"); + return ACE_OS::putpmsg (this->get_handle (), (strbuf *) cntl, (strbuf *) data, band, flags); +} + +ACE_INLINE ssize_t +ACE_DEV_IO::recv (ACE_Str_Buf *cntl, ACE_Str_Buf *data, int *flags) const +{ + ACE_TRACE ("ACE_DEV_IO::recv"); + return ACE_OS::getmsg (this->get_handle (), (strbuf *) cntl, (strbuf *) data, flags); +} + +ACE_INLINE ssize_t +ACE_DEV_IO::send (const ACE_Str_Buf *cntl, const ACE_Str_Buf *data, int flags) const +{ + ACE_TRACE ("ACE_DEV_IO::send"); + return ACE_OS::putmsg (this->get_handle (), (strbuf *) cntl, (strbuf *) data, flags); +} +#endif /* ACE_HAS_STREAM_PIPES */ + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/DLL.cpp b/dep/acelite/ace/DLL.cpp new file mode 100644 index 00000000000..cad25110032 --- /dev/null +++ b/dep/acelite/ace/DLL.cpp @@ -0,0 +1,267 @@ +// $Id: DLL.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/DLL.h" + +#include "ace/Log_Msg.h" +#include "ace/ACE.h" +#include "ace/DLL_Manager.h" +#include "ace/OS_NS_string.h" +#include "ace/OS_NS_dlfcn.h" +#include "ace/OS_NS_Thread.h" + +#include + +ACE_RCSID(ace, DLL, "$Id: DLL.cpp 80826 2008-03-04 14:51:23Z wotte $") + + ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Default constructor. Also, by default, the object will be closed +// before it is destroyed. + +ACE_DLL::ACE_DLL (bool close_handle_on_destruction) + : open_mode_ (0), + dll_name_ (0), + close_handle_on_destruction_ (close_handle_on_destruction), + dll_handle_ (0), + error_ (0) +{ + ACE_TRACE ("ACE_DLL::ACE_DLL (int)"); +} + +ACE_DLL::ACE_DLL (const ACE_DLL &rhs) + : open_mode_ (0), + dll_name_ (0), + close_handle_on_destruction_ (false), + dll_handle_ (0), + error_ (0) +{ + ACE_TRACE ("ACE_DLL::ACE_DLL (const ACE_DLL &)"); + + if (rhs.dll_name_ + // This will automatically up the refcount. + && this->open (rhs.dll_name_, + rhs.open_mode_, + rhs.close_handle_on_destruction_) != 0 + && ACE::debug ()) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("ACE_DLL::copy_ctor: error: %s\n"), + this->error ())); +} + +// Assignment operator + +ACE_DLL & +ACE_DLL::operator= (const ACE_DLL &rhs) +{ + ACE_TRACE ("ACE_DLL::operator= (const ACE_DLL &)"); + + ACE_DLL tmp (rhs); + + std::swap (this->open_mode_, tmp.open_mode_); + std::swap (this->dll_name_, tmp.dll_name_); + std::swap (this->close_handle_on_destruction_, + tmp.close_handle_on_destruction_); + std::swap (this->dll_handle_, tmp.dll_handle_); + std::swap (this->error_, tmp.error_); + + return *this; +} + + +// If the library name and the opening mode are specified than on +// object creation the library is implicitly opened. + +ACE_DLL::ACE_DLL (const ACE_TCHAR *dll_name, + int open_mode, + bool close_handle_on_destruction) + : open_mode_ (open_mode), + dll_name_ (0), + close_handle_on_destruction_ (close_handle_on_destruction), + dll_handle_ (0), + error_ (0) +{ + ACE_TRACE ("ACE_DLL::ACE_DLL"); + + if (this->open (dll_name, this->open_mode_, close_handle_on_destruction) != 0 + && ACE::debug ()) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("ACE_DLL::open: error calling open: %s\n"), + this->error ())); +} + +// The library is closed before the class gets destroyed depending on +// the close_handle_on_destruction value specified which is stored in +// close_handle_on_destruction_. + +ACE_DLL::~ACE_DLL (void) +{ + ACE_TRACE ("ACE_DLL::~ACE_DLL"); + + this->close (); + + // Normally delete()d in ACE_DLL::close(). However, that may not + // occur if full ACE_DLL initialization is interrupted due to errors + // (e.g. attempting to open a DSO/DLL that does not exist). Make + // sure this->dll_name_ is deallocated. + delete [] this->dll_name_; +} + +// This method opens the library based on the mode specified using the +// ACE_SHLIB_HANDLE which is obtained on making the ACE_OS::dlopen call. +// The default mode is: +// RTLD_LAZY Only references to data symbols are relocate when the +// object is first loaded. +// The other modes include: +// RTLD_NOW All necessary relocations are performed when the +// object is first loaded. +// RTLD_GLOBAL The object symbols are made available for the +// relocation processing of any other object. + +int +ACE_DLL::open (const ACE_TCHAR *dll_filename, + int open_mode, + bool close_handle_on_destruction) +{ + ACE_TRACE ("ACE_DLL::open"); + + return open_i (dll_filename, open_mode, close_handle_on_destruction); +} + +int +ACE_DLL::open_i (const ACE_TCHAR *dll_filename, + int open_mode, + bool close_handle_on_destruction, + ACE_SHLIB_HANDLE handle) +{ + ACE_TRACE ("ACE_DLL::open_i"); + + this->error_ = 0; + + if (!dll_filename) + { + if (ACE::debug ()) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("ACE_DLL::open_i: dll_name is %s\n"), + this->dll_name_ == 0 ? ACE_TEXT ("(null)") + : this->dll_name_)); + return -1; + } + + if (this->dll_handle_) + { + // If we have a good handle and its the same name, just return. + if (ACE_OS::strcmp (this->dll_name_, dll_filename) == 0) + return 0; + else + this->close (); + } + + if (!this->dll_name_) + this->dll_name_ = ACE::strnew (dll_filename); + + this->open_mode_ = open_mode; + this->close_handle_on_destruction_ = close_handle_on_destruction; + + this->dll_handle_ = ACE_DLL_Manager::instance()->open_dll (this->dll_name_, + this->open_mode_, + handle); + + if (!this->dll_handle_) + this->error_ = 1; + + return this->error_ ? -1 : 0; +} + +// The symbol refernce of the name specified is obtained. + +void * +ACE_DLL::symbol (const ACE_TCHAR *sym_name, int ignore_errors) +{ + ACE_TRACE ("ACE_DLL::symbol"); + + this->error_ = 0; + + void *sym = 0; + if (this->dll_handle_) + sym = this->dll_handle_->symbol (sym_name, ignore_errors); + + if (!sym) + this->error_ = 1; + + return sym; +} + +// The library is closed using the ACE_SHLIB_HANDLE object, i.e., the +// shared object is now disassociated form the current process. + +int +ACE_DLL::close (void) +{ + ACE_TRACE ("ACE_DLL::close"); + + int retval = 0; + + if (this->dll_handle_ + && this->close_handle_on_destruction_ + && this->dll_name_ + && (retval = ACE_DLL_Manager::instance ()->close_dll (this->dll_name_)) != 0) + this->error_ = 1; + + // Even if close_dll() failed, go ahead and cleanup. + this->dll_handle_ = 0; + delete [] this->dll_name_; + this->dll_name_ = 0; + this->close_handle_on_destruction_ = false; + + return retval; +} + +// This method is used return the last error of a library operation. + +ACE_TCHAR * +ACE_DLL::error (void) const +{ + ACE_TRACE ("ACE_DLL::error"); + if (this->error_) + { + return ACE_OS::dlerror (); + } + + return 0; +} + +// Return the handle to the user either temporarily or forever, thus +// orphaning it. If 0 means the user wants the handle forever and if 1 +// means the user temporarily wants to take the handle. + +ACE_SHLIB_HANDLE +ACE_DLL::get_handle (int become_owner) const +{ + ACE_TRACE ("ACE_DLL::get_handle"); + + ACE_SHLIB_HANDLE handle = ACE_SHLIB_INVALID_HANDLE; + + if (this->dll_handle_) + handle = this->dll_handle_->get_handle (become_owner); + + return handle; +} + +// Set the handle for the DLL. By default, the object will be closed +// before it is destroyed. + +int +ACE_DLL::set_handle (ACE_SHLIB_HANDLE handle, + bool close_handle_on_destruction) +{ + ACE_TRACE ("ACE_DLL::set_handle"); + + // Create a unique name. Note that this name is only quaranteed + // to be unique for the life of this object. + ACE_TCHAR temp[ACE_UNIQUE_NAME_LEN]; + ACE_OS::unique_name (this, temp, ACE_UNIQUE_NAME_LEN); + + return this->open_i (temp, 1, close_handle_on_destruction, handle); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/DLL.h b/dep/acelite/ace/DLL.h new file mode 100644 index 00000000000..20d333db81a --- /dev/null +++ b/dep/acelite/ace/DLL.h @@ -0,0 +1,196 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file DLL.h + * + * $Id: DLL.h 91064 2010-07-12 10:11:24Z johnnyw $ + * + * @author Kirthika Parameswaran + */ +//============================================================================= + +#ifndef ACE_DLL_H +#define ACE_DLL_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Global_Macros.h" +#include "ace/os_include/os_dlfcn.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +class ACE_DLL_Handle; + +/** + * @class ACE_DLL + * + * @brief Provides an abstract interface for handling various DLL + * operations. + * + * This class is a wrapper over the various methods for utilizing + * a dynamically linked library (DLL), which is called a shared + * library on some platforms. Operations @c open(), @c close(), and + * @c symbol() have been implemented to help opening/closing and + * extracting symbol information from a DLL, respectively. + */ +class ACE_Export ACE_DLL +{ +public: + // = Initialization and termination methods. + + /** + * Default constructor. By default, the close() operation on the + * object will be invoked before it is destroyed. + * @param close_handle_on_destruction Indicates whether or not the + * close() method will be called to close an open DLL when this + * object is destroyed. By default, close() will be called. + * Set this parameter to 0 for situations where the DLL's lifetime + * is controlled in a scope other than that of this ACE_DLL object. + * For example, termination by ACE_DLL_Manager via ACE::fini(). + */ + explicit ACE_DLL (bool close_handle_on_destruction = true); + + /// Allow assignment + ACE_DLL& operator= (const ACE_DLL &rhs); + + + /** + * This constructor performs the actions of open() during construction. + * @param dll_name The name or path of the DLL to load. + * @param open_mode Flags to alter the actions taken when loading the DLL. + * The possible values are: + * @li @c RTLD_LAZY (this the default): loads identifier symbols but + * not the symbols for functions, which are loaded dynamically + * on-demand. + * @li @c RTLD_NOW: performs all necessary relocations when + * @a dll_name is first loaded + * @li RTLD_GLOBAL: makes symbols available for relocation + * processing of any other DLLs. + * @param close_handle_on_destruction Indicates whether or not the + * close() method will be called to close an open DLL when this + * object is destroyed. By default, close() will be called. + * Set this parameter to 0 for situations where the DLL's lifetime + * is controlled in a scope other than that of this ACE_DLL object. + * For example, termination by ACE_DLL_Manager via ACE::fini(). + */ + explicit ACE_DLL (const ACE_TCHAR *dll_name, + int open_mode = ACE_DEFAULT_SHLIB_MODE, + bool close_handle_on_destruction = true); + + /// Copy constructor. + ACE_DLL (const ACE_DLL &); + + /** + * This method opens and dynamically links a specified DLL. + * @param dll_name The filename or path of the DLL to load. + * If a filename is given to @c open(), the @c ACE::ldfind() is used + * to locate DLLs via the following algorithms: (1) DLL filename + * expansion: @c ACE::ldfind() determines the name of the DLL by + * adding the appropriate prefix and suffix, e.g., it adds the @c lib + * prefix and @c .so suffix for Solaris and the @c .dll suffix for + * Windows and (2) DLL search path: @c ACE::ldfind() will also search + * for the designated DLL using the platform's DLL search path + * environment variable, e.g., it searches for DLLs using @c + * LD_LIBRARY_PATH on many UNIX systems and @c PATH on Windows. + * @param open_mode Flags to alter the actions taken when loading the DLL. + * The possible values are: + * @li @c RTLD_LAZY (this the default): loads identifier symbols but + * not the symbols for functions, which are loaded dynamically + * on-demand. + * @li @c RTLD_NOW: performs all necessary relocations when + * @a dll_name is first loaded + * @li RTLD_GLOBAL: makes symbols available for relocation + * processing of any other DLLs. + * @param close_handle_on_destruction Indicates whether or not the + * close() method will be called to close an open DLL when this + * object is destroyed. By default, close() will be called. + * Set this parameter to 0 for situations where the DLL's lifetime + * is controlled in a scope other than that of this ACE_DLL object. + * For example, termination by ACE_DLL_Manager via ACE::fini(). + * @retval -1 On failure + * @retval 0 On success. + */ + int open (const ACE_TCHAR *dll_name, + int open_mode = ACE_DEFAULT_SHLIB_MODE, + bool close_handle_on_destruction = true); + + /// Call to close the DLL object. + int close (void); + + /** + * Called when the DLL object is destroyed -- invokes close() if the + * @a close_handle_on_destruction flag was set to non-zero in the + * constructor or open() method. + */ + ~ACE_DLL (void); + + /** + * Look up a named symbol in the DLL. DLL must be successfully opened + * before calling symbol(). + * @param symbol_name The symbol name to look up. + * @param ignore_errors If set to 1, allows you to probe a dll without + * generating error messages in the log. Handy for determining + * the capabilities of a library. + * @return Returns the value of @a symbol_name if it is a valid symbol + * in the DLL. Otherwise, returns 0. + */ + void *symbol (const ACE_TCHAR *symbol_name, int ignore_errors = 0); + + /// Returns a pointer to a string explaining that an error occured. You + /// will need to consult the error log for the actual error string + /// returned by the OS. + ACE_TCHAR *error (void) const; + + /** + * Return the handle to the caller. If @a become_owner is non-0 then + * caller assumes ownership of the handle and the ACE_DLL object + * won't call close() when it goes out of scope, even if + * @c close_handle_on_destruction is set. + */ + ACE_SHLIB_HANDLE get_handle (int become_owner = 0) const; + + /// Set the handle for the DLL object. By default, the close() + /// operation on / the object will be invoked before it is destroyed. + int set_handle (ACE_SHLIB_HANDLE handle, + bool close_handle_on_destruction = true); + +private: + + int open_i (const ACE_TCHAR *dll_name, + int open_mode = ACE_DEFAULT_SHLIB_MODE, + bool close_handle_on_destruction = true, + ACE_SHLIB_HANDLE handle = 0); + + + //private: +public: + + /// Open mode. + int open_mode_; + + /// Keep track of the name of the loaded dll, so it can be used + /// to remove framework components, singletons that live in the dll, + /// prior to unloading the dll in the close() method. + ACE_TCHAR *dll_name_; + + /// This flag keeps track of whether we should close the handle + /// automatically when the object is destroyed. + bool close_handle_on_destruction_; + + ACE_DLL_Handle *dll_handle_; + + /// Flag to record if the last operation had an error. + bool error_; + +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" +#endif /* ACE_DLL_H */ diff --git a/dep/acelite/ace/DLL_Manager.cpp b/dep/acelite/ace/DLL_Manager.cpp new file mode 100644 index 00000000000..be73f455800 --- /dev/null +++ b/dep/acelite/ace/DLL_Manager.cpp @@ -0,0 +1,787 @@ +// $Id: DLL_Manager.cpp 90712 2010-06-18 20:01:29Z shuston $ + +#include "ace/DLL_Manager.h" + +#include "ace/Log_Msg.h" +#include "ace/ACE.h" +#include "ace/Framework_Component.h" + +#include "ace/Lib_Find.h" +#include "ace/Object_Manager.h" +#include "ace/SString.h" +#include "ace/Recursive_Thread_Mutex.h" +#include "ace/Guard_T.h" +#include "ace/OS_NS_dlfcn.h" +#include "ace/OS_NS_string.h" + +ACE_RCSID (ace, + DLL_Manager, + "DLL_Manager.cpp,v 4.23 2003/11/05 23:30:46 shuston Exp") + +/******************************************************************/ + + ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +sig_atomic_t ACE_DLL_Handle::open_called_ = 0; + +ACE_DLL_Handle::ACE_DLL_Handle (void) + : refcount_ (0), + dll_name_ (0), + handle_ (ACE_SHLIB_INVALID_HANDLE) +{ + ACE_TRACE ("ACE_DLL_Handle::ACE_DLL_Handle"); +} + +ACE_DLL_Handle::~ACE_DLL_Handle (void) +{ + ACE_TRACE ("ACE_DLL_Handle::~ACE_DLL_Handle"); + this->close (1); + delete[] this->dll_name_; +} + +const ACE_TCHAR * +ACE_DLL_Handle::dll_name (void) const +{ + ACE_TRACE ("ACE_DLL_Handle::dll_name"); + return this->dll_name_; +} + +int +ACE_DLL_Handle::open (const ACE_TCHAR *dll_name, + int open_mode, + ACE_SHLIB_HANDLE handle) +{ + ACE_TRACE ("ACE_DLL_Handle::open"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0)); + + if (this->dll_name_) + { + // Once dll_name_ has been set, it can't be changed.. + if (ACE_OS::strcmp (this->dll_name_, dll_name) != 0) + { + if (ACE::debug ()) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("ACE (%P|%t) DLL_Handle::open: error, ") + ACE_TEXT ("tried to reopen %s with name %s\n"), + this->dll_name_, + dll_name)); + + return -1; + } + } + else + this->dll_name_ = ACE::strnew (dll_name); + + if (!this->open_called_) + this->open_called_ = 1; + + // If it hasn't been loaded yet, go ahead and do that now. + if (this->handle_ == ACE_SHLIB_INVALID_HANDLE) + { + if (handle) + this->handle_ = handle; + else + { + /* + ** Get the set of names to try loading. We need to do this to + ** properly support the ability for a user to specify a simple, + ** unadorned name (for example, "ACE") that will work across + ** platforms. We apply platform specifics to get a name that will + ** work (e.g. libACE, ACEd.dll, ACE.dll, etc.) We rely on the + ** underlying dlopen() implementation to "Do The Right Thing" in + ** terms of using relative paths, LD_LIBRARY_PATH, system security + ** rules, etc. except when ACE_MUST_HELP_DLOPEN_SEARCH_PATH is set. + ** If it is set, then ACE::ldfind() scans the configured path + ** looking for a match on the name and prefix/suffix applications. + ** NOTE: having ACE scan for a file and then pass a fully-qualified + ** pathname to dlopen() is a potential security hole; therefore, + ** do not use ACE_MUST_HELP_DLOPEN_SEARCH_PATH unless necessary + ** and only after considering the risks. + */ + ACE_Array dll_names; + dll_names.max_size (10); // Decent guess to avoid realloc later + +#if defined (ACE_MUST_HELP_DLOPEN_SEARCH_PATH) + // Find out where the library is + ACE_TCHAR dll_pathname[MAXPATHLEN + 1]; + + // Transform the pathname into the appropriate dynamic link library + // by searching the ACE_LD_SEARCH_PATH. + ACE::ldfind (dll_name, + dll_pathname, + (sizeof dll_pathname / sizeof (ACE_TCHAR))); + ACE_TString dll_str (dll_pathname); + dll_names.size (1); + dll_names.set (dll_str, 0); +#else + this->get_dll_names (dll_name, dll_names); +#endif + + ACE_Array_Iterator name_iter (dll_names); + ACE_TString *name = 0; + while (name_iter.next (name)) + { + // The ACE_SHLIB_HANDLE object is obtained. + this->handle_ = ACE_OS::dlopen (name->c_str (), + open_mode); + + if (ACE::debug ()) + { + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) DLL_Handle::open ") + ACE_TEXT ("(\"%s\", 0x%x) -> %s: %s\n"), + name->c_str (), + open_mode, + ((this->handle_ != ACE_SHLIB_INVALID_HANDLE) + ? ACE_TEXT ("succeeded") + : ACE_TEXT ("failed")), + this->error()->c_str())); + } + + if (this->handle_ != ACE_SHLIB_INVALID_HANDLE) // Good one? + break; + + // If errno is ENOENT we just skip over this one, + // anything else - like an undefined symbol, for + // instance must be flagged here or the next error will + // mask it. + // @TODO: If we've found our DLL _and_ it's + // broken, should we continue at all? + if ((errno != 0) && (errno != ENOENT) && ACE::debug ()) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("ACE (%P|%t) DLL_Handle::open ") + ACE_TEXT ("(\'%s\') failed, errno=") + ACE_TEXT ("%d: <%s>\n"), + name->c_str (), + ACE_ERRNO_GET, + this->error ()->c_str ())); + +#if defined (AIX) + // AIX often puts the shared library file (most often named + // shr.o) inside an archive library. If this is an archive + // library name, then try appending [shr.o] and retry. + if (ACE_TString::npos != name->strstr (ACE_TEXT (".a"))) + { + ACE_TCHAR aix_pathname[MAXPATHLEN + 1]; + ACE_OS::strncpy (aix_pathname, + name->c_str (), + name->length ()); + aix_pathname[name->length ()] = '\0'; + ACE_OS::strcat (aix_pathname, ACE_TEXT ("(shr.o)")); + open_mode |= RTLD_MEMBER; + + if (ACE::debug ()) + { + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) DLL_Handle::open ") + ACE_TEXT ("(\"%s\", 0x%x) -> %s: %s\n"), + aix_pathname, + open_mode, + (this->handle_ != ACE_SHLIB_INVALID_HANDLE + ? ACE_TEXT ("succeeded") + : ACE_TEXT ("failed")), + this->error()->c_str())); + } + + this->handle_ = ACE_OS::dlopen (aix_pathname, open_mode); + if (this->handle_ != ACE_SHLIB_INVALID_HANDLE) + break; + + // If errno is ENOENT we just skip over this one, anything + // else - like an undefined symbol, for instance + // must be flagged here or the next error will mask it. + // + // @TODO: If we've found our DLL _and_ it's broken, + // should we continue at all? + if (ACE::debug () && (errno != 0) && (errno != ENOENT)) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("ACE (%P|%t) DLL_Handle::open ") + ACE_TEXT ("(\'%s\') failed, errno=") + ACE_TEXT ("%d: %s\n"), + name->c_str (), + errno, + this->error ()->c_str ())); + + } +#endif /* AIX */ + + name_iter.advance (); + } + + if (this->handle_ == ACE_SHLIB_INVALID_HANDLE) + { + if (ACE::debug ()) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("ACE (%P|%t) DLL_Handle::open (\"%s\"): ") + ACE_TEXT ("Invalid handle error: %s\n"), + this->dll_name_, + this->error ()->c_str ())); + + return -1; + } + } + } + + ++this->refcount_; + + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) DLL_Handle::open - %s (%d), refcount=%d\n"), + this->dll_name_, + this->handle_, + this->refcount_)); + return 0; +} + + +int +ACE_DLL_Handle::close (int unload) +{ + ACE_TRACE ("ACE_DLL_Handle::close"); + + int retval = 0; + ACE_SHLIB_HANDLE h = ACE_SHLIB_INVALID_HANDLE; + + // Only hold the lock until it comes time to dlclose() the DLL. Closing + // the DLL can cause further shutdowns as DLLs and their dependents are + // unloaded. + { + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0)); + + // Since we don't actually unload the dll as soon as the refcount + // reaches zero, we need to make sure we don't decrement it below + // zero. + if (this->refcount_ > 0) + --this->refcount_; + else + this->refcount_ = 0; + + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) DLL_Handle::close - ") + ACE_TEXT ("%s (handle=%d, refcount=%d)\n"), + this->dll_name_, + this->handle_, + this->refcount_)); + + if (this->refcount_ == 0 && + this->handle_ != ACE_SHLIB_INVALID_HANDLE && + unload == 1) + { + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) DLL_Handle::close: ") + ACE_TEXT ("Unloading %s (handle=%d)\n"), + this->dll_name_, + this->handle_)); + + // First remove any associated Framework Components. + ACE_Framework_Repository *frPtr= ACE_Framework_Repository::instance (); + if (frPtr) + { + frPtr->remove_dll_components (this->dll_name_); + } + + h = this->handle_; + this->handle_ = ACE_SHLIB_INVALID_HANDLE; + } + } // Release lock_ here + + if (h != ACE_SHLIB_INVALID_HANDLE) + { + retval = ACE_OS::dlclose (h); + + if (retval != 0 && ACE::debug ()) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("ACE (%P|%t) DLL_Handle::close - ") + ACE_TEXT ("Failed with: \"%s\".\n"), + this->error ()->c_str ())); + } + + return retval; +} + +sig_atomic_t +ACE_DLL_Handle::refcount (void) const +{ + return this->refcount_; +} + +void * +ACE_DLL_Handle::symbol (const ACE_TCHAR *sym_name, int ignore_errors) +{ + ACE_TRACE ("ACE_DLL_Handle::symbol"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0)); + + ACE_Auto_Array_Ptr auto_name (ACE::ldname (sym_name)); + // handle_ can be invalid especially when ACE_DLL_Handle resigned ownership + // BTW. Handle lifecycle management is a little crazy in ACE + if (this->handle_ != ACE_SHLIB_INVALID_HANDLE) + { +#if defined (ACE_OPENVMS) + void *sym = ACE::ldsymbol (this->handle_, auto_name.get ()); +#else + void *sym = ACE_OS::dlsym (this->handle_, auto_name.get ()); +#endif + + // Linux says that the symbol could be null and that it isn't an + // error. So you should check the error message also, but since + // null symbols won't do us much good anyway, let's still report + // an error. + if (!sym && ignore_errors != 1) + { + if (ACE::debug ()) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("ACE (%P|%t) DLL_Handle::symbol (\"%s\") ") + ACE_TEXT (" failed with \"%s\".\n"), + auto_name.get (), + this->error ()->c_str ())); + + return 0; + } + return sym; + } + return 0; +} + +ACE_SHLIB_HANDLE +ACE_DLL_Handle::get_handle (int become_owner) +{ + ACE_TRACE ("ACE_DLL_Handle::get_handle"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0)); + + if (this->refcount_ == 0 && become_owner != 0) + { + if (ACE::debug ()) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("ACE (%P|%t) DLL_Handle::get_handle: ") + ACE_TEXT ("cannot become owner, refcount == 0.\n"))); + + return ACE_SHLIB_INVALID_HANDLE; + } + + ACE_SHLIB_HANDLE handle = this->handle_; + + if (become_owner != 0) + { + if (--this->refcount_ == 0) + this->handle_ = ACE_SHLIB_INVALID_HANDLE; + } + + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) DLL_Handle::get_handle: ") + ACE_TEXT ("post call: handle %s, refcount %d\n"), + this->handle_ == ACE_SHLIB_INVALID_HANDLE ? + ACE_TEXT ("invalid") : ACE_TEXT ("valid"), + this->refcount_)); + + return handle; +} + +// This method is used return the last error of a library operation. + +auto_ptr +ACE_DLL_Handle::error (void) +{ + ACE_TRACE ("ACE_DLL_Handle::error"); + const ACE_TCHAR *error = ACE_OS::dlerror (); + auto_ptr str + (new ACE_TString (error ? error : ACE_TEXT ("no error"))); + return str; +} + +void +ACE_DLL_Handle::get_dll_names (const ACE_TCHAR *dll_name, + ACE_Array &try_names) +{ + // Build the array of DLL names to try on this platform by applying the + // proper prefixes and/or suffixes to the specified dll_name. + ACE_TString base (dll_name); + ACE_TString base_dir, base_file, base_suffix; + + // 1. Separate the dll_name into the dir part and the file part. We + // only decorate the file part to determine the names to try loading. + ACE_TString::size_type pos = base.rfind (ACE_DIRECTORY_SEPARATOR_CHAR); + if (pos != ACE_TString::npos) + { + base_dir = base.substr (0, pos + 1); + base_file = base.substr (pos + 1); + } + else + base_file = base; + + // 2. Locate the file suffix, if there is one. Move the '.' and the + // suffix to base_suffix. + if ((pos = base_file.rfind (ACE_TEXT ('.'))) != ACE_TString::npos) + { + base_suffix = base_file.substr (pos); + base_file = base_file.substr (0, pos); + } + + // 3. Build the combinations to try for this platform. + // Try these combinations: + // - name with decorator and platform's suffix appended (if not supplied) + // - name with platform's suffix appended (if not supplied) + // - name with platform's dll prefix (if it has one) and suffix + // - name with platform's dll prefix, decorator, and suffix. + // - name as originally given + // We first try to find the file using the decorator so that when a + // filename with and without decorator is used, we get the file with + // the same decorator as the ACE dll has and then as last resort + // the one without. For example with msvc, the debug build has a "d" + // decorator, but the release build has none and we really want to get + // the debug version of the library in a debug application instead + // of the release one. + // So we need room for 5 entries in try_names. + try_names.size (0); + if ((try_names.max_size () - try_names.size ()) < 5) + try_names.max_size (try_names.max_size () + 5); +#if defined (ACE_LD_DECORATOR_STR) && !defined (ACE_DISABLE_DEBUG_DLL_CHECK) + ACE_TString decorator (ACE_LD_DECORATOR_STR); +#endif + ACE_TString suffix (ACE_DLL_SUFFIX); + ACE_TString prefix (ACE_DLL_PREFIX); + + for (size_t i = 0; i < 5 && try_names.size () < try_names.max_size (); ++i) + { + ACE_TString try_this; + size_t const j = try_names.size (); + switch (i) + { + case 0: // Name + decorator + suffix + case 1: // Name + suffix + case 2: // Prefix + name + decorator + suffix + case 3: // Prefix + name + suffix + if ( + base_suffix.length () > 0 +#if !(defined (ACE_LD_DECORATOR_STR) && !defined (ACE_DISABLE_DEBUG_DLL_CHECK)) + || (i == 1 || i == 3) // No decorator desired; skip +#endif + ) + break; + try_this = base_dir; + if (i > 1) + try_this += prefix; + try_this += base_file; + if (base_suffix.length () > 0) + try_this += base_suffix; + else + { +#if defined (ACE_LD_DECORATOR_STR) && !defined (ACE_DISABLE_DEBUG_DLL_CHECK) + try_this += decorator; +#endif + try_this += suffix; + } + break; + case 4: + try_this = dll_name; + break; + } + + if (try_this.length ()) + { + try_names.size (j + 1); + try_names.set (try_this, j); + } + } + return; +} + +/******************************************************************/ + +// Pointer to the Singleton instance. +ACE_DLL_Manager *ACE_DLL_Manager::instance_ = 0; + + +ACE_DLL_Manager * +ACE_DLL_Manager::instance (int size) +{ + ACE_TRACE ("ACE_DLL_Manager::instance"); + + if (ACE_DLL_Manager::instance_ == 0) + { + // Perform Double-Checked Locking Optimization. + ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, + *ACE_Static_Object_Lock::instance (), 0)); + if (ACE_DLL_Manager::instance_ == 0) + { + ACE_NEW_RETURN (ACE_DLL_Manager::instance_, + ACE_DLL_Manager (size), + 0); + } + } + + return ACE_DLL_Manager::instance_; +} + +void +ACE_DLL_Manager::close_singleton (void) +{ + ACE_TRACE ("ACE_DLL_Manager::close_singleton"); + + ACE_MT (ACE_GUARD (ACE_Recursive_Thread_Mutex, ace_mon, + *ACE_Static_Object_Lock::instance ())); + + delete ACE_DLL_Manager::instance_; + ACE_DLL_Manager::instance_ = 0; +} + +ACE_DLL_Manager::ACE_DLL_Manager (int size) + : handle_vector_ (0), + current_size_ (0), + total_size_ (0), + unload_policy_ (ACE_DLL_UNLOAD_POLICY_PER_DLL) +{ + ACE_TRACE ("ACE_DLL_Manager::ACE_DLL_Manager"); + + if (this->open (size) != 0 && ACE::debug ()) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("ACE (%P|%t) DLL_Manager ctor failed to allocate ") + ACE_TEXT ("handle_vector_.\n"))); +} + +ACE_DLL_Manager::~ACE_DLL_Manager (void) +{ + ACE_TRACE ("ACE_DLL_Manager::~ACE_DLL_Manager"); + + if (this->close () != 0 && ACE::debug ()) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("ACE (%P|%t) DLL_Manager dtor failed to close ") + ACE_TEXT ("properly.\n"))); +} + +ACE_DLL_Handle * +ACE_DLL_Manager::open_dll (const ACE_TCHAR *dll_name, + int open_mode, + ACE_SHLIB_HANDLE handle) +{ + ACE_TRACE ("ACE_DLL_Manager::open_dll"); + + ACE_DLL_Handle *temp_handle = 0; + ACE_DLL_Handle *dll_handle = 0; + { + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0)); + dll_handle = this->find_dll (dll_name); + if (!dll_handle) + { + if (this->current_size_ < this->total_size_) + { + ACE_NEW_RETURN (temp_handle, + ACE_DLL_Handle, + 0); + + dll_handle = temp_handle; + } + } + } + + if (dll_handle) + { + if (dll_handle->open (dll_name, open_mode, handle) != 0) + { + // Error while opening dll. Free temp handle + if (ACE::debug ()) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("ACE (%P|%t) DLL_Manager::open_dll: Could not ") + ACE_TEXT ("open dll %s.\n"), + dll_name)); + + delete temp_handle; + return 0; + } + + // Add the handle to the vector only if the dll is successfully + // opened. + if (temp_handle != 0) + { + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0)); + this->handle_vector_[this->current_size_] = dll_handle; + ++this->current_size_; + } + } + + return dll_handle; +} + +int +ACE_DLL_Manager::close_dll (const ACE_TCHAR *dll_name) +{ + ACE_TRACE ("ACE_DLL_Manager::close_dll"); + ACE_DLL_Handle *handle = 0; + + { + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0)); + handle = this->find_dll (dll_name); + } + + if (handle) + { + return this->unload_dll (handle, 0); + } + + return -1; +} + +u_long +ACE_DLL_Manager::unload_policy (void) const +{ + ACE_TRACE ("ACE_DLL_Manager::unload_policy"); + return this->unload_policy_; +} + +void +ACE_DLL_Manager::unload_policy (u_long unload_policy) +{ + ACE_TRACE ("ACE_DLL_Manager::unload_policy"); + ACE_MT (ACE_GUARD (ACE_Thread_Mutex, ace_mon, this->lock_)); + + u_long old_policy = this->unload_policy_; + this->unload_policy_ = unload_policy; + + // If going from LAZY to EAGER or from PER_DLL to PER_PROCESS|EAGER, + // call close(1) on all the ACE_DLL_Handle objects with refcount == 0 + // which will force those that are still loaded to be unloaded. + if (this->handle_vector_) + if (( ACE_BIT_ENABLED (old_policy, ACE_DLL_UNLOAD_POLICY_LAZY) && + ACE_BIT_DISABLED (this->unload_policy_, ACE_DLL_UNLOAD_POLICY_LAZY) ) || + ( ACE_BIT_DISABLED (this->unload_policy_, ACE_DLL_UNLOAD_POLICY_LAZY) && + ACE_BIT_ENABLED (old_policy, ACE_DLL_UNLOAD_POLICY_PER_DLL) && + ACE_BIT_DISABLED (this->unload_policy_, ACE_DLL_UNLOAD_POLICY_PER_DLL) )) + { + for (int i = this->current_size_ - 1; i >= 0; i--) + { + if (this->handle_vector_[i] && + this->handle_vector_[i]->refcount () == 0) + this->handle_vector_[i]->close (1); + } + } +} + +int +ACE_DLL_Manager::open (int size) +{ + ACE_TRACE ("ACE_DLL_Manager::open"); + + ACE_DLL_Handle **temp = 0; + + ACE_NEW_RETURN (temp, + ACE_DLL_Handle *[size], + -1); + + this->handle_vector_ = temp; + this->total_size_ = size; + return 0; +} + +int +ACE_DLL_Manager::close (void) +{ + ACE_TRACE ("ACE_DLL_Manager::close"); + + int force_close = 1; + + if (this->handle_vector_ != 0) + { + // Delete components in reverse order. + for (int i = this->current_size_ - 1; i >= 0; i--) + { + if (this->handle_vector_[i]) + { + ACE_DLL_Handle *s = + const_cast (this->handle_vector_[i]); + this->handle_vector_[i] = 0; + this->unload_dll (s, force_close); + delete s; + } + } + + delete [] this->handle_vector_; + this->handle_vector_ = 0; + this->current_size_ = 0; + } + return 0; +} + +ACE_DLL_Handle * +ACE_DLL_Manager::find_dll (const ACE_TCHAR *dll_name) const +{ + ACE_TRACE ("ACE_DLL_Manager::find_dll"); + + for (int i = 0; i < this->current_size_; i++) + if (this->handle_vector_[i] && + ACE_OS::strcmp (this->handle_vector_[i]->dll_name (), dll_name) == 0) + { + return this->handle_vector_[i]; + } + + return 0; +} + +int +ACE_DLL_Manager::unload_dll (ACE_DLL_Handle *dll_handle, int force_unload) +{ + ACE_TRACE ("ACE_DLL_Manager::unload_dll"); + + if (dll_handle) + { + int unload = force_unload; + if (unload == 0) + { + // apply strategy + if (ACE_BIT_DISABLED (this->unload_policy_, + ACE_DLL_UNLOAD_POLICY_PER_DLL)) + { + unload = ACE_BIT_DISABLED (this->unload_policy_, + ACE_DLL_UNLOAD_POLICY_LAZY); + } + else + { + // Declare the type of the symbol: + typedef int (*dll_unload_policy)(void); + + void * const unload_policy_ptr = + dll_handle->symbol (ACE_TEXT ("_get_dll_unload_policy"), 1); +#if defined (ACE_OPENVMS) && (!defined (__INITIAL_POINTER_SIZE) || (__INITIAL_POINTER_SIZE < 64)) + int const temp_p = + reinterpret_cast (unload_policy_ptr); +#else + intptr_t const temp_p = + reinterpret_cast (unload_policy_ptr); +#endif + + dll_unload_policy const the_policy = + reinterpret_cast (temp_p); + + if (the_policy != 0) + unload = ACE_BIT_DISABLED (the_policy (), + ACE_DLL_UNLOAD_POLICY_LAZY); + else + unload = ACE_BIT_DISABLED (this->unload_policy_, + ACE_DLL_UNLOAD_POLICY_LAZY); + } + } + + if (dll_handle->close (unload) != 0) + { + if (ACE::debug ()) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("ACE (%P|%t) DLL_Manager::unload error.\n"))); + + return -1; + } + } + else + { + if (ACE::debug ()) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("ACE (%P|%t) DLL_Manager::unload_dll called with ") + ACE_TEXT ("null pointer.\n"))); + + return -1; + } + + return 0; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/DLL_Manager.h b/dep/acelite/ace/DLL_Manager.h new file mode 100644 index 00000000000..716e3299557 --- /dev/null +++ b/dep/acelite/ace/DLL_Manager.h @@ -0,0 +1,269 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file DLL_Manager.h + * + * $Id: DLL_Manager.h 91064 2010-07-12 10:11:24Z johnnyw $ + * + * @author Don Hinton + */ +//============================================================================= + +#ifndef ACE_DLL_MANAGER_H +#define ACE_DLL_MANAGER_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Auto_Ptr.h" +#include "ace/Containers_T.h" +#include "ace/SStringfwd.h" +#include "ace/os_include/os_dlfcn.h" + +#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) +# include "ace/Thread_Mutex.h" +#endif /* ACE_MT_SAFE */ + +#define ACE_DEFAULT_DLL_MANAGER_SIZE 1024 + + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_DLL_Handle + * + * @brief Provides an abstract interface for handling various DLL + * operations. + * + * This class is an wrapper over the various methods for utilizing a + * dynamically linked library (DLL), which is called a shared library + * on some platforms. It is refcounted and managed by + * ACE_DLL_Manager, so there will only be a single instance of this + * class for each dll loaded, no matter how many instances of ACE_DLL + * an application has open. Operations open(), close(), and symbol() + * have been implemented to help opening/closing and extracting symbol + * information from a DLL, respectively. + * + * Most of this class came from the original ACE_DLL class. ACE_DLL + * is now just an interface that passed all it's calls either directly + * or via ACE_DLL_Manager to this class for execution. + * + */ +class ACE_Export ACE_DLL_Handle +{ +public: + + /// Default construtor. + ACE_DLL_Handle (void); + + /// Destructor. + ~ACE_DLL_Handle (void); + + /// Returns the name of the shared library (without prefixes or suffixes). + const ACE_TCHAR *dll_name () const; + + /** + * This method opens and dynamically links @a dll_name. The default + * mode is @c RTLD_LAZY, which loads identifier symbols but not the + * symbols for functions, which are loaded dynamically on-demand. + * Other supported modes include: @c RTLD_NOW, which performs all + * necessary relocations when @a dll_name is first loaded and + * @c RTLD_GLOBAL, which makes symbols available for relocation + * processing of any other DLLs. Returns -1 on failure and 0 on + * success. + */ + int open (const ACE_TCHAR *dll_name, + int open_mode, + ACE_SHLIB_HANDLE handle); + + /// Call to close the DLL object. If unload = 0, it only decrements + /// the refcount, but if unload = 1, then it will actually unload + /// the library when the refcount == 0; + int close (int unload = 0); + + /// Return the current refcount. + sig_atomic_t refcount (void) const; + + /// If @a symbol_name is in the symbol table of the DLL a pointer to + /// the @a symbol_name is returned. Otherwise, returns 0. Set the + /// ignore_errors flag to supress logging errors if symbol_name isn't + /// found. This is nice if you just want to probe a dll to see what's + /// available, since missing functions in that case aren't really errors. + void *symbol (const ACE_TCHAR *symbol_name, int ignore_errors = 0); + + /** + * Return the handle to the caller. If @a become_owner is non-0 then + * caller assumes ownership of the handle so we decrement the retcount. + */ + ACE_SHLIB_HANDLE get_handle (int become_owner = 0); + +private: + + /// Returns a pointer to a string explaining why or + /// failed. This is used internal to print out the error to the log, + /// but since this object is shared, we can't store or return the error + /// to the caller. + auto_ptr error (void); + + /// Builds array of DLL names to try to dlopen, based on platform + /// and configured DLL prefixes/suffixes. + /// Returns the array of names to try in try_names. + void get_dll_names (const ACE_TCHAR *dll_name, + ACE_Array &try_names); + + /// Disallow copying and assignment since we don't handle them. + ACE_DLL_Handle (const ACE_DLL_Handle &); + void operator= (const ACE_DLL_Handle &); + +private: + + /// Keep track of how many ACE_DLL objects have a reference to this + /// dll. + sig_atomic_t refcount_; + + /// Name of the shared library. + ACE_TCHAR *dll_name_; + + /// Handle to the actual library loaded by the OS. + ACE_SHLIB_HANDLE handle_; + + /// Keeps track of whether or not open() has ever been called. This + /// helps get around problem on Linux, and perhaps other OS's, that + /// seg-fault if dlerror() is called before the ld library has been + /// initialized by a call to dlopen(). + static sig_atomic_t open_called_; + +#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) + /// Synchronization variable for the MT_SAFE Repository + ACE_Thread_Mutex lock_; +#endif /* ACE_MT_SAFE */ +}; + +class ACE_Framework_Repository; + +/** + * @class ACE_DLL_Manager + * + * @brief This class is a singleton and serves as a factory and + * repository for instances of ACE_DLL_Handle. + * + * This class is a singleton whose lifetime is managed by the + * ACE_Framework_Repository. Although it is normally meant to be + * used directly only by ACE_DLL, applications can call the unload_policy() + * methods in order get/set the the dll unload policy. Unload policies include + * per_process/per-dll and eager/lazy. Dlls can export set their own policy + * by using the ACE_DLL_UNLOAD_POLICY macro found in config-all.h. If a dll + * choses to set an unload policy, it will be used when the per-dll policy + * (the default) is in effect. If the per-dll policy is in effect and a dll + * has not chosen to set a policy, the current per-process policy will be + * used. + * + * The following policy macros are provided in config-all.h: + * + * ACE_DLL_UNLOAD_POLICY_PER_PROCESS - Per-process policy that unloads dlls + * eagerly. + * + * ACE_DLL_UNLOAD_POLICY_PER_DLL - Apply policy on a per-dll basis. If the + * dll doesn't use one of the macros below, the current per-process policy + * will be used. + * + * ACE_DLL_UNLOAD_POLICY_LAZY - Don't unload dll when refcount reaches + * zero, i.e., wait for either an explicit unload request or program exit. + * + * ACE_DLL_UNLOAD_POLICY_DEFAULT - Default policy allows dlls to control + * their own destinies, but will unload those that don't make a choice eagerly. + * + */ +class ACE_Export ACE_DLL_Manager +{ +public: + friend class ACE_Framework_Repository; + friend class ACE_Object_Manager; + + enum + { + DEFAULT_SIZE = ACE_DEFAULT_DLL_MANAGER_SIZE + }; + + /// Return a unique instance + static ACE_DLL_Manager *instance (int size = ACE_DLL_Manager::DEFAULT_SIZE); + + /// Factory for ACE_DLL_Handle objects. If one already exits, + /// its refcount is incremented. + ACE_DLL_Handle *open_dll (const ACE_TCHAR *dll_name, + int openmode, + ACE_SHLIB_HANDLE handle); + + /// Close the underlying dll. Decrements the refcount. + int close_dll (const ACE_TCHAR *dll_name); + + /// Returns the current per-process UNLOAD_POLICY. + u_long unload_policy (void) const; + + /// Set the per-process UNLOAD_POLICY. If the policy is changed from + /// LAZY to EAGER, then it will also unload any dlls with zero + /// refcounts. + void unload_policy (u_long unload_policy); + +protected: + + /// Default constructor. + ACE_DLL_Manager (int size = ACE_DLL_Manager::DEFAULT_SIZE); + + /// Destructor. + ~ACE_DLL_Manager (void); + + /// Allocate handle_vector_. + int open (int size); + + /// Close all open dlls and deallocate memory. + int close (void); + + /// Find dll in handle_vector_. + ACE_DLL_Handle *find_dll (const ACE_TCHAR *dll_name) const; + + /// Applies strategy for unloading dll. + int unload_dll (ACE_DLL_Handle *dll_handle, int force_unload = 0); + +private: + + /// Close the singleton instance. + static void close_singleton (void); + + /// Disallow copying and assignment since we don't handle these. + ACE_DLL_Manager (const ACE_DLL_Manager &); + void operator= (const ACE_DLL_Manager &); + +private: + + /// Vector containing all loaded handle objects. + ACE_DLL_Handle **handle_vector_; + + /// Current number of handles. + int current_size_; + + /// Maximum number of handles. + int total_size_; + + /// Unload strategy. + u_long unload_policy_; + + /// Pointer to a process-wide ACE_DLL_Manager. + static ACE_DLL_Manager *instance_; + +#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) + /// Synchronization variable for the MT_SAFE Repository + ACE_Thread_Mutex lock_; +#endif /* ACE_MT_SAFE */ + +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" +#endif /* ACE_DLL_MANAGER_H */ diff --git a/dep/acelite/ace/Date_Time.cpp b/dep/acelite/ace/Date_Time.cpp new file mode 100644 index 00000000000..eff0f273fe7 --- /dev/null +++ b/dep/acelite/ace/Date_Time.cpp @@ -0,0 +1,10 @@ +// Date_Time.cpp +// $Id: Date_Time.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Date_Time.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Date_Time.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID(ace, Date_Time, "$Id: Date_Time.cpp 80826 2008-03-04 14:51:23Z wotte $") diff --git a/dep/acelite/ace/Date_Time.h b/dep/acelite/ace/Date_Time.h new file mode 100644 index 00000000000..a15d435eeb8 --- /dev/null +++ b/dep/acelite/ace/Date_Time.h @@ -0,0 +1,125 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file Date_Time.h + * + * $Id: Date_Time.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Tim Harrison (harrison@cs.wustl.edu) (and he's darn proud of this ;-)) + * + */ +//========================================================================== + +#ifndef ACE_DATE_TIME_H +#define ACE_DATE_TIME_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +class ACE_Time_Value; + +/** + * @class ACE_Date_Time + * + * @brief System independent representation of date and time. + */ +class ACE_Export ACE_Date_Time +{ +public: + /// Constructor initializes current time/date info. + ACE_Date_Time (void); + + /// Constructor initializes with the given ACE_Time_Value + explicit ACE_Date_Time (const ACE_Time_Value& timevalue); + + /// Constructor with init values, no check for validy + /// Set/get portions of ACE_Date_Time, no check for validity. + ACE_Date_Time (long day, + long month = 0, + long year = 0, + long hour = 0, + long minute = 0, + long second = 0, + long microsec = 0, + long wday = 0); + + /// Update to the current time/date. + void update (void); + + /// Update to the given ACE_Time_Value + void update (const ACE_Time_Value& timevalue); + + /// Get day. + long day (void) const; + + /// Set day. + void day (long day); + + /// Get month. + long month (void) const; + + /// Set month. + void month (long month); + + /// Get year. + long year (void) const; + + /// Set year. + void year (long year); + + /// Get hour. + long hour (void) const; + + /// Set hour. + void hour (long hour); + + /// Get minute. + long minute (void) const; + + /// Set minute. + void minute (long minute); + + /// Get second. + long second (void) const; + + /// Set second. + void second (long second); + + /// Get microsec. + long microsec (void) const; + + /// Set microsec. + void microsec (long microsec); + + /// Get weekday. + long weekday (void) const; + + /// Set weekday. + void weekday (long wday); + +private: + long day_; + long month_; + long year_; + long hour_; + long minute_; + long second_; + long microsec_; + long wday_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Date_Time.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_DATE_TIME_H */ diff --git a/dep/acelite/ace/Date_Time.inl b/dep/acelite/ace/Date_Time.inl new file mode 100644 index 00000000000..d34807d83a4 --- /dev/null +++ b/dep/acelite/ace/Date_Time.inl @@ -0,0 +1,219 @@ +// -*- C++ -*- +// +// $Id: Date_Time.inl 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Global_Macros.h" +#include "ace/Time_Value.h" +#include "ace/OS_NS_sys_time.h" +#include "ace/OS_NS_time.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE void +ACE_Date_Time::update (const ACE_Time_Value& timevalue) +{ +#if defined (ACE_HAS_WINCE) + // CE doesn't do localtime(). + FILETIME file_time = timevalue; + FILETIME local_file_time; + SYSTEMTIME sys_time; + ::FileTimeToLocalFileTime (&file_time, &local_file_time); + ::FileTimeToSystemTime (&local_file_time, &sys_time); + this->day_ = sys_time.wDay; + this->month_ = sys_time.wMonth; + this->year_ = sys_time.wYear; + this->hour_ = sys_time.wHour; + this->minute_ = sys_time.wMinute; + this->second_ = sys_time.wSecond; + this->microsec_ = sys_time.wMilliseconds * 1000; + this->wday_ = sys_time.wDayOfWeek; +#else + time_t time = timevalue.sec (); + struct tm tm_time; + ACE_OS::localtime_r (&time, &tm_time); + this->day_ = tm_time.tm_mday; + this->month_ = tm_time.tm_mon + 1; // localtime's months are 0-11 + this->year_ = tm_time.tm_year + 1900; // localtime reports years since 1900 + this->hour_ = tm_time.tm_hour; + this->minute_ = tm_time.tm_min; + this->second_ = tm_time.tm_sec; + this->microsec_ = timevalue.usec (); + this->wday_ = tm_time.tm_wday; +#endif /* ACE_HAS_WINCE */ +} + +ACE_INLINE void +ACE_Date_Time::update (void) +{ + ACE_TRACE ("ACE_Date_Time::update"); + + update(ACE_OS::gettimeofday ()); +} + +ACE_INLINE +ACE_Date_Time::ACE_Date_Time (void) +{ + ACE_TRACE ("ACE_Date_Time::ACE_Date_Time"); + this->update (); +} + +ACE_INLINE +ACE_Date_Time::ACE_Date_Time (const ACE_Time_Value& timevalue) +{ + ACE_TRACE ("ACE_Date_Time::ACE_Date_Time: timevalue"); + this->update (timevalue); +} + +// Constructor with init values, no check for validy +ACE_INLINE +ACE_Date_Time::ACE_Date_Time (long day, + long month, + long year, + long hour, + long minute, + long second, + long microsec, + long wday) + : day_ (day), + month_ (month), + year_ (year), + hour_ (hour), + minute_ (minute), + second_ (second), + microsec_ (microsec), + wday_ (wday) +{ + ACE_TRACE ("ACE_Date_Time::ACE_Date_Time"); +} + +// set/get portions of ACE_Date_Time, no check for validy + +// get day +ACE_INLINE long +ACE_Date_Time::day (void) const +{ + ACE_TRACE ("ACE_Date_Time::day"); + return day_; +} + +// set day +ACE_INLINE void +ACE_Date_Time::day (long day) +{ + ACE_TRACE ("ACE_Date_Time::day"); + day_ = day; +} + +// get month +ACE_INLINE long +ACE_Date_Time::month (void) const +{ + ACE_TRACE ("ACE_Date_Time::month"); + return month_; +} + +// set month +ACE_INLINE void +ACE_Date_Time::month (long month) +{ + ACE_TRACE ("ACE_Date_Time::month"); + month_ = month; +} + +// get year +ACE_INLINE long +ACE_Date_Time::year (void) const +{ + ACE_TRACE ("ACE_Date_Time::year"); + return year_; +} + +// set year +ACE_INLINE void +ACE_Date_Time::year (long year) +{ + ACE_TRACE ("ACE_Date_Time::year"); + year_ = year; +} + +// get hour +ACE_INLINE long +ACE_Date_Time::hour (void) const +{ + ACE_TRACE ("ACE_Date_Time::hour"); + return hour_; +} + +// set hour +ACE_INLINE void +ACE_Date_Time::hour (long hour) +{ + ACE_TRACE ("ACE_Date_Time::hour"); + hour_ = hour; +} + +// get minute +ACE_INLINE long +ACE_Date_Time::minute (void) const +{ + ACE_TRACE ("ACE_Date_Time::minute"); + return minute_; +} + +// set minute +ACE_INLINE void +ACE_Date_Time::minute (long minute) +{ + ACE_TRACE ("ACE_Date_Time::minute"); + minute_ = minute; +} + +// get second +ACE_INLINE long +ACE_Date_Time::second (void) const +{ + ACE_TRACE ("ACE_Date_Time::second"); + return second_; +} + +// set second +ACE_INLINE void +ACE_Date_Time::second (long second) +{ + ACE_TRACE ("ACE_Date_Time::second"); + second_ = second; +} + +// get microsec +ACE_INLINE long +ACE_Date_Time::microsec (void) const +{ + ACE_TRACE ("ACE_Date_Time::microsec"); + return microsec_; +} + +// set microsec +ACE_INLINE void +ACE_Date_Time::microsec (long microsec) +{ + ACE_TRACE ("ACE_Date_Time::microsec"); + microsec_ = microsec; +} + +// get wday +ACE_INLINE long +ACE_Date_Time::weekday (void) const +{ + ACE_TRACE ("ACE_Date_Time::weekday"); + return wday_; +} + +// set wday +ACE_INLINE void +ACE_Date_Time::weekday (long wday) +{ + ACE_TRACE ("ACE_Date_Time::weekday"); + wday_ = wday; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Default_Constants.h b/dep/acelite/ace/Default_Constants.h new file mode 100644 index 00000000000..1c0743b523c --- /dev/null +++ b/dep/acelite/ace/Default_Constants.h @@ -0,0 +1,605 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Default_Constants.h + * + * $Id: Default_Constants.h 87487 2009-11-12 07:54:39Z johnnyw $ + * + * @author Douglas C. Schmidt + * @author Jesper S. M|ller + * @author and a cast of thousands... + * + * This one is split from the famous OS.h + */ +//============================================================================= + +#ifndef ACE_DEFAULT_CONSTANTS_H +#define ACE_DEFAULT_CONSTANTS_H +#include /**/ "ace/pre.h" + +// Included just keep compilers that see #pragma directive first +// happy. +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +// For _POSIX_TIMER_MAX +#include "ace/os_include/os_limits.h" + +// Define the default constants for ACE. Many of these are used for +// the ACE tests and applications. You can change these values by +// defining the macros in your config.h file. +# if !defined (ACE_DEFAULT_CLOSE_ALL_HANDLES) +# define ACE_DEFAULT_CLOSE_ALL_HANDLES true +# endif /* ACE_DEFAULT_CLOSE_ALL_HANDLES */ + +// The maximum length for a fully qualified Internet name. +# if !defined(ACE_MAX_FULLY_QUALIFIED_NAME_LEN) +# define ACE_MAX_FULLY_QUALIFIED_NAME_LEN 256 +# endif /* ACE_MAX_FULLY_QUALIFIED_NAME_LEN */ + +#if !defined (ACE_DEFAULT_PAGEFILE_POOL_BASE) +#define ACE_DEFAULT_PAGEFILE_POOL_BASE (void *) 0 +#endif /* ACE_DEFAULT_PAGEFILE_POOL_BASE */ + +#if !defined (ACE_DEFAULT_PAGEFILE_POOL_SIZE) +#define ACE_DEFAULT_PAGEFILE_POOL_SIZE (size_t) 0x01000000 +#endif /* ACE_DEFAULT_PAGEFILE_POOL_SIZE */ + +#if !defined (ACE_DEFAULT_PAGEFILE_POOL_CHUNK) +#define ACE_DEFAULT_PAGEFILE_POOL_CHUNK (size_t) 0x00010000 +#endif /* ACE_DEFAULT_PAGEFILE_POOL_CHUNK */ + +#if !defined (ACE_DEFAULT_PAGEFILE_POOL_NAME) +#define ACE_DEFAULT_PAGEFILE_POOL_NAME ACE_TEXT ("Default_ACE_Pagefile_Memory_Pool") +#endif /* ACE_DEFAULT_PAGEFILE_POOL_NAME */ + +#if !defined (ACE_DEFAULT_MESSAGE_BLOCK_PRIORITY) +#define ACE_DEFAULT_MESSAGE_BLOCK_PRIORITY 0 +#endif /* ACE_DEFAULT_MESSAGE_BLOCK_PRIORITY */ + +#if !defined (ACE_DEFAULT_SERVICE_REPOSITORY_SIZE) +#define ACE_DEFAULT_SERVICE_REPOSITORY_SIZE 1024 +#endif /* ACE_DEFAULT_SERVICE_REPOSITORY_SIZE */ + +#if !defined (ACE_DEFAULT_SERVICE_GESTALT_SIZE) +#define ACE_DEFAULT_SERVICE_GESTALT_SIZE 1024 +#endif /* ACE_DEFAULT_SERVICE_GESTALT_SIZE */ + +#if !defined (ACE_REACTOR_NOTIFICATION_ARRAY_SIZE) +#define ACE_REACTOR_NOTIFICATION_ARRAY_SIZE 1024 +#endif /* ACE_REACTOR_NOTIFICATION_ARRAY_SIZE */ + +# if !defined (ACE_DEFAULT_TIMEOUT) +# define ACE_DEFAULT_TIMEOUT 5 +# endif /* ACE_DEFAULT_TIMEOUT */ + +# if !defined (ACE_DEFAULT_BACKLOG) +# define ACE_DEFAULT_BACKLOG 5 +# endif /* ACE_DEFAULT_BACKLOG */ + +# if !defined (ACE_DEFAULT_ASYNCH_BACKLOG) +# define ACE_DEFAULT_ASYNCH_BACKLOG 5 +# endif /* ACE_DEFAULT_ASYNCH_BACKLOG */ + +# if !defined (ACE_DEFAULT_THREADS) +# define ACE_DEFAULT_THREADS 1 +# endif /* ACE_DEFAULT_THREADS */ + +// The following 3 defines are used in the IP multicast and broadcast tests. +# if !defined (ACE_DEFAULT_BROADCAST_PORT) +# define ACE_DEFAULT_BROADCAST_PORT 20000 +# endif /* ACE_DEFAULT_BROADCAST_PORT */ + +# if !defined (ACE_DEFAULT_MULTICAST_PORT) +# define ACE_DEFAULT_MULTICAST_PORT 20001 +# endif /* ACE_DEFAULT_MULTICAST_PORT */ + +# if !defined (ACE_DEFAULT_MULTICAST_ADDR) +// This address MUST be within the range for host group addresses: +// 224.0.0.0 to 239.255.255.255. +# define ACE_DEFAULT_MULTICAST_ADDR "224.9.9.2" +# endif /* ACE_DEFAULT_MULTICAST_ADDR */ + +# if defined (ACE_HAS_IPV6) +# if !defined (ACE_DEFAULT_MULTICASTV6_ADDR) +// This address should be within the range for site-local addresses: +// ff05::0/16 . +# define ACE_DEFAULT_MULTICASTV6_ADDR "ff05:0::ff01:1" +# endif /* ACE_DEFAULT_MULTICASTV6_ADDR */ +# endif + +// Default port number for HTTP. +# if !defined (ACE_DEFAULT_HTTP_SERVER_PORT) +# define ACE_DEFAULT_HTTP_SERVER_PORT 80 +# endif /* ACE_DEFAULT_HTTP_SERVER_PORT */ + +// Used in many IPC_SAP tests +# if !defined (ACE_DEFAULT_SERVER_PORT) +# define ACE_DEFAULT_SERVER_PORT 20002 +# endif /* ACE_DEFAULT_SERVER_PORT */ + +# if !defined (ACE_DEFAULT_HTTP_PORT) +# define ACE_DEFAULT_HTTP_PORT 80 +# endif /* ACE_DEFAULT_HTTP_PORT */ + +# if !defined (ACE_DEFAULT_MAX_SOCKET_BUFSIZ) +# define ACE_DEFAULT_MAX_SOCKET_BUFSIZ 65536 +# endif /* ACE_DEFAULT_MAX_SOCKET_BUFSIZ */ + +# if !defined (ACE_DEFAULT_SERVER_PORT_STR) +# define ACE_DEFAULT_SERVER_PORT_STR ACE_TEXT("20002") +# endif /* ACE_DEFAULT_SERVER_PORT_STR */ + +// Used for the Service_Directory test +# if !defined (ACE_DEFAULT_SERVICE_PORT) +# define ACE_DEFAULT_SERVICE_PORT 20003 +# endif /* ACE_DEFAULT_SERVICE_PORT */ + +// Used for the ACE_Thread_Spawn test +# if !defined (ACE_DEFAULT_THR_PORT ) +# define ACE_DEFAULT_THR_PORT 20004 +# endif /* ACE_DEFAULT_THR_PORT */ + +// Used for tests +# if !defined (ACE_DEFAULT_LOCAL_PORT) +# define ACE_DEFAULT_LOCAL_PORT 20005 +# endif /* ACE_DEFAULT_LOCAL_PORT */ + +// Used for Connector tests +# if !defined (ACE_DEFAULT_LOCAL_PORT_STR) +# define ACE_DEFAULT_LOCAL_PORT_STR "20005" +# endif /* ACE_DEFAULT_LOCAL_PORT_STR */ + +// Used for the name server. +# if !defined (ACE_DEFAULT_NAME_SERVER_PORT) +# define ACE_DEFAULT_NAME_SERVER_PORT 20006 +# endif /* ACE_DEFAULT_NAME_SERVER_PORT */ + +# if !defined (ACE_DEFAULT_NAME_SERVER_PORT_STR) +# define ACE_DEFAULT_NAME_SERVER_PORT_STR "20006" +# endif /* ACE_DEFAULT_NAME_SERVER_PORT_STR */ + +// Used for the token server. +# if !defined (ACE_DEFAULT_TOKEN_SERVER_PORT) +# define ACE_DEFAULT_TOKEN_SERVER_PORT 20007 +# endif /* ACE_DEFAULT_TOKEN_SERVER_PORT */ + +# if !defined (ACE_DEFAULT_TOKEN_SERVER_PORT_STR) +# define ACE_DEFAULT_TOKEN_SERVER_PORT_STR "20007" +# endif /* ACE_DEFAULT_TOKEN_SERVER_PORT_STR */ + +// Used for the logging server. +# if !defined (ACE_DEFAULT_LOGGING_SERVER_PORT) +# define ACE_DEFAULT_LOGGING_SERVER_PORT 20008 +# endif /* ACE_DEFAULT_LOGGING_SERVER_PORT */ + +# if !defined (ACE_DEFAULT_LOGGING_SERVER_PORT_STR) +# define ACE_DEFAULT_LOGGING_SERVER_PORT_STR "20008" +# endif /* ACE_DEFAULT_LOGGING_SERVER_PORT_STR */ + +// Used for the logging server. +# if !defined (ACE_DEFAULT_THR_LOGGING_SERVER_PORT) +# define ACE_DEFAULT_THR_LOGGING_SERVER_PORT 20008 +# endif /* ACE_DEFAULT_THR_LOGGING_SERVER_PORT */ + +# if !defined (ACE_DEFAULT_THR_LOGGING_SERVER_PORT_STR) +# define ACE_DEFAULT_THR_LOGGING_SERVER_PORT_STR "20008" +# endif /* ACE_DEFAULT_THR_LOGGING_SERVER_PORT_STR */ + +// Used for the time server. +# if !defined (ACE_DEFAULT_TIME_SERVER_PORT) +# define ACE_DEFAULT_TIME_SERVER_PORT 20009 +# endif /* ACE_DEFAULT_TIME_SERVER_PORT */ + +# if !defined (ACE_DEFAULT_TIME_SERVER_PORT_STR) +# define ACE_DEFAULT_TIME_SERVER_PORT_STR "20009" +# endif /* ACE_DEFAULT_TIME_SERVER_PORT_STR */ + +# if !defined (ACE_DEFAULT_TIME_SERVER_STR) +# define ACE_DEFAULT_TIME_SERVER_STR "ACE_TS_TIME" +# endif /* ACE_DEFAULT_TIME_SERVER_STR */ + +// Used by the FIFO tests +# if !defined (ACE_DEFAULT_RENDEZVOUS) +# if defined (ACE_HAS_STREAM_PIPES) +# define ACE_DEFAULT_RENDEZVOUS ACE_TEXT("/tmp/fifo.ace") +# else +# define ACE_DEFAULT_RENDEZVOUS ACE_TEXT("localhost:20010") +# endif /* ACE_HAS_STREAM_PIPES */ +# endif /* ACE_DEFAULT_RENDEZVOUS */ + +// Used for the UNIX syslog logging interface to ACE_Log_Msg. +# ifndef ACE_DEFAULT_SYSLOG_FACILITY +# define ACE_DEFAULT_SYSLOG_FACILITY LOG_USER +# endif /* ACE_DEFAULT_SYSLOG_FACILITY */ + +# if !defined (ACE_HAS_STREAM_LOG_MSG_IPC) +# if defined (ACE_HAS_STREAM_PIPES) +# define ACE_HAS_STREAM_LOG_MSG_IPC 1 +# else +# define ACE_HAS_STREAM_LOG_MSG_IPC 0 +# endif /* ACE_HAS_STREAM_PIPES */ +# endif /* !ACE_HAS_STREAM_LOG_MSG_IPC */ + +# if !defined (ACE_DEFAULT_LOGGER_KEY) +# if (ACE_HAS_STREAM_LOG_MSG_IPC == 1) +# define ACE_DEFAULT_LOGGER_KEY ACE_TEXT ("/tmp/server_daemon") +# else +# define ACE_DEFAULT_LOGGER_KEY ACE_TEXT ("localhost:20012") +# endif /* ACE_HAS_STREAM_LOG_MSG_IPC==1 */ +# endif /* ACE_DEFAULT_LOGGER_KEY */ + +// The way to specify the local host for loopback IP. This is usually +// "localhost" but it may need changing on some platforms. +# if !defined (ACE_LOCALHOST) +# define ACE_LOCALHOST ACE_TEXT ("localhost") +# endif + +// This specification for an IPv6 localhost should work on all platforms +// supporting IPv6 +# if defined (ACE_HAS_IPV6) +# if !defined (ACE_IPV6_LOCALHOST) +# define ACE_IPV6_LOCALHOST ACE_TEXT ("::1") +# endif /* ACE_IPV6_LOCALHOST*/ +#endif /* ACE_HAS_IPV6 */ + +// This specification for an IPv6 ANY address should work on all platforms +// supporting IPv6 +# if defined (ACE_HAS_IPV6) +# if !defined (ACE_IPV6_ANY) +# define ACE_IPV6_ANY ACE_TEXT ("::") +# endif /* ACE_IPV6_ANY*/ +#endif /* ACE_HAS_IPV6 */ + +# if !defined (ACE_DEFAULT_SERVER_HOST) +# if defined (ACE_HAS_IPV6) +# define ACE_DEFAULT_SERVER_HOST ACE_IPV6_LOCALHOST +# else /*ACE_HAS_IPV6*/ +# define ACE_DEFAULT_SERVER_HOST ACE_LOCALHOST +# endif /*ACE_HAS_IPV6*/ +# endif /* ACE_DEFAULT_SERVER_HOST */ + +// Default shared memory key +# if !defined (ACE_DEFAULT_SHM_KEY) +# define ACE_DEFAULT_SHM_KEY 1234 +# endif /* ACE_DEFAULT_SHM_KEY */ + +// Default address for shared memory mapped files and SYSV shared memory +// (defaults to 64 M). +# if !defined (ACE_DEFAULT_BASE_ADDR) +# define ACE_DEFAULT_BASE_ADDR ((char *) (64 * 1024 * 1024)) +# endif /* ACE_DEFAULT_BASE_ADDR */ + +// Default segment size used by SYSV shared memory (128 K) +# if !defined (ACE_DEFAULT_SEGMENT_SIZE) +# define ACE_DEFAULT_SEGMENT_SIZE 1024 * 128 +# endif /* ACE_DEFAULT_SEGMENT_SIZE */ + +// Maximum number of SYSV shared memory segments +// (does anyone know how to figure out the right values?!) +# if !defined (ACE_DEFAULT_MAX_SEGMENTS) +# define ACE_DEFAULT_MAX_SEGMENTS 6 +# endif /* ACE_DEFAULT_MAX_SEGMENTS */ + +// Name of the map that's stored in shared memory. +# if !defined (ACE_NAME_SERVER_MAP) +# define ACE_NAME_SERVER_MAP "Name Server Map" +# endif /* ACE_NAME_SERVER_MAP */ + +// Default file permissions. +# if !defined (ACE_DEFAULT_FILE_PERMS) +# if defined (ACE_VXWORKS) +# define ACE_DEFAULT_FILE_PERMS (S_IRUSR | S_IWUSR| S_IRGRP| S_IROTH) +# else +# define ACE_DEFAULT_FILE_PERMS 0644 +# endif /* ACE_VXWORKS */ +# endif /* ACE_DEFAULT_FILE_PERMS */ + +// Default directory permissions. +# if !defined (ACE_DEFAULT_DIR_PERMS) +# define ACE_DEFAULT_DIR_PERMS 0755 +# endif /* ACE_DEFAULT_DIR_PERMS */ + +# if !defined (ACE_DEFAULT_TIMEPROBE_TABLE_SIZE) +# define ACE_DEFAULT_TIMEPROBE_TABLE_SIZE 8 * 1024 +# endif /* ACE_DEFAULT_TIMEPROBE_TABLE_SIZE */ + +// Default size of the ACE Map_Manager. +# if !defined (ACE_DEFAULT_MAP_SIZE) +# define ACE_DEFAULT_MAP_SIZE 1024 +# endif /* ACE_DEFAULT_MAP_SIZE */ + +# if defined (ACE_DEFAULT_MAP_SIZE) && (ACE_DEFAULT_MAP_SIZE == 0) +# error ACE_DEFAULT_MAP_SIZE should not be zero +# endif /* ACE_DEFAULT_MAP_SIZE */ + +// Defaults for ACE Timer Wheel +# if !defined (ACE_DEFAULT_TIMER_WHEEL_SIZE) +# define ACE_DEFAULT_TIMER_WHEEL_SIZE 1024 +# endif /* ACE_DEFAULT_TIMER_WHEEL_SIZE */ + +# if !defined (ACE_DEFAULT_TIMER_WHEEL_RESOLUTION) +# define ACE_DEFAULT_TIMER_WHEEL_RESOLUTION 100 +# endif /* ACE_DEFAULT_TIMER_WHEEL_RESOLUTION */ + +// Default size for ACE Timer Hash table +# if !defined (ACE_DEFAULT_TIMER_HASH_TABLE_SIZE) +# define ACE_DEFAULT_TIMER_HASH_TABLE_SIZE 1024 +# endif /* ACE_DEFAULT_TIMER_HASH_TABLE_SIZE */ + +// Defaults for the ACE Free List +# if !defined (ACE_DEFAULT_FREE_LIST_PREALLOC) +# define ACE_DEFAULT_FREE_LIST_PREALLOC 0 +# endif /* ACE_DEFAULT_FREE_LIST_PREALLOC */ + +# if !defined (ACE_DEFAULT_FREE_LIST_LWM) +# define ACE_DEFAULT_FREE_LIST_LWM 0 +# endif /* ACE_DEFAULT_FREE_LIST_LWM */ + +# if !defined (ACE_DEFAULT_FREE_LIST_HWM) +# define ACE_DEFAULT_FREE_LIST_HWM 25000 +# endif /* ACE_DEFAULT_FREE_LIST_HWM */ + +# if !defined (ACE_DEFAULT_FREE_LIST_INC) +# define ACE_DEFAULT_FREE_LIST_INC 100 +# endif /* ACE_DEFAULT_FREE_LIST_INC */ + +# if !defined (ACE_UNIQUE_NAME_LEN) +# define ACE_UNIQUE_NAME_LEN 100 +# endif /* ACE_UNIQUE_NAME_LEN */ + +# if !defined (ACE_MAX_DGRAM_SIZE) + // This is just a guess. 8k is the normal limit on + // most machines because that's what NFS expects. +# define ACE_MAX_DGRAM_SIZE 8192 +# endif /* ACE_MAX_DGRAM_SIZE */ + +# if !defined (ACE_DEFAULT_ARGV_BUFSIZ) +# define ACE_DEFAULT_ARGV_BUFSIZ 1024 * 4 +# endif /* ACE_DEFAULT_ARGV_BUFSIZ */ + +// A free list which create more elements when there aren't enough +// elements. +# define ACE_FREE_LIST_WITH_POOL 1 + +// A simple free list which doen't allocate/deallocate elements. +# define ACE_PURE_FREE_LIST 2 + +# if defined (ACE_WIN32) + +// This is necessary to work around bugs with Win32 non-blocking +// connects... +# if !defined (ACE_NON_BLOCKING_BUG_DELAY) +# define ACE_NON_BLOCKING_BUG_DELAY 35000 +# endif /* ACE_NON_BLOCKING_BUG_DELAY */ +# endif /*ACE_WIN32*/ + +// Max size of an ACE Log Record data buffer. This can be reset in +// the config.h file if you'd like to increase or decrease the size. +# if !defined (ACE_MAXLOGMSGLEN) +# define ACE_MAXLOGMSGLEN 4 * 1024 +# endif /* ACE_MAXLOGMSGLEN */ + +// Max size of an ACE Token. +# define ACE_MAXTOKENNAMELEN 40 + +// Max size of an ACE Token client ID. +# define ACE_MAXCLIENTIDLEN MAXHOSTNAMELEN + 20 + +/// Max udp packet size +#if !defined (ACE_MAX_UDP_PACKET_SIZE) +#define ACE_MAX_UDP_PACKET_SIZE 65536 +#endif + +/** + * @name Default values to control CDR classes memory allocation strategies + */ +//@{ + +/// Control the initial size of all CDR buffers, application +/// developers may want to optimize this value to fit their request +/// size +#if !defined (ACE_DEFAULT_CDR_BUFSIZE) +# define ACE_DEFAULT_CDR_BUFSIZE 512 +#endif /* ACE_DEFAULT_CDR_BUFSIZE */ + +#if (ACE_DEFAULT_CDR_BUFSIZE == 0) +# error: ACE_DEFAULT_CDR_BUFSIZE should be bigger then 0 +#endif + +/// Stop exponential growth of CDR buffers to avoid overallocation +#if !defined (ACE_DEFAULT_CDR_EXP_GROWTH_MAX) +# define ACE_DEFAULT_CDR_EXP_GROWTH_MAX 65536 +#endif /* ACE_DEFAULT_CDR_EXP_GROWTH_MAX */ + +/// Control CDR buffer growth after maximum exponential growth is +/// reached +#if !defined (ACE_DEFAULT_CDR_LINEAR_GROWTH_CHUNK) +# define ACE_DEFAULT_CDR_LINEAR_GROWTH_CHUNK 65536 +#endif /* ACE_DEFAULT_CDR_LINEAR_GROWTH_CHUNK */ +//@} + +/// Control the zero-copy optimizations for octet sequences +/** + * Large octet sequences can be sent without any copies by chaining + * them in the list of message blocks that represent a single CDR + * stream. However, if the octet sequence is too small the zero copy + * optimizations actually hurt performance. Octet sequences smaller + * than this value will be copied. + */ +#if !defined (ACE_DEFAULT_CDR_MEMCPY_TRADEOFF) +#define ACE_DEFAULT_CDR_MEMCPY_TRADEOFF 256 +#endif /* ACE_DEFAULT_CDR_MEMCPY_TRADEOFF */ + +#if defined (ACE_WIN32) + // Define the pathname separator characters for Win32 (ugh). +# define ACE_DIRECTORY_SEPARATOR_STR_A "\\" +# define ACE_DIRECTORY_SEPARATOR_CHAR_A '\\' +#else + // Define the pathname separator characters for UNIX. +# define ACE_DIRECTORY_SEPARATOR_STR_A "/" +# define ACE_DIRECTORY_SEPARATOR_CHAR_A '/' +#endif /* ACE_WIN32 */ + +// Define the Wide character and normal versions of some of the string macros +#if defined (ACE_HAS_WCHAR) +# define ACE_DIRECTORY_SEPARATOR_STR_W ACE_TEXT_WIDE(ACE_DIRECTORY_SEPARATOR_STR_A) +# define ACE_DIRECTORY_SEPARATOR_CHAR_W ACE_TEXT_WIDE(ACE_DIRECTORY_SEPARATOR_CHAR_A) +#endif /* ACE_HAS_WCHAR */ + +#define ACE_DIRECTORY_SEPARATOR_STR ACE_TEXT (ACE_DIRECTORY_SEPARATOR_STR_A) +#define ACE_DIRECTORY_SEPARATOR_CHAR ACE_TEXT (ACE_DIRECTORY_SEPARATOR_CHAR_A) + +#if !defined (ACE_DEFAULT_THREAD_PRIORITY) +# define ACE_DEFAULT_THREAD_PRIORITY (-0x7fffffffL - 1L) +#endif /* ACE_DEFAULT_THREAD_PRIORITY */ + +#if !defined (ACE_DEFAULT_THREAD_STACKSIZE) +# define ACE_DEFAULT_THREAD_STACKSIZE 0 +#endif /* ACE_DEFAULT_THREAD_STACKSIZE */ + +#if !defined (ACE_MAX_DEFAULT_PORT) +# define ACE_MAX_DEFAULT_PORT 65535 +#endif /* ACE_MAX_DEFAULT_PORT */ + +// Default number of ACE_Event_Handlers supported by +// ACE_Timer_Heap. +#if !defined (ACE_DEFAULT_TIMERS) && defined (_POSIX_TIMER_MAX) +# define ACE_DEFAULT_TIMERS _POSIX_TIMER_MAX +#endif /* ACE_DEFAULT_TIMERS */ + +#if !defined (ACE_DEFAULT_TIMERS) || (defined (ACE_DEFAULT_TIMERS) && (ACE_DEFAULT_TIMERS == 0)) +#error ACE_DEFAULT_TIMERS should be defined and not be zero +#endif /* ACE_DEFAULT_TIMERS */ + +#if defined (ACE_WIN32) +# define ACE_PLATFORM_A "Win32" +# define ACE_PLATFORM_EXE_SUFFIX_A ".exe" +#elif defined (ACE_VXWORKS) +# define ACE_PLATFORM_A "VxWorks" +# if defined (__RTP__) +# define ACE_PLATFORM_EXE_SUFFIX_A ".vxe" +# else +# define ACE_PLATFORM_EXE_SUFFIX_A ".out" +# endif +#else /* !ACE_WIN32 && !ACE_VXWORKS */ +# define ACE_PLATFORM_A "UNIX" +# define ACE_PLATFORM_EXE_SUFFIX_A "" +#endif /* ACE_WIN32 */ + +// Define the Wide character and normal versions of some of the string macros +#if defined (ACE_HAS_WCHAR) +# define ACE_PLATFORM_W ACE_TEXT_WIDE(ACE_PLATFORM_A) +# define ACE_PLATFORM_EXE_SUFFIX_W ACE_TEXT_WIDE(ACE_PLATFORM_EXE_SUFFIX_A) +#endif /* ACE_HAS_WCHAR */ + +#define ACE_PLATFORM ACE_TEXT (ACE_PLATFORM_A) +#define ACE_PLATFORM_EXE_SUFFIX ACE_TEXT (ACE_PLATFORM_EXE_SUFFIX_A) + +#if defined (ACE_WIN32) +# define ACE_LD_SEARCH_PATH ACE_TEXT ("PATH") +# define ACE_LD_SEARCH_PATH_SEPARATOR_STR ACE_TEXT (";") +# define ACE_DLL_SUFFIX ACE_TEXT (".dll") +# if !defined (ACE_DLL_PREFIX) +# define ACE_DLL_PREFIX ACE_TEXT ("") +# endif /* !ACE_DLL_PREFIX */ +#else /* !ACE_WIN32 */ +# if !defined (ACE_LD_SEARCH_PATH) +# define ACE_LD_SEARCH_PATH ACE_TEXT ("LD_LIBRARY_PATH") +# endif /* ACE_LD_SEARCH_PATH */ +# if !defined (ACE_LD_SEARCH_PATH_SEPARATOR_STR) +# define ACE_LD_SEARCH_PATH_SEPARATOR_STR ACE_TEXT (":") +# endif /* ACE_LD_SEARCH_PATH_SEPARATOR_STR */ +#endif /* ACE_WIN32 */ + +#if !defined (ACE_DLL_SUFFIX) +# define ACE_DLL_SUFFIX ACE_TEXT (".so") +#endif /* ACE_DLL_SUFFIX */ + +#if !defined (ACE_DLL_PREFIX) +# define ACE_DLL_PREFIX ACE_TEXT ("lib") +#endif /* ACE_DLL_PREFIX */ + +#if defined (ACE_WIN32) +// Used for dynamic linking +# if !defined (ACE_DEFAULT_SVC_CONF) +# if (ACE_USES_CLASSIC_SVC_CONF == 1) +# define ACE_DEFAULT_SVC_CONF ACE_TEXT (".\\svc.conf") +# else +# define ACE_DEFAULT_SVC_CONF ACE_TEXT (".\\svc.conf.xml") +# endif /* ACE_USES_CLASSIC_SVC_CONF ==1 */ +# endif /* ACE_DEFAULT_SVC_CONF */ +#endif /* ACE_WIN32 */ + + // Used for dynamic linking. +#if !defined (ACE_DEFAULT_SVC_CONF) +# if (ACE_USES_CLASSIC_SVC_CONF == 1) +# define ACE_DEFAULT_SVC_CONF ACE_TEXT ("./svc.conf") +# else +# define ACE_DEFAULT_SVC_CONF ACE_TEXT ("./svc.conf.xml") +# endif /* ACE_USES_CLASSIC_SVC_CONF ==1 */ +#endif /* ACE_DEFAULT_SVC_CONF */ + +#if !defined (ACE_LOGGER_KEY) +# define ACE_LOGGER_KEY ACE_TEXT ("/tmp/server_daemon") +#endif /* ACE_LOGGER_KEY */ + +// Theses defines are used by the ACE Name Server. +#if !defined (ACE_DEFAULT_LOCALNAME_A) +# define ACE_DEFAULT_LOCALNAME_A "localnames" +#endif /* ACE_DEFAULT_LOCALNAME_A */ +#if !defined (ACE_DEFAULT_GLOBALNAME_A) +# define ACE_DEFAULT_GLOBALNAME_A "globalnames" +#endif /* ACE_DEFAULT_GLOBALNAME_A */ + +// ACE_DEFAULT_NAMESPACE_DIR is for legacy mode apps. A better +// way of doing this is something like ACE_Lib_Find::get_temp_dir, since +// this directory may not exist +#if defined (ACE_LEGACY_MODE) +# if defined (ACE_WIN32) +# define ACE_DEFAULT_NAMESPACE_DIR_A "C:\\temp" +# else /* ACE_WIN32 */ +# define ACE_DEFAULT_NAMESPACE_DIR_A "/tmp" +# endif /* ACE_WIN32 */ +# if defined (ACE_HAS_WCHAR) +# define ACE_DEFAULT_NAMESPACE_DIR_W ACE_TEXT_WIDE(ACE_DEFAULT_NAMESPACE_DIR_A) +# endif /* ACE_HAS_WCHAR */ +# define ACE_DEFAULT_NAMESPACE_DIR ACE_TEXT(ACE_DEFAULT_NAMESPACE_DIR_A) +#endif /* ACE_LEGACY_MODE */ + +#if defined (ACE_HAS_WCHAR) +# define ACE_DEFAULT_LOCALNAME_W ACE_TEXT_WIDE(ACE_DEFAULT_LOCALNAME_A) +# define ACE_DEFAULT_GLOBALNAME_W ACE_TEXT_WIDE(ACE_DEFAULT_GLOBALNAME_A) +#endif /* ACE_HAS_WCHAR */ + +#define ACE_DEFAULT_LOCALNAME ACE_TEXT (ACE_DEFAULT_LOCALNAME_A) +#define ACE_DEFAULT_GLOBALNAME ACE_TEXT (ACE_DEFAULT_GLOBALNAME_A) + +#if !defined (ACE_DEFAULT_OPEN_PERMS) +# define ACE_DEFAULT_OPEN_PERMS ACE_DEFAULT_FILE_PERMS +#endif /* ACE_DEFAULT_OPEN_PERMS */ + +#if !defined (ACE_DEFAULT_RW_PROCESS_MUTEX_PERMS) +# if defined (ACE_WIN32) +# define ACE_DEFAULT_RW_PROCESS_MUTEX_PERMS ACE_DEFAULT_OPEN_PERMS +# else +# define ACE_DEFAULT_RW_PROCESS_MUTEX_PERMS (S_IRUSR | S_IWUSR) +# endif /* ACE_WIN32 */ +#endif /* ACE_DEFAULT_RW_PROCESS_MUTEX_PERMS */ + +# if defined (ACE_WIN32) + // The "null" device on Win32. +# define ACE_DEV_NULL "nul" +# define ACE_SYSCALL_FAILED 0xFFFFFFFF +# else /* !ACE_WIN32 */ + // The "null" device on UNIX. +# define ACE_DEV_NULL "/dev/null" +# define ACE_SYSCALL_FAILED -1 +# endif /* ACE_WIN32 */ + +#include /**/ "ace/post.h" +#endif /*ACE_DEFAULT_CONSTANTS_H*/ diff --git a/dep/acelite/ace/Dev_Poll_Reactor.cpp b/dep/acelite/ace/Dev_Poll_Reactor.cpp new file mode 100644 index 00000000000..e0adc19a418 --- /dev/null +++ b/dep/acelite/ace/Dev_Poll_Reactor.cpp @@ -0,0 +1,2610 @@ +// $Id: Dev_Poll_Reactor.cpp 90177 2010-05-19 11:44:22Z vzykov $ + +#include "ace/OS_NS_errno.h" +#include "ace/Dev_Poll_Reactor.h" +#include "ace/Signal.h" +#include "ace/Sig_Handler.h" + +ACE_RCSID (ace, + Dev_Poll_Reactor, + "$Id: Dev_Poll_Reactor.cpp 90177 2010-05-19 11:44:22Z vzykov $") + +#if defined (ACE_HAS_EVENT_POLL) || defined (ACE_HAS_DEV_POLL) + +# include "ace/OS_NS_unistd.h" +# include "ace/OS_NS_fcntl.h" +# include "ace/OS_NS_stropts.h" + +# if defined (ACE_HAS_DEV_POLL) +# if defined (linux) +# include /**/ +# elif defined (HPUX_VERS) && HPUX_VERS < 1123 +# include /**/ +# else +# include /**/ +# endif /* linux */ +# endif /* ACE_HAS_DEV_POLL */ + +#if !defined (__ACE_INLINE__) +# include "ace/Dev_Poll_Reactor.inl" +#endif /* __ACE_INLINE__ */ + + +#include "ace/Handle_Set.h" +#include "ace/Reactor.h" +#include "ace/Timer_Heap.h" +#include "ace/Timer_Queue.h" +#include "ace/ACE.h" +#include "ace/Reverse_Lock_T.h" +#include "ace/Recursive_Thread_Mutex.h" +#include "ace/Null_Mutex.h" +#include "ace/os_include/os_poll.h" +#include "ace/OS_NS_sys_mman.h" +#include "ace/Guard_T.h" +#include "ace/OS_NS_string.h" +#include "ace/OS_NS_sys_time.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_Dev_Poll_Reactor_Notify::ACE_Dev_Poll_Reactor_Notify (void) + : dp_reactor_ (0) + , notification_pipe_ () + , max_notify_iterations_ (-1) +#if defined (ACE_HAS_REACTOR_NOTIFICATION_QUEUE) + , notification_queue_ () +#endif /* ACE_HAS_REACTOR_NOTIFICATION_QUEUE */ + , dispatching_ (false) +{ +} + +int +ACE_Dev_Poll_Reactor_Notify::open (ACE_Reactor_Impl *r, + ACE_Timer_Queue * /* timer_queue */, + int disable_notify_pipe) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor_Notify::open"); + + if (disable_notify_pipe == 0) + { + this->dp_reactor_ = dynamic_cast (r); + + if (this->dp_reactor_ == 0) + { + errno = EINVAL; + return -1; + } + + if (this->notification_pipe_.open () == -1) + return -1; + +#if defined (F_SETFD) + // close-on-exec + ACE_OS::fcntl (this->notification_pipe_.read_handle (), F_SETFD, 1); + ACE_OS::fcntl (this->notification_pipe_.write_handle (), F_SETFD, 1); +#endif /* F_SETFD */ + +#if defined (ACE_HAS_REACTOR_NOTIFICATION_QUEUE) + if (notification_queue_.open () == -1) + { + return -1; + } + + if (ACE::set_flags (this->notification_pipe_.write_handle (), + ACE_NONBLOCK) == -1) + return -1; +#endif /* ACE_HAS_REACTOR_NOTIFICATION_QUEUE */ + + // Set the read handle into non-blocking mode since we need to + // perform a "speculative" read when determining if there are + // notifications to dispatch. + if (ACE::set_flags (this->notification_pipe_.read_handle (), + ACE_NONBLOCK) == -1) + return -1; + } + + return 0; +} + +int +ACE_Dev_Poll_Reactor_Notify::close (void) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor_Notify::close"); + +#if defined (ACE_HAS_REACTOR_NOTIFICATION_QUEUE) + notification_queue_.reset (); +#endif /* ACE_HAS_REACTOR_NOTIFICATION_QUEUE */ + + return this->notification_pipe_.close (); +} + +int +ACE_Dev_Poll_Reactor_Notify::notify (ACE_Event_Handler *eh, + ACE_Reactor_Mask mask, + ACE_Time_Value *timeout) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor_Notify::notify"); + + // Just consider this method a "no-op" if there's no + // ACE_Dev_Poll_Reactor configured. + if (this->dp_reactor_ == 0) + return 0; + + ACE_Notification_Buffer buffer (eh, mask); + +#if defined (ACE_HAS_REACTOR_NOTIFICATION_QUEUE) + ACE_UNUSED_ARG (timeout); + ACE_Dev_Poll_Handler_Guard eh_guard (eh); + + // When using the queue, the push call indicates whether or not a pipe + // write is needed. If it's not, don't waste pipe space. + int push_result = this->notification_queue_.push_new_notification (buffer); + if (-1 == push_result || 1 == push_result) + return -1 == push_result ? -1 : 0; // Also decrement eh's reference count + + // The notification has been queued, so it will be delivered at some + // point (and may have been already); release the refcnt guard. + eh_guard.release (); + + // Now pop the pipe to force the callback for dispatching when ready. If + // the send fails due to a full pipe, don't fail - assume the already-sent + // pipe bytes will cause the entire notification queue to be processed. + // Note that we don't need a timeout since the pipe is already in + // nonblocking mode and all we want is one attempt. + ssize_t n = ACE::send (this->notification_pipe_.write_handle (), + (char *) &buffer, + 1); // Only need one byte to pop the pipe + if (n == -1 && (errno != EAGAIN)) + return -1; + + return 0; +#else + + ACE_Dev_Poll_Handler_Guard eh_guard (eh); + + ssize_t n = ACE::send (this->notification_pipe_.write_handle (), + (char *) &buffer, + sizeof buffer, + timeout); + if (n == -1) + return -1; + + eh_guard.release (); + + return 0; +#endif /* ACE_HAS_REACTOR_NOTIFICATION_QUEUE */ +} + +int +ACE_Dev_Poll_Reactor_Notify::dispatch_notifications ( + int & /* number_of_active_handles */, + ACE_Handle_Set & /* rd_mask */) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor_Notify::dispatch_notifications"); + + // This method is unimplemented in the ACE_Dev_Poll_Reactor. + // Instead, the notification handler is invoked as part of the IO + // event set. Doing so alters the some documented semantics that + // state that the notifications are handled before IO events. + // Enforcing such semantics does not appear to be beneficial, and + // also serves to slow down event dispatching particularly with this + // ACE_Dev_Poll_Reactor. + + ACE_NOTSUP_RETURN (-1); +} + +int +ACE_Dev_Poll_Reactor_Notify::read_notify_pipe (ACE_HANDLE handle, + ACE_Notification_Buffer &buffer) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor_Notify::read_notify_pipe"); + + // This is a (non-blocking) "speculative" read, i.e., we attempt to + // read even if no event was polled on the read handle. A + // speculative read is necessary since notifications must be + // dispatched before IO events. We can avoid the speculative read + // by "walking" the array of pollfd structures returned from + // `/dev/poll' or `/dev/epoll' but that is potentially much more + // expensive than simply checking for an EWOULDBLOCK. + size_t to_read; + char *read_p; + +#if defined (ACE_HAS_REACTOR_NOTIFICATION_QUEUE) + // The idea in the queued case is to be sure we never end up with a notify + // queued but no byte in the pipe. If that happens, the notify won't be + // dispatched. So always try to empty the pipe, read the queue, then put + // a byte in if needed. The notify() method is enqueueing then writing the + // pipe, so be sure to do it in the reverse order here to avoid a race + // between removing the last notification from the queue and the notify + // side writing its byte. + char b[1024]; + read_p = b; + to_read = sizeof(b); + (void)ACE::recv (handle, read_p, to_read); + + bool more_messages_queued = false; + ACE_Notification_Buffer next; + int result = notification_queue_.pop_next_notification (buffer, + more_messages_queued, + next); + + if (result <= 0) // Nothing dequeued or error + return result; + + // If there are more messages, ensure there's a byte in the pipe + // in case the notification limit stops dequeuing notifies before + // emptying the queue. + if (more_messages_queued) + (void) ACE::send (this->notification_pipe_.write_handle (), + (char *)&next, + 1); /* one byte is enough */ + return 1; +#else + to_read = sizeof buffer; + read_p = (char *)&buffer; + + ssize_t n = ACE::recv (handle, read_p, to_read); + + if (n > 0) + { + // Check to see if we've got a short read. + if (static_cast (n) != to_read) + { + size_t remainder = to_read - n; + + // If so, try to recover by reading the remainder. If this + // doesn't work we're in big trouble since the input stream + // won't be aligned correctly. I'm not sure quite what to + // do at this point. It's probably best just to return -1. + if (ACE::recv (handle, &read_p[n], remainder) <= 0) + return -1; + } + + return 1; + } + + // Return -1 if things have gone seriously wrong. + if (n <= 0 && (errno != EWOULDBLOCK && errno != EAGAIN)) + return -1; + + return 0; +#endif /* ACE_HAS_REACTOR_NOTIFICATION_QUEUE */ +} + + +int +ACE_Dev_Poll_Reactor_Notify::handle_input (ACE_HANDLE handle) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor_Notify::handle_input"); + + { + ACE_MT (ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, mon, this->dispatching_lock_, -1)); + if (this->dispatching_) + return 0; + this->dispatching_ = true; + } + + int number_dispatched = 0; + int result = 0; + ACE_Notification_Buffer buffer; + + while ((result = this->read_notify_pipe (handle, buffer)) > 0) + { + // Dispatch the buffer + // NOTE: We count only if we made any dispatches ie. upcalls. + if (this->dispatch_notify (buffer) > 0) + ++number_dispatched; + + // Bail out if we've reached the . Note that + // by default is -1, so we'll loop until all + // the available notifications have been dispatched. + if (number_dispatched == this->max_notify_iterations_) + break; + } + + if (result == -1) + { + // Reassign number_dispatched to -1 if things have gone + // seriously wrong. + number_dispatched = -1; + } + + this->dispatching_ = false; + + return number_dispatched; +} + +ACE_HANDLE +ACE_Dev_Poll_Reactor_Notify::notify_handle (void) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor_Notify::notify_handle"); + + return this->notification_pipe_.read_handle (); +} + +int +ACE_Dev_Poll_Reactor_Notify::is_dispatchable (ACE_Notification_Buffer &) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor_Notify::is_dispatchable"); + + ACE_NOTSUP_RETURN (-1); +} + +int +ACE_Dev_Poll_Reactor_Notify::dispatch_notify (ACE_Notification_Buffer &buffer) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor_Notify::dispatch_notify"); + + // If eh == 0 then another thread is unblocking the + // ACE_Dev_Poll_Reactor to update the ACE_Dev_Poll_Reactor's + // internal structures. Otherwise, we need to dispatch the + // appropriate handle_* method on the ACE_Event_Handler + // pointer we've been passed. + if (buffer.eh_ != 0) + { + int result = 0; + + // Guard the handler's refcount. Recall that when the notify + // was queued, the refcount was incremented, so it need not be + // now. The guard insures that it is decremented properly. + ACE_Dev_Poll_Handler_Guard eh_guard (buffer.eh_, false); + + switch (buffer.mask_) + { + case ACE_Event_Handler::READ_MASK: + case ACE_Event_Handler::ACCEPT_MASK: + result = buffer.eh_->handle_input (ACE_INVALID_HANDLE); + break; + case ACE_Event_Handler::WRITE_MASK: + result = buffer.eh_->handle_output (ACE_INVALID_HANDLE); + break; + case ACE_Event_Handler::EXCEPT_MASK: + result = buffer.eh_->handle_exception (ACE_INVALID_HANDLE); + break; + default: + // Should we bail out if we get an invalid mask? + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("dispatch_notify invalid mask = %d\n"), + buffer.mask_)); + } + if (result == -1) + buffer.eh_->handle_close (ACE_INVALID_HANDLE, buffer.mask_); + } + + return 1; +} + +void +ACE_Dev_Poll_Reactor_Notify::max_notify_iterations (int iterations) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor_Notify::max_notify_iterations"); + + // Must always be > 0 or < 0 to optimize the loop exit condition. + if (iterations == 0) + iterations = 1; + + this->max_notify_iterations_ = iterations; +} + +int +ACE_Dev_Poll_Reactor_Notify::max_notify_iterations (void) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor_Notify::max_notify_iterations"); + + return this->max_notify_iterations_; +} + +int +ACE_Dev_Poll_Reactor_Notify::purge_pending_notifications ( + ACE_Event_Handler *eh, + ACE_Reactor_Mask mask) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor_Notify::purge_pending_notifications"); + +#if defined (ACE_HAS_REACTOR_NOTIFICATION_QUEUE) + + return notification_queue_.purge_pending_notifications (eh, mask); + +#else /* defined (ACE_HAS_REACTOR_NOTIFICATION_QUEUE) */ + ACE_UNUSED_ARG (eh); + ACE_UNUSED_ARG (mask); + ACE_NOTSUP_RETURN (-1); +#endif /* defined (ACE_HAS_REACTOR_NOTIFICATION_QUEUE) */ +} + +void +ACE_Dev_Poll_Reactor_Notify::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Dev_Poll_Reactor_Notify::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("dp_reactor_ = %@"), + this->dp_reactor_)); + this->notification_pipe_.dump (); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +// ----------------------------------------------------------------- + +ACE_Dev_Poll_Reactor::Handler_Repository::Handler_Repository (void) + : size_ (0), + max_size_ (0), + handlers_ (0) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::Handler_Repository::Handler_Repository"); +} + +bool +ACE_Dev_Poll_Reactor::Handler_Repository::invalid_handle ( + ACE_HANDLE handle) const +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::Handler_Repository::invalid_handle"); + + if (handle < 0 || handle >= this->max_size_) + { + errno = EINVAL; + return true; + } + else + return false; +} + +bool +ACE_Dev_Poll_Reactor::Handler_Repository::handle_in_range ( + ACE_HANDLE handle) const +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::Handler_Repository::handle_in_range"); + + if (handle >= 0 && handle < this->max_size_) + return true; + else + { + errno = EINVAL; + return false; + } +} + +int +ACE_Dev_Poll_Reactor::Handler_Repository::open (size_t size) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::Handler_Repository::open"); + + this->max_size_ = size; + + // Try to allocate the memory. + ACE_NEW_RETURN (this->handlers_, Event_Tuple[size], -1); + + // Try to increase the number of handles if is greater than + // the current limit. + return ACE::set_handle_limit (size); +} + +int +ACE_Dev_Poll_Reactor::Handler_Repository::unbind_all (void) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::Handler_Repository::unbind_all"); + + // Unbind all of the event handlers; similar to remove_handler() on all. + for (int handle = 0; + handle < this->max_size_; + ++handle) + { + Event_Tuple *entry = this->find (handle); + if (entry == 0) + continue; + + // Check for ref counting now - handle_close () may delete eh. + bool const requires_reference_counting = + entry->event_handler->reference_counting_policy ().value () == + ACE_Event_Handler::Reference_Counting_Policy::ENABLED; + + (void) entry->event_handler->handle_close (handle, entry->mask); + this->unbind (handle, requires_reference_counting); + } + + return 0; +} + +int +ACE_Dev_Poll_Reactor::Handler_Repository::close (void) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::Handler_Repository::close"); + + if (this->handlers_ != 0) + { + this->unbind_all (); + + delete [] this->handlers_; + this->handlers_ = 0; + } + + return 0; +} + +ACE_Dev_Poll_Reactor::Event_Tuple * +ACE_Dev_Poll_Reactor::Handler_Repository::find (ACE_HANDLE handle) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::Handler_Repository::find"); + + Event_Tuple *tuple = 0; + + // Only bother to search for the if it's in range. + if (!this->handle_in_range (handle)) + { + errno = ERANGE; + return 0; + } + + tuple = &(this->handlers_[handle]); + if (tuple->event_handler == 0) + { + errno = ENOENT; + tuple = 0; + } + + return tuple; +} + +int +ACE_Dev_Poll_Reactor::Handler_Repository::bind ( + ACE_HANDLE handle, + ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::Handler_Repository::bind"); + + if (event_handler == 0) + return -1; + + if (handle == ACE_INVALID_HANDLE) + handle = event_handler->get_handle (); + + if (this->invalid_handle (handle)) + return -1; + + this->handlers_[handle].event_handler = event_handler; + this->handlers_[handle].mask = mask; + event_handler->add_reference (); + ++this->size_; + + return 0; +} + +int +ACE_Dev_Poll_Reactor::Handler_Repository::unbind (ACE_HANDLE handle, + bool decr_refcnt) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::Handler_Repository::unbind"); + + Event_Tuple *entry = this->find (handle); + if (entry == 0) + return -1; + + if (decr_refcnt) + entry->event_handler->remove_reference (); + + entry->event_handler = 0; + entry->mask = ACE_Event_Handler::NULL_MASK; + entry->suspended = false; + entry->controlled = false; + --this->size_; + return 0; +} + +// ----------------------------------------------------------------- + +ACE_Dev_Poll_Reactor::ACE_Dev_Poll_Reactor (ACE_Sig_Handler *sh, + ACE_Timer_Queue *tq, + int disable_notify_pipe, + ACE_Reactor_Notify *notify, + int mask_signals, + int s_queue) + : initialized_ (false) + , poll_fd_ (ACE_INVALID_HANDLE) + // , ready_set_ () +#if defined (ACE_HAS_EVENT_POLL) + , epoll_wait_in_progress_ (false) +#endif /* ACE_HAS_EVENT_POLL */ +#if defined (ACE_HAS_DEV_POLL) + , dp_fds_ (0) + , start_pfds_ (0) + , end_pfds_ (0) +#endif /* ACE_HAS_DEV_POLL */ + , deactivated_ (0) + , token_ (*this, s_queue) + , lock_adapter_ (token_) + , timer_queue_ (0) + , delete_timer_queue_ (false) + , signal_handler_ (0) + , delete_signal_handler_ (false) + , notify_handler_ (0) + , delete_notify_handler_ (false) + , mask_signals_ (mask_signals) + , restart_ (0) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::ACE_Dev_Poll_Reactor"); + + if (this->open (ACE::max_handles (), + 0, + sh, + tq, + disable_notify_pipe, + notify) == -1) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_Dev_Poll_Reactor::open ") + ACE_TEXT ("failed inside ") + ACE_TEXT ("ACE_Dev_Poll_Reactor::CTOR"))); +} + +ACE_Dev_Poll_Reactor::ACE_Dev_Poll_Reactor (size_t size, + bool rs, + ACE_Sig_Handler *sh, + ACE_Timer_Queue *tq, + int disable_notify_pipe, + ACE_Reactor_Notify *notify, + int mask_signals, + int s_queue) + : initialized_ (false) + , poll_fd_ (ACE_INVALID_HANDLE) + // , ready_set_ () +#if defined (ACE_HAS_DEV_POLL) + , dp_fds_ (0) + , start_pfds_ (0) + , end_pfds_ (0) +#endif /* ACE_HAS_DEV_POLL */ + , deactivated_ (0) + , token_ (*this, s_queue) + , lock_adapter_ (token_) + , timer_queue_ (0) + , delete_timer_queue_ (false) + , signal_handler_ (0) + , delete_signal_handler_ (false) + , notify_handler_ (0) + , delete_notify_handler_ (false) + , mask_signals_ (mask_signals) + , restart_ (0) +{ + if (this->open (size, + rs, + sh, + tq, + disable_notify_pipe, + notify) == -1) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_Dev_Poll_Reactor::open ") + ACE_TEXT ("failed inside ACE_Dev_Poll_Reactor::CTOR"))); +} + +ACE_Dev_Poll_Reactor::~ACE_Dev_Poll_Reactor (void) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::~ACE_Dev_Poll_Reactor"); + + (void) this->close (); +} + +int +ACE_Dev_Poll_Reactor::open (size_t size, + bool restart, + ACE_Sig_Handler *sh, + ACE_Timer_Queue *tq, + int disable_notify_pipe, + ACE_Reactor_Notify *notify) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::open"); + + ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); + + // Can't initialize ourselves more than once. + if (this->initialized_) + return -1; + +#ifdef ACE_HAS_EVENT_POLL + ACE_OS::memset (&this->event_, 0, sizeof (this->event_)); + this->event_.data.fd = ACE_INVALID_HANDLE; +#endif /* ACE_HAS_EVENT_POLL */ + + this->restart_ = restart; + this->signal_handler_ = sh; + this->timer_queue_ = tq; + this->notify_handler_ = notify; + + int result = 0; + + // Allows the signal handler to be overridden. + if (this->signal_handler_ == 0) + { + ACE_NEW_RETURN (this->signal_handler_, + ACE_Sig_Handler, + -1); + + if (this->signal_handler_ == 0) + result = -1; + else + this->delete_signal_handler_ = true; + } + + // Allows the timer queue to be overridden. + if (result != -1 && this->timer_queue_ == 0) + { + ACE_NEW_RETURN (this->timer_queue_, + ACE_Timer_Heap, + -1); + + if (this->timer_queue_ == 0) + result = -1; + else + this->delete_timer_queue_ = true; + } + + // Allows the Notify_Handler to be overridden. + if (result != -1 && this->notify_handler_ == 0) + { + ACE_NEW_RETURN (this->notify_handler_, + ACE_Dev_Poll_Reactor_Notify, + -1); + + if (this->notify_handler_ == 0) + result = -1; + else + this->delete_notify_handler_ = true; + } + +#if defined (ACE_HAS_EVENT_POLL) + + // Initialize epoll: + this->poll_fd_ = ::epoll_create (size); + if (this->poll_fd_ == -1) + result = -1; + +#else + + // Allocate the array before opening the device to avoid a potential + // resource leak if allocation fails. + ACE_NEW_RETURN (this->dp_fds_, + pollfd[size], + -1); + + // Open the `/dev/poll' character device. + this->poll_fd_ = ACE_OS::open ("/dev/poll", O_RDWR); + if (this->poll_fd_ == ACE_INVALID_HANDLE) + result = -1; + +#endif /* ACE_HAS_EVENT_POLL */ + + if (result != -1 && this->handler_rep_.open (size) == -1) + result = -1; + + // Registration of the notification handler must be done after the + // /dev/poll device has been fully initialized. + else if (this->notify_handler_->open (this, + 0, + disable_notify_pipe) == -1 + || (disable_notify_pipe == 0 + && this->register_handler_i ( + this->notify_handler_->notify_handle (), + this->notify_handler_, + ACE_Event_Handler::READ_MASK) == -1)) + result = -1; + + if (result != -1) + // We're all set to go. + this->initialized_ = true; + else + // This will close down all the allocated resources properly. + (void) this->close (); + + return result; +} + +int +ACE_Dev_Poll_Reactor::current_info (ACE_HANDLE, size_t & /* size */) +{ + ACE_NOTSUP_RETURN (-1); +} + + +int +ACE_Dev_Poll_Reactor::set_sig_handler (ACE_Sig_Handler *signal_handler) +{ + if (this->delete_signal_handler_) + delete this->signal_handler_; + + this->signal_handler_ = signal_handler; + this->delete_signal_handler_ = false; + + return 0; +} + +int +ACE_Dev_Poll_Reactor::timer_queue (ACE_Timer_Queue *tq) +{ + if (this->delete_timer_queue_) + delete this->timer_queue_; + + this->timer_queue_ = tq; + this->delete_timer_queue_ = false; + + return 0; + +} + +ACE_Timer_Queue * +ACE_Dev_Poll_Reactor::timer_queue (void) const +{ + return this->timer_queue_; +} + +int +ACE_Dev_Poll_Reactor::close (void) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::close"); + + ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); + + int result = 0; + + if (this->poll_fd_ != ACE_INVALID_HANDLE) + { + result = ACE_OS::close (this->poll_fd_); + } + +#if defined (ACE_HAS_EVENT_POLL) + + ACE_OS::memset (&this->event_, 0, sizeof (this->event_)); + this->event_.data.fd = ACE_INVALID_HANDLE; + +#else + + delete [] this->dp_fds_; + this->dp_fds_ = 0; + this->start_pfds_ = 0; + this->end_pfds_ = 0; + +#endif /* ACE_HAS_EVENT_POLL */ + + if (this->delete_signal_handler_) + { + delete this->signal_handler_; + this->signal_handler_ = 0; + this->delete_signal_handler_ = false; + } + + (void) this->handler_rep_.close (); + + if (this->delete_timer_queue_) + { + delete this->timer_queue_; + this->timer_queue_ = 0; + this->delete_timer_queue_ = false; + } + + if (this->notify_handler_ != 0) + this->notify_handler_->close (); + + if (this->delete_notify_handler_) + { + delete this->notify_handler_; + this->notify_handler_ = 0; + this->delete_notify_handler_ = false; + } + + this->poll_fd_ = ACE_INVALID_HANDLE; + + this->initialized_ = false; + + return result; +} + +int +ACE_Dev_Poll_Reactor::work_pending (const ACE_Time_Value & max_wait_time) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::work_pending"); + + // Stash the current time + // + // The destructor of this object will automatically compute how much + // time elapsed since this method was called. + ACE_Time_Value mwt (max_wait_time); + ACE_MT (ACE_Countdown_Time countdown (&mwt)); + + Token_Guard guard (this->token_); + int const result = guard.acquire_quietly (&mwt); + + // If the guard is NOT the owner just return the retval + if (!guard.is_owner ()) + return result; + + // Update the countdown to reflect time waiting for the mutex. + ACE_MT (countdown.update ()); + + return this->work_pending_i (&mwt); +} + +int +ACE_Dev_Poll_Reactor::work_pending_i (ACE_Time_Value * max_wait_time) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::work_pending_i"); + + if (this->deactivated_) + return 0; + +#if defined (ACE_HAS_EVENT_POLL) + if (this->event_.data.fd != ACE_INVALID_HANDLE) +#else + if (this->start_pfds_ != this->end_pfds_) +#endif /* ACE_HAS_EVENT_POLL */ + return 1; // We still have work_pending (). Do not poll for + // additional events. + + ACE_Time_Value timer_buf (0); + ACE_Time_Value *this_timeout = + this->timer_queue_->calculate_timeout (max_wait_time, &timer_buf); + + // Check if we have timers to fire. + int const timers_pending = + ((this_timeout != 0 && max_wait_time == 0) + || (this_timeout != 0 && max_wait_time != 0 + && *this_timeout != *max_wait_time) ? 1 : 0); + + long const timeout = + (this_timeout == 0 + ? -1 /* Infinity */ + : static_cast (this_timeout->msec ())); + +#if defined (ACE_HAS_EVENT_POLL) + + // See if there are handlers that have to be resumed before waiting. + { + ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, grd, this->to_be_resumed_lock_, -1); + this->epoll_wait_in_progress_ = true; + for (Resume_Map::iterator i = this->to_be_resumed_.begin (); + i != this->to_be_resumed_.end (); + ++i) + { + // Make sure that 1) the handle is still registered, + // 2) the registered handler is the one we're waiting to resume. + Event_Tuple *info = this->handler_rep_.find (i->first); + if (info != 0 && info->event_handler == i->second) + { + this->resume_handler_i (i->first); + } + } + this->to_be_resumed_.clear (); + } + + // Wait for an event. + int const nfds = ::epoll_wait (this->poll_fd_, + &this->event_, + 1, + static_cast (timeout)); + // Count on this being an atomic update; at worst, we may get an + // extraneous notify() from dispatch_io_event. + this->epoll_wait_in_progress_ = false; + +#else + + struct dvpoll dvp; + + dvp.dp_fds = this->dp_fds_; + dvp.dp_nfds = this->handler_rep_.size (); + dvp.dp_timeout = timeout; // Milliseconds + + // Poll for events + int const nfds = ACE_OS::ioctl (this->poll_fd_, DP_POLL, &dvp); + + // Retrieve the results from the pollfd array. + this->start_pfds_ = dvp.dp_fds; + + // If nfds == 0 then end_pfds_ == start_pfds_ meaning that there is + // no work pending. If nfds > 0 then there is work pending. + // Otherwise an error occurred. + if (nfds > -1) + this->end_pfds_ = this->start_pfds_ + nfds; +#endif /* ACE_HAS_EVENT_POLL */ + + // If timers are pending, override any timeout from the poll. + return (nfds == 0 && timers_pending != 0 ? 1 : nfds); +} + + +int +ACE_Dev_Poll_Reactor::handle_events (ACE_Time_Value *max_wait_time) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::handle_events"); + + // Stash the current time + // + // The destructor of this object will automatically compute how much + // time elapsed since this method was called. + ACE_MT (ACE_Countdown_Time countdown (max_wait_time)); + + Token_Guard guard (this->token_); + int const result = guard.acquire_quietly (max_wait_time); + + // If the guard is NOT the owner just return the retval + if (!guard.is_owner ()) + return result; + + if (this->deactivated_) + return -1; + + // Update the countdown to reflect time waiting for the mutex. + ACE_MT (countdown.update ()); + + return this->handle_events_i (max_wait_time, guard); +} + +int +ACE_Dev_Poll_Reactor::handle_events_i (ACE_Time_Value *max_wait_time, + Token_Guard &guard) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::handle_events_i"); + + int result = 0; + + // Poll for events + // + // If the underlying event wait call was interrupted via the interrupt + // signal (i.e. returned -1 with errno == EINTR) then the loop will + // be restarted if so desired. + do + { + result = this->work_pending_i (max_wait_time); + if (result == -1 && (this->restart_ == 0 || errno != EINTR)) + ACE_ERROR ((LM_ERROR, ACE_TEXT("%t: %p\n"), ACE_TEXT("work_pending_i"))); + } + while (result == -1 && this->restart_ != 0 && errno == EINTR); + + if (result == 0 || (result == -1 && errno == ETIME)) + return 0; + else if (result == -1) + { + if (errno != EINTR) + return -1; + + // Bail out -- we got here since the poll was interrupted. + // If it was due to a signal registered through our ACE_Sig_Handler, + // then it was dispatched, so we count it in the number of events + // handled rather than cause an error return. + if (ACE_Sig_Handler::sig_pending () != 0) + { + ACE_Sig_Handler::sig_pending (0); + return 1; + } + return -1; + } + + // Dispatch an event. + return this->dispatch (guard); +} + +// Dispatch an event. On entry, the token is held by the caller. If an +// event is found to dispatch, the token is released before dispatching it. +int +ACE_Dev_Poll_Reactor::dispatch (Token_Guard &guard) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::dispatch"); + + // Perform the Template Method for dispatching the first located event. + // We dispatch only one to effectively dispatch events concurrently. + // As soon as an event is located, the token is released, allowing the + // next waiter to begin getting an event while we dispatch one here. + int result = 0; + + // Handle timers early since they may have higher latency + // constraints than I/O handlers. Ideally, the order of + // dispatching should be a strategy... + if ((result = this->dispatch_timer_handler (guard)) != 0) + return result; + + // If no timer dispatched, check for an I/O event. + result = this->dispatch_io_event (guard); + + return result; +} + +int +ACE_Dev_Poll_Reactor::dispatch_timer_handler (Token_Guard &guard) +{ + if (this->timer_queue_->is_empty ()) + return 0; // Empty timer queue so cannot have any expired timers. + + // Get the current time + ACE_Time_Value cur_time (this->timer_queue_->gettimeofday () + + this->timer_queue_->timer_skew ()); + + // Look for a node in the timer queue whose timer <= the present + // time. + ACE_Timer_Node_Dispatch_Info info; + if (this->timer_queue_->dispatch_info (cur_time, info)) + { + const void *upcall_act = 0; + + // Preinvoke (handles refcount if needed, etc.) + this->timer_queue_->preinvoke (info, cur_time, upcall_act); + + // Release the token before expiration upcall. + guard.release_token (); + + // call the functor + this->timer_queue_->upcall (info, cur_time); + + // Postinvoke (undo refcount if needed, etc.) + this->timer_queue_->postinvoke (info, cur_time, upcall_act); + + // We have dispatched a timer + return 1; + } + + return 0; +} + +#if 0 +int +ACE_Dev_Poll_Reactor::dispatch_notification_handlers ( + ACE_Select_Reactor_Handle_Set &dispatch_set, + int &number_of_active_handles, + int &number_of_handlers_dispatched) +{ + // Check to see if the ACE_HANDLE associated with the + // Dev_Poll_Reactor's notify hook is enabled. If so, it means that + // one or more other threads are trying to update the + // ACE_Dev_Poll_Reactor's internal tables or the notify pipe is + // enabled. We'll handle all these threads and notifications, and + // then break out to continue the event loop. + + const int n = + this->notify_handler_->dispatch_notifications (number_of_active_handles, + dispatch_set.rd_mask_); + + if (n == -1) + return -1; + else + number_of_handlers_dispatched += n; + + return /* this->state_changed_ ? -1 : */ 0; +} +#endif /* 0 */ + +int +ACE_Dev_Poll_Reactor::dispatch_io_event (Token_Guard &guard) +{ + + // Dispatch a ready event. + + // Define bits to check for while dispatching. +#if defined (ACE_HAS_EVENT_POLL) + const __uint32_t out_event = EPOLLOUT; + const __uint32_t exc_event = EPOLLPRI; + const __uint32_t in_event = EPOLLIN; + const __uint32_t err_event = EPOLLHUP | EPOLLERR; +#else + const short out_event = POLLOUT; + const short exc_event = POLLPRI; + const short in_event = POLLIN; + const short err_event = 0; // No known bits for this +#endif /* ACE_HAS_EVENT_POLL */ + +#if defined (ACE_HAS_EVENT_POLL) + // epoll_wait() pulls one event which is stored in event_. If the handle + // is invalid, there's no event there. Else process it. In any event, we + // have the event, so clear event_ for the next thread. + const ACE_HANDLE handle = this->event_.data.fd; + __uint32_t revents = this->event_.events; + this->event_.data.fd = ACE_INVALID_HANDLE; + this->event_.events = 0; + if (handle != ACE_INVALID_HANDLE) + +#else + // Since the underlying event demultiplexing mechansim (`/dev/poll' + // or '/dev/epoll') is stateful, and since only one result buffer is + // used, all pending events (i.e. those retrieved from a previous + // poll) must be dispatched before any additional event can be + // polled. As such, the Dev_Poll_Reactor keeps track of the + // progress of events that have been dispatched. + + // Select the first available handle with event (s) pending. Check for + // event type in defined order of dispatch: output, exception, input. + // When an event is located, clear its bit in the dispatch set. If there + // are no more events for the handle, also increment the pfds pointer + // to move to the next handle ready. + // + // Notice that pfds only contains file descriptors that have + // received events. + struct pollfd *& pfds = this->start_pfds_; + const ACE_HANDLE handle = pfds->fd; + short &revents = pfds->revents; + if (pfds < this->end_pfds_) +#endif /* ACE_HAS_EVENT_POLL */ + + { + /* When using sys_epoll, we can attach arbitrary user + data to the descriptor, so it can be delivered when + activity is detected. Perhaps we should store event + handler together with descriptor, instead of looking + it up in a repository ? Could it boost performance ? + */ + Event_Tuple *info = this->handler_rep_.find (handle); + if (info == 0) // No registered handler any longer + { +#ifdef ACE_HAS_EVENT_POLL + this->event_.data.fd = ACE_INVALID_HANDLE; // Dump the event +#endif /* ACE_HAS_EVENT_POLL */ + return 0; + } + + // Figure out what to do first in order to make it easier to manage + // the bit twiddling and possible pfds increment before releasing + // the token for dispatch. + // Note that if there's an error (such as the handle was closed + // without being removed from the event set) the EPOLLHUP and/or + // EPOLLERR bits will be set in revents. + ACE_Reactor_Mask disp_mask = 0; + ACE_Event_Handler *eh = info->event_handler; + int (ACE_Event_Handler::*callback)(ACE_HANDLE) = 0; + if (ACE_BIT_ENABLED (revents, out_event)) + { + disp_mask = ACE_Event_Handler::WRITE_MASK; + callback = &ACE_Event_Handler::handle_output; + ACE_CLR_BITS (revents, out_event); + } + else if (ACE_BIT_ENABLED (revents, exc_event)) + { + disp_mask = ACE_Event_Handler::EXCEPT_MASK; + callback = &ACE_Event_Handler::handle_exception; + ACE_CLR_BITS (revents, exc_event); + } + else if (ACE_BIT_ENABLED (revents, in_event)) + { + disp_mask = ACE_Event_Handler::READ_MASK; + callback = &ACE_Event_Handler::handle_input; + ACE_CLR_BITS (revents, in_event); + } + else if (ACE_BIT_ENABLED (revents, err_event)) + { + this->remove_handler_i (handle, + ACE_Event_Handler::ALL_EVENTS_MASK, + info->event_handler); +#ifdef ACE_HAS_DEV_POLL + ++pfds; +#endif /* ACE_HAS_DEV_POLL */ + return 1; + } + else + { + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("(%t) dispatch_io h %d unknown events 0x%x\n"), + handle, revents)); + } + +#ifdef ACE_HAS_DEV_POLL + // Increment the pointer to the next element before we + // release the token. Otherwise event handlers end up being + // dispatched multiple times for the same poll. + if (revents == 0) + ++pfds; +#else + // With epoll, events are registered with oneshot, so the handle is + // effectively suspended; future calls to epoll_wait() will select + // the next event, so they're not managed here. + // The hitch to this is that the notify handler is always registered + // WITHOUT oneshot and is never suspended/resumed. This avoids endless + // notify loops caused by the notify handler requiring a resumption + // which requires the token, which requires a notify, etc. described + // in Bugzilla 3714. So, never suspend the notify handler. + + bool reactor_resumes_eh = false; + if (eh != this->notify_handler_) + { + info->suspended = true; + + reactor_resumes_eh = + eh->resume_handler () == + ACE_Event_Handler::ACE_REACTOR_RESUMES_HANDLER; + } +#endif /* ACE_HAS_DEV_POLL */ + + int status = 0; // gets callback status, below. + { + // Modify the reference count in an exception-safe way. + // Note that eh could be the notify handler. It's not strictly + // necessary to manage its refcount, but since we don't enable + // the counting policy, it won't do much. Management of the + // notified handlers themselves is done in the notify handler. + ACE_Dev_Poll_Handler_Guard eh_guard (eh); + + // Release the reactor token before upcall. + guard.release_token (); + + // Dispatch the detected event; will do the repeated upcalls + // if callback returns > 0, unless it's the notify handler (which + // returns the number of notfies dispatched, not an indication of + // re-callback requested). If anything other than the notify, come + // back with either 0 or < 0. + status = this->upcall (eh, callback, handle); + + if (eh == this->notify_handler_) + return status; + + // If the callback returned 0, epoll-based needs to resume the + // suspended handler but dev/poll doesn't. + // The epoll case is optimized to not acquire the token in order + // to resume the handler; the handler is added to a list of those + // that need to be resumed and is handled by the next leader + // that does an epoll_wait(). + // In both epoll and dev/poll cases, if the callback returns <0, + // the token needs to be acquired and the handler checked and + // removed if it hasn't already been. + if (status == 0) + { +#ifdef ACE_HAS_EVENT_POLL + // epoll-based effectively suspends handlers around the upcall. + // If the handler must be resumed, add it to the list. + if (reactor_resumes_eh) + { + ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, + grd, + this->to_be_resumed_lock_, + -1); + bool map_was_empty = this->to_be_resumed_.empty(); + this->to_be_resumed_.insert + (Resume_Map::value_type (handle, eh)); + if (this->epoll_wait_in_progress_ && map_was_empty) + this->notify(); + } +#endif /* ACE_HAS_EVENT_POLL */ + return 1; + } + + // All state in the handler repository may have changed during the + // upcall while other threads had the token. Thus, reacquire the + // token and evaluate what's needed. If the upcalled handler is still + // the handler of record for handle, continue with checking whether + // or not to remove or resume the handler. + guard.acquire (); + info = this->handler_rep_.find (handle); + if (info != 0 && info->event_handler == eh) + { + if (status < 0) + this->remove_handler_i (handle, disp_mask); + } + } + // Scope close handles eh ref count decrement, if needed. + + return 1; + } + + return 0; +} + +int +ACE_Dev_Poll_Reactor::alertable_handle_events (ACE_Time_Value *max_wait_time) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::alertable_handle_events"); + + return this->handle_events (max_wait_time); +} + +int +ACE_Dev_Poll_Reactor::handle_events (ACE_Time_Value &max_wait_time) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::handle_events"); + + return this->handle_events (&max_wait_time); +} + +int +ACE_Dev_Poll_Reactor::alertable_handle_events (ACE_Time_Value &max_wait_time) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::alertable_handle_events"); + + return this->handle_events (max_wait_time); +} + +int +ACE_Dev_Poll_Reactor::deactivated (void) +{ + return this->deactivated_; +} + +void +ACE_Dev_Poll_Reactor::deactivate (int do_stop) +{ + this->deactivated_ = do_stop; + this->wakeup_all_threads (); +} + +int +ACE_Dev_Poll_Reactor::register_handler (ACE_Event_Handler *handler, + ACE_Reactor_Mask mask) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::register_handler"); + + ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); + + return this->register_handler_i (handler->get_handle (), + handler, + mask); +} + +int +ACE_Dev_Poll_Reactor::register_handler (ACE_HANDLE handle, + ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::register_handler"); + + ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); + + return this->register_handler_i (handle, + event_handler, + mask); +} + +int +ACE_Dev_Poll_Reactor::register_handler_i (ACE_HANDLE handle, + ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::register_handler_i"); + + if (handle == ACE_INVALID_HANDLE + || mask == ACE_Event_Handler::NULL_MASK) + { + errno = EINVAL; + return -1; + } + + if (this->handler_rep_.find (handle) == 0) + { + // Handler not present in the repository. Bind it. + if (this->handler_rep_.bind (handle, event_handler, mask) != 0) + return -1; + +#if defined (ACE_HAS_EVENT_POLL) + + Event_Tuple *info = this->handler_rep_.find (handle); + + struct epoll_event epev; + ACE_OS::memset (&epev, 0, sizeof (epev)); + static const int op = EPOLL_CTL_ADD; + + epev.data.fd = handle; + epev.events = this->reactor_mask_to_poll_event (mask); + // All but the notify handler get registered with oneshot to facilitate + // auto suspend before the upcall. See dispatch_io_event for more + // information. + if (event_handler != this->notify_handler_) + epev.events |= EPOLLONESHOT; + + if (::epoll_ctl (this->poll_fd_, op, handle, &epev) == -1) + { + ACE_ERROR ((LM_ERROR, ACE_TEXT("%p\n"), ACE_TEXT("epoll_ctl"))); + (void) this->handler_rep_.unbind (handle); + return -1; + } + info->controlled = true; + +#endif /* ACE_HAS_EVENT_POLL */ + } + else + { + // Handler is already present in the repository, so register it + // again, possibly for different event. Add new mask to the + // current one. + if (this->mask_ops_i (handle, mask, ACE_Reactor::ADD_MASK) == -1) + ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT("%p\n"), ACE_TEXT("mask_ops_i")), + -1); + } + +#ifdef ACE_HAS_DEV_POLL + + struct pollfd pfd; + + pfd.fd = handle; + pfd.events = this->reactor_mask_to_poll_event (mask); + pfd.revents = 0; + + // Add file descriptor to the "interest set." + if (ACE_OS::write (this->poll_fd_, &pfd, sizeof (pfd)) != sizeof (pfd)) + { + (void) this->handler_rep_.unbind (handle); + return -1; + } +#endif /*ACE_HAS_DEV_POLL*/ + + // Note the fact that we've changed the state of the wait_set_, + // which is used by the dispatching loop to determine whether it can + // keep going or if it needs to reconsult select (). + // this->state_changed_ = 1; + + return 0; +} + +int +ACE_Dev_Poll_Reactor::register_handler ( + ACE_HANDLE /* event_handle */, + ACE_HANDLE /* io_handle */, + ACE_Event_Handler * /* event_handler */, + ACE_Reactor_Mask /* mask */) +{ + ACE_NOTSUP_RETURN (-1); +} + +int +ACE_Dev_Poll_Reactor::register_handler (const ACE_Handle_Set &handle_set, + ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::register_handler"); + + ACE_Handle_Set_Iterator handle_iter (handle_set); + + ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); + + // @@ It might be more efficient to construct a pollfd array and + // pass it to the write () call in register_handler_i () only once, + // instead of calling write () (a system call) once for each file + // descriptor. + + for (ACE_HANDLE h = handle_iter (); + h != ACE_INVALID_HANDLE; + h = handle_iter ()) + if (this->register_handler_i (h, event_handler, mask) == -1) + return -1; + + return 0; +} + +int +ACE_Dev_Poll_Reactor::register_handler (int signum, + ACE_Event_Handler *new_sh, + ACE_Sig_Action *new_disp, + ACE_Event_Handler **old_sh, + ACE_Sig_Action *old_disp) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::register_handler"); + + return this->signal_handler_->register_handler (signum, + new_sh, + new_disp, + old_sh, + old_disp); +} + +int +ACE_Dev_Poll_Reactor::register_handler (const ACE_Sig_Set &sigset, + ACE_Event_Handler *new_sh, + ACE_Sig_Action *new_disp) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::register_handler"); + + int result = 0; + +#if (ACE_NSIG > 0) + + for (int s = 1; s < ACE_NSIG; ++s) + if ((sigset.is_member (s) == 1) + && this->signal_handler_->register_handler (s, + new_sh, + new_disp) == -1) + result = -1; + +#else /* ACE_NSIG <= 0 */ + + ACE_UNUSED_ARG (sigset); + ACE_UNUSED_ARG (new_sh); + ACE_UNUSED_ARG (new_disp); + +#endif /* ACE_NSIG <= 0 */ + + return result; +} + +int +ACE_Dev_Poll_Reactor::remove_handler (ACE_Event_Handler *handler, + ACE_Reactor_Mask mask) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::remove_handler"); + + ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); + + return this->remove_handler_i (handler->get_handle (), mask); +} + +int +ACE_Dev_Poll_Reactor::remove_handler (ACE_HANDLE handle, + ACE_Reactor_Mask mask) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::remove_handler"); + + ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); + + return this->remove_handler_i (handle, mask); +} + +int +ACE_Dev_Poll_Reactor::remove_handler_i (ACE_HANDLE handle, + ACE_Reactor_Mask mask, + ACE_Event_Handler *eh) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::remove_handler_i"); + + // If registered event handler not the same as eh, don't mess with + // the mask, but do the proper callback and refcount when needed. + bool handle_reg_changed = true; + Event_Tuple *info = this->handler_rep_.find (handle); + if (info == 0 && eh == 0) // Nothing to work with + return -1; + if (info != 0 && (eh == 0 || info->event_handler == eh)) + { + if (this->mask_ops_i (handle, mask, ACE_Reactor::CLR_MASK) == -1) + return -1; + handle_reg_changed = false; + eh = info->event_handler; + } + + // Check for ref counting now - handle_close () may delete eh. + bool const requires_reference_counting = + eh->reference_counting_policy ().value () == + ACE_Event_Handler::Reference_Counting_Policy::ENABLED; + + if (ACE_BIT_DISABLED (mask, ACE_Event_Handler::DONT_CALL)) + (void) eh->handle_close (handle, mask); + + // If there are no longer any outstanding events on the given handle + // then remove it from the handler repository. + if (!handle_reg_changed && info->mask == ACE_Event_Handler::NULL_MASK) + this->handler_rep_.unbind (handle, requires_reference_counting); + + return 0; +} + +int +ACE_Dev_Poll_Reactor::remove_handler (const ACE_Handle_Set &handle_set, + ACE_Reactor_Mask mask) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::remove_handler"); + + ACE_Handle_Set_Iterator handle_iter (handle_set); + + ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); + + // @@ It might be more efficient to construct a pollfd array and + // pass it to the write () call in register_handler_i () only once, + // instead of calling write () (a system call) once for each file + // descriptor. + + for (ACE_HANDLE h = handle_iter (); + h != ACE_INVALID_HANDLE; + h = handle_iter ()) + if (this->remove_handler_i (h, mask) == -1) + return -1; + + return 0; +} + +int +ACE_Dev_Poll_Reactor::remove_handler (int signum, + ACE_Sig_Action *new_disp, + ACE_Sig_Action *old_disp, + int sigkey) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::remove_handler"); + + return this->signal_handler_->remove_handler (signum, + new_disp, + old_disp, + sigkey); +} + +int +ACE_Dev_Poll_Reactor::remove_handler (const ACE_Sig_Set &sigset) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::remove_handler"); + + int result = 0; + +#if (ACE_NSIG > 0) + + for (int s = 1; s < ACE_NSIG; ++s) + if ((sigset.is_member (s) == 1) + && this->signal_handler_->remove_handler (s) == -1) + result = -1; + +#else /* ACE_NSIG <= 0 */ + + ACE_UNUSED_ARG (sigset); + +#endif /* ACE_NSIG <= 0 */ + + return result; +} + +int +ACE_Dev_Poll_Reactor::suspend_handler (ACE_Event_Handler *event_handler) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::suspend_handler"); + + if (event_handler == 0) + { + errno = EINVAL; + return -1; + } + + ACE_HANDLE handle = event_handler->get_handle (); + + ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); + + return this->suspend_handler_i (handle); +} + +int +ACE_Dev_Poll_Reactor::suspend_handler (ACE_HANDLE handle) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::suspend_handler"); + + ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); + + return this->suspend_handler_i (handle); +} + +int +ACE_Dev_Poll_Reactor::suspend_handler (const ACE_Handle_Set &handles) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::suspend_handler"); + + ACE_Handle_Set_Iterator handle_iter (handles); + ACE_HANDLE h; + + ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); + + while ((h = handle_iter ()) != ACE_INVALID_HANDLE) + if (this->suspend_handler_i (h) == -1) + return -1; + + return 0; +} + +int +ACE_Dev_Poll_Reactor::suspend_handlers (void) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::suspend_handlers"); + + ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); + + size_t const len = this->handler_rep_.max_size (); + + for (size_t i = 0; i < len; ++i) + { + Event_Tuple *info = this->handler_rep_.find (i); + if (info != 0 && !info->suspended && this->suspend_handler_i (i) != 0) + return -1; + } + return 0; +} + +int +ACE_Dev_Poll_Reactor::suspend_handler_i (ACE_HANDLE handle) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::suspend_handler_i"); + + Event_Tuple *info = this->handler_rep_.find (handle); + if (info == 0) + return -1; + + if (info->suspended) + return 0; // Already suspended. @@ Should this be an error? + + // Remove the handle from the "interest set." + // + // Note that the associated event handler is still in the handler + // repository, but no events will be polled on the given handle thus + // no event will be dispatched to the event handler. + +#if defined (ACE_HAS_EVENT_POLL) + + struct epoll_event epev; + ACE_OS::memset (&epev, 0, sizeof (epev)); + static const int op = EPOLL_CTL_DEL; + + epev.events = 0; + epev.data.fd = handle; + + if (::epoll_ctl (this->poll_fd_, op, handle, &epev) == -1) + return -1; + info->controlled = false; +#else + + struct pollfd pfd[1]; + + pfd[0].fd = handle; + pfd[0].events = POLLREMOVE; + pfd[0].revents = 0; + + if (ACE_OS::write (this->poll_fd_, pfd, sizeof (pfd)) != sizeof (pfd)) + return -1; + +#endif /* ACE_HAS_EVENT_POLL */ + + info->suspended = true; + + return 0; +} + +int +ACE_Dev_Poll_Reactor::resume_handler (ACE_Event_Handler *event_handler) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::resume_handler"); + + if (event_handler == 0) + { + errno = EINVAL; + return -1; + } + + ACE_HANDLE handle = event_handler->get_handle (); + + ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); + + return this->resume_handler_i (handle); +} + +int +ACE_Dev_Poll_Reactor::resume_handler (ACE_HANDLE handle) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::resume_handler"); + + ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); + + return this->resume_handler_i (handle); +} + +int +ACE_Dev_Poll_Reactor::resume_handler (const ACE_Handle_Set &handles) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::resume_handler"); + + ACE_Handle_Set_Iterator handle_iter (handles); + ACE_HANDLE h; + + ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); + + while ((h = handle_iter ()) != ACE_INVALID_HANDLE) + if (this->resume_handler_i (h) == -1) + return -1; + + return 0; +} + +int +ACE_Dev_Poll_Reactor::resume_handlers (void) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::resume_handlers"); + + ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); + + size_t const len = this->handler_rep_.max_size (); + + for (size_t i = 0; i < len; ++i) + { + Event_Tuple *info = this->handler_rep_.find (i); + if (info != 0 && info->suspended && this->resume_handler_i (i) != 0) + return -1; + } + + return 0; +} + +int +ACE_Dev_Poll_Reactor::resume_handler_i (ACE_HANDLE handle) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::resume_handler_i"); + + Event_Tuple *info = this->handler_rep_.find (handle); + if (info == 0) + return -1; + + if (!info->suspended) + return 0; + + ACE_Reactor_Mask mask = info->mask; + if (mask == ACE_Event_Handler::NULL_MASK) + { + info->suspended = false; + return 0; + } + + // Place the handle back in to the "interest set." + // + // Events for the given handle will once again be polled. + +#if defined (ACE_HAS_EVENT_POLL) + + struct epoll_event epev; + ACE_OS::memset (&epev, 0, sizeof (epev)); + int op = EPOLL_CTL_ADD; + if (info->controlled) + op = EPOLL_CTL_MOD; + epev.events = this->reactor_mask_to_poll_event (mask) | EPOLLONESHOT; + epev.data.fd = handle; + + if (::epoll_ctl (this->poll_fd_, op, handle, &epev) == -1) + return -1; + info->controlled = true; + +#else + + struct pollfd pfd[1]; + + pfd[0].fd = handle; + pfd[0].events = this->reactor_mask_to_poll_event (mask); + pfd[0].revents = 0; + + if (ACE_OS::write (this->poll_fd_, pfd, sizeof (pfd)) != sizeof (pfd)) + return -1; + +#endif /* ACE_HAS_EVENT_POLL */ + + info->suspended = false; + + return 0; +} + +int +ACE_Dev_Poll_Reactor::resumable_handler (void) +{ + // @@ Is this correct? + + return 0; +} + +bool +ACE_Dev_Poll_Reactor::uses_event_associations (void) +{ + // Since the Dev_Poll_Reactor does not do any event associations, + // this method always return false. + return false; +} + +long +ACE_Dev_Poll_Reactor::schedule_timer (ACE_Event_Handler *event_handler, + const void *arg, + const ACE_Time_Value &delay, + const ACE_Time_Value &interval) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::schedule_timer"); + + ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); + + if (0 != this->timer_queue_) + return this->timer_queue_->schedule + (event_handler, + arg, + this->timer_queue_->gettimeofday () + delay, + interval); + + errno = ESHUTDOWN; + return -1; +} + +int +ACE_Dev_Poll_Reactor::reset_timer_interval (long timer_id, + const ACE_Time_Value &interval) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::reset_timer_interval"); + + ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); + + if (0 != this->timer_queue_) + return this->timer_queue_->reset_interval (timer_id, interval); + + errno = ESHUTDOWN; + return -1; +} + +int +ACE_Dev_Poll_Reactor::cancel_timer (ACE_Event_Handler *event_handler, + int dont_call_handle_close) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::cancel_timer"); + + ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); + + return (this->timer_queue_ == 0 + ? 0 + : this->timer_queue_->cancel (event_handler, + dont_call_handle_close)); +} + +int +ACE_Dev_Poll_Reactor::cancel_timer (long timer_id, + const void **arg, + int dont_call_handle_close) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::cancel_timer"); + + ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); + + return (this->timer_queue_ == 0 + ? 0 + : this->timer_queue_->cancel (timer_id, + arg, + dont_call_handle_close)); +} + +int +ACE_Dev_Poll_Reactor::schedule_wakeup (ACE_Event_Handler *eh, + ACE_Reactor_Mask mask) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::schedule_wakeup"); + + return this->mask_ops (eh->get_handle (), mask, ACE_Reactor::ADD_MASK); +} + +int +ACE_Dev_Poll_Reactor::schedule_wakeup (ACE_HANDLE handle, + ACE_Reactor_Mask mask) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::schedule_wakeup"); + + return this->mask_ops (handle, mask, ACE_Reactor::ADD_MASK); +} + +int +ACE_Dev_Poll_Reactor::cancel_wakeup (ACE_Event_Handler *eh, + ACE_Reactor_Mask mask) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::cancel_wakeup"); + + return this->mask_ops (eh->get_handle (), mask, ACE_Reactor::CLR_MASK); +} + +int +ACE_Dev_Poll_Reactor::cancel_wakeup (ACE_HANDLE handle, + ACE_Reactor_Mask mask) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::cancel_wakeup"); + + return this->mask_ops (handle, mask, ACE_Reactor::CLR_MASK); +} + +int +ACE_Dev_Poll_Reactor::notify (ACE_Event_Handler *eh, + ACE_Reactor_Mask mask, + ACE_Time_Value *timeout) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::notify"); + + ssize_t n = 0; + + // Pass over both the Event_Handler *and* the mask to allow the + // caller to dictate which Event_Handler method the receiver + // invokes. Note that this call can timeout. + + n = this->notify_handler_->notify (eh, mask, timeout); + + return n == -1 ? -1 : 0; +} + +void +ACE_Dev_Poll_Reactor::max_notify_iterations (int iterations) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::max_notify_iterations"); + + ACE_MT (ACE_GUARD (ACE_Dev_Poll_Reactor_Token, mon, this->token_)); + + this->notify_handler_->max_notify_iterations (iterations); +} + +int +ACE_Dev_Poll_Reactor::max_notify_iterations (void) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::max_notify_iterations"); + + ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); + + return this->notify_handler_->max_notify_iterations (); +} + +int +ACE_Dev_Poll_Reactor::purge_pending_notifications (ACE_Event_Handler * eh, + ACE_Reactor_Mask mask) +{ + if (this->notify_handler_ == 0) + return 0; + + return this->notify_handler_->purge_pending_notifications (eh, mask); +} + +ACE_Event_Handler * +ACE_Dev_Poll_Reactor::find_handler (ACE_HANDLE handle) +{ + ACE_MT (ACE_READ_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, 0)); + + Event_Tuple *info = this->handler_rep_.find (handle); + if (info) + { + info->event_handler->add_reference (); + return info->event_handler; + } + else + { + return 0; + } +} + +int +ACE_Dev_Poll_Reactor::handler (ACE_HANDLE handle, + ACE_Reactor_Mask mask, + ACE_Event_Handler **event_handler) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::handler"); + + ACE_MT (ACE_READ_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); + + Event_Tuple *info = this->handler_rep_.find (handle); + + if (info != 0 + && ACE_BIT_CMP_MASK (info->mask, + mask, // Compare all bits in the mask + mask)) + { + if (event_handler != 0) + *event_handler = info->event_handler; + + return 0; + } + + return -1; +} + +int +ACE_Dev_Poll_Reactor::handler (int signum, + ACE_Event_Handler **eh) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::handler"); + + ACE_Event_Handler *handler = this->signal_handler_->handler (signum); + + if (handler == 0) + return -1; + else if (eh != 0) + *eh = handler; + + return 0; +} + +bool +ACE_Dev_Poll_Reactor::initialized (void) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::initialized"); + + ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, false)); + + return this->initialized_; +} + +size_t +ACE_Dev_Poll_Reactor::size (void) const +{ + return this->handler_rep_.size (); +} + +ACE_Lock & +ACE_Dev_Poll_Reactor::lock (void) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::lock"); + + return this->lock_adapter_; +} + +void +ACE_Dev_Poll_Reactor::wakeup_all_threads (void) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::wakeup_all_threads"); + + // Send a notification, but don't block if there's no one to receive + // it. + this->notify (0, + ACE_Event_Handler::NULL_MASK, + (ACE_Time_Value *) &ACE_Time_Value::zero); +} + +int +ACE_Dev_Poll_Reactor::owner (ACE_thread_t /* new_owner */, + ACE_thread_t * /* old_owner */) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::owner"); + + // There is no need to set the owner of the event loop. Multiple + // threads may invoke the event loop simulataneously. + + return 0; +} + +int +ACE_Dev_Poll_Reactor::owner (ACE_thread_t * /* owner */) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::owner"); + + // There is no need to set the owner of the event loop. Multiple + // threads may invoke the event loop simulataneously. + + return 0; +} + +bool +ACE_Dev_Poll_Reactor::restart (void) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::restart"); + + ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, false)); + + return this->restart_; +} + +bool +ACE_Dev_Poll_Reactor::restart (bool r) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::restart"); + + ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, false)); + + bool current_value = this->restart_; + this->restart_ = r; + return current_value; +} + +void +ACE_Dev_Poll_Reactor::requeue_position (int) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::requeue_position"); +} + +int +ACE_Dev_Poll_Reactor::requeue_position (void) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::requeue_position"); + + ACE_NOTSUP_RETURN (-1); +} + +int +ACE_Dev_Poll_Reactor::mask_ops (ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask, + int ops) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::mask_ops"); + + ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); + + return this->mask_ops_i (event_handler->get_handle (), mask, ops); +} + +int +ACE_Dev_Poll_Reactor::mask_ops (ACE_HANDLE handle, + ACE_Reactor_Mask mask, + int ops) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::mask_ops"); + + ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); + + return this->mask_ops_i (handle, mask, ops); +} + +int +ACE_Dev_Poll_Reactor::mask_ops_i (ACE_HANDLE handle, + ACE_Reactor_Mask mask, + int ops) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::mask_ops_i"); + + Event_Tuple *info = this->handler_rep_.find (handle); + if (info == 0) + return -1; + + // Block out all signals until method returns. + ACE_Sig_Guard sb; + + ACE_Reactor_Mask const old_mask = info->mask; + ACE_Reactor_Mask new_mask = old_mask; + + // Perform GET, CLR, SET, and ADD operations on the interest/wait + // set and the suspend set (if necessary). + // + // GET = 1, Retrieve current value + // SET = 2, Set value of bits to new mask (changes the entire mask) + // ADD = 3, Bitwise "or" the value into the mask (only changes + // enabled bits) + // CLR = 4 Bitwise "and" the negation of the value out of the mask + // (only changes enabled bits) + // + // Returns the original mask. + + switch (ops) + { + case ACE_Reactor::GET_MASK: + // The work for this operation is done in all cases at the + // begining of the function. + return old_mask; + + case ACE_Reactor::CLR_MASK: + ACE_CLR_BITS (new_mask, mask); + break; + + case ACE_Reactor::SET_MASK: + new_mask = mask; + break; + + case ACE_Reactor::ADD_MASK: + ACE_SET_BITS (new_mask, mask); + break; + + default: + return -1; + } + + /// Reset the mask for the given handle. + info->mask = new_mask; + + // Only attempt to alter events for the handle from the + // "interest set" if it hasn't been suspended. If it has been + // suspended, the revised mask will take affect when the + // handle is resumed. The exception is if all the mask bits are + // cleared, we can un-control the fd now. + if (!info->suspended || (info->controlled && new_mask == 0)) + { + + short const events = this->reactor_mask_to_poll_event (new_mask); + +#if defined (sun) + // Apparently events cannot be updated on-the-fly on Solaris so + // remove the existing events, and then add the new ones. + struct pollfd pfd[2]; + + pfd[0].fd = handle; + pfd[0].events = POLLREMOVE; + pfd[0].revents = 0; + pfd[1].fd = (events == POLLREMOVE ? ACE_INVALID_HANDLE : handle); + pfd[1].events = events; + pfd[1].revents = 0; + + // Change the events associated with the given file descriptor. + if (ACE_OS::write (this->poll_fd_, + pfd, + sizeof (pfd)) != sizeof (pfd)) + return -1; +#elif defined (ACE_HAS_EVENT_POLL) + + struct epoll_event epev; + ACE_OS::memset (&epev, 0, sizeof (epev)); + int op; + + // ACE_Event_Handler::NULL_MASK ??? + if (new_mask == 0) + { + op = EPOLL_CTL_DEL; + epev.events = 0; + } + else + { + op = EPOLL_CTL_MOD; + epev.events = events | EPOLLONESHOT; + } + + epev.data.fd = handle; + + if (::epoll_ctl (this->poll_fd_, op, handle, &epev) == -1) + { + // If a handle is closed, epoll removes it from the poll set + // automatically - we may not know about it yet. If that's the + // case, a mod operation will fail with ENOENT. Retry it as + // an add. + if (op == EPOLL_CTL_MOD && errno == ENOENT && + ::epoll_ctl (this->poll_fd_, EPOLL_CTL_ADD, handle, &epev) == -1) + return -1; + } + info->controlled = (op != EPOLL_CTL_DEL); +#else + pollfd pfd[1]; + + pfd[0].fd = handle; + pfd[0].events = events; + pfd[0].revents = 0; + + // Change the events associated with the given file descriptor. + if (ACE_OS::write (this->poll_fd_, + pfd, + sizeof (pfd)) != sizeof (pfd)) + return -1; +#endif /*ACE_HAS_EVENT_POLL */ + } + + return old_mask; +} + +int +ACE_Dev_Poll_Reactor::ready_ops (ACE_Event_Handler * /* event_handler */, + ACE_Reactor_Mask /* mask */, + int /* ops */) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::ready_ops"); + + // Since the Dev_Poll_Reactor uses the poll result buffer, the + // ready_set cannot be directly manipulated outside of the event + // loop. + ACE_NOTSUP_RETURN (-1); +} + +int +ACE_Dev_Poll_Reactor::ready_ops (ACE_HANDLE /* handle */, + ACE_Reactor_Mask /* mask */, + int /* ops */) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::ready_ops"); + + // Since the Dev_Poll_Reactor uses the poll result buffer, the + // ready_set cannot be directly manipulated outside of the event + // loop. + ACE_NOTSUP_RETURN (-1); +} + +void +ACE_Dev_Poll_Reactor::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Dev_Poll_Reactor::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("restart_ = %d\n"), this->restart_)); + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("initialized_ = %d"), + this->initialized_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("poll_fd_ = %d"), this->poll_fd_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("size_ = %u"), this->handler_rep_.size ())); + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("deactivated_ = %d"), + this->deactivated_)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +short +ACE_Dev_Poll_Reactor::reactor_mask_to_poll_event (ACE_Reactor_Mask mask) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::reactor_mask_to_poll_event"); + + if (mask == ACE_Event_Handler::NULL_MASK) + // No event. Remove from interest set. +#if defined (ACE_HAS_EVENT_POLL) + return EPOLL_CTL_DEL; +#else + return POLLREMOVE; +#endif /* ACE_HAS_EVENT_POLL */ + + short events = 0; + + // READ, ACCEPT, and CONNECT flag will place the handle in the + // read set. + if (ACE_BIT_ENABLED (mask, ACE_Event_Handler::READ_MASK) + || ACE_BIT_ENABLED (mask, ACE_Event_Handler::ACCEPT_MASK) + || ACE_BIT_ENABLED (mask, ACE_Event_Handler::CONNECT_MASK)) + { +#if defined (ACE_HAS_EVENT_POLL) + ACE_SET_BITS (events, EPOLLIN); +#else + ACE_SET_BITS (events, POLLIN); +#endif /*ACE_HAS_EVENT_POLL*/ + } + + // WRITE and CONNECT flag will place the handle in the write set. + if (ACE_BIT_ENABLED (mask, ACE_Event_Handler::WRITE_MASK) + || ACE_BIT_ENABLED (mask, ACE_Event_Handler::CONNECT_MASK)) + { +#if defined (ACE_HAS_EVENT_POLL) + ACE_SET_BITS (events, EPOLLOUT); +#else + ACE_SET_BITS (events, POLLOUT); +#endif /*ACE_HAS_EVENT_POLL*/ + } + + // EXCEPT flag will place the handle in the except set. + if (ACE_BIT_ENABLED (mask, ACE_Event_Handler::EXCEPT_MASK)) + { +#if defined (ACE_HAS_EVENT_POLL) + ACE_SET_BITS (events, EPOLLPRI); +#else + ACE_SET_BITS (events, POLLPRI); +#endif /*ACE_HAS_EVENT_POLL*/ + } + + return events; +} + +namespace { + void polite_sleep_hook (void *) { } +} + +int +ACE_Dev_Poll_Reactor::Token_Guard::acquire_quietly (ACE_Time_Value *max_wait) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::Token_Guard::acquire_quietly"); + + // Acquire the token but don't ping any waiters; just queue up politely. + int result = 0; + if (max_wait) + { + ACE_Time_Value tv = ACE_OS::gettimeofday (); + tv += *max_wait; + + ACE_MT (result = this->token_.acquire_read (&polite_sleep_hook, + 0, + &tv)); + } + else + { + ACE_MT (result = this->token_.acquire_read (&polite_sleep_hook)); + } + + // Check for timeouts and errors. + if (result == -1) + { + if (errno == ETIME) + return 0; + else + { + ACE_ERROR ((LM_ERROR, ACE_TEXT("%t: %p\n"), ACE_TEXT("token acquire_read"))); + return -1; + } + } + + // We got the token and so let us mark ourselves as owner + this->owner_ = 1; + + return result; +} + +int +ACE_Dev_Poll_Reactor::Token_Guard::acquire (ACE_Time_Value *max_wait) +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::Token_Guard::acquire"); + + // Try to grab the token. If someone if already there, don't wake + // them up, just queue up in the thread pool. + int result = 0; + if (max_wait) + { + ACE_Time_Value tv = ACE_OS::gettimeofday (); + tv += *max_wait; + + ACE_MT (result = this->token_.acquire (0, 0, &tv)); + } + else + { + ACE_MT (result = this->token_.acquire ()); + } + + // Check for timeouts and errors. + if (result == -1) + { + if (errno == ETIME) + return 0; + else + return -1; + } + + // We got the token and so let us mark ourseleves as owner + this->owner_ = 1; + + return result; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_EVENT_POLL || ACE_HAS_DEV_POLL */ diff --git a/dep/acelite/ace/Dev_Poll_Reactor.h b/dep/acelite/ace/Dev_Poll_Reactor.h new file mode 100644 index 00000000000..68724bf8f9c --- /dev/null +++ b/dep/acelite/ace/Dev_Poll_Reactor.h @@ -0,0 +1,1208 @@ +// -*- C++ -*- + +// ========================================================================= +/** + * @file Dev_Poll_Reactor.h + * + * $Id: Dev_Poll_Reactor.h 91066 2010-07-12 11:05:04Z johnnyw $ + * + * @c /dev/poll (or Linux @c sys_epoll) based Reactor implementation. + * + * @author Ossama Othman + */ +// ========================================================================= + + +#ifndef ACE_DEV_POLL_REACTOR_H +#define ACE_DEV_POLL_REACTOR_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_EVENT_POLL) && defined (ACE_HAS_DEV_POLL) +# error ACE_HAS_EVENT_POLL and ACE_HAS_DEV_POLL are mutually exclusive. +#endif /* ACE_HAS_EVENT_POLL && defined ACE_HAS_DEV_POLL */ + +#if defined (ACE_HAS_EVENT_POLL) || defined (ACE_HAS_DEV_POLL) + +#include "ace/Pipe.h" +#include "ace/Lock_Adapter_T.h" +#include "ace/Reactor_Impl.h" +#include "ace/Reactor_Token_T.h" +#include "ace/Token.h" + +#if defined (ACE_HAS_REACTOR_NOTIFICATION_QUEUE) +# include "ace/Notification_Queue.h" +#endif /* ACE_HAS_REACTOR_NOTIFICATION_QUEUE */ + +#if defined (ACE_HAS_DEV_POLL) +struct pollfd; +#elif defined (ACE_HAS_EVENT_POLL) +# include "ace/Array_Map.h" +# include /**/ +#endif + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Forward declarations +class ACE_Sig_Handler; +class ACE_Dev_Poll_Reactor; + + +// --------------------------------------------------------------------- + +/** + * @class ACE_Dev_Poll_Reactor_Notify + * + * @brief Event handler used for unblocking the ACE_Dev_Poll_Reactor + * from its event loop. + * + * This event handler is used internally by the ACE_Dev_Poll_Reactor + * as a means to allow a thread other then the one running the event + * loop to unblock the event loop. + */ +class ACE_Dev_Poll_Reactor_Notify : public ACE_Reactor_Notify +{ +public: + + /// Constructor + ACE_Dev_Poll_Reactor_Notify (void); + + /** + * @name Initialization and Termination Methods + * + * Methods called when initializing and terminating this event + * handler. + */ + virtual int open (ACE_Reactor_Impl *, + ACE_Timer_Queue *timer_queue = 0, + int disable_notify = 0); + virtual int close (void); + + /** + * Called by a thread when it wants to unblock the Reactor_Impl. + * This wakes up the Reactor_Impl if currently blocked. Pass over + * both the Event_Handler and the mask to allow the caller to + * dictate which Event_Handler method the Reactor_Impl will + * invoke. The ACE_Time_Value indicates how long to block + * trying to notify the Reactor_Impl. If timeout == 0, the + * caller will block until action is possible, else will wait until + * the relative time specified in *timeout elapses). + */ + virtual int notify (ACE_Event_Handler *eh = 0, + ACE_Reactor_Mask mask = ACE_Event_Handler::EXCEPT_MASK, + ACE_Time_Value *timeout = 0); + + /// Unimplemented method required by pure virtual method in abstract + /// base class. + /** + * This method's interface is not very compatibile with this + * Reactor's design. It's not clear why this method is pure virtual + * either. + */ + virtual int dispatch_notifications (int &number_of_active_handles, + ACE_Handle_Set &rd_mask); + + /// Returns the ACE_HANDLE of the notify pipe on which the reactor + /// is listening for notifications so that other threads can unblock + /// the Reactor_Impl. + virtual ACE_HANDLE notify_handle (void); + + /// Verify whether the buffer has dispatchable info or not. + virtual int is_dispatchable (ACE_Notification_Buffer &buffer); + + /// Handle one notify call represented in @a buffer. This could be + /// because of a thread trying to unblock the Reactor_Impl. + virtual int dispatch_notify (ACE_Notification_Buffer &buffer); + + /// Read one notify call on the handle into @a buffer. + /// This could be because of a thread trying to unblock the Reactor_Impl. + virtual int read_notify_pipe (ACE_HANDLE handle, + ACE_Notification_Buffer &buffer); + + /// Called back by the ACE_Dev_Poll_Reactor when a thread wants to + /// unblock us. + virtual int handle_input (ACE_HANDLE handle); + + /** + * Set the maximum number of times that the handle_input method + * will iterate and dispatch the ACE_Event_Handlers that are + * passed in via the notify queue before breaking out of the event + * loop. By default, this is set to -1, which means "iterate until + * the queue is empty." Setting this to a value like "1 or 2" will + * increase "fairness" (and thus prevent starvation) at the expense + * of slightly higher dispatching overhead. + */ + virtual void max_notify_iterations (int); + + /** + * Get the maximum number of times that the handle_input method + * will iterate and dispatch the ACE_Event_Handlers that are + * passed in via the notify queue before breaking out of its event + * loop. + */ + virtual int max_notify_iterations (void); + + /** + * Purge any notifications pending in this reactor for the specified + * ACE_Event_Handler object. Returns the number of notifications + * purged. Returns -1 on error. + */ + virtual int purge_pending_notifications ( + ACE_Event_Handler * = 0, + ACE_Reactor_Mask = ACE_Event_Handler::ALL_EVENTS_MASK); + + /// Dump the state of an object. + virtual void dump (void) const; + +protected: + + /** + * Keep a back pointer to the ACE_Dev_Poll_Reactor. If this value + * if NULL then the ACE_Dev_Poll_Reactor has been initialized with + * disable_notify_pipe. + */ + ACE_Dev_Poll_Reactor *dp_reactor_; + + /** + * Contains the ACE_HANDLE the ACE_Dev_Poll_Reactor is listening + * on, as well as the ACE_HANDLE that threads wanting the attention + * of the ACE_Dev_Poll_Reactor will write to. + */ + ACE_Pipe notification_pipe_; + + /** + * Keeps track of the maximum number of times that the + * ACE_Dev_Poll_Reactor_Notify::handle_input method will iterate and + * dispatch the ACE_Event_Handlers that are passed in via the + * notify pipe before breaking out of its recv loop. By default, + * this is set to -1, which means "iterate until the pipe is empty." + */ + int max_notify_iterations_; + +#if defined (ACE_HAS_REACTOR_NOTIFICATION_QUEUE) + /** + * @brief A user-space queue to store the notifications. + * + * The notification pipe has OS-specific size restrictions. That + * is, no more than a certain number of bytes may be stored in the + * pipe without blocking. This limit may be too small for certain + * applications. In this case, ACE can be configured to store all + * the events in user-space. The pipe is still needed to wake up + * the reactor thread, but only one event is sent through the pipe + * at a time. + */ + ACE_Notification_Queue notification_queue_; +#endif /* ACE_HAS_REACTOR_NOTIFICATION_QUEUE */ + + /// Lock and flag to say whether we're already dispatching notifies. + /// Purpose is to only dispatch notifies from one thread at a time. + ACE_SYNCH_MUTEX dispatching_lock_; + volatile bool dispatching_; +}; + +// --------------------------------------------------------------------- + +/** + * @class ACE_Dev_Poll_Reactor + * + * @brief A `/dev/poll' or `/dev/epoll' based Reactor implemenatation. + * + * @attention The Linux epoll implementation works quite well and is + * fully supported; however, the /dev/poll implementation is @em experimental. + * + * The ACE_Dev_Poll_Reactor uses the `/dev/poll' or '/dev/epoll' + * character devices to demultiplex events on a given set of file + * descriptors. Unlike @c select(), `/dev/poll' and `/dev/epoll' have + * no hard-coded limit on the number of file descriptors that may be + * handled at any given time. As such, the ACE_Dev_Poll_Reactor can + * generally handle a much larger number of file descriptors than + * @c select() -based reactors. Furthermore, since `/dev/poll' and + * `/dev/epoll' both return a set of file descriptors that are active, + * there is no need to "walk" the set of file descriptors to determine + * which ones are active, such as what is done with the @c select() and + * @c poll() system calls. All returned file descriptors are active. + * This makes event dispatching very efficient. + * + * @note In general, this reactor may only be used to demultiplex + * events on sockets. Demultiplexing events on pipes, for + * example may not work. This is due to a limitation in the + * underlying `/dev/poll' device driver. + * + * @note It is only possible to achieve millisecond timeout + * resolutions with the @c ACE_Dev_Poll_Reactor. However, the + * timeout resolution for timers is independent of the reactors + * timeout resolution. As such, it may be possible to achieve + * sub-millisecond timeout resolutions for timers but that is + * entirely platform dependent. + */ + +#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) +typedef ACE_Token ACE_DEV_POLL_TOKEN; +#else +typedef ACE_Noop_Token ACE_DEV_POLL_TOKEN; +#endif /* ACE_MT_SAFE && ACE_MT_SAFE != 0 */ +typedef ACE_Reactor_Token_T ACE_Dev_Poll_Reactor_Token; + +class ACE_Export ACE_Dev_Poll_Reactor : public ACE_Reactor_Impl +{ + + /** + * @struct Event_Tuple + * + * @brief Struct that collects event registration information for a handle. + * + * @internal Internal use only + * + * This struct merely provides a means to associate an event mask + * with an event handler. Such an association is needed since it is + * not possible to retrieve the event mask from the "interest set" + * stored in the `/dev/poll' or `/dev/epoll' driver. Without this + * external association, it would not be possible keep track of the + * event mask for a given event handler when suspending it or resuming + * it. + * + * @note An ACE_Handle_Set is not used since the number of handles may + * exceed its capacity (ACE_DEFAULT_SELECT_REACTOR_SIZE). + */ + struct Event_Tuple + { + /// Constructor to set up defaults. + Event_Tuple (ACE_Event_Handler *eh = 0, + ACE_Reactor_Mask m = ACE_Event_Handler::NULL_MASK, + bool is_suspended = false, + bool is_controlled = false); + + /// The event handler. + ACE_Event_Handler *event_handler; + + /// The event mask for the above event handler. + ACE_Reactor_Mask mask; + + /// Flag that states whether or not the event handler is suspended. + bool suspended; + + /// Flag to say whether or not this handle is registered with epoll. + bool controlled; + }; + + + // --------------------------------------------------------------------- + + /** + * @class Handler_Repository + * + * @internal + * + * @brief Used to map ACE_HANDLEs onto the appropriate Event_Tuple. + * + * This class is simply a container that maps a handle to its + * corresponding event tuple. It is not meant for use outside of + * the Dev_Poll_Reactor. + * + * @note Calls to any method in this class, and any modification to a + * Event_Tuple returned from this class's methods, must be made + * while holding the reactor token. + */ + class Handler_Repository + { + public: + + /// Constructor. + Handler_Repository (void); + + /// Initialize a repository that can map handles up to the value @a size. + /// Since the event tuples are accessed directly using the handle as + /// an index, @a size sets the maximum handle value, minus 1. + int open (size_t size); + + /// Close down the repository. + int close (void); + + /** + * @name Repository Manipulation Operations + * + * Methods used to search and modify the handler repository. + */ + //@{ + + /// Return a pointer to the Event_Tuple associated with @a handle. + /// If there is none associated, returns 0 and sets errno. + Event_Tuple *find (ACE_HANDLE handle); + + + /// Bind the ACE_Event_Handler to the @c ACE_HANDLE with the + /// appropriate ACE_Reactor_Mask settings. + int bind (ACE_HANDLE handle, + ACE_Event_Handler *handler, + ACE_Reactor_Mask mask); + + /// Remove the binding for @a handle; optionally decrement the associated + /// handler's reference count. + int unbind (ACE_HANDLE handle, bool decr_refcnt = true); + + /// Remove all the registered tuples. + int unbind_all (void); + + //@} + + /** + * @name Sanity Checking + * + * Methods used to prevent "out-of-range" errors when indexing the + * underlying handler array. + */ + //@{ + + // Check the @a handle to make sure it's a valid @c ACE_HANDLE that + // within the range of legal handles (i.e., greater than or equal to + // zero and less than @c max_size_). + bool invalid_handle (ACE_HANDLE handle) const; + + // Check the handle to make sure it's a valid @c ACE_HANDLE that is + // within the range of currently registered handles (i.e., greater + // than or equal to zero and less than @c max_handlep1_). + bool handle_in_range (ACE_HANDLE handle) const; + + //@} + + /// Returns the current table size. + size_t size (void) const; + + /// Returns the current table size. + size_t max_size (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + + private: + + /// Current number of handles. + int size_; + + /// Maximum number of handles. + int max_size_; + + /// The underlying array of event handlers. + /** + * The array of event handlers is directly indexed directly using + * an @c ACE_HANDLE value. This is Unix-specific. + */ + Event_Tuple *handlers_; + + }; + +public: + + /// Initialize @c ACE_Dev_Poll_Reactor with the default size. + /** + * The default size for the @c ACE_Dev_Poll_Reactor is the maximum + * number of open file descriptors for the process. + */ + ACE_Dev_Poll_Reactor (ACE_Sig_Handler * = 0, + ACE_Timer_Queue * = 0, + int disable_notify_pipe = 0, + ACE_Reactor_Notify *notify = 0, + int mask_signals = 1, + int s_queue = ACE_DEV_POLL_TOKEN::FIFO); + + /// Initialize ACE_Dev_Poll_Reactor with size @a size. + /** + * @note On Unix platforms, the @a size parameter should be as large + * as the maximum number of file descriptors allowed for a + * given process. This is necessary since a file descriptor + * is used to directly index the array of event handlers + * maintained by the Reactor's handler repository. Direct + * indexing is used for efficiency reasons. If the size + * parameter is less than the process maximum, the process + * maximum will be decreased in order to prevent potential + * access violations. + */ + ACE_Dev_Poll_Reactor (size_t size, + bool restart = false, + ACE_Sig_Handler * = 0, + ACE_Timer_Queue * = 0, + int disable_notify_pipe = 0, + ACE_Reactor_Notify *notify = 0, + int mask_signals = 1, + int s_queue = ACE_DEV_POLL_TOKEN::FIFO); + + /// Close down and release all resources. + virtual ~ACE_Dev_Poll_Reactor (void); + + /// Initialization. + virtual int open (size_t size, + bool restart = false, + ACE_Sig_Handler * = 0, + ACE_Timer_Queue * = 0, + int disable_notify_pipe = 0, + ACE_Reactor_Notify * = 0); + + /** + * @param handle allows the reactor to check if the caller is + * valid. + * + * @return 0 if the size of the current message has been put in + * size. -1 if not. + */ + virtual int current_info (ACE_HANDLE handle, size_t & /* size */); + + /// Use a user specified signal handler instead. + virtual int set_sig_handler (ACE_Sig_Handler *signal_handler); + + /// Set a user-specified timer queue. + virtual int timer_queue (ACE_Timer_Queue *tq); + + /// Get the timer queue + /// @return The current @c ACE_Timer_Queue. + virtual ACE_Timer_Queue *timer_queue (void) const; + + /// Close down and release all resources. + virtual int close (void); + + // = Event loop drivers. + /** + * Returns non-zero if there are I/O events "ready" for dispatching, + * but does not actually dispatch the event handlers. By default, + * don't block while checking this, i.e., "poll". + * + * @note It is only possible to achieve millisecond timeout + * resolutions with the @c ACE_Dev_Poll_Reactor. + */ + virtual int work_pending ( + const ACE_Time_Value &max_wait_time = ACE_Time_Value::zero); + + /** + * This event loop driver blocks for up to @a max_wait_time before + * returning. It will return earlier if events occur. Note that + * @a max_wait_time can be 0, in which case this method blocks + * indefinitely until events occur. + * @par + * @a max_wait_time is decremented to reflect how much time this + * call took. For instance, if a time value of 3 seconds is passed + * to @c handle_events() and an event occurs after 2 seconds, + * @a max_wait_time will equal 1 second. This can be used if an + * application wishes to handle events for some fixed amount of + * time. + * @par + * The only difference between @c alertable_handle_events() and + * handle_events() is that in the alertable case, the event loop + * will return when the system queues an I/O completion routine or + * an Asynchronous Procedure Call. + * + * @return The total number of @c ACE_Event_Handlers that were + * dispatched, 0 if the @a max_wait_time elapsed without + * dispatching any handlers, or -1 if an error occurs. + + * @note It is only possible to achieve millisecond timeout + * resolutions with the @c ACE_Dev_Poll_Reactor. + */ + virtual int handle_events (ACE_Time_Value *max_wait_time = 0); + virtual int alertable_handle_events (ACE_Time_Value *max_wait_time = 0); + + /** + * This method is just like the one above, except the + * @a max_wait_time value is a reference and can therefore never be + * @c NULL. + * + * @note It is only possible to achieve millisecond timeout + * resolutions with the @c ACE_Dev_Poll_Reactor. + */ + virtual int handle_events (ACE_Time_Value &max_wait_time); + virtual int alertable_handle_events (ACE_Time_Value &max_wait_time); + + // = Event handling control. + + /** + * @return The status of Reactor. If this function returns 0, the + * reactor is actively handling events. If it returns + * non-zero, @c handle_events() and + * @c handle_alertable_events() return -1 immediately. + */ + virtual int deactivated (void); + + /** + * Control whether the Reactor will handle any more incoming events + * or not. If @a do_stop == 1, the Reactor will be disabled. By + * default, a reactor is in active state and can be + * deactivated/reactived as desired. + */ + virtual void deactivate (int do_stop); + + // = Register and remove Handlers. + + /// Register @a event_handler with @a mask. The I/O handle will + /// always come from get_handle on the event_handler. + virtual int register_handler (ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask); + + /// Register @a event_handler with @a mask. The I/O handle is + /// provided through the @a io_handle parameter. + virtual int register_handler (ACE_HANDLE io_handle, + ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask); + + /** + * Register an @a event_handler that will be notified when + * @a event_handle is signaled. @a mask specifies the network + * events that the @a event_handler is interested in. + */ + virtual int register_handler (ACE_HANDLE event_handle, + ACE_HANDLE io_handle, + ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask); + + /// Register @a event_handler> with all the @a handles> in the @c + /// Handle_Set. + virtual int register_handler (const ACE_Handle_Set &handles, + ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask); + + /** + * Register @a new_sh to handle the signal @a signum using the + * @a new_disp. Returns the @a old_sh that was previously + * registered (if any), along with the @a old_disp of the signal + * handler. + */ + virtual int register_handler (int signum, + ACE_Event_Handler *new_sh, + ACE_Sig_Action *new_disp = 0, + ACE_Event_Handler **old_sh = 0, + ACE_Sig_Action *old_disp = 0); + + /// Registers @a new_sh to handle a set of signals @a sigset using the + /// @a new_disp. + virtual int register_handler (const ACE_Sig_Set &sigset, + ACE_Event_Handler *new_sh, + ACE_Sig_Action *new_disp = 0); + + /// Removes @a event_handler. + /** + * @note The I/O handle will be obtained using @c get_handle() + * method of @a event_handler . If @a mask == + * @c ACE_Event_Handler::DONT_CALL then the @c handle_close() + * method of the @a event_handler is not invoked. + */ + virtual int remove_handler (ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask); + + /** + * Removes @a handle. If @a mask == ACE_Event_Handler::DONT_CALL + * then the method of the associated + * is not invoked. + */ + virtual int remove_handler (ACE_HANDLE handle, + ACE_Reactor_Mask mask); + + /** + * Removes all handles in @a handle_set. If @a mask == + * ACE_Event_Handler::DONT_CALL then the method of + * the associated s is not invoked. + */ + virtual int remove_handler (const ACE_Handle_Set &handle_set, + ACE_Reactor_Mask mask); + + /** + * Remove the ACE_Event_Handler currently associated with @a signum. + * Install the new disposition (if given) and return the previous + * disposition (if desired by the caller). Returns 0 on success and + * -1 if @a signum is invalid. + */ + virtual int remove_handler (int signum, + ACE_Sig_Action *new_disp, + ACE_Sig_Action *old_disp = 0, + int sigkey = -1); + + /// Calls for every signal in @a sigset. + virtual int remove_handler (const ACE_Sig_Set &sigset); + + // = Suspend and resume Handlers. + + /// Suspend event_handler temporarily. Use + /// ACE_Event_Handler::get_handle() to get the handle. + virtual int suspend_handler (ACE_Event_Handler *event_handler); + + /// Suspend handle temporarily. + virtual int suspend_handler (ACE_HANDLE handle); + + /// Suspend all handles in handle set temporarily. + virtual int suspend_handler (const ACE_Handle_Set &handles); + + /// Suspend all handles temporarily. + virtual int suspend_handlers (void); + + /// Resume event_handler. Use ACE_Event_Handler::get_handle() to + /// get the handle. + virtual int resume_handler (ACE_Event_Handler *event_handler); + + /// Resume handle. + virtual int resume_handler (ACE_HANDLE handle); + + /// Resume all handles in handle set. + virtual int resume_handler (const ACE_Handle_Set &handles); + + /// Resume all handles. + virtual int resume_handlers (void); + + /// Does the reactor allow the application to resume the handle on + /// its own, i.e., can it pass on the control of handle resumption to + /// the application. + virtual int resumable_handler (void); + + /// Return true if we any event associations were made by the reactor + /// for the handles that it waits on, false otherwise. + virtual bool uses_event_associations (void); + + // = Timer management. + + /** + * Schedule an ACE_Event_Handler that will expire after an amount + * of time. The return value of this method, a timer_id value, + * uniquely identifies the event_handler in the ACE_Reactor's + * internal list of timers. + * This timer_id value can be used to cancel the timer + * with the cancel_timer() call. + * + * @see cancel_timer() + * @see reset_timer_interval() + * + * @param event_handler event handler to schedule on reactor + * @param arg argument passed to the handle_timeout() method of + * event_handler. + * @param delay time interval after which the timer will expire. + * @param interval time interval for which the timer will be + * automatically rescheduled. + * @return -1 on failure, a timer_id value on success + */ + virtual long schedule_timer (ACE_Event_Handler *event_handler, + const void *arg, + const ACE_Time_Value &delay, + const ACE_Time_Value &interval = ACE_Time_Value::zero); + + /** + * Resets the interval of the timer represented by @a timer_id to + * @a interval, which is specified in relative time to the current + * . If @a interval is equal to + * ACE_Time_Value::zero, the timer will become a non-rescheduling + * timer. Returns 0 if successful, -1 if not. + */ + virtual int reset_timer_interval (long timer_id, + const ACE_Time_Value &interval); + + /// Cancel all Event_Handlers that match the address of + /// @a event_handler. Returns number of handlers cancelled. + virtual int cancel_timer (ACE_Event_Handler *event_handler, + int dont_call_handle_close = 1); + + /** + * Cancel the single event handler that matches the @a timer_id value + * (which was returned from the schedule method). If @a arg is + * non-NULL then it will be set to point to the ``magic cookie'' + * argument passed in when the event handler was registered. This + * makes it possible to free up the memory and avoid memory leaks. + * Returns 1 if cancellation succeeded and 0 if the @a timer_id + * wasn't found. + */ + virtual int cancel_timer (long timer_id, + const void **arg = 0, + int dont_call_handle_close = 1); + + // = High-level event handler scheduling operations + + /// Add @a masks_to_be_added to the @a event_handler's entry. + /// @a event_handler must already have been registered. + virtual int schedule_wakeup (ACE_Event_Handler *event_handler, + ACE_Reactor_Mask masks_to_be_added); + + /// Add @a masks_to_be_added to the @a handle's entry. + /// associated with @a handle must already have been registered. + virtual int schedule_wakeup (ACE_HANDLE handle, + ACE_Reactor_Mask masks_to_be_added); + + /// Clear @a masks_to_be_cleared from the @a event_handler's entry. + virtual int cancel_wakeup (ACE_Event_Handler *event_handler, + ACE_Reactor_Mask masks_to_be_cleared); + + /// Clear @a masks_to_be_cleared from the @a handle's entry. + virtual int cancel_wakeup (ACE_HANDLE handle, + ACE_Reactor_Mask masks_to_be_cleared); + + // = Notification methods. + + /** + * Notify @a event_handler of @a mask event. The ACE_Time_Value + * indicates how long to blocking trying to notify. If @a timeout == + * 0, the caller will block until action is possible, else will wait + * until the relative time specified in @a timeout elapses). + */ + virtual int notify (ACE_Event_Handler *event_handler = 0, + ACE_Reactor_Mask mask = ACE_Event_Handler::EXCEPT_MASK, + ACE_Time_Value * = 0); + + /** + * Set the maximum number of times that ACE_Reactor_Impl will + * iterate and dispatch the ACE_Event_Handlers that are passed in + * via the notify queue before breaking out of its + * loop. By default, this is set to + * -1, which means "iterate until the queue is empty." Setting this + * to a value like "1 or 2" will increase "fairness" (and thus + * prevent starvation) at the expense of slightly higher dispatching + * overhead. + */ + virtual void max_notify_iterations (int); + + /** + * Get the maximum number of times that the ACE_Reactor_Impl will + * iterate and dispatch the ACE_Event_Handlers that are passed in + * via the notify queue before breaking out of its + * loop. + */ + virtual int max_notify_iterations (void); + + /** + * Purge any notifications pending in this reactor for the specified + * ACE_Event_Handler object. Returns the number of notifications + * purged. Returns -1 on error. + */ + virtual int purge_pending_notifications (ACE_Event_Handler * = 0, + ACE_Reactor_Mask = ACE_Event_Handler::ALL_EVENTS_MASK); + + /** + * Return the Event_Handler associated with @a handle. Return 0 if + * @a handle is not registered. + */ + virtual ACE_Event_Handler *find_handler (ACE_HANDLE handle); + + /** + * Check to see if @a handle is associated with a valid Event_Handler + * bound to @a mask. Return the @a event_handler associated with this + * @c handler if @a event_handler != 0. + */ + virtual int handler (ACE_HANDLE handle, + ACE_Reactor_Mask mask, + ACE_Event_Handler **event_handler = 0); + + /** + * Check to see if @a signum is associated with a valid Event_Handler + * bound to a signal. Return the @a event_handler associated with + * this @c handler if @a event_handler != 0. + */ + virtual int handler (int signum, + ACE_Event_Handler ** = 0); + + /// Returns true if Reactor has been successfully initialized, else + /// false. + virtual bool initialized (void); + + /// Returns the current size of the Reactor's internal descriptor + /// table. + virtual size_t size (void) const; + + /// Returns a reference to the Reactor's internal lock. + virtual ACE_Lock &lock (void); + + /// Wake up all threads waiting in the event loop. + virtual void wakeup_all_threads (void); + + /// Transfers ownership of Reactor_Impl to the new_owner. + /** + * @note There is no need to set the owner of the event loop for the + * ACE_Dev_Poll_Reactor. Multiple threads may invoke the + * event loop simulataneously. As such, this method is a + * no-op. + */ + virtual int owner (ACE_thread_t new_owner, ACE_thread_t *old_owner = 0); + + /// Return the ID of the "owner" thread. + /** + * @note There is no need to set the owner of the event loop for the + * ACE_Dev_Poll_Reactor. Multiple threads may invoke the + * event loop simulataneously. As such, this method is a + * no-op. + */ + virtual int owner (ACE_thread_t *owner); + + /// Get the existing restart value. + virtual bool restart (void); + + /// Set a new value for restart and return the original value. + /** + * @param r If zero, then the event loop will not be automatically + * restarted if the underlying poll is interrupted via the + * INTR (interrupt) signal. + * + * @return Returns the previous "restart" value. + */ + virtual bool restart (bool r); + + /// Set position of the owner thread. + /** + * @note This is currently a no-op. + */ + virtual void requeue_position (int); + + /// Get position of the owner thread. + /** + * @note This is currently a no-op. + */ + virtual int requeue_position (void); + + /** + * @name Low-level wait_set mask manipulation methods + * + * Low-level methods to manipulate the event/reactor mask associated + * with a handle and event handler when polling for events. + * @par + * The "interest set," i.e. the wait set, can be directly + * manipulated with these methods. + */ + //@{ + + /// GET/SET/ADD/CLR the dispatch mask "bit" bound with the + /// event_handler and mask. + /** + * @return Old mask on success, -1 on error. + */ + virtual int mask_ops (ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask, + int ops); + + /// GET/SET/ADD/CLR the dispatch MASK "bit" bound with the handle + /// and mask. + /** + * @return Old mask on success, -1 on error. + */ + virtual int mask_ops (ACE_HANDLE handle, + ACE_Reactor_Mask mask, + int ops); + + //@} + + /** + * @name Low-level ready_set mask manipulation methods + * + * These methods are unimplemented. + */ + //@{ + + /// GET/SET/ADD/CLR the ready "bit" bound with the event_handler + /// and mask. + virtual int ready_ops (ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask, + int ops); + + /// GET/SET/ADD/CLR the ready "bit" bound with the handle and mask. + virtual int ready_ops (ACE_HANDLE handle, + ACE_Reactor_Mask, + int ops); + + //@} + + /// Dump the state of an object. + virtual void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + + class Token_Guard; + + /// Non-locking version of wait_pending(). + /** + * Returns non-zero if there are I/O events "ready" for dispatching, + * but does not actually dispatch the event handlers. By default, + * don't block while checking this, i.e., "poll". + * + * @note It is only possible to achieve millisecond timeout + * resolutions with the ACE_Dev_Poll_Reactor. + */ + int work_pending_i (ACE_Time_Value *max_wait_time); + + /// Poll for events and return the number of event handlers that + /// were dispatched. + /** + * This is a helper method called by all handle_events() methods. + */ + int handle_events_i (ACE_Time_Value *max_wait_time, Token_Guard &guard); + + /// Perform the upcall with the given event handler method. + int upcall (ACE_Event_Handler *event_handler, + int (ACE_Event_Handler::*callback)(ACE_HANDLE), + ACE_HANDLE handle); + + /** + * Dispatch ACE_Event_Handlers for time events, I/O events, and + * signal events. Returns the total number of ACE_Event_Handlers + * that were dispatched or -1 if something goes wrong. + */ + int dispatch (Token_Guard &guard); + + /// Dispatch a single timer, if ready. + /// Returns: 0 if no timers ready (token still held), + /// 1 if a timer was expired (token released), + /// -1 on error (token still held). + int dispatch_timer_handler (Token_Guard &guard); + + /// Dispatch an IO event to the corresponding event handler. Returns + /// Returns: 0 if no events ready (token still held), + /// 1 if an event was expired (token released), + /// -1 on error (token still held). + int dispatch_io_event (Token_Guard &guard); + + /// Register the given event handler with the reactor. + int register_handler_i (ACE_HANDLE handle, + ACE_Event_Handler *eh, + ACE_Reactor_Mask mask); + + /// Remove the event handler associated with the given handle and + /// event mask from the "interest set." If @a eh is supplied, only + /// do the remove if @eh matches the event handler that's registered + /// for @a handle. + int remove_handler_i (ACE_HANDLE handle, + ACE_Reactor_Mask mask, + ACE_Event_Handler *eh = 0); + + /// Temporarily remove the given handle from the "interest set." + int suspend_handler_i (ACE_HANDLE handle); + + /// Place the given handle that was temporarily removed from the + /// "interest set," i.e that was suspended, back in to the interest + /// set. The given handle will once again be polled for events. + int resume_handler_i (ACE_HANDLE handle); + + /// GET/SET/ADD/CLR the dispatch MASK "bit" bound with the handle + /// and mask. This internal helper method acquires no lock. + /** + * @return Old mask on success, -1 on error. + */ + int mask_ops_i (ACE_HANDLE handle, + ACE_Reactor_Mask mask, + int ops); + + /// Convert a reactor mask to its corresponding poll() event mask. + short reactor_mask_to_poll_event (ACE_Reactor_Mask mask); + +protected: + + /// Has the reactor been initialized. + bool initialized_; + + /// The file descriptor associated with the open `/dev/poll' or + /// `/dev/epoll' device. + /** + * All interactions with the `/dev/poll' or `/dev/epoll' device are + * done through this file descriptor. + */ + ACE_HANDLE poll_fd_; + +#if defined (ACE_HAS_EVENT_POLL) + /// Event structure to be filled by epoll_wait. epoll_wait() only gets + /// one event at a time and we rely on it's internals for fairness. + /// If this struct's fd is ACE_INVALID_HANDLE, the rest is indeterminate. + /// If the fd is good, the event is one that's been retrieved by + /// epoll_wait() but not yet processed. + struct epoll_event event_; + + /// Event handlers that are suspended/resumed around upcalls are not + /// immediately resumed; they're added to this list for resumption at + /// the next epoll_wait() call. This avoids always needing to acquire the + /// token just to resume a handler. Of course, if there are no other + /// handlers in the to-be-resumed list and an epoll_wait is already in + /// progress, the reactor needs to be notified to force another run around + /// the epoll_wait() call. + typedef ACE_Array_Map Resume_Map; + Resume_Map to_be_resumed_; + volatile bool epoll_wait_in_progress_; + ACE_SYNCH_MUTEX to_be_resumed_lock_; +#else + /// The pollfd array that `/dev/poll' will feed its results to. + struct pollfd *dp_fds_; + + + /// Pointer to the next pollfd array element that contains the next + /// event to be dispatched. + struct pollfd *start_pfds_; + + /// The last element in the pollfd array plus one. + /** + * The loop that dispatches IO events stops when this->start_pfds == + * this->end_pfds_. + */ + struct pollfd *end_pfds_; +#endif /* ACE_HAS_EVENT_POLL */ + + /// This flag is used to keep track of whether we are actively handling + /// events or not. + sig_atomic_t deactivated_; + + /// Lock used for synchronization of reactor state. + ACE_Dev_Poll_Reactor_Token token_; + + /// Adapter used to return internal lock to outside world. + ACE_Lock_Adapter lock_adapter_; + + /// The repository that contains all registered event handlers. + Handler_Repository handler_rep_; + + /// Defined as a pointer to allow overriding by derived classes... + ACE_Timer_Queue *timer_queue_; + + /// Keeps track of whether we should delete the timer queue (if we + /// didn't create it, then we don't delete it). + bool delete_timer_queue_; + + /// Handle signals without requiring global/static variables. + ACE_Sig_Handler *signal_handler_; + + /// Keeps track of whether we should delete the signal handler (if we + /// didn't create it, then we don't delete it). + bool delete_signal_handler_; + + /// Callback object that unblocks the if it's + /// sleeping. + ACE_Reactor_Notify *notify_handler_; + + /// Keeps track of whether we need to delete the notify handler (if + /// we didn't create it, then we don't delete it). + bool delete_notify_handler_; + + /// Flag that determines if signals are masked during event + /// dispatching. + /** + * If 0 then the Reactor will not mask the signals during the event + * dispatching. This is useful for applications that do not + * register any signal handlers and want to reduce the overhead + * introduce by the kernel level locks required to change the mask. + */ + int mask_signals_; + + /// Restart the handle_events event loop method automatically when + /// polling function in use (ioctl() in this case) is interrupted + /// via an EINTR signal. + bool restart_; + +protected: + + /** + * @class Token_Guard + * + * @brief A helper class that helps grabbing, releasing and waiting + * on tokens for a thread that needs access to the reactor's token. + */ + class ACE_Export Token_Guard + { + public: + + /// Constructor that will grab the token for us + Token_Guard (ACE_Dev_Poll_Reactor_Token &token); + + /// Destructor. This will release the token if it hasn't been + /// released till this point + ~Token_Guard (void); + + /// Release the token .. + void release_token (void); + + /// Returns whether the thread that created this object owns the + /// token or not. + int is_owner (void); + + /// A helper method that acquires the token 1) at a low priority, and + /// 2) wait quietly for the token, not waking another thread. This + /// is appropriate for cases where a thread wants to wait for and + /// dispatch an event, not causing an existing waiter to relinquish the + /// token, and also queueing up behind other threads waiting to modify + /// event records. + int acquire_quietly (ACE_Time_Value *max_wait = 0); + + /// A helper method that acquires the token at a high priority, and + /// does wake the current token holder. + int acquire (ACE_Time_Value *max_wait = 0); + + private: + + Token_Guard (void); + + private: + + /// The Reactor token. + ACE_Dev_Poll_Reactor_Token &token_; + + /// Flag that indicate whether the thread that created this object + /// owns the token or not. A value of 0 indicates that this class + /// hasn't got the token (and hence the thread) and a value of 1 + /// vice-versa. + int owner_; + + }; + +}; + + +/** + * @class ACE_Dev_Poll_Handler_Guard + * + * @brief Class used to make event handler reference count + * manipulation exception-safe. + * + * This class makes the reference count manipulation that occurs + * during an upcall exception-safe. Prior to dispatching the event + * handler, the reference count is increased. Once the upcall for the + * given event handler is complete, its reference count will be decreased. + */ +class ACE_Dev_Poll_Handler_Guard +{ +public: + + /// Constructor + /** + * The constructor checks to see if @a eh is a reference-counted handler and + * remember that for later. If @a eh is reference counted, its reference + * count is incremented unless @a do_incr is false. + * @a do_incr should be false if the reference count was incremented + * independently of this guard, for example, on a notify handler since + * the reference count is incremented when the notify is queued. + */ + ACE_Dev_Poll_Handler_Guard (ACE_Event_Handler *eh, bool do_incr = true); + + /// Destructor + /** + * The destructor decrements the reference count on the event + * handler corresponding to the given handle. + */ + ~ACE_Dev_Poll_Handler_Guard (void); + + /// Release the event handler from this guard; when the destructor is + /// called, the handler's reference count will not be decremented. + void release (void); + +private: + + /// The event handler being managed. + ACE_Event_Handler *eh_; + + /// true if eh_ is a reference-counted handler. + bool refcounted_; + +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +# include "ace/Dev_Poll_Reactor.inl" +#endif /* __ACE_INLINE__ */ + +#endif /* ACE_HAS_EVENT_POLL || ACE_HAS_DEV_POLL */ + +#include /**/ "ace/post.h" + +#endif /* ACE_DEV_POLL_REACTOR_H */ diff --git a/dep/acelite/ace/Dev_Poll_Reactor.inl b/dep/acelite/ace/Dev_Poll_Reactor.inl new file mode 100644 index 00000000000..0e72b305c62 --- /dev/null +++ b/dep/acelite/ace/Dev_Poll_Reactor.inl @@ -0,0 +1,134 @@ +// -*- C++ -*- +// $Id: Dev_Poll_Reactor.inl 91066 2010-07-12 11:05:04Z johnnyw $ + +#include "ace/Log_Msg.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE +ACE_Dev_Poll_Reactor::Event_Tuple::Event_Tuple (ACE_Event_Handler *eh, + ACE_Reactor_Mask m, + bool is_suspended, + bool is_controlled) + : event_handler (eh), + mask (m), + suspended (is_suspended), + controlled (is_controlled) +{ +} + +// --------------------------------------------------------------------- + +ACE_INLINE size_t +ACE_Dev_Poll_Reactor::Handler_Repository::size (void) const +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::Handler_Repository::size"); + + return this->size_; +} + +ACE_INLINE size_t +ACE_Dev_Poll_Reactor::Handler_Repository::max_size (void) const +{ + ACE_TRACE ("ACE_Dev_Poll_Reactor::Handler_Repository::max_size"); + + return this->max_size_; +} + +// ----------------------------------------------------------------- + +ACE_INLINE +ACE_Dev_Poll_Handler_Guard::ACE_Dev_Poll_Handler_Guard + (ACE_Event_Handler *eh, + bool do_incr) + : eh_ (eh), + refcounted_ (false) +{ + if (eh == 0) + return; + + this->refcounted_ = + eh->reference_counting_policy ().value () == + ACE_Event_Handler::Reference_Counting_Policy::ENABLED; + + if (do_incr && this->refcounted_) + eh->add_reference (); +} + +ACE_INLINE +ACE_Dev_Poll_Handler_Guard::~ACE_Dev_Poll_Handler_Guard (void) +{ + if (this->refcounted_ && this->eh_ != 0) + this->eh_->remove_reference (); +} + +ACE_INLINE void +ACE_Dev_Poll_Handler_Guard::release (void) +{ + this->eh_ = 0; +} + +// --------------------------------------------------------------------- + +ACE_INLINE int +ACE_Dev_Poll_Reactor::upcall (ACE_Event_Handler *event_handler, + int (ACE_Event_Handler::*callback)(ACE_HANDLE), + ACE_HANDLE handle) +{ + // If the handler returns positive value (requesting a reactor + // callback) just call back as many times as the handler requests + // it. The handler is suspended internally and other threads are off + // handling other things. + int status = 0; + + do + { + status = (event_handler->*callback) (handle); + } + while (status > 0 && event_handler != this->notify_handler_); + + return status; +} + + +/************************************************************************/ +// Methods for ACE_Dev_Poll_Reactor::Token_Guard +/************************************************************************/ + +ACE_INLINE +ACE_Dev_Poll_Reactor::Token_Guard::Token_Guard (ACE_Dev_Poll_Reactor_Token &token) + + : token_ (token), + owner_ (0) +{ +} + +ACE_INLINE +ACE_Dev_Poll_Reactor::Token_Guard::~Token_Guard (void) +{ + if (this->owner_ == 1) + { + ACE_MT (this->token_.release ()); + this->owner_ = 0; + } +} + +ACE_INLINE void +ACE_Dev_Poll_Reactor::Token_Guard::release_token (void) +{ + if (this->owner_) + { + ACE_MT (this->token_.release ()); + + // We are not the owner anymore.. + this->owner_ = 0; + } +} + +ACE_INLINE int +ACE_Dev_Poll_Reactor::Token_Guard::is_owner (void) +{ + return this->owner_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Dirent.cpp b/dep/acelite/ace/Dirent.cpp new file mode 100644 index 00000000000..df1290e1e53 --- /dev/null +++ b/dep/acelite/ace/Dirent.cpp @@ -0,0 +1,7 @@ +// $Id: Dirent.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Dirent.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Dirent.inl" +#endif /* __ACE_INLINE__ */ diff --git a/dep/acelite/ace/Dirent.h b/dep/acelite/ace/Dirent.h new file mode 100644 index 00000000000..7735fb1f293 --- /dev/null +++ b/dep/acelite/ace/Dirent.h @@ -0,0 +1,122 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Dirent.h + * + * $Id: Dirent.h 91064 2010-07-12 10:11:24Z johnnyw $ + * + * Define a portable C++ interface to ACE_OS_Dirent directory-entry + * manipulation. + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_DIRENT_H +#define ACE_DIRENT_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/OS_NS_dirent.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Dirent + * + * @brief Define a portable C++ directory-entry iterator based on the POSIX API. + */ +class ACE_Export ACE_Dirent +{ +public: + // = Initialization and termination methods. + /// Default constructor. + ACE_Dirent (void); + + /// Constructor calls @c opendir() + explicit ACE_Dirent (const ACE_TCHAR *dirname); + + /// Opens the directory named by filename and associates a directory + /// stream with it. + int open (const ACE_TCHAR *filename); + + /// Destructor calls @c closedir(). + ~ACE_Dirent (void); + + /// Closes the directory stream and frees the ACE_DIR structure. + void close (void); + + // = Iterator methods. + /** + * Returns a pointer to a structure representing the directory entry + * at the current position in the directory stream to which dirp + * refers, and positions the directory stream at the next entry, + * except on read-only filesystems. It returns a NULL pointer upon + * reaching the end of the directory stream, or upon detecting an + * invalid location in the directory. @c read() shall not return + * directory entries containing empty names. It is unspecified + * whether entries are returned for dot or dot-dot. The pointer + * returned by @c read() points to data that may be overwritten by + * another call to @c read() on the same directory stream. This + * data shall not be overwritten by another call to @c read() on a + * different directory stream. @c read() may buffer several + * directory entries per actual read operation; @c read() marks for + * update the st_atime field of the directory each time the + * directory is actually read. + */ + ACE_DIRENT *read (void); + + /** + * Has the equivalent functionality as @c read() except that an + * @a entry and @a result buffer must be supplied by the caller to + * store the result. + */ + int read (struct ACE_DIRENT *entry, + struct ACE_DIRENT **result); + + // = Manipulators. + /// Returns the current location associated with the directory + /// stream. + long tell (void); + + /** + * Sets the position of the next @c read() operation on the + * directory stream. The new position reverts to the position + * associated with the directory stream at the time the @c tell() + * operation that provides loc was performed. Values returned by + * @c tell() are good only for the lifetime of the ACE_DIR pointer from + * which they are derived. If the directory is closed and then + * reopened, the @c telldir() value may be invalidated due to + * undetected directory compaction. It is safe to use a previous + * @c telldir() value immediately after a call to @c opendir() and before + * any calls to readdir. + */ + void seek (long loc); + + /** + * Resets the position of the directory stream to the beginning of + * the directory. It also causes the directory stream to refer to + * the current state of the corresponding directory, as a call to + * @c opendir() would. + */ + void rewind (void); + +private: + /// Pointer to the directory stream. + ACE_DIR *dirp_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Dirent.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_DIRENT_H */ diff --git a/dep/acelite/ace/Dirent.inl b/dep/acelite/ace/Dirent.inl new file mode 100644 index 00000000000..01ce3a96c4b --- /dev/null +++ b/dep/acelite/ace/Dirent.inl @@ -0,0 +1,99 @@ +// -*- C++ -*- +// +// $Id: Dirent.inl 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Log_Msg.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE int +ACE_Dirent::open (const ACE_TCHAR *dirname) +{ + // If the directory stream is already open, close it to prevent + // possible resource leaks. + + if (this->dirp_ != 0) + { + ACE_OS::closedir (this->dirp_); + this->dirp_ = 0; + } + + this->dirp_ = ACE_OS::opendir (dirname); + + if (this->dirp_ == 0) + return -1; + else + return 0; +} + +ACE_INLINE +ACE_Dirent::ACE_Dirent (void) + : dirp_ (0) +{ +} + +ACE_INLINE +ACE_Dirent::ACE_Dirent (const ACE_TCHAR *dirname) + : dirp_ (0) +{ + if (this->open (dirname) == -1) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_Dirent::ACE_Dirent"))); +} + +ACE_INLINE +ACE_Dirent::~ACE_Dirent (void) +{ + if (this->dirp_ != 0) + ACE_OS::closedir (this->dirp_); +} + +ACE_INLINE ACE_DIRENT * +ACE_Dirent::read (void) +{ + return this->dirp_ ? ACE_OS::readdir (this->dirp_) : 0; +} + +ACE_INLINE int +ACE_Dirent::read (struct ACE_DIRENT *entry, + struct ACE_DIRENT **result) +{ + return this->dirp_ + ? ACE_OS::readdir_r (this->dirp_, entry, result) + : 0; +} + +ACE_INLINE void +ACE_Dirent::close (void) +{ + if (this->dirp_ != 0) + { + ACE_OS::closedir (this->dirp_); + + // Prevent double closure + this->dirp_ = 0; + } +} + +ACE_INLINE void +ACE_Dirent::rewind (void) +{ + if (this->dirp_) + ACE_OS::rewinddir (this->dirp_); +} + +ACE_INLINE void +ACE_Dirent::seek (long loc) +{ + if (this->dirp_) + ACE_OS::seekdir (this->dirp_, loc); +} + +ACE_INLINE long +ACE_Dirent::tell (void) +{ + return this->dirp_ ? ACE_OS::telldir (this->dirp_) : 0; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Dirent_Selector.cpp b/dep/acelite/ace/Dirent_Selector.cpp new file mode 100644 index 00000000000..8fcb5775b29 --- /dev/null +++ b/dep/acelite/ace/Dirent_Selector.cpp @@ -0,0 +1,59 @@ +// $Id: Dirent_Selector.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Dirent_Selector.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Dirent_Selector.inl" +#endif /* __ACE_INLINE__ */ + +#include "ace/OS_NS_dirent.h" +#include "ace/OS_NS_stdlib.h" + +ACE_RCSID (ace, + Dirent_Selector, + "$Id: Dirent_Selector.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Construction/Destruction + +ACE_Dirent_Selector::ACE_Dirent_Selector (void) + : namelist_ (0), + n_ (0) +{ +} + +ACE_Dirent_Selector::~ACE_Dirent_Selector (void) +{ + // Free up any allocated resources. + this->close(); +} + +int +ACE_Dirent_Selector::open (const ACE_TCHAR *dir, + ACE_SCANDIR_SELECTOR sel, + ACE_SCANDIR_COMPARATOR cmp) +{ + n_ = ACE_OS::scandir (dir, &this->namelist_, sel, cmp); + return n_; +} + +int +ACE_Dirent_Selector::close (void) +{ + for (--n_; n_ >= 0; --n_) + { +#if defined (ACE_LACKS_STRUCT_DIR) + // Only the lacking-struct-dir emulation allocates this. Native + // scandir includes d_name in the dirent struct itself. + ACE_OS::free (this->namelist_[n_]->d_name); +#endif + ACE_OS::free (this->namelist_[n_]); + } + + ACE_OS::free (this->namelist_); + this->namelist_ = 0; + return 0; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Dirent_Selector.h b/dep/acelite/ace/Dirent_Selector.h new file mode 100644 index 00000000000..20673c473a9 --- /dev/null +++ b/dep/acelite/ace/Dirent_Selector.h @@ -0,0 +1,75 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Dirent_Selector.h + * + * $Id: Dirent_Selector.h 80826 2008-03-04 14:51:23Z wotte $ + * + * Define a portable C++ interface to the method. + * + * @author Rich Newman + */ +//============================================================================= + +#ifndef ACE_DIRENT_SELECTOR_H +#define ACE_DIRENT_SELECTOR_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +#pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/OS_NS_dirent.h" /* Need ACE_SCANDIR_SELECTOR, COMPARATOR */ +#include "ace/os_include/os_dirent.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Dirent_Selector + * + * @brief Define a portable C++ directory-entry iterator based on the + * POSIX scandir API. + */ +class ACE_Export ACE_Dirent_Selector +{ +public: + /// Constructor + ACE_Dirent_Selector (void); + + /// Destructor. + virtual ~ACE_Dirent_Selector (void); + + /// Return the length of the list of matching directory entries. + int length (void) const; + + /// Return the entry at @a index. + ACE_DIRENT *operator[] (const int index) const; + + /// Free up resources. + int close (void); + + /// Open the directory @a dir and populate the current list of names with + /// directory entries that match the @a selector and @a comparator. + int open (const ACE_TCHAR *dir, + ACE_SCANDIR_SELECTOR selector = 0, + ACE_SCANDIR_COMPARATOR comparator = 0); + +protected: + /// Ptr to the namelist array. + ACE_DIRENT **namelist_; + + /// Number of entries in the array. + int n_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Dirent_Selector.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_DIRENT_SELECTOR_H */ diff --git a/dep/acelite/ace/Dirent_Selector.inl b/dep/acelite/ace/Dirent_Selector.inl new file mode 100644 index 00000000000..15f804704bf --- /dev/null +++ b/dep/acelite/ace/Dirent_Selector.inl @@ -0,0 +1,19 @@ +// -*- C++ -*- +// +// $Id: Dirent_Selector.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE int +ACE_Dirent_Selector::length (void) const +{ + return n_; +} + +ACE_INLINE ACE_DIRENT * +ACE_Dirent_Selector::operator[] (const int n) const +{ + return this->namelist_[n]; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Dump.cpp b/dep/acelite/ace/Dump.cpp new file mode 100644 index 00000000000..6e5c2d0c3ea --- /dev/null +++ b/dep/acelite/ace/Dump.cpp @@ -0,0 +1,141 @@ +// $Id: Dump.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Dump.h" +#include "ace/Guard_T.h" +#include "ace/Thread_Mutex.h" +#include "ace/Object_Manager.h" +#include "ace/Log_Msg.h" + +ACE_RCSID(ace, Dump, "$Id: Dump.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Implementations (very simple for now...) + +ACE_Dumpable::~ACE_Dumpable (void) +{ + ACE_TRACE ("ACE_Dumpable::~ACE_Dumpable"); +} + +ACE_Dumpable::ACE_Dumpable (const void *this_ptr) + : this_ (this_ptr) +{ + ACE_TRACE ("ACE_Dumpable::ACE_Dumpable"); +} + +ACE_Dumpable_Ptr::ACE_Dumpable_Ptr (const ACE_Dumpable *dumper) + : dumper_ (dumper) +{ + ACE_TRACE ("ACE_Dumpable_Ptr::ACE_Dumpable_Ptr"); +} + +const ACE_Dumpable * +ACE_Dumpable_Ptr::operator->() const +{ + ACE_TRACE ("ACE_Dumpable_Ptr::operator->"); + return this->dumper_; +} + +void +ACE_Dumpable_Ptr::operator= (const ACE_Dumpable *dumper) const +{ + ACE_TRACE ("ACE_Dumpable_Ptr::operator="); + if (this->dumper_ != dumper) + { + delete const_cast (this->dumper_); + (const_cast (this))->dumper_ = dumper; + } +} + +ACE_ODB::ACE_ODB (void) + // Let the Tuple default constructor initialize object_table_ + : current_size_ (0) +{ + ACE_TRACE ("ACE_ODB::ACE_ODB"); +} + +ACE_ODB * +ACE_ODB::instance (void) +{ + ACE_TRACE ("ACE_ODB::instance"); + + if (ACE_ODB::instance_ == 0) + { + ACE_MT (ACE_Thread_Mutex *lock = + ACE_Managed_Object::get_preallocated_object + (ACE_Object_Manager::ACE_DUMP_LOCK); + ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, *lock, 0)); + + if (ACE_ODB::instance_ == 0) + ACE_NEW_RETURN (ACE_ODB::instance_, + ACE_ODB, + 0); + } + + return ACE_ODB::instance_; +} + +void +ACE_ODB::dump_objects (void) +{ + ACE_TRACE ("ACE_ODB::dump_objects"); + for (int i = 0; i < this->current_size_; i++) + { + if (this->object_table_[i].this_ != 0) + // Dump the state of the object. + this->object_table_[i].dumper_->dump (); + } +} + +// This method registers a new . It detects +// duplicates and simply overwrites them. + +void +ACE_ODB::register_object (const ACE_Dumpable *dumper) +{ + ACE_TRACE ("ACE_ODB::register_object"); + int i; + int slot = 0; + + for (i = 0; i < this->current_size_; i++) + { + if (this->object_table_[i].this_ == 0) + slot = i; + else if (this->object_table_[i].this_ == dumper->this_) + { + slot = i; + break; + } + } + + if (i == this->current_size_) + { + slot = this->current_size_++; + ACE_ASSERT (this->current_size_ < ACE_ODB::MAX_TABLE_SIZE); + } + this->object_table_[slot].this_ = dumper->this_; + this->object_table_[slot].dumper_ = dumper; +} + +void +ACE_ODB::remove_object (const void *this_ptr) +{ + ACE_TRACE ("ACE_ODB::remove_object"); + int i; + + for (i = 0; i < this->current_size_; i++) + { + if (this->object_table_[i].this_ == this_ptr) + break; + } + + if (i < this->current_size_) + { + this->object_table_[i].this_ = 0; + this->object_table_[i].dumper_ = 0; + } +} + +ACE_ODB *ACE_ODB::instance_ = 0; + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Dump.h b/dep/acelite/ace/Dump.h new file mode 100644 index 00000000000..4ccd64adb95 --- /dev/null +++ b/dep/acelite/ace/Dump.h @@ -0,0 +1,172 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file Dump.h + * + * $Id: Dump.h 80826 2008-03-04 14:51:23Z wotte $ + * + * + * A prototype mechanism that allow all ACE objects to be registered + * with a central in-memory "database" that can dump the state of all + * live ACE objects (e.g., from within a debugger). + * + * The macros which allow easy registration and removal of objects to be + * dumped (ACE_REGISTER_OBJECT and ACE_REMOVE_OBJECT) are turned into + * no-ops by compiling with the ACE_NDEBUG macro defined. This allows + * usage to be removed in "release mode" builds without changing code. + * + * There are several interesting aspects to this design: + * + * 1. It uses the External Polymorphism pattern to avoid having to + * derive all ACE classes from a common base class that has virtual + * methods (this is crucial to avoid unnecessary overhead). In + * addition, there is no additional space added to ACE objects + * (this is crucial to maintain binary layout compatibility). + * + * 2. This mechanism can be conditionally compiled in order to + * completely disable this feature entirely. Moreover, by + * using macros there are relatively few changes to ACE code. + * + * 3. This mechanism copes with single-inheritance hierarchies of + * dumpable classes. In such cases we typically want only one + * dump, corresponding to the most derived instance. Thanks to + * Christian Millour (chris@etca.fr) for illustrating how to do + * this. Note, however, that this scheme doesn't generalize to + * work with multiple-inheritance or virtual base classes. + * + * Future work includes: + * + * 1. Using a dynamic object table rather than a static table + * + * 2. Adding support to allow particular classes of objects to + * be selectively dumped. + * + * + * @author Doug Schmidt + */ +//============================================================================= + + +#ifndef ACE_DUMP_H +#define ACE_DUMP_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Dumpable + * + * @brief Base class that defines a uniform interface for all object + * dumping. + */ +class ACE_Export ACE_Dumpable +{ +public: + friend class ACE_ODB; + friend class ACE_Dumpable_Ptr; + + /// Constructor. + ACE_Dumpable (const void *); + + /// This pure virtual method must be filled in by a subclass. + virtual void dump (void) const = 0; + +protected: + virtual ~ACE_Dumpable (void); + +private: + /// Pointer to the object that is being stored. + const void *this_; +}; + +/** + * @class ACE_Dumpable_Ptr + * + * @brief A smart pointer stored in the in-memory object database + * ACE_ODB. The pointee (if any) is deleted when reassigned. + */ +class ACE_Export ACE_Dumpable_Ptr +{ +public: + ACE_Dumpable_Ptr (const ACE_Dumpable *dumper = 0); + const ACE_Dumpable *operator->() const; + void operator= (const ACE_Dumpable *dumper) const; + +private: + /// "Real" pointer to the underlying abstract base class + /// pointer that does the real work. + const ACE_Dumpable *dumper_; +}; + +/** + * @class ACE_ODB + * + * @brief This is the object database (ODB) that keeps track of all + * live ACE objects. + */ +class ACE_Export ACE_ODB +{ +public: + /// @todo This is clearly inadequate and should be dynamic... + enum {MAX_TABLE_SIZE = 100000}; + + /// Iterates through the entire set of registered objects and + /// dumps their state. + void dump_objects (void); + + /// Add the tuple to the list of registered ACE objects. + void register_object (const ACE_Dumpable *dumper); + + /// Use to locate and remove the associated from the + /// list of registered ACE objects. + void remove_object (const void *this_); + + /// Interface to the Singleton instance of the object database. + static ACE_ODB *instance (void); + +private: + ACE_ODB (void); // Ensure we have a Singleton... + + struct Tuple + { + /// Pointer to the object that is registered. + const void *this_; + + /// Smart pointer to the ACE_Dumpable object associated with this_. + /// This uses an ACE_Dumpable_Ptr, instead of a bare pointer, to + /// cope with hierarchies of dumpable classes. In such cases we + /// typically want only one dump, corresponding to the most derived + /// instance. To achieve this, the handle registered for the + /// subobject corresponding to the base class is destroyed (hence + /// on destruction of the subobject its handle won't exist anymore + /// and we'll have to check for that). + const ACE_Dumpable_Ptr dumper_; + + Tuple (void) : dumper_(0) {} + }; + + /// Singleton instance of this class. + static ACE_ODB *instance_; + + /// The current implementation is very simple-minded and will be + /// changed to be dynamic. + Tuple object_table_[ACE_ODB::MAX_TABLE_SIZE]; + + /// Current size of . + int current_size_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +// Include the templates classes at this point. +#include "ace/Dump_T.h" + +#include /**/ "ace/post.h" +#endif /* ACE_DUMP_H */ diff --git a/dep/acelite/ace/Dump_T.cpp b/dep/acelite/ace/Dump_T.cpp new file mode 100644 index 00000000000..da2b62a6fa3 --- /dev/null +++ b/dep/acelite/ace/Dump_T.cpp @@ -0,0 +1,48 @@ +// Dump_T.cpp +// +// $Id: Dump_T.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#ifndef ACE_DUMP_T_CPP +#define ACE_DUMP_T_CPP + +#include "ace/Dump_T.h" +#include "ace/Global_Macros.h" +#include "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template +ACE_Dumpable_Adapter::~ACE_Dumpable_Adapter (void) +{ + ACE_TRACE ("ACE_Dumpable_Adapter::~ACE_Dumpable_Adapter"); +} + +template +ACE_Dumpable_Adapter::ACE_Dumpable_Adapter (const Concrete *t) + : ACE_Dumpable ((const void *) t), this_ (t) +{ + ACE_TRACE ("ACE_Dumpable_Adapter::ACE_Dumpable_Adapter"); +} + +template Concrete * +ACE_Dumpable_Adapter::operator->() const +{ + return (Concrete *) this->this_; +} + +template void +ACE_Dumpable_Adapter::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Dumpable_Adapter::dump"); + this->this_->dump (); +#endif /* ACE_HAS_DUMP */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_DUMP_T_CPP */ diff --git a/dep/acelite/ace/Dump_T.h b/dep/acelite/ace/Dump_T.h new file mode 100644 index 00000000000..4186cabf937 --- /dev/null +++ b/dep/acelite/ace/Dump_T.h @@ -0,0 +1,83 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Dump_T.h + * + * $Id: Dump_T.h 91064 2010-07-12 10:11:24Z johnnyw $ + * + * @author Doug Schmidt + */ +//============================================================================= + + +#ifndef ACE_DUMP_T_H +#define ACE_DUMP_T_H +#include /**/ "ace/pre.h" + +#include "ace/Dump.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Dumpable_Adapter + * + * @brief + * This class inherits the interface of the abstract ACE_Dumpable + * class and is instantiated with the implementation of the + * concrete component class . + * + * This design is similar to the Adapter and Decorator patterns + * from the ``Gang of Four'' book. Note that + * need not inherit from a common class since ACE_Dumpable + * provides the uniform virtual interface! + */ +template +class ACE_Dumpable_Adapter : public ACE_Dumpable +{ +public: + // = Initialization and termination methods. + ACE_Dumpable_Adapter (const Concrete *t); + ~ACE_Dumpable_Adapter (void); + + /// Concrete dump method (simply delegates to the method of + /// ). + virtual void dump (void) const; + + /// Delegate to methods in the Concrete class. + Concrete *operator->() const; + +private: + /// Pointer to @c this of . + const Concrete *this_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +// Some useful macros for conditionally compiling this feature... +#if defined (ACE_NDEBUG) +#define ACE_REGISTER_OBJECT(CLASS) +#define ACE_REMOVE_OBJECT +#else +#define ACE_REGISTER_OBJECT(CLASS) \ + ACE_ODB::instance ()->register_object \ + (new ACE_Dumpable_Adapter (this)); +#define ACE_REMOVE_OBJECT \ + ACE_ODB::instance ()->remove_object \ + ((void *) this); +#endif /* ACE_NDEBUG */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Dump_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Dump_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" +#endif /* ACE_DUMP_T_H */ diff --git a/dep/acelite/ace/Dynamic.cpp b/dep/acelite/ace/Dynamic.cpp new file mode 100644 index 00000000000..4eaedad0cfe --- /dev/null +++ b/dep/acelite/ace/Dynamic.cpp @@ -0,0 +1,34 @@ +// $Id: Dynamic.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Dynamic.h" +#include "ace/Singleton.h" +#include "ace/TSS_T.h" +#include "ace/Synch_Traits.h" +#include "ace/Null_Mutex.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Dynamic.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID(ace, Dynamic, "$Id: Dynamic.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_Dynamic::ACE_Dynamic (void) + : is_dynamic_ (false) +{ + ACE_TRACE ("ACE_Dynamic::ACE_Dynamic"); +} + +/* static */ ACE_Dynamic * +ACE_Dynamic::instance (void) +{ + return ACE_TSS_Singleton::instance (); +} + +#if defined (ACE_HAS_EXPLICIT_STATIC_TEMPLATE_MEMBER_INSTANTIATION) +template ACE_TSS_Singleton * + ACE_TSS_Singleton::singleton_; +#endif /* ACE_HAS_EXPLICIT_STATIC_TEMPLATE_MEMBER_INSTANTIATION */ + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Dynamic.h b/dep/acelite/ace/Dynamic.h new file mode 100644 index 00000000000..70dfcd8d90a --- /dev/null +++ b/dep/acelite/ace/Dynamic.h @@ -0,0 +1,75 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file Dynamic.h + * + * $Id: Dynamic.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Doug Schmidt + * @author Irfan Pyarali. + */ +//========================================================================== + +#ifndef ACE_DYNAMIC_H +#define ACE_DYNAMIC_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Dynamic + * + * @brief Checks to see if an object was dynamically allocated. + * + * This class holds the pointer in a thread-safe manner between + * the call to operator new and the call to the constructor. + */ +class ACE_Export ACE_Dynamic +{ +public: + // = Initialization and termination method. + /// Constructor. + ACE_Dynamic (void); + + /// Destructor. + ~ACE_Dynamic (void); + + /** + * Sets a flag that indicates that the object was dynamically + * created. This method is usually called in operator new and then + * checked and reset in the constructor. + */ + void set (void); + + /// @c true if we were allocated dynamically, else @c false. + bool is_dynamic (void); + + /// Resets state flag. + void reset (void); + + static ACE_Dynamic *instance (void); + +private: + /** + * Flag that indicates that the object was dynamically created. This + * method is usually called in operator new and then checked and + * reset in the constructor. + */ + bool is_dynamic_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Dynamic.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_DYNAMIC_H */ diff --git a/dep/acelite/ace/Dynamic.inl b/dep/acelite/ace/Dynamic.inl new file mode 100644 index 00000000000..1e8e968f898 --- /dev/null +++ b/dep/acelite/ace/Dynamic.inl @@ -0,0 +1,34 @@ +// -*- C++ -*- +// +// $Id: Dynamic.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE +ACE_Dynamic::~ACE_Dynamic (void) +{ + // ACE_TRACE ("ACE_Dynamic::~ACE_Dynamic"); +} + +ACE_INLINE void +ACE_Dynamic::set (void) +{ + // ACE_TRACE ("ACE_Dynamic::set"); + this->is_dynamic_ = true; +} + +ACE_INLINE bool +ACE_Dynamic::is_dynamic (void) +{ + // ACE_TRACE ("ACE_Dynamic::is_dynamic"); + return this->is_dynamic_; +} + +ACE_INLINE void +ACE_Dynamic::reset (void) +{ + // ACE_TRACE ("ACE_Dynamic::reset"); + this->is_dynamic_ = false; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Dynamic_Message_Strategy.cpp b/dep/acelite/ace/Dynamic_Message_Strategy.cpp new file mode 100644 index 00000000000..bce5865a1e6 --- /dev/null +++ b/dep/acelite/ace/Dynamic_Message_Strategy.cpp @@ -0,0 +1,205 @@ +#include "ace/Dynamic_Message_Strategy.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Dynamic_Message_Strategy.inl" +#endif /* __ACE_INLINE__ */ + +#include "ace/Guard_T.h" +#include "ace/Log_Msg.h" +#include "ace/Malloc_Base.h" +#include "ace/OS_NS_string.h" + +ACE_RCSID (ace, + Dynamic_Message_Strategy, + "$Id: Dynamic_Message_Strategy.cpp 84565 2009-02-23 08:20:39Z johnnyw $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// ctor + +ACE_Dynamic_Message_Strategy::ACE_Dynamic_Message_Strategy (unsigned long static_bit_field_mask, + unsigned long static_bit_field_shift, + unsigned long dynamic_priority_max, + unsigned long dynamic_priority_offset) + : static_bit_field_mask_ (static_bit_field_mask), + static_bit_field_shift_ (static_bit_field_shift), + dynamic_priority_max_ (dynamic_priority_max), + dynamic_priority_offset_ (dynamic_priority_offset), + max_late_ (0, dynamic_priority_offset - 1), + min_pending_ (0, dynamic_priority_offset), + pending_shift_ (0, dynamic_priority_max) +{ +} + +// dtor + +ACE_Dynamic_Message_Strategy::~ACE_Dynamic_Message_Strategy (void) +{ +} + +ACE_Dynamic_Message_Strategy::Priority_Status +ACE_Dynamic_Message_Strategy::priority_status (ACE_Message_Block & mb, + const ACE_Time_Value & tv) +{ + // default the message to have pending priority status + Priority_Status status = ACE_Dynamic_Message_Strategy::PENDING; + + // start with the passed absolute time as the message's priority, then + // call the polymorphic hook method to (at least partially) convert + // the absolute time and message attributes into the message's priority + ACE_Time_Value priority (tv); + convert_priority (priority, mb); + + // if the priority is negative, the message is pending + if (priority < ACE_Time_Value::zero) + { + // priority for pending messages must be shifted + // upward above the late priority range + priority += pending_shift_; + if (priority < min_pending_) + priority = min_pending_; + } + // otherwise, if the priority is greater than the maximum late + // priority value that can be represented, it is beyond late + else if (priority > max_late_) + { + // all messages that are beyond late are assigned lowest priority (zero) + mb.msg_priority (0); + return ACE_Dynamic_Message_Strategy::BEYOND_LATE; + } + // otherwise, the message is late, but its priority is correct + else + status = ACE_Dynamic_Message_Strategy::LATE; + + // use (fast) bitwise operators to isolate and replace + // the dynamic portion of the message's priority + mb.msg_priority((mb.msg_priority() & static_bit_field_mask_) | + ((priority.usec () + + ACE_ONE_SECOND_IN_USECS * (suseconds_t)(priority.sec())) << + static_bit_field_shift_)); + + // returns the priority status of the message + return status; +} + + +// Dump the state of the strategy. + +void +ACE_Dynamic_Message_Strategy::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Dynamic_Message_Strategy::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("static_bit_field_mask_ = %u\n") + ACE_TEXT ("static_bit_field_shift_ = %u\n") + ACE_TEXT ("dynamic_priority_max_ = %u\n") + ACE_TEXT ("dynamic_priority_offset_ = %u\n") + ACE_TEXT ("max_late_ = [%d sec, %d usec]\n") + ACE_TEXT ("min_pending_ = [%d sec, %d usec]\n") + ACE_TEXT ("pending_shift_ = [%d sec, %d usec]\n"), + this->static_bit_field_mask_, + this->static_bit_field_shift_, + this->dynamic_priority_max_, + this->dynamic_priority_offset_, + this->max_late_.sec (), + this->max_late_.usec (), + this->min_pending_.sec (), + this->min_pending_.usec (), + this->pending_shift_.sec (), + this->pending_shift_.usec ())); + + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +ACE_Deadline_Message_Strategy::ACE_Deadline_Message_Strategy (unsigned long static_bit_field_mask, + unsigned long static_bit_field_shift, + unsigned long dynamic_priority_max, + unsigned long dynamic_priority_offset) + : ACE_Dynamic_Message_Strategy (static_bit_field_mask, + static_bit_field_shift, + dynamic_priority_max, + dynamic_priority_offset) +{ +} + +ACE_Deadline_Message_Strategy::~ACE_Deadline_Message_Strategy (void) +{ +} + +void +ACE_Deadline_Message_Strategy::convert_priority (ACE_Time_Value & priority, + const ACE_Message_Block & mb) +{ + // Convert absolute time passed in tv to negative time + // to deadline of mb with respect to that absolute time. + priority -= mb.msg_deadline_time (); +} + // dynamic priority conversion function based on time to deadline + +void +ACE_Deadline_Message_Strategy::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Deadline_Message_Strategy::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("ACE_Dynamic_Message_Strategy base class:\n"))); + this->ACE_Dynamic_Message_Strategy::dump (); + + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nderived class: ACE_Deadline_Message_Strategy\n"))); + + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +ACE_Laxity_Message_Strategy::ACE_Laxity_Message_Strategy (unsigned long static_bit_field_mask, + unsigned long static_bit_field_shift, + unsigned long dynamic_priority_max, + unsigned long dynamic_priority_offset) + : ACE_Dynamic_Message_Strategy (static_bit_field_mask, + static_bit_field_shift, + dynamic_priority_max, + dynamic_priority_offset) +{ +} + +ACE_Laxity_Message_Strategy::~ACE_Laxity_Message_Strategy (void) +{ +} + +void +ACE_Laxity_Message_Strategy::convert_priority (ACE_Time_Value & priority, + const ACE_Message_Block & mb) +{ + // Convert absolute time passed in tv to negative + // laxity of mb with respect to that absolute time. + priority += mb.msg_execution_time (); + priority -= mb.msg_deadline_time (); +} + // dynamic priority conversion function based on laxity + +void +ACE_Laxity_Message_Strategy::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Laxity_Message_Strategy::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("ACE_Dynamic_Message_Strategy base class:\n"))); + this->ACE_Dynamic_Message_Strategy::dump (); + + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nderived class: ACE_Laxity_Message_Strategy\n"))); + + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + // Dump the state of the strategy. + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Dynamic_Message_Strategy.h b/dep/acelite/ace/Dynamic_Message_Strategy.h new file mode 100644 index 00000000000..090ad3a8f82 --- /dev/null +++ b/dep/acelite/ace/Dynamic_Message_Strategy.h @@ -0,0 +1,217 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file Dynamic_Message_Strategy.h + * + * $Id: Dynamic_Message_Strategy.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Douglas C. Schmidt + */ +//========================================================================== + +#ifndef ACE_DYNAMIC_MESSAGE_STRATEGY_H +#define ACE_DYNAMIC_MESSAGE_STRATEGY_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Message_Block.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Dynamic_Message_Strategy + * + * @brief An abstract base class which provides dynamic priority + * evaluation methods for use by the ACE_Dynamic_Message_Queue + * class or any other class which needs to manage the priorities + * of a collection of ACE_Message_Blocks dynamically. + * + * Methods for deadline and laxity based priority evaluation are + * provided. These methods assume a specific partitioning of + * the message priority number into a higher order dynamic bit + * field and a lower order static priority bit field. The + * default partitioning assumes an unsigned dynamic message + * priority field of 22 bits and an unsigned static message + * priority field of 10 bits. This corresponds to the initial + * values of the static class members. To provide a different + * partitioning, assign a different set of values to the static + * class memebers before using the static member functions. + */ +class ACE_Export ACE_Dynamic_Message_Strategy +{ +public: + + // = Message priority status + + // Values are defined as bit flags so that status combinations may + // be specified easily. + + enum Priority_Status + { + /// Message can still make its deadline + PENDING = 0x01, + /// Message cannot make its deadline + LATE = 0x02, + /// Message is so late its priority is undefined + BEYOND_LATE = 0x04, + /// Mask to match any priority status + ANY_STATUS = 0x07 + }; + + /// Constructor. + ACE_Dynamic_Message_Strategy (unsigned long static_bit_field_mask, + unsigned long static_bit_field_shift, + unsigned long dynamic_priority_max, + unsigned long dynamic_priority_offset); + + /// Virtual destructor. + virtual ~ACE_Dynamic_Message_Strategy (void); + + /// Updates the message's priority and returns its priority status. + Priority_Status priority_status (ACE_Message_Block &mb, + const ACE_Time_Value &tv); + + /// Get static bit field mask. + unsigned long static_bit_field_mask (void) const; + + /// Set static bit field mask. + void static_bit_field_mask (unsigned long); + + /// Get left shift value to make room for static bit field. + unsigned long static_bit_field_shift (void) const; + + /// Set left shift value to make room for static bit field. + void static_bit_field_shift (unsigned long); + + /// Get maximum supported priority value. + unsigned long dynamic_priority_max (void) const; + + /// Set maximum supported priority value. + void dynamic_priority_max (unsigned long); + + /// Get offset to boundary between signed range and unsigned range. + unsigned long dynamic_priority_offset (void) const; + + /// Set offset to boundary between signed range and unsigned range. + void dynamic_priority_offset (unsigned long); + + /// Dump the state of the strategy. + virtual void dump (void) const; + +protected: + /// Hook method for dynamic priority conversion. + virtual void convert_priority (ACE_Time_Value &priority, + const ACE_Message_Block &mb) = 0; + + /// This is a bit mask with all ones in the static bit field. + unsigned long static_bit_field_mask_; + + /** + * This is a left shift value to make room for static bit field: + * this value should be the logarithm base 2 of + * (static_bit_field_mask_ + 1). + */ + unsigned long static_bit_field_shift_; + + /// Maximum supported priority value. + unsigned long dynamic_priority_max_; + + /// Offset to boundary between signed range and unsigned range. + unsigned long dynamic_priority_offset_; + + /// Maximum late time value that can be represented. + ACE_Time_Value max_late_; + + /// Minimum pending time value that can be represented. + ACE_Time_Value min_pending_; + + /// Time value by which to shift pending priority. + ACE_Time_Value pending_shift_; +}; + +/** + * @class ACE_Deadline_Message_Strategy + * + * @brief Deadline based message priority strategy. + * + * Assigns dynamic message priority according to time to deadline. The + * message priority is divided into high and low order bit fields. The + * high order bit field is used for dynamic message priority, which is + * updated whenever the convert_priority() method is called. The + * low order bit field is used for static message priority and is left + * unchanged. The partitioning of the priority value into high and low + * order bit fields is done according to the arguments passed to the + * strategy object's constructor. + */ +class ACE_Export ACE_Deadline_Message_Strategy : public ACE_Dynamic_Message_Strategy +{ +public: + /// Ctor, with all arguments defaulted. + ACE_Deadline_Message_Strategy (unsigned long static_bit_field_mask = 0x3FFUL, // 2^(10) - 1 + unsigned long static_bit_field_shift = 10, // 10 low order bits + unsigned long dynamic_priority_max = 0x3FFFFFUL, // 2^(22)-1 + unsigned long dynamic_priority_offset = 0x200000UL); // 2^(22-1) + + /// Virtual dtor. + virtual ~ACE_Deadline_Message_Strategy (void); + + /// Dynamic priority conversion function based on time to deadline. + virtual void convert_priority (ACE_Time_Value &priority, + const ACE_Message_Block &mb); + + /// Dump the state of the strategy. + virtual void dump (void) const; +}; + +/** + * @class ACE_Laxity_Message_Strategy + * + * @brief Laxity based message priority strategy. + * + * Assigns dynamic message priority according to laxity (time to + * deadline minus worst case execution time). The message priority is + * divided into high and low order bit fields. The high order + * bit field is used for dynamic message priority, which is + * updated whenever the convert_priority() method is called. The + * low order bit field is used for static message priority and is left + * unchanged. The partitioning of the priority value into high and low + * order bit fields is done according to the arguments passed to the + * strategy object's constructor. + */ +class ACE_Export ACE_Laxity_Message_Strategy : public ACE_Dynamic_Message_Strategy +{ +public: + /// Ctor, with all arguments defaulted. + ACE_Laxity_Message_Strategy (unsigned long static_bit_field_mask = 0x3FFUL, // 2^(10) - 1 + unsigned long static_bit_field_shift = 10, // 10 low order bits + unsigned long dynamic_priority_max = 0x3FFFFFUL, // 2^(22)-1 + unsigned long dynamic_priority_offset = 0x200000UL); // 2^(22-1) + + /// virtual dtor. + virtual ~ACE_Laxity_Message_Strategy (void); + + /// Dynamic priority conversion function based on laxity. + virtual void convert_priority (ACE_Time_Value &priority, + const ACE_Message_Block &mb); + + /// Dump the state of the strategy. + virtual void dump (void) const; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Dynamic_Message_Strategy.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" + +#endif /* ACE_DYNAMIC_MESSAGE_STRATEGY_H */ diff --git a/dep/acelite/ace/Dynamic_Message_Strategy.inl b/dep/acelite/ace/Dynamic_Message_Strategy.inl new file mode 100644 index 00000000000..9742a07fd88 --- /dev/null +++ b/dep/acelite/ace/Dynamic_Message_Strategy.inl @@ -0,0 +1,75 @@ +// -*- C++ -*- +// +// $Id: Dynamic_Message_Strategy.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE unsigned long +ACE_Dynamic_Message_Strategy::static_bit_field_mask (void) const +{ + return static_bit_field_mask_; +} + // get static bit field mask + +ACE_INLINE void +ACE_Dynamic_Message_Strategy::static_bit_field_mask (unsigned long ul) +{ + static_bit_field_mask_ = ul; +} + // set static bit field mask + +ACE_INLINE unsigned long +ACE_Dynamic_Message_Strategy::static_bit_field_shift (void) const +{ + return static_bit_field_shift_; +} + // get left shift value to make room for static bit field + +ACE_INLINE void +ACE_Dynamic_Message_Strategy::static_bit_field_shift (unsigned long ul) +{ + static_bit_field_shift_ = ul; +} + // set left shift value to make room for static bit field + +ACE_INLINE unsigned long +ACE_Dynamic_Message_Strategy::dynamic_priority_max (void) const +{ + return dynamic_priority_max_; +} + // get maximum supported priority value + +ACE_INLINE void +ACE_Dynamic_Message_Strategy::dynamic_priority_max (unsigned long ul) +{ + // pending_shift_ depends on dynamic_priority_max_: for performance + // reasons, the value in pending_shift_ is (re)calculated only when + // dynamic_priority_max_ is initialized or changes, and is stored + // as a class member rather than being a derived value. + dynamic_priority_max_ = ul; + pending_shift_ = ACE_Time_Value (0, ul); +} + // set maximum supported priority value + +ACE_INLINE unsigned long +ACE_Dynamic_Message_Strategy::dynamic_priority_offset (void) const +{ + return dynamic_priority_offset_; +} + // get offset for boundary between signed range and unsigned range + +ACE_INLINE void +ACE_Dynamic_Message_Strategy::dynamic_priority_offset (unsigned long ul) +{ + // max_late_ and min_pending_ depend on dynamic_priority_offset_: + // for performance reasons, the values in max_late_ and min_pending_ + // are (re)calculated only when dynamic_priority_offset_ is + // initialized or changes, and are stored as a class member rather + // than being derived each time one of their values is needed. + dynamic_priority_offset_ = ul; + max_late_ = ACE_Time_Value (0, ul - 1); + min_pending_ = ACE_Time_Value (0, ul); +} + // set offset for boundary between signed range and unsigned range + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Dynamic_Service.cpp b/dep/acelite/ace/Dynamic_Service.cpp new file mode 100644 index 00000000000..28d6e4526f2 --- /dev/null +++ b/dep/acelite/ace/Dynamic_Service.cpp @@ -0,0 +1,63 @@ +// $Id: Dynamic_Service.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#ifndef ACE_DYNAMIC_SERVICE_CPP +#define ACE_DYNAMIC_SERVICE_CPP + +#include "ace/Dynamic_Service.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Service_Object.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Dynamic_Service.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + + +template TYPE * +ACE_Dynamic_Service::instance (const ACE_TCHAR *name) +{ + ACE_Service_Object * svc_obj = + static_cast + (ACE_Dynamic_Service_Base::instance (name,false)); + return dynamic_cast (svc_obj); +} + +template TYPE * +ACE_Dynamic_Service::instance (const ACE_TCHAR *name, + bool no_global) +{ + ACE_Service_Object * svc_obj = + static_cast + (ACE_Dynamic_Service_Base::instance (name, no_global)); + return dynamic_cast (svc_obj); +} + +template TYPE * +ACE_Dynamic_Service::instance (const ACE_Service_Gestalt* conf, + const ACE_TCHAR *name) +{ + ACE_Service_Object * svc_obj = + static_cast + (ACE_Dynamic_Service_Base::instance (conf, name, false)); + return dynamic_cast (svc_obj); +} + +template TYPE * +ACE_Dynamic_Service::instance (const ACE_Service_Gestalt* conf, + const ACE_TCHAR *name, + bool no_global) +{ + ACE_Service_Object * svc_obj = + static_cast + (ACE_Dynamic_Service_Base::instance (conf, name, no_global)); + return dynamic_cast (svc_obj); +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_DYNAMIC_SERVICE_CPP */ diff --git a/dep/acelite/ace/Dynamic_Service.h b/dep/acelite/ace/Dynamic_Service.h new file mode 100644 index 00000000000..b90095c766d --- /dev/null +++ b/dep/acelite/ace/Dynamic_Service.h @@ -0,0 +1,89 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Dynamic_Service.h + * + * $Id: Dynamic_Service.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Prashant Jain + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_DYNAMIC_SERVICE_H +#define ACE_DYNAMIC_SERVICE_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" +#include "ace/Global_Macros.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Dynamic_Service_Base.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +class ACE_Service_Object; + +/** + * @class ACE_Dynamic_Service + * + * @brief Provides a general interface to retrieve arbitrary objects + * from the ACE service repository. + * + * Uses "name" for lookup in the ACE service repository. Obtains + * the object and returns it as the appropriate type. + */ +template +class ACE_Dynamic_Service : public ACE_Dynamic_Service_Base +{ +public: + /// Return instance using @a name to search the Service_Repository. + static TYPE* instance (const ACE_TCHAR *name); + static TYPE* instance (const ACE_TCHAR *name, bool no_global); + + static TYPE* instance (const ACE_Service_Gestalt* repo, + const ACE_TCHAR *name); + static TYPE* instance (const ACE_Service_Gestalt* repo, + const ACE_TCHAR *name, bool no_global); + +#if defined (ACE_USES_WCHAR) + + /// Return instance using @a name to search the Service_Repository. + static TYPE* instance (const ACE_ANTI_TCHAR *name); + + static TYPE* instance (const ACE_ANTI_TCHAR *name, bool no_global); + + static TYPE* instance (const ACE_Service_Gestalt* repo, + const ACE_ANTI_TCHAR *name); + static TYPE* instance (const ACE_Service_Gestalt* repo, + const ACE_ANTI_TCHAR *name, bool no_global); +#endif // ACE_USES_WCHAR + +private: + ACE_UNIMPLEMENTED_FUNC (ACE_Dynamic_Service ()) + ACE_UNIMPLEMENTED_FUNC (ACE_Dynamic_Service (const ACE_Dynamic_Service&)) + ACE_UNIMPLEMENTED_FUNC (ACE_Dynamic_Service& operator= (const ACE_Dynamic_Service&)) +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Dynamic_Service.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +# include "ace/Dynamic_Service.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +# pragma implementation ("Dynamic_Service.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" + +#endif /* ACE_DYNAMIC_SERVICE_H */ diff --git a/dep/acelite/ace/Dynamic_Service.inl b/dep/acelite/ace/Dynamic_Service.inl new file mode 100644 index 00000000000..31324bf535b --- /dev/null +++ b/dep/acelite/ace/Dynamic_Service.inl @@ -0,0 +1,39 @@ +// -*- C++ -*- +// +// $Id: Dynamic_Service.inl 81318 2008-04-10 10:12:05Z johnnyw $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +#if defined (ACE_USES_WCHAR) + +template ACE_INLINE TYPE * +ACE_Dynamic_Service::instance (const ACE_ANTI_TCHAR *name) +{ + return instance (ACE_TEXT_CHAR_TO_TCHAR (name),false); +} + +template ACE_INLINE TYPE * +ACE_Dynamic_Service::instance (const ACE_ANTI_TCHAR *name, + bool no_global) +{ + return instance (ACE_TEXT_CHAR_TO_TCHAR (name),no_global); +} + +template ACE_INLINE TYPE * +ACE_Dynamic_Service::instance (const ACE_Service_Gestalt* repo, + const ACE_ANTI_TCHAR *name) +{ + return instance (repo, ACE_TEXT_CHAR_TO_TCHAR (name),false); +} + +template ACE_INLINE TYPE * +ACE_Dynamic_Service::instance (const ACE_Service_Gestalt* repo, + const ACE_ANTI_TCHAR *name, + bool no_global) +{ + return instance (repo, ACE_TEXT_CHAR_TO_TCHAR (name),no_global); +} + +#endif // ACE_USES_WCHAR + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Dynamic_Service_Base.cpp b/dep/acelite/ace/Dynamic_Service_Base.cpp new file mode 100644 index 00000000000..ecefcf17207 --- /dev/null +++ b/dep/acelite/ace/Dynamic_Service_Base.cpp @@ -0,0 +1,106 @@ +#include "ace/Dynamic_Service_Base.h" +#include "ace/ACE.h" +#include "ace/Service_Config.h" +#include "ace/Service_Repository.h" +#include "ace/Service_Types.h" +#include "ace/Log_Msg.h" + + +ACE_RCSID (ace, + Dynamic_Service_Base, + "$Id: Dynamic_Service_Base.cpp 84282 2009-01-30 15:04:29Z msmit $") + + ACE_BEGIN_VERSIONED_NAMESPACE_DECL + + +void +ACE_Dynamic_Service_Base::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Dynamic_Service_Base::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n"))); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +// Get the instance using for the current global +// service configuration repository. + +void * +ACE_Dynamic_Service_Base::instance (const ACE_TCHAR *name, bool no_global) +{ + ACE_TRACE ("ACE_Dynamic_Service_Base::instance"); + return instance (ACE_Service_Config::current (), name, no_global); +} + +// Find a service registration + +const ACE_Service_Type * +ACE_Dynamic_Service_Base::find_i (const ACE_Service_Gestalt* &repo, + const ACE_TCHAR *name, + bool no_global) +{ + ACE_TRACE ("ACE_Dynamic_Service_Base::find_i"); + const ACE_Service_Type *svc_rec = 0; + + ACE_Service_Gestalt* global = ACE_Service_Config::global (); + + for ( ; (repo->find (name, &svc_rec) == -1) && !no_global; repo = global) + { + // Check the static repo, too if different + if (repo == global) + break; + } + + return svc_rec; +} + + +// Get the instance using for specific configuration repository. +void * +ACE_Dynamic_Service_Base::instance (const ACE_Service_Gestalt* repo, + const ACE_TCHAR *name, + bool no_global) +{ + ACE_TRACE ("ACE_Dynamic_Service_Base::instance"); + + void *obj = 0; + const ACE_Service_Type_Impl *type = 0; + + const ACE_Service_Gestalt* repo_found = repo; + const ACE_Service_Type *svc_rec = find_i (repo_found, name, no_global); + if (svc_rec != 0) + { + type = svc_rec->type (); + if (type != 0) + obj = type->object (); + } + + if (ACE::debug ()) + { + ACE_Guard log_guard (*ACE_Log_Msg::instance ()); + + if (repo->repo_ != repo_found->repo_) + { + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) DSB::instance, repo=%@, name=%s") + ACE_TEXT (" type=%@ => %@") + ACE_TEXT (" [in repo=%@]\n"), + repo->repo_, name, type, obj, + repo_found->repo_)); + } + else + { + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) DSB::instance, repo=%@, name=%s") + ACE_TEXT (" type=%@ => %@\n"), + repo->repo_, name, type, obj)); + } + } + + return obj; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Dynamic_Service_Base.h b/dep/acelite/ace/Dynamic_Service_Base.h new file mode 100644 index 00000000000..31fdadaa152 --- /dev/null +++ b/dep/acelite/ace/Dynamic_Service_Base.h @@ -0,0 +1,73 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file Dynamic_Service_Base.h + * + * $Id: Dynamic_Service_Base.h 89454 2010-03-11 09:35:25Z johnnyw $ + * + * @author Prashant Jain + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_DYNAMIC_SERVICE_BASE_H +#define ACE_DYNAMIC_SERVICE_BASE_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +class ACE_Service_Gestalt; +class ACE_Service_Type; + +/** + * @class ACE_Dynamic_Service_Base + * + * @brief Base class for all ACE_Dynamic_Service instantiations. + * + * Factors out common code shared by all ACE_Dynamic_Service + * instantiations, this avoid code bloat. + */ +class ACE_Export ACE_Dynamic_Service_Base +{ +public: + /// Dump the current static of the object + void dump (void) const; + +protected: + /// Perform the default repo search, but optionally skip searching the global + /// repo. + static void* instance (const ACE_TCHAR *name, bool no_global = false); + + static void* instance (const ACE_Service_Gestalt* repo, + const ACE_TCHAR *name, + bool no_global = false); + + /// No need to create, or assign instances of this class + ACE_Dynamic_Service_Base (void); + ~ACE_Dynamic_Service_Base (void); + const ACE_Dynamic_Service_Base& operator= (const ACE_Dynamic_Service_Base&); + +private: + /// Implement the service search policy, i.e. "look for the service first + /// locally and then globally" + static const ACE_Service_Type *find_i (const ACE_Service_Gestalt* &repo, + const ACE_TCHAR *name, + bool no_global); + + /// The dependency declaration class needs access to the service search + /// policy, implemented by find_i() + friend class ACE_Dynamic_Service_Dependency; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" +#endif /* ACE_DYNAMIC_SERVICE_BASE_H */ diff --git a/dep/acelite/ace/Dynamic_Service_Dependency.cpp b/dep/acelite/ace/Dynamic_Service_Dependency.cpp new file mode 100644 index 00000000000..df7cd0f5d48 --- /dev/null +++ b/dep/acelite/ace/Dynamic_Service_Dependency.cpp @@ -0,0 +1,51 @@ +#include "ace/ACE.h" +#include "ace/DLL_Manager.h" +#include "ace/Dynamic_Service_Dependency.h" +#include "ace/Service_Config.h" +#include "ace/Log_Msg.h" + +ACE_RCSID (ace, + Dynamic_Service_Dependency, + "$Id: Dynamic_Service_Dependency.cpp 80826 2008-03-04 14:51:23Z wotte $") + + + ACE_BEGIN_VERSIONED_NAMESPACE_DECL + + +ACE_Dynamic_Service_Dependency::ACE_Dynamic_Service_Dependency (const ACE_TCHAR *principal) +{ + this->init (ACE_Service_Config::current (), principal); +} + +ACE_Dynamic_Service_Dependency::ACE_Dynamic_Service_Dependency (const ACE_Service_Gestalt *cfg, + const ACE_TCHAR *principal) +{ + this->init (cfg, principal); +} + + +ACE_Dynamic_Service_Dependency::~ACE_Dynamic_Service_Dependency (void) +{ + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("(%P|%t) DSD, this=%@ - destroying\n"), + this)); +} + +void +ACE_Dynamic_Service_Dependency::init (const ACE_Service_Gestalt *cfg, + const ACE_TCHAR *principal) +{ + const ACE_Service_Type* st = + ACE_Dynamic_Service_Base::find_i (cfg, principal,false); + if (ACE::debug ()) + { + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("(%P|%t) DSD, this=%@ - creating dependency on "), this)); + st->dump (); + } + this->tracker_ = st->dll (); +} + + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Dynamic_Service_Dependency.h b/dep/acelite/ace/Dynamic_Service_Dependency.h new file mode 100644 index 00000000000..0f187d0037a --- /dev/null +++ b/dep/acelite/ace/Dynamic_Service_Dependency.h @@ -0,0 +1,70 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Dynamic_Service_Dependency.h + * + * $Id: Dynamic_Service_Dependency.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Iliyan Jeliazkov + */ +//============================================================================= + +#ifndef ACE_DYNAMIC_SERVICE_DEPENDENCY_H +#define ACE_DYNAMIC_SERVICE_DEPENDENCY_H + +#include /**/ "ace/pre.h" + + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Dynamic_Service_Base.h" +#include "ace/Service_Object.h" +#include "ace/DLL.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Dynamic_Service_Dependency + * + * @brief Provides a way to declare dependency on specific service, + * thus helping to avoid order of initialization issues with instances + * of an objects whose implementation code resides in dynamically loaded + * services. + * + * It is disastrous to have dynamically loadable services create and give away + * ownership of objects and then ending up being unloaded before all those + * instances have been deleted. Normally the code for such objects classes + * resides within the TEXT segment of the DLL, which implements the service. + * If a service gets removed, its DLL may be unmapped from memory and then + * any attempt to invoke a method on the said objects will cause SEGV. + * + * Such instances must contain a member of ACE_Dynamic_Service_Dependency + * initialized with the service they depend on. + * ACE_Dynamic_Service_Dependency's constructor and destructor are + * "magical" - they work by maintaining the underlying dynamic service's + * DLL reference count. + */ +class ACE_Export ACE_Dynamic_Service_Dependency +{ +public: + ACE_Dynamic_Service_Dependency (const ACE_Service_Gestalt *cfg, + const ACE_TCHAR *principal); + ACE_Dynamic_Service_Dependency (const ACE_TCHAR *principal); + ~ACE_Dynamic_Service_Dependency (void); + +private: + void init (const ACE_Service_Gestalt *cfg, const ACE_TCHAR *principal); + +private: + ACE_DLL tracker_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + + +#include /**/ "ace/post.h" + +#endif /* ACE_DYNAMIC_SERVICE_DEPENDENCY_H */ diff --git a/dep/acelite/ace/Encoding_Converter.cpp b/dep/acelite/ace/Encoding_Converter.cpp new file mode 100644 index 00000000000..b5fd2b35402 --- /dev/null +++ b/dep/acelite/ace/Encoding_Converter.cpp @@ -0,0 +1,12 @@ +// $Id: Encoding_Converter.cpp 80826 2008-03-04 14:51:23Z wotte $ +#include "ace/Encoding_Converter.h" + +#if defined (ACE_USES_WCHAR) +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_Encoding_Converter::~ACE_Encoding_Converter (void) +{ +} + +ACE_END_VERSIONED_NAMESPACE_DECL +#endif /* ACE_USES_WCHAR */ diff --git a/dep/acelite/ace/Encoding_Converter.h b/dep/acelite/ace/Encoding_Converter.h new file mode 100644 index 00000000000..34d22fa29a1 --- /dev/null +++ b/dep/acelite/ace/Encoding_Converter.h @@ -0,0 +1,70 @@ +// -*- C++ -*- + +//========================================================================= +/** + * @file Encoding_Converter.h + * + * $Id: Encoding_Converter.h 80826 2008-03-04 14:51:23Z wotte $ + * + * This class is the base class for all encoding converters that convert + * to and from UTF-8. + * + * @author Chad Elliott + */ +//========================================================================= + +#ifndef ACE_ENCODING_CONVERTER_H +#define ACE_ENCODING_CONVERTER_H + +#include /**/ "ace/pre.h" + +#include "ace/Basic_Types.h" + +#if defined (ACE_USES_WCHAR) +#include /**/ "ace/ACE_export.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** The base class for all ACE UTF Encoding Converters. + * This class provides a generic interface that is used to implement + * various UTF encoding conversion classes. + */ +class ACE_Export ACE_Encoding_Converter +{ +public: + /// This enum describes the various states that can be returned + /// from the to_utf8() and from_utf8() methods which depends on + /// both the source buffer and the size of the target buffer. + enum Result {CONVERSION_OK, + SOURCE_EXHAUSTED, + TARGET_EXHAUSTED, + SOURCE_ILLEGAL + }; + + /// This destructor is here (and virtual) because we have virtual + /// functions. + virtual ~ACE_Encoding_Converter (void); + + /// Convert the source (which can be in any encoding) to UTF-8 and + /// store it in the provided target buffer. + virtual Result to_utf8 (const void* source, + size_t source_size, + ACE_Byte* target, + size_t target_size, + bool strict = true) = 0; + + /// Convert the UTF-8 source into an alternate encoding and store it + /// in the provided target buffer. + virtual Result from_utf8 (const ACE_Byte* source, + size_t source_size, + void* target, + size_t target_size, + bool strict = true) = 0; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL +#endif /* ACE_USES_WCHAR */ + +#include /**/ "ace/post.h" + +#endif /* ACE_ENCODING_CONVERTER_H */ diff --git a/dep/acelite/ace/Encoding_Converter_Factory.cpp b/dep/acelite/ace/Encoding_Converter_Factory.cpp new file mode 100644 index 00000000000..f603ae3e893 --- /dev/null +++ b/dep/acelite/ace/Encoding_Converter_Factory.cpp @@ -0,0 +1,74 @@ +// $Id: Encoding_Converter_Factory.cpp 80826 2008-03-04 14:51:23Z wotte $ +#include "ace/Encoding_Converter_Factory.h" + +#if defined (ACE_USES_WCHAR) +#include "ace/UTF32_Encoding_Converter.h" +#include "ace/UTF16_Encoding_Converter.h" +#include "ace/UTF8_Encoding_Converter.h" +#include "ace/OS_Memory.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_Encoding_Converter* +ACE_Encoding_Converter_Factory::create ( + const ACE_Byte* source, + size_t source_size, + ACE_Encoding_Converter_Factory::Encoding_Hint hint) +{ +#if defined (ACE_BIG_ENDIAN) + bool const convert_for_bigendian = true; +#else + bool const convert_for_bigendian = false; +#endif /* ACE_BIG_ENDIAN */ + ACE_Encoding_Converter* converter = 0; + + switch (hint) + { + case ACE_UTF_32BE: + ACE_NEW_RETURN (converter, + ACE_UTF32_Encoding_Converter (!convert_for_bigendian), + 0); + break; + case ACE_UTF_32LE: + ACE_NEW_RETURN (converter, + ACE_UTF32_Encoding_Converter (convert_for_bigendian), + 0); + break; + case ACE_UTF_16BE: + ACE_NEW_RETURN (converter, + ACE_UTF16_Encoding_Converter (!convert_for_bigendian), + 0); + break; + case ACE_UTF_16LE: + ACE_NEW_RETURN (converter, + ACE_UTF16_Encoding_Converter (convert_for_bigendian), + 0); + break; + case ACE_UTF_8: + ACE_NEW_RETURN (converter, + ACE_UTF8_Encoding_Converter, + 0); + break; + default: + // First check for ASCII since much of ASCII text will appear to + // convert from UTF-16 to UTF-8. + converter = ACE_UTF8_Encoding_Converter::encoded (source, source_size); + if (converter != 0) + return converter; + + // Check for UTF-32 + converter = ACE_UTF32_Encoding_Converter::encoded (source, source_size); + if (converter != 0) + return converter; + + // Check for UTF-16 + converter = ACE_UTF16_Encoding_Converter::encoded (source, source_size); + if (converter != 0) + return converter; + } + + return converter; +} + +ACE_END_VERSIONED_NAMESPACE_DECL +#endif /* ACE_USES_WCHAR */ diff --git a/dep/acelite/ace/Encoding_Converter_Factory.h b/dep/acelite/ace/Encoding_Converter_Factory.h new file mode 100644 index 00000000000..1441c690bef --- /dev/null +++ b/dep/acelite/ace/Encoding_Converter_Factory.h @@ -0,0 +1,54 @@ +// -*- C++ -*- + +//========================================================================= +/** + * @file Encoding_Converter_Factory.h + * + * $Id: Encoding_Converter_Factory.h 80826 2008-03-04 14:51:23Z wotte $ + * + * This class can be used to create encoding converters of various types. + * + * @author Chad Elliott + */ +//========================================================================= + +#ifndef ACE_ENCODING_CONVERTER_FACTORY_H +#define ACE_ENCODING_CONVERTER_FACTORY_H + +#include /**/ "ace/pre.h" + +#include "ace/Basic_Types.h" + +#if defined (ACE_USES_WCHAR) +#include /**/ "ace/ACE_export.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +class ACE_Encoding_Converter; + +/** Create an encoding converter based on the source or hint. + * This class allows users to avoid knowing any concrete converter types. + */ +class ACE_Export ACE_Encoding_Converter_Factory +{ +public: + /// This enum is used to tell what type of converter to create. + enum Encoding_Hint { ACE_UTF_32BE, ACE_UTF_32LE, + ACE_UTF_16BE, ACE_UTF_16LE, + ACE_UTF_8, ACE_NONE + }; + + /// Create an encoding converter based on the source. If a hint is + /// given, it just creates the specified type of converter without looking + /// at the source. + static ACE_Encoding_Converter* create (const ACE_Byte* source, + size_t source_size, + Encoding_Hint hint = ACE_NONE); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL +#endif /* ACE_USES_WCHAR */ + +#include /**/ "ace/post.h" + +#endif /* ACE_ENCODING_CONVERTER_FACTORY_H */ diff --git a/dep/acelite/ace/Env_Value_T.cpp b/dep/acelite/ace/Env_Value_T.cpp new file mode 100644 index 00000000000..1997bbea484 --- /dev/null +++ b/dep/acelite/ace/Env_Value_T.cpp @@ -0,0 +1,12 @@ +// $Id: Env_Value_T.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#ifndef ACE_ENV_VALUE_T_CPP +#define ACE_ENV_VALUE_T_CPP + +#include "ace/Env_Value_T.h" + +#if ! defined (__ACE_INLINE__) +#include "ace/Env_Value_T.inl" +#endif /* __ACE_INLINE__ */ + +#endif /* ACE_ENV_VALUE_T_CPP */ diff --git a/dep/acelite/ace/Env_Value_T.h b/dep/acelite/ace/Env_Value_T.h new file mode 100644 index 00000000000..df2178a0f11 --- /dev/null +++ b/dep/acelite/ace/Env_Value_T.h @@ -0,0 +1,166 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Env_Value_T.h + * + * $Id: Env_Value_T.h 80826 2008-03-04 14:51:23Z wotte $ + * + * Template to encapsulate getting a value from an environment variable + * and using a supplied default value if not in the environment. + * + * + * @author Chris Cleeland (derived from work by Carlos O'Ryan) + */ +//============================================================================= + +#ifndef ACE_ENV_VALUE_T_H +#define ACE_ENV_VALUE_T_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" +#include "ace/Global_Macros.h" +#include "ace/OS_NS_stdlib.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Env_Value + * + * @brief Environment Variable Value + * + * Reads a variable from the user environment, providing a default + * value. + */ +template +class ACE_Env_Value +{ +public: + /** + * Default constructor which isn't bound to a specific environment + * variable name or a default value. Before being useful it must + * 'd. + */ + ACE_Env_Value (void); + + /// Constructor that calls . + ACE_Env_Value (const ACE_TCHAR *varname, + const T &vardefault); + + /// Destroy the value. + ~ACE_Env_Value (void); + + /// Returns the value as type T. + operator T (void); + + /// The constructor, read @a varname from the environment, using + /// @a defval as its value if it is not defined. + void open (const ACE_TCHAR *varname, const T &defval); + + /// Returns the name of the variable being tracked. + const ACE_TCHAR *varname (void) const; + +private: + /// Disallow copying and assignment. + ACE_UNIMPLEMENTED_FUNC (ACE_Env_Value(const ACE_Env_Value &)) + ACE_UNIMPLEMENTED_FUNC (ACE_Env_Value operator=(const ACE_Env_Value &)) + + void fetch_value (void); + + const ACE_TCHAR *varname_; + T value_; +}; + +/// Function to convert a string @a s into type @c T. +template void ACE_Convert (const ACE_TCHAR *s, T &t); + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Env_Value_T.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Env_Value_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template <> inline void +ACE_Convert (const ACE_TCHAR *s, ACE_TCHAR *&v) +{ + v = (ACE_TCHAR *) s; +} + +template <> inline void +ACE_Convert (const ACE_TCHAR *s, const ACE_TCHAR *&v) +{ + v = (const ACE_TCHAR *) s; +} + +template <> inline void +ACE_Convert (const ACE_TCHAR *s, short &si) +{ + si = static_cast (ACE_OS::strtol (s, 0, 10)); +} + +template <> inline void +ACE_Convert (const ACE_TCHAR *s, u_short &us) +{ + us = static_cast (ACE_OS::strtol (s, 0, 10)); +} + +template <> inline void +ACE_Convert (const ACE_TCHAR *s, u_int &i) +{ + i = static_cast (ACE_OS::strtol (s, 0, 10)); +} + +template <> inline void +ACE_Convert (const ACE_TCHAR *s, long &l) +{ + l = ACE_OS::strtol (s, 0, 10); +} + +template <> inline void +ACE_Convert (const ACE_TCHAR *s, int &i) +{ + i = static_cast (ACE_OS::strtol (s, 0, 10)); +} + +template <> inline void +ACE_Convert (const ACE_TCHAR *s, u_long &ul) +{ + ul = ACE_OS::strtoul (s, 0, 10); +} + +template <> inline void +ACE_Convert (const ACE_TCHAR *s, double &d) +{ + d = ACE_OS::strtod (s, 0); +} + +// Default calls a CTOR on type T of the form 'T::T(const char*)', but +// users can feel free to create their own specialized conversion +// functions if necessary, as shown above. Note that for 'char*' the +// default is used because a simple cast will be performed and no +// conversion will be necessary. +template inline void +ACE_Convert (const ACE_TCHAR *s, T &t) +{ + t = T (s); +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Env_Value_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" +#endif /* ACE_ENV_VALUE_T_H */ diff --git a/dep/acelite/ace/Env_Value_T.inl b/dep/acelite/ace/Env_Value_T.inl new file mode 100644 index 00000000000..d9af1b03164 --- /dev/null +++ b/dep/acelite/ace/Env_Value_T.inl @@ -0,0 +1,60 @@ +// $Id: Env_Value_T.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template ACE_INLINE +ACE_Env_Value::operator T (void) +{ + return value_; +} + +template ACE_INLINE +ACE_Env_Value::ACE_Env_Value (void) + : varname_ (0) +{ +} + +template ACE_INLINE +ACE_Env_Value::ACE_Env_Value (const ACE_TCHAR *varname, + const T &defval) + : varname_ (varname), + value_(defval) +{ + this->fetch_value (); +} + +template ACE_INLINE void +ACE_Env_Value::open (const ACE_TCHAR *varname, + const T &defval) +{ + this->varname_ = varname; + this->value_ = defval; + this->fetch_value (); +} + +template ACE_INLINE void +ACE_Env_Value::fetch_value (void) +{ +#if defined (ACE_WIN32) + const ACE_TCHAR *env = ACE_OS::getenv (this->varname_); + if (env != 0) + ACE_Convert (env, value_); +#else + char *nenv = ACE_OS::getenv (ACE_TEXT_ALWAYS_CHAR (this->varname_)); + if (nenv != 0) + ACE_Convert (ACE_TEXT_CHAR_TO_TCHAR (nenv), this->value_); +#endif +} + +template ACE_INLINE const ACE_TCHAR* +ACE_Env_Value::varname (void) const +{ + return this->varname_; +} + +template ACE_INLINE +ACE_Env_Value::~ACE_Env_Value (void) +{ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Event.cpp b/dep/acelite/ace/Event.cpp new file mode 100644 index 00000000000..ea5f86d99d1 --- /dev/null +++ b/dep/acelite/ace/Event.cpp @@ -0,0 +1,93 @@ +// $Id: Event.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Event.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Event.inl" +#endif /* __ACE_INLINE__ */ + +#include "ace/Log_Msg.h" + +ACE_RCSID(ace, Event, "$Id: Event.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_Event::ACE_Event (int manual_reset, + int initial_state, + int type, + const ACE_TCHAR *name, + void *arg, + LPSECURITY_ATTRIBUTES sa) + : removed_ (false) +{ + if (ACE_OS::event_init (&this->handle_, + manual_reset, + initial_state, + type, + name, + arg, + sa) != 0) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_Event::ACE_Event"))); +} + +ACE_Event::~ACE_Event (void) +{ + this->remove (); +} + +int +ACE_Event::remove (void) +{ + int result = 0; + if (!this->removed_) + { + this->removed_ = true; + result = ACE_OS::event_destroy (&this->handle_); + } + return result; +} + +int +ACE_Event::wait (void) +{ + return ACE_OS::event_wait (&this->handle_); +} + +int +ACE_Event::wait (const ACE_Time_Value *abstime, int use_absolute_time) +{ + return ACE_OS::event_timedwait (&this->handle_, + const_cast (abstime), + use_absolute_time); +} + +int +ACE_Event::signal (void) +{ + return ACE_OS::event_signal (&this->handle_); +} + +int +ACE_Event::pulse (void) +{ + return ACE_OS::event_pulse (&this->handle_); +} + +int +ACE_Event::reset (void) +{ + return ACE_OS::event_reset (&this->handle_); +} + +void +ACE_Event::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Event.h b/dep/acelite/ace/Event.h new file mode 100644 index 00000000000..887b504d8f9 --- /dev/null +++ b/dep/acelite/ace/Event.h @@ -0,0 +1,143 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file Event.h + * + * $Id: Event.h 80826 2008-03-04 14:51:23Z wotte $ + * + * Moved from Synch.h. + * + * @author Douglas C. Schmidt + */ +//========================================================================== + +#ifndef ACE_EVENT_H +#define ACE_EVENT_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/OS_NS_Thread.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Event + * + * @brief A wrapper around the Win32 event locking mechanism. + * + * Portable implementation of an Event mechanism, which is native to + * Win32, but must be emulated on UNIX. All platforms support + * process-scope locking support. However, only Win32 platforms + * support global naming and system-scope locking support. + */ +class ACE_Export ACE_Event +{ +public: + /// Constructor that creates event. + ACE_Event (int manual_reset = 0, + int initial_state = 0, + int type = USYNC_THREAD, + const ACE_TCHAR *name = 0, + void *arg = 0, + LPSECURITY_ATTRIBUTES sa = 0); + + /// Implicitly destroy the event variable. + ~ACE_Event (void); + + /** + * Explicitly destroy the event variable. Note that only one thread + * should call this method since it doesn't protect against race + * conditions. + */ + int remove (void); + + /// Underlying handle to event. + ACE_event_t handle (void) const; + + /** + * Set the underlying handle to event. Note that this method assumes + * ownership of the and will close it down in . If + * you want the to stay open when is called make + * sure to call on the before closing it. You are + * responsible for the closing the existing before + * overwriting it. + */ + void handle (ACE_event_t new_handle); + + /** + * if MANUAL reset + * sleep till the event becomes signaled + * event remains signaled after wait() completes. + * else AUTO reset + * sleep till the event becomes signaled + * event resets wait() completes. + */ + int wait (void); + + /// Same as wait() above, but this one can be timed + /// @a abstime is absolute time-of-day if if @a use_absolute_time + /// is non-0, else it is relative time. + int wait (const ACE_Time_Value *abstime, + int use_absolute_time = 1); + + /** + * if MANUAL reset + * wake up all waiting threads + * set to signaled state + * else AUTO reset + * if no thread is waiting, set to signaled state + * if thread(s) are waiting, wake up one waiting thread and + * reset event + */ + int signal (void); + + /** + * if MANUAL reset + * wakeup all waiting threads and + * reset event + * else AUTO reset + * wakeup one waiting thread (if present) and + * reset event + */ + int pulse (void); + + /// Set to nonsignaled state. + int reset (void); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks + ACE_ALLOC_HOOK_DECLARE; + +protected: + /// The underlying handle. + ACE_event_t handle_; + + /// Keeps track of whether has been called yet to avoid + /// multiple calls, e.g., explicitly and implicitly in the + /// destructor. This flag isn't protected by a lock, so make sure + /// that you don't have multiple threads simultaneously calling + /// on the same object, which is a bad idea anyway... + bool removed_; + +private: + // = Prevent copying. + ACE_Event (const ACE_Event& event); + const ACE_Event &operator= (const ACE_Event &rhs); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Event.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_EVENT_H */ diff --git a/dep/acelite/ace/Event.inl b/dep/acelite/ace/Event.inl new file mode 100644 index 00000000000..ae0805c95f0 --- /dev/null +++ b/dep/acelite/ace/Event.inl @@ -0,0 +1,18 @@ +// -*- C++ -*- +// $Id: Event.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE ACE_event_t +ACE_Event::handle (void) const +{ + return this->handle_; +} + +ACE_INLINE void +ACE_Event::handle (ACE_event_t new_handle) +{ + this->handle_ = new_handle; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Event_Handler.cpp b/dep/acelite/ace/Event_Handler.cpp new file mode 100644 index 00000000000..e04e8cb5d10 --- /dev/null +++ b/dep/acelite/ace/Event_Handler.cpp @@ -0,0 +1,394 @@ +// Event_Handler.cpp +// $Id: Event_Handler.cpp 85236 2009-05-01 11:43:56Z johnnyw $ + +#include "ace/Event_Handler.h" +#include "ace/OS_Errno.h" +#include "ace/Reactor.h" +#include "ace/Thread_Manager.h" +/* Need to see if ACE_HAS_BUILTIN_ATOMIC_OP defined */ +#include "ace/Atomic_Op.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Event_Handler.inl" +#endif /* __ACE_INLINE__ */ + +#include + +ACE_RCSID(ace, Event_Handler, "$Id: Event_Handler.cpp 85236 2009-05-01 11:43:56Z johnnyw $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Implement conceptually abstract virtual functions in the base class +// so derived classes don't have to implement unused ones. + +ACE_Event_Handler::ACE_Event_Handler (ACE_Reactor *r, + int p) + : reference_count_ (1), + priority_ (p), + reactor_ (r), + reference_counting_policy_ (Reference_Counting_Policy::DISABLED) +{ + // ACE_TRACE ("ACE_Event_Handler::ACE_Event_Handler"); +} + +ACE_Event_Handler::~ACE_Event_Handler (void) +{ + // ACE_TRACE ("ACE_Event_Handler::~ACE_Event_Handler"); +} + +// Gets the file descriptor associated with this I/O device. + +ACE_HANDLE +ACE_Event_Handler::get_handle (void) const +{ + ACE_TRACE ("ACE_Event_Handler::get_handle"); + return ACE_INVALID_HANDLE; +} + +// Sets the file descriptor associated with this I/O device. + +void +ACE_Event_Handler::set_handle (ACE_HANDLE) +{ + ACE_TRACE ("ACE_Event_Handler::set_handle"); +} + +// Gets the priority of this handler. + +int +ACE_Event_Handler::priority (void) const +{ + ACE_TRACE ("ACE_Event_Handler::priority"); + return this->priority_; +} + +// Sets the priority + +void +ACE_Event_Handler::priority (int priority) +{ + ACE_TRACE ("ACE_Event_Handler::priority"); + this->priority_ = priority; +} + +// Called when the object is about to be removed from the Dispatcher +// tables. + +int +ACE_Event_Handler::handle_close (ACE_HANDLE, ACE_Reactor_Mask) +{ + ACE_TRACE ("ACE_Event_Handler::handle_close"); + return -1; +} + +// Called when input becomes available on fd. + +int +ACE_Event_Handler::handle_input (ACE_HANDLE) +{ + ACE_TRACE ("ACE_Event_Handler::handle_input"); + return -1; +} + +// Called when output is possible on fd. + +int +ACE_Event_Handler::handle_output (ACE_HANDLE) +{ + ACE_TRACE ("ACE_Event_Handler::handle_output"); + return -1; +} + +// Called when urgent data is available on fd. + +int +ACE_Event_Handler::handle_exception (ACE_HANDLE) +{ + ACE_TRACE ("ACE_Event_Handler::handle_exception"); + return -1; +} + +// Called when timer expires, TV stores the current time. + +int +ACE_Event_Handler::handle_timeout (const ACE_Time_Value &, const void *) +{ + ACE_TRACE ("ACE_Event_Handler::handle_timeout"); + return -1; +} + +// Called when a monitored Process exits + +int +ACE_Event_Handler::handle_exit (ACE_Process *) +{ + ACE_TRACE ("ACE_Event_Handler::handle_exit"); + return -1; +} + +// Called when a registered signal occurs. + +int +ACE_Event_Handler::handle_signal (int, siginfo_t *, ucontext_t *) +{ + ACE_TRACE ("ACE_Event_Handler::handle_signal"); + return -1; +} + +int +ACE_Event_Handler::resume_handler (void) +{ + ACE_TRACE ("ACE_Event_Handler::resume_handler"); + + // Return a default value and allow the reactor to take care of + // resuming the handler + return ACE_Event_Handler::ACE_REACTOR_RESUMES_HANDLER; +} + + +int +ACE_Event_Handler::handle_qos (ACE_HANDLE) +{ + ACE_TRACE ("ACE_Event_Handler::handle_qos"); + return -1; +} + +int +ACE_Event_Handler::handle_group_qos (ACE_HANDLE) +{ + ACE_TRACE ("ACE_Event_Handler::handle_group_qos"); + return -1; +} + +void +ACE_Event_Handler::reactor (ACE_Reactor *reactor) +{ + ACE_TRACE ("ACE_Event_Handler::reactor"); + this->reactor_ = reactor; +} + +ACE_Reactor * +ACE_Event_Handler::reactor (void) const +{ + ACE_TRACE ("ACE_Event_Handler::reactor"); + return this->reactor_; +} + +ACE_Reactor_Timer_Interface * +ACE_Event_Handler::reactor_timer_interface (void) const +{ + ACE_TRACE ("ACE_Event_Handler::reactor_timer_interface"); + return this->reactor_; +} + +ACE_Event_Handler::Reference_Count +ACE_Event_Handler::add_reference (void) +{ + bool const reference_counting_required = + this->reference_counting_policy ().value () == + ACE_Event_Handler::Reference_Counting_Policy::ENABLED; + + if (reference_counting_required) + return ++this->reference_count_; + else + return 1; +} + +ACE_Event_Handler::Reference_Count +ACE_Event_Handler::remove_reference (void) +{ + bool const reference_counting_required = + this->reference_counting_policy ().value () == + ACE_Event_Handler::Reference_Counting_Policy::ENABLED; + + if (reference_counting_required) + { + Reference_Count result = + --this->reference_count_; + + if (result == 0) + delete this; + + return result; + } + else + { + return 1; + } +} + +ACE_Event_Handler::Policy::~Policy (void) +{ +} + +ACE_Event_Handler::Reference_Counting_Policy::Reference_Counting_Policy (Reference_Counting_Policy::Value value) + : value_ (value) +{ +} + +ACE_Event_Handler::Reference_Counting_Policy::Value +ACE_Event_Handler::Reference_Counting_Policy::value (void) const +{ + return this->value_; +} + +void +ACE_Event_Handler::Reference_Counting_Policy::value (ACE_Event_Handler::Reference_Counting_Policy::Value value) +{ + this->value_ = value; +} + +ACE_Event_Handler::Reference_Counting_Policy & +ACE_Event_Handler::reference_counting_policy (void) +{ + return this->reference_counting_policy_; +} + +ACE_THR_FUNC_RETURN +ACE_Event_Handler::read_adapter (void *args) +{ + ACE_Event_Handler *this_ptr = static_cast (args); + ACE_Reactor *r = this_ptr->reactor (); + + while (this_ptr->handle_input (ACE_STDIN) != -1) + continue; + + this_ptr->handle_close (ACE_STDIN, ACE_Event_Handler::READ_MASK); + // It's possible for handle_close() to "delete this" so we need to + // cache the reactor pointer and use it here. + r->notify (); + + return 0; +} + +int +ACE_Event_Handler::register_stdin_handler (ACE_Event_Handler *eh, + ACE_Reactor *reactor, + ACE_Thread_Manager *thr_mgr, + int flags) +{ +#if defined (ACE_WIN32) + ACE_UNUSED_ARG (reactor); + + eh->reactor (reactor); + return thr_mgr->spawn (&read_adapter, static_cast (eh), flags); +#else + // Keep compilers happy. + ACE_UNUSED_ARG (flags); + ACE_UNUSED_ARG (thr_mgr); + return reactor->register_handler (ACE_STDIN, + eh, + ACE_Event_Handler::READ_MASK); +#endif /* ACE_WIN32 */ +} + +int +ACE_Event_Handler::remove_stdin_handler (ACE_Reactor *reactor, + ACE_Thread_Manager * /* thr_mgr */) +{ +#if defined (ACE_WIN32) + ACE_UNUSED_ARG (reactor); + + // What should we do here? + ACE_NOTSUP_RETURN (-1); +#else + return reactor->remove_handler (ACE_STDIN, + ACE_Event_Handler::READ_MASK); +#endif /* ACE_WIN32 */ +} + +// --------------------------------------------------------------------- + +ACE_Event_Handler_var::ACE_Event_Handler_var (void) + : ptr_ (0) +{ +} + +ACE_Event_Handler_var::ACE_Event_Handler_var (ACE_Event_Handler *p) + : ptr_ (p) +{ +} + +ACE_Event_Handler_var::ACE_Event_Handler_var (const ACE_Event_Handler_var &b) + : ptr_ (b.ptr_) +{ + if (this->ptr_ != 0) + { + this->ptr_->add_reference (); + } +} + +ACE_Event_Handler_var::~ACE_Event_Handler_var (void) +{ + if (this->ptr_ != 0) + { + ACE_Errno_Guard eguard (errno); + this->ptr_->remove_reference (); + } +} + +ACE_Event_Handler_var & +ACE_Event_Handler_var::operator= (ACE_Event_Handler *p) +{ + if (this->ptr_ != p) + { + ACE_Event_Handler_var tmp (p); + std::swap (this->ptr_, tmp.ptr_); + } + + return *this; +} + +ACE_Event_Handler_var & +ACE_Event_Handler_var::operator= (const ACE_Event_Handler_var &b) +{ + ACE_Event_Handler_var tmp (b); + std::swap (this->ptr_, tmp.ptr_); + + return *this; +} + +ACE_Event_Handler * +ACE_Event_Handler_var::operator->() const +{ + return this->ptr_; +} + +ACE_Event_Handler * +ACE_Event_Handler_var::handler (void) const +{ + return this->ptr_; +} + +ACE_Event_Handler * +ACE_Event_Handler_var::release (void) +{ + ACE_Event_Handler * const old = this->ptr_; + this->ptr_ = 0; + return old; +} + +void +ACE_Event_Handler_var::reset (ACE_Event_Handler *p) +{ + *this = p; +} + +// --------------------------------------------------------------------- + +ACE_Notification_Buffer::ACE_Notification_Buffer (void) + : eh_ (0), + mask_ (ACE_Event_Handler::NULL_MASK) +{ + ACE_TRACE ("ACE_Notification_Buffer::ACE_Notification_Buffer"); +} + +ACE_Notification_Buffer::ACE_Notification_Buffer (ACE_Event_Handler *eh, + ACE_Reactor_Mask mask) + : eh_ (eh), + mask_ (mask) +{ + ACE_TRACE ("ACE_Notification_Buffer::ACE_Notification_Buffer"); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Event_Handler.h b/dep/acelite/ace/Event_Handler.h new file mode 100644 index 00000000000..417f78578e7 --- /dev/null +++ b/dep/acelite/ace/Event_Handler.h @@ -0,0 +1,389 @@ +/* -*- C++ -*- */ + +//========================================================================== +/** + * @file Event_Handler.h + * + * $Id: Event_Handler.h 91066 2010-07-12 11:05:04Z johnnyw $ + * + * @author Douglas C. Schmidt + */ +//========================================================================== + +#ifndef ACE_EVENT_HANDLER_H +#define ACE_EVENT_HANDLER_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/os_signal.h" +#include "ace/Atomic_Op.h" +#include "ace/Synch_Traits.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Forward declaration. +class ACE_Message_Block; +class ACE_Reactor; +class ACE_Reactor_Timer_Interface; +class ACE_Thread_Manager; +class ACE_Process; + +typedef unsigned long ACE_Reactor_Mask; + +/** + * @class ACE_Event_Handler + * + * @brief + * Provides an abstract interface for handling various types of + * I/O, timer, and signal events. + * + * Subclasses read/write input/output on an I/O descriptor, + * handle an exception raised on an I/O descriptor, handle a + * timer's expiration, or handle a signal. + */ +class ACE_Export ACE_Event_Handler +{ +public: + enum + { + LO_PRIORITY = 0, + HI_PRIORITY = 10, + NULL_MASK = 0, +#if defined (ACE_USE_POLL) + READ_MASK = POLLIN, + WRITE_MASK = POLLOUT, + EXCEPT_MASK = POLLPRI, +#else /* USE SELECT */ + READ_MASK = (1 << 0), + WRITE_MASK = (1 << 1), + EXCEPT_MASK = (1 << 2), +#endif /* ACE_USE_POLL */ + ACCEPT_MASK = (1 << 3), + CONNECT_MASK = (1 << 4), + TIMER_MASK = (1 << 5), + QOS_MASK = (1 << 6), + GROUP_QOS_MASK = (1 << 7), + SIGNAL_MASK = (1 << 8), + ALL_EVENTS_MASK = READ_MASK | + WRITE_MASK | + EXCEPT_MASK | + ACCEPT_MASK | + CONNECT_MASK | + TIMER_MASK | + QOS_MASK | + GROUP_QOS_MASK | + SIGNAL_MASK, + RWE_MASK = READ_MASK | + WRITE_MASK | + EXCEPT_MASK, + DONT_CALL = (1 << 9) + }; + + /// Destructor is virtual to enable proper cleanup. + virtual ~ACE_Event_Handler (void); + + /// Get the I/O handle. + virtual ACE_HANDLE get_handle (void) const; + + /// Set the I/O handle. + virtual void set_handle (ACE_HANDLE); + + // = Get/set priority + + /// Get the priority of the Event_Handler. + /// @note Priorities run from MIN_PRIORITY (which is the "lowest priority") + /// to MAX_PRIORITY (which is the "highest priority"). + virtual int priority (void) const; + + /// Set the priority of the Event_Handler. + virtual void priority (int priority); + + /// Called when input events occur (e.g., connection or data). + virtual int handle_input (ACE_HANDLE fd = ACE_INVALID_HANDLE); + + /// Called when output events are possible (e.g., when flow control + /// abates or non-blocking connection completes). + virtual int handle_output (ACE_HANDLE fd = ACE_INVALID_HANDLE); + + /// Called when an exceptional events occur (e.g., SIGURG). + virtual int handle_exception (ACE_HANDLE fd = ACE_INVALID_HANDLE); + + /** + * Called when timer expires. @a current_time represents the current + * time that the Event_Handler was selected for timeout + * dispatching and @a act is the asynchronous completion token that + * was passed in when was invoked. + */ + virtual int handle_timeout (const ACE_Time_Value ¤t_time, + const void *act = 0); + + /// Called when a process exits. + virtual int handle_exit (ACE_Process *); + + /// Called when a method returns -1 or when the + /// method is called on an ACE_Reactor. The + /// @a close_mask indicates which event has triggered the + /// method callback on a particular @a handle. + virtual int handle_close (ACE_HANDLE handle, + ACE_Reactor_Mask close_mask); + + /// Called when object is signaled by OS (either via UNIX signals or + /// when a Win32 object becomes signaled). + virtual int handle_signal (int signum, siginfo_t * = 0, ucontext_t * = 0); + + enum + { + /// The handler is not resumed at all. Could lead to deadlock.. + ACE_EVENT_HANDLER_NOT_RESUMED = -1, + /// The reactor takes responsibility of resuming the handler and + /// is the default + ACE_REACTOR_RESUMES_HANDLER = 0, + /// The application takes responsibility of resuming the handler + ACE_APPLICATION_RESUMES_HANDLER + }; + /** + * Called to figure out whether the handler needs to resumed by the + * reactor or the application can take care of it. The default + * value of 0 would be returned which would allow the reactor to + * take care of resumption of the handler. The application can + * return a value more than zero and decide to resume the handler + * themseleves. + * + * @note This method has an affect only when used with the + * ACE_Dev_Poll_Reactor (and then, only on Linux) or the ACE_TP_Reactor. + */ + virtual int resume_handler (void); + + virtual int handle_qos (ACE_HANDLE = ACE_INVALID_HANDLE); + virtual int handle_group_qos (ACE_HANDLE = ACE_INVALID_HANDLE); + + // = Accessors to set/get the various event demultiplexors. + /// Set the event demultiplexors. + virtual void reactor (ACE_Reactor *reactor); + + /// Get the event demultiplexors. + virtual ACE_Reactor *reactor (void) const; + + /// Get only the reactor's timer related interface. + virtual ACE_Reactor_Timer_Interface *reactor_timer_interface (void) const; + + /** + * Used to read from non-socket ACE_HANDLEs in our own thread to + * work around Win32 limitations that don't allow us to 'able on + * Win32. + */ + static int register_stdin_handler (ACE_Event_Handler *eh, + ACE_Reactor *reactor, + ACE_Thread_Manager *thr_mgr, + int flags = THR_DETACHED); + + /// Performs the inverse of the register_stdin_handler() method. + static int remove_stdin_handler (ACE_Reactor *reactor, + ACE_Thread_Manager *thr_mgr); + + /// Reference count type. + typedef long Reference_Count; + + /// Increment reference count on the handler. + /** + * This method is called when the handler is registered with the + * Reactor and when the Reactor makes an upcall on the handler. + * Reference count is 1 when the handler is created. + * + * @return Current reference count. + */ + virtual Reference_Count add_reference (void); + + /// Decrement reference count on the handler. + /** + * This method is called when the handler is removed from the + * Reactor and when an upcall made on the handler by the Reactor + * completes. Handler is deleted when the reference count reaches + * 0. + * + * @return Current reference count. + */ + virtual Reference_Count remove_reference (void); + + /** + * @class Policy + * + * @brief Base class for all handler policies. + */ + class ACE_Export Policy + { + + public: + + /// Virtual destructor. + virtual ~Policy (void); + }; + + /** + * @class Reference_Counting_Policy + * + * @brief + * This policy dictates the reference counting requirements + * for the handler. + * + * This policy allows applications to configure whether it wants the + * Reactor to call add_reference() and remove_reference() during + * registrations, removals, and upcalls. + * + * Default: DISABLED. + */ + class ACE_Export Reference_Counting_Policy : public Policy + { + /// This policy can only be created by the handler. + friend class ACE_Event_Handler; + + public: + + enum Value + { + /// Perform reference counting. + ENABLED, + /// Don't perform reference counting. + DISABLED + }; + + /// Current Reference_Counting_Policy. + Value value (void) const; + + /// Update Reference_Counting_Policy. + void value (Value value); + + private: + + /// Private constructor. + Reference_Counting_Policy (Value value); + + /// The value of the policy. + Value value_; + }; + + /// Current Reference_Counting_Policy. + Reference_Counting_Policy &reference_counting_policy (void); + +protected: + /// Force ACE_Event_Handler to be an abstract base class. + ACE_Event_Handler (ACE_Reactor * = 0, + int priority = ACE_Event_Handler::LO_PRIORITY); + + /// Typedef for implementation of reference counting. + typedef ACE_Atomic_Op Atomic_Reference_Count; + + /// Reference count. + Atomic_Reference_Count reference_count_; + +private: + + /// Priority of this Event_Handler. + int priority_; + + /// Pointer to the various event demultiplexors. + ACE_Reactor *reactor_; + + /// Reference counting requirements. + Reference_Counting_Policy reference_counting_policy_; +}; + +/** + * @class ACE_Event_Handler_var + * + * @brief Auto pointer like class for Event Handlers. + * + * Used to manage lifecycle of handlers. This class calls + * ACE_Event_Handler::remove_reference() in its destructor. + */ +class ACE_Export ACE_Event_Handler_var +{ + +public: + + /// Default constructor. + ACE_Event_Handler_var (void); + + /// Construct with a handler. + ACE_Event_Handler_var (ACE_Event_Handler *p); + + /// Copy constructor. + ACE_Event_Handler_var (const ACE_Event_Handler_var &b); + + /// Destructor. + ~ACE_Event_Handler_var (void); + + /// Assignment to a handler. + ACE_Event_Handler_var &operator= (ACE_Event_Handler *p); + + /// Assignment to a ACE_Event_Handler_var. + ACE_Event_Handler_var &operator= (const ACE_Event_Handler_var &b); + + /// Overloaded "->". + ACE_Event_Handler *operator-> () const; + + /// Access the handler. + ACE_Event_Handler *handler (void) const; + + /// Release the handler. + ACE_Event_Handler *release (void); + + /// Reset the handler. + void reset (ACE_Event_Handler *p = 0); + +private: + + /// Handler. + ACE_Event_Handler *ptr_; +}; + +/** + * @class ACE_Notification_Buffer + * + * @brief Simple wrapper for passing s and + * ACE_Reactor_Masks between threads. + */ +class ACE_Export ACE_Notification_Buffer +{ +public: + ACE_Notification_Buffer (void); + + ACE_Notification_Buffer (ACE_Event_Handler *eh, + ACE_Reactor_Mask mask); + + /// Default dtor. + ~ACE_Notification_Buffer (void); + + /// Pointer to the Event_Handler that will be dispatched + /// by the main event loop. + ACE_Event_Handler *eh_; + + /// Mask that indicates which method to call. + ACE_Reactor_Mask mask_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Event_Handler.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_EVENT_HANDLER_H */ diff --git a/dep/acelite/ace/Event_Handler.inl b/dep/acelite/ace/Event_Handler.inl new file mode 100644 index 00000000000..d97c45466ae --- /dev/null +++ b/dep/acelite/ace/Event_Handler.inl @@ -0,0 +1,12 @@ +// -*- C++ -*- +// +// $Id: Event_Handler.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE +ACE_Notification_Buffer::~ACE_Notification_Buffer (void) +{ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Event_Handler_T.cpp b/dep/acelite/ace/Event_Handler_T.cpp new file mode 100644 index 00000000000..45d9d4e2767 --- /dev/null +++ b/dep/acelite/ace/Event_Handler_T.cpp @@ -0,0 +1,125 @@ +// Event_Handler_T.cpp +// +// $Id: Event_Handler_T.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#ifndef ACE_EVENT_HANDLER_T_CPP +#define ACE_EVENT_HANDLER_T_CPP + +#include "ace/Event_Handler_T.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_TEMPLATE_TYPEDEFS) + +#if !defined (__ACE_INLINE__) +#include "ace/Event_Handler_T.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Event_Handler_T) + +template void +ACE_Event_Handler_T::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Event_Handler_T::dump"); +#endif /* ACE_HAS_DUMP */ +} + +template +ACE_Event_Handler_T::~ACE_Event_Handler_T (void) +{ + ACE_TRACE ("ACE_Event_Handler_T::~ACE_Event_Handler_T"); + if (this->delete_handler_) + delete this->op_handler_; +} + +template +ACE_Event_Handler_T::ACE_Event_Handler_T (T *op_handler, int delete_handler, + GET_HANDLE get_handle, + IO_HANDLER input_h, + CL_HANDLER close_h, + SIG_HANDLER sig_h, + TO_HANDLER timeout_h, + IO_HANDLER output_h, + SET_HANDLE set_handle, + IO_HANDLER except_h) + : op_handler_ (op_handler), + input_handler_ (input_h), + output_handler_ (output_h), + except_handler_ (except_h), + to_handler_ (timeout_h), + cl_handler_ (close_h), + sig_handler_ (sig_h), + delete_handler_ (delete_handler), + set_handle_ (set_handle), + get_handle_ (get_handle) +{ + ACE_TRACE ("ACE_Event_Handler_T::ACE_Event_Handler_T"); +} + +template ACE_HANDLE +ACE_Event_Handler_T::get_handle (void) const +{ + ACE_TRACE ("ACE_Event_Handler_T::get_handle"); + return this->get_handle_ == 0 ? ACE_INVALID_HANDLE : (this->op_handler_->*get_handle_) (); +} + +template void +ACE_Event_Handler_T::set_handle (ACE_HANDLE h) +{ + ACE_TRACE ("ACE_Event_Handler_T::set_handle"); + if (this->set_handle_ != 0) + (this->op_handler_->*set_handle_) (h); +} + +template int +ACE_Event_Handler_T::handle_input (ACE_HANDLE fd) +{ + ACE_TRACE ("ACE_Event_Handler_T::handle_input"); + return this->input_handler_ == 0 ? 0 : (this->op_handler_->*input_handler_) (fd); +} + +template int +ACE_Event_Handler_T::handle_output (ACE_HANDLE fd) +{ + ACE_TRACE ("ACE_Event_Handler_T::handle_output"); + return this->output_handler_ == 0 ? 0 : (this->op_handler_->*output_handler_) (fd); +} + +template int +ACE_Event_Handler_T::handle_exception (ACE_HANDLE fd) +{ + ACE_TRACE ("ACE_Event_Handler_T::handle_exception"); + return this->except_handler_ == 0 ? 0 : (this->op_handler_->*except_handler_) (fd); +} + +template int +ACE_Event_Handler_T::handle_timeout (const ACE_Time_Value &tv, const void *arg) +{ + ACE_TRACE ("ACE_Event_Handler_T::handle_timeout"); + return this->to_handler_ == 0 ? 0 : (this->op_handler_->*to_handler_) (tv, arg); +} + +template int +ACE_Event_Handler_T::handle_close (ACE_HANDLE fd, ACE_Reactor_Mask close_mask) +{ + ACE_TRACE ("ACE_Event_Handler_T::handle_close"); + return this->cl_handler_ == 0 ? 0 : (this->op_handler_->*cl_handler_) (fd, close_mask); +} + +template int +ACE_Event_Handler_T::handle_signal (int signum, siginfo_t *s, ucontext_t *u) +{ + ACE_TRACE ("ACE_Event_Handler_T::handle_signal"); + return this->sig_handler_ == 0 ? 0 : (this->op_handler_->*sig_handler_) (signum, s, u); +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_TEMPLATE_TYPEDEFS */ + +#endif /* ACE_EVENT_HANDLER_T_CPP */ diff --git a/dep/acelite/ace/Event_Handler_T.h b/dep/acelite/ace/Event_Handler_T.h new file mode 100644 index 00000000000..d86ac333221 --- /dev/null +++ b/dep/acelite/ace/Event_Handler_T.h @@ -0,0 +1,191 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file Event_Handler_T.h + * + * $Id: Event_Handler_T.h 83891 2008-11-28 11:01:50Z johnnyw $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_EVENT_HANDLER_T_H +#define ACE_EVENT_HANDLER_T_H +#include /**/ "ace/pre.h" + +#include "ace/Event_Handler.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_TEMPLATE_TYPEDEFS) + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Event_Handler_T + * + * @brief Enable a class that doesn't inherit from the + * ACE_Event_Handler to be incorporated into the ACE_Reactor + * framework. Thanks to Greg Lavender (g.lavender@isode.com) + * for sharing this idea. + * + * It is sometimes the case that an application has a hierarchy + * of operation dispatcher classes that have their own + * inheritance hierarchy but also would like to integrate with + * the ACE_Reactor. Rather than adopt a "mixin" approach, it is + * often cleaner to define a template as a subclass of + * ACE_Event_Handler and parameterize it with an operation + * dispatcher type. + * When constructing an instantiation of the ACE_Event_Handler_T + * object, a set of pointers to member functions must be + * provided so that when one of the handle_* methods is called + * by the ACE_Reactor, the appropriate method is called on the + * underlying operations object. This is done since in some + * cases it is useful to map any event that happens to the same + * method on an object. + * The ACE_Event_Handler_T template is instantiated by an + * operations object and registered with the ACE_Reactor, and it + * then calls the appropriate op_handler. So, it's basically + * just another level of indirection in event dispatching. The + * coupling betweent the ultimate handler of the event and the + * ACE_Event_Handler class is relaxed a bit by have this + * intermediate object of type around. The + * client object can then dynamically change the bindings for + * the various handlers so that during the life of one of the + * operation objects, it can change how it wants events to be + * handled. It just instantiates a new instance of the template + * with different bindings and reregisters this new object with + * the ACE_Reactor. + */ +template +class ACE_Event_Handler_T : public ACE_Event_Handler +{ +public: + // = Typedefs to simplify pointer-to-member-function registration. + + // Get/set the underlying handle. + typedef ACE_HANDLE (T::*GET_HANDLE) (void) const; + typedef void (T::*SET_HANDLE) (ACE_HANDLE); + + /// Handle I/O events. + typedef int (T::*IO_HANDLER) (ACE_HANDLE); + + /// Handle timeout events. + typedef int (T::*TO_HANDLER) (const ACE_Time_Value &, const void *); + + /// Handle close events. + typedef int (T::*CL_HANDLER) (ACE_HANDLE, ACE_Reactor_Mask); + + /// = Initialization and termination methods. + typedef int (T::*SIG_HANDLER) (int, siginfo_t*, ucontext_t*); + + /// Initialize the op_handler. + ACE_Event_Handler_T (T *op_handler, + int delete_handler, + GET_HANDLE get_handle = 0, + IO_HANDLER input = 0, + CL_HANDLER close = 0, + SIG_HANDLER sig = 0, + TO_HANDLER timeout = 0, + IO_HANDLER output = 0, + SET_HANDLE set_handle = 0, + IO_HANDLER except = 0); + + /// Close down and delete the + ~ACE_Event_Handler_T (void); + + // = Override all the ACE_Event_Handler methods. + + // These methods all delegate down to the operations handler. + virtual ACE_HANDLE get_handle (void) const; + virtual void set_handle (ACE_HANDLE); + virtual int handle_input (ACE_HANDLE fd = ACE_INVALID_HANDLE); + virtual int handle_output (ACE_HANDLE fd = ACE_INVALID_HANDLE); + virtual int handle_exception (ACE_HANDLE fd = ACE_INVALID_HANDLE); + virtual int handle_timeout (const ACE_Time_Value &tv, const void *arg = 0); + virtual int handle_close (ACE_HANDLE fd, ACE_Reactor_Mask close_mask); + virtual int handle_signal (int signum, siginfo_t * = 0, ucontext_t * = 0); + + // = Get/set the operations handler. + T *op_handler (void); + void op_handler (T *); + + // = Get/set the target pointer-to-method used for dispatching. + + GET_HANDLE handle_get (void); + void handle_get (GET_HANDLE); + + SET_HANDLE handle_set (void); + void handle_set (SET_HANDLE); + + IO_HANDLER input_handler (void); + void input_handler (IO_HANDLER); + + IO_HANDLER output_handler (void); + void output_handler (IO_HANDLER); + + IO_HANDLER except_handler (void); + void except_handler (IO_HANDLER); + + TO_HANDLER to_handler (void); + void to_handler (TO_HANDLER); + + CL_HANDLER cl_handler (void); + void cl_handler (CL_HANDLER); + + SIG_HANDLER sig_handler (void); + void sig_handler (SIG_HANDLER); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + /// Pointer to the object that handles all the delegated operations. + T *op_handler_; + + // = Handle input, output, and exception events. + IO_HANDLER input_handler_; + IO_HANDLER output_handler_; + IO_HANDLER except_handler_; + + /// Handle timeout events. + TO_HANDLER to_handler_; + + /// Handle close events. + CL_HANDLER cl_handler_; + + /// Handle signal events. + SIG_HANDLER sig_handler_; + + /// Keeps track of whether we need to delete the handler in the + /// destructor. + int delete_handler_; + + // = Get/set underlying handle. + SET_HANDLE set_handle_; + GET_HANDLE get_handle_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Event_Handler_T.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Event_Handler_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Event_Handler_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#endif /* ACE_HAS_TEMPLATE_TYPEDEFS */ +#include /**/ "ace/post.h" +#endif /* ACE_EVENT_HANDLER_H */ diff --git a/dep/acelite/ace/Event_Handler_T.inl b/dep/acelite/ace/Event_Handler_T.inl new file mode 100644 index 00000000000..40db43e8e23 --- /dev/null +++ b/dep/acelite/ace/Event_Handler_T.inl @@ -0,0 +1,135 @@ +// -*- C++ -*- +// +// $Id: Event_Handler_T.inl 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Global_Macros.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template ACE_INLINE void +ACE_Event_Handler_T::op_handler (T *op) +{ + ACE_TRACE ("ACE_Event_Handler_T::op_handler"); + this->op_handler_ = op; +} + +template ACE_INLINE T * +ACE_Event_Handler_T::op_handler (void) +{ + ACE_TRACE ("ACE_Event_Handler_T::op_handler"); + return this->op_handler_; +} + +template ACE_INLINE typename ACE_Event_Handler_T::GET_HANDLE +ACE_Event_Handler_T::handle_get (void) +{ + ACE_TRACE ("ACE_Event_Handler_T::handle_get"); + return this->get_handle_; +} + +template ACE_INLINE void +ACE_Event_Handler_T::handle_get (typename ACE_Event_Handler_T::GET_HANDLE h) +{ + ACE_TRACE ("ACE_Event_Handler_T::handle_get"); + this->get_handle_ = h; +} + +template ACE_INLINE typename ACE_Event_Handler_T::SET_HANDLE +ACE_Event_Handler_T::handle_set (void) +{ + ACE_TRACE ("ACE_Event_Handler_T::handle_set"); + return this->set_handle_; +} + +template ACE_INLINE void +ACE_Event_Handler_T::handle_set (typename ACE_Event_Handler_T::SET_HANDLE h) +{ + ACE_TRACE ("ACE_Event_Handler_T::handle_set"); + this->set_handle_ = h; +} + +template ACE_INLINE typename ACE_Event_Handler_T::IO_HANDLER +ACE_Event_Handler_T::input_handler (void) +{ + ACE_TRACE ("ACE_Event_Handler_T::input_handler"); + return this->input_handler_; +} + +template ACE_INLINE void +ACE_Event_Handler_T::input_handler (typename ACE_Event_Handler_T::IO_HANDLER h) +{ + ACE_TRACE ("ACE_Event_Handler_T::input_handler"); + this->input_handler_ = h; +} + +template ACE_INLINE typename ACE_Event_Handler_T::IO_HANDLER +ACE_Event_Handler_T::output_handler (void) +{ + ACE_TRACE ("ACE_Event_Handler_T::output_handler"); + return this->output_handler_; +} + +template ACE_INLINE void +ACE_Event_Handler_T::output_handler (typename ACE_Event_Handler_T::IO_HANDLER h) +{ + ACE_TRACE ("ACE_Event_Handler_T::output_handler"); + this->output_handler_ = h; +} + +template ACE_INLINE typename ACE_Event_Handler_T::IO_HANDLER +ACE_Event_Handler_T::except_handler (void) +{ + ACE_TRACE ("ACE_Event_Handler_T::except_handler"); + return this->except_handler_; +} + +template ACE_INLINE void +ACE_Event_Handler_T::except_handler (typename ACE_Event_Handler_T::IO_HANDLER h) +{ + ACE_TRACE ("ACE_Event_Handler_T::except_handler"); + this->except_handler_ = h; +} + +template ACE_INLINE typename ACE_Event_Handler_T::TO_HANDLER +ACE_Event_Handler_T::to_handler (void) +{ + ACE_TRACE ("ACE_Event_Handler_T::to_handler"); + return this->to_handler_; +} + +template ACE_INLINE void +ACE_Event_Handler_T::to_handler (typename ACE_Event_Handler_T::TO_HANDLER h) +{ + ACE_TRACE ("ACE_Event_Handler_T::to_handler"); + this->to_handler_ = h; +} + +template ACE_INLINE typename ACE_Event_Handler_T::CL_HANDLER +ACE_Event_Handler_T::cl_handler (void) +{ + ACE_TRACE ("ACE_Event_Handler_T::cl_handler"); + return this->cl_handler_; +} + +template ACE_INLINE void +ACE_Event_Handler_T::cl_handler (typename ACE_Event_Handler_T::CL_HANDLER h) +{ + ACE_TRACE ("ACE_Event_Handler_T::cl_handler"); + this->cl_handler_ = h; +} + +template ACE_INLINE typename ACE_Event_Handler_T::SIG_HANDLER +ACE_Event_Handler_T::sig_handler (void) +{ + ACE_TRACE ("ACE_Event_Handler_T::sig_handler"); + return this->sig_handler_; +} + +template ACE_INLINE void +ACE_Event_Handler_T::sig_handler (typename ACE_Event_Handler_T::SIG_HANDLER h) +{ + ACE_TRACE ("ACE_Event_Handler_T::sig_handler"); + this->sig_handler_ = h; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Exception_Macros.h b/dep/acelite/ace/Exception_Macros.h new file mode 100644 index 00000000000..bb74b1a2129 --- /dev/null +++ b/dep/acelite/ace/Exception_Macros.h @@ -0,0 +1,55 @@ +// -*- C++ -*- + +// ============================================================================ +/** + * @file Exception_Macros.h + * + * $Id: Exception_Macros.h 80826 2008-03-04 14:51:23Z wotte $ + * + * Writing code that is portable between platforms with or without + * native C++ exceptions is hard. The following macros offer some + * help on this task. + * + * @author Nanbor Wang + * @author Aniruddha Gokhale + * @author Carlos O'Ryan + * @author Krishnakumar B , et al. + */ +// ============================================================================ + +// Macros for handling exceptions. + +#ifndef ACE_EXCEPTION_MACROS_H +#define ACE_EXCEPTION_MACROS_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +# if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +# endif /* ACE_LACKS_PRAGMA_ONCE */ + +// By default, if the compiler supports native exception handling, assume +// CORBA also support native exception handling. But it can be disabled by +// defining ACE_CORBA_HAS_EXCEPTIONS=0. If the compiler does not support +// exceptions handling, make sure native exception handling is disabled. +#if defined (ACE_HAS_EXCEPTIONS) +# if defined (ACE_CORBA_HAS_EXCEPTIONS) +# if (ACE_CORBA_HAS_EXCEPTIONS == 0) +# undef ACE_USES_NATIVE_EXCEPTIONS +# else /* ACE_CORBA_HAS_EXCEPTIONS != 0 */ +# define ACE_USES_NATIVE_EXCEPTIONS +# endif /* ACE_CORBA_HAS_EXCEPTIONS == 0 */ +# else +# define ACE_USES_NATIVE_EXCEPTIONS +# define ACE_CORBA_HAS_EXCEPTIONS +# endif /* ACE_CORBA_HAS_EXCEPTIONS */ +#else /* ! ACE_HAS_EXCEPTIONS */ +# undef ACE_CORBA_HAS_EXCEPTIONS +# undef ACE_USES_NATIVE_EXCEPTIONS +#endif /* ACE_HAS_EXCEPTIONS */ + +#include /**/ "ace/post.h" + +#endif /* ACE_EXCEPTION_MACROS_H */ diff --git a/dep/acelite/ace/FIFO.cpp b/dep/acelite/ace/FIFO.cpp new file mode 100644 index 00000000000..e3970015c43 --- /dev/null +++ b/dep/acelite/ace/FIFO.cpp @@ -0,0 +1,78 @@ +// $Id: FIFO.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/FIFO.h" + +#if !defined (__ACE_INLINE__) +#include "ace/FIFO.inl" +#endif /* __ACE_INLINE__ */ + +#include "ace/Log_Msg.h" +#include "ace/OS_NS_string.h" +#include "ace/OS_NS_errno.h" +#include "ace/OS_NS_sys_stat.h" +#include "ace/OS_NS_fcntl.h" + +ACE_RCSID(ace, FIFO, "$Id: FIFO.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_FIFO) + +void +ACE_FIFO::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_FIFO::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("rendezvous_ = %s"), this->rendezvous_)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +int +ACE_FIFO::open (const ACE_TCHAR *r, int flags, mode_t perms, + LPSECURITY_ATTRIBUTES sa) +{ + ACE_TRACE ("ACE_FIFO::open"); + ACE_OS::strsncpy (this->rendezvous_, r, MAXPATHLEN); + + if ((flags & O_CREAT) != 0 + && ACE_OS::mkfifo (this->rendezvous_, perms) == -1 + && !(errno == EEXIST)) + return -1; + + this->set_handle (ACE_OS::open (this->rendezvous_, flags, 0, sa)); + return this->get_handle () == ACE_INVALID_HANDLE ? -1 : 0; +} + +ACE_FIFO::ACE_FIFO (const ACE_TCHAR *fifo_name, + int flags, + mode_t perms, + LPSECURITY_ATTRIBUTES sa) +{ + ACE_TRACE ("ACE_FIFO::ACE_FIFO"); + if (this->open (fifo_name, flags, perms, sa) == -1) + ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("ACE_FIFO"))); +} + +ACE_FIFO::ACE_FIFO (void) +{ +// ACE_TRACE ("ACE_FIFO::ACE_FIFO"); +} + +int +ACE_FIFO::close (void) +{ + ACE_TRACE ("ACE_FIFO::close"); + int result = 0; + + if (this->get_handle () != ACE_INVALID_HANDLE) + { + result = ACE_OS::close (this->get_handle ()); + this->set_handle (ACE_INVALID_HANDLE); + } + return result; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/FIFO.h b/dep/acelite/ace/FIFO.h new file mode 100644 index 00000000000..2d590563a99 --- /dev/null +++ b/dep/acelite/ace/FIFO.h @@ -0,0 +1,85 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file FIFO.h + * + * $Id: FIFO.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Doug Schmidt + */ +//========================================================================== + + +#ifndef ACE_FIFO_H +#define ACE_FIFO_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/IPC_SAP.h" +#include "ace/os_include/os_limits.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_FIFO + * + * @brief Abstract base class for UNIX FIFOs + * + * UNIX FIFOs are also known Named Pipes, which are totally + * unrelated to Win32 Named Pipes. If you want to use a local + * IPC mechanism that will be portable to both UNIX and Win32, + * take a look at the classes. + */ +class ACE_Export ACE_FIFO : public ACE_IPC_SAP +{ +public: + /// Open up the named pipe on the in accordance with the + /// flags. + int open (const ACE_TCHAR *rendezvous, int flags, mode_t perms, + LPSECURITY_ATTRIBUTES sa = 0); + + /// Close down the ACE_FIFO without removing the rendezvous point. + int close (void); + + /// Close down the ACE_FIFO and remove the rendezvous point from the + /// file system. + int remove (void); + + /// Return the local address of this endpoint. + int get_local_addr (const ACE_TCHAR *&rendezvous) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + // = Make these protected to ensure that the class is "abstract." + /// Default constructor. + ACE_FIFO (void); + + /// Open up the named pipe on the in accordance with the + /// flags. + ACE_FIFO (const ACE_TCHAR *rendezvous, int flags, mode_t perms, + LPSECURITY_ATTRIBUTES sa = 0); + +private: + /// Rendezvous point in the file system. + ACE_TCHAR rendezvous_[MAXPATHLEN + 1]; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/FIFO.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_FIFO_H */ diff --git a/dep/acelite/ace/FIFO.inl b/dep/acelite/ace/FIFO.inl new file mode 100644 index 00000000000..05cc030a917 --- /dev/null +++ b/dep/acelite/ace/FIFO.inl @@ -0,0 +1,25 @@ +// -*- C++ -*- +// +// $Id: FIFO.inl 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/OS_NS_unistd.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE int +ACE_FIFO::get_local_addr (const ACE_TCHAR *&r) const +{ + ACE_TRACE ("ACE_FIFO::get_local_addr"); + r = this->rendezvous_; + return 0; +} + +ACE_INLINE int +ACE_FIFO::remove (void) +{ + ACE_TRACE ("ACE_FIFO::remove"); + int const result = this->close (); + return ACE_OS::unlink (this->rendezvous_) == -1 || result == -1 ? -1 : 0; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/FIFO_Recv.cpp b/dep/acelite/ace/FIFO_Recv.cpp new file mode 100644 index 00000000000..254e30f21d1 --- /dev/null +++ b/dep/acelite/ace/FIFO_Recv.cpp @@ -0,0 +1,88 @@ +// $Id: FIFO_Recv.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/FIFO_Recv.h" +#include "ace/Log_Msg.h" +#include "ace/OS_NS_fcntl.h" + +#if !defined (__ACE_INLINE__) +#include "ace/FIFO_Recv.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID(ace, FIFO_Recv, "$Id: FIFO_Recv.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_FIFO_Recv) + +void +ACE_FIFO_Recv::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_FIFO_Recv::dump"); + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_FIFO::dump (); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("aux_handle_ = %d"), this->aux_handle_)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +int +ACE_FIFO_Recv::close (void) +{ + ACE_TRACE ("ACE_FIFO_Recv::close"); + int result = ACE_FIFO::close (); + + if (this->aux_handle_ != ACE_INVALID_HANDLE) + return ACE_OS::close (this->aux_handle_); + else + return result; +} + +// Note that persistent means "open fifo for writing, as well as +// reading." This ensures that the fifo never gets EOF, even if there +// aren't any writers at the moment! + +int +ACE_FIFO_Recv::open (const ACE_TCHAR *fifo_name, + int flags, + mode_t perms, + int persistent, + LPSECURITY_ATTRIBUTES sa) +{ + ACE_TRACE ("ACE_FIFO_Recv::open"); + + if (ACE_FIFO::open (fifo_name, ACE_NONBLOCK | flags, perms, sa) == -1) + return -1; + else if (this->disable (ACE_NONBLOCK) == -1) + return -1; + else if (persistent + && (this->aux_handle_ = ACE_OS::open (fifo_name, O_WRONLY, 0, sa)) == ACE_INVALID_HANDLE) + return -1; + else + return this->get_handle () == ACE_INVALID_HANDLE ? -1 : 0; +} + +ACE_FIFO_Recv::ACE_FIFO_Recv (void) + : aux_handle_ (ACE_INVALID_HANDLE) +{ + ACE_TRACE ("ACE_FIFO_Recv::ACE_FIFO_Recv"); +} + +ACE_FIFO_Recv::ACE_FIFO_Recv (const ACE_TCHAR *fifo_name, + int flags, + mode_t perms, + int persistent, + LPSECURITY_ATTRIBUTES sa) + : aux_handle_ (ACE_INVALID_HANDLE) +{ + ACE_TRACE ("ACE_FIFO_Recv::ACE_FIFO_Recv"); + + if (this->ACE_FIFO_Recv::open (fifo_name, + flags, + perms, + persistent, + sa) == -1) + ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("ACE_FIFO_Recv"))); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/FIFO_Recv.h b/dep/acelite/ace/FIFO_Recv.h new file mode 100644 index 00000000000..c19d102c82a --- /dev/null +++ b/dep/acelite/ace/FIFO_Recv.h @@ -0,0 +1,85 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file FIFO_Recv.h + * + * $Id: FIFO_Recv.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Doug Schmidt + */ +//========================================================================== + + +#ifndef ACE_FIFO_RECV_H +#define ACE_FIFO_RECV_H + +#include /**/ "ace/pre.h" + +#include "ace/FIFO.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/os_fcntl.h" +#include "ace/Default_Constants.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_FIFO_Recv + * + * @brief Receiver side of the bytestream C++ wrapper for UNIX + * FIFOs. + */ +class ACE_Export ACE_FIFO_Recv : public ACE_FIFO +{ +public: + // = Initialization methods. + /// Default constructor. + ACE_FIFO_Recv (void); + + /// Open up a bytestream named pipe for reading. + ACE_FIFO_Recv (const ACE_TCHAR *rendezvous, + int flags = O_CREAT | O_RDONLY, + mode_t perms = ACE_DEFAULT_FILE_PERMS, + int persistent = 1, + LPSECURITY_ATTRIBUTES sa = 0); + + /// Open up a bytestream named pipe for reading. + int open (const ACE_TCHAR *rendezvous, + int flags = O_CREAT | O_RDONLY, + mode_t perms = ACE_DEFAULT_FILE_PERMS, + int persistent = 1, + LPSECURITY_ATTRIBUTES sa = 0); + + /// Close down the named pipe. + int close (void); + + /// Recv @a buf of up to @a len bytes. + ssize_t recv (void *buf, size_t len); + + /// Recv @a buf of exactly @a len bytes (block until done). + ssize_t recv_n (void *buf, size_t len); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + /// Auxiliary handle that is used to implement persistent FIFOs. + ACE_HANDLE aux_handle_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/FIFO_Recv.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" + +#endif /* ACE_FIFO_RECV_H */ diff --git a/dep/acelite/ace/FIFO_Recv.inl b/dep/acelite/ace/FIFO_Recv.inl new file mode 100644 index 00000000000..d4c3fee4326 --- /dev/null +++ b/dep/acelite/ace/FIFO_Recv.inl @@ -0,0 +1,24 @@ +// -*- C++ -*- +// +// $Id: FIFO_Recv.inl 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/ACE.h" +#include "ace/OS_NS_unistd.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE ssize_t +ACE_FIFO_Recv::recv (void *buf, size_t len) +{ + ACE_TRACE ("ACE_FIFO_Recv::recv"); + return ACE_OS::read (this->get_handle (), (char *) buf, len); +} + +ACE_INLINE ssize_t +ACE_FIFO_Recv::recv_n (void *buf, size_t n) +{ + ACE_TRACE ("ACE_FIFO_Recv::recv_n"); + return ACE::recv_n (this->get_handle (), buf, n); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/FIFO_Recv_Msg.cpp b/dep/acelite/ace/FIFO_Recv_Msg.cpp new file mode 100644 index 00000000000..f389d03d276 --- /dev/null +++ b/dep/acelite/ace/FIFO_Recv_Msg.cpp @@ -0,0 +1,67 @@ +// $Id: FIFO_Recv_Msg.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/FIFO_Recv_Msg.h" + +#include "ace/Log_Msg.h" + +#if !defined (__ACE_INLINE__) +#include "ace/FIFO_Recv_Msg.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID(ace, FIFO_Recv_Msg, "$Id: FIFO_Recv_Msg.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_FIFO_Recv_Msg) + +void +ACE_FIFO_Recv_Msg::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_FIFO_Recv_Msg::dump"); + ACE_FIFO_Recv::dump (); +#endif /* ACE_HAS_DUMP */ +} + +// Note that persistent means "open FIFO for writing, as well as +// reading." This ensures that the FIFO never gets EOF, even if there +// aren't any writers at the moment! + +int +ACE_FIFO_Recv_Msg::open (const ACE_TCHAR *fifo_name, + int flags, + mode_t perms, + int persistent, + LPSECURITY_ATTRIBUTES sa) +{ + ACE_TRACE ("ACE_FIFO_Recv_Msg::open"); + + return ACE_FIFO_Recv::open (fifo_name, + flags, + perms, + persistent, + sa); +} + +ACE_FIFO_Recv_Msg::ACE_FIFO_Recv_Msg (void) +{ + ACE_TRACE ("ACE_FIFO_Recv_Msg::ACE_FIFO_Recv_Msg"); +} + +ACE_FIFO_Recv_Msg::ACE_FIFO_Recv_Msg (const ACE_TCHAR *fifo_name, + int flags, + mode_t perms, + int persistent, + LPSECURITY_ATTRIBUTES sa) +{ + ACE_TRACE ("ACE_FIFO_Recv_Msg::ACE_FIFO_Recv_Msg"); + + if (this->ACE_FIFO_Recv_Msg::open (fifo_name, + flags, + perms, + persistent, + sa) == -1) + ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("ACE_FIFO_Recv_Msg"))); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/FIFO_Recv_Msg.h b/dep/acelite/ace/FIFO_Recv_Msg.h new file mode 100644 index 00000000000..6b691e97f10 --- /dev/null +++ b/dep/acelite/ace/FIFO_Recv_Msg.h @@ -0,0 +1,138 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file FIFO_Recv_Msg.h + * + * $Id: FIFO_Recv_Msg.h 84480 2009-02-16 18:58:16Z johnnyw $ + * + * @author Doug Schmidt + */ +//============================================================================= + + +#ifndef ACE_FIFO_RECV_MSG_H +#define ACE_FIFO_RECV_MSG_H +#include /**/ "ace/pre.h" + +#include "ace/FIFO_Recv.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Forward decls +class ACE_Str_Buf; + +/** + * @class ACE_FIFO_Recv_Msg + * + * @brief Receiver side for the record oriented C++ wrapper for UNIX FIFOs. + * + * This method works slightly differently on platforms with the + * @c ACE_HAS_STREAM_PIPES configuration setting than those without. + * With ACE_HAS_STREAM_PIPES, the @c getmsg() system function is used + * and it preserves message boundaries internally. Without + * @c ACE_HAS_STREAM_PIPES, the message boundaries are emulated by + * this class and ACE_FIFO_Send_Msg cooperating. The sending class + * first writes an integer number of bytes in the message, then the + * message. ACE_FIFO_Recv_Msg reads the count, then the data. + * The operational differences occur primarily when a message is larger + * than what a caller of this class requests. See recv() for details. + */ +class ACE_Export ACE_FIFO_Recv_Msg : public ACE_FIFO_Recv +{ +public: + // = Initialization methods. + /// Default constructor. + ACE_FIFO_Recv_Msg (void); + + /// Open up a record-oriented named pipe for reading. + ACE_FIFO_Recv_Msg (const ACE_TCHAR *rendezvous, + int flags = O_CREAT | O_RDONLY, + mode_t perms = ACE_DEFAULT_FILE_PERMS, + int persistent = 1, + LPSECURITY_ATTRIBUTES sa = 0); + + /// Open up a record-oriented named pipe for reading. + int open (const ACE_TCHAR *rendezvous, + int flags = O_CREAT | O_RDONLY, + mode_t perms = ACE_DEFAULT_FILE_PERMS, + int persistent = 1, + LPSECURITY_ATTRIBUTES sa = 0); + + /// Receive a message based on attributes in an ACE_Str_Buf. + /** + * @param msg Reference to an ACE_Str_Buf whose @c buf member points + * to the memory to receive the data and @c maxlen member + * contains the maximum number of bytes to receive. + * On return after successfully reading data, the + * @c len member contains the number of bytes received and + * placed in the buffer pointed to by @c msg.buf. + * + * @retval -1 Error; consult @c errno for specific error number. + * @return If the @c ACE_HAS_STREAM_PIPES configuration setting is + * defined, the return value is the number of bytes received + * in the message and will be the same as @c buf.len. + * The return value from the @c getmsg() system function + * is discarded. + * If @c ACE_HAS_STREAM_PIPES is not defined, the number + * of bytes in the message read from the FIFO is returned. + * If the message is larger than the maximum length + * requested in @c msg.maxlen, the return value reflects + * the entire message length, and the @c msg.len member + * reflects how many bytes were actually placed in the + * caller's buffer. Any part of the message longer than + * @c msg.maxlen is discarded. + */ + ssize_t recv (ACE_Str_Buf &msg); + + /// Receive a message based on buffer pointer and maximum size. + /** + * @param buf Pointer to the memory to receive the data. + * @param len The maximum number of bytes to receive. + * + * @retval -1 Error; consult @c errno for specific error number. + * @return The number of bytes received in the message. For messages + * that are larger than the requested maximum size, the + * behavior is different depending on the @c ACE_HAS_STREAM_PIPES + * configuration setting. With @c ACE_HAS_STREAM_PIPES, + * the return value will be the same as @arg len (this is + * also possible if the message is exactly the same length + * as @arg len, and the two cases are indistinguishable). + * Without @c ACE_HAS_STREAM_PIPES, the return value is + * the total length of the message, including bytes in + * excess of @arg len. The excess bytes are discarded. + */ + ssize_t recv (void *buf, size_t len); + +#if defined (ACE_HAS_STREAM_PIPES) + /// Recv @a data and @a cntl message via Stream pipes. + ssize_t recv (ACE_Str_Buf *data, + ACE_Str_Buf *cntl, + int *flags); + + /// Recv @a data and @a cntl message via Stream pipes in "band" mode. + ssize_t recv (int *band, + ACE_Str_Buf *data, + ACE_Str_Buf *cntl, + int *flags); +#endif /* ACE_HAS_STREAM_PIPES */ + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/FIFO_Recv_Msg.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_FIFO_RECV_MSG_H */ diff --git a/dep/acelite/ace/FIFO_Recv_Msg.inl b/dep/acelite/ace/FIFO_Recv_Msg.inl new file mode 100644 index 00000000000..0a0b0673d38 --- /dev/null +++ b/dep/acelite/ace/FIFO_Recv_Msg.inl @@ -0,0 +1,137 @@ +// -*- C++ -*- +// +// $Id: FIFO_Recv_Msg.inl 82559 2008-08-07 20:23:07Z parsons $ + +#include "ace/Min_Max.h" +#include "ace/OS_NS_stropts.h" +#include "ace/Truncate.h" + +#if !defined (ACE_HAS_STREAM_PIPES) +#include "ace/OS_NS_unistd.h" +#endif + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE ssize_t +ACE_FIFO_Recv_Msg::recv (ACE_Str_Buf &recv_msg) +{ + ACE_TRACE ("ACE_FIFO_Recv_Msg::recv"); +#if defined (ACE_HAS_STREAM_PIPES) + int i = 0; + if (ACE_OS::getmsg (this->get_handle (), + (strbuf *) 0, + (strbuf *) &recv_msg, + &i) == -1) + { + return -1; + } + else + { + return recv_msg.len; + } +#else /* Do the ol' 2-read trick... */ + if (ACE_OS::read (this->get_handle (), + (char *) &recv_msg.len, + sizeof recv_msg.len) != sizeof recv_msg.len) + { + return -1; + } + else + { + size_t remaining = static_cast (recv_msg.len); + size_t requested = static_cast (recv_msg.maxlen); + ssize_t recv_len = ACE_OS::read (this->get_handle (), + (char *) recv_msg.buf, + ACE_MIN (remaining, requested)); + + if (recv_len == -1) + { + return -1; + } + + // Tell caller what's really in the buffer. + recv_msg.len = static_cast (recv_len); + + // If there are more bytes remaining in the message, read them and + // throw them away. Leaving them in the FIFO would make it difficult + // to find the start of the next message in the fifo. + // Since the ACE_HAS_STREAM_PIPES version of this method doesn't + // return getmsg()'s indication of "data remaining", don't worry about + // saving the indication here either to read the remainder later. + size_t total_msg_size = remaining; + remaining -= recv_len; + + while (remaining > 0) + { + const size_t throw_away = 1024; + char dev_null[throw_away]; + recv_len = ACE_OS::read (this->get_handle (), + dev_null, + ACE_MIN (remaining, throw_away)); + + if (recv_len == -1) + { + break; + } + + remaining -= recv_len; + } + + return ACE_Utils::truncate_cast (total_msg_size); + } +#endif /* ACE_HAS_STREAM_PIPES */ +} + +ACE_INLINE ssize_t +ACE_FIFO_Recv_Msg::recv (void *buf, size_t max_len) +{ + ACE_TRACE ("ACE_FIFO_Recv_Msg::recv"); + ACE_Str_Buf recv_msg ((char *) buf, 0, static_cast (max_len)); + + return this->recv (recv_msg); +} + +#if defined (ACE_HAS_STREAM_PIPES) +ACE_INLINE ssize_t +ACE_FIFO_Recv_Msg::recv (ACE_Str_Buf *data, + ACE_Str_Buf *cntl, + int *flags) +{ + ACE_TRACE ("ACE_FIFO_Recv_Msg::recv"); + if (ACE_OS::getmsg (this->get_handle (), + (strbuf *) cntl, + (strbuf *) data, + flags) == -1) + { + return -1; + } + else + { + return (cntl == 0 ? 0 : cntl->len) + (data == 0 ? 0 : data->len); + } +} + +ACE_INLINE ssize_t +ACE_FIFO_Recv_Msg::recv (int *band, + ACE_Str_Buf *data, + ACE_Str_Buf *cntl, + int *flags) +{ + ACE_TRACE ("ACE_FIFO_Recv_Msg::recv"); + + if (ACE_OS::getpmsg (this->get_handle (), + (strbuf *) cntl, + (strbuf *) data, + band, + flags) == -1) + { + return -1; + } + else + { + return (cntl == 0 ? 0 : cntl->len) + (data == 0 ? 0 : data->len); + } +} +#endif /* ACE_HAS_STREAM_PIPES */ + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/FIFO_Send.cpp b/dep/acelite/ace/FIFO_Send.cpp new file mode 100644 index 00000000000..720e63c5425 --- /dev/null +++ b/dep/acelite/ace/FIFO_Send.cpp @@ -0,0 +1,58 @@ +// $Id: FIFO_Send.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/FIFO_Send.h" +#include "ace/Log_Msg.h" + +#if !defined (__ACE_INLINE__) +#include "ace/FIFO_Send.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID(ace, FIFO_Send, "$Id: FIFO_Send.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_FIFO_Send) + +void +ACE_FIFO_Send::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_FIFO_Send::dump"); + ACE_FIFO::dump (); +#endif /* ACE_HAS_DUMP */ +} + +ACE_FIFO_Send::ACE_FIFO_Send (void) +{ +// ACE_TRACE ("ACE_FIFO_Send::ACE_FIFO_Send"); +} + +int +ACE_FIFO_Send::open (const ACE_TCHAR *rendezvous_name, + int flags, + mode_t perms, + LPSECURITY_ATTRIBUTES sa) +{ + ACE_TRACE ("ACE_FIFO_Send::open"); + return ACE_FIFO::open (rendezvous_name, + flags | O_WRONLY, + perms, + sa); +} + +ACE_FIFO_Send::ACE_FIFO_Send (const ACE_TCHAR *fifo_name, + int flags, + mode_t perms, + LPSECURITY_ATTRIBUTES sa) +{ + ACE_TRACE ("ACE_FIFO_Send::ACE_FIFO_Send"); + if (this->ACE_FIFO_Send::open (fifo_name, + flags, + perms, + sa) == -1) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_FIFO_Send::ACE_FIFO_Send"))); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/FIFO_Send.h b/dep/acelite/ace/FIFO_Send.h new file mode 100644 index 00000000000..cc0fc282f83 --- /dev/null +++ b/dep/acelite/ace/FIFO_Send.h @@ -0,0 +1,75 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file FIFO_Send.h + * + * $Id: FIFO_Send.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Doug Schmidt + */ +//========================================================================== + + +#ifndef ACE_FIFO_SEND_H +#define ACE_FIFO_SEND_H + +#include /**/ "ace/pre.h" + +#include "ace/FIFO.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/os_fcntl.h" +#include "ace/Default_Constants.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_FIFO_Send + * + * @brief Sender side for the bytestream C++ wrapper for UNIX FIFOs + */ +class ACE_Export ACE_FIFO_Send : public ACE_FIFO +{ +public: + // = Initialization methods. + /// Default constructor. + ACE_FIFO_Send (void); + + /// Open up a bytestream named pipe for writing. + ACE_FIFO_Send (const ACE_TCHAR *rendezvous, + int flags = O_WRONLY, + mode_t perms = ACE_DEFAULT_FILE_PERMS, + LPSECURITY_ATTRIBUTES sa = 0); + + /// Open up a bytestream named pipe for writing. + int open (const ACE_TCHAR *rendezvous, + int flags = O_WRONLY, + mode_t perms = ACE_DEFAULT_FILE_PERMS, + LPSECURITY_ATTRIBUTES sa = 0); + + /// Send @a buf of up to @a len bytes. + ssize_t send (const void *buf, size_t len); + + /// Send @a buf of exactly @a len bytes (block until done). + ssize_t send_n (const void *buf, size_t len); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/FIFO_Send.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" + +#endif /* ACE_FIFO_SEND_H */ diff --git a/dep/acelite/ace/FIFO_Send.inl b/dep/acelite/ace/FIFO_Send.inl new file mode 100644 index 00000000000..a01facd61f0 --- /dev/null +++ b/dep/acelite/ace/FIFO_Send.inl @@ -0,0 +1,24 @@ +// -*- C++ -*- +// +// $Id: FIFO_Send.inl 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/ACE.h" +#include "ace/OS_NS_unistd.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE ssize_t +ACE_FIFO_Send::send (const void *buf, size_t len) +{ + ACE_TRACE ("ACE_FIFO_Send::send"); + return ACE_OS::write (this->get_handle (), (const char *) buf, len); +} + +ACE_INLINE ssize_t +ACE_FIFO_Send::send_n (const void *buf, size_t n) +{ + ACE_TRACE ("ACE_FIFO_Send::send_n"); + return ACE::send_n (this->get_handle (), buf, n); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/FIFO_Send_Msg.cpp b/dep/acelite/ace/FIFO_Send_Msg.cpp new file mode 100644 index 00000000000..b3bbae00aed --- /dev/null +++ b/dep/acelite/ace/FIFO_Send_Msg.cpp @@ -0,0 +1,80 @@ +// $Id: FIFO_Send_Msg.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/FIFO_Send_Msg.h" + +#include "ace/Log_Msg.h" +#include "ace/OS_NS_sys_uio.h" + +#if !defined (__ACE_INLINE__) +#include "ace/FIFO_Send_Msg.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID(ace, FIFO_Send_Msg, "$Id: FIFO_Send_Msg.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_FIFO_Send_Msg) + +void +ACE_FIFO_Send_Msg::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_FIFO_Send_Msg::dump"); + ACE_FIFO_Send::dump (); +#endif /* ACE_HAS_DUMP */ +} + +ssize_t +ACE_FIFO_Send_Msg::send (const ACE_Str_Buf &send_msg) +{ + // ACE_TRACE ("ACE_FIFO_Send_Msg::send"); +#if defined (ACE_HAS_STREAM_PIPES) + if (ACE_OS::putmsg (this->get_handle (), + (strbuf *) 0, + (strbuf *) &send_msg, + 0) == -1) + return -1; + else + return send_msg.len; +#else + iovec iov[2]; + + iov[0].iov_base = (char *) &send_msg.len; + iov[0].iov_len = sizeof send_msg.len; + + iov[1].iov_base = (char *) send_msg.buf; + iov[1].iov_len = static_cast (send_msg.len); + + ssize_t sent = ACE_OS::writev (this->get_handle (), iov, 2); + if (sent > 0) + sent -= iov[0].iov_len; // Don't count the length we added. + return sent; +#endif /* ACE_HAS_STREAM_PIPES */ +} + +ACE_FIFO_Send_Msg::ACE_FIFO_Send_Msg (void) +{ +// ACE_TRACE ("ACE_FIFO_Send_Msg::ACE_FIFO_Send_Msg"); +} + +int +ACE_FIFO_Send_Msg::open (const ACE_TCHAR *fifo_name, + int flags, + mode_t perms, + LPSECURITY_ATTRIBUTES sa) +{ + ACE_TRACE ("ACE_FIFO_Send_Msg::open"); + return ACE_FIFO_Send::open (fifo_name, flags | O_WRONLY, perms, sa); +} + +ACE_FIFO_Send_Msg::ACE_FIFO_Send_Msg (const ACE_TCHAR *fifo_name, + int flags, + mode_t perms, + LPSECURITY_ATTRIBUTES sa) +{ + ACE_TRACE ("ACE_FIFO_Send_Msg::ACE_FIFO_Send_Msg"); + if (this->ACE_FIFO_Send_Msg::open (fifo_name, flags, perms, sa) == -1) + ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("ACE_FIFO_Send_Msg"))); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/FIFO_Send_Msg.h b/dep/acelite/ace/FIFO_Send_Msg.h new file mode 100644 index 00000000000..434ae108130 --- /dev/null +++ b/dep/acelite/ace/FIFO_Send_Msg.h @@ -0,0 +1,91 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file FIFO_Send_Msg.h + * + * $Id: FIFO_Send_Msg.h 84480 2009-02-16 18:58:16Z johnnyw $ + * + * @author Doug Schmidt + */ +//============================================================================= + + +#ifndef ACE_FIFO_SEND_MSG_H +#define ACE_FIFO_SEND_MSG_H +#include /**/ "ace/pre.h" + +#include "ace/FIFO_Send.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_STREAM_PIPES) +# include "ace/OS_NS_stropts.h" +#endif /* ACE_HAS_STREAM_PIPES */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Forward Decls +class ACE_Str_Buf; + +/** + * @class ACE_FIFO_Send_Msg + * + * @brief Sender side for the Record oriented C++ wrapper for UNIX + * FIFOs. + */ +class ACE_Export ACE_FIFO_Send_Msg : public ACE_FIFO_Send +{ +public: + // = Initialization methods. + /// Default constructor. + ACE_FIFO_Send_Msg (void); + + /// Open up a record-oriented named pipe for writing. + ACE_FIFO_Send_Msg (const ACE_TCHAR *rendezvous, + int flags = O_WRONLY, + mode_t perms = ACE_DEFAULT_FILE_PERMS, + LPSECURITY_ATTRIBUTES sa = 0); + + /// Open up a record-oriented named pipe for writing. + int open (const ACE_TCHAR *rendezvous, + int flags = O_WRONLY, + mode_t perms = ACE_DEFAULT_FILE_PERMS, + LPSECURITY_ATTRIBUTES sa = 0); + + /// Send @a buf of up to @a len bytes. + ssize_t send (const ACE_Str_Buf &msg); + + /// Send @a buf of exactly @a len bytes (block until done). + ssize_t send (const void *buf, size_t len); + +#if defined (ACE_HAS_STREAM_PIPES) + /// Send @a data and @a cntl message via Stream pipes. + ssize_t send (const ACE_Str_Buf *data, + const ACE_Str_Buf *cntl = 0, + int flags = 0); + + /// Send @a data and @a cntl message via Stream pipes in "band" mode. + ssize_t send (int band, + const ACE_Str_Buf *data, + const ACE_Str_Buf *cntl = 0, + int flags = MSG_BAND); +#endif /* ACE_HAS_STREAM_PIPES */ + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/FIFO_Send_Msg.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_FIFO_SEND_MSG_H */ diff --git a/dep/acelite/ace/FIFO_Send_Msg.inl b/dep/acelite/ace/FIFO_Send_Msg.inl new file mode 100644 index 00000000000..0a34e64e370 --- /dev/null +++ b/dep/acelite/ace/FIFO_Send_Msg.inl @@ -0,0 +1,53 @@ +// -*- C++ -*- +// +// $Id: FIFO_Send_Msg.inl 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/OS_NS_stropts.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE ssize_t +ACE_FIFO_Send_Msg::send (const void *buf, size_t len) +{ + ACE_TRACE ("ACE_FIFO_Send_Msg::send"); + ACE_Str_Buf send_msg ((char *) buf, static_cast (len)); + + return this->send (send_msg); +} + +#if defined (ACE_HAS_STREAM_PIPES) +ACE_INLINE ssize_t +ACE_FIFO_Send_Msg::send (const ACE_Str_Buf *data, + const ACE_Str_Buf *cntl, + int flags) +{ + ACE_TRACE ("ACE_FIFO_Send_Msg::send"); + if (ACE_OS::putmsg (this->get_handle (), + (strbuf *) cntl, + (strbuf *) data, + flags) == -1) + return-1; + else + return (cntl == 0 ? 0 : cntl->len) + (data == 0 ? 0 : data->len); +} + +ACE_INLINE ssize_t +ACE_FIFO_Send_Msg::send (int band, + const ACE_Str_Buf *data, + const ACE_Str_Buf *cntl, + int flags) +{ + ACE_TRACE ("ACE_FIFO_Send_Msg::send"); + + if (ACE_OS::putpmsg (this->get_handle (), + (strbuf *) cntl, + (strbuf *) data, + band, + flags) == -1) + return -1; + else + return (cntl == 0 ? 0 : cntl->len) + (data == 0 ? 0 : data->len); +} +#endif /* ACE_HAS_STREAM_PIPES */ + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/FILE.cpp b/dep/acelite/ace/FILE.cpp new file mode 100644 index 00000000000..8fe88d1b09c --- /dev/null +++ b/dep/acelite/ace/FILE.cpp @@ -0,0 +1,147 @@ +// $Id: FILE.cpp 80826 2008-03-04 14:51:23Z wotte $ + +/* Defines the member functions for the base class of the ACE_IO_SAP + ACE_FILE abstraction. */ + +#include "ace/FILE.h" + +#include "ace/OS_NS_unistd.h" +#include "ace/OS_NS_sys_stat.h" + +#if !defined (__ACE_INLINE__) +#include "ace/FILE.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID(ace, FILE, "$Id: FILE.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_FILE) + +void +ACE_FILE::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_FILE::dump"); + ACE_IO_SAP::dump (); +#endif /* ACE_HAS_DUMP */ +} + +// This is the do-nothing constructor. + +ACE_FILE::ACE_FILE (void) +{ + ACE_TRACE ("ACE_FILE::ACE_FILE"); +} + +// Close the file + +int +ACE_FILE::close (void) +{ + ACE_TRACE ("ACE_FILE::close"); + int result = 0; + + if (this->get_handle () != ACE_INVALID_HANDLE) + { + result = ACE_OS::close (this->get_handle ()); + this->set_handle (ACE_INVALID_HANDLE); + } + return result; +} + +int +ACE_FILE::get_info (ACE_FILE_Info *finfo) +{ + ACE_TRACE ("ACE_FILE::get_info"); + ACE_stat filestatus; + + int const result = ACE_OS::fstat (this->get_handle (), &filestatus); + + if (result == 0) + { + finfo->mode_ = filestatus.st_mode; + finfo->nlink_ = filestatus.st_nlink; + finfo->size_ = filestatus.st_size; + } + + return result; +} + +int +ACE_FILE::get_info (ACE_FILE_Info &finfo) +{ + ACE_TRACE ("ACE_FILE::get_info"); + + return this->get_info (&finfo); +} + +int +ACE_FILE::truncate (ACE_OFF_T length) +{ + ACE_TRACE ("ACE_FILE::truncate"); + return ACE_OS::ftruncate (this->get_handle (), length); +} + +ACE_OFF_T +ACE_FILE::seek (ACE_OFF_T offset, int startpos) +{ + return ACE_OS::lseek (this->get_handle (), offset, startpos); +} + +ACE_OFF_T +ACE_FILE::tell (void) +{ + ACE_TRACE ("ACE_FILE::tell"); + return ACE_OS::lseek (this->get_handle (), 0, SEEK_CUR); +} + +// Return the local endpoint address. + +int +ACE_FILE::get_local_addr (ACE_Addr &addr) const +{ + ACE_TRACE ("ACE_FILE::get_local_addr"); + + // Perform the downcast since had better be an + // . + ACE_FILE_Addr *file_addr = + dynamic_cast (&addr); + + if (file_addr == 0) + return -1; + else + { + *file_addr = this->addr_; + return 0; + } +} + +// Return the same result as . + +int +ACE_FILE::get_remote_addr (ACE_Addr &addr) const +{ + ACE_TRACE ("ACE_FILE::get_remote_addr"); + + return this->get_local_addr (addr); +} + +int +ACE_FILE::remove (void) +{ + ACE_TRACE ("ACE_FILE::remove"); + + this->close (); + return ACE_OS::unlink (this->addr_.get_path_name ()); +} + +int +ACE_FILE::unlink (void) +{ + ACE_TRACE ("ACE_FILE::unlink"); + + return ACE_OS::unlink (this->addr_.get_path_name ()); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/FILE.h b/dep/acelite/ace/FILE.h new file mode 100644 index 00000000000..407a03379e5 --- /dev/null +++ b/dep/acelite/ace/FILE.h @@ -0,0 +1,139 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file FILE.h + * + * $Id: FILE.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Gerhard Lenzer + */ +//============================================================================= + +#ifndef ACE_FILE_H +#define ACE_FILE_H +#include /**/ "ace/pre.h" + +#include "ace/IO_SAP.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/FILE_Addr.h" + +// The following is necessary since many C++ compilers don't support +// typedef'd types inside of classes used as formal template +// arguments... ;-(. Luckily, using the C++ preprocessor I can hide +// most of this nastiness! + +#if defined (ACE_HAS_TEMPLATE_TYPEDEFS) +#define ACE_FILE_CONNECTOR ACE_FILE_Connector +#define ACE_FILE_STREAM ACE_FILE_IO +#else /* TEMPLATES are broken (must be a cfront-based compiler...) */ +#define ACE_FILE_CONNECTOR ACE_FILE_Connector, ACE_FILE_Addr +#define ACE_FILE_STREAM ACE_FILE_IO, ACE_FILE_Addr +#endif /* ACE_TEMPLATE_TYPEDEFS */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_FILE_Info + * + * @brief Abstracts basic OS FILE information. + */ +class ACE_Export ACE_FILE_Info +{ +public: + /// Mode of file + mode_t mode_; + + /// No of links + nlink_t nlink_; + + /// Size of file + ACE_OFF_T size_; +}; + +/** + * @class ACE_FILE + * + * @brief Defines the core methods of the ACE_FILE abstraction. + */ +class ACE_Export ACE_FILE : public ACE_IO_SAP +{ +public: + /// Close the ACE_FILE handle without removing the ACE_FILE from + /// the file system. + int close (void); + + /// Close and remove the ACE_FILE from the file system. + int remove (void); + + /// Remove the ACE_FILE from the file system without closing the + /// ACE_FILE handle. + int unlink (void); + + /// Get information on this ACE_FILE. + int get_info (ACE_FILE_Info *finfo); + + /// Get information on this ACE_FILE. + int get_info (ACE_FILE_Info &finfo); + + /// Set filesize to length byte. + int truncate (ACE_OFF_T length); + + /** + * Sets the file pointer as follows: + * o If is , the pointer is set to @a offset + * bytes. + * + * o If is , the pointer is set to its + * current location plus @a offset. + * + * o If is , the pointer is set to the size + * of the file plus offset. + */ + ACE_OFF_T seek (ACE_OFF_T offset, + int whence = SEEK_CUR); + + /// Return an offset for the file handle. + ACE_OFF_T tell (void); + + /** + * Disable signal @a signum + * This is here to prevent Win32 from + * disabling SPIPE using socket calls + */ + int disable (int signum) const ; + + /// Return the local endpoint address in the referenced ACE_Addr. + /// Returns 0 if successful, else -1. + int get_local_addr (ACE_Addr &) const; + + /// Return the same thing as get_local_addr(). + int get_remote_addr (ACE_Addr &) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + /// Ensure that this class is only created by the + /// ACE_FILE_Connector. + ACE_FILE (void); + + /// File we are "connected" with... + ACE_FILE_Addr addr_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/FILE.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_FILE_H */ diff --git a/dep/acelite/ace/FILE.inl b/dep/acelite/ace/FILE.inl new file mode 100644 index 00000000000..288374afc58 --- /dev/null +++ b/dep/acelite/ace/FILE.inl @@ -0,0 +1,18 @@ +// -*- C++ -*- +// +// $Id: FILE.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE int +ACE_FILE::disable (int signum) const +{ +#if defined (ACE_WIN32) + ACE_UNUSED_ARG (signum) ; + return 0 ; +#else /* ACE_WIN32 */ + return ACE_IO_SAP::disable (signum) ; +#endif /* ACE_WIN32 */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/FILE_Addr.cpp b/dep/acelite/ace/FILE_Addr.cpp new file mode 100644 index 00000000000..6d8fbeb775b --- /dev/null +++ b/dep/acelite/ace/FILE_Addr.cpp @@ -0,0 +1,124 @@ +// $Id: FILE_Addr.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/FILE_Addr.h" +#include "ace/Lib_Find.h" +#include "ace/Log_Msg.h" +#include "ace/OS_NS_stdlib.h" +#include "ace/OS_NS_string.h" +#include "ace/os_include/sys/os_socket.h" + +#if !defined (__ACE_INLINE__) +#include "ace/FILE_Addr.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID(ace, FILE_Addr, "$Id: FILE_Addr.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_FILE_Addr) + +ACE_FILE_Addr::ACE_FILE_Addr (void) + : ACE_Addr (AF_FILE, sizeof this->filename_ / sizeof (ACE_TCHAR)) +{ + this->filename_[0] = '\0'; +} + +int +ACE_FILE_Addr::set (const ACE_FILE_Addr &sa) +{ + if (sa.get_type () == AF_ANY) + { +#if defined (ACE_DEFAULT_TEMP_FILE) + // Create a temporary file. + ACE_OS::strcpy (this->filename_, + ACE_DEFAULT_TEMP_FILE); +#else /* ACE_DEFAULT_TEMP_FILE */ + if (ACE::get_temp_dir (this->filename_, MAXPATHLEN - 15) == -1) + // -15 for ace-file-XXXXXX + { + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("Temporary path too long, ") + ACE_TEXT ("defaulting to current directory\n"))); + this->filename_[0] = 0; + } + + // Add the filename to the end + ACE_OS::strcat (this->filename_, ACE_TEXT ("ace-fileXXXXXX")); + +#endif /* ACE_DEFAULT_TEMP_FILE */ + + if (ACE_OS::mktemp (this->filename_) == 0) + return -1; + this->base_set (AF_FILE, + static_cast (ACE_OS::strlen (this->filename_) + 1)); + } + else + { + (void)ACE_OS::strsncpy (this->filename_, sa.filename_, sa.get_size ()); + + this->base_set (sa.get_type (), sa.get_size ()); + } + return 0; +} + +// Copy constructor. + +ACE_FILE_Addr::ACE_FILE_Addr (const ACE_FILE_Addr &sa) + : ACE_Addr (AF_FILE, sizeof this->filename_) +{ + this->set (sa); +} + +int +ACE_FILE_Addr::set (const ACE_TCHAR *filename) +{ + this->ACE_Addr::base_set (AF_FILE, + static_cast (ACE_OS::strlen (filename) + 1)); + (void) ACE_OS::strsncpy (this->filename_, + filename, + sizeof this->filename_ / sizeof (ACE_TCHAR)); + return 0; +} + +ACE_FILE_Addr & +ACE_FILE_Addr::operator= (const ACE_FILE_Addr &sa) +{ + if (this != &sa) + this->set (sa); + return *this; +} + +// Create a ACE_Addr from a ACE_FILE pathname. + +ACE_FILE_Addr::ACE_FILE_Addr (const ACE_TCHAR *filename) +{ + this->set (filename); +} + +int +ACE_FILE_Addr::addr_to_string (ACE_TCHAR *s, size_t len) const +{ + ACE_OS::strsncpy (s, this->filename_, len); + return 0; +} + +// Return the address. + +void * +ACE_FILE_Addr::get_addr (void) const +{ + return (void *)&this->filename_; +} + +void +ACE_FILE_Addr::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_FILE_Addr::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("filename_ = %s"), this->filename_)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/FILE_Addr.h b/dep/acelite/ace/FILE_Addr.h new file mode 100644 index 00000000000..432275b9665 --- /dev/null +++ b/dep/acelite/ace/FILE_Addr.h @@ -0,0 +1,89 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file FILE_Addr.h + * + * $Id: FILE_Addr.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_FILE_ADDR_H +#define ACE_FILE_ADDR_H +#include /**/ "ace/pre.h" + +#include "ace/Addr.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Flag_Manip.h" +#include "ace/os_include/os_dirent.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_FILE_Addr + * + * @brief Defines the FILE address family address format. + */ +class ACE_Export ACE_FILE_Addr : public ACE_Addr +{ +public: + // = Initialization methods. + /// Default constructor. + ACE_FILE_Addr (void); + + /// Copy constructor. + ACE_FILE_Addr (const ACE_FILE_Addr &sa); + + /// Acts like a copy constructor. If @a sa == ACE_Addr::sap_any then + /// create a temporary filename using ACE_OS::mktemp. + int set (const ACE_FILE_Addr &sa); + + /// Create a ACE_FILE_Addr from a pathname. + explicit ACE_FILE_Addr (const ACE_TCHAR *filename); + + /// Create a ACE_FILE_Addr from a pathname. + int set (const ACE_TCHAR *filename); + + /// Assignment operator. + ACE_FILE_Addr &operator= (const ACE_FILE_Addr &); + + /// Return a pointer to the address. + virtual void *get_addr (void) const; + + /// Transform the current address into string format. + virtual int addr_to_string (ACE_TCHAR *addr, size_t) const; + + /// Compare two addresses for equality. + bool operator == (const ACE_FILE_Addr &SAP) const; + + /// Compare two addresses for inequality. + bool operator != (const ACE_FILE_Addr &SAP) const; + + /// Return the path name used for the rendezvous point. + const ACE_TCHAR *get_path_name (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + /// Name of the file. + ACE_TCHAR filename_[MAXPATHLEN + 1]; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/FILE_Addr.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_FILE_ADDR_H */ diff --git a/dep/acelite/ace/FILE_Addr.inl b/dep/acelite/ace/FILE_Addr.inl new file mode 100644 index 00000000000..0ae7d31d278 --- /dev/null +++ b/dep/acelite/ace/FILE_Addr.inl @@ -0,0 +1,34 @@ +// -*- C++ -*- +// +// $Id: FILE_Addr.inl 80826 2008-03-04 14:51:23Z wotte $ + + +#include "ace/SString.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Compare two addresses for equality. + +ACE_INLINE bool +ACE_FILE_Addr::operator == (const ACE_FILE_Addr &sap) const +{ + return ACE_OS::strcmp (this->filename_, sap.filename_) == 0; +} + +// Compare two addresses for inequality. + +ACE_INLINE bool +ACE_FILE_Addr::operator != (const ACE_FILE_Addr &sap) const +{ + return !((*this) == sap); // This is lazy, of course... ;-) +} + +// Return the path name used for the rendezvous point. + +ACE_INLINE const ACE_TCHAR * +ACE_FILE_Addr::get_path_name (void) const +{ + return this->filename_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/FILE_Connector.cpp b/dep/acelite/ace/FILE_Connector.cpp new file mode 100644 index 00000000000..b59b1e8913d --- /dev/null +++ b/dep/acelite/ace/FILE_Connector.cpp @@ -0,0 +1,84 @@ +// $Id: FILE_Connector.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/FILE_Connector.h" +#include "ace/Handle_Ops.h" +#include "ace/OS_NS_stdlib.h" + +#if !defined (__ACE_INLINE__) +#include "ace/FILE_Connector.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID(ace, FILE_Connector, "$Id: FILE_Connector.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_FILE_Connector) + +void +ACE_FILE_Connector::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_FILE_Connector::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n"))); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +ACE_FILE_Connector::ACE_FILE_Connector (void) +{ + ACE_TRACE ("ACE_FILE_Connector::ACE_FILE_Connector"); +} + +int +ACE_FILE_Connector::connect (ACE_FILE_IO &new_io, + const ACE_FILE_Addr &remote_sap, + ACE_Time_Value *timeout, + const ACE_Addr &, + int, + int flags, + int perms) +{ + ACE_TRACE ("ACE_FILE_Connector::connect"); + ACE_ASSERT (new_io.get_handle () == ACE_INVALID_HANDLE); + + ACE_HANDLE handle = ACE_INVALID_HANDLE; + + // Check to see if caller has requested that we create the filename. + if (reinterpret_cast ( + const_cast (remote_sap)) == ACE_Addr::sap_any) + { + // Create a new temporary file. + // Use ACE_OS::mkstemp() if it is available since it avoids a + // race condition, and subsequently a security hole due to that + // race condition (specifically, a denial-of-service attack). + // + // However, using mkstemp() prevents us from doing a timed open + // since it opens the file for us. Better to avoid the race + // condition. + char filename[] = "ace-file-XXXXXX"; + + handle = ACE_OS::mkstemp (filename); // mkstemp() replaces "XXXXXX" + + if (handle == ACE_INVALID_HANDLE + || new_io.addr_.set (ACE_TEXT_CHAR_TO_TCHAR (filename)) != 0) + return -1; + + new_io.set_handle (handle); + + return 0; + } + else + new_io.addr_ = remote_sap; // class copy. + + handle = ACE::handle_timed_open (timeout, + new_io.addr_.get_path_name (), + flags, + perms); + + new_io.set_handle (handle); + return handle == ACE_INVALID_HANDLE ? -1 : 0; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/FILE_Connector.h b/dep/acelite/ace/FILE_Connector.h new file mode 100644 index 00000000000..624ab3d6a5f --- /dev/null +++ b/dep/acelite/ace/FILE_Connector.h @@ -0,0 +1,113 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file FILE_Connector.h + * + * $Id: FILE_Connector.h 82723 2008-09-16 09:35:44Z johnnyw $ + * + * @author Doug Schmidt + */ +//============================================================================= + +#ifndef ACE_FILE_CONNECTOR_H +#define ACE_FILE_CONNECTOR_H +#include /**/ "ace/pre.h" + +#include "ace/FILE_IO.h" +#include "ace/Log_Msg.h" +#include "ace/os_include/os_fcntl.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_FILE_Connector + * + * @brief Defines an active connection factory for the ACE_FILE wrappers. + * + * Note that the O_APPEND flag is only partly supported on Win32. If + * you specify O_APPEND, then the file pointer will be positioned at + * the end of the file initially during open, but it is not + * re-positioned at the end prior to each write, as specified by + * POSIX. This is generally good enough for typical situations, but + * it is ``not quite right'' in its semantics. + */ +class ACE_Export ACE_FILE_Connector +{ +public: + // = Initialization methods. + /// Default constructor. + ACE_FILE_Connector (void); + + /** + * Actively ``connect'' and produce a @a new_io ACE_FILE_IO object + * if things go well. The @a remote_sap is the file that we are + * trying to create/open. If it's the default value of + * ACE_Addr::sap_any then the user is letting the OS create the + * filename (via ). The @a timeout is the amount of + * time to wait to create/open the file. If it's 0 then we block + * indefinitely. If *timeout == {0, 0} then the file is created + * using non-blocking mode. If *timeout > {0, 0} then this is the + * maximum amount of time to wait before timing out. The + * @a local_sap and @a reuse_addr parameters are ignored. The @a flags + * and @a perms arguments are passed down to the + * method. + */ + ACE_FILE_Connector (ACE_FILE_IO &new_io, + const ACE_FILE_Addr &remote_sap, + ACE_Time_Value *timeout = 0, + const ACE_Addr &local_sap = ACE_Addr::sap_any, + int reuse_addr = 0, + int flags = O_RDWR | O_CREAT, + int perms = ACE_DEFAULT_FILE_PERMS); + + /** + * Actively ``connect'' and produce a @a new_io object + * if things go well. The @a remote_sap is the file that we are + * trying to create/open. If it's the default value of + * ACE_Addr::sap_any then the user is letting the OS create the + * filename (via ). The @a timeout is the amount of + * time to wait to create/open the file. If it's 0 then we block + * indefinitely. If *timeout == {0, 0} then the file is created + * using non-blocking mode. In this case, if the create/open can't + * be done immediately the value of -1 is returned with . If *timeout > {0, 0} then this is the maximum amount of + * time to wait before timing out. If the time expires before the + * connection is made @c errno == ETIME. The @a local_sap and + * @a reuse_addr parameters are ignored. The @a flags and @a perms + * arguments are passed down to the method. + */ + int connect (ACE_FILE_IO &new_io, + const ACE_FILE_Addr &remote_sap, + ACE_Time_Value *timeout = 0, + const ACE_Addr &local_sap = ACE_Addr::sap_any, + int reuse_addr = 0, + int flags = O_RDWR | O_CREAT, + int perms = ACE_DEFAULT_FILE_PERMS); + + /// Resets any event associations on this handle + bool reset_new_handle (ACE_HANDLE handle); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + + // = Meta-type "trait" information. + typedef ACE_FILE_Addr PEER_ADDR; + typedef ACE_FILE_IO PEER_STREAM; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/FILE_Connector.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_FILE_CONNECTOR_H */ diff --git a/dep/acelite/ace/FILE_Connector.inl b/dep/acelite/ace/FILE_Connector.inl new file mode 100644 index 00000000000..953f661fb05 --- /dev/null +++ b/dep/acelite/ace/FILE_Connector.inl @@ -0,0 +1,35 @@ +// -*- C++ -*- +// +// $Id: FILE_Connector.inl 82723 2008-09-16 09:35:44Z johnnyw $ + +// Creates a Local ACE_FILE. + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE +ACE_FILE_Connector::ACE_FILE_Connector (ACE_FILE_IO &new_io, + const ACE_FILE_Addr &remote_sap, + ACE_Time_Value *timeout, + const ACE_Addr &local_sap, + int reuse_addr, + int flags, + int perms) +{ + ACE_TRACE ("ACE_FILE_Connector::ACE_FILE_Connector"); + if (this->connect (new_io, remote_sap, timeout, local_sap, + reuse_addr, flags, perms) == ACE_IO_SAP::INVALID_HANDLE + && timeout != 0 && !(errno == EWOULDBLOCK || errno == ETIME)) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("address %s, %p\n"), + remote_sap.get_path_name (), + ACE_TEXT ("ACE_FILE_IO"))); +} + +ACE_INLINE bool +ACE_FILE_Connector::reset_new_handle (ACE_HANDLE) +{ + // Nothing to do here since the handle is not a socket + return false; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/FILE_IO.cpp b/dep/acelite/ace/FILE_IO.cpp new file mode 100644 index 00000000000..d6bf084dfae --- /dev/null +++ b/dep/acelite/ace/FILE_IO.cpp @@ -0,0 +1,145 @@ +// $Id: FILE_IO.cpp 82559 2008-08-07 20:23:07Z parsons $ + +#include "ace/FILE_IO.h" + +#include "ace/Log_Msg.h" +#include "ace/OS_NS_sys_stat.h" +#include "ace/OS_Memory.h" +#include "ace/Truncate.h" + +#if !defined (__ACE_INLINE__) +#include "ace/FILE_IO.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID(ace, FILE_IO, "$Id: FILE_IO.cpp 82559 2008-08-07 20:23:07Z parsons $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_FILE_IO) + +void +ACE_FILE_IO::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_FILE_IO::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + this->addr_.dump (); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +// Simple-minded do nothing constructor. + +ACE_FILE_IO::ACE_FILE_IO (void) +{ + ACE_TRACE ("ACE_FILE_IO::ACE_FILE_IO"); +} + +// Send N char *ptrs and int lengths. Note that the char *'s precede +// the ints (basically, an varargs version of writev). The count N is +// the *total* number of trailing arguments, *not* a couple of the +// number of tuple pairs! + +ssize_t +ACE_FILE_IO::send (size_t n, ...) const +{ + ACE_TRACE ("ACE_FILE_IO::send"); + va_list argp; + int total_tuples = ACE_Utils::truncate_cast (n / 2); + iovec *iovp = 0; +#if defined (ACE_HAS_ALLOCA) + iovp = (iovec *) alloca (total_tuples * sizeof (iovec)); +#else + ACE_NEW_RETURN (iovp, + iovec[total_tuples], + -1); +#endif /* !defined (ACE_HAS_ALLOCA) */ + + va_start (argp, n); + + for (int i = 0; i < total_tuples; i++) + { + iovp[i].iov_base = va_arg (argp, char *); + iovp[i].iov_len = va_arg (argp, int); + } + + ssize_t result = ACE_OS::writev (this->get_handle (), + iovp, + total_tuples); +#if !defined (ACE_HAS_ALLOCA) + delete [] iovp; +#endif /* !defined (ACE_HAS_ALLOCA) */ + va_end (argp); + return result; +} + +// This is basically an interface to ACE_OS::readv, that doesn't use +// the struct iovec explicitly. The ... can be passed as an arbitrary +// number of (char *ptr, int len) tuples. However, the count N is the +// *total* number of trailing arguments, *not* a couple of the number +// of tuple pairs! + +ssize_t +ACE_FILE_IO::recv (size_t n, ...) const +{ + ACE_TRACE ("ACE_FILE_IO::recv"); + va_list argp; + int total_tuples = ACE_Utils::truncate_cast (n / 2); + iovec *iovp = 0; +#if defined (ACE_HAS_ALLOCA) + iovp = (iovec *) alloca (total_tuples * sizeof (iovec)); +#else + ACE_NEW_RETURN (iovp, + iovec[total_tuples], + -1); +#endif /* !defined (ACE_HAS_ALLOCA) */ + + va_start (argp, n); + + for (int i = 0; i < total_tuples; i++) + { + iovp[i].iov_base = va_arg (argp, char *); + iovp[i].iov_len = va_arg (argp, int); + } + + ssize_t const result = ACE_OS::readv (this->get_handle (), + iovp, + total_tuples); +#if !defined (ACE_HAS_ALLOCA) + delete [] iovp; +#endif /* !defined (ACE_HAS_ALLOCA) */ + va_end (argp); + return result; +} + +// Allows a client to read from a file without having to provide a +// buffer to read. This method determines how much data is in the +// file, allocates a buffer of this size, reads in the data, and +// returns the number of bytes read. + +ssize_t +ACE_FILE_IO::recvv (iovec *io_vec) +{ + ACE_TRACE ("ACE_FILE_IO::recvv"); + + io_vec->iov_base = 0; + size_t const length = + static_cast (ACE_OS::filesize (this->get_handle ())); + + if (length > 0) + { + ACE_NEW_RETURN (io_vec->iov_base, + char[length], + -1); + io_vec->iov_len = this->recv_n (io_vec->iov_base, + length); + return io_vec->iov_len; + } + else + { + return ACE_Utils::truncate_cast (length); + } +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/FILE_IO.h b/dep/acelite/ace/FILE_IO.h new file mode 100644 index 00000000000..951069e3652 --- /dev/null +++ b/dep/acelite/ace/FILE_IO.h @@ -0,0 +1,170 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file FILE_IO.h + * + * $Id: FILE_IO.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_FILE_IO_H +#define ACE_FILE_IO_H +#include /**/ "ace/pre.h" + +#include "ace/FILE.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/FILE_Addr.h" + +// Used in the FILE_IO.h file... +#include "ace/os_include/os_stdio.h" +#include "ace/os_include/sys/os_uio.h" + +#if defined (ACE_HAS_STREAM_PIPES) +# include "ace/OS_NS_stropts.h" +#endif /* ACE_HAS_STREAM_PIPES */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Forward decl. +class ACE_Message_Block; +class ACE_Time_Value; + +/** + * @class ACE_FILE_IO + * + * @brief Read/Write operations on Files + */ +class ACE_Export ACE_FILE_IO : public ACE_FILE +{ +public: + friend class ACE_FILE_Connector; + + // = Initialization method. + /// Default constructor. + ACE_FILE_IO (void); + + /// send upto @a n bytes in @a buf. + ssize_t send (const void *buf, size_t n) const; + + /// Recv upto @a n bytes in @a buf. + ssize_t recv (void *buf, size_t n) const; + + /// Send n bytes, keep trying until n are sent. + ssize_t send_n (const void *buf, size_t n) const; + + /// Send all the @a message_blocks chained through their and + /// pointers. This call uses the underlying OS gather-write + /// operation to reduce the domain-crossing penalty. + ssize_t send_n (const ACE_Message_Block *message_block, + const ACE_Time_Value *timeout = 0, + size_t *bytes_transferred = 0); + + /// Recv n bytes, keep trying until n are received. + ssize_t recv_n (void *buf, size_t n) const; + +#if defined (ACE_HAS_STREAM_PIPES) + /// Send bytes via STREAM pipes. + ssize_t send (const ACE_Str_Buf *cntl, + const ACE_Str_Buf *data, + int flags = 0) const; + + /// Recv bytes via STREAM pipes. + ssize_t recv (ACE_Str_Buf *cntl, + ACE_Str_Buf *data, + int *flags) const; + + /// Send bytes via STREAM pipes using "band" mode. + ssize_t send (const ACE_Str_Buf *cntl, + const ACE_Str_Buf *data, + int band, + int flags) const; + + /// Recv bytes via STREAM pipes using "band" mode. + ssize_t recv (ACE_Str_Buf *cntl, + ACE_Str_Buf *data, + int *band, + int *flags) const; + +#endif /* ACE_HAS_STREAM_PIPES */ + + /// Send iovecs via <::writev>. + ssize_t send (const iovec iov[], int n) const; + + /// Recv iovecs via <::readv>. + ssize_t recv (iovec iov[], int n) const; + + /** + * Send N char *ptrs and int lengths. Note that the char *'s + * precede the ints (basically, an varargs version of writev). The + * count N is the *total* number of trailing arguments, *not* a + * couple of the number of tuple pairs! + */ + ssize_t send (size_t n, ...) const; + + /** + * This is an interface to ::readv, that doesn't use the struct + * iovec explicitly. The ... can be passed as an arbitrary number + * of (char *ptr, int len) tuples. However, the count N is the + * *total* number of trailing arguments, *not* a couple of the + * number of tuple pairs! + */ + ssize_t recv (size_t n, ...) const; + + /// Send @a n bytes via Win32 WriteFile using overlapped I/O. + ssize_t send (const void *buf, + size_t n, + ACE_OVERLAPPED *overlapped) const; + + /// Recv @a n bytes via Win32 ReadFile using overlapped I/O. + ssize_t recv (void *buf, + size_t n, + ACE_OVERLAPPED *overlapped) const; + + /// Send an @c iovec of size @a n to the file. + ssize_t sendv (const iovec iov[], + int n) const; + + /** + * Allows a client to read from a file without having to provide a + * buffer to read. This method determines how much data is in the + * file, allocates a buffer of this size, reads in the data, and + * returns the number of bytes read. The caller is responsible for + * deleting the member in the field of using + * delete [] io_vec->iov_base. + */ + ssize_t recvv (iovec *io_vec); + + /// Send an of size @a n to the file. Will block until all + /// bytes are sent or an error occurs. + ssize_t sendv_n (const iovec iov[], + int n) const; + + /// Receive an of size @a n to the file. + ssize_t recvv_n (iovec iov[], + int n) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + + // = Meta-type info + typedef ACE_FILE_Addr PEER_ADDR; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/FILE_IO.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_FILE_IO_H */ diff --git a/dep/acelite/ace/FILE_IO.inl b/dep/acelite/ace/FILE_IO.inl new file mode 100644 index 00000000000..d2e4f756c2c --- /dev/null +++ b/dep/acelite/ace/FILE_IO.inl @@ -0,0 +1,152 @@ +// -*- C++ -*- +// +// $Id: FILE_IO.inl 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/ACE.h" +#include "ace/OS_NS_sys_uio.h" +#include "ace/OS_NS_unistd.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE ssize_t +ACE_FILE_IO::sendv_n (const iovec iov[], int n) const +{ + ACE_TRACE ("ACE_FILE_IO::sendv_n"); + return ACE::writev_n (this->get_handle (), + iov, + n); +} + +ACE_INLINE ssize_t +ACE_FILE_IO::send_n (const ACE_Message_Block *message_block, + const ACE_Time_Value *timeout, + size_t *bytes_transferred) +{ + ACE_TRACE ("ACE_FILE_IO::send_n"); + ACE_UNUSED_ARG (timeout); + return ACE::write_n (this->get_handle (), + message_block, + bytes_transferred); +} + +// Recv an n byte message from the file. + +ACE_INLINE ssize_t +ACE_FILE_IO::recvv_n (iovec iov[], int n) const +{ + ACE_TRACE ("ACE_FILE_IO::recvv_n"); + // @@ Carlos, can you please update this to call the + // new ACE::recvv_n() method that you write? + return ACE_OS::readv (this->get_handle (), + iov, + n); +} + +// Send an of size to the file. + +ACE_INLINE ssize_t +ACE_FILE_IO::sendv (const iovec iov[], int n) const +{ + ACE_TRACE ("ACE_FILE_IO::sendv"); + return ACE_OS::writev (this->get_handle (), iov, n); +} + +// Send exactly N bytes from BUF to this file. Keeping trying until +// this many bytes are sent. + +ACE_INLINE ssize_t +ACE_FILE_IO::send_n (const void *buf, size_t n) const +{ + ACE_TRACE ("ACE_FILE_IO::send_n"); + return ACE::write_n (this->get_handle (), buf, n); +} + +// Receive exactly N bytes from this file into BUF. Keep trying until +// this many bytes are received. + +ACE_INLINE ssize_t +ACE_FILE_IO::recv_n (void *buf, size_t n) const +{ + ACE_TRACE ("ACE_FILE_IO::recv_n"); + return ACE::read_n (this->get_handle (), buf, n); +} + +ACE_INLINE ssize_t +ACE_FILE_IO::send (const void *buf, size_t n) const +{ + ACE_TRACE ("ACE_FILE_IO::send"); + return ACE_OS::write (this->get_handle (), buf, n); +} + +ACE_INLINE ssize_t +ACE_FILE_IO::recv (void *buf, size_t n) const +{ + ACE_TRACE ("ACE_FILE_IO::recv"); + return ACE_OS::read (this->get_handle (), buf, n); +} + +ACE_INLINE ssize_t +ACE_FILE_IO::send (const iovec iov[], int n) const +{ + ACE_TRACE ("ACE_FILE_IO::send"); + return ACE_OS::writev (this->get_handle (), iov, n); +} + +ACE_INLINE ssize_t +ACE_FILE_IO::recv (iovec iov[], int n) const +{ + ACE_TRACE ("ACE_FILE_IO::recv"); + return ACE_OS::readv (this->get_handle (), iov, n); +} + +#if defined (ACE_HAS_STREAM_PIPES) +ACE_INLINE ssize_t +ACE_FILE_IO::recv (ACE_Str_Buf *cntl, ACE_Str_Buf *data, int *band, int *flags) const +{ + ACE_TRACE ("ACE_FILE_IO::recv"); + return ACE_OS::getpmsg (this->get_handle (), (strbuf *) cntl, (strbuf *) data, band, flags); +} + +ACE_INLINE ssize_t +ACE_FILE_IO::send (const ACE_Str_Buf *cntl, const ACE_Str_Buf *data, int band, int flags) const +{ + ACE_TRACE ("ACE_FILE_IO::send"); + return ACE_OS::putpmsg (this->get_handle (), (strbuf *) cntl, (strbuf *) data, band, flags); +} + +ACE_INLINE ssize_t +ACE_FILE_IO::recv (ACE_Str_Buf *cntl, ACE_Str_Buf *data, int *flags) const +{ + ACE_TRACE ("ACE_FILE_IO::recv"); + return ACE_OS::getmsg (this->get_handle (), (strbuf *) cntl, (strbuf *) data, flags); +} + +ACE_INLINE ssize_t +ACE_FILE_IO::send (const ACE_Str_Buf *cntl, const ACE_Str_Buf *data, int flags) const +{ + ACE_TRACE ("ACE_FILE_IO::send"); + return ACE_OS::putmsg (this->get_handle (), (strbuf *) cntl, (strbuf *) data, flags); +} + +ACE_INLINE ssize_t +ACE_FILE_IO::send (const void *buf, size_t n, + ACE_OVERLAPPED *overlapped) const +{ + ACE_TRACE ("ACE_FILE_IO::send"); + return ACE_OS::write (this->get_handle (), + buf, n, + overlapped); +} + +ACE_INLINE ssize_t +ACE_FILE_IO::recv (void *buf, size_t n, + ACE_OVERLAPPED *overlapped) const +{ + ACE_TRACE ("ACE_FILE_IO::recv"); + return ACE_OS::read (this->get_handle (), buf, n, + overlapped); +} + +#endif /* ACE_HAS_STREAM_PIPES */ + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/File_Lock.cpp b/dep/acelite/ace/File_Lock.cpp new file mode 100644 index 00000000000..9eac8883d48 --- /dev/null +++ b/dep/acelite/ace/File_Lock.cpp @@ -0,0 +1,72 @@ +// $Id: File_Lock.cpp 87213 2009-10-23 13:11:34Z johnnyw $ + +#include "ace/File_Lock.h" +#include "ace/Log_Msg.h" + +#if !defined (__ACE_INLINE__) +#include "ace/File_Lock.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID(ace, File_Lock, "$Id: File_Lock.cpp 87213 2009-10-23 13:11:34Z johnnyw $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_File_Lock) + +void +ACE_File_Lock::dump (void) const +{ +#if defined (ACE_HAS_DUMP) +// ACE_TRACE ("ACE_File_Lock::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + this->lock_.dump (); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +ACE_File_Lock::ACE_File_Lock (ACE_HANDLE h, + bool unlink_in_destructor) + : removed_ (false), + unlink_in_destructor_ (unlink_in_destructor) +{ +// ACE_TRACE ("ACE_File_Lock::ACE_File_Lock"); + if (ACE_OS::flock_init (&this->lock_) == -1) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_File_Lock::ACE_File_Lock"))); + this->set_handle (h); +} + +ACE_File_Lock::ACE_File_Lock (const ACE_TCHAR *name, + int flags, + mode_t perms, + bool unlink_in_destructor) + : unlink_in_destructor_ (unlink_in_destructor) +{ +// ACE_TRACE ("ACE_File_Lock::ACE_File_Lock"); + + if (this->open (name, flags, perms) == -1) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p %s\n"), + ACE_TEXT ("ACE_File_Lock::ACE_File_Lock"), + name)); +} + +int +ACE_File_Lock::open (const ACE_TCHAR *name, + int flags, + mode_t perms) +{ +// ACE_TRACE ("ACE_File_Lock::open"); + this->removed_ = false; + return ACE_OS::flock_init (&this->lock_, flags, name, perms); +} + +ACE_File_Lock::~ACE_File_Lock (void) +{ +// ACE_TRACE ("ACE_File_Lock::~ACE_File_Lock"); + this->remove (this->unlink_in_destructor_); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/File_Lock.h b/dep/acelite/ace/File_Lock.h new file mode 100644 index 00000000000..4cd58fcd184 --- /dev/null +++ b/dep/acelite/ace/File_Lock.h @@ -0,0 +1,170 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file File_Lock.h + * + * $Id: File_Lock.h 91064 2010-07-12 10:11:24Z johnnyw $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_FILE_LOCK_H +#define ACE_FILE_LOCK_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/OS_NS_stdio.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_File_Lock + * + * @brief A wrapper around the UNIX file locking mechanism. + * + * Allows us to "adapt" the UNIX file locking mechanisms to work + * with all of our Guard stuff... + */ +class ACE_Export ACE_File_Lock +{ +public: + /** + * Set the of the File_Lock to @a handle. Note that this + * constructor assumes ownership of the @a handle and will close it + * down in . If you want the @a handle to stay open when + * is called make sure to call on the @a handle. + * If you don't want the file unlinked in the destructor pass a + * zero value for . + */ + ACE_File_Lock (ACE_HANDLE handle = ACE_INVALID_HANDLE, + bool unlink_in_destructor = true); + + /// Open the @a filename with @a flags and @a mode and set the result + /// to . If you don't want the file unlinked in the + /// destructor pass a false value for @a unlink_in_destructor. + ACE_File_Lock (const ACE_TCHAR *filename, + int flags, + mode_t mode = 0, + bool unlink_in_destructor = true); + + /// Open the @a filename with @a flags and @a mode and set the result to + /// . + int open (const ACE_TCHAR *filename, + int flags, + mode_t mode = 0); + + /// Remove a File lock by releasing it and closing down the . + ~ACE_File_Lock (void); + + /// Remove a File lock by releasing it and closing down the + /// . If @a unlink_file is true then we unlink the file. + int remove (bool unlink_file = true); + + /** + * Note, for interface uniformity with other synchronization + * wrappers we include the acquire() method. This is implemented as + * a write-lock to be on the safe-side... + */ + int acquire (short whence = 0, ACE_OFF_T start = 0, ACE_OFF_T len = 1); + + /** + * Note, for interface uniformity with other synchronization + * wrappers we include the method. This is implemented + * as a write-lock to be on the safe-side... Returns -1 on failure. + * If we "failed" because someone else already had the lock, @c errno + * is set to @c EBUSY. + */ + int tryacquire (short whence = 0, ACE_OFF_T start = 0, ACE_OFF_T len = 1); + + /// Unlock a readers/writer lock. + int release (short whence = 0, ACE_OFF_T start = 0, ACE_OFF_T len = 1); + + /// Acquire a write lock, but block if any readers or a + /// writer hold the lock. + int acquire_write (short whence = 0, ACE_OFF_T start = 0, ACE_OFF_T len = 1); + + /** + * Conditionally acquire a write lock (i.e., won't block). Returns + * -1 on failure. If we "failed" because someone else already had + * the lock, @c errno is set to @c EBUSY. + */ + int tryacquire_write (short whence = 0, ACE_OFF_T start = 0, ACE_OFF_T len = 1); + + /** + * Conditionally upgrade to a write lock (i.e., won't block). Returns + * -1 on failure. If we "failed" because someone else already had + * the lock, @c errno is set to @c EBUSY. + */ + int tryacquire_write_upgrade (short whence = 0, + ACE_OFF_T start = 0, + ACE_OFF_T len = 1); + + /** + * Acquire a read lock, but block if a writer hold the lock. + * Returns -1 on failure. If we "failed" because someone else + * already had the lock, @c errno is set to @c EBUSY. + */ + int acquire_read (short whence = 0, ACE_OFF_T start = 0, ACE_OFF_T len = 1); + + /** + * Conditionally acquire a read lock (i.e., won't block). Returns + * -1 on failure. If we "failed" because someone else already had + * the lock, @c errno is set to @c EBUSY. + */ + int tryacquire_read (short whence = 0, ACE_OFF_T start = 0, ACE_OFF_T len = 1); + + /// Get underlying ACE_HANDLE for the file. + ACE_HANDLE get_handle (void) const; + + /** + * Set underlying ACE_HANDLE. Note that this method assumes + * ownership of the @a handle and will close it down in . If + * you want the @a handle to stay open when is called make + * sure to call on the @a handle before closing it. You are + * responsible for the closing the existing @a handle before + * overwriting it. + */ + void set_handle (ACE_HANDLE); + + /// Dump state of the object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + /// Locking structure for OS record locks. + ACE_OS::ace_flock_t lock_; + + /// Keeps track of whether has been called yet to avoid + /// multiple calls, e.g., explicitly and implicitly in the + /// destructor. This flag isn't protected by a lock, so make sure + /// that you don't have multiple threads simultaneously calling + /// on the same object, which is a bad idea anyway... + bool removed_; + + /// Keeps track of whether to unlink the underlying file in the + /// destructor. + bool const unlink_in_destructor_; + +private: + // = Prevent assignment and initialization. + void operator= (const ACE_File_Lock &); + ACE_File_Lock (const ACE_File_Lock &); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/File_Lock.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_FILE_LOCK_H */ diff --git a/dep/acelite/ace/File_Lock.inl b/dep/acelite/ace/File_Lock.inl new file mode 100644 index 00000000000..cf0cefed16e --- /dev/null +++ b/dep/acelite/ace/File_Lock.inl @@ -0,0 +1,96 @@ +// -*- C++ -*- +// +// $Id: File_Lock.inl 87213 2009-10-23 13:11:34Z johnnyw $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE int +ACE_File_Lock::acquire_read (short whence, ACE_OFF_T start, ACE_OFF_T len) +{ +// ACE_TRACE ("ACE_File_Lock::acquire_read"); + return ACE_OS::flock_rdlock (&this->lock_, whence, start, len); +} + +ACE_INLINE int +ACE_File_Lock::tryacquire_read (short whence, ACE_OFF_T start, ACE_OFF_T len) +{ +// ACE_TRACE ("ACE_File_Lock::tryacquire_read"); + return ACE_OS::flock_tryrdlock (&this->lock_, whence, start, len); +} + +ACE_INLINE int +ACE_File_Lock::tryacquire_write (short whence, ACE_OFF_T start, ACE_OFF_T len) +{ +// ACE_TRACE ("ACE_File_Lock::tryacquire_write"); + return ACE_OS::flock_trywrlock (&this->lock_, whence, start, len); +} + +ACE_INLINE int +ACE_File_Lock::tryacquire_write_upgrade (short whence, + ACE_OFF_T start, + ACE_OFF_T len) +{ +// ACE_TRACE ("ACE_File_Lock::tryacquire_write_upgrade"); + return ACE_OS::flock_trywrlock (&this->lock_, whence, start, len); +} + +ACE_INLINE int +ACE_File_Lock::tryacquire (short whence, ACE_OFF_T start, ACE_OFF_T len) +{ +// ACE_TRACE ("ACE_File_Lock::tryacquire"); + return this->tryacquire_write (whence, start, len); +} + +ACE_INLINE int +ACE_File_Lock::acquire_write (short whence, ACE_OFF_T start, ACE_OFF_T len) +{ +// ACE_TRACE ("ACE_File_Lock::acquire_write"); + return ACE_OS::flock_wrlock (&this->lock_, whence, start, len); +} + +ACE_INLINE int +ACE_File_Lock::acquire (short whence, ACE_OFF_T start, ACE_OFF_T len) +{ +// ACE_TRACE ("ACE_File_Lock::acquire"); + return this->acquire_write (whence, start, len); +} + +ACE_INLINE int +ACE_File_Lock::release (short whence, ACE_OFF_T start, ACE_OFF_T len) +{ +// ACE_TRACE ("ACE_File_Lock::release"); + return ACE_OS::flock_unlock (&this->lock_, whence, start, len); +} + +ACE_INLINE int +ACE_File_Lock::remove (bool unlink_file) +{ +// ACE_TRACE ("ACE_File_Lock::remove"); + + int result = 0; + + if (!this->removed_) + { + this->removed_ = true; + result = ACE_OS::flock_destroy (&this->lock_, + unlink_file); + } + return result; +} + +ACE_INLINE ACE_HANDLE +ACE_File_Lock::get_handle (void) const +{ +// ACE_TRACE ("ACE_File_Lock::get_handle"); + return this->lock_.handle_; +} + +ACE_INLINE void +ACE_File_Lock::set_handle (ACE_HANDLE h) +{ +// ACE_TRACE ("ACE_File_Lock::set_handle"); + this->lock_.handle_ = h; + this->removed_ = false; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Filecache.cpp b/dep/acelite/ace/Filecache.cpp new file mode 100644 index 00000000000..494749ca7ce --- /dev/null +++ b/dep/acelite/ace/Filecache.cpp @@ -0,0 +1,746 @@ +// $Id: Filecache.cpp 83735 2008-11-14 09:41:52Z johnnyw $ + +#include "ace/Filecache.h" +#include "ace/Object_Manager.h" +#include "ace/Log_Msg.h" +#include "ace/ACE.h" +#include "ace/Guard_T.h" +#include "ace/OS_NS_string.h" +#include "ace/OS_NS_time.h" +#include "ace/OS_NS_unistd.h" +#include "ace/OS_NS_fcntl.h" +#include "ace/Truncate.h" + +ACE_RCSID (ace, + Filecache, + "$Id: Filecache.cpp 83735 2008-11-14 09:41:52Z johnnyw $") + +#if defined (ACE_WIN32) +// Specifies no sharing flags. +#define R_MASK ACE_DEFAULT_OPEN_PERMS +#define W_MASK 0 +#else +#define R_MASK S_IRUSR|S_IRGRP|S_IROTH +#define W_MASK S_IRUSR|S_IRGRP|S_IROTH|S_IWUSR|S_IWGRP|S_IWOTH +#endif /* ACE_WIN32 */ + +#if defined (ACE_WIN32) +// See if you can get rid of some of these. +#define READ_FLAGS (FILE_FLAG_SEQUENTIAL_SCAN | \ + FILE_FLAG_OVERLAPPED | \ + O_RDONLY) +// static const int RCOPY_FLAGS = (FILE_FLAG_SEQUENTIAL_SCAN | +// O_RDONLY); +#define WRITE_FLAGS (FILE_FLAG_SEQUENTIAL_SCAN | \ + FILE_FLAG_OVERLAPPED | \ + O_RDWR | O_CREAT | O_TRUNC) +// static const int WCOPY_FLAGS = (FILE_FLAG_SEQUENTIAL_SCAN | +// O_RDWR | O_CREAT | O_TRUNC); +#else +#define READ_FLAGS O_RDONLY +// static const int RCOPY_FLAGS = O_RDONLY; +#define WRITE_FLAGS (O_RDWR | O_CREAT | O_TRUNC) +// static const int WCOPY_FLAGS = O_RDWR | O_CREAT | O_TRUNC; +#endif /* ACE_WIN32 */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// static data members +ACE_Filecache *ACE_Filecache::cvf_ = 0; + +void +ACE_Filecache_Handle::init (void) +{ + this->file_ = 0; + this->handle_ = ACE_INVALID_HANDLE; +} + +ACE_Filecache_Handle::ACE_Filecache_Handle (void) + : file_ (0), handle_ (0), mapit_ (0) +{ + this->init (); +} + +ACE_Filecache_Handle::ACE_Filecache_Handle (const ACE_TCHAR *filename, + ACE_Filecache_Flag mapit) + : file_ (0), handle_ (0), mapit_ (mapit) +{ + this->init (); + // Fetch the file from the Virtual_Filesystem let the + // Virtual_Filesystem do the work of cache coherency. + + // Filecache will also do the acquire, since it holds the lock at + // that time. + this->file_ = ACE_Filecache::instance ()->fetch (filename, mapit); +} + +ACE_Filecache_Handle::ACE_Filecache_Handle (const ACE_TCHAR *filename, + int size, + ACE_Filecache_Flag mapit) + : file_ (0), handle_ (0), mapit_ (mapit) +{ + this->init (); + + if (size == 0) + ACE_Filecache::instance ()->remove (filename); + else + { + // Since this is being opened for a write, simply create a new + // ACE_Filecache_Object now, and let the destructor add it into CVF + // later + + // Filecache will also do the acquire, since it holds the lock at + // that time. + this->file_ = ACE_Filecache::instance ()->create (filename, size); + } +} + +ACE_Filecache_Handle::~ACE_Filecache_Handle (void) +{ + if (this->handle_ != ACE_INVALID_HANDLE) + // this was dup ()'d + ACE_OS::close (this->handle_); + + ACE_Filecache::instance ()->finish (this->file_); +} + +void * +ACE_Filecache_Handle::address (void) const +{ + return this->file_ == 0 ? 0 : this->file_->address (); +} + +ACE_HANDLE +ACE_Filecache_Handle::handle (void) const +{ + if (this->handle_ == ACE_INVALID_HANDLE && this->file_ != 0) + { + ACE_Filecache_Handle *mutable_this = + const_cast (this); + mutable_this->handle_ = ACE_OS::dup (this->file_->handle ()); + } + return this->handle_; +} + +int +ACE_Filecache_Handle::error (void) const +{ + if (this->file_ == 0) + return -1; + else + return this->file_->error (); +} + +ACE_OFF_T +ACE_Filecache_Handle::size (void) const +{ + if (this->file_ == 0) + return -1; + else + return this->file_->size (); +} + +// ------------------ +// ACE_Filecache_Hash +// ------------------ + +#define ACE_Filecache_Hash \ + ACE_Hash_Map_Manager_Ex, ACE_Equal_To, ACE_Null_Mutex> +#define ACE_Filecache_Hash_Entry \ + ACE_Hash_Map_Entry + +template <> +ACE_Filecache_Hash_Entry::ACE_Hash_Map_Entry ( + const ACE_TCHAR *const &ext_id, + ACE_Filecache_Object *const &int_id, + ACE_Filecache_Hash_Entry *next, + ACE_Filecache_Hash_Entry *prev) + : ext_id_ (ext_id + ? ACE_OS::strdup (ext_id) + : ACE_OS::strdup (ACE_TEXT (""))), + int_id_ (int_id), + next_ (next), + prev_ (prev) +{ +} + +template <> +ACE_Filecache_Hash_Entry::ACE_Hash_Map_Entry (ACE_Filecache_Hash_Entry *next, + ACE_Filecache_Hash_Entry *prev) + : ext_id_ (0), + next_ (next), + prev_ (prev) +{ +} + +template <> +ACE_Filecache_Hash_Entry::~ACE_Hash_Map_Entry (void) +{ + ACE_OS::free ((void *) ext_id_); +} + +// We need these template specializations since KEY is defined as a +// ACE_TCHAR*, which doesn't have a hash() or equal() method defined on it. + +template <> +unsigned long +ACE_Filecache_Hash::hash (const ACE_TCHAR *const &ext_id) +{ + return ACE::hash_pjw (ext_id); +} + +template <> +int +ACE_Filecache_Hash::equal (const ACE_TCHAR *const &id1, + const ACE_TCHAR *const &id2) +{ + return ACE_OS::strcmp (id1, id2) == 0; +} + +#undef ACE_Filecache_Hash +#undef ACE_Filecache_Hash_Entry + + +// ------------- +// ACE_Filecache +// ------------- + +ACE_Filecache * +ACE_Filecache::instance (void) +{ + // Double check locking pattern. + if (ACE_Filecache::cvf_ == 0) + { + ACE_SYNCH_RW_MUTEX &lock = + *ACE_Managed_Object::get_preallocated_object + (ACE_Object_Manager::ACE_FILECACHE_LOCK); + ACE_GUARD_RETURN (ACE_SYNCH_RW_MUTEX, ace_mon, lock, 0); + + // @@ James, please check each of the ACE_NEW_RETURN calls to + // make sure that it is safe to return if allocation fails. + if (ACE_Filecache::cvf_ == 0) + ACE_NEW_RETURN (ACE_Filecache::cvf_, + ACE_Filecache, + 0); + } + + return ACE_Filecache::cvf_; +} + +ACE_Filecache::ACE_Filecache (void) + : size_ (ACE_DEFAULT_VIRTUAL_FILESYSTEM_TABLE_SIZE), + hash_ (size_) +{ +} + +ACE_Filecache::~ACE_Filecache (void) +{ +} + +ACE_Filecache_Object * +ACE_Filecache::insert_i (const ACE_TCHAR *filename, + ACE_SYNCH_RW_MUTEX &filelock, + int mapit) +{ + ACE_Filecache_Object *handle = 0; + + if (this->hash_.find (filename, handle) == -1) + { + ACE_NEW_RETURN (handle, + ACE_Filecache_Object (filename, filelock, 0, mapit), + 0); + + // ACE_DEBUG ((LM_DEBUG, ACE_TEXT (" (%t) CVF: creating %s\n"), filename)); + + if (this->hash_.bind (filename, handle) == -1) + { + delete handle; + handle = 0; + } + } + else + handle = 0; + + return handle; +} + +ACE_Filecache_Object * +ACE_Filecache::remove_i (const ACE_TCHAR *filename) +{ + ACE_Filecache_Object *handle = 0; + + // Disassociate file from the cache. + if (this->hash_.unbind (filename, handle) == 0) + { + handle->stale_ = 1; + + // Try a lock. If it succeeds, we can delete it now. + // Otherwise, it will clean itself up later. + if (handle->lock_.tryacquire_write () == 0) + { + delete handle; + handle = 0; + } + } + else + handle = 0; + + return handle; +} + +ACE_Filecache_Object * +ACE_Filecache::update_i (const ACE_TCHAR *filename, + ACE_SYNCH_RW_MUTEX &filelock, + int mapit) +{ + ACE_Filecache_Object *handle = 0; + + handle = this->remove_i (filename); + handle = this->insert_i (filename, filelock, mapit); + + return handle; +} + +int +ACE_Filecache::find (const ACE_TCHAR *filename) +{ + return this->hash_.find (filename); +} + + +ACE_Filecache_Object * +ACE_Filecache::remove (const ACE_TCHAR *filename) +{ + ACE_Filecache_Object *handle = 0; + + ACE_OFF_T loc = ACE::hash_pjw (filename) % this->size_; + ACE_SYNCH_RW_MUTEX &hashlock = this->hash_lock_[loc]; + // ACE_SYNCH_RW_MUTEX &filelock = this->file_lock_[loc]; + + if (this->hash_.find (filename, handle) != -1) + { + ACE_WRITE_GUARD_RETURN (ACE_SYNCH_RW_MUTEX, + ace_mon, + hashlock, + 0); + + return this->remove_i (filename); + } + + return 0; +} + + +ACE_Filecache_Object * +ACE_Filecache::fetch (const ACE_TCHAR *filename, int mapit) +{ + ACE_Filecache_Object *handle = 0; + + ACE_OFF_T loc = ACE::hash_pjw (filename) % this->size_; + ACE_SYNCH_RW_MUTEX &hashlock = this->hash_lock_[loc]; + ACE_SYNCH_RW_MUTEX &filelock = this->file_lock_[loc]; + + filelock.acquire_read (); + + if (this->hash_.find (filename, handle) == -1) + { + ACE_WRITE_GUARD_RETURN (ACE_SYNCH_RW_MUTEX, + ace_mon, + hashlock, + 0); + + // Second check in the method call + handle = this->insert_i (filename, filelock, mapit); + + if (handle == 0) + filelock.release (); + } + else + { + if (handle->update ()) + { + { + // Double check locking pattern + ACE_WRITE_GUARD_RETURN (ACE_SYNCH_RW_MUTEX, + ace_mon, + hashlock, + 0); + + // Second check in the method call + handle = this->update_i (filename, filelock, mapit); + + if (handle == 0) + filelock.release (); + } + } + // ACE_DEBUG ((LM_DEBUG, ACE_TEXT (" (%t) CVF: found %s\n"), filename)); + } + + return handle; +} + +ACE_Filecache_Object * +ACE_Filecache::create (const ACE_TCHAR *filename, int size) +{ + ACE_Filecache_Object *handle = 0; + + ACE_OFF_T loc = ACE::hash_pjw (filename) % this->size_; + ACE_SYNCH_RW_MUTEX &filelock = this->file_lock_[loc]; + + ACE_NEW_RETURN (handle, + ACE_Filecache_Object (filename, size, filelock), + 0); + handle->acquire (); + + return handle; +} + +ACE_Filecache_Object * +ACE_Filecache::finish (ACE_Filecache_Object *&file) +{ + if (file == 0) + return file; + + ACE_OFF_T loc = ACE::hash_pjw (file->filename_) % this->size_; + ACE_SYNCH_RW_MUTEX &hashlock = this->hash_lock_[loc]; + + if (file != 0) + switch (file->action_) + { + case ACE_Filecache_Object::ACE_WRITING: + { + ACE_WRITE_GUARD_RETURN (ACE_SYNCH_RW_MUTEX, + ace_mon, + hashlock, + 0); + + file->release (); + + this->remove_i (file->filename_); +#if 0 + int result = this->hash_.bind (file->filename (), file); + + if (result == 0) + file->acquire (); +#else + // Last one using a stale file is resposible for deleting it. + if (file->stale_) + { + // Try a lock. If it succeds, we can delete it now. + // Otherwise, it will clean itself up later. + if (file->lock_.tryacquire_write () == 0) + { + delete file; + file = 0; + } + } +#endif + } + + break; + default: + file->release (); + + // Last one using a stale file is resposible for deleting it. + if (file->stale_) + { + // Try a lock. If it succeds, we can delete it now. + // Otherwise, it will clean itself up later. + if (file->lock_.tryacquire_write () == 0) + { + delete file; + file = 0; + } + } + + break; + } + + return file; +} + +void +ACE_Filecache_Object::init (void) +{ + this->filename_[0] = '\0'; + this->handle_ = ACE_INVALID_HANDLE; + this->error_ = ACE_SUCCESS; + this->tempname_ = 0; + this->size_ = 0; + + ACE_OS::memset (&(this->stat_), 0, sizeof (this->stat_)); +} + +ACE_Filecache_Object::ACE_Filecache_Object (void) + : tempname_ (0), + mmap_ (), + handle_ (0), + // stat_ (), + size_ (0), + action_ (0), + error_ (0), + stale_ (0), + // sa_ (), + junklock_ (), + lock_ (junklock_) +{ + this->init (); +} + +ACE_Filecache_Object::ACE_Filecache_Object (const ACE_TCHAR *filename, + ACE_SYNCH_RW_MUTEX &lock, + LPSECURITY_ATTRIBUTES sa, + int mapit) + : tempname_ (0), + mmap_ (), + handle_ (0), + // stat_ (), + size_ (0), + action_ (0), + error_ (0), + stale_ (0), + sa_ (sa), + junklock_ (), + lock_ (lock) +{ + this->init (); + + // ASSERT strlen(filename) < sizeof (this->filename_) + ACE_OS::strcpy (this->filename_, filename); + this->action_ = ACE_Filecache_Object::ACE_READING; + // place ourselves into the READING state + + // Can we access the file? + if (ACE_OS::access (this->filename_, R_OK) == -1) + { + this->error_i (ACE_Filecache_Object::ACE_ACCESS_FAILED); + return; + } + + // Can we stat the file? + if (ACE_OS::stat (this->filename_, &this->stat_) == -1) + { + this->error_i (ACE_Filecache_Object::ACE_STAT_FAILED); + return; + } + + this->size_ = ACE_Utils::truncate_cast (this->stat_.st_size); + this->tempname_ = this->filename_; + + // Can we open the file? + this->handle_ = ACE_OS::open (this->tempname_, + READ_FLAGS, R_MASK, this->sa_); + if (this->handle_ == ACE_INVALID_HANDLE) + { + this->error_i (ACE_Filecache_Object::ACE_OPEN_FAILED, + ACE_TEXT ("ACE_Filecache_Object::ctor: open")); + return; + } + + if (mapit) + { + // Can we map the file? + if (this->mmap_.map (this->handle_, static_cast (-1), + PROT_READ, ACE_MAP_PRIVATE, 0, 0, this->sa_) != 0) + { + this->error_i (ACE_Filecache_Object::ACE_MEMMAP_FAILED, + ACE_TEXT ("ACE_Filecache_Object::ctor: map")); + ACE_OS::close (this->handle_); + this->handle_ = ACE_INVALID_HANDLE; + return; + } + } + + // Ok, finished! + this->action_ = ACE_Filecache_Object::ACE_READING; +} + +ACE_Filecache_Object::ACE_Filecache_Object (const ACE_TCHAR *filename, + ACE_OFF_T size, + ACE_SYNCH_RW_MUTEX &lock, + LPSECURITY_ATTRIBUTES sa) + : stale_ (0), + sa_ (sa), + lock_ (lock) +{ + this->init (); + + this->size_ = size; + ACE_OS::strcpy (this->filename_, filename); + this->action_ = ACE_Filecache_Object::ACE_WRITING; + + // Can we access the file? + if (ACE_OS::access (this->filename_, R_OK|W_OK) == -1 + // Does it exist? + && ACE_OS::access (this->filename_, F_OK) != -1) + { + // File exists, but we cannot access it. + this->error_i (ACE_Filecache_Object::ACE_ACCESS_FAILED); + return; + } + + this->tempname_ = this->filename_; + + // Can we open the file? + this->handle_ = ACE_OS::open (this->tempname_, WRITE_FLAGS, W_MASK, this->sa_); + if (this->handle_ == ACE_INVALID_HANDLE) + { + this->error_i (ACE_Filecache_Object::ACE_OPEN_FAILED, + ACE_TEXT ("ACE_Filecache_Object::acquire: open")); + return; + } + + // Can we write? + if (ACE_OS::pwrite (this->handle_, "", 1, this->size_ - 1) != 1) + { + this->error_i (ACE_Filecache_Object::ACE_WRITE_FAILED, + ACE_TEXT ("ACE_Filecache_Object::acquire: write")); + ACE_OS::close (this->handle_); + return; + } + + // Can we map? + if (this->mmap_.map (this->handle_, this->size_, PROT_RDWR, MAP_SHARED, + 0, 0, this->sa_) != 0) + { + this->error_i (ACE_Filecache_Object::ACE_MEMMAP_FAILED, + ACE_TEXT ("ACE_Filecache_Object::acquire: map")); + ACE_OS::close (this->handle_); + } + + // Ok, done! +} + +ACE_Filecache_Object::~ACE_Filecache_Object (void) +{ + if (this->error_ == ACE_SUCCESS) + { + this->mmap_.unmap (); + ACE_OS::close (this->handle_); + this->handle_ = ACE_INVALID_HANDLE; + } + + this->lock_.release (); +} + +int +ACE_Filecache_Object::acquire (void) +{ + return this->lock_.tryacquire_read (); +} + +int +ACE_Filecache_Object::release (void) +{ + if (this->action_ == ACE_WRITING) + { + // We are safe since only one thread has a writable Filecache_Object + +#if 0 + ACE_HANDLE original = ACE_OS::open (this->filename_, WRITE_FLAGS, W_MASK, + this->sa_); + if (original == ACE_INVALID_HANDLE) + this->error_ = ACE_Filecache_Object::ACE_OPEN_FAILED; + else if (ACE_OS::write (original, this->mmap_.addr (), + this->size_) == -1) + { + this->error_ = ACE_Filecache_Object::ACE_WRITE_FAILED; + ACE_OS::close (original); + ACE_OS::unlink (this->filename_); + } + else if (ACE_OS::stat (this->filename_, &this->stat_) == -1) + this->error_ = ACE_Filecache_Object::ACE_STAT_FAILED; +#endif + + this->mmap_.unmap (); + ACE_OS::close (this->handle_); + this->handle_ = ACE_INVALID_HANDLE; + +#if 0 + // Leave the file in an acquirable state. + this->handle_ = ACE_OS::open (this->tempname_, READ_FLAGS, R_MASK); + if (this->handle_ == ACE_INVALID_HANDLE) + { + this->error_i (ACE_Filecache_Object::ACE_OPEN_FAILED, + "ACE_Filecache_Object::acquire: open"); + } + else if (this->mmap_.map (this->handle_, -1, + PROT_READ, + ACE_MAP_PRIVATE, + 0, + 0, + this->sa_) != 0) + { + this->error_i (ACE_Filecache_Object::ACE_MEMMAP_FAILED, + "ACE_Filecache_Object::acquire: map"); + ACE_OS::close (this->handle_); + this->handle_ = ACE_INVALID_HANDLE; + } + + this->action_ = ACE_Filecache_Object::ACE_READING; +#endif + } + + return this->lock_.release (); +} + +int +ACE_Filecache_Object::error (void) const +{ + // The existence of the object means a read lock is being held. + return this->error_; +} + +int +ACE_Filecache_Object::error_i (int error_value, const ACE_TCHAR *s) +{ + s = s; + ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p.\n"), s)); + this->error_ = error_value; + return error_value; +} + +const ACE_TCHAR * +ACE_Filecache_Object::filename (void) const +{ + // The existence of the object means a read lock is being held. + return this->filename_; +} + +ACE_OFF_T +ACE_Filecache_Object::size (void) const +{ + // The existence of the object means a read lock is being held. + return this->size_; +} + +ACE_HANDLE +ACE_Filecache_Object::handle (void) const +{ + // The existence of the object means a read lock is being held. + return this->handle_; +} + +void * +ACE_Filecache_Object::address (void) const +{ + // The existence of the object means a read lock is being held. + return this->mmap_.addr (); +} + +int +ACE_Filecache_Object::update (void) const +{ + // The existence of the object means a read lock is being held. + int result; + ACE_stat statbuf; + + if (ACE_OS::stat (this->filename_, &statbuf) == -1) + result = 1; + else + result = ACE_OS::difftime (this->stat_.st_mtime, statbuf.st_mtime) < 0; + + return result; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Filecache.h b/dep/acelite/ace/Filecache.h new file mode 100644 index 00000000000..9165a70fcd3 --- /dev/null +++ b/dep/acelite/ace/Filecache.h @@ -0,0 +1,356 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Filecache.h + * + * $Id: Filecache.h 91066 2010-07-12 11:05:04Z johnnyw $ + * + * @author James Hu + */ +//============================================================================= + + +#ifndef ACE_FILECACHE_H +#define ACE_FILECACHE_H + +#include /**/ "ace/pre.h" + +#include "ace/Mem_Map.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Hash_Map_Manager_T.h" +#include "ace/Null_Mutex.h" +#include "ace/Synch_Traits.h" +#include "ace/RW_Thread_Mutex.h" +#include "ace/OS_NS_sys_stat.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +enum ACE_Filecache_Flag +{ + ACE_NOMAP = 0, + ACE_MAPIT = 1 +}; + +class ACE_Filecache_Object; + +/** + * @class ACE_Filecache_Handle + * + * @brief + * Abstraction over a real file. This is meant to be the entry + * point into the Cached Virtual Filesystem. + * + * This is a cached filesystem implementation based loosely on the + * implementation of JAWS_File. The interfaces will be nearly the + * same. The under-the-hood implementation should hopefully be a + * much faster thing. + * These will be given their own implementations later. For now, we + * borrow the implementation provided by JAWS. + * On creation, the cache is checked, and reference count is + * incremented. On destruction, reference count is decremented. If + * the reference count is 0, the file is removed from the cache. + * E.g. 1, + * { + * ACE_Filecache_Handle foo("foo.html"); + * this->peer ().send (foo.address (), foo.size ()); + * } + * E.g. 2, + * { + * ACE_Filecache_Handle foo("foo.html"); + * io->transmitfile (foo.handle (), this->peer ().handle ()); + * } + * E.g. 3, + * { + * ACE_Filecache_Handle foo("foo.html", content_length); + * this->peer ().recv (foo.address (), content_length); + * } + * TODO: + */ +class ACE_Export ACE_Filecache_Handle +{ + // (1) Get rid of the useless copying of files when reading. + // Although it does make sure the file you send isn't being changed, + // it doesn't make sure the file is in a sensible state before + // sending it. + // + // Alternative: if the file get's trashed while it is being shipped, + // let the client request the file again. The cache should have an + // updated copy by that point. + // + // (2) Use hashing for locating files. This means I need a hastable + // implementation with buckets. + // + // (3) Only lock when absolutely necessary. JAWS_Virtual_Filesystem was + // rather conservative, but for some reason it still ran into problems. + // Since this design should be simpler, problems should be easier to spot. + // +public: + + /// Query cache for file, and acquire it. Assumes the file is being + /// opened for reading. + ACE_Filecache_Handle (const ACE_TCHAR *filename, + ACE_Filecache_Flag mapit = ACE_MAPIT); + + /** + * Create new entry, and acquire it. Presence of SIZE assumes the + * file is being opened for writing. If SIZE is zero, assumes the + * file is to be removed from the cache. + */ + ACE_Filecache_Handle (const ACE_TCHAR *filename, + int size, + ACE_Filecache_Flag mapit = ACE_MAPIT); + + /// Closes any open handles, release acquired file. + ~ACE_Filecache_Handle (void); + + /// Base address of memory mapped file. + void *address (void) const; + + /// A handle (e.g., UNIX file descriptor, or NT file handle). + ACE_HANDLE handle (void) const; + + /// Any associated error in handle creation and acquisition. + int error (void) const; + + /// The size of the file. + ACE_OFF_T size (void) const; + +protected: + /// Default do nothing constructor. Prevent it from being called. + ACE_Filecache_Handle (void); + + /// Common initializations for constructors. + void init (void); + +public: + /// These come from ACE_Filecache_Object, which is an internal class. + enum + { + ACE_SUCCESS = 0, + ACE_ACCESS_FAILED, + ACE_OPEN_FAILED, + ACE_COPY_FAILED, + ACE_STAT_FAILED, + ACE_MEMMAP_FAILED, + ACE_WRITE_FAILED + }; + +private: + /// A reference to the low level instance. + ACE_Filecache_Object *file_; + + /// A dup'd version of the one from file_. + ACE_HANDLE handle_; + + int mapit_; +}; + +typedef ACE_Hash_Map_Manager_Ex, ACE_Equal_To, ACE_Null_Mutex> + ACE_Filecache_Hash; + +typedef ACE_Hash_Map_Entry ACE_Filecache_Hash_Entry; + +/** + * @class ACE_Filecache + * + * @brief + * A hash table holding the information about entry point into + * the Cached Virtual Filesystem. On insertion, the reference + * count is incremented. On destruction, reference count is + * decremented. + */ +class ACE_Export ACE_Filecache +{ +public: + /// Singleton pattern. + static ACE_Filecache *instance (void); + + ~ACE_Filecache (void); + + /// Returns 0 if the file associated with ``filename'' is in the cache, + /// or -1 if not. + int find (const ACE_TCHAR *filename); + + /// Return the file associated with ``filename'' if it is in the cache, + /// or create if not. + ACE_Filecache_Object *fetch (const ACE_TCHAR *filename, int mapit = 1); + + /// Remove the file associated with ``filename'' from the cache. + ACE_Filecache_Object *remove (const ACE_TCHAR *filename); + + /// Create a new Filecache_Object, returns it. + ACE_Filecache_Object *create (const ACE_TCHAR *filename, int size); + + /// Release an acquired Filecache_Object, returns it again or NULL if it + /// was deleted. + ACE_Filecache_Object *finish (ACE_Filecache_Object *&new_file); + +protected: + ACE_Filecache_Object *insert_i (const ACE_TCHAR *filename, + ACE_SYNCH_RW_MUTEX &filelock, + int mapit); + ACE_Filecache_Object *remove_i (const ACE_TCHAR *filename); + ACE_Filecache_Object *update_i (const ACE_TCHAR *filename, + ACE_SYNCH_RW_MUTEX &filelock, + int mapit); + +public: + + enum + { + /// For this stupid implementation, use an array. Someday, use a + /// balanced search tree, or real hash table. + ACE_DEFAULT_VIRTUAL_FILESYSTEM_TABLE_SIZE = 512, + + /// This determines the highwater mark in megabytes for the cache. + /// This will be ignored for now. + ACE_DEFAULT_VIRTUAL_FILESYSTEM_CACHE_SIZE = 20 + }; + +protected: + /// Prevent it from being called. + ACE_Filecache (void); + +private: + ACE_OFF_T size_; + + /// The hash table + ACE_Filecache_Hash hash_; + + /// The reference to the instance + static ACE_Filecache *cvf_; + + // = Synchronization variables. + ACE_SYNCH_RW_MUTEX hash_lock_[ACE_DEFAULT_VIRTUAL_FILESYSTEM_TABLE_SIZE]; + ACE_SYNCH_RW_MUTEX file_lock_[ACE_DEFAULT_VIRTUAL_FILESYSTEM_TABLE_SIZE]; +}; + +/** + * @class ACE_Filecache_Object + * + * @brief + * Abstraction over a real file. This is what the Virtual + * Filesystem contains. This class is not intended for general + * consumption. Please consult a physician before attempting to + * use this class. + */ +class ACE_Export ACE_Filecache_Object +{ +public: + friend class ACE_Filecache; + + /// Creates a file for reading. + ACE_Filecache_Object (const ACE_TCHAR *filename, + ACE_SYNCH_RW_MUTEX &lock, + LPSECURITY_ATTRIBUTES sa = 0, + int mapit = 1); + + /// Creates a file for writing. + ACE_Filecache_Object (const ACE_TCHAR *filename, + ACE_OFF_T size, + ACE_SYNCH_RW_MUTEX &lock, + LPSECURITY_ATTRIBUTES sa = 0); + + /// Only if reference count is zero should this be called. + ~ACE_Filecache_Object (void); + + /// Increment the reference_count_. + int acquire (void); + + /// Decrement the reference_count_. + int release (void); + + // = error_ accessors + int error (void) const; + int error (int error_value, + const ACE_TCHAR *s = ACE_TEXT ("ACE_Filecache_Object")); + + /// filename_ accessor + const ACE_TCHAR *filename (void) const; + + /// handle_ accessor. + ACE_HANDLE handle (void) const; + + /// Base memory address for memory mapped file. + void *address (void) const; + + /// size_ accessor. + ACE_OFF_T size (void) const; + + /// True if file on disk is newer than cached file. + int update (void) const; + +protected: + /// Prevent from being called. + ACE_Filecache_Object (void); + + /// Common initialization code, + void init (void); + +private: + /// Internal error logging method, no locking. + int error_i (int error_value, + const ACE_TCHAR *s = ACE_TEXT ("ACE_Filecache_Object")); + +public: + + enum Creation_States + { + ACE_READING = 1, + ACE_WRITING = 2 + }; + + enum Error_Conditions + { + ACE_SUCCESS = 0, + ACE_ACCESS_FAILED, + ACE_OPEN_FAILED, + ACE_COPY_FAILED, + ACE_STAT_FAILED, + ACE_MEMMAP_FAILED, + ACE_WRITE_FAILED + }; + +private: + /// The temporary file name and the real file name. The real file is + /// copied into the temporary file for safety reasons. + ACE_TCHAR *tempname_; + ACE_TCHAR filename_[MAXPATHLEN + 1]; + + /// Holds the memory mapped version of the temporary file. + ACE_Mem_Map mmap_; + + /// The descriptor to the temporary file. + ACE_HANDLE handle_; + + /// Used to compare against the real file to test if an update is needed. + ACE_stat stat_; + ACE_OFF_T size_; + + /// Status indicators. + int action_; + int error_; + + /// If set to 1, means the object is flagged for removal. + int stale_; + + /// Security attribute object. + LPSECURITY_ATTRIBUTES sa_; + + /// The default initializer + ACE_SYNCH_RW_MUTEX junklock_; + + /// Provides a bookkeeping mechanism for users of this object. + ACE_SYNCH_RW_MUTEX &lock_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" + +#endif /* ACE_FILECACHE_H */ diff --git a/dep/acelite/ace/Flag_Manip.cpp b/dep/acelite/ace/Flag_Manip.cpp new file mode 100644 index 00000000000..f9ac4083fa0 --- /dev/null +++ b/dep/acelite/ace/Flag_Manip.cpp @@ -0,0 +1,95 @@ +// $Id: Flag_Manip.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Flag_Manip.h" + +#if defined (ACE_LACKS_FCNTL) +# include "ace/OS_NS_stropts.h" +# include "ace/OS_NS_errno.h" +#endif /* ACE_LACKS_FCNTL */ + +#if !defined (__ACE_INLINE__) +#include "ace/Flag_Manip.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (CYGWIN32) +# include "ace/os_include/os_termios.h" +#endif /* CYGWIN32 */ + +ACE_RCSID (ace, + Flag_Manip, + "$Id: Flag_Manip.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Flags are file status flags to turn on. + +int +ACE::set_flags (ACE_HANDLE handle, int flags) +{ + ACE_TRACE ("ACE::set_flags"); +#if defined (ACE_LACKS_FCNTL) + switch (flags) + { + case ACE_NONBLOCK: + // nonblocking argument (1) + // blocking: (0) + { + int nonblock = 1; + return ACE_OS::ioctl (handle, FIONBIO, &nonblock); + } + default: + ACE_NOTSUP_RETURN (-1); + } +#else + int val = ACE_OS::fcntl (handle, F_GETFL, 0); + + if (val == -1) + return -1; + + // Turn on flags. + ACE_SET_BITS (val, flags); + + if (ACE_OS::fcntl (handle, F_SETFL, val) == -1) + return -1; + else + return 0; +#endif /* ACE_LACKS_FCNTL */ +} + +// Flags are the file status flags to turn off. + +int +ACE::clr_flags (ACE_HANDLE handle, int flags) +{ + ACE_TRACE ("ACE::clr_flags"); + +#if defined (ACE_LACKS_FCNTL) + switch (flags) + { + case ACE_NONBLOCK: + // nonblocking argument (1) + // blocking: (0) + { + int nonblock = 0; + return ACE_OS::ioctl (handle, FIONBIO, &nonblock); + } + default: + ACE_NOTSUP_RETURN (-1); + } +#else + int val = ACE_OS::fcntl (handle, F_GETFL, 0); + + if (val == -1) + return -1; + + // Turn flags off. + ACE_CLR_BITS (val, flags); + + if (ACE_OS::fcntl (handle, F_SETFL, val) == -1) + return -1; + else + return 0; +#endif /* ACE_LACKS_FCNTL */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Flag_Manip.h b/dep/acelite/ace/Flag_Manip.h new file mode 100644 index 00000000000..0457dcb4d95 --- /dev/null +++ b/dep/acelite/ace/Flag_Manip.h @@ -0,0 +1,58 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Flag_Manip.h + * + * $Id: Flag_Manip.h 80826 2008-03-04 14:51:23Z wotte $ + * + * This class includes the functions used for the Flag Manipulation. + * + * @author Priyanka Gontla + */ +//============================================================================= + +#ifndef ACE_FLAG_MANIP_H +#define ACE_FLAG_MANIP_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Global_Macros.h" +#include "ace/os_include/os_fcntl.h" /* For values passed to these methods */ + +#if defined (ACE_EXPORT_MACRO) +# undef ACE_EXPORT_MACRO +#endif +#define ACE_EXPORT_MACRO ACE_Export + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +namespace ACE +{ + // = Set/get/clear various flags related to I/O HANDLE. + /// Set flags associated with @a handle. + extern ACE_Export int set_flags (ACE_HANDLE handle, + int flags); + + /// Clear flags associated with @a handle. + extern ACE_Export int clr_flags (ACE_HANDLE handle, + int flags); + + /// Return the current setting of flags associated with @a handle. + ACE_NAMESPACE_INLINE_FUNCTION int get_flags (ACE_HANDLE handle); +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Flag_Manip.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_FLAG_MANIP_H */ diff --git a/dep/acelite/ace/Flag_Manip.inl b/dep/acelite/ace/Flag_Manip.inl new file mode 100644 index 00000000000..229a4ee596c --- /dev/null +++ b/dep/acelite/ace/Flag_Manip.inl @@ -0,0 +1,26 @@ +// -*- C++ -*- +// +// $Id: Flag_Manip.inl 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/OS_NS_fcntl.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Return flags currently associated with handle. +ACE_INLINE int +ACE::get_flags (ACE_HANDLE handle) +{ + ACE_TRACE ("ACE::get_flags"); + +#if defined (ACE_LACKS_FCNTL) + // ACE_OS::fcntl is not supported. It + // would be better to store ACE's notion of the flags + // associated with the handle, but this works for now. + ACE_UNUSED_ARG (handle); + return 0; +#else + return ACE_OS::fcntl (handle, F_GETFL, 0); +#endif /* ACE_LACKS_FCNTL */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Framework_Component.cpp b/dep/acelite/ace/Framework_Component.cpp new file mode 100644 index 00000000000..7b63ad5eeeb --- /dev/null +++ b/dep/acelite/ace/Framework_Component.cpp @@ -0,0 +1,279 @@ +// Framework_Component.cpp +// $Id: Framework_Component.cpp 84128 2009-01-09 15:07:40Z johnnyw $ + +#include "ace/Framework_Component.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Framework_Component.inl" +#endif /* __ACE_INLINE__ */ + +#include "ace/Object_Manager.h" +#include "ace/Log_Msg.h" +#include "ace/DLL_Manager.h" +#include "ace/Recursive_Thread_Mutex.h" +#include "ace/OS_NS_string.h" + +ACE_RCSID(ace, Framework_Component, "$Id: Framework_Component.cpp 84128 2009-01-09 15:07:40Z johnnyw $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_Framework_Component::~ACE_Framework_Component (void) +{ + ACE_TRACE ("ACE_Framework_Component::~ACE_Framework_Component"); + + ACE::strdelete (const_cast (this->dll_name_)); + ACE::strdelete (const_cast (this->name_)); +} + +/***************************************************************/ + +ACE_ALLOC_HOOK_DEFINE(ACE_Framework_Repository) + +sig_atomic_t ACE_Framework_Repository::shutting_down_ = 0; + +// Pointer to the Singleton instance. +ACE_Framework_Repository *ACE_Framework_Repository::repository_ = 0; + +ACE_Framework_Repository::~ACE_Framework_Repository (void) +{ + ACE_TRACE ("ACE_Framework_Repository::~ACE_Framework_Repository"); + this->close (); +} + +int +ACE_Framework_Repository::open (int size) +{ + ACE_TRACE ("ACE_Framework_Repository::open"); + + ACE_Framework_Component **temp = 0; + + ACE_NEW_RETURN (temp, + ACE_Framework_Component *[size], + -1); + + this->component_vector_ = temp; + this->total_size_ = size; + return 0; +} + +int +ACE_Framework_Repository::close (void) +{ + ACE_TRACE ("ACE_Framework_Repository::close"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + + this->shutting_down_ = 1; + + if (this->component_vector_ != 0) + { + // Delete components in reverse order. + for (int i = this->current_size_ - 1; i >= 0; i--) + if (this->component_vector_[i]) + { + ACE_Framework_Component *s = + const_cast ( + this->component_vector_[i]); + + this->component_vector_[i] = 0; + delete s; + } + + delete [] this->component_vector_; + this->component_vector_ = 0; + this->current_size_ = 0; + } + + ACE_DLL_Manager::close_singleton (); + return 0; +} + +ACE_Framework_Repository * +ACE_Framework_Repository::instance (int size) +{ + ACE_TRACE ("ACE_Framework_Repository::instance"); + + if (ACE_Framework_Repository::repository_ == 0) + { + // Perform Double-Checked Locking Optimization. + ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, + *ACE_Static_Object_Lock::instance (), 0)); + if (ACE_Framework_Repository::repository_ == 0) + { + if (ACE_Object_Manager::starting_up () || + !ACE_Object_Manager::shutting_down ()) + { + ACE_NEW_RETURN (ACE_Framework_Repository::repository_, + ACE_Framework_Repository (size), + 0); + } + } + } + + return ACE_Framework_Repository::repository_; +} + +void +ACE_Framework_Repository::close_singleton (void) +{ + ACE_TRACE ("ACE_Framework_Repository::close_singleton"); + + ACE_MT (ACE_GUARD (ACE_Recursive_Thread_Mutex, ace_mon, + *ACE_Static_Object_Lock::instance ())); + + delete ACE_Framework_Repository::repository_; + ACE_Framework_Repository::repository_ = 0; +} + +int +ACE_Framework_Repository::register_component (ACE_Framework_Component *fc) +{ + ACE_TRACE ("ACE_Framework_Repository::register_component"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + int i; + + // Check to see if it's already registered + for (i = 0; i < this->current_size_; i++) + if (this->component_vector_[i] && + fc->this_ == this->component_vector_[i]->this_) + { + ACE_ERROR_RETURN ((LM_ERROR, + "AFR::register_component: error, compenent already registered\n"), + -1); + } + + if (i < this->total_size_) + { + this->component_vector_[i] = fc; + ++this->current_size_; + return 0; + } + + return -1; +} + +int +ACE_Framework_Repository::remove_component (const ACE_TCHAR *name) +{ + ACE_TRACE ("ACE_Framework_Repository::remove_component"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + int i; + + for (i = 0; i < this->current_size_; i++) + if (this->component_vector_[i] && + ACE_OS::strcmp (this->component_vector_[i]->name_, name) == 0) + { + delete this->component_vector_[i]; + this->component_vector_[i] = 0; + this->compact (); + return 0; + } + + return -1; +} + +int +ACE_Framework_Repository::remove_dll_components (const ACE_TCHAR *dll_name) +{ + ACE_TRACE ("ACE_Framework_Repository::remove_dll_components"); + + if (this->shutting_down_) + return this->remove_dll_components_i (dll_name); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + + return this->remove_dll_components_i (dll_name); +} + +int +ACE_Framework_Repository::remove_dll_components_i (const ACE_TCHAR *dll_name) +{ + ACE_TRACE ("ACE_Framework_Repository::remove_dll_components_i"); + + int i; + int retval = -1; + + for (i = 0; i < this->current_size_; i++) + if (this->component_vector_[i] && + ACE_OS::strcmp (this->component_vector_[i]->dll_name_, dll_name) == 0) + { + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("AFR::remove_dll_components_i (%s) ") + ACE_TEXT ("component \"%s\"\n"), + dll_name, this->component_vector_[i]->name_)); + delete this->component_vector_[i]; + this->component_vector_[i] = 0; + ++retval; + } + + this->compact (); + + return retval == -1 ? -1 : 0; +} + +void +ACE_Framework_Repository::compact (void) +{ + ACE_TRACE ("ACE_Framework_Repository::compact"); + + int i; + int start_hole; + int end_hole; + + do + { + start_hole = this->current_size_; + end_hole = this->current_size_; + + // Find hole + for (i = 0; i < this->current_size_; ++i) + { + if (this->component_vector_[i] == 0) + { + if (start_hole == this->current_size_) + { + start_hole = i; + end_hole = i; + } + else + end_hole = i; + } + else if (end_hole != this->current_size_) + break; + } + + if (start_hole != this->current_size_) + { + // move the contents and reset current_size_ + while (end_hole + 1 < this->current_size_) + { + this->component_vector_[start_hole++] = + this->component_vector_[++end_hole]; + } + // Since start_hole is now one past the last + // active slot. + this->current_size_ = start_hole; + } + + } while (start_hole != this->current_size_); +} + +void +ACE_Framework_Repository::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Framework_Repository::dump"); +#endif /* ACE_HAS_DUMP */ +} + +ACE_Framework_Repository::ACE_Framework_Repository (int size) + : current_size_ (0) +{ + ACE_TRACE ("ACE_Framework_Repository::ACE_Framework_Repository"); + + if (this->open (size) == -1) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_Framework_Repository"))); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Framework_Component.h b/dep/acelite/ace/Framework_Component.h new file mode 100644 index 00000000000..941960bf047 --- /dev/null +++ b/dep/acelite/ace/Framework_Component.h @@ -0,0 +1,210 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Framework_Component.h + * + * $Id: Framework_Component.h 80826 2008-03-04 14:51:23Z wotte $ + * + * A prototype mechanism that allows framework components, singletons + * such as ACE_Reactor, ACE_Proactor, etc, to be registered with a + * central repository managed by the ACE_Object_Manager or + * ACE_Service_Config that will handle destruction. + * + * This technique obviates changing ACE_Object_Manager and + * ACE_Service_Config everytime a new framework is added. Which also + * means that unused framework components don't need to linked into + * the final application which is important for applications with + * stringent footprint requirements. + * + * Framework components need only provide a static method, + * close_singleton() and add the ACE_REGISTER_FRAMEWORK_COMPONENT macro + * call to their instance() methods in order to participate. Components + * that don't have a close_singleton() method can also participate via + * template specialization of ACE_Framework_Component_T. + * + * This design uses the External Polymorphism pattern to avoid having + * to derive all framework components from a common base class that + * has virtual methods (this is crucial to avoid unnecessary overhead), + * and is based on the dump debugging implementation found in + * . + * + * @author Don Hinton . + */ +//============================================================================= + +#ifndef ACE_FRAMEWORK_COMPONENT_H +#define ACE_FRAMEWORK_COMPONENT_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/os_signal.h" +#include "ace/Thread_Mutex.h" + +#define ACE_DEFAULT_FRAMEWORK_REPOSITORY_SIZE 1024 + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Framework_Component + * + * @brief Base class that defines a uniform interface for all managed + * framework components. + */ +class ACE_Export ACE_Framework_Component +{ +public: + friend class ACE_Framework_Repository; + + /// Constructor. + ACE_Framework_Component (void *_this, + const ACE_TCHAR *dll_name = 0, + const ACE_TCHAR *name = 0); + + /// Close the contained singleton. + virtual void close_singleton (void) = 0; + +protected: + /// Destructor. + virtual ~ACE_Framework_Component (void); + +private: + // No copy possible + ACE_Framework_Component (const ACE_Framework_Component &); + void operator= (const ACE_Framework_Component &); + +private: + /// Pointer to the actual component. + const void *this_; + + /// Library associated with this component + const ACE_TCHAR *dll_name_; + + /// Component name + const ACE_TCHAR *name_; +}; + +/** + * @class ACE_Framework_Repository + * + * @brief Contains all framework components used by an application. + * + * This class contains a vector of ACE_Framework_Component *'s. On + * destruction, framework components are destroyed in the reverse order + * that they were added originally. + */ +class ACE_Export ACE_Framework_Repository +{ +public: + // This is just to silence a compiler warning about no public ctors + friend class ACE_Framework_Component; + + enum + { + DEFAULT_SIZE = ACE_DEFAULT_FRAMEWORK_REPOSITORY_SIZE + }; + + /// Close down the repository and free up dynamically allocated + /// resources. + ~ACE_Framework_Repository (void); + + /// Initialize the repository. + int open (int size = DEFAULT_SIZE); + + /// Close down the repository and free up dynamically allocated + /// resources, also called by dtor. + int close (void); + + /// Get pointer to a process-wide ACE_Framework_Repository. + static ACE_Framework_Repository *instance + (int size = ACE_Framework_Repository::DEFAULT_SIZE); + + /// Delete the dynamically allocated Singleton. + static void close_singleton (void); + + // = Search structure operations (all acquire locks as necessary). + + /// Insert a new component. Returns -1 when the repository is full + /// and 0 on success. + int register_component (ACE_Framework_Component *fc); + + /// Remove a component. Returns -1 on error or if component not found + /// and 0 on success. + int remove_component (const ACE_TCHAR *name); + + /// Remove all components associated with a particular dll. + int remove_dll_components (const ACE_TCHAR *dll_name); + + /// Return the current size of the repository. + int current_size (void) const; + + /// Return the total size of the repository. + int total_size (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + + /// Initialize the repository. + ACE_Framework_Repository (int size = ACE_Framework_Repository::DEFAULT_SIZE); + +private: + + /// Actually removes the dll components, must be called with locks held. + int remove_dll_components_i (const ACE_TCHAR *dll_name); + + /// Compact component_vector_ after components have been removed__maintains + /// order. + void compact (void); + + /// Disallow copying and assignment. + ACE_Framework_Repository (const ACE_Framework_Repository &); + ACE_Framework_Repository &operator= (const ACE_Framework_Repository &); + +private: + + /// Contains all the framework components. + ACE_Framework_Component **component_vector_; + + /// Current number of components. + int current_size_; + + /// Maximum number of components. + int total_size_; + + /// Pointer to a process-wide ACE_Framework_Repository. + static ACE_Framework_Repository *repository_; + + /// Flag set when repository is the process of shutting down. This + /// is necessary to keep from self-deadlocking since some of + /// the components might make calls back to the repository to + /// unload their components, e.g., ACE_DLL_Manager. + static sig_atomic_t shutting_down_; + +#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) + /// Synchronization variable for the MT_SAFE Repository + ACE_Thread_Mutex lock_; +#endif /* ACE_MT_SAFE */ + +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Framework_Component.inl" +#endif /* __ACE_INLINE__ */ + +// Include the templates classes at this point. +#include "ace/Framework_Component_T.h" + +#include /**/ "ace/post.h" +#endif /* ACE_FRAMEWORK_COMPONENT_H */ diff --git a/dep/acelite/ace/Framework_Component.inl b/dep/acelite/ace/Framework_Component.inl new file mode 100644 index 00000000000..1fb2de38b85 --- /dev/null +++ b/dep/acelite/ace/Framework_Component.inl @@ -0,0 +1,39 @@ +// -*- C++ -*- +// +// $Id: Framework_Component.inl 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/ACE.h" +#include "ace/Guard_T.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE +ACE_Framework_Component::ACE_Framework_Component (void *_this, + const ACE_TCHAR *dll_name, + const ACE_TCHAR *name) + : this_ (_this), + dll_name_ (ACE::strnew (dll_name ? dll_name : ACE_TEXT (""))), + name_ (ACE::strnew (name ? name : ACE_TEXT (""))) +{ + ACE_TRACE ("ACE_Framework_Component::ctor"); +} + +/***************************************************************/ + +ACE_INLINE int +ACE_Framework_Repository::current_size (void) const +{ + ACE_TRACE ("ACE_Framework_Repository::current_size"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, (ACE_Thread_Mutex &) this->lock_, -1)); + return this->current_size_; +} + +ACE_INLINE int +ACE_Framework_Repository::total_size (void) const +{ + ACE_TRACE ("ACE_Framework_Repository::total_size"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, (ACE_Thread_Mutex &) this->lock_, -1)); + return this->total_size_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Framework_Component_T.cpp b/dep/acelite/ace/Framework_Component_T.cpp new file mode 100644 index 00000000000..6f0be7b5e2a --- /dev/null +++ b/dep/acelite/ace/Framework_Component_T.cpp @@ -0,0 +1,33 @@ +// $Id: Framework_Component_T.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#ifndef ACE_FRAMEWORK_COMPONENT_T_CPP +#define ACE_FRAMEWORK_COMPONENT_T_CPP + +#include "ace/Framework_Component_T.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template +ACE_Framework_Component_T::ACE_Framework_Component_T (Concrete *concrete) + : ACE_Framework_Component ((void *) concrete, concrete->dll_name (), concrete->name ()) +{ + ACE_TRACE ("ACE_Framework_Component_T::ctor"); +} + +template +ACE_Framework_Component_T::~ACE_Framework_Component_T (void) +{ + ACE_TRACE ("ACE_Framework_Component_T::~ACE_Framework_Component_T"); + Concrete::close_singleton (); +} + +template void +ACE_Framework_Component_T::close_singleton (void) +{ + ACE_TRACE ("ACE_Framework_Component_T::close_singleton"); + Concrete::close_singleton (); +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_FRAMEWORK_COMPONENT_T_CPP */ diff --git a/dep/acelite/ace/Framework_Component_T.h b/dep/acelite/ace/Framework_Component_T.h new file mode 100644 index 00000000000..2dcef43e384 --- /dev/null +++ b/dep/acelite/ace/Framework_Component_T.h @@ -0,0 +1,71 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Framework_Component_T.h + * + * $Id: Framework_Component_T.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + */ +//============================================================================= + +#ifndef ACE_FRAMEWORK_COMPONENT_T_H +#define ACE_FRAMEWORK_COMPONENT_T_H +#include /**/ "ace/pre.h" +#include "ace/Framework_Component.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Framework_Component_T + * + * @brief This class inherits the interface of the abstract + * ACE_Framework_Component class and is instantiated with the + * implementation of the concrete component class @c class Concrete. + * + * This design is similar to the Adapter and Decorator patterns + * from the ``Gang of Four'' book. Note that @c class Concrete + * need not inherit from a common class since ACE_Framework_Component + * provides the uniform virtual interface! (implementation based on + * ACE_Dumpable_Adapter in . + */ +template +class ACE_Framework_Component_T : public ACE_Framework_Component +{ +public: + // = Initialization and termination methods. + + /// Constructor. + ACE_Framework_Component_T (Concrete *concrete); + + /// Destructor. + ~ACE_Framework_Component_T (void); + + /// Close the contained singleton. + void close_singleton (void); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +// This macro should be called in the instance() method +// of the Concrete class that will be managed. Along +// with the appropriate template instantiation. +#define ACE_REGISTER_FRAMEWORK_COMPONENT(CLASS, INSTANCE) \ + ACE_Framework_Repository::instance ()->register_component \ + (new ACE_Framework_Component_T (INSTANCE)); + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Framework_Component_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Framework_Component_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" +#endif /* ACE_FRAMEWORK_COMPONENT_T_H */ diff --git a/dep/acelite/ace/Free_List.cpp b/dep/acelite/ace/Free_List.cpp new file mode 100644 index 00000000000..4da723f4898 --- /dev/null +++ b/dep/acelite/ace/Free_List.cpp @@ -0,0 +1,163 @@ +// $Id: Free_List.cpp 81107 2008-03-27 11:12:42Z johnnyw $ + +#ifndef ACE_FREE_LIST_CPP +#define ACE_FREE_LIST_CPP + +#include "ace/Free_List.h" +#include "ace/Guard_T.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template +ACE_Free_List::~ACE_Free_List (void) +{ +} + +// Default constructor that takes in a preallocation number +// (), a low and high water mark ( and ) and an +// increment value () + +template +ACE_Locked_Free_List::ACE_Locked_Free_List (int mode, + size_t prealloc, + size_t lwm, + size_t hwm, + size_t inc) + : mode_ (mode), + free_list_ (0), + lwm_ (lwm), + hwm_ (hwm), + inc_ (inc), + size_ (0) +{ + this->alloc (prealloc); +} + +// Destructor - removes all the elements from the free_list + +template +ACE_Locked_Free_List::~ACE_Locked_Free_List (void) +{ + if (this->mode_ != ACE_PURE_FREE_LIST) + while (this->free_list_ != 0) + { + T *temp = this->free_list_; + this->free_list_ = this->free_list_->get_next (); + delete temp; + } +} + +// Inserts an element onto the free list (if we are allowed to manage +// elements withing and it pasts the high water mark, delete the +// element) + +template void +ACE_Locked_Free_List::add (T *element) +{ + ACE_MT (ACE_GUARD (ACE_LOCK, ace_mon, this->mutex_)); + + // Check to see that we not at the high water mark. + if (this->mode_ == ACE_PURE_FREE_LIST + || this->size_ < this->hwm_) + { + element->set_next (this->free_list_); + this->free_list_ = element; + this->size_++; + } + else + delete element; +} + +// Takes a element off the freelist and returns it. It creates +// new elements if we are allowed to do it and the size is at the low +// water mark. + +template T * +ACE_Locked_Free_List::remove (void) +{ + ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, 0)); + + // If we are at the low water mark, add some nodes + if (this->mode_ != ACE_PURE_FREE_LIST && this->size_ <= this->lwm_) + this->alloc (this->inc_); + + // Remove a node + T *temp = this->free_list_; + + if (temp != 0) + { + this->free_list_ = this->free_list_->get_next (); + this->size_--; + } + + return temp; +} + + +// Returns the current size of the free list + +template size_t +ACE_Locked_Free_List::size (void) +{ + return this->size_; +} + +// Resizes the free list to + +template void +ACE_Locked_Free_List::resize (size_t newsize) +{ + ACE_MT (ACE_GUARD (ACE_LOCK, ace_mon, this->mutex_)); + + // Check if we are allowed to resize + if (this->mode_ != ACE_PURE_FREE_LIST) + { + // Check to see if we grow or shrink + if (newsize < this->size_) + { + this->dealloc (this->size_ - newsize); + } + else + { + this->alloc (newsize - this->size_); + } + } +} + +// Allocates extra nodes for the freelist + +template void +ACE_Locked_Free_List::alloc (size_t n) +{ + for (; n > 0; n--) + { + T *temp = 0; + ACE_NEW (temp, T); + temp->set_next (this->free_list_); + this->free_list_ = temp; + this->size_++; + } +} + +// Removes and frees nodes from the freelist. + +template void +ACE_Locked_Free_List::dealloc (size_t n) +{ + for (; this->free_list_ != 0 && n > 0; + n--) + { + T *temp = this->free_list_; + this->free_list_ = this->free_list_->get_next (); + delete temp; + this->size_--; + } +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_FREE_LIST_CPP */ diff --git a/dep/acelite/ace/Free_List.h b/dep/acelite/ace/Free_List.h new file mode 100644 index 00000000000..7f2ce593c7a --- /dev/null +++ b/dep/acelite/ace/Free_List.h @@ -0,0 +1,150 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file Free_List.h + * + * $Id: Free_List.h 84619 2009-02-26 12:26:16Z johnnyw $ + * + * @author Darrell Brunsch (brunsch@cs.wustl.edu) + */ +//============================================================================= + +#ifndef ACE_FREE_LIST_H +#define ACE_FREE_LIST_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Global_Macros.h" +#include "ace/Default_Constants.h" +#include "ace/os_include/os_stddef.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Free_List + * + * @brief Implements a free list. + * + * This class maintains a free list of nodes of type T. + */ +template +class ACE_Free_List +{ +public: + /// Destructor - removes all the elements from the free_list. + virtual ~ACE_Free_List (void); + + /// Inserts an element onto the free list (if it isn't past the high + /// water mark). + virtual void add (T *element) = 0; + + /// Takes a element off the freelist and returns it. It creates + /// new elements if the size is at or below the low water mark. + virtual T *remove (void) = 0; + + /// Returns the current size of the free list. + virtual size_t size (void) = 0; + + /// Resizes the free list to @a newsize. + virtual void resize (size_t newsize) = 0; +}; + +/** + * @class ACE_Locked_Free_List + * + * @brief Implements a free list. + * + * This class maintains a free list of nodes of type T. It + * depends on the type T having a and + * method. It maintains a mutex so the freelist can be used in + * a multithreaded program . + */ +template +class ACE_Locked_Free_List : public ACE_Free_List +{ +public: + // = Initialization and termination. + /** + * Constructor takes a @a mode (i.e., ACE_FREE_LIST_WITH_POOL or + * ACE_PURE_FREE_LIST), a count of the number of nodes to + * @a prealloc, a low and high water mark (@a lwm and @a hwm) that + * indicate when to allocate more nodes, an increment value (@a inc) + * that indicates how many nodes to allocate when the list must + * grow. + */ + ACE_Locked_Free_List (int mode = ACE_FREE_LIST_WITH_POOL, + size_t prealloc = ACE_DEFAULT_FREE_LIST_PREALLOC, + size_t lwm = ACE_DEFAULT_FREE_LIST_LWM, + size_t hwm = ACE_DEFAULT_FREE_LIST_HWM, + size_t inc = ACE_DEFAULT_FREE_LIST_INC); + + /// Destructor - removes all the elements from the free_list. + virtual ~ACE_Locked_Free_List (void); + + /// Inserts an element onto the free list (if it isn't past the high + /// water mark). + virtual void add (T *element); + + /// Takes a element off the freelist and returns it. It creates + /// new elements if the size is at or below the low water mark. + virtual T *remove (void); + + /// Returns the current size of the free list. + virtual size_t size (void); + + /// Resizes the free list to @a newsize. + virtual void resize (size_t newsize); + +protected: + /// Allocates @a n extra nodes for the freelist. + virtual void alloc (size_t n); + + /// Removes and frees @a n nodes from the freelist. + virtual void dealloc (size_t n); + + /// Free list operation mode, either ACE_FREE_LIST_WITH_POOL or + /// ACE_PURE_FREE_LIST. + int mode_; + + /// Pointer to the first node in the freelist. + T *free_list_; + + /// Low water mark. + size_t lwm_; + + /// High water mark. + size_t hwm_; + + /// Increment value. + size_t inc_; + + /// Keeps track of the size of the list. + size_t size_; + + /// Synchronization variable for ACE_Timer_Queue. + ACE_LOCK mutex_; + +private: + // = Don't allow these operations for now. + ACE_UNIMPLEMENTED_FUNC (ACE_Locked_Free_List (const ACE_Locked_Free_List &)) + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Locked_Free_List &)) +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Free_List.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Free_List.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" +#endif /* ACE_FREE_LIST_H */ diff --git a/dep/acelite/ace/Functor.cpp b/dep/acelite/ace/Functor.cpp new file mode 100644 index 00000000000..429aaac9f22 --- /dev/null +++ b/dep/acelite/ace/Functor.cpp @@ -0,0 +1,43 @@ + +//============================================================================= +/** + * @file Functor.cpp + * + * $Id: Functor.cpp 80826 2008-03-04 14:51:23Z wotte $ + * + * Non-inlinable method definitions for non-templatized classes + * and template specializations implementing the GOF Command Pattern, + * and STL-style functors. + * + * + * @author Chris Gill + * + * Based on Command Pattern implementations originally done by + * + * Carlos O'Ryan + * Douglas C. Schmidt + * Sergio Flores-Gaitan + * + * and on STL-style functor implementations originally done by + * + * Irfan Pyarali + */ +//============================================================================= + + +#include "ace/Functor_T.h" +#include "ace/Functor.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Functor.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID(ace, Functor, "$Id: Functor.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_Command_Base::~ACE_Command_Base (void) +{ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Functor.h b/dep/acelite/ace/Functor.h new file mode 100644 index 00000000000..ec1d285061f --- /dev/null +++ b/dep/acelite/ace/Functor.h @@ -0,0 +1,523 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file Functor.h + * + * $Id: Functor.h 86698 2009-09-13 15:58:17Z johnnyw $ + * + * Non-templatized classes and class template specializations for + * implementing function objects that are used in various places + * in ACE. There are currently two major categories of function + * objects in ACE: GoF Command Pattern objects, and STL-style + * functors for comparison of container elements. The command objects + * are invoked via an execute () method, while the STL-style functors are + * invoked via an operator() () method. + * Non-templatized classes for implementing the GoF Command Pattern, + * also known as functors or function objects. + * + * + * @author Chris Gill + * @author Based on Command Pattern implementations originally done by + * @author Carlos O'Ryan + * @author Douglas C. Schmidt + * @author Sergio Flores-Gaitan + * @author and on STL-style functor implementations originally done by + * @author Irfan Pyarali + */ +//========================================================================== + + +#ifndef ACE_FUNCTOR_H +#define ACE_FUNCTOR_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include /**/ "ace/ACE_export.h" +#include "ace/Basic_Types.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +////////////////////////////////////////////////////////////// +// GOF Command Pattern Classes and Template Specializations // +////////////////////////////////////////////////////////////// + +/** + * @class ACE_Command_Base + * + * @brief Defines an abstract class that allows us to invoke commands + * without knowing anything about the implementation. + * + * This class declares an interface to execute a command + * independent of the effect of the command, or the objects used + * to implement it. + */ +class ACE_Export ACE_Command_Base +{ +public: + // = Initialization and termination methods. + /// Default constructor. + ACE_Command_Base (void); + + /// Virtual destructor. + virtual ~ACE_Command_Base (void); + + /** + * Invokes the method encapsulated by the command, passing along the + * passed argument (if any). Users of classes derived from this + * class must ensure that the resulting invocation can tolerate a + * null void pointer being passed, or otherwise ensure that this + * will never occur. + */ + virtual int execute (void *arg = 0) = 0; +}; + +//////////////////////////////////////////////////////////// +// STL-style Functor Classes and Template Specializations // +//////////////////////////////////////////////////////////// + +// Forward declaration since we are going to specialize that template +// here. The template itself requires this file so every user of the +// template should also see the specialization. +template class ACE_Hash; +template class ACE_Equal_To; +template class ACE_Less_Than; + +/** + * @brief Function object for hashing a char + */ +template<> +class ACE_Export ACE_Hash +{ +public: + /// Simply returns t + unsigned long operator () (char t) const; +}; + +/** + * @brief Function object for hashing a signed char + */ +template<> +class ACE_Export ACE_Hash +{ +public: + /// Simply returns t + unsigned long operator () (signed char t) const; +}; + +/** + * @brief Function object for hashing an unsigned char + */ +template<> +class ACE_Export ACE_Hash +{ +public: + /// Simply returns t + unsigned long operator () (unsigned char t) const; +}; + +#if 0 +// @@ ADD HASHES FOR ACE TYPES + +/** + * @brief Function object for hashing a 16-bit signed number + */ +template<> +class ACE_Export ACE_Hash +{ +public: + /// Simply returns t + unsigned long operator () (ACE_INT16 t) const; +}; + +/** + * @brief Function object for hashing a 16-bit unsigned number + */ +template<> +class ACE_Export ACE_Hash +{ +public: + /// Simply returns t + unsigned long operator () (ACE_UINT16 t) const; +}; + +/** + * @brief Function object for hashing a 32-bit signed number + */ +template<> +class ACE_Export ACE_Hash +{ +public: + /// Simply returns t + unsigned long operator () (ACE_INT32 t) const; +}; + +/** + * @brief Function object for hashing a 32-bit unsigned number + */ +template<> +class ACE_Export ACE_Hash +{ +public: + /// Simply returns t + unsigned long operator () (ACE_UINT32 t) const; +}; + +/** + * @brief Function object for hashing a 64-bit unsigned number + */ +template<> +class ACE_Export ACE_Hash +{ +public: + /// Simply returns t + unsigned long operator () (ACE_UINT64 t) const; +}; + +// @@ DONE ADDING HASHES FOR ACE TYPES +#endif + +/** + * @brief Function object for hashing a short number + */ +template<> +class ACE_Export ACE_Hash +{ +public: + /// Simply returns t + unsigned long operator () (short t) const; +}; + +/** + * @brief Function object for hashing an unsigned short number + */ +template<> +class ACE_Export ACE_Hash +{ +public: + /// Simply returns t + unsigned long operator () (unsigned short t) const; +}; + +/** + * @brief Function object for hashing an int number + */ +template<> +class ACE_Export ACE_Hash +{ +public: + /// Simply returns t + unsigned long operator () (int t) const; +}; + +/** + * @brief Function object for hashing an unsigned int number + */ +template<> +class ACE_Export ACE_Hash +{ +public: + /// Simply returns t + unsigned long operator () (unsigned int t) const; +}; + +/** + * @brief Function object for hashing a long number + */ +template<> +class ACE_Export ACE_Hash +{ +public: + /// Simply returns t + unsigned long operator () (long t) const; +}; + +/** + * @brief Function object for hashing an unsigned long number + */ +template<> +class ACE_Export ACE_Hash +{ +public: + /// Simply returns t + unsigned long operator () (unsigned long t) const; +}; + +#if !defined (ACE_LACKS_LONGLONG_T) && (ACE_SIZEOF_LONG < 8) +/** + * @brief Function object for hashing a signed 64-bit number + */ +template<> +class ACE_Export ACE_Hash +{ +public: + /// Simply returns t + unsigned long operator () (ACE_INT64 t) const; +}; +#endif /* !ACE_LACKS_LONGLONG_T && ACE_SIZEOF_LONG < 8 */ + +// We can do this even if ACE_LACKS_UNSIGNEDLONGLONG_T because there's an +// emulation for it in ACE_U_LongLong. +#if (ACE_SIZEOF_LONG < 8) +/** + * @brief Function object for hashing an unsigned 64-bit number + */ +template<> +class ACE_Export ACE_Hash +{ +public: + /// Simply returns t + unsigned long operator () (const ACE_UINT64 &t) const; +}; +#endif /* ACE_SIZEOF_LONG < 8 */ + +/** + * @brief Function object for hashing a const string + */ +template<> +class ACE_Export ACE_Hash +{ +public: + /// Calls ACE::hash_pjw + unsigned long operator () (const char *t) const; +}; + +/** + * @brief Function object for hashing a string + */ +template<> +class ACE_Export ACE_Hash +{ +public: + /// Calls ACE::hash_pjw + unsigned long operator () (const char *t) const; +}; + +/** + * @brief Function object for hashing a void * + */ +template<> +class ACE_Export ACE_Hash +{ +public: + unsigned long operator () (const void *) const; +}; + +/** + * @brief Function object for determining whether two const strings are equal. + */ +template<> +class ACE_Export ACE_Equal_To +{ +public: + /// Simply calls ACE_OS::strcmp + int operator () (const char *lhs, + const char *rhs) const; +}; + +/** + * @brief Function object for determining whether two non-const + * strings are equal. + */ +template<> +class ACE_Export ACE_Equal_To +{ +public: + /// Simply calls ACE_OS::strcmp + int operator () (const char *lhs, + const char *rhs) const; +}; + +/** + * @brief Function object for determining whether two unsigned + * 16 bit ints are equal. + */ +template<> +class ACE_Export ACE_Equal_To +{ +public: + /// Simply calls built-in operators + int operator () (const ACE_UINT16 lhs, + const ACE_UINT16 rhs) const; +}; + +/** + * @brief Function object for determining whether two + * 16 bit ints are equal. + */ +template<> +class ACE_Export ACE_Equal_To +{ +public: + /// Simply calls built-in operators + int operator () (const ACE_INT16 lhs, + const ACE_INT16 rhs) const; +}; + +/** + * @brief Function object for determining whether two unsigned + * 32 bit ints are equal. + */ +template<> +class ACE_Export ACE_Equal_To +{ +public: + /// Simply calls built-in operators + int operator () (const ACE_UINT32 lhs, + const ACE_UINT32 rhs) const; +}; + +/** + * @brief Function object for determining whether two + * 32 bit ints are equal. + */ +template<> +class ACE_Export ACE_Equal_To +{ +public: + /// Simply calls built-in operators + int operator () (const ACE_INT32 lhs, + const ACE_INT32 rhs) const; +}; + +/** + * @brief Function object for determining whether two unsigned + * 64 bit ints are equal. + */ +template<> +class ACE_Export ACE_Equal_To +{ +public: + /// Simply calls built-in operators + int operator () (const ACE_UINT64 lhs, + const ACE_UINT64 rhs) const; +}; + +/** + * @brief Function object for determining whether the first const string + * is less than the second const string. + */ +template<> +class ACE_Export ACE_Less_Than +{ +public: + /// Simply calls ACE_OS::strcmp + int operator () (const char *lhs, + const char *rhs) const; +}; + +/** + * @brief Function object for determining whether the first string + * is less than the second string. + */ +template<> +class ACE_Export ACE_Less_Than +{ +public: + /// Simply calls ACE_OS::strcmp + int operator () (const char *lhs, + const char *rhs) const; +}; + +#if defined (ACE_HAS_WCHAR) + +# if ! defined (ACE_LACKS_NATIVE_WCHAR_T) +/** + * @brief Function object for hashing a wchar_t + */ +template<> +class ACE_Export ACE_Hash +{ +public: + /// Simply returns t + unsigned long operator () (wchar_t t) const; +}; +# endif /* ACE_LACKS_NATIVE_WCHAR_T */ +/** + * @brief Function object for hashing a const string + */ +template<> +class ACE_Export ACE_Hash +{ +public: + /// Calls ACE::hash_pjw + unsigned long operator () (const wchar_t *t) const; +}; + +/** + * @brief Function object for hashing a string + */ +template<> +class ACE_Export ACE_Hash +{ +public: + /// Calls ACE::hash_pjw + unsigned long operator () (const wchar_t *t) const; +}; + +/** + * @brief Function object for determining whether two const strings are equal. + */ +template<> +class ACE_Export ACE_Equal_To +{ +public: + /// Simply calls ACE_OS::strcmp + int operator () (const wchar_t *lhs, + const wchar_t *rhs) const; +}; + +/** + * @brief Function object for determining whether two non-const + * strings are equal. + */ +template<> +class ACE_Export ACE_Equal_To +{ +public: + /// Simply calls ACE_OS::strcmp + int operator () (const wchar_t *lhs, + const wchar_t *rhs) const; +}; + +/** + * @brief Function object for determining whether the first const string + * is less than the second const string. + */ +template<> +class ACE_Export ACE_Less_Than +{ +public: + /// Simply calls ACE_OS::strcmp + int operator () (const wchar_t *lhs, + const wchar_t *rhs) const; +}; + +/** + * @brief Function object for determining whether the first string + * is less than the second string. + */ +template<> +class ACE_Export ACE_Less_Than +{ +public: + /// Simply calls ACE_OS::strcmp + int operator () (const wchar_t *lhs, + const wchar_t *rhs) const; +}; + +#endif // ACE_HAS_WCHAR + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Functor.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_FUNCTOR_H */ diff --git a/dep/acelite/ace/Functor.inl b/dep/acelite/ace/Functor.inl new file mode 100644 index 00000000000..30e539459a8 --- /dev/null +++ b/dep/acelite/ace/Functor.inl @@ -0,0 +1,284 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Functor.inl + * + * $Id: Functor.inl 80826 2008-03-04 14:51:23Z wotte $ + * + * Inlinable method definitions for non-templatized classes + * and template specializations implementing the GOF Command Pattern, + * and STL-style functors. + * + * + * @author Chris Gill + * + * Based on Command Pattern implementations originally done by + * + * Carlos O'Ryan + * Douglas C. Schmidt + * Sergio Flores-Gaitan + * + * and on STL-style functor implementations originally done by + * Irfan Pyarali + */ +//============================================================================= + + +#include "ace/ACE.h" +#include "ace/OS_NS_string.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +////////////////////////////////////////////////////////////// +// GOF Command Pattern Classes and Template Specializations // +////////////////////////////////////////////////////////////// + +// Default constructor. + +ACE_INLINE +ACE_Command_Base::ACE_Command_Base (void) +{ +} + +//////////////////////////////////////////////////////////// +// STL-style Functor Classes and Template Specializations // +//////////////////////////////////////////////////////////// + +ACE_INLINE unsigned long +ACE_Hash::operator () (char t) const +{ + return t; +} + +#if defined (ACE_HAS_WCHAR) && ! defined (ACE_LACKS_NATIVE_WCHAR_T) +ACE_INLINE unsigned long +ACE_Hash::operator () (wchar_t t) const +{ + return t; +} +#endif /* ACE_HAS_WCHAR && ! ACE_LACKS_NATIVE_WCHAR_T */ + +ACE_INLINE unsigned long +ACE_Hash::operator () (signed char t) const +{ + return t; +} + +ACE_INLINE unsigned long +ACE_Hash::operator () (unsigned char t) const +{ + return t; +} + +#if 0 +ACE_INLINE unsigned long +ACE_Hash::operator () (ACE_INT16 t) const +{ + return t; +} + +ACE_INLINE unsigned long +ACE_Hash::operator () (ACE_UINT16 t) const +{ + return t; +} + +ACE_INLINE unsigned long +ACE_Hash::operator () (ACE_INT32 t) const +{ + return static_cast (t); +} + +ACE_INLINE unsigned long +ACE_Hash::operator () (ACE_UINT32 t) const +{ + return t; +} + +ACE_INLINE unsigned long +ACE_Hash::operator () (ACE_UINT64 t) const +{ +#if (ACE_SIZEOF_LONG == 4) + return ACE_U64_TO_U32 (t); +#else + return static_cast (t); +#endif /* ACE_SIZEOF_LONG */ +} +#endif + +ACE_INLINE unsigned long +ACE_Hash::operator () (short t) const +{ + return static_cast (t); +} + +ACE_INLINE unsigned long +ACE_Hash::operator () (unsigned short t) const +{ + return static_cast (t); +} + +ACE_INLINE unsigned long +ACE_Hash::operator () (int t) const +{ + return static_cast (t); +} + +ACE_INLINE unsigned long +ACE_Hash::operator () (unsigned int t) const +{ + return static_cast (t); +} + +ACE_INLINE unsigned long +ACE_Hash::operator () (long t) const +{ + return static_cast (t); +} + +ACE_INLINE unsigned long +ACE_Hash::operator () (unsigned long t) const +{ + return t; +} + +// This #if needs to match the one in Functor.h +#if !defined (ACE_LACKS_LONGLONG_T) && (ACE_SIZEOF_LONG < 8) +ACE_INLINE unsigned long +ACE_Hash::operator () (ACE_INT64 t) const +{ + return static_cast (t); +} +#endif /* !ACE_LACKS_LONGLONG_T && ACE_SIZEOF_LONG < 8 */ + +#if (ACE_SIZEOF_LONG < 8) +ACE_INLINE unsigned long +ACE_Hash::operator () (const ACE_UINT64 &t) const +{ +#if (ACE_SIZEOF_LONG == 4) + return ACE_U64_TO_U32 (t); +#else + return static_cast (t); +#endif /* ACE_SIZEOF_LONG */ +} +#endif /* !ACE_LACKS_UNSIGNEDLONGLONG_T */ + +ACE_INLINE unsigned long +ACE_Hash::operator () (const char *t) const +{ + return ACE::hash_pjw (t); +} + +ACE_INLINE unsigned long +ACE_Hash::operator () (const char *t) const +{ + return ACE::hash_pjw (t); +} + +ACE_INLINE unsigned long +ACE_Hash::operator () (const void *t) const +{ + return static_cast (reinterpret_cast (t)); +} + +/***********************************************************************/ +ACE_INLINE int +ACE_Equal_To::operator () (const char *lhs, const char *rhs) const +{ + return !ACE_OS::strcmp (lhs, rhs); +} + +ACE_INLINE int +ACE_Equal_To::operator () (const char *lhs, const char *rhs) const +{ + return !ACE_OS::strcmp (lhs, rhs); +} + +ACE_INLINE int +ACE_Equal_To::operator () (const ACE_UINT16 lhs, const ACE_UINT16 rhs) const +{ + return (lhs == rhs); +} + +ACE_INLINE int +ACE_Equal_To::operator () (const ACE_INT16 lhs, const ACE_INT16 rhs) const +{ + return (lhs == rhs); +} + +ACE_INLINE int +ACE_Equal_To::operator () (const ACE_UINT32 lhs, const ACE_UINT32 rhs) const +{ + return (lhs == rhs); +} + +ACE_INLINE int +ACE_Equal_To::operator () (const ACE_INT32 lhs, const ACE_INT32 rhs) const +{ + return (lhs == rhs); +} + +ACE_INLINE int +ACE_Equal_To::operator () (const ACE_UINT64 lhs, const ACE_UINT64 rhs) const +{ + return (lhs == rhs); +} + +/****************************************************************************/ +ACE_INLINE int +ACE_Less_Than::operator () (const char *lhs, const char *rhs) const +{ + return (ACE_OS::strcmp (lhs, rhs) < 0) ? 1 : 0; +} + +ACE_INLINE int +ACE_Less_Than::operator () (const char *lhs, const char *rhs) const +{ + return (ACE_OS::strcmp (lhs, rhs) < 0) ? 1 : 0; +} + + +#if defined (ACE_HAS_WCHAR) + +ACE_INLINE unsigned long +ACE_Hash::operator () (const wchar_t *t) const +{ + return ACE::hash_pjw (t); +} + +ACE_INLINE unsigned long +ACE_Hash::operator () (const wchar_t *t) const +{ + return ACE::hash_pjw (t); +} + +ACE_INLINE int +ACE_Equal_To::operator () (const wchar_t *lhs, + const wchar_t *rhs) const +{ + return !ACE_OS::strcmp (lhs, rhs); +} + +ACE_INLINE int +ACE_Equal_To::operator () (const wchar_t *lhs, + const wchar_t *rhs) const +{ + return !ACE_OS::strcmp (lhs, rhs); +} + +ACE_INLINE int +ACE_Less_Than::operator () (const wchar_t *lhs, const wchar_t *rhs) const +{ + return (ACE_OS::strcmp (lhs, rhs) < 0) ? 1 : 0; +} + +ACE_INLINE int +ACE_Less_Than::operator () (const wchar_t *lhs, const wchar_t *rhs) const +{ + return (ACE_OS::strcmp (lhs, rhs) < 0) ? 1 : 0; +} + +#endif // ACE_HAS_WCHAR + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Functor_String.cpp b/dep/acelite/ace/Functor_String.cpp new file mode 100644 index 00000000000..c113f5cdf6f --- /dev/null +++ b/dep/acelite/ace/Functor_String.cpp @@ -0,0 +1,7 @@ +#include "ace/Functor_String.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Functor_String.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID(ace, Functor, "$Id: Functor_String.cpp 80826 2008-03-04 14:51:23Z wotte $") diff --git a/dep/acelite/ace/Functor_String.h b/dep/acelite/ace/Functor_String.h new file mode 100644 index 00000000000..2adf561a65f --- /dev/null +++ b/dep/acelite/ace/Functor_String.h @@ -0,0 +1,129 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file Functor_String.h + * + * $Id: Functor_String.h 86698 2009-09-13 15:58:17Z johnnyw $ + * + * Class template specializations for ACE_*String types implementing + * function objects that are used in various places in ATC. They + * could be placed in Functor.h. But we don't want to couple string + * types to the rest of ACE+TAO. Hence they are placed in a seperate + * file. + */ +//========================================================================== +#ifndef ACE_FUNCTOR_STRING_H +#define ACE_FUNCTOR_STRING_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include /**/ "ace/ACE_export.h" +#include "ace/SStringfwd.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +//////////////////////////////////////////////////////////// +// STL-style Functor Classes and Template Specializations // +//////////////////////////////////////////////////////////// + +// Forward declaration since we are going to specialize that template +// here. The template itself requires this file so every user of the +// template should also see the specialization. +template class ACE_Hash; +template class ACE_Equal_To; +template class ACE_Less_Than; + +/** + * @brief Function object for determining whether two ACE_CStrings are + * equal. + */ +template<> +class ACE_Export ACE_Equal_To +{ +public: + int operator () (const ACE_CString &lhs, + const ACE_CString &rhs) const; +}; + + +/** + * @brief Function object for hashing a ACE_CString + */ +template<> +class ACE_Export ACE_Hash +{ +public: + /// Calls ACE::hash_pjw + unsigned long operator () (const ACE_CString &lhs) const; +}; + + +/** + * @brief Function object for determining whether the first const string + * is less than the second const string. + */ +template<> +class ACE_Export ACE_Less_Than +{ +public: + /// Simply calls ACE_OS::strcmp + int operator () (const ACE_CString &lhs, + const ACE_CString &rhs) const; +}; + + +#if defined (ACE_USES_WCHAR) + +/** + * @brief Function object for determining whether two ACE_WStrings are + * equal. + */ +template<> +class ACE_Export ACE_Equal_To +{ +public: + int operator () (const ACE_WString &lhs, + const ACE_WString &rhs) const; +}; + + +/** + * @brief Function object for hashing a ACE_WString + */ +template<> +class ACE_Export ACE_Hash +{ +public: + /// Calls ACE::hash_pjw + unsigned long operator () (const ACE_WString &lhs) const; +}; + +/** + * @brief Function object for determining whether the first const wstring + * is less than the second const wstring. + */ +template<> +class ACE_Export ACE_Less_Than +{ +public: + /// Simply calls ACE_OS::strcmp + int operator () (const ACE_WString &lhs, + const ACE_WString &rhs) const; +}; + +#endif /*ACE_USES_WCHAR*/ + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Functor_String.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /*ACE_FUNCTOR_STRING_H*/ diff --git a/dep/acelite/ace/Functor_String.inl b/dep/acelite/ace/Functor_String.inl new file mode 100644 index 00000000000..bdac96386f8 --- /dev/null +++ b/dep/acelite/ace/Functor_String.inl @@ -0,0 +1,56 @@ +// -*- C++ -*- +// +// $Id: Functor_String.inl 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/ACE.h" +#include "ace/String_Base.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE unsigned long +ACE_Hash::operator () (const ACE_CString &t) const +{ + return t.hash (); +} + + +ACE_INLINE int +ACE_Equal_To::operator () (const ACE_CString &lhs, + const ACE_CString &rhs) const +{ + return lhs == rhs; +} + +ACE_INLINE int +ACE_Less_Than::operator () (const ACE_CString &lhs, + const ACE_CString &rhs) const +{ + return (lhs < rhs); +} + + +#if defined (ACE_USES_WCHAR) +ACE_INLINE unsigned long +ACE_Hash::operator () (const ACE_WString &t) const +{ + return t.hash (); +} + + +ACE_INLINE int +ACE_Equal_To::operator () (const ACE_WString &lhs, + const ACE_WString &rhs) const +{ + return lhs == rhs; +} + +ACE_INLINE int +ACE_Less_Than::operator () (const ACE_WString &lhs, + const ACE_WString &rhs) const +{ + return (lhs < rhs); +} + +#endif /*ACE_USES_WCHAR*/ + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Functor_T.cpp b/dep/acelite/ace/Functor_T.cpp new file mode 100644 index 00000000000..213b501aac1 --- /dev/null +++ b/dep/acelite/ace/Functor_T.cpp @@ -0,0 +1,49 @@ +// $Id: Functor_T.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#ifndef ACE_FUNCTOR_T_CPP +#define ACE_FUNCTOR_T_CPP + +#include "ace/Functor_T.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (__ACE_INLINE__) +#include "ace/Functor_T.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Command_Callback) + +/////////////////////////////////// +// GOF Command Pattern Templates // +/////////////////////////////////// + +// Constructor. + +template +ACE_Command_Callback::ACE_Command_Callback (RECEIVER &recvr, + ACTION action) + : receiver_ (recvr), + action_ (action) +{ +} + +template +ACE_Command_Callback::~ACE_Command_Callback (void) +{ +} + +// Invokes an operation. + +template int +ACE_Command_Callback::execute (void *arg) +{ + return (receiver_.*action_) (arg); +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_FUNCTOR_T_CPP */ diff --git a/dep/acelite/ace/Functor_T.h b/dep/acelite/ace/Functor_T.h new file mode 100644 index 00000000000..f055c3c885e --- /dev/null +++ b/dep/acelite/ace/Functor_T.h @@ -0,0 +1,158 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file Functor_T.h + * + * $Id: Functor_T.h 80826 2008-03-04 14:51:23Z wotte $ + * + * Templatized classes for implementing function objects that are + * used in various places in ACE. There are currently two major + * categories of function objects in ACE: GOF Command Pattern + * objects, and STL-style functors for comparison of container + * elements. The command objects are invoked via an + * method, while the STL-style functors are invoked via an + * method. + * + * + * @author Chris Gill + * @author Based on Command Pattern implementations originally done by + * @author Carlos O'Ryan + * @author Douglas C. Schmidt + * @author Sergio Flores-Gaitan + * @author and on STL-style functor implementations originally done by + * @author Irfan Pyarali + */ +//============================================================================= + + +#ifndef ACE_FUNCTOR_T_H +#define ACE_FUNCTOR_T_H +#include /**/ "ace/pre.h" + +#include "ace/Functor.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Functor_String.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/////////////////////////////////// +// GOF Command Pattern Templates // +/////////////////////////////////// + +/** + * @class ACE_Command_Callback + * + * @brief Defines a class template that allows us to invoke a GOF + * command style callback to an object without knowing anything + * about the object except its type. + * + * This class declares an interface to execute operations, + * binding a RECEIVER object with an ACTION. The RECEIVER knows + * how to implement the operation. A class can invoke operations + * without knowing anything about it, or how it was implemented. + */ +template +class ACE_Command_Callback : public ACE_Command_Base +{ +public: + /// Constructor: sets the of the Command to recvr, and the + /// of the Command to . + ACE_Command_Callback (RECEIVER &recvr, ACTION action); + + /// Virtual destructor. + virtual ~ACE_Command_Callback (void); + + /// Invokes the method from the object . + virtual int execute (void *arg = 0); + +private: + /// Object where the method resides. + RECEIVER &receiver_; + + /// Method that is going to be invoked. + ACTION action_; +}; + +///////////////////////////////// +// STL-style Functor Templates // +///////////////////////////////// + +/** + * @class ACE_Hash + * + * @brief Function object for hashing + */ +template +class ACE_Hash +{ +public: + /// Simply calls t.hash () + unsigned long operator () (const TYPE &t) const; +}; + +/** + * @class ACE_Pointer_Hash + * + * @brief Function object for hashing pointers + */ +template +class ACE_Pointer_Hash +{ +public: + /// Simply returns t. + unsigned long operator () (TYPE t) const; +}; + +/** + * @class ACE_Equal_To + * + * @brief Function object for comparing two objects of + * the given type for equality. + */ +template +class ACE_Equal_To +{ +public: + /// Simply calls operator== + bool operator () (const TYPE &lhs, + const TYPE &rhs) const; +}; + +/** + * @class ACE_Less_Than + * + * @brief Function object for determining whether the first object of + * the given type is less than the second object of the same + * type. + */ +template +class ACE_Less_Than +{ +public: + /// Simply calls operator< + bool operator () (const TYPE &lhs, + const TYPE &rhs) const; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Functor_T.inl" +#endif /* __ACE_INLINE__ */ + + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Functor_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Functor_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" +#endif /* ACE_FUNCTOR_T_H */ diff --git a/dep/acelite/ace/Functor_T.inl b/dep/acelite/ace/Functor_T.inl new file mode 100644 index 00000000000..35cfed5b798 --- /dev/null +++ b/dep/acelite/ace/Functor_T.inl @@ -0,0 +1,42 @@ +// -*- C++ -*- +// +// $Id: Functor_T.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template ACE_INLINE unsigned long +ACE_Hash::operator () (const TYPE &t) const +{ + return t.hash (); +} + +template ACE_INLINE unsigned long +ACE_Pointer_Hash::operator () (TYPE t) const +{ +#if defined (ACE_WIN64) + // The cast below is legit... we only want a hash, and need not convert + // the hash back to a pointer. +# pragma warning(push) +# pragma warning(disable : 4311) /* Truncate pointer to unsigned long */ +#endif /* ACE_WIN64 */ + return reinterpret_cast (t); +#if defined (ACE_WIN64) +# pragma warning(pop) +#endif /* ACE_WIN64 */ +} + +template ACE_INLINE bool +ACE_Equal_To::operator () (const TYPE &lhs, + const TYPE &rhs) const +{ + return lhs == rhs; +} + +template ACE_INLINE bool +ACE_Less_Than::operator () (const TYPE &lhs, + const TYPE &rhs) const +{ + return lhs < rhs; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Future.cpp b/dep/acelite/ace/Future.cpp new file mode 100644 index 00000000000..da40c468f31 --- /dev/null +++ b/dep/acelite/ace/Future.cpp @@ -0,0 +1,434 @@ + // $Id: Future.cpp 85358 2009-05-17 10:34:33Z johnnyw $ + +#ifndef ACE_FUTURE_CPP +#define ACE_FUTURE_CPP + +#include "ace/Future.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_RCSID (ace, Future, "$Id: Future.cpp 85358 2009-05-17 10:34:33Z johnnyw $") + +#if defined (ACE_HAS_THREADS) + +# include "ace/Guard_T.h" +# include "ace/Recursive_Thread_Mutex.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template +ACE_Future_Holder::ACE_Future_Holder (void) +{ +} + +template +ACE_Future_Holder::ACE_Future_Holder (const ACE_Future &item) + : item_ (item) +{ +} + +template +ACE_Future_Holder::~ACE_Future_Holder (void) +{ +} + +template +ACE_Future_Observer::ACE_Future_Observer (void) +{ +} + +template +ACE_Future_Observer::~ACE_Future_Observer (void) +{ +} + +// Dump the state of an object. + +template void +ACE_Future_Rep::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, + "ref_count_ = %d\n", + (int) this->ref_count_)); + ACE_DEBUG ((LM_INFO,"value_:\n")); + if (this->value_) + ACE_DEBUG ((LM_DEBUG, ACE_TEXT (" (NON-NULL)\n"))); + else + //FUZZ: disable check_for_NULL + ACE_DEBUG ((LM_DEBUG, ACE_TEXT (" (NULL)\n"))); + //FUZZ: enable check_for_NULL + + ACE_DEBUG ((LM_INFO,"value_ready_:\n")); + this->value_ready_.dump (); + ACE_DEBUG ((LM_INFO,"value_ready_mutex_:\n")); + this->value_ready_mutex_.dump (); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +template ACE_Future_Rep * +ACE_Future_Rep::internal_create (void) +{ + ACE_Future_Rep *temp = 0; + ACE_NEW_RETURN (temp, + ACE_Future_Rep (), + 0); + return temp; +} + +template ACE_Future_Rep * +ACE_Future_Rep::create (void) +{ + // Yes set ref count to zero. + ACE_Future_Rep *temp = internal_create (); +#if defined (ACE_NEW_THROWS_EXCEPTIONS) + if (temp == 0) + ACE_throw_bad_alloc; +#else + ACE_ASSERT (temp != 0); +#endif /* ACE_NEW_THROWS_EXCEPTIONS */ + return temp; + } + + +template ACE_Future_Rep * +ACE_Future_Rep::attach (ACE_Future_Rep*& rep) +{ + ACE_ASSERT (rep != 0); + // Use value_ready_mutex_ for both condition and ref count management + ACE_MT (ACE_Guard r_mon (rep->value_ready_mutex_)); + ++rep->ref_count_; + return rep; +} + +template void +ACE_Future_Rep::detach (ACE_Future_Rep*& rep) +{ + ACE_ASSERT (rep != 0); + // Use value_ready_mutex_ for both condition and ref count management + ACE_MT (ACE_GUARD (ACE_Recursive_Thread_Mutex, r_mon, rep->value_ready_mutex_)); + + if (rep->ref_count_-- == 0) + { + ACE_MT (r_mon.release ()); + // We do not need the lock when deleting the representation. + // There should be no side effects from deleting rep and we don + // not want to release a deleted mutex. + delete rep; + } +} + +template void +ACE_Future_Rep::assign (ACE_Future_Rep*& rep, ACE_Future_Rep* new_rep) +{ + ACE_ASSERT (rep != 0); + ACE_ASSERT (new_rep != 0); + // Use value_ready_mutex_ for both condition and ref count management + ACE_MT (ACE_GUARD (ACE_Recursive_Thread_Mutex, r_mon, rep->value_ready_mutex_)); + + ACE_Future_Rep* old = rep; + rep = new_rep; + + // detached old last for exception safety + if (old->ref_count_-- == 0) + { + ACE_MT (r_mon.release ()); + // We do not need the lock when deleting the representation. + // There should be no side effects from deleting rep and we don + // not want to release a deleted mutex. + delete old; + } +} + +template +ACE_Future_Rep::ACE_Future_Rep (void) + : value_ (0), + ref_count_ (0), + value_ready_ (value_ready_mutex_) +{ +} + +template +ACE_Future_Rep::~ACE_Future_Rep (void) +{ + delete this->value_; +} + +template int +ACE_Future_Rep::ready (void) const +{ + return this->value_ != 0; +} + +template int +ACE_Future_Rep::set (const T &r, + ACE_Future &caller) +{ + // If the value is already produced, ignore it... + if (this->value_ == 0) + { + ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, + ace_mon, + this->value_ready_mutex_, + -1)); + // Otherwise, create a new result value. Note the use of the + // Double-checked locking pattern to avoid multiple allocations. + + if (this->value_ == 0) // Still no value, so proceed + { + ACE_NEW_RETURN (this->value_, + T (r), + -1); + + // Remove and notify all subscribed observers. + typename OBSERVER_COLLECTION::iterator iterator = + this->observer_collection_.begin (); + + typename OBSERVER_COLLECTION::iterator end = + this->observer_collection_.end (); + + while (iterator != end) + { + OBSERVER *observer = *iterator++; + observer->update (caller); + } + + // Signal all the waiting threads. + return this->value_ready_.broadcast (); + } + // Destructor releases the lock. + } + return 0; +} + +template int +ACE_Future_Rep::get (T &value, + ACE_Time_Value *tv) const +{ + // If the value is already produced, return it. + if (this->value_ == 0) + { + ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, + this->value_ready_mutex_, + -1)); + // If the value is not yet defined we must block until the + // producer writes to it. + + while (this->value_ == 0) + // Perform a timed wait. + if (this->value_ready_.wait (tv) == -1) + return -1; + + // Destructor releases the lock. + } + + value = *this->value_; + return 0; +} + +template int +ACE_Future_Rep::attach (ACE_Future_Observer *observer, + ACE_Future &caller) +{ + ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, this->value_ready_mutex_, -1)); + + // Otherwise, create a new result value. Note the use of the + // Double-checked locking pattern to avoid corrupting the list. + + int result = 1; + + // If the value is already produced, then notify observer + if (this->value_ == 0) + result = this->observer_collection_.insert (observer); + else + observer->update (caller); + + return result; +} + +template int +ACE_Future_Rep::detach (ACE_Future_Observer *observer) +{ + ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, this->value_ready_mutex_, -1)); + + // Remove all occurrences of the specified observer from this + // objects hash map. + return this->observer_collection_.remove (observer); +} + +template +ACE_Future_Rep::operator T () +{ + // If the value is already produced, return it. + if (this->value_ == 0) + { + // Constructor of ace_mon acquires the mutex. + ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, this->value_ready_mutex_, 0)); + + // If the value is not yet defined we must block until the + // producer writes to it. + + // Wait ``forever.'' + + while (this->value_ == 0) + if (this->value_ready_.wait () == -1) + // What to do in this case since we've got to indicate + // failure somehow? Exceptions would be nice, but they're + // not portable... + return 0; + + // Destructor releases the mutex + } + + return *this->value_; +} + +template +ACE_Future::ACE_Future (void) + : future_rep_ (FUTURE_REP::create ()) +{ +} + +template +ACE_Future::ACE_Future (const ACE_Future &r) + : future_rep_ (FUTURE_REP::attach (((ACE_Future &) r).future_rep_)) +{ +} + +template +ACE_Future::ACE_Future (const T &r) + : future_rep_ (FUTURE_REP::create ()) +{ + this->future_rep_->set (r, *this); +} + +template +ACE_Future::~ACE_Future (void) +{ + FUTURE_REP::detach (future_rep_); +} + +template bool +ACE_Future::operator== (const ACE_Future &r) const +{ + return r.future_rep_ == this->future_rep_; +} + +template bool +ACE_Future::operator!= (const ACE_Future &r) const +{ + return r.future_rep_ != this->future_rep_; +} + +template int +ACE_Future::cancel (const T &r) +{ + this->cancel (); + return this->future_rep_->set (r, *this); +} + +template int +ACE_Future::cancel (void) +{ + // If this ACE_Future is already attached to a ACE_Future_Rep, + // detach it (maybe delete the ACE_Future_Rep). + FUTURE_REP::assign (this->future_rep_, + FUTURE_REP::create ()); + return 0; +} + +template int +ACE_Future::set (const T &r) +{ + // Give the pointer to the result to the ACE_Future_Rep. + return this->future_rep_->set (r, *this); +} + +template int +ACE_Future::ready (void) const +{ + // We're ready if the ACE_Future_rep is ready... + return this->future_rep_->ready (); +} + +template int +ACE_Future::get (T &value, + ACE_Time_Value *tv) const +{ + // We return the ACE_Future_rep. + return this->future_rep_->get (value, tv); +} + +template int +ACE_Future::attach (ACE_Future_Observer *observer) +{ + return this->future_rep_->attach (observer, *this); +} + +template int +ACE_Future::detach (ACE_Future_Observer *observer) +{ + return this->future_rep_->detach (observer); +} + +template +ACE_Future::operator T () +{ + // note that this will fail (and COREDUMP!) + // if future_rep_ == 0 ! + // + // but... + // this is impossible unless somebody is so stupid to + // try something like this: + // + // Future futT; + // T t; + // t = futT; + + // perform type conversion on Future_Rep. + return *future_rep_; +} + +template void +ACE_Future::operator = (const ACE_Future &rhs) +{ + // assignment: + // + // bind to the same as . + + // This will work if &r == this, by first increasing the ref count + ACE_Future &r = (ACE_Future &) rhs; + FUTURE_REP::assign (this->future_rep_, + FUTURE_REP::attach (r.future_rep_)); +} + +template void +ACE_Future::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_DEBUG ((LM_DEBUG, + ACE_BEGIN_DUMP, this)); + + if (this->future_rep_) + this->future_rep_->dump (); + + ACE_DEBUG ((LM_DEBUG, + ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +template ACE_Future_Rep * +ACE_Future::get_rep () +{ + return this->future_rep_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_THREADS */ + +#endif /* ACE_FUTURE_CPP */ diff --git a/dep/acelite/ace/Future.h b/dep/acelite/ace/Future.h new file mode 100644 index 00000000000..e30159eaf96 --- /dev/null +++ b/dep/acelite/ace/Future.h @@ -0,0 +1,387 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Future.h + * + * $Id: Future.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Andres Kruse + * @author Douglas C. Schmidt + * @author Per Andersson and + * @author John Tucker + */ +//============================================================================= + +#ifndef ACE_FUTURE_H +#define ACE_FUTURE_H + +#include /**/ "ace/pre.h" + +#include "ace/Unbounded_Set.h" +#include "ace/Strategies_T.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_THREADS) + +#include "ace/Recursive_Thread_Mutex.h" +#include "ace/Condition_Recursive_Thread_Mutex.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Forward decl. +template class ACE_Future_Holder; +template class ACE_Future_Observer; +template class ACE_Future_Rep; +template class ACE_Future; + +/** + * @class ACE_Future_Holder + * + * @brief Implementation of object that holds an ACE_Future. + */ +template +class ACE_Future_Holder +{ +public: + ACE_Future_Holder (const ACE_Future &future); + ~ACE_Future_Holder (void); + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + + ACE_Future item_; + +protected: + ACE_Future_Holder (void); +}; + +/** + * @class ACE_Future_Observer + * + * @brief ACE_Future_Observer + * + * An ACE_Future_Observer object implements an object that is + * subscribed with an ACE_Future object so that it may be notified + * when the value of the ACE_Future object is written to by a writer + * thread. It uses the Observer pattern. + */ +template +class ACE_Future_Observer +{ +public: + /// Destructor + virtual ~ACE_Future_Observer (void); + + /// Called by the ACE_Future in which we are subscribed to when + /// its value is written to. + virtual void update (const ACE_Future &future) = 0; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; +protected: + + /// Constructor + ACE_Future_Observer (void); +}; + +/** + * @class ACE_Future_Rep + * + * @internal + * + * @brief ACE_Future_Rep + * + * An ACE_Future_Rep object encapsules a pointer to an object + * of class T which is the result of an asynchronous method + * invocation. It is pointed to by ACE_Future object[s] and + * only accessible through them. + */ +template +class ACE_Future_Rep +{ +private: + friend class ACE_Future; + + /** + * Set the result value. The specified represents the + * future that invoked this method, which is used to notify + * the list of future observers. Returns 0 for success, -1 on error. + * This function only has an effect the first time it is called for + * the object. Subsequent calls return 0 (success) but have no effect. + */ + int set (const T &r, + ACE_Future &caller); + + /// Wait up to @a tv time to get the @a value. Note that @a tv must be + /// specified in absolute time rather than relative time. + int get (T &value, + ACE_Time_Value *tv) const; + + /** + * Attaches the specified observer to a subject (i.e., the ACE_Future_Rep). + * The update method of the specified subject will be invoked with a copy of + * the written-to ACE_Future as input when the result gets set. + * + * Returns 0 if the observer is successfully attached, 1 if the + * observer is already attached, and -1 if failures occur. + */ + int attach (ACE_Future_Observer *observer, + ACE_Future &caller); + + /** + * Detaches the specified observer from a subject (i.e., the ACE_Future_Rep). + * The update method of the specified subject will not be invoked when the + * ACE_Future_Reps result gets set. Returns 1 if the specified observer was + * actually attached to the subject prior to this call and 0 if was not. + * + * Returns 0 if the observer was successfully detached, and -1 if the + * observer was not attached in the first place. + */ + int detach (ACE_Future_Observer *observer); + + /** + * Type conversion. will block forever until the result is + * available. Note that this method is going away in a subsequent + * release since it doesn't distinguish between failure results and + * success results (exceptions should be used, but they aren't + * portable...). The method should be used instead since it + * separates the error value from the result, and also permits + * timeouts. + */ + operator T (); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + + // = Encapsulate reference count and object lifetime of instances. + + // These methods must go after the others to work around a bug with + // Borland's C++ Builder... + + /// Allocate a new ACE_Future_Rep instance, returning NULL if it + /// cannot be created. + static ACE_Future_Rep *internal_create (void); + + /// Create a ACE_Future_Rep and initialize the reference count. + static ACE_Future_Rep *create (void); + + /** + * Increase the reference count and return argument. Uses the + * attribute "value_ready_mutex_" to synchronize reference count + * updating. + * + * Precondition (rep != 0). + */ + static ACE_Future_Rep *attach (ACE_Future_Rep *&rep); + + /** + * Decreases the reference count and deletes rep if there are no + * more references to rep. + * + * Precondition (rep != 0) + */ + static void detach (ACE_Future_Rep *&rep); + + /** + * Decreases the rep's reference count and deletes rep if there + * are no more references to rep. Then assigns new_rep to rep. + * + * Precondition (rep != 0 && new_rep != 0) + */ + static void assign (ACE_Future_Rep *&rep, ACE_Future_Rep *new_rep); + + /// Is result available? + int ready (void) const; + + /// Pointer to the result. + T *value_; + + /// Reference count. + int ref_count_; + + typedef ACE_Future_Observer OBSERVER; + + typedef ACE_Unbounded_Set OBSERVER_COLLECTION; + + /// Keep a list of ACE_Future_Observers unread by client's reader thread. + OBSERVER_COLLECTION observer_collection_; + + // = Condition variable and mutex that protect the . + mutable ACE_Recursive_Thread_Mutex value_ready_mutex_; + mutable ACE_Condition_Recursive_Thread_Mutex value_ready_; + +private: + + ACE_Future_Rep (void); + +protected: + + ~ACE_Future_Rep (void); + +}; + +/** + * @class ACE_Future + * + * @brief This class implements a ``single write, multiple read'' + * pattern that can be used to return results from asynchronous + * method invocations. + */ +template +class ACE_Future +{ +public: + // = Initialization and termination methods. + /// Constructor. + ACE_Future (void); + + /// Copy constructor binds @a this and @a r to the same + /// ACE_Future_Rep. An ACE_Future_Rep is created if necessary. + ACE_Future (const ACE_Future &r); + + /// Constructor that initialises an ACE_Future to point to the + /// result @a r immediately. + ACE_Future (const T &r); + + /// Destructor. + ~ACE_Future (void); + + /// Assignment operator that binds @a this and @a r to the same + /// ACE_Future_Rep. An ACE_Future_Rep is created if necessary. + void operator = (const ACE_Future &r); + + /// Cancel an ACE_Future and assign the value @a r. It is used if a + /// client does not want to wait for the value to be produced. + int cancel (const T &r); + + /** + * Cancel an ACE_Future. Put the future into its initial + * state. Returns 0 on succes and -1 on failure. It is now possible + * to reuse the ACE_Future. But remember, the ACE_Future + * is now bound to a new ACE_Future_Rep. + */ + int cancel (void); + + /** + * Equality operator that returns @c true if both ACE_Future objects + * point to the same ACE_Future_Rep object. + * + * @note It also returns @c true if both objects have just been + * instantiated and not used yet. + */ + bool operator == (const ACE_Future &r) const; + + /// Inequality operator, which is the opposite of equality. + bool operator != (const ACE_Future &r) const; + + /** + * Make the result available. Is used by the server thread to give + * the result to all waiting clients. Returns 0 for success, -1 on failure. + * This function only has an effect the first time it is called for + * the object (actually, the first time the underlying ACE_Future_Rep has a + * value assigned to it). Subsequent calls return 0 (success) but have no + * effect. + */ + int set (const T &r); + + /** + * Wait to get the object's value. + * + * @param value Receives the value of this ACE_Future when it is set. + * @param tv Pointer to an ACE_Time_Value containing the absolute + * time to wait until for the value to be set. If @a tv + * is 0, the call waits indefinitely for the value to be + * set, unless an error occurs. + * + * @retval 0 Success; @a value contains the value of the ACE_Future. + * @retval -1 Error; check ACE_OS::last_error() for an error code. + */ + int get (T &value, + ACE_Time_Value *tv = 0) const; + + /** + * @deprecated Note that this method is going away in a subsequent + * release since it doesn't distinguish between failure + * results and success results (exceptions should be + * used, but they aren't portable...). + * Type conversion, which obtains the result of the asynchronous + * method invocation. Will block forever. The get() method should be + * used instead since it separates the error value from the result, + * and also permits timeouts. + */ + operator T (); + + /// Check if the result is available. + int ready (void) const; + + /** + * Attaches the specified observer to a subject (this ACE_Future). + * The update method of the specified subject will be invoked with a copy of + * the associated ACE_Future as input when the result gets set. If the + * result is already set when this method gets invoked, then the update + * method of the specified subject will be invoked immediately. + * + * @param observer The observer to attach to the subject. + * + * @retval 0 Success. + * @retval 1 The observer was already attached. + * @retval -1 Error; check ACE_OS::last_error() for an error code. + */ + int attach (ACE_Future_Observer *observer); + + /** + * Detaches the specified observer from a subject (this ACE_Future). + * The update method of the specified subject will not be invoked when the + * ACE_Future_Rep result gets set. + * + * @param observer The observer to attach to the subject. + * + * @retval 0 The observer was successfully detached. + * @retval -1 Error, including the observer not attached prior + * to calling this method. + */ + int detach (ACE_Future_Observer *observer); + + /// Dump the state of an object. + void dump (void) const; + + /** + * Get the underlying ACE_Future_Rep pointer. Note that this method should + * rarely, if ever, be used and that modifying the underlying + * ACE_Future_Rep should be done with extreme caution. + */ + ACE_Future_Rep *get_rep (void); + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + + // the ACE_Future_Rep + /// Protect operations on the . + typedef ACE_Future_Rep FUTURE_REP; + FUTURE_REP *future_rep_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Future.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Future.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#endif /* ACE_HAS_THREADS */ + +#include /**/ "ace/post.h" + +#endif /* ACE_FUTURE_H */ diff --git a/dep/acelite/ace/Future_Set.cpp b/dep/acelite/ace/Future_Set.cpp new file mode 100644 index 00000000000..a40b0700dc5 --- /dev/null +++ b/dep/acelite/ace/Future_Set.cpp @@ -0,0 +1,136 @@ +// $Id: Future_Set.cpp 88128 2009-12-14 02:17:22Z schmidt $ + +#ifndef ACE_FUTURE_SET_CPP +#define ACE_FUTURE_SET_CPP + +#include "ace/Future_Set.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +#pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_THREADS) + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template +ACE_Future_Set::ACE_Future_Set (ACE_Message_Queue *new_queue) + : delete_queue_ (false) +{ + if (new_queue) + this->future_notification_queue_ = new_queue; + else + { + ACE_NEW (this->future_notification_queue_, + ACE_Message_Queue); + this->delete_queue_ = true; + } +} + +template +ACE_Future_Set::~ACE_Future_Set (void) +{ + // Detach ourselves from all remaining futures, if any, in our map. + typename FUTURE_HASH_MAP::iterator iterator = + this->future_map_.begin (); + + typename FUTURE_HASH_MAP::iterator end = + this->future_map_.end (); + + for (; + iterator != end; + ++iterator) + { + FUTURE_HOLDER *future_holder = (*iterator).int_id_; + future_holder->item_.detach (this); + delete future_holder; + } + + if (this->delete_queue_) + delete this->future_notification_queue_; +} + +template int +ACE_Future_Set::is_empty () const +{ + return (((ACE_Future_Set*)this)->future_map_.current_size () == 0 ); +} + +template int +ACE_Future_Set::insert (ACE_Future &future) +{ + FUTURE_HOLDER *future_holder; + ACE_NEW_RETURN (future_holder, + FUTURE_HOLDER (future), + -1); + + FUTURE_REP *future_rep = future.get_rep (); + int result = this->future_map_.bind (future_rep, + future_holder); + + // If a new map entry was created, then attach to the future, + // otherwise we were already attached to the future or some error + // occurred so just delete the future holder. + if (result == 0) + // Attach ourself to the ACE_Futures list of observer + future.attach (this); + else + delete future_holder; + + return result; +} + +template void +ACE_Future_Set::update (const ACE_Future &future) +{ + ACE_Message_Block *mb; + FUTURE &local_future = const_cast &> (future); + + ACE_NEW (mb, + ACE_Message_Block ((char *) local_future.get_rep (), 0)); + + // Enqueue in priority order. + this->future_notification_queue_->enqueue (mb, 0); +} + +template int +ACE_Future_Set::next_readable (ACE_Future &future, + ACE_Time_Value *tv) +{ + if (this->is_empty ()) + return 0; + + ACE_Message_Block *mb = 0; + FUTURE_REP *future_rep = 0; + + // Wait for a "readable future" signal from the message queue. + if (this->future_notification_queue_->dequeue_head (mb, + tv) != -1) + { + // Extract future rep from the message block. + future_rep = reinterpret_cast (mb->base ()); + + // Delete the message block. + mb->release (); + } + else + return 0; + + // Remove the hash map entry with the specified future rep from our map. + FUTURE_HOLDER *future_holder; + if (this->future_map_.find (future_rep, + future_holder) != -1) + { + future = future_holder->item_; + this->future_map_.unbind (future_rep); + delete future_holder; + return 1; + } + + return 0; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_THREADS */ +#endif /* ACE_FUTURE_SET_CPP */ diff --git a/dep/acelite/ace/Future_Set.h b/dep/acelite/ace/Future_Set.h new file mode 100644 index 00000000000..3d07f4f73e2 --- /dev/null +++ b/dep/acelite/ace/Future_Set.h @@ -0,0 +1,146 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Future_Set.h + * + * $Id: Future_Set.h 88128 2009-12-14 02:17:22Z schmidt $ + * + * @author John Tucker + */ +//============================================================================= + +#ifndef ACE_FUTURE_SET_H +#define ACE_FUTURE_SET_H +#include /**/ "ace/pre.h" + +#include "ace/Thread.h" +#include "ace/Message_Queue.h" +#include "ace/Future.h" +#include "ace/Hash_Map_Manager_T.h" +#include "ace/Null_Mutex.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +#pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_THREADS) + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Future_Set + * + * @brief This class implements a mechanism that allows the values of + * a collection of ACE_Future objects to be accessed by reader threads + * as they become available. The caller(s) provide the ACE_Future_Set + * (i.e. the observer...) with the collection of ACE_Future objects + * (i.e. the subjects...) that are to be observed using the the + * ACE_Future_Set::insert() method. The caller(s) may then iterate + * over the collection in the order in which they become readable + * using the ACE_Future_Set::next_readable() method. + */ +template +class ACE_Future_Set : public ACE_Future_Observer +{ +public: + // = Initialization and termination methods. + + /// Constructor. + ACE_Future_Set (ACE_Message_Queue *future_notification_queue_ = 0); + + /// Destructor. + ~ACE_Future_Set (void); + + /** + * Return 1 if their are no ACE_Future objects left on its queue and + * 0 otherwise. + * + * When an ACE_Future_Set has no ACE_Future>subjects to observe it is + * empty. The ACE_Future_Set is in the empty state when either the caller(s) + * have retrieved every readable ACE_Future subject assigned the + * ACE_Future_Set via the ACE_Future_Set::next_readable() method, + * or when the ACE_Future_Set has not been assigned any subjects. + */ + int is_empty (void) const; + + /** + * Enqueus the given ACE_Future into this objects queue when it is + * readable. + * + * Returns 0 if the future is successfully inserted, 1 if the + * future is already inserted, and -1 if failures occur. + */ + int insert (ACE_Future &future); + + /** + * Wait up to @a tv time to get the @a value. Note that @a tv must be + * specified in absolute time rather than relative time.); get the + * next ACE_Future that is readable. If @a tv = 0, the will block + * forever. + * + * If a readable future becomes available, then the input + * ACE_Future object param will be assigned with it and 1 will + * be returned. If the ACE_Future_Set is empty (i.e. see definition + * of ACE_Future_Set::is_empty()), then 0 is returned. + * + * When a readable ACE_Future object is retrieved via the + * ACE_Future_Set::next_readable() method, the ACE_Future_Set will + * remove that ACE_Future object from its list of subjects. + */ + int next_readable (ACE_Future &result, + ACE_Time_Value *tv = 0); + + /// Called by the ACE_Future subject in which we are subscribed to + /// when its value is written to. + virtual void update (const ACE_Future &future); + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + // = Disallow these operations. + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Future_Set &)) + ACE_UNIMPLEMENTED_FUNC (ACE_Future_Set (const ACE_Future_Set &)) + + typedef ACE_Future FUTURE; + + typedef ACE_Future_Rep FUTURE_REP; + + typedef ACE_Future_Holder FUTURE_HOLDER; + + typedef ACE_Pointer_Hash FUTURE_REP_HASH; + + typedef ACE_Equal_To FUTURE_REP_COMPARE; + + typedef ACE_Hash_Map_Manager_Ex FUTURE_HASH_MAP; + + /// Map of , subjects, which have not been written to by + /// client's writer thread. + FUTURE_HASH_MAP future_map_; + + /// Message queue for notifying the reader thread of which + /// have been written to by client's writer thread. + ACE_Message_Queue *future_notification_queue_; + + /// Keeps track of whether we need to delete the message queue. + bool delete_queue_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Future_Set.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Future_Set.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#endif /* ACE_HAS_THREADS */ +#include /**/ "ace/post.h" +#endif /* ACE_FUTURE_SET_H */ diff --git a/dep/acelite/ace/Get_Opt.cpp b/dep/acelite/ace/Get_Opt.cpp new file mode 100644 index 00000000000..915ff8a87a9 --- /dev/null +++ b/dep/acelite/ace/Get_Opt.cpp @@ -0,0 +1,734 @@ +// $Id: Get_Opt.cpp 81840 2008-06-05 13:46:45Z sma $ + +#include "ace/Get_Opt.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Get_Opt.inl" +#endif /* __ACE_INLINE__ */ + +#include "ace/ACE.h" +#include "ace/Log_Msg.h" +#include "ace/SString.h" +#include "ace/OS_Memory.h" +#include "ace/OS_NS_string.h" +#include "ace/OS_NS_ctype.h" +#include "ace/OS_NS_stdlib.h" + +ACE_RCSID (ace, + Get_Opt, + "$Id: Get_Opt.cpp 81840 2008-06-05 13:46:45Z sma $") + +/* + * Copyright (c) 1987, 1993, 1994 + * The Regents of the University of California. 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University 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 REGENTS 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 REGENTS 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. + */ + +/*- + * Copyright (c) 2000 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Dieter Baron and Thomas Klausner. + * + * 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the NetBSD + * Foundation, Inc. and its contributors. + * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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. + */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Get_Opt) + +#ifdef ACE_USES_WCHAR +void ACE_Get_Opt::ACE_Get_Opt_Init (const ACE_TCHAR *optstring) +#else +ACE_Get_Opt::ACE_Get_Opt (int argc, + ACE_TCHAR **argv, + const ACE_TCHAR *optstring, + int skip, + int report_errors, + int ordering, + int long_only) + : argc_ (argc), + argv_ (argv), + optind (skip), + opterr (report_errors), + optarg (0), + optstring_ (0), + long_only_ (long_only), + has_colon_ (0), + last_option_ (0), + nextchar_ (0), + optopt_ (0), + ordering_ (ordering), + nonopt_start_ (optind), + nonopt_end_ (optind), + long_option_ (0) +#endif +{ + ACE_TRACE ("ACE_Get_Opt::ACE_Get_Opt"); + + ACE_NEW (this->optstring_, ACE_TString (optstring)); + ACE_NEW (this->last_option_, ACE_TString (ACE_TEXT (""))); + + // First check to see if POSIXLY_CORRECT was set. + // Win32 is the only platform capable of wide-char env var. +#if defined (ACE_WIN32) + const ACE_TCHAR *env_check = ACE_TEXT ("POSIXLY_CORRECT"); +#else + const char *env_check = "POSIXLY_CORRECT"; +#endif + if (ACE_OS::getenv (env_check) != 0) + this->ordering_ = REQUIRE_ORDER; + + // Now, check to see if any or the following were passed at + // the begining of optstring: '+' same as POSIXLY_CORRECT; + // '-' turns off POSIXLY_CORRECT; or ':' which signifies we + // should return ':' if a parameter is missing for an option. + // We use a loop here, since a combination of "{+|-}:" in any + // order should be legal. + int done = 0; + int offset = 0; + while (!done) + { + switch (optstring[offset++]) + { + case '+': + this->ordering_ = REQUIRE_ORDER; + break; + case '-': + this->ordering_ = RETURN_IN_ORDER; + break; + case ':': + this->has_colon_ = 1; + break; + default: + // Quit as soon as we see something else... + done = 1; + break; + } + } +} + +ACE_Get_Opt::~ACE_Get_Opt (void) +{ + ACE_TRACE ("ACE_Get_Opt::~ACE_Get_Opt"); + + size_t i = 0; + size_t size = this->long_opts_.size (); + ACE_Get_Opt_Long_Option *option = 0; + for (i = 0; i < size; ++i) + { + int retval = this->long_opts_.get (option, i); + if (retval != 0) + { + // Should never happen. + retval = 0; + continue; + } + if (option) + { + delete option; + option = 0; + } + } + delete this->optstring_; + delete this->last_option_; +} + +int +ACE_Get_Opt::nextchar_i (void) +{ + ACE_TRACE ("ACE_Get_Opt::nextchar_i"); + + if (this->ordering_ == PERMUTE_ARGS) + if (this->permute () == EOF) + return EOF; + + // Update scanning pointer. + if (this->optind >= this->argc_) + { + // We're done... + this->nextchar_ = 0; + return EOF; + } + else if (*(this->nextchar_ = this->argv_[this->optind]) != '-' + || this->nextchar_[1] == '\0') + { + // We didn't get an option. + + if (this->ordering_ == REQUIRE_ORDER + || this->ordering_ == PERMUTE_ARGS) + // If we permuted or require the options to be in order, we're done. + return EOF; + + // It must be RETURN_IN_ORDER... + this->optarg = this->argv_[this->optind++]; + this->nextchar_ = 0; + return 1; + } + else if (this->nextchar_[1] != 0 + && *++this->nextchar_ == '-' + && this->nextchar_[1] == 0) + { + // Found "--" so we're done... + ++this->optind; + this->nextchar_ = 0; + return EOF; + } + + // If it's a long option, and we allow long options advance nextchar_. + if (*this->nextchar_ == '-' && this->long_opts_.size () != 0) + this->nextchar_++; + + return 0; +} + +int +ACE_Get_Opt::long_option_i (void) +{ + ACE_TRACE ("ACE_Get_Opt::long_option_i"); + + ACE_Get_Opt_Long_Option *p; + ACE_TCHAR *s = this->nextchar_; + int hits = 0; + int exact = 0; + ACE_Get_Opt_Long_Option *pfound = 0; + int indfound = 0; + + // Advance to the end of the long option name so we can use + // it to get the length for a string compare. + while (*s && *s != '=') + s++; + + size_t len = s - this->nextchar_; + // set last_option_ to nextchar_, up to the '='. + this->last_option (ACE_TString (this->nextchar_, len)); + + size_t size = this->long_opts_.size (); + u_int option_index = 0; + for (option_index = 0; option_index < size ; option_index++) + { + p = this->long_opts_[option_index]; + ACE_ASSERT (p); + + if (!ACE_OS::strncmp (p->name_, this->nextchar_, len)) + { + // Got at least a partial match. + pfound = p; + indfound = option_index; + hits += 1; + if (len == ACE_OS::strlen(p->name_)) + { + // And in fact, it's an exact match, so let's use it. + exact = 1; + break; + } + } + } + + if ((hits > 1) && !exact) + { + // Great, we found a match, but unfortunately we found more than + // one and it wasn't exact. + if (this->opterr) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%s: option `%s' is ambiguous\n"), + this->argv_[0], this->argv_[this->optind])); + this->nextchar_ = 0; + this->optind++; + return '?'; + } + + if (pfound != 0) + { + // Okay, we found a good one (either a single hit or an exact match). + option_index = indfound; + this->optind++; + if (*s) + { + // s must point to '=' which means there's an argument (well + // close enough). + if (pfound->has_arg_ != NO_ARG) + // Good, we want an argument and here it is. + this->optarg = ++s; + else + { + // Whoops, we've got what looks like an argument, but we + // don't want one. + if (this->opterr) + ACE_ERROR + ((LM_ERROR, + ACE_TEXT ("%s: long option `--%s' doesn't allow ") + ACE_TEXT ("an argument\n"), + this->argv_[0], pfound->name_)); + // The spec doesn't cover this, so we keep going and the program + // doesn't know we ignored an argument if opt_err is off!!! + } + } + else if (pfound->has_arg_ == ARG_REQUIRED) + { + // s didn't help us, but we need an argument. Note that + // optional arguments for long options must use the "=" syntax, + // so we won't get here in that case. + if (this->optind < this->argc_) + // We still have some elements left, so use the next one. + this->optarg = this->argv_[this->optind++]; + else + { + // All out of elements, so we have to punt... + if (this->opterr) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%s: long option '--%s' requires ") + ACE_TEXT ("an argument\n"), + this->argv_[0], pfound->name_)); + this->nextchar_ = 0; + this->optopt_ = pfound->val_; // Remember matching short equiv + return this->has_colon_ ? ':' : '?'; + } + } + this->nextchar_ = 0; + this->long_option_ = pfound; + // Since val_ has to be either a valid short option or 0, this works + // great. If the user really wants to know if a long option was passed. + this->optopt_ = pfound->val_; + return pfound->val_; + } + if (!this->long_only_ || this->argv_[this->optind][1] == '-' + || this->optstring_->find (*this->nextchar_) == ACE_TString::npos) + { + // Okay, we couldn't find a long option. If it isn't long_only (which + // means try the long first, and if not found try the short) or a long + // signature was passed, e.g. "--", or it's not a short (not sure when + // this could happen) it's an error. + if (this->opterr) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%s: illegal long option '--%s'\n"), + this->argv_[0], this->nextchar_)); + this->nextchar_ = 0; + this->optind++; + return '?'; + } + return this->short_option_i (); +} + +int +ACE_Get_Opt::short_option_i (void) +{ + ACE_TRACE ("ACE_Get_Opt::short_option_i"); + + /* Look at and handle the next option-character. */ + ACE_TCHAR opt = *this->nextchar_++; + // Set last_option_ to opt + this->last_option (opt); + + ACE_TCHAR *oli = 0; + oli = + const_cast (ACE_OS::strchr (this->optstring_->c_str (), opt)); + + /* Increment `optind' when we start to process its last character. */ + if (*this->nextchar_ == '\0') + ++this->optind; + + if (oli == 0 || opt == ':') + { + if (this->opterr) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%s: illegal short option -- %c\n"), + this->argv_[0], opt)); + return '?'; + } + if (opt == 'W' && oli[1] == ';') + { + if (this->nextchar_[0] == 0) + this->nextchar_ = this->argv_[this->optind]; + return long_option_i (); + } + this->optopt_ = oli[0]; // Remember the option that matched + if (oli[1] == ':') + { + if (oli[2] == ':') + { + // Takes an optional argument, and since short option args must + // must follow directly in the same argument, a NULL nextchar_ + // means we didn't get one. + if (*this->nextchar_ != '\0') + { + this->optarg = this->nextchar_; + this->optind++; + } + else + this->optarg = 0; + this->nextchar_ = 0; + } + else + { + // Takes a required argument. + if (*this->nextchar_ != '\0') + { + // Found argument in same argv-element. + this->optarg = this->nextchar_; + this->optind++; + } + else if (this->optind == this->argc_) + { + // Ran out of arguments before finding required argument. + if (this->opterr) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%s: short option requires ") + ACE_TEXT ("an argument -- %c\n"), + this->argv_[0], opt)); + opt = this->has_colon_ ? ':' : '?'; + } + else + // Use the next argv-element as the argument. + this->optarg = this->argv_[this->optind++]; + this->nextchar_ = 0; + } + } + return opt; +} + +int +ACE_Get_Opt::operator () (void) +{ + ACE_TRACE ("ACE_Get_Opt_Long::operator"); + + // First of all, make sure we reinitialize any pointers.. + this->optarg = 0; + this->long_option_ = 0; + + if (this->argv_ == 0) + { + // It can happen, e.g., on VxWorks. + this->optind = 0; + return -1; + } + + // We check this because we can string short options together if the + // preceding one doesn't take an argument. + if (this->nextchar_ == 0 || *this->nextchar_ == '\0') + { + int retval = this->nextchar_i (); + if (retval != 0) + return retval; + } + + if (((this->argv_[this->optind][0] == '-') + && (this->argv_[this->optind][1] == '-')) || this->long_only_) + return this->long_option_i (); + + return this->short_option_i (); +} + +int +ACE_Get_Opt::long_option (const ACE_TCHAR *name, + OPTION_ARG_MODE has_arg) +{ + ACE_TRACE ("ACE_Get_Opt::long_option (const ACE_TCHAR *name, OPTION_ARG_MODE has_arg)"); + return this->long_option (name, 0, has_arg); +} + +int +ACE_Get_Opt::long_option (const ACE_TCHAR *name, + int short_option, + OPTION_ARG_MODE has_arg) +{ + ACE_TRACE ("ACE_Get_Opt::long_option (const ACE_TCHAR *name, int short_option, OPTION_ARG_MODE has_arg)"); + + // We only allow valid alpha-numeric characters as short options. + // If short_options is not a valid alpha-numeric, we can still return it + // when the long option is found, but won't allow the caller to pass it on + // the command line (how could they?). The special case is 0, but since + // we always return it, we let the caller worry about that. + if (ACE_OS::ace_isalnum (short_option) != 0) + { + // If the short_option already exists, make sure it matches, otherwise + // add it. + ACE_TCHAR *s = 0; + if ((s = const_cast ( + ACE_OS::strchr (this->optstring_->c_str (), + short_option))) != 0) + { + // Short option exists, so verify the argument options + if (s[1] == ':') + { + if (s[2] == ':') + { + if (has_arg != ARG_OPTIONAL) + { + if (this->opterr) + ACE_ERROR + ((LM_ERROR, + ACE_TEXT ("Existing short option '%c' takes ") + ACE_TEXT ("optional argument; adding %s ") + ACE_TEXT ("requires ARG_OPTIONAL\n"), + short_option, name)); + return -1; + } + } + else + if (has_arg != ARG_REQUIRED) + { + if (this->opterr) + ACE_ERROR + ((LM_ERROR, + ACE_TEXT ("Existing short option '%c' requires ") + ACE_TEXT ("an argument; adding %s ") + ACE_TEXT ("requires ARG_REQUIRED\n"), + short_option, name)); + return -1; + } + } + else if (has_arg != NO_ARG) + { + if (this->opterr) + ACE_ERROR + ((LM_ERROR, + ACE_TEXT ("Existing short option '%c' does not ") + ACE_TEXT ("accept an argument; adding %s ") + ACE_TEXT ("requires NO_ARG\n"), + short_option, name)); + return -1; + } + } + else + { + // Didn't find short option, so add it... + *this->optstring_ += (ACE_TCHAR) short_option; + if (has_arg == ARG_REQUIRED) + *this->optstring_ += ACE_TEXT (":"); + else if (has_arg == ARG_OPTIONAL) + *this->optstring_ += ACE_TEXT ("::"); + } + } + + ACE_Get_Opt_Long_Option *option = + new ACE_Get_Opt_Long_Option (name, has_arg, short_option); + + if (!option) + return -1; + + // Add to array + size_t size = this->long_opts_.size (); + if (this->long_opts_.size (size + 1) != 0 + || this->long_opts_.set (option, size) != 0) + { + delete option; + ACE_ERROR_RETURN + ((LM_ERROR, ACE_TEXT ("Could not add long option to array.\n")), + -1); + } + return 0; +} + +const ACE_TCHAR* +ACE_Get_Opt::long_option (void) const +{ + ACE_TRACE ("ACE_Get_Opt::long_option (void)"); + if (this->long_option_) + return this->long_option_->name_; + return 0; +} + +const ACE_TCHAR* +ACE_Get_Opt::last_option (void) const +{ + return this->last_option_->c_str (); +} + +void +ACE_Get_Opt::last_option (const ACE_TString &last_option) +{ + *this->last_option_ = last_option; +} + +void +ACE_Get_Opt::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Get_Opt::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n") + ACE_TEXT ("opstring_ = %s\n") + ACE_TEXT ("long_only_ = %d\n") + ACE_TEXT ("has_colon_ = %d\n") + ACE_TEXT ("last_option_ = %s\n") + ACE_TEXT ("nextchar_ = %s\n") + ACE_TEXT ("optopt_ = %c\n") + ACE_TEXT ("ordering_ = %d\n"), + this->optstring_->c_str (), + this->long_only_, + this->has_colon_, + this->last_option_->c_str (), + this->nextchar_, + this->optopt_, + this->ordering_)); + + // now loop through the + size_t size = this->long_opts_.size (); + for (u_int i = 0; i < size ; ++i) + { + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n") + ACE_TEXT ("long_option name_ = %s\n") + ACE_TEXT ("has_arg_ = %d\n") + ACE_TEXT ("val_ = %d\n"), + this->long_opts_[i]->name_, + this->long_opts_[i]->has_arg_, + this->long_opts_[i]->val_)); + } + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +void +ACE_Get_Opt::permute_args (void) +{ + ACE_TRACE ("ACE_Get_Opt::permute_args"); + + u_long cyclelen, i, j, ncycle, nnonopts, nopts; + u_long opt_end = this->optind; + int cstart, pos = 0; + ACE_TCHAR *swap = 0; + + nnonopts = this->nonopt_end_ - this->nonopt_start_; + nopts = opt_end - this->nonopt_end_; + ncycle = ACE::gcd (nnonopts, nopts); + cyclelen = (opt_end - this->nonopt_start_) / ncycle; + + this->optind = this->optind - nnonopts; + + for (i = 0; i < ncycle; i++) + { + cstart = this->nonopt_end_ + i; + pos = cstart; + for (j = 0; j < cyclelen; j++) + { + if (pos >= this->nonopt_end_) + pos -= nnonopts; + else + pos += nopts; + swap = this->argv_[pos]; + + ((ACE_TCHAR **)this->argv_)[pos] = argv_[cstart]; + + ((ACE_TCHAR **)this->argv_)[cstart] = swap; + } + } +} + +int +ACE_Get_Opt::permute (void) +{ + ACE_TRACE ("ACE_Get_Opt::permute"); + + if (this->nonopt_start_ != this->nonopt_end_ + && this->nonopt_start_ != this->optind) + this->permute_args (); + + this->nonopt_start_ = this->optind; + + // Skip over args untill we find the next option. + while (this->optind < this->argc_ + && (this->argv_[this->optind][0] != '-' + || this->argv_[this->optind][1] == '\0')) + this->optind++; + + // Got an option, so mark this as the end of the non options. + this->nonopt_end_ = this->optind; + + if (this->optind != this->argc_ + && ACE_OS::strcmp (this->argv_[this->optind], + ACE_TEXT ("--")) == 0) + { + // We found the marker for the end of the options. + ++this->optind; + + if (this->nonopt_start_ != this->nonopt_end_ + && this->nonopt_end_ != this->optind) + this->permute_args (); + } + + if (this->optind == this->argc_) + { + if (this->nonopt_start_ != this->nonopt_end_) + this->optind = this->nonopt_start_; + return EOF; + } + return 0; +} + +const ACE_TCHAR * +ACE_Get_Opt::optstring (void) const +{ + return this->optstring_->c_str (); +} + +ACE_Get_Opt::ACE_Get_Opt_Long_Option::ACE_Get_Opt_Long_Option ( + const ACE_TCHAR *name, + int has_arg, + int val) + : name_ (ACE::strnew (name)), + has_arg_ (has_arg), + val_ (val) +{} + +ACE_Get_Opt::ACE_Get_Opt_Long_Option::~ACE_Get_Opt_Long_Option (void) +{ + delete [] this->name_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Get_Opt.h b/dep/acelite/ace/Get_Opt.h new file mode 100644 index 00000000000..1c30096ea6d --- /dev/null +++ b/dep/acelite/ace/Get_Opt.h @@ -0,0 +1,494 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file Get_Opt.h + * + * $Id: Get_Opt.h 86367 2009-08-05 09:41:11Z johnnyw $ + * + * @author Douglas C. Schmidt + * @author Don Hinton (added long option support) + */ +//========================================================================== + +#ifndef ACE_GET_OPT_H +#define ACE_GET_OPT_H +#include /**/ "ace/pre.h" + +#include "ace/SStringfwd.h" +#include "ace/Containers.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#undef optind +#undef optarg +#undef opterr + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/* + * These definitions are for backward compatibility with previous versions. + * of ACE_Get_Opt. + */ + +/** + * @class ACE_Get_Opt + * + * @brief Iterator for parsing command-line arguments. + * + * This is a C++ wrapper for getopt(3c) and getopt_long(3c). + */ + +class ACE_Export ACE_Get_Opt +{ +public: + /// Mutually exclusive ordering values. + enum + { + /** + * REQUIRE_ORDER means that processing stops and @c EOF is + * returned as soon as a non-option argument is found. @c opt_ind() + * will return the index of the next @a argv element so the program + * can continue processing the rest of the @a argv elements. + */ + REQUIRE_ORDER = 1, + + /** + * PERMUTE_ARGS means the @a argv elements are reordered dynamically + * (permuted) so that all options appear first. When the elements are + * permuted, the order of the options and the following arguments are + * maintained. When the last option has been processed, @c EOF is + * returned and @c opt_ind() returns the index into the next non-option + * element. + */ + PERMUTE_ARGS = 2, + + /** + * RETURN_IN_ORDER means each @a argv element is processed in the + * order is it seen. If the element is not recognized as an option, '1' + * is returned and @c opt_arg() refers to the @a argv element found. + */ + RETURN_IN_ORDER = 3 + }; + + /// Mutually exclusive option argument mode used by long options. + enum OPTION_ARG_MODE + { + /// Doesn't take an argument. + NO_ARG = 0, + + /// Requires an argument, same as passing ":" after a short option + /// character in @a optstring. + ARG_REQUIRED = 1, + + /// Argument is optional, same as passing "::" after a short + /// option character in @a optstring. + ARG_OPTIONAL = 2 + }; + + /** + * Constructor initializes the command line to be parsed. All information + * for parsing must be supplied to this constructor. + * + * @param argc The number of @a argv elements to parse. + * @param argv Command line tokens, such as would be passed + * to @c main(). + * @param optstring Nul-terminated string containing the legitimate + * short option characters. A single colon ":" + * following an option character means the option + * requires an argument. A double colon "::" following + * an option character means the argument is optional. + * The argument is taken from the rest of the current + * @a argv element, or from the following @a argv + * element (only valid for required arguments; + * optional arguments must always reside in the same + * @a argv element). The argument value, if any is + * returned by the @c opt_arg() method. + * @a optstring can be extended by adding long options + * with corresponding short options via the + * @c long_option() method. If the short option + * already appears in @a optstring, the argument + * characteristics must match, otherwise it is added. + * See @c long_option() for more information. + * If 'W', followed by a semi-colon ';' appears in + * @a optstring, then any time a 'W' appears on the + * command line, the following argument is treated as + * a long option. For example, if the command line + * contains "program -W foo", "foo" is treated as a + * long option, that is, as if "program --foo" had + * been passed. + * The following characters can appear in @a optstring + * before any option characters, with the described + * effect: + * - '+' changes the @a ordering to @a REQUIRE_ORDER. + * - '-' changes the @a ordering to @a RETURN_IN_ORDER. + * - ':' changes the return value from @c operator() + * and get_opt() from '?' to ':' when an option + * requires an argument but none is specified. + * + * @param skip_args Optional (default 1). The specified number of + * initial elements in @a argv are skipped before + * parsing begins. Thus, the default prevents + * @a argv[0] (usually the command name) from being + * parsed. @a argc includes all @a argv elements, + * including any skipped elements. + * @param report_errors Optional, if non-zero then parsing errors cause + * an error message to be displayed from the + * @c operator() method before it returns. The + * error message is suppressed if this argument is 0. + * This setting also controls whether or not an error + * message is displayed in @c long_option() encounters + * an error. + * @param ordering Optional (default is @c PERMUTE_ARGS); determines + * how the @a argv elements are processed. This argument + * is overridden by two factors: + * -# The @c POSIXLY_CORRECT environment variable. If + * this environment variable is set, the ordering + * is changed to @c REQUIRE_ORDER. + * -# Leading characters in @a optstring (see above). + * Any leading ordering characters override both + * the @a ordering argument and any effect of the + * @c POSIXLY_CORRECT environment variable. + * @param long_only Optional. If non-zero, then long options can be + * specified using a single '-' on the command line. + * If the token is not a long option, it is processed + * as usual, that is, as a short option or set of + * short options. + * + * Multiple short options can be combined as long as only the last + * one can takes an argument. For example, if @a optstring is defined as + * @c "abc:" or @c "abc::" then the command line @e "program -abcxxx" short + * options @e a, @e b, and @e c are found with @e "xxx" as the argument for + * @e c. + * However, if the command line is specified as @e "program -acb" only + * options @e a and @e c are found with @e "b" as the argument for @e c. + * Also, for options with optional arguments, that is, those followed by + * "::", the argument must be in the same @a argv element, so "program -abc + * xxx" will only find "xxx" as the argument for @e c if @a optstring is + * specified as @c "abc:" not @c "abc::". + */ +#ifndef ACE_USES_WCHAR + ACE_Get_Opt (int argc, + ACE_TCHAR **argv, + const ACE_TCHAR *optstring = ACE_TEXT (""), + int skip_args = 1, + int report_errors = 0, + int ordering = PERMUTE_ARGS, + int long_only = 0); + +#else +private: + void ACE_Get_Opt_Init (const ACE_TCHAR *optstring); +public: + ACE_Get_Opt (int argc, + ACE_TCHAR **argv, + const ACE_TCHAR *optstring = ACE_TEXT (""), + int skip_args = 1, + int report_errors = 0, + int ordering = PERMUTE_ARGS, + int long_only = 0); + ACE_Get_Opt (int argc, + ACE_TCHAR **argv, + const char *optstring, + int skip_args = 1, + int report_errors = 0, + int ordering = PERMUTE_ARGS, + int long_only = 0); +#endif + /// Default dtor. + ~ACE_Get_Opt (void); + + /** + * Scan elements of @a argv (whose length is @a argc) for short option + * characters given in @a optstring or long options (with no short + * option equivalents). + * + * If an element of @a argv starts with '-', and is not exactly "-" + * or "--", then it is a short option element. The characters of this + * element (aside from the initial '-') are option characters. If + * it starts with "--" followed by other characters it is treated as + * a long option. If @c operator() is called repeatedly, it returns + * each of the option characters from each of the option elements. + * + * @return The parsed option character. The following characters have + * special significance. + * @retval 0 A long option was found + * @retval '\?' Either an unknown option character was found, or the + * option is known but requires an argument, none was + * specified, and @a optstring did not contain a leading + * colon. + * @retval ':' A known option character was found but it requires an + * argument and none was supplied, and the first character + * of @a optstring was a colon. @c opt_opt() indicates + * which option was specified. + * @retval '1' @c RETURN_IN_ORDER was specified and a non-option argument + * was found. + * @retval EOF No more option characters were found. @c opt_ind() will + * return the index in @a argv of the first @a argv element + * that is not an option. If @c PERMUTE_ARGS was + * specified, the @a argv elements have been permuted so that + * those that are not options now come last. + * + * @note The standards are unclear with respect to the conditions under + * which '?' and ':' are returned, so we scan the initial characters of + * @a optstring up unto the first short option character for '+', '-', + * and ':' in order to determine ordering and missing argument behavior. + */ + int operator () (void); + + /** + * For communication from @c operator() to the caller. When + * @c operator() finds an option that takes an argument, the argument + * value is returned from this method, otherwise it returns 0. + */ + ACE_TCHAR *opt_arg (void) const; + + /** + * Returns the most recently matched option character. Especially + * useful when operator() returns ':' for an unspecified argument + * that's required, since this allows the caller to learn what option + * was specified without its required argument. + */ + int opt_opt (void); + + /** + * Index in @a argv of the next element to be scanned. This is used + * for communication to and from the caller and for communication + * between successive calls to @c operator(). On entry to + * @c operator(), zero means this is the first call; initialize. + * + * When @c operator() returns @c EOF, this is the index of the first of + * the non-option elements that the caller should itself scan. + * + * Otherwise, @c opt_ind() communicates from one call to the next how + * much of @a argv has been scanned so far. + */ + int &opt_ind (void); + + /// Adds a long option with no corresponding short option. + /** + * If the @a name option is seen, @c operator() returns 0. + * + * @param name The long option to add. + * @param has_arg Defines the argument requirements for + * the new option. + * + * @retval 0 Success + * @retval -1 The long option can not be added. + */ + int long_option (const ACE_TCHAR *name, + OPTION_ARG_MODE has_arg = NO_ARG); + + /// Adds a long option with a corresponding short option. + /** + * @param name The long option to add. + * @param short_option A character, the short option that corresponds + * to @a name. + * @param has_arg Defines the argument requirements for + * the new option. If the short option has already + * been supplied in the @a optstring, @a has_arg + * must match or an error is returned; otherwise, the + * new short option is added to the @a optstring. + * + * @retval 0 Success + * @retval -1 The long option can not be added. + */ + int long_option (const ACE_TCHAR *name, + int short_option, + OPTION_ARG_MODE has_arg = NO_ARG); + + /// Returns the name of the long option found on the last call to + /// @c operator() or 0 if none was found. + const ACE_TCHAR *long_option (void) const; + + /// The number of arguments in the internal @c argv_. + int argc (void) const; + + /// Accessor for the internal @c argv_ pointer. + ACE_TCHAR **argv (void) const; + + /// Accessor for the @c last_option that was processed. This allows + /// applications to know if the found option was a short or long + /// option, and is especially useful in cases where it was invalid + /// and the caller wants to print out the invalid value. + const ACE_TCHAR *last_option (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Return the @a optstring. This is handy to verify that calls to + /// long_option added short options as expected. + const ACE_TCHAR *optstring (void) const; + +public: + /* + * The following five data members should be private, but that + * would break backwards compatibility. However, we recommend not + * writing code that uses these fields directly. + */ + + /// Holds the @a argc count. + /** + * @deprecated This is public for backwards compatibility only. + * It will be made private in a release of ACE past 5.3. Do not + * write code that relies on this member being public; use the + * @c argc() accessor method instead. + */ + int argc_; + + /// Holds the @a argv pointer. + /** + * @deprecated This is public for backwards compatibility only. + * It will be made private in a release of ACE past 5.3. Do not + * write code that relies on this member being public; use the + * @c argv() accessor method instead. + */ + ACE_TCHAR **argv_; + + /// Index in @c argv_ of the next element to be scanned. + /** + * @deprecated This is public for backwards compatibility only. + * It will be made private in a release of ACE past 5.3. Do not + * write code that relies on this member being public; use the + * @c opt_ind() accessor method instead. + */ + int optind; + + /// Callers store zero here to inhibit the error message for + /// unrecognized options. + /** + * @deprecated This is public for backwards compatibility only. + * It will be made private in a release of ACE past 5.3. Do not + * write code that relies on this member being public; use the + * @a report_errors argument to this class's constructor instead. + */ + int opterr; + + /// Points to the option argument when one is found on last call to + /// @c operator(). + /** + * @deprecated This is public for backwards compatibility only. + * It will be made private in a release of ACE past 5.3. Do not + * write code that relies on this member being public; use the + * @c opt_arg() accessor method instead. + */ + ACE_TCHAR *optarg; + +private: + /** + * @class ACE_Get_Opt_Long_Option This class is for internal use + * in the ACE_Get_Opt class, and is inaccessible to users. + */ + class ACE_Get_Opt_Long_Option + { + public: + /// ctor + ACE_Get_Opt_Long_Option (const ACE_TCHAR *name, + int has_arg, + int val = 0); + + /// Dtor. + ~ACE_Get_Opt_Long_Option (void); + + bool operator < (const ACE_Get_Opt_Long_Option &rhs); + + /// Long option name. + const ACE_TCHAR *name_; + + /// Contains value for . + int has_arg_; + + /// Contains a valid short option character or zero if it doesn't + /// have a corresponding short option. It can also contain a + /// non-printable value that cannot be passed to but + /// will be returned by . This is handy for + /// simplifying long option handling, see tests/Get_Opt_Test.cpp + /// for an example of this technique. + int val_; + }; + + /// Updates nextchar_. + int nextchar_i (void); + + /// Handles long options. + int long_option_i (void); + + /// Handles short options. + int short_option_i (void); + + /// If permuting args, this functions manages the nonopt_start_ and + /// nonopt_end_ indexes and makes calls to permute to actually + /// reorder the -elements. + void permute_args (void); + + /// Handles reordering -elements. + int permute (void); + + /// Set last_option. + void last_option (const ACE_TString &s); + + // Disallow copying and assignment. + ACE_Get_Opt (const ACE_Get_Opt &); + ACE_Get_Opt &operator= (const ACE_Get_Opt &); + +private: + + /// Holds the option string. + ACE_TString *optstring_; + + /// Treat all options as long options. + int long_only_; + + /// Keeps track of whether or not a colon was passed in . + /// This is used to determine the return value when required + /// arguments are missing. + int has_colon_; + + /// This is the last option, short or long, that was processed. This + /// is handy to have in cases where the option passed was invalid. + ACE_TString *last_option_; + + /** + * The next char to be scanned in the option-element in which the + * last option character we returned was found. This allows us to + * pick up the scan where we left off * + * If this is zero, or a null string, it means resume the scan + * by advancing to the next -element. + */ + ACE_TCHAR *nextchar_; + + /// Most recently matched short option character. + int optopt_; + + /// Keeps track of ordering mode (default ). + int ordering_; + + /// Index of the first non-option -element found (only valid + /// when permuting). + int nonopt_start_; + + /// Index of the -element following the last non-option element + /// (only valid when permuting). + int nonopt_end_; + + /// Points to the long_option found on last call to . + ACE_Get_Opt_Long_Option *long_option_; + + /// Array of long options. + ACE_Array long_opts_; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Get_Opt.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_GET_OPT_H */ diff --git a/dep/acelite/ace/Get_Opt.inl b/dep/acelite/ace/Get_Opt.inl new file mode 100644 index 00000000000..e307fb5e400 --- /dev/null +++ b/dep/acelite/ace/Get_Opt.inl @@ -0,0 +1,97 @@ +// -*- C++ -*- +// +// $Id: Get_Opt.inl 81840 2008-06-05 13:46:45Z sma $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE bool +ACE_Get_Opt::ACE_Get_Opt_Long_Option::operator < (const ACE_Get_Opt_Long_Option &rhs) +{ + return this->name_ < rhs.name_; +} + +ACE_INLINE int +ACE_Get_Opt::argc (void) const +{ + return this->argc_; +} + +ACE_INLINE ACE_TCHAR ** +ACE_Get_Opt::argv (void) const +{ + return this->argv_; +} + +ACE_INLINE ACE_TCHAR* +ACE_Get_Opt::opt_arg (void) const +{ + return this->optarg; +} + +ACE_INLINE int +ACE_Get_Opt::opt_opt (void) +{ + return this->optopt_; +} + +ACE_INLINE int & +ACE_Get_Opt::opt_ind (void) +{ + return this->optind; +} + +#ifdef ACE_USES_WCHAR +ACE_INLINE ACE_Get_Opt::ACE_Get_Opt (int argc, + ACE_TCHAR **argv, + const ACE_TCHAR *optstring, + int skip_args, + int report_errors, + int ordering, + int long_only) + : argc_ (argc), + argv_ (argv), + optind (skip_args), + opterr (report_errors), + optarg (0), + optstring_ (0), + long_only_ (long_only), + has_colon_ (0), + last_option_ (0), + nextchar_ (0), + optopt_ (0), + ordering_ (ordering), + nonopt_start_ (optind), + nonopt_end_ (optind), + long_option_ (0) +{ + ACE_Get_Opt_Init (optstring); +} + +ACE_INLINE ACE_Get_Opt::ACE_Get_Opt (int argc, + ACE_TCHAR **argv, + const char *optstring, + int skip_args, + int report_errors, + int ordering, + int long_only) + : argc_ (argc), + argv_ (argv), + optind (skip_args), + opterr (report_errors), + optarg (0), + optstring_ (), + long_only_ (long_only), + has_colon_ (0), + last_option_ (0), + nextchar_ (0), + optopt_ (0), + ordering_ (ordering), + nonopt_start_ (optind), + nonopt_end_ (optind), + long_option_ (0) +{ + ACE_Get_Opt_Init (ACE_TEXT_CHAR_TO_TCHAR (optstring)); +} +#endif + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Global_Macros.h b/dep/acelite/ace/Global_Macros.h new file mode 100644 index 00000000000..d1bf6420b05 --- /dev/null +++ b/dep/acelite/ace/Global_Macros.h @@ -0,0 +1,1121 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Global_Macros.h + * + * $Id: Global_Macros.h 82442 2008-07-28 13:11:29Z johnnyw $ + * + * @author Douglas C. Schmidt + * @author Jesper S. M|ller + * @author and a cast of thousands... + * + * This one is split from the famous OS.h + */ +//============================================================================= + +#ifndef ACE_GLOBAL_MACROS_H +#define ACE_GLOBAL_MACROS_H + +#include /**/ "ace/pre.h" + +// Included just keep compilers that see #pragma dierctive first +// happy. +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/config-lite.h" +#include "ace/Assert.h" // For ACE_ASSERT + +// Start Global Macros +# define ACE_BEGIN_DUMP ACE_TEXT ("\n====\n(%P|%t|%x)\n") +# define ACE_END_DUMP ACE_TEXT ("====\n") + +# if defined (ACE_NDEBUG) +# define ACE_DB(X) +# else +# define ACE_DB(X) X +# endif /* ACE_NDEBUG */ + +// ACE_NO_HEAP_CHECK macro can be used to suppress false report of +// memory leaks. It turns off the built-in heap checking until the +// block is left. The old state will then be restored Only used for +// Win32 (in the moment). +# if defined (ACE_WIN32) + +# if defined (_DEBUG) && !defined (ACE_HAS_WINCE) && !defined (__BORLANDC__) +# include /**/ + +// Open versioned namespace, if enabled by the user. +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +class ACE_Export ACE_No_Heap_Check +{ +public: + ACE_No_Heap_Check (void) + : old_state (_CrtSetDbgFlag (_CRTDBG_REPORT_FLAG)) + { _CrtSetDbgFlag (old_state & ~_CRTDBG_ALLOC_MEM_DF);} + ~ACE_No_Heap_Check (void) { _CrtSetDbgFlag (old_state);} +private: + int old_state; +}; + +// Close versioned namespace, if enabled by the user. +ACE_END_VERSIONED_NAMESPACE_DECL + +# define ACE_NO_HEAP_CHECK ACE_No_Heap_Check ____no_heap; +# else /* !_DEBUG */ +# define ACE_NO_HEAP_CHECK +# endif /* _DEBUG */ +# else /* !ACE_WIN32 */ +# define ACE_NO_HEAP_CHECK +# endif /* ACE_WIN32 */ + +// Turn a number into a string. +# define ACE_ITOA(X) #X + +// Create a string of a server address with a "host:port" format. +# define ACE_SERVER_ADDRESS(H,P) H ACE_TEXT(":") P + +// A couple useful inline functions for checking whether bits are +// enabled or disabled. + +// Efficiently returns the least power of two >= X... +# define ACE_POW(X) (((X) == 0)?1:(X-=1,X|=X>>1,X|=X>>2,X|=X>>4,X|=X>>8,X|=X>>16,(++X))) +# define ACE_EVEN(NUM) (((NUM) & 1) == 0) +# define ACE_ODD(NUM) (((NUM) & 1) == 1) +# define ACE_BIT_ENABLED(WORD, BIT) (((WORD) & (BIT)) != 0) +# define ACE_BIT_DISABLED(WORD, BIT) (((WORD) & (BIT)) == 0) +# define ACE_BIT_CMP_MASK(WORD, BIT, MASK) (((WORD) & (BIT)) == MASK) +# define ACE_SET_BITS(WORD, BITS) (WORD |= (BITS)) +# define ACE_CLR_BITS(WORD, BITS) (WORD &= ~(BITS)) + +# if !defined (ACE_ENDLESS_LOOP) +# define ACE_ENDLESS_LOOP +# endif /* ! ACE_ENDLESS_LOOP */ + +# if defined (ACE_NEEDS_FUNC_DEFINITIONS) + // It just evaporated ;-) Not pleasant. +# define ACE_UNIMPLEMENTED_FUNC(f) +# else +# define ACE_UNIMPLEMENTED_FUNC(f) f; +# endif /* ACE_NEEDS_FUNC_DEFINITIONS */ + +#if !defined (ACE_LACKS_DEPRECATED_MACROS) + // Easy way to designate that a class is used as a pseudo-namespace. + // Insures that g++ "friendship" anamolies are properly handled. + # define ACE_CLASS_IS_NAMESPACE(CLASSNAME) \ + private: \ + CLASSNAME (void); \ + CLASSNAME (const CLASSNAME&); \ + friend class ace_dewarn_gplusplus +#endif /* ACE_LACKS_DEPRECATED_MACROS */ + +// ---------------------------------------------------------------- + +//FUZZ: disable check_for_exception_sepc +#if !defined (ACE_LACKS_DEPRECATED_MACROS) + #if defined (ACE_HAS_NO_THROW_SPEC) + # define ACE_THROW_SPEC(X) + #else + # if defined (ACE_HAS_EXCEPTIONS) + # if defined (ACE_WIN32) && defined (_MSC_VER) && \ + (_MSC_VER >= 1400) && (_MSC_VER <= 1500) + # define ACE_THROW_SPEC(X) throw(...) + # else + # define ACE_THROW_SPEC(X) throw X + # endif /* ACE_WIN32 && VC8 */ + # else /* ! ACE_HAS_EXCEPTIONS */ + # define ACE_THROW_SPEC(X) + # endif /* ! ACE_HAS_EXCEPTIONS */ + #endif /*ACE_HAS_NO_THROW_SPEC*/ +#endif /* ACE_LACKS_DEPRECATED_MACROS */ +//FUZZ: enable check_for_exception_sepc + +// ---------------------------------------------------------------- + +#if !defined (ACE_LACKS_DEPRECATED_MACROS) + /** + * This macro is deprecated + */ + #define ACE_NESTED_CLASS(TYPE, NAME) TYPE::NAME +#endif /* ACE_LACKS_DEPRECATED_MACROS */ + +#if !defined (ACE_LACKS_DEPRECATED_MACROS) + /** + * @name CORBA namespace macros. + * + * CORBA namespace macros. + * + * @deprecated These macros were formerly used by TAO but are now + * deprecated, and only remain to retain some backward + * compatibility. They will be removed in a future ACE + * release. + */ + //@{ + #define ACE_CORBA_1(NAME) CORBA::NAME + #define ACE_CORBA_2(TYPE, NAME) CORBA::TYPE::NAME + #define ACE_CORBA_3(TYPE, NAME) CORBA::TYPE::NAME + //@} +#endif /* ACE_LACKS_DEPRECATED_MACROS */ + +// ---------------------------------------------------------------- + +// Convenient macro for testing for deadlock, as well as for detecting +// when mutexes fail. +#define ACE_GUARD_ACTION(MUTEX, OBJ, LOCK, ACTION, REACTION) \ + ACE_Guard< MUTEX > OBJ (LOCK); \ + if (OBJ.locked () != 0) { ACTION; } \ + else { REACTION; } +#define ACE_GUARD_REACTION(MUTEX, OBJ, LOCK, REACTION) \ + ACE_GUARD_ACTION(MUTEX, OBJ, LOCK, ;, REACTION) +#define ACE_GUARD(MUTEX, OBJ, LOCK) \ + ACE_GUARD_REACTION(MUTEX, OBJ, LOCK, return) +#define ACE_GUARD_RETURN(MUTEX, OBJ, LOCK, RETURN) \ + ACE_GUARD_REACTION(MUTEX, OBJ, LOCK, return RETURN) +# define ACE_WRITE_GUARD(MUTEX,OBJ,LOCK) \ + ACE_Write_Guard< MUTEX > OBJ (LOCK); \ + if (OBJ.locked () == 0) return; +# define ACE_WRITE_GUARD_RETURN(MUTEX,OBJ,LOCK,RETURN) \ + ACE_Write_Guard< MUTEX > OBJ (LOCK); \ + if (OBJ.locked () == 0) return RETURN; +# define ACE_READ_GUARD(MUTEX,OBJ,LOCK) \ + ACE_Read_Guard< MUTEX > OBJ (LOCK); \ + if (OBJ.locked () == 0) return; +# define ACE_READ_GUARD_RETURN(MUTEX,OBJ,LOCK,RETURN) \ + ACE_Read_Guard< MUTEX > OBJ (LOCK); \ + if (OBJ.locked () == 0) return RETURN; + +// ---------------------------------------------------------------- + +# define ACE_DES_NOFREE(POINTER,CLASS) \ + do { \ + if (POINTER) \ + { \ + (POINTER)->~CLASS (); \ + } \ + } \ + while (0) + +# define ACE_DES_ARRAY_NOFREE(POINTER,SIZE,CLASS) \ + do { \ + if (POINTER) \ + { \ + for (size_t i = 0; \ + i < SIZE; \ + ++i) \ + { \ + (&(POINTER)[i])->~CLASS (); \ + } \ + } \ + } \ + while (0) + +# define ACE_DES_FREE(POINTER,DEALLOCATOR,CLASS) \ + do { \ + if (POINTER) \ + { \ + (POINTER)->~CLASS (); \ + DEALLOCATOR (POINTER); \ + } \ + } \ + while (0) + +# define ACE_DES_ARRAY_FREE(POINTER,SIZE,DEALLOCATOR,CLASS) \ + do { \ + if (POINTER) \ + { \ + for (size_t i = 0; \ + i < SIZE; \ + ++i) \ + { \ + (&(POINTER)[i])->~CLASS (); \ + } \ + DEALLOCATOR (POINTER); \ + } \ + } \ + while (0) + +# if defined (ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR) +# define ACE_DES_NOFREE_TEMPLATE(POINTER,T_CLASS,T_PARAMETER) \ + do { \ + if (POINTER) \ + { \ + (POINTER)->~T_CLASS (); \ + } \ + } \ + while (0) +# define ACE_DES_ARRAY_NOFREE_TEMPLATE(POINTER,SIZE,T_CLASS,T_PARAMETER) \ + do { \ + if (POINTER) \ + { \ + for (size_t i = 0; \ + i < SIZE; \ + ++i) \ + { \ + (&(POINTER)[i])->~T_CLASS (); \ + } \ + } \ + } \ + while (0) + +#if defined (ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS) +# define ACE_DES_FREE_TEMPLATE(POINTER,DEALLOCATOR,T_CLASS,T_PARAMETER) \ + do { \ + if (POINTER) \ + { \ + (POINTER)->~T_CLASS T_PARAMETER (); \ + DEALLOCATOR (POINTER); \ + } \ + } \ + while (0) +#else +# define ACE_DES_FREE_TEMPLATE(POINTER,DEALLOCATOR,T_CLASS,T_PARAMETER) \ + do { \ + if (POINTER) \ + { \ + (POINTER)->~T_CLASS (); \ + DEALLOCATOR (POINTER); \ + } \ + } \ + while (0) +#endif /* defined(ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS) */ +# define ACE_DES_ARRAY_FREE_TEMPLATE(POINTER,SIZE,DEALLOCATOR,T_CLASS,T_PARAMETER) \ + do { \ + if (POINTER) \ + { \ + for (size_t i = 0; \ + i < SIZE; \ + ++i) \ + { \ + (&(POINTER)[i])->~T_CLASS (); \ + } \ + DEALLOCATOR (POINTER); \ + } \ + } \ + while (0) +#if defined(ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS) +# define ACE_DES_FREE_TEMPLATE2(POINTER,DEALLOCATOR,T_CLASS,T_PARAM1,T_PARAM2) \ + do { \ + if (POINTER) \ + { \ + (POINTER)->~T_CLASS (); \ + DEALLOCATOR (POINTER); \ + } \ + } \ + while (0) +#else +# define ACE_DES_FREE_TEMPLATE2(POINTER,DEALLOCATOR,T_CLASS,T_PARAM1,T_PARAM2) \ + do { \ + if (POINTER) \ + { \ + (POINTER)->~T_CLASS (); \ + DEALLOCATOR (POINTER); \ + } \ + } \ + while (0) +#endif /* defined(ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS) */ +#if defined(ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS) +# define ACE_DES_FREE_TEMPLATE3(POINTER,DEALLOCATOR,T_CLASS,T_PARAM1,T_PARAM2,T_PARAM3) \ + do { \ + if (POINTER) \ + { \ + (POINTER)->~T_CLASS (); \ + DEALLOCATOR (POINTER); \ + } \ + } \ + while (0) +#else +# define ACE_DES_FREE_TEMPLATE3(POINTER,DEALLOCATOR,T_CLASS,T_PARAM1,T_PARAM2,T_PARAM3) \ + do { \ + if (POINTER) \ + { \ + (POINTER)->~T_CLASS (); \ + DEALLOCATOR (POINTER); \ + } \ + } \ + while (0) +#endif /* defined(ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS) */ +#if defined(ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS) +# define ACE_DES_FREE_TEMPLATE4(POINTER,DEALLOCATOR,T_CLASS,T_PARAM1,T_PARAM2,T_PARAM3, T_PARAM4) \ + do { \ + if (POINTER) \ + { \ + (POINTER)->~T_CLASS (); \ + DEALLOCATOR (POINTER); \ + } \ + } \ + while (0) +#else +# define ACE_DES_FREE_TEMPLATE4(POINTER,DEALLOCATOR,T_CLASS,T_PARAM1,T_PARAM2,T_PARAM3, T_PARAM4) \ + do { \ + if (POINTER) \ + { \ + (POINTER)->~T_CLASS (); \ + DEALLOCATOR (POINTER); \ + } \ + } \ + while (0) +#endif /* defined(ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS) */ +# define ACE_DES_ARRAY_FREE_TEMPLATE2(POINTER,SIZE,DEALLOCATOR,T_CLASS,T_PARAM1,T_PARAM2) \ + do { \ + if (POINTER) \ + { \ + for (size_t i = 0; \ + i < SIZE; \ + ++i) \ + { \ + (&(POINTER)[i])->~T_CLASS (); \ + } \ + DEALLOCATOR (POINTER); \ + } \ + } \ + while (0) +# else /* ! ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR */ +# define ACE_DES_NOFREE_TEMPLATE(POINTER,T_CLASS,T_PARAMETER) \ + do { \ + if (POINTER) \ + { \ + (POINTER)->T_CLASS T_PARAMETER::~T_CLASS (); \ + } \ + } \ + while (0) +# define ACE_DES_ARRAY_NOFREE_TEMPLATE(POINTER,SIZE,T_CLASS,T_PARAMETER) \ + do { \ + if (POINTER) \ + { \ + for (size_t i = 0; \ + i < SIZE; \ + ++i) \ + { \ + (POINTER)[i].T_CLASS T_PARAMETER::~T_CLASS (); \ + } \ + } \ + } \ + while (0) +# define ACE_DES_FREE_TEMPLATE(POINTER,DEALLOCATOR,T_CLASS,T_PARAMETER) \ + do { \ + if (POINTER) \ + { \ + POINTER->T_CLASS T_PARAMETER::~T_CLASS (); \ + DEALLOCATOR (POINTER); \ + } \ + } \ + while (0) +# define ACE_DES_ARRAY_FREE_TEMPLATE(POINTER,SIZE,DEALLOCATOR,T_CLASS,T_PARAMETER) \ + do { \ + if (POINTER) \ + { \ + for (size_t i = 0; \ + i < SIZE; \ + ++i) \ + { \ + POINTER[i].T_CLASS T_PARAMETER::~T_CLASS (); \ + } \ + DEALLOCATOR (POINTER); \ + } \ + } \ + while (0) +# define ACE_DES_FREE_TEMPLATE2(POINTER,DEALLOCATOR,T_CLASS,T_PARAM1,T_PARAM2) \ + do { \ + if (POINTER) \ + { \ + POINTER->T_CLASS ::~T_CLASS (); \ + DEALLOCATOR (POINTER); \ + } \ + } \ + while (0) +# define ACE_DES_FREE_TEMPLATE3(POINTER,DEALLOCATOR,T_CLASS,T_PARAM1,T_PARAM2,T_PARAM3) \ + do { \ + if (POINTER) \ + { \ + POINTER->T_CLASS ::~T_CLASS (); \ + DEALLOCATOR (POINTER); \ + } \ + } \ + while (0) +# define ACE_DES_FREE_TEMPLATE4(POINTER,DEALLOCATOR,T_CLASS,T_PARAM1,T_PARAM2,T_PARAM3,T_PARAM4) \ + do { \ + if (POINTER) \ + { \ + POINTER->T_CLASS ::~T_CLASS (); \ + DEALLOCATOR (POINTER); \ + } \ + } \ + while (0) +# define ACE_DES_ARRAY_FREE_TEMPLATE2(POINTER,SIZE,DEALLOCATOR,T_CLASS,T_PARAM1,T_PARAM2) \ + do { \ + if (POINTER) \ + { \ + for (size_t i = 0; \ + i < SIZE; \ + ++i) \ + { \ + POINTER[i].T_CLASS ::~T_CLASS (); \ + } \ + DEALLOCATOR (POINTER); \ + } \ + } \ + while (0) +# endif /* defined ! ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR */ + + +/*******************************************************************/ + +/// Service Objects, i.e., objects dynamically loaded via the service +/// configurator, must provide a destructor function with the +/// following prototype to perform object cleanup. +typedef void (*ACE_Service_Object_Exterminator)(void *); + +/** @name Service Configurator macros + * + * The following macros are used to define helper objects used in + * ACE's Service Configurator framework, which is described in + * Chapter 5 of C++NPv2 . This + * framework implements the Component Configurator pattern, which is + * described in Chapter 2 of POSA2 . + * The intent of this pattern is to allow developers to dynamically + * load and configure services into a system. With a little help from + * this macros statically linked services can also be dynamically + * configured. + * + * More details about this component are available in the documentation + * of the ACE_Service_Configurator class and also + * ACE_Dynamic_Service. + * + * Notice that in all the macros the SERVICE_CLASS parameter must be + * the name of a class derived from ACE_Service_Object. + */ +//@{ +/// Declare a the data structure required to register a statically +/// linked service into the service configurator. +/** + * The macro should be used in the header file where the service is + * declared, its only argument is usually the name of the class that + * implements the service. + * + * @param SERVICE_CLASS The name of the class implementing the + * service. + */ +# define ACE_STATIC_SVC_DECLARE(SERVICE_CLASS) \ +extern ACE_Static_Svc_Descriptor ace_svc_desc_##SERVICE_CLASS ; + +/// As ACE_STATIC_SVC_DECLARE, but using an export macro for NT +/// compilers. +/** + * NT compilers require the use of explicit directives to export and + * import symbols from a DLL. If you need to define a service in a + * dynamic library you should use this version instead. + * Normally ACE uses a macro to inject the correct export/import + * directives on NT. Naturally it also the macro expands to a blank + * on platforms that do not require such directives. + * The first argument (EXPORT_NAME) is the prefix for this export + * macro, the full name is formed by appending _Export. + * ACE provides tools to generate header files that define the macro + * correctly on all platforms, please see + * $ACE_ROOT/bin/generate_export_file.pl + * + * @param EXPORT_NAME The export macro name prefix. + * @param SERVICE_CLASS The name of the class implementing the service. + */ +#define ACE_STATIC_SVC_DECLARE_EXPORT(EXPORT_NAME,SERVICE_CLASS) \ +extern EXPORT_NAME##_Export ACE_Static_Svc_Descriptor ace_svc_desc_##SERVICE_CLASS; + +/// Define the data structure used to register a statically linked +/// service into the Service Configurator. +/** + * The service configurator requires several arguments to build and + * control an statically linked service, including its name, the + * factory function used to construct the service, and some flags. + * All those parameters are configured in a single structure, an + * instance of this structure is statically initialized using the + * following macro. + * + * @param SERVICE_CLASS The name of the class that implements the + * service, must be derived (directly or indirectly) from + * ACE_Service_Object. + * @param NAME The name for this service, this name is used by the + * service configurator to match configuration options provided in + * the svc.conf file. + * @param TYPE The type of object. Objects can be streams or service + * objects. Please read the ACE_Service_Configurator and ASX + * documentation for more details. + * @param FN The name of the factory function, usually the + * ACE_SVC_NAME macro can be used to generate the name. The + * factory function is often defined using ACE_FACTORY_DECLARE and + * ACE_FACTORY_DEFINE. + * @param FLAGS Flags to control the ownership and lifecycle of the + * object. Please read the ACE_Service_Configurator documentation + * for more details. + * @param ACTIVE If not zero then a thread will be dedicate to the + * service. Please read the ACE_Service_Configurator documentation + * for more details. + */ +# define ACE_STATIC_SVC_DEFINE(SERVICE_CLASS, NAME, TYPE, FN, FLAGS, ACTIVE) \ +ACE_Static_Svc_Descriptor ace_svc_desc_##SERVICE_CLASS = { NAME, TYPE, FN, FLAGS, ACTIVE }; + +/// Automatically register a service with the service configurator +/** + * In some applications the services must be automatically registered + * with the service configurator, before main() starts. + * The ACE_STATIC_SVC_REQUIRE macro defines a class whose constructor + * register the service, it also defines a static instance of that + * class to ensure that the service is registered before main. + * + * On platforms that lack adequate support for static C++ objects the + * macro ACE_STATIC_SVC_REGISTER can be used to explicitly register + * the service. + * + * @todo One class per-Service_Object seems wasteful. It should be + * possible to define a single class and re-use it for all the + * service objects, just by passing the Service_Descriptor as an + * argument to the constructor. + */ +#if defined(ACE_LACKS_STATIC_CONSTRUCTORS) +# define ACE_STATIC_SVC_REQUIRE(SERVICE_CLASS)\ +class ACE_Static_Svc_##SERVICE_CLASS {\ +public:\ + ACE_Static_Svc_##SERVICE_CLASS() { \ + ACE_Service_Config::insert (\ + &ace_svc_desc_##SERVICE_CLASS); \ + } \ +}; +#define ACE_STATIC_SVC_REGISTER(SERVICE_CLASS)\ +ACE_Static_Svc_##SERVICE_CLASS ace_static_svc_##SERVICE_CLASS + +#else /* !ACE_LACKS_STATIC_CONSTRUCTORS */ + +# define ACE_STATIC_SVC_REQUIRE(SERVICE_CLASS)\ +class ACE_Static_Svc_##SERVICE_CLASS {\ +public:\ + ACE_Static_Svc_##SERVICE_CLASS() { \ + ACE_Service_Config::insert (\ + &ace_svc_desc_##SERVICE_CLASS); \ + } \ +};\ +static ACE_Static_Svc_##SERVICE_CLASS ace_static_svc_##SERVICE_CLASS; +#define ACE_STATIC_SVC_REGISTER(SERVICE_CLASS) do {} while (0) + +#endif /* !ACE_LACKS_STATIC_CONSTRUCTORS */ + +// Preprocessor symbols will not be expanded if they are +// concatenated. Force the preprocessor to expand them during the +// argument prescan by calling a macro that itself calls another that +// performs the actual concatenation. +#define ACE_PREPROC_CONCATENATE_IMPL(A,B) A ## B +#define ACE_PREPROC_CONCATENATE(A,B) ACE_PREPROC_CONCATENATE_IMPL(A,B) + +#if defined (ACE_HAS_VERSIONED_NAMESPACE) && ACE_HAS_VERSIONED_NAMESPACE == 1 +// Preprocessor symbols will not be expanded if they are +// concatenated. Force the preprocessor to expand them during the +// argument prescan by calling a macro that itself calls another that +// performs the actual concatenation. +# define ACE_MAKE_SVC_CONFIG_FUNCTION_NAME(PREFIX,VERSIONED_NAMESPACE,SERVICE_CLASS) PREFIX ## _ ## VERSIONED_NAMESPACE ## _ ## SERVICE_CLASS +#else +# define ACE_MAKE_SVC_CONFIG_FUNCTION_NAME(PREFIX,VERSIONED_NAMESPACE,SERVICE_CLASS) PREFIX ## _ ## SERVICE_CLASS +#endif /* ACE_HAS_VERSIONED_NAMESPACE == 1 */ + +#define ACE_MAKE_SVC_CONFIG_FACTORY_NAME(VERSIONED_NAMESPACE,SERVICE_CLASS) ACE_MAKE_SVC_CONFIG_FUNCTION_NAME(_make,VERSIONED_NAMESPACE,SERVICE_CLASS) +#define ACE_MAKE_SVC_CONFIG_GOBBLER_NAME(VERSIONED_NAMESPACE,SERVICE_CLASS) ACE_MAKE_SVC_CONFIG_FUNCTION_NAME(_gobble,VERSIONED_NAMESPACE,SERVICE_CLASS) + + +/// Declare the factory method used to create dynamically loadable +/// services. +/** + * Once the service implementation is dynamically loaded the Service + * Configurator uses a factory method to create the object. + * This macro declares such a factory function with the proper + * interface and export macros. + * Normally used in the header file that declares the service + * implementation. + * + * @param CLS must match the prefix of the export macro used for this + * service. + * @param SERVICE_CLASS must match the name of the class that + * implements the service. + * + */ +# define ACE_FACTORY_DECLARE(CLS,SERVICE_CLASS) \ +extern "C" CLS##_Export ACE_VERSIONED_NAMESPACE_NAME::ACE_Service_Object * \ +ACE_MAKE_SVC_CONFIG_FACTORY_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS) (ACE_Service_Object_Exterminator *); + +/// Define the factory method (and destructor) for a dynamically +/// loadable service. +/** + * Use with arguments matching ACE_FACTORY_DECLARE. + * Normally used in the .cpp file that defines the service + * implementation. + * + * This macro defines both the factory method and the function used to + * cleanup the service object. + * + * If this macro is used to define a factory function that need not be + * exported (for example, in a static service situation), CLS can be + * specified as ACE_Local_Service. + */ +# define ACE_Local_Service_Export + +#if defined (ACE_OPENVMS) +# define ACE_PREPROC_STRINGIFY(A) #A +# define ACE_MAKE_SVC_REGISTRAR_ARG(A) ACE_PREPROC_STRINGIFY(A), (void*)&A +# define ACE_FACTORY_DEFINE(CLS,SERVICE_CLASS) \ +void ACE_MAKE_SVC_CONFIG_GOBBLER_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS) (void *p) { \ + ACE_VERSIONED_NAMESPACE_NAME::ACE_Service_Object * _p = \ + static_cast< ACE_VERSIONED_NAMESPACE_NAME::ACE_Service_Object *> (p); \ + ACE_ASSERT (_p != 0); \ + delete _p; } \ +extern "C" CLS##_Export ACE_VERSIONED_NAMESPACE_NAME::ACE_Service_Object *\ +ACE_MAKE_SVC_CONFIG_FACTORY_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS) (ACE_Service_Object_Exterminator *gobbler) \ +{ \ + ACE_TRACE (#SERVICE_CLASS); \ + if (gobbler != 0) \ + *gobbler = (ACE_Service_Object_Exterminator) ACE_MAKE_SVC_CONFIG_GOBBLER_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS); \ + return new SERVICE_CLASS; \ +} \ +ACE_Dynamic_Svc_Registrar ace_svc_reg_##SERVICE_CLASS \ + (ACE_MAKE_SVC_REGISTRAR_ARG(ACE_MAKE_SVC_CONFIG_FACTORY_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS))); +#else +# define ACE_FACTORY_DEFINE(CLS,SERVICE_CLASS) \ +void ACE_MAKE_SVC_CONFIG_GOBBLER_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS) (void *p) { \ + ACE_VERSIONED_NAMESPACE_NAME::ACE_Service_Object * _p = \ + static_cast< ACE_VERSIONED_NAMESPACE_NAME::ACE_Service_Object *> (p); \ + ACE_ASSERT (_p != 0); \ + delete _p; } \ +extern "C" CLS##_Export ACE_VERSIONED_NAMESPACE_NAME::ACE_Service_Object *\ +ACE_MAKE_SVC_CONFIG_FACTORY_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS) (ACE_Service_Object_Exterminator *gobbler) \ +{ \ + ACE_TRACE (#SERVICE_CLASS); \ + if (gobbler != 0) \ + *gobbler = (ACE_Service_Object_Exterminator) ACE_MAKE_SVC_CONFIG_GOBBLER_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS); \ + return new SERVICE_CLASS; \ +} +#endif + +/** + * For service classes scoped within namespaces, use this macro in + * place of ACE_FACTORY_DEFINE. The third argument in this case is + * the fully scoped name of the class as it is to be + * instantiated. For example, given: + * namespace ACE + * { + * namespace Foo + * { + * class Bar : public ACE_Service_Object + * {}; + * }; + * }; + * + * ACE_FACTORY_DECLARE(ACE,ACE_Foo_Bar) + * + * you would then use: + * + * ACE_FACTORY_NAMESPACE_DEFINE(ACE,ACE_Foo_Bar,ACE::Foo::Bar) + * + * Note that in this example, the ACE_FACTORY_DECLARE is done outside + * the namespace scope. Then, the SERVICE_CLASS name is the same as + * the fully scoped class name, but with '::' replaced with '_'. Doing + * this will ensure unique generated signatures for the various C + * style functions. + */ +#if defined (ACE_OPENVMS) +# define ACE_PREPROC_STRINGIFY(A) #A +# define ACE_MAKE_SVC_REGISTRAR_ARG(A) ACE_PREPROC_STRINGIFY(A), (void*)&A +# define ACE_FACTORY_NAMESPACE_DEFINE(CLS,SERVICE_CLASS,NAMESPACE_CLASS) \ +void ACE_MAKE_SVC_CONFIG_GOBBLER_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS) (void *p) { \ + ACE_VERSIONED_NAMESPACE_NAME::ACE_Service_Object * _p = \ + static_cast< ACE_VERSIONED_NAMESPACE_NAME::ACE_Service_Object *> (p); \ + ACE_ASSERT (_p != 0); \ + delete _p; } \ +extern "C" CLS##_Export ACE_VERSIONED_NAMESPACE_NAME::ACE_Service_Object *\ +ACE_MAKE_SVC_CONFIG_FACTORY_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS) (ACE_Service_Object_Exterminator *gobbler) \ +{ \ + ACE_TRACE (#SERVICE_CLASS); \ + if (gobbler != 0) \ + *gobbler = (ACE_Service_Object_Exterminator) ACE_MAKE_SVC_CONFIG_GOBBLER_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS); \ + return new NAMESPACE_CLASS; \ +} \ +ACE_Dynamic_Svc_Registrar ace_svc_reg_##SERVICE_CLASS \ + (ACE_MAKE_SVC_REGISTRAR_ARG(ACE_MAKE_SVC_CONFIG_FACTORY_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS))); +#else +# define ACE_FACTORY_NAMESPACE_DEFINE(CLS,SERVICE_CLASS,NAMESPACE_CLASS) \ +void ACE_MAKE_SVC_CONFIG_GOBBLER_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS) (void *p) { \ + ACE_VERSIONED_NAMESPACE_NAME::ACE_Service_Object * _p = \ + static_cast< ACE_VERSIONED_NAMESPACE_NAME::ACE_Service_Object *> (p); \ + ACE_ASSERT (_p != 0); \ + delete _p; } \ +extern "C" CLS##_Export ACE_VERSIONED_NAMESPACE_NAME::ACE_Service_Object *\ +ACE_MAKE_SVC_CONFIG_FACTORY_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS) (ACE_Service_Object_Exterminator *gobbler) \ +{ \ + ACE_TRACE (#SERVICE_CLASS); \ + if (gobbler != 0) \ + *gobbler = (ACE_Service_Object_Exterminator) ACE_MAKE_SVC_CONFIG_GOBBLER_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS); \ + return new NAMESPACE_CLASS; \ +} +#endif + +/// The canonical name for a service factory method +# define ACE_SVC_NAME(SERVICE_CLASS) ACE_MAKE_SVC_CONFIG_FACTORY_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS) + +/// The canonical way to invoke (i.e. construct) a service factory +/// method. +#define ACE_SVC_INVOKE(SERVICE_CLASS) ACE_SVC_NAME(SERVICE_CLASS) (0) + +//@} + +/** @name Helper macros for services defined in the netsvcs library. + * + * The ACE services defined in netsvcs use this helper macros for + * simplicity. + * + */ +//@{ +# define ACE_SVC_FACTORY_DECLARE(X) ACE_FACTORY_DECLARE (ACE_Svc, X) +# define ACE_SVC_FACTORY_DEFINE(X) ACE_FACTORY_DEFINE (ACE_Svc, X) +//@} + +#if defined (ACE_WIN32) +// These are used in SPIPE_Acceptor/Connector, but are ignored at runtime. +# if defined (ACE_HAS_WINCE) +# if !defined (PIPE_TYPE_MESSAGE) +# define PIPE_TYPE_MESSAGE 0 +# endif +# if !defined (PIPE_READMODE_MESSAGE) +# define PIPE_READMODE_MESSAGE 0 +# endif +# if !defined (PIPE_WAIT) +# define PIPE_WAIT 0 +# endif +# endif /* ACE_HAS_WINCE */ +#else /* !ACE_WIN32 */ +// Add some typedefs and macros to enhance Win32 conformance... +# if !defined (LPSECURITY_ATTRIBUTES) +# define LPSECURITY_ATTRIBUTES int +# endif /* !defined LPSECURITY_ATTRIBUTES */ +# if !defined (GENERIC_READ) +# define GENERIC_READ 0 +# endif /* !defined GENERIC_READ */ +# if !defined (FILE_SHARE_READ) +# define FILE_SHARE_READ 0 +# endif /* !defined FILE_SHARE_READ */ +# if !defined (OPEN_EXISTING) +# define OPEN_EXISTING 0 +# endif /* !defined OPEN_EXISTING */ +# if !defined (FILE_ATTRIBUTE_NORMAL) +# define FILE_ATTRIBUTE_NORMAL 0 +# endif /* !defined FILE_ATTRIBUTE_NORMAL */ +# if !defined (MAXIMUM_WAIT_OBJECTS) +# define MAXIMUM_WAIT_OBJECTS 0 +# endif /* !defined MAXIMUM_WAIT_OBJECTS */ +# if !defined (FILE_FLAG_OVERLAPPED) +# define FILE_FLAG_OVERLAPPED 0 +# endif /* !defined FILE_FLAG_OVERLAPPED */ +# if !defined (FILE_FLAG_SEQUENTIAL_SCAN) +# define FILE_FLAG_SEQUENTIAL_SCAN 0 +# endif /* FILE_FLAG_SEQUENTIAL_SCAN */ +# if !defined(FILE_FLAG_WRITE_THROUGH) +# define FILE_FLAG_WRITE_THROUGH 0 +# endif /* !defined FILE_FLAG_WRITE_THROUGH */ +# if !defined(PIPE_WAIT) +# define PIPE_WAIT 0 +# endif /* !defined PIPE_WAIT */ +# if !defined(PIPE_NOWAIT) +# define PIPE_NOWAIT 0 +# endif /* !defined PIPE_WAIT */ +# if !defined(PIPE_READMODE_BYTE) +# define PIPE_READMODE_BYTE 0 +# endif /* !defined PIPE_READMODE_BYTE */ +# if !defined(PIPE_READMODE_MESSAGE) +# define PIPE_READMODE_MESSAGE 0 +# endif /* !defined PIPE_READMODE_MESSAGE */ +# if !defined(PIPE_TYPE_BYTE) +# define PIPE_TYPE_BYTE 0 +# endif /* !defined PIPE_TYPE_BYTE */ +# if !defined(PIPE_TYPE_MESSAGE) +# define PIPE_TYPE_MESSAGE 0 +# endif /* !defined PIPE_TYPE_MESSAGE */ +#endif /* ACE_WIN32 */ + + +// Some useful abstrations for expressions involving +// ACE_Allocator.malloc (). The difference between ACE_NEW_MALLOC* +// with ACE_ALLOCATOR* is that they call constructors also. + +#include "ace/OS_Errno.h" /* Need errno and ENOMEM */ + +# define ACE_ALLOCATOR_RETURN(POINTER,ALLOCATOR,RET_VAL) \ + do { POINTER = ALLOCATOR; \ + if (POINTER == 0) { errno = ENOMEM; return RET_VAL; } \ + } while (0) +# define ACE_ALLOCATOR(POINTER,ALLOCATOR) \ + do { POINTER = ALLOCATOR; \ + if (POINTER == 0) { errno = ENOMEM; return; } \ + } while (0) +# define ACE_ALLOCATOR_NORETURN(POINTER,ALLOCATOR) \ + do { POINTER = ALLOCATOR; \ + if (POINTER == 0) { errno = ENOMEM; } \ + } while (0) + +# define ACE_NEW_MALLOC_RETURN(POINTER,ALLOCATOR,CONSTRUCTOR,RET_VAL) \ + do { POINTER = ALLOCATOR; \ + if (POINTER == 0) { errno = ENOMEM; return RET_VAL;} \ + else { (void) new (POINTER) CONSTRUCTOR; } \ + } while (0) +# define ACE_NEW_MALLOC(POINTER,ALLOCATOR,CONSTRUCTOR) \ + do { POINTER = ALLOCATOR; \ + if (POINTER == 0) { errno = ENOMEM; return;} \ + else { (void) new (POINTER) CONSTRUCTOR; } \ + } while (0) +# define ACE_NEW_MALLOC_NORETURN(POINTER,ALLOCATOR,CONSTRUCTOR) \ + do { POINTER = ALLOCATOR; \ + if (POINTER == 0) { errno = ENOMEM;} \ + else { (void) new (POINTER) CONSTRUCTOR; } \ + } while (0) + +/* ACE_Metrics */ +#if defined ACE_LACKS_ARRAY_PLACEMENT_NEW +# define ACE_NEW_MALLOC_ARRAY_RETURN(POINTER,ALLOCATOR,CONSTRUCTOR,COUNT,RET_VAL) \ + do { POINTER = ALLOCATOR; \ + if (POINTER == 0) { errno = ENOMEM; return RET_VAL;} \ + else { for (u_int i = 0; i < COUNT; ++i) \ + {(void) new (POINTER) CONSTRUCTOR; ++POINTER;} \ + POINTER -= COUNT;} \ + } while (0) +# define ACE_NEW_MALLOC_ARRAY(POINTER,ALLOCATOR,CONSTRUCTOR,COUNT) \ + do { POINTER = ALLOCATOR; \ + if (POINTER == 0) { errno = ENOMEM; return;} \ + else { for (u_int i = 0; i < COUNT; ++i) \ + {(void) new (POINTER) CONSTRUCTOR; ++POINTER;} \ + POINTER -= COUNT;} \ + } while (0) +#else /* ! defined ACE_LACKS_ARRAY_PLACEMENT_NEW */ +# define ACE_NEW_MALLOC_ARRAY_RETURN(POINTER,ALLOCATOR,CONSTRUCTOR,COUNT,RET_VAL) \ + do { POINTER = ALLOCATOR; \ + if (POINTER == 0) { errno = ENOMEM; return RET_VAL;} \ + else { (void) new (POINTER) CONSTRUCTOR [COUNT]; } \ + } while (0) +# define ACE_NEW_MALLOC_ARRAY(POINTER,ALLOCATOR,CONSTRUCTOR,COUNT) \ + do { POINTER = ALLOCATOR; \ + if (POINTER == 0) { errno = ENOMEM; return;} \ + else { (void) new (POINTER) CONSTRUCTOR [COUNT]; } \ + } while (0) +#endif /* defined ACE_LACKS_ARRAY_PLACEMENT_NEW */ + +// This is being placed here temporarily to help stablelize the builds, but will +// be moved out along with the above macros as part of the subsetting. dhinton +#if !defined (ACE_LACKS_NEW_H) +# if defined (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB) +# include /**/ +# else +# include /**/ +# endif /* ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB */ +#endif /* ! ACE_LACKS_NEW_H */ + +# define ACE_NOOP(x) + +#if defined (ACE_WIN32) && defined (ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS) +# define ACE_SEH_TRY __try +# define ACE_SEH_EXCEPT(X) __except(X) +# define ACE_SEH_FINALLY __finally +#else /* !ACE_WIN32 */ +# define ACE_SEH_TRY if (1) +# define ACE_SEH_EXCEPT(X) while (0) +# define ACE_SEH_FINALLY if (1) +#endif /* ACE_WIN32 */ + +// These should probably be put into a seperate header. + +// The following is necessary since many C++ compilers don't support +// typedef'd types inside of classes used as formal template +// arguments... ;-(. Luckily, using the C++ preprocessor I can hide +// most of this nastiness! + +# if defined (ACE_HAS_TEMPLATE_TYPEDEFS) + +// Handle ACE_Message_Queue. +# define ACE_SYNCH_DECL class _ACE_SYNCH +# define ACE_SYNCH_USE _ACE_SYNCH +# define ACE_SYNCH_MUTEX_T typename _ACE_SYNCH::MUTEX +# define ACE_SYNCH_CONDITION_T typename _ACE_SYNCH::CONDITION +# define ACE_SYNCH_SEMAPHORE_T typename _ACE_SYNCH::SEMAPHORE + +// Handle ACE_Malloc* +# define ACE_MEM_POOL_1 class _ACE_MEM_POOL +# define ACE_MEM_POOL_2 _ACE_MEM_POOL +# define ACE_MEM_POOL _ACE_MEM_POOL +# define ACE_MEM_POOL_OPTIONS typename _ACE_MEM_POOL::OPTIONS + +// Handle ACE_Svc_Handler +# define ACE_PEER_STREAM_1 class _ACE_PEER_STREAM +# define ACE_PEER_STREAM_2 _ACE_PEER_STREAM +# define ACE_PEER_STREAM _ACE_PEER_STREAM +# define ACE_PEER_STREAM_ADDR typename _ACE_PEER_STREAM::PEER_ADDR + +// Handle ACE_Acceptor +# define ACE_PEER_ACCEPTOR_1 class _ACE_PEER_ACCEPTOR +# define ACE_PEER_ACCEPTOR_2 _ACE_PEER_ACCEPTOR +# define ACE_PEER_ACCEPTOR _ACE_PEER_ACCEPTOR +# define ACE_PEER_ACCEPTOR_ADDR typename _ACE_PEER_ACCEPTOR::PEER_ADDR + +// Handle ACE_Connector +# define ACE_PEER_CONNECTOR_1 class _ACE_PEER_CONNECTOR +# define ACE_PEER_CONNECTOR_2 _ACE_PEER_CONNECTOR +# define ACE_PEER_CONNECTOR _ACE_PEER_CONNECTOR +# define ACE_PEER_CONNECTOR_ADDR typename ACE_PEER_CONNECTOR::PEER_ADDR +# define ACE_PEER_CONNECTOR_ADDR_ANY ACE_PEER_ADDR_TYPEDEF::sap_any + +// Handle ACE_SOCK_* +# define ACE_SOCK_ACCEPTOR ACE_SOCK_Acceptor +# define ACE_SOCK_CONNECTOR ACE_SOCK_Connector +# define ACE_SOCK_STREAM ACE_SOCK_Stream +# define ACE_SOCK_DGRAM ACE_SOCK_Dgram +# define ACE_SOCK_DGRAM_BCAST ACE_SOCK_Dgram_Bcast +# define ACE_SOCK_DGRAM_MCAST ACE_SOCK_Dgram_Mcast + +// Handle ACE_SOCK_SEQPACK_* +# define ACE_SOCK_SEQPACK_ACCEPTOR ACE_SOCK_SEQPACK_Acceptor +# define ACE_SOCK_SEQPACK_CONNECTOR ACE_SOCK_SEQPACK_Connector +# define ACE_SOCK_SEQPACK_ASSOCIATION ACE_SOCK_SEQPACK_Association + +// Handle ACE_MEM_* +# define ACE_MEM_ACCEPTOR ACE_MEM_Acceptor +# define ACE_MEM_CONNECTOR ACE_MEM_Connector +# define ACE_MEM_STREAM ACE_MEM_Stream + +// Handle ACE_LSOCK_* +# define ACE_LSOCK_ACCEPTOR ACE_LSOCK_Acceptor +# define ACE_LSOCK_CONNECTOR ACE_LSOCK_Connector +# define ACE_LSOCK_STREAM ACE_LSOCK_Stream + +// Handle ACE_TLI_* +# define ACE_TLI_ACCEPTOR ACE_TLI_Acceptor +# define ACE_TLI_CONNECTOR ACE_TLI_Connector +# define ACE_TLI_STREAM ACE_TLI_Stream + +// Handle ACE_SPIPE_* +# define ACE_SPIPE_ACCEPTOR ACE_SPIPE_Acceptor +# define ACE_SPIPE_CONNECTOR ACE_SPIPE_Connector +# define ACE_SPIPE_STREAM ACE_SPIPE_Stream + +// Handle ACE_UPIPE_* +# define ACE_UPIPE_ACCEPTOR ACE_UPIPE_Acceptor +# define ACE_UPIPE_CONNECTOR ACE_UPIPE_Connector +# define ACE_UPIPE_STREAM ACE_UPIPE_Stream + +// Handle ACE_FILE_* +# define ACE_FILE_CONNECTOR ACE_FILE_Connector +# define ACE_FILE_STREAM ACE_FILE_IO + +// Handle ACE_*_Memory_Pool. +# define ACE_MMAP_MEMORY_POOL ACE_MMAP_Memory_Pool +# define ACE_LITE_MMAP_MEMORY_POOL ACE_Lite_MMAP_Memory_Pool +# define ACE_SBRK_MEMORY_POOL ACE_Sbrk_Memory_Pool +# define ACE_SHARED_MEMORY_POOL ACE_Shared_Memory_Pool +# define ACE_LOCAL_MEMORY_POOL ACE_Local_Memory_Pool +# define ACE_PAGEFILE_MEMORY_POOL ACE_Pagefile_Memory_Pool + +# else /* TEMPLATES are broken in some form or another (i.e., most C++ compilers) */ + +// Handle ACE_Message_Queue. +# if defined (ACE_HAS_OPTIMIZED_MESSAGE_QUEUE) +# define ACE_SYNCH_DECL class _ACE_SYNCH_MUTEX_T, class _ACE_SYNCH_CONDITION_T, class _ACE_SYNCH_SEMAPHORE_T +# define ACE_SYNCH_USE _ACE_SYNCH_MUTEX_T, _ACE_SYNCH_CONDITION_T, _ACE_SYNCH_SEMAPHORE_T +# else +# define ACE_SYNCH_DECL class _ACE_SYNCH_MUTEX_T, class _ACE_SYNCH_CONDITION_T +# define ACE_SYNCH_USE _ACE_SYNCH_MUTEX_T, _ACE_SYNCH_CONDITION_T +# endif /* ACE_HAS_OPTIMIZED_MESSAGE_QUEUE */ +# define ACE_SYNCH_MUTEX_T _ACE_SYNCH_MUTEX_T +# define ACE_SYNCH_CONDITION_T _ACE_SYNCH_CONDITION_T +# define ACE_SYNCH_SEMAPHORE_T _ACE_SYNCH_SEMAPHORE_T + +// Handle ACE_Malloc* +# define ACE_MEM_POOL_1 class _ACE_MEM_POOL, class _ACE_MEM_POOL_OPTIONS +# define ACE_MEM_POOL_2 _ACE_MEM_POOL, _ACE_MEM_POOL_OPTIONS +# define ACE_MEM_POOL _ACE_MEM_POOL +# define ACE_MEM_POOL_OPTIONS _ACE_MEM_POOL_OPTIONS + +// Handle ACE_Svc_Handler +# define ACE_PEER_STREAM_1 class _ACE_PEER_STREAM, class _ACE_PEER_ADDR +# define ACE_PEER_STREAM_2 _ACE_PEER_STREAM, _ACE_PEER_ADDR +# define ACE_PEER_STREAM _ACE_PEER_STREAM +# define ACE_PEER_STREAM_ADDR _ACE_PEER_ADDR + +// Handle ACE_Acceptor +# define ACE_PEER_ACCEPTOR_1 class _ACE_PEER_ACCEPTOR, class _ACE_PEER_ADDR +# define ACE_PEER_ACCEPTOR_2 _ACE_PEER_ACCEPTOR, _ACE_PEER_ADDR +# define ACE_PEER_ACCEPTOR _ACE_PEER_ACCEPTOR +# define ACE_PEER_ACCEPTOR_ADDR _ACE_PEER_ADDR + +// Handle ACE_Connector +# define ACE_PEER_CONNECTOR_1 class _ACE_PEER_CONNECTOR, class _ACE_PEER_ADDR +# define ACE_PEER_CONNECTOR_2 _ACE_PEER_CONNECTOR, _ACE_PEER_ADDR +# define ACE_PEER_CONNECTOR _ACE_PEER_CONNECTOR +# define ACE_PEER_CONNECTOR_ADDR _ACE_PEER_ADDR +# define ACE_PEER_CONNECTOR_ADDR_ANY ACE_PEER_CONNECTOR_ADDR::sap_any + +// Handle ACE_SOCK_* +# define ACE_SOCK_ACCEPTOR ACE_SOCK_Acceptor, ACE_INET_Addr +# define ACE_SOCK_CONNECTOR ACE_SOCK_Connector, ACE_INET_Addr +# define ACE_SOCK_STREAM ACE_SOCK_Stream, ACE_INET_Addr +# define ACE_SOCK_DGRAM ACE_SOCK_Dgram, ACE_INET_Addr +# define ACE_SOCK_DGRAM_BCAST ACE_SOCK_Dgram_Bcast, ACE_INET_Addr +# define ACE_SOCK_DGRAM_MCAST ACE_SOCK_Dgram_Mcast, ACE_INET_Addr + +// Handle ACE_SOCK_SEQPACK_* +# define ACE_SOCK_SEQPACK_ACCEPTOR ACE_SOCK_SEQPACK_Acceptor, ACE_Multihomed_INET_Addr +# define ACE_SOCK_SEQPACK_CONNECTOR ACE_SOCK_SEQPACK_Connector, ACE_Multihomed_INET_Addr +# define ACE_SOCK_SEQPACK_ASSOCIATION ACE_SOCK_SEQPACK_Association, ACE_Multihomed_INET_Addr + +// Handle ACE_MEM_* +# define ACE_MEM_ACCEPTOR ACE_MEM_Acceptor, ACE_MEM_Addr +# define ACE_MEM_CONNECTOR ACE_MEM_Connector, ACE_INET_Addr +# define ACE_MEM_STREAM ACE_MEM_Stream, ACE_INET_Addr + +// Handle ACE_LSOCK_* +# define ACE_LSOCK_ACCEPTOR ACE_LSOCK_Acceptor, ACE_UNIX_Addr +# define ACE_LSOCK_CONNECTOR ACE_LSOCK_Connector, ACE_UNIX_Addr +# define ACE_LSOCK_STREAM ACE_LSOCK_Stream, ACE_UNIX_Addr + +// Handle ACE_TLI_* +# define ACE_TLI_ACCEPTOR ACE_TLI_Acceptor, ACE_INET_Addr +# define ACE_TLI_CONNECTOR ACE_TLI_Connector, ACE_INET_Addr +# define ACE_TLI_STREAM ACE_TLI_Stream, ACE_INET_Addr + +// Handle ACE_SPIPE_* +# define ACE_SPIPE_ACCEPTOR ACE_SPIPE_Acceptor, ACE_SPIPE_Addr +# define ACE_SPIPE_CONNECTOR ACE_SPIPE_Connector, ACE_SPIPE_Addr +# define ACE_SPIPE_STREAM ACE_SPIPE_Stream, ACE_SPIPE_Addr + +// Handle ACE_UPIPE_* +# define ACE_UPIPE_ACCEPTOR ACE_UPIPE_Acceptor, ACE_SPIPE_Addr +# define ACE_UPIPE_CONNECTOR ACE_UPIPE_Connector, ACE_SPIPE_Addr +# define ACE_UPIPE_STREAM ACE_UPIPE_Stream, ACE_SPIPE_Addr + +// Handle ACE_FILE_* +# define ACE_FILE_CONNECTOR ACE_FILE_Connector, ACE_FILE_Addr +# define ACE_FILE_STREAM ACE_FILE_IO, ACE_FILE_Addr + +// Handle ACE_*_Memory_Pool. +# define ACE_MMAP_MEMORY_POOL ACE_MMAP_Memory_Pool, ACE_MMAP_Memory_Pool_Options +# define ACE_LITE_MMAP_MEMORY_POOL ACE_Lite_MMAP_Memory_Pool, ACE_MMAP_Memory_Pool_Options +# define ACE_SBRK_MEMORY_POOL ACE_Sbrk_Memory_Pool, ACE_Sbrk_Memory_Pool_Options +# define ACE_SHARED_MEMORY_POOL ACE_Shared_Memory_Pool, ACE_Shared_Memory_Pool_Options +# define ACE_LOCAL_MEMORY_POOL ACE_Local_Memory_Pool, ACE_Local_Memory_Pool_Options +# define ACE_PAGEFILE_MEMORY_POOL ACE_Pagefile_Memory_Pool, ACE_Pagefile_Memory_Pool_Options +# endif /* ACE_HAS_TEMPLATE_TYPEDEFS */ + +// Work around compilers that don't like in-class static integral +// constants. Constants in this case are meant to be compile-time +// constants so that they may be used as template arguments, for +// example. BOOST provides a similar macro. +#ifndef ACE_LACKS_STATIC_IN_CLASS_CONSTANTS +# define ACE_STATIC_CONSTANT(TYPE, ASSIGNMENT) static TYPE const ASSIGNMENT +#else +# define ACE_STATIC_CONSTANT(TYPE, ASSIGNMENT) enum { ASSIGNMENT } +#endif /* !ACE_LACKS_STATIC_IN_CLASS_CONSTANTS */ + +#include /**/ "ace/post.h" + +#endif /*ACE_GLOBAL_MACROS_H*/ diff --git a/dep/acelite/ace/Guard_T.cpp b/dep/acelite/ace/Guard_T.cpp new file mode 100644 index 00000000000..2090ddda2b7 --- /dev/null +++ b/dep/acelite/ace/Guard_T.cpp @@ -0,0 +1,61 @@ +// $Id: Guard_T.cpp 85141 2009-04-22 08:48:30Z johnnyw $ + +#ifndef ACE_GUARD_T_CPP +#define ACE_GUARD_T_CPP + +#include "ace/Guard_T.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (__ACE_INLINE__) +#include "ace/Guard_T.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_HAS_DUMP) +# include "ace/Log_Msg.h" +#endif /* ACE_HAS_DUMP */ + +// **************************************************************** + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// ACE_ALLOC_HOOK_DEFINE(ACE_Guard) + +template void +ACE_Guard::dump (void) const +{ +#if defined (ACE_HAS_DUMP) +// ACE_TRACE ("ACE_Guard::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("mutex_ = %x\n"), this->lock_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("owner_ = %d\n"), this->owner_)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP, this)); +#endif /* ACE_HAS_DUMP */ +} + +// ACE_ALLOC_HOOK_DEFINE(ACE_Write_Guard) + +template void +ACE_Write_Guard::dump (void) const +{ +#if defined (ACE_HAS_DUMP) +// ACE_TRACE ("ACE_Write_Guard::dump"); + ACE_Guard::dump (); +#endif /* ACE_HAS_DUMP */ +} + +// ACE_ALLOC_HOOK_DEFINE(ACE_Read_Guard) + +template void +ACE_Read_Guard::dump (void) const +{ +// ACE_TRACE ("ACE_Read_Guard::dump"); + ACE_Guard::dump (); +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_GUARD_T_CPP */ diff --git a/dep/acelite/ace/Guard_T.h b/dep/acelite/ace/Guard_T.h new file mode 100644 index 00000000000..aee5c266c63 --- /dev/null +++ b/dep/acelite/ace/Guard_T.h @@ -0,0 +1,365 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file Guard_T.h + * + * $Id: Guard_T.h 83306 2008-10-17 12:19:53Z johnnyw $ + * + * Moved from Synch.h. + * + * @author Douglas C. Schmidt + */ +//========================================================================== + +#ifndef ACE_GUARD_T_H +#define ACE_GUARD_T_H +#include /**/ "ace/pre.h" + +#include "ace/Lock.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Global_Macros.h" +#include "ace/OS_NS_Thread.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Guard + * + * @brief This data structure is meant to be used within a method or + * function... It performs automatic aquisition and release of + * a parameterized synchronization object ACE_LOCK. + * + * The class given as an actual parameter must provide at + * the very least the , , , and + * methods. + */ +template +class ACE_Guard +{ +public: + + // = Initialization and termination methods. + ACE_Guard (ACE_LOCK &l); + + /// Implicitly and automatically acquire (or try to acquire) the + /// lock. If @a block is non-0 then the , else + /// it. + ACE_Guard (ACE_LOCK &l, bool block); + + /// Initialise the guard without implicitly acquiring the lock. The + /// @a become_owner parameter indicates whether the guard should release + /// the lock implicitly on destruction. The @a block parameter is + /// ignored and is used here to disambiguate with the preceding + /// constructor. + ACE_Guard (ACE_LOCK &l, bool block, int become_owner); + + /// Implicitly release the lock. + ~ACE_Guard (void); + + // = Lock accessors. + + /// Explicitly acquire the lock. + int acquire (void); + + /// Conditionally acquire the lock (i.e., won't block). + int tryacquire (void); + + /// Explicitly release the lock, but only if it is held! + int release (void); + + /// Relinquish ownership of the lock so that it is not released + /// implicitly in the destructor. + void disown (void); + + // = Utility methods. + /// true if locked, false if couldn't acquire the lock + /// (errno will contain the reason for this). + bool locked (void) const; + + /// Explicitly remove the lock. + int remove (void); + + /// Dump the state of an object. + void dump (void) const; + + // ACE_ALLOC_HOOK_DECLARE; + // Declare the dynamic allocation hooks. + +protected: + + /// Helper, meant for subclass only. + ACE_Guard (ACE_LOCK *lock): lock_ (lock), owner_ (0) {} + + /// Pointer to the ACE_LOCK we're guarding. + ACE_LOCK *lock_; + + /// Keeps track of whether we acquired the lock or failed. + int owner_; + +private: + // = Prevent assignment and initialization. + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Guard &)) + ACE_UNIMPLEMENTED_FUNC (ACE_Guard (const ACE_Guard &)) +}; + +/** + * @class ACE_Write_Guard + * + * @brief This class is similar to class ACE_Guard, though it + * acquires/releases a write lock automatically (naturally, the + * it is instantiated with must support the appropriate + * API). + */ +template +class ACE_Write_Guard : public ACE_Guard +{ +public: + // = Initialization method. + + /// Implicitly and automatically acquire a write lock. + ACE_Write_Guard (ACE_LOCK &m); + + /// Implicitly and automatically acquire (or try to acquire) a write + /// lock. + ACE_Write_Guard (ACE_LOCK &m, bool block); + + // = Lock accessors. + + /// Explicitly acquire the write lock. + int acquire_write (void); + + /// Explicitly acquire the write lock. + int acquire (void); + + /// Conditionally acquire the write lock (i.e., won't block). + int tryacquire_write (void); + + /// Conditionally acquire the write lock (i.e., won't block). + int tryacquire (void); + + // = Utility methods. + + /// Dump the state of an object. + void dump (void) const; + + // ACE_ALLOC_HOOK_DECLARE; + // Declare the dynamic allocation hooks. +}; + +/** + * @class ACE_Read_Guard + * + * @brief This class is similar to class ACE_Guard, though it + * acquires/releases a read lock automatically (naturally, the + * it is instantiated with must support the appropriate + * API). + */ +template +class ACE_Read_Guard : public ACE_Guard +{ +public: + // = Initialization methods. + + /// Implicitly and automatically acquire a read lock. + ACE_Read_Guard (ACE_LOCK& m); + + /// Implicitly and automatically acquire (or try to acquire) a read + /// lock. + ACE_Read_Guard (ACE_LOCK &m, bool block); + + // = Lock accessors. + + /// Explicitly acquire the read lock. + int acquire_read (void); + + /// Explicitly acquire the read lock. + int acquire (void); + + /// Conditionally acquire the read lock (i.e., won't block). + int tryacquire_read (void); + + /// Conditionally acquire the read lock (i.e., won't block). + int tryacquire (void); + + // = Utility methods. + + /// Dump the state of an object. + void dump (void) const; + + // ACE_ALLOC_HOOK_DECLARE; + // Declare the dynamic allocation hooks. +}; + +#if !(defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION))) + +#define ACE_TSS_Guard ACE_Guard +#define ACE_TSS_Write_GUARD ACE_Write_Guard +#define ACE_TSS_Read_GUARD ACE_Read_Guard + +#else + /* ACE platform supports some form of threading and + thread-specific storage. */ + +/** + * @class ACE_TSS_Guard + * + * @brief This data structure is meant to be used within a method or + * function... It performs automatic aquisition and release of + * a synchronization object. Moreover, it ensures that the lock + * is released even if a thread exits via ! + */ +template +class ACE_TSS_Guard +{ +public: + // = Initialization and termination methods. + + /// Implicitly and automatically acquire the thread-specific lock. + ACE_TSS_Guard (ACE_LOCK &lock, bool block = true); + + /// Implicitly release the thread-specific lock. + ~ACE_TSS_Guard (void); + + // = Lock accessors. + + /// Explicitly acquire the thread-specific lock. + int acquire (void); + + /// Conditionally acquire the thread-specific lock (i.e., won't + /// block). + int tryacquire (void); + + /// Explicitly release the thread-specific lock. + int release (void); + + // = Utility methods. + /// Explicitly release the thread-specific lock. + int remove (void); + + /// Dump the state of an object. + void dump (void) const; + + // ACE_ALLOC_HOOK_DECLARE; + // Declare the dynamic allocation hooks. + +protected: + /// Helper, meant for subclass only. + ACE_TSS_Guard (void); + + /// Initialize the key. + void init_key (void); + + /// Called when thread exits to clean up the lock. + static void cleanup (void *ptr); + + /// Thread-specific key... + ACE_thread_key_t key_; + +private: + // = Prevent assignment and initialization. + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_TSS_Guard &)) + ACE_UNIMPLEMENTED_FUNC (ACE_TSS_Guard (const ACE_TSS_Guard &)) +}; + +/** + * @class ACE_TSS_Write_Guard + * + * @brief This class is similar to class ACE_TSS_Guard, though it + * acquires/releases a write-lock automatically (naturally, the + * ACE_LOCK it is instantiated with must support the appropriate + * API). + */ +template +class ACE_TSS_Write_Guard : public ACE_TSS_Guard +{ +public: + // = Initialization method. + + /// Implicitly and automatically acquire the thread-specific write lock. + ACE_TSS_Write_Guard (ACE_LOCK &lock, bool block = true); + + // = Lock accessors. + + /// Explicitly acquire the thread-specific write lock. + int acquire_write (void); + + /// Explicitly acquire the thread-specific write lock. + int acquire (void); + + /// Conditionally acquire the thread-specific write lock (i.e., won't block). + int tryacquire_write (void); + + /// Conditionally acquire the thread-specific write lock (i.e., won't block). + int tryacquire (void); + + // = Utility methods. + + /// Dump the state of an object. + void dump (void) const; + + // ACE_ALLOC_HOOK_DECLARE; + // Declare the dynamic allocation hooks. +}; + +/** + * @class ACE_TSS_Read_Guard + * + * @brief This class is similar to class , though it + * acquires/releases a read lock automatically (naturally, the + * it is instantiated with must support the + * appropriate API). + */ +template +class ACE_TSS_Read_Guard : public ACE_TSS_Guard +{ +public: + // = Initialization method. + /// Implicitly and automatically acquire the thread-specific read lock. + ACE_TSS_Read_Guard (ACE_LOCK &lock, bool block = true); + + // = Lock accessors. + /// Explicitly acquire the thread-specific read lock. + int acquire_read (void); + + /// Explicitly acquire the thread-specific read lock. + int acquire (void); + + /// Conditionally acquire the thread-specific read lock (i.e., won't + /// block). + int tryacquire_read (void); + + /// Conditionally acquire the thread-specific read lock (i.e., won't + /// block). + int tryacquire (void); + + // = Utility methods. + /// Dump the state of an object. + void dump (void) const; + + // ACE_ALLOC_HOOK_DECLARE; + // Declare the dynamic allocation hooks. +}; + +#endif /* !(defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION))) */ + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Guard_T.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Guard_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Guard_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" +#endif /* ACE_GUARD_T_H */ diff --git a/dep/acelite/ace/Guard_T.inl b/dep/acelite/ace/Guard_T.inl new file mode 100644 index 00000000000..3e7d5b61f8d --- /dev/null +++ b/dep/acelite/ace/Guard_T.inl @@ -0,0 +1,170 @@ +// -*- C++ -*- +// +// $Id: Guard_T.inl 82723 2008-09-16 09:35:44Z johnnyw $ + +#include "ace/RW_Thread_Mutex.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template ACE_INLINE int +ACE_Guard::acquire (void) +{ + return this->owner_ = this->lock_->acquire (); +} + +template ACE_INLINE int +ACE_Guard::tryacquire (void) +{ + return this->owner_ = this->lock_->tryacquire (); +} + +template ACE_INLINE int +ACE_Guard::release (void) +{ + if (this->owner_ == -1) + return -1; + else + { + this->owner_ = -1; + return this->lock_->release (); + } +} + +template ACE_INLINE +ACE_Guard::ACE_Guard (ACE_LOCK &l) + : lock_ (&l), + owner_ (0) +{ + this->acquire (); +} + +template ACE_INLINE +ACE_Guard::ACE_Guard (ACE_LOCK &l, bool block) + : lock_ (&l), + owner_ (0) +{ + if (block) + this->acquire (); + else + this->tryacquire (); +} + +template ACE_INLINE +ACE_Guard::ACE_Guard (ACE_LOCK &l, bool /* block */, int become_owner) + : lock_ (&l), + owner_ (become_owner == 0 ? -1 : 0) +{ +} + +// Implicitly and automatically acquire (or try to acquire) the +// lock. + +template ACE_INLINE +ACE_Guard::~ACE_Guard (void) +{ + this->release (); +} + +template ACE_INLINE bool +ACE_Guard::locked (void) const +{ + return this->owner_ != -1; +} + +template ACE_INLINE int +ACE_Guard::remove (void) +{ + return this->lock_->remove (); +} + +template ACE_INLINE void +ACE_Guard::disown (void) +{ + this->owner_ = -1; +} + +template ACE_INLINE +ACE_Write_Guard::ACE_Write_Guard (ACE_LOCK &m) + : ACE_Guard (&m) +{ + this->acquire_write (); +} + +template ACE_INLINE int +ACE_Write_Guard::acquire_write (void) +{ + return this->owner_ = this->lock_->acquire_write (); +} + +template ACE_INLINE int +ACE_Write_Guard::acquire (void) +{ + return this->owner_ = this->lock_->acquire_write (); +} + +template ACE_INLINE int +ACE_Write_Guard::tryacquire_write (void) +{ + return this->owner_ = this->lock_->tryacquire_write (); +} + +template ACE_INLINE int +ACE_Write_Guard::tryacquire (void) +{ + return this->owner_ = this->lock_->tryacquire_write (); +} + +template ACE_INLINE +ACE_Write_Guard::ACE_Write_Guard (ACE_LOCK &m, + bool block) + : ACE_Guard (&m) +{ + if (block) + this->acquire_write (); + else + this->tryacquire_write (); +} + +template ACE_INLINE int +ACE_Read_Guard::acquire_read (void) +{ + return this->owner_ = this->lock_->acquire_read (); +} + +template ACE_INLINE int +ACE_Read_Guard::acquire (void) +{ + return this->owner_ = this->lock_->acquire_read (); +} + +template ACE_INLINE int +ACE_Read_Guard::tryacquire_read (void) +{ + return this->owner_ = this->lock_->tryacquire_read (); +} + +template ACE_INLINE int +ACE_Read_Guard::tryacquire (void) +{ + return this->owner_ = this->lock_->tryacquire_read (); +} + +template ACE_INLINE +ACE_Read_Guard::ACE_Read_Guard (ACE_LOCK &m) + : ACE_Guard (&m) +{ + this->acquire_read (); +} + +template ACE_INLINE +ACE_Read_Guard::ACE_Read_Guard (ACE_LOCK &m, + bool block) + : ACE_Guard (&m) +{ + if (block) + this->acquire_read (); + else + this->tryacquire_read (); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Handle_Gobbler.h b/dep/acelite/ace/Handle_Gobbler.h new file mode 100644 index 00000000000..9d6890a03fc --- /dev/null +++ b/dep/acelite/ace/Handle_Gobbler.h @@ -0,0 +1,68 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Handle_Gobbler.h + * + * $Id: Handle_Gobbler.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Kirthika Parameswaran + * @author Irfan Pyarali + */ +//============================================================================= + + +#ifndef ACE_HANDLE_GOBBLER_H +#define ACE_HANDLE_GOBBLER_H +#include /**/ "ace/pre.h" + +#include "ace/Handle_Set.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Handle_Gobbler + * + * @brief This class gobbles up handles. + * + * This is useful when we need to control the number of handles + * available for a process. This class is mostly used for + * testing purposes. + */ +class ACE_Handle_Gobbler +{ +public: + + /// Destructor. Cleans up any remaining handles. + inline ~ACE_Handle_Gobbler (void); + + /** + * Handles are opened continously until the process runs out of + * them, and then handles are closed + * (freed) thereby making them usable in the future. + */ + inline int consume_handles (size_t n_handles_to_keep_available); + + /// Free up @a n_handles. + inline int free_handles (size_t n_handles); + + /// All remaining handles are closed. + inline void close_remaining_handles (void); + +private: + typedef ACE_Handle_Set HANDLE_SET; + + /// The container which holds the open descriptors. + HANDLE_SET handle_set_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include "ace/Handle_Gobbler.inl" + +#include /**/ "ace/post.h" +#endif /* ACE_HANDLE_GOBBLER_H */ diff --git a/dep/acelite/ace/Handle_Gobbler.inl b/dep/acelite/ace/Handle_Gobbler.inl new file mode 100644 index 00000000000..6a053d88be0 --- /dev/null +++ b/dep/acelite/ace/Handle_Gobbler.inl @@ -0,0 +1,79 @@ +// -*- C++ -*- +// +// $Id: Handle_Gobbler.inl 90388 2010-06-02 15:27:59Z vzykov $ + +// Since this is only included in Handle_Gobbler.h, these should be +// inline, not ACE_INLINE. +// FUZZ: disable check_for_inline + +#include "ace/ACE.h" +#include "ace/OS_NS_unistd.h" +#include "ace/OS_NS_fcntl.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +inline void +ACE_Handle_Gobbler::close_remaining_handles (void) +{ + ACE_Handle_Set_Iterator iter (this->handle_set_); + for (ACE_HANDLE h = iter (); h != ACE_INVALID_HANDLE; h = iter ()) + ACE_OS::close (h); +} + +inline +ACE_Handle_Gobbler::~ACE_Handle_Gobbler (void) +{ + this->close_remaining_handles (); +} + +inline int +ACE_Handle_Gobbler::free_handles (size_t n_handles) +{ + ACE_Handle_Set_Iterator iter (this->handle_set_); + for (ACE_HANDLE h = iter (); + h != ACE_INVALID_HANDLE && n_handles > 0; + --n_handles, h = iter ()) + ACE_OS::close (h); + + return 0; +} + +inline int +ACE_Handle_Gobbler::consume_handles (size_t n_handles_to_keep_available) +{ + int result = 0; + +#if defined(ACE_WIN32) + // On Win32, this style of gobbling doesn't seem to work. + ACE_UNUSED_ARG(n_handles_to_keep_available); + +#else + + while (1) + { + ACE_HANDLE handle = ACE_OS::open (ACE_DEV_NULL, O_WRONLY); + + if (handle == ACE_INVALID_HANDLE) + { + if (ACE::out_of_handles (errno)) + { + result = this->free_handles (n_handles_to_keep_available); + break; + } + else + { + result = -1; + break; + } + } + if (handle >= static_cast(FD_SETSIZE)) + break; + this->handle_set_.set_bit (handle); + } + +#endif /* ACE_WIN32 */ + + return result; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Handle_Ops.cpp b/dep/acelite/ace/Handle_Ops.cpp new file mode 100644 index 00000000000..0ec856cf1c9 --- /dev/null +++ b/dep/acelite/ace/Handle_Ops.cpp @@ -0,0 +1,48 @@ +// $Id: Handle_Ops.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Handle_Ops.h" + +#include "ace/OS_NS_errno.h" +#include "ace/OS_NS_fcntl.h" +#include "ace/Time_Value.h" + +ACE_RCSID (ace, + Handle_Ops, + "$Id: Handle_Ops.cpp 80826 2008-03-04 14:51:23Z wotte $") + + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_HANDLE +ACE::handle_timed_open (ACE_Time_Value *timeout, + const ACE_TCHAR *name, + int flags, + int perms, + LPSECURITY_ATTRIBUTES sa) +{ + ACE_TRACE ("ACE::handle_timed_open"); + + if (timeout != 0) + { +#if !defined (ACE_WIN32) + // On Win32, ACE_NONBLOCK gets recognized as O_WRONLY so we + // don't use it there + flags |= ACE_NONBLOCK; +#endif /* ACE_WIN32 */ + + // Open the named pipe or file using non-blocking mode... + ACE_HANDLE const handle = ACE_OS::open (name, flags, perms, sa); + + if (handle == ACE_INVALID_HANDLE + && (errno == EWOULDBLOCK + && (timeout->sec () > 0 || timeout->usec () > 0))) + // This expression checks if we were polling. + errno = ETIMEDOUT; + + return handle; + } + else + return ACE_OS::open (name, flags, perms, sa); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Handle_Ops.h b/dep/acelite/ace/Handle_Ops.h new file mode 100644 index 00000000000..c615380f8dd --- /dev/null +++ b/dep/acelite/ace/Handle_Ops.h @@ -0,0 +1,50 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Handle_Ops.h + * + * $Id: Handle_Ops.h 80826 2008-03-04 14:51:23Z wotte $ + * + * Handle operations. + */ +//============================================================================= + +#ifndef ACE_HANDLE_OPS_H +#define ACE_HANDLE_OPS_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Global_Macros.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +class ACE_Time_Value; + +// = Operations on HANDLEs. +namespace ACE +{ + /** + * Wait up to @a timeout amount of time to actively open a device. + * This method doesn't perform the @c connect, it just does the + * timed wait. + */ + extern ACE_Export ACE_HANDLE handle_timed_open ( + ACE_Time_Value *timeout, + const ACE_TCHAR *name, + int flags, + int perms, + LPSECURITY_ATTRIBUTES sa = 0); +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" + +#endif /* ACE_HANDLE_OPS_H */ diff --git a/dep/acelite/ace/Handle_Set.cpp b/dep/acelite/ace/Handle_Set.cpp new file mode 100644 index 00000000000..168acca86cd --- /dev/null +++ b/dep/acelite/ace/Handle_Set.cpp @@ -0,0 +1,565 @@ +// Handle_Set.cpp +// $Id: Handle_Set.cpp 83306 2008-10-17 12:19:53Z johnnyw $ + +#include "ace/Handle_Set.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Handle_Set.inl" +#endif /* __ACE_INLINE__ */ + +#include "ace/OS_NS_string.h" + +ACE_RCSID(ace, Handle_Set, "$Id: Handle_Set.cpp 83306 2008-10-17 12:19:53Z johnnyw $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Handle_Set) + + // ACE_MSB_MASK is only used here. + // This needs to go here to avoid overflow problems on some compilers. +#if defined (ACE_WIN32) + // Does ACE_WIN32 have an fd_mask? +# define ACE_MSB_MASK (~(1 << (NFDBITS - 1))) +#else /* ! ACE_WIN32 */ +# define ACE_MSB_MASK (~((fd_mask) 1 << (NFDBITS - 1))) +#endif /* ! ACE_WIN32 */ + +#if defined (linux) && __GLIBC__ > 1 && __GLIBC_MINOR__ >= 1 && !defined (_XOPEN_SOURCE) + // XPG4.2 requires the fds_bits member name, so it is not enabled by + // default on Linux/glibc-2.1.x systems. Instead use "__fds_bits." + // Ugly, but "what are you going to do?" 8-) +#define fds_bits __fds_bits +#endif /* linux && __GLIBC__ > 1 && __GLIBC_MINOR__ >= 1 && !_XOPEN_SOURCE */ + +void +ACE_Handle_Set::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Handle_Set::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nsize_ = %d"), this->size_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nmax_handle_ = %d"), this->max_handle_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n[ "))); + +#if defined (ACE_WIN32) + for (size_t i = 0; i < (size_t) this->mask_.fd_count + 1; i++) + ACE_DEBUG ((LM_DEBUG, ACE_TEXT (" %x "), this->mask_.fd_array[i])); +#else /* !ACE_WIN32 */ + for (ACE_HANDLE i = 0; i < this->max_handle_ + 1; i++) + if (this->is_set (i)) + ACE_DEBUG ((LM_DEBUG, ACE_TEXT (" %d "), i)); +#endif /* ACE_WIN32 */ + + ACE_DEBUG ((LM_DEBUG, ACE_TEXT (" ]\n"))); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +// Table that maps bytes to counts of the enabled bits in each value +// from 0 to 255, +// +// nbits_[0] == 0 +// +// because there are no bits enabled for the value 0. +// +// nbits_[5] == 2 +// +// because there are 2 bits enabled in the value 5, i.e., it's +// 101 in binary. + +const char ACE_Handle_Set::nbits_[256] = +{ + 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8}; + +// Constructor, initializes the bitmask to all 0s. + +ACE_Handle_Set::ACE_Handle_Set (void) +{ + ACE_TRACE ("ACE_Handle_Set::ACE_Handle_Set"); + this->reset (); +} + +ACE_Handle_Set::ACE_Handle_Set (const fd_set &fd_mask) +{ + ACE_TRACE ("ACE_Handle_Set::ACE_Handle_Set"); + this->reset (); + ACE_OS::memcpy ((void *) &this->mask_, + (void *) &fd_mask, + sizeof this->mask_); +#if !defined (ACE_WIN32) + this->sync (ACE_Handle_Set::MAXSIZE); +#if defined (ACE_HAS_BIG_FD_SET) + this->min_handle_ = 0; +#endif /* ACE_HAS_BIG_FD_SET */ +#endif /* !ACE_WIN32 */ +} + +// Counts the number of bits enabled in N. Uses a table lookup to +// speed up the count. + +int +ACE_Handle_Set::count_bits (u_long n) +{ + + ACE_TRACE ("ACE_Handle_Set::count_bits"); +#if defined (ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT) + register int rval = 0; + + // Count the number of enabled bits in . This algorithm is very + // fast, i.e., O(enabled bits in n). + + for (register u_long m = n; + m != 0; + m &= m - 1) + rval++; + + return rval; +#else + return (ACE_Handle_Set::nbits_[n & 0xff] + + ACE_Handle_Set::nbits_[(n >> 8) & 0xff] + + ACE_Handle_Set::nbits_[(n >> 16) & 0xff] + + ACE_Handle_Set::nbits_[(n >> 24) & 0xff]); +#endif /* ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT */ +} + +#if defined (ACE_HAS_BIG_FD_SET) +// Find the bit position counting from right to left worst case +// (1<<31) is 8. + +int +ACE_Handle_Set::bitpos (u_long bit) +{ + register int l = 0; + register u_long n = bit - 1; + + // This is a fast count method when have the most significative bit. + + while (n >> 8) + { + n >>= 8; + l += 8; + } + + // Is greater than 15? + if (n & 16) + { + n >>= 4; + l += 4; + } + + // Count number remaining bits. + while (n != 0) + { + n &= n - 1; + l++; + } + return l; +} +#endif /* ACE_HAS_BIG_FD_SET */ + +// Synchronize the underlying FD_SET with the MAX_FD and the SIZE. + +#if defined (ACE_USE_SHIFT_FOR_EFFICIENCY) +// These don't work because shifting right 3 bits is not the same as +// dividing by 3, e.g., dividing by 8 requires shifting right 3 bits. +// In order to do the shift, we need to calculate the number of bits +// at some point. +#define ACE_DIV_BY_WORDSIZE(x) ((x) >> ((int) ACE_Handle_Set::WORDSIZE)) +#define ACE_MULT_BY_WORDSIZE(x) ((x) << ((int) ACE_Handle_Set::WORDSIZE)) +#else +#define ACE_DIV_BY_WORDSIZE(x) ((x) / ((int) ACE_Handle_Set::WORDSIZE)) +#define ACE_MULT_BY_WORDSIZE(x) ((x) * ((int) ACE_Handle_Set::WORDSIZE)) +#endif /* ACE_USE_SHIFT_FOR_EFFICIENCY */ + +void +ACE_Handle_Set::sync (ACE_HANDLE max) +{ + ACE_TRACE ("ACE_Handle_Set::sync"); +#if !defined (ACE_WIN32) + fd_mask *maskp = (fd_mask *)(this->mask_.fds_bits); + this->size_ = 0; + + for (int i = ACE_DIV_BY_WORDSIZE (max - 1); + i >= 0; + i--) + this->size_ += ACE_Handle_Set::count_bits (maskp[i]); + + this->set_max (max); +#else + ACE_UNUSED_ARG (max); +#endif /* !ACE_WIN32 */ +} + +// Resets the MAX_FD after a clear of the original MAX_FD. + +void +ACE_Handle_Set::set_max (ACE_HANDLE current_max) +{ + ACE_TRACE ("ACE_Handle_Set::set_max"); +#if !defined(ACE_WIN32) + fd_mask * maskp = (fd_mask *)(this->mask_.fds_bits); + + if (this->size_ == 0) + this->max_handle_ = ACE_INVALID_HANDLE; + else + { + int i; + + for (i = ACE_DIV_BY_WORDSIZE (current_max - 1); + maskp[i] == 0; + i--) + continue; +#if defined (ACE_TANDEM_NSK_BIT_ORDER) + // bits are in reverse order, MSB (sign bit) = bit 0. + this->max_handle_ = ACE_MULT_BY_WORDSIZE (i); + for (fd_mask val = maskp[i]; + (val & ACE_MSB_MASK) != 0; + val = (val << 1)) + ++this->max_handle_; +#elif 1 /* !defined(ACE_HAS_BIG_FD_SET) */ + this->max_handle_ = ACE_MULT_BY_WORDSIZE (i); + for (fd_mask val = maskp[i]; + (val & ~1) != 0; // This obscure code is needed since "bit 0" is in location 1... + val = (val >> 1) & ACE_MSB_MASK) + ++this->max_handle_; +#else + register u_long val = this->mask_.fds_bits[i]; + this->max_handle_ = ACE_MULT_BY_WORDSIZE (i) + + ACE_Handle_Set::bitpos(val & ~(val - 1)); +#endif /* 1 */ + } + + // Do some sanity checking... + if (this->max_handle_ >= ACE_Handle_Set::MAXSIZE) + this->max_handle_ = ACE_Handle_Set::MAXSIZE - 1; +#else + ACE_UNUSED_ARG (current_max); +#endif /* !ACE_WIN32 */ +} + +ACE_ALLOC_HOOK_DEFINE(ACE_Handle_Set_Iterator) + +void +ACE_Handle_Set_Iterator::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Handle_Set_Iterator::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); +#if defined(ACE_WIN32) || !defined(ACE_HAS_BIG_FD_SET) + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nhandle_index_ = %d"), this->handle_index_)); +#elif defined(ACE_HAS_BIG_FD_SET) + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nword_max_ = %d"), this->word_max_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nword_val_ = %d"), this->word_val_)); +#endif + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nword_num_ = %d"), this->word_num_)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +ACE_HANDLE +ACE_Handle_Set_Iterator::operator () (void) +{ + ACE_TRACE ("ACE_Handle_Set_Iterator::operator"); +#if defined (ACE_WIN32) + if (this->handle_index_ < this->handles_.mask_.fd_count) + // Return the handle and advance the iterator. + return (ACE_HANDLE) this->handles_.mask_.fd_array[this->handle_index_++]; + else + return ACE_INVALID_HANDLE; + +#elif !defined (ACE_HAS_BIG_FD_SET) /* !ACE_WIN32 */ + // No sense searching further than the max_handle_ + 1; + ACE_HANDLE maxhandlep1 = this->handles_.max_handle_ + 1; + + // HP-UX 11 plays some games with the fd_mask type - fd_mask is + // defined as an int_32t, but the fds_bits is an array of longs. + // This makes plainly indexing through the array by hand tricky, + // since the FD_* macros treat the array as int32_t. So the bits + // are in the right place for int32_t, even though the array is + // long. This, they say, is to preserve the same in-memory layout + // for 32-bit and 64-bit processes. So, we play the same game as + // the FD_* macros to get the bits right. On all other systems, + // this amounts to practically a NOP, since this is what would have + // been done anyway, without all this type jazz. + fd_mask * maskp = (fd_mask *)(this->handles_.mask_.fds_bits); + + if (this->handle_index_ >= maxhandlep1) + // We've seen all the handles we're interested in seeing for this + // iterator. + return ACE_INVALID_HANDLE; + else + { + ACE_HANDLE result = this->handle_index_; + + // Increment the iterator and advance to the next bit in this + // word. + this->handle_index_++; +#if defined (ACE_TANDEM_NSK_BIT_ORDER) + // bits are in reverse order, MSB (sign bit) = bit 0. + this->word_val_ = (this->word_val_ << 1); +# else + this->word_val_ = (this->word_val_ >> 1) & ACE_MSB_MASK; +# endif /* ACE_TANDEM_NSK_BIT_ORDER */ + + // If we've examined all the bits in this word, we'll go onto + // the next word. + + if (this->word_val_ == 0) + { + // Start the handle_index_ at the beginning of the next word + // and then loop until we've found the first non-zero bit or + // we run past the of the bitset. + + for (this->handle_index_ = ACE_MULT_BY_WORDSIZE(++this->word_num_); + this->handle_index_ < maxhandlep1 + && maskp[this->word_num_] == 0; + this->word_num_++) + this->handle_index_ += ACE_Handle_Set::WORDSIZE; + + // If the bit index becomes >= the maxhandlep1 that means + // there weren't any more bits set that we want to consider. + // Therefore, we'll just store the maxhandlep1, which will + // cause to return + // immediately next time it's called. + if (this->handle_index_ >= maxhandlep1) + { + this->handle_index_ = maxhandlep1; + return result; + } + else + // Load the bits of the next word. + this->word_val_ = maskp[this->word_num_]; + } + + // Loop until we get to have its least significant + // bit enabled, keeping track of which this + // represents (this information is used by subsequent calls to + // ). + +#if defined (ACE_TANDEM_NSK_BIT_ORDER) + // bits are in reverse order, MSB (sign bit) = bit 0. + for (; + this->word_val_ > 0; + this->word_val_ = (this->word_val_ << 1)) + this->handle_index_++; +# else + for (; + ACE_BIT_DISABLED (this->word_val_, 1); + this->handle_index_++) + this->word_val_ = (this->word_val_ >> 1) & ACE_MSB_MASK; +# endif /* ACE_TANDEM_NSK_BIT_ORDER */ + + return result; + } +#else /* !ACE_HAS_BIG_FD_SET */ + // Find the first word in fds_bits with bit on + register u_long lsb = this->word_val_; + + if (lsb == 0) + { + do + { + // We have exceeded the word count in Handle_Set? + if (++this->word_num_ >= this->word_max_) + return ACE_INVALID_HANDLE; + + lsb = this->handles_.mask_.fds_bits[this->word_num_]; + } + while (lsb == 0); + + // Set index to word boundary. + this->handle_index_ = ACE_MULT_BY_WORDSIZE (this->word_num_); + + // Put new word_val. + this->word_val_ = lsb; + + // Find the least significative bit. + lsb &= ~(lsb - 1); + + // Remove least significative bit. + this->word_val_ ^= lsb; + + // Save to calculate bit distance. + this->oldlsb_ = lsb; + + // Move index to least significative bit. + while (lsb >>= 1) + this->handle_index_++; + } + else + { + // Find the least significative bit. + lsb &= ~(lsb - 1); + + // Remove least significative bit. + this->word_val_ ^= lsb; + + register u_long n = lsb - this->oldlsb_; + + // Move index to bit distance between new lsb and old lsb. + do + { + this->handle_index_++; + n &= n >> 1; + } + while (n != 0); + + this->oldlsb_ = lsb; + } + + return this->handle_index_; +#endif /* ACE_WIN32 */ +} + +ACE_Handle_Set_Iterator::ACE_Handle_Set_Iterator (const ACE_Handle_Set &hs) + : handles_ (hs), +#if !defined (ACE_HAS_BIG_FD_SET) || defined (ACE_WIN32) + handle_index_ (0), + word_num_ (-1) +#elif defined (ACE_HAS_BIG_FD_SET) + oldlsb_ (0), + word_max_ (hs.max_handle_ == ACE_INVALID_HANDLE + ? 0 + : ((ACE_DIV_BY_WORDSIZE (hs.max_handle_)) + 1)) +#endif /* ACE_HAS_BIG_FD_SET */ +{ + ACE_TRACE ("ACE_Handle_Set_Iterator::ACE_Handle_Set_Iterator"); +#if !defined (ACE_WIN32) && !defined (ACE_HAS_BIG_FD_SET) + // No sense searching further than the max_handle_ + 1; + ACE_HANDLE maxhandlep1 = + this->handles_.max_handle_ + 1; + + fd_mask *maskp = + (fd_mask *)(this->handles_.mask_.fds_bits); + + // Loop until we've found the first non-zero bit or we run past the + // of the bitset. + while (this->handle_index_ < maxhandlep1 + && maskp[++this->word_num_] == 0) + this->handle_index_ += ACE_Handle_Set::WORDSIZE; + + // If the bit index becomes >= the maxhandlep1 that means there + // weren't any bits set. Therefore, we'll just store the + // maxhandlep1, which will cause to return + // immediately. + if (this->handle_index_ >= maxhandlep1) + this->handle_index_ = maxhandlep1; + else + // Loop until we get to have its least significant bit + // enabled, keeping track of which this represents + // (this information is used by ). +#if defined (ACE_TANDEM_NSK_BIT_ORDER) + // bits are in reverse order, MSB (sign bit) = bit 0. + for (this->word_val_ = maskp[this->word_num_]; + this->word_val_ > 0; + this->word_val_ = (this->word_val_ << 1)) + this->handle_index_++; +# else + for (this->word_val_ = maskp[this->word_num_]; + ACE_BIT_DISABLED (this->word_val_, 1) + && this->handle_index_ < maxhandlep1; + this->handle_index_++) + this->word_val_ = (this->word_val_ >> 1) & ACE_MSB_MASK; +# endif /* ACE_TANDEM_NSK_BIT_ORDER */ +#elif !defined (ACE_WIN32) && defined (ACE_HAS_BIG_FD_SET) + if (this->word_max_==0) + { + this->word_num_ = -1; + this->word_val_ = 0; + } + else + { + this->word_num_ = + ACE_DIV_BY_WORDSIZE (this->handles_.min_handle_) - 1; + this->word_val_ = 0; + } +#endif /* !ACE_WIN32 && !ACE_HAS_BIG_FD_SET */ +} + + +void +ACE_Handle_Set_Iterator::reset_state (void) +{ + ACE_TRACE ("ACE_Handle_Set_Iterator::reset_state"); + +#if !defined (ACE_HAS_BIG_FD_SET) || defined (ACE_WIN32) + this->handle_index_ = 0; + this->word_num_ = -1; +#elif defined (ACE_HAS_BIG_FD_SET) + this->oldlsb_ = 0; + this->word_max_ = + this->handles_.max_handle_ == ACE_INVALID_HANDLE ? 0 + : ((ACE_DIV_BY_WORDSIZE (this->handles_.max_handle_)) + 1); +#endif /* ACE_HAS_BIG_FD_SET */ + +#if !defined (ACE_WIN32) && !defined (ACE_HAS_BIG_FD_SET) + // No sense searching further than the max_handle_ + 1; + ACE_HANDLE maxhandlep1 = + this->handles_.max_handle_ + 1; + + fd_mask *maskp = + (fd_mask *)(this->handles_.mask_.fds_bits); + + // Loop until we've found the first non-zero bit or we run past the + // of the bitset. + while (this->handle_index_ < maxhandlep1 + && maskp[++this->word_num_] == 0) + this->handle_index_ += ACE_Handle_Set::WORDSIZE; + + // If the bit index becomes >= the maxhandlep1 that means there + // weren't any bits set. Therefore, we'll just store the + // maxhandlep1, which will cause to return + // immediately. + if (this->handle_index_ >= maxhandlep1) + this->handle_index_ = maxhandlep1; + else + // Loop until we get to have its least significant bit + // enabled, keeping track of which this represents + // (this information is used by ). +#if defined (ACE_TANDEM_NSK_BIT_ORDER) + // bits are in reverse order, MSB (sign bit) = bit 0. + for (this->word_val_ = maskp[this->word_num_]; + this->word_val_ > 0; + this->word_val_ = (this->word_val_ << 1)) + this->handle_index_++; +# else + for (this->word_val_ = maskp[this->word_num_]; + ACE_BIT_DISABLED (this->word_val_, 1) + && this->handle_index_ < maxhandlep1; + this->handle_index_++) + this->word_val_ = (this->word_val_ >> 1) & ACE_MSB_MASK; +# endif /* ACE_TANDEM_NSK_BIT_ORDER */ +#elif !defined (ACE_WIN32) && defined (ACE_HAS_BIG_FD_SET) + if (this->word_max_==0) + { + this->word_num_ = -1; + this->word_val_ = 0; + } + else + { + this->word_num_ = + ACE_DIV_BY_WORDSIZE (this->handles_.min_handle_) - 1; + this->word_val_ = 0; + } +#endif /* !ACE_WIN32 && !ACE_HAS_BIG_FD_SET */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Handle_Set.h b/dep/acelite/ace/Handle_Set.h new file mode 100644 index 00000000000..11188f9fc38 --- /dev/null +++ b/dep/acelite/ace/Handle_Set.h @@ -0,0 +1,236 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file Handle_Set.h + * + * $Id: Handle_Set.h 82723 2008-09-16 09:35:44Z johnnyw $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_HANDLE_SET_H +#define ACE_HANDLE_SET_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_select.h" +#include "ace/os_include/os_limits.h" + +// Default size of the ACE Reactor. +#if defined (FD_SETSIZE) + int const ACE_FD_SETSIZE = FD_SETSIZE; +#else /* !FD_SETSIZE */ +# define ACE_FD_SETSIZE FD_SETSIZE +#endif /* ACE_FD_SETSIZE */ + +#if !defined (ACE_DEFAULT_SELECT_REACTOR_SIZE) +# define ACE_DEFAULT_SELECT_REACTOR_SIZE ACE_FD_SETSIZE +#endif /* ACE_DEFAULT_SELECT_REACTOR_SIZE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Handle_Set + * + * @brief C++ wrapper facade for the socket @c fd_set abstraction. + * + * This abstraction is a very efficient wrapper facade over + * @c fd_set. In particular, no range checking is performed, so + * it's important not to set or clear bits that are outside the + * @c ACE_DEFAULT_SELECT_REACTOR_SIZE. + */ +class ACE_Export ACE_Handle_Set +{ +public: + friend class ACE_Handle_Set_Iterator; + + // = Initialization and termination. + + enum + { + MAXSIZE = ACE_DEFAULT_SELECT_REACTOR_SIZE + }; + + // = Initialization methods. + /// Constructor, initializes the bitmask to all 0s. + ACE_Handle_Set (void); + + /** + * Constructor, initializes the handle set from a given mask. + */ + ACE_Handle_Set (const fd_set &mask); + + // = Methods for manipulating bitsets. + /// Initialize the bitmask to all 0s and reset the associated fields. + void reset (void); + + /** + * Checks whether @a handle is enabled. No range checking is + * performed so @a handle must be less than + * @c ACE_DEFAULT_SELECT_REACTOR_SIZE. + */ + int is_set (ACE_HANDLE handle) const; + + /// Enables the @a handle. No range checking is performed so @a handle + /// must be less than @c ACE_DEFAULT_SELECT_REACTOR_SIZE. + void set_bit (ACE_HANDLE handle); + + /// Disables the @a handle. No range checking is performed so + /// @a handle must be less than @c ACE_DEFAULT_SELECT_REACTOR_SIZE. + void clr_bit (ACE_HANDLE handle); + + /// Returns a count of the number of enabled bits. + int num_set (void) const; + + /// Returns the number of the large bit. + ACE_HANDLE max_set (void) const; + + /** + * Rescan the underlying @c fd_set up to handle @a max to find the new + * (highest bit set) and (how many bits set) values. + * This is useful for evaluating the changes after the handle set has + * been manipulated in some way other than member functions; for example, + * after + ACE_Select_Reactor_Handle_Set dispatch_set_; + + /// Tracks handles that are waited for by . + ACE_Select_Reactor_Handle_Set ready_set_; + + /// Defined as a pointer to allow overriding by derived classes... + ACE_Timer_Queue *timer_queue_; + + /// Handle signals without requiring global/static variables. + ACE_Sig_Handler *signal_handler_; + + /// Callback object that unblocks the ACE_Select_Reactor if it's + /// sleeping. + ACE_Reactor_Notify *notify_handler_; + + /// Keeps track of whether we should delete the timer queue (if we + /// didn't create it, then we don't delete it). + bool delete_timer_queue_; + + /// Keeps track of whether we should delete the signal handler (if we + /// didn't create it, then we don't delete it). + bool delete_signal_handler_; + + /// Keeps track of whether we need to delete the notify handler (if + /// we didn't create it, then we don't delete it). + bool delete_notify_handler_; + + /// True if we've been initialized yet... + bool initialized_; + + /// Restart the event-loop method automatically when + /// . + + if (number_of_active_handles == 0) + { + do + { + if (this->timer_queue_ == 0) + return 0; + + this_timeout = + this->timer_queue_->calculate_timeout (max_wait_time, + &timer_buf); +#ifdef ACE_WIN32 + // This arg is ignored on Windows and causes pointer + // truncation warnings on 64-bit compiles. + int const width = 0; +#else + int const width = this->handler_rep_.max_handlep1 (); +#endif /* ACE_WIN32 */ + + dispatch_set.rd_mask_ = this->wait_set_.rd_mask_; + dispatch_set.wr_mask_ = this->wait_set_.wr_mask_; + dispatch_set.ex_mask_ = this->wait_set_.ex_mask_; + number_of_active_handles = ACE_OS::select (width, + dispatch_set.rd_mask_, + dispatch_set.wr_mask_, + dispatch_set.ex_mask_, + this_timeout); + } + while (number_of_active_handles == -1 && this->handle_error () > 0); + + if (number_of_active_handles > 0) + { +#if !defined (ACE_WIN32) + // Resynchronize the fd_sets so their "max" is set properly. + dispatch_set.rd_mask_.sync (this->handler_rep_.max_handlep1 ()); + dispatch_set.wr_mask_.sync (this->handler_rep_.max_handlep1 ()); + dispatch_set.ex_mask_.sync (this->handler_rep_.max_handlep1 ()); +#endif /* ACE_WIN32 */ + } + else if (number_of_active_handles == -1) + { + // Normally, select() will reset the bits in dispatch_set + // so that only those filed descriptors that are ready will + // have bits set. However, when an error occurs, the bit + // set remains as it was when the select call was first made. + // Thus, we now have a dispatch_set that has every file + // descriptor that was originally waited for, which is not + // correct. We must clear all the bit sets because we + // have no idea if any of the file descriptors is ready. + // + // NOTE: We dont have a test case to reproduce this + // problem. But pleae dont ignore this and remove it off. + dispatch_set.rd_mask_.reset (); + dispatch_set.wr_mask_.reset (); + dispatch_set.ex_mask_.reset (); + } + } + + // Return the number of events to dispatch. + return number_of_active_handles; +} + +template int +ACE_Select_Reactor_T::dispatch_timer_handlers + (int &number_of_handlers_dispatched) +{ + number_of_handlers_dispatched += this->timer_queue_->expire (); + + return 0; +} + +template int +ACE_Select_Reactor_T::dispatch_notification_handlers + (ACE_Select_Reactor_Handle_Set &dispatch_set, + int &number_of_active_handles, + int &number_of_handlers_dispatched) +{ + // Check to see if the ACE_HANDLE associated with the + // Select_Reactor's notify hook is enabled. If so, it means that + // one or more other threads are trying to update the + // ACE_Select_Reactor_T's internal tables or the notify pipe is + // enabled. We'll handle all these threads and notifications, and + // then break out to continue the event loop. + int const n = + this->notify_handler_->dispatch_notifications (number_of_active_handles, + dispatch_set.rd_mask_); + + if (n == -1) + return -1; + else + { + number_of_handlers_dispatched += n; + number_of_active_handles -= n; + } + + // Same as dispatch_timer_handlers + // No need to do anything with the state changed. That is because + // unbind already handles the case where someone unregister some + // kind of handle and unbind it. (::unbind calls the function + // state_changed () to reflect ant change with that) + // return this->state_changed_ ? -1 : 0; + return 0; +} + +template int +ACE_Select_Reactor_T::dispatch_io_set + (int number_of_active_handles, + int &number_of_handlers_dispatched, + int mask, + ACE_Handle_Set &dispatch_mask, + ACE_Handle_Set &ready_mask, + ACE_EH_PTMF callback) +{ + ACE_TRACE ("ACE_Select_Reactor_T::dispatch_io_set"); + ACE_HANDLE handle; + + ACE_Handle_Set_Iterator handle_iter (dispatch_mask); + + while ((handle = handle_iter ()) != ACE_INVALID_HANDLE && + number_of_handlers_dispatched < number_of_active_handles) + { + ++number_of_handlers_dispatched; + + this->notify_handle (handle, + mask, + ready_mask, + this->handler_rep_.find (handle), + callback); + + // clear the bit from that dispatch mask, + // so when we need to restart the iteration (rebuilding the iterator...) + // we will not dispatch the already dispatched handlers + this->clear_dispatch_mask (handle, mask); + + if (this->state_changed_) + { + + handle_iter.reset_state (); + this->state_changed_ = false; + } + } + + return 0; +} + +template int +ACE_Select_Reactor_T::dispatch_io_handlers + (ACE_Select_Reactor_Handle_Set &dispatch_set, + int &number_of_active_handles, + int &number_of_handlers_dispatched) +{ + ACE_TRACE ("ACE_Select_Reactor_T::dispatch_io_handlers"); + + // Handle output events (this code needs to come first to handle the + // obscure case of piggy-backed data coming along with the final + // handshake message of a nonblocking connection). + + if (this->dispatch_io_set (number_of_active_handles, + number_of_handlers_dispatched, + ACE_Event_Handler::WRITE_MASK, + dispatch_set.wr_mask_, + this->ready_set_.wr_mask_, + &ACE_Event_Handler::handle_output) == -1) + { + number_of_active_handles -= number_of_handlers_dispatched; + return -1; + } + + // ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("ACE_Select_Reactor_T::dispatch - EXCEPT\n"))); + if (this->dispatch_io_set (number_of_active_handles, + number_of_handlers_dispatched, + ACE_Event_Handler::EXCEPT_MASK, + dispatch_set.ex_mask_, + this->ready_set_.ex_mask_, + &ACE_Event_Handler::handle_exception) == -1) + { + number_of_active_handles -= number_of_handlers_dispatched; + return -1; + } + + // ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("ACE_Select_Reactor_T::dispatch - READ\n"))); + if (this->dispatch_io_set (number_of_active_handles, + number_of_handlers_dispatched, + ACE_Event_Handler::READ_MASK, + dispatch_set.rd_mask_, + this->ready_set_.rd_mask_, + &ACE_Event_Handler::handle_input) == -1) + { + number_of_active_handles -= number_of_handlers_dispatched; + return -1; + } + + number_of_active_handles -= number_of_handlers_dispatched; + return 0; +} + +template int +ACE_Select_Reactor_T::dispatch + (int active_handle_count, + ACE_Select_Reactor_Handle_Set &dispatch_set) +{ + ACE_TRACE ("ACE_Select_Reactor_T::dispatch"); + + int io_handlers_dispatched = 0; + int other_handlers_dispatched = 0; + int signal_occurred = 0; + // The following do/while loop keeps dispatching as long as there + // are still active handles. Note that the only way we should ever + // iterate more than once through this loop is if signals occur + // while we're dispatching other handlers. + + do + { + // We expect that the loop will decrease the number of active + // handles in each iteration. If it does not, then something is + // inconsistent in the state of the Reactor and we should avoid + // the loop. Please read the comments on bug 2540 for more + // details. + int initial_handle_count = active_handle_count; + + // Note that we keep track of changes to our state. If any of + // the dispatch_*() methods below return -1 it means that the + // state has changed as the result of an + // being dispatched. This means that we + // need to bail out and rerun the select() loop since our + // existing notion of handles in may no longer be + // correct. + // + // In the beginning, our state starts out unchanged. After + // every iteration (i.e., due to signals), our state starts out + // unchanged again. + + this->state_changed_ = false; + + // Perform the Template Method for dispatching all the handlers. + + // First check for interrupts. + if (active_handle_count == -1) + { + // Bail out -- we got here since /. Pass over both the Event_Handler *and* the + * @a mask to allow the caller to dictate which + * method the will invoke. The ACE_Time_Value + * indicates how long to blocking trying to notify the + * . If @a timeout == 0, the caller will block until + * action is possible, else will wait until the relative time + * specified in *@a timeout elapses). + */ + virtual int notify (ACE_Event_Handler * = 0, + ACE_Reactor_Mask = ACE_Event_Handler::EXCEPT_MASK, + ACE_Time_Value * = 0); + + /** + * Set the maximum number of times that the + * method will iterate and + * dispatch the ACE_Event_Handlers that are passed in via the + * notify pipe before breaking out of its loop. By default, + * this is set to -1, which means "iterate until the pipe is empty." + * Setting this to a value like "1 or 2" will increase "fairness" + * (and thus prevent starvation) at the expense of slightly higher + * dispatching overhead. + */ + virtual void max_notify_iterations (int); + + /** + * Get the maximum number of times that the + * method will iterate and + * dispatch the ACE_Event_Handlers that are passed in via the + * notify pipe before breaking out of its loop. + */ + virtual int max_notify_iterations (void); + + /// Get the existing restart value. + virtual bool restart (void); + + /// Set a new value for restart and return the original value. + virtual bool restart (bool r); + + /// Set position that the main ACE_Select_Reactor thread is requeued in the + /// list of waiters during a callback. + virtual void requeue_position (int); + + /// Get position that the main ACE_Select_Reactor thread is requeued in the + /// list of waiters during a callback. + virtual int requeue_position (void); + + // = Low-level wait_set mask manipulation methods. + /// GET/SET/ADD/CLR the dispatch mask "bit" bound with the @a eh and + /// @a mask. + virtual int mask_ops (ACE_Event_Handler *eh, + ACE_Reactor_Mask mask, + int ops); + + /// GET/SET/ADD/CLR the dispatch MASK "bit" bound with the @a handle + /// and @a mask. + virtual int mask_ops (ACE_HANDLE handle, + ACE_Reactor_Mask mask, + int ops); + + // = Low-level ready_set mask manipulation methods. + /// GET/SET/ADD/CLR the ready "bit" bound with the @a eh and @a mask. + virtual int ready_ops (ACE_Event_Handler *eh, + ACE_Reactor_Mask mask, + int ops); + + /// GET/SET/ADD/CLR the ready "bit" bound with the @a handle and @a mask. + virtual int ready_ops (ACE_HANDLE handle, + ACE_Reactor_Mask, + int ops); + + /// Wake up all threads in waiting in the event loop + virtual void wakeup_all_threads (void); + + // = Only the owner thread can perform a . + + /// Set the new owner of the thread and return the old owner. + virtual int owner (ACE_thread_t n_id, ACE_thread_t *o_id = 0); + + /// Return the current owner of the thread. + virtual int owner (ACE_thread_t *); + + // = Miscellaneous Handler operations. + + /** + * Return the Event_Handler associated with @a handle. Return 0 if + * @a handle is not registered. + */ + virtual ACE_Event_Handler *find_handler (ACE_HANDLE handle); + + /** + * Check to see if @a handle is associated with a valid Event_Handler + * bound to @a mask. Return the @a eh associated with this @a handler + * if @a eh != 0. + */ + virtual int handler (ACE_HANDLE handle, + ACE_Reactor_Mask mask, + ACE_Event_Handler **eh = 0); + + /** + * Check to see if @a signum is associated with a valid Event_Handler + * bound to a signal. Return the @a eh associated with this + * handler if @a eh != 0. + */ + virtual int handler (int signum, + ACE_Event_Handler ** = 0); + + /// Returns true if we've been successfully initialized, else false. + virtual bool initialized (void); + + /// Returns the current size of the Reactor's internal descriptor + /// table. + virtual size_t size (void) const; + + /** + * Returns a reference to the ACE_Reactor_Token that is + * used to serialize the internal processing logic. + * This can be useful for situations where you need to avoid + * deadlock efficiently when ACE_Event_Handlers are used in + * multiple threads. + */ + virtual ACE_Lock &lock (void); + + /// Dump the state of an object. + virtual void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + // = Internal methods that do the actual work. + + // All of these methods assume that the token + // lock is held by the public methods that call down to them. + + /// Do the work of actually binding the @a handle and @a eh with the + /// @a mask. + virtual int register_handler_i (ACE_HANDLE handle, + ACE_Event_Handler *eh, + ACE_Reactor_Mask mask); + + /// Register a set of @a handles. + virtual int register_handler_i (const ACE_Handle_Set &handles, + ACE_Event_Handler *handler, + ACE_Reactor_Mask mask); + + /// Do the work of actually unbinding the @a handle and @a eh with the + /// @a mask. + virtual int remove_handler_i (ACE_HANDLE handle, + ACE_Reactor_Mask); + + /// Remove a set of @a handles. + virtual int remove_handler_i (const ACE_Handle_Set &handles, + ACE_Reactor_Mask); + + /// Suspend the associated with @a handle + virtual int suspend_i (ACE_HANDLE handle); + + /// Check to see if the associated with @a handle is + /// suspended. Returns 0 if not, 1 if so. + virtual int is_suspended_i (ACE_HANDLE handle); + + /// Resume the associated with @a handle + virtual int resume_i (ACE_HANDLE handle); + + /// Implement the public handler method. + virtual ACE_Event_Handler *find_handler_i (ACE_HANDLE handle); + + /// Implement the public handler method. + virtual int handler_i (ACE_HANDLE handle, + ACE_Reactor_Mask, + ACE_Event_Handler ** = 0); + + /// Implement the public handler method. + virtual int handler_i (int signum, ACE_Event_Handler ** = 0); + + /** + * Check if there are any HANDLEs enabled in the , and + * if so, update the @a handle_set and return the number ready. If + * there aren't any HANDLEs enabled return 0. + */ + virtual int any_ready (ACE_Select_Reactor_Handle_Set &handle_set); + + /// Implement the method, assuming that the Sig_Guard is + /// beign held + virtual int any_ready_i (ACE_Select_Reactor_Handle_Set &handle_set); + + /// Take corrective action when errors occur. + virtual int handle_error (void); + + /// Make sure the handles are all valid. + virtual int check_handles (void); + + /// Wait for events to occur. + virtual int wait_for_multiple_events (ACE_Select_Reactor_Handle_Set &, + ACE_Time_Value *); + + // = Dispatching methods. + + /** + * Template Method that dispatches ACE_Event_Handlers for time + * events, I/O events, and signal events. Returns the total number + * of ACE_Event_Handlers that were dispatched or -1 if something + * goes wrong. + */ + virtual int dispatch (int nfound, + ACE_Select_Reactor_Handle_Set &); + + /** + * Dispatch all timer handlers that have expired. Returns -1 if the + * state of the has changed, else 0. + * is set to the number of timer handlers + * dispatched. + */ + virtual int dispatch_timer_handlers (int &number_dispatched); + + /** + * Dispatch any notification handlers. Returns -1 if the state of + * the has changed, else returns number of handlers + * notified. + */ + virtual int dispatch_notification_handlers (ACE_Select_Reactor_Handle_Set &dispatch_set, + int &number_of_active_handles, + int &number_of_handlers_dispatched); + + /** + * Dispatch all the input/output/except handlers that are enabled in + * the @a dispatch_set. Updates @a number_of_active_handles and + * @a number_of_handlers_dispatched according to the behavior of the + * number Returns -1 if the state of the has changed, + * else 0. + */ + virtual int dispatch_io_handlers (ACE_Select_Reactor_Handle_Set &dispatch_set, + int &number_of_active_handles, + int &number_of_handlers_dispatched); + + /** + * Factors the dispatching of an io handle set (each WRITE, EXCEPT + * or READ set of handles). It updates the + * @a number_of_handlers_dispatched and invokes this->notify_handle + * for all the handles in using the @a mask, + * and @a callback parameters. Must return -1 if + * this->state_changed otherwise it must return 0. + */ + virtual int dispatch_io_set (int number_of_active_handles, + int &number_of_handlers_dispatched, + int mask, + ACE_Handle_Set& dispatch_mask, + ACE_Handle_Set& ready_mask, + ACE_EH_PTMF callback); + + /// Notify the appropriate @a callback in the context of the @a eh + /// associated with @a handle that a particular event has occurred. + virtual void notify_handle (ACE_HANDLE handle, + ACE_Reactor_Mask mask, + ACE_Handle_Set &, + ACE_Event_Handler *eh, + ACE_EH_PTMF callback); + + /// Enqueue ourselves into the list of waiting threads at the + /// appropriate point specified by . + virtual void renew (void); + + /// Synchronization token for the MT_SAFE ACE_Select_Reactor. + ACE_SELECT_REACTOR_TOKEN token_; + + /// Adapter used to return internal lock to outside world. + ACE_Lock_Adapter lock_adapter_; + + /// Release the token lock when a Win32 structured exception occurs. + int release_token (void); + + /// Stops the VC++ compiler from bitching about exceptions and destructors + int handle_events_i (ACE_Time_Value *max_wait_time = 0); + + /// This flag is used to keep track of whether we are actively handling + /// events or not. + sig_atomic_t deactivated_; + +private: + /// Deny access since member-wise won't work... + ACE_UNIMPLEMENTED_FUNC (ACE_Select_Reactor_T (const ACE_Select_Reactor_T &)) + ACE_UNIMPLEMENTED_FUNC (ACE_Select_Reactor_T &operator= (const ACE_Select_Reactor_T &) ) +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Select_Reactor_T.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Select_Reactor_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Select_Reactor_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" +#endif /* ACE_SELECT_REACTOR_T_H */ diff --git a/dep/acelite/ace/Select_Reactor_T.inl b/dep/acelite/ace/Select_Reactor_T.inl new file mode 100644 index 00000000000..30c8cbc6b7d --- /dev/null +++ b/dep/acelite/ace/Select_Reactor_T.inl @@ -0,0 +1,236 @@ +// -*- C++ -*- +// +// $Id: Select_Reactor_T.inl 82723 2008-09-16 09:35:44Z johnnyw $ + +#include "ace/Reactor.h" +#include "ace/Signal.h" +#include "ace/Sig_Handler.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template +ACE_INLINE int +ACE_Select_Reactor_T::resume_handler (ACE_Event_Handler *h) +{ + ACE_TRACE ("ACE_Select_Reactor_T::resume_handler"); + return this->resume_handler (h->get_handle ()); +} + +template +ACE_INLINE int +ACE_Select_Reactor_T::resume_handler (const ACE_Handle_Set &handles) +{ + ACE_TRACE ("ACE_Select_Reactor_T::resume_handler"); + ACE_Handle_Set_Iterator handle_iter (handles); + ACE_HANDLE h; + + ACE_MT (ACE_GUARD_RETURN (ACE_SELECT_REACTOR_TOKEN, ace_mon, this->token_, -1)); + + while ((h = handle_iter ()) != ACE_INVALID_HANDLE) + if (this->resume_i (h) == -1) + return -1; + + return 0; +} + +template +ACE_INLINE int +ACE_Select_Reactor_T::suspend_handler (ACE_Event_Handler *h) +{ + ACE_TRACE ("ACE_Select_Reactor_T::suspend_handler"); + return this->suspend_handler (h->get_handle ()); +} + +template +ACE_INLINE int +ACE_Select_Reactor_T::suspend_handler (const ACE_Handle_Set &handles) +{ + ACE_TRACE ("ACE_Select_Reactor_T::suspend_handler"); + ACE_Handle_Set_Iterator handle_iter (handles); + ACE_HANDLE h; + + ACE_MT (ACE_GUARD_RETURN (ACE_SELECT_REACTOR_TOKEN, ace_mon, this->token_, -1)); + + while ((h = handle_iter ()) != ACE_INVALID_HANDLE) + if (this->suspend_i (h) == -1) + return -1; + + return 0; +} + +template +ACE_INLINE int +ACE_Select_Reactor_T::register_handler (int signum, + ACE_Event_Handler *new_sh, + ACE_Sig_Action *new_disp, + ACE_Event_Handler **old_sh, + ACE_Sig_Action *old_disp) +{ + ACE_TRACE ("ACE_Select_Reactor_T::register_handler"); + return this->signal_handler_->register_handler (signum, + new_sh, new_disp, + old_sh, old_disp); +} + +#if defined (ACE_WIN32) + +template +ACE_INLINE int +ACE_Select_Reactor_T::register_handler (ACE_Event_Handler *, + ACE_HANDLE ) +{ + // Don't have an implementation for this yet... + ACE_NOTSUP_RETURN (-1); +} + +#endif /* ACE_WIN32 */ + +template +ACE_INLINE int +ACE_Select_Reactor_T::register_handler (ACE_HANDLE , + ACE_HANDLE , + ACE_Event_Handler *, + ACE_Reactor_Mask ) +{ + // Don't have an implementation for this yet... + ACE_NOTSUP_RETURN (-1); +} + +template +ACE_INLINE int +ACE_Select_Reactor_T::handler (int signum, ACE_Event_Handler **handler) +{ + ACE_TRACE ("ACE_Select_Reactor_T::handler"); + return this->handler_i (signum, handler); +} + +template +ACE_INLINE int +ACE_Select_Reactor_T::remove_handler (int signum, + ACE_Sig_Action *new_disp, + ACE_Sig_Action *old_disp, + int sigkey) +{ + ACE_TRACE ("ACE_Select_Reactor_T::remove_handler"); + return this->signal_handler_->remove_handler (signum, new_disp, old_disp, sigkey); +} + +template +ACE_INLINE bool +ACE_Select_Reactor_T::uses_event_associations (void) +{ + // Since the Select_Reactor does not do any event associations, this + // function always return false. + return false; +} + +// = The remaining methods in this file must be called with locks +// held. + +// Performs operations on the "ready" bits. + +template ACE_INLINE int +ACE_Select_Reactor_T::ready_ops (ACE_Event_Handler *handler, + ACE_Reactor_Mask mask, + int ops) +{ + ACE_TRACE ("ACE_Select_Reactor_T::ready_ops"); + return this->ready_ops (handler->get_handle (), mask, ops); +} + +// Performs operations on the "dispatch" masks. + +template ACE_INLINE int +ACE_Select_Reactor_T::mask_ops (ACE_Event_Handler *handler, + ACE_Reactor_Mask mask, + int ops) +{ + ACE_TRACE ("ACE_Select_Reactor_T::mask_ops"); + return this->mask_ops (handler->get_handle (), mask, ops); +} + +template ACE_INLINE int +ACE_Select_Reactor_T::schedule_wakeup (ACE_Event_Handler *eh, + ACE_Reactor_Mask mask) +{ + ACE_TRACE ("ACE_Select_Reactor_T::schedule_wakeup"); + return this->mask_ops (eh->get_handle (), mask, ACE_Reactor::ADD_MASK); +} + +template ACE_INLINE int +ACE_Select_Reactor_T::cancel_wakeup (ACE_Event_Handler *eh, + ACE_Reactor_Mask mask) +{ + ACE_TRACE ("ACE_Select_Reactor_T::cancel_wakeup"); + return this->mask_ops (eh->get_handle (), mask, ACE_Reactor::CLR_MASK); +} + +template ACE_INLINE int +ACE_Select_Reactor_T::schedule_wakeup (ACE_HANDLE handle, + ACE_Reactor_Mask mask) +{ + ACE_TRACE ("ACE_Select_Reactor_T::schedule_wakeup"); + return this->mask_ops (handle, mask, ACE_Reactor::ADD_MASK); +} + +template ACE_INLINE int +ACE_Select_Reactor_T::cancel_wakeup (ACE_HANDLE handle, + ACE_Reactor_Mask mask) +{ + ACE_TRACE ("ACE_Select_Reactor_T::cancel_wakeup"); + return this->mask_ops (handle, mask, ACE_Reactor::CLR_MASK); +} + +template ACE_INLINE ACE_Lock & +ACE_Select_Reactor_T::lock (void) +{ + ACE_TRACE ("ACE_Select_Reactor_T::lock"); + return this->lock_adapter_; +} + +template ACE_INLINE void +ACE_Select_Reactor_T::wakeup_all_threads (void) +{ + // Send a notification, but don't block if there's no one to receive + // it. + this->notify (0, ACE_Event_Handler::NULL_MASK, (ACE_Time_Value *) &ACE_Time_Value::zero); +} + +template ACE_INLINE int +ACE_Select_Reactor_T::alertable_handle_events (ACE_Time_Value *max_wait_time) +{ + return this->handle_events (max_wait_time); +} + +template ACE_INLINE int +ACE_Select_Reactor_T::alertable_handle_events (ACE_Time_Value &max_wait_time) +{ + return this->handle_events (max_wait_time); +} + +template ACE_INLINE int +ACE_Select_Reactor_T::deactivated (void) +{ + return this->deactivated_; +} + +template ACE_INLINE void +ACE_Select_Reactor_T::deactivate (int do_stop) +{ + { + ACE_MT (ACE_GUARD (ACE_SELECT_REACTOR_TOKEN, + ace_mon, + this->token_)); + this->deactivated_ = do_stop; + } + + this->wakeup_all_threads (); +} + +template ACE_INLINE size_t +ACE_Select_Reactor_T::size (void) const +{ + return this->handler_rep_.size (); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Semaphore.cpp b/dep/acelite/ace/Semaphore.cpp new file mode 100644 index 00000000000..2be156b8d7c --- /dev/null +++ b/dep/acelite/ace/Semaphore.cpp @@ -0,0 +1,64 @@ +// $Id: Semaphore.cpp 84282 2009-01-30 15:04:29Z msmit $ + +#include "ace/Semaphore.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Semaphore.inl" +#endif /* __ACE_INLINE__ */ + +#include "ace/Log_Msg.h" +#include "ace/ACE.h" + +ACE_RCSID (ace, + Semaphore, + "$Id: Semaphore.cpp 84282 2009-01-30 15:04:29Z msmit $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Semaphore) + +void +ACE_Semaphore::dump (void) const +{ +#if defined (ACE_HAS_DUMP) +// ACE_TRACE ("ACE_Semaphore::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n"))); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +ACE_Semaphore::ACE_Semaphore (unsigned int count, + int type, + const ACE_TCHAR *name, + void *arg, + int max) + : removed_ (false) +{ +// ACE_TRACE ("ACE_Semaphore::ACE_Semaphore"); +#if defined(ACE_LACKS_UNNAMED_SEMAPHORE) +// if the user does not provide a name, we generate a unique name here + ACE_TCHAR iname[ACE_UNIQUE_NAME_LEN]; + if (name == 0) + ACE::unique_name (this, iname, ACE_UNIQUE_NAME_LEN); + if (ACE_OS::sema_init (&this->semaphore_, count, type, + name ? name : iname, + arg, max) != 0) +#else + if (ACE_OS::sema_init (&this->semaphore_, count, type, + name, arg, max) != 0) +#endif + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_Semaphore::ACE_Semaphore"))); +} + +ACE_Semaphore::~ACE_Semaphore (void) +{ +// ACE_TRACE ("ACE_Semaphore::~ACE_Semaphore"); + + this->remove (); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Semaphore.h b/dep/acelite/ace/Semaphore.h new file mode 100644 index 00000000000..7c4936abfd3 --- /dev/null +++ b/dep/acelite/ace/Semaphore.h @@ -0,0 +1,183 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file Semaphore.h + * + * $Id: Semaphore.h 81014 2008-03-19 11:41:31Z johnnyw $ + * + * Moved from Synch.h. + * + * @author Douglas C. Schmidt + */ +//========================================================================== + +#ifndef ACE_SEMAPHORE_H +#define ACE_SEMAPHORE_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/OS_NS_Thread.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +class ACE_Time_Value; + +/** + * @class ACE_Semaphore + * + * @brief Wrapper for Dijkstra style general semaphores. + */ +class ACE_Export ACE_Semaphore +{ +public: + // = Initialization and termination. + /// Initialize the semaphore, with initial value of "count". + ACE_Semaphore (unsigned int count = 1, // By default make this unlocked. + int type = USYNC_THREAD, + const ACE_TCHAR *name = 0, + void * = 0, + int max = 0x7fffffff); + + /// Implicitly destroy the semaphore. + ~ACE_Semaphore (void); + + /** + * Explicitly destroy the semaphore. Note that only one thread + * should call this method since it doesn't protect against race + * conditions. + */ + int remove (void); + + /// Block the thread until the semaphore count becomes + /// greater than 0, then decrement it. + int acquire (void); + + /** + * Block the thread until the semaphore count becomes greater than 0 + * (at which point it is decremented) or until @a tv times out (in + * which case -1 is returned and @c errno == @c ETIME). Note that @a tv + * is assumed to be in "absolute" rather than "relative" time. The + * value of @a tv is updated upon return to show the actual + * (absolute) acquisition time. + * + * @note Solaris threads do not support timed semaphores. + * Therefore, if you're running on Solaris you might want to + * consider using the ACE POSIX pthreads implementation instead, + * which can be enabled by compiling ACE with + * -DACE_HAS_PTHREADS, rather than -DACE_HAS_STHREADS or + * -DACE_HAS_POSIX_SEM. + */ + int acquire (ACE_Time_Value &tv); + + /** + * If @a tv == 0 then call directly. Otherwise, Block + * the thread until the semaphore count becomes greater than 0 + * (at which point it is decremented) or until @a tv times out (in + * which case -1 is returned and @c errno == @c ETIME). Note that + * <*tv> is assumed to be in "absolute" rather than "relative" time. + * The value of <*tv> is updated upon return to show the actual + * (absolute) acquisition time. + * + * @note Solaris threads do not support timed semaphores. + * Therefore, if you're running on Solaris you might want to + * consider using the ACE POSIX pthreads implementation instead, + * which can be enabled by compiling ACE with + * -DACE_HAS_PTHREADS, rather than -DACE_HAS_STHREADS or + * -DACE_HAS_POSIX_SEM. */ + int acquire (ACE_Time_Value *tv); + + /** + * Conditionally decrement the semaphore if count is greater than 0 + * (i.e., won't block). Returns -1 on failure. If we "failed" + * because someone else already had the lock, @c errno is set to + * @c EBUSY. + */ + int tryacquire (void); + + /// Increment the semaphore by 1, potentially unblocking a waiting + /// thread. + int release (void); + + /// Increment the semaphore by @a release_count, potentially + /// unblocking waiting threads. + int release (unsigned int release_count); + + /** + * Acquire semaphore ownership. This calls and is only + * here to make the ACE_Semaphore interface consistent with the + * other synchronization APIs. + */ + int acquire_read (void); + + /** + * Acquire semaphore ownership. This calls and is only + * here to make the ACE_Semaphore interface consistent with the + * other synchronization APIs. + */ + int acquire_write (void); + + /** + * Conditionally acquire semaphore (i.e., won't block). This calls + * and is only here to make the ACE_Semaphore + * interface consistent with the other synchronization APIs. + * Returns -1 on failure. If we "failed" because someone else + * already had the lock, @c errno is set to @c EBUSY. + */ + int tryacquire_read (void); + + /** + * Conditionally acquire semaphore (i.e., won't block). This calls + * and is only here to make the ACE_Semaphore + * interface consistent with the other synchronization APIs. + * Returns -1 on failure. If we "failed" because someone else + * already had the lock, @c errno is set to @c EBUSY. + */ + int tryacquire_write (void); + + /** + * This is only here to make the ACE_Semaphore + * interface consistent with the other synchronization APIs. + * Assumes the caller has already acquired the semaphore using one of + * the above calls, and returns 0 (success) always. + */ + int tryacquire_write_upgrade (void); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + + /// Return the underlying lock. + const ACE_sema_t &lock (void) const; + +protected: + ACE_sema_t semaphore_; + + /// Keeps track of whether remove() has been called yet to avoid + /// multiple remove() calls, e.g., explicitly and implicitly in the + /// destructor. This flag isn't protected by a lock, so make sure + /// that you don't have multiple threads simultaneously calling + /// remove () on the same object, which is a bad idea anyway... + bool removed_; + +private: + // = Prevent assignment and initialization. + void operator= (const ACE_Semaphore &); + ACE_Semaphore (const ACE_Semaphore &); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Semaphore.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_SEMAPHORE_H */ diff --git a/dep/acelite/ace/Semaphore.inl b/dep/acelite/ace/Semaphore.inl new file mode 100644 index 00000000000..e0162dc247b --- /dev/null +++ b/dep/acelite/ace/Semaphore.inl @@ -0,0 +1,119 @@ +// -*- C++ -*- +// +// $Id: Semaphore.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE const ACE_sema_t & +ACE_Semaphore::lock (void) const +{ +// ACE_TRACE ("ACE_Semaphore::lock"); + return this->semaphore_; +} + +ACE_INLINE int +ACE_Semaphore::remove (void) +{ +// ACE_TRACE ("ACE_Semaphore::remove"); + int result = 0; + if (!this->removed_) + { + this->removed_ = true; + result = ACE_OS::sema_destroy (&this->semaphore_); + } + return result; +} + +ACE_INLINE int +ACE_Semaphore::acquire (void) +{ +// ACE_TRACE ("ACE_Semaphore::acquire"); + return ACE_OS::sema_wait (&this->semaphore_); +} + +ACE_INLINE int +ACE_Semaphore::acquire (ACE_Time_Value &tv) +{ +// ACE_TRACE ("ACE_Semaphore::acquire"); + return ACE_OS::sema_wait (&this->semaphore_, tv); +} + +ACE_INLINE int +ACE_Semaphore::acquire (ACE_Time_Value *tv) +{ +// ACE_TRACE ("ACE_Semaphore::acquire"); + return ACE_OS::sema_wait (&this->semaphore_, tv); +} + +ACE_INLINE int +ACE_Semaphore::tryacquire (void) +{ +// ACE_TRACE ("ACE_Semaphore::tryacquire"); + return ACE_OS::sema_trywait (&this->semaphore_); +} + +ACE_INLINE int +ACE_Semaphore::release (void) +{ +// ACE_TRACE ("ACE_Semaphore::release"); + return ACE_OS::sema_post (&this->semaphore_); +} + +ACE_INLINE int +ACE_Semaphore::release (unsigned int release_count) +{ +// ACE_TRACE ("ACE_Semaphore::release"); + return ACE_OS::sema_post (&this->semaphore_, release_count); +} + +// Acquire semaphore ownership. This calls and is only +// here to make the interface consistent with the +// other synchronization APIs. + +ACE_INLINE int +ACE_Semaphore::acquire_read (void) +{ + return this->acquire (); +} + +// Acquire semaphore ownership. This calls and is only +// here to make the interface consistent with the +// other synchronization APIs. + +ACE_INLINE int +ACE_Semaphore::acquire_write (void) +{ + return this->acquire (); +} + +// Conditionally acquire semaphore (i.e., won't block). This calls +// and is only here to make the +// interface consistent with the other synchronization APIs. + +ACE_INLINE int +ACE_Semaphore::tryacquire_read (void) +{ + return this->tryacquire (); +} + +// Conditionally acquire semaphore (i.e., won't block). This calls +// and is only here to make the +// interface consistent with the other synchronization APIs. + +ACE_INLINE int +ACE_Semaphore::tryacquire_write (void) +{ + return this->tryacquire (); +} + +// This is only here to make the interface consistent +// with the other synchronization APIs. Assumes the caller has +// already acquired the semaphore using one of the above calls, and +// returns 0 (success) always. +ACE_INLINE int +ACE_Semaphore::tryacquire_write_upgrade (void) +{ + return 0; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Service_Config.cpp b/dep/acelite/ace/Service_Config.cpp new file mode 100644 index 00000000000..b1ec0329eb5 --- /dev/null +++ b/dep/acelite/ace/Service_Config.cpp @@ -0,0 +1,610 @@ +// $Id: Service_Config.cpp 84619 2009-02-26 12:26:16Z johnnyw $ + +#include "ace/Service_Config.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Service_Config.inl" +#endif /* __ACE_INLINE__ */ + +#include "ace/Service_Types.h" +#include "ace/Reactor.h" +#include "ace/Singleton.h" +#include "ace/Service_Repository.h" + +#ifndef ACE_LACKS_UNIX_SIGNALS +# include "ace/Sig_Adapter.h" +#endif /* !ACE_LACKS_UNIX_SIGNALS */ + +#include "ace/OS_NS_time.h" +#include "ace/OS_NS_stdio.h" +#include "ace/OS_NS_unistd.h" +#include "ace/Thread.h" +#include "ace/Get_Opt.h" +#include "ace/ARGV.h" +#include "ace/Log_Msg.h" +#include "ace/ACE.h" + +ACE_RCSID (ace, + Service_Config, + "$Id: Service_Config.cpp 84619 2009-02-26 12:26:16Z johnnyw $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_Threading_Helper::~ACE_Threading_Helper () +{ + ACE_OS::thr_key_detach (this->key_, 0); + ACE_OS::thr_keyfree (this->key_); +} + +ACE_Threading_Helper::ACE_Threading_Helper () + : key_ (ACE_OS::NULL_key) +{ +# if defined (ACE_HAS_TSS_EMULATION) + ACE_Object_Manager::init_tss (); +# endif + + if (ACE_Thread::keycreate (&key_, 0, 0) == -1) + { + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("(%P|%t) Failed to create thread key: %p\n"), + ACE_TEXT (""))); + } +} + +void +ACE_Threading_Helper::set (void* p) +{ + if (ACE_Thread::setspecific (key_, p) == -1) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("(%P|%t) Service Config failed to set thread key value: %p\n"), + ACE_TEXT(""))); +} + +void* +ACE_Threading_Helper::get (void) +{ + void* temp = 0; + if (ACE_Thread::getspecific (key_, &temp) == -1) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("(%P|%t) Service Config failed to get thread key value: %p\n"), + ACE_TEXT("")), + 0); + return temp; +} + +ACE_Threading_Helper::~ACE_Threading_Helper () +{ +} + +ACE_Threading_Helper::ACE_Threading_Helper () +{ +} + +void +ACE_Threading_Helper::set (void*) +{ +} + +void* +ACE_Threading_Helper::get (void) +{ + return ACE_Service_Config::singleton()->instance_.get (); +} + +/** + * @c ACE_Service_Config is supposed to be a Singleton. This is the + * only Configuration Gestalt available for access from static + * initializers at proces start-up time. Using Unmanaged Singleton + * is safer because (a) the Object Manager may not yet be fully initialized + * in the context of a static initializer that uses SC, and (b) because we + * know that upon process exit the SC will still be automaticaly and explicitly + * closed by @c ACE_Object_Manager::fini(). + */ +typedef ACE_Unmanaged_Singleton ACE_SERVICE_CONFIG_SINGLETON; + + +/// ctor +ACE_Service_Config_Guard::ACE_Service_Config_Guard (ACE_Service_Gestalt * psg) + : saved_ (ACE_Service_Config::current ()) +{ + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) - SCG:") + ACE_TEXT (" - config=%@ repo=%@ superceded by repo=%@\n"), + this, + this->saved_.get (), + this->saved_->repo_, + psg->repo_)); + + // Modify the TSS if the repo has changed + ACE_Service_Config::current (psg); +} + +ACE_Service_Config_Guard::~ACE_Service_Config_Guard (void) +{ + ACE_Service_Gestalt* s = this->saved_.get (); + ACE_ASSERT (s != 0); + + ACE_Service_Config::current (s); + + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) SCG:") + ACE_TEXT (" - new repo=%@\n"), + this, + this->saved_->repo_)); +} + + +ACE_ALLOC_HOOK_DEFINE (ACE_Service_Config) + +// Set the signal handler to point to the handle_signal() function. +ACE_Sig_Adapter *ACE_Service_Config::signal_handler_ = 0; + +// Trigger a reconfiguration. +sig_atomic_t ACE_Service_Config::reconfig_occurred_ = 0; + +// = Set by command-line options. + +/// Pathname of file to write process id. +ACE_TCHAR *ACE_Service_Config::pid_file_name_ = 0; + +/// Shall we become a daemon process? +bool ACE_Service_Config::be_a_daemon_ = false; + +/// Number of the signal used to trigger reconfiguration. +int ACE_Service_Config::signum_ = SIGHUP; + +void +ACE_Service_Config::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Service_Config::dump"); +#endif /* ACE_HAS_DUMP */ +} + +int +ACE_Service_Config::parse_args_i (int argc, ACE_TCHAR *argv[]) +{ + ACE_TRACE ("ACE_Service_Config::parse_args_i"); + + // Using PERMUTE_ARGS (default) in order to have all + // unrecognized options and their value arguments moved + // to the end of the argument vector. We'll pick them up + // after processing our options and pass them on to the + // base class for further parsing. + //FUZZ: disable check_for_lack_ACE_OS + ACE_Get_Opt getopt (argc, + argv, + ACE_TEXT ("bs:p:"), + 1 , // Start at argv[1]. + 0, // Do not report errors + ACE_Get_Opt::RETURN_IN_ORDER); + //FUZZ: enable check_for_lack_ACE_OS + + //FUZZ: disable check_for_lack_ACE_OS + for (int c; (c = getopt ()) != -1; ) + //FUZZ: enable check_for_lack_ACE_OS + switch (c) + { + case 'p': + ACE_Service_Config::pid_file_name_ = getopt.opt_arg (); + break; + case 'b': + ACE_Service_Config::be_a_daemon_ = true; + break; + case 's': + { + // There's no point in dealing with this on NT since it + // doesn't really support signals very well... +#if !defined (ACE_LACKS_UNIX_SIGNALS) + ACE_Service_Config::signum_ = + ACE_OS::atoi (getopt.opt_arg ()); + + if (ACE_Reactor::instance ()->register_handler + (ACE_Service_Config::signum_, + ACE_Service_Config::signal_handler_) == -1) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("cannot obtain signal handler\n")), + -1); +#endif /* ACE_LACKS_UNIX_SIGNALS */ + break; + } + default:; // unknown arguments are benign + + } + + return 0; +} /* parse_args_i () */ + + +int +ACE_Service_Config::open_i (const ACE_TCHAR program_name[], + const ACE_TCHAR *logger_key, + bool , + bool , + bool ) +{ + ACE_TRACE ("ACE_Service_Config::open_i"); + ACE_MT (ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, ace_mon, this->lock_, -1)); + + ACE_Log_Msg *log_msg = ACE_LOG_MSG; + + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) SC::open_i - this=%@, opened=%d\n"), + this, this->is_opened_)); + + // Guard against reentrant processing. + if (this->is_opened_) + return 0; + + this->is_opened_ = true; + + // Check for things we need to do on a per-process basis and which + // may not be safe, or wise to do an a per instance basis + + // Become a daemon before doing anything else. + if (ACE_Service_Config::be_a_daemon_) + ACE::daemonize (); + + // Write process id to file. + if (this->pid_file_name_ != 0) + { + FILE* pidf = ACE_OS::fopen (this->pid_file_name_, + ACE_TEXT("w")); + + if (pidf != 0) + { + ACE_OS::fprintf (pidf, + "%ld\n", + static_cast (ACE_OS::getpid())); + ACE_OS::fclose (pidf); + } + } + + u_long flags = log_msg->flags (); + + // Only use STDERR if the caller hasn't already set the flags. + if (flags == 0) + flags = (u_long) ACE_Log_Msg::STDERR; + + const ACE_TCHAR *key = logger_key; + + if (key == 0 || ACE_OS::strcmp (key, ACE_DEFAULT_LOGGER_KEY) == 0) + { + // Only use the static if the caller doesn't + // override it in the parameter list or if the key supplied is + // equal to the default static logger key. + key = ACE_Service_Config::current()->logger_key_; + } + else + { + ACE_SET_BITS (flags, ACE_Log_Msg::LOGGER); + } + + if (log_msg->open (program_name, + flags, + key) == -1) + return -1; + + if (ACE::debug ()) + ACE_DEBUG ((LM_STARTUP, + ACE_TEXT ("starting up daemon %n\n"))); + + // Initialize the Service Repository (this will still work if + // user forgets to define an object of type ACE_Service_Config). + ACE_Service_Repository::instance (ACE_Service_Gestalt::MAX_SERVICES); + + // Initialize the ACE_Reactor (the ACE_Reactor should be the + // same size as the ACE_Service_Repository). + ACE_Reactor::instance (); + + // There's no point in dealing with this on NT since it doesn't + // really support signals very well... +#if !defined (ACE_LACKS_UNIX_SIGNALS) + // Only attempt to register a signal handler for positive + // signal numbers. + if (ACE_Service_Config::signum_ > 0) + { + ACE_Sig_Set ss; + ss.sig_add (ACE_Service_Config::signum_); + if ((ACE_Reactor::instance () != 0) && + (ACE_Reactor::instance ()->register_handler + (ss, ACE_Service_Config::signal_handler_) == -1)) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("can't register signal handler\n"))); + } +#endif /* ACE_LACKS_UNIX_SIGNALS */ + + return 0; +} + +/// Return the global configuration instance. Always returns the same +/// instance +ACE_Service_Config * +ACE_Service_Config::singleton (void) +{ + return ACE_SERVICE_CONFIG_SINGLETON::instance (); +} + +int +ACE_Service_Config::insert (ACE_Static_Svc_Descriptor* stsd) +{ + return ACE_Service_Config::instance ()->insert (stsd); +} + + +// Totally remove from the daemon by removing it from the +// ACE_Reactor, and unlinking it if necessary. +int +ACE_Service_Config::remove (const ACE_TCHAR svc_name[]) +{ + ACE_TRACE ("ACE_Service_Config::remove"); + return ACE_Service_Repository::instance ()->remove (svc_name); +} + +// Suspend . Note that this will not unlink the service +// from the daemon if it was dynamically linked, it will mark it as +// being suspended in the Service Repository and call the +// member function on the appropriate . A service +// can be resumed later on by calling the method... + +int +ACE_Service_Config::suspend (const ACE_TCHAR svc_name[]) +{ + ACE_TRACE ("ACE_Service_Config::suspend"); + return ACE_Service_Repository::instance ()->suspend (svc_name); +} + +// Resume a SVC_NAME that was previously suspended or has not yet +// been resumed (e.g., a static service). + +int +ACE_Service_Config::resume (const ACE_TCHAR svc_name[]) +{ + ACE_TRACE ("ACE_Service_Config::resume"); + return ACE_Service_Repository::instance ()->resume (svc_name); +} + + +ACE_Service_Config::ACE_Service_Config (bool ignore_static_svcs, + size_t size, + int signum) +{ + ACE_TRACE ("ACE_Service_Config::ACE_Service_Config"); + + // TODO: Need to find a more customizable way of instantiating the + // gestalt but perhaps we should leave this out untill such + // customizations are identified. + ACE_Service_Gestalt* tmp = 0; + ACE_NEW_NORETURN (tmp, + ACE_Service_Gestalt (size, false, ignore_static_svcs)); + + this->is_opened_ = false; + this->instance_ = tmp; + this->threadkey_.set (tmp); + + ACE_Service_Config::signum_ = signum; +} + +ACE_Service_Config::ACE_Service_Config (const ACE_TCHAR program_name[], + const ACE_TCHAR *logger_key) +{ + ACE_TRACE ("ACE_Service_Config::ACE_Service_Config"); + + // TODO: Need to find a more customizable way of instantiating the + // gestalt but perhaps we should leave this out untill such + // customizations are identified. + ACE_Service_Gestalt* tmp = 0; + ACE_NEW_NORETURN (tmp, + ACE_Service_Gestalt (ACE_Service_Repository::DEFAULT_SIZE, false)); + + this->is_opened_ = false; + this->instance_ = tmp; + this->threadkey_.set (tmp); + + if (this->open (program_name, + logger_key) == -1 && errno != ENOENT) + { + // Only print out an error if it wasn't the svc.conf file that was + // missing. + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("(%P|%t) SC failed to open: %p\n"), + program_name)); + } +} + +/// Return the "global" configuration instance, for the current +/// thread. This may be the same as instance(), but on some occasions, +/// it may be a different one. For example, ACE_Service_Config_Guard +/// provides a way of temporarily replacing the "current" +/// configuration instance in the context of a thread. +ACE_Service_Gestalt* +ACE_Service_Config::current (void) +{ + void* temp = ACE_Service_Config::singleton()->threadkey_.get (); + if (temp == 0) { + + // The most likely reason is that the current thread was spawned + // by some native primitive, like pthreads or Windows API - not + // from ACE. This is perfectly legal for callers who are not, or + // do not need to be ACE-aware. Such callers must have no + // expectation that the pluggable, multi-context configuration + // support will work - they would always get the global context, + // because at this point there is no information what the "parent" + // thread's configuration context was. + + temp = global(); + singleton()->threadkey_.set (temp); + } + + return static_cast (temp); +} + +/// A mutator to set the "current" (TSS) gestalt instance. +void +ACE_Service_Config::current (ACE_Service_Gestalt* newcurrent) +{ + ACE_Service_Config::singleton()->threadkey_.set (newcurrent); +} + + + +#if (ACE_USES_CLASSIC_SVC_CONF == 0) +ACE_Service_Type * +ACE_Service_Config::create_service_type (const ACE_TCHAR *n, + ACE_Service_Type_Impl *o, + ACE_DLL &dll, + int active) +{ + ACE_Service_Type *sp = 0; + ACE_NEW_RETURN (sp, + ACE_Service_Type (n, o, dll, active), + 0); + return sp; +} +#endif /* ACE_USES_CLASSIC_SVC_CONF == 0 */ + +ACE_Service_Type_Impl * +ACE_Service_Config::create_service_type_impl (const ACE_TCHAR *name, + int type, + void *symbol, + u_int flags, + ACE_Service_Object_Exterminator gobbler) +{ + ACE_Service_Type_Impl *stp = 0; + + // Note, the only place we need to put a case statement. This is + // also the place where we'd put the RTTI tests, if the compiler + // actually supported them! + + switch (type) + { + case ACE_Service_Type::SERVICE_OBJECT: + ACE_NEW_RETURN (stp, + ACE_Service_Object_Type ((ACE_Service_Object *) symbol, + name, flags, + gobbler), + 0); + break; + case ACE_Service_Type::MODULE: + ACE_NEW_RETURN (stp, + ACE_Module_Type (symbol, name, flags), + 0); + break; + case ACE_Service_Type::STREAM: + ACE_NEW_RETURN (stp, + ACE_Stream_Type (symbol, name, flags), + 0); + break; + default: + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("unknown case\n"))); + break; + } + return stp; + +} + + +// Signal handling API to trigger dynamic reconfiguration. +void +ACE_Service_Config::handle_signal (int sig, + siginfo_t *, + ucontext_t *) +{ +#if defined (ACE_NDEBUG) + ACE_UNUSED_ARG (sig); +#else /* ! ACE_NDEBUG */ + ACE_ASSERT (ACE_Service_Config::signum_ == sig); +#endif /* ! ACE_NDEBUG */ + + ACE_Service_Config::reconfig_occurred_ = 1; +} + +// Trigger reconfiguration to re-read configuration files. +void +ACE_Service_Config::reconfigure (void) +{ + ACE_TRACE ("ACE_Service_Config::reconfigure"); + + ACE_Service_Config::reconfig_occurred_ = 0; + + if (ACE::debug ()) + { +#if !defined (ACE_NLOGGING) + time_t t = ACE_OS::time (0); +#endif /* ! ACE_NLOGGING */ + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("beginning reconfiguration at %s"), + ACE_OS::ctime (&t))); + } + if (ACE_Service_Config::process_directives () == -1) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("process_directives"))); +} + +// Tidy up and perform last rites on a terminating ACE_Service_Config. +int +ACE_Service_Config::close (void) +{ + ACE_Service_Config::singleton ()->instance_->close (); + + // Delete the service repository. All the objects inside the + // service repository should already have been finalized. + ACE_Service_Repository::close_singleton (); + + // Do away with the singleton ACE_Service_Config (calls dtor) + ACE_SERVICE_CONFIG_SINGLETON::close (); + + return 0; +} + + +int +ACE_Service_Config::fini_svcs (void) +{ + ACE_TRACE ("ACE_Service_Config::fini_svcs"); + + // Clear the LM_DEBUG bit from log messages if appropriate + if (ACE::debug ()) + ACE_Log_Msg::disable_debug_messages (); + + int result = 0; + if (ACE_Service_Repository::instance () != 0) + result = ACE_Service_Repository::instance ()->fini (); + + if (ACE::debug ()) + ACE_Log_Msg::enable_debug_messages (); + + return result; +} + +/// Perform user-specified close activities and remove dynamic memory. +ACE_Service_Config::~ACE_Service_Config (void) +{ + ACE_TRACE ("ACE_Service_Config::~ACE_Service_Config"); +} + +// ************************************************************ + +/* static */ +int +ACE_Service_Config::reconfig_occurred (void) +{ + ACE_TRACE ("ACE_Service_Config::reconfig_occurred"); + return ACE_Service_Config::reconfig_occurred_ != 0; +} + +void +ACE_Service_Config::reconfig_occurred (int config_occurred) +{ + ACE_TRACE ("ACE_Service_Config::reconfig_occurred"); + ACE_Service_Config::reconfig_occurred_ = config_occurred; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Service_Config.h b/dep/acelite/ace/Service_Config.h new file mode 100644 index 00000000000..5269d8f367e --- /dev/null +++ b/dep/acelite/ace/Service_Config.h @@ -0,0 +1,692 @@ +// -*- C++ -*- + +//==================================================================== +/** + * @file Service_Config.h + * + * $Id: Service_Config.h 89501 2010-03-17 08:59:56Z vzykov $ + * + * @author Douglas C. Schmidt + */ +//==================================================================== + +#ifndef ACE_SERVICE_CONFIG_H +#define ACE_SERVICE_CONFIG_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" +#include "ace/Default_Constants.h" +#include "ace/Intrusive_Auto_Ptr.h" +#include "ace/Service_Gestalt.h" +#include "ace/Synch_Traits.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/OS_NS_signal.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Forward decl. +class ACE_Service_Object; +class ACE_Service_Type; +class ACE_Service_Type_Impl; +class ACE_Service_Repository; +class ACE_Sig_Adapter; +class ACE_Allocator; +class ACE_Reactor; +class ACE_Thread_Manager; +class ACE_DLL; + +#if (ACE_USES_CLASSIC_SVC_CONF == 1) +#define ACE_STATIC_SERVICE_DIRECTIVE(ident, parameters) \ + ACE_TEXT ("static ") \ + ACE_TEXT (ident) \ + ACE_TEXT (" \"") \ + ACE_TEXT (parameters) \ + ACE_TEXT ("\"") +#define ACE_DYNAMIC_SERVICE_DIRECTIVE(ident, libpathname, objectclass, parameters) \ + ACE_TEXT ("dynamic ") \ + ACE_TEXT (ident) \ + ACE_TEXT (" Service_Object * ") \ + ACE_TEXT (libpathname) \ + ACE_TEXT (":") \ + ACE_TEXT (objectclass) \ + ACE_TEXT ("() \"") \ + ACE_TEXT (parameters) \ + ACE_TEXT ("\"") +#define ACE_REMOVE_SERVICE_DIRECTIVE(ident) \ + ACE_TEXT ("remove ") \ + ACE_TEXT (ident) +class ACE_Svc_Conf_Param; +#else +#define ACE_STATIC_SERVICE_DIRECTIVE(ident, parameters) \ + ACE_TEXT ("") +#define ACE_DYNAMIC_SERVICE_DIRECTIVE(ident, libpathname, objectclass, parameters) \ + ACE_TEXT ("") \ + ACE_TEXT ("") +#define ACE_REMOVE_SERVICE_DIRECTIVE(ident) \ + ACE_TEXT ("") +class ACE_XML_Svc_Conf; +#endif /* ACE_USES_CLASSIC_SVC_CONF == 1 */ + +ACE_END_VERSIONED_NAMESPACE_DECL + +extern "C" +{ + typedef ACE_Service_Object *(*ACE_SERVICE_ALLOCATOR) (ACE_Service_Object_Exterminator *); +} + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Static_Svc_Descriptor + * + * @brief Holds the information necessary to describe a statically linked + * Svc. + */ +class ACE_Static_Svc_Descriptor +{ +public: + /// Name of the service. + const ACE_TCHAR *name_; + + /// Type of service. + int type_; + + /// Factory function that allocates the service. + ACE_SERVICE_ALLOCATOR alloc_; + + /// Bitmask flags indicating how the framework should delete memory. + u_int flags_; + + /// Flag indicating whether the service starts out active. + int active_; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +public: + /// Compare two service descriptors for equality. + bool operator== (ACE_Static_Svc_Descriptor &) const; + + /// Compare two service descriptors for inequality. + bool operator!= (ACE_Static_Svc_Descriptor &) const; +}; + + +/** + * @class ACE_Threading_Helper + * + * @brief Encapsulates responsibility for allocating, destroying and + * manipulating the value, associated with a thread-specific + * key. Relates to the ability of the created thread to inherit the + * parent thread's gestalt. Designed to be used as an instance member + * of @c ACE_Service_Config. + * + * Partial specialization over ACE_SYNCH_MUTEX is used to implement + * specific behavior in both multi- and single-threaded builds. + */ +template +class ACE_Threading_Helper +{ +}; + +/* + * Specialization for a multi threaded program + */ +template<> +class ACE_Export ACE_Threading_Helper +{ +public: + ACE_Threading_Helper (); + ~ACE_Threading_Helper (); + + void set (void*); + void* get (void); + +private: + /// Key for the thread-specific data, which is a simple pointer to + /// the thread's (currently-) global configuration context. + ACE_thread_key_t key_; +}; + +/* + * Specialization for a single threaded program + */ +template<> +class ACE_Export ACE_Threading_Helper +{ +public: + ACE_Threading_Helper (); + ~ACE_Threading_Helper (); + + void set (void*); + void* get (void); +}; + +#define ACE_Component_Config ACE_Service_Config + +/** + * @class ACE_Service_Config + * + * @brief Supplies common server operations for dynamic and static + * configuration of service. + * + * The ACE_Service_Config uses the Monostate pattern. Therefore, + * you can only have one of these instantiated per-process. It + * represents the process-wide collection of services, which is + * typicaly shared among all other configurable entities. The only + * ACE_Service_Config instance is registered with and owned by the + * ACE_Object_Manager. + * + * By contrast, the ACE_Service_Gestalt represents the collection + * of services, pertaining to a configurable entity. Typicaly, a + * "configurable entity" is an instance, which owns an instance of + * ACE_Service_Gestalt in order to ensure full controll over the + * services it needs. + * + * Another facet of ACE_Service_Config is that for a given thread, + * it provides access to its current, process-global + * ACE_Service_Gestalt instance through its curent() method. + * + * @note The signal_handler_ static member is allocated by the + * ACE_Object_Manager. The ACE_Service_Config constructor + * uses signal_handler_. Therefore, if the program has any + * static ACE_Service_Config objects, there might be + * initialization order problems. They can be minimized, but + * not eliminated, by _not_ #defining + * ACE_HAS_NONSTATIC_OBJECT_MANAGER. + */ +class ACE_Export ACE_Service_Config +{ + + /// The Instance, or the global (default) configuration context. + /// The monostate would forward the calls to that instance. The TSS + /// will point here + ACE_Intrusive_Auto_Ptr instance_; + + /// A helper instance to manage thread-specific key creation. + /// Dependent on the syncronization mutex ACE uses, the corresponding + /// partial template instantiation will perform the right services + /// that have to do with managing thread-specific storage. Note that, + /// for single-threaded builds they would do (next to) nothing. + ACE_Threading_Helper threadkey_; + +public: + + // = Initialization and termination methods. + + /** + * Initialize the Service Repository. Note that initialising @a + * signum to a negative number will prevent a signal handler being + * registered when the repository is opened. + */ + ACE_Service_Config (bool ignore_static_svcs = true, + size_t size = ACE_DEFAULT_SERVICE_REPOSITORY_SIZE, + int signum = SIGHUP); + + /** + * Performs an open without parsing command-line arguments. The + * @a logger_key indicates where to write the logging output, which + * is typically either a STREAM pipe or a socket address. + */ + ACE_Service_Config (const ACE_TCHAR program_name[], + const ACE_TCHAR *logger_key = ACE_DEFAULT_LOGGER_KEY); + + /// Perform user-specified close activities and remove dynamic + /// memory. + virtual ~ACE_Service_Config (void); + +private: + + /** + * Performs an open without parsing command-line arguments. + * Implements whats different in the opening sequence + * for this class, as opposed to the base class. + * + * The @a logger_key indicates where to write the logging output, which + * is typically either a STREAM pipe or a socket address. If + * @a ignore_default_svc_conf_file is non-0 then the "svc.conf" file + * will be ignored. If @a ignore_debug_flag is non-0 then the + * application is responsible for setting the + * @c ACE_Log_Msg::priority_mask() appropriately. Returns number of + * errors that occurred on failure and 0 otherwise. + */ + virtual int open_i (const ACE_TCHAR program_name[], + const ACE_TCHAR *logger_key, + bool ignore_static_svcs, + bool ignore_default_svc_conf_file, + bool ignore_debug_flag); + + /** + * Implements whats different in the command line parameter processing + * for this class, as opposed to the base class. + */ + virtual int parse_args_i (int argc, ACE_TCHAR *argv[]); + + /// = Static interfaces + + public: + /** + * Returns the process-wide global singleton instance. It would + * have been created and will be managed by the Object Manager. + */ + static ACE_Service_Config* singleton (void); + + /** + * Mutator for the currently active configuration context instance + * (gestalt). Intended for use by helper classes like @see + * ACE_Service_Config_Guard. Stack-based instances can be used to + * temporarily change which gestalt is seen as global by static + * initializers (especially those in DLLs loaded at run-time). + */ + static void current (ACE_Service_Gestalt*); + + /** + * Accessor for the "current" service gestalt + */ + static ACE_Service_Gestalt* current (void); + + /** + * This is what the static service initializators are hard-wired to + * use, so in order to avoid interface changes this method merely + * forwards to @c ACE_Service_Config::current. This enables us to + * enforce which Service Gestalt is used for services registering + * through static initializers. Especially important for DLL-based + * dynamic services, which can contain their own static services and + * static initializers. + * + * @deprecated Use current() instead. + */ + static ACE_Service_Gestalt* instance (void); + + /** + * Returns a process-wide global singleton instance in contrast with + * current (), which may return a different instance at different + * times, dependent on the context. Modifying this method's return + * value is strongly discouraged as it will circumvent the mechanism + * for dynamically loading services. If you must, use with extreme + * caution! + */ + static ACE_Service_Gestalt* global (void); + + /** + * Performs an open without parsing command-line arguments. The + * @a logger_key indicates where to write the logging output, which + * is typically either a STREAM pipe or a socket address. If + * @a ignore_static_svcs is true then static services are not loaded, + * otherwise, they are loaded. If @a ignore_default_svc_conf_file is + * non-0 then the configuration file will be ignored. + * Returns zero upon success, -1 if the file is not found or cannot + * be opened (errno is set accordingly), otherwise returns the + * number of errors encountered loading the services in the + * specified svc.conf configuration file. If @a ignore_debug_flag is + * non-0 then the application is responsible for setting the + * @c ACE_Log_Msg::priority_mask appropriately. + */ + static int open (const ACE_TCHAR program_name[], + const ACE_TCHAR *logger_key = ACE_DEFAULT_LOGGER_KEY, + bool ignore_static_svcs = true, + bool ignore_default_svc_conf_file = false, + bool ignore_debug_flag = false); + + /** + * This is the primary entry point into the ACE_Service_Config (the + * constructor just handles simple initializations). It parses + * arguments passed in from @a argc and @a argv parameters. The + * arguments that are valid in a call to this method include: + * + * - '-b' Option to indicate that we should be a daemon. Note that when + * this option is used, the process will be daemonized before the + * service configuration file(s) are read. During daemonization, + * (on POSIX systems) the current directory will be changed to "/" + * so the caller should either fully specify the file names, or + * execute a @c chroot() to the appropriate directory. + * @sa ACE::daemonize(). + * - '-d' Turn on debugging mode + * - '-f' Specifies a configuration file name other than the default + * svc.conf. Can be specified multiple times to use multiple files. + * If any configuration file is provided with this option then + * the default svc.conf will be ignored. + * - '-k' Specifies the rendezvous point to use for the ACE distributed + * logger. + * - '-y' Explicitly enables the use of static services. This flag + * overrides the @a ignore_static_svcs parameter value. + * - '-n' Explicitly disables the use of static services. This flag + * overrides the @a ignore_static_svcs parameter value. + * - '-p' Specifies a pathname which is used to store the process id. + * - '-s' Specifies a signal number other than SIGHUP to trigger reprocessing + * of the configuration file(s). Ignored for platforms that do not + * have POSIX signals, such as Windows. + * - '-S' Specifies a service directive string. Enclose the string in quotes + * and escape any embedded quotes with a backslash. This option + * specifies service directives without the need for a configuration + * file. Can be specified multiple times. + * + * Note: Options '-f' and '-S' complement each other. Directives from files + * and from '-S' option are processed together in the following order. First, + * all files are processed in the order they are specified in @a argv + * parameter. Second, all directive strings are executed in the order the + * directives appear in @a argv parameter. + * + * @param argc The number of commandline arguments. + * @param argv The array with commandline arguments + * @param logger_key Indicates where to write the logging output, + * which is typically either a STREAM pipe or a + * socket address. + * @param ignore_static_svcs If true then static services are not loaded, + * otherwise, they are loaded. + * @param ignore_default_svc_conf_file If non-0 then the @c svc.conf + * configuration file will be ignored. + * @param ignore_debug_flag If true then the application is responsible + * for setting the @c ACE_Log_Msg::priority_mask + * appropriately. + * + * @retval -1 The configuration file is not found or cannot + * be opened (errno is set accordingly). + * @retval 0 Success. + * @retval >0 The number of errors encountered while processing + * the service configuration file(s). + */ + static int open (int argc, + ACE_TCHAR *argv[], + const ACE_TCHAR *logger_key = ACE_DEFAULT_LOGGER_KEY, + bool ignore_static_svcs = true, + bool ignore_default_svc_conf_file = false, + bool ignore_debug_flag = false); + + /// Tidy up and perform last rites when ACE_Service_Config is shut + /// down. This method calls close_svcs(). Returns 0. + static int close (void); + + /// Perform user-specified close hooks and possibly delete all of the + /// configured services in the . + static int fini_svcs (void); + + /// True if reconfiguration occurred. + static int reconfig_occurred (void); + + /// Indicate that reconfiguration occurred. + static void reconfig_occurred (int); + + /// Perform the reconfiguration process. + static void reconfigure (void); + + // = The following methods are static in order to enforce Singleton + // semantics for the Reactor, Service_Repository, Thread_Manager, + // and Acceptor/Connector Strategy factory. Other portions of the + // system may need to access them at some point or another... + + // = This is not strictly needed, anymore since the service configurator + // has been refactored to allow multiple service configuration + // instances (called gestalts). The interfaces, however were retained in for + // the sake of maintaining source-code compatibility. + + + // = Accessors and mutators for process-wide Singletons. + + /// Returns a pointer to the list of statically linked services. + /// + /// @deprecated - Same as instance(), but still useful in legacy code, + /// (notably, one that can not be easily modified) which uses the following + /// idiom for registering static services: + /// + /// ACE_Service_Config::static_svcs ()->insert (...); + static ACE_Service_Gestalt* static_svcs (void); + + /// Insert a static service descriptor for processing on open_i(). The + /// corresponding ACE_STATIC_SVC_* macros were chaged to use this method + /// instead of obtaining a ptr to a container. See the note on static_svcs(). + /// Added to prevent exposing the internal storage representation of the + /// services repository and provide a better way of debugging service + /// loading and registration problems. + static int insert (ACE_Static_Svc_Descriptor *svc); + + // = Utility methods. + /// Dynamically link the shared object file and retrieve a pointer to + /// the designated shared object in this file. + static int initialize (const ACE_Service_Type *, + const ACE_TCHAR *parameters); + + /// Initialize and activate a statically @a svc_name service. + static int initialize (const ACE_TCHAR *svc_name, + const ACE_TCHAR *parameters); + + /// Resume a @a svc_name that was previously suspended or has not yet + /// been resumed (e.g., a static service). + static int resume (const ACE_TCHAR svc_name[]); + + /** + * Suspend @a svc_name. Note that this will not unlink the service + * from the daemon if it was dynamically linked, it will mark it as + * being suspended in the Service Repository and call the + * member function on the appropriate ACE_Service_Object. A + * service can be resumed later on by calling the member + * function... + */ + static int suspend (const ACE_TCHAR svc_name[]); + + /// Totally remove @a svc_name from the daemon by removing it + /// from the ACE_Reactor, and unlinking it if necessary. + static int remove (const ACE_TCHAR svc_name[]); + +#if defined (ACE_HAS_WINCE) && defined (ACE_USES_WCHAR) + // We must provide these function to bridge the Svc_Conf parser + // with ACE. + static int initialize (const ACE_Service_Type *, ACE_ANTI_TCHAR []); + static int initialize (const char svc_name[], ACE_ANTI_TCHAR parameters[]); + static int resume (const ACE_ANTI_TCHAR svc_name[]); + static int suspend (const ACE_ANTI_TCHAR svc_name[]); + static int remove (const ACE_ANTI_TCHAR svc_name[]); +#endif /* ACE_HAS_WINCE */ + + /// Dump the state of an object. + void dump (void) const; + + /// Set the signal_handler;for internal use by ACE_Object_Manager only. + static ACE_INLINE void signal_handler (ACE_Sig_Adapter *); + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + + /// Process a file containing a list of service configuration + /// directives. + static int process_file (const ACE_TCHAR file[]); + + /// Process one service configuration @a directive, which is passed as + /// a string. Returns the number of errors that occurred. + static int process_directive (const ACE_TCHAR directive[]); + + /** + * Process one static service definition. Load a new static service + * into the ACE_Service_Repository. + * + * @param ssd Service descriptor, see the document of + * ACE_Static_Svc_Descriptor for more details. + * + * @param force_replace If set the new service descriptor replaces + * any previous instance in the ACE_Service_Repository. + * + * @return Returns -1 if the service cannot be 'loaded'. + */ + static int process_directive (const ACE_Static_Svc_Descriptor &ssd, + bool force_replace = false); + + /** + * Process (or re-process) service configuration requests that are + * provided in the svc.conf file(s). Returns the number of errors + * that occurred. + */ + static int process_directives (void); + + /// Handles signals to trigger reconfigurations. + static void handle_signal (int sig, siginfo_t *, ucontext_t *); + + /** + * Handle the command-line options intended for the + * ACE_Service_Config. Note that @c argv[0] is assumed to be the + * program name. + * The arguments that are valid in a call to this method are + * - '-b' Option to indicate that we should be a daemon + * - '-d' Turn on debugging mode + * - '-f' Option to read in the list of svc.conf file names + * - '-k' Option to read a wide string where in the logger output can + * be written + * - '-y' Turn on the flag for a repository of statically + * linked services + * - '-n' Need not have a repository of statically linked services + * - '-S' Option to read in the list of services on the command-line + * Please observe the difference between options '-f' that looks + * for a list of files and here a list of services. + */ + static int parse_args (int, ACE_TCHAR *argv[]); + +#if (ACE_USES_CLASSIC_SVC_CONF == 0) + static ACE_Service_Type *create_service_type (const ACE_TCHAR *n, + ACE_Service_Type_Impl *o, + ACE_DLL &dll, + int active); +#endif /* ACE_USES_CLASSIC_SVC_CONF == 0 */ + + static ACE_Service_Type_Impl * + create_service_type_impl (const ACE_TCHAR *name, + int type, + void *symbol, + u_int flags, + ACE_Service_Object_Exterminator gobbler); + + /// @deprecated + /// Process service configuration requests that were provided on the + /// command-line. Returns the number of errors that occurred. + static int process_commandline_directives (void); + + /// Become a daemon. + static int start_daemon (void); + + // @deprecated + // Add the default statically-linked services to the + // ACE_Service_Repository. + static int load_static_svcs (void); + +protected: + +#if (ACE_USES_CLASSIC_SVC_CONF == 1) + /// @deprecated + /// This is the implementation function that process_directives() + /// and process_directive() both call. Returns the number of errors + /// that occurred. + static int process_directives_i (ACE_Svc_Conf_Param *param); +#endif /* ACE_USES_CLASSIC_SVC_CONF == 1 */ + + + // = Process-wide state. + +private: + + /// Have we called ACE_Service_Config::open() yet? + bool is_opened_; + +#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) + /// Synchronization variable for open, etc. + mutable ACE_SYNCH_MUTEX lock_; +#endif /* ACE_MT_SAFE */ + + /// True if reconfiguration occurred. + static sig_atomic_t reconfig_occurred_; + + // = Set by command-line options. + /// Shall we become a daemon process? + static bool be_a_daemon_; + + /// Pathname of file to write process id. + static ACE_TCHAR *pid_file_name_; + + /// Number of the signal used to trigger reconfiguration. + static int signum_; + + /// Handles the reconfiguration signals. + static ACE_Sig_Adapter *signal_handler_; + + /// Pointer to the Singleton (ACE_Cleanup) Gestalt instance. + /// There is thread-specific global instance pointer, which is used to + /// temporarily change which Gestalt instance is used for static service + /// registrations. + /// + /// A specific use case is a thread, which loads a _dynamic_ service from + /// a DLL. If the said DLL also contains additional _static_ services, + /// those *must* be registered with the same configuration repository as + /// the dynamic service. Otherwise, the DLL's static services would be + /// registered with the global Gestalt and may outlive the DLL that + /// contains their code and perhaps the memory in which they are in. + /// This is a problem because if the DLL gets unloaded (as it will, if + /// it was loaded in an instance of Gestalt), the DLL's memory will be + /// deallocated, but the global service repository will still "think" + /// it must finalize the (DLL's) static services - with disastrous + /// consequences, occurring in the post-main code (at_exit()). + + /// This class needs the intimate access to be able to swap the + /// current TSS pointer for the global Gestalt. + friend class ACE_Service_Config_Guard; + + /// The helper needs intimate access (when building with no threads) + friend class ACE_Threading_Helper ; + friend class ACE_Threading_Helper ; +}; + +/** + * @class ACE_Service_Config_Guard + * + * @brief A guard class, designed to be instantiated on the stack. + * + * Instantiating it with a specific configuration ensures any references to + * ACE_Service_Config::instance(), even when occuring in static constructors, + * will allways access the designated configuration instance. + * This comes very handy when a dynamic service also registers any static + * services of its own and their static factories. + */ +class ACE_Export ACE_Service_Config_Guard +{ +public: + ACE_Service_Config_Guard (ACE_Service_Gestalt* psg); + ~ACE_Service_Config_Guard (void); + +private: + // Private AND not implemented to disable copying + ACE_Service_Config_Guard(const ACE_Service_Config_Guard&); + ACE_Service_Config_Guard& operator= (const ACE_Service_Config_Guard&); + +private: + ACE_Intrusive_Auto_Ptr saved_; +}; + + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Service_Config.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" + +#endif /* ACE_SERVICE_CONFIG_H */ diff --git a/dep/acelite/ace/Service_Config.inl b/dep/acelite/ace/Service_Config.inl new file mode 100644 index 00000000000..35be0e84db9 --- /dev/null +++ b/dep/acelite/ace/Service_Config.inl @@ -0,0 +1,208 @@ +// -*- C++ -*- +// +// $Id: Service_Config.inl 83302 2008-10-16 19:28:11Z mesnier_p $ + +#include "ace/OS_NS_string.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// This is the primary entry point into the ACE_Service_Config (the +// constructor just handles simple initializations). +ACE_INLINE int +ACE_Service_Config::open (const ACE_TCHAR program_name[], + const ACE_TCHAR *logger_key, + bool ignore_static_svcs, + bool ignore_default_svc_conf, + bool ignore_debug_flag) +{ + ACE_TRACE ("ACE_Service_Config::open"); + if (singleton()->open_i (program_name, + logger_key, + ignore_static_svcs, + ignore_default_svc_conf, + ignore_debug_flag) == -1) + return -1; + + return current()->open (program_name, + logger_key, + ignore_static_svcs, + ignore_default_svc_conf, + ignore_debug_flag); +} + + +ACE_INLINE int +ACE_Service_Config::open (int argc, + ACE_TCHAR *argv[], + const ACE_TCHAR *logger_key, + bool ignore_static_svcs, + bool ignore_default_svc_conf, + bool ignore_debug_flag) +{ + ACE_TRACE ("ACE_Service_Config::open"); + + if (singleton()->parse_args_i(argc, argv) == -1) + return -1; + + if (singleton()->open_i (argv[0], + logger_key, + ignore_static_svcs, + ignore_default_svc_conf, + ignore_debug_flag) == -1) + return -1; + + return current()->open (argc, + argv, + logger_key, + ignore_static_svcs, + ignore_default_svc_conf, + ignore_debug_flag); +} + +// Handle the command-line options intended for the +// ACE_Service_Config. +ACE_INLINE int +ACE_Service_Config::parse_args (int argc, ACE_TCHAR *argv[]) +{ + return ACE_Service_Config::current ()->parse_args (argc, argv); +} + +/// Return the global configuration instance. Allways returns the same +/// instance +ACE_INLINE ACE_Service_Gestalt * +ACE_Service_Config::global (void) +{ + return ACE_Service_Config::singleton()->instance_.get (); +} + +/// Return the configuration instance, considered "global" in the +/// current thread. This may be the same as instance(), but on some +/// occasions, it may be a different one. For example, +/// ACE_Service_Config_Guard provides a way of temporarily replacing +/// the "current" configuration instance in the context of a thread. +ACE_INLINE ACE_Service_Gestalt * +ACE_Service_Config::instance (void) +{ + return ACE_Service_Config::current (); +} + +// This method has changed to return the gestalt instead of the +// container, underlying the service repository and defined +// ACE_Service_Gestalt::insert (ACE_Static_Svc_Descriptor*). This way +// the existing source code can keep using +// ACE_Service_Config::static_svcs(), however now it is not necessary +// to expose the repository storage *and* it is much easier to debug +// service registration problems. + +ACE_INLINE ACE_Service_Gestalt* +ACE_Service_Config::static_svcs (void) +{ + return ACE_Service_Config::current (); +} + +/// Compare two service descriptors for equality. +ACE_INLINE bool +ACE_Static_Svc_Descriptor::operator== (ACE_Static_Svc_Descriptor &d) const +{ + return ACE_OS::strcmp (name_, d.name_) == 0; +} + +/// Compare two service descriptors for inequality. +ACE_INLINE bool +ACE_Static_Svc_Descriptor::operator!= (ACE_Static_Svc_Descriptor &d) const +{ + return !(*this == d); +} + +ACE_INLINE void +ACE_Service_Config::signal_handler (ACE_Sig_Adapter *signal_handler) +{ + signal_handler_ = signal_handler; +} + +/// Initialize and activate a statically linked service. +ACE_INLINE int +ACE_Service_Config::initialize (const ACE_TCHAR *svc_name, + const ACE_TCHAR *parameters) +{ + ACE_TRACE ("ACE_Service_Config::initialize"); + return ACE_Service_Config::current ()->initialize (svc_name, + parameters); +} + +/// Dynamically link the shared object file and retrieve a pointer to +/// the designated shared object in this file. +ACE_INLINE int +ACE_Service_Config::initialize (const ACE_Service_Type *sr, + const ACE_TCHAR *parameters) +{ + ACE_TRACE ("ACE_Service_Config::initialize"); + return ACE_Service_Config::current ()->initialize (sr, parameters); +} + +/// Process a file containing a list of service configuration +/// directives. +ACE_INLINE int ACE_Service_Config::process_file (const ACE_TCHAR file[]) +{ + return ACE_Service_Config::current ()->process_file (file); +} + +/// +ACE_INLINE int +ACE_Service_Config::process_directive (const ACE_TCHAR directive[]) +{ + return ACE_Service_Config::current ()->process_directive (directive); +} + +/// Process service configuration requests as indicated in the queue of +/// svc.conf files. +ACE_INLINE int +ACE_Service_Config::process_directives (void) +{ + return ACE_Service_Config::current ()->process_directives (false); +} + +ACE_INLINE int +ACE_Service_Config::process_directive (const ACE_Static_Svc_Descriptor &ssd, + bool force_replace) +{ + return ACE_Service_Config::current ()->process_directive (ssd, force_replace); +} + + +#if defined (ACE_HAS_WINCE) && defined (ACE_USES_WCHAR) +// We must provide these function to bridge Svc_Conf parser with ACE. + +ACE_INLINE int +ACE_Service_Config::initialize (const ACE_Service_Type *sp, ACE_ANTI_TCHAR parameters[]) +{ + return ACE_Service_Config::initialize (sp, ACE_TEXT_ANTI_TO_TCHAR (parameters)); +} + +ACE_INLINE int +ACE_Service_Config::initialize (const ACE_ANTI_TCHAR svc_name[], ACE_ANTI_TCHAR parameters[]) +{ + return ACE_Service_Config::initialize (ACE_TEXT_ANTI_TO_TCHAR (svc_name), + ACE_TEXT_ANTI_TO_TCHAR (parameters)); +} + +ACE_INLINE int +ACE_Service_Config::resume (const ACE_ANTI_TCHAR svc_name[]) +{ + return ACE_Service_Config::resume (ACE_TEXT_ANTI_TO_TCHAR (svc_name)); +} + +ACE_INLINE int +ACE_Service_Config::suspend (const ACE_ANTI_TCHAR svc_name[]) +{ + return ACE_Service_Config::suspend (ACE_TEXT_ANTI_TO_TCHAR (svc_name)); +} + +ACE_INLINE int +ACE_Service_Config::remove (const ACE_ANTI_TCHAR svc_name[]) +{ + return ACE_Service_Config::remove (ACE_TEXT_ANTI_TO_TCHAR (svc_name)); +} +#endif /* ACE_HAS_WINCE && !ACE_USES_WCHAR */ + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Service_Gestalt.cpp b/dep/acelite/ace/Service_Gestalt.cpp new file mode 100644 index 00000000000..47ea3d1e81b --- /dev/null +++ b/dep/acelite/ace/Service_Gestalt.cpp @@ -0,0 +1,1327 @@ +// $Id: Service_Gestalt.cpp 91158 2010-07-21 15:54:12Z mesnier_p $ + +#include "ace/Svc_Conf.h" +#include "ace/Get_Opt.h" +#include "ace/ARGV.h" +#include "ace/Malloc.h" +#include "ace/Service_Manager.h" +#include "ace/Service_Types.h" +#include "ace/Containers.h" +#include "ace/Auto_Ptr.h" +#include "ace/Reactor.h" +#include "ace/Thread_Manager.h" +#include "ace/DLL.h" +#include "ace/XML_Svc_Conf.h" +#include "ace/SString.h" + +#ifndef ACE_LACKS_UNIX_SIGNALS +# include "ace/Signal.h" +#endif /* !ACE_LACKS_UNIX_SIGNALS */ + +#include "ace/OS_NS_stdio.h" +#include "ace/OS_NS_string.h" +#include "ace/OS_NS_time.h" +#include "ace/OS_NS_unistd.h" +#include "ace/OS_NS_sys_stat.h" + +#include "ace/TSS_T.h" +#include "ace/Service_Gestalt.h" + +#include "ace/Svc_Conf_Param.h" + +ACE_RCSID (ace, + Service_Gestalt, + "$Id: Service_Gestalt.cpp 91158 2010-07-21 15:54:12Z mesnier_p $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_Service_Type_Dynamic_Guard::ACE_Service_Type_Dynamic_Guard + (ACE_Service_Repository &r, const ACE_TCHAR *name) + : repo_ (r) + // Relocation starts where the next service will be inserted (if any) + , repo_begin_ (r.current_size ()) + , name_ (name) +# if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) + // On this thread (for the duration of the initialize() method), + // we're about to do two things that require locking: (1) fiddle + // with the repository and (2) load a DLL and hence lock the + // DLL_Manager. + // + // Now if we don't lock the repo here, it is possible that two + // threads may deadlock on initialization because they can acquire + // locks (1) and (2) in different order, for instance: + // + // T1: loads a DLL (2) and registers a service (1); + // + // T2: may be relocating a service (1), which could lead to a + // (re)opening or uping the ref count on a DLL (2); + // + // To prevent this, we lock the repo here, using the repo_monitor_ + // member guard. + , repo_monitor_ (r.lock_) +#endif +{ + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) STDG::, repo=%@") + ACE_TEXT(", name=%s - begining at [%d]\n"), + &this->repo_, + this->name_, + this->repo_begin_)); + + ACE_ASSERT (this->name_ != 0); // No name? +} + + +/// Destructor +ACE_Service_Type_Dynamic_Guard::~ACE_Service_Type_Dynamic_Guard (void) +{ + const ACE_Service_Type *tmp = 0; + + // Lookup without ignoring suspended services. Making sure + // not to ignore any inactive services, since those may be forward + // declarations + size_t slot = 0; + int const ret = this->repo_.find_i (this->name_, slot, &tmp, false); + + // We inserted it (as inactive), so we expect to find it, right? + if ((ret < 0 && ret != -2) || tmp == 0) + { + if (ACE::debug ()) + ACE_ERROR ((LM_WARNING, + ACE_TEXT ("ACE (%P|%t) STDG:: - Failed (%d) to find %s -> %@\n"), + ret, this->name_, tmp)); + return; + } + + if (tmp->type () != 0) + { + // Something has registered a proper (non-forward-decl) service with + // the same name as our dummy. + + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) STDG::, repo=%@ [%d], ") + ACE_TEXT ("name=%s - updating dependents [%d - %d)\n"), + &this->repo_, + slot, + this->name_, + this->repo_begin_, + this->repo_.current_size ())); + + // Relocate any services inserted since we were created. + // Any (static, i.e. DLL = 0) services registered in + // the context of this guard aren't really static because + // their code belongs in the DLL's code segment + this->repo_.relocate_i (this->repo_begin_, this->repo_.current_size (), tmp->dll()); + + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) STDG::, repo=%@ [%d], ") + ACE_TEXT ("name=%s - loaded (type=%@, impl=%@, object=%@, active=%d)\n"), + &this->repo_, + slot, + this->name_, + tmp, + tmp->type (), + tmp->type ()->object (), + tmp->active ())); + } +} + + + +// ---------------------------------------- + +ACE_Service_Gestalt::Processed_Static_Svc:: +Processed_Static_Svc (const ACE_Static_Svc_Descriptor *assd) + :name_(0), + assd_(assd) +{ + ACE_NEW_NORETURN (name_, ACE_TCHAR[ACE_OS::strlen(assd->name_)+1]); + ACE_OS::strcpy(name_,assd->name_); +} + +ACE_Service_Gestalt::Processed_Static_Svc::~Processed_Static_Svc (void) +{ + delete [] name_; +} + +void +ACE_Service_Gestalt::intrusive_add_ref (ACE_Service_Gestalt* g) +{ + if (g != 0) + { + ++g->refcnt_; + ACE_ASSERT (g->refcnt_ > 0); + } +} + +void +ACE_Service_Gestalt::intrusive_remove_ref (ACE_Service_Gestalt* g) +{ + if (g != 0) + { + long tmp = --g->refcnt_; + if (tmp <= 0) delete g; + ACE_ASSERT (tmp >= 0); + } +} + + +ACE_Service_Gestalt::~ACE_Service_Gestalt (void) +{ + + if (this->svc_repo_is_owned_) + delete this->repo_; + + this->repo_ =0; + + delete this->static_svcs_; + this->static_svcs_ = 0; + + // Delete the dynamically allocated static_svcs instance. +#ifndef ACE_NLOGGING + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) SG::~SG - this=%@, pss = %@\n"), + this, this->processed_static_svcs_)); +#endif + + if (this->processed_static_svcs_ && + !this->processed_static_svcs_->is_empty()) + { + Processed_Static_Svc **pss = 0; + for (ACE_PROCESSED_STATIC_SVCS_ITERATOR iter (*this->processed_static_svcs_); + iter.next (pss) != 0; + iter.advance ()) + { + delete *pss; + } + } + + delete this->processed_static_svcs_; + this->processed_static_svcs_ = 0; + + delete this->svc_conf_file_queue_; + this->svc_conf_file_queue_ = 0; +} + +ACE_Service_Gestalt::ACE_Service_Gestalt (size_t size, + bool svc_repo_is_owned, + bool no_static_svcs) + : svc_repo_is_owned_ (svc_repo_is_owned) + , svc_repo_size_ (size) + , is_opened_ (0) + , logger_key_ (ACE_DEFAULT_LOGGER_KEY) + , no_static_svcs_ (no_static_svcs) + , svc_queue_ (0) + , svc_conf_file_queue_ (0) + , repo_ (0) + , static_svcs_ (0) + , processed_static_svcs_ (0) + , refcnt_ (0) +{ + (void)this->init_i (); + +#ifndef ACE_NLOGGING + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) SG::ctor - this = %@, pss = %@\n"), + this, this->processed_static_svcs_)); +#endif +} + +/// Performs the common initialization tasks for a new or previously +/// closed instance. Must not be virtual, as it is also called from +/// the constructor. +int +ACE_Service_Gestalt::init_i (void) +{ + // Only initialize the repo_ if (a) we are being constructed, or; + // (b) we're being open()-ed, perhaps after previously having been + // close()-ed. In both cases: repo_ == 0 and we need a repository. + if (this->repo_ == 0) + { + if (this->svc_repo_is_owned_) + { + ACE_NEW_RETURN (this->repo_, + ACE_Service_Repository (this->svc_repo_size_), + -1); + } + else + { + this->repo_ = + ACE_Service_Repository::instance (this->svc_repo_size_); + } + } + + if (init_svc_conf_file_queue () == -1) + return -1; + + return 0; +} + + +/// Add the default statically-linked services to the Service +/// Repository. +int +ACE_Service_Gestalt::load_static_svcs (void) +{ + ACE_TRACE ("ACE_Service_Gestalt::load_static_svcs"); + + if (this->static_svcs_ == 0) + return 0; // Nothing to do + + ACE_Static_Svc_Descriptor **ssdp = 0; + for (ACE_STATIC_SVCS_ITERATOR iter (*this->static_svcs_); + iter.next (ssdp) != 0; + iter.advance ()) + { + ACE_Static_Svc_Descriptor *ssd = *ssdp; + + if (this->process_directive (*ssd, 1) == -1) + return -1; + } + return 0; + +} /* load_static_svcs () */ + + + +/// Find a static service descriptor by name +int +ACE_Service_Gestalt::find_static_svc_descriptor (const ACE_TCHAR* name, + ACE_Static_Svc_Descriptor **ssd) const +{ + ACE_TRACE ("ACE_Service_Gestalt::find_static_svc_descriptor"); + + if (this->static_svcs_ == 0) + return -1; + + ACE_Static_Svc_Descriptor **ssdp = 0; + for (ACE_STATIC_SVCS_ITERATOR iter ( *this->static_svcs_); + iter.next (ssdp) != 0; + iter.advance ()) + { + if (ACE_OS::strcmp ((*ssdp)->name_, name) == 0) + { + if (ssd != 0) + *ssd = *ssdp; + + return 0; + } + } + + return -1; +} + +/// @brief +const ACE_Static_Svc_Descriptor* +ACE_Service_Gestalt::find_processed_static_svc (const ACE_TCHAR* name) +{ + if (this->processed_static_svcs_ == 0 || name == 0) + return 0; + + Processed_Static_Svc **pss = 0; + for (ACE_PROCESSED_STATIC_SVCS_ITERATOR iter (*this->processed_static_svcs_); + iter.next (pss) != 0; + iter.advance ()) + { + if (ACE_OS::strcmp ((*pss)->name_, name) == 0) + return (*pss)->assd_; + } + return 0; +} + + + +/// @brief Captures a list of the direcives processed (explicitely) for this +/// Gestalt so that services can be replicated in other repositories +/// upon their first initialization. +/// +/// This is part of the mechanism ensuring distinct local instances +/// for static service objects, loaded in another repository. +void +ACE_Service_Gestalt::add_processed_static_svc + (const ACE_Static_Svc_Descriptor *assd) +{ + + /// When process_directive(Static_Svc_Descriptor&) is called, it + /// associates a service object with the Gestalt and makes the + /// resource (a Service Object) local to the repository. This is but + /// the first step in using such SO. The next is the + /// "initialization" step. It is typicaly done through a "static" + /// service configuration directive. + /// + /// In contrast a "dynamic" directive, when processed through the + /// overloaded process_directives(string) both creates the SO + /// locally and initializes it, where the statics directive must + /// first locate the SO and then calls the init() method. This means + /// that durig the "static" initialization there's no specific + /// information about the hosting repository and the gestalt must + /// employ some lookup strategy to find it elsewhere. + + if (this->processed_static_svcs_ == 0) + ACE_NEW (this->processed_static_svcs_, + ACE_PROCESSED_STATIC_SVCS); + + Processed_Static_Svc **pss = 0; + for (ACE_PROCESSED_STATIC_SVCS_ITERATOR iter (*this->processed_static_svcs_); + iter.next (pss) != 0; + iter.advance ()) + { + if (ACE_OS::strcmp ((*pss)->name_, assd->name_) == 0) + { + (*pss)->assd_ = assd; + return; + } + } + Processed_Static_Svc *tmp = 0; + ACE_NEW (tmp,Processed_Static_Svc(assd)); + this->processed_static_svcs_->insert(tmp); + + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) SG::add_processed_static_svc, ") + ACE_TEXT ("repo=%@ - %s\n"), + this->repo_, + assd->name_)); +} + + +/// Queues a static service object descriptor which, during open() +/// will be given to process_directive() to create the Service +/// Object. Normally, only called from static initializers, prior to +/// calling open() but loading a service from a DLL can cause it too. + +int +ACE_Service_Gestalt::insert (ACE_Static_Svc_Descriptor *stsd) +{ + if (this->static_svcs_ == 0) + ACE_NEW_RETURN (this->static_svcs_, + ACE_STATIC_SVCS, + -1); + + return this->static_svcs_->insert (stsd); +} + + +ACE_ALLOC_HOOK_DEFINE (ACE_Service_Gestalt) + + +void +ACE_Service_Gestalt::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Service_Gestalt::dump"); +#endif /* ACE_HAS_DUMP */ +} + +int +ACE_Service_Gestalt::initialize (const ACE_TCHAR *svc_name, + const ACE_TCHAR *parameters) +{ + ACE_TRACE ("ACE_Service_Gestalt_Base::initialize (repo)"); + ACE_ARGV args (parameters); + +#ifndef ACE_NLOGGING + if (ACE::debug ()) + { + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) SG::initialize - () repo=%@, ") + ACE_TEXT ("looking up static ") + ACE_TEXT ("service \'%s\' to initialize\n"), + this->repo_, + svc_name)); + } +#endif + + const ACE_Service_Type *srp = 0; + for (int i = 0; this->find (svc_name, &srp) == -1 && i < 2; i++) + // if (this->repo_->find (svc_name, &srp) == -1) + { + const ACE_Static_Svc_Descriptor *assd = + ACE_Service_Config::global()->find_processed_static_svc(svc_name); + if (assd != 0) + { + this->process_directive_i(*assd, 0); + } + else + { + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("ACE (%P|%t) ERROR: SG::initialize - service \'%s\'") + ACE_TEXT (" was not located.\n"), + svc_name), + -1); + } + } + if (srp == 0) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("ACE (%P|%t) ERROR: SG::initialize - service \'%s\'") + ACE_TEXT (" was not located.\n"), + svc_name), + -1); + + /// If initialization fails ... + if (srp->type ()->init (args.argc (), + args.argv ()) == -1) + { + // ... report and remove this entry. + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("ACE (%P|%t) ERROR: SG::initialize - static init of \'%s\'") + ACE_TEXT (" failed (%p)\n"), + svc_name, ACE_TEXT ("error"))); + this->repo_->remove (svc_name); + return -1; + } + + // If everything is ok, activate it + const_cast(srp)->active (1); + return 0; +} + + +#if (ACE_USES_CLASSIC_SVC_CONF == 1) +int +ACE_Service_Gestalt::initialize (const ACE_Service_Type_Factory *stf, + const ACE_TCHAR *parameters) +{ + ACE_TRACE ("ACE_Service_Gestalt::initialize"); + +#ifndef ACE_NLOGGING + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) SG::initialize - repo=%@, name=%s") + ACE_TEXT (" - looking up in the repo\n"), + this->repo_, + stf->name ())); +#endif + + ACE_Service_Type *srp = 0; + int const retv = this->repo_->find (stf->name (), + (const ACE_Service_Type **) &srp); + + // If there is an active service already, remove it first + // before it can be re-installed. + if (retv >= 0) + { +#ifndef ACE_NLOGGING + if (ACE::debug ()) + ACE_DEBUG ((LM_WARNING, + ACE_TEXT ("ACE (%P|%t) SG::initialize - repo=%@,") + ACE_TEXT (" name=%s - removing a pre-existing namesake.\n"), + this->repo_, + stf->name ())); +#endif + this->repo_->remove (stf->name ()); + } + + // If there is an inactive service by that name it may have been + // either inactivated, or just a forward declaration for a service, + // that is in the process of being initialized. If it is the latter, + // then we have detected an attempt to initialize the same dynamic + // service while still processing previous attempt. This can lock up + // the process, because the ACE_DLL_Manager::open () is not + // re-entrant - it uses a Singleton lock to serialize concurent + // invocations. This use case must be handled here, because if the + // DLL_Manager was re-entrant we would have entered an infinite + // recursion here. + if (retv == -2 && srp->type () == 0) + ACE_ERROR_RETURN ((LM_WARNING, + ACE_TEXT ("ACE (%P|%t) SG::initialize - repo=%@,") + ACE_TEXT (" name=%s - forward-declared; ") + ACE_TEXT (" recursive initialization requests are") + ACE_TEXT (" ignored.\n"), + this->repo_, + stf->name ()), + -1); + + // Reserve a spot for the dynamic service by inserting an incomplete + // service declaration, i.e. one that can not produce a service + // object if asked (a forward declaration). This declaration + // ensures maintaining the proper partial ordering of the services + // with respect to their finalization. For example, dependent static + // services must be registered *after* the dynamic service that + // loads them, so that their finalization is complete *before* + // finalizing the dynamic service. + ACE_Service_Type_Dynamic_Guard dummy (*this->repo_, + stf->name ()); + + // make_service_type() is doing the dynamic loading and also runs + // any static initializers + ACE_Auto_Ptr tmp (stf->make_service_type (this)); + + if (tmp.get () != 0 && + this->initialize_i (tmp.get (), parameters) == 0) + { + // All good. Tthe ACE_Service_Type instance is now owned by the + // repository and we should make sure it is not destroyed upon + // exit from this method. + tmp.release (); + return 0; + } + + return -1; +} +#endif /* (ACE_USES_CLASSIC_SVC_CONF == 1) */ + + +/// Dynamically link the shared object file and retrieve a pointer to +/// the designated shared object in this file. +/// @note This is obsolete (and error-prone) in the presense of dynamic +/// services with their own static services. This method will allow those +/// static services to register *before* the dynamic service that owns them. +/// Upon finalization of the static services the process may crash, because +/// the dynamic service's DLL may have been already released, together with +/// the memory in which the static services reside. +/// It may not crash, for instance, when the first static service to register +/// is the same as the dynamic service being loaded. You should be so lucky! .. +int +ACE_Service_Gestalt::initialize (const ACE_Service_Type *sr, + const ACE_TCHAR *parameters) +{ + ACE_TRACE ("ACE_Service_Gestalt::initialize"); + + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) SG::initialize - repo=%@, name=%s") + ACE_TEXT (" - looking up in the repo\n"), + this->repo_, + sr->name ())); + + ACE_Service_Type *srp = 0; + if (this->repo_->find (sr->name (), + (const ACE_Service_Type **) &srp) >= 0) + { +#ifndef ACE_NLOGGING + ACE_DEBUG ((LM_WARNING, + ACE_TEXT ("ACE (%P|%t) SG::initialize - repo=%@, name=%s") + ACE_TEXT (" - removing a pre-existing namesake.\n"), + this->repo_, + sr->name ())); +#endif + this->repo_->remove (sr->name ()); + } + + return this->initialize_i (sr, parameters); + +} + +/// Dynamically link the shared object file and retrieve a pointer to +/// the designated shared object in this file. +int +ACE_Service_Gestalt::initialize_i (const ACE_Service_Type *sr, + const ACE_TCHAR *parameters) +{ + ACE_TRACE ("ACE_Service_Gestalt::initialize_i"); + ACE_ARGV args (parameters); + if (sr->type ()->init (args.argc (), + args.argv ()) == -1) + { + // We just get ps to avoid having remove() delete it. + ACE_Service_Type *ps = 0; + this->repo_->remove (sr->name (), &ps); + +#ifndef ACE_NLOGGING + // Not using LM_ERROR here to avoid confusing the test harness + if (ACE::debug ()) + ACE_ERROR_RETURN ((LM_WARNING, + ACE_TEXT ("ACE (%P|%t) SG::initialize_i -") + ACE_TEXT (" repo=%@, name=%s - remove failed: %m\n"), + this->repo_, + sr->name ()), + -1); +#endif + return -1; + } + + if (this->repo_->insert (sr) == -1) + { +#ifndef ACE_NLOGGING + // Not using LM_ERROR here to avoid confusing the test harness + if (ACE::debug ()) + ACE_ERROR_RETURN ((LM_WARNING, + ACE_TEXT ("ACE (%P|%t) SG::initialize_i -") + ACE_TEXT (" repo=%@, name=%s - insert failed: %m\n"), + this->repo_, + sr->name ()), + -1); +#endif + return -1; + } + + return 0; +} + +// Totally remove from the daemon by removing it from the +// ACE_Reactor, and unlinking it if necessary. + +int +ACE_Service_Gestalt::remove (const ACE_TCHAR svc_name[]) +{ + ACE_TRACE ("ACE_Service_Gestalt::remove"); + if (this->repo_ == 0) + return -1; + + return this->repo_->remove (svc_name); +} + +/// Suspend @a svc_name. Note that this will not unlink the service +/// from the daemon if it was dynamically linked, it will mark it as +/// being suspended in the Service Repository and call the +/// member function on the appropriate . A service +/// can be resumed later on by calling the method... +int +ACE_Service_Gestalt::suspend (const ACE_TCHAR svc_name[]) +{ + ACE_TRACE ("ACE_Service_Gestalt::suspend"); + if (this->repo_ == 0) + return -1; + + return this->repo_->suspend (svc_name); +} + +// Resume a SVC_NAME that was previously suspended or has not yet +// been resumed (e.g., a static service). + +int +ACE_Service_Gestalt::resume (const ACE_TCHAR svc_name[]) +{ + ACE_TRACE ("ACE_Service_Gestalt::resume"); + if (this->repo_ == 0) + return -1; + + return this->repo_->resume (svc_name); +} + + +int +ACE_Service_Gestalt::process_directive (const ACE_Static_Svc_Descriptor &ssd, + bool force_replace) +{ + int const result = process_directive_i (ssd, force_replace); + if (result == 0) + { + this->add_processed_static_svc(&ssd); + } + return result; +} + +int +ACE_Service_Gestalt::process_directive_i (const ACE_Static_Svc_Descriptor &ssd, + bool force_replace) +{ + if (this->repo_ == 0) + return -1; + + if (!force_replace) + { + if (this->repo_->find (ssd.name_, 0, 0) >= 0) + { + // The service is already there, just return + return 0; + } + } + + + ACE_Service_Object_Exterminator gobbler; + void *sym = (ssd.alloc_)(&gobbler); + + ACE_Service_Type_Impl *stp = + ACE_Service_Config::create_service_type_impl (ssd.name_, + ssd.type_, + sym, + ssd.flags_, + gobbler); + if (stp == 0) + return 0; + + ACE_Service_Type *service_type = 0; + + // This is just a temporary to force the compiler to use the right + // constructor in ACE_Service_Type. Note that, in cases where we are + // called from a static initializer which is part of a DLL, there is + // not enough information about the actuall DLL in this context. + ACE_DLL tmp_dll; + + ACE_NEW_RETURN (service_type, + ACE_Service_Type (ssd.name_, + stp, + tmp_dll, + ssd.active_), + -1); + +#ifndef ACE_NLOGGING + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) SG::process_directive_i, ") + ACE_TEXT ("repo=%@ - %s, dll=%s, force=%d\n"), + this->repo_, + ssd.name_, + (tmp_dll.dll_name_ == 0) ? ACE_TEXT ("") : tmp_dll.dll_name_, + force_replace)); +#endif + + return this->repo_->insert (service_type); +} + +#if (ACE_USES_CLASSIC_SVC_CONF == 1) + +int +ACE_Service_Gestalt::process_directives_i (ACE_Svc_Conf_Param *param) +{ +#ifndef ACE_NLOGGING + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) SG::process_directives_i, ") + ACE_TEXT ("repo=%@ - %s\n"), + this->repo_, + (param->type == ACE_Svc_Conf_Param::SVC_CONF_FILE) + ? ACE_TEXT ("") + : param->source.directive)); +#endif + + // AC 970827 Skip the heap check because yacc allocates a buffer + // here which will be reported as a memory leak for some reason. + ACE_NO_HEAP_CHECK + + // Were we called in the context of the current instance? + ACE_ASSERT (this == param->config); + + // Temporarily (for the duration of this call) make sure that *any* + // static service registrations will happen with this instance. Such + // registrations are possible as a side-effect of dynamically + // loading a DLL, which has other static services registered. Thus + // this instance will own both the DLL and those static services, + // which implies that their finalization will be performed in the + // correct order, i.e. prior to finalizing the DLL + ACE_Service_Config_Guard guard (this); + + ::ace_yyparse (param); + + // This is a hack, better errors should be provided... + if (param->yyerrno > 0) + { + // Always set the last error if ace_yyparse() fails. + // Other code may use errno to determine the type + // of problem that occurred from processing directives. + ACE_OS::last_error (EINVAL); + return param->yyerrno; + } + else + return 0; +} + +#else + +ACE_XML_Svc_Conf * +ACE_Service_Gestalt::get_xml_svc_conf (ACE_DLL &xmldll) +{ + if (xmldll.open (ACE_TEXT ("ACEXML_XML_Svc_Conf_Parser")) == -1) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("ACE (%P|%t) Failure to open ACEXML_XML_Svc_Conf_Parser: %p\n"), + ACE_TEXT("ACE_Service_Config::get_xml_svc_conf")), + 0); + + void * foo = + xmldll.symbol (ACE_TEXT ("_ACEXML_create_XML_Svc_Conf_Object")); + +#if defined (ACE_OPENVMS) && (!defined (__INITIAL_POINTER_SIZE) || (__INITIAL_POINTER_SIZE < 64)) + int const temp_p = reinterpret_cast (foo); +#else + intptr_t const temp_p = reinterpret_cast (foo); +#endif + + ACE_XML_Svc_Conf::Factory factory = reinterpret_cast (temp_p); + + if (factory == 0) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("ACE (%P|%t) Unable to resolve factory: %p\n"), + xmldll.error ()), + 0); + + return factory (); +} +#endif /* ACE_USES_CLASSIC_SVC_CONF == 1 */ + +int +ACE_Service_Gestalt::process_file (const ACE_TCHAR file[]) +{ + ACE_TRACE ("ACE_Service_Gestalt::process_file"); + + // To avoid recursive processing of the same file and the same repository + // we maintain an implicit stack of dummy "services" named after the file + // being processed. Anytime we have to open a new file, we then can check + // to see if it is not already being processed by searching for a dummy + // service with a matching name. + if (this->repo_->find (file, 0, 0) >=0) + { + ACE_DEBUG ((LM_WARNING, + ACE_TEXT ("ACE (%P|%t) Configuration file %s is currently") + ACE_TEXT (" being processed. Ignoring recursive process_file().\n"), + file)); + return 0; + } + + // Register a dummy service as a forward decl, using the file name as name. + // The entry will be automaticaly removed once the thread exits this block. + ACE_Service_Type_Dynamic_Guard recursion_guard (*this->repo_, + file); + + /* + * @TODO: Test with ACE_USES_CLASSIC_SVC_CONF turned off! + */ +#if (ACE_USES_CLASSIC_SVC_CONF == 1) + int result = 0; + + FILE *fp = ACE_OS::fopen (file, + ACE_TEXT ("r")); + + if (fp == 0) + { + // Invalid svc.conf file. We'll report it here and break out of + // the method. + if (ACE::debug ()) + ACE_DEBUG ((LM_ERROR, + ACE_TEXT ("ACE (%P|%t): %p\n"), + file)); + + // Use stat to find out if the file exists. I didn't use access() + // because stat is better supported on most non-unix platforms. + ACE_stat exists; + if (ACE_OS::stat (file, &exists) == 0) + // If it exists, but we couldn't open it for reading then we + // must not have permission to read it. + errno = EPERM; + else + errno = ENOENT; + result = -1; + } + else + { + ACE_Svc_Conf_Param f (this, fp); + + // Keep track of the number of errors. + result = this->process_directives_i (&f); + + (void) ACE_OS::fclose (fp); + } + return result; +#else + ACE_DLL dll; + + auto_ptr xml_svc_conf (this->get_xml_svc_conf (dll)); + + if (xml_svc_conf.get () == 0) + return -1; + + return xml_svc_conf->parse_file (file); +#endif /* ACE_USES_CLASSIC_SVC_CONF == 1 */ +} + +int +ACE_Service_Gestalt::process_directive (const ACE_TCHAR directive[]) +{ + ACE_TRACE ("ACE_Service_Gestalt::process_directive"); + +#ifndef ACE_NLOGGING + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) SG::process_directive, repo=%@ - %s\n"), + this->repo_, + directive)); +#endif + +#if (ACE_USES_CLASSIC_SVC_CONF == 1) + ACE_UNUSED_ARG (directive); + + ACE_Svc_Conf_Param d (this, directive); + + return this->process_directives_i (&d); +#else + ACE_DLL dll; + + auto_ptr + xml_svc_conf (this->get_xml_svc_conf (dll)); + + if (xml_svc_conf.get () == 0) + return -1; + + // Temporarily (for the duration of this call) make sure that *any* static + // service registrations will happen with this instance. Such registrations + // are possible as a side-effect of dynamically loading a DLL, which has + // other static services registered. Thus this instance will own both the + // DLL and those static services, which implies that their finalization + // will be performed in the correct order, i.e. prior to finalizing the DLL + ACE_Service_Config_Guard guard (this); + + return xml_svc_conf->parse_string (directive); +#endif /* ACE_USES_CLASSIC_SVC_CONF == 1 */ + +} /* process_directive () */ + + +int +ACE_Service_Gestalt::init_svc_conf_file_queue (void) +{ + if (this->svc_conf_file_queue_ == 0) + { + ACE_SVC_QUEUE *tmp = 0; + ACE_NEW_RETURN (tmp, + ACE_SVC_QUEUE, + -1); + this->svc_conf_file_queue_ = tmp; + } + +#ifndef ACE_NLOGGING + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) SG::init_svc_conf_file_queue ") + ACE_TEXT ("- this=%@, repo=%@\n"), + this, this->repo_)); +#endif + + return 0; + +} /* init_svc_conf_file_queue () */ + + +int +ACE_Service_Gestalt::open_i (const ACE_TCHAR program_name[], + const ACE_TCHAR* logger_key, + bool ignore_static_svcs, + bool ignore_default_svc_conf_file, + bool ignore_debug_flag) +{ + ACE_TRACE ("ACE_Service_Gestalt::open_i"); + int result = 0; + ACE_Log_Msg *log_msg = ACE_LOG_MSG; + + this->no_static_svcs_ = ignore_static_svcs; + + // Record the current log setting upon entering this thread. + u_long old_process_mask = log_msg->priority_mask + (ACE_Log_Msg::PROCESS); + + u_long old_thread_mask = log_msg->priority_mask + (ACE_Log_Msg::THREAD); + +#ifndef ACE_NLOGGING + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) SG::open_i - this=%@, ") + ACE_TEXT ("opened=%d, loadstatics=%d\n"), + this, this->is_opened_, this->no_static_svcs_)); +#endif + + // Guard against reentrant processing. For example, + // if the singleton gestalt (ubergestalt) was already open, + // do not open it again... + if (this->is_opened_++ != 0) + return 0; + + if (this->init_i () != 0) + return -1; + + u_long flags = log_msg->flags (); + + // Only use STDERR if the caller hasn't already set the flags. + if (flags == 0) + flags = (u_long) ACE_Log_Msg::STDERR; + + const ACE_TCHAR *key = logger_key; + + if (key == 0 || ACE_OS::strcmp (key, ACE_DEFAULT_LOGGER_KEY) == 0) + { + // Only use the static if the caller doesn't + // override it in the parameter list or if the key supplied is + // equal to the default static logger key. + key = this->logger_key_; + } + else + { + ACE_SET_BITS (flags, ACE_Log_Msg::LOGGER); + } + + if (log_msg->open (program_name, + flags, + key) == -1) + return -1; + + if (!ignore_debug_flag) + { + // If -d was included as a startup parameter, the user wants debug + // information printed during service initialization. + if (ACE::debug ()) + ACE_Log_Msg::enable_debug_messages (); + else + // The user has requested no debugging info. + ACE_Log_Msg::disable_debug_messages (); + } + + if (!ignore_default_svc_conf_file) + { + bool add_default = true; + bool has_files = this->svc_conf_file_queue_ && + !this->svc_conf_file_queue_->is_empty (); + bool has_cmdline = this->svc_queue_ && !this->svc_queue_->is_empty (); + if (has_files || has_cmdline) + { + // check if default file is already listed + ACE_TString *sptr = 0; + ACE_TString default_svc_conf (ACE_DEFAULT_SVC_CONF); + + for (ACE_SVC_QUEUE_ITERATOR iter (*this->svc_conf_file_queue_); + iter.next (sptr) != 0 && add_default; + iter.advance ()) + { + add_default = (*sptr != default_svc_conf); + } + + if (add_default) + { + FILE *fp = ACE_OS::fopen (ACE_DEFAULT_SVC_CONF, ACE_TEXT ("r")); + if (fp != 0) + ACE_OS::fclose(fp); + else + add_default = false; + + } + } + + // Load the default "svc.conf" entry. here if there weren't + // overriding -f arguments in . + if (add_default && svc_conf_file_queue_->enqueue_head + (ACE_TString (ACE_DEFAULT_SVC_CONF)) == -1) + { + errno = ENOENT; + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("enqueuing ") + ACE_DEFAULT_SVC_CONF + ACE_TEXT(" file")), + -1); + } + } + + // See if we need to load the static services. + if (this->no_static_svcs_ == 0 + && this->load_static_svcs () == -1) + result = -1; + else + { + result = this->process_directives (); + if (result != -1 || errno == ENOENT) + result = this->process_commandline_directives (); + } + + // Reset debugging back to the way it was when we came into + // into . + { + // Make sure to save/restore errno properly. + ACE_Errno_Guard error (errno); + + if (!ignore_debug_flag) + { + log_msg->priority_mask (old_process_mask, ACE_Log_Msg::PROCESS); + log_msg->priority_mask (old_thread_mask, ACE_Log_Msg::THREAD); + } + } + + return result; +} /* open_i () */ + + +int +ACE_Service_Gestalt::is_opened (void) +{ + return this->is_opened_; +} + +int +ACE_Service_Gestalt::process_commandline_directives (void) +{ + int result = 0; + if (this->svc_queue_ != 0) + { + ACE_TString *sptr = 0; + for (ACE_SVC_QUEUE_ITERATOR iter (*this->svc_queue_); + iter.next (sptr) != 0; + iter.advance ()) + { + // Process just a single directive. + if (this->process_directive ((sptr->fast_rep ())) != 0) + { + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("ACE (%P|%t) %p\n"), + ACE_TEXT ("process_directive"))); + result = -1; + } + } + + delete this->svc_queue_; + this->svc_queue_ = 0; + } + + return result; + +} /* process_commandline_directives () */ + + +int +ACE_Service_Gestalt::parse_args (int argc, ACE_TCHAR *argv[]) +{ + ACE_TRACE ("ACE_Service_Gestalt::parse_args"); + bool unused_ignore_default_svc_conf = true; + return parse_args_i (argc, argv, unused_ignore_default_svc_conf); +} + +int +ACE_Service_Gestalt::parse_args_i (int argc, + ACE_TCHAR *argv[], + bool &ignore_default_svc_conf_file) +{ + ACE_TRACE ("ACE_Service_Gestalt::parse_args_i"); + ACE_Get_Opt get_opt (argc, + argv, + ACE_TEXT ("df:k:nyS:"), + 1); // Start at argv[1]. + + if (this->init_svc_conf_file_queue () == -1) + return -1; + + for (int c; (argc != 0) && ((c = get_opt ()) != -1); ) + switch (c) + { + case 'd': + ACE::debug (1); + break; + case 'f': + if (this->svc_conf_file_queue_->enqueue_tail (ACE_TString (get_opt.opt_arg ())) == -1) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("enqueue_tail")), + -1); + ignore_default_svc_conf_file = true; + break; + case 'k': + /* + * @TODO: Is this always a static storage? Shouldn't we copy + * & gain ownership of the value? + */ + this->logger_key_ = get_opt.opt_arg (); + break; + case 'n': + this->no_static_svcs_ = 1; + break; + case 'y': + this->no_static_svcs_ = 0; + break; + case 'S': + if (this->svc_queue_ == 0) + { + ACE_NEW_RETURN (this->svc_queue_, + ACE_SVC_QUEUE, + -1); + } + + if (this->svc_queue_->enqueue_tail (ACE_TString (get_opt.opt_arg ())) == -1) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("enqueue_tail")), + -1); + break; + default: + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) %c is not a ACE_Service_Config option\n"), + c)); + } + + return 0; +} /* parse_args_i () */ + + + +// Process service configuration directives from the files queued for +// processing +int +ACE_Service_Gestalt::process_directives (bool ) +{ + ACE_TRACE ("ACE_Service_Gestalt::process_directives"); + if (this->svc_conf_file_queue_ == 0 + || this->svc_conf_file_queue_->is_empty ()) + { + return 0; + } + + ACE_TString *sptr = 0; + int failed = 0; + + // Iterate through all the svc.conf files. + for (ACE_SVC_QUEUE_ITERATOR iter (*this->svc_conf_file_queue_); + iter.next (sptr) != 0; + iter.advance ()) + { + int result = this->process_file (sptr->fast_rep ()); + if (result < 0) + return result; + failed += result; + } + + return failed; + +} /* process_directives () */ + +// Tidy up and perform last rites on a terminating ACE_Service_Gestalt. +int +ACE_Service_Gestalt::close (void) +{ + ACE_TRACE ("ACE_Service_Gestalt::close"); + + if (!this->is_opened_ || --this->is_opened_ != 0) + return 0; + + // Delete the list fo svc.conf files + delete this->svc_conf_file_queue_; + this->svc_conf_file_queue_ = 0; + + if (this->processed_static_svcs_ && + !this->processed_static_svcs_->is_empty()) + { + Processed_Static_Svc **pss = 0; + for (ACE_PROCESSED_STATIC_SVCS_ITERATOR iter (*this->processed_static_svcs_); + iter.next (pss) != 0; + iter.advance ()) + { + delete *pss; + } + } + delete this->processed_static_svcs_; + this->processed_static_svcs_ = 0; + +#ifndef ACE_NLOGGING + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) SG::close - complete this=%@, repo=%@, owned=%d\n"), + this, this->repo_, this->svc_repo_is_owned_)); +#endif + + if (this->svc_repo_is_owned_) + delete this->repo_; + + this->repo_ = 0; + + return 0; +} /* close () */ + + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if !defined (__ACE_INLINE__) +#include "ace/Service_Gestalt.inl" +#endif /* __ACE_INLINE__ */ + +// Allocate a Service Manager. +ACE_FACTORY_DEFINE (ACE, ACE_Service_Manager) diff --git a/dep/acelite/ace/Service_Gestalt.h b/dep/acelite/ace/Service_Gestalt.h new file mode 100644 index 00000000000..68a2ce7e7cc --- /dev/null +++ b/dep/acelite/ace/Service_Gestalt.h @@ -0,0 +1,530 @@ +// -*- C++ -*- + +//==================================================================== +/** + * @file Service_Gestalt.h + * + * $Id: Service_Gestalt.h 91158 2010-07-21 15:54:12Z mesnier_p $ + * + * @author Iliyan Jeliazkov + */ +//==================================================================== + +#ifndef ACE_SERVICE_GESTALT_H +#define ACE_SERVICE_GESTALT_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" +#include "ace/Default_Constants.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Auto_Ptr.h" +#include "ace/SString.h" +#include "ace/Unbounded_Queue.h" +#include "ace/Unbounded_Set.h" +#include "ace/Service_Repository.h" +#include "ace/Singleton.h" +#include "ace/OS_NS_signal.h" +#include "ace/Synch_Traits.h" +#include "ace/Atomic_Op.h" +#include "ace/Guard_T.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +#if (ACE_USES_CLASSIC_SVC_CONF == 1) +class ACE_Service_Type_Factory; +class ACE_Location_Node; +#else +class ACE_XML_Svc_Conf; +class ACE_DLL; +#endif /* ACE_USES_CLASSIC_SVC_CONF == 1 */ + +class ACE_Static_Svc_Descriptor; +class ACE_Svc_Conf_Param; + +/** + * @class ACE_Service_Gestalt + * + * @brief Supplies common server operations for dynamic and static + * configuration of services. + * + * The Gestalt embodies the concept of configuration context. On one + * hand, it is a flat namespace, where names correspond to a Service + * Object instance. A Gestalt owns the Service Repository instance, + * which in turn owns the Service Object instances. + * + * Another aspect of a Gestalt is its responsibility for + * record-keeping and accounting for the meta-data, necessary for + * locating, removing or instantiating a service. + * + * A repository underlies an instance of a gestalt and its lifetime + * may or may not be bounded by the lifetime of the gestalt, that owns + * it. This feature is important for the derived classes and the + * Service Config in particular. + * + */ +class ACE_Export ACE_Service_Gestalt +{ +private: + /// + /// Not implemented to enforce no copying + // + ACE_UNIMPLEMENTED_FUNC (ACE_Service_Gestalt(const ACE_Service_Gestalt&)) + ACE_UNIMPLEMENTED_FUNC (ACE_Service_Gestalt& operator=(const ACE_Service_Gestalt&)) + +public: + enum + { + MAX_SERVICES = ACE_DEFAULT_SERVICE_REPOSITORY_SIZE + }; + + enum + { + DEFAULT_SIZE = ACE_DEFAULT_SERVICE_GESTALT_SIZE + }; + + /// Constructor either associates the instance with the process-wide + /// singleton instance of ACE_Service_Repository, or creates and + /// manages its own instance of the specified size. + ACE_Service_Gestalt (size_t size = DEFAULT_SIZE, + bool svc_repo_is_owned = true, + bool no_static_svcs = true); + + /// Perform user-specified close activities and remove dynamic + /// memory. + ~ACE_Service_Gestalt (void); + + /// Dump the state of an object. + void dump (void) const; + + /** + * Performs an open without parsing command-line arguments. The + * @a logger_key indicates where to write the logging output, which + * is typically either a STREAM pipe or a socket address. If + * @a ignore_static_svcs is true then static services are not loaded, + * otherwise, they are loaded. If @a ignore_default_svc_conf_file is + * true then the @c svc.conf configuration file will be ignored. + * Returns zero upon success, -1 if the file is not found or cannot + * be opened (errno is set accordingly), otherwise returns the + * number of errors encountered loading the services in the + * specified svc.conf configuration file. If @a ignore_debug_flag is + * true then the application is responsible for setting the + * ACE_Log_Msg::priority_mask appropriately. + */ + int open (const ACE_TCHAR program_name[], + const ACE_TCHAR *logger_key = 0, + bool ignore_static_svcs = true, + bool ignore_default_svc_conf_file = false, + bool ignore_debug_flag = false); + + /** + * This is the primary entry point into the ACE_Service_Config (the + * constructor just handles simple initializations). It parses + * arguments passed in from @a argc and @a argv parameters. The + * arguments that are valid in a call to this method include: + * + * - '-b' Option to indicate that we should be a daemon. Note that when + * this option is used, the process will be daemonized before the + * service configuration file(s) are read. During daemonization, + * (on POSIX systems) the current directory will be changed to "/" + * so the caller should either fully specify the file names, or + * execute a @c chroot() to the appropriate directory. + * @sa ACE::daemonize(). + * - '-d' Turn on debugging mode + * - '-f' Specifies a configuration file name other than the default + * svc.conf. Can be specified multiple times to use multiple files. + * If any configuration file is provided with this option then + * the default svc.conf will be ignored. + * - '-k' Specifies the rendezvous point to use for the ACE distributed + * logger. + * - '-y' Explicitly enables the use of static services. This flag + * overrides the @a ignore_static_svcs parameter value. + * - '-n' Explicitly disables the use of static services. This flag + * overrides the @a ignore_static_svcs parameter value. + * - '-p' Specifies a pathname which is used to store the process id. + * - '-s' Specifies a signal number other than SIGHUP to trigger reprocessing + * of the configuration file(s). Ignored for platforms that do not + * have POSIX signals, such as Windows. + * - '-S' Specifies a service directive string. Enclose the string in quotes + * and escape any embedded quotes with a backslash. This option + * specifies service directives without the need for a configuration + * file. Can be specified multiple times. + * + * Note: Options '-f' and '-S' complement each other. Directives + * from files and from '-S' option are processed together in the + * following order. First, the default file "./svc.conf" is + * evaluated if not ignored, then all files are processed in the + * order they are specified in '-f' @a argv parameter. Finally, all + * '-S' directive strings are executed in the order the directives + * appear in @a argv parameter. + * + * If no files or directives are added via the '-f' and '-S' + * arguments, and the default file is not ignored, it will be + * evaluated whether it exists or not, possibly causing a failure + * return. If any other directives are added then the default file + * will be evaluated only if it exists. + * + * @param argc The number of commandline arguments. + * @param argv The array with commandline arguments + * @param logger_key Indicates where to write the logging output, + * which is typically either a STREAM pipe or a + * socket address. + * @param ignore_static_svcs If true then static services are not loaded, + * otherwise, they are loaded. + * @param ignore_default_svc_conf_file If false then the @c ./svc.conf + * configuration file will be ignored. + * @param ignore_debug_flag If false then the application is responsible + * for setting the @c ACE_Log_Msg::priority_mask + * appropriately. + * + * @retval -1 A configuration file is not found or cannot + * be opened (errno is set accordingly). + * @retval 0 Success. + * @retval >0 The number of directive errors encountered while processing + * the service configuration file(s). + */ + int open (int argc, + ACE_TCHAR *argv[], + const ACE_TCHAR *logger_key = 0, + bool ignore_static_svcs = true, + bool ignore_default_svc_conf_file = false, + bool ignore_debug_flag = false); + + /// Has it been opened? Returns the difference between the times + /// open and close have been called on this instance + int is_opened (void); + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + + /// Process one service configuration @a directive, which is passed as + /// a string. Returns the number of errors that occurred. + int process_directive (const ACE_TCHAR directive[]); + + /// Process one static service definition. + /** + * Load a new static service. + * + * @param ssd Service descriptor, see the document of + * ACE_Static_Svc_Descriptor for more details. + * + * @param force_replace If set the new service descriptor replaces + * any previous instance in the repository. + * + * @return Returns -1 if the service cannot be 'loaded'. + */ + int process_directive (const ACE_Static_Svc_Descriptor &ssd, + bool force_replace = false); + + /// Process a file containing a list of service configuration + /// directives. + int process_file (const ACE_TCHAR file[]); + + /** + * Locate an entry with @a name in the table. If @a ignore_suspended + * is set then only consider services marked as resumed. If the + * caller wants the located entry, pass back a pointer to the + * located entry via @a srp. If @a name is not found, -1 is returned. + * If @a name is found, but it is suspended and the caller wants to + * ignore suspended services a -2 is returned. + */ + int find (const ACE_TCHAR name[], + const ACE_Service_Type **srp = 0, + bool ignore_suspended = true) const; + + /** + * Handle the command-line options intended for the + * ACE_Service_Gestalt. Note that @c argv[0] is assumed to be the + * program name. + * + * The arguments that are valid in a call to this method are + * - '-d' Turn on debugging mode + * - '-f' Option to read in the list of svc.conf file names + * - '-k' Option to read a wide string where in the logger output can + * be written + * - '-y' Turn on the flag for a repository of statically + * linked services + * - '-n' Need not have a repository of statically linked services + * - '-S' Option to read in the list of services on the command-line + * Please observe the difference between options '-f' that looks + * for a list of files and here a list of services. + */ + int parse_args (int argc, ACE_TCHAR *argv[]); + + /** + * Process (or re-process) service configuration requests that are + * provided in the svc.conf file(s). Returns the number of errors + * that occurred. + */ + int process_directives (bool defunct_option = false); + + /// Tidy up and perform last rites when ACE_Service_Config is shut + /// down. This method calls @c close_svcs. Returns 0. + int close (void); + + /// Registers a service descriptor for a static service object + int insert (ACE_Static_Svc_Descriptor *stsd); + + // = Utility methods. + +#if (ACE_USES_CLASSIC_SVC_CONF == 1) + /// Dynamically link the shared object file and retrieve a pointer to + /// the designated shared object in this file. Also account for the + /// possiblity to have static services registered when loading the DLL, by + /// ensuring that the dynamic sevice is registered before any of its + /// subordibnate static services. Thus avoiding any finalization order + /// problems. + int initialize (const ACE_Service_Type_Factory *, + const ACE_TCHAR *parameters); +#endif /* (ACE_USES_CLASSIC_SVC_CONF == 1) */ + + /// Dynamically link the shared object file and retrieve a pointer to + /// the designated shared object in this file. + /// @deprecated + /// @note This is error-prone in the presense of dynamic services, + /// which in turn initialize their own static services. This method + /// will allow those static services to register *before* the dynamic + /// service that owns them. Upon finalization of the static services + /// the process will typically crash, because the dynamic service's + /// DLL may have been already released, together with the memory in + /// which the static services reside. It may not crash, for + /// instance, when the first static service to register is the same + /// as the dynamic service being loaded. You should be so lucky! + int initialize (const ACE_Service_Type *, + const ACE_TCHAR *parameters); + + /// Initialize and activate a statically @a svc_name service. + int initialize (const ACE_TCHAR *svc_name, + const ACE_TCHAR *parameters); + + /// Resume a @a svc_name that was previously suspended or has not yet + /// been resumed (e.g., a static service). + int resume (const ACE_TCHAR svc_name[]); + + /** + * Suspend @a svc_name. Note that this will not unlink the service + * from the daemon if it was dynamically linked, it will mark it as + * being suspended in the Service Repository and call the @c suspend() + * member function on the appropriate ACE_Service_Object. A + * service can be resumed later on by calling the @c resume() member + * function... + */ + int suspend (const ACE_TCHAR svc_name[]); + + /// Totally remove @a svc_name from the daemon by removing it + /// from the ACE_Reactor, and unlinking it if necessary. + int remove (const ACE_TCHAR svc_name[]); + + /** + * Using the supplied name, finds and (if needed) returns a pointer to a + * static service descriptor. Returns 0 for success and -1 for failure + */ + int find_static_svc_descriptor (const ACE_TCHAR* name, + ACE_Static_Svc_Descriptor **ssd = 0) const; + + struct Processed_Static_Svc + { + Processed_Static_Svc (const ACE_Static_Svc_Descriptor *); + ~Processed_Static_Svc (void); + ACE_TCHAR * name_; + const ACE_Static_Svc_Descriptor *assd_; + }; + + /// Get the current ACE_Service_Repository held by this object. + ACE_Service_Repository* current_service_repository (void); + +protected: + + int parse_args_i (int, ACE_TCHAR *argv[], + bool& ignore_default_svc_conf_file); + + /** + * Performs an open without parsing command-line arguments. The @a + * logger_key indicates where to write the logging output, which is + * typically either a STREAM pipe or a socket address. If @a + * ignore_default_svc_conf_file is non-0 then the "svc.conf" file + * will not be added by default. If @a ignore_debug_flag is non-0 + * then the application is responsible for setting the @c + * ACE_Log_Msg::priority_mask() appropriately. Returns number of + * errors that occurred on failure and 0 otherwise. + */ + int open_i (const ACE_TCHAR program_name[], + const ACE_TCHAR *logger_key = 0, + bool ignore_static_svcs = true, + bool ignore_default_svc_conf_file = false, + bool ignore_debug_flag = false); + + /// Initialize the @c svc_conf_file_queue_ if necessary. + int init_svc_conf_file_queue (void); + + /// Add the default statically-linked services to the + /// ACE_Service_Repository. + int load_static_svcs (void); + + /// Process service configuration requests that were provided on the + /// command-line. Returns the number of errors that occurred. + int process_commandline_directives (void); + + /// Process a static directive without also inserting its descriptor + /// the global table. This avoids multiple additions when processing + /// directives in non-global gestalts. + int process_directive_i (const ACE_Static_Svc_Descriptor &ssd, + bool force_replace = false); + +#if (ACE_USES_CLASSIC_SVC_CONF == 1) + /// This is the implementation function that process_directives() + /// and process_directive() both call. Returns the number of errors + /// that occurred. + int process_directives_i (ACE_Svc_Conf_Param *param); +#else + /// Helper function to dynamically link in the XML Service Configurator + /// parser. + ACE_XML_Svc_Conf* get_xml_svc_conf (ACE_DLL &d); +#endif /* ACE_USES_CLASSIC_SVC_CONF == 1 */ + + /// Dynamically link the shared object file and retrieve a pointer to + /// the designated shared object in this file. + int initialize_i (const ACE_Service_Type *sr, const ACE_TCHAR *parameters); + + const ACE_Static_Svc_Descriptor* find_processed_static_svc (const ACE_TCHAR*); + void add_processed_static_svc (const ACE_Static_Svc_Descriptor *); + + /// Performs the common initialization tasks for a new or previously + /// closed instance. Must not be virtual, as it is called from the + /// constructor. + int init_i (void); + +protected: + + /// Maintain a queue of services to be configured from the + /// command-line. + typedef ACE_Unbounded_Queue ACE_SVC_QUEUE; + typedef ACE_Unbounded_Queue_Iterator ACE_SVC_QUEUE_ITERATOR; + + /// Maintain a set of the statically linked service descriptors. + typedef ACE_Unbounded_Set + ACE_STATIC_SVCS; + + typedef ACE_Unbounded_Set_Iterator + ACE_STATIC_SVCS_ITERATOR; + + typedef ACE_Unbounded_Set + ACE_PROCESSED_STATIC_SVCS; + + typedef ACE_Unbounded_Set_Iterator + ACE_PROCESSED_STATIC_SVCS_ITERATOR; + + friend class ACE_Dynamic_Service_Base; + friend class ACE_Service_Object; + friend class ACE_Service_Config; + friend class ACE_Service_Config_Guard; + +protected: + + /// Do we own the service repository instance, or have only been + /// given a ptr to the singleton? + bool svc_repo_is_owned_; + + /// Repository size is necessary, so that we can close (which may + /// destroy the repository instance), and then re-open again. + size_t svc_repo_size_; + + /// Keep track of the number of times the instance has been + /// initialized (opened). "If so, we can't allow to be called since + /// it's not reentrant" is the original motivation, but that does not seem + /// to be the case anymore. This variable is incremented by the + /// method and decremented by the + /// method. + int is_opened_; + + /// Indicates where to write the logging output. This is typically + /// either a STREAM pipe or a socket + const ACE_TCHAR *logger_key_; + + /// Should we avoid loading the static services? + bool no_static_svcs_; + + /// Queue of services specified on the command-line. + ACE_SVC_QUEUE* svc_queue_; + + /** + * Queue of svc.conf files specified on the command-line. + * @@ This should probably be made to handle unicode filenames... + */ + ACE_SVC_QUEUE* svc_conf_file_queue_; + + /// The service repository to hold the services. + ACE_Service_Repository* repo_; + + /// Repository of statically linked services. + ACE_STATIC_SVCS* static_svcs_; + + /// Repository of statically linked services for which process + /// directive was called, but the service is not already a member of + /// the static_svcs_ list. + ACE_PROCESSED_STATIC_SVCS* processed_static_svcs_; + + /// Support for intrusive reference counting + ACE_Atomic_Op refcnt_; + + public: + static void intrusive_add_ref (ACE_Service_Gestalt*); + static void intrusive_remove_ref (ACE_Service_Gestalt*); + +}; /* class ACE_Service_Gestalt */ + + +/** + * @class ACE_Service_Type_Dynamic_Guard + * + * @brief A forward service declaration guard. + * + * Helps to resolve an issue with hybrid services, i.e. dynamic + * services, accompanied by static services in the same DLL. Only + * automatic instances of this class are supposed to exist. Those are + * created during (dynamic) service initialization and serve to: + * + * (a) Ensure the service we are loading is ordered last in the + * repository, following any other services it may cause to register, + * as part of its own registration. This is a common case when + * loading dynamic services from DLLs - there are often static + * initializers, which register static services. + * + * (b) The SDG instance destructor detects if the dynamic service + * initialized successfully and "fixes-up" all the newly registered + * static services to hold a reference to the DLL, from which they + * have originated. + */ +class ACE_Export ACE_Service_Type_Dynamic_Guard +{ +public: + ACE_Service_Type_Dynamic_Guard (ACE_Service_Repository &r, + ACE_TCHAR const *name); + + ~ACE_Service_Type_Dynamic_Guard (void); + +private: + ACE_Service_Repository & repo_; + size_t repo_begin_; + ACE_TCHAR const * const name_; + +# if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) + ACE_Guard< ACE_Recursive_Thread_Mutex > repo_monitor_; +#endif +}; + + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Service_Gestalt.inl" +#endif /* __ACE_INLINE__ */ + + +#include /**/ "ace/post.h" + +#endif /* ACE_SERVICE_GESTALT_H */ diff --git a/dep/acelite/ace/Service_Gestalt.inl b/dep/acelite/ace/Service_Gestalt.inl new file mode 100644 index 00000000000..436037b71a1 --- /dev/null +++ b/dep/acelite/ace/Service_Gestalt.inl @@ -0,0 +1,78 @@ +// -*- C++ -*- +// +// $Id: Service_Gestalt.inl 91158 2010-07-21 15:54:12Z mesnier_p $ + + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + + +// This is the primary entry point into the ACE_Service_Config (the +// constructor just handles simple initializations). + +ACE_INLINE int +ACE_Service_Gestalt::open (const ACE_TCHAR program_name[], + const ACE_TCHAR *logger_key, + bool ignore_static_svcs, + bool ignore_default_svc_conf, + bool ignore_debug_flag) +{ + ACE_TRACE ("ACE_Service_Gestalt::open"); + this->no_static_svcs_ = ignore_static_svcs; + + return this->open_i (program_name, + logger_key, + ignore_static_svcs, + ignore_default_svc_conf, + ignore_debug_flag); +} + +ACE_INLINE int +ACE_Service_Gestalt::open (int argc, + ACE_TCHAR *argv[], + const ACE_TCHAR *logger_key, + bool ignore_static_svcs, + bool ignore_default_svc_conf, + bool ignore_debug_flag) +{ + ACE_TRACE ("ACE_Service_Gestalt::open"); + + // Parsing argv may change no_static_svcs_ so set the default here, then + // parse, then pass the final value to open_i(). + this->no_static_svcs_ = ignore_static_svcs; + + if (this->parse_args_i (argc, + argv, + ignore_default_svc_conf) == -1) + return -1; + + return this->open_i (argv == 0 ? 0 : argv[0], + logger_key, + this->no_static_svcs_, + ignore_default_svc_conf, + ignore_debug_flag); +} + +/// Searches for a service object declaration in the local repo, only + +ACE_INLINE int +ACE_Service_Gestalt::find (const ACE_TCHAR name[], + const ACE_Service_Type **srp, + bool ignore_suspended) const +{ + // Closing the gestalt will have disassociated it from the + // repository. If the repository used to be owned by the gestalt, it + // will also have been destroyed - so just check for repo_ before + // doing anything with it. + if (this->repo_ != 0) + return this->repo_->find (name, srp, ignore_suspended); + + return 0; +} + +ACE_INLINE ACE_Service_Repository* +ACE_Service_Gestalt::current_service_repository (void) +{ + return this->repo_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Service_Manager.cpp b/dep/acelite/ace/Service_Manager.cpp new file mode 100644 index 00000000000..5a4dbcb89bd --- /dev/null +++ b/dep/acelite/ace/Service_Manager.cpp @@ -0,0 +1,437 @@ +// $Id: Service_Manager.cpp 82723 2008-09-16 09:35:44Z johnnyw $ + +#include "ace/Service_Manager.h" + +#include "ace/Get_Opt.h" +#include "ace/Log_Msg.h" +#include "ace/Service_Repository.h" +#include "ace/Service_Config.h" +#include "ace/Service_Types.h" +#include "ace/Reactor.h" +#include "ace/WFMO_Reactor.h" +#include "ace/OS_NS_stdio.h" +#include "ace/OS_NS_string.h" + +ACE_RCSID (ace, + Service_Manager, + "$Id: Service_Manager.cpp 82723 2008-09-16 09:35:44Z johnnyw $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE (ACE_Service_Manager) + +void +ACE_Service_Manager::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Service_Manager::dump"); +#endif /* ACE_HAS_DUMP */ +} + +// Static variables. + +u_short ACE_Service_Manager::DEFAULT_PORT_ = 10000; + +ACE_Service_Manager::ACE_Service_Manager (void) + : debug_ (false), + signum_ (SIGHUP) +{ + ACE_TRACE ("ACE_Service_Manager::ACE_Service_Manager"); +} + +ACE_Service_Manager::~ACE_Service_Manager (void) +{ + ACE_TRACE ("ACE_Service_Manager::~ACE_Service_Manager"); +} + +int +ACE_Service_Manager::suspend (void) +{ + ACE_TRACE ("ACE_Service_Manager::suspend"); + return ACE_Reactor::instance ()->suspend_handler (this); +} + +int +ACE_Service_Manager::resume (void) +{ + ACE_TRACE ("ACE_Service_Manager::resume"); + return ACE_Reactor::instance ()->resume_handler (this); +} + +int +ACE_Service_Manager::open (const ACE_INET_Addr &sia) +{ + ACE_TRACE ("ACE_Service_Manager::open"); + + // Reuse the listening address, even if it's already in use! + if (this->acceptor_.open (sia, 1) == -1) + { + return -1; + } + + return 0; +} + +int +ACE_Service_Manager::info (ACE_TCHAR **strp, size_t length) const +{ + ACE_TRACE ("ACE_Service_Manager::info"); + ACE_INET_Addr sa; + ACE_TCHAR buf[BUFSIZ]; + + if (this->acceptor_.get_local_addr (sa) == -1) + { + return -1; + } + + ACE_OS::sprintf (buf, + ACE_TEXT ("%d/%s %s"), + sa.get_port_number (), + ACE_TEXT ("tcp"), + ACE_TEXT ("# lists all services in the daemon\n")); + + if (*strp == 0 && (*strp = ACE_OS::strdup (buf)) == 0) + { + return -1; + } + else + { + ACE_OS::strsncpy (*strp, buf, length); + } + + return static_cast (ACE_OS::strlen (buf)); +} + +int +ACE_Service_Manager::init (int argc, ACE_TCHAR *argv[]) +{ + ACE_TRACE ("ACE_Service_Manager::init"); + ACE_INET_Addr local_addr (ACE_Service_Manager::DEFAULT_PORT_); + + //FUZZ: disable check_for_lack_ACE_OS + ACE_Get_Opt getopt (argc, argv, ACE_TEXT ("dp:s:"), 0); // Start at argv[0] + + for (int c; (c = getopt ()) != -1; ) + //FUZZ: enable check_for_lack_ACE_OS + switch (c) + { + case 'd': + this->debug_ = true; + break; + case 'p': + local_addr.set ((u_short) ACE_OS::atoi (getopt.opt_arg ())); + break; + case 's': + this->signum_ = ACE_OS::atoi (getopt.opt_arg ()); + break; + default: + break; + } + + if (this->get_handle () == ACE_INVALID_HANDLE && + this->open (local_addr) == -1) + { + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("open")), -1); + } + else if (ACE_Reactor::instance ()->register_handler + (this, + ACE_Event_Handler::ACCEPT_MASK) == -1) + { + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("registering service with ACE_Reactor\n")), + -1); + } + + return 0; +} + +int +ACE_Service_Manager::handle_close (ACE_HANDLE, ACE_Reactor_Mask) +{ + ACE_TRACE ("ACE_Service_Manager::handle_close"); + return this->acceptor_.close (); +} + +int +ACE_Service_Manager::fini (void) +{ + ACE_TRACE ("ACE_Service_Manager::fini"); + + int retv = 0; + + if (this->get_handle () != ACE_INVALID_HANDLE) + { + retv = + ACE_Reactor::instance ()->remove_handler ( + this, + ACE_Event_Handler::ACCEPT_MASK | ACE_Event_Handler::DONT_CALL); + + this->handle_close (ACE_INVALID_HANDLE, + ACE_Event_Handler::NULL_MASK); + } + + return retv; +} + +ACE_HANDLE +ACE_Service_Manager::get_handle (void) const +{ + ACE_TRACE ("ACE_Service_Manager::get_handle"); + return this->acceptor_.get_handle (); +} + +int +ACE_Service_Manager::handle_signal (int, siginfo_t *, ucontext_t *) +{ + return 0; +} + +// Determine all the services offered by this daemon and return the +// information back to the client. + +int +ACE_Service_Manager::list_services (void) +{ + ACE_TRACE ("ACE_Service_Manager::list_services"); + ACE_Service_Repository_Iterator sri (*ACE_Service_Repository::instance (), 0); + + for (const ACE_Service_Type *sr; + sri.next (sr) != 0; + sri.advance ()) + { + ssize_t len = static_cast (ACE_OS::strlen (sr->name ())) + 11; + ACE_TCHAR buf[BUFSIZ]; + ACE_TCHAR *p = buf + len; + + ACE_OS::strcpy (buf, sr->name ()); + ACE_OS::strcat (buf, (sr->active ()) ? + ACE_TEXT (" (active) ") : + ACE_TEXT (" (paused) ")); + + p[-1] = ' '; + p[0] = '\0'; + + len += sr->type ()->info (&p, sizeof buf - len); + + if (this->debug_) + { + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("len = %d, info = %s%s"), + len, + buf, + buf[len - 1] == '\n' ? ACE_TEXT ("") : ACE_TEXT ("\n"))); + } + + if (len > 0) + { + ssize_t n = this->client_stream_.send_n (buf, len); + + if (n <= 0 && errno != EPIPE) + { + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("send_n"))); + } + } + } + + return 0; +} + +// Trigger a reconfiguration of the Service Configurator via its +// svc.conf file. + +int +ACE_Service_Manager::reconfigure_services (void) +{ + ACE_TRACE ("ACE_Service_Manager::reconfigure_services"); + +#if 0 +// Send ourselves a signal! ACE_OS::kill (ACE_OS::getpid (), +// this->signum_); +#endif /* 0 */ + + // Flag the main event loop that a reconfiguration should occur. + // The next trip through the should + // pick this up and cause a reconfiguration. Note that we can't + // trigger the reconfiguration automatically since that might "pull + // the rug" out from underneath the existing services in a + // problematic way. + ACE_Service_Config::reconfig_occurred ((sig_atomic_t) 1); + return static_cast (this->client_stream_.send_n ("done\n", + sizeof ("done\n"))); +} + +// isolate the request-processing code +void +ACE_Service_Manager::process_request (ACE_TCHAR *request) +{ + ACE_TRACE("ACE_Service_Manager::process_request"); + ACE_TCHAR *p; + + // Kill trailing newlines. + for (p = request; + (*p != '\0') && (*p != '\r') && (*p != '\n'); + p++) + { + continue; + } + + *p = '\0'; + + if (ACE_OS::strcmp (request, ACE_TEXT ("help")) == 0) + { + // Return a list of the configured services. + this->list_services (); + } + else if (ACE_OS::strcmp (request, ACE_TEXT ("reconfigure") )== 0) + { + // Trigger a reconfiguration by re-reading the local file. + this->reconfigure_services (); + } + else + { + // Just process a single request passed in via the socket + // remotely. + ACE_Service_Config_Guard guard (ACE_Service_Config::global ()); + ACE_Service_Config::process_directive (request); + } + + // Additional management services may be handled here... +} + +// Accept new connection from client and carry out the service they +// request. + +int +ACE_Service_Manager::handle_input (ACE_HANDLE) +{ + ACE_TRACE ("ACE_Service_Manager::handle_input"); + + // Try to find out if the implementation of the reactor that we are + // using requires us to reset the event association for the newly + // created handle. This is because the newly created handle will + // inherit the properties of the listen handle, including its event + // associations. + bool reset_new_handle = + ACE_Reactor::instance ()->uses_event_associations (); + + if (this->acceptor_.accept (this->client_stream_, // stream + 0, // remote address + 0, // timeout + 1, // restart + reset_new_handle // reset new handler + ) == -1) + { + return -1; + } + + if (this->debug_) + { + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("client_stream fd = %d\n"), + this->client_stream_.get_handle ())); + ACE_INET_Addr sa; + + if (this->client_stream_.get_remote_addr (sa) == -1) + { + return -1; + } + + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("accepted from host %C at port %d\n"), + sa.get_host_name (), + sa.get_port_number ())); + } + + ACE_TCHAR request[BUFSIZ]; + ACE_TCHAR* offset = request; + ssize_t remaining = sizeof (request); + + // Read service request from client. + + ssize_t result; + + // Keep looping until we actually get the request. Note that Win32 + // sets the socket into non-blocking mode, so we may need to loop if + // the system is heavily loaded. Read bytes into the buffer until a + // '\n' or '\r' is found in the buffer, otherwise the buffer + // contains an incomplete string. + + int error; + + do + { + result = client_stream_.recv (offset, remaining); + error = errno; + + if (result == 0 && error != EWOULDBLOCK) + { + remaining = 0; + } + + if (result >= 0) + { + if ((remaining -= result) <= 0) + { + ACE_DEBUG ((LM_ERROR, + ACE_TEXT ("Request buffer overflow.\n"))); + result = 0; + break; + } + + offset += result; + *offset = 0; + + if (ACE_OS::strchr (request, '\r') != 0 + || ACE_OS::strchr (request, '\n') != 0) + { + remaining = 0; + } + } + } + while ((result == -1 && error == EWOULDBLOCK) || remaining > 0); + + switch (result) + { + case -1: + if (this->debug_) + { + ACE_DEBUG ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("recv"))); + } + + break; + case 0: + return 0; + /* NOTREACHED */ + default: + { + ACE_Event_Handler *old_signal_handler = 0; + ACE_Reactor::instance ()->register_handler (SIGPIPE, + this, + 0, + &old_signal_handler); + + this->process_request (request); + + // Restore existing SIGPIPE handler + ACE_Reactor::instance ()->register_handler (SIGPIPE, + old_signal_handler); + } + } + + if (this->client_stream_.close () == -1 && this->debug_) + { + ACE_DEBUG ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("close"))); + } + + return 0; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Service_Manager.h b/dep/acelite/ace/Service_Manager.h new file mode 100644 index 00000000000..13ce60405ff --- /dev/null +++ b/dep/acelite/ace/Service_Manager.h @@ -0,0 +1,120 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Service_Manager.h + * + * $Id: Service_Manager.h 81388 2008-04-23 14:02:05Z johnnyw $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_SERVICE_MANAGER_H +#define ACE_SERVICE_MANAGER_H +#include /**/ "ace/pre.h" + +#include "ace/SOCK_Stream.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/SOCK_Acceptor.h" +#include "ace/INET_Addr.h" +#include "ace/Service_Object.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Service_Manager + * + * @brief Provide a standard ACE service for managing all the services + * configured in an ACE_Service_Repository. + * + * This implementation is simple and just handles each client + * request one at a time. There are currently 3 types of requests: + * - List services: If the string "help" is sent, return a list of all + * the services supported by the Service Configurator. + * - Reconfigure: If the string "reconfigure" is sent trigger a + * reconfiguration, which will re-read the local file. + * - Process directive: If neither "help" nor "reconfigure" is sent, + * simply treat the incoming string as a process directive and pass + * it along to . This allows + * remote configuration via command-line instructions like + * % echo suspend My_Remote_Service | telnet hostname 3911 + * + * Each request is associated with a new connection, which is closed + * when the request is processed. In addition, you must be using the + * singleton in order to trigger + * reconfigurations. + */ +class ACE_Export ACE_Service_Manager : public ACE_Service_Object +{ +public: + // = Initialization and termination hooks. + /// Constructor. + ACE_Service_Manager (void); + + /// Destructor. + virtual ~ACE_Service_Manager (void); + +protected: + // = Perform the various meta-services. + + /// Trigger a reconfiguration of the Service Configurator by + /// re-reading its local file. + virtual int reconfigure_services (void); + + /// Determine all the services offered by this daemon and return the + /// information back to the client. + virtual int list_services (void); + + // = Dynamic linking hooks. + virtual int init (int argc, ACE_TCHAR *argv[]); + virtual int info (ACE_TCHAR **info_string, size_t length) const; + virtual int fini (void); + + // = Scheduling hooks. + virtual int suspend (void); + virtual int resume (void); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + int open (const ACE_INET_Addr &sia); + + // = Demultiplexing hooks. + virtual ACE_HANDLE get_handle (void) const; + virtual int handle_input (ACE_HANDLE fd); + virtual int handle_close (ACE_HANDLE fd, ACE_Reactor_Mask); + virtual int handle_signal (int signum, siginfo_t *, ucontext_t *); + + /// Handle one request. + virtual void process_request (ACE_TCHAR *request); + + /// Connection to the client (we only support one client connection + /// at a time). + ACE_SOCK_Stream client_stream_; + + /// Acceptor instance. + ACE_SOCK_Acceptor acceptor_; + + /// Keep track whether we debug or not. + bool debug_; + + /// The signal used to trigger reconfiguration. + int signum_; + + /// Default port for the Acceptor to listen on. + static u_short DEFAULT_PORT_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" +#endif /* _SERVICE_MANAGER_H */ diff --git a/dep/acelite/ace/Service_Object.cpp b/dep/acelite/ace/Service_Object.cpp new file mode 100644 index 00000000000..0ac76be21cb --- /dev/null +++ b/dep/acelite/ace/Service_Object.cpp @@ -0,0 +1,183 @@ +// $Id: Service_Object.cpp 90077 2010-05-05 16:19:16Z cbeaulac $ + +#include "ace/config-all.h" + +#include "ace/Service_Object.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Service_Object.inl" +#endif /* __ACE_INLINE__ */ + +#include "ace/OS_NS_stdio.h" +#include "ace/Service_Types.h" +#include "ace/DLL.h" +#include "ace/ACE.h" +#include "ace/Log_Msg.h" +#if defined (ACE_OPENVMS) +# include "ace/Lib_Find.h" +#endif + +ACE_RCSID (ace, + Service_Object, + "$Id: Service_Object.cpp 90077 2010-05-05 16:19:16Z cbeaulac $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Service_Object) +ACE_ALLOC_HOOK_DEFINE(ACE_Service_Type) + +void +ACE_Service_Type::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Service_Type::dump"); +#endif /* ACE_HAS_DUMP */ + + + // Using printf, since the log facility may not have been + // initialized yet. Using a "//" prefix, in case the executable + // happens to be a code generator and the output gets embedded in + // the generated C++ code. + ACE_OS::fprintf(stderr, + "// [ST] dump, this=%p, name=%s, type=%p, so=%p, active=%d\n", + this, + this->name_, + this->type_, + (this->type_ != 0) ? this->type_->object () : 0, + this->active_); + +} + +ACE_Service_Type::ACE_Service_Type (const ACE_TCHAR *n, + ACE_Service_Type_Impl *t, + const ACE_DLL &dll, + bool active) + : name_ (0), + type_ (t), + dll_ (dll), + active_ (active), + fini_already_called_ (false) +{ + ACE_TRACE ("ACE_Service_Type::ACE_Service_Type"); + this->name (n); +} + +ACE_Service_Type::ACE_Service_Type (const ACE_TCHAR *n, + ACE_Service_Type_Impl *t, + ACE_SHLIB_HANDLE handle, + bool active) + : name_ (0), + type_ (t), + active_ (active), + fini_already_called_ (false) +{ + ACE_TRACE ("ACE_Service_Type::ACE_Service_Type"); + this->dll_.set_handle (handle); + this->name (n); +} + +ACE_Service_Type::~ACE_Service_Type (void) +{ + ACE_TRACE ("ACE_Service_Type::~ACE_Service_Type"); + this->fini (); + + delete [] const_cast (this->name_); +} + +int +ACE_Service_Type::fini (void) +{ + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) ST::fini - destroying name=%s, dll=%s\n"), + this->name_, + this->dll_.dll_name_)); + + if (this->fini_already_called_) + return 0; + + this->fini_already_called_ = true; + + if (this->type_ == 0) + { + // Returning 1 currently only makes sense for dummy instances, used + // to "reserve" a spot (kind of like forward-declarations) for a + // dynamic service. This is necessary to help enforce the correct + // finalization order, when such service also has any (dependent) + // static services + + return 1; // No implementation was found. + } + + int ret = this->type_->fini (); + + // Ensure type is 0 to prevent invalid access after call to fini. + this->type_ = 0; + + // Ensure that closing the DLL is done after type_->fini() as it may + // require access to the code for the service object destructor, + // which resides in the DLL + + return (ret | this->dll_.close ()); +} + +int +ACE_Service_Type::suspend (void) const +{ + ACE_TRACE ("ACE_Service_Type::suspend"); + (const_cast (this))->active_ = false; + return this->type_->suspend (); +} + +int +ACE_Service_Type::resume (void) const +{ + ACE_TRACE ("ACE_Service_Type::resume"); + (const_cast (this))->active_ = true; + return this->type_->resume (); +} + +ACE_Service_Object::ACE_Service_Object (ACE_Reactor *r) + : ACE_Event_Handler (r) +{ + ACE_TRACE ("ACE_Service_Object::ACE_Service_Object"); +} + +ACE_Service_Object::~ACE_Service_Object (void) +{ + ACE_TRACE ("ACE_Service_Object::~ACE_Service_Object"); +} + +int +ACE_Service_Object::suspend (void) +{ + ACE_TRACE ("ACE_Service_Object::suspend"); + return 0; +} + +int +ACE_Service_Object::resume (void) +{ + ACE_TRACE ("ACE_Service_Object::resume"); + return 0; +} + +void +ACE_Service_Type::name (const ACE_TCHAR *n) +{ + ACE_TRACE ("ACE_Service_Type::name"); + + delete [] const_cast (this->name_); + this->name_ = ACE::strnew (n); +} + +#if defined (ACE_OPENVMS) +ACE_Dynamic_Svc_Registrar::ACE_Dynamic_Svc_Registrar (const ACE_TCHAR* alloc_name, + void* svc_allocator) +{ + // register service allocator function by full name in ACE singleton registry + ACE::ldregister (alloc_name, svc_allocator); +} +#endif + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Service_Object.h b/dep/acelite/ace/Service_Object.h new file mode 100644 index 00000000000..2f24ccbd47d --- /dev/null +++ b/dep/acelite/ace/Service_Object.h @@ -0,0 +1,206 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file Service_Object.h + * + * $Id: Service_Object.h 84170 2009-01-15 13:31:50Z johnnyw $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_SERVICE_OBJECT_H +#define ACE_SERVICE_OBJECT_H +#include /**/ "ace/pre.h" + +#include "ace/Shared_Object.h" +#include "ace/Svc_Conf_Tokens.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Event_Handler.h" +#include "ace/DLL.h" + +#include "ace/Service_Gestalt.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +#define ACE_Component ACE_Service_Object + +/** + * @class ACE_Service_Object + * + * @brief Provide the abstract base class common to all service + * implementations. + * + * Classes that inherit from ACE_Service_Objects are capable + * of being registered with the ACE_Reactor (due to the + * ACE_Event_Handler, as well as being dynamically linked by + * the ACE_Service_Config (due to the ACE_Shared_Object). + */ +class ACE_Export ACE_Service_Object + : public ACE_Event_Handler, + public ACE_Shared_Object +{ +public: + // = Initialization and termination methods. + /// Constructor. + ACE_Service_Object (ACE_Reactor * = 0); + + /// Destructor. + virtual ~ACE_Service_Object (void); + + /// Temporarily disable a service without removing it completely. + virtual int suspend (void); + + /// Re-enable a previously suspended service. + virtual int resume (void); +}; + +// Forward decl. +class ACE_Service_Type_Impl; + +/** + * @class ACE_Service_Type + * + * @brief Keeps track of information related to the various + * ACE_Service_Type_Impl subclasses. + * + * This class acts as the interface of the "Bridge" pattern. + */ +class ACE_Export ACE_Service_Type +{ +public: + enum + { + /// Delete the payload object. + DELETE_OBJ = 1, + + /// Delete the enclosing object. + DELETE_THIS = 2 + }; + + enum + { + SERVICE_OBJECT = ACE_SVC_OBJ_T, + MODULE = ACE_MODULE_T, + STREAM = ACE_STREAM_T, + INVALID_TYPE = -1 + }; + + // = Initialization and termination methods. + ACE_Service_Type (const ACE_TCHAR *n, + ACE_Service_Type_Impl *o, + const ACE_DLL &dll, + bool active); + ACE_Service_Type (const ACE_TCHAR *n, + ACE_Service_Type_Impl *o, + ACE_SHLIB_HANDLE handle, + bool active); + ~ACE_Service_Type (void); + + const ACE_TCHAR *name (void) const; + void name (const ACE_TCHAR *); + + const ACE_Service_Type_Impl *type (void) const; + void type (const ACE_Service_Type_Impl *, bool active = true); + + /// Is this just a stub for the real thing? + bool is_forward_declaration (void) const; + + int suspend (void) const; + int resume (void) const; + bool active (void) const; + void active (bool turnon); + + /// Calls @c fini on @c type_ + int fini (void); + + /// Check if the service has been fini'ed. + bool fini_called (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Get to the DLL's implentation + const ACE_DLL & dll (void) const; + + /// Sets the DLL + void dll (const ACE_DLL&); + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + /// Humanly readible name of svc. + const ACE_TCHAR *name_; + + /// Pointer to C++ object that implements the svc. + const ACE_Service_Type_Impl *type_; + + /// ACE_DLL representing the shared object file (non-zero if + /// dynamically linked). + mutable ACE_DLL dll_; + + /// true if svc is currently active, otherwise false. + bool active_; + + /// true if @c fini on @c type_ has already been called, otherwise false. + bool fini_already_called_; +}; + +/** + * @class ACE_Service_Object_Ptr + * + * @brief This is a smart pointer that holds onto the associated + * ACE_Service_Object * until the current scope is left, at + * which point the object's fini() hook is called and the + * service_object_ gets deleted. + * + * This class is similar to the Standard C++ Library class + * auto_ptr. It is used in conjunction with statically linked + * ACE_Service_Objects, as shown in the ./netsvcs/server/main.cpp example. + */ +class ACE_Export ACE_Service_Object_Ptr +{ +public: + // = Initialization and termination methods. + /// Acquire ownership of the @a so. + ACE_Service_Object_Ptr (ACE_Service_Object *so); + + /// Release the held ACE_Service_Object by calling its fini() hook. + ~ACE_Service_Object_Ptr (void); + + /// Smart pointer to access the underlying ACE_Service_Object. + ACE_Service_Object *operator-> (); + +private: + /// Holds the service object until we're done. + ACE_Service_Object *service_object_; +}; + +#if defined (ACE_OPENVMS) +/** + * @class ACE_Dynamic_Svc_Registrar + * + * @brief Used to register Service allocator function by its full name. + */ +class ACE_Dynamic_Svc_Registrar +{ +public: + ACE_Dynamic_Svc_Registrar (const ACE_TCHAR* alloc_name, + void* svc_allocator); +}; +#endif + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Service_Object.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_SERVICE_OBJECT_H */ diff --git a/dep/acelite/ace/Service_Object.inl b/dep/acelite/ace/Service_Object.inl new file mode 100644 index 00000000000..6283f3e9981 --- /dev/null +++ b/dep/acelite/ace/Service_Object.inl @@ -0,0 +1,79 @@ +// -*- C++ -*- +// $Id: Service_Object.inl 81388 2008-04-23 14:02:05Z johnnyw $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE ACE_Service_Object_Ptr::ACE_Service_Object_Ptr (ACE_Service_Object *so) + : service_object_ (so) +{ +} + +ACE_INLINE ACE_Service_Object_Ptr::~ACE_Service_Object_Ptr (void) +{ + this->service_object_->fini (); + delete this->service_object_; +} + +ACE_INLINE ACE_Service_Object * +ACE_Service_Object_Ptr::operator-> () +{ + return this->service_object_; +} + +ACE_INLINE const ACE_TCHAR * +ACE_Service_Type::name (void) const +{ + ACE_TRACE ("ACE_Service_Type::name"); + return this->name_; +} + +ACE_INLINE const ACE_Service_Type_Impl * +ACE_Service_Type::type (void) const +{ + ACE_TRACE ("ACE_Service_Type::type"); + return this->type_; +} + +ACE_INLINE void +ACE_Service_Type::type (const ACE_Service_Type_Impl *o, bool enabled) +{ + ACE_TRACE ("ACE_Service_Type::type"); + this->type_ = o; + ((ACE_Service_Type *) this)->active_ = enabled; +} + +ACE_INLINE bool +ACE_Service_Type::active (void) const +{ + ACE_TRACE ("ACE_Service_Type::active"); + return this->active_; +} + +ACE_INLINE void +ACE_Service_Type::active (bool turnon) +{ + ACE_TRACE ("ACE_Service_Type::active"); + this->active_ = turnon; +} + +ACE_INLINE bool +ACE_Service_Type::fini_called (void) const +{ + ACE_TRACE ("ACE_Service_Type::fini_called"); + return this->fini_already_called_; +} + +ACE_INLINE const ACE_DLL & ACE_Service_Type::dll () const +{ + ACE_TRACE ("ACE_Service_Type::dll"); + return this->dll_; +} + +ACE_INLINE void ACE_Service_Type::dll (const ACE_DLL &adll) +{ + ACE_TRACE ("ACE_Service_Type::dll"); + this->dll_ = adll; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + diff --git a/dep/acelite/ace/Service_Repository.cpp b/dep/acelite/ace/Service_Repository.cpp new file mode 100644 index 00000000000..10195145ff1 --- /dev/null +++ b/dep/acelite/ace/Service_Repository.cpp @@ -0,0 +1,630 @@ +// $Id: Service_Repository.cpp 90337 2010-05-28 20:00:49Z cbeaulac $ + +#include "ace/Service_Repository.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Service_Repository.inl" +#endif /* __ACE_INLINE__ */ + +#include "ace/Service_Types.h" +#include "ace/Object_Manager.h" +#include "ace/Log_Msg.h" +#include "ace/ACE.h" +#include "ace/OS_NS_unistd.h" +#include "ace/OS_NS_errno.h" +#include "ace/OS_NS_string.h" + +ACE_RCSID (ace, + Service_Repository, + "$Id: Service_Repository.cpp 90337 2010-05-28 20:00:49Z cbeaulac $") + + ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Service_Repository) + +/// Process-wide Service Repository. +ACE_Service_Repository *ACE_Service_Repository::svc_rep_ = 0; + +/// Controls whether the Service_Repository is deleted when we shut +/// down (we can only delete it safely if we created it)! +bool ACE_Service_Repository::delete_svc_rep_ = false; + +void +ACE_Service_Repository::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Service_Repository::dump"); +#endif /* ACE_HAS_DUMP */ +} + +ACE_Service_Repository * +ACE_Service_Repository::instance (size_t size) +{ + ACE_TRACE ("ACE_Service_Repository::instance"); + + if (ACE_Service_Repository::svc_rep_ == 0) + { + // Perform Double-Checked Locking Optimization. + ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, + *ACE_Static_Object_Lock::instance (), 0)); + if (ACE_Service_Repository::svc_rep_ == 0) + { + if (ACE_Object_Manager::starting_up () || + !ACE_Object_Manager::shutting_down ()) + { + ACE_NEW_RETURN (ACE_Service_Repository::svc_rep_, + ACE_Service_Repository (size), + 0); + ACE_Service_Repository::delete_svc_rep_ = true; + } + } + } + + return ACE_Service_Repository::svc_rep_; +} + +ACE_Service_Repository * +ACE_Service_Repository::instance (ACE_Service_Repository *s) +{ + ACE_TRACE ("ACE_Service_Repository::instance"); + ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, + *ACE_Static_Object_Lock::instance (), 0)); + + ACE_Service_Repository *t = ACE_Service_Repository::svc_rep_; + // We can't safely delete it since we don't know who created it! + ACE_Service_Repository::delete_svc_rep_ = false; + + ACE_Service_Repository::svc_rep_ = s; + return t; +} + +void +ACE_Service_Repository::close_singleton (void) +{ + ACE_TRACE ("ACE_Service_Repository::close_singleton"); + + ACE_MT (ACE_GUARD (ACE_Recursive_Thread_Mutex, ace_mon, + *ACE_Static_Object_Lock::instance ())); + + if (ACE_Service_Repository::delete_svc_rep_) + { + delete ACE_Service_Repository::svc_rep_; + ACE_Service_Repository::svc_rep_ = 0; + ACE_Service_Repository::delete_svc_rep_ = false; + } +} + +/// Initialize the Repository to a clean slate. +int +ACE_Service_Repository::open (size_t size) +{ + ACE_TRACE ("ACE_Service_Repository::open"); + + // Create a new array and swap it with the local array + array_type local_array (size); + this->service_array_.swap (local_array); + + return 0; +} + +ACE_Service_Repository::ACE_Service_Repository (size_t size) + : service_array_ (size) +{ + ACE_TRACE ("ACE_Service_Repository::ACE_Service_Repository"); +} + + +/// Finalize (call fini() and possibly delete) all the services. + +int +ACE_Service_Repository::fini (void) +{ + ACE_TRACE ("ACE_Service_Repository::fini"); + ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, this->lock_, -1)); + + int retval = 0; + // Do not be tempted to use the prefix decrement operator. Use + // postfix decrement operator since the index is unsigned and may + // wrap around the 0 + // + // debug output for empty service entries +#ifndef ACE_NLOGGING + if (ACE::debug ()) + { + for (size_t i = this->service_array_.size (); i-- != 0;) + { + ACE_Service_Type *s = + const_cast (this->service_array_[i]); + if (s == 0) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) SR::fini, repo=%@ [%d] -> 0\n"), + this, + i)); + } + } +#endif + // + // Remove all the Service_Object and Stream instances + // + for (size_t i = this->service_array_.size (); i-- != 0;) + { + // the services in reverse order. + ACE_Service_Type *s = + const_cast (this->service_array_[i]); + + if (s != 0 && + s->type () != 0 && + (s->type ()->service_type () != ACE_Service_Type::MODULE)) + { +#ifndef ACE_NLOGGING + if (ACE::debug ()) + { + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) SR::fini, repo=%@ [%d], ") + ACE_TEXT ("name=%s, type=%@, object=%@, active=%d\n"), + this, + i, + s->name (), + s->type (), + (s->type () != 0) ? s->type ()->object () : 0, + s->active ())); + } +#endif + + // Collect any errors. + retval += s->fini (); + } + } + // + // Remove all the Module instances + // + for (size_t i = this->service_array_.size (); i-- != 0;) + { + // the services in reverse order. + ACE_Service_Type *s = + const_cast (this->service_array_[i]); + + if (s != 0 && + s->type () != 0 && + (s->type ()->service_type () == ACE_Service_Type::MODULE)) + { +#ifndef ACE_NLOGGING + if (ACE::debug ()) + { + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) SR::fini, repo=%@ [%d], ") + ACE_TEXT ("name=%s, type=%@, object=%@, active=%d\n"), + this, + i, + s->name (), + s->type (), + (s->type () != 0) ? s->type ()->object () : 0, + s->active ())); + } +#endif + // Collect any errors. + retval += s->fini (); + } + } + return (retval == 0) ? 0 : -1; +} + + +/// Close down all the services. +int +ACE_Service_Repository::close (void) +{ + ACE_TRACE ("ACE_Service_Repository::close"); + ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, this->lock_, -1)); + +#ifndef ACE_NLOGGING + if(ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) SR::close - repo=%@, size=%d\n"), + this, + this->service_array_.size())); +#endif + + // Do not use the prefix decrement operator since the index is + // unsigned and may wrap around the 0. + for (size_t i = this->service_array_.size(); i-- != 0; ) + { + // Delete services in reverse order. + ACE_Service_Type *s = + const_cast (this->service_array_[i]); + +#ifndef ACE_NLOGGING + if(ACE::debug ()) + { + if (s == 0) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) SR::close - repo=%@ [%d] -> 0\n"), + this, + i)); + else + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) SR::close - repo=%@ [%d], name=%s, object=%@\n"), + this, + i, + s->name (), + s)); + } +#endif + delete s; + } + + this->service_array_.clear (); + + return 0; +} + +ACE_Service_Repository::~ACE_Service_Repository (void) +{ + ACE_TRACE ("ACE_Service_Repository::~ACE_Service_Repository"); +#ifndef ACE_NLOGGING + if(ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, "ACE (%P|%t) SR::, this=%@\n", this)); +#endif + this->close (); +} + +/// Locate an entry with @a name in the table. If @a ignore_suspended is +/// set then only consider services marked as resumed. If the caller +/// wants the located entry, pass back a pointer to the located entry +/// via @a srp. If @a name is not found -1 is returned. If @a name is +/// found, but it is suspended and the caller wants to ignore suspended +/// services a -2 is returned. Must be called with locks held. +int +ACE_Service_Repository::find_i (const ACE_TCHAR name[], + size_t &slot, + const ACE_Service_Type **srp, + bool ignore_suspended) const +{ + ACE_TRACE ("ACE_Service_Repository::find_i"); + size_t i = 0; + array_type::const_iterator element = this->service_array_.end (); + + for (i = 0; i < this->service_array_.size(); i++) + { + array_type::const_iterator iter = this->service_array_.find (i); + if (iter != this->service_array_.end () + && (*iter).second != 0 // skip any empty slots + && ACE_OS::strcmp (name, (*iter).second->name ()) == 0) + { + element = iter; + break; + } + } + + if (element != this->service_array_.end ()) + { + slot = i; + if ((*element).second->fini_called ()) + { + if (srp != 0) + *srp = 0; + return -1; + } + + if (srp != 0) + *srp = (*element).second; + + if (ignore_suspended + && (*element).second->active () == 0) + return -2; + + return 0; + } + + return -1; +} + + +/// @brief Relocate (a static) service to another DLL. +/// +/// Works by having the service type keep a reference to a specific +/// DLL. No locking, caller makes sure calling it is safe. You can +/// forcefully relocate any DLLs in the given range, not only the +/// static ones - but that will cause Very Bad Things (tm) to happen. +int +ACE_Service_Repository::relocate_i (size_t begin, + size_t end, + const ACE_DLL& adll) +{ + ACE_SHLIB_HANDLE new_handle = adll.get_handle (0); + + for (size_t i = begin; i < end; i++) + { + ACE_Service_Type *type = + const_cast (this->service_array_[i]); + + ACE_SHLIB_HANDLE old_handle = (type == 0) ? ACE_SHLIB_INVALID_HANDLE + : type->dll ().get_handle (0); + +#ifndef ACE_NLOGGING + if (ACE::debug ()) + { + if (type == 0) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) SR::relocate_i - repo=%@ [%d]") + ACE_TEXT (": skipping empty slot\n"), + this, + i)); + else + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) SR::relocate_i - repo=%@ [%d]") + ACE_TEXT (": trying name=%s, handle: %d -> %d\n"), + this, + i, + type->name (), + old_handle, + new_handle)); + } +#endif + + if (type != 0 // skip any gaps + && old_handle == ACE_SHLIB_INVALID_HANDLE + && new_handle != old_handle) + { +#ifndef ACE_NLOGGING + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) SR::relocate_i - repo=%@ [%d]") + ACE_TEXT (": relocating name=%s, handle: %d -> %d\n"), + this, + i, + type->name (), + old_handle, + new_handle)); +#endif + type->dll (adll); // ups the refcount on adll + } + } + + return 0; +} + +int +ACE_Service_Repository::find (const ACE_TCHAR name[], + const ACE_Service_Type **srp, + bool ignore_suspended) const +{ + ACE_TRACE ("ACE_Service_Repository::find"); + ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, this->lock_, -1)); + size_t ignore_location = 0; + return this->find_i (name, ignore_location, srp, ignore_suspended); +} + +/// Insert the ACE_Service_Type SR into the repository. Note that +/// services may be inserted either resumed or suspended. Using same +/// name as in an existing service causes the delete () to be called +/// for the old one, i.e. make sure @code sr is allocated on the heap! +int +ACE_Service_Repository::insert (const ACE_Service_Type *sr) +{ + ACE_TRACE ("ACE_Service_Repository::insert"); + + size_t i = 0; + int return_value = -1; + ACE_Service_Type const *s = 0; + + // Establish scope for locking while manipulating the service + // storage + { + // @TODO: Do we need a recursive mutex here? + ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, + ace_mon, + this->lock_, + -1)); + + return_value = find_i (sr->name (), i, &s, false); + + // Adding an entry. + if (s != 0) + { + this->service_array_[i] = sr; + } + else + { + // New services are always added where current_size_ points, + // because if any DLL relocation needs to happen, it will be + // performed on services with indexes between some old + // current_size_ and the new current_size_ value. See + // ACE_Service_Type_Dynamic_Guard ctor and dtor for details. + + if (i < this->service_array_.size ()) + i = this->service_array_.size (); + + this->service_array_[i] = sr; + return_value = 0; + } + } +#ifndef ACE_NLOGGING + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) SR::insert - repo=%@ [%d],") + ACE_TEXT (" name=%s (%C) (type=%@, object=%@, active=%d)\n"), + this, + i, + sr->name(), + (return_value == 0 ? ((s==0) ? "new" : "replacing") : "failed"), + sr->type (), + (sr->type () != 0) ? sr->type ()->object () : 0, + sr->active ())); +#endif + + // If necessary, delete but outside the lock. (s may be 0, but + // that's okay, too) + delete s; + + if (return_value == -1) + ACE_OS::last_error (ENOSPC); + + return return_value; +} + +/// Resume a service that was previously suspended. +int +ACE_Service_Repository::resume (const ACE_TCHAR name[], + const ACE_Service_Type **srp) +{ + ACE_TRACE ("ACE_Service_Repository::resume"); + ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, this->lock_, -1)); + + size_t i = 0; + if (-1 == this->find_i (name, i, srp, 0)) + return -1; + + return this->service_array_[i]->resume (); +} + +/// Suspend a service so that it will not be considered active under +/// most circumstances by other portions of the ACE_Service_Repository. +int +ACE_Service_Repository::suspend (const ACE_TCHAR name[], + const ACE_Service_Type **srp) +{ + ACE_TRACE ("ACE_Service_Repository::suspend"); + ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, this->lock_, -1)); + size_t i = 0; + if (-1 == this->find_i (name, i, srp, 0)) + return -1; + + return this->service_array_[i]->suspend (); +} + +/** + * @brief Completely remove a @a name entry from the Repository and + * dynamically unlink it if it was originally dynamically linked. + */ +int +ACE_Service_Repository::remove (const ACE_TCHAR name[], ACE_Service_Type **ps) +{ + ACE_TRACE ("ACE_Service_Repository::remove"); + ACE_Service_Type *s = 0; + { + ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, this->lock_, -1)); + + // Not found!? + if (this->remove_i (name, &s) == -1) + return -1; + } + + if (ps != 0) + *ps = s; + else + delete s; + return 0; +} + +/** + * @brief Completely remove a @a name entry from the Repository and + * dynamically unlink it if it was originally dynamically linked. + * + * Return a ptr to the entry in @code ps. There is no locking so make + * sure you hold the repo lock when calling. + * + * Since the order of services in the Respository matters, we can't + * simply overwrite the entry being deleted with the last and + * decrement the @c current_size by 1. A good example of why the order + * matters is a dynamic service, in whose DLL there is at least one + * static service. In order to prevent SEGV during finalization, those + * static services must be finalized _before_the dynamic service that + * owns them. Otherwice the TEXT segment, containing the code for the + * static service's desructor may be unloaded with the DLL. + * + * Neither can we "pack" the array because this may happen inside the + * scope of a Service_Dynamic_Guard, which caches an index where + * loading of a DLL started in order to relocate dependent services. + */ +int +ACE_Service_Repository::remove_i (const ACE_TCHAR name[], ACE_Service_Type **ps) +{ + size_t i = 0; + if (-1 == this->find_i (name, i, 0, false)) + return -1; // Not found + + // We may need the old ptr - to be delete outside the lock! + *ps = const_cast (this->service_array_[i]); + +#ifndef ACE_NLOGGING + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ACE (%P|%t) SR::remove_i - repo=%@ [%d],") + ACE_TEXT (" name=%s (removed) (type=%@, active=%d)\n"), + this, + i, + name, + *ps, + (*ps)->active ())); +#endif + + this->service_array_[i] = 0; // simply leave a gap + return 0; +} + +ACE_ALLOC_HOOK_DEFINE(ACE_Service_Repository_Iterator) + +void +ACE_Service_Repository_Iterator::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Service_Repository_Iterator::dump"); +#endif /* ACE_HAS_DUMP */ +} + +/// Initializes the iterator and skips over any suspended entries at +/// the beginning of the table, if necessary. Note, you must not +/// perform destructive operations on elements during this iteration... +ACE_Service_Repository_Iterator::ACE_Service_Repository_Iterator + (ACE_Service_Repository &sr, bool ignored_suspended) + : svc_rep_ (sr), + next_ (0), + ignore_suspended_ (ignored_suspended) +{ + while (!(done() || valid())) + this->next_++; +} + +/// Obtains a pointer to the next valid service in the table. If there +/// are no more entries, returns 0, else 1. +int +ACE_Service_Repository_Iterator::next (const ACE_Service_Type *&sr) +{ + ACE_TRACE ("ACE_Service_Repository_Iterator::next"); + + if (done ()) + return 0; + + sr = this->svc_rep_.service_array_[this->next_]; + return 1; +} + +/// Advance the iterator by the proper amount. If we are ignoring +/// suspended entries and the current entry is suspended, then we must +/// skip over this entry. Otherwise, we must advance the NEXT index to +/// reference the next valid service entry. +int +ACE_Service_Repository_Iterator::advance (void) +{ + ACE_TRACE ("ACE_Service_Repository_Iterator::advance"); + + if (done()) return 0; + + do this->next_++; while (!(done () || valid ())); + + return !done(); +} + +bool +ACE_Service_Repository_Iterator::valid (void) const +{ + ACE_TRACE ("ACE_Service_Repository_Iterator::valid"); + if (!this->ignore_suspended_) + return (this->svc_rep_.service_array_[this->next_] != 0); // skip over gaps + + return (this->svc_rep_.service_array_[this->next_] != 0 + && this->svc_rep_.service_array_[this->next_]->active ()); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Service_Repository.h b/dep/acelite/ace/Service_Repository.h new file mode 100644 index 00000000000..9d03b113381 --- /dev/null +++ b/dep/acelite/ace/Service_Repository.h @@ -0,0 +1,271 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Service_Repository.h + * + * $Id: Service_Repository.h 91016 2010-07-06 11:29:50Z johnnyw $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_SERVICE_REPOSITORY_H +#define ACE_SERVICE_REPOSITORY_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Default_Constants.h" +#include "ace/Recursive_Thread_Mutex.h" +#include "ace/Array_Map.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +class ACE_Service_Type; +class ACE_DLL; + +#define ACE_Component_Repository ACE_Service_Repository +/** + * @class ACE_Service_Repository + * + * @brief Contains all the services offered by a Service + * Configurator-based application. + * + * This class contains a vector of ACE_Service_Types *'s and + * allows an administrative entity to centrally manage and + * control the behavior of application services. Note that if + * services are removed from the middle of the repository the + * order won't necessarily be maintained since the @a remove + * method performs compaction. However, the common case is not + * to remove services, so typically they are deleted in the + * reverse order that they were added originally. + */ +class ACE_Export ACE_Service_Repository +{ +public: + friend class ACE_Service_Repository_Iterator; + + enum + { + DEFAULT_SIZE = ACE_DEFAULT_SERVICE_REPOSITORY_SIZE + }; + + // = Initialization and termination methods. + /// Initialize the repository. + ACE_Service_Repository (size_t size = DEFAULT_SIZE); + + /// Initialize the repository. + int open (size_t size = DEFAULT_SIZE); + + /// Close down the repository and free up dynamically allocated + /// resources. + ~ACE_Service_Repository (void); + + /// Close down the repository and free up dynamically allocated + /// resources. + int close (void); + + /// Finalize all the services by calling fini() and deleting + /// dynamically allocated services. + int fini (void); + + /// Get pointer to a process-wide ACE_Service_Repository. + static ACE_Service_Repository * instance + (size_t size = ACE_Service_Repository::DEFAULT_SIZE); + + /// Set pointer to a process-wide ACE_Service_Repository and return + /// existing pointer. + static ACE_Service_Repository *instance (ACE_Service_Repository *); + + /// Delete the dynamically allocated Singleton. + static void close_singleton (void); + + // = Search structure operations (all acquire locks as necessary). + + /// Insert a new service record. Returns -1 when the service repository + /// is full and 0 on success. + int insert (const ACE_Service_Type *sr); + + /** + * Locate a named entry in the service table, optionally ignoring + * suspended entries. + * + * @param name The name of the service to search for. + * @param srp Optional; if not 0, it is a pointer to a location + * to receive the ACE_Service_Type pointer for the + * located service. Meaningless if this method + * returns -1. + * @param ignore_suspended If true, the search ignores suspended services. + * + * @retval 0 Named service was located. + * @retval -1 Named service was not found. + * @retval -2 Named service was found, but is suspended and + * @a ignore_suspended is true. + */ + int find (const ACE_TCHAR name[], + const ACE_Service_Type **srp = 0, + bool ignore_suspended = true) const; + + /// Remove an existing service record. If @a sr == 0, the service record + /// is deleted before control is returned to the caller. If @a sr != 0, + /// the service's record is removed from the repository, but not deleted; + /// *sr receives the service record pointer and the caller is responsible + /// for properly disposing of it. + int remove (const ACE_TCHAR name[], ACE_Service_Type **sr = 0); + + // = Liveness control + /// Resume a service record. + int resume (const ACE_TCHAR name[], const ACE_Service_Type **srp = 0); + + /// Suspend a service record. + int suspend (const ACE_TCHAR name[], const ACE_Service_Type **srp = 0); + + /// Return the current size of the repository. + size_t current_size (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + + friend class ACE_Service_Type_Dynamic_Guard; + + /// Remove an existing service record. It requires @a sr != 0, which + /// receives the service record pointer and the caller is + /// responsible for properly disposing of it. + int remove_i (const ACE_TCHAR[], ACE_Service_Type **sr); + + /** + * Locate a named entry in the service table, optionally ignoring + * suspended entries. + * + * @param service_name The name of the service to search for. + * @param slot Receives the position index of the service if it + * is found. Contents are meaningless if this method + * returns -1. + * @param srp Optional; if not 0, it is a pointer to a location + * to receive the ACE_Service_Type pointer for the + * located service. Meaningless if this method + * returns -1. + * @param ignore_suspended If true, the search ignores suspended services. + * + * @retval 0 Named service was located; index in the table is set in + * @a slot. + * @retval -1 Named service was not found. + * @retval -2 Named service was found, but is suspended and + * @a ignore_suspended is true. + */ + int find_i (const ACE_TCHAR service_name[], + size_t &slot, + const ACE_Service_Type **srp = 0, + bool ignore_suspended = true) const; + + /// @brief Relocate (static) services to another DLL. + /// + /// If any have been registered in the context of a "forward + /// declaration" guard, those really aren't static services. Their + /// code is in the DLL's code segment, or in one of the dependent + /// DLLs. Therefore, such services need to be associated with the + /// proper DLL in order to prevent failures upon finalization. The + /// method locks the repo. + /// + /// Works by having the service type keep a reference to a specific + /// DLL. No locking, caller makes sure calling it is safe. You can + /// forcefully relocate any DLLs in the given range, not only the + /// static ones - but that will cause Very Bad Things (tm) to happen. + int relocate_i (size_t begin, + size_t end, + const ACE_DLL &adll); + + /// The typedef of the array used to store the services. + typedef ACE_Array_Map array_type; + + /// Contains all the configured services. + array_type service_array_; + + /// Pointer to a process-wide ACE_Service_Repository. + static ACE_Service_Repository *svc_rep_; + + /// Must delete the @c svc_rep_ if true. + static bool delete_svc_rep_; + +#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) + /// Synchronization variable for the MT_SAFE Repository + mutable ACE_Recursive_Thread_Mutex lock_; +#endif /* ACE_MT_SAFE */ +}; + +/** + * @class ACE_Service_Repository_Iterator + * + * @brief Iterate through the ACE_Service_Repository. + * + * Make sure not to delete entries as the iteration is going on + * since this class is not designed as a robust iterator. + */ +class ACE_Export ACE_Service_Repository_Iterator +{ +public: + // = Initialization and termination methods. + /// Constructor initializes the iterator. + ACE_Service_Repository_Iterator (ACE_Service_Repository &sr, + bool ignored_suspended = true); + + /// Destructor. + ~ACE_Service_Repository_Iterator (void); + + +public: + // = Iteration methods. + + /// Pass back the @a next_item that hasn't been seen in the repository. + /// Returns 0 when all items have been seen, else 1. + int next (const ACE_Service_Type *&next_item); + + /// Returns 1 when all items have been seen, else 0. + int done (void) const; + + /// Move forward by one element in the repository. Returns 0 when all the + /// items in the set have been seen, else 1. + int advance (void); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + bool valid (void) const; + +private: + ACE_Service_Repository_Iterator (const ACE_Service_Repository_Iterator&); + + /// Reference to the Service Repository we are iterating over. + ACE_Service_Repository &svc_rep_; + + /// Next index location that we haven't yet seen. + size_t next_; + + /// Are we ignoring suspended services? + bool const ignore_suspended_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Service_Repository.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" + +#endif /* _SERVICE_REPOSITORY_H */ diff --git a/dep/acelite/ace/Service_Repository.inl b/dep/acelite/ace/Service_Repository.inl new file mode 100644 index 00000000000..1645f380335 --- /dev/null +++ b/dep/acelite/ace/Service_Repository.inl @@ -0,0 +1,38 @@ +// -*- C++ -*- +// +// $Id: Service_Repository.inl 84170 2009-01-15 13:31:50Z johnnyw $ + +// Returns a count of the number of currently valid entries (counting +// both resumed and suspended entries). + +#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) +#include "ace/Guard_T.h" +#include "ace/Thread_Mutex.h" +#endif /* ACE_MT_SAFE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE size_t +ACE_Service_Repository::current_size (void) const +{ + ACE_TRACE ("ACE_Service_Repository::current_size"); + ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, + ace_mon, + (ACE_Recursive_Thread_Mutex &) this->lock_, 0)); + return this->service_array_.size (); +} + +ACE_INLINE int +ACE_Service_Repository_Iterator::done (void) const +{ + ACE_TRACE ("ACE_Service_Repository_Iterator::done"); + + return this->next_ >= this->svc_rep_.current_size (); +} + +ACE_INLINE +ACE_Service_Repository_Iterator::~ACE_Service_Repository_Iterator (void) +{ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Service_Templates.h b/dep/acelite/ace/Service_Templates.h new file mode 100644 index 00000000000..d05d0d611d2 --- /dev/null +++ b/dep/acelite/ace/Service_Templates.h @@ -0,0 +1,29 @@ + +//============================================================================= +/** + * @file Service_Templates.h + * + * $Id: Service_Templates.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Priyanka Gontla + */ +//============================================================================= + + +#ifndef ACE_SERVICE_TEMPLATES_H +#define ACE_SERVICE_TEMPLATES_H +#include /**/ "ace/pre.h" + +#include "ace/Svc_Conf.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Auto_Ptr.h" +#include "ace/Thread_Manager.h" +#include "ace/Stream_Modules.h" +#include "ace/Stream.h" + +#include /**/ "ace/post.h" +#endif /* ACE_SERVICE_TEMPLATES_H */ diff --git a/dep/acelite/ace/Service_Types.cpp b/dep/acelite/ace/Service_Types.cpp new file mode 100644 index 00000000000..3465d774d53 --- /dev/null +++ b/dep/acelite/ace/Service_Types.cpp @@ -0,0 +1,461 @@ +// $Id: Service_Types.cpp 90072 2010-05-04 21:34:39Z cbeaulac $ + +#include "ace/Service_Types.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Service_Types.inl" +#endif /* __ACE_INLINE__ */ + +#include "ace/Stream_Modules.h" +#include "ace/Stream.h" +#include "ace/OS_NS_stdio.h" +#include "ace/OS_NS_string.h" + + +ACE_RCSID (ace, + Service_Types, + "$Id: Service_Types.cpp 90072 2010-05-04 21:34:39Z cbeaulac $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +typedef ACE_Stream MT_Stream; +typedef ACE_Module MT_Module; +typedef ACE_Task MT_Task; + +ACE_ALLOC_HOOK_DEFINE(ACE_Service_Type_Impl) + +void +ACE_Service_Type_Impl::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Service_Type_Impl::dump"); +#endif /* ACE_HAS_DUMP */ +} + +ACE_Service_Type_Impl::ACE_Service_Type_Impl (void *so, + const ACE_TCHAR *s_name, + u_int f, + ACE_Service_Object_Exterminator gobbler, + int stype) + : name_ (0), + obj_ (so), + gobbler_ (gobbler), + flags_ (f), + service_type_ (stype) +{ + ACE_TRACE ("ACE_Service_Type_Impl::ACE_Service_Type_Impl"); + this->name (s_name); +} + +ACE_Service_Type_Impl::~ACE_Service_Type_Impl (void) +{ + ACE_TRACE ("ACE_Service_Type_Impl::~ACE_Service_Type_Impl"); + + // It's ok to call this, even though we may have already deleted it + // in the fini() method since it would then be NULL. + delete [] const_cast (this->name_); +} + +int +ACE_Service_Type_Impl::fini (void) const +{ + ACE_TRACE ("ACE_Service_Type_Impl::fini"); + + delete [] const_cast (this->name_); + (const_cast (this))->name_ = 0; + + if (ACE_BIT_ENABLED (this->flags_, + ACE_Service_Type::DELETE_OBJ)) + { + if (gobbler_ != 0) + gobbler_ (this->object ()); + else + // Cast to remove const-ness. + operator delete ((void *) this->object ()); + } + + if (ACE_BIT_ENABLED (this->flags_, + ACE_Service_Type::DELETE_THIS)) + delete const_cast (this); + + return 0; +} + +ACE_Service_Object_Type::ACE_Service_Object_Type (void *so, + const ACE_TCHAR *s_name, + u_int f, + ACE_Service_Object_Exterminator gobbler, + int stype) + : ACE_Service_Type_Impl (so, s_name, f, gobbler, stype) + , initialized_ (-1) +{ + ACE_TRACE ("ACE_Service_Object_Type::ACE_Service_Object_Type"); +} + +int +ACE_Service_Object_Type::init (int argc, ACE_TCHAR *argv[]) const +{ + ACE_TRACE ("ACE_Service_Object_Type::init"); + + void * const obj = this->object (); + + ACE_Service_Object * const so = + static_cast (obj); + + if (so == 0) + return -1; + + this->initialized_ = so->init (argc, argv); + + return this->initialized_; +} + +int +ACE_Service_Object_Type::fini (void) const +{ + ACE_TRACE ("ACE_Service_Object_Type::fini"); + + void * const obj = this->object (); + + ACE_Service_Object * const so = + static_cast (obj); + + // Call fini() if an only if, the object was successfuly + // initialized, i.e. init() returned 0. This is necessary to + // maintain the ctor/dtor-like semantics for init/fini. + if (so != 0 && this->initialized_ == 0) + so->fini (); + + return ACE_Service_Type_Impl::fini (); +} + +ACE_Service_Object_Type::~ACE_Service_Object_Type (void) +{ + ACE_TRACE ("ACE_Service_Object_Type::~ACE_Service_Object_Type"); +} + +int +ACE_Service_Object_Type::suspend (void) const +{ + ACE_TRACE ("ACE_Service_Object_Type::suspend"); + return static_cast (this->object ())->suspend (); +} + +int +ACE_Service_Object_Type::resume (void) const +{ + ACE_TRACE ("ACE_Service_Object_Type::resume"); + return static_cast (this->object ())->resume (); +} + +int +ACE_Service_Object_Type::info (ACE_TCHAR **str, size_t len) const +{ + ACE_TRACE ("ACE_Service_Object_Type::info"); + return static_cast (this->object ())->info (str, len); +} + +ACE_ALLOC_HOOK_DEFINE(ACE_Module_Type) + +void +ACE_Module_Type::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Module_Type::dump"); +#endif /* ACE_HAS_DUMP */ +} + +ACE_Module_Type::ACE_Module_Type (void *m, + const ACE_TCHAR *m_name, + u_int f, + int stype) + : ACE_Service_Type_Impl (m, m_name, f, 0, stype) +{ + ACE_TRACE ("ACE_Module_Type::ACE_Module_Type"); +} + +ACE_Module_Type::~ACE_Module_Type (void) +{ + ACE_TRACE ("ACE_Module_Type::~ACE_Module_Type"); +} + +int +ACE_Module_Type::init (int argc, ACE_TCHAR *argv[]) const +{ + ACE_TRACE ("ACE_Module_Type::init"); + void *obj = this->object (); + MT_Module *mod = (MT_Module *) obj; + // + // Change the Module's name to what's in the svc.conf file. + // We must do this so the names match up so everything shuts + // down properly during the call to ACE_Stream_Type::fini + // which calls MT_Stream::remove([name]) for all the modules. + // If the calls to remove fail, we end up with a double delete + // during shutdown. Bugzilla #3847 + // + mod->name (this->name_); + MT_Task *reader = mod->reader (); + MT_Task *writer = mod->writer (); + + if (reader->init (argc, argv) == -1 + || writer->init (argc, argv) == -1) + return -1; + else + return 0; +} + +int +ACE_Module_Type::suspend (void) const +{ + ACE_TRACE ("ACE_Module_Type::suspend"); + void *obj = this->object (); + MT_Module *mod = (MT_Module *) obj; + MT_Task *reader = mod->reader (); + MT_Task *writer = mod->writer (); + + if (reader->suspend () == -1 + || writer->suspend () == -1) + return -1; + else + return 0; +} + +int +ACE_Module_Type::resume (void) const +{ + ACE_TRACE ("ACE_Module_Type::resume"); + void *obj = this->object (); + MT_Module *mod = (MT_Module *) obj; + MT_Task *reader = mod->reader (); + MT_Task *writer = mod->writer (); + + if (reader->resume () == -1 + || writer->resume () == -1) + return -1; + else + return 0; +} + +// Note, these operations are somewhat too familiar with the +// implementation of ACE_Module and ACE_Module::close... + +int +ACE_Module_Type::fini (void) const +{ + ACE_TRACE ("ACE_Module_Type::fini"); + void *obj = this->object (); + MT_Module *mod = (MT_Module *) obj; + MT_Task *reader = mod->reader (); + MT_Task *writer = mod->writer (); + + if (reader != 0) + reader->fini (); + + if (writer != 0) + writer->fini (); + + // Close the module and delete the memory. + mod->close (MT_Module::M_DELETE); + return ACE_Service_Type_Impl::fini (); +} + +int +ACE_Module_Type::info (ACE_TCHAR **str, size_t len) const +{ + ACE_TRACE ("ACE_Module_Type::info"); + ACE_TCHAR buf[BUFSIZ]; + + ACE_OS::sprintf (buf, + ACE_TEXT ("%s\t %s"), + this->name (), + ACE_TEXT ("# ACE_Module\n")); + + if (*str == 0 && (*str = ACE_OS::strdup (buf)) == 0) + return -1; + else + ACE_OS::strsncpy (*str, buf, len); + return static_cast (ACE_OS::strlen (buf)); +} + +void +ACE_Module_Type::link (ACE_Module_Type *n) +{ + ACE_TRACE ("ACE_Module_Type::link"); + this->link_ = n; +} + +ACE_Module_Type * +ACE_Module_Type::link (void) const +{ + ACE_TRACE ("ACE_Module_Type::link"); + return this->link_; +} + +ACE_ALLOC_HOOK_DEFINE(ACE_Stream_Type) + +void +ACE_Stream_Type::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Stream_Type::dump"); +#endif /* ACE_HAS_DUMP */ +} + +int +ACE_Stream_Type::init (int, ACE_TCHAR *[]) const +{ + ACE_TRACE ("ACE_Stream_Type::init"); + return 0; +} + +int +ACE_Stream_Type::suspend (void) const +{ + ACE_TRACE ("ACE_Stream_Type::suspend"); + + for (ACE_Module_Type *m = this->head_; + m != 0; + m = m->link ()) + m->suspend (); + + return 0; +} + +int +ACE_Stream_Type::resume (void) const +{ + ACE_TRACE ("ACE_Stream_Type::resume"); + + for (ACE_Module_Type *m = this->head_; + m != 0; + m = m->link ()) + m->resume (); + + return 0; +} + +ACE_Stream_Type::ACE_Stream_Type (void *s, + const ACE_TCHAR *s_name, + u_int f, + int stype) + : ACE_Service_Type_Impl (s, s_name, f, 0, stype), + head_ (0) +{ + ACE_TRACE ("ACE_Stream_Type::ACE_Stream_Type"); +} + +ACE_Stream_Type::~ACE_Stream_Type (void) +{ + ACE_TRACE ("ACE_Stream_Type::~ACE_Stream_Type"); +} + +int +ACE_Stream_Type::info (ACE_TCHAR **str, size_t len) const +{ + ACE_TRACE ("ACE_Stream_Type::info"); + ACE_TCHAR buf[BUFSIZ]; + + ACE_OS::sprintf (buf, + ACE_TEXT ("%s\t %s"), + this->name (), + ACE_TEXT ("# STREAM\n")); + + if (*str == 0 && (*str = ACE_OS::strdup (buf)) == 0) + return -1; + else + ACE_OS::strsncpy (*str, buf, len); + return static_cast (ACE_OS::strlen (buf)); +} + +int +ACE_Stream_Type::fini (void) const +{ + ACE_TRACE ("ACE_Stream_Type::fini"); + void *obj = this->object (); + MT_Stream *str = (MT_Stream *) obj; + + for (ACE_Module_Type *m = this->head_; m != 0;) + { + ACE_Module_Type *t = m->link (); + + // Final arg is an indication to *not* delete the Module. + str->remove (m->name (), + MT_Module::M_DELETE_NONE); + m = t; + } + str->close (); + + return ACE_Service_Type_Impl::fini (); +} + +// Locate and remove from the ACE_Stream. + +int +ACE_Stream_Type::remove (ACE_Module_Type *mod) +{ + ACE_TRACE ("ACE_Stream_Type::remove"); + + ACE_Module_Type *prev = 0; + void *obj = this->object (); + MT_Stream *str = (MT_Stream *) obj; + int result = 0; + + for (ACE_Module_Type *m = this->head_; m != 0; ) + { + // We need to do this first so we don't bomb out if we delete m! + ACE_Module_Type *link = m->link (); + + if (m == mod) + { + if (prev == 0) + this->head_ = link; + else + prev->link (link); + + // Final arg is an indication to *not* delete the Module. + if (str->remove (m->name (), + MT_Module::M_DELETE_NONE) == -1) + result = -1; + + // Do not call m->fini (); as this will result in a double delete + // of the ACE_Module_type when ACE_Service_Repository::fini is called + } + else + prev = m; + + m = link; + } + + return result; +} + +int +ACE_Stream_Type::push (ACE_Module_Type *new_module) +{ + ACE_TRACE ("ACE_Stream_Type::push"); + void *obj = this->object (); + MT_Stream *str = (MT_Stream *) obj; + + new_module->link (this->head_); + this->head_ = new_module; + obj = new_module->object (); + return str->push ((MT_Module *) obj); +} + +ACE_Module_Type * +ACE_Stream_Type::find (const ACE_TCHAR *module_name) const +{ + ACE_TRACE ("ACE_Stream_Type::find"); + + for (ACE_Module_Type *m = this->head_; + m != 0; + m = m->link ()) + if (ACE_OS::strcmp (m->name (), module_name) == 0) + return m; + + return 0; +} + +// @@@ Eliminated ommented out explicit template instantiation code + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Service_Types.h b/dep/acelite/ace/Service_Types.h new file mode 100644 index 00000000000..70a7ac4f566 --- /dev/null +++ b/dep/acelite/ace/Service_Types.h @@ -0,0 +1,221 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file Service_Types.h + * + * $Id: Service_Types.h 89925 2010-04-19 12:49:11Z cbeaulac $ + * + * @author Douglas C. Schmidt + */ +//========================================================================== + +#ifndef ACE_SERVICE_TYPE_H +#define ACE_SERVICE_TYPE_H + +#include /**/ "ace/pre.h" + +#include "ace/Service_Object.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Service_Type_Impl + * + * @brief The abstract base class of the hierarchy that defines the + * contents of the ACE_Service_Repository. The subclasses of + * this class allow the configuration of ACE_Service_Objects, + * ACE_Modules, and ACE_Streams. + * + * This class provides the root of the implementation hierarchy + * of the "Bridge" pattern. It maintains a pointer to the + * appropriate type of service implementation, i.e., + * ACE_Service_Object, ACE_Module, or ACE_Stream. + */ +class ACE_Export ACE_Service_Type_Impl +{ +public: + // = Initialization and termination methods. + ACE_Service_Type_Impl (void *object, + const ACE_TCHAR *s_name, + u_int flags = 0, + ACE_Service_Object_Exterminator gobbler = 0, + int stype = ACE_Service_Type::INVALID_TYPE); + virtual ~ACE_Service_Type_Impl (void); + + // = Pure virtual interface (must be defined by the subclass). + virtual int suspend (void) const = 0; + virtual int resume (void) const = 0; + virtual int init (int argc, ACE_TCHAR *argv[]) const = 0; + virtual int fini (void) const; + virtual int info (ACE_TCHAR **str, size_t len) const = 0; + + /// The pointer to the service. + void *object (void) const; + + /// Get the name of the service. + const ACE_TCHAR *name (void) const; + + /// Set the name of the service. + void name (const ACE_TCHAR *); + + /// Dump the state of an object. + void dump (void) const; + + /// get the service_type of this service + int service_type (void) const; + + /// set the service_type of this service + void service_type (int stype); + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + /// Name of the service. + const ACE_TCHAR *name_; + + /// Pointer to object that implements the service. This actually + /// points to an ACE_Service_Object, ACE_Module, or ACE_Stream. + void *obj_; + + /// Destroy function to deallocate obj_. + ACE_Service_Object_Exterminator gobbler_; + + /// Flags that control serivce behavior (particularly deletion). + u_int flags_; + + /// type of this service + /// Used to properly manage the lifecycle of ACE_Modules and ACE_Streams + /// during shutdown + int service_type_; +}; + +/** + * @class ACE_Service_Object_Type + * + * @brief Define the methods for handling the configuration of + * ACE_Service_Objects. + */ +class ACE_Export ACE_Service_Object_Type : public ACE_Service_Type_Impl +{ +public: + // = Initialization method. + ACE_Service_Object_Type (void *so, + const ACE_TCHAR *name, + u_int flags = 0, + ACE_Service_Object_Exterminator gobbler = 0, + int stype = ACE_Service_Type::SERVICE_OBJECT); + + ~ACE_Service_Object_Type (void); + + // = Implement the hooks for . + virtual int suspend (void) const; + virtual int resume (void) const; + virtual int init (int argc, ACE_TCHAR *argv[]) const; + virtual int fini (void) const; + virtual int info (ACE_TCHAR **str, size_t len) const; + +private: + /// Holds the initialization status (result of object->init()) + mutable int initialized_; +}; + +/** + * @class ACE_Module_Type + * + * @brief Define the methods for handling the configuration of + * ACE_Modules. + */ +class ACE_Export ACE_Module_Type : public ACE_Service_Type_Impl +{ +public: + // = Initialization method. + ACE_Module_Type (void *m, // Really an ACE_Module *. + const ACE_TCHAR *identifier, + u_int flags = 0, + int stype = ACE_Service_Type::MODULE); + + ~ACE_Module_Type (void); + + // = Implement the hooks for . + virtual int suspend (void) const; + virtual int resume (void) const; + virtual int init (int argc, ACE_TCHAR *argv[]) const; + virtual int fini (void) const; + virtual int info (ACE_TCHAR **str, size_t len) const; + + /// Get the link pointer. + ACE_Module_Type *link (void) const; + + /// Set the link pointer. + void link (ACE_Module_Type *); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + /// Pointer to the next ACE_Module_Type in an ACE_Stream_Type. + ACE_Module_Type *link_; +}; + +/** + * @class ACE_Stream_Type + * + * @brief Define the methods for handling the configuration of + * ACE_Streams. + */ +class ACE_Export ACE_Stream_Type : public ACE_Service_Type_Impl +{ +public: + // = Initialization method. + ACE_Stream_Type (void *s, // Really an ACE_Stream *. + const ACE_TCHAR *identifier, + u_int flags = 0, + int stype = ACE_Service_Type::STREAM); + + ~ACE_Stream_Type (void); + + // = Implement the hooks for . + virtual int suspend (void) const; + virtual int resume (void) const; + virtual int init (int argc, ACE_TCHAR *argv[]) const; + virtual int fini (void) const; + virtual int info (ACE_TCHAR **str, size_t len) const; + + /// Add a new ACE_Module to the top of the ACE_Stream. + int push (ACE_Module_Type *new_module); + + /// Search for @a module and remove it from the ACE_Stream. + int remove (ACE_Module_Type *module); + + /// Locate the ACE_Module with @a mod_name. + ACE_Module_Type *find (const ACE_TCHAR *module_name) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + /// Pointer to the head of the ACE_Module list. + ACE_Module_Type *head_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Service_Types.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" + +#endif /* _SERVICE_TYPE_H */ diff --git a/dep/acelite/ace/Service_Types.inl b/dep/acelite/ace/Service_Types.inl new file mode 100644 index 00000000000..4586ac6122a --- /dev/null +++ b/dep/acelite/ace/Service_Types.inl @@ -0,0 +1,43 @@ +// -*- C++ -*- +// +// $Id: Service_Types.inl 89925 2010-04-19 12:49:11Z cbeaulac $ + +#include "ace/ACE.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE void * +ACE_Service_Type_Impl::object (void) const +{ + ACE_TRACE ("ACE_Service_Type_Impl::object"); + return this->obj_; +} + +ACE_INLINE const ACE_TCHAR * +ACE_Service_Type_Impl::name (void) const +{ + ACE_TRACE ("ACE_Service_Type_Impl::name"); + return this->name_; +} + +ACE_INLINE void +ACE_Service_Type_Impl::name (const ACE_TCHAR *n) +{ + ACE_TRACE ("ACE_Service_Type_Impl::name"); + + ACE::strdelete (const_cast (this->name_)); + this->name_ = ACE::strnew (n); +} + +ACE_INLINE int +ACE_Service_Type_Impl::service_type (void) const +{ + return service_type_; +} + +ACE_INLINE void +ACE_Service_Type_Impl::service_type (int stype) +{ + service_type_ = stype; +} +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Shared_Memory.cpp b/dep/acelite/ace/Shared_Memory.cpp new file mode 100644 index 00000000000..ccb1f26c401 --- /dev/null +++ b/dep/acelite/ace/Shared_Memory.cpp @@ -0,0 +1,13 @@ +// $Id: Shared_Memory.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Shared_Memory.h" + +ACE_RCSID(ace, Shared_Memory, "$Id: Shared_Memory.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_Shared_Memory::~ACE_Shared_Memory (void) +{ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Shared_Memory.h b/dep/acelite/ace/Shared_Memory.h new file mode 100644 index 00000000000..6dbd17ff492 --- /dev/null +++ b/dep/acelite/ace/Shared_Memory.h @@ -0,0 +1,58 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file Shared_Memory.h + * + * $Id: Shared_Memory.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Doug Schmidt + */ +//========================================================================== + + +#ifndef ACE_SHARED_MEMORY_H +#define ACE_SHARED_MEMORY_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#include "ace/os_include/os_stddef.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Shared_Memory + * + * @brief This base class adapts both System V shared memory and "BSD" + * mmap to a common API. + * + * This is a very simple-minded wrapper, i.e., it really is only + * useful for allocating large contiguous chunks of shared + * memory. For a much more sophisticated version, please check + * out the class. + */ +class ACE_Export ACE_Shared_Memory +{ +public: + virtual ~ACE_Shared_Memory (void); + + // = Note that all the following methods are pure virtual. + virtual int close (void) = 0; + virtual int remove (void) = 0; + virtual void *malloc (size_t = 0) = 0; + virtual int free (void *p) = 0; + virtual size_t get_segment_size (void) const = 0; + virtual ACE_HANDLE get_id (void) const = 0; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" + +#endif /* ACE_SHARED_MEMORY_H */ diff --git a/dep/acelite/ace/Shared_Memory_MM.cpp b/dep/acelite/ace/Shared_Memory_MM.cpp new file mode 100644 index 00000000000..d6d1ed90cce --- /dev/null +++ b/dep/acelite/ace/Shared_Memory_MM.cpp @@ -0,0 +1,111 @@ +// $Id: Shared_Memory_MM.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Shared_Memory_MM.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Shared_Memory_MM.inl" +#endif /* __ACE_INLINE__ */ + + +ACE_RCSID (ace, + Shared_Memory_MM, + "$Id: Shared_Memory_MM.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Shared_Memory_MM) + +void +ACE_Shared_Memory_MM::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Shared_Memory_MM::dump"); +#endif /* ACE_HAS_DUMP */ +} + +// Creates a shared memory segment of SIZE bytes. + +ACE_Shared_Memory_MM::ACE_Shared_Memory_MM (ACE_HANDLE handle, + size_t length, + int prot, + int share, + char *addr, + ACE_OFF_T pos) + : shared_memory_ (handle, length, prot, share, addr, pos) +{ + ACE_TRACE ("ACE_Shared_Memory_MM::ACE_Shared_Memory_MM"); +} + +ACE_Shared_Memory_MM::ACE_Shared_Memory_MM (const ACE_TCHAR *file_name, + size_t len, + int flags, + int mode, + int prot, + int share, + char *addr, + ACE_OFF_T pos) + : shared_memory_ (file_name, len, flags, mode, + prot, share, addr, pos) +{ + ACE_TRACE ("ACE_Shared_Memory_MM::ACE_Shared_Memory_MM"); +} + +// The "do-nothing" constructor. + +ACE_Shared_Memory_MM::ACE_Shared_Memory_MM (void) +{ + ACE_TRACE ("ACE_Shared_Memory_MM::ACE_Shared_Memory_MM"); +} + +// The overall size of the segment. + +size_t +ACE_Shared_Memory_MM::get_segment_size (void) const +{ + ACE_TRACE ("ACE_Shared_Memory_MM::get_segment_size"); + // This cast is legit since the original length in open() is an int. + return this->shared_memory_.size (); +} + +// Unmaps the shared memory segment. + +int +ACE_Shared_Memory_MM::remove (void) +{ + ACE_TRACE ("ACE_Shared_Memory_MM::remove"); + return shared_memory_.remove (); +} + +// Closes (unmaps) the shared memory segment. + +int +ACE_Shared_Memory_MM::close (void) +{ + ACE_TRACE ("ACE_Shared_Memory_MM::close"); + return shared_memory_.unmap (); +} + +void * +ACE_Shared_Memory_MM::malloc (size_t) +{ + ACE_TRACE ("ACE_Shared_Memory_MM::malloc"); + void *addr = 0; + + return this->shared_memory_ (addr) == -1 ? 0 : addr; +} + +ACE_HANDLE +ACE_Shared_Memory_MM::get_id (void) const +{ + ACE_TRACE ("ACE_Shared_Memory_MM::get_id"); + return this->shared_memory_.handle (); +} + +int +ACE_Shared_Memory_MM::free (void *p) +{ + ACE_TRACE ("ACE_Shared_Memory_MM::free"); + return p != 0; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Shared_Memory_MM.h b/dep/acelite/ace/Shared_Memory_MM.h new file mode 100644 index 00000000000..e02b21249ac --- /dev/null +++ b/dep/acelite/ace/Shared_Memory_MM.h @@ -0,0 +1,120 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file Shared_Memory_MM.h + * + * $Id: Shared_Memory_MM.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + + +#ifndef ACE_SHARED_MALLOC_MM_H +#define ACE_SHARED_MALLOC_MM_H +#include /**/ "ace/pre.h" + +#include "ace/Shared_Memory.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Mem_Map.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Shared_Memory_MM + * + * @brief Shared memory wrapper based on MMAP. + * + * This class provides a very simple-minded shared memory manager. We + * strongly recommend that you do NOT use this class. Instead, please + * use @c ACE_Malloc, which has much more powerful capabilities. + */ +class ACE_Export ACE_Shared_Memory_MM : public ACE_Shared_Memory +{ +public: + // = Initialization and termination methods. + /// Default constructor. + ACE_Shared_Memory_MM (void); + + /// Constructor. + ACE_Shared_Memory_MM (ACE_HANDLE handle, + size_t length = static_cast (-1), + int prot = PROT_RDWR, + int share = ACE_MAP_PRIVATE, + char *addr = 0, + ACE_OFF_T pos = 0); + + /// Constructor. + ACE_Shared_Memory_MM (const ACE_TCHAR *file_name, + size_t length = static_cast (-1), + int flags = O_RDWR | O_CREAT, + int mode = ACE_DEFAULT_FILE_PERMS, + int prot = PROT_RDWR, + int share = ACE_MAP_SHARED, + char *addr = 0, ACE_OFF_T pos = 0); + + /// Open method. + int open (ACE_HANDLE handle, + size_t length = static_cast (-1), + int prot = PROT_RDWR, + int share = ACE_MAP_PRIVATE, + char *addr = 0, + ACE_OFF_T pos = 0); + + /// Open method. + int open (const ACE_TCHAR *file_name, + size_t length = static_cast (-1), + int flags = O_RDWR | O_CREAT, + int mode = ACE_DEFAULT_FILE_PERMS, + int prot = PROT_RDWR, + int share = ACE_MAP_SHARED, + char *addr = 0, + ACE_OFF_T pos = 0); + + /// Return the name of file that is mapped (if any). + const ACE_TCHAR *filename (void) const; + + /// Close down the shared memory segment. + virtual int close (void); + + /// Remove the shared memory segment and the underlying file. + virtual int remove (void); + + // = Allocation and deallocation methods. + /// Create a new chuck of memory containing @a size bytes. + virtual void *malloc (size_t size = 0); + + /// Free a chuck of memory allocated by + /// . + virtual int free (void *p); + + /// Return the size of the shared memory segment. + virtual size_t get_segment_size (void) const; + + /// Return the ID of the shared memory segment (i.e., an ACE_HANDLE). + virtual ACE_HANDLE get_id (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + /// This version is implemented with memory-mapped files. + ACE_Mem_Map shared_memory_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Shared_Memory_MM.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_SHARED_MALLOC_MM_H */ diff --git a/dep/acelite/ace/Shared_Memory_MM.inl b/dep/acelite/ace/Shared_Memory_MM.inl new file mode 100644 index 00000000000..6e1f4b76616 --- /dev/null +++ b/dep/acelite/ace/Shared_Memory_MM.inl @@ -0,0 +1,42 @@ +// -*- C++ -*- +// +// $Id: Shared_Memory_MM.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Return the name of file that is mapped (if any). + +ACE_INLINE const ACE_TCHAR * +ACE_Shared_Memory_MM::filename (void) const +{ + return this->shared_memory_.filename (); +} + +ACE_INLINE int +ACE_Shared_Memory_MM::open (ACE_HANDLE handle, + size_t length, + int prot, + int share, + char *addr, + ACE_OFF_T pos) +{ + ACE_TRACE ("ACE_Shared_Memory_MM::open"); + return shared_memory_.map (handle, length, prot, share, addr, pos); +} + +ACE_INLINE int +ACE_Shared_Memory_MM::open (const ACE_TCHAR *file_name, + size_t len, + int flags, + int mode, + int prot, + int share, + char *addr, + ACE_OFF_T pos) +{ + ACE_TRACE ("ACE_Shared_Memory_MM::open"); + return shared_memory_.map (file_name, len, flags, mode, + prot, share, addr, pos); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Shared_Memory_Pool.cpp b/dep/acelite/ace/Shared_Memory_Pool.cpp new file mode 100644 index 00000000000..0ef93925e89 --- /dev/null +++ b/dep/acelite/ace/Shared_Memory_Pool.cpp @@ -0,0 +1,461 @@ +// $Id: Shared_Memory_Pool.cpp 84455 2009-02-13 13:31:02Z johnnyw $ + +// Shared_Memory_Pool.cpp +#include "ace/Shared_Memory_Pool.h" +#include "ace/OS_NS_sys_shm.h" +#include "ace/Log_Msg.h" + +ACE_RCSID(ace, Shared_Memory_Pool, "$Id: Shared_Memory_Pool.cpp 84455 2009-02-13 13:31:02Z johnnyw $") + +#if !defined (ACE_LACKS_SYSV_SHMEM) + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Shared_Memory_Pool) + +ACE_Shared_Memory_Pool_Options::ACE_Shared_Memory_Pool_Options ( + const char *base_addr, + size_t max_segments, + size_t file_perms, + ACE_OFF_T minimum_bytes, + size_t segment_size) + : base_addr_ (base_addr), + max_segments_ (max_segments), + minimum_bytes_ (minimum_bytes), + file_perms_ (file_perms), + segment_size_ (segment_size) +{ + ACE_TRACE ("ACE_Shared_Memory_Pool_Options::ACE_Shared_Memory_Pool_Options"); +} + +void +ACE_Shared_Memory_Pool::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Shared_Memory_Pool::dump"); +#endif /* ACE_HAS_DUMP */ +} + +int +ACE_Shared_Memory_Pool::in_use (ACE_OFF_T &offset, + size_t &counter) +{ + offset = 0; + SHM_TABLE *st = reinterpret_cast (this->base_addr_); + shmid_ds buf; + + for (counter = 0; + counter < this->max_segments_ && st[counter].used_ == 1; + counter++) + { + if (ACE_OS::shmctl (st[counter].shmid_, IPC_STAT, &buf) == -1) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("(%P|%t) %p\n"), + ACE_TEXT ("shmctl")), + -1); + offset += buf.shm_segsz; + // ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) segment size = %d, offset = %d\n"), buf.shm_segsz, offset)); + } + + return 0; +} + +int +ACE_Shared_Memory_Pool::find_seg (const void* const searchPtr, + ACE_OFF_T &offset, + size_t &counter) +{ + offset = 0; + SHM_TABLE *st = reinterpret_cast (this->base_addr_); + shmid_ds buf; + + for (counter = 0; + counter < this->max_segments_ + && st[counter].used_ == 1; + counter++) + { + if (ACE_OS::shmctl (st[counter].shmid_, IPC_STAT, &buf) == -1) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("(%P|%t) %p\n"), + ACE_TEXT ("shmctl")), + -1); + offset += buf.shm_segsz; + + // If segment 'counter' starts at a location greater than the + // place we are searching for. We then decrement the offset to + // the start of counter-1. (flabar@vais.net) + if (((ptrdiff_t) offset + (ptrdiff_t) (this->base_addr_)) > (ptrdiff_t) searchPtr) + { + --counter; + offset -= buf.shm_segsz; + return 0; + } + // ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) segment size = %d, offset = %d\n"), buf.shm_segsz, offset)); + } + + return 0; +} + +int +ACE_Shared_Memory_Pool::commit_backing_store_name (size_t rounded_bytes, + ACE_OFF_T &offset) +{ + ACE_TRACE ("ACE_Shared_Memory_Pool::commit_backing_store_name"); + + size_t counter; + SHM_TABLE *st = reinterpret_cast (this->base_addr_); + + if (this->in_use (offset, counter) == -1) + return -1; + + if (counter == this->max_segments_) + ACE_ERROR_RETURN ((LM_ERROR, + "exceeded max number of segments = %d, base = %u, offset = %u\n", + counter, + this->base_addr_, + offset), + -1); + else + { + int shmid = ACE_OS::shmget (st[counter].key_, + rounded_bytes, + this->file_perms_ | IPC_CREAT | IPC_EXCL); + if (shmid == -1) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("(%P|%t) %p\n"), + ACE_TEXT ("shmget")), + -1); + st[counter].shmid_ = shmid; + st[counter].used_ = 1; + + void *address = (void *) (((char *) this->base_addr_) + offset); + void *shmem = ACE_OS::shmat (st[counter].shmid_, + (char *) address, + 0); + + if (shmem != address) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT("(%P|%t) %p, shmem = %u, address = %u\n"), + ACE_TEXT("shmat"), + shmem, + address), + -1); + } + return 0; +} + +// Handle SIGSEGV and SIGBUS signals to remap shared memory properly. + +int +ACE_Shared_Memory_Pool::handle_signal (int , siginfo_t *siginfo, ucontext_t *) +{ + ACE_TRACE ("ACE_Shared_Memory_Pool::handle_signal"); + // ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("signal %S occurred\n"), signum)); + + // While FreeBSD 5.X has a siginfo_t struct with a si_addr field, + // it does not define SEGV_MAPERR. +#if defined (ACE_HAS_SIGINFO_T) && !defined (ACE_LACKS_SI_ADDR) && \ + (defined (SEGV_MAPERR) || defined (SEGV_MEMERR)) + ACE_OFF_T offset; + // Make sure that the pointer causing the problem is within the + // range of the backing store. + + if (siginfo != 0) + { + // ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) si_signo = %d, si_code = %d, addr = %u\n"), siginfo->si_signo, siginfo->si_code, siginfo->si_addr)); + size_t counter; + if (this->in_use (offset, counter) == -1) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("(%P|%t) %p\n"), + ACE_TEXT ("in_use"))); +#if !defined(_UNICOS) + else if (!(siginfo->si_code == SEGV_MAPERR + && siginfo->si_addr < (((char *) this->base_addr_) + offset) + && siginfo->si_addr >= ((char *) this->base_addr_))) + ACE_ERROR_RETURN ((LM_ERROR, + "(%P|%t) address %u out of range\n", + siginfo->si_addr), + -1); +#else /* ! _UNICOS */ + else if (!(siginfo->si_code == SEGV_MEMERR + && siginfo->si_addr < (((unsigned long) this->base_addr_) + offset) + && siginfo->si_addr >= ((unsigned long) this->base_addr_))) + ACE_ERROR_RETURN ((LM_ERROR, + "(%P|%t) address %u out of range\n", + siginfo->si_addr), + -1); +#endif /* ! _UNICOS */ + } + + // The above if case will check to see that the address is in the + // proper range. Therefore there is a segment out there that the + // pointer wants to point into. Find the segment that someone else + // has used and attach to it (flabar@vais.net) + + size_t counter; // ret value to get shmid from the st table. + +#if !defined(_UNICOS) + if (this->find_seg (siginfo->si_addr, offset, counter) == -1) +#else /* ! _UNICOS */ + if (this->find_seg ((const void *)siginfo->si_addr, offset, counter) == -1) +#endif /* ! _UNICOS */ + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("(%P|%t) %p\n"), + ACE_TEXT ("in_use")), + -1); + + void *address = (void *) (((char *) this->base_addr_) + offset); + SHM_TABLE *st = reinterpret_cast (this->base_addr_); + + void *shmem = ACE_OS::shmat (st[counter].shmid_, (char *) address, 0); + + if (shmem != address) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT("(%P|%t) %p, shmem = %u, address = %u\n"), + ACE_TEXT("shmat"), + shmem, + address), + -1); + + // NOTE: this won't work if we dont have SIGINFO_T or SI_ADDR +#else + ACE_UNUSED_ARG (siginfo); +#endif /* ACE_HAS_SIGINFO_T && !defined (ACE_LACKS_SI_ADDR) */ + + return 0; +} + +ACE_Shared_Memory_Pool::ACE_Shared_Memory_Pool ( + const ACE_TCHAR *backing_store_name, + const OPTIONS *options) + : base_addr_ (0), + file_perms_ (ACE_DEFAULT_FILE_PERMS), + max_segments_ (ACE_DEFAULT_MAX_SEGMENTS), + minimum_bytes_ (0), + segment_size_ (ACE_DEFAULT_SEGMENT_SIZE) +{ + ACE_TRACE ("ACE_Shared_Memory_Pool::ACE_Shared_Memory_Pool"); + + // Only change the defaults if != 0. + if (options) + { + this->base_addr_ = + reinterpret_cast (const_cast (options->base_addr_)); + this->max_segments_ = options->max_segments_; + this->file_perms_ = options->file_perms_; + this->minimum_bytes_ = options->minimum_bytes_; + this->segment_size_ = options->segment_size_; + } + + if (backing_store_name) + { + // Convert the string into a number that is used as the segment + // key. + + int segment_key; + int result = ::sscanf (ACE_TEXT_ALWAYS_CHAR (backing_store_name), + "%d", + &segment_key); + + if (result == 0 || result == EOF) + // The conversion to a number failed so hash with crc32 + // ACE::crc32 is also used in . + this->base_shm_key_ = + (key_t) ACE::crc32 (ACE_TEXT_ALWAYS_CHAR (backing_store_name)); + else + this->base_shm_key_ = segment_key; + + if (this->base_shm_key_ == IPC_PRIVATE) + // Make sure that the segment can be shared between unrelated + // processes. + this->base_shm_key_ = ACE_DEFAULT_SHM_KEY; + } + else + this->base_shm_key_ = ACE_DEFAULT_SHM_KEY; + + if (this->signal_handler_.register_handler (SIGSEGV, this) == -1) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_Sig_Handler::register_handler"))); +} + +ACE_Shared_Memory_Pool::~ACE_Shared_Memory_Pool (void) +{ +} + +// Ask system for more shared memory. + +void * +ACE_Shared_Memory_Pool::acquire (size_t nbytes, + size_t &rounded_bytes) +{ + ACE_TRACE ("ACE_Shared_Memory_Pool::acquire"); + + rounded_bytes = this->round_up (nbytes); + + // ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) acquiring more chunks, nbytes = %d, rounded_bytes = %d\n"), nbytes, rounded_bytes)); + + ACE_OFF_T offset; + + if (this->commit_backing_store_name (rounded_bytes, offset) == -1) + return 0; + + // ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) acquired more chunks, nbytes = %d, rounded_bytes = %d\n"), nbytes, rounded_bytes)); + return ((char *) this->base_addr_) + offset; +} + +// Ask system for initial chunk of shared memory. + +void * +ACE_Shared_Memory_Pool::init_acquire (size_t nbytes, + size_t &rounded_bytes, + int &first_time) +{ + ACE_TRACE ("ACE_Shared_Memory_Pool::init_acquire"); + + ACE_OFF_T shm_table_offset = ACE::round_to_pagesize (sizeof (SHM_TABLE)); + rounded_bytes = this->round_up (nbytes > (size_t) this->minimum_bytes_ + ? nbytes + : (size_t) this->minimum_bytes_); + + // Acquire the semaphore to serialize initialization and prevent + // race conditions. + + int shmid = ACE_OS::shmget (this->base_shm_key_, + rounded_bytes + shm_table_offset, + this->file_perms_ | IPC_CREAT | IPC_EXCL); + if (shmid == -1) + { + if (errno != EEXIST) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("(%P|%t) %p\n"), + ACE_TEXT ("shmget")), + 0); + first_time = 0; + + shmid = ACE_OS::shmget (this->base_shm_key_, 0, 0); + + if (shmid == -1) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("(%P|%t) %p\n"), + ACE_TEXT ("shmget")), + 0); + + // This implementation doesn't care if we don't get the key we + // want... + this->base_addr_ = + ACE_OS::shmat (shmid, + reinterpret_cast (this->base_addr_), + 0); + if (this->base_addr_ == reinterpret_cast (-1)) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT("(%P|%t) %p, base_addr = %u\n"), + ACE_TEXT("shmat"), + this->base_addr_), + 0); + } + else + { + first_time = 1; + + // This implementation doesn't care if we don't get the key we + // want... + this->base_addr_ = + ACE_OS::shmat (shmid, + reinterpret_cast (this->base_addr_), + 0); + if (this->base_addr_ == reinterpret_cast (-1)) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT("(%P|%t) %p, base_addr = %u\n"), + ACE_TEXT("shmat"), + this->base_addr_), 0); + + SHM_TABLE *st = reinterpret_cast (this->base_addr_); + st[0].key_ = this->base_shm_key_; + st[0].shmid_ = shmid; + + st[0].used_ = 1; + + for (size_t counter = 1; // Skip over the first entry... + counter < this->max_segments_; + counter++) + { + st[counter].key_ = this->base_shm_key_ + counter; + st[counter].shmid_ = 0; + st[counter].used_ = 0; + } + } + + return (void *) (((char *) this->base_addr_) + shm_table_offset); +} + +// Instruct the memory pool to release all of its resources. + +int +ACE_Shared_Memory_Pool::release (int) +{ + ACE_TRACE ("ACE_Shared_Memory_Pool::release"); + + int result = 0; + SHM_TABLE *st = reinterpret_cast (this->base_addr_); + + for (size_t counter = 0; + counter < this->max_segments_ && st[counter].used_ == 1; + counter++) + if (ACE_OS::shmctl (st[counter].shmid_, IPC_RMID, 0) == -1) + result = -1; + + return result; +} + +int +ACE_Shared_Memory_Pool::sync (ssize_t, int) +{ + ACE_TRACE ("ACE_Shared_Memory_Pool::sync"); + return 0; +} + +int +ACE_Shared_Memory_Pool::sync (void *, size_t, int) +{ + ACE_TRACE ("ACE_Shared_Memory_Pool::sync"); + return 0; +} + +int +ACE_Shared_Memory_Pool::protect (ssize_t, int) +{ + ACE_TRACE ("ACE_Shared_Memory_Pool::protect"); + return 0; +} + +int +ACE_Shared_Memory_Pool::protect (void *, size_t, int) +{ + ACE_TRACE ("ACE_Shared_Memory_Pool::protect"); + return 0; +} + +void * +ACE_Shared_Memory_Pool::base_addr (void) const +{ + ACE_TRACE ("ACE_Shared_Memory_Pool::base_addr"); + return this->base_addr_; +} + +// Implement the algorithm for rounding up the request to an +// appropriate chunksize. + +size_t +ACE_Shared_Memory_Pool::round_up (size_t nbytes) +{ + ACE_TRACE ("ACE_Shared_Memory_Pool::round_up"); + if (nbytes < this->segment_size_) + nbytes = this->segment_size_; + + return ACE::round_to_pagesize (nbytes); +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* !ACE_LACKS_SYSV_SHMEM */ diff --git a/dep/acelite/ace/Shared_Memory_Pool.h b/dep/acelite/ace/Shared_Memory_Pool.h new file mode 100644 index 00000000000..79cb970e712 --- /dev/null +++ b/dep/acelite/ace/Shared_Memory_Pool.h @@ -0,0 +1,210 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Shared_Memory_Pool.h + * + * $Id: Shared_Memory_Pool.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Dougls C. Schmidt + * @author Prashant Jain + */ +//============================================================================= + +#ifndef ACE_SHARED_MEMORY_POOL_H +#define ACE_SHARED_MEMORY_POOL_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_SYSV_SHMEM) + +#include "ace/ACE.h" +#include "ace/Event_Handler.h" +#include "ace/Sig_Handler.h" +#include "ace/os_include/sys/os_mman.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Shared_Memory_Pool_Options + * + * @brief Helper class for Shared Memory Pool constructor options. + * + * This should be a nested class, but that breaks too many + * compilers. + */ +class ACE_Export ACE_Shared_Memory_Pool_Options +{ +public: + /// Initialization method. + ACE_Shared_Memory_Pool_Options ( + const char *base_addr = ACE_DEFAULT_BASE_ADDR, + size_t max_segments = ACE_DEFAULT_MAX_SEGMENTS, + size_t file_perms = ACE_DEFAULT_FILE_PERMS, + ACE_OFF_T minimum_bytes = 0, + size_t segment_size = ACE_DEFAULT_SEGMENT_SIZE); + + /// Base address of the memory-mapped backing store. + const char *base_addr_; + + /// Number of shared memory segments to allocate. + size_t max_segments_; + + /// What the minimum bytes of the initial segment should be. + ACE_OFF_T minimum_bytes_; + + /// File permissions to use when creating/opening a segment. + size_t file_perms_; + + /// Shared memory segment size. + size_t segment_size_; +}; + +/** + * @class ACE_Shared_Memory_Pool + * + * @brief Make a memory pool that is based on System V shared memory + * (shmget(2) etc.). This implementation allows memory to be + * shared between processes. If your platform doesn't support + * System V shared memory (e.g., Win32 and many RTOS platforms + * do not) then you should use ACE_MMAP_Memory_Pool instead of this + * class. In fact, you should probably use ACE_MMAP_Memory_Pool on + * platforms that *do* support System V shared memory since it + * provides more powerful features, such as persistent backing store + * and greatly scalability. + */ +class ACE_Export ACE_Shared_Memory_Pool : public ACE_Event_Handler +{ +public: + typedef ACE_Shared_Memory_Pool_Options OPTIONS; + + /// Initialize the pool. + ACE_Shared_Memory_Pool (const ACE_TCHAR *backing_store_name = 0, + const OPTIONS *options = 0); + + virtual ~ACE_Shared_Memory_Pool (void); + + /// Ask system for initial chunk of local memory. + virtual void *init_acquire (size_t nbytes, + size_t &rounded_bytes, + int &first_time); + + /** + * Acquire at least @a nbytes from the memory pool. @a rounded_byes is + * the actual number of bytes allocated. Also acquires an internal + * semaphore that ensures proper serialization of Memory_Pool + * initialization across processes. + */ + virtual void *acquire (size_t nbytes, + size_t &rounded_bytes); + + /// Instruct the memory pool to release all of its resources. + virtual int release (int destroy = 1); + + /// Sync the memory region to the backing store starting at + /// @c this->base_addr_. + virtual int sync (ssize_t len = -1, int flags = MS_SYNC); + + /// Sync the memory region to the backing store starting at @a addr. + virtual int sync (void *addr, size_t len, int flags = MS_SYNC); + + /** + * Change the protection of the pages of the mapped region to @a prot + * starting at @c this->base_addr_ up to @a len bytes. If @a len == -1 + * then change protection of all pages in the mapped region. + */ + virtual int protect (ssize_t len = -1, int prot = PROT_RDWR); + + /// Change the protection of the pages of the mapped region to @a prot + /// starting at @a addr up to @a len bytes. + virtual int protect (void *addr, size_t len, int prot = PROT_RDWR); + + /// Return the base address of this memory pool, 0 if base_addr + /// never changes. + virtual void *base_addr (void) const; + + /// Dump the state of an object. + virtual void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + /// Implement the algorithm for rounding up the request to an + /// appropriate chunksize. + virtual size_t round_up (size_t nbytes); + + /** + * Commits a new shared memory segment if necessary after an + * or a signal. @a offset is set to the new offset into + * the backing store. + */ + virtual int commit_backing_store_name (size_t rounded_bytes, + ACE_OFF_T &offset); + + /// Keeps track of all the segments being used. + struct SHM_TABLE + { + /// Shared memory segment key. + key_t key_; + + /// Shared memory segment internal id. + int shmid_; + + /// Is the segment currently used.; + int used_; + }; + + /** + * Base address of the shared memory segment. If this has the value + * of 0 then the OS is free to select any address, otherwise this + * value is what the OS must try to use to map the shared memory + * segment. + */ + void *base_addr_; + + /// File permissions to use when creating/opening a segment. + size_t file_perms_; + + /// Number of shared memory segments in the table. + size_t max_segments_; + + /// What the minimim bytes of the initial segment should be. + ACE_OFF_T minimum_bytes_; + + /// Shared memory segment size. + size_t segment_size_; + + /// Base shared memory key for the segment. + key_t base_shm_key_; + + /// Find the segment that contains the @a searchPtr + virtual int find_seg (const void *const searchPtr, + ACE_OFF_T &offset, + size_t &counter); + + /// Determine how much memory is currently in use. + virtual int in_use (ACE_OFF_T &offset, + size_t &counter); + + /// Handles SIGSEGV. + ACE_Sig_Handler signal_handler_; + + /// Handle SIGSEGV and SIGBUS signals to remap shared memory + /// properly. + virtual int handle_signal (int signum, siginfo_t *, ucontext_t *); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* !ACE_LACKS_SYSV_SHMEM */ + +#include /**/ "ace/post.h" + +#endif /* ACE_SHARED_MEMORY_POOL_H */ diff --git a/dep/acelite/ace/Shared_Memory_SV.cpp b/dep/acelite/ace/Shared_Memory_SV.cpp new file mode 100644 index 00000000000..fe26688b098 --- /dev/null +++ b/dep/acelite/ace/Shared_Memory_SV.cpp @@ -0,0 +1,88 @@ +// $Id: Shared_Memory_SV.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Shared_Memory_SV.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Shared_Memory_SV.inl" +#endif /* __ACE_INLINE__ */ + + +ACE_RCSID (ace, + Shared_Memory_SV, + "$Id: Shared_Memory_SV.cpp 80826 2008-03-04 14:51:23Z wotte $") + + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Shared_Memory_SV) + +void +ACE_Shared_Memory_SV::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Shared_Memory_SV::dump"); +#endif /* ACE_HAS_DUMP */ +} + +ACE_Shared_Memory_SV::ACE_Shared_Memory_SV (key_t id, + size_t length, + int create, + int perms, + void *addr, + int flags) + : shared_memory_ (id, length, create, perms, addr, flags) +{ + ACE_TRACE ("ACE_Shared_Memory_SV::ACE_Shared_Memory_SV"); +} + +// The overall size of the segment. + +size_t +ACE_Shared_Memory_SV::get_segment_size (void) const +{ + ACE_TRACE ("ACE_Shared_Memory_SV::get_segment_size"); + // This cast is ok since the 'open' method for this class allows only + // an 'int' size. Therefore, this case should not lose information. + return this->shared_memory_.get_segment_size (); +} + +// Removes the shared memory segment. + +int +ACE_Shared_Memory_SV::remove (void) +{ + ACE_TRACE ("ACE_Shared_Memory_SV::remove"); + return shared_memory_.remove (); +} + +// Closes (detaches) the shared memory segment. + +int +ACE_Shared_Memory_SV::close (void) +{ + ACE_TRACE ("ACE_Shared_Memory_SV::close"); + return shared_memory_.detach (); +} + +void * +ACE_Shared_Memory_SV::malloc (size_t) +{ + ACE_TRACE ("ACE_Shared_Memory_SV::malloc"); + return this->shared_memory_.get_segment_ptr (); +} + +ACE_HANDLE +ACE_Shared_Memory_SV::get_id (void) const +{ + ACE_TRACE ("ACE_Shared_Memory_SV::get_id"); + return this->shared_memory_.get_id (); +} + +int +ACE_Shared_Memory_SV::free (void *p) +{ + ACE_TRACE ("ACE_Shared_Memory_SV::free"); + return p != 0; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Shared_Memory_SV.h b/dep/acelite/ace/Shared_Memory_SV.h new file mode 100644 index 00000000000..7ae62a3323f --- /dev/null +++ b/dep/acelite/ace/Shared_Memory_SV.h @@ -0,0 +1,101 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Shared_Memory_SV.h + * + * $Id: Shared_Memory_SV.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + + +#ifndef ACE_SHARED_MALLOC_SV_H +#define ACE_SHARED_MALLOC_SV_H +#include /**/ "ace/pre.h" + +#include "ace/Shared_Memory.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/SV_Shared_Memory.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Shared_Memory_SV + * + * @brief Shared memory wrapper based on System V shared memory. + * + * This class provides a very simple-minded shared memory manager. We + * strongly recommend that you do NOT use this class. Instead, please + * use @c ACE_Malloc, which has much more powerful capabilities. + */ +class ACE_Export ACE_Shared_Memory_SV : public ACE_Shared_Memory +{ +public: + enum + { + ACE_CREATE = IPC_CREAT, + ACE_OPEN = 0 + }; + + // = Initialization and termination methods. + ACE_Shared_Memory_SV (void); + ACE_Shared_Memory_SV (key_t id, + size_t length, + int create = ACE_Shared_Memory_SV::ACE_OPEN, + int perms = ACE_DEFAULT_FILE_PERMS, + void *addr = 0, + int flags = 0); + + int open (key_t id, + size_t length, + int create = ACE_Shared_Memory_SV::ACE_OPEN, + int perms = ACE_DEFAULT_FILE_PERMS, + void *addr = 0, + int flags = 0); + + /// Close down the shared memory segment. + virtual int close (void); + + /// Remove the underlying shared memory segment. + virtual int remove (void); + + // = Allocation and deallocation methods. + /// Create a new chuck of memory containing @a size bytes. + virtual void *malloc (size_t = 0); + + /// Free a chuck of memory allocated by . + virtual int free (void *p); + + /// Return the size of the shared memory segment. + virtual size_t get_segment_size (void) const; + + /// Return the ID of the shared memory segment (i.e., a System V + /// shared memory internal id). + virtual ACE_HANDLE get_id (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + /// This version is implemented with System V shared memory + /// segments. + ACE_SV_Shared_Memory shared_memory_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Shared_Memory_SV.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_SHARED_MALLOC_SV_H */ diff --git a/dep/acelite/ace/Shared_Memory_SV.inl b/dep/acelite/ace/Shared_Memory_SV.inl new file mode 100644 index 00000000000..1a586701cc3 --- /dev/null +++ b/dep/acelite/ace/Shared_Memory_SV.inl @@ -0,0 +1,30 @@ +// -*- C++ -*- +// +// $Id: Shared_Memory_SV.inl 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Global_Macros.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE int +ACE_Shared_Memory_SV::open (key_t id, + size_t length, + int create, + int perms, + void *addr, + int flags) +{ + ACE_TRACE ("ACE_Shared_Memory_SV::open"); + return shared_memory_.open_and_attach (id, length, create, + perms, addr, flags); +} + +// The "do-nothing" constructor. + +ACE_INLINE +ACE_Shared_Memory_SV::ACE_Shared_Memory_SV (void) +{ + ACE_TRACE ("ACE_Shared_Memory_SV::ACE_Shared_Memory_SV"); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Shared_Object.cpp b/dep/acelite/ace/Shared_Object.cpp new file mode 100644 index 00000000000..76c27df1cb1 --- /dev/null +++ b/dep/acelite/ace/Shared_Object.cpp @@ -0,0 +1,54 @@ +// $Id: Shared_Object.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Shared_Object.h" +#include "ace/Global_Macros.h" +#include "ace/config-all.h" + +/* Provide the abstract base class used to access dynamic linking + facilities */ + +#if !defined (__ACE_INLINE__) +#include "ace/Shared_Object.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID (ace, + Shared_Object, + "$Id: Shared_Object.cpp 80826 2008-03-04 14:51:23Z wotte $") + + ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Initializes object when dynamic linking occurs. + +int +ACE_Shared_Object::init (int, ACE_TCHAR *[]) +{ + ACE_TRACE ("ACE_Shared_Object::init"); + return 0; +} + +// Terminates object when dynamic unlinking occurs. + +int +ACE_Shared_Object::fini (void) +{ + ACE_TRACE ("ACE_Shared_Object::fini"); + return 0; +} + +// Returns information on active object. + +int +ACE_Shared_Object::info (ACE_TCHAR **, size_t) const +{ + ACE_TRACE ("ACE_Shared_Object::info"); + return 0; +} + +// Need to give a default implementation. + +ACE_Shared_Object::~ACE_Shared_Object (void) +{ + ACE_TRACE ("ACE_Shared_Object::~ACE_Shared_Object"); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Shared_Object.h b/dep/acelite/ace/Shared_Object.h new file mode 100644 index 00000000000..fedf051ba6f --- /dev/null +++ b/dep/acelite/ace/Shared_Object.h @@ -0,0 +1,62 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file Shared_Object.h + * + * $Id: Shared_Object.h 81348 2008-04-14 09:00:32Z johnnyw $ + * + * @author Douglas C. Schmidt + */ +//========================================================================== + +#ifndef ACE_SHARED_OBJECT_H +#define ACE_SHARED_OBJECT_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_types.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Shared_Object + * + * @brief Provide the abstract base class used to access dynamic + * linking facilities. + */ +class ACE_Export ACE_Shared_Object +{ +public: + /// Constructor + ACE_Shared_Object (void); + + /// Destructor + virtual ~ACE_Shared_Object (void); + + /// Initializes object when dynamic linking occurs. + virtual int init (int argc, ACE_TCHAR *argv[]); + + /// Terminates object when dynamic unlinking occurs. + virtual int fini (void); + + /// Returns information on a service object. + virtual int info (ACE_TCHAR **info_string, size_t length = 0) const; + +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Shared_Object.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" + +#endif /* ACE_SHARED_OBJECT_H */ diff --git a/dep/acelite/ace/Shared_Object.inl b/dep/acelite/ace/Shared_Object.inl new file mode 100644 index 00000000000..4f5f0020604 --- /dev/null +++ b/dep/acelite/ace/Shared_Object.inl @@ -0,0 +1,12 @@ +// -*- C++ -*- +// +// $Id: Shared_Object.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE +ACE_Shared_Object::ACE_Shared_Object (void) +{ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Sig_Adapter.cpp b/dep/acelite/ace/Sig_Adapter.cpp new file mode 100644 index 00000000000..d1af40f12d5 --- /dev/null +++ b/dep/acelite/ace/Sig_Adapter.cpp @@ -0,0 +1,80 @@ +// $Id: Sig_Adapter.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Sig_Adapter.h" + +ACE_RCSID(ace, Sig_Adapter, "$Id: Sig_Adapter.cpp 80826 2008-03-04 14:51:23Z wotte $") + + +ACE_Sig_Adapter::ACE_Sig_Adapter (ACE_Sig_Action &sa, int sigkey) + : sigkey_ (sigkey), + type_ (SIG_ACTION), + sa_ (sa) +{ + // ACE_TRACE ("ACE_Sig_Adapter::ACE_Sig_Adapter"); +} + +ACE_Sig_Adapter::ACE_Sig_Adapter (ACE_Event_Handler *eh, + int sigkey) + : sigkey_ (sigkey), + type_ (ACE_HANDLER), + eh_ (eh) +{ + // ACE_TRACE ("ACE_Sig_Adapter::ACE_Sig_Adapter"); +} + +ACE_Sig_Adapter::ACE_Sig_Adapter (ACE_Sig_Handler_Ex sig_func, + int sigkey) + : sigkey_ (sigkey), + type_ (C_FUNCTION), + sig_func_ (sig_func) +{ + // ACE_TRACE ("ACE_Sig_Adapter::ACE_Sig_Adapter"); +} + +ACE_Sig_Adapter::~ACE_Sig_Adapter () +{ +} + +int +ACE_Sig_Adapter::sigkey (void) +{ + ACE_TRACE ("ACE_Sig_Adapter::sigkey"); + return this->sigkey_; +} + +int +ACE_Sig_Adapter::handle_signal (int signum, + siginfo_t *siginfo, + ucontext_t *ucontext) +{ + ACE_TRACE ("ACE_Sig_Adapter::handle_signal"); + + switch (this->type_) + { + case SIG_ACTION: + { + // We have to dispatch a handler that was registered by a + // third-party library. + + ACE_Sig_Action old_disp; + + // Make sure this handler executes in the context it was + // expecting... + this->sa_.register_action (signum, &old_disp); + + ACE_Sig_Handler_Ex sig_func = ACE_Sig_Handler_Ex (this->sa_.handler ()); + + (*sig_func) (signum, siginfo, ucontext); + // Restore the original disposition. + old_disp.register_action (signum); + break; + } + case ACE_HANDLER: + this->eh_->handle_signal (signum, siginfo, ucontext); + break; + case C_FUNCTION: + (*this->sig_func_) (signum, siginfo, ucontext); + break; + } + return 0; +} diff --git a/dep/acelite/ace/Sig_Adapter.h b/dep/acelite/ace/Sig_Adapter.h new file mode 100644 index 00000000000..cbd6b399867 --- /dev/null +++ b/dep/acelite/ace/Sig_Adapter.h @@ -0,0 +1,81 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Sig_Adapter.h + * + * $Id: Sig_Adapter.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_SIG_ADAPTER_H +#define ACE_SIG_ADAPTER_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Event_Handler.h" +#include "ace/Signal.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Sig_Adapter + * + * @brief Provide an adapter that transforms various types of signal + * handlers into the scheme used by the ACE_Reactor. + */ +class ACE_Export ACE_Sig_Adapter : public ACE_Event_Handler +{ +public: + ACE_Sig_Adapter (ACE_Sig_Action &, int sigkey); + ACE_Sig_Adapter (ACE_Event_Handler *, int sigkey); + ACE_Sig_Adapter (ACE_Sig_Handler_Ex, int sigkey = 0); + ~ACE_Sig_Adapter (void); + + /// Returns this signal key that's used to remove this from the + /// ACE_Reactor's internal table. + int sigkey (void); + + /// Called by the to dispatch the signal handler. + virtual int handle_signal (int, siginfo_t *, ucontext_t *); + +private: + /// Key for this signal handler (used to remove it). + int sigkey_; + + /// Is this an external handler or an ACE handler? + enum + { + /// We're just wrapping an ACE_Event_Handler. + ACE_HANDLER, + /// An ACE_Sig_Action. + SIG_ACTION, + /// A normal C function. + C_FUNCTION + } type_; + + // = This should be a union, but C++ won't allow that because the + // has a constructor. + /// This is an external handler (ugh). + ACE_Sig_Action sa_; + + /// This is an ACE hander. + ACE_Event_Handler *eh_; + + /// This is a normal C function. + ACE_Sig_Handler_Ex sig_func_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" + +#endif /* ACE_SIG_ADAPTER_H */ diff --git a/dep/acelite/ace/Sig_Handler.cpp b/dep/acelite/ace/Sig_Handler.cpp new file mode 100644 index 00000000000..8691f817fa0 --- /dev/null +++ b/dep/acelite/ace/Sig_Handler.cpp @@ -0,0 +1,616 @@ +// $Id: Sig_Handler.cpp 88360 2009-12-30 08:42:20Z olli $ + +#include "ace/Sig_Handler.h" +#include "ace/Sig_Adapter.h" +#include "ace/Signal.h" +#include "ace/Recursive_Thread_Mutex.h" +#include "ace/Managed_Object.h" +#include "ace/Containers.h" +#include "ace/Guard_T.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Sig_Handler.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID(ace, Sig_Handler, "$Id: Sig_Handler.cpp 88360 2009-12-30 08:42:20Z olli $") + +#if defined (ACE_HAS_SIG_C_FUNC) + +extern "C" void +ace_sig_handler_dispatch (int signum, siginfo_t *info, ucontext_t *context) +{ + ACE_TRACE ("ace_sig_handler_dispatch"); + ACE_Sig_Handler::dispatch (signum, info, context); +} + +#define ace_signal_handler_dispatcher ACE_SignalHandler(ace_sig_handler_dispatch) + +extern "C" void +ace_sig_handlers_dispatch (int signum, siginfo_t *info, ucontext_t *context) +{ + ACE_TRACE ("ace_sig_handlers_dispatch"); + ACE_Sig_Handlers::dispatch (signum, info, context); +} + +#define ace_signal_handlers_dispatcher ACE_SignalHandler(ace_sig_handlers_dispatch) + +#else +#define ace_signal_handler_dispatcher ACE_SignalHandler(ACE_Sig_Handler::dispatch) + +#define ace_signal_handlers_dispatcher ACE_SignalHandler(ACE_Sig_Handlers::dispatch) +#endif /* ACE_HAS_SIG_C_FUNC */ + + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Array of Event_Handlers that will handle the signals. +ACE_Event_Handler *ACE_Sig_Handler::signal_handlers_[ACE_NSIG]; + +// Remembers if a signal has occurred. +sig_atomic_t ACE_Sig_Handler::sig_pending_ = 0; + + +ACE_ALLOC_HOOK_DEFINE(ACE_Sig_Handler) + +ACE_Sig_Handler::~ACE_Sig_Handler (void) +{ +} + +void +ACE_Sig_Handler::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Sig_Handler::dump"); +#endif /* ACE_HAS_DUMP */ +} + +int +ACE_Sig_Handler::sig_pending (void) +{ + ACE_TRACE ("ACE_Sig_Handler::sig_pending"); + ACE_MT (ACE_Recursive_Thread_Mutex *lock = + ACE_Managed_Object::get_preallocated_object + (ACE_Object_Manager::ACE_SIG_HANDLER_LOCK); + ACE_Guard m (*lock)); + return ACE_Sig_Handler::sig_pending_ != 0; +} + +void +ACE_Sig_Handler::sig_pending (int pending) +{ + ACE_TRACE ("ACE_Sig_Handler::sig_pending"); + + ACE_MT (ACE_Recursive_Thread_Mutex *lock = + ACE_Managed_Object::get_preallocated_object + (ACE_Object_Manager::ACE_SIG_HANDLER_LOCK); + ACE_Guard m (*lock)); + ACE_Sig_Handler::sig_pending_ = pending; +} + +ACE_Event_Handler * +ACE_Sig_Handler::handler (int signum) +{ + ACE_TRACE ("ACE_Sig_Handler::handler"); + ACE_MT (ACE_Recursive_Thread_Mutex *lock = + ACE_Managed_Object::get_preallocated_object + (ACE_Object_Manager::ACE_SIG_HANDLER_LOCK); + ACE_Guard m (*lock)); + + if (ACE_Sig_Handler::in_range (signum)) + return ACE_Sig_Handler::signal_handlers_[signum]; + else + return 0; +} + +ACE_Event_Handler * +ACE_Sig_Handler::handler_i (int signum, + ACE_Event_Handler *new_sh) +{ + ACE_TRACE ("ACE_Sig_Handler::handler_i"); + + if (ACE_Sig_Handler::in_range (signum)) + { + ACE_Event_Handler *sh = ACE_Sig_Handler::signal_handlers_[signum]; + + ACE_Sig_Handler::signal_handlers_[signum] = new_sh; + return sh; + } + else + return 0; +} + +ACE_Event_Handler * +ACE_Sig_Handler::handler (int signum, + ACE_Event_Handler *new_sh) +{ + ACE_TRACE ("ACE_Sig_Handler::handler"); + ACE_MT (ACE_Recursive_Thread_Mutex *lock = + ACE_Managed_Object::get_preallocated_object + (ACE_Object_Manager::ACE_SIG_HANDLER_LOCK); + ACE_Guard m (*lock)); + + return ACE_Sig_Handler::handler_i (signum, new_sh); +} + +// Register an ACE_Event_Handler along with the corresponding SIGNUM. +// This method does NOT acquire any locks, so it can be called from a +// signal handler. + +int +ACE_Sig_Handler::register_handler_i (int signum, + ACE_Event_Handler *new_sh, + ACE_Sig_Action *new_disp, + ACE_Event_Handler **old_sh, + ACE_Sig_Action *old_disp) +{ + ACE_TRACE ("ACE_Sig_Handler::register_handler_i"); + + if (ACE_Sig_Handler::in_range (signum)) + { + ACE_Sig_Action sa; // Define a "null" action. + ACE_Event_Handler *sh = ACE_Sig_Handler::handler_i (signum, new_sh); + + // Return a pointer to the old if the user + // asks for this. + if (old_sh != 0) + *old_sh = sh; + + // Make sure that points to a valid location if the + // user doesn't care... + if (new_disp == 0) + new_disp = &sa; + + new_disp->handler (ace_signal_handler_dispatcher); +#if !defined (ACE_HAS_LYNXOS4_SIGNALS) + new_disp->flags (new_disp->flags () | SA_SIGINFO); +#endif /* ACE_HAS_LYNXOS4_SIGNALS */ + return new_disp->register_action (signum, old_disp); + } + else + return -1; +} + +// Register an ACE_Event_Handler along with the corresponding SIGNUM. +// This method acquires a lock, so it can't be called from a signal +// handler, e.g., . + +int +ACE_Sig_Handler::register_handler (int signum, + ACE_Event_Handler *new_sh, + ACE_Sig_Action *new_disp, + ACE_Event_Handler **old_sh, + ACE_Sig_Action *old_disp) +{ + ACE_TRACE ("ACE_Sig_Handler::register_handler"); + ACE_MT (ACE_Recursive_Thread_Mutex *lock = + ACE_Managed_Object::get_preallocated_object + (ACE_Object_Manager::ACE_SIG_HANDLER_LOCK); + ACE_Guard m (*lock)); + + return ACE_Sig_Handler::register_handler_i (signum, + new_sh, + new_disp, + old_sh, + old_disp); +} + +// Remove an ACE_Event_Handler. + +int +ACE_Sig_Handler::remove_handler (int signum, + ACE_Sig_Action *new_disp, + ACE_Sig_Action *old_disp, + int) +{ + ACE_TRACE ("ACE_Sig_Handler::remove_handler"); + ACE_MT (ACE_Recursive_Thread_Mutex *lock = + ACE_Managed_Object::get_preallocated_object + (ACE_Object_Manager::ACE_SIG_HANDLER_LOCK); + ACE_Guard m (*lock)); + + if (ACE_Sig_Handler::in_range (signum)) + { + ACE_Sig_Action sa (SIG_DFL, (sigset_t *) 0); // Define the default disposition. + + if (new_disp == 0) + new_disp = &sa; + + ACE_Sig_Handler::signal_handlers_[signum] = 0; + + // Register either the new disposition or restore the default. + return new_disp->register_action (signum, old_disp); + } + + return -1; +} + +// Master dispatcher function that gets called by a signal handler and +// dispatches one handler... + +void +ACE_Sig_Handler::dispatch (int signum, + siginfo_t *siginfo, + ucontext_t *ucontext) +{ + ACE_TRACE ("ACE_Sig_Handler::dispatch"); + + // Save/restore errno. + ACE_Errno_Guard error (errno); + + // We can't use the call here because that acquires + // the lock, which is non-portable... + ACE_Sig_Handler::sig_pending_ = 1; + + // Darn well better be in range since the OS dispatched this... + ACE_ASSERT (ACE_Sig_Handler::in_range (signum)); + + ACE_Event_Handler *eh = ACE_Sig_Handler::signal_handlers_[signum]; + + if (eh != 0) + { + if (eh->handle_signal (signum, siginfo, ucontext) == -1) + { + // Define the default disposition. + ACE_Sig_Action sa ((ACE_SignalHandler) SIG_DFL, (sigset_t *) 0); + + ACE_Sig_Handler::signal_handlers_[signum] = 0; + + // Remove the current disposition by registering the default + // disposition. + sa.register_action (signum); + + // Allow the event handler to close down if necessary. + eh->handle_close (ACE_INVALID_HANDLE, + ACE_Event_Handler::SIGNAL_MASK); + } +#if defined (ACE_WIN32) + else + // Win32 is weird in the sense that it resets the signal + // disposition to SIG_DFL after a signal handler is + // dispatched. Therefore, to workaround this "feature" we + // must re-register the with + // explicitly. + ACE_Sig_Handler::register_handler_i (signum, + eh); +#endif /* ACE_WIN32*/ + } +} + +// ---------------------------------------- +// The following classes are local to this file. + +// There are bugs with HP/UX's C++ compiler that prevents this stuff +// from compiling... +#define ACE_MAX_SIGNAL_HANDLERS ((size_t) 20) + +// Keeps track of the id that uniquely identifies each registered +// signal handler. This id can be used to cancel a timer via the +// method. +int ACE_Sig_Handlers::sigkey_ = 0; + +// If this is true then a 3rd party library has registered a +// handler... +bool ACE_Sig_Handlers::third_party_sig_handler_ = false; + +// Make life easier by defining typedefs... +typedef ACE_Fixed_Set ACE_SIG_HANDLERS_SET; +typedef ACE_Fixed_Set_Iterator ACE_SIG_HANDLERS_ITERATOR; + +class ACE_Sig_Handlers_Set +{ +public: + static ACE_SIG_HANDLERS_SET *instance (int signum); + +private: + static ACE_SIG_HANDLERS_SET *sig_handlers_[ACE_NSIG]; +}; + +/* static */ +ACE_SIG_HANDLERS_SET *ACE_Sig_Handlers_Set::sig_handlers_[ACE_NSIG]; + +/* static */ +ACE_SIG_HANDLERS_SET * +ACE_Sig_Handlers_Set::instance (int signum) +{ + if (signum <= 0 || signum >= ACE_NSIG) + return 0; // This will cause problems... + else if (ACE_Sig_Handlers_Set::sig_handlers_[signum] == 0) + ACE_NEW_RETURN (ACE_Sig_Handlers_Set::sig_handlers_[signum], + ACE_SIG_HANDLERS_SET, + 0); + return ACE_Sig_Handlers_Set::sig_handlers_[signum]; +} + +ACE_ALLOC_HOOK_DEFINE(ACE_Sig_Handlers) + +void +ACE_Sig_Handlers::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Sig_Handlers::dump"); +#endif /* ACE_HAS_DUMP */ +} + +// This is the method that does all the dirty work... The basic +// structure of this method was devised by Detlef Becker. + +int +ACE_Sig_Handlers::register_handler (int signum, + ACE_Event_Handler *new_sh, + ACE_Sig_Action *new_disp, + ACE_Event_Handler **, + ACE_Sig_Action *old_disp) +{ + ACE_TRACE ("ACE_Sig_Handlers::register_handler"); + ACE_MT (ACE_Recursive_Thread_Mutex *lock = + ACE_Managed_Object::get_preallocated_object + (ACE_Object_Manager::ACE_SIG_HANDLER_LOCK); + ACE_Guard m (*lock)); + + if (ACE_Sig_Handler::in_range (signum)) + { + ACE_Sig_Adapter *ace_sig_adapter = 0; // Our signal handler. + ACE_Sig_Adapter *extern_sh = 0; // An external signal handler. + ACE_Sig_Action sa; + + // Get current signal disposition. + sa.retrieve_action (signum); + + // Check whether we are already in control of the signal + // handling disposition... + + if (!(sa.handler () == ace_signal_handlers_dispatcher + || sa.handler () == ACE_SignalHandler (SIG_IGN) + || sa.handler () == ACE_SignalHandler (SIG_DFL))) + { + // Drat, a 3rd party library has already installed a signal ;-( + + // Upto here we never disabled RESTART_MODE. Thus, + // RESTART_MODE can only be changed by 3rd party libraries. + + if (ACE_BIT_DISABLED (sa.flags (), SA_RESTART) + && ACE_Sig_Handlers::third_party_sig_handler_) + // Toggling is disallowed since we might break 3rd party + // code. + return -1; + + // Note that we've seen a 3rd party handler... + ACE_Sig_Handlers::third_party_sig_handler_ = true; + + // Create a new 3rd party disposition, remembering its + // preferred signal blocking etc...; + ACE_NEW_RETURN (extern_sh, + ACE_Sig_Adapter (sa, + ++ACE_Sig_Handlers::sigkey_), + -1); + // Add the external signal handler to the set of handlers + // for this signal. + if (ACE_Sig_Handlers_Set::instance (signum)->insert (extern_sh) == -1) + { + delete extern_sh; + return -1; + } + } + // Add our new handler at this point. + ACE_NEW_RETURN (ace_sig_adapter, + ACE_Sig_Adapter (new_sh, + ++ACE_Sig_Handlers::sigkey_), + -1); + // Add the ACE signal handler to the set of handlers for this + // signal (make sure it goes before the external one if there is + // one of these). + + int result = ACE_Sig_Handlers_Set::instance (signum)->insert (ace_sig_adapter); + + if (result == -1) + { + // We couldn't reinstall our handler, so let's pretend like + // none of this happened... + if (extern_sh) + { + ACE_Sig_Handlers_Set::instance (signum)->remove (extern_sh); + delete extern_sh; + } + delete ace_sig_adapter; + return -1; + } + // If ACE_Sig_Handlers::dispatch() was set we're done. + else if (sa.handler () == ace_signal_handlers_dispatcher) + return ace_sig_adapter->sigkey (); + + // Otherwise, we need to register our handler function so that + // all signals will be dispatched through ACE. + else + { + // Make sure that new_disp points to a valid location if the + // user doesn't care... + if (new_disp == 0) + new_disp = &sa; + + new_disp->handler (ace_signal_handlers_dispatcher); + + // Default is to restart signal handlers. + new_disp->flags (new_disp->flags () | SA_RESTART); +#if !defined (ACE_HAS_LYNXOS4_SIGNALS) + new_disp->flags (new_disp->flags () | SA_SIGINFO); +#endif /* ACE_HAS_LYNXOS4_SIGNALS */ + + // Finally install (possibly reinstall) the ACE signal + // handler disposition with the SA_RESTART mode enabled. + if (new_disp->register_action (signum, old_disp) == -1) + { + // Yikes, lots of roll back at this point... + ACE_Sig_Handlers_Set::instance (signum)->remove (ace_sig_adapter); + delete ace_sig_adapter; + + if (extern_sh) + { + ACE_Sig_Handlers_Set::instance (signum)->remove (extern_sh); + delete extern_sh; + } + return -1; + } + else // Return the signal key so that programs can cancel this + // handler if they want! + return ace_sig_adapter->sigkey (); + } + } + + return -1; +} + +// Remove the ACE_Event_Handler currently associated with . +// Install the new disposition (if given) and return the previous +// disposition (if desired by the caller). Returns 0 on success and +// -1 if is invalid. + +int +ACE_Sig_Handlers::remove_handler (int signum, + ACE_Sig_Action *new_disp, + ACE_Sig_Action *old_disp, + int sigkey) +{ + ACE_TRACE ("ACE_Sig_Handlers::remove_handler"); + ACE_MT (ACE_Recursive_Thread_Mutex *lock = + ACE_Managed_Object::get_preallocated_object + (ACE_Object_Manager::ACE_SIG_HANDLER_LOCK); + ACE_Guard m (*lock)); + + if (ACE_Sig_Handler::in_range (signum)) + { + ACE_SIG_HANDLERS_SET *handler_set = + ACE_Sig_Handlers_Set::instance (signum); + + ACE_SIG_HANDLERS_ITERATOR handler_iterator (*handler_set); + + // Iterate through the set of handlers for this signal. + + for (ACE_Event_Handler **eh; + handler_iterator.next (eh) != 0; + ) + { + // Type-safe downcast would be nice here... + ACE_Sig_Adapter *sh = (ACE_Sig_Adapter *) *eh; + + // Remove the handler if (1) its key matches the key we've + // been told to remove or (2) if we've been told to remove + // *all* handlers (i.e., == -1). + + if (sh->sigkey () == sigkey || sigkey == -1) + { + handler_set->remove (*eh); + delete *eh; + } + } + + if (handler_set->size () == 0) + { + // If there are no more handlers left for a signal then + // register the new disposition or restore the default + // disposition. + + ACE_Sig_Action sa (SIG_DFL, (sigset_t *) 0); + + if (new_disp == 0) + new_disp = &sa; + + return new_disp->register_action (signum, old_disp); + } + return 0; + } + else + return -1; +} + +// Master dispatcher function that gets called by a signal handler and +// dispatches *all* the handlers... + +void +ACE_Sig_Handlers::dispatch (int signum, + siginfo_t *siginfo, + ucontext_t *ucontext) +{ + ACE_TRACE ("ACE_Sig_Handlers::dispatch"); + // The following is #ifdef'd out because it's entirely non-portable + // to acquire a mutex in a signal handler... +#if 0 + ACE_MT (ACE_Recursive_Thread_Mutex *lock = + ACE_Managed_Object::get_preallocated_object + (ACE_Object_Manager::ACE_SIG_HANDLER_LOCK); + ACE_TSS_Guard m (*lock)); +#endif /* 0 */ + + // Save/restore errno. + ACE_Errno_Guard error (errno); + + ACE_Sig_Handler::sig_pending_ = 1; + + // Darn well better be in range since the OS dispatched this... + ACE_ASSERT (ACE_Sig_Handler::in_range (signum)); + + ACE_SIG_HANDLERS_SET *handler_set = + ACE_Sig_Handlers_Set::instance (signum); + + ACE_SIG_HANDLERS_ITERATOR handler_iterator (*handler_set); + + for (ACE_Event_Handler **eh = 0; + handler_iterator.next (eh) != 0; + ) + if ((*eh)->handle_signal (signum, siginfo, ucontext) == -1) + { + handler_set->remove (*eh); + delete *eh; + } +} + +// Return the first item in the list of handlers. Note that this will +// trivially provide the same behavior as the ACE_Sig_Handler +// version if there is only 1 handler registered! + +ACE_Event_Handler * +ACE_Sig_Handlers::handler (int signum) +{ + ACE_TRACE ("ACE_Sig_Handlers::handler"); + ACE_SIG_HANDLERS_SET *handler_set = + ACE_Sig_Handlers_Set::instance (signum); + ACE_SIG_HANDLERS_ITERATOR handler_iterator (*handler_set); + ACE_Event_Handler **eh = 0; + handler_iterator.next (eh); + return *eh; +} + +// The following is a strange bit of logic that tries to give the same +// semantics as what happens in ACE_Sig_Handler when we replace the +// current signal handler with a new one. Note that if there is only +// one signal handler the behavior will be identical. If there is +// more than one handler then things get weird... + +ACE_Event_Handler * +ACE_Sig_Handlers::handler (int signum, ACE_Event_Handler *new_sh) +{ + ACE_TRACE ("ACE_Sig_Handlers::handler"); + ACE_SIG_HANDLERS_SET *handler_set = + ACE_Sig_Handlers_Set::instance (signum); + ACE_SIG_HANDLERS_ITERATOR handler_iterator (*handler_set); + ACE_Event_Handler **eh = 0; + + // Find the first handler... + handler_iterator.next (eh); + + // ... then remove it from the set ... + handler_set->remove (*eh); + + // ... and then insert the new signal handler into the beginning of + // the set (note, this is a bit too tied up in the implementation of + // ACE_Unbounded_Set...). + ACE_Sig_Adapter *temp = 0; + + ACE_NEW_RETURN (temp, + ACE_Sig_Adapter (new_sh, + ++ACE_Sig_Handlers::sigkey_), + 0); + handler_set->insert (temp); + return *eh; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Sig_Handler.h b/dep/acelite/ace/Sig_Handler.h new file mode 100644 index 00000000000..df1f0bfc495 --- /dev/null +++ b/dep/acelite/ace/Sig_Handler.h @@ -0,0 +1,237 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Sig_Handler.h + * + * $Id: Sig_Handler.h 84727 2009-03-05 19:22:29Z johnnyw $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_SIGNAL_HANDLER_H +#define ACE_SIGNAL_HANDLER_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Event_Handler.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +class ACE_Sig_Action; + +/** + * @class ACE_Sig_Handler + * + * @brief This is the main dispatcher of signals for ACE. It improves + * the existing UNIX signal handling mechanism by allowing C++ + * objects to handle signals in a way that avoids the use of + * global/static variables and functions. + * + * Using this class a program can register an ACE_Event_Handler + * with the ACE_Sig_Handler in order to handle a designated + * @a signum. When a signal occurs that corresponds to this + * @a signum, the @c handle_signal method of the registered + * ACE_Event_Handler is invoked automatically. + */ +class ACE_Export ACE_Sig_Handler +{ +public: + /// Default constructor. + ACE_Sig_Handler (void); + + /// Destructor + virtual ~ACE_Sig_Handler (void); + + // = Registration and removal methods. + /** + * Add a new ACE_Event_Handler and a new sigaction associated with + * @a signum. Passes back the existing ACE_Event_Handler and its + * sigaction if pointers are non-zero. Returns -1 on failure and >= + * 0 on success. + */ + virtual int register_handler (int signum, + ACE_Event_Handler *new_sh, + ACE_Sig_Action *new_disp = 0, + ACE_Event_Handler **old_sh = 0, + ACE_Sig_Action *old_disp = 0); + + /** + * Remove the ACE_Event_Handler currently associated with + * @a signum. @a sigkey is ignored in this implementation since there + * is only one instance of a signal handler. Install the new + * disposition (if given) and return the previous disposition (if + * desired by the caller). Returns 0 on success and -1 if @a signum + * is invalid. + */ + virtual int remove_handler (int signum, + ACE_Sig_Action *new_disp = 0, + ACE_Sig_Action *old_disp = 0, + int sigkey = -1); + + // Set/get signal status. + /// True if there is a pending signal. + static int sig_pending (void); + + /// Reset the value of so that no signal is pending. + static void sig_pending (int); + + // = Set/get the handler associated with a particular signal. + + /// Return the ACE_Sig_Handler associated with @a signum. + virtual ACE_Event_Handler *handler (int signum); + + /// Set a new ACE_Event_Handler that is associated with @a signum. + /// Return the existing handler. + virtual ACE_Event_Handler *handler (int signum, ACE_Event_Handler *); + + /** + * Callback routine registered with sigaction(2) that dispatches the + * method of the appropriate pre-registered + * ACE_Event_Handler. + */ + static void dispatch (int, siginfo_t *, + ucontext_t *); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + // = These methods and data members are shared by derived classes. + + /** + * Set a new ACE_Event_Handler that is associated with @a signum. + * Return the existing handler. Does not acquire any locks so that + * it can be called from a signal handler, such as . + */ + static ACE_Event_Handler *handler_i (int signum, + ACE_Event_Handler *); + + /** + * This implementation method is called by and + * @c dispatch. It doesn't do any locking so that it can be called + * within a signal handler, such as @c dispatch. It adds a new + * ACE_Event_Handler and a new sigaction associated with @a signum. + * Passes back the existing ACE_Event_Handler and its sigaction if + * pointers are non-zero. Returns -1 on failure and >= 0 on + * success. + */ + static int register_handler_i (int signum, + ACE_Event_Handler *new_sh, + ACE_Sig_Action *new_disp = 0, + ACE_Event_Handler **old_sh = 0, + ACE_Sig_Action *old_disp = 0); + + /// Check whether the SIGNUM is within the legal range of signals. + static int in_range (int signum); + + /// Keeps track of whether a signal is pending. + static sig_atomic_t sig_pending_; + +private: + /// Array used to store one user-defined Event_Handler for every + /// signal. + static ACE_Event_Handler *signal_handlers_[ACE_NSIG]; +}; + +/** + * @class ACE_Sig_Handlers + * + * @brief This is an alternative signal handling dispatcher for ACE. It + * allows a list of signal handlers to be registered for each + * signal. It also makes SA_RESTART the default mode. + * + * Using this class a program can register one or more + * ACE_Event_Handler with the ACE_Sig_Handler in order to + * handle a designated @a signum. When a signal occurs that + * corresponds to this @a signum, the methods of + * all the registered ACE_Event_Handlers are invoked + * automatically. + */ +class ACE_Export ACE_Sig_Handlers : public ACE_Sig_Handler +{ +public: + // = Registration and removal methods. + /** + * Add a new ACE_Event_Handler and a new sigaction associated with + * @a signum. Passes back the existing ACE_Event_Handler and its + * sigaction if pointers are non-zero. Returns -1 on failure and + * a that is >= 0 on success. + */ + virtual int register_handler (int signum, + ACE_Event_Handler *new_sh, + ACE_Sig_Action *new_disp = 0, + ACE_Event_Handler **old_sh = 0, + ACE_Sig_Action *old_disp = 0); + + /** + * Remove an ACE_Event_Handler currently associated with @a signum. + * We remove the handler if (1) its sigkey> matches the @a sigkey + * passed as a parameter or (2) if we've been told to remove all the + * handlers, i.e., @a sigkey == -1. If a new disposition is given it + * is installed and the previous disposition is returned (if desired + * by the caller). Returns 0 on success and -1 if @a signum is + * invalid. + */ + virtual int remove_handler (int signum, + ACE_Sig_Action *new_disp = 0, + ACE_Sig_Action *old_disp = 0, + int sigkey = -1); + + // = Set/get the handler associated with a particular signal. + + /// Return the head of the list of s associated with + /// SIGNUM. + virtual ACE_Event_Handler *handler (int signum); + + /** + * Set a new ACE_Event_Handler that is associated with SIGNUM at + * the head of the list of signals. Return the existing handler + * that was at the head. + */ + virtual ACE_Event_Handler *handler (int signum, + ACE_Event_Handler *); + + /** + * Callback routine registered with sigaction(2) that dispatches the + * method of all the pre-registered + * ACE_Event_Handlers for @a signum + */ + static void dispatch (int signum, siginfo_t *, ucontext_t *); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + /** + * Keeps track of the id that uniquely identifies each registered + * signal handler. This id can be used to cancel a timer via the + * method. + */ + static int sigkey_; + + /// If this is true then a 3rd party library has registered a + /// handler... + static bool third_party_sig_handler_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Sig_Handler.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_SIG_HANDLER_H */ diff --git a/dep/acelite/ace/Sig_Handler.inl b/dep/acelite/ace/Sig_Handler.inl new file mode 100644 index 00000000000..de02c09ab16 --- /dev/null +++ b/dep/acelite/ace/Sig_Handler.inl @@ -0,0 +1,15 @@ +// -*- C++ -*- +// +// $Id: Sig_Handler.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_INLINE +ACE_Sig_Handler::ACE_Sig_Handler (void) +{ +} + +ACE_INLINE int +ACE_Sig_Handler::in_range (int signum) +{ + ACE_TRACE ("ACE_Sig_Handler::in_range"); + return signum > 0 && signum < ACE_NSIG; +} diff --git a/dep/acelite/ace/Signal.cpp b/dep/acelite/ace/Signal.cpp new file mode 100644 index 00000000000..5f17455502b --- /dev/null +++ b/dep/acelite/ace/Signal.cpp @@ -0,0 +1,221 @@ +// $Id: Signal.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Signal.h" +// #include "ace/Log_Msg.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Signal.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID(ace, Signal, "$Id: Signal.cpp 80826 2008-03-04 14:51:23Z wotte $") + + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Sig_Action) + +void +ACE_Sig_Action::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Sig_Action::dump"); +#endif /* ACE_HAS_DUMP */ +} + +ACE_ALLOC_HOOK_DEFINE(ACE_Sig_Set) + +ACE_Sig_Set::~ACE_Sig_Set (void) +{ + ACE_TRACE ("ACE_Sig_Set::~ACE_Sig_Set"); + ACE_OS::sigemptyset (&this->sigset_); +} + +ACE_Sig_Action::~ACE_Sig_Action (void) +{ + ACE_TRACE ("ACE_Sig_Action::~ACE_Sig_Action"); +} + +// Restore the signal mask. + +ACE_Sig_Guard::~ACE_Sig_Guard (void) +{ + //ACE_TRACE ("ACE_Sig_Guard::~ACE_Sig_Guard"); + if (!this->condition_) + return; + +#if !defined (ACE_LACKS_UNIX_SIGNALS) +#if defined (ACE_LACKS_PTHREAD_THR_SIGSETMASK) + ACE_OS::sigprocmask (SIG_SETMASK, + (sigset_t *) this->omask_, + 0); +#else + ACE_OS::thr_sigsetmask (SIG_SETMASK, + (sigset_t *) this->omask_, + 0); +#endif /* ACE_LACKS_PTHREAD_THR_SIGSETMASK */ +#endif /* !ACE_LACKS_UNIX_SIGNALS */ +} + +void +ACE_Sig_Set::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Sig_Set::dump"); +#endif /* ACE_HAS_DUMP */ +} + +ACE_ALLOC_HOOK_DEFINE(ACE_Sig_Guard) + +void +ACE_Sig_Guard::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Sig_Guard::dump"); +#endif /* ACE_HAS_DUMP */ +} + +ACE_Sig_Action::ACE_Sig_Action (void) +{ + // ACE_TRACE ("ACE_Sig_Action::ACE_Sig_Action"); + this->sa_.sa_flags = 0; + + // Since Service_Config::signal_handler_ is static and has an + // ACE_Sig_Action instance, Win32 will get errno set unless this is + // commented out. +#if !defined (ACE_WIN32) + ACE_OS::sigemptyset (&this->sa_.sa_mask); +#endif /* ACE_WIN32 */ + this->sa_.sa_handler = 0; +} + +ACE_Sig_Action::ACE_Sig_Action (ACE_SignalHandler sig_handler, + sigset_t *sig_mask, + int sig_flags) +{ + // ACE_TRACE ("ACE_Sig_Action::ACE_Sig_Action"); + this->sa_.sa_flags = sig_flags; + + if (sig_mask == 0) + ACE_OS::sigemptyset (&this->sa_.sa_mask); + else + this->sa_.sa_mask = *sig_mask; // Structure assignment... + +#if !defined(ACE_HAS_TANDEM_SIGNALS) + this->sa_.sa_handler = ACE_SignalHandlerV (sig_handler); +#else + this->sa_.sa_handler = (void (*)()) ACE_SignalHandlerV (sig_handler); +#endif /* !ACE_HAS_TANDEM_SIGNALS */ +} + +ACE_Sig_Action::ACE_Sig_Action (ACE_SignalHandler sig_handler, + const ACE_Sig_Set &sig_mask, + int sig_flags) +{ + // ACE_TRACE ("ACE_Sig_Action::ACE_Sig_Action"); + this->sa_.sa_flags = sig_flags; + + // Structure assignment... + this->sa_.sa_mask = sig_mask.sigset (); + +#if !defined(ACE_HAS_TANDEM_SIGNALS) + this->sa_.sa_handler = ACE_SignalHandlerV (sig_handler); +#else + this->sa_.sa_handler = (void (*)()) ACE_SignalHandlerV (sig_handler); +#endif /* !ACE_HAS_TANDEM_SIGNALS */ +} + +ACE_Sig_Action::ACE_Sig_Action (ACE_SignalHandler sig_handler, + int signum, + sigset_t *sig_mask, + int sig_flags) +{ + // ACE_TRACE ("ACE_Sig_Action::ACE_Sig_Action"); + this->sa_.sa_flags = sig_flags; + + if (sig_mask == 0) + ACE_OS::sigemptyset (&this->sa_.sa_mask); + else + this->sa_.sa_mask = *sig_mask; // Structure assignment... + +#if !defined(ACE_HAS_TANDEM_SIGNALS) + this->sa_.sa_handler = ACE_SignalHandlerV (sig_handler); +#else + this->sa_.sa_handler = (void (*)()) ACE_SignalHandlerV (sig_handler); +#endif /* !ACE_HAS_TANDEM_SIGNALS */ + ACE_OS::sigaction (signum, &this->sa_, 0); +} + +ACE_Sig_Action::ACE_Sig_Action (ACE_SignalHandler sig_handler, + int signum, + const ACE_Sig_Set &sig_mask, + int sig_flags) +{ + // ACE_TRACE ("ACE_Sig_Action::ACE_Sig_Action"); + this->sa_.sa_flags = sig_flags; + + // Structure assignment... + this->sa_.sa_mask = sig_mask.sigset (); + +#if !defined(ACE_HAS_TANDEM_SIGNALS) + this->sa_.sa_handler = ACE_SignalHandlerV (sig_handler); +#else + this->sa_.sa_handler = (void (*)()) ACE_SignalHandlerV (sig_handler); +#endif /* !ACE_HAS_TANDEM_SIGNALS */ + ACE_OS::sigaction (signum, &this->sa_, 0); +} + +ACE_Sig_Action::ACE_Sig_Action (const ACE_Sig_Set &signals, + ACE_SignalHandler sig_handler, + const ACE_Sig_Set &sig_mask, + int sig_flags) +{ + // ACE_TRACE ("ACE_Sig_Action::ACE_Sig_Action"); + this->sa_.sa_flags = sig_flags; + + // Structure assignment... + this->sa_.sa_mask = sig_mask.sigset (); + +#if !defined(ACE_HAS_TANDEM_SIGNALS) + this->sa_.sa_handler = ACE_SignalHandlerV (sig_handler); +#else + this->sa_.sa_handler = (void (*)()) ACE_SignalHandlerV (sig_handler); +#endif /* !ACE_HAS_TANDEM_SIGNALS */ + +#if (ACE_NSIG > 0) + for (int s = 1; s < ACE_NSIG; s++) + if ((signals.is_member (s)) == 1) + ACE_OS::sigaction (s, &this->sa_, 0); +#else /* ACE_NSIG <= 0 */ + ACE_UNUSED_ARG (signals); +#endif /* ACE_NSIG <= 0 */ +} + +ACE_Sig_Action::ACE_Sig_Action (const ACE_Sig_Set &signals, + ACE_SignalHandler sig_handler, + sigset_t *sig_mask, + int sig_flags) +{ + // ACE_TRACE ("ACE_Sig_Action::ACE_Sig_Action"); + this->sa_.sa_flags = sig_flags; + + if (sig_mask == 0) + ACE_OS::sigemptyset (&this->sa_.sa_mask); + else + this->sa_.sa_mask = *sig_mask; // Structure assignment... + +#if !defined(ACE_HAS_TANDEM_SIGNALS) + this->sa_.sa_handler = ACE_SignalHandlerV (sig_handler); +#else + this->sa_.sa_handler = (void (*)()) ACE_SignalHandlerV (sig_handler); +#endif /* !ACE_HAS_TANDEM_SIGNALS */ + +#if (ACE_NSIG > 0) + for (int s = 1; s < ACE_NSIG; s++) + if ((signals.is_member (s)) == 1) + ACE_OS::sigaction (s, &this->sa_, 0); +#else /* ACE_NSIG <= 0 */ + ACE_UNUSED_ARG (signals); +#endif /* ACE_NSIG <= 0 */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Signal.h b/dep/acelite/ace/Signal.h new file mode 100644 index 00000000000..736d62e5c08 --- /dev/null +++ b/dep/acelite/ace/Signal.h @@ -0,0 +1,267 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Signal.h + * + * $Id: Signal.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_SIGNAL_H +#define ACE_SIGNAL_H +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if defined (ACE_DONT_INCLUDE_ACE_SIGNAL_H) +# error ace/Signal.h was #included instead of signal.h by ace/OS_NS_signal.h: fix!!!! +#endif /* ACE_DONT_INCLUDE_ACE_SIGNAL_H */ + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/OS_NS_signal.h" + +// Type of the extended signal handler. +typedef void (*ACE_Sig_Handler_Ex) (int, siginfo_t *siginfo, ucontext_t *ucontext); + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Sig_Set + * + * @brief Provide a C++ wrapper for the C sigset_t interface. + * + * Handle signals via a more elegant C++ interface (e.g., + * doesn't require the use of global variables or global + * functions in an application). + */ +class ACE_Export ACE_Sig_Set +{ +public: + // = Initialization and termination methods. + /// Initialize with @a sigset. If @a sigset == 0 then fill + /// the set. + ACE_Sig_Set (sigset_t *sigset); + + /// Initialize with @a sigset. If @a sigset == 0 then fill + /// the set. + ACE_Sig_Set (ACE_Sig_Set *sigset); + + /// If @a fill == 0 then initialize the to be empty, else + /// full. + ACE_Sig_Set (int fill = 0); + + ~ACE_Sig_Set (void); + + /// Create a set that excludes all signals defined by the system. + int empty_set (void); + + /// Create a set that includes all signals defined by the system. + int fill_set (void); + + /// Adds the individual signal specified by @a signo to the set. + int sig_add (int signo); + + /// Deletes the individual signal specified by @a signo from the set. + int sig_del (int signo); + + /// Checks whether the signal specified by @a signo is in the set. + int is_member (int signo) const; + + /// Returns a pointer to the underlying @c sigset_t. + operator sigset_t *(); + + /// Returns a copy of the underlying @c sigset_t. + sigset_t sigset (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + /// Set of signals. + sigset_t sigset_; +}; + +/** + * @class ACE_Sig_Action + * + * @brief C++ wrapper facade for the @c sigaction struct. + */ +class ACE_Export ACE_Sig_Action +{ +public: + // = Initialization methods. + /// Default constructor. Initializes everything to 0. + ACE_Sig_Action (void); + + /// Assigns the various fields of a @c sigaction struct but doesn't + /// register for signal handling via the @c sigaction function. + ACE_Sig_Action (ACE_SignalHandler handler, + sigset_t *sigmask = 0, + int flags = 0); + + /// Assigns the various fields of a @c sigaction struct but doesn't + /// register for signal handling via the @c sigaction function. + ACE_Sig_Action (ACE_SignalHandler handler, + const ACE_Sig_Set &sigmask, + int flags = 0); + + /** + * Assigns the various fields of a @c sigaction struct and registers + * the @a handler to process signal @a signum via the @c sigaction + * function. + */ + ACE_Sig_Action (ACE_SignalHandler handler, + int signum, + sigset_t *sigmask = 0, + int flags = 0); + + /** + * Assigns the various fields of a @c sigaction struct and registers + * the @a handler to process signal @a signum via the @c sigaction + * function. + */ + ACE_Sig_Action (ACE_SignalHandler handler, + int signum, + const ACE_Sig_Set &sigmask, + int flags = 0); + + + // @@ The next two methods have a parameter as "signalss". Please do + // not change the argument name as "signals". This causes the + // following problem as reported by + // . + + // In the file Signal.h two of the functions have and argument name + // of signals. signals is a Qt macro (to do with their meta object + // stuff. + // We could as well have it as "signal", but I am nost sure whether + // that would cause a problem with something else - Bala + + /** + * Assigns the various fields of a @c sigaction struct and registers + * the @a handler to process all @a signalss via the @c sigaction + * function. + */ + ACE_Sig_Action (const ACE_Sig_Set &signalss, + ACE_SignalHandler handler, + const ACE_Sig_Set &sigmask, + int flags = 0); + + /** + * Assigns the various fields of a @c sigaction struct and registers + * the @a handler to process all @a signalss via the @c sigaction + * function. + */ + ACE_Sig_Action (const ACE_Sig_Set &signalss, + ACE_SignalHandler handler, + sigset_t *sigmask = 0, + int flags = 0); + + /// Copy constructor. + ACE_Sig_Action (const ACE_Sig_Action &s); + + /// Default dtor. + ~ACE_Sig_Action (void); + + // = Signal action management. + /// Register @c this as the current disposition and store old + /// disposition into @a oaction if it is non-NULL. + int register_action (int signum, + ACE_Sig_Action *oaction = 0); + + /// Assign the value of @a oaction to @c this and make it become the + /// new signal disposition. + int restore_action (int signum, + ACE_Sig_Action &oaction); + + /// Retrieve the current disposition into @c this. + int retrieve_action (int signum); + + /// Set current signal action. + void set (struct sigaction *); + + /// Get current signal action. + struct sigaction *get (void); + operator struct sigaction *(); + + /// Set current signal flags. + void flags (int); + + /// Get current signal flags. + int flags (void); + + /// Set current signal mask. + void mask (sigset_t *); + void mask (ACE_Sig_Set &); + + /// Get current signal mask. + sigset_t *mask (void); + + /// Set current signal handler (pointer to function). + void handler (ACE_SignalHandler); + + /// Get current signal handler (pointer to function). + ACE_SignalHandler handler (void); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + /// Controls signal behavior. + struct sigaction sa_; +}; + +/** + * @class ACE_Sig_Guard + * + * @brief Hold signals in MASK for duration of a C++ statement block. + * Note that a "0" for mask causes all signals to be held. + */ +class ACE_Export ACE_Sig_Guard +{ +public: + // = Initialization and termination methods. + /// This is kind of conditional Guard, needed when guard should be + /// activated only when a spcific condition met. When condition == + /// true (default), Guard is activated + ACE_Sig_Guard (ACE_Sig_Set *mask = 0, bool condition = true); + + /// Restore blocked signals. + ~ACE_Sig_Guard (void); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + /// Original signal mask. + ACE_Sig_Set omask_; + + /// Guard Condition + bool condition_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Signal.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_SIGNAL_HANDLER_H */ diff --git a/dep/acelite/ace/Signal.inl b/dep/acelite/ace/Signal.inl new file mode 100644 index 00000000000..858c33c26fb --- /dev/null +++ b/dep/acelite/ace/Signal.inl @@ -0,0 +1,265 @@ +// -*- C++ -*- +// +// $Id: Signal.inl 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/OS_NS_signal.h" +#include "ace/config-all.h" +#include "ace/Trace.h" +#include "ace/Object_Manager_Base.h" +#include "ace/OS_NS_Thread.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE +ACE_Sig_Set::ACE_Sig_Set (sigset_t *ss) + // : sigset_ () +{ + ACE_TRACE ("ACE_Sig_Set::ACE_Sig_Set"); + + if (ss == 0) + ACE_OS::sigfillset (&this->sigset_); + else + // Structure assignment. + this->sigset_ = *ss; +} + +ACE_INLINE +ACE_Sig_Set::ACE_Sig_Set (int fill) + // : sigset_ () +{ + ACE_TRACE ("ACE_Sig_Set::ACE_Sig_Set"); + + if (fill) + ACE_OS::sigfillset (&this->sigset_); + else + ACE_OS::sigemptyset (&this->sigset_); +} + +ACE_INLINE +ACE_Sig_Set::ACE_Sig_Set (ACE_Sig_Set *ss) + // : sigset_ () +{ + ACE_TRACE ("ACE_Sig_Set::ACE_Sig_Set"); + + if (ss == 0) + ACE_OS::sigfillset (&this->sigset_); + else + this->sigset_ = ss->sigset_; +} + +ACE_INLINE int +ACE_Sig_Set::empty_set (void) +{ + ACE_TRACE ("ACE_Sig_Set::empty_set"); + return ACE_OS::sigemptyset (&this->sigset_); +} + +ACE_INLINE int +ACE_Sig_Set::fill_set (void) +{ + ACE_TRACE ("ACE_Sig_Set::fill_set"); + return ACE_OS::sigfillset (&this->sigset_); +} + +ACE_INLINE int +ACE_Sig_Set::sig_add (int signo) +{ + ACE_TRACE ("ACE_Sig_Set::sig_add"); + return ACE_OS::sigaddset (&this->sigset_, signo); +} + +ACE_INLINE int +ACE_Sig_Set::sig_del (int signo) +{ + ACE_TRACE ("ACE_Sig_Set::sig_del"); + return ACE_OS::sigdelset (&this->sigset_, signo); +} + +ACE_INLINE int +ACE_Sig_Set::is_member (int signo) const +{ + ACE_TRACE ("ACE_Sig_Set::is_member"); + return ACE_OS::sigismember (const_cast (&this->sigset_), signo); +} + +ACE_INLINE +ACE_Sig_Set::operator sigset_t *(void) +{ + ACE_TRACE ("ACE_Sig_Set::operator sigset_t *"); + return &this->sigset_; +} + +ACE_INLINE sigset_t +ACE_Sig_Set::sigset (void) const +{ + ACE_TRACE ("ACE_Sig_Set::sigset"); + return this->sigset_; +} + +ACE_INLINE int +ACE_Sig_Action::flags (void) +{ + ACE_TRACE ("ACE_Sig_Action::flags"); + return this->sa_.sa_flags; +} + +ACE_INLINE void +ACE_Sig_Action::flags (int flags) +{ + ACE_TRACE ("ACE_Sig_Action::flags"); + this->sa_.sa_flags = flags; +} + +ACE_INLINE sigset_t * +ACE_Sig_Action::mask (void) +{ + ACE_TRACE ("ACE_Sig_Action::mask"); + return &this->sa_.sa_mask; +} + +ACE_INLINE void +ACE_Sig_Action::mask (sigset_t *ss) +{ + ACE_TRACE ("ACE_Sig_Action::mask"); + if (ss != 0) + this->sa_.sa_mask = *ss; // Structure assignment +} + +ACE_INLINE void +ACE_Sig_Action::mask (ACE_Sig_Set &ss) +{ + ACE_TRACE ("ACE_Sig_Action::mask"); + this->sa_.sa_mask = ss.sigset (); // Structure assignment +} + +ACE_INLINE ACE_SignalHandler +ACE_Sig_Action::handler (void) +{ + ACE_TRACE ("ACE_Sig_Action::handler"); + return ACE_SignalHandler (this->sa_.sa_handler); +} + +ACE_INLINE void +ACE_Sig_Action::handler (ACE_SignalHandler handler) +{ + ACE_TRACE ("ACE_Sig_Action::handler"); +#if !defined(ACE_HAS_TANDEM_SIGNALS) + this->sa_.sa_handler = ACE_SignalHandlerV (handler); +#else + this->sa_.sa_handler = (void (*)()) ACE_SignalHandlerV (handler); +#endif /* !ACE_HAS_TANDEM_SIGNALS */ +} + +#if 0 +ACE_INLINE ACE_SignalHandler +ACE_Sig_Action::sigaction (void) +{ + ACE_TRACE ("ACE_Sig_Action::sigaction"); + return ACE_SignalHandler (this->sa_.sa_sigaction); +} + +ACE_INLINE void +ACE_Sig_Action::sigaction (ACE_SignalHandler handler) +{ + ACE_TRACE ("ACE_Sig_Action::sigaction"); + this->sa_.sa_sigaction = (void (*)()) ACE_SignalHandlerV (handler); +} +#endif /* 0 */ + +ACE_INLINE void +ACE_Sig_Action::set (struct sigaction *sa) +{ + ACE_TRACE ("ACE_Sig_Action::set"); + this->sa_ = *sa; // Structure assignment. +} + +ACE_INLINE struct sigaction * +ACE_Sig_Action::get (void) +{ + ACE_TRACE ("ACE_Sig_Action::get"); + return &this->sa_; +} + +ACE_INLINE +ACE_Sig_Action::operator struct sigaction * () +{ + ACE_TRACE ("ACE_Sig_Action::operator struct sigaction *"); + return &this->sa_; +} + +ACE_INLINE +ACE_Sig_Action::ACE_Sig_Action (const ACE_Sig_Action &s) + // : sa_ () +{ + ACE_TRACE ("ACE_Sig_Action::ACE_Sig_Action"); + *this = s; // structure copy. +} + +ACE_INLINE int +ACE_Sig_Action::register_action (int signum, ACE_Sig_Action *oaction) +{ + ACE_TRACE ("ACE_Sig_Action::register_action"); + struct sigaction *sa = oaction == 0 ? 0 : oaction->get (); + + return ACE_OS::sigaction (signum, &this->sa_, sa); +} + +ACE_INLINE int +ACE_Sig_Action::retrieve_action (int signum) +{ + ACE_TRACE ("ACE_Sig_Action::retrieve_action"); + return ACE_OS::sigaction (signum, 0, &this->sa_); +} + +ACE_INLINE int +ACE_Sig_Action::restore_action (int signum, ACE_Sig_Action &oaction) +{ + ACE_TRACE ("ACE_Sig_Action::restore_action"); + this->sa_ = *oaction.get (); // Structure assignment + return ACE_OS::sigaction (signum, &this->sa_, 0); +} + +// Block out the signal MASK until the destructor is called. + +ACE_INLINE +ACE_Sig_Guard::ACE_Sig_Guard (ACE_Sig_Set *mask, + bool condition) + : omask_ () + , condition_ (condition) +{ + //ACE_TRACE ("ACE_Sig_Guard::ACE_Sig_Guard"); + if (!this->condition_) + return; + +#if defined (ACE_LACKS_UNIX_SIGNALS) + ACE_UNUSED_ARG (mask); +#else + // If MASK is 0 then block all signals! + if (mask == 0) + { +# if defined (ACE_LACKS_PTHREAD_THR_SIGSETMASK) + ACE_OS::sigprocmask (SIG_BLOCK, + ACE_OS_Object_Manager::default_mask (), + (sigset_t *) this->omask_); +# else + ACE_OS::thr_sigsetmask (SIG_BLOCK, + ACE_OS_Object_Manager::default_mask (), + (sigset_t *) this->omask_); +# endif /* ACE_LACKS_PTHREAD_THR_SIGSETMASK */ + } + else +# if defined (ACE_LACKS_PTHREAD_THR_SIGSETMASK) + ACE_OS::sigprocmask (SIG_BLOCK, + (sigset_t *) *mask, + (sigset_t *) + this->omask_); +# else + ACE_OS::thr_sigsetmask (SIG_BLOCK, + (sigset_t *) *mask, + (sigset_t *) + this->omask_); +# endif /* ACE_LACKS_PTHREAD_THR_SIGSETMASK */ +#endif /* ACE_LACKS_UNIX_SIGNALS */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Singleton.cpp b/dep/acelite/ace/Singleton.cpp new file mode 100644 index 00000000000..25b7983a2a6 --- /dev/null +++ b/dep/acelite/ace/Singleton.cpp @@ -0,0 +1,548 @@ +// $Id: Singleton.cpp 84273 2009-01-30 12:55:25Z johnnyw $ + +#ifndef ACE_SINGLETON_CPP +#define ACE_SINGLETON_CPP + +#include "ace/Singleton.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (__ACE_INLINE__) +#include "ace/Singleton.inl" +#endif /* __ACE_INLINE__ */ + +#include "ace/Object_Manager.h" +#include "ace/Log_Msg.h" +#include "ace/Framework_Component.h" +#include "ace/Guard_T.h" +#include "ace/os_include/os_typeinfo.h" + +ACE_RCSID (ace, + Singleton, + "$Id: Singleton.cpp 84273 2009-01-30 12:55:25Z johnnyw $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template void +ACE_Singleton::dump (void) +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Singleton::dump"); + +#if !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("instance_ = %x"), + ACE_Singleton::instance_i ())); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ +#endif /* ACE_HAS_DUMP */ +} + +template ACE_Singleton *& +ACE_Singleton::instance_i (void) +{ +#if defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) + // Pointer to the Singleton instance. This works around a bug with + // G++ and it's (mis-)handling of templates and statics... + static ACE_Singleton *singleton_ = 0; + + return singleton_; +#else + return ACE_Singleton::singleton_; +#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ +} + +template TYPE * +ACE_Singleton::instance (void) +{ + ACE_TRACE ("ACE_Singleton::instance"); + + ACE_Singleton *&singleton = + ACE_Singleton::instance_i (); + + // Perform the Double-Check pattern... + if (singleton == 0) + { + if (ACE_Object_Manager::starting_up () || + ACE_Object_Manager::shutting_down ()) + { + // The program is still starting up, and therefore assumed + // to be single threaded. There's no need to double-check. + // Or, the ACE_Object_Manager instance has been destroyed, + // so the preallocated lock is not available. Either way, + // don't register for destruction with the + // ACE_Object_Manager: we'll have to leak this instance. + + ACE_NEW_RETURN (singleton, (ACE_Singleton), 0); + } + else + { +#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) + // Obtain a lock from the ACE_Object_Manager. The pointer + // is static, so we only obtain one per ACE_Singleton + // instantiation. + static ACE_LOCK *lock = 0; + if (ACE_Object_Manager::get_singleton_lock (lock) != 0) + // Failed to acquire the lock! + return 0; + + ACE_GUARD_RETURN (ACE_LOCK, ace_mon, *lock, 0); + + if (singleton == 0) + { +#endif /* ACE_MT_SAFE */ + ACE_NEW_RETURN (singleton, (ACE_Singleton), 0); + + // Register for destruction with ACE_Object_Manager. + ACE_Object_Manager::at_exit (singleton, 0, typeid (TYPE).name ()); +#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) + } +#endif /* ACE_MT_SAFE */ + } + } + + return &singleton->instance_; +} + +template void +ACE_Singleton::cleanup (void *) +{ + ACE_Object_Manager::remove_at_exit (this); + delete this; + ACE_Singleton::instance_i () = 0; +} + +template void +ACE_Singleton::close (void) +{ + ACE_Singleton *&singleton = + ACE_Singleton::instance_i (); + + if (singleton) + { + singleton->cleanup (); + ACE_Singleton::instance_i () = 0; + } +} + +#if !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) +// Pointer to the Singleton instance. +template ACE_Singleton * +ACE_Singleton::singleton_ = 0; + +template ACE_Unmanaged_Singleton * +ACE_Unmanaged_Singleton::singleton_ = 0; +#endif /* !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) */ + +template void +ACE_Unmanaged_Singleton::dump (void) +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Unmanaged_Singleton::dump"); + +#if !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("instance_ = %x"), + ACE_Unmanaged_Singleton::instance_i ())); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ +#endif /* ACE_HAS_DUMP */ +} + +template +ACE_Unmanaged_Singleton *& +ACE_Unmanaged_Singleton::instance_i (void) +{ +#if defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) + // Pointer to the Singleton instance. This works around a bug with + // G++ and it's (mis-)handling of templates and statics... + static ACE_Unmanaged_Singleton *singleton_ = 0; + + return singleton_; +#else + return ACE_Unmanaged_Singleton::singleton_; +#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ +} + +template TYPE * +ACE_Unmanaged_Singleton::instance (void) +{ + ACE_TRACE ("ACE_Unmanaged_Singleton::instance"); + + ACE_Unmanaged_Singleton *&singleton = + ACE_Unmanaged_Singleton::instance_i (); + + // Perform the Double-Check pattern... + if (singleton == 0) + { + if (ACE_Object_Manager::starting_up () || + ACE_Object_Manager::shutting_down ()) + { + // The program is still starting up, and therefore assumed + // to be single threaded. There's no need to double-check. + // Or, the ACE_Object_Manager instance has been destroyed, + // so the preallocated lock is not available. Either way, + // don't register for destruction with the + // ACE_Object_Manager: we'll have to leak this instance. + + ACE_NEW_RETURN (singleton, (ACE_Unmanaged_Singleton), + 0); + } + else + { +#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) + // Obtain a lock from the ACE_Object_Manager. The pointer + // is static, so we only obtain one per + // ACE_Unmanaged_Singleton instantiation. + static ACE_LOCK *lock = 0; + if (ACE_Object_Manager::get_singleton_lock (lock) != 0) + // Failed to acquire the lock! + return 0; + + ACE_GUARD_RETURN (ACE_LOCK, ace_mon, *lock, 0); +#endif /* ACE_MT_SAFE */ + + if (singleton == 0) + ACE_NEW_RETURN (singleton, + (ACE_Unmanaged_Singleton), + 0); + } + } + + return &singleton->instance_; +} + +template void +ACE_Unmanaged_Singleton::close (void) +{ + ACE_Unmanaged_Singleton *&singleton = + ACE_Unmanaged_Singleton::instance_i (); + + if (singleton) + { + singleton->cleanup (); + ACE_Unmanaged_Singleton::instance_i () = 0; + } +} + +template void +ACE_TSS_Singleton::dump (void) +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_TSS_Singleton::dump"); + +#if !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("instance_ = %x"), + ACE_TSS_Singleton::instance_i ())); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ +#endif /* ACE_HAS_DUMP */ +} + +template ACE_TSS_Singleton *& +ACE_TSS_Singleton::instance_i (void) +{ +#if defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) + // Pointer to the Singleton instance. This works around a bug with + // G++ and it's (mis-)handling of templates and statics... + static ACE_TSS_Singleton *singleton_ = 0; + + return singleton_; +#else + return ACE_TSS_Singleton::singleton_; +#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ +} + +template TYPE * +ACE_TSS_Singleton::instance (void) +{ + ACE_TRACE ("ACE_TSS_Singleton::instance"); + + ACE_TSS_Singleton *&singleton = + ACE_TSS_Singleton::instance_i (); + + // Perform the Double-Check pattern... + if (singleton == 0) + { + if (ACE_Object_Manager::starting_up () || + ACE_Object_Manager::shutting_down ()) + { + // The program is still starting up, and therefore assumed + // to be single threaded. There's no need to double-check. + // Or, the ACE_Object_Manager instance has been destroyed, + // so the preallocated lock is not available. Either way, + // don't register for destruction with the + // ACE_Object_Manager: we'll have to leak this instance. + + ACE_NEW_RETURN (singleton, (ACE_TSS_Singleton), 0); + } + else + { +#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) + + // Obtain a lock from the ACE_Object_Manager. The pointer + // is static, so we only obtain one per ACE_Singleton instantiation. + static ACE_LOCK *lock = 0; + if (ACE_Object_Manager::get_singleton_lock (lock) != 0) + // Failed to acquire the lock! + return 0; + + ACE_GUARD_RETURN (ACE_LOCK, ace_mon, *lock, 0); + + if (singleton == 0) + { +#endif /* ACE_MT_SAFE */ + ACE_NEW_RETURN (singleton, (ACE_TSS_Singleton), + 0); + + // Register for destruction with ACE_Object_Manager. + ACE_Object_Manager::at_exit (singleton, 0, typeid (TYPE).name ()); +#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) + } +#endif /* ACE_MT_SAFE */ + } + } + + return ACE_TSS_GET (&singleton->instance_, TYPE); +} + +template void +ACE_TSS_Singleton::cleanup (void *) +{ + delete this; + ACE_TSS_Singleton::instance_i () = 0; +} + +template void +ACE_Unmanaged_TSS_Singleton::dump (void) +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Unmanaged_TSS_Singleton::dump"); + +#if !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("instance_ = %x"), + ACE_Unmanaged_TSS_Singleton::instance_i ())); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ +#endif /* ACE_HAS_DUMP */ +} + +template +ACE_Unmanaged_TSS_Singleton *& +ACE_Unmanaged_TSS_Singleton::instance_i (void) +{ +#if defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) + // Pointer to the Singleton instance. This works around a bug with + // G++ and it's (mis-)handling of templates and statics... + static ACE_Unmanaged_TSS_Singleton *singleton_ = 0; + + return singleton_; +#else + return ACE_Unmanaged_TSS_Singleton::singleton_; +#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ +} + +template TYPE * +ACE_Unmanaged_TSS_Singleton::instance (void) +{ + ACE_TRACE ("ACE_Unmanaged_TSS_Singleton::instance"); + + ACE_Unmanaged_TSS_Singleton *&singleton = + ACE_Unmanaged_TSS_Singleton::instance_i (); + + // Perform the Double-Check pattern... + if (singleton == 0) + { + if (ACE_Object_Manager::starting_up () || + ACE_Object_Manager::shutting_down ()) + { + // The program is still starting up, and therefore assumed + // to be single threaded. There's no need to double-check. + // Or, the ACE_Object_Manager instance has been destroyed, + // so the preallocated lock is not available. Either way, + // don't register for destruction with the + // ACE_Object_Manager: we'll have to leak this instance. + + ACE_NEW_RETURN (singleton, + (ACE_Unmanaged_TSS_Singleton), + 0); + } + else + { +#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) + // Obtain a lock from the ACE_Object_Manager. The pointer + // is static, so we only obtain one per + // ACE_Unmanaged_Singleton instantiation. + static ACE_LOCK *lock = 0; + if (ACE_Object_Manager::get_singleton_lock (lock) != 0) + // Failed to acquire the lock! + return 0; + + ACE_GUARD_RETURN (ACE_LOCK, ace_mon, *lock, 0); +#endif /* ACE_MT_SAFE */ + + if (singleton == 0) + ACE_NEW_RETURN (singleton, + (ACE_Unmanaged_TSS_Singleton), + 0); + } + } + + return ACE_TSS_GET (&singleton->instance_, TYPE); +} + +template void +ACE_Unmanaged_TSS_Singleton::close (void) +{ + ACE_Unmanaged_TSS_Singleton *&singleton = + ACE_Unmanaged_TSS_Singleton::instance_i (); + + if (singleton) + singleton->cleanup (); +} + +#if !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) +// Pointer to the Singleton instance. +template ACE_TSS_Singleton * +ACE_TSS_Singleton::singleton_ = 0; + +template +ACE_Unmanaged_TSS_Singleton * +ACE_Unmanaged_TSS_Singleton::singleton_ = 0; +#endif /* !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) */ + +/*************************************************************************/ + +#if !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) +// Pointer to the Singleton instance. +template ACE_DLL_Singleton_T * +ACE_DLL_Singleton_T::singleton_ = 0; +#endif /* !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) */ + +template void +ACE_DLL_Singleton_T::dump (void) +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_DLL_Singleton_T::dump"); + +#if !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("instance_ = %x"), + ACE_DLL_Singleton_T::instance_i ())); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ +#endif /* ACE_HAS_DUMP */ +} + +template +ACE_DLL_Singleton_T *& +ACE_DLL_Singleton_T::instance_i (void) +{ + ACE_TRACE ("ACE_DLL_Singleton_T::instance_i"); + +#if defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) + // Pointer to the Singleton instance. This works around a bug with + // G++ and it's (mis-)handling of templates and statics... + static ACE_DLL_Singleton_T *singleton_ = 0; + + return singleton_; +#else + return ACE_DLL_Singleton_T::singleton_; +#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ +} + +template TYPE * +ACE_DLL_Singleton_T::instance (void) +{ + ACE_TRACE ("ACE_DLL_Singleton_T::instance"); + + ACE_DLL_Singleton_T *&singleton = + ACE_DLL_Singleton_T::instance_i (); + + // Perform the Double-Check pattern... + if (singleton == 0) + { + if (ACE_Object_Manager::starting_up () || + ACE_Object_Manager::shutting_down ()) + { + // The program is still starting up, and therefore assumed + // to be single threaded. There's no need to double-check. + // Or, the ACE_Object_Manager instance has been destroyed, + // so the preallocated lock is not available. Either way, + // don't register for destruction with the + // ACE_Object_Manager: we'll have to leak this instance. + + ACE_NEW_RETURN (singleton, (ACE_DLL_Singleton_T), + 0); + } + else + { +#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) + // Obtain a lock from the ACE_Object_Manager. The pointer + // is static, so we only obtain one per + // ACE_Unmanaged_Singleton instantiation. + static ACE_LOCK *lock = 0; + if (ACE_Object_Manager::get_singleton_lock (lock) != 0) + // Failed to acquire the lock! + return 0; + + ACE_GUARD_RETURN (ACE_LOCK, ace_mon, *lock, 0); +#endif /* ACE_MT_SAFE */ + + if (singleton == 0) + ACE_NEW_RETURN (singleton, + (ACE_DLL_Singleton_T), + 0); + } + //ACE_REGISTER_FRAMEWORK_COMPONENT(ACE_DLL_Singleton, singleton); + ACE_Framework_Repository::instance ()->register_component + (new ACE_Framework_Component_T > (singleton)); + } + + return &singleton->instance_; +} + +template void +ACE_DLL_Singleton_T::close (void) +{ + ACE_TRACE ("ACE_DLL_Singleton_T::close"); + + ACE_DLL_Singleton_T *&singleton = + ACE_DLL_Singleton_T::instance_i (); + + delete singleton; + singleton = 0; +} + +template void +ACE_DLL_Singleton_T::close_singleton (void) +{ + ACE_TRACE ("ACE_DLL_Singleton_T::close_singleton"); + ACE_DLL_Singleton_T::close (); +} + +template const ACE_TCHAR * +ACE_DLL_Singleton_T::dll_name (void) +{ + return this->instance ()->dll_name (); +} + +template const ACE_TCHAR * +ACE_DLL_Singleton_T::name (void) +{ + return this->instance ()->name (); +} + + +/**********************************************************************/ + +template const ACE_TCHAR* +ACE_DLL_Singleton_Adapter_T::dll_name (void) +{ + // @todo make this a constant somewhere (or it there already is one + // then use it. + return ACE_TEXT("ACE"); +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_SINGLETON_CPP */ diff --git a/dep/acelite/ace/Singleton.h b/dep/acelite/ace/Singleton.h new file mode 100644 index 00000000000..308ddc3c245 --- /dev/null +++ b/dep/acelite/ace/Singleton.h @@ -0,0 +1,330 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Singleton.h + * + * $Id: Singleton.h 84273 2009-01-30 12:55:25Z johnnyw $ + * + * @brief + * + * @author Tim Harrison + * @author Douglas C. Schmidt + * @author Chris Lahey + * @author Rich Christy + * @author David Levine + */ +//============================================================================= + +#ifndef ACE_SINGLETON_H +#define ACE_SINGLETON_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" +#include "ace/TSS_T.h" +#include "ace/Cleanup.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Singleton + * + * @brief A Singleton Adapter uses the Adapter pattern to turn ordinary + * classes into Singletons optimized with the Double-Checked + * Locking optimization pattern. + * + * This implementation is a slight variation on the GoF + * Singleton pattern. In particular, a single + * > instance is allocated here, + * not a instance. The reason for this is to allow + * registration with the ACE_Object_Manager, so that the + * Singleton can be cleaned up when the process exits. For this + * scheme to work, a (static) cleanup() function must be + * provided. ACE_Singleton provides one so that TYPE doesn't + * need to. + * If you want to make sure that only the singleton instance of + * is created, and that users cannot create their own + * instances of , do the following to class : + * (a) Make the constructor of private (or protected) + * (b) Make Singleton a friend of + * Here is an example: + * @verbatim + * class foo + * { + * friend class ACE_Singleton; + * private: + * foo () { cout << "foo constructed" << endl; } + * ~foo () { cout << "foo destroyed" << endl; } + * }; + * typedef ACE_Singleton FOO; + * @endverbatim + * + * @note The best types to use for ACE_LOCK are + * ACE_Recursive_Thread_Mutex and ACE_Null_Mutex. + * ACE_Recursive_Thread_Mutex should be used in multi-threaded + * programs in which it is possible for more than one thread to + * access the > instance. + * ACE_Null_Mutex can be used otherwise. The reason that these + * types of locks are best has to do with their allocation by + * the ACE_Object_Manager. Single ACE_Recursive_Thread_Mutex + * and ACE_Null_Mutex instances are used for all ACE_Singleton + * instantiations. However, other types of locks are allocated + * per ACE_Singleton instantiation. + */ +template +class ACE_Singleton : public ACE_Cleanup +{ +public: + /// Global access point to the Singleton. + static TYPE *instance (void); + + /// Cleanup method, used by @c ace_cleanup_destroyer to destroy the + /// ACE_Singleton. + virtual void cleanup (void *param = 0); + + /// Explicitly delete the Singleton instance. + static void close (void); + + /// Dump the state of the object. + static void dump (void); + +protected: + /// Default constructor. + ACE_Singleton (void); + + /// Contained instance. + TYPE instance_; + +#if !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) + /// Pointer to the Singleton (ACE_Cleanup) instance. + static ACE_Singleton *singleton_; +#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ + + /// Get pointer to the Singleton instance. + static ACE_Singleton *&instance_i (void); +}; + +/** + * @class ACE_Unmanaged_Singleton + * + * @brief Same as ACE_Singleton, except does _not_ register with + * ACE_Object_Manager for destruction. + * + * This version of ACE_Singleton can be used if, for example, + * its DLL will be unloaded before the ACE_Object_Manager + * destroys the instance. Unlike with ACE_Singleton, the + * application is responsible for explicitly destroying the + * instance after it is no longer needed (if it wants to avoid + * memory leaks, at least). The close() static member function + * must be used to explicitly destroy the Singleton. + * Usage is the same as for ACE_Singleton, but note that if you + * you declare a friend, the friend class must still be an + * *ACE_Singleton*, not an ACE_Unmanaged_Singleton. + */ +template +class ACE_Unmanaged_Singleton : public ACE_Singleton +{ +public: + /// Global access point to the Singleton. + static TYPE *instance (void); + + /// Explicitly delete the Singleton instance. + static void close (void); + + /// Dump the state of the object. + static void dump (void); + +protected: + /// Default constructor. + ACE_Unmanaged_Singleton (void); + +#if !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) + /// Pointer to the Singleton (ACE_Cleanup) instance. + static ACE_Unmanaged_Singleton *singleton_; +#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ + + /// Get pointer to the Singleton instance. + static ACE_Unmanaged_Singleton *&instance_i (void); +}; + +/** + * @class ACE_TSS_Singleton + * + * @brief This class uses the Adapter pattern to turn ordinary classes + * into Thread-specific Singletons optimized with the + * Double-Checked Locking optimization pattern. + * + * This implementation is another variation on the GoF Singleton + * pattern. In this case, a single > instance is allocated here, not a instance. + * Each call to the static method returns a Singleton + * whose pointer resides in thread-specific storage. As with + * ACE_Singleton, we use the ACE_Object_Manager so that the + * Singleton can be cleaned up when the process exits. For this + * scheme to work, a (static) cleanup() function must be + * provided. ACE_Singleton provides one so that TYPE doesn't + * need to. + */ +template +class ACE_TSS_Singleton : public ACE_Cleanup +{ +public: + /// Global access point to the singleton. + static TYPE *instance (void); + + /// Cleanup method, used by to destroy the + /// singleton. + virtual void cleanup (void *param = 0); + + /// Dump the state of the object. + static void dump (void); + +protected: + /// Default constructor. + ACE_TSS_Singleton (void); + + /// Contained instance. + ACE_TSS_TYPE (TYPE) instance_; + + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_TSS_Singleton &)) + ACE_UNIMPLEMENTED_FUNC (ACE_TSS_Singleton (const ACE_TSS_Singleton &)) + +#if !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) + /// Pointer to the Singleton (ACE_Cleanup) instance. + static ACE_TSS_Singleton *singleton_; +#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ + + /// Get pointer to the TSS Singleton instance. + static ACE_TSS_Singleton *&instance_i (void); +}; + +/** + * @class ACE_Unmanaged_TSS_Singleton + * + * @brief Same as ACE_TSS_Singleton, except does _not_ register with + * ACE_Object_Manager for destruction. + * + * This version of ACE_TSS_Singleton can be used if, for example, its DLL will + * be unloaded before the ACE_Object_Manager destroys the instance. Unlike with + * ACE_Singleton, the application is responsible for explicitly destroying the + * instance after it is no longer needed (if it wants to avoid memory leaks, + * at least). The close() static member function must be used to explicitly + * destroy the Singleton. + */ +template +class ACE_Unmanaged_TSS_Singleton : public ACE_TSS_Singleton +{ +public: + /// Global access point to the singleton. + static TYPE *instance (void); + + /// Explicitly delete the singleton instance. + static void close (void); + + /// Dump the state of the object. + static void dump (void); + +protected: + /// Default constructor. + ACE_Unmanaged_TSS_Singleton (void); + +#if !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) + /// Pointer to the Singleton (ACE_Cleanup) instance. + static ACE_Unmanaged_TSS_Singleton *singleton_; +#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ + + /// Get pointer to the Singleton instance. + static ACE_Unmanaged_TSS_Singleton *&instance_i (void); +}; + +/** + * @class ACE_DLL_Singleton_T + * + * @brief Same as ACE_Singleton, except that it registers for + * destruction with the ACE_Framework_Repository instead of + * with the ACE_Object_Manager directly. + * + * This version of ACE_Singleton should be used for singletons + * that live in a dll loaded either directly by ACE_DLL or indirectly + * by the ACE Service Configuration framework. Whenever ACE_DLL is ready + * to actually unload the dll, ACE_DLL_Singleton based dlls associated + * with that dll will be destroyed first. In fact, any singleton can + * safely use ACE_DLL_Singleton, even those that don't live in dlls. In + * that case, the singleton will be destroyed at normal program shutdown. + * + * The only additional requirement is that the contained class + * export name() and dll_name() methods. See ACE_DLL_Singleton_Adapter_T + * below for a convenient example of how to satisfy this + * requirement for the dll_name(). + * + * Usage is the same as for ACE_Singleton, but note that if you + * you declare a friend, the friend class must still be an + * *ACE_Singleton*, not an ACE_Unmanaged_Singleton. + */ +template +class ACE_DLL_Singleton_T +{ +public: + //void cleanup (void *param = 0); + + /// Global access point to the Singleton. + static TYPE *instance (void); + + /// Explicitly delete the Singleton instance. + static void close (void); + + static void close_singleton (void); + + /// Dump the state of the object. + static void dump (void); + + const ACE_TCHAR *dll_name (void); + + const ACE_TCHAR *name (void); + +protected: + /// Default constructor. + ACE_DLL_Singleton_T (void); + + /// Destructor. + ~ACE_DLL_Singleton_T (void); + + /// Contained instance. + TYPE instance_; + +#if !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) + /// Pointer to the Singleton instance. + static ACE_DLL_Singleton_T *singleton_; +#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ + + /// Get pointer to the singleton instance. + static ACE_DLL_Singleton_T *&instance_i (void); +}; + +template +class ACE_DLL_Singleton_Adapter_T : public TYPE +{ +public: + const ACE_TCHAR *dll_name (void); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Singleton.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Singleton.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Singleton.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" +#endif /* ACE_SINGLETON_H */ diff --git a/dep/acelite/ace/Singleton.inl b/dep/acelite/ace/Singleton.inl new file mode 100644 index 00000000000..107a8b78c6d --- /dev/null +++ b/dep/acelite/ace/Singleton.inl @@ -0,0 +1,42 @@ +// -*- C++ -*- +// +// $Id: Singleton.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Default constructors. +// +// Note: don't explicitly initialize "instance_", because TYPE may not +// have a default constructor. Let the compiler figure it out . . . + +template ACE_INLINE +ACE_Singleton::ACE_Singleton (void) +{ +} + +template ACE_INLINE +ACE_Unmanaged_Singleton::ACE_Unmanaged_Singleton (void) +{ +} + +template ACE_INLINE +ACE_TSS_Singleton::ACE_TSS_Singleton (void) +{ +} + +template ACE_INLINE +ACE_Unmanaged_TSS_Singleton::ACE_Unmanaged_TSS_Singleton (void) +{ +} + +template ACE_INLINE +ACE_DLL_Singleton_T::ACE_DLL_Singleton_T (void) +{ +} + +template +ACE_DLL_Singleton_T::~ACE_DLL_Singleton_T (void) +{ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Sock_Connect.cpp b/dep/acelite/ace/Sock_Connect.cpp new file mode 100644 index 00000000000..dc4362e697e --- /dev/null +++ b/dep/acelite/ace/Sock_Connect.cpp @@ -0,0 +1,1594 @@ +// $Id: Sock_Connect.cpp 90399 2010-06-03 21:35:20Z mesnier_p $ + +#include "ace/Sock_Connect.h" +#include "ace/INET_Addr.h" +#include "ace/Log_Msg.h" +#include "ace/Handle_Set.h" +#include "ace/Auto_Ptr.h" +#include "ace/SString.h" +#include "ace/OS_Memory.h" +#include "ace/OS_NS_stdio.h" +#include "ace/ACE.h" + +#if defined (sparc) +# include "ace/OS_NS_fcntl.h" +#endif // sparc + +#include "ace/OS_NS_stdlib.h" +#include "ace/OS_NS_string.h" +#include "ace/OS_NS_sys_socket.h" +#include "ace/OS_NS_netdb.h" +#include "ace/OS_NS_unistd.h" +#include "ace/os_include/net/os_if.h" + +#if defined (ACE_HAS_IPV6) +# include "ace/Guard_T.h" +# include "ace/Recursive_Thread_Mutex.h" +# if defined (_AIX) +# include /**/ +# endif /* _AIX */ +#endif /* ACE_HAS_IPV6 */ + +# if defined (ACE_HAS_GETIFADDRS) +# if defined (ACE_VXWORKS) +# include /**/ +# else +# include /**/ +# endif /*ACE_VXWORKS */ +# endif /* ACE_HAS_GETIFADDRS */ + +#if defined (ACE_VXWORKS) && (ACE_VXWORKS < 0x600) +#include /**/ +#include /**/ +#if defined (ACE_HAS_IPV6) +#include /**/ +extern "C" { + extern struct in_ifaddr* in_ifaddr; + extern LIST_HEAD(in_ifaddrhashhead, in_ifaddr) *in_ifaddrhashtbl; +} +#endif /* ACE_HAS_IPV6 */ +#include "ace/OS_NS_stdio.h" +#endif /* ACE_VXWORKS < 0x600 */ + +#if defined (ACE_VXWORKS) && ((ACE_VXWORKS >= 0x630) && (ACE_VXWORKS <= 0x670)) && defined (__RTP__) && defined (ACE_HAS_IPV6) +const struct in6_addr in6addr_any = IN6ADDR_ANY_INIT; +const struct in6_addr in6addr_nodelocal_allnodes = IN6ADDR_NODELOCAL_ALLNODES_INIT; +const struct in6_addr in6addr_linklocal_allnodes = IN6ADDR_LINKLOCAL_ALLNODES_INIT; +const struct in6_addr in6addr_linklocal_allrouters = IN6ADDR_LINKLOCAL_ALLROUTERS_INIT; +#endif /* ACE_VXWORKS >= 0x630 && <= 0x670 && __RTP__ && ACE_HAS_IPV6 */ + +#if defined (ACE_HAS_WINCE) +#include /**/ +# if defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0) && (_WIN32_WCE < 0x600) && defined (ACE_HAS_IPV6) +# include /**/ +const struct in6_addr in6addr_any = IN6ADDR_ANY_INIT; +const struct in6_addr in6addr_loopback = IN6ADDR_LOOPBACK_INIT; +# endif +#endif // ACE_HAS_WINCE + +#if defined (ACE_WIN32) && defined (ACE_HAS_PHARLAP) +# include "ace/OS_NS_stdio.h" +#endif + +#if defined (ACE_HAS_IPV6) + +// These defines support a generic usage based on +// the various SIGCF*IF ioctl implementations + +# if defined (SIOCGLIFCONF) +# define SIOCGIFCONF_CMD SIOCGLIFCONF +# if defined (__hpux) +# define IFREQ if_laddrreq +# define IFCONF if_laddrconf +# define IFC_REQ iflc_req +# define IFC_LEN iflc_len +# define IFC_BUF iflc_buf +# define IFR_ADDR iflr_addr +# define IFR_NAME iflr_name +# define IFR_FLAGS iflr_flags +# undef SETFAMILY +# define SA_FAMILY sa_family +# else +# define IFREQ lifreq +# define IFCONF lifconf +# define IFC_REQ lifc_req +# define IFC_LEN lifc_len +# define IFC_BUF lifc_buf +# define IFR_ADDR lifr_addr +# define IFR_NAME lifr_name +# define IFR_FLAGS lifr_flags +# define SETFAMILY +# define IFC_FAMILY lifc_family +# define IFC_FLAGS lifc_flags +# define SA_FAMILY ss_family +# endif +# else +# define SIOCGIFCONF_CMD SIOCGIFCONF +# define IFREQ ifreq +# define IFCONF ifconf +# define IFC_REQ ifc_req +# define IFC_LEN ifc_len +# define IFC_BUF ifc_buf +# define IFR_ADDR ifr_addr +# define IFR_NAME ifr_name +# define IFR_FLAGS ifr_flags +# undef SETFAMILY +# define SA_FAMILY sa_family +# endif /* SIOCGLIFCONF */ + +# if defined (ACE_HAS_THREADS) +# include "ace/Object_Manager.h" +# endif /* ACE_HAS_THREADS */ + +namespace +{ + // private: + // Used internally so not exported. + + // Does this box have ipv4 turned on? + int ace_ipv4_enabled = -1; + + // Does this box have ipv6 turned on? + int ace_ipv6_enabled = -1; + +} +#else /* ACE_HAS_IPV6 */ +# define SIOCGIFCONF_CMD SIOCGIFCONF +# define IFREQ ifreq +# define IFCONF ifconf +# define IFC_REQ ifc_req +# define IFC_LEN ifc_len +# define IFC_BUF ifc_buf +# define IFR_ADDR ifr_addr +# define IFR_NAME ifr_name +# define IFR_FLAGS ifr_flags +# undef SETFAMILY +# define SA_FAMILY sa_family +#endif /* ACE_HAS_IPV6 */ + +// This is a hack to work around a problem with Visual Age C++ 5 and 6 on AIX. +// Without this, the compiler auto-instantiates the ACE_Auto_Array_Ptr for +// ifreq (contained in this module) but only adds the #include for +// and not the one for which is also needed. Although we +// don't need the template defined here, it makes the compiler pull in +// and the build runs clean. +#if defined (AIX) && defined (__IBMCPP__) && (__IBMCPP__ >= 500) && (__IBMCPP__ < 700) +static ACE_Auto_Array_Ptr force_compiler_to_include_socket_h; +#endif /* AIX && __IBMCPP__ >= 500 */ + + +ACE_RCSID (ace, + Sock_Connect, + "$Id: Sock_Connect.cpp 90399 2010-06-03 21:35:20Z mesnier_p $") + + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Bind socket to an unused port. + +int +ACE::bind_port (ACE_HANDLE handle, ACE_UINT32 ip_addr, int address_family) +{ + ACE_TRACE ("ACE::bind_port"); + + ACE_INET_Addr addr; + +#if defined (ACE_HAS_IPV6) + if (address_family != PF_INET6) + // What do we do if it is PF_"INET6? Since it's 4 bytes, it must be an + // IPV4 address. Is there a difference? Why is this test done? dhinton +#else /* ACE_HAS_IPV6 */ + ACE_UNUSED_ARG (address_family); +#endif /* !ACE_HAS_IPV6 */ + addr = ACE_INET_Addr ((u_short)0, ip_addr); +#if defined (ACE_HAS_IPV6) + else if (ip_addr != INADDR_ANY) + // address_family == PF_INET6 and a non default IP address means to bind + // to the IPv4-mapped IPv6 address + addr.set ((u_short)0, ip_addr, 1, 1); +#endif /* ACE_HAS_IPV6 */ + + // The OS kernel should select a free port for us. + return ACE_OS::bind (handle, + (sockaddr*)addr.get_addr(), + addr.get_size()); +} + +int +ACE::get_bcast_addr (ACE_UINT32 &bcast_addr, + const ACE_TCHAR *host_name, + ACE_UINT32 host_addr, + ACE_HANDLE handle) +{ + ACE_TRACE ("ACE::get_bcast_addr"); + +#if defined (ACE_LACKS_GET_BCAST_ADDR) + ACE_UNUSED_ARG (bcast_addr); + ACE_UNUSED_ARG (host_name); + ACE_UNUSED_ARG (host_addr); + ACE_UNUSED_ARG (handle); + ACE_NOTSUP_RETURN (-1); +#elif !defined(ACE_WIN32) && !defined(__INTERIX) + ACE_HANDLE s = handle; + + if (s == ACE_INVALID_HANDLE) + s = ACE_OS::socket (AF_INET, SOCK_STREAM, 0); + + if (s == ACE_INVALID_HANDLE) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_OS::socket")), + -1); + + struct ifconf ifc; + char buf[BUFSIZ]; + + ifc.ifc_len = sizeof buf; + ifc.ifc_buf = buf; + + // Get interface structure and initialize the addresses using UNIX + // techniques + if (ACE_OS::ioctl (s, SIOCGIFCONF_CMD, (char *) &ifc) == -1) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE::get_bcast_addr:") + ACE_TEXT ("ioctl (get interface configuration)")), + -1); + + struct ifreq *ifr = ifc.ifc_req; + + struct sockaddr_in ip_addr; + + // Get host ip address if necessary. + if (host_name) + { + hostent *hp = ACE_OS::gethostbyname (ACE_TEXT_ALWAYS_CHAR (host_name)); + + if (hp == 0) + return -1; + else +#if !defined(_UNICOS) + ACE_OS::memcpy ((char *) &ip_addr.sin_addr.s_addr, + (char *) hp->h_addr, + hp->h_length); +#else /* _UNICOS */ + { + ACE_UINT64 haddr; // a place to put the address + char * haddrp = (char *) &haddr; // convert to char pointer + ACE_OS::memcpy(haddrp,(char *) hp->h_addr,hp->h_length); + ip_addr.sin_addr.s_addr = haddr; + } +#endif /* ! _UNICOS */ + } + else + { + ACE_OS::memset ((void *) &ip_addr, 0, sizeof ip_addr); +#if !defined(_UNICOS) + ACE_OS::memcpy ((void *) &ip_addr.sin_addr, + (void*) &host_addr, + sizeof ip_addr.sin_addr); +#else /* _UNICOS */ + ip_addr.sin_addr.s_addr = host_addr; // just copy to the bitfield +#endif /* ! _UNICOS */ + } + +#if !defined(AIX) && !defined (__QNX__) && !defined (__FreeBSD__) && !defined(__NetBSD__) && !defined (__Lynx__) + for (int n = ifc.ifc_len / sizeof (struct ifreq) ; n > 0; + n--, ifr++) +#else + // see mk_broadcast@SOCK_Dgram_Bcast.cpp + for (int nbytes = ifc.ifc_len; nbytes >= (int) sizeof (struct ifreq) && + ((ifr->ifr_addr.sa_len > sizeof (struct sockaddr)) ? + (nbytes >= (int) sizeof (ifr->ifr_name) + ifr->ifr_addr.sa_len) : 1); + ((ifr->ifr_addr.sa_len > sizeof (struct sockaddr)) ? + (nbytes -= sizeof (ifr->ifr_name) + ifr->ifr_addr.sa_len, + ifr = (struct ifreq *) + ((caddr_t) &ifr->ifr_addr + ifr->ifr_addr.sa_len)) : + (nbytes -= sizeof (struct ifreq), ifr++))) +#endif /* !defined(AIX) && !defined (__QNX__) && !defined (__FreeBSD__) && !defined(__NetBSD__) && !defined (__Lynx__) */ + { + struct sockaddr_in if_addr; + + // Compare host ip address with interface ip address. + ACE_OS::memcpy (&if_addr, + &ifr->ifr_addr, + sizeof if_addr); + + if (ip_addr.sin_addr.s_addr != if_addr.sin_addr.s_addr) + continue; + + if (ifr->ifr_addr.sa_family != AF_INET) + { + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE::get_bcast_addr:") + ACE_TEXT ("Not AF_INET"))); + continue; + } + + struct ifreq flags = *ifr; + struct ifreq if_req = *ifr; + + if (ACE_OS::ioctl (s, SIOCGIFFLAGS, (char *) &flags) == -1) + { + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE::get_bcast_addr:") + ACE_TEXT (" ioctl (get interface flags)"))); + continue; + } + + if (ACE_BIT_DISABLED (flags.ifr_flags, IFF_UP)) + { + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE::get_bcast_addr:") + ACE_TEXT ("Network interface is not up"))); + continue; + } + + if (ACE_BIT_ENABLED (flags.ifr_flags, IFF_LOOPBACK)) + continue; + + if (ACE_BIT_ENABLED (flags.ifr_flags, IFF_BROADCAST)) + { + if (ACE_OS::ioctl (s, + SIOCGIFBRDADDR, + (char *) &if_req) == -1) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE::get_bcast_addr:") + ACE_TEXT ("ioctl (get broadaddr)"))); + else + { + ACE_OS::memcpy (&ip_addr, + &if_req.ifr_broadaddr, + sizeof if_req.ifr_broadaddr); + + ACE_OS::memcpy ((void *) &host_addr, + (void *) &ip_addr.sin_addr, + sizeof host_addr); + + if (handle == ACE_INVALID_HANDLE) + ACE_OS::close (s); + + bcast_addr = host_addr; + return 0; + } + } + else + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE::get_bcast_addr:") + ACE_TEXT ("Broadcast is not enable for this interface."))); + + if (handle == ACE_INVALID_HANDLE) + ACE_OS::close (s); + + bcast_addr = host_addr; + return 0; + } + + return 0; +#else + ACE_UNUSED_ARG (handle); + ACE_UNUSED_ARG (host_addr); + ACE_UNUSED_ARG (host_name); + bcast_addr = (ACE_UINT32 (INADDR_BROADCAST)); + return 0; +#endif /* !ACE_WIN32 && !__INTERIX */ +} + +int +ACE::get_fqdn (ACE_INET_Addr const & addr, + char hostname[], + size_t len) +{ + int h_error; // Not the same as errno! + hostent hentry; + ACE_HOSTENT_DATA buf; + + char * ip_addr = 0; + int ip_addr_size = 0; + if (addr.get_type () == AF_INET) + { + sockaddr_in * const sock_addr = + reinterpret_cast (addr.get_addr ()); + ip_addr_size = sizeof sock_addr->sin_addr; + ip_addr = (char*) &sock_addr->sin_addr; + } +#ifdef ACE_HAS_IPV6 + else + { + sockaddr_in6 * sock_addr = + reinterpret_cast (addr.get_addr ()); + + ip_addr_size = sizeof sock_addr->sin6_addr; + ip_addr = (char*) &sock_addr->sin6_addr; + } +#endif /* ACE_HAS_IPV6 */ + + // get the host entry for the address in question + hostent * const hp = ACE_OS::gethostbyaddr_r (ip_addr, + ip_addr_size, + addr.get_type (), + &hentry, + buf, + &h_error); + + // if it's not found in the host file or the DNS datase, there is nothing + // much we can do. embed the IP address + if (hp == 0 || hp->h_name == 0) + return -1; + + if (ACE::debug()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("(%P|%t) - ACE::get_fqdn, ") + ACE_TEXT ("canonical host name is %C\n"), + hp->h_name)); + + // check if the canonical name is the FQDN + if (!ACE_OS::strchr(hp->h_name, '.')) + { + // list of address + char** p; + // list of aliases + char** q; + + // for every address and for every alias within the address, check and + // see if we can locate a FQDN + for (p = hp->h_addr_list; *p != 0; ++p) + { + for (q = hp->h_aliases; *q != 0; ++q) + { + if (ACE_OS::strchr(*q, '.')) + { + // we got an FQDN from an alias. use this + if (ACE_OS::strlen (*q) >= len) + // the hostname is too huge to fit into a + // buffer of size MAXHOSTNAMELEN + // should we check other aliases as well + // before bailing out prematurely? + // for right now, let's do it. this (short name) + // is atleast better than embedding the IP + // address in the profile + continue; + + if (ACE::debug ()) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("(%P|%t) - ACE::get_fqdn, ") + ACE_TEXT ("found fqdn within alias as %C\n"), + *q)); + ACE_OS::strcpy (hostname, *q); + + return 0; + } + } + } + } + + // The canonical name may be an FQDN when we reach here. + // Alternatively, the canonical name (a non FQDN) may be the best + // we can do. + if (ACE_OS::strlen (hp->h_name) >= len) + { + // The hostname is too large to fit into a buffer of size + // MAXHOSTNAMELEN. + return -2; + } + else + { + ACE_OS::strcpy (hostname, hp->h_name); + } + + return 0; +} + +#if defined (ACE_WIN32) + +static int +get_ip_interfaces_win32 (size_t &count, + ACE_INET_Addr *&addrs) +{ +# if defined (ACE_HAS_WINCE) && defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0) + // moved the ACE_HAS_WINCE impl ahaid of ACE_HAS_WINSOCK2 because + // WINCE in fact has winsock2, but doesn't properly support the + // WSAIoctl for obtaining IPv6 address info. + PIP_ADAPTER_ADDRESSES AdapterAddresses = 0; + ULONG OutBufferLength = 0; + ULONG RetVal = 0; + unsigned char *octet_buffer = 0; + + RetVal = + GetAdaptersAddresses(AF_UNSPEC, + 0, + 0, + AdapterAddresses, + &OutBufferLength); + + if (RetVal != ERROR_BUFFER_OVERFLOW) + { + return -1; + } + + ACE_NEW_RETURN (octet_buffer, unsigned char[OutBufferLength],-1); + AdapterAddresses = (IP_ADAPTER_ADDRESSES *)octet_buffer; + + RetVal = + GetAdaptersAddresses(AF_UNSPEC, + 0, + 0, + AdapterAddresses, + &OutBufferLength); + + if (RetVal != NO_ERROR) + { + delete [] octet_buffer; + return -1; + } + + // If successful, output some information from the data we received + PIP_ADAPTER_ADDRESSES AdapterList = AdapterAddresses; + while (AdapterList) + { + if (AdapterList->OperStatus == IfOperStatusUp) + { + if (AdapterList->IfIndex != 0) + ++count; + if (AdapterList->Ipv6IfIndex != 0) + ++count; + } + AdapterList = AdapterList->Next; + } + + AdapterList = AdapterAddresses; + + ACE_NEW_RETURN (addrs, ACE_INET_Addr[count],-1); + count = 0; + for (AdapterList = AdapterAddresses; + AdapterList != 0; + AdapterList = AdapterList->Next) + { + if (AdapterList->OperStatus != IfOperStatusUp) + continue; + + IP_ADAPTER_UNICAST_ADDRESS *uni = 0; + if (AdapterList->IfIndex != 0) + for (uni = AdapterList->FirstUnicastAddress; + uni != 0; + uni = uni->Next) + { + SOCKET_ADDRESS *sa_addr = &uni->Address; + if (sa_addr->lpSockaddr->sa_family == AF_INET) + { + sockaddr_in *sin = (sockaddr_in*)sa_addr->lpSockaddr; + addrs[count].set(sin,sa_addr->iSockaddrLength); + ++count; + break; + } + } + if (AdapterList->Ipv6IfIndex != 0) + { + for (uni = AdapterList->FirstUnicastAddress; + uni != 0; + uni = uni->Next) + { + SOCKET_ADDRESS *sa_addr = &uni->Address; + if (sa_addr->lpSockaddr->sa_family == AF_INET6) + { + sockaddr_in *sin = (sockaddr_in*)sa_addr->lpSockaddr; + addrs[count].set(sin,sa_addr->iSockaddrLength); + ++count; + break; + } + } + } + } + + delete [] octet_buffer; + return 0; + +# elif defined (ACE_HAS_PHARLAP) + // PharLap ETS has its own kernel routines to rummage through the device + // configs and extract the interface info, but only for Pharlap RT. +# if !defined (ACE_HAS_PHARLAP_RT) + ACE_NOTSUP_RETURN (-1); +# endif /* ACE_HAS_PHARLAP_RT */ + + // Locate all of the IP devices in the system, saving a DEVHANDLE + // for each. Then allocate the ACE_INET_Addrs needed and fetch all + // the IP addresses. To locate the devices, try the available + // device name roots and increment the device number until the + // kernel says there are no more of that type. + const size_t ACE_MAX_ETS_DEVICES = 64; // Arbitrary, but should be enough. + DEVHANDLE ip_dev[ACE_MAX_ETS_DEVICES]; + EK_TCPIPCFG *devp = 0; + size_t i, j; + ACE_TCHAR dev_name[16]; + + count = 0; + for (i = 0; count < ACE_MAX_ETS_DEVICES; i++, ++count) + { + // Ethernet. + ACE_OS::sprintf (dev_name, + "ether%d", + i); + ip_dev[count] = EtsTCPGetDeviceHandle (dev_name); + if (ip_dev[count] == 0) + break; + } + for (i = 0; count < ACE_MAX_ETS_DEVICES; i++, ++count) + { + // SLIP. + ACE_OS::sprintf (dev_name, + "sl%d", + i); + ip_dev[count] = EtsTCPGetDeviceHandle (dev_name); + if (ip_dev[count] == 0) + break; + } + for (i = 0; count < ACE_MAX_ETS_DEVICES; i++, ++count) + { + // PPP. + ACE_OS::sprintf (dev_name, + "ppp%d", + i); + ip_dev[count] = EtsTCPGetDeviceHandle (dev_name); + if (ip_dev[count] == 0) + break; + } + + if (count > 0) + ACE_NEW_RETURN (addrs, + ACE_INET_Addr[count], + -1); + else + addrs = 0; + + for (i = 0, j = 0; i < count; i++) + { + devp = EtsTCPGetDeviceCfg (ip_dev[i]); + if (devp != 0) + { + addrs[j].set (0, + devp->nwIPAddress, + 0); // Already in net order. + ++j; + } + // There's no call to close the DEVHANDLE. + } + + count = j; + if (count == 0 && addrs != 0) + { + delete [] addrs; + addrs = 0; + } + + return 0; + + +# else + // All non-CE, non-Pharlap Windows. Must support Winsock2. + + int i, n_interfaces, status; + + INTERFACE_INFO info[64]; + SOCKET sock; + + // Get an (overlapped) DGRAM socket to test with + sock = socket (AF_INET, SOCK_DGRAM, 0); + if (sock == INVALID_SOCKET) + return -1; + + DWORD bytes; + status = WSAIoctl(sock, + SIO_GET_INTERFACE_LIST, + 0, + 0, + info, + sizeof(info), + &bytes, + 0, + 0); + closesocket (sock); + if (status == SOCKET_ERROR) + return -1; + + n_interfaces = bytes / sizeof(INTERFACE_INFO); + + // SIO_GET_INTERFACE_LIST does not work for IPv6 + // Instead recent versions of Winsock2 add the new opcode + // SIO_ADDRESS_LIST_QUERY. + // If this is not available forget about IPv6 local interfaces:-/ + int n_v6_interfaces = 0; + +# if defined (ACE_HAS_IPV6) && defined (SIO_ADDRESS_LIST_QUERY) + + LPSOCKET_ADDRESS_LIST v6info; + char *buffer; + DWORD buflen = sizeof (SOCKET_ADDRESS_LIST) + (63 * sizeof (SOCKET_ADDRESS)); + ACE_NEW_RETURN (buffer, + char[buflen], + -1); + v6info = reinterpret_cast (buffer); + + // Get an (overlapped) DGRAM socket to test with. + // If it fails only return IPv4 interfaces. + sock = socket (AF_INET6, SOCK_DGRAM, IPPROTO_UDP); + if (sock != INVALID_SOCKET) + { + status = WSAIoctl(sock, + SIO_ADDRESS_LIST_QUERY, + 0, + 0, + v6info, + buflen, + &bytes, + 0, + 0); + closesocket (sock); + if (status != SOCKET_ERROR) + n_v6_interfaces = v6info->iAddressCount; + } +# endif /* ACE_HAS_IPV6 */ + + ACE_NEW_RETURN (addrs, + ACE_INET_Addr[n_interfaces + n_v6_interfaces], + -1); + + // Now go through the list and transfer the good ones to the list of + // because they're down or don't have an IP address. + for (count = 0, i = 0; i < n_interfaces; ++i) + { + LPINTERFACE_INFO lpii; + struct sockaddr_in *addrp = 0; + + lpii = &info[i]; + if (!(lpii->iiFlags & IFF_UP)) + continue; + + // We assume IPv4 addresses here + addrp = reinterpret_cast (&lpii->iiAddress.AddressIn); + if (addrp->sin_addr.s_addr == INADDR_ANY) + continue; + + // Set the address for the caller. + addrs[count].set(addrp, sizeof(sockaddr_in)); + ++count; + } + +# if defined (ACE_HAS_IPV6) && defined (SIO_ADDRESS_LIST_QUERY) + // Now go through the list and transfer the good ones to the list of + // because they're down or don't have an IP address. + for (i = 0; i < n_v6_interfaces; i++) + { + struct sockaddr_in6 *addr6p; + + if (v6info->Address[i].lpSockaddr->sa_family != AF_INET6) + continue; + + addr6p = reinterpret_cast (v6info->Address[i].lpSockaddr); + if (IN6_IS_ADDR_UNSPECIFIED(&addr6p->sin6_addr)) // IN6ADDR_ANY? + continue; + + // Set the address for the caller. + addrs[count].set(reinterpret_cast (addr6p), sizeof(sockaddr_in6)); + ++count; + } + + delete [] buffer; // Clean up +# endif /* ACE_HAS_IPV6 */ + + if (count == 0) + { + delete [] addrs; + addrs = 0; + } + + return 0; + +# endif /* ACE_HAS_WINCE */ +} +#elif defined (ACE_HAS_GETIFADDRS) +static int +get_ip_interfaces_getifaddrs (size_t &count, + ACE_INET_Addr *&addrs) +{ + // Take advantage of the BSD getifaddrs function that simplifies + // access to connected interfaces. + struct ifaddrs *ifap = 0; + struct ifaddrs *p_if = 0; + + if (::getifaddrs (&ifap) != 0) + return -1; + + // Count number of interfaces. + size_t num_ifs = 0; + for (p_if = ifap; p_if != 0; p_if = p_if->ifa_next) + ++num_ifs; + + // Now create and initialize output array. + ACE_NEW_RETURN (addrs, + ACE_INET_Addr[num_ifs], + -1); // caller must free + + // Pull the address out of each INET interface. Not every interface + // is for IP, so be careful to count properly. When setting the + // INET_Addr, note that the 3rd arg (0) says to leave the byte order + // (already in net byte order from the interface structure) as is. + count = 0; + + for (p_if = ifap; + p_if != 0; + p_if = p_if->ifa_next) + { + if (p_if->ifa_addr && + p_if->ifa_addr->sa_family == AF_INET) + { + struct sockaddr_in *addr = + reinterpret_cast (p_if->ifa_addr); + + // Sometimes the kernel returns 0.0.0.0 as the interface + // address, skip those... + if (addr->sin_addr.s_addr != INADDR_ANY) + { + addrs[count].set ((u_short) 0, + addr->sin_addr.s_addr, + 0); + ++count; + } + } +# if defined (ACE_HAS_IPV6) + else if (p_if->ifa_addr && + p_if->ifa_addr->sa_family == AF_INET6) + { + struct sockaddr_in6 *addr = + reinterpret_cast (p_if->ifa_addr); + + // Skip the ANY address + if (!IN6_IS_ADDR_UNSPECIFIED(&addr->sin6_addr)) + { + addrs[count].set(reinterpret_cast (addr), + sizeof(sockaddr_in6)); + ++count; + } + } +# endif /* ACE_HAS_IPV6 */ + } + + ::freeifaddrs (ifap); + + return 0; +} +#elif defined (__hpux) +static int +get_ip_interfaces_hpux (size_t &count, + ACE_INET_Addr *&addrs) +{ + size_t num_ifs = 0; + size_t num_ifs_found = 0; + + // Call specific routine as necessary. + ACE_HANDLE handle = ACE_OS::socket (PF_INET, SOCK_DGRAM, 0); + ACE_HANDLE handle_ipv6 = ACE_INVALID_HANDLE; + + if (handle == ACE_INVALID_HANDLE) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE::get_ip_interfaces:open")), + -1); + + int result = 0; + int tmp_how_many = 0; + + result = ACE_OS::ioctl (handle, + SIOCGIFNUM, + (caddr_t) &tmp_how_many); + if (result != -1) + num_ifs = (size_t)tmp_how_many; + +# if defined (ACE_HAS_IPV6) + tmp_how_many = 0; + handle_ipv6 = ACE_OS::socket (PF_INET6, SOCK_DGRAM, 0); + result = ACE_OS::ioctl (handle_ipv6, + SIOCGLIFNUM, + (caddr_t) &tmp_how_many); + if (result != -1) + num_ifs += (size_t)tmp_how_many; +# endif + + if (num_ifs == 0) + { + ACE_OS::close (handle); + ACE_OS::close (handle_ipv6); + return -1; + } + + // ioctl likes to have an extra IFREQ structure to mark the end of + // what it returned, so increase the num_ifs by one. + ++num_ifs; + + //HPUX requires two passes, First for IPv4, then for IPv6 + + struct ifreq *ifs = 0; + ACE_NEW_RETURN (ifs, + struct ifreq[num_ifs], + -1); + ACE_OS::memset (ifs, 0, num_ifs * sizeof (struct ifreq)); + + ACE_Auto_Array_Ptr p_ifs (ifs); + + if (p_ifs.get() == 0) + { + ACE_OS::close (handle); + ACE_OS::close (handle_ipv6); + errno = ENOMEM; + return -1; + } + + struct ifconf ifcfg; + ACE_OS::memset (&ifcfg, 0, sizeof (struct ifconf)); + + ifcfg.ifc_req = p_ifs.get (); + ifcfg.ifc_len = num_ifs * sizeof (struct ifreq); + + if (ACE_OS::ioctl (handle, + SIOCGIFCONF, + (char *) &ifcfg) == -1) + { + ACE_OS::close (handle); + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE::get_ip_interfaces:") + ACE_TEXT ("ioctl - SIOCGIFCONF failed")), + -1); + } + + ACE_OS::close (handle); + + // Now create and initialize output array. + + ACE_NEW_RETURN (addrs, + ACE_INET_Addr[num_ifs], + -1); // caller must free + + struct ifreq *pcur = p_ifs.get (); + num_ifs_found = ifcfg.ifc_len / sizeof (struct ifreq); // get the number of returned ifs + + for (size_t i = 0; + i < num_ifs_found; + i++) + { + struct sockaddr_in *addr = + reinterpret_cast (&pcur->ifr_addr); + if (addr->sin_addr.s_addr != 0) + { + addrs[count].set ((u_short) 0, + addr->sin_addr.s_addr, + 0); + ++count; + } + ++pcur; + } + +# if defined (ACE_HAS_IPV6) + + if (handle_ipv6 != ACE_INVALID_HANDLE) + { + struct if_laddrreq *lifs = 0; + ACE_NEW_RETURN (lifs, + struct if_laddrreq[num_ifs], + -1); + ACE_OS::memset (lifs, 0, num_ifs * sizeof (struct if_laddrreq)); + + ACE_Auto_Array_Ptr p_lifs (lifs); + + if (p_lifs.get() == 0) + { + ACE_OS::close (handle); + ACE_OS::close (handle_ipv6); + errno = ENOMEM; + return -1; + } + + struct if_laddrconf lifcfg; + ACE_OS::memset (&lifcfg, 0, sizeof (struct if_laddrconf)); + + lifcfg.iflc_req = p_lifs.get (); + lifcfg.iflc_len = num_ifs * sizeof (struct if_laddrreq); + + if (ACE_OS::ioctl (handle_ipv6, + SIOCGLIFCONF, + (char *) &lifcfg) == -1) + { + ACE_OS::close (handle); + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE::get_ip_interfaces:") + ACE_TEXT ("ioctl - SIOCGLIFCONF failed")), + -1); + } + + ACE_OS::close (handle_ipv6); + + struct if_laddrreq *plcur = p_lifs.get (); + num_ifs_found = lifcfg.iflc_len / sizeof (struct if_laddrreq); + + for (size_t i = 0; + i < num_ifs_found; + i++) + { + struct sockaddr_in *addr = + reinterpret_cast (&plcur->iflr_addr); + if (!IN6_IS_ADDR_UNSPECIFIED(&reinterpret_cast(addr)->sin6_addr)) + { + addrs[count].set(addr, sizeof(struct sockaddr_in6)); + ++count; + } + ++plcur; + } + } +# endif /* ACE_HAS_IPV6 */ + return 0; +} +#elif defined (_AIX) +static int +get_ip_interfaces_aix (size_t &count, + ACE_INET_Addr *&addrs) +{ + ACE_HANDLE handle = ACE::get_handle(); + size_t num_ifs = 0; + struct ifconf ifc; + + if (handle == ACE_INVALID_HANDLE) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE::get_ip_interfaces_aix:")), + -1); + + if (ACE_OS::ioctl (handle, + SIOCGSIZIFCONF, + (caddr_t)&ifc.ifc_len) == -1) + { + ACE_OS::close (handle); + ACE_ERROR_RETURN((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("get ifconf size")), + -1); + } + + ACE_NEW_RETURN (ifc.ifc_buf,char [ifc.ifc_len], -1); + + ACE_Auto_Array_Ptr safe_buf (ifc.ifc_buf); + ACE_OS::memset (safe_buf.get(), 0, ifc.ifc_len); + + if (ACE_OS::ioctl(handle, SIOCGIFCONF, (caddr_t)&ifc) == -1) + { + ACE_OS::close (handle); + ACE_ERROR_RETURN((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("get ifconf")), + -1); + } + + ACE_OS::close (handle); + + char *buf_start = safe_buf.get(); + char *buf_end = buf_start + ifc.ifc_len; + + num_ifs = 0; + for (char *ptr = buf_start; ptr < buf_end; ) + { + struct ifreq *req = reinterpret_cast(ptr); + ptr += IFNAMSIZ; + ptr += req->ifr_addr.sa_len; + if (req->ifr_addr.sa_family == AF_INET +# if defined (ACE_HAS_IPV6) + || req->ifr_addr.sa_family == AF_INET6 +# endif + ) + ++num_ifs; + } + ACE_NEW_RETURN (addrs,ACE_INET_Addr[num_ifs], -1); + + for (char * ptr = buf_start; ptr < buf_end; ) + { + struct ifreq *req = reinterpret_cast(ptr); + // skip the interface name + ptr += IFNAMSIZ; + if (req->ifr_addr.sa_family == AF_INET +# if defined (ACE_HAS_IPV6) + || req->ifr_addr.sa_family == AF_INET6 +# endif + ) + { + sockaddr_in *addr = (sockaddr_in*)&req->ifr_addr; + addrs[count++].set(addr, addr->sin_len); + } + ptr += req->ifr_addr.sa_len; + } + + return 0; +} + +#elif defined (ACE_VXWORKS) && (ACE_VXWORKS < 0x600) && !defined (ACE_HAS_VXWORKS551_MEDUSA) +int +get_ip_interfaces_vxworks_lt600 (size_t &count, + ACE_INET_Addr *&addrs) +{ + count = 0; + // Loop through each address structure + +# if defined (ACE_HAS_IPV6) && defined (TAILQ_ENTRY) +# define ia_next ia_link.tqe_next +# endif /* TAILQ_ENTRY */ + + for (struct in_ifaddr* ia = in_ifaddr; ia != 0; ia = ia->ia_next) + { + ++count; + } + + // Now create and initialize output array. + ACE_NEW_RETURN (addrs, + ACE_INET_Addr[count], + -1); // caller must free + count = 0; + for (struct in_ifaddr* ia = in_ifaddr; ia != 0; ia = ia->ia_next) + { + struct ifnet* ifp = ia->ia_ifa.ifa_ifp; + if (ifp != 0) + { + // Get the current interface name + char interface[64]; + ACE_OS::sprintf(interface, "%s%d", ifp->if_name, ifp->if_unit); + + // Get the address for the current interface + char address [INET_ADDR_LEN]; + STATUS status = ifAddrGet(interface, address); + + if (status == OK) + { + // Concatenate a ':' at the end. This is because in + // ACE_INET_Addr::string_to_addr, the ip_address is + // obtained using ':' as the delimiter. Since, using + // ifAddrGet(), we just get the IP address, I am adding + // a ":" to get with the general case. + ACE_OS::strcat (address, ":"); + addrs[count].set (address); + } + else + { + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("ACE::get_ip_interface failed\n") + ACE_TEXT ("Couldnt get the IP Address\n")), + -1); + } + ++count; + } + } + return 0; +} +#endif // ACE_WIN32 || ACE_HAS_GETIFADDRS || __hpux || _AIX || ACE_VXWORKS < 0x600 + + +// return an array of all configured IP interfaces on this host, count +// rc = 0 on success (count == number of interfaces else -1 caller is +// responsible for calling delete [] on parray + +int +ACE::get_ip_interfaces (size_t &count, ACE_INET_Addr *&addrs) +{ + ACE_TRACE ("ACE::get_ip_interfaces"); + + count = 0; + addrs = 0; + +#if defined (ACE_WIN32) + return get_ip_interfaces_win32 (count, addrs); +#elif defined (ACE_HAS_GETIFADDRS) + return get_ip_interfaces_getifaddrs (count, addrs); +#elif defined (__hpux) + return get_ip_interfaces_hpux (count, addrs); +#elif defined (_AIX) + return get_ip_interfaces_aix (count, addrs); +#elif defined (ACE_VXWORKS) && (ACE_VXWORKS < 0x600) && !defined (ACE_HAS_VXWORKS551_MEDUSA) + return get_ip_interfaces_vxworks_lt600 (count, addrs); +#elif (defined (__unix) || defined (__unix__) || defined (ACE_OPENVMS) || (defined (ACE_VXWORKS) && !defined (ACE_HAS_GETIFADDRS)) || defined (ACE_HAS_RTEMS)) && !defined (ACE_LACKS_NETWORKING) + // COMMON (SVR4 and BSD) UNIX CODE + + // Call specific routine as necessary. + ACE_HANDLE handle = ACE::get_handle(); + + if (handle == ACE_INVALID_HANDLE) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE::get_ip_interfaces:open")), + -1); + + size_t num_ifs = 0; + + if (ACE::count_interfaces (handle, num_ifs)) + { + ACE_OS::close (handle); + return -1; + } + + // ioctl likes to have an extra ifreq structure to mark the end of + // what it returned, so increase the num_ifs by one. + ++num_ifs; + + struct IFREQ *ifs = 0; + ACE_NEW_RETURN (ifs, + struct IFREQ[num_ifs], + -1); + ACE_OS::memset (ifs, 0, num_ifs * sizeof (struct IFREQ)); + + ACE_Auto_Array_Ptr p_ifs (ifs); + + if (p_ifs.get() == 0) + { + ACE_OS::close (handle); + errno = ENOMEM; + return -1; + } + + struct IFCONF ifcfg; + ACE_OS::memset (&ifcfg, 0, sizeof (struct IFCONF)); + +# ifdef SETFAMILY + ifcfg.IFC_FAMILY = AF_UNSPEC; // request all families be returned + ifcfg.IFC_FLAGS = 0; +# endif + + ifcfg.IFC_REQ = p_ifs.get (); + ifcfg.IFC_LEN = num_ifs * sizeof (struct IFREQ); + + if (ACE_OS::ioctl (handle, + SIOCGIFCONF_CMD, + (caddr_t) &ifcfg) == -1) + { + ACE_OS::close (handle); + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE::get_ip_interfaces:") + ACE_TEXT ("ioctl - SIOCGIFCONF failed")), + -1); + } + + ACE_OS::close (handle); + + // Now create and initialize output array. + + ACE_NEW_RETURN (addrs, + ACE_INET_Addr[num_ifs], + -1); // caller must free + + struct IFREQ *pcur = p_ifs.get (); + size_t num_ifs_found = ifcfg.IFC_LEN / sizeof (struct IFREQ); // get the number of returned ifs + + // Pull the address out of each INET interface. Not every interface + // is for IP, so be careful to count properly. When setting the + // INET_Addr, note that the 3rd arg (0) says to leave the byte order + // (already in net byte order from the interface structure) as is. + count = 0; + + for (size_t i = 0; + i < num_ifs_found; + i++) + { + if (pcur->IFR_ADDR.SA_FAMILY == AF_INET +# if defined (ACE_HAS_IPV6) + || pcur->IFR_ADDR.SA_FAMILY == AF_INET6 +# endif + ) + + { +# if !defined(_UNICOS) + struct sockaddr_in *addr = + reinterpret_cast (&pcur->IFR_ADDR); + + // Sometimes the kernel returns 0.0.0.0 as an IPv4 interface + // address; skip those... + if (addr->sin_addr.s_addr != 0 +# if defined (ACE_HAS_IPV6) + || (addr->sin_family == AF_INET6 && + !IN6_IS_ADDR_UNSPECIFIED(&reinterpret_cast(addr)->sin6_addr)) +# endif + ) + { + int addrlen = static_cast (sizeof (struct sockaddr_in)); +# if defined (ACE_HAS_IPV6) + if (addr->sin_family == AF_INET6) + addrlen = static_cast (sizeof (struct sockaddr_in6)); +# endif + addrs[count].set (addr, addrlen); + ++count; + } +# else /* ! _UNICOS */ + // need to explicitly copy on the Cray, since the bitfields kinda + // screw things up here + struct sockaddr_in inAddr; + + inAddr.sin_len = pcur->IFR_ADDR.sa_len; + inAddr.sin_family = pcur->IFR_ADDR.sa_family; + memcpy((void *)&(inAddr.sin_addr), + (const void *)&(pcur->IFR_ADDR.sa_data[8]), + sizeof(struct in_addr)); + + if (inAddr.sin_addr.s_addr != 0) + { + addrs[count].set(&inAddr, sizeof(struct sockaddr_in)); + ++count; + } +# endif /* ! _UNICOS */ + } + +#if !defined (__QNX__) && !defined (__FreeBSD__) && !defined(__NetBSD__) && !defined (ACE_HAS_RTEMS) && !defined (__Lynx__) + ++pcur; +#else + if (pcur->ifr_addr.sa_len <= sizeof (struct sockaddr)) + { + ++pcur; + } + else + { + pcur = (struct ifreq *) + (pcur->ifr_addr.sa_len + (caddr_t) &pcur->ifr_addr); + } +#endif /* !defined (__QNX__) && !defined (__FreeBSD__) && !defined(__NetBSD__) && !defined (ACE_HAS_RTEMS) && !defined (__Lynx__) */ + } + +# if defined (ACE_HAS_IPV6) + // Retrieve IPv6 local interfaces by scanning /proc/net/if_inet6 if + // it exists. If we cannot open it then ignore possible IPv6 + // interfaces, we did our best;-) + FILE* fp = 0; + char addr_p[8][5]; + char s_ipaddr[64]; + int scopeid; + struct addrinfo hints, *res0; + int error; + + ACE_OS::memset (&hints, 0, sizeof (hints)); + hints.ai_flags = AI_NUMERICHOST; + hints.ai_family = AF_INET6; + + if ((fp = ACE_OS::fopen (ACE_TEXT ("/proc/net/if_inet6"), ACE_TEXT ("r"))) != 0) + { + while (fscanf (fp, + "%4s%4s%4s%4s%4s%4s%4s%4s %02x %*02x %*02x %*02x %*8s\n", + addr_p[0], addr_p[1], addr_p[2], addr_p[3], + addr_p[4], addr_p[5], addr_p[6], addr_p[7], &scopeid) != EOF) + { + // Format the address intoa proper IPv6 decimal address specification and + // resolve the resulting text using getaddrinfo(). + + const char* ip_fmt = "%s:%s:%s:%s:%s:%s:%s:%s%%%d"; + ACE_OS::sprintf (s_ipaddr, + ip_fmt, + addr_p[0], addr_p[1], addr_p[2], addr_p[3], + addr_p[4], addr_p[5], addr_p[6], addr_p[7], scopeid); + + error = getaddrinfo (s_ipaddr, 0, &hints, &res0); + if (error) + continue; + + if (res0->ai_family == AF_INET6 && + !IN6_IS_ADDR_UNSPECIFIED (&reinterpret_cast (res0->ai_addr)->sin6_addr)) + { + addrs[count].set(reinterpret_cast (res0->ai_addr), res0->ai_addrlen); + ++count; + } + freeaddrinfo (res0); + + } + ACE_OS::fclose (fp); + } +# endif /* ACE_HAS_IPV6 */ + + return 0; +#else + ACE_UNUSED_ARG (count); + ACE_UNUSED_ARG (addrs); + ACE_NOTSUP_RETURN (-1); // no implementation +#endif /* ACE_WIN32 */ +} + +// Helper routine for get_ip_interfaces, differs by UNIX platform so +// put into own subroutine. perform some ioctls to retrieve ifconf +// list of ifreq structs. + +int +ACE::count_interfaces (ACE_HANDLE handle, size_t &how_many) +{ +#if defined (SIOCGIFNUM) +# if defined (SIOCGLIFNUM) && !defined (ACE_LACKS_STRUCT_LIFNUM) + int cmd = SIOCGLIFNUM; + struct lifnum if_num = {AF_UNSPEC,0,0}; +# else + int cmd = SIOCGIFNUM; + int if_num = 0; +# endif /* SIOCGLIFNUM */ + if (ACE_OS::ioctl (handle, cmd, (caddr_t)&if_num) == -1) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE::count_interfaces:") + ACE_TEXT ("ioctl - SIOCGLIFNUM failed")), + -1); +# if defined (SIOCGLIFNUM) && !defined (ACE_LACKS_STRUCT_LIFNUM) + how_many = if_num.lifn_count; +# else + how_many = if_num; +# endif /* SIOCGLIFNUM */ +return 0; + +#elif (defined (__unix) || defined (__unix__) || defined (ACE_OPENVMS) || defined (ACE_HAS_RTEMS) || (defined (ACE_VXWORKS) && !defined (ACE_HAS_GETIFADDRS))) && !defined (ACE_LACKS_NETWORKING) + // Note: DEC CXX doesn't define "unix". BSD compatible OS: HP UX, + // AIX, SunOS 4.x perform some ioctls to retrieve ifconf list of + // ifreq structs no SIOCGIFNUM on SunOS 4.x, so use guess and scan + // algorithm + + // Probably hard to put this many ifs in a unix box.. + int const MAX_IF = 50; + + // HACK - set to an unreasonable number + int const num_ifs = MAX_IF; + + struct ifconf ifcfg; + size_t ifreq_size = num_ifs * sizeof (struct ifreq); + struct ifreq *p_ifs = (struct ifreq *) ACE_OS::malloc (ifreq_size); + + if (!p_ifs) + { + errno = ENOMEM; + return -1; + } + + ACE_OS::memset (p_ifs, 0, ifreq_size); + ACE_OS::memset (&ifcfg, 0, sizeof (struct ifconf)); + + ifcfg.ifc_req = p_ifs; + ifcfg.ifc_len = ifreq_size; + + if (ACE_OS::ioctl (handle, + SIOCGIFCONF_CMD, + (caddr_t) &ifcfg) == -1) + { + ACE_OS::free (ifcfg.ifc_req); + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE::count_interfaces:") + ACE_TEXT ("ioctl - SIOCGIFCONF failed")), + -1); + } + + int if_count = 0; + int i = 0; + + // get if address out of ifreq buffers. ioctl puts a blank-named + // interface to mark the end of the returned interfaces. + for (i = 0; + i < num_ifs; + i++) + { + /* In OpenBSD, the length of the list is returned. */ + ifcfg.ifc_len -= sizeof (struct ifreq); + if (ifcfg.ifc_len < 0) + break; + + ++if_count; +#if !defined (__QNX__) && !defined (__FreeBSD__) && !defined(__NetBSD__) && !defined (ACE_HAS_RTEMS) && !defined (__Lynx__) + ++p_ifs; +#else + if (p_ifs->ifr_addr.sa_len <= sizeof (struct sockaddr)) + { + ++p_ifs; + } + else + { + p_ifs = (struct ifreq *) + (p_ifs->ifr_addr.sa_len + (caddr_t) &p_ifs->ifr_addr); + } +#endif /* !defined (__QNX__) && !defined (__FreeBSD__) && !defined(__NetBSD__) && !defined (ACE_HAS_RTEMS) && !defined (__Lynx__)*/ + } + + ACE_OS::free (ifcfg.ifc_req); + +# if defined (ACE_HAS_IPV6) + FILE* fp = 0; + + if ((fp = ACE_OS::fopen (ACE_TEXT ("/proc/net/if_inet6"), ACE_TEXT ("r"))) != 0) + { + // Scan the lines according to the expected format but don't really read any input + while (fscanf (fp, "%*32s %*02x %*02x %*02x %*02x %*8s\n") != EOF) + { + ++if_count; + } + ACE_OS::fclose (fp); + } +# endif /* ACE_HAS_IPV6 */ + + how_many = if_count; + return 0; +#else + ACE_UNUSED_ARG (handle); + ACE_UNUSED_ARG (how_many); + ACE_NOTSUP_RETURN (-1); // no implementation +#endif /* sparc && SIOCGIFNUM */ +} + +// Routine to return a handle from which ioctl() requests can be made. + +ACE_HANDLE +ACE::get_handle (void) +{ + // Solaris 2.x + ACE_HANDLE handle = ACE_INVALID_HANDLE; +#if defined (sparc) + handle = ACE_OS::open ("/dev/udp", O_RDONLY); +#elif defined (__unix) || defined (__unix__) || defined (_AIX) || defined (__hpux) || (defined (ACE_VXWORKS) && (ACE_VXWORKS >= 0x600)) || defined (ACE_OPENVMS) || defined (ACE_HAS_RTEMS) + // Note: DEC CXX doesn't define "unix" BSD compatible OS: HP UX, + // AIX, SunOS 4.x + + handle = ACE_OS::socket (PF_INET, SOCK_DGRAM, 0); +#endif /* sparc */ + return handle; +} + + +#if defined (ACE_HAS_IPV6) +static int +ip_check (int &ipvn_enabled, int pf) +{ + // We only get to this point if ipvn_enabled was -1 in the caller. + // Perform Double-Checked Locking Optimization. + ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, + *ACE_Static_Object_Lock::instance (), 0)); + + if (ipvn_enabled == -1) + { + // Determine if the kernel has IPv6 support by attempting to + // create a PF_INET socket and see if it fails. + ACE_HANDLE const s = ACE_OS::socket (pf, SOCK_DGRAM, 0); + if (s == ACE_INVALID_HANDLE) + { + ipvn_enabled = 0; + } + else + { + ipvn_enabled = 1; + ACE_OS::closesocket (s); + } + } + return ipvn_enabled; +} +#endif /* ACE_HAS_IPV6 */ + +bool +ACE::ipv4_enabled (void) +{ +#if defined (ACE_HAS_IPV6) + return static_cast (ace_ipv4_enabled == -1 ? + ::ip_check (ace_ipv4_enabled, PF_INET) : + ace_ipv4_enabled); +#else + // Assume it's always enabled since ACE requires some version of + // TCP/IP to exist. + return true; +#endif /* ACE_HAS_IPV6*/ +} + +int +ACE::ipv6_enabled (void) +{ +#if defined (ACE_HAS_IPV6) + return ace_ipv6_enabled == -1 ? + ::ip_check (ace_ipv6_enabled, PF_INET6) : + ace_ipv6_enabled; +#else /* ACE_HAS_IPV6 */ + return 0; +#endif /* !ACE_HAS_IPV6 */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Sock_Connect.h b/dep/acelite/ace/Sock_Connect.h new file mode 100644 index 00000000000..d6a72c718b8 --- /dev/null +++ b/dep/acelite/ace/Sock_Connect.h @@ -0,0 +1,107 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file Sock_Connect.h + * + * $Id: Sock_Connect.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Priyanka Gontla + * @author Based on code that existed formerly in ACE.h. + */ +//========================================================================== + +#ifndef ACE_SOCK_CONNECT_H +#define ACE_SOCK_CONNECT_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Basic_Types.h" +#include "ace/os_include/netinet/os_in.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Forward Declarations +class ACE_INET_Addr; + +namespace ACE +{ + // = Socket connection establishment calls. + + /// Bind a new unused port to @a handle. + extern ACE_Export int bind_port (ACE_HANDLE handle, + ACE_UINT32 ip_addr = INADDR_ANY, + int address_family = AF_UNSPEC); + + /** + * Get our broadcast address based on our @a host_addr. If + * @a hostname is non-0 we'll use it to determine our IP address. If + * @a handle is not ACE_INVALID_HANDLE then we'll use this to + * determine our broadcast address, otherwise we'll have to create a + * socket internally (and free it). Returns -1 on failure and 0 on + * success. + */ + extern ACE_Export int get_bcast_addr ( + ACE_UINT32 &bcast_addr, + const ACE_TCHAR *hostname = 0, + ACE_UINT32 host_addr = 0, + ACE_HANDLE handle = ACE_INVALID_HANDLE); + + /// Get fully qualified host/domain name. + extern ACE_Export int get_fqdn (ACE_INET_Addr const & addr, + char hostname[], + size_t len); + + /** + * Return count and array of all configured IP interfaces on this + * host, rc = 0 on success (count == number of interfaces else -1). + * Caller is responsible for calling delete [] on @a addr_array. + */ + extern ACE_Export int get_ip_interfaces (size_t &count, + ACE_INET_Addr *&addr_array); + + /** + * Helper routine for get_ip_interfaces, differs by UNIX platform so + * put into own subroutine. perform some ioctls to retrieve ifconf + * list of ifreq structs. + */ + extern ACE_Export int count_interfaces (ACE_HANDLE handle, + size_t &how_many); + + /// Routine to return a handle from which @c ioctl requests can be + /// made. Caller must close the handle. + extern ACE_Export ACE_HANDLE get_handle (void); + + /// Returns @c true if IPv4 is enabled on the current host; @c false + /// if not. + /** + * This is an execution-time check. If ACE has not been compiled + * with @c ACE_HAS_IPV6, it always returns @c true. This function + * tries to create a @c PF_INET socket, returning @c true if it + * succeeds, and @c false if it fails. Caches the result so it only + gets checked once. + */ + extern ACE_Export bool ipv4_enabled (void); + + /** + * Returns 1 if IPv6 is enabled on the current host; 0 if not. + * This is an execution-time check. If ACE has not been compiled + * with ACE_HAS_IPV6, it always returns 0. If ACE_HAS_IPV6 is + * enabled, this function tries to create a PF_INET6 socket, + * returning 1 if it succeeds, and 0 if it fails. Caches the result + * so it only gets checked once. + */ + extern ACE_Export int ipv6_enabled (void); +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" + +#endif /* ACE_SOCK_CONNECT_H */ diff --git a/dep/acelite/ace/Stack_Trace.cpp b/dep/acelite/ace/Stack_Trace.cpp new file mode 100644 index 00000000000..3beb1c52f3e --- /dev/null +++ b/dep/acelite/ace/Stack_Trace.cpp @@ -0,0 +1,723 @@ +//============================================================================= +/** + * @file Stack_Trace.cpp + * + * $Id: Stack_Trace.cpp 90041 2010-04-29 03:38:07Z cleeland $ + * + * @brief Encapsulate string representation of stack trace. + * + * Some platform-specific areas of this code have been adapted from + * examples found elsewhere. Specifically, + * - the GLIBC stack generation uses the documented "backtrace" API + * and is adapted from examples shown in relevant documentation + * and repeated elsewhere, e.g., + * http://www.linuxselfhelp.com/gnu/glibc/html_chapter/libc_33.html + * - the Solaris stack generation is adapted from a 1995 post on + * comp.unix.solaris by Bart Smaalders, + * http://groups.google.com/group/comp.unix.solaris/browse_thread/thread/8b9f3de8be288f1c/31550f93a48231d5?lnk=gst&q=how+to+get+stack+trace+on+solaris+group:comp.unix.solaris#31550f93a48231d5 + * - VxWorks kernel-mode stack tracing is adapted from a code example + * in the VxWorks FAQ at http://www.xs4all.nl/~borkhuis/vxworks/vxw_pt5.html + * although the undocumented functions it uses are also mentioned in + * various documents available on the WindRiver support website. + * + * If you add support for a new platform, please add a bullet to the + * above list with durable references to the origins of your code. + * + */ +//============================================================================= + +#include "ace/Stack_Trace.h" +#include "ace/Min_Max.h" +#include "ace/OS_NS_string.h" +#include "ace/OS_NS_stdio.h" + +ACE_RCSID (ace, Stack_Trace, "$Id: Stack_Trace.cpp 90041 2010-04-29 03:38:07Z cleeland $") + +/* + This is ugly, simply because it's very platform-specific. +*/ + +const char ACE_Stack_Trace::UNSUPPORTED[] = ""; +const char ACE_Stack_Trace::UNABLE_TO_GET_TRACE[] = ""; + +ACE_Stack_Trace::ACE_Stack_Trace (ssize_t starting_frame_offset, size_t num_frames) + : buflen_(0) +{ + // cannot initialize arrays, so we must assign. + this->buf_[0] = '\0'; + this->generate_trace (starting_frame_offset, num_frames); +} + +const char* +ACE_Stack_Trace::c_str () const +{ + return &this->buf_[0]; +} + +static inline size_t +determine_starting_frame (ssize_t initial_frame, ssize_t offset) +{ + return ACE_MAX( initial_frame + offset, static_cast(0)); +} + +#if (defined(__GLIBC__) || defined(ACE_HAS_EXECINFO_H)) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 3)) +// This is the code for glibc +# include + +void +ACE_Stack_Trace::generate_trace (ssize_t starting_frame_offset, size_t num_frames) +{ + const size_t MAX_FRAMES = 128; + const ssize_t INITIAL_FRAME = 3; + + void* stack[MAX_FRAMES]; + size_t stack_size = 0; + char** stack_syms; + + if (num_frames == 0) + num_frames = MAX_FRAMES; + + size_t starting_frame = + determine_starting_frame (INITIAL_FRAME, starting_frame_offset); + + stack_size = ::backtrace (&stack[0], sizeof(stack)/sizeof(stack[0])); + if (stack_size != 0) + { + stack_syms = ::backtrace_symbols (stack, stack_size); + + for (size_t i = starting_frame; + i < stack_size && num_frames > 0; + i++, num_frames--) + { + // this could be more efficient by remembering where we left off in buf_ + char *symp = &stack_syms[i][0]; + while (this->buflen_ < SYMBUFSIZ - 2 && *symp != '\0') + { + this->buf_[this->buflen_++] = *symp++; + } + this->buf_[this->buflen_++] = '\n'; // put a newline at the end + } + this->buf_[this->buflen_] = '\0'; // zero terminate the string + + ::free (stack_syms); + } + else + { + ACE_OS::strcpy (&this->buf_[0], UNABLE_TO_GET_TRACE); + } +} +#elif defined(VXWORKS) && !defined(__RTP__) +# include +# include // hopefully this is enough to get all the necessary #defines. + +struct ACE_Stack_Trace_stackstate +{ + ACE_Stack_Trace_stackstate (char* b, size_t& bl, size_t nf, size_t sf) + : buf(b), buflen(bl), num_frames(nf), starting_frame(sf) + { } + + char* buf; + size_t& buflen; + size_t num_frames; + size_t starting_frame; +}; + +//@TODO: Replace with a TSS-based pointer to avoid problems in multithreaded environs, +// or use a mutex to serialize access to this. +static ACE_Stack_Trace_stackstate* ACE_Stack_Trace_stateptr = 0; + +static void +ACE_Stack_Trace_Add_Frame_To_Buf (INSTR *caller, + unsigned int func, + unsigned int nargs, + unsigned int *args) +{ + if (ACE_Stack_Trace_stateptr == 0) + return; + + ACE_Stack_Trace_stackstate *stackstate = ACE_Stack_Trace_stateptr; + + // Decrement the num_frames and starting_frame elements, + // then see if we're ready to start or ready to finish. + --stackstate->num_frames; + --stackstate->starting_frame; + + if (stackstate->num_frames == 0 || stackstate->starting_frame > 0) + return; + + // These are references so that the structure gets updated + // in the code below. + char*& buf = stackstate->buf; + unsigned int& len = stackstate->buflen; + + // At some point try using symFindByValue() to lookup func (and caller?) + // to print out symbols rather than simply addresses. + + // VxWorks can pass -1 for "nargs" if there was an error + if (nargs == static_cast (-1)) nargs = 0; + + len += ACE_OS::sprintf (&buf[len], "%#10x: %#10x (", (int)caller, func); + for (unsigned int i = 0; i < nargs; ++i) + { + if (i != 0) + len += ACE_OS::sprintf (&buf[len], ", "); + len += ACE_OS::sprintf(&buf [len], "%#x", args [i]); + } + + len += ACE_OS::sprintf(&buf[len], ")\n"); +} + +void +ACE_Stack_Trace::generate_trace (ssize_t starting_frame_offset, + size_t num_frames) +{ + const size_t MAX_FRAMES = 128; + const ssize_t INITIAL_FRAME = 3; + + if (num_frames == 0) + num_frames = MAX_FRAMES; + + size_t starting_frame = + determine_starting_frame (INITIAL_FRAME, starting_frame_offset); + + ACE_Stack_Trace_stackstate state (&this->buf_[0], this->buflen_, + num_frames, starting_frame); + + REG_SET regs; + + taskRegsGet ((int)taskIdSelf(), ®s); + // Maybe we should take a lock here to guard stateptr? + ACE_Stack_Trace_stateptr = &state; + trcStack (®s, (FUNCPTR)ACE_Stack_Trace_Add_Frame_To_Buf, taskIdSelf ()); +} + + +#elif defined(VXWORKS) && defined(__RTP__) +# include +# include +# include + +// See memEdrLib.c in VxWorks RTP sources for an example of stack tracing. + +static STATUS ace_vx_rtp_pc_validate (INSTR *pc, TRC_OS_CTX *pOsCtx) +{ + return ALIGNED (pc, sizeof (INSTR)) ? OK : ERROR; +} + +void +ACE_Stack_Trace::generate_trace (ssize_t starting_frame_offset, + size_t num_frames) +{ + const size_t MAX_FRAMES = 128; + const ssize_t INITIAL_FRAME = 2; + + if (num_frames == 0) num_frames = MAX_FRAMES; + size_t starting_frame = + determine_starting_frame (INITIAL_FRAME, starting_frame_offset); + + jmp_buf regs; + setjmp (regs); + + TASK_DESC desc; + if (taskInfoGet (taskIdSelf (), &desc) == ERROR) return; + + TRC_OS_CTX osCtx; + osCtx.stackBase = desc.td_pStackBase; + osCtx.stackEnd = desc.td_pStackEnd; + osCtx.pcValidateRtn = reinterpret_cast (ace_vx_rtp_pc_validate); + + char *fp = _WRS_FRAMEP_FROM_JMP_BUF (regs); + INSTR *pc = _WRS_RET_PC_FROM_JMP_BUF (regs); + + for (size_t depth = 0; depth < num_frames + starting_frame; ++depth) + { + char *prevFp; + INSTR *prevPc; + INSTR *prevFn; + + if (trcLibFuncs.lvlInfoGet (fp, pc, &osCtx, &prevFp, &prevPc, &prevFn) + == ERROR) + { + ACE_OS::strcpy (this->buf_, UNABLE_TO_GET_TRACE); + return; + } + + if(prevPc == 0 || prevFp == 0) break; + + if (depth >= starting_frame) + { + //Hopefully a future version of VxWorks will have a system call + //for an RTP to query its own symbols, but this is not possible now. + //An enhancement request has been filed under WIND00123307. + const char *fnName = "(no symbols)"; + + static const int N_ARGS = 12; + int buf[N_ARGS]; + int *pArgs = 0; + int numArgs = + trcLibFuncs.lvlArgsGet (prevPc, prevFn, prevFp, + buf, N_ARGS, &pArgs); + + // VxWorks can return -1 for "numArgs" if there was an error + if (numArgs == -1) numArgs = 0; + + size_t len = ACE_OS::strlen (this->buf_); + size_t space = SYMBUFSIZ - len - 1; + char *cursor = this->buf_ + len; + size_t written = ACE_OS::snprintf (cursor, space, "%x %s", + prevFn, fnName); + cursor += written; + space -= written; + + if (space < 1) return; //no point in logging when we're out of buffer + for (int arg = 0; numArgs != -1 && pArgs && arg < numArgs; ++arg) + { + if (arg == 0) *cursor++ = '(', --space; + written = ACE_OS::snprintf (cursor, space, + (arg < numArgs - 1) ? "%x, " : "%x", + pArgs[arg]); + cursor += written; + space -= written; + if (space && arg == numArgs - 1) *cursor++ = ')', --space; + } + if (space) *cursor++ = '\n', --space; + *cursor++ = 0; //we saved space for the null terminator + } + + fp = prevFp; + pc = prevPc; + } +} + +#elif defined(sun) +/* + * walks up call stack, printing library:routine+offset for each routine + */ + +# include +# include +# include +# include +# include +# define ACE_STACK_TRACE_BIAS 0 + +# if defined(sparc) || defined(__sparc) +# define ACE_STACK_TRACE_FLUSHWIN() asm("ta 3"); +# define ACE_STACK_TRACE_FRAME_PTR_INDEX 1 +# define ACE_STACK_TRACE_SKIP_FRAMES 0 +# if defined(__sparcv9) +# undef ACE_STACK_TRACE_BIAS +# define ACE_STACK_TRACE_BIAS 2047 +# endif +# endif + +# if defined(i386) || defined(__i386) +# define ACE_STACK_TRACE_FLUSHWIN() +# define ACE_STACK_TRACE_FRAME_PTR_INDEX 3 +# define ACE_STACK_TRACE_SKIP_FRAMES 0 +# endif + +# if defined(__amd64) || defined(__x86_64) +# define ACE_STACK_TRACE_FLUSHWIN() +# define ACE_STACK_TRACE_FRAME_PTR_INDEX 5 +# define ACE_STACK_TRACE_SKIP_FRAMES 0 +# endif + +# if defined(ppc) || defined(__ppc) +# define ACE_STACK_TRACE_FLUSHWIN() +# define ACE_STACK_TRACE_FRAME_PTR_INDEX 0 +# define ACE_STACK_TRACE_SKIP_FRAMES 2 +# endif + +static frame* +cs_frame_adjust(frame* sp) +{ + unsigned char* sp_byte = (unsigned char*)sp; + sp_byte += ACE_STACK_TRACE_BIAS; + return (frame*) sp_byte; +} + +/* + this function walks up call stack, calling user-supplied + function once for each stack frame, passing the pc and the user-supplied + usrarg as the argument. + */ + +static int +cs_operate(int (*func)(void *, void *), void * usrarg, + size_t starting_frame, size_t num_frames_arg) +{ + ACE_STACK_TRACE_FLUSHWIN(); + + jmp_buf env; + setjmp(env); + frame* sp = cs_frame_adjust((frame*) env[ACE_STACK_TRACE_FRAME_PTR_INDEX]); + + // make a copy of num_frames_arg to eliminate the following warning on some + // solaris platforms: + // Stack_Trace.cpp:318: warning: argument `size_t num_frames' might be clobbered by `longjmp' or `vfork' + size_t num_frames = num_frames_arg; + + // I would like to use ACE_MAX below rather than ?:, but + // I get linker relocation errors such as the following when + // I use it: + // ld: fatal: relocation error: file: .shobj/Stack_Trace.o section: + // .rela.debug_line symbol: : relocation against a discarded symbol, + // symbol is part of discarded section: + // .text%const __type_0&ace_max(const __type_0&,const __type_0&) + // + const size_t starting_skip = starting_frame - 1; +#if ACE_STACK_TRACE_SKIP_FRAMES == 0 + size_t skip_frames = starting_skip; +#else + size_t skip_frames = + ACE_STACK_TRACE_SKIP_FRAMES > starting_skip ? + ACE_STACK_TRACE_SKIP_FRAMES : starting_skip; +#endif /* ACE_STACK_TRACE_SKIP_FRAMES == 0 */ + size_t i; + for (i = 0; i < skip_frames && sp; ++i) + { + sp = cs_frame_adjust((frame*) sp->fr_savfp); + } + + i = 0; + + while ( sp + && sp->fr_savpc + && ++i + && --num_frames + && (*func)((void*)sp->fr_savpc, usrarg)) + { + sp = cs_frame_adjust((frame*) sp->fr_savfp); + } + + return(i); +} + +static int +add_frame_to_buf (void* pc, void* usrarg) +{ + char* buf = (char*)usrarg; + Dl_info info; + const char* func = "??"; + const char* lib = "??"; + + if(dladdr(pc, & info) != 0) + { + lib = (const char *) info.dli_fname; + func = (const char *) info.dli_sname; + } + + (void) ACE_OS::snprintf(buf, + ACE_Stack_Trace::SYMBUFSIZ, + "%s%s:%s+0x%x\n", + buf, + lib, + func, + //@@ Should the arithmetic on the following + //line be done with two void* ptrs? The result + //would be ptrdiff_t, and what is the correct + //sprintf() conversion character for that? + (size_t)pc - (size_t)info.dli_saddr); + + return(1); +} + +void +ACE_Stack_Trace::generate_trace (ssize_t starting_frame_offset, + size_t num_frames) +{ + const size_t MAX_FRAMES = 128; + const ssize_t INITIAL_FRAME = 3; + + if (num_frames == 0) + num_frames = MAX_FRAMES; + + size_t starting_frame = + determine_starting_frame (INITIAL_FRAME, starting_frame_offset); + + cs_operate (&add_frame_to_buf, &this->buf_[0], starting_frame, num_frames); +} + +#elif defined(ACE_WIN64) && (_WIN32_WINNT <= _WIN32_WINNT_WIN2K) +# if defined(_MSC_VER) +# define STRING2(X) #X +# define STRING(X) STRING2(X) +# pragma message (__FILE__ "(" STRING(__LINE__) ") : warning: stack traces"\ + " can't be generated on 64-bit Windows when _WIN32_WINNT is less than "\ + "0x501.") +# undef STRING +# undef STRING2 +# endif /*_MSC_VER*/ +void +ACE_Stack_Trace::generate_trace (ssize_t, size_t) +{ + ACE_OS::strcpy (&this->buf_[0], ""); +} + +#elif defined(ACE_WIN32) && !defined(ACE_HAS_WINCE) && !defined (__MINGW32__) \ + && !defined(__BORLANDC__) +# include +# include + +# define MAXTEXT 5000 +# define SYMSIZE 100 + +//@TODO: Test with WCHAR +//@TODO: Need a common CriticalSection since dbghelp is not thread-safe + +typedef struct _dbghelp_functions +{ + HMODULE hMod; //our handle to dbghelp.dll + + //these already have typedefs in DbgHelp.h + DWORD64 (WINAPI *SymGetModuleBase64) (HANDLE hProc, DWORD64 dwAddr); + PVOID (WINAPI *SymFunctionTableAccess64) (HANDLE hProc, DWORD64 AddrBase); + + typedef BOOL (WINAPI *SymFromAddr_t) + (HANDLE hProc, DWORD64 Addr, PDWORD64 Disp, PSYMBOL_INFO Symbol); + SymFromAddr_t SymFromAddr; + + typedef BOOL (WINAPI *SymGetLineFromAddr64_t) (HANDLE hProc, DWORD64 dwAddr, + PDWORD pdwDisplacement, + PIMAGEHLP_LINE64 Line); + SymGetLineFromAddr64_t SymGetLineFromAddr64; + + typedef DWORD (WINAPI *SymSetOptions_t) (DWORD SymOptions); + SymSetOptions_t SymSetOptions; + + typedef DWORD (WINAPI *SymGetOptions_t) (); + SymGetOptions_t SymGetOptions; + + typedef BOOL (WINAPI *SymInitialize_t) (HANDLE hProc, PCTSTR UserSearchPath, + BOOL invasive); + SymInitialize_t SymInitialize; + + typedef BOOL + (WINAPI *StackWalk64_t) (DWORD MachineType, HANDLE hPRoc, HANDLE hThr, + LPSTACKFRAME64 StackFrame, PVOID ContextRecord, + PREAD_PROCESS_MEMORY_ROUTINE64 RMRoutine, + PFUNCTION_TABLE_ACCESS_ROUTINE64 FTARoutine, + PGET_MODULE_BASE_ROUTINE64 GMBRoutine, + PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress); + StackWalk64_t StackWalk64; + + typedef BOOL (WINAPI *SymCleanup_t) (HANDLE hProc); + SymCleanup_t SymCleanup; +} dbghelp_functions; + + +# pragma warning (push) +# pragma warning (disable:4706) +static bool load_dbghelp_library_if_needed (dbghelp_functions *pDbg) +{ + //@TODO: See codeproject's StackWalker.cpp for the list of locations to + //search so we get the "enhanced" dbghelp if the user has it but it is not + //first on the path. + if (!(pDbg->hMod = ACE_TEXT_LoadLibrary (ACE_TEXT ("Dbghelp")))) + return false; + + //@TODO: Cache this so we don't have to re-link every time. When to unload? + +# define LINK(TYPE, NAME) (pDbg->NAME = \ + (TYPE) GetProcAddress (pDbg->hMod, #NAME)) +# define LINK_T(NAME) LINK (dbghelp_functions::NAME##_t, NAME) + return LINK (PGET_MODULE_BASE_ROUTINE64, SymGetModuleBase64) + && LINK (PFUNCTION_TABLE_ACCESS_ROUTINE64, SymFunctionTableAccess64) + && LINK_T (SymFromAddr) && LINK_T (SymGetLineFromAddr64) + && LINK_T (SymSetOptions)&& LINK_T (SymGetOptions) + && LINK_T (SymInitialize) && LINK_T (StackWalk64) && LINK_T (SymCleanup); +# undef LINK +# undef LINK_T +} +# pragma warning (pop) + + +struct frame_state { + STACKFRAME64 sf; + PSYMBOL_INFO pSym; + dbghelp_functions *pDbg; +}; + +static int +add_frame_to_buf (struct frame_state const *fs, void *usrarg) +{ + if (fs == 0 || usrarg == 0) + return -1; + + char *buf = static_cast (usrarg); + + DWORD64 disp; + DWORD64 dwModBase = fs->pDbg->SymGetModuleBase64 (GetCurrentProcess (), + fs->sf.AddrPC.Offset); + if (fs->pDbg->SymFromAddr (GetCurrentProcess (), + fs->sf.AddrPC.Offset, &disp, fs->pSym)) + { + IMAGEHLP_LINE64 line = {sizeof (IMAGEHLP_LINE64)}; + DWORD lineDisp; + if (fs->pDbg->SymGetLineFromAddr64 (GetCurrentProcess (), + fs->sf.AddrPC.Offset, + &lineDisp, &line)) + { + (void) ACE_OS::snprintf (buf, ACE_Stack_Trace::SYMBUFSIZ, + "%s%s() %s: %d + 0x%x\n", + buf, fs->pSym->Name, line.FileName, + line.LineNumber, lineDisp); + } + else + { + (void) ACE_OS::snprintf (buf, ACE_Stack_Trace::SYMBUFSIZ, + "%s%s()+0x%x [0x%x]\n", + buf, fs->pSym->Name, disp, + fs->sf.AddrPC.Offset - dwModBase); + } + } + else + { + (void) ACE_OS::snprintf (buf, ACE_Stack_Trace::SYMBUFSIZ, + "%s[0x%x]\n", + buf, fs->sf.AddrPC.Offset - dwModBase); + } + return 0; +} + +static void emptyStack () { } + +#if defined (_MSC_VER) +# pragma warning(push) +// Suppress warning 4748 "/GS can not protect parameters and local +// variables from local buffer overrun because optimizations are +// disabled in function" +# pragma warning(disable: 4748) +#endif /* _MSC_VER */ + +static int +cs_operate(int (*func)(struct frame_state const *, void *), void *usrarg, + size_t starting_frame, size_t num_frames) +{ + dbghelp_functions dbg; + if (!load_dbghelp_library_if_needed (&dbg)) + { + ACE_OS::strcpy (static_cast (usrarg), + ""); + if (dbg.hMod) FreeLibrary (dbg.hMod); + return 1; + } + + frame_state fs; + ZeroMemory (&fs.sf, sizeof (fs.sf)); + fs.pDbg = &dbg; + emptyStack (); //Not sure what this should do, Chad? + + CONTEXT c; + ZeroMemory (&c, sizeof (CONTEXT)); + c.ContextFlags = CONTEXT_FULL; + +# if defined (_M_IX86) + DWORD machine = IMAGE_FILE_MACHINE_I386; + __asm { + call x + x: pop eax + mov c.Eip, eax + mov c.Ebp, ebp + mov c.Esp, esp + } + fs.sf.AddrPC.Offset = c.Eip; + fs.sf.AddrStack.Offset = c.Esp; + fs.sf.AddrFrame.Offset = c.Ebp; + fs.sf.AddrPC.Mode = AddrModeFlat; + fs.sf.AddrStack.Mode = AddrModeFlat; + fs.sf.AddrFrame.Mode = AddrModeFlat; +# elif defined (_M_X64) + DWORD machine = IMAGE_FILE_MACHINE_AMD64; + RtlCaptureContext (&c); + fs.sf.AddrPC.Offset = c.Rip; + fs.sf.AddrFrame.Offset = c.Rsp; //should be Rbp or Rdi instead? + fs.sf.AddrStack.Offset = c.Rsp; + fs.sf.AddrPC.Mode = AddrModeFlat; + fs.sf.AddrFrame.Mode = AddrModeFlat; + fs.sf.AddrStack.Mode = AddrModeFlat; +# elif defined (_M_IA64) + DWORD machine = IMAGE_FILE_MACHINE_IA64; + RtlCaptureContext (&c); + fs.sf.AddrPC.Offset = c.StIIP; + fs.sf.AddrFrame.Offset = c.RsBSP; + fs.sf.AddrBStore.Offset = c.RsBSP; + fs.sf.AddrStack.Offset = c.IntSp; + fs.sf.AddrPC.Mode = AddrModeFlat; + fs.sf.AddrFrame.Mode = AddrModeFlat; + fs.sf.AddrBStore.Mode = AddrModeFlat; + fs.sf.AddrStack.Mode = AddrModeFlat; +# endif + + fs.pSym = (PSYMBOL_INFO) GlobalAlloc (GMEM_FIXED, + sizeof (SYMBOL_INFO) + + sizeof (ACE_TCHAR) * (SYMSIZE - 1)); + fs.pSym->SizeOfStruct = sizeof (SYMBOL_INFO); + fs.pSym->MaxNameLen = SYMSIZE * sizeof (ACE_TCHAR); + dbg.SymSetOptions (SYMOPT_DEFERRED_LOADS | SYMOPT_LOAD_LINES + | SYMOPT_FAIL_CRITICAL_ERRORS | dbg.SymGetOptions ()); + dbg.SymInitialize (GetCurrentProcess (), 0, true); + //What does the "true" parameter mean when tracing the current process? + + for (size_t current_frame = 0; current_frame < num_frames + starting_frame; + ++current_frame) + { + BOOL ok = dbg.StackWalk64 (machine, + GetCurrentProcess (), + GetCurrentThread (), + &fs.sf, &c, 0, + dbg.SymFunctionTableAccess64, + dbg.SymGetModuleBase64, 0); + if (!ok || fs.sf.AddrFrame.Offset == 0) + break; + + if (current_frame < starting_frame) + continue; + + func (&fs, usrarg); + } + + dbg.SymCleanup (GetCurrentProcess ()); + GlobalFree (fs.pSym); + FreeLibrary (dbg.hMod); + + return 0; +} + +#if defined (_MSC_VER) +// Restore the warning state to what it was before entry. +# pragma warning(pop) +#endif /* _MSC_VER */ + +void +ACE_Stack_Trace::generate_trace (ssize_t starting_frame_offset, + size_t num_frames) +{ + const size_t MAX_FRAMES = 128; + const ssize_t INITIAL_FRAME = 3; + + if (num_frames == 0) + num_frames = MAX_FRAMES; + + size_t starting_frame = + determine_starting_frame (INITIAL_FRAME, starting_frame_offset); + + cs_operate (&add_frame_to_buf, &this->buf_[0], starting_frame, num_frames); +} + +#else // Unsupported platform +void +ACE_Stack_Trace::generate_trace (ssize_t, size_t) +{ +// Call determine_starting_frame() on HP aCC build to resolve declared +// method never referenced warning. +#if defined (__HP_aCC) + size_t starting_frame = determine_starting_frame (0, 0); +#endif + + ACE_OS::strcpy (&this->buf_[0], UNSUPPORTED); +} +#endif + diff --git a/dep/acelite/ace/Stack_Trace.h b/dep/acelite/ace/Stack_Trace.h new file mode 100644 index 00000000000..56cf8a09208 --- /dev/null +++ b/dep/acelite/ace/Stack_Trace.h @@ -0,0 +1,107 @@ +// -*- C++ -*- +//============================================================================= +/** + * @file Stack_Trace.h + * + * $Id: Stack_Trace.h 81926 2008-06-12 14:43:09Z mitza $ + * + * @author Chris Cleeland (cleeland.ociweb.com) + */ +//============================================================================= + +#ifndef ACE_STACK_TRACE_H +#define ACE_STACK_TRACE_H + +#include /**/ "ace/pre.h" + +#include "ace/ACE_export.h" +#include "ace/Basic_Types.h" + +# if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +# endif /* ACE_LACKS_PRAGMA_ONCE */ + +# ifndef ACE_STACK_TRACE_SYMBUFSIZ +# define ACE_STACK_TRACE_SYMBUFSIZ 4096 +# endif + +/** + * @class ACE_Stack_Trace + * + * @brief Encapsulate a string representation of a stack trace on supported platforms. + * Stack traces for code built with optimize=1 (or "Release" configs on Visual + * Studio) may be misleading (missng frames) due to inlining performed by the + * compiler, which is indepenent of the inline=0 / inline=1 build option and + * the __ACE_INLINE__ / ACE_NO_INLINE macros. + * + * A new conversion character, the question mark, was added to ACE_Log_Msg for stack + * trace logging. The %? conversion character was added as a convenience so that users + * need not instantiate an ACE_Stack_Trace instance solely for the purpose of printing + * it in an ACE logging message. The following are functionally equivalent: + * + * \code + * ACE_DEBUG((LM_DEBUG, "%?")); + * + * ACE_Stack_Trace st; + * ACE_DEBUG ((LM_DEBUG, "%s", st.c_str() )); + * \endcode + * + * These usage examples were shown in $ACE_ROOT/tests/Stack_Trace_Test.cpp. + * + * @note The stack trace functionality was currently supported on platforms: + * - Any platform using glibc as its runtime library, or where ACE_HAS_EXECINFO_H is defined + * (this covers Linux and Mac) and gcc version >= 3.3. + * - VxWorks, both kernel and RTP + * - Solaris + * - Windows 32 and 64 bit (Visual C++, excluding WinCE/mobile) + * + * @note Since stack trace buffer size has limitation(@c ACE_STACK_TRACE_SYMBUFSIZ), you will not + * get a complete stack trace if @c ACE_STACK_TRACE_SYMBUFSIZ value is less than actual stack + * trace data length. To get a complete stack trace, you need set @c ACE_STACK_TRACE_SYMBUFSIZ + * with a larger value that is enough for the stack trace data in your @c config.h file + * and rebuild ACE. + * + * @note Using ACE logging mechanism (%?) to log the stack trace also has ACE_MAXLOGMSGLEN size limitation. + * To get a complete stack trace, you could use different output method. Following is an example. + * + * \code + * ACE_Stack_Trace st; + * ACE_OS::printf("at [%s]\n", st.c_str()); + * \endcode + */ +class ACE_Export ACE_Stack_Trace +{ +public: + /** + * @brief Grab a snapshot of the current stack trace and hold it for later use. + * + * @param starting_frame_offset offset into the array of frames to start printing; 0 is the + * platform-specific offset for the first frame, positive numbers give less frames, negative give + * more frames + * @param num_frames the number of stack frames to include (0 indicates platform-specific maximum) + * + */ + explicit ACE_Stack_Trace (ssize_t starting_frame_offset = 0, size_t num_frames = 0); + + /** + * @brief Return buffer as a C-style string. + * @return C-style string with string representation of stack trace. + * @note Lifecycle of string follows lifecycle of ACE_Stack_Trace instance. + */ + const char* c_str() const; + + static const size_t SYMBUFSIZ = ACE_STACK_TRACE_SYMBUFSIZ; + +private: + char buf_[SYMBUFSIZ]; + size_t buflen_; + + static const char UNSUPPORTED[]; + static const char UNABLE_TO_GET_TRACE[]; + + void generate_trace (ssize_t starting_frame_offset, size_t num_frames); +}; + +#include /**/ "ace/post.h" +#endif /* ACE_STACK_TRACE_H */ + diff --git a/dep/acelite/ace/Static_Object_Lock.h b/dep/acelite/ace/Static_Object_Lock.h new file mode 100644 index 00000000000..ad780258ee1 --- /dev/null +++ b/dep/acelite/ace/Static_Object_Lock.h @@ -0,0 +1,78 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Static_Object_Lock.h + * + * $Id: Static_Object_Lock.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author David L. Levine + * @author Matthias Kerkhoff + * @author Per Andersson + */ +//============================================================================= + +#ifndef ACE_STATIC_OBJECT_LOCK_H +#define ACE_STATIC_OBJECT_LOCK_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_THREADS) + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +class ACE_Recursive_Thread_Mutex; + +/** + * @class ACE_Static_Object_Lock + * + * @brief Provide an interface to access a global lock. + * + * This class is used to serialize the creation of static + * singleton objects. It really isn't needed any more, because + * anyone can access ACE_STATIC_OBJECT_LOCK directly. But, it + * is retained for backward compatibility. + */ +class ACE_Export ACE_Static_Object_Lock +{ +public: + /// Static lock access point. + static ACE_Recursive_Thread_Mutex *instance (void); + + /// For use only by ACE_Object_Manager to clean up lock if it + /// what dynamically allocated. + static void cleanup_lock (void); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_THREADS */ + +// hack to get around errors while compiling using split-cpp +#if defined (ACE_HAS_THREADS) + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +# if defined (ACE_IS_SPLITTING) +typedef ACE_Cleanup_Adapter ACE_Static_Object_Lock_Type; + +# if defined (__GNUC__) +// With g++, suppress the warning that this is unused. +static ACE_Static_Object_Lock_Type *ACE_Static_Object_Lock_lock __attribute__ ((unused)) = 0; +# else +static ACE_Static_Object_Lock_Type *ACE_Static_Object_Lock_lock = 0; +# endif /* __GNUC__ */ + +# endif /* ACE_IS_SPLITTING */ + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_THREADS */ + +#include /**/ "ace/post.h" +#endif /* ACE_STATIC_OBJECT_LOCK_H */ diff --git a/dep/acelite/ace/Stats.cpp b/dep/acelite/ace/Stats.cpp new file mode 100644 index 00000000000..840dc40e7f5 --- /dev/null +++ b/dep/acelite/ace/Stats.cpp @@ -0,0 +1,421 @@ +// $Id: Stats.cpp 83735 2008-11-14 09:41:52Z johnnyw $ + +#include "ace/Stats.h" + +#if !defined (__ACE_INLINE__) +# include "ace/Stats.inl" +#endif /* __ACE_INLINE__ */ + +#include "ace/OS_NS_stdio.h" +#include "ace/OS_NS_string.h" + +ACE_RCSID(ace, Stats, "$Id: Stats.cpp 83735 2008-11-14 09:41:52Z johnnyw $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_UINT32 +ACE_Stats_Value::fractional_field (void) const +{ + if (precision () == 0) + { + return 1; + } + else + { + ACE_UINT32 field = 10; + for (u_int i = 0; i < precision () - 1; ++i) + { + field *= 10; + } + + return field; + } +} + +int +ACE_Stats::sample (const ACE_INT32 value) +{ + if (samples_.enqueue_tail (value) == 0) + { + ++number_of_samples_; + if (number_of_samples_ == 0) + { + // That's a lot of samples :-) + overflow_ = EFAULT; + return -1; + } + + if (value < min_) + min_ = value; + + if (value > max_) + max_ = value; + + return 0; + } + else + { + // Probably failed due to running out of memory when trying to + // enqueue the new value. + overflow_ = errno; + return -1; + } +} + +void +ACE_Stats::mean (ACE_Stats_Value &m, + const ACE_UINT32 scale_factor) +{ + if (number_of_samples_ > 0) + { +#if defined ACE_LACKS_LONGLONG_T + // If ACE_LACKS_LONGLONG_T, then ACE_UINT64 is a user-defined class. + // To prevent having to construct a static of that class, declare it + // on the stack, and construct it, in each function that needs it. + const ACE_U_LongLong ACE_STATS_INTERNAL_OFFSET (0, 8); +#else /* ! ACE_LACKS_LONGLONG_T */ + const ACE_UINT64 ACE_STATS_INTERNAL_OFFSET = + ACE_UINT64_LITERAL (0x100000000); +#endif /* ! ACE_LACKS_LONGLONG_T */ + + ACE_UINT64 sum = ACE_STATS_INTERNAL_OFFSET; + ACE_Unbounded_Queue_Iterator i (samples_); + while (! i.done ()) + { + ACE_INT32 *sample; + if (i.next (sample)) + { + sum += *sample; + i.advance (); + } + } + + // sum_ was initialized with ACE_STATS_INTERNAL_OFFSET, so + // subtract that off here. + quotient (sum - ACE_STATS_INTERNAL_OFFSET, + number_of_samples_ * scale_factor, + m); + } + else + { + m.whole (0); + m.fractional (0); + } +} + +int +ACE_Stats::std_dev (ACE_Stats_Value &std_dev, + const ACE_UINT32 scale_factor) +{ + if (number_of_samples_ <= 1) + { + std_dev.whole (0); + std_dev.fractional (0); + } + else + { + const ACE_UINT32 field = std_dev.fractional_field (); + + // The sample standard deviation is: + // + // sqrt (sum (sample_i - mean)^2 / (number_of_samples_ - 1)) + + ACE_UINT64 mean_scaled; + // Calculate the mean, scaled, so that we don't lose its + // precision. + ACE_Stats_Value avg (std_dev.precision ()); + mean (avg, 1u); + avg.scaled_value (mean_scaled); + + // Calculate the summation term, of squared differences from the + // mean. + ACE_UINT64 sum_of_squares = 0; + ACE_Unbounded_Queue_Iterator i (samples_); + while (! i.done ()) + { + ACE_INT32 *sample; + if (i.next (sample)) + { + const ACE_UINT64 original_sum_of_squares = sum_of_squares; + + // Scale up by field width so that we don't lose the + // precision of the mean. Carefully . . . + const ACE_UINT64 product (*sample * field); + + ACE_UINT64 difference; + // NOTE: please do not reformat this code! It // + // works with the Diab compiler the way it is! // + if (product >= mean_scaled) // + { // + difference = product - mean_scaled; // + } // + else // + { // + difference = mean_scaled - product; // + } // + // NOTE: please do not reformat this code! It // + // works with the Diab compiler the way it is! // + + // Square using 64-bit arithmetic. + sum_of_squares += difference * ACE_U64_TO_U32 (difference); + i.advance (); + + if (sum_of_squares < original_sum_of_squares) + { + overflow_ = ENOSPC; + return -1; + } + } + } + + // Divide the summation by (number_of_samples_ - 1), to get the + // variance. In addition, scale the variance down to undo the + // mean scaling above. Otherwise, it can get too big. + ACE_Stats_Value variance (std_dev.precision ()); + quotient (sum_of_squares, + (number_of_samples_ - 1) * field * field, + variance); + + // Take the square root of the variance to get the standard + // deviation. First, scale up . . . + ACE_UINT64 scaled_variance; + variance.scaled_value (scaled_variance); + + // And scale up, once more, because we'll be taking the square + // root. + scaled_variance *= field; + ACE_Stats_Value unscaled_standard_deviation (std_dev.precision ()); + square_root (scaled_variance, + unscaled_standard_deviation); + + // Unscale. + quotient (unscaled_standard_deviation, + scale_factor * field, + std_dev); + } + + return 0; +} + + +void +ACE_Stats::reset (void) +{ + overflow_ = 0u; + number_of_samples_ = 0u; + min_ = 0x7FFFFFFF; + max_ = -0x8000 * 0x10000; + samples_.reset (); +} + +int +ACE_Stats::print_summary (const u_int precision, + const ACE_UINT32 scale_factor, + FILE *file) const +{ + ACE_TCHAR mean_string [128]; + ACE_TCHAR std_dev_string [128]; + ACE_TCHAR min_string [128]; + ACE_TCHAR max_string [128]; + int success = 0; + + for (int tmp_precision = precision; + ! overflow_ && ! success && tmp_precision >= 0; + --tmp_precision) + { + // Build a format string, in case the C library doesn't support %*u. + ACE_TCHAR format[32]; + if (tmp_precision == 0) + ACE_OS::sprintf (format, ACE_TEXT ("%%%d"), tmp_precision); + else + ACE_OS::sprintf (format, ACE_TEXT ("%%d.%%0%du"), tmp_precision); + + ACE_Stats_Value u (tmp_precision); + ((ACE_Stats *) this)->mean (u, scale_factor); + ACE_OS::sprintf (mean_string, format, u.whole (), u.fractional ()); + + ACE_Stats_Value sd (tmp_precision); + if (((ACE_Stats *) this)->std_dev (sd, scale_factor)) + { + success = 0; + continue; + } + else + { + success = 1; + } + ACE_OS::sprintf (std_dev_string, format, sd.whole (), sd.fractional ()); + + ACE_Stats_Value minimum (tmp_precision), maximum (tmp_precision); + if (min_ != 0) + { + const ACE_UINT64 m (min_); + quotient (m, scale_factor, minimum); + } + if (max_ != 0) + { + const ACE_UINT64 m (max_); + quotient (m, scale_factor, maximum); + } + ACE_OS::sprintf (min_string, format, + minimum.whole (), minimum.fractional ()); + ACE_OS::sprintf (max_string, format, + maximum.whole (), maximum.fractional ()); + } + + if (success == 1) + { + ACE_OS::fprintf (file, ACE_TEXT ("samples: %u (%s - %s); mean: ") + ACE_TEXT ("%s; std dev: %s\n"), + samples (), min_string, max_string, + mean_string, std_dev_string); + return 0; + } + else + { + ACE_OS::fprintf (file, + ACE_TEXT ("ACE_Stats::print_summary: OVERFLOW: %s\n"), + ACE_OS::strerror (overflow_)); + + return -1; + } +} + +void +ACE_Stats::quotient (const ACE_UINT64 dividend, + const ACE_UINT32 divisor, + ACE_Stats_Value "ient) +{ + // The whole part of the division comes from simple integer division. + quotient.whole (static_cast (divisor == 0 + ? 0 : dividend / divisor)); + + if (quotient.precision () > 0 || divisor == 0) + { + const ACE_UINT32 field = quotient.fractional_field (); + + // Fractional = (dividend % divisor) * 10^precision / divisor + + // It would be nice to add round-up term: + // Fractional = (dividend % divisor) * 10^precision / divisor + + // 10^precision/2 / 10^precision + // = ((dividend % divisor) * 10^precision + divisor) / + // divisor + quotient.fractional (static_cast ( + dividend % divisor * field / divisor)); + } + else + { + // No fractional portion is requested, so don't bother + // calculating it. + quotient.fractional (0); + } +} + +void +ACE_Stats::quotient (const ACE_Stats_Value ÷nd, + const ACE_UINT32 divisor, + ACE_Stats_Value "ient) +{ + // The whole part of the division comes from simple integer division. + quotient.whole (divisor == 0 ? 0 : dividend.whole () / divisor); + + if (quotient.precision () > 0 || divisor == 0) + { + const ACE_UINT32 field = quotient.fractional_field (); + + // Fractional = (dividend % divisor) * 10^precision / divisor. + quotient.fractional (dividend.whole () % divisor * field / divisor + + dividend.fractional () / divisor); + } + else + { + // No fractional portion is requested, so don't bother + // calculating it. + quotient.fractional (0); + } +} + +void +ACE_Stats::square_root (const ACE_UINT64 n, + ACE_Stats_Value &square_root) +{ + ACE_UINT32 floor = 0; + ACE_UINT32 ceiling = 0xFFFFFFFFu; + ACE_UINT32 mid = 0; + u_int i; + + // The maximum number of iterations is log_2 (2^64) == 64. + for (i = 0; i < 64; ++i) + { + mid = (ceiling - floor) / 2 + floor; + if (floor == mid) + // Can't divide the interval any further. + break; + else + { + // Multiply carefully to avoid overflow. + ACE_UINT64 mid_squared = mid; mid_squared *= mid; + if (mid_squared == n) + break; + else if (mid_squared < n) + floor = mid; + else + ceiling = mid; + } + } + + square_root.whole (mid); + ACE_UINT64 mid_squared = mid; mid_squared *= mid; + + if (square_root.precision () && mid_squared < n) + { + // (mid * 10^precision + fractional)^2 == + // n^2 * 10^(precision * 2) + + const ACE_UINT32 field = square_root.fractional_field (); + + floor = 0; + ceiling = field; + mid = 0; + + // Do the 64-bit arithmetic carefully to avoid overflow. + ACE_UINT64 target = n; + target *= field; + target *= field; + + ACE_UINT64 difference = 0; + + for (i = 0; i < square_root.precision (); ++i) + { + mid = (ceiling - floor) / 2 + floor; + + ACE_UINT64 current = square_root.whole () * field + mid; + current *= square_root.whole () * field + mid; + + if (floor == mid) + { + difference = target - current; + break; + } + else if (current <= target) + floor = mid; + else + ceiling = mid; + } + + // Check to see if the fractional part should be one greater. + ACE_UINT64 next = square_root.whole () * field + mid + 1; + next *= square_root.whole () * field + mid + 1; + + square_root.fractional (next - target < difference ? mid + 1 : mid); + } + else + { + // No fractional portion is requested, so don't bother + // calculating it. + square_root.fractional (0); + } +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Stats.h b/dep/acelite/ace/Stats.h new file mode 100644 index 00000000000..2590ec95c10 --- /dev/null +++ b/dep/acelite/ace/Stats.h @@ -0,0 +1,222 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file Stats.h + * + * $Id: Stats.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author David L. Levine + */ +//========================================================================== + + +#ifndef ACE_STATS_H +#define ACE_STATS_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Unbounded_Queue.h" +#include "ace/Log_Msg.h" +#include "ace/Basic_Stats.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Stats_Value + * + * @brief Helper class for ACE_Stats. + * + * Container struct for 64-bit signed quantity and its + * precision. It would be nicer to use a fixed-point class, but + * this is sufficient. Users typically don't need to use this + * class directly; see ACE_Stats below. + */ +class ACE_Export ACE_Stats_Value +{ +public: + /** + * Constructor, which requires precision in terms of number of + * decimal digits. The more variation in the data, and the greater + * the data values, the smaller the precision must be to avoid + * overflow in the standard deviation calculation. 3 might be a + * good value, or maybe 4. 5 will probably be too large for + * non-trivial data sets. + */ + ACE_Stats_Value (const u_int precision); + + /// Accessor for precision. + u_int precision (void) const; + + /// Set the whole_ field. + void whole (const ACE_UINT32); + + /// Accessor for the whole_ field. + ACE_UINT32 whole (void) const; + + /// Set the fractional_ field. + void fractional (const ACE_UINT32); + + /// Accessor for the fractional_ field. + ACE_UINT32 fractional (void) const; + + /// Calculates the maximum value of the fractional portion, given its + /// precision. + ACE_UINT32 fractional_field (void) const; + + /** + * Access the value as an _unsigned_ 64 bit quantity. It scales the + * value up by {precision} decimal digits, so that no precision will + * be lost. It assumes that {whole_} is >= 0. + */ + void scaled_value (ACE_UINT64 &) const; + + /// Print to stdout. + void dump (void) const; + +private: + + ACE_Stats_Value (void) {} + +private: + /// The integer portion of the value. + ACE_UINT32 whole_; + + /// The fractional portion of the value. + ACE_UINT32 fractional_; + + /** + * The number of decimal digits of precision represented by + * {fractional_}. Not declared const, so the only way to change it + * is via the assignment operator. + */ + u_int precision_; + +}; + +/** + * @class ACE_Stats + * + * @brief Provides simple statistical analysis. + * + * Simple statistical analysis package. Prominent features are: + * -# It does not use any floating point arithmetic. + * -# It handles positive and/or negative sample values. The + * sample value type is ACE_INT32. + * -# It uses 64 bit unsigned, but not 64 bit signed, quantities + * internally. + * -# It checks for overflow of internal state. + * -# It has no static variables of other than built-in types. + * + * Example usage: + * + * @verbatim + * ACE_Stats stats; + * for (u_int i = 0; i < n; ++i) + * { + * const ACE_UINT32 sample = ...; + * stats.sample (sample); + * } + * stats.print_summary (3); + * @endverbatim + */ +class ACE_Export ACE_Stats +{ +public: + /// Default constructor. + ACE_Stats (void); + + /// Provide a new sample. Returns 0 on success, -1 if it fails due + /// to running out of memory, or to rolling over of the sample count. + int sample (const ACE_INT32 value); + + /// Access the number of samples provided so far. + ACE_UINT32 samples (void) const; + + /// Value of the minimum sample provided so far. + ACE_INT32 min_value (void) const; + + /// Value of the maximum sample provided so far. + ACE_INT32 max_value (void) const; + + /** + * Access the mean of all samples provided so far. The fractional + * part is to the specified number of digits. E.g., 3 fractional + * digits specifies that the fractional part is in thousandths. + */ + void mean (ACE_Stats_Value &mean, + const ACE_UINT32 scale_factor = 1); + + /// Access the standard deviation, whole and fractional parts. See + /// description of {mean} method for argument descriptions. + int std_dev (ACE_Stats_Value &std_dev, + const ACE_UINT32 scale_factor = 1); + + /** + * Print summary statistics. If scale_factor is not 1, then the + * results are divided by it, i.e., each of the samples is scaled + * down by it. If internal overflow is reached with the specified + * scale factor, it successively tries to reduce it. Returns -1 if + * there is overflow even with a 0 scale factor. + */ + int print_summary (const u_int precision, + const ACE_UINT32 scale_factor = 1, + FILE * = stdout) const; + + /// Initialize internal state. + void reset (void); + + /// Utility division function, for ACE_UINT64 dividend. + static void quotient (const ACE_UINT64 dividend, + const ACE_UINT32 divisor, + ACE_Stats_Value "ient); + + /// Utility division function, for ACE_Stats_Value dividend. + static void quotient (const ACE_Stats_Value ÷nd, + const ACE_UINT32 divisor, + ACE_Stats_Value "ient); + + /** + * Sqrt function, which uses an oversimplified version of Newton's + * method. It's not fast, but it doesn't require floating point + * support. + */ + static void square_root (const ACE_UINT64 n, + ACE_Stats_Value &square_root); + + /// Print summary statistics to stdout. + void dump (void) const; + +protected: + /// Internal indication of whether there has been overflow. Contains + /// the errno corresponding to the cause of overflow. + u_int overflow_; + + /// Number of samples. + ACE_UINT32 number_of_samples_; + + /// Minimum sample value. + ACE_INT32 min_; + + /// Maximum sample value. + ACE_INT32 max_; + + /// The samples. + ACE_Unbounded_Queue samples_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +# include "ace/Stats.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" + +#endif /* ! ACE_STATS_H */ diff --git a/dep/acelite/ace/Stats.inl b/dep/acelite/ace/Stats.inl new file mode 100644 index 00000000000..4c76838c207 --- /dev/null +++ b/dep/acelite/ace/Stats.inl @@ -0,0 +1,104 @@ +// -*- C++ -*- +// +// $Id: Stats.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE +ACE_Stats_Value::ACE_Stats_Value (const u_int precision) + : whole_ (0), + fractional_ (0), + precision_ (precision) +{ +} + +ACE_INLINE +u_int +ACE_Stats_Value::precision (void) const +{ + return precision_; +} + +ACE_INLINE +void +ACE_Stats_Value::whole (const ACE_UINT32 value) +{ + whole_ = value; +} + +ACE_INLINE +ACE_UINT32 +ACE_Stats_Value::whole (void) const +{ + return whole_; +} + +ACE_INLINE +void +ACE_Stats_Value::fractional (const ACE_UINT32 value) +{ + fractional_ = value; +} + +ACE_INLINE +ACE_UINT32 +ACE_Stats_Value::fractional (void) const +{ + return fractional_; +} + +ACE_INLINE +void +ACE_Stats_Value::scaled_value (ACE_UINT64 &sv) const +{ + sv = whole () * fractional_field () + fractional (); +} + +ACE_INLINE +void +ACE_Stats_Value::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("precision: %u digits; whole: %u, fractional: %u\n"), + precision_, whole_, fractional_)); +#endif /* ACE_HAS_DUMP */ +} + +ACE_INLINE +ACE_Stats::ACE_Stats (void) +{ + reset (); +} + +ACE_INLINE +ACE_UINT32 +ACE_Stats::samples (void) const +{ + return number_of_samples_; +} + +ACE_INLINE +ACE_INT32 +ACE_Stats::min_value (void) const +{ + return min_; +} + +ACE_INLINE +ACE_INT32 +ACE_Stats::max_value (void) const +{ + return max_; +} + +ACE_INLINE +void +ACE_Stats::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + print_summary (3u); +#endif /* ACE_HAS_DUMP */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Strategies.h b/dep/acelite/ace/Strategies.h new file mode 100644 index 00000000000..484ffa9a510 --- /dev/null +++ b/dep/acelite/ace/Strategies.h @@ -0,0 +1,33 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Strategies.h + * + * $Id: Strategies.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_STRATEGIES_H +#define ACE_STRATEGIES_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +/// Place holder for backward compatibility.. +#include "ace/Connection_Recycling_Strategy.h" +#include "ace/Hashable.h" +#include "ace/Notification_Strategy.h" +#include "ace/Reactor_Notification_Strategy.h" +#include "ace/Recyclable.h" +#include "ace/Refcountable.h" + + +#include /**/ "ace/post.h" +#endif /*ACE_STRATEGIES_H*/ diff --git a/dep/acelite/ace/Strategies_T.cpp b/dep/acelite/ace/Strategies_T.cpp new file mode 100644 index 00000000000..fbbc1a5bc93 --- /dev/null +++ b/dep/acelite/ace/Strategies_T.cpp @@ -0,0 +1,1502 @@ +// $Id: Strategies_T.cpp 89510 2010-03-17 12:21:14Z vzykov $ + +#ifndef ACE_STRATEGIES_T_CPP +#define ACE_STRATEGIES_T_CPP + +#include "ace/Strategies_T.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Service_Repository.h" +#include "ace/Service_Types.h" +#include "ace/Thread_Manager.h" +#include "ace/WFMO_Reactor.h" +#include "ace/ACE.h" +#include "ace/OS_NS_dlfcn.h" +#include "ace/OS_NS_string.h" +#include "ace/OS_Errno.h" +#include "ace/Svc_Handler.h" +#if defined (ACE_OPENVMS) +# include "ace/Lib_Find.h" +#endif + +#if !defined (__ACE_INLINE__) +#include "ace/Strategies_T.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template +ACE_Recycling_Strategy::~ACE_Recycling_Strategy (void) +{ +} + +template int +ACE_Recycling_Strategy::assign_recycler (SVC_HANDLER *svc_handler, + ACE_Connection_Recycling_Strategy *recycler, + const void *recycling_act) +{ + svc_handler->recycler (recycler, recycling_act); + return 0; +} + +template int +ACE_Recycling_Strategy::prepare_for_recycling (SVC_HANDLER *svc_handler) +{ + return svc_handler->recycle (); +} + +template +ACE_Singleton_Strategy::~ACE_Singleton_Strategy (void) +{ + ACE_TRACE ("ACE_Singleton_Strategy::~ACE_Singleton_Strategy"); + if (this->delete_svc_handler_) + delete this->svc_handler_; +} + +// Create a Singleton SVC_HANDLER by always returning the same +// SVC_HANDLER. + +template int +ACE_Singleton_Strategy::make_svc_handler (SVC_HANDLER *&sh) +{ + ACE_TRACE ("ACE_Singleton_Strategy::make_svc_handler"); + sh = this->svc_handler_; + return 0; +} + +template int +ACE_Singleton_Strategy::open (SVC_HANDLER *sh, + ACE_Thread_Manager *) +{ + ACE_TRACE ("ACE_Singleton_Strategy::open"); + + if (this->delete_svc_handler_) + delete this->svc_handler_; + + // If is NULL then create a new . + if (sh == 0) + { + ACE_NEW_RETURN (this->svc_handler_, + SVC_HANDLER, + -1); + this->delete_svc_handler_ = true; + } + else + { + this->svc_handler_ = sh; + this->delete_svc_handler_ = false; + } + + return 0; +} + +template int +ACE_DLL_Strategy::open (const ACE_TCHAR dll_name[], + const ACE_TCHAR factory_function[], + const ACE_TCHAR svc_name[], + ACE_Service_Repository *svc_rep, + ACE_Thread_Manager *thr_mgr) +{ + ACE_TRACE ("ACE_DLL_Strategy::open"); + this->inherited::open (thr_mgr); + ACE_OS::strcpy (this->dll_name_, dll_name); + ACE_OS::strcpy (this->factory_function_, factory_function); + ACE_OS::strcpy (this->svc_name_, svc_name); + this->svc_rep_ = svc_rep; + return 0; +} + +// Create a SVC_HANDLER by dynamically linking it from a DLL. + +template int +ACE_DLL_Strategy::make_svc_handler (SVC_HANDLER *&sh) +{ + ACE_TRACE ("ACE_DLL_Strategy::make_svc_handler"); + + // Open the shared library. + ACE_SHLIB_HANDLE handle = ACE_OS::dlopen (this->dll_name_); + + // Extract the factory function. +#if defined (ACE_OPENVMS) + SVC_HANDLER *(*factory)(void) = + (SVC_HANDLER *(*)(void)) ACE::ldsymbol (handle, + this->factory_function_); +#else + SVC_HANDLER *(*factory)(void) = + (SVC_HANDLER *(*)(void)) ACE_OS::dlsym (handle, + this->factory_function_); +#endif + + // Call the factory function to obtain the new SVC_Handler (should + // use RTTI here when it becomes available...) + SVC_HANDLER *svc_handler = 0; + + ACE_ALLOCATOR_RETURN (svc_handler, (*factory)(), -1); + + if (svc_handler != 0) + { + // Create an ACE_Service_Type containing the SVC_Handler and + // insert into this->svc_rep_; + + ACE_Service_Type_Impl *stp = 0; + ACE_NEW_RETURN (stp, + ACE_Service_Object_Type (svc_handler, + this->svc_name_), + -1); + + ACE_Service_Type *srp = 0; + + ACE_NEW_RETURN (srp, + ACE_Service_Type (this->svc_name_, + stp, + handle, + 1), + -1); + if (srp == 0) + { + delete stp; + errno = ENOMEM; + return -1; + } + + if (this->svc_rep_->insert (srp) == -1) + return -1; + // @@ Somehow, we need to deal with this->thr_mgr_... + } + + sh = svc_handler; + return 0; +} + +// Default behavior is to activate the SVC_HANDLER by calling it's +// open() method, which allows the SVC_HANDLER to determine its own +// concurrency strategy. + +template int +ACE_Concurrency_Strategy::activate_svc_handler (SVC_HANDLER *svc_handler, + void *arg) +{ + ACE_TRACE ("ACE_Concurrency_Strategy::activate_svc_handler"); + + int result = 0; + + // See if we should enable non-blocking I/O on the 's + // peer. + if (ACE_BIT_ENABLED (this->flags_, ACE_NONBLOCK) != 0) + { + if (svc_handler->peer ().enable (ACE_NONBLOCK) == -1) + result = -1; + } + // Otherwise, make sure it's disabled by default. + else if (svc_handler->peer ().disable (ACE_NONBLOCK) == -1) + result = -1; + + if (result == 0 && svc_handler->open (arg) == -1) + result = -1; + + if (result == -1) + // The connection was already made; so this close is a "normal" close + // operation. + svc_handler->close (NORMAL_CLOSE_OPERATION); + + return result; +} + +template int +ACE_Reactive_Strategy::open (ACE_Reactor *reactor, + ACE_Reactor_Mask mask, + int flags) +{ + ACE_TRACE ("ACE_Reactive_Strategy::open"); + this->reactor_ = reactor; + this->mask_ = mask; + this->flags_ = flags; + + // Must have a + if (this->reactor_ == 0) + return -1; + else + return 0; +} + +template int +ACE_Reactive_Strategy::activate_svc_handler (SVC_HANDLER *svc_handler, + void *arg) +{ + ACE_TRACE ("ACE_Reactive_Strategy::activate_svc_handler"); + + int result = 0; + + if (this->reactor_ == 0) + result = -1; + + // Register with the Reactor with the appropriate . + else if (this->reactor_->register_handler (svc_handler, this->mask_) == -1) + result = -1; + + // If the implementation of the reactor uses event associations + else if (this->reactor_->uses_event_associations ()) + { + // If we don't have non-block on, it won't work with + // WFMO_Reactor + // This maybe too harsh + // if (!ACE_BIT_ENABLED (this->flags_, ACE_NONBLOCK)) + // goto failure; + if (svc_handler->open (arg) != -1) + return 0; + else + result = -1; + } + else + // Call up to our parent to do the SVC_HANDLER initialization. + return this->inherited::activate_svc_handler (svc_handler, arg); + + if (result == -1) + // The connection was already made; so this close is a "normal" close + // operation. + svc_handler->close (NORMAL_CLOSE_OPERATION); + + return result; +} + +template int +ACE_Thread_Strategy::open (ACE_Thread_Manager *thr_mgr, + long thr_flags, + int n_threads, + int flags) +{ + ACE_TRACE ("ACE_Thread_Strategy::open"); + this->thr_mgr_ = thr_mgr; + this->n_threads_ = n_threads; + this->thr_flags_ = thr_flags; + this->flags_ = flags; + + // Must have a thread manager! + if (this->thr_mgr_ == 0) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("error: must have a non-NULL thread manager\n")), + -1); + else + return 0; +} + +template int +ACE_Thread_Strategy::activate_svc_handler (SVC_HANDLER *svc_handler, + void *arg) +{ + ACE_TRACE ("ACE_Thread_Strategy::activate_svc_handler"); + // Call up to our parent to do the SVC_HANDLER initialization. + if (this->inherited::activate_svc_handler (svc_handler, + arg) == -1) + return -1; + else + // Turn the into an active object (if it isn't + // already one as a result of the first activation...) + return svc_handler->activate (this->thr_flags_, + this->n_threads_); +} + +template int +ACE_Accept_Strategy::open + (const ACE_PEER_ACCEPTOR_ADDR &local_addr, bool reuse_addr) +{ + this->reuse_addr_ = reuse_addr; + this->peer_acceptor_addr_ = local_addr; + if (this->peer_acceptor_.open (local_addr, reuse_addr) == -1) + return -1; + + // Set the peer acceptor's handle into non-blocking mode. This is a + // safe-guard against the race condition that can otherwise occur + // between the time when was interrupted. + if (ACE_Sig_Handler::sig_pending () != 0) + { + ACE_Sig_Handler::sig_pending (0); + + // This piece of code comes from the old TP_Reactor. We did not + // handle signals at all then. If we happen to handle signals + // in the TP_Reactor, we should then start worryiung about this + // - Bala 21-Aug- 01 +if 0 + // Not sure if this should be done in the TP_Reactor + // case... leave it out for now. -Steve Huston 22-Aug-00 + + // If any HANDLES in the are activated as a + // result of signals they should be dispatched since + // they may be time critical... + active_handle_count = this->any_ready (dispatch_set); +else + // active_handle_count = 0; +endif + + // Record the fact that the Reactor has dispatched a + // handle_signal() method. We need this to return the + // appropriate count. + return 1; + } + + return -1; +} +#endif // #if 0 + + +int +ACE_TP_Reactor::handle_timer_events (int & /*event_count*/, + ACE_TP_Token_Guard &guard) +{ + if (this->timer_queue_ == 0 || this->timer_queue_->is_empty()) + { // Empty timer queue so cannot have any expired timers. + return 0; + } + + // Get the current time + ACE_Time_Value cur_time (this->timer_queue_->gettimeofday () + + this->timer_queue_->timer_skew ()); + + // Look for a node in the timer queue whose timer <= the present + // time. + ACE_Timer_Node_Dispatch_Info info; + + if (this->timer_queue_->dispatch_info (cur_time, info)) + { + const void *upcall_act = 0; + + // Preinvoke. + this->timer_queue_->preinvoke (info, cur_time, upcall_act); + + // Release the token before dispatching notifies... + guard.release_token (); + + // call the functor + this->timer_queue_->upcall (info, cur_time); + + // Postinvoke + this->timer_queue_->postinvoke (info, cur_time, upcall_act); + + // We have dispatched a timer + return 1; + } + + return 0; +} + +int +ACE_TP_Reactor::handle_notify_events (int & /*event_count*/, + ACE_TP_Token_Guard &guard) +{ + // Get the handle on which notify calls could have occured + ACE_HANDLE notify_handle = this->get_notify_handle (); + + int result = 0; + + // The notify was not in the list returned by + // wait_for_multiple_events (). + if (notify_handle == ACE_INVALID_HANDLE) + return result; + + // Now just do a read on the pipe.. + ACE_Notification_Buffer buffer; + + // Clear the handle of the read_mask of our + this->ready_set_.rd_mask_.clr_bit (notify_handle); + + // Keep reading notifies till we empty it or till we have a + // dispatchable buffer + while (this->notify_handler_->read_notify_pipe (notify_handle, buffer) > 0) + { + // Just figure out whether we can read any buffer that has + // dispatchable info. If not we have just been unblocked by + // another thread trying to update the reactor. If we get any + // buffer that needs dispatching we will dispatch that after + // releasing the lock + if (this->notify_handler_->is_dispatchable (buffer) > 0) + { + // Release the token before dispatching notifies... + guard.release_token (); + + // Dispatch the upcall for the notify + this->notify_handler_->dispatch_notify (buffer); + + // We had a successful dispatch. + result = 1; + + // break out of the while loop + break; + } + } + + // If we did some work, then we just return 1 which will allow us + // to get out of here. If we return 0, then we will be asked to do + // some work ie. dispacth socket events + return result; +} + +int +ACE_TP_Reactor::handle_socket_events (int &event_count, + ACE_TP_Token_Guard &guard) +{ + + // We got the lock, lets handle some I/O events. + ACE_EH_Dispatch_Info dispatch_info; + + this->get_socket_event_info (dispatch_info); + + // If there is any event handler that is ready to be dispatched, the + // dispatch information is recorded in dispatch_info. + if (!dispatch_info.dispatch ()) + { + // Check for removed handlers. + if (dispatch_info.event_handler_ == 0) + { + this->handler_rep_.unbind(dispatch_info.handle_, + dispatch_info.mask_); + } + + + return 0; + } + + // Suspend the handler so that other threads don't start dispatching + // it, if we can't suspend then return directly + // + // NOTE: This check was performed in older versions of the + // TP_Reactor. Looks like it is a waste.. + if (dispatch_info.event_handler_ != this->notify_handler_) + if (this->suspend_i (dispatch_info.handle_) == -1) + return 0; + + // Call add_reference() if needed. + if (dispatch_info.reference_counting_required_) + dispatch_info.event_handler_->add_reference (); + + // Release the lock. Others threads can start waiting. + guard.release_token (); + + int result = 0; + + // If there was an event handler ready, dispatch it. + // Decrement the event left + --event_count; + + // Dispatched an event + if (this->dispatch_socket_event (dispatch_info) == 0) + ++result; + + return result; +} + +int +ACE_TP_Reactor::get_event_for_dispatching (ACE_Time_Value *max_wait_time) +{ + // If the reactor handler state has changed, clear any remembered + // ready bits and re-scan from the master wait_set. + if (this->state_changed_) + { + this->ready_set_.rd_mask_.reset (); + this->ready_set_.wr_mask_.reset (); + this->ready_set_.ex_mask_.reset (); + + this->state_changed_ = false; + } + else + { + // This is a hack... somewhere, under certain conditions (which + // I don't understand...) the mask will have all of its bits clear, + // yet have a size_ > 0. This is an attempt to remedy the affect, + // without knowing why it happens. + + this->ready_set_.rd_mask_.sync (this->ready_set_.rd_mask_.max_set ()); + this->ready_set_.wr_mask_.sync (this->ready_set_.wr_mask_.max_set ()); + this->ready_set_.ex_mask_.sync (this->ready_set_.ex_mask_.max_set ()); + } + + return this->wait_for_multiple_events (this->ready_set_, max_wait_time); +} + +int +ACE_TP_Reactor::get_socket_event_info (ACE_EH_Dispatch_Info &event) +{ + // Check for dispatch in write, except, read. Only catch one, but if + // one is caught, be sure to clear the handle from each mask in case + // there is more than one mask set for it. This would cause problems + // if the handler is suspended for dispatching, but its set bit in + // another part of ready_set_ kept it from being dispatched. + int found_io = 0; + ACE_HANDLE handle; + + // @@todo: We can do quite a bit of code reduction here. Let me get + // it to work before I do this. + { + ACE_Handle_Set_Iterator handle_iter (this->ready_set_.wr_mask_); + + while (!found_io && (handle = handle_iter ()) != ACE_INVALID_HANDLE) + { + if (this->is_suspended_i (handle)) + continue; + + // Remember this info + event.set (handle, + this->handler_rep_.find (handle), + ACE_Event_Handler::WRITE_MASK, + &ACE_Event_Handler::handle_output); + + this->clear_handle_read_set (handle); + found_io = 1; + } + } + + if (!found_io) + { + ACE_Handle_Set_Iterator handle_iter (this->ready_set_.ex_mask_); + + while (!found_io && (handle = handle_iter ()) != ACE_INVALID_HANDLE) + { + if (this->is_suspended_i (handle)) + continue; + + // Remember this info + event.set (handle, + this->handler_rep_.find (handle), + ACE_Event_Handler::EXCEPT_MASK, + &ACE_Event_Handler::handle_exception); + + this->clear_handle_read_set (handle); + + found_io = 1; + } + } + + if (!found_io) + { + ACE_Handle_Set_Iterator handle_iter (this->ready_set_.rd_mask_); + + while (!found_io && (handle = handle_iter ()) != ACE_INVALID_HANDLE) + { + if (this->is_suspended_i (handle)) + continue; + + // Remember this info + event.set (handle, + this->handler_rep_.find (handle), + ACE_Event_Handler::READ_MASK, + &ACE_Event_Handler::handle_input); + + this->clear_handle_read_set (handle); + found_io = 1; + } + } + + return found_io; +} + +// Dispatches a single event handler +int +ACE_TP_Reactor::dispatch_socket_event (ACE_EH_Dispatch_Info &dispatch_info) +{ + ACE_TRACE ("ACE_TP_Reactor::dispatch_socket_event"); + + ACE_Event_Handler * const event_handler = dispatch_info.event_handler_; + ACE_EH_PTMF const callback = dispatch_info.callback_; + + // Check for removed handlers. + if (event_handler == 0) + return -1; + + // Upcall. If the handler returns positive value (requesting a + // reactor callback) don't set the ready-bit because it will be + // ignored if the reactor state has changed. Just call back + // as many times as the handler requests it. Other threads are off + // handling other things. + int status = 1; + while (status > 0) + status = (event_handler->*callback) (dispatch_info.handle_); + + // Post process socket event + return this->post_process_socket_event (dispatch_info, status); +} + +int +ACE_TP_Reactor::post_process_socket_event (ACE_EH_Dispatch_Info &dispatch_info, + int status) +{ + int result = 0; + + // First check if we really have to post process something, if not, then + // we don't acquire the token which saves us a lot of time. + if (status < 0 || + (dispatch_info.event_handler_ != this->notify_handler_ && + dispatch_info.resume_flag_ == + ACE_Event_Handler::ACE_REACTOR_RESUMES_HANDLER)) + { + // Get the reactor token and with this token acquired remove first the + // handler and resume it at the same time. This must be atomic, see also + // bugzilla 2395. When this is not atomic it can be that we resume the + // handle after it is reused by the OS. + ACE_TP_Token_Guard guard (this->token_); + + result = guard.acquire_token (); + + // If the guard is NOT the owner just return the retval + if (!guard.is_owner ()) + return result; + + // A different event handler may have been registered during the + // upcall if the handle was closed and then reopened, for + // example. Make sure we're removing and/or resuming the event + // handler used during the upcall. + ACE_Event_Handler const * const eh = + this->handler_rep_.find (dispatch_info.handle_); + + // Only remove or resume the event handler used during the + // upcall. + if (eh == dispatch_info.event_handler_) + { + if (status < 0) + { + result = + this->remove_handler_i (dispatch_info.handle_, + dispatch_info.mask_); + } + + // Resume handler if required. + if (dispatch_info.event_handler_ != this->notify_handler_ && + dispatch_info.resume_flag_ == + ACE_Event_Handler::ACE_REACTOR_RESUMES_HANDLER) + this->resume_i (dispatch_info.handle_); + } + } + + // Call remove_reference() if needed. + if (dispatch_info.reference_counting_required_) + dispatch_info.event_handler_->remove_reference (); + + return result; +} + +int +ACE_TP_Reactor::resumable_handler (void) +{ + return 1; +} + +int +ACE_TP_Reactor::handle_events (ACE_Time_Value &max_wait_time) +{ + return this->handle_events (&max_wait_time); +} + +void +ACE_TP_Reactor::notify_handle (ACE_HANDLE, + ACE_Reactor_Mask, + ACE_Handle_Set &, + ACE_Event_Handler *eh, + ACE_EH_PTMF) +{ + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("ACE_TP_Reactor::notify_handle: ") + ACE_TEXT ("Wrong version of notify_handle() got called\n"))); + + ACE_ASSERT (eh == 0); + ACE_UNUSED_ARG (eh); +} + +ACE_HANDLE +ACE_TP_Reactor::get_notify_handle (void) +{ + // Call the notify handler to get a handle on which we would have a + // notify waiting + ACE_HANDLE const read_handle = + this->notify_handler_->notify_handle (); + + // Check whether the rd_mask has been set on that handle. If so + // return the handle. + if (read_handle != ACE_INVALID_HANDLE && + this->ready_set_.rd_mask_.is_set (read_handle)) + { + return read_handle; + } + + // None found.. + return ACE_INVALID_HANDLE; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/TP_Reactor.h b/dep/acelite/ace/TP_Reactor.h new file mode 100644 index 00000000000..33e00c2e57f --- /dev/null +++ b/dep/acelite/ace/TP_Reactor.h @@ -0,0 +1,320 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file TP_Reactor.h + * + * $Id: TP_Reactor.h 82723 2008-09-16 09:35:44Z johnnyw $ + * + * The ACE_TP_Reactor (aka, Thread Pool Reactor) uses the + * Leader/Followers pattern to demultiplex events among a pool of + * threads. When using a thread pool reactor, an application + * pre-spawns a fixed number of threads. When these threads + * invoke the ACE_TP_Reactor's handle_events() method, one thread + * will become the leader and wait for an event. The other + * follower threads will queue up waiting for their turn to become + * the leader. When an event occurs, the leader will pick a + * follower to become the leader and go on to handle the event. + * The consequence of using ACE_TP_Reactor is the amortization of + * the costs used to create threads. The context switching cost + * will also reduce. Moreover, the total resources used by + * threads are bounded because there are a fixed number of threads. + * + * @author Irfan Pyarali + * @author Nanbor Wang + */ +//============================================================================= + + +#ifndef ACE_TP_REACTOR_H +#define ACE_TP_REACTOR_H + +#include /**/ "ace/pre.h" + +#include "ace/Select_Reactor.h" +#include "ace/Timer_Queue.h" /* Simple forward decl won't work... */ + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_EH_Dispatch_Info + * + * @brief This structure contains information of the activated event + * handler. + */ +class ACE_EH_Dispatch_Info +{ +public: + ACE_EH_Dispatch_Info (void); + + void set (ACE_HANDLE handle, + ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask, + ACE_EH_PTMF callback); + + bool dispatch (void) const; + + ACE_HANDLE handle_; + ACE_Event_Handler *event_handler_; + ACE_Reactor_Mask mask_; + ACE_EH_PTMF callback_; + int resume_flag_; + bool reference_counting_required_; + +private: + bool dispatch_; + + // Disallow copying and assignment. + ACE_EH_Dispatch_Info (const ACE_EH_Dispatch_Info &); + ACE_EH_Dispatch_Info &operator= (const ACE_EH_Dispatch_Info &); +}; + + +/** + * @class ACE_TP_Token_Guard + * + * @brief A helper class that helps grabbing, releasing and waiting + * on tokens for a thread that tries calling handle_events (). + * + * In short, this class will be owned by one thread by creating on the + * stack. This class gives the status of the ownership of the token + * and manages the ownership + */ + +class ACE_TP_Token_Guard +{ +public: + + /// Constructor that will grab the token for us + ACE_TP_Token_Guard (ACE_Select_Reactor_Token &token); + + /// Destructor. This will release the token if it hasnt been + /// released till this point + ~ACE_TP_Token_Guard (void); + + /// Release the token .. + void release_token (void); + + /// Returns whether the thread that created this object ownes the + /// token or not. + bool is_owner (void); + + /// A helper method that grabs the token for us, after which the + /// thread that owns that can do some actual work. + int acquire_read_token (ACE_Time_Value *max_wait_time = 0); + + /** + * A helper method that grabs the token for us, after which the + * thread that owns that can do some actual work. This differs from + * acquire_read_token() as it uses acquire () to get the token instead of + * acquire_read () + */ + int acquire_token (ACE_Time_Value *max_wait_time = 0); + +private: + + // Disallow default construction. + ACE_TP_Token_Guard (void); + + // Disallow copying and assignment. + ACE_TP_Token_Guard (const ACE_TP_Token_Guard &); + ACE_TP_Token_Guard &operator= (const ACE_TP_Token_Guard &); + +private: + + /// The Select Reactor token. + ACE_Select_Reactor_Token &token_; + + /// Flag that indicate whether the thread that created this object + /// owns the token or not. A value of false indicates that this class + /// hasnt got the token (and hence the thread) and a value of true + /// vice-versa. + bool owner_; + +}; + +/** + * @class ACE_TP_Reactor + * + * @brief Specialization of ACE_Select_Reactor to support thread-pool + * based event dispatching. + * + * One of the shortcomings of the ACE_Select_Reactor is that it + * does not support a thread pool-based event dispatching model, + * similar to the one in ACE_WFMO_Reactor. In ACE_Select_Reactor, only + * thread can call handle_events() at any given time. ACE_TP_Reactor + * removes this short-coming. + * + * ACE_TP_Reactor is a specialization of ACE_Select_Reactor to support + * thread pool-based event dispatching. This reactor takes advantage + * of the fact that events reported by @c select() are persistent if not + * acted upon immediately. It works by remembering the event handler + * which was just activated, suspending it for further I/O activities, + * releasing the internal lock (so that another thread can start waiting + * in the event loop) and then dispatching the event's handler outside the + * scope of the reactor lock. After the event handler has been dispatched + * the event handler is resumed for further I/O activity. + * + * This reactor implementation is best suited for situations when the + * callbacks to event handlers can take arbitrarily long and/or a number + * of threads are available to run the event loop. Note that I/O-processing + * callback code in event handlers (e.g. handle_input()) does not have to + * be modified or made thread-safe for this reactor. This is because + * before an I/O event is dispatched to an event handler, the handler is + * suspended; it is resumed by the reactor after the upcall completes. + * Therefore, multiple I/O events will not be made to one event handler + * multiple threads simultaneously. This suspend/resume protection does not + * apply to either timers scheduled with the reactor or to notifications + * requested via the reactor. When using timers and/or notifications you + * must provide proper protection for your class in the context of multiple + * threads. + */ +class ACE_Export ACE_TP_Reactor : public ACE_Select_Reactor +{ +public: + + /// Initialize ACE_TP_Reactor with the default size. + ACE_TP_Reactor (ACE_Sig_Handler * = 0, + ACE_Timer_Queue * = 0, + bool mask_signals = true, + int s_queue = ACE_Select_Reactor_Token::FIFO); + + /** + * Initialize the ACE_TP_Reactor to manage + * @a max_number_of_handles. If @a restart is non-0 then the + * ACE_Reactor's @c handle_events() method will be restarted + * automatically when @c EINTR occurs. If @a sh or + * @a tq are non-0 they are used as the signal handler and + * timer queue, respectively. + */ + ACE_TP_Reactor (size_t max_number_of_handles, + bool restart = false, + ACE_Sig_Handler *sh = 0, + ACE_Timer_Queue *tq = 0, + bool mask_signals = true, + int s_queue = ACE_Select_Reactor_Token::FIFO); + + /** + * This event loop driver that blocks for @a max_wait_time before + * returning. It will return earlier if timer events, I/O events, + * or signal events occur. Note that @a max_wait_time can be 0, in + * which case this method blocks indefinitely until events occur. + * + * @a max_wait_time is decremented to reflect how much time this call + * took. For instance, if a time value of 3 seconds is passed to + * handle_events and an event occurs after 2 seconds, + * @a max_wait_time will equal 1 second. This can be used if an + * application wishes to handle events for some fixed amount of + * time. + * + * @return The total number of events that were dispatched; 0 if the + * @a max_wait_time elapsed without dispatching any handlers, or -1 + * if an error occurs (check @c errno for more information). + */ + virtual int handle_events (ACE_Time_Value *max_wait_time = 0); + + virtual int handle_events (ACE_Time_Value &max_wait_time); + + /// Does the reactor allow the application to resume the handle on + /// its own ie. can it pass on the control of handle resumption to + /// the application. The TP reactor has can allow applications to + /// resume handles. So return a positive value. + virtual int resumable_handler (void); + + /// Called from handle events + static void no_op_sleep_hook (void *); + + /// The ACE_TP_Reactor implementation does not have a single owner thread. + /// Attempts to set the owner explicitly are ignored. The reported owner + /// thread is the current Leader in the pattern. + virtual int owner (ACE_thread_t n_id, ACE_thread_t *o_id = 0); + + /// Return the thread ID of the current Leader. + virtual int owner (ACE_thread_t *t_id); + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + // = Internal methods that do the actual work. + + /// Template method from the base class. + virtual void clear_dispatch_mask (ACE_HANDLE handle, + ACE_Reactor_Mask mask); + + /// Dispatch just 1 signal, timer, notification handlers + int dispatch_i (ACE_Time_Value *max_wait_time, + ACE_TP_Token_Guard &guard); + + /// Get the event that needs dispatching. It could be either a + /// signal, timer, notification handlers or return possibly 1 I/O + /// handler for dispatching. In the most common use case, this would + /// return 1 I/O handler for dispatching + int get_event_for_dispatching (ACE_Time_Value *max_wait_time); + +#if 0 + // @Ciju + // signal handling isn't in a production state yet. + // Commenting it out for now. + + /// Method to handle signals + /// @note It is just busted at this point in time. + int handle_signals (int &event_count, + ACE_TP_Token_Guard &g); +#endif // #if 0 + + /// Handle timer events + int handle_timer_events (int &event_count, + ACE_TP_Token_Guard &g); + + /// Handle notify events + int handle_notify_events (int &event_count, + ACE_TP_Token_Guard &g); + + /// handle socket events + int handle_socket_events (int &event_count, + ACE_TP_Token_Guard &g); + + /// This method shouldn't get called. + virtual void notify_handle (ACE_HANDLE handle, + ACE_Reactor_Mask mask, + ACE_Handle_Set &, + ACE_Event_Handler *eh, + ACE_EH_PTMF callback); +private: + + /// Get the handle of the notify pipe from the ready set if there is + /// an event in the notify pipe. + ACE_HANDLE get_notify_handle (void); + + /// Get socket event dispatch information. + int get_socket_event_info (ACE_EH_Dispatch_Info &info); + + /// Notify the appropriate in the context of the + /// associated with that a particular event has occurred. + int dispatch_socket_event (ACE_EH_Dispatch_Info &dispatch_info); + + /// Clear the @a handle from the read_set + void clear_handle_read_set (ACE_HANDLE handle); + + int post_process_socket_event (ACE_EH_Dispatch_Info &dispatch_info,int status); + +private: + /// Deny access since member-wise won't work... + ACE_TP_Reactor (const ACE_TP_Reactor &); + ACE_TP_Reactor &operator = (const ACE_TP_Reactor &); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/TP_Reactor.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" + +#endif /* ACE_TP_REACTOR_H */ diff --git a/dep/acelite/ace/TP_Reactor.inl b/dep/acelite/ace/TP_Reactor.inl new file mode 100644 index 00000000000..2b14a8c9b96 --- /dev/null +++ b/dep/acelite/ace/TP_Reactor.inl @@ -0,0 +1,119 @@ +// -*- C++ -*- +// +// $Id: TP_Reactor.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/************************************************************************/ +// Methods for ACE_EH_Dispatch_Info +/************************************************************************/ + +ACE_INLINE +ACE_EH_Dispatch_Info::ACE_EH_Dispatch_Info (void) : + handle_ (ACE_INVALID_HANDLE), + event_handler_ (0), + mask_ (ACE_Event_Handler::NULL_MASK), + callback_ (0), + resume_flag_ (ACE_Event_Handler::ACE_REACTOR_RESUMES_HANDLER), + reference_counting_required_ (false), + dispatch_ (false) +{ +} + +ACE_INLINE void +ACE_EH_Dispatch_Info::set (ACE_HANDLE handle, + ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask, + ACE_EH_PTMF callback) +{ + this->dispatch_ = true; + + this->handle_ = handle; + this->event_handler_ = event_handler; + this->mask_ = mask; + this->callback_ = callback; + if (event_handler_) + { + this->resume_flag_ = event_handler->resume_handler (); + this->reference_counting_required_ = + (event_handler_->reference_counting_policy ().value () == + ACE_Event_Handler::Reference_Counting_Policy::ENABLED); + } + else + this->dispatch_ = false; +} + +ACE_INLINE bool +ACE_EH_Dispatch_Info::dispatch (void) const +{ + return this->dispatch_; +} + +/************************************************************************/ +// Methods for ACE_TP_Token_Guard +/************************************************************************/ + +ACE_INLINE +ACE_TP_Token_Guard::ACE_TP_Token_Guard (ACE_Select_Reactor_Token &token) + + : token_ (token), + owner_ (false) +{ +} + +ACE_INLINE +ACE_TP_Token_Guard::~ACE_TP_Token_Guard (void) +{ + if (this->owner_) + { + ACE_MT (this->token_.release ()); + this->owner_ = false; + } +} + +ACE_INLINE void +ACE_TP_Token_Guard::release_token (void) +{ + if (this->owner_) + { + ACE_MT (this->token_.release ()); + + // We are not the owner anymore.. + this->owner_ = false; + } +} + +ACE_INLINE bool +ACE_TP_Token_Guard::is_owner (void) +{ + return this->owner_; +} + + +/************************************************************************/ +// Methods for ACE_TP_Reactor +/************************************************************************/ + +ACE_INLINE void +ACE_TP_Reactor::no_op_sleep_hook (void *) +{ +} + +ACE_INLINE void +ACE_TP_Reactor::clear_handle_read_set (ACE_HANDLE handle) +{ + this->ready_set_.wr_mask_.clr_bit (handle); + this->ready_set_.ex_mask_.clr_bit (handle); + this->ready_set_.rd_mask_.clr_bit (handle); +} + +ACE_INLINE void +ACE_TP_Reactor::clear_dispatch_mask (ACE_HANDLE , + ACE_Reactor_Mask ) +{ + this->ready_set_.rd_mask_.reset (); + this->ready_set_.wr_mask_.reset (); + this->ready_set_.ex_mask_.reset (); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/TSS_Adapter.cpp b/dep/acelite/ace/TSS_Adapter.cpp new file mode 100644 index 00000000000..da6218dddb8 --- /dev/null +++ b/dep/acelite/ace/TSS_Adapter.cpp @@ -0,0 +1,45 @@ +/** + * @file TSS_Adapter.cpp + * + * $Id: TSS_Adapter.cpp 80826 2008-03-04 14:51:23Z wotte $ + * + * Originally in Synch.cpp + * + * @author Douglas C. Schmidt + */ + +#include "ace/TSS_Adapter.h" + +ACE_RCSID(ace, TSS_Adapter, "$Id: TSS_Adapter.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_TSS_Adapter::ACE_TSS_Adapter (void *object, ACE_THR_DEST f) + : ts_obj_ (object), + func_ (f) +{ + // ACE_TRACE ("ACE_TSS_Adapter::ACE_TSS_Adapter"); +} + +void +ACE_TSS_Adapter::cleanup (void) +{ + // ACE_TRACE ("ACE_TSS_Adapter::cleanup"); + (*this->func_)(this->ts_obj_); // call cleanup routine for ts_obj_ +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +extern "C" void +ACE_TSS_C_cleanup (void *object) +{ + // ACE_TRACE ("ACE_TSS_C_cleanup"); + if (object != 0) + { + ACE_TSS_Adapter * const tss_adapter = (ACE_TSS_Adapter *) object; + // Perform cleanup on the real TS object. + tss_adapter->cleanup (); + // Delete the adapter object. + delete tss_adapter; + } +} diff --git a/dep/acelite/ace/TSS_Adapter.h b/dep/acelite/ace/TSS_Adapter.h new file mode 100644 index 00000000000..b8ff85e3210 --- /dev/null +++ b/dep/acelite/ace/TSS_Adapter.h @@ -0,0 +1,61 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file TSS_Adapter.h + * + * $Id: TSS_Adapter.h 80826 2008-03-04 14:51:23Z wotte $ + * + * Originally in Synch.h + * + * @author Douglas C. Schmidt + */ +//========================================================================== + +#ifndef ACE_TSS_ADAPTER_H +#define ACE_TSS_ADAPTER_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_TSS_Adapter + * + * @brief This class encapsulates a TSS object and its associated + * C++ destructor function. It is used by the ACE_TSS... + * methods (in Synch_T.cpp) in order to allow an extern + * "C" cleanup routine to be used. Needed by the "frigging" + * MVS C++ compiler. + * + * Objects of this class are stored in thread specific + * storage. ts_obj_ points to the "real" object and + * func_ is a pointer to the C++ cleanup function for ts_obj_. + */ +class ACE_Export ACE_TSS_Adapter +{ +public: + /// Initialize the adapter. + ACE_TSS_Adapter (void *object, ACE_THR_DEST f); + + /// Perform the cleanup operation. + void cleanup (void); + +//private: + + /// The real TS object. + void * const ts_obj_; + + /// The real cleanup routine for ts_obj; + ACE_THR_DEST func_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" +#endif /* ACE_TSS_ADAPTER_H */ diff --git a/dep/acelite/ace/TSS_T.cpp b/dep/acelite/ace/TSS_T.cpp new file mode 100644 index 00000000000..79603f8467c --- /dev/null +++ b/dep/acelite/ace/TSS_T.cpp @@ -0,0 +1,709 @@ +// $Id: TSS_T.cpp 91136 2010-07-20 08:56:37Z vzykov $ + +#ifndef ACE_TSS_T_CPP +#define ACE_TSS_T_CPP + +#include "ace/TSS_T.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (__ACE_INLINE__) +#include "ace/TSS_T.inl" +#endif /* __ACE_INLINE__ */ + +#include "ace/Thread.h" +#include "ace/Log_Msg.h" +#include "ace/Guard_T.h" +#include "ace/OS_NS_stdio.h" + +#if defined (ACE_HAS_THR_C_DEST) +# include "ace/TSS_Adapter.h" +#endif /* ACE_HAS_THR_C_DEST */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_TSS) + +#if defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION)) +# if defined (ACE_HAS_THR_C_DEST) +extern "C" void ACE_TSS_C_cleanup (void *); // defined in Synch.cpp +# endif /* ACE_HAS_THR_C_DEST */ +#endif /* defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION)) */ + +template +ACE_TSS::~ACE_TSS (void) +{ +#if defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION)) + if (this->once_) + { +# if defined (ACE_HAS_THR_C_DEST) + ACE_TSS_Adapter *tss_adapter = this->ts_value (); + this->ts_value (0); + ACE_TSS_C_cleanup (tss_adapter); +# else + TYPE *ts_obj = this->ts_value (); + this->ts_value (0); + ACE_TSS::cleanup (ts_obj); +# endif /* ACE_HAS_THR_C_DEST */ + + ACE_OS::thr_key_detach (this->key_, this); + ACE_OS::thr_keyfree (this->key_); + } +#else // defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION)) + // We own it, we need to delete it. + delete type_; +#endif // defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION)) +} + +template TYPE * +ACE_TSS::operator-> () const +{ + return this->ts_get (); +} + +template +ACE_TSS::operator TYPE *(void) const +{ + return this->ts_get (); +} + +template TYPE * +ACE_TSS::make_TSS_TYPE (void) const +{ + TYPE *temp = 0; + ACE_NEW_RETURN (temp, + TYPE, + 0); + return temp; +} + +template void +ACE_TSS::dump (void) const +{ +#if defined (ACE_HAS_DUMP) +// ACE_TRACE ("ACE_TSS::dump"); +#if defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION)) + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + this->keylock_.dump (); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("key_ = %d\n"), this->key_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nonce_ = %d\n"), this->once_)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION)) */ +#endif /* ACE_HAS_DUMP */ +} + +#if defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION)) + +template void +ACE_TSS::cleanup (void *ptr) +{ + // Cast this to the concrete TYPE * so the destructor gets called. + delete (TYPE *) ptr; +} + +template int +ACE_TSS::ts_init (void) +{ + // Ensure that we are serialized! + ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->keylock_, 0); + + // Use the Double-Check pattern to make sure we only create the key + // once! + if (!this->once_) + { + if (ACE_Thread::keycreate (&this->key_, +#if defined (ACE_HAS_THR_C_DEST) + &ACE_TSS_C_cleanup, +#else + &ACE_TSS::cleanup, +#endif /* ACE_HAS_THR_C_DEST */ + (void *) this) != 0) + return -1; // Major problems, this should *never* happen! + else + { + // This *must* come last to avoid race conditions! + this->once_ = true; + return 0; + } + } + + return 0; +} + +template +ACE_TSS::ACE_TSS (TYPE *ts_obj) + : once_ (false), + key_ (ACE_OS::NULL_key) +{ + // If caller has passed us a non-NULL TYPE *, then we'll just use + // this to initialize the thread-specific value. Thus, subsequent + // calls to operator->() will return this value. This is useful + // since it enables us to assign objects to thread-specific data + // that have arbitrarily complex constructors! + + if (ts_obj != 0) + { + if (this->ts_init () == -1) + { + // Save/restore errno. + ACE_Errno_Guard error (errno); + // What should we do if this call fails?! +#if defined (ACE_HAS_WINCE) + ::MessageBox (0, + ACE_TEXT ("ACE_Thread::keycreate() failed!"), + ACE_TEXT ("ACE_TSS::ACE_TSS"), + MB_OK); +#else + ACE_OS::fprintf (stderr, + "ACE_Thread::keycreate() failed!"); +#endif /* ACE_HAS_WINCE */ + return; + } + +#if defined (ACE_HAS_THR_C_DEST) + // Encapsulate a ts_obj and it's destructor in an + // ACE_TSS_Adapter. + ACE_TSS_Adapter *tss_adapter = 0; + ACE_NEW (tss_adapter, + ACE_TSS_Adapter ((void *) ts_obj, + ACE_TSS::cleanup)); + + // Put the adapter in thread specific storage + if (this->ts_value (tss_adapter) == -1) + { + delete tss_adapter; + } +#else + this->ts_value (ts_obj); +#endif /* ACE_HAS_THR_C_DEST */ + } +} + +template TYPE * +ACE_TSS::ts_get (void) const +{ + if (!this->once_) + { + // Create and initialize thread-specific ts_obj. + if (const_cast< ACE_TSS < TYPE > * >(this)->ts_init () == -1) + // Seriously wrong.. + return 0; + } + + TYPE *ts_obj = 0; + +#if defined (ACE_HAS_THR_C_DEST) + ACE_TSS_Adapter *tss_adapter = this->ts_value (); + ACE_TSS_Adapter *fake_tss_adapter = 0; + + // If tss_adapter is not 0 but its ts_obj_ is 0 then we still need to create + // a proper ts_obj. That's the intent of this member function. + if (tss_adapter != 0 && tss_adapter->ts_obj_ == 0) + { + fake_tss_adapter = tss_adapter; + tss_adapter = 0; + } + + // Check to see if this is the first time in for this thread. + if (tss_adapter == 0) +#else + ts_obj = this->ts_value (); + + // Check to see if this is the first time in for this thread. + if (ts_obj == 0) +#endif /* ACE_HAS_THR_C_DEST */ + { + // Allocate memory off the heap and store it in a pointer in + // thread-specific storage (on the stack...). + + ts_obj = this->make_TSS_TYPE (); + + if (ts_obj == 0) + return 0; + +#if defined (ACE_HAS_THR_C_DEST) + // Encapsulate a ts_obj and it's destructor in an + // ACE_TSS_Adapter. + ACE_NEW_RETURN (tss_adapter, + ACE_TSS_Adapter (ts_obj, + ACE_TSS::cleanup), 0); + + // Put the adapter in thread specific storage + if (this->ts_value (tss_adapter) == -1) + { + delete tss_adapter; + delete ts_obj; + return 0; // Major problems, this should *never* happen! + } +#else + // Store the dynamically allocated pointer in thread-specific + // storage. + if (this->ts_value (ts_obj) == -1) + { + delete ts_obj; + return 0; // Major problems, this should *never* happen! + } +#endif /* ACE_HAS_THR_C_DEST */ + } + +#if defined (ACE_HAS_THR_C_DEST) + // Delete the adapter that didn't actually have a real ts_obj. + delete fake_tss_adapter; + // Return the underlying ts object. + return static_cast (tss_adapter->ts_obj_); +#else + return ts_obj; +#endif /* ACE_HAS_THR_C_DEST */ +} + +// Get the thread-specific object for the key associated with this +// object. Returns 0 if the ts_obj has never been initialized, +// otherwise returns a pointer to the ts_obj. + +template TYPE * +ACE_TSS::ts_object (void) const +{ + if (!this->once_) // Return 0 if we've never been initialized. + return 0; + + TYPE *ts_obj = 0; + +#if defined (ACE_HAS_THR_C_DEST) + ACE_TSS_Adapter *tss_adapter = this->ts_value (); + + if (tss_adapter != 0) + { + // Extract the real TS object. + ts_obj = static_cast (tss_adapter->ts_obj_); + } +#else + ts_obj = this->ts_value (); +#endif /* ACE_HAS_THR_C_DEST */ + + return ts_obj; +} + +template TYPE * +ACE_TSS::ts_object (TYPE *new_ts_obj) +{ + // Note, we shouldn't hold the keylock at this point because + // does it for us and we'll end up with deadlock + // otherwise... + if (!this->once_) + { + // Create and initialize thread-specific ts_obj. + if (this->ts_init () == -1) + return 0; + } + + TYPE *ts_obj = 0; + +#if defined (ACE_HAS_THR_C_DEST) + ACE_TSS_Adapter *tss_adapter = this->ts_value (); + + if (tss_adapter != 0) + { + ts_obj = static_cast (tss_adapter->ts_obj_); + // Don't delete tss_adapter yet. It can be double-deleted + // in case setspecific below fails. + } + + ACE_TSS_Adapter *new_tss_adapter = 0; + ACE_NEW_RETURN (new_tss_adapter, + ACE_TSS_Adapter ((void *) new_ts_obj, + ACE_TSS::cleanup), + 0); + + if (this->ts_value (new_tss_adapter) == -1) + { + delete new_tss_adapter; + } + else + { + // Now it's fine to delete the old tss_adapter. + delete tss_adapter; + } +#else + ts_obj = this->ts_value (); + this->ts_value (new_ts_obj); +#endif /* ACE_HAS_THR_C_DEST */ + + return ts_obj; +} + +ACE_ALLOC_HOOK_DEFINE(ACE_TSS_Guard) + +template void +ACE_TSS_Guard::dump (void) const +{ +#if defined (ACE_HAS_DUMP) +// ACE_TRACE ("ACE_TSS_Guard::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("key_ = %d\n"), this->key_)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +template void +ACE_TSS_Guard::init_key (void) +{ +// ACE_TRACE ("ACE_TSS_Guard::init_key"); + + this->key_ = ACE_OS::NULL_key; + ACE_Thread::keycreate (&this->key_, +#if defined (ACE_HAS_THR_C_DEST) + &ACE_TSS_C_cleanup, +#else + &ACE_TSS_Guard::cleanup, +#endif /* ACE_HAS_THR_C_DEST */ + (void *) this); +} + +template +ACE_TSS_Guard::ACE_TSS_Guard (void) +{ +// ACE_TRACE ("ACE_TSS_Guard::ACE_TSS_Guard"); + this->init_key (); +} + +template int +ACE_TSS_Guard::release (void) +{ +// ACE_TRACE ("ACE_TSS_Guard::release"); + + ACE_Guard *guard = 0; + +#if defined (ACE_HAS_THR_C_DEST) + ACE_TSS_Adapter *tss_adapter = 0; + void *temp = tss_adapter; // Need this temp to keep G++ from complaining. + ACE_Thread::getspecific (this->key_, &temp); + tss_adapter = static_cast (temp); + guard = static_cast *> (tss_adapter->ts_obj_); +#else + void *temp = guard; // Need this temp to keep G++ from complaining. + ACE_Thread::getspecific (this->key_, &temp); + guard = static_cast *> (temp); +#endif /* ACE_HAS_THR_C_DEST */ + + return guard->release (); +} + +template int +ACE_TSS_Guard::remove (void) +{ +// ACE_TRACE ("ACE_TSS_Guard::remove"); + + ACE_Guard *guard = 0; + +#if defined (ACE_HAS_THR_C_DEST) + ACE_TSS_Adapter *tss_adapter = 0; + void *temp = tss_adapter; // Need this temp to keep G++ from complaining. + ACE_Thread::getspecific (this->key_, &temp); + tss_adapter = static_cast (temp); + guard = static_cast *> (tss_adapter->ts_obj_); +#else + void *temp = guard; // Need this temp to keep G++ from complaining. + ACE_Thread::getspecific (this->key_, &temp); + guard = static_cast *> (temp); +#endif /* ACE_HAS_THR_C_DEST */ + + return guard->remove (); +} + +template +ACE_TSS_Guard::~ACE_TSS_Guard (void) +{ +// ACE_TRACE ("ACE_TSS_Guard::~ACE_TSS_Guard"); + + ACE_Guard *guard = 0; + +#if defined (ACE_HAS_THR_C_DEST) + ACE_TSS_Adapter *tss_adapter = 0; + void *temp = tss_adapter; // Need this temp to keep G++ from complaining. + ACE_Thread::getspecific (this->key_, &temp); + tss_adapter = static_cast (temp); + guard = static_cast *> (tss_adapter->ts_obj_); +#else + void *temp = guard; // Need this temp to keep G++ from complaining. + ACE_Thread::getspecific (this->key_, &temp); + guard = static_cast *> (temp); +#endif /* ACE_HAS_THR_C_DEST */ + + // Make sure that this pointer is NULL when we shut down... + ACE_Thread::setspecific (this->key_, 0); + ACE_Thread::keyfree (this->key_); + // Destructor releases lock. + delete guard; +} + +template void +ACE_TSS_Guard::cleanup (void *ptr) +{ +// ACE_TRACE ("ACE_TSS_Guard::cleanup"); + + // Destructor releases lock. + delete (ACE_Guard *) ptr; +} + +template +ACE_TSS_Guard::ACE_TSS_Guard (ACE_LOCK &lock, bool block) +{ +// ACE_TRACE ("ACE_TSS_Guard::ACE_TSS_Guard"); + + this->init_key (); + ACE_Guard *guard = 0; + ACE_NEW (guard, + ACE_Guard (lock, + block)); + +#if defined (ACE_HAS_THR_C_DEST) + ACE_TSS_Adapter *tss_adapter = 0; + ACE_NEW (tss_adapter, + ACE_TSS_Adapter ((void *) guard, + ACE_TSS_Guard::cleanup)); + ACE_Thread::setspecific (this->key_, + (void *) tss_adapter); +#else + ACE_Thread::setspecific (this->key_, + (void *) guard); +#endif /* ACE_HAS_THR_C_DEST */ +} + +template int +ACE_TSS_Guard::acquire (void) +{ +// ACE_TRACE ("ACE_TSS_Guard::acquire"); + + ACE_Guard *guard = 0; + +#if defined (ACE_HAS_THR_C_DEST) + ACE_TSS_Adapter *tss_adapter = 0; + void *temp = tss_adapter; // Need this temp to keep G++ from complaining. + ACE_Thread::getspecific (this->key_, &temp); + tss_adapter = static_cast (temp); + guard = static_cast *> (tss_adapter->ts_obj_); +#else + void *temp = guard; // Need this temp to keep G++ from complaining. + ACE_Thread::getspecific (this->key_, &temp); + guard = static_cast *> (temp); +#endif /* ACE_HAS_THR_C_DEST */ + + return guard->acquire (); +} + +template int +ACE_TSS_Guard::tryacquire (void) +{ +// ACE_TRACE ("ACE_TSS_Guard::tryacquire"); + + ACE_Guard *guard = 0; + +#if defined (ACE_HAS_THR_C_DEST) + ACE_TSS_Adapter *tss_adapter = 0; + void *temp = tss_adapter; // Need this temp to keep G++ from complaining. + ACE_Thread::getspecific (this->key_, &temp); + tss_adapter = static_cast (temp); + guard = static_cast *> (tss_adapter->ts_obj_); +#else + void *temp = guard; // Need this temp to keep G++ from complaining. + ACE_Thread::getspecific (this->key_, &temp); + guard = static_cast *> (temp); +#endif /* ACE_HAS_THR_C_DEST */ + + return guard->tryacquire (); +} + +template +ACE_TSS_Write_Guard::ACE_TSS_Write_Guard (ACE_LOCK &lock, + bool block) +{ +// ACE_TRACE ("ACE_TSS_Write_Guard::ACE_TSS_Write_Guard"); + + this->init_key (); + ACE_Guard *guard = 0; + ACE_NEW (guard, + ACE_Write_Guard (lock, + block)); + +#if defined (ACE_HAS_THR_C_DEST) + ACE_TSS_Adapter *tss_adapter = 0; + ACE_NEW (tss_adapter, + ACE_TSS_Adapter ((void *) guard, + ACE_TSS_Guard::cleanup)); + ACE_Thread::setspecific (this->key_, + (void *) tss_adapter); +#else + ACE_Thread::setspecific (this->key_, + (void *) guard); +#endif /* ACE_HAS_THR_C_DEST */ +} + +template int +ACE_TSS_Write_Guard::acquire (void) +{ +// ACE_TRACE ("ACE_TSS_Write_Guard::acquire"); + + ACE_Write_Guard *guard = 0; + +#if defined (ACE_HAS_THR_C_DEST) + ACE_TSS_Adapter *tss_adapter = 0; + void *temp = tss_adapter; // Need this temp to keep G++ from complaining. + ACE_Thread::getspecific (this->key_, &temp); + tss_adapter = static_cast (temp); + guard = static_cast *> (tss_adapter->ts_obj_); +#else + void *temp = guard; // Need this temp to keep G++ from complaining. + ACE_Thread::getspecific (this->key_, &temp); + guard = static_cast *> (temp); +#endif /* ACE_HAS_THR_C_DEST */ + + return guard->acquire_write (); +} + +template int +ACE_TSS_Write_Guard::tryacquire (void) +{ +// ACE_TRACE ("ACE_TSS_Write_Guard::tryacquire"); + + ACE_Write_Guard *guard = 0; + +#if defined (ACE_HAS_THR_C_DEST) + ACE_TSS_Adapter *tss_adapter = 0; + void *temp = tss_adapter; // Need this temp to keep G++ from complaining. + ACE_Thread::getspecific (this->key_, &temp); + tss_adapter = static_cast (temp); + guard = static_cast *> (tss_adapter->ts_obj_); +#else + void *temp = guard; // Need this temp to keep G++ from complaining. + ACE_Thread::getspecific (this->key_, &temp); + guard = static_cast *> (temp); +#endif /* ACE_HAS_THR_C_DEST */ + + return guard->tryacquire_write (); +} + +template int +ACE_TSS_Write_Guard::acquire_write (void) +{ +// ACE_TRACE ("ACE_TSS_Write_Guard::acquire_write"); + + return this->acquire (); +} + +template int +ACE_TSS_Write_Guard::tryacquire_write (void) +{ +// ACE_TRACE ("ACE_TSS_Write_Guard::tryacquire_write"); + + return this->tryacquire (); +} + +template void +ACE_TSS_Write_Guard::dump (void) const +{ +#if defined (ACE_HAS_DUMP) +// ACE_TRACE ("ACE_TSS_Write_Guard::dump"); + ACE_TSS_Guard::dump (); +#endif /* ACE_HAS_DUMP */ +} + +template +ACE_TSS_Read_Guard::ACE_TSS_Read_Guard (ACE_LOCK &lock, bool block) +{ +// ACE_TRACE ("ACE_TSS_Read_Guard::ACE_TSS_Read_Guard"); + + this->init_key (); + ACE_Guard *guard = 0; + ACE_NEW (guard, + ACE_Read_Guard (lock, + block)); +#if defined (ACE_HAS_THR_C_DEST) + ACE_TSS_Adapter *tss_adapter; + ACE_NEW (tss_adapter, + ACE_TSS_Adapter ((void *)guard, + ACE_TSS_Guard::cleanup)); + ACE_Thread::setspecific (this->key_, + (void *) tss_adapter); +#else + ACE_Thread::setspecific (this->key_, + (void *) guard); +#endif /* ACE_HAS_THR_C_DEST */ +} + +template int +ACE_TSS_Read_Guard::acquire (void) +{ +// ACE_TRACE ("ACE_TSS_Read_Guard::acquire"); + + ACE_Read_Guard *guard = 0; + +#if defined (ACE_HAS_THR_C_DEST) + ACE_TSS_Adapter *tss_adapter = 0; + void *temp = tss_adapter; // Need this temp to keep G++ from complaining. + ACE_Thread::getspecific (this->key_, &temp); + tss_adapter = static_cast (temp); + guard = static_cast *> (tss_adapter->ts_obj_); +#else + void *temp = guard; // Need this temp to keep G++ from complaining. + ACE_Thread::getspecific (this->key_, &temp); + guard = static_cast *> (temp); +#endif /* ACE_HAS_THR_C_DEST */ + + return guard->acquire_read (); +} + +template int +ACE_TSS_Read_Guard::tryacquire (void) +{ +// ACE_TRACE ("ACE_TSS_Read_Guard::tryacquire"); + + ACE_Read_Guard *guard = 0; + +#if defined (ACE_HAS_THR_C_DEST) + ACE_TSS_Adapter *tss_adapter = 0; + void *temp = tss_adapter; // Need this temp to keep G++ from complaining. + ACE_Thread::getspecific (this->key_, &temp); + tss_adapter = static_cast (temp); + guard = static_cast *> (tss_adapter->ts_obj_); +#else + void *temp = guard; // Need this temp to keep G++ from complaining. + ACE_Thread::getspecific (this->key_, &temp); + guard = static_cast *> (temp); +#endif /* ACE_HAS_THR_C_DEST */ + + return guard->tryacquire_read (); +} + +template int +ACE_TSS_Read_Guard::acquire_read (void) +{ +// ACE_TRACE ("ACE_TSS_Read_Guard::acquire_read"); + + return this->acquire (); +} + +template int +ACE_TSS_Read_Guard::tryacquire_read (void) +{ +// ACE_TRACE ("ACE_TSS_Read_Guard::tryacquire_read"); + + return this->tryacquire (); +} + +template void +ACE_TSS_Read_Guard::dump (void) const +{ +#if defined (ACE_HAS_DUMP) +// ACE_TRACE ("ACE_TSS_Read_Guard::dump"); + ACE_TSS_Guard::dump (); +#endif /* ACE_HAS_DUMP */ +} + +#endif /* defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION)) */ + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_TSS_T_CPP */ diff --git a/dep/acelite/ace/TSS_T.h b/dep/acelite/ace/TSS_T.h new file mode 100644 index 00000000000..d4fa8d52974 --- /dev/null +++ b/dep/acelite/ace/TSS_T.h @@ -0,0 +1,271 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file TSS_T.h + * + * $Id: TSS_T.h 91124 2010-07-19 11:54:35Z vzykov $ + * + * Moved from Synch.h. + * + * @author Douglas C. Schmidt + */ +//========================================================================== + +#ifndef ACE_TSS_T_H +#define ACE_TSS_T_H +#include /**/ "ace/pre.h" + +#include "ace/Lock.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +// This should probably go somewhere else, but it's only used here and +// in Thread_Manager. +// Note there is no ACE_TSS_SET because one would typicaly do +// 'ACE_TSS_GET()->xyz_ = value', so the macro would have been too +// complicated. +# if defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION)) +# define ACE_TSS_TYPE(T) ACE_TSS< T > +# define ACE_TSS_GET(I, T) ((I)->operator T * ()) +# else +# define ACE_TSS_TYPE(T) T +# define ACE_TSS_GET(I, T) (I) +# endif /* ACE_HAS_THREADS && (ACE_HAS_THREAD_SPECIFIC_STORAGE || ACE_HAS_TSS_EMULATION) */ + +#include "ace/Thread_Mutex.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +#if defined (ACE_HAS_THR_C_DEST) +class ACE_TSS_Adapter; +#endif + +/** + * @class ACE_TSS + * + * @brief Allows objects that are "physically" in thread specific + * storage (i.e., private to a thread) to be accessed as though + * they were "logically" global to a program. + * + * This class helps to maintain a separate copy of an object for each thread + * that needs access to it. All threads access a single instance of ACE_TSS + * to obtain a pointer to a thread-specific copy of a TYPE object. Using + * a pointer to TYPE in TSS instead of TYPE itself is useful because, + * in addition to avoiding copies on what may be a complex class, it allows + * assignment of objects to thread-specific data that have arbitrarily + * complex constructors. + * + * When the ACE_TSS object is destroyed, all threads's instances of the + * data are deleted. + * + * Modern compilers have no problem using a built-in type for @c TYPE. + * However, if you must use an older compiler that won't work with a built-in + * type, the ACE_TSS_Type_Adapter class template, below, can be used for + * adapting built-in types to work with ACE_TSS. + * + * @note Beware when creating static instances of this type + * (as with any other, btw). The unpredictable order of initialization + * across different platforms may cause a situation where one uses + * the instance before it is fully initialized. That's why typically + * instances of this type are dynamicaly allocated. On the stack it is + * typically allocated inside the ACE_Thread::svc() method which + * limits its lifetime appropriately. + * + */ +template +class ACE_TSS +{ +public: + /** + * Default constructor. Can also initialize this ACE_TSS instance, + * readying it for use by the calling thread as well as all other + * threads in the process. If the constructor does not initialize this + * object, the first access to it will perform the initialization, which + * could possibly (under odd error conditions) fail. + * + * @param ts_obj If non-zero, this object is initialized for use by + * all threads and @a ts_obj is used to set the + * thread-specific value for the calling thread. Other + * threads use the ts_object (TYPE *) method to set + * a specific value. + */ + ACE_TSS (TYPE *ts_obj = 0); + + /// Deregister this object from thread-specific storage administration. + /// Will cause all threads' copies of TYPE to be destroyed. + virtual ~ACE_TSS (void); + + /** + * Set the thread-specific object for the calling thread. + * If this object has not been initialized yet, this method performs the + * initialization. + * + * @param new_ts_obj The new value for the calling thread's copy of + * this object. + * + * @return The previous value of the calling thread's copy of this + * object; 0 if there was no previous value. This method also + * returns 0 on errors. To tell the difference between an error + * and a returned 0 pointer, it's recommended that one set errno + * to 0 prior to calling ts_object() and check for a new errno + * value if ts_object() returns 0. + */ + TYPE *ts_object (TYPE *new_ts_obj); + + /** @name Accessors + * + * All accessors return a pointer to the calling thread's copy of the + * TYPE data. The pointer may be 0 on error conditions or if the calling + * thread's copy of the data has not yet been set. See specific method + * descriptions for complete details. + */ + //@{ + /** + * Get the thread-specific object for this object. + * + * @return 0 if the object has never been initialized, otherwise returns + * the calling thread's copy of the data. The returned pointer + * may be 0 under odd error conditions; check errno for further + * information. + */ + TYPE *ts_object (void) const; + + /** + * Use a "smart pointer" to get the thread-specific data associated + * with this object. + * If this ACE_TSS object hasn't been initialized, this method + * will initialize it as a side-affect. If the calling thread has not + * set a value, a default-constructed instance of TYPE is allocated and it + * becomes the thread's instance. + * + * @return The calling thread's copy of the data. The returned pointer + * may be 0 under odd error conditions; check errno for further + * information. + */ + TYPE *operator-> () const; + + /** + * Obtain a pointer to the calling thread's TYPE object. + * If this ACE_TSS object hasn't been initialized, this method + * will initialize it as a side-affect. If the calling thread has not + * set a value, a default-constructed instance of TYPE is allocated and it + * becomes the thread's instance. + * + * @return The calling thread's copy of the data. The returned pointer + * may be 0 under odd error conditions; check errno for further + * information. + */ + operator TYPE *(void) const; + + //@} + + /// Hook for construction parameters. + virtual TYPE *make_TSS_TYPE (void) const; + + // = Utility methods. + + /// Dump the state of an object. + void dump (void) const; + + // ACE_ALLOC_HOOK_DECLARE; + // Declare the dynamic allocation hooks. + +protected: + /// Actually implements the code that retrieves the object from + /// thread-specific storage. + TYPE *ts_get (void) const; + + /// Factors out common code for initializing TSS. This must NOT be + /// called with the lock held... + int ts_init (void); + +#if !(defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION))) + /// This implementation only works for non-threading systems... + TYPE *type_; +#else + /// Avoid race conditions during initialization. + ACE_Thread_Mutex keylock_; + + /// "First time in" flag. + volatile bool once_; + + /// Key for the thread-specific error data. + ACE_thread_key_t key_; + + /// "Destructor" that deletes internal TYPE * when thread exits. + static void cleanup (void *ptr); + + /// Obtains a plain value stored in the thread-specific storage. +# if defined (ACE_HAS_THR_C_DEST) + ACE_TSS_Adapter *ts_value (void) const; +# else + TYPE *ts_value (void) const; +# endif /* ACE_HAS_THR_C_DEST */ + + /// Stores a new plain value in the thread-specific storage. +# if defined (ACE_HAS_THR_C_DEST) + int ts_value (ACE_TSS_Adapter *new_tss_adapter) const; +# else + int ts_value (TYPE *new_ts_obj) const; +# endif /* ACE_HAS_THR_C_DEST */ +#endif /* defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION)) */ + // = Disallow copying... + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_TSS &)) + ACE_UNIMPLEMENTED_FUNC (ACE_TSS (const ACE_TSS &)) +}; + +/** + * @class ACE_TSS_Type_Adapter + * + * @brief Adapter that allows built-in types to be used with ACE_TSS. + * + * Wraps a value of a built-in type, providing conversions to + * and from the type. Example use with ACE_TSS: + * ACE_TSS > i; + * *i = 37; + * ACE_OS::fprintf (stderr, "%d\n", *i); + * Unfortunately, though, some compilers have trouble with the + * implicit type conversions. This seems to work better: + * ACE_TSS > i; + * i->operator int & () = 37; + * ACE_OS::fprintf (stderr, "%d\n", i->operator int ()); + */ +template +class ACE_TSS_Type_Adapter +{ +public: + /// Constructor. Inlined here so that it should _always_ be inlined. + ACE_TSS_Type_Adapter (const TYPE value = 0): value_ (value) {} + + /// TYPE conversion. Inlined here so that it should _always_ be + /// inlined. + operator TYPE () const { return value_; }; + + /// TYPE & conversion. Inlined here so that it should _always_ be + /// inlined. + operator TYPE &() { return value_; }; + +private: + /// The wrapped value. + TYPE value_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/TSS_T.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/TSS_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("TSS_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" +#endif /* ACE_TSS_T_H */ diff --git a/dep/acelite/ace/TSS_T.inl b/dep/acelite/ace/TSS_T.inl new file mode 100644 index 00000000000..16c7b5de487 --- /dev/null +++ b/dep/acelite/ace/TSS_T.inl @@ -0,0 +1,103 @@ +// -*- C++ -*- +// +// $Id: TSS_T.inl 91124 2010-07-19 11:54:35Z vzykov $ + +#include "ace/Thread.h" +#include "ace/Log_Msg.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +#if !(defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION))) + +template ACE_INLINE +ACE_TSS::ACE_TSS (TYPE *type) + : type_ (type) +{ +} + +template ACE_INLINE int +ACE_TSS::ts_init (void) +{ + return 0; +} + +template ACE_INLINE TYPE * +ACE_TSS::ts_object (void) const +{ + return this->type_; +} + +template ACE_INLINE TYPE * +ACE_TSS::ts_object (TYPE *type) +{ + this->type_ = type; + return this->type_; +} + +template ACE_INLINE TYPE * +ACE_TSS::ts_get (void) const +{ + return this->type_; +} + +#else + +# if defined (ACE_HAS_THR_C_DEST) +template ACE_INLINE ACE_TSS_Adapter * +ACE_TSS::ts_value (void) const +{ + // Get the tss adapter from thread-specific storage + void *temp = 0; + if (ACE_Thread::getspecific (this->key_, &temp) == -1) + { + return 0; // This should not happen! + } + return static_cast (temp); +} +# else +template ACE_INLINE TYPE * +ACE_TSS::ts_value (void) const +{ + void *temp = 0; + if (ACE_Thread::getspecific (this->key_, &temp) == -1) + { + return 0; // This should not happen! + } + return static_cast (temp); +} +# endif /* ACE_HAS_THR_C_DEST */ + +# if defined (ACE_HAS_THR_C_DEST) +template ACE_INLINE int +ACE_TSS::ts_value (ACE_TSS_Adapter *new_tss_adapter) const +{ + if (ACE_Thread::setspecific (this->key_, + (void *) new_tss_adapter) != 0) + { + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_Thread::setspecific() failed!"))); + return -1; + } + + return 0; +} +# else +template ACE_INLINE int +ACE_TSS::ts_value (TYPE *new_ts_obj) const +{ + if (ACE_Thread::setspecific (this->key_, (void *) new_ts_obj) != 0) + { + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_Thread::setspecific() failed!"))); + return -1; + } + + return 0; +} +# endif /* ACE_HAS_THR_C_DEST */ + +#endif /* ! (defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION))) */ + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/TTY_IO.cpp b/dep/acelite/ace/TTY_IO.cpp new file mode 100644 index 00000000000..6d5be6f2c38 --- /dev/null +++ b/dep/acelite/ace/TTY_IO.cpp @@ -0,0 +1,705 @@ +// $Id: TTY_IO.cpp 86739 2009-09-21 07:33:22Z olli $ + +#include "ace/TTY_IO.h" +#include "ace/OS_NS_errno.h" +#include "ace/OS_NS_string.h" +#include "ace/OS_NS_strings.h" + +#if defined (ACE_HAS_TERMIOS) +# include "ace/os_include/os_termios.h" +#elif defined (ACE_HAS_TERMIO) +# include +#endif + +ACE_RCSID (ace, + TTY_IO, + "$Id: TTY_IO.cpp 86739 2009-09-21 07:33:22Z olli $") + +namespace +{ + const char ACE_TTY_IO_NONE[] = "none"; +#if defined (ACE_HAS_TERMIOS) || defined (ACE_HAS_TERMIO) || defined (ACE_WIN32) + const char ACE_TTY_IO_ODD[] = "odd"; + const char ACE_TTY_IO_EVEN[] = "even"; +#endif +#if defined (ACE_WIN32) + const char ACE_TTY_IO_MARK[] = "mark"; + const char ACE_TTY_IO_SPACE[] = "space"; +#endif /* ACE_WIN32 */ +} + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_TTY_IO::Serial_Params::Serial_Params (void) +{ + baudrate = 9600; + xonlim = 0; + xofflim = 0; + readmincharacters = 0; + readtimeoutmsec = 10000; + paritymode = ACE_TTY_IO_NONE; + ctsenb = false; + rtsenb = 0; + xinenb = false; + xoutenb = false; + modem = false; + rcvenb = true; + dsrenb = false; + dtrdisable = false; + databits = 8; + stopbits = 1; +} + +// Interface for reading/writing serial device parameters + +int ACE_TTY_IO::control (Control_Mode cmd, Serial_Params *arg) const +{ +#if defined (ACE_HAS_TERMIOS) || defined (ACE_HAS_TERMIO) + +#if defined (ACE_HAS_TERMIOS) + struct termios devpar; + speed_t newbaudrate = 0; + if (tcgetattr (get_handle () , &devpar) == -1) +#elif defined (TCGETS) + struct termios devpar; + unsigned int newbaudrate = 0; + if (this->ACE_IO_SAP::control (TCGETS, static_cast(&devpar)) == -1) +#elif defined (TCGETA) + struct termio devpar; + unsigned int newbaudrate = 0; + if (this->ACE_IO_SAP::control (TCGETA, static_cast(&devpar)) == -1) +#else + errno = ENOSYS; +#endif /* ACE_HAS_TERMIOS */ + return -1; + + switch (cmd) + { + case SETPARAMS: + switch (arg->baudrate) + { +#if defined (B0) + case 0: newbaudrate = B0; break; +#endif /* B0 */ +#if defined (B50) + case 50: newbaudrate = B50; break; +#endif /* B50 */ +#if defined (B75) + case 75: newbaudrate = B75; break; +#endif /* B75 */ +#if defined (B110) + case 110: newbaudrate = B110; break; +#endif /* B110 */ +#if defined (B134) + case 134: newbaudrate = B134; break; +#endif /* B134 */ +#if defined (B150) + case 150: newbaudrate = B150; break; +#endif /* B150 */ +#if defined (B200) + case 200: newbaudrate = B200; break; +#endif /* B200 */ +#if defined (B300) + case 300: newbaudrate = B300; break; +#endif /* B300 */ +#if defined (B600) + case 600: newbaudrate = B600; break; +#endif /* B600 */ +#if defined (B1200) + case 1200: newbaudrate = B1200; break; +#endif /* B1200 */ +#if defined (B1800) + case 1800: newbaudrate = B1800; break; +#endif /* B1800 */ +#if defined (B2400) + case 2400: newbaudrate = B2400; break; +#endif /* B2400 */ +#if defined (B4800) + case 4800: newbaudrate = B4800; break; +#endif /* B4800 */ +#if defined (B9600) + case 9600: newbaudrate = B9600; break; +#endif /* B9600 */ +#if defined (B19200) + case 19200: newbaudrate = B19200; break; +#endif /* B19200 */ +#if defined (B38400) + case 38400: newbaudrate = B38400; break; +#endif /* B38400 */ +#if defined (B56000) + case 56000: newbaudrate = B56000; break; +#endif /* B56000 */ +#if defined (B57600) + case 57600: newbaudrate = B57600; break; +#endif /* B57600 */ +#if defined (B76800) + case 76800: newbaudrate = B76800; break; +#endif /* B76800 */ +#if defined (B115200) + case 115200: newbaudrate = B115200; break; +#endif /* B115200 */ +#if defined (B128000) + case 128000: newbaudrate = B128000; break; +#endif /* B128000 */ +#if defined (B153600) + case 153600: newbaudrate = B153600; break; +#endif /* B153600 */ +#if defined (B230400) + case 230400: newbaudrate = B230400; break; +#endif /* B230400 */ +#if defined (B307200) + case 307200: newbaudrate = B307200; break; +#endif /* B307200 */ +#if defined (B256000) + case 256000: newbaudrate = B256000; break; +#endif /* B256000 */ +#if defined (B460800) + case 460800: newbaudrate = B460800; break; +#endif /* B460800 */ +#if defined (B500000) + case 500000: newbaudrate = B500000; break; +#endif /* B500000 */ +#if defined (B576000) + case 576000: newbaudrate = B576000; break; +#endif /* B576000 */ +#if defined (B921600) + case 921600: newbaudrate = B921600; break; +#endif /* B921600 */ +#if defined (B1000000) + case 1000000: newbaudrate = B1000000; break; +#endif /* B1000000 */ +#if defined (B1152000) + case 1152000: newbaudrate = B1152000; break; +#endif /* B1152000 */ +#if defined (B1500000) + case 1500000: newbaudrate = B1500000; break; +#endif /* B1500000 */ +#if defined (B2000000) + case 2000000: newbaudrate = B2000000; break; +#endif /* B2000000 */ +#if defined (B2500000) + case 2500000: newbaudrate = B2500000; break; +#endif /* B2500000 */ +#if defined (B3000000) + case 3000000: newbaudrate = B3000000; break; +#endif /* B3000000 */ +#if defined (B3500000) + case 3500000: newbaudrate = B3500000; break; +#endif /* B3500000 */ +#if defined (B4000000) + case 4000000: newbaudrate = B4000000; break; +#endif /* B4000000 */ + default: + return -1; + } + +#if defined (ACE_HAS_TERMIOS) + // Can you really have different input and output baud rates?! + if (cfsetospeed (&devpar, newbaudrate) == -1) + return -1; + if (cfsetispeed (&devpar, newbaudrate) == -1) + return -1; +#else + devpar.c_cflag &= ~CBAUD; +# if defined (CBAUDEX) + devpar.c_cflag &= ~CBAUDEX; +# endif /* CBAUDEX */ + devpar.c_cflag |= newbaudrate; +#endif /* ACE_HAS_TERMIOS */ + + devpar.c_cflag &= ~CSIZE; + switch (arg->databits) + { + case 5: + devpar.c_cflag |= CS5; + break; + case 6: + devpar.c_cflag |= CS6; + break; + case 7: + devpar.c_cflag |= CS7; + break; + case 8: + devpar.c_cflag |= CS8; + break; + default: + return -1; + } + + switch (arg->stopbits) + { + case 1: + devpar.c_cflag &= ~CSTOPB; + break; + case 2: + devpar.c_cflag |= CSTOPB; + break; + default: + return -1; + } + + if (arg->paritymode) + { + if (ACE_OS::strcasecmp (arg->paritymode, ACE_TTY_IO_ODD) == 0) + { + devpar.c_cflag |= PARENB; + devpar.c_cflag |= PARODD; + } + else if (ACE_OS::strcasecmp (arg->paritymode, ACE_TTY_IO_EVEN) == 0) + { + devpar.c_cflag |= PARENB; + devpar.c_cflag &= ~PARODD; + } + else if (ACE_OS::strcasecmp (arg->paritymode, ACE_TTY_IO_NONE) == 0) + devpar.c_cflag &= ~PARENB; + else + return -1; + } + else + { + devpar.c_cflag &= ~PARENB; + } + +#if defined (CNEW_RTSCTS) + if ((arg->ctsenb) || (arg->rtsenb)) // Enable RTS/CTS protocol + devpar.c_cflag |= CNEW_RTSCTS; + else + devpar.c_cflag &= ~CNEW_RTSCTS; +#elif defined (CRTSCTS) + if ((arg->ctsenb) || (arg->rtsenb)) // Enable RTS/CTS protocol + devpar.c_cflag |= CRTSCTS; + else + devpar.c_cflag &= ~CRTSCTS; +#endif /* NEW_RTSCTS || CRTSCTS */ + +#if defined (CREAD) + // Enable/disable receiver + if (arg->rcvenb) + devpar.c_cflag |= CREAD; + else + devpar.c_cflag &= ~CREAD; +#endif /* CREAD */ + +#if defined (HUPCL) + // Cause DTR to drop after port close. + devpar.c_cflag |= HUPCL; +#endif /* HUPCL */ + +#if defined (CLOCAL) + // If device is not a modem set to local device. + if (arg->modem) + devpar.c_cflag &= ~CLOCAL; + else + devpar.c_cflag |= CLOCAL; +#endif /* CLOCAL */ + + devpar.c_iflag = IGNPAR | INPCK; + if (arg->databits < 8) + devpar.c_iflag |= ISTRIP; + +#if defined (IGNBRK) + // If device is not a modem set to ignore break points + if(arg->modem) + devpar.c_iflag &= ~IGNBRK; + else + devpar.c_iflag |= IGNBRK; +#endif /* IGNBRK */ + +#if defined (IXOFF) + // Enable/disable software flow control on input + if (arg->xinenb) + devpar.c_iflag |= IXOFF; + else + devpar.c_iflag &= ~IXOFF; +#endif /* IXOFF */ + +#if defined (IXON) + // Enable/disable software flow control on output + if (arg->xoutenb) + devpar.c_iflag |= IXON; + else + devpar.c_iflag &= ~IXON; +#endif /* IXON */ + +#if defined (ICANON) + // Enable noncanonical input processing mode + devpar.c_lflag &= ~ICANON; +#endif /* ICANON */ + +#if defined (ECHO) + // Disable echoing of input characters + devpar.c_lflag &= ~ECHO; +#endif /* ECHO */ + +#if defined (ECHOE) + // Disable echoing erase chareacter as BS-SP-BS + devpar.c_lflag &= ~ECHOE; +#endif /* ECHOE */ + +#if defined (ISIG) + // Disable SIGINTR, SIGSUSP, SIGDSUSP and SIGQUIT signals + devpar.c_lflag &= ~ISIG; +#endif /* ISIG */ + +#if defined (OPOST) + // Disable post-processing of output data + devpar.c_oflag &= ~OPOST; +#endif /* OPOST */ + + if (arg->readtimeoutmsec < 0) + { + // Settings for infinite timeout. + devpar.c_cc[VTIME] = 0; + // In case of infinite timeout [VMIN] must be at least 1. + if (arg->readmincharacters > UCHAR_MAX) + devpar.c_cc[VMIN] = UCHAR_MAX; + else if (arg->readmincharacters < 1) + devpar.c_cc[VMIN] = 1; + else + devpar.c_cc[VMIN] = static_cast(arg->readmincharacters); + } + else + { + devpar.c_cc[VTIME] = static_cast(arg->readtimeoutmsec / 100); + + if (arg->readmincharacters > UCHAR_MAX) + devpar.c_cc[VMIN] = UCHAR_MAX; + else if (arg->readmincharacters < 1) + devpar.c_cc[VMIN] = 0; + else + devpar.c_cc[VMIN] = static_cast(arg->readmincharacters); + } + +#if defined (TIOCMGET) + int status; + this->ACE_IO_SAP::control (TIOCMGET, &status); + + if (arg->dtrdisable) + status &= ~TIOCM_DTR; + else + status |= TIOCM_DTR; + + this->ACE_IO_SAP::control (TIOCMSET, &status); +#endif /* definded (TIOCMGET) */ + +#if defined (ACE_HAS_TERMIOS) + return tcsetattr (get_handle (), TCSANOW, &devpar); +#elif defined (TCSETS) + return this->ACE_IO_SAP::control (TCSETS, static_cast(&devpar)); +#elif defined (TCSETA) + return this->ACE_IO_SAP::control (TCSETA, static_cast(&devpar)); +#else + errno = ENOSYS; + return -1; +#endif /* ACE_HAS_TERMIOS */ + + case GETPARAMS: + return -1; // Not yet implemented. + default: + return -1; // Wrong cmd. + } +#elif defined (ACE_WIN32) + DCB dcb; + dcb.DCBlength = sizeof dcb; + if (!::GetCommState (this->get_handle (), &dcb)) + { + ACE_OS::set_errno_to_last_error (); + return -1; + } + + COMMTIMEOUTS timeouts; + if (!::GetCommTimeouts (this->get_handle(), &timeouts)) + { + ACE_OS::set_errno_to_last_error (); + return -1; + } + + switch (cmd) + { + case SETPARAMS: + dcb.BaudRate = arg->baudrate; + + switch (arg->databits) + { + case 4: + case 5: + case 6: + case 7: + case 8: + dcb.ByteSize = arg->databits; + break; + default: + return -1; + } + + switch (arg->stopbits) + { + case 1: + dcb.StopBits = ONESTOPBIT; + break; + case 2: + dcb.StopBits = TWOSTOPBITS; + break; + default: + return -1; + } + + if (arg->paritymode) + { + dcb.fParity = TRUE; + if (ACE_OS::strcasecmp (arg->paritymode, ACE_TTY_IO_ODD) == 0) + dcb.Parity = ODDPARITY; + else if (ACE_OS::strcasecmp (arg->paritymode, ACE_TTY_IO_EVEN) == 0) + dcb.Parity = EVENPARITY; + else if (ACE_OS::strcasecmp (arg->paritymode, ACE_TTY_IO_NONE) == 0) + dcb.Parity = NOPARITY; + else if (ACE_OS::strcasecmp (arg->paritymode, ACE_TTY_IO_MARK) == 0) + dcb.Parity = MARKPARITY; + else if (ACE_OS::strcasecmp (arg->paritymode, ACE_TTY_IO_SPACE) == 0) + dcb.Parity = SPACEPARITY; + else + return -1; + } + else + { + dcb.fParity = FALSE; + dcb.Parity = NOPARITY; + } + + // Enable/disable RTS protocol. + switch (arg->rtsenb) + { + case 1: + dcb.fRtsControl = RTS_CONTROL_ENABLE; + break; + case 2: + dcb.fRtsControl = RTS_CONTROL_HANDSHAKE; + break; + case 3: + dcb.fRtsControl = RTS_CONTROL_TOGGLE; + break; + default: + dcb.fRtsControl = RTS_CONTROL_DISABLE; + } + + // Enable/disable CTS protocol. + if (arg->ctsenb) + dcb.fOutxCtsFlow = TRUE; + else + dcb.fOutxCtsFlow = FALSE; + + // Enable/disable DSR protocol. + if (arg->dsrenb) + dcb.fOutxDsrFlow = TRUE; + else + dcb.fOutxDsrFlow = FALSE; + + // Disable/enable DTR protocol + if (arg->dtrdisable) + dcb.fDtrControl = DTR_CONTROL_DISABLE; + else + dcb.fDtrControl = DTR_CONTROL_ENABLE; + + // Enable/disable software flow control on input + if (arg->xinenb) + dcb.fInX = TRUE; + else + dcb.fInX = FALSE; + + // Enable/disable software flow control on output + if (arg->xoutenb) + dcb.fOutX = TRUE; + else + dcb.fOutX = FALSE; + + // Always set limits unless set to negative to use default. + if (arg->xonlim >= 0) + dcb.XonLim = static_cast(arg->xonlim); + if (arg->xofflim >= 0) + dcb.XoffLim = static_cast(arg->xofflim); + + dcb.fAbortOnError = FALSE; + dcb.fErrorChar = FALSE; + dcb.fNull = FALSE; + dcb.fBinary = TRUE; + + if (!::SetCommState (this->get_handle (), &dcb)) + { + ACE_OS::set_errno_to_last_error (); + return -1; + } + + if (arg->readtimeoutmsec < 0) + { + // Settings for infinite timeout. + timeouts.ReadIntervalTimeout = 0; + timeouts.ReadTotalTimeoutMultiplier = 0; + timeouts.ReadTotalTimeoutConstant = 0; + } + else if (arg->readtimeoutmsec == 0) + { + // Return immediately if no data in the input buffer. + timeouts.ReadIntervalTimeout = MAXDWORD; + timeouts.ReadTotalTimeoutMultiplier = 0; + timeouts.ReadTotalTimeoutConstant = 0; + } + else + { + // Wait for specified timeout for char to arrive before returning. + timeouts.ReadIntervalTimeout = MAXDWORD; + timeouts.ReadTotalTimeoutMultiplier = MAXDWORD; + timeouts.ReadTotalTimeoutConstant = arg->readtimeoutmsec; + } + + if (!::SetCommTimeouts (this->get_handle (), &timeouts)) + { + ACE_OS::set_errno_to_last_error (); + return -1; + } + + return 0; + + case GETPARAMS: + arg->baudrate = dcb.BaudRate; + + switch (dcb.ByteSize) + { + case 4: + case 5: + case 6: + case 7: + case 8: + arg->databits = dcb.ByteSize; + break; + default: + return -1; + } + + switch (dcb.StopBits) + { + case ONESTOPBIT: + arg->stopbits = 1; + break; + case TWOSTOPBITS: + arg->stopbits = 2; + break; + default: + return -1; + } + + if (!dcb.fParity) + { + arg->paritymode = ACE_TTY_IO_NONE; + } + else + { + switch (dcb.Parity) + { + case ODDPARITY: + arg->paritymode = ACE_TTY_IO_ODD; + break; + case EVENPARITY: + arg->paritymode = ACE_TTY_IO_EVEN; + break; + case NOPARITY: + arg->paritymode = ACE_TTY_IO_NONE; + break; + case MARKPARITY: + arg->paritymode = ACE_TTY_IO_MARK; + break; + case SPACEPARITY: + arg->paritymode = ACE_TTY_IO_SPACE; + break; + default: + return -1; + } + } + + // Enable/disable RTS protocol. + switch (dcb.fRtsControl) + { + case RTS_CONTROL_ENABLE: + arg->rtsenb = 1; + break; + case RTS_CONTROL_HANDSHAKE: + arg->rtsenb = 2; + break; + case RTS_CONTROL_TOGGLE: + arg->rtsenb = 3; + break; + case RTS_CONTROL_DISABLE: + arg->rtsenb = 0; + break; + default: + return -1; + } + + // Enable/disable CTS protocol. + if (dcb.fOutxCtsFlow) + arg->ctsenb = true; + else + arg->ctsenb = false; + + // Enable/disable DSR protocol. + if (dcb.fOutxDsrFlow) + arg->dsrenb = true; + else + arg->dsrenb = false; + + // Disable/enable DTR protocol + // Attention: DTR_CONTROL_HANDSHAKE is not supported. + switch (dcb.fDtrControl) + { + case DTR_CONTROL_DISABLE: + arg->dtrdisable = true; + break; + case DTR_CONTROL_ENABLE: + arg->dtrdisable = false; + break; + default: + return -1; + } + + // Enable/disable software flow control on input + if (dcb.fInX) + arg->xinenb = true; + else + arg->xinenb = false; + + // Enable/disable software flow control on output + if (dcb.fOutX) + arg->xoutenb = true; + else + arg->xoutenb = false; + + arg->xonlim = static_cast(dcb.XonLim); + arg->xofflim = static_cast(dcb.XoffLim); + + if (timeouts.ReadIntervalTimeout == 0 && + timeouts.ReadTotalTimeoutMultiplier == 0 && + timeouts.ReadTotalTimeoutConstant == 0) + arg->readtimeoutmsec = -1; + else + arg->readtimeoutmsec = timeouts.ReadTotalTimeoutConstant; + + return 0; + + default: + return -1; // Wrong cmd. + + } // arg switch +#else + ACE_UNUSED_ARG (cmd); + ACE_UNUSED_ARG (arg); + ACE_NOTSUP_RETURN (-1); +#endif /* ACE_HAS_TERMIOS || ACE_HAS_TERMIO */ +} + +#if defined (ACE_NEEDS_DEV_IO_CONVERSION) +ACE_TTY_IO::operator ACE_DEV_IO &() +{ + return static_cast(*this); +} +#endif /* ACE_NEEDS_DEV_IO_CONVERSION */ + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/TTY_IO.h b/dep/acelite/ace/TTY_IO.h new file mode 100644 index 00000000000..1029966e56c --- /dev/null +++ b/dep/acelite/ace/TTY_IO.h @@ -0,0 +1,113 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file TTY_IO.h + * + * $Id: TTY_IO.h 82271 2008-07-09 09:23:03Z olli $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_TTY_IO_H +#define ACE_TTY_IO_H + +#include "ace/DEV_IO.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_TTY_IO + * + * @brief Class definitions for platform specific TTY features. + * + * This class represents an example interface for a specific + * device (a serial line). It extends the capability of the + * underlying DEV_IO class by adding a control method that takes + * a special structure (Serial_Params) as argument to allow a + * comfortable user interface (away from that annoying termios + * structure, which is very specific to UNIX). + */ +class ACE_Export ACE_TTY_IO : public ACE_DEV_IO +{ +public: + enum Control_Mode + { + SETPARAMS, ///< Set control parameters. + GETPARAMS ///< Get control parameters. + }; + + struct ACE_Export Serial_Params + { + Serial_Params (void); + + /** Specifies the baudrate at which the communnication port operates. */ + int baudrate; + /** Specifies the minimum number of bytes in input buffer before XON char + is sent. Negative value indicates that default value should + be used (Win32). */ + int xonlim; + /** Specifies the maximum number of bytes in input buffer before XOFF char + is sent. Negative value indicates that default value should + be used (Win32). */ + int xofflim; + /** Specifies the minimum number of characters for non-canonical + read (POSIX). */ + unsigned int readmincharacters; + /** Specifies the time to wait before returning from read. Negative value + means infinite timeout. */ + int readtimeoutmsec; + /** Specifies the parity mode. POSIX supports "none", "even" and + "odd" parity. Additionally Win32 supports "mark" and "space" + parity modes. */ + const char *paritymode; + /** Enable & set CTS mode. Note that RTS & CTS are enabled/disabled + together on some systems (RTS/CTS is enabled if either + ctsenb or rtsenb is set). */ + bool ctsenb; + /** Enable & set RTS mode. Note that RTS & CTS are enabled/disabled + together on some systems (RTS/CTS is enabled if either + ctsenb or rtsenb is set). + - 0 = Disable RTS. + - 1 = Enable RTS. + - 2 = Enable RTS flow-control handshaking (Win32). + - 3 = Specifies that RTS line will be high if bytes are available + for transmission. After transmission RTS will be low (Win32). */ + unsigned char rtsenb; + /** Enable/disable software flow control on input. */ + bool xinenb; + /** Enable/disable software flow control on output. */ + bool xoutenb; + /** Specifies if device is a modem (POSIX). If not set modem status + lines are ignored. */ + bool modem; + /** Enable/disable receiver (POSIX). */ + bool rcvenb; + /** Controls whether DSR is disabled or enabled (Win32). */ + bool dsrenb; + /** Controls whether DTR is disabled or enabled. */ + bool dtrdisable; + /** Data bits. Valid values 5, 6, 7 and 8 data bits. + Additionally Win32 supports 4 data bits. */ + unsigned char databits; + /** Stop bits. Valid values are 1 and 2. */ + unsigned char stopbits; + }; + + /** Interface for reading/writing serial device parameters. */ + int control (Control_Mode cmd, Serial_Params *arg) const; + +#if defined (ACE_NEEDS_DEV_IO_CONVERSION) + /** This is necessary to pass ACE_TTY_IO as parameter to DEV_Connector. */ + operator ACE_DEV_IO &(); +#endif /* ACE_NEEDS_DEV_IO_CONVERSION */ +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_TTY_IO_H */ diff --git a/dep/acelite/ace/Task.cpp b/dep/acelite/ace/Task.cpp new file mode 100644 index 00000000000..b3d8aad7a86 --- /dev/null +++ b/dep/acelite/ace/Task.cpp @@ -0,0 +1,299 @@ +// $Id: Task.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Task.h" +#include "ace/Module.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Task.inl" +#endif /* __ACE_INLINE__ */ + + +ACE_RCSID (ace, + Task, + "$Id: Task.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_Task_Base::ACE_Task_Base (ACE_Thread_Manager *thr_man) + : thr_count_ (0), + thr_mgr_ (thr_man), + flags_ (0), + grp_id_ (-1) +#if !(defined (ACE_MVS) || defined(__TANDEM)) + ,last_thread_id_ (0) +#endif /* !defined (ACE_MVS) */ +{ +#if (defined (ACE_MVS) || defined(__TANDEM)) + ACE_OS::memset( &this->last_thread_id_, '\0', sizeof( this->last_thread_id_ )); +#endif /* defined (ACE_MVS) */ +} + +ACE_Task_Base::~ACE_Task_Base (void) +{ +} + +// Default ACE_Task service routine + +int +ACE_Task_Base::svc (void) +{ + ACE_TRACE ("ACE_Task_Base::svc"); + return 0; +} + +// Default ACE_Task open routine + +int +ACE_Task_Base::open (void *) +{ + ACE_TRACE ("ACE_Task_Base::open"); + return 0; +} + +// Default ACE_Task close routine + +int +ACE_Task_Base::close (u_long) +{ + ACE_TRACE ("ACE_Task_Base::close"); + return 0; +} + +// Forward the call to close() so that existing applications don't +// break. + +int +ACE_Task_Base::module_closed (void) +{ + return this->close (1); +} + +// Default ACE_Task put routine. + +int +ACE_Task_Base::put (ACE_Message_Block *, ACE_Time_Value *) +{ + ACE_TRACE ("ACE_Task_Base::put"); + return 0; +} + +// Wait for all threads running in a task to exit. + +int +ACE_Task_Base::wait (void) +{ + ACE_TRACE ("ACE_Task_Base::wait"); + + // If we don't have a thread manager, we probably were never + // activated. + if (this->thr_mgr () != 0) + return this->thr_mgr ()->wait_task (this); + else + return 0; +} + +// Suspend a task. +int +ACE_Task_Base::suspend (void) +{ + ACE_TRACE ("ACE_Task_Base::suspend"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + if (this->thr_count_ > 0) + return this->thr_mgr_->suspend_task (this); + + return 0; +} + +// Resume a suspended task. +int +ACE_Task_Base::resume (void) +{ + ACE_TRACE ("ACE_Task_Base::resume"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + if (this->thr_count_ > 0) + return this->thr_mgr_->resume_task (this); + + return 0; +} + +int +ACE_Task_Base::activate (long flags, + int n_threads, + int force_active, + long priority, + int grp_id, + ACE_Task_Base *task, + ACE_hthread_t thread_handles[], + void *stack[], + size_t stack_size[], + ACE_thread_t thread_ids[], + const char* thr_name[]) +{ + ACE_TRACE ("ACE_Task_Base::activate"); + +#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) + ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1); + + // If the task passed in is zero, we will use + if (task == 0) + task = this; + + if (this->thr_count_ > 0 && force_active == 0) + return 1; // Already active. + else + { + if (this->thr_count_ > 0 && this->grp_id_ != -1) + // If we're joining an existing group of threads then make + // sure to use its group id. + grp_id = this->grp_id_; + this->thr_count_ += n_threads; + } + + // Use the ACE_Thread_Manager singleton if we're running as an + // active object and the caller didn't supply us with a + // Thread_Manager. + if (this->thr_mgr_ == 0) +# if defined (ACE_THREAD_MANAGER_LACKS_STATICS) + this->thr_mgr_ = ACE_THREAD_MANAGER_SINGLETON::instance (); +# else /* ! ACE_THREAD_MANAGER_LACKS_STATICS */ + this->thr_mgr_ = ACE_Thread_Manager::instance (); +# endif /* ACE_THREAD_MANAGER_LACKS_STATICS */ + + int grp_spawned = -1; + if (thread_ids == 0) + // Thread Ids were not specified + grp_spawned = + this->thr_mgr_->spawn_n (n_threads, + &ACE_Task_Base::svc_run, + (void *) this, + flags, + priority, + grp_id, + task, + thread_handles, + stack, + stack_size, + thr_name); + else + // thread names were specified + grp_spawned = + this->thr_mgr_->spawn_n (thread_ids, + n_threads, + &ACE_Task_Base::svc_run, + (void *) this, + flags, + priority, + grp_id, + stack, + stack_size, + thread_handles, + task, + thr_name); + if (grp_spawned == -1) + { + // If spawn_n fails, restore original thread count. + this->thr_count_ -= n_threads; + return -1; + } + + if (this->grp_id_ == -1) + this->grp_id_ = grp_spawned; + +#if defined (ACE_MVS) || defined(__TANDEM) + ACE_OS::memcpy( &this->last_thread_id_, '\0', sizeof(this->last_thread_id_)); +#else + this->last_thread_id_ = 0; // Reset to prevent inadvertant match on ID +#endif /* defined (ACE_MVS) */ + + return 0; + +#else + { + // Keep the compiler from complaining. + ACE_UNUSED_ARG (flags); + ACE_UNUSED_ARG (n_threads); + ACE_UNUSED_ARG (force_active); + ACE_UNUSED_ARG (priority); + ACE_UNUSED_ARG (grp_id); + ACE_UNUSED_ARG (task); + ACE_UNUSED_ARG (thread_handles); + ACE_UNUSED_ARG (stack); + ACE_UNUSED_ARG (stack_size); + ACE_UNUSED_ARG (thread_ids); + ACE_UNUSED_ARG (thr_name); + ACE_NOTSUP_RETURN (-1); + } +#endif /* ACE_MT_SAFE */ +} + +void +ACE_Task_Base::cleanup (void *object, void *) +{ + ACE_Task_Base *t = (ACE_Task_Base *) object; + + // The thread count must be decremented first in case the + // hook does something crazy like "delete this". + { + ACE_MT (ACE_GUARD (ACE_Thread_Mutex, ace_mon, t->lock_)); + t->thr_count_--; + if (0 == t->thr_count_) + t->last_thread_id_ = ACE_Thread::self (); + } + + // @@ Is it possible to pass in the exit status somehow? + t->close (); + // t is undefined here. close() could have deleted it. +} + + +#if defined (ACE_HAS_SIG_C_FUNC) +extern "C" void +ACE_Task_Base_cleanup (void *object, void *) +{ + ACE_Task_Base::cleanup (object, 0); +} +#endif /* ACE_HAS_SIG_C_FUNC */ + +ACE_THR_FUNC_RETURN +ACE_Task_Base::svc_run (void *args) +{ + ACE_TRACE ("ACE_Task_Base::svc_run"); + + ACE_Task_Base *t = (ACE_Task_Base *) args; + + // Register ourself with our 's thread exit hook + // mechanism so that our close() hook will be sure to get invoked + // when this thread exits. + +#if defined ACE_HAS_SIG_C_FUNC + t->thr_mgr ()->at_exit (t, ACE_Task_Base_cleanup, 0); +#else + t->thr_mgr ()->at_exit (t, ACE_Task_Base::cleanup, 0); +#endif /* ACE_HAS_SIG_C_FUNC */ + + // Call the Task's svc() hook method. + int const svc_status = t->svc (); + ACE_THR_FUNC_RETURN status; +#if defined (ACE_HAS_INTEGRAL_TYPE_THR_FUNC_RETURN) + // Reinterpret case between integral types is not mentioned in the C++ spec + status = static_cast (svc_status); +#else + status = reinterpret_cast (svc_status); +#endif /* ACE_HAS_INTEGRAL_TYPE_THR_FUNC_RETURN */ + +// If we changed this zero change the other if in OS.cpp Thread_Adapter::invoke +#if 1 + // Call the close> hook. + ACE_Thread_Manager *thr_mgr_ptr = t->thr_mgr (); + + // This calls the Task->close () hook. + t->cleanup (t, 0); + + // This prevents a second invocation of the cleanup code + // (called later by . + thr_mgr_ptr->at_exit (t, 0, 0); +#endif + return status; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Task.h b/dep/acelite/ace/Task.h new file mode 100644 index 00000000000..08147a6459a --- /dev/null +++ b/dep/acelite/ace/Task.h @@ -0,0 +1,307 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Task.h + * + * $Id: Task.h 91058 2010-07-12 08:20:09Z johnnyw $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_TASK_H +#define ACE_TASK_H +#include /**/ "ace/pre.h" + +#include "ace/Service_Object.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Thread_Manager.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Task_Flags + * + * @brief These flags are used within the ACE_Task. + * + * These flags should be hidden within ACE_Task. Unfortunately, the + * HP/UX C++ compiler can't grok this... Fortunately, there's no + * code defined here, so we don't have to worry about multiple + * definitions. + */ +namespace ACE_Task_Flags +{ + enum + { + /// Identifies a Task as being the "reader" in a Module. + ACE_READER = 01, + /// Just flush data messages in the queue. + ACE_FLUSHDATA = 02, + /// Flush all messages in the Queue. + ACE_FLUSHALL = 04, + /// Flush read queue + ACE_FLUSHR = 010, + /// Flush write queue + ACE_FLUSHW = 020, + /// Flush both queues + ACE_FLUSHRW = 030 + }; +} + +/** + * @class ACE_Task_Base + * + * @brief Direct base class for the ACE_Task template. + * + * This class factors out the non-template code in order to + * reduce template bloat, as well as to make it possible for the + * ACE_Thread_Manager to store ACE_Task_Base *'s + * polymorphically. + */ +class ACE_Export ACE_Task_Base : public ACE_Service_Object +{ +public: + // = Initialization and termination methods. + /// Constructor. + ACE_Task_Base (ACE_Thread_Manager * = 0); + + /// Destructor. + virtual ~ACE_Task_Base (void); + + // = Initialization and termination hooks. + + // These methods should be overridden by subclasses if you'd like to + // provide -specific initialization and termination behavior. + + /// Hook called to initialize a task and prepare it for execution. + /// @a args can be used to pass arbitrary information into . + virtual int open (void *args = 0); + + /** + * Hook called from ACE_Thread_Exit when during thread exit and from + * the default implementation of @c module_closed(). In general, this + * method shouldn't be called directly by an application, + * particularly if the Task is running as an Active Object. + * Instead, a special message should be passed into the Task via + * the put() method defined below, and the svc() method should + * interpret this as a flag to shut down the Task. + */ + virtual int close (u_long flags = 0); + + /** + * Hook called during ACE_Module::close(). The default + * implementation calls forwards the call to close(1). Please + * notice the changed value of the default argument of close(). + * This allows tasks to differ between the call has been originated + * from ACE_Thread_Exit or from module_closed(). Be aware that + * close(0) will be also called when a thread associated with the + * ACE_Task instance exits. + */ + virtual int module_closed (void); + + // = Immediate and deferred processing methods, respectively. + + // These methods should be overridden by subclasses if you'd like to + // provide -specific message processing behavior. + + /// A hook method that can be used to pass a message to a + /// task, where it can be processed immediately or queued for subsequent + /// processing in the svc() hook method. + virtual int put (ACE_Message_Block *, ACE_Time_Value * = 0); + + /// Run by a daemon thread to handle deferred processing. + virtual int svc (void); + + // = Active object activation method. + /** + * Turn the task into an active object, i.e., having @a n_threads of + * control, all running at the @a priority level (see below) with the + * same @a grp_id, all of which invoke . Returns -1 if + * failure occurs, returns 1 if Task is already an active object and + * @a force_active is false (i.e., do *not* create a new thread in + * this case), and returns 0 if Task was not already an active + * object and a thread is created successfully or thread is an + * active object and @a force_active is true. Note that if + * @a force_active is true and there are already threads spawned in + * this , the @a grp_id parameter is ignored and the @a grp_id + * of any newly activated thread(s) will inherit the existing + * @a grp_id of the existing thread(s) in the . + * + * The <{flags}> are a bitwise-OR of the following: + * = BEGIN + * THR_CANCEL_DISABLE, THR_CANCEL_ENABLE, THR_CANCEL_DEFERRED, + * THR_CANCEL_ASYNCHRONOUS, THR_BOUND, THR_NEW_LWP, THR_DETACHED, + * THR_SUSPENDED, THR_DAEMON, THR_JOINABLE, THR_SCHED_FIFO, + * THR_SCHED_RR, THR_SCHED_DEFAULT, THR_EXPLICIT_SCHED, + * THR_SCOPE_SYSTEM, THR_SCOPE_PROCESS + * = END + * If THR_SCHED_INHERIT is not desirable, applications should + * specifically pass in THR_EXPLICIT_SCHED. + * + * + * By default, or if <{priority}> is set to + * ACE_DEFAULT_THREAD_PRIORITY, an "appropriate" priority value for + * the given scheduling policy (specified in <{flags}>, e.g., + * ) is used. This value is calculated + * dynamically, and is the median value between the minimum and + * maximum priority values for the given policy. If an explicit + * value is given, it is used. Note that actual priority values are + * EXTREMEMLY implementation-dependent, and are probably best + * avoided. + * + * If @a thread_handles != 0 it is assumed to be an array of @a n + * thread_handles that will be assigned the values of the thread + * handles being spawned. Returns -1 on failure (@c errno will + * explain...), otherwise returns the group id of the threads. + * + * Assigning @a task allows you to associate the newly spawned + * threads with an instance of ACE_Task_Base. If @a task == 0, then + * the new threads are associated automatically with @c this + * ACE_Task_Base. Setting the @a task argument to value other than + * @c this makes the thread manipulating methods, such as wait(), + * suspend(), resume(), useless. Threads spawned with user + * specified @a task value must therefore be manipulated thru + * ACE_Thread_Manager directly. + * + * If @a stack != 0 it is assumed to be an array of @a n pointers to + * the base of the stacks to use for the threads being spawned. + * Likewise, if @a stack_size != 0 it is assumed to be an array of + * @a n values indicating how big each of the corresponding @a stacks + * are. + * + * + */ + virtual int activate (long flags = THR_NEW_LWP | THR_JOINABLE | THR_INHERIT_SCHED, + int n_threads = 1, + int force_active = 0, + long priority = ACE_DEFAULT_THREAD_PRIORITY, + int grp_id = -1, + ACE_Task_Base *task = 0, + ACE_hthread_t thread_handles[] = 0, + void *stack[] = 0, + size_t stack_size[] = 0, + ACE_thread_t thread_ids[] = 0, + const char* thr_name[] = 0); + + /** + * Block until there are no more threads running in this task. + * This method will not wait for either detached or daemon threads; + * the threads must have been spawned with the @c THR_JOINABLE flag. + * Upon successful completion, the threads have been joined, so further + * attempts to join with any of the waited-for threads will fail. + * + * @retval 0 Success. + * @retval -1 Failure (consult errno for further information). + */ + virtual int wait (void); + + // = Suspend/resume a Task. + + // Note that these methods are not portable and should be avoided + // since they are inherently error-prone to use. They are only here + // for (the rare) applications that know how to use them correctly. + /// Suspend a task. + virtual int suspend (void); + /// Resume a suspended task. + virtual int resume (void); + + /// Get the current group id. + int grp_id (void) const; + + /// Set the current group id. + void grp_id (int); + + /// Get the thread manager associated with this Task. + ACE_Thread_Manager *thr_mgr (void) const; + + /// Set the thread manager associated with this Task. + void thr_mgr (ACE_Thread_Manager *); + + /// True if queue is a reader, else false. + int is_reader (void) const; + + /// True if queue is a writer, else false. + int is_writer (void) const; + + /** + * Returns the number of threads currently running within a task. + * If we're a passive object this value is 0, else it's greater than + * 0. + */ + size_t thr_count (void) const; + + /** + * Returns the thread ID of the thread whose exit caused this object's + * thread count to be decremented to 0. + * + * When a thread spawned in the context of this object (using activate()) + * returns from its svc() method ACE calls the close() hook. Before it does + * so, it decrements the number of active threads. If the number of threads + * is decremented to 0, the thread ID of the current thread is stored for + * access by this method. If the returned thread ID matches the calling + * thread's ID, the calling thread knows that there are no other threads + * still active in the ACE_Task. + * + * @retval ACE_thread_t of the last thread to close. 0 if the last thread + * is not yet known; for example, if no threads are active, or if + * multiple threads are active. + */ + ACE_thread_t last_thread (void) const; + + /// Routine that runs the service routine as a daemon thread. + static ACE_THR_FUNC_RETURN svc_run (void *); + + /// Cleanup hook that is called when a thread exits to gracefully + /// shutdown an ACE_Task. + static void cleanup (void *object, void *params); + +protected: + /** + * Count of the number of threads running within the task. If this + * value is greater than 0 then we're an active object and the value + * of is the number of active threads at this instant. + * If the value == 0, then we're a passive object. + */ + size_t thr_count_; + + /// Multi-threading manager. + ACE_Thread_Manager *thr_mgr_; + + /// ACE_Task flags. + u_long flags_; + + /// This maintains the group id of the Task. + int grp_id_; + +#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) + /// Protect the state of a Task during concurrent operations, but + /// only if we're configured as MT safe... + ACE_Thread_Mutex lock_; +#endif /* ACE_MT_SAFE */ + + /// Holds the thread ID of the last thread to exit svc() in this object. + ACE_thread_t last_thread_id_; + +private: + + // = Disallow these operations. + ACE_Task_Base &operator= (const ACE_Task_Base &); + ACE_Task_Base (const ACE_Task_Base &); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Task.inl" +#endif /* __ACE_INLINE__ */ + +// Include the ACE_Task templates classes at this point. +#include "ace/Task_T.h" + +#include /**/ "ace/post.h" +#endif /* ACE_TASK_H */ diff --git a/dep/acelite/ace/Task.inl b/dep/acelite/ace/Task.inl new file mode 100644 index 00000000000..9f70371e5f5 --- /dev/null +++ b/dep/acelite/ace/Task.inl @@ -0,0 +1,77 @@ +// -*- C++ -*- +// +// $Id: Task.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Get the current group id. +ACE_INLINE int +ACE_Task_Base::grp_id (void) const +{ + ACE_TRACE ("ACE_Task_Base::grp_id"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, const_cast (this->lock_), -1)); + return this->grp_id_; +} + +// Set the current group id. + +ACE_INLINE void +ACE_Task_Base::grp_id (int identifier) +{ + ACE_TRACE ("ACE_Task_Base::grp_id"); + ACE_MT (ACE_GUARD (ACE_Thread_Mutex, ace_mon, this->lock_)); + + // Cache the group id in the task and then set it in the + // Thread_Manager, if there is one. + this->grp_id_ = identifier; + if (this->thr_mgr ()) + this->thr_mgr ()->set_grp (this, identifier); +} + +ACE_INLINE ACE_Thread_Manager * +ACE_Task_Base::thr_mgr (void) const +{ + ACE_TRACE ("ACE_Task_Base::thr_mgr"); + return this->thr_mgr_; +} + +ACE_INLINE void +ACE_Task_Base::thr_mgr (ACE_Thread_Manager *thr_mgr) +{ + ACE_TRACE ("ACE_Task_Base::thr_mgr"); + this->thr_mgr_ = thr_mgr; +} + +ACE_INLINE int +ACE_Task_Base::is_reader (void) const +{ + ACE_TRACE ("ACE_Task_Base::is_reader"); + return (ACE_BIT_ENABLED (this->flags_, ACE_Task_Flags::ACE_READER)); +} + +ACE_INLINE int +ACE_Task_Base::is_writer (void) const +{ + ACE_TRACE ("ACE_Task_Base::is_writer"); + return (ACE_BIT_DISABLED (this->flags_, ACE_Task_Flags::ACE_READER)); +} + +// Return the count of the current number of threads. +ACE_INLINE size_t +ACE_Task_Base::thr_count (void) const +{ + ACE_TRACE ("ACE_Task_Base::thr_count"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, const_cast (this->lock_), 0)); + + return this->thr_count_; +} + +// Return the thread ID of the last thread to exit svc(). +ACE_INLINE ACE_thread_t +ACE_Task_Base::last_thread (void) const +{ + ACE_TRACE ("ACE_Task_Base::last_thread"); + return this->last_thread_id_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Task_Ex_T.cpp b/dep/acelite/ace/Task_Ex_T.cpp new file mode 100644 index 00000000000..de97e5ba6b4 --- /dev/null +++ b/dep/acelite/ace/Task_Ex_T.cpp @@ -0,0 +1,114 @@ +// $Id: Task_Ex_T.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#ifndef ACE_TASK_EX_T_CPP +#define ACE_TASK_EX_T_CPP + +#include "ace/Task_Ex_T.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Module.h" +#include "ace/Null_Condition.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Task_Ex_T.inl" +#endif /* __ACE_INLINE__ */ + + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template void +ACE_Task_Ex::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Task_Ex::dump"); + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nthr_mgr_ = %x"), this->thr_mgr_)); + this->msg_queue_->dump (); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("delete_msg_queue_ = %d\n"), this->delete_msg_queue_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nflags = %x"), this->flags_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nmod_ = %x"), this->mod_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nnext_ = %x"), this->next_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ngrp_id_ = %d"), this->grp_id_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nthr_count_ = %d"), this->thr_count_)); +#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) + this->lock_.dump (); +#endif /* ACE_MT_SAFE */ + + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +// If the user doesn't supply a ACE_Message_Queue_Ex pointer then we'll +// allocate one dynamically. Otherwise, we'll use the one they give. + +template +ACE_Task_Ex::ACE_Task_Ex (ACE_Thread_Manager *thr_man, + ACE_Message_Queue_Ex *mq) + : ACE_Task_Base (thr_man), + msg_queue_ (0), + delete_msg_queue_ (false), + mod_ (0), + next_ (0) +{ + ACE_TRACE ("ACE_Task_Ex::ACE_Task_Ex"); + + if (mq == 0) + { + ACE_NEW (mq, + (ACE_Message_Queue_Ex)); + this->delete_msg_queue_ = true; + } + + this->msg_queue_ = mq; +} + +template +ACE_Task_Ex::~ACE_Task_Ex (void) +{ + ACE_TRACE ("ACE_Task_Ex::~ACE_Task_Ex"); + if (this->delete_msg_queue_) + delete this->msg_queue_; + + // These assignments aren't strickly necessary but they help guard + // against odd race conditions... + this->delete_msg_queue_ = false; +} + +template ACE_Task * +ACE_Task_Ex::sibling (void) +{ + ACE_TRACE ("ACE_Task_Ex::sibling"); + /// @todo FIXME Need to impl ACE_Moudle to support ACE_Task as well. + /// Now always return 0 for sibling + return 0; +/* + if (this->mod_ == 0) + return 0; + else + return this->mod_->sibling (this); +*/ +} + +template const ACE_TCHAR * +ACE_Task_Ex::name (void) const +{ + ACE_TRACE ("ACE_Task_Ex::name"); + if (this->mod_ == 0) + return 0; + else + return this->mod_->name (); +} + +template ACE_Module * +ACE_Task_Ex::module (void) const +{ + ACE_TRACE ("ACE_Task_Ex::module"); + return this->mod_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_TASK_EX_T_CPP */ diff --git a/dep/acelite/ace/Task_Ex_T.h b/dep/acelite/ace/Task_Ex_T.h new file mode 100644 index 00000000000..00233d4e7d9 --- /dev/null +++ b/dep/acelite/ace/Task_Ex_T.h @@ -0,0 +1,205 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Task_Ex_T.h + * + * $Id: Task_Ex_T.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Kobi Cohen-Arazi + */ +//============================================================================= + +#ifndef ACE_TASK_EX_T_H +#define ACE_TASK_EX_T_H +#include /**/ "ace/pre.h" + +#include "ace/Service_Object.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Synch_Traits.h" +#include "ace/Task.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Forward decls... +template class ACE_Module; + +/** + * @class ACE_Task_Ex + * + * @brief Primary interface for application message processing, as well + * as input and output message queueing. + * + * Unlike ACE_Task, these class doesn't have the ability to be a part of + * a Stream chain. I.e. You cannot (yet) chain modules based on ACE_Task_Ex. + * + * @todo: We can merge ACE_Task and ACE_Task_Ex to be one class. + * something like that: + * template + * class ACE_Task : public ACE_Task_Base + * { + * // use here the code from ACE_Task_Ex using ACE_Message_Queue_Ex + * }; + * + * Now specialized version of ACE_Task with ACE_Message_Block as its + * ACE_MESSAGE_TYPE... + * + * template + * class ACE_Task : public ACE_Task_Base + * { + * // put here the good old ACE_Task code + * }; + * + * When User (and legacy code) write ACE_Task, specialized ACE_Task + * code is in action. + */ +template +class ACE_Task_Ex : public ACE_Task_Base +{ +public: + friend class ACE_Module; + friend class ACE_Module_Type; + typedef ACE_Message_Queue_Ex MESSAGE_QUEUE_EX; + + // = Initialization/termination methods. + /** + * Initialize a Task, supplying a thread manager and a message + * queue. If the user doesn't supply a ACE_Message_Queue pointer + * then we'll allocate one dynamically. Otherwise, we'll use the + * one passed as a parameter. + */ + ACE_Task_Ex (ACE_Thread_Manager *thr_mgr = 0, + MESSAGE_QUEUE_EX *mq = 0); + + /// Destructor. + virtual ~ACE_Task_Ex (void); + + /// Gets the message queue associated with this task. + MESSAGE_QUEUE_EX *msg_queue (void); + + /// Sets the message queue associated with this task. + void msg_queue (MESSAGE_QUEUE_EX *); + +public: // Should be protected: + // = Message queue manipulation methods. + + // = Enqueue and dequeue methods. + + // For the following five method if @a timeout == 0, the caller will + // block until action is possible, else will wait until the + // <{absolute}> time specified in *@a timeout elapses). These calls + // will return, however, when queue is closed, deactivated, when a + // signal occurs, or if the time specified in timeout elapses, (in + // which case errno = EWOULDBLOCK). + + /// Insert message into the message queue. Note that @a timeout uses + /// <{absolute}> time rather than <{relative}> time. + int putq (ACE_MESSAGE_TYPE *, ACE_Time_Value *timeout = 0); + + /** + * Extract the first message from the queue (blocking). Note that + * @a timeout uses <{absolute}> time rather than <{relative}> time. + * Returns number of items in queue if the call succeeds or -1 otherwise. + */ + int getq (ACE_MESSAGE_TYPE *&mb, ACE_Time_Value *timeout = 0); + + /// Return a message to the queue. Note that @a timeout uses + /// <{absolute}> time rather than <{relative}> time. + int ungetq (ACE_MESSAGE_TYPE *, ACE_Time_Value *timeout = 0); + + /** + * Turn the message around and send it back down the Stream. Note + * that @a timeout uses <{absolute}> time rather than <{relative}> + * time. + */ + int reply (ACE_MESSAGE_TYPE *, ACE_Time_Value *timeout = 0); + + /** + * Transfer message to the adjacent ACE_Task_Ex in a ACE_Stream. Note + * that @a timeout uses <{absolute}> time rather than <{relative}> + * time. + */ + int put_next (ACE_MESSAGE_TYPE *msg, ACE_Time_Value *timeout = 0); + + /** + * Tests whether we can enqueue a message without blocking. + * @deprecated This method is deprecated and will go away in the future. + */ + int can_put (ACE_MESSAGE_TYPE *); + + // = ACE_Task utility routines to identify names et al. + /// Return the name of the enclosing Module if there's one associated + /// with the Task, else returns 0. + const ACE_TCHAR *name (void) const; + + // = Pointers to next ACE_Task_Base (if ACE is part of an ACE_Stream). + /// Get next Task pointer. + ACE_Task *next (void); + + /// Set next Task pointer. + void next (ACE_Task *); + + /// Alwasy return 0. @todo FIXME + ACE_Task *sibling (void); + + /// Return the Task's Module if there is one, else returns 0. + ACE_Module *module (void) const; + + /** + * Flush the task's queue, i.e., free all of the enqueued + * message blocks and releases any threads blocked on the queue. + * Note that if this conflicts with the C++ iostream + * function, just rewrite the iostream function as ::. + */ + int flush (u_long flag = ACE_Task_Flags::ACE_FLUSHALL); + + // = Special routines corresponding to certain message types. + + /// Manipulate watermarks. + void water_marks (ACE_IO_Cntl_Msg::ACE_IO_Cntl_Cmds, size_t); + + /// Queue of messages on the ACE_Task.. + MESSAGE_QUEUE_EX *msg_queue_; + + /// true if should delete Message_Queue, false otherwise. + bool delete_msg_queue_; + + /// Back-pointer to the enclosing module. + ACE_Module *mod_; + + /// Pointer to adjacent ACE_Task. + ACE_Task *next_; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + + // = Disallow these operations. + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Task_Ex &)) + ACE_UNIMPLEMENTED_FUNC (ACE_Task_Ex (const ACE_Task_Ex &)) +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Task_Ex_T.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Task_Ex_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Task_Ex_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" +#endif /* ACE_TASK_EX_H */ diff --git a/dep/acelite/ace/Task_Ex_T.inl b/dep/acelite/ace/Task_Ex_T.inl new file mode 100644 index 00000000000..dd90bcd499a --- /dev/null +++ b/dep/acelite/ace/Task_Ex_T.inl @@ -0,0 +1,109 @@ +// -*- C++ -*- +// +// $Id: Task_Ex_T.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template ACE_INLINE void +ACE_Task_Ex::water_marks (ACE_IO_Cntl_Msg::ACE_IO_Cntl_Cmds cmd, + size_t wm_size) +{ + ACE_TRACE ("ACE_Task_Ex::water_marks"); + if (cmd == ACE_IO_Cntl_Msg::SET_LWM) + this->msg_queue_->low_water_mark (wm_size); + else /* cmd == ACE_IO_Cntl_Msg::SET_HWM */ + this->msg_queue_->high_water_mark (wm_size); +} + +template ACE_INLINE int +ACE_Task_Ex::getq (ACE_MESSAGE_TYPE *&mb, ACE_Time_Value *tv) +{ + ACE_TRACE ("ACE_Task_Ex::getq"); + return this->msg_queue_->dequeue_head (mb, tv); +} + +template ACE_INLINE int +ACE_Task_Ex::can_put (ACE_MESSAGE_TYPE *) +{ + ACE_TRACE ("ACE_Task_Ex::can_put"); + ACE_NOTSUP_RETURN (-1); +} + +template ACE_INLINE int +ACE_Task_Ex::putq (ACE_MESSAGE_TYPE *mb, ACE_Time_Value *tv) +{ + ACE_TRACE ("ACE_Task_Ex::putq"); + return this->msg_queue_->enqueue_tail (mb, tv); +} + +template ACE_INLINE int +ACE_Task_Ex::ungetq (ACE_MESSAGE_TYPE *mb, ACE_Time_Value *tv) +{ + ACE_TRACE ("ACE_Task_Ex::ungetq"); + return this->msg_queue_->enqueue_head (mb, tv); +} + +template ACE_INLINE int +ACE_Task_Ex::flush (u_long flag) +{ + ACE_TRACE ("ACE_Task_Ex::flush"); + if (ACE_BIT_ENABLED (flag, ACE_Task_Flags::ACE_FLUSHALL)) + return this->msg_queue_ != 0 && this->msg_queue_->close (); + else + return -1; // Note, need to be more careful about what we free... +} + +template ACE_INLINE void +ACE_Task_Ex::msg_queue (ACE_Message_Queue_Ex *mq) +{ + ACE_TRACE ("ACE_Task_Ex::msg_queue"); + if (this->delete_msg_queue_) + { + delete this->msg_queue_; + this->delete_msg_queue_ = false; + } + this->msg_queue_ = mq; +} + +template ACE_Message_Queue_Ex * +ACE_Task_Ex::msg_queue (void) +{ + ACE_TRACE ("ACE_Task_Ex::msg_queue"); + return this->msg_queue_; +} + +template ACE_INLINE int +ACE_Task_Ex::reply (ACE_MESSAGE_TYPE *mb, ACE_Time_Value *tv) +{ + ACE_TRACE ("ACE_Task_Ex::reply"); + ACE_UNUSED_ARG (mb); + ACE_UNUSED_ARG (tv); + return -1 ; // this->sibling ()->put_next (mb, tv); +} + +template ACE_INLINE ACE_Task * +ACE_Task_Ex::next (void) +{ + ACE_TRACE ("ACE_Task_Ex::next"); + return this->next_; +} + +template ACE_INLINE void +ACE_Task_Ex::next (ACE_Task *q) +{ + ACE_TRACE ("ACE_Task_Ex::next"); + this->next_ = q; +} + +// Transfer msg to the next ACE_Task_Ex. + +template ACE_INLINE int +ACE_Task_Ex::put_next ( + ACE_MESSAGE_TYPE * /* msg */, + ACE_Time_Value * /* tv */) +{ + ACE_TRACE ("ACE_Task_Ex::put_next"); + return -1; // this->next_ == 0 ? -1 : this->next_->put (msg, tv); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Task_T.cpp b/dep/acelite/ace/Task_T.cpp new file mode 100644 index 00000000000..08b36f82f08 --- /dev/null +++ b/dep/acelite/ace/Task_T.cpp @@ -0,0 +1,108 @@ +// $Id: Task_T.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#ifndef ACE_TASK_T_CPP +#define ACE_TASK_T_CPP + +#include "ace/Task_T.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Module.h" +#include "ace/Null_Condition.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Task_T.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template void +ACE_Task::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Task::dump"); + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nthr_mgr_ = %x"), this->thr_mgr_)); + this->msg_queue_->dump (); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("delete_msg_queue_ = %d\n"), this->delete_msg_queue_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nflags = %x"), this->flags_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nmod_ = %x"), this->mod_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nnext_ = %x"), this->next_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ngrp_id_ = %d"), this->grp_id_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nthr_count_ = %d"), this->thr_count_)); +#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) + this->lock_.dump (); +#endif /* ACE_MT_SAFE */ + + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +// If the user doesn't supply a ACE_Message_Queue pointer then we'll +// allocate one dynamically. Otherwise, we'll use the one they give. + +template +ACE_Task::ACE_Task (ACE_Thread_Manager *thr_man, + ACE_Message_Queue *mq) + : ACE_Task_Base (thr_man), + msg_queue_ (0), + delete_msg_queue_ (false), + mod_ (0), + next_ (0) +{ + ACE_TRACE ("ACE_Task::ACE_Task"); + + if (mq == 0) + { + ACE_NEW (mq, + ACE_Message_Queue); + this->delete_msg_queue_ = true; + } + + this->msg_queue_ = mq; +} + +template +ACE_Task::~ACE_Task (void) +{ + ACE_TRACE ("ACE_Task::~ACE_Task"); + if (this->delete_msg_queue_) + delete this->msg_queue_; + + // These assignments aren't strickly necessary but they help guard + // against odd race conditions... + this->delete_msg_queue_ = false; +} + +template ACE_Task * +ACE_Task::sibling (void) +{ + ACE_TRACE ("ACE_Task::sibling"); + if (this->mod_ == 0) + return 0; + else + return this->mod_->sibling (this); +} + +template const ACE_TCHAR * +ACE_Task::name (void) const +{ + ACE_TRACE ("ACE_Task::name"); + if (this->mod_ == 0) + return 0; + else + return this->mod_->name (); +} + +template ACE_Module * +ACE_Task::module (void) const +{ + ACE_TRACE ("ACE_Task::module"); + return this->mod_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_TASK_T_CPP */ diff --git a/dep/acelite/ace/Task_T.h b/dep/acelite/ace/Task_T.h new file mode 100644 index 00000000000..d79a5fb0e46 --- /dev/null +++ b/dep/acelite/ace/Task_T.h @@ -0,0 +1,198 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Task_T.h + * + * $Id: Task_T.h 91016 2010-07-06 11:29:50Z johnnyw $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_TASK_T_H +#define ACE_TASK_T_H +#include /**/ "ace/pre.h" + +#include "ace/Message_Queue.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Synch_Traits.h" +#include "ace/Task.h" +#include "ace/IO_Cntl_Msg.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Forward decls... +template class ACE_Module; + +/** + * @class ACE_Task + * + * @brief Primary interface for application message processing, as well + * as input and output message queueing. + * + * This class serves as the basis for passive and active objects + * in ACE. + */ +template +class ACE_Task : public ACE_Task_Base +{ +public: + friend class ACE_Module; + friend class ACE_Module_Type; + + // = Initialization/termination methods. + /** + * Initialize a Task, supplying a thread manager and a message + * queue. If the user doesn't supply a ACE_Message_Queue pointer + * then we'll allocate one dynamically. Otherwise, we'll use the + * one passed as a parameter. + */ + ACE_Task (ACE_Thread_Manager *thr_mgr = 0, + ACE_Message_Queue *mq = 0); + + /// Destructor. + virtual ~ACE_Task (void); + + /// Gets the message queue associated with this task. + ACE_Message_Queue *msg_queue (void); + + /// Sets the message queue associated with this task. + void msg_queue (ACE_Message_Queue *); + +public: // Should be protected: + // = Message queue manipulation methods. + + // = Enqueue and dequeue methods. + + // For the following five method if @a timeout == 0, the caller will + // block until action is possible, else will wait until the + // <{absolute}> time specified in *@a timeout elapses). These calls + // will return, however, when queue is closed, deactivated, when a + // signal occurs, or if the time specified in timeout elapses, (in + // which case errno = EWOULDBLOCK). + + /// Insert message into the message queue. Note that @a timeout uses + /// <{absolute}> time rather than <{relative}> time. + int putq (ACE_Message_Block *, ACE_Time_Value *timeout = 0); + + /** + * Extract the first message from the queue (blocking). Note that + * @a timeout uses <{absolute}> time rather than <{relative}> time. + * Returns number of items in queue if the call succeeds or -1 otherwise. + */ + int getq (ACE_Message_Block *&mb, ACE_Time_Value *timeout = 0); + + /// Return a message to the queue. Note that @a timeout uses + /// <{absolute}> time rather than <{relative}> time. + int ungetq (ACE_Message_Block *, ACE_Time_Value *timeout = 0); + + /** + * Turn the message around, sending it in the opposite direction in + * the stream. To do this, the message is put onto the task next in + * the stream after this task's sibling. + * + * @param mb Pointer to the block that is used in the reply. + * @param tv The absolute time at which the put operation used to + * send the message block to the next module in the stream + * will time out. If 0, this call blocks until it can be + * completed. + */ + int reply (ACE_Message_Block *mb, ACE_Time_Value *tv = 0); + + /** + * Transfer message to the adjacent ACE_Task in a ACE_Stream. Note + * that @a timeout uses <{absolute}> time rather than <{relative}> + * time. + */ + int put_next (ACE_Message_Block *msg, ACE_Time_Value *timeout = 0); + + /** + * Tests whether we can enqueue a message without blocking. + * + * @deprecated This method is deprecated and will go away in the future. + */ + int can_put (ACE_Message_Block *); + + // = ACE_Task utility routines to identify names et al. + /// Return the name of the enclosing Module if there's one associated + /// with the Task, else returns 0. + const ACE_TCHAR *name (void) const; + + // = Pointers to next ACE_Task_Base (if ACE is part of an ACE_Stream). + /// Get next Task pointer. + ACE_Task *next (void); + + /// Set next Task pointer. + void next (ACE_Task *); + + /// Return the Task's sibling if there's one associated with the + /// Task's Module, else returns 0. + ACE_Task *sibling (void); + + /// Return the Task's Module if there is one, else returns 0. + ACE_Module *module (void) const; + + /** + * Flush the task's queue, i.e., free all of the enqueued + * message blocks and unblocks any threads waiting on the queue. + * Note that if this conflicts with the C++ iostream + * function, just rewrite the iostream function as ::. + */ + int flush (u_long flag = ACE_Task_Flags::ACE_FLUSHALL); + + // = Special routines corresponding to certain message types. + + /// Manipulate watermarks. + void water_marks (ACE_IO_Cntl_Msg::ACE_IO_Cntl_Cmds, size_t); + + /// Queue of messages on the ACE_Task.. + ACE_Message_Queue *msg_queue_; + + /// true if should delete Message_Queue, false otherwise. + bool delete_msg_queue_; + + /// Back-pointer to the enclosing module. + ACE_Module *mod_; + + /// Pointer to adjacent ACE_Task. + ACE_Task *next_; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + + // = Disallow these operations. + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Task &)) + ACE_UNIMPLEMENTED_FUNC (ACE_Task (const ACE_Task &)) +}; + +#if defined ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION_EXPORT +template class ACE_Export ACE_Task; +template class ACE_Export ACE_Task; +#endif /* ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION_EXPORT */ + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Task_T.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Task_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Task_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" +#endif /* ACE_TASK_T_H */ diff --git a/dep/acelite/ace/Task_T.inl b/dep/acelite/ace/Task_T.inl new file mode 100644 index 00000000000..a441ca9d0b3 --- /dev/null +++ b/dep/acelite/ace/Task_T.inl @@ -0,0 +1,105 @@ +// -*- C++ -*- +// +// $Id: Task_T.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template ACE_INLINE void +ACE_Task::water_marks (ACE_IO_Cntl_Msg::ACE_IO_Cntl_Cmds cmd, + size_t wm_size) +{ + ACE_TRACE ("ACE_Task::water_marks"); + if (cmd == ACE_IO_Cntl_Msg::SET_LWM) + this->msg_queue_->low_water_mark (wm_size); + else /* cmd == ACE_IO_Cntl_Msg::SET_HWM */ + this->msg_queue_->high_water_mark (wm_size); +} + +template ACE_INLINE int +ACE_Task::getq (ACE_Message_Block *&mb, ACE_Time_Value *tv) +{ + ACE_TRACE ("ACE_Task::getq"); + return this->msg_queue_->dequeue_head (mb, tv); +} + +template ACE_INLINE int +ACE_Task::can_put (ACE_Message_Block *) +{ + ACE_TRACE ("ACE_Task::can_put"); + ACE_NOTSUP_RETURN (-1); +} + +template ACE_INLINE int +ACE_Task::putq (ACE_Message_Block *mb, ACE_Time_Value *tv) +{ + ACE_TRACE ("ACE_Task::putq"); + return this->msg_queue_->enqueue_tail (mb, tv); +} + +template ACE_INLINE int +ACE_Task::ungetq (ACE_Message_Block *mb, ACE_Time_Value *tv) +{ + ACE_TRACE ("ACE_Task::ungetq"); + return this->msg_queue_->enqueue_head (mb, tv); +} + +template ACE_INLINE int +ACE_Task::flush (u_long flag) +{ + ACE_TRACE ("ACE_Task::flush"); + if (ACE_BIT_ENABLED (flag, ACE_Task_Flags::ACE_FLUSHALL)) + return this->msg_queue_ != 0 && this->msg_queue_->close (); + else + return -1; // Note, need to be more careful about what we free... +} + +template ACE_INLINE void +ACE_Task::msg_queue (ACE_Message_Queue *mq) +{ + ACE_TRACE ("ACE_Task::msg_queue"); + if (this->delete_msg_queue_) + { + delete this->msg_queue_; + this->delete_msg_queue_ = false; + } + this->msg_queue_ = mq; +} + +template ACE_Message_Queue * +ACE_Task::msg_queue (void) +{ + ACE_TRACE ("ACE_Task::msg_queue"); + return this->msg_queue_; +} + +template ACE_INLINE int +ACE_Task::reply (ACE_Message_Block *mb, ACE_Time_Value *tv) +{ + ACE_TRACE ("ACE_Task::reply"); + return this->sibling ()->put_next (mb, tv); +} + +template ACE_INLINE ACE_Task * +ACE_Task::next (void) +{ + ACE_TRACE ("ACE_Task::next"); + return this->next_; +} + +template ACE_INLINE void +ACE_Task::next (ACE_Task *q) +{ + ACE_TRACE ("ACE_Task::next"); + this->next_ = q; +} + +// Transfer msg to the next ACE_Task. + +template ACE_INLINE int +ACE_Task::put_next (ACE_Message_Block *msg, ACE_Time_Value *tv) +{ + ACE_TRACE ("ACE_Task::put_next"); + return this->next_ == 0 ? -1 : this->next_->put (msg, tv); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Test_and_Set.cpp b/dep/acelite/ace/Test_and_Set.cpp new file mode 100644 index 00000000000..15fbfe084f5 --- /dev/null +++ b/dep/acelite/ace/Test_and_Set.cpp @@ -0,0 +1,51 @@ +// $Id: Test_and_Set.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#ifndef ACE_TEST_AND_SET_CPP +#define ACE_TEST_AND_SET_CPP + +#include "ace/Test_and_Set.h" +#include "ace/Guard_T.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template +ACE_Test_and_Set::ACE_Test_and_Set (TYPE initial_value) + : is_set_ (initial_value) +{ +} + +// Returns true if we are done, else false. +template TYPE +ACE_Test_and_Set::is_set (void) const +{ + ACE_GUARD_RETURN (ACE_LOCK, ace_mon, (ACE_LOCK &) this->lock_, this->is_set_); + return this->is_set_; +} + +// Sets the status. +template TYPE +ACE_Test_and_Set::set (TYPE status) +{ + ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->lock_, this->is_set_); + TYPE o_status = this->is_set_; + this->is_set_ = status; + return o_status; +} + +template int +ACE_Test_and_Set::handle_signal (int, siginfo_t *, ucontext_t *) +{ + // By setting this to 1, we are "signaling" to anyone calling + // or or that the "test and set" object is in the + // "signaled" state, i.e., it's "available" to be set back to 0. + this->set (1); + return 0; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_TEST_AND_SET_CPP */ diff --git a/dep/acelite/ace/Test_and_Set.h b/dep/acelite/ace/Test_and_Set.h new file mode 100644 index 00000000000..062de0bc804 --- /dev/null +++ b/dep/acelite/ace/Test_and_Set.h @@ -0,0 +1,75 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Test_and_Set.h + * + * $Id: Test_and_Set.h 80826 2008-03-04 14:51:23Z wotte $ + */ +//============================================================================= + + +#ifndef ACE_TEST_AND_SET_H +#define ACE_TEST_AND_SET_H + +#include /**/ "ace/pre.h" +#include "ace/Event_Handler.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Test_and_Set + * + * @brief Implements the classic ``test and set'' operation. + * + * + * This class keeps track of the status of , which can + * be set based on various events (such as receipt of a + * signal). This class is derived from ACE_Event_Handler so + * that it can be "signaled" by a Reactor when a signal occurs. + * We assume that is a data type that can be assigned the + * value 0 or 1. + */ +template +class ACE_Test_and_Set : public ACE_Event_Handler +{ +public: + ACE_Test_and_Set (TYPE initial_value = 0); + + /// Returns true if we are set, else false. + TYPE is_set (void) const; + + /// Sets the status, returning the original value of + /// . + TYPE set (TYPE); + + /// Called when object is signaled by OS (either via UNIX signals or + /// when a Win32 object becomes signaled). + virtual int handle_signal (int signum, + siginfo_t * = 0, + ucontext_t * = 0); + +private: + /// Keeps track of our state. + TYPE is_set_; + + /// Protect the state from race conditions. + ACE_LOCK lock_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Test_and_Set.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Test_and_Set.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" +#endif /* ACE_TEST_AND_SET_H */ diff --git a/dep/acelite/ace/Thread.cpp b/dep/acelite/ace/Thread.cpp new file mode 100644 index 00000000000..2fb009b67d2 --- /dev/null +++ b/dep/acelite/ace/Thread.cpp @@ -0,0 +1,101 @@ +// $Id: Thread.cpp 84163 2009-01-15 07:57:27Z johnnyw $ + +#include "ace/Thread.h" + +ACE_RCSID(ace, + Thread, + "$Id: Thread.cpp 84163 2009-01-15 07:57:27Z johnnyw $") + +#if !defined (__ACE_INLINE__) +#include "ace/Thread.inl" +#endif /* !defined (__ACE_INLINE__) */ + +#if defined (ACE_HAS_THREADS) + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +size_t +ACE_Thread::spawn_n (size_t n, + ACE_THR_FUNC func, + void *arg, + long flags, + long priority, + void *stack[], + size_t stack_size[], + ACE_Thread_Adapter *thread_adapter, + const char* thr_name[]) +{ + ACE_TRACE ("ACE_Thread::spawn_n"); + size_t i; + + for (i = 0; i < n; i++) + { + ACE_thread_t t_id; + // Bail out if error occurs. + if (ACE_OS::thr_create (func, + arg, + flags, + &t_id, + 0, + priority, + stack == 0 ? 0 : stack[i], + stack_size == 0 ? ACE_DEFAULT_THREAD_STACKSIZE : stack_size[i], + thread_adapter, + thr_name == 0 ? 0 : &thr_name[i]) != 0) + break; + } + + return i; +} + +size_t +ACE_Thread::spawn_n (ACE_thread_t thread_ids[], + size_t n, + ACE_THR_FUNC func, + void *arg, + long flags, + long priority, + void *stack[], + size_t stack_size[], + ACE_hthread_t thread_handles[], + ACE_Thread_Adapter *thread_adapter, + const char* thr_name[]) +{ + ACE_TRACE ("ACE_Thread::spawn_n"); + size_t i = 0; + + for (i = 0; i < n; i++) + { + ACE_thread_t t_id; + ACE_hthread_t t_handle; + + int const result = + ACE_OS::thr_create (func, + arg, + flags, + &t_id, + &t_handle, + priority, + stack == 0 ? 0 : stack[i], + stack_size == 0 ? ACE_DEFAULT_THREAD_STACKSIZE : stack_size[i], + thread_adapter, + thr_name == 0 ? 0 : &thr_name[i]); + + if (result == 0) + { + if (thread_ids != 0) + thread_ids[i] = t_id; + if (thread_handles != 0) + thread_handles[i] = t_handle; + } + else + // Bail out if error occurs. + break; + } + + return i; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_THREADS */ diff --git a/dep/acelite/ace/Thread.h b/dep/acelite/ace/Thread.h new file mode 100644 index 00000000000..4d44858fa5b --- /dev/null +++ b/dep/acelite/ace/Thread.h @@ -0,0 +1,282 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file Thread.h + * + * $Id: Thread.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Douglas Schmidt + */ +//========================================================================== + +#ifndef ACE_THREAD_H +#define ACE_THREAD_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/OS_NS_Thread.h" +#include "ace/Thread_Adapter.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +struct cancel_state +{ + /// e.g., PTHREAD_CANCEL_ENABLE, PTHREAD_CANCEL_DISABLE, + /// PTHREAD_CANCELED. + int cancelstate; + + /// e.g., PTHREAD_CANCEL_DEFERRED and PTHREAD_CANCEL_ASYNCHRONOUS. + int canceltype; +}; + +/** + * @class ACE_Thread + * + * @brief Provides a wrapper for threads. + * + * This class provides a common interface that is mapped onto + * POSIX Pthreads, Solaris threads, Win32 threads, VxWorks + * threads, or pSoS threads. Note, however, that it is + * generally a better idea to use the ACE_Thread_Manager + * programming API rather than the API since the + * thread manager is more powerful. + */ +class ACE_Export ACE_Thread +{ +public: + /** + * Creates a new thread having @a flags attributes and running @a func + * with (if is non-0 then @a func and + * are ignored and are obtained from ). + * and are set to the thread's ID and handle (?), + * respectively. The thread runs at @a priority priority (see + * below). + * + * The @a flags are a bitwise-OR of the following: + * = BEGIN + * THR_CANCEL_DISABLE, THR_CANCEL_ENABLE, THR_CANCEL_DEFERRED, + * THR_CANCEL_ASYNCHRONOUS, THR_BOUND, THR_NEW_LWP, THR_DETACHED, + * THR_SUSPENDED, THR_DAEMON, THR_JOINABLE, THR_SCHED_FIFO, + * THR_SCHED_RR, THR_SCHED_DEFAULT, THR_EXPLICIT_SCHED, + * THR_SCOPE_SYSTEM, THR_SCOPE_PROCESS + * = END + * + * By default, or if @a priority is set to + * ACE_DEFAULT_THREAD_PRIORITY, an "appropriate" priority value for + * the given scheduling policy (specified in , e.g., + * ) is used. This value is calculated + * dynamically, and is the median value between the minimum and + * maximum priority values for the given policy. If an explicit + * value is given, it is used. Note that actual priority values are + * EXTREMEMLY implementation-dependent, and are probably best + * avoided. + * + * Note that is always deleted when + * is called, so it must be allocated with global operator new. + */ + static int spawn (ACE_THR_FUNC func, + void *arg = 0, + long flags = THR_NEW_LWP | THR_JOINABLE, + ACE_thread_t *t_id = 0, + ACE_hthread_t *t_handle = 0, + long priority = ACE_DEFAULT_THREAD_PRIORITY, + void *stack = 0, + size_t stack_size = ACE_DEFAULT_THREAD_STACKSIZE, + ACE_Thread_Adapter *thread_adapter = 0, + const char** thr_name = 0); + + /** + * Spawn N new threads, which execute @a func with argument @a arg (if + * @a thread_adapter is non-0 then @a func and @a args are ignored and + * are obtained from @a thread_adapter). If @a stack != 0 it is + * assumed to be an array of @a n pointers to the base of the stacks + * to use for the threads being spawned. Likewise, if @a stack_size + * != 0 it is assumed to be an array of @a n values indicating how + * big each of the corresponding @a stacks are. Returns the number + * of threads actually spawned (if this doesn't equal the number + * requested then something has gone wrong and @c errno will + * explain...). + * + * @see spawn() + */ + static size_t spawn_n (size_t n, + ACE_THR_FUNC func, + void *arg = 0, + long flags = THR_NEW_LWP | THR_JOINABLE, + long priority = ACE_DEFAULT_THREAD_PRIORITY, + void *stack[] = 0, + size_t stack_size[] = 0, + ACE_Thread_Adapter *thread_adapter = 0, + const char* thr_name[] = 0); + + /** + * Spawn @a n new threads, which execute @a func with argument @a arg + * (if @a thread_adapter is non-0 then @a func and @a args are ignored + * and are obtained from @a thread_adapter). The thread_ids of + * successfully spawned threads will be placed into the + * buffer (which must be the same size as @a n). If @a stack != 0 it + * is assumed to be an array of @a n pointers to the base of the + * stacks to use for the threads being spawned. If @a stack_size != + * 0 it is assumed to be an array of @a n values indicating how big + * each of the corresponding @a stacks are. If @a thread_handles != 0 + * it is assumed to be an array of @a n thread_handles that will be + * assigned the values of the thread handles being spawned. Returns + * the number of threads actually spawned (if this doesn't equal the + * number requested then something has gone wrong and @c errno will + * explain...). + * + * @see spawn() + */ + static size_t spawn_n (ACE_thread_t thread_ids[], + size_t n, + ACE_THR_FUNC func, + void *arg, + long flags, + long priority = ACE_DEFAULT_THREAD_PRIORITY, + void *stack[] = 0, + size_t stack_size[] = 0, + ACE_hthread_t thread_handles[] = 0, + ACE_Thread_Adapter *thread_adapter = 0, + const char* thr_name[] = 0); + + /** + * Wait for one or more threads to exit and reap their exit status. + * thr_join() returns successfully when the target thread terminates. + * + * @param thread_id is the ACE_thread_t ID of the thread to wait for. + * If @a thread_id is 0, join() waits for any + * undetached thread in the process to terminate + * on platforms that support this capability + * (for example, Solaris). + * @param departed points to a location that is set to the ID of the + * terminated thread if join() returns successfully. + * If @a departed is 0, it is ignored. + * @param status Points to the location that receives the joined + * thread's exit value. If @a status is 0, it is ignored. + * + * @retval 0 for success + * @retval -1 (with errno set) for failure. + */ + static int join (ACE_thread_t thread_id, + ACE_thread_t *departed, + ACE_THR_FUNC_RETURN *status); + + /// Wait for one thread to exit and reap its exit status. + static int join (ACE_hthread_t, + ACE_THR_FUNC_RETURN * = 0); + + /// Continue the execution of a previously suspended thread. + static int resume (ACE_hthread_t); + + /// Suspend the execution of a particular thread. + static int suspend (ACE_hthread_t); + + /// Get the priority of a particular thread. + static int getprio (ACE_hthread_t ht_id, int &priority); + + /// Get the priority and policy of a particular thread. + static int getprio (ACE_hthread_t ht_id, int &priority, int &policy); + + /// Set the priority of a particular thread. + static int setprio (ACE_hthread_t ht_id, int priority, int policy = -1); + + /// Send a signal to the thread. + static int kill (ACE_thread_t, int signum); + + /// Yield the thread to another. + static void yield (void); + + /** + * Return the unique kernel handle of the thread. Note that on + * Win32 this is actually a pseudohandle, which cannot be shared + * with other processes or waited on by threads. To locate the real + * handle, please use the ACE_Thread_Manager::thr_self() method. + */ + static void self (ACE_hthread_t &t_handle); + + /// Return the unique ID of the thread. + static ACE_thread_t self (void); + + /// Exit the current thread and return "status". + /// Should _not_ be called by main thread. + static void exit (ACE_THR_FUNC_RETURN status = 0); + + /// Get the LWP concurrency level of the process. + static int getconcurrency (void); + + /// Set the LWP concurrency level of the process. + static int setconcurrency (int new_level); + + /// Change and/or examine calling thread's signal mask. + static int sigsetmask (int how, + const sigset_t *sigset, + sigset_t *osigset = 0); + + /** + * Allocates a @a keyp that is used to identify data that is specific + * to each thread in the process. The key is global to all threads + * in the process. + */ + static int keycreate (ACE_thread_key_t *keyp, +#if defined (ACE_HAS_THR_C_DEST) + ACE_THR_C_DEST destructor, +#else + ACE_THR_DEST destructor, +#endif /* ACE_HAS_THR_C_DEST */ + void * = 0); + + /// Free up the key so that other threads can reuse it. + static int keyfree (ACE_thread_key_t key); + + /// Bind value to the thread-specific data key, @a key, for the calling + /// thread. + static int setspecific (ACE_thread_key_t key, + void *value); + + /// Stores the current value bound to @a key for the calling thread + /// into the location pointed to by @a valuep. + static int getspecific (ACE_thread_key_t key, + void **valuep); + + /// Disable thread cancellation. + static int disablecancel (struct cancel_state *old_state); + + /// Enable thread cancellation. + static int enablecancel (struct cancel_state *old_state, + int flag); + + /// Set the cancellation state. + static int setcancelstate (struct cancel_state &new_state, + struct cancel_state *old_state); + + /** + * Cancel a thread. + * @note This method is only portable on platforms, such as POSIX pthreads, + * that support thread cancellation. + */ + static int cancel (ACE_thread_t t_id); + + /// Test the cancel. + static void testcancel (void); + +private: + /// Ensure that we don't get instantiated. + ACE_Thread (void); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Thread.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" + +#endif /* ACE_THREAD_H */ diff --git a/dep/acelite/ace/Thread.inl b/dep/acelite/ace/Thread.inl new file mode 100644 index 00000000000..87e47e13580 --- /dev/null +++ b/dep/acelite/ace/Thread.inl @@ -0,0 +1,286 @@ +// -*- C++ -*- +// +// $Id: Thread.inl 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/OS_NS_string.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Allocates a that is used to identify data that is specific +// to each thread in the process. The key is global to all threads in +// the process. + +ACE_INLINE int +ACE_Thread::keycreate (ACE_thread_key_t *keyp, +#if defined (ACE_HAS_THR_C_DEST) + ACE_THR_C_DEST destructor, +#else + ACE_THR_DEST destructor, +#endif /* ACE_HAS_THR_C_DEST */ + void *inst) +{ + // ACE_TRACE ("ACE_Thread::keycreate"); + return ACE_OS::thr_keycreate (keyp, destructor, inst); +} + +// Free up the key so that other threads can reuse it. + +ACE_INLINE int +ACE_Thread::keyfree (ACE_thread_key_t key) +{ + ACE_TRACE ("ACE_Thread::keyfree"); + return ACE_OS::thr_keyfree (key); +} + +// Bind value to the thread-specific data key, , for the calling +// thread. + +ACE_INLINE int +ACE_Thread::setspecific (ACE_thread_key_t key, void *value) +{ + // ACE_TRACE ("ACE_Thread::setspecific"); + return ACE_OS::thr_setspecific (key, value); +} + +// Stores the current value bound to for the calling thread +// into the location pointed to by . + +ACE_INLINE int +ACE_Thread::getspecific (ACE_thread_key_t key, void **valuep) +{ + // ACE_TRACE ("ACE_Thread::getspecific"); + return ACE_OS::thr_getspecific (key, valuep); +} + +ACE_INLINE ACE_thread_t +ACE_Thread::self (void) +{ +// ACE_TRACE ("ACE_Thread::self"); + return ACE_OS::thr_self (); +} + +ACE_INLINE void +ACE_Thread::exit (ACE_THR_FUNC_RETURN status) +{ + ACE_TRACE ("ACE_Thread::exit"); + ACE_OS::thr_exit (status); +} + +ACE_INLINE void +ACE_Thread::yield (void) +{ + ACE_TRACE ("ACE_Thread::yield"); + ACE_OS::thr_yield (); +} + +ACE_INLINE int +ACE_Thread::spawn (ACE_THR_FUNC func, + void *arg, + long flags, + ACE_thread_t *t_id, + ACE_hthread_t *t_handle, + long priority, + void *thr_stack, + size_t thr_stack_size, + ACE_Thread_Adapter *thread_adapter, + const char** thr_name) +{ + ACE_TRACE ("ACE_Thread::spawn"); + + return ACE_OS::thr_create (func, + arg, + flags, + t_id, + t_handle, + priority, + thr_stack, + thr_stack_size, + thread_adapter, + thr_name); +} + +ACE_INLINE int +ACE_Thread::resume (ACE_hthread_t t_id) +{ + ACE_TRACE ("ACE_Thread::resume"); + return ACE_OS::thr_continue (t_id); +} + +ACE_INLINE int +ACE_Thread::suspend (ACE_hthread_t t_id) +{ + ACE_TRACE ("ACE_Thread::suspend"); + return ACE_OS::thr_suspend (t_id); +} + +ACE_INLINE int +ACE_Thread::kill (ACE_thread_t t_id, int signum) +{ + ACE_TRACE ("ACE_Thread::kill"); + return ACE_OS::thr_kill (t_id, signum); +} + +ACE_INLINE int +ACE_Thread::join (ACE_thread_t wait_for, + ACE_thread_t *departed, + ACE_THR_FUNC_RETURN *status) +{ + ACE_TRACE ("ACE_Thread::join"); + return ACE_OS::thr_join (wait_for, departed, status); +} + +ACE_INLINE int +ACE_Thread::join (ACE_hthread_t wait_for, + ACE_THR_FUNC_RETURN *status) +{ + ACE_TRACE ("ACE_Thread::join"); + return ACE_OS::thr_join (wait_for, status); +} + +ACE_INLINE int +ACE_Thread::getconcurrency (void) +{ + ACE_TRACE ("ACE_Thread::getconcurrency"); + return ACE_OS::thr_getconcurrency (); +} + +ACE_INLINE int +ACE_Thread::setconcurrency (int new_level) +{ + ACE_TRACE ("ACE_Thread::setconcurrency"); + return ACE_OS::thr_setconcurrency (new_level); +} + +ACE_INLINE int +ACE_Thread::sigsetmask (int how, + const sigset_t *sigset, + sigset_t *osigset) +{ + ACE_TRACE ("ACE_Thread::sigsetmask"); + return ACE_OS::thr_sigsetmask (how, sigset, osigset); +} + +ACE_INLINE int +ACE_Thread::disablecancel (struct cancel_state *old_state) +{ + ACE_TRACE ("ACE_Thread::disablecancel"); + int old_cstate = 0; + int result = ACE_OS::thr_setcancelstate (THR_CANCEL_DISABLE, + &old_cstate); + if (result == 0 && old_state != 0) + { + ACE_OS::memset (old_state, + 0, + sizeof (old_state)); + old_state->cancelstate = old_cstate; + } + + return result; +} + +ACE_INLINE int +ACE_Thread::enablecancel (struct cancel_state *old_state, + int flag) +{ + ACE_TRACE ("ACE_Thread::enablecancel"); + int old_cstate = 0; + int old_ctype = 0; + int result; + + result = ACE_OS::thr_setcancelstate (THR_CANCEL_ENABLE, + &old_cstate); + if (result != 0) + return result; + + result = ACE_OS::thr_setcanceltype (flag, + &old_ctype); + if (result != 0) + return result; + + if (old_state != 0) + { + old_state->cancelstate = old_cstate; + old_state->canceltype = old_ctype; + } + + return 0; +} + +ACE_INLINE int +ACE_Thread::setcancelstate (struct cancel_state &new_state, + struct cancel_state *old_state) +{ + ACE_TRACE ("ACE_Thread::setcancelstate"); + int old_cstate = 0; + int old_ctype = 0; + + if (new_state.cancelstate != 0 + && ACE_OS::thr_setcancelstate (new_state.cancelstate, + &old_cstate) != 0) + return -1; + + if (new_state.canceltype != 0 + && ACE_OS::thr_setcanceltype (new_state.canceltype, + &old_ctype) != 0) + { + int o_cstate; + + ACE_OS::thr_setcancelstate (old_cstate, + &o_cstate); + return -1; + } + + if (old_state != 0) + { + old_state->cancelstate = old_cstate; + old_state->canceltype = old_ctype; + } + + return 0; +} + +ACE_INLINE int +ACE_Thread::cancel (ACE_thread_t t_id) +{ + ACE_TRACE ("ACE_Thread::cancel"); + + return ACE_OS::thr_cancel (t_id); +} + +ACE_INLINE void +ACE_Thread::testcancel (void) +{ + ACE_TRACE ("ACE_Thread::testcancel"); + + ACE_OS::thr_testcancel (); +} + +ACE_INLINE void +ACE_Thread::self (ACE_hthread_t &t_id) +{ +// ACE_TRACE ("ACE_Thread::self"); + ACE_OS::thr_self (t_id); +} + +ACE_INLINE int +ACE_Thread::getprio (ACE_hthread_t ht_id, int &priority) +{ + ACE_TRACE ("ACE_Thread::getprio"); + return ACE_OS::thr_getprio (ht_id, priority); +} + +ACE_INLINE int +ACE_Thread::getprio (ACE_hthread_t ht_id, int &priority, int &policy) +{ + ACE_TRACE ("ACE_Thread::getprio"); + return ACE_OS::thr_getprio (ht_id, priority, policy); +} + +ACE_INLINE int +ACE_Thread::setprio (ACE_hthread_t ht_id, int priority, int policy) +{ + ACE_TRACE ("ACE_Thread::setprio"); + return ACE_OS::thr_setprio (ht_id, priority, policy); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Thread_Adapter.cpp b/dep/acelite/ace/Thread_Adapter.cpp new file mode 100644 index 00000000000..9dbad0580b8 --- /dev/null +++ b/dep/acelite/ace/Thread_Adapter.cpp @@ -0,0 +1,228 @@ +// $Id: Thread_Adapter.cpp 81239 2008-04-04 22:28:48Z iliyan $ + +#include "ace/Thread_Adapter.h" +#include "ace/Thread_Manager.h" +#include "ace/Thread_Exit.h" +#include "ace/Thread_Hook.h" +#include "ace/Object_Manager_Base.h" +#include "ace/Service_Config.h" + +ACE_RCSID (ace, + Thread_Adapter, + "$Id: Thread_Adapter.cpp 81239 2008-04-04 22:28:48Z iliyan $") + +#if !defined (ACE_HAS_INLINED_OSCALLS) +# include "ace/Thread_Adapter.inl" +#endif /* ACE_HAS_INLINED_OSCALLS */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_Thread_Adapter::ACE_Thread_Adapter (ACE_THR_FUNC user_func, + void *arg, + ACE_THR_C_FUNC entry_point, + ACE_Thread_Manager *tm, + ACE_Thread_Descriptor *td +#if defined (ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS) + , ACE_SEH_EXCEPT_HANDLER selector, + ACE_SEH_EXCEPT_HANDLER handler +#endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */ + ) + : ACE_Base_Thread_Adapter ( + user_func + , arg + , entry_point + , td +#if defined (ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS) + , selector + , handler +#endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */ + ) + , thr_mgr_ (tm) +{ + ACE_OS_TRACE ("ACE_Thread_Adapter::ACE_Thread_Adapter"); +} + +ACE_Thread_Adapter::~ACE_Thread_Adapter (void) +{ +} + +ACE_THR_FUNC_RETURN +ACE_Thread_Adapter::invoke (void) +{ + // Inherit the logging features if the parent thread has an + // ACE_Log_Msg instance in thread-specific storage. + this->inherit_log_msg (); + + ACE_Service_Config::current (ACE_Service_Config::global()); + +#if !defined(ACE_USE_THREAD_MANAGER_ADAPTER) + // NOTE: this preprocessor directive should match the one in above + // ACE_Thread_Exit::instance (). With the Xavier Pthreads package, + // the exit_hook in TSS causes a seg fault. So, this works around + // that by creating exit_hook on the stack. +# if defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION) + // Obtain our thread-specific exit hook and make sure that it knows + // how to clean us up! Note that we never use this pointer directly + // (it's stored in thread-specific storage), so it's ok to + // dereference it here and only store it as a reference. + + // Except if it is null, then the thr_mgr() method crashes. + // -jxh + + ACE_Thread_Exit *exit_hook_instance = ACE_Thread_Exit::instance (); + ACE_Thread_Exit_Maybe exit_hook_maybe (exit_hook_instance == 0); + ACE_Thread_Exit *exit_hook_ptr = exit_hook_instance + ? exit_hook_instance + : exit_hook_maybe.instance (); + ACE_Thread_Exit &exit_hook = *exit_hook_ptr; + + if (this->thr_mgr () != 0) + { + // Keep track of the that's associated with this + // . + exit_hook.thr_mgr (this->thr_mgr ()); + } +# else + // Without TSS, create an instance. When this + // function returns, its destructor will be called because the + // object goes out of scope. The drawback with this appraoch is + // that the destructor _won't_ get called if is called. + // So, threads shouldn't exit that way. Instead, they should return + // from . + ACE_Thread_Exit exit_hook; + exit_hook.thr_mgr (this->thr_mgr ()); +# endif /* ACE_HAS_THREAD_SPECIFIC_STORAGE || ACE_HAS_TSS_EMULATION */ + +#endif /* ! ACE_USE_THREAD_MANAGER_ADAPTER */ + + return this->invoke_i (); +} + +ACE_THR_FUNC_RETURN +ACE_Thread_Adapter::invoke_i (void) +{ + // Extract the arguments. + ACE_THR_FUNC func = reinterpret_cast (this->user_func_); + void *arg = this->arg_; + +#if defined (ACE_WIN32) && defined (ACE_HAS_MFC) && (ACE_HAS_MFC != 0) + ACE_OS_Thread_Descriptor *thr_desc = this->thr_desc_; +#endif /* ACE_WIN32 && ACE_HAS_MFC && (ACE_HAS_MFC != 0) */ + + // Delete ourselves since we don't need anymore. Make sure + // not to access anywhere below this point. + delete this; + +#if defined (ACE_NEEDS_LWP_PRIO_SET) + // On SunOS, the LWP priority needs to be set in order to get + // preemption when running in the RT class. This is the ACE way to + // do that . . . + ACE_hthread_t thr_handle; + ACE_OS::thr_self (thr_handle); + int prio; + + // thr_getprio () on the current thread should never fail. + ACE_OS::thr_getprio (thr_handle, prio); + + // ACE_OS::thr_setprio () has the special logic to set the LWP priority, + // if running in the RT class. + ACE_OS::thr_setprio (prio); + +#endif /* ACE_NEEDS_LWP_PRIO_SET */ + + ACE_THR_FUNC_RETURN status = 0; + + ACE_SEH_TRY + { + ACE_SEH_TRY + { + ACE_Thread_Hook *hook = + ACE_OS_Object_Manager::thread_hook (); + + if (hook) + // Invoke the start hook to give the user a chance to + // perform some initialization processing before the + // is invoked. + status = hook->start (func, arg); + else + // Call thread entry point. + status = (*func) (arg); + } + +#if defined (ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS) + ACE_SEH_EXCEPT (ACE_OS_Object_Manager::seh_except_selector ()( + (void *) GetExceptionInformation ())) + { + ACE_OS_Object_Manager::seh_except_handler ()(0); + } +#endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */ + } + + ACE_SEH_FINALLY + { + // If we changed this to 1, change the respective if in + // Task::svc_run to 0. +#if 0 + // Call the close> hook. + if (func == reinterpret_cast ( + ACE_Task_Base::svc_run)) + { + ACE_Task_Base *task_ptr = (ACE_Task_Base *) arg; + ACE_Thread_Manager *thr_mgr_ptr = task_ptr->thr_mgr (); + + // This calls the Task->close () hook. + task_ptr->cleanup (task_ptr, 0); + + // This prevents a second invocation of the cleanup code + // (called later by . + thr_mgr_ptr->at_exit (task_ptr, 0, 0); + } +#endif /* 0 */ + +#if defined (ACE_WIN32) || defined (ACE_HAS_TSS_EMULATION) +# if defined (ACE_WIN32) && defined (ACE_HAS_MFC) && (ACE_HAS_MFC != 0) + int using_afx = -1; + if (thr_desc) + using_afx = ACE_BIT_ENABLED (thr_desc->flags (), THR_USE_AFX); +# endif /* ACE_WIN32 && ACE_HAS_MFC && (ACE_HAS_MFC != 0) */ + // Call TSS destructors. + ACE_OS::cleanup_tss (0 /* not main thread */); + +# if defined (ACE_WIN32) + // Exit the thread. Allow CWinThread-destructor to be invoked + // from AfxEndThread. _endthreadex will be called from + // AfxEndThread so don't exit the thread now if we are running + // an MFC thread. +# if defined (ACE_HAS_MFC) && (ACE_HAS_MFC != 0) + if (using_afx != -1) + { + if (using_afx) + ::AfxEndThread ((DWORD) status); + else + ACE_ENDTHREADEX (status); + } + else + { + // Not spawned by ACE_Thread_Manager, use the old buggy + // version. You should seriously consider using + // ACE_Thread_Manager to spawn threads. The following code + // is know to cause some problem. + CWinThread *pThread = ::AfxGetThread (); + + if (!pThread || pThread->m_nThreadID != ACE_OS::thr_self ()) + ACE_ENDTHREADEX (status); + else + ::AfxEndThread ((DWORD)status); + } +# else + + ACE_ENDTHREADEX (status); +# endif /* ACE_HAS_MFC && ACE_HAS_MFS != 0*/ +# endif /* ACE_WIN32 */ +#endif /* ACE_WIN32 || ACE_HAS_TSS_EMULATION */ + } + + return status; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Thread_Adapter.h b/dep/acelite/ace/Thread_Adapter.h new file mode 100644 index 00000000000..8f1f259eff3 --- /dev/null +++ b/dep/acelite/ace/Thread_Adapter.h @@ -0,0 +1,100 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Thread_Adapter.h + * + * $Id: Thread_Adapter.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Carlos O'Ryan + */ +//============================================================================= + +#ifndef ACE_THREAD_ADAPTER_H +#define ACE_THREAD_ADAPTER_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Base_Thread_Adapter.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Forward decl. +class ACE_Thread_Manager; +class ACE_Thread_Descriptor; + +/** + * @class ACE_Thread_Adapter + * + * @brief Converts a C++ function into a function that + * can be called from a thread creation routine + * (e.g., pthread_create() or _beginthreadex()) that expects an + * extern "C" entry point. This class also makes it possible to + * transparently provide hooks to register a thread with an + * ACE_Thread_Manager. + * + * This class is used in ACE_OS::thr_create(). In general, the + * thread that creates an object of this class is different from + * the thread that calls @c invoke() on this object. Therefore, + * the @c invoke() method is responsible for deleting itself. + */ +class ACE_Export ACE_Thread_Adapter : public ACE_Base_Thread_Adapter +{ +public: + /// Constructor. + ACE_Thread_Adapter (ACE_THR_FUNC user_func, + void *arg, + ACE_THR_C_FUNC entry_point = (ACE_THR_C_FUNC) ACE_THREAD_ADAPTER_NAME, + ACE_Thread_Manager *thr_mgr = 0, + ACE_Thread_Descriptor *td = 0 +# if defined (ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS) + , ACE_SEH_EXCEPT_HANDLER selector = 0, + ACE_SEH_EXCEPT_HANDLER handler = 0 +# endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */ + ); + + /** + * Execute the with the . This function deletes + * @c this, thereby rendering the object useless after the call + * returns. + */ + virtual ACE_THR_FUNC_RETURN invoke (void); + + /// Accessor for the optional ACE_Thread_Manager. + ACE_Thread_Manager *thr_mgr (void); + +protected: + + /// Ensure that this object must be allocated on the heap. + ~ACE_Thread_Adapter (void); + +private: + + /// Called by invoke, mainly here to separate the SEH stuff because + /// SEH on Win32 doesn't compile with local vars with destructors. + virtual ACE_THR_FUNC_RETURN invoke_i (void); + +private: + + /// Optional thread manager. + ACE_Thread_Manager *thr_mgr_; + +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +# if defined (ACE_HAS_INLINED_OSCALLS) +# if defined (ACE_INLINE) +# undef ACE_INLINE +# endif /* ACE_INLINE */ +# define ACE_INLINE inline +# include "ace/Thread_Adapter.inl" +# endif /* ACE_HAS_INLINED_OSCALLS */ + +#include /**/ "ace/post.h" +#endif /* ACE_THREAD_ADAPTER_H */ diff --git a/dep/acelite/ace/Thread_Adapter.inl b/dep/acelite/ace/Thread_Adapter.inl new file mode 100644 index 00000000000..6def13be5ab --- /dev/null +++ b/dep/acelite/ace/Thread_Adapter.inl @@ -0,0 +1,13 @@ +// -*- C++ -*- +// +// $Id: Thread_Adapter.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE ACE_Thread_Manager * +ACE_Thread_Adapter::thr_mgr (void) +{ + return this->thr_mgr_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Thread_Control.cpp b/dep/acelite/ace/Thread_Control.cpp new file mode 100644 index 00000000000..51d0f4c18eb --- /dev/null +++ b/dep/acelite/ace/Thread_Control.cpp @@ -0,0 +1,96 @@ +// $Id: Thread_Control.cpp 80826 2008-03-04 14:51:23Z wotte $ + +// +#include "ace/config-all.h" +#if defined (ACE_LEGACY_MODE) +// This silly include breaks a cycle when compiling in backwards +// compatibility mode +# include "ace/Thread_Exit.h" +#endif /* ACE_LEGACY_MODE */ +// + +#include "ace/Thread_Control.h" +#include "ace/Thread_Manager.h" + +ACE_RCSID(ace, Thread_Control, "$Id: Thread_Control.cpp 80826 2008-03-04 14:51:23Z wotte $") + +#if !defined (ACE_HAS_INLINED_OSCALLS) +# include "ace/Thread_Control.inl" +#endif /* ACE_HAS_INLINED_OSCALLS */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +void +ACE_Thread_Control::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_OS_TRACE ("ACE_Thread_Control::dump"); +#endif /* ACE_HAS_DUMP */ +} + +int +ACE_Thread_Control::insert (ACE_Thread_Manager *tm, int insert) +{ + ACE_OS_TRACE ("ACE_Thread_Control::insert"); + + ACE_hthread_t t_id; + ACE_OS::thr_self (t_id); + this->tm_ = tm; + + if (insert) + return this->tm_->insert_thr (ACE_OS::thr_self (), t_id); + else + return 0; +} + +// Initialize the thread controller. + +ACE_Thread_Control::ACE_Thread_Control (ACE_Thread_Manager *t, + int insert) + : tm_ (t), + status_ (0) +{ + ACE_OS_TRACE ("ACE_Thread_Control::ACE_Thread_Control"); + + if (this->tm_ != 0 && insert) + { + ACE_hthread_t t_id; + ACE_OS::thr_self (t_id); + this->tm_->insert_thr (ACE_OS::thr_self (), t_id); + } +} + +// Automatically kill thread on exit. + +ACE_Thread_Control::~ACE_Thread_Control (void) +{ + ACE_OS_TRACE ("ACE_Thread_Control::~ACE_Thread_Control"); + +#if defined (ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS) || defined (ACE_HAS_TSS_EMULATION) || defined (ACE_WIN32) + this->exit (this->status_, 0); +#else + this->exit (this->status_, 1); +#endif /* ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS */ +} + +// Exit from thread (but clean up first). + +ACE_THR_FUNC_RETURN +ACE_Thread_Control::exit (ACE_THR_FUNC_RETURN exit_status, int do_thr_exit) +{ + ACE_OS_TRACE ("ACE_Thread_Control::exit"); + + if (this->tm_ != 0) + return this->tm_->exit (exit_status, do_thr_exit); + else + { +#if !defined (ACE_HAS_TSS_EMULATION) + // With ACE_HAS_TSS_EMULATION, we let ACE_Thread_Adapter::invoke () + // exit the thread after cleaning up TSS. + ACE_OS::thr_exit (exit_status); +#endif /* ! ACE_HAS_TSS_EMULATION */ + return 0; + } +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Thread_Control.h b/dep/acelite/ace/Thread_Control.h new file mode 100644 index 00000000000..3eb5185c84c --- /dev/null +++ b/dep/acelite/ace/Thread_Control.h @@ -0,0 +1,102 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Thread_Control.h + * + * $Id: Thread_Control.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Carlos O'Ryan + */ +//============================================================================= + + +#ifndef ACE_THREAD_CONTROL_H +#define ACE_THREAD_CONTROL_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +class ACE_Thread_Manager; + +/** + * @class ACE_Thread_Control + * + * @brief Used to keep track of a thread's activities within its entry + * point function. + * + * A ACE_Thread_Manager uses this class to ensure that threads + * it spawns automatically register and unregister themselves + * with it. + * This class can be stored in thread-specific storage using the + * ACE_TSS wrapper. When a thread exits the + * function deletes this object, thereby + * ensuring that it gets removed from its associated + * ACE_Thread_Manager. + */ +class ACE_Export ACE_Thread_Control +{ +public: + /// Initialize the thread control object. If @a insert != 0, then + /// register the thread with the Thread_Manager. + ACE_Thread_Control (ACE_Thread_Manager *tm = 0, + int insert = 0); + + /// Remove the thread from its associated and exit + /// the thread if is enabled. + ~ACE_Thread_Control (void); + + /// Remove this thread from its associated ACE_Thread_Manager and exit + /// the thread if @a do_thr_exit is enabled. + ACE_THR_FUNC_RETURN exit (ACE_THR_FUNC_RETURN status, + int do_thr_exit); + + /// Store the and use it to register ourselves for + /// correct shutdown. + int insert (ACE_Thread_Manager *tm, int insert = 0); + + /// Returns the current . + ACE_Thread_Manager *thr_mgr (void); + + /// Atomically set a new and return the old + /// . + ACE_Thread_Manager *thr_mgr (ACE_Thread_Manager *); + + /// Set the exit status (and return existing status). + ACE_THR_FUNC_RETURN status (ACE_THR_FUNC_RETURN status); + + /// Get the current exit status. + ACE_THR_FUNC_RETURN status (void); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + /// Pointer to the thread manager for this block of code. + ACE_Thread_Manager *tm_; + + /// Keeps track of the exit status for the thread. + ACE_THR_FUNC_RETURN status_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +# if defined (ACE_HAS_INLINED_OSCALLS) +# if defined (ACE_INLINE) +# undef ACE_INLINE +# endif /* ACE_INLINE */ +# define ACE_INLINE inline +# include "ace/Thread_Control.inl" +# endif /* ACE_HAS_INLINED_OSCALLS */ + +#include /**/ "ace/post.h" +#endif /* ACE_THREAD_CONTROL_H */ diff --git a/dep/acelite/ace/Thread_Control.inl b/dep/acelite/ace/Thread_Control.inl new file mode 100644 index 00000000000..6ebd3ac2c56 --- /dev/null +++ b/dep/acelite/ace/Thread_Control.inl @@ -0,0 +1,46 @@ +// -*- C++ -*- +// +// $Id: Thread_Control.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Set the exit status. + +ACE_INLINE ACE_THR_FUNC_RETURN +ACE_Thread_Control::status (ACE_THR_FUNC_RETURN s) +{ + ACE_OS_TRACE ("ACE_Thread_Control::status"); + return this->status_ = s; +} + +// Get the exit status. + +ACE_INLINE ACE_THR_FUNC_RETURN +ACE_Thread_Control::status (void) +{ + ACE_OS_TRACE ("ACE_Thread_Control::status"); + return this->status_; +} + +// Returns the current . + +ACE_INLINE ACE_Thread_Manager * +ACE_Thread_Control::thr_mgr (void) +{ + ACE_OS_TRACE ("ACE_Thread_Control::thr_mgr"); + return this->tm_; +} + +// Atomically set a new and return the old +// . + +ACE_INLINE ACE_Thread_Manager * +ACE_Thread_Control::thr_mgr (ACE_Thread_Manager *tm) +{ + ACE_OS_TRACE ("ACE_Thread_Control::thr_mgr"); + ACE_Thread_Manager *o_tm = this->tm_; + this->tm_ = tm; + return o_tm; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Thread_Exit.cpp b/dep/acelite/ace/Thread_Exit.cpp new file mode 100644 index 00000000000..cc6a8620cbe --- /dev/null +++ b/dep/acelite/ace/Thread_Exit.cpp @@ -0,0 +1,123 @@ +// $Id: Thread_Exit.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Thread_Exit.h" +#include "ace/Managed_Object.h" +#include "ace/Thread_Manager.h" +#include "ace/Guard_T.h" + +ACE_RCSID(ace, Thread_Exit, "$Id: Thread_Exit.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +bool ACE_Thread_Exit::is_constructed_ = false; + +void +ACE_Thread_Exit::cleanup (void *instance) +{ + ACE_OS_TRACE ("ACE_Thread_Exit::cleanup"); + + delete (ACE_TSS_TYPE (ACE_Thread_Exit) *) instance; + + // Set the thr_exit_ static to null to keep things from crashing if + // ACE::fini() is enabled here. + ACE_Thread_Manager::thr_exit_ = 0; + + ACE_Thread_Exit::is_constructed_ = false; + // All TSS objects have been destroyed. Reset this flag so + // ACE_Thread_Exit singleton can be created again. +} + +// NOTE: this preprocessor directive should match the one in +// ACE_Task_Base::svc_run () below. This prevents the two statics +// from being defined. + +ACE_Thread_Exit * +ACE_Thread_Exit::instance (void) +{ +#if defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION) + ACE_OS_TRACE ("ACE_Thread_Exit::instance"); + + // Determines if we were dynamically allocated. + static ACE_TSS_TYPE (ACE_Thread_Exit) * volatile instance_; + + // Implement the Double Check pattern. + + if (!ACE_Thread_Exit::is_constructed_) + { + ACE_MT (ACE_Thread_Mutex *lock = + ACE_Managed_Object::get_preallocated_object + (ACE_Object_Manager::ACE_THREAD_EXIT_LOCK); + ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, *lock, 0)); + + if (!ACE_Thread_Exit::is_constructed_) + { + ACE_NEW_RETURN (instance_, + ACE_TSS_TYPE (ACE_Thread_Exit), + 0); + + ACE_Thread_Exit::is_constructed_ = true; + + ACE_Thread_Manager::set_thr_exit (instance_); + } + } + + return ACE_TSS_GET (instance_, ACE_Thread_Exit); +#else + return 0; +#endif /* ACE_HAS_THREAD_SPECIFIC_STORAGE || ACE_HAS_TSS_EMULATION */ +} + +// Grab hold of the Task * so that we can close() it in the +// destructor. + +ACE_Thread_Exit::ACE_Thread_Exit (void) +{ + ACE_OS_TRACE ("ACE_Thread_Exit::ACE_Thread_Exit"); +} + +// Set the this pointer... + +void +ACE_Thread_Exit::thr_mgr (ACE_Thread_Manager *tm) +{ + ACE_OS_TRACE ("ACE_Thread_Exit::thr_mgr"); + + if (tm != 0) + this->thread_control_.insert (tm, 0); +} + +// When this object is destroyed the Task is automatically closed +// down! + +ACE_Thread_Exit::~ACE_Thread_Exit (void) +{ + ACE_OS_TRACE ("ACE_Thread_Exit::~ACE_Thread_Exit"); +} + +ACE_Thread_Exit_Maybe::ACE_Thread_Exit_Maybe (int flag) + : instance_ (0) +{ + if (flag) + { + ACE_NEW (instance_, ACE_Thread_Exit); + } +} + +ACE_Thread_Exit_Maybe::~ACE_Thread_Exit_Maybe (void) +{ + delete this->instance_; +} + +ACE_Thread_Exit * +ACE_Thread_Exit_Maybe::operator -> (void) const +{ + return this->instance_; +} + +ACE_Thread_Exit * +ACE_Thread_Exit_Maybe::instance (void) const +{ + return this->instance_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Thread_Exit.h b/dep/acelite/ace/Thread_Exit.h new file mode 100644 index 00000000000..5b614e2e807 --- /dev/null +++ b/dep/acelite/ace/Thread_Exit.h @@ -0,0 +1,111 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Thread_Exit.h + * + * $Id: Thread_Exit.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Carlos O'Ryan + */ +//============================================================================= + + +#ifndef ACE_THREAD_EXIT_H +#define ACE_THREAD_EXIT_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Thread_Control.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Thread_Exit + * + * @brief Keep exit information for a Thread in thread specific storage. + * so that the thread-specific exit hooks will get called no + * matter how the thread exits (e.g., via , C++ + * or Win32 exception, "falling off the end" of the thread entry + * point function, etc.). + * + * This clever little helper class is stored in thread-specific + * storage using the wrapper. When a thread exits the + * function deletes this object, thereby + * closing it down gracefully. + */ +class ACE_Export ACE_Thread_Exit +{ +public: + /// Capture the Thread that will be cleaned up automatically. + ACE_Thread_Exit (void); + + /// Set the ACE_Thread_Manager. + void thr_mgr (ACE_Thread_Manager *tm); + + /// Destructor calls the thread-specific exit hooks when a thread + /// exits. + ~ACE_Thread_Exit (void); + + /// Singleton access point. + static ACE_Thread_Exit *instance (void); + + /// Cleanup method, used by the ACE_Object_Manager to destroy the + /// singleton. + static void cleanup (void *instance); + +private: + /// Automatically add/remove the thread from the + /// ACE_Thread_Manager. + ACE_Thread_Control thread_control_; + + /** + * Used to detect whether we should create a new instance (or not) + * within the instance method -- we don't trust the instance_ ptr + * because the destructor may have run (if ACE::fini() was called). + * See bug #526. + * We don't follow the singleton pattern due to dependency issues. + */ + static bool is_constructed_; +}; + +/** + * @class ACE_Thread_Exit_Maybe + * + * @brief A version of ACE_Thread_Exit that is created dynamically + * under the hood if the flag is set to TRUE. + * + * Allows the appearance of a "smart pointer", but is not + * always created. + */ +class ACE_Export ACE_Thread_Exit_Maybe +{ +public: + /// Don't create an ACE_Thread_Exit instance by default. + ACE_Thread_Exit_Maybe (int flag = 0); + + /// Destroys the underlying ACE_Thread_Exit instance if it exists. + ~ACE_Thread_Exit_Maybe (void); + + /// Delegates to underlying instance. + ACE_Thread_Exit * operator -> (void) const; + + /// Returns the underlying instance. + ACE_Thread_Exit * instance (void) const; + +private: + + /// Holds the underlying instance. + ACE_Thread_Exit *instance_; + +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" +#endif /* ACE_THREAD_EXIT_H */ diff --git a/dep/acelite/ace/Thread_Hook.cpp b/dep/acelite/ace/Thread_Hook.cpp new file mode 100644 index 00000000000..79d937f9ff5 --- /dev/null +++ b/dep/acelite/ace/Thread_Hook.cpp @@ -0,0 +1,33 @@ +// $Id: Thread_Hook.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Thread_Hook.h" +#include "ace/Object_Manager_Base.h" + +ACE_RCSID(ace, Thread_Hook, "$Id: Thread_Hook.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_Thread_Hook::~ACE_Thread_Hook () +{ +} + +ACE_THR_FUNC_RETURN +ACE_Thread_Hook::start (ACE_THR_FUNC func, + void *arg) +{ + return (func) (arg); +} + +ACE_Thread_Hook * +ACE_Thread_Hook::thread_hook (ACE_Thread_Hook *hook) +{ + return ACE_OS_Object_Manager::thread_hook (hook); +} + +ACE_Thread_Hook * +ACE_Thread_Hook::thread_hook (void) +{ + return ACE_OS_Object_Manager::thread_hook (); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Thread_Hook.h b/dep/acelite/ace/Thread_Hook.h new file mode 100644 index 00000000000..7bc3bcce492 --- /dev/null +++ b/dep/acelite/ace/Thread_Hook.h @@ -0,0 +1,65 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Thread_Hook.h + * + * $Id: Thread_Hook.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Carlos O'Ryan + */ +//============================================================================= + + +#ifndef ACE_THREAD_HOOK_H +#define ACE_THREAD_HOOK_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include /**/ "ace/ACE_export.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Thread_Hook + * + * @brief This class makes it possible to provide user-defined "start" + * hooks that are called before the thread entry point function + * is invoked. + */ +class ACE_Export ACE_Thread_Hook +{ + +public: + + /// Destructor. + virtual ~ACE_Thread_Hook (void); + + /** + * This method can be overridden in a subclass to customize this + * pre-function call "hook" invocation that can perform + * initialization processing before the thread entry point @a func + * method is called back. The @a func and @a arg passed into the + * start hook are the same as those passed by the application that + * spawned the thread. + */ + virtual ACE_THR_FUNC_RETURN start (ACE_THR_FUNC func, + void *arg); + + /// sets the system wide thread hook, returns the previous thread + /// hook or 0 if none is set. + static ACE_Thread_Hook *thread_hook (ACE_Thread_Hook *hook); + + /// Returns the current system thread hook. + static ACE_Thread_Hook *thread_hook (void); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" +#endif /* ACE_THREAD_HOOK_H */ diff --git a/dep/acelite/ace/Thread_Manager.cpp b/dep/acelite/ace/Thread_Manager.cpp new file mode 100644 index 00000000000..4737dcbfaad --- /dev/null +++ b/dep/acelite/ace/Thread_Manager.cpp @@ -0,0 +1,2223 @@ +// $Id: Thread_Manager.cpp 85341 2009-05-14 11:07:37Z johnnyw $ + +#include "ace/TSS_T.h" +#include "ace/Thread_Manager.h" +#include "ace/Dynamic.h" +#include "ace/Object_Manager.h" +#include "ace/Singleton.h" +#include "ace/Auto_Ptr.h" +#include "ace/Guard_T.h" +#include "ace/Time_Value.h" +#include "ace/OS_NS_sys_time.h" +#include "ace/Truncate.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Thread_Manager.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID (ace, + Thread_Manager, + "$Id: Thread_Manager.cpp 85341 2009-05-14 11:07:37Z johnnyw $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_At_Thread_Exit::~ACE_At_Thread_Exit (void) +{ + this->do_apply (); +} + +ACE_At_Thread_Exit_Func::~ACE_At_Thread_Exit_Func (void) +{ + this->do_apply (); +} + +void +ACE_At_Thread_Exit_Func::apply (void) +{ + this->func_ (this->object_, this->param_); +} + +ACE_ALLOC_HOOK_DEFINE(ACE_Thread_Control) +ACE_ALLOC_HOOK_DEFINE(ACE_Thread_Manager) + +#if ! defined (ACE_THREAD_MANAGER_LACKS_STATICS) +// Process-wide Thread Manager. +ACE_Thread_Manager *ACE_Thread_Manager::thr_mgr_ = 0; + +// Controls whether the Thread_Manager is deleted when we shut down +// (we can only delete it safely if we created it!) +bool ACE_Thread_Manager::delete_thr_mgr_ = false; +#endif /* ! defined (ACE_THREAD_MANAGER_LACKS_STATICS) */ + +ACE_TSS_TYPE (ACE_Thread_Exit) *ACE_Thread_Manager::thr_exit_ = 0; + +int +ACE_Thread_Manager::set_thr_exit (ACE_TSS_TYPE (ACE_Thread_Exit) *ptr) +{ + if (ACE_Thread_Manager::thr_exit_ == 0) + ACE_Thread_Manager::thr_exit_ = ptr; + else + return -1; + return 0; +} + +void +ACE_Thread_Manager::dump (void) +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Thread_Manager::dump"); + // Cast away const-ness of this in order to use its non-const lock_. + ACE_MT (ACE_GUARD (ACE_Thread_Mutex, ace_mon, + ((ACE_Thread_Manager *) this)->lock_)); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ngrp_id_ = %d"), this->grp_id_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ncurrent_count_ = %d"), this->thr_list_.size ())); + + for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); + !iter.done (); + iter.advance ()) + { + iter.next ()->dump (); + } + + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +ACE_Thread_Descriptor::~ACE_Thread_Descriptor (void) +{ + delete this->sync_; +} + +void +ACE_Thread_Descriptor::at_pop (int apply) +{ + ACE_TRACE ("ACE_Thread_Descriptor::at_pop"); + // Get first at from at_exit_list + ACE_At_Thread_Exit* at = this->at_exit_list_; + // Remove at from at_exit list + this->at_exit_list_ = at->next_; + // Apply if required + if (apply) + { + at->apply (); + // Do the apply method + at->was_applied (true); + // Mark at has been applied to avoid double apply from + // at destructor + } + // If at is not owner delete at. + if (!at->is_owner ()) + delete at; +} + +void +ACE_Thread_Descriptor::at_push (ACE_At_Thread_Exit* cleanup, bool is_owner) +{ + ACE_TRACE ("ACE_Thread_Descriptor::at_push"); + cleanup->is_owner (is_owner); + cleanup->td_ = this; + cleanup->next_ = at_exit_list_; + at_exit_list_ = cleanup; +} + +int +ACE_Thread_Descriptor::at_exit (ACE_At_Thread_Exit& cleanup) +{ + ACE_TRACE ("ACE_Thread_Descriptor::at_exit"); + at_push (&cleanup, 1); + return 0; +} + +int +ACE_Thread_Descriptor::at_exit (ACE_At_Thread_Exit* cleanup) +{ + ACE_TRACE ("ACE_Thread_Descriptor::at_exit"); + if (cleanup==0) + return -1; + else + { + this->at_push (cleanup); + return 0; + } +} + +void +ACE_Thread_Descriptor::do_at_exit () +{ + ACE_TRACE ("ACE_Thread_Descriptor::do_at_exit"); + while (at_exit_list_!=0) + this->at_pop (); +} + +void +ACE_Thread_Descriptor::terminate () +{ + ACE_TRACE ("ACE_Thread_Descriptor::terminate"); + + if (!terminated_) + { + ACE_Log_Msg* log_msg = this->log_msg_; + terminated_ = true; + // Run at_exit hooks + this->do_at_exit (); + // We must remove Thread_Descriptor from Thread_Manager list + if (this->tm_ != 0) + { + int close_handle = 0; + +#if !defined (ACE_HAS_VXTHREADS) + // Threads created with THR_DAEMON shouldn't exist here, but + // just to be safe, let's put it here. + + if (ACE_BIT_DISABLED (this->thr_state_, ACE_Thread_Manager::ACE_THR_JOINING)) + { + if (ACE_BIT_DISABLED (this->flags_, THR_DETACHED | THR_DAEMON) + || ACE_BIT_ENABLED (this->flags_, THR_JOINABLE)) + { + // Mark thread as terminated. + ACE_SET_BITS (this->thr_state_, ACE_Thread_Manager::ACE_THR_TERMINATED); + tm_->register_as_terminated (this); + // Must copy the information here because td will be + // "freed" below. + } +#if defined (ACE_WIN32) + else + { + close_handle = 1; + } +#endif /* ACE_WIN32 */ + } +#endif /* !ACE_HAS_VXTHREADS */ + + // Remove thread descriptor from the table. + if (this->tm_ != 0) + tm_->remove_thr (this, close_handle); + } + + // Check if we need delete ACE_Log_Msg instance + // If ACE_TSS_cleanup was not executed first log_msg == 0 + if (log_msg == 0) + { + // Only inform to ACE_TSS_cleanup that it must delete the log instance + // setting ACE_LOG_MSG thr_desc to 0. + ACE_LOG_MSG->thr_desc (0); + } + else + { + // Thread_Descriptor is the owner of the Log_Msg instance!! + // deleted. + this->log_msg_ = 0; + delete log_msg; + } + } +} + +int +ACE_Thread_Descriptor::at_exit (void *object, + ACE_CLEANUP_FUNC cleanup_hook, + void *param) +{ + ACE_TRACE ("ACE_Thread_Descriptor::at_exit"); + // To keep compatibility, when cleanup_hook is null really is a at_pop + // without apply. + if (cleanup_hook == 0) + { + if (this->at_exit_list_!= 0) + this->at_pop(0); + } + else + { + ACE_At_Thread_Exit* cleanup = 0; + ACE_NEW_RETURN (cleanup, + ACE_At_Thread_Exit_Func (object, + cleanup_hook, + param), + -1); + this->at_push (cleanup); + } + return 0; +} + +void +ACE_Thread_Descriptor::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Thread_Descriptor::dump"); + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nthr_id_ = %d"), this->thr_id_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nthr_handle_ = %d"), this->thr_handle_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ngrp_id_ = %d"), this->grp_id_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nthr_state_ = %d"), this->thr_state_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nflags_ = %x\n"), this->flags_)); + + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +ACE_Thread_Descriptor::ACE_Thread_Descriptor (void) + : log_msg_ (0), + at_exit_list_ (0), + terminated_ (false) +{ + ACE_TRACE ("ACE_Thread_Descriptor::ACE_Thread_Descriptor"); + ACE_NEW (this->sync_, + ACE_DEFAULT_THREAD_MANAGER_LOCK); +} + +void +ACE_Thread_Descriptor::acquire_release (void) +{ + // Just try to acquire the lock then release it. +#if defined (ACE_THREAD_MANAGER_USES_SAFE_SPAWN) + if (ACE_BIT_DISABLED (this->thr_state_, ACE_Thread_Manager::ACE_THR_SPAWNED)) +#endif /* ACE_THREAD_MANAGER_USES_SAFE_SPAWN */ + { + this->sync_->acquire (); + // Acquire the lock before removing from the thread table. If + // this thread is in the table already, it should simply acquire the + // lock easily. + + // Once we get the lock, we must have registered. + ACE_ASSERT (ACE_BIT_ENABLED (this->thr_state_, ACE_Thread_Manager::ACE_THR_SPAWNED)); + + this->sync_->release (); + // Release the lock before putting it back to freelist. + } +} + +void +ACE_Thread_Descriptor::acquire (void) +{ + // Just try to acquire the lock then release it. +#if defined (ACE_THREAD_MANAGER_USES_SAFE_SPAWN) + if (ACE_BIT_DISABLED (this->thr_state_, ACE_Thread_Manager::ACE_THR_SPAWNED)) +#endif /* ACE_THREAD_MANAGER_USES_SAFE_SPAWN */ + { + this->sync_->acquire (); + } +} + +void +ACE_Thread_Descriptor::release (void) +{ + // Just try to acquire the lock then release it. +#if defined (ACE_THREAD_MANAGER_USES_SAFE_SPAWN) + if (ACE_BIT_DISABLED (this->thr_state_, ACE_Thread_Manager::ACE_THR_SPAWNED)) +#endif /* ACE_THREAD_MANAGER_USES_SAFE_SPAWN */ + { + this->sync_->release (); + // Release the lock before putting it back to freelist. + } +} + +// The following macro simplifies subsequence code. +#define ACE_FIND(OP,INDEX) \ + ACE_Thread_Descriptor *INDEX = OP; \ + +ACE_Thread_Descriptor * +ACE_Thread_Manager::thread_descriptor (ACE_thread_t thr_id) +{ + ACE_TRACE ("ACE_Thread_Manager::thread_descriptor"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0)); + + ACE_FIND (this->find_thread (thr_id), ptr); + return ptr; +} + +ACE_Thread_Descriptor * +ACE_Thread_Manager::hthread_descriptor (ACE_hthread_t thr_handle) +{ + ACE_TRACE ("ACE_Thread_Manager::hthread_descriptor"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0)); + + ACE_FIND (this->find_hthread (thr_handle), ptr); + return ptr; +} + +// Return the thread descriptor (indexed by ACE_hthread_t). + +int +ACE_Thread_Manager::thr_self (ACE_hthread_t &self) +{ + ACE_TRACE ("ACE_Thread_Manager::thr_self"); + + ACE_Thread_Descriptor *desc = + this->thread_desc_self (); + + if (desc == 0) + return -1; + else + desc->self (self); + + return 0; +} + +// Initialize the synchronization variables. + +ACE_Thread_Manager::ACE_Thread_Manager (size_t prealloc, + size_t lwm, + size_t inc, + size_t hwm) + : grp_id_ (1), + automatic_wait_ (1) +#if defined (ACE_HAS_THREADS) + , zero_cond_ (lock_) +#endif /* ACE_HAS_THREADS */ + , thread_desc_freelist_ (ACE_FREE_LIST_WITH_POOL, + prealloc, lwm, hwm, inc) +{ + ACE_TRACE ("ACE_Thread_Manager::ACE_Thread_Manager"); +} + +#if ! defined (ACE_THREAD_MANAGER_LACKS_STATICS) +ACE_Thread_Manager * +ACE_Thread_Manager::instance (void) +{ + ACE_TRACE ("ACE_Thread_Manager::instance"); + + if (ACE_Thread_Manager::thr_mgr_ == 0) + { + // Perform Double-Checked Locking Optimization. + ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, + *ACE_Static_Object_Lock::instance (), 0)); + + if (ACE_Thread_Manager::thr_mgr_ == 0) + { + ACE_NEW_RETURN (ACE_Thread_Manager::thr_mgr_, + ACE_Thread_Manager, + 0); + ACE_Thread_Manager::delete_thr_mgr_ = true; + } + } + + return ACE_Thread_Manager::thr_mgr_; +} + +ACE_Thread_Manager * +ACE_Thread_Manager::instance (ACE_Thread_Manager *tm) +{ + ACE_TRACE ("ACE_Thread_Manager::instance"); + ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, + *ACE_Static_Object_Lock::instance (), 0)); + + ACE_Thread_Manager *t = ACE_Thread_Manager::thr_mgr_; + // We can't safely delete it since we don't know who created it! + ACE_Thread_Manager::delete_thr_mgr_ = false; + + ACE_Thread_Manager::thr_mgr_ = tm; + return t; +} + +void +ACE_Thread_Manager::close_singleton (void) +{ + ACE_TRACE ("ACE_Thread_Manager::close_singleton"); + + ACE_MT (ACE_GUARD (ACE_Recursive_Thread_Mutex, ace_mon, + *ACE_Static_Object_Lock::instance ())); + + if (ACE_Thread_Manager::delete_thr_mgr_) + { + // First, we clean up the thread descriptor list. + ACE_Thread_Manager::thr_mgr_->close (); + delete ACE_Thread_Manager::thr_mgr_; + ACE_Thread_Manager::thr_mgr_ = 0; + ACE_Thread_Manager::delete_thr_mgr_ = false; + } + + ACE_Thread_Exit::cleanup (ACE_Thread_Manager::thr_exit_); +} +#endif /* ! defined (ACE_THREAD_MANAGER_LACKS_STATICS) */ + +// Close up and release all resources. + +int +ACE_Thread_Manager::close () +{ + ACE_TRACE ("ACE_Thread_Manager::close"); + + // Clean up the thread descriptor list. + if (this->automatic_wait_) + this->wait (0, 1); + else + { + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + + this->remove_thr_all (); + } + + return 0; +} + +ACE_Thread_Manager::~ACE_Thread_Manager (void) +{ + ACE_TRACE ("ACE_Thread_Manager::~ACE_Thread_Manager"); + this->close (); +} + + +// Run the entry point for thread spawned under the control of the +// . This must be an extern "C" to make certain +// compilers happy... +// +// The interaction with and +// works like this, with +// ACE_HAS_THREAD_SPECIFIC_STORAGE or ACE_HAS_TSS_EMULATION: +// +// o Every thread in the is run with +// . +// +// o retrieves the singleton +// instance from . +// The singleton gets created in thread-specific storage +// in the first call to that function. The key point is that the +// instance is in thread-specific storage. +// +// o A thread can exit by various means, such as , C++ +// or Win32 exception, "falling off the end" of the thread entry +// point function, etc. +// +// o If you follow this so far, now it gets really fun . . . +// When the thread-specific storage (for the thread that +// is being destroyed) is cleaned up, the OS threads package (or +// the ACE emulation of thread-specific storage) will destroy any +// objects that are in thread-specific storage. It has a list of +// them, and just walks down the list and destroys each one. +// +// o That's where the ACE_Thread_Exit destructor gets called. + +#if defined(ACE_USE_THREAD_MANAGER_ADAPTER) +extern "C" void * +ace_thread_manager_adapter (void *args) +{ +#if defined (ACE_HAS_TSS_EMULATION) + // As early as we can in the execution of the new thread, allocate + // its local TS storage. Allocate it on the stack, to save dynamic + // allocation/dealloction. + void *ts_storage[ACE_TSS_Emulation::ACE_TSS_THREAD_KEYS_MAX]; + ACE_TSS_Emulation::tss_open (ts_storage); +#endif /* ACE_HAS_TSS_EMULATION */ + + ACE_Thread_Adapter *thread_args = reinterpret_cast (args); + + // NOTE: this preprocessor directive should match the one in above + // ACE_Thread_Exit::instance (). With the Xavier Pthreads package, + // the exit_hook in TSS causes a seg fault. So, this works around + // that by creating exit_hook on the stack. +#if defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION) + // Obtain our thread-specific exit hook and make sure that it knows + // how to clean us up! Note that we never use this pointer directly + // (it's stored in thread-specific storage), so it's ok to + // dereference it here and only store it as a reference. + ACE_Thread_Exit &exit_hook = *ACE_Thread_Exit::instance (); +#else + // Without TSS, create an instance. When this + // function returns, its destructor will be called because the + // object goes out of scope. The drawback with this appraoch is + // that the destructor _won't_ get called if is called. + // So, threads shouldn't exit that way. Instead, they should return + // from . + ACE_Thread_Exit exit_hook; +#endif /* ACE_HAS_THREAD_SPECIFIC_STORAGE || ACE_HAS_TSS_EMULATION */ + + // Keep track of the that's associated with this + // . + exit_hook.thr_mgr (thread_args->thr_mgr ()); + + // Invoke the user-supplied function with the args. + void *status = thread_args->invoke (); + + delete static_cast (thread_args); + return status; +} +#endif + +// Call the appropriate OS routine to spawn a thread. Should *not* be +// called with the lock_ held... + +int +ACE_Thread_Manager::spawn_i (ACE_THR_FUNC func, + void *args, + long flags, + ACE_thread_t *t_id, + ACE_hthread_t *t_handle, + long priority, + int grp_id, + void *stack, + size_t stack_size, + ACE_Task_Base *task, + const char** thr_name) +{ + // First, threads created by Thread Manager should not be daemon threads. + // Using assertion is probably a bit too strong. However, it helps + // finding this kind of error as early as possible. Perhaps we can replace + // assertion by returning error. + ACE_ASSERT (ACE_BIT_DISABLED (flags, THR_DAEMON)); + + // Create a new thread running . *Must* be called with the + // held... + // Get a "new" Thread Descriptor from the freelist. + auto_ptr new_thr_desc (this->thread_desc_freelist_.remove ()); + + // Reset thread descriptor status + new_thr_desc->reset (this); + + ACE_Thread_Adapter *thread_args = 0; +# if defined (ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS) + ACE_NEW_RETURN (thread_args, + ACE_Thread_Adapter (func, + args, + (ACE_THR_C_FUNC) ACE_THREAD_ADAPTER_NAME, + this, + new_thr_desc.get (), + ACE_OS_Object_Manager::seh_except_selector(), + ACE_OS_Object_Manager::seh_except_handler()), + -1); +# else + ACE_NEW_RETURN (thread_args, + ACE_Thread_Adapter (func, + args, + (ACE_THR_C_FUNC) ACE_THREAD_ADAPTER_NAME, + this, + new_thr_desc.get ()), + -1); +# endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */ + auto_ptr auto_thread_args (static_cast (thread_args)); + + ACE_TRACE ("ACE_Thread_Manager::spawn_i"); + ACE_hthread_t thr_handle; + + ACE_thread_t thr_id; + if (t_id == 0) + t_id = &thr_id; + + // Acquire the lock to block the spawned thread from + // removing this Thread Descriptor before it gets put into our + // thread table. + new_thr_desc->sync_->acquire (); + + int const result = ACE_Thread::spawn (func, + args, + flags, + t_id, + &thr_handle, + priority, + stack, + stack_size, + thread_args, + thr_name); + + if (result != 0) + { + // _Don't_ clobber errno here! result is either 0 or -1, and + // ACE_OS::thr_create () already set errno! D. Levine 28 Mar 1997 + // errno = result; + ACE_Errno_Guard guard (errno); // Lock release may smash errno + new_thr_desc->sync_->release (); + return -1; + } + auto_thread_args.release (); + +#if defined (ACE_HAS_WTHREADS) + // Have to duplicate handle if client asks for it. + // @@ How are thread handles implemented on AIX? Do they + // also need to be duplicated? + if (t_handle != 0) +# if defined (ACE_LACKS_DUPLICATEHANDLE) + *t_handle = thr_handle; +# else /* ! ACE_LACKS_DUP */ + (void) ::DuplicateHandle (::GetCurrentProcess (), + thr_handle, + ::GetCurrentProcess (), + t_handle, + 0, + TRUE, + DUPLICATE_SAME_ACCESS); +# endif /* ! ACE_LACKS_DUP */ +#else /* ! ACE_HAS_WTHREADS */ + if (t_handle != 0) + *t_handle = thr_handle; +#endif /* ! ACE_HAS_WTHREADS */ + + // append_thr also put the into Thread_Manager's + // double-linked list. Only after this point, can we manipulate + // double-linked list from a spawned thread's context. + return this->append_thr (*t_id, + thr_handle, + ACE_THR_SPAWNED, + grp_id, + task, + flags, + new_thr_desc.release ()); +} + +int +ACE_Thread_Manager::spawn (ACE_THR_FUNC func, + void *args, + long flags, + ACE_thread_t *t_id, + ACE_hthread_t *t_handle, + long priority, + int grp_id, + void *stack, + size_t stack_size, + const char** thr_name) +{ + ACE_TRACE ("ACE_Thread_Manager::spawn"); + + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + + if (grp_id == -1) + grp_id = this->grp_id_++; // Increment the group id. + + if (priority != ACE_DEFAULT_THREAD_PRIORITY) + ACE_CLR_BITS (flags, THR_INHERIT_SCHED); + + if (this->spawn_i (func, + args, + flags, + t_id, + t_handle, + priority, + grp_id, + stack, + stack_size, + 0, + thr_name) == -1) + return -1; + + return grp_id; +} + +// Create N new threads running FUNC. + +int +ACE_Thread_Manager::spawn_n (size_t n, + ACE_THR_FUNC func, + void *args, + long flags, + long priority, + int grp_id, + ACE_Task_Base *task, + ACE_hthread_t thread_handles[], + void *stack[], + size_t stack_size[], + const char* thr_name[]) +{ + ACE_TRACE ("ACE_Thread_Manager::spawn_n"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + + if (grp_id == -1) + grp_id = this->grp_id_++; // Increment the group id. + + for (size_t i = 0; i < n; i++) + { + // @@ What should happen if this fails?! e.g., should we try to + // cancel the other threads that we've already spawned or what? + if (this->spawn_i (func, + args, + flags, + 0, + thread_handles == 0 ? 0 : &thread_handles[i], + priority, + grp_id, + stack == 0 ? 0 : stack[i], + stack_size == 0 ? ACE_DEFAULT_THREAD_STACKSIZE : stack_size[i], + task, + thr_name == 0 ? 0 : &thr_name [i]) == -1) + return -1; + } + + return grp_id; +} + +// Create N new threads running FUNC. + +int +ACE_Thread_Manager::spawn_n (ACE_thread_t thread_ids[], + size_t n, + ACE_THR_FUNC func, + void *args, + long flags, + long priority, + int grp_id, + void *stack[], + size_t stack_size[], + ACE_hthread_t thread_handles[], + ACE_Task_Base *task, + const char* thr_name[]) +{ + ACE_TRACE ("ACE_Thread_Manager::spawn_n"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + + if (grp_id == -1) + grp_id = this->grp_id_++; // Increment the group id. + + for (size_t i = 0; i < n; i++) + { + // @@ What should happen if this fails?! e.g., should we try to + // cancel the other threads that we've already spawned or what? + if (this->spawn_i (func, + args, + flags, + thread_ids == 0 ? 0 : &thread_ids[i], + thread_handles == 0 ? 0 : &thread_handles[i], + priority, + grp_id, + stack == 0 ? 0 : stack[i], + stack_size == 0 ? ACE_DEFAULT_THREAD_STACKSIZE : stack_size[i], + task, + thr_name == 0 ? 0 : &thr_name [i]) == -1) + return -1; + } + + return grp_id; +} + +// Append a thread into the pool (does not check for duplicates). +// Must be called with locks held. + +int +ACE_Thread_Manager::append_thr (ACE_thread_t t_id, + ACE_hthread_t t_handle, + ACE_UINT32 thr_state, + int grp_id, + ACE_Task_Base *task, + long flags, + ACE_Thread_Descriptor *td) +{ + ACE_TRACE ("ACE_Thread_Manager::append_thr"); + ACE_Thread_Descriptor *thr_desc = 0; + + if (td == 0) + { + ACE_NEW_RETURN (thr_desc, + ACE_Thread_Descriptor, + -1); + thr_desc->tm_ = this; + // Setup the Thread_Manager. + } + else + thr_desc = td; + + thr_desc->thr_id_ = t_id; + thr_desc->thr_handle_ = t_handle; + thr_desc->grp_id_ = grp_id; + thr_desc->task_ = task; + thr_desc->flags_ = flags; + + this->thr_list_.insert_head (thr_desc); + ACE_SET_BITS (thr_desc->thr_state_, thr_state); + thr_desc->sync_->release (); + + return 0; +} + +// Return the thread descriptor (indexed by ACE_hthread_t). + +ACE_Thread_Descriptor * +ACE_Thread_Manager::find_hthread (ACE_hthread_t h_id) +{ + for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); + !iter.done (); + iter.advance ()) + { + if (ACE_OS::thr_cmp (iter.next ()->thr_handle_, h_id)) + { + return iter.next (); + } + } + + return 0; +} + +// Locate the index in the table associated with . Must be +// called with the lock held. + +ACE_Thread_Descriptor * +ACE_Thread_Manager::find_thread (ACE_thread_t t_id) +{ + ACE_TRACE ("ACE_Thread_Manager::find_thread"); + + for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); + !iter.done (); + iter.advance ()) + { + if (ACE_OS::thr_equal (iter.next ()->thr_id_, t_id)) + { + return iter.next (); + } + } + return 0; +} + +// Insert a thread into the pool (checks for duplicates and doesn't +// allow them to be inserted twice). + +int +ACE_Thread_Manager::insert_thr (ACE_thread_t t_id, + ACE_hthread_t t_handle, + int grp_id, + long flags) +{ + ACE_TRACE ("ACE_Thread_Manager::insert_thr"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + + // Check for duplicates and bail out if we're already registered... + if (this->find_thread (t_id) != 0 ) + return -1; + + if (grp_id == -1) + grp_id = this->grp_id_++; + + if (this->append_thr (t_id, + t_handle, + ACE_THR_SPAWNED, + grp_id, + 0, + flags) == -1) + return -1; + + return grp_id; +} + +// Run the registered hooks when the thread exits. + +void +ACE_Thread_Manager::run_thread_exit_hooks (int i) +{ +#if 0 // currently unused! + ACE_TRACE ("ACE_Thread_Manager::run_thread_exit_hooks"); + + // @@ Currently, we have just one hook. This should clearly be + // generalized to support an arbitrary number of hooks. + + ACE_Thread_Descriptor *td = this->thread_desc_self (); + for (ACE_Cleanup_Info_Node *iter = td->cleanup_info_->pop_front (); + iter != 0; + iter = cleanup_info_->pop_front ()) + { + if (iter->cleanup_hook () != 0) + { + (*iter->cleanup_hook ()) (iter->object (), iter->param ()); + } + delete iter; + } + + ACE_UNUSED_ARG (i); +#else + ACE_UNUSED_ARG (i); +#endif /* 0 */ +} + +// Remove a thread from the pool. Must be called with locks held. + +void +ACE_Thread_Manager::remove_thr (ACE_Thread_Descriptor *td, + int close_handler) +{ + ACE_TRACE ("ACE_Thread_Manager::remove_thr"); + + td->tm_ = 0; + this->thr_list_.remove (td); + +#if defined (ACE_WIN32) + if (close_handler != 0) + ::CloseHandle (td->thr_handle_); +#else + ACE_UNUSED_ARG (close_handler); +#endif /* ACE_WIN32 */ + + this->thread_desc_freelist_.add (td); + +#if defined (ACE_HAS_THREADS) + // Tell all waiters when there are no more threads left in the pool. + if (this->thr_list_.size () == 0) + this->zero_cond_.broadcast (); +#endif /* ACE_HAS_THREADS */ +} + +// Repeatedly call remove_thr on all table entries until there +// is no thread left. Must be called with lock held. +void +ACE_Thread_Manager::remove_thr_all (void) +{ + ACE_Thread_Descriptor *td = 0; + + while ((td = this->thr_list_.delete_head ()) != 0) + { + this->remove_thr (td, 1); + } +} + +// ------------------------------------------------------------------ +// Factor out some common behavior to simplify the following methods. +#define ACE_THR_OP(OP,STATE) \ + int result = OP (td->thr_handle_); \ + if (result == -1) { \ + if (errno != ENOTSUP) \ + this->thr_to_be_removed_.enqueue_tail (td); \ + return -1; \ + } \ + else { \ + ACE_SET_BITS (td->thr_state_, STATE); \ + return 0; \ + } + +int +ACE_Thread_Manager::join_thr (ACE_Thread_Descriptor *td, int) +{ + ACE_TRACE ("ACE_Thread_Manager::join_thr"); + int const result = ACE_Thread::join (td->thr_handle_); + if (result != 0) + { + // Since the thread are being joined, we should + // let it remove itself from the list. + + // this->remove_thr (td); + errno = result; + return -1; + } + + return 0; +} + +int +ACE_Thread_Manager::suspend_thr (ACE_Thread_Descriptor *td, int) +{ + ACE_TRACE ("ACE_Thread_Manager::suspend_thr"); + + int const result = ACE_Thread::suspend (td->thr_handle_); + if (result == -1) { + if (errno != ENOTSUP) + this->thr_to_be_removed_.enqueue_tail (td); + return -1; + } + else { + ACE_SET_BITS (td->thr_state_, ACE_THR_SUSPENDED); + return 0; + } +} + +int +ACE_Thread_Manager::resume_thr (ACE_Thread_Descriptor *td, int) +{ + ACE_TRACE ("ACE_Thread_Manager::resume_thr"); + + int const result = ACE_Thread::resume (td->thr_handle_); + if (result == -1) { + if (errno != ENOTSUP) + this->thr_to_be_removed_.enqueue_tail (td); + return -1; + } + else { + ACE_CLR_BITS (td->thr_state_, ACE_THR_SUSPENDED); + return 0; + } +} + +int +ACE_Thread_Manager::cancel_thr (ACE_Thread_Descriptor *td, int async_cancel) +{ + ACE_TRACE ("ACE_Thread_Manager::cancel_thr"); + // Must set the state first and then try to cancel the thread. + ACE_SET_BITS (td->thr_state_, ACE_THR_CANCELLED); + + if (async_cancel != 0) + // Note that this call only does something relevant if the OS + // platform supports asynchronous thread cancellation. Otherwise, + // it's a no-op. + return ACE_Thread::cancel (td->thr_id_); + + return 0; +} + +int +ACE_Thread_Manager::kill_thr (ACE_Thread_Descriptor *td, int signum) +{ + ACE_TRACE ("ACE_Thread_Manager::kill_thr"); + + ACE_thread_t tid = td->thr_id_; + + int const result = ACE_Thread::kill (tid, signum); + + if (result != 0) + { + // Only remove a thread from us when there is a "real" error. + if (errno != ENOTSUP) + this->thr_to_be_removed_.enqueue_tail (td); + + return -1; + } + + return 0; +} + +// ------------------------------------------------------------------ +// Factor out some common behavior to simplify the following methods. +#define ACE_EXECUTE_OP(OP, ARG) \ + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); \ + ACE_ASSERT (this->thr_to_be_removed_.is_empty ()); \ + ACE_FIND (this->find_thread (t_id), ptr); \ + if (ptr == 0) \ + { \ + errno = ENOENT; \ + return -1; \ + } \ + int const result = OP (ptr, ARG); \ + ACE_Errno_Guard error (errno); \ + while (! this->thr_to_be_removed_.is_empty ()) { \ + ACE_Thread_Descriptor * td = 0; \ + this->thr_to_be_removed_.dequeue_head (td); \ + this->remove_thr (td, 1); \ + } \ + return result + +// Suspend a single thread. + +int +ACE_Thread_Manager::suspend (ACE_thread_t t_id) +{ + ACE_TRACE ("ACE_Thread_Manager::suspend"); + ACE_EXECUTE_OP (this->suspend_thr, 0); +} + +// Resume a single thread. + +int +ACE_Thread_Manager::resume (ACE_thread_t t_id) +{ + ACE_TRACE ("ACE_Thread_Manager::resume"); + ACE_EXECUTE_OP (this->resume_thr, 0); +} + +// Cancel a single thread. + +int +ACE_Thread_Manager::cancel (ACE_thread_t t_id, int async_cancel) +{ + ACE_TRACE ("ACE_Thread_Manager::cancel"); + ACE_EXECUTE_OP (this->cancel_thr, async_cancel); +} + +// Send a signal to a single thread. + +int +ACE_Thread_Manager::kill (ACE_thread_t t_id, int signum) +{ + ACE_TRACE ("ACE_Thread_Manager::kill"); + ACE_EXECUTE_OP (this->kill_thr, signum); +} + +int +ACE_Thread_Manager::check_state (ACE_UINT32 state, + ACE_thread_t id, + int enable) +{ + ACE_TRACE ("ACE_Thread_Manager::check_state"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + + ACE_UINT32 thr_state; + + int self_check = ACE_OS::thr_equal (id, ACE_OS::thr_self ()); + + // If we're checking the state of our thread, try to get the cached + // value out of TSS to avoid lookup. + if (self_check) + { + ACE_Thread_Descriptor *desc = ACE_LOG_MSG->thr_desc (); + if (desc == 0) + return 0; // Always return false. + thr_state = desc->thr_state_; + } + else + { + // Not calling from self, have to look it up from the list. + ACE_FIND (this->find_thread (id), ptr); + if (ptr == 0) + return 0; + thr_state = ptr->thr_state_; + } + if (enable) + return ACE_BIT_ENABLED (thr_state, state); + + return ACE_BIT_DISABLED (thr_state, state); +} + +// Test if a single thread has terminated. + +int +ACE_Thread_Manager::testterminate (ACE_thread_t t_id) +{ + ACE_TRACE ("ACE_Thread_Manager::testterminate"); + return this->check_state (ACE_THR_TERMINATED, t_id); +} + +// Test if a single thread is suspended. + +int +ACE_Thread_Manager::testsuspend (ACE_thread_t t_id) +{ + ACE_TRACE ("ACE_Thread_Manager::testsuspend"); + return this->check_state (ACE_THR_SUSPENDED, t_id); +} + +// Test if a single thread is active (i.e., resumed). + +int +ACE_Thread_Manager::testresume (ACE_thread_t t_id) +{ + ACE_TRACE ("ACE_Thread_Manager::testresume"); + return this->check_state (ACE_THR_SUSPENDED, t_id, 0); +} + +// Test if a single thread is cancelled. + +int +ACE_Thread_Manager::testcancel (ACE_thread_t t_id) +{ + ACE_TRACE ("ACE_Thread_Manager::testcancel"); + return this->check_state (ACE_THR_CANCELLED, t_id); +} + +// Thread information query functions. + +int +ACE_Thread_Manager::hthread_within (ACE_hthread_t handle) +{ + ACE_TRACE ("ACE_Thread_Manager::hthread_within"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_monx, this->lock_, -1)); + + for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); + !iter.done (); + iter.advance ()) + { + if (ACE_OS::thr_cmp(iter.next ()->thr_handle_, handle)) + { + return 1; + } + } + + return 0; +} + +int +ACE_Thread_Manager::thread_within (ACE_thread_t tid) +{ + ACE_TRACE ("ACE_Thread_Manager::thread_within"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_monx, this->lock_, -1)); + + for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); + !iter.done (); + iter.advance ()) + { + if (ACE_OS::thr_equal (iter.next ()->thr_id_, tid)) + { + return 1; + } + } + + return 0; +} + +// Get group ids for a particular thread id. + +int +ACE_Thread_Manager::get_grp (ACE_thread_t t_id, int &grp_id) +{ + ACE_TRACE ("ACE_Thread_Manager::get_grp"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + + ACE_FIND (this->find_thread (t_id), ptr); + + if (ptr) + grp_id = ptr->grp_id_; + else + return -1; + return 0; +} + +// Set group ids for a particular thread id. + +int +ACE_Thread_Manager::set_grp (ACE_thread_t t_id, int grp_id) +{ + ACE_TRACE ("ACE_Thread_Manager::set_grp"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + + ACE_FIND (this->find_thread (t_id), ptr); + if (ptr) + ptr->grp_id_ = grp_id; + else + return -1; + return 0; +} + +// Suspend a group of threads. + +int +ACE_Thread_Manager::apply_grp (int grp_id, + ACE_THR_MEMBER_FUNC func, + int arg) +{ + ACE_TRACE ("ACE_Thread_Manager::apply_grp"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_monx, this->lock_, -1)); + ACE_ASSERT (this->thr_to_be_removed_.is_empty ()); + + int result = 0; + + for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); + !iter.done (); + iter.advance ()) + { + if (iter.next ()->grp_id_ == grp_id) + { + if ((this->*func) (iter.next (), arg) == -1) + { + result = -1; + } + } + } + + // Must remove threads after we have traversed the thr_list_ to + // prevent clobber thr_list_'s integrity. + + if (! this->thr_to_be_removed_.is_empty ()) + { + // Save/restore errno. + ACE_Errno_Guard error (errno); + + for (ACE_Thread_Descriptor *td; + this->thr_to_be_removed_.dequeue_head (td) != -1; + ) + this->remove_thr (td, 1); + } + + return result; +} + +int +ACE_Thread_Manager::suspend_grp (int grp_id) +{ + ACE_TRACE ("ACE_Thread_Manager::suspend_grp"); + return this->apply_grp (grp_id, + ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::suspend_thr)); +} + +// Resume a group of threads. + +int +ACE_Thread_Manager::resume_grp (int grp_id) +{ + ACE_TRACE ("ACE_Thread_Manager::resume_grp"); + return this->apply_grp (grp_id, + ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::resume_thr)); +} + +// Kill a group of threads. + +int +ACE_Thread_Manager::kill_grp (int grp_id, int signum) +{ + ACE_TRACE ("ACE_Thread_Manager::kill_grp"); + return this->apply_grp (grp_id, + ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::kill_thr), signum); +} + +// Cancel a group of threads. + +int +ACE_Thread_Manager::cancel_grp (int grp_id, int async_cancel) +{ + ACE_TRACE ("ACE_Thread_Manager::cancel_grp"); + return this->apply_grp (grp_id, + ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::cancel_thr), + async_cancel); +} + +int +ACE_Thread_Manager::apply_all (ACE_THR_MEMBER_FUNC func, int arg) +{ + ACE_TRACE ("ACE_Thread_Manager::apply_all"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + ACE_ASSERT (this->thr_to_be_removed_.is_empty ()); + + int result = 0; + + for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); + !iter.done (); + iter.advance ()) + { + if ((this->*func)(iter.next (), arg) == -1) + { + result = -1; + } + } + + // Must remove threads after we have traversed the thr_list_ to + // prevent clobber thr_list_'s integrity. + + if (! this->thr_to_be_removed_.is_empty ()) + { + // Save/restore errno. + ACE_Errno_Guard error (errno); + + for (ACE_Thread_Descriptor *td; + this->thr_to_be_removed_.dequeue_head (td) != -1; + ) + this->remove_thr (td, 1); + } + + return result; +} + +// Resume all threads that are suspended. + +int +ACE_Thread_Manager::resume_all (void) +{ + ACE_TRACE ("ACE_Thread_Manager::resume_all"); + return this->apply_all (ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::resume_thr)); +} + +int +ACE_Thread_Manager::suspend_all (void) +{ + ACE_TRACE ("ACE_Thread_Manager::suspend_all"); + return this->apply_all (ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::suspend_thr)); +} + +int +ACE_Thread_Manager::kill_all (int sig) +{ + ACE_TRACE ("ACE_Thread_Manager::kill_all"); + return this->apply_all (&ACE_Thread_Manager::kill_thr, sig); +} + +int +ACE_Thread_Manager::cancel_all (int async_cancel) +{ + ACE_TRACE ("ACE_Thread_Manager::cancel_all"); + return this->apply_all (ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::cancel_thr), + async_cancel); +} + +int +ACE_Thread_Manager::join (ACE_thread_t tid, ACE_THR_FUNC_RETURN *status) +{ + ACE_TRACE ("ACE_Thread_Manager::join"); + + bool found = false; + ACE_Thread_Descriptor_Base tdb; + + { + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + +#if !defined (ACE_HAS_VXTHREADS) + for (ACE_Double_Linked_List_Iterator biter (this->terminated_thr_list_); + !biter.done (); + biter.advance ()) + { + if (ACE_OS::thr_equal (biter.next ()->thr_id_, tid)) + { + ACE_Thread_Descriptor_Base *tdb = biter.advance_and_remove (false); + if (ACE_Thread::join (tdb->thr_handle_, status) == -1) + { + return -1; + } + delete tdb; + + // return immediately if we've found the thread we want to join. + return 0; + } + } +#endif /* !ACE_HAS_VXTHREADS */ + + for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); + !iter.done (); + iter.advance ()) + { + // If threads are created as THR_DETACHED or THR_DAEMON, we + // can't help much. + if (ACE_OS::thr_equal (iter.next ()->thr_id_,tid) && + (ACE_BIT_DISABLED (iter.next ()->flags_, THR_DETACHED | THR_DAEMON) + || ACE_BIT_ENABLED (iter.next ()->flags_, THR_JOINABLE))) + { + tdb = *iter.next (); + ACE_SET_BITS (iter.next ()->thr_state_, ACE_THR_JOINING); + found = 1; + break; + } + } + + if (!found) + return -1; + // Didn't find the thread we want or the thread is not joinable. + } + + if (ACE_Thread::join (tdb.thr_handle_, status) == -1) + return -1; + + return 0; +} + +// Wait for group of threads + +int +ACE_Thread_Manager::wait_grp (int grp_id) +{ + ACE_TRACE ("ACE_Thread_Manager::wait_grp"); + + int copy_count = 0; + ACE_Thread_Descriptor_Base *copy_table = 0; + + // We have to make sure that while we wait for these threads to + // exit, we do not have the lock. Therefore we make a copy of all + // interesting entries and let go of the lock. + { + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + +#if !defined (ACE_HAS_VXTHREADS) + ACE_NEW_RETURN (copy_table, + ACE_Thread_Descriptor_Base [this->thr_list_.size () + + this->terminated_thr_list_.size ()], + -1); +#else + ACE_NEW_RETURN (copy_table, + ACE_Thread_Descriptor_Base [this->thr_list_.size ()], + -1); +#endif /* !ACE_HAS_VXTHREADS */ + + for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); + !iter.done (); + iter.advance ()) + { + // If threads are created as THR_DETACHED or THR_DAEMON, we + // can't help much. + if (iter.next ()->grp_id_ == grp_id && + (ACE_BIT_DISABLED (iter.next ()->flags_, THR_DETACHED | THR_DAEMON) + || ACE_BIT_ENABLED (iter.next ()->flags_, THR_JOINABLE))) + { + ACE_SET_BITS (iter.next ()->thr_state_, ACE_THR_JOINING); + copy_table[copy_count++] = *iter.next (); + } + } + +#if !defined (ACE_HAS_VXTHREADS) + for (ACE_Double_Linked_List_Iterator biter (this->terminated_thr_list_); + !biter.done (); + biter.advance ()) + { + // If threads are created as THR_DETACHED or THR_DAEMON, we + // can't help much. + if (biter.next ()->grp_id_ == grp_id) + { + ACE_Thread_Descriptor_Base *tdb = biter.advance_and_remove (false); + copy_table[copy_count++] = *tdb; + delete tdb; + } + } +#endif /* !ACE_HAS_VXTHREADS */ + } + + // Now actually join() with all the threads in this group. + int result = 0; + + for (int i = 0; + i < copy_count && result != -1; + i++) + { + if (ACE_Thread::join (copy_table[i].thr_handle_) == -1) + result = -1; + } + + delete [] copy_table; + + return result; +} + +// Must be called when thread goes out of scope to clean up its table +// slot. + +ACE_THR_FUNC_RETURN +ACE_Thread_Manager::exit (ACE_THR_FUNC_RETURN status, bool do_thread_exit) +{ + ACE_TRACE ("ACE_Thread_Manager::exit"); +#if defined (ACE_WIN32) + // Remove detached thread handle. + + if (do_thread_exit) + { +#if 0 + // @@ This callback is now taken care of by TSS_Cleanup. Do we + // need it anymore? + + // On Win32, if we really wants to exit from a thread, we must + // first clean up the thread specific storage. By doing so, + // ACE_Thread_Manager::exit will be called again with + // do_thr_exit = 0 and cleaning up the ACE_Cleanup_Info (but not + // exiting the thread.) After the following call returns, we + // are safe to exit this thread. + delete ACE_Thread_Exit::instance (); +#endif /* 0 */ + ACE_Thread::exit (status); + } +#endif /* ACE_WIN32 */ + + // Just hold onto the guard while finding this thread's id and + { + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0)); + + // Find the thread id, but don't use the cache. It might have been + // deleted already. + ACE_thread_t const id = ACE_OS::thr_self (); + ACE_Thread_Descriptor* td = this->find_thread (id); + if (td != 0) + { + // @@ We call Thread_Descriptor terminate this realize the cleanup + // process itself. + td->terminate(); + } + } + + if (do_thread_exit) + { + ACE_Thread::exit (status); + // On reasonable systems should not return. + // However, due to horrible semantics with Win32 thread-specific + // storage this call can return (don't ask...). + } + + return 0; +} + +// Wait for all the threads to exit. + +int +ACE_Thread_Manager::wait (const ACE_Time_Value *timeout, + bool abandon_detached_threads, + bool use_absolute_time) +{ + ACE_TRACE ("ACE_Thread_Manager::wait"); + + ACE_Time_Value local_timeout; + // Check to see if we're using absolute time or not. + if (use_absolute_time == false && timeout != 0) + { + local_timeout = *timeout; + local_timeout += ACE_OS::gettimeofday (); + timeout = &local_timeout; + } + +#if !defined (ACE_HAS_VXTHREADS) + ACE_Double_Linked_List term_thr_list_copy; +#endif /* ACE_HAS_VXTHREADS */ + +#if defined (ACE_HAS_THREADS) + { + // Just hold onto the guard while waiting. + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + + if (ACE_Object_Manager::shutting_down () != 1) + { + // Program is not shutting down. Perform a normal wait on threads. + if (abandon_detached_threads != 0) + { + ACE_ASSERT (this->thr_to_be_removed_.is_empty ()); + for (ACE_Double_Linked_List_Iterator + iter (this->thr_list_); + !iter.done (); + iter.advance ()) + { + if (ACE_BIT_ENABLED (iter.next ()->flags_, + THR_DETACHED | THR_DAEMON) + && ACE_BIT_DISABLED (iter.next ()->flags_, THR_JOINABLE)) + { + this->thr_to_be_removed_.enqueue_tail (iter.next ()); + ACE_SET_BITS (iter.next ()->thr_state_, ACE_THR_JOINING); + } + } + + if (! this->thr_to_be_removed_.is_empty ()) + { + ACE_Thread_Descriptor *td = 0; + while (this->thr_to_be_removed_.dequeue_head (td) != -1) + this->remove_thr (td, 1); + } + } + + while (this->thr_list_.size () > 0) + if (this->zero_cond_.wait (timeout) == -1) + return -1; + } + else + // Program is shutting down, no chance to wait on threads. + // Therefore, we'll just remove threads from the list. + this->remove_thr_all (); + +#if !defined (ACE_HAS_VXTHREADS) + ACE_Thread_Descriptor_Base* item = 0; + while ((item = this->terminated_thr_list_.delete_head ()) != 0) + { + term_thr_list_copy.insert_tail (item); + } +#endif /* ACE_HAS_VXTHREADS */ + // Release the guard, giving other threads a chance to run. + } + +#if !defined (ACE_HAS_VXTHREADS) + // @@ VxWorks doesn't support thr_join (yet.) We are working + // on our implementation. Chorus'es thr_join seems broken. + ACE_Thread_Descriptor_Base *item = 0; + + while ((item = term_thr_list_copy.delete_head ()) != 0) + { + if (ACE_BIT_DISABLED (item->flags_, THR_DETACHED | THR_DAEMON) + || ACE_BIT_ENABLED (item->flags_, THR_JOINABLE)) + // Detached handles shouldn't reached here. + (void) ACE_Thread::join (item->thr_handle_); + + delete item; + } + +#endif /* !ACE_HAS_VXTHREADS */ +#else + ACE_UNUSED_ARG (timeout); + ACE_UNUSED_ARG (abandon_detached_threads); +#endif /* ACE_HAS_THREADS */ + + return 0; +} + +int +ACE_Thread_Manager::apply_task (ACE_Task_Base *task, + ACE_THR_MEMBER_FUNC func, + int arg) +{ + ACE_TRACE ("ACE_Thread_Manager::apply_task"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + ACE_ASSERT (this->thr_to_be_removed_.is_empty ()); + + int result = 0; + + for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); + !iter.done (); + iter.advance ()) + if (iter.next ()->task_ == task + && (this->*func) (iter.next (), arg) == -1) + result = -1; + + // Must remove threads after we have traversed the thr_list_ to + // prevent clobber thr_list_'s integrity. + + if (! this->thr_to_be_removed_.is_empty ()) + { + // Save/restore errno. + ACE_Errno_Guard error (errno); + + for (ACE_Thread_Descriptor *td = 0; + this->thr_to_be_removed_.dequeue_head (td) != -1; + ) + this->remove_thr (td, 1); + } + + return result; +} + +// Wait for all threads to exit a task. + +int +ACE_Thread_Manager::wait_task (ACE_Task_Base *task) +{ + int copy_count = 0; + ACE_Thread_Descriptor_Base *copy_table = 0; + + // We have to make sure that while we wait for these threads to + // exit, we do not have the lock. Therefore we make a copy of all + // interesting entries and let go of the lock. + { + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + +#if !defined (ACE_HAS_VXTHREADS) + ACE_NEW_RETURN (copy_table, + ACE_Thread_Descriptor_Base [this->thr_list_.size () + + this->terminated_thr_list_.size ()], + -1); +#else + ACE_NEW_RETURN (copy_table, + ACE_Thread_Descriptor_Base [this->thr_list_.size ()], + -1); +#endif /* !ACE_HAS_VXTHREADS */ + + for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); + !iter.done (); + iter.advance ()) + { + // If threads are created as THR_DETACHED or THR_DAEMON, we + // can't wait on them here. + if (iter.next ()->task_ == task && + (ACE_BIT_DISABLED (iter.next ()->flags_, + THR_DETACHED | THR_DAEMON) + || ACE_BIT_ENABLED (iter.next ()->flags_, + THR_JOINABLE))) + { + ACE_SET_BITS (iter.next ()->thr_state_, + ACE_THR_JOINING); + copy_table[copy_count++] = *iter.next (); + } + } + +#if !defined (ACE_HAS_VXTHREADS) + for (ACE_Double_Linked_List_Iterator titer (this->terminated_thr_list_); + !titer.done (); + titer.advance ()) + { + // If threads are created as THR_DETACHED or THR_DAEMON, we can't help much here. + if (titer.next ()->task_ == task) + { + ACE_Thread_Descriptor_Base *tdb = titer.advance_and_remove (false); + copy_table[copy_count++] = *tdb; + delete tdb; + } + } +#endif /* !ACE_HAS_VXTHREADS */ + } + + // Now to do the actual work + int result = 0; + + for (int i = 0; + i < copy_count && result != -1; + i++) + { + if (ACE_Thread::join (copy_table[i].thr_handle_) == -1) + result = -1; + } + + delete [] copy_table; + + return result; +} + +// Suspend a task + +int +ACE_Thread_Manager::suspend_task (ACE_Task_Base *task) +{ + ACE_TRACE ("ACE_Thread_Manager::suspend_task"); + return this->apply_task (task, + ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::suspend_thr)); +} + +// Resume a task. +int +ACE_Thread_Manager::resume_task (ACE_Task_Base *task) +{ + ACE_TRACE ("ACE_Thread_Manager::resume_task"); + return this->apply_task (task, + ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::resume_thr)); +} + +// Kill a task. + +int +ACE_Thread_Manager::kill_task (ACE_Task_Base *task, int /* signum */) +{ + ACE_TRACE ("ACE_Thread_Manager::kill_task"); + return this->apply_task (task, + ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::kill_thr)); +} + +// Cancel a task. +int +ACE_Thread_Manager::cancel_task (ACE_Task_Base *task, + int async_cancel) +{ + ACE_TRACE ("ACE_Thread_Manager::cancel_task"); + return this->apply_task (task, + ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::cancel_thr), + async_cancel); +} + +// Locate the index in the table associated with from the +// beginning of the table up to an index. Must be called with the +// lock held. + +ACE_Thread_Descriptor * +ACE_Thread_Manager::find_task (ACE_Task_Base *task, size_t slot) +{ + ACE_TRACE ("ACE_Thread_Manager::find_task"); + + size_t i = 0; + + for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); + !iter.done (); + iter.advance ()) + { + if (i >= slot) + break; + + if (task == iter.next ()->task_) + return iter.next (); + + ++i; + } + + return 0; +} + +// Returns the number of ACE_Task in a group. + +int +ACE_Thread_Manager::num_tasks_in_group (int grp_id) +{ + ACE_TRACE ("ACE_Thread_Manager::num_tasks_in_group"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + + int tasks_count = 0; + size_t i = 0; + + for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); + !iter.done (); + iter.advance ()) + { + if (iter.next ()->grp_id_ == grp_id + && this->find_task (iter.next ()->task_, i) == 0 + && iter.next ()->task_ != 0) + { + ++tasks_count; + } + + ++i; + } + return tasks_count; +} + +// Returns the number of threads in an ACE_Task. + +int +ACE_Thread_Manager::num_threads_in_task (ACE_Task_Base *task) +{ + ACE_TRACE ("ACE_Thread_Manager::num_threads_in_task"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + + int threads_count = 0; + + for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); + !iter.done (); + iter.advance ()) + { + if (iter.next ()->task_ == task) + { + ++threads_count; + } + } + + return threads_count; +} + +// Returns in task_list a list of ACE_Tasks registered with ACE_Thread_Manager. + +ssize_t +ACE_Thread_Manager::task_all_list (ACE_Task_Base *task_list[], + size_t n) +{ + ACE_TRACE ("ACE_Thread_Manager::task_all_list"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + + size_t task_list_count = 0; + + for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); + !iter.done (); + iter.advance ()) + { + if (task_list_count >= n) + { + break; + } + + ACE_Task_Base *task_p = iter.next ()->task_; + + if (0 != task_p) + { + // This thread has a task pointer; see if it's already in the + // list. Don't add duplicates. + size_t i = 0; + + for (; i < task_list_count; ++i) + { + if (task_list[i] == task_p) + { + break; + } + } + + if (i == task_list_count) // No match - add this one + { + task_list[task_list_count++] = task_p; + } + } + } + + return ACE_Utils::truncate_cast (task_list_count); +} + +// Returns in thread_list a list of all thread ids + +ssize_t +ACE_Thread_Manager::thread_all_list (ACE_thread_t thread_list[], + size_t n) +{ + ACE_TRACE ("ACE_Thread_Manager::thread_all_list"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + + size_t thread_count = 0; + + for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); + !iter.done (); + iter.advance ()) + { + if (thread_count >= n) + { + break; + } + + thread_list[thread_count] = iter.next ()->thr_id_; + ++thread_count; + } + + return ACE_Utils::truncate_cast (thread_count); +} + + +int +ACE_Thread_Manager::thr_state (ACE_thread_t id, + ACE_UINT32& state) +{ + ACE_TRACE ("ACE_Thread_Manager::thr_state"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + + int const self_check = ACE_OS::thr_equal (id, ACE_OS::thr_self ()); + + // If we're checking the state of our thread, try to get the cached + // value out of TSS to avoid lookup. + if (self_check) + { + ACE_Thread_Descriptor *desc = ACE_LOG_MSG->thr_desc (); + + if (desc == 0) + { + return 0; // Always return false. + } + + state = desc->thr_state_; + } + else + { + // Not calling from self, have to look it up from the list. + ACE_FIND (this->find_thread (id), ptr); + + if (ptr == 0) + { + return 0; + } + + state = ptr->thr_state_; + } + + return 1; +} + +// Returns in task_list a list of ACE_Tasks in a group. + +ssize_t +ACE_Thread_Manager::task_list (int grp_id, + ACE_Task_Base *task_list[], + size_t n) +{ + ACE_TRACE ("ACE_Thread_Manager::task_list"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + + ACE_Task_Base **task_list_iterator = task_list; + size_t task_list_count = 0; + size_t i = 0; + + for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); + !iter.done (); + iter.advance ()) + { + if (task_list_count >= n) + { + break; + } + + if (iter.next ()->grp_id_ == grp_id + && this->find_task (iter.next ()->task_, i) == 0) + { + task_list_iterator[task_list_count] = iter.next ()->task_; + ++task_list_count; + } + + ++i; + } + + return ACE_Utils::truncate_cast (task_list_count); +} + +// Returns in thread_list a list of thread ids in an ACE_Task. + +ssize_t +ACE_Thread_Manager::thread_list (ACE_Task_Base *task, + ACE_thread_t thread_list[], + size_t n) +{ + ACE_TRACE ("ACE_Thread_Manager::thread_list"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + + size_t thread_count = 0; + + for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); + !iter.done (); + iter.advance ()) + { + if (thread_count >= n) + { + break; + } + + if (iter.next ()->task_ == task) + { + thread_list[thread_count] = iter.next ()->thr_id_; + ++thread_count; + } + } + + return ACE_Utils::truncate_cast (thread_count); +} + +// Returns in thread_list a list of thread handles in an ACE_Task. + +ssize_t +ACE_Thread_Manager::hthread_list (ACE_Task_Base *task, + ACE_hthread_t hthread_list[], + size_t n) +{ + ACE_TRACE ("ACE_Thread_Manager::hthread_list"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + + size_t hthread_count = 0; + + for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); + !iter.done (); + iter.advance ()) + { + if (hthread_count >= n) + { + break; + } + + if (iter.next ()->task_ == task) + { + hthread_list[hthread_count] = iter.next ()->thr_handle_; + ++hthread_count; + } + } + + return ACE_Utils::truncate_cast (hthread_count); +} + +ssize_t +ACE_Thread_Manager::thread_grp_list (int grp_id, + ACE_thread_t thread_list[], + size_t n) +{ + ACE_TRACE ("ACE_Thread_Manager::thread_grp_list"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + + size_t thread_count = 0; + + for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); + !iter.done (); + iter.advance ()) + { + if (thread_count >= n) + { + break; + } + + if (iter.next ()->grp_id_ == grp_id) + { + thread_list[thread_count] = iter.next ()->thr_id_; + thread_count++; + } + } + + return ACE_Utils::truncate_cast (thread_count); +} + +// Returns in thread_list a list of thread handles in an ACE_Task. + +ssize_t +ACE_Thread_Manager::hthread_grp_list (int grp_id, + ACE_hthread_t hthread_list[], + size_t n) +{ + ACE_TRACE ("ACE_Thread_Manager::hthread_grp_list"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + + size_t hthread_count = 0; + + for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); + !iter.done (); + iter.advance ()) + { + if (hthread_count >= n) + { + break; + } + + if (iter.next ()->grp_id_ == grp_id) + { + hthread_list[hthread_count] = iter.next ()->thr_handle_; + hthread_count++; + } + } + + return ACE_Utils::truncate_cast (hthread_count); +} + +int +ACE_Thread_Manager::set_grp (ACE_Task_Base *task, int grp_id) +{ + ACE_TRACE ("ACE_Thread_Manager::set_grp"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + + for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); + !iter.done (); + iter.advance ()) + { + if (iter.next ()->task_ == task) + { + iter.next ()->grp_id_ = grp_id; + } + } + + return 0; +} + +int +ACE_Thread_Manager::get_grp (ACE_Task_Base *task, int &grp_id) +{ + ACE_TRACE ("ACE_Thread_Manager::get_grp"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + + ACE_FIND (this->find_task (task), ptr); + grp_id = ptr->grp_id_; + return 0; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Thread_Manager.h b/dep/acelite/ace/Thread_Manager.h new file mode 100644 index 00000000000..650287277d7 --- /dev/null +++ b/dep/acelite/ace/Thread_Manager.h @@ -0,0 +1,1267 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Thread_Manager.h + * + * $Id: Thread_Manager.h 83956 2008-12-03 07:57:38Z johnnyw $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_THREAD_MANAGER_H +#define ACE_THREAD_MANAGER_H +#include /**/ "ace/pre.h" + +#include "ace/Thread.h" +#include "ace/Thread_Adapter.h" +#include "ace/Thread_Exit.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Condition_Thread_Mutex.h" +#include "ace/Unbounded_Queue.h" +#include "ace/Containers.h" +#include "ace/Free_List.h" +#include "ace/Singleton.h" +#include "ace/Log_Msg.h" +#include "ace/Synch_Traits.h" +#include "ace/Basic_Types.h" + +// The following macros control how a Thread Manager manages a pool of +// Thread_Descriptor. Currently, the default behavior is not to +// preallocate any thread descriptor and never (well, almost never) +// free up any thread descriptor until the Thread Manager gets +// destructed. Which means, once your system is stable, you rarely +// need to pay the price of memory allocation. On a deterministic +// system, which means, the number of threads spawned can be +// determined before hand, you can either redefine the memory pool +// size macros to suit your need or constructed the Thread_Manager +// accordingly. That way, you don't pay the price of memory +// allocation when the system is really doing its job. OTOH, on +// system with resources constraint, you may want to lower the size of +// ACE_DEFAULT_THREAD_MANAGER_HWM to avoid unused memory hanging +// around. + +#if !defined (ACE_DEFAULT_THREAD_MANAGER_PREALLOC) +# define ACE_DEFAULT_THREAD_MANAGER_PREALLOC 0 +#endif /* ACE_DEFAULT_THREAD_MANAGER_PREALLOC */ + +#if !defined (ACE_DEFAULT_THREAD_MANAGER_LWM) +# define ACE_DEFAULT_THREAD_MANAGER_LWM 1 +#endif /* ACE_DEFAULT_THREAD_MANAGER_LWM */ + +#if !defined (ACE_DEFAULT_THREAD_MANAGER_INC) +# define ACE_DEFAULT_THREAD_MANAGER_INC 1 +#endif /* ACE_DEFAULT_THREAD_MANAGER_INC */ + +#if !defined (ACE_DEFAULT_THREAD_MANAGER_HWM) +# define ACE_DEFAULT_THREAD_MANAGER_HWM ACE_DEFAULT_FREE_LIST_HWM +// this is a big number +#endif /* ACE_DEFAULT_THREAD_MANAGER_HWM */ + +// This is the synchronization mechanism used to prevent a thread +// descriptor gets removed from the Thread_Manager before it gets +// stash into it. If you want to disable this feature (and risk of +// corrupting the freelist,) you define the lock as ACE_Null_Mutex. +// Usually, if you can be sure that your threads will run for an +// extended period of time, you can safely disable the lock. + +#if !defined (ACE_DEFAULT_THREAD_MANAGER_LOCK) +# define ACE_DEFAULT_THREAD_MANAGER_LOCK ACE_SYNCH_MUTEX +#endif /* ACE_DEFAULT_THREAD_MANAGER_LOCK */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Forward declarations. +class ACE_Task_Base; +class ACE_Thread_Manager; +class ACE_Thread_Descriptor; + +/** + * @class ACE_At_Thread_Exit + * + * @brief Contains a method to be applied when a thread is terminated. + */ +class ACE_Export ACE_At_Thread_Exit +{ + friend class ACE_Thread_Descriptor; + friend class ACE_Thread_Manager; +public: + /// Default constructor + ACE_At_Thread_Exit (void); + + /// The destructor + virtual ~ACE_At_Thread_Exit (void); + + /// At_Thread_Exit has the ownership? + bool is_owner (void) const; + + /// Set the ownership of the At_Thread_Exit. + bool is_owner (bool owner); + + /// This At_Thread_Exit was applied? + bool was_applied (void) const; + + /// Set applied state of At_Thread_Exit. + bool was_applied (bool applied); + +protected: + /// The next At_Thread_Exit hook in the list. + ACE_At_Thread_Exit *next_; + + /// Do the apply if necessary + void do_apply (void); + + /// The apply method. + virtual void apply (void) = 0; + + /// The Thread_Descriptor where this at is registered. + ACE_Thread_Descriptor* td_; + + /// The at was applied? + bool was_applied_; + + /// The at has the ownership of this? + bool is_owner_; +}; + +class ACE_Export ACE_At_Thread_Exit_Func : public ACE_At_Thread_Exit +{ +public: + /// Constructor + ACE_At_Thread_Exit_Func (void *object, + ACE_CLEANUP_FUNC func, + void *param = 0); + + virtual ~ACE_At_Thread_Exit_Func (void); + +protected: + /// The object to be cleanup + void *object_; + + /// The cleanup func + ACE_CLEANUP_FUNC func_; + + /// A param if required + void *param_; + + /// The apply method + void apply (void); +}; + +/** + * @class ACE_Thread_Descriptor_Base + * + * @brief Basic information for thread descriptors. These information + * gets extracted out because we need it after a thread is + * terminated. + * + * @internal + */ +class ACE_Export ACE_Thread_Descriptor_Base : public ACE_OS_Thread_Descriptor +{ + + friend class ACE_Thread_Manager; + friend class ACE_Double_Linked_List; + friend class ACE_Double_Linked_List_Iterator_Base; + friend class ACE_Double_Linked_List_Iterator; + friend class ACE_Double_Linked_List; + friend class ACE_Double_Linked_List_Iterator_Base; + friend class ACE_Double_Linked_List_Iterator; +public: + ACE_Thread_Descriptor_Base (void); + ~ACE_Thread_Descriptor_Base (void); + + // = We need the following operators to make Borland happy. + + /// Equality operator. + bool operator== (const ACE_Thread_Descriptor_Base &rhs) const; + + /// Inequality operator. + bool operator!= (const ACE_Thread_Descriptor_Base &rhs) const; + + /// Group ID. + int grp_id (void) const; + + /// Current state of the thread. + ACE_UINT32 state (void) const; + + /// Return the pointer to an ACE_Task_Base or NULL if there's no + /// ACE_Task_Base associated with this thread.; + ACE_Task_Base *task (void) const; + +protected: + /// Reset this base thread descriptor. + void reset (void); + + /// Unique thread ID. + ACE_thread_t thr_id_; + + /// Unique handle to thread (used by Win32 and AIX). + ACE_hthread_t thr_handle_; + + /// Group ID. + int grp_id_; + + /// Current state of the thread. + ACE_UINT32 thr_state_; + + /// Pointer to an ACE_Task_Base or NULL if there's no + /// ACE_Task_Base. + ACE_Task_Base *task_; + + /// We need these pointers to maintain the double-linked list in a + /// thread managers. + ACE_Thread_Descriptor_Base *next_; + ACE_Thread_Descriptor_Base *prev_; +}; + +/** + * @class ACE_Thread_Descriptor + * + * @brief Information for controlling threads that run under the control + * of the . + */ +class ACE_Export ACE_Thread_Descriptor : public ACE_Thread_Descriptor_Base +{ + friend class ACE_At_Thread_Exit; + friend class ACE_Thread_Manager; + friend class ACE_Double_Linked_List; + friend class ACE_Double_Linked_List_Iterator; +public: + // = Initialization method. + ACE_Thread_Descriptor (void); + + // = Accessor methods. + /// Unique thread id. + ACE_thread_t self (void) const; + + /// Unique handle to thread (used by Win32 and AIX). + void self (ACE_hthread_t &); + + /// Dump the state of an object. + void dump (void) const; + + /** + * This cleanup function must be called only for ACE_TSS_cleanup. + * The ACE_TSS_cleanup delegate Log_Msg instance destruction when + * Log_Msg cleanup is called before terminate. + */ + void log_msg_cleanup(ACE_Log_Msg* log_msg); + + /** + * Register an At_Thread_Exit hook and the ownership is acquire by + * Thread_Descriptor, this is the usual case when the AT is dynamically + * allocated. + */ + int at_exit (ACE_At_Thread_Exit* cleanup); + + /// Register an At_Thread_Exit hook and the ownership is retained for the + /// caller. Normally used when the at_exit hook is created in stack. + int at_exit (ACE_At_Thread_Exit& cleanup); + + /** + * Register an object (or array) for cleanup at thread termination. + * "cleanup_hook" points to a (global, or static member) function + * that is called for the object or array when it to be destroyed. + * It may perform any necessary cleanup specific for that object or + * its class. "param" is passed as the second parameter to the + * "cleanup_hook" function; the first parameter is the object (or + * array) to be destroyed. Returns 0 on success, non-zero on + * failure: -1 if virtual memory is exhausted or 1 if the object (or + * arrayt) had already been registered. + */ + int at_exit (void *object, + ACE_CLEANUP_FUNC cleanup_hook, + void *param); + + /// Do nothing destructor to keep some compilers happy + ~ACE_Thread_Descriptor (void); + + /** + * Do nothing but to acquire the thread descriptor's lock and + * release. This will first check if the thread is registered or + * not. If it is already registered, there's no need to reacquire + * the lock again. This is used mainly to get newly spawned thread + * in synch with thread manager and prevent it from accessing its + * thread descriptor before it gets fully built. This function is + * only called from ACE_Log_Msg::thr_desc. + */ + void acquire_release (void); + void acquire (void); + void release (void); + + /** + * Set/get the @c next_ pointer. These are required by the + * ACE_Free_List. + */ + void set_next (ACE_Thread_Descriptor *td); + ACE_Thread_Descriptor *get_next (void) const; + +private: + /// Reset this thread descriptor. + void reset (ACE_Thread_Manager *tm); + + /// Pop an At_Thread_Exit from at thread termination list, apply the at + /// if apply is true. + void at_pop (int apply = 1); + + /// Push an At_Thread_Exit to at thread termination list and set the + /// ownership of at. + void at_push (ACE_At_Thread_Exit* cleanup, + bool is_owner = false); + + /// Run the AT_Thread_Exit hooks. + void do_at_exit (void); + + /// Terminate realize the cleanup process to thread termination + void terminate (void); + + /// Thread_Descriptor is the ownership of ACE_Log_Msg if log_msg_!=0 + /// This can occur because ACE_TSS_cleanup was executed before terminate. + ACE_Log_Msg *log_msg_; + + /// The AT_Thread_Exit list + ACE_At_Thread_Exit *at_exit_list_; + +#if 0 +/// Currently not used + /** + * Stores the cleanup info for a thread. + * @note This should be generalized to be a stack of ACE_Cleanup_Info's. + */ + ACE_Cleanup_Info_Node_List cleanup_info_; +#endif + + /// Pointer to an ACE_Thread_Manager or NULL if there's no + /// ACE_Thread_Manager> + ACE_Thread_Manager* tm_; + + /// Registration lock to prevent premature removal of thread descriptor. + ACE_DEFAULT_THREAD_MANAGER_LOCK *sync_; + + /// Keep track of termination status. + bool terminated_; +}; + +// Forward declaration. +class ACE_Thread_Control; + +// This typedef should be (and used to be) inside the +// ACE_Thread_Manager declaration. But, it caused compilation +// problems on g++/VxWorks/i960 with -g. Note that +// ACE_Thread_Manager::THR_FUNC is only used internally in +// ACE_Thread_Manager, so it's not useful for anyone else. +// It also caused problems on IRIX5 with g++. +#if defined (__GNUG__) +typedef int (ACE_Thread_Manager::*ACE_THR_MEMBER_FUNC)(ACE_Thread_Descriptor *, int); +#endif /* __GNUG__ */ + +/** + * @class ACE_Thread_Manager + * + * @brief Manages a pool of threads. + * + * This class allows operations on groups of threads atomically. + * The default behavior of thread manager is to wait on + * all threads under it's management when it gets destructed. + * Therefore, remember to remove a thread from thread manager if + * you don't want it to wait for the thread. There are also + * functions to disable this default wait-on-exit behavior. + * However, if your program depends on turning this off to run + * correctly, you are probably doing something wrong. Rule of + * thumb, use ACE_Thread to manage your daemon threads. + * Notice that if there're threads which live beyond the scope of + * main(), you are sure to have resource leaks in your program. + * Remember to wait on threads before exiting your main program if that + * could happen in your programs. + */ +class ACE_Export ACE_Thread_Manager +{ +public: + friend class ACE_Thread_Control; + + // Allow ACE_THread_Exit to register the global TSS instance object. + friend class ACE_Thread_Exit; + friend class ACE_Thread_Descriptor; + +#if !defined (__GNUG__) + typedef int (ACE_Thread_Manager::*ACE_THR_MEMBER_FUNC)(ACE_Thread_Descriptor *, int); +#endif /* !__GNUG__ */ + + /// These are the various states a thread managed by the + /// ACE_Thread_Manager can be in. + enum + { + /// Uninitialized. + ACE_THR_IDLE = 0x00000000, + + /// Created but not yet running. + ACE_THR_SPAWNED = 0x00000001, + + /// Thread is active (naturally, we don't know if it's actually + /// *running* because we aren't the scheduler...). + ACE_THR_RUNNING = 0x00000002, + + /// Thread is suspended. + ACE_THR_SUSPENDED = 0x00000004, + + /// Thread has been cancelled (which is an indiction that it needs to + /// terminate...). + ACE_THR_CANCELLED = 0x00000008, + + /// Thread has shutdown, but the slot in the thread manager hasn't + /// been reclaimed yet. + ACE_THR_TERMINATED = 0x00000010, + + /// Join operation has been invoked on the thread by thread manager. + ACE_THR_JOINING = 0x10000000 + }; + + /** + * @brief Initialization and termination methods. + * + * Internally, ACE_Thread_Manager keeps a freelist for caching + * resources it uses to keep track of managed threads (not the + * threads themselves.) @a prealloc, @a lwm, @a inc, @hwm + * determine the initial size, the low water mark, increment step, + * and high water mark of the freelist. + * + * @sa ACE_Free_List + */ + ACE_Thread_Manager (size_t preaolloc = ACE_DEFAULT_THREAD_MANAGER_PREALLOC, + size_t lwm = ACE_DEFAULT_THREAD_MANAGER_LWM, + size_t inc = ACE_DEFAULT_THREAD_MANAGER_INC, + size_t hwm = ACE_DEFAULT_THREAD_MANAGER_HWM); + ~ACE_Thread_Manager (void); + +#if ! defined (ACE_THREAD_MANAGER_LACKS_STATICS) + /// Get pointer to a process-wide ACE_Thread_Manager. + static ACE_Thread_Manager *instance (void); + + /// Set pointer to a process-wide ACE_Thread_Manager and return + /// existing pointer. + static ACE_Thread_Manager *instance (ACE_Thread_Manager *); + + /// Delete the dynamically allocated Singleton + static void close_singleton (void); +#endif /* ! defined (ACE_THREAD_MANAGER_LACKS_STATICS) */ + + /// No-op. Currently unused. + int open (size_t size = 0); + + /** + * Release all resources. + * By default, this method will wait until all threads exit. + * However, when called from close_singleton(), most global resources + * are destroyed and thus, close() does not try to wait; it simply cleans + * up internal thread records (the thread descriptor list). + */ + int close (void); + + /** + * Create a new thread, which executes @a func with argument @a arg. + * + * @param func The function that is called in the spawned thread. + * + * @param arg The value passed to each spawned thread's @a func. + * + * @param flags Flags to control attributes of the spawned threads. + * @sa ACE_OS::thr_create() for descriptions of the + * possible flags values and their interactions. + * + * @param t_id Pointer to a location to receive the spawned thread's + * ID. If 0, the ID is not returned. + * + * @param t_handle Pointer to a location to receive the spawned thread's + * thread handle. If 0, the handle is not returned. + * + * @param priority The priority at which the thread is spawned. + * + * @param grp_id The thread group that the spawned thread is + * added to. If -1 is specified, a new thread group is + * created for the spawned thread. + * + * @param stack Pointers to the base of a pre-allocated stack space + * for the thread's stack. If 0, the platform allocates + * stack space for the thread. If a stack is specified, + * it is recommended that @a stack_size also be supplied + * to specify the size of the stack. + * Not all platforms support pre-allocated stacks. If + * @a stack is specified for a platform which does not + * allow pre-allocated stack space this parameter is + * ignored. + * + * @param stack_size Indicate how large the thread's stack should be, in + * bytes. If a pre-allocated stack pointer is passed in + * @a stack, @a stack_size indicates the size of that + * stack area. If no pre-allocated stack is passed, + * the stack size specified is passed to the + * operating system to request that it allocate a stack + * of the specified size. + * + * @param thr_name Pointer to a name to assign to the spawned thread. + * This is only meaningful for platforms that have a + * capacity to name threads (e.g., VxWorks and some + * varieties of Pthreads). This argument is ignored if + * specified as 0 and on platforms that do not have the + * capability to name threads. + * + * @retval -1 on failure; @c errno contains an error value. + * @retval The group id of the spawned thread. + */ + int spawn (ACE_THR_FUNC func, + void *arg = 0, + long flags = THR_NEW_LWP | THR_JOINABLE | THR_INHERIT_SCHED, + ACE_thread_t *t_id = 0, + ACE_hthread_t *t_handle = 0, + long priority = ACE_DEFAULT_THREAD_PRIORITY, + int grp_id = -1, + void *stack = 0, + size_t stack_size = ACE_DEFAULT_THREAD_STACKSIZE, + const char** thr_name = 0); + + /** + * Spawn a specified number of threads, all of which execute @a func + * with argument @a arg. + * + * @param n The number of threads to spawn. + * + * @param func The function that is called in the spawned thread. + * + * @param arg The value passed to each spawned thread's @a func. + * + * @param flags Flags to control attributes of the spawned threads. + * @sa ACE_OS::thr_create() for descriptions of the + * possible flags values and their interactions. + * + * @param priority The priority at which the threads are spawned. + * + * @param grp_id The thread group that the spawned threads are + * added to. If -1 is specified, a new thread group is + * created for the spawned threads. + * + * @param task The ACE_Task that the spawned threads are associated + * with. If 0, the threads are not associated with an + * ACE_Task. This argument is usually assigned by the + * ACE_Task_Base::activate() method to associate the + * spawned threads with the spawning ACE_Task object. + * + * @param thread_handles An array of @a n entries which will receive + * the thread handles of the spawned threads. + * + * @param stack An array of @a n pointers to pre-allocated stack space + * for each thread's stack. If specified as 0, the + * platform allocates stack space for each thread. If + * a stack is specified, it is recommended that a + * @a stack_size element also be supplied that specifies + * the size of the stack. + * Not all platforms support pre-allocated stacks. If + * @a stack is specified for a platform which does not + * allow pre-allocated stack space this parameter is + * ignored. + * + * @param stack_size An array of @a n values which indicate how large + * each thread's stack should be, in bytes. + * If pre-allocated stacks are passed in @a stacks, these + * sizes are for those stacks. If no pre-allocated stacks + * are passed, the stack sizes are specified to the + * operating system to request that it allocate stacks + * of the specified sizes. If an array entry is 0, the + * platform defaults are used for the corresponding thread. + * If a 0 array pointer is specified, platform defaults + * are used for all thread stack sizes. + * + * @param thr_name An array of names to assign to the spawned threads. + * This is only meaningful for platforms that have a + * capacity to name threads (e.g., VxWorks and some + * varieties of Pthreads). This argument is ignored if + * specified as 0 and on platforms that do not have the + * capability to name threads. + * + * ACE_Thread_Manager can manipulate threads in groups based on + * @a grp_id or @a task using functions such as kill_grp() or + * cancel_task(). + * + * @retval -1 on failure; @c errno contains an error value. + * @retval The group id of the threads. + */ + int spawn_n (size_t n, + ACE_THR_FUNC func, + void *arg = 0, + long flags = THR_NEW_LWP | THR_JOINABLE | THR_INHERIT_SCHED, + long priority = ACE_DEFAULT_THREAD_PRIORITY, + int grp_id = -1, + ACE_Task_Base *task = 0, + ACE_hthread_t thread_handles[] = 0, + void *stack[] = 0, + size_t stack_size[] = 0, + const char* thr_name[] = 0); + + /** + * Spawn a specified number of threads, all of which execute @a func + * with argument @a arg. + * + * @param thread_ids An array to receive the thread IDs of successfully + * spawned buffer. If 0, the thread IDs are not returned. + * If specified, the array must be at least @a n entries. + * + * @param n The number of threads to spawn. + * + * @param func The function that is called in the spawned thread. + * + * @param arg The value passed to each spawned thread's @a func. + * + * @param flags Flags to control attributes of the spawned threads. + * @sa ACE_OS::thr_create() for descriptions of the + * possible flags values and their interactions. + * + * @param priority The priority at which the threads are spawned. + * + * @param grp_id The thread group that the spawned threads are + * added to. If -1 is specified, a new thread group is + * created for the spawned threads. + * + * @param stack An array of @a n pointers to pre-allocated stack space + * for each thread's stack. If specified as 0, the + * platform allocates stack space for each thread. If + * a stack is specified, it is recommended that a + * @a stack_size element also be supplied that specifies + * the size of the stack. + * Not all platforms support pre-allocated stacks. If + * @a stack is specified for a platform which does not + * allow pre-allocated stack space this parameter is + * ignored. + * + * @param stack_size An array of @a n values which indicate how large + * each thread's stack should be, in bytes. + * If pre-allocated stacks are passed in @a stacks, these + * sizes are for those stacks. If no pre-allocated stacks + * are passed, the stack sizes are specified to the + * operating system to request that it allocate stacks + * of the specified sizes. If an array entry is 0, the + * platform defaults are used for the corresponding thread. + * If a 0 array pointer is specified, platform defaults + * are used for all thread stack sizes. + * + * @param thread_handles An array of @a n entries which will receive + * the thread handles of the spawned threads. + * + * @param task The ACE_Task that the spawned threads are associated + * with. If 0, the threads are not associated with an + * ACE_Task. This argument is usually assigned by the + * ACE_Task_Base::activate() method to associate the + * spawned threads with the spawning ACE_Task object. + * + * @param thr_name An array of names to assign to the spawned threads. + * This is only meaningful for platforms that have a + * capacity to name threads (e.g., VxWorks and some + * varieties of Pthreads). This argument is ignored if + * specified as 0 and on platforms that do not have the + * capability to name threads. + * + * ACE_Thread_Manager can manipulate threads in groups based on + * @a grp_id or @a task using functions such as kill_grp() or + * cancel_task(). + * + * @retval -1 on failure; @c errno contains an error value. + * @retval The group id of the threads. + + */ + int spawn_n (ACE_thread_t thread_ids[], + size_t n, + ACE_THR_FUNC func, + void *arg, + long flags, + long priority = ACE_DEFAULT_THREAD_PRIORITY, + int grp_id = -1, + void *stack[] = 0, + size_t stack_size[] = 0, + ACE_hthread_t thread_handles[] = 0, + ACE_Task_Base *task = 0, + const char* thr_name[] = 0); + + /** + * Called to clean up when a thread exits. + * + * @param do_thread_exit If non-0 then ACE_Thread::exit is called to + * exit the thread + * @param status If ACE_Thread_Exit is called, this is passed as + * the exit value of the thread. + * Should _not_ be called by main thread. + */ + ACE_THR_FUNC_RETURN exit (ACE_THR_FUNC_RETURN status = 0, + bool do_thread_exit = true); + + /** + * Block until there are no more threads running in this thread + * manager or @c timeout expires. + * + * @param timeout is treated as "absolute" time by default, but this + * can be changed to "relative" time by setting the @c + * use_absolute_time to false. + * @param abandon_detached_threads If true, @c wait() will first + * check thru its thread list for + * threads with THR_DETACHED or + * THR_DAEMON flags set and remove + * these threads. Notice that + * unlike other @c wait_*() methods, + * by default, @c wait() does wait on + * all thread spawned by this + * thread manager no matter the detached + * flags are set or not unless it is + * called with @c + * abandon_detached_threads flag set. + * @param use_absolute_time If true then treat @c timeout as + * absolute time, else relative time. + * @return 0 on success * and -1 on failure. + * + * @note If this function is called while the @c + * ACE_Object_Manager is shutting down (as a result of program + * rundown via @c ACE::fini()), it will not wait for any threads to + * complete. If you must wait for threads spawned by this thread + * manager to complete and you are in a ACE rundown situation (such + * as your object is being destroyed by the @c ACE_Object_Manager) + * you can use @c wait_grp() instead. + */ + int wait (const ACE_Time_Value *timeout = 0, + bool abandon_detached_threads = false, + bool use_absolute_time = true); + + /// Join a thread specified by @a tid. Do not wait on a detached thread. + int join (ACE_thread_t tid, ACE_THR_FUNC_RETURN *status = 0); + + /** + * Block until there are no more threads running in a group. + * Returns 0 on success and -1 on failure. Notice that wait_grp + * will not wait on detached threads. + */ + int wait_grp (int grp_id); + + /** + * Return the "real" handle to the calling thread, caching it if + * necessary in TSS to speed up subsequent lookups. This is + * necessary since on some platforms (e.g., Windows) we can't get this + * handle via direct method calls. Notice that you should *not* + * close the handle passed back from this method. It is used + * internally by Thread Manager. On the other hand, you *have to* + * use this internal thread handle when working on Thread_Manager. + * Return -1 if fail. + */ + int thr_self (ACE_hthread_t &); + + /** + * Return the unique ID of the calling thread. + * Same as calling ACE_Thread::self(). + */ + ACE_thread_t thr_self (void); + + /** + * Returns a pointer to the current ACE_Task_Base we're executing + * in if this thread is indeed running in an ACE_Task_Base, else + * return 0. + */ + ACE_Task_Base *task (void); + + /** + * @name Suspend and resume methods + * + * Suspend/resume is not supported on all platforms. For example, Pthreads + * does not support these functions. + */ + //@{ + + /// Suspend all threads + int suspend_all (void); + + /// Suspend a single thread. + int suspend (ACE_thread_t); + + /// Suspend a group of threads. + int suspend_grp (int grp_id); + + /** + * True if @a t_id is inactive (i.e., suspended), else false. Always + * return false if @a t_id is not managed by the Thread_Manager. + */ + int testsuspend (ACE_thread_t t_id); + + /// Resume all stopped threads + int resume_all (void); + + /// Resume a single thread. + int resume (ACE_thread_t); + + /// Resume a group of threads. + int resume_grp (int grp_id); + + /** + * True if @a t_id is active (i.e., resumed), else false. Always + * return false if @a t_id is not managed by the Thread_Manager. + */ + int testresume (ACE_thread_t t_id); + + //@} + + // = Send signals to one or more threads without blocking. + /** + * Send @a signum to all stopped threads. Not supported on platforms + * that do not have advanced signal support, such as Win32. + */ + int kill_all (int signum); + /** + * Send the @a signum to a single thread. Not supported on platforms + * that do not have advanced signal support, such as Win32. + */ + int kill (ACE_thread_t, int signum); + /** + * Send @a signum to a group of threads, not supported on platforms + * that do not have advanced signal support, such as Win32. + */ + int kill_grp (int grp_id, int signum); + + // = Cancel methods, which provides a cooperative thread-termination mechanism (will not block). + /** + * Cancel's all the threads. + */ + int cancel_all (int async_cancel = 0); + + /** + * Cancel a single thread. + */ + int cancel (ACE_thread_t, int async_cancel = 0); + + /** + * Cancel a group of threads. + */ + int cancel_grp (int grp_id, int async_cancel = 0); + + /** + * True if @a t_id is cancelled, else false. Always return false if + * @a t_id is not managed by the Thread_Manager. + */ + int testcancel (ACE_thread_t t_id); + + /** + * True if @a t_id has terminated (i.e., is no longer running), + * but the slot in the thread manager hasn't been reclaimed yet, + * else false. Always return false if @a t_id is not managed by the + * Thread_Manager. + */ + int testterminate (ACE_thread_t t_id); + + /// Set group ids for a particular thread id. + int set_grp (ACE_thread_t, + int grp_id); + + /// Get group ids for a particular thread id. + int get_grp (ACE_thread_t, + int &grp_id); + + /** + * @name Task-related operations + */ + //@{ + /** + * Block until there are no more threads running in a specified task. + * This method will not wait for either detached or daemon threads; + * the threads must have been spawned with the @c THR_JOINABLE flag. + * Upon successful completion, the threads have been joined, so further + * attempts to join with any of the waited-for threads will fail. + * + * @param task The ACE_Task_Base object whose threads are to waited for. + * + * @retval 0 Success. + * @retval -1 Failure (consult errno for further information). + */ + int wait_task (ACE_Task_Base *task); + + /** + * Suspend all threads in an ACE_Task. + */ + int suspend_task (ACE_Task_Base *task); + + /** + * Resume all threads in an ACE_Task. + */ + int resume_task (ACE_Task_Base *task); + + /** + * Send a signal @a signum to all threads in an ACE_Task. + */ + int kill_task (ACE_Task_Base *task, int signum); + + /** + * Cancel all threads in an ACE_Task. If is non-0, + * then asynchronously cancel these threads if the OS platform + * supports cancellation. Otherwise, perform a "cooperative" + * cancellation. + */ + int cancel_task (ACE_Task_Base *task, int async_cancel = 0); + + //@} + + // = Collect thread handles in the thread manager. Notice that + // the collected information is just a snapshot. + /// Check if the thread is managed by the thread manager. Return true if + /// the thread is found, false otherwise. + int hthread_within (ACE_hthread_t handle); + int thread_within (ACE_thread_t tid); + + /// Returns the number of ACE_Task_Base in a group. + int num_tasks_in_group (int grp_id); + + /// Returns the number of threads in an ACE_Task_Base. + int num_threads_in_task (ACE_Task_Base *task); + + /** + * Returns a list of ACE_Task_Base pointers corresponding to the tasks + * that have active threads in a specified thread group. + * + * @param grp_id The thread group ID to obtain task pointers for. + * + * @param task_list is a pointer to an array to receive the list of pointers. + * The caller is responsible for supplying an array with at + * least @arg n entries. + * + * @param n The maximum number of ACE_Task_Base pointers to write + * in @arg task_list. + * + * @retval If successful, the number of pointers returned, which will be + * no greater than @arg n. Returns -1 on error. + * + * @note This method has no way to indicate if there are more than + * @arg n ACE_Task_Base pointers available. Therefore, it may be + * wise to guess a larger value of @arg n than one thinks in cases + * where the exact number of tasks is not known. + * + * @sa num_tasks_in_group(), task_all_list() + */ + ssize_t task_list (int grp_id, + ACE_Task_Base *task_list[], + size_t n); + + /** + * Returns in @a thread_list a list of up to @a n thread ids in an + * ACE_Task_Base. The caller must allocate the memory for + * @a thread_list. In case of an error, -1 is returned. If no + * requested values are found, 0 is returned, otherwise correct + * number of retrieved values are returned. + */ + ssize_t thread_list (ACE_Task_Base *task, + ACE_thread_t thread_list[], + size_t n); + + /** + * Returns in @a hthread_list a list of up to @a n thread handles in + * an ACE_Task_Base. The caller must allocate memory for + * @a hthread_list. In case of an error, -1 is returned. If no + * requested values are found, 0 is returned, otherwise correct + * number of retrieved values are returned. + */ + ssize_t hthread_list (ACE_Task_Base *task, + ACE_hthread_t hthread_list[], + size_t n); + + /** + * Returns in @a thread_list a list of up to @a n thread ids in a + * group @a grp_id. The caller must allocate the memory for + * @a thread_list. In case of an error, -1 is returned. If no + * requested values are found, 0 is returned, otherwise correct + * number of retrieved values are returned. + */ + ssize_t thread_grp_list (int grp_id, + ACE_thread_t thread_list[], + size_t n); + + /** + * Returns in @a hthread_list a list of up to @a n thread handles in + * a group @a grp_id. The caller must allocate memory for + * @a hthread_list. + */ + ssize_t hthread_grp_list (int grp_id, + ACE_hthread_t hthread_list[], + size_t n); + + /** + * Returns a list of ACE_Task_Base pointers corresponding to the tasks + * that have active threads managed by this instance. + * + * @param task_list is a pointer to an array to receive the list of pointers. + * The caller is responsible for supplying an array with at + * least @arg n entries. + * + * @param n The maximum number of ACE_Task_Base pointers to write + * in @arg task_list. + * + * @retval If successful, the number of pointers returned, which will be + * no greater than @arg n. Returns -1 on error. + * + * @note This method has no way to indicate if there are more than + * @arg n ACE_Task_Base pointers available. Therefore, it may be + * wise to guess a larger value of @arg n than one thinks in cases + * where the exact number of tasks is not known. + * + * @sa count_threads() + */ + ssize_t task_all_list (ACE_Task_Base *task_list[], + size_t n); + + /** + * Returns in @a thread_list a list of up to @a n thread ids. The + * caller must allocate the memory for @a thread_list. In case of an + * error, -1 is returned. If no requested values are found, 0 is + * returned, otherwise correct number of retrieved values are + * returned. + */ + ssize_t thread_all_list (ACE_thread_t thread_list[], + size_t n); + + /// Set group ids for a particular task. + int set_grp (ACE_Task_Base *task, int grp_id); + + /// Get group ids for a particular task. + int get_grp (ACE_Task_Base *task, int &grp_id); + + /// Return a count of the current number of threads active in the + /// . + size_t count_threads (void) const; + + /// Get the state of the thread. Returns false if the thread is not + /// managed by this thread manager. + int thr_state (ACE_thread_t id, ACE_UINT32& state); + + /** + * Register an At_Thread_Exit hook and the ownership is acquire by + * Thread_Descriptor, this is the usual case when the AT is dynamically + * allocated. + */ + int at_exit (ACE_At_Thread_Exit* cleanup); + + /// Register an At_Thread_Exit hook and the ownership is retained for the + /// caller. Normally used when the at_exit hook is created in stack. + int at_exit (ACE_At_Thread_Exit& cleanup); + + /** + * + ***** + * @deprecated This function is deprecated. Please use the previous two + * at_exit method. Notice that you should avoid mixing this method + * with the previous two at_exit methods. + ***** + * + * Register an object (or array) for cleanup at + * thread termination. "cleanup_hook" points to a (global, or + * static member) function that is called for the object or array + * when it to be destroyed. It may perform any necessary cleanup + * specific for that object or its class. "param" is passed as the + * second parameter to the "cleanup_hook" function; the first + * parameter is the object (or array) to be destroyed. + * "cleanup_hook", for example, may delete the object (or array). + * If == 0, the will _NOT_ get cleanup at + * thread exit. You can use this to cancel the previously added + * at_exit. + */ + int at_exit (void *object, + ACE_CLEANUP_FUNC cleanup_hook, + void *param); + + /// Access function to determine whether the Thread_Manager will + /// wait for its thread to exit or not when being closing down. + void wait_on_exit (int dowait); + int wait_on_exit (void); + + /// Dump the state of an object. + void dump (void); + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + // = Accessors for ACE_Thread_Descriptors. + /** + * Get a pointer to the calling thread's own thread_descriptor. + * This must be called from a spawn thread. This function will + * fetch the info from TSS. + */ + ACE_Thread_Descriptor *thread_desc_self (void); + + /// Return a pointer to the thread's Thread_Descriptor, + /// 0 if fail. + ACE_Thread_Descriptor *thread_descriptor (ACE_thread_t); + + /// Return a pointer to the thread's Thread_Descriptor, + /// 0 if fail. + ACE_Thread_Descriptor *hthread_descriptor (ACE_hthread_t); + + /// Create a new thread (must be called with locks held). + int spawn_i (ACE_THR_FUNC func, + void *arg, + long flags, + ACE_thread_t * = 0, + ACE_hthread_t *t_handle = 0, + long priority = ACE_DEFAULT_THREAD_PRIORITY, + int grp_id = -1, + void *stack = 0, + size_t stack_size = 0, + ACE_Task_Base *task = 0, + const char** thr_name = 0); + + /// Run the registered hooks when the thread exits. + void run_thread_exit_hooks (int i); + + /// Locate the index of the table slot occupied by . Returns + /// -1 if is not in the table doesn't contain . + ACE_Thread_Descriptor *find_thread (ACE_thread_t t_id); + + /// Locate the index of the table slot occupied by . Returns + /// -1 if is not in the table doesn't contain . + ACE_Thread_Descriptor *find_hthread (ACE_hthread_t h_id); + + /** + * Locate the thread descriptor address of the list occupied by + * @a task. Returns 0 if @a task is not in the table doesn't contain + * @a task. + */ + ACE_Thread_Descriptor *find_task (ACE_Task_Base *task, + size_t slot = 0); + + /// Insert a thread in the table (checks for duplicates). + int insert_thr (ACE_thread_t t_id, + ACE_hthread_t, + int grp_id = -1, + long flags = 0); + + /// Append a thread in the table (adds at the end, growing the table + /// if necessary). + int append_thr (ACE_thread_t t_id, ACE_hthread_t, + ACE_UINT32, + int grp_id, + ACE_Task_Base *task = 0, + long flags = 0, + ACE_Thread_Descriptor *td = 0); + + /// Remove thread from the table. + void remove_thr (ACE_Thread_Descriptor *td, + int close_handler); + + /// Remove all threads from the table. + void remove_thr_all (void); + + // = The following four methods implement a simple scheme for + // operating on a collection of threads atomically. + + /** + * Efficiently check whether @a thread is in a particular @a state. + * This call updates the TSS cache if possible to speed up + * subsequent searches. + */ + int check_state (ACE_UINT32 state, + ACE_thread_t thread, + int enable = 1); + + /// Apply @a func to all members of the table that match the @a task + int apply_task (ACE_Task_Base *task, + ACE_THR_MEMBER_FUNC func, + int = 0); + + /// Apply @a func to all members of the table that match the @a grp_id. + int apply_grp (int grp_id, + ACE_THR_MEMBER_FUNC func, + int arg = 0); + + /// Apply @a func to all members of the table. + int apply_all (ACE_THR_MEMBER_FUNC, + int = 0); + + /// Join the thread described in @a td. + int join_thr (ACE_Thread_Descriptor *td, + int = 0); + + /// Resume the thread described in @a td. + int resume_thr (ACE_Thread_Descriptor *td, + int = 0); + + /// Suspend the thread described in @a td. + int suspend_thr (ACE_Thread_Descriptor *td, + int = 0); + + /// Send signal @a signum to the thread described in @a td. + int kill_thr (ACE_Thread_Descriptor *td, + int signum); + + /// Set the cancellation flag for the thread described in @a td. + int cancel_thr (ACE_Thread_Descriptor *td, + int async_cancel = 0); + + /// Register a thread as terminated and put it into the . + int register_as_terminated (ACE_Thread_Descriptor *td); + + /// Setting the static ACE_TSS_TYPE (ACE_Thread_Exit) *thr_exit_ pointer. + static int set_thr_exit (ACE_TSS_TYPE (ACE_Thread_Exit) *ptr); + + /** + * Keeping a list of thread descriptors within the thread manager. + * Double-linked list enables us to cache the entries in TSS + * and adding/removing thread descriptor entries without + * affecting other thread's descriptor entries. + */ + ACE_Double_Linked_List thr_list_; + +#if !defined (ACE_HAS_VXTHREADS) + /// Collect terminated but not yet joined thread entries. + ACE_Double_Linked_List terminated_thr_list_; +#endif /* !ACE_HAS_VXTHREADS */ + + /// Collect pointers to thread descriptors of threads to be removed later. + ACE_Unbounded_Queue thr_to_be_removed_; + + /// Keeps track of the next group id to assign. + int grp_id_; + + /// Set if we want the Thread_Manager to wait on all threads before + /// being closed, reset otherwise. + int automatic_wait_; + + // = ACE_Thread_Mutex and condition variable for synchronizing termination. +#if defined (ACE_HAS_THREADS) + /// Serialize access to the . + ACE_Thread_Mutex lock_; + + /// Keep track of when there are no more threads. + ACE_Condition_Thread_Mutex zero_cond_; +#endif /* ACE_HAS_THREADS */ + + ACE_Locked_Free_List thread_desc_freelist_; + +private: +#if ! defined (ACE_THREAD_MANAGER_LACKS_STATICS) + /// Pointer to a process-wide ACE_Thread_Manager. + static ACE_Thread_Manager *thr_mgr_; + + /// Must delete the thr_mgr_ if true. + static bool delete_thr_mgr_; + + /// Global ACE_TSS (ACE_Thread_Exit) object ptr. + static ACE_TSS_TYPE (ACE_Thread_Exit) *thr_exit_; +#endif /* ! defined (ACE_THREAD_MANAGER_LACKS_STATICS) */ +}; + +#if defined (ACE_THREAD_MANAGER_LACKS_STATICS) +#define ACE_THREAD_MANAGER_SINGLETON_DEFINE \ + ACE_Singleton; +typedef ACE_Singleton ACE_THREAD_MANAGER_SINGLETON; +#endif /* defined (ACE_THREAD_MANAGER_LACKS_STATICS) */ + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Thread_Manager.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif /* ACE_THREAD_MANAGER_H */ diff --git a/dep/acelite/ace/Thread_Manager.inl b/dep/acelite/ace/Thread_Manager.inl new file mode 100644 index 00000000000..4b9afe979c0 --- /dev/null +++ b/dep/acelite/ace/Thread_Manager.inl @@ -0,0 +1,305 @@ +// -*- C++ -*- +// +// $Id: Thread_Manager.inl 85341 2009-05-14 11:07:37Z johnnyw $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE +ACE_At_Thread_Exit::ACE_At_Thread_Exit (void) + : next_ (0), + td_ (0), + was_applied_ (false), + is_owner_ (true) +{ +} + +ACE_INLINE bool +ACE_At_Thread_Exit::was_applied() const +{ + return was_applied_; +} + +ACE_INLINE bool +ACE_At_Thread_Exit::was_applied (bool applied) +{ + was_applied_ = applied; + if (was_applied_) + td_ = 0; + return was_applied_; +} + +ACE_INLINE bool +ACE_At_Thread_Exit::is_owner() const +{ + return is_owner_; +} + +ACE_INLINE bool +ACE_At_Thread_Exit::is_owner (bool owner) +{ + is_owner_ = owner; + return is_owner_; +} + +ACE_INLINE void +ACE_At_Thread_Exit::do_apply (void) +{ + if (!this->was_applied_ && this->is_owner_) + td_->at_pop(); +} + +ACE_INLINE +ACE_At_Thread_Exit_Func::ACE_At_Thread_Exit_Func (void *object, + ACE_CLEANUP_FUNC func, + void *param) + : object_(object), + func_(func), + param_(param) +{ +} + +ACE_INLINE +ACE_Thread_Descriptor_Base::ACE_Thread_Descriptor_Base (void) + : ACE_OS_Thread_Descriptor (), + thr_id_ (ACE_OS::NULL_thread), + thr_handle_ (ACE_OS::NULL_hthread), + grp_id_ (0), + thr_state_ (ACE_Thread_Manager::ACE_THR_IDLE), + task_ (0), + next_ (0), + prev_ (0) +{ +} + +ACE_INLINE +ACE_Thread_Descriptor_Base::~ACE_Thread_Descriptor_Base (void) +{ +} + +ACE_INLINE bool +ACE_Thread_Descriptor_Base::operator== ( + const ACE_Thread_Descriptor_Base &rhs) const +{ + return + ACE_OS::thr_cmp (this->thr_handle_, rhs.thr_handle_) + && ACE_OS::thr_equal (this->thr_id_, rhs.thr_id_); +} + +ACE_INLINE bool +ACE_Thread_Descriptor_Base::operator!=(const ACE_Thread_Descriptor_Base &rhs) const +{ + return !(*this == rhs); +} + +ACE_INLINE ACE_Task_Base * +ACE_Thread_Descriptor_Base::task (void) const +{ + ACE_TRACE ("ACE_Thread_Descriptor_Base::task"); + return this->task_; +} + +// Group ID. + +ACE_INLINE int +ACE_Thread_Descriptor_Base::grp_id (void) const +{ + ACE_TRACE ("ACE_Thread_Descriptor_Base::grp_id"); + return grp_id_; +} + +// Current state of the thread. +ACE_INLINE ACE_UINT32 +ACE_Thread_Descriptor_Base::state (void) const +{ + ACE_TRACE ("ACE_Thread_Descriptor_Base::state"); + return thr_state_; +} + +// Reset this base descriptor. +ACE_INLINE void +ACE_Thread_Descriptor_Base::reset (void) +{ + ACE_TRACE ("ACE_Thread_Descriptor_Base::reset"); + this->thr_id_ = ACE_OS::NULL_thread; + this->thr_handle_ = ACE_OS::NULL_hthread; + this->grp_id_ = 0; + this->thr_state_ = ACE_Thread_Manager::ACE_THR_IDLE; + this->task_ = 0; + this->flags_ = 0; +} + +// Unique thread id. +ACE_INLINE ACE_thread_t +ACE_Thread_Descriptor::self (void) const +{ + ACE_TRACE ("ACE_Thread_Descriptor::self"); + return this->thr_id_; +} + +// Unique kernel-level thread handle. + +ACE_INLINE void +ACE_Thread_Descriptor::self (ACE_hthread_t &handle) +{ + ACE_TRACE ("ACE_Thread_Descriptor::self"); + handle = this->thr_handle_; +} + +ACE_INLINE void +ACE_Thread_Descriptor::log_msg_cleanup (ACE_Log_Msg* log_msg) + +{ + log_msg_ = log_msg; +} + +// Set the pointer +ACE_INLINE void +ACE_Thread_Descriptor::set_next (ACE_Thread_Descriptor *td) +{ + ACE_TRACE ("ACE_Thread_Descriptor::set_next"); + this->next_ = td; +} + +// Get the pointer +ACE_INLINE ACE_Thread_Descriptor * +ACE_Thread_Descriptor::get_next (void) const +{ + ACE_TRACE ("ACE_Thread_Descriptor::get_next"); + return static_cast (this->next_); +} + +// Reset this thread descriptor +ACE_INLINE void +ACE_Thread_Descriptor::reset (ACE_Thread_Manager *tm) +{ + ACE_TRACE ("ACE_Thread_Descriptor::reset"); + this->ACE_Thread_Descriptor_Base::reset (); + this->at_exit_list_ = 0; + // Start the at_exit hook list. + this->tm_ = tm; + // Setup the Thread_Manager. + this->log_msg_ = 0; + this->terminated_ = false; +} + +ACE_INLINE ACE_Thread_Descriptor * +ACE_Thread_Manager::thread_desc_self (void) +{ + // This method must be called with lock held. + + // Try to get it from cache. + ACE_Thread_Descriptor *desc = ACE_LOG_MSG->thr_desc (); + +#if 1 + // ACE_ASSERT (desc != 0); + // Thread descriptor should always get cached. +#else + if (desc == 0) + { + ACE_thread_t id = ACE_OS::thr_self (); + + desc = this->find_thread (id); + + // Thread descriptor adapter might not have been put into the + // list yet. + if (desc != 0) + // Update the TSS cache. + ACE_LOG_MSG->thr_desc (desc); + } +#endif + return desc; +} + +// Return the unique ID of the thread. + +ACE_INLINE ACE_thread_t +ACE_Thread_Manager::thr_self (void) +{ + ACE_TRACE ("ACE_Thread_Manager::thr_self"); + return ACE_Thread::self (); +} + +ACE_INLINE ACE_Task_Base * +ACE_Thread_Manager::task (void) +{ + ACE_TRACE ("ACE_Thread_Manager::task"); + + ACE_Thread_Descriptor *td = this->thread_desc_self () ; + + if (td == 0) + return 0; + else + return td->task (); +} + +ACE_INLINE int +ACE_Thread_Manager::open (size_t) +{ + // Currently no-op. + return 0; +} + +ACE_INLINE int +ACE_Thread_Manager::at_exit (ACE_At_Thread_Exit* at) +{ + ACE_Thread_Descriptor *td = this->thread_desc_self (); + if (td == 0) + return -1; + else + return td->at_exit (at); +} + +ACE_INLINE int +ACE_Thread_Manager::at_exit (ACE_At_Thread_Exit& at) +{ + ACE_Thread_Descriptor *td = this->thread_desc_self (); + if (td == 0) + return -1; + else + return td->at_exit (at); +} + +ACE_INLINE int +ACE_Thread_Manager::at_exit (void *object, + ACE_CLEANUP_FUNC cleanup_hook, + void *param) +{ + ACE_Thread_Descriptor *td = this->thread_desc_self (); + if (td == 0) + return -1; + else + return td->at_exit (object, cleanup_hook, param); +} + +ACE_INLINE void +ACE_Thread_Manager::wait_on_exit (int do_wait) +{ + this->automatic_wait_ = do_wait; +} + +ACE_INLINE int +ACE_Thread_Manager::wait_on_exit (void) +{ + return this->automatic_wait_; +} + +ACE_INLINE int +ACE_Thread_Manager::register_as_terminated (ACE_Thread_Descriptor *td) +{ +#if defined (ACE_HAS_VXTHREADS) + ACE_UNUSED_ARG (td); +#else /* ! ACE_HAS_VXTHREADS */ + ACE_Thread_Descriptor_Base *tdb = 0; + ACE_NEW_RETURN (tdb, ACE_Thread_Descriptor_Base (*td), -1); + this->terminated_thr_list_.insert_tail (tdb); +#endif /* !ACE_HAS_VXTHREADS */ + return 0; +} + +ACE_INLINE size_t +ACE_Thread_Manager::count_threads (void) const +{ + return this->thr_list_.size (); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Thread_Mutex.cpp b/dep/acelite/ace/Thread_Mutex.cpp new file mode 100644 index 00000000000..4ebdc412e6f --- /dev/null +++ b/dep/acelite/ace/Thread_Mutex.cpp @@ -0,0 +1,62 @@ +/** + * @file Thread_Mutex.cpp + * + * $Id: Thread_Mutex.cpp 80826 2008-03-04 14:51:23Z wotte $ + * + * Originally in Synch.cpp + * + * @author Douglas C. Schmidt + */ + +#include "ace/Thread_Mutex.h" + +#if defined (ACE_HAS_THREADS) + +#if !defined (__ACE_INLINE__) +#include "ace/Thread_Mutex.inl" +#endif /* __ACE_INLINE__ */ + +#include "ace/Log_Msg.h" +#include "ace/Malloc_T.h" + +ACE_RCSID(ace, Thread_Mutex, "$Id: Thread_Mutex.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Thread_Mutex) + +void +ACE_Thread_Mutex::dump (void) const +{ +#if defined (ACE_HAS_DUMP) +// ACE_TRACE ("ACE_Thread_Mutex::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n"))); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +ACE_Thread_Mutex::~ACE_Thread_Mutex (void) +{ +// ACE_TRACE ("ACE_Thread_Mutex::~ACE_Thread_Mutex"); + this->remove (); +} + +ACE_Thread_Mutex::ACE_Thread_Mutex (const ACE_TCHAR *name, ACE_mutexattr_t *arg) + : removed_ (false) +{ +// ACE_TRACE ("ACE_Thread_Mutex::ACE_Thread_Mutex"); + + if (ACE_OS::thread_mutex_init (&this->lock_, + 0, + name, + arg) != 0) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_Thread_Mutex::ACE_Thread_Mutex"))); +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_THREADS */ diff --git a/dep/acelite/ace/Thread_Mutex.h b/dep/acelite/ace/Thread_Mutex.h new file mode 100644 index 00000000000..fd8f3959587 --- /dev/null +++ b/dep/acelite/ace/Thread_Mutex.h @@ -0,0 +1,176 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file Thread_Mutex.h + * + * $Id: Thread_Mutex.h 89127 2010-02-22 19:58:18Z schmidt $ + * + * Moved from Synch.h. + * + * @author Douglas C. Schmidt + */ +//========================================================================== + +#ifndef ACE_THREAD_MUTEX_H +#define ACE_THREAD_MUTEX_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_HAS_THREADS) +# include "ace/Null_Mutex.h" +#else /* ACE_HAS_THREADS */ +// ACE platform supports some form of threading. + +#include /**/ "ace/ACE_export.h" +#include "ace/OS_NS_Thread.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Thread_Mutex + * + * @brief ACE_Thread_Mutex wrapper (only valid for threads in the same + * process). + * + * This implementation is optimized for locking threads that are + * in the same process. It maps to s on NT + * and with set to on UNIX. + * ACE_Thread_Mutex is recursive on some platforms (like + * Win32). However, on most platforms (like Solaris) it is not + * recursive. To be totally safe and portable, developers + * should use ACE_Recursive_Thread_Mutex when they need a + * recursive mutex. + */ +class ACE_Export ACE_Thread_Mutex +{ + friend class ACE_Condition_Thread_Mutex; +public: + /// Constructor. + ACE_Thread_Mutex (const ACE_TCHAR *name = 0, + ACE_mutexattr_t *attributes = 0); + + /// Implicitly destroy the mutex. + ~ACE_Thread_Mutex (void); + + /** + * Explicitly destroy the mutex. Note that only one thread should + * call this method since it doesn't protect against race + * conditions. + */ + int remove (void); + + /// Acquire lock ownership (wait on queue if necessary). + int acquire (void); + + /** + * Block the thread until we acquire the mutex or until @a tv times + * out, in which case -1 is returned with @c errno == @c ETIME. Note + * that @a tv is assumed to be in "absolute" rather than "relative" + * time. The value of @a tv is updated upon return to show the + * actual (absolute) acquisition time. + */ + int acquire (ACE_Time_Value &tv); + + /** + * If @a tv == 0 the call directly. Otherwise, Block the + * thread until we acquire the mutex or until @a tv times out, in + * which case -1 is returned with @c errno == @c ETIME. Note that + * @a tv is assumed to be in "absolute" rather than "relative" time. + * The value of @a tv is updated upon return to show the actual + * (absolute) acquisition time. + */ + int acquire (ACE_Time_Value *tv); + + /** + * Conditionally acquire lock (i.e., don't wait on queue). Returns + * -1 on failure. If we "failed" because someone else already had + * the lock, @c errno is set to @c EBUSY. + */ + int tryacquire (void); + + /// Release lock and unblock a thread at head of queue. + int release (void); + + /** + * Acquire mutex ownership. This calls acquire() and is only here + * to make the ACE_Thread_Mutex interface consistent with the + * other synchronization APIs. + */ + int acquire_read (void); + + /** + * Acquire mutex ownership. This calls acquire() and is only here + * to make the ACE_Thread_Mutex interface consistent with the + * other synchronization APIs. + */ + int acquire_write (void); + + /** + * Conditionally acquire mutex (i.e., won't block). This calls + * tryacquire() and is only here to make the ACE_Thread_Mutex + * interface consistent with the other synchronization APIs. + * Returns -1 on failure. If we "failed" because someone else + * already had the lock, @c errno is set to @c EBUSY. + */ + int tryacquire_read (void); + + /** + * Conditionally acquire mutex (i.e., won't block). This calls + * tryacquire() and is only here to make the ACE_Thread_Mutex + * interface consistent with the other synchronization APIs. + * Returns -1 on failure. If we "failed" because someone else + * already had the lock, @c errno is set to @c EBUSY. + */ + int tryacquire_write (void); + + /** + * This is only here to make the ACE_Thread_Mutex interface + * consistent with the other synchronization APIs. Assumes the + * caller has already acquired the mutex using one of the above + * calls, and returns 0 (success) always. + */ + int tryacquire_write_upgrade (void); + + /// Return the underlying mutex. + const ACE_thread_mutex_t &lock (void) const; + ACE_thread_mutex_t &lock (void); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + /// Mutex type that supports single-process locking efficiently. + ACE_thread_mutex_t lock_; + + /// Keeps track of whether remove() has been called yet to avoid + /// multiple calls, e.g., explicitly and implicitly in the + /// destructor. This flag isn't protected by a lock, so make sure + /// that you don't have multiple threads simultaneously calling + /// on the same object, which is a bad idea anyway... + bool removed_; + +private: + // = Prevent assignment and initialization. + void operator= (const ACE_Thread_Mutex &); + ACE_Thread_Mutex (const ACE_Thread_Mutex &); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Thread_Mutex.inl" +#endif /* __ACE_INLINE__ */ + +#endif /* !ACE_HAS_THREADS */ + +#include /**/ "ace/post.h" +#endif /* ACE_THREAD_MUTEX_H */ diff --git a/dep/acelite/ace/Thread_Mutex.inl b/dep/acelite/ace/Thread_Mutex.inl new file mode 100644 index 00000000000..d52fce904d0 --- /dev/null +++ b/dep/acelite/ace/Thread_Mutex.inl @@ -0,0 +1,104 @@ +// -*- C++ -*- +// +// $Id: Thread_Mutex.inl 89127 2010-02-22 19:58:18Z schmidt $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE const ACE_thread_mutex_t & +ACE_Thread_Mutex::lock (void) const +{ +// ACE_TRACE ("ACE_Thread_Mutex::lock"); + return this->lock_; +} + +ACE_INLINE ACE_thread_mutex_t & +ACE_Thread_Mutex::lock (void) +{ +// ACE_TRACE ("ACE_Thread_Mutex::lock"); + return this->lock_; +} + +ACE_INLINE int +ACE_Thread_Mutex::acquire_read (void) +{ +// ACE_TRACE ("ACE_Thread_Mutex::acquire_read"); + return ACE_OS::thread_mutex_lock (&this->lock_); +} + +ACE_INLINE int +ACE_Thread_Mutex::acquire_write (void) +{ +// ACE_TRACE ("ACE_Thread_Mutex::acquire_write"); + return ACE_OS::thread_mutex_lock (&this->lock_); +} + +ACE_INLINE int +ACE_Thread_Mutex::tryacquire_read (void) +{ +// ACE_TRACE ("ACE_Thread_Mutex::tryacquire_read"); + return ACE_OS::thread_mutex_trylock (&this->lock_); +} + +ACE_INLINE int +ACE_Thread_Mutex::tryacquire_write (void) +{ +// ACE_TRACE ("ACE_Thread_Mutex::tryacquire_write"); + return ACE_OS::thread_mutex_trylock (&this->lock_); +} + +ACE_INLINE int +ACE_Thread_Mutex::tryacquire_write_upgrade (void) +{ +// ACE_TRACE ("ACE_Thread_Mutex::tryacquire_write_upgrade"); + return 0; +} + +ACE_INLINE int +ACE_Thread_Mutex::acquire (void) +{ +// ACE_TRACE ("ACE_Thread_Mutex::acquire"); + return ACE_OS::thread_mutex_lock (&this->lock_); +} + +ACE_INLINE int +ACE_Thread_Mutex::acquire (ACE_Time_Value &tv) +{ + // ACE_TRACE ("ACE_Thread_Mutex::acquire"); + return ACE_OS::thread_mutex_lock (&this->lock_, tv); +} + +ACE_INLINE int +ACE_Thread_Mutex::acquire (ACE_Time_Value *tv) +{ + // ACE_TRACE ("ACE_Thread_Mutex::acquire"); + return ACE_OS::thread_mutex_lock (&this->lock_, tv); +} + +ACE_INLINE int +ACE_Thread_Mutex::tryacquire (void) +{ +// ACE_TRACE ("ACE_Thread_Mutex::tryacquire"); + return ACE_OS::thread_mutex_trylock (&this->lock_); +} + +ACE_INLINE int +ACE_Thread_Mutex::release (void) +{ +// ACE_TRACE ("ACE_Thread_Mutex::release"); + return ACE_OS::thread_mutex_unlock (&this->lock_); +} + +ACE_INLINE int +ACE_Thread_Mutex::remove (void) +{ +// ACE_TRACE ("ACE_Thread_Mutex::remove"); + int result = 0; + if (!this->removed_) + { + this->removed_ = true; + result = ACE_OS::thread_mutex_destroy (&this->lock_); + } + return result; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Thread_Semaphore.cpp b/dep/acelite/ace/Thread_Semaphore.cpp new file mode 100644 index 00000000000..39b28931db5 --- /dev/null +++ b/dep/acelite/ace/Thread_Semaphore.cpp @@ -0,0 +1,62 @@ +/** + * @file Thread_Semaphore.cpp + * + * $Id: Thread_Semaphore.cpp 80826 2008-03-04 14:51:23Z wotte $ + * + * Originally in Synch.cpp + * + * @author Douglas C. Schmidt + */ + +#include "ace/Thread_Semaphore.h" + +#if defined (ACE_HAS_THREADS) + +#if !defined (__ACE_INLINE__) +#include "ace/Thread_Semaphore.inl" +#endif /* __ACE_INLINE__ */ + +#include "ace/ACE.h" + +ACE_RCSID(ace, Thread_Semaphore, "$Id: Thread_Semaphore.cpp 80826 2008-03-04 14:51:23Z wotte $") + + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +void +ACE_Thread_Semaphore::dump (void) const +{ +#if defined (ACE_HAS_DUMP) +// ACE_TRACE ("ACE_Thread_Semaphore::dump"); + + ACE_Semaphore::dump (); +#endif /* ACE_HAS_DUMP */ +} + +ACE_Thread_Semaphore::ACE_Thread_Semaphore (unsigned int count, + const ACE_TCHAR *name, + void *arg, + int max) + : ACE_Semaphore (count, USYNC_THREAD, name, arg, max) +{ +// ACE_TRACE ("ACE_Thread_Semaphore::ACE_Thread_Semaphore"); +} + +/*****************************************************************************/ + +ACE_Thread_Semaphore * +ACE_Malloc_Lock_Adapter_T::operator () (const ACE_TCHAR *name) +{ + ACE_Thread_Semaphore *p = 0; + if (name == 0) + ACE_NEW_RETURN (p, ACE_Thread_Semaphore (1, name), 0); + else + ACE_NEW_RETURN (p, ACE_Thread_Semaphore (1, ACE::basename (name, + ACE_DIRECTORY_SEPARATOR_CHAR)), + 0); + return p; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_THREADS */ diff --git a/dep/acelite/ace/Thread_Semaphore.h b/dep/acelite/ace/Thread_Semaphore.h new file mode 100644 index 00000000000..d7013d9c3f2 --- /dev/null +++ b/dep/acelite/ace/Thread_Semaphore.h @@ -0,0 +1,87 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file Thread_Semaphore.h + * + * $Id: Thread_Semaphore.h 86731 2009-09-17 12:23:48Z johnnyw $ + * + * Moved from Synch.h. + * + * @author Douglas C. Schmidt + */ +//========================================================================== + +#ifndef ACE_THREAD_SEMAPHORE_H +#define ACE_THREAD_SEMAPHORE_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_HAS_THREADS) +# include "ace/Null_Semaphore.h" +#else /* ACE_HAS_THREADS */ +// ACE platform supports some form of threading. + +#include "ace/Semaphore.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Thread_Semaphore + * + * @brief Wrapper for Dijkstra style general semaphores that work + * only within one process. + */ +class ACE_Export ACE_Thread_Semaphore : public ACE_Semaphore +{ +public: + /// Initialize the semaphore, with an initial value of @a count, + /// maximum value of @a max, and unlocked by default. + ACE_Thread_Semaphore (unsigned int count = 1, // By default make this unlocked. + const ACE_TCHAR *name = 0, + void * = 0, + int max = 0x7FFFFFFF); + + /// Default dtor. + ~ACE_Thread_Semaphore (void); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; +}; + +/*****************************************************************************/ + +template class ACE_Malloc_Lock_Adapter_T; + +/** + * @brief Template specialization of ACE_Malloc_Lock_Adapter_T for + * ACE_Thread_Semaphore. + * + * This is needed since the ctor for ACE_Thread_Semaphore doesn't match + * the standard form used by other lock strategy classes. + */ +template<> +class ACE_Export ACE_Malloc_Lock_Adapter_T +{ +public: + ACE_Thread_Semaphore * operator () (const ACE_TCHAR *name); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Thread_Semaphore.inl" +#endif /* __ACE_INLINE__ */ + +#endif /* !ACE_HAS_THREADS */ + +#include /**/ "ace/post.h" +#endif /* ACE_THREAD_SEMAPHORE_H */ diff --git a/dep/acelite/ace/Thread_Semaphore.inl b/dep/acelite/ace/Thread_Semaphore.inl new file mode 100644 index 00000000000..b64ec3c08f5 --- /dev/null +++ b/dep/acelite/ace/Thread_Semaphore.inl @@ -0,0 +1,12 @@ +// -*- C++ -*- +// +// $Id: Thread_Semaphore.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE +ACE_Thread_Semaphore::~ACE_Thread_Semaphore (void) +{ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Throughput_Stats.cpp b/dep/acelite/ace/Throughput_Stats.cpp new file mode 100644 index 00000000000..6e667299729 --- /dev/null +++ b/dep/acelite/ace/Throughput_Stats.cpp @@ -0,0 +1,202 @@ +// $Id: Throughput_Stats.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Throughput_Stats.h" + +#include "ace/OS_NS_stdio.h" +#include "ace/OS_NS_string.h" +#include "ace/High_Res_Timer.h" +#include "ace/Log_Msg.h" + +ACE_RCSID(ace, Throughput_Stats, "$Id: Throughput_Stats.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_Throughput_Stats::ACE_Throughput_Stats (void) + : ACE_Basic_Stats () + , throughput_last_ (0) +#if 0 + // @@TODO: This is what I really wanted to compute, but it just + // does not work. + , throughput_sum_x_ (0) + , throughput_sum_x2_ (0) + , throughput_sum_y_ (0) + , throughput_sum_y2_ (0) + , throughput_sum_xy_ (0) +#endif /* 0 */ +{ +} + +void +ACE_Throughput_Stats::sample (ACE_UINT64 throughput, + ACE_UINT64 latency) +{ + this->ACE_Basic_Stats::sample (latency); + + if (this->samples_count () == 1u) + { + + this->throughput_last_ = throughput; +#if 0 + // @@TODO: This is what I really wanted to compute, but it just + // does not work. + this->throughput_sum_y_ = this->samples_count_; + this->throughput_sum_y2_ = this->samples_count_ * this->samples_count_; + this->throughput_sum_x_ = throughput; + this->throughput_sum_x2_ = throughput * throughput; + this->throughput_sum_xy_ = throughput * this->samples_count_; + + ACE_OS::printf ("%f %qu\n", throughput / 400000000.0, this->samples_count_); +#endif /* 0 */ + } + else + { + this->throughput_last_ = throughput; + +#if 0 + // @@TODO: This is what I really wanted to compute, but it just + // does not work. + this->throughput_sum_y_ += this->samples_count_; + this->throughput_sum_y2_ += this->samples_count_ * this->samples_count_; + this->throughput_sum_x_ += throughput; + this->throughput_sum_x2_ += throughput * throughput; + this->throughput_sum_xy_ += throughput * this->samples_count_; + + ACE_OS::printf ("%f %qu\n", throughput / 400000000.0, this->samples_count_); +#endif /* 0 */ + } +} + +void +ACE_Throughput_Stats::accumulate (const ACE_Throughput_Stats &rhs) +{ + if (rhs.samples_count () == 0u) + return; + + this->ACE_Basic_Stats::accumulate (rhs); + + if (this->samples_count () == 0u) + { + this->throughput_last_ = rhs.throughput_last_; +#if 0 + // @@TODO: This is what I really wanted to compute, but it just + // does not work. + this->throughput_sum_x_ = rhs.throughput_sum_x_; + this->throughput_sum_x2_ = rhs.throughput_sum_x2_; + this->throughput_sum_y_ = rhs.throughput_sum_y_; + this->throughput_sum_y2_ = rhs.throughput_sum_y2_; + this->throughput_sum_xy_ = rhs.throughput_sum_xy_; +#endif /* 0 */ + + return; + } + + + if (this->throughput_last_ < rhs.throughput_last_) + this->throughput_last_ = rhs.throughput_last_; + +#if 0 + // @@TODO: This is what I really wanted to compute, but it just + // does not work. + this->throughput_sum_x_ += rhs.throughput_sum_x_; + this->throughput_sum_x2_ += rhs.throughput_sum_x2_; + this->throughput_sum_y_ += rhs.throughput_sum_y_; + this->throughput_sum_y2_ += rhs.throughput_sum_y2_; + this->throughput_sum_xy_ += rhs.throughput_sum_xy_; +#endif /* 0 */ +} + +void +ACE_Throughput_Stats::dump_results (const ACE_TCHAR* msg, + ACE_UINT32 sf) +{ + if (this->samples_count () == 0u) + { + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("%s : no data collected\n"), msg)); + return; + } + + this->ACE_Basic_Stats::dump_results (msg, sf); + + ACE_Throughput_Stats::dump_throughput (msg, sf, + this->throughput_last_, + this->samples_count ()); + +#if 0 + // @@TODO: This is what I really wanted to generate, but it just + // doesn't work. + double t_sum_x = + ACE_CU64_TO_CU32 (this->throughput_sum_x_);// / sf); + //t_sum_x /= 1000000.0; + double t_sum_y = + ACE_CU64_TO_CU32 (this->throughput_sum_y_); + double t_sum_x2 = + ACE_CU64_TO_CU32 (this->throughput_sum_x2_);// / (sf*sf)); + //t_sum_x2 /= 1000000.0; + //t_sum_x2 /= 1000000.0; + double t_sum_y2 = + ACE_CU64_TO_CU32 (this->throughput_sum_y2_); + double t_sum_xy = + ACE_CU64_TO_CU32 (this->throughput_sum_xy_);// / sf); + //t_sum_xy /= 1000000.0; + double t_avgx = t_sum_x / this->samples_count (); + double t_avgy = t_sum_y / this->samples_count (); + + double t_a = + (this->samples_count () * t_sum_xy - t_sum_x * t_sum_y) + / (this->samples_count () * t_sum_x2 - t_sum_x * t_sum_x); + double t_b = (t_avgy - t_a * t_avgx); + + t_a *= 1000000.0; + + double d_r = + (t_sum_xy - t_avgx * t_sum_y - t_avgy * t_sum_x + + this->samples_count () * t_avgx * t_avgy); + double n_r = + (t_sum_x2 + - this->samples_count () * t_avgx * t_avgx) + * (t_sum_y2 + - this->samples_count () * t_avgy * t_avgy); + double t_r = d_r * d_r / n_r; + + // ACE_DEBUG ((LM_DEBUG, + // "%s throughput: %.2f/%.2f/%.2f/%.6f/%.2f (avg/a/b/r/elapsed)\n", + // msg, t_avg, t_a, t_b, t_r, seconds)); + // ACE_DEBUG ((LM_DEBUG, + // "%s data: %.2f/%.2f/%.2f/%.6f/%.2f (x/x2/y/y2/xy)\n", + // msg, t_sum_x, t_sum_x2, t_sum_y, t_sum_y2, t_sum_xy)); +#endif +} + +void +ACE_Throughput_Stats::dump_throughput (const ACE_TCHAR *msg, + ACE_UINT32 sf, + ACE_UINT64 elapsed_time, + ACE_UINT32 samples_count) +{ +#ifndef ACE_NLOGGING + double seconds = +# if defined ACE_LACKS_LONGLONG_T + elapsed_time / sf; +#elif defined (ACE_LACKS_UNSIGNEDLONGLONG_T) + static_cast (ACE_UINT64_DBLCAST_ADAPTER ( + ACE_U_LongLong(elapsed_time / sf))); +# else /* ! ACE_LACKS_LONGLONG_T */ + static_cast (ACE_UINT64_DBLCAST_ADAPTER (elapsed_time / sf)); +# endif /* ! ACE_LACKS_LONGLONG_T */ + seconds /= ACE_HR_SCALE_CONVERSION; + + const double t_avg = samples_count / seconds; + + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("%s throughput: %.2f (events/second)\n"), + msg, t_avg)); +#else + ACE_UNUSED_ARG (msg); + ACE_UNUSED_ARG (sf); + ACE_UNUSED_ARG (elapsed_time); + ACE_UNUSED_ARG (samples_count); +#endif /* ACE_NLOGGING */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Throughput_Stats.h b/dep/acelite/ace/Throughput_Stats.h new file mode 100644 index 00000000000..c306c856c5e --- /dev/null +++ b/dep/acelite/ace/Throughput_Stats.h @@ -0,0 +1,86 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file Throughput_Stats.h + * + * $Id: Throughput_Stats.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author David L. Levine + */ +//========================================================================== + + +#ifndef ACE_THROUGHPUT_STATS_H +#define ACE_THROUGHPUT_STATS_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Basic_Stats.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/// A simple class to make throughput and latency analysis. +/** + * + * Keep the relevant information to perform throughput and latency + * analysis, including: + * -# Minimum, Average and Maximum latency + * -# Jitter for the latency + * -# Linear regression for throughput + * -# Accumulate results from several samples to obtain aggregated + * results, across several threads or experiments. + * + * @todo The idea behind this class was to use linear regression to + * determine if the throughput was linear or exhibited jitter. + * Unfortunately it never worked quite right, so only average + * throughput is computed. + */ +class ACE_Export ACE_Throughput_Stats : public ACE_Basic_Stats +{ +public: + /// Constructor + ACE_Throughput_Stats (void); + + /// Store one sample + void sample (ACE_UINT64 throughput, ACE_UINT64 latency); + + /// Update the values to reflect the stats in @a throughput + void accumulate (const ACE_Throughput_Stats &throughput); + + /// Print down the stats + void dump_results (const ACE_TCHAR* msg, ACE_UINT32 scale_factor); + + /// Dump the average throughput stats. + static void dump_throughput (const ACE_TCHAR *msg, + ACE_UINT32 scale_factor, + ACE_UINT64 elapsed_time, + ACE_UINT32 samples_count); +private: + /// The last throughput measurement. + ACE_UINT64 throughput_last_; + +#if 0 + /// These are the fields that we should keep to perform linear + /// regression + //@{ + ///@} + ACE_UINT64 throughput_sum_x_; + ACE_UINT64 throughput_sum_x2_; + ACE_UINT64 throughput_sum_y_; + ACE_UINT64 throughput_sum_y2_; + ACE_UINT64 throughput_sum_xy_; +#endif /* 0 */ +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" + +#endif /* ! ACE_THROUGHPUT_STATS_H */ diff --git a/dep/acelite/ace/Time_Value.cpp b/dep/acelite/ace/Time_Value.cpp new file mode 100644 index 00000000000..af07c54422a --- /dev/null +++ b/dep/acelite/ace/Time_Value.cpp @@ -0,0 +1,359 @@ +#include "ace/Time_Value.h" + +ACE_RCSID (ace, + Time_Value, + "$Id: Time_Value.cpp 89791 2010-04-07 14:36:21Z schmidt $") + +#if !defined (__ACE_INLINE__) +#include "ace/Time_Value.inl" +#endif /* __ACE_INLINE__ */ + +#include "ace/Numeric_Limits.h" +#include "ace/If_Then_Else.h" +#include "ace/OS_NS_math.h" + +#ifdef ACE_HAS_CPP98_IOSTREAMS +#include +#include +#endif /* ACE_HAS_CPP98_IOSTREAMS */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/// Static constant representing `zero-time'. +/// Note: this object requires static construction. +const ACE_Time_Value ACE_Time_Value::zero; + +/// Constant for maximum time representable. Note that this time +/// is not intended for use with select () or other calls that may +/// have *their own* implementation-specific maximum time representations. +/// Its primary use is in time computations such as those used by the +/// dynamic subpriority strategies in the ACE_Dynamic_Message_Queue class. +/// Note: this object requires static construction. +const ACE_Time_Value ACE_Time_Value::max_time ( + ACE_Numeric_Limits::max (), + ACE_ONE_SECOND_IN_USECS - 1); + +ACE_ALLOC_HOOK_DEFINE (ACE_Time_Value) + +/// Increment microseconds (the only reason this is here is to allow +/// the use of ACE_Atomic_Op with ACE_Time_Value). +ACE_Time_Value +ACE_Time_Value::operator ++ (int) +{ + // ACE_OS_TRACE ("ACE_Time_Value::operator ++ (int)"); + ACE_Time_Value tv (*this); + ++*this; + return tv; +} + +ACE_Time_Value & +ACE_Time_Value::operator ++ (void) +{ + // ACE_OS_TRACE ("ACE_Time_Value::operator ++ (void)"); + this->usec (this->usec () + 1); + this->normalize (); + return *this; +} + +/// Decrement microseconds (the only reason this is here is / to allow +/// the use of ACE_Atomic_Op with ACE_Time_Value). +ACE_Time_Value +ACE_Time_Value::operator -- (int) +{ + // ACE_OS_TRACE ("ACE_Time_Value::operator -- (int)"); + ACE_Time_Value tv (*this); + --*this; + return tv; +} + +ACE_Time_Value & +ACE_Time_Value::operator -- (void) +{ + // ACE_OS_TRACE ("ACE_Time_Value::operator -- (void)"); + this->usec (this->usec () - 1); + this->normalize (); + return *this; +} + +#if defined (ACE_WIN32) +/// Static constant to remove time skew between FILETIME and POSIX +/// time. POSIX and Win32 use different epochs (Jan. 1, 1970 v.s. +/// Jan. 1, 1601). The following constant defines the difference +/// in 100ns ticks. +/// +/// In the beginning (Jan. 1, 1601), there was no time and no computer. +/// And Bill said: "Let there be time," and there was time.... +# if defined (ACE_LACKS_LONGLONG_T) +const ACE_U_LongLong ACE_Time_Value::FILETIME_to_timval_skew = +ACE_U_LongLong (0xd53e8000, 0x19db1de); +# else +const DWORDLONG ACE_Time_Value::FILETIME_to_timval_skew = +ACE_INT64_LITERAL (0x19db1ded53e8000); +# endif + +/// Initializes the ACE_Time_Value object from a Win32 FILETIME +ACE_Time_Value::ACE_Time_Value (const FILETIME &file_time) +{ + // // ACE_OS_TRACE ("ACE_Time_Value::ACE_Time_Value"); + this->set (file_time); +} + +void ACE_Time_Value::set (const FILETIME &file_time) +{ + // Initializes the ACE_Time_Value object from a Win32 FILETIME +#if defined (ACE_LACKS_LONGLONG_T) + ACE_U_LongLong LL_100ns(file_time.dwLowDateTime, file_time.dwHighDateTime); + LL_100ns -= ACE_Time_Value::FILETIME_to_timval_skew; + // Convert 100ns units to seconds; + this->tv_.tv_sec = (long) (LL_100ns / ((double) (10000 * 1000))); + // Convert remainder to microseconds; + this->tv_.tv_usec = (suseconds_t)((LL_100ns % ((ACE_UINT32)(10000 * 1000))) / 10); +#else + // Don't use a struct initializer, gcc don't like it. + ULARGE_INTEGER _100ns; + _100ns.LowPart = file_time.dwLowDateTime; + _100ns.HighPart = file_time.dwHighDateTime; + + _100ns.QuadPart -= ACE_Time_Value::FILETIME_to_timval_skew; + + // Convert 100ns units to seconds; + this->tv_.tv_sec = (long) (_100ns.QuadPart / (10000 * 1000)); + // Convert remainder to microseconds; + this->tv_.tv_usec = (suseconds_t) ((_100ns.QuadPart % (10000 * 1000)) / 10); +#endif // ACE_LACKS_LONGLONG_T + this->normalize (); +} + +/// Returns the value of the object as a Win32 FILETIME. +ACE_Time_Value::operator FILETIME () const +{ + FILETIME file_time; + // ACE_OS_TRACE ("ACE_Time_Value::operator FILETIME"); + +#if defined (ACE_LACKS_LONGLONG_T) + ACE_U_LongLong LL_sec(this->tv_.tv_sec); + ACE_U_LongLong LL_usec(this->tv_.tv_usec); + ACE_U_LongLong LL_100ns = LL_sec * (ACE_UINT32)(10000 * 1000) + + LL_usec * (ACE_UINT32)10 + + ACE_Time_Value::FILETIME_to_timval_skew; + file_time.dwLowDateTime = LL_100ns.lo(); + file_time.dwHighDateTime = LL_100ns.hi(); +#else + ULARGE_INTEGER _100ns; + _100ns.QuadPart = (((DWORDLONG) this->tv_.tv_sec * (10000 * 1000) + + this->tv_.tv_usec * 10) + + ACE_Time_Value::FILETIME_to_timval_skew); + + file_time.dwLowDateTime = _100ns.LowPart; + file_time.dwHighDateTime = _100ns.HighPart; +#endif //ACE_LACKS_LONGLONG_T + + return file_time; +} + +#endif /* ACE_WIN32 */ + +void +ACE_Time_Value::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + // ACE_OS_TRACE ("ACE_Time_Value::dump"); +#if 0 + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ntv_sec_ = %d"), this->tv_.tv_sec)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ntv_usec_ = %d\n"), this->tv_.tv_usec)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* 0 */ +#endif /* ACE_HAS_DUMP */ +} + +void +ACE_Time_Value::normalize (bool saturate) +{ + // // ACE_OS_TRACE ("ACE_Time_Value::normalize"); + // From Hans Rohnert... + + if (this->tv_.tv_usec >= ACE_ONE_SECOND_IN_USECS) + { + /*! \todo This loop needs some optimization. + */ + if (!saturate) // keep the conditionnal expression outside the while loop to minimize performance cost + do + { + ++this->tv_.tv_sec; + this->tv_.tv_usec -= ACE_ONE_SECOND_IN_USECS; + } + while (this->tv_.tv_usec >= ACE_ONE_SECOND_IN_USECS); + else + do + if (this->tv_.tv_sec < ACE_Numeric_Limits::max()) + { + ++this->tv_.tv_sec; + this->tv_.tv_usec -= ACE_ONE_SECOND_IN_USECS; + } + else + this->tv_.tv_usec = ACE_ONE_SECOND_IN_USECS - 1; + while (this->tv_.tv_usec >= ACE_ONE_SECOND_IN_USECS); + } + else if (this->tv_.tv_usec <= -ACE_ONE_SECOND_IN_USECS) + { + /*! \todo This loop needs some optimization. + */ + if (!saturate) + do + { + --this->tv_.tv_sec; + this->tv_.tv_usec += ACE_ONE_SECOND_IN_USECS; + } + while (this->tv_.tv_usec <= -ACE_ONE_SECOND_IN_USECS); + else + do + if (this->tv_.tv_sec > ACE_Numeric_Limits::min()) + { + --this->tv_.tv_sec; + this->tv_.tv_usec += ACE_ONE_SECOND_IN_USECS; + } + else + this->tv_.tv_usec = -ACE_ONE_SECOND_IN_USECS + 1; + while (this->tv_.tv_usec <= -ACE_ONE_SECOND_IN_USECS); + } + + if (this->tv_.tv_sec >= 1 && this->tv_.tv_usec < 0) + { + --this->tv_.tv_sec; + this->tv_.tv_usec += ACE_ONE_SECOND_IN_USECS; + } + // tv_sec in qnxnto is unsigned +#if !defined ( __QNXNTO__) + else if (this->tv_.tv_sec < 0 && this->tv_.tv_usec > 0) + { + ++this->tv_.tv_sec; + this->tv_.tv_usec -= ACE_ONE_SECOND_IN_USECS; + } +#endif /* __QNXNTO__ */ +} + + +ACE_Time_Value & +ACE_Time_Value::operator *= (double d) +{ + // To work around the lack of precision of a long double to contain + // a 64-bits time_t + 6 digits after the decimal point for the usec part, + // we perform the multiplication of the 2 timeval parts separately. + // + // This extra precision step is adding a cost when transfering the + // seconds resulting from the usec multiplication. This operation + // correspond to the normalization process performed in normalize() + // but we must absolutly do it here because the usec multiplication + // result value could exceed what can be stored in a suseconds_t + // type variable. + // + // Since this is a costly operation, we try to detect as soon as + // possible if we are having a saturation in order to abort the rest + // of the computation. + typedef ACE::If_Then_Else<(sizeof (double) > sizeof (time_t)), + double, + long double>::result_type float_type; + + float_type sec_total = static_cast (this->sec()); + sec_total *= d; + + // shall we saturate the result? + static const float_type max_int = + ACE_Numeric_Limits::max() + 0.999999; + static const float_type min_int = + ACE_Numeric_Limits::min() - 0.999999; + + if (sec_total > max_int) + { + this->set(ACE_Numeric_Limits::max(), ACE_ONE_SECOND_IN_USECS-1); + } + else if (sec_total < min_int) + { + this->set(ACE_Numeric_Limits::min(), -ACE_ONE_SECOND_IN_USECS+1); + } + else + { + time_t time_sec = static_cast (sec_total); + + float_type usec_total = this->usec(); + usec_total *= d; + + // adding usec resulting from tv_sec mult + usec_total += (sec_total-time_sec) * ACE_ONE_SECOND_IN_USECS; + + // extract seconds component of the usec mult + sec_total = usec_total / ACE_ONE_SECOND_IN_USECS; + // keep remaining usec + if (sec_total > 0) + { + usec_total = (sec_total - ACE_OS::floor(sec_total)); + } + else + { + usec_total = (sec_total - ACE_OS::ceil(sec_total)); + } + + sec_total -= usec_total; + usec_total *= ACE_ONE_SECOND_IN_USECS; + + // add the seconds component of the usec mult with the tv_sec mult prod. + sec_total += time_sec; + + // recheck for saturation + if (sec_total > max_int) + { + this->set (ACE_Numeric_Limits::max(), ACE_ONE_SECOND_IN_USECS - 1); + } + else if (sec_total < min_int) + { + this->set (ACE_Numeric_Limits::min(), -ACE_ONE_SECOND_IN_USECS + 1); + } + else + { + time_sec = static_cast (sec_total); + suseconds_t time_usec = static_cast (usec_total); + + // round up the result to save the last usec + if (time_usec > 0 && (usec_total - time_usec) >= 0.5) + { + ++time_usec; + } + else if (time_usec < 0 && (usec_total - time_usec) <= -0.5) + { + --time_usec; + } + + this->set (time_sec, time_usec); + } + } + return *this; +} + +#ifdef ACE_HAS_CPP98_IOSTREAMS +ostream &operator<<(ostream &o, const ACE_Time_Value &v) +{ + char oldFiller = o.fill (); + o.fill ('0'); + const timeval *tv = v; + if (tv->tv_sec) + { + o << tv->tv_sec; + if (tv->tv_usec) + o << '.' << std::setw (6) << ACE_STD_NAMESPACE::abs (tv->tv_usec); + } + else if (tv->tv_usec < 0) + o << "-0." << std::setw (6) << - tv->tv_usec; + else + { + o << '0'; + if (tv->tv_usec > 0) + o << '.'<< std::setw (6) << tv->tv_usec; + } + + o.fill (oldFiller); + return o; +} +#endif /* ACE_HAS_CPP98_IOSTREAMS */ + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Time_Value.h b/dep/acelite/ace/Time_Value.h new file mode 100644 index 00000000000..f92c8c7f7f5 --- /dev/null +++ b/dep/acelite/ace/Time_Value.h @@ -0,0 +1,397 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Time_Value.h + * + * $Id: Time_Value.h 90683 2010-06-17 22:07:42Z shuston $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_TIME_VALUE_H +#define ACE_TIME_VALUE_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +# include "ace/os_include/os_time.h" + +// Define some helpful constants. +// Not type-safe, and signed. For backward compatibility. +#define ACE_ONE_SECOND_IN_MSECS 1000L +suseconds_t const ACE_ONE_SECOND_IN_USECS = 1000000; +#define ACE_ONE_SECOND_IN_NSECS 1000000000L + +// needed for ACE_UINT64 +#include "ace/Basic_Types.h" + +// needed to determine if iostreams are present +#include "ace/iosfwd.h" + +// This forward declaration is needed by the set() and FILETIME() functions +#if defined (ACE_LACKS_LONGLONG_T) +ACE_BEGIN_VERSIONED_NAMESPACE_DECL +class ACE_Export ACE_U_LongLong; +ACE_END_VERSIONED_NAMESPACE_DECL +#endif /* ACE_LACKS_LONGLONG_T */ + +// ------------------------------------------------------------------- + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + + +/** + * @class ACE_Time_Value + * + * @brief Operations on "timeval" structures, which express time in + * seconds (secs) and microseconds (usecs). + * + * This class centralizes all the time related processing in + * ACE. These time values are typically used in conjunction with OS + * mechanisms like or other calls that may have + * *their own* implementation-specific maximum time representations. + * Its primary use is in time computations such as those used by the + * dynamic subpriority strategies in the ACE_Dynamic_Message_Queue + * class. + */ + static const ACE_Time_Value max_time; + + // = Initialization methods. + + /// Default Constructor. + ACE_Time_Value (void); + + /// Constructor. + explicit ACE_Time_Value (time_t sec, suseconds_t usec = 0); + + // = Methods for converting to/from various time formats. + + /// Construct the ACE_Time_Value from a timeval. + explicit ACE_Time_Value (const struct timeval &t); + + /// Construct the ACE_Time_Value object from a timespec_t. + explicit ACE_Time_Value (const timespec_t &t); + +# if defined (ACE_WIN32) + /// Construct the ACE_Time_Value object from a Win32 FILETIME + explicit ACE_Time_Value (const FILETIME &ft); +# endif /* ACE_WIN32 */ + + /// Initializes the ACE_Time_Value from seconds and useconds. + void set (time_t sec, suseconds_t usec); + + /// Initializes the ACE_Time_Value from a double, which is assumed to be + /// in second format, with any remainder treated as microseconds. + void set (double d); + + /// Initializes the ACE_Time_Value from a timeval. + void set (const timeval &t); + + /// Initializes the ACE_Time_Value object from a timespec_t. + void set (const timespec_t &t); + +# if defined (ACE_WIN32) + /// Initializes the ACE_Time_Value object from a Win32 FILETIME. + void set (const FILETIME &ft); +# endif /* ACE_WIN32 */ + + /// Converts from ACE_Time_Value format into milliseconds format. + /** + * @return Sum of second field (in milliseconds) and microsecond field + * (in milliseconds). Note that this method can overflow if + * the second and microsecond field values are large, so use + * the msec (ACE_UINT64 &ms) method instead. + * + * @note The semantics of this method differs from the sec() and + * usec() methods. There is no analogous "millisecond" + * component in an ACE_Time_Value. + */ + unsigned long msec (void) const; + + /// Converts from ACE_Time_Value format into milliseconds format. + /** + * @return Sum of second field (in milliseconds) and microsecond field + * (in milliseconds). + * + * @note The semantics of this method differs from the sec() and + * usec() methods. There is no analogous "millisecond" + * component in an ACE_Time_Value. + */ + ACE_UINT64 get_msec () const; + + /// Converts from ACE_Time_Value format into milliseconds format. + /** + * @return Sum of second field (in milliseconds) and microsecond field + * (in milliseconds) and return them via the @param ms parameter. + * + * @note The semantics of this method differs from the sec() and + * usec() methods. There is no analogous "millisecond" + * component in an ACE_Time_Value. + * + * @deprecated Use get_msec() instead. + */ + void msec (ACE_UINT64 &ms) const; + + /// Converts from ACE_Time_Value format into milliseconds format. + /** + * @return Sum of second field (in milliseconds) and microsecond field + * (in milliseconds) and return them via the @param ms parameter. + * + * @note The semantics of this method differs from the sec() and + * usec() methods. There is no analogous "millisecond" + * component in an ACE_Time_Value. + * + * @deprecated Use get_msec() instead. + */ + void msec (ACE_UINT64 &ms) /* const */; + + /// Converts from milli-seconds format into ACE_Time_Value format. + /** + * @note The semantics of this method differs from the sec() and + * usec() methods. There is no analogous "millisecond" + * component in an ACE_Time_Value. + */ + void set_msec (const ACE_UINT64 &ms); + + /// Converts from milli-seconds format into ACE_Time_Value format. + /** + * @note The semantics of this method differs from the sec() and + * usec() methods. There is no analogous "millisecond" + * component in an ACE_Time_Value. + */ + void msec (long); + + /// Converts from milli-seconds format into ACE_Time_Value format. + /** + * @note The semantics of this method differs from the sec() and + * usec() methods. There is no analogous "millisecond" + * component in an ACE_Time_Value. + */ + void msec (int); // converted to long then calls above. + + /// Returns the value of the object as a timespec_t. + operator timespec_t () const; + + /// Returns the value of the object as a timeval. + operator timeval () const; + + /// Returns a pointer to the object as a timeval. + operator const timeval *() const; + +# if defined (ACE_WIN32) + /// Returns the value of the object as a Win32 FILETIME. + operator FILETIME () const; +# endif /* ACE_WIN32 */ + + // = The following are accessor/mutator methods. + + /// Get seconds. + /** + * @return The second field/component of this ACE_Time_Value. + * + * @note The semantics of this method differs from the msec() + * method. + */ + time_t sec (void) const; + + /// Set seconds. + void sec (time_t sec); + + /// Get microseconds. + /** + * @return The microsecond field/component of this ACE_Time_Value. + * + * @note The semantics of this method differs from the msec() + * method. + */ + suseconds_t usec (void) const; + + /// Set microseconds. + void usec (suseconds_t usec); + + /** + * @return Sum of second field (in microseconds) and microsecond field + * and return them via the @param usec parameter. + */ + void to_usec (ACE_UINT64 &usec) const; + + // = The following arithmetic methods operate on ACE_Time_Value's. + + /// Add @a tv to this. + ACE_Time_Value &operator += (const ACE_Time_Value &tv); + + /// Add @a tv to this. + ACE_Time_Value &operator += (time_t tv); + + /// Assign @ tv to this + ACE_Time_Value &operator = (const ACE_Time_Value &tv); + + /// Assign @ tv to this + ACE_Time_Value &operator = (time_t tv); + + /// Subtract @a tv to this. + ACE_Time_Value &operator -= (const ACE_Time_Value &tv); + + /// Substract @a tv to this. + ACE_Time_Value &operator -= (time_t tv); + + /** + \brief Multiply the time value by the @a d factor. + \note The result of the operator is valid for results from range + < (ACE_INT32_MIN, -999999), (ACE_INT32_MAX, 999999) >. Result + outside this range are saturated to a limit. + */ + ACE_Time_Value &operator *= (double d); + + /// Increment microseconds as postfix. + /** + * @note The only reason this is here is to allow the use of ACE_Atomic_Op + * with ACE_Time_Value. + */ + ACE_Time_Value operator++ (int); + + /// Increment microseconds as prefix. + /** + * @note The only reason this is here is to allow the use of ACE_Atomic_Op + * with ACE_Time_Value. + */ + ACE_Time_Value &operator++ (void); + + /// Decrement microseconds as postfix. + /** + * @note The only reason this is here is to allow the use of ACE_Atomic_Op + * with ACE_Time_Value. + */ + ACE_Time_Value operator-- (int); + + /// Decrement microseconds as prefix. + /** + * @note The only reason this is here is to allow the use of ACE_Atomic_Op + * with ACE_Time_Value. + */ + ACE_Time_Value &operator-- (void); + + /// Adds two ACE_Time_Value objects together, returns the sum. + friend ACE_Export ACE_Time_Value operator + (const ACE_Time_Value &tv1, + const ACE_Time_Value &tv2); + + /// Subtracts two ACE_Time_Value objects, returns the difference. + friend ACE_Export ACE_Time_Value operator - (const ACE_Time_Value &tv1, + const ACE_Time_Value &tv2); + + /// True if @a tv1 < @a tv2. + friend ACE_Export bool operator < (const ACE_Time_Value &tv1, + const ACE_Time_Value &tv2); + + /// True if @a tv1 > @a tv2. + friend ACE_Export bool operator > (const ACE_Time_Value &tv1, + const ACE_Time_Value &tv2); + + /// True if @a tv1 <= @a tv2. + friend ACE_Export bool operator <= (const ACE_Time_Value &tv1, + const ACE_Time_Value &tv2); + + /// True if @a tv1 >= @a tv2. + friend ACE_Export bool operator >= (const ACE_Time_Value &tv1, + const ACE_Time_Value &tv2); + + /// True if @a tv1 == @a tv2. + friend ACE_Export bool operator == (const ACE_Time_Value &tv1, + const ACE_Time_Value &tv2); + + /// True if @a tv1 != @a tv2. + friend ACE_Export bool operator != (const ACE_Time_Value &tv1, + const ACE_Time_Value &tv2); + + //@{ + /// Multiplies the time value by @a d + friend ACE_Export ACE_Time_Value operator * (double d, + const ACE_Time_Value &tv); + + friend ACE_Export ACE_Time_Value operator * (const ACE_Time_Value &tv, + double d); + //@} + + /// Dump is a no-op. + /** + * The dump() method is a no-op. It's here for backwards compatibility + * only, but does not dump anything. Invoking logging methods here + * violates layering restrictions in ACE because this class is part + * of the OS layer and @c ACE_Log_Msg is at a higher level. + */ + void dump (void) const; + +# if defined (ACE_WIN32) + /// Const time difference between FILETIME and POSIX time. +# if defined (ACE_LACKS_LONGLONG_T) + static const ACE_U_LongLong FILETIME_to_timval_skew; +# else + static const DWORDLONG FILETIME_to_timval_skew; +# endif // ACE_LACKS_LONGLONG_T +# endif /* ACE_WIN32 */ + +private: + /// Put the timevalue into a canonical form. + void normalize (bool saturate = false); + + /// Store the values as a timeval. +#if defined (ACE_HAS_TIME_T_LONG_MISMATCH) + // Windows' timeval is non-conformant, so swap in a struct that conforms + // to the proper data types to represent the entire time range that this + // class's API can accept. + // Also, since this class can supply a pointer to a timeval that things + // like select() expect, we need the OS-defined one as well. To make this + // available, use a real timeval called ext_tv_ and set it up when needed. + // Since this is most often for relative times that don't approach 32 bits + // in size, reducing a time_t to fit should be no problem. + struct { + time_t tv_sec; + suseconds_t tv_usec; + } tv_; + timeval ext_tv_; +#else + timeval tv_; +#endif /* ACE_HAS_TIME_T_LONG_MISMATCH */ +}; + +#ifdef ACE_HAS_CPP98_IOSTREAMS +extern ACE_Export ostream &operator<<( ostream &o, const ACE_Time_Value &v ); +#endif + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Time_Value.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (__MINGW32__) +ACE_BEGIN_VERSIONED_NAMESPACE_DECL +// The MingW linker has problems with the exported statics +// zero and max_time with these two statics the linker will be able to +// resolve the static exported symbols. +static const ACE_Time_Value& __zero_time = ACE_Time_Value::zero; +static const ACE_Time_Value& __max_time = ACE_Time_Value::max_time; +ACE_END_VERSIONED_NAMESPACE_DECL +#endif /* __MINGW32__ */ + +#include /**/ "ace/post.h" + +#endif /* ACE_TIME_VALUE_H */ diff --git a/dep/acelite/ace/Time_Value.inl b/dep/acelite/ace/Time_Value.inl new file mode 100644 index 00000000000..8f7bf23d837 --- /dev/null +++ b/dep/acelite/ace/Time_Value.inl @@ -0,0 +1,418 @@ +// -*- C++ -*- +// +// $Id: Time_Value.inl 90689 2010-06-18 11:14:47Z shuston $ + +#include "ace/Truncate.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/// Returns the value of the object as a timeval. +ACE_INLINE +ACE_Time_Value::operator timeval () const +{ + // ACE_OS_TRACE ("ACE_Time_Value::operator timeval"); +#if defined (ACE_HAS_TIME_T_LONG_MISMATCH) + // Recall that on some Windows we substitute another type for timeval in tv_ + ACE_Time_Value *me = const_cast (this); + me->ext_tv_.tv_sec = ACE_Utils::truncate_cast (this->tv_.tv_sec); + me->ext_tv_.tv_usec = ACE_Utils::truncate_cast (this->tv_.tv_usec); + return this->ext_tv_; +#else + return this->tv_; +#endif /* ACE_HAS_TIME_T_LONG_MISMATCH */ +} + +ACE_INLINE void +ACE_Time_Value::set (const timeval &tv) +{ + // ACE_OS_TRACE ("ACE_Time_Value::set"); + this->tv_.tv_sec = tv.tv_sec; + this->tv_.tv_usec = tv.tv_usec; + + this->normalize (); +} + +ACE_INLINE +ACE_Time_Value::ACE_Time_Value (const struct timeval &tv) +{ + // ACE_OS_TRACE ("ACE_Time_Value::ACE_Time_Value"); + this->set (tv); +} + +ACE_INLINE +ACE_Time_Value::operator const timeval * () const +{ + // ACE_OS_TRACE ("ACE_Time_Value::operator const timeval *"); +#if defined (ACE_HAS_TIME_T_LONG_MISMATCH) + // Recall that on some Windows we substitute another type for timeval in tv_ + ACE_Time_Value *me = const_cast (this); + me->ext_tv_.tv_sec = ACE_Utils::truncate_cast (this->tv_.tv_sec); + me->ext_tv_.tv_usec = ACE_Utils::truncate_cast (this->tv_.tv_usec); + return (const timeval *) &this->ext_tv_; +#else + return (const timeval *) &this->tv_; +#endif /* ACE_HAS_TIME_T_LONG_MISMATCH */ +} + +ACE_INLINE void +ACE_Time_Value::set (time_t sec, suseconds_t usec) +{ + // ACE_OS_TRACE ("ACE_Time_Value::set"); +# if defined (_WIN32_WCE) && (_WIN32_WCE == 0x600) && !defined (_USE_32BIT_TIME_T) && defined (_MSC_VER) + // The WinCE 6.0 SDK ships with a timeval tv_sec member that uses long as type + // not time_t. This resolves in compilation warnings because time_t + // can be 64bit. Disable at this momemt the warning for just this method + // else we get a compile warnings each time this inline file is included + // this file. +# pragma warning (push) +# pragma warning (disable: 4244) +# endif + this->tv_.tv_sec = sec; +# if defined (_WIN32_WCE) && (_WIN32_WCE == 0x600) && !defined (_USE_32BIT_TIME_T) && defined (_MSC_VER) +# pragma warning (pop) +# endif + this->tv_.tv_usec = usec; +#if __GNUC__ + if (__builtin_constant_p(sec) && + __builtin_constant_p(usec) && + (sec >= 0 && usec >= 0 && usec < ACE_ONE_SECOND_IN_USECS)) + return; +#endif + this->normalize (); +} + +ACE_INLINE void +ACE_Time_Value::set (double d) +{ + // ACE_OS_TRACE ("ACE_Time_Value::set"); + long l = (long) d; + this->tv_.tv_sec = l; + this->tv_.tv_usec = (suseconds_t) ((d - (double) l) * ACE_ONE_SECOND_IN_USECS + .5); + this->normalize (); +} + +/// Initializes a timespec_t. Note that this approach loses precision +/// since it converts the nano-seconds into micro-seconds. But then +/// again, do any real systems have nano-second timer precision?! +ACE_INLINE void +ACE_Time_Value::set (const timespec_t &tv) +{ + // ACE_OS_TRACE ("ACE_Time_Value::set"); + + this->set (tv.tv_sec, + tv.tv_nsec / 1000); // Convert nanoseconds into microseconds. +} + +ACE_INLINE +ACE_Time_Value::ACE_Time_Value (void) + // : tv_ () +{ + // ACE_OS_TRACE ("ACE_Time_Value::ACE_Time_Value"); + this->set (0, 0); +} + +ACE_INLINE +ACE_Time_Value::ACE_Time_Value (time_t sec, suseconds_t usec) +{ + // ACE_OS_TRACE ("ACE_Time_Value::ACE_Time_Value"); + this->set (sec, usec); +} + +/// Returns number of seconds. +ACE_INLINE time_t +ACE_Time_Value::sec (void) const +{ + // ACE_OS_TRACE ("ACE_Time_Value::sec"); + return this->tv_.tv_sec; +} + +/// Sets the number of seconds. +ACE_INLINE void +ACE_Time_Value::sec (time_t sec) +{ + // ACE_OS_TRACE ("ACE_Time_Value::sec"); + this->tv_.tv_sec = ACE_Utils::truncate_cast (sec); +} + +/// Converts from Time_Value format into milli-seconds format. +ACE_INLINE unsigned long +ACE_Time_Value::msec (void) const +{ + // ACE_OS_TRACE ("ACE_Time_Value::msec"); + + // Note - we're truncating a value here, which can lose data. This is + // called out in the user documentation for this with a recommendation to + // use msec(ACE_UINT64&) instead, so just go ahead and truncate. + time_t secs = this->tv_.tv_sec * 1000 + this->tv_.tv_usec / 1000; + return ACE_Utils::truncate_cast (secs); +} + +ACE_INLINE ACE_UINT64 +ACE_Time_Value::get_msec () const +{ + // ACE_OS_TRACE ("ACE_Time_Value::get_msec"); + ACE_UINT64 ms = ACE_Utils::truncate_cast (this->tv_.tv_sec); + ms *= 1000; + ms += (this->tv_.tv_usec / 1000); + return ms; +} + +ACE_INLINE void +ACE_Time_Value::msec (ACE_UINT64 &ms) const +{ + // ACE_OS_TRACE ("ACE_Time_Value::msec"); + ms = this->get_msec (); +} + +ACE_INLINE void +ACE_Time_Value::msec (ACE_UINT64 &ms) /*const*/ +{ + // ACE_OS_TRACE ("ACE_Time_Value::msec"); + const ACE_Time_Value *tv = this; + tv->msec (ms); +} + +ACE_INLINE void +ACE_Time_Value::set_msec (const ACE_UINT64 &ms) +{ + // ACE_OS_TRACE ("ACE_Time_Value::set_msec"); + // Convert millisecond units to seconds; + ACE_UINT64 secs = ms / 1000; + this->tv_.tv_sec = static_cast (secs); + // Convert remainder to microseconds; + this->tv_.tv_usec = static_cast((ms - (secs * 1000)) * 1000); +} + +/// Converts from milli-seconds format into Time_Value format. +ACE_INLINE void +ACE_Time_Value::msec (long milliseconds) +{ + // ACE_OS_TRACE ("ACE_Time_Value::msec"); + // Convert millisecond units to seconds; + long secs = milliseconds / 1000; + this->tv_.tv_sec = secs; + // Convert remainder to microseconds; + this->tv_.tv_usec = (milliseconds - (secs * 1000)) * 1000; +} + +/// Converts from milli-seconds format into Time_Value format. +ACE_INLINE void +ACE_Time_Value::msec (int milliseconds) +{ + ACE_Time_Value::msec (static_cast (milliseconds)); +} + +/// Returns number of micro-seconds. +ACE_INLINE suseconds_t +ACE_Time_Value::usec (void) const +{ + // ACE_OS_TRACE ("ACE_Time_Value::usec"); + return this->tv_.tv_usec; +} + +/// Sets the number of micro-seconds. +ACE_INLINE void +ACE_Time_Value::usec (suseconds_t usec) +{ + // ACE_OS_TRACE ("ACE_Time_Value::usec"); + this->tv_.tv_usec = usec; +} + +ACE_INLINE void +ACE_Time_Value::to_usec (ACE_UINT64 & usec) const +{ + // ACE_OS_TRACE ("ACE_Time_Value::to_usec"); + +#if defined (ACE_LACKS_UNSIGNEDLONGLONG_T) + usec = ACE_U_LongLong (static_cast (this->tv_.tv_sec)); +#elif defined (ACE_LACKS_LONGLONG_T) + // No native 64-bit type, meaning time_t is most likely 32 bits. + usec = ACE_U_LongLong (this->tv_.tv_sec); +#else + usec = static_cast (this->tv_.tv_sec); +#endif /* ACE_LACKS_LONGLONG_T */ + usec *= 1000000; + usec += this->tv_.tv_usec; +} + +ACE_INLINE ACE_Time_Value +operator * (double d, const ACE_Time_Value &tv) +{ + return ACE_Time_Value (tv) *= d; +} + +ACE_INLINE ACE_Time_Value +operator * (const ACE_Time_Value &tv, double d) +{ + return ACE_Time_Value (tv) *= d; +} + +/// True if tv1 > tv2. +ACE_INLINE bool +operator > (const ACE_Time_Value &tv1, + const ACE_Time_Value &tv2) +{ + // ACE_OS_TRACE ("operator >"); + if (tv1.sec () > tv2.sec ()) + return 1; + else if (tv1.sec () == tv2.sec () + && tv1.usec () > tv2.usec ()) + return 1; + else + return 0; +} + +/// True if tv1 >= tv2. +ACE_INLINE bool +operator >= (const ACE_Time_Value &tv1, + const ACE_Time_Value &tv2) +{ + // ACE_OS_TRACE ("operator >="); + if (tv1.sec () > tv2.sec ()) + return 1; + else if (tv1.sec () == tv2.sec () + && tv1.usec () >= tv2.usec ()) + return 1; + else + return 0; +} + +/// Returns the value of the object as a timespec_t. +ACE_INLINE +ACE_Time_Value::operator timespec_t () const +{ + // ACE_OS_TRACE ("ACE_Time_Value::operator timespec_t"); + timespec_t tv; + tv.tv_sec = this->sec (); + // Convert microseconds into nanoseconds. + tv.tv_nsec = this->tv_.tv_usec * 1000; + return tv; +} + +/// Initializes the ACE_Time_Value object from a timespec_t. +ACE_INLINE +ACE_Time_Value::ACE_Time_Value (const timespec_t &tv) + // : tv_ () +{ + // ACE_OS_TRACE ("ACE_Time_Value::ACE_Time_Value"); + this->set (tv); +} + +/// True if tv1 < tv2. +ACE_INLINE bool +operator < (const ACE_Time_Value &tv1, + const ACE_Time_Value &tv2) +{ + // ACE_OS_TRACE ("operator <"); + return tv2 > tv1; +} + +/// True if tv1 >= tv2. +ACE_INLINE bool +operator <= (const ACE_Time_Value &tv1, + const ACE_Time_Value &tv2) +{ + // ACE_OS_TRACE ("operator <="); + return tv2 >= tv1; +} + +/// True if tv1 == tv2. +ACE_INLINE bool +operator == (const ACE_Time_Value &tv1, + const ACE_Time_Value &tv2) +{ + // ACE_OS_TRACE ("operator =="); + return tv1.sec () == tv2.sec () + && tv1.usec () == tv2.usec (); +} + +/// True if tv1 != tv2. +ACE_INLINE bool +operator != (const ACE_Time_Value &tv1, + const ACE_Time_Value &tv2) +{ + // ACE_OS_TRACE ("operator !="); + return !(tv1 == tv2); +} + +/// Add TV to this. +ACE_INLINE ACE_Time_Value & +ACE_Time_Value::operator+= (const ACE_Time_Value &tv) +{ + // ACE_OS_TRACE ("ACE_Time_Value::operator+="); + this->sec (this->sec () + tv.sec ()); + this->usec (this->usec () + tv.usec ()); + this->normalize (); + return *this; +} + +ACE_INLINE ACE_Time_Value & +ACE_Time_Value::operator+= (time_t tv) +{ + // ACE_OS_TRACE ("ACE_Time_Value::operator+="); + this->sec (this->sec () + tv); + return *this; +} + +ACE_INLINE ACE_Time_Value & +ACE_Time_Value::operator= (const ACE_Time_Value &tv) +{ + // ACE_OS_TRACE ("ACE_Time_Value::operator="); + this->sec (tv.sec ()); + this->usec (tv.usec ()); + return *this; +} + +ACE_INLINE ACE_Time_Value & +ACE_Time_Value::operator= (time_t tv) +{ + // ACE_OS_TRACE ("ACE_Time_Value::operator="); + this->sec (tv); + this->usec (0); + return *this; +} + +/// Subtract TV to this. +ACE_INLINE ACE_Time_Value & +ACE_Time_Value::operator-= (const ACE_Time_Value &tv) +{ + // ACE_OS_TRACE ("ACE_Time_Value::operator-="); + this->sec (this->sec () - tv.sec ()); + this->usec (this->usec () - tv.usec ()); + this->normalize (); + return *this; +} + +ACE_INLINE ACE_Time_Value & +ACE_Time_Value::operator-= (time_t tv) +{ + // ACE_OS_TRACE ("ACE_Time_Value::operator-="); + this->sec (this->sec () - tv); + return *this; +} + +/// Adds two ACE_Time_Value objects together, returns the sum. +ACE_INLINE ACE_Time_Value +operator + (const ACE_Time_Value &tv1, + const ACE_Time_Value &tv2) +{ + // ACE_OS_TRACE ("operator +"); + ACE_Time_Value sum (tv1); + sum += tv2; + + return sum; +} + +/// Subtracts two ACE_Time_Value objects, returns the difference. +ACE_INLINE ACE_Time_Value +operator - (const ACE_Time_Value &tv1, + const ACE_Time_Value &tv2) +{ + // ACE_OS_TRACE ("operator -"); + ACE_Time_Value delta (tv1); + delta -= tv2; + + return delta; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Timeprobe.cpp b/dep/acelite/ace/Timeprobe.cpp new file mode 100644 index 00000000000..1fe8459ed8d --- /dev/null +++ b/dep/acelite/ace/Timeprobe.cpp @@ -0,0 +1,15 @@ +// $Id: Timeprobe.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/config-all.h" + +ACE_RCSID(ace, Timeprobe, "$Id: Timeprobe.cpp 80826 2008-03-04 14:51:23Z wotte $") + +#if defined (ACE_COMPILE_TIMEPROBES) + +#include "ace/Timeprobe.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Timeprobe.inl" +#endif /* __ACE_INLINE__ */ + +#endif /* ACE_COMPILE_TIMEPROBES */ diff --git a/dep/acelite/ace/Timeprobe.h b/dep/acelite/ace/Timeprobe.h new file mode 100644 index 00000000000..ac2abe38d0e --- /dev/null +++ b/dep/acelite/ace/Timeprobe.h @@ -0,0 +1,201 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Timeprobe.h + * + * $Id: Timeprobe.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Irfan Pyarali + * + * If users want to use time probes, the ACE_COMPILE_TIMEPROBES + * flag must be defined when compiling ACE. This can be achieved + * by doing one of the following: + * + * . Use make probe = 1, if you are using the make utility. + * + * . Define ACE_COMPILE_TIMEPROBES in config.h + * + * . Define ACE_COMPILE_TIMEPROBES in the VC project file. + * + * . Other regular methods will also work. + * + * It is not necessary to define ACE_COMPILE_TIMEPROBES when using + * time probes, you simply need ACE_ENABLE_TIMEPROBES. You can use + * the ACE_TIMEPROBE_* macros to program the time probes, and use + * the ACE_ENABLE_TIMEPROBE to enable the time probes. If you + * define ACE_ENABLE_TIMEPROBE in your code, but forget to compile + * ACE with ACE_COMPILE_TIMEPROBES, you will end up with linker + * errors. + * + * Remember that ACE_COMPILE_TIMEPROBES means that the ACE library + * will contain code for time probes. This is only useful when + * compiling ACE. ACE_ENABLE_TIMEPROBES means that the + * ACE_TIMEPROBE_* macros should spring to life. + */ +//============================================================================= + +#ifndef ACE_TIMEPROBE_H +#define ACE_TIMEPROBE_H +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" +#include /**/ "ace/ACE_export.h" +#include "ace/Malloc_Allocator.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +/* Enable ACE Timeprobes */ +#if defined (ACE_ENABLE_TIMEPROBES) + #if !defined (ACE_COMPILE_TIMEPROBES) + #define ACE_COMPILE_TIMEPROBES + #endif /* ACE_COMPILE_TIMEPROBES */ +#endif /* ACE_ENABLE_TIMEPROBES */ + +#if defined (ACE_COMPILE_TIMEPROBES) + +#include "ace/OS_NS_time.h" +#include "ace/OS_NS_Thread.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Event_Descriptions + * + * @brief Event Descriptions. + */ +class ACE_Export ACE_Event_Descriptions +{ +public: + /// Event descriptions + const char **descriptions_; + + /// Minimum id of this description set + u_long minimum_id_; + + /// Comparison + bool operator== (const ACE_Event_Descriptions &rhs) const; +}; + +/** + * @class ACE_timeprobe_t + * + * @brief Time probe record. + */ +class ACE_Export ACE_timeprobe_t +{ +public: + /// Events are record as strings or numbers. + union event + { + u_long event_number_; + const char *event_description_; + }; + + /// Type of event. + enum event_type + { + NUMBER, + STRING + }; + + /// Event. + event event_; + + /// Type of event. + event_type event_type_; + + /// Timestamp. + ACE_hrtime_t time_; + + /// Id of thread posting the time probe. + ACE_thread_t thread_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Timeprobe.inl" +#endif /* __ACE_INLINE__ */ + +#include "ace/Synch_Traits.h" +#include "ace/Null_Mutex.h" +#include "ace/Singleton.h" +#include "ace/Timeprobe_T.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// If ACE_MT_TIMEPROBES is defined, use a Thread_Mutex to lock the +// internal state of ACE_Timerprobe. This allows multiple threads to +// use the same ACE_Timerprobe. +# if defined (ACE_MT_TIMEPROBES) +typedef ACE_SYNCH_MUTEX ACE_TIMEPROBE_MUTEX; +# else /* ACE_MT_TIMEPROBES */ +typedef ACE_SYNCH_NULL_MUTEX ACE_TIMEPROBE_MUTEX; +# endif /* ACE_MT_TIMEPROBES */ + +typedef ACE_New_Allocator ACE_TIMEPROBE_ALLOCATOR; + +typedef ACE_Timeprobe_Ex + ACE_TIMEPROBE_WITH_LOCKING; + +// If ACE_TSS_TIMEPROBES is defined, store the ACE_Timeprobe singleton +// in thread specific storage. This allows multiple threads to use +// their own instance of ACE_Timerprobe, without interfering with each +// other. + +# if defined (ACE_TSS_TIMEPROBES) +# define ACE_TIMEPROBE_SINGLETON_TYPE ACE_TSS_Singleton +# define ACE_TIMEPROBE_SINGLETON_LOCK_TYPE ACE_SYNCH_NULL_MUTEX +# else /* ACE_TSS_TIMEPROBES */ +# define ACE_TIMEPROBE_SINGLETON_TYPE ACE_Singleton +# define ACE_TIMEPROBE_SINGLETON_LOCK_TYPE ACE_SYNCH_MUTEX +# endif /* ACE_TSS_TIMEPROBES */ + +ACE_SINGLETON_DECLARE (ACE_TIMEPROBE_SINGLETON_TYPE, \ + ACE_TIMEPROBE_WITH_LOCKING, \ + ACE_TIMEPROBE_SINGLETON_LOCK_TYPE) + +typedef ACE_TIMEPROBE_SINGLETON_TYPE + ACE_TIMEPROBE_SINGLETON; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_COMPILE_TIMEPROBES */ + +// If ACE_ENABLE_TIMEPROBES is defined, the macros below will +// work. Otherwise, they just vanish. Using this macro, you can +// control which files/libraries are probed. +#if defined (ACE_ENABLE_TIMEPROBES) && defined (ACE_COMPILE_TIMEPROBES) + +# define ACE_TIMEPROBE_RESET ACE_TIMEPROBE_SINGLETON::instance ()->reset () + +# define ACE_TIMEPROBE(id) ACE_TIMEPROBE_SINGLETON::instance ()->timeprobe (id) + +# define ACE_TIMEPROBE_PRINT ACE_TIMEPROBE_SINGLETON::instance ()->print_times () + +# define ACE_TIMEPROBE_PRINT_ABSOLUTE ACE_TIMEPROBE_SINGLETON::instance ()->print_absolute_times () + +# define ACE_TIMEPROBE_EVENT_DESCRIPTIONS(descriptions, minimum_id) \ +static int ace_timeprobe_##descriptions##_return = \ + ACE_TIMEPROBE_SINGLETON::instance ()->event_descriptions \ + (descriptions, minimum_id) + +# define ACE_FUNCTION_TIMEPROBE(X) \ + ACE_Function_Timeprobe function_timeprobe \ + (*ACE_TIMEPROBE_SINGLETON::instance (), X) + +#else /* ACE_ENABLE_TIMEPROBES && ACE_COMPILE_TIMEPROBES */ + +# define ACE_TIMEPROBE_RESET +# define ACE_TIMEPROBE(id) +# define ACE_TIMEPROBE_PRINT +# define ACE_TIMEPROBE_PRINT_ABSOLUTE +# define ACE_TIMEPROBE_EVENT_DESCRIPTIONS(descriptions, minimum_id) +# define ACE_FUNCTION_TIMEPROBE(X) + +#endif /* ACE_ENABLE_TIMEPROBES && ACE_COMPILE_TIMEPROBES */ +#include /**/ "ace/post.h" +#endif /* ACE_TIMEPROBE_H */ diff --git a/dep/acelite/ace/Timeprobe.inl b/dep/acelite/ace/Timeprobe.inl new file mode 100644 index 00000000000..aa7a9240648 --- /dev/null +++ b/dep/acelite/ace/Timeprobe.inl @@ -0,0 +1,14 @@ +// -*- C++ -*- +// +// $Id: Timeprobe.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE bool +ACE_Event_Descriptions::operator== (const ACE_Event_Descriptions &rhs) const +{ + return this->minimum_id_ == rhs.minimum_id_ && + this->descriptions_ == rhs.descriptions_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Timeprobe_T.cpp b/dep/acelite/ace/Timeprobe_T.cpp new file mode 100644 index 00000000000..d23b7b8b869 --- /dev/null +++ b/dep/acelite/ace/Timeprobe_T.cpp @@ -0,0 +1,427 @@ +// $Id: Timeprobe_T.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#ifndef ACE_TIMEPROBE_T_CPP +#define ACE_TIMEPROBE_T_CPP + +#include "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_COMPILE_TIMEPROBES) + +#include "ace/Timeprobe.h" +#include "ace/High_Res_Timer.h" +#include "ace/OS_NS_string.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template +ACE_Timeprobe_Ex::ACE_Timeprobe_Ex (u_long size) + : timeprobes_ (0), + lock_ (), + max_size_ (size), + current_size_ (0), + report_buffer_full_ (0), + allocator_ (0) +{ + ACE_timeprobe_t *temp; + //FUZZ: disable check_for_lack_ACE_OS + ACE_NEW_MALLOC_ARRAY (temp, + (ACE_timeprobe_t *) this->allocator ()-> + malloc (this->max_size_*sizeof(ACE_timeprobe_t)), + ACE_timeprobe_t, + this->max_size_); + //FUZZ: enable check_for_lack_ACE_OS + this->timeprobes_ = temp; + +} + +template +ACE_Timeprobe_Ex:: +ACE_Timeprobe_Ex (ALLOCATOR *allocator, + u_long size) + : timeprobes_ (0), + lock_ (), + max_size_ (size), + current_size_ (0), + report_buffer_full_ (0), + allocator_ (allocator) +{ + ACE_timeprobe_t *temp = 0; + //FUZZ: disable check_for_lack_ACE_OS + ACE_NEW_MALLOC_ARRAY (temp, + (ACE_timeprobe_t *) this->allocator ()-> + malloc (this->max_size_*sizeof(ACE_timeprobe_t)), + ACE_timeprobe_t, + this->max_size_); + //FUZZ: enable check_for_lack_ACE_OS + this->timeprobes_ = temp; + +} + +template +ACE_Timeprobe_Ex::ACE_Timeprobe_Ex (const ACE_Timeprobe_Ex &) +{ + // + // Stupid MSVC is forcing me to define this; please don't use it. + // + + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("ACE_NOTSUP: %N, line %l\n"))); + errno = ENOTSUP; +} + +template +ACE_Timeprobe_Ex::~ACE_Timeprobe_Ex (void) +{ + ACE_DES_ARRAY_FREE ((ACE_timeprobe_t *) (this->timeprobes_), + this->max_size_, + this->allocator ()->free, + ACE_timeprobe_t); +} + +template void +ACE_Timeprobe_Ex::timeprobe (u_long event) +{ + ACE_GUARD (ACE_LOCK, ace_mon, this->lock_); + + this->timeprobes_[this->current_size_].event_.event_number_ = event; + this->timeprobes_[this->current_size_].event_type_ = ACE_timeprobe_t::NUMBER; + this->timeprobes_[this->current_size_].time_ = ACE_OS::gethrtime (); + this->timeprobes_[this->current_size_].thread_ = ACE_OS::thr_self (); + + ++this->current_size_; + +#if !defined (ACE_TIMEPROBE_ASSERTS_FIXED_SIZE) + // wrap around to the beginning on overflow + if (this->current_size_ >= this->max_size_) + { + this->current_size_ = 0; + this->report_buffer_full_ = 1; + } +#endif /* ACE_TIMEPROBE_ASSERTS_FIXED_SIZE */ + + ACE_ASSERT (this->current_size_ < this->max_size_); +} + +template void +ACE_Timeprobe_Ex::timeprobe (const char *event) +{ + ACE_GUARD (ACE_LOCK, ace_mon, this->lock_); + + this->timeprobes_[this->current_size_].event_.event_description_ = event; + this->timeprobes_[this->current_size_].event_type_ = ACE_timeprobe_t::STRING; + this->timeprobes_[this->current_size_].time_ = ACE_OS::gethrtime (); + this->timeprobes_[this->current_size_].thread_ = ACE_OS::thr_self (); + + ++this->current_size_; + +#if !defined (ACE_TIMEPROBE_ASSERTS_FIXED_SIZE) + // wrap around to the beginning on overflow + if (this->current_size_ >= this->max_size_) + { + this->current_size_ = 0; + this->report_buffer_full_ = 1; + } +#endif /* ACE_TIMEPROBE_ASSERTS_FIXED_SIZE */ + + ACE_ASSERT (this->current_size_ < this->max_size_); +} + +template void +ACE_Timeprobe_Ex::reset (void) +{ + ACE_GUARD (ACE_LOCK, ace_mon, this->lock_); + + this->current_size_ = 0; + this->report_buffer_full_ = 0; +} + +template void +ACE_Timeprobe_Ex::increase_size (u_long size) +{ + ACE_GUARD (ACE_LOCK, ace_mon, this->lock_); + + if (size > this->max_size_) + { + ACE_timeprobe_t *temp = 0; + //FUZZ: disable check_for_lack_ACE_OS + ACE_NEW_MALLOC_ARRAY (temp, + (ACE_timeprobe_t *) this->allocator ()-> + malloc (this->max_size_ + * sizeof (ACE_timeprobe_t)), + ACE_timeprobe_t, + size); + //FUZZ: enable check_for_lack_ACE_OS + + if (this->max_size_ > 0) + { + ACE_OS::memcpy (temp, + this->timeprobes_, + this->max_size_ * sizeof (ACE_timeprobe_t)); + + // Iterates over the array explicitly calling the destructor for + // each probe instance, then deallocates the memory + + ACE_DES_ARRAY_FREE ((ACE_timeprobe_t *)(this->timeprobes_), + this->max_size_, + this->allocator ()->free, + ACE_timeprobe_t); + } + this->timeprobes_ = temp; + this->max_size_ = size; + } +} + +template ACE_Unbounded_Set & +ACE_Timeprobe_Ex::event_descriptions (void) +{ + return this->event_descriptions_; +} + +template ACE_Unbounded_Set & +ACE_Timeprobe_Ex::sorted_event_descriptions (void) +{ + return this->sorted_event_descriptions_; +} + +template ACE_timeprobe_t * +ACE_Timeprobe_Ex::timeprobes (void) +{ + return this->timeprobes_; +} + +template ACE_LOCK & +ACE_Timeprobe_Ex::lock (void) +{ + return this->lock_; +} + +template u_long +ACE_Timeprobe_Ex::max_size (void) +{ + return this->max_size_; +} + +template u_long +ACE_Timeprobe_Ex::current_size (void) +{ + return this->current_size_; +} + +template int +ACE_Timeprobe_Ex::event_descriptions (const char **descriptions, + u_long minimum_id) +{ + ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->lock_, -1); + + ACE_Event_Descriptions events; + events.descriptions_ = descriptions; + events.minimum_id_ = minimum_id; + + this->event_descriptions_.insert (events); + + return 0; +} + +template void +ACE_Timeprobe_Ex::print_times (void) +{ + ACE_GUARD (ACE_LOCK, ace_mon, this->lock_); + + // Sort the event descriptions + this->sort_event_descriptions_i (); + + u_long size = this->report_buffer_full_ ? this->max_size_ + : this->current_size_; + + ACE_DEBUG ((LM_DEBUG, + "\nACE_Timeprobe_Ex; %u timestamps were recorded:\n", + size)); + + if (size == 0) + return; + + ACE_DEBUG ((LM_DEBUG, + "\n%-50.50s %8.8s %13.13s\n\n", + "Event", + "thread", + "usec")); + + double gsf = ACE_High_Res_Timer::global_scale_factor (); + u_long i, j; + + // First element + i = this->report_buffer_full_ ? this->current_size_ : 0; + + ACE_DEBUG ((LM_DEBUG, + "%-50.50s %8.8x %13.13s\n", + this->find_description_i (i), + this->timeprobes_[i].thread_, + "START")); + + if (size == 1) + return; + + bool has_timestamp_inversion = false; + + j = i; + i = (i + 1) % this->max_size_; + + do + { + // When reusing the same ACE_Timeprobe from multiple threads + // with Linux on Intel SMP, it sometimes happens that the + // recorded times go backward in time if they are recorded from + // different threads (see bugzilla #2342). To obtain the + // correct signed difference between consecutive recorded times, + // one has to cast the time difference to an intermediate signed + // integral type of the same size as ACE_hrtime_t. + + double time_difference = + (ACE_INT64) (this->timeprobes_[i].time_ - this->timeprobes_[j].time_); + + if (time_difference < 0) + has_timestamp_inversion = true; + + // Convert to microseconds. + time_difference /= gsf; + + ACE_DEBUG ((LM_DEBUG, + "%-50.50s %8.8x %14.3f\n", + this->find_description_i (i), + this->timeprobes_[i].thread_, + time_difference)); + + j = i; + i = (i + 1) % this->max_size_; + } + while (i != this->current_size_); + + static bool inversion_warning_printed = false; + if (!inversion_warning_printed && has_timestamp_inversion) + { + inversion_warning_printed = true; + ACE_DEBUG ((LM_DEBUG, + "\nWARNING: The timestamps recorded by gethrtime() on" + " this platform are\n" + "not monotonic across different threads.\n")); + } +} + +template void +ACE_Timeprobe_Ex::print_absolute_times (void) +{ + ACE_GUARD (ACE_LOCK, ace_mon, this->lock_); + + // Sort the event descriptions + this->sort_event_descriptions_i (); + + u_long size = this->report_buffer_full_ ? this->max_size_ + : this->current_size_; + + ACE_DEBUG ((LM_DEBUG, + "\nACE_Timeprobe_Ex; %u timestamps were recorded:\n", + size)); + + if (size == 0) + return; + + ACE_DEBUG ((LM_DEBUG, + "\n%-50.50s %8.8s %13.13s\n\n", + "Event", + "thread", + "stamp")); + + u_long i = this->report_buffer_full_ ? this->current_size_ : 0; + + ACE_Time_Value tv; // to convert ACE_hrtime_t + do + { + ACE_High_Res_Timer::hrtime_to_tv (tv, this->timeprobes_ [i].time_); + + ACE_DEBUG ((LM_DEBUG, + "%-50.50s %8.8x %12.12u\n", + this->find_description_i (i), + this->timeprobes_ [i].thread_, + tv.sec () * 1000000 + + tv.usec ())); + + // Modulus increment: loops around at the end. + i = (i + 1) % this->max_size_; + } + while (i != this->current_size_); +} + +template const char * +ACE_Timeprobe_Ex::find_description_i (u_long i) +{ + if (this->timeprobes_[i].event_type_ == ACE_timeprobe_t::STRING) + return this->timeprobes_[i].event_.event_description_; + else + { + EVENT_DESCRIPTIONS::iterator iterator = this->sorted_event_descriptions_.begin (); + for (u_long j = 0; + j < this->sorted_event_descriptions_.size () - 1; + iterator++, j++) + { + EVENT_DESCRIPTIONS::iterator next_event_descriptions = iterator; + ++next_event_descriptions; + + if (this->timeprobes_[i].event_.event_number_ < (*next_event_descriptions).minimum_id_) + break; + } + return (*iterator).descriptions_[this->timeprobes_[i].event_.event_number_ - (*iterator).minimum_id_]; + } +} + +template void +ACE_Timeprobe_Ex::sort_event_descriptions_i (void) +{ + size_t total_elements = this->event_descriptions_.size (); + + for (size_t i = 0; + i < total_elements; + i++) + { + EVENT_DESCRIPTIONS::iterator iterator = this->event_descriptions_.begin (); + ACE_Event_Descriptions min_entry = *iterator; + + for (; + iterator != this->event_descriptions_.end (); + iterator++) + if ((*iterator).minimum_id_ < min_entry.minimum_id_) + min_entry = *iterator; + + this->sorted_event_descriptions_.insert (min_entry); + this->event_descriptions_.remove (min_entry); + } +} + +template ALLOCATOR * +ACE_Timeprobe_Ex::allocator (void) +{ + return allocator_ ? allocator_ : ACE_Singleton::instance (); +} + +template +ACE_Function_Timeprobe::ACE_Function_Timeprobe (Timeprobe &timeprobe, + u_long event) + : timeprobe_ (timeprobe), + event_ (event) +{ + this->timeprobe_.timeprobe (this->event_); +} + +template +ACE_Function_Timeprobe::~ACE_Function_Timeprobe (void) +{ + this->timeprobe_.timeprobe (this->event_ + 1); +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_COMPILE_TIMEPROBES */ +#endif /* ACE_TIMEPROBE_T_CPP */ diff --git a/dep/acelite/ace/Timeprobe_T.h b/dep/acelite/ace/Timeprobe_T.h new file mode 100644 index 00000000000..54e5ff4c185 --- /dev/null +++ b/dep/acelite/ace/Timeprobe_T.h @@ -0,0 +1,220 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Timeprobe_T.h + * + * $Id: Timeprobe_T.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Irfan Pyarali + */ +//============================================================================= + + +#ifndef ACE_TIMEPROBE_T_H +#define ACE_TIMEPROBE_T_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_COMPILE_TIMEPROBES) + +#include "ace/Unbounded_Set.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Timeprobe_Ex + * + * @brief This class is used to instrument code. This is accomplished + * by inserting time probes at different location in the code. + * ACE_Timeprobe then measures the time difference between two + * time probes. + * + * This class provides a lightweight implementation for + * measuring the time required to execute code between two time + * probes. When a time probe executes, it records the time, the + * id of the calling thread, and an event description. The + * event description can either be an unsigned long or a string + * (char *). If string are used, care must be taken cause only + * pointer copies are done and the string data is *not* copied. + * The recorded time probes can then be printed by calling + * . If you have used unsigned longs as event + * descriptions in any of your time probes, you must have + * provided an event description table that maps the unsigned + * longs to readable strings. This map is a simple array of + * strings, and the event number is used as the index into the + * array when looking for the event description. If you have + * only used strings for the event description, this map is not + * necessary. + * Multiple maps can also be used to chunk up the time probes. + * Each one can be added by calling . + * Different tables are used internally by consulting the + * minimum_id for each table. It is up to the user to make sure + * that multiple tables do not share the same event id range. + */ +template +class ACE_Timeprobe_Ex +{ +public: + + /// Self + typedef ACE_Timeprobe_Ex + SELF; + + /** + * ACE_Timeprobe + */ + typedef ACE_Timeprobe_Ex ACE_Timeprobe; + + + /// We can hold multiple event description tables. + typedef ACE_Unbounded_Set + EVENT_DESCRIPTIONS; + + /// Create Timeprobes with @a size slots + ACE_Timeprobe_Ex (u_long size = ACE_DEFAULT_TIMEPROBE_TABLE_SIZE); + + /// Create Timeprobes with @a size slots + ACE_Timeprobe_Ex (ALLOCATOR *allocator, + u_long size = ACE_DEFAULT_TIMEPROBE_TABLE_SIZE); + /// Destructor. + ~ACE_Timeprobe_Ex (void); + + /// Record a time. @a event is used to describe this time probe. + void timeprobe (u_long event); + + /// Record a time. @a id is used to describe this time probe. + void timeprobe (const char *id); + + /// Record event descriptions. + int event_descriptions (const char **descriptions, + u_long minimum_id); + + /// Print the time probes. + void print_times (void); + + /// Print the time probes. + void print_absolute_times (void); + + /// Reset the slots. All old time probes will be lost. + void reset (void); + + void increase_size (u_long size); + + /// Not implemented (stupid MSVC won't let it be protected). + ACE_Timeprobe_Ex (const ACE_Timeprobe_Ex &); + + // = (Somewhat private) Accessors + + /// Event Descriptions + ACE_Unbounded_Set &event_descriptions (void); + + /// Sorted Event Descriptions. + ACE_Unbounded_Set &sorted_event_descriptions (void); + + /// Find description of event @a i + const char *find_description_i (u_long i); + + /// Sort event descriptions + void sort_event_descriptions_i (void); + + /// Time probe slots + ACE_timeprobe_t *timeprobes (void); + + /// Synchronization variable. + ACE_LOCK &lock (void); + + /// Max size of timestamp table + u_long max_size (void); + + /// Current size of timestamp table + u_long current_size (void); + +protected: + + /// Obtain an allocator pointer. If there is no allocator stored in + /// the instance, the singleton allocator in the current process is used. + ALLOCATOR * allocator (void); + + /// Event Descriptions + EVENT_DESCRIPTIONS event_descriptions_; + + /// Sorted Event Descriptions. + EVENT_DESCRIPTIONS sorted_event_descriptions_; + + /// Time probe slots + ACE_timeprobe_t *timeprobes_; + + /// Synchronization variable. + ACE_LOCK lock_; + + /// Max size of timestamp table + u_long max_size_; + + /// Current size of timestamp table + u_long current_size_; + + /// Flag indicating the report buffer has filled up, and is now + /// acting as a ring-buffer using modulus arithmetic: this saves the + /// max_size_ most recent time stamps and loses earlier ones until + /// drained. + u_short report_buffer_full_; + +private: + ALLOCATOR * allocator_; +}; + +// template +// class ACE_Timeprobe : public ACE_Timeprobe_Ex +// { +// public: +// // Initialize a ACE_Timeprobe with default size +// ACE_Timeprobe (ACE_Allocator *allocator = ACE_Allocator::instance()); + +// /// Create Timeprobes with @a size slots +// ACE_Timeprobe (ACE_Allocator *allocator = ACE_Allocator::instance(), +// u_long size = ACE_DEFAULT_TIMEPROBE_TABLE_SIZE); +// }; + +/** + * @class ACE_Function_Timeprobe + * + * @brief Auto pointer like time probes. It will record on + * construction and on destruction. + */ +template +class ACE_Function_Timeprobe +{ +public: + /// Constructor. + ACE_Function_Timeprobe (Timeprobe &timeprobe, u_long event); + + /// Destructor. + ~ACE_Function_Timeprobe (void); + +protected: + /// Reference to timeprobe. + Timeprobe &timeprobe_; + + /// Event. + u_long event_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Timeprobe_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Timeprobe_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#endif /* ACE_COMPILE_TIMEPROBES */ +#include /**/ "ace/post.h" +#endif /* ACE_TIMEPROBE_T_H */ diff --git a/dep/acelite/ace/Timer_Hash.h b/dep/acelite/ace/Timer_Hash.h new file mode 100644 index 00000000000..b381419da44 --- /dev/null +++ b/dep/acelite/ace/Timer_Hash.h @@ -0,0 +1,75 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file Timer_Hash.h + * + * $Id: Timer_Hash.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Darrell Brunsch + */ +//============================================================================= + + +#ifndef ACE_TIMER_HASH_H +#define ACE_TIMER_HASH_H +#include /**/ "ace/pre.h" + +#include "ace/Timer_Hash_T.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Timer_Heap_T.h" +#include "ace/Timer_List_T.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// The following typedef are here for ease of use + +typedef ACE_Timer_Hash_Upcall , + ACE_SYNCH_RECURSIVE_MUTEX> + ACE_Hash_Upcall; + +typedef ACE_Timer_List_T + ACE_Hash_Timer_List; + +typedef ACE_Timer_Heap_T + ACE_Hash_Timer_Heap; + + +typedef ACE_Timer_Hash_T, + ACE_SYNCH_RECURSIVE_MUTEX, + ACE_Hash_Timer_List> + + ACE_Timer_Hash; + +typedef ACE_Timer_Hash_Iterator_T, + ACE_SYNCH_RECURSIVE_MUTEX, + ACE_Hash_Timer_List> + ACE_Timer_Hash_Iterator; + +typedef ACE_Timer_Hash_T, + ACE_SYNCH_RECURSIVE_MUTEX, + ACE_Hash_Timer_Heap> + ACE_Timer_Hash_Heap; + +typedef ACE_Timer_Hash_Iterator_T, + ACE_SYNCH_RECURSIVE_MUTEX, + ACE_Hash_Timer_Heap> + ACE_Timer_Hash_Heap_Iterator; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" +#endif /* ACE_TIMER_HASH_H */ diff --git a/dep/acelite/ace/Timer_Hash_T.cpp b/dep/acelite/ace/Timer_Hash_T.cpp new file mode 100644 index 00000000000..d8153c1eee2 --- /dev/null +++ b/dep/acelite/ace/Timer_Hash_T.cpp @@ -0,0 +1,870 @@ +// $Id: Timer_Hash_T.cpp 89254 2010-02-25 22:10:39Z cleeland $ + +#ifndef ACE_TIMER_HASH_T_CPP +#define ACE_TIMER_HASH_T_CPP + +#include "ace/Timer_Hash_T.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/OS_NS_sys_time.h" +#include "ace/Guard_T.h" +#include "ace/Log_Msg.h" + +ACE_RCSID(ace, + Timer_Hash_T, + "$Id: Timer_Hash_T.cpp 89254 2010-02-25 22:10:39Z cleeland $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template +class Hash_Token +{ +public: + // This constructor is required by ACE_Locked_Free_List::alloc. + Hash_Token (void) + {} + + Hash_Token *get_next (void) + { + return this->next_; + } + + void set_next (Hash_Token *next) + { + this->next_ = next; + } + + void set (const void *act, + size_t pos, + long orig_id, + const TYPE &type) + { + this->act_ = act; + this->pos_ = pos; + this->orig_id_ = orig_id; + this->type_ = type; + this->next_ = 0; + } + + const void *act_; + size_t pos_; + long orig_id_; + TYPE type_; + /// Pointer to next token. + Hash_Token *next_; +}; + +// Default constructor + +template +ACE_Timer_Hash_Upcall::ACE_Timer_Hash_Upcall (void) + : timer_hash_ (0) +{ + // Nothing +} + +// Constructor that specifies a Timer_Hash to call up to + +template +ACE_Timer_Hash_Upcall::ACE_Timer_Hash_Upcall ( + ACE_Timer_Queue_T *timer_hash) + : timer_hash_ (timer_hash) +{ + // Nothing +} + +template int +ACE_Timer_Hash_Upcall::registration ( + TIMER_QUEUE &, + ACE_Event_Handler *, + const void *) +{ + // Registration will be handled by the upcall functor of the timer + // hash. + return 0; +} + +template int +ACE_Timer_Hash_Upcall::preinvoke (TIMER_QUEUE &, + ACE_Event_Handler *, + const void *, + int, + const ACE_Time_Value &, + const void *&) +{ + // This method should never be invoked since we don't invoke + // expire() on the buckets. + ACE_ASSERT (0); + return 0; +} + +template int +ACE_Timer_Hash_Upcall::postinvoke ( + TIMER_QUEUE &, + ACE_Event_Handler *, + const void *, + int, + const ACE_Time_Value &, + const void *) +{ + // This method should never be invoked since we don't invoke + // expire() on the buckets. + ACE_ASSERT (0); + return 0; +} + +// Calls up to timer_hash's upcall functor +template int +ACE_Timer_Hash_Upcall::timeout ( + TIMER_QUEUE &, + ACE_Event_Handler *, + const void *, + int, + const ACE_Time_Value &) +{ + // This method should never be invoked since we don't invoke + // expire() on the buckets. + ACE_ASSERT (0); + return 0; +} + +template int +ACE_Timer_Hash_Upcall::cancel_type ( + TIMER_QUEUE &, + ACE_Event_Handler *, + int, + int &) +{ + // Cancellation will be handled by the upcall functor of the timer + // hash. + return 0; +} + +template int +ACE_Timer_Hash_Upcall::cancel_timer ( + TIMER_QUEUE &, + ACE_Event_Handler *, + int, + int) +{ + // Cancellation will be handled by the upcall functor of the timer + // hash. + return 0; +} + +template int +ACE_Timer_Hash_Upcall::deletion ( + TIMER_QUEUE &, + ACE_Event_Handler *event_handler, + const void *arg) +{ + // Call up to the upcall functor of the timer hash since the timer + // hash does not invoke deletion() on its upcall functor directly. + Hash_Token *h = + reinterpret_cast *> (const_cast (arg)); + + int result = + this->timer_hash_->upcall_functor (). + deletion (*this->timer_hash_, + event_handler, + h->act_); + + return result; +} + +template +ACE_Timer_Hash_Iterator_T::ACE_Timer_Hash_Iterator_T (ACE_Timer_Hash_T &hash) + : timer_hash_ (hash) +{ + this->first (); + // Nothing +} + +// Positions the iterator at the first node in the timing hash table + +template void +ACE_Timer_Hash_Iterator_T::first (void) +{ + for (this->position_ = 0; + this->position_ < this->timer_hash_.table_size_; + ++this->position_) + { + // Check for an empty entry + if (!this->timer_hash_.table_[this->position_]->is_empty ()) + { + this->iter_ = &this->timer_hash_.table_[this->position_]->iter (); + this->iter_->first (); + return; + } + } + + // Didn't find any + this->iter_ = 0; +} + +// Positions the iterator at the next node in the bucket or goes to the next +// bucket + +template void +ACE_Timer_Hash_Iterator_T::next (void) +{ + if (this->isdone ()) + return; + + // If there is no more in the current bucket, go to the next + if (this->iter_->isdone ()) + { + for (++this->position_; + this->position_ < this->timer_hash_.table_size_; + ++this->position_) + { + // Check for an empty entry + if (!this->timer_hash_.table_[this->position_]->is_empty ()) + { + this->iter_ = &this->timer_hash_.table_[this->position_]->iter (); + this->iter_->first (); + return; + } + } + + // Didn't find any. + this->iter_ = 0; + } + else + this->iter_->next (); +} + +// Returns true when we are at the end (when bucket_item_ == 0) + +template bool +ACE_Timer_Hash_Iterator_T::isdone (void) const +{ + return this->iter_ == 0; +} + +// Returns the node at the current position in the sequence + +template +ACE_Timer_Node_T * +ACE_Timer_Hash_Iterator_T::item (void) +{ + if (this->isdone ()) + return 0; + + return this->iter_->item (); +} + +template +ACE_Timer_Queue_Iterator_T & +ACE_Timer_Hash_T::iter (void) +{ + this->iterator_->first (); + return *this->iterator_; +} + +// Create an empty queue. + +template +ACE_Timer_Hash_T::ACE_Timer_Hash_T ( + size_t table_size, + FUNCTOR *upcall_functor, + ACE_Free_List > *freelist) + : ACE_Timer_Queue_T (upcall_functor, freelist), + size_ (0), + table_size_ (table_size), + table_functor_ (this), + earliest_position_ (0) +#if defined (ACE_WIN64) + , pointer_base_ (0) +#endif /* ACE_WIN64 */ + , token_list_ () +{ + ACE_TRACE ("ACE_Timer_Hash_T::ACE_Timer_Hash_T"); + + ACE_NEW (table_, + BUCKET *[table_size]); + + this->gettimeofday (ACE_OS::gettimeofday); + + for (size_t i = 0; + i < table_size; + ++i) + { + ACE_NEW (this->table_[i], + BUCKET (&this->table_functor_, + this->free_list_)); + this->table_[i]->gettimeofday (ACE_OS::gettimeofday); + } + + ACE_NEW (iterator_, + HASH_ITERATOR (*this)); +} + + +template +ACE_Timer_Hash_T::ACE_Timer_Hash_T ( + FUNCTOR *upcall_functor, + ACE_Free_List > *freelist) + : ACE_Timer_Queue_T (upcall_functor, freelist), + size_ (0), + table_size_ (ACE_DEFAULT_TIMER_HASH_TABLE_SIZE), + table_functor_ (this), + earliest_position_ (0) +#if defined (ACE_WIN64) + , pointer_base_ (0) +#endif /* ACE_WIN64 */ + , token_list_ () +{ + ACE_TRACE ("ACE_Timer_Hash_T::ACE_Timer_Hash_T"); + + ACE_NEW (table_, + BUCKET *[ACE_DEFAULT_TIMER_HASH_TABLE_SIZE]); + + + this->gettimeofday (ACE_OS::gettimeofday); + + for (size_t i = 0; + i < this->table_size_; + ++i) + { + ACE_NEW (this->table_[i], + BUCKET (&this->table_functor_, + this->free_list_)); + this->table_[i]->gettimeofday (ACE_OS::gettimeofday); + } + + ACE_NEW (iterator_, + HASH_ITERATOR (*this)); +} + +// Remove all remaining items in the Queue. + +template +ACE_Timer_Hash_T::~ACE_Timer_Hash_T (void) +{ + ACE_TRACE ("ACE_Timer_Hash_T::~ACE_Timer_Hash_T"); + ACE_MT (ACE_GUARD (ACE_LOCK, ace_mon, this->mutex_)); + + delete iterator_; + + for (size_t i = 0; + i < this->table_size_; + ++i) + delete this->table_[i]; + + delete [] this->table_; +} + +// Checks if queue is empty. + +template bool +ACE_Timer_Hash_T::is_empty (void) const +{ + ACE_TRACE ("ACE_Timer_Hash_T::is_empty"); + return this->table_[this->earliest_position_]->is_empty (); +} + +// Returns earliest time in a non-empty bucket + +template +const ACE_Time_Value & +ACE_Timer_Hash_T::earliest_time (void) const +{ + ACE_TRACE ("ACE_Timer_Hash_T::earliest_time"); + return this->table_[this->earliest_position_]->earliest_time (); +} + +template void +ACE_Timer_Hash_T::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Timer_Hash_T::dump"); + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ntable_size_ = %d"), this->table_size_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nearliest_position_ = %d"), this->earliest_position_)); + + for (size_t i = 0; i < this->table_size_; ++i) + if (!this->table_[i]->is_empty ()) + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nBucket %d contains nodes"), i)); + + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n"))); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +// Reschedule a periodic timer. This function must be called with the +// mutex lock held. + +template +void +ACE_Timer_Hash_T::reschedule ( + ACE_Timer_Node_T *expired) +{ + ACE_TRACE ("ACE_Timer_Hash_T::reschedule"); + + Hash_Token *h = + reinterpret_cast *> ( + const_cast (expired->get_act ())); + + // Don't use ACE_Utils::truncate_cast<> here. A straight + // static_cast<> will provide more unique results when the number + // of seconds is greater than std::numeric_limits::max(). + size_t const secs_hash_input = + static_cast (expired->get_timer_value ().sec ()); + h->pos_ = secs_hash_input % this->table_size_; + + h->orig_id_ = + this->table_[h->pos_]->schedule (expired->get_type (), + h, + expired->get_timer_value (), + expired->get_interval ()); + ACE_ASSERT (h->orig_id_ != -1); + +#if 0 + ACE_DEBUG ((LM_DEBUG, "Hash::reschedule() resets %d in slot %d where it's id is %d and token is %x\n", + expired->get_timer_value ().msec (), + h->pos_, + h->orig_id_, + h)); +#endif + + // Since schedule() above will allocate a new node + // then here schedule for deletion. Don't call + // this->free_node() because that will invalidate + // and that's what user have as timer_id. + ACE_Timer_Queue_T::free_node (expired); + + if (this->table_[this->earliest_position_]->is_empty () + || this->table_[h->pos_]->earliest_time () + < this->table_[this->earliest_position_]->earliest_time ()) + this->earliest_position_ = h->pos_; +} + +// Insert a new handler that expires at time future_time; if interval +// is > 0, the handler will be reinvoked periodically. + +template +long +ACE_Timer_Hash_T::schedule_i ( + const TYPE &type, + const void *act, + const ACE_Time_Value &future_time, + const ACE_Time_Value &interval) +{ + ACE_TRACE ("ACE_Timer_Hash_T::schedule_i"); + + // Don't use ACE_Utils::truncate_cast<> here. A straight + // static_cast<> will provide more unique results when the number + // of seconds is greater than std::numeric_limits::max(). + size_t const secs_hash_input = static_cast (future_time.sec ()); + size_t const position = secs_hash_input % this->table_size_; + + // Don't create Hash_Token directly. Instead we get one from Free_List + // and then set it properly. + Hash_Token *h = this->token_list_.remove (); + h->set (act, position, 0, type); + + h->orig_id_ = + this->table_[position]->schedule (type, + h, + future_time, + interval); + ACE_ASSERT (h->orig_id_ != -1); + +#if 0 + ACE_DEBUG ((LM_DEBUG, "Hash::schedule() placing %d in slot %d where it's id is %d and token is %x\n", + future_time.msec (), + position, + h->orig_id_, + h)); +#endif + + if (this->table_[this->earliest_position_]->is_empty () + || this->table_[position]->earliest_time () + < this->table_[this->earliest_position_]->earliest_time ()) + this->earliest_position_ = position; + + ++this->size_; + +#if defined (ACE_WIN64) + // This is a Win64 hack, necessary because of the original (bad) decision + // to use a pointer as the timer ID. This class doesn't follow the usual + // timer expiration rules (see comments in header file) and is probably + // not used much. The dynamic allocation of Hash_Tokens without + // recording them anywhere is a large problem for Win64 since the + // size of a pointer is 64 bits, but a long is 32. Since this class + // is not much used, I'm hacking this, at least for now. If it becomes + // an issue, I'll look at it again then. + intptr_t hi = reinterpret_cast (h); + if (this->pointer_base_ == 0) + this->pointer_base_ = hi & 0xffffffff00000000; + return static_cast (hi & 0xffffffff); +#else + return reinterpret_cast (h); +#endif +} + +// Locate and update the inteval on the timer_id + +template +int +ACE_Timer_Hash_T::reset_interval ( + long timer_id, + const ACE_Time_Value & interval) +{ + ACE_TRACE ("ACE_Timer_Hash_T::reset_interval"); + + // Make sure we are getting a valid , not an error + // returned by . + if (timer_id == -1) + return -1; + +#if defined (ACE_WIN64) + unsigned long const timer_offset = + static_cast (timer_id); + + ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); + + Hash_Token * const h = + reinterpret_cast *> (this->pointer_base_ + timer_offset); +#else + Hash_Token * const h = + reinterpret_cast *> (timer_id); + + // Grab the lock before accessing the table. We don't need to do so + // before this point since no members are accessed until now. + ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); +#endif /* ACE_WIN64 */ + + return this->table_[h->pos_]->reset_interval (h->orig_id_, + interval); +} + +// Locate and remove the single with a value of +// @a timer_id from the correct table timer queue. + +template +int +ACE_Timer_Hash_T::cancel (long timer_id, + const void **act, + int dont_call) +{ + ACE_TRACE ("ACE_Timer_Hash_T::cancel"); + + // Make sure we are getting a valid , not an error + // returned by . + if (timer_id == -1) + return 0; + +#if defined (ACE_WIN64) + unsigned long const timer_offset = + static_cast (timer_id); + + ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); + + Hash_Token * const h = + reinterpret_cast *> (this->pointer_base_ + timer_offset); +#else + Hash_Token * const h = + reinterpret_cast *> (timer_id); + + // Grab the lock before accessing the table. We don't need to do so + // before this point since no members are accessed until now. + ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); +#endif /* ACE_WIN64 */ + + int const result = this->table_[h->pos_]->cancel (h->orig_id_, + 0, + dont_call); + + if (result == 1) + { + // Call the close hooks. + int cookie = 0; + + // cancel_type() called once per . + this->upcall_functor ().cancel_type (*this, + h->type_, + dont_call, + cookie); + + // cancel_timer() called once per . + this->upcall_functor ().cancel_timer (*this, + h->type_, + dont_call, + cookie); + + if (h->pos_ == this->earliest_position_) + this->find_new_earliest (); + + if (act != 0) + *act = h->act_; + + // We could destruct Hash_Token explicitly but we better + // schedule it for destruction. In this case next + // token_list_.remove () will use it. + this->token_list_.add (h); + + --this->size_; + } + + return result; +} + +// Locate and remove all values of from the timer queue. + +template +int +ACE_Timer_Hash_T::cancel (const TYPE &type, + int dont_call) +{ + ACE_TRACE ("ACE_Timer_Hash_T::cancel"); + + size_t i; // loop variable. + + Hash_Token **timer_ids = 0; + size_t pos = 0; + + ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); + + ACE_NEW_RETURN (timer_ids, + Hash_Token *[this->size_], + -1); + + for (i = 0; + i < this->table_size_; + ++i) + { + ACE_Timer_Queue_Iterator_T, + ACE_Null_Mutex> &iter = + this->table_[i]->iter (); + + for (iter.first (); + !iter.isdone (); + iter.next ()) + if (iter.item ()->get_type () == type) + timer_ids[pos++] = + reinterpret_cast *> ( + const_cast (iter.item ()->get_act ())); + } + + if (pos > this->size_) + return -1; + + for (i = 0; i < pos; ++i) + { + int const result = + this->table_[timer_ids[i]->pos_]->cancel (timer_ids[i]->orig_id_, + 0, + dont_call); + ACE_ASSERT (result == 1); + ACE_UNUSED_ARG (result); + + // We could destruct Hash_Token explicitly but we better + // schedule it for destruction. + this->token_list_.add (timer_ids[i]); + + --this->size_; + } + + delete [] timer_ids; + + this->find_new_earliest (); + + // Call the close hooks. + int cookie = 0; + + // cancel_type() called once per . + this->upcall_functor ().cancel_type (*this, + type, + dont_call, + cookie); + + for (i = 0; + i < pos; + ++i) + { + // cancel_timer() called once per . + this->upcall_functor ().cancel_timer (*this, + type, + dont_call, + cookie); + } + + return static_cast (pos); +} + +// Removes the earliest node and finds the new earliest position + +template ACE_Timer_Node_T * +ACE_Timer_Hash_T::remove_first (void) +{ + if (this->is_empty ()) + return 0; + + ACE_Timer_Node_T *temp = + this->table_[this->earliest_position_]->remove_first (); + + this->find_new_earliest (); + + --this->size_; + + return temp; +} + +// Finds a new earliest position + +template void +ACE_Timer_Hash_T::find_new_earliest (void) +{ + for (size_t i = 0; i < this->table_size_; ++i) + if (!this->table_[i]->is_empty ()) + if (this->table_[this->earliest_position_]->is_empty () + || this->earliest_time () == ACE_Time_Value::zero + || this->table_[i]->earliest_time () <= this->earliest_time ()) + this->earliest_position_ = i; +} + +// Returns the earliest node without removing it + +template ACE_Timer_Node_T * +ACE_Timer_Hash_T::get_first (void) +{ + ACE_TRACE ("ACE_Timer_Hash_T::get_first"); + + if (this->is_empty ()) + return 0; + + return this->table_[this->earliest_position_]->get_first (); +} + +template void +ACE_Timer_Hash_T::free_node (ACE_Timer_Node_T *node) +{ + ACE_Timer_Queue_T::free_node (node); + + Hash_Token *h = + reinterpret_cast *> (const_cast (node->get_act ())); + this->token_list_.add (h); +} + +template int +ACE_Timer_Hash_T::dispatch_info_i (const ACE_Time_Value &cur_time, + ACE_Timer_Node_Dispatch_Info_T &info) +{ + int const result = + ACE_Timer_Queue_T::dispatch_info_i (cur_time, + info); + + if (result == 1) + { + Hash_Token *h = + reinterpret_cast *> (const_cast (info.act_)); + + info.act_ = h->act_; + } + + return result; +} + +// Dummy version of expire to get rid of warnings in Sun CC 4.2 + +template int +ACE_Timer_Hash_T::expire () +{ + return ACE_Timer_Queue_T::expire(); +} + +// Specialized expire for Timer Hash + +template int +ACE_Timer_Hash_T::expire (const ACE_Time_Value &cur_time) +{ + ACE_TRACE ("ACE_Timer_Hash_T::expire"); + + int number_of_timers_expired = 0; + + ACE_Timer_Node_T *expired = 0; + + ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); + + // Go through the table and expire anything that can be expired + + for (size_t i = 0; + i < this->table_size_; + ++i) + { + while (!this->table_[i]->is_empty () + && this->table_[i]->earliest_time () <= cur_time) + { + expired = this->table_[i]->remove_first (); + const void *act = expired->get_act (); + bool reclaim = true; + + Hash_Token *h = + reinterpret_cast *> (const_cast (act)); + + ACE_ASSERT (h->pos_ == i); + +#if 0 + ACE_DEBUG ((LM_DEBUG, "Hash::expire() expiring %d in slot %d where it's id is %d and token is %x\n", + expired->get_timer_value ().msec (), + h->pos_, + h->orig_id_, + h)); +#endif + + // Check if this is an interval timer. + if (expired->get_interval () > ACE_Time_Value::zero) + { + // Make sure that we skip past values that have already + // "expired". + this->recompute_next_abs_interval_time (expired, cur_time); + + // Since this is an interval timer, we need to + // reschedule it. + this->reschedule (expired); + reclaim = false; + } + else + { + this->free_node (expired); + } + + ACE_Timer_Node_Dispatch_Info_T info; + + // Get the dispatch info + expired->get_dispatch_info (info); + + info.act_ = h->act_; + + const void *upcall_act = 0; + + this->preinvoke (info, cur_time, upcall_act); + + this->upcall (info, cur_time); + + this->postinvoke (info, cur_time, upcall_act); + + if (reclaim) + { + --this->size_; + } + + ++number_of_timers_expired; + } + } + + if (number_of_timers_expired > 0) + this->find_new_earliest (); + + return number_of_timers_expired; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_TIMER_HASH_T_CPP */ diff --git a/dep/acelite/ace/Timer_Hash_T.h b/dep/acelite/ace/Timer_Hash_T.h new file mode 100644 index 00000000000..b04e7cfbcf3 --- /dev/null +++ b/dep/acelite/ace/Timer_Hash_T.h @@ -0,0 +1,342 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file Timer_Hash_T.h + * + * $Id: Timer_Hash_T.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Darrell Brunsch + */ +//============================================================================= + +#ifndef ACE_TIMER_HASH_T_H +#define ACE_TIMER_HASH_T_H +#include /**/ "ace/pre.h" + +#include "ace/Timer_Queue_T.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Free_List.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Forward declaration. +template +class ACE_Timer_Hash_T; +template +class Hash_Token; + +/** + * @class ACE_Timer_Hash_Upcall + * + * @brief Functor for Timer_Hash + * + * This class calls up to the Timer Hash's functor from the + * timer queues in the hash table + */ +template +class ACE_Timer_Hash_Upcall +{ +public: + typedef ACE_Timer_Queue_T, + ACE_Null_Mutex> + TIMER_QUEUE; + + /// Default constructor (creates an invalid object, but needs to be here + /// so timer queues using this functor can be constructed) + ACE_Timer_Hash_Upcall (void); + + /// Constructor that specifies a Timer_Hash to call up to + ACE_Timer_Hash_Upcall (ACE_Timer_Queue_T *timer_hash); + + /// This method is called when a timer is registered. + int registration (TIMER_QUEUE &timer_queue, + ACE_Event_Handler *handler, + const void *arg); + + /// This method is called before the timer expires. + int preinvoke (TIMER_QUEUE &timer_queue, + ACE_Event_Handler *handler, + const void *arg, + int recurring_timer, + const ACE_Time_Value &cur_time, + const void *&upcall_act); + + /// This method is called when the timer expires. + int timeout (TIMER_QUEUE &timer_queue, + ACE_Event_Handler *handler, + const void *arg, + int recurring_timer, + const ACE_Time_Value &cur_time); + + /// This method is called after the timer expires. + int postinvoke (TIMER_QUEUE &timer_queue, + ACE_Event_Handler *handler, + const void *arg, + int recurring_timer, + const ACE_Time_Value &cur_time, + const void *upcall_act); + + /// This method is called when a handler is cancelled + int cancel_type (TIMER_QUEUE &timer_queue, + ACE_Event_Handler *handler, + int dont_call, + int &requires_reference_counting); + + /// This method is called when a timer is cancelled + int cancel_timer (TIMER_QUEUE &timer_queue, + ACE_Event_Handler *handler, + int dont_call, + int requires_reference_counting); + + /// This method is called when the timer queue is destroyed and + /// the timer is still contained in it + int deletion (TIMER_QUEUE &timer_queue, + ACE_Event_Handler *handler, + const void *arg); + +private: + /// Timer Queue to do the calling up to + ACE_Timer_Queue_T *timer_hash_; + + // = Don't allow these operations for now. + ACE_UNIMPLEMENTED_FUNC (ACE_Timer_Hash_Upcall (const ACE_Timer_Hash_Upcall &)) + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Timer_Hash_Upcall &)) +}; + +/** + * @class ACE_Timer_Hash_Iterator_T + * + * @brief Iterates over an ACE_Timer_Hash_T. + * + * This is a generic iterator that can be used to visit every + * node of a timer queue. Be aware that it doesn't transverse + * in the order of timeout values. + */ +template +class ACE_Timer_Hash_Iterator_T : public ACE_Timer_Queue_Iterator_T +{ +public: + /// Constructor. + ACE_Timer_Hash_Iterator_T (ACE_Timer_Hash_T &); + + /// Positions the iterator at the earliest node in the Timer Queue + virtual void first (void); + + /// Positions the iterator at the next node in the Timer Queue + virtual void next (void); + + /// Returns true when there are no more nodes in the sequence + virtual bool isdone (void) const; + + /// Returns the node at the current position in the sequence + virtual ACE_Timer_Node_T *item (void); + +protected: + /// Pointer to the ACE_Timer_Hash that we are iterating over. + ACE_Timer_Hash_T &timer_hash_; + + /// Current position in 's table + size_t position_; + + /// Current iterator used on 's bucket + ACE_Timer_Queue_Iterator_T, ACE_Null_Mutex> *iter_; +}; + +/** + * @class ACE_Timer_Hash_T + * + * @brief Provides a hash table of BUCKETs as an implementation for + * a timer queue. + * + * This implementation uses a hash table of BUCKETs. The hash + * is based on the time_value of the event. Unlike other Timer + * Queues, ACE_Timer_Hash does not expire events in order. + */ +template +class ACE_Timer_Hash_T : public ACE_Timer_Queue_T +{ +public: + /// Type of iterator + typedef ACE_Timer_Hash_Iterator_T + HASH_ITERATOR; + + /// Iterator is a friend + friend class ACE_Timer_Hash_Iterator_T; + + /// Type inherited from + typedef ACE_Timer_Queue_T INHERITED; + + // = Initialization and termination methods. + /** + * Default constructor. @a table_size determines the size of the + * hash table. @a upcall_functor is the instance of the FUNCTOR + * to be used by the buckets. If @a upcall_functor is 0, a default + * FUNCTOR will be created. + */ + ACE_Timer_Hash_T (size_t table_size, + FUNCTOR *upcall_functor = 0, + ACE_Free_List > *freelist = 0); + + /** + * Default constructor. @a upcall_functor is the instance of the + * FUNCTOR to be used by the queue. If @a upcall_functor is 0, Timer + * Hash will create a default FUNCTOR. @a freelist the freelist of + * timer nodes. If 0, then a default freelist will be created. The default + * size will be ACE_DEFAULT_TIMERS and there will be no preallocation. + */ + ACE_Timer_Hash_T (FUNCTOR *upcall_functor = 0, ACE_Free_List > *freelist = 0); + + /// Destructor + virtual ~ACE_Timer_Hash_T (void); + + /// True if queue is empty, else false. + virtual bool is_empty (void) const; + + /// Returns the time of the earlier node in the . + /// Must be called on a non-empty queue. + virtual const ACE_Time_Value &earliest_time (void) const; + + /** + * Resets the interval of the timer represented by @a timer_id to + * @a interval, which is specified in relative time to the current + * . If @a interval is equal to + * ACE_Time_Value::zero, the timer will become a non-rescheduling + * timer. Returns 0 if successful, -1 if not. + */ + virtual int reset_interval (long timer_id, + const ACE_Time_Value &interval); + + /** + * Cancel all timer associated with @a type. If is 0 + * then the will be invoked. Returns number of timers + * cancelled. If any valid timer is not cancelled before destruction + * of this instance of ACE_Timer_Hash_T then user will get a memory + * leak. + */ + virtual int cancel (const TYPE &type, + int dont_call_handle_close = 1); + + /** + * Cancel the single timer that matches the @a timer_id value (which + * was returned from the method). If act is non-NULL + * then it will be set to point to the ``magic cookie'' argument + * passed in when the timer was registered. This makes it possible + * to free up the memory and avoid memory leaks. If is + * 0 then the will be invoked. Returns 1 if cancellation + * succeeded and 0 if the @a timer_id wasn't found. If any valid + * timer is not cancelled before destruction of this instance of + * ACE_Timer_Hash_T then user will get a memory leak. + */ + virtual int cancel (long timer_id, + const void **act = 0, + int dont_call_handle_close = 1); + + /** + * Run the for all timers whose values are <= + * . Also accounts for . Returns + * the number of timers canceled. + */ + virtual int expire (void); + + /** + * Run the for all timers whose values are <= @a current_time. + * This does not account for . Returns the number of + * timers canceled. + */ + virtual int expire (const ACE_Time_Value ¤t_time); + + /// Returns a pointer to this ACE_Timer_Queue's iterator. + virtual ACE_Timer_Queue_Iterator_T &iter (void); + + /// Removes the earliest node from the queue and returns it + virtual ACE_Timer_Node_T *remove_first (void); + + /// Dump the state of an object. + virtual void dump (void) const; + + /// Reads the earliest node from the queue and returns it. + virtual ACE_Timer_Node_T *get_first (void); + +protected: + /// Factory method that frees a previously allocated node. + virtual void free_node (ACE_Timer_Node_T *); + +private: + + /** + * Schedule @a type that will expire at @a future_time, + * which is specified in absolute time. If it expires then @a act is + * passed in as the value to the . If @a interval is != to + * ACE_Time_Value::zero then it is used to reschedule the @a type + * automatically, using relative time to the current . + * This method returns a that is a pointer to a token + * which stores information about the event. This can be + * used to cancel the timer before it expires. Returns -1 on + * failure. + */ + virtual long schedule_i (const TYPE &type, + const void *act, + const ACE_Time_Value &future_time, + const ACE_Time_Value &interval); + + /// Non-locking version of dispatch_info () + virtual int dispatch_info_i (const ACE_Time_Value ¤t_time, + ACE_Timer_Node_Dispatch_Info_T &info); + + /// Reschedule an "interval" ACE_Timer_Node. + virtual void reschedule (ACE_Timer_Node_T *); + + /// Finds the earliest node + void find_new_earliest (void); + + /// Keeps track of the size of the queue + size_t size_; + + /// Table of BUCKETS + BUCKET **table_; + + /// Keeps track of the size of table_ + size_t table_size_; + + /// Functor used for the table's timer queues + ACE_Timer_Hash_Upcall table_functor_; + + /// Index to the position with the earliest entry + size_t earliest_position_; + + /// Iterator used to expire timers. + HASH_ITERATOR *iterator_; + +#if defined (ACE_WIN64) + // Part of a hack... see comments in schedule(). + // This is, essentially, the upper 32 bits of a 64-bit pointer on Win64. + ptrdiff_t pointer_base_; +#endif + + /// Hash_Token is usually allocated in schedule but its + /// deallocation is problematic and token_list_ helps with this. + ACE_Locked_Free_List, ACE_Null_Mutex> token_list_; + + // = Don't allow these operations for now. + ACE_UNIMPLEMENTED_FUNC (ACE_Timer_Hash_T (const ACE_Timer_Hash_T &)) + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Timer_Hash_T &)) +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Timer_Hash_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Timer_Hash_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" +#endif /* ACE_TIMER_HASH_T_H */ diff --git a/dep/acelite/ace/Timer_Heap.h b/dep/acelite/ace/Timer_Heap.h new file mode 100644 index 00000000000..7dec5ec22b4 --- /dev/null +++ b/dep/acelite/ace/Timer_Heap.h @@ -0,0 +1,41 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file Timer_Heap.h + * + * $Id: Timer_Heap.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_TIMER_HEAP_H +#define ACE_TIMER_HEAP_H +#include /**/ "ace/pre.h" + +#include "ace/Timer_Heap_T.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// The following typedefs are here for ease of use and backward +// compatibility. + +typedef ACE_Timer_Heap_T, + ACE_SYNCH_RECURSIVE_MUTEX> + ACE_Timer_Heap; + +typedef ACE_Timer_Heap_Iterator_T, + ACE_SYNCH_RECURSIVE_MUTEX> + ACE_Timer_Heap_Iterator; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" +#endif /* ACE_TIMER_HEAP_H */ diff --git a/dep/acelite/ace/Timer_Heap_T.cpp b/dep/acelite/ace/Timer_Heap_T.cpp new file mode 100644 index 00000000000..75ec9ef70fc --- /dev/null +++ b/dep/acelite/ace/Timer_Heap_T.cpp @@ -0,0 +1,889 @@ +// $Id: Timer_Heap_T.cpp 84962 2009-03-24 15:16:25Z johnnyw $ + +#ifndef ACE_TIMER_HEAP_T_CPP +#define ACE_TIMER_HEAP_T_CPP + +#include "ace/Timer_Heap_T.h" +#include "ace/Log_Msg.h" +#include "ace/Guard_T.h" +#include "ace/OS_NS_errno.h" +#include "ace/OS_NS_string.h" +#include "ace/Numeric_Limits.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +/* +** The ACE_Timer_Heap::max_size_ and array loops, checks, etc. are all size_t. +** The timer IDs are long, and since they are indices into the heap, we need +** to be sure that the timer heap size can fit in a long. Hence, when size +** is (re)set, limit it to the maximum long value. We use the C++ standard +** limits if available. +*/ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Define some simple inlined functions to clarify the code. +inline size_t +ACE_HEAP_PARENT (size_t X) +{ + return (X == 0 ? 0 : ((X - 1) / 2)); +} + +inline size_t +ACE_HEAP_LCHILD (size_t X) +{ + return X + X + 1; +} + +// Constructor that takes in an to iterate over. + +template +ACE_Timer_Heap_Iterator_T::ACE_Timer_Heap_Iterator_T ( + ACE_Timer_Heap_T &heap) + : timer_heap_ (heap) +{ + ACE_TRACE ("ACE_Timer_Heap_Iterator_T::ACE_Timer_Heap_Iterator"); + this->first (); +} + +template +ACE_Timer_Heap_Iterator_T::~ACE_Timer_Heap_Iterator_T (void) +{ +} + +// Positions the iterator at the first node in the heap array + +template +void +ACE_Timer_Heap_Iterator_T::first (void) +{ + this->position_ = 0; +} + +// Positions the iterator at the next node in the heap array + +template +void +ACE_Timer_Heap_Iterator_T::next (void) +{ + if (this->position_ != this->timer_heap_.cur_size_) + ++this->position_; +} + +// Returns true the is at the end of the heap array + +template bool +ACE_Timer_Heap_Iterator_T::isdone (void) const +{ + return this->position_ == this->timer_heap_.cur_size_; +} + +// Returns the node at the current position in the heap or 0 if at the end + +template ACE_Timer_Node_T * +ACE_Timer_Heap_Iterator_T::item (void) +{ + if (this->position_ != this->timer_heap_.cur_size_) + return this->timer_heap_.heap_[this->position_]; + return 0; +} + +// Constructor +// Note that timer_ids_curr_ and timer_ids_min_free_ both start at 0. +// Since timer IDs are assigned by first incrementing the timer_ids_curr_ +// value, the first ID assigned will be 1 (just as in the previous design). +// When it's time to wrap, the next ID given out will be 0. +template +ACE_Timer_Heap_T::ACE_Timer_Heap_T ( + size_t size, + bool preallocated, + FUNCTOR *upcall_functor, + ACE_Free_List > *freelist) + : ACE_Timer_Queue_T (upcall_functor, freelist), + max_size_ (size), + cur_size_ (0), + cur_limbo_ (0), + timer_ids_curr_ (0), + timer_ids_min_free_ (0), + preallocated_nodes_ (0), + preallocated_nodes_freelist_ (0) +{ + ACE_TRACE ("ACE_Timer_Heap_T::ACE_Timer_Heap_T"); + + // Possibly reduce size to fit in a long. + if (size > static_cast (ACE_Numeric_Limits::max ())) + { + size = static_cast (ACE_Numeric_Limits::max ()); + this->max_size_ = size; + } + + // Create the heap array. + ACE_NEW (this->heap_, + ACE_Timer_Node_T *[size]); + + // Create the parallel + ACE_NEW (this->timer_ids_, + ssize_t[size]); + + // Initialize the "freelist," which uses negative values to + // distinguish freelist elements from "pointers" into the + // array. + for (size_t i = 0; i < size; ++i) + this->timer_ids_[i] = -1; + + if (preallocated) + { + ACE_NEW (this->preallocated_nodes_, + ACE_Timer_Node_T[size]); + + // Add allocated array to set of such arrays for deletion on + // cleanup. + this->preallocated_node_set_.insert (this->preallocated_nodes_); + + // Form the freelist by linking the next_ pointers together. + for (size_t j = 1; j < size; ++j) + this->preallocated_nodes_[j - 1].set_next (&this->preallocated_nodes_[j]); + + // NULL-terminate the freelist. + this->preallocated_nodes_[size - 1].set_next (0); + + // Assign the freelist pointer to the front of the list. + this->preallocated_nodes_freelist_ = + &this->preallocated_nodes_[0]; + } + + ACE_NEW (iterator_, + HEAP_ITERATOR (*this)); +} + +// Note that timer_ids_curr_ and timer_ids_min_free_ both start at 0. +// Since timer IDs are assigned by first incrementing the timer_ids_curr_ +// value, the first ID assigned will be 1 (just as in the previous design). +// When it's time to wrap, the next ID given out will be 0. +template +ACE_Timer_Heap_T::ACE_Timer_Heap_T ( + FUNCTOR *upcall_functor, + ACE_Free_List > *freelist) + : ACE_Timer_Queue_T (upcall_functor, freelist), + max_size_ (ACE_DEFAULT_TIMERS), + cur_size_ (0), + cur_limbo_ (0), + timer_ids_curr_ (0), + timer_ids_min_free_ (0), + preallocated_nodes_ (0), + preallocated_nodes_freelist_ (0) +{ + ACE_TRACE ("ACE_Timer_Heap_T::ACE_Timer_Heap_T"); + + // Possibly reduce size to fit in a long. + if (this->max_size_ > static_cast (ACE_Numeric_Limits::max ())) + this->max_size_ = static_cast (ACE_Numeric_Limits::max ()); + + // Create the heap array. + ACE_NEW (this->heap_, + ACE_Timer_Node_T *[this->max_size_]); + + // Create the parallel array. + ACE_NEW (this->timer_ids_, + ssize_t[this->max_size_]); + + // Initialize the "freelist," which uses negative values to + // distinguish freelist elements from "pointers" into the + // array. + for (size_t i = 0; i < this->max_size_; ++i) + this->timer_ids_[i] = -1; + + ACE_NEW (iterator_, + HEAP_ITERATOR (*this)); +} + +template +ACE_Timer_Heap_T::~ACE_Timer_Heap_T (void) +{ + ACE_TRACE ("ACE_Timer_Heap_T::~ACE_Timer_Heap_T"); + + delete iterator_; + + size_t current_size = + this->cur_size_; + + // Clean up all the nodes still in the queue + for (size_t i = 0; i < current_size; ++i) + { + // Grab the event_handler and act, then delete the node before calling + // back to the handler. Prevents a handler from trying to cancel_timer() + // inside handle_close(), ripping the current timer node out from + // under us. + TYPE eh = this->heap_[i]->get_type (); + const void *act = this->heap_[i]->get_act (); + this->free_node (this->heap_[i]); + this->upcall_functor ().deletion (*this, eh, act); + } + + delete [] this->heap_; + delete [] this->timer_ids_; + + // clean up any preallocated timer nodes + if (preallocated_nodes_ != 0) + { + ACE_Unbounded_Set_Iterator *> + set_iterator (this->preallocated_node_set_); + + for (ACE_Timer_Node_T **entry = 0; + set_iterator.next (entry) !=0; + set_iterator.advance ()) + delete [] *entry; + } +} + +template +long +ACE_Timer_Heap_T::pop_freelist (void) +{ + ACE_TRACE ("ACE_Timer_Heap_T::pop_freelist"); + + // Scan for a free timer ID. Note that since this function is called + // _after_ the check for a full timer heap, we are guaranteed to find + // a free ID, even if we need to wrap around and start reusing freed IDs. + // On entry, the curr_ index is at the previous ID given out; start + // up where we left off last time. + // NOTE - a timer_ids_ slot with -2 is out of the heap, but not freed. + // It must be either freed (free_node) or rescheduled (reschedule). + ++this->timer_ids_curr_; + while (this->timer_ids_curr_ < this->max_size_ && + (this->timer_ids_[this->timer_ids_curr_] >= 0 || + this->timer_ids_[this->timer_ids_curr_] == -2 )) + ++this->timer_ids_curr_; + if (this->timer_ids_curr_ == this->max_size_) + { + ACE_ASSERT (this->timer_ids_min_free_ < this->max_size_); + this->timer_ids_curr_ = this->timer_ids_min_free_; + // We restarted the free search at min. Since min won't be + // free anymore, and curr_ will just keep marching up the list + // on each successive need for an ID, reset min_free_ to the + // size of the list until an ID is freed that curr_ has already + // gone past (see push_freelist). + this->timer_ids_min_free_ = this->max_size_; + } + + return static_cast (this->timer_ids_curr_); +} + +template +void +ACE_Timer_Heap_T::push_freelist (long old_id) +{ + ACE_TRACE ("ACE_Timer_Heap_T::push_freelist"); + + // Since this ID has already been checked by one of the public + // functions, it's safe to cast it here. + size_t oldid = static_cast (old_id); + + // The freelist values in the are negative, so set the + // freed entry back to 'free'. If this is the new lowest value free + // timer ID that curr_ won't see on it's normal march through the list, + // remember it. + ACE_ASSERT (this->timer_ids_[oldid] >= 0 || this->timer_ids_[oldid] == -2); + if (this->timer_ids_[oldid] == -2) + --this->cur_limbo_; + else + --this->cur_size_; + this->timer_ids_[oldid] = -1; + if (oldid < this->timer_ids_min_free_ && oldid <= this->timer_ids_curr_) + this->timer_ids_min_free_ = oldid; + return; +} + +template +long +ACE_Timer_Heap_T::timer_id (void) +{ + ACE_TRACE ("ACE_Timer_Heap_T::timer_id"); + + // Return the next item off the freelist and use it as the timer id. + return this->pop_freelist (); +} + +// Checks if queue is empty. + +template +bool +ACE_Timer_Heap_T::is_empty (void) const +{ + ACE_TRACE ("ACE_Timer_Heap_T::is_empty"); + return this->cur_size_ == 0; +} + +template +ACE_Timer_Queue_Iterator_T & +ACE_Timer_Heap_T::iter (void) +{ + this->iterator_->first (); + return *this->iterator_; +} + +// Returns earliest time in a non-empty queue. + +template const ACE_Time_Value & +ACE_Timer_Heap_T::earliest_time (void) const +{ + ACE_TRACE ("ACE_Timer_Heap_T::earliest_time"); + return this->heap_[0]->get_timer_value (); +} + +template +void +ACE_Timer_Heap_T::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Timer_Heap_T::dump"); + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nmax_size_ = %d"), this->max_size_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ncur_size_ = %d"), this->cur_size_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ncur_limbo_= %d"), this->cur_limbo_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nids_curr_ = %d"), + this->timer_ids_curr_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nmin_free_ = %d"), + this->timer_ids_min_free_)); + + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nheap_ =\n"))); + + for (size_t i = 0; i < this->cur_size_; ++i) + { + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("%d\n"), + i)); + this->heap_[i]->dump (); + } + + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ntimer_ids_ =\n"))); + + for (size_t j = 0; j < this->max_size_; ++j) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("%d\t%d\n"), + j, + this->timer_ids_[j])); + + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +template +void +ACE_Timer_Heap_T::copy ( + size_t slot, + ACE_Timer_Node_T *moved_node) +{ + // Insert into its new location in the heap. + this->heap_[slot] = moved_node; + + ACE_ASSERT (moved_node->get_timer_id () >= 0 + && moved_node->get_timer_id () < (int) this->max_size_); + + // Update the corresponding slot in the parallel array. + this->timer_ids_[moved_node->get_timer_id ()] = static_cast (slot); +} + +// Remove the slot'th timer node from the heap, but do not reclaim its +// timer ID or change the size of this timer heap object. The caller of +// this function must call either free_node (to reclaim the timer ID +// and the timer node memory, as well as decrement the size of the queue) +// or reschedule (to reinsert the node in the heap at a new time). +template +ACE_Timer_Node_T * +ACE_Timer_Heap_T::remove (size_t slot) +{ + ACE_Timer_Node_T *removed_node = + this->heap_[slot]; + + // NOTE - the cur_size_ is being decremented since the queue has one + // less active timer in it. However, this ACE_Timer_Node is not being + // freed, and there is still a place for it in timer_ids_ (the timer ID + // is not being relinquished). The node can still be rescheduled, or + // it can be freed via free_node. + --this->cur_size_; + + // Only try to reheapify if we're not deleting the last entry. + + if (slot < this->cur_size_) + { + ACE_Timer_Node_T *moved_node = + this->heap_[this->cur_size_]; + + // Move the end node to the location being removed and update + // the corresponding slot in the parallel array. + this->copy (slot, moved_node); + + // If the time_value_> is great than or equal its + // parent it needs be moved down the heap. + size_t parent = ACE_HEAP_PARENT (slot); + + if (moved_node->get_timer_value () + >= this->heap_[parent]->get_timer_value ()) + this->reheap_down (moved_node, + slot, + ACE_HEAP_LCHILD (slot)); + else + this->reheap_up (moved_node, + slot, + parent); + } + + this->timer_ids_[removed_node->get_timer_id ()] = -2; + ++this->cur_limbo_; + return removed_node; +} + +template void +ACE_Timer_Heap_T::reheap_down ( + ACE_Timer_Node_T *moved_node, + size_t slot, + size_t child) +{ + // Restore the heap property after a deletion. + + while (child < this->cur_size_) + { + // Choose the smaller of the two children. + if (child + 1 < this->cur_size_ + && this->heap_[child + 1]->get_timer_value () + < this->heap_[child]->get_timer_value ()) + child++; + + // Perform a if the child has a larger timeout value than + // the . + if (this->heap_[child]->get_timer_value () + < moved_node->get_timer_value ()) + { + this->copy (slot, + this->heap_[child]); + slot = child; + child = ACE_HEAP_LCHILD (child); + } + else + // We've found our location in the heap. + break; + } + + this->copy (slot, moved_node); +} + +template +void +ACE_Timer_Heap_T::reheap_up ( + ACE_Timer_Node_T *moved_node, + size_t slot, + size_t parent) +{ + // Restore the heap property after an insertion. + + while (slot > 0) + { + // If the parent node is greater than the we need + // to copy it down. + if (moved_node->get_timer_value () + < this->heap_[parent]->get_timer_value ()) + { + this->copy (slot, this->heap_[parent]); + slot = parent; + parent = ACE_HEAP_PARENT (slot); + } + else + break; + } + + // Insert the new node into its proper resting place in the heap and + // update the corresponding slot in the parallel array. + this->copy (slot, + moved_node); +} + +template +void +ACE_Timer_Heap_T::insert ( + ACE_Timer_Node_T *new_node) +{ + if (this->cur_size_ + this->cur_limbo_ + 2 >= this->max_size_) + this->grow_heap (); + + this->reheap_up (new_node, + this->cur_size_, + ACE_HEAP_PARENT (this->cur_size_)); + this->cur_size_++; +} + +template +void +ACE_Timer_Heap_T::grow_heap (void) +{ + // All the containers will double in size from max_size_. + size_t new_size = this->max_size_ * 2; + +#if 0 + // Yikes - there's no way to flag a failure of going out of range of + // a 'long' - this is a problem that should be addressed at some point. + if (new_size > ACE_Numeric_Limits::max ()) + new_size = ACE_Numeric_Limits::max (); + + if (new_size <= this->max_size_) // We are already at the limit + { + errno = ENOMEM; + return -1; + } +#endif /* 0 */ + + // First grow the heap itself. + + ACE_Timer_Node_T **new_heap = 0; + + ACE_NEW (new_heap, + ACE_Timer_Node_T *[new_size]); + + ACE_OS::memcpy (new_heap, + this->heap_, + this->max_size_ * sizeof *new_heap); + delete [] this->heap_; + this->heap_ = new_heap; + + // Grow the array of timer ids. + + ssize_t *new_timer_ids = 0; + + ACE_NEW (new_timer_ids, + ssize_t[new_size]); + + ACE_OS::memcpy (new_timer_ids, + this->timer_ids_, + this->max_size_ * sizeof (ssize_t)); + + delete [] timer_ids_; + this->timer_ids_ = new_timer_ids; + + // And add the new elements to the end of the "freelist". + for (size_t i = this->max_size_; i < new_size; ++i) + this->timer_ids_[i] = -(static_cast (i) + 1); + + // Grow the preallocation array (if using preallocation) + if (this->preallocated_nodes_ != 0) + { + // Create a new array with max_size elements to link in to + // existing list. + ACE_NEW (this->preallocated_nodes_, + ACE_Timer_Node_T[this->max_size_]); + + // Add it to the set for later deletion + this->preallocated_node_set_.insert (this->preallocated_nodes_); + + // Link new nodes together (as for original list). + for (size_t k = 1; k < this->max_size_; ++k) + this->preallocated_nodes_[k - 1].set_next (&this->preallocated_nodes_[k]); + + // NULL-terminate the new list. + this->preallocated_nodes_[this->max_size_ - 1].set_next (0); + + // Link new array to the end of the existling list. + if (this->preallocated_nodes_freelist_ == 0) + this->preallocated_nodes_freelist_ = + &preallocated_nodes_[0]; + else + { + ACE_Timer_Node_T *previous = + this->preallocated_nodes_freelist_; + + for (ACE_Timer_Node_T *current = this->preallocated_nodes_freelist_->get_next (); + current != 0; + current = current->get_next ()) + previous = current; + + previous->set_next (&this->preallocated_nodes_[0]); + } + } + + this->max_size_ = new_size; + // Force rescan of list from beginning for a free slot (I think...) + // This fixed Bugzilla #2447. + this->timer_ids_min_free_ = this->max_size_; +} + +// Reschedule a periodic timer. This function must be called with the +// mutex lock held. + +template +void +ACE_Timer_Heap_T::reschedule ( + ACE_Timer_Node_T *expired) +{ + ACE_TRACE ("ACE_Timer_Heap_T::reschedule"); + + // If we are rescheduling, then the most recent call was to + // remove_first (). That called remove () to remove the node from the + // heap, but did not free the timer ID. The ACE_Timer_Node still has + // its assigned ID - just needs to be inserted at the new proper + // place, and the heap restored properly. + if (this->timer_ids_[expired->get_timer_id ()] == -2) + --this->cur_limbo_; + this->insert (expired); +} + +template +ACE_Timer_Node_T * +ACE_Timer_Heap_T::alloc_node (void) +{ + ACE_Timer_Node_T *temp = 0; + + // Only allocate a node if we are *not* using the preallocated heap. + if (this->preallocated_nodes_ == 0) + ACE_NEW_RETURN (temp, + ACE_Timer_Node_T, + 0); + else + { + // check to see if the heap needs to grow + if (this->preallocated_nodes_freelist_ == 0) + this->grow_heap (); + + temp = this->preallocated_nodes_freelist_; + + // Remove the first element from the freelist. + this->preallocated_nodes_freelist_ = + this->preallocated_nodes_freelist_->get_next (); + } + return temp; +} + +template +void +ACE_Timer_Heap_T::free_node ( + ACE_Timer_Node_T *node) +{ + // Return this timer id to the freelist. + this->push_freelist (node->get_timer_id ()); + + // Only free up a node if we are *not* using the preallocated heap. + if (this->preallocated_nodes_ == 0) + delete node; + else + { + node->set_next (this->preallocated_nodes_freelist_); + this->preallocated_nodes_freelist_ = node; + } +} + +// Insert a new timer that expires at time future_time; if interval is +// > 0, the handler will be reinvoked periodically. + +template +long +ACE_Timer_Heap_T::schedule_i ( + const TYPE &type, + const void *act, + const ACE_Time_Value &future_time, + const ACE_Time_Value &interval) +{ + ACE_TRACE ("ACE_Timer_Heap_T::schedule_i"); + + if ((this->cur_size_ + this->cur_limbo_) < this->max_size_) + { + // Obtain the next unique sequence number. + long const timer_id = this->timer_id (); + + // Obtain the memory to the new node. + ACE_Timer_Node_T *temp = 0; + + ACE_ALLOCATOR_RETURN (temp, + this->alloc_node (), + -1); + temp->set (type, + act, + future_time, + interval, + 0, + timer_id); + + this->insert (temp); + return timer_id; + } + else + return -1; +} + +// Locate and remove the single timer with a value of @a timer_id from +// the timer queue. + +template +int +ACE_Timer_Heap_T::cancel (long timer_id, + const void **act, + int dont_call) +{ + ACE_TRACE ("ACE_Timer_Heap_T::cancel"); + ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); + + // Locate the ACE_Timer_Node that corresponds to the timer_id. + + // Check to see if the timer_id is out of range + if (timer_id < 0 + || (size_t) timer_id > this->max_size_) + return 0; + + ssize_t timer_node_slot = this->timer_ids_[timer_id]; + + // Check to see if timer_id is still valid. + if (timer_node_slot < 0) + return 0; + + if (timer_id != this->heap_[timer_node_slot]->get_timer_id ()) + { + ACE_ASSERT (timer_id == this->heap_[timer_node_slot]->get_timer_id ()); + return 0; + } + else + { + ACE_Timer_Node_T *temp = + this->remove (timer_node_slot); + + // Call the close hooks. + int cookie = 0; + + // cancel_type() called once per . + this->upcall_functor ().cancel_type (*this, + temp->get_type (), + dont_call, + cookie); + + // cancel_timer() called once per . + this->upcall_functor ().cancel_timer (*this, + temp->get_type (), + dont_call, + cookie); + + if (act != 0) + *act = temp->get_act (); + + this->free_node (temp); + return 1; + } +} + +// Locate and update the inteval on the timer_id + +template +int +ACE_Timer_Heap_T::reset_interval (long timer_id, + const ACE_Time_Value &interval) +{ + ACE_TRACE ("ACE_Timer_Heap_T::reset_interval"); + ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); + + // Locate the ACE_Timer_Node that corresponds to the timer_id. + + // Check to see if the timer_id is out of range + if (timer_id < 0 + || (size_t) timer_id > this->max_size_) + return -1; + + ssize_t timer_node_slot = this->timer_ids_[timer_id]; + + // Check to see if timer_id is still valid. + if (timer_node_slot < 0) + return -1; + + if (timer_id != this->heap_[timer_node_slot]->get_timer_id ()) + { + ACE_ASSERT (timer_id == this->heap_[timer_node_slot]->get_timer_id ()); + return -1; + } + else + { + // Reset the timer interval + this->heap_[timer_node_slot]->set_interval (interval); + return 0; + } +} + +// Locate and remove all values of @a type from the timer queue. + +template +int +ACE_Timer_Heap_T::cancel (const TYPE &type, + int dont_call) +{ + ACE_TRACE ("ACE_Timer_Heap_T::cancel"); + + ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); + + int number_of_cancellations = 0; + + // Try to locate the ACE_Timer_Node that matches the timer_id. + + for (size_t i = 0; i < this->cur_size_; ) + { + if (this->heap_[i]->get_type () == type) + { + ACE_Timer_Node_T *temp = this->remove (i); + + ++number_of_cancellations; + + this->free_node (temp); + + // We reset to zero so that we don't miss checking any nodes + // if a reheapify occurs when a node is removed. There + // may be a better fix than this, however. + i = 0; + } + else + ++i; + } + + // Call the close hooks. + int cookie = 0; + + // cancel_type() called once per . + this->upcall_functor ().cancel_type (*this, + type, + dont_call, + cookie); + + for (int j = 0; + j < number_of_cancellations; + ++j) + { + // cancel_timer() called once per . + this->upcall_functor ().cancel_timer (*this, + type, + dont_call, + cookie); + } + + return number_of_cancellations; +} + +// Returns the earliest node or returns 0 if the heap is empty. + +template +ACE_Timer_Node_T * +ACE_Timer_Heap_T::remove_first (void) +{ + ACE_TRACE ("ACE_Timer_Heap_T::remove_first"); + + if (this->cur_size_ == 0) + return 0; + + return this->remove (0); +} + +template +ACE_Timer_Node_T * +ACE_Timer_Heap_T::get_first (void) +{ + ACE_TRACE ("ACE_Timer_Heap_T::get_first"); + + return this->cur_size_ == 0 ? 0 : this->heap_[0]; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_TIMER_HEAP_T_CPP */ diff --git a/dep/acelite/ace/Timer_Heap_T.h b/dep/acelite/ace/Timer_Heap_T.h new file mode 100644 index 00000000000..d6a6221aeed --- /dev/null +++ b/dep/acelite/ace/Timer_Heap_T.h @@ -0,0 +1,338 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Timer_Heap_T.h + * + * $Id: Timer_Heap_T.h 84619 2009-02-26 12:26:16Z johnnyw $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_TIMER_HEAP_T_H +#define ACE_TIMER_HEAP_T_H +#include /**/ "ace/pre.h" + +#include "ace/Timer_Queue_T.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Free_List.h" +#include "ace/Unbounded_Set.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Forward declaration +template +class ACE_Timer_Heap_T; + +/** + * @class ACE_Timer_Heap_Iterator_T + * + * @brief Iterates over an ACE_Timer_Heap_T. + * + * This is a generic iterator that can be used to visit every + * node of a timer queue. Be aware that it doesn't transverse + * in the order of timeout values. + */ +template +class ACE_Timer_Heap_Iterator_T : public ACE_Timer_Queue_Iterator_T +{ +public: + /// Constructor. + ACE_Timer_Heap_Iterator_T (ACE_Timer_Heap_T &); + + /// Destructor. + ~ACE_Timer_Heap_Iterator_T (void); + + /// Positions the iterator at the earliest node in the Timer Queue + virtual void first (void); + + /// Positions the iterator at the next node in the Timer Queue + virtual void next (void); + + /// Returns true when there are no more nodes in the sequence + virtual bool isdone (void) const; + + /// Returns the node at the current position in the sequence + virtual ACE_Timer_Node_T *item (void); + +protected: + /// Pointer to the ACE_Timer_Heap that we are iterating over. + ACE_Timer_Heap_T &timer_heap_; + + /// Position in the array where the iterator is at + size_t position_; +}; + +/** + * @class ACE_Timer_Heap_T + * + * @brief Provides a very fast and predictable timer implementation. + * + * This implementation uses a heap-based callout queue of + * absolute times. Therefore, in the average and worst case, + * scheduling, canceling, and expiring timers is O(log N) (where + * N is the total number of timers). In addition, we can also + * preallocate as many @c ACE_Timer_Node objects as there are slots + * in the heap. This allows us to completely remove the need for + * dynamic memory allocation, which is important for real-time + * systems. + */ +template +class ACE_Timer_Heap_T : public ACE_Timer_Queue_T +{ +public: + typedef ACE_Timer_Heap_Iterator_T HEAP_ITERATOR; + friend class ACE_Timer_Heap_Iterator_T; + + typedef ACE_Timer_Queue_T INHERITED; + + // = Initialization and termination methods. + /** + * The Constructor creates a heap with specified number of elements. + * This can also take in a upcall functor and freelist (if 0, then + * defaults will be created). + * + * @param size The maximum number of timers that can be + * inserted into the new object. + * @param preallocated Default false, true then all the memory + * for the @c ACE_Timer_Node objects will be pre-allocated. This saves + * time and is more predictable (though it requires more space). + * Otherwise, timer nodes are allocated as needed. + * @param freelist is the freelist of timer nodes. + * @param upcall_functor If 0 Timer Heap will create a default FUNCTOR. + */ + ACE_Timer_Heap_T (size_t size, + bool preallocated = false, + FUNCTOR *upcall_functor = 0, + ACE_Free_List > *freelist = 0); + + /** + * Default constructor. @c upcall_functor is the instance of the + * FUNCTOR to be used by the queue. If @c upcall_functor is 0, Timer + * Heap will create a default FUNCTOR. @c freelist is the freelist of + * timer nodes. If 0, then a default freelist will be created. The default + * size will be ACE_DEFAULT_TIMERS and there will be no preallocation. + */ + ACE_Timer_Heap_T (FUNCTOR *upcall_functor = 0, + ACE_Free_List > *freelist = 0); + + /// Destructor. + virtual ~ACE_Timer_Heap_T (void); + + /// True if heap is empty, else false. + virtual bool is_empty (void) const; + + /// Returns the time of the earliest node in the Timer_Queue. + /// Must be called on a non-empty queue. + virtual const ACE_Time_Value &earliest_time (void) const; + + /** + * Resets the interval of the timer represented by @a timer_id to + * @a interval, which is specified in relative time to the current + * . If @a interval is equal to + * ACE_Time_Value::zero, the timer will become a non-rescheduling + * timer. Returns 0 if successful, -1 if not. + */ + virtual int reset_interval (long timer_id, + const ACE_Time_Value &interval); + + /** + * Cancel all timers associated with @a type. If @a dont_call_handle_close + * is 0 then the will be invoked. Returns number of timers + * cancelled. + */ + virtual int cancel (const TYPE &type, + int dont_call_handle_close = 1); + + /** + * Cancel the single timer that matches the @a timer_id value (which + * was returned from the method). If act is non-NULL + * then it will be set to point to the ``magic cookie'' argument + * passed in when the timer was registered. This makes it possible + * to free up the memory and avoid memory leaks. If @a dont_call_handle_close + * is 0 then the will be invoked. Returns 1 if cancellation + * succeeded and 0 if the @a timer_id wasn't found. + */ + virtual int cancel (long timer_id, + const void **act = 0, + int dont_call_handle_close = 1); + + /// Returns a pointer to this ACE_Timer_Queue's iterator. + virtual ACE_Timer_Queue_Iterator_T &iter (void); + + /** + * Removes the earliest node from the queue and returns it. Note that + * the timer is removed from the heap, but is not freed, and its ID + * is not reclaimed. The caller is responsible for calling either + * @c reschedule() or @c free_node() after this function returns. Thus, + * this function is for support of @c ACE_Timer_Queue::expire and + * should not be used unadvisedly in other conditions. + */ + ACE_Timer_Node_T *remove_first (void); + + /// Dump the state of an object. + virtual void dump (void) const; + + /// Reads the earliest node from the queue and returns it. + virtual ACE_Timer_Node_T *get_first (void); + +protected: + + /** + * Schedule a timer that may optionally auto-reset. + * Schedule @a type that will expire at @a future_time, + * which is specified in absolute time. If it expires then @a act is + * passed in as the value to the . If @a interval is != to + * ACE_Time_Value::zero then it is used to reschedule the @a type + * automatically, using relative time to the current . + * This method returns a that uniquely identifies the the + * @a type entry in an internal list. This can be used to + * cancel the timer before it expires. The cancellation ensures + * that are unique up to values of greater than 2 + * billion timers. As long as timers don't stay around longer than + * this there should be no problems with accidentally deleting the + * wrong timer. Returns -1 on failure (which is guaranteed never to + * be a valid ). + */ + virtual long schedule_i (const TYPE &type, + const void *act, + const ACE_Time_Value &future_time, + const ACE_Time_Value &interval); + + /// Reschedule an "interval" ACE_Timer_Node. + virtual void reschedule (ACE_Timer_Node_T *); + + /// Factory method that allocates a new node (uses operator new if + /// we're *not* preallocating, otherwise uses an internal freelist). + virtual ACE_Timer_Node_T *alloc_node (void); + + /** + * Factory method that frees a previously allocated node (uses + * operator delete if we're *not* preallocating, otherwise uses an + * internal freelist). + */ + virtual void free_node (ACE_Timer_Node_T *); + +private: + /// Remove and return the @a sloth ACE_Timer_Node and restore the + /// heap property. + ACE_Timer_Node_T *remove (size_t slot); + + /// Insert @a new_node into the heap and restore the heap property. + void insert (ACE_Timer_Node_T *new_node); + + /** + * Doubles the size of the heap and the corresponding timer_ids array. + * If preallocation is used, will also double the size of the + * preallocated array of ACE_Timer_Nodes. + */ + void grow_heap (void); + + /// Restore the heap property, starting at @a slot. + void reheap_up (ACE_Timer_Node_T *new_node, + size_t slot, + size_t parent); + + /// Restore the heap property, starting at @a slot. + void reheap_down (ACE_Timer_Node_T *moved_node, + size_t slot, + size_t child); + + /// Copy @a moved_node into the @a slot slot of and move + /// @a slot into the corresponding slot in the array. + void copy (size_t slot, ACE_Timer_Node_T *moved_node); + + /** + * Returns a timer id that uniquely identifies this timer. This id + * can be used to cancel a timer via the method. The + * timer id returned from this method will never == -1 to avoid + * conflicts with other failure return values. + */ + long timer_id (void); + + /// Pops and returns a new timer id from the freelist. + long pop_freelist (void); + + /// Pushes @a old_id onto the freelist. + void push_freelist (long old_id); + + /// Maximum size of the heap. + size_t max_size_; + + /// Current size of the heap. + size_t cur_size_; + + /// Number of heap entries in transition (removed from the queue, but + /// not freed) and may be rescheduled or freed. + size_t cur_limbo_; + + /// Iterator used to expire timers. + HEAP_ITERATOR *iterator_; + + /** + * Current contents of the Heap, which is organized as a "heap" of + * ACE_Timer_Node *'s. In this context, a heap is a "partially + * ordered, almost complete" binary tree, which is stored in an + * array. + */ + ACE_Timer_Node_T **heap_; + + /** + * An array of "pointers" that allows each ACE_Timer_Node in the + * to be located in O(1) time. Basically, + * contains the slot in the array where an ACE_Timer_Node + * * with timer id \ resides. Thus, the timer id passed back from + * is really a slot into the array. The + * array serves two purposes: negative values are + * indications of free timer IDs, whereas positive values are + * "pointers" into the array for assigned timer IDs. + */ + ssize_t *timer_ids_; + + /// "Pointer" to the element in the array that was + /// last given out as a timer ID. + size_t timer_ids_curr_; + + /// Index representing the lowest timer ID that has been freed. When + /// the timer_ids_next_ value wraps around, it starts back at this + /// point. + size_t timer_ids_min_free_; + + /** + * If this is non-0, then we preallocate number of + * ACE_Timer_Node objects in order to reduce dynamic allocation + * costs. In auto-growing implementation, this points to the + * last array of nodes allocated. + */ + ACE_Timer_Node_T *preallocated_nodes_; + + /// This points to the head of the freelist, + /// which is organized as a stack. + ACE_Timer_Node_T *preallocated_nodes_freelist_; + + /// Set of pointers to the arrays of preallocated timer nodes. + /// Used to delete the allocated memory when required. + ACE_Unbounded_Set *> preallocated_node_set_; + + // = Don't allow these operations for now. + ACE_UNIMPLEMENTED_FUNC (ACE_Timer_Heap_T (const ACE_Timer_Heap_T &)) + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Timer_Heap_T &)) +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Timer_Heap_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Timer_Heap_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" +#endif /* ACE_TIMER_HEAP_T_H */ diff --git a/dep/acelite/ace/Timer_List.h b/dep/acelite/ace/Timer_List.h new file mode 100644 index 00000000000..f2d9cc2a458 --- /dev/null +++ b/dep/acelite/ace/Timer_List.h @@ -0,0 +1,42 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Timer_List.h + * + * $Id: Timer_List.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Doug Schmidt + */ +//============================================================================= + + +#ifndef ACE_TIMER_LIST_H +#define ACE_TIMER_LIST_H +#include /**/ "ace/pre.h" + +#include "ace/Timer_List_T.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// The following typedefs are here for ease of use and backward +// compatibility. + +typedef ACE_Timer_List_T, + ACE_SYNCH_RECURSIVE_MUTEX> + ACE_Timer_List; + +typedef ACE_Timer_List_Iterator_T, + ACE_SYNCH_RECURSIVE_MUTEX> + ACE_Timer_List_Iterator; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" +#endif /* ACE_TIMER_LIST_H */ diff --git a/dep/acelite/ace/Timer_List_T.cpp b/dep/acelite/ace/Timer_List_T.cpp new file mode 100644 index 00000000000..c3b837bb289 --- /dev/null +++ b/dep/acelite/ace/Timer_List_T.cpp @@ -0,0 +1,418 @@ +// $Id: Timer_List_T.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#ifndef ACE_TIMER_LIST_T_C +#define ACE_TIMER_LIST_T_C + +#include "ace/Timer_List_T.h" +#include "ace/Guard_T.h" +#include "ace/Log_Msg.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_RCSID(ace, Timer_List_T, "$Id: Timer_List_T.cpp 80826 2008-03-04 14:51:23Z wotte $") + +// Default Constructor + +template +ACE_Timer_List_Iterator_T::ACE_Timer_List_Iterator_T (List& lst) + : list_ (lst) +{ + this->first(); +} + +template +ACE_Timer_List_Iterator_T::~ACE_Timer_List_Iterator_T (void) +{ +} + +// Positions the iterator at the node right after the dummy node + +template void +ACE_Timer_List_Iterator_T::first (void) +{ + this->current_node_ = this->list_.get_first(); +} + +// Positions the iterator at the next node in the Timer Queue + +template void +ACE_Timer_List_Iterator_T::next (void) +{ + // Make sure that if we are at the end, we don't wrap around + if (! this->isdone()) + this->current_node_ = this->current_node_->get_next (); + if (this->current_node_ == this->list_.head_) + this->current_node_ = 0; +} + +// Returns true when we are at + +template bool +ACE_Timer_List_Iterator_T::isdone (void) const +{ + return this->current_node_ == 0; +} + +// Returns the node at or 0 if we are at the end + +template ACE_Timer_Node_T * +ACE_Timer_List_Iterator_T::item (void) +{ + if (! this->isdone()) + return this->current_node_; + return 0; +} + +/////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// + +// Return our instance of the iterator + +template ACE_Timer_Queue_Iterator_T & +ACE_Timer_List_T::iter (void) +{ + this->iterator_->first (); + return *this->iterator_; +} + +// Create an empty list. + +template +ACE_Timer_List_T::ACE_Timer_List_T (FUNCTOR* uf, FreeList* fl) + : Base(uf, fl) + , head_ (new ACE_Timer_Node_T) + , id_counter_ (0) +{ + ACE_TRACE ("ACE_Timer_List_T::ACE_Timer_List_T"); + + this->head_->set_next (this->head_); + this->head_->set_prev (this->head_); + + ACE_NEW (iterator_, Iterator(*this)); +} + + +// Checks if list is empty. + +template bool +ACE_Timer_List_T::is_empty (void) const +{ + ACE_TRACE ("ACE_Timer_List_T::is_empty"); + return this->get_first_i() == 0; +} + + +// Returns earliest time in a non-empty list. + +template const ACE_Time_Value & +ACE_Timer_List_T::earliest_time (void) const +{ + ACE_TRACE ("ACE_Timer_List_T::earliest_time"); + ACE_Timer_Node_T* first = this->get_first_i(); + if (first != 0) + return first->get_timer_value (); + return ACE_Time_Value::zero; +} + + +// Remove all remaining items in the list. + +template +ACE_Timer_List_T::~ACE_Timer_List_T (void) +{ + ACE_TRACE ("ACE_Timer_List_T::~ACE_Timer_List_T"); + ACE_MT (ACE_GUARD (ACE_LOCK, ace_mon, this->mutex_)); + + delete iterator_; + + if (!this->is_empty()) + { + for (ACE_Timer_Node_T* n = this->get_first(); + n != this->head_; + ) + { + this->upcall_functor ().deletion (*this, + n->get_type(), + n->get_act()); + + ACE_Timer_Node_T *next = + n->get_next (); + + this->free_node (n); + + n = next; + } + } + + // delete the dummy node + delete this->head_; +} + +template void +ACE_Timer_List_T::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Timer_List_T::dump"); + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + + int count = 0; + + ACE_Timer_Node_T* n = this->get_first_i(); + if (n != 0) { + for (; n != this->head_; n = n->get_next()) { + ++count; + } + } + + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nsize_ = %d"), count)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + + +// Reschedule a periodic timer. This function must be called with the +// lock held. + +template void +ACE_Timer_List_T::reschedule (ACE_Timer_Node_T* n) +{ + ACE_TRACE ("ACE_Timer_List_T::reschedule"); + this->schedule_i(n, n->get_timer_value()); +} + + +// Insert a new handler that expires at time future_time; if interval +// is > 0, the handler will be reinvoked periodically. + +template long +ACE_Timer_List_T::schedule_i (const TYPE &type, + const void *act, + const ACE_Time_Value &future_time, + const ACE_Time_Value &interval) +{ + ACE_TRACE ("ACE_Timer_List_T::schedule_i"); + + ACE_Timer_Node_T* n = this->alloc_node(); + + if (n != 0) + { + long id = this->id_counter_++; + + if (id != -1) { + n->set (type, act, future_time, interval, 0, 0, id); + this->schedule_i (n, future_time); + } + return id; + } + + // Failure return + errno = ENOMEM; + return -1; +} + +/// The shared scheduling functionality between schedule() and reschedule() +template void +ACE_Timer_List_T::schedule_i (ACE_Timer_Node_T* n, + const ACE_Time_Value& expire) +{ + if (this->is_empty()) { + n->set_prev(this->head_); + n->set_next(this->head_); + this->head_->set_prev(n); + this->head_->set_next(n); + return; + } + + // We always want to search backwards from the tail of the list, because + // this minimizes the search in the extreme case when lots of timers are + // scheduled for exactly the same time, and it also assumes that most of + // the timers will be scheduled later than existing timers. + ACE_Timer_Node_T* p = this->head_->get_prev(); + while (p != this->head_ && p->get_timer_value() > expire) + p = p->get_prev(); + + // insert after + n->set_prev(p); + n->set_next(p->get_next()); + p->get_next()->set_prev(n); + p->set_next(n); +} + +template +ACE_Timer_Node_T* +ACE_Timer_List_T::find_node (long timer_id) const +{ + ACE_Timer_Node_T* n = this->get_first_i(); + if (n == 0) + return 0; + + for (; n != this->head_; n = n->get_next()) { + if (n->get_timer_id() == timer_id) { + return n; + } + } + return 0; +} + +// Locate and update the inteval on the timer_id +template int +ACE_Timer_List_T::reset_interval (long timer_id, + const ACE_Time_Value &interval) +{ + ACE_TRACE ("ACE_Timer_List_T::reset_interval"); + ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); + ACE_Timer_Node_T* n = this->find_node(timer_id); + if (n != 0) { + n->set_interval(interval); // The interval will take effect the next time this node is expired. + return 0; + } + return -1; +} + +// Locate and remove the single with a value of +// @a timer_id from the timer queue. +template int +ACE_Timer_List_T::cancel (long timer_id, + const void **act, + int skip_close) +{ + ACE_TRACE ("ACE_Timer_List_T::cancel"); + ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); + ACE_Timer_Node_T* n = this->find_node(timer_id); + if (n != 0) + { + if (act != 0) + *act = n->get_act (); + + // Call the close hooks. + int cookie = 0; + + // cancel_type() called once per . + this->upcall_functor ().cancel_type (*this, + n->get_type (), + skip_close, + cookie); + + // cancel_timer() called once per . + this->upcall_functor ().cancel_timer (*this, + n->get_type (), + skip_close, + cookie); + + this->cancel_i (n); + + return 1; + } + + return 0; +} + +// Locate and remove all values of from the timer queue. +template int +ACE_Timer_List_T::cancel (const TYPE &type, int skip_close) +{ + ACE_TRACE ("ACE_Timer_List_T::cancel"); + + int num_canceled = 0; // Note : Technically this can overflow. + + int cookie = 0; + + ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); + + if (!this->is_empty ()) + { + for (ACE_Timer_Node_T* n = this->get_first(); + n != this->head_; + ) + { + if (n->get_type() == type) // Note: Typically Type is an ACE_Event_Handler* + { + ++num_canceled; + + ACE_Timer_Node_T* tmp = n; + n = n->get_next(); + + this->cancel_i (tmp); + } + else + { + n = n->get_next(); + } + } + } + + // Call the close hooks. + + // cancel_type() called once per . + this->upcall_functor ().cancel_type (*this, + type, + skip_close, + cookie); + + for (int i = 0; + i < num_canceled; + ++i) + { + // cancel_timer() called once per . + this->upcall_functor ().cancel_timer (*this, + type, + skip_close, + cookie); + } + + return num_canceled; +} + +template void +ACE_Timer_List_T::unlink (ACE_Timer_Node_T* n) +{ + n->get_prev()->set_next(n->get_next()); + n->get_next()->set_prev(n->get_prev()); + n->set_prev(0); + n->set_next(0); +} + +/// Shared subset of the two cancel() methods. +template void +ACE_Timer_List_T::cancel_i (ACE_Timer_Node_T* n) +{ + this->unlink (n); + this->free_node (n); +} + +// Reads the first node on the list and returns it. +template ACE_Timer_Node_T * +ACE_Timer_List_T::get_first (void) +{ + ACE_TRACE ("ACE_Timer_List_T::get_first"); + return this->get_first_i(); +} + +template ACE_Timer_Node_T * +ACE_Timer_List_T::get_first_i (void) const +{ + ACE_TRACE ("ACE_Timer_List_T::get_first_i"); + ACE_Timer_Node_T* first = this->head_->get_next(); + if (first != this->head_) // Note : is_empty() uses get_first() + return first; + return 0; +} + + +// Removes the first node on the list and returns it. + +template ACE_Timer_Node_T * +ACE_Timer_List_T::remove_first (void) +{ + ACE_TRACE ("ACE_Timer_List_T::remove_first"); + ACE_Timer_Node_T* first = this->get_first(); + if (first != 0) { + this->unlink(first); + return first; + } + return 0; +} + +#endif /* ACE_TIMER_LIST_T_C */ diff --git a/dep/acelite/ace/Timer_List_T.h b/dep/acelite/ace/Timer_List_T.h new file mode 100644 index 00000000000..cabd47aeaf0 --- /dev/null +++ b/dep/acelite/ace/Timer_List_T.h @@ -0,0 +1,226 @@ +/* -*- C++ -*- */ + +//============================================================================= +/** + * @file Timer_List_T.h + * + * $Id: Timer_List_T.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_TIMER_LIST_T_H +#define ACE_TIMER_LIST_T_H +#include /**/ "ace/pre.h" + +#include "ace/Timer_Queue_T.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +// Forward declaration. +template +class ACE_Timer_List_T; + +/** + * @class ACE_Timer_List_Iterator_T + * + * @brief Iterates over an ACE_Timer_List. + * + * This is a generic iterator that can be used to visit every + * node of a timer queue. + */ +template +class ACE_Timer_List_Iterator_T +: public ACE_Timer_Queue_Iterator_T +{ +public: + typedef ACE_Timer_List_T List; + /// Constructor. + ACE_Timer_List_Iterator_T (List& lst); + + /// Destructor. + virtual ~ACE_Timer_List_Iterator_T (void); + + /// Positions the iterator at the earliest node in the Timer Queue + virtual void first (void); + + /// Positions the iterator at the next node in the Timer Queue + virtual void next (void); + + /// Returns true when there are no more nodes in the sequence + virtual bool isdone (void) const; + + /// Returns the node at the current position in the sequence + virtual ACE_Timer_Node_T *item (void); + +protected: + /// Pointer to the ACE_Timer_List that we are iterating over. + List& list_; + + /// Current position in the ACE_Timer_List + ACE_Timer_Node_T* current_node_; +}; + +/** + * @class ACE_Timer_List_T + * + * @brief Provides a simple implementation of timers. + * + * This implementation uses a linked list of absolute times. + * Therefore, in the average case, scheduling and canceling + * timers is O(N) (where N is the total number of timers) and + * expiring timers is O(K) (where K is the total number of timers + * that are < the current time of day). + * More clever implementations could use a delta-list, a heap, + * or timing wheels, etc. For instance, ACE_Timer_Heap + * is a subclass of ACE_Timer_List that implements a + * heap-based callout queue. For most applications, the + * ACE_Timer_Heap will perform substantially faster than the + * ACE_Timer_List. + */ +template +class ACE_Timer_List_T : public ACE_Timer_Queue_T +{ +public: + /// Type of iterator + typedef ACE_Timer_List_Iterator_T Iterator; + + /// Iterator is a friend + friend class ACE_Timer_List_Iterator_T; + + typedef ACE_Timer_Node_T Node; + /// Type inherited from + typedef ACE_Timer_Queue_T Base; + typedef ACE_Free_List FreeList; + + // = Initialization and termination methods. + /** + * Default constructor. @a upcall_functor is the instance of the + * FUNCTOR to be used by the list. If @a upcall_functor is 0, a + * default FUNCTOR will be created. @a freelist is the freelist of + * timer nodes. If 0, then a default freelist will be created. + */ + ACE_Timer_List_T (FUNCTOR* upcall_functor = 0, FreeList* freelist = 0); + + /// Destructor + virtual ~ACE_Timer_List_T (void); + + /// True if queue is empty, else false. + virtual bool is_empty (void) const; + + /// Returns the time of the earlier node in the ACE_Timer_List. + /// Must be called on a non-empty queue. + virtual const ACE_Time_Value& earliest_time (void) const; + + /** + * Resets the interval of the timer represented by @a timer_id to + * @a interval, which is specified in relative time to the current + * . If @a interval is equal to + * ACE_Time_Value::zero, the timer will become a non-rescheduling + * timer. Returns 0 if successful, -1 if not. + */ + virtual int reset_interval (long timer_id, + const ACE_Time_Value& interval); + + /** + * Cancel all timers associated with @a type. If dont_call_handle_close is 0 + * then the @a functor will be invoked. Returns the number of timers + * cancelled. + */ + virtual int cancel (const TYPE& type, + int dont_call_handle_close = 1); + + /** + * Cancel the single timer that matches the @a timer_id value (which + * was returned from the method). If act is non-NULL + * then it will be set to point to the ``magic cookie'' argument + * passed in when the timer was registered. This makes it possible + * to free up the memory and avoid memory leaks. If is + * 0 then the will be invoked. Returns 1 if cancellation + * succeeded and 0 if the @a timer_id wasn't found. + */ + virtual int cancel (long timer_id, + const void** act = 0, + int dont_call_handle_close = 1); + + /// Returns a pointer to this ACE_Timer_Queue's iterator. + virtual ACE_Timer_Queue_Iterator_T& iter (void); + + /// Removes the earliest node from the queue and returns it + virtual ACE_Timer_Node_T* remove_first (void); + + /// Dump the state of an object. + virtual void dump (void) const; + + /// Reschedule an "interval" ACE_Timer_Node_T. This should be private + /// but for now it needs to be public for + virtual void reschedule (ACE_Timer_Node_T *); + + /// Reads the earliest node from the queue and returns it. + virtual ACE_Timer_Node_T* get_first (void); + +private: + + /** + * Schedule @a type that will expire at @a future_time, which is + * specified in absolute time. If it expires then @a act is passed + * in as the value to the . If @a interval is != to + * ACE_Time_Value::zero then it is used to reschedule the @a type + * automatically, using relative time to the current . + * This method returns a that uniquely identifies the the + * @a type entry in an internal list. This can be used to + * cancel the timer before it expires. The cancellation ensures + * that are unique up to values of greater than 2 + * billion timers. As long as timers don't stay around longer than + * this there should be no problems with accidentally deleting the + * wrong timer. Returns -1 on failure (which is guaranteed never to + * be a valid ). + */ + virtual long schedule_i (const TYPE& type, + const void* act, + const ACE_Time_Value& future_time, + const ACE_Time_Value& interval); + + void schedule_i(ACE_Timer_Node_T* n, const ACE_Time_Value& exp); + + ACE_Timer_Node_T* find_node(long timer_id) const; + + void cancel_i (ACE_Timer_Node_T* n); + + void unlink (ACE_Timer_Node_T* n); + + ACE_Timer_Node_T* get_first_i(void) const; + +private: + + /// Pointer to linked list of . + ACE_Timer_Node_T* head_; + + /// Iterator used to expire timers. + Iterator* iterator_; + + /** + * Keeps track of the timer id that uniquely identifies each timer. + * This id can be used to cancel a timer via the + * method. + */ + long id_counter_; + + // = Don't allow these operations for now. + ACE_UNIMPLEMENTED_FUNC (ACE_Timer_List_T (const ACE_Timer_List_T &)) + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Timer_List_T &)) +}; + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Timer_List_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Timer_List_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" +#endif /* ACE_TIMER_LIST_T_H */ diff --git a/dep/acelite/ace/Timer_Queue.h b/dep/acelite/ace/Timer_Queue.h new file mode 100644 index 00000000000..4644aa1b43d --- /dev/null +++ b/dep/acelite/ace/Timer_Queue.h @@ -0,0 +1,52 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Timer_Queue.h + * + * $Id: Timer_Queue.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Douglas C. Schmidt + * @author Irfan Pyarali + */ +//============================================================================= + +#ifndef ACE_TIMER_QUEUE_H +#define ACE_TIMER_QUEUE_H + +#include /**/ "ace/pre.h" + +#include "ace/Synch_Traits.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Timer_Queuefwd.h" +#include "ace/Timer_Queue_T.h" +#if defined (ACE_HAS_THREADS) +# include "ace/Recursive_Thread_Mutex.h" +#else +# include "ace/Null_Mutex.h" +#endif /* ACE_HAS_THREADS */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// The following typedef are here for ease of use and backward +// compatibility. +typedef ACE_Timer_Node_Dispatch_Info_T + ACE_Timer_Node_Dispatch_Info; + +typedef ACE_Timer_Node_T + ACE_Timer_Node; + +typedef ACE_Timer_Queue_Iterator_T, + ACE_SYNCH_RECURSIVE_MUTEX> + ACE_Timer_Queue_Iterator; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" + +#endif /* ACE_TIMER_QUEUE_H */ diff --git a/dep/acelite/ace/Timer_Queue_Adapters.cpp b/dep/acelite/ace/Timer_Queue_Adapters.cpp new file mode 100644 index 00000000000..54e8f8ade5f --- /dev/null +++ b/dep/acelite/ace/Timer_Queue_Adapters.cpp @@ -0,0 +1,361 @@ +// $Id: Timer_Queue_Adapters.cpp 89482 2010-03-15 07:58:50Z johnnyw $ + +#ifndef ACE_TIMER_QUEUE_ADAPTERS_CPP +#define ACE_TIMER_QUEUE_ADAPTERS_CPP + +#include "ace/Timer_Queue_Adapters.h" + +#if defined (ACE_HAS_DEFERRED_TIMER_COMMANDS) +#include "ace/Functor.h" +#endif /* ACE_HAS_DEFERRED_TIMER_COMMANDS */ + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +# if !defined (__ACE_INLINE__) +# include "ace/Timer_Queue_Adapters.inl" +# endif /* __ACE_INLINE__ */ + +#include "ace/Signal.h" +#include "ace/OS_NS_unistd.h" +#include "ace/OS_NS_sys_time.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template TQ & +ACE_Async_Timer_Queue_Adapter::timer_queue (void) +{ + return this->timer_queue_; +} + +template int +ACE_Async_Timer_Queue_Adapter::cancel (long timer_id, + const void **act) +{ + // Block designated signals. + ACE_Sig_Guard sg (&this->mask_); + ACE_UNUSED_ARG (sg); + + return this->timer_queue_.cancel (timer_id, act); +} + +template int +ACE_Async_Timer_Queue_Adapter::expire (void) +{ + // Block designated signals. + ACE_Sig_Guard sg (&this->mask_); + ACE_UNUSED_ARG (sg); + + return this->timer_queue_.expire (); +} + +template int +ACE_Async_Timer_Queue_Adapter::schedule_ualarm (void) +{ + ACE_Time_Value tv = this->timer_queue_.earliest_time () + - this->timer_queue_.gettimeofday (); + + // Beware of negative times and zero times (which cause problems for + // ). + if (tv < ACE_Time_Value::zero) + tv = ACE_Time_Value (0, 1); + + // @@ This code should be clever enough to avoid updating the + // if we haven't actually changed the earliest time. + // Schedule a new timer. + ACE_OS::ualarm (tv); + return 0; +} + +template long +ACE_Async_Timer_Queue_Adapter::schedule (TYPE eh, + const void *act, + const ACE_Time_Value &future_time, + const ACE_Time_Value &interval) +{ + ACE_UNUSED_ARG (act); + ACE_UNUSED_ARG (interval); + + // Block designated signals. + ACE_Sig_Guard sg (&this->mask_); + ACE_UNUSED_ARG (sg); + + // @@ We still need to implement interval timers... + long tid = this->timer_queue_.schedule (eh, act, future_time); + + if (tid == -1) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("schedule_timer")), + -1); + + if (this->schedule_ualarm () == -1) + return 0; + + return tid; +} + +template +ACE_Async_Timer_Queue_Adapter::ACE_Async_Timer_Queue_Adapter (ACE_Sig_Set *mask) + // If == 0, block *all* signals when the SIGARLM handler is + // running, else just block those in the mask. + : mask_ (mask) +{ + // The following code is necessary to selectively "block" certain + // signals when SIGALRM is running. Also, we always restart system + // calls that are interrupted by the signals. + + ACE_Sig_Action sa ((ACE_SignalHandler) 0, + this->mask_, + SA_RESTART); + + if (this->sig_handler_.register_handler (SIGALRM, this, &sa) == -1) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("register_handler"))); +} + +// This is the signal handler function for the asynchronous timer +// list. It gets invoked asynchronously when the SIGALRM signal +// occurs. + +template int +ACE_Async_Timer_Queue_Adapter::handle_signal (int signum, + siginfo_t *, + ucontext_t *) +{ + switch (signum) + { + case SIGALRM: + { + // Expire the pending timers. + + // @@ We need to figure out how to implement interval + // timers... + this->timer_queue_.expire (); + + // Only schedule a new timer if there is one in the list. + + // @@ This code should also become smarter to avoid + // unnecessary calls to ualarm(). + if (this->timer_queue_.is_empty () == 0) + return this->schedule_ualarm (); + else + return 0; + /* NOTREACHED */ + } + default: + ACE_ERROR_RETURN ((LM_ERROR, + "unexpected signal %S\n", + signum), + -1); + /* NOTREACHED */ + } +} + +template +ACE_Thread_Timer_Queue_Adapter::ACE_Thread_Timer_Queue_Adapter (ACE_Thread_Manager *tm, + TQ* timer_queue) + : ACE_Task_Base (tm), + timer_queue_(timer_queue), + delete_timer_queue_(false), + condition_ (mutex_), + active_ (true), // Assume that we start in active mode. + thr_id_ (ACE_OS::NULL_thread) +{ + if (timer_queue_ == 0) + { + ACE_NEW (this->timer_queue_, + TQ); + this->delete_timer_queue_ = true; + } +} + +template +ACE_Thread_Timer_Queue_Adapter::~ACE_Thread_Timer_Queue_Adapter (void) +{ + if (this->delete_timer_queue_) + { + delete this->timer_queue_; + this->timer_queue_ = 0; + this->delete_timer_queue_ = false; + } +} + +template ACE_SYNCH_RECURSIVE_MUTEX & +ACE_Thread_Timer_Queue_Adapter::mutex (void) +{ + return this->mutex_; +} + +template long +ACE_Thread_Timer_Queue_Adapter::schedule + (TYPE handler, + const void *act, + const ACE_Time_Value &future_time, + const ACE_Time_Value &interval) +{ + ACE_GUARD_RETURN (ACE_SYNCH_RECURSIVE_MUTEX, guard, this->mutex_, -1); + + long result = this->timer_queue_->schedule (handler, act, future_time, interval); + this->condition_.signal (); + return result; +} + +template int +ACE_Thread_Timer_Queue_Adapter::cancel (long timer_id, + const void **act) +{ + ACE_GUARD_RETURN (ACE_SYNCH_RECURSIVE_MUTEX, guard, this->mutex_, -1); + + int result = this->timer_queue_->cancel (timer_id, act); + condition_.signal (); + return result; +} + +template void +ACE_Thread_Timer_Queue_Adapter::deactivate (void) +{ + ACE_GUARD (ACE_SYNCH_RECURSIVE_MUTEX, guard, this->mutex_); + + this->active_ = false; + this->condition_.signal (); +} + +template int +ACE_Thread_Timer_Queue_Adapter::svc (void) +{ + ACE_GUARD_RETURN (ACE_SYNCH_RECURSIVE_MUTEX, guard, this->mutex_, -1); + + this->thr_id_ = ACE_Thread::self (); + + // Thread cancellation point, if ACE supports it. + // + // Note: This call generates a warning under Solaris because the header + // file /usr/include/pthread.h redefines the routine argument. This + // is a bug in the Solaris header files and has nothing to do with + // ACE. +# if !defined (ACE_LACKS_PTHREAD_CANCEL) + ACE_PTHREAD_CLEANUP_PUSH (&this->condition_.mutex ().get_nesting_mutex ()); +# endif /* ACE_LACKS_PTHREAD_CANCEL */ + + while (this->active_) + { +# if defined (ACE_HAS_DEFERRED_TIMER_COMMANDS) + // Temporarily suspend ownership of the timer queue mutex in + // order to dispatch deferred execution commands. These + // commands are to be treated as executing in a context + // "external" to the timer queue adapter, and thus must compete + // separately for this lock. + mutex_.release (); + this->dispatch_commands (); + + // Re-acquire ownership of the timer queue mutex in order to + // restore the "internal" timer queue adapter context + mutex_.acquire (); +# endif /* ACE_HAS_DEFERRED_TIMER_COMMANDS */ + + // If the queue is empty, sleep until there is a change on it. + if (this->timer_queue_->is_empty ()) + this->condition_.wait (); + else + { + // Compute the remaining time, being careful not to sleep + // for "negative" amounts of time. + ACE_Time_Value const tv_curr = this->timer_queue_->gettimeofday (); + ACE_Time_Value const tv_earl = this->timer_queue_->earliest_time (); + + if (tv_earl > tv_curr) + { + // The earliest time on the Timer_Queue is in future, so + // use ACE_OS::gettimeofday() to convert the tv to the + // absolute time. + ACE_Time_Value const tv = ACE_OS::gettimeofday () + (tv_earl - tv_curr); + // ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("waiting until %u.%3.3u secs\n"), + // tv.sec(), tv.msec())); + this->condition_.wait (&tv); + } + } + + // Expire timers anyway, at worst this is a no-op. + this->timer_queue_->expire (); + } + + // Thread cancellation point, if ACE supports it. +# if !defined (ACE_LACKS_PTHREAD_CANCEL) + ACE_PTHREAD_CLEANUP_POP (0); +# endif /* ACE_LACKS_PTHREAD_CANCEL */ + + return 0; +} + +template int +ACE_Thread_Timer_Queue_Adapter::activate (long flags, + int , + int , + long priority, + int grp_id, + ACE_Task_Base *task, + ACE_hthread_t [], + void *stack[], + size_t stack_size[], + ACE_thread_t thread_ids[], + const char* thr_name[]) +{ + // Make sure to set this flag in case we were deactivated earlier. + this->active_ = true; + + // Make sure that we only allow a single thread to be spawned for + // our adapter. Otherwise, too many weird things can happen. + return ACE_Task_Base::activate (flags, 1, 0, priority, grp_id, task, 0, + stack, stack_size, thread_ids, thr_name); +} + +# if defined (ACE_HAS_DEFERRED_TIMER_COMMANDS) + +// Enqueues a command object for execution just before waiting on the next +// timer event. This allows deferred execution of commands that cannot +// be performed in the timer event handler context, such as registering +// or cancelling timers on platforms where the timer queue mutex is not +// recursive. + +template int +ACE_Thread_Timer_Queue_Adapter::enqueue_command (ACE_Command_Base *cmd, + COMMAND_ENQUEUE_POSITION pos) +{ + // Serialize access to the command queue. + ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, guard, this->command_mutex_, -1); + + if (pos == ACE_Thread_Timer_Queue_Adapter::TAIL) + return command_queue_.enqueue_tail (cmd); + else + return command_queue_.enqueue_head (cmd); +} + +// Dispatches all command objects enqueued in the most recent event +// handler context. + +template int +ACE_Thread_Timer_Queue_Adapter::dispatch_commands (void) +{ + // Serialize access to the command queue. + ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, guard, this->command_mutex_, -1); + + // loop through the enqueued commands + ACE_Command_Base *cmd = 0; + while (command_queue_.dequeue_head (cmd) == 0) + if (cmd) + { + cmd->execute (); + delete cmd; + } + + return 0; +} + +# endif /* ACE_HAS_DEFERRED_TIMER_COMMANDS */ + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_TIMER_QUEUE_ADAPTERS_CPP */ diff --git a/dep/acelite/ace/Timer_Queue_Adapters.h b/dep/acelite/ace/Timer_Queue_Adapters.h new file mode 100644 index 00000000000..d5561717142 --- /dev/null +++ b/dep/acelite/ace/Timer_Queue_Adapters.h @@ -0,0 +1,261 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Timer_Queue_Adapters.h + * + * $Id: Timer_Queue_Adapters.h 89482 2010-03-15 07:58:50Z johnnyw $ + * + * @author Douglas C. Schmidt and + * Carlos O'Ryan + */ +//============================================================================= + +#ifndef ACE_TIMER_QUEUE_ADAPTERS_H +#define ACE_TIMER_QUEUE_ADAPTERS_H +#include /**/ "ace/pre.h" + +#include "ace/Task.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Signal.h" +#include "ace/Sig_Handler.h" +#include "ace/Condition_Recursive_Thread_Mutex.h" + +#if defined (ACE_HAS_DEFERRED_TIMER_COMMANDS) +# include "ace/Unbounded_Queue.h" +ACE_BEGIN_VERSIONED_NAMESPACE_DECL +class ACE_Command_Base; +ACE_END_VERSIONED_NAMESPACE_DECL +#endif /* ACE_HAS_DEFERRED_TIMER_COMMANDS */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +class ACE_Sig_Set; + +/** + * @class ACE_Async_Timer_Queue_Adapter + * + * @brief Adapts an ACE timer queue to be driven asynchronously using signals. + * + * This implementation uses the ACE_OS::ualarm call, to generate + * the SIGARLM signal that is caught by this class. + * + * @note This adapter only works on platforms that support ualarm(). + * POSIX platforms generally do; Windows and some others do not. + * + * @todo This adapter does not automatically reschedule repeating timers. + */ +template +class ACE_Async_Timer_Queue_Adapter : public ACE_Event_Handler +{ +public: + typedef TQ TIMER_QUEUE; + + /// Constructor + /** + * Register the SIGALRM handler. If @a mask == 0 then block all + * signals when @c SIGALRM is run. Otherwise, just block the signals + * indicated in @a mask. + */ + ACE_Async_Timer_Queue_Adapter (ACE_Sig_Set *mask = 0); + + /// Schedule the timer according to the semantics of the + /// ACE_Timer_List. + /** + * This timer gets dispatched via a signal, rather than by a user + * calling expire(). Note that interval timers are not implemented + * yet. + */ + long schedule (TYPE type, + const void *act, + const ACE_Time_Value &future_time, + const ACE_Time_Value &interval = ACE_Time_Value::zero); + + /// Cancel the @a timer_id and pass back the @a act if an address is + /// passed in. + int cancel (long timer_id, const void **act = 0); + + /// Dispatch all timers with expiry time at or before the current time. + /// Returns the number of timers expired. + int expire (void); + + /// Return a reference to the underlying timer queue. + TQ &timer_queue (void); + +private: + /// Perform the logic to compute the new ualarm(2) setting. + virtual int schedule_ualarm (void); + + /// Called back by @c SIGALRM handler. + virtual int handle_signal (int signum, siginfo_t *, ucontext_t *); + + /// Handler for the @c SIGALRM signal, so that we can access our state + /// without requiring any global variables. + ACE_Sig_Handler sig_handler_; + + /// Implementation of the timer queue (e.g., ACE_Timer_List, + /// ACE_Timer_Heap, etc.). + TQ timer_queue_; + + /// Mask of signals to be blocked when we're servicing @c SIGALRM. + ACE_Sig_Set mask_; +}; + +/** + * @class ACE_Thread_Timer_Queue_Adapter + * + * @brief Adapts an ACE timer queue using a separate thread for dispatching. + * + * This implementation uses a separate thread to dispatch the timers. + * The base queue need not be thread safe; this class takes all the + * necessary locks. + * + * @note This is a case where template parameters will be useful, but + * (IMHO) the effort and portability problems discourage their + * use. + * + */ +template +class ACE_Thread_Timer_Queue_Adapter : public ACE_Task_Base +{ +public: + /// Trait for the underlying queue type. + typedef TQ TIMER_QUEUE; + +# if defined (ACE_HAS_DEFERRED_TIMER_COMMANDS) + + /// Typedef for the position at which to enqueue a deferred + /// execution command. + enum COMMAND_ENQUEUE_POSITION {HEAD, TAIL}; + +# endif /* ACE_HAS_DEFERRED_TIMER_COMMANDS */ + + /// Creates the timer queue. Activation of the task is the user's + /// responsibility. Optionally a pointer to a timer queue can be passed, + /// when no pointer is passed, a TQ is dynamically created + ACE_Thread_Timer_Queue_Adapter (ACE_Thread_Manager * = ACE_Thread_Manager::instance (), + TQ* timer_queue = 0); + + /// Destructor. + virtual ~ACE_Thread_Timer_Queue_Adapter (void); + + /// Schedule the timer according to the semantics of the ; wakes + /// up the dispatching thread. + long schedule (TYPE handler, + const void *act, + const ACE_Time_Value &future_time, + const ACE_Time_Value &interval = ACE_Time_Value::zero); + + /// Cancel the @a timer_id and return the @a act parameter if an + /// address is passed in. Also wakes up the dispatching thread. + int cancel (long timer_id, const void **act = 0); + + /// Runs the dispatching thread. + virtual int svc (void); + + /// Inform the dispatching thread that it should terminate. + virtual void deactivate (void); + + /// Access the locking mechanism, useful for iteration. + ACE_SYNCH_RECURSIVE_MUTEX &mutex (void); + + /// Set a user-specified timer queue. + int timer_queue (TQ *tq); + + /// Return the current . + TQ *timer_queue (void) const; + + /// Return the thread id of our active object. + ACE_thread_t thr_id (void) const; + + /** + * We override the default activate() method so that we can ensure + * that only a single thread is ever spawned. Otherwise, too many + * weird things can happen... + */ + virtual int activate (long flags = THR_NEW_LWP | THR_JOINABLE, + int n_threads = 1, + int force_active = 0, + long priority = ACE_DEFAULT_THREAD_PRIORITY, + int grp_id = -1, + ACE_Task_Base *task = 0, + ACE_hthread_t thread_handles[] = 0, + void *stack[] = 0, + size_t stack_size[] = 0, + ACE_thread_t thread_ids[] = 0, + const char* thr_name[] = 0); + +# if defined (ACE_HAS_DEFERRED_TIMER_COMMANDS) + + /** + * Enqueues a command object for execution just before waiting on the next + * timer event. This allows deferred execution of commands that cannot + * be performed in the timer event handler context, such as registering + * or cancelling timers on platforms where the timer queue mutex is not + * recursive. + */ + int enqueue_command (ACE_Command_Base *command_, + COMMAND_ENQUEUE_POSITION pos = TAIL); + +# endif /* ACE_HAS_DEFERRED_TIMER_COMMANDS */ + +private: + +# if defined (ACE_HAS_DEFERRED_TIMER_COMMANDS) + /// Dispatches all command objects enqueued in the most + /// recent event handler context. + int dispatch_commands (void); + + /// Queue of commands for deferred execution. + ACE_Unbounded_Queue command_queue_; + + /// The mutual exclusion mechanism for the command queue. + ACE_SYNCH_MUTEX command_mutex_; +# endif /* ACE_HAS_DEFERRED_TIMER_COMMANDS */ + + /// The underlying Timer_Queue. + TQ* timer_queue_; + + /// Keeps track of whether we should delete the timer queue (if we + /// didn't create it, then we don't delete it). + bool delete_timer_queue_; + + /// The mutual exclusion mechanism that is required to use the + /// . + ACE_SYNCH_RECURSIVE_MUTEX mutex_; + + /** + * The dispatching thread sleeps on this condition while waiting to + * dispatch the next timer; it is used to wake it up if there is a + * change on the timer queue. + */ + ACE_SYNCH_RECURSIVE_CONDITION condition_; + + /// When deactivate is called this variable turns to false and the + /// dispatching thread is signalled, to terminate its main loop. + bool active_; + + /// Thread id of our active object task. + ACE_thread_t thr_id_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +# include "ace/Timer_Queue_Adapters.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +# include "ace/Timer_Queue_Adapters.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +# pragma implementation ("Timer_Queue_Adapters.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" +#endif /* ACE_TIMER_QUEUE_ADAPTERS_H */ diff --git a/dep/acelite/ace/Timer_Queue_Adapters.inl b/dep/acelite/ace/Timer_Queue_Adapters.inl new file mode 100644 index 00000000000..d73ef024246 --- /dev/null +++ b/dep/acelite/ace/Timer_Queue_Adapters.inl @@ -0,0 +1,29 @@ +// -*- C++ -*- +// +// $Id: Timer_Queue_Adapters.inl 89482 2010-03-15 07:58:50Z johnnyw $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template ACE_INLINE TQ * +ACE_Thread_Timer_Queue_Adapter::timer_queue (void) const +{ + return this->timer_queue_; +} + +template ACE_INLINE int +ACE_Thread_Timer_Queue_Adapter::timer_queue (TQ *tq) +{ + if (this->delete_timer_queue_) + delete this->timer_queue_; + this->timer_queue_ = tq; + this->delete_timer_queue_ = false; + return 0; +} + +template ACE_INLINE ACE_thread_t +ACE_Thread_Timer_Queue_Adapter::thr_id (void) const +{ + return this->thr_id_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Timer_Queue_T.cpp b/dep/acelite/ace/Timer_Queue_T.cpp new file mode 100644 index 00000000000..258e68edd55 --- /dev/null +++ b/dep/acelite/ace/Timer_Queue_T.cpp @@ -0,0 +1,538 @@ +// $Id: Timer_Queue_T.cpp 89254 2010-02-25 22:10:39Z cleeland $ + +#ifndef ACE_TIMER_QUEUE_T_CPP +#define ACE_TIMER_QUEUE_T_CPP + +#include "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +/* + * Hook to specialize to add includes + */ +//@@ REACTOR_SPL_INCLUDE_FORWARD_DECL_ADD_HOOK + +#include "ace/Timer_Queue_T.h" +#include "ace/Guard_T.h" +#include "ace/Log_Msg.h" +#include "ace/Reactor_Timer_Interface.h" +#include "ace/Null_Mutex.h" +#include "ace/OS_NS_sys_time.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Timer_Queue_T.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// This fudge factor can be overriden for timers that need it, such as on +// Solaris, by defining the ACE_TIMER_SKEW symbol in the appropriate config +// header. +#if !defined (ACE_TIMER_SKEW) +# define ACE_TIMER_SKEW 0 +#endif /* ACE_TIMER_SKEW */ + +template void +ACE_Timer_Node_T::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Timer_Node_T::dump"); + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nact_ = %x"), this->act_)); + this->timer_value_.dump (); + this->interval_.dump (); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nprev_ = %x"), this->prev_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nnext_ = %x"), this->next_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ntimer_id_ = %d\n"), this->timer_id_)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +template +ACE_Timer_Node_T::ACE_Timer_Node_T (void) +{ + ACE_TRACE ("ACE_Timer_Node_T::ACE_Timer_Node_T"); +} + +template +ACE_Timer_Node_T::~ACE_Timer_Node_T (void) +{ + ACE_TRACE ("ACE_Timer_Node_T::~ACE_Timer_Node_T"); +} + +template +ACE_Timer_Queue_Iterator_T::ACE_Timer_Queue_Iterator_T (void) +{ +} + +template +ACE_Timer_Queue_Iterator_T::~ACE_Timer_Queue_Iterator_T (void) +{ +} + +template ACE_Time_Value * +ACE_Timer_Queue_T::calculate_timeout (ACE_Time_Value *max_wait_time) +{ + ACE_TRACE ("ACE_Timer_Queue_T::calculate_timeout"); + ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, max_wait_time)); + + if (this->is_empty ()) + // Nothing on the Timer_Queue, so use whatever the caller gave us. + return max_wait_time; + else + { + ACE_Time_Value const cur_time = this->gettimeofday (); + + if (this->earliest_time () > cur_time) + { + // The earliest item on the Timer_Queue is still in the + // future. Therefore, use the smaller of (1) caller's wait + // time or (2) the delta time between now and the earliest + // time on the Timer_Queue. + + this->timeout_ = this->earliest_time () - cur_time; + if (max_wait_time == 0 || *max_wait_time > timeout_) + return &this->timeout_; + else + return max_wait_time; + } + else + { + // The earliest item on the Timer_Queue is now in the past. + // Therefore, we've got to "poll" the Reactor, i.e., it must + // just check the descriptors and then dispatch timers, etc. + this->timeout_ = ACE_Time_Value::zero; + return &this->timeout_; + } + } +} + +template ACE_Time_Value * +ACE_Timer_Queue_T::calculate_timeout (ACE_Time_Value *max_wait_time, + ACE_Time_Value *the_timeout) +{ + ACE_TRACE ("ACE_Timer_Queue_T::calculate_timeout"); + + if (the_timeout == 0) + return 0; + + if (this->is_empty ()) + { + // Nothing on the Timer_Queue, so use whatever the caller gave us. + if (max_wait_time) + *the_timeout = *max_wait_time; + else + return 0; + } + else + { + ACE_Time_Value cur_time = this->gettimeofday (); + + if (this->earliest_time () > cur_time) + { + // The earliest item on the Timer_Queue is still in the + // future. Therefore, use the smaller of (1) caller's wait + // time or (2) the delta time between now and the earliest + // time on the Timer_Queue. + + *the_timeout = this->earliest_time () - cur_time; + if (!(max_wait_time == 0 || *max_wait_time > *the_timeout)) + *the_timeout = *max_wait_time; + } + else + { + // The earliest item on the Timer_Queue is now in the past. + // Therefore, we've got to "poll" the Reactor, i.e., it must + // just check the descriptors and then dispatch timers, etc. + *the_timeout = ACE_Time_Value::zero; + } + } + return the_timeout; +} + +template void +ACE_Timer_Queue_T::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Timer_Queue_T::dump"); + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + this->timeout_.dump (); + this->timer_skew_.dump (); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +template +ACE_Timer_Queue_T::ACE_Timer_Queue_T (FUNCTOR *upcall_functor, + ACE_Free_List > *freelist) + : gettimeofday_ (ACE_OS::gettimeofday), + delete_upcall_functor_ (upcall_functor == 0), + delete_free_list_ (freelist == 0), + timer_skew_ (0, ACE_TIMER_SKEW) +{ + ACE_TRACE ("ACE_Timer_Queue_T::ACE_Timer_Queue_T"); + + if (!freelist) + ACE_NEW (free_list_, + (ACE_Locked_Free_List,ACE_Null_Mutex>)); + else + free_list_ = freelist; + + if (!upcall_functor) + ACE_NEW (upcall_functor_, + FUNCTOR); + else + upcall_functor_ = upcall_functor; +} + +template +ACE_Timer_Queue_T::~ACE_Timer_Queue_T (void) +{ + ACE_TRACE ("ACE_Timer_Queue_T::~ACE_Timer_Queue_T"); + + // Cleanup the functor and free_list on the way out + if (this->delete_upcall_functor_) + delete this->upcall_functor_; + + if (this->delete_free_list_) + delete this->free_list_; +} + +template ACE_Timer_Node_T * +ACE_Timer_Queue_T::alloc_node (void) +{ + return this->free_list_->remove (); +} + +template void +ACE_Timer_Queue_T::free_node (ACE_Timer_Node_T *node) +{ + this->free_list_->add (node); +} + +template ACE_LOCK & +ACE_Timer_Queue_T::mutex (void) +{ + return this->mutex_; +} + +template long +ACE_Timer_Queue_T::schedule (const TYPE &type, + const void *act, + const ACE_Time_Value &future_time, + const ACE_Time_Value &interval) +{ + ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); + + // Schedule the timer. + long const result = + this->schedule_i (type, + act, + future_time, + interval); + + // Return on failure. + if (result == -1) + return result; + + // Inform upcall functor of successful registration. + this->upcall_functor ().registration (*this, + type, + act); + + // Return result; + return result; +} + +// Run the method for all Timers whose values are <= +// . +template int +ACE_Timer_Queue_T::expire (const ACE_Time_Value &cur_time) +{ + ACE_TRACE ("ACE_Timer_Queue_T::expire"); + ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); + + // Keep looping while there are timers remaining and the earliest + // timer is <= the passed in to the method. + + if (this->is_empty ()) + return 0; + + int number_of_timers_expired = 0; + int result = 0; + + ACE_Timer_Node_Dispatch_Info_T info; + + while ((result = this->dispatch_info_i (cur_time, info)) != 0) + { + const void *upcall_act = 0; + + this->preinvoke (info, cur_time, upcall_act); + + this->upcall (info, cur_time); + + this->postinvoke (info, cur_time, upcall_act); + + ++number_of_timers_expired; + + } + + ACE_UNUSED_ARG (result); + return number_of_timers_expired; +} + +template void +ACE_Timer_Queue_T::recompute_next_abs_interval_time + (ACE_Timer_Node_T *expired, + const ACE_Time_Value &cur_time) +{ + if ( expired->get_timer_value () <= cur_time ) + { + /* + * Somehow the current time is past when this time was + * supposed to expire (e.g., timer took too long, + * somebody changed system time, etc.). There used to + * be a simple loop here that skipped ahead one timer + * interval at a time, but that was horribly inefficient + * (an O(n) algorithm) when the timer duration was small + * relative to the amount of time skipped. + * + * So, we replace the loop with a simple computation, + * which also happens to be O(1). All times get + * normalized in the computation to microseconds. + * + * For reference, the loop looked like this: + * + * do + * expired->set_timer_value (expired->get_timer_value () + + * expired->get_interval ()); + * while (expired->get_timer_value () <= cur_time); + * + */ + + // Compute the duration of the timer's interval + ACE_UINT64 interval_usec; + expired->get_interval ().to_usec (interval_usec); + + // Compute the span between the current time and when + // the timer would have expired in the past (and + // normalize to microseconds). + ACE_Time_Value old_diff = cur_time - expired->get_timer_value (); + ACE_UINT64 old_diff_usec; + old_diff.to_usec (old_diff_usec); + + // Compute the delta time in the future when the timer + // should fire as if it had advanced incrementally. The + // modulo arithmetic accomodates the likely case that + // the current time doesn't fall precisely on a timer + // firing interval. + ACE_UINT64 new_timer_usec = + interval_usec - (old_diff_usec % interval_usec); + + // Compute the absolute time in the future when this + // interval timer should expire. + ACE_Time_Value new_timer_value + (cur_time.sec () + + static_cast(new_timer_usec / ACE_ONE_SECOND_IN_USECS), + cur_time.usec () + + static_cast(new_timer_usec % ACE_ONE_SECOND_IN_USECS)); + + expired->set_timer_value (new_timer_value); + } +} + +template int +ACE_Timer_Queue_T::dispatch_info_i (const ACE_Time_Value &cur_time, + ACE_Timer_Node_Dispatch_Info_T &info) +{ + ACE_TRACE ("ACE_Timer_Queue_T::dispatch_info_i"); + + if (this->is_empty ()) + return 0; + + ACE_Timer_Node_T *expired = 0; + + if (this->earliest_time () <= cur_time) + { + expired = this->remove_first (); + + // Get the dispatch info + expired->get_dispatch_info (info); + + // Check if this is an interval timer. + if (expired->get_interval () > ACE_Time_Value::zero) + { + // Make sure that we skip past values that have already + // "expired". + this->recompute_next_abs_interval_time (expired, cur_time); + + // Since this is an interval timer, we need to reschedule + // it. + this->reschedule (expired); + } + else + { + // Call the factory method to free up the node. + this->free_node (expired); + } + + return 1; + } + + return 0; +} + +template void +ACE_Timer_Queue_T::return_node (ACE_Timer_Node_T *node) +{ + ACE_MT (ACE_GUARD (ACE_LOCK, ace_mon, this->mutex_)); + this->free_node (node); +} + + +template +ACE_Event_Handler_Handle_Timeout_Upcall::ACE_Event_Handler_Handle_Timeout_Upcall (void) +{ +} + +template +ACE_Event_Handler_Handle_Timeout_Upcall::~ACE_Event_Handler_Handle_Timeout_Upcall (void) +{ +} + +template int +ACE_Event_Handler_Handle_Timeout_Upcall::registration (TIMER_QUEUE &, + ACE_Event_Handler *event_handler, + const void *) +{ + event_handler->add_reference (); + return 0; +} + +template int +ACE_Event_Handler_Handle_Timeout_Upcall::preinvoke (TIMER_QUEUE & /* timer_queue */, + ACE_Event_Handler *event_handler, + const void * /* timer_act */, + int /* recurring_timer */, + const ACE_Time_Value & /* cur_time */, + const void *&upcall_act) +{ + bool const requires_reference_counting = + event_handler->reference_counting_policy ().value () == + ACE_Event_Handler::Reference_Counting_Policy::ENABLED; + + if (requires_reference_counting) + { + event_handler->add_reference (); + + upcall_act = &this->requires_reference_counting_; + } + + return 0; +} + +template int +ACE_Event_Handler_Handle_Timeout_Upcall::postinvoke (TIMER_QUEUE & /* timer_queue */, + ACE_Event_Handler *event_handler, + const void * /* timer_act */, + int /* recurring_timer */, + const ACE_Time_Value & /* cur_time */, + const void *upcall_act) +{ + if (upcall_act == &this->requires_reference_counting_) + { + event_handler->remove_reference (); + } + + return 0; +} + +template int +ACE_Event_Handler_Handle_Timeout_Upcall::timeout (TIMER_QUEUE &timer_queue, + ACE_Event_Handler *event_handler, + const void *act, + int recurring_timer, + const ACE_Time_Value &cur_time) +{ + int requires_reference_counting = 0; + + if (!recurring_timer) + { + requires_reference_counting = + event_handler->reference_counting_policy ().value () == + ACE_Event_Handler::Reference_Counting_Policy::ENABLED; + } + + // Upcall to the s handle_timeout method. + if (event_handler->handle_timeout (cur_time, act) == -1) + { + if (event_handler->reactor_timer_interface ()) + event_handler->reactor_timer_interface ()->cancel_timer (event_handler, 0); + else + timer_queue.cancel (event_handler, 0); // 0 means "call handle_close()". + } + + if (!recurring_timer && + requires_reference_counting) + { + event_handler->remove_reference (); + } + + return 0; +} + +template int +ACE_Event_Handler_Handle_Timeout_Upcall::cancel_type (TIMER_QUEUE &, + ACE_Event_Handler *event_handler, + int dont_call, + int &requires_reference_counting) +{ + requires_reference_counting = + event_handler->reference_counting_policy ().value () == + ACE_Event_Handler::Reference_Counting_Policy::ENABLED; + + // Upcall to the s handle_close method + if (dont_call == 0) + event_handler->handle_close (ACE_INVALID_HANDLE, + ACE_Event_Handler::TIMER_MASK); + + return 0; +} + +template int +ACE_Event_Handler_Handle_Timeout_Upcall::cancel_timer (TIMER_QUEUE &, + ACE_Event_Handler *event_handler, + int, + int requires_reference_counting) +{ + if (requires_reference_counting) + event_handler->remove_reference (); + + return 0; +} + +template int +ACE_Event_Handler_Handle_Timeout_Upcall::deletion (TIMER_QUEUE &timer_queue, + ACE_Event_Handler *event_handler, + const void *) +{ + int requires_reference_counting = 0; + + this->cancel_type (timer_queue, + event_handler, + 0, + requires_reference_counting); + + this->cancel_timer (timer_queue, + event_handler, + 0, + requires_reference_counting); + + return 0; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_TIMER_QUEUE_T_CPP */ diff --git a/dep/acelite/ace/Timer_Queue_T.h b/dep/acelite/ace/Timer_Queue_T.h new file mode 100644 index 00000000000..5e316e1e04b --- /dev/null +++ b/dep/acelite/ace/Timer_Queue_T.h @@ -0,0 +1,566 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Timer_Queue_T.h + * + * $Id: Timer_Queue_T.h 89254 2010-02-25 22:10:39Z cleeland $ + * + * @author Doug Schmidt + * @author Irfan Pyarali and + * @author Darrell Brunsch + */ +//============================================================================= + +#ifndef ACE_TIMER_QUEUE_T_H +#define ACE_TIMER_QUEUE_T_H +#include /**/ "ace/pre.h" + +#include "ace/Free_List.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Event_Handler.h" +#include "ace/Time_Value.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Timer_Node_Dispatch_Info_T + * + * @brief Maintains generated dispatch information for Timer nodes. + * + */ +template +class ACE_Timer_Node_Dispatch_Info_T +{ +public: + /// The type of object held in the queue + TYPE type_; + + /// Asynchronous completion token associated with the timer. + const void *act_; + + /// Flag to check if the timer is recurring. + int recurring_timer_; +}; + +/** + * @class ACE_Timer_Node_T + * + * @brief Maintains the state associated with a Timer entry. + */ +template +class ACE_Timer_Node_T +{ +public: + /// Default constructor + ACE_Timer_Node_T (void); + + /// Destructor + ~ACE_Timer_Node_T (void); + + /// Useful typedef .. + typedef ACE_Timer_Node_Dispatch_Info_T DISPATCH_INFO; + + /// Singly linked list + void set (const TYPE &type, + const void *a, + const ACE_Time_Value &t, + const ACE_Time_Value &i, + ACE_Timer_Node_T *n, + long timer_id); + + /// Doubly linked list version + void set (const TYPE &type, + const void *a, + const ACE_Time_Value &t, + const ACE_Time_Value &i, + ACE_Timer_Node_T *p, + ACE_Timer_Node_T *n, + long timer_id); + + // = Accessors + + /// Get the type. + TYPE &get_type (void); + + /// Set the type. + void set_type (TYPE &type); + + /// Get the asynchronous completion token. + const void *get_act (void); + + /// Set the asynchronous completion token. + void set_act (void *act); + + /// Get the timer value. + const ACE_Time_Value &get_timer_value (void) const; + + /// Set the timer value. + void set_timer_value (const ACE_Time_Value &timer_value); + + /// Get the timer interval. + const ACE_Time_Value &get_interval (void) const; + + /// Set the timer interval. + void set_interval (const ACE_Time_Value &interval); + + /// Get the previous pointer. + ACE_Timer_Node_T *get_prev (void); + + /// Set the previous pointer. + void set_prev (ACE_Timer_Node_T *prev); + + /// Get the next pointer. + ACE_Timer_Node_T *get_next (void); + + /// Set the next pointer. + void set_next (ACE_Timer_Node_T *next); + + /// Get the timer_id. + long get_timer_id (void) const; + + /// Set the timer_id. + void set_timer_id (long timer_id); + + /// Get the dispatch info. The dispatch information is got + /// through . This form helps us in preventing allocation and + /// deleting data along the criticl path. + /// @@TODO: We may want to have a copying version too, so that our + /// interface will be complete.. + void get_dispatch_info (ACE_Timer_Node_Dispatch_Info_T &info); + + /// Dump the state of an TYPE. + void dump (void) const; + +private: + /// Type of object stored in the Queue + TYPE type_; + + /// Asynchronous completion token associated with the timer. + const void *act_; + + /// Time until the timer expires. + ACE_Time_Value timer_value_; + + /// If this is a periodic timer this holds the time until the next + /// timeout. + ACE_Time_Value interval_; + + /// Pointer to previous timer. + ACE_Timer_Node_T *prev_; + + /// Pointer to next timer. + ACE_Timer_Node_T *next_; + + /// Id of this timer (used to cancel timers before they expire). + long timer_id_; +}; + +/** + * @class ACE_Timer_Queue_Iterator_T + * + * @brief Generic interface for iterating over a subclass of + * ACE_Timer_Queue. + * + * This is a generic iterator that can be used to visit every + * node of a timer queue. Be aware that it isn't guaranteed + * that the transversal will be in order of timeout values. + */ +template +class ACE_Timer_Queue_Iterator_T +{ +public: + // = Initialization and termination methods. + /// Constructor. + ACE_Timer_Queue_Iterator_T (void); + + /// Destructor. + virtual ~ACE_Timer_Queue_Iterator_T (void); + + /// Positions the iterator at the earliest node in the Timer Queue + virtual void first (void) = 0; + + /// Positions the iterator at the next node in the Timer Queue + virtual void next (void) = 0; + + /// Returns true when there are no more nodes in the sequence + virtual bool isdone (void) const = 0; + + /// Returns the node at the current position in the sequence + virtual ACE_Timer_Node_T *item (void) = 0; +}; + +/** + * @class ACE_Timer_Queue_T + * + * @brief Provides an interface to timers. + * + * This is an abstract base class that provides hook for + * implementing specialized policies such as ACE_Timer_List + * and ACE_Timer_Heap. + */ +template +class ACE_Timer_Queue_T +{ +public: + /// Type of Iterator. + typedef ACE_Timer_Queue_Iterator_T ITERATOR; + + // = Initialization and termination methods. + /** + * Default constructor. @a upcall_functor is the instance of the + * FUNCTOR to be used by the queue. If @a upcall_functor is 0, Timer + * Queue will create a default FUNCTOR. @a freelist the freelist of + * timer nodes. If 0, then a default freelist will be created. + */ + ACE_Timer_Queue_T (FUNCTOR *upcall_functor = 0, + ACE_Free_List > *freelist = 0); + + /// Destructor - make virtual for proper destruction of inherited + /// classes. + virtual ~ACE_Timer_Queue_T (void); + + /// True if queue is empty, else false. + virtual bool is_empty (void) const = 0; + + /// Returns the time of the earlier node in the Timer_Queue. Must + /// be called on a non-empty queue. + virtual const ACE_Time_Value &earliest_time (void) const = 0; + + /** + * Schedule @a type that will expire at @a future_time, which is + * specified in absolute time. If it expires then @a act is passed + * in as the value to the . If @a interval is != to + * ACE_Time_Value::zero then it is used to reschedule the @a type + * automatically, using relative time to the current . + * This method returns a that uniquely identifies the the + * @a type entry in an internal list. This can be used to + * cancel the timer before it expires. The cancellation ensures + * that are unique up to values of greater than 2 + * billion timers. As long as timers don't stay around longer than + * this there should be no problems with accidentally deleting the + * wrong timer. Returns -1 on failure (which is guaranteed never to + * be a valid ). + */ + virtual long schedule (const TYPE &type, + const void *act, + const ACE_Time_Value &future_time, + const ACE_Time_Value &interval = ACE_Time_Value::zero); + + /** + * Resets the interval of the timer represented by @a timer_id to + * @a interval, which is specified in relative time to the current + * . If @a interval is equal to + * ACE_Time_Value::zero, the timer will become a non-rescheduling + * timer. Returns 0 if successful, -1 if not. + */ + virtual int reset_interval (long timer_id, + const ACE_Time_Value &interval) = 0; + + /** + * Cancel all timer associated with @a type. If + * @a dont_call_handle_close is 0 then the will be invoked, + * which typically invokes the hook. Returns number + * of timers cancelled. + */ + virtual int cancel (const TYPE &type, + int dont_call_handle_close = 1) = 0; + + /** + * Cancel the single timer that matches the @a timer_id value (which + * was returned from the method). If act is non-NULL + * then it will be set to point to the ``magic cookie'' argument + * passed in when the timer was registered. This makes it possible + * to free up the memory and avoid memory leaks. If + * @a dont_call_handle_close is 0 then the will be invoked, + * which typically calls the hook. Returns 1 if + * cancellation succeeded and 0 if the @a timer_id wasn't found. + */ + virtual int cancel (long timer_id, + const void **act = 0, + int dont_call_handle_close = 1) = 0; + + /** + * Run the for all timers whose values are <= @a current_time. + * This does not account for . Returns the number of + * timers canceled. + */ + virtual int expire (const ACE_Time_Value ¤t_time); + + /** + * Get the dispatch information for a timer whose value is <= @a current_time. + * This does not account for . Returns 1 if + * there is a node whose value <= @a current_time else returns a 0. + * + */ + virtual int dispatch_info (const ACE_Time_Value ¤t_time, + ACE_Timer_Node_Dispatch_Info_T &info); + + /** + * Run the for all timers whose values are <= + * . Also accounts for . + * + * Depending on the resolution of the underlying OS the system calls + * like select()/poll() might return at time different than that is + * specified in the timeout. Suppose the OS guarantees a resolution of t ms. + * The timeline will look like + * + * A B + * | | + * V V + * |-------------|-------------|-------------|-------------| + * t t t t t + * + * + * If you specify a timeout value of A, then the timeout will not occur + * at A but at the next interval of the timer, which is later than + * that is expected. Similarly, if your timeout value is equal to B, + * then the timeout will occur at interval after B. Now depending upon the + * resolution of your timeouts and the accuracy of the timeouts + * needed for your application, you should set the value of + * . In the above case, if you want the timeout A to fire + * no later than A, then you should specify your to be + * A % t. + * + * The timeout value should be specified via the macro ACE_TIMER_SKEW + * in your config.h file. The default value is zero. + * + * Things get interesting if the t before the timeout value B is zero + * i.e your timeout is less than the interval. In that case, you are + * almost sure of not getting the desired timeout behaviour. Maybe you + * should look for a better OS :-) + * + * Returns the number of timers canceled. + */ + + /* virtual */ int expire (void); + + /** + * Returns the current time of day. This method allows different + * implementations of the timer queue to use special high resolution + * timers. + */ + /* virtual */ ACE_Time_Value gettimeofday (void); + + /// Allows applications to control how the timer queue gets the time + /// of day. + void gettimeofday (ACE_Time_Value (*gettimeofday)(void)); + + /// Determine the next event to timeout. Returns @a max if there are + /// no pending timers or if all pending timers are longer than max. + /// This method acquires a lock internally since it modifies internal state. + virtual ACE_Time_Value *calculate_timeout (ACE_Time_Value *max); + + /** + * Determine the next event to timeout. Returns @a max if there are + * no pending timers or if all pending timers are longer than max. + * should be a pointer to storage for the timeout value, + * and this value is also returned. This method does not acquire a + * lock internally since it doesn't modify internal state. If you + * need to call this method when the queue is being modified + * concurrently, however, you should make sure to acquire the + * externally before making the call. + */ + virtual ACE_Time_Value *calculate_timeout (ACE_Time_Value *max, + ACE_Time_Value *the_timeout); + + /// Set the timer skew for the Timer_Queue. + void timer_skew (const ACE_Time_Value &skew); + + /// Get the timer skew for the Timer_Queue. + const ACE_Time_Value &timer_skew (void) const; + + /// Synchronization variable used by the queue + ACE_LOCK &mutex (void); + + /// Accessor to the upcall functor + FUNCTOR &upcall_functor (void); + + /// Returns a pointer to this ACE_Timer_Queue's iterator. + virtual ITERATOR &iter (void) = 0; + + /// Removes the earliest node from the queue and returns it + virtual ACE_Timer_Node_T *remove_first (void) = 0; + + /// Dump the state of a object. + virtual void dump (void) const; + + /// Reads the earliest node from the queue and returns it. + virtual ACE_Timer_Node_T *get_first (void) = 0; + + /// Method used to return a timer node to the queue's ownership + /// after it is returned by a method like . + virtual void return_node (ACE_Timer_Node_T *); + + /// This method will call the preinvoke() on . + void preinvoke (ACE_Timer_Node_Dispatch_Info_T &info, + const ACE_Time_Value &cur_time, + const void *&upcall_act); + + /// This method will call the timeout() on . + void upcall (ACE_Timer_Node_Dispatch_Info_T &info, + const ACE_Time_Value &cur_time); + + /// This method will call the postinvoke() on . + void postinvoke (ACE_Timer_Node_Dispatch_Info_T &info, + const ACE_Time_Value &cur_time, + const void *upcall_act); + +protected: + + /// Schedule a timer. + virtual long schedule_i (const TYPE &type, + const void *act, + const ACE_Time_Value &future_time, + const ACE_Time_Value &interval) = 0; + + /// Reschedule an "interval" ACE_Timer_Node. + virtual void reschedule (ACE_Timer_Node_T *) = 0; + + /// Factory method that allocates a new node. + virtual ACE_Timer_Node_T *alloc_node (void); + + /// Factory method that frees a previously allocated node. + virtual void free_node (ACE_Timer_Node_T *); + + /// Non-locking version of dispatch_info () + virtual int dispatch_info_i (const ACE_Time_Value ¤t_time, + ACE_Timer_Node_Dispatch_Info_T &info); + + /// Recompute when the next time is that this interval timer should fire. + void recompute_next_abs_interval_time (ACE_Timer_Node_T* expired, + const ACE_Time_Value &cur_time); + + /// Synchronization variable for ACE_Timer_Queue. + /// @note The right name would be lock_, but HP/C++ will choke on that! + ACE_LOCK mutex_; + + /// Class that implements a free list + ACE_Free_List > *free_list_; + + /// Pointer to function that returns the current time of day. + ACE_Time_Value (*gettimeofday_)(void); + + /// Upcall functor + FUNCTOR *upcall_functor_; + + /// To delete or not to delete is the question? + bool const delete_upcall_functor_; + + /// Flag to delete only if the class created the + bool const delete_free_list_; + +private: + + /// Returned by . + ACE_Time_Value timeout_; + + /// Adjusts for timer skew in various clocks. + ACE_Time_Value timer_skew_; + + // = Don't allow these operations for now. + ACE_UNIMPLEMENTED_FUNC (ACE_Timer_Queue_T (const ACE_Timer_Queue_T &)) + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Timer_Queue_T &)) +}; + +/** + * @class ACE_Event_Handler_Handle_Timeout_Upcall + * + * @brief Functor for Timer_Queues. + * + * This class implements the functor required by the Timer + * Queue to call on ACE_Event_Handlers. + */ +template +class ACE_Event_Handler_Handle_Timeout_Upcall +{ +public: + typedef ACE_Timer_Queue_T, + ACE_LOCK> + TIMER_QUEUE; + + // = Initialization and termination methods. + /// Constructor. + ACE_Event_Handler_Handle_Timeout_Upcall (void); + + /// Destructor. + ~ACE_Event_Handler_Handle_Timeout_Upcall (void); + + /// This method is called when a timer is registered. + int registration (TIMER_QUEUE &timer_queue, + ACE_Event_Handler *handler, + const void *arg); + + /// This method is called before the timer expires. + int preinvoke (TIMER_QUEUE &timer_queue, + ACE_Event_Handler *handler, + const void *arg, + int recurring_timer, + const ACE_Time_Value &cur_time, + const void *&upcall_act); + + /// This method is called when the timer expires. + int timeout (TIMER_QUEUE &timer_queue, + ACE_Event_Handler *handler, + const void *arg, + int recurring_timer, + const ACE_Time_Value &cur_time); + + /// This method is called after the timer expires. + int postinvoke (TIMER_QUEUE &timer_queue, + ACE_Event_Handler *handler, + const void *arg, + int recurring_timer, + const ACE_Time_Value &cur_time, + const void *upcall_act); + + /// This method is called when a handler is cancelled + int cancel_type (TIMER_QUEUE &timer_queue, + ACE_Event_Handler *handler, + int dont_call, + int &requires_reference_counting); + + /// This method is called when a timer is cancelled + int cancel_timer (TIMER_QUEUE &timer_queue, + ACE_Event_Handler *handler, + int dont_call, + int requires_reference_counting); + + /// This method is called when the timer queue is destroyed and + /// the timer is still contained in it + int deletion (TIMER_QUEUE &timer_queue, + ACE_Event_Handler *handler, + const void *arg); + +private: + + /// Flag indicating that reference counting is required for this + /// event handler upcall. + int requires_reference_counting_; + + // = Don't allow these operations for now. + ACE_UNIMPLEMENTED_FUNC (ACE_Event_Handler_Handle_Timeout_Upcall (const ACE_Event_Handler_Handle_Timeout_Upcall &)) + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Event_Handler_Handle_Timeout_Upcall &)) +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Timer_Queue_T.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Timer_Queue_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Timer_Queue_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" +#endif /* ACE_TIMER_QUEUE_T_H */ diff --git a/dep/acelite/ace/Timer_Queue_T.inl b/dep/acelite/ace/Timer_Queue_T.inl new file mode 100644 index 00000000000..7606a2e1f62 --- /dev/null +++ b/dep/acelite/ace/Timer_Queue_T.inl @@ -0,0 +1,222 @@ +// -*- C++ -*- +// +// $Id: Timer_Queue_T.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template ACE_INLINE void +ACE_Timer_Node_T::set (const TYPE &type, + const void *a, + const ACE_Time_Value &t, + const ACE_Time_Value &i, + ACE_Timer_Node_T *n, + long timer_id) +{ + this->type_ = type; + this->act_ = a; + this->timer_value_ = t; + this->interval_ = i; + this->next_ = n; + this->timer_id_ = timer_id; +} + +template ACE_INLINE void +ACE_Timer_Node_T::set (const TYPE &type, + const void *a, + const ACE_Time_Value &t, + const ACE_Time_Value &i, + ACE_Timer_Node_T *p, + ACE_Timer_Node_T *n, + long timer_id) +{ + this->type_ = type; + this->act_ = a; + this->timer_value_ = t; + this->interval_ = i; + this->prev_ = p; + this->next_ = n; + this->timer_id_ = timer_id; +} + +template ACE_INLINE TYPE & +ACE_Timer_Node_T::get_type (void) +{ + return this->type_; +} + +template ACE_INLINE void +ACE_Timer_Node_T::set_type (TYPE &type) +{ + this->type_ = type; +} + +template ACE_INLINE const void * +ACE_Timer_Node_T::get_act (void) +{ + return this->act_; +} + +template ACE_INLINE void +ACE_Timer_Node_T::set_act (void *act) +{ + this->act_ = act; +} + +template ACE_INLINE const ACE_Time_Value & +ACE_Timer_Node_T::get_timer_value (void) const +{ + return this->timer_value_; +} + +template ACE_INLINE void +ACE_Timer_Node_T::set_timer_value (const ACE_Time_Value &timer_value) +{ + this->timer_value_ = timer_value; +} + +template ACE_INLINE const ACE_Time_Value & +ACE_Timer_Node_T::get_interval (void) const +{ + return this->interval_; +} + +template ACE_INLINE void +ACE_Timer_Node_T::set_interval (const ACE_Time_Value &interval) +{ + this->interval_ = interval; +} + +template ACE_INLINE ACE_Timer_Node_T * +ACE_Timer_Node_T::get_prev (void) +{ + return this->prev_; +} + +template ACE_INLINE void +ACE_Timer_Node_T::set_prev (ACE_Timer_Node_T *prev) +{ + this->prev_ = prev; +} + +template ACE_INLINE ACE_Timer_Node_T * +ACE_Timer_Node_T::get_next (void) +{ + return this->next_; +} + +template ACE_INLINE void +ACE_Timer_Node_T::set_next (ACE_Timer_Node_T *next) +{ + this->next_ = next; +} + +template ACE_INLINE long +ACE_Timer_Node_T::get_timer_id (void) const +{ + return this->timer_id_; +} + +template ACE_INLINE void +ACE_Timer_Node_T::set_timer_id (long timer_id) +{ + this->timer_id_ = timer_id; +} + +template ACE_INLINE void +ACE_Timer_Node_T::get_dispatch_info (ACE_Timer_Node_Dispatch_Info_T &info) +{ + // Yes, do a copy + info.type_ = this->type_; + info.act_ = this->act_; + info.recurring_timer_ = + this->interval_ > ACE_Time_Value::zero; +} + +template ACE_INLINE void +ACE_Timer_Queue_T::timer_skew (const ACE_Time_Value &skew) +{ + timer_skew_ = skew; +} + +template ACE_INLINE const ACE_Time_Value & +ACE_Timer_Queue_T::timer_skew (void) const +{ + return timer_skew_; +} + +template ACE_INLINE int +ACE_Timer_Queue_T::expire (void) +{ + if (!this->is_empty ()) + return this->expire (this->gettimeofday () + timer_skew_); + else + return 0; +} + +template int +ACE_Timer_Queue_T::dispatch_info (const ACE_Time_Value &cur_time, + ACE_Timer_Node_Dispatch_Info_T &info) +{ + ACE_TRACE ("ACE_Timer_Queue_T::dispatch_info"); + ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, 0)); + + return this->dispatch_info_i (cur_time, info); +} + +template ACE_INLINE void +ACE_Timer_Queue_T::upcall (ACE_Timer_Node_Dispatch_Info_T &info, + const ACE_Time_Value &cur_time) +{ + this->upcall_functor ().timeout (*this, + info.type_, + info.act_, + info.recurring_timer_, + cur_time); +} + +template ACE_INLINE void +ACE_Timer_Queue_T::preinvoke (ACE_Timer_Node_Dispatch_Info_T &info, + const ACE_Time_Value &cur_time, + const void *&upcall_act) +{ + this->upcall_functor ().preinvoke (*this, + info.type_, + info.act_, + info.recurring_timer_, + cur_time, + upcall_act); +} + +template ACE_INLINE void +ACE_Timer_Queue_T::postinvoke (ACE_Timer_Node_Dispatch_Info_T &info, + const ACE_Time_Value &cur_time, + const void *upcall_act) +{ + this->upcall_functor ().postinvoke (*this, + info.type_, + info.act_, + info.recurring_timer_, + cur_time, + upcall_act); +} + +template ACE_INLINE ACE_Time_Value +ACE_Timer_Queue_T::gettimeofday (void) +{ + // Invoke gettimeofday via pointer to function. + return this->gettimeofday_ (); +} + +template ACE_INLINE void +ACE_Timer_Queue_T::gettimeofday (ACE_Time_Value (*gettimeofday)(void)) +{ + this->gettimeofday_ = gettimeofday; +} + +template ACE_INLINE FUNCTOR & +ACE_Timer_Queue_T::upcall_functor (void) +{ + return *this->upcall_functor_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Timer_Queuefwd.h b/dep/acelite/ace/Timer_Queuefwd.h new file mode 100644 index 00000000000..662f29c0411 --- /dev/null +++ b/dep/acelite/ace/Timer_Queuefwd.h @@ -0,0 +1,38 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Timer_Queuefwd.h + * + * $Id: Timer_Queuefwd.h 80826 2008-03-04 14:51:23Z wotte $ + * + * Forward declarations and typedefs of ACE_Timer_Queue class. + * + * @author Ossama Othman + */ +//============================================================================= + +#ifndef ACE_TIMER_QUEUE_FWD_H +#define ACE_TIMER_QUEUE_FWD_H + +#include /**/ "ace/pre.h" + +#include "ace/Synch_Traits.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template class ACE_Timer_Queue_T; +template class ACE_Event_Handler_Handle_Timeout_Upcall; + +class ACE_Event_Handler; + +typedef ACE_Timer_Queue_T, + ACE_SYNCH_RECURSIVE_MUTEX> + ACE_Timer_Queue; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" + +#endif /* ACE_TIMER_QUEUE_FWD_H */ diff --git a/dep/acelite/ace/Timer_Wheel.h b/dep/acelite/ace/Timer_Wheel.h new file mode 100644 index 00000000000..21ba8776102 --- /dev/null +++ b/dep/acelite/ace/Timer_Wheel.h @@ -0,0 +1,42 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Timer_Wheel.h + * + * $Id: Timer_Wheel.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Darrell Brunsch (brunsch@cs.wustl.edu) + */ +//============================================================================= + + +#ifndef ACE_TIMER_WHEEL_H +#define ACE_TIMER_WHEEL_H +#include /**/ "ace/pre.h" + +#include "ace/Timer_Wheel_T.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// The following typedefs are here for ease of use and backward +// compatibility. + +typedef ACE_Timer_Wheel_T, + ACE_SYNCH_RECURSIVE_MUTEX> + ACE_Timer_Wheel; + +typedef ACE_Timer_Wheel_Iterator_T, + ACE_SYNCH_RECURSIVE_MUTEX> + ACE_Timer_Wheel_Iterator; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" +#endif /* ACE_TIMER_WHEEL_H */ diff --git a/dep/acelite/ace/Timer_Wheel_T.cpp b/dep/acelite/ace/Timer_Wheel_T.cpp new file mode 100644 index 00000000000..529cc456d50 --- /dev/null +++ b/dep/acelite/ace/Timer_Wheel_T.cpp @@ -0,0 +1,964 @@ +// $Id: Timer_Wheel_T.cpp 89254 2010-02-25 22:10:39Z cleeland $ + +#ifndef ACE_TIMER_WHEEL_T_CPP +#define ACE_TIMER_WHEEL_T_CPP + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/OS_NS_sys_time.h" +#include "ace/Guard_T.h" +#include "ace/Timer_Wheel_T.h" +#include "ace/Log_Msg.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Design/implementation notes for ACE_Timer_Wheel_T. +// +// Each timer queue entry is represented by a ACE_Timer_Node. +// The timing wheel is divided into a number of "spokes"; there are +// spoke_count_ spokes in the wheel. Each timer is hashed into one of the +// spokes. Entries within each spoke are linked in a double-linked list +// in order of increasing expiration. The first ACE_Timer_Node in each +// spoke is a "dummy node" that marks the end of the list of ACE_Timer_Nodes +// in that spoke. +// +// The timer ID for a scheduled timer is formed by its spoke position in +// the wheel, and the number of timers that have been inserted in that spoke +// since the queue was initialized. N bits of the long timer_id are used +// to determine the spoke, and M bits are used as a counter. +// Each time a Node is inserted into a spoke, it's counter +// is incremented. The count is kept in the timer ID field +// of the dummy root Node. In the event of overflow of the counter, the spoke +// must be searched for each new id to make sure it's not already in use. To +// prevent having to do an exhaustive search each time, we keep extra data +// in the dummy root Node. +/** +* Default Constructor that sets defaults for spoke_count_ and resolution_ +* and doesn't do any preallocation. +* +* @param upcall_functor A pointer to a functor to use instead of the default +* @param freelist A pointer to a freelist to use instead of the default +*/ +template +ACE_Timer_Wheel_T::ACE_Timer_Wheel_T +(FUNCTOR* upcall_functor + , FreeList* freelist + ) +: Base (upcall_functor, freelist) +, spokes_(0) +, spoke_count_(0) // calculated in open_i +, spoke_bits_(0) +, res_bits_ (0) +, earliest_spoke_ (0) +, iterator_(0) +, timer_count_(0) +{ + ACE_TRACE ("ACE_Timer_Wheel_T::ACE_Timer_Wheel_T"); + this->open_i (0, + ACE_DEFAULT_TIMER_WHEEL_SIZE, + ACE_DEFAULT_TIMER_WHEEL_RESOLUTION); +} + +/** +* Constructor that sets up the timing wheel and also may preallocate +* some nodes on the free list +* +* @param spoke_count The number of lists in the timer wheel +* @param resolution The time resolution in milliseconds used by the hashing function +* @param prealloc The number of entries to prealloc in the free_list +* @param upcall_functor A pointer to a functor to use instead of the default +* @param freelist A pointer to a freelist to use instead of the default +*/ +template +ACE_Timer_Wheel_T::ACE_Timer_Wheel_T + (u_int spoke_count, + u_int resolution, + size_t prealloc, + FUNCTOR* upcall_functor, + FreeList* freelist) +: Base (upcall_functor, freelist) +, spokes_ (0) +, spoke_count_ (0) // calculated in open_i +, spoke_bits_ (0) +, res_bits_ (0) +, earliest_spoke_ (0) +, iterator_ (0) +, timer_count_ (0) +{ + ACE_TRACE ("ACE_Timer_Wheel_T::ACE_Timer_Wheel_T"); + this->open_i (prealloc, spoke_count, resolution); +} + +template int +ACE_Timer_Wheel_T::power2bits (int n, + int min_bits, + int max_bits) +{ + int max = (1 << max_bits) - 1; + if (n > max) + return max_bits; + + // count the bits in n. + int i = 0; + int tmp = n; + do + { + tmp >>= 1; + ++i; + } + while (tmp != 0); + + if (i <= min_bits) + return min_bits; + + // Which is nearest? + int a = (1 << i) - n; + int b = (1 << (i - 1)) - n; + if (b < 0) + b = -b; + if (b < a) + return i - 1; + return i; +} + +/** +* Initialize the queue. Uses the established members for all needed +* information. +*/ +template void +ACE_Timer_Wheel_T::open_i + (size_t prealloc, u_int spokes, u_int res) +{ + ACE_TRACE ("ACE_Timer_Wheel_T::open_i"); + + this->gettimeofday (ACE_OS::gettimeofday); + + // Rather than waste bits in our timer id, we might as well round up + // the spoke count to the next power of two - 1 . (i.e 1,3,7,15,...127,etc.) + const int MIN_SPOKE_BITS = 3; // Allow between 8 and 4096 spokes + const int MAX_SPOKE_BITS = 12; + const int MAX_RES_BITS = 20; // 20 is plenty, even on 64 bit platforms. + + this->spoke_bits_ = power2bits (spokes, MIN_SPOKE_BITS, MAX_SPOKE_BITS); + this->res_bits_ = power2bits (res, 1, MAX_RES_BITS); + + this->spoke_count_ = 1 << this->spoke_bits_; + + this->free_list_->resize (prealloc + this->spoke_count_); + + this->wheel_time_.msec (1 << (this->res_bits_)); + + ACE_NEW (this->spokes_, ACE_Timer_Node_T* [this->spoke_count_]); + + // Create the root nodes. These will be treated specially + for (u_int i = 0; i < this->spoke_count_; ++i) + { + ACE_Timer_Node_T* root = this->alloc_node (); + root->set (0, 0, ACE_Time_Value::zero, ACE_Time_Value::zero, root, root, 0); + this->spokes_[i] = root; + } + + ACE_NEW (iterator_, Iterator (*this)); +} + +/// Destructor just cleans up its memory +template +ACE_Timer_Wheel_T::~ACE_Timer_Wheel_T (void) +{ + ACE_TRACE ("ACE_Timer_Wheel_T::~ACE_Timer_Wheel_T"); + + delete iterator_; + + for (u_int i = 0; i < this->spoke_count_; ++i) + { + // Free all the nodes starting at the root + ACE_Timer_Node_T* root = this->spokes_[i]; + for (ACE_Timer_Node_T* n = root->get_next (); n != root;) + { + ACE_Timer_Node_T* next = n->get_next (); + this->upcall_functor ().deletion (*this, + n->get_type (), + n->get_act ()); + this->free_node (n); + n = next; + } + delete root; + } + delete[] this->spokes_; +} + +/// Searches for a node by timer_id within one spoke. +template +ACE_Timer_Node_T* +ACE_Timer_Wheel_T::find_spoke_node + (u_int spoke, long timer_id) const +{ + ACE_Timer_Node_T* root = this->spokes_[spoke]; + for (ACE_Timer_Node_T* n = root->get_next (); + n != root; + n = n->get_next ()) + { + if (n->get_timer_id () == timer_id) + return n; + } + return 0; +} + +/// Searches all spokes for a node matching the specified timer_id +/// Uses the spoke encoded in the timer_id as a starting place. +template +ACE_Timer_Node_T* +ACE_Timer_Wheel_T::find_node (long timer_id) const +{ + if (timer_id == -1) + return 0; + + // Search the spoke where timer_id was originally scheduled + u_int spoke_mask = this->spoke_count_ - 1; + u_int start = timer_id & spoke_mask; + ACE_Timer_Node_T* n = this->find_spoke_node (start, timer_id); + if (n != 0) + return n; + + //ACE_ERROR((LM_ERROR, "Node not found in original spoke.\n")); + + // Search the rest of the spokes + for (u_int i = 0; i < this->spoke_count_; ++i) + { + if (i != start) + { // already searched this one + n = this->find_spoke_node (i, timer_id); + if (n != 0) + return n; + } + } + + //ACE_ERROR((LM_ERROR, "Node not found.\n")); + return 0; +} + +/** +* Check to see if the wheel is empty +* +* @return True if empty +*/ +template bool +ACE_Timer_Wheel_T::is_empty (void) const +{ + ACE_TRACE ("ACE_Timer_Wheel_T::is_empty"); + return timer_count_ == 0; +} + + +/** +* @return First (earliest) node in the wheel_'s earliest_spoke_ list +*/ +template const ACE_Time_Value & +ACE_Timer_Wheel_T::earliest_time (void) const +{ + ACE_TRACE ("ACE_Timer_Wheel_T::earliest_time"); + ACE_Timer_Node_T* n = this->get_first_i (); + if (n != 0) + return n->get_timer_value (); + return ACE_Time_Value::zero; +} + +/// Uses a simple hash to find which spoke to use based on when the +/// timer is due to expire. Hopefully the 64bit int operations avoid +/// any overflow problems. +template u_int +ACE_Timer_Wheel_T::calculate_spoke + (const ACE_Time_Value& t) const +{ + return static_cast ((t.msec () >> this->res_bits_) & (this->spoke_count_ - 1)); +} + +/// Generates a unique timer_id for the given spoke. It should be pretty +/// fast until the point where the counter overflows. At that time you +/// have to do exhaustive searches within the spoke to ensure that a particular +/// timer id is not already in use. Some optimizations are in place so +/// that this hopefully doesn't have to happen often. +template long +ACE_Timer_Wheel_T::generate_timer_id (u_int spoke) +{ + + int cnt_bits = sizeof (long) * 8 - this->spoke_bits_; + long max_cnt = ((long)1 << cnt_bits) - 1; + if (spoke == this->spoke_count_) + --max_cnt; // Because -1 is used as a special invalid timer_id. + + ACE_Timer_Node_T* root = this->spokes_[spoke]; + + if (root == root->get_next ()) + root->set_act(0); + + // We use this field to keep track of the next counter value that + // may be in use. Of course it may have expired, so we just use + // this field so that we know when we don't have to check for duplicates +#if defined (ACE_WIN64) + // The cast below is legit... we know that long is shorter than a + // pointer, but are only using it as a 'long' storage area. +# pragma warning(push) +# pragma warning(disable : 4311) +#endif /* ACE_WIN64 */ + long next_cnt = reinterpret_cast (root->get_act ()); +#if defined (ACE_WIN64) +# pragma warning(pop) +#endif /* ACE_WIN64 */ + + // This field is used as a counter instead of a timer_id. + long cnt = root->get_timer_id (); + + if (cnt >= max_cnt && root == root->get_next ()) + { + // Special case when we overflow on an empty spoke. We can just + // wrap the count around without searching for duplicates. We only + // want to do this when the counter overflows, so that we return + // unique timer_id values as often as possible. + root->set_timer_id (1); + return spoke; + } + else if (cnt >= max_cnt) + { // overflow + cnt = 0; // try again starting at zero + } + else if (next_cnt == 0 || cnt < next_cnt) + { + root->set_timer_id (cnt + 1); + return (cnt << this->spoke_bits_) | spoke; + } + + //ACE_ERROR((LM_ERROR, "Timer id overflow. We have to search now.\n")); + + // We've run out of consecutive id numbers so now we have to search + // for a unique id. + // We'll try increasing numbers until we find one that is not in use, + // and we'll record the next highest number so that we can avoid this + // search as often as possible. + for (; cnt < max_cnt - 1; ++cnt) + { + long id = (cnt << this->spoke_bits_) | spoke; + ACE_Timer_Node_T* n = this->find_spoke_node (spoke, id); + if (n == 0) + { + root->set_timer_id (cnt + 1); + // Now we need to find the next highest cnt in use + next_cnt = 0; + for (; n != root; n = n->get_next ()) + { + long tmp = n->get_timer_id () >> this->spoke_bits_; + if (tmp > cnt && (tmp < next_cnt || next_cnt == 0)) + next_cnt = tmp; + } +#if defined (ACE_WIN64) + // The cast below is legit... we know we're storing a long in + // a pointer, but are only using it as a 'long' storage area. +# pragma warning(push) +# pragma warning(disable : 4312) +#endif /* ACE_WIN64 */ + root->set_act (reinterpret_cast (next_cnt)); +#if defined (ACE_WIN64) +# pragma warning(pop) +#endif /* ACE_WIN64 */ + return id; + } + } + + return -1; // We did our best, but the spoke is full. +} + +/** +* Creates a ACE_Timer_Node_T based on the input parameters. Then inserts +* the node into the wheel using reschedule (). Then returns a timer_id. +* +* @param type The data of the timer node +* @param act Asynchronous Completion Token (AKA magic cookie) +* @param future_time The time the timer is scheduled for (absolute time) +* @param interval If not ACE_Time_Value::zero, then this is a periodic +* timer and interval is the time period +* +* @return Unique identifier (can be used to cancel the timer). +* -1 on failure. +*/ +template long +ACE_Timer_Wheel_T::schedule_i (const TYPE& type, + const void* act, + const ACE_Time_Value& future_time, + const ACE_Time_Value& interval) +{ + ACE_TRACE ("ACE_Timer_Wheel_T::schedule_i"); + + ACE_Timer_Node_T* n = this->alloc_node (); + + if (n != 0) + { + u_int spoke = calculate_spoke (future_time); + long id = generate_timer_id (spoke); + + //ACE_ERROR((LM_ERROR, "Scheduling %x spoke:%d id:%d\n", (long) n, spoke, id)); + + if (id != -1) + { + n->set (type, act, future_time, interval, 0, 0, id); + this->schedule_i (n, spoke, future_time); + } + return id; + } + + // Failure return + errno = ENOMEM; + return -1; +} + +/** +* Takes an ACE_Timer_Node and inserts it into the correct position in +* the correct list. Also makes sure to update the earliest time. +* +* @param n The timer node to reschedule +*/ +template void +ACE_Timer_Wheel_T::reschedule (ACE_Timer_Node_T* n) +{ + ACE_TRACE ("ACE_Timer_Wheel_T::reschedule"); + const ACE_Time_Value& expire = n->get_timer_value (); + u_int spoke = calculate_spoke (expire); + this->schedule_i (n, spoke, expire); +} + +/// The shared scheduling functionality between schedule() and reschedule() +template void +ACE_Timer_Wheel_T::schedule_i + (ACE_Timer_Node_T* n, + u_int spoke, + const ACE_Time_Value& expire) +{ + // See if we need to update the earliest time + if (this->is_empty() || expire < this->earliest_time ()) + this->earliest_spoke_ = spoke; + + ACE_Timer_Node_T* root = this->spokes_[spoke]; + ACE_Timer_Node_T* last = root->get_prev (); + + ++timer_count_; + + // If the spoke is empty + if (last == root) { + n->set_prev (root); + n->set_next (root); + root->set_prev (n); + root->set_next (n); + return; + } + + // We always want to search backwards from the tail of the list, because + // this minimizes the search in the extreme case when lots of timers are + // scheduled for exactly the same time + ACE_Timer_Node_T* p = root->get_prev (); + while (p != root && p->get_timer_value () > expire) + p = p->get_prev (); + + // insert after + n->set_prev (p); + n->set_next (p->get_next ()); + p->get_next ()->set_prev (n); + p->set_next (n); +} + + +/** +* Find the timer node by using the id as a pointer. Then use set_interval() +* on the node to update the interval. +* +* @param timer_id The timer identifier +* @param interval The new interval +* +* @return 0 if successful, -1 if no. +*/ +template int +ACE_Timer_Wheel_T::reset_interval (long timer_id, + const ACE_Time_Value &interval + ) +{ + ACE_TRACE ("ACE_Timer_Wheel_T::reset_interval"); + ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); + ACE_Timer_Node_T* n = this->find_node (timer_id); + if (n != 0) + { + // The interval will take effect the next time this node is expired. + n->set_interval (interval); + return 0; + } + return -1; +} + + +/** +* Goes through every list in the wheel and whenever we find one with the +* correct type value, we remove it and continue. At the end make sure +* we reset the earliest time value in case the earliest timers were +* removed. +* +* @param type The value to search for. +* @param skip_close If this non-zero, the cancellation method of the +* functor will not be called for each cancelled timer. +* +* @return Number of timers cancelled +*/ +template int +ACE_Timer_Wheel_T::cancel (const TYPE& type, int skip_close) +{ + ACE_TRACE ("ACE_Timer_Wheel_T::cancel"); + + int num_canceled = 0; // Note : Technically this can overflow. + int cookie = 0; + + ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); + + if (!this->is_empty ()) + { + ACE_Timer_Node_T* first = this->get_first (); + ACE_Time_Value last = first->get_timer_value (); + int recalc = 0; + + for (u_int i = 0; i < this->spoke_count_; ++i) + { + ACE_Timer_Node_T* root = this->spokes_[i]; + for (ACE_Timer_Node_T* n = root->get_next (); n != root; ) + { + if (n->get_type () == type) + { + ++num_canceled; + if (n == first) + recalc = 1; + + ACE_Timer_Node_T* tmp = n; + n = n->get_next (); + + this->cancel_i (tmp); + } + else + { + n = n->get_next (); + } + } + } + + if (recalc) + this->recalc_earliest (last); + } + + // Call the close hooks. + + // cancel_type() called once per . + this->upcall_functor ().cancel_type (*this, + type, + skip_close, + cookie); + + for (int i = 0; + i < num_canceled; + ++i) + { + // cancel_timer() called once per . + this->upcall_functor ().cancel_timer (*this, + type, + skip_close, + cookie); + } + + return num_canceled; +} + + +/** +* Cancels the single timer that is specified by the timer_id. In this +* case the timer_id is actually a pointer to the node, so we cast it +* to the node. This can be dangerous if the timer_id is made up +* (or deleted twice) so we do a little sanity check. Finally we update +* the earliest time in case the earliest timer was removed. +* +* @param timer_id Timer Identifier +* @param act Asychronous Completion Token (AKA magic cookie): +* If this is non-zero, stores the magic cookie of +* the cancelled timer here. +* @param skip_close If this non-zero, the cancellation method of the +* functor will not be called. +* +* @return 1 for sucess and 0 if the timer_id wasn't found (or was +* found to be invalid) +*/ +template int +ACE_Timer_Wheel_T::cancel (long timer_id, + const void **act, + int skip_close) +{ + ACE_TRACE ("ACE_Timer_Wheel_T::cancel"); + ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); + ACE_Timer_Node_T* n = this->find_node (timer_id); + if (n != 0) + { + ACE_Time_Value last = n->get_timer_value (); + + int recalc = (this->get_first_i () == n); + + // Call the close hooks. + int cookie = 0; + + // cancel_type() called once per . + this->upcall_functor ().cancel_type (*this, + n->get_type (), + skip_close, + cookie); + + // cancel_timer() called once per . + this->upcall_functor ().cancel_timer (*this, + n->get_type (), + skip_close, + cookie); + if (act != 0) + *act = n->get_act (); + + this->cancel_i (n); + + if (recalc) + this->recalc_earliest (last); + + return 1; + } + return 0; +} + +/// Shared subset of the two cancel() methods. +template void +ACE_Timer_Wheel_T::cancel_i (ACE_Timer_Node_T* n) +{ + this->unlink (n); + this->free_node (n); +} + +/// There are a few places where we have to figure out which timer +/// will expire next. This method makes the assumption that spokes +/// are always sorted, and that timers are always in the correct spoke +/// determined from their expiration time. +/// The last time is always passed in, even though you can often calculate +/// it as get_first()->get_timer_value(). +template void +ACE_Timer_Wheel_T::recalc_earliest + (const ACE_Time_Value& last) +{ + // This is possible because we use a count for is_empty() + if (this->is_empty ()) + return; + + ACE_Time_Value et = ACE_Time_Value::zero; + u_int es = 0; + u_int spoke = this->earliest_spoke_; + + // We will have to go around the wheel at most one time. + for (u_int i = 0; i < this->spoke_count_; ++i) + { + ACE_Timer_Node_T* root = this->spokes_[spoke]; + ACE_Timer_Node_T* n = root->get_next (); + if (n != root) + { + ACE_Time_Value t = n->get_timer_value (); + if (t < last + this->wheel_time_) + { + this->earliest_spoke_ = spoke; + return; + } + else if (et == ACE_Time_Value::zero || t < et) + { + et = t; + es = spoke; + } + } + if (++spoke >= this->spoke_count_) + spoke = 0; + } + + this->earliest_spoke_ = es; + //ACE_ERROR((LM_ERROR, "We had to search the whole wheel.\n")); +} + +/** +* Dumps out the size of the wheel, the resolution, and the contents +* of the wheel. +*/ +template void +ACE_Timer_Wheel_T::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Timer_Wheel_T::dump"); + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("\nspoke_count_ = %d"), this->spoke_count_)); + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("\nresolution_ = %d"), 1 << this->res_bits_)); + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("\nwheel_ =\n"))); + + for (u_int i = 0; i < this->spoke_count_; ++i) + { + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("%d\n"), i)); + ACE_Timer_Node_T* root = this->spokes_[i]; + for (ACE_Timer_Node_T* n = root->get_next (); + n != root; + n = n->get_next ()) + { + n->dump (); + } + } + + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + + +/** +* Removes the earliest node and then find the new +* +* @return The earliest timer node. +*/ +template ACE_Timer_Node_T * +ACE_Timer_Wheel_T::remove_first (void) +{ + ACE_TRACE ("ACE_Timer_Wheel_T::remove_first"); + return remove_first_expired (ACE_Time_Value::max_time); +} + +template void +ACE_Timer_Wheel_T::unlink (ACE_Timer_Node_T* n) +{ + ACE_TRACE ("ACE_Timer_Wheel_T::unlink"); + --timer_count_; + n->get_prev ()->set_next (n->get_next ()); + n->get_next ()->set_prev (n->get_prev ()); + n->set_prev (0); + n->set_next (0); +} + +template ACE_Timer_Node_T * +ACE_Timer_Wheel_T::remove_first_expired (const ACE_Time_Value& now) +{ + ACE_Timer_Node_T* n = this->get_first (); + if (n != 0 && n->get_timer_value() <= now) + { + this->unlink (n); + this->recalc_earliest (n->get_timer_value ()); + return n; + } + return 0; +} + +/** +* Returns the earliest node without removing it +* +* @return The earliest timer node. +*/ +template +ACE_Timer_Node_T* +ACE_Timer_Wheel_T::get_first (void) +{ + ACE_TRACE ("ACE_Timer_Wheel_T::get_first"); + return this->get_first_i (); +} + +template +ACE_Timer_Node_T* +ACE_Timer_Wheel_T::get_first_i (void) const +{ + ACE_Timer_Node_T* root = this->spokes_[this->earliest_spoke_]; + ACE_Timer_Node_T* first = root->get_next (); + if (first != root) + return first; + return 0; +} + + +/** +* @return The iterator +*/ +template +ACE_Timer_Queue_Iterator_T& +ACE_Timer_Wheel_T::iter (void) +{ + this->iterator_->first (); + return *this->iterator_; +} + +/** +* Dummy version of expire to get rid of warnings in Sun CC 4.2 +* Just call the expire of the base class. +*/ +template int +ACE_Timer_Wheel_T::expire () +{ + return ACE_Timer_Queue_T::expire (); +} + +/** +* This is a specialized version of expire that is more suited for the +* internal data representation. +* +* @param cur_time The time to expire timers up to. +* +* @return Number of timers expired +*/ +template int +ACE_Timer_Wheel_T::expire (const ACE_Time_Value& cur_time) +{ + ACE_TRACE ("ACE_Timer_Wheel_T::expire"); + + int expcount = 0; + + ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); + + ACE_Timer_Node_T* n = this->remove_first_expired (cur_time); + + while (n != 0) + { + ++expcount; + + //ACE_ERROR((LM_ERROR, "Expiring %x\n", (long) n)); + + ACE_Timer_Node_Dispatch_Info_T info; + + // Get the dispatch info + n->get_dispatch_info (info); + + if (n->get_interval () > ACE_Time_Value::zero) + { + // Make sure that we skip past values that have already + // "expired". + this->recompute_next_abs_interval_time (n, cur_time); + + this->reschedule (n); + } + else + { + this->free_node (n); + } + + const void *upcall_act = 0; + + this->preinvoke (info, cur_time, upcall_act); + + this->upcall (info, cur_time); + + this->postinvoke (info, cur_time, upcall_act); + + n = this->remove_first_expired (cur_time); + } + + return expcount; +} + +/////////////////////////////////////////////////////////////////////////// +// ACE_Timer_Wheel_Iterator_T + +/** +* Just initializes the iterator with a ACE_Timer_Wheel_T and then calls +* first() to initialize the rest of itself. +* +* @param wheel A reference for a timer queue to iterate over +*/ +template +ACE_Timer_Wheel_Iterator_T::ACE_Timer_Wheel_Iterator_T +(Wheel& wheel) +: timer_wheel_ (wheel) +{ + this->first(); +} + + +/** +* Destructor, at this level does nothing. +*/ +template +ACE_Timer_Wheel_Iterator_T::~ACE_Timer_Wheel_Iterator_T (void) +{ +} + + +/** +* Positions the iterator at the first position in the timing wheel +* that contains something. spoke_ will be set to the spoke position of +* this entry and current_node_ will point to the first entry in that spoke. +* +* If the wheel is empty, spoke_ will be equal timer_wheel_.spoke_count_ and +* current_node_ would be 0. +*/ +template void +ACE_Timer_Wheel_Iterator_T::first (void) +{ + this->goto_next(0); +} + + +/** +* Positions the iterator at the next node. +*/ +template void +ACE_Timer_Wheel_Iterator_T::next (void) +{ + if (this->isdone()) + return; + + ACE_Timer_Node_T* n = this->current_node_->get_next (); + ACE_Timer_Node_T* root = this->timer_wheel_.spokes_[this->spoke_]; + if (n == root) + this->goto_next (this->spoke_ + 1); + else + this->current_node_ = n; +} + +/// Helper class for common functionality of next() and first() +template void +ACE_Timer_Wheel_Iterator_T::goto_next (u_int start_spoke) +{ + // Find the first non-empty entry. + u_int sc = this->timer_wheel_.spoke_count_; + for (u_int i = start_spoke; i < sc; ++i) + { + ACE_Timer_Node_T* root = this->timer_wheel_.spokes_[i]; + ACE_Timer_Node_T* n = root->get_next (); + if (n != root) + { + this->spoke_ = i; + this->current_node_ = n; + return; + } + } + // empty + this->spoke_ = sc; + this->current_node_ = 0; +} + +/** +* @return True when we there aren't any more items (when current_node_ == 0) +*/ +template bool +ACE_Timer_Wheel_Iterator_T::isdone (void) const +{ + return this->current_node_ == 0; +} + +/** +* @return The node at the current spokeition in the sequence or 0 if the wheel +* is empty +*/ +template ACE_Timer_Node_T * +ACE_Timer_Wheel_Iterator_T::item (void) +{ + return this->current_node_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_TIMER_WHEEL_T_CPP */ diff --git a/dep/acelite/ace/Timer_Wheel_T.h b/dep/acelite/ace/Timer_Wheel_T.h new file mode 100644 index 00000000000..266099f2e6a --- /dev/null +++ b/dep/acelite/ace/Timer_Wheel_T.h @@ -0,0 +1,226 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Timer_Wheel_T.h + * + * $Id: Timer_Wheel_T.h 84619 2009-02-26 12:26:16Z johnnyw $ + * + * @author Darrell Brunsch + */ +//============================================================================= + +#ifndef ACE_TIMER_WHEEL_T_H +#define ACE_TIMER_WHEEL_T_H +#include /**/ "ace/pre.h" + +#include "ace/Timer_Queue_T.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Forward declaration +template +class ACE_Timer_Wheel_T; + +/** + * @class ACE_Timer_Wheel_Iterator_T + * + * @brief Iterates over an ACE_Timer_Wheel. + * + * This is a generic iterator that can be used to visit every + * node of a timer queue. Be aware that it doesn't traverse + * in the order of timeout values. + */ +template +class ACE_Timer_Wheel_Iterator_T + : public ACE_Timer_Queue_Iterator_T +{ +public: + typedef ACE_Timer_Wheel_T Wheel; + typedef ACE_Timer_Node_T Node; + + /// Constructor + ACE_Timer_Wheel_Iterator_T (Wheel &); + + /// Destructor + ~ACE_Timer_Wheel_Iterator_T (void); + + /// Positions the iterator at the earliest node in the Timer Queue + virtual void first (void); + + /// Positions the iterator at the next node in the Timer Queue + virtual void next (void); + + /// Returns true when there are no more nodes in the sequence + virtual bool isdone (void) const; + + /// Returns the node at the current position in the sequence + virtual ACE_Timer_Node_T* item (void); + +protected: + /// Pointer to the ACE_Timer_List that we are iterating over. + Wheel& timer_wheel_; + + /// Current position in the timing wheel + u_int spoke_; + + /// Pointer to the position in the the th list + ACE_Timer_Node_T* current_node_; +private: + void goto_next(u_int start_spoke); +}; + +/** + * @class ACE_Timer_Wheel_T + * + * @brief Provides a Timing Wheel version of ACE_Timer_Queue. + * + * This implementation uses a hash table of ordered doubly- + * linked lists of absolute times. The enhancements over the + * @c ACE_Timer_List include adding a free list and the ability + * to preallocate nodes. Timer Wheel is based on the timing + * wheel implementation used in Adam M. Costello and + * George Varghese's paper "Redesigning the BSD Callout and + * Timer Facilities" + * (http://dworkin.wustl.edu/~varghese/PAPERS/newbsd.ps.Z) + */ +template +class ACE_Timer_Wheel_T : public ACE_Timer_Queue_T +{ +public: + /// Type of iterator + typedef ACE_Timer_Wheel_Iterator_T Iterator; + /// Iterator is a friend + friend class ACE_Timer_Wheel_Iterator_T; + typedef ACE_Timer_Node_T Node; + /// Type inherited from + typedef ACE_Timer_Queue_T Base; + typedef ACE_Free_List FreeList; + + /// Default constructor + ACE_Timer_Wheel_T (FUNCTOR* upcall_functor = 0, FreeList* freelist = 0); + + /// Constructor with opportunities to set the wheelsize and resolution + ACE_Timer_Wheel_T (u_int spoke_count, + u_int resolution, + size_t prealloc = 0, + FUNCTOR* upcall_functor = 0, + FreeList* freelist = 0); + + /// Destructor + virtual ~ACE_Timer_Wheel_T (void); + + /// True if queue is empty, else false. + virtual bool is_empty (void) const; + + /// Returns the time of the earlier node in the ACE_Timer_Wheel. + /// Must be called on a non-empty queue. + virtual const ACE_Time_Value& earliest_time (void) const; + + /// Changes the interval of a timer (and can make it periodic or non + /// periodic by setting it to ACE_Time_Value::zero or not). + virtual int reset_interval (long timer_id, + const ACE_Time_Value& interval); + + /// Cancel all timer associated with @a type. If @a dont_call_handle_close is + /// 0 then the will be invoked. Returns number of timers + /// cancelled. + virtual int cancel (const TYPE& type, + int dont_call_handle_close = 1); + + // Cancel a timer, storing the magic cookie in act (if nonzero). + // Calls the functor if dont_call_handle_close is 0 and returns 1 + // on success + virtual int cancel (long timer_id, + const void** act = 0, + int dont_call_handle_close = 1); + + /// Run the for all timers whose values are <= + /// . Also accounts for . Returns + /// the number of timers canceled. + virtual int expire (void); + + // Run the for all timers whose values are <= @a current_time. + // This does not account for . Returns the number of + // timers canceled. + int expire (const ACE_Time_Value& current_time); + + /// Returns a pointer to this 's iterator. + virtual ACE_Timer_Queue_Iterator_T& iter (void); + + /// Removes the earliest node from the queue and returns it + virtual ACE_Timer_Node_T* remove_first (void); + + /// Dump the state of an object. + virtual void dump (void) const; + + /// Reads the earliest node from the queue and returns it. + virtual ACE_Timer_Node_T* get_first (void); + +protected: + + /// Schedules a timer. + virtual long schedule_i (const TYPE& type, + const void* act, + const ACE_Time_Value& future_time, + const ACE_Time_Value& interval); + +private: + // The following are documented in the .cpp file. + ACE_Timer_Node_T* get_first_i (void) const; + ACE_Timer_Node_T* remove_first_expired (const ACE_Time_Value& now); + void open_i (size_t prealloc, u_int spokes, u_int res); + virtual void reschedule (ACE_Timer_Node_T *); + ACE_Timer_Node_T* find_spoke_node(u_int spoke, long timer_id) const; + ACE_Timer_Node_T* find_node(long timer_id) const; + u_int calculate_spoke(const ACE_Time_Value& expire) const; + long generate_timer_id(u_int spoke); + void schedule_i (ACE_Timer_Node_T* n, u_int spoke, const ACE_Time_Value& expire); + void cancel_i (ACE_Timer_Node_T* n); + void unlink (ACE_Timer_Node_T* n); + void recalc_earliest(const ACE_Time_Value& last); + +private: + int power2bits (int n, int min_bits, int max_bits); + + /// Timing Wheel. + ACE_Timer_Node_T** spokes_; + /// Size of the timing wheel. + u_int spoke_count_; + /// Number of timer_id bits used for the spoke + int spoke_bits_; + /// Maximum number of timers per spoke + u_int max_per_spoke_; + /// Resolution (in microsoconds) of the timing wheel. + int res_bits_; + /// Index of the list with the earliest time + u_int earliest_spoke_; + /// Iterator used to expire timers. + Iterator* iterator_; + /// The total amount of time in one iteration of the wheel. (resolution * spoke_count) + ACE_Time_Value wheel_time_; + /// The total number of timers currently scheduled. + u_int timer_count_; + + // = Don't allow these operations for now, don't split into multiple lines + // breaks sun compilers + ACE_UNIMPLEMENTED_FUNC (ACE_Timer_Wheel_T (const ACE_Timer_Wheel_T &)) + ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Timer_Wheel_T &)) +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Timer_Wheel_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Timer_Wheel_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" +#endif /* ACE_TIMER_WHEEL_T_H */ diff --git a/dep/acelite/ace/Token.cpp b/dep/acelite/ace/Token.cpp new file mode 100644 index 00000000000..9993261be17 --- /dev/null +++ b/dep/acelite/ace/Token.cpp @@ -0,0 +1,545 @@ +// $Id: Token.cpp 83735 2008-11-14 09:41:52Z johnnyw $ + +#include "ace/Token.h" + +#if !defined (__ACE_INLINE__) +# include "ace/Token.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID(ace, Token, "$Id: Token.cpp 83735 2008-11-14 09:41:52Z johnnyw $") + +#if defined (ACE_HAS_THREADS) + +#include "ace/Thread.h" +#include "ace/Log_Msg.h" + +#if defined (ACE_TOKEN_DEBUGGING) +// FUZZ: disable check_for_streams_include +#include "ace/streams.h" +#endif /* ACE_TOKEN_DEBUGGING */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Token) + +void +ACE_Token::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Token::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nthread = %d"), ACE_Thread::self ())); + // @@ Is there a portable way to do this? + // ACE_DEBUG ((LM_DEBUG, "\nowner_ = %d", (long) this->owner_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nowner_ addr = %x"), &this->owner_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nwaiters_ = %d"), this->waiters_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nin_use_ = %d"), this->in_use_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nnesting level = %d"), this->nesting_level_)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +ACE_Token::ACE_Token_Queue_Entry::ACE_Token_Queue_Entry (ACE_Thread_Mutex &m, + ACE_thread_t t_id) + : next_ (0), + thread_id_ (t_id), +#if defined (ACE_TOKEN_USES_SEMAPHORE) + cv_ (0), +#else + cv_ (m), +#endif /* ACE_TOKEN_USES_SEMAPHORE */ + runable_ (0) +{ +#if defined (ACE_TOKEN_USES_SEMAPHORE) + ACE_UNUSED_ARG (m); +#endif /* ACE_TOKEN_USES_SEMAPHORE */ + + ACE_TRACE ("ACE_Token::ACE_Token_Queue_Entry::ACE_Token_Queue_Entry"); +} + +ACE_Token::ACE_Token_Queue_Entry::ACE_Token_Queue_Entry (ACE_Thread_Mutex &m, + ACE_thread_t t_id, + ACE_Condition_Attributes &attributes) + : next_ (0), + thread_id_ (t_id), +#if defined (ACE_TOKEN_USES_SEMAPHORE) + cv_ (0), +#else + cv_ (m, attributes), +#endif /* ACE_TOKEN_USES_SEMAPHORE */ + runable_ (0) +{ +#if defined (ACE_TOKEN_USES_SEMAPHORE) + ACE_UNUSED_ARG (m); + ACE_UNUSED_ARG (attributes); +#endif /* ACE_TOKEN_USES_SEMAPHORE */ + + ACE_TRACE ("ACE_Token::ACE_Token_Queue_Entry::ACE_Token_Queue_Entry"); +} + +ACE_Token::ACE_Token_Queue::ACE_Token_Queue (void) + : head_ (0), + tail_ (0) +{ + ACE_TRACE ("ACE_Token::ACE_Token_Queue::ACE_Token_Queue"); +} + +// +// Remove an entry from the list. Must be called with locks held. +// +void +ACE_Token::ACE_Token_Queue::remove_entry (ACE_Token::ACE_Token_Queue_Entry *entry) +{ + ACE_TRACE ("ACE_Token::ACE_Token_Queue::remove_entry"); + ACE_Token_Queue_Entry *curr = 0; + ACE_Token_Queue_Entry *prev = 0; + + if (this->head_ == 0) + return; + + for (curr = this->head_; + curr != 0 && curr != entry; + curr = curr->next_) + prev = curr; + + if (curr == 0) + // Didn't find the entry... + return; + else if (prev == 0) + // Delete at the head. + this->head_ = this->head_->next_; + else + // Delete in the middle. + prev->next_ = curr->next_; + + // We need to update the tail of the list if we've deleted the last + // entry. + if (curr->next_ == 0) + this->tail_ = prev; +} + +// +// Add an entry into the list. Must be called with locks held. +// +void +ACE_Token::ACE_Token_Queue::insert_entry (ACE_Token::ACE_Token_Queue_Entry &entry, + int requeue_position) +{ + if (this->head_ == 0) + { + // No other threads - just add me + this->head_ = &entry; + this->tail_ = &entry; + } + else if (requeue_position == -1) + { + // Insert at the end of the queue. + this->tail_->next_ = &entry; + this->tail_ = &entry; + } + else if (requeue_position == 0) + { + // Insert at head of queue. + entry.next_ = this->head_; + this->head_ = &entry; + } + else + // Insert in the middle of the queue somewhere. + { + // Determine where our thread should go in the queue of waiters. + + ACE_Token::ACE_Token_Queue_Entry *insert_after = this->head_; + while (requeue_position-- && insert_after->next_ != 0) + insert_after = insert_after->next_; + + entry.next_ = insert_after->next_; + + if (entry.next_ == 0) + this->tail_ = &entry; + + insert_after->next_ = &entry; + } +} + +ACE_Token::ACE_Token (const ACE_TCHAR *name, void *any) + : lock_ (name, (ACE_mutexattr_t *) any), + owner_ (ACE_OS::NULL_thread), + in_use_ (0), + waiters_ (0), + nesting_level_ (0), + attributes_ (USYNC_THREAD), + queueing_strategy_ (FIFO) +{ +// ACE_TRACE ("ACE_Token::ACE_Token"); +} + +ACE_Token::~ACE_Token (void) +{ + ACE_TRACE ("ACE_Token::~ACE_Token"); +} + +int +ACE_Token::shared_acquire (void (*sleep_hook_func)(void *), + void *arg, + ACE_Time_Value *timeout, + ACE_Token_Op_Type op_type) +{ + ACE_TRACE ("ACE_Token::shared_acquire"); + ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1); + +#if defined (ACE_TOKEN_DEBUGGING) + this->dump (); +#endif /* ACE_TOKEN_DEBUGGING */ + + ACE_thread_t const thr_id = ACE_Thread::self (); + + // Nobody holds the token. + if (!this->in_use_) + { + // Its mine! + this->in_use_ = op_type; + this->owner_ = thr_id; + return 0; + } + + // + // Someone already holds the token. + // + + // Check if it is us. + if (ACE_OS::thr_equal (thr_id, this->owner_)) + { + ++this->nesting_level_; + return 0; + } + + // Do a quick check for "polling" behavior. + if (timeout != 0 && *timeout == ACE_Time_Value::zero) + { + errno = ETIME; + return -1; + } + + // + // We've got to sleep until we get the token. + // + + // Which queue we should end up in... + ACE_Token_Queue *queue = (op_type == ACE_Token::READ_TOKEN + ? &this->readers_ + : &this->writers_); + + // Allocate queue entry on stack. This works since we don't exit + // this method's activation record until we've got the token. + ACE_Token::ACE_Token_Queue_Entry my_entry (this->lock_, + thr_id, + this->attributes_); + queue->insert_entry (my_entry, this->queueing_strategy_); + ++this->waiters_; + + // Execute appropriate callback. (@@ should these + // methods return a success/failure status, and if so, what should + // we do with it?) + int ret = 0; + if (sleep_hook_func) + { + (*sleep_hook_func) (arg); + ++ret; + } + else + { + // Execute virtual method. + this->sleep_hook (); + ++ret; + } + + bool timed_out = false; + bool error = false; + + // Sleep until we've got the token (ignore signals). + do + { + int const result = my_entry.wait (timeout, this->lock_); + + if (result == -1) + { + // Note, this should obey whatever thread-specific interrupt + // policy is currently in place... + if (errno == EINTR) + continue; + +#if defined (ACE_TOKEN_DEBUGGING) + cerr << '(' << ACE_Thread::self () << ')' + << " acquire: " + << (errno == ETIME ? "timed out" : "error occurred") + << endl; +#endif /* ACE_TOKEN_DEBUGGING */ + + // We come here if a timeout occurs or some serious + // ACE_Condition object error. + if (errno == ETIME) + timed_out = true; + else + error = true; + + // Stop the loop. + break; + } + } + while (!ACE_OS::thr_equal (thr_id, this->owner_)); + + // Do this always and irrespective of the result of wait(). + --this->waiters_; + queue->remove_entry (&my_entry); + +#if defined (ACE_TOKEN_DEBUGGING) + ACE_DEBUG ((LM_DEBUG, "(%t) ACE_Token::shared_acquire (UNBLOCKED)\n")); +#endif /* ACE_TOKEN_DEBUGGING */ + + // If timeout occured + if (timed_out) + { + // This thread was still selected to own the token. + if (my_entry.runable_) + { + // Wakeup next waiter since this thread timed out. + this->wakeup_next_waiter (); + } + + // Return error. + return -1; + } + else if (error) + { + // Return error. + return -1; + } + + // If this is a normal wakeup, this thread should be runnable. + ACE_ASSERT (my_entry.runable_); + + return ret; +} + +// By default this is a no-op. + +/* virtual */ +void +ACE_Token::sleep_hook (void) +{ + ACE_TRACE ("ACE_Token::sleep_hook"); +} + +int +ACE_Token::acquire (ACE_Time_Value *timeout) +{ + ACE_TRACE ("ACE_Token::acquire"); + return this->shared_acquire (0, 0, timeout, ACE_Token::WRITE_TOKEN); +} + +// Acquire the token, sleeping until it is obtained or until +// expires. + +int +ACE_Token::acquire (void (*sleep_hook_func)(void *), + void *arg, + ACE_Time_Value *timeout) +{ + ACE_TRACE ("ACE_Token::acquire"); + return this->shared_acquire (sleep_hook_func, arg, timeout, ACE_Token::WRITE_TOKEN); +} + +// Try to renew the token. + +int +ACE_Token::renew (int requeue_position, + ACE_Time_Value *timeout) +{ + ACE_TRACE ("ACE_Token::renew"); + ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1); + +#if defined (ACE_TOKEN_DEBUGGING) + this->dump (); +#endif /* ACE_TOKEN_DEBUGGING */ + // ACE_ASSERT (ACE_OS::thr_equal (ACE_Thread::self (), this->owner_)); + + // Check to see if there are any waiters worth giving up the lock + // for. + + // If no writers and either we are a writer or there are no readers. + if (this->writers_.head_ == 0 && + (this->in_use_ == ACE_Token::WRITE_TOKEN || + this->readers_.head_ == 0)) + // Immediate return. + return 0; + + // We've got to sleep until we get the token again. + + // Determine which queue should this thread go to. + ACE_Token::ACE_Token_Queue *this_threads_queue = + this->in_use_ == ACE_Token::READ_TOKEN ? + &this->readers_ : &this->writers_; + + ACE_Token::ACE_Token_Queue_Entry my_entry (this->lock_, + this->owner_); + + this_threads_queue->insert_entry (my_entry, + // if requeue_position == 0 then we want to go next, + // otherwise use the queueing strategy, which might also + // happen to be 0. + requeue_position == 0 ? 0 : this->queueing_strategy_); + ++this->waiters_; + + // Remember nesting level... + int const save_nesting_level_ = this->nesting_level_; + + // Reset state for new owner. + this->nesting_level_ = 0; + + // Wakeup waiter. + this->wakeup_next_waiter (); + + bool timed_out = false; + bool error = false; + + // Sleep until we've got the token (ignore signals). + do + { + int const result = my_entry.wait (timeout, this->lock_); + + if (result == -1) + { + // Note, this should obey whatever thread-specific interrupt + // policy is currently in place... + if (errno == EINTR) + continue; + +#if defined (ACE_TOKEN_DEBUGGING) + cerr << '(' << ACE_Thread::self () << ')' + << " renew: " + << (errno == ETIME ? "timed out" : "error occurred") + << endl; +#endif /* ACE_TOKEN_DEBUGGING */ + + // We come here if a timeout occurs or some serious + // ACE_Condition object error. + if (errno == ETIME) + timed_out = true; + else + error = true; + + // Stop the loop. + break; + } + } + while (!ACE_OS::thr_equal (my_entry.thread_id_, this->owner_)); + + // Do this always and irrespective of the result of wait(). + --this->waiters_; + this_threads_queue->remove_entry (&my_entry); + +#if defined (ACE_TOKEN_DEBUGGING) + ACE_DEBUG ((LM_DEBUG, "(%t) ACE_Token::renew (UNBLOCKED)\n")); +#endif /* ACE_TOKEN_DEBUGGING */ + + // If timeout occured + if (timed_out) + { + // This thread was still selected to own the token. + if (my_entry.runable_) + { + // Wakeup next waiter since this thread timed out. + this->wakeup_next_waiter (); + } + + // Return error. + return -1; + } + else if (error) + { + // Return error. + return -1; + } + + // If this is a normal wakeup, this thread should be runnable. + ACE_ASSERT (my_entry.runable_); + + // Reinstate nesting level. + this->nesting_level_ = save_nesting_level_; + + return 0; +} + +// Release the current holder of the token (which had +// better be the caller's thread!). + +int +ACE_Token::release (void) +{ + ACE_TRACE ("ACE_Token::release"); + ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1); + +#if defined (ACE_TOKEN_DEBUGGING) + this->dump (); +#endif /* ACE_TOKEN_DEBUGGING */ + + // Nested release... + if (this->nesting_level_ > 0) + --this->nesting_level_; + else + { + // + // Regular release... + // + + // Wakeup waiter. + this->wakeup_next_waiter (); + } + + return 0; +} + +void +ACE_Token::wakeup_next_waiter (void) +{ + ACE_TRACE ("ACE_Token::wakeup_next_waiter"); + + // Reset state for new owner. + this->owner_ = ACE_OS::NULL_thread; + this->in_use_ = 0; + + // Any waiters... + if (this->writers_.head_ == 0 && + this->readers_.head_ == 0) + { + // No more waiters... + return; + } + + // Wakeup next waiter. + ACE_Token_Queue *queue = 0; + + // Writer threads get priority to run first. + if (this->writers_.head_ != 0) + { + this->in_use_ = ACE_Token::WRITE_TOKEN; + queue = &this->writers_; + } + else + { + this->in_use_ = ACE_Token::READ_TOKEN; + queue = &this->readers_; + } + + // Wake up waiter and make it runable. + queue->head_->runable_ = 1; + queue->head_->signal (); + + this->owner_ = queue->head_->thread_id_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_THREADS */ diff --git a/dep/acelite/ace/Token.h b/dep/acelite/ace/Token.h new file mode 100644 index 00000000000..7857c44dfb5 --- /dev/null +++ b/dep/acelite/ace/Token.h @@ -0,0 +1,376 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Token.h + * + * $Id: Token.h 85367 2009-05-18 10:11:54Z johnnyw $ + * + * @author Original author + * @author Karl-Heinz Dorn (kdorn@erlh.siemens.de) + * @author Ported to ACE by + * @author Douglas C. Schmidt (schmidt@cs.wustl.edu) + */ +//============================================================================= + +#ifndef ACE_TOKEN_H +#define ACE_TOKEN_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Null_Mutex.h" + +#if defined (ACE_HAS_THREADS) + +#include "ace/Thread_Mutex.h" + +#if (defined (ACE_WIN32) && !defined (ACE_USES_WINCE_SEMA_SIMULATION)) || defined (ACE_HAS_VXTHREADS) +// If platforms support semaphores with timed wait, then we use semaphores instead of c.v. +# define ACE_TOKEN_USES_SEMAPHORE +#endif /* ACE_WIN32 || ACE_HAS_VXTHREADS */ + +#if defined (ACE_TOKEN_USES_SEMAPHORE) +# include "ace/Semaphore.h" +#endif /* ACE_TOKEN_USES_SEMAPHORE */ + +#include "ace/Condition_Thread_Mutex.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +class ACE_Time_Value; + +/** + * @class ACE_Token + * + * @brief Class that acquires, renews, and releases a synchronization + * token that is serviced in strict FIFO/LIFO ordering and that also + * supports (1) recursion and (2) readers/writer semantics. + * + * This class is a more general-purpose synchronization mechanism + * than many native OS mutexes. For example, it implements + * "recursive mutex" semantics, where a thread that owns the token + * can reacquire it without deadlocking. If the same thread calls + * multiple times, however, it must call an + * equal number of times before the token is actually released. + * Threads that are blocked awaiting the token are serviced in + * strict FIFO/LIFO order as other threads release the token (Solaris + * and Pthread mutexes don't strictly enforce an acquisition + * order). There are two lists within the class. Write + * acquires always have higher priority over read acquires. Which + * means, if you use both write/read operations, care must be + * taken to avoid starvation on the readers. Notice that the + * read/write acquire operations do not have the usual semantic of + * reader/writer locks. Only one reader can acquire the token at + * a time (which is different from the usual reader/writer locks + * where several readers can acquire a lock at the same time as + * long as there is no writer waiting for the lock). We choose + * the names to (1) borrow the semantic to give writers higher + * priority and (2) support a common interface for all locking + * classes in ACE. + */ +class ACE_Export ACE_Token +{ +public: + + /** + * Available queueing strategies. + */ + enum QUEUEING_STRATEGY + { + /// FIFO, First In, First Out. + FIFO = -1, + /// LIFO, Last In, First Out + LIFO = 0 + }; + + // = Initialization and termination. + + /// Constructor + ACE_Token (const ACE_TCHAR *name = 0, void * = 0); + + /// Destructor + virtual ~ACE_Token (void); + + // = Strategies + + /// Retrieve the current queueing strategy. + int queueing_strategy (void); + + /// Set the queueing strategy. + void queueing_strategy (int queueing_strategy); + + // = Synchronization operations. + + /** + * Acquire the token, sleeping until it is obtained or until the + * expiration of @a timeout, which is treated as "absolute" time. If + * some other thread currently holds the token then is + * called before our thread goes to sleep. This can be + * used by the requesting thread to unblock a token-holder that is + * sleeping, e.g., by means of writing to a pipe (the ACE + * ACE_Reactor uses this functionality). Return values: 0 if + * acquires without calling 1 if is + * called. 2 if the token is signaled. -1 if failure or timeout + * occurs (if timeout occurs errno == ETIME) If @a timeout == + * <&ACE_Time_Value::zero> then acquire has polling semantics (and + * does *not* call ). + */ + int acquire (void (*sleep_hook)(void *), + void *arg = 0, + ACE_Time_Value *timeout = 0); + + /** + * This behaves just like the previous method, except that + * it invokes the virtual function called that can be + * overridden by a subclass of ACE_Token. + */ + int acquire (ACE_Time_Value *timeout = 0); + + /** + * This should be overridden by a subclass to define the appropriate + * behavior before goes to sleep. By default, this is a + * no-op... + */ + virtual void sleep_hook (void); + + /** + * An optimized method that efficiently reacquires the token if no + * other threads are waiting. This is useful for situations where + * you don't want to degrade the quality of service if there are + * other threads waiting to get the token. If == + * -1 and there are other threads waiting to obtain the token we are + * queued according to the queueing strategy. If + * > -1 then it indicates how many entries to skip over before + * inserting our thread into the list of waiters (e.g., + * == 0 means "insert at front of the queue"). + * Renew has the rather odd semantics such that if there are other + * waiting threads it will give up the token even if the + * nesting_level_ > 1. I'm not sure if this is really the right + * thing to do (since it makes it possible for shared data to be + * changed unexpectedly) so use with caution... This method + * maintians the original token priority. As in , the + * @a timeout value is an absolute time. + */ + int renew (int requeue_position = 0, + ACE_Time_Value *timeout = 0); + + /// Become interface-compliant with other lock mechanisms (implements + /// a non-blocking ). + int tryacquire (void); + + /// Shuts down the ACE_Token instance. + int remove (void); + + /// Relinquish the token. If there are any waiters then the next one + /// in line gets it. + int release (void); + + /// Behaves like acquire() but at a lower priority. It should probably + /// be called acquire_yield() since the semantics aren't really + /// what's commonly expected for readers/writer locks. See the class + /// documentation above for more details. + int acquire_read (void); + + /// Behaves like acquire() but at a lower priority. It should probably + /// be called acquire_yield() since the semantics aren't really + /// what's commonly expected for readers/writer locks. See the class + /// documentation above for more details. + int acquire_read (void (*sleep_hook)(void *), + void *arg = 0, + ACE_Time_Value *timeout = 0); + + /// Calls acquire(). + int acquire_write (void); + + /// Calls acquire(). + int acquire_write (void (*sleep_hook)(void *), + void *arg = 0, + ACE_Time_Value *timeout = 0); + + /// Lower priority try_acquire(). + int tryacquire_read (void); + + /// Just calls . + int tryacquire_write (void); + + /// Assumes the caller has acquired the token and returns 0. + int tryacquire_write_upgrade (void); + + // = Accessor methods. + + /// Return the number of threads that are currently waiting to get + /// the token. + int waiters (void); + + /// Return the id of the current thread that owns the token. + ACE_thread_t current_owner (void); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + + /// The following structure implements a LIFO/FIFO queue of waiter threads + /// that are asleep waiting to obtain the token. + struct ACE_Token_Queue_Entry + { + /// Constructor + ACE_Token_Queue_Entry (ACE_Thread_Mutex &m, + ACE_thread_t t_id); + + /// Constructor using a pre-allocated attributes + ACE_Token_Queue_Entry (ACE_Thread_Mutex &m, + ACE_thread_t t_id, + ACE_Condition_Attributes &attributes); + + /// Entry blocks on the token. + int wait (ACE_Time_Value *timeout, ACE_Thread_Mutex &lock); + + /// Notify (unblock) the entry. + int signal (void); + + /// Pointer to next waiter. + ACE_Token_Queue_Entry *next_; + + /// ACE_Thread id of this waiter. + ACE_thread_t thread_id_; + +#if defined (ACE_TOKEN_USES_SEMAPHORE) + /// ACE_Semaphore object used to wake up waiter when it can run again. + ACE_Semaphore cv_; +#else + /// ACE_Condition object used to wake up waiter when it can run again. + ACE_Condition_Thread_Mutex cv_; +#endif /* ACE_TOKEN_USES_SEMAPHORE */ + + /// Ok to run. + int runable_; + }; + +private: + enum ACE_Token_Op_Type + { + READ_TOKEN = 1, + WRITE_TOKEN + }; + + struct ACE_Token_Queue + { + /// Constructor + ACE_Token_Queue (void); + + /// Remove a waiter from the queue. + void remove_entry (ACE_Token_Queue_Entry *); + + /// Insert a waiter into the queue. + void insert_entry (ACE_Token_Queue_Entry &entry, + int requeue_position = -1); + + /// Head of the list of waiting threads. + ACE_Token_Queue_Entry *head_; + + /// Tail of the list of waiting threads. + ACE_Token_Queue_Entry *tail_; + }; + + /// Implements the and methods above. + int shared_acquire (void (*sleep_hook_func)(void *), + void *arg, + ACE_Time_Value *timeout, + ACE_Token_Op_Type op_type); + + /// Wake next in line for ownership. + void wakeup_next_waiter (void); + + /// A queue of writer threads. + ACE_Token_Queue writers_; + + /// A queue of reader threads. + ACE_Token_Queue readers_; + + /// ACE_Thread_Mutex used to lock internal data structures. + ACE_Thread_Mutex lock_; + + /// Current owner of the token. + ACE_thread_t owner_; + + /// Some thread (i.e., ) is using the token. We need this + /// extra variable to deal with POSIX pthreads madness... + int in_use_; + + /// Number of waiters. + int waiters_; + + /// Current nesting level. + int nesting_level_; + + /// The attributes for the condition variables, optimizes lock time. + ACE_Condition_Attributes attributes_; + + /// Queueing strategy, LIFO/FIFO. + int queueing_strategy_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#else + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +class ACE_Export ACE_Token +{ +public: + int queueing_strategy (void) { ACE_NOTSUP_RETURN (-1); } + void queueing_strategy (int /*queueing_strategy*/) { } + int acquire (ACE_Time_Value * = 0) { ACE_NOTSUP_RETURN (-1); } + int tryacquire (void) { ACE_NOTSUP_RETURN (-1); } + int remove (void) { ACE_NOTSUP_RETURN (-1); } + int release (void) { ACE_NOTSUP_RETURN (-1); } +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_THREADS */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +class ACE_Export ACE_Noop_Token : public ACE_Null_Mutex +{ +public: + /// Queueing strategy + enum QUEUEING_STRATEGY + { + FIFO = -1, + LIFO = 0 + }; + + /// Get queueing strategy. + int queueing_strategy (void); + + /// Set queueing strategy. + void queueing_strategy (int queueing_strategy); + + int renew (int = 0, ACE_Time_Value * =0); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Token.inl" +#endif /* __ACE_INLINE__ */ + + +#include /**/ "ace/post.h" +#endif /* ACE_TOKEN_H */ diff --git a/dep/acelite/ace/Token.inl b/dep/acelite/ace/Token.inl new file mode 100644 index 00000000000..f09a0e6f3de --- /dev/null +++ b/dep/acelite/ace/Token.inl @@ -0,0 +1,176 @@ +// -*- C++ -*- +// +// $Id: Token.inl 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/config-macros.h" + +#if defined (ACE_HAS_THREADS) + +#include "ace/Guard_T.h" +#include "ace/Time_Value.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE int +ACE_Token::queueing_strategy (void) +{ + return this->queueing_strategy_; +} + +ACE_INLINE void +ACE_Token::queueing_strategy (int queueing_strategy) +{ + this->queueing_strategy_ = queueing_strategy == -1 ? -1 : 0; +} + +ACE_INLINE int +ACE_Token::remove (void) +{ + ACE_TRACE ("ACE_Token::remove"); + // Don't have an implementation for this yet... + ACE_NOTSUP_RETURN (-1); +} + +ACE_INLINE int +ACE_Token::tryacquire (void) +{ + ACE_TRACE ("ACE_Token::tryacquire"); + return this->shared_acquire + (0, 0, (ACE_Time_Value *) &ACE_Time_Value::zero, ACE_Token::WRITE_TOKEN); +} + +ACE_INLINE int +ACE_Token::waiters (void) +{ + ACE_TRACE ("ACE_Token::waiters"); + ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1); + + int const ret = this->waiters_; + return ret; +} + +ACE_INLINE ACE_thread_t +ACE_Token::current_owner (void) +{ + ACE_TRACE ("ACE_Token::current_owner"); + ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, this->owner_); + + return this->owner_; +} + +ACE_INLINE int +ACE_Token::acquire_read (void) +{ + ACE_TRACE ("ACE_Token::acquire_read"); + return this->shared_acquire + (0, 0, 0, ACE_Token::READ_TOKEN); +} + +ACE_INLINE int +ACE_Token::acquire_write (void) +{ + ACE_TRACE ("ACE_Token::acquire_write"); + return this->shared_acquire + (0, 0, 0, ACE_Token::WRITE_TOKEN); +} + +ACE_INLINE int +ACE_Token::tryacquire_read (void) +{ + ACE_TRACE ("ACE_Token::tryacquire_read"); + return this->shared_acquire + (0, 0, (ACE_Time_Value *) &ACE_Time_Value::zero, ACE_Token::READ_TOKEN); +} + +ACE_INLINE int +ACE_Token::acquire_read (void (*sleep_hook_func)(void *), + void *arg, + ACE_Time_Value *timeout) +{ + ACE_TRACE ("ACE_Token::acquire_read"); + return this->shared_acquire (sleep_hook_func, arg, timeout, ACE_Token::READ_TOKEN); +} + +ACE_INLINE int +ACE_Token::tryacquire_write (void) +{ + ACE_TRACE ("ACE_Token::tryacquire_write"); + return this->shared_acquire + (0, 0, (ACE_Time_Value *) &ACE_Time_Value::zero, ACE_Token::WRITE_TOKEN); +} + +ACE_INLINE int +ACE_Token::tryacquire_write_upgrade (void) +{ + ACE_TRACE ("ACE_Token::tryacquire_write_upgrade"); + return 0; +} + +ACE_INLINE int +ACE_Token::acquire_write (void (*sleep_hook_func)(void *), + void *arg, + ACE_Time_Value *timeout) +{ + ACE_TRACE ("ACE_Token::acquire_write"); + return this->shared_acquire (sleep_hook_func, arg, timeout, ACE_Token::WRITE_TOKEN); +} + +ACE_INLINE int +ACE_Token::ACE_Token_Queue_Entry::wait (ACE_Time_Value *timeout, ACE_Thread_Mutex &lock) +{ +#if defined (ACE_TOKEN_USES_SEMAPHORE) + lock.release (); + int const retv = (timeout == 0 ? + this->cv_.acquire () : + this->cv_.acquire (*timeout)); + lock.acquire (); + return retv; +#else + ACE_UNUSED_ARG (lock); + return this->cv_.wait (timeout); +#endif /* ACE_TOKEN_USES_SEMAPHORE */ +} + +ACE_INLINE int +ACE_Token::ACE_Token_Queue_Entry::signal (void) +{ + return +#if defined (ACE_TOKEN_USES_SEMAPHORE) + this->cv_.release (); +#else + this->cv_.signal (); +#endif /* ACE_TOKEN_USES_SEMAPHORE */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_THREADS */ + +/*****************************************************************************/ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE int +ACE_Noop_Token::queueing_strategy (void) +{ + return -1; +} + +ACE_INLINE void +ACE_Noop_Token::queueing_strategy (int /* queueing_strategy */) +{ +} + +ACE_INLINE int +ACE_Noop_Token::renew (int, ACE_Time_Value *) +{ + return 0; +} + +ACE_INLINE void +ACE_Noop_Token::dump (void) const +{ +} + +ACE_END_VERSIONED_NAMESPACE_DECL + diff --git a/dep/acelite/ace/Token_Collection.cpp b/dep/acelite/ace/Token_Collection.cpp new file mode 100644 index 00000000000..23a5813c958 --- /dev/null +++ b/dep/acelite/ace/Token_Collection.cpp @@ -0,0 +1,294 @@ +#include "ace/Token_Collection.h" + +#if defined (ACE_HAS_TOKENS_LIBRARY) + +#if !defined (__ACE_INLINE__) +#include "ace/Token_Collection.inl" +#endif /* __ACE_INLINE__ */ + + +ACE_RCSID (ace, + Token_Collection, + "$Id: Token_Collection.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_Token_Collection::ACE_Token_Collection (bool debug, + const ACE_TCHAR *name) +: debug_ (debug) +{ + ACE_TRACE ("ACE_Token_Collection::ACE_Token_Collection"); + + if (name == 0) + name = ACE_TEXT ("no name"); + + ACE_OS::strsncpy (this->name_, + const_cast (name), + ACE_MAXTOKENNAMELEN); +} + +int +ACE_Token_Collection::insert (ACE_Token_Proxy &new_token) +{ + ACE_TRACE ("ACE_Token_Collection::insert"); + + TOKEN_NAME name (new_token.name ()); + + // Check if the new_proxy is already in the list. + if (collection_.find (name) == 1) + // One already exists, so fail. + return -1; + + // Clone the new token. + ACE_Token_Proxy *temp = new_token.clone (); + + if (collection_.bind (name, temp) == -1) + ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("bind failed\n")), -1); + return 0; +} + +int +ACE_Token_Collection::extract (const ACE_TCHAR *token_name, ACE_Token_Proxy *&proxy) +{ + ACE_TRACE ("ACE_Token_Collection::extract"); + TOKEN_NAME name (token_name); + return collection_.unbind (token_name, proxy); +} + +ACE_Token_Proxy * +ACE_Token_Collection::is_member (const ACE_TCHAR *token_name) +{ + ACE_TRACE ("ACE_Token_Collection::is_member"); + TOKEN_NAME name (token_name); + ACE_Token_Proxy *temp; + // Get the token from the collection. + return collection_.find (name, temp) == -1 ? 0 : temp; +} + +int +ACE_Token_Collection::is_member (const ACE_Token_Proxy &token) +{ + ACE_TRACE ("ACE_Token_Collection::is_member"); + TOKEN_NAME token_name (token.name ()); + return collection_.find (token_name) == 0; +} + +int +ACE_Token_Collection::acquire (int notify, + void (*sleep_hook)(void *), + ACE_Synch_Options &options) +{ + ACE_TRACE ("ACE_Token_Collection::acquire"); + + COLLECTION::ITERATOR iterator (collection_); + + for (COLLECTION::ENTRY *temp = 0; + iterator.next (temp) != 0; + iterator.advance ()) + { + if (debug_) + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("collection acquiring %s\n"), + temp->int_id_->name ())); + if (temp->int_id_->acquire (notify, + sleep_hook, + options) == -1) + { + // Save/restore errno. + ACE_Errno_Guard error (errno); + this->release (); + ACE_RETURN (-1); + } + } + + return 0; +} + +int +ACE_Token_Collection::acquire (const ACE_TCHAR *token_name, + int notify, + void (*sleep_hook)(void *), + ACE_Synch_Options &options) +{ + ACE_TRACE ("ACE_Token_Collection::acquire"); + TOKEN_NAME name (token_name); + ACE_Token_Proxy *temp; + // Get the token from the collection. + int result = collection_.find (name, temp); + // did we find it? + if (result == -1) + return result; + // perform the operation + return temp->acquire (notify, sleep_hook, options); +} + + +int +ACE_Token_Collection::tryacquire (const ACE_TCHAR *token_name, + void (*sleep_hook)(void *)) +{ + ACE_TRACE ("ACE_Token_Collection::tryacquire"); + TOKEN_NAME name (token_name); + ACE_Token_Proxy *temp; + // Get the token from the collection. + int result = collection_.find (name, temp); + // did we find it? + if (result == -1) + return result; + + // perform the operation + return temp->tryacquire (sleep_hook); +} + +int +ACE_Token_Collection::tryacquire (void (*sleep_hook)(void *)) +{ + ACE_TRACE ("ACE_Token_Collection::tryacquire"); + + COLLECTION::ITERATOR iterator (collection_); + + for (COLLECTION::ENTRY *temp = 0; + iterator.next (temp) != 0; + iterator.advance ()) + { + if (debug_) + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("collection acquiring %s\n"), + temp->int_id_->name ())); + // We will fail if _any_ token is not free. + if (temp->int_id_->tryacquire (sleep_hook) == -1) + return -1; + } + + return 0; +} + +int +ACE_Token_Collection::renew (int requeue_position, + ACE_Synch_Options &options) +{ + ACE_TRACE ("ACE_Token_Collection::renew"); + + COLLECTION::ITERATOR iterator (collection_); + + for (COLLECTION::ENTRY *temp = 0; + iterator.next (temp) != 0; + iterator.advance ()) + { + if (debug_) + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("collection renewing %s\n"), + temp->int_id_->name ())); + if (temp->int_id_->renew (requeue_position, options) == -1) + return -1; + } + + return 0; +} + +int +ACE_Token_Collection::renew (const ACE_TCHAR *token_name, + int requeue_position, + ACE_Synch_Options &options) +{ + ACE_TRACE ("ACE_Token_Collection::renew"); + TOKEN_NAME name (token_name); + ACE_Token_Proxy *temp; + + // Get the token from the collection. + int result = collection_.find (name, temp); + + // Did we find it? + if (result == -1) + ACE_ERROR_RETURN ((LM_DEBUG, ACE_TEXT ("%p %s\n"), + ACE_TEXT ("not in collection "), + token_name), -1); + // perform the operation + return temp->renew (requeue_position, options); +} + +int +ACE_Token_Collection::release (ACE_Synch_Options &) + +{ + ACE_TRACE ("ACE_Token_Collection::release"); + COLLECTION::ITERATOR iterator (collection_); + + for (COLLECTION::ENTRY *temp = 0; + iterator.next (temp) != 0; + iterator.advance ()) + { + if (debug_) + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("collection releasing %s\n"), + temp->int_id_->name ())); + temp->int_id_->release (); + } + + return 0; +} + +int +ACE_Token_Collection::release (const ACE_TCHAR *token_name, + ACE_Synch_Options &options) +{ + ACE_TRACE ("ACE_Token_Collection::release"); + TOKEN_NAME name (token_name); + ACE_Token_Proxy *temp; + // get the token from the collection + int result = collection_.find (name, temp); + // did we find it? + if (result != 0) + return result; + // perform the operation + return temp->release (options); +} + +ACE_Token_Collection::~ACE_Token_Collection (void) +{ + ACE_TRACE ("ACE_Token_Collection::~ACE_Token_Collection"); + COLLECTION::ITERATOR iterator (collection_); + + for (COLLECTION::ENTRY *temp = 0; + iterator.next (temp) != 0; + iterator.advance ()) + { + delete temp->int_id_; + // The ext_id_'s delete themselves when the array of + // COLLECTION::ENTRYs goes away. + } +} + + +// This method doesn't mean anything for a collection. +ACE_Token_Proxy * +ACE_Token_Collection::clone (void) const +{ + ACE_TRACE ("ACE_Token_Collection::clone"); + return (ACE_Token_Proxy *) 0; +} + +// This method doesn't mean anything for a collection. +ACE_Tokens * +ACE_Token_Collection::create_token (const ACE_TCHAR *) +{ + ACE_TRACE ("ACE_Token_Collection::create_token"); + return (ACE_Tokens *) 0; +} + +void +ACE_Token_Collection::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Token_Collection::dump"); + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("ACE_Token_Collection::dump:\n") + ACE_TEXT (" debug_ = %d\n"), debug_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("collection_\n"))); + collection_.dump (); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("base:\n"))); + ACE_Token_Proxy::dump (); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_TOKENS_LIBRARY */ diff --git a/dep/acelite/ace/Token_Collection.h b/dep/acelite/ace/Token_Collection.h new file mode 100644 index 00000000000..16a9bb412b0 --- /dev/null +++ b/dep/acelite/ace/Token_Collection.h @@ -0,0 +1,243 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Token_Collection.h + * + * $Id: Token_Collection.h 80826 2008-03-04 14:51:23Z wotte $ + * + * The ACE_Token class offers methods for acquiring, renewing, + * and releasing a synchronization token on a per-token basis. The + * ACE_Token_Collection offers an interface for performing + * operations on groups of tokens as a whole, or on a single token + * within the collection. + * + * The atomic group operations are not yet implemented. + * + * + * @author Douglas C. Schmidt (schmidt@cs.wustl.edu) + * @author Tim Harrison (harrison@cs.wustl.edu) + */ +//============================================================================= + +#ifndef ACE_TOKEN_COLLECTION_H +#define ACE_TOKEN_COLLECTION_H +#include /**/ "ace/pre.h" + +#include "ace/Map_Manager.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_TOKENS_LIBRARY) + +#include "ace/Local_Tokens.h" +#include "ace/Null_Mutex.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Token_Collection + * + * @brief Allows atomic token group operations AND + * provides a ACE_Token manager interface. + * + * There are two types of operations offered by + * ACE_Token_Collection. The first is atomic operations on + * collections of Token_Proxies. In this respect, the + * ACE_Token_Collection can be thought of as a single token + * consisting of multiple Token_Proxies. The second role of the + * ACE_Token_Collection is as a ACE_Token manager. + * ACE_Token_Collection allows individual operations on single + * members of a collection of Token_Proxies. This provides a + * single access point for operations on multiple tokens. + * + * @bug Although ACE_Token_Collection inherits from ACE_Token_Proxy, it + * can not be including in a collection. This is because + * returns zero for now. + * + */ +class ACE_Export ACE_Token_Collection : public ACE_Token_Proxy +{ +public: + /** + * @a debug print out verbose debugging messages. @a name will give a + * name to the collection. Collections don't really need names, but + * are sometimes useful for debugging. + */ + ACE_Token_Collection (bool debug = false, + const ACE_TCHAR *name = 0); + +// Collection Management operations + + /** + * Insert a Token into the collection. All ACE_Token type + * operations performed on the collection will also be performed on + * the new_proxy until it is removed. Note that no operations + * performed prior to the insertion will be performed. Returns: 0 + * on success, -1 on failure with @c errno == problem. If a token + * proxy already exists in the collection with the same name, the + * insertion will fail. Also, is copied. Note that during + * the copy, client_id's are *not* inherited. The client ID of the + * thread using the collection will be used. Client ID's can be + * changed explicity on each proxy using is_member. + */ + int insert (ACE_Token_Proxy &token); + + /** + * Removes the ACE_Token matching the given token_name from the + * collection. On success, extract returns 0. On failure + * (token_name was not in the collection,) extract returns -1. On + * success, the state of the token found is copied into proxy. + * The returned ACE_Token_Proxy* must be deleted by the user. + */ + int extract (const ACE_TCHAR *token_name, ACE_Token_Proxy *&proxy); + + /// Returns the proxy if true. 0 otherwise. + ACE_Token_Proxy *is_member (const ACE_TCHAR *token_name); + + /** + * Is the specified token in the collection? + * 1, yes. + * 0, no. + */ + int is_member (const ACE_Token_Proxy &token); + +// = Collective operation semantics. + +// For acquire, renew, and release, there are two interfaces. Once +// interface allows an operation on a single token in the +// collection. The collective interfaces perform atomic operations +// on the entire collection. For instance, a collective acquire +// will perform an acquire for each and every token in the +// collection or the operation will fail. Currently, these +// operations are performed with no ordering heuristics. That is, +// the Collection steps through the tokens in the order they were +// inserted. For each one it performs the operation (acquire, +// renew, or release). + + /** + * Acquire "atomically" all resources in the collection. This is + * only successfull if all tokens in the collection could be + * acquired. options contains the blocking semantics, timeout + * value, etc. Returns: 0 on success, -1 on failure with @c errno == + * problem. If and error or deadlock occurs for one of the tokens, + * all the tokens will be released and the method will return -1. + * Note that returning on detection of deadlock prevents livelock + * between competing collections. If a collection returns after + * detecting deadlock, it is the application's responsibility to not + * to blindly loop on the collection::acquire operation. In other + * words, once the collection reports deadlock, it is out of our + * hands. + */ + virtual int acquire (int notify = 0, + void (*sleep_hook)(void *) = 0, + ACE_Synch_Options &options = + ACE_Synch_Options::defaults); + + /// Acquire the token corresponding to @a token_name. The other + /// parameters are passed to ::acquire. + virtual int acquire (const ACE_TCHAR *token_name, + int notify = 0, + void (*sleep_hook)(void *) = 0, + ACE_Synch_Options &options = + ACE_Synch_Options::defaults); + + /// Try to acquire all tokens in collection. + virtual int tryacquire (void (*sleep_hook)(void *) = 0); + + /// Try to acquire @a token_name. + virtual int tryacquire (const ACE_TCHAR *token_name, + void (*sleep_hook)(void *) = 0); + + /** + * Renews "atomically" all resources in the collection. This is + * only successfull if all tokens in the collection could be + * renewed. options contains the blocking semantics, timeout + * value, etc. Returns: 0 on success, -1 on failure with @c errno == + * problem. + */ + virtual int renew (int requeue_position = 0, + ACE_Synch_Options &options = + ACE_Synch_Options::defaults); + + + /// Renew the token corresponding to @a token_name. The other + /// parameters are passed to ::renew. + virtual int renew (const ACE_TCHAR *token_name, + int requeue_position = 0, + ACE_Synch_Options &options = + ACE_Synch_Options::defaults); + + /** + * Releases "atomically" all resources in the collection. This is + * only successfull if all tokens in the collection could be + * released. options contains the blocking semantics, timeout + * value, etc. Returns: 0 on success, -1 on failure with @c errno == + * problem. + */ + virtual int release (ACE_Synch_Options &options = + ACE_Synch_Options::defaults); + + + /// Release the token corresponding to . The other + /// parameters are passed to ::release. + virtual int release (const ACE_TCHAR *token_name, + ACE_Synch_Options &options = + ACE_Synch_Options::defaults); + + ~ACE_Token_Collection (void); + + /// Dump the state of the class. + void dump (void) const; + + /// Return the name of the collection. Not very functionally + /// important, but sometimes a useful debugging tool. + virtual const ACE_TCHAR *name (void) const; + +protected: + + typedef ACE_Token_Name TOKEN_NAME; + + /// COLLECTION maintains a mapping from token names to ACE_Tokens* + typedef ACE_Map_Manager + COLLECTION; + + /// Allows iterations through collection_ + /** + * @deprecated Deprecated typedef. Use COLLECTION::ITERATOR trait instead. + */ + typedef COLLECTION::ITERATOR COLLECTION_ITERATOR; + + /// Allows iterations through collection_ + /** + * @deprecated Deprecated typedef. Use COLLECTION::ENTRY trait instead. + */ + typedef COLLECTION::ENTRY COLLECTION_ENTRY; + + /// COLLECTION maintains a mapping from token names to ACE_Tokens*. + COLLECTION collection_; + + /// Whether to print out debug messages or not. + bool debug_; + + /// Name of the collection. + ACE_TCHAR name_[ACE_MAXTOKENNAMELEN]; + + // = I'm not sure what these mean, but they have to be defined since they're + // pure virtual in ACE_Token_Proxy. + virtual ACE_Token_Proxy *clone (void) const; + virtual ACE_Tokens *create_token (const ACE_TCHAR *name); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Token_Collection.inl" +#endif /* __ACE_INLINE__ */ + +#endif /* ACE_HAS_TOKENS_LIBRARY */ + +#include /**/ "ace/post.h" +#endif /* ACE_TOKEN_COLLECTION_H */ diff --git a/dep/acelite/ace/Token_Collection.inl b/dep/acelite/ace/Token_Collection.inl new file mode 100644 index 00000000000..73f1e95d76e --- /dev/null +++ b/dep/acelite/ace/Token_Collection.inl @@ -0,0 +1,17 @@ +// -*- C++ -*- +// +// $Id: Token_Collection.inl 80826 2008-03-04 14:51:23Z wotte $ + +#if defined (ACE_HAS_TOKENS_LIBRARY) + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE const ACE_TCHAR * +ACE_Token_Collection::name (void) const +{ + return name_; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_TOKENS_LIBRARY */ diff --git a/dep/acelite/ace/Token_Invariants.cpp b/dep/acelite/ace/Token_Invariants.cpp new file mode 100644 index 00000000000..52b1f85eebe --- /dev/null +++ b/dep/acelite/ace/Token_Invariants.cpp @@ -0,0 +1,356 @@ +#include "ace/Token_Invariants.h" + +#if defined (ACE_HAS_TOKENS_LIBRARY) + +#include "ace/Object_Manager.h" +#include "ace/os_include/os_typeinfo.h" + +ACE_RCSID (ace, + Token_Invariants, + "$Id: Token_Invariants.cpp 84179 2009-01-16 07:26:45Z johnnyw $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_Token_Invariant_Manager *ACE_Token_Invariant_Manager::instance_ = 0; + +ACE_Token_Invariant_Manager * +ACE_Token_Invariant_Manager::instance (void) +{ + ACE_TRACE ("ACE_Token_Invariant_Manager::instance"); + + // Perform the Double-Check pattern... + if (instance_ == 0) + { + ACE_MT (ACE_TOKEN_CONST::MUTEX *lock = + ACE_Managed_Object::get_preallocated_object + (ACE_Object_Manager::ACE_TOKEN_INVARIANTS_CREATION_LOCK); + ACE_GUARD_RETURN (ACE_TOKEN_CONST::MUTEX, ace_mon, *lock, 0)); + + if (instance_ == 0) + { + ACE_NEW_RETURN (instance_, + ACE_Token_Invariant_Manager, + 0); + // Register for destruction with ACE_Object_Manager. + ACE_Object_Manager::at_exit (instance_, 0, typeid (instance_).name ()); + } + } + + return instance_; +} + +ACE_Token_Invariant_Manager::ACE_Token_Invariant_Manager (void) +{ + ACE_TRACE ("ACE_Token_Invariant_Manager::ACE_Token_Invariant_Manager"); +} + +int +ACE_Token_Invariant_Manager::mutex_acquired (const ACE_TCHAR *token_name) +{ + ACE_TRACE ("ACE_Token_Invariant_Manager::mutex_acquired"); + + ACE_GUARD_RETURN (ACE_TOKEN_CONST::MUTEX, ace_mon, this->lock_, -1); + + ACE_Mutex_Invariants *inv = 0; + if (this->get_mutex (token_name, inv) == -1) + return -1; + + return inv->acquired (); +} + +int +ACE_Token_Invariant_Manager::acquired (const ACE_Token_Proxy *proxy) +{ + ACE_TRACE ("ACE_Token_Invariant_Manager::acquired"); + + // Reach into the proxy to find the token type. + if (proxy->token_->type () == ACE_Tokens::MUTEX) + return this->mutex_acquired (proxy->name ()); + else // ACE_Tokens::RWLOCK. + { + if (proxy->type () == ACE_RW_Token::READER) + return this->reader_acquired (proxy->name ()); + else // ACE_RW_Token::WRITER. + return this->writer_acquired (proxy->name ()); + } +} + +void +ACE_Token_Invariant_Manager::releasing (const ACE_Token_Proxy *proxy) +{ + ACE_TRACE ("ACE_Token_Invariant_Manager::releasing"); + + // Reach into the proxy to find the token type. + if (proxy->token_->type () == ACE_Tokens::MUTEX) + this->mutex_releasing (proxy->name ()); + else // ACE_Tokens::RWLOCK. + this->rwlock_releasing (proxy->name ()); +} + +void +ACE_Token_Invariant_Manager::mutex_releasing (const ACE_TCHAR *token_name) +{ + ACE_TRACE ("ACE_Token_Invariant_Manager::mutex_releasing"); + ACE_GUARD (ACE_TOKEN_CONST::MUTEX, ace_mon, this->lock_); + + ACE_Mutex_Invariants *inv = 0; + if (this->get_mutex (token_name, inv) == 0) + inv->releasing (); +} + +int +ACE_Token_Invariant_Manager::reader_acquired (const ACE_TCHAR *token_name) +{ + ACE_TRACE ("ACE_Token_Invariant_Manager::reader_acquired"); + ACE_GUARD_RETURN (ACE_TOKEN_CONST::MUTEX, ace_mon, this->lock_, -1); + + ACE_RWLock_Invariants *inv = 0; + if (this->get_rwlock (token_name, inv) == -1) + return -1; + + return inv->reader_acquired (); +} + +int +ACE_Token_Invariant_Manager::writer_acquired (const ACE_TCHAR *token_name) +{ + ACE_TRACE ("ACE_Token_Invariant_Manager::writer_acquired"); + + ACE_GUARD_RETURN (ACE_TOKEN_CONST::MUTEX, ace_mon, this->lock_, -1); + + ACE_RWLock_Invariants *inv = 0; + if (this->get_rwlock (token_name, inv) == -1) + return -1; + + return inv->writer_acquired (); +} + +void +ACE_Token_Invariant_Manager::rwlock_releasing (const ACE_TCHAR *token_name) +{ + ACE_TRACE ("ACE_Token_Invariant_Manager::rwlock_releasing"); + + ACE_GUARD (ACE_TOKEN_CONST::MUTEX, ace_mon, this->lock_); + + ACE_RWLock_Invariants *inv = 0; + if (this->get_rwlock (token_name, inv) == 0) + inv->releasing (); +} + +void +ACE_Token_Invariant_Manager::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Token_Invariant_Manager::dump"); + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("mutex_collection_:\n"))); + mutex_collection_.dump (); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("rwlock_collection_:\n"))); + rwlock_collection_.dump (); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + + +int +ACE_Token_Invariant_Manager::get_mutex (const ACE_TCHAR *token_name, + ACE_Mutex_Invariants *&inv) +{ + ACE_TRACE ("ACE_Token_Invariant_Manager::get_mutex"); + TOKEN_NAME name (token_name); + if (mutex_collection_.find (name, inv) == -1) + // We did not find one in the collection. + { + ACE_Mutex_Invariants *new_invariant; + + ACE_NEW_RETURN (new_invariant, + ACE_Mutex_Invariants, + -1); + if (mutex_collection_.bind (name, new_invariant) == -1) + { + delete new_invariant; + return -1; + } + + if (mutex_collection_.find (name, inv) == -1) + // We did not find one in the collection. + return -1; + } + + return 0; +} + +int +ACE_Token_Invariant_Manager::get_rwlock (const ACE_TCHAR *token_name, + ACE_RWLock_Invariants *&inv) +{ + ACE_TRACE ("ACE_Token_Invariant_Manager::get_rwlock"); + TOKEN_NAME name (token_name); + if (rwlock_collection_.find (name, inv) == -1) + // We did not find one in the collection. + { + ACE_RWLock_Invariants *new_invariant; + + ACE_NEW_RETURN (new_invariant, + ACE_RWLock_Invariants, + -1); + if (rwlock_collection_.bind (name, new_invariant) == -1) + return -1; + + if (rwlock_collection_.find (name, inv) == -1) + // We did not find one in the collection. + return -1; + } + + return 0; +} + + +ACE_Token_Invariant_Manager::~ACE_Token_Invariant_Manager (void) +{ + ACE_TRACE ("ACE_Token_Invariant_Manager::~ACE_Token_Invariant_Manager"); + + MUTEX_COLLECTION::ITERATOR iterator (mutex_collection_); + + for (MUTEX_COLLECTION::ENTRY *temp = 0; + iterator.next (temp) != 0; + iterator.advance ()) + delete temp->int_id_; + + RWLOCK_COLLECTION::ITERATOR iterator2 (rwlock_collection_); + + for (RWLOCK_COLLECTION::ENTRY *temp2 = 0; + iterator2.next (temp2) != 0; + iterator2.advance ()) + delete temp2->int_id_; +} + +// ************************************************** +// ************************************************** +// ************************************************** + +ACE_Mutex_Invariants::ACE_Mutex_Invariants (void) +: owners_ (0) +{ +} + +int +ACE_Mutex_Invariants::acquired (void) +{ + if (++owners_ > 1) + { + owners_ = 42; + return 0; + } + else + return 1; +} + +void +ACE_Mutex_Invariants::releasing (void) +{ + if (owners_ == 1) + --owners_; +} + +ACE_Mutex_Invariants::ACE_Mutex_Invariants (const ACE_Mutex_Invariants &rhs) +: owners_ (rhs.owners_) +{ +} + +void +ACE_Mutex_Invariants::operator= (const ACE_Mutex_Invariants &rhs) +{ + owners_ = rhs.owners_; +} + +void +ACE_Mutex_Invariants::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Mutex_Invariants::dump"); + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("owners_ = %d\n"), owners_)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +// ************************************************** +// ************************************************** +// ************************************************** + +ACE_RWLock_Invariants::ACE_RWLock_Invariants (void) +: writers_ (0), + readers_ (0) +{ +} + +int +ACE_RWLock_Invariants::writer_acquired (void) +{ + if (readers_ > 0) + { + writers_ = readers_ = 42; + return 0; + } + else if (++writers_ > 1) + { + writers_ = readers_ = 42; + return 0; + } + else + return 1; +} + +int +ACE_RWLock_Invariants::reader_acquired (void) +{ + if (writers_ > 0) + { + writers_ = readers_ = 42; + return 0; + } + else + { + ++readers_; + return 1; + } +} + +void +ACE_RWLock_Invariants::releasing (void) +{ + if (writers_ == 1) + writers_ = 0; + else if (readers_ > 0) + --readers_; +} + +ACE_RWLock_Invariants::ACE_RWLock_Invariants (const ACE_RWLock_Invariants &rhs) +: writers_ (rhs.writers_), + readers_ (rhs.readers_) +{ +} + +void +ACE_RWLock_Invariants::operator= (const ACE_RWLock_Invariants &rhs) +{ + writers_ = rhs.writers_; + readers_ = rhs.readers_; +} + +void +ACE_RWLock_Invariants::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_RWLock_Invariants::dump"); + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("writers_ = %d readers_ = %d\n"), + writers_, readers_)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_TOKENS_LIBRARY */ diff --git a/dep/acelite/ace/Token_Invariants.h b/dep/acelite/ace/Token_Invariants.h new file mode 100644 index 00000000000..5cec394763d --- /dev/null +++ b/dep/acelite/ace/Token_Invariants.h @@ -0,0 +1,245 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Token_Invariants.h + * + * $Id: Token_Invariants.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Tim Harrison (harrison@cs.wustl.edu) + * + * Allows applications to test that invariants are always + * satisfied. Can test mutexes and readers/writer locks. Does + * not test recursive acquisition. + * + * + */ +//============================================================================= + +#ifndef ACE_TOKEN_INVARIANTS_H +#define ACE_TOKEN_INVARIANTS_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_TOKENS_LIBRARY) + +#include "ace/Map_Manager.h" +#include "ace/Local_Tokens.h" +#include "ace/Null_Mutex.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Mutex_Invariants + * + * @brief Mutex Invariants + * = INVARIANTS + * 1. Only one owner at a time. + */ +class ACE_Export ACE_Mutex_Invariants +{ +public: + /// Default construction. + ACE_Mutex_Invariants (void); + + /// Returns 1 on success, 0 when an invariant has been violated and + /// -1 on error. + int acquired (void); + + /// Updates internal database. + void releasing (void); + + // = Map_Manager operations. + + /// Copy construction. + ACE_Mutex_Invariants (const ACE_Mutex_Invariants &rhs); + + /// Copy. + void operator= (const ACE_Mutex_Invariants &rhs); + + /// Dump the state of the class. + void dump (void) const; + +private: + /// Number of owners. This had better be 0 >= owners_ <= 1; + int owners_; +}; + +/** + * @class ACE_RWLock_Invariants + * + * @brief RWLock Invariants + * + * Preserve the following invariants: + * -# Only one writer at a time. + * -# If there is an owning writer, there are no owning readers. + */ +class ACE_Export ACE_RWLock_Invariants +{ +public: + /// Default construction. + ACE_RWLock_Invariants (void); + + /// Returns 1 on success, 0 when an invariant has been violated and + /// -1 on error. + int writer_acquired (void); + + /// Returns 1 on success, 0 when an invariant has been violated and + /// -1 on error. + int reader_acquired (void); + + /// Updates internal database. + void releasing (void); + + // = Map_Manager operations. + + /// Copy construction. + ACE_RWLock_Invariants (const ACE_RWLock_Invariants &rhs); + + /// Copy. + void operator= (const ACE_RWLock_Invariants &rhs); + + /// Dump the state of the class. + void dump (void) const; + +private: + /// Number of owning writers. + int writers_; + + /// Number of owning readers. + int readers_; +}; + +/** + * @class ACE_Token_Invariant_Manager + * + * @brief Token Invariants + * + * The Token Invariant Manager allows applications to test that + * invariants are always satisfied. Currently, Token_Invariants + * can test mutexes and readers/writer locks. Does not test + * recursive acquisition. + * Note that this class does not ever clean its database. Until + * destroyed, it's size will forever increase. + */ +class ACE_Export ACE_Token_Invariant_Manager : public ACE_Cleanup +{ +public: + + /// Singleton access point. + static ACE_Token_Invariant_Manager *instance (void); + + // = Polymorphic methods. Just pass in the proxy and the method + // figures out the type of the token. + + /// Returns 1 on success, 0 when an invariant has been violated and + /// -1 on error. + int acquired (const ACE_Token_Proxy *proxy); + + /// Updates internal database. + void releasing (const ACE_Token_Proxy *proxy); + + // = Explicit methods. These to not require actual proxies in order + // to test a scenario. + + /// Returns 1 on success, 0 when an invariant has been violated and + /// -1 on error. + int mutex_acquired (const ACE_TCHAR *token_name); + + /// Updates internal database. + void mutex_releasing (const ACE_TCHAR *token_name); + + /// Returns 1 on success, 0 when an invariant has been violated and + /// -1 on error. + int reader_acquired (const ACE_TCHAR *token_name); + + /// Returns 1 on success, 0 when an invariant has been violated and + /// -1 on error. + int writer_acquired (const ACE_TCHAR *token_name); + + /// Updates internal database. + void rwlock_releasing (const ACE_TCHAR *token_name); + + /// Dump the state of the class. + void dump (void) const; + + // = The following two method should be in the protected part of the + // class. Bugs with certain compilers preclude this. + /// Prevent non-singleton construction. + ACE_Token_Invariant_Manager (void); + + /// Destruction. + virtual ~ACE_Token_Invariant_Manager (void); + +protected: + /// Return or create. + int get_mutex (const ACE_TCHAR *token_name, + ACE_Mutex_Invariants *&inv); + + /// Return or create. + int get_rwlock (const ACE_TCHAR *token_name, + ACE_RWLock_Invariants *&inv); + + /// ACE_Mutex_Token used to lock internal data structures. + ACE_TOKEN_CONST::MUTEX lock_; + + /// This may be changed to a template type. + typedef ACE_Token_Name TOKEN_NAME; + + /// COLLECTION maintains a mapping from token names to mutexes. + typedef ACE_Map_Manager + MUTEX_COLLECTION; + + /// Allows iterations through collection. + /** + * @deprecated Deprecated typedef. Use MUTEX_COLLECTION::ITERATOR trait + * instead. + */ + typedef MUTEX_COLLECTION::ITERATOR MUTEX_COLLECTION_ITERATOR; + + /// Allows iterations through collection. + /** + * @deprecated Deprecated typedef. Use MUTEX_COLLECTION::ENTRY trait + * instead. + */ + typedef MUTEX_COLLECTION::ENTRY MUTEX_COLLECTION_ENTRY; + + /// MUTEX_COLLECTION maintains a mapping from token names to mutexes. + MUTEX_COLLECTION mutex_collection_; + + /// COLLECTION maintains a mapping from token names to mutexes. + typedef ACE_Map_Manager + RWLOCK_COLLECTION; + + /// Allows iterations through collection. + /** + * @deprecated Deprecated typedef. Use RWLOCK_COLLECTION::ITERATOR trait + * instead. + */ + typedef RWLOCK_COLLECTION::ITERATOR RWLOCK_COLLECTION_ITERATOR; + + /// Allows iterations through collection. + /** + * @deprecated Deprecated typedef. Use RWLOCK_COLLECTION::ENTRY trait + * instead. + */ + typedef RWLOCK_COLLECTION::ENTRY RWLOCK_COLLECTION_ENTRY; + + /// MUTEX_COLLECTION maintains a mapping from token names to mutexes. + RWLOCK_COLLECTION rwlock_collection_; + + /// Singleton pointer. + static ACE_Token_Invariant_Manager *instance_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_TOKENS_LIBRARY */ + +#include /**/ "ace/post.h" +#endif /* ACE_TOKEN_INVARIANTS_H */ diff --git a/dep/acelite/ace/Token_Manager.cpp b/dep/acelite/ace/Token_Manager.cpp new file mode 100644 index 00000000000..1127622d96e --- /dev/null +++ b/dep/acelite/ace/Token_Manager.cpp @@ -0,0 +1,274 @@ +#include "ace/Token_Manager.h" + +#if defined (ACE_HAS_TOKENS_LIBRARY) + +#include "ace/Object_Manager.h" +#include "ace/os_include/os_typeinfo.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Token_Manager.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID (ace, + Token_Manager, + "$Id: Token_Manager.cpp 84179 2009-01-16 07:26:45Z johnnyw $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// singleton token manager +ACE_Token_Manager *ACE_Token_Manager::token_manager_ = 0; + +ACE_Token_Manager::ACE_Token_Manager () +{ + ACE_TRACE ("ACE_Token_Manager::ACE_Token_Manager"); +} + +ACE_Token_Manager::~ACE_Token_Manager () +{ + ACE_TRACE ("ACE_Token_Manager::~ACE_Token_Manager"); + + COLLECTION::ITERATOR iterator (collection_); + + for (COLLECTION::ENTRY *temp = 0; + iterator.next (temp) != 0; + iterator.advance ()) + { + // @ should I be doing an unbind here? + delete temp->int_id_; + // The ext_id_'s delete themselves when the array of + // COLLECTION::ENTRYs goes away. + } +} + +ACE_Token_Manager * +ACE_Token_Manager::instance (void) +{ + ACE_TRACE ("ACE_Token_Manager::instance"); + + // This first check is to avoid acquiring the mutex in the common + // case. Double-Check pattern rules. + if (token_manager_ == 0) + { +#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) + ACE_TOKEN_CONST::MUTEX *lock = + ACE_Managed_Object::get_preallocated_object + (ACE_Object_Manager::ACE_TOKEN_MANAGER_CREATION_LOCK); + ACE_GUARD_RETURN (ACE_TOKEN_CONST::MUTEX, ace_mon, *lock, 0); +#endif /* ACE_MT_SAFE */ + + if (token_manager_ == 0) + { + ACE_NEW_RETURN (token_manager_, + ACE_Token_Manager, + 0); + // Register for destruction with ACE_Object_Manager. + ACE_Object_Manager::at_exit (token_manager_, 0, typeid (token_manager_).name ()); + } + } + + return token_manager_; +} + +void +ACE_Token_Manager::get_token (ACE_Token_Proxy *proxy, + const ACE_TCHAR *token_name) +{ + ACE_TRACE ("ACE_Token_Manager::get_token"); + // Hmm. I think this makes sense. We perform our own locking here + // (see safe_acquire.) We have to make sure that only one thread + // uses the collection at a time. + + ACE_GUARD (ACE_TOKEN_CONST::MUTEX, ace_mon, this->lock_); + + TOKEN_NAME name (token_name); + + if (collection_.find (name, proxy->token_) == -1) + // We did not find one in the collection. + { + // Make one. + proxy->token_ = proxy->create_token (token_name); + + // Put it in the collection. + if (collection_.bind (name, proxy->token_) == -1) + { + delete proxy->token_; + proxy->token_ = 0; + } + } + + if (proxy->token_ != 0) + proxy->token_->inc_reference (); + + // We may be returning proxy->token_ == 0 if new failed, caller must + // check. +} + +// 0. check_deadlock (TOKEN) +// 1. if TOKEN->visited (), return 0. +// 2. mark TOKEN visited. +// 3. get ALL_OWNERS +// 4. if CLIENT in ALL_OWNERS, return *DEADLOCK*. +// 5. for each OWNER in ALL_OWNERS, +// 6. if OWNER is not waiting for a NEW_TOKEN, continue. +// 7. else, if check_deadlock (NEW_TOKEN) == 1, return *DEADLOCK* +// 8. return 0. + +int +ACE_Token_Manager::check_deadlock (ACE_Token_Proxy *proxy) +{ + ACE_TRACE ("ACE_Token_Manager::check_deadlock"); + + // Start the recursive deadlock detection algorithm. + int result = this->check_deadlock (proxy->token_, proxy); + + // Whether or not we detect deadlock, we have to unmark all tokens + // for the next time. + COLLECTION::ITERATOR iterator (collection_); + for (COLLECTION::ENTRY *temp = 0; + iterator.next (temp) != 0; + iterator.advance ()) + temp->int_id_->visit (0); + + return result; +} + +int +ACE_Token_Manager::check_deadlock (ACE_Tokens *token, ACE_Token_Proxy *proxy) +{ + ACE_TRACE ("ACE_Token_Manager::check_deadlock"); + + if (token->visited ()) + return 0; + + token->visit (1); + + ACE_Tokens::OWNER_STACK owners; + + int is_owner = token->owners (owners, proxy->client_id ()); + + switch (is_owner) + { + case -1: + // Error. + return -1; + case 1: + // The caller is an owner, so we have a deadlock situation. + if (debug_) + { + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Deadlock detected.\n"))); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("%s owns %s and is waiting for %s.\n"), + proxy->client_id (), + token->name (), + proxy->token_->name ())); + } + + return 1; + case 0: + default: + // Recurse on each owner. + while (!owners.is_empty ()) + { + ACE_TPQ_Entry *e; + owners.pop (e); + // If the owner is waiting on another token, recurse. + ACE_Tokens *twf = this->token_waiting_for (e->client_id ()); + if ((twf != 0) && + (this->check_deadlock (twf, proxy) == 1)) + { + if (debug_) + { + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("%s owns %s and is waiting for %s.\n"), + e->client_id (), + token->name (), + twf->name ())); + } + return 1; + } + // else, check the next owner. + } + + // We've checked all the owners and found no deadlock. + return 0; + } +} + + +ACE_Tokens * +ACE_Token_Manager::token_waiting_for (const ACE_TCHAR *client_id) +{ + COLLECTION::ITERATOR iterator (collection_); + for (COLLECTION::ENTRY *temp = 0; + iterator.next (temp) != 0; + iterator.advance ()) + { + if (temp->int_id_->is_waiting_for (client_id)) + return temp->int_id_; + } + + // nothing was found, return NULL. + return 0; +} + +// Notify the token manager that a token is has been released. If +// as a result, there is no owner of the token, the token is +// deleted. +void +ACE_Token_Manager::release_token (ACE_Tokens *&token) +{ + ACE_TRACE ("ACE_Token_Manager::release_token"); + // again, let's perform our own locking here. + + ACE_GUARD (ACE_TOKEN_CONST::MUTEX, ace_mon, this->lock_); + + if (token->dec_reference () == 0) + { + // No one has the token, so we can delete it and remove it from + // our collection. First, let's get it from the collection. + TOKEN_NAME token_name (token->name ()); + + ACE_Tokens *temp; + + if (collection_.unbind (token_name, temp) == -1) + // we did not find one in the collection + { + errno = ENOENT; + ACE_ERROR ((LM_ERROR, ACE_TEXT ("Token Manager could not release %s:%d\n"), + token->name (), token->type ())); + // @@ bad + } + else + // we found it + { + // sanity pointer comparison. The token referenced by the + // proxy better be the one we found in the list. + ACE_ASSERT (token == temp); + delete token; // or delete temp + // we set their token to zero. if the calling proxy is + // still going to be used, it had better check it's token + // value before calling a method on it! + token = 0; + } + } + // else + // someone is still interested in the token, so keep it around. +} + +void +ACE_Token_Manager::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Token_Manager::dump"); + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("ACE_Token_Manager::dump:\n"))); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("lock_\n"))); + lock_.dump (); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("collection_\n"))); + collection_.dump (); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_TOKENS_LIBRARY */ diff --git a/dep/acelite/ace/Token_Manager.h b/dep/acelite/ace/Token_Manager.h new file mode 100644 index 00000000000..9882e28ef67 --- /dev/null +++ b/dep/acelite/ace/Token_Manager.h @@ -0,0 +1,150 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Token_Manager.h + * + * $Id: Token_Manager.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Tim Harrison (harrison@cs.wustl.edu) + */ +//============================================================================= + +#ifndef ACE_TOKEN_MANAGER_H +#define ACE_TOKEN_MANAGER_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Local_Tokens.h" + +#if defined (ACE_HAS_TOKENS_LIBRARY) + +#include "ace/Null_Mutex.h" +#include "ace/Map_Manager.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +class ACE_Local_Mutex; +class ACE_Mutex_Token; + +/** + * @class ACE_Token_Manager + * + * @brief Manages all tokens in a process space. + * + * Factory: Proxies use the token manager to obtain token + * references. This allows multiple proxies to reference the same + * logical token. + * Deadlock detection: Tokens use the manager to check for + * deadlock situations during acquires. + */ +class ACE_Export ACE_Token_Manager : public ACE_Cleanup +{ + + // To add a new type of token (e.g. semaphore), do the following + // steps: 1. Create a new derivation of ACE_Token. This class + // defines the semantics of the new Token. 2. Create a + // derivation of ACE_Token_Manager. You will only need to + // redefine make_mutex. +public: + ACE_Token_Manager (void); + virtual ~ACE_Token_Manager (void); + + /// Get the pointer to token manager singleton. + static ACE_Token_Manager *instance (void); + + /// Set the pointer to token manager singleton. + void instance (ACE_Token_Manager *); + + /** + * The Token manager uses ACE_Token_Proxy::token_id_ to look for + * an existing token. If none is found, the Token Manager calls + * ACE_Token_Proxy::create_token to create a new one. When + * finished, sets ACE_Token_Proxy::token_. @a token_name uniquely + * id's the token name. + */ + void get_token (ACE_Token_Proxy *, const ACE_TCHAR *token_name); + + /** + * Check whether acquire will cause deadlock or not. + * returns 1 if the acquire will _not_ cause deadlock. + * returns 0 if the acquire _will_ cause deadlock. + * This method ignores recursive acquisition. That is, it will not + * report deadlock if the client holding the token requests the + * token again. Thus, it assumes recursive mutexes. + */ + int check_deadlock (ACE_Token_Proxy *proxy); + int check_deadlock (ACE_Tokens *token, ACE_Token_Proxy *proxy); + + /// Notify the token manager that a token has been released. If as a + /// result, there is no owner of the token, the token is deleted. + void release_token (ACE_Tokens *&token); + + /** + * This is to allow Tokens to perform atomic transactions. The + * typical usage is to acquire this mutex, check for a safe_acquire, + * perform some queueing (if need be) and then release the lock. + * This is necessary since safe_acquire is implemented in terms of + * the Token queues. + */ + ACE_TOKEN_CONST::MUTEX &mutex (void); + + /// Dump the state of the class. + void dump (void) const; + + /// Turn debug mode on/off. + void debug (bool d); + +private: + /// Whether to print debug messages or not. + bool debug_; + + /// pointer to singleton token manager. + static ACE_Token_Manager *token_manager_; + + /// Return the token that the given client_id is waiting for, if any + ACE_Tokens *token_waiting_for (const ACE_TCHAR *client_id); + + /// ACE_Mutex_Token used to lock internal data structures. + ACE_TOKEN_CONST::MUTEX lock_; + + /// This may be changed to a template type. + typedef ACE_Token_Name TOKEN_NAME; + + /// COLLECTION maintains a mapping from token names to ACE_Tokens* + typedef ACE_Map_Manager + COLLECTION; + + /// Allows iterations through collection_ + /** + * @deprecated Deprecated typedef. Use COLLECTION::ITERATOR trait + * instead. + */ + typedef COLLECTION::ITERATOR COLLECTION_ITERATOR; + + /// Allows iterations through collection_ + /** + * @deprecated Deprecated typedef. Use COLLECTION::ENTRY trait + * instead. + */ + typedef COLLECTION::ENTRY COLLECTION_ENTRY; + + /// COLLECTION maintains a mapping from token names to ACE_Tokens*. + COLLECTION collection_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Token_Manager.inl" +#endif /* __ACE_INLINE__ */ + +#endif /* ACE_HAS_TOKENS_LIBRARY */ + +#include /**/ "ace/post.h" +#endif /* ACE_TOKEN_MANAGER_H */ diff --git a/dep/acelite/ace/Token_Manager.inl b/dep/acelite/ace/Token_Manager.inl new file mode 100644 index 00000000000..a44778c89b2 --- /dev/null +++ b/dep/acelite/ace/Token_Manager.inl @@ -0,0 +1,25 @@ +// -*- C++ -*- +// +// $Id: Token_Manager.inl 80826 2008-03-04 14:51:23Z wotte $ + +#if defined (ACE_HAS_TOKENS_LIBRARY) + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE ACE_TOKEN_CONST::MUTEX & +ACE_Token_Manager::mutex (void) +{ + ACE_TRACE ("ACE_Token_Manager::mutex"); + return lock_; +} + +ACE_INLINE void +ACE_Token_Manager::debug (bool d) +{ + ACE_TRACE ("ACE_Token_Manager::debug"); + debug_ = d; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_TOKENS_LIBRARY */ diff --git a/dep/acelite/ace/Token_Request_Reply.cpp b/dep/acelite/ace/Token_Request_Reply.cpp new file mode 100644 index 00000000000..598afe01388 --- /dev/null +++ b/dep/acelite/ace/Token_Request_Reply.cpp @@ -0,0 +1,186 @@ +// $Id: Token_Request_Reply.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/Token_Request_Reply.h" + +#if defined (ACE_HAS_TOKENS_LIBRARY) + +#if !defined (__ACE_INLINE__) +#include "ace/Token_Request_Reply.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID(ace, Token_Request_Reply, "$Id: Token_Request_Reply.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Default "do nothing" constructor. + +ACE_Token_Request::ACE_Token_Request (void) + : token_name_ (0), + client_id_ (0) +{ +} + +// Create a ACE_Token_Request message. + +ACE_Token_Request::ACE_Token_Request (int token_type, + int proxy_type, + ACE_UINT32 operation_type, + const ACE_TCHAR token_name[], + const ACE_TCHAR client_id[], + const ACE_Synch_Options &options) +{ + this->token_type (token_type); + this->proxy_type (proxy_type); + this->operation_type (operation_type); + this->requeue_position (0); // to avoid Purify UMR + this->notify (0); // to avoid Purify UMR + transfer_.arg_ = 0; // to avoid Purify UMR + ACE_OS::memset (transfer_.data_, 0, sizeof transfer_.data_); // to avoid Purify UMR + this->token_name (token_name, client_id); + this->options (options); +} + +// Encode the transfer buffer into network byte order +// so that it can be sent to the server. + +int +ACE_Token_Request::encode (void *&buf) +{ + buf = (void *) &this->transfer_; + return this->length (); +} + +// Decode the transfer buffer into host byte byte order +// so that it can be used by the server. + +int +ACE_Token_Request::decode (void) +{ + this->token_name_ = this->transfer_.data_; + + options_.set (transfer_.use_timeout_ == 1 ? ACE_Synch_Options::USE_TIMEOUT : 0, + ACE_Time_Value (transfer_.sec_, transfer_.usec_), + (void *) transfer_.arg_); + + // Decode the variable-sized portion. + size_t token_len = ACE_OS::strlen (this->token_name_); + + // Check to make sure this->tokenName_ isn't too long! + if (token_len >= ACE_MAXTOKENNAMELEN) + { + errno = ENAMETOOLONG; + return -1; + } + else // Skip this->tokenName_ + '\0' + ':'. + this->client_id_ = + &this->token_name_[(token_len + 2) * sizeof (ACE_TCHAR)]; + + // Fixed size header + // token_name_ plus '\0' + // ':' + // client_id_ plus '\0' + size_t data_size = ACE_TOKEN_REQUEST_HEADER_SIZE + + ACE_OS::strlen (this->token_name_) + 1 + + ACE_OS::strlen (this->client_id_) + 1 + + 1; + + // Make sure the message was correctly received and framed. + return this->length () == data_size ? 0 : -1; +} + +// Print out the current values of the ACE_Token_Request. + +void +ACE_Token_Request::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("*******\nlength = %d\ntoken name = %s\nclient id = %s\n"), + this->length (), this->token_name (), this->client_id ())); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("type = "))); + + if (this->token_type () == ACE_Tokens::MUTEX) + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("MUTEX\n"))); + else // == ACE_Tokens::RWLOCK + { + if (this->proxy_type () == ACE_RW_Token::READER) + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("RLOCK\n"))); + else // == WRITER + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("WLOCK\n"))); + } + + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("operation = "))); + switch (this->operation_type ()) + { + case ACE_Token_Request::ACQUIRE: + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("ACQUIRE\n"))); + break; + case ACE_Token_Request::RELEASE: + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("RELEASE\n"))); + break; + case ACE_Token_Request::RENEW: + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("RENEW\n"))); + break; + default: + ACE_DEBUG ((LM_DEBUG, ACE_TEXT (" = %d\n"), this->operation_type ())); + break; + } + + if (this->options ()[ACE_Synch_Options::USE_TIMEOUT] == 0) + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("blocking forever\n"))); + else + { + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("waiting for %d secs and %d usecs\n"), + this->options ().timeout ().sec (), this->options ().timeout ().usec ())); + } + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +// ************************************************************ +// ************************************************************ +// ************************************************************ + +// Create a ACE_Token_Reply message. + +ACE_Token_Reply::ACE_Token_Reply (void) // Type of reply. +{ + this->arg (0); + this->errnum (0); + this->length (sizeof (Transfer)); +} + +// Encode the transfer buffer into network byte order +// so that it can be sent to the client. + +int +ACE_Token_Reply::encode (void *&buf) +{ + buf = (void *) &this->transfer_; + return this->length (); +} + +// Decode the transfer buffer into host byte order +// so that it can be used by the client. + +int +ACE_Token_Reply::decode (void) +{ + return 0; +} + +// Print out current values of the ACE_Token_Reply object. + +void +ACE_Token_Reply::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("*******\nlength = %d\nerrnum = %d"), + this->length (), this->errnum ())); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("arg = %d"), this->arg ())); +#endif /* ACE_HAS_DUMP */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_TOKENS_LIBRARY */ diff --git a/dep/acelite/ace/Token_Request_Reply.h b/dep/acelite/ace/Token_Request_Reply.h new file mode 100644 index 00000000000..01a7cfd3e82 --- /dev/null +++ b/dep/acelite/ace/Token_Request_Reply.h @@ -0,0 +1,270 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Token_Request_Reply.h + * + * $Id: Token_Request_Reply.h 80826 2008-03-04 14:51:23Z wotte $ + * + * Define the format used to exchange messages between the + * ACE_Token Server and its clients. + * + * + * @author Douglas C. Schmidt (schmidt@cs.wustl.edu) + * @author Tim Harrison (harrison@cs.wustl.edu) + */ +//============================================================================= + + +#ifndef ACE_TOKEN_REQUEST_REPLY_H +#define ACE_TOKEN_REQUEST_REPLY_H +#include /**/ "ace/pre.h" + +#include "ace/Local_Tokens.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_TOKENS_LIBRARY) + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/// Specifies the size of the fixed length portion of +/// the Transfer structure in ACE_Token_Request +#define ACE_TOKEN_REQUEST_HEADER_SIZE 40 + +/** + * @class ACE_Token_Request + * + * @brief Message format for delivering requests to the ACE_Token Server. + * + * This class is implemented to minimize data copying. + * In particular, all marshaling is done in situ... + */ +class ACE_Export ACE_Token_Request +{ +public: + /// Operation types. + enum OPERATION + { + /// Acquire the token. + ACQUIRE, + /// Release the token. + RELEASE, + /// Renew the token. + RENEW, + /// Remove the token. + REMOVE, + // Try to acquire the token. + TRY_ACQUIRE + }; + + /// Default constructor. + ACE_Token_Request (void); + + /** + * @param token_type MUTEX, RWLOCK + * @param proxy_type MUTEX, RLOCK, WLOCK (acquires mean different things) + * @param operation method + * @param token_name + * @param client_id + * @param options We check USE_TIMEOUT and use the arg. + */ + ACE_Token_Request (int token_type, + int proxy_type, + ACE_UINT32 operation, + const ACE_TCHAR token_name[], + const ACE_TCHAR client_id[], + const ACE_Synch_Options &options); + + /// Get the length of the encoded/decoded message. + ACE_UINT32 length (void) const; + + /// Set the length of the encoded/decoded message. + void length (ACE_UINT32); + + /// Get the type of proxy + int proxy_type (void) const; + + /// Set the type of proxy + void proxy_type (int proxy_type); + + /// Get the type of token + int token_type (void) const; + + /// Set the type of token + void token_type (int token_type); + + /// Get the type of the operation. + ACE_UINT32 operation_type (void) const; + + /// Set the type of the operation. + void operation_type (ACE_UINT32); + + /// Get the requeue position. These should be used when renew + /// is the operation type. + ACE_UINT32 requeue_position (void) const; + + /// Set the requeue position. These should be used when renew + /// is the operation type. + void requeue_position (ACE_UINT32); + + /// Get notify. These should be used when acquire is the operation type. + ACE_UINT32 notify (void) const; + + /// Set notify. These should be used when acquire is the operation type. + void notify (ACE_UINT32); + + /// Get the timeout. + ACE_Synch_Options &options (void) const; + + /// Set the timeout. + void options (const ACE_Synch_Options &options); + + // = Set/get the name of the token and the client id. The set + // method is combined to make it easier on us. We're copying the + // names as a contiguous buffer. + ACE_TCHAR *token_name (void) const; + ACE_TCHAR *client_id (void) const; + void token_name (const ACE_TCHAR *token_name, const ACE_TCHAR *client_id); + + /// Encode the message before transmission. + int encode (void *&); + + /// Decode message after reception. This must be called to set the + /// internal options. + int decode (void); + + /// Print out the values of the message for debugging purposes. + void dump (void) const; + +private: + // = The 5 fields in the struct are transmitted to the server. + // The remaining 2 fields are not tranferred -- they are used only on + // the server-side to simplify lookups. + + struct Transfer + { + /// Length of entire request. + ACE_UINT32 length_; + + /// Type of the request (i.e., MUTEX, RLOCK, WLOCK... + ACE_UINT32 token_type_; + + /// Type of the request (i.e., MUTEX, RLOCK, WLOCK... + ACE_UINT32 proxy_type_; + + /// Type of the request (i.e., , , , and ). + ACE_UINT32 operation_type_; + + /// this only makes sense when operation type is renew + ACE_UINT32 requeue_position_; + + /// this only makes sense when operation type is renew + ACE_UINT32 notify_; + + // = ACE_Synch_Options stuff + + /// Indicates if we should block forever. If 1, then + /// and indicates how long we should wait. If 0, + /// then we block forever. + ACE_UINT32 use_timeout_; + + /// Max seconds willing to wait for token if not blocking forever. + ACE_UINT32 sec_; + + /// Max micro seconds to wait for token if not blocking forever. + ACE_UINT32 usec_; + + /// value returned in ; + ACE_UINT32 arg_; + + /// The data portion contains the including a 0 terminator, + /// a ':', then the including a 0 terminator + ACE_TCHAR data_[ACE_MAXTOKENNAMELEN + ACE_MAXCLIENTIDLEN + 3]; + } transfer_; + + /// Pointer to the beginning of the token name in this->data_. + ACE_TCHAR *token_name_; + + /// Pointer to the beginning of the client id in this->data_; + ACE_TCHAR *client_id_; + + /// Holds arg, sec, usec, etc. + ACE_Synch_Options options_; +}; + +/** + * @class ACE_Token_Reply + * + * @brief Message format for delivering replies from the ACE_Token Server. + * + * This class is implemented to minimize data copying. + * In particular, all marshaling is done in situ... + */ +class ACE_Export ACE_Token_Reply +{ +public: + /// Default constructor. + ACE_Token_Reply (void); + + /// Get the length of the encoded/decoded message. + ACE_UINT32 length (void) const; + + /// Set the length of the encoded/decoded message. + void length (ACE_UINT32); + + /// Get the errno of a reply. + ACE_UINT32 errnum (void) const; + + /// Set the errno of a reply. + void errnum (ACE_UINT32); + + /// Get the arg of a reply. + ACE_UINT32 arg (void) const; + + /// Set the arg of a reply. + void arg (ACE_UINT32); + + /// Encode the message before transfer. + int encode (void *&); + + /// Decode a message after reception. + int decode (void); + + /// Print out the values of the message for debugging purposes. + void dump (void) const; + +private: + // = The 2 fields in the struct are transmitted to the server. + + struct Transfer + { + /// Length of entire reply. + ACE_UINT32 length_; + + /// Indicates why error occurred if type_> == . + /// Typical reasons include: + /// @c EWOULDBLOCK (if client requested a non-blocking check for the token). + /// @c ETIME (if the client timed out after waiting for the token). + /// (if the token lock was removed out from underneath a waiter). + /// (attempt to renew a token that isn't owned by the client). + ACE_UINT32 errno_; + + /// magic cookie + ACE_UINT32 arg_; + + } transfer_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Token_Request_Reply.inl" +#endif /* __ACE_INLINE__ */ + +#endif /* ACE_HAS_TOKENS_LIBRARY */ + +#include /**/ "ace/post.h" +#endif /* ACE_TOKEN_REQUEST_REPLY_H */ diff --git a/dep/acelite/ace/Token_Request_Reply.inl b/dep/acelite/ace/Token_Request_Reply.inl new file mode 100644 index 00000000000..4291bfa6089 --- /dev/null +++ b/dep/acelite/ace/Token_Request_Reply.inl @@ -0,0 +1,205 @@ +// -*- C++ -*- +// +// $Id: Token_Request_Reply.inl 80826 2008-03-04 14:51:23Z wotte $ + +#if defined (ACE_HAS_TOKENS_LIBRARY) + +#include "ace/Truncate.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// = Set/get the length of the encoded/decoded message. + +ACE_INLINE ACE_UINT32 +ACE_Token_Request::length (void) const +{ + return ntohl (this->transfer_.length_); +} + +ACE_INLINE void +ACE_Token_Request::length (ACE_UINT32 l) +{ + this->transfer_.length_ = htonl (l); +} + +// = Set/get the type of the message. +ACE_INLINE int +ACE_Token_Request::token_type (void) const +{ + return (int) ntohl (this->transfer_.token_type_); +} + +ACE_INLINE void +ACE_Token_Request::token_type (int t) +{ + this->transfer_.token_type_ = htonl ((ACE_UINT32) t); +} + +// = Set/get the type of the message. +ACE_INLINE int +ACE_Token_Request::proxy_type (void) const +{ + return (int) ntohl (this->transfer_.proxy_type_); +} + +ACE_INLINE void +ACE_Token_Request::proxy_type (int t) +{ + this->transfer_.proxy_type_ = htonl ((ACE_UINT32) t); +} + +// = Set/get the type of the message. +ACE_INLINE ACE_UINT32 +ACE_Token_Request::operation_type (void) const +{ + return ntohl (this->transfer_.operation_type_); +} + +ACE_INLINE void +ACE_Token_Request::operation_type (ACE_UINT32 t) +{ + this->transfer_.operation_type_ = htonl (t); +} + +// = Set/get the requeue position +ACE_INLINE ACE_UINT32 +ACE_Token_Request::requeue_position (void) const +{ + return ntohl (this->transfer_.requeue_position_); +} + +ACE_INLINE void +ACE_Token_Request::requeue_position (ACE_UINT32 rq) +{ + this->transfer_.requeue_position_ = htonl (rq); +} + +// = Set/get the requeue position +ACE_INLINE ACE_UINT32 +ACE_Token_Request::notify (void) const +{ + return ntohl (this->transfer_.notify_); +} + +ACE_INLINE void +ACE_Token_Request::notify (ACE_UINT32 rq) +{ + this->transfer_.notify_ = htonl (rq); +} + +// = Set/get the blocking semantics. +ACE_INLINE ACE_Synch_Options & +ACE_Token_Request::options (void) const +{ + return (ACE_Synch_Options &) options_; +} + +ACE_INLINE void +ACE_Token_Request::options (const ACE_Synch_Options &opt) +{ + // fight the friggin const from hell + ACE_Synch_Options *options = (ACE_Synch_Options *) &opt; + + transfer_.use_timeout_ = options->operator[](ACE_Synch_Options::USE_TIMEOUT); + if (transfer_.use_timeout_ == 1) + { + transfer_.usec_ = options->timeout ().usec (); + if (options->timeout ().sec () > (time_t) ACE_UINT32_MAX) + transfer_.sec_ = ACE_UINT32_MAX; + else + transfer_.sec_ = static_cast (options->timeout ().sec ()); + } + else + { + transfer_.usec_ = 0; + transfer_.sec_ = 0; + } +} + +// = Set/get the name of the token. +ACE_INLINE ACE_TCHAR * +ACE_Token_Request::token_name (void) const +{ + return token_name_; +} + +ACE_INLINE void +ACE_Token_Request::token_name (const ACE_TCHAR *token_name, + const ACE_TCHAR *client_id) +{ + size_t token_name_length = ACE_OS::strlen (token_name) + 1; // Add 1 for '\0'. + size_t client_id_length = ACE_OS::strlen (client_id) + 1; // Add 1 for '\0'. + + // Set up pointers and copy token_name and client_id into request. + token_name_ = this->transfer_.data_; + client_id_ = &this->token_name_[token_name_length + 1]; // Add 1 for ':'; + client_id_[-1] = ACE_TEXT (':'); // Insert the ':' before this->clientId_. + + (void) ACE_OS::memcpy (this->token_name_, + token_name, + token_name_length * sizeof (ACE_TCHAR)); + (void) ACE_OS::memcpy (this->client_id_, + client_id, + client_id_length * sizeof (ACE_TCHAR)); + + // Fixed length header size + size_t len = ACE_TOKEN_REQUEST_HEADER_SIZE; + + // ... then add in the amount of the variable-sized portion. + len += token_name_length + client_id_length + 1; + this->length (ACE_Utils::truncate_cast (len)); +} + +// = Set/get the id of the client. +ACE_INLINE ACE_TCHAR * +ACE_Token_Request::client_id (void) const +{ + return this->client_id_; +} + +// ************************************************************ +// ************************************************************ +// ************************************************************ + +// = Set/get the length of the encoded/decoded message. +ACE_INLINE ACE_UINT32 +ACE_Token_Reply::length (void) const +{ + return ntohl (this->transfer_.length_); +} + +ACE_INLINE void +ACE_Token_Reply::length (ACE_UINT32 l) +{ + this->transfer_.length_ = htonl (l); +} + +// = Set/get the errno of a failed reply. +ACE_INLINE ACE_UINT32 +ACE_Token_Reply::errnum (void) const +{ + return ntohl (this->transfer_.errno_); +} + +ACE_INLINE void +ACE_Token_Reply::errnum (ACE_UINT32 e) +{ + this->transfer_.errno_ = htonl (e); +} + +// = Set/get the length of the encoded/decoded message. +ACE_INLINE ACE_UINT32 +ACE_Token_Reply::arg (void) const +{ + return ntohl (this->transfer_.arg_); +} + +ACE_INLINE void +ACE_Token_Reply::arg (ACE_UINT32 arg) +{ + this->transfer_.arg_ = htonl (arg); +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_TOKENS_LIBRARY */ diff --git a/dep/acelite/ace/Tokenizer_T.cpp b/dep/acelite/ace/Tokenizer_T.cpp new file mode 100644 index 00000000000..00aa2abdc79 --- /dev/null +++ b/dep/acelite/ace/Tokenizer_T.cpp @@ -0,0 +1,242 @@ +// $Id: Tokenizer_T.cpp 88793 2010-02-01 17:50:34Z cleeland $ + +#ifndef ACE_TOKENIZER_T_CPP +#define ACE_TOKENIZER_T_CPP + +#include "ace/ACE.h" +#include "ace/Malloc_Base.h" +#include "ace/String_Base.h" +#include "ace/Auto_Ptr.h" +#include "ace/OS_NS_string.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template +ACE_Tokenizer_T::ACE_Tokenizer_T (ACE_CHAR_T *buffer) + : buffer_ (buffer), + index_ (0), + preserves_index_ (0), + delimiter_index_ (0) +{ +} + +template +int +ACE_Tokenizer_T::delimiter (ACE_CHAR_T d) +{ + if (delimiter_index_ == MAX_DELIMITERS) + return -1; + + delimiters_[delimiter_index_].delimiter_ = d; + delimiters_[delimiter_index_].replace_ = 0; + ++delimiter_index_; + return 0; +} + +template +int +ACE_Tokenizer_T::delimiter_replace (ACE_CHAR_T d, + ACE_CHAR_T replacement) +{ + // Make it possible to replace delimiters on-the-fly, e.g., parse + // string until certain token count and then copy rest of the + // original string. + for (int i = 0; i < delimiter_index_; i++) + if (delimiters_[i].delimiter_ == d) + { + delimiters_[i].replacement_ = replacement; + delimiters_[i].replace_ = 1; + return 0; + } + + if (delimiter_index_ >= MAX_DELIMITERS) + return -1; + + delimiters_[delimiter_index_].delimiter_ = d; + delimiters_[delimiter_index_].replacement_ = replacement; + delimiters_[delimiter_index_].replace_ = 1; + ++delimiter_index_; + return 0; +} + +template +int +ACE_Tokenizer_T::preserve_designators (ACE_CHAR_T start, + ACE_CHAR_T stop, + int strip) +{ + if (preserves_index_ == MAX_PRESERVES) + return -1; + + preserves_[preserves_index_].start_ = start; + preserves_[preserves_index_].stop_ = stop; + preserves_[preserves_index_].strip_ = strip; + ++preserves_index_; + return 0; +} + +template +int +ACE_Tokenizer_T::is_delimiter (ACE_CHAR_T d, + int &replace, + ACE_CHAR_T &r) +{ + replace = 0; + + for (int x = 0; x < delimiter_index_; x++) + if (delimiters_[x].delimiter_ == d) + { + if (delimiters_[x].replace_) + { + r = delimiters_[x].replacement_; + replace = 1; + } + return 1; + } + + return 0; +} + +template +int +ACE_Tokenizer_T::is_preserve_designator (ACE_CHAR_T start, + ACE_CHAR_T &stop, + int &strip) +{ + for (int x = 0; x < preserves_index_; x++) + if (preserves_[x].start_ == start) + { + stop = preserves_[x].stop_; + strip = preserves_[x].strip_; + return 1; + } + + return 0; +} + +template +ACE_CHAR_T * +ACE_Tokenizer_T::next (void) +{ + // Check if the previous pass was the last one in the buffer. + if (index_ == -1) + { + index_ = 0; + return 0; + } + + // Check if a buffer has been passed + if (!buffer_) + { + return 0; + } + + ACE_CHAR_T replacement = 0; + int replace; + ACE_CHAR_T *next_token = 0; + + // Skip all leading delimiters. + for (;;) + { + // Check for end of string. + if (buffer_[index_] == '\0') + { + // If we hit EOS at the start, return 0. + index_ = 0; + return 0; + } + + if (this->is_delimiter (buffer_[index_], + replace, + replacement)) + ++index_; + else + break; + } + + // When we reach this point, buffer_[index_] is a non-delimiter and + // not EOS - the start of our next_token. + next_token = buffer_ + index_; + + // A preserved region is it's own token. + ACE_CHAR_T stop; + int strip; + if (this->is_preserve_designator (buffer_[index_], + stop, + strip)) + { + while (++index_) + { + if (buffer_[index_] == '\0') + { + index_ = -1; + goto EXIT_LABEL; + } + + if (buffer_[index_] == stop) + break; + } + + if (strip) + { + // Skip start preserve designator. + next_token += 1; + // Zap the stop preserve designator. + buffer_[index_] = '\0'; + // Increment to the next token. + ++index_; + } + + goto EXIT_LABEL; + } + + // Step through finding the next delimiter or EOS. + for (;;) + { + // Advance pointer. + ++index_; + + // Check for delimiter. + if (this->is_delimiter (buffer_[index_], + replace, + replacement)) + { + // Replace the delimiter. + if (replace != 0) + buffer_[index_] = replacement; + + // Move the pointer up and return. + ++index_; + goto EXIT_LABEL; + } + + // A preserve designator is NESTED inside this token + // We can't strip such preserve designators, just skip + // over them so that delimiters nested within arn't seen. + if (this->is_preserve_designator (buffer_[index_], + stop, + strip)) + { + ++index_; // Skip starting preserve_designator + while (('\0' != buffer_[index_]) && (stop != buffer_[index_])) + ++index_; // Skip enclosed character + } + + // Check for end of string. + if (buffer_[index_] == '\0') + { + index_ = -1; + goto EXIT_LABEL; + } + } + +EXIT_LABEL: + return next_token; +} + +// ************************************************************* + + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_TOKENIZER_T_CPP */ diff --git a/dep/acelite/ace/Tokenizer_T.h b/dep/acelite/ace/Tokenizer_T.h new file mode 100644 index 00000000000..b13f5bb5ab6 --- /dev/null +++ b/dep/acelite/ace/Tokenizer_T.h @@ -0,0 +1,241 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Tokenizer_T.h + * + * $Id: Tokenizer_T.h 88793 2010-02-01 17:50:34Z cleeland $ + * + * @author Douglas C. Schmidt (schmidt@cs.wustl.edu) + * @author Nanbor Wang + */ +//============================================================================= + +#ifndef ACE_TOKENIZER_T_H +#define ACE_TOKENIZER_T_H + +#include /**/ "ace/pre.h" + +#include "ace/Global_Macros.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Tokenizer_T + * + * @brief Tokenizer + * + * Tokenizes a buffer. Allows application to set delimiters and + * preserve designators. Does not allow special characters, yet + * (e.g., printf ("\"like a quoted string\"")). + */ +template +class ACE_Tokenizer_T +{ +public: + /** + * \a buffer will be parsed. Notice that ACE_Tokenizer_T will modify + * \a buffer if you use delimiter_replace or + * preserve_designators to do character substitution. + * @note You should NOT pass a constant string or string literal + * to this constructor, since ACE_Tokenizer_T will try to modify + * the string. + * \sa preserve_designators + * \sa preserve_designators + */ + ACE_Tokenizer_T (ACE_CHAR_T *buffer); + + /** + * \a d is a delimiter. + * \return Returns 0 on success, -1 if there is no memory left. + * + * Example: + * \verbatim + char buf[30]; + ACE_OS::strcpy(buf, "William/Joseph/Hagins"); + + ACE_Tokenizer_T tok (buf); + tok.delimiter ('/'); + for (char *p = tok.next (); p; p = tok.next ()) + cout << p << endl; + \endverbatim + * + * This will print out: + * \verbatim + William/Joseph/Hagins + Joseph/Hagins + Hagins \endverbatim + */ + int delimiter (ACE_CHAR_T d); + + /** + * \a d is a delimiter and, when found, will be replaced by + * \a replacement. + * \return 0 on success, -1 if there is no memory left. + * + * Example: + * \verbatim + char buf[30]; + ACE_OS::strcpy(buf, "William/Joseph/Hagins"); + + ACE_Tokenizer tok (buf); + tok.delimiter_replace ('/', 0); + for (char *p = tok.next (); p; p = tok.next ()) + cout << p << endl; + \endverbatim + * + * This will print out: + * \verbatim + William + Joseph + Hagins \endverbatim + */ + int delimiter_replace (ACE_CHAR_T d, ACE_CHAR_T replacement); + + /** + * Extract string between a pair of designator characters. + * For instance, quotes, or '(' and ')'. + * \a start specifies the begin designator. + * \a stop specifies the end designator. + * \a strip If \a strip == 1, then the preserve + * designators will be stripped from the tokens returned by next. + * \return 0 on success, -1 if there is no memory left. + * + * Example with strip = 0: + * \verbatim + char buf[30]; + ACE_OS::strcpy(buf, "William(Joseph)Hagins"); + + ACE_Tokenizer tok (buf); + tok.preserve_designators ('(', ')', 0); + for (char *p = tok.next (); p; p = tok.next ()) + cout << p << endl; + \endverbatim + * + * This will print out: + * \verbatim + William(Joseph)Hagins + (Joseph)Hagins + )Hagins \endverbatim + * + * Example with strip = 1: + * \verbatim + char buf[30]; + ACE_OS::strcpy(buf, "William(Joseph)Hagins"); + + ACE_Tokenizer tok (buf); + tok.preserve_designators ('(', ')', 1); + for (char *p = tok.next (); p; p = tok.next ()) + cout << p << endl; + \endverbatim + * + * This will print out: + * \verbatim + William + Joseph + Hagins \endverbatim + */ + int preserve_designators (ACE_CHAR_T start, ACE_CHAR_T stop, int strip=1); + + /// Returns the next token. + ACE_CHAR_T *next (void); + + enum { + MAX_DELIMITERS=16, + MAX_PRESERVES=16 + }; + +protected: + /// Returns 1 if @a d is a delimiter, 0 otherwise. If @a d should be + /// replaced with @a r, @a replace is set to 1, otherwise 0. + int is_delimiter (ACE_CHAR_T d, int &replace, ACE_CHAR_T &r); + + /** + * If @a start is a start preserve designator, returns 1 and sets + * @a stop to the stop designator. Returns 0 if @a start is not a + * preserve designator. + */ + int is_preserve_designator (ACE_CHAR_T start, ACE_CHAR_T &stop, int &strip); + + ACE_CHAR_T *buffer_; + int index_; + + /** + * @class Preserve_Entry + * + * @brief Preserve Entry + * + * Defines a set of characters that designate an area that + * should not be parsed, but should be treated as a complete + * token. For instance, in: (this is a preserve region), start + * would be a left paren -(- and stop would be a right paren + * -)-. The strip determines whether the designators should be + * removed from the token. + */ + class Preserve_Entry + { + public: + /** + * E.g., "(". + * E.g., ")". + * Whether the designators should be removed from the token. + */ + ACE_CHAR_T start_; + ACE_CHAR_T stop_; + int strip_; + }; + + /// The application can specify MAX_PRESERVES preserve designators. + Preserve_Entry preserves_[MAX_PRESERVES]; + + /// Pointer to the next free spot in preserves_. + int preserves_index_; + + /** + * @class Delimiter_Entry + * + * @brief Delimiter Entry + * + * Describes a delimiter for the tokenizer. + */ + class Delimiter_Entry + { + public: + /** + * Most commonly a space ' '. + * What occurrences of delimiter_ should be replaced with. + * Whether replacement_ should be used. This should be replaced + * with a technique that sets replacement_ = delimiter by + * default. I'll do that next iteration. + */ + ACE_CHAR_T delimiter_; + ACE_CHAR_T replacement_; + int replace_; + }; + + /// The tokenizer allows MAX_DELIMITERS number of delimiters. + Delimiter_Entry delimiters_[MAX_DELIMITERS]; + + /// Pointer to the next free space in delimiters_. + int delimiter_index_; +}; + +typedef ACE_Tokenizer_T ACE_Tokenizer; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Tokenizer_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Tokenizer_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" + +#endif /* ACE_TOKENIZER_T_H */ diff --git a/dep/acelite/ace/Trace.cpp b/dep/acelite/ace/Trace.cpp new file mode 100644 index 00000000000..06269ccac1f --- /dev/null +++ b/dep/acelite/ace/Trace.cpp @@ -0,0 +1,136 @@ +// $Id: Trace.cpp 87823 2009-11-30 12:38:34Z johnnyw $ + +#include "ace/Trace.h" + +ACE_RCSID (ace, + Trace, + "$Id: Trace.cpp 87823 2009-11-30 12:38:34Z johnnyw $") + +// Turn off tracing for the duration of this file. +#if defined (ACE_NTRACE) +#undef ACE_NTRACE +#endif /* ACE_NTRACE */ +#define ACE_NTRACE 1 + +#include "ace/Log_Msg.h" +#include "ace/Object_Manager_Base.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// = Static initialization. + +// Keeps track of how far to indent per trace call. +int ACE_Trace::nesting_indent_ = ACE_Trace::DEFAULT_INDENT; + +// Is tracing enabled? +bool ACE_Trace::enable_tracing_ = ACE_Trace::DEFAULT_TRACING; + +ACE_ALLOC_HOOK_DEFINE(ACE_Trace) + +void +ACE_Trace::dump (void) const +{ +#if defined (ACE_HAS_DUMP) +#endif /* ACE_HAS_DUMP */ +} + +// Determine whether or not tracing is enabled + +bool +ACE_Trace::is_tracing (void) +{ + return ACE_Trace::enable_tracing_; +} + +// Enable the tracing facility. + +void +ACE_Trace::start_tracing (void) +{ + ACE_Trace::enable_tracing_ = true; +} + +// Disable the tracing facility. + +void +ACE_Trace::stop_tracing (void) +{ + ACE_Trace::enable_tracing_ = false; +} + +// Change the nesting indentation level. + +void +ACE_Trace::set_nesting_indent (int indent) +{ + ACE_Trace::nesting_indent_ = indent; +} + +// Get the nesting indentation level. + +int +ACE_Trace::get_nesting_indent (void) +{ + return ACE_Trace::nesting_indent_; +} + +// Perform the first part of the trace, which prints out the string N, +// the LINE, and the ACE_FILE as the function is entered. + +ACE_Trace::ACE_Trace (const ACE_TCHAR *n, + int line, + const ACE_TCHAR *file) +{ +#if defined (ACE_NLOGGING) + ACE_UNUSED_ARG (line); + ACE_UNUSED_ARG (file); +#endif /* ACE_NLOGGING */ + + this->name_ = n; + + // If ACE has not yet been initialized, don't try to trace... there's + // too much stuff not yet initialized. + if (ACE_Trace::enable_tracing_ && !ACE_OS_Object_Manager::starting_up ()) + { + ACE_Log_Msg *lm = ACE_LOG_MSG; + if (lm->tracing_enabled () + && lm->trace_active () == 0) + { + lm->trace_active (1); + ACE_DEBUG ((LM_TRACE, + ACE_TEXT ("%*s(%t) calling %s in file `%s' on line %d\n"), + ACE_Trace::nesting_indent_ * lm->inc (), + ACE_TEXT (""), + this->name_, + file, + line)); + lm->trace_active (0); + } + } +} + +// Perform the second part of the trace, which prints out the NAME as +// the function is exited. + +ACE_Trace::~ACE_Trace (void) +{ + // If ACE has not yet been initialized, don't try to trace... there's + // too much stuff not yet initialized. + if (ACE_Trace::enable_tracing_ && !ACE_OS_Object_Manager::starting_up ()) + { + ACE_Log_Msg *lm = ACE_LOG_MSG; + if (lm->tracing_enabled () + && lm->trace_active () == 0) + { + lm->trace_active (1); + ACE_DEBUG ((LM_TRACE, + ACE_TEXT ("%*s(%t) leaving %s\n"), + ACE_Trace::nesting_indent_ * lm->dec (), + ACE_TEXT (""), + this->name_)); + lm->trace_active (0); + } + } +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Trace.h b/dep/acelite/ace/Trace.h new file mode 100644 index 00000000000..3fbc9ce0be5 --- /dev/null +++ b/dep/acelite/ace/Trace.h @@ -0,0 +1,96 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Trace.h + * + * $Id: Trace.h 87823 2009-11-30 12:38:34Z johnnyw $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_TRACE_H +#define ACE_TRACE_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Trace + * + * @brief A C++ trace facility that keeps track of which methods are + * entered and exited. + * + * This class uses C++ constructors and destructors to automate + * the ACE_Trace nesting. In addition, thread-specific storage + * is used to enable multiple threads to work correctly. + */ +class ACE_Export ACE_Trace +{ +public: + // = Initialization and termination methods. + + /// Perform the first part of the trace, which prints out the string + /// N, the LINE, and the ACE_FILE as the function is entered. + ACE_Trace (const ACE_TCHAR *n, + int line = 0, + const ACE_TCHAR *file = ACE_TEXT ("")); + + /// Perform the second part of the trace, which prints out the NAME + /// as the function is exited. + ~ACE_Trace (void); + + // = Control the tracing level. + /// Determine if tracing is enabled or not + static bool is_tracing(void); + + /// Enable the tracing facility. + static void start_tracing (void); + + /// Disable the tracing facility. + static void stop_tracing (void); + + /// Change the nesting indentation level. + static void set_nesting_indent (int indent); + + /// Get the nesting indentation level. + static int get_nesting_indent (void); + + /// Dump the state of an object. + void dump (void) const; + +private: + // Keeps track of how deeply the call stack is nested (this is + // maintained in thread-specific storage to ensure correctness in + // multiple threads of control. + + /// Name of the method we are in. + const ACE_TCHAR *name_; + + /// Keeps track of how far to indent per trace call. + static int nesting_indent_; + + /// Is tracing enabled? + static bool enable_tracing_; + + /// Default values. + enum + { + DEFAULT_INDENT = 3, + DEFAULT_TRACING = 1 + }; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" + +#endif /* ACE_TRACE_H */ diff --git a/dep/acelite/ace/Truncate.h b/dep/acelite/ace/Truncate.h new file mode 100644 index 00000000000..223513a56d9 --- /dev/null +++ b/dep/acelite/ace/Truncate.h @@ -0,0 +1,517 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Truncate.h + * + * $Id: Truncate.h 83306 2008-10-17 12:19:53Z johnnyw $ + * + * @author Steve Huston + * @author Ossama Othman + * @author Russell Mora + */ +//============================================================================= + +#ifndef ACE_TRUNCATE_H +#define ACE_TRUNCATE_H + +#include /**/ "ace/pre.h" + +#include "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Global_Macros.h" +#include "ace/If_Then_Else.h" +#include "ace/Numeric_Limits.h" + +#if defined (ACE_LACKS_LONGLONG_T) +# include "ace/Basic_Types.h" +#endif /* ACE_LACKS_LONGLONG_T */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +namespace ACE_Utils +{ + template struct Sign_Check; + + // Specialize the unsigned signed cases. + template<> struct Sign_Check { ACE_STATIC_CONSTANT (bool, is_signed = 0); }; + template<> struct Sign_Check { ACE_STATIC_CONSTANT (bool, is_signed = 0); }; + template<> struct Sign_Check { ACE_STATIC_CONSTANT (bool, is_signed = 0); }; + template<> struct Sign_Check { ACE_STATIC_CONSTANT (bool, is_signed = 0); }; +#if !(defined(ACE_LACKS_LONGLONG_T) || defined(ACE_LACKS_UNSIGNEDLONGLONG_T)) +# ifdef __GNUC__ + // Silence g++ "-pedantic" warnings regarding use of "long long" + // type. + __extension__ +# endif /* __GNUC__ */ + template<> struct Sign_Check { ACE_STATIC_CONSTANT (bool, is_signed = 0); }; +#else + template<> struct Sign_Check { ACE_STATIC_CONSTANT (bool, is_signed = 0); }; +#endif /* !ACE_LACKS_LONGLONG_T */ + + // Specialize the signed cases. + template<> struct Sign_Check { ACE_STATIC_CONSTANT (bool, is_signed = 1); }; + template<> struct Sign_Check { ACE_STATIC_CONSTANT (bool, is_signed = 1); }; + template<> struct Sign_Check { ACE_STATIC_CONSTANT (bool, is_signed = 1); }; + template<> struct Sign_Check { ACE_STATIC_CONSTANT (bool, is_signed = 1); }; +#ifndef ACE_LACKS_LONGLONG_T +# ifdef __GNUC__ + // Silence g++ "-pedantic" warnings regarding use of "long long" + // type. + __extension__ +# endif /* __GNUC__ */ + template<> struct Sign_Check { ACE_STATIC_CONSTANT (bool, is_signed = 1); }; +#endif /* !ACE_LACKS_LONGLONG_T */ + + // ----------------------------------------------------- + + /** + * @struct To_Unsigned + * + * @brief Retrieve unsigned counterpart to given type or value. + * + * Retrieve unsigned counterpart to given type or value. + */ + template struct To_Unsigned; + + template<> + struct To_Unsigned + { + typedef unsigned char unsigned_type; + + unsigned_type operator() (unsigned_type x) { return x; } + }; + + template<> + struct To_Unsigned + { + typedef unsigned short unsigned_type; + + unsigned_type operator() (unsigned_type x) { return x; } + }; + + template<> + struct To_Unsigned + { + typedef unsigned int unsigned_type; + + unsigned_type operator() (unsigned_type x) { return x; } + }; + + template<> + struct To_Unsigned + { + typedef unsigned long unsigned_type; + + unsigned_type operator() (unsigned_type x) { return x; } + }; + +#if !(defined(ACE_LACKS_LONGLONG_T) || defined(ACE_LACKS_UNSIGNEDLONGLONG_T)) +# ifdef __GNUC__ + // Silence g++ "-pedantic" warnings regarding use of "long long" + // type. + __extension__ +# endif /* __GNUC__ */ + template<> + struct To_Unsigned + { + typedef unsigned long long unsigned_type; + + unsigned_type operator() (unsigned_type x) { return x; } + }; +#else + template<> + struct To_Unsigned + { + typedef ACE_U_LongLong unsigned_type; + + unsigned_type operator() (unsigned_type x) { return x; } + }; +#endif /* !ACE_LACKS_LONGLONG_T */ + + // ---------------- + + template<> + struct To_Unsigned + { + typedef signed char signed_type; + typedef unsigned char unsigned_type; + + unsigned_type operator() (signed_type x) + { + return static_cast (x); + } + }; + + template<> + struct To_Unsigned + { + typedef signed short signed_type; + typedef unsigned short unsigned_type; + + unsigned_type operator() (signed_type x) + { + return static_cast (x); + } + }; + + template<> + struct To_Unsigned + { + typedef signed int signed_type; + typedef unsigned int unsigned_type; + + unsigned_type operator() (signed_type x) + { + return static_cast (x); + } + }; + + template<> + struct To_Unsigned + { + typedef signed long signed_type; + typedef unsigned long unsigned_type; + + unsigned_type operator() (signed_type x) + { + return static_cast (x); + } + }; + +#if !(defined(ACE_LACKS_LONGLONG_T) || defined(ACE_LACKS_UNSIGNEDLONGLONG_T)) +# ifdef __GNUC__ + // Silence g++ "-pedantic" warnings regarding use of "long long" + // type. + __extension__ +# endif /* __GNUC__ */ + template<> + struct To_Unsigned + { + typedef signed long long signed_type; + typedef unsigned long long unsigned_type; + + unsigned_type operator() (signed_type x) + { + return static_cast (x); + } + }; +#endif /* !ACE_LACKS_LONGLONG_T */ + + // ----------------------------------------------------- + + /** + * @struct Safe_Comparator + * + * @brief Conservative comparison of types that may not be safely + * promoted and/or converted to each other. + * + * The comparison operations provided by this structure perform + * negative value checking when necessary to prevent wrap-around + * when explicitly casting to an unsigned type. + * + * @internal This structure is not meant for general use. + */ + template struct Safe_Comparator; + + // LEFT: signed, RIGHT: unsigned + template + struct Safe_Comparator + { + static bool greater_than (LEFT lhs, RIGHT rhs) + { + // Prevent wrap-around when casting to unsigned. + if (lhs < 0) + return false; // since rhs is always positive + else + { + // Implicit promotion of unsigned LEFT and RIGHT types here. + return To_Unsigned() (lhs) > rhs; + } + } + }; + + // LEFT: unsigned, RIGHT: signed + template + struct Safe_Comparator + { + static bool greater_than (LEFT lhs, RIGHT rhs) + { + // Prevent wrap-around when casting to unsigned. + if (rhs < 0) + return true; // since lhs is always positive + else + { + // Implicit promotion of unsigned LEFT and RIGHT types here. + return lhs > To_Unsigned() (rhs); + } + } + }; + + // LEFT: unsigned, RIGHT: unsigned + template + struct Safe_Comparator + { + static bool greater_than (LEFT lhs, RIGHT rhs) + { + // Implicit promotion of unsigned LEFT and RIGHT types here. + return lhs > rhs; + } + }; + + // LEFT: signed, RIGHT: signed + template + struct Safe_Comparator + { + static bool greater_than (LEFT lhs, RIGHT rhs) + { + // Implicit promotion of signed LEFT and RIGHT types here. + return lhs > rhs; + } + }; + + // ----------------------------------------------------- + + /** + * @struct Fast_Comparator + * + * @brief Quick comparison of types that can be safely promoted + * and/or converted to each other. + * + * The comparison operations provided by this structure perform no + * negative value checking, meaning it is not applicable to all + * types. Check the value of the @c USABLE enumerator to determine + * if it applies to the types in question. + * + * @internal This structure is not meant for general use. + */ + template + struct Fast_Comparator + { + ACE_STATIC_CONSTANT ( + bool, + USE_LEFT = ((sizeof (LEFT) > sizeof (RIGHT) + && (Sign_Check::is_signed == 1 + || Sign_Check::is_signed == 0)) + + // The following is basically the case where LEFT + // and RIGHT are the same integral type. + || (sizeof (LEFT) == sizeof (RIGHT) + // Can't portably do + // Sign_Check::is_signed == + // Sign_Check::is_signed, + // i.e. comparison of anonymous enumerations, + // without triggering a compiler diagnostic + // so expand the comparison. + && ((Sign_Check::is_signed == 1 + && Sign_Check::is_signed == 1) + || (Sign_Check::is_signed == 0 + && Sign_Check::is_signed == 0))))); + + ACE_STATIC_CONSTANT ( + bool, + USE_RIGHT = (sizeof (RIGHT) > sizeof (LEFT) + && (Sign_Check::is_signed == 1 + || Sign_Check::is_signed == 0))); + + ACE_STATIC_CONSTANT (bool, USABLE = (USE_LEFT || USE_RIGHT)); + + typedef typename ACE::If_Then_Else< + USE_LEFT, + LEFT, + typename ACE::If_Then_Else< + USE_RIGHT, + RIGHT, + void>::result_type>::result_type promote_type; + + static bool greater_than (LEFT lhs, RIGHT rhs) + { + // The explicit cast is assumed to change the type of rhs without + // changing its value. + return + (static_cast (lhs) > static_cast (rhs)); + } + + }; + + // ----------------------------------------------------- + + /** + * @struct Comparator + * + * @brief Structure that provides optimal comparison operation for + * given types. + * + * The comparison operations provided by this structure are chosen + * at compile time based on the signs and sizes of types being + * compared. + * @par + * Comparisons of values with the same sign or those with types that + * can be promoted safely are done quickly, without any range + * checking. + * @par + * Comparisons of values of different types that cannot be safely + * promoted incur an additional check for a negative value to allow + * the compiler to perform the appropriate implicit unsigned type + * promotion. + * + * @note In general, the operations found in this structure should + * not be used to work around compiler diagnostics regarding + * comparison of signed and unsigned types. Verify that your + * types are correct before relying on those operations. + * + * @internal This structure is not meant for general use. + */ + template + struct Comparator + { + typedef typename ACE::If_Then_Else< + Fast_Comparator::USABLE, + Fast_Comparator, + Safe_Comparator::is_signed, + Sign_Check::is_signed> >::result_type comp_type; + }; + + // ----------------------------------------------------- + + /** + * @struct Truncator + * + * @brief Truncate value of type @c FROM to value of type @c TO. + * + * Truncate a value of type @c FROM to value of type @c TO, if the + * value is larger than the maximum of value of type @c TO. + */ + template + struct Truncator + { + ACE_STATIC_CONSTANT ( + bool, + // max FROM always greater than max TO + MAX_FROM_GT_MAX_TO = (sizeof(FROM) > sizeof (TO) + || (sizeof(FROM) == sizeof (TO) + && Sign_Check::is_signed == 0))); + + typedef typename ACE::If_Then_Else< + MAX_FROM_GT_MAX_TO, + FROM, + TO>::result_type comp_to_type; + + // Take advantage of knowledge that we're casting a positive value + // to a type large enough to hold it so that we can bypass + // negative value checks at compile-time. Otherwise fallback on + // the safer comparison. + typedef typename ACE::If_Then_Else< + MAX_FROM_GT_MAX_TO, + Fast_Comparator, + typename Comparator::comp_type>::result_type comparator; + + /// Truncate a value of type @c FROM to value of type @c TO, if + /// the value is larger than the maximum of value of type @c TO. + TO operator() (FROM val) + { + return + (comparator::greater_than (val, ACE_Numeric_Limits::max ()) + ? ACE_Numeric_Limits::max () + : static_cast (val)); + } + + }; + + // Partial specialization for the case where the types are the same. + // No truncation is necessary. + template + struct Truncator + { + T operator() (T val) + { + return val; + } + }; + + +#if defined (ACE_LACKS_LONGLONG_T) || defined (ACE_LACKS_UNSIGNEDLONGLONG_T) + // Partial specialization for the case where we're casting from + // ACE_U_LongLong to a smaller integer. We assume that we're always + // truncating from ACE_U_LongLong to a smaller type. The partial + // specialization above handles the case where both the FROM and TO + // types are ACE_U_LongLong. + template + struct Truncator + { + TO operator() (ACE_U_LongLong const & val) + { + // If val less than or equal to ACE_Numeric_Limits::max(), + // val.lo() must be less than or equal to + // ACE_Numeric_Limits::max (), as well. + return + (val > ACE_Numeric_Limits::max () + ? ACE_Numeric_Limits::max () + : static_cast (val.lo ())); + } + }; +#endif /* ACE_LACKS_LONGLONG_T || ACE_LACKS_UNSIGNEDLONGLONG_T */ + + // ----------------------------------------------------- + /** + * @struct Noop_Truncator + * + * @brief No-op truncation. + * + * This structure/functor performs no truncation since it assumes + * that @c sizeof(FROM) @c < @c sizeof(TO), meaning that + * @c numeric_limits::max() @c < @c numeric_limits::max(). + */ + template + struct Noop_Truncator + { + TO operator() (FROM val) + { + return static_cast (val); + } + }; + // ----------------------------------------------------- + + /** + * @class truncate_cast + * + * @brief Helper function to truncate an integral value to the + * maximum value of the given type. + * + * Very useful since ACE methods return @c int very often and + * the value's source is often a different-size integral + * type, such as @c size_t. This function hides the + * truncation logic and resolves compiler diagnostics. + * + * @internal Internal use only. + */ + template + inline TO truncate_cast (FROM val) + { + // If the size of FROM is less than the size of TO, "val" will + // never be greater than the maximum "TO" value, so there is no + // need to attempt to truncate. + typedef typename ACE::If_Then_Else< + (sizeof (FROM) < sizeof (TO)), + Noop_Truncator, + Truncator >::result_type truncator; + + return truncator() (val); + } + +} // namespace ACE_Utils + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" + +#endif /* ACE_TRUNCATE_H*/ diff --git a/dep/acelite/ace/Typed_SV_Message.cpp b/dep/acelite/ace/Typed_SV_Message.cpp new file mode 100644 index 00000000000..6be3d4c682a --- /dev/null +++ b/dep/acelite/ace/Typed_SV_Message.cpp @@ -0,0 +1,30 @@ +// $Id: Typed_SV_Message.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#ifndef ACE_TYPED_SV_MESSAGE_CPP +#define ACE_TYPED_SV_MESSAGE_CPP + +#include "ace/Typed_SV_Message.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (__ACE_INLINE__) +#include "ace/Typed_SV_Message.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Typed_SV_Message) + +template void +ACE_Typed_SV_Message::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Typed_SV_Message::dump"); +#endif /* ACE_HAS_DUMP */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_TYPED_SV_MESSAGE_CPP */ diff --git a/dep/acelite/ace/Typed_SV_Message.h b/dep/acelite/ace/Typed_SV_Message.h new file mode 100644 index 00000000000..b43258e01a3 --- /dev/null +++ b/dep/acelite/ace/Typed_SV_Message.h @@ -0,0 +1,107 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file Typed_SV_Message.h + * + * $Id: Typed_SV_Message.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Doug Schmidt + */ +//========================================================================== + + +#ifndef ACE_TYPED_SV_MESSAGE_H +#define ACE_TYPED_SV_MESSAGE_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Typed_SV_Message + * + * @brief Defines the header file for the C++ wrapper for System V + * message queues. + */ +template +class ACE_Typed_SV_Message +{ +public: + // = Initialization and termination methods. + ACE_Typed_SV_Message (long type = 0, + int length = sizeof (T), + int max_size = sizeof (T)); + ACE_Typed_SV_Message (const T &data, + long type = 0, + int length = sizeof (T), + int max_size = sizeof (T)); + ~ACE_Typed_SV_Message (void); + + /// Get the type of the message. + long type (void) const; + + /// Set the type of the message. + void type (long type); + + /// Get the length of the message. + int length (void) const; + + /// Set the length of the message. + void length (int l); + + /// Get the maximum size of the message. + int max_size (void) const; + + /// Set the maximum size of the message. + void max_size (int m); + + /// Get a pointer to the data in the message. + T &data (void); + + /// Set a pointer to the data in the message. + void data (const T &data); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + /// Type of message. + long type_; + + /// Length of this message. + int length_; + + /// Maximum length of any message. + int max_; + + /// Data stored in a message. + T data_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Typed_SV_Message.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Typed_SV_Message.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Typed_SV_Message.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" + +#endif /* ACE_TYPED_SV_MESSAGE_H */ diff --git a/dep/acelite/ace/Typed_SV_Message.inl b/dep/acelite/ace/Typed_SV_Message.inl new file mode 100644 index 00000000000..6d8ea702321 --- /dev/null +++ b/dep/acelite/ace/Typed_SV_Message.inl @@ -0,0 +1,96 @@ +// -*- C++ -*- +// +// $Id: Typed_SV_Message.inl 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/config-all.h" +#include "ace/Global_Macros.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template ACE_INLINE +ACE_Typed_SV_Message::ACE_Typed_SV_Message (long t, + int l, + int m) + : type_ (t) +{ + ACE_TRACE ("ACE_Typed_SV_Message::ACE_Typed_SV_Message"); + this->length (l); + this->max_size (m); +} + +template ACE_INLINE +ACE_Typed_SV_Message::ACE_Typed_SV_Message (const T &d, + long t, + int l, + int m) + : type_ (t), + data_ (d) +{ + ACE_TRACE ("ACE_Typed_SV_Message::ACE_Typed_SV_Message"); + this->length (l); + this->max_size (m); +} + +template ACE_INLINE +ACE_Typed_SV_Message::~ACE_Typed_SV_Message (void) +{ + ACE_TRACE ("ACE_Typed_SV_Message::~ACE_Typed_SV_Message"); +} + +template ACE_INLINE long +ACE_Typed_SV_Message::type (void) const +{ + ACE_TRACE ("ACE_Typed_SV_Message::type"); + return this->type_; +} + +template ACE_INLINE void +ACE_Typed_SV_Message::type (long t) +{ + ACE_TRACE ("ACE_Typed_SV_Message::type"); + this->type_ = t; +} + +template ACE_INLINE int +ACE_Typed_SV_Message::length (void) const +{ + ACE_TRACE ("ACE_Typed_SV_Message::length"); + return this->length_; +} + +template ACE_INLINE void +ACE_Typed_SV_Message::length (int len) +{ + ACE_TRACE ("ACE_Typed_SV_Message::length"); + this->length_ = len + (sizeof *this - (sizeof this->type_ + sizeof this->data_)); +} + +template ACE_INLINE int +ACE_Typed_SV_Message::max_size (void) const +{ + ACE_TRACE ("ACE_Typed_SV_Message::max_size"); + return this->max_; +} + +template ACE_INLINE void +ACE_Typed_SV_Message::max_size (int m) +{ + ACE_TRACE ("ACE_Typed_SV_Message::max_size"); + this->max_ = m + (sizeof *this - (sizeof this->type_ + sizeof this->data_)); +} + +template T & +ACE_Typed_SV_Message::data (void) +{ + ACE_TRACE ("ACE_Typed_SV_Message::data"); + return this->data_; +} + +template void +ACE_Typed_SV_Message::data (const T &d) +{ + ACE_TRACE ("ACE_Typed_SV_Message::data"); + this->data_ = d; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Typed_SV_Message_Queue.cpp b/dep/acelite/ace/Typed_SV_Message_Queue.cpp new file mode 100644 index 00000000000..0adb589e62b --- /dev/null +++ b/dep/acelite/ace/Typed_SV_Message_Queue.cpp @@ -0,0 +1,56 @@ +// $Id: Typed_SV_Message_Queue.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#ifndef ACE_TYPED_SV_MESSAGE_QUEUE_CPP +#define ACE_TYPED_SV_MESSAGE_QUEUE_CPP + +#include "ace/Typed_SV_Message.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Typed_SV_Message_Queue.h" +#include "ace/Log_Msg.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Typed_SV_Message_Queue.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Typed_SV_Message_Queue) + +template void +ACE_Typed_SV_Message_Queue::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Typed_SV_Message_Queue::dump"); +#endif /* ACE_HAS_DUMP */ +} + +template +ACE_Typed_SV_Message_Queue::ACE_Typed_SV_Message_Queue (void) +{ + ACE_TRACE ("ACE_Typed_SV_Message_Queue::ACE_Typed_SV_Message_Queue"); +} + +template +ACE_Typed_SV_Message_Queue::ACE_Typed_SV_Message_Queue (key_t external_id, + int create, + int perms) +{ + ACE_TRACE ("ACE_Typed_SV_Message_Queue::ACE_Typed_SV_Message_Queue"); + if (this->open (external_id, create, perms) == -1) + ACE_ERROR ((LM_ERROR, + "ACE_Typed_SV_Message_Queue::ACE_Typed_SV_Message_Queue")); +} + +template +ACE_Typed_SV_Message_Queue::~ACE_Typed_SV_Message_Queue (void) +{ + ACE_TRACE ("ACE_Typed_SV_Message_Queue::~ACE_Typed_SV_Message_Queue"); +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_TYPED_SV_MESSAGE_QUEUE_CPP */ diff --git a/dep/acelite/ace/Typed_SV_Message_Queue.h b/dep/acelite/ace/Typed_SV_Message_Queue.h new file mode 100644 index 00000000000..12c0e50921b --- /dev/null +++ b/dep/acelite/ace/Typed_SV_Message_Queue.h @@ -0,0 +1,92 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Typed_SV_Message_Queue.h + * + * $Id: Typed_SV_Message_Queue.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_TYPED_MESSAGE_QUEUE_H +#define ACE_TYPED_MESSAGE_QUEUE_H +#include /**/ "ace/pre.h" + +#include "ace/SV_Message_Queue.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Typed_SV_Message.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Typed_SV_Message_Queue + * + * @brief Defines the header file for the C++ wrapper facade for typed message queues. + */ +template +class ACE_Typed_SV_Message_Queue +{ +public: + enum + { + ACE_CREATE = IPC_CREAT, + ACE_OPEN = 0, + ACE_NOWAIT = IPC_NOWAIT + }; + + // = Initialization and termination operations. + ACE_Typed_SV_Message_Queue (void); + ACE_Typed_SV_Message_Queue (key_t external_id, + int create = ACE_OPEN, + int perms = ACE_DEFAULT_FILE_PERMS); + int open (key_t external_id, + int create = ACE_OPEN, + int perms = ACE_DEFAULT_FILE_PERMS); + int close (void); + int remove (void); + ~ACE_Typed_SV_Message_Queue (void); + + /// Send method. + int send (const ACE_Typed_SV_Message &mb, int mflags = 0); + + /// Recv method. + int recv (ACE_Typed_SV_Message &mb, int mflags = 0); + + /// Return the id of the underlying ACE_SV_Message_Queue. + int get_id (void) const; + + /// Control the underlying message queue. + int control (int option, void *arg = 0); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + ACE_SV_Message_Queue message_queue_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Typed_SV_Message_Queue.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Typed_SV_Message_Queue.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Typed_SV_Message_Queue.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" +#endif /* ACE_TYPED_MESSAGE_QUEUE_H */ diff --git a/dep/acelite/ace/Typed_SV_Message_Queue.inl b/dep/acelite/ace/Typed_SV_Message_Queue.inl new file mode 100644 index 00000000000..90539936e62 --- /dev/null +++ b/dep/acelite/ace/Typed_SV_Message_Queue.inl @@ -0,0 +1,80 @@ +// -*- C++ -*- +// +// $Id: Typed_SV_Message_Queue.inl 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/SV_Message_Queue.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template ACE_INLINE int +ACE_Typed_SV_Message_Queue::open (key_t external_id, + int create, + int perms) +{ + ACE_TRACE ("ACE_Typed_SV_Message_Queue::open"); + return this->message_queue_.open (external_id, create, perms); +} + +// What does it mean to close a message queue?! + +template ACE_INLINE int +ACE_Typed_SV_Message_Queue::close (void) +{ + ACE_TRACE ("ACE_Typed_SV_Message_Queue::close"); + return 1; +} + +template ACE_INLINE int +ACE_Typed_SV_Message_Queue::recv (ACE_Typed_SV_Message &mb, + int mflags) +{ + ACE_TRACE ("ACE_Typed_SV_Message_Queue::recv"); + + int length = + this->message_queue_.recv (reinterpret_cast (mb), + mb.max_size (), + mb.type (), + mflags); + if (length != -1) + mb.length (length); + + return length; +} + +template ACE_INLINE int +ACE_Typed_SV_Message_Queue::send (const ACE_Typed_SV_Message &mb, + int mflags) +{ + ACE_TRACE ("ACE_Typed_SV_Message_Queue::send"); + return + this->message_queue_.send ( + reinterpret_cast ( + const_cast &> (mb)), + mb.length (), + mflags); +} + +template ACE_INLINE int +ACE_Typed_SV_Message_Queue::remove (void) +{ + ACE_TRACE ("ACE_Typed_SV_Message_Queue::remove"); + + return this->message_queue_.remove (); +} + +template ACE_INLINE int +ACE_Typed_SV_Message_Queue::control (int option, + void *arg) +{ + ACE_TRACE ("ACE_Typed_SV_Message_Queue::control"); + + return this->message_queue_.control (option, arg); +} + +template ACE_INLINE int +ACE_Typed_SV_Message_Queue::get_id (void) const +{ + return this->message_queue_.get_id (); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/UNIX_Addr.cpp b/dep/acelite/ace/UNIX_Addr.cpp new file mode 100644 index 00000000000..013af8a33ec --- /dev/null +++ b/dep/acelite/ace/UNIX_Addr.cpp @@ -0,0 +1,151 @@ +// $Id: UNIX_Addr.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/UNIX_Addr.h" + +ACE_RCSID(ace, UNIX_Addr, "$Id: UNIX_Addr.cpp 80826 2008-03-04 14:51:23Z wotte $") + +#if !defined (ACE_LACKS_UNIX_DOMAIN_SOCKETS) + +#if !defined (__ACE_INLINE__) +#include "ace/UNIX_Addr.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_UNIX_Addr) + +// Set a pointer to the address. +void +ACE_UNIX_Addr::set_addr (void *addr, int len) +{ + ACE_TRACE ("ACE_UNIX_Addr::set_addr"); + + this->ACE_Addr::base_set (AF_UNIX, len); + ACE_OS::memcpy ((void *) &this->unix_addr_, + (void *) addr, + len); +} + +// Return a pointer to the underlying address. + +void * +ACE_UNIX_Addr::get_addr (void) const +{ + return (void *) &this->unix_addr_; +} + +// Transform the string into the current addressing format. + +int +ACE_UNIX_Addr::string_to_addr (const char addr[]) +{ + ACE_OS::strsncpy (this->unix_addr_.sun_path, addr, + sizeof this->unix_addr_.sun_path); + return 0; +} + +// Transform the current address into string format. + +int +ACE_UNIX_Addr::addr_to_string (ACE_TCHAR s[], size_t len) const +{ + ACE_OS::strsncpy (s, + ACE_TEXT_CHAR_TO_TCHAR (this->unix_addr_.sun_path), + len); + return 0; +} + +u_long +ACE_UNIX_Addr::hash (void) const +{ + return ACE::hash_pjw (this->unix_addr_.sun_path); +} + +void +ACE_UNIX_Addr::dump (void) const +{ +#if defined (ACE_HAS_DUMP) +#endif /* ACE_HAS_DUMP */ +} + +// Do nothing constructor. + +ACE_UNIX_Addr::ACE_UNIX_Addr (void) + : ACE_Addr (AF_UNIX, sizeof this->unix_addr_) +{ + (void) ACE_OS::memset ((void *) &this->unix_addr_, + 0, + sizeof this->unix_addr_); + + this->unix_addr_.sun_family = AF_UNIX; +} + +int +ACE_UNIX_Addr::set (const ACE_UNIX_Addr &sa) +{ + if (sa.get_type () == AF_ANY) + (void) ACE_OS::memset ((void *) &this->unix_addr_, + 0, + sizeof this->unix_addr_); + else + ACE_OS::strcpy (this->unix_addr_.sun_path, + sa.unix_addr_.sun_path); + + this->unix_addr_.sun_family = AF_UNIX; + this->base_set (sa.get_type (), sa.get_size ()); + + return 0; +} + +// Copy constructor. + +ACE_UNIX_Addr::ACE_UNIX_Addr (const ACE_UNIX_Addr &sa) + : ACE_Addr (AF_UNIX, sa.get_size ()) +{ + this->set (sa); +} + +int +ACE_UNIX_Addr::set (const sockaddr_un *un, int len) +{ + (void) ACE_OS::memset ((void *) &this->unix_addr_, 0, + sizeof this->unix_addr_); + this->unix_addr_.sun_family = AF_UNIX; + ACE_OS::strcpy (this->unix_addr_.sun_path, un->sun_path); + this->base_set (AF_UNIX, len); + return 0; +} + +ACE_UNIX_Addr::ACE_UNIX_Addr (const sockaddr_un *un, int len) +{ + this->set (un, len); +} + +int +ACE_UNIX_Addr::set (const char rendezvous_point[]) +{ + (void) ACE_OS::memset ((void *) &this->unix_addr_, + 0, + sizeof this->unix_addr_); + this->unix_addr_.sun_family = AF_UNIX; + (void) ACE_OS::strsncpy (this->unix_addr_.sun_path, + rendezvous_point, + sizeof this->unix_addr_.sun_path); + + this->ACE_Addr::base_set (AF_UNIX, + sizeof this->unix_addr_ - + sizeof (this->unix_addr_.sun_path) + + ACE_OS::strlen (this->unix_addr_.sun_path)); + return 0; +} + +// Create a ACE_Addr from a UNIX pathname. + +ACE_UNIX_Addr::ACE_UNIX_Addr (const char rendezvous_point[]) +{ + this->set (rendezvous_point); +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_LACKS_UNIX_DOMAIN_SOCKETS */ diff --git a/dep/acelite/ace/UNIX_Addr.h b/dep/acelite/ace/UNIX_Addr.h new file mode 100644 index 00000000000..887529fe152 --- /dev/null +++ b/dep/acelite/ace/UNIX_Addr.h @@ -0,0 +1,117 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file UNIX_Addr.h + * + * $Id: UNIX_Addr.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Doug Schmidt + */ +//============================================================================= + + +#ifndef ACE_UNIX_ADDR_H +#define ACE_UNIX_ADDR_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_UNIX_DOMAIN_SOCKETS) + +#include "ace/Addr.h" +#include "ace/Log_Msg.h" +#include "ace/ACE.h" +#include "ace/os_include/sys/os_un.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_UNIX_Addr + * + * @brief Defines the ``UNIX domain address family'' address format. + */ +class ACE_Export ACE_UNIX_Addr : public ACE_Addr +{ +public: + // = Initialization methods. + /// Default constructor. + ACE_UNIX_Addr (void); + + /// Copy constructor. + ACE_UNIX_Addr (const ACE_UNIX_Addr &sa); + + /// Creates an ACE_UNIX_Addr from a string. + ACE_UNIX_Addr (const char rendezvous_point[]); + + /// Creates an ACE_INET_Addr from a sockaddr_un structure. + ACE_UNIX_Addr (const sockaddr_un *, int len); + + /// Creates an ACE_UNIX_Addr from another ACE_UNIX_Addr. + int set (const ACE_UNIX_Addr &sa); + + /// Creates an ACE_UNIX_Addr from a string. + int set (const char rendezvous_point[]); + + /// Creates an ACE_UNIX_Addr from a sockaddr_un structure. + int set (const sockaddr_un *, int len); + + /// Return a pointer to the underlying network address. + virtual void *get_addr (void) const; + + /// Set a pointer to the underlying network address. + virtual void set_addr (void *addr, int len); + + /// Transform the current address into string format. + virtual int addr_to_string (ACE_TCHAR addr[], size_t) const; + + /// Transform the string into the current addressing format. + virtual int string_to_addr (const char addr[]); + +#if defined (ACE_HAS_WCHAR) + /// Creates an ACE_UNIX_Addr from a string. + ACE_UNIX_Addr (const wchar_t rendezvous_point[]); + + /// Creates an ACE_UNIX_Addr from a string. + int set (const wchar_t rendezvous_point[]); +#endif /* ACE_HAS_WCHAR */ + + /// Compare two addresses for equality. + bool operator == (const ACE_UNIX_Addr &SAP) const; + + /// Compare two addresses for inequality. + bool operator != (const ACE_UNIX_Addr &SAP) const; + + /// Return the path name of the underlying rendezvous point. + const char *get_path_name (void) const; + + /// Computes and returns hash value. + virtual u_long hash (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + /// Underlying socket address. + sockaddr_un unix_addr_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/UNIX_Addr.inl" +#endif /* __ACE_INLINE__ */ + +#endif /* ACE_LACKS_UNIX_DOMAIN_SOCKETS */ + +#include /**/ "ace/post.h" + +#endif /* ACE_UNIX_ADDR_H */ diff --git a/dep/acelite/ace/UNIX_Addr.inl b/dep/acelite/ace/UNIX_Addr.inl new file mode 100644 index 00000000000..5e801b56fea --- /dev/null +++ b/dep/acelite/ace/UNIX_Addr.inl @@ -0,0 +1,57 @@ +// -*- C++ -*- +// +// $Id: UNIX_Addr.inl 80826 2008-03-04 14:51:23Z wotte $ + + +#include "ace/OS_NS_string.h" + + +#if !defined (ACE_LACKS_UNIX_DOMAIN_SOCKETS) + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +#if defined (ACE_HAS_WCHAR) +/// Creates an ACE_UNIX_Addr from a string. +ACE_INLINE +ACE_UNIX_Addr::ACE_UNIX_Addr (const wchar_t rendezvous_point[]) +{ + this->set (ACE_Wide_To_Ascii (rendezvous_point).char_rep ()); +} + +/// Creates an ACE_UNIX_Addr from a string. +ACE_INLINE int +ACE_UNIX_Addr::set (const wchar_t rendezvous_point[]) +{ + return this->set (ACE_Wide_To_Ascii (rendezvous_point).char_rep ()); +} +#endif /* ACE_HAS_WCHAR */ + +// Compare two addresses for equality. + +ACE_INLINE bool +ACE_UNIX_Addr::operator == (const ACE_UNIX_Addr &sap) const +{ + return ACE_OS::strncmp (this->unix_addr_.sun_path, + sap.unix_addr_.sun_path, + sizeof this->unix_addr_.sun_path) == 0; +} + +// Compare two addresses for inequality. + +ACE_INLINE bool +ACE_UNIX_Addr::operator != (const ACE_UNIX_Addr &sap) const +{ + return !((*this) == sap); // This is lazy, of course... ;-) +} + +// Return the path name used for the rendezvous point. + +ACE_INLINE const char * +ACE_UNIX_Addr::get_path_name (void) const +{ + return this->unix_addr_.sun_path; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_LACKS_UNIX_DOMAIN_SOCKETS */ diff --git a/dep/acelite/ace/UPIPE_Acceptor.cpp b/dep/acelite/ace/UPIPE_Acceptor.cpp new file mode 100644 index 00000000000..c2c10155c35 --- /dev/null +++ b/dep/acelite/ace/UPIPE_Acceptor.cpp @@ -0,0 +1,129 @@ +// $Id: UPIPE_Acceptor.cpp 82723 2008-09-16 09:35:44Z johnnyw $ + +#include "ace/UPIPE_Acceptor.h" + +ACE_RCSID(ace, UPIPE_Acceptor, "$Id: UPIPE_Acceptor.cpp 82723 2008-09-16 09:35:44Z johnnyw $") + +#if defined (ACE_HAS_THREADS) + +#include "ace/OS_NS_unistd.h" + +#if !defined (__ACE_INLINE__) +#include "ace/UPIPE_Acceptor.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_UPIPE_Acceptor) + +void +ACE_UPIPE_Acceptor::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_UPIPE_Acceptor::dump"); +#endif /* ACE_HAS_DUMP */ +} + +/* Do nothing routine for constructor. */ + +ACE_UPIPE_Acceptor::ACE_UPIPE_Acceptor (void) + : mb_ (sizeof (ACE_UPIPE_Stream *)) +{ + ACE_TRACE ("ACE_UPIPE_Acceptor::ACE_UPIPE_Acceptor"); +} + +ACE_UPIPE_Acceptor::~ACE_UPIPE_Acceptor (void) +{ + ACE_TRACE ("ACE_UPIPE_Acceptor::~ACE_UPIPE_Acceptor"); +} + +// General purpose routine for performing server ACE_UPIPE. + +int +ACE_UPIPE_Acceptor::open (const ACE_UPIPE_Addr &local_addr, + int reuse_addr) +{ + ACE_TRACE ("ACE_UPIPE_Acceptor::open"); + return this->ACE_SPIPE_Acceptor::open (local_addr, reuse_addr); +} + +int +ACE_UPIPE_Acceptor::close (void) +{ + ACE_TRACE ("ACE_UPIPE_Acceptor::close"); + return this->ACE_SPIPE_Acceptor::close (); +} + +// General purpose routine for accepting new connections. + +ACE_UPIPE_Acceptor::ACE_UPIPE_Acceptor (const ACE_UPIPE_Addr &local_addr, + int reuse_addr) + : mb_ (sizeof (ACE_UPIPE_Stream *)) +{ + ACE_TRACE ("ACE_UPIPE_Acceptor::ACE_UPIPE_Acceptor"); + + if (this->open (local_addr, reuse_addr) == -1) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_UPIPE_Acceptor"))); +} + +int +ACE_UPIPE_Acceptor::accept (ACE_UPIPE_Stream &new_stream, + ACE_UPIPE_Addr *remote_addr, + ACE_Time_Value *timeout, + bool restart, + bool reset_new_handle) +{ + ACE_TRACE ("ACE_UPIPE_Acceptor::accept"); + ACE_UNUSED_ARG (reset_new_handle); + + ACE_SPIPE_Stream new_io; + + if (this->ACE_SPIPE_Acceptor::accept (new_io, remote_addr, + timeout, restart) == -1) + return -1; + else + { + ACE_UPIPE_Stream *remote_stream = 0; + + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, new_stream.lock_, -1)); + + new_stream.set_handle (new_io.get_handle ()); + new_stream.reference_count_++; + + // Transfer address ownership. + new_io.get_local_addr (new_stream.local_addr_); + new_io.get_remote_addr (new_stream.remote_addr_); + + // Now that we got the handle, we'll read the address of the + // connector-side ACE_UPIPE_Stream out of the pipe and link that + // ACE_UPIPE_Stream to our ACE_UPIPE_Stream. + + if (ACE_OS::read (new_stream.get_handle (), + (char *) &remote_stream, + sizeof remote_stream) == -1) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("ACE_UPIPE_Acceptor: %p\n"), + ACE_TEXT ("read stream address failed"))); + else if (new_stream.stream_.link (remote_stream->stream_) == -1) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("ACE_UPIPE_Acceptor: %p\n"), + ACE_TEXT ("link streams failed"))); + // Send a message over the new streampipe to confirm acceptance. + else if (new_stream.send (&mb_, 0) == -1) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("ACE_UPIPE_Acceptor: %p\n"), + ACE_TEXT ("linked stream.put failed"))); + + // Close down the new_stream at this point in order to conserve + // handles. Note that we don't need the SPIPE connection + // anymore since we're now linked via the . + new_stream.ACE_SPIPE::close (); + return 0; + } +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_THREADS */ diff --git a/dep/acelite/ace/UPIPE_Acceptor.h b/dep/acelite/ace/UPIPE_Acceptor.h new file mode 100644 index 00000000000..e4925a045a2 --- /dev/null +++ b/dep/acelite/ace/UPIPE_Acceptor.h @@ -0,0 +1,99 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file UPIPE_Acceptor.h + * + * $Id: UPIPE_Acceptor.h 82723 2008-09-16 09:35:44Z johnnyw $ + * + * @author Gerhard Lenzer + * @author Douglas C. Schmidt + */ +//============================================================================= + + +#ifndef ACE_UPIPE_ACCEPTOR_H +#define ACE_UPIPE_ACCEPTOR_H +#include /**/ "ace/pre.h" + +#include "ace/UPIPE_Stream.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_THREADS) + +#include "ace/SPIPE_Acceptor.h" +#include "ace/Thread_Manager.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_UPIPE_Acceptor + * + * @brief Defines the format and interface for the listener side of the + * ACE_UPIPE_Stream. + */ +class ACE_Export ACE_UPIPE_Acceptor : public ACE_SPIPE_Acceptor +{ +public: + // = Initialization and termination. + /// Default constructor. + ACE_UPIPE_Acceptor (void); + + /// Initialize passive endpoint. + ACE_UPIPE_Acceptor (const ACE_UPIPE_Addr &local_sap, + int reuse_addr = 0); + + /// Initialize passive endpoint. + int open (const ACE_UPIPE_Addr &local_sap, + int reuse_addr = 0); + + /// Close down and release resources. + ~ACE_UPIPE_Acceptor (void); + + /// Close down and release resources. + int close (void); + + /// Close down and release resources and remove the underlying SPIPE + /// rendezvous point. + int remove (void); + + // = Passive connection acceptance method. + /** + * Accept a new data transfer connection. A @a timeout of 0 means + * block forever, a @a timeout of {0, 0} means poll. @a restart == 1 + * means "restart if interrupted." + */ + int accept (ACE_UPIPE_Stream &server_stream, + ACE_UPIPE_Addr *remote_addr = 0, + ACE_Time_Value *timeout = 0, + bool restart = true, + bool reset_new_handle = false); + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + /// Manage threads. + ACE_Thread_Manager tm; + + /// To confirm connection establishment. + ACE_Message_Block mb_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/UPIPE_Acceptor.inl" +#endif /* __ACE_INLINE__ */ + +#endif /* ACE_HAS_THREADS */ + +#include /**/ "ace/post.h" + +#endif /* ACE_UPIPE_ACCEPTOR_H */ diff --git a/dep/acelite/ace/UPIPE_Acceptor.inl b/dep/acelite/ace/UPIPE_Acceptor.inl new file mode 100644 index 00000000000..9432ad7bb88 --- /dev/null +++ b/dep/acelite/ace/UPIPE_Acceptor.inl @@ -0,0 +1,14 @@ +// -*- C++ -*- +// +// $Id: UPIPE_Acceptor.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE int +ACE_UPIPE_Acceptor::remove (void) +{ + ACE_TRACE ("ACE_UPIPE_Acceptor::remove"); + return this->ACE_SPIPE_Acceptor::remove (); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/UPIPE_Addr.h b/dep/acelite/ace/UPIPE_Addr.h new file mode 100644 index 00000000000..aaf33b683fa --- /dev/null +++ b/dep/acelite/ace/UPIPE_Addr.h @@ -0,0 +1,33 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file UPIPE_Addr.h + * + * $Id: UPIPE_Addr.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Doug Schmidt + */ +//============================================================================= + + +#ifndef ACE_UPIPE_ADDR_H +#define ACE_UPIPE_ADDR_H + +#include /**/ "ace/pre.h" + +#include "ace/SPIPE_Addr.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +typedef ACE_SPIPE_Addr ACE_UPIPE_Addr; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#include /**/ "ace/post.h" + +#endif /* ACE_UPIPE_ADDR_H */ diff --git a/dep/acelite/ace/UPIPE_Connector.cpp b/dep/acelite/ace/UPIPE_Connector.cpp new file mode 100644 index 00000000000..9b9bfcd3878 --- /dev/null +++ b/dep/acelite/ace/UPIPE_Connector.cpp @@ -0,0 +1,101 @@ +// $Id: UPIPE_Connector.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/UPIPE_Connector.h" + +ACE_RCSID(ace, UPIPE_Connector, "$Id: UPIPE_Connector.cpp 80826 2008-03-04 14:51:23Z wotte $") + +#if defined (ACE_HAS_THREADS) + +#include "ace/Handle_Ops.h" +#include "ace/OS_NS_unistd.h" +#include "ace/OS_NS_stropts.h" + +#if !defined (__ACE_INLINE__) +#include "ace/UPIPE_Connector.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_UPIPE_Connector) + +void +ACE_UPIPE_Connector::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_UPIPE_Connector::dump"); +#endif /* ACE_HAS_DUMP */ +} + +ACE_UPIPE_Connector::ACE_UPIPE_Connector (void) +{ + ACE_TRACE ("ACE_UPIPE_Connector::ACE_UPIPE_Connector"); +} + +int +ACE_UPIPE_Connector::connect (ACE_UPIPE_Stream &new_stream, + const ACE_UPIPE_Addr &addr, + ACE_Time_Value *timeout, + const ACE_Addr & /* local_sap */, + int /* reuse_addr */, + int flags, + int perms) +{ + ACE_TRACE ("ACE_UPIPE_Connector::connect"); + ACE_ASSERT (new_stream.get_handle () == ACE_INVALID_HANDLE); + + ACE_HANDLE handle = ACE::handle_timed_open (timeout, + addr.get_path_name (), + flags, perms); + + if (handle == ACE_INVALID_HANDLE) + return -1; +#if !defined (ACE_WIN32) + else if (ACE_OS::isastream (handle) != 1) + return -1; +#endif + else // We're connected! + { + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, new_stream.lock_, -1)); + + ACE_UPIPE_Stream *ustream = &new_stream; + + new_stream.set_handle (handle); + new_stream.remote_addr_ = addr; // class copy. + new_stream.reference_count_++; + + // Now send the address of our ACE_UPIPE_Stream over this pipe + // to our corresponding ACE_UPIPE_Acceptor, so he may link the + // two streams. + ssize_t result = ACE_OS::write (handle, + (const char *) &ustream, + sizeof ustream); + if (result == -1) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("ACE_UPIPE_Connector %p\n"), + ACE_TEXT ("write to pipe failed"))); + + // Wait for confirmation of stream linking. + ACE_Message_Block *mb_p = 0; + + // Our part is done, wait for server to confirm connection. + result = new_stream.recv (mb_p, 0); + + // Do *not* coalesce the following two checks for result == -1. + // They perform different checks and cannot be merged. + if (result == -1) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("ACE_UPIPE_Connector %p\n"), + ACE_TEXT ("no confirmation from server"))); + else + // Close down the new_stream at this point in order to + // conserve handles. Note that we don't need the SPIPE + // connection anymore since we're linked via the Message_Queue + // now. + new_stream.ACE_SPIPE::close (); + return static_cast (result); + } +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_THREADS */ diff --git a/dep/acelite/ace/UPIPE_Connector.h b/dep/acelite/ace/UPIPE_Connector.h new file mode 100644 index 00000000000..b2ad1787aaf --- /dev/null +++ b/dep/acelite/ace/UPIPE_Connector.h @@ -0,0 +1,115 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file UPIPE_Connector.h + * + * $Id: UPIPE_Connector.h 82723 2008-09-16 09:35:44Z johnnyw $ + * + * @author Gerhard Lenzer and Douglas C. Schmidt + */ +//============================================================================= + + +#ifndef ACE_UPIPE_CONNECTOR_H +#define ACE_UPIPE_CONNECTOR_H +#include /**/ "ace/pre.h" + +#include "ace/UPIPE_Stream.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_THREADS) + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_UPIPE_Connector + * + * @brief Defines an active connection factory for the + * ACE_UPIPE_STREAM wrappers. + */ +class ACE_Export ACE_UPIPE_Connector +{ +public: + // = Initialization methods. + /// Default constructor. + ACE_UPIPE_Connector (void); + + /** + * Actively connect and produce a @a new_stream if things go well. + * The @a addr is the address that we are trying to connect + * with. The @a timeout is the amount of time to wait to connect. + * If it's 0 then we block indefinitely. If *timeout == {0, 0} then + * the connection is done using non-blocking mode. In this case, if + * the connection can't be made immediately the value of -1 is + * returned with @c errno == EWOULDBLOCK. If *timeout > {0, 0} then + * this is the maximum amount of time to wait before timing out. If the + * time expires before the connection is made @c errno == ETIME. The + * @a local_sap is the value of local address to bind to. If it's + * the default value of ACE_Addr::sap_any then the user is letting + * the OS do the binding. If @a reuse_addr == 1 then the + * @a local_addr is reused, even if it hasn't been cleanedup yet. + * The @a flags and @a perms arguments are passed down to the open() + * method. + */ + ACE_UPIPE_Connector (ACE_UPIPE_Stream &new_stream, + const ACE_UPIPE_Addr &addr, + ACE_Time_Value *timeout = 0, + const ACE_Addr &local_sap = ACE_Addr::sap_any, + int reuse_addr = 0, + int flags = O_RDWR, + int perms = 0); + + /** + * Actively connect and produce a @a new_stream if things go well. + * The @a addr is the address that we are trying to connect + * with. The @a timeout is the amount of time to wait to connect. + * If it's 0 then we block indefinitely. If *timeout == {0, 0} then + * the connection is done using non-blocking mode. In this case, if + * the connection can't be made immediately the value of -1 is + * returned with @c errno == EWOULDBLOCK. If *timeout > {0, 0} then + * this is the maximum amount of time to wait before timing out. If the + * time expires before the connection is made @c errno == ETIME. The + * @a local_sap is the value of local address to bind to. If it's + * the default value of ACE_Addr::sap_any then the user is letting + * the OS do the binding. If @a reuse_addr == 1 then the + * @a local_addr is reused, even if it hasn't been cleanedup yet. + * The @a flags and @a perms arguments are passed down to the open() + * method. + */ + int connect (ACE_UPIPE_Stream &new_stream, + const ACE_UPIPE_Addr &addr, + ACE_Time_Value *timeout = 0, + const ACE_Addr &local_sap = ACE_Addr::sap_any, + int reuse_addr = 0, + int flags = O_RDWR, + int perms = 0); + + /// Resets any event associations on this handle + bool reset_new_handle (ACE_HANDLE handle); + + // = Meta-type info + typedef ACE_UPIPE_Addr PEER_ADDR; + typedef ACE_UPIPE_Stream PEER_STREAM; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/UPIPE_Connector.inl" +#endif /* __ACE_INLINE__ */ + +#endif /* ACE_HAS_THREADS */ + +#include /**/ "ace/post.h" + +#endif /* ACE_UPIPE_CONNECTOR_H */ diff --git a/dep/acelite/ace/UPIPE_Connector.inl b/dep/acelite/ace/UPIPE_Connector.inl new file mode 100644 index 00000000000..07b7502cce0 --- /dev/null +++ b/dep/acelite/ace/UPIPE_Connector.inl @@ -0,0 +1,34 @@ +// -*- C++ -*- +// +// $Id: UPIPE_Connector.inl 82723 2008-09-16 09:35:44Z johnnyw $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Creates a Local ACE_UPIPE. +ACE_INLINE +ACE_UPIPE_Connector::ACE_UPIPE_Connector (ACE_UPIPE_Stream &new_stream, + const ACE_UPIPE_Addr &addr, + ACE_Time_Value *timeout, + const ACE_Addr &local_sap, + int reuse_addr, + int flags, + int perms) +{ + ACE_TRACE ("ACE_UPIPE_Connector::ACE_UPIPE_Connector"); + if (this->connect (new_stream, addr, timeout, local_sap, + reuse_addr, flags, perms) == -1 + && timeout != 0 && !(errno == EWOULDBLOCK || errno == ETIME)) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("address %s, %p\n"), + addr.get_path_name (), + ACE_TEXT ("ACE_UPIPE_Connector"))); +} + +ACE_INLINE bool +ACE_UPIPE_Connector::reset_new_handle (ACE_HANDLE /* handle */) +{ + // Nothing to do here since the handle is not a socket + return false; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/UPIPE_Stream.cpp b/dep/acelite/ace/UPIPE_Stream.cpp new file mode 100644 index 00000000000..d07722a482e --- /dev/null +++ b/dep/acelite/ace/UPIPE_Stream.cpp @@ -0,0 +1,234 @@ +// $Id: UPIPE_Stream.cpp 82559 2008-08-07 20:23:07Z parsons $ + +#include "ace/UPIPE_Stream.h" + +ACE_RCSID(ace, UPIPE_Stream, "$Id: UPIPE_Stream.cpp 82559 2008-08-07 20:23:07Z parsons $") + +#if defined (ACE_HAS_THREADS) + +#include "ace/OS_NS_string.h" + +#if !defined (__ACE_INLINE__) +#include "ace/UPIPE_Stream.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_UPIPE_Stream) + +ACE_UPIPE_Stream::ACE_UPIPE_Stream (void) + : mb_last_ (0), + reference_count_ (0) +{ + ACE_TRACE ("ACE_UPIPE_Stream::ACE_UPIPE_STREAM"); +} + +ACE_UPIPE_Stream::~ACE_UPIPE_Stream (void) +{ + if (this->mb_last_ != 0) + { + this->mb_last_->release (); + this->mb_last_ = 0; + } +} + +int +ACE_UPIPE_Stream::control (int cmd, + void * val) const +{ + ACE_TRACE ("ACE_UPIPE_Stream::control"); + + return ((ACE_UPIPE_Stream *) this)->stream_.control + ((ACE_IO_Cntl_Msg::ACE_IO_Cntl_Cmds) cmd, val); +} + +void +ACE_UPIPE_Stream::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_UPIPE_Stream::dump"); +#endif /* ACE_HAS_DUMP */ +} + +int +ACE_UPIPE_Stream::close (void) +{ + ACE_TRACE ("ACE_UPIPE_Stream::close"); + ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); + + this->reference_count_--; + + if (this->reference_count_ == 0) + { + // Since the UPIPE should have been closed earlier we won't bother + // checking to see if closing it now fails. + + if (this->ACE_SPIPE::get_handle () != ACE_INVALID_HANDLE) + this->ACE_SPIPE::close (); + + // Close down the ACE_stream. + return this->stream_.close (); + } + return 0; +} + +int +ACE_UPIPE_Stream::get_remote_addr (ACE_UPIPE_Addr &remote_sap) const +{ + ACE_TRACE ("ACE_UPIPE_Stream::get_remote_addr"); + remote_sap = this->remote_addr_; + return 0; +} + +int +ACE_UPIPE_Stream::send (ACE_Message_Block *mb_p, + ACE_Time_Value *timeout) +{ + ACE_TRACE ("ACE_UPIPE_Stream::send_msg"); + return this->stream_.put (mb_p, timeout) == -1 ? -1 : 0; +} + +int ACE_UPIPE_Stream::recv (ACE_Message_Block *& mb_p, + ACE_Time_Value *timeout) +{ + return this->stream_.get (mb_p, timeout) == -1 ? -1 : 0; +} + +// Send a buffer. + +ssize_t +ACE_UPIPE_Stream::send (const char *buffer, + size_t n, + ACE_Time_Value *timeout) +{ + ACE_TRACE ("ACE_UPIPE_Stream::send"); + + ACE_Message_Block *mb_p; + ACE_NEW_RETURN (mb_p, + ACE_Message_Block (n), + -1); + mb_p->copy (buffer, n); + return + this->stream_.put (mb_p, timeout) == -1 + ? -1 + : static_cast (n); +} + +// Receive a buffer. + +ssize_t +ACE_UPIPE_Stream::recv (char *buffer, + size_t n, + ACE_Time_Value *timeout) +{ + ACE_TRACE ("ACE_UPIPE_Stream::recv"); + // Index in buffer. + size_t bytes_read = 0; + + while (bytes_read < n) + if (this->mb_last_ != 0) + { + // We have remaining data in our last read Message_Buffer. + size_t this_len = this->mb_last_->length (); + if (this_len < n) + { + // The remaining data is not enough. + + ACE_OS::memcpy ((void *) &buffer[bytes_read], + this->mb_last_->rd_ptr (), + this_len); + bytes_read += this_len; + this->mb_last_ = this->mb_last_->release (); // mb_last_ now 0 + return static_cast (bytes_read); + } + else + { + // The remaining data is at least enough. If there's + // more, we'll get it the next time through. + ACE_OS::memcpy (&buffer[bytes_read], + this->mb_last_->rd_ptr (), + n); + bytes_read += n; + + // Advance rd_ptr. + this->mb_last_->rd_ptr (n); + + if (this->mb_last_->length () == 0) + // Now the Message_Buffer is empty. + this->mb_last_ = this->mb_last_->release (); + } + } + else + { + // We have to get a new Message_Buffer from our stream. + int result = this->stream_.get (this->mb_last_, timeout); + + if (result == -1) + { + if (errno == EWOULDBLOCK && bytes_read > 0) + // Return the number of bytes read before we timed out. + return static_cast (bytes_read); + else + return -1; + } + } + + return static_cast (bytes_read); +} + +ssize_t +ACE_UPIPE_Stream::send_n (const char *buf, + size_t n, + ACE_Time_Value *timeout) +{ + ACE_TRACE ("ACE_UPIPE_Stream::send_n"); + + size_t bytes_written; + ssize_t len = 0; + + for (bytes_written = 0; bytes_written < n; bytes_written += len) + { + len = this->send (buf + bytes_written, + n - bytes_written, + timeout); + + if (len == -1) + { + return -1; + } + } + + return static_cast (bytes_written); +} + +ssize_t +ACE_UPIPE_Stream::recv_n (char *buf, + size_t n, + ACE_Time_Value *timeout) +{ + ACE_TRACE ("ACE_UPIPE_Stream::recv_n"); + size_t bytes_read; + ssize_t len = 0; + + for (bytes_read = 0; bytes_read < n; bytes_read += len) + { + len = this->recv (buf + bytes_read, + n - bytes_read, + timeout); + + if (len == -1) + { + return -1; + } + else if (len == 0) + { + break; + } + } + + return static_cast< ssize_t> (bytes_read); +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_THREADS */ diff --git a/dep/acelite/ace/UPIPE_Stream.h b/dep/acelite/ace/UPIPE_Stream.h new file mode 100644 index 00000000000..b10aef11591 --- /dev/null +++ b/dep/acelite/ace/UPIPE_Stream.h @@ -0,0 +1,140 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file UPIPE_Stream.h + * + * $Id: UPIPE_Stream.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Gerhard Lenzer + * @author Douglas C. Schmidt + */ +//============================================================================= + + +#ifndef ACE_UPIPE_STREAM_H +#define ACE_UPIPE_STREAM_H +#include /**/ "ace/pre.h" + +#include "ace/Stream.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_THREADS) + +#include "ace/SPIPE.h" +#include "ace/Message_Queue.h" +#include "ace/UPIPE_Addr.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_UPIPE_Stream + * + * @brief Defines the method that transfer data on a UPIPE. + */ +class ACE_Export ACE_UPIPE_Stream : public ACE_SPIPE +{ +public: + friend class ACE_UPIPE_Acceptor; + friend class ACE_UPIPE_Connector; + + typedef ACE_Stream MT_Stream; + + // = Initialization and Termination. + + ACE_UPIPE_Stream (void); + + virtual ~ACE_UPIPE_Stream (void); + + /// Shut down the UPIPE and release resources. + int close (void); + + /// Return the underlying I/O handle. + ACE_HANDLE get_handle (void) const; + + // = Send/recv ACE Message_Blocks. + /// Send a message through the message queue. Returns -1 on error, + /// else 0. + int send (ACE_Message_Block *mb_p, + ACE_Time_Value *timeout = 0); + + /// Recv a message from the message queue. Returns -1 on error, else + /// 0. + int recv (ACE_Message_Block *&mb_p, + ACE_Time_Value *timeout = 0); + + // = Send/recv char buffers. + /// Send a buffer of @a n bytes through the message queue. Returns -1 + /// on error, else number of bytes sent. + ssize_t send (const char *buffer, + size_t n, + ACE_Time_Value *timeout = 0); + + /// Recv a buffer of upto @a n bytes from the message queue. Returns + /// -1 on error, else number of bytes read. + ssize_t recv (char *buffer, + size_t n, + ACE_Time_Value *timeout = 0); + + /// Send a buffer of exactly @a n bytes to the message queue. Returns + /// -1 on error, else number of bytes written (which should == n). + ssize_t send_n (const char *buffer, + size_t n, + ACE_Time_Value *timeout = 0); + + /// Recv a buffer of exactly @a n bytes from the message queue. + /// Returns -1 on error, else the number of bytes read. + ssize_t recv_n (char *buffer, + size_t n, + ACE_Time_Value *timeout = 0); + + /// Perform control operations on the UPIPE_Stream. + int control (int cmd, void *val) const; + + /// Return the remote address we are connected to. + int get_remote_addr (ACE_UPIPE_Addr &remote_sap) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + + // = Meta-type info + typedef ACE_UPIPE_Addr PEER_ADDR; + +private: + /// To hold the last ACE_Message_Block read out of the stream. Thus + /// allowing subsequent reads from one ACE_Message_Block + ACE_Message_Block *mb_last_; + + /// Address of who we are connected to. + ACE_UPIPE_Addr remote_addr_; + + /// Stream component used by the @c UPIPE_Acceptor and + /// @c UPIPE_Connector to link together two UPIPE_Streams. + MT_Stream stream_; + + /// Keep track of whether the sender and receiver have both shutdown. + int reference_count_; + +#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) + /// Ensure that we are thread-safe. + ACE_Thread_Mutex lock_; +#endif /* ACE_MT_SAFE */ +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/UPIPE_Stream.inl" +#endif /* __ACE_INLINE__ */ + +#endif /* ACE_HAS_THREADS */ + +#include /**/ "ace/post.h" + +#endif /*ACE_UPIPE_STREAM_H */ diff --git a/dep/acelite/ace/UPIPE_Stream.inl b/dep/acelite/ace/UPIPE_Stream.inl new file mode 100644 index 00000000000..7a0d73c3179 --- /dev/null +++ b/dep/acelite/ace/UPIPE_Stream.inl @@ -0,0 +1,14 @@ +// -*- C++ -*- +// +// $Id: UPIPE_Stream.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE ACE_HANDLE +ACE_UPIPE_Stream::get_handle (void) const +{ + ACE_TRACE ("ACE_UPIPE_Stream::get_handle"); + return this->ACE_SPIPE::get_handle (); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/UTF16_Encoding_Converter.cpp b/dep/acelite/ace/UTF16_Encoding_Converter.cpp new file mode 100644 index 00000000000..da883734c39 --- /dev/null +++ b/dep/acelite/ace/UTF16_Encoding_Converter.cpp @@ -0,0 +1,364 @@ +// $Id: UTF16_Encoding_Converter.cpp 83735 2008-11-14 09:41:52Z johnnyw $ + +// ====================================================================== +// +// The actual conversion methods are covered by the copyright information +// below. It is not the actual code provided by Unicode, Inc. but is an +// ACE-ified and only slightly modified version. +// Chad Elliott 4/28/2005 +// +// Copyright 2001-2004 Unicode, Inc. +// +// Limitations on Rights to Redistribute This Code +// +// Unicode, Inc. hereby grants the right to freely use the information +// supplied in this file in the creation of products supporting the +// Unicode Standard, and to make copies of this file in any form +// for internal or external distribution as long as this notice +// remains attached. +// +// ====================================================================== + +#include "ace/UTF16_Encoding_Converter.h" + +#if defined (ACE_USES_WCHAR) +#include "ace/OS_NS_stdio.h" +#include "ace/OS_Memory.h" +#include "ace/Min_Max.h" + +#if !defined (__ACE_INLINE__) +#include "ace/UTF16_Encoding_Converter.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +static const ACE_UINT32 halfShift = 10; +static const ACE_UINT32 halfBase = 0x00010000; +static const ACE_UINT32 halfMask = 0x000003FF; + +static const ACE_UINT32 UNI_SUR_HIGH_START = 0x0000D800; +static const ACE_UINT32 UNI_SUR_HIGH_END = 0x0000DBFF; +static const ACE_UINT32 UNI_SUR_LOW_START = 0x0000DC00; +static const ACE_UINT32 UNI_SUR_LOW_END = 0x0000DFFF; +static const ACE_UINT32 UNI_REPLACEMENT_CHAR = 0x0000FFFD; +static const ACE_UINT32 UNI_MAX_BMP = 0x0000FFFF; +static const ACE_UINT32 UNI_MAX_UTF16 = 0x0010FFFF; + +// Once the bits are split out into bytes of UTF-8, this is a mask OR-ed +// into the first byte, depending on how many bytes follow. There are +// as many entries in this table as there are UTF-8 sequence types. +// (I.e., one byte sequence, two byte... etc.). Remember that sequencs +// for *legal* UTF-8 will be 4 or fewer bytes total. +static const ACE_Byte firstByteMark[7] = { 0x00, 0x00, 0xC0, + 0xE0, 0xF0, 0xF8, 0xFC }; + +// Index into the table below with the first byte of a UTF-8 sequence to +// get the number of trailing bytes that are supposed to follow it. +// Note that *legal* UTF-8 values can't have 4 or 5-bytes. The table is +// left as-is for anyone who may want to do such conversion, which was +// allowed in earlier algorithms. +static const ACE_Byte trailingBytesForUTF8[256] = { + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 +}; + +// Magic values subtracted from a buffer value during UTF8 conversion. +// This table contains as many values as there might be trailing bytes +// in a UTF-8 sequence. +static const ACE_UINT32 offsetsFromUTF8[6] = { 0x00000000, 0x00003080, + 0x000E2080, 0x03C82080, + 0xFA082080, 0x82082080 }; + + +ACE_UTF16_Encoding_Converter::ACE_UTF16_Encoding_Converter (bool swap) + : swap_ (swap) +{ +} + +ACE_UTF16_Encoding_Converter::~ACE_UTF16_Encoding_Converter (void) +{ +} + +ACE_UTF16_Encoding_Converter::Result +ACE_UTF16_Encoding_Converter::to_utf8 (const void* source, + size_t source_size, + ACE_Byte* target, + size_t target_size, + bool strict) +{ + static const ACE_UINT32 byteMask = 0xBF; + static const ACE_UINT32 byteMark = 0x80; + Result result = CONVERSION_OK; + + ACE_Byte* targetEnd = target + target_size; + const ACE_UINT16* sourceStart = static_cast (source); + const ACE_UINT16* sourceEnd = sourceStart + + (source_size / sizeof (ACE_UINT16)); + + while (sourceStart < sourceEnd) + { + ACE_UINT16 nw = *sourceStart++; + ACE_UINT32 ch = (this->swap_ ? ACE_SWAP_WORD (nw) : nw); + + // If we have a surrogate pair, convert to ACE_UINT32 first. + if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) + { + // If the 16 bits following the high surrogate are in the + // sourceStart buffer... + if (sourceStart < sourceEnd) + { + ACE_UINT32 ch2 = (this->swap_ ? ACE_SWAP_WORD (*sourceStart) : + *sourceStart); + // If it's a low surrogate, convert to ACE_UINT32. + if (ch2 >= UNI_SUR_LOW_START && ch2 <= UNI_SUR_LOW_END) + { + ch = ((ch - UNI_SUR_HIGH_START) << halfShift) + + (ch2 - UNI_SUR_LOW_START) + halfBase; + ++sourceStart; + } + else if (strict) + { + // it's an unpaired high surrogate + result = SOURCE_ILLEGAL; + break; + } + } + else + { + // We don't have the 16 bits following the high surrogate. + result = SOURCE_EXHAUSTED; + break; + } + } + else if (strict) + { + // UTF-16 surrogate values are illegal in UTF-32 + if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) + { + result = SOURCE_ILLEGAL; + break; + } + } + + // Figure out how many bytes the result will require + unsigned short bytesToWrite = 0; + if (ch < 0x80) + bytesToWrite = 1; + else if (ch < 0x800) + bytesToWrite = 2; + else if (ch < 0x10000) + bytesToWrite = 3; + else if (ch < 0x110000) + bytesToWrite = 4; + else + { + bytesToWrite = 3; + ch = UNI_REPLACEMENT_CHAR; + } + + target += bytesToWrite; + if (target > targetEnd) + { + result = TARGET_EXHAUSTED; + break; + } + + // NOTE: Everything falls through for efficiency purposes. + switch (bytesToWrite) + { + case 4: + *--target = (ACE_Byte)((ch | byteMark) & byteMask); + ch >>= 6; + case 3: + *--target = (ACE_Byte)((ch | byteMark) & byteMask); + ch >>= 6; + case 2: + *--target = (ACE_Byte)((ch | byteMark) & byteMask); + ch >>= 6; + case 1: + *--target = (ACE_Byte)(ch | firstByteMark[bytesToWrite]); + } + target += bytesToWrite; + } + + return result; +} + +ACE_UTF16_Encoding_Converter::Result +ACE_UTF16_Encoding_Converter::from_utf8 (const ACE_Byte* source, + size_t source_size, + void* target, + size_t target_size, + bool strict) +{ + Result result = CONVERSION_OK; + const ACE_Byte* sourceEnd = source + source_size; + ACE_UINT16* targetStart = static_cast (target); + ACE_UINT16* targetEnd = targetStart + target_size; + + while (source < sourceEnd) + { + ACE_UINT32 ch = 0; + unsigned short extraBytesToRead = trailingBytesForUTF8[*source]; + if (source + extraBytesToRead >= sourceEnd) + { + result = SOURCE_EXHAUSTED; + break; + } + + // Do this check whether lenient or strict + if (!this->is_legal_utf8 (source, extraBytesToRead + 1)) + { + result = SOURCE_ILLEGAL; + break; + } + + // The cases all fall through. See "Note A" below. + switch (extraBytesToRead) + { + case 5: // remember, illegal UTF-8 + ch += *source++; + ch <<= 6; + case 4: // remember, illegal UTF-8 + ch += *source++; + ch <<= 6; + case 3: + ch += *source++; + ch <<= 6; + case 2: + ch += *source++; + ch <<= 6; + case 1: + ch += *source++; + ch <<= 6; + case 0: + ch += *source++; + } + ch -= offsetsFromUTF8[extraBytesToRead]; + + if (targetStart >= targetEnd) + { + result = TARGET_EXHAUSTED; + break; + } + + if (ch <= UNI_MAX_BMP) // Target is a character <= 0xFFFF + { + // UTF-16 surrogate values are illegal in UTF-32 + if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) + { + if (strict) + { + result = SOURCE_ILLEGAL; + break; + } + else + { + *targetStart++ = UNI_REPLACEMENT_CHAR; + } + } + else + { + *targetStart++ = (ACE_UINT16)ch; + } + } + else if (ch > UNI_MAX_UTF16) + { + if (strict) + { + result = SOURCE_ILLEGAL; + break; + } + else + { + *targetStart++ = UNI_REPLACEMENT_CHAR; + } + } + else + { + // targetStart is a character in range 0xFFFF - 0x10FFFF. + if (targetStart + 1 >= targetEnd) + { + result = TARGET_EXHAUSTED; + break; + } + ch -= halfBase; + *targetStart++ = (ACE_UINT16)((ch >> halfShift) + UNI_SUR_HIGH_START); + *targetStart++ = (ACE_UINT16)((ch & halfMask) + UNI_SUR_LOW_START); + } + } + + return result; +} + +ACE_UTF16_Encoding_Converter* +ACE_UTF16_Encoding_Converter::encoded (const ACE_Byte* source, + size_t source_size) +{ + static const size_t begin = 16; + static const size_t converted = begin * 4; + + ACE_Byte target[converted]; + ACE_UTF16_Encoding_Converter* converter = 0; + ACE_NEW_RETURN (converter, + ACE_UTF16_Encoding_Converter (false), + 0); + if (converter->to_utf8 (source, + ACE_MIN (begin, source_size), + target, + converted) == CONVERSION_OK) + { + return converter; + } + else + { + delete converter; + } + + return 0; +} + +ACE_UINT32 +ACE_UTF16_Encoding_Converter::get_UNI_SUR_HIGH_START (void) +{ + return UNI_SUR_HIGH_START; +} + +ACE_UINT32 +ACE_UTF16_Encoding_Converter::get_UNI_SUR_LOW_END (void) +{ + return UNI_SUR_LOW_END; +} + +ACE_UINT32 +ACE_UTF16_Encoding_Converter::get_UNI_REPLACEMENT_CHAR (void) +{ + return UNI_REPLACEMENT_CHAR; +} + +const ACE_Byte* +ACE_UTF16_Encoding_Converter::get_first_byte_mark (void) +{ + return firstByteMark; +} + +const ACE_Byte* +ACE_UTF16_Encoding_Converter::get_trailing_bytes_for_utf8 (void) +{ + return trailingBytesForUTF8; +} + +const ACE_UINT32* +ACE_UTF16_Encoding_Converter::get_offsets_from_utf8 (void) +{ + return offsetsFromUTF8; +} + +ACE_END_VERSIONED_NAMESPACE_DECL +#endif /* ACE_USES_WCHAR */ diff --git a/dep/acelite/ace/UTF16_Encoding_Converter.h b/dep/acelite/ace/UTF16_Encoding_Converter.h new file mode 100644 index 00000000000..9bdcb21a07f --- /dev/null +++ b/dep/acelite/ace/UTF16_Encoding_Converter.h @@ -0,0 +1,86 @@ +// -*- C++ -*- + +//========================================================================= +/** + * @file UTF16_Encoding_Converter.h + * + * $Id: UTF16_Encoding_Converter.h 80826 2008-03-04 14:51:23Z wotte $ + * + * This class contains declarations for methods that convert between + * UTF-16 (both BE and LE) and UTF-8 + * + * @author Chad Elliott + */ +//========================================================================= + +#ifndef ACE_UTF16_ENCODING_CONVERTER_H +#define ACE_UTF16_ENCODING_CONVERTER_H + +#include /**/ "ace/pre.h" + +#include "ace/Encoding_Converter.h" + +#if defined (ACE_USES_WCHAR) +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** Convert from UTF-16 to UTF-8 and from UTF-8 to UTF-16. + * This class implements the ACE_Encoding_Converter interface. + */ +class ACE_UTF16_Encoding_Converter: public ACE_Encoding_Converter +{ +public: + /// The swap parameter determines whether we need to swap byte order on + /// the stream as each word is pulled off when converting to UTF-8. + ACE_UTF16_Encoding_Converter (bool swap = false); + + /// This is a do nothing destructor. + virtual ~ACE_UTF16_Encoding_Converter (void); + + /// Convert the source from UTF-16 to UTF-8 and store it in the + /// provided target buffer. + virtual Result to_utf8 (const void* source, + size_t source_size, + ACE_Byte* target, + size_t target_size, + bool strict = true); + + /// Convert the UTF-8 source into a UTF-16 encoding and store it + /// in the provided target buffer. + virtual Result from_utf8 (const ACE_Byte* source, + size_t source_size, + void* target, + size_t target_size, + bool strict = true); + + /// This factory helper method determines if the source stream is UTF-16 + /// encoded. If it is, allocate an ACE_UTF16_Encoding_Converter and + /// return it. The caller then owns the allocated object. + static ACE_UTF16_Encoding_Converter* encoded (const ACE_Byte* source, + size_t source_size); + +protected: + /// Determines if the source buffer is legal UTF-8 + bool is_legal_utf8 (const ACE_Byte* source, + size_t length) const; + + static ACE_UINT32 get_UNI_SUR_HIGH_START (void); + static ACE_UINT32 get_UNI_SUR_LOW_END (void); + static ACE_UINT32 get_UNI_REPLACEMENT_CHAR (void); + static const ACE_Byte* get_first_byte_mark (void); + static const ACE_Byte* get_trailing_bytes_for_utf8 (void); + static const ACE_UINT32* get_offsets_from_utf8 (void); + + bool swap_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/UTF16_Encoding_Converter.inl" +#endif /* __ACE_INLINE__ */ + +#endif /* ACE_USES_WCHAR */ + +#include /**/ "ace/post.h" + +#endif /* ACE_UTF16_ENCODING_CONVERTER_H */ diff --git a/dep/acelite/ace/UTF16_Encoding_Converter.inl b/dep/acelite/ace/UTF16_Encoding_Converter.inl new file mode 100644 index 00000000000..e5292757889 --- /dev/null +++ b/dep/acelite/ace/UTF16_Encoding_Converter.inl @@ -0,0 +1,76 @@ +/* -*- C++ -*- */ +// $Id: UTF16_Encoding_Converter.inl 80826 2008-03-04 14:51:23Z wotte $ + +// ====================================================================== +// +// The actual conversion methods are covered by the copyright information +// below. +// Chad Elliott 4/28/2005 +// +// Copyright 2001-2004 Unicode, Inc. +// +// Limitations on Rights to Redistribute This Code +// +// Unicode, Inc. hereby grants the right to freely use the information +// supplied in this file in the creation of products supporting the +// Unicode Standard, and to make copies of this file in any form +// for internal or external distribution as long as this notice +// remains attached. +// +// ====================================================================== + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE bool +ACE_UTF16_Encoding_Converter::is_legal_utf8 (const ACE_Byte* source, + size_t length) const +{ + ACE_Byte a; + const ACE_Byte* srcptr = source + length; + + switch (length) + { + default: + return false; + + // Everything else falls through when "true"... + case 4: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false; + case 3: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false; + case 2: if ((a = (*--srcptr)) > 0xBF) return false; + + switch (*source) + { + // no fall-through in this inner switch + case 0xE0: + if (a < 0xA0) + return false; + break; + case 0xED: + if (a > 0x9F) + return false; + break; + case 0xF0: + if (a < 0x90) + return false; + break; + case 0xF4: + if (a > 0x8F) + return false; + break; + default: + if (a < 0x80) + return false; + } + + case 1: + if (*source >= 0x80 && *source < 0xC2) + return false; + } + + if (*source > 0xF4) + return false; + + return true; +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/UTF32_Encoding_Converter.cpp b/dep/acelite/ace/UTF32_Encoding_Converter.cpp new file mode 100644 index 00000000000..459bf2530b0 --- /dev/null +++ b/dep/acelite/ace/UTF32_Encoding_Converter.cpp @@ -0,0 +1,254 @@ +// $Id: UTF32_Encoding_Converter.cpp 80826 2008-03-04 14:51:23Z wotte $ + +// ====================================================================== +// +// The actual conversion methods are covered by the copyright information +// below. It is not the actual code provided by Unicode, Inc. but is an +// ACE-ified and only slightly modified version. +// +// Chad Elliott 4/28/2005 +// +// Copyright 2001-2004 Unicode, Inc. +// +// Limitations on Rights to Redistribute This Code +// +// Unicode, Inc. hereby grants the right to freely use the information +// supplied in this file in the creation of products supporting the +// Unicode Standard, and to make copies of this file in any form +// for internal or external distribution as long as this notice +// remains attached. +// +// ====================================================================== + +#include "ace/UTF32_Encoding_Converter.h" + +#if defined (ACE_USES_WCHAR) +#include "ace/OS_NS_stdio.h" +#include "ace/OS_Memory.h" +#include "ace/Min_Max.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +static const ACE_UINT32 UNI_MAX_LEGAL_UTF32 = 0x0010FFFF; + +ACE_UTF32_Encoding_Converter::ACE_UTF32_Encoding_Converter (bool swap) + : ACE_UTF16_Encoding_Converter (swap) +{ +} + +ACE_UTF32_Encoding_Converter::~ACE_UTF32_Encoding_Converter (void) +{ +} + +ACE_UTF32_Encoding_Converter::Result +ACE_UTF32_Encoding_Converter::to_utf8 (const void* source, + size_t source_size, + ACE_Byte* target, + size_t target_size, + bool strict) +{ + static const ACE_UINT32 byteMask = 0xBF; + static const ACE_UINT32 byteMark = 0x80; + static const ACE_UINT32 UNI_SUR_HIGH_START = get_UNI_SUR_HIGH_START (); + static const ACE_UINT32 UNI_SUR_LOW_END = get_UNI_SUR_LOW_END (); + static const ACE_Byte* firstByteMark = get_first_byte_mark (); + + Result result = CONVERSION_OK; + ACE_Byte* targetEnd = target + target_size; + const ACE_UINT32* sourceStart = static_cast (source); + const ACE_UINT32* sourceEnd = sourceStart + (source_size / sizeof (ACE_UINT32)); + + while (sourceStart < sourceEnd) + { + ACE_UINT32 nw = *sourceStart++; + ACE_UINT32 ch = (this->swap_ ? ACE_SWAP_LONG (nw) : nw); + unsigned short bytesToWrite = 0; + + if (strict) + { + // UTF-16 surrogate values are illegal in UTF-32 + if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) + { + result = SOURCE_ILLEGAL; + break; + } + } + + // Figure out how many bytes the result will require. Turn any + // illegally large ACE_UINT32 things (> Plane 17) into replacement + // chars. + if (ch < 0x80) + { + bytesToWrite = 1; + } + else if (ch < 0x800) + { + bytesToWrite = 2; + } + else if (ch < 0x10000) + { + bytesToWrite = 3; + } + else if (ch <= UNI_MAX_LEGAL_UTF32) + { + bytesToWrite = 4; + } + else + { + result = SOURCE_ILLEGAL; + break; + } + + target += bytesToWrite; + if (target > targetEnd) + { + result = TARGET_EXHAUSTED; + break; + } + + // NOTE: everything falls through. + switch (bytesToWrite) + { + case 4: + *--target = (ACE_Byte)((ch | byteMark) & byteMask); + ch >>= 6; + case 3: + *--target = (ACE_Byte)((ch | byteMark) & byteMask); + ch >>= 6; + case 2: + *--target = (ACE_Byte)((ch | byteMark) & byteMask); + ch >>= 6; + case 1: + *--target = (ACE_Byte) (ch | firstByteMark[bytesToWrite]); + } + target += bytesToWrite; + } + + return result; +} + +ACE_UTF32_Encoding_Converter::Result +ACE_UTF32_Encoding_Converter::from_utf8 (const ACE_Byte* source, + size_t source_size, + void* target, + size_t target_size, + bool strict) +{ + static const ACE_UINT32 UNI_SUR_HIGH_START = get_UNI_SUR_HIGH_START (); + static const ACE_UINT32 UNI_SUR_LOW_END = get_UNI_SUR_LOW_END (); + static const ACE_UINT32 UNI_REPLACEMENT_CHAR = get_UNI_REPLACEMENT_CHAR (); + static const ACE_Byte* trailingBytesForUTF8 = get_trailing_bytes_for_utf8 (); + static const ACE_UINT32* offsetsFromUTF8 = get_offsets_from_utf8 (); + + Result result = CONVERSION_OK; + const ACE_Byte* sourceEnd = source + source_size; + ACE_UINT32* targetStart = static_cast (target); + ACE_UINT32* targetEnd = targetStart + target_size; + + while (source < sourceEnd) + { + ACE_UINT32 ch = 0; + unsigned short extraBytesToRead = trailingBytesForUTF8[*source]; + if (source + extraBytesToRead >= sourceEnd) + { + result = SOURCE_EXHAUSTED; + break; + } + + // Do this check whether lenient or strict + if (!this->is_legal_utf8 (source, extraBytesToRead + 1)) + { + result = SOURCE_ILLEGAL; + break; + } + + // The cases all fall through. See "Note A" below. + switch (extraBytesToRead) + { + case 5: + ch += *source++; + ch <<= 6; + case 4: + ch += *source++; + ch <<= 6; + case 3: + ch += *source++; + ch <<= 6; + case 2: + ch += *source++; + ch <<= 6; + case 1: + ch += *source++; + ch <<= 6; + case 0: + ch += *source++; + } + ch -= offsetsFromUTF8[extraBytesToRead]; + + if (targetStart >= targetEnd) + { + result = TARGET_EXHAUSTED; + break; + } + + if (ch <= UNI_MAX_LEGAL_UTF32) + { + // UTF-16 surrogate values are illegal in UTF-32, and anything + // over Plane 17 (> 0x10FFFF) is illegal. + if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) + { + if (strict) + { + result = SOURCE_ILLEGAL; + break; + } + else + { + *targetStart++ = UNI_REPLACEMENT_CHAR; + } + } + else + { + *targetStart++ = ch; + } + } + else + { + result = SOURCE_ILLEGAL; + break; + } + } + + return result; +} + +ACE_UTF32_Encoding_Converter* +ACE_UTF32_Encoding_Converter::encoded (const ACE_Byte* source, + size_t source_size) +{ + static const size_t begin = 16; + static const size_t converted = begin * 4; + + ACE_Byte target[converted]; + ACE_UTF32_Encoding_Converter* converter = 0; + ACE_NEW_RETURN (converter, + ACE_UTF32_Encoding_Converter (false), + 0); + + if (converter->to_utf8 (source, + ACE_MIN (begin, source_size), + target, + converted) == CONVERSION_OK) + { + return converter; + } + else + { + delete converter; + } + + return 0; +} + +ACE_END_VERSIONED_NAMESPACE_DECL +#endif /* ACE_USES_WCHAR */ diff --git a/dep/acelite/ace/UTF32_Encoding_Converter.h b/dep/acelite/ace/UTF32_Encoding_Converter.h new file mode 100644 index 00000000000..214edeeeed8 --- /dev/null +++ b/dep/acelite/ace/UTF32_Encoding_Converter.h @@ -0,0 +1,67 @@ +// -*- C++ -*- + +//========================================================================= +/** + * @file UTF32_Encoding_Converter.h + * + * $Id: UTF32_Encoding_Converter.h 80826 2008-03-04 14:51:23Z wotte $ + * + * This class contains declarations for methods that convert between + * UTF-32 (both BE and LE) and UTF-8 + * + * @author Chad Elliott + */ +//========================================================================= + +#ifndef ACE_UTF32_ENCODING_CONVERTER_H +#define ACE_UTF32_ENCODING_CONVERTER_H + +#include /**/ "ace/pre.h" + +#include "ace/UTF16_Encoding_Converter.h" + +#if defined (ACE_USES_WCHAR) +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** Convert from UTF-32 to UTF-8 and from UTF-8 to UTF-32. + * This class implements the ACE_Encoding_Converter interface. + */ +class ACE_UTF32_Encoding_Converter: public ACE_UTF16_Encoding_Converter +{ +public: + /// This class has some similarities to the UTF16 converter, so + /// we just construct our base class and pass the swap parameter. + ACE_UTF32_Encoding_Converter (bool swap = false); + + /// This is a do nothing destructor. + virtual ~ACE_UTF32_Encoding_Converter (void); + + /// Convert the source from UTF-32 to UTF-8 and store it in the + /// provided target buffer. + virtual Result to_utf8 (const void* source, + size_t source_size, + ACE_Byte* target, + size_t target_size, + bool strict = true); + + /// Convert the UTF-8 source into a UTF-32 encoding and store it + /// in the provided target buffer. + virtual Result from_utf8 (const ACE_Byte* source, + size_t source_size, + void* target, + size_t target_size, + bool strict = true); + + /// This factory helper method determines if the source stream is UTF-32 + /// encoded. If it is, allocate an ACE_UTF32_Encoding_Converter and + /// return it. The caller then owns the allocated object. + static ACE_UTF32_Encoding_Converter* encoded (const ACE_Byte* source, + size_t source_size); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL +#endif /* ACE_USES_WCHAR */ + +#include /**/ "ace/post.h" + +#endif /* ACE_UTF32_ENCODING_CONVERTER_H */ diff --git a/dep/acelite/ace/UTF8_Encoding_Converter.cpp b/dep/acelite/ace/UTF8_Encoding_Converter.cpp new file mode 100644 index 00000000000..cd6c409d0f8 --- /dev/null +++ b/dep/acelite/ace/UTF8_Encoding_Converter.cpp @@ -0,0 +1,92 @@ +// $Id: UTF8_Encoding_Converter.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/UTF8_Encoding_Converter.h" + +#if defined (ACE_USES_WCHAR) +#include "ace/UTF16_Encoding_Converter.h" +#include "ace/UTF32_Encoding_Converter.h" +#include "ace/OS_NS_string.h" +#include "ace/OS_Memory.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_UTF8_Encoding_Converter::ACE_UTF8_Encoding_Converter (void) + : native_ (0) +{ + // Choose a converter for the ASCII or UTF-8 string to a wide character + // string which we will use in from_utf8. We have to make an + // assumption here about the encoding based on the size of ACE_TCHAR. + switch (sizeof (ACE_TCHAR)) + { + case 4: + ACE_NEW(this->native_, ACE_UTF32_Encoding_Converter); + break; + case 2: + ACE_NEW(this->native_, ACE_UTF16_Encoding_Converter); + break; + } +} + +ACE_UTF8_Encoding_Converter::~ACE_UTF8_Encoding_Converter (void) +{ + delete native_; +} + +ACE_UTF8_Encoding_Converter::Result +ACE_UTF8_Encoding_Converter::to_utf8 (const void* source, + size_t source_size, + ACE_Byte* target, + size_t target_size, + bool /*strict*/) +{ + if (target_size >= source_size) + { + ACE_OS::memcpy (target, source, source_size); + return CONVERSION_OK; + } + + return TARGET_EXHAUSTED; +} + +ACE_UTF8_Encoding_Converter::Result +ACE_UTF8_Encoding_Converter::from_utf8 (const ACE_Byte* source, + size_t source_size, + void* target, + size_t target_size, + bool strict) +{ + if (this->native_ != 0) + { + return this->native_->from_utf8(source, source_size, + target, target_size, strict); + } + + ACE_TCHAR* targetStart = static_cast (target); + ACE_OS::strncpy (targetStart, + ACE_TEXT_CHAR_TO_TCHAR ( + reinterpret_cast (source)), + source_size); + targetStart[source_size] = 0; + return CONVERSION_OK; +} + +ACE_UTF8_Encoding_Converter* +ACE_UTF8_Encoding_Converter::encoded (const ACE_Byte* source, + size_t source_size) +{ + for(size_t i = 0; i < source_size; i++) + { + if (source[i] < 0x01 || source[i] > 0x7f) + return 0; + } + + // All characters are "valid" ASCII + ACE_UTF8_Encoding_Converter* converter = 0; + ACE_NEW_RETURN (converter, + ACE_UTF8_Encoding_Converter, + 0); + return converter; +} + +ACE_END_VERSIONED_NAMESPACE_DECL +#endif /* ACE_USES_WCHAR */ diff --git a/dep/acelite/ace/UTF8_Encoding_Converter.h b/dep/acelite/ace/UTF8_Encoding_Converter.h new file mode 100644 index 00000000000..2cb6ed4e452 --- /dev/null +++ b/dep/acelite/ace/UTF8_Encoding_Converter.h @@ -0,0 +1,72 @@ +// -*- C++ -*- + +//========================================================================= +/** + * @file UTF8_Encoding_Converter.h + * + * $Id: UTF8_Encoding_Converter.h 80826 2008-03-04 14:51:23Z wotte $ + * + * This class contains declarations for methods that convert between + * UTF-8 and the native ACE_TCHAR representation. + * + * @author Chad Elliott + */ +//========================================================================= + +#ifndef ACE_UTF8_ENCODING_CONVERTER_H +#define ACE_UTF8_ENCODING_CONVERTER_H + +#include /**/ "ace/pre.h" + +#include "ace/Encoding_Converter.h" + +#if defined (ACE_USES_WCHAR) +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** Convert from UTF-16 or UTF-32 to UTF-8. + * This class implements the ACE_Encoding_Converter interface. + */ +class ACE_UTF8_Encoding_Converter: public ACE_Encoding_Converter +{ +public: + /// Allocate the converter to be used by the from_utf8() method based + /// on the size of the native wide character. + ACE_UTF8_Encoding_Converter (void); + + /// De-allocate the native converter. + virtual ~ACE_UTF8_Encoding_Converter (void); + + /// Since the source *must be* UTF-8, there is no conversion required. + /// This method just copies the source to the target given that there + /// is enough space. + virtual Result to_utf8 (const void* source, + size_t source_size, + ACE_Byte* target, + size_t target_size, + bool strict = true); + + /// Utilize the native converter to convert the UTF-8 source into an + /// alternate encoding and store it in the provided target buffer. + virtual Result from_utf8 (const ACE_Byte* source, + size_t source_size, + void* target, + size_t target_size, + bool strict = true); + + + /// This factory helper method determines if the source stream is UTF-8 + /// encoded. If it is, allocate an ACE_UTF8_Encoding_Converter and + /// return it. The caller then owns the allocated object. + static ACE_UTF8_Encoding_Converter* encoded (const ACE_Byte* source, + size_t source_size); + +private: + ACE_Encoding_Converter* native_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL +#endif /* ACE_USES_WCHAR */ + +#include /**/ "ace/post.h" + +#endif /* ACE_UTF8_ENCODING_CONVERTER_H */ diff --git a/dep/acelite/ace/UUID.cpp b/dep/acelite/ace/UUID.cpp new file mode 100644 index 00000000000..800469481e7 --- /dev/null +++ b/dep/acelite/ace/UUID.cpp @@ -0,0 +1,506 @@ +//$Id: UUID.cpp 88515 2010-01-13 08:47:38Z johnnyw $ + +#include "ace/UUID.h" +#include "ace/Guard_T.h" + +#if !defined (__ACE_INLINE__) +#include "ace/UUID.inl" +#endif /* __ACE_INLINE__ */ + +#include "ace/Log_Msg.h" +#include "ace/OS_NS_stdio.h" +#include "ace/OS_NS_string.h" +#include "ace/OS_NS_sys_time.h" +#include "ace/OS_NS_netdb.h" +#include "ace/OS_NS_unistd.h" +#include "ace/ACE.h" + +ACE_RCSID (ace, + UUID, + "$Id: UUID.cpp 88515 2010-01-13 08:47:38Z johnnyw $") + + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +namespace ACE_Utils +{ + // NIL version of the UUID + const UUID UUID::NIL_UUID; + + UUID::UUID (const ACE_CString& uuid_string) + { + this->init (); + this->from_string_i (uuid_string); + } + + const UUID & + UUID::operator = (const UUID & rhs) + { + if (this != &rhs) + { + // Reset the string version of the UUID a string version + // exist, and the UUID is not equal to the old UUID. + if (0 != this->as_string_.get ()) + { + if (0 == rhs.as_string_.get () || *this != rhs) + this->as_string_.reset (); + } + + // Copy the contents of the UUID. + ACE_OS::memcpy (&this->uuid_, &rhs.uuid_, BINARY_SIZE); + + /// @todo We should create an UUID_Ex class for UUIDs that + /// contain the thread id and process id. + this->thr_id_ = rhs.thr_id_; + this->pid_ = rhs.pid_; + } + + return *this; + } + + const ACE_CString * UUID::to_string (void) const + { + // Compute the string representation only once. + if (0 != this->as_string_.get ()) + return this->as_string_.get (); + + // Get a buffer exactly the correct size. Use the nil UUID as a + // gauge. Don't forget the trailing nul. + ACE_Auto_Array_Ptr auto_clean; + size_t UUID_STRING_LENGTH = 36 + thr_id_.length () + pid_.length (); + char *buf = 0; + + if (36 == UUID_STRING_LENGTH) + { + ACE_NEW_RETURN (buf, + char[UUID_STRING_LENGTH + 1], + 0); + + // Let the auto array pointer manage the buffer. + auto_clean.reset (buf); + + ACE_OS::sprintf (buf, + "%8.8x-%4.4x-%4.4x-%2.2x%2.2x-%2.2x%2.2x%2.2x%2.2x%2.2x%2.2x", + this->uuid_.time_low_, + this->uuid_.time_mid_, + this->uuid_.time_hi_and_version_, + this->uuid_.clock_seq_hi_and_reserved_, + this->uuid_.clock_seq_low_, + (this->uuid_.node_.node_ID ()) [0], + (this->uuid_.node_.node_ID ()) [1], + (this->uuid_.node_.node_ID ()) [2], + (this->uuid_.node_.node_ID ()) [3], + (this->uuid_.node_.node_ID ()) [4], + (this->uuid_.node_.node_ID ()) [5]); + } + else + { + UUID_STRING_LENGTH += 2; //for '-' + ACE_NEW_RETURN (buf, + char[UUID_STRING_LENGTH + 1], + 0); + + // Let the auto array pointer manage the buffer. + auto_clean.reset (buf); + + ACE_OS::sprintf (buf, + "%8.8x-%4.4x-%4.4x-%2.2x%2.2x-%2.2x%2.2x%2.2x%2.2x%2.2x%2.2x-%s-%s", + this->uuid_.time_low_, + this->uuid_.time_mid_, + this->uuid_.time_hi_and_version_, + this->uuid_.clock_seq_hi_and_reserved_, + this->uuid_.clock_seq_low_, + (this->uuid_.node_.node_ID ()) [0], + (this->uuid_.node_.node_ID ()) [1], + (this->uuid_.node_.node_ID ()) [2], + (this->uuid_.node_.node_ID ()) [3], + (this->uuid_.node_.node_ID ()) [4], + (this->uuid_.node_.node_ID ()) [5], + thr_id_.c_str (), + pid_.c_str ()); + } + + // Save the string. + ACE_CString * as_string = 0; + + ACE_NEW_RETURN (as_string, + ACE_CString (buf, UUID_STRING_LENGTH), + 0); + + this->as_string_.reset (as_string); + return this->as_string_.get (); + } + + void + UUID::from_string_i (const ACE_CString& uuid_string) + { + if (uuid_string.length () < NIL_UUID.to_string ()->length ()) + { + ACE_ERROR ((LM_ERROR, + "%N ACE_UUID::from_string_i - " + "IllegalArgument (incorrect string length)\n")); + return; + } + + /// Special case for the nil UUID. + if (uuid_string == *NIL_UUID.to_string ()) + { + *this = NIL_UUID; + return; + } + + unsigned int time_low; + unsigned int time_mid; + unsigned int time_hi_and_version; + unsigned int clock_seq_hi_and_reserved; + unsigned int clock_seq_low; + unsigned int node [UUID_Node::NODE_ID_SIZE]; + char thr_pid_buf [BUFSIZ]; + + if (uuid_string.length () == NIL_UUID.to_string ()->length ()) + { + // This might seem quite strange this being in ACE, but it + // seems to be a bit difficult to write a facade for ::sscanf + // because some compilers dont support vsscanf, including + // MSVC. It appears that most platforms support sscanf though + // so we need to use it directly. + const int nScanned = +#if defined (ACE_HAS_TR24731_2005_CRT) + sscanf_s ( +#else + ::sscanf ( +#endif /* ACE_HAS_TR24731_2005_CRT */ + uuid_string.c_str (), + "%8x-%4x-%4x-%2x%2x-%2x%2x%2x%2x%2x%2x", + &time_low, + &time_mid, + &time_hi_and_version, + &clock_seq_hi_and_reserved, + &clock_seq_low, + &node[0], + &node[1], + &node[2], + &node[3], + &node[4], + &node[5] + ); + + if (nScanned != 11) + { + ACE_DEBUG ((LM_DEBUG, + "UUID::from_string_i - " + "IllegalArgument (invalid string representation)\n")); + return; + } + } + else + { + const int nScanned = +#if defined (ACE_HAS_TR24731_2005_CRT) + sscanf_s (uuid_string.c_str (), + "%8x-%4x-%4x-%2x%2x-%2x%2x%2x%2x%2x%2x-%s", + &time_low, + &time_mid, + &time_hi_and_version, + &clock_seq_hi_and_reserved, + &clock_seq_low, + &node[0], + &node[1], + &node[2], + &node[3], + &node[4], + &node[5], + thr_pid_buf, + BUFSIZ + ); +#else + ::sscanf (uuid_string.c_str (), + "%8x-%4x-%4x-%2x%2x-%2x%2x%2x%2x%2x%2x-%s", + &time_low, + &time_mid, + &time_hi_and_version, + &clock_seq_hi_and_reserved, + &clock_seq_low, + &node[0], + &node[1], + &node[2], + &node[3], + &node[4], + &node[5], + thr_pid_buf + ); +#endif /* ACE_HAS_TR24731_2005_CRT */ + + if (nScanned != 12) + { + ACE_DEBUG ((LM_DEBUG, + "ACE_UUID::from_string_i - " + "IllegalArgument (invalid string representation)\n")); + return; + } + } + + this->uuid_.time_low_ = static_cast (time_low); + this->uuid_.time_mid_ = static_cast (time_mid); + this->uuid_.time_hi_and_version_ = static_cast (time_hi_and_version); + this->uuid_.clock_seq_hi_and_reserved_ = static_cast (clock_seq_hi_and_reserved); + this->uuid_.clock_seq_low_ = static_cast (clock_seq_low); + + for (size_t i = 0; i < UUID_Node::NODE_ID_SIZE; ++ i) + this->uuid_.node_.node_ID ()[i] = static_cast (node[i]); + + // Support varient 10- only + if ((this->uuid_.clock_seq_hi_and_reserved_ & 0xc0) != 0x80 && + (this->uuid_.clock_seq_hi_and_reserved_ & 0xc0) != 0xc0) + { + ACE_DEBUG ((LM_DEBUG, + "ACE_UUID::from_string_i - " + "IllegalArgument (unsupported variant)\n")); + return; + } + + /// Support versions 1, 3, and 4 only + ACE_UINT16 V1 = this->uuid_.time_hi_and_version_; + + if ((V1 & 0xF000) != 0x1000 && + (V1 & 0xF000) != 0x3000 && + (V1 & 0xF000) != 0x4000) + { + ACE_DEBUG ((LM_DEBUG, + "ACE_UUID::from_string_i - " + "IllegalArgument (unsupported version)\n")); + return; + } + + if ((this->uuid_.clock_seq_hi_and_reserved_ & 0xc0) == 0xc0) + { + if (uuid_string.length () == NIL_UUID.to_string ()->length ()) + { + ACE_DEBUG ((LM_DEBUG, + "ACE_UUID::from_string_i - " + "IllegalArgument (Missing Thread and Process Id)\n")); + return; + } + ACE_CString thr_pid_str (thr_pid_buf); + ssize_t pos = static_cast (thr_pid_str.find ('-')); + if (pos == -1) + ACE_DEBUG ((LM_DEBUG, + "ACE_UUID::from_string_i - " + "IllegalArgument (Thread and Process Id format incorrect)\n")); + + this->thr_id_ = thr_pid_str.substr (0, pos); + this->pid_ = thr_pid_str.substr (pos+1, thr_pid_str.length ()-pos-1); + } + } + + UUID_Generator::UUID_Generator (void) + : time_last_ (0), + destroy_lock_ (true), + is_init_ (false) + { + ACE_NEW (lock_, ACE_SYNCH_MUTEX); + this->init (); + } + + UUID_Generator::~UUID_Generator (void) + { + if (destroy_lock_) + delete lock_; + } + + void + UUID_Generator::init (void) + { + if (this->is_init_) + return; + + ACE_OS::macaddr_node_t macaddress; + int const result = ACE_OS::getmacaddress (&macaddress); + + UUID_Node::Node_ID node_id; + + if (-1 != result) + { + ACE_OS::memcpy (node_id, + macaddress.node, + UUID_Node::NODE_ID_SIZE); + } + else + { + node_id [0] = static_cast (ACE_OS::rand ()); + node_id [1] = static_cast (ACE_OS::rand ()); + node_id [2] = static_cast (ACE_OS::rand ()); + node_id [3] = static_cast (ACE_OS::rand ()); + node_id [4] = static_cast (ACE_OS::rand ()); + node_id [5] = static_cast (ACE_OS::rand ()); + } + + this->get_timestamp (time_last_); + + { + ACE_GUARD (ACE_SYNCH_MUTEX, ace_mon, *lock_); + uuid_state_.timestamp = time_last_; + + ACE_OS::memcpy (uuid_state_.node.node_ID (), + node_id, + UUID_Node::NODE_ID_SIZE); + } + + this->is_init_ = true; + } + + void + UUID_Generator:: + generate_UUID (UUID& uuid, ACE_UINT16 version, u_char variant) + { + UUID_Time timestamp; + ACE_UINT16 clock_sequence; + + this->get_timestamp_and_clocksequence (timestamp, + clock_sequence); + + // Construct a Version 1 UUID with the information in the arguements. + uuid.time_low (static_cast (timestamp & 0xFFFFFFFF)); + uuid.time_mid (static_cast ((timestamp >> 32) & 0xFFFF)); + + ACE_UINT16 tHAV = static_cast ((timestamp >> 48) & 0xFFFF); + tHAV |= (version << 12); + uuid.time_hi_and_version (tHAV); + + u_char cseqHAV; + uuid.clock_seq_low (static_cast (clock_sequence & 0xFF)); + cseqHAV = static_cast ((clock_sequence & 0x3f00) >> 8); + uuid_state_.timestamp = timestamp; + + cseqHAV |= variant; + uuid.clock_seq_hi_and_reserved (cseqHAV); + uuid.node (uuid_state_.node); + + if (variant == 0xc0) + { + ACE_Thread_ID thread_id; + char buf [BUFSIZ]; + thread_id.to_string (buf); + uuid.thr_id (buf); + + ACE_OS::sprintf (buf, + "%d", + static_cast (ACE_OS::getpid ())); + uuid.pid (buf); + } + } + + UUID* + UUID_Generator::generate_UUID (ACE_UINT16 version, u_char variant) + { + UUID* uuid = 0; + ACE_NEW_RETURN (uuid, + UUID, + 0); + + this->generate_UUID (*uuid, version, variant); + return uuid; + } + + /// Obtain a new timestamp. If UUID's are being generated too quickly + /// the clock sequence will be incremented + void + UUID_Generator::get_timestamp (UUID_Time& timestamp) + { + ACE_GUARD (ACE_SYNCH_MUTEX, mon, *lock_); + + this->get_systemtime (timestamp); + + // Account for the clock being set back. Increment the clock / + // sequence. + if (timestamp <= time_last_) + { + uuid_state_.clock_sequence = static_cast + ((uuid_state_.clock_sequence + 1) & ACE_UUID_CLOCK_SEQ_MASK); + } + // If the system time ticked since the last UUID was + // generated. Set / the clock sequence back. + else if (timestamp > time_last_) + { + uuid_state_.clock_sequence = 0; + } + + time_last_ = timestamp; + } + + void + UUID_Generator::get_timestamp_and_clocksequence (UUID_Time& timestamp, + ACE_UINT16& clock_sequence) + { + ACE_GUARD (ACE_SYNCH_MUTEX, mon, *lock_); + + this->get_systemtime (timestamp); + + // Account for the clock being set back. Increment the clock / + // sequence. + if (timestamp <= time_last_) + uuid_state_.clock_sequence = static_cast ((uuid_state_.clock_sequence + 1) & ACE_UUID_CLOCK_SEQ_MASK); + + // If the system time ticked since the last UUID was + // generated. Set / the clock sequence back. + else if (timestamp > time_last_) + uuid_state_.clock_sequence = 0; + + time_last_ = timestamp; + clock_sequence = uuid_state_.clock_sequence; + } + + /** + * ACE_Time_Value is in POSIX time, seconds since Jan 1, 1970. UUIDs use + * time in 100ns ticks since 15 October 1582. The difference is: + * 15 Oct 1582 - 1 Jan 1600: 17 days in Oct, 30 in Nov, 31 in Dec + + * 17 years and 4 leap days (1584, 88, 92 and 96) + * 1 Jan 1600 - 1 Jan 1900: 3 centuries + 73 leap days ( 25 in 17th cent. + * and 24 each in 18th and 19th centuries) + * 1 Jan 1900 - 1 Jan 1970: 70 years + 17 leap days. + * This adds up, in days: (17+30+31+365*17+4)+ (365*300+73)+ (365*70+17) or + * 122192928000000000U (0x1B21DD213814000) 100 ns ticks. + */ + void + UUID_Generator::get_systemtime (UUID_Time & timestamp) + { + const UUID_Time timeOffset = +#if defined (ACE_LACKS_UNSIGNEDLONGLONG_T) + ACE_U_LongLong (ACE_INT64_LITERAL (0x1B21DD213814000)); +#elif defined (ACE_LACKS_LONGLONG_T) + ACE_U_LongLong (0x13814000u, 0x1B21DD2u); +#else + ACE_UINT64_LITERAL (0x1B21DD213814000); +#endif /* ACE_LACKS_UNSIGNEDLONGLONG_T */ + + /// Get the time of day, convert to 100ns ticks then add the offset. + ACE_Time_Value now = ACE_OS::gettimeofday (); + ACE_UINT64 time; + now.to_usec (time); + time = time * 10; + timestamp = time + timeOffset; + } + + ACE_SYNCH_MUTEX* + UUID_Generator::lock (void) + { + return this->lock_; + } + + void + UUID_Generator::lock (ACE_SYNCH_MUTEX* lock, bool release_lock) + { + if (this->destroy_lock_) + delete this->lock_; + + this->lock_ = lock; + this->destroy_lock_ = release_lock; + } +} + +#if defined (ACE_HAS_EXPLICIT_STATIC_TEMPLATE_MEMBER_INSTANTIATION) + template ACE_Singleton * + ACE_Singleton ::singleton_; +#endif /* ACE_HAS_EXPLICIT_STATIC_TEMPLATE_MEMBER_INSTANTIATION */ + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/UUID.h b/dep/acelite/ace/UUID.h new file mode 100644 index 00000000000..ae43c145dbb --- /dev/null +++ b/dep/acelite/ace/UUID.h @@ -0,0 +1,282 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file UUID.h + * + * $Id: UUID.h 88604 2010-01-18 18:01:19Z hillj $ + * + * @author Andrew T. Finnel + * @author Yamuna Krishnmaurthy + */ +//============================================================================= + +#ifndef ACE_UUID_H +#define ACE_UUID_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Auto_Ptr.h" +#include "ace/SString.h" +#include "ace/Singleton.h" +#include "ace/Synch_Traits.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +namespace ACE_Utils +{ + /** + * @class UUID_Node + * + * @brief Holds the MAC-address of the UUID. + */ + class ACE_Export UUID_Node + { + public: + /// Size of the node in bytes. + enum {NODE_ID_SIZE = 6}; + + /// Type definition of the node. + typedef u_char Node_ID[NODE_ID_SIZE]; + + /// Get the node id + Node_ID & node_ID (void); + + /** + * @overload + */ + const Node_ID & node_ID (void) const; + + /// Test for equality. + bool operator == (const UUID_Node & right) const; + + /// Test for inequality. + bool operator != (const UUID_Node & right) const; + + private: + /// The value of the node id. + Node_ID node_ID_; + }; + + /** + * @class ACE_UUID + * + * ACE_UUID represents a Universally Unique IDentifier (UUID) as + * described in (the expired) INTERNET-DRAFT specification entitled + * UUIDs and GUIDs. All instances of UUID are of the time-based + * variety. That is, the version number part of the timeHiAndVersion + * field is 1. + * + * The default constructor creates a nil UUID. + * + * UUIDs have value semantics. In addition, they may be compared for + * ordering and equality. + * + * Additionally in this implementation provisions have been made to include + * process and thread ids to make the UUIDs more unique. The variant 0xc0 + * has been added to facilitate this. + */ + class ACE_Export UUID + { + public: + /// The size of a binary UUID. + enum { BINARY_SIZE = 16 }; + + /// Constructor + UUID (void); + + /// Constructs a UUID from a string representation. + UUID (const ACE_CString& uuidString); + + UUID (const UUID &right); + + // Destructor + ~UUID (void); + + ACE_UINT32 time_low (void) const; + void time_low (ACE_UINT32); + + ACE_UINT16 time_mid (void) const; + void time_mid (ACE_UINT16); + + ACE_UINT16 time_hi_and_version (void) const; + void time_hi_and_version (ACE_UINT16); + + u_char clock_seq_hi_and_reserved (void) const; + void clock_seq_hi_and_reserved (u_char); + + u_char clock_seq_low (void) const; + void clock_seq_low (u_char); + + UUID_Node & node (void); + const UUID_Node & node (void) const; + + void node (const UUID_Node & node); + + ACE_CString* thr_id (void); + void thr_id (char*); + + ACE_CString* pid (void); + void pid (char*); + + /// Returns a string representation of the UUID + const ACE_CString* to_string (void) const; + + /// Set the value using a string + void from_string (const ACE_CString& uuid_string); + + /// NIL UUID + static const UUID NIL_UUID; + + /// Equality Operations + bool operator == (const UUID &right) const; + bool operator != (const UUID &right) const; + + /// Compute a hash value for the UUID. + unsigned long hash (void) const; + + /// Assign an existing UUID to this UUID. + const UUID & operator = (const UUID & rhs); + + private: + /// Initialize the UUID + void init (void); + + /** + * Helper method to convert from a string UUID. + * + * @param[in] uuid_string String version of UUID. + */ + void from_string_i (const ACE_CString& uuid_string); + + /// Data Members for Class Attributes + struct data + { + /// Time low. + ACE_UINT32 time_low_; + + /// Time mid. + ACE_UINT16 time_mid_; + + /// Time high and version. + ACE_UINT16 time_hi_and_version_; + + /// Clock sequence high and reserved space. + u_char clock_seq_hi_and_reserved_; + + /// Clock sequence low. + u_char clock_seq_low_; + + /// MAC-address within the UUID. + UUID_Node node_; + } uuid_; + + ACE_CString thr_id_; + ACE_CString pid_; + + /// The string representation of the UUID. This is created and + /// updated only on demand. + mutable ACE_Auto_Ptr as_string_; + }; + + /** + * @class ACE_UUID_Generator + * + * Singleton class that generates UUIDs. + * + */ + class ACE_Export UUID_Generator + { + public: + + enum {ACE_UUID_CLOCK_SEQ_MASK = 0x3FFF}; + + /// Default constructor. + UUID_Generator(void); + + /// Destructor. + ~UUID_Generator(); + + /// Initialize the UUID generator + /// @deprecated This method may go away in some future release. + void init (void); + + /// Format timestamp, clockseq, and nodeID into an UUID of the + /// specified version and variant. For generating UUID's with + /// thread and process ids use variant=0xc0 + void generate_UUID (UUID&, ACE_UINT16 version=0x0001, u_char variant=0x80); + + /// Format timestamp, clockseq, and nodeID into a VI UUID. For + /// generating UUID's with thread and process ids use variant=0xc0 + UUID* generate_UUID (ACE_UINT16 version=0x0001, u_char variant=0x80); + + /// Type to represent UTC as a count of 100 nanosecond intervals + /// since 00:00:00.00, 15 October 1582. + typedef ACE_UINT64 UUID_Time; + + /// The locking strategy prevents multiple generators from accessing + /// the UUID_state at the same time. Get the locking strategy. + ACE_SYNCH_MUTEX* lock (void); + + /// Set a new locking strategy and return the old one. + void lock (ACE_SYNCH_MUTEX* lock, bool release_lock); + + private: + /// The system time when that last uuid was generated. + UUID_Time time_last_; + + /// Type to contain the UUID generator persistent state. This will + /// be kept in memory mapped shared memory + struct UUID_State + { + UUID_Time timestamp; + UUID_Node node; + ACE_UINT16 clock_sequence; + }; + + /// Obtain a UUID timestamp. Compensate for the fact that the time + /// obtained from getSystem time has a resolution less than 100ns. + void get_timestamp (UUID_Time& timestamp); + + /// Obtain a UUID timestamp and clock sequence. Compensate for the + /// fact that the time obtained from getSystem time has a + /// resolution less than 100ns. + void get_timestamp_and_clocksequence (UUID_Time& timestamp, + ACE_UINT16& clockSequence); + + /// Obtain the system time in UTC as a count of 100 nanosecond intervals + /// since 00:00:00.00, 15 October 1582 (the date of Gregorian reform to + /// the Christian calendar). + void get_systemtime( UUID_Time& timeNow); + + /// The UUID generator persistent state. + UUID_State uuid_state_; + + ACE_SYNCH_MUTEX* lock_; + + bool destroy_lock_; + + /// Initalization state of the generator. + bool is_init_; + }; + + typedef ACE_Singleton + UUID_GENERATOR; +} + +ACE_SINGLETON_DECLARE (ACE_Singleton, ACE_Utils::UUID_Generator, ACE_SYNCH_MUTEX) + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/UUID.inl" +#endif /* __ACE_INLINE__ */ + +#include /**/ "ace/post.h" +#endif // ACE_UUID_H + diff --git a/dep/acelite/ace/UUID.inl b/dep/acelite/ace/UUID.inl new file mode 100644 index 00000000000..568adfa00d0 --- /dev/null +++ b/dep/acelite/ace/UUID.inl @@ -0,0 +1,204 @@ +// -*- C++ -*- +// +//$Id: UUID.inl 85331 2009-05-14 00:04:12Z hillj $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +namespace ACE_Utils +{ + ACE_INLINE + const UUID_Node::Node_ID & UUID_Node::node_ID (void) const + { + return this->node_ID_; + } + + ACE_INLINE + UUID_Node::Node_ID & UUID_Node::node_ID (void) + { + return this->node_ID_; + } + + ACE_INLINE + UUID::UUID (void) + { + this->init (); + } + + ACE_INLINE + UUID::UUID (const UUID &right) + : thr_id_ (right.thr_id_), + pid_ (right.pid_) + { + ACE_OS::memcpy (&this->uuid_, &right.uuid_, BINARY_SIZE); + } + + ACE_INLINE + UUID::~UUID (void) + { + + } + + ACE_INLINE void + UUID::init (void) + { + ACE_OS::memset (&this->uuid_, 0, BINARY_SIZE); + } + + ACE_INLINE unsigned long + UUID::hash (void) const + { + return ACE::hash_pjw (reinterpret_cast (&this->uuid_), + UUID::BINARY_SIZE); + } + + ACE_INLINE ACE_UINT32 + UUID::time_low (void) const + { + return this->uuid_.time_low_; + } + + ACE_INLINE void + UUID::time_low (ACE_UINT32 timelow) + { + this->uuid_.time_low_ = timelow; + } + + ACE_INLINE ACE_UINT16 + UUID::time_mid (void) const + { + return this->uuid_.time_mid_; + } + + ACE_INLINE void + UUID::time_mid (ACE_UINT16 time_mid) + { + this->uuid_.time_mid_ = time_mid; + } + + ACE_INLINE ACE_UINT16 + UUID::time_hi_and_version (void) const + { + return this->uuid_.time_hi_and_version_; + } + + ACE_INLINE void + UUID::time_hi_and_version (ACE_UINT16 time_hi_and_version) + { + this->uuid_.time_hi_and_version_ = time_hi_and_version; + } + + ACE_INLINE u_char + UUID::clock_seq_hi_and_reserved (void) const + { + return this->uuid_.clock_seq_hi_and_reserved_; + } + + ACE_INLINE void + UUID::clock_seq_hi_and_reserved (u_char clock_seq_hi_and_reserved) + { + this->uuid_.clock_seq_hi_and_reserved_ = clock_seq_hi_and_reserved; + } + + ACE_INLINE u_char + UUID::clock_seq_low (void) const + { + return this->uuid_.clock_seq_low_; + } + + ACE_INLINE void + UUID::clock_seq_low (u_char clock_seq_low) + { + this->uuid_.clock_seq_low_ = clock_seq_low; + } + + ACE_INLINE const UUID_Node & + UUID::node (void) const + { + return this->uuid_.node_; + } + + ACE_INLINE UUID_Node & + UUID::node (void) + { + return this->uuid_.node_; + } + + ACE_INLINE void + UUID::node (const UUID_Node & node) + { + ACE_OS::memcpy (&this->uuid_.node_, + node.node_ID (), + UUID_Node::NODE_ID_SIZE); + } + + ACE_INLINE ACE_CString* + UUID::thr_id (void) + { + return &this->thr_id_; + } + + ACE_INLINE void + UUID::thr_id (char* thr_id) + { + this->thr_id_ = thr_id; + } + + ACE_INLINE ACE_CString* + UUID::pid (void) + { + return &this->pid_; + } + + ACE_INLINE void + UUID::pid (char* pid) + { + this->pid_ = pid; + } + + ACE_INLINE void + UUID::from_string (const ACE_CString& uuidString) + { + this->from_string_i (uuidString); + } + + ACE_INLINE bool + UUID::operator == (const UUID &right) const + { + return 0 == ACE_OS::memcmp (&this->uuid_, &right.uuid_, BINARY_SIZE); + } + + ACE_INLINE bool + UUID::operator != (const UUID &right) const + { + return 0 != ACE_OS::memcmp (&this->uuid_, &right.uuid_, BINARY_SIZE); + } + + ACE_INLINE bool + UUID_Node::operator == (const UUID_Node& rt) const + { + for (size_t i = 0; i < NODE_ID_SIZE; ++i) + if (node_ID_ [i] != rt.node_ID_ [i]) + return false; + + return true; + } + + ACE_INLINE bool + UUID_Node::operator != (const UUID_Node& right) const + { + return !(*this == right); + } + +// ACE_INLINE bool +// UUID_node::operator < (const UUID_node& rt) const +// { +// UUID_node right = rt; +// for (size_t i = 0; i < NODE_ID_SIZE; ++i) +// if (nodeID_ [i] < right.nodeID ()[i]) +// return true; +// +// return false; +// } +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Unbounded_Queue.cpp b/dep/acelite/ace/Unbounded_Queue.cpp new file mode 100644 index 00000000000..2890650fbe1 --- /dev/null +++ b/dep/acelite/ace/Unbounded_Queue.cpp @@ -0,0 +1,433 @@ +// $Id: Unbounded_Queue.cpp 82723 2008-09-16 09:35:44Z johnnyw $ + +#ifndef ACE_UNBOUNDED_QUEUE_CPP +#define ACE_UNBOUNDED_QUEUE_CPP + +#include "ace/Unbounded_Queue.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (__ACE_INLINE__) +#include "ace/Unbounded_Queue.inl" +#endif /* __ACE_INLINE__ */ + +#include "ace/Malloc_Base.h" +#include "ace/Log_Msg.h" +#include "ace/os_include/os_errno.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Unbounded_Queue) + +template +ACE_Unbounded_Queue::ACE_Unbounded_Queue (ACE_Allocator *alloc) + : head_ (0), + cur_size_ (0), + allocator_ (alloc) +{ + // ACE_TRACE ("ACE_Unbounded_Queue::ACE_Unbounded_Queue (void)"); + + if (this->allocator_ == 0) + this->allocator_ = ACE_Allocator::instance (); + + ACE_NEW_MALLOC (this->head_, + (ACE_Node *) this->allocator_->malloc (sizeof (ACE_Node)), + ACE_Node); + // Make the list circular by pointing it back to itself. + this->head_->next_ = this->head_; +} + +template +ACE_Unbounded_Queue::ACE_Unbounded_Queue (const ACE_Unbounded_Queue &us) + : head_ (0), + cur_size_ (0), + allocator_ (us.allocator_) +{ + // ACE_TRACE ("ACE_Unbounded_Queue::ACE_Unbounded_Queue"); + + if (this->allocator_ == 0) + this->allocator_ = ACE_Allocator::instance (); + + ACE_NEW_MALLOC (this->head_, + (ACE_Node *) this->allocator_->malloc (sizeof (ACE_Node)), + ACE_Node); + this->head_->next_ = this->head_; + this->copy_nodes (us); +} + +template void +ACE_Unbounded_Queue::operator= (const ACE_Unbounded_Queue &us) +{ + // ACE_TRACE ("ACE_Unbounded_Queue::operator="); + + if (this != &us) + { + this->delete_nodes (); + this->copy_nodes (us); + } +} + +template ACE_Unbounded_Queue_Iterator +ACE_Unbounded_Queue::begin (void) +{ + // ACE_TRACE ("ACE_Unbounded_Queue::begin"); + return ACE_Unbounded_Queue_Iterator (*this); +} + +template ACE_Unbounded_Queue_Iterator +ACE_Unbounded_Queue::end (void) +{ + // ACE_TRACE ("ACE_Unbounded_Queue::end"); + return ACE_Unbounded_Queue_Iterator (*this, 1); +} + +template void +ACE_Unbounded_Queue::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + // ACE_TRACE ("ACE_Unbounded_Queue::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nhead_ = %u"), this->head_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nhead_->next_ = %u"), this->head_->next_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ncur_size_ = %d\n"), this->cur_size_)); + + T *item = 0; +#if !defined (ACE_NLOGGING) + size_t count = 1; +#endif /* ! ACE_NLOGGING */ + + for (ACE_Unbounded_Queue_Iterator iter (*(ACE_Unbounded_Queue *) this); + iter.next (item) != 0; + iter.advance ()) + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("count = %d\n"), count++)); + + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +template void +ACE_Unbounded_Queue::copy_nodes (const ACE_Unbounded_Queue &us) +{ + for (ACE_Node *curr = us.head_->next_; + curr != us.head_; + curr = curr->next_) + if (this->enqueue_tail (curr->item_) == -1) + // @@ What's the right thing to do here? + this->delete_nodes (); +} + +template void +ACE_Unbounded_Queue::delete_nodes (void) +{ + for (ACE_Node *curr = this->head_->next_; + // Keep looking until we've hit the dummy node. + curr != this->head_; + ) + { + ACE_Node *temp = curr; + curr = curr->next_; + + ACE_DES_FREE_TEMPLATE (temp, + this->allocator_->free, + ACE_Node, + ); + --this->cur_size_; + // @@ Doesnt make sense to have this check since + // this will always be true. + // ACE_ASSERT (this->cur_size_ >= 0); + } + + // Reset the list to be a circular list with just a dummy node. + this->head_->next_ = this->head_; +} + +template +ACE_Unbounded_Queue::~ACE_Unbounded_Queue (void) +{ + // ACE_TRACE ("ACE_Unbounded_Queue::~ACE_Unbounded_Queue (void)"); + + this->delete_nodes (); + ACE_DES_FREE_TEMPLATE (head_, + this->allocator_->free, + ACE_Node, + ); +} + +template int +ACE_Unbounded_Queue::enqueue_head (const T &new_item) +{ + // ACE_TRACE ("ACE_Unbounded_Queue::enqueue_head"); + + ACE_Node *temp = 0; + + // Create a new node that points to the original head. + ACE_NEW_MALLOC_RETURN (temp, + static_cast *> (this->allocator_->malloc (sizeof (ACE_Node))), + ACE_Node (new_item, this->head_->next_), + -1); + // Link this pointer into the front of the list. Note that the + // "real" head of the queue is next_>, whereas is + // just a pointer to the dummy node. + this->head_->next_ = temp; + + ++this->cur_size_; + return 0; +} + +template int +ACE_Unbounded_Queue::enqueue_tail (const T &new_item) +{ + // ACE_TRACE ("ACE_Unbounded_Queue::enqueue_tail"); + + // Insert into the old dummy node location. Note that this + // isn't actually the "head" item in the queue, it's a dummy node at + // the "tail" of the queue... + this->head_->item_ = new_item; + + ACE_Node *temp = 0; + + // Create a new dummy node. + ACE_NEW_MALLOC_RETURN (temp, + static_cast *> (this->allocator_->malloc (sizeof (ACE_Node))), + ACE_Node (this->head_->next_), + -1); + // Link this dummy pointer into the list. + this->head_->next_ = temp; + + // Point the head to the new dummy node. + this->head_ = temp; + + ++this->cur_size_; + return 0; +} + +template int +ACE_Unbounded_Queue::dequeue_head (T &item) +{ + // ACE_TRACE ("ACE_Unbounded_Queue::dequeue_head"); + + // Check for empty queue. + if (this->is_empty ()) + return -1; + + ACE_Node *temp = this->head_->next_; + + item = temp->item_; + this->head_->next_ = temp->next_; + ACE_DES_FREE_TEMPLATE (temp, + this->allocator_->free, + ACE_Node, + ); + --this->cur_size_; + return 0; +} + +template void +ACE_Unbounded_Queue::reset (void) +{ + ACE_TRACE ("reset"); + + this->delete_nodes (); +} + +template int +ACE_Unbounded_Queue::get (T *&item, size_t slot) const +{ + // ACE_TRACE ("ACE_Unbounded_Queue::get"); + + ACE_Node *curr = this->head_->next_; + + size_t i; + + for (i = 0; i < this->cur_size_; i++) + { + if (i == slot) + break; + + curr = curr->next_; + } + + if (i < this->cur_size_) + { + item = &curr->item_; + return 0; + } + else + return -1; +} + +template int +ACE_Unbounded_Queue::set (const T &item, + size_t slot) +{ + // ACE_TRACE ("ACE_Unbounded_Queue::set"); + + ACE_Node *curr = this->head_->next_; + + size_t i; + + for (i = 0; + i < slot && i < this->cur_size_; + ++i) + curr = curr->next_; + + if (i < this->cur_size_) + { + // We're in range, so everything's cool. + curr->item_ = item; + return 0; + } + else + { + // We need to expand the list. + + // A common case will be increasing the set size by 1. + // Therefore, we'll optimize for this case. + if (i == slot) + { + // Try to expand the size of the set by 1. + if (this->enqueue_tail (item) == -1) + return -1; + else + return 0; + } + else + { + T const dummy = T (); + + // We need to expand the list by multiple (dummy) items. + for (; i < slot; ++i) + { + // This head points to the existing dummy node, which is + // about to be overwritten when we add the new dummy + // node. + curr = this->head_; + + // Try to expand the size of the set by 1, but don't + // store anything in the dummy node (yet). + if (this->enqueue_tail (dummy) == -1) + return -1; + } + + curr->item_ = item; + return 0; + } + } +} + +// **************************************************************** + +template void +ACE_Unbounded_Queue_Const_Iterator::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + // ACE_TRACE ("ACE_Unbounded_Queue_Const_Iterator::dump"); +#endif /* ACE_HAS_DUMP */ +} + +template +ACE_Unbounded_Queue_Const_Iterator::ACE_Unbounded_Queue_Const_Iterator (const ACE_Unbounded_Queue &q, int end) + : current_ (end == 0 ? q.head_->next_ : q.head_ ), + queue_ (q) +{ + // ACE_TRACE ("ACE_Unbounded_Queue_Const_Iterator::ACE_Unbounded_Queue_Const_Iterator"); +} + +template int +ACE_Unbounded_Queue_Const_Iterator::advance (void) +{ + // ACE_TRACE ("ACE_Unbounded_Queue_Const_Iterator::advance"); + this->current_ = this->current_->next_; + return this->current_ != this->queue_.head_; +} + +template int +ACE_Unbounded_Queue_Const_Iterator::first (void) +{ + // ACE_TRACE ("ACE_Unbounded_Queue_Const_Iterator::first"); + this->current_ = this->queue_.head_->next_; + return this->current_ != this->queue_.head_; +} + +template int +ACE_Unbounded_Queue_Const_Iterator::done (void) const +{ + ACE_TRACE ("ACE_Unbounded_Queue_Const_Iterator::done"); + + return this->current_ == this->queue_.head_; +} + +template int +ACE_Unbounded_Queue_Const_Iterator::next (T *&item) +{ + // ACE_TRACE ("ACE_Unbounded_Queue_Const_Iterator::next"); + if (this->current_ == this->queue_.head_) + return 0; + else + { + item = &this->current_->item_; + return 1; + } +} + +// **************************************************************** + +template void +ACE_Unbounded_Queue_Iterator::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + // ACE_TRACE ("ACE_Unbounded_Queue_Iterator::dump"); +#endif /* ACE_HAS_DUMP */ +} + +template +ACE_Unbounded_Queue_Iterator::ACE_Unbounded_Queue_Iterator (ACE_Unbounded_Queue &q, int end) + : current_ (end == 0 ? q.head_->next_ : q.head_ ), + queue_ (q) +{ + // ACE_TRACE ("ACE_Unbounded_Queue_Iterator::ACE_Unbounded_Queue_Iterator"); +} + +template int +ACE_Unbounded_Queue_Iterator::advance (void) +{ + // ACE_TRACE ("ACE_Unbounded_Queue_Iterator::advance"); + this->current_ = this->current_->next_; + return this->current_ != this->queue_.head_; +} + +template int +ACE_Unbounded_Queue_Iterator::first (void) +{ + // ACE_TRACE ("ACE_Unbounded_Queue_Iterator::first"); + this->current_ = this->queue_.head_->next_; + return this->current_ != this->queue_.head_; +} + +template int +ACE_Unbounded_Queue_Iterator::done (void) const +{ + ACE_TRACE ("ACE_Unbounded_Queue_Iterator::done"); + + return this->current_ == this->queue_.head_; +} + +template int +ACE_Unbounded_Queue_Iterator::next (T *&item) +{ + // ACE_TRACE ("ACE_Unbounded_Queue_Iterator::next"); + if (this->current_ == this->queue_.head_) + return 0; + else + { + item = &this->current_->item_; + return 1; + } +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_UNBOUNDED_QUEUE_CPP */ diff --git a/dep/acelite/ace/Unbounded_Queue.h b/dep/acelite/ace/Unbounded_Queue.h new file mode 100644 index 00000000000..65be7aaaec6 --- /dev/null +++ b/dep/acelite/ace/Unbounded_Queue.h @@ -0,0 +1,297 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Unbounded_Queue.h + * + * $Id: Unbounded_Queue.h 84316 2009-02-03 19:46:05Z johnnyw $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_UNBOUNDED_QUEUE_H +#define ACE_UNBOUNDED_QUEUE_H +#include /**/ "ace/pre.h" + +#include "ace/Node.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/os_stddef.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +class ACE_Allocator; + +template +class ACE_Unbounded_Queue; + +/** + * @class ACE_Unbounded_Queue_Iterator + * + * @brief Implement an iterator over an unbounded queue. + */ +template +class ACE_Unbounded_Queue_Iterator +{ +public: + // = Initialization method. + ACE_Unbounded_Queue_Iterator (ACE_Unbounded_Queue &q, int end = 0); + + // = Iteration methods. + + /// Pass back the @a next_item that hasn't been seen in the queue. + /// Returns 0 when all items have been seen, else 1. + int next (T *&next_item); + + /// Move forward by one element in the set. Returns 0 when all the + /// items in the queue have been seen, else 1. + int advance (void); + + /// Move to the first element in the queue. Returns 0 if the + /// queue is empty, else 1. + int first (void); + + /// Returns 1 when all items have been seen, else 0. + int done (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + /// Pointer to the current node in the iteration. + ACE_Node *current_; + + /// Pointer to the queue we're iterating over. + ACE_Unbounded_Queue &queue_; +}; + +/** + * @class ACE_Unbounded_Queue_Const_Iterator + * + * @brief Implement an iterator over an const unbounded queue. + */ +template +class ACE_Unbounded_Queue_Const_Iterator +{ +public: + // = Initialization method. + ACE_Unbounded_Queue_Const_Iterator (const ACE_Unbounded_Queue &q, int end = 0); + + // = Iteration methods. + + /// Pass back the @a next_item that hasn't been seen in the queue. + /// Returns 0 when all items have been seen, else 1. + int next (T *&next_item); + + /// Move forward by one element in the set. Returns 0 when all the + /// items in the queue have been seen, else 1. + int advance (void); + + /// Move to the first element in the queue. Returns 0 if the + /// queue is empty, else 1. + int first (void); + + /// Returns 1 when all items have been seen, else 0. + int done (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + /// Pointer to the current node in the iteration. + ACE_Node *current_; + + /// Pointer to the queue we're iterating over. + const ACE_Unbounded_Queue &queue_; +}; + +/** + * @class ACE_Unbounded_Queue + * + * @brief A Queue of "infinite" length. + * + * This implementation of an unbounded queue uses a circular + * linked list with a dummy node. + * + * Requirements and Performance Characteristics + * - Internal Structure + * Circular linked list + * - Duplicates allowed? + * Yes + * - Random access allowed? + * No + * - Search speed + * N/A + * - Insert/replace speed + * N/A + * - Iterator still valid after change to container? + * Yes + * - Frees memory for removed elements? + * Yes + * - Items inserted by + * Value + * - Requirements for contained type + * -# Default constructor + * -# Copy constructor + * -# operator= + * + */ +template +class ACE_Unbounded_Queue +{ +public: + friend class ACE_Unbounded_Queue_Iterator; + friend class ACE_Unbounded_Queue_Const_Iterator; + + // Trait definition. + typedef ACE_Unbounded_Queue_Iterator ITERATOR; + typedef ACE_Unbounded_Queue_Const_Iterator CONST_ITERATOR; + + // = Initialization and termination methods. + /// Construction. Use user specified allocation strategy + /// if specified. + /** + * Initialize an empty queue using the strategy provided. + */ + ACE_Unbounded_Queue (ACE_Allocator *alloc = 0); + + /// Copy constructor. + /** + * Initialize the queue to be a copy of the provided queue. + */ + ACE_Unbounded_Queue (const ACE_Unbounded_Queue &); + + /// Assignment operator. + /** + * Perform a deep copy of rhs. + */ + void operator= (const ACE_Unbounded_Queue &); + + /// Destructor. + /** + * Clean up the memory for the queue. + */ + ~ACE_Unbounded_Queue (void); + + // = Check boundary conditions. + + /// Returns true if the container is empty, otherwise returns false. + /** + * Constant time check to see if the queue is empty. + */ + bool is_empty (void) const; + + /// Returns 0. + /** + * The queue cannot be full, so it always returns 0. + */ + bool is_full (void) const; + + // = Classic queue operations. + + /// Adds @a new_item to the tail of the queue. Returns 0 on success, + /// -1 on failure. + /** + * Insert an item at the end of the queue. + */ + int enqueue_tail (const T &new_item); + + /// Adds @a new_item to the head of the queue. Returns 0 on success, + /// -1 on failure. + /** + * Insert an item at the head of the queue. + */ + int enqueue_head (const T &new_item); + + /// Removes and returns the first @a item on the queue. Returns 0 on + /// success, -1 if the queue was empty. + /** + * Remove an item from the head of the queue. + */ + int dequeue_head (T &item); + + // = Additional utility methods. + + /// Reset the ACE_Unbounded_Queue to be empty and release all its + /// dynamically allocated resources. + /** + * Delete the queue nodes. + */ + void reset (void); + + /// Get the @a slot th element in the set. Returns -1 if the element + /// isn't in the range {0..#cur_size_ - 1}, else 0. + /** + * Find the item in the queue between 0 and the provided index of the + * queue. + */ + int get (T *&item, size_t slot = 0) const; + + /// Set the @a slot th element of the queue to @a item. + /** + * Set the @a slot th element in the set. Will pad out the set with + * empty nodes if @a slot is beyond the range {0..#cur_size_ - 1}. + * Returns -1 on failure, 0 if @a slot isn't initially in range, and + * 0 otherwise. + */ + int set (const T &item, size_t slot); + + /// The number of items in the queue. + /** + * Return the size of the queue. + */ + size_t size (void) const; + + /// Dump the state of an object. + void dump (void) const; + + // = STL-styled unidirectional iterator factory. + ACE_Unbounded_Queue_Iterator begin (void); + ACE_Unbounded_Queue_Iterator end (void); + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +protected: + /// Delete all the nodes in the queue. + void delete_nodes (void); + + /// Copy nodes into this queue. + void copy_nodes (const ACE_Unbounded_Queue &); + + /// Pointer to the dummy node in the circular linked Queue. + ACE_Node *head_; + + /// Current size of the queue. + size_t cur_size_; + + /// Allocation Strategy of the queue. + ACE_Allocator *allocator_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Unbounded_Queue.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Unbounded_Queue.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Unbounded_Queue.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" +#endif /* ACE_UNBOUNDED_QUEUE_H */ diff --git a/dep/acelite/ace/Unbounded_Queue.inl b/dep/acelite/ace/Unbounded_Queue.inl new file mode 100644 index 00000000000..81e3ded3e04 --- /dev/null +++ b/dep/acelite/ace/Unbounded_Queue.inl @@ -0,0 +1,27 @@ +// -*- C++ -*- +// +// $Id: Unbounded_Queue.inl 84316 2009-02-03 19:46:05Z johnnyw $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template ACE_INLINE size_t +ACE_Unbounded_Queue::size (void) const +{ + return this->cur_size_; +} + +template ACE_INLINE bool +ACE_Unbounded_Queue::is_empty (void) const +{ + // ACE_TRACE ("ACE_Unbounded_Queue::is_empty"); + return this->head_ == this->head_->next_; +} + +template ACE_INLINE bool +ACE_Unbounded_Queue::is_full (void) const +{ + // ACE_TRACE ("ACE_Unbounded_Queue::is_full"); + return false; // We should implement a "node of last resort for this..." +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Unbounded_Set.cpp b/dep/acelite/ace/Unbounded_Set.cpp new file mode 100644 index 00000000000..c54e3fcfa2f --- /dev/null +++ b/dep/acelite/ace/Unbounded_Set.cpp @@ -0,0 +1,18 @@ +// $Id: Unbounded_Set.cpp 81624 2008-05-06 17:14:57Z wotte $ + +#ifndef ACE_UNBOUNDED_SET_CPP +#define ACE_UNBOUNDED_SET_CPP + +#include "ace/Unbounded_Set.h" +#include "ace/Malloc_Base.h" +#include "ace/Log_Msg.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (__ACE_INLINE__) +#include "ace/Unbounded_Set.inl" +#endif /* __ACE_INLINE__ */ + +#endif /* ACE_UNBOUNDED_SET_CPP */ diff --git a/dep/acelite/ace/Unbounded_Set.h b/dep/acelite/ace/Unbounded_Set.h new file mode 100644 index 00000000000..a75eac18fc3 --- /dev/null +++ b/dep/acelite/ace/Unbounded_Set.h @@ -0,0 +1,103 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Unbounded_Set.h + * + * $Id: Unbounded_Set.h 81642 2008-05-07 19:30:35Z shuston $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_UNBOUNDED_SET_H +#define ACE_UNBOUNDED_SET_H +#include /**/ "ace/pre.h" + +#include "ace/Unbounded_Set_Ex.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +class ACE_Allocator; + +/** + * @struct ACE_Unbounded_Set_Default_Comparator + * @brief Simple comparator that evaluates equality using == operator. + */ +template +struct ACE_Unbounded_Set_Default_Comparator +{ + bool operator() (const T&lhs, const T&rhs) const; +}; + +template +class ACE_Unbounded_Set; + +/** + * @class ACE_Unbounded_Set_Iterator + * @brief Compatibility wrapper for ACE_Unbounded_Set_Ex_Iterator. + */ +template +class ACE_Unbounded_Set_Iterator : public + ACE_Unbounded_Set_Ex_Iterator > +{ +public: + typedef ACE_Unbounded_Set_Ex_Iterator > base_type; + + // = Initialization method. + ACE_Unbounded_Set_Iterator (ACE_Unbounded_Set &s, bool end = false); + + ACE_Unbounded_Set_Iterator (const base_type &s); +}; + +/** + * @class ACE_Unbounded_Set_Const_Iterator + * @brief Compatibility wrapper for ACE_Unbounded_Set_Ex_Const_Iterator. + */ +template +class ACE_Unbounded_Set_Const_Iterator : public + ACE_Unbounded_Set_Ex_Const_Iterator > +{ +public: + + typedef ACE_Unbounded_Set_Ex_Const_Iterator > base_type; + + // = Initialization method. + ACE_Unbounded_Set_Const_Iterator (const ACE_Unbounded_Set &s, + bool end = false); + + ACE_Unbounded_Set_Const_Iterator (const base_type &s); +}; + +/** + * @class ACE_Unbounded_Set + * @brief Compatibility wrapper for ACE_Unbounded_Set_Ex. + */ +template +class ACE_Unbounded_Set : public + ACE_Unbounded_Set_Ex > +{ +public: + ACE_Unbounded_Set (ACE_Allocator *alloc = 0); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Unbounded_Set.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Unbounded_Set.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Unbounded_Set.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" +#endif /* ACE_UNBOUNDED_SET_H */ diff --git a/dep/acelite/ace/Unbounded_Set.inl b/dep/acelite/ace/Unbounded_Set.inl new file mode 100644 index 00000000000..365b025c0be --- /dev/null +++ b/dep/acelite/ace/Unbounded_Set.inl @@ -0,0 +1,49 @@ +// -*- C++ -*- +// +// $Id: Unbounded_Set.inl 81642 2008-05-07 19:30:35Z shuston $ + +#include "ace/Global_Macros.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template ACE_INLINE bool +ACE_Unbounded_Set_Default_Comparator::operator () (const T &lhs, const T &rhs) const +{ + return lhs == rhs; +} + +template +ACE_Unbounded_Set_Iterator::ACE_Unbounded_Set_Iterator (ACE_Unbounded_Set &s, + bool end) + : base_type (s, end) +{ +} + +template +ACE_Unbounded_Set_Iterator::ACE_Unbounded_Set_Iterator (const base_type & s) + : base_type (s) +{ +} + +template +ACE_Unbounded_Set_Const_Iterator:: +ACE_Unbounded_Set_Const_Iterator (const ACE_Unbounded_Set &s, + bool end) + : base_type (s, end) +{ +} + +template +ACE_Unbounded_Set_Const_Iterator::ACE_Unbounded_Set_Const_Iterator (const base_type & s) + : base_type (s) +{ +} + +template +ACE_Unbounded_Set::ACE_Unbounded_Set (ACE_Allocator *alloc) + : ACE_Unbounded_Set_Ex > (alloc) +{ +} + + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Unbounded_Set_Ex.cpp b/dep/acelite/ace/Unbounded_Set_Ex.cpp new file mode 100644 index 00000000000..c5cd9e27b21 --- /dev/null +++ b/dep/acelite/ace/Unbounded_Set_Ex.cpp @@ -0,0 +1,499 @@ +// $Id: Unbounded_Set_Ex.cpp 81702 2008-05-15 10:18:07Z johnnyw $ + +#ifndef ACE_UNBOUNDED_SET_EX_CPP +#define ACE_UNBOUNDED_SET_EX_CPP + +#include "ace/Unbounded_Set.h" +#include "ace/Malloc_Base.h" +#include "ace/Log_Msg.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (__ACE_INLINE__) +#include "ace/Unbounded_Set_Ex.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Unbounded_Set_Ex) + +template size_t +ACE_Unbounded_Set_Ex::size (void) const +{ + // ACE_TRACE ("ACE_Unbounded_Set_Ex::size"); + return this->cur_size_; +} + +template int +ACE_Unbounded_Set_Ex::insert_tail (const T &item) +{ + // ACE_TRACE ("ACE_Unbounded_Set_Ex::insert_tail"); + NODE *temp = 0; + + // Insert into the old dummy node location. + this->head_->item_ = item; + + // Create a new dummy node. + ACE_NEW_MALLOC_RETURN (temp, + static_cast (this->allocator_->malloc (sizeof (NODE))), + NODE (this->head_->next_), + -1); + // Link this pointer into the list. + this->head_->next_ = temp; + + // Point the head to the new dummy node. + this->head_ = temp; + + ++this->cur_size_; + return 0; +} + +template void +ACE_Unbounded_Set_Ex::reset (void) +{ + ACE_TRACE ("reset"); + + this->delete_nodes (); +} + +template void +ACE_Unbounded_Set_Ex::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Unbounded_Set_Ex::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nhead_ = %u"), this->head_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nhead_->next_ = %u"), this->head_->next_)); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ncur_size_ = %d\n"), this->cur_size_)); + + T *item = 0; +#if !defined (ACE_NLOGGING) + size_t count = 1; +#endif /* ! ACE_NLOGGING */ + + const_iterator const the_end = this->end (); + for (const_iterator i (this->begin ()); + i != end; + ++i) + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("count = %u\n"), count++)); + + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +template void +ACE_Unbounded_Set_Ex::copy_nodes (const ACE_Unbounded_Set_Ex &us) +{ + for (NODE *curr = us.head_->next_; + curr != us.head_; + curr = curr->next_) + this->insert_tail (curr->item_); +} + +template void +ACE_Unbounded_Set_Ex::delete_nodes (void) +{ + NODE *curr = this->head_->next_; + + // Keep looking until we've hit the dummy node. + + while (curr != this->head_) + { + NODE *temp = curr; + curr = curr->next_; + ACE_DES_FREE_TEMPLATE2 (temp, + this->allocator_->free, + ACE_Node, + T, C); + --this->cur_size_; + } + + // Reset the list to be a circular list with just a dummy node. + this->head_->next_ = this->head_; +} + +template +ACE_Unbounded_Set_Ex::~ACE_Unbounded_Set_Ex (void) +{ + // ACE_TRACE ("ACE_Unbounded_Set_Ex::~ACE_Unbounded_Set_Ex"); + + this->delete_nodes (); + + // Delete the dummy node. + ACE_DES_FREE_TEMPLATE2 (head_, + this->allocator_->free, + ACE_Node, + T, C); + this->head_ = 0; +} + +template +ACE_Unbounded_Set_Ex::ACE_Unbounded_Set_Ex (ACE_Allocator *alloc) + : head_ (0), + cur_size_ (0), + allocator_ (alloc) +{ + // ACE_TRACE ("ACE_Unbounded_Set_Ex::ACE_Unbounded_Set_Ex"); + + if (this->allocator_ == 0) + this->allocator_ = ACE_Allocator::instance (); + + ACE_NEW_MALLOC (this->head_, + (NODE*) this->allocator_->malloc (sizeof (NODE)), + NODE); + // Make the list circular by pointing it back to itself. + this->head_->next_ = this->head_; +} + +template +ACE_Unbounded_Set_Ex::ACE_Unbounded_Set_Ex (const C &comp, + ACE_Allocator *alloc) + : head_ (0), + cur_size_ (0), + allocator_ (alloc), + comp_ (comp) +{ + // ACE_TRACE ("ACE_Unbounded_Set_Ex::ACE_Unbounded_Set_Ex"); + + if (this->allocator_ == 0) + this->allocator_ = ACE_Allocator::instance (); + + ACE_NEW_MALLOC (this->head_, + (NODE*) this->allocator_->malloc (sizeof (NODE)), + NODE); + // Make the list circular by pointing it back to itself. + this->head_->next_ = this->head_; +} + +template +ACE_Unbounded_Set_Ex::ACE_Unbounded_Set_Ex (const ACE_Unbounded_Set_Ex &us) + : head_ (0), + cur_size_ (0), + allocator_ (us.allocator_), + comp_ (us.comp_) +{ + ACE_TRACE ("ACE_Unbounded_Set_Ex::ACE_Unbounded_Set_Ex"); + + if (this->allocator_ == 0) + this->allocator_ = ACE_Allocator::instance (); + + ACE_NEW_MALLOC (this->head_, + (NODE*) this->allocator_->malloc (sizeof (NODE)), + NODE); + this->head_->next_ = this->head_; + this->copy_nodes (us); +} + +template ACE_Unbounded_Set_Ex & +ACE_Unbounded_Set_Ex::operator= (const ACE_Unbounded_Set_Ex &us) +{ + ACE_TRACE ("ACE_Unbounded_Set_Ex::operator="); + + if (this != &us) + { + this->delete_nodes (); + this->copy_nodes (us); + } + + return *this; +} + +template int +ACE_Unbounded_Set_Ex::find (const T &item) const +{ + // ACE_TRACE ("ACE_Unbounded_Set_Ex::find"); + const_iterator const the_end = this->end (); + for (const_iterator i = this->begin (); i != the_end; ++i) + if (this->comp_(*i, item)) + return 0; + + return -1; +} + +template int +ACE_Unbounded_Set_Ex::insert (const T &item) +{ + // ACE_TRACE ("ACE_Unbounded_Set_Ex::insert"); + if (this->find (item) == 0) + return 1; + else + return this->insert_tail (item); +} + +template int +ACE_Unbounded_Set_Ex::remove (const T &item) +{ + // ACE_TRACE ("ACE_Unbounded_Set_Ex::remove"); + + // Insert the item to be founded into the dummy node. + this->head_->item_ = item; + + NODE *curr = this->head_; + + while (!(this->comp_ (curr->next_->item_, item))) + curr = curr->next_; + + if (curr->next_ == this->head_) + return -1; // Item was not found. + else + { + NODE *temp = curr->next_; + // Skip over the node that we're deleting. + curr->next_ = temp->next_; + --this->cur_size_; + ACE_DES_FREE_TEMPLATE2 (temp, + this->allocator_->free, + ACE_Node, + T, C); + return 0; + } +} + +template typename ACE_Unbounded_Set_Ex::iterator +ACE_Unbounded_Set_Ex::begin (void) +{ + // ACE_TRACE ("ACE_Unbounded_Set_Ex::begin"); + return iterator (*this); +} + +template typename ACE_Unbounded_Set_Ex::iterator +ACE_Unbounded_Set_Ex::end (void) +{ + // ACE_TRACE ("ACE_Unbounded_Set_Ex::end"); + return iterator (*this, 1); +} + +template typename ACE_Unbounded_Set_Ex::const_iterator +ACE_Unbounded_Set_Ex::begin (void) const +{ + // ACE_TRACE ("ACE_Unbounded_Set_Ex::begin"); + return const_iterator (*this); +} + +template typename ACE_Unbounded_Set_Ex::const_iterator +ACE_Unbounded_Set_Ex::end (void) const +{ + // ACE_TRACE ("ACE_Unbounded_Set_Ex::end"); + return const_iterator (*this, 1); +} + +ACE_ALLOC_HOOK_DEFINE(ACE_Unbounded_Set_Ex_Iterator) + +template void +ACE_Unbounded_Set_Ex_Iterator::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + // ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator::dump"); +#endif /* ACE_HAS_DUMP */ +} + +template +ACE_Unbounded_Set_Ex_Iterator::ACE_Unbounded_Set_Ex_Iterator ( + ACE_Unbounded_Set_Ex &s, + bool end) + : current_ (!end ? s.head_->next_ : s.head_ ), + set_ (&s) +{ + // ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator::ACE_Unbounded_Set_Ex_Iterator"); +} + +template int +ACE_Unbounded_Set_Ex_Iterator::advance (void) +{ + // ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator::advance"); + this->current_ = this->current_->next_; + return this->current_ != this->set_->head_; +} + +template int +ACE_Unbounded_Set_Ex_Iterator::first (void) +{ + // ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator::first"); + this->current_ = this->set_->head_->next_; + return this->current_ != this->set_->head_; +} + +template int +ACE_Unbounded_Set_Ex_Iterator::done (void) const +{ + ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator::done"); + + return this->current_ == this->set_->head_; +} + +template int +ACE_Unbounded_Set_Ex_Iterator::next (T *&item) +{ + // ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator::next"); + if (this->current_ == this->set_->head_) + return 0; + else + { + item = &this->current_->item_; + return 1; + } +} + +template ACE_Unbounded_Set_Ex_Iterator +ACE_Unbounded_Set_Ex_Iterator::operator++ (int) +{ + //ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator::operator++ (int)"); + ACE_Unbounded_Set_Ex_Iterator retv (*this); + + // postfix operator + + this->advance (); + return retv; +} + +template ACE_Unbounded_Set_Ex_Iterator& +ACE_Unbounded_Set_Ex_Iterator::operator++ (void) +{ + // ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator::operator++ (void)"); + + // prefix operator + + this->advance (); + return *this; +} + +template T& +ACE_Unbounded_Set_Ex_Iterator::operator* (void) +{ + //ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator::operator*"); + T *retv = 0; + + int result = this->next (retv); + ACE_ASSERT (result != 0); + ACE_UNUSED_ARG (result); + + return *retv; +} + +template bool +ACE_Unbounded_Set_Ex_Iterator::operator== (const ACE_Unbounded_Set_Ex_Iterator &rhs) const +{ + //ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator::operator=="); + return (this->set_ == rhs.set_ && this->current_ == rhs.current_); +} + +template bool +ACE_Unbounded_Set_Ex_Iterator::operator!= (const ACE_Unbounded_Set_Ex_Iterator &rhs) const +{ + //ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator::operator!="); + return (this->set_ != rhs.set_ || this->current_ != rhs.current_); +} + +ACE_ALLOC_HOOK_DEFINE(ACE_Unbounded_Set_Ex_Const_Iterator) + +template void +ACE_Unbounded_Set_Ex_Const_Iterator::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + // ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator::dump"); +#endif /* ACE_HAS_DUMP */ +} + +template +ACE_Unbounded_Set_Ex_Const_Iterator::ACE_Unbounded_Set_Ex_Const_Iterator ( + const ACE_Unbounded_Set_Ex &s, + bool end) + : current_ (!end ? s.head_->next_ : s.head_ ), + set_ (&s) +{ + // ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator::ACE_Unbounded_Set_Ex_Const_Iterator"); +} + +template int +ACE_Unbounded_Set_Ex_Const_Iterator::advance (void) +{ + // ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator::advance"); + this->current_ = this->current_->next_; + return this->current_ != this->set_->head_; +} + +template int +ACE_Unbounded_Set_Ex_Const_Iterator::first (void) +{ + // ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator::first"); + this->current_ = this->set_->head_->next_; + return this->current_ != this->set_->head_; +} + +template int +ACE_Unbounded_Set_Ex_Const_Iterator::done (void) const +{ + ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator::done"); + + return this->current_ == this->set_->head_; +} + +template int +ACE_Unbounded_Set_Ex_Const_Iterator::next (T *&item) +{ + // ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator::next"); + if (this->current_ == this->set_->head_) + return 0; + else + { + item = &this->current_->item_; + return 1; + } +} + +template ACE_Unbounded_Set_Ex_Const_Iterator +ACE_Unbounded_Set_Ex_Const_Iterator::operator++ (int) +{ + //ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator::operator++ (int)"); + ACE_Unbounded_Set_Ex_Const_Iterator retv (*this); + + // postfix operator + + this->advance (); + return retv; +} + +template ACE_Unbounded_Set_Ex_Const_Iterator& +ACE_Unbounded_Set_Ex_Const_Iterator::operator++ (void) +{ + // ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator::operator++ (void)"); + + // prefix operator + + this->advance (); + return *this; +} + +template T& +ACE_Unbounded_Set_Ex_Const_Iterator::operator* (void) +{ + //ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator::operator*"); + T *retv = 0; + + int const result = this->next (retv); + ACE_ASSERT (result != 0); + ACE_UNUSED_ARG (result); + + return *retv; +} + +template bool +ACE_Unbounded_Set_Ex_Const_Iterator::operator== (const ACE_Unbounded_Set_Ex_Const_Iterator &rhs) const +{ + //ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator::operator=="); + return (this->set_ == rhs.set_ && this->current_ == rhs.current_); +} + +template bool +ACE_Unbounded_Set_Ex_Const_Iterator::operator!= (const ACE_Unbounded_Set_Ex_Const_Iterator &rhs) const +{ + //ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator::operator!="); + return (this->set_ != rhs.set_ || this->current_ != rhs.current_); +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_UNBOUNDED_SET_EX_CPP */ diff --git a/dep/acelite/ace/Unbounded_Set_Ex.h b/dep/acelite/ace/Unbounded_Set_Ex.h new file mode 100644 index 00000000000..3d290a6acb3 --- /dev/null +++ b/dep/acelite/ace/Unbounded_Set_Ex.h @@ -0,0 +1,376 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Unbounded_Set_Ex.h + * + * $Id: Unbounded_Set_Ex.h 88978 2010-02-13 16:03:31Z hillj $ + * + * @author Douglas C. Schmidt + */ +//============================================================================= + +#ifndef ACE_UNBOUNDED_SET_EX_H +#define ACE_UNBOUNDED_SET_EX_H +#include /**/ "ace/pre.h" + +#include "ace/Node.h" +#include "ace/os_include/os_stddef.h" +#include + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +class ACE_Allocator; + +template +class ACE_Unbounded_Set_Ex_Iterator; + +template +class ACE_Unbounded_Set_Ex_Const_Iterator; + +template +class ACE_Unbounded_Set_Ex; + +/** + * @class ACE_Unbounded_Set_Ex_Iterator + * + * @brief Implement an iterator over an unbounded set. + */ +template +class ACE_Unbounded_Set_Ex_Iterator +{ +public: + /// Type definition of the container type. + typedef ACE_Unbounded_Set_Ex container_type; + + // = std::iterator_traits typedefs/traits. + typedef std::forward_iterator_tag iterator_category; + typedef typename container_type::value_type value_type; + typedef typename container_type::reference reference; + typedef typename container_type::pointer pointer; + typedef typename container_type::difference_type difference_type; + + // = Initialization method. + ACE_Unbounded_Set_Ex_Iterator (ACE_Unbounded_Set_Ex &s, bool end = false); + + // = Iteration methods. + + /// Pass back the @a next_item that hasn't been seen in the Set. + /// Returns 0 when all items have been seen, else 1. + int next (T *&next_item); + + /// Move forward by one element in the set. Returns 0 when all the + /// items in the set have been seen, else 1. + int advance (void); + + /// Move to the first element in the set. Returns 0 if the + /// set is empty, else 1. + int first (void); + + /// Returns 1 when all items have been seen, else 0. + int done (void) const; + + /// Dump the state of an object. + void dump (void) const; + + // = STL styled iteration, compare, and reference functions. + + /// Postfix advance. + ACE_Unbounded_Set_Ex_Iterator operator++ (int); + + /// Prefix advance. + ACE_Unbounded_Set_Ex_Iterator& operator++ (void); + + /// Returns a reference to the internal element @c this is pointing to. + T& operator* (void); + + /// Check if two iterators point to the same position + bool operator== (const ACE_Unbounded_Set_Ex_Iterator &) const; + bool operator!= (const ACE_Unbounded_Set_Ex_Iterator &) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + + /// Pointer to the current node in the iteration. + ACE_Node *current_; + + /// Pointer to the set we're iterating over. + ACE_Unbounded_Set_Ex *set_; +}; + +/** + * @class ACE_Unbounded_Set_Ex_Const_Iterator + * + * @brief Implement an const iterator over an unbounded set. + */ +template +class ACE_Unbounded_Set_Ex_Const_Iterator +{ +public: + typedef ACE_Unbounded_Set_Ex container_type; + + // = std::iterator_traits typedefs/traits. + typedef std::forward_iterator_tag iterator_category; + typedef typename container_type::const_value_type value_type; + typedef typename container_type::const_reference reference; + typedef typename container_type::const_pointer pointer; + typedef typename container_type::difference_type difference_type; + + // = Initialization method. + ACE_Unbounded_Set_Ex_Const_Iterator (const ACE_Unbounded_Set_Ex &s, + bool end = false); + + // = Iteration methods. + + /// Pass back the @a next_item that hasn't been seen in the Set. + /// @return Returns 0 when all items have been seen, else 1. + int next (T *&next_item); + + /// Move forward by one element in the set. Returns 0 when all the + /// items in the set have been seen, else 1. + int advance (void); + + /// Move to the first element in the set. Returns 0 if the + /// set is empty, else 1. + int first (void); + + /// Returns 1 when all items have been seen, else 0. + int done (void) const; + + /// Dump the state of an object. + void dump (void) const; + + // = STL styled iteration, compare, and reference functions. + + /// Postfix advance. + ACE_Unbounded_Set_Ex_Const_Iterator operator++ (int); + + /// Prefix advance. + ACE_Unbounded_Set_Ex_Const_Iterator& operator++ (void); + + /// Returns a reference to the internal element @c this is pointing to. + T& operator* (void); + + /// Check if two iterators point to the same position + bool operator== (const ACE_Unbounded_Set_Ex_Const_Iterator &) const; + bool operator!= (const ACE_Unbounded_Set_Ex_Const_Iterator &) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + + /// Pointer to the current node in the iteration. + ACE_Node *current_; + + /// Pointer to the set we're iterating over. + const ACE_Unbounded_Set_Ex *set_; +}; + +/** + * @class ACE_Unbounded_Set_Ex + * + * @brief Implement a simple unordered set of of unbounded size. + * + * This implementation of an unordered set uses a circular + * linked list with a dummy node. This implementation does not + * allow duplicates, but it maintains FIFO ordering of insertions. + * + * This implementation may also be parameterized with a comparator + * functor, which must implement bool operator () (const T&, const T&) const, + * returning true if the given items are equivalent. The default comparator + * is sufficient for objects reliably compared with operator==. + * + * Requirements and Performance Characteristics + * - Internal Structure + * Circular linked list + * - Duplicates allowed? + * No + * - Random access allowed? + * No + * - Search speed + * Linear + * - Insert/replace speed + * Linear + * - Iterator still valid after change to container? + * Yes + * - Frees memory for removed elements? + * Yes + * - Items inserted by + * Value + * - Requirements for contained type + * -# Default constructor + * -# Copy constructor + * -# operator= + * -# operator== const + * + */ +template +class ACE_Unbounded_Set_Ex +{ +public: + friend class ACE_Unbounded_Set_Ex_Iterator; + friend class ACE_Unbounded_Set_Ex_Const_Iterator; + + // Trait definition. + typedef ACE_Unbounded_Set_Ex_Iterator ITERATOR; + typedef ACE_Unbounded_Set_Ex_Iterator iterator; + typedef ACE_Unbounded_Set_Ex_Const_Iterator CONST_ITERATOR; + typedef ACE_Unbounded_Set_Ex_Const_Iterator const_iterator; + typedef C COMP; + typedef ACE_Node NODE; + + // = STL typedefs/traits. + typedef T value_type; + typedef T const const_value_type; + typedef value_type & reference; + typedef const_value_type & const_reference; + typedef value_type * pointer; + typedef const_value_type * const_pointer; + typedef ptrdiff_t difference_type; + + // = Initialization and termination methods. + /// Constructor. Use user specified allocation strategy + /// if specified. + /** + * Initialize an empty set using the allocation strategy of the user if + * provided. + */ + ACE_Unbounded_Set_Ex (ACE_Allocator *alloc = 0); + + /** + * Initialize an empty set using the allocation strategy of the user if + * provided, and a given comparator functor. + */ + ACE_Unbounded_Set_Ex (const C &comparator, ACE_Allocator *alloc = 0); + + /// Copy constructor. + /** + * Initialize this set to be an exact copy of the set provided. + */ + ACE_Unbounded_Set_Ex (const ACE_Unbounded_Set_Ex &); + + /// Assignment operator. + /** + * Perform a deep copy of the rhs into the lhs. + */ + ACE_Unbounded_Set_Ex & operator= (const ACE_Unbounded_Set_Ex &); + + /// Destructor. + /** + * Destroy the nodes of the set. + */ + ~ACE_Unbounded_Set_Ex (void); + + // = Check boundary conditions. + + /// Returns @c true if the container is empty, otherwise returns @c false. + /** + * Constant time is_empty check. + */ + bool is_empty (void) const; + + /// Returns @c false. + /** + * Always returns @c false since the set can never fill up. + */ + bool is_full (void) const; + + // = Classic unordered set operations. + + /// Linear insertion of an item. + /** + * Insert @a new_item into the set (doesn't allow duplicates). + * Returns -1 if failures occur, 1 if item is already present, else + * 0. + */ + int insert (const T &new_item); + + /// Insert @a item at the tail of the set (doesn't check for + /// duplicates). + /** + * Constant time insert at the end of the set. + */ + int insert_tail (const T &item); + + /// Linear remove operation. + /** + * Remove first occurrence of @a item from the set. Returns 0 if + * it removes the item, -1 if it can't find the item, and -1 if a + * failure occurs. + */ + int remove (const T &item); + + /// Finds if @a item occurs in the set. Returns 0 if find succeeds, + /// else -1. + /** + * Performs a linear find operation. + */ + int find (const T &item) const; + + /// Size of the set. + /** + * Access the size of the set. + */ + size_t size (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Reset the ACE_Unbounded_Set_Ex to be empty. + /** + * Delete the nodes of the set. + */ + void reset (void); + + // = STL-styled unidirectional iterator factory. + iterator begin (void); + iterator end (void); + const_iterator begin (void) const; + const_iterator end (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + /// Delete all the nodes in the Set. + void delete_nodes (void); + + /// Copy nodes into this set. + void copy_nodes (const ACE_Unbounded_Set_Ex &); + + /// Head of the linked list of Nodes. + NODE *head_; + + /// Current size of the set. + size_t cur_size_; + + /// Allocation strategy of the set. + ACE_Allocator *allocator_; + + /// Comparator to be used + COMP comp_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Unbounded_Set_Ex.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Unbounded_Set_Ex.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Unbounded_Set_Ex.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" +#endif /* ACE_UNBOUNDED_SET_H */ diff --git a/dep/acelite/ace/Unbounded_Set_Ex.inl b/dep/acelite/ace/Unbounded_Set_Ex.inl new file mode 100644 index 00000000000..356a1f58f1d --- /dev/null +++ b/dep/acelite/ace/Unbounded_Set_Ex.inl @@ -0,0 +1,23 @@ +// -*- C++ -*- +// +// $Id: Unbounded_Set_Ex.inl 81624 2008-05-06 17:14:57Z wotte $ + +#include "ace/Global_Macros.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template ACE_INLINE bool +ACE_Unbounded_Set_Ex::is_empty (void) const +{ + ACE_TRACE ("ACE_Unbounded_Set_Ex::is_empty"); + return this->head_ == this->head_->next_; +} + +template ACE_INLINE bool +ACE_Unbounded_Set_Ex::is_full (void) const +{ + ACE_TRACE ("ACE_Unbounded_Set_Ex::is_full"); + return 0; // We should implement a "node of last resort for this..." +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/Value_Ptr.h b/dep/acelite/ace/Value_Ptr.h new file mode 100644 index 00000000000..c9272a90cff --- /dev/null +++ b/dep/acelite/ace/Value_Ptr.h @@ -0,0 +1,167 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file Value_Ptr.h + * + * $Id: Value_Ptr.h 80826 2008-03-04 14:51:23Z wotte $ + * + * Value_Ptr implementation based on code in Herb Sutter's book "More + * Exceptional C++". + * + * @author Ossama Othman + */ +//========================================================================== + +#ifndef ACE_VALUE_PTR_H +#define ACE_VALUE_PTR_H + +#include "ace/config-lite.h" + +#include + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +namespace ACE +{ + /** + * @struct VP_traits + * + * @brief @c Value_Ptr traits template structure. + * + * The @c Value_Ptr template class delegates some operations to this + * template traits structure. + * + * Specialize this trait template if cloning through copy + * construction is not sufficient. For example, to avoid slicing + * when copying an object through a base class pointer, one can + * implement a virtual "clone" method that can be used to + * polymorphically invoke the appropriate cloning operation(s). + * That virtual method would then be invoked by the @c VP_traits\<\> + * specialization. + */ + template + struct VP_traits + { + /// Copy the given object. + static T * clone (T const * p) { return new T (*p); } + }; + + /** + * @class Value_Ptr + * + * @brief Smart pointer implementation designed for use as a class + * member. + * + * Using a @c std::auto_ptr\<\> as a class member is sometimes + * problematic since ownership of memory is transferred when copying + * such members. This @c Value_Ptr class is explicitly designed to + * avoid such problems by performing copies of the underlying object + * rather than transfer ownership. This, for example, allows it to + * be readily used as a member in classes placed inside STL + * containers. + * + * @see Item 31 in "More Exceptional C++" by Herb Sutter. + */ + template + class Value_Ptr + { + public: + + /// Constructor. + explicit Value_Ptr (T * p = 0) : p_ (p) { } + + /// Destructor. + ~Value_Ptr (void) { delete this->p_; } + + /// Deference operator. + T & operator* (void) const { return *this->p_; } + + /// Pointer operator. + T * operator-> (void) const { return this->p_; } + + /// Non-throwing swap operation used to make assignment strongly + /// exception-safe. + /** + * @note As implemented, the swap operation may not work correctly + * for @c auto_ptr\<\>s, but why would one use an @c + * auto_ptr\<\> as the template argument for this particular + * template class!? + */ + void swap (Value_Ptr & other) { std::swap (this->p_, other.p_); } + + /// Copy constructor. + Value_Ptr (Value_Ptr const & other) + : p_ (create_from (other.p_)) { } + + /// Assignment operator. + Value_Ptr & operator= (Value_Ptr const & other) + { + // Strongly exception-safe. + Value_Ptr temp (other); + this->swap (temp); + return *this; + } + +#ifndef ACE_LACKS_MEMBER_TEMPLATES + + // Compiler can't handle member templates so we lose converting + // copy operations. + + /// Converting copy constructor. + template + Value_Ptr (Value_Ptr const & other) + : p_ (create_from (other.p_)) { } + + /// Converting assignment operator. + template + Value_Ptr & operator= (Value_Ptr const & other) + { + // Strongly exception-safe. + Value_Ptr temp (other); + this->swap (temp); + return *this; + } + +#endif /* !ACE_LACKS_MEMBER_TEMPLATES */ + + private: + +#ifndef ACE_LACKS_MEMBER_TEMPLATES + + /// Copying method invoked when copy constructing. + template + T * create_from (U const * p) const + { + return p ? VP_traits::clone (p) : 0; + } + +#else + + // Compiler can't handle member templates so we lose converting + // copy operations. + + /// Copying method invoked when copy constructing. + T * create_from (T const * p) const + { + return p ? VP_traits::clone (p) : 0; + } + +#endif /* !ACE_LACKS_MEMBER_TEMPLATES */ + + private: + +#ifndef ACE_LACKS_MEMBER_TEMPLATES + template friend class Value_Ptr; +#endif /* !ACE_LACKS_MEMBER_TEMPLATES */ + + /// Object owned by this @c Value_Ptr. + T * p_; + + }; + +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_VALUE_PTR_H */ diff --git a/dep/acelite/ace/Vector_T.cpp b/dep/acelite/ace/Vector_T.cpp new file mode 100644 index 00000000000..006e6db1b4a --- /dev/null +++ b/dep/acelite/ace/Vector_T.cpp @@ -0,0 +1,154 @@ +// $Id: Vector_T.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#ifndef ACE_VECTOR_T_CPP +#define ACE_VECTOR_T_CPP + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/Vector_T.h" + +#if !defined (__ACE_INLINE__) +#include "ace/Vector_T.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_Vector) + +template +void ACE_Vector::resize (const size_t new_size, + const T& t) +{ + ACE_Array::size (new_size); + if (new_size > length_) + for (size_t i = length_; i < new_size; ++i) + (*this)[i]=t; + + curr_max_size_ = this->max_size (); + length_ = new_size; +} + +template +void ACE_Vector::push_back (const T& elem) +{ + if (length_ == curr_max_size_) + { + ACE_Array::size (curr_max_size_ * 2); + curr_max_size_ = this->max_size (); + } + else + ACE_Array::size (length_ + 1); + + ++length_; + (*this)[length_-1] = elem; +} + +template +void ACE_Vector::dump (void) const +{ +#if defined (ACE_HAS_DUMP) +#if 0 + // Can't do this unless the vector is an object with a dump + // function. + for (size_t i = 0; i < this->size (); ++i) + (*this)[i].dump (); +#endif /* 0 */ +#endif /* ACE_HAS_DUMP */ +} + +// Compare this vector with for equality. +template bool +ACE_Vector::operator== (const ACE_Vector &s) const +{ + if (this == &s) + return true; + else if (this->size () != s.size ()) + return false; + + const size_t len = s.size (); + for (size_t slot = 0; slot < len; ++slot) + if ((*this)[slot] != s[slot]) + return false; + + return true; +} + +#if 0 +template +int compare(const ACE_Vector& v1, + const ACE_Vector& v2, + const size_t from_ndx, + const size_t to_ndx) +{ + size_t last1 = v1.size () - 1; + size_t last2 = v2.size () - 1; + if (last1 < from_ndx || last1 < to_ndx) + return false; + if (last2 < from_ndx || last2 < to_ndx) + return false; + if (last1 != last2) + return false; + + // cout<<"compare() <================="<"< +int partial_compare(const ACE_Vector& v1, + const ACE_Vector& v2, + const size_t from_ndx, + const size_t to_ndx) +{ + size_t last1 = v1.size () - 1; + size_t last2 = v2.size () - 1; + + if (last1 < from_ndx || last1 < to_ndx) + return false; + if (last2 < from_ndx || last2 < to_ndx) + return false; + + // cout<<"partial_compare() <================="<"< int +ACE_Vector_Iterator::next (T *&item) +{ + // ACE_TRACE ("ACE_Vector_Iterator::next"); + + if (this->done ()) + { + item = 0; + return 0; + } + else + { + item = &vector_[current_]; + return 1; + } +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_VECTOR_T_CPP */ diff --git a/dep/acelite/ace/Vector_T.h b/dep/acelite/ace/Vector_T.h new file mode 100644 index 00000000000..3d49f4391bb --- /dev/null +++ b/dep/acelite/ace/Vector_T.h @@ -0,0 +1,316 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file Vector_T.h + * + * $Id: Vector_T.h 84477 2009-02-16 13:30:38Z johnnyw $ + * + * @author Craig L. Ching + * @author Gonzalo Diethelm + */ +//========================================================================== + +#ifndef ACE_VECTOR_T_H +#define ACE_VECTOR_T_H + +#include /**/ "ace/pre.h" + +#include "ace/Array.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/* + * Default size for an ACE_Vector. + */ +static const size_t ACE_VECTOR_DEFAULT_SIZE = 32; + +// Forward declaration. +template class ACE_Vector_Iterator; + +/** + * @class ACE_Vector + * + * @brief Defines an STL-like vector container. + * + * This is an STL-like template vector container, a wrapper around + * ACE_Array. It provides at least the basic std::vector look and + * feel: push_back(), clear(), resize(), capacity(). This template + * class uses the copy semantic paradigm, though it is okay to use + * reference counted smart pointers (see ACE_Ptr<T>) with this + * template class. + * + * Requirements and Performance Characteristics + * - Internal Structure + * ACE_Array + * - Duplicates allowed? + * Yes + * - Random access allowed? + * No + * - Search speed + * N/A + * - Insert/replace speed + * Linear + * - Iterator still valid after change to container? + * Yes + * - Frees memory for removed elements? + * No + * - Items inserted by + * Value + * - Requirements for contained type + * -# Default constructor + * -# Copy constructor + * -# operator= + */ +template +class ACE_Vector : public ACE_Array +{ +public: + /** + * A short name for iterator for ACE_Vector. + */ + typedef ACE_Vector_Iterator Iterator; + + + /** + * General constructor. + * + * @param init_size Initial size of the vector with the default + * value of DEFAULT_SIZE + * @param alloc Pointer to an ACE allocator. If it is NULL then the + * default ACE allocator is used + */ + ACE_Vector (const size_t init_size = DEFAULT_SIZE, + ACE_Allocator* alloc = 0); + + /** + * Destructor. + */ + ~ACE_Vector (); + + /** + * Returns the current vector capacity, that is, the currently + * allocated buffer size. + * + * @return Current buffer size of the vector + */ + size_t capacity (void) const; + + /** + * Returns the vector's dynamic size / actual current size of the + * vector. Do not confuse it with ACE_Array::size(), which returns + * the array's capacity. Unfortunately, ACE is not very consistent + * with the function names. + * + * @return Dynamic size / actual current size of the vector. + */ + size_t size (void) const; + + /** + * Clears out the vector. It does not reallocate the vector's + * buffer, it is just sets the vector's dynamic size to 0. + */ + void clear (void); + + /** + * Resizes the vector to the new capacity. If the vector's current + * capacity is smaller than the size to be specified, then the + * buffer gets reallocated. If the new capacity is less than the + * current capacity of the vector, the buffer size stays the same. + * + * @param new_size New capacity of the vector + * @param t A filler value (of the class T) for initializing the + * elements of the vector with. By default, if this + * parameter is not specified, the default value of the + * class T will be used (for more detail, see the + * initialization clause for this parameter). + */ + void resize (const size_t new_size, + const T& t); + + /** + * Appends a new element to the vector ("push back"). If the + * dynamic size of the vector is equal to the capacity of the vector + * (vector is at capacity), the vector automatically doubles its + * capacity. + * + * @param elem A reference to the new element to be appended. By + * default, this parameters gets initialized with the + * default value of the class T. + */ + void push_back (const T& elem); + + /** + * Deletes the last element from the vector ("pop back"). What this + * function really does is decrement the dynamic size of the + * vector. The vector's buffer does not get reallocated for + * performance. + */ + void pop_back (void); + + /** + * This function dumps the content of the vector. TO BE MOVED out + * of this class. It needs to be implemented as a global template + * function that accepts a const ACE_Vector<T>, in order to + * make instances of this class compile on Linux, AIX. G++ and xlC + * have template instantiation algoriths, which are different from + * the one in Visual C++. The algorithms try to instantiate ALL + * methods declared in the template class, regardless of whether the + * functions are used or not. That is, all of the classes, that are + * used as elements in ACE_Vector's, have to have the dump() methods + * defined in them (seems to be overkill). + * + * This function calls T::dump() for each element of the vector. + */ + void dump (void) const; + + // = Compare operators + + /// Equality comparison operator. + /** + * Compare this vector with @arg s for equality. Two vectors are equal + * if their sizes are equal and all the elements are equal. + */ + bool operator== (const ACE_Vector &s) const; + + /// Inequality comparison operator. + /** + * Compare this vector with @arg s for inequality such that @c *this != + * @arg s is always the complement of the boolean return value of + * @c *this == @arg s. + */ + bool operator!= (const ACE_Vector &s) const; + + void swap (ACE_Vector &rhs); + +protected: + + /** + * Dynamic size (length) of the vector. + */ + size_t length_; + + /** + * Current capacity (buffer size) of the vector. + */ + size_t curr_max_size_; + + friend class ACE_Vector_Iterator; +}; + +#if 0 +/* + * Not sure about including these functions, if for no other reason, + * because they polute the global namespace! + */ + +/** + * Compare two vectors in the range of [from_ndx..to_ndx]. This + * template function requires class T to have the bool operator!=() + * declared in the class. It is safe to define vectors of scalar data + * types, like int, double, etc., including class ACE_TString. + * + * @param v1 The first vector (out of the two) to be compared. + * @param v2 The Second vector (out of the two) to be compared. + * @param from_ndx Compare vector v1 and v2, starting with the + * "from_ndx" index . + * @param to_ndx Compare vector v1 and v2, from "from_ndx" to + * "to_ndx". + * @return Returns true if v1==v2 in the specified index range, + * returns false otherwise. Also, returns false in case if + * v1's size is not equal to v2's size. + */ +template +int compare (const ACE_Vector& v1, + const ACE_Vector& v2, + const size_t from_ndx, + const size_t to_ndx); + +/** + * Does a partial comparison of two vectors in the range of + * [from_ndx..to_ndx]. The only difference between this function and + * the template compare<T> function is that this function does + * not require v1 and v2 to be of equal size. + * + * @param v1 The first vector (out of the two) to be compared. + * @param v2 The Second vector (out of the two) to be compared. + * @param from_ndx Compare vector v1 and v2, starting with the + * "from_ndx" index . + * @param to_ndx Compare vector v1 and v2, from "from_ndx" to + * "to_ndx". + * @return Returns true if vector v1 and v2 are equal in the specified + * index range. + */ + +template +int partial_compare (const ACE_Vector& v1, + const ACE_Vector& v2, + const size_t from_ndx, + const size_t to_ndx); +#endif /* 0 */ +// **************************************************************** + +/** + * @class ACE_Vector_Iterator + * + * @brief Implement an iterator over an ACE_Vector. + * + * This iterator is safe in the face of vector element deletions. + * But it is NOT safe if the vector is resized via the assignment + * operator during iteration. That would be very odd, and dangerous. + */ +template +class ACE_Vector_Iterator +{ +public: + // = Initialization method. + ACE_Vector_Iterator (ACE_Vector &); + + // = Iteration methods. + + /// Pass back the @a next_item that hasn't been seen in the vector. + /// Returns 0 when all items have been seen, else 1. + int next (T *&next_item); + + /// Move forward by one element in the vector. Returns 0 when all the + /// items in the vector have been seen, else 1. + int advance (void); + + /// Returns 1 when all items have been seen, else 0. + int done (void) const; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + +private: + /// Pointer to the current item in the iteration. + size_t current_; + + /// Reference to the vector we're iterating over. + ACE_Vector &vector_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/Vector_T.inl" +#endif /* __ACE_INLINE__ */ + +#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) +#include "ace/Vector_T.cpp" +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ + +#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) +#pragma implementation ("Vector_T.cpp") +#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ + +#include /**/ "ace/post.h" + +#endif /* ACE_VECTOR_T_H */ diff --git a/dep/acelite/ace/Vector_T.inl b/dep/acelite/ace/Vector_T.inl new file mode 100644 index 00000000000..4b773109a84 --- /dev/null +++ b/dep/acelite/ace/Vector_T.inl @@ -0,0 +1,107 @@ +// -*- C++ -*- +// +// $Id: Vector_T.inl 81478 2008-04-28 13:22:26Z schmidt $ + +#include + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +template ACE_INLINE +ACE_Vector::ACE_Vector (const size_t init_size, + ACE_Allocator* alloc) + : ACE_Array (init_size == 0 ? DEFAULT_SIZE : init_size, alloc), + length_ (0) +{ + this->curr_max_size_ = this->max_size (); +} + +template ACE_INLINE +ACE_Vector::~ACE_Vector () +{ +} + +template ACE_INLINE +size_t ACE_Vector::capacity (void) const +{ + return curr_max_size_; +} + +template ACE_INLINE +size_t ACE_Vector::size (void) const +{ + return length_; +} + +template ACE_INLINE +void ACE_Vector::clear (void) +{ + length_ = 0; +} + +template ACE_INLINE +void ACE_Vector::pop_back (void) +{ + if (length_ > 0) + { + --length_; + ACE_Array::size (length_); + } +} + +// Compare this vector with for inequality. + +template ACE_INLINE bool +ACE_Vector::operator!= (const ACE_Vector &s) const +{ + return !(*this == s); +} + +template ACE_INLINE void +ACE_Vector::swap (ACE_Vector &rhs) +{ + ACE_Array::swap (rhs); + std::swap (this->length_, rhs.length_); + std::swap (this->curr_max_size_, rhs.curr_max_size_); +} + +// **************************************************************** + +template ACE_INLINE void +ACE_Vector_Iterator::dump (void) const +{ + // ACE_TRACE ("ACE_Vector_Iterator::dump"); +} + +template ACE_INLINE +ACE_Vector_Iterator::ACE_Vector_Iterator (ACE_Vector &v) + : current_ (0), + vector_ (v) +{ + // ACE_TRACE ("ACE_Vector_Iterator::ACE_Vector_Iterator"); +} + +template ACE_INLINE int +ACE_Vector_Iterator::advance (void) +{ + // ACE_TRACE ("ACE_Vector_Iterator::advance"); + + if (this->current_ < vector_.size ()) + { + ++this->current_; + return 1; + } + else + // Already finished iterating. + return 0; +} + +template ACE_INLINE int +ACE_Vector_Iterator::done (void) const +{ + ACE_TRACE ("ACE_Vector_Iterator::done"); + + return this->current_ >= vector_.size (); +} + +ACE_END_VERSIONED_NAMESPACE_DECL + diff --git a/dep/acelite/ace/Version.h b/dep/acelite/ace/Version.h new file mode 100644 index 00000000000..92d70e802ec --- /dev/null +++ b/dep/acelite/ace/Version.h @@ -0,0 +1,9 @@ + +// -*- C++ -*- +// $Id: Version.h 91247 2010-08-01 09:46:33Z johnnyw $ +// This is file was automatically generated by \$ACE_ROOT/bin/make_release. + +#define ACE_MAJOR_VERSION 5 +#define ACE_MINOR_VERSION 8 +#define ACE_BETA_VERSION 1 +#define ACE_VERSION "5.8.1" diff --git a/dep/acelite/ace/Versioned_Namespace.h b/dep/acelite/ace/Versioned_Namespace.h new file mode 100644 index 00000000000..542254876ff --- /dev/null +++ b/dep/acelite/ace/Versioned_Namespace.h @@ -0,0 +1,51 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file Versioned_Namespace.h + * + * $Id$ + * + * Versioned namespace support. + * + * Useful for preventing conflicts when using a third party library. + * + * @author Ossama Othman + */ +//============================================================================= + +#ifndef ACE_VERSIONED_NAMESPACE_H +#define ACE_VERSIONED_NAMESPACE_H + +#ifndef ACE_CONFIG_MACROS_H +# error This header is only meant to be included by or after "ace/config-lite.h". +#endif /* !ACE_CONFIG_LITE_H */ + + +#if defined (ACE_HAS_VERSIONED_NAMESPACE) && ACE_HAS_VERSIONED_NAMESPACE == 1 + +# ifndef ACE_VERSIONED_NAMESPACE_NAME +//# include "ace/Version.h" + +// Preprocessor symbols will not be expanded if they are +// concatenated. Force the preprocessor to expand them during the +// argument prescan by calling a macro that itself calls another that +// performs the actual concatenation. +# define ACE_MAKE_VERSIONED_NAMESPACE_NAME_IMPL(MAJOR,MINOR,BETA) ACE_ ## MAJOR ## _ ## MINOR ## _ ## BETA +# define ACE_MAKE_VERSIONED_NAMESPACE_NAME(MAJOR,MINOR,BETA) ACE_MAKE_VERSIONED_NAMESPACE_NAME_IMPL(MAJOR,MINOR,BETA) +# define ACE_VERSIONED_NAMESPACE_NAME ACE_MAKE_VERSIONED_NAMESPACE_NAME(ACE_MAJOR_VERSION,ACE_MINOR_VERSION,ACE_BETA_VERSION) +# endif /* !ACE_VERSIONED_NAMESPACE_NAME */ + +# define ACE_BEGIN_VERSIONED_NAMESPACE_DECL namespace ACE_VERSIONED_NAMESPACE_NAME { +# define ACE_END_VERSIONED_NAMESPACE_DECL } \ + using namespace ACE_VERSIONED_NAMESPACE_NAME; + +#else + +# define ACE_VERSIONED_NAMESPACE_NAME +# define ACE_BEGIN_VERSIONED_NAMESPACE_DECL +# define ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_VERSIONED_NAMESPACE */ + +#endif /* !ACE_VERSIONED_NAMESPACE_H */ diff --git a/dep/acelite/ace/WFMO_Reactor.cpp b/dep/acelite/ace/WFMO_Reactor.cpp new file mode 100644 index 00000000000..713b5689cdb --- /dev/null +++ b/dep/acelite/ace/WFMO_Reactor.cpp @@ -0,0 +1,2748 @@ +// $Id: WFMO_Reactor.cpp 85125 2009-04-20 16:47:38Z johnnyw $ + +#include "ace/WFMO_Reactor.h" + +#if defined (ACE_WIN32) + +#include "ace/Handle_Set.h" +#include "ace/Timer_Heap.h" +#include "ace/Thread.h" +#include "ace/OS_NS_errno.h" +#include "ace/Null_Condition.h" + +#if !defined (__ACE_INLINE__) +#include "ace/WFMO_Reactor.inl" +#endif /* __ACE_INLINE__ */ + +ACE_RCSID(ace, WFMO_Reactor, "$Id: WFMO_Reactor.cpp 85125 2009-04-20 16:47:38Z johnnyw $") + +#include "ace/Auto_Ptr.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_WFMO_Reactor_Handler_Repository::ACE_WFMO_Reactor_Handler_Repository (ACE_WFMO_Reactor &wfmo_reactor) + : wfmo_reactor_ (wfmo_reactor) +{ +} + +int +ACE_WFMO_Reactor_Handler_Repository::open (size_t size) +{ + if (size > MAXIMUM_WAIT_OBJECTS) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("%d exceeds MAXIMUM_WAIT_OBJECTS (%d)\n"), + size, + MAXIMUM_WAIT_OBJECTS), + -1); + + // Dynamic allocation + ACE_NEW_RETURN (this->current_handles_, + ACE_HANDLE[size], + -1); + ACE_NEW_RETURN (this->current_info_, + Current_Info[size], + -1); + ACE_NEW_RETURN (this->current_suspended_info_, + Suspended_Info[size], + -1); + ACE_NEW_RETURN (this->to_be_added_info_, + To_Be_Added_Info[size], + -1); + + // Initialization + this->max_size_ = size; + this->max_handlep1_ = 0; + this->suspended_handles_ = 0; + this->handles_to_be_added_ = 0; + this->handles_to_be_deleted_ = 0; + this->handles_to_be_suspended_ = 0; + this->handles_to_be_resumed_ = 0; + + for (size_t i = 0; i < size; ++i) + this->current_handles_[i] = ACE_INVALID_HANDLE; + + return 0; +} + +ACE_WFMO_Reactor_Handler_Repository::~ACE_WFMO_Reactor_Handler_Repository (void) +{ + // Free up dynamically allocated space + delete [] this->current_handles_; + delete [] this->current_info_; + delete [] this->current_suspended_info_; + delete [] this->to_be_added_info_; +} + +ACE_Reactor_Mask +ACE_WFMO_Reactor_Handler_Repository::bit_ops (long &existing_masks, + ACE_Reactor_Mask change_masks, + int operation) +{ + // Find the old reactor masks. This automatically does the work of + // the GET_MASK operation. + + ACE_Reactor_Mask old_masks = ACE_Event_Handler::NULL_MASK; + + if (ACE_BIT_ENABLED (existing_masks, FD_READ) + || ACE_BIT_ENABLED (existing_masks, FD_CLOSE)) + ACE_SET_BITS (old_masks, ACE_Event_Handler::READ_MASK); + + if (ACE_BIT_ENABLED (existing_masks, FD_WRITE)) + ACE_SET_BITS (old_masks, ACE_Event_Handler::WRITE_MASK); + + if (ACE_BIT_ENABLED (existing_masks, FD_OOB)) + ACE_SET_BITS (old_masks, ACE_Event_Handler::EXCEPT_MASK); + + if (ACE_BIT_ENABLED (existing_masks, FD_ACCEPT)) + ACE_SET_BITS (old_masks, ACE_Event_Handler::ACCEPT_MASK); + + if (ACE_BIT_ENABLED (existing_masks, FD_CONNECT)) + ACE_SET_BITS (old_masks, ACE_Event_Handler::CONNECT_MASK); + + if (ACE_BIT_ENABLED (existing_masks, FD_QOS)) + ACE_SET_BITS (old_masks, ACE_Event_Handler::QOS_MASK); + + if (ACE_BIT_ENABLED (existing_masks, FD_GROUP_QOS)) + ACE_SET_BITS (old_masks, ACE_Event_Handler::GROUP_QOS_MASK); + + switch (operation) + { + case ACE_Reactor::CLR_MASK: + // For the CLR_MASK operation, clear only the specific masks. + + if (ACE_BIT_ENABLED (change_masks, ACE_Event_Handler::READ_MASK)) + { + ACE_CLR_BITS (existing_masks, FD_READ); + ACE_CLR_BITS (existing_masks, FD_CLOSE); + } + + if (ACE_BIT_ENABLED (change_masks, ACE_Event_Handler::WRITE_MASK)) + ACE_CLR_BITS (existing_masks, FD_WRITE); + + if (ACE_BIT_ENABLED (change_masks, ACE_Event_Handler::EXCEPT_MASK)) + ACE_CLR_BITS (existing_masks, FD_OOB); + + if (ACE_BIT_ENABLED (change_masks, ACE_Event_Handler::ACCEPT_MASK)) + ACE_CLR_BITS (existing_masks, FD_ACCEPT); + + if (ACE_BIT_ENABLED (change_masks, ACE_Event_Handler::CONNECT_MASK)) + ACE_CLR_BITS (existing_masks, FD_CONNECT); + + if (ACE_BIT_ENABLED (change_masks, ACE_Event_Handler::QOS_MASK)) + ACE_CLR_BITS (existing_masks, FD_QOS); + + if (ACE_BIT_ENABLED (change_masks, ACE_Event_Handler::GROUP_QOS_MASK)) + ACE_CLR_BITS (existing_masks, FD_GROUP_QOS); + + break; + + case ACE_Reactor::SET_MASK: + // If the operation is a set, first reset any existing masks + + existing_masks = 0; + /* FALLTHRU */ + + case ACE_Reactor::ADD_MASK: + // For the ADD_MASK and the SET_MASK operation, add only the + // specific masks. + + if (ACE_BIT_ENABLED (change_masks, ACE_Event_Handler::READ_MASK)) + { + ACE_SET_BITS (existing_masks, FD_READ); + ACE_SET_BITS (existing_masks, FD_CLOSE); + } + + if (ACE_BIT_ENABLED (change_masks, ACE_Event_Handler::WRITE_MASK)) + ACE_SET_BITS (existing_masks, FD_WRITE); + + if (ACE_BIT_ENABLED (change_masks, ACE_Event_Handler::EXCEPT_MASK)) + ACE_SET_BITS (existing_masks, FD_OOB); + + if (ACE_BIT_ENABLED (change_masks, ACE_Event_Handler::ACCEPT_MASK)) + ACE_SET_BITS (existing_masks, FD_ACCEPT); + + if (ACE_BIT_ENABLED (change_masks, ACE_Event_Handler::CONNECT_MASK)) + ACE_SET_BITS (existing_masks, FD_CONNECT); + + if (ACE_BIT_ENABLED (change_masks, ACE_Event_Handler::QOS_MASK)) + ACE_SET_BITS (existing_masks, FD_QOS); + + if (ACE_BIT_ENABLED (change_masks, ACE_Event_Handler::GROUP_QOS_MASK)) + ACE_SET_BITS (existing_masks, FD_GROUP_QOS); + + break; + + case ACE_Reactor::GET_MASK: + + // The work for this operation is done in all cases at the + // begining of the function. + + ACE_UNUSED_ARG (change_masks); + + break; + } + + return old_masks; +} + +int +ACE_WFMO_Reactor_Handler_Repository::unbind_i (ACE_HANDLE handle, + ACE_Reactor_Mask mask, + bool &changes_required) +{ + int error = 0; + + // Remember this value; only if it changes do we need to wakeup + // the other threads + size_t const original_handle_count = this->handles_to_be_deleted_; + size_t i; + + // Go through all the handles looking for . Even if we find + // it, we continue through the rest of the list since could + // appear multiple times. All handles are checked. + + // First check the current entries + for (i = 0; i < this->max_handlep1_ && error == 0; ++i) + // Since the handle can either be the event or the I/O handle, + // we have to check both + if ((this->current_handles_[i] == handle + || this->current_info_[i].io_handle_ == handle) + && // Make sure that it is not already marked for deleted + !this->current_info_[i].delete_entry_) + { + if (this->remove_handler_i (i, mask) == -1) + error = 1; + } + + // Then check the suspended entries + for (i = 0; i < this->suspended_handles_ && error == 0; ++i) + // Since the handle can either be the event or the I/O handle, we + // have to check both + if ((this->current_suspended_info_[i].io_handle_ == handle + || this->current_suspended_info_[i].event_handle_ == handle) + && + // Make sure that it is not already marked for deleted + !this->current_suspended_info_[i].delete_entry_) + { + if (this->remove_suspended_handler_i (i, mask) == -1) + error = 1; + } + + // Then check the to_be_added entries + for (i = 0; i < this->handles_to_be_added_ && error == 0; ++i) + // Since the handle can either be the event or the I/O handle, + // we have to check both + if ((this->to_be_added_info_[i].io_handle_ == handle + || this->to_be_added_info_[i].event_handle_ == handle) + && + // Make sure that it is not already marked for deleted + !this->to_be_added_info_[i].delete_entry_) + { + if (this->remove_to_be_added_handler_i (i, mask) == -1) + error = 1; + } + + // Only if the number of handlers to be deleted changes do we need + // to wakeup the other threads + if (original_handle_count < this->handles_to_be_deleted_) + changes_required = true; + + return error ? -1 : 0; +} + +int +ACE_WFMO_Reactor_Handler_Repository::remove_handler_i (size_t slot, + ACE_Reactor_Mask to_be_removed_masks) +{ + // I/O entries + if (this->current_info_[slot].io_entry_) + { + // See if there are other events that the is + // interested in + this->bit_ops (this->current_info_[slot].network_events_, + to_be_removed_masks, + ACE_Reactor::CLR_MASK); + + // Disassociate/Reassociate the event from/with the I/O handle. + // This will depend on the value of remaining set of network + // events that the is interested in. I don't + // think we can do anything about errors here, so I will not + // check this. + ::WSAEventSelect ((SOCKET) this->current_info_[slot].io_handle_, + this->current_handles_[slot], + this->current_info_[slot].network_events_); + } + // Normal event entries. + else if (ACE_BIT_ENABLED (to_be_removed_masks, ACE_Event_Handler::DONT_CALL)) + // Preserve DONT_CALL + to_be_removed_masks = ACE_Event_Handler::DONT_CALL; + else + // Make sure that the is the NULL_MASK + to_be_removed_masks = ACE_Event_Handler::NULL_MASK; + + // If this event was marked for suspension, undo the suspension flag + // and reduce the to be suspended count. + if (this->current_info_[slot].suspend_entry_) + { + // Undo suspension + this->current_info_[slot].suspend_entry_ = false; + // Decrement the handle count + --this->handles_to_be_suspended_; + } + + // If there are no more events that the is + // interested in, or this is a non-I/O entry, schedule the + // for removal + if (this->current_info_[slot].network_events_ == 0) + { + // Mark to be deleted + this->current_info_[slot].delete_entry_ = true; + // Remember the mask + this->current_info_[slot].close_masks_ = to_be_removed_masks; + // Increment the handle count + ++this->handles_to_be_deleted_; + } + + // Since it is not a complete removal, we'll call handle_close + // for all the masks that were removed. This does not change + // the internal state of the reactor. + // + // Note: this condition only applies to I/O entries + else if (ACE_BIT_ENABLED (to_be_removed_masks, ACE_Event_Handler::DONT_CALL) == 0) + { + ACE_HANDLE handle = this->current_info_[slot].io_handle_; + this->current_info_[slot].event_handler_->handle_close (handle, + to_be_removed_masks); + } + + return 0; +} + +int +ACE_WFMO_Reactor_Handler_Repository::remove_suspended_handler_i (size_t slot, + ACE_Reactor_Mask to_be_removed_masks) +{ + // I/O entries + if (this->current_suspended_info_[slot].io_entry_) + { + // See if there are other events that the is + // interested in + this->bit_ops (this->current_suspended_info_[slot].network_events_, + to_be_removed_masks, + ACE_Reactor::CLR_MASK); + + // Disassociate/Reassociate the event from/with the I/O handle. + // This will depend on the value of remaining set of network + // events that the is interested in. I don't + // think we can do anything about errors here, so I will not + // check this. + ::WSAEventSelect ((SOCKET) this->current_suspended_info_[slot].io_handle_, + this->current_suspended_info_[slot].event_handle_, + this->current_suspended_info_[slot].network_events_); + } + // Normal event entries. + else if (ACE_BIT_ENABLED (to_be_removed_masks, ACE_Event_Handler::DONT_CALL)) + // Preserve DONT_CALL + to_be_removed_masks = ACE_Event_Handler::DONT_CALL; + else + // Make sure that the is the NULL_MASK + to_be_removed_masks = ACE_Event_Handler::NULL_MASK; + + // If this event was marked for resumption, undo the resumption flag + // and reduce the to be resumed count. + if (this->current_suspended_info_[slot].resume_entry_) + { + // Undo resumption + this->current_suspended_info_[slot].resume_entry_ = false; + // Decrement the handle count + --this->handles_to_be_resumed_; + } + + // If there are no more events that the is + // interested in, or this is a non-I/O entry, schedule the + // for removal + if (this->current_suspended_info_[slot].network_events_ == 0) + { + // Mark to be deleted + this->current_suspended_info_[slot].delete_entry_ = true; + // Remember the mask + this->current_suspended_info_[slot].close_masks_ = to_be_removed_masks; + // Increment the handle count + ++this->handles_to_be_deleted_; + } + // Since it is not a complete removal, we'll call handle_close for + // all the masks that were removed. This does not change the + // internal state of the reactor. + // + // Note: this condition only applies to I/O entries + else if (ACE_BIT_ENABLED (to_be_removed_masks, ACE_Event_Handler::DONT_CALL) == 0) + { + ACE_HANDLE handle = this->current_suspended_info_[slot].io_handle_; + this->current_suspended_info_[slot].event_handler_->handle_close (handle, + to_be_removed_masks); + } + + return 0; +} + +int +ACE_WFMO_Reactor_Handler_Repository::remove_to_be_added_handler_i (size_t slot, + ACE_Reactor_Mask to_be_removed_masks) +{ + // I/O entries + if (this->to_be_added_info_[slot].io_entry_) + { + // See if there are other events that the is + // interested in + this->bit_ops (this->to_be_added_info_[slot].network_events_, + to_be_removed_masks, + ACE_Reactor::CLR_MASK); + + // Disassociate/Reassociate the event from/with the I/O handle. + // This will depend on the value of remaining set of network + // events that the is interested in. I don't + // think we can do anything about errors here, so I will not + // check this. + ::WSAEventSelect ((SOCKET) this->to_be_added_info_[slot].io_handle_, + this->to_be_added_info_[slot].event_handle_, + this->to_be_added_info_[slot].network_events_); + } + // Normal event entries. + else if (ACE_BIT_ENABLED (to_be_removed_masks, ACE_Event_Handler::DONT_CALL)) + // Preserve DONT_CALL + to_be_removed_masks = ACE_Event_Handler::DONT_CALL; + else + // Make sure that the is the NULL_MASK + to_be_removed_masks = ACE_Event_Handler::NULL_MASK; + + // If this event was marked for suspension, undo the suspension flag + // and reduce the to be suspended count. + if (this->to_be_added_info_[slot].suspend_entry_) + { + // Undo suspension + this->to_be_added_info_[slot].suspend_entry_ = false; + // Decrement the handle count + --this->handles_to_be_suspended_; + } + + // If there are no more events that the is + // interested in, or this is a non-I/O entry, schedule the + // for removal + if (this->to_be_added_info_[slot].network_events_ == 0) + { + // Mark to be deleted + this->to_be_added_info_[slot].delete_entry_ = true; + // Remember the mask + this->to_be_added_info_[slot].close_masks_ = to_be_removed_masks; + // Increment the handle count + ++this->handles_to_be_deleted_; + } + // Since it is not a complete removal, we'll call handle_close + // for all the masks that were removed. This does not change + // the internal state of the reactor. + // + // Note: this condition only applies to I/O entries + else if (ACE_BIT_ENABLED (to_be_removed_masks, ACE_Event_Handler::DONT_CALL) == 0) + { + ACE_HANDLE handle = this->to_be_added_info_[slot].io_handle_; + this->to_be_added_info_[slot].event_handler_->handle_close (handle, + to_be_removed_masks); + } + + return 0; +} + +int +ACE_WFMO_Reactor_Handler_Repository::suspend_handler_i (ACE_HANDLE handle, + bool &changes_required) +{ + size_t i = 0; + + // Go through all the handles looking for . Even if we find + // it, we continue through the rest of the list since could + // appear multiple times. All handles are checked. + + // Check the current entries first. + for (i = 0; i < this->max_handlep1_; ++i) + // Since the handle can either be the event or the I/O handle, + // we have to check both + if ((this->current_handles_[i] == handle || + this->current_info_[i].io_handle_ == handle) && + // Make sure that it is not already marked for suspension + !this->current_info_[i].suspend_entry_) + { + // Mark to be suspended + this->current_info_[i].suspend_entry_ = true; + // Increment the handle count + ++this->handles_to_be_suspended_; + // Changes will be required + changes_required = true; + } + + // Then check the suspended entries. + for (i = 0; i < this->suspended_handles_; ++i) + // Since the handle can either be the event or the I/O handle, + // we have to check both + if ((this->current_suspended_info_[i].event_handle_ == handle || + this->current_suspended_info_[i].io_handle_ == handle) && + // Make sure that the resumption is not already undone + this->current_suspended_info_[i].resume_entry_) + { + // Undo resumption + this->current_suspended_info_[i].resume_entry_ = false; + // Decrement the handle count + --this->handles_to_be_resumed_; + // Changes will be required + changes_required = true; + } + + // Then check the to_be_added entries. + for (i = 0; i < this->handles_to_be_added_; ++i) + // Since the handle can either be the event or the I/O handle, + // we have to check both + if ((this->to_be_added_info_[i].io_handle_ == handle || + this->to_be_added_info_[i].event_handle_ == handle) && + // Make sure that it is not already marked for suspension + !this->to_be_added_info_[i].suspend_entry_) + { + // Mark to be suspended + this->to_be_added_info_[i].suspend_entry_ = true; + // Increment the handle count + ++this->handles_to_be_suspended_; + // Changes will be required + changes_required = true; + } + + return 0; +} + +int +ACE_WFMO_Reactor_Handler_Repository::resume_handler_i (ACE_HANDLE handle, + bool &changes_required) +{ + size_t i = 0; + + // Go through all the handles looking for . Even if we find + // it, we continue through the rest of the list since could + // appear multiple times. All handles are checked. + + // Check the current entries first. + for (i = 0; i < this->max_handlep1_; ++i) + // Since the handle can either be the event or the I/O handle, + // we have to check both + if ((this->current_handles_[i] == handle || + this->current_info_[i].io_handle_ == handle) && + // Make sure that the suspension is not already undone + this->current_info_[i].suspend_entry_) + { + // Undo suspension + this->current_info_[i].suspend_entry_ = false; + // Decrement the handle count + --this->handles_to_be_suspended_; + // Changes will be required + changes_required = true; + } + + // Then check the suspended entries. + for (i = 0; i < this->suspended_handles_; ++i) + // Since the handle can either be the event or the I/O handle, + // we have to check both + if ((this->current_suspended_info_[i].event_handle_ == handle || + this->current_suspended_info_[i].io_handle_ == handle) && + // Make sure that it is not already marked for resumption + !this->current_suspended_info_[i].resume_entry_) + { + // Mark to be resumed + this->current_suspended_info_[i].resume_entry_ = true; + // Increment the handle count + ++this->handles_to_be_resumed_; + // Changes will be required + changes_required = true; + } + + // Then check the to_be_added entries. + for (i = 0; i < this->handles_to_be_added_; ++i) + // Since the handle can either be the event or the I/O handle, + // we have to check both + if ((this->to_be_added_info_[i].io_handle_ == handle || + this->to_be_added_info_[i].event_handle_ == handle) && + // Make sure that the suspension is not already undone + this->to_be_added_info_[i].suspend_entry_) + { + // Undo suspension + this->to_be_added_info_[i].suspend_entry_ = false; + // Decrement the handle count + --this->handles_to_be_suspended_; + // Changes will be required + changes_required = true; + } + + return 0; +} + +void +ACE_WFMO_Reactor_Handler_Repository::unbind_all (void) +{ + { + ACE_GUARD (ACE_Process_Mutex, ace_mon, this->wfmo_reactor_.lock_); + + bool dummy; + size_t i; + + // Remove all the current handlers + for (i = 0; i < this->max_handlep1_; ++i) + this->unbind_i (this->current_handles_[i], + ACE_Event_Handler::ALL_EVENTS_MASK, + dummy); + + // Remove all the suspended handlers + for (i = 0; i < this->suspended_handles_; ++i) + this->unbind_i (this->current_suspended_info_[i].event_handle_, + ACE_Event_Handler::ALL_EVENTS_MASK, + dummy); + + // Remove all the to_be_added handlers + for (i = 0; i < this->handles_to_be_added_; ++i) + this->unbind_i (this->to_be_added_info_[i].event_handle_, + ACE_Event_Handler::ALL_EVENTS_MASK, + dummy); + } + + // The guard is released here + + // Wake up all threads in WaitForMultipleObjects so that they can + // reconsult the handle set + this->wfmo_reactor_.wakeup_all_threads (); +} + +int +ACE_WFMO_Reactor_Handler_Repository::bind_i (bool io_entry, + ACE_Event_Handler *event_handler, + long network_events, + ACE_HANDLE io_handle, + ACE_HANDLE event_handle, + bool delete_event) +{ + if (event_handler == 0) + return -1; + + // Make sure that the is valid + if (event_handle == ACE_INVALID_HANDLE) + event_handle = event_handler->get_handle (); + if (this->invalid_handle (event_handle)) + return -1; + + size_t current_size = this->max_handlep1_ + + this->handles_to_be_added_ - + this->handles_to_be_deleted_ + + this->suspended_handles_; + + // Make sure that there's room in the table and that total pending + // additions should not exceed what the array + // can hold. + if (current_size < this->max_size_ && + this->handles_to_be_added_ < this->max_size_) + { + // Cache this set into the , till we come + // around to actually adding this to the + this->to_be_added_info_[this->handles_to_be_added_].set (event_handle, + io_entry, + event_handler, + io_handle, + network_events, + delete_event); + + ++this->handles_to_be_added_; + + event_handler->add_reference (); + + // Wake up all threads in WaitForMultipleObjects so that they can + // reconsult the handle set + this->wfmo_reactor_.wakeup_all_threads (); + } + else + { + errno = EMFILE; // File descriptor table is full (better than nothing) + return -1; + } + + return 0; +} + +int +ACE_WFMO_Reactor_Handler_Repository::make_changes_in_current_infos (void) +{ + // Go through the entire valid array and check for all handles that + // have been schedule for deletion + if (this->handles_to_be_deleted_ > 0 || this->handles_to_be_suspended_ > 0) + { + size_t i = 0; + while (i < this->max_handlep1_) + { + // This stuff is necessary here, since we should not make + // the upcall until all the internal data structures have + // been updated. This is to protect against upcalls that + // try to deregister again. + ACE_HANDLE handle = ACE_INVALID_HANDLE; + ACE_Reactor_Mask masks = ACE_Event_Handler::NULL_MASK; + ACE_Event_Handler *event_handler = 0; + + // See if this entry is scheduled for deletion + if (this->current_info_[i].delete_entry_) + { + // Calling the method here will ensure that we + // will only call it once per deregistering . + // This is essential in the case when the will + // do something like delete itself and we have multiple + // threads in WFMO_Reactor. + // + // Make sure that the DONT_CALL mask is not set + masks = this->current_info_[i].close_masks_; + if (ACE_BIT_ENABLED (masks, ACE_Event_Handler::DONT_CALL) == 0) + { + // Grab the correct handle depending on the type entry + if (this->current_info_[i].io_entry_) + handle = this->current_info_[i].io_handle_; + else + handle = this->current_handles_[i]; + + // Event handler + event_handler = this->current_info_[i].event_handler_; + } + + // If created the event, we need to clean it up + if (this->current_info_[i].delete_event_) + ACE_OS::event_destroy (&this->current_handles_[i]); + + // Reduce count by one + --this->handles_to_be_deleted_; + } + + // See if this entry is scheduled for suspension + else if (this->current_info_[i].suspend_entry_) + { + this->current_suspended_info_ [this->suspended_handles_].set (this->current_handles_[i], + this->current_info_[i]); + // Increase number of suspended handles + ++this->suspended_handles_; + + // Reduce count by one + --this->handles_to_be_suspended_; + } + + // See if this entry is scheduled for deletion or suspension + // If so we need to clean up + if (this->current_info_[i].delete_entry_ || + this->current_info_[i].suspend_entry_ ) + { + size_t last_valid_slot = this->max_handlep1_ - 1; + // If this is the last handle in the set, no need to swap + // places. Simply remove it. + if (i < last_valid_slot) + // Swap this handle with the last valid handle + { + // Struct copy + this->current_info_[i] = + this->current_info_[last_valid_slot]; + this->current_handles_[i] = + this->current_handles_[last_valid_slot]; + } + // Reset the info in this slot + this->current_info_[last_valid_slot].reset (); + this->current_handles_[last_valid_slot] = ACE_INVALID_HANDLE; + --this->max_handlep1_; + } + else + { + // This current entry is not up for deletion or + // suspension. Proceed to the next entry in the current + // handles. + ++i; + } + + // Now that all internal structures have been updated, make + // the upcall. + if (event_handler != 0) + { + bool const requires_reference_counting = + event_handler->reference_counting_policy ().value () == + ACE_Event_Handler::Reference_Counting_Policy::ENABLED; + + event_handler->handle_close (handle, masks); + + if (requires_reference_counting) + { + event_handler->remove_reference (); + } + } + } + } + + return 0; +} + +int +ACE_WFMO_Reactor_Handler_Repository::make_changes_in_suspension_infos (void) +{ + // Go through the array + if (this->handles_to_be_deleted_ > 0 || this->handles_to_be_resumed_ > 0) + { + size_t i = 0; + while (i < this->suspended_handles_) + { + // This stuff is necessary here, since we should not make + // the upcall until all the internal data structures have + // been updated. This is to protect against upcalls that + // try to deregister again. + ACE_HANDLE handle = ACE_INVALID_HANDLE; + ACE_Reactor_Mask masks = ACE_Event_Handler::NULL_MASK; + ACE_Event_Handler *event_handler = 0; + + // See if this entry is scheduled for deletion + if (this->current_suspended_info_[i].delete_entry_) + { + // Calling the method here will ensure that we + // will only call it once per deregistering . + // This is essential in the case when the will + // do something like delete itself and we have multiple + // threads in WFMO_Reactor. + // + // Make sure that the DONT_CALL mask is not set + masks = this->current_suspended_info_[i].close_masks_; + if (ACE_BIT_ENABLED (masks, ACE_Event_Handler::DONT_CALL) == 0) + { + // Grab the correct handle depending on the type entry + if (this->current_suspended_info_[i].io_entry_) + handle = this->current_suspended_info_[i].io_handle_; + else + handle = this->current_suspended_info_[i].event_handle_; + + // Upcall + event_handler = this->current_suspended_info_[i].event_handler_; + } + + // If created the event, we need to clean it up + if (this->current_suspended_info_[i].delete_event_) + ACE_OS::event_destroy (&this->current_suspended_info_[i].event_handle_); + + // Reduce count by one + --this->handles_to_be_deleted_; + } + + else if (this->current_suspended_info_[i].resume_entry_) + { + // Add to the end of the current handles set + this->current_handles_[this->max_handlep1_] = this->current_suspended_info_[i].event_handle_; + // Struct copy + this->current_info_[this->max_handlep1_].set (this->current_suspended_info_[i]); + ++this->max_handlep1_; + + // Reduce count by one + --this->handles_to_be_resumed_; + } + + // If an entry needs to be removed, either because it + // was deleted or resumed, remove it now before doing + // the upcall. + if (this->current_suspended_info_[i].resume_entry_ || + this->current_suspended_info_[i].delete_entry_) + { + size_t last_valid_slot = this->suspended_handles_ - 1; + // Net effect is that we're removing an entry and + // compressing the list from the end. So, if removing + // an entry from the middle, copy the last valid one to the + // removed slot. Reset the end and decrement the number + // of suspended handles. + if (i < last_valid_slot) + // Struct copy + this->current_suspended_info_[i] = + this->current_suspended_info_[last_valid_slot]; + this->current_suspended_info_[last_valid_slot].reset (); + --this->suspended_handles_; + } + else + { + // This current entry is not up for deletion or + // resumption. Proceed to the next entry in the + // suspended handles. + ++i; + } + + // Now that all internal structures have been updated, make + // the upcall. + if (event_handler != 0) + { + int requires_reference_counting = + event_handler->reference_counting_policy ().value () == + ACE_Event_Handler::Reference_Counting_Policy::ENABLED; + + event_handler->handle_close (handle, masks); + + if (requires_reference_counting) + { + event_handler->remove_reference (); + } + } + } + } + + return 0; +} + +int +ACE_WFMO_Reactor_Handler_Repository::make_changes_in_to_be_added_infos (void) +{ + // Go through the arrays + for (size_t i = 0; i < this->handles_to_be_added_; ++i) + { + // This stuff is necessary here, since we should not make + // the upcall until all the internal data structures have + // been updated. This is to protect against upcalls that + // try to deregister again. + ACE_HANDLE handle = ACE_INVALID_HANDLE; + ACE_Reactor_Mask masks = ACE_Event_Handler::NULL_MASK; + ACE_Event_Handler *event_handler = 0; + + // See if this entry is scheduled for deletion + if (this->to_be_added_info_[i].delete_entry_) + { + // Calling the method here will ensure that we + // will only call it once per deregistering . + // This is essential in the case when the will + // do something like delete itself and we have multiple + // threads in WFMO_Reactor. + // + // Make sure that the DONT_CALL mask is not set + masks = this->to_be_added_info_[i].close_masks_; + if (ACE_BIT_ENABLED (masks, ACE_Event_Handler::DONT_CALL) == 0) + { + // Grab the correct handle depending on the type entry + if (this->to_be_added_info_[i].io_entry_) + handle = this->to_be_added_info_[i].io_handle_; + else + handle = this->to_be_added_info_[i].event_handle_; + + // Upcall + event_handler = this->to_be_added_info_[i].event_handler_; + } + + // If created the event, we need to clean it up + if (this->to_be_added_info_[i].delete_event_) + ACE_OS::event_destroy (&this->to_be_added_info_[i].event_handle_); + + // Reduce count by one + --this->handles_to_be_deleted_; + } + + // See if this entry is scheduled for suspension + else if (this->to_be_added_info_[i].suspend_entry_) + { + this->current_suspended_info_ [this->suspended_handles_].set (this->to_be_added_info_[i].event_handle_, + this->to_be_added_info_[i]); + // Increase number of suspended handles + ++this->suspended_handles_; + + // Reduce count by one + --this->handles_to_be_suspended_; + } + + // If neither of the two flags are on, add to current + else + { + // Add to the end of the current handles set + this->current_handles_[this->max_handlep1_] = this->to_be_added_info_[i].event_handle_; + // Struct copy + this->current_info_[this->max_handlep1_].set (this->to_be_added_info_[i]); + ++this->max_handlep1_; + } + + // Reset the + this->to_be_added_info_[i].reset (); + + // Now that all internal structures have been updated, make the + // upcall. + if (event_handler != 0) + { + int requires_reference_counting = + event_handler->reference_counting_policy ().value () == + ACE_Event_Handler::Reference_Counting_Policy::ENABLED; + + event_handler->handle_close (handle, masks); + + if (requires_reference_counting) + { + event_handler->remove_reference (); + } + } + } + + // Since all to be added handles have been taken care of, reset the + // counter + this->handles_to_be_added_ = 0; + + return 0; +} + +void +ACE_WFMO_Reactor_Handler_Repository::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + size_t i = 0; + + ACE_TRACE ("ACE_WFMO_Reactor_Handler_Repository::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("Max size = %d\n"), + this->max_size_)); + + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("Current info table\n\n"))); + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("\tSize = %d\n"), + this->max_handlep1_)); + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("\tHandles to be suspended = %d\n"), + this->handles_to_be_suspended_)); + + for (i = 0; i < this->max_handlep1_; ++i) + this->current_info_[i].dump (this->current_handles_[i]); + + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("\n"))); + + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("To-be-added info table\n\n"))); + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("\tSize = %d\n"), + this->handles_to_be_added_)); + + for (i = 0; i < this->handles_to_be_added_; ++i) + this->to_be_added_info_[i].dump (); + + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("\n"))); + + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("Suspended info table\n\n"))); + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("\tSize = %d\n"), + this->suspended_handles_)); + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("\tHandles to be resumed = %d\n"), + this->handles_to_be_resumed_)); + + for (i = 0; i < this->suspended_handles_; ++i) + this->current_suspended_info_[i].dump (); + + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("\n"))); + + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("Total handles to be deleted = %d\n"), + this->handles_to_be_deleted_)); + + ACE_DEBUG ((LM_DEBUG, + ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +/************************************************************/ + +int +ACE_WFMO_Reactor::work_pending (const ACE_Time_Value &) +{ + ACE_NOTSUP_RETURN (-1); +} + +#if defined (ACE_WIN32_VC8) +# pragma warning (push) +# pragma warning (disable:4355) /* Use of 'this' in initializer list */ +# endif +ACE_WFMO_Reactor::ACE_WFMO_Reactor (ACE_Sig_Handler *sh, + ACE_Timer_Queue *tq, + ACE_Reactor_Notify *notify) + : signal_handler_ (0), + delete_signal_handler_ (false), + timer_queue_ (0), + delete_timer_queue_ (false), + delete_handler_rep_ (false), + notify_handler_ (0), + delete_notify_handler_ (false), + lock_adapter_ (lock_), + handler_rep_ (*this), + // this event is initially signaled + ok_to_wait_ (1), + // this event is initially unsignaled + wakeup_all_threads_ (0), + // this event is initially unsignaled + waiting_to_change_state_ (0), + active_threads_ (0), + owner_ (ACE_Thread::self ()), + new_owner_ (0), + change_state_thread_ (0), + open_for_business_ (false), + deactivated_ (0) +{ + if (this->open (ACE_WFMO_Reactor::DEFAULT_SIZE, 0, sh, tq, 0, notify) == -1) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("WFMO_Reactor"))); +} + +ACE_WFMO_Reactor::ACE_WFMO_Reactor (size_t size, + int unused, + ACE_Sig_Handler *sh, + ACE_Timer_Queue *tq, + ACE_Reactor_Notify *notify) + : signal_handler_ (0), + delete_signal_handler_ (false), + timer_queue_ (0), + delete_timer_queue_ (false), + delete_handler_rep_ (false), + notify_handler_ (0), + delete_notify_handler_ (false), + lock_adapter_ (lock_), + handler_rep_ (*this), + // this event is initially signaled + ok_to_wait_ (1), + // this event is initially unsignaled + wakeup_all_threads_ (0), + // this event is initially unsignaled + waiting_to_change_state_ (0), + active_threads_ (0), + owner_ (ACE_Thread::self ()), + new_owner_ (0), + change_state_thread_ (0), + open_for_business_ (false), + deactivated_ (0) +{ + ACE_UNUSED_ARG (unused); + + if (this->open (size, 0, sh, tq, 0, notify) == -1) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("WFMO_Reactor"))); +} +#if defined (ACE_WIN32_VC8) +# pragma warning (pop) +#endif + +int +ACE_WFMO_Reactor::current_info (ACE_HANDLE, size_t &) +{ + return -1; +} + +int +ACE_WFMO_Reactor::open (size_t size, + bool, + ACE_Sig_Handler *sh, + ACE_Timer_Queue *tq, + int, + ACE_Reactor_Notify *notify) +{ + // This GUARD is necessary since we are updating shared state. + ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); + + // If we are already open, return -1 + if (this->open_for_business_) + return -1; + + // Timer Queue + if (this->delete_timer_queue_) + delete this->timer_queue_; + + if (tq == 0) + { + ACE_NEW_RETURN (this->timer_queue_, + ACE_Timer_Heap, + -1); + this->delete_timer_queue_ = true; + } + else + { + this->timer_queue_ = tq; + this->delete_timer_queue_ = false; + } + + // Signal Handler + if (this->delete_signal_handler_) + delete this->signal_handler_; + + if (sh == 0) + { + ACE_NEW_RETURN (this->signal_handler_, + ACE_Sig_Handler, + -1); + this->delete_signal_handler_ = true; + } + else + { + this->signal_handler_ = sh; + this->delete_signal_handler_ = false; + } + + // Setup the atomic wait array (used later in ) + this->atomic_wait_array_[0] = this->lock_.lock ().proc_mutex_; + this->atomic_wait_array_[1] = this->ok_to_wait_.handle (); + + // Prevent memory leaks when the ACE_WFMO_Reactor is reopened. + if (this->delete_handler_rep_) + { + if (this->handler_rep_.changes_required ()) + { + // Make necessary changes to the handler repository + this->handler_rep_.make_changes (); + // Turn off since all necessary changes + // have completed + this->wakeup_all_threads_.reset (); + } + + this->handler_rep_.~ACE_WFMO_Reactor_Handler_Repository (); + } + + // Open the handle repository. Two additional handles for internal + // purposes + if (this->handler_rep_.open (size + 2) == -1) + ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"), + ACE_TEXT ("opening handler repository")), + -1); + else + this->delete_handler_rep_ = true; + + if (this->notify_handler_ != 0 && this->delete_notify_handler_) + delete this->notify_handler_; + + this->notify_handler_ = notify; + + if (this->notify_handler_ == 0) + { + ACE_NEW_RETURN (this->notify_handler_, + ACE_WFMO_Reactor_Notify, + -1); + + if (this->notify_handler_ == 0) + return -1; + else + this->delete_notify_handler_ = true; + } + + /* NOTE */ + // The order of the following two registrations is very important + + // Open the notification handler + if (this->notify_handler_->open (this, this->timer_queue_) == -1) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("opening notify handler ")), + -1); + + // Register for event + if (this->register_handler (&this->wakeup_all_threads_handler_, + this->wakeup_all_threads_.handle ()) == -1) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("registering thread wakeup handler")), + -1); + + // Since we have added two handles into the handler repository, + // update the + if (this->handler_rep_.changes_required ()) + { + // Make necessary changes to the handler repository + this->handler_rep_.make_changes (); + // Turn off since all necessary changes + // have completed + this->wakeup_all_threads_.reset (); + } + + // We are open for business + this->open_for_business_ = true; + + return 0; +} + +int +ACE_WFMO_Reactor::set_sig_handler (ACE_Sig_Handler *signal_handler) +{ + if (this->signal_handler_ != 0 && this->delete_signal_handler_) + delete this->signal_handler_; + this->signal_handler_ = signal_handler; + this->delete_signal_handler_ = false; + return 0; +} + +ACE_Timer_Queue * +ACE_WFMO_Reactor::timer_queue (void) const +{ + return this->timer_queue_; +} + +int +ACE_WFMO_Reactor::timer_queue (ACE_Timer_Queue *tq) +{ + if (this->timer_queue_ != 0 && this->delete_timer_queue_) + delete this->timer_queue_; + this->timer_queue_ = tq; + this->delete_timer_queue_ = false; + return 0; +} + +int +ACE_WFMO_Reactor::close (void) +{ + // This GUARD is necessary since we are updating shared state. + ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); + + // If we are already closed, return error + if (!this->open_for_business_) + return -1; + + // We are now closed + this->open_for_business_ = false; + // This will unregister all handles + this->handler_rep_.close (); + + return 0; +} + +ACE_WFMO_Reactor::~ACE_WFMO_Reactor (void) +{ + // Assumption: No threads are left in the Reactor when this method + // is called (i.e., active_threads_ == 0) + + // Close down + this->close (); + + // Make necessary changes to the handler repository that we caused + // by . + this->handler_rep_.make_changes (); + + if (this->delete_timer_queue_) + { + delete this->timer_queue_; + this->timer_queue_ = 0; + this->delete_timer_queue_ = false; + } + + if (this->delete_signal_handler_) + { + delete this->signal_handler_; + this->signal_handler_ = 0; + this->delete_signal_handler_ = false; + } + + if (this->delete_notify_handler_) + { + delete this->notify_handler_; + this->notify_handler_ = 0; + this->delete_notify_handler_ = false; + } +} + +int +ACE_WFMO_Reactor::register_handler_i (ACE_HANDLE event_handle, + ACE_HANDLE io_handle, + ACE_Event_Handler *event_handler, + ACE_Reactor_Mask new_masks) +{ + // If this is a Winsock 1 system, the underlying event assignment will + // not work, so don't try. Winsock 1 must use ACE_Select_Reactor for + // reacting to socket activity. + +#if !defined (ACE_HAS_WINSOCK2) || (ACE_HAS_WINSOCK2 == 0) + + ACE_UNUSED_ARG (event_handle); + ACE_UNUSED_ARG (io_handle); + ACE_UNUSED_ARG (event_handler); + ACE_UNUSED_ARG (new_masks); + ACE_NOTSUP_RETURN (-1); + +#else + + // Make sure that the is valid + if (io_handle == ACE_INVALID_HANDLE) + io_handle = event_handler->get_handle (); + + if (this->handler_rep_.invalid_handle (io_handle)) + { + errno = ERROR_INVALID_HANDLE; + return -1; + } + + long new_network_events = 0; + bool delete_event = false; + auto_ptr event; + + // Look up the repository to see if the is already + // there. + ACE_Reactor_Mask old_masks; + int found = this->handler_rep_.modify_network_events_i (io_handle, + new_masks, + old_masks, + new_network_events, + event_handle, + delete_event, + ACE_Reactor::ADD_MASK); + + // Check to see if the user passed us a valid event; If not then we + // need to create one + if (event_handle == ACE_INVALID_HANDLE) + { + // Note: don't change this since some C++ compilers have + // s that don't work properly... + auto_ptr tmp (new ACE_Auto_Event); + event = tmp; + event_handle = event->handle (); + delete_event = true; + } + + int result = ::WSAEventSelect ((SOCKET) io_handle, + event_handle, + new_network_events); + // If we had found the there is nothing more to do + if (found) + return result; + else if (result != SOCKET_ERROR && + this->handler_rep_.bind_i (1, + event_handler, + new_network_events, + io_handle, + event_handle, + delete_event) != -1) + { + // The was not found in the repository, add to + // the repository. + if (delete_event) + { + // Clear out the handle in the ACE_Auto_Event so that when + // it is destroyed, the handle isn't closed out from under + // the reactor. After setting it, running down the event + // (via auto_ptr<> event, above) at function return will + // cause an error because it'll try to close an invalid handle. + // To avoid that smashing the errno value, save the errno + // here, explicitly remove the event so the dtor won't do it + // again, then restore errno. + ACE_Errno_Guard guard (errno); + event->handle (ACE_INVALID_HANDLE); + event->remove (); + } + return 0; + } + else + return -1; + +#endif /* ACE_HAS_WINSOCK2 || ACE_HAS_WINSOCK2 == 0 */ + +} + +int +ACE_WFMO_Reactor::mask_ops_i (ACE_HANDLE io_handle, + ACE_Reactor_Mask new_masks, + int operation) +{ + // Make sure that the is valid + if (this->handler_rep_.invalid_handle (io_handle)) + return -1; + + long new_network_events = 0; + bool delete_event = false; + ACE_HANDLE event_handle = ACE_INVALID_HANDLE; + + // Look up the repository to see if the is already + // there. + ACE_Reactor_Mask old_masks; + int found = this->handler_rep_.modify_network_events_i (io_handle, + new_masks, + old_masks, + new_network_events, + event_handle, + delete_event, + operation); + if (found) + { + int result = ::WSAEventSelect ((SOCKET) io_handle, + event_handle, + new_network_events); + if (result == 0) + return old_masks; + else + return result; + } + else + return -1; +} + + + +int +ACE_WFMO_Reactor_Handler_Repository::modify_network_events_i (ACE_HANDLE io_handle, + ACE_Reactor_Mask new_masks, + ACE_Reactor_Mask &old_masks, + long &new_network_events, + ACE_HANDLE &event_handle, + bool &delete_event, + int operation) +{ + long *modified_network_events = &new_network_events; + int found = 0; + size_t i; + + // First go through the current entries + // + // Look for all entries in the current handles for matching handle + // (except those that have been scheduled for deletion) + for (i = 0; i < this->max_handlep1_ && !found; ++i) + if (io_handle == this->current_info_[i].io_handle_ && + !this->current_info_[i].delete_entry_) + { + found = 1; + modified_network_events = &this->current_info_[i].network_events_; + delete_event = this->current_info_[i].delete_event_; + event_handle = this->current_handles_[i]; + } + + // Then pass through the suspended handles + // + // Look for all entries in the suspended handles for matching handle + // (except those that have been scheduled for deletion) + for (i = 0; i < this->suspended_handles_ && !found; ++i) + if (io_handle == this->current_suspended_info_[i].io_handle_ && + !this->current_suspended_info_[i].delete_entry_) + { + found = 1; + modified_network_events = &this->current_suspended_info_[i].network_events_; + delete_event = this->current_suspended_info_[i].delete_event_; + event_handle = this->current_suspended_info_[i].event_handle_; + } + + // Then check the to_be_added handles + // + // Look for all entries in the to_be_added handles for matching + // handle (except those that have been scheduled for deletion) + for (i = 0; i < this->handles_to_be_added_ && !found; ++i) + if (io_handle == this->to_be_added_info_[i].io_handle_ && + !this->to_be_added_info_[i].delete_entry_) + { + found = 1; + modified_network_events = &this->to_be_added_info_[i].network_events_; + delete_event = this->to_be_added_info_[i].delete_event_; + event_handle = this->to_be_added_info_[i].event_handle_; + } + + old_masks = this->bit_ops (*modified_network_events, + new_masks, + operation); + + new_network_events = *modified_network_events; + + return found; +} + +ACE_Event_Handler * +ACE_WFMO_Reactor_Handler_Repository::find_handler (ACE_HANDLE handle) +{ + long existing_masks_ignored = 0; + return this->handler (handle, existing_masks_ignored); +} + +ACE_Event_Handler * +ACE_WFMO_Reactor_Handler_Repository::handler (ACE_HANDLE handle, + long &existing_masks) +{ + int found = 0; + size_t i = 0; + ACE_Event_Handler *event_handler = 0; + existing_masks = 0; + + // Look for the handle first + + // First go through the current entries + // + // Look for all entries in the current handles for matching handle + // (except those that have been scheduled for deletion) + for (i = 0; i < this->max_handlep1_ && !found; ++i) + if ((handle == this->current_info_[i].io_handle_ || + handle == this->current_handles_[i]) && + !this->current_info_[i].delete_entry_) + { + found = 1; + event_handler = this->current_info_[i].event_handler_; + existing_masks = this->current_info_[i].network_events_; + } + + // Then pass through the suspended handles + // + // Look for all entries in the suspended handles for matching handle + // (except those that have been scheduled for deletion) + for (i = 0; i < this->suspended_handles_ && !found; ++i) + if ((handle == this->current_suspended_info_[i].io_handle_ || + handle == this->current_suspended_info_[i].event_handle_) && + !this->current_suspended_info_[i].delete_entry_) + { + found = 1; + event_handler = this->current_suspended_info_[i].event_handler_; + existing_masks = this->current_suspended_info_[i].network_events_; + } + + // Then check the to_be_added handles + // + // Look for all entries in the to_be_added handles for matching + // handle (except those that have been scheduled for deletion) + for (i = 0; i < this->handles_to_be_added_ && !found; ++i) + if ((handle == this->to_be_added_info_[i].io_handle_ || + handle == this->to_be_added_info_[i].event_handle_) && + !this->to_be_added_info_[i].delete_entry_) + { + found = 1; + event_handler = this->to_be_added_info_[i].event_handler_; + existing_masks = this->to_be_added_info_[i].network_events_; + } + + if (event_handler) + event_handler->add_reference (); + + return event_handler; +} + +int +ACE_WFMO_Reactor_Handler_Repository::handler (ACE_HANDLE handle, + ACE_Reactor_Mask user_masks, + ACE_Event_Handler **user_event_handler) +{ + long existing_masks = 0; + int found = 0; + + ACE_Event_Handler_var safe_event_handler = + this->handler (handle, + existing_masks); + + if (safe_event_handler.handler ()) + found = 1; + + if (!found) + return -1; + + // Otherwise, make sure that the masks that the user is looking for + // are on. + if (found && + ACE_BIT_ENABLED (user_masks, ACE_Event_Handler::READ_MASK)) + if (!ACE_BIT_ENABLED (existing_masks, FD_READ) && + !ACE_BIT_ENABLED (existing_masks, FD_CLOSE)) + found = 0; + + if (found && + ACE_BIT_ENABLED (user_masks, ACE_Event_Handler::WRITE_MASK)) + if (!ACE_BIT_ENABLED (existing_masks, FD_WRITE)) + found = 0; + + if (found && + ACE_BIT_ENABLED (user_masks, ACE_Event_Handler::EXCEPT_MASK)) + if (!ACE_BIT_ENABLED (existing_masks, FD_OOB)) + found = 0; + + if (found && + ACE_BIT_ENABLED (user_masks, ACE_Event_Handler::ACCEPT_MASK)) + if (!ACE_BIT_ENABLED (existing_masks, FD_ACCEPT)) + found = 0; + + if (found && + ACE_BIT_ENABLED (user_masks, ACE_Event_Handler::CONNECT_MASK)) + if (!ACE_BIT_ENABLED (existing_masks, FD_CONNECT)) + found = 0; + + if (found && + ACE_BIT_ENABLED (user_masks, ACE_Event_Handler::QOS_MASK)) + if (!ACE_BIT_ENABLED (existing_masks, FD_QOS)) + found = 0; + + if (found && + ACE_BIT_ENABLED (user_masks, ACE_Event_Handler::GROUP_QOS_MASK)) + if (!ACE_BIT_ENABLED (existing_masks, FD_GROUP_QOS)) + found = 0; + + if (found && + user_event_handler) + *user_event_handler = safe_event_handler.release (); + + if (found) + return 0; + else + return -1; +} + +// Waits for and dispatches all events. Returns -1 on error, 0 if +// max_wait_time expired, or the number of events that were dispatched. +int +ACE_WFMO_Reactor::event_handling (ACE_Time_Value *max_wait_time, + int alertable) +{ + ACE_TRACE ("ACE_WFMO_Reactor::event_handling"); + + // Make sure we are not closed + if (!this->open_for_business_ || this->deactivated_) + return -1; + + // Stash the current time -- the destructor of this object will + // automatically compute how much time elapsed since this method was + // called. + ACE_Countdown_Time countdown (max_wait_time); + + int result; + do + { + // Check to see if it is ok to enter ::WaitForMultipleObjects + // This will acquire lock_> on success On failure, the + // lock will not be acquired + result = this->ok_to_wait (max_wait_time, alertable); + if (result != 1) + return result; + + // Increment the number of active threads + ++this->active_threads_; + + // Release the + this->lock_.release (); + + // Update the countdown to reflect time waiting to play with the + // mut and event. + countdown.update (); + + // Calculate timeout + int timeout = this->calculate_timeout (max_wait_time); + + // Wait for event to happen + DWORD wait_status = this->wait_for_multiple_events (timeout, + alertable); + + // Upcall + result = this->safe_dispatch (wait_status); + if (0 == result) + { + // wait_for_multiple_events timed out without dispatching + // anything. Because of rounding and conversion errors and + // such, it could be that the wait loop timed out, but + // the timer queue said it wasn't quite ready to expire a + // timer. In this case, max_wait_time won't have quite been + // reduced to 0, and we need to go around again. If max_wait_time + // is all the way to 0, just return, as the entire time the + // caller wanted to wait has been used up. + countdown.update (); // Reflect time waiting for events + if (0 == max_wait_time || max_wait_time->usec () == 0) + break; + } + } + while (result == 0); + + return result; +} + +int +ACE_WFMO_Reactor::ok_to_wait (ACE_Time_Value *max_wait_time, + int alertable) +{ + // Calculate the max time we should spend here + // + // Note: There is really no need to involve the here + // because even if a timeout in the does expire we + // will not be able to dispatch it + + // We need to wait for both the and event. + // If not on WinCE, use WaitForMultipleObjects() to wait for both atomically. + // On WinCE, the waitAll arg to WFMO must be false, so wait for the + // ok_to_wait_ event first (since that's likely to take the longest) then + // grab the lock and recheck the ok_to_wait_ event. When we can get them + // both, or there's an error/timeout, return. +#if defined (ACE_HAS_WINCE) + ACE_UNUSED_ARG (alertable); + ACE_Time_Value timeout; + if (max_wait_time != 0) + { + timeout = ACE_OS::gettimeofday (); + timeout += *max_wait_time; + } + while (1) + { + int status; + if (max_wait_time == 0) + status = this->ok_to_wait_.wait (); + else + status = this->ok_to_wait_.wait (&timeout); + if (status == -1) + return -1; + // The event is signaled, so it's ok to wait; grab the lock and + // recheck the event. If something has changed, restart the wait. + if (max_wait_time == 0) + status = this->lock_.acquire (); + else + { + status = this->lock_.acquire (timeout); + } + if (status == -1) + return -1; + + // Have the lock_, now re-check the event. If it's not signaled, + // another thread changed something so go back and wait again. + if (this->ok_to_wait_.wait (&ACE_Time_Value::zero, 0) == 0) + break; + this->lock_.release (); + } + return 1; + +#else + int timeout = max_wait_time == 0 ? INFINITE : max_wait_time->msec (); + DWORD result = 0; + while (1) + { +# if defined (ACE_HAS_PHARLAP) + // PharLap doesn't implement WaitForMultipleObjectsEx, and doesn't + // do async I/O, so it's not needed in this case anyway. + result = ::WaitForMultipleObjects (sizeof this->atomic_wait_array_ / sizeof (ACE_HANDLE), + this->atomic_wait_array_, + TRUE, + timeout); + + if (result != WAIT_IO_COMPLETION) + break; + +# else + result = ::WaitForMultipleObjectsEx (sizeof this->atomic_wait_array_ / sizeof (ACE_HANDLE), + this->atomic_wait_array_, + TRUE, + timeout, + alertable); + + if (result != WAIT_IO_COMPLETION) + break; + +# endif /* ACE_HAS_PHARLAP */ + } + + switch (result) + { + case WAIT_TIMEOUT: + errno = ETIME; + return 0; + case WAIT_FAILED: + case WAIT_ABANDONED_0: + ACE_OS::set_errno_to_last_error (); + return -1; + default: + break; + } + + // It is ok to enter ::WaitForMultipleObjects + return 1; +#endif /* ACE_HAS_WINCE */ +} + +DWORD +ACE_WFMO_Reactor::wait_for_multiple_events (int timeout, + int alertable) +{ + // Wait for any of handles_ to be active, or until timeout expires. + // If is enabled allow asynchronous completion of + // ReadFile and WriteFile operations. + +#if defined (ACE_HAS_PHARLAP) || defined (ACE_HAS_WINCE) + // PharLap doesn't do async I/O and doesn't implement + // WaitForMultipleObjectsEx, so use WaitForMultipleObjects. + ACE_UNUSED_ARG (alertable); + return ::WaitForMultipleObjects (this->handler_rep_.max_handlep1 (), + this->handler_rep_.handles (), + FALSE, + timeout); +#else + return ::WaitForMultipleObjectsEx (this->handler_rep_.max_handlep1 (), + this->handler_rep_.handles (), + FALSE, + timeout, + alertable); +#endif /* ACE_HAS_PHARLAP */ +} + +DWORD +ACE_WFMO_Reactor::poll_remaining_handles (DWORD slot) +{ + return ::WaitForMultipleObjects (this->handler_rep_.max_handlep1 () - slot, + this->handler_rep_.handles () + slot, + FALSE, + 0); +} + +int +ACE_WFMO_Reactor::calculate_timeout (ACE_Time_Value *max_wait_time) +{ + ACE_Time_Value *time = 0; + if (this->owner_ == ACE_Thread::self ()) + time = this->timer_queue_->calculate_timeout (max_wait_time); + else + time = max_wait_time; + + if (time == 0) + return INFINITE; + else + return time->msec (); +} + + +int +ACE_WFMO_Reactor::expire_timers (void) +{ + // If "owner" thread + if (ACE_Thread::self () == this->owner_) + // expire all pending timers. + return this->timer_queue_->expire (); + + else + // Nothing to expire + return 0; +} + +int +ACE_WFMO_Reactor::dispatch (DWORD wait_status) +{ + // Expire timers + int handlers_dispatched = this->expire_timers (); + + switch (wait_status) + { + case WAIT_FAILED: // Failure. + ACE_OS::set_errno_to_last_error (); + return -1; + + case WAIT_TIMEOUT: // Timeout. + errno = ETIME; + return handlers_dispatched; + +#ifndef ACE_HAS_WINCE + case WAIT_IO_COMPLETION: // APC. + return handlers_dispatched; +#endif // ACE_HAS_WINCE + + default: // Dispatch. + // We'll let dispatch worry about abandoned mutes. + handlers_dispatched += this->dispatch_handles (wait_status); + return handlers_dispatched; + } +} + +// Dispatches any active handles from to +// , polling through our handle set looking +// for active handles. +int +ACE_WFMO_Reactor::dispatch_handles (DWORD wait_status) +{ + // dispatch_slot is the absolute slot. Only += is used to + // increment it. + DWORD dispatch_slot = 0; + + // Cache this value, this is the absolute value. + DWORD const max_handlep1 = this->handler_rep_.max_handlep1 (); + + // nCount starts off at , this is a transient count of + // handles last waited on. + DWORD nCount = max_handlep1; + + for (int number_of_handlers_dispatched = 1; + ; + ++number_of_handlers_dispatched) + { + const bool ok = ( +#if ! defined(__BORLANDC__) \ + && !defined (ghs) \ + && !defined (__MINGW32__) \ + && !defined (_MSC_VER) + // wait_status is unsigned in Borland, Green Hills, + // mingw32 and MSVC++ + // This >= is always true, with a warning. + wait_status >= WAIT_OBJECT_0 && +#endif + wait_status <= (WAIT_OBJECT_0 + nCount)); + + if (ok) + dispatch_slot += wait_status - WAIT_OBJECT_0; + else + // Otherwise, a handle was abandoned. + dispatch_slot += wait_status - WAIT_ABANDONED_0; + + // Dispatch handler + if (this->dispatch_handler (dispatch_slot, max_handlep1) == -1) + return -1; + + // Increment slot + ++dispatch_slot; + + // We're done. + if (dispatch_slot >= max_handlep1) + return number_of_handlers_dispatched; + + // Readjust nCount + nCount = max_handlep1 - dispatch_slot; + + // Check the remaining handles + wait_status = this->poll_remaining_handles (dispatch_slot); + switch (wait_status) + { + case WAIT_FAILED: // Failure. + ACE_OS::set_errno_to_last_error (); + /* FALLTHRU */ + case WAIT_TIMEOUT: + // There are no more handles ready, we can return. + return number_of_handlers_dispatched; + } + } +} + +int +ACE_WFMO_Reactor::dispatch_handler (DWORD slot, + DWORD max_handlep1) +{ + // Check if there are window messages that need to be dispatched + if (slot == max_handlep1) + return this->dispatch_window_messages (); + + // Dispatch the handler if it has not been scheduled for deletion. + // Note that this is a very week test if there are multiple threads + // dispatching this slot as no locks are held here. Generally, you + // do not want to do something like deleting the this pointer in + // handle_close() if you have registered multiple times and there is + // more than one thread in WFMO_Reactor->handle_events(). + else if (!this->handler_rep_.scheduled_for_deletion (slot)) + { + ACE_HANDLE event_handle = *(this->handler_rep_.handles () + slot); + + if (this->handler_rep_.current_info ()[slot].io_entry_) + return this->complex_dispatch_handler (slot, + event_handle); + else + return this->simple_dispatch_handler (slot, + event_handle); + } + else + // The handle was scheduled for deletion, so we will skip it. + return 0; +} + +int +ACE_WFMO_Reactor::simple_dispatch_handler (DWORD slot, + ACE_HANDLE event_handle) +{ + // This dispatch is used for non-I/O entires + + // Assign the ``signaled'' HANDLE so that callers can get it. + // siginfo_t is an ACE - specific fabrication. Constructor exists. + siginfo_t sig (event_handle); + + ACE_Event_Handler *event_handler = + this->handler_rep_.current_info ()[slot].event_handler_; + + int requires_reference_counting = + event_handler->reference_counting_policy ().value () == + ACE_Event_Handler::Reference_Counting_Policy::ENABLED; + + if (requires_reference_counting) + { + event_handler->add_reference (); + } + + // Upcall + if (event_handler->handle_signal (0, &sig) == -1) + this->handler_rep_.unbind (event_handle, + ACE_Event_Handler::NULL_MASK); + + // Call remove_reference() if needed. + if (requires_reference_counting) + { + event_handler->remove_reference (); + } + + return 0; +} + +int +ACE_WFMO_Reactor::complex_dispatch_handler (DWORD slot, + ACE_HANDLE event_handle) +{ + // This dispatch is used for I/O entires. + + ACE_WFMO_Reactor_Handler_Repository::Current_Info ¤t_info = + this->handler_rep_.current_info ()[slot]; + + WSANETWORKEVENTS events; + ACE_Reactor_Mask problems = ACE_Event_Handler::NULL_MASK; + if (::WSAEnumNetworkEvents ((SOCKET) current_info.io_handle_, + event_handle, + &events) == SOCKET_ERROR) + problems = ACE_Event_Handler::ALL_EVENTS_MASK; + else + { + // Prepare for upcalls. Clear the bits from representing + // events the handler is not interested in. If there are any left, + // do the upcall(s). upcall will replace events.lNetworkEvents + // with bits representing any functions that requested a repeat + // callback before checking handles again. In this case, continue + // to call back unless the handler is unregistered as a result of + // one of the upcalls. The way this is written, the upcalls will + // keep being done even if one or more upcalls reported problems. + // In practice this may turn out not so good, but let's see. If any + // problems, please notify Steve Huston + // before or after you change this code. + events.lNetworkEvents &= current_info.network_events_; + while (events.lNetworkEvents != 0) + { + ACE_Event_Handler *event_handler = + current_info.event_handler_; + + int reference_counting_required = + event_handler->reference_counting_policy ().value () == + ACE_Event_Handler::Reference_Counting_Policy::ENABLED; + + // Call add_reference() if needed. + if (reference_counting_required) + { + event_handler->add_reference (); + } + + // Upcall + problems |= this->upcall (current_info.event_handler_, + current_info.io_handle_, + events); + + // Call remove_reference() if needed. + if (reference_counting_required) + { + event_handler->remove_reference (); + } + + if (this->handler_rep_.scheduled_for_deletion (slot)) + break; + } + } + + if (problems != ACE_Event_Handler::NULL_MASK + && !this->handler_rep_.scheduled_for_deletion (slot) ) + this->handler_rep_.unbind (event_handle, problems); + + return 0; +} + +ACE_Reactor_Mask +ACE_WFMO_Reactor::upcall (ACE_Event_Handler *event_handler, + ACE_HANDLE io_handle, + WSANETWORKEVENTS &events) +{ + // This method figures out what exactly has happened to the socket + // and then calls appropriate methods. + ACE_Reactor_Mask problems = ACE_Event_Handler::NULL_MASK; + + // Go through the events and do the indicated upcalls. If the handler + // doesn't want to be called back, clear the bit for that event. + // At the end, set the bits back to to request a repeat call. + + long actual_events = events.lNetworkEvents; + int action; + + if (ACE_BIT_ENABLED (actual_events, FD_WRITE)) + { + action = event_handler->handle_output (io_handle); + if (action <= 0) + { + ACE_CLR_BITS (actual_events, FD_WRITE); + if (action == -1) + ACE_SET_BITS (problems, ACE_Event_Handler::WRITE_MASK); + } + } + + if (ACE_BIT_ENABLED (actual_events, FD_CONNECT)) + { + if (events.iErrorCode[FD_CONNECT_BIT] == 0) + { + // Successful connect + action = event_handler->handle_output (io_handle); + if (action <= 0) + { + ACE_CLR_BITS (actual_events, FD_CONNECT); + if (action == -1) + ACE_SET_BITS (problems, + ACE_Event_Handler::CONNECT_MASK); + } + } + // Unsuccessful connect + else + { + action = event_handler->handle_input (io_handle); + if (action <= 0) + { + ACE_CLR_BITS (actual_events, FD_CONNECT); + if (action == -1) + ACE_SET_BITS (problems, + ACE_Event_Handler::CONNECT_MASK); + } + } + } + + if (ACE_BIT_ENABLED (actual_events, FD_OOB)) + { + action = event_handler->handle_exception (io_handle); + if (action <= 0) + { + ACE_CLR_BITS (actual_events, FD_OOB); + if (action == -1) + ACE_SET_BITS (problems, ACE_Event_Handler::EXCEPT_MASK); + } + } + + if (ACE_BIT_ENABLED (actual_events, FD_READ)) + { + action = event_handler->handle_input (io_handle); + if (action <= 0) + { + ACE_CLR_BITS (actual_events, FD_READ); + if (action == -1) + ACE_SET_BITS (problems, ACE_Event_Handler::READ_MASK); + } + } + + if (ACE_BIT_ENABLED (actual_events, FD_CLOSE) + && ACE_BIT_DISABLED (problems, ACE_Event_Handler::READ_MASK)) + { + action = event_handler->handle_input (io_handle); + if (action <= 0) + { + ACE_CLR_BITS (actual_events, FD_CLOSE); + if (action == -1) + ACE_SET_BITS (problems, ACE_Event_Handler::READ_MASK); + } + } + + if (ACE_BIT_ENABLED (actual_events, FD_ACCEPT)) + { + action = event_handler->handle_input (io_handle); + if (action <= 0) + { + ACE_CLR_BITS (actual_events, FD_ACCEPT); + if (action == -1) + ACE_SET_BITS (problems, ACE_Event_Handler::ACCEPT_MASK); + } + } + + if (ACE_BIT_ENABLED (actual_events, FD_QOS)) + { + action = event_handler->handle_qos (io_handle); + if (action <= 0) + { + ACE_CLR_BITS (actual_events, FD_QOS); + if (action == -1) + ACE_SET_BITS (problems, ACE_Event_Handler::QOS_MASK); + } + } + + if (ACE_BIT_ENABLED (actual_events, FD_GROUP_QOS)) + { + action = event_handler->handle_group_qos (io_handle); + if (action <= 0) + { + ACE_CLR_BITS (actual_events, FD_GROUP_QOS); + if (action == -1) + ACE_SET_BITS (problems, ACE_Event_Handler::GROUP_QOS_MASK); + } + } + + events.lNetworkEvents = actual_events; + return problems; +} + + +int +ACE_WFMO_Reactor::update_state (void) +{ + // This GUARD is necessary since we are updating shared state. + ACE_GUARD_RETURN (ACE_Process_Mutex, monitor, this->lock_, -1); + + // Decrement active threads + --this->active_threads_; + + // Check if the state of the handler repository has changed or new + // owner has to be set + if (this->handler_rep_.changes_required () || this->new_owner ()) + { + if (this->change_state_thread_ == 0) + // Try to become the thread which will be responsible for the + // changes + { + this->change_state_thread_ = ACE_Thread::self (); + // Make sure no new threads are allowed to enter + this->ok_to_wait_.reset (); + + if (this->active_threads_ > 0) + // Check for other active threads + { + // Wake up all other threads + this->wakeup_all_threads_.signal (); + // Release + monitor.release (); + // Go to sleep waiting for all other threads to get done + this->waiting_to_change_state_.wait (); + // Re-acquire again + monitor.acquire (); + } + + // Note that make_changes() calls into user code which can + // request other changes. So keep looping until all + // requested changes are completed. + while (this->handler_rep_.changes_required ()) + // Make necessary changes to the handler repository + this->handler_rep_.make_changes (); + if (this->new_owner ()) + // Update the owner + this->change_owner (); + // Turn off + this->wakeup_all_threads_.reset (); + // Let everyone know that it is ok to go ahead + this->ok_to_wait_.signal (); + // Reset this flag + this->change_state_thread_ = 0; + } + else if (this->active_threads_ == 0) + // This thread did not get a chance to become the change + // thread. If it is the last one out, it will wakeup the + // change thread + this->waiting_to_change_state_.signal (); + } + // This is if we were woken up explicitily by the user and there are + // no state changes required. + else if (this->active_threads_ == 0) + // Turn off + this->wakeup_all_threads_.reset (); + + return 0; +} + +void +ACE_WFMO_Reactor::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_WFMO_Reactor::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("Count of currently active threads = %d\n"), + this->active_threads_)); + + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("ID of owner thread = %d\n"), + this->owner_)); + + this->handler_rep_.dump (); + this->signal_handler_->dump (); + this->timer_queue_->dump (); + + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +int +ACE_WFMO_Reactor_Notify::dispatch_notifications (int & /*number_of_active_handles*/, + ACE_Handle_Set & /*rd_mask*/) +{ + return -1; +} + +int +ACE_WFMO_Reactor_Notify::is_dispatchable (ACE_Notification_Buffer & /*buffer*/) +{ + return 0; +} + +ACE_HANDLE +ACE_WFMO_Reactor_Notify::notify_handle (void) +{ + return ACE_INVALID_HANDLE; +} + +int +ACE_WFMO_Reactor_Notify::read_notify_pipe (ACE_HANDLE , + ACE_Notification_Buffer &) +{ + return 0; +} + +int +ACE_WFMO_Reactor_Notify::dispatch_notify (ACE_Notification_Buffer &) +{ + return 0; +} + +int +ACE_WFMO_Reactor_Notify::close (void) +{ + return -1; +} + +ACE_WFMO_Reactor_Notify::ACE_WFMO_Reactor_Notify (size_t max_notifies) + : timer_queue_ (0), + message_queue_ (max_notifies * sizeof (ACE_Notification_Buffer), + max_notifies * sizeof (ACE_Notification_Buffer)), + max_notify_iterations_ (-1) +{ +} + +int +ACE_WFMO_Reactor_Notify::open (ACE_Reactor_Impl *wfmo_reactor, + ACE_Timer_Queue *timer_queue, + int ignore_notify) +{ + ACE_UNUSED_ARG (ignore_notify); + timer_queue_ = timer_queue; + return wfmo_reactor->register_handler (this); +} + +ACE_HANDLE +ACE_WFMO_Reactor_Notify::get_handle (void) const +{ + return this->wakeup_one_thread_.handle (); +} + +// Handle all pending notifications. + +int +ACE_WFMO_Reactor_Notify::handle_signal (int signum, + siginfo_t *siginfo, + ucontext_t *) +{ + ACE_UNUSED_ARG (signum); + + // Just check for sanity... + if (siginfo->si_handle_ != this->wakeup_one_thread_.handle ()) + return -1; + + // This will get called when wakeup_one_thread_> event + // is signaled. + // ACE_DEBUG ((LM_DEBUG, + // ACE_TEXT ("(%t) waking up to handle internal notifications\n"))); + + for (int i = 1; ; ++i) + { + ACE_Message_Block *mb = 0; + // Copy ACE_Time_Value::zero since dequeue_head will modify it. + ACE_Time_Value zero_timeout (ACE_Time_Value::zero); + if (this->message_queue_.dequeue_head (mb, &zero_timeout) == -1) + { + if (errno == EWOULDBLOCK) + // We've reached the end of the processing, return + // normally. + return 0; + else + return -1; // Something weird happened... + } + else + { + ACE_Notification_Buffer *buffer = + reinterpret_cast (mb->base ()); + + // If eh == 0 then we've got major problems! Otherwise, we + // need to dispatch the appropriate handle_* method on the + // ACE_Event_Handler pointer we've been passed. + + if (buffer->eh_ != 0) + { + ACE_Event_Handler *event_handler = + buffer->eh_; + + bool const requires_reference_counting = + event_handler->reference_counting_policy ().value () == + ACE_Event_Handler::Reference_Counting_Policy::ENABLED; + + int result = 0; + + switch (buffer->mask_) + { + case ACE_Event_Handler::READ_MASK: + case ACE_Event_Handler::ACCEPT_MASK: + result = event_handler->handle_input (ACE_INVALID_HANDLE); + break; + case ACE_Event_Handler::WRITE_MASK: + result = event_handler->handle_output (ACE_INVALID_HANDLE); + break; + case ACE_Event_Handler::EXCEPT_MASK: + result = event_handler->handle_exception (ACE_INVALID_HANDLE); + break; + case ACE_Event_Handler::QOS_MASK: + result = event_handler->handle_qos (ACE_INVALID_HANDLE); + break; + case ACE_Event_Handler::GROUP_QOS_MASK: + result = event_handler->handle_group_qos (ACE_INVALID_HANDLE); + break; + default: + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("invalid mask = %d\n"), + buffer->mask_)); + break; + } + + if (result == -1) + event_handler->handle_close (ACE_INVALID_HANDLE, + ACE_Event_Handler::EXCEPT_MASK); + + if (requires_reference_counting) + { + event_handler->remove_reference (); + } + } + + // Make sure to delete the memory regardless of success or + // failure! + mb->release (); + + // Bail out if we've reached the . + // Note that by default is -1, so + // we'll loop until we're done. + if (i == this->max_notify_iterations_) + { + // If there are still notification in the queue, we need + // to wake up again + if (!this->message_queue_.is_empty ()) + this->wakeup_one_thread_.signal (); + + // Break the loop as we have reached max_notify_iterations_ + return 0; + } + } + } +} + +// Notify the WFMO_Reactor, potentially enqueueing the +// for subsequent processing in the WFMO_Reactor +// thread of control. + +int +ACE_WFMO_Reactor_Notify::notify (ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask, + ACE_Time_Value *timeout) +{ + if (event_handler != 0) + { + ACE_Message_Block *mb = 0; + ACE_NEW_RETURN (mb, + ACE_Message_Block (sizeof (ACE_Notification_Buffer)), + -1); + + ACE_Notification_Buffer *buffer = + (ACE_Notification_Buffer *) mb->base (); + buffer->eh_ = event_handler; + buffer->mask_ = mask; + + // Convert from relative time to absolute time by adding the + // current time of day. This is what + // expects. + if (timeout != 0) + *timeout += timer_queue_->gettimeofday (); + + if (this->message_queue_.enqueue_tail + (mb, timeout) == -1) + { + mb->release (); + return -1; + } + + event_handler->add_reference (); + } + + return this->wakeup_one_thread_.signal (); +} + +void +ACE_WFMO_Reactor_Notify::max_notify_iterations (int iterations) +{ + ACE_TRACE ("ACE_WFMO_Reactor_Notify::max_notify_iterations"); + // Must always be > 0 or < 0 to optimize the loop exit condition. + if (iterations == 0) + iterations = 1; + + this->max_notify_iterations_ = iterations; +} + +int +ACE_WFMO_Reactor_Notify::max_notify_iterations (void) +{ + ACE_TRACE ("ACE_WFMO_Reactor_Notify::max_notify_iterations"); + return this->max_notify_iterations_; +} + +int +ACE_WFMO_Reactor_Notify::purge_pending_notifications (ACE_Event_Handler *eh, + ACE_Reactor_Mask mask) +{ + ACE_TRACE ("ACE_WFMO_Reactor_Notify::purge_pending_notifications"); + + // Go over message queue and take out all the matching event + // handlers. If eh == 0, purge all. Note that reactor notifies (no + // handler specified) are never purged, as this may lose a needed + // notify the reactor queued for itself. + + if (this->message_queue_.is_empty ()) + return 0; + + // Guard against new and/or delivered notifications while purging. + // WARNING!!! The use of the notification queue's lock object for + // this guard makes use of the knowledge that on Win32, the mutex + // protecting the queue is really a CriticalSection, which is + // recursive. This is how we can get away with locking it down here + // and still calling member functions on the queue object. + ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, monitor, this->message_queue_.lock(), -1); + + // first, copy all to our own local queue. Since we've locked everyone out + // of here, there's no need to use any synchronization on this queue. + ACE_Message_Queue local_queue; + + size_t queue_size = this->message_queue_.message_count (); + int number_purged = 0; + + size_t index; + + for (index = 0; index < queue_size; ++index) + { + ACE_Message_Block *mb = 0; + if (-1 == this->message_queue_.dequeue_head (mb)) + return -1; // This shouldn't happen... + + ACE_Notification_Buffer *buffer = + reinterpret_cast (mb->base ()); + + // If this is not a Reactor notify (it is for a particular handler), + // and it matches the specified handler (or purging all), + // and applying the mask would totally eliminate the notification, then + // release it and count the number purged. + if ((0 != buffer->eh_) && + (0 == eh || eh == buffer->eh_) && + ACE_BIT_DISABLED (buffer->mask_, ~mask)) // the existing notification mask + // is left with nothing when + // applying the mask + { + ACE_Event_Handler *event_handler = buffer->eh_; + + event_handler->remove_reference (); + + mb->release (); + ++number_purged; + } + else + { + // To preserve it, move it to the local_queue. But first, if + // this is not a Reactor notify (it is for a + // particularhandler), and it matches the specified handler + // (or purging all), then apply the mask + if ((0 != buffer->eh_) && + (0 == eh || eh == buffer->eh_)) + ACE_CLR_BITS(buffer->mask_, mask); + if (-1 == local_queue.enqueue_head (mb)) + return -1; + } + } + + if (this->message_queue_.message_count ()) + { // Should be empty! + ACE_ASSERT (0); + return -1; + } + + // Now copy back from the local queue to the class queue, taking + // care to preserve the original order... + queue_size = local_queue.message_count (); + for (index = 0; index < queue_size; ++index) + { + ACE_Message_Block *mb = 0; + if (-1 == local_queue.dequeue_head (mb)) + { + ACE_ASSERT (0); + return -1; + } + + if (-1 == this->message_queue_.enqueue_head (mb)) + { + ACE_ASSERT (0); + return -1; + } + } + + return number_purged; +} + +void +ACE_WFMO_Reactor_Notify::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_WFMO_Reactor_Notify::dump"); + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + this->timer_queue_->dump (); + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("Max. iteration: %d\n"), + this->max_notify_iterations_)); + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +void +ACE_WFMO_Reactor::max_notify_iterations (int iterations) +{ + ACE_TRACE ("ACE_WFMO_Reactor::max_notify_iterations"); + ACE_GUARD (ACE_Process_Mutex, monitor, this->lock_); + + // Must always be > 0 or < 0 to optimize the loop exit condition. + this->notify_handler_->max_notify_iterations (iterations); +} + +int +ACE_WFMO_Reactor::max_notify_iterations (void) +{ + ACE_TRACE ("ACE_WFMO_Reactor::max_notify_iterations"); + ACE_GUARD_RETURN (ACE_Process_Mutex, monitor, this->lock_, -1); + + return this->notify_handler_->max_notify_iterations (); +} + +int +ACE_WFMO_Reactor::purge_pending_notifications (ACE_Event_Handler *eh, + ACE_Reactor_Mask mask) +{ + ACE_TRACE ("ACE_WFMO_Reactor::purge_pending_notifications"); + if (this->notify_handler_ == 0) + return 0; + else + return this->notify_handler_->purge_pending_notifications (eh, mask); +} + +int +ACE_WFMO_Reactor::resumable_handler (void) +{ + ACE_TRACE ("ACE_WFMO_Reactor::resumable_handler"); + return 0; +} + + +// No-op WinSOCK2 methods to help WFMO_Reactor compile +#if !defined (ACE_HAS_WINSOCK2) || (ACE_HAS_WINSOCK2 == 0) +int +WSAEventSelect (SOCKET /* s */, + WSAEVENT /* hEventObject */, + long /* lNetworkEvents */) +{ + return -1; +} + +int +WSAEnumNetworkEvents (SOCKET /* s */, + WSAEVENT /* hEventObject */, + LPWSANETWORKEVENTS /* lpNetworkEvents */) +{ + return -1; +} +#endif /* !defined ACE_HAS_WINSOCK2 */ + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_WIN32 */ diff --git a/dep/acelite/ace/WFMO_Reactor.h b/dep/acelite/ace/WFMO_Reactor.h new file mode 100644 index 00000000000..fb3a14d28cd --- /dev/null +++ b/dep/acelite/ace/WFMO_Reactor.h @@ -0,0 +1,1368 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file WFMO_Reactor.h + * + * $Id: WFMO_Reactor.h 84727 2009-03-05 19:22:29Z johnnyw $ + * + * @author Irfan Pyarali + * @author Tim Harrison + * @author Doug Schmidt + */ +//============================================================================= + +#ifndef ACE_WFMO_REACTOR_H +#define ACE_WFMO_REACTOR_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_WIN32) + +#include "ace/Signal.h" +#include "ace/Timer_Queue.h" +#include "ace/Event_Handler.h" +#include "ace/Auto_Event.h" +#include "ace/Manual_Event.h" +#include "ace/Condition_Thread_Mutex.h" +#include "ace/Lock_Adapter_T.h" +#include "ace/Reactor_Impl.h" +#include "ace/Message_Queue.h" +#include "ace/Process_Mutex.h" + +// If we don't have WinSOCK2, we need these defined +#if !defined (ACE_HAS_WINSOCK2) || (ACE_HAS_WINSOCK2 == 0) +/* + * WinSock 2 extension -- bit values and indices for FD_XXX network events + */ +#define FD_READ_BIT 0 +#define FD_WRITE_BIT 1 +#define FD_OOB_BIT 2 +#define FD_ACCEPT_BIT 3 +#define FD_CONNECT_BIT 4 +#define FD_CLOSE_BIT 5 +#define FD_QOS_BIT 6 +#define FD_GROUP_QOS_BIT 7 + +#define FD_QOS (1 << FD_QOS_BIT) +#define FD_GROUP_QOS (1 << FD_GROUP_QOS_BIT) + +#define FD_MAX_EVENTS 8 +#define FD_ALL_EVENTS ((1 << FD_MAX_EVENTS) - 1) + +#define WSAEVENT HANDLE + +typedef struct _WSANETWORKEVENTS +{ + long lNetworkEvents; + int iErrorCode[FD_MAX_EVENTS]; +} WSANETWORKEVENTS, FAR * LPWSANETWORKEVENTS; + +int WSAEventSelect (SOCKET s, + WSAEVENT hEventObject, + long lNetworkEvents); + +int WSAEnumNetworkEvents (SOCKET s, + WSAEVENT hEventObject, + LPWSANETWORKEVENTS lpNetworkEvents); + +#endif /* !defined ACE_HAS_WINSOCK2 */ + +class ACE_WFMO_Reactor_Test; // Must be out of versioned namespace. + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Forward decl. +class ACE_WFMO_Reactor; +class ACE_Handle_Set; + +/** + * @class ACE_Wakeup_All_Threads_Handler + * + * @brief This is a helper class whose sole purpose is to handle events + * on wakeup_all_threads_> + */ +class ACE_Export ACE_Wakeup_All_Threads_Handler : public ACE_Event_Handler +{ +public: + /// Called when the wakeup_all_threads_> + virtual int handle_signal (int signum, siginfo_t * = 0, ucontext_t * = 0); +}; + +/** + * @class ACE_WFMO_Reactor_Handler_Repository + * + * @internal This class is for internal ACE use only. + * + * @brief Used to map ACE_HANDLEs onto the appropriate + * ACE_Event_Handler * and other information. + */ +class ACE_Export ACE_WFMO_Reactor_Handler_Repository +{ +public: + friend class ACE_WFMO_Reactor; + friend class ACE_WFMO_Reactor_Test; + + /** + * @class Common_Info + * + * @brief This struct contains the necessary information for every + * entry. The reason the event is not in this + * structure is because we need to pass an event array into + * WaitForMultipleObjects and therefore keeping the events + * seperate makes sense. + */ + class Common_Info + { + public: + /// This indicates whether this entry is for I/O or for a regular + /// event + bool io_entry_; + + /// The assosiated + ACE_Event_Handler *event_handler_; + + /// The I/O handle related to the . This entry is + /// only valid if the flag is true. + ACE_HANDLE io_handle_; + + /** + * This is the set of events that the is + * interested in. This entry is only valid if the flag + * is true. + */ + long network_events_; + + /** + * This flag indicates that created the event on + * behalf of the user. Therefore we need to clean this up when the + * removes itself from . This entry + * is only valid if the flag is true. + */ + bool delete_event_; + + /// This is set when the entry needed to be deleted. + bool delete_entry_; + + /** + * These are the masks related to for the + * . This is only valid when is + * set. + */ + ACE_Reactor_Mask close_masks_; + + /// Constructor used for initializing the structure + Common_Info (void); + + /// Reset the state of the structure + void reset (void); + + /// Set the structure to these new values + void set (bool io_entry, + ACE_Event_Handler *event_handler, + ACE_HANDLE io_handle, + long network_events, + bool delete_event, + bool delete_entry, + ACE_Reactor_Mask close_masks); + + /// Set the structure to these new values + void set (Common_Info &common_info); + + /// Dump the state of an object. + void dump (void) const; + }; + + /** + * @class Current_Info + * + * @brief This structure inherits from the common structure to add + * information for current entries. + */ + class Current_Info : public Common_Info + { + public: + /// This is set when the entry needed to be suspended. + bool suspend_entry_; + + /// Default constructor + Current_Info (void); + + /// Reset the state of the structure + void reset (void); + + /// Set the structure to these new values + void set (bool io_entry, + ACE_Event_Handler *event_handler, + ACE_HANDLE io_handle, + long network_events, + bool delete_event, + bool delete_entry = false, + ACE_Reactor_Mask close_masks = ACE_Event_Handler::NULL_MASK, + bool suspend_entry = false); + + /// Set the structure to these new values + void set (Common_Info &common_info, + bool suspend_entry = false); + + /// Dump the state of an object. + void dump (ACE_HANDLE event_handle) const; + }; + + /** + * @class To_Be_Added_Info + * + * @brief This structure inherits from the common structure to add + * information for entries. + */ + class To_Be_Added_Info : public Common_Info + { + public: + /// Handle for the event + ACE_HANDLE event_handle_; + + /// This is set when the entry needed to be suspended. + bool suspend_entry_; + + /// Default constructor + To_Be_Added_Info (void); + + /// Reset the state of the structure + void reset (void); + + /// Set the structure to these new values + void set (ACE_HANDLE event_handle, + bool io_entry, + ACE_Event_Handler *event_handler, + ACE_HANDLE io_handle, + long network_events, + bool delete_event, + bool delete_entry = false, + ACE_Reactor_Mask close_masks = ACE_Event_Handler::NULL_MASK, + bool suspend_entry = false); + + /// Set the structure to these new values + void set (ACE_HANDLE event_handle, + Common_Info &common_info, + bool suspend_entry = false); + + /// Dump the state of an object. + void dump (void) const; + }; + + /** + * @class Suspended_Info + * + * @brief This structure inherits from the common structure to add + * information for suspended entries. + */ + class Suspended_Info : public Common_Info + { + public: + /// Handle for the event + ACE_HANDLE event_handle_; + + /// This is set when the entry needed to be resumed. + bool resume_entry_; + + /// Constructor used for initializing the structure + Suspended_Info (void); + + /// Reset the state of the structure + void reset (void); + + /// Set the structure to these new values + void set (ACE_HANDLE event_handle, + bool io_entry, + ACE_Event_Handler *event_handler, + ACE_HANDLE io_handle, + long network_events, + bool delete_event, + bool delete_entry = false, + ACE_Reactor_Mask close_masks = 0, + bool resume_entry = false); + + /// Set the structure to these new values + void set (ACE_HANDLE event_handle, + Common_Info &common_info, + bool resume_entry = false); + + /// Dump the state of an object. + void dump (void) const; + }; + + /// Constructor. + ACE_WFMO_Reactor_Handler_Repository (ACE_WFMO_Reactor &wfmo_reactor); + + /// Destructor. + virtual ~ACE_WFMO_Reactor_Handler_Repository (void); + + /// Initialize the repository of the approriate @a size. + int open (size_t size); + + /// Close down the handler repository. + int close (void); + + // = Search structure operations. + + /// Bind the to the ACE_HANDLE. This is for + /// the simple event entry. + int bind (ACE_HANDLE, ACE_Event_Handler *); + + /// Insert I/O entry into the system. This method + /// assumes that the lock are head *before* this method is invoked. + int bind_i (bool io_entry, + ACE_Event_Handler *event_handler, + long network_events, + ACE_HANDLE io_handle, + ACE_HANDLE event_handle, + bool delete_event); + + /// Remove the binding of ACE_HANDLE in accordance with the @a mask. + int unbind (ACE_HANDLE, + ACE_Reactor_Mask mask); + + /// Non-lock-grabbing version of + int unbind_i (ACE_HANDLE, + ACE_Reactor_Mask mask, + bool &changes_required); + + /// Remove all bindings of tuples. + void unbind_all (void); + + // = Sanity checking. + + // Check the @a handle to make sure it's a valid ACE_HANDLE + int invalid_handle (ACE_HANDLE handle) const; + + // = Accessors. + /// Maximum ACE_HANDLE value, plus 1. + DWORD max_handlep1 (void) const; + + /// Pointer to the beginning of the current array of ACE_HANDLE + /// *'s. + ACE_HANDLE *handles (void) const; + + /// Pointer to the beginning of the current array of + /// ACE_Event_Handler *'s. + Current_Info *current_info (void) const; + + /// Check if changes to the handle set are required. + virtual bool changes_required (void); + + /// Make changes to the handle set + virtual int make_changes (void); + + /// Check to see if @a slot has been scheduled for deletion + int scheduled_for_deletion (size_t slot) const; + + /** + * This method is used to calculate the network mask after a mask_op + * request to . Note that because the + * may already be in the handler repository, we may have to find the + * old event and the old network events + */ + int modify_network_events_i (ACE_HANDLE io_handle, + ACE_Reactor_Mask new_masks, + ACE_Reactor_Mask &old_masks, + long &new_network_events, + ACE_HANDLE &event_handle, + bool &delete_event, + int operation); + + /// This method is used to change the network mask left (if any) + /// after a remove request to + ACE_Reactor_Mask bit_ops (long &existing_masks, + ACE_Reactor_Mask to_be_removed_masks, + int operation); + + /// Temporarily suspend entry + int suspend_handler_i (ACE_HANDLE handle, + bool &changes_required); + + /// Resume suspended entry + int resume_handler_i (ACE_HANDLE handle, + bool &changes_required); + + /// Deletions and suspensions in current_info_ + int make_changes_in_current_infos (void); + + /// Deletions and resumptions in current_suspended_info_ + int make_changes_in_suspension_infos (void); + + /// Deletions in to_be_added_info_, or transfers to current_info_ or + /// current_suspended_info_ from to_be_added_info_ + int make_changes_in_to_be_added_infos (void); + + /// Removes the ACE_Event_Handler at @a slot from the table. + int remove_handler_i (size_t slot, + ACE_Reactor_Mask mask); + + /// Removes the ACE_Event_Handler at @a slot from the table. + int remove_suspended_handler_i (size_t slot, + ACE_Reactor_Mask mask); + + /// Removes the ACE_Event_Handler at @a slot from the table. + int remove_to_be_added_handler_i (size_t slot, + ACE_Reactor_Mask to_be_removed_masks); + + /** + * Return the Event_Handler associated with @a handle. Return 0 if + * @a handle is not registered. + */ + ACE_Event_Handler *find_handler (ACE_HANDLE handle); + + /** + * Check to see if @a handle is associated with a valid Event_Handler + * bound to @a mask. Return the @a event_handler associated with this + * @a handler if @a event_handler != 0. + */ + int handler (ACE_HANDLE handle, + ACE_Reactor_Mask mask, + ACE_Event_Handler **event_handler = 0); + + /** + * Check to see if @a handle is associated with a valid + * Event_Handler. Return Event_Handler and associated masks. + */ + ACE_Event_Handler *handler (ACE_HANDLE handle, + long &existing_masks); + + /// Dump the state of an object. + void dump (void) const; + +protected: + /// Reference to our . + ACE_WFMO_Reactor &wfmo_reactor_; + + /// Maximum number of handles. + size_t max_size_; + + /** + * Array of passed to . This + * is not part of the structure as the handle array needs to be + * passed directly to . + */ + ACE_HANDLE *current_handles_; + + /// Array of current entries in the table + Current_Info *current_info_; + + /// A count of the number of active handles. + DWORD max_handlep1_; + + /// Information for entries to be added + To_Be_Added_Info *to_be_added_info_; + + /// Number of records to be added + size_t handles_to_be_added_; + + /// Currently suspended handles + Suspended_Info *current_suspended_info_; + + /// Number of currently suspended handles + size_t suspended_handles_; + + /// Number of records to be suspended + size_t handles_to_be_suspended_; + + /// Number of records to be resumed + size_t handles_to_be_resumed_; + + /// Number of records to be deleted + size_t handles_to_be_deleted_; + +}; + +/** + * @class ACE_WFMO_Reactor_Notify + * + * @brief Unblock the from its event loop, passing + * it an optional ACE_Event_Handler to dispatch. + * + * This implementation is necessary for cases where the + * is run in a multi-threaded program. In + * this case, we need to be able to unblock + * when updates occur other than in the + * main thread. To do this, we signal an + * auto-reset event the is listening on. If + * an ACE_Event_Handler and ACE_Reactor_Mask is passed to + * , the appropriate method is dispatched. + */ +class ACE_Export ACE_WFMO_Reactor_Notify : public ACE_Reactor_Notify +{ +public: + /// Constructor + ACE_WFMO_Reactor_Notify (size_t max_notifies = 1024); + + /// Initialization. is stored to call . + virtual int open (ACE_Reactor_Impl *wfmo_reactor, + ACE_Timer_Queue *timer_queue, + int disable_notify = 0); + + /// No-op. + virtual int close (void); + + /** + * Special trick to unblock when updates + * occur. All we do is enqueue @a event_handler and @a mask onto the + * ACE_Message_Queue and wakeup the by signaling + * its handle. The ACE_Time_Value indicates how long + * to blocking trying to notify the . If @a timeout == + * 0, the caller will block until action is possible, else will wait + * until the relative time specified in @a timeout elapses). + */ + virtual int notify (ACE_Event_Handler *event_handler = 0, + ACE_Reactor_Mask mask = ACE_Event_Handler::EXCEPT_MASK, + ACE_Time_Value *timeout = 0); + + /// No-op. + virtual int dispatch_notifications (int &number_of_active_handles, + ACE_Handle_Set &rd_mask); + + /// Returns a handle to the . + virtual ACE_HANDLE get_handle (void) const; + + /// Returns the ACE_HANDLE of the notify pipe on which the reactor + /// is listening for notifications so that other threads can unblock + /// the + virtual ACE_HANDLE notify_handle (void); + + /// Handle one of the notify call on the . This could be + /// because of a thread trying to unblock the + virtual int dispatch_notify (ACE_Notification_Buffer &buffer); + + /// Verify whether the buffer has dispatchable info or not. + virtual int is_dispatchable (ACE_Notification_Buffer &buffer); + + /// Read one of the notify call on the @a handle into the + /// . This could be because of a thread trying to unblock + /// the + virtual int read_notify_pipe (ACE_HANDLE handle, + ACE_Notification_Buffer &buffer); + + /** + * Set the maximum number of times that the + * method will iterate and + * dispatch the ACE_Event_Handlers that are passed in via the + * notify queue before breaking out of its + * loop. By default, this is set to + * -1, which means "iterate until the queue is empty." Setting this + * to a value like "1 or 2" will increase "fairness" (and thus + * prevent starvation) at the expense of slightly higher dispatching + * overhead. + */ + void max_notify_iterations (int); + + /** + * Get the maximum number of times that the + * method will iterate and + * dispatch the ACE_Event_Handlers that are passed in via the + * notify queue before breaking out of its + * loop. + */ + int max_notify_iterations (void); + + /** + * Purge any notifications pending in this reactor for the specified + * ACE_Event_Handler object. If @a eh == 0, all notifications for all + * handlers are removed (but not any notifications posted just to wake up + * the reactor itself). Returns the number of notifications purged. + * Returns -1 on error. + */ + virtual int purge_pending_notifications (ACE_Event_Handler *, + ACE_Reactor_Mask = ACE_Event_Handler::ALL_EVENTS_MASK); + + /// Dump the state of an object. + virtual void dump (void) const; + +private: + /// Pointer to the wfmo_reactor's timer queue. + ACE_Timer_Queue *timer_queue_; + + /** + * Called when the notification event waited on by + * is signaled. This dequeues all pending + * ACE_Event_Handlers and dispatches them. + */ + virtual int handle_signal (int signum, siginfo_t * = 0, ucontext_t * = 0); + + /// An auto event is used so that we can it to wakeup one + /// thread up (e.g., when the method is called). + ACE_Auto_Event wakeup_one_thread_; + + /// Message queue that keeps track of pending ACE_Event_Handlers. + /// This queue must be thread-safe because it can be called by + /// multiple threads of control. + ACE_Message_Queue message_queue_; + + /** + * Keeps track of the maximum number of times that the + * method will iterate and + * dispatch the ACE_Event_Handlers that are passed in via the + * notify queue before breaking out of its + * loop. By default, this is set to + * -1, which means "iterate until the queue is empty." + */ + int max_notify_iterations_; +}; + +/** + * @class ACE_WFMO_Reactor + * + * @brief An object oriented event demultiplexor and event handler. + * ACE_WFMO_Reactor is a Windows-only implementation of the ACE_Reactor + * interface that uses the WaitForMultipleObjects() event demultiplexer. + * + * Like the other ACE Reactors, ACE_WFMO_Reactor can schedule timers. + * It also reacts to signalable handles, such as events (see the documentation + * for WaitForMultipleObjects() for a complete list of signalable handle + * types). Therefore, I/O handles are not directly usable for registering + * for input, output, and exception notification. The exception to this + * is ACE_SOCK-based handles, which can be registered for input, output, and + * exception notification just as with other platforms. See Chapter 4 in + * C++NPv2 for complete details. + * + * Note that changes to the state of ACE_WFMO_Reactor are not + * instantaneous. Most changes (registration, removal, + * suspension, and resumption of handles, and changes in + * ownership) are made when the ACE_WFMO_Reactor reaches a stable + * state. Users should be careful, especially when removing + * handlers. This is because the ACE_WFMO_Reactor will call + * handle_close() on the handler when it is finally removed and + * not when remove_handler() is called. If the registered handler's pointer + * is not valid when ACE_WFMO_Reactor calls ACE_Event_Handler::handle_close(), + * use the DONT_CALL flag with remove_handler(). Preferably, use dynamically + * allocated event handlers and call "delete this" inside the handle_close() + * hook method. + * + * Note that although multiple threads can concurrently run the + * ACE_WFMO_Reactor event loop, the concept of the reactor "owner" is still + * important. Only the owner thread can expire timers and wait on the + * notifications handle. Thus, be careful to properly set the owner thread + * when spawning threads to run the event loop while you are using timers + * or notifications. + */ +class ACE_Export ACE_WFMO_Reactor : public ACE_Reactor_Impl +{ +public: + friend class ACE_WFMO_Reactor_Handler_Repository; + friend class ACE_WFMO_Reactor_Test; + + enum + { + /// Default size of the WFMO_Reactor's handle table. + /** + * Two slots will be added to the @a size parameter in the + * constructor and open methods which will store handles used for + * internal management purposes. + */ + DEFAULT_SIZE = MAXIMUM_WAIT_OBJECTS - 2 + }; + + // = Initialization and termination methods. + + /// Initialize ACE_WFMO_Reactor with the default size. + ACE_WFMO_Reactor (ACE_Sig_Handler * = 0, + ACE_Timer_Queue * = 0, + ACE_Reactor_Notify * = 0); + + /** + * Initialize ACE_WFMO_Reactor with the specified size. + * + * @param size The maximum number of handles the reactor can + * register. The value should not exceed + * ACE_WFMO_Reactor::DEFAULT_SIZE. Two slots will be + * added to the @a size parameter which will store handles + * used for internal management purposes. + */ + ACE_WFMO_Reactor (size_t size, + int unused = 0, + ACE_Sig_Handler * = 0, + ACE_Timer_Queue * = 0, + ACE_Reactor_Notify * = 0); + + /** + * Initialize ACE_WFMO_Reactor with the specified size. + * + * @param size The maximum number of handles the reactor can + * register. The value should not exceed + * ACE_WFMO_Reactor::DEFAULT_SIZE. Two slots will be + * added to the @a size parameter which will store handles + * used for internal management purposes. + */ + virtual int open (size_t size = ACE_WFMO_Reactor::DEFAULT_SIZE, + bool restart = false, + ACE_Sig_Handler * = 0, + ACE_Timer_Queue * = 0, + int disable_notify_pipe = 0, + ACE_Reactor_Notify * = 0); + + /// Returns -1 (not used in this implementation); + virtual int current_info (ACE_HANDLE, size_t & /* size */); + + /// Use a user specified signal handler instead. + virtual int set_sig_handler (ACE_Sig_Handler *signal_handler); + + /// Set a user-specified timer queue. + virtual int timer_queue (ACE_Timer_Queue *tq); + + /// Return the current ACE_Timer_Queue. + virtual ACE_Timer_Queue *timer_queue (void) const; + + /// Close down the ACE_WFMO_Reactor and release all of its resources. + virtual int close (void); + + /// Close down the ACE_WFMO_Reactor and release all of its resources. + virtual ~ACE_WFMO_Reactor (void); + + // = Event loop drivers. + + /** + * This method is not currently implemented. We recommend that you + * use handle_events (ACE_Time_Value::zero) to get basically the + * same effect, i.e., it won't block the caller if there are no events. + */ + virtual int work_pending (const ACE_Time_Value &max_wait_time = ACE_Time_Value::zero); + + /** + * This event loop driver blocks for up to @a max_wait_time before + * returning. It will return earlier if timer events, I/O events, + * or signal events occur. Note that @a max_wait_time can be 0, in + * which case this method blocks indefinitely until events occur. + * + * @a max_wait_time is decremented to reflect how much time this call + * took. For instance, if a time value of 3 seconds is passed to + * handle_events and an event occurs after 2 seconds, + * @a max_wait_time will equal 1 second. This can be used if an + * application wishes to handle events for some fixed amount of + * time. + * + * is used as the demultiplexing call + * + * Returns the total number of I/O and timer ACE_Event_Handlers + * that were dispatched, 0 if the @a max_wait_time elapsed without + * dispatching any handlers, or -1 if an error occurs. + * + * The only difference between and + * is that in the alertable case, TRUE is passed to + * for the option. + */ + virtual int handle_events (ACE_Time_Value *max_wait_time = 0); + virtual int alertable_handle_events (ACE_Time_Value *max_wait_time = 0); + + /** + * This method is just like the one above, except the + * @a max_wait_time value is a reference and can therefore never be + * NULL. + * + * The only difference between and + * is that in the alertable case, TRUE is passed to + * for the option. + */ + virtual int handle_events (ACE_Time_Value &max_wait_time); + virtual int alertable_handle_events (ACE_Time_Value &max_wait_time); + + + // = Event handling control. + + /** + * Return the status of Reactor. If this function returns 0, the reactor is + * actively handling events. If it returns non-zero, and + * return -1 immediately. + */ + virtual int deactivated (void); + + /** + * Control whether the Reactor will handle any more incoming events or not. + * If == 1, the Reactor will be disabled. By default, a reactor + * is in active state and can be deactivated/reactived as wish. + */ + virtual void deactivate (int do_stop); + + // = Register and remove Handlers. + + /** + * Register an ACE_Event_Handler @a event_handler. Since no Event + * Mask is passed through this interface, it is assumed that the + * @a handle being passed in is an event handle and when the event + * becomes signaled, will call handle_signal on + * @a event_handler. If @a handle == the + * will call the method of + * @a event_handler to extract the underlying event handle. + */ + virtual int register_handler (ACE_Event_Handler *event_handler, + ACE_HANDLE event_handle = ACE_INVALID_HANDLE); + + /** + * Register an ACE_Event_Handler . @a mask specifies + * the network events that the is interested in. If + * == the will + * call the method of to extract the + * underlying I/O handle. If the == + * , WFMO_Reactor will create an event for + * associating it with the I/O handle. When the is + * signalled, the appropriate callback will be invoked on + * the + */ + virtual int register_handler (ACE_HANDLE event_handle, + ACE_HANDLE io_handle, + ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask); + + /** + * This is a simple version of the above method + * where the I/O handle is passed in and the event handle will + * always be created by + */ + virtual int register_handler (ACE_HANDLE io_handle, + ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask); + + /** + * This is a simple version of the above method + * where the I/O handle will always come from on the + * and the event handle will always be created by + * + */ + virtual int register_handler (ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask); + + /// Register @a event_handler with all the @a handles in the + /// . + virtual int register_handler (const ACE_Handle_Set &handles, + ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask); + + /** + * Register @a new_sh to handle the signal @a signum using the + * @a new_disp. Returns the @a old_sh that was previously registered + * (if any), along with the @a old_disp of the signal handler. + */ + virtual int register_handler (int signum, + ACE_Event_Handler *new_sh, + ACE_Sig_Action *new_disp = 0, + ACE_Event_Handler **old_sh = 0, + ACE_Sig_Action *old_disp = 0); + + /// Registers @a new_sh to handle a set of signals @a sigset using the + /// @a new_disp. + virtual int register_handler (const ACE_Sig_Set &sigset, + ACE_Event_Handler *new_sh, + ACE_Sig_Action *new_disp = 0); + + /** + * Removes @a event_handler from the . Note that + * the will call the method of + * @a event_handler to extract the underlying handle. If @a mask == + * ACE_Event_Handler::DONT_CALL then the method of + * the @a event_handler is not invoked. Note that the @a handle can + * either be the or the + */ + virtual int remove_handler (ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask); + + /** + * Removes @a handle from the . If @a mask == + * ACE_Event_Handler::DONT_CALL then the method of + * the is not invoked. Note that the @a handle can + * either be the or the + * + * For the case of I/O entries, this removes the @a mask binding of + * whose handle is @a handle from . If + * there are no more bindings for this then it is + * removed from the WFMO_Reactor. For simple event entries, mask is + * mostly ignored and the is always removed from + * + */ + virtual int remove_handler (ACE_HANDLE handle, + ACE_Reactor_Mask mask); + + /** + * Removes all the @a mask bindings for handles in the @a handle_set + * bind of . If there are no more bindings for any + * of these handles then they are removed from WFMO_Reactor. + */ + virtual int remove_handler (const ACE_Handle_Set &handle_set, + ACE_Reactor_Mask); + + /** + * Remove the ACE_Event_Handler currently associated with @a signum. + * @a sigkey is ignored in this implementation since there is only + * one instance of a signal handler. Install the new disposition + * (if given) and return the previous disposition (if desired by the + * caller). Returns 0 on success and -1 if @a signum is invalid. + */ + virtual int remove_handler (int signum, + ACE_Sig_Action *new_disp, + ACE_Sig_Action *old_disp = 0, + int sigkey = -1); + + /// Calls for every signal in @a sigset. + virtual int remove_handler (const ACE_Sig_Set &sigset); + + // = Suspend and resume Handlers. + + /// Suspend @a event_handler temporarily. Use + /// to get the handle. + virtual int suspend_handler (ACE_Event_Handler *event_handler); + + /// Suspend @a handle temporarily. + virtual int suspend_handler (ACE_HANDLE handle); + + /// Suspend all @a handles in handle set temporarily. + virtual int suspend_handler (const ACE_Handle_Set &handles); + + /// Suspend all temporarily. + virtual int suspend_handlers (void); + + /// Resume @a event_handler. Use to + /// get the handle. + virtual int resume_handler (ACE_Event_Handler *event_handler); + + /// Resume @a handle. + virtual int resume_handler (ACE_HANDLE handle); + + /// Resume all @a handles in handle set. + virtual int resume_handler (const ACE_Handle_Set &handles); + + /// Resume all . + virtual int resume_handlers (void); + + /// Does the reactor allow the application to resume the handle on + /// its own ie. can it pass on the control of handle resumption to + /// the application. A positive value indicates that the handlers + /// are application resumable. A value of 0 indicates otherwise. + virtual int resumable_handler (void); + + /** + * Return true if we any event associations were made by the reactor + * for the handles that it waits on, false otherwise. Since the + * WFMO_Reactor does use event associations, this function always + * return true. + */ + virtual bool uses_event_associations (void); + + // Timer management. + + /** + * Schedule an ACE_Event_Handler that will expire after an amount + * of time. The return value of this method, a timer_id value, + * uniquely identifies the event_handler in the ACE_Reactor's + * internal list of timers. + * This timer_id value can be used to cancel the timer + * with the cancel_timer() call. + * + * @see cancel_timer() + * @see reset_timer_interval() + * + * @param event_handler event handler to schedule on reactor + * @param arg argument passed to the handle_timeout() method of event_handler + * @param delay time interval after which the timer will expire + * @param interval time interval after which the timer will be automatically rescheduled + * @return -1 on failure, a timer_id value on success + */ + virtual long schedule_timer (ACE_Event_Handler *event_handler, + const void *arg, + const ACE_Time_Value &delay, + const ACE_Time_Value &interval = ACE_Time_Value::zero); + + /** + * Resets the interval of the timer represented by @a timer_id to + * @a interval, which is specified in relative time to the current + * . If @a interval is equal to + * ACE_Time_Value::zero, the timer will become a non-rescheduling + * timer. Returns 0 if successful, -1 if not. + */ + virtual int reset_timer_interval (long timer_id, + const ACE_Time_Value &interval); + + /// Cancel all Event_Handlers that match the address of + /// @a event_handler. Returns number of handler's cancelled. + virtual int cancel_timer (ACE_Event_Handler *event_handler, + int dont_call_handle_close = 1); + + /** + * Cancel the single Event_Handler that matches the @a timer_id value + * (which was returned from the schedule method). If arg is + * non-NULL then it will be set to point to the ``magic cookie'' + * argument passed in when the Event_Handler was registered. This + * makes it possible to free up the memory and avoid memory leaks. + * Returns 1 if cancellation succeeded and 0 if the @a timer_id + * wasn't found. + */ + virtual int cancel_timer (long timer_id, + const void **arg = 0, + int dont_call_handle_close = 1); + + // = High-level Event_Handler scheduling operations + + /** + * Add @a masks_to_be_added to the @a event_handler's entry in + * WFMO_Reactor. @a event_handler must already have been registered + * with WFMO_Reactor. + */ + virtual int schedule_wakeup (ACE_Event_Handler *event_handler, + ACE_Reactor_Mask masks_to_be_added); + + /** + * Add @a masks_to_be_added to the @a handle's entry in WFMO_Reactor. + * The Event_Handler associated with @a handle must already have been + * registered with WFMO_Reactor. + */ + virtual int schedule_wakeup (ACE_HANDLE handle, + ACE_Reactor_Mask masks_to_be_added); + + /** + * Remove to the 's entry in + * WFMO_Reactor. The Event_Handler associated with must + * already have been registered with WFMO_Reactor. + */ + virtual int cancel_wakeup (ACE_Event_Handler *event_handler, + ACE_Reactor_Mask masks_to_be_deleted); + + /** + * Remove to the 's entry in + * WFMO_Reactor. The Event_Handler associated with must + * already have been registered with WFMO_Reactor. + */ + virtual int cancel_wakeup (ACE_HANDLE handle, + ACE_Reactor_Mask masks_to_be_deleted); + + // = Notification methods. + + /** + * Wakeup one thread if it is currently blocked + * in . The ACE_Time_Value indicates how + * long to blocking trying to notify the . If + * @a timeout == 0, the caller will block until action is possible, + * else will wait until the relative time specified in @a timeout + * elapses). + */ + virtual int notify (ACE_Event_Handler * = 0, + ACE_Reactor_Mask = ACE_Event_Handler::EXCEPT_MASK, + ACE_Time_Value * = 0); + + /** + * Set the maximum number of times that the + * method will iterate and + * dispatch the ACE_Event_Handlers that are passed in via the + * notify queue before breaking out of its + * loop. By default, this is set to + * -1, which means "iterate until the queue is empty." Setting this + * to a value like "1 or 2" will increase "fairness" (and thus + * prevent starvation) at the expense of slightly higher dispatching + * overhead. + */ + virtual void max_notify_iterations (int); + + /** + * Get the maximum number of times that the + * method will iterate and + * dispatch the ACE_Event_Handlers that are passed in via the + * notify queue before breaking out of its + * loop. + */ + virtual int max_notify_iterations (void); + + /** + * Purge any notifications pending in this reactor for the specified + * ACE_Event_Handler object. Returns the number of notifications + * purged. Returns -1 on error. + */ + virtual int purge_pending_notifications (ACE_Event_Handler * = 0, + ACE_Reactor_Mask = ACE_Event_Handler::ALL_EVENTS_MASK); + + // = Assorted helper methods. + + /** + * Return the Event_Handler associated with . Return 0 if + * is not registered. + */ + ACE_Event_Handler *find_handler (ACE_HANDLE handle); + + /** + * Check to see if is associated with a valid Event_Handler + * bound to @a mask. Return the @a event_handler associated with this + * @a handler if @a event_handler != 0. + */ + virtual int handler (ACE_HANDLE handle, + ACE_Reactor_Mask mask, + ACE_Event_Handler **event_handler = 0); + + /** + * Check to see if @a signum is associated with a valid Event_Handler + * bound to a signal. Return the associated with + * this @a handler if != 0. + */ + virtual int handler (int signum, + ACE_Event_Handler ** = 0); + + /// Returns true if WFMO_Reactor has been successfully initialized, else + /// false. + virtual bool initialized (void); + + /// Returns the current size of the WFMO_Reactor's internal + /// descriptor table. + virtual size_t size (void) const; + + /// Returns a reference to the WFMO_Reactor's internal lock. + virtual ACE_Lock &lock (void); + + /// Wake up all threads in WaitForMultipleObjects so that they can + /// reconsult the handle set + virtual void wakeup_all_threads (void); + + /** + * Transfers ownership of the WFMO_Reactor to the @a new_owner. The + * transfer will not complete until all threads are ready (just like + * the handle set). + */ + virtual int owner (ACE_thread_t new_owner, ACE_thread_t *old_owner = 0); + + /// Return the ID of the "owner" thread. + virtual int owner (ACE_thread_t *owner); + + /// Get the existing restart value. + virtual bool restart (void); + + /// Set a new value for restart and return the original value. + virtual bool restart (bool r); + + /// Not implemented + virtual void requeue_position (int); + + /// Not implemented + virtual int requeue_position (void); + + // = Low-level wait_set mask manipulation methods. + + /** + * Modify @a masks of the @a event_handler's entry in WFMO_Reactor + * depending upon . @a event_handler must already have + * been registered with WFMO_Reactor. + */ + virtual int mask_ops (ACE_Event_Handler *event_handler, + ACE_Reactor_Mask masks, + int operation); + + /** + * Modify @a masks of the 's entry in WFMO_Reactor depending + * upon . must already have been registered + * with WFMO_Reactor. + */ + virtual int mask_ops (ACE_HANDLE handle, + ACE_Reactor_Mask masks, + int ops); + + // = Low-level ready_set mask manipulation methods. + + /// Not implemented + virtual int ready_ops (ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask, + int ops); + + /// Not implemented + virtual int ready_ops (ACE_HANDLE handle, + ACE_Reactor_Mask, + int ops); + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; + + /// Dump the state of an object. + virtual void dump (void) const; + +protected: + /// Registration workhorse + virtual int register_handler_i (ACE_HANDLE event_handle, + ACE_HANDLE io_handle, + ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask); + + /// Event handling workhorse + virtual int event_handling (ACE_Time_Value *max_wait_time = 0, + int alertable = 0); + + /// Bit masking workhorse + virtual int mask_ops_i (ACE_HANDLE io_handle, + ACE_Reactor_Mask masks, + int operation); + + /// Return the ID of the "owner" thread. Does not do any locking. + virtual ACE_thread_t owner_i (void); + + /// Wait up to @a max_wait_time until it's ok to enter + /// WaitForMultipleObjects. Returns 1 (and holding lock_) if ok to wait; + /// -1 (and not holding lock_) if not. + virtual int ok_to_wait (ACE_Time_Value *max_wait_time, + int alertable); + + /// Wait for timer and I/O events to occur. + virtual DWORD wait_for_multiple_events (int timeout, + int alertable); + + /// Check for activity on remaining handles. + virtual DWORD poll_remaining_handles (DWORD slot); + + /// Expire timers. Only the owner thread does useful stuff in this + /// function. + virtual int expire_timers (void); + + /// Dispatches the timers and I/O handlers. + virtual int dispatch (DWORD wait_status); + + /// Protect against structured exceptions caused by user code when + /// dispatching handles + virtual int safe_dispatch (DWORD wait_status); + + /** + * Dispatches any active handles from handles_[@a slot] to + * handles_[active_handles_] using to poll + * through our handle set looking for active handles. + */ + virtual int dispatch_handles (DWORD slot); + + /// Dispatches a single handler. Returns 0 on success, -1 if the + /// handler was removed. + virtual int dispatch_handler (DWORD slot, + DWORD max_handlep1); + + /// Dispatches a single handler. Returns 0 on success, -1 if the + /// handler was removed. + virtual int simple_dispatch_handler (DWORD slot, + ACE_HANDLE event_handle); + + /// Dispatches a single handler. Returns 0 on success, -1 if the + /// handler was removed. + virtual int complex_dispatch_handler (DWORD slot, + ACE_HANDLE event_handle); + + /// Dispatches window messages. Noop for WFMO_Reactor. + virtual int dispatch_window_messages (void); + + virtual ACE_Reactor_Mask upcall (ACE_Event_Handler *event_handler, + ACE_HANDLE io_handle, + WSANETWORKEVENTS &events); + + /// Used to caluculate the next timeout + virtual int calculate_timeout (ACE_Time_Value *time); + + /// Update the state of the handler repository + virtual int update_state (void); + + /// Check to see if we have a new owner + virtual int new_owner (void); + + /// Set owner to new owner + virtual int change_owner (void); + + /// Handle signals without requiring global/static variables. + ACE_Sig_Handler *signal_handler_; + + /// Keeps track of whether we should delete the signal handler (if we + /// didn't create it, then we don't delete it). + bool delete_signal_handler_; + + /// Defined as a pointer to allow overriding by derived classes... + ACE_Timer_Queue *timer_queue_; + + /// Keeps track of whether we should delete the timer queue (if we + /// didn't create it, then we don't delete it). + bool delete_timer_queue_; + + /// Keeps track of whether we should delete the handler repository + bool delete_handler_rep_; + + /// Used when is called. + ACE_Reactor_Notify *notify_handler_; + + /// Keeps track of whether we should delete the notify handler. + bool delete_notify_handler_; + + /** + * Synchronization for the ACE_WFMO_Reactor. + * + * A Process Mutex is used here because of two reasons: + * (a) The implementation of ACE_Thread_Mutex uses CriticalSections + * CriticalSections are not waitable using ::WaitForMultipleObjects + * (b) This is really not a process mutex because it is not + * named. No other process can use this mutex. + */ + ACE_Process_Mutex lock_; + + /// Adapter used to return internal lock to outside world. + ACE_Lock_Adapter lock_adapter_; + + /// Table that maps to 's. + ACE_WFMO_Reactor_Handler_Repository handler_rep_; + + /// A manual event used to block threads from proceeding into + /// WaitForMultipleObjects + ACE_Manual_Event ok_to_wait_; + + /** + * A manual event is used so that we can wake everyone up (e.g., + * when ACE_Event_Handlers are bounded and unbound from the + * handler repository). + */ + ACE_Manual_Event wakeup_all_threads_; + + /// Used when is signaled + ACE_Wakeup_All_Threads_Handler wakeup_all_threads_handler_; + + /// The changing thread waits on this event, till all threads are not + /// active anymore + ACE_Auto_Event waiting_to_change_state_; + + /// Count of currently active threads + size_t active_threads_; + + /** + * The thread which is "owner" of the WFMO_Reactor. The owner + * concept is used because we don't want multiple threads to try to + * expire timers. Therefore the "owner" thread is the only one + * allowed to expire timers. Also, the owner thread is the only + * thread which waits on the notify handle. Note that the ownership + * can be transferred. + */ + ACE_thread_t owner_; + + /// The owner to be of the WFMO_Reactor + ACE_thread_t new_owner_; + + /// This is the thread which is responsible for the changing the + /// state of the handle set + ACE_thread_t change_state_thread_; + + /// This is an array of ACE_HANDLEs which keep track of the + /// and handles + ACE_HANDLE atomic_wait_array_ [2]; + + /// This flag is used to keep track of whether we are already closed. + bool open_for_business_; + + /// This flag is used to keep track of whether we are actively handling + /// events or not. + sig_atomic_t deactivated_; + +private: + /// Deny access since member-wise won't work... + ACE_WFMO_Reactor (const ACE_WFMO_Reactor &); + ACE_WFMO_Reactor &operator = (const ACE_WFMO_Reactor &); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/WFMO_Reactor.inl" +#endif /* __ACE_INLINE__ */ + +#endif /* ACE_WIN32 */ +#include /**/ "ace/post.h" +#endif /* ACE_WFMO_REACTOR_H */ diff --git a/dep/acelite/ace/WFMO_Reactor.inl b/dep/acelite/ace/WFMO_Reactor.inl new file mode 100644 index 00000000000..6d3e43db67e --- /dev/null +++ b/dep/acelite/ace/WFMO_Reactor.inl @@ -0,0 +1,1202 @@ +// -*- C++ -*- +// +// $Id: WFMO_Reactor.inl 82949 2008-10-06 22:32:10Z shuston $ + +#include "ace/Handle_Set.h" +#include "ace/Reactor.h" +#include "ace/Thread.h" +#include "ace/Sig_Handler.h" +#include "ace/OS_NS_errno.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/************************************************************/ + +ACE_INLINE int +ACE_Wakeup_All_Threads_Handler::handle_signal (int /* signum */, + siginfo_t * /* siginfo */, + ucontext_t *) +{ + // This will get called when wakeup_all_threads_> event + // is signaled. There is nothing to be done here. + // ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) waking up to get updated handle set info\n"))); + return 0; +} + +#if defined (ACE_WIN32) + +/************************************************************/ + +ACE_INLINE +ACE_WFMO_Reactor_Handler_Repository::Common_Info::Common_Info (void) + : io_entry_ (false), + event_handler_ (0), + io_handle_ (ACE_INVALID_HANDLE), + network_events_ (0), + delete_event_ (false), + delete_entry_ (false), + close_masks_ (ACE_Event_Handler::NULL_MASK) +{ +} + +ACE_INLINE void +ACE_WFMO_Reactor_Handler_Repository::Common_Info::reset (void) +{ + this->event_handler_ = 0; + this->io_entry_ = false; + this->io_handle_ = ACE_INVALID_HANDLE; + this->network_events_ = 0; + this->delete_event_ = false; + this->delete_entry_ = false; + this->close_masks_ = ACE_Event_Handler::NULL_MASK; +} + +ACE_INLINE void +ACE_WFMO_Reactor_Handler_Repository::Common_Info::set (bool io_entry, + ACE_Event_Handler *event_handler, + ACE_HANDLE io_handle, + long network_events, + bool delete_event, + bool delete_entry, + ACE_Reactor_Mask close_masks) +{ + this->event_handler_ = event_handler; + this->io_entry_ = io_entry; + this->io_handle_ = io_handle; + this->network_events_ = network_events; + this->delete_event_ = delete_event; + this->delete_entry_ = delete_entry; + this->close_masks_ = close_masks; +} + +ACE_INLINE void +ACE_WFMO_Reactor_Handler_Repository::Common_Info::set (Common_Info &common_info) +{ + *this = common_info; +} + +ACE_INLINE void +ACE_WFMO_Reactor_Handler_Repository::Common_Info::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_WFMO_Reactor_Handler_Repository::Common_Info::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("I/O Entry = %d\n"), + this->io_entry_)); + + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("Event Handler = %d\n"), + this->event_handler_)); + + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("I/O Handle = %d\n"), + this->io_handle_)); + + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("Network Events = %d\n"), + this->network_events_)); + + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("Delete Event = %d\n"), + this->delete_event_)); + + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("Delete Entry = %d\n"), + this->delete_entry_)); + + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("Close Masks = %d\n"), + this->close_masks_)); + + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +/************************************************************/ + +ACE_INLINE +ACE_WFMO_Reactor_Handler_Repository::Current_Info::Current_Info (void) + : suspend_entry_ (false) +{ +} + +ACE_INLINE void +ACE_WFMO_Reactor_Handler_Repository::Current_Info::set (bool io_entry, + ACE_Event_Handler *event_handler, + ACE_HANDLE io_handle, + long network_events, + bool delete_event, + bool delete_entry, + ACE_Reactor_Mask close_masks, + bool suspend_entry) +{ + this->suspend_entry_ = suspend_entry; + Common_Info::set (io_entry, + event_handler, + io_handle, + network_events, + delete_event, + delete_entry, + close_masks); +} + +ACE_INLINE void +ACE_WFMO_Reactor_Handler_Repository::Current_Info::set (Common_Info &common_info, + bool suspend_entry) +{ + this->suspend_entry_ = suspend_entry; + Common_Info::set (common_info); +} + +ACE_INLINE void +ACE_WFMO_Reactor_Handler_Repository::Current_Info::reset (void) +{ + this->suspend_entry_ = false; + Common_Info::reset (); +} + +ACE_INLINE void +ACE_WFMO_Reactor_Handler_Repository::Current_Info::dump (ACE_HANDLE event_handle) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_WFMO_Reactor_Handler_Repository::Current_Info::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + + Common_Info::dump (); + + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("Event Handle = %d\n"), + event_handle)); + + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("Suspend Entry = %d\n"), + this->suspend_entry_)); + + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#else /* !ACE_HAS_DUMP */ + ACE_UNUSED_ARG (event_handle); +#endif /* ACE_HAS_DUMP */ +} + +/************************************************************/ + +ACE_INLINE +ACE_WFMO_Reactor_Handler_Repository::To_Be_Added_Info::To_Be_Added_Info (void) + : event_handle_ (ACE_INVALID_HANDLE), + suspend_entry_ (false) +{ +} + +ACE_INLINE void +ACE_WFMO_Reactor_Handler_Repository::To_Be_Added_Info::set (ACE_HANDLE event_handle, + bool io_entry, + ACE_Event_Handler *event_handler, + ACE_HANDLE io_handle, + long network_events, + bool delete_event, + bool delete_entry, + ACE_Reactor_Mask close_masks, + bool suspend_entry) +{ + this->event_handle_ = event_handle; + this->suspend_entry_ = suspend_entry; + Common_Info::set (io_entry, + event_handler, + io_handle, + network_events, + delete_event, + delete_entry, + close_masks); +} + +ACE_INLINE void +ACE_WFMO_Reactor_Handler_Repository::To_Be_Added_Info::set (ACE_HANDLE event_handle, + Common_Info &common_info, + bool suspend_entry) +{ + this->event_handle_ = event_handle; + this->suspend_entry_ = suspend_entry; + Common_Info::set (common_info); +} + +ACE_INLINE void +ACE_WFMO_Reactor_Handler_Repository::To_Be_Added_Info::reset (void) +{ + this->event_handle_ = ACE_INVALID_HANDLE; + this->suspend_entry_ = false; + Common_Info::reset (); +} + +ACE_INLINE void +ACE_WFMO_Reactor_Handler_Repository::To_Be_Added_Info::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_WFMO_Reactor_Handler_Repository::To_Be_Added_Info::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + + Common_Info::dump (); + + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("Event Handle = %d\n"), + this->event_handle_)); + + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("Suspend Entry = %d\n"), + this->suspend_entry_)); + + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +/************************************************************/ + +ACE_INLINE +ACE_WFMO_Reactor_Handler_Repository::Suspended_Info::Suspended_Info (void) + : event_handle_ (ACE_INVALID_HANDLE), + resume_entry_ (false) +{ +} + +ACE_INLINE void +ACE_WFMO_Reactor_Handler_Repository::Suspended_Info::reset (void) +{ + this->event_handle_ = ACE_INVALID_HANDLE; + this->resume_entry_ = false; + Common_Info::reset (); +} + +ACE_INLINE void +ACE_WFMO_Reactor_Handler_Repository::Suspended_Info::set (ACE_HANDLE event_handle, + bool io_entry, + ACE_Event_Handler *event_handler, + ACE_HANDLE io_handle, + long network_events, + bool delete_event, + bool delete_entry, + ACE_Reactor_Mask close_masks, + bool resume_entry) +{ + this->event_handle_ = event_handle; + this->resume_entry_ = resume_entry; + Common_Info::set (io_entry, + event_handler, + io_handle, + network_events, + delete_event, + delete_entry, + close_masks); +} + +ACE_INLINE void +ACE_WFMO_Reactor_Handler_Repository::Suspended_Info::set (ACE_HANDLE event_handle, + Common_Info &common_info, + bool resume_entry) +{ + this->event_handle_ = event_handle; + this->resume_entry_ = resume_entry; + Common_Info::set (common_info); +} + +ACE_INLINE void +ACE_WFMO_Reactor_Handler_Repository::Suspended_Info::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_WFMO_Reactor_Handler_Repository::Suspended_Info::dump"); + + ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + + Common_Info::dump (); + + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("Event Handle = %d\n"), + this->event_handle_)); + + ACE_DEBUG ((LM_DEBUG, + ACE_TEXT ("Resume Entry = %d\n"), + this->resume_entry_)); + + ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +/************************************************************/ + +ACE_INLINE int +ACE_WFMO_Reactor_Handler_Repository::close (void) +{ + // Let all the handlers know that the is closing down + this->unbind_all (); + + return 0; +} + +ACE_INLINE ACE_HANDLE * +ACE_WFMO_Reactor_Handler_Repository::handles (void) const +{ + // This code is probably too subtle to be useful in the long run... + // The basic idea is that all threads wait on all user handles plus + // the handle. The owner thread additional + // waits on the handle. This is to ensure that only the + // thread get to expire timers and handle event on the + // notify pipe. + if (ACE_Thread::self () == this->wfmo_reactor_.owner_i ()) + return this->current_handles_; + else + return this->current_handles_ + 1; +} + +ACE_INLINE ACE_WFMO_Reactor_Handler_Repository::Current_Info * +ACE_WFMO_Reactor_Handler_Repository::current_info (void) const +{ + if (ACE_Thread::self () == this->wfmo_reactor_.owner_i ()) + return this->current_info_; + else + return this->current_info_ + 1; +} + +ACE_INLINE DWORD +ACE_WFMO_Reactor_Handler_Repository::max_handlep1 (void) const +{ + if (ACE_Thread::self () == this->wfmo_reactor_.owner_i ()) + return this->max_handlep1_; + else + return this->max_handlep1_ - 1; +} + +ACE_INLINE int +ACE_WFMO_Reactor_Handler_Repository::scheduled_for_deletion (size_t slot) const +{ + if (ACE_Thread::self () == this->wfmo_reactor_.owner_i ()) + return this->current_info_[slot].delete_entry_ == true; + else + return this->current_info_[slot + 1].delete_entry_ == true; +} + +ACE_INLINE int +ACE_WFMO_Reactor_Handler_Repository::invalid_handle (ACE_HANDLE handle) const +{ + ACE_TRACE ("ACE_WFMO_Reactor_Handler_Repository::invalid_handle"); + // It's too expensive to perform more exhaustive validity checks on + // Win32 due to the way that they implement SOCKET HANDLEs. + if (handle == ACE_INVALID_HANDLE) + { + errno = EINVAL; + return 1; + } + else + return 0; +} + +ACE_INLINE bool +ACE_WFMO_Reactor_Handler_Repository::changes_required (void) +{ + // Check if handles have be scheduled for additions or removal + return this->handles_to_be_added_ > 0 + || this->handles_to_be_deleted_ > 0 + || this->handles_to_be_suspended_ > 0 + || this->handles_to_be_resumed_ > 0; +} + +ACE_INLINE int +ACE_WFMO_Reactor_Handler_Repository::make_changes (void) +{ + // This method must ONLY be called by the + // change_state_thread_>. We therefore assume that + // there will be no contention for this method and hence no guards + // are neccessary. + + // Deletions and suspensions in current_info_ + this->make_changes_in_current_infos (); + + // Deletions and resumptions in current_suspended_info_ + this->make_changes_in_suspension_infos (); + + // Deletions in to_be_added_info_, or transfers to current_info_ or + // current_suspended_info_ from to_be_added_info_ + this->make_changes_in_to_be_added_infos (); + + return 0; +} + +ACE_INLINE int +ACE_WFMO_Reactor_Handler_Repository::unbind (ACE_HANDLE handle, + ACE_Reactor_Mask mask) +{ + if (this->invalid_handle (handle)) + return -1; + + ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->wfmo_reactor_.lock_, -1); + + bool changes_required = false; + int const result = this->unbind_i (handle, + mask, + changes_required); + + if (changes_required) + // Wake up all threads in WaitForMultipleObjects so that they can + // reconsult the handle set + this->wfmo_reactor_.wakeup_all_threads (); + + return result; +} + +ACE_INLINE int +ACE_WFMO_Reactor::reset_timer_interval + (long timer_id, + const ACE_Time_Value &interval) +{ + ACE_TRACE ("ACE_WFMO_Reactor::reset_timer_interval"); + + if (0 != this->timer_queue_) + { + long result = this->timer_queue_->reset_interval + (timer_id, + interval); + + // Wakeup the owner thread so that it gets the latest timer values + this->notify (); + + return result; + } + + errno = ESHUTDOWN; + return -1; +} + +ACE_INLINE long +ACE_WFMO_Reactor::schedule_timer (ACE_Event_Handler *handler, + const void *arg, + const ACE_Time_Value &delay_time, + const ACE_Time_Value &interval) +{ + ACE_TRACE ("ACE_WFMO_Reactor::schedule_timer"); + + if (0 != this->timer_queue_) + { + long result = this->timer_queue_->schedule + (handler, + arg, + timer_queue_->gettimeofday () + delay_time, + interval); + + // Wakeup the owner thread so that it gets the latest timer values + this->notify (); + + return result; + } + + errno = ESHUTDOWN; + return -1; +} + +ACE_INLINE int +ACE_WFMO_Reactor::cancel_timer (ACE_Event_Handler *handler, + int dont_call_handle_close) +{ + ACE_TRACE ("ACE_WFMO_Reactor::cancel_timer"); + if (0 != this->timer_queue_) + return this->timer_queue_->cancel (handler, dont_call_handle_close); + return 0; +} + +ACE_INLINE int +ACE_WFMO_Reactor::cancel_timer (long timer_id, + const void **arg, + int dont_call_handle_close) +{ + ACE_TRACE ("ACE_WFMO_Reactor::cancel_timer"); + if (0 != this->timer_queue_) + return this->timer_queue_->cancel (timer_id, arg, dont_call_handle_close); + return 0; +} + +ACE_INLINE int +ACE_WFMO_Reactor::register_handler (ACE_Event_Handler *event_handler, + ACE_HANDLE event_handle) +{ + // This GUARD is necessary since we are updating shared state. + ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); + + return this->handler_rep_.bind_i (0, + event_handler, + 0, + ACE_INVALID_HANDLE, + event_handle, + 0); +} + +ACE_INLINE int +ACE_WFMO_Reactor::register_handler (ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask) +{ + // This GUARD is necessary since we are updating shared state. + ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); + + return this->register_handler_i (ACE_INVALID_HANDLE, + ACE_INVALID_HANDLE, + event_handler, + mask); +} + +ACE_INLINE int +ACE_WFMO_Reactor::register_handler (ACE_HANDLE io_handle, + ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask) +{ + // This GUARD is necessary since we are updating shared state. + ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); + + return this->register_handler_i (ACE_INVALID_HANDLE, + io_handle, + event_handler, + mask); +} + +ACE_INLINE int +ACE_WFMO_Reactor::register_handler (ACE_HANDLE event_handle, + ACE_HANDLE io_handle, + ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask) +{ + // This GUARD is necessary since we are updating shared state. + ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); + + return this->register_handler_i (event_handle, + io_handle, + event_handler, + mask); +} + +ACE_INLINE int +ACE_WFMO_Reactor::register_handler (const ACE_Handle_Set &handles, + ACE_Event_Handler *handler, + ACE_Reactor_Mask mask) +{ + // This GUARD is necessary since we are updating shared state. + ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); + + ACE_Handle_Set_Iterator handle_iter (handles); + ACE_HANDLE h; + + while ((h = handle_iter ()) != ACE_INVALID_HANDLE) + if (this->register_handler_i (h, + ACE_INVALID_HANDLE, + handler, + mask) == -1) + return -1; + + return 0; +} + +ACE_INLINE int +ACE_WFMO_Reactor::schedule_wakeup (ACE_HANDLE io_handle, + ACE_Reactor_Mask masks_to_be_added) +{ + // This GUARD is necessary since we are updating shared state. + ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); + + return this->mask_ops_i (io_handle, + masks_to_be_added, + ACE_Reactor::ADD_MASK); +} + +ACE_INLINE int +ACE_WFMO_Reactor::schedule_wakeup (ACE_Event_Handler *event_handler, + ACE_Reactor_Mask masks_to_be_added) +{ + // This GUARD is necessary since we are updating shared state. + ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); + + return this->mask_ops_i (event_handler->get_handle (), + masks_to_be_added, + ACE_Reactor::ADD_MASK); +} + +ACE_INLINE int +ACE_WFMO_Reactor::cancel_wakeup (ACE_HANDLE io_handle, + ACE_Reactor_Mask masks_to_be_removed) +{ + // This GUARD is necessary since we are updating shared state. + ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); + + return this->mask_ops_i (io_handle, + masks_to_be_removed, + ACE_Reactor::CLR_MASK); +} + +ACE_INLINE int +ACE_WFMO_Reactor::cancel_wakeup (ACE_Event_Handler *event_handler, + ACE_Reactor_Mask masks_to_be_removed) +{ + // This GUARD is necessary since we are updating shared state. + ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); + + return this->mask_ops_i (event_handler->get_handle (), + masks_to_be_removed, + ACE_Reactor::CLR_MASK); +} + +ACE_INLINE int +ACE_WFMO_Reactor::remove_handler (ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask) +{ + return this->handler_rep_.unbind (event_handler->get_handle (), + mask); +} + +ACE_INLINE int +ACE_WFMO_Reactor::remove_handler (ACE_HANDLE handle, + ACE_Reactor_Mask mask) +{ + return this->handler_rep_.unbind (handle, + mask); +} + +ACE_INLINE int +ACE_WFMO_Reactor::remove_handler (const ACE_Handle_Set &handles, + ACE_Reactor_Mask mask) +{ + ACE_Handle_Set_Iterator handle_iter (handles); + ACE_HANDLE h; + bool changes_required = false; + + ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); + + while ((h = handle_iter ()) != ACE_INVALID_HANDLE) + if (this->handler_rep_.unbind_i (h, + mask, + changes_required) == -1) + return -1; + + // Wake up all threads in WaitForMultipleObjects so that they can + // reconsult the handle set + this->wakeup_all_threads (); + + return 0; +} + +ACE_INLINE int +ACE_WFMO_Reactor::suspend_handler (ACE_HANDLE handle) +{ + ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); + + bool changes_required = false; + int const result = + this->handler_rep_.suspend_handler_i (handle, + changes_required); + + if (changes_required) + // Wake up all threads in WaitForMultipleObjects so that they can + // reconsult the handle set + this->wakeup_all_threads (); + + return result; +} + +ACE_INLINE int +ACE_WFMO_Reactor::suspend_handler (ACE_Event_Handler *event_handler) +{ + return this->suspend_handler (event_handler->get_handle ()); +} + +ACE_INLINE int +ACE_WFMO_Reactor::suspend_handler (const ACE_Handle_Set &handles) +{ + ACE_Handle_Set_Iterator handle_iter (handles); + ACE_HANDLE h; + bool changes_required = false; + + ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); + + while ((h = handle_iter ()) != ACE_INVALID_HANDLE) + if (this->handler_rep_.suspend_handler_i (h, + changes_required) == -1) + return -1; + + // Wake up all threads in WaitForMultipleObjects so that they can + // reconsult the handle set + this->wakeup_all_threads (); + + return 0; +} + +ACE_INLINE int +ACE_WFMO_Reactor::suspend_handlers (void) +{ + bool error = false; + int result = 0; + ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); + + // First suspend all current handles + bool changes_required = false; + + // Skip over the notify and wakeup_all_threads handles. These are registered + // by ACE_WFMO_Reactor::open(), not by users, and should not be suspended. + for (size_t i = 2; + i < this->handler_rep_.max_handlep1_ && !error; + i++) + { + result = + this->handler_rep_.suspend_handler_i (this->handler_rep_.current_handles_[i], + changes_required); + if (result == -1) + error = true; + } + + // Then suspend all to_be_added_handles + for (size_t i = 0; + i < this->handler_rep_.handles_to_be_added_ && !error; + i++) + { + if (this->handler_rep_.to_be_added_info_[i].io_entry_) + { + result = + this->handler_rep_.suspend_handler_i (this->handler_rep_.to_be_added_info_[i].io_handle_, + changes_required); + } + else + { + result = + this->handler_rep_.suspend_handler_i (this->handler_rep_.to_be_added_info_[i].event_handle_, + changes_required); + } + if (result == -1) + error = true; + } + + // Wake up all threads in WaitForMultipleObjects so that they can + // reconsult the handle set + this->wakeup_all_threads (); + + return error ? -1 : 0; +} + +ACE_INLINE int +ACE_WFMO_Reactor::resume_handler (ACE_HANDLE handle) +{ + ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); + + bool changes_required = false; + int result = + this->handler_rep_.resume_handler_i (handle, changes_required); + + if (changes_required) + // Wake up all threads in WaitForMultipleObjects so that they can + // reconsult the handle set + this->wakeup_all_threads (); + + return result; +} + +ACE_INLINE int +ACE_WFMO_Reactor::resume_handler (ACE_Event_Handler *event_handler) +{ + return this->resume_handler (event_handler->get_handle ()); +} + +ACE_INLINE int +ACE_WFMO_Reactor::resume_handler (const ACE_Handle_Set &handles) +{ + ACE_Handle_Set_Iterator handle_iter (handles); + ACE_HANDLE h; + bool changes_required = false; + + ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); + + while ((h = handle_iter ()) != ACE_INVALID_HANDLE) + if (this->handler_rep_.resume_handler_i (h, + changes_required) == -1) + return -1; + + // Wake up all threads in WaitForMultipleObjects so that they can + // reconsult the handle set + this->wakeup_all_threads (); + + return 0; +} + +ACE_INLINE int +ACE_WFMO_Reactor::resume_handlers (void) +{ + bool error = false; + int result = 0; + ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); + + bool changes_required = false; + for (size_t i = 0; + i < this->handler_rep_.suspended_handles_ && !error; + i++) + { + result = + this->handler_rep_.resume_handler_i (this->handler_rep_.current_suspended_info_[i].event_handle_, + changes_required); + if (result == -1) + error = true; + } + + // Then resume all to_be_added_handles + for (size_t i = 0; + i < this->handler_rep_.handles_to_be_added_ && !error; + i++) + { + if (this->handler_rep_.to_be_added_info_[i].io_entry_) + { + result = + this->handler_rep_.resume_handler_i (this->handler_rep_.to_be_added_info_[i].io_handle_, + changes_required); + } + else + { + result = + this->handler_rep_.resume_handler_i (this->handler_rep_.to_be_added_info_[i].event_handle_, + changes_required); + } + if (result == -1) + error = true; + } + + // Wake up all threads in WaitForMultipleObjects so that they can + // reconsult the handle set + this->wakeup_all_threads (); + + return error ? -1 : 0; +} + +ACE_INLINE bool +ACE_WFMO_Reactor::uses_event_associations (void) +{ + // Since the WFMO_Reactor does use event associations, this function + // always return 1. + return true; +} + +ACE_INLINE int +ACE_WFMO_Reactor::handle_events (ACE_Time_Value &how_long) +{ + return this->event_handling (&how_long, FALSE); +} + +ACE_INLINE int +ACE_WFMO_Reactor::alertable_handle_events (ACE_Time_Value &how_long) +{ + return this->event_handling (&how_long, TRUE); +} + +ACE_INLINE int +ACE_WFMO_Reactor::handle_events (ACE_Time_Value *how_long) +{ + return this->event_handling (how_long, FALSE); +} + +ACE_INLINE int +ACE_WFMO_Reactor::alertable_handle_events (ACE_Time_Value *how_long) +{ + return this->event_handling (how_long, TRUE); +} + +ACE_INLINE int +ACE_WFMO_Reactor::deactivated (void) +{ + return this->deactivated_; +} + +ACE_INLINE void +ACE_WFMO_Reactor::deactivate (int do_stop) +{ + this->deactivated_ = do_stop; + this->wakeup_all_threads (); +} + +ACE_INLINE int +ACE_WFMO_Reactor::owner (ACE_thread_t *t) +{ + ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); + *t = this->owner_i (); + return 0; +} + +ACE_INLINE ACE_thread_t +ACE_WFMO_Reactor::owner_i (void) +{ + return this->owner_; +} + +ACE_INLINE int +ACE_WFMO_Reactor::owner (ACE_thread_t new_owner, ACE_thread_t *old_owner) +{ + ACE_GUARD_RETURN (ACE_Process_Mutex, monitor, this->lock_, -1); + this->new_owner_ = new_owner; + + if (old_owner != 0) + *old_owner = this->owner_i (); + + // Wake up all threads in WaitForMultipleObjects so that they can + // reconsult the new owner responsibilities + this->wakeup_all_threads (); + + return 0; +} + +ACE_INLINE int +ACE_WFMO_Reactor::new_owner (void) +{ + return this->new_owner_ != ACE_thread_t (0); +} + +ACE_INLINE int +ACE_WFMO_Reactor::change_owner (void) +{ + this->owner_ = this->new_owner_; + this->new_owner_ = ACE_thread_t (0); + return 0; +} + +ACE_INLINE int +ACE_WFMO_Reactor::safe_dispatch (DWORD wait_status) +{ + int result = -1; + ACE_SEH_TRY + { + result = this->dispatch (wait_status); + } + ACE_SEH_FINALLY + { + this->update_state (); + } + + return result; +} + +ACE_INLINE int +ACE_WFMO_Reactor::dispatch_window_messages (void) +{ + return 0; +} + +ACE_INLINE void +ACE_WFMO_Reactor::wakeup_all_threads (void) +{ + this->wakeup_all_threads_.signal (); +} + +ACE_INLINE int +ACE_WFMO_Reactor::notify (ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask, + ACE_Time_Value *timeout) +{ + return this->notify_handler_->notify (event_handler, mask, timeout); +} + +ACE_INLINE int +ACE_WFMO_Reactor::register_handler (int signum, + ACE_Event_Handler *new_sh, + ACE_Sig_Action *new_disp, + ACE_Event_Handler **old_sh, + ACE_Sig_Action *old_disp) +{ + return this->signal_handler_->register_handler (signum, + new_sh, new_disp, + old_sh, old_disp); +} + +ACE_INLINE int +ACE_WFMO_Reactor::register_handler (const ACE_Sig_Set &sigset, + ACE_Event_Handler *new_sh, + ACE_Sig_Action *new_disp) +{ + int result = 0; + +#if (ACE_NSIG > 0) + for (int s = 1; s < ACE_NSIG; s++) + if (sigset.is_member (s) + && this->signal_handler_->register_handler (s, + new_sh, + new_disp) == -1) + result = -1; +#else + ACE_UNUSED_ARG (sigset); + ACE_UNUSED_ARG (new_sh); + ACE_UNUSED_ARG (new_disp); +#endif /* ACE_NSIG */ + + return result; +} + +ACE_INLINE int +ACE_WFMO_Reactor::remove_handler (int signum, + ACE_Sig_Action *new_disp, + ACE_Sig_Action *old_disp, + int sigkey) +{ + return this->signal_handler_->remove_handler (signum, + new_disp, + old_disp, + sigkey); +} + +ACE_INLINE int +ACE_WFMO_Reactor::remove_handler (const ACE_Sig_Set &sigset) +{ + int result = 0; + +#if (ACE_NSIG > 0) + for (int s = 1; s < ACE_NSIG; s++) + if (sigset.is_member (s) + && this->signal_handler_->remove_handler (s) == -1) + result = -1; +#else + ACE_UNUSED_ARG (sigset); +#endif /* ACE_NSIG */ + + return result; +} + +ACE_INLINE int +ACE_WFMO_Reactor::handler (int signum, ACE_Event_Handler **eh) +{ + ACE_Event_Handler *handler = + this->signal_handler_->handler (signum); + + if (handler == 0) + return -1; + else if (eh != 0) + *eh = handler; + return 0; +} + +ACE_INLINE int +ACE_WFMO_Reactor::mask_ops (ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask, + int operation) +{ + ACE_GUARD_RETURN (ACE_Process_Mutex, monitor, this->lock_, -1); + + return this->mask_ops_i (event_handler->get_handle (), + mask, + operation); +} + +ACE_INLINE int +ACE_WFMO_Reactor::mask_ops (ACE_HANDLE io_handle, + ACE_Reactor_Mask mask, + int operation) +{ + ACE_GUARD_RETURN (ACE_Process_Mutex, monitor, this->lock_, -1); + + return this->mask_ops_i (io_handle, + mask, + operation); +} + +ACE_INLINE void +ACE_WFMO_Reactor::requeue_position (int) +{ + // Not implemented +} + +ACE_INLINE int +ACE_WFMO_Reactor::requeue_position (void) +{ + // Don't have an implementation for this yet... + ACE_NOTSUP_RETURN (-1); +} + +ACE_INLINE bool +ACE_WFMO_Reactor::restart (void) +{ + return false; +} + +ACE_INLINE bool +ACE_WFMO_Reactor::restart (bool) +{ + return false; +} + +ACE_INLINE int +ACE_WFMO_Reactor::ready_ops (ACE_Event_Handler *event_handler, + ACE_Reactor_Mask mask, + int ops) +{ + // Don't have an implementation for this yet... + ACE_UNUSED_ARG (event_handler); + ACE_UNUSED_ARG (mask); + ACE_UNUSED_ARG (ops); + ACE_NOTSUP_RETURN (-1); +} + +ACE_INLINE int +ACE_WFMO_Reactor::ready_ops (ACE_HANDLE handle, + ACE_Reactor_Mask, + int ops) +{ + // Don't have an implementation for this yet... + ACE_UNUSED_ARG (handle); + ACE_UNUSED_ARG (ops); + ACE_NOTSUP_RETURN (-1); +} + +ACE_INLINE ACE_Event_Handler * +ACE_WFMO_Reactor::find_handler (ACE_HANDLE handle) +{ + ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, 0); + + return this->handler_rep_.find_handler (handle); +} + +ACE_INLINE int +ACE_WFMO_Reactor::handler (ACE_HANDLE handle, + ACE_Reactor_Mask mask, + ACE_Event_Handler **event_handler) +{ + ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); + + return this->handler_rep_.handler (handle, + mask, + event_handler); +} + +ACE_INLINE bool +ACE_WFMO_Reactor::initialized (void) +{ + return this->open_for_business_; +} + +ACE_INLINE ACE_Lock & +ACE_WFMO_Reactor::lock (void) +{ + return this->lock_adapter_; +} + +ACE_INLINE size_t +ACE_WFMO_Reactor::size (void) const +{ + // Size of repository minus the 2 used for internal purposes + return this->handler_rep_.max_size_ - 2; +} +#else +ACE_INLINE bool +ACE_WFMO_Reactor_Handler_Repository::changes_required (void) +{ + return false; +} + +ACE_INLINE int +ACE_WFMO_Reactor_Handler_Repository::make_changes (void) +{ + return 0; +} + +ACE_INLINE +ACE_WFMO_Reactor_Handler_Repository::~ACE_WFMO_Reactor_Handler_Repository (void) +{ +} + +#endif /* ACE_WIN32 */ + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/WIN32_Asynch_IO.cpp b/dep/acelite/ace/WIN32_Asynch_IO.cpp new file mode 100644 index 00000000000..3dd6efcd1c5 --- /dev/null +++ b/dep/acelite/ace/WIN32_Asynch_IO.cpp @@ -0,0 +1,3782 @@ +// $Id: WIN32_Asynch_IO.cpp 89454 2010-03-11 09:35:25Z johnnyw $ + +#include "ace/WIN32_Asynch_IO.h" + +ACE_RCSID (ace, + Win32_Asynch_IO, + "$Id: WIN32_Asynch_IO.cpp 89454 2010-03-11 09:35:25Z johnnyw $") + +#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) && \ + (defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 == 1)) + +#include "ace/WIN32_Proactor.h" +#include "ace/Proactor.h" +#include "ace/Message_Block.h" +#include "ace/Service_Config.h" +#include "ace/INET_Addr.h" +#include "ace/Task_T.h" +#include "ace/OS_NS_errno.h" +#include "ace/OS_NS_unistd.h" +#include "ace/OS_NS_sys_socket.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +size_t +ACE_WIN32_Asynch_Result::bytes_transferred (void) const +{ + return this->bytes_transferred_; +} + +const void * +ACE_WIN32_Asynch_Result::act (void) const +{ + return this->act_; +} + +int +ACE_WIN32_Asynch_Result::success (void) const +{ + return this->success_; +} + +const void * +ACE_WIN32_Asynch_Result::completion_key (void) const +{ + return this->completion_key_; +} + +u_long +ACE_WIN32_Asynch_Result::error (void) const +{ + return this->error_; +} + +ACE_HANDLE +ACE_WIN32_Asynch_Result::event (void) const +{ + return this->hEvent; +} + +u_long +ACE_WIN32_Asynch_Result::offset (void) const +{ + return this->Offset; +} + +u_long +ACE_WIN32_Asynch_Result::offset_high (void) const +{ + return this->OffsetHigh; +} + +int +ACE_WIN32_Asynch_Result::priority (void) const +{ + ACE_NOTSUP_RETURN (0); +} + +int +ACE_WIN32_Asynch_Result::signal_number (void) const +{ + ACE_NOTSUP_RETURN (0); +} + +int +ACE_WIN32_Asynch_Result::post_completion (ACE_Proactor_Impl *proactor) +{ + // Get to the platform specific implementation. + ACE_WIN32_Proactor *win32_proactor = dynamic_cast (proactor); + + if (win32_proactor == 0) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("Dynamic cast to WIN32 Proactor failed\n")), + -1); + + // Post myself. + return win32_proactor->post_completion (this); +} + +void +ACE_WIN32_Asynch_Result::set_bytes_transferred (size_t nbytes) +{ + this->bytes_transferred_ = nbytes; +} + +void +ACE_WIN32_Asynch_Result::set_error (u_long errcode) +{ + this->error_ = errcode; +} + +ACE_WIN32_Asynch_Result::~ACE_WIN32_Asynch_Result (void) +{ +} + +ACE_WIN32_Asynch_Result::ACE_WIN32_Asynch_Result + (const ACE_Handler::Proxy_Ptr &handler_proxy, + const void* act, + ACE_HANDLE event, + u_long offset, + u_long offset_high, + int priority, + int signal_number) + : ACE_Asynch_Result_Impl (), + OVERLAPPED (), + handler_proxy_ (handler_proxy), + act_ (act), + bytes_transferred_ (0), + success_ (0), + completion_key_ (0), + error_ (0) +{ + // Set the ACE_OVERLAPPED structure + this->Internal = 0; + this->InternalHigh = 0; + this->Offset = offset; + this->OffsetHigh = offset_high; + this->hEvent = event; + + ACE_UNUSED_ARG (priority); + ACE_UNUSED_ARG (signal_number); +} + +int +ACE_WIN32_Asynch_Operation::open (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor) +{ + this->proactor_ = proactor; + this->handler_proxy_ = handler_proxy; + this->handle_ = handle; + + // Grab the handle from the if is invalid + if (this->handle_ == ACE_INVALID_HANDLE) + { + ACE_Handler *handler = handler_proxy.get ()->handler (); + if (handler != 0) + this->handle_ = handler->handle (); + } + if (this->handle_ == ACE_INVALID_HANDLE) + return -1; + + if (this->proactor_!= 0) + // update implementation. + this->win32_proactor_ = + dynamic_cast (this->proactor_->implementation ()); + + // Register with the . + return this->win32_proactor_->register_handle (this->handle_, + completion_key); +} + +int +ACE_WIN32_Asynch_Operation::cancel (void) +{ +#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) + // All I/O operations that are canceled will complete with the error + // ERROR_OPERATION_ABORTED. All completion notifications for the I/O + // operations will occur normally. + + // @@ This API returns 0 on failure. So, I am returning -1 in that + // case. Is that right? (Alex). + int const result = (int) ::CancelIo (this->handle_); + + if (result == 0) + // Couldn't cancel the operations. + return 2; + + // result is non-zero. All the operations are cancelled then. + return 0; + +#else /* !ACE_HAS_WIN32_OVERLAPPED_IO */ + ACE_NOTSUP_RETURN (-1); +#endif /* ACE_HAS_AIO_CALLS */ +} + +ACE_Proactor * +ACE_WIN32_Asynch_Operation::proactor (void) const +{ + return this->proactor_; +} + +ACE_WIN32_Asynch_Operation::ACE_WIN32_Asynch_Operation (ACE_WIN32_Proactor *win32_proactor) + : ACE_Asynch_Operation_Impl (), + win32_proactor_ (win32_proactor), + proactor_ (0), + handle_ (ACE_INVALID_HANDLE) +{ +} + +ACE_WIN32_Asynch_Operation::~ACE_WIN32_Asynch_Operation (void) +{ +} + +// ************************************************************ + +size_t +ACE_WIN32_Asynch_Read_Stream_Result::bytes_to_read (void) const +{ + return this->bytes_to_read_; +} + +ACE_Message_Block & +ACE_WIN32_Asynch_Read_Stream_Result::message_block (void) const +{ + return this->message_block_; +} + +ACE_HANDLE +ACE_WIN32_Asynch_Read_Stream_Result::handle (void) const +{ + return this->handle_; +} + +ACE_WIN32_Asynch_Read_Stream_Result::ACE_WIN32_Asynch_Read_Stream_Result ( + const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + ACE_Message_Block &message_block, + size_t bytes_to_read, + const void* act, + ACE_HANDLE event, + int priority, + int signal_number, + int scatter_enabled) + : ACE_Asynch_Result_Impl (), + ACE_Asynch_Read_Stream_Result_Impl (), + ACE_WIN32_Asynch_Result (handler_proxy, + act, + event, + 0, + 0, + priority, + signal_number), + bytes_to_read_ (bytes_to_read), + message_block_ (message_block), + handle_ (handle), + scatter_enabled_ (scatter_enabled) +{ +} + +void +ACE_WIN32_Asynch_Read_Stream_Result::complete (size_t bytes_transferred, + int success, + const void *completion_key, + u_long error) +{ + // Copy the data which was returned by GetQueuedCompletionStatus + this->bytes_transferred_ = bytes_transferred; + this->success_ = success; + this->completion_key_ = completion_key; + this->error_ = error; + + // Appropriately move the pointers in the message block. + if (!this->scatter_enabled ()) + this->message_block_.wr_ptr (bytes_transferred); + else + { + for (ACE_Message_Block* mb = &this->message_block_; + (mb != 0) && (bytes_transferred > 0); + mb = mb->cont ()) + { + size_t len_part = mb->space (); + + if (len_part > bytes_transferred) + len_part = bytes_transferred; + + mb->wr_ptr (len_part); + + bytes_transferred -= len_part; + } + } + + // Create the interface result class. + ACE_Asynch_Read_Stream::Result result (this); + + // Call the application handler. + ACE_Handler *handler = this->handler_proxy_.get ()->handler (); + if (handler != 0) + handler->handle_read_stream (result); +} + +ACE_WIN32_Asynch_Read_Stream_Result::~ACE_WIN32_Asynch_Read_Stream_Result (void) +{ +} + +// Base class operations. These operations are here to kill dominance +// warnings. These methods call the base class methods. + +size_t +ACE_WIN32_Asynch_Read_Stream_Result::bytes_transferred (void) const +{ + return ACE_WIN32_Asynch_Result::bytes_transferred (); +} + +const void * +ACE_WIN32_Asynch_Read_Stream_Result::act (void) const +{ + return ACE_WIN32_Asynch_Result::act (); +} + +int +ACE_WIN32_Asynch_Read_Stream_Result::success (void) const +{ + return ACE_WIN32_Asynch_Result::success (); +} + +const void * +ACE_WIN32_Asynch_Read_Stream_Result::completion_key (void) const +{ + return ACE_WIN32_Asynch_Result::completion_key (); +} + +u_long +ACE_WIN32_Asynch_Read_Stream_Result::error (void) const +{ + return ACE_WIN32_Asynch_Result::error (); +} + +ACE_HANDLE +ACE_WIN32_Asynch_Read_Stream_Result::event (void) const +{ + return ACE_WIN32_Asynch_Result::event (); +} + +u_long +ACE_WIN32_Asynch_Read_Stream_Result::offset (void) const +{ + return ACE_WIN32_Asynch_Result::offset (); +} + +u_long +ACE_WIN32_Asynch_Read_Stream_Result::offset_high (void) const +{ + return ACE_WIN32_Asynch_Result::offset_high (); +} + +int +ACE_WIN32_Asynch_Read_Stream_Result::priority (void) const +{ + return ACE_WIN32_Asynch_Result::priority (); +} + +int +ACE_WIN32_Asynch_Read_Stream_Result::signal_number (void) const +{ + return ACE_WIN32_Asynch_Result::signal_number (); +} + +int +ACE_WIN32_Asynch_Read_Stream_Result::post_completion (ACE_Proactor_Impl *proactor) +{ + return ACE_WIN32_Asynch_Result::post_completion (proactor); +} + +int +ACE_WIN32_Asynch_Read_Stream_Result::scatter_enabled (void) const +{ + return this->scatter_enabled_; +} + +ACE_WIN32_Asynch_Read_Stream::ACE_WIN32_Asynch_Read_Stream (ACE_WIN32_Proactor *win32_proactor) + : ACE_Asynch_Operation_Impl (), + ACE_Asynch_Read_Stream_Impl (), + ACE_WIN32_Asynch_Operation (win32_proactor) +{ +} + +int +ACE_WIN32_Asynch_Read_Stream::read (ACE_Message_Block &message_block, + size_t bytes_to_read, + const void *act, + int priority, + int signal_number) +{ + size_t space = message_block.space (); + if (bytes_to_read > space) + bytes_to_read = space; + + if (bytes_to_read == 0) + { + errno = ENOSPC; + return -1; + } + + // Create the Asynch_Result. + ACE_WIN32_Asynch_Read_Stream_Result *result = 0; + ACE_NEW_RETURN (result, + ACE_WIN32_Asynch_Read_Stream_Result (this->handler_proxy_, + this->handle_, + message_block, + bytes_to_read, + act, + this->win32_proactor_->get_handle (), + priority, + signal_number), + -1); + + // Shared read + int const return_val = this->shared_read (result); + + // Upon errors + if (return_val == -1) + delete result; + + return return_val; +} + +int +ACE_WIN32_Asynch_Read_Stream::readv (ACE_Message_Block &message_block, + size_t bytes_to_read, + const void *act, + int priority, + int signal_number) +{ +#if (defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0)) + iovec iov[ACE_IOV_MAX]; + int iovcnt = 0; + + // We should not read more than user requested, + // but it is allowed to read less + + for (const ACE_Message_Block* msg = &message_block; + msg != 0 && bytes_to_read > 0 && iovcnt < ACE_IOV_MAX; + msg = msg->cont () , ++iovcnt ) + { + size_t msg_space = msg->space (); + + // OS should correctly process zero length buffers + // if ( msg_space == 0 ) + // ACE_ERROR_RETURN ((LM_ERROR, + // ACE_TEXT ("ACE_WIN32_Asynch_Read_Stream::readv:") + // ACE_TEXT ("No space in the message block\n")), + // -1); + + if (msg_space > bytes_to_read) + msg_space = bytes_to_read; + bytes_to_read -= msg_space; + + // Make as many iovec as needed to fit all of msg_space. + size_t wr_ptr_offset = 0; + + while (msg_space > 0 && iovcnt < ACE_IOV_MAX) + { + u_long this_chunk_length; + if (msg_space > ULONG_MAX) + this_chunk_length = ULONG_MAX; + else + this_chunk_length = static_cast (msg_space); + // Collect the data in the iovec. + iov[iovcnt].iov_base = msg->wr_ptr () + wr_ptr_offset; + iov[iovcnt].iov_len = this_chunk_length; + msg_space -= this_chunk_length; + wr_ptr_offset += this_chunk_length; + + // Increment iovec counter if there's more to do. + if (msg_space > 0) + ++iovcnt; + } + if (msg_space > 0) // Ran out of iovecs before msg_space exhausted + { + errno = ERANGE; + return -1; + } + } + + // Re-calculate number bytes to read + bytes_to_read = 0; + + for (int i = 0; i < iovcnt ; ++i) + bytes_to_read += iov[i].iov_len; + + if (bytes_to_read == 0) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("ACE_WIN32_Asynch_Read_Stream::readv:") + ACE_TEXT ("Attempt to read 0 bytes\n")), + -1); + + // Create the Asynch_Result. + ACE_WIN32_Asynch_Read_Stream_Result *result = 0; + ACE_NEW_RETURN (result, + ACE_WIN32_Asynch_Read_Stream_Result (this->handler_proxy_, + this->handle_, + message_block, + bytes_to_read, + act, + this->win32_proactor_->get_handle (), + priority, + signal_number, + 1), // scatter read enabled + -1); + + // do the scatter recv + + result->set_error (0); // Clear error before starting IO. + + DWORD bytes_recvd = 0; + u_long flags = 0; + + int initiate_result = ::WSARecv (reinterpret_cast (result->handle ()), + reinterpret_cast (iov), + iovcnt, + &bytes_recvd, + &flags, + result, + 0); + + if (0 == initiate_result) + // Immediate success: the OVERLAPPED will still get queued. + return 1; + + ACE_ASSERT (initiate_result == SOCKET_ERROR); + + // If initiate failed, check for a bad error. + ACE_OS::set_errno_to_last_error (); + switch (errno) + { + case ERROR_IO_PENDING: + // The IO will complete proactively: the OVERLAPPED will still + // get queued. + initiate_result = 0; + break; + + default: + // Something else went wrong: the OVERLAPPED will not get + // queued. + + if (ACE::debug ()) + { + ACE_DEBUG ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("WSARecv"))); + } + + delete result; + initiate_result = -1; + break; + } + + return initiate_result; +#else + ACE_UNUSED_ARG (message_block); + ACE_UNUSED_ARG (bytes_to_read); + ACE_UNUSED_ARG (act); + ACE_UNUSED_ARG (priority); + ACE_UNUSED_ARG (signal_number); + ACE_NOTSUP_RETURN (-1); +#endif /* ACE_HAS_WINSOCK2 && ACE_HAS_WINSOCK2 != 0 */ +} + +ACE_WIN32_Asynch_Read_Stream::~ACE_WIN32_Asynch_Read_Stream (void) +{ +} + +int +ACE_WIN32_Asynch_Read_Stream::shared_read (ACE_WIN32_Asynch_Read_Stream_Result *result) +{ + // ReadFile API limits us to DWORD range. + if (result->bytes_to_read () > MAXDWORD) + { + errno = ERANGE; + return -1; + } + DWORD bytes_to_read = static_cast (result->bytes_to_read ()); + u_long bytes_read; + + result->set_error (0); // Clear error before starting IO. + + // Initiate the read + int initiate_result = ::ReadFile (result->handle (), + result->message_block ().wr_ptr (), + bytes_to_read, + &bytes_read, + result); + if (initiate_result == 1) + // Immediate success: the OVERLAPPED will still get queued. + return 0; + + // If initiate failed, check for a bad error. + ACE_OS::set_errno_to_last_error (); + switch (errno) + { + case ERROR_IO_PENDING: + /* FALLTHRU */ + case ERROR_MORE_DATA: + // The IO will complete proactively: the OVERLAPPED will still + // get queued. + return 0; + + default: + // Something else went wrong: the OVERLAPPED will not get + // queued. + + if (ACE::debug ()) + { + ACE_DEBUG ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ReadFile"))); + } + + return -1; + } +} + +// Methods belong to ACE_WIN32_Asynch_Operation base class. These +// methods are defined here to avoid VC++ warnings. They route the +// call to the ACE_WIN32_Asynch_Operation base class. + +int +ACE_WIN32_Asynch_Read_Stream::open (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor) +{ + return ACE_WIN32_Asynch_Operation::open (handler_proxy, + handle, + completion_key, + proactor); +} + +int +ACE_WIN32_Asynch_Read_Stream::cancel (void) +{ + return ACE_WIN32_Asynch_Operation::cancel (); +} + +ACE_Proactor * +ACE_WIN32_Asynch_Read_Stream::proactor (void) const +{ + return ACE_WIN32_Asynch_Operation::proactor (); +} + +size_t +ACE_WIN32_Asynch_Write_Stream_Result::bytes_to_write (void) const +{ + return this->bytes_to_write_; +} + +ACE_Message_Block & +ACE_WIN32_Asynch_Write_Stream_Result::message_block (void) const +{ + return this->message_block_; +} + +ACE_HANDLE +ACE_WIN32_Asynch_Write_Stream_Result::handle (void) const +{ + return this->handle_; +} + +ACE_WIN32_Asynch_Write_Stream_Result::ACE_WIN32_Asynch_Write_Stream_Result ( + const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + ACE_Message_Block &message_block, + size_t bytes_to_write, + const void* act, + ACE_HANDLE event, + int priority, + int signal_number, + int gather_enabled) + : ACE_Asynch_Result_Impl (), + ACE_Asynch_Write_Stream_Result_Impl (), + ACE_WIN32_Asynch_Result + (handler_proxy, act, event, 0, 0, priority, signal_number), + bytes_to_write_ (bytes_to_write), + message_block_ (message_block), + handle_ (handle), + gather_enabled_ (gather_enabled) +{ +} + +void +ACE_WIN32_Asynch_Write_Stream_Result::complete (size_t bytes_transferred, + int success, + const void *completion_key, + u_long error) +{ + // Copy the data which was returned by . + this->bytes_transferred_ = bytes_transferred; + this->success_ = success; + this->completion_key_ = completion_key; + this->error_ = error; + + // Appropriately move the pointers in the message block. + if (!this->gather_enabled ()) + this->message_block_.rd_ptr (bytes_transferred); + else + { + for (ACE_Message_Block* mb = &this->message_block_; + (mb != 0) && (bytes_transferred > 0); + mb = mb->cont ()) + { + size_t len_part = mb->length (); + + if ( len_part > bytes_transferred) + len_part = bytes_transferred; + + mb->rd_ptr (len_part); + + bytes_transferred -= len_part; + } + } + + // Create the interface result class. + ACE_Asynch_Write_Stream::Result result (this); + + // Call the application handler. + ACE_Handler *handler = this->handler_proxy_.get ()->handler (); + if (handler != 0) + handler->handle_write_stream (result); +} + +ACE_WIN32_Asynch_Write_Stream_Result::~ACE_WIN32_Asynch_Write_Stream_Result (void) +{ +} + +// Base class operations. These operations are here to kill dominance +// warnings. These methods call the base class methods. + +size_t +ACE_WIN32_Asynch_Write_Stream_Result::bytes_transferred (void) const +{ + return ACE_WIN32_Asynch_Result::bytes_transferred (); +} + +const void * +ACE_WIN32_Asynch_Write_Stream_Result::act (void) const +{ + return ACE_WIN32_Asynch_Result::act (); +} + +int +ACE_WIN32_Asynch_Write_Stream_Result::success (void) const +{ + return ACE_WIN32_Asynch_Result::success (); +} + +const void * +ACE_WIN32_Asynch_Write_Stream_Result::completion_key (void) const +{ + return ACE_WIN32_Asynch_Result::completion_key (); +} + +u_long +ACE_WIN32_Asynch_Write_Stream_Result::error (void) const +{ + return ACE_WIN32_Asynch_Result::error (); +} + +ACE_HANDLE +ACE_WIN32_Asynch_Write_Stream_Result::event (void) const +{ + return ACE_WIN32_Asynch_Result::event (); +} + +u_long +ACE_WIN32_Asynch_Write_Stream_Result::offset (void) const +{ + return ACE_WIN32_Asynch_Result::offset (); +} + +u_long +ACE_WIN32_Asynch_Write_Stream_Result::offset_high (void) const +{ + return ACE_WIN32_Asynch_Result::offset_high (); +} + +int +ACE_WIN32_Asynch_Write_Stream_Result::priority (void) const +{ + return ACE_WIN32_Asynch_Result::priority (); +} + +int +ACE_WIN32_Asynch_Write_Stream_Result::signal_number (void) const +{ + return ACE_WIN32_Asynch_Result::signal_number (); +} + +int +ACE_WIN32_Asynch_Write_Stream_Result::post_completion (ACE_Proactor_Impl *proactor) +{ + return ACE_WIN32_Asynch_Result::post_completion (proactor); +} + +int +ACE_WIN32_Asynch_Write_Stream_Result::gather_enabled (void) const +{ + return this->gather_enabled_; +} + +ACE_WIN32_Asynch_Write_Stream::ACE_WIN32_Asynch_Write_Stream (ACE_WIN32_Proactor *win32_proactor) + : ACE_Asynch_Operation_Impl (), + ACE_Asynch_Write_Stream_Impl (), + ACE_WIN32_Asynch_Operation (win32_proactor) +{ +} + +int +ACE_WIN32_Asynch_Write_Stream::write (ACE_Message_Block &message_block, + size_t bytes_to_write, + const void *act, + int priority, + int signal_number) +{ + size_t len = message_block.length(); + + if (bytes_to_write > len) + bytes_to_write = len ; + + if (bytes_to_write == 0) + ACE_ERROR_RETURN + ((LM_ERROR, + ACE_TEXT ("ACE_WIN32_Asynch_Write_Stream::write:") + ACE_TEXT ("Attempt to write 0 bytes\n")), + -1); + + ACE_WIN32_Asynch_Write_Stream_Result *result = 0; + ACE_NEW_RETURN (result, + ACE_WIN32_Asynch_Write_Stream_Result (this->handler_proxy_, + this->handle_, + message_block, + bytes_to_write, + act, + this->win32_proactor_->get_handle (), + priority, + signal_number), + -1); + + // Shared write + int const return_val = this->shared_write (result); + + // Upon errors + if (return_val == -1) + { + delete result; + } + + return return_val; +} + +int +ACE_WIN32_Asynch_Write_Stream::writev (ACE_Message_Block &message_block, + size_t bytes_to_write, + const void *act, + int priority, + int signal_number) +{ +#if (defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0)) + iovec iov[ACE_IOV_MAX]; + int iovcnt = 0; + + // We should not write more than user requested, + // but it is allowed to write less + + for (const ACE_Message_Block* msg = &message_block; + msg != 0 && bytes_to_write > 0 && iovcnt < ACE_IOV_MAX; + msg = msg->cont ()) + { + size_t msg_len = msg->length (); + + // Skip 0-length blocks. + if (msg_len == 0) + continue; + if (msg_len > bytes_to_write) + msg_len = bytes_to_write; + bytes_to_write -= msg_len; + + // Make as many iovec as needed to fit all of msg_len. + size_t rd_ptr_offset = 0; + + while (msg_len > 0 && iovcnt < ACE_IOV_MAX) + { + u_long this_chunk_length; + if (msg_len > ULONG_MAX) + this_chunk_length = ULONG_MAX; + else + this_chunk_length = static_cast (msg_len); + // Collect the data in the iovec. + iov[iovcnt].iov_base = msg->rd_ptr () + rd_ptr_offset; + iov[iovcnt].iov_len = this_chunk_length; + msg_len -= this_chunk_length; + rd_ptr_offset += this_chunk_length; + + // Increment iovec counter if there's more to do. + if (msg_len > 0) + iovcnt++; + } + if (msg_len > 0) // Ran out of iovecs before msg_space exhausted + { + errno = ERANGE; + return -1; + } + ++iovcnt; + } + + // Re-calculate number bytes to write + bytes_to_write = 0; + + for ( int i=0; i < iovcnt ; ++i ) + bytes_to_write += iov[i].iov_len; + + if ( bytes_to_write == 0 ) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("ACE_WIN32_Asynch_Write_Stream::writev:") + ACE_TEXT ("Attempt to write 0 bytes\n")), + -1); + + + ACE_WIN32_Asynch_Write_Stream_Result *result = 0; + ACE_NEW_RETURN (result, + ACE_WIN32_Asynch_Write_Stream_Result (this->handler_proxy_, + this->handle_, + message_block, + bytes_to_write, + act, + this->win32_proactor_->get_handle (), + priority, + signal_number, + 1), // gather write enabled + -1); + + // do the gather send + + u_long bytes_sent = 0; + + int initiate_result = ::WSASend (reinterpret_cast (result->handle ()), + reinterpret_cast (iov), + iovcnt, + &bytes_sent, + 0, // flags + result, + 0); + + if (0 == initiate_result) + // Immediate success: the OVERLAPPED will still get queued. + return 1; + + ACE_ASSERT (initiate_result == SOCKET_ERROR); + + // If initiate failed, check for a bad error. + ACE_OS::set_errno_to_last_error (); + switch (errno) + { + case ERROR_IO_PENDING: + // The IO will complete proactively: the OVERLAPPED will still + // get queued. + initiate_result = 0; + break; + + default: + // Something else went wrong: the OVERLAPPED will not get + // queued. + + if (ACE::debug ()) + { + ACE_DEBUG ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("WSASend"))); + } + + delete result; + initiate_result = -1; + break; + } + + return initiate_result; +#else + ACE_UNUSED_ARG (message_block); + ACE_UNUSED_ARG (bytes_to_write); + ACE_UNUSED_ARG (act); + ACE_UNUSED_ARG (priority); + ACE_UNUSED_ARG (signal_number); + ACE_NOTSUP_RETURN (-1); +#endif /* ACE_HAS_WINSOCK2 && ACE_HAS_WINSOCK2 != 0 */ +} + +ACE_WIN32_Asynch_Write_Stream::~ACE_WIN32_Asynch_Write_Stream (void) +{ +} + +int +ACE_WIN32_Asynch_Write_Stream::shared_write (ACE_WIN32_Asynch_Write_Stream_Result *result) +{ + u_long bytes_written; + if (result->bytes_to_write () > MAXDWORD) + { + errno = ERANGE; + return -1; + } + DWORD bytes_to_write = static_cast (result->bytes_to_write ()); + + result->set_error (0); // Clear error before starting IO. + + // Initiate the write; Winsock 2 is required for the higher-performing + // WSASend() function. For Winsock 1, fall back to the slower WriteFile(). + int initiate_result = 0; +#if (defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0)) + WSABUF iov; + iov.buf = result->message_block ().rd_ptr (); + iov.len = bytes_to_write; + initiate_result = ::WSASend (reinterpret_cast (result->handle ()), + &iov, + 1, + &bytes_written, + 0, // flags + result, + 0); + if (initiate_result == 0) + { + // Immediate success: the OVERLAPPED will still get queued. + return 0; + } +#else + initiate_result = ::WriteFile (result->handle (), + result->message_block ().rd_ptr (), + bytes_to_write, + &bytes_written, + result); + if (initiate_result == 1) + // Immediate success: the OVERLAPPED will still get queued. + return 0; +#endif /* ACE_HAS_WINSOCK2 */ + + // If initiate failed, check for a bad error. + ACE_OS::set_errno_to_last_error (); + switch (errno) + { + case ERROR_IO_PENDING: + // The IO will complete proactively: the OVERLAPPED will still + // get queued. + return 0; + + default: + // Something else went wrong: the OVERLAPPED will not get + // queued. + + if (ACE::debug ()) + ACE_DEBUG ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("Initiating write"))); + return -1; + } +} + +// Methods belong to ACE_WIN32_Asynch_Operation base class. These +// methods are defined here to avoid VC++ warnings. They route the +// call to the ACE_WIN32_Asynch_Operation base class. + +int +ACE_WIN32_Asynch_Write_Stream::open (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor) +{ + return ACE_WIN32_Asynch_Operation::open (handler_proxy, + handle, + completion_key, + proactor); +} + +int +ACE_WIN32_Asynch_Write_Stream::cancel (void) +{ + return ACE_WIN32_Asynch_Operation::cancel (); +} + +ACE_Proactor * +ACE_WIN32_Asynch_Write_Stream::proactor (void) const +{ + return ACE_WIN32_Asynch_Operation::proactor (); +} + +ACE_WIN32_Asynch_Read_File_Result::ACE_WIN32_Asynch_Read_File_Result ( + const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + ACE_Message_Block &message_block, + size_t bytes_to_read, + const void* act, + u_long offset, + u_long offset_high, + ACE_HANDLE event, + int priority, + int signal_number, + int scatter_enabled) + : ACE_Asynch_Result_Impl (), + ACE_Asynch_Read_Stream_Result_Impl (), + ACE_Asynch_Read_File_Result_Impl (), + ACE_WIN32_Asynch_Read_Stream_Result (handler_proxy, + handle, + message_block, + bytes_to_read, + act, + event, + priority, + signal_number, + scatter_enabled) +{ + this->Offset = offset; + this->OffsetHigh = offset_high; +} + +void +ACE_WIN32_Asynch_Read_File_Result::complete (size_t bytes_transferred, + int success, + const void *completion_key, + u_long error) +{ + // Copy the data which was returned by GetQueuedCompletionStatus. + this->bytes_transferred_ = bytes_transferred; + this->success_ = success; + this->completion_key_ = completion_key; + this->error_ = error; + + // Appropriately move the pointers in the message block. + if (!this->scatter_enabled ()) + this->message_block_.wr_ptr (bytes_transferred); + else + { + static const size_t page_size = ACE_OS::getpagesize(); + + for (ACE_Message_Block* mb = &this->message_block_; + (mb != 0) && (bytes_transferred > 0); + mb = mb->cont ()) + { + // mb->space () is ought to be >= page_size. + // this is verified in the readv method + // ACE_ASSERT (mb->space () >= page_size); + + size_t len_part = page_size ; + + if ( len_part > bytes_transferred) + len_part = bytes_transferred; + + mb->wr_ptr (len_part); + + bytes_transferred -= len_part; + } + } + + // Create the interface result class. + ACE_Asynch_Read_File::Result result (this); + + // Call the application handler. + ACE_Handler *handler = this->handler_proxy_.get ()->handler (); + if (handler != 0) + handler->handle_read_file (result); +} + +ACE_WIN32_Asynch_Read_File_Result::~ACE_WIN32_Asynch_Read_File_Result (void) +{ +} + +// Base class operations. These operations are here to kill dominance +// warnings. These methods call the base class methods. + +size_t +ACE_WIN32_Asynch_Read_File_Result::bytes_transferred (void) const +{ + return ACE_WIN32_Asynch_Result::bytes_transferred (); +} + +const void * +ACE_WIN32_Asynch_Read_File_Result::act (void) const +{ + return ACE_WIN32_Asynch_Result::act (); +} + +int +ACE_WIN32_Asynch_Read_File_Result::success (void) const +{ + return ACE_WIN32_Asynch_Result::success (); +} + +const void * +ACE_WIN32_Asynch_Read_File_Result::completion_key (void) const +{ + return ACE_WIN32_Asynch_Result::completion_key (); +} + +u_long +ACE_WIN32_Asynch_Read_File_Result::error (void) const +{ + return ACE_WIN32_Asynch_Result::error (); +} + +ACE_HANDLE +ACE_WIN32_Asynch_Read_File_Result::event (void) const +{ + return ACE_WIN32_Asynch_Result::event (); +} + +u_long +ACE_WIN32_Asynch_Read_File_Result::offset (void) const +{ + return ACE_WIN32_Asynch_Result::offset (); +} + +u_long +ACE_WIN32_Asynch_Read_File_Result::offset_high (void) const +{ + return ACE_WIN32_Asynch_Result::offset_high (); +} + +int +ACE_WIN32_Asynch_Read_File_Result::priority (void) const +{ + return ACE_WIN32_Asynch_Result::priority (); +} + +int +ACE_WIN32_Asynch_Read_File_Result::signal_number (void) const +{ + return ACE_WIN32_Asynch_Result::signal_number (); +} + +// The following methods belong to +// ACE_WIN32_Asynch_Read_Stream_Result. They are here to avoid VC++ +// warnings. These methods route their call to the +// ACE_WIN32_Asynch_Read_Stream_Result base class. + +size_t +ACE_WIN32_Asynch_Read_File_Result::bytes_to_read (void) const +{ + return ACE_WIN32_Asynch_Read_Stream_Result::bytes_to_read (); +} + +ACE_Message_Block & +ACE_WIN32_Asynch_Read_File_Result::message_block (void) const +{ + return ACE_WIN32_Asynch_Read_Stream_Result::message_block (); +} + +ACE_HANDLE +ACE_WIN32_Asynch_Read_File_Result::handle (void) const +{ + return ACE_WIN32_Asynch_Read_Stream_Result::handle (); +} + +int +ACE_WIN32_Asynch_Read_File_Result::post_completion (ACE_Proactor_Impl *proactor) +{ + return ACE_WIN32_Asynch_Result::post_completion (proactor); +} + +// ************************************************************ + +ACE_WIN32_Asynch_Read_File::ACE_WIN32_Asynch_Read_File (ACE_WIN32_Proactor *win32_proactor) + : ACE_Asynch_Operation_Impl (), + ACE_Asynch_Read_Stream_Impl (), + ACE_Asynch_Read_File_Impl (), + ACE_WIN32_Asynch_Read_Stream (win32_proactor) +{ +} + +int +ACE_WIN32_Asynch_Read_File::read (ACE_Message_Block &message_block, + size_t bytes_to_read, + u_long offset, + u_long offset_high, + const void *act, + int priority, + int signal_number) +{ + size_t space = message_block.space (); + if ( bytes_to_read > space ) + bytes_to_read = space; + + if ( bytes_to_read == 0 ) + ACE_ERROR_RETURN + ((LM_ERROR, + ACE_TEXT ("ACE_WIN32_Asynch_Read_File::read:") + ACE_TEXT ("Attempt to read 0 bytes or no space in the message block\n")), + -1); + + + ACE_WIN32_Asynch_Read_File_Result *result = 0; + ACE_NEW_RETURN (result, + ACE_WIN32_Asynch_Read_File_Result (this->handler_proxy_, + this->handle_, + message_block, + bytes_to_read, + act, + offset, + offset_high, + this->win32_proactor_->get_handle (), + priority, + signal_number), + -1); + + // Shared read + int return_val = this->shared_read (result); + + // Upon errors + if (return_val == -1) + delete result; + + return return_val; +} + +int +ACE_WIN32_Asynch_Read_File::readv (ACE_Message_Block &message_block, + size_t bytes_to_read, + u_long offset, + u_long offset_high, + const void *act, + int priority, + int signal_number) +{ +#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) + static const size_t page_size = ACE_OS::getpagesize(); + + FILE_SEGMENT_ELEMENT buffer_pointers[ACE_IOV_MAX + 1]; + int buffer_pointers_count = 0; + + // Each buffer must be at least the size of a system memory page + // and must be aligned on a system memory page size boundary + + // We should not read more than user requested, + // but it is allowed to read less + + size_t total_space = 0; + + for (const ACE_Message_Block* msg = &message_block; + msg != 0 && buffer_pointers_count < ACE_IOV_MAX && total_space < bytes_to_read; + msg = msg->cont(), ++buffer_pointers_count ) + { + size_t msg_space = msg->space (); + + if (msg_space < page_size) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("ACE_WIN32_Asynch_Read_File::readv:") + ACE_TEXT ("Invalid message block size\n")), + -1); + + buffer_pointers[buffer_pointers_count].Buffer = msg->wr_ptr (); + total_space += page_size; + } + + // not read more than buffers space + if (bytes_to_read > total_space) + bytes_to_read = total_space; + + // ReadFileScatter API limits us to DWORD range. + if (bytes_to_read > MAXDWORD) + { + errno = ERANGE; + return -1; + } + DWORD dword_bytes_to_read = static_cast (bytes_to_read); + + // last one should be completely 0 + buffer_pointers[buffer_pointers_count].Buffer = 0; + + ACE_WIN32_Asynch_Read_File_Result *result = 0; + ACE_NEW_RETURN (result, + ACE_WIN32_Asynch_Read_File_Result (this->handler_proxy_, + this->handle_, + message_block, + bytes_to_read, + act, + offset, + offset_high, + this->win32_proactor_->get_handle (), + priority, + signal_number, + 1), // scatter read enabled + -1); + + // do the scatter read + result->set_error (0); // Clear error before starting IO. + + int initiate_result = ::ReadFileScatter (result->handle (), + buffer_pointers, + dword_bytes_to_read, + 0, // reserved, must be NULL + result); + + if (0 != initiate_result) + // Immediate success: the OVERLAPPED will still get queued. + return 1; + + // If initiate failed, check for a bad error. + ACE_OS::set_errno_to_last_error (); + switch (errno) + { + case ERROR_IO_PENDING: + // The IO will complete proactively: the OVERLAPPED will still + // get queued. + initiate_result = 0; + break; + + default: + // Something else went wrong: the OVERLAPPED will not get + // queued. + + if (ACE::debug ()) + { + ACE_DEBUG ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ReadFileScatter"))); + } + + delete result; + initiate_result = -1; + break; + } + + return initiate_result; +#else + ACE_NOTSUP_RETURN (-1); +#endif /* ACE_WIN32_OVERLAPPED_IO */ +} + + +ACE_WIN32_Asynch_Read_File::~ACE_WIN32_Asynch_Read_File (void) +{ +} + +int +ACE_WIN32_Asynch_Read_File::read (ACE_Message_Block &message_block, + size_t bytes_to_read, + const void *act, + int priority, + int signal_number) +{ + return ACE_WIN32_Asynch_Read_Stream::read (message_block, + bytes_to_read, + act, + priority, + signal_number); +} + +int +ACE_WIN32_Asynch_Read_File::readv (ACE_Message_Block &message_block, + size_t bytes_to_read, + const void *act, + int priority, + int signal_number) +{ + return ACE_WIN32_Asynch_Read_Stream::readv (message_block, + bytes_to_read, + act, + priority, + signal_number); +} + +// Methods belong to ACE_WIN32_Asynch_Operation base class. These +// methods are defined here to avoid VC++ warnings. They route the +// call to the ACE_WIN32_Asynch_Operation base class. + +int +ACE_WIN32_Asynch_Read_File::open (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor) +{ + return ACE_WIN32_Asynch_Operation::open (handler_proxy, + handle, + completion_key, + proactor); +} + +int +ACE_WIN32_Asynch_Read_File::cancel (void) +{ + return ACE_WIN32_Asynch_Operation::cancel (); +} + +ACE_Proactor * +ACE_WIN32_Asynch_Read_File::proactor (void) const +{ + return ACE_WIN32_Asynch_Operation::proactor (); +} + +ACE_WIN32_Asynch_Write_File_Result::ACE_WIN32_Asynch_Write_File_Result ( + const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + ACE_Message_Block &message_block, + size_t bytes_to_write, + const void* act, + u_long offset, + u_long offset_high, + ACE_HANDLE event, + int priority, + int signal_number, + int gather_enabled) + : ACE_Asynch_Result_Impl (), + ACE_Asynch_Write_Stream_Result_Impl (), + ACE_Asynch_Write_File_Result_Impl (), + ACE_WIN32_Asynch_Write_Stream_Result (handler_proxy, + handle, + message_block, + bytes_to_write, + act, + event, + priority, + signal_number, + gather_enabled) +{ + this->Offset = offset; + this->OffsetHigh = offset_high; +} + +void +ACE_WIN32_Asynch_Write_File_Result::complete (size_t bytes_transferred, + int success, + const void *completion_key, + u_long error) +{ + // Copy the data which was returned by GetQueuedCompletionStatus + this->bytes_transferred_ = bytes_transferred; + this->success_ = success; + this->completion_key_ = completion_key; + this->error_ = error; + + // Appropriately move the pointers in the message block. + if (!this->gather_enabled ()) + this->message_block_.rd_ptr (bytes_transferred); + else + { + static const size_t page_size = ACE_OS::getpagesize(); + + for (ACE_Message_Block* mb = &this->message_block_; + (mb != 0) && (bytes_transferred > 0); + mb = mb->cont ()) + { + // mb->length () is ought to be >= page_size. + // this is verified in the writev method + // ACE_ASSERT (mb->length () >= page_size); + + size_t len_part = page_size; + + if ( len_part > bytes_transferred) + len_part = bytes_transferred; + + mb->rd_ptr (len_part); + + bytes_transferred -= len_part; + } + + } + + // Create the interface result class. + ACE_Asynch_Write_File::Result result (this); + + // Call the application handler. + ACE_Handler *handler = this->handler_proxy_.get ()->handler (); + if (handler != 0) + handler->handle_write_file (result); +} + +ACE_WIN32_Asynch_Write_File_Result::~ACE_WIN32_Asynch_Write_File_Result (void) +{ +} + +// Base class operations. These operations are here to kill dominance +// warnings. These methods call the base class methods. + +size_t +ACE_WIN32_Asynch_Write_File_Result::bytes_transferred (void) const +{ + return ACE_WIN32_Asynch_Result::bytes_transferred (); +} + +const void * +ACE_WIN32_Asynch_Write_File_Result::act (void) const +{ + return ACE_WIN32_Asynch_Result::act (); +} + +int +ACE_WIN32_Asynch_Write_File_Result::success (void) const +{ + return ACE_WIN32_Asynch_Result::success (); +} + +const void * +ACE_WIN32_Asynch_Write_File_Result::completion_key (void) const +{ + return ACE_WIN32_Asynch_Result::completion_key (); +} + +u_long +ACE_WIN32_Asynch_Write_File_Result::error (void) const +{ + return ACE_WIN32_Asynch_Result::error (); +} + +ACE_HANDLE +ACE_WIN32_Asynch_Write_File_Result::event (void) const +{ + return ACE_WIN32_Asynch_Result::event (); +} + +u_long +ACE_WIN32_Asynch_Write_File_Result::offset (void) const +{ + return ACE_WIN32_Asynch_Result::offset (); +} + +u_long +ACE_WIN32_Asynch_Write_File_Result::offset_high (void) const +{ + return ACE_WIN32_Asynch_Result::offset_high (); +} + +int +ACE_WIN32_Asynch_Write_File_Result::priority (void) const +{ + return ACE_WIN32_Asynch_Result::priority (); +} + +int +ACE_WIN32_Asynch_Write_File_Result::signal_number (void) const +{ + return ACE_WIN32_Asynch_Result::signal_number (); +} + +// The following methods belong to +// ACE_WIN32_Asynch_Write_Stream_Result. They are here to avoid VC++ +// warnings. These methods route their call to the +// ACE_WIN32_Asynch_Write_Stream_Result base class. + +size_t +ACE_WIN32_Asynch_Write_File_Result::bytes_to_write (void) const +{ + return ACE_WIN32_Asynch_Write_Stream_Result::bytes_to_write (); +} + +ACE_Message_Block & +ACE_WIN32_Asynch_Write_File_Result::message_block (void) const +{ + return ACE_WIN32_Asynch_Write_Stream_Result::message_block (); +} + +ACE_HANDLE +ACE_WIN32_Asynch_Write_File_Result::handle (void) const +{ + return ACE_WIN32_Asynch_Write_Stream_Result::handle (); +} + +int +ACE_WIN32_Asynch_Write_File_Result::post_completion (ACE_Proactor_Impl *proactor) +{ + return ACE_WIN32_Asynch_Result::post_completion (proactor); +} + +ACE_WIN32_Asynch_Write_File::ACE_WIN32_Asynch_Write_File (ACE_WIN32_Proactor *win32_proactor) + : ACE_Asynch_Operation_Impl (), + ACE_Asynch_Write_Stream_Impl (), + ACE_Asynch_Write_File_Impl (), + ACE_WIN32_Asynch_Write_Stream (win32_proactor) +{ +} + +int +ACE_WIN32_Asynch_Write_File::write (ACE_Message_Block &message_block, + size_t bytes_to_write, + u_long offset, + u_long offset_high, + const void *act, + int priority, + int signal_number) +{ + size_t len = message_block.length (); + if ( bytes_to_write > len ) + bytes_to_write = len; + + if ( bytes_to_write == 0 ) + ACE_ERROR_RETURN + ((LM_ERROR, + ACE_TEXT ("ACE_WIN32_Asynch_Write_File::write:") + ACE_TEXT ("Attempt to read 0 bytes\n")), + -1); + + ACE_WIN32_Asynch_Write_File_Result *result = 0; + ACE_NEW_RETURN (result, + ACE_WIN32_Asynch_Write_File_Result (this->handler_proxy_, + this->handle_, + message_block, + bytes_to_write, + act, + offset, + offset_high, + this->win32_proactor_->get_handle (), + priority, + signal_number), + -1); + + // Shared write + int return_val = this->shared_write (result); + + // Upon errors + if (return_val == -1) + delete result; + + return return_val; +} + +int +ACE_WIN32_Asynch_Write_File::writev (ACE_Message_Block &message_block, + size_t bytes_to_write, + u_long offset, + u_long offset_high, + const void *act, + int priority, + int signal_number) +{ +#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) + static const size_t page_size = ACE_OS::getpagesize(); + + FILE_SEGMENT_ELEMENT buffer_pointers[ACE_IOV_MAX + 1]; + int buffer_pointers_count = 0; + + // Each buffer must be at least the size of a system memory page + // and must be aligned on a system memory page size boundary + + // We should not read more than user requested, + // but it is allowed to read less + + size_t total_len = 0; + + for (const ACE_Message_Block* msg = &message_block; + msg != 0 && buffer_pointers_count < ACE_IOV_MAX && total_len < bytes_to_write; + msg = msg->cont (), ++buffer_pointers_count ) + { + size_t msg_len = msg->length (); + + // Don't allow writing less than page_size, unless + // the size of the message block is big enough (so we don't write from + // memory which does not belong to the message block), and the message + // block is the last in the chain. + if (msg_len < page_size && + (msg->size () - (msg->rd_ptr () - msg->base ()) < page_size || // message block too small + bytes_to_write - total_len > page_size ))// NOT last chunk + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("ACE_WIN32_Asynch_Write_File::writev:") + ACE_TEXT ("Invalid message block length\n")), + -1); + + buffer_pointers[buffer_pointers_count].Buffer = msg->rd_ptr (); + total_len += page_size; + } + + // not write more than we have in buffers + if (bytes_to_write > total_len) + bytes_to_write = total_len; + // WriteFileGather API limits us to DWORD range. + if (bytes_to_write > MAXDWORD) + { + errno = ERANGE; + return -1; + } + DWORD dword_bytes_to_write = static_cast (bytes_to_write); + + // last one should be completely 0 + buffer_pointers[buffer_pointers_count].Buffer = 0; + + ACE_WIN32_Asynch_Write_File_Result *result = 0; + ACE_NEW_RETURN (result, + ACE_WIN32_Asynch_Write_File_Result (this->handler_proxy_, + this->handle_, + message_block, + bytes_to_write, + act, + offset, + offset_high, + this->win32_proactor_->get_handle (), + priority, + signal_number, + 1), // gather write enabled + -1); + + result->set_error(0); + + // do the gather write + int initiate_result = ::WriteFileGather (result->handle (), + buffer_pointers, + dword_bytes_to_write, + 0, // reserved, must be NULL + result); + + if (0 != initiate_result) + // Immediate success: the OVERLAPPED will still get queued. + return 1; + + // If initiate failed, check for a bad error. + ACE_OS::set_errno_to_last_error (); + switch (errno) + { + case ERROR_IO_PENDING: + // The IO will complete proactively: the OVERLAPPED will still + // get queued. + initiate_result = 0; + break; + + default: + // Something else went wrong: the OVERLAPPED will not get + // queued. + + if (ACE::debug ()) + { + ACE_DEBUG ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("WriteFileGather"))); + } + + delete result; + initiate_result = -1; + break; + } + + return initiate_result; +#else + + ACE_NOTSUP_RETURN (-1); + +#endif /* ACE_HAS_WIN32_OVERLAPPED_IO */ +} + + +ACE_WIN32_Asynch_Write_File::~ACE_WIN32_Asynch_Write_File (void) +{ +} + +int +ACE_WIN32_Asynch_Write_File::write (ACE_Message_Block &message_block, + size_t bytes_to_write, + const void *act, + int priority, + int signal_number) +{ + return ACE_WIN32_Asynch_Write_Stream::write (message_block, + bytes_to_write, + act, + priority, + signal_number); +} + +int +ACE_WIN32_Asynch_Write_File::writev (ACE_Message_Block &message_block, + size_t bytes_to_write, + const void *act, + int priority, + int signal_number) +{ + return ACE_WIN32_Asynch_Write_Stream::writev (message_block, + bytes_to_write, + act, + priority, + signal_number); +} + +// Methods belong to ACE_WIN32_Asynch_Operation base class. These +// methods are defined here to avoid VC++ warnings. They route the +// call to the ACE_WIN32_Asynch_Operation base class. + +int +ACE_WIN32_Asynch_Write_File::open (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor) +{ + return ACE_WIN32_Asynch_Operation::open (handler_proxy, + handle, + completion_key, + proactor); +} + +int +ACE_WIN32_Asynch_Write_File::cancel (void) +{ + return ACE_WIN32_Asynch_Operation::cancel (); +} + +ACE_Proactor * +ACE_WIN32_Asynch_Write_File::proactor (void) const +{ + return ACE_WIN32_Asynch_Operation::proactor (); +} + +size_t +ACE_WIN32_Asynch_Accept_Result::bytes_to_read (void) const +{ + return this->bytes_to_read_; +} + +ACE_Message_Block & +ACE_WIN32_Asynch_Accept_Result::message_block (void) const +{ + return this->message_block_; +} + +ACE_HANDLE +ACE_WIN32_Asynch_Accept_Result::listen_handle (void) const +{ + return this->listen_handle_; +} + +ACE_HANDLE +ACE_WIN32_Asynch_Accept_Result::accept_handle (void) const +{ + return this->accept_handle_; +} + +ACE_WIN32_Asynch_Accept_Result::ACE_WIN32_Asynch_Accept_Result ( + const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE listen_handle, + ACE_HANDLE accept_handle, + ACE_Message_Block &message_block, + size_t bytes_to_read, + const void* act, + ACE_HANDLE event, + int priority, + int signal_number) + : ACE_Asynch_Result_Impl (), + ACE_Asynch_Accept_Result_Impl (), + ACE_WIN32_Asynch_Result (handler_proxy, + act, + event, + 0, + 0, + priority, + signal_number), + bytes_to_read_ (bytes_to_read), + message_block_ (message_block), + listen_handle_ (listen_handle), + accept_handle_ (accept_handle) +{ +} + +void +ACE_WIN32_Asynch_Accept_Result::complete (size_t bytes_transferred, + int success, + const void *completion_key, + u_long error) +{ + // Copy the data which was returned by GetQueuedCompletionStatus + this->bytes_transferred_ = bytes_transferred; + this->success_ = success; + this->completion_key_ = completion_key; + this->error_ = error; + + // Appropriately move the pointers in the message block. + this->message_block_.wr_ptr (bytes_transferred); + + if (!success && this->accept_handle_ != ACE_INVALID_HANDLE) + { + ACE_OS::closesocket (this->accept_handle_); + this->accept_handle_ = ACE_INVALID_HANDLE; + } + + // Create the interface result class. + ACE_Asynch_Accept::Result result (this); + + // Call the application handler. + ACE_Handler *handler = this->handler_proxy_.get ()->handler (); + if (handler != 0) + handler->handle_accept (result); +} + +ACE_WIN32_Asynch_Accept_Result::~ACE_WIN32_Asynch_Accept_Result (void) +{ +} + +// Base class operations. These operations are here to kill dominance +// warnings. These methods call the base class methods. + +size_t +ACE_WIN32_Asynch_Accept_Result::bytes_transferred (void) const +{ + return ACE_WIN32_Asynch_Result::bytes_transferred (); +} + +const void * +ACE_WIN32_Asynch_Accept_Result::act (void) const +{ + return ACE_WIN32_Asynch_Result::act (); +} + +int +ACE_WIN32_Asynch_Accept_Result::success (void) const +{ + return ACE_WIN32_Asynch_Result::success (); +} + +const void * +ACE_WIN32_Asynch_Accept_Result::completion_key (void) const +{ + return ACE_WIN32_Asynch_Result::completion_key (); +} + +u_long +ACE_WIN32_Asynch_Accept_Result::error (void) const +{ + return ACE_WIN32_Asynch_Result::error (); +} + +ACE_HANDLE +ACE_WIN32_Asynch_Accept_Result::event (void) const +{ + return ACE_WIN32_Asynch_Result::event (); +} + +u_long +ACE_WIN32_Asynch_Accept_Result::offset (void) const +{ + return ACE_WIN32_Asynch_Result::offset (); +} + +u_long +ACE_WIN32_Asynch_Accept_Result::offset_high (void) const +{ + return ACE_WIN32_Asynch_Result::offset_high (); +} + +int +ACE_WIN32_Asynch_Accept_Result::priority (void) const +{ + return ACE_WIN32_Asynch_Result::priority (); +} + +int +ACE_WIN32_Asynch_Accept_Result::signal_number (void) const +{ + return ACE_WIN32_Asynch_Result::signal_number (); +} + +int +ACE_WIN32_Asynch_Accept_Result::post_completion (ACE_Proactor_Impl *proactor) +{ + return ACE_WIN32_Asynch_Result::post_completion (proactor); +} + +ACE_WIN32_Asynch_Accept::ACE_WIN32_Asynch_Accept (ACE_WIN32_Proactor *win32_proactor) + : ACE_Asynch_Operation_Impl (), + ACE_Asynch_Accept_Impl (), + ACE_WIN32_Asynch_Operation (win32_proactor) +{ +} + +int +ACE_WIN32_Asynch_Accept::accept (ACE_Message_Block &message_block, + size_t bytes_to_read, + ACE_HANDLE accept_handle, + const void *act, + int priority, + int signal_number, + int addr_family) +{ +#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) || (defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0)) + // Sanity check: make sure that enough space has been allocated by + // the caller. + size_t address_size = +#if defined (ACE_HAS_IPV6) + addr_family == AF_INET ? sizeof (sockaddr_in) : sizeof (sockaddr_in6); +#else + sizeof (sockaddr_in); +#endif /* ACE_HAS_IPV6 */ + address_size += 16; // AcceptEx requires address size + 16 (minimum) + size_t available_space = message_block.space (); + size_t space_needed = bytes_to_read + 2 * address_size; + if (available_space < space_needed) + ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("Buffer too small\n")), -1); + + // WIN Specific. + + // AcceptEx API limits us to DWORD range. + if (bytes_to_read > MAXDWORD) + { + errno = ERANGE; + return -1; + } + DWORD dword_bytes_to_read = static_cast (bytes_to_read); + + int close_accept_handle = 0; + // If the is invalid, we will create a new socket. + if (accept_handle == ACE_INVALID_HANDLE) + { + accept_handle = ACE_OS::socket (addr_family, + SOCK_STREAM, + 0); + if (accept_handle == ACE_INVALID_HANDLE) + { + if (ACE::debug ()) + { + ACE_DEBUG ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("ACE_OS::socket"))); + } + return -1; + } + else + // Remember to close the socket down if failures occur. + close_accept_handle = 1; + } + + // Common code for both WIN and POSIX. + ACE_WIN32_Asynch_Accept_Result *result = 0; + ACE_NEW_RETURN (result, + ACE_WIN32_Asynch_Accept_Result (this->handler_proxy_, + this->handle_, + accept_handle, + message_block, + bytes_to_read, + act, + this->win32_proactor_->get_handle (), + priority, + signal_number), + -1); + + u_long bytes_read; + + // Initiate the accept. + int initiate_result = ::AcceptEx ((SOCKET) result->listen_handle (), + (SOCKET) result->accept_handle (), + result->message_block ().wr_ptr (), + dword_bytes_to_read, + static_cast (address_size), + static_cast (address_size), + &bytes_read, + result); + if (initiate_result == 1) + // Immediate success: the OVERLAPPED will still get queued. + return 1; + + // If initiate failed, check for a bad error. + ACE_OS::set_errno_to_last_error (); + switch (errno) + { + case ERROR_IO_PENDING: + // The IO will complete proactively: the OVERLAPPED will still + // get queued. + return 0; + + default: + // Something else went wrong: the OVERLAPPED will not get + // queued. + + if (close_accept_handle == 1) + // Close the newly created socket + ACE_OS::closesocket (accept_handle); + + // Cleanup dynamically allocated Asynch_Result. + delete result; + + if (ACE::debug ()) + { + ACE_DEBUG ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("AcceptEx"))); + } + return -1; + } +#else + ACE_UNUSED_ARG (message_block); + ACE_UNUSED_ARG (bytes_to_read); + ACE_UNUSED_ARG (accept_handle); + ACE_UNUSED_ARG (act); + ACE_UNUSED_ARG (priority); + ACE_UNUSED_ARG (signal_number); + ACE_UNUSED_ARG (addr_family); + ACE_NOTSUP_RETURN (-1); +#endif /* defined (ACE_HAS_WIN32_OVERLAPPED_IO) || (defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0)) */ +} + +ACE_WIN32_Asynch_Accept::~ACE_WIN32_Asynch_Accept (void) +{ +} + +// Methods belong to ACE_WIN32_Asynch_Operation base class. These +// methods are defined here to avoid VC++ warnings. They route the +// call to the ACE_WIN32_Asynch_Operation base class. + +int +ACE_WIN32_Asynch_Accept::open (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor) +{ + return ACE_WIN32_Asynch_Operation::open (handler_proxy, + handle, + completion_key, + proactor); +} + +int +ACE_WIN32_Asynch_Accept::cancel (void) +{ + return ACE_WIN32_Asynch_Operation::cancel (); +} + +ACE_Proactor * +ACE_WIN32_Asynch_Accept::proactor (void) const +{ + return ACE_WIN32_Asynch_Operation::proactor (); +} + +// ********************************************************************* + +ACE_HANDLE +ACE_WIN32_Asynch_Connect_Result::connect_handle (void) const +{ + return this->connect_handle_; +} + +void ACE_WIN32_Asynch_Connect_Result::connect_handle ( ACE_HANDLE handle ) +{ + this->connect_handle_ = handle; +} + + +ACE_WIN32_Asynch_Connect_Result::ACE_WIN32_Asynch_Connect_Result + (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE connect_handle, + const void* act, + ACE_HANDLE event, + int priority, + int signal_number) + : ACE_Asynch_Result_Impl (), + ACE_Asynch_Connect_Result_Impl (), + ACE_WIN32_Asynch_Result + (handler_proxy, act, event, 0, 0, priority, signal_number), + connect_handle_ (connect_handle) +{ + ; +} + +void +ACE_WIN32_Asynch_Connect_Result::complete (size_t bytes_transferred, + int success, + const void *completion_key, + u_long error) +{ + // Copy the data. + this->bytes_transferred_ = bytes_transferred; + this->success_ = success; + this->completion_key_ = completion_key; + this->error_ = error; + + // Create the interface result class. + ACE_Asynch_Connect::Result result (this); + + // Call the application handler. + ACE_Handler *handler = this->handler_proxy_.get ()->handler (); + if (handler != 0) + handler->handle_connect (result); +} + +ACE_WIN32_Asynch_Connect_Result::~ACE_WIN32_Asynch_Connect_Result (void) +{ +} + +// Base class operations. These operations are here to kill dominance +// warnings. These methods call the base class methods. + +size_t +ACE_WIN32_Asynch_Connect_Result::bytes_transferred (void) const +{ + return ACE_WIN32_Asynch_Result::bytes_transferred (); +} + +const void * +ACE_WIN32_Asynch_Connect_Result::act (void) const +{ + return ACE_WIN32_Asynch_Result::act (); +} + +int +ACE_WIN32_Asynch_Connect_Result::success (void) const +{ + return ACE_WIN32_Asynch_Result::success (); +} + +const void * +ACE_WIN32_Asynch_Connect_Result::completion_key (void) const +{ + return ACE_WIN32_Asynch_Result::completion_key (); +} + +u_long +ACE_WIN32_Asynch_Connect_Result::error (void) const +{ + return ACE_WIN32_Asynch_Result::error (); +} + +ACE_HANDLE +ACE_WIN32_Asynch_Connect_Result::event (void) const +{ + return ACE_WIN32_Asynch_Result::event (); +} + +u_long +ACE_WIN32_Asynch_Connect_Result::offset (void) const +{ + return ACE_WIN32_Asynch_Result::offset (); +} + +u_long +ACE_WIN32_Asynch_Connect_Result::offset_high (void) const +{ + return ACE_WIN32_Asynch_Result::offset_high (); +} + +int +ACE_WIN32_Asynch_Connect_Result::priority (void) const +{ + return ACE_WIN32_Asynch_Result::priority (); +} + +int +ACE_WIN32_Asynch_Connect_Result::signal_number (void) const +{ + return ACE_WIN32_Asynch_Result::signal_number (); +} + +int +ACE_WIN32_Asynch_Connect_Result::post_completion (ACE_Proactor_Impl *proactor) +{ + return ACE_WIN32_Asynch_Result::post_completion (proactor); +} + +// ********************************************************************* + +ACE_WIN32_Asynch_Connect::ACE_WIN32_Asynch_Connect (ACE_WIN32_Proactor * win32_proactor) + : ACE_Asynch_Operation_Impl (), + ACE_Asynch_Connect_Impl (), + ACE_WIN32_Asynch_Operation (win32_proactor), + flg_open_ (false) +{ +} + +ACE_WIN32_Asynch_Connect::~ACE_WIN32_Asynch_Connect (void) +{ + this->close (); + this->reactor (0); // to avoid purge_pending_notifications +} + +ACE_Proactor * +ACE_WIN32_Asynch_Connect::proactor (void) const +{ + return ACE_WIN32_Asynch_Operation::proactor (); +} + +ACE_HANDLE +ACE_WIN32_Asynch_Connect::get_handle (void) const +{ + + ACE_ASSERT (0); + return ACE_INVALID_HANDLE; +} + +void +ACE_WIN32_Asynch_Connect::set_handle (ACE_HANDLE) +{ + ACE_ASSERT (0) ; +} + +int +ACE_WIN32_Asynch_Connect::open (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE, + const void *completion_key, + ACE_Proactor *proactor) +{ + ACE_TRACE ("ACE_WIN32_Asynch_Connect::open"); + + // if we are already opened, + // we could not create a new handler without closing the previous + if (this->flg_open_) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("%N:%l:ACE_WIN32_Asynch_Connect::open:") + ACE_TEXT ("connector already open\n")), + -1); + + //int result = + ACE_WIN32_Asynch_Operation::open (handler_proxy, + ACE_INVALID_HANDLE, + completion_key, + proactor); + + // Ignore result as we pass ACE_INVALID_HANDLE + //if (result == -1) + // return result; + + this->flg_open_ = true; + + return 0; +} + +int +ACE_WIN32_Asynch_Connect::connect (ACE_HANDLE connect_handle, + const ACE_Addr & remote_sap, + const ACE_Addr & local_sap, + int reuse_addr, + const void *act, + int priority, + int signal_number) +{ + ACE_TRACE ("ACE_WIN32_Asynch_Connect::connect"); + + if (!this->flg_open_) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("%N:%l:ACE_WIN32_Asynch_Connect::connect") + ACE_TEXT ("connector was not opened before\n")), + -1); + + // Common code for both WIN and WIN32. + // Create future Asynch_Connect_Result + ACE_WIN32_Asynch_Connect_Result *result = 0; + ACE_NEW_RETURN (result, + ACE_WIN32_Asynch_Connect_Result (this->handler_proxy_, + connect_handle, + act, + this->win32_proactor_->get_handle (), + priority, + signal_number), + -1); + + int rc = connect_i (result, + remote_sap, + local_sap, + reuse_addr); + + // update handle + connect_handle = result->connect_handle (); + + if (rc != 0) + return post_result (result, true); + + // Enqueue result we will wait for completion + { + ACE_MT (ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, ace_mon, this->lock_, -1)); + + if (this->result_map_.bind (connect_handle, result) == -1) + { + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("ACE_WIN32_Asynch_Connect::connect: %p\n"), + ACE_TEXT ("bind"))); + result->set_error (EFAULT); + return post_result (result, true); + } + } + + ACE_Asynch_Pseudo_Task & task = + this->win32_proactor_->get_asynch_pseudo_task (); + + if (-1 == task.register_io_handler (connect_handle, + this, + ACE_Event_Handler::CONNECT_MASK, + 0)) // not to suspend after register + { + result = 0; + { + ACE_MT (ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, ace_mon, this->lock_, -1)); + this->result_map_.unbind (connect_handle, result); + } + if (result != 0) + { + result->set_error (EFAULT); + this->post_result (result, true); + } + } + + return 0; +} + +int ACE_WIN32_Asynch_Connect::post_result (ACE_WIN32_Asynch_Connect_Result * result, + bool post_enable) +{ + ACE_HANDLE handle = result->connect_handle (); + if (this->flg_open_ && post_enable) + { + // NOTE: result is invalid after post_completion(). It's either deleted + // or will be shortly via the proactor dispatch, regardless of success + // or fail of the call. + if (this->win32_proactor_ ->post_completion (result) == 0) + return 0; + + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("Error:(%P | %t):%p\n"), + ACE_TEXT ("ACE_WIN32_Asynch_Connect::post_result: ") + ACE_TEXT (" failed"))); + } + else + { + // There was no call to post_completion() so manually delete result. + delete result; + } + + if (handle != ACE_INVALID_HANDLE) + ACE_OS::closesocket (handle); + + return -1; +} + +// connect_i +// return code : +// -1 errors before attempt to connect +// 0 connect started +// 1 connect finished ( may be unsuccessfully) + +int +ACE_WIN32_Asynch_Connect::connect_i (ACE_WIN32_Asynch_Connect_Result *result, + const ACE_Addr & remote_sap, + const ACE_Addr & local_sap, + int reuse_addr) +{ + result->set_bytes_transferred (0); + + ACE_HANDLE handle = result->connect_handle (); + if (handle == ACE_INVALID_HANDLE) + { + int protocol_family = remote_sap.get_type (); + handle = ACE_OS::socket (protocol_family, + SOCK_STREAM, + 0); + + // save it + result->connect_handle (handle); + if (handle == ACE_INVALID_HANDLE) + { + result->set_error (errno); + ACE_ERROR_RETURN + ((LM_ERROR, + ACE_TEXT ("ACE_WIN32_Asynch_Connect::connect_i: %p\n"), + ACE_TEXT ("socket")), + -1); + } + + // Reuse the address + int one = 1; + if (protocol_family != PF_UNIX && + reuse_addr != 0 && + ACE_OS::setsockopt (handle, + SOL_SOCKET, + SO_REUSEADDR, + (const char*) &one, + sizeof one) == -1) + { + result->set_error (errno); + ACE_ERROR_RETURN + ((LM_ERROR, + ACE_TEXT ("ACE_WIN32_Asynch_Connect::connect_i: %p\n"), + ACE_TEXT ("setsockopt")), + -1); + } + } + + if (local_sap != ACE_Addr::sap_any) + { + sockaddr * laddr = reinterpret_cast (local_sap.get_addr ()); + int size = local_sap.get_size (); + if (ACE_OS::bind (handle, laddr, size) == -1) + { + result->set_error (errno); + ACE_ERROR_RETURN + ((LM_ERROR, + ACE_TEXT ("ACE_WIN32_Asynch_Connect::connect_i: %p\n"), + ACE_TEXT ("bind")), + -1); + } + } + + // set non blocking mode + if (ACE::set_flags (handle, ACE_NONBLOCK) != 0) + { + result->set_error (errno); + ACE_ERROR_RETURN + ((LM_ERROR, + ACE_TEXT ("ACE_WIN32_Asynch_Connect::connect_i: %p\n"), + ACE_TEXT ("set_flags")), + -1); + } + + for (;;) + { + int rc = ACE_OS::connect + (handle, + reinterpret_cast (remote_sap.get_addr ()), + remote_sap.get_size ()); + + if (rc < 0) // failure + { + if (errno == EWOULDBLOCK || errno == EINPROGRESS) + return 0; // connect started + + if (errno == EINTR) + continue; + + result->set_error (errno); + } + return 1 ; // connect finished + } +} + + +// cancel_uncompleted +// It performs cancellation of all pending requests +// +// Parameter flg_notify can be +// 0 - don't send notifications about canceled accepts +// !0 - notify user about canceled accepts +// according WIN32 standards we should receive notifications +// on canceled AIO requests +// +// Return value : number of cancelled requests +// + +int +ACE_WIN32_Asynch_Connect::cancel_uncompleted (bool flg_notify, + ACE_Handle_Set &set) +{ + ACE_TRACE ("ACE_WIN32_Asynch_Connect::cancel_uncompleted"); + + int retval = 0; + + MAP_MANAGER::ITERATOR iter (result_map_); + MAP_MANAGER::ENTRY * me = 0; + + set.reset (); + + for (; iter.next (me) != 0; retval++, iter.advance ()) + { + ACE_HANDLE handle = me->ext_id_; + ACE_WIN32_Asynch_Connect_Result* result = me->int_id_ ; + + set.set_bit (handle); + + result->set_bytes_transferred (0); + result->set_error (ERROR_OPERATION_ABORTED); + this->post_result (result, flg_notify); + } + + result_map_.unbind_all (); + + return retval; +} + +int +ACE_WIN32_Asynch_Connect::cancel (void) +{ + ACE_TRACE ("ACE_WIN32_Asynch_Connect::cancel"); + + int rc = -1 ; // ERRORS + + ACE_Handle_Set set; + int num_cancelled = 0; + { + ACE_MT (ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, ace_mon, this->lock_, -1)); + + num_cancelled = cancel_uncompleted (flg_open_, set); + } + if (num_cancelled == 0) + rc = 1; // AIO_ALLDONE + else if (num_cancelled > 0) + rc = 0; // AIO_CANCELED + + if (!this->flg_open_) + return rc; + + ACE_Asynch_Pseudo_Task & task = + this->win32_proactor_->get_asynch_pseudo_task (); + + task.remove_io_handler (set); + return rc; +} + +int +ACE_WIN32_Asynch_Connect::close (void) +{ + ACE_TRACE ("ACE_WIN32_Asynch_Connect::close"); + + ACE_Handle_Set set; + int num_cancelled = 0; + { + ACE_MT (ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, ace_mon, this->lock_, -1)); + + num_cancelled = cancel_uncompleted (flg_open_, set); + } + if (num_cancelled == 0 || this->flg_open_ == 0) + { + this->flg_open_ = false; + return 0; + } + + ACE_Asynch_Pseudo_Task & task = + this->win32_proactor_->get_asynch_pseudo_task (); + + task.remove_io_handler (set); + return 0; +} + +int +ACE_WIN32_Asynch_Connect::handle_exception (ACE_HANDLE fd) +{ + ACE_TRACE ("ACE_WIN32_Asynch_Connect::handle_exception"); + return handle_output (fd); +} + +int +ACE_WIN32_Asynch_Connect::handle_input (ACE_HANDLE fd) +{ + ACE_TRACE ("ACE_WIN32_Asynch_Connect::handle_input"); + return handle_output (fd); +} + +int +ACE_WIN32_Asynch_Connect::handle_output (ACE_HANDLE fd) +{ + ACE_TRACE ("ACE_WIN32_Asynch_Connect::handle_output"); + + ACE_WIN32_Asynch_Connect_Result* result = 0; + + { + ACE_MT (ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, ace_mon, this->lock_, 0)); + if (this->result_map_.unbind (fd, result) != 0) // not found + return -1; + } + + int sockerror = 0 ; + int lsockerror = sizeof sockerror; + + ACE_OS::getsockopt (fd, + SOL_SOCKET, + SO_ERROR, + (char*) & sockerror, + & lsockerror); + + // This previously just did a "return -1" and let handle_close() clean + // things up. However, this entire object may be gone as a result of + // the application's completion handler, so don't count on 'this' being + // legitimate on return from post_result(). + // remove_io_handler() contains flag DONT_CALL + this->win32_proactor_->get_asynch_pseudo_task().remove_io_handler (fd); + + result->set_bytes_transferred (0); + result->set_error (sockerror); + this->post_result (result, this->flg_open_); + return 0; +} + + +int +ACE_WIN32_Asynch_Connect::handle_close (ACE_HANDLE fd, ACE_Reactor_Mask) +{ + ACE_TRACE ("ACE_WIN32_Asynch_Connect::handle_close"); + + ACE_Asynch_Pseudo_Task & task = + this->win32_proactor_->get_asynch_pseudo_task (); + task.remove_io_handler (fd); + + ACE_WIN32_Asynch_Connect_Result* result = 0; + + { + ACE_MT (ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, ace_mon, this->lock_, 0)); + if (this->result_map_.unbind (fd, result) != 0) // not found + return -1; + } + + result->set_bytes_transferred (0); + result->set_error (ERROR_OPERATION_ABORTED); + this->post_result (result, this->flg_open_); + + return 0; +} + +// ********************************************************************* + +ACE_HANDLE +ACE_WIN32_Asynch_Transmit_File_Result::socket (void) const +{ + return this->socket_; +} + +ACE_HANDLE +ACE_WIN32_Asynch_Transmit_File_Result::file (void) const +{ + return this->file_; +} + +ACE_Asynch_Transmit_File::Header_And_Trailer * +ACE_WIN32_Asynch_Transmit_File_Result::header_and_trailer (void) const +{ + return this->header_and_trailer_; +} + +size_t +ACE_WIN32_Asynch_Transmit_File_Result::bytes_to_write (void) const +{ + return this->bytes_to_write_; +} + +size_t +ACE_WIN32_Asynch_Transmit_File_Result::bytes_per_send (void) const +{ + return this->bytes_per_send_; +} + +u_long +ACE_WIN32_Asynch_Transmit_File_Result::flags (void) const +{ + return this->flags_; +} + +ACE_WIN32_Asynch_Transmit_File_Result::ACE_WIN32_Asynch_Transmit_File_Result ( + const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE socket, + ACE_HANDLE file, + ACE_Asynch_Transmit_File::Header_And_Trailer *header_and_trailer, + size_t bytes_to_write, + u_long offset, + u_long offset_high, + size_t bytes_per_send, + u_long flags, + const void *act, + ACE_HANDLE event, + int priority, + int signal_number) + : ACE_Asynch_Result_Impl (), + ACE_Asynch_Transmit_File_Result_Impl (), + ACE_WIN32_Asynch_Result (handler_proxy, + act, + event, + offset, + offset_high, + priority, + signal_number), + socket_ (socket), + file_ (file), + header_and_trailer_ (header_and_trailer), + bytes_to_write_ (bytes_to_write), + bytes_per_send_ (bytes_per_send), + flags_ (flags) +{ +} + +void +ACE_WIN32_Asynch_Transmit_File_Result::complete (size_t bytes_transferred, + int success, + const void *completion_key, + u_long error) +{ + // Copy the data which was returned by GetQueuedCompletionStatus + this->bytes_transferred_ = bytes_transferred; + this->success_ = success; + this->completion_key_ = completion_key; + this->error_ = error; + + // We will not do this because (a) the header and trailer blocks may + // be the same message_blocks and (b) in cases of failures we have + // no idea how much of what (header, data, trailer) was sent. + /* + if (this->success_ && this->header_and_trailer_ != 0) + { + ACE_Message_Block *header = this->header_and_trailer_->header (); + if (header != 0) + header->rd_ptr (this->header_and_trailer_->header_bytes ()); + + ACE_Message_Block *trailer = this->header_and_trailer_->trailer (); + if (trailer != 0) + trailer->rd_ptr (this->header_and_trailer_->trailer_bytes ()); + } + */ + + // Create the interface result class. + ACE_Asynch_Transmit_File::Result result (this); + + // Call the application handler. + ACE_Handler *handler = this->handler_proxy_.get ()->handler (); + if (handler != 0) + handler->handle_transmit_file (result); +} + +ACE_WIN32_Asynch_Transmit_File_Result::~ACE_WIN32_Asynch_Transmit_File_Result (void) +{ +} + +// Base class operations. These operations are here to kill dominance +// warnings. These methods call the base class methods. + +size_t +ACE_WIN32_Asynch_Transmit_File_Result::bytes_transferred (void) const +{ + return ACE_WIN32_Asynch_Result::bytes_transferred (); +} + +const void * +ACE_WIN32_Asynch_Transmit_File_Result::act (void) const +{ + return ACE_WIN32_Asynch_Result::act (); +} + +int +ACE_WIN32_Asynch_Transmit_File_Result::success (void) const +{ + return ACE_WIN32_Asynch_Result::success (); +} + +const void * +ACE_WIN32_Asynch_Transmit_File_Result::completion_key (void) const +{ + return ACE_WIN32_Asynch_Result::completion_key (); +} + +u_long +ACE_WIN32_Asynch_Transmit_File_Result::error (void) const +{ + return ACE_WIN32_Asynch_Result::error (); +} + +ACE_HANDLE +ACE_WIN32_Asynch_Transmit_File_Result::event (void) const +{ + return ACE_WIN32_Asynch_Result::event (); +} + +u_long +ACE_WIN32_Asynch_Transmit_File_Result::offset (void) const +{ + return ACE_WIN32_Asynch_Result::offset (); +} + +u_long +ACE_WIN32_Asynch_Transmit_File_Result::offset_high (void) const +{ + return ACE_WIN32_Asynch_Result::offset_high (); +} + +int +ACE_WIN32_Asynch_Transmit_File_Result::priority (void) const +{ + return ACE_WIN32_Asynch_Result::priority (); +} + +int +ACE_WIN32_Asynch_Transmit_File_Result::signal_number (void) const +{ + return ACE_WIN32_Asynch_Result::signal_number (); +} + +int +ACE_WIN32_Asynch_Transmit_File_Result::post_completion (ACE_Proactor_Impl *proactor) +{ + return ACE_WIN32_Asynch_Result::post_completion (proactor); +} + +ACE_WIN32_Asynch_Transmit_File::ACE_WIN32_Asynch_Transmit_File (ACE_WIN32_Proactor *win32_proactor) + : ACE_Asynch_Operation_Impl (), + ACE_Asynch_Transmit_File_Impl (), + ACE_WIN32_Asynch_Operation (win32_proactor) +{ +} + +int +ACE_WIN32_Asynch_Transmit_File::transmit_file (ACE_HANDLE file, + ACE_Asynch_Transmit_File::Header_And_Trailer *header_and_trailer, + size_t bytes_to_write, + u_long offset, + u_long offset_high, + size_t bytes_per_send, + u_long flags, + const void *act, + int priority, + int signal_number) +{ +#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) || (defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0)) + + // TransmitFile API limits us to DWORD range. + if (bytes_to_write > MAXDWORD || bytes_per_send > MAXDWORD) + { + errno = ERANGE; + return -1; + } + DWORD dword_bytes_to_write = static_cast (bytes_to_write); + DWORD dword_bytes_per_send = static_cast (bytes_per_send); + + ACE_WIN32_Asynch_Transmit_File_Result *result = 0; + ACE_NEW_RETURN (result, + ACE_WIN32_Asynch_Transmit_File_Result (this->handler_proxy_, + this->handle_, + file, + header_and_trailer, + bytes_to_write, + offset, + offset_high, + bytes_per_send, + flags, + act, + this->win32_proactor_->get_handle (), + priority, + signal_number), + -1); + + ACE_LPTRANSMIT_FILE_BUFFERS transmit_buffers = 0; + if (result->header_and_trailer () != 0) + transmit_buffers = result->header_and_trailer ()->transmit_buffers (); + + // Initiate the transmit file + int initiate_result = ::TransmitFile ((SOCKET) result->socket (), + result->file (), + dword_bytes_to_write, + dword_bytes_per_send, + result, + transmit_buffers, + result->flags ()); + if (initiate_result == 1) + // Immediate success: the OVERLAPPED will still get queued. + return 1; + + // If initiate failed, check for a bad error. + ACE_OS::set_errno_to_last_error (); + switch (errno) + { + case ERROR_IO_PENDING: + // The IO will complete proactively: the OVERLAPPED will still + // get queued. + return 0; + + default: + // Something else went wrong: the OVERLAPPED will not get + // queued. + + // Cleanup dynamically allocated Asynch_Result + delete result; + + if (ACE::debug ()) + { + ACE_DEBUG ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("TransmitFile"))); + } + return -1; + } +#else + ACE_UNUSED_ARG (file); + ACE_UNUSED_ARG (header_and_trailer); + ACE_UNUSED_ARG (bytes_to_write); + ACE_UNUSED_ARG (offset); + ACE_UNUSED_ARG (offset_high); + ACE_UNUSED_ARG (bytes_per_send); + ACE_UNUSED_ARG (flags); + ACE_UNUSED_ARG (act); + ACE_UNUSED_ARG (priority); + ACE_UNUSED_ARG (signal_number); + ACE_NOTSUP_RETURN (-1); +#endif /* ACE_HAS_WIN32_OVERLAPPED_IO || ACE_HAS_WINSOCK2 */ +} + +ACE_WIN32_Asynch_Transmit_File::~ACE_WIN32_Asynch_Transmit_File (void) +{ +} + +// Methods belong to ACE_WIN32_Asynch_Operation base class. These +// methods are defined here to avoid VC++ warnings. They route the +// call to the ACE_WIN32_Asynch_Operation base class. + +int +ACE_WIN32_Asynch_Transmit_File::open (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor) +{ + return ACE_WIN32_Asynch_Operation::open (handler_proxy, + handle, + completion_key, + proactor); +} + +int +ACE_WIN32_Asynch_Transmit_File::cancel (void) +{ + return ACE_WIN32_Asynch_Operation::cancel (); +} + +ACE_Proactor * +ACE_WIN32_Asynch_Transmit_File::proactor (void) const +{ + return ACE_WIN32_Asynch_Operation::proactor (); +} + +size_t +ACE_WIN32_Asynch_Read_Dgram_Result::bytes_to_read (void) const +{ + return this->bytes_to_read_; +} + +ACE_Message_Block* +ACE_WIN32_Asynch_Read_Dgram_Result::message_block (void) const +{ + return this->message_block_; +} + + +int +ACE_WIN32_Asynch_Read_Dgram_Result::remote_address (ACE_Addr& addr) const +{ + int retVal = -1; // failure + + // make sure the addresses are of the same type + if (addr.get_type () == this->remote_address_->get_type ()) + { // copy the remote_address_ into addr + addr.set_addr (this->remote_address_->get_addr (), + this->remote_address_->get_size ()); + retVal = 0; // success + } + + return retVal; +} + +sockaddr * +ACE_WIN32_Asynch_Read_Dgram_Result::saddr () const +{ + return (sockaddr *) this->remote_address_->get_addr (); +} + + +int +ACE_WIN32_Asynch_Read_Dgram_Result::flags (void) const +{ + return this->flags_; +} + +ACE_HANDLE +ACE_WIN32_Asynch_Read_Dgram_Result::handle (void) const +{ + return this->handle_; +} + +size_t +ACE_WIN32_Asynch_Read_Dgram_Result::bytes_transferred (void) const +{ + return ACE_WIN32_Asynch_Result::bytes_transferred (); +} + +const void * +ACE_WIN32_Asynch_Read_Dgram_Result::act (void) const +{ + return ACE_WIN32_Asynch_Result::act (); +} + +int +ACE_WIN32_Asynch_Read_Dgram_Result::success (void) const +{ + return ACE_WIN32_Asynch_Result::success (); +} + +const void * +ACE_WIN32_Asynch_Read_Dgram_Result::completion_key (void) const +{ + return ACE_WIN32_Asynch_Result::completion_key (); +} + +u_long +ACE_WIN32_Asynch_Read_Dgram_Result::error (void) const +{ + return ACE_WIN32_Asynch_Result::error (); +} + +ACE_HANDLE +ACE_WIN32_Asynch_Read_Dgram_Result::event (void) const +{ + return ACE_WIN32_Asynch_Result::event (); +} + +u_long +ACE_WIN32_Asynch_Read_Dgram_Result::offset (void) const +{ + return ACE_WIN32_Asynch_Result::offset (); +} + +u_long +ACE_WIN32_Asynch_Read_Dgram_Result::offset_high (void) const +{ + return ACE_WIN32_Asynch_Result::offset_high (); +} + +int +ACE_WIN32_Asynch_Read_Dgram_Result::priority (void) const +{ + return ACE_WIN32_Asynch_Result::priority (); +} + +int +ACE_WIN32_Asynch_Read_Dgram_Result::signal_number (void) const +{ + return ACE_WIN32_Asynch_Result::signal_number (); +} + +int +ACE_WIN32_Asynch_Read_Dgram_Result::post_completion (ACE_Proactor_Impl *proactor) +{ + return ACE_WIN32_Asynch_Result::post_completion (proactor); +} + +ACE_WIN32_Asynch_Read_Dgram_Result::ACE_WIN32_Asynch_Read_Dgram_Result ( + const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + ACE_Message_Block *message_block, + size_t bytes_to_read, + int flags, + int protocol_family, + const void* act, + ACE_HANDLE event, + int priority, + int signal_number) + : ACE_Asynch_Result_Impl (), + ACE_Asynch_Read_Dgram_Result_Impl(), + ACE_WIN32_Asynch_Result (handler_proxy, act, event, 0, 0, priority, signal_number), + bytes_to_read_ (bytes_to_read), + message_block_ (message_block), + remote_address_ (0), + addr_len_ (0), + flags_ (flags), + handle_ (handle) +{ + ACE_ASSERT (protocol_family == PF_INET); // only supporting INET addresses + + ACE_NEW (remote_address_, ACE_INET_Addr); + addr_len_ = remote_address_->get_size (); + + ACE_UNUSED_ARG (protocol_family); +} + +void +ACE_WIN32_Asynch_Read_Dgram_Result::complete (size_t bytes_transferred, + int success, + const void *completion_key, + u_long error) +{ + // Copy the data which was returned by GetQueuedCompletionStatus + this->bytes_transferred_ = bytes_transferred; + this->success_ = success; + this->completion_key_ = completion_key; + this->error_ = error; + + // Appropriately move the pointers in the message block. + for (ACE_Message_Block* mb = this->message_block_; + (mb != 0) && (bytes_transferred > 0); + mb = mb->cont ()) + { + size_t len_part = mb->space (); + + if ( len_part > bytes_transferred) + len_part = bytes_transferred; + + mb->wr_ptr (len_part); + + bytes_transferred -= len_part; + } + + // Adjust the address length + this->remote_address_->set_size (this->addr_len_); + + // Create the interface result class. + ACE_Asynch_Read_Dgram::Result result (this); + + // Call the application handler. + ACE_Handler *handler = this->handler_proxy_.get ()->handler (); + if (handler != 0) + handler->handle_read_dgram (result); +} + +ACE_WIN32_Asynch_Read_Dgram_Result::~ACE_WIN32_Asynch_Read_Dgram_Result (void) +{ + delete this->remote_address_; +} + +//*************************************************************************** + +ACE_WIN32_Asynch_Read_Dgram::~ACE_WIN32_Asynch_Read_Dgram (void) +{ +} + +ssize_t +ACE_WIN32_Asynch_Read_Dgram::recv (ACE_Message_Block *message_block, + size_t & number_of_bytes_recvd, + int flags, + int protocol_family, + const void *act, + int priority, + int signal_number) +{ + number_of_bytes_recvd = 0; + + size_t bytes_to_read = 0; + + iovec iov[ACE_IOV_MAX]; + int iovcnt = 0; + + for (const ACE_Message_Block* msg = message_block; + msg != 0 && iovcnt < ACE_IOV_MAX; + msg = msg->cont () , ++iovcnt ) + { + size_t msg_space = msg->space (); + + // OS should correctly process zero length buffers + // if ( msg_space == 0 ) + // ACE_ERROR_RETURN ((LM_ERROR, + // ACE_TEXT ("ACE_WIN32_Asynch_Read_Dgram::recv:") + // ACE_TEXT ("No space in the message block\n")), + // -1); + + bytes_to_read += msg_space; + + // Make as many iovec as needed to fit all of msg_len. + size_t wr_ptr_offset = 0; + + while (msg_space > 0 && iovcnt < ACE_IOV_MAX) + { + u_long this_chunk_length; + if (msg_space > ULONG_MAX) + this_chunk_length = ULONG_MAX; + else + this_chunk_length = static_cast (msg_space); + // Collect the data in the iovec. + iov[iovcnt].iov_base = msg->wr_ptr () + wr_ptr_offset; + iov[iovcnt].iov_len = this_chunk_length; + msg_space -= this_chunk_length; + wr_ptr_offset += this_chunk_length; + + // Increment iovec counter if there's more to do. + if (msg_space > 0) + iovcnt++; + } + if (msg_space > 0) // Ran out of iovecs before msg_space exhausted + { + errno = ERANGE; + return -1; + } + } + + if (bytes_to_read == 0) + ACE_ERROR_RETURN ((LM_ERROR, + ACE_TEXT ("ACE_WIN32_Asynch_Read_Dgram::recv:") + ACE_TEXT ("Attempt to read 0 bytes\n")), + -1); + + // Create the Asynch_Result. + ACE_WIN32_Asynch_Read_Dgram_Result *result = 0; + ACE_NEW_RETURN (result, + ACE_WIN32_Asynch_Read_Dgram_Result (this->handler_proxy_, + this->handle_, + message_block, + bytes_to_read, + flags, + protocol_family, + act, + this->win32_proactor_->get_handle (), + priority, + signal_number), + -1); + + // do the scatter/gather recv + ssize_t initiate_result = ACE_OS::recvfrom (result->handle (), + iov, + iovcnt, + number_of_bytes_recvd, + result->flags_, + result->saddr (), + &(result->addr_len_), + result, + 0); + if (initiate_result == SOCKET_ERROR) + { + // If initiate failed, check for a bad error. + ACE_OS::set_errno_to_last_error (); + switch (errno) + { + case ERROR_IO_PENDING: + // The IO will complete proactively: the OVERLAPPED will still + // get queued. + initiate_result = 0; + break; + + default: + // Something else went wrong: the OVERLAPPED will not get + // queued. + + if (ACE::debug ()) + { + ACE_DEBUG ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("WSARecvFrom"))); + } + + delete result; + initiate_result = -1; + break; + } + + } + else + { + // Immediate success: the OVERLAPPED will still get queued. + // number_of_bytes_recvd contains the number of bytes recvd + // addr contains the peer address + // flags was updated + + // number_of_bytes_recvd = bytes_recvd; + initiate_result = 1; + } + + return initiate_result; +} + +int +ACE_WIN32_Asynch_Read_Dgram::open (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor) +{ + return ACE_WIN32_Asynch_Operation::open (handler_proxy, + handle, + completion_key, + proactor); +} + +int +ACE_WIN32_Asynch_Read_Dgram::cancel (void) +{ + return ACE_WIN32_Asynch_Operation::cancel (); +} + +ACE_Proactor * +ACE_WIN32_Asynch_Read_Dgram::proactor (void) const +{ + return ACE_WIN32_Asynch_Operation::proactor (); +} + +ACE_WIN32_Asynch_Read_Dgram::ACE_WIN32_Asynch_Read_Dgram (ACE_WIN32_Proactor *win32_proactor) + : ACE_Asynch_Operation_Impl (), + ACE_Asynch_Read_Dgram_Impl (), + ACE_WIN32_Asynch_Operation (win32_proactor) +{ +} + +//*********************************************** + +size_t +ACE_WIN32_Asynch_Write_Dgram_Result::bytes_to_write (void) const +{ + return this->bytes_to_write_; +} + +ACE_Message_Block* +ACE_WIN32_Asynch_Write_Dgram_Result::message_block () const +{ + return this->message_block_; +} + +int +ACE_WIN32_Asynch_Write_Dgram_Result::flags (void) const +{ + return this->flags_; +} + +ACE_HANDLE +ACE_WIN32_Asynch_Write_Dgram_Result::handle (void) const +{ + return this->handle_; +} + +size_t +ACE_WIN32_Asynch_Write_Dgram_Result::bytes_transferred (void) const +{ + return ACE_WIN32_Asynch_Result::bytes_transferred (); +} + +const void * +ACE_WIN32_Asynch_Write_Dgram_Result::act (void) const +{ + return ACE_WIN32_Asynch_Result::act (); +} + +int +ACE_WIN32_Asynch_Write_Dgram_Result::success (void) const +{ + return ACE_WIN32_Asynch_Result::success (); +} + +const void * +ACE_WIN32_Asynch_Write_Dgram_Result::completion_key (void) const +{ + return ACE_WIN32_Asynch_Result::completion_key (); +} + +u_long +ACE_WIN32_Asynch_Write_Dgram_Result::error (void) const +{ + return ACE_WIN32_Asynch_Result::error (); +} + +ACE_HANDLE +ACE_WIN32_Asynch_Write_Dgram_Result::event (void) const +{ + return ACE_WIN32_Asynch_Result::event (); +} + +u_long +ACE_WIN32_Asynch_Write_Dgram_Result::offset (void) const +{ + return ACE_WIN32_Asynch_Result::offset (); +} + +u_long +ACE_WIN32_Asynch_Write_Dgram_Result::offset_high (void) const +{ + return ACE_WIN32_Asynch_Result::offset_high (); +} + +int +ACE_WIN32_Asynch_Write_Dgram_Result::priority (void) const +{ + return ACE_WIN32_Asynch_Result::priority (); +} + +int +ACE_WIN32_Asynch_Write_Dgram_Result::signal_number (void) const +{ + return ACE_WIN32_Asynch_Result::signal_number (); +} + +int +ACE_WIN32_Asynch_Write_Dgram_Result::post_completion (ACE_Proactor_Impl *proactor) +{ + return ACE_WIN32_Asynch_Result::post_completion (proactor); +} + +ACE_WIN32_Asynch_Write_Dgram_Result::ACE_WIN32_Asynch_Write_Dgram_Result ( + const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + ACE_Message_Block *message_block, + size_t bytes_to_write, + int flags, + const void* act, + ACE_HANDLE event, + int priority, + int signal_number) + : ACE_Asynch_Result_Impl (), + ACE_Asynch_Write_Dgram_Result_Impl(), + ACE_WIN32_Asynch_Result (handler_proxy, + act, + event, + 0, + 0, + priority, + signal_number), + bytes_to_write_ (bytes_to_write), + message_block_ (message_block), + flags_ (flags), + handle_ (handle) +{ +} + +void +ACE_WIN32_Asynch_Write_Dgram_Result::complete (size_t bytes_transferred, + int success, + const void *completion_key, + u_long error) +{ + // Copy the data which was returned by GetQueuedCompletionStatus + this->bytes_transferred_ = bytes_transferred; + this->success_ = success; + this->completion_key_ = completion_key; + this->error_ = error; + + // Appropriately move the pointers in the message block. + for (ACE_Message_Block* mb = this->message_block_; + (mb != 0) && (bytes_transferred > 0); + mb = mb->cont ()) + { + size_t len_part = mb->length (); + + if ( len_part > bytes_transferred) + len_part = bytes_transferred; + + mb->rd_ptr (len_part); + + bytes_transferred -= len_part; + } + + // Create the interface result class. + ACE_Asynch_Write_Dgram::Result result (this); + + // Call the application handler. + ACE_Handler *handler = this->handler_proxy_.get ()->handler (); + if (handler != 0) + handler->handle_write_dgram (result); +} + +ACE_WIN32_Asynch_Write_Dgram_Result::~ACE_WIN32_Asynch_Write_Dgram_Result (void) +{ +} + + +//*********************************************** + +ACE_WIN32_Asynch_Write_Dgram::~ACE_WIN32_Asynch_Write_Dgram (void) +{ +} + +ssize_t +ACE_WIN32_Asynch_Write_Dgram::send (ACE_Message_Block *message_block, + size_t &number_of_bytes_sent, + int flags, + const ACE_Addr &addr, + const void *act, + int priority, + int signal_number) +{ + number_of_bytes_sent = 0; + + size_t bytes_to_write = 0; + + iovec iov[ACE_IOV_MAX]; + int iovcnt = 0; + + for (const ACE_Message_Block* msg = message_block; + msg != 0 && iovcnt < ACE_IOV_MAX; + msg = msg->cont () , ++iovcnt ) + { + size_t msg_len = msg->length (); + + bytes_to_write += msg_len; + + // Make as many iovec as needed to fit all of msg_len. + size_t rd_ptr_offset = 0; + + do + { + if (msg_len >= 0 && iovcnt < ACE_IOV_MAX) + { + u_long this_chunk_length; + if (msg_len > ULONG_MAX) + this_chunk_length = ULONG_MAX; + else + this_chunk_length = static_cast (msg_len); + + // Collect the data in the iovec. + iov[iovcnt].iov_base = msg->rd_ptr () + rd_ptr_offset; + iov[iovcnt].iov_len = this_chunk_length; + msg_len -= this_chunk_length; + rd_ptr_offset += this_chunk_length; + + // Increment iovec counter if there's more to do. + if (msg_len > 0) + iovcnt++; + } + } + while (msg_len > 0 && iovcnt < ACE_IOV_MAX); + + if (msg_len > 0) // Ran out of iovecs before msg_space exhausted + { + errno = ERANGE; + return -1; + } + } + + // Create the Asynch_Result. + ACE_WIN32_Asynch_Write_Dgram_Result *result = 0; + ACE_NEW_RETURN (result, + ACE_WIN32_Asynch_Write_Dgram_Result (this->handler_proxy_, + this->handle_, + message_block, + bytes_to_write, + flags, + act, + this->win32_proactor_->get_handle (), + priority, + signal_number), + -1); + + // do the scatter/gather send + + ssize_t initiate_result = ACE_OS::sendto (result->handle (), + iov, + iovcnt, + number_of_bytes_sent, + result->flags_, + (sockaddr *) addr.get_addr (), + addr.get_size(), + result, + 0); + + + if (initiate_result == SOCKET_ERROR) + { + // If initiate failed, check for a bad error. + ACE_OS::set_errno_to_last_error (); + switch (errno) + { + case ERROR_IO_PENDING: + // The IO will complete proactively: the OVERLAPPED will still + // get queued. + initiate_result = 0; + break; + + default: + // Something else went wrong: the OVERLAPPED will not get + // queued. + + if (ACE::debug ()) + { + ACE_DEBUG ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("WSASendTo"))); + } + + delete result; + initiate_result = -1; + break; + } + + } + else + { + // Immediate success: the OVERLAPPED will still get queued. + // number_of_bytes_recvd contains the number of bytes recvd + // addr contains the peer address + // flags was updated + + // number_of_bytes_sent = bytes_sent; + initiate_result = 1; + } + + return initiate_result; +} + +int +ACE_WIN32_Asynch_Write_Dgram::open (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor) +{ + return ACE_WIN32_Asynch_Operation::open (handler_proxy, + handle, + completion_key, + proactor); +} + +int +ACE_WIN32_Asynch_Write_Dgram::cancel (void) +{ + return ACE_WIN32_Asynch_Operation::cancel (); +} + +ACE_Proactor * +ACE_WIN32_Asynch_Write_Dgram::proactor (void) const +{ + return ACE_WIN32_Asynch_Operation::proactor (); +} + +ACE_WIN32_Asynch_Write_Dgram::ACE_WIN32_Asynch_Write_Dgram (ACE_WIN32_Proactor *win32_proactor) + : ACE_Asynch_Operation_Impl (), + ACE_Asynch_Write_Dgram_Impl (), + ACE_WIN32_Asynch_Operation (win32_proactor) +{ +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_WIN32_OVERLAPPED_IO && ACE_HAS_WINSOCK2 */ diff --git a/dep/acelite/ace/WIN32_Asynch_IO.h b/dep/acelite/ace/WIN32_Asynch_IO.h new file mode 100644 index 00000000000..34af77dabb2 --- /dev/null +++ b/dep/acelite/ace/WIN32_Asynch_IO.h @@ -0,0 +1,1937 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file WIN32_Asynch_IO.h + * + * $Id: WIN32_Asynch_IO.h 80826 2008-03-04 14:51:23Z wotte $ + * + * + * These classes only works on Win32 platforms. + * + * The implementation of ACE_Asynch_Transmit_File, + * ACE_Asynch_Accept, and ACE_Asynch_Connect are only supported if + * ACE_HAS_WINSOCK2 is defined or you are on WinNT 4.0 or higher. + * + * + * @author Irfan Pyarali + * @author Tim Harrison + * @author Alexander Babu Arulanthu + * @author Roger Tragin + * @author Alexander Libman + */ +//============================================================================= + +#ifndef ACE_WIN32_ASYNCH_IO_H +#define ACE_WIN32_ASYNCH_IO_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +#pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) && \ + (defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 == 1)) + +#include "ace/Asynch_IO_Impl.h" +#include "ace/Addr.h" +#include "ace/Event_Handler.h" +#include "ace/Handle_Set.h" +#include "ace/Map_Manager.h" +#include "ace/Null_Mutex.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Forward declaration +class ACE_WIN32_Proactor; + +/** + * @class ACE_WIN32_Asynch_Result + * + * @brief An abstract class which adds information to the OVERLAPPED + * structure to make it more useful. + * + * An abstract base class from which you can obtain some basic + * information like the number of bytes transferred, the ACT + * associated with the asynchronous operation, indication of + * success or failure, etc. Subclasses may want to store more + * information that is particular to the asynchronous operation + * it represents. + */ +class ACE_Export ACE_WIN32_Asynch_Result : public virtual ACE_Asynch_Result_Impl, + public OVERLAPPED +{ + /// Factory class has special permissions. + friend class ACE_WIN32_Asynch_Accept; + + /// Proactor class has special permission. + friend class ACE_WIN32_Proactor; + +public: + /// Number of bytes transferred by the operation. + size_t bytes_transferred (void) const; + + /// ACT associated with the operation. + const void *act (void) const; + + /// Did the operation succeed? + int success (void) const; + + /** + * This returns the ACT associated with the handle when it was + * registered with the I/O completion port. This ACT is not the + * same as the ACT associated with the asynchronous operation. + */ + const void *completion_key (void) const; + + /// Error value if the operation fail. + u_long error (void) const; + + /// Event associated with the OVERLAPPED structure. + ACE_HANDLE event (void) const; + + /// This really make sense only when doing file I/O. + u_long offset (void) const; + + /// Offset_high associated with the OVERLAPPED structure. + u_long offset_high (void) const; + + /// The priority of the asynchronous operation. Currently, this is + /// not supported on Win32. + int priority (void) const; + + /// Returns 0. + int signal_number (void) const; + + /// Post @c this to the Proactor's completion port. + int post_completion (ACE_Proactor_Impl *proactor); + + /// Destructor. + virtual ~ACE_WIN32_Asynch_Result (void); + + /// Simulate error value to use in the post_completion () + void set_error (u_long errcode); + + /// Simulate value to use in the post_completion () + void set_bytes_transferred (size_t nbytes); + +protected: + /// Constructor. + ACE_WIN32_Asynch_Result (const ACE_Handler::Proxy_Ptr &handler_proxy, + const void* act, + ACE_HANDLE event, + u_long offset, + u_long offset_high, + int priority, + int signal_number = 0); + + /// Proxy for the ACE_Handler that will be called back. + ACE_Handler::Proxy_Ptr handler_proxy_; + + /// ACT for this operation. + const void *act_; + + /// Bytes transferred by this operation. + size_t bytes_transferred_; + + /// Success indicator. + int success_; + + /// ACT associated with handle. + const void *completion_key_; + + /// Error if operation failed. + u_long error_; +}; + +/** + * @class ACE_WIN32_Asynch_Operation + * + * @brief This class abstracts out the common things needed for + * implementing Asynch_Operation for WIN32 platform. + * + */ +class ACE_Export ACE_WIN32_Asynch_Operation : public virtual ACE_Asynch_Operation_Impl +{ +public: + /** + * Initializes the factory with information which will be used with + * each asynchronous call. If ( == ACE_INVALID_HANDLE), + * will be called on the @a handler to get the + * correct handle. + */ + int open (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor); + + /** + * This cancels all pending accepts operations that were issued by + * the calling thread. The function does not cancel asynchronous + * operations issued by other threads. + */ + int cancel (void); + + // = Access methods. + + /// Return the underlying proactor. + ACE_Proactor* proactor (void) const; + +protected: + /// Constructor. + ACE_WIN32_Asynch_Operation (ACE_WIN32_Proactor *win32_proactor); + + /// Destructor. + virtual ~ACE_WIN32_Asynch_Operation (void); + + /// Win32 Proactor. + ACE_WIN32_Proactor *win32_proactor_; + + /// Proactor that this asynch IO is registered with. + ACE_Proactor *proactor_; + + /// Handler that will receive the callback. + ACE_Handler::Proxy_Ptr handler_proxy_; + + /// I/O handle used for reading. + ACE_HANDLE handle_; +}; + +/** + * @class ACE_WIN32_Asynch_Read_Stream_Result + * + * @brief This class provides concrete implementation for + * ACE_Asynch_Read_Stream::Result class. + */ +class ACE_Export ACE_WIN32_Asynch_Read_Stream_Result : public virtual ACE_Asynch_Read_Stream_Result_Impl, + public ACE_WIN32_Asynch_Result +{ + /// Factory class will have special permissions. + friend class ACE_WIN32_Asynch_Read_Stream; + + /// Proactor class has special permission. + friend class ACE_WIN32_Proactor; + +public: + /// The number of bytes which were requested at the start of the + /// asynchronous read. + size_t bytes_to_read (void) const; + + /// Message block which contains the read data. + ACE_Message_Block &message_block (void) const; + + /// I/O handle used for reading. + ACE_HANDLE handle (void) const; + + // Base class operations. These operations are here to kill + // dominance warnings. These methods call the base class methods. + + /// Number of bytes transferred by the operation. + size_t bytes_transferred (void) const; + + /// ACT associated with the operation. + const void *act (void) const; + + /// Did the operation succeed? + int success (void) const; + + /** + * This returns the ACT associated with the handle when it was + * registered with the I/O completion port. This ACT is not the + * same as the ACT associated with the asynchronous operation. + */ + const void *completion_key (void) const; + + /// Error value if the operation fail. + u_long error (void) const; + + /// Event associated with the OVERLAPPED structure. + ACE_HANDLE event (void) const; + + /// This really make sense only when doing file I/O. + u_long offset (void) const; + + /// Offset_high associated with the OVERLAPPED structure. + u_long offset_high (void) const; + + /// The priority of the asynchronous operation. Currently, this is + /// not supported on Win32. + int priority (void) const; + + /// No-op. Returns 0. + int signal_number (void) const; + + /// Post @c this to the Proactor's completion port. + int post_completion (ACE_Proactor_Impl *proactor); + + /// Accessor for the scatter read flag + int scatter_enabled (void) const; + +protected: + /// Constructor is protected since creation is limited to + /// ACE_Asynch_Read_Stream factory. + ACE_WIN32_Asynch_Read_Stream_Result (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + ACE_Message_Block &message_block, + size_t bytes_to_read, + const void* act, + ACE_HANDLE event, + int priority, + int signal_number = 0, + int scatter_enabled = 0); + + /// Proactor will call this method when the read completes. + virtual void complete (size_t bytes_transferred, + int success, + const void *completion_key, + u_long error); + + /// Destructor. + virtual ~ACE_WIN32_Asynch_Read_Stream_Result (void); + + /// Bytes requested when the asynchronous read was initiated. + size_t bytes_to_read_; + + /// Message block for reading the data into. + ACE_Message_Block &message_block_; + + /// I/O handle used for reading. + ACE_HANDLE handle_; + + /// Flag for scatter read + int scatter_enabled_; +}; + +/** + * @class ACE_WIN32_Asynch_Read_Stream + * + * @brief This class is a factory for starting off asynchronous reads + * on a stream. + * + * Once is called, multiple asynchronous s can + * started using this class. An ACE_Asynch_Read_Stream::Result + * will be passed back to the @a handler when the asynchronous + * reads completes through the + * callback. + */ +class ACE_Export ACE_WIN32_Asynch_Read_Stream : public virtual ACE_Asynch_Read_Stream_Impl, + public ACE_WIN32_Asynch_Operation +{ + +public: + /// Constructor. + ACE_WIN32_Asynch_Read_Stream (ACE_WIN32_Proactor *win32_proactor); + + /// This starts off an asynchronous read. Upto @a bytes_to_read will + /// be read and stored in the @a message_block. + int read (ACE_Message_Block &message_block, + size_t bytes_to_read, + const void *act, + int priority, + int signal_number = 0); + + /** + * Same as above but with scatter support, through chaining of composite + * message blocks using the continuation field. + */ + int readv (ACE_Message_Block &message_block, + size_t bytes_to_read, + const void *act, + int priority, + int signal_number = 0); + + /// Destructor. + virtual ~ACE_WIN32_Asynch_Read_Stream (void); + + // Methods belong to ACE_WIN32_Asynch_Operation base class. These + // methods are defined here to avoid VC++ warnings. They route the + // call to the ACE_WIN32_Asynch_Operation base class. + + /** + * Initializes the factory with information which will be used with + * each asynchronous call. If ( == ACE_INVALID_HANDLE), + * will be called on the @a handler to get the + * correct handle. + */ + int open (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor); + + /** + * This cancels all pending accepts operations that were issued by + * the calling thread. The function does not cancel asynchronous + * operations issued by other threads. + */ + int cancel (void); + + /// Return the underlying proactor. + ACE_Proactor* proactor (void) const; + +protected: + /// This is the method which does the real work and is there so that + /// the ACE_Asynch_Read_File class can use it too. + int shared_read (ACE_WIN32_Asynch_Read_Stream_Result *result); +}; + +/** + * @class ACE_WIN32_Asynch_Write_Stream_Result + * + * @brief This class provides concrete implementation for + * ACE_Asynch_Write_Stream::Result class. + */ +class ACE_Export ACE_WIN32_Asynch_Write_Stream_Result : public virtual ACE_Asynch_Write_Stream_Result_Impl, + public ACE_WIN32_Asynch_Result +{ + /// Factory class willl have special permissions. + friend class ACE_WIN32_Asynch_Write_Stream; + + /// Proactor class has special permission. + friend class ACE_WIN32_Proactor; + +public: + /// The number of bytes which were requested at the start of the + /// asynchronous write. + size_t bytes_to_write (void) const; + + /// Message block that contains the data to be written. + ACE_Message_Block &message_block (void) const; + + /// I/O handle used for writing. + ACE_HANDLE handle (void) const; + + // = Base class operations. These operations are here to kill some + // warnings. These methods call the base class methods. + + /// Number of bytes transferred by the operation. + size_t bytes_transferred (void) const; + + /// ACT associated with the operation. + const void *act (void) const; + + /// Did the operation succeed? + int success (void) const; + + /** + * This returns the ACT associated with the handle when it was + * registered with the I/O completion port. This ACT is not the + * same as the ACT associated with the asynchronous operation. + */ + const void *completion_key (void) const; + + /// Error value if the operation fail. + u_long error (void) const; + + /// Event associated with the OVERLAPPED structure. + ACE_HANDLE event (void) const; + + /// This really make sense only when doing file I/O. + u_long offset (void) const; + + /// Offset_high associated with the OVERLAPPED structure. + u_long offset_high (void) const; + + /// The priority of the asynchronous operation. Currently, this is + /// not supported on Win32. + int priority (void) const; + + /// No-op. Returns 0. + int signal_number (void) const; + + /// Post @c this to the Proactor's completion port. + int post_completion (ACE_Proactor_Impl *proactor); + + /// Accessor for the gather write flag + int gather_enabled (void) const; + +protected: + /// Constructor is protected since creation is limited to + /// ACE_Asynch_Write_Stream factory. + ACE_WIN32_Asynch_Write_Stream_Result (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + ACE_Message_Block &message_block, + size_t bytes_to_write, + const void* act, + ACE_HANDLE event, + int priority, + int signal_number = 0, + int gather_enabled = 0); + + /// ACE_Proactor will call this method when the write completes. + virtual void complete (size_t bytes_transferred, + int success, + const void *completion_key, + u_long error); + + /// Destructor. + virtual ~ACE_WIN32_Asynch_Write_Stream_Result (void); + + /// The number of bytes which were requested at the start of the + /// asynchronous write. + size_t bytes_to_write_; + + /// Message block that contains the data to be written. + ACE_Message_Block &message_block_; + + /// I/O handle used for writing. + ACE_HANDLE handle_; + + /// Flag for gather write + int gather_enabled_; +}; + +/** + * @class ACE_WIN32_Asynch_Write_Stream + * + * @brief This class is a factory for starting off asynchronous writes + * on a stream. + * + * + * Once is called, multiple asynchronous s can + * started using this class. A ACE_Asynch_Write_Stream::Result + * will be passed back to the @a handler when the asynchronous + * write completes through the + * callback. + */ +class ACE_Export ACE_WIN32_Asynch_Write_Stream : public virtual ACE_Asynch_Write_Stream_Impl, + public ACE_WIN32_Asynch_Operation +{ +public: + /// Constructor. + ACE_WIN32_Asynch_Write_Stream (ACE_WIN32_Proactor *win32_proactor); + + /// This starts off an asynchronous write. Upto @a bytes_to_write + /// will be written from the @a message_block. + int write (ACE_Message_Block &message_block, + size_t bytes_to_write, + const void *act, + int priority, + int signal_number = 0); + + /** + * Same as above but with gather support, through chaining of composite + * message blocks using the continuation field. + */ + int writev (ACE_Message_Block &message_block, + size_t bytes_to_write, + const void *act, + int priority, + int signal_number = 0); + + /// Destructor. + virtual ~ACE_WIN32_Asynch_Write_Stream (void); + + // = Methods belonging to base class. + + // These methods are defined here to avoid VC++ warnings. They route + // the call to the base class. + + /** + * Initializes the factory with information which will be used with + * each asynchronous call. If ( == ACE_INVALID_HANDLE), + * will be called on the @a handler to get the + * correct handle. + */ + int open (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor); + + /** + * This cancels all pending accepts operations that were issued by + * the calling thread. The function does not cancel asynchronous + * operations issued by other threads. + */ + int cancel (void); + + /// Return the underlying proactor. + ACE_Proactor* proactor (void) const; + +protected: + /// This is the method which does the real work and is there so that + /// the ACE_Asynch_Write_File class can use it too. + int shared_write (ACE_WIN32_Asynch_Write_Stream_Result *result); +}; + +/** + * @class ACE_WIN32_Asynch_Read_File_Result + * + * @brief This class provides concrete implementation for + * ACE_Asynch_Read_File::Result class. + */ +class ACE_Export ACE_WIN32_Asynch_Read_File_Result : public virtual ACE_Asynch_Read_File_Result_Impl, + public ACE_WIN32_Asynch_Read_Stream_Result +{ + /// Factory class will have special permissions. + friend class ACE_WIN32_Asynch_Read_File; + + /// Proactor class has special permission. + friend class ACE_WIN32_Proactor; + +public: + // = These methods belong to ACE_WIN32_Asynch_Result class base + // class. These operations are here to kill some warnings. These + // methods call the base class methods. + + /// Number of bytes transferred by the operation. + size_t bytes_transferred (void) const; + + /// ACT associated with the operation. + const void *act (void) const; + + /// Did the operation succeed? + int success (void) const; + + /** + * This returns the ACT associated with the handle when it was + * registered with the I/O completion port. This ACT is not the + * same as the ACT associated with the asynchronous operation. + */ + const void *completion_key (void) const; + + /// Error value if the operation fail. + u_long error (void) const; + + /// Event associated with the OVERLAPPED structure. + ACE_HANDLE event (void) const; + + /// This really make sense only when doing file I/O. + u_long offset (void) const; + + /// Offset_high associated with the OVERLAPPED structure. + u_long offset_high (void) const; + + /// The priority of the asynchronous operation. Currently, this is + /// not supported on Win32. + int priority (void) const; + + /// No-op. Returns 0. + int signal_number (void) const; + + // The following methods belong to + // ACE_WIN32_Asynch_Read_Stream_Result. They are here to avoid VC++ + // dominance warnings. These methods route their call to the + // ACE_WIN32_Asynch_Read_Stream_Result base class. + + /// The number of bytes which were requested at the start of the + /// asynchronous read. + size_t bytes_to_read (void) const; + + /// Message block which contains the read data. + ACE_Message_Block &message_block (void) const; + + /// I/O handle used for reading. + ACE_HANDLE handle (void) const; + + /// Post @c this to the Proactor's completion port. + int post_completion (ACE_Proactor_Impl *proactor); + +protected: + /// Constructor is protected since creation is limited to + /// ACE_Asynch_Read_File factory. + ACE_WIN32_Asynch_Read_File_Result (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + ACE_Message_Block &message_block, + size_t bytes_to_read, + const void* act, + u_long offset, + u_long offset_high, + ACE_HANDLE event, + int priority, + int signal_number = 0, + int scatter_enabled = 0); + + /// ACE_Proactor will call this method when the read completes. + virtual void complete (size_t bytes_transferred, + int success, + const void *completion_key, + u_long error); + + /// Destructor. + virtual ~ACE_WIN32_Asynch_Read_File_Result (void); +}; + +/** + * @class ACE_WIN32_Asynch_Read_File + * + * @brief This class is a factory for starting off asynchronous reads + * on a file. + * + * Once is called, multiple asynchronous s can + * started using this class. A ACE_Asynch_Read_File::Result + * will be passed back to the @a handler when the asynchronous + * reads completes through the + * callback. + * + * This class differs slightly from ACE_Asynch_Read_Stream as it + * allows the user to specify an offset for the read. + */ +class ACE_Export ACE_WIN32_Asynch_Read_File : public virtual ACE_Asynch_Read_File_Impl, + public ACE_WIN32_Asynch_Read_Stream +{ + +public: + /// Constructor. + ACE_WIN32_Asynch_Read_File (ACE_WIN32_Proactor *win32_proactor); + + /** + * This starts off an asynchronous read. Upto @a bytes_to_read will + * be read and stored in the @a message_block. The read will start + * at @a offset from the beginning of the file. + */ + int read (ACE_Message_Block &message_block, + size_t bytes_to_read, + u_long offset, + u_long offset_high, + const void *act, + int priority, + int signal_number = 0); + + /** + * Same as above but with scatter support, through chaining of + * composite message blocks using the continuation field. + * @note Each data block payload must be at least the size of a + * system memory page and must be aligned on a system memory page + * size boundary + */ + int readv (ACE_Message_Block &message_block, + size_t bytes_to_read, + u_long offset, + u_long offset_high, + const void *act, + int priority, + int signal_number = 0); + + + /// Destructor. + virtual ~ACE_WIN32_Asynch_Read_File (void); + + // = Methods belong to ACE_WIN32_Asynch_Operation base class. These + // methods are defined here to avoid VC++ warnings. They route the + // call to the ACE_WIN32_Asynch_Operation base class. + + /** + * Initializes the factory with information which will be used with + * each asynchronous call. If ( == ACE_INVALID_HANDLE), + * will be called on the @a handler to get the + * correct handle. + */ + int open (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor); + + /** + * This cancels all pending accepts operations that were issued by + * the calling thread. The function does not cancel asynchronous + * operations issued by other threads. + */ + int cancel (void); + + /// Return the underlying proactor. + ACE_Proactor* proactor (void) const; + +private: + /** + * This method belongs to ACE_WIN32_Asynch_Read_Stream. It is here + * to avoid the compiler warnings. We forward this call to the + * ACE_WIN32_Asynch_Read_Stream class. + */ + int read (ACE_Message_Block &message_block, + size_t bytes_to_read, + const void *act, + int priority, + int signal_number = 0); + + /** + * Same as above but with scatter support, through chaining of composite + * message blocks using the continuation field. + */ + int readv (ACE_Message_Block &message_block, + size_t bytes_to_read, + const void *act, + int priority, + int signal_number = 0); +}; + +/** + * @class ACE_WIN32_Asynch_Write_File_Result + * + * @brief This class provides implementation for + * ACE_Asynch_Write_File_Result for WIN32 platforms. + * + * This class has all the information necessary for the + * @a handler to uniquiely identify the completion of the + * asynchronous write. + * + * This class differs slightly from + * ACE_Asynch_Write_Stream::Result as it calls back + * on the @a handler instead + * of . No additional state + * is required by this class as ACE_Asynch_Result can store + * the @a offset. + */ +class ACE_Export ACE_WIN32_Asynch_Write_File_Result : public virtual ACE_Asynch_Write_File_Result_Impl, + public ACE_WIN32_Asynch_Write_Stream_Result +{ + /// Factory class will have special permission. + friend class ACE_WIN32_Asynch_Write_File; + + /// Proactor class has special permission. + friend class ACE_WIN32_Proactor; + +public: + // = Base class operations. These operations are here to kill some + // warnings. These methods call the base class methods. + + /// Number of bytes transferred by the operation. + size_t bytes_transferred (void) const; + + /// ACT associated with the operation. + const void *act (void) const; + + /// Did the operation succeed? + int success (void) const; + + /** + * This returns the ACT associated with the handle when it was + * registered with the I/O completion port. This ACT is not the + * same as the ACT associated with the asynchronous operation. + */ + const void *completion_key (void) const; + + /// Error value if the operation fail. + u_long error (void) const; + + /// Event associated with the OVERLAPPED structure. + ACE_HANDLE event (void) const; + + /// This really make sense only when doing file I/O. + u_long offset (void) const; + + /// Offset_high associated with the OVERLAPPED structure. + u_long offset_high (void) const; + + /// The priority of the asynchronous operation. Currently, this is + /// not supported on Win32. + int priority (void) const; + + /// No-op. Returns 0. + int signal_number (void) const; + + // The following methods belong to + // ACE_WIN32_Asynch_Read_Stream_Result. They are here to avoid VC++ + // warnings. These methods route their call to the + // ACE_WIN32_Asynch_Read_Stream_Result base class. + + /// The number of bytes which were requested at the start of the + /// asynchronous write. + size_t bytes_to_write (void) const; + + /// Message block that contains the data to be written. + ACE_Message_Block &message_block (void) const; + + /// I/O handle used for writing. + ACE_HANDLE handle (void) const; + + /// Post @c this to the Proactor's completion port. + int post_completion (ACE_Proactor_Impl *proactor); + +protected: + /// Constructor is protected since creation is limited to + /// ACE_Asynch_Write_File factory. + ACE_WIN32_Asynch_Write_File_Result (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + ACE_Message_Block &message_block, + size_t bytes_to_write, + const void* act, + u_long offset, + u_long offset_high, + ACE_HANDLE event, + int priority, + int signal_number = 0, + int gather_enabled = 0); + + /// ACE_Proactor will call this method when the write completes. + virtual void complete (size_t bytes_transferred, + int success, + const void *completion_key, + u_long error); + + /// Destructor. + virtual ~ACE_WIN32_Asynch_Write_File_Result (void); +}; + +/** + * @class ACE_WIN32_Asynch_Write_File + * + * @brief This class is a factory for starting off asynchronous writes + * on a file. + * + * Once is called, multiple asynchronous s can be + * started using this class. A ACE_Asynch_Write_File::Result + * will be passed back to the @a handler when the asynchronous + * writes completes through the + * callback. + */ +class ACE_Export ACE_WIN32_Asynch_Write_File : public virtual ACE_Asynch_Write_File_Impl, + public ACE_WIN32_Asynch_Write_Stream +{ +public: + /// Constructor. + ACE_WIN32_Asynch_Write_File (ACE_WIN32_Proactor *win32_proactor); + + /** + * This starts off an asynchronous write. Upto @a bytes_to_write + * will be write and stored in the @a message_block. The write will + * start at @a offset from the beginning of the file. + */ + int write (ACE_Message_Block &message_block, + size_t bytes_to_write, + u_long offset, + u_long offset_high, + const void *act, + int priority, + int signal_number = 0); + + /** + * Same as above but with gather support, through chaining of + * composite message blocks using the continuation field. + * @note Each data block payload must be at least the size of a + * system memory page and must be aligned on a system memory page + * size boundary + */ + int writev (ACE_Message_Block &message_block, + size_t bytes_to_write, + u_long offset, + u_long offset_high, + const void *act, + int priority, + int signal_number = 0); + + /// Destrcutor. + virtual ~ACE_WIN32_Asynch_Write_File (void); + + // = Methods belong to ACE_WIN32_Asynch_Operation base class. These + // methods are defined here to avoid VC++ warnings. They route the + // call to the ACE_WIN32_Asynch_Operation base class. + + /** + * Initializes the factory with information which will be used with + * each asynchronous call. If ( == ACE_INVALID_HANDLE), + * will be called on the @a handler to get the + * correct handle. + */ + int open (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor); + + /** + * This cancels all pending accepts operations that were issued by + * the calling thread. The function does not cancel asynchronous + * operations issued by other threads. + */ + int cancel (void); + + /// Return the underlying proactor. + ACE_Proactor* proactor (void) const; + +private: + /** + * This method belongs to ACE_WIN32_Asynch_Write_Stream. It is here + * to avoid compiler warnings. This method is forwarded to the + * ACE_WIN32_Asynch_Write_Stream class. + */ + int write (ACE_Message_Block &message_block, + size_t bytes_to_write, + const void *act, + int priority, + int signal_number = 0); + + /** + * Same as above but with gather support, through chaining of composite + * message blocks using the continuation field. + */ + int writev (ACE_Message_Block &message_block, + size_t bytes_to_write, + const void *act, + int priority, + int signal_number = 0); +}; + +/** + * @class ACE_WIN32_Asynch_Accept_Result + * + * @brief This class implements ACE_Asynch_Accept::Result for WIN32 + * platform. + * + * This class has all the information necessary for the + * @a handler to uniquiely identify the completion of the + * asynchronous accept. + */ +class ACE_Export ACE_WIN32_Asynch_Accept_Result : public virtual ACE_Asynch_Accept_Result_Impl, + public ACE_WIN32_Asynch_Result +{ + /// Factory will have special permission. + friend class ACE_WIN32_Asynch_Accept; + + /// Proactor class has special permission. + friend class ACE_WIN32_Proactor; + +public: + /// The number of bytes which were requested at the start of the + /// asynchronous accept. + size_t bytes_to_read (void) const; + + /// Message block which contains the read data. + ACE_Message_Block &message_block (void) const; + + /// I/O handle used for accepting new connections. + ACE_HANDLE listen_handle (void) const; + + /// I/O handle for the new connection. + ACE_HANDLE accept_handle (void) const; + + // = Base class operations. These operations are here to kill some + // warnings. These methods call the base class methods. + + /// Number of bytes transferred by the operation. + size_t bytes_transferred (void) const; + + /// ACT associated with the operation. + const void *act (void) const; + + /// Did the operation succeed? + int success (void) const; + + /** + * This returns the ACT associated with the handle when it was + * registered with the I/O completion port. This ACT is not the + * same as the ACT associated with the asynchronous operation. + */ + const void *completion_key (void) const; + + /// Error value if the operation fail. + u_long error (void) const; + + /// Event associated with the OVERLAPPED structure. + ACE_HANDLE event (void) const; + + /// This really make sense only when doing file I/O. + u_long offset (void) const; + + /// Offset_high associated with the OVERLAPPED structure. + u_long offset_high (void) const; + + /// The priority of the asynchronous operation. Currently, this is + /// not supported on Win32. + int priority (void) const; + + /// No-op. Returns 0. + int signal_number (void) const; + + /// Post @c this to the Proactor's completion port. + int post_completion (ACE_Proactor_Impl *proactor); + +protected: + /// Constructor is protected since creation is limited to + /// ACE_Asynch_Accept factory. + ACE_WIN32_Asynch_Accept_Result (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE listen_handle, + ACE_HANDLE accept_handle, + ACE_Message_Block &message_block, + size_t bytes_to_read, + const void* act, + ACE_HANDLE event, + int priority, + int signal_number = 0); + + /// ACE_Proactor will call this method when the accept completes. + virtual void complete (size_t bytes_transferred, + int success, + const void *completion_key, + u_long error); + + /// Destructor. + virtual ~ACE_WIN32_Asynch_Accept_Result (void); + + /// Bytes requested when the asynchronous read was initiated. + size_t bytes_to_read_; + + /// Message block for reading the data into. + ACE_Message_Block &message_block_; + + /// I/O handle used for accepting new connections. + ACE_HANDLE listen_handle_; + + /// I/O handle for the new connection. + ACE_HANDLE accept_handle_; +}; + +/** + * @class ACE_WIN32_Asynch_Accept + * + * @brief This class is a factory for starting off asynchronous accepts + * on a listen handle. + * + * Once is called, multiple asynchronous s can + * started using this class. A ACE_Asynch_Accept::Result will + * be passed back to the @a handler when the asynchronous accept + * completes through the + * callback. + */ +class ACE_Export ACE_WIN32_Asynch_Accept : public virtual ACE_Asynch_Accept_Impl, + public ACE_WIN32_Asynch_Operation +{ +public: + /// Constructor. + ACE_WIN32_Asynch_Accept (ACE_WIN32_Proactor *win32_proactor); + + /** + * This starts off an asynchronous accept. The asynchronous accept + * call also allows any initial data to be returned to the + * @a handler. Upto @a bytes_to_read will be read and stored in the + * @a message_block. The will be used for the + * call. If ( == INVALID_HANDLE), a new + * handle will be created. + * + * @a message_block must be specified. This is because the address of + * the new connection is placed at the end of this buffer. + */ + int accept (ACE_Message_Block &message_block, + size_t bytes_to_read, + ACE_HANDLE accept_handle, + const void *act, + int priority, + int signal_number = 0, + int addr_family = AF_INET); + + /// Destructor. + ~ACE_WIN32_Asynch_Accept (void); + + // Methods belong to ACE_WIN32_Asynch_Operation base class. These + // methods are defined here to avoid VC++ warnings. They route the + // call to the ACE_WIN32_Asynch_Operation base class. + + /** + * Initializes the factory with information which will be used with + * each asynchronous call. If ( == ACE_INVALID_HANDLE), + * will be called on the @a handler to get the + * correct handle. + */ + int open (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor); + + /** + * This cancels all pending accepts operations that were issued by + * the calling thread. The function does not cancel asynchronous + * operations issued by other threads. + */ + int cancel (void); + + /// Return the underlying proactor. + ACE_Proactor* proactor (void) const; +}; + +/** + * @class ACE_WIN32_Asynch_Connect_Result + * + * @brief This is that class which will be passed back to the + * completion handler when the asynchronous connect completes. + * + * This class has all the information necessary for the + * completion handler to uniquiely identify the completion of the + * asynchronous connect. + */ +class ACE_Export ACE_WIN32_Asynch_Connect_Result : public virtual ACE_Asynch_Connect_Result_Impl, + public ACE_WIN32_Asynch_Result +{ + /// Factory classes will have special permissions. + friend class ACE_WIN32_Asynch_Connect; + + /// The Proactor constructs the Result class for faking results. + friend class ACE_WIN32_Proactor; + +public: + + /// I/O handle for the connection. + ACE_HANDLE connect_handle (void) const; + + // = Base class operations. These operations are here to kill some + // warnings. These methods call the base class methods. + + /// Number of bytes transferred by the operation. + size_t bytes_transferred (void) const; + + /// ACT associated with the operation. + const void *act (void) const; + + /// Did the operation succeed? + int success (void) const; + + /** + * Returns the ACT associated with the handle when it was + * registered with the I/O completion port. This ACT is not the + * same as the ACT associated with the asynchronous operation. + */ + const void *completion_key (void) const; + + /// Error value if the operation fail. + u_long error (void) const; + + /// Event associated with the OVERLAPPED structure. + ACE_HANDLE event (void) const; + + /// This really make sense only when doing file I/O. + u_long offset (void) const; + + /// Offset_high associated with the OVERLAPPED structure. + u_long offset_high (void) const; + + /// The priority of the asynchronous operation. Currently, this is + /// not supported on Win32. + int priority (void) const; + + /// No-op. Returns 0. + int signal_number (void) const; + + /// Post this object to the Proactor's completion port. + int post_completion (ACE_Proactor_Impl *proactor); + +protected: + /// Constructor is protected since creation is limited to + /// ACE_Asynch_Connect factory. + ACE_WIN32_Asynch_Connect_Result (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE connect_handle, + const void* act, + ACE_HANDLE event, + int priority, + int signal_number); + + /// ACE_Proactor will call this method when the accept completes. + virtual void complete (size_t bytes_transferred, + int success, + const void *completion_key, + u_long error); + + /// Destructor. + virtual ~ACE_WIN32_Asynch_Connect_Result (void); + + /// Set the I/O handle for the new connection. + void connect_handle (ACE_HANDLE handle); + + ACE_HANDLE connect_handle_; +}; + + +/** + * @class ACE_WIN32_Asynch_Connect + */ +class ACE_Export ACE_WIN32_Asynch_Connect : + public virtual ACE_Asynch_Connect_Impl, + public ACE_WIN32_Asynch_Operation, + public ACE_Event_Handler +{ +public: + + /// Constructor. + ACE_WIN32_Asynch_Connect (ACE_WIN32_Proactor * win32_proactor); + + /// Destructor. + virtual ~ACE_WIN32_Asynch_Connect (void); + + /** + * This open belongs to ACE_WIN32_Asynch_Operation. We forward + * this call to that method. We have put this here to avoid the + * compiler warnings. + */ + int open (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor = 0); + + /** + * Start an asynchronous connect. + * + * @param connect_handle Handle to use for the connect. If the value + * ACE_INVALID_HANDLE, a new handle will be created. + * + * @retval 0 Success + * @retval -1 Error + */ + int connect (ACE_HANDLE connect_handle, + const ACE_Addr &remote_sap, + const ACE_Addr &local_sap, + int reuse_addr, + const void *act, + int priority, + int signal_number = 0); + + /** + * Cancel all pending pseudo-asynchronus requests + * Behavior as usual AIO request + */ + int cancel (void); + + /** + * Close performs cancellation of all pending requests + * and close the connect handle + */ + int close (void); + + /// Virtual from ACE_Event_Handler + ACE_HANDLE get_handle (void) const; + + /// Virtual from ACE_Event_Handler + void set_handle (ACE_HANDLE handle); + + /// Virtual from ACE_Event_Handler + int handle_input ( ACE_HANDLE handle); + int handle_output ( ACE_HANDLE handle); + int handle_exception ( ACE_HANDLE handle); + + /// Virtual from ACE_Event_Handler + int handle_close (ACE_HANDLE handle, ACE_Reactor_Mask close_mask) ; + + // = Methods belong to ACE_WIN32_Asynch_Operation base class. These + // methods are defined here to avoid dominace warnings. They route + // the call to the ACE_WIN32_Asynch_Operation base class. + /// Return the underlying proactor. + ACE_Proactor* proactor (void) const; + +private: + int connect_i (ACE_WIN32_Asynch_Connect_Result *result, + const ACE_Addr &remote_sap, + const ACE_Addr &local_sap, + int reuse_addr); + + int post_result (ACE_WIN32_Asynch_Connect_Result *result, bool flg_post); + + /// Cancel uncompleted connect operations. + /** + * @param flg_notify Indicates whether or not to send notification about + * canceled connect operations. If false, don't send + * notifications. If true, notify user about canceled + * connects. + * According WIN32 standards we should receive + * notifications on canceled AIO requests. + * + * @param set Receives the set of I/O handles on which asynchronous + * connect requests were canceled as a result of this + * method. The contents of @a set are completely + * replaced. + */ + int cancel_uncompleted (bool flg_notify, ACE_Handle_Set &set); + + /// true - Connect is registered in ACE_Asynch_Pseudo_Task + /// false - Accept is deregisted in ACE_Asynch_Pseudo_Task + bool flg_open_ ; + + typedef ACE_Map_Manager + MAP_MANAGER; + + /// Map of Result pointers that correspond to all the 's + /// pending. + MAP_MANAGER result_map_; + + /// The lock to protect the result map which is shared. The queue + /// is updated by main thread in the register function call and + /// through the auxillary thread in the asynch pseudo task. + ACE_SYNCH_MUTEX lock_; +}; + +/** + * @class ACE_WIN32_Asynch_Transmit_File_Result + * + * + * @brief This class implements ACE_Asynch_Transmit_File::Result for + * WIN32 platforms. + * + * This class has all the information necessary for the + * @a handler to uniquiely identify the completion of the + * asynchronous transmit file. + */ +class ACE_Export ACE_WIN32_Asynch_Transmit_File_Result : public virtual ACE_Asynch_Transmit_File_Result_Impl, + public ACE_WIN32_Asynch_Result +{ + /// Factory class will have special permission. + friend class ACE_WIN32_Asynch_Transmit_File; + + /// Proactor class has special permission. + friend class ACE_WIN32_Proactor; + +public: + /// Socket used for transmitting the file. + ACE_HANDLE socket (void) const; + + /// File from which the data is read. + ACE_HANDLE file (void) const; + + /// Header and trailer data associated with this transmit file. + ACE_Asynch_Transmit_File::Header_And_Trailer *header_and_trailer (void) const; + + /// The number of bytes which were requested at the start of the + /// asynchronous transmit file. + size_t bytes_to_write (void) const; + + /// Number of bytes per send requested at the start of the transmit + /// file. + size_t bytes_per_send (void) const; + + /// Flags which were passed into transmit file. + u_long flags (void) const; + + // Base class operations. These operations are here to kill some + // warnings. These methods call the base class methods. + + /// Number of bytes transferred by the operation. + size_t bytes_transferred (void) const; + + /// ACT associated with the operation. + const void *act (void) const; + + /// Did the operation succeed? + int success (void) const; + + /** + * This returns the ACT associated with the handle when it was + * registered with the I/O completion port. This ACT is not the + * same as the ACT associated with the asynchronous operation. + */ + const void *completion_key (void) const; + + /// Error value if the operation fail. + u_long error (void) const; + + /// Event associated with the OVERLAPPED structure. + ACE_HANDLE event (void) const; + + /// This really make sense only when doing file I/O. + u_long offset (void) const; + + /// Offset_high associated with the OVERLAPPED structure. + u_long offset_high (void) const; + + /// The priority of the asynchronous operation. Currently, this is + /// not supported on Win32. + int priority (void) const; + + /// No-op. Returns 0. + int signal_number (void) const; + + /// Post @c this to the Proactor's completion port. + int post_completion (ACE_Proactor_Impl *proactor); + +protected: + /// Constructor is protected since creation is limited to + /// ACE_Asynch_Transmit_File factory. + ACE_WIN32_Asynch_Transmit_File_Result (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE socket, + ACE_HANDLE file, + ACE_Asynch_Transmit_File::Header_And_Trailer *header_and_trailer, + size_t bytes_to_write, + u_long offset, + u_long offset_high, + size_t bytes_per_send, + u_long flags, + const void *act, + ACE_HANDLE event, + int priority, + int signal_number = 0); + + /// Proactor will call this method when the write completes. + virtual void complete (size_t bytes_transferred, + int success, + const void *completion_key, + u_long error); + + /// Destructor. + virtual ~ACE_WIN32_Asynch_Transmit_File_Result (void); + + /// Network I/O handle. + ACE_HANDLE socket_; + + /// File I/O handle. + ACE_HANDLE file_; + + /// Header and trailer data associated with this transmit file. + ACE_Asynch_Transmit_File::Header_And_Trailer *header_and_trailer_; + + /// The number of bytes which were requested at the start of the + /// asynchronous transmit file. + size_t bytes_to_write_; + + /// Number of bytes per send requested at the start of the transmit + /// file. + size_t bytes_per_send_; + + /// Flags which were passed into transmit file. + u_long flags_; +}; + +/** + * @class ACE_WIN32_Asynch_Transmit_File + * + * @brief This class is a factory for starting off asynchronous + * transmit files on a stream. + * + * Once is called, multiple asynchronous s + * can started using this class. A + * ACE_Asynch_Transmit_File::Result will be passed back to the + * @a handler when the asynchronous transmit file completes + * through the callback. + * + * The transmit_file function transmits file data over a + * connected network connection. The function uses the operating + * system's cache manager to retrieve the file data. This + * function provides high-performance file data transfer over + * network connections. This function would be of great use in + * a Web Server, Image Server, etc. + */ +class ACE_Export ACE_WIN32_Asynch_Transmit_File : public virtual ACE_Asynch_Transmit_File_Impl, + public ACE_WIN32_Asynch_Operation +{ +public: + /// Constructor. + ACE_WIN32_Asynch_Transmit_File (ACE_WIN32_Proactor *win32_proactor); + + /** + * This starts off an asynchronous transmit file. The is a + * handle to an open file. is a pointer to a + * data structure that contains pointers to data to send before and + * after the file data is sent. Set this parameter to 0 if you only + * want to transmit the file data. Upto @a bytes_to_write will be + * written to the . If you want to send the entire file, + * let @a bytes_to_write = 0. @a bytes_per_send is the size of each + * block of data sent per send operation. Please read the Win32 + * documentation on what the flags should be. + */ + int transmit_file (ACE_HANDLE file, + ACE_Asynch_Transmit_File::Header_And_Trailer *header_and_trailer, + size_t bytes_to_write, + u_long offset, + u_long offset_high, + size_t bytes_per_send, + u_long flags, + const void *act, + int priority, + int signal_number = 0); + + /// Destructor. + ~ACE_WIN32_Asynch_Transmit_File (void); + + // Methods belong to ACE_WIN32_Asynch_Operation base class. These + // methods are defined here to avoid VC++ warnings. They route the + // call to the ACE_WIN32_Asynch_Operation base class. + + /** + * Initializes the factory with information which will be used with + * each asynchronous call. If ( == ACE_INVALID_HANDLE), + * will be called on the @a handler to get the + * correct handle. + */ + int open (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor); + + /** + * This cancels all pending accepts operations that were issued by + * the calling thread. The function does not cancel asynchronous + * operations issued by other threads. + */ + int cancel (void); + + /// Return the underlying proactor. + ACE_Proactor* proactor (void) const; +}; + +/** + * @class ACE_WIN32_Asynch_Read_Dgram_Result + * + * @brief This class provides concrete implementation for + * ACE_Asynch_Read_Dgram::Result class. + */ +class ACE_Export ACE_WIN32_Asynch_Read_Dgram_Result : public virtual ACE_Asynch_Read_Dgram_Result_Impl, + public ACE_WIN32_Asynch_Result +{ + /// Factory class will have special permissions. + friend class ACE_WIN32_Asynch_Read_Dgram; + + /// Proactor class has special permission. + friend class ACE_WIN32_Proactor; + +public: + /// The number of bytes which were requested at the start of the + /// asynchronous read. + size_t bytes_to_read (void) const; + + /// Message block which contains the read data + ACE_Message_Block *message_block (void) const; + + /// The address of where the packet came from + int remote_address (ACE_Addr& addr) const; + + sockaddr *saddr () const; + + /// The flags used in the read + int flags (void) const; + + /// I/O handle used for reading. + ACE_HANDLE handle (void) const; + + // Base class operations. These operations are here to kill + // dominance warnings. These methods call the base class methods. + + /// Number of bytes transferred by the operation. + size_t bytes_transferred (void) const; + + /// ACT associated with the operation. + const void *act (void) const; + + /// Did the operation succeed? + int success (void) const; + + /** + * This returns the ACT associated with the handle when it was + * registered with the I/O completion port. This ACT is not the + * same as the ACT associated with the asynchronous operation. + */ + const void *completion_key (void) const; + + /// Error value if the operation fail. + u_long error (void) const; + + /// Event associated with the OVERLAPPED structure. + ACE_HANDLE event (void) const; + + /// This really make sense only when doing file I/O. + u_long offset (void) const; + + /// Offset_high associated with the OVERLAPPED structure. + u_long offset_high (void) const; + + /// The priority of the asynchronous operation. Currently, this is + /// not supported on Win32. + int priority (void) const; + + /// No-op. Returns 0. + int signal_number (void) const; + + /// Post @c this to the Proactor's completion port. + int post_completion (ACE_Proactor_Impl *proactor); + +protected: + /// Constructor is protected since creation is limited to + /// ACE_Asynch_Read_Dgram factory. + ACE_WIN32_Asynch_Read_Dgram_Result (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + ACE_Message_Block *message_block, + size_t bytes_to_read, + int flags, + int protocol_family, + const void* act, + ACE_HANDLE event, + int priority, + int signal_number = 0); + + /// Proactor will call this method when the read completes. + virtual void complete (size_t bytes_transferred, + int success, + const void *completion_key, + u_long error); + + /// Destructor. + virtual ~ACE_WIN32_Asynch_Read_Dgram_Result (void); + + /// Bytes requested when the asynchronous read was initiated. + size_t bytes_to_read_; + + /// Message block for reading the data into. + ACE_Message_Block *message_block_; + + /// The address of where the packet came from + ACE_Addr *remote_address_; + + int addr_len_; + + /// The flags used in the read + int flags_; + + /// I/O handle used for reading. + ACE_HANDLE handle_; +}; + +/** + * @class ACE_WIN32_Asynch_Read_Dgram + * + * @brief This class is a factory for starting off asynchronous reads + * on a UDP socket. + * + * Once is called, multiple asynchronous s can be + * started using this class. An ACE_Asynch_Read_Dgram::Result + * will be passed back to the @a handler when the asynchronous + * reads completes through the + * callback. + * + */ +class ACE_Export ACE_WIN32_Asynch_Read_Dgram : public virtual ACE_Asynch_Read_Dgram_Impl, + public ACE_WIN32_Asynch_Operation +{ +public: + /// Constructor. + ACE_WIN32_Asynch_Read_Dgram (ACE_WIN32_Proactor *win32_proactor); + + /// Destructor. + virtual ~ACE_WIN32_Asynch_Read_Dgram (void); + + /** This starts off an asynchronous read. Upto + * total_size()> will be read and stored in the + * @a message_block. @a message_block's will be updated to reflect + * the added bytes if the read operation is successfully completed. + * Return code of 1 means immediate success and + * will contain number of bytes read. The + * method will still be called. Return code of 0 means the IO will + * complete proactively. Return code of -1 means there was an error, use + * errno to get the error code. + * + * Scatter/gather is supported on WIN32 by using the cont()> + * method. Up to ACE_IOV_MAX @a message_block's are supported. Upto + * size()> bytes will be read into each for + * a total of total_size()> bytes. All @a message_block's + * 's will be updated to reflect the added bytes for each + * @a message_block + */ + virtual ssize_t recv (ACE_Message_Block *message_block, + size_t &number_of_bytes_recvd, + int flags, + int protocol_family, + const void *act, + int priority, + int signal_number); + + // Methods belong to ACE_WIN32_Asynch_Operation base class. These + // methods are defined here to avoid VC++ warnings. They route the + // call to the ACE_WIN32_Asynch_Operation base class. + + /** + * Initializes the factory with information which will be used with + * each asynchronous call. If ( == ACE_INVALID_HANDLE), + * will be called on the @a handler to get the + * correct handle. + */ + int open (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor); + + /** + * This cancels all pending accepts operations that were issued by + * the calling thread. The function does not cancel asynchronous + * operations issued by other threads. + */ + int cancel (void); + + /// Return the underlying proactor. + ACE_Proactor* proactor (void) const; + +protected: + /// Do-nothing constructor. + ACE_WIN32_Asynch_Read_Dgram (void); +}; + +/** + * @class ACE_WIN32_Asynch_Write_Dgram_Result + * + * @brief This class provides concrete implementation for + * ACE_Asynch_Write_Dgram::Result class. + */ +class ACE_Export ACE_WIN32_Asynch_Write_Dgram_Result : public virtual ACE_Asynch_Write_Dgram_Result_Impl, + public ACE_WIN32_Asynch_Result +{ + /// Factory class willl have special permissions. + friend class ACE_WIN32_Asynch_Write_Dgram; + + /// Proactor class has special permission. + friend class ACE_WIN32_Proactor; + +public: + /// The number of bytes which were requested at the start of the + /// asynchronous write. + size_t bytes_to_write (void) const; + + /// Message block which contains the sent data + ACE_Message_Block *message_block (void) const; + + /// The flags using in the write + int flags (void) const; + + /// I/O handle used for writing. + ACE_HANDLE handle (void) const; + + // = Base class operations. These operations are here to kill some + // warnings. These methods call the base class methods. + + /// Number of bytes transferred by the operation. + size_t bytes_transferred (void) const; + + /// ACT associated with the operation. + const void *act (void) const; + + /// Did the operation succeed? + int success (void) const; + + /** + * This returns the ACT associated with the handle when it was + * registered with the I/O completion port. This ACT is not the + * same as the ACT associated with the asynchronous operation. + */ + const void *completion_key (void) const; + + /// Error value if the operation fail. + u_long error (void) const; + + /// Event associated with the OVERLAPPED structure. + ACE_HANDLE event (void) const; + + /// This really make sense only when doing file I/O. + u_long offset (void) const; + + /// Offset_high associated with the OVERLAPPED structure. + u_long offset_high (void) const; + + /// The priority of the asynchronous operation. Currently, this is + /// not supported on Win32. + int priority (void) const; + + /// No-op. Returns 0. + int signal_number (void) const; + + /// Post @c this to the Proactor's completion port. + int post_completion (ACE_Proactor_Impl *proactor); + +protected: + /// Constructor is protected since creation is limited to + /// ACE_Asynch_Write_Stream factory. + ACE_WIN32_Asynch_Write_Dgram_Result (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + ACE_Message_Block *message_block, + size_t bytes_to_write, + int flags, + const void* act, + ACE_HANDLE event, + int priority, + int signal_number = 0); + + /// ACE_Proactor will call this method when the write completes. + virtual void complete (size_t bytes_transferred, + int success, + const void *completion_key, + u_long error); + + /// Destructor. + virtual ~ACE_WIN32_Asynch_Write_Dgram_Result (void); + + /// The number of bytes which were requested at the start of the + /// asynchronous write. + size_t bytes_to_write_; + + /// Message block used for the send. + ACE_Message_Block *message_block_; + + /// The flags using in the write + int flags_; + + /// I/O handle used for writing. + ACE_HANDLE handle_; +}; + +/** + * @class ACE_WIN32_Asynch_Write_Dgram + * + * @brief This class is a factory for starting off asynchronous writes + * on a UDP socket. + * + * + * Once is called, multiple asynchronous s can + * started using this class. A ACE_Asynch_Write_Stream::Result + * will be passed back to the @a handler when the asynchronous + * write completes through the + * callback. + */ +class ACE_Export ACE_WIN32_Asynch_Write_Dgram : public virtual ACE_Asynch_Write_Dgram_Impl, + public ACE_WIN32_Asynch_Operation +{ +public: + /// Constructor. + ACE_WIN32_Asynch_Write_Dgram (ACE_WIN32_Proactor *win32_proactor); + + /// Destructor. + virtual ~ACE_WIN32_Asynch_Write_Dgram (void); + + /** This starts off an asynchronous send. Upto + * total_length()> will be sent. @a message_block's + * will be updated to reflect the sent bytes if the send operation + * is successfully completed. + * Return code of 1 means immediate success and + * is updated to number of bytes sent. The + * method will still be called. Return code of 0 means the IO will + * complete proactively. Return code of -1 means there was an error, use + * errno to get the error code. + * + * Scatter/gather is supported on WIN32 by using the cont()> + * method. Up to ACE_IOV_MAX @a message_block's are supported. Upto + * length()> bytes will be sent from each + * for a total of total_length()> bytes. All + * @a message_block's 's will be updated to reflect the bytes sent + * from each @a message_block. + */ + virtual ssize_t send (ACE_Message_Block *message_block, + size_t &number_of_bytes_sent, + int flags, + const ACE_Addr &addr, + const void *act, + int priority, + int signal_number); + + // = Methods belonging to base class. + + // These methods are defined here to avoid VC++ warnings. They route + // the call to the base class. + + /** + * Initializes the factory with information which will be used with + * each asynchronous call. If ( == ACE_INVALID_HANDLE), + * will be called on the @a handler to get the + * correct handle. + */ + int open (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + const void *completion_key, + ACE_Proactor *proactor); + + /** + * This cancels all pending accepts operations that were issued by + * the calling thread. The function does not cancel asynchronous + * operations issued by other threads. + */ + int cancel (void); + + /// Return the underlying proactor. + ACE_Proactor* proactor (void) const; + +protected: + /// Do-nothing constructor. + ACE_WIN32_Asynch_Write_Dgram (void); +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_WIN32_OVERLAPPED_IO && ACE_HAS_WINSOCK2 */ +#include /**/ "ace/post.h" +#endif /* ACE_WIN32_ASYNCH_IO_H */ diff --git a/dep/acelite/ace/WIN32_Proactor.cpp b/dep/acelite/ace/WIN32_Proactor.cpp new file mode 100644 index 00000000000..a559838976f --- /dev/null +++ b/dep/acelite/ace/WIN32_Proactor.cpp @@ -0,0 +1,804 @@ +// $Id: WIN32_Proactor.cpp 80826 2008-03-04 14:51:23Z wotte $ + +// ACE_RCSID(ace, Proactor, "$Id: WIN32_Proactor.cpp 80826 2008-03-04 14:51:23Z wotte $") + +#include "ace/WIN32_Proactor.h" + +#if defined (ACE_WIN32) && defined (ACE_HAS_WIN32_OVERLAPPED_IO) +// WIN implemenatation of the Proactor. + +#include "ace/Log_Msg.h" +#include "ace/Object_Manager.h" +#include "ace/OS_NS_errno.h" +#include "ace/OS_NS_unistd.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_WIN32_Wakeup_Completion + * + * This is result object is used by the of the + * ACE_Proactor interface to wake up all the threads blocking + * for completions. + */ +class ACE_WIN32_Wakeup_Completion : public ACE_WIN32_Asynch_Result +{ + +public: + /// Constructor. + ACE_WIN32_Wakeup_Completion (ACE_Handler::Proxy_Ptr &handler_proxy, + const void *act = 0, + ACE_HANDLE event = ACE_INVALID_HANDLE, + int priority = 0, + int signal_number = ACE_SIGRTMIN); + + /// Destructor. + virtual ~ACE_WIN32_Wakeup_Completion (void); + + /// This method calls the 's method. + virtual void complete (size_t bytes_transferred = 0, + int success = 1, + const void *completion_key = 0, + u_long error = 0); +}; + +ACE_WIN32_Proactor::ACE_WIN32_Proactor (size_t number_of_threads, + bool used_with_reactor_event_loop) + : completion_port_ (0), + // This *MUST* be 0, *NOT* ACE_INVALID_HANDLE !!! + number_of_threads_ (static_cast (number_of_threads)), + used_with_reactor_event_loop_ (used_with_reactor_event_loop) +{ + // Create the completion port. + this->completion_port_ = ::CreateIoCompletionPort (INVALID_HANDLE_VALUE, + 0, + 0, + this->number_of_threads_); + if (this->completion_port_ == 0) + ACE_ERROR ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("CreateIoCompletionPort"))); + + this->get_asynch_pseudo_task ().start (); +} + +ACE_WIN32_Proactor::~ACE_WIN32_Proactor (void) +{ + this->get_asynch_pseudo_task ().stop (); + + this->close (); +} + +ACE_Asynch_Pseudo_Task & +ACE_WIN32_Proactor::get_asynch_pseudo_task () +{ + return this->pseudo_task_; +} + +int +ACE_WIN32_Proactor::close (void) +{ + // Close the completion port + if (this->completion_port_ != 0) + { + // To avoid memory leaks we should delete all results from queue. + + for (;;) + { + ACE_OVERLAPPED *overlapped = 0; + u_long bytes_transferred = 0; + ULONG_PTR completion_key = 0; + + // Get the next asynchronous operation that completes + BOOL res = ::GetQueuedCompletionStatus + (this->completion_port_, + &bytes_transferred, + &completion_key, + &overlapped, + 0); // poll + + if (overlapped == 0 || res == FALSE) + break; + + ACE_WIN32_Asynch_Result *asynch_result = + (ACE_WIN32_Asynch_Result *) overlapped; + + delete asynch_result; + } + + int result = ACE_OS::close (this->completion_port_); + this->completion_port_ = 0; + return result; + } + + return 0; +} + +int +ACE_WIN32_Proactor::register_handle (ACE_HANDLE handle, + const void *completion_key) +{ + ULONG_PTR comp_key (reinterpret_cast (completion_key)); + + // No locking is needed here as no state changes. + ACE_HANDLE cp = ::CreateIoCompletionPort (handle, + this->completion_port_, + comp_key, + this->number_of_threads_); + if (cp == 0) + { + ACE_OS::set_errno_to_last_error (); + // If errno == ERROR_INVALID_PARAMETER, then this handle was + // already registered. + if (errno != ERROR_INVALID_PARAMETER) + { + if (ACE::debug ()) + { + ACE_DEBUG ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("CreateIoCompletionPort"))); + } + return -1; + } + } + return 0; +} + +ACE_Asynch_Read_Stream_Impl * +ACE_WIN32_Proactor::create_asynch_read_stream (void) +{ + ACE_Asynch_Read_Stream_Impl *implementation = 0; + ACE_NEW_RETURN (implementation, + ACE_WIN32_Asynch_Read_Stream (this), + 0); + return implementation; +} + +ACE_Asynch_Write_Stream_Impl * +ACE_WIN32_Proactor::create_asynch_write_stream (void) +{ + ACE_Asynch_Write_Stream_Impl *implementation = 0; + ACE_NEW_RETURN (implementation, + ACE_WIN32_Asynch_Write_Stream (this), + 0); + return implementation; +} + +ACE_Asynch_Read_Dgram_Impl * +ACE_WIN32_Proactor::create_asynch_read_dgram (void) +{ + ACE_Asynch_Read_Dgram_Impl *implementation = 0; + ACE_NEW_RETURN (implementation, + ACE_WIN32_Asynch_Read_Dgram (this), + 0); + return implementation; +} + +ACE_Asynch_Write_Dgram_Impl * +ACE_WIN32_Proactor::create_asynch_write_dgram (void) +{ + ACE_Asynch_Write_Dgram_Impl *implementation = 0; + ACE_NEW_RETURN (implementation, + ACE_WIN32_Asynch_Write_Dgram (this), + 0); + return implementation; +} + +ACE_Asynch_Read_File_Impl * +ACE_WIN32_Proactor::create_asynch_read_file (void) +{ + ACE_Asynch_Read_File_Impl *implementation = 0; + ACE_NEW_RETURN (implementation, + ACE_WIN32_Asynch_Read_File (this), + 0); + return implementation; +} + +ACE_Asynch_Write_File_Impl * +ACE_WIN32_Proactor::create_asynch_write_file (void) +{ + ACE_Asynch_Write_File_Impl *implementation = 0; + ACE_NEW_RETURN (implementation, + ACE_WIN32_Asynch_Write_File (this), + 0); + return implementation; +} + +ACE_Asynch_Accept_Impl * +ACE_WIN32_Proactor::create_asynch_accept (void) +{ + ACE_Asynch_Accept_Impl *implementation = 0; + ACE_NEW_RETURN (implementation, + ACE_WIN32_Asynch_Accept (this), + 0); + return implementation; +} + +ACE_Asynch_Connect_Impl * +ACE_WIN32_Proactor::create_asynch_connect (void) +{ + ACE_Asynch_Connect_Impl *implementation = 0; + ACE_NEW_RETURN (implementation, + ACE_WIN32_Asynch_Connect (this), + 0); + return implementation; +} + +ACE_Asynch_Transmit_File_Impl * +ACE_WIN32_Proactor::create_asynch_transmit_file (void) +{ + ACE_Asynch_Transmit_File_Impl *implementation = 0; + ACE_NEW_RETURN (implementation, + ACE_WIN32_Asynch_Transmit_File (this), + 0); + return implementation; +} + +ACE_Asynch_Read_Stream_Result_Impl * +ACE_WIN32_Proactor::create_asynch_read_stream_result + (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + ACE_Message_Block &message_block, + size_t bytes_to_read, + const void* act, + ACE_HANDLE event, + int priority, + int signal_number) +{ + ACE_Asynch_Read_Stream_Result_Impl *implementation = 0; + ACE_NEW_RETURN (implementation, + ACE_WIN32_Asynch_Read_Stream_Result (handler_proxy, + handle, + message_block, + bytes_to_read, + act, + event, + priority, + signal_number), + 0); + return implementation; +} + +ACE_Asynch_Write_Stream_Result_Impl * +ACE_WIN32_Proactor::create_asynch_write_stream_result + (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + ACE_Message_Block &message_block, + size_t bytes_to_write, + const void* act, + ACE_HANDLE event, + int priority, + int signal_number) +{ + ACE_Asynch_Write_Stream_Result_Impl *implementation = 0; + ACE_NEW_RETURN (implementation, + ACE_WIN32_Asynch_Write_Stream_Result (handler_proxy, + handle, + message_block, + bytes_to_write, + act, + event, + priority, + signal_number), + 0); + return implementation; +} + +ACE_Asynch_Read_File_Result_Impl * +ACE_WIN32_Proactor::create_asynch_read_file_result + (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + ACE_Message_Block &message_block, + size_t bytes_to_read, + const void* act, + u_long offset, + u_long offset_high, + ACE_HANDLE event, + int priority, + int signal_number) +{ + ACE_Asynch_Read_File_Result_Impl *implementation = 0; + ACE_NEW_RETURN (implementation, + ACE_WIN32_Asynch_Read_File_Result (handler_proxy, + handle, + message_block, + bytes_to_read, + act, + offset, + offset_high, + event, + priority, + signal_number), + 0); + return implementation; +} + +ACE_Asynch_Write_File_Result_Impl * +ACE_WIN32_Proactor::create_asynch_write_file_result + (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + ACE_Message_Block &message_block, + size_t bytes_to_write, + const void* act, + u_long offset, + u_long offset_high, + ACE_HANDLE event, + int priority, + int signal_number) +{ + ACE_Asynch_Write_File_Result_Impl *implementation = 0; + ACE_NEW_RETURN (implementation, + ACE_WIN32_Asynch_Write_File_Result (handler_proxy, + handle, + message_block, + bytes_to_write, + act, + offset, + offset_high, + event, + priority, + signal_number), + 0); + return implementation; +} + +ACE_Asynch_Read_Dgram_Result_Impl * +ACE_WIN32_Proactor::create_asynch_read_dgram_result + (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + ACE_Message_Block *message_block, + size_t bytes_to_read, + int flags, + int protocol_family, + const void* act, + ACE_HANDLE event, + int priority, + int signal_number) +{ + ACE_Asynch_Read_Dgram_Result_Impl *implementation = 0; + ACE_NEW_RETURN (implementation, + ACE_WIN32_Asynch_Read_Dgram_Result (handler_proxy, + handle, + message_block, + bytes_to_read, + flags, + protocol_family, + act, + event, + priority, + signal_number), + 0); + return implementation; +} + +ACE_Asynch_Write_Dgram_Result_Impl * +ACE_WIN32_Proactor::create_asynch_write_dgram_result + (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + ACE_Message_Block *message_block, + size_t bytes_to_read, + int flags, + const void* act, + ACE_HANDLE event, + int priority, + int signal_number) +{ + ACE_Asynch_Write_Dgram_Result_Impl *implementation = 0; + ACE_NEW_RETURN (implementation, + ACE_WIN32_Asynch_Write_Dgram_Result(handler_proxy, + handle, + message_block, + bytes_to_read, + flags, + act, + event, + priority, + signal_number), + 0); + return implementation; +} + +ACE_Asynch_Accept_Result_Impl * +ACE_WIN32_Proactor::create_asynch_accept_result + (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE listen_handle, + ACE_HANDLE accept_handle, + ACE_Message_Block &message_block, + size_t bytes_to_read, + const void* act, + ACE_HANDLE event, + int priority, + int signal_number) +{ + ACE_Asynch_Accept_Result_Impl *implementation = 0; + ACE_NEW_RETURN (implementation, + ACE_WIN32_Asynch_Accept_Result (handler_proxy, + listen_handle, + accept_handle, + message_block, + bytes_to_read, + act, + event, + priority, + signal_number), + 0); + return implementation; +} + +ACE_Asynch_Connect_Result_Impl * +ACE_WIN32_Proactor::create_asynch_connect_result + (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE connect_handle, + const void *act, + ACE_HANDLE event, + int priority, + int signal_number) +{ + ACE_Asynch_Connect_Result_Impl *implementation = 0; + ACE_NEW_RETURN (implementation, + ACE_WIN32_Asynch_Connect_Result (handler_proxy, + connect_handle, + act, + event, + priority, + signal_number), + 0); + return implementation; +} + +ACE_Asynch_Transmit_File_Result_Impl * +ACE_WIN32_Proactor::create_asynch_transmit_file_result + (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE socket, + ACE_HANDLE file, + ACE_Asynch_Transmit_File::Header_And_Trailer *header_and_trailer, + size_t bytes_to_write, + u_long offset, + u_long offset_high, + size_t bytes_per_send, + u_long flags, + const void *act, + ACE_HANDLE event, + int priority, + int signal_number) +{ + ACE_Asynch_Transmit_File_Result_Impl *implementation = 0; + ACE_NEW_RETURN (implementation, + ACE_WIN32_Asynch_Transmit_File_Result (handler_proxy, + socket, + file, + header_and_trailer, + bytes_to_write, + offset, + offset_high, + bytes_per_send, + flags, + act, + event, + priority, + signal_number), + 0); + return implementation; +} + +ACE_Asynch_Result_Impl * +ACE_WIN32_Proactor::create_asynch_timer (const ACE_Handler::Proxy_Ptr &handler_proxy, + const void *act, + const ACE_Time_Value &tv, + ACE_HANDLE event, + int priority, + int signal_number) +{ + ACE_Asynch_Result_Impl *implementation = 0; + ACE_NEW_RETURN (implementation, + ACE_WIN32_Asynch_Timer (handler_proxy, + act, + tv, + event, + priority, + signal_number), + 0); + return implementation; +} + +int +ACE_WIN32_Proactor::handle_signal (int, siginfo_t *, ucontext_t *) +{ + // Perform a non-blocking "poll" for all the I/O events that have + // completed in the I/O completion queue. + + int result = 0; + + for (ACE_Time_Value timeout (0, 0); + ; + ) + { + result = this->handle_events (timeout); + + if (result != 1) + break; + } + + // If our handle_events failed, we'll report a failure to the + // Reactor. + return result == -1 ? -1 : 0; +} + +int +ACE_WIN32_Proactor::handle_close (ACE_HANDLE handle, + ACE_Reactor_Mask close_mask) +{ + ACE_UNUSED_ARG (close_mask); + ACE_UNUSED_ARG (handle); + + return this->close (); +} + +ACE_HANDLE +ACE_WIN32_Proactor::get_handle (void) const +{ + if (this->used_with_reactor_event_loop_) + return this->event_.handle (); + else + return 0; +} + +int +ACE_WIN32_Proactor::handle_events (ACE_Time_Value &wait_time) +{ + // Decrement with the amount of time spent in the method + ACE_Countdown_Time countdown (&wait_time); + return this->handle_events (wait_time.msec ()); +} + +int +ACE_WIN32_Proactor::handle_events (void) +{ + return this->handle_events (ACE_INFINITE); +} + +int +ACE_WIN32_Proactor::handle_events (unsigned long milli_seconds) +{ + ACE_OVERLAPPED *overlapped = 0; + u_long bytes_transferred = 0; + ULONG_PTR completion_key = 0; + + // Get the next asynchronous operation that completes + BOOL result = ::GetQueuedCompletionStatus (this->completion_port_, + &bytes_transferred, + &completion_key, + &overlapped, + milli_seconds); + if (result == FALSE && overlapped == 0) + { + ACE_OS::set_errno_to_last_error (); + + switch (errno) + { + case WAIT_TIMEOUT: + errno = ETIME; + return 0; + + case ERROR_SUCCESS: + // Calling GetQueuedCompletionStatus with timeout value 0 + // returns FALSE with extended errno "ERROR_SUCCESS" errno = + // ETIME; ?? I don't know if this has to be done !! + return 0; + + default: + if (ACE::debug ()) + ACE_DEBUG ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("GetQueuedCompletionStatus"))); + return -1; + } + } + else if (overlapped != 0) + { + // Narrow the result. + ACE_WIN32_Asynch_Result *asynch_result = (ACE_WIN32_Asynch_Result *) overlapped; + + // If errors happen, grab the error. + if (result == FALSE) + ACE_OS::set_errno_to_last_error (); + else + errno = 0; + + u_long result_err = asynch_result->error (); + + // if "result_err" is 0 than + // It is normal OS/WIN32 AIO completion. + // We have cleared asynch_result->error_ + // during shared_read/shared_write. + // The real error code is already stored in "errno", + // so copy "errno" value to the "result_err" + // and pass this "result_err" code + // to the application_specific_code () + // else + // "result_err" non zero + // it means we have "post_completed" result + // so pass this "result_err" code + // to the application_specific_code () + + if (result_err == 0) + result_err = errno ; + + this->application_specific_code (asynch_result, + static_cast (bytes_transferred), + (void *) completion_key, + result_err); + } + return 1; +} + +void +ACE_WIN32_Proactor::application_specific_code (ACE_WIN32_Asynch_Result *asynch_result, + size_t bytes_transferred, + const void *completion_key, + u_long error) +{ + ACE_SEH_TRY + { + // Call completion hook + asynch_result->complete (bytes_transferred, + error ? 0 : 1, + (void *) completion_key, + error); + } + ACE_SEH_FINALLY + { + // This is crucial to prevent memory leaks + delete asynch_result; + } +} + +int +ACE_WIN32_Proactor::post_completion (ACE_WIN32_Asynch_Result *result) +{ + // Grab the event associated with the Proactor + HANDLE handle = this->get_handle (); + + // pass + // bytes_transferred + // completion_key + // to the ::PostQueuedCompletionStatus() + // error will be extracted later in handle_events() + + DWORD bytes_transferred = 0; + const void * completion_key = 0 ; + + if (result != 0) + { + // This cast is ok since the original API calls restricted the transfer + // counts to DWORD range. + bytes_transferred = static_cast (result->bytes_transferred ()); + completion_key = result->completion_key(); + } + + ULONG_PTR comp_key (reinterpret_cast (completion_key)); + + // Post a completion + if (::PostQueuedCompletionStatus (this->completion_port_, // completion port + bytes_transferred, // xfer count + comp_key, // completion key + result // overlapped + ) == FALSE) + { + delete result; + + if (ACE::debug ()) + { + ACE_DEBUG ((LM_ERROR, + ACE_TEXT ("%p\n"), + ACE_TEXT ("PostQueuedCompletionStatus failed"))); + } + return -1; + } + + // If Proactor event is valid, signal it + if (handle != ACE_INVALID_HANDLE + && handle != 0) + ACE_OS::event_signal (&handle); + + return 0; +} + +int +ACE_WIN32_Proactor::post_wakeup_completions (int how_many) +{ + ACE_WIN32_Wakeup_Completion *wakeup_completion = 0; + + for (ssize_t ci = 0; ci < how_many; ci++) + { + ACE_NEW_RETURN + (wakeup_completion, + ACE_WIN32_Wakeup_Completion (this->wakeup_handler_.proxy ()), + -1); + + if (wakeup_completion->post_completion (this) == -1) + return -1; + } + + return 0; +} + +int +ACE_WIN32_Proactor::wake_up_dispatch_threads (void) +{ + return 0; +} + +int +ACE_WIN32_Proactor::close_dispatch_threads (int) +{ + return 0; +} + +size_t +ACE_WIN32_Proactor::number_of_threads (void) const +{ + return static_cast (this->number_of_threads_); +} + +void +ACE_WIN32_Proactor::number_of_threads (size_t threads) +{ + this->number_of_threads_ = static_cast (threads); +} + +ACE_WIN32_Asynch_Timer::ACE_WIN32_Asynch_Timer + (const ACE_Handler::Proxy_Ptr &handler_proxy, + const void *act, + const ACE_Time_Value &tv, + ACE_HANDLE event, + int priority, + int signal_number) + : ACE_Asynch_Result_Impl (), + ACE_WIN32_Asynch_Result (handler_proxy, act, event, 0, 0, priority, + signal_number), + time_ (tv) +{ +} + +void +ACE_WIN32_Asynch_Timer::complete (size_t, + int, + const void *, + u_long) +{ + ACE_Handler *handler = this->handler_proxy_.get ()->handler (); + if (handler != 0) + handler->handle_time_out (this->time_, this->act ()); +} + +ACE_WIN32_Wakeup_Completion::ACE_WIN32_Wakeup_Completion + (ACE_Handler::Proxy_Ptr &handler_proxy, + const void *act, + ACE_HANDLE event, + int priority, + int signal_number) + : ACE_Asynch_Result_Impl (), + ACE_WIN32_Asynch_Result + (handler_proxy, act, event, 0, 0, priority, signal_number) +{ +} + +ACE_WIN32_Wakeup_Completion::~ACE_WIN32_Wakeup_Completion (void) +{ +} + +void +ACE_WIN32_Wakeup_Completion::complete (size_t /* bytes_transferred */, + int /* success */, + const void * /* completion_key */, + u_long /* error */) +{ + ACE_Handler *handler = this->handler_proxy_.get ()->handler (); + if (handler != 0) + handler->handle_wakeup (); +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_WIN32 */ diff --git a/dep/acelite/ace/WIN32_Proactor.h b/dep/acelite/ace/WIN32_Proactor.h new file mode 100644 index 00000000000..4fb686d7a7e --- /dev/null +++ b/dep/acelite/ace/WIN32_Proactor.h @@ -0,0 +1,325 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file WIN32_Proactor.h + * + * $Id: WIN32_Proactor.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Irfan Pyarali (irfan@cs.wustl.edu) + * @author Tim Harrison (harrison@cs.wustl.edu) + * @author Alexander Babu Arulanthu + * @author Roger Tragin + * @author Alexander Libman + */ +//============================================================================= + +#ifndef ACE_WIN32_PROACTOR_H +#define ACE_WIN32_PROACTOR_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +#pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_WIN32) && defined (ACE_HAS_WIN32_OVERLAPPED_IO) +// WIN32 implementation of the Proactor. + +#include "ace/WIN32_Asynch_IO.h" +#include "ace/Event_Handler.h" + +#include "ace/Proactor_Impl.h" +#include "ace/Asynch_Pseudo_Task.h" +#include "ace/Auto_Event.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Forward declarations. +class ACE_WIN32_Asynch_Result; +class ACE_WIN32_Proactor_Timer_Handler; + +/** + * @class ACE_WIN32_Proactor + * + * @brief A manager for asynchronous event demultiplexing on Win32. + * + * See the Proactor pattern description at + * http://www.cs.wustl.edu/~schmidt/PDF/proactor.pdf for more + * details. + */ +class ACE_Export ACE_WIN32_Proactor : public ACE_Proactor_Impl +{ + friend class ACE_WIN32_Asynch_Connect; + +public: + /// A do nothing constructor. + ACE_WIN32_Proactor (size_t number_of_threads = 0, + bool used_with_reactor_event_loop = false); + + /// Virtual destruction. + virtual ~ACE_WIN32_Proactor (void); + + /// Close the IO completion port. + virtual int close (void); + + /// This method adds the @a handle to the I/O completion port. This + /// function is a no-op function for Unix systems. + virtual int register_handle (ACE_HANDLE handle, + const void *completion_key); + + /** + * Dispatch a single set of events. If @a wait_time elapses before + * any events occur, return 0. Return 1 on success i.e., when a + * completion is dispatched, non-zero (-1) on errors and errno is + * set accordingly. + */ + virtual int handle_events (ACE_Time_Value &wait_time); + + /** + * Block indefinitely until at least one event is dispatched. + * Dispatch a single set of events. Return 1 on success i.e., when a + * completion is dispatched, non-zero (-1) on errors and errno is + * set accordingly. + */ + virtual int handle_events (void); + + /** + * Post a result to the completion port of the Proactor. If errors + * occur, the result will be deleted by this method. If successful, + * the result will be deleted by the Proactor when the result is + * removed from the completion port. Therefore, the result should + * have been dynamically allocated and should be orphaned by the + * user once this method is called. + */ + virtual int post_completion (ACE_WIN32_Asynch_Result *result); + + /// Add wakeup dispatch threads (reinit). + int wake_up_dispatch_threads (void); + + /// Close all dispatch threads. + int close_dispatch_threads (int wait); + + /// Get number of thread used as a parameter to @c CreateIoCompletionPort. + size_t number_of_threads (void) const; + + /// Set number of thread used as a parameter to @c CreateIoCompletionPort. + void number_of_threads (size_t threads); + + /// Get the event handle. + virtual ACE_HANDLE get_handle (void) const; + + virtual ACE_Asynch_Read_Stream_Impl *create_asynch_read_stream (void); + virtual ACE_Asynch_Write_Stream_Impl *create_asynch_write_stream (void); + virtual ACE_Asynch_Read_File_Impl *create_asynch_read_file (void); + virtual ACE_Asynch_Write_File_Impl *create_asynch_write_file (void); + virtual ACE_Asynch_Read_Dgram_Impl *create_asynch_read_dgram (void); + virtual ACE_Asynch_Write_Dgram_Impl *create_asynch_write_dgram (void); + virtual ACE_Asynch_Accept_Impl *create_asynch_accept (void); + virtual ACE_Asynch_Connect_Impl *create_asynch_connect (void); + virtual ACE_Asynch_Transmit_File_Impl *create_asynch_transmit_file (void); + + // Methods used to create Asynch_IO_Result objects. We create the right + // objects here in these methods. + + virtual ACE_Asynch_Read_Stream_Result_Impl *create_asynch_read_stream_result (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + ACE_Message_Block &message_block, + size_t bytes_to_read, + const void* act, + ACE_HANDLE event, + int priority, + int signal_number = 0); + + virtual ACE_Asynch_Write_Stream_Result_Impl *create_asynch_write_stream_result (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + ACE_Message_Block &message_block, + size_t bytes_to_write, + const void* act, + ACE_HANDLE event, + int priority, + int signal_number = 0); + + virtual ACE_Asynch_Read_File_Result_Impl *create_asynch_read_file_result (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + ACE_Message_Block &message_block, + size_t bytes_to_read, + const void* act, + u_long offset, + u_long offset_high, + ACE_HANDLE event, + int priority, + int signal_number = 0); + + virtual ACE_Asynch_Write_File_Result_Impl *create_asynch_write_file_result (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + ACE_Message_Block &message_block, + size_t bytes_to_write, + const void* act, + u_long offset, + u_long offset_high, + ACE_HANDLE event, + int priority, + int signal_number = 0); + + /// Create the correct implementation class for ACE_Asynch_Read_Dgram::Result. + virtual ACE_Asynch_Read_Dgram_Result_Impl *create_asynch_read_dgram_result (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + ACE_Message_Block *message_block, + size_t bytes_to_read, + int flags, + int protocol_family, + const void* act, + ACE_HANDLE event, + int priority, + int signal_number = 0); + + /// Create the correct implementation class for ACE_Asynch_Write_Dgram::Result. + virtual ACE_Asynch_Write_Dgram_Result_Impl *create_asynch_write_dgram_result (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE handle, + ACE_Message_Block *message_block, + size_t bytes_to_write, + int flags, + const void* act, + ACE_HANDLE event, + int priority, + int signal_number = 0); + + virtual ACE_Asynch_Accept_Result_Impl *create_asynch_accept_result (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE listen_handle, + ACE_HANDLE accept_handle, + ACE_Message_Block &message_block, + size_t bytes_to_read, + const void* act, + ACE_HANDLE event, + int priority, + int signal_number = 0); + + virtual ACE_Asynch_Connect_Result_Impl *create_asynch_connect_result (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE connect_handle, + const void *act, + ACE_HANDLE event, + int priority, + int signal_number = 0); + + + virtual ACE_Asynch_Transmit_File_Result_Impl *create_asynch_transmit_file_result (const ACE_Handler::Proxy_Ptr &handler_proxy, + ACE_HANDLE socket, + ACE_HANDLE file, + ACE_Asynch_Transmit_File::Header_And_Trailer *header_and_trailer, + size_t bytes_to_write, + u_long offset, + u_long offset_high, + size_t bytes_per_send, + u_long flags, + const void *act, + ACE_HANDLE event, + int priority, + int signal_number = 0); + + /// Create a timer result object which can be used with the Timer + /// mechanism of the Proactor. + virtual ACE_Asynch_Result_Impl *create_asynch_timer (const ACE_Handler::Proxy_Ptr &handler_proxy, + const void *act, + const ACE_Time_Value &tv, + ACE_HANDLE event, + int priority, + int signal_number = 0); + +protected: + /// Task to process pseudo-asynchronous operations + ACE_Asynch_Pseudo_Task & get_asynch_pseudo_task (void); + + /// Called when object is signaled by OS (either via UNIX signals or + /// when a Win32 object becomes signaled). + virtual int handle_signal (int signum, siginfo_t * = 0, ucontext_t * = 0); + + /// Called when object is removed from the ACE_Reactor. + virtual int handle_close (ACE_HANDLE handle, + ACE_Reactor_Mask close_mask); + + /** + * Dispatch a single set of events. If @a milli_seconds elapses + * before any events occur, return 0. Return 1 if a completion is + * dispatched. Return -1 on errors. + */ + virtual int handle_events (unsigned long milli_seconds); + + /// Protect against structured exceptions caused by user code when + /// dispatching handles. + void application_specific_code (ACE_WIN32_Asynch_Result *asynch_result, + size_t bytes_transferred, + const void *completion_key, + u_long error); + + /** + * Post @a how_many completions to the completion port so that all + * threads can wake up. This is used in conjunction with the + * run_event_loop(). + */ + virtual int post_wakeup_completions (int how_many); + + /// Handle for the completion port. Unix doesnt have completion + /// ports. + ACE_HANDLE completion_port_; + + /// This number is passed to the @c CreateIOCompletionPort system + /// call. + DWORD number_of_threads_; + + /// This event is used in conjunction with Reactor when we try to + /// integrate the event loops of Reactor and the Proactor. + ACE_Auto_Event event_; + + /// Flag that indicates whether we are used in conjunction with + /// Reactor. + bool const used_with_reactor_event_loop_; + + /// Handler to handle the wakeups. This works in conjunction with the + /// ACE_Proactor::run_event_loop(). + ACE_Handler wakeup_handler_; + + /// Pseudo-task for asynch connect ( NT/2000) + /// In future should removed in XP with ConnectEx support + ACE_Asynch_Pseudo_Task pseudo_task_; +}; + +/** + * @class ACE_WIN32_Asynch_Timer + * + * @brief This class is posted to the completion port when a timer + * expires. When the complete method of this object is + * called, the @a handler's handle_timeout method will be + * called. + */ +class ACE_WIN32_Asynch_Timer : public ACE_WIN32_Asynch_Result +{ + /// The factory method for this class is with the POSIX_Proactor + /// class. + friend class ACE_WIN32_Proactor; + +protected: + /// Constructor. + ACE_WIN32_Asynch_Timer (const ACE_Handler::Proxy_Ptr &handler_proxy, + const void *act, + const ACE_Time_Value &tv, + ACE_HANDLE event = ACE_INVALID_HANDLE, + int priority = 0, + int signal_number = 0); + + /// This method calls the @a handler's handle_timeout method. + virtual void complete (size_t bytes_transferred, + int success, + const void *completion_key, + u_long error = 0); + + /// Time value requested by caller + ACE_Time_Value time_; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_WIN32 */ +#include /**/ "ace/post.h" +#endif /* ACE_PROACTOR_H */ diff --git a/dep/acelite/ace/XML_Svc_Conf.cpp b/dep/acelite/ace/XML_Svc_Conf.cpp new file mode 100644 index 00000000000..23dddad8469 --- /dev/null +++ b/dep/acelite/ace/XML_Svc_Conf.cpp @@ -0,0 +1,15 @@ +// $Id: XML_Svc_Conf.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/XML_Svc_Conf.h" + +#if (ACE_USES_CLASSIC_SVC_CONF == 0) + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_XML_Svc_Conf::~ACE_XML_Svc_Conf (void) +{ +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_USES_CLASSIC_SVC_CONF == 0 */ diff --git a/dep/acelite/ace/XML_Svc_Conf.h b/dep/acelite/ace/XML_Svc_Conf.h new file mode 100644 index 00000000000..883151e05d2 --- /dev/null +++ b/dep/acelite/ace/XML_Svc_Conf.h @@ -0,0 +1,65 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file XML_Svc_Conf.h + * + * $Id: XML_Svc_Conf.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Nanbor Wang + */ +//============================================================================= + + +#ifndef ACE_XML_SVC_CONF_H +#define ACE_XML_SVC_CONF_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/ACE_export.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if (ACE_USES_CLASSIC_SVC_CONF==0) + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_XML_Svc_Conf + * + * @brief This abstract class defines the common operations + * ACE_Service_Config expects when using the XML Service Config Parser. + * + * When implementing a concret XML_Svc_Conf class, be sure to overload + * the new/delete function so the dynamically created concret XML_Svc_Conf + * instance can be deleted from the original heap in the DLL/SO. The + * concret XML_Svc_Conf implementation will be put into a DLL/SO that + * ACE applications can link to dynamically using the ACE_DLL class. + * This DLL should include an operation as follow: + * + * extern "C" ACE_XML_Svc_Conf_Parser * _ACEXML_create_XML_Svc_Conf_Object (void); + * + * + */ + +class ACE_Export ACE_XML_Svc_Conf +{ +public: + typedef ACE_XML_Svc_Conf *(*Factory)(void); + + virtual ~ACE_XML_Svc_Conf (void) = 0; + + virtual int parse_file (const ACE_TCHAR file[]) = 0; + + virtual int parse_string (const ACE_TCHAR str[]) = 0; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_USES_CLASSIC_SVC_CONF == 0 */ + +#include /**/ "ace/post.h" + +#endif /* ACE_XML_SVC_CONF_H */ diff --git a/dep/acelite/ace/XTI_ATM_Mcast.cpp b/dep/acelite/ace/XTI_ATM_Mcast.cpp new file mode 100644 index 00000000000..503e3fea0e2 --- /dev/null +++ b/dep/acelite/ace/XTI_ATM_Mcast.cpp @@ -0,0 +1,70 @@ +// $Id: XTI_ATM_Mcast.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/XTI_ATM_Mcast.h" + +ACE_RCSID(ace, XTI_ATM_Mcast, "$Id: XTI_ATM_Mcast.cpp 80826 2008-03-04 14:51:23Z wotte $") + +#if defined (ACE_HAS_XTI_ATM) + +#if !defined (__ACE_INLINE__) +#include "ace/XTI_ATM_Mcast.inl" +#endif /* __ACE_INLINE__ */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_ALLOC_HOOK_DEFINE(ACE_XTI_ATM_Mcast) + +void +ACE_XTI_ATM_Mcast::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_XTI_ATM_Mcast::dump"); +#endif /* ACE_HAS_DUMP */ +} + +ACE_XTI_ATM_Mcast::ACE_XTI_ATM_Mcast (void) +{ + ACE_TRACE ("ACE_XTI_ATM_Mcast::ACE_XTI_ATM_Mcast"); +} + +// Add a leaf to the current connection (i.e., multicast). + +int +ACE_XTI_ATM_Mcast::add_leaf (ACE_TLI_Stream ¤t_stream, + const ACE_Addr &remote_sap, + ACE_INT32 leaf_id, + ACE_Time_Value *timeout) +{ + ACE_TRACE ("ACE_XTI_ATM_Mcast::add_leaf"); + + struct netbuf call_req; + memset(&call_req, 0, sizeof(call_req)); + call_req.len = remote_sap.get_size (); + call_req.buf = (char *)remote_sap.get_addr (); + + if (::t_addleaf(current_stream.get_handle(), + leaf_id, + &call_req) < 0) + { + // Check for asynchronous event + if (t_errno == TLOOK) + { + int const event = ACE_OS::t_look(current_stream.get_handle()); + if (event != TNODATA && event != T_DATA) + return -1; + else + // If this doesn't work for asynchronous calls we need to call + // the XTI/ATM t_rcvleafchange() function to check for t_addleaf + // completion. + return complete (current_stream, 0, timeout); + } + else + return -1; + } + + return 0; +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_XTI_ATM */ diff --git a/dep/acelite/ace/XTI_ATM_Mcast.h b/dep/acelite/ace/XTI_ATM_Mcast.h new file mode 100644 index 00000000000..bfdfa92c957 --- /dev/null +++ b/dep/acelite/ace/XTI_ATM_Mcast.h @@ -0,0 +1,137 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file XTI_ATM_Mcast.h + * + * $Id: XTI_ATM_Mcast.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Joe Hoffert + */ +//============================================================================= + + +#ifndef ACE_XTI_ATM_MCAST_H +#define ACE_XTI_ATM_MCAST_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +#pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_XTI_ATM) + +#include "ace/TLI_Connector.h" +#include "ace/ATM_Addr.h" + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_XTI_ATM_Mcast + * + * @brief Defines an active connection factory for the ACE_TLI C++ + * wrappers to support XTI/ATM multicast. + */ +class ACE_Export ACE_XTI_ATM_Mcast : public ACE_TLI_Connector +{ +public: + // = Initialization methods. + /// Default constructor. + ACE_XTI_ATM_Mcast (void); + + /** + * Actively connect and produce a @a new_stream if things go well. + * The @a remote_sap is the address that we are trying to connect + * with. The @a timeout is the amount of time to wait to connect. + * If it's 0 then we block indefinitely. If *timeout == {0, 0} then + * the connection is done using non-blocking mode. In this case, if + * the connection can't be made immediately the value of -1 is + * returned with @c errno == EWOULDBLOCK. If *timeout > {0, 0} then + * this is the amount of time to wait before timing out. If the + * time expires before the connection is made @c errno == ETIME. The + * @a local_sap is the value of local address to bind to. If it's + * the default value of ACE_Addr::sap_any then the user is letting + * the OS do the binding. If @a reuse_addr == 1 then the + * is reused, even if it hasn't been cleanedup yet. + */ + ACE_XTI_ATM_Mcast (ACE_TLI_Stream &new_stream, + const ACE_Addr &remote_sap, + ACE_Time_Value *timeout = 0, + const ACE_Addr &local_sap = ACE_Addr::sap_any, + int reuse_addr = 0, + int flags = O_RDWR, + int perms = 0, + const char device[] = ACE_XTI_ATM_DEVICE, + struct t_info *info = 0, + int rw_flag = 1, + struct netbuf *udata = 0, + struct netbuf *opt = 0); + + /** + * Actively connect and produce a @a new_stream if things go well. + * The @a remote_sap is the address that we are trying to connect + * with. The @a timeout is the amount of time to wait to connect. + * If it's 0 then we block indefinitely. If *timeout == {0, 0} then + * the connection is done using non-blocking mode. In this case, if + * the connection can't be made immediately the value of -1 is + * returned with @c errno == EWOULDBLOCK. If *timeout > {0, 0} then + * this is the amount of time to wait before timing out. If the + * time expires before the connection is made @c errno == ETIME. The + * @a local_sap is the value of local address to bind to. If it's + * the default value of ACE_Addr::sap_any then the user is letting + * the OS do the binding. If @a reuse_addr == 1 then the + * is reused, even if it hasn't been cleanedup yet. + */ + int connect (ACE_TLI_Stream &new_stream, + const ACE_Addr &remote_sap, + ACE_Time_Value *timeout = 0, + const ACE_Addr &local_sap = ACE_Addr::sap_any, + int reuse_addr = 0, + int flags = O_RDWR, + int perms = 0, + const char device[] = ACE_XTI_ATM_DEVICE, + struct t_info *info = 0, + int rw_flag = 1, + struct netbuf *udata = 0, + struct netbuf *opt = 0); + + /** + * Actively add a leaf to the currently connected stream (i.e., + * multicast). The @a remote_sap is the address of the leaf that we + * are trying to add. The @a timeout is the amount of time to wait to + * connect. If it's 0 then we block indefinitely. If *timeout == + * {0, 0} then the connection is done using non-blocking mode. In + * this case, if the connection can't be made immediately the value + * of -1 is returned with @c errno == EWOULDBLOCK. If *timeout > + * {0, 0} then this is the amount of time to wait before timing out. + * If the time expires before the connection is made @c errno == ETIME. + */ + int add_leaf (ACE_TLI_Stream ¤t_stream, + const ACE_Addr &remote_sap, + ACE_INT32 leaf_id, + ACE_Time_Value *timeout = 0); + + // = Meta-type info + typedef ACE_ATM_Addr PEER_ADDR; + typedef ACE_TLI_Stream PEER_STREAM; + + /// Dump the state of an object. + void dump (void) const; + + /// Declare the dynamic allocation hooks. + ACE_ALLOC_HOOK_DECLARE; +}; + +ACE_END_VERSIONED_NAMESPACE_DECL + +#if defined (__ACE_INLINE__) +#include "ace/XTI_ATM_Mcast.inl" +#endif /* __ACE_INLINE__ */ + +#endif /* ACE_HAS_XTI_ATM */ + +#include /**/ "ace/post.h" + +#endif /* ACE_XTI_ATM_MCAST_H */ diff --git a/dep/acelite/ace/XTI_ATM_Mcast.inl b/dep/acelite/ace/XTI_ATM_Mcast.inl new file mode 100644 index 00000000000..b182bb41b20 --- /dev/null +++ b/dep/acelite/ace/XTI_ATM_Mcast.inl @@ -0,0 +1,65 @@ +// -*- C++ -*- +// +// $Id: XTI_ATM_Mcast.inl 80826 2008-03-04 14:51:23Z wotte $ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +ACE_INLINE +ACE_XTI_ATM_Mcast::ACE_XTI_ATM_Mcast (ACE_TLI_Stream &new_stream, + const ACE_Addr &remote_sap, + ACE_Time_Value *timeout, + const ACE_Addr &local_sap, + int reuse_addr, + int flags, + int perms, + const char device[], + struct t_info *info, + int rw_flag, + struct netbuf *udata, + struct netbuf *opt) +{ + ACE_TRACE ("ACE_XTI_ATM_Mcast::ACE_XTI_ATM_Mcast"); + if (this->connect (new_stream, remote_sap, timeout, local_sap, reuse_addr, + flags, perms, device, + info, rw_flag, + udata, opt) == ACE_INVALID_HANDLE + && timeout != 0 && !(errno == EWOULDBLOCK || errno == ETIME)) + ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("ACE_TLI_Stream::ACE_TLI_Stream"))); +} + +// Connect the to the , waiting up to +// amount of time if necessary. This is simple a pass- +// through function to ACE_TLI_Connector::connect(). It is over- +// ridden to change the default device from TCP to XTI/ATM. + +ACE_INLINE +int +ACE_XTI_ATM_Mcast::connect (ACE_TLI_Stream &new_stream, + const ACE_Addr &remote_sap, + ACE_Time_Value *timeout, + const ACE_Addr &local_sap, + int reuse_addr, + int flags, + int perms, + const char device[], + struct t_info *info, + int rw_flag, + struct netbuf *udata, + struct netbuf *opt) +{ + ACE_TRACE ("ACE_XTI_ATM_Mcast::connect"); + return ACE_TLI_Connector::connect(new_stream, + remote_sap, + timeout, + local_sap, + reuse_addr, + flags, + perms, + device, + info, + rw_flag, + udata, + opt); +} + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/ace.rc b/dep/acelite/ace/ace.rc new file mode 100644 index 00000000000..54792491900 --- /dev/null +++ b/dep/acelite/ace/ace.rc @@ -0,0 +1,38 @@ +#include "Version.h" + +1 VERSIONINFO + FILEVERSION ACE_MAJOR_VERSION,ACE_MINOR_VERSION,ACE_BETA_VERSION,0 + PRODUCTVERSION ACE_MAJOR_VERSION,ACE_MINOR_VERSION,ACE_BETA_VERSION,0 + FILEFLAGSMASK 0x3fL + FILEFLAGS 0x0L + FILEOS 0x4L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904B0" + BEGIN + VALUE "FileDescription", "ACE\0" + VALUE "FileVersion", ACE_VERSION "\0" + VALUE "InternalName", "ACEDLL\0" + VALUE "LegalCopyright", "\0" + VALUE "LegalTrademarks", "\0" + VALUE "OriginalFilename", "ACE.DLL\0" + VALUE "ProductName", "ACE\0" + VALUE "ProductVersion", ACE_VERSION "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + +/* + * The following resource is used by the ACE logger to write messages + * to the NT event log. If you are statically linking to the ACE + * library, and you wish to use the NT event log, you should copy this + * message table to your application's resource script. + */ +1 MESSAGETABLE ace_message_table.bin diff --git a/dep/acelite/ace/ace_message_table.bin b/dep/acelite/ace/ace_message_table.bin new file mode 100644 index 00000000000..6ac08e5dc69 Binary files /dev/null and b/dep/acelite/ace/ace_message_table.bin differ diff --git a/dep/acelite/ace/ace_wchar.cpp b/dep/acelite/ace/ace_wchar.cpp new file mode 100644 index 00000000000..bec8255447d --- /dev/null +++ b/dep/acelite/ace/ace_wchar.cpp @@ -0,0 +1,17 @@ +// -*- C++ -*- +// +// $Id: ace_wchar.cpp 80826 2008-03-04 14:51:23Z wotte $ + +#include "ace/config-macros.h" +#include "ace/ace_wchar.h" + +ACE_RCSID(ace, ace_wchar, "$Id: ace_wchar.cpp 80826 2008-03-04 14:51:23Z wotte $") + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +#if defined(ACE_HAS_ICONV) +iconv_t ACE_Wide_To_Ascii::ACE_Wide_To_Ascii_iconv_env = 0; +iconv_t ACE_Ascii_To_Wide::ACE_Ascii_To_Wide_iconv_env = 0; +#endif + +ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/dep/acelite/ace/ace_wchar.h b/dep/acelite/ace/ace_wchar.h new file mode 100644 index 00000000000..f556e0f9cf8 --- /dev/null +++ b/dep/acelite/ace/ace_wchar.h @@ -0,0 +1,385 @@ +//* -*- C++ -*- */ + +//============================================================================= +/** + * @file ace_wchar.h + * + * $Id: ace_wchar.h 82441 2008-07-28 13:04:13Z johnnyw $ + * + * @author Darrell Brunsch + */ +//============================================================================= + +#ifndef ACE_WCHAR_H +#define ACE_WCHAR_H + +#include "ace/config-macros.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +// These macros have been deprecated and should be replaced by their +// ACE_TEXT_* equivalents. These macros are just hacks and may not +// completely provide the old functionality. +#if defined (ACE_LEGACY_MODE) +// Convert the old unicode indicators +# if defined (ACE_HAS_MOSTLY_UNICODE_APIS) +# define ACE_USES_WCHAR +# endif /* ACE_HAS_MOSTLY_UNICODE_APIS */ +# if defined (ACE_HAS_UNICODE) +# define ACE_HAS_WCHAR +# endif /* ACE_HAS_UNICODE */ + +// These are defined to get older stuff to compile +// FUZZ: disable check_for_tchar +# define ASYS_TCHAR ACE_TCHAR +# define ASYS_TEXT ACE_TEXT +# define ASYS_ONLY_MULTIBYTE_STRING ACE_TEXT_ALWAYS_CHAR +# define ASYS_MULTIBYTE_STRING ACE_TEXT_CHAR_TO_TCHAR +# define ASYS_WIDE_STRING ACE_TEXT_CHAR_TO_TCHAR +# define ACE_WIDE_STRING ACE_TEXT_CHAR_TO_TCHAR + +# if defined (ACE_USES_WCHAR) +# define ASYS_ONLY_WIDE_STRING(STRING) STRING +# else /* ACE_USES_WCHAR */ +# define ASYS_ONLY_WIDE_STRING(STRING) \ + ACE_Ascii_To_Wide (STRING).wchar_rep () +# endif /* ACE_USES_WCHAR */ + +# define ACE_TEXT_STRING ACE_TString + +#endif /* ACE_LEGACY_MODE */ + +#if defined (ACE_HAS_XPG4_MULTIBYTE_CHAR) +# if !defined (ACE_HAS_WCHAR) +# define ACE_HAS_WCHAR +# endif +# include /**/ +#endif /* ACE_HAS_XPG4_MULTIBYTE_CHAR */ + +#if defined (ACE_HAS_WCHAR) +# if defined (ACE_VXWORKS) +# include /**/ /* For wchar_t */ +# include /**/ /* For mbstowcs, etc. */ +# include /**/ /* For strlen */ +# if !defined (__RTP__) +# define wint_t unsigned int /* VxWorks has wchar_t but not wint_t */ +# else +# include /**/ +# include /**/ +# endif +# elif defined (ACE_OPENVMS) +# include /**/ +# include /**/ +# elif defined (ACE_HAS_STANDARD_CPP_LIBRARY) && \ + (ACE_HAS_STANDARD_CPP_LIBRARY != 0) +# include /**/ +# include /**/ +# elif defined (ACE_HAS_WINCE) +# include /**/ +# else +# include /**/ +# endif /* ACE_HAS_STANDARD_CPP_LIBRARY */ +#endif /* ACE_HAS_WCHAR */ + +#if defined (ACE_HAS_ICONV) +# include /**/ +# if !defined (ACE_MAX_ICONV_BUFFER) +# define ACE_MAX_ICONV_BUFFER 16*1024 +# endif +#endif /* ACE_HAS_ICONV */ + +#if defined (ACE_USES_STD_NAMESPACE_FOR_STDC_LIB) && \ + (ACE_USES_STD_NAMESPACE_FOR_STDC_LIB != 0) +using std::size_t; +#endif /* ACE_USES_STD_NAMESPACE_FOR_STDC_LIB */ + +// This makes the somewhat dubious assumption that if a platform lacks +// a native wchar_t type, then it will typedef it as unsigned short. +#if defined (ACE_HAS_WCHAR) && !defined (ACE_LACKS_NATIVE_WCHAR_T) +# if !defined (ACE_WSTRING_HAS_USHORT_SUPPORT) +# define ACE_WSTRING_HAS_USHORT_SUPPORT +# endif /* ACE_WSTRING_HAS_USHORT_SUPPORT */ +#endif /* ACE_HAS_WCHAR && !ACE_LACKS_NATIVE_WCHAR_T */ + +// Set the default behaviour for ACE_TEXT_WIDE to use the L-prefix +#if !defined (ACE_USES_L_PREFIX) +# define ACE_USES_L_PREFIX 1 +#endif /* ACE_USES_L_PREFIX */ + +// Define the unicode/wchar related macros correctly + +# if !defined (ACE_TEXT_WIDE) +# if (ACE_USES_L_PREFIX == 1) +# define ACE_TEXT_WIDE_I(STRING) L##STRING +# else /* ACE_USES_L_PREFIX */ +# define ACE_TEXT_WIDE_I(STRING) STRING +# endif /* ACE_USES_L_PREFIX */ +# define ACE_TEXT_WIDE(STRING) ACE_TEXT_WIDE_I (STRING) +# endif /* ACE_TEXT_WIDE */ + +#if defined (ACE_USES_WCHAR) +typedef wchar_t ACE_TCHAR; +typedef char ACE_ANTI_TCHAR; +# define ACE_TEXT(STRING) ACE_TEXT_WIDE (STRING) +# if !defined (ACE_LACKS_DEPRECATED_MACROS) +# define ACE_LIB_TEXT(STRING) ACE_TEXT_WIDE (STRING) +# endif +# define ACE_TEXT_ALWAYS_CHAR(STRING) ACE_Wide_To_Ascii (STRING).char_rep () +# define ACE_TEXT_ALWAYS_WCHAR(STRING) STRING +# define ACE_TEXT_CHAR_TO_TCHAR(STRING) ACE_Ascii_To_Wide (STRING).wchar_rep () +# define ACE_TEXT_WCHAR_TO_TCHAR(STRING) STRING +# define ACE_TEXT_ANTI_TO_TCHAR(STRING) ACE_Ascii_To_Wide (STRING).wchar_rep () +#else /* ACE_USES_WCHAR */ +typedef char ACE_TCHAR; +typedef wchar_t ACE_ANTI_TCHAR; +# define ACE_TEXT(STRING) STRING +# if !defined (ACE_LACKS_DEPRECATED_MACROS) +# define ACE_LIB_TEXT(STRING) STRING +# endif +# define ACE_TEXT_ALWAYS_CHAR(STRING) STRING +# define ACE_TEXT_ALWAYS_WCHAR(STRING) ACE_Ascii_To_Wide (STRING).wchar_rep () +# define ACE_TEXT_CHAR_TO_TCHAR(STRING) STRING +# define ACE_TEXT_WCHAR_TO_TCHAR(STRING) ACE_Wide_To_Ascii (STRING).char_rep () +# define ACE_TEXT_ANTI_TO_TCHAR(STRING) ACE_Wide_To_Ascii (STRING).char_rep () +#endif /* ACE_USES_WCHAR */ + +// The OS_String module defines some wide-char functions that are not +// universally available. In particular, they're not part of the +// XPG4 Worldwide Portability Interface wide-character string handling +// functions. So, if ACE_HAS_XPG4_MULTIBYTE_CHAR is defined, note that +// these functions are missing. +#if defined (ACE_HAS_XPG4_MULTIBYTE_CHAR) + +# if !defined (ACE_LACKS_ITOW) +# define ACE_LACKS_ITOW +# endif + +# if !defined (ACE_LACKS_WCSICMP) +# define ACE_LACKS_WCSICMP +# endif + +# if !defined (ACE_LACKS_WCSNICMP) +# define ACE_LACKS_WCSNICMP +# endif + +# if !defined (ACE_LACKS_WCSDUP) +# define ACE_LACKS_WCSDUP +# endif + +#endif /* ACE_HAS_XPG4_MULTIBYTE_CHAR */ + +#if defined ACE_HAS_WCHAR + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +/** + * @class ACE_Wide_To_Ascii + * + * @brief A lightweight wchar* to char* string conversion class. + * + * The purpose of this class is to perform conversion from + * wchar* to char* strings. It is not intended for general + * purpose use. + */ +class ACE_Wide_To_Ascii +{ +public: + /// Ctor must take a wchar string. + ACE_Wide_To_Ascii (const wchar_t *s); + + /// Dtor will free up the memory. + ~ACE_Wide_To_Ascii (void); + + /// Return the internal char* representation. + char *char_rep (void); + + /// Converts an wchar_t string to ascii and returns a new string. + static char *convert (const wchar_t *wstr); + +private: + /// Internal pointer to the converted string. + char *s_; + +#if defined (ACE_HAS_ICONV) + static iconv_t ACE_Wide_To_Ascii_iconv_env; +#endif /* ACE_HAS_ICONV */ + + /// Disallow these operation. + ACE_Wide_To_Ascii (void); + ACE_Wide_To_Ascii (ACE_Wide_To_Ascii &); + ACE_Wide_To_Ascii& operator= (ACE_Wide_To_Ascii &); +}; + +/** + * @class ACE_Ascii_To_Wide + * + * @brief A lightweight char* to wchar* string conversion class. + * + * The purpose of this class is to perform conversion from + * char* to wchar* strings. It is not intended for general + * purpose use. + */ +class ACE_Ascii_To_Wide +{ +public: + /// Ctor must take a wchar string. + ACE_Ascii_To_Wide (const char *s); + + /// Dtor will free up the memory. + ~ACE_Ascii_To_Wide (void); + + /// Return the internal wchar* representation. + wchar_t *wchar_rep (void); + + /// Converts an char string to unicode/wide and returns a new string. + static wchar_t *convert (const char *str); + +private: + /// Internal pointer to the converted string. + wchar_t *s_; + +#if defined (ACE_HAS_ICONV) + static iconv_t ACE_Ascii_To_Wide_iconv_env; +#endif /* ACE_HAS_ICONV */ + + /// Disallow these operation. + ACE_Ascii_To_Wide (void); + ACE_Ascii_To_Wide (ACE_Ascii_To_Wide &); + ACE_Ascii_To_Wide operator= (ACE_Ascii_To_Wide &); +}; + +#if defined (ACE_LEGACY_MODE) +typedef ACE_Ascii_To_Wide ACE_OS_CString; +typedef ACE_Wide_To_Ascii ACE_OS_WString; +#endif /* ACE_LEGACY_MODE */ + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_WCHAR */ + +#if defined (ACE_WIN32) +#if defined (ACE_USES_WCHAR) +#define ACE_LPSTR LPWSTR +#define ACE_TEXT_SERVICE_TABLE_ENTRY SERVICE_TABLE_ENTRYW +#define ACE_TEXT_STARTUPINFO STARTUPINFOW +#define ACE_TEXT_WIN32_FIND_DATA WIN32_FIND_DATAW +#define ACE_TEXT_OSVERSIONINFO OSVERSIONINFOW +#define ACE_TEXT_EXPLICIT_ACCESS EXPLICIT_ACCESS_W + +#define ACE_TEXT_CreateEvent ::CreateEventW +#define ACE_TEXT_CreateFile ::CreateFileW +#define ACE_TEXT_CreateFileMapping ::CreateFileMappingW +#define ACE_TEXT_CreateMutex ::CreateMutexW +#define ACE_TEXT_CreateProcess ::CreateProcessW +#define ACE_TEXT_CreateSemaphore ::CreateSemaphoreW +#define ACE_TEXT_CreateService ::CreateServiceW +#define ACE_TEXT_ExpandEnvironmentStrings ::ExpandEnvironmentStringsW +#define ACE_TEXT_FindFirstChangeNotification ::FindFirstChangeNotificationW +#define ACE_TEXT_FindFirstFile ::FindFirstFileW +#define ACE_TEXT_FindNextFile ::FindNextFileW +#define ACE_TEXT_FormatMessage ::FormatMessageW +#define ACE_TEXT_FreeEnvironmentStrings ::FreeEnvironmentStringsW +#define ACE_TEXT_GetComputerName ::GetComputerNameW +#define ACE_TEXT_GetEnvironmentStrings ::GetEnvironmentStringsW +#define ACE_TEXT_GetFileAttributes ::GetFileAttributesW +#define ACE_TEXT_GetModuleFileName ::GetModuleFileNameW +#define ACE_TEXT_GetTempPath ::GetTempPathW +#define ACE_TEXT_GetUserName ::GetUserNameW +#define ACE_TEXT_GetUserNameEx ::GetUserNameExW +#define ACE_TEXT_GetVersionEx ::GetVersionExW +#define ACE_TEXT_LoadLibrary ::LoadLibraryW +#define ACE_TEXT_MoveFileEx ::MoveFileExW +#define ACE_TEXT_WaitNamedPipe ::WaitNamedPipeW +#define ACE_TEXT_OpenFileMapping ::OpenFileMappingW +#define ACE_TEXT_OpenSCManager ::OpenSCManagerW +#define ACE_TEXT_OpenService ::OpenServiceW +#define ACE_TEXT_OutputDebugString ::OutputDebugStringW +#define ACE_TEXT_RegisterEventSource ::RegisterEventSourceW +#define ACE_TEXT_RegisterServiceCtrlHandler ::RegisterServiceCtrlHandlerW +#define ACE_TEXT_RegConnectRegistry ::RegConnectRegistryW +#define ACE_TEXT_RegCreateKeyEx ::RegCreateKeyExW +#define ACE_TEXT_RegDeleteKey ::RegDeleteKeyW +#define ACE_TEXT_RegDeleteValue ::RegDeleteValueW +#define ACE_TEXT_RegEnumKeyEx ::RegEnumKeyExW +#define ACE_TEXT_RegEnumValue ::RegEnumValueW +#define ACE_TEXT_RegCreateKey ::RegCreateKeyW +#define ACE_TEXT_RegOpenKey ::RegOpenKeyW +#define ACE_TEXT_RegOpenKeyEx ::RegOpenKeyExW +#define ACE_TEXT_RegQueryValueEx ::RegQueryValueExW +#define ACE_TEXT_RegSetValueEx ::RegSetValueExW +#define ACE_TEXT_ReportEvent ::ReportEventW +#define ACE_TEXT_SearchPath ::SearchPathW +#define ACE_TEXT_StartService ::StartServiceW +#define ACE_TEXT_StartServiceCtrlDispatcher ::StartServiceCtrlDispatcherW +#define ACE_TEXT_SetFileSecurity ::SetFileSecurityW +#define ACE_TEXT_SetEntriesInAcl ::SetEntriesInAclW +#define ACE_TEXT_PdhExpandCounterPath ::PdhExpandCounterPathW +#define ACE_TEXT_PdhOpenQuery ::PdhOpenQueryW +#define ACE_TEXT_PdhAddCounter ::PdhAddCounterW + +#else /* ACE_USES_WCHAR */ +#define ACE_LPSTR LPSTR +#define ACE_TEXT_SERVICE_TABLE_ENTRY SERVICE_TABLE_ENTRYA +#define ACE_TEXT_STARTUPINFO STARTUPINFOA +#define ACE_TEXT_WIN32_FIND_DATA WIN32_FIND_DATAA +#define ACE_TEXT_OSVERSIONINFO OSVERSIONINFOA +#define ACE_TEXT_EXPLICIT_ACCESS EXPLICIT_ACCESS_A + +#define ACE_TEXT_CreateEvent ::CreateEventA +#define ACE_TEXT_CreateFile ::CreateFileA +#define ACE_TEXT_CreateFileMapping ::CreateFileMappingA +#define ACE_TEXT_CreateMutex ::CreateMutexA +#define ACE_TEXT_CreateProcess ::CreateProcessA +#define ACE_TEXT_CreateSemaphore ::CreateSemaphoreA +#define ACE_TEXT_CreateService ::CreateServiceA +#define ACE_TEXT_ExpandEnvironmentStrings ::ExpandEnvironmentStringsA +#define ACE_TEXT_FindFirstChangeNotification ::FindFirstChangeNotificationA +#define ACE_TEXT_FindFirstFile ::FindFirstFileA +#define ACE_TEXT_FindNextFile ::FindNextFileA +#define ACE_TEXT_FormatMessage ::FormatMessageA +#define ACE_TEXT_FreeEnvironmentStrings ::FreeEnvironmentStringsA +#define ACE_TEXT_GetComputerName ::GetComputerNameA +#define ACE_TEXT_GetEnvironmentStrings ::GetEnvironmentStringsA +#define ACE_TEXT_GetFileAttributes ::GetFileAttributesA +#define ACE_TEXT_GetModuleFileName ::GetModuleFileNameA +#define ACE_TEXT_GetTempPath ::GetTempPathA +#define ACE_TEXT_GetUserName ::GetUserNameA +#define ACE_TEXT_GetUserNameEx ::GetUserNameExA +#define ACE_TEXT_GetVersionEx ::GetVersionExA +#define ACE_TEXT_LoadLibrary ::LoadLibraryA +#define ACE_TEXT_MoveFileEx ::MoveFileExA +#define ACE_TEXT_WaitNamedPipe ::WaitNamedPipeA +#define ACE_TEXT_OpenFileMapping ::OpenFileMappingA +#define ACE_TEXT_OpenSCManager ::OpenSCManagerA +#define ACE_TEXT_OpenService ::OpenServiceA +#define ACE_TEXT_OutputDebugString ::OutputDebugStringA +#define ACE_TEXT_RegisterEventSource ::RegisterEventSourceA +#define ACE_TEXT_RegisterServiceCtrlHandler ::RegisterServiceCtrlHandlerA +#define ACE_TEXT_RegConnectRegistry ::RegConnectRegistryA +#define ACE_TEXT_RegCreateKeyEx ::RegCreateKeyExA +#define ACE_TEXT_RegDeleteKey ::RegDeleteKeyA +#define ACE_TEXT_RegDeleteValue ::RegDeleteValueA +#define ACE_TEXT_RegEnumKeyEx ::RegEnumKeyExA +#define ACE_TEXT_RegEnumValue ::RegEnumValueA +#define ACE_TEXT_RegCreateKey ::RegCreateKeyA +#define ACE_TEXT_RegOpenKey ::RegOpenKeyA +#define ACE_TEXT_RegOpenKeyEx ::RegOpenKeyExA +#define ACE_TEXT_RegQueryValueEx ::RegQueryValueExA +#define ACE_TEXT_RegSetValueEx ::RegSetValueExA +#define ACE_TEXT_ReportEvent ::ReportEventA +#define ACE_TEXT_SearchPath ::SearchPathA +#define ACE_TEXT_StartService ::StartServiceA +#define ACE_TEXT_StartServiceCtrlDispatcher ::StartServiceCtrlDispatcherA +#define ACE_TEXT_SetFileSecurity ::SetFileSecurityA +#define ACE_TEXT_SetEntriesInAcl ::SetEntriesInAclA +#define ACE_TEXT_PdhExpandCounterPath ::PdhExpandCounterPathA +#define ACE_TEXT_PdhOpenQuery ::PdhOpenQueryA +#define ACE_TEXT_PdhAddCounter ::PdhAddCounterA +#endif /* ACE_USES_WCHAR */ +#endif /* ACE_WIN32 */ + +#include "ace/ace_wchar.inl" + +#endif /* ACE_WCHAR_H */ diff --git a/dep/acelite/ace/ace_wchar.inl b/dep/acelite/ace/ace_wchar.inl new file mode 100644 index 00000000000..744b44f5e73 --- /dev/null +++ b/dep/acelite/ace/ace_wchar.inl @@ -0,0 +1,183 @@ +// -*- C++ -*- +// +// $Id: ace_wchar.inl 80826 2008-03-04 14:51:23Z wotte $ + +// These are always inlined +// FUZZ: disable check_for_inline + +#if defined (ACE_HAS_WCHAR) + +#if !defined (ACE_WIN32) +# include /**/ // Need to see strlen() +#endif /* ACE_WIN32 */ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +inline +ACE_Wide_To_Ascii::~ACE_Wide_To_Ascii (void) +{ + delete [] this->s_; +} + +inline char * +ACE_Wide_To_Ascii::char_rep (void) +{ + return this->s_; +} + +inline char * +ACE_Wide_To_Ascii::convert (const wchar_t *wstr) +{ + // Short circuit null pointer case + if (wstr == 0) + return 0; + +# if defined (ACE_WIN32) + UINT const cp = GetACP (); // Codepage + int const len = ::WideCharToMultiByte (cp, + 0, + wstr, + -1, + 0, + 0, + 0, + 0); +# elif defined (ACE_LACKS_WCSLEN) + const wchar_t * wtemp = wstr; + while ((*wtemp) != 0) // Hopefully the string is null terminated! + ++wtemp; + + int const len = wtemp - wstr + 1; +# else /* ACE_WIN32 */ + size_t const len = ::wcslen (wstr) + 1; +# endif /* ACE_WIN32 */ + +#if !defined (ACE_HAS_ICONV) + char *str = new char[len]; +#endif + +# if defined (ACE_WIN32) + ::WideCharToMultiByte (cp, 0, wstr, -1, str, len, 0, 0); +# elif defined (ACE_VXWORKS) + ::wcstombs (str, wstr, len); +# elif defined (ACE_HAS_ICONV) + wchar_t * wstri = const_cast (wstr); + size_t lensi = ACE_MAX_ICONV_BUFFER; + size_t lenwi = len * sizeof(wchar_t); + char buf[ACE_MAX_ICONV_BUFFER]; + char *stri = buf; + + size_t hr = iconv (ACE_Wide_To_Ascii_iconv_env, (char**)&wstri, &lenwi, &stri, &lensi); + if ((hr==size_t(-1))||(lensi==ACE_MAX_ICONV_BUFFER)) + { + char *str=new char[len]; + for (size_t i = 0; i < len; i++) + { + wchar_t *t = const_cast (wstr); + str[i] = static_cast (*(t + i)); + } + + return str; + } + char *str = new char[ACE_MAX_ICONV_BUFFER-lensi]; + ::memcpy(str, buf, ACE_MAX_ICONV_BUFFER-lensi); +# else /* ACE_HAS_ICONV */ + for (size_t i = 0; i < len; ++i) + { + wchar_t *t = const_cast (wstr); + str[i] = static_cast (*(t + i)); + } +# endif /* ACE_WIN32 */ + return str; +} + +inline +ACE_Wide_To_Ascii::ACE_Wide_To_Ascii (const wchar_t *s) +{ +#if defined(ACE_HAS_ICONV) + if (ACE_Wide_To_Ascii_iconv_env == 0) + { + ACE_Wide_To_Ascii_iconv_env = iconv_open("", "WCHAR_T"); + } +#endif + s_ = ACE_Wide_To_Ascii::convert (s); +} + +inline +ACE_Ascii_To_Wide::~ACE_Ascii_To_Wide (void) +{ + delete [] this->s_; +} + +inline wchar_t * +ACE_Ascii_To_Wide::wchar_rep (void) +{ + return this->s_; +} + +inline wchar_t * +ACE_Ascii_To_Wide::convert (const char *str) +{ + // Short circuit null pointer case + if (str == 0) + return 0; + +# if defined (ACE_WIN32) + UINT const cp = GetACP (); // Codepage + int const len = ::MultiByteToWideChar (cp, 0, str, -1, 0, 0); +# else /* ACE_WIN32 */ + size_t const len = strlen (str) + 1; +# endif /* ACE_WIN32 */ + +#if !defined (ACE_HAS_ICONV) + wchar_t *wstr = new wchar_t[len]; +#endif + +# if defined (ACE_WIN32) + ::MultiByteToWideChar (cp, 0, str, -1, wstr, len); +# elif defined (ACE_VXWORKS) + ::mbstowcs (wstr, str, len); +# elif defined (ACE_HAS_ICONV) /* ACE_VXWORKS */ + char *stri = const_cast(str); + size_t lensi = len; + size_t lenwi = ACE_MAX_ICONV_BUFFER; + wchar_t buf[ACE_MAX_ICONV_BUFFER/sizeof(wchar_t)]; + wchar_t *wstri=buf; + + size_t hr=iconv(ACE_Ascii_To_Wide_iconv_env, &stri, &lensi, (char**)&wstri, &lenwi); + if((hr==size_t(-1))||(lenwi==ACE_MAX_ICONV_BUFFER)){ + wchar_t *wstr=new wchar_t[len*sizeof(wchar_t)]; + for (size_t i = 0; i < len; i++){ + char *t = const_cast (str); + wstr[i] = static_cast (*((unsigned char*)t + i)); + } + + return wstr; + } + wchar_t *wstr=new wchar_t[(ACE_MAX_ICONV_BUFFER-lenwi)/sizeof(wchar_t)]; + ::memcpy(wstr,buf,ACE_MAX_ICONV_BUFFER-lenwi); +# else /* ACE_HAS_ICONV */ + for (size_t i = 0; i < len; ++i) + { + char *t = const_cast (str); + wstr[i] = static_cast (*((unsigned char*)(t + i))); + } +# endif /* ACE_WIN32 */ + return wstr; +} + +inline +ACE_Ascii_To_Wide::ACE_Ascii_To_Wide (const char *s) +{ +#if defined(ACE_HAS_ICONV) + if (ACE_Ascii_To_Wide_iconv_env == 0) + { + ACE_Ascii_To_Wide_iconv_env = iconv_open("WCHAR_T", ""); + } +#endif + s_ = ACE_Ascii_To_Wide::convert (s); +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_WCHAR */ diff --git a/dep/acelite/ace/checked_iterator.h b/dep/acelite/ace/checked_iterator.h new file mode 100644 index 00000000000..08940e62bbb --- /dev/null +++ b/dep/acelite/ace/checked_iterator.h @@ -0,0 +1,58 @@ +// -*- C++ -*- + +#ifndef ACE_CHECKED_ITERATOR_H +#define ACE_CHECKED_ITERATOR_H + +/** + * @file checked_iterator.h + * + * @brief Checked iterator factory function. + * + * Some compilers (e.g. MSVC++ >= 8) issue security related + * diagnostics if algorithms such as std::copy() are used in an unsafe + * way. Normally this isn't an issue if STL container iterators are + * used in conjuction with the standard algorithms. However, in cases + * where application-specific iterators are use with standard + * algorithms that could potentially overrun a buffer, extra care must + * be taken to prevent such an overrun. If supported, checked + * iterators can be used to address the potential destination buffer + * overrun. + * + * This header provides function templates that generate the + * appropriate checked iterator. In cases where checked iterators are + * not supported, the pointer passed to the function is returned + * instead. + * + * $Id: checked_iterator.h 88263 2009-12-20 07:58:09Z johnnyw $ + * + * @internal The functions and types in this header are meant for + * internal use. They may change at any point between + * releases. + * + * @author Ossama Othman + */ + +# if defined (_MSC_VER) && (_MSC_FULL_VER >= 140050000) && (!defined (_STLPORT_VERSION)) +// Checked iterators are currently only supported in MSVC++ 8 or better. +# include +# endif /* _MSC_VER >= 1400 && !_STLPORT_VERSION */ + +# if defined (_MSC_VER) && (_MSC_FULL_VER >= 140050000) && (!defined (_STLPORT_VERSION)) +template +stdext::checked_array_iterator +ACE_make_checked_array_iterator (PTR buf, size_t len) +{ + return stdext::checked_array_iterator (buf, len); +} +# else +template +PTR +ACE_make_checked_array_iterator (PTR buf, size_t /* len */) +{ + // Checked iterators are unsupported. Just return the pointer to + // the buffer itself. + return buf; +} +# endif /* _MSC_VER >= 1400 && !_STLPORT_VERSION */ + +#endif /* ACE_CHECKED_ITERATOR_H */ diff --git a/dep/acelite/ace/config-WinCE.h b/dep/acelite/ace/config-WinCE.h new file mode 100644 index 00000000000..93040583980 --- /dev/null +++ b/dep/acelite/ace/config-WinCE.h @@ -0,0 +1,229 @@ +// $Id: config-WinCE.h 89494 2010-03-15 20:11:18Z olli $ + +// Note: For WinCE build, simply use: #include "ace/config-win32.h" +// It is same as config.h for Windows NT/2k so that you can +// share same files and directories for both WinCE and NT/2k +// builds, unless you add additional definition(s) for each +// specific build or change the output directory. + +#ifndef ACE_CONFIG_WINCE_H +#define ACE_CONFIG_WINCE_H + +#include /**/ "ace/pre.h" + +#ifndef ACE_CONFIG_WIN32_H +# error Use config-win32.h in config.h instead of this header +#endif // ACE_CONFIG_WIN32_H + +#if !defined (_WIN32_WCE) +# error Define _WIN32_WCE to version (i.e. 500 = 5.0) +#endif // _WIN32_WCE + +#if (_WIN32_WCE < 500) +# error ACE requires Windows CE 5.0 and later. +#endif // _WIN32_WCE + +#if !defined (ACE_HAS_WINCE) +# define ACE_HAS_WINCE 1 +#endif + +#if defined (_MSC_VER) && (_MSC_VER < 1400) +// WinCE prior to Visual Studio 2005 integration doesn't have most of +// the standard C library time functions. It also doesn't define struct tm. +// SYSTEMTIME has pretty much the same info though, so we can map it when +// needed. Define struct tm here and use it when needed. This is taken +// from the standard C library. +# define ACE_LACKS_STRUCT_TM +#endif + +// We need these libraries to build: +#if defined (_MSC_VER) +# pragma comment(lib,"corelibc.lib") +# pragma comment(linker, "/nodefaultlib:oldnames.lib") +#endif + +// Only DLL version is supported on CE. +//#if defined (ACE_HAS_DLL) +//# undef ACE_HAS_DLL +//#endif // ACE_HAS_DLL +//#define ACE_HAS_DLL 1 + +// Need to define LD search path explicitly on CE because +// CE doesn't have environment variables and we can't get +// the information using getenv. +#define ACE_DEFAULT_LD_SEARCH_PATH ACE_TEXT (".\\;\\windows") + +#define ACE_LACKS_FCNTL_H +#define ACE_LACKS_SYS_TYPES_H +#define ACE_LACKS_GETCWD +#define ACE_LACKS_ASCTIME +#define ACE_LACKS_ASCTIME_R +#define ACE_LACKS_GMTIME +#define ACE_LACKS_GMTIME_R +#define ACE_LACKS_LOCALTIME +#define ACE_LACKS_PERROR +#define ACE_LACKS_STRFTIME +#define ACE_LACKS_WIN32_SETFILEPOINTEREX +#define ACE_LACKS_WIN32_SERVICES +#define ACE_LACKS_WIN32_SECURITY_DESCRIPTORS +#define ACE_LACKS_GETPROCESSTIMES +#define ACE_LACKS_PDH_H +#define ACE_LACKS_PDHMSG_H +#define ACE_LACKS_TIME +#define ACE_LACKS_TZSET +#define ACE_LACKS_RAISE +#define ACE_LACKS_BSEARCH + +#define ACE_HAS_POSITION_INDEPENDENT_POINTERS 1 + +#define ACE_LACKS_MSG_WFMO +#define ACE_LACKS_UMASK +#define ACE_HAS_TYPES_H +#define ACE_LACKS_DEV_T + +#define ACE_ISCTYPE_EQUIVALENT ::_isctype + +// WinCE only supports the UNICODE API +#if !defined (ACE_USES_WCHAR) +# define ACE_USES_WCHAR +#endif /* ACE_USES_WCHAR */ + +#if (_WIN32_WCE < 0x600) +# define ACE_USES_WINCE_SEMA_SIMULATION +# define ACE_LACKS_ERRNO_H +# define ACE_LACKS_DUP +# define ACE_LACKS_GETSYSTEMTIMEASFILETIME +#endif /* (_WIN32_WCE < 0x600) */ + +#define ACE_LACKS_REGNOTIFYCHANGEKEYVALUE + +#define ACE_HAS_NONSTATIC_OBJECT_MANAGER 1 + +#if ! defined(ACE_DEFAULT_THREAD_KEYS) +# define ACE_DEFAULT_THREAD_KEYS TLS_MINIMUM_AVAILABLE +#endif // ! defined(ACE_DEFAULT_THREAD_KEYS) + +// FILE stuff isn't always defined in CE +#if (_MSC_VER < 1400) && !defined (_FILE_DEFINED) + typedef void FILE; +# define _FILE_DEFINED +#endif /* _MSC_VER < 1400 && !_FILE_DEFINED */ + +// This was defined in previous versions of CE, but not 2.11 +#define EXCEPTION_ACCESS_VIOLATION STATUS_ACCESS_VIOLATION + +#define ACE_MAIN WINAPI WinMain + +// SH3 cross-compiler can't handle inline functions correctly +// (along with other bugs.) +#if defined (SH3) +# define ACE_LACKS_INLINE_FUNCTIONS +#endif // SH3 && _DEBUG + +#ifndef ACE_DEFAULT_SERVER_HOST +# define ACE_DEFAULT_SERVER_HOST ACE_TEXT("localhost") +#endif // ACE_DEFAULT_SERVER_HOST + +// @@ Need to remap every function that uses any of these flags to +// Win32 API. These are for ANSI styled function and are not +// available on WinCE. + +#define _O_RDONLY 0x0000 // open for reading only +#define _O_WRONLY 0x0001 // open for writing only +#define _O_RDWR 0x0002 // open for reading and writing +#define _O_APPEND 0x0008 // writes done at eof + +#define _O_CREAT 0x0100 // create and open file +#define _O_TRUNC 0x0200 // open and truncate +#define _O_EXCL 0x0400 // open only if file doesn't already exist + +// O_TEXT files have sequences translated to on read()'s, +// and sequences translated to on write()'s +#define _O_TEXT 0x4000 // file mode is text (translated) +#define _O_BINARY 0x8000 // file mode is binary (untranslated) + +// Temporary file bit - file is deleted when last handle is closed +#define _O_TEMPORARY 0x0040 // temporary file bit + +// Non-ANSI names +#define O_RDONLY _O_RDONLY +#define O_WRONLY _O_WRONLY +#define O_RDWR _O_RDWR +#define O_APPEND _O_APPEND +#define O_CREAT _O_CREAT +#define O_TRUNC _O_TRUNC +#define O_EXCL _O_EXCL +#define O_TEXT _O_TEXT +#define O_BINARY _O_BINARY +#define O_TEMPORARY _O_TEMPORARY + +// @@ NSIG value. This is definitely not correct. +#define NSIG 23 + +#if !defined (FILE_MAP_COPY) +#define FILE_MAP_COPY 0 +#endif + +#define ACE_HAS_INTERLOCKED_EXCHANGEADD +#define ACE_LACKS_ACCESS +#define ACE_LACKS__WACCESS +#define ACE_HAS_ACCESS_EMULATION +#define ACE_LACKS_EXEC +#define ACE_LACKS_MKTEMP +#define ACE_LACKS_ISATTY +#define ACE_LACKS_STRERROR +#define ACE_LACKS_SYSTEM +#define ACE_LACKS_PIPE + +#define ACE_LACKS_CHDIR +#define ACE_LACKS_GETENV +#define ACE_LACKS_SETENV +#define ACE_LACKS_UNSETENV +#define ACE_LACKS_PUTENV +#define ACE_LACKS_GETENVSTRINGS +#define ACE_LACKS_STRENVDUP +#define ACE_LACKS_REALPATH +#define ACE_LACKS_SWAB +#define ACE_LACKS_TEMPNAM + +#if defined (_WIN32_WCE_EMULATION) +// @@ For some reason, qsort isn't defined correctly (_stdcall vs _cdecl) +// under emulation. So for right now, exclude it. +# define ACE_LACKS_QSORT +#endif // _WIN32_WCE_EMULATION + +#if !defined (BUFSIZ) +# define BUFSIZ 1024 +#endif + +#define ACE_LACKS_MALLOC_H // We do have malloc.h, but don't use it. + +#define ACE_HAS_WINCE_BROKEN_ERRNO + +#define ACE_HAS_STRDUP_EMULATION + +#if !defined (MAXSYMLINKS) +# define MAXSYMLINKS 0 +#endif + +// WinCE can't do fixed addresses for memory-mapped files. +#if defined (ACE_DEFAULT_BASE_ADDR) +# undef ACE_DEFAULT_BASE_ADDR +#endif +#define ACE_DEFAULT_BASE_ADDR 0 + +#if (_WIN32_WCE < 0x600) +# define ACE_HAS_TSS_EMULATION +#endif // WinCE version < 6.0 + +// CE doesn't support FILE_SHARE_DELETE like regular windows +#if !defined (ACE_DEFAULT_FILE_PERMS) +# define ACE_DEFAULT_FILE_PERMS (FILE_SHARE_READ | FILE_SHARE_WRITE) +#endif + +#define ACE_LACKS_SIGNAL_H +#define ACE_LACKS_SYS_STAT_H + +#include /**/ "ace/post.h" + +#endif // ACE_CONFIG_WINCE_H diff --git a/dep/acelite/ace/config-aix-5.x.h b/dep/acelite/ace/config-aix-5.x.h new file mode 100644 index 00000000000..d524e9530fc --- /dev/null +++ b/dep/acelite/ace/config-aix-5.x.h @@ -0,0 +1,326 @@ +// $Id: config-aix-5.x.h 87268 2009-10-29 21:06:06Z olli $ +// +// Config file for AIX 5.1 and higher. + +#ifndef ACE_CONFIG_AIX_5_X_H +#define ACE_CONFIG_AIX_5_X_H + +// This define is needed for building with Visual Age C++ 5 in incremental +// mode. In the batch mode build, platform_aix_ibm.GNU sets it. The incremental +// mode compiler won't be supported after ACE 5.3, so this will also go away +// in that timeframe, so don't worry about future AIX versions. +#if !defined (ACE_AIX_VERS) +# define ACE_AIX_VERS 501 +#endif + +// AIX 5.1 has AIO, but it doesn't have the same API as other POSIX +// systems, and the semantics of operations are a bit different. Will take +// some real work to get this going. +// AIX 5.2, however, has the POSIX API implemented. However, the libc functions +// to implement it aren't exported by default. You need to use smit to enable +// them. So, leave AIO disabled unless the user explicitly enables it. +// config-aix-4.x.h will set ACE_HAS_AIO_CALLS if config-posix.h senses the +// feature-test macros, so set up _ACE_DISABLE_AIO_CALLS_ if the user didn't +// set it. Then check for it after including config-aix-4.x.h and remove +// ACE_HAS_AIO_CALLS if so. +#if !defined (ACE_HAS_AIO_CALLS) +# define _ACE_DISABLE_AIO_CALLS_ +#endif + +// Both IBM and g++ compilers set _THREAD_SAFE if compiler is asked to compile +// threaded code (xlC_r, as opposed to xlC; and g++ -pthread) +#if !defined (ACE_MT_SAFE) || (ACE_MT_SAFE != 0) +# if defined (ACE_HAS_THREADS) +# undef ACE_HAS_THREADS +# endif +# if defined (_THREAD_SAFE) +# define ACE_HAS_THREADS 1 +// # else +// # define ACE_HAS_THREADS 0 +# endif /* _THREAD_SAFE */ +#endif /* !ACE_MT_SAFE || (ACE_MT_SAFE != 0) */ + +#if defined (__IBMCPP__) + // AIX xlC, IBM C/C++ compiler + //******************************************************************** + // + + // Compiler does this with a builtin - it's not in libc. + // Although ACE does have alloca() on this compiler/platform combination, + // it is disabled by default since it can be dangerous. Uncomment the + // following line if you ACE to use it. + //# define ACE_HAS_ALLOCA + + // Compiler supports the ssize_t typedef. +# define ACE_HAS_SSIZE_T + + // Keep an eye on this as the compiler and standards converge... +# define ACE_LACKS_LINEBUFFERED_STREAMBUF +# define ACE_LACKS_PRAGMA_ONCE + +# define ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS + // When using -qtempinc, we don't need to see template implementation + // source (though we do need a pragma to find the correct source file). + // However, without -qtempinc (either -qnotempinc or -qtemplateregistry) + // we do need to see the source. +# if defined (__TEMPINC__) +# if !defined ACE_TEMPLATES_REQUIRE_PRAGMA +# define ACE_TEMPLATES_REQUIRE_PRAGMA +# endif +# else +# if !defined (ACE_TEMPLATES_REQUIRE_SOURCE) +# define ACE_TEMPLATES_REQUIRE_SOURCE +# endif +# endif /* __TEMPINC__ */ + +# undef WIFEXITED +# undef WEXITSTATUS +# define ACE_HAS_STANDARD_CPP_LIBRARY 1 +# define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 + +# define ACE_HAS_TEMPLATE_TYPEDEFS +# define ACE_HAS_CUSTOM_EXPORT_MACROS +# define ACE_Proper_Export_Flag +# define ACE_Proper_Import_Flag + // There's no explicit import/export per-se, but to be sure that declared + // template code is exported, explicitly instantiate the class. +# define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) template class SINGLETON_TYPE < CLASS, LOCK >; +# define ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) extern template class SINGLETON_TYPE < CLASS, LOCK >; + +#elif defined (__GNUG__) + // config-g++-common.h undef's ACE_HAS_STRING_CLASS with -frepo, so + // this must appear before its #include. +# define ACE_HAS_STRING_CLASS + +# include "ace/config-g++-common.h" + +# define ACE_HAS_SSIZE_T + +# if (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ == 0)) +// We have to explicitly instantiate static template members prior to g++ 4.1 +# define ACE_HAS_EXPLICIT_STATIC_TEMPLATE_MEMBER_INSTANTIATION +#endif /* g++ prior to 4.1 */ + +# if !defined (ACE_MT_SAFE) || ACE_MT_SAFE != 0 + // ACE_MT_SAFE is #defined below, for all compilers. +# if !defined (_REENTRANT) +# define _REENTRANT +# endif /* _REENTRANT */ +# endif /* !ACE_MT_SAFE */ + +#else /* ! __IBMCPP__ && ! __GNUG__ */ +# ifdef __cplusplus /* Let it slide for C compilers. */ +# error unsupported compiler in ace/config-aix-5.x.h +# endif /* __cplusplus */ +#endif /* ! __xlC__ && ! __GNUG__ */ + +// Compiling for AIX. +#ifndef AIX +# define AIX +#endif /* AIX */ + +// Pick up all the detectable settings. +#include "ace/config-posix.h" + +// Regardless of what config-posix.h may indicate, AIX 5.3 is the first +// to support sem_timedwait(). Prior to that, use the emulation. +#if defined (ACE_HAS_POSIX_SEM_TIMEOUT) && \ + (defined (ACE_AIX_VERS) && (ACE_AIX_VERS < 503)) +# undef ACE_HAS_POSIX_SEM_TIMEOUT +#endif /* ACE_HAS_POSIX_SEM_TIMEOUT && ACE_AIX_VERS < 503 */ + +#if defined (ACE_DLL_SUFFIX) +# undef ACE_DLL_SUFFIX +#endif +#define ACE_DLL_SUFFIX ACE_TEXT (".so") + +#define ACE_DEFAULT_BASE_ADDR ((char *) 0x80000000) + +#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R + +#define ACE_HAS_SOCKLEN_T +#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG + +// AIX has AIO, but the functions don't match those of other AIO-enabled +// platforms. If this is to work, it'll require some significant work, +// maybe moving the OS-abstraction stuff to an OS_AIO or some such thing. +//# define ACE_HAS_AIO_CALLS + +#define ACE_HAS_AIX_HI_RES_TIMER + +// Compiler/platform has correctly prototyped header files. +#define ACE_HAS_CPLUSPLUS_HEADERS + +// Prototypes for both signal() and struct sigaction are consistent. +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES + +// OS has readdir and friends. +#define ACE_HAS_DIRENT + +// OS supports the getrusage() system call +#define ACE_HAS_GETRUSAGE + +#define ACE_HAS_GPERF + +#define ACE_HAS_H_ERRNO + +#define ACE_LACKS_STDINT_H +#define ACE_LACKS_SYS_SYSCTL_H + +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT +#define ACE_HAS_NONCONST_SELECT_TIMEVAL +#define ACE_HAS_ICMP_SUPPORT 1 +#define ACE_HAS_IP_MULTICAST + +// Lacks perfect filtering, must bind group address. +#if !defined ACE_LACKS_PERFECT_MULTICAST_FILTERING +# define ACE_LACKS_PERFECT_MULTICAST_FILTERING 1 +#endif /* ACE_LACKS_PERFECT_MULTICAST_FILTERING */ + +#define ACE_HAS_MSG + +// Compiler/platform supports poll(). +#define ACE_HAS_POLL + +// Platform supports POSIX O_NONBLOCK semantics. +#define ACE_HAS_POSIX_NONBLOCK + +#define ACE_HAS_POSIX_TIME +// ... but needs to include another header for it on 4.2+ +# define ACE_HAS_BROKEN_POSIX_TIME +// ... and needs another typedef +#define ACE_LACKS_TIMESPEC_T +#define ACE_HAS_SELECT_H + +#define ACE_HAS_REENTRANT_FUNCTIONS + +// Compiler/platform defines the sig_atomic_t typedef +#define ACE_HAS_SIG_ATOMIC_T +#define ACE_HAS_SIGINFO_T +#define ACE_LACKS_SIGINFO_H +#define ACE_HAS_P_READ_WRITE + +#define ACE_HAS_SIGWAIT +#define ACE_HAS_SOCKADDR_IN_SIN_LEN +#define ACE_HAS_STRBUF_T + +// Compiler supports stropts.h +#define ACE_HAS_STREAMS +// #define ACE_HAS_STREAM_PIPES + +// AIX bzero() +#define ACE_HAS_STRINGS + +#define ACE_HAS_STRUCT_NETDB_DATA + +// Dynamic linking is in good shape on newer OS/patch levels. If you have +// trouble with the dynamic linking parts of ACE, and can't patch your OS +// up to latest levels, comment this out. +#define ACE_HAS_SVR4_DYNAMIC_LINKING +// This is tightly related to dynamic linking... +#define ACE_HAS_AUTOMATIC_INIT_FINI + +#define ACE_HAS_SVR4_GETTIMEOFDAY + +#define ACE_HAS_SYSV_IPC +#define ACE_HAS_TIMOD_H +#define ACE_HAS_XTI +#define ACE_HAS_BROKEN_T_ERROR +#define ACE_TLI_TCP_DEVICE "/dev/xti/tcp" + +#define ACE_HAS_UALARM + +#define ACE_HAS_UCONTEXT_T + +#define ACE_HAS_UTIME + +#define ACE_HAS_CTYPE_T + +// Platform has XPG4 wide character type and functions. However, the size +// of wchar_t changes for 32- vs. 64-bit builds (unsigned short vs. unsigned +// int, respectively). +#define ACE_HAS_XPG4_MULTIBYTE_CHAR +#ifdef __64BIT__ +# define ACE_SIZEOF_WCHAR 4 +#else +# define ACE_SIZEOF_WCHAR 2 +#endif /* __64BIT__ */ + +#define ACE_LACKS_NETINET_TCP_H + +// AIX uses LIBPATH to search for libraries +#define ACE_LD_SEARCH_PATH ACE_TEXT ("LIBPATH") + +// Defines the page size of the system. +#define ACE_PAGE_SIZE 4096 + +//************************************************************** +// +// Threads related definitions. +// +// The threads on AIX are generally POSIX P1003.1c (ACE_HAS_PTHREADS). +// However, there is also a kernel thread ID (tid_t) that is used in +// ACE_Log_Msg (printing the thread ID). The tid_t is not the same as +// pthread_t, and can't derive one from the other - thread_self() gets +// the tid_t (kernel thread ID) if called from a thread. +// Thanks very much to Chris Lahey for straightening this out. + +#if defined (ACE_HAS_THREADS) +# if !defined (ACE_MT_SAFE) +# define ACE_MT_SAFE 1 +# endif + +# define ACE_HAS_PTHREADS +# define ACE_HAS_PTHREADS_UNIX98_EXT +# define ACE_HAS_PTHREAD_CONTINUE_NP +# define ACE_HAS_PTHREAD_SUSPEND_NP +# define ACE_HAS_RECURSIVE_MUTEXES +# define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS +# define ACE_HAS_SIGTHREADMASK +# define ACE_HAS_THREAD_SPECIFIC_STORAGE + +# define ACE_LACKS_THREAD_PROCESS_SCOPING +#else +# undef ACE_HAS_THREADS +#endif /* ACE_HAS_THREADS != 0 */ + +#define ACE_MALLOC_ALIGN 8 + +#if (defined _XOPEN_SOURCE && (_XOPEN_SOURCE - 0) >= 500) && !defined(_UNIX95) +# define ACE_HAS_3_PARAM_WCSTOK +#endif /* (_XOPEN_SOURCE -0) >= 500 && !_UNIX95 */ + +#if defined (_ACE_DISABLE_AIO_CALLS_) +# if defined (ACE_HAS_AIO_CALLS) +# undef ACE_HAS_AIO_CALLS +# endif +# undef _ACE_DISABLE_AIO_CALLS_ +#endif + +// AIX's /usr/include/unistd.h sets _POSIX_SEMAPHORE to indicate the system +// supplies such a facility, but the headers don't enable it unless +// _XOPEN_SOURCE >= 500. So disable semaphores here if _XOPEN_SOURCE isn't +// up to snuff. +#if defined (ACE_HAS_POSIX_SEM) && \ + (!defined (_XOPEN_SOURCE) || (_XOPEN_SOURCE-0 < 500)) +# undef ACE_HAS_POSIX_SEM +#endif + +// I think this is correct, but needs to be verified... -Steve Huston +#define ACE_HAS_SIGTIMEDWAIT + +// AIX 5.1 has netinet/tcp.h +#undef ACE_LACKS_NETINET_TCP_H + +#define ACE_HAS_3_PARAM_READDIR_R +#define ACE_HAS_POSIX_GETPWNAM_R +#define ACE_HAS_SCANDIR +#define ACE_SCANDIR_CMP_USES_VOIDPTR +#define ACE_SCANDIR_SEL_LACKS_CONST +#define ACE_HAS_SIGSUSPEND +#define ACE_HAS_TIMEZONE /* Call tzset() to set timezone */ +#define ACE_LACKS_ISCTYPE +#define ACE_HAS_STRSIGNAL +#define ACE_NEEDS_STRSIGNAL_RANGE_CHECK + +#endif /* ACE_CONFIG_AIX_5_X_H */ diff --git a/dep/acelite/ace/config-all.h b/dep/acelite/ace/config-all.h new file mode 100644 index 00000000000..e19caec8e45 --- /dev/null +++ b/dep/acelite/ace/config-all.h @@ -0,0 +1,93 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file config-all.h + * + * $Id: config-all.h 84216 2009-01-22 18:34:40Z johnnyw $ + * + * @author (Originally in OS.h)Doug Schmidt + * @author Jesper S. M|ller + * @author and a cast of thousands... + */ +//========================================================================== + +#ifndef ACE_CONFIG_ALL_H +#define ACE_CONFIG_ALL_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +// This is used to indicate that a platform doesn't support a +// particular feature. +#if defined ACE_HAS_VERBOSE_NOTSUP + // Print a console message with the file and line number of the + // unsupported function. +# include "ace/OS_NS_stdio.h" +# define ACE_NOTSUP_RETURN(FAILVALUE) do { errno = ENOTSUP; ACE_OS::fprintf (stderr, ACE_TEXT ("ACE_NOTSUP: %s, line %d\n"), __FILE__, __LINE__); return FAILVALUE; } while (0) +# define ACE_NOTSUP do { errno = ENOTSUP; ACE_OS::fprintf (stderr, ACE_TEXT ("ACE_NOTSUP: %s, line %d\n"), __FILE__, __LINE__); return; } while (0) +#else /* ! ACE_HAS_VERBOSE_NOTSUP */ +# define ACE_NOTSUP_RETURN(FAILVALUE) do { errno = ENOTSUP ; return FAILVALUE; } while (0) +# define ACE_NOTSUP do { errno = ENOTSUP; return; } while (0) +#endif /* ! ACE_HAS_VERBOSE_NOTSUP */ + +// ---------------------------------------------------------------- + +# define ACE_TRACE_IMPL(X) ACE_Trace ____ (ACE_TEXT (X), __LINE__, ACE_TEXT (__FILE__)) + +// By default tracing is turned off. +#if !defined (ACE_NTRACE) +# define ACE_NTRACE 1 +#endif /* ACE_NTRACE */ + +#if (ACE_NTRACE == 1) +# define ACE_TRACE(X) +#else +# if !defined (ACE_HAS_TRACE) +# define ACE_HAS_TRACE +# endif /* ACE_HAS_TRACE */ +# define ACE_TRACE(X) ACE_TRACE_IMPL(X) +# include "ace/Trace.h" +#endif /* ACE_NTRACE */ + +// By default we perform no tracing on the OS layer, otherwise the +// coupling between the OS layer and Log_Msg is too tight. But the +// application can override the default if they wish to. +#if !defined (ACE_OS_NTRACE) +# define ACE_OS_NTRACE 1 +#endif /* ACE_OS_NTRACE */ + +#if (ACE_OS_NTRACE == 1) +# define ACE_OS_TRACE(X) +#else +# if !defined (ACE_HAS_TRACE) +# define ACE_HAS_TRACE +# endif /* ACE_HAS_TRACE */ +# define ACE_OS_TRACE(X) ACE_TRACE_IMPL(X) +# include "ace/Trace.h" +#endif /* ACE_OS_NTRACE */ + +#if !defined (ACE_HAS_MONITOR_FRAMEWORK) +# define ACE_HAS_MONITOR_FRAMEWORK 1 +#endif + +#if !defined (ACE_HAS_SENDFILE) +# define ACE_HAS_SENDFILE 0 +#endif + +#if !defined (ACE_HAS_MONITOR_POINTS) +# define ACE_HAS_MONITOR_POINTS 0 +#endif + +// These includes are here to avoid circular dependencies. +// Keep this at the bottom of the file. It contains the main macros. +#include "ace/OS_main.h" + +#include /**/ "ace/post.h" + +#endif /* ACE_CONFIG_ALL_H */ diff --git a/dep/acelite/ace/config-cray.h b/dep/acelite/ace/config-cray.h new file mode 100644 index 00000000000..1b944876112 --- /dev/null +++ b/dep/acelite/ace/config-cray.h @@ -0,0 +1,205 @@ +/* -*- C++ -*- */ +// $Id: config-cray.h 87169 2009-10-19 20:26:55Z olli $ + +#ifndef ACE_CONFIG_CRAY_H +#define ACE_CONFIG_CRAY_H +#include /**/ "ace/pre.h" + +/* + The following predefined macros are used within ACE ifdefs. + These are defined when using the Cray compilers. _CRAYMPP + is defined, for example, if you are running on a Cray T3E + massively parallel machine. Moreover, in the case of the T3E, + _CRAYT3E will be defined. This is used to determine the + ACE_SIZEOF defines for primitive types. + + _UNICOS is defined as either the major version of UNICOS being run, + e.g. 9 or 10 on the vector machines (e.g. C90, T90, J90, YMP, ...) + or the major+minor+level UNICOS/mk version, e.g. 2.0.3 => 203, + being run on an MPP machine. + + Summary: + + _CRAYMPP (defined only if running on MPP machine, e.g. T3E, UNICOS/mk) + _CRAYT3E (defined specifically if compiling on a Cray T3E) + _UNICOS (defined if running UNICOS or UNICOS/mk) + + Tested on UNICOS 10.0.0.5, UNICOS/mk 2.0.4.57 + Compiles on UNICOS 9.0.2.8, but some tests deadlock + + Contributed by Doug Anderson +*/ + +#if defined (_UNICOS) && !defined (MAXPATHLEN) +#define MAXPATHLEN 1023 +#endif /* _UNICOS */ + +#define ACE_DEFAULT_CLOSE_ALL_HANDLES 0 + +// Defines the page size of the system. +#define ACE_PAGE_SIZE 4096 + +#define ACE_HAS_CPLUSPLUS_HEADERS + +#define ACE_HAS_SSIZE_T + +#define ACE_HAS_SYSV_IPC + +#define ACE_MT_SAFE 1 + +#define ACE_HAS_THREADS + +#define ACE_HAS_PTHREADS + +#define ACE_HAS_THREAD_SPECIFIC_STORAGE + +#define ACE_HAS_PTHREAD_MUTEXATTR_SETKIND_NP + +#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R + +#define ACE_HAS_POSIX_TIME + +#define ACE_HAS_TIMEZONE_GETTIMEOFDAY + +#define ACE_HAS_POSIX_NONBLOCK + +// Platform has POSIX terminal interface. +#define ACE_HAS_TERMIOS + +#define ACE_HAS_DIRENT + +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT + +#define ACE_HAS_IP_MULTICAST + +#define ACE_HAS_SOCKADDR_IN_SIN_LEN + +#define ACE_HAS_NONCONST_SELECT_TIMEVAL + +#define ACE_HAS_NONCONST_READLINK + +#define ACE_HAS_CHARPTR_SOCKOPT + +#define ACE_HAS_NONCONST_GETBY +#define ACE_HAS_NONCONST_INET_ADDR + +// has man pages, but links with missing symbols and I can't find lib yet +/* #define ACE_HAS_REGEX */ + +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES + +#if _UNICOS > 9 +# define ACE_HAS_SIGWAIT +#endif + +#define ACE_HAS_SIG_ATOMIC_T + +#define ACE_HAS_SIGISMEMBER_BUG + +#define ACE_HAS_MSG + +#define ACE_HAS_GPERF + +// Special modifications that apply to UNICOS/mk +#if defined(_CRAYMPP) + +# define ACE_HAS_SIGINFO_T +# define ACE_HAS_UCONTEXT_T + +#endif + +// The Cray T90 supposedly supports SYSV SHMEM, but I was unable to get it +// working. Of course, all other Cray PVP and MPP systems do NOT support it, +// so it's probably good to just define like this for consistency +#define ACE_LACKS_SYSV_SHMEM +#define ACE_LACKS_MMAP +#define ACE_LACKS_CONST_TIMESPEC_PTR +#define ACE_LACKS_SYSCALL +#define ACE_LACKS_STRRECVFD +#define ACE_LACKS_MADVISE +#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS +#define ACE_LACKS_LINEBUFFERED_STREAMBUF +#define ACE_LACKS_PTHREAD_CLEANUP +#define ACE_LACKS_CONDATTR_PSHARED +#define ACE_LACKS_THREAD_PROCESS_SCOPING + +#if !defined(_CRAYMPP) + +#define ACE_LACKS_PTHREAD_CANCEL +#define ACE_LACKS_PTHREAD_KILL + +#endif + +#define ACE_LACKS_MUTEXATTR_PSHARED +#define ACE_LACKS_RWLOCK_T +#define ACE_LACKS_PRI_T +#define ACE_LACKS_GETPGID +#define ACE_LACKS_SETPGID +#define ACE_LACKS_SETREGID +#define ACE_LACKS_SETREUID +#define ACE_LACKS_MPROTECT +#define ACE_LACKS_MSYNC +#define ACE_LACKS_READV +#define ACE_LACKS_RLIMIT + +// we probably want to fake not having this, since Cray memory mgmt is different +#define ACE_LACKS_SBRK + +#define ACE_LACKS_SETSCHED + +#define ACE_LACKS_SIGINFO_H + +#define ACE_LACKS_TIMESPEC_T + +#define ACE_LACKS_WRITEV + +// Cray vector machines are "word" oriented, and modern ones are hard 64-bit. +// "char" is somewhat of a special case. Most problems arise when code thinks +// it can address 32-bit quantities and the like. MPP crays are typically +// byte oriented, e.g. T3E uses Alpha processors, so we don't need as much +// special treatment. + +#ifndef _CRAYMPP + +# define ACE_SIZEOF_CHAR 1 +# define ACE_SIZEOF_SHORT 8 +# define ACE_SIZEOF_INT 8 +# define ACE_SIZEOF_LONG 8 +# define ACE_SIZEOF_LONG_LONG 8 +# define ACE_SIZEOF_FLOAT 8 +# define ACE_SIZEOF_DOUBLE 8 +# define ACE_SIZEOF_LONG_DOUBLE 16 +# define ACE_SIZEOF_VOID_P 8 + +#elif defined(_CRAYT3E) + +# define ACE_SIZEOF_CHAR 1 +# define ACE_SIZEOF_SHORT 4 +# define ACE_SIZEOF_INT 8 +# define ACE_SIZEOF_LONG 8 +# define ACE_SIZEOF_LONG_LONG 8 +# define ACE_SIZEOF_FLOAT 4 +# define ACE_SIZEOF_DOUBLE 8 +# define ACE_SIZEOF_LONG_DOUBLE 8 +# define ACE_SIZEOF_VOID_P 8 + +#endif + +// Ones to check out at some point + +// C++ Compiler stuff to verify +/* #define ACE_NEW_THROWS_EXCEPTIONS */ +/* #define ACE_HAS_TEMPLATE_TYPEDEFS */ + +// thread issues to check out +/* #define ACE_LACKS_TIMEDWAIT_PROTOTYPES */ + +// Cray does seem to support it, in -lnsl and has tiuser.h header +/* #define ACE_HAS_TLI */ +/* #define ACE_HAS_TIUSER_H */ +/* #define ACE_HAS_TLI_PROTOTYPES */ + +/* #define ACE_LACKS_NAMED_POSIX_SEM */ + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_CRAY_H */ diff --git a/dep/acelite/ace/config-cxx-common.h b/dep/acelite/ace/config-cxx-common.h new file mode 100644 index 00000000000..024c25fd27e --- /dev/null +++ b/dep/acelite/ace/config-cxx-common.h @@ -0,0 +1,86 @@ +// -*- C++ -*- +// +// $Id: config-cxx-common.h 81935 2008-06-12 22:01:53Z jtc $ + +#ifndef ACE_CXX_COMMON_H +#define ACE_CXX_COMMON_H +#include /**/ "ace/pre.h" + +#if !defined (ACE_CONFIG_INCLUDE_CXX_COMMON) +# error ace/config-cxx-common.h: ACE configuration error! Do not #include this file directly! +#endif + +#if defined (__DECCXX) +# if !defined (linux) +# define ACE_HAS_STRING_CLASS +# if (__DECCXX_VER >= 60090010) +# define ACE_HAS_STDCPP_STL_INCLUDES +# endif /* __DECCXX_VER < 60090010 */ +# endif /* ! linux */ + +# define DEC_CXX +# define ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR +# define ACE_LACKS_LINEBUFFERED_STREAMBUF +# define ACE_LACKS_SIGNED_CHAR +# define ACE_HAS_CPLUSPLUS_HEADERS +# define ACE_TEMPLATES_REQUIRE_SOURCE +# if (__DECCXX_VER >= 60090010) + // DEC CXX 6.0 supports exceptions, etc., by default. Exceptions + // are enabled by platform_osf1_4.x.GNU/wrapper_macros.GNU. +# if defined (ACE_HAS_EXCEPTIONS) +# define ACE_NEW_THROWS_EXCEPTIONS +# endif /* ACE_HAS_EXCEPTIONS */ +# define ACE_HAS_STANDARD_CPP_LIBRARY 1 +# define ACE_HAS_TEMPLATE_TYPEDEFS + +# define ACE_ENDLESS_LOOP \ + unsigned int ace_endless_loop____ = 0; if (ace_endless_loop____) break; + +# if defined (__USE_STD_IOSTREAM) +# define ACE_LACKS_CHAR_RIGHT_SHIFTS +# define ACE_LACKS_IOSTREAM_FX +# define ACE_LACKS_UNBUFFERED_STREAMBUF +# define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 +# else /* ! __USE_STD_IOSTREAM */ +# define ACE_USES_OLD_IOSTREAMS +# endif /* ! __USE_STD_IOSTREAM */ + +// 9: nested comment not allowed. (/usr/include/pdsc.h!) (nestcomment) +// 177: variable was declared but never referenced (declbutnotref) +// 193: zero used for undefined preprocessing identifier (undpreid) +// 236: controlling expression is constant (boolexprconst) +// 401: base_class_with_nonvirtual_dtor (basclsnondto) +// 1016: expected type is incompatible with declared type of int (incint) +// 1136: conversion to smaller size integer could lose data (intconlosbit) + +# pragma message disable basclsnondto +# pragma message disable boolexprconst +# pragma message disable undpreid +# pragma message disable notusetmpfunprm +# pragma message disable bltinclnk + +# if (__DECCXX_VER >= 60190029) + // 6.1-029 and later support msg 1136. Disable it because it + // causes warnings from ACE and/or TAO. +# pragma message disable intconlosbit +# endif /* __DECCXX_VER >= 60190029 */ + +# if (__DECCXX_VER == 60190027) + // Seems that this version of cxx doesn't have reset +# define ACE_AUTO_PTR_LACKS_RESET +# endif /* __DECCXX_VER == 60190027 */ + +# if defined (DIGITAL_UNIX) && DIGITAL_UNIX >= 0x40D + // variable "PTHREAD_THIS_CATCH_NP" was declared but never referenced +# pragma message disable declbutnotref +# endif /* DIGITAL_UNIX >= 4.0f */ + +# else /* __DECCXX_VER < 60090010 */ +# define ACE_LACKS_PRAGMA_ONCE +# endif /* __DECCXX_VER < 60090010 */ +#else /* ! __DECCXX */ +# error ace/config-cxx-common.h can only be used with Compaq CXX! +#endif /* ! __DECCXX */ + +#include /**/ "ace/post.h" +#endif /* ACE_CXX_COMMON_H */ diff --git a/dep/acelite/ace/config-cygwin32.h b/dep/acelite/ace/config-cygwin32.h new file mode 100644 index 00000000000..35c517c3ca6 --- /dev/null +++ b/dep/acelite/ace/config-cygwin32.h @@ -0,0 +1,216 @@ +/* -*- C++ -*- */ +// $Id: config-cygwin32.h 87169 2009-10-19 20:26:55Z olli $ + +// The following configuration file is designed to work for CygWin +// platforms using GNU C++. + +#ifndef ACE_CONFIG_CYGWIN32_H +#define ACE_CONFIG_CYGWIN32_H + +#include /**/ "ace/pre.h" + +#if !defined (ACE_MT_SAFE) +#define ACE_MT_SAFE 1 +#endif + +#define CYGWIN32 + +// We trust this file will get included before +#if !defined(FD_SETSIZE) +# define FD_SETSIZE 1024 +#endif + +#if !defined (ACE_IOV_MAX) +# define ACE_IOV_MAX 64 +#endif /* ACE_IOV_MAX */ + +// Define custom export macros for export/import of symbols from/of dll's +#if !defined (ACE_HAS_CUSTOM_EXPORT_MACROS) +# define ACE_HAS_CUSTOM_EXPORT_MACROS 1 +# define ACE_Proper_Export_Flag __declspec (dllexport) +# define ACE_Proper_Import_Flag __declspec (dllimport) +# define ACE_EXPORT_SINGLETON_DECLARATION(T) template class __declspec (dllexport) T +# define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) template class __declspec (dllexport) SINGLETON_TYPE; +# define ACE_IMPORT_SINGLETON_DECLARATION(T) extern template class T +# define ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) extern template class SINGLETON_TYPE ; +#endif + +#define ACE_HAS_SELECT_H + +#define ACE_LACKS_PRAGMA_ONCE + +#if ! defined (__ACE_INLINE__) +# define __ACE_INLINE__ +#endif /* ! __ACE_INLINE__ */ + +#include /**/ + +// Needed to differentiate between libc 5 and libc 6 (aka glibc). +// It's there on all libc 5 systems I checked. +#include /**/ + +// config-g++-common.h undef's ACE_HAS_STRING_CLASS with -frepo, so +// this must appear before its #include. +#define ACE_HAS_STRING_CLASS + +#if defined (__GNUG__) +# include "ace/config-g++-common.h" +#else +# ifdef __cplusplus /* Let it slide for C compilers. */ +# error unsupported compiler in ace/config-cygwin32.h +# endif /* __cplusplus */ +#endif /* __GNUG__ */ + +#define ACE_HAS_VOIDPTR_SOCKOPT 1 +#define ACE_HAS_UALARM 1 +#define ACE_HAS_STRNLEN 1 +#define ACE_HAS_POSIX_GETPWNAM_R 1 +#define ACE_HAS_POSIX_NONBLOCK 1 +#define ACE_HAS_POSIX_TIME +#define ACE_HAS_CLOCK_GETTIME 1 +#define ACE_HAS_TIMEZONE_GETTIMEOFDAY +#define ACE_HAS_MSG +#define ACE_DEFAULT_BASE_ADDR ((char *) 0x8000000) +#define ACE_HAS_NONCONST_SELECT_TIMEVAL +#define ACE_HAS_SVR4_DYNAMIC_LINKING +//#define ACE_HAS_SYSV_IPC +#define ACE_HAS_VOIDPTR_MMAP +#define ACE_HAS_CPLUSPLUS_HEADERS +#define ACE_HAS_POLL +#define ACE_HAS_POSITION_INDEPENDENT_POINTERS 1 +#define ACE_HAS_SOCKADDR_MSG_NAME 1 +#define ACE_LACKS_PRI_T 1 +#define ACE_HAS_3_PARAM_READDIR_R + +// Compiler/platform supports alloca(). +// Although ACE does have alloca() on this compiler/platform combination, it is +// disabled by default since it can be dangerous. Uncomment the following line +// if you want ACE to use it. +//#define ACE_HAS_ALLOCA + +// Compiler/platform has the getrusage() system call. +#define ACE_HAS_GETRUSAGE + +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES + +// Optimize ACE_Handle_Set for select(). +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT + +#define ACE_HAS_IP_MULTICAST + +#define ACE_HAS_BIG_FD_SET + +// Platform has POSIX terminal interface. +#define ACE_HAS_TERMIOS + +#define ACE_DEFAULT_MAX_SOCKET_BUFSIZ 65535 + +#define ACE_DEFAULT_SELECT_REACTOR_SIZE 256 + +#define ACE_HAS_GETPAGESIZE + +#define ACE_HAS_VOIDPTR_GETTIMEOFDAY + +#define ACE_HAS_STRSIGNAL + +// Compiler supports the ssize_t typedef. +#define ACE_HAS_SSIZE_T + +#define ACE_HAS_SOCKLEN_T 1 + +#define ACE_HAS_GPERF + +#define ACE_HAS_DIRENT +#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG + +#define ACE_LACKS_MKFIFO +#define ACE_LACKS_SIGINFO_H +#define ACE_LACKS_UCONTEXT_H +#define ACE_LACKS_STROPTS_H +#define ACE_LACKS_FGETWC 1 +#define ACE_LACKS_NAMED_POSIX_SEM +#define ACE_LACKS_STRRECVFD +#define ACE_LACKS_MADVISE +#define ACE_LACKS_GETPGID_PROTOTYPE +#define ACE_LACKS_GETHOSTENT +#define ACE_LACKS_ITOW 1 +#define ACE_LACKS_LINEBUFFERED_STREAMBUF 1 +#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS 1 +#define ACE_LACKS_RLIMIT +#define ACE_LACKS_RWLOCK_T 1 +#define ACE_LACKS_SUSECONDS_T +#define ACE_LACKS_SYS_SYSCTL_H + +#define ACE_LACKS_FGETWS 1 +#define ACE_LACKS_FPUTWS 1 + +#define ACE_LACKS_WCSTOULL 1 +#define ACE_LACKS_ISCTYPE + +#define ACE_HAS_AUTOMATIC_INIT_FINI + +#define ACE_HAS_SIGWAIT +#define ACE_HAS_SIGINFO_T +#define ACE_HAS_SIGACTION_CONSTP2 +#define ACE_HAS_SIGSUSPEND +#define ACE_HAS_SIG_C_FUNC 1 +#define ACE_HAS_SIG_ATOMIC_T + +#define ACE_HAS_POSIX_SEM + +#define ACE_HAS_P_READ_WRITE + +#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R + +// Cygwin DLL suffix is .dll +#define ACE_DLL_SUFFIX ACE_TEXT (".dll") + +// Cygwin runs on Windows, so we have to get the environment variable PATH and +// not LD_LIBRARY_PATH which is the default in ACE +#define ACE_LD_SEARCH_PATH ACE_TEXT ("PATH") + +#if ACE_MT_SAFE +// Yes, we do have threads. +# define ACE_HAS_THREADS +// And they're even POSIX pthreads (LinuxThreads implementation) +# define ACE_HAS_PTHREADS + +# define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS + +// Compiler/platform has thread-specific storage +# define ACE_HAS_THREAD_SPECIFIC_STORAGE + +# define ACE_HAS_PTHREADS_UNIX98_EXT +# define ACE_HAS_PTHREAD_CONTINUE 1 +# define ACE_HAS_PTHREAD_SUSPEND 1 + +# define ACE_LACKS_PTHREAD_ATTR_SETSTACKADDR +// Cygwin (see pthread.h): Not supported or implemented. +# define ACE_LACKS_SETSCHED +# define ACE_LACKS_SETDETACH +# define ACE_LACKS_PTHREAD_CANCEL +# define ACE_LACKS_THREAD_PROCESS_SCOPING +# define ACE_LACKS_MUTEXATTR_PSHARED +# define ACE_LACKS_RWLOCKATTR_PSHARED +# define ACE_LACKS_PTHREAD_THR_SIGSETMASK 1 +# define ACE_LACKS_PTHREAD_YIELD 1 +# define ACE_LACKS_PTHREAD_ATTR_SETSTACK + +#if CYGWIN_VERSION_API_MINOR < 207 +// In the 1.5.9 release of Cygwin the pthread_kill gives an access violation +// so for the time being we say Cygwin doesn't support pthread_kill. +# define ACE_LACKS_PTHREAD_KILL +#endif + +#endif /* ACE_MT_SAFE */ + +#if CYGWIN_VERSION_API_MINOR >= 207 +// > Cygwin 1.7 +#define ACE_HAS_VWPRINTF +#define ACE_HAS_VFWPRINTF +#define ACE_HAS_VSWPRINTF +#endif + +#include /**/ "ace/post.h" + +#endif /* ACE_CONFIG_CYGWIN32_H */ diff --git a/dep/acelite/ace/config-doxygen.h b/dep/acelite/ace/config-doxygen.h new file mode 100644 index 00000000000..ddd84e88e7a --- /dev/null +++ b/dep/acelite/ace/config-doxygen.h @@ -0,0 +1,128 @@ +// -*- C++ -*- + +/** + * This is a configuration file to define all the macros that Doxygen + * needs + * + * @file config-doxygen.h + * + * $Id: config-doxygen.h 91101 2010-07-15 09:49:28Z johnnyw $ + * + * @author Carlos O'Ryan + * @author Darrell Brunsch + * + */ +#ifndef ACE_CONFIG_DOXYGEN_H +#define ACE_CONFIG_DOXYGEN_H + +/// Make sure that we always turn inlining on. +#define __ACE_INLINE__ + +/// Make the wchar_t interfaces available. +#define ACE_HAS_WCHAR + +/// Make all the emulation versions of string operations visible +// #define ACE_LACKS_WCSTOK +#define ACE_LACKS_ITOW +#define ACE_LACKS_STRCASECMP +#define ACE_LACKS_STRRCHR +#define ACE_LACKS_WCSCAT +#define ACE_LACKS_WCSCHR +#define ACE_LACKS_WCSCMP +#define ACE_LACKS_WCSCPY +#define ACE_LACKS_WCSICMP +#define ACE_LACKS_WCSLEN +#define ACE_LACKS_WCSNCAT +#define ACE_LACKS_WCSNCMP +#define ACE_LACKS_WCSNCPY +#define ACE_LACKS_WCSNICMP +#define ACE_LACKS_WCSPBRK +#define ACE_LACKS_WCSRCHR +#define ACE_LACKS_WCSCSPN +#define ACE_LACKS_WCSSPN +#define ACE_LACKS_WCSSTR + +/// Support for threads enables several important classes +#define ACE_HAS_THREADS + +/// Support for Win32 enables the WFMO_Reactor and several Async I/O +/// classes +#define ACE_WIN32 + +/// Enable support for POSIX Asynchronous I/O calls +#define ACE_HAS_AIO_CALLS + +/// Enable support for TLI interfaces +#define ACE_HAS_TLI + +/// Enable support for the SSL wrappers +#define ACE_HAS_SSL 1 + +/// Enable exceptions +#define ACE_HAS_EXCEPTIONS + +/// Enable timeprobes +#define ACE_COMPILE_TIMEPROBES + +/// Enable unicode to generate ACE_Registry_Name_Space +#define UNICODE + +/// These defines make sure that Svc_Conf_y.cpp and Svc_Conf_l.cpp are correctly +/// parsed +#define __cplusplus +#define ACE_YY_USE_PROTOS + +/// TAO features that should be documented too +#define TAO_HAS_RT_CORBA 1 +#define TAO_HAS_MINIMUM_CORBA 0 +#define TAO_HAS_AMI 1 +#define TAO_HAS_INTERCEPTORS 1 +#define TAO_HAS_SCIOP 1 +#define TAO_HAS_COIOP 1 +#define TAO_HAS_TRANSPORT_CURRENT 1 + +/// Generate token library documentation +#define ACE_HAS_TOKENS_LIBRARY + +/// Generate ACE ATM classes documentation +#define ACE_HAS_ATM + +/// Generate ACE XTI ATM class documentation +#define ACE_HAS_XTI_ATM + +/// Generate ACE_Dev_Poll_Reactor documentation +#define ACE_HAS_DEV_POLL + +/// Generate ACE_Event_Handler_T documentation +#define ACE_HAS_TEMPLATE_TYPEDEFS + +/// Generate ACE_Log_Msg_NT_Event_Log documentation +#define ACE_HAS_LOG_MSG_NT_EVENT_LOG + +/// Generate icmp documentation +#define ACE_HAS_ICMP_SUPPORT 1 + +/// Don't expand ACE_RCSID macro +#define ACE_USE_RCSID 0 + +/// Parse some ACE_SSL classes that depend on recent versions of +/// OpenSSL. +#define OPENSSL_VERSION_NUMBER 0x00905820L + +/// Enable IPv6 +#define ACE_HAS_IPV6 + +/// Enable netlink socket support +#define ACE_HAS_NETLINK + +#define ACE_HAS_IP_MULTICAST + +#define ACE_INLINE +#define ACE_BEGIN_VERSIONED_NAMESPACE_DECL +#define ACE_END_VERSIONED_NAMESPACE_DECL +#define TAO_BEGIN_VERSIONED_NAMESPACE_DECL +#define TAO_END_VERSIONED_NAMESPACE_DECL + +#define ACE_HAS_POSITION_INDEPENDENT_POINTERS 1 + +#endif /* ACE_CONFIG_DOXYGEN_H */ diff --git a/dep/acelite/ace/config-freebsd.h b/dep/acelite/ace/config-freebsd.h new file mode 100644 index 00000000000..b83394ddece --- /dev/null +++ b/dep/acelite/ace/config-freebsd.h @@ -0,0 +1,215 @@ +/* -*- C++ -*- */ +// $Id: config-freebsd.h 87483 2009-11-11 13:50:04Z olli $ + +// The following configuration file is designed to work for FreeBSD + +#ifndef ACE_CONFIG_H +#define ACE_CONFIG_H +#include /**/ "ace/pre.h" + +#if !defined (ACE_MT_SAFE) +# define ACE_MT_SAFE 1 +#endif + +#if ACE_MT_SAFE + // Yes, we do have threads. +# define ACE_HAS_THREADS 1 +#else + // Set to 0 since that's what config-posix.h checks for. +# define ACE_HAS_THREADS 0 +#endif /* ACE_MT_SAFE */ + +#include "ace/config-posix.h" + +// Make sure we source in the OS version. +#include + +#if !defined (__ACE_INLINE__) +# define __ACE_INLINE__ +#endif /* ! __ACE_INLINE__ */ + +#if (__FreeBSD_version < 220000) +# if defined (ACE_HAS_THREADS) +# error Threads are not supported. +# endif /* ACE_HAS_THREADS */ +#endif /* __FreeBSD_version < 220000 */ + +#if defined (__GNUG__) +# include "ace/config-g++-common.h" +#endif /* __GNUG__ */ + +#if defined (ACE_HAS_PENTIUM) +# undef ACE_HAS_PENTIUM +#endif /* ACE_HAS_PENTIUM */ + +// Platform specific directives +// gcc defines __FreeBSD__ automatically for us. +#ifdef ACE_HAS_THREADS +# if !defined (_THREAD_SAFE) +# define _THREAD_SAFE +# endif /* _THREAD_SAFE */ +#endif + + +#define ACE_HAS_3_PARAM_READDIR_R +#define ACE_HAS_3_PARAM_WCSTOK +#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG +#define ACE_HAS_ALLOCA +#define ACE_HAS_ALT_CUSERID +#define ACE_HAS_AUTOMATIC_INIT_FINI +#define ACE_HAS_CHARPTR_DL +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES +#define ACE_HAS_DIRENT +#define ACE_HAS_GETRUSAGE +#define ACE_HAS_GPERF +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT +#define ACE_HAS_IP_MULTICAST +#define ACE_HAS_MSG +#define ACE_HAS_NONCONST_SELECT_TIMEVAL +#define ACE_HAS_POSIX_NONBLOCK +#define ACE_HAS_POSIX_TIME +#define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS +#define ACE_HAS_RTLD_LAZY_V +#define ACE_HAS_SEMUN +#define ACE_HAS_SIGISMEMBER_BUG +#define ACE_HAS_SIGSUSPEND +#define ACE_HAS_SIGWAIT +#define ACE_HAS_SIG_ATOMIC_T +#define ACE_HAS_SOCKADDR_IN6_SIN6_LEN +#define ACE_HAS_SOCKADDR_IN_SIN_LEN +#define ACE_HAS_SSIZE_T +#define ACE_HAS_STRSIGNAL +#define ACE_HAS_SVR4_DYNAMIC_LINKING +#define ACE_HAS_SVR4_SIGNAL_T +#define ACE_HAS_SYSCTL +#define ACE_HAS_SYSV_IPC +#define ACE_HAS_SYS_FILIO_H +#define ACE_HAS_SYS_SOCKIO_H +#define ACE_HAS_SYS_SYSCALL_H +#define ACE_HAS_TERMIOS +#define ACE_HAS_THREAD_SPECIFIC_STORAGE +#define ACE_HAS_TIMEZONE_GETTIMEOFDAY +#define ACE_HAS_UALARM + +#define ACE_LACKS_CONDATTR_PSHARED +#define ACE_LACKS_ISCTYPE +#define ACE_LACKS_ITOW +#define ACE_LACKS_LOG2 +#define ACE_LACKS_MALLOC_H +#define ACE_LACKS_MUTEXATTR_PSHARED +#define ACE_LACKS_SIGINFO_H +#define ACE_LACKS_SI_ADDR +#define ACE_LACKS_STROPTS_H +#define ACE_LACKS_STRRECVFD +#define ACE_LACKS_THREAD_PROCESS_SCOPING +#define ACE_LACKS_TIMESPEC_T +#define ACE_LACKS_WCSDUP +#define ACE_LACKS_WCSICMP +#define ACE_LACKS_WCSNICMP + +#define ACE_NEEDS_SCHED_H + +// Defines the page size of the system. +#define ACE_PAGE_SIZE 4096 + +// Note, on FreeBSD 5, POSIX aio is now an optional kernel module which +// must be loaded. +// Read the aio(4) man page for what to do, otherwise any aio_* call +// will coredump. + +// By default use Proactor which does not use POSIX Real-time Signals. +#ifdef ACE_HAS_AIO_CALLS +# ifndef ACE_POSIX_AIOCB_PROACTOR +# define ACE_POSIX_AIOCB_PROACTOR +# endif /* ACE_POSIX_AIOCB_PROACTOR */ +#endif /* ACE_HAS_AIO_CALLS */ + +#if !defined ACE_LACKS_PERFECT_MULTICAST_FILTERING +# define ACE_LACKS_PERFECT_MULTICAST_FILTERING 1 +#endif /* ACE_LACKS_PERFECT_MULTICAST_FILTERING */ + +// +// Version specific settings +// + +#if (__FreeBSD_version >= 220000) +# define ACE_HAS_VASPRINTF +#endif + +#if (__FreeBSD_version >= 300000) +# define ACE_HAS_SIGINFO_T +#endif /* __FreeBSD_version >= 300000 */ + +#if (__FreeBSD_version >= 320000) +# define ACE_HAS_REENTRANT_FUNCTIONS +# define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS +# define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R +#endif /* __FreeBSD_version >= 320000 */ + +#if (__FreeBSD_version > 400000) +# define ACE_HAS_UCONTEXT_T +# define ACE_HAS_SOCKLEN_T +# define ACE_HAS_GETIFADDRS +# define ACE_HAS_PTHREADS_UNIX98_EXT +#endif + +#if (__FreeBSD_version < 400000) +# define ACE_LACKS_SIGSET +# define ACE_LACKS_RWLOCK_T +# define ACE_LACKS_READDIR_R +# define ACE_LACKS_SETSCHED +# define ACE_LACKS_PTHREAD_THR_SIGSETMASK +# define ACE_LACKS_UCONTEXT_H +# define ACE_LACKS_RAND_REENTRANT_FUNCTIONS + +enum schedparam_policy { + SCHED_RR, + SCHED_IO, + SCHED_FIFO, + SCHED_OTHER +}; +#endif + +#if (__FreeBSD_version < 420000) +# define ACE_LACKS_GETPGID +# define ACE_LACKS_SETPGID +# define ACE_LACKS_SETREGID +# define ACE_LACKS_SETREUID +# define ACE_LACKS_PTHREAD_CANCEL +#endif /* __FreeBSD_version < 420000 */ + +#if (__FreeBSD_version >= 440000) +# define ACE_HAS_GETPROGNAME +# define ACE_HAS_SETPROGNAME +#endif + +#if (__FreeBSD_version < 500100) +# define ACE_HAS_NONCONST_MSGSND +#endif + +#if (__FreeBSD_version < 501000) +# define ACE_LACKS_STDINT_H +# define ACE_LACKS_PWD_REENTRANT_FUNCTIONS +#endif + +#if (__FreeBSD_version >= 501000) +# define ACE_HAS_PTHREAD_SETSTACK +#endif + +#if (__FreeBSD_version < 700007) +# define ACE_HAS_SIGVAL_SIGVAL_INT +# define ACE_HAS_BROKEN_SIGEVENT_STRUCT +#endif + +#if (__FreeBSD_version >= 700028) +# define ACE_HAS_SCTP +# define ACE_HAS_LKSCTP +#endif + +#if (__FreeBSD_version < 700038) +# define ACE_HAS_VOID_UNSETENV +#endif + +#include /**/ "ace/post.h" + +#endif /* ACE_CONFIG_H */ diff --git a/dep/acelite/ace/config-g++-common.h b/dep/acelite/ace/config-g++-common.h new file mode 100644 index 00000000000..dc010182a70 --- /dev/null +++ b/dep/acelite/ace/config-g++-common.h @@ -0,0 +1,183 @@ +// -*- C++ -*- +// +// $Id: config-g++-common.h 89454 2010-03-11 09:35:25Z johnnyw $ + +// This configuration file is designed to be included by another, +// specific configuration file. It provides config information common +// to all g++ platforms, including egcs. + +#ifndef ACE_GNUG_COMMON_H +#define ACE_GNUG_COMMON_H +#include /**/ "ace/pre.h" + +#define ACE_HAS_CPLUSPLUS_HEADERS +#define ACE_HAS_STDCPP_STL_INCLUDES +#define ACE_HAS_TEMPLATE_TYPEDEFS +#define ACE_HAS_STANDARD_CPP_LIBRARY 1 +#define ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR +#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 +#define ACE_TEMPLATES_REQUIRE_SOURCE + +#if ( __GNUC__ == 2 && __GNUC_MINOR__ < 97 ) + // gcc 2.97 and lower use old iostreams +# define ACE_USES_OLD_IOSTREAMS +#endif /* __GNUC__ >= 2.97 */ + +#if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS +#endif /* __GNUC__ >= 3.4 */ + +#if (__GNUC__ < 3) +# define ACE_LACKS_MEMBER_TEMPLATES +# define ACE_LACKS_NUMERIC_LIMITS +#endif /* __GNUC__ < 3 */ + +// __EXCEPTIONS is defined with -fexceptions, the egcs default. It +// is not defined with -fno-exceptions, the ACE default for g++. +// ACE_HAS_EXCEPTIONS is defined in +// include/makeinclude/wrapper_macros.GNU, so this really isn't +// necessary. Just in case . . . +#if defined (__EXCEPTIONS) && !defined (ACE_HAS_EXCEPTIONS) +# define ACE_HAS_EXCEPTIONS +#endif /* __EXCEPTIONS && ! ACE_HAS_EXCEPTIONS */ + +#if defined (ACE_HAS_EXCEPTIONS) +# define ACE_NEW_THROWS_EXCEPTIONS +# if (__GNUC__ >= 4 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 3)) +// Versions of g++ prior to 3.3 had a buggy operator // new(nothrow)[](). +# define ACE_HAS_NEW_NOTHROW +# endif /* __GNUC__ >= 3.3 */ +#endif /* ACE_HAS_EXCEPTIONS */ + +#if (defined (i386) || defined (__i386__)) && !defined (ACE_SIZEOF_LONG_DOUBLE) +# define ACE_SIZEOF_LONG_DOUBLE 12 +#endif /* i386 */ + +#if !defined (__MINGW32__) && (defined (i386) || defined (__i386__)) + // If running an Intel, assume that it's a Pentium so that + // ACE_OS::gethrtime () can use the RDTSC instruction. If running a + // 486 or lower, be sure to comment this out. (If not running an + // Intel CPU, this #define will not be seen because of the i386 + // protection, so it can be ignored.) +# define ACE_HAS_PENTIUM +#endif /* i386 */ + +#if (defined (ACE_HAS_PENTIUM) || defined (__amd64__) || defined (__x86_64__)) +# define ACE_HAS_INTEL_ASSEMBLY +#endif + +#if !defined (ACE_HAS_GCC_CONSTRUCTOR_ATTRIBUTE) +#define ACE_HAS_GCC_CONSTRUCTOR_ATTRIBUTE 1 +#endif + +#if !defined (ACE_HAS_GCC_DESTRUCTOR_ATTRIBUTE) +#define ACE_HAS_GCC_DESTRUCTOR_ATTRIBUTE 1 +#endif + +#if !defined (ACE_HAS_GCC_DEPRECATED_ATTRIBUTE) +#define ACE_HAS_GCC_DEPRECATED_ATTRIBUTE 1 +#endif + +#if (ACE_HAS_GCC_CONSTRUCTOR_ATTRIBUTE == 1) +# define ACE_GCC_CONSTRUCTOR_ATTRIBUTE __attribute__ ((constructor)) +#endif + +#if (ACE_HAS_GCC_DESTRUCTOR_ATTRIBUTE == 1) +# define ACE_GCC_DESTRUCTOR_ATTRIBUTE __attribute__ ((destructor)) +#endif + +#if (ACE_HAS_GCC_DEPRECATED_ATTRIBUTE == 1) +#define ACE_DEPRECATED __attribute__ ((deprecated)) +#endif + +// GNU g++ >= 4.x implements "#pragma once". +#if (__GNUC__ < 4) && !defined (ACE_LACKS_PRAGMA_ONCE) +// We define it with a -D with make depend. +# define ACE_LACKS_PRAGMA_ONCE +#endif /* ! ACE_LACKS_PRAGMA_ONCE */ + +// Take advantage of G++ (>= 4.x) visibility attributes to generate +// improved shared library binaries. +#if (__GNUC__ >= 4) && !defined (__MINGW32__) && !defined (ACE_HAS_CEGCC) + +# if defined (ACE_HAS_CUSTOM_EXPORT_MACROS) && ACE_HAS_CUSTOM_EXPORT_MACROS == 0 +# undef ACE_HAS_CUSTOM_EXPORT_MACROS +# if defined (ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS) +# undef ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS +# endif /* ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS */ +# define ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS 0 +# else +# ifndef ACE_HAS_CUSTOM_EXPORT_MACROS +# define ACE_HAS_CUSTOM_EXPORT_MACROS +# endif /* !ACE_HAS_CUSTOM_EXPORT_MACROS */ +# define ACE_Proper_Export_Flag __attribute__ ((visibility("default"))) +# define ACE_Proper_Import_Flag __attribute__ ((visibility("default"))) + +# if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 2)) +// Sadly, G++ 4.x silently ignores visibility attributes on +// template instantiations, which breaks singletons. +// As a workaround, we use the GCC visibility pragmas. +// And to make them fit in a macro, we use C99's _Pragma() +// http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17470 +// This has been fixed in GCC 4.1.1 with FC6 but not with SuSE 10.2 +// that gets shipped with GCC 4.1.2 so we assume that with GCC 4.2 +// this will be fixed on the head. With FC6 just set this define yourself +# ifndef ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS +# define ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS 1 +# endif +# endif + +# if defined (ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS) && ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS == 1 +# define ACE_EXPORT_SINGLETON_DECLARATION(T) template class ACE_Proper_Export_Flag T +# define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) template class ACE_Proper_Export_Flag SINGLETON_TYPE ; +# else /* ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS */ +# define ACE_EXPORT_SINGLETON_DECLARATION(T) \ + _Pragma ("GCC visibility push(default)") \ + template class T \ + _Pragma ("GCC visibility pop") +# define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) \ + _Pragma ("GCC visibility push(default)") \ + template class SINGLETON_TYPE; \ + _Pragma ("GCC visibility pop") +# endif /* ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS */ + +// Note that the "__extension__" is needed to prevent g++ from issuing +// an error when using its "-pedantic" command line flag. +# define ACE_IMPORT_SINGLETON_DECLARATION(T) __extension__ extern template class T +# define ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) __extension__ extern template class SINGLETON_TYPE; + +# endif /* ACE_HAS_CUSTOM_EXPORT_MACROS == 0 */ +#endif /* __GNU__ >= 4 */ + +// GCC >= 4.1 provides __sync_XXXX builtins for use in atomic operations +// although the builtins are provided globally they are not supported on all platforms +#if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 1)) +# if defined (__powerpc__) +// The builtins seem to be provided for all powerpc platforms +# define ACE_HAS_GCC_ATOMIC_BUILTINS 1 +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ == 1) && (__GNUC_PATCHLEVEL__ == 1)) +// PPU GCC 4.1.1 doesn't have builtin atomic ops for size 1/2 +# define ACE_LACKS_GCC_ATOMIC_BUILTINS_2 +# define ACE_LACKS_GCC_ATOMIC_BUILTINS_1 +# endif +# endif +# if defined (__ia64) +// The builtins seem to be provided for the IA64 platforms +# define ACE_HAS_GCC_ATOMIC_BUILTINS 1 +# endif +# if defined (__amd64__) || defined (__x86_64__) +// The builtin's are provided also for 64bit linux +# define ACE_HAS_GCC_ATOMIC_BUILTINS 1 +# endif +#endif + +#if defined (ACE_HAS_GNU_REPO) + // -frepo causes unresolved symbols of basic_string left- and + // right-shift operators with ACE_HAS_STRING_CLASS. +# if defined (ACE_HAS_STRING_CLASS) +# undef ACE_HAS_STRING_CLASS +# endif /* ACE_HAS_STRING_CLASS */ +#endif /* ! ACE_HAS_GNU_REPO */ + +#include /**/ "ace/post.h" +#endif /* ACE_GNUG_COMMON_H */ diff --git a/dep/acelite/ace/config-ghs-common.h b/dep/acelite/ace/config-ghs-common.h new file mode 100644 index 00000000000..ffa554c047e --- /dev/null +++ b/dep/acelite/ace/config-ghs-common.h @@ -0,0 +1,43 @@ +/* -*- C++ -*- */ +// $Id: config-ghs-common.h 80826 2008-03-04 14:51:23Z wotte $ + +// This configuration file is designed to be included by another, +// specific configuration file. It provides config information common +// to all Green Hills platforms. + +#ifndef ACE_GHS_COMMON_H +#define ACE_GHS_COMMON_H +#include /**/ "ace/pre.h" + +#if !defined (ACE_CONFIG_INCLUDE_GHS_COMMON) +# error ace/config-ghs-common.h: ACE configuration error! Do not #include this file directly! +#endif + +#if defined (ghs) + +# if defined (sun) + // Need nonstatic Object_Manager on Solaris to prevent seg fault + // on startup. +# define ACE_HAS_NONSTATIC_OBJECT_MANAGER +# endif /* sun */ + +# if defined (__STANDARD_CXX) + // Green Hills 1.8.9, but not 1.8.8. +# define ACE_HAS_STANDARD_CPP_LIBRARY 1 +# define ACE_LACKS_AUTO_PTR +# define ACE_LACKS_CHAR_RIGHT_SHIFTS +# define ACE_LACKS_UNBUFFERED_STREAMBUF +# else +# define ACE_HAS_TEMPLATE_INSTANTIATION_PRAGMA +# endif /* __STANDARD_CXX */ + +# define ACE_LACKS_LINEBUFFERED_STREAMBUF +# define ACE_LACKS_LONGLONG_T +# define ACE_LACKS_SIGNED_CHAR + +#else /* ! ghs */ +# error ace/config-ghs-common.h can only be used with Green Hills compilers! +#endif /* ! ghs */ + +#include /**/ "ace/post.h" +#endif /* ACE_GHS_COMMON_H */ diff --git a/dep/acelite/ace/config-hpux-11.00.h b/dep/acelite/ace/config-hpux-11.00.h new file mode 100644 index 00000000000..82420f210f3 --- /dev/null +++ b/dep/acelite/ace/config-hpux-11.00.h @@ -0,0 +1,451 @@ +/* -*- C++ -*- */ +// $Id: config-hpux-11.00.h 89494 2010-03-15 20:11:18Z olli $ + +// The following configuration file is designed to work for HP +// platforms running HP-UX 11.00 using aC++ or gcc (2.95 and up). + +#ifndef ACE_CONFIG_H +#define ACE_CONFIG_H +#include /**/ "ace/pre.h" + +#define ACE_LACKS_STDINT_H +#define ACE_LACKS_SYS_SELECT_H + +#if defined (__GNUG__) + +// config-g++-common.h undef's ACE_HAS_STRING_CLASS with -frepo, so +// this must appear before its #include. +# define ACE_HAS_STRING_CLASS + +# include "ace/config-g++-common.h" + +#else + +// aC++... + +// Precompiler needs extra flags to ignore "invalid #pragma directive" +# ifndef ACE_USING_MCPP_PREPROCESSOR +# define ACE_CC_PREPROCESSOR_ARGS "-E +W 67" +# endif +// Compiler supports C++ exception handling. It's on by default. If the +// +noeh compiler option is used to disable exceptions, the compiler defines +// __HPACC_NOEH. +# if !defined (__HPACC_NOEH) +# define ACE_HAS_EXCEPTIONS 1 +# endif + +// If the -AA compile option is used, the compiler defines _HP_NAMESPACE_STD. +// The -AA option enables the 2.0 standard C++ library. If not used, then +// we have the old, 1.2.1 C++ library. +# if defined (_HP_NAMESPACE_STD) +# if defined (ACE_HAS_STANDARD_CPP_LIBRARY) +# undef ACE_HAS_STANDARD_CPP_LIBRARY +# endif +# define ACE_HAS_STANDARD_CPP_LIBRARY 1 +# if defined (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB) +# undef ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB +# endif +# if defined (RWSTD_NO_NAMESPACE) + namespace std {} using namespace std; +# else +# define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 +# endif /* RWSTD_NO_NAMESPACE */ +# else +# define ACE_USES_OLD_IOSTREAMS + // There's no support in ACE's use of numeric_limits for those that + // aren't in std:: +# define ACE_LACKS_NUMERIC_LIMITS +# endif /* _HP_NAMESPACE_STD */ + +// Compiler implements templates that support typedefs inside of classes +// used as formal arguments to a template class. +# define ACE_HAS_TEMPLATE_TYPEDEFS + +# define ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR + +// Platform lacks streambuf "linebuffered ()". +# define ACE_LACKS_LINEBUFFERED_STREAMBUF 1 + +// Lack of (and broken) support for placement operator delete is a known +// bug by HP, up until aC++ A.03.55.02. +# if (__HP_aCC < 35502) +# define ACE_LACKS_PLACEMENT_OPERATOR_DELETE +# endif /* __HP_aCC < 35502 */ + +// Compiler's 'new' throws exceptions on failure, regardless of whether or +// not exception handling is enabled in the compiler options. Fortunately, +// new(nothrow_t) is offered. +# define ACE_NEW_THROWS_EXCEPTIONS +# define ACE_HAS_NEW_NOTHROW +# define ACE_HAS_NEW_NO_H 1 + +// Compiler's template mechanism must see source code (i.e., .C files). +# define ACE_TEMPLATES_REQUIRE_SOURCE + +// Compiler doesn't handle 'signed char' correctly (used in ace/IOStream.h) +# define ACE_LACKS_SIGNED_CHAR + +#endif /* __GNUG__, HP */ + +//********************************************************************* +// +// From here down is the compiler-INdependent OS settings. +// +//********************************************************************* + +// Compiling for HPUX. +#if !defined (HPUX) +#define HPUX +#endif /* HPUX */ +#define HPUX_11 + +#ifndef _HPUX_SOURCE +#define _HPUX_SOURCE +#endif + +#include /**/ + +// HP-UX is a POSIX-compliant system - see what's available. +#include "ace/config-posix.h" + +// config-posix.h sets up ACE_HAS_AIO_CALLS if the headers define the +// proper things. In HP-UX 11's case, the AIOCB Proactor works the best +// overall. If the user hasn't overridden it, select AIOCB. +#if defined (ACE_HAS_AIO_CALLS) +# if !defined (ACE_POSIX_AIOCB_PROACTOR) && !defined (ACE_POSIX_SIG_PROACTOR) +# define ACE_POSIX_AIOCB_PROACTOR +# endif /* !ACE_HAS_POSIX_AIOCB_PROACTOR && !ACE_POSIX_SIG_PROACTOR */ +#endif /* ACE_HAS_AIO_CALLS */ + +//////////////////////////////////////////////////////////////////////////// +// +// General OS information - see README for more details on what they mean +// +/////////////////////////////////////////////////////////////////////////// + +// HP/UX needs to have these addresses in a special range. +// If this is on a 64-bit model, the default is to use 64-bit addressing. +// It can also be set so that the mapped region is shareable with 32-bit +// programs. To enable the 32/64 sharing, comment out the first definition +// of ACE_DEFAULT_BASE_ADDR and uncomment the two lines after it. +#if defined (__LP64__) +# define ACE_DEFAULT_BASE_ADDR ((char *) 0x0000001100000000) +//# define ACE_DEFAULT_BASE_ADDR ((char *) 0x80000000) +//# define ACE_OS_EXTRA_MMAP_FLAGS MAP_ADDR32 + +# define ACE_DEFAULT_BASE_ADDRL (0x0000001100000000) +//# define ACE_DEFAULT_BASE_ADDRL (0x80000000) +#else +# define ACE_DEFAULT_BASE_ADDR ((char *) 0x80000000) +#endif /* __LP64__ */ + +// Preprocessor needs some help with data types +#if defined (__LP64__) +# define ACE_SIZEOF_LONG 8 +#else +# define ACE_SIZEOF_LONG 4 +#endif + +// Platform can do async I/O (aio_*) (set up in config-posix.h) +// ... but seems to require this in order to keep from hanging. Needs some +// investigation, maybe with HP. John Mulhern determined this value +// empirically. YMMV. If it does vary, set it up in your own config.h which +// then includes the ACE-supplied config. +#if !defined (ACE_INFINITE) +# define ACE_INFINITE 10000000 +#endif + +/* Compiler/platform correctly calls init()/fini() for shared libraries. */ +#define ACE_HAS_AUTOMATIC_INIT_FINI 1 + +// Manually tweak the malloc control block paddings to properly align +// things. +#define ACE_MALLOC_PADDING 16 +#define ACE_MALLOC_ALIGN 8 +#define ACE_PI_CONTROL_BLOCK_ALIGN_LONGS 3 + +// Compiler/platform contains the file. +#define ACE_HAS_SYS_SYSCALL_H + +#define ACE_HAS_SYS_PSTAT_H + +// But doesn't have a prototype for syscall() +#define ACE_LACKS_SYSCALL + +// Platform supports POSIX.1b clock_gettime () +#define ACE_HAS_CLOCK_GETTIME +#define ACE_HAS_CLOCK_SETTIME + +// Prototypes for both signal() and struct sigaction are consistent. +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES + +// Compiler/platform has correctly prototyped header files. +#define ACE_HAS_CPLUSPLUS_HEADERS + +// Compiler/platform has Dirent iterator functions. +#define ACE_HAS_DIRENT + +#define ACE_HAS_VSWPRINTF + +// Platform supports getpagesize() call +#define ACE_HAS_GETPAGESIZE +// But we define this just to be safe +#define ACE_PAGE_SIZE 4096 + +// Can run gperf on this platform (needed for TAO) +# define ACE_HAS_GPERF + +// Optimize ACE_Handle_Set for select(). +# define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT + +// Platform supports IP multicast +#define ACE_HAS_IP_MULTICAST +// At least for 11iv2, lacks perfect filtering. +#if (HPUX_VERS >= 1123) && !defined (ACE_LACKS_PERFECT_MULTICAST_FILTERING) +# define ACE_LACKS_PERFECT_MULTICAST_FILTERING 1 +#endif + +/* Platform defines MAP_FAILED as a long constant. */ +#define ACE_HAS_LONG_MAP_FAILED 1 + +// Platform supports recvmsg and sendmsg. +#define ACE_HAS_MSG + +// Platform's select() has non-const timeval argument +#define ACE_HAS_NONCONST_SELECT_TIMEVAL + +// Compiler/platform supports poll(). +#define ACE_HAS_POLL + +/* Platform supports "position-independent" features provided by + ACE_Based_Pointer<>. */ +#define ACE_HAS_POSITION_INDEPENDENT_POINTERS 1 + +/* Platform supports POSIX getpwnam_r() function */ +#define ACE_HAS_POSIX_GETPWNAM_R 1 + +// Platform supports POSIX O_NONBLOCK semantics. +#define ACE_HAS_POSIX_NONBLOCK + +// Platform supports the POSIX struct timespec type +#define ACE_HAS_POSIX_TIME + +/* Platform has pread() and pwrite() support. */ +#define ACE_HAS_P_READ_WRITE 1 + +/* Platform will recurse infinitely on thread exits from TSS cleanup routines + (e.g., AIX) */ +#define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS 1 + +// Platform supports reentrant functions (all the POSIX *_r functions). +#define ACE_HAS_REENTRANT_FUNCTIONS +// ctime_r and asctime_r conform to POSIX.1c (2 param version) +#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R + +// Platform offers scandir(), and requires no adjustments for its API. +#define ACE_HAS_SCANDIR + +// HP-UX 11 has reentrant netdb functions. The catch is that the old +// functions (gethostbyname, etc.) are thread-safe and the _r versions are +// not used and will be removed at some point. So, define things so +// the _r versions are not used. This will slow things down a bit due to +// the extra mutex lock in the ACE_NETDBCALL_RETURN macro, and will be fixed +// in the future (problem ID P64). +#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS + +/* Platform lacks pri_t (e.g., Tandem NonStop UNIX). */ +#define ACE_LACKS_PRI_T 1 + +// Platform has shm_open +#define ACE_HAS_SHM_OPEN + +// Compiler/platform defines the sig_atomic_t typedef +#define ACE_HAS_SIG_ATOMIC_T + +/* Compiler requires extern "C" functions for signals. */ +#define ACE_HAS_SIG_C_FUNC 1 + +// Platform's sigaction() function takes const sigaction* as 2nd parameter. +#define ACE_HAS_SIGACTION_CONSTP2 + +#define ACE_HAS_SSIZE_T + +// Platform supports SVR4 extended signals +#define ACE_HAS_SIGINFO_T + +/* Define to 1 if platform has sigsuspend(). */ +#define ACE_HAS_SIGSUSPEND 1 + +// Platform doesn't detect a signal out of range unless it's way out of range. +#define ACE_HAS_SIGISMEMBER_BUG + +/* Platform provides socklen_t type, such as Linux with glibc2. */ +#define ACE_HAS_SOCKLEN_T 1 + +#define ACE_HAS_XPG4_MULTIBYTE_CHAR + +#define ACE_HAS_UALARM + +// Platform supports ucontext_t (which is used in the extended signal API). +#define ACE_HAS_UCONTEXT_T + +// Platform/compiler supports void * as second parameter to gettimeofday(). +#define ACE_HAS_VOIDPTR_GETTIMEOFDAY + +/* Platform requires void * for mmap(). */ +#define ACE_HAS_VOIDPTR_MMAP 1 + +/* OS/compiler uses void * arg 4 setsockopt() rather than const char * */ +#define ACE_HAS_VOIDPTR_SOCKOPT 1 + +// Platform supports SVR4 dynamic linking semantics. +// When used, this requires -ldl on the ACE library link line. +#define ACE_HAS_SVR4_DYNAMIC_LINKING + +// Platform supports the getrusage() system call. +#define ACE_HAS_GETRUSAGE + +/* Define to 1 if platform has the declaration of getrusage(). */ +#define ACE_HAS_GETRUSAGE_PROTOTYPE 1 + +// Platform has the sigwait function in a header file +#define ACE_HAS_SIGWAIT +#define ACE_HAS_SIGTIMEDWAIT + +// Platform supports System V IPC (most versions of UNIX, but not Win32) +#define ACE_HAS_SYSV_IPC + +// accept() is thread-safe +#define ACE_HAS_THREAD_SAFE_ACCEPT + +// Platform lacks a typedef for timespec_t, but has struct timespec +#define ACE_LACKS_TIMESPEC_T + +// dlopen() takes a char* instead of const char* +#define ACE_HAS_CHARPTR_DL + +// lacks setegid and seteuid +#define ACE_LACKS_SETEGID +#define ACE_LACKS_SETEUID + +#define ACE_LACKS_SUSECONDS_T +#define ACE_LACKS_SYS_SYSCTL_H + +// @@ TODO: It looks like HP-UX provides strtoll, strtoull, wcstoll and +// wcstoull but some more work is needed to plug them in correctly. +#define ACE_LACKS_STRTOLL +#define ACE_LACKS_WCSTOLL +#define ACE_LACKS_STRTOULL +#define ACE_LACKS_WCSTOULL + +#define ACE_LACKS_ISWASCII + +#define ACE_LACKS_SETENV +#define ACE_LACKS_UNSETENV + +// Shared library name/path components +#if defined (__ia64) +# define ACE_DLL_SUFFIX ACE_TEXT (".so") +#else +# define ACE_DLL_SUFFIX ACE_TEXT (".sl") +#endif /* __ia64 */ +#if defined (__LP64__) +# define ACE_LD_SEARCH_PATH ACE_TEXT ("LD_LIBRARY_PATH") +#else +# define ACE_LD_SEARCH_PATH ACE_TEXT ("SHLIB_PATH") +#endif /* __LP64__ */ + +#if defined (_INCLUDE__STDC_A1_SOURCE) +# define ACE_HAS_3_PARAM_WCSTOK +#endif + +#define ACE_HAS_3_PARAM_READDIR_R + +#define ACE_LACKS_STRUCT_LIFNUM + +////////////////////////////////////////////////////////////////////////// +// +// STREAMS information +// +////////////////////////////////////////////////////////////////////////// + +// Platform supports STREAMS +#define ACE_HAS_STREAMS +// Compiler/platform supports struct strbuf. +#define ACE_HAS_STRBUF_T +// But the putmsg signature doesn't have it as const... +// Well, it really does, but it depends on preprocessor defines. +#define ACE_LACKS_CONST_STRBUF_PTR +/* Platform supports TLI timod STREAMS module */ +#define ACE_HAS_TIMOD_H 1 + +// Platform supports STREAM pipes +// This is possible, but not by default - need to rebuild the kernel to +// get them enabled - see pipe(2) and "STREAMS/UX for the HP 9000" +// #define ACE_HAS_STREAM_PIPES + +///////////////////////////////////////////////////////////////////////// +// +// TLI/XTI information +// +//////////////////////////////////////////////////////////////////////// + +// Platform supports XTI (includes TLI). +#define ACE_HAS_XTI +// HP-UX 11 conforms to the XPG4 spec, which ACE calls broken for the +// errmsg not being const... +#define ACE_HAS_BROKEN_T_ERROR +// The definitions of TCP_NODELAY and TCP_MAXSEG conflict between +// sys/xti.h and netinet/tcp.h. +#define ACE_HAS_CONFLICTING_XTI_MACROS +/* Platform provides header */ +#define ACE_HAS_SYS_XTI_H 1 + +///////////////////////////////////////////////////////////////////////// +// +// Threads information. +// +// Use of threads is controlled by the 'threads' argument to make. See +// include/makeinclude/platform_hpux_aCC.GNU for details. If it's not set, +// the default is to enable it, since kernel threads are always available +// on HP-UX 11, as opposed to 10.x where it was optional software. +// +//////////////////////////////////////////////////////////////////////// + +#if defined (ACE_HAS_THREADS) +# if (ACE_HAS_THREADS == 0) +# undef ACE_HAS_THREADS +# endif /* ACE_HAS_THREADS == 0 */ +#else +# define ACE_HAS_THREADS +#endif /* ACE_HAS_THREADS */ + +#if defined (ACE_HAS_THREADS) + +# if !defined (ACE_MT_SAFE) +# define ACE_MT_SAFE 1 +# endif + +// HP-UX doesn't define _POSIX_THREADS since it doesn't implement all +// features (lacks thread priority inheritance and protection), so +// config-posix.h doesn't get this one... +# define ACE_HAS_PTHREADS +# define ACE_HAS_PTHREADS_UNIX98_EXT +# define ACE_HAS_PTHREAD_CONTINUE +# define ACE_HAS_PTHREAD_RESUME_NP +# define ACE_HAS_PTHREAD_SUSPEND +# define ACE_HAS_RECURSIVE_MUTEXES +# define ACE_HAS_THREAD_SPECIFIC_STORAGE +# define ACE_LACKS_PTHREAD_ATTR_SETSTACK +#endif /* ACE_HAS_THREADS */ + +#define ACE_HAS_POSIX_SEM + +// Platform has POSIX terminal interface. +#define ACE_HAS_TERMIOS + +// gethostbyaddr does not handle IPv6-mapped-IPv4 addresses +#define ACE_HAS_BROKEN_GETHOSTBYADDR_V4MAPPED + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_H */ diff --git a/dep/acelite/ace/config-icc-common.h b/dep/acelite/ace/config-icc-common.h new file mode 100644 index 00000000000..1ebd0c52ed7 --- /dev/null +++ b/dep/acelite/ace/config-icc-common.h @@ -0,0 +1,113 @@ +// -*- C++ -*- +// +// $Id: config-icc-common.h 81935 2008-06-12 22:01:53Z jtc $ + +#ifndef ACE_LINUX_ICC_COMMON_H +#define ACE_LINUX_ICC_COMMON_H +#include /**/ "ace/pre.h" + +# define ACE_HAS_CPLUSPLUS_HEADERS +# define ACE_HAS_STDCPP_STL_INCLUDES +# define ACE_HAS_TEMPLATE_TYPEDEFS +# define ACE_HAS_STANDARD_CPP_LIBRARY 1 +# define ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR +# define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 +# define ACE_HAS_STRING_CLASS + +#if defined (ACE_HAS_CUSTOM_EXPORT_MACROS) && ACE_HAS_CUSTOM_EXPORT_MACROS == 0 +# undef ACE_HAS_CUSTOM_EXPORT_MACROS +# if defined (ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS) +# undef ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS +# endif /* ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS */ +# define ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS 0 +#else +# ifndef ACE_HAS_CUSTOM_EXPORT_MACROS +# define ACE_HAS_CUSTOM_EXPORT_MACROS +# endif /* !ACE_HAS_CUSTOM_EXPORT_MACROS */ +# define ACE_Proper_Export_Flag __attribute__ ((visibility("default"))) +# define ACE_Proper_Import_Flag __attribute__ ((visibility("default"))) + +# if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 2)) +// Sadly, G++ 4.x silently ignores visibility attributes on +// template instantiations, which breaks singletons. +// As a workaround, we use the GCC visibility pragmas. +// And to make them fit in a macro, we use C99's _Pragma() +// http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17470 +// This has been fixed in GCC 4.1.1 with FC6 but not with SuSE 10.2 +// that gets shipped with GCC 4.1.2 so we assume that with GCC 4.2 +// this will be fixed on the head. With FC6 just set this define yourself +# ifndef ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS +# define ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS 1 +# endif +# endif + +# if defined (ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS) && ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS == 1 +# define ACE_EXPORT_SINGLETON_DECLARATION(T) template class ACE_Proper_Export_Flag T +# define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) template class ACE_Proper_Export_Flag SINGLETON_TYPE ; +# else /* ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS */ +# define ACE_EXPORT_SINGLETON_DECLARATION(T) \ + _Pragma ("GCC visibility push(default)") \ + template class T \ + _Pragma ("GCC visibility pop") +# define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) \ + _Pragma ("GCC visibility push(default)") \ + template class SINGLETON_TYPE; \ + _Pragma ("GCC visibility pop") +# endif /* ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS */ + +// Note that the "__extension__" is needed to prevent g++ from issuing +// an error when using its "-pedantic" command line flag. +# define ACE_IMPORT_SINGLETON_DECLARATION(T) __extension__ extern template class T +# define ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) __extension__ extern template class SINGLETON_TYPE; +#endif /* ACE_HAS_CUSTOM_EXPORT_MACROS == 0 */ + +// __EXCEPTIONS is defined with -fexceptions, the egcs default. It +// is not defined with -fno-exceptions, the ACE default for g++. +// ACE_HAS_EXCEPTIONS is defined in +// include/makeinclude/wrapper_macros.GNU, so this really isn't +// necessary. Just in case . . . +# if defined (__EXCEPTIONS) && !defined (ACE_HAS_EXCEPTIONS) +# define ACE_HAS_EXCEPTIONS +# endif /* __EXCEPTIONS && ! ACE_HAS_EXCEPTIONS */ + +# if defined (ACE_HAS_EXCEPTIONS) +# define ACE_NEW_THROWS_EXCEPTIONS +# endif /* ACE_HAS_EXCEPTIONS */ + +#if (defined (i386) || defined (__i386__)) && !defined (ACE_SIZEOF_LONG_DOUBLE) +# define ACE_SIZEOF_LONG_DOUBLE 12 +#endif /* i386 */ + +#if !defined (__MINGW32__) && (defined (i386) || defined (__i386__)) + // If running an Intel, assume that it's a Pentium so that + // ACE_OS::gethrtime () can use the RDTSC instruction. If running a + // 486 or lower, be sure to comment this out. (If not running an + // Intel CPU, this #define will not be seen because of the i386 + // protection, so it can be ignored.) +# define ACE_HAS_PENTIUM +#endif /* i386 */ + +#if (defined (ACE_HAS_PENTIUM) || defined (__amd64__) || defined (__x86_64__)) +# define ACE_HAS_INTEL_ASSEMBLY +#endif + +#if !defined (ACE_LACKS_PRAGMA_ONCE) + // We define it with a -D with make depend. +# define ACE_LACKS_PRAGMA_ONCE +#endif /* ! ACE_LACKS_PRAGMA_ONCE */ + +#define ACE_TEMPLATES_REQUIRE_SOURCE + +#if (__INTEL_COMPILER >= 910) +# define ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS +#endif + +#if defined (__ia64) +# define ACE_HAS_IA64INTRIN_H +# define ACE_HAS_INTRINSIC_INTERLOCKED +#else +# define ACE_HAS_IA32INTRIN_H +#endif + +#include /**/ "ace/post.h" +#endif /* ACE_LINUX_ICC_COMMON_H */ diff --git a/dep/acelite/ace/config-integritySCA.h b/dep/acelite/ace/config-integritySCA.h new file mode 100644 index 00000000000..41afec58758 --- /dev/null +++ b/dep/acelite/ace/config-integritySCA.h @@ -0,0 +1,229 @@ +// -*- C++ -*- + +#ifndef ACE_INT_CONFIG_H +#define ACE_INT_CONFIG_H + +/* + * This config.h file is for version 4.0.x of the + * Integrity RTOS with SCA from Green Hills Software + * http://www.ghs.com/products/rtos/integrity.html + * + * $Id: config-integritySCA.h 88501 2010-01-12 19:41:53Z olli $ + */ + +#define ghs +/* compilation defines */ +#define ACE_LACKS_GETPGID +#define ACE_LACKS_SETPGID +#define ACE_LACKS_SETREUID +#define ACE_LACKS_SETREGID +#define ACE_LACKS_SETSID +#define ACE_LACKS_SETEGID +#define ACE_LACKS_SETUID +#define ACE_LACKS_SETEUID +#define ACE_LACKS_GETEUID +#define ACE_LACKS_GETUID +#define ACE_LACKS_GETEGID +#define ACE_LACKS_GETGID + +#ifndef ACE_HAS_EXCEPTIONS + #define ACE_HAS_EXCEPTIONS +#endif +#define ACE_NEW_THROWS_EXCEPTIONS +#define ACE_HAS_STANDARD_CPP_LIBRARY 1 +#define ACE_TEMPLATES_REQUIRE_SOURCE 1 +#define ACE_HAS_TEMPLATE_TYPEDEFS +#define TAO_USE_SEQUENCE_TEMPLATES +#define ACE_NEEDS_FUNC_DEFINITIONS +#define _REENTRANT +#define ACE_MT_SAFE 1 + +// Compiler/platform has correctly prototyped header files. +#define ACE_HAS_CPLUSPLUS_HEADERS + +#define ACE_HAS_SHM_OPEN + +/***** Operating System Defines *****/ + +/***** ANSI defines *****/ +#define ACE_LACKS_TEMPNAM /* believe it or not, this is ANSI C */ +#define ACE_LACKS_PUTENV_PROTOTYPE + +#define ACE_LACKS_SENDMSG + +/***** End Stack Defines *****/ + + +/* SCA STUFF */ +#if defined(INTEGRITY_VERSION) && (INTEGRITY_VERSION >= 40108) +#define ACE_HAS_SIG_ATOMIC_T +#endif /* INTEGRITY_VERSION */ +#define ACE_HAS_SIGWAIT +#define ACE_HAS_SIGACTION +#define ACE_HAS_SIGINFO_T +#define ACE_LACKS_SIGINFO_H +#define ACE_LACKS_UCONTEXT_H +#define ACE_HAS_SIG_C_FUNC +#define ACE_LACKS_SI_ADDR +#define ACE_HAS_AIO_CALLS + +#define ACE_HAS_POSIX_NONBLOCK +#define ACE_HAS_DIRENT + +#define ACE_HAS_THREADS + +#define ACE_HAS_PTHREADS +/***** End Threading Defines *****/ + +/***** Hardware Defines *****/ +#define ACE_PAGE_SIZE 4096 +/***** End Hardware Defines *****/ + +/****** SYSV_IPC STUFF *****/ +#define ACE_LACKS_KEY_T + +/****** Posix Defines *****/ +#define ACE_LACKS_WAIT +#define ACE_LACKS_WAITPID +#define ACE_HAS_POSIX_TIME +#define ACE_HAS_POSIX_SEM +#define ACE_HAS_STRDUP_EMULATION +#define ACE_HAS_MSG +#define ACE_LACKS_CONDATTR_PSHARED +#define ACE_LACKS_EXEC +#define ACE_LACKS_FORK +#define ACE_LACKS_MKFIFO +#define ACE_LACKS_MKTEMP +#define ACE_LACKS_MKSTEMP +#define ACE_LACKS_MPROTECT +#define ACE_LACKS_MUTEXATTR_PSHARED +#define ACE_LACKS_PIPE +#define ACE_LACKS_RLIMIT +#define ACE_LACKS_RECVMSG +#define ACE_LACKS_RWLOCK_T +#define ACE_LACKS_SEMBUF_T +#define ACE_LACKS_UNIX_DOMAIN_SOCKETS +#define ACE_LACKS_FCNTL +#define ACE_LACKS_UMASK +#define ACE_LACKS_SEEK +#define ACE_LACKS_MSYNC +#define ACE_LACKS_PID_STUFF +#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS +#define ACE_LACKS_IPC_H +#define ACE_LACKS_SETGID +#define ACE_LACKS_PIPE +#define ACE_LACKS_SYS_PARAM_H +#define ACE_LACKS_SYS_MSG_H +#define ACE_LACKS_UTSNAME_T +#define ACE_LACKS_UNAME +#define ACE_LACKS_UMASK +#define ACE_LACKS_ISATTY +#define ACE_LACKS_GETOPT +#define ACE_LACKS_STRCASECMP +#define ACE_LACKS_TRUNCATE +#define ACE_LACKS_PWD_FUNCTIONS +#define ACE_LACKS_UNIX_SIGNALS +#define ACE_HAS_THREAD_SPECIFIC_STORAGE +#define ACE_LACKS_SYSV_SHMEM +#define ACE_LACKS_PUTENV +#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG +#define ACE_HAS_CLOCK_GETTIME +#define ACE_HAS_CLOCK_SETTIME +#define ACE_LACKS_THREAD_PROCESS_SCOPING +#define ACE_LACKS_SETSCHED +#define ACE_LACKS_STRRECVFD +#define ACE_LACKS_WRITEV +#define ACE_LACKS_READV +#define ACE_LACKS_SYSCONF +#define ACE_LACKS_GETOPT +/* below refers to fcntl style locking */ +#define ACE_LACKS_FILELOCKS + +#define ACE_LACKS_REALPATH +#define ACE_HAS_CONST_CHAR_SWAB +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES + +/***** Not tied to standards AFAIK ****/ +#define ACE_LACKS_MADVISE /* paging optimization not needed with INTEGRITY */ +#define ACE_LACKS_MALLOC_H /* netbsd's just includes stdlib.h */ +#define ACE_LACKS_MEMORY_H /* netbsd's just includes string.h */ +#define ACE_LACKS_INTTYPES_H +#define ACE_LACKS_SYS_RESOURCE_H +#define ACE_LACKS_SYS_WAIT_H +#define ACE_LACKS_SEARCH_H +#define ACE_LACKS_SYS_IPC_H +#define ACE_LACKS_SYS_SEM_H +#define ACE_LACKS_PWD_H +#define ACE_LACKS_STROPTS_H +#define ACE_LACKS_DLFCN_H +#define ACE_LACKS_REGEX_H +#define ACE_LACKS_POLL_H +#define ACE_LACKS_SYS_SHM_H +#define ACE_LACKS_TERMIOS_H + +/***** STUFF INTEGRITY 4.0.8 APPEARS TO SUPPORT ****/ +/* note, possibly untested with ace */ + +/***** TAO STUFF ****/ +#define TAO_USE_DOTTED_DECIMAL_ADDRESSES 1 + +#include + +#include + +typedef void (*__sighandler_t)(int); + +extern "C" +{ + inline int isatty(int) { return 0; } +} + +#ifdef ppc +#define ACE_HAS_POWERPC_TIMER +#endif + +/* MIKEC Addtions */ +#define ACE_HAS_NONCONST_SELECT_TIMEVAL +#include // needed to define iovec +#define ACE_LACKS_READLINK +#define ACE_LACKS_GETPPID +#define NSIG (SIGRTMAX+1) +#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 +#define ACE_USE_RCSID 0 +#define ACE_LACKS_CUSERID +#define ACE_NEEDS_HUGE_THREAD_STACKSIZE 0x5000 +#define fileno(file) ((file)->io_channel) //Hack to get Svc_Conf_l.cpp compiled +#define ACE_DEFAULT_THREAD_PRIORITY 127 +#define PRI_FIFO_MIN 1 +#define PRI_FIFO_MAX 127 +#define ACE_THR_PRI_FIFO_DEF 127 +#define PRI_RR_MIN 1 +#define PRI_RR_MAX 127 +#define ACE_THR_PRI_RR_DEF 127 +#define PRI_OTHER_MIN 1 +#define PRI_OTHER_MAX 127 +#define ACE_THR_PRI_OTHER_DEF 127 +#define ACE_PTHREAD_RETURN_ON_EXIT +#undef ACE_LACKS_UNLINK + +#define ACE_HAS_TIMED_MESSAGE_BLOCKS + +extern "C" { +int unlink(const char *); +} + +#define ACE_LACKS_SETSID +#define ACE_HAS_VOIDPTR_GETTIMEOFDAY +#define ACE_LACKS_UNIX_SYSLOG +#define ACE_LACKS_TELLDIR +#define ACE_LACKS_SEEKDIR +#define ACE_LACKS_GETHOSTENT + + +/* end MIKEC Addtions */ + +// Hack to avoid ensure that things defined in ind_io.h +// have the right linkage +#include + +#endif /* ACE_CONFIG_H */ diff --git a/dep/acelite/ace/config-irix6.5.x-sgic++.h b/dep/acelite/ace/config-irix6.5.x-sgic++.h new file mode 100644 index 00000000000..2d501010b68 --- /dev/null +++ b/dep/acelite/ace/config-irix6.5.x-sgic++.h @@ -0,0 +1,18 @@ +// -*- C++ -*- +// $Id: config-irix6.5.x-sgic++.h 80826 2008-03-04 14:51:23Z wotte $ + +// Use this file for IRIX 6.5.x + +#ifndef ACE_CONFIG_IRIX65X_H +#define ACE_CONFIG_IRIX65X_H +#include /**/ "ace/pre.h" + +// Include IRIX 6.[234] configuration +#include "ace/config-irix6.x-sgic++.h" + +// Irix 6.5 man pages show that they exist +#undef ACE_LACKS_CONDATTR_PSHARED +#undef ACE_LACKS_MUTEXATTR_PSHARED + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_IRIX65X_H */ diff --git a/dep/acelite/ace/config-irix6.x-common.h b/dep/acelite/ace/config-irix6.x-common.h new file mode 100644 index 00000000000..1de756d530c --- /dev/null +++ b/dep/acelite/ace/config-irix6.x-common.h @@ -0,0 +1,254 @@ +/* -*- C++ -*- */ +// +// $Id: config-irix6.x-common.h 87167 2009-10-19 19:33:53Z olli $ +// +// This file contains the common configuration options for both +// SGI/MIPSPro C++ and g++ under IRIX 6.X +// +// For IRIX 6.2 there are several patches that should be applied to +// get reliable operation with multi-threading and exceptions. +// Specifically you should get a reasonable current IRIX, Compiler +// and POSIX patch-sets. + +// For IRIX 6.[34] it's less critical, but it's still recommended +// that you apply the applicable patch-sets (IRIX and Compiler I believe). + +// These patches are updated frequently, so you should ask your support +// contact or search SGI's web site (http://www.sgi.com) for the latest +// version. + +// Use this file for IRIX 6.[234] if you have the pthreads patches +// installed. + +#ifndef ACE_CONFIG_IRIX6X_COMMON_H + +#ifndef IRIX6 +# define IRIX6 +#endif + +#if ! defined(ACE_CONFIG_H) +#error "This file may only be included by config-irix6.x-sgic++.h, config-irix6.x-kcc.h or config-irix6.x-g++.h" +#endif + +// The Irix 6.x float.h doesn't allow us to distinguish between a +// double and a long double. So, we have to hard-code this. Thanks +// to Bob Laferriere for figuring it out. +#if defined (_MIPS_SIM) /* 6.X System */ +# include +# if defined (__GNUC__) +# define ACE_SIZEOF_LONG_DOUBLE 16 +# elif defined (_MIPS_SIM_NABI32) && (_MIPS_SIM == _MIPS_SIM_NABI32) +# define ACE_SIZEOF_LONG_DOUBLE 16 +# elif defined (_MIPS_SIM_ABI32) && (_MIPS_SIM == _MIPS_SIM_ABI32) +# define ACE_SIZEOF_LONG_DOUBLE 8 +# elif defined (_MIPS_SIM_ABI64) && (_MIPS_SIM == _MIPS_SIM_ABI64) +# define ACE_SIZEOF_LONG_DOUBLE 16 +# elif !defined (ACE_SIZEOF_LONG_DOUBLE) +# define ACE_SIZEOF_LONG_DOUBLE 8 +# endif +#else +# define ACE_SIZEOF_LONG_DOUBLE 8 /* 5.3 System */ +#endif + +// petern, Next part of it: + +// Platform supports getpagesize() call. +#define ACE_HAS_GETPAGESIZE + +// Platform has no implementation of pthread_condattr_setpshared(), +// even though it supports pthreads! (like Irix 6.2) +#define ACE_LACKS_CONDATTR_PSHARED +#define ACE_LACKS_MUTEXATTR_PSHARED + +#define ACE_LACKS_SUSECONDS_T + +// Platform/compiler has the sigwait(2) prototype +#define ACE_HAS_SIGWAIT +#define ACE_HAS_SIGTIMEDWAIT +#define ACE_HAS_SIGSUSPEND + +// Platform supports System V IPC (most versions of UNIX, but not Win32) +#define ACE_HAS_SYSV_IPC + +// Platform requires void * for mmap(). +#define ACE_HAS_VOIDPTR_MMAP + +// Platform supports recvmsg and sendmsg. +#define ACE_HAS_MSG + +// Compiler/platform contains the file. +#define ACE_HAS_SYS_SYSCALL_H + +// Compiler/platform supports alloca() +// Although ACE does have alloca() on this compiler/platform combination, it is +// disabled by default since it can be dangerous. Uncomment the following line +// if you ACE to use it. +//#define ACE_HAS_ALLOCA + +// Compiler/platform has +#define ACE_HAS_ALLOCA_H + +// Irix needs to define bzero() in this odd file +#define ACE_HAS_BSTRING + +// Compiler/platform has the getrusage() system call. +#define ACE_HAS_GETRUSAGE + +// Platform supports POSIX O_NONBLOCK semantics. +#define ACE_HAS_POSIX_NONBLOCK + +// Compiler/platform has correctly prototyped header files. +#define ACE_HAS_CPLUSPLUS_HEADERS + +// Platform contains . +#define ACE_HAS_POLL + +// Platform supports the /proc file system. +#define ACE_HAS_PROC_FS + +// Compiler/platform defines the sig_atomic_t typedef. +#define ACE_HAS_SIG_ATOMIC_T + +// Platform supports SVR4 extended signals. +#define ACE_HAS_SIGINFO_T +#define ACE_HAS_UCONTEXT_T + +// Compiler supports the ssize_t typedef. +#define ACE_HAS_SSIZE_T + +// Platform supports STREAMS. +#define ACE_HAS_STREAMS + +// Compiler/platform supports struct strbuf. +#define ACE_HAS_STRBUF_T + +// Compiler/platform supports SVR4 dynamic linking semantics. +#define ACE_HAS_SVR4_DYNAMIC_LINKING + +// Platform provides header. +#define ACE_HAS_SYS_FILIO_H + +// Compiler/platform defines a union semun for SysV shared memory. +#define ACE_HAS_SEMUN + +// Platform supports IP multicast +#define ACE_HAS_IP_MULTICAST +#ifdef ACE_LACKS_PERFECT_MULTICAST_FILTERING + #undef ACE_LACKS_PERFECT_MULTICAST_FILTERING +#endif +#define ACE_LACKS_PERFECT_MULTICAST_FILTERING 1 + +//************************************************************** +// Not so sure how next lines should look like + +// Platform supports POSIX timers via timestruc_t. +#define ACE_HAS_POSIX_TIME + +//************************************************************** + +// IRIX 6.4 and below do not support reentrant netdb functions +// (getprotobyname_r, getprotobynumber_r, gethostbyaddr_r, +// gethostbyname_r, getservbyname_r). +#if (ACE_IRIX_VERS <= 64) && !defined (ACE_HAS_NETDB_REENTRANT_FUNCTIONS) +#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS +#endif /* ACE_HAS_NETDB_REENTRANT_FUNCTIONS */ + +#define ACE_HAS_DIRENT +// Unless the thread enabled version is used the readdir_r interface +// does not get defined in IRIX 6.2 +#define ACE_LACKS_READDIR_R +#define ACE_LACKS_RWLOCK_T + +#define ACE_HAS_GPERF + +#define ACE_HAS_NONCONST_SELECT_TIMEVAL +#define ACE_HAS_BROKEN_DGRAM_SENDV + +#define ACE_LACKS_PLACEMENT_OPERATOR_DELETE +#define ACE_PI_CONTROL_BLOCK_ALIGN_LONGS 2 + +// Platform has POSIX terminal interface. +#define ACE_HAS_TERMIOS + +// IRIX 6.5 supports AIO +#define ACE_HAS_AIO_CALLS +#define ACE_POSIX_AIOCB_PROACTOR +#define ACE_HAS_SGIDLADD +#define ACE_HAS_P_READ_WRITE +#define ACE_LACKS_LINEBUFFERED_STREAMBUF +#define ACE_LACKS_STDINT_H +#define ACE_HAS_SYSENT_H +#define ACE_HAS_SYSV_SYSINFO +#define ACE_HAS_SYS_SYSTEMINFO_H + +// Platform has support for multi-byte character support compliant +// with the XPG4 Worldwide Portability Interface wide-character +// classification. +#define ACE_HAS_XPG4_MULTIBYTE_CHAR + +// We need to setup a very high address or Naming_Test won't run. +#define ACE_DEFAULT_BASE_ADDR ((char *) (1024U * 1024 * 1024)) + +#define ACE_LACKS_SIGNED_CHAR + +// Platform supports reentrant functions (i.e., all the POSIX *_r +// functions). +#define ACE_HAS_REENTRANT_FUNCTIONS + +// Optimize ACE_Handle_Set for select(). +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT + +// Platform does not support reentrant password file accessor functiions. +#define ACE_LACKS_PWD_REENTRANT_FUNCTIONS + +// uses ctime_r & asctime_r with only two parameters vs. three +#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R + +// Prototypes for both signal() and struct sigaction are consistent. +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES + +#define ACE_HAS_UALARM + +// Scheduling functions are declared in +#define ACE_NEEDS_SCHED_H + +// Compile using multi-thread libraries by default +#if !defined (ACE_MT_SAFE) + #define ACE_MT_SAFE 1 +#endif /* ACE_MT_SAFE */ + +#if (ACE_MT_SAFE != 0) + +// Add threading support + +#define ACE_HAS_IRIX62_THREADS + +// Needed for the threading stuff? +#include /**/ +#define PTHREAD_MIN_PRIORITY PX_PRIO_MIN +#define PTHREAD_MAX_PRIORITY PX_PRIO_MAX + +// ACE supports threads. +#define ACE_HAS_THREADS + +// Platform has no implementation of pthread_condattr_setpshared(), +// even though it supports pthreads! (like Irix 6.2) +#define ACE_LACKS_CONDATTR_PSHARED +#define ACE_LACKS_MUTEXATTR_PSHARED + +// IRIX 6.2 supports a variant of POSIX Pthreads, supposedly POSIX 1c +#define ACE_HAS_PTHREADS + +// Compiler/platform has thread-specific storage +#define ACE_HAS_THREAD_SPECIFIC_STORAGE + +// The pthread_cond_timedwait call does not reset the timer. +#define ACE_LACKS_COND_TIMEDWAIT_RESET 1 + +// When threads are enabled READDIR_R is supported on IRIX. +#undef ACE_LACKS_READDIR_R + +#endif /* (ACE_MT_SAFE == 0) */ + + +#endif /* ACE_CONFIG_IRIX6X_COMMON_H */ diff --git a/dep/acelite/ace/config-irix6.x-g++.h b/dep/acelite/ace/config-irix6.x-g++.h new file mode 100644 index 00000000000..94c79119a64 --- /dev/null +++ b/dep/acelite/ace/config-irix6.x-g++.h @@ -0,0 +1,15 @@ +/* -*- C++ -*- */ +// $Id: config-irix6.x-g++.h 87268 2009-10-29 21:06:06Z olli $ + +// The following configuration file is designed to work for the SGI +// Indigo2EX running Irix 6.2 platform using the GNU C++ Compiler + +#ifndef ACE_CONFIG_H +#define ACE_CONFIG_H +#include /**/ "ace/pre.h" + +#include "ace/config-g++-common.h" +#include "ace/config-irix6.x-common.h" + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_H */ diff --git a/dep/acelite/ace/config-irix6.x-sgic++.h b/dep/acelite/ace/config-irix6.x-sgic++.h new file mode 100644 index 00000000000..8bba07ac671 --- /dev/null +++ b/dep/acelite/ace/config-irix6.x-sgic++.h @@ -0,0 +1,36 @@ +/* -*- C++ -*- */ +// $Id: config-irix6.x-sgic++.h 81935 2008-06-12 22:01:53Z jtc $ + +// Use this file for IRIX 6.[234] if you have the pthreads patches +// installed. + +#ifndef ACE_CONFIG_H +#define ACE_CONFIG_H +#include /**/ "ace/pre.h" + +#include "ace/config-irix6.x-common.h" + +// This is the config file for IRIX 6.2, 6.4 and hopefully 6.3, using +// the SGI C++ compiler (7.1 or higher). + +// The following three should be enabled/disabled together. +#if _COMPILER_VERSION < 720 +#define ACE_HAS_TEMPLATE_INSTANTIATION_PRAGMA +#endif /* _COMPILER_VERSION < 720 */ +#define ACE_TEMPLATES_REQUIRE_SOURCE +#define ACE_NEEDS_FUNC_DEFINITIONS + +// Platform supports STREAM pipes (note that this is disabled by +// default, see the manual page on pipe(2) to find out how to enable +// it). +// #define ACE_HAS_STREAM_PIPES + +#if defined (_COMPILER_VERSION) +# define ACE_CC_NAME ACE_TEXT ("SGI/MIPSPro") +# define ACE_CC_MAJOR_VERSION (_COMPILER_VERSION / 100) +# define ACE_CC_MINOR_VERSION (_COMPILER_VERSION % 100) +# define ACE_CC_BETA_VERSION (0) +#endif /* _COMPILER_VERSION */ + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_H */ diff --git a/dep/acelite/ace/config-linux-common.h b/dep/acelite/ace/config-linux-common.h new file mode 100644 index 00000000000..b787a1447ad --- /dev/null +++ b/dep/acelite/ace/config-linux-common.h @@ -0,0 +1,464 @@ +/* -*- C++ -*- */ +// $Id: config-linux-common.h 88663 2010-01-22 10:49:22Z mcorino $ + +// Do not use this configuration file directly since it's designed to +// be included by another, specific configuration file, such as +// config-linux.h. It provides config information common to all Linux +// platforms. It automatically determines the CPU architecture, +// compiler (g++ or egcs), and libc (libc5 or glibc), and configures +// based on those. + +#ifndef ACE_LINUX_COMMON_H +#define ACE_LINUX_COMMON_H +#include /**/ "ace/pre.h" + +#define ACE_HAS_BYTESEX_H + +#if ! defined (__ACE_INLINE__) +#define __ACE_INLINE__ +#endif /* ! __ACE_INLINE__ */ + +// Needed to differentiate between libc 5 and libc 6 (aka glibc). +#include + +#if (defined _XOPEN_SOURCE && (_XOPEN_SOURCE - 0) >= 500) +# define ACE_HAS_PTHREADS_UNIX98_EXT +#endif /* _XOPEN_SOURCE - 0 >= 500 */ + +#if !defined (ACE_LACKS_LINUX_NPTL) + +# include "ace/config-posix.h" + + // Temporary fix because NPTL kernels do have shm_open but there is a problem + // with shm_open/shm_unlink pairing in ACE which needs to be fixed when I have time. +# if defined (ACE_HAS_SHM_OPEN) +# undef ACE_HAS_SHM_OPEN +# endif /* ACE_HAS_SHM_OPEN */ + +# if defined (ACE_USES_FIFO_SEM) + // Don't use this for Linux NPTL since this has complete + // POSIX semaphores which are more efficient +# undef ACE_USES_FIFO_SEM +# endif /* ACE_USES_FIFO_SEM */ + +# if defined (ACE_HAS_POSIX_SEM) + // Linux NPTL may not define the right POSIX macro + // but they have the actual runtime support for this stuff +# if !defined (ACE_HAS_POSIX_SEM_TIMEOUT) && (((_POSIX_C_SOURCE - 0) >= 200112L) || (_XOPEN_SOURCE >= 600)) +# define ACE_HAS_POSIX_SEM_TIMEOUT +# endif /* !ACE_HAS_POSIX_SEM_TIMEOUT && (((_POSIX_C_SOURCE - 0) >= 200112L) || (_XOPEN_SOURCE >= 600)) */ +# endif /* ACE_HAS_POSIX_SEM */ +#endif /* !ACE_LACKS_LINUX_NPTL */ + +// First the machine specific part + +#if defined (__powerpc__) || defined (__x86_64__) +# if !defined (ACE_DEFAULT_BASE_ADDR) +# define ACE_DEFAULT_BASE_ADDR ((char *) 0x40000000) +# endif /* ! ACE_DEFAULT_BASE_ADDR */ +#elif defined (__ia64) +# if !defined (ACE_DEFAULT_BASE_ADDR) +// Zero base address should work fine for Linux of IA-64: it just lets +// the kernel to choose the right value. +# define ACE_DEFAULT_BASE_ADDR ((char *) 0x0000000000000000) +# endif /* ! ACE_DEFAULT_BASE_ADDR */ +#endif /* ! __powerpc__ && ! __ia64 */ + +// Then glibc/libc5 specific parts + +#if defined(__GLIBC__) +# if (__GLIBC__ < 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 1) +# define ACE_HAS_NONCONST_SETRLIMIT +# endif +# if (__GLIBC__ < 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 3) +# define ACE_HAS_RUSAGE_WHO_ENUM enum __rusage_who +# define ACE_HAS_RLIMIT_RESOURCE_ENUM enum __rlimit_resource +# define ACE_LACKS_ISCTYPE +# endif +# define ACE_HAS_SOCKLEN_T +# define ACE_HAS_4_4BSD_SENDMSG_RECVMSG + + // glibc defines both of these, used in OS_String. +# if defined (_GNU_SOURCE) +# define ACE_HAS_STRNLEN +# define ACE_HAS_WCSNLEN + + // This is probably not a 100%-sure-fire check... Red Hat Linux 9 + // and Enterprise Linux 3 and up have a new kernel that can send signals + // across threads. This was not possible prior because there was no real + // difference between a process and a thread. With this, the + // ACE_POSIX_SIG_Proactor is the only chance of getting asynch I/O working. + // There are restrictions, such as all socket operations being silently + // converted to synchronous by the kernel, that make aio a non-starter + // for most Linux platforms at this time. But we'll start to crawl... +# define ACE_POSIX_SIG_PROACTOR +# endif + + // To avoid the strangeness with Linux's ::select (), which modifies + // its timeout argument, use ::poll () instead. +# define ACE_HAS_POLL + +// Don't define _XOPEN_SOURCE and _XOPEN_SOURCE_EXTENDED in ACE to make +// getpgid() prototype visible. ACE shouldn't depend on feature test +// macros to make prototypes visible. +# define ACE_LACKS_GETPGID_PROTOTYPE + +// @note the following defines are necessary with glibc 2.0 (0.961212-5) +// on Alpha. I assume that they're necessary on Intel as well, +// but that may depend on the version of glibc that is used. +//# define ACE_HAS_DLFCN_H_BROKEN_EXTERN_C +# define ACE_HAS_VOIDPTR_SOCKOPT + +// Don't define _POSIX_SOURCE in ACE to make strtok() prototype +// visible. ACE shouldn't depend on feature test macros to make +// prototypes visible. +# define ACE_LACKS_STRTOK_R_PROTOTYPE +// @note end of glibc 2.0 (0.961212-5)-specific configuration. + +# if __GLIBC__ > 1 && __GLIBC_MINOR__ >= 1 + // These were suggested by Robert Hanzlik to get + // ACE to compile on Linux using glibc 2.1 and libg++/gcc 2.8. +# undef ACE_HAS_BYTESEX_H +# define ACE_HAS_SIGINFO_T +# define ACE_LACKS_SIGINFO_H +# define ACE_HAS_UCONTEXT_T + + // Pre-glibc (RedHat 5.2) doesn't have sigtimedwait. +# define ACE_HAS_SIGTIMEDWAIT +# endif /* __GLIBC__ 2.1+ */ +#else /* ! __GLIBC__ */ + // Fixes a problem with some non-glibc versions of Linux... +# define ACE_LACKS_MADVISE +# define ACE_LACKS_MSG_ACCRIGHTS +#endif /* ! __GLIBC__ */ + +// Don't define _LARGEFILE64_SOURCE in ACE to make llseek() or +// lseek64() prototype visible. ACE shouldn't depend on feature test +// macros to make prototypes visible. +#if __GLIBC__ > 1 +# if __GLIBC_MINOR__ == 0 +# define ACE_HAS_LLSEEK +# define ACE_LACKS_LLSEEK_PROTOTYPE +# else /* __GLIBC_MINOR__ > 0 */ +# define ACE_HAS_LSEEK64 +# define ACE_LACKS_LSEEK64_PROTOTYPE +# endif +#endif /* __GLIBC__ > 1 */ + +#if __GLIBC__ > 1 && __GLIBC_MINOR__ >= 1 +# define ACE_HAS_P_READ_WRITE +# define ACE_LACKS_PREAD_PROTOTYPE +// Use ACE's alternate cuserid() implementation since the use of the +// system cuserid() is discouraged. +# define ACE_HAS_ALT_CUSERID +#endif /* __GLIBC__ > 1 && __GLIBC_MINOR__ >= 0 */ + +#if (__GLIBC__ > 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3) +# define ACE_HAS_ISASTREAM_PROTOTYPE +# define ACE_HAS_PTHREAD_SIGMASK_PROTOTYPE +# define ACE_HAS_CPU_SET_T +#endif /* __GLIBC__ > 2 || __GLIBC__ === 2 && __GLIBC_MINOR__ >= 3) */ + +// Then the compiler specific parts + +#if defined (__INTEL_COMPILER) +# include "ace/config-icc-common.h" +#elif defined (__GNUG__) + // config-g++-common.h undef's ACE_HAS_STRING_CLASS with -frepo, so + // this must appear before its #include. +# define ACE_HAS_STRING_CLASS +# include "ace/config-g++-common.h" +#define ACE_CC_NAME ACE_TEXT ("g++") +#define ACE_CC_MAJOR_VERSION __GNUC__ +#define ACE_CC_MINOR_VERSION __GNUC_MINOR__ +//#define ACE_CC_BETA_VERSION 0 /* ??? */ +#elif defined (__DECCXX) +# define ACE_CONFIG_INCLUDE_CXX_COMMON +# include "ace/config-cxx-common.h" +#elif defined (__SUNCC_PRO) || defined (__SUNPRO_CC) +# include "ace/config-suncc-common.h" +#elif defined (__PGI) +// Portable group compiler +# define ACE_HAS_CPLUSPLUS_HEADERS +# define ACE_HAS_STDCPP_STL_INCLUDES +# define ACE_HAS_TEMPLATE_TYPEDEFS +# define ACE_HAS_STANDARD_CPP_LIBRARY 1 +# define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 +# define ACE_LACKS_SWAB +#elif defined (__GNUC__) +/** + * GNU C compiler. + * + * We need to recognize the GNU C compiler since TAO has at least one + * C source header and file + * (TAO/orbsvcs/orbsvcs/SSLIOP/params_dup.{h,c}) that may indirectly + * include this + */ +#else /* ! __GNUG__ && !__DECCXX && !__INTEL_COMPILER && && !__PGI */ +# ifdef __cplusplus /* Let it slide for C compilers. */ +# error unsupported compiler in ace/config-linux-common.h +# endif /* __cplusplus */ +#endif /* ! __GNUG__*/ + +// Completely common part :-) + +// Platform/compiler has the sigwait(2) prototype +#define ACE_HAS_SIGWAIT + +#define ACE_HAS_SIGSUSPEND + +#define ACE_HAS_UALARM + +#define ACE_HAS_STRSIGNAL + +#if __GLIBC__ >= 2 +#ifndef ACE_HAS_POSIX_REALTIME_SIGNALS +#define ACE_HAS_POSIX_REALTIME_SIGNALS +#endif /* ACE_HAS_POSIX_REALTIME_SIGNALS */ + +#ifndef ACE_HAS_AIO_CALLS +#define ACE_HAS_AIO_CALLS +#endif /* ACE_HAS_AIO_CALLS */ +#endif + +#if __GLIBC__ >= 2 +// glibc 2 and higher has wchar support +# define ACE_HAS_XPG4_MULTIBYTE_CHAR +# define ACE_HAS_VFWPRINTF +#endif + +#if __GLIBC__ < 2 +// These are present in glibc 2 and higher +# define ACE_LACKS_WCSTOK +# define ACE_LACKS_WCSDUP_PROTOTYPE +#endif /* __GLIBC__ < 2 */ + +#define ACE_LACKS_ITOW +#define ACE_LACKS_WCSICMP +#define ACE_LACKS_WCSNICMP +#define ACE_LACKS_ISWASCII + +#if __GLIBC__ >= 2 +# define ACE_HAS_3_PARAM_WCSTOK +#endif + +#define ACE_HAS_3_PARAM_READDIR_R + +#if !defined (ACE_DEFAULT_BASE_ADDR) +# define ACE_DEFAULT_BASE_ADDR ((char *) 0x80000000) +#endif /* ! ACE_DEFAULT_BASE_ADDR */ + +// Compiler/platform supports alloca(). +// Although ACE does have alloca() on this compiler/platform combination, it is +// disabled by default since it can be dangerous. Uncomment the following line +// if you ACE to use it. +//#define ACE_HAS_ALLOCA + +// Compiler/platform has +#define ACE_HAS_ALLOCA_H +#define ACE_HAS_SYS_SYSINFO_H +#define ACE_HAS_LINUX_SYSINFO + +// Compiler/platform has the getrusage() system call. +#define ACE_HAS_GETRUSAGE +#define ACE_HAS_GETRUSAGE_PROTOTYPE + +#define ACE_HAS_BYTESWAP_H +#define ACE_HAS_BSWAP_16 +#define ACE_HAS_BSWAP_32 + +#if defined __GNUC__ && __GNUC__ >= 2 +# define ACE_HAS_BSWAP_64 +#endif + +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES + +// Optimize ACE_Handle_Set for select(). +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT + +// ONLY define this if you have config'd multicast into a 2.0.34 or +// prior kernel. It is enabled by default in 2.0.35 kernels. +#if !defined (ACE_HAS_IP_MULTICAST) +# define ACE_HAS_IP_MULTICAST +#endif /* ! ACE_HAS_IP_MULTICAST */ + +// At least for IPv4, Linux lacks perfect filtering. +#if !defined ACE_LACKS_PERFECT_MULTICAST_FILTERING +# define ACE_LACKS_PERFECT_MULTICAST_FILTERING 1 +#endif /* ACE_LACKS_PERFECT_MULTICAST_FILTERING */ + +#define ACE_HAS_BIG_FD_SET + +// Linux defines struct msghdr in /usr/include/socket.h +#define ACE_HAS_MSG + +// Linux "improved" the interface to select() so that it modifies +// the struct timeval to reflect the amount of time not slept +// (see NOTES in Linux's select(2) man page). +#define ACE_HAS_NONCONST_SELECT_TIMEVAL + +#define ACE_DEFAULT_MAX_SOCKET_BUFSIZ 65535 + +#define ACE_CDR_IMPLEMENT_WITH_NATIVE_DOUBLE 1 + +#define ACE_HAS_GETPAGESIZE 1 + +#if (__GLIBC__ < 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 2) +// glibc supports wchar, but lacks fgetwc and ungetwc +# define ACE_LACKS_FGETWC +# define ACE_HAS_NONCONST_MSGSND +# define ACE_LACKS_STRNLEN_PROTOTYPE +#endif + +// glibc requires _XOPEN_SOURCE_EXTENDED to make this prototype +// visible, so force ACE to declare one. Yuk! +#ifndef _XOPEN_SOURCE_EXTENDED +# define ACE_LACKS_MKSTEMP_PROTOTYPE +#endif /* !_XOPEN_SOURCE_EXTENDED */ + +// Platform defines struct timespec but not timespec_t +#define ACE_LACKS_TIMESPEC_T + +// Platform supplies scandir() +#define ACE_HAS_SCANDIR +#if (__GLIBC__ < 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 10) +// Although the scandir man page says otherwise, this setting is correct. +// The setting was fixed in 2.10, so do not use the hack after that. +#define ACE_SCANDIR_CMP_USES_CONST_VOIDPTR +#endif + +// A conflict appears when including both and +// with recent glibc headers. +//#define ACE_HAS_PROC_FS + +// Platform supports System V IPC (most versions of UNIX, but not Win32) +#define ACE_HAS_SYSV_IPC + +// Compiler/platform contains the file. +#define ACE_HAS_SYS_SYSCALL_H + +// Platform/compiler supports global timezone variable. +#define ACE_HAS_TIMEZONE + +#define ACE_HAS_TIMEZONE_GETTIMEOFDAY + +// Don't define _XOPEN_SOURCE in ACE to make strptime() prototype +// visible. ACE shouldn't depend on feature test macros to make +// prototypes visible. +#define ACE_LACKS_STRPTIME_PROTOTYPE + +// Compiler supports the ssize_t typedef. +#define ACE_HAS_SSIZE_T + +// Compiler/platform defines the sig_atomic_t typedef. +#define ACE_HAS_SIG_ATOMIC_T + +// Compiler/platform defines a union semun for SysV shared memory. +#define ACE_HAS_SEMUN + +#define ACE_HAS_POSIX_TIME + +#define ACE_HAS_GPERF + +#define ACE_HAS_DIRENT + +// Starting with FC9 rawhide this file is not available anymore but +// this define is set +#if defined _XOPEN_STREAMS && _XOPEN_STREAMS == -1 +# define ACE_LACKS_STROPTS_H +# define ACE_LACKS_STRRECVFD +#endif + +#if !defined (ACE_LACKS_STROPTS_H) +# define ACE_HAS_STRBUF_T +#endif + +#if defined (__ia64) || defined(__alpha) || defined (__x86_64__) +// On 64 bit platforms, the "long" type is 64-bits. Override the +// default 32-bit platform-specific format specifiers appropriately. +# define ACE_UINT64_FORMAT_SPECIFIER_ASCII "%lu" +# define ACE_SSIZE_T_FORMAT_SPECIFIER_ASCII "%ld" +# define ACE_SIZE_T_FORMAT_SPECIFIER_ASCII "%lu" +#endif /* __ia64 */ + +#define ACE_SIZEOF_WCHAR 4 + +#if defined (__powerpc__) && !defined (ACE_SIZEOF_LONG_DOUBLE) +// 32bit PowerPC Linux uses 128bit long double +# define ACE_SIZEOF_LONG_DOUBLE 16 +#endif + +#define ACE_LACKS_GETIPNODEBYADDR +#define ACE_LACKS_GETIPNODEBYNAME + +// Platform has POSIX terminal interface. +#define ACE_HAS_TERMIOS + +// Linux implements sendfile(). +#define ACE_HAS_SENDFILE 1 + +#define ACE_HAS_VOIDPTR_MMAP + +#define ACE_HAS_ICMP_SUPPORT 1 + +#define ACE_HAS_VASPRINTF + +// According to man pages Linux uses different (compared to UNIX systems) types +// for setting IP_MULTICAST_TTL and IPV6_MULTICAST_LOOP / IP_MULTICAST_LOOP +// in setsockopt/getsockopt. +#define ACE_HAS_IP_MULTICAST_TTL_AS_INT 1 +#define ACE_HAS_IPV6_MULTICAST_LOOP_AS_BOOL 1 +#define ACE_HAS_IP_MULTICAST_LOOP_AS_INT 1 + +#if defined (ACE_LACKS_NETWORKING) +# include "ace/config-posix-nonetworking.h" +#else +# define ACE_HAS_NETLINK +# if (__GLIBC__ > 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 2) +# define ACE_HAS_GETIFADDRS +# endif +#endif + +#if !defined (ACE_GETNAME_RETURNS_RANDOM_SIN_ZERO) +// Detect if getsockname() and getpeername() returns random values in +// the sockaddr_in::sin_zero field by evaluation of the kernel +// version. Since version 2.5.47 this problem is fixed. +# if !defined (ACE_LACKS_LINUX_VERSION_H) +# include +# endif /* !ACE_LACKS_LINUX_VERSION_H */ +# if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,47)) +# define ACE_GETNAME_RETURNS_RANDOM_SIN_ZERO 0 +# else +# define ACE_GETNAME_RETURNS_RANDOM_SIN_ZERO 1 +# endif /* (LINUX_VERSION_CODE <= KERNEL_VERSION(2,5,47)) */ +#endif /* ACE_GETNAME_RETURNS_RANDOM_SIN_ZERO */ + +#if defined (ACE_HAS_EVENT_POLL) +// The sys_epoll interface was introduced in Linux kernel 2.5.45. +// Don't support backported versions since they appear to be buggy. +// The obsolete ioctl()-based interface is no longer supported. +#if 0 +// linux/version.h may not be accurate. It's not for Fedora Core 2... +# if !defined (ACE_LACKS_LINUX_VERSION_H) +# include +# endif /* !ACE_LACKS_LINUX_VERSION_H */ +# if (LINUX_VERSION_CODE < KERNEL_VERSION (2,5,45)) +# undef ACE_HAS_EVENT_POLL +# error Disabling Linux epoll support. Kernel used in C library is too old. +# error Linux kernel 2.5.45 or better is required. +# endif /* LINUX_VERSION_CODE < KERNEL_VERSION (2,5,45) */ +#endif /* ACE_HAS_EVENT_POLL */ +#endif + +#if !defined (ACE_HAS_EVENT_POLL) && !defined (ACE_HAS_DEV_POLL) +# if !defined (ACE_LACKS_LINUX_VERSION_H) +# include +# endif /* !ACE_LACKS_LINUX_VERSION_H */ +# if (LINUX_VERSION_CODE > KERNEL_VERSION (2,6,0)) +# define ACE_HAS_EVENT_POLL +# endif +#endif + +#include /**/ "ace/post.h" + +#endif /* ACE_LINUX_COMMON_H */ diff --git a/dep/acelite/ace/config-linux.h b/dep/acelite/ace/config-linux.h new file mode 100644 index 00000000000..8b79c13a415 --- /dev/null +++ b/dep/acelite/ace/config-linux.h @@ -0,0 +1,75 @@ +// -*- C++ -*- +// +// $Id: config-linux.h 80826 2008-03-04 14:51:23Z wotte $ + +// The following configuration file is designed to work for Linux +// platforms using GNU C++. + +#ifndef ACE_CONFIG_LINUX_H +#define ACE_CONFIG_LINUX_H +#include /**/ "ace/pre.h" + +#define ACE_PLATFORM_CONFIG config-linux.h + +#include "ace/config-linux-common.h" + +#define ACE_HAS_SVR4_DYNAMIC_LINKING +#define ACE_HAS_AUTOMATIC_INIT_FINI +#define ACE_HAS_DLSYM_SEGFAULT_ON_INVALID_HANDLE + +#if !defined (ACE_MT_SAFE) +#define ACE_MT_SAFE 1 // JCEJ 12/22/96 #1 +#endif + +#if ACE_MT_SAFE +// Yes, we do have threads. +#define ACE_HAS_THREADS +// And they're even POSIX pthreads (LinuxThreads implementation) +#define ACE_HAS_PTHREADS + +// On linux this is part of pthreads +# if (defined _POSIX_C_SOURCE && (_POSIX_C_SOURCE - 0) >= 199309L) +# if !defined (ACE_HAS_CLOCK_GETTIME) +# if !defined(__PGI) +# define ACE_HAS_CLOCK_GETTIME +# endif /* __PGI */ +# define ACE_HAS_CLOCK_SETTIME +# endif /* !ACE_HAS_CLOCK_GETTIME */ +# endif /* _POSIX_C_SOURCE >= 199309L */ + +#if !defined (ACE_HAS_PTHREADS_UNIX98_EXT) +# define ACE_LACKS_RWLOCK_T +#else +# define ACE_HAS_RECURSIVE_MUTEXES +#endif /* !ACE_HAS_PTHREADS_UNIX98_EXT */ + +#define ACE_HAS_THREAD_SPECIFIC_STORAGE // jcej 12/22/96 #2 + +#define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS // JCEJ 1/7-8/96 + +#if defined(__GLIBC__) +// Platform supports reentrant functions (i.e., all the POSIX *_r +// functions). +#define ACE_HAS_REENTRANT_FUNCTIONS + +#if (__GLIBC__ < 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 1) + // Older versions of glibc lacked reentrant netdb functions +# define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS + + // glibc < 2.1 lacks pthread_attr_setstacksize() +# define ACE_LACKS_PTHREAD_ATTR_SETSTACKSIZE +#endif /* (__GLIBC__ < 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 1) */ + +// uses ctime_r & asctime_r with only two parameters vs. three +#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R +#endif + +#else +// AIO support pulls in the rt library, which pulls in the pthread +// library. Disable AIO in single-threaded builds. +# undef ACE_HAS_AIO_CALLS +#endif /* ACE_MT_SAFE */ + +#include /**/ "ace/post.h" + +#endif /* ACE_CONFIG_LINUX_H */ diff --git a/dep/acelite/ace/config-lite.h b/dep/acelite/ace/config-lite.h new file mode 100644 index 00000000000..1a6937c851b --- /dev/null +++ b/dep/acelite/ace/config-lite.h @@ -0,0 +1,164 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file config-lite.h + * + * $Id: config-lite.h 85832 2009-06-28 16:14:59Z johnnyw $ + * + * @author (Originally in OS.h)Doug Schmidt + * @author Jesper S. M|ller + * @author and a cast of thousands... + * + * This file contains the contents of the old config-all.h in order to + * avoid a circular dependency problem caused by some of the new + * includes added to config-all.h, e.g., OS_main.h. + */ +//========================================================================== + +#ifndef ACE_CONFIG_LITE_H +#define ACE_CONFIG_LITE_H + +#include /**/ "ace/pre.h" + +#include "ace/config-macros.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +// Empty ACE_OS namespace to help identify compiler errors more +// easily. -- @@ Do we really need this? +ACE_BEGIN_VERSIONED_NAMESPACE_DECL +namespace ACE_OS {} +ACE_END_VERSIONED_NAMESPACE_DECL + +// ============================================================================ +// UNICODE macros (to be added later) +// ============================================================================ + +// Get the unicode (i.e. ACE_TCHAR) defines +# include "ace/ace_wchar.h" + +// ============================================================================ +// at_exit declarations +// ============================================================================ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +// Marker for cleanup, used by ACE_Exit_Info. +extern int ace_exit_hook_marker; + +ACE_END_VERSIONED_NAMESPACE_DECL + +// For use by . +extern "C" +{ + typedef void (*ACE_EXIT_HOOK) (void); +} + +// Signature for registering a cleanup function that is used by the +// ACE_Object_Manager and the ACE_Thread_Manager. +# if defined (ACE_HAS_SIG_C_FUNC) +extern "C" { +# endif /* ACE_HAS_SIG_C_FUNC */ +typedef void (*ACE_CLEANUP_FUNC)(void *object, void *param) /* throw () */; +# if defined (ACE_HAS_SIG_C_FUNC) +} +# endif /* ACE_HAS_SIG_C_FUNC */ + +// ============================================================================ +// log_msg declarations +// ============================================================================ + +ACE_BEGIN_VERSIONED_NAMESPACE_DECL + +# if defined (ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS) +typedef int (*ACE_SEH_EXCEPT_HANDLER)(void *); +// Prototype of win32 structured exception handler functions. +// They are used to get the exception handling expression or +// as exception handlers. +# endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */ + +class ACE_OS_Thread_Descriptor; +class ACE_OS_Log_Msg_Attributes; +typedef void (*ACE_INIT_LOG_MSG_HOOK) (ACE_OS_Log_Msg_Attributes &attr +# if defined (ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS) + , ACE_SEH_EXCEPT_HANDLER selector + , ACE_SEH_EXCEPT_HANDLER handler +# endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */ + ); +typedef void (*ACE_INHERIT_LOG_MSG_HOOK) (ACE_OS_Thread_Descriptor*, + ACE_OS_Log_Msg_Attributes &); + +typedef void (*ACE_CLOSE_LOG_MSG_HOOK) (void); + +typedef void (*ACE_SYNC_LOG_MSG_HOOK) (const ACE_TCHAR *prog_name); + +typedef ACE_OS_Thread_Descriptor *(*ACE_THR_DESC_LOG_MSG_HOOK) (void); + +ACE_END_VERSIONED_NAMESPACE_DECL + +/** + * @deprecated ACE_DECLARE_STL_REVERSE_ITERATORS is a crutch to be + * used until all C++ compiler supported by ACE support + * the standard reverse_iterator adapters. + * @internal ACE_DECLARE_STL_REVERSE_ITERATORS is not meant for use + * outside of ACE. + */ +// STL reverse_iterator declaration generator +// Make sure you include in the file you're using this +// generator, and that the following traits are available: +// +// iterator +// const_iterator +// value_type +// reference +// pointer +// const_reference +// const_pointer +// difference_type +// +// Once all C++ compilers support the standard reverse_iterator +// adapters, we can drop this generator macro or at least drop the +// MSVC++ or Sun Studio preprocessor conditional blocks. +#if defined (__SUNPRO_CC) && __SUNPRO_CC <= 0x5100 \ + && !defined (_STLPORT_VERSION) + // If we're not using the stlport4 C++ library (which has standard + // iterators), we need to ensure this is included in order to test + // the _RWSTD_NO_CLASS_PARTIAL_SPEC feature test macro below. +# include +#endif /* __SUNPRO_CC <= 0x5100 */ +#if (defined (_MSC_VER) && (_MSC_VER <= 1310) && defined (_WIN64)) \ + || defined (ACE_HAS_BROKEN_STD_REVERSE_ITERATOR) + // VC 7.1 and the latest 64-bit platform SDK still don't define a standard + // compliant reverse_iterator adapter. +# define ACE_DECLARE_STL_REVERSE_ITERATORS \ + typedef std::reverse_iterator reverse_iterator; \ + typedef std::reverse_iterator const_reverse_iterator; +#elif defined (__SUNPRO_CC) && __SUNPRO_CC <= 0x5100 \ + && defined (_RWSTD_NO_CLASS_PARTIAL_SPEC) +# define ACE_DECLARE_STL_REVERSE_ITERATORS \ + typedef std::reverse_iterator reverse_iterator; \ + typedef std::reverse_iterator const_reverse_iterator; +#else +# define ACE_DECLARE_STL_REVERSE_ITERATORS \ + typedef std::reverse_iterator reverse_iterator; \ + typedef std::reverse_iterator const_reverse_iterator; +#endif /* _MSC_VER && _WIN64 */ + + +#include /**/ "ace/post.h" + +#endif /* ACE_CONFIG_LITE_H */ diff --git a/dep/acelite/ace/config-lynxos.h b/dep/acelite/ace/config-lynxos.h new file mode 100644 index 00000000000..81176f615b9 --- /dev/null +++ b/dep/acelite/ace/config-lynxos.h @@ -0,0 +1,199 @@ +// $Id: config-lynxos.h 89494 2010-03-15 20:11:18Z olli $ + +// The following configuration file is designed to work for LynxOS, +// version 4.0.0 and later, using the GNU g++ compiler. + +#ifndef ACE_CONFIG_H +#define ACE_CONFIG_H +#include /**/ "ace/pre.h" + +// System include files are not in sys/, this gets rid of warning. +#define __NO_INCLUDE_WARN__ + +#define __FREEBSDCODE__ +#include +#undef __FREEBSDCODE__ + +#if ! defined (__ACE_INLINE__) +# define __ACE_INLINE__ +#endif /* ! __ACE_INLINE__ */ + +#if defined (__GNUG__) +# include "ace/config-g++-common.h" +#endif /* __GNUG__ */ + +// Compile using multi-thread libraries. +#if !defined (ACE_MT_SAFE) +# define ACE_MT_SAFE 1 +#endif + +#include "ace/config-posix.h" + +#if defined (__x86__) +# define ACE_HAS_PENTIUM +#elif defined (__powerpc__) + // It looks like the default stack size is 15000. + // ACE's Recursive_Mutex_Test needs more. +# define ACE_NEEDS_HUGE_THREAD_STACKSIZE 65536 + // This doesn't work on LynxOS 3.0.0, because it resets the TimeBaseRegister. + // # define ACE_HAS_POWERPC_TIMER +#endif /* __x86__ || __powerpc__ */ + +#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R +#define ACE_HAS_3_PARAM_READDIR_R +#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG +#define ACE_HAS_ALLOCA +#define ACE_HAS_ALLOCA_H +#define ACE_HAS_AUTOMATIC_INIT_FINI +#define ACE_HAS_BROKEN_PREALLOCATED_OBJECTS_AFTER_FORK 1 +#define ACE_HAS_BROKEN_SIGEVENT_STRUCT +#define ACE_HAS_CHARPTR_SHMAT +#define ACE_HAS_CHARPTR_SHMDT +#define ACE_HAS_CLOCK_GETTIME +#define ACE_HAS_CLOCK_SETTIME +#define ACE_HAS_CPLUSPLUS_HEADERS +#define ACE_HAS_DIRENT +#define ACE_HAS_GETIFADDRS +#define ACE_HAS_GETPAGESIZE +#define ACE_HAS_GETRUSAGE +#define ACE_HAS_GETRUSAGE_PROTOTYPE +#define ACE_HAS_GPERF +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT +#define ACE_HAS_ICMP_SUPPORT 1 +#define ACE_HAS_IP_MULTICAST +#define ACE_HAS_MEMCHR +#define ACE_HAS_MKDIR +#define ACE_HAS_MSG +#define ACE_HAS_NANOSLEEP +#define ACE_HAS_NEW_NOTHROW +#define ACE_HAS_NONCONST_CLOCK_SETTIME +#define ACE_HAS_NONCONST_MSGSND +#define ACE_HAS_NONCONST_READV +#define ACE_HAS_NONCONST_SELECT_TIMEVAL +#define ACE_HAS_NONCONST_SETRLIMIT +#define ACE_HAS_NONCONST_WRITEV +#define ACE_HAS_POSITION_INDEPENDENT_POINTERS 1 +#define ACE_HAS_POSIX_NONBLOCK +#define ACE_HAS_POSIX_TIME +#define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS +#define ACE_HAS_SCANDIR +#define ACE_HAS_SIGACTION_CONSTP2 +#define ACE_HAS_SIGINFO_T +#define ACE_HAS_SIGSUSPEND +#define ACE_HAS_SIGTIMEDWAIT +#define ACE_HAS_SIGWAIT +#define ACE_HAS_SIG_ATOMIC_T +#define ACE_HAS_SIG_C_FUNC +#define ACE_HAS_SOCKADDR_IN6_SIN6_LEN +#define ACE_HAS_SOCKADDR_IN_SIN_LEN +#define ACE_HAS_SOCKADDR_MSG_NAME +#define ACE_HAS_SOCKLEN_T +#define ACE_HAS_SSIZE_T +#define ACE_HAS_STREAMS +#define ACE_HAS_STRINGS +#define ACE_HAS_STRING_CLASS +#define ACE_HAS_SYSCTL +#define ACE_HAS_SYS_FILIO_H +#define ACE_HAS_SYS_SOCKIO_H +#define ACE_HAS_TERMIOS +#define ACE_HAS_TIMEZONE_GETTIMEOFDAY + +#define ACE_LACKS_ALPHASORT_PROTOTYPE +#define ACE_LACKS_CONST_TIMESPEC_PTR +#define ACE_LACKS_GETPGID +#define ACE_LACKS_ISCTYPE +#define ACE_LACKS_MADVISE +#define ACE_LACKS_MKSTEMP_PROTOTYPE +#define ACE_LACKS_MKTEMP_PROTOTYPE +#define ACE_LACKS_PUTENV_PROTOTYPE +#define ACE_LACKS_REALPATH +#define ACE_LACKS_RLIMIT_NOFILE +#define ACE_LACKS_RWLOCK_T +#define ACE_LACKS_SCANDIR_PROTOTYPE +#define ACE_LACKS_SETEGID +#define ACE_LACKS_SETEUID +#define ACE_LACKS_SIGINFO_H +#define ACE_LACKS_STRPTIME +#define ACE_LACKS_SWAB_PROTOTYPE +#define ACE_LACKS_TIMESPEC_T +#define ACE_LACKS_UCONTEXT_H +#define ACE_LACKS_SUSECONDS_T + +#define ACE_DEFAULT_BASE_ADDR ((char *) 0) +#define ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS +#define ACE_MALLOC_ALIGN 8 +#define ACE_PAGE_SIZE 4096 +#define ACE_POSIX_SIG_PROACTOR +#define ACE_SCANDIR_CMP_USES_CONST_VOIDPTR + +// LynxOS has poll.h but it is unusable since implementation is not provided +#define ACE_LACKS_POLL_H + +#if ACE_MT_SAFE == 1 + // Platform supports threads. +# define ACE_HAS_PTHREADS +# define ACE_HAS_PTHREADS_STD +# define ACE_HAS_PTHREADS_UNIX98_EXT +# define ACE_HAS_PTHREAD_GETCONCURRENCY +# define ACE_HAS_PTHREAD_SETCONCURRENCY +# define ACE_HAS_PTHREAD_SIGMASK_PROTOTYPE +# define ACE_HAS_THREAD_SPECIFIC_STORAGE +# define ACE_LACKS_PTHREAD_ATTR_SETSTACK +# define ACE_LACKS_THREAD_PROCESS_SCOPING +# if ACE_LYNXOS_MAJOR == 4 && ACE_LYNXOS_MINOR == 0 +# define ACE_LACKS_SETDETACH +# define ACE_LACKS_PTHREAD_ATTR_SETSTACKADDR +# endif +#endif /* ACE_MT_SAFE */ + +// By default, don't include RCS Id strings in object code. +#if !defined (ACE_USE_RCSID) +# define ACE_USE_RCSID 0 +#endif /* ! ACE_USE_RCSID */ + +#if ACE_LYNXOS_MAJOR == 4 && ACE_LYNXOS_MINOR == 0 +# define ACE_LACKS_GETOPT_PROTOTYPE +# define ACE_LACKS_INET_ATON_PROTOTYPE +# define ACE_LACKS_REGEX_H +# define ACE_LACKS_STRCASECMP_PROTOTYPE +# define ACE_LACKS_STRNCASECMP_PROTOTYPE +# define ACE_LACKS_SYS_SELECT_H +#endif + +#if (ACE_LYNXOS_MAJOR > 4) || (ACE_LYNXOS_MAJOR == 4 && ACE_LYNXOS_MINOR >= 2) +// LynxOS 4.2 additons +# define ACE_HAS_POSIX_SEM_TIMEOUT +# define ACE_HAS_MUTEX_TIMEOUTS +#endif + +#if (ACE_LYNXOS_MAJOR >=5) +// LynxOS 5.0 Additons +# define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES +# define ACE_HAS_NONCONST_INET_ADDR +# define ACE_LACKS_INET_ATON_PROTOTYPE +# define ACE_LACKS_SEMBUF_T +# define ACE_LACKS_STROPTS_H +# define ACE_LACKS_STRRECVFD +# define ACE_LACKS_SYS_SEM_H +# define ACE_SYS_SIGLIST __sys_siglist +#else +// LynxOS 5.0 Removals +# define ACE_HAS_LYNXOS4_SIGNALS +# define ACE_HAS_SEMUN +# define ACE_HAS_STRBUF_T +# define ACE_HAS_SYSV_IPC +# define ACE_LACKS_ISBLANK +# define ACE_LACKS_SETENV +# define ACE_LACKS_UNSETENV +# define ACE_LACKS_USECONDS_T +# define ACE_LACKS_VSNPRINTF +# define ACE_LACKS_WCHAR_H +# define ACE_SYS_SIGLIST sys_siglist +#endif + +#if defined (ACE_HAS_SVR4_DYNAMIC_LINKING) +# define ACE_HAS_BROKEN_THREAD_KEYFREE +#endif /* ACE_HAS_SVR4_DYNAMIC_LINKING */ + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_H */ diff --git a/dep/acelite/ace/config-macosx-iphone-hardware.h b/dep/acelite/ace/config-macosx-iphone-hardware.h new file mode 100644 index 00000000000..6201d8e824b --- /dev/null +++ b/dep/acelite/ace/config-macosx-iphone-hardware.h @@ -0,0 +1,15 @@ +// $Id: config-macosx-iphone-hardware.h 88739 2010-01-27 05:35:23Z sowayaa $ +#ifndef ACE_CONFIG_MACOSX_IPHONE_HARDWARE_H +#define ACE_CONFIG_MACOSX_IPHONE_HARDWARE_H + +#define ACE_HAS_IPHONE +#define ACE_SIZEOF_LONG_DOUBLE 8 + +#include "ace/config-macosx-snowleopard.h" + +#ifdef ACE_HAS_SYSV_IPC +#undef ACE_HAS_SYSV_IPC +#endif + +#endif ACE_CONFIG_MACOSX_IPHONE_HARDWARE_H + diff --git a/dep/acelite/ace/config-macosx-iphone-simulator.h b/dep/acelite/ace/config-macosx-iphone-simulator.h new file mode 100644 index 00000000000..024cf8480a3 --- /dev/null +++ b/dep/acelite/ace/config-macosx-iphone-simulator.h @@ -0,0 +1,9 @@ +// $Id: config-macosx-iphone-simulator.h 88653 2010-01-21 23:19:50Z sowayaa $ +#ifndef ACE_CONFIG_MACOSX_IPHONE_SIMULATOR_H +#define ACE_CONFIG_MACOSX_IPHONE_SIMULATOR_H + +#define ACE_HAS_IPHONE +#include "ace/config-macosx-snowleopard.h" + +#endif ACE_CONFIG_MACOSX_IPHONE_SIMULATOR_H + diff --git a/dep/acelite/ace/config-macosx-leopard.h b/dep/acelite/ace/config-macosx-leopard.h new file mode 100644 index 00000000000..dfaaf870947 --- /dev/null +++ b/dep/acelite/ace/config-macosx-leopard.h @@ -0,0 +1,231 @@ +/* -*- C++ -*- */ +// $Id: config-macosx-leopard.h 90343 2010-05-29 02:18:47Z wotte $ + +// This configuration file is designed to work with the MacOS X operating system. + +#ifndef ACE_CONFIG_MACOSX_LEOPARD_H +#define ACE_CONFIG_MACOSX_LEOPARD_H + +#define ACE_HAS_MAC_OSX +#define ACE_HAS_NET_IF_DL_H + +#define ACE_HAS_VOID_UNSETENV + +#if ! defined (__ACE_INLINE__) +#define __ACE_INLINE__ +#endif /* ! __ACE_INLINE__ */ + +#if !defined (ACE_SIZEOF_LONG_DOUBLE) +# if (__GNUC__ == 3 && __GNUC_MINOR__ == 3) + // Size of long double in GCC 3.3 is 8. +# define ACE_SIZEOF_LONG_DOUBLE 8 +# else // Else, the compiler is GCC4 + // For GCC4, the size is 16. +# define ACE_SIZEOF_LONG_DOUBLE 16 +# endif // GCC 3.3 +#endif // ACE_SIZEOF_LONG_DOUBLE + +#if defined (__GNUG__) +# include "ace/config-g++-common.h" +#endif /* __GNUG__ */ + +#define ACE_ISCTYPE_EQUIVALENT __isctype + +#ifndef ACE_HAS_NONCONST_FD_ISSET +#define ACE_HAS_NONCONST_FD_ISSET +#endif + +#define ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR + +#define ACE_SIZE_T_FORMAT_SPECIFIER_ASCII "%lu" + +#if !defined (__i386__) +# if defined (ACE_HAS_PENTIUM) +# undef ACE_HAS_PENTIUM +# endif /* ACE_HAS_PENTIUM */ +#else // __i386__ +# define ACE_HAS_PENTIUM +#endif //__i386__ + +#if !defined (_THREAD_SAFE) +#define _THREAD_SAFE +#endif /* _THREAD_SAFE */ + +#define ACE_HAS_GPERF +#define ACE_HAS_POSIX_SEM + +#define ACE_HAS_SUNOS4_GETTIMEOFDAY + +#define ACE_LACKS_STROPTS_H + +// Platform provides header. +#define ACE_HAS_EXECINFO_H + +// Wcharness.... +#define ACE_HAS_WCHAR +#define ACE_SIZEOF_WCHAR 4 + + +#define ACE_HAS_3_PARAM_WCSTOK +#define ACE_LACKS_ITOW +#define ACE_LACKS_WCSICMP +#define ACE_LACKS_WCSNICMP +#define ACE_LACKS_WCSDUP + +// Mac lacks the following pthread features +#define ACE_LACKS_MUTEXATTR_PSHARED +#define ACE_LACKS_CONDATTR_PSHARED +// +// Compiler/platform defines the sig_atomic_t typedef. +#define ACE_HAS_SIG_ATOMIC_T + +// Compiler/platform supports SVR4 signal typedef +#define ACE_HAS_SVR4_SIGNAL_T + +//Platform/compiler has the sigwait(2) prototype +#define ACE_HAS_SIGWAIT + +#define ACE_HAS_AIO_CALLS + +//Platform supports sigsuspend() +#define ACE_HAS_SIGSUSPEND + +#define ACE_LACKS_GETPGID +#define ACE_LACKS_RWLOCK_T + +// Optimize ACE_Handle_Set for select(). +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT + +#define ACE_HAS_NONCONST_SELECT_TIMEVAL + +#define ACE_NEEDS_SCHED_H + +// Use of is deprecated. +#define ACE_LACKS_MALLOC_H + +#define ACE_HAS_ALT_CUSERID + +// Platform supports POSIX timers via struct timespec. +#define ACE_HAS_POSIX_TIME +#define ACE_HAS_UALARM + +// Platform defines struct timespec but not timespec_t +#define ACE_LACKS_TIMESPEC_T + +#define ACE_LACKS_STRRECVFD + +#define ACE_HAS_SOCKADDR_IN_SIN_LEN +#define ACE_HAS_SOCKADDR_IN6_SIN6_LEN + +// Platform supports System V IPC (most versions of UNIX, but not Win32) +#define ACE_HAS_SYSV_IPC + +// Compiler/platform contains the file. +#define ACE_HAS_SYS_SYSCALL_H + +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES + +// Compiler/platform supports alloca(). +// Although ACE does have alloca() on this compiler/platform combination, it is +// disabled by default since it can be dangerous. Uncomment the following line +// if you ACE to use it. +//#define ACE_HAS_ALLOCA + +// Compiler/platform correctly calls init()/fini() for shared libraries. +#define ACE_HAS_AUTOMATIC_INIT_FINI + +// platform supports POSIX O_NONBLOCK semantics +#define ACE_HAS_POSIX_NONBLOCK + +// platform supports IP multicast +#define ACE_HAS_IP_MULTICAST +#define ACE_LACKS_PERFECT_MULTICAST_FILTERING 1 + +// Compiler/platform has the getrusage() system call. +#define ACE_HAS_GETRUSAGE + +// Compiler supports the ssize_t typedef. +#define ACE_HAS_SSIZE_T + +// Compiler/platform provides the sockio.h file. +#define ACE_HAS_SYS_SOCKIO_H + +// Compiler/platform provides the socklen_t type. +#define ACE_HAS_SOCKLEN_T + +// Defines the page size of the system. +#define ACE_HAS_GETPAGESIZE + +// Platform provides header. +#define ACE_HAS_SYS_FILIO_H + +// Platform/compiler supports timezone * as second parameter to gettimeofday(). +#define ACE_HAS_TIMEZONE_GETTIMEOFDAY + +#define ACE_LACKS_SYS_MSG_H +#define ACE_LACKS_SYSV_MSQ_PROTOS +#define ACE_HAS_MSG +#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG +#define ACE_HAS_NONCONST_MSGSND + +#if !defined (ACE_MT_SAFE) +# define ACE_MT_SAFE 1 +#endif + +#if ACE_MT_SAFE == 1 +// Yes, we do have threads. +# define ACE_HAS_THREADS +// And they're even POSIX pthreads +# define ACE_HAS_PTHREADS +# define ACE_HAS_PTHREADS_STD +# define ACE_HAS_PTHREAD_SCHEDPARAM +# define ACE_HAS_THREAD_SPECIFIC_STORAGE +#endif /* ACE_MT_SAFE == 1 */ + +#define ACE_LACKS_THREAD_PROCESS_SCOPING + +#define ACE_HAS_DIRENT +#define ACE_LACKS_POLL_H +#define ACE_LACKS_SEARCH_H + +#define ACE_LACKS_SETSCHED +//#define ACE_HAS_RECURSIVE_MUTEXES + +// Platform has POSIX terminal interface. +#define ACE_HAS_TERMIOS + +#define ACE_HAS_SEMUN +#define ACE_HAS_SIGINFO_T +#define ACE_LACKS_SIGINFO_H +#define ACE_HAS_UCONTEXT_T +#define ACE_HAS_GETIFADDRS +#define ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES +#define ACE_LACKS_UNNAMED_SEMAPHORE + +#if !defined (__DARWIN_UNIX03) +#define ACE_HAS_VOID_UNSETENV +#endif + + +// dlcompat package (not part of base Darwin) is needed for dlopen(). +// You may download directly from sourceforge and install or use fink +// Fink installer puts libraries in /sw/lib and headers in /sw/include +// In order to install dlcompat do the following: +// - download fink from http://fink.sf.net +// - type: +// fink install dlcompat +// as of Dec 2002, if you use fink you will need to uncomment the next line +// #define ACE_NEEDS_DL_UNDERSCORE +#define ACE_HAS_SVR4_DYNAMIC_LINKING +#define ACE_LD_SEARCH_PATH ACE_TEXT ("DYLD_LIBRARY_PATH") +#define ACE_DLL_SUFFIX ACE_TEXT (".dylib") +//#define ACE_LACKS_DLCLOSE + +// gperf seems to need this +//#define ACE_HAS_NONSTATIC_OBJECT_MANAGER + +#if defined(__APPLE_CC__) && (__APPLE_CC__ < 1173) +#error "Compiler must be upgraded, see http://developer.apple.com" +#endif /* __APPLE_CC__ */ + +#endif /* ACE_CONFIG_MACOSX_TIGER_H */ diff --git a/dep/acelite/ace/config-macosx-panther.h b/dep/acelite/ace/config-macosx-panther.h new file mode 100644 index 00000000000..4b131f9867a --- /dev/null +++ b/dep/acelite/ace/config-macosx-panther.h @@ -0,0 +1,182 @@ +/* -*- C++ -*- */ +// $Id: config-macosx-panther.h 87167 2009-10-19 19:33:53Z olli $ + +// This configuration file is designed to work with the MacOS X operating system. + +#ifndef ACE_CONFIG_MACOSX_H +#define ACE_CONFIG_MACOSX_H + +#if ! defined (__ACE_INLINE__) +#define __ACE_INLINE__ +#endif /* ! __ACE_INLINE__ */ + +#if defined (__GNUG__) +# include "ace/config-g++-common.h" +#endif /* __GNUG__ */ + +#define ACE_LACKS_SUSECONDS_T +#define ACE_SIZE_T_FORMAT_SPECIFIER_ASCII "%lu" + +#if defined (ACE_HAS_PENTIUM) +# undef ACE_HAS_PENTIUM +#endif /* ACE_HAS_PENTIUM */ + +#if !defined (_THREAD_SAFE) +#define _THREAD_SAFE +#endif /* _THREAD_SAFE */ + +#define ACE_HAS_GPERF +#define ACE_HAS_POSIX_SEM + +//#define ACE_HAS_SVR4_TLI + +#define ACE_LACKS_STROPTS_H +#define ACE_LACKS_WCHAR_H + +// +// Compiler/platform defines the sig_atomic_t typedef. +#define ACE_HAS_SIG_ATOMIC_T + +// Compiler/platform supports SVR4 signal typedef +#define ACE_HAS_SVR4_SIGNAL_T + +//Platform/compiler has the sigwait(2) prototype +#define ACE_HAS_SIGWAIT + +//Platform supports sigsuspend() +#define ACE_HAS_SIGSUSPEND + +//#define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS +#define ACE_LACKS_GETPGID +#define ACE_LACKS_RWLOCK_T + +// Optimize ACE_Handle_Set for select(). +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT + +#define ACE_HAS_NONCONST_SELECT_TIMEVAL + +#define ACE_NEEDS_SCHED_H + +// Use of is deprecated. +#define ACE_LACKS_MALLOC_H + +#define ACE_HAS_ALT_CUSERID + +// Platform supports POSIX timers via struct timespec. +#define ACE_HAS_POSIX_TIME +#define ACE_HAS_UALARM + +// Platform defines struct timespec but not timespec_t +#define ACE_LACKS_TIMESPEC_T + +#define ACE_LACKS_STRRECVFD + +#define ACE_HAS_SOCKADDR_IN_SIN_LEN +#define ACE_HAS_SOCKADDR_IN6_SIN6_LEN + +// Platform supports System V IPC (most versions of UNIX, but not Win32) +#define ACE_HAS_SYSV_IPC + +// Compiler/platform contains the file. +#define ACE_HAS_SYS_SYSCALL_H + +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES + +// Compiler/platform supports alloca(). +// Although ACE does have alloca() on this compiler/platform combination, it is +// disabled by default since it can be dangerous. Uncomment the following line +// if you ACE to use it. +//#define ACE_HAS_ALLOCA + +// Compiler/platform correctly calls init()/fini() for shared libraries. +#define ACE_HAS_AUTOMATIC_INIT_FINI + +// Explicit dynamic linking permits "lazy" symbol resolution +//#define ACE_HAS_RTLD_LAZY_V + +// platform supports POSIX O_NONBLOCK semantics +#define ACE_HAS_POSIX_NONBLOCK + +// platform supports IP multicast +#define ACE_HAS_IP_MULTICAST +#define ACE_LACKS_PERFECT_MULTICAST_FILTERING 1 + +// Compiler/platform has the getrusage() system call. +#define ACE_HAS_GETRUSAGE + +// Compiler supports the ssize_t typedef. +#define ACE_HAS_SSIZE_T + +// Compiler/platform provides the sockio.h file. +#define ACE_HAS_SYS_SOCKIO_H + +// Defines the page size of the system. +#define ACE_HAS_GETPAGESIZE + +// Platform provides header. +#define ACE_HAS_SYS_FILIO_H + +// Platform/compiler supports timezone * as second parameter to gettimeofday(). +#define ACE_HAS_TIMEZONE_GETTIMEOFDAY + +#define ACE_LACKS_SYS_MSG_H +#define ACE_LACKS_SYSV_MSQ_PROTOS +#define ACE_HAS_MSG +#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG +#define ACE_HAS_NONCONST_MSGSND + +#if !defined (ACE_MT_SAFE) +# define ACE_MT_SAFE 1 +#endif + +#if ACE_MT_SAFE == 1 +// Yes, we do have threads. +# define ACE_HAS_THREADS +// And they're even POSIX pthreads +# define ACE_HAS_PTHREADS +# define ACE_HAS_PTHREAD_SCHEDPARAM +# define ACE_HAS_THREAD_SPECIFIC_STORAGE +#endif /* ACE_MT_SAFE == 1 */ + +# define ACE_LACKS_THREAD_PROCESS_SCOPING + +#define ACE_HAS_DIRENT +#define ACE_LACKS_POLL_H +#define ACE_LACKS_SEARCH_H + +#define ACE_LACKS_SETSCHED +//#define ACE_HAS_RECURSIVE_MUTEXES + +// Platform has POSIX terminal interface. +#define ACE_HAS_TERMIOS + +#define ACE_HAS_SEMUN +#define ACE_HAS_SIGINFO_T +#define ACE_LACKS_SIGINFO_H +#define ACE_HAS_UCONTEXT_T +#define ACE_HAS_GETIFADDRS +#define ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES +#define ACE_LACKS_UNNAMED_SEMAPHORE + +// dlcompat package (not part of base Darwin) is needed for dlopen(). +// You may download directly from sourceforge and install or use fink +// Fink installer puts libraries in /sw/lib and headers in /sw/include +// In order to install dlcompat do the following: +// - download fink from http://fink.sf.net +// - type: +// fink install dlcompat +// as of Dec 2002, if you use fink you will need to uncomment the next line +//#define ACE_NEEDS_DL_UNDERSCORE +#define ACE_HAS_SVR4_DYNAMIC_LINKING +#define ACE_LD_SEARCH_PATH ACE_TEXT ("DYLD_LIBRARY_PATH") +#define ACE_DLL_SUFFIX ACE_TEXT (".dylib") +//#define ACE_LACKS_DLCLOSE + +// gperf seems to need this +//#define ACE_HAS_NONSTATIC_OBJECT_MANAGER + +#if defined(__APPLE_CC__) && (__APPLE_CC__ < 1173) +#error "Compiler must be upgraded, see http://developer.apple.com" +#endif /* __APPLE_CC__ */ + +#endif /* ACE_CONFIG_MACOSX_H */ diff --git a/dep/acelite/ace/config-macosx-snowleopard.h b/dep/acelite/ace/config-macosx-snowleopard.h new file mode 100644 index 00000000000..09e9458d6b9 --- /dev/null +++ b/dep/acelite/ace/config-macosx-snowleopard.h @@ -0,0 +1,17 @@ +// $Id: config-macosx-snowleopard.h 91093 2010-07-15 09:12:20Z wotte $ +#ifndef ACE_CONFIG_MACOSX_SNOWLEOPARD_H +#define ACE_CONFIG_MACOSX_SNOWLEOPARD_H + + +#include "ace/config-macosx-leopard.h" + +#ifdef __clang__ +#ifdef ACE_HAS_GCC_ATOMIC_BUILTINS +#undef ACE_HAS_GCC_ATOMIC_BUILTINS +#endif +#endif + +// This header has been deprecated in Snow Leopard. +#define ACE_LACKS_UCONTEXT_H + +#endif // ACE_CONFIG_MACOSX_SNOWLEOPARD_H diff --git a/dep/acelite/ace/config-macosx-tiger.h b/dep/acelite/ace/config-macosx-tiger.h new file mode 100644 index 00000000000..f3d1ddcf8ad --- /dev/null +++ b/dep/acelite/ace/config-macosx-tiger.h @@ -0,0 +1,213 @@ +/* -*- C++ -*- */ +// $Id: config-macosx-tiger.h 87167 2009-10-19 19:33:53Z olli $ + +// This configuration file is designed to work with the MacOS X operating system. + +#ifndef ACE_CONFIG_MACOSX_TIGER_H +#define ACE_CONFIG_MACOSX_TIGER_H + +#if ! defined (__ACE_INLINE__) +#define __ACE_INLINE__ +#endif /* ! __ACE_INLINE__ */ + +#if !defined (ACE_SIZEOF_LONG_DOUBLE) +# if (__GNUC__ == 3 && __GNUC_MINOR__ == 3) + // Size of long double in GCC 3.3 is 8. +# define ACE_SIZEOF_LONG_DOUBLE 8 +# else // Else, the compiler is GCC4 + // For GCC4, the size is 16. +# define ACE_SIZEOF_LONG_DOUBLE 16 +# endif // GCC 3.3 +#endif // ACE_SIZEOF_LONG_DOUBLE + +#if defined (__GNUG__) +# include "ace/config-g++-common.h" +#endif /* __GNUG__ */ + +#define ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR + +#define ACE_SIZE_T_FORMAT_SPECIFIER_ASCII "%lu" + +#if !defined (__i386__) +# if defined (ACE_HAS_PENTIUM) +# undef ACE_HAS_PENTIUM +# endif /* ACE_HAS_PENTIUM */ +#else // __i386__ +# define ACE_HAS_PENTIUM +#endif //__i386__ + +#if !defined (_THREAD_SAFE) +#define _THREAD_SAFE +#endif /* _THREAD_SAFE */ + +#define ACE_HAS_GPERF +#define ACE_HAS_POSIX_SEM + +#define ACE_HAS_SUNOS4_GETTIMEOFDAY + +#define ACE_LACKS_STROPTS_H + +// Wcharness.... +#define ACE_HAS_WCHAR +#define ACE_SIZEOF_WCHAR 4 + + +#define ACE_HAS_3_PARAM_WCSTOK +#define ACE_LACKS_ITOW +#define ACE_LACKS_WCSICMP +#define ACE_LACKS_WCSNICMP +#define ACE_LACKS_WCSDUP + +// Mac lacks the following pthread features +#define ACE_LACKS_MUTEXATTR_PSHARED +#define ACE_LACKS_CONDATTR_PSHARED +// +// Compiler/platform defines the sig_atomic_t typedef. +#define ACE_HAS_SIG_ATOMIC_T + +// Compiler/platform supports SVR4 signal typedef +#define ACE_HAS_SVR4_SIGNAL_T + +//Platform/compiler has the sigwait(2) prototype +#define ACE_HAS_SIGWAIT + +#define ACE_HAS_AIO_CALLS + +//Platform supports sigsuspend() +#define ACE_HAS_SIGSUSPEND + +#define ACE_LACKS_GETPGID +#define ACE_LACKS_RWLOCK_T + +// Optimize ACE_Handle_Set for select(). +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT + +#define ACE_HAS_NONCONST_SELECT_TIMEVAL + +#define ACE_NEEDS_SCHED_H + +// Use of is deprecated. +#define ACE_LACKS_MALLOC_H + +#define ACE_HAS_ALT_CUSERID + +// Platform supports POSIX timers via struct timespec. +#define ACE_HAS_POSIX_TIME +#define ACE_HAS_UALARM + +// Platform defines struct timespec but not timespec_t +#define ACE_LACKS_TIMESPEC_T + +#define ACE_LACKS_STRRECVFD + +#define ACE_HAS_SOCKADDR_IN6_SIN6_LEN + +// Platform supports System V IPC (most versions of UNIX, but not Win32) +#define ACE_HAS_SYSV_IPC + +// Compiler/platform contains the file. +#define ACE_HAS_SYS_SYSCALL_H + +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES + +// Compiler/platform supports alloca(). +// Although ACE does have alloca() on this compiler/platform combination, it is +// disabled by default since it can be dangerous. Uncomment the following line +// if you ACE to use it. +//#define ACE_HAS_ALLOCA + +// Compiler/platform correctly calls init()/fini() for shared libraries. +#define ACE_HAS_AUTOMATIC_INIT_FINI + +// platform supports POSIX O_NONBLOCK semantics +#define ACE_HAS_POSIX_NONBLOCK + +// platform supports IP multicast +#define ACE_HAS_IP_MULTICAST +#define ACE_LACKS_PERFECT_MULTICAST_FILTERING 1 + +// Compiler/platform has the getrusage() system call. +#define ACE_HAS_GETRUSAGE + +// Compiler supports the ssize_t typedef. +#define ACE_HAS_SSIZE_T + +// Compiler/platform provides the sockio.h file. +#define ACE_HAS_SYS_SOCKIO_H + +// Compiler/platform provides the socklen_t type. +#define ACE_HAS_SOCKLEN_T + +// Defines the page size of the system. +#define ACE_HAS_GETPAGESIZE + +// Platform provides header. +#define ACE_HAS_SYS_FILIO_H + +// Platform/compiler supports timezone * as second parameter to gettimeofday(). +#define ACE_HAS_TIMEZONE_GETTIMEOFDAY + +#define ACE_LACKS_SYS_MSG_H +#define ACE_LACKS_SYSV_MSQ_PROTOS +#define ACE_HAS_MSG +#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG +#define ACE_HAS_NONCONST_MSGSND + +#if !defined (ACE_MT_SAFE) +# define ACE_MT_SAFE 1 +#endif + +#if ACE_MT_SAFE == 1 +// Yes, we do have threads. +# define ACE_HAS_THREADS +// And they're even POSIX pthreads +# define ACE_HAS_PTHREADS +# define ACE_HAS_PTHREAD_SCHEDPARAM +# define ACE_HAS_THREAD_SPECIFIC_STORAGE +#endif /* ACE_MT_SAFE == 1 */ + +#define ACE_LACKS_THREAD_PROCESS_SCOPING + +#define ACE_HAS_DIRENT +#define ACE_LACKS_POLL_H +#define ACE_LACKS_SEARCH_H + +#define ACE_LACKS_SETSCHED +//#define ACE_HAS_RECURSIVE_MUTEXES + +// Platform has POSIX terminal interface. +#define ACE_HAS_TERMIOS + +#define ACE_HAS_SEMUN +#define ACE_HAS_SIGINFO_T +#define ACE_LACKS_SIGINFO_H +#define ACE_HAS_UCONTEXT_T +#define ACE_HAS_GETIFADDRS +#define ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES +#define ACE_LACKS_UNNAMED_SEMAPHORE + +// dlcompat package (not part of base Darwin) is needed for dlopen(). +// You may download directly from sourceforge and install or use fink +// Fink installer puts libraries in /sw/lib and headers in /sw/include +// In order to install dlcompat do the following: +// - download fink from http://fink.sf.net +// - type: +// fink install dlcompat +// as of Dec 2002, if you use fink you will need to uncomment the next line +// #define ACE_NEEDS_DL_UNDERSCORE +#define ACE_HAS_SVR4_DYNAMIC_LINKING +#define ACE_LD_SEARCH_PATH ACE_TEXT ("DYLD_LIBRARY_PATH") +#define ACE_DLL_SUFFIX ACE_TEXT (".dylib") +//#define ACE_LACKS_DLCLOSE + +// gperf seems to need this +//#define ACE_HAS_NONSTATIC_OBJECT_MANAGER + +#define ACE_LACKS_UNSETENV +#define ACE_LACKS_ISCTYPE + +#if defined(__APPLE_CC__) && (__APPLE_CC__ < 1173) +#error "Compiler must be upgraded, see http://developer.apple.com" +#endif /* __APPLE_CC__ */ + +#endif /* ACE_CONFIG_MACOSX_TIGER_H */ diff --git a/dep/acelite/ace/config-macosx.h b/dep/acelite/ace/config-macosx.h new file mode 100644 index 00000000000..ae2552f14a2 --- /dev/null +++ b/dep/acelite/ace/config-macosx.h @@ -0,0 +1,182 @@ +/* -*- C++ -*- */ +// $Id: config-macosx.h 87167 2009-10-19 19:33:53Z olli $ + +// This configuration file is designed to work with the MacOS X operating system, version 10.2 (Jaguar). + +#ifndef ACE_CONFIG_MACOSX_H +#define ACE_CONFIG_MACOSX_H + +#if ! defined (__ACE_INLINE__) +#define __ACE_INLINE__ +#endif /* ! __ACE_INLINE__ */ + +#if defined (__GNUG__) +# include "ace/config-g++-common.h" +#endif /* __GNUG__ */ + +#define ACE_SIZE_T_FORMAT_SPECIFIER_ASCII "%lu" + +#if defined (ACE_HAS_PENTIUM) +# undef ACE_HAS_PENTIUM +#endif /* ACE_HAS_PENTIUM */ + +#if !defined (_THREAD_SAFE) +#define _THREAD_SAFE +#endif /* _THREAD_SAFE */ + +#define ACE_HAS_GPERF +#define ACE_HAS_POSIX_SEM + +//#define ACE_HAS_SVR4_TLI + +#define ACE_LACKS_STROPTS_H +#define ACE_LACKS_WCHAR_H + +#define ACE_SYS_SELECT_NEEDS_UNISTD_H + +// +// Compiler/platform defines the sig_atomic_t typedef. +#define ACE_HAS_SIG_ATOMIC_T + +// Compiler/platform supports SVR4 signal typedef +#define ACE_HAS_SVR4_SIGNAL_T + +//Platform/compiler has the sigwait(2) prototype +#define ACE_HAS_SIGWAIT + +//Platform supports sigsuspend() +#define ACE_HAS_SIGSUSPEND + +//#define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS +#define ACE_LACKS_GETPGID +#define ACE_LACKS_RWLOCK_T + +// Optimize ACE_Handle_Set for select(). +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT + +#define ACE_HAS_NONCONST_SELECT_TIMEVAL + +#define ACE_HAS_SYSCTL + +#define ACE_NEEDS_SCHED_H + +// Use of is deprecated. +#define ACE_LACKS_MALLOC_H + +#define ACE_HAS_ALT_CUSERID + +// Platform supports POSIX timers via struct timespec. +#define ACE_HAS_POSIX_TIME +#define ACE_HAS_UALARM + +// Platform defines struct timespec but not timespec_t +#define ACE_LACKS_TIMESPEC_T + +#define ACE_LACKS_STRRECVFD + +#define ACE_HAS_SOCKADDR_IN6_SIN6_LEN + +// Platform supports System V IPC (most versions of UNIX, but not Win32) +//#define ACE_HAS_SYSV_IPC + +// Compiler/platform contains the file. +#define ACE_HAS_SYS_SYSCALL_H + +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES + +// Compiler/platform supports alloca(). +// Although ACE does have alloca() on this compiler/platform combination, it is +// disabled by default since it can be dangerous. Uncomment the following line +// if you ACE to use it. +//#define ACE_HAS_ALLOCA + +// Compiler/platform correctly calls init()/fini() for shared libraries. +#define ACE_HAS_AUTOMATIC_INIT_FINI + +// Explicit dynamic linking permits "lazy" symbol resolution +//#define ACE_HAS_RTLD_LAZY_V + +// platform supports POSIX O_NONBLOCK semantics +#define ACE_HAS_POSIX_NONBLOCK + +// platform supports IP multicast +#define ACE_HAS_IP_MULTICAST +#define ACE_LACKS_PERFECT_MULTICAST_FILTERING 1 + +// Compiler/platform has the getrusage() system call. +#define ACE_HAS_GETRUSAGE + +// Compiler supports the ssize_t typedef. +#define ACE_HAS_SSIZE_T + +// Compiler/platform provides the sockio.h file. +#define ACE_HAS_SYS_SOCKIO_H + +// Defines the page size of the system. +#define ACE_HAS_GETPAGESIZE + +// Platform provides header. +#define ACE_HAS_SYS_FILIO_H + +// Platform/compiler supports timezone * as second parameter to gettimeofday(). +#define ACE_HAS_TIMEZONE_GETTIMEOFDAY + +#define ACE_LACKS_SYS_MSG_H +#define ACE_LACKS_SYSV_MSQ_PROTOS +#define ACE_HAS_MSG +#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG +#define ACE_HAS_NONCONST_MSGSND + +#if !defined (ACE_MT_SAFE) +# define ACE_MT_SAFE 1 +#endif + +#if ACE_MT_SAFE == 1 +// Yes, we do have threads. +# define ACE_HAS_THREADS +// And they're even POSIX pthreads +# define ACE_HAS_PTHREADS +# define ACE_HAS_THREAD_SPECIFIC_STORAGE +# define ACE_LACKS_THREAD_PROCESS_SCOPING +#endif /* ACE_MT_SAFE == 1 */ + +#define ACE_HAS_DIRENT +#define ACE_LACKS_POLL_H +#define ACE_LACKS_SEARCH_H + +#define ACE_LACKS_SETSCHED +//#define ACE_HAS_RECURSIVE_MUTEXES + +// Platform has POSIX terminal interface. +#define ACE_HAS_TERMIOS + +#define ACE_HAS_SEMUN +#define ACE_HAS_SIGINFO_T +#define ACE_LACKS_SIGINFO_H +#define ACE_HAS_UCONTEXT_T +#define ACE_HAS_GETIFADDRS +#define ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES +#define ACE_LACKS_UNNAMED_SEMAPHORE + +// dlcompat package (not part of base Darwin) is needed for dlopen(). +// You may download directly from sourceforge and install or use fink +// Fink installer puts libraries in /sw/lib and headers in /sw/include +// In order to install dlcompat do the following: +// - download fink from http://fink.sf.net +// - type: +// fink install dlcompat +// as of Dec 2002, if you use fink you will need to uncomment the next line +//#define ACE_NEEDS_DL_UNDERSCORE +#define ACE_HAS_SVR4_DYNAMIC_LINKING +#define ACE_LD_SEARCH_PATH ACE_TEXT ("DYLD_LIBRARY_PATH") +#define ACE_DLL_SUFFIX ACE_TEXT (".dylib") +#define ACE_LACKS_DLCLOSE + +// gperf seems to need this +#define ACE_HAS_NONSTATIC_OBJECT_MANAGER + +#if defined(__APPLE_CC__) && (__APPLE_CC__ < 1173) +#error "Compiler must be upgraded, see http://developer.apple.com" +#endif /* __APPLE_CC__ */ + +#endif /* ACE_CONFIG_MACOSX_H */ diff --git a/dep/acelite/ace/config-macros.h b/dep/acelite/ace/config-macros.h new file mode 100644 index 00000000000..6820fc351d9 --- /dev/null +++ b/dep/acelite/ace/config-macros.h @@ -0,0 +1,655 @@ +// -*- C++ -*- + +//========================================================================== +/** + * @file config-macros.h + * + * $Id: config-macros.h 88485 2010-01-12 13:36:59Z schmidt $ + * + * @author (Originally in OS.h)Doug Schmidt + * @author Jesper S. M|ller + * @author and a cast of thousands... + * + * This file contains the contents of the old config-lite.h header + * without C++ code (except for C++ code in macros). Specifically, + * only macros or C language constructs are found in this header. + * Allows configuration values and macros to be used by some C + * language sources. + */ +//========================================================================== + +#ifndef ACE_CONFIG_MACROS_H +#define ACE_CONFIG_MACROS_H + +#ifdef _WIN32 + #include "ace/config-win32.h" +#else + #include "ace/config.h" +#endif + +#include "ace/Version.h" +#include "ace/Versioned_Namespace.h" + +// ACE_HAS_TLI is used to decide whether to try any XTI/TLI functionality +// so if it isn't set, set it. Capabilities and differences between +// XTI and TLI favor XTI, but when deciding to do anything, as opposed to +// ACE_NOTSUP_RETURN for example, ACE_HAS_TLI is the deciding factor. +#if !defined (ACE_HAS_TLI) +# if defined (ACE_HAS_XTI) +# define ACE_HAS_TLI +# endif /* ACE_HAS_XTI */ +#endif /* ACE_HAS_TLI */ + +#define ACE_BITS_PER_ULONG (8 * sizeof (u_long)) + +#if !defined (ACE_OSTREAM_TYPE) +# if defined (ACE_LACKS_IOSTREAM_TOTALLY) +# define ACE_OSTREAM_TYPE FILE +# else /* ! ACE_LACKS_IOSTREAM_TOTALLY */ +# define ACE_OSTREAM_TYPE ostream +# endif /* ! ACE_LACKS_IOSTREAM_TOTALLY */ +#endif /* ! ACE_OSTREAM_TYPE */ + +#if !defined (ACE_DEFAULT_LOG_STREAM) +# if defined (ACE_LACKS_IOSTREAM_TOTALLY) +# define ACE_DEFAULT_LOG_STREAM 0 +# else /* ! ACE_LACKS_IOSTREAM_TOTALLY */ +# define ACE_DEFAULT_LOG_STREAM (&cerr) +# endif /* ! ACE_LACKS_IOSTREAM_TOTALLY */ +#endif /* ! ACE_DEFAULT_LOG_STREAM */ + +// These two are only for backward compatibility. You should avoid +// using them if not necessary. +#if !defined (ACE_LACKS_DEPRECATED_MACROS) +/** + * @deprecated The ACE_SYNCH_1 macro is deprecated + */ +# define ACE_SYNCH_1 ACE_SYNCH_DECL +/** + * @deprecated The ACE_SYNCH_2 macro is deprecated + */ +# define ACE_SYNCH_2 ACE_SYNCH_USE +#endif + +// For Win32 compatibility... +# if !defined (ACE_WSOCK_VERSION) +# define ACE_WSOCK_VERSION 0, 0 +# endif /* ACE_WSOCK_VERSION */ + +# if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) +# define ACE_MT(X) X +# if !defined (_REENTRANT) +# define _REENTRANT +# endif /* _REENTRANT */ +# else +# define ACE_MT(X) +# endif /* ACE_MT_SAFE */ + +# if defined (ACE_HAS_PURIFY) +# define ACE_INITIALIZE_MEMORY_BEFORE_USE +# endif /* ACE_HAS_PURIFY */ + +# if defined (ACE_HAS_VALGRIND) +# define ACE_INITIALIZE_MEMORY_BEFORE_USE +# endif /* ACE_HAS_VALGRIND */ + +#if !defined (ACE_LACKS_DEPRECATED_MACROS) +/** + * @deprecated The @c ACE_HAS_USING macros are deprecated + */ +# define ACE_USING using +#endif /* !ACE_LACKS_DEPRECATED_MACROS */ + +#if !defined (ACE_LACKS_DEPRECATED_MACROS) +/** + * @deprecated The @c ACE_TYPENAME macros is deprecated. Use standard + * C++ keyword typename instead. + */ +# define ACE_TYPENAME typename +#endif /* !ACE_LACKS_DEPRECATED_MACROS */ + +#if !defined (ACE_LACKS_DEPRECATED_MACROS) +/** + * @deprecated The @c ACE_TEMPLATE_SPECIALIZATION and + * @c ACE_TEMPLATE_CLASS_MEMBER_SPECIALIZATION macros are + * deprecated. Use standard C++ template specialization + * syntax instead. + */ +# define ACE_TEMPLATE_SPECIALIZATION template<> +# define ACE_TEMPLATE_CLASS_MEMBER_SPECIALIZATION +#endif /* !ACE_LACKS_DEPRECATED_MACROS */ + +// ========================================================================= +// Perfect Multicast filting refers to RFC 3376, where a socket is only +// delivered dgrams for groups joined even if it didn't bind the group +// address. We turn this option off by default, although most OS's +// except for Windows and Solaris probably lack perfect filtering. +// ========================================================================= + +# if !defined (ACE_LACKS_PERFECT_MULTICAST_FILTERING) +# define ACE_LACKS_PERFECT_MULTICAST_FILTERING 0 +# endif /* ACE_LACKS_PERFECT_MULTICAST_FILTERING */ + +// ========================================================================= +// Enable/Disable Features By Default +// ========================================================================= + +# if !defined (ACE_HAS_POSITION_INDEPENDENT_POINTERS) +# define ACE_HAS_POSITION_INDEPENDENT_POINTERS 1 +# endif /* ACE_HAS_POSITION_INDEPENDENT_POINTERS */ + +# if !defined (ACE_HAS_PROCESS_SPAWN) +# if !defined (ACE_LACKS_FORK) || \ + (defined (ACE_WIN32) && !defined (ACE_HAS_PHARLAP)) || \ + defined (ACE_WINCE) || defined (ACE_OPENVMS) +# define ACE_HAS_PROCESS_SPAWN 1 +# endif +# endif /* ACE_HAS_PROCESS_SPAWN */ + +# if !defined (ACE_HAS_DYNAMIC_LINKING) +# if defined (ACE_HAS_SVR4_DYNAMIC_LINKING) || defined (ACE_WIN32) || defined (ACE_VXWORKS) || defined (__hpux) +# define ACE_HAS_DYNAMIC_LINKING 1 +# endif +# endif /* ACE_HAS_DYNAMIC_LINKING */ + +# if defined (ACE_USES_FIFO_SEM) +# if defined (ACE_HAS_POSIX_SEM) || defined (ACE_LACKS_MKFIFO) || defined (ACE_LACKS_FCNTL) +# undef ACE_USES_FIFO_SEM +# endif +# endif /* ACE_USES_FIFO_SEM */ + +// ========================================================================= +// RCSID Macros +// ========================================================================= + +// By default, DO NOT include RCS Id strings in object code. +#if ! defined (ACE_USE_RCSID) +# define ACE_USE_RCSID 0 +#endif /* #if ! defined (ACE_USE_RCSID) */ + +#if (defined (ACE_USE_RCSID) && (ACE_USE_RCSID != 0)) +# if ! defined (ACE_RCSID) + + // This hack has the following purposes: + // 1. To define the RCS id string variable as a static char*, so + // that there won't be any duplicate extern symbols at link + // time. + // 2. To have a RCS id string variable with a unique name for each + // file. + // 3. To avoid warnings of the type "variable declared and never + // used". + +# define ACE_RCSID(path, file, id) \ + static inline const char* get_rcsid_ ## path ## _ ## file (const char*) \ + { \ + return id ; \ + } \ + static const char* rcsid_ ## path ## _ ## file = \ + get_rcsid_ ## path ## _ ## file ( rcsid_ ## path ## _ ## file ) ; + +# endif /* #if ! defined (ACE_RCSID) */ +#else + + // RCS id strings are not wanted. +# if defined (ACE_RCSID) +# undef ACE_RCSID +# endif /* #if defined (ACE_RCSID) */ +# define ACE_RCSID(path, file, id) /* noop */ +#endif /* #if (defined (ACE_USE_RCSID) && (ACE_USE_RCSID != 0)) */ + +// ========================================================================= +// INLINE macros +// +// These macros handle all the inlining of code via the .i or .inl files +// ========================================================================= + +#if defined (ACE_LACKS_INLINE_FUNCTIONS) && !defined (ACE_NO_INLINE) +# define ACE_NO_INLINE +#endif /* defined (ACE_LACKS_INLINE_FUNCTIONS) && !defined (ACE_NO_INLINE) */ + +// ACE inlining has been explicitly disabled. Implement +// internally within ACE by undefining __ACE_INLINE__. +#if defined (ACE_NO_INLINE) +# undef __ACE_INLINE__ +#endif /* ! ACE_NO_INLINE */ + +#if defined (__ACE_INLINE__) +# define ACE_INLINE inline +# if !defined (ACE_HAS_INLINED_OSCALLS) +# define ACE_HAS_INLINED_OSCALLS +# endif /* !ACE_HAS_INLINED_OSCALLS */ +#else +# define ACE_INLINE +#endif /* __ACE_INLINE__ */ + +#if !defined (ACE_LACKS_DEPRECATED_MACROS) + // ========================================================================= + // EXPLICIT macro + // ========================================================================= + + /** + * @deprecated explicit is deprecated. ACE requires C++ + * "explicit" keyword support. + */ + # define ACE_EXPLICIT explicit +#endif /* ACE_LACKS_DEPRECATED_MACROS */ + +#if !defined (ACE_LACKS_DEPRECATED_MACROS) + // ========================================================================= + // MUTABLE macro + // ========================================================================= + + /** + * @deprecated ACE_MUTABLE is deprecated. ACE requires C++ "mutable" + * keyword support. + */ + # define ACE_MUTABLE mutable + # define ACE_CONST_WHEN_MUTABLE const +#endif /* ACE_LACKS_DEPRECATED_MACROS */ + +// ============================================================================ +// EXPORT macros +// +// Since Win32 DLL's do not export all symbols by default, they must be +// explicitly exported (which is done by *_Export macros). +// ============================================================================ + +// Win32 should have already defined the macros in config-win32-common.h +#if !defined (ACE_HAS_CUSTOM_EXPORT_MACROS) +# define ACE_Proper_Export_Flag +# define ACE_Proper_Import_Flag +# define ACE_EXPORT_SINGLETON_DECLARATION(T) +# define ACE_IMPORT_SINGLETON_DECLARATION(T) +# define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) +# define ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) +#else +// An export macro should at the very least have been defined. + +# ifndef ACE_Proper_Import_Flag +# define ACE_Proper_Import_Flag +# endif /* !ACE_Proper_Import_Flag */ + +# ifndef ACE_EXPORT_SINGLETON_DECLARATION +# define ACE_EXPORT_SINGLETON_DECLARATION(T) +# endif /* !ACE_EXPORT_SINGLETON_DECLARATION */ + +# ifndef ACE_IMPORT_SINGLETON_DECLARATION +# define ACE_IMPORT_SINGLETON_DECLARATION(T) +# endif /* !ACE_IMPORT_SINGLETON_DECLARATION */ + +# ifndef ACE_EXPORT_SINGLETON_DECLARE +# define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) +# endif /* !ACE_EXPORT_SINGLETON_DECLARE */ + +# ifndef ACE_IMPORT_SINGLETON_DECLARE +# define ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) +# endif /* !ACE_IMPORT_SINGLETON_DECLARE */ + +#endif /* !ACE_HAS_CUSTOM_EXPORT_MACROS */ + +// This is a whim of mine -- that instead of annotating a class with +// ACE_Export in its declaration, we make the declaration near the TOP +// of the file with ACE_DECLARE_EXPORT. +// TS = type specifier (e.g., class, struct, int, etc.) +// ID = identifier +// So, how do you use it? Most of the time, just use ... +// ACE_DECLARE_EXPORT(class, someobject); +// If there are global functions to be exported, then use ... +// ACE_DECLARE_EXPORT(void, globalfunction) (int, ...); +// Someday, when template libraries are supported, we made need ... +// ACE_DECLARE_EXPORT(template class, sometemplate) ; +# define ACE_DECLARE_EXPORT(TS,ID) TS ACE_Export ID + +// ============================================================================ +// Cast macros +// +// These macros are used to choose between the old cast style and the new +// *_cast<> operators +// ============================================================================ + +# define ACE_sap_any_cast(TYPE) reinterpret_cast (const_cast (ACE_Addr::sap_any)) + +#if !defined (ACE_LACKS_DEPRECATED_MACROS) + /** + * @deprecated ACE_{static,reinterpret,dynamic,const}_cast@<@> is + * deprecated. Directly use standard C++ casts instead. + */ + # define ACE_static_cast(TYPE, EXPR) static_cast (EXPR) + # define ACE_static_cast_1_ptr(TYPE, T1, EXPR) static_cast *> (EXPR) + # define ACE_static_cast_2_ptr(TYPE, T1, T2, EXPR) static_cast *> (EXPR) + # define ACE_static_cast_3_ptr(TYPE, T1, T2, T3, EXPR) static_cast *> (EXPR) + # define ACE_static_cast_4_ptr(TYPE, T1, T2, T3, T4, EXPR) static_cast *> (EXPR) + # define ACE_static_cast_5_ptr(TYPE, T1, T2, T3, T4, T5, EXPR) static_cast *> (EXPR) + # define ACE_static_cast_1_ref(TYPE, T1, EXPR) static_cast &> (EXPR) + # define ACE_static_cast_2_ref(TYPE, T1, T2, EXPR) static_cast &> (EXPR) + # define ACE_static_cast_3_ref(TYPE, T1, T2, T3, EXPR) static_cast &> (EXPR) + # define ACE_static_cast_4_ref(TYPE, T1, T2, T3, T4, EXPR) static_cast &> (EXPR) + # define ACE_static_cast_5_ref(TYPE, T1, T2, T3, T4, T5, EXPR) static_cast &> (EXPR) + + # define ACE_const_cast(TYPE, EXPR) const_cast (EXPR) + # define ACE_const_cast_1_ptr(TYPE, T1, EXPR) const_cast *> (EXPR) + # define ACE_const_cast_2_ptr(TYPE, T1, T2, EXPR) const_cast *> (EXPR) + # define ACE_const_cast_3_ptr(TYPE, T1, T2, T3, EXPR) const_cast *> (EXPR) + # define ACE_const_cast_4_ptr(TYPE, T1, T2, T3, T4, EXPR) const_cast *> (EXPR) + # define ACE_const_cast_5_ptr(TYPE, T1, T2, T3, T4, T5, EXPR) const_cast *> (EXPR) + # define ACE_const_cast_1_ref(TYPE, T1, EXPR) const_cast &> (EXPR) + # define ACE_const_cast_2_ref(TYPE, T1, T2, EXPR) const_cast &> (EXPR) + # define ACE_const_cast_3_ref(TYPE, T1, T2, T3, EXPR) const_cast &> (EXPR) + # define ACE_const_cast_4_ref(TYPE, T1, T2, T3, T4, EXPR) const_cast &> (EXPR) + # define ACE_const_cast_5_ref(TYPE, T1, T2, T3, T4, T5, EXPR) const_cast &> (EXPR) + + # define ACE_reinterpret_cast(TYPE, EXPR) reinterpret_cast (EXPR) + # define ACE_reinterpret_cast_1_ptr(TYPE, T1, EXPR) reinterpret_cast *> (EXPR) + # define ACE_reinterpret_cast_2_ptr(TYPE, T1, T2, EXPR) reinterpret_cast *> (EXPR) + # define ACE_reinterpret_cast_3_ptr(TYPE, T1, T2, T3, EXPR) reinterpret_cast *> (EXPR) + # define ACE_reinterpret_cast_4_ptr(TYPE, T1, T2, T3, T4, EXPR) reinterpret_cast *> (EXPR) + # define ACE_reinterpret_cast_5_ptr(TYPE, T1, T2, T3, T4, T5, EXPR) reinterpret_cast *> (EXPR) + # define ACE_reinterpret_cast_1_ref(TYPE, T1, EXPR) reinterpret_cast &> (EXPR) + # define ACE_reinterpret_cast_2_ref(TYPE, T1, T2, EXPR) reinterpret_cast &> (EXPR) + # define ACE_reinterpret_cast_3_ref(TYPE, T1, T2, T3, EXPR) reinterpret_cast &> (EXPR) + # define ACE_reinterpret_cast_4_ref(TYPE, T1, T2, T3, T4, EXPR) reinterpret_cast &> (EXPR) + # define ACE_reinterpret_cast_5_ref(TYPE, T1, T2, T3, T4, T5, EXPR) reinterpret_cast &> (EXPR) + + # define ACE_dynamic_cast(TYPE, EXPR) dynamic_cast (EXPR) + # define ACE_dynamic_cast_1_ptr(TYPE, T1, EXPR) dynamic_cast *> (EXPR) + # define ACE_dynamic_cast_2_ptr(TYPE, T1, T2, EXPR) dynamic_cast *> (EXPR) + # define ACE_dynamic_cast_3_ptr(TYPE, T1, T2, T3, EXPR) dynamic_cast *> (EXPR) + # define ACE_dynamic_cast_4_ptr(TYPE, T1, T2, T3, T4, EXPR) dynamic_cast *> (EXPR) + # define ACE_dynamic_cast_5_ptr(TYPE, T1, T2, T3, T4, T5, EXPR) dynamic_cast *> (EXPR) + # define ACE_dynamic_cast_1_ref(TYPE, T1, EXPR) dynamic_cast &> (EXPR) + # define ACE_dynamic_cast_2_ref(TYPE, T1, T2, EXPR) dynamic_cast &> (EXPR) + # define ACE_dynamic_cast_3_ref(TYPE, T1, T2, T3, EXPR) dynamic_cast &> (EXPR) + # define ACE_dynamic_cast_4_ref(TYPE, T1, T2, T3, T4, EXPR) dynamic_cast &> (EXPR) + # define ACE_dynamic_cast_5_ref(TYPE, T1, T2, T3, T4, T5, EXPR) dynamic_cast &> (EXPR) +#endif /* ACE_LACKS_DEPRECATED_MACROS */ + +# if !defined (ACE_CAST_CONST) + // Sun CC 4.2, for example, requires const in reinterpret casts of + // data members in const member functions. But, other compilers + // complain about the useless const. This keeps everyone happy. +# if defined (__SUNPRO_CC) +# define ACE_CAST_CONST const +# else /* ! __SUNPRO_CC */ +# define ACE_CAST_CONST +# endif /* ! __SUNPRO_CC */ +# endif /* ! ACE_CAST_CONST */ + +// ============================================================================ +// Compiler Silencing macros +// +// Some compilers complain about parameters that are not used. This macro +// should keep them quiet. +// ============================================================================ + +#if !defined (ACE_UNUSED_ARG) +# if defined (__GNUC__) && ((__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2))) +# define ACE_UNUSED_ARG(a) (void) (a) +# elif defined (__GNUC__) || defined (ghs) || defined (__hpux) || defined (__sgi) || defined (__DECCXX) || defined (__rational__) || defined (__USLC__) || defined (ACE_RM544) || defined (__DCC__) || defined (__PGI) || defined (__TANDEM) +// Some compilers complain about "statement with no effect" with (a). +// This eliminates the warnings, and no code is generated for the null +// conditional statement. @note that may only be true if -O is enabled, +// such as with GreenHills (ghs) 1.8.8. +# define ACE_UNUSED_ARG(a) do {/* null */} while (&a == 0) +# elif defined (__DMC__) + #define ACE_UNUSED_ID(identifier) + template + inline void ACE_UNUSED_ARG(const T& ACE_UNUSED_ID(t)) { } +# else /* ghs || __GNUC__ || ..... */ +# define ACE_UNUSED_ARG(a) (a) +# endif /* ghs || __GNUC__ || ..... */ +#endif /* !ACE_UNUSED_ARG */ + +#if defined (_MSC_VER) || defined(__sgi) || defined (ghs) || defined (__DECCXX) || defined(__BORLANDC__) || defined (ACE_RM544) || defined (__USLC__) || defined (__DCC__) || defined (__PGI) || defined (__TANDEM) || (defined (__HP_aCC) && (__HP_aCC < 40000 || __HP_aCC >= 60500)) +# define ACE_NOTREACHED(a) +#else /* __sgi || ghs || ..... */ +# define ACE_NOTREACHED(a) a +#endif /* __sgi || ghs || ..... */ + +// ============================================================================ +// ACE_ALLOC_HOOK* macros +// +// Macros to declare and define class-specific allocation operators. +// ============================================================================ + +# if defined (ACE_HAS_ALLOC_HOOKS) +# define ACE_ALLOC_HOOK_DECLARE \ + void *operator new (size_t bytes); \ + void operator delete (void *ptr); + + // Note that these are just place holders for now. Some day they + // may be be replaced by . +# define ACE_ALLOC_HOOK_DEFINE(CLASS) \ + void *CLASS::operator new (size_t bytes) { return ::new char[bytes]; } \ + void CLASS::operator delete (void *ptr) { delete [] ((char *) ptr); } +# else +# define ACE_ALLOC_HOOK_DECLARE struct __Ace {} /* Just need a dummy... */ +# define ACE_ALLOC_HOOK_DEFINE(CLASS) +# endif /* ACE_HAS_ALLOC_HOOKS */ + +// ============================================================================ +/** + * ACE_OSCALL* macros + * + * @deprecated ACE_OSCALL_RETURN and ACE_OSCALL should not be used. + * Please restart system calls in your application code. + * See the @c sigaction(2) man page for documentation + * regarding enabling restartable system calls across + * signals via the @c SA_RESTART flag. + * + * The following two macros used ensure that system calls are properly + * restarted (if necessary) when interrupts occur. However, that + * capability was never enabled by any of our supported platforms. + * In fact, some parts of ACE would not function properly when that + * ability was enabled. Furthermore, they assumed that ability to + * restart system calls was determined statically. That assumption + * does not hold for modern platforms, where that ability is + * determined dynamically at run-time. + */ +// ============================================================================ + +#define ACE_OSCALL_RETURN(X,TYPE,FAILVALUE) \ + do \ + return (TYPE) (X); \ + while (0) +#define ACE_OSCALL(X,TYPE,FAILVALUE,RESULT) \ + do \ + RESULT = (TYPE) (X); \ + while (0) + +#if defined (ACE_WIN32) +# define ACE_WIN32CALL_RETURN(X,TYPE,FAILVALUE) \ + do { \ + TYPE ace_result_; \ + ace_result_ = (TYPE) X; \ + if (ace_result_ == FAILVALUE) \ + ACE_OS::set_errno_to_last_error (); \ + return ace_result_; \ + } while (0) +# define ACE_WIN32CALL(X,TYPE,FAILVALUE,RESULT) \ + do { \ + RESULT = (TYPE) X; \ + if (RESULT == FAILVALUE) \ + ACE_OS::set_errno_to_last_error (); \ + } while (0) +#endif /* ACE_WIN32 */ + +// The C99 security-improved run-time returns an error value on failure; +// 0 on success. +#if defined (ACE_HAS_TR24731_2005_CRT) +# define ACE_SECURECRTCALL(X,TYPE,FAILVALUE,RESULT) \ + do { \ + errno_t ___ = X; \ + if (___ != 0) { errno = ___; RESULT = FAILVALUE; } \ + } while (0) +#endif /* ACE_HAS_TR24731_2005_CRT */ + +// ============================================================================ +// Fundamental types +// ============================================================================ + +#if defined (ACE_WIN32) + +typedef HANDLE ACE_HANDLE; +typedef SOCKET ACE_SOCKET; +# define ACE_INVALID_HANDLE INVALID_HANDLE_VALUE + +#else /* ! ACE_WIN32 */ + +typedef int ACE_HANDLE; +typedef ACE_HANDLE ACE_SOCKET; +# define ACE_INVALID_HANDLE -1 + +#endif /* ACE_WIN32 */ + +// Define the type that's returned from the platform's native thread +// functions. ACE_THR_FUNC_RETURN is the type defined as the thread +// function's return type, except when the thread function doesn't return +// anything (pSoS). The ACE_THR_FUNC_NO_RETURN_VAL macro is used to +// indicate that the actual thread function doesn't return anything. The +// rest of ACE uses a real type so there's no a ton of conditional code +// everywhere to deal with the possibility of no return type. +# if defined (ACE_VXWORKS) && !defined (ACE_HAS_PTHREADS) +# include /**/ +typedef int ACE_THR_FUNC_RETURN; +#define ACE_HAS_INTEGRAL_TYPE_THR_FUNC_RETURN +# elif defined (ACE_WIN32) +typedef DWORD ACE_THR_FUNC_RETURN; +#define ACE_HAS_INTEGRAL_TYPE_THR_FUNC_RETURN +# else +typedef void* ACE_THR_FUNC_RETURN; +# endif /* ACE_VXWORKS */ +typedef ACE_THR_FUNC_RETURN (*ACE_THR_FUNC)(void *); + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ +typedef void (*ACE_THR_C_DEST)(void *); +#ifdef __cplusplus +} +#endif /* __cplusplus */ +typedef void (*ACE_THR_DEST)(void *); + +// Now some platforms have special requirements... +# if defined (ACE_VXWORKS) && !defined (ACE_HAS_PTHREADS) +typedef FUNCPTR ACE_THR_FUNC_INTERNAL; // where typedef int (*FUNCPTR) (...) +# else +typedef ACE_THR_FUNC ACE_THR_FUNC_INTERNAL; +# endif /* ACE_VXWORKS */ + +# ifdef __cplusplus +extern "C" +{ +# endif /* __cplusplus */ +# if defined (ACE_VXWORKS) && !defined (ACE_HAS_PTHREADS) +typedef FUNCPTR ACE_THR_C_FUNC; // where typedef int (*FUNCPTR) (...) +# else +typedef ACE_THR_FUNC_RETURN (*ACE_THR_C_FUNC)(void *); +# endif /* ACE_VXWORKS */ +# ifdef __cplusplus +} +# endif /* __cplusplus */ + +// ============================================================================ +// Macros for controlling the lifetimes of dlls loaded by ACE_DLL--including +// all dlls loaded via the ACE Service Config framework. +// +// Please don't change these values or add new ones wantonly, since we use +// the ACE_BIT_ENABLED, etc..., macros to test them. +// ============================================================================ + +// Per-process policy that unloads dlls eagerly. +#define ACE_DLL_UNLOAD_POLICY_PER_PROCESS 0 +// Apply policy on a per-dll basis. If the dll doesn't use one of the macros +// below, the current per-process policy will be used. +#define ACE_DLL_UNLOAD_POLICY_PER_DLL 1 +// Don't unload dll when refcount reaches zero, i.e., wait for either an +// explicit unload request or program exit. +#define ACE_DLL_UNLOAD_POLICY_LAZY 2 +// Default policy allows dlls to control their own destinies, but will +// unload those that don't make a choice eagerly. +#define ACE_DLL_UNLOAD_POLICY_DEFAULT ACE_DLL_UNLOAD_POLICY_PER_DLL + +// Add this macro you one of your cpp file in your dll. X should +// be either ACE_DLL_UNLOAD_POLICY_DEFAULT or ACE_DLL_UNLOAD_POLICY_LAZY. +#define ACE_DLL_UNLOAD_POLICY(CLS,X) \ +extern "C" u_long CLS##_Export _get_dll_unload_policy (void) \ + { return X;} + +// ============================================================================ +// ACE_USES_CLASSIC_SVC_CONF macro +// ============================================================================ + +// For now, default is to use the classic svc.conf format. +#if !defined (ACE_USES_CLASSIC_SVC_CONF) +# if defined (ACE_HAS_CLASSIC_SVC_CONF) && defined (ACE_HAS_XML_SVC_CONF) +# error You can only use either CLASSIC or XML svc.conf, not both. +# endif +// Change the ACE_HAS_XML_SVC_CONF to ACE_HAS_CLASSIC_SVC_CONF when +// we switch ACE to use XML svc.conf as default format. +# if defined (ACE_HAS_XML_SVC_CONF) +# define ACE_USES_CLASSIC_SVC_CONF 0 +# else +# define ACE_USES_CLASSIC_SVC_CONF 1 +# endif /* ACE_HAS_XML_SVC_CONF */ +#endif /* ACE_USES_CLASSIC_SVC_CONF */ + +// ============================================================================ +// Default svc.conf file extension. +// ============================================================================ +#if defined (ACE_USES_CLASSIC_SVC_CONF) && (ACE_USES_CLASSIC_SVC_CONF == 1) +# define ACE_DEFAULT_SVC_CONF_EXT ".conf" +#else +# define ACE_DEFAULT_SVC_CONF_EXT ".conf.xml" +#endif /* ACE_USES_CLASSIC_SVC_CONF && ACE_USES_CLASSIC_SVC_CONF == 1 */ + +// ============================================================================ +// Miscellaneous macros +// ============================================================================ + +#if defined (ACE_USES_EXPLICIT_STD_NAMESPACE) +# define ACE_STD_NAMESPACE std +#else +# define ACE_STD_NAMESPACE +#endif + +#if !defined (ACE_OS_String) +# define ACE_OS_String ACE_OS +#endif /* ACE_OS_String */ +#if !defined (ACE_OS_Memory) +# define ACE_OS_Memory ACE_OS +#endif /* ACE_OS_Memory */ +#if !defined (ACE_OS_Dirent) +# define ACE_OS_Dirent ACE_OS +#endif /* ACE_OS_Dirent */ +#if !defined (ACE_OS_TLI) +# define ACE_OS_TLI ACE_OS +#endif /* ACE_OS_TLI */ + +// ------------------------------------------------------------------- +// Preprocessor symbols will not be expanded if they are +// concatenated. Force the preprocessor to expand them during the +// argument prescan by calling a macro that itself calls another that +// performs the actual concatenation. +#define ACE_PREPROC_CONCATENATE_IMPL(A,B) A ## B +#define ACE_PREPROC_CONCATENATE(A,B) ACE_PREPROC_CONCATENATE_IMPL(A,B) +// ------------------------------------------------------------------- + +/// If MPC is using a lib modifier this define will be set and this then +/// is used by the service configurator framework +#if defined MPC_LIB_MODIFIER && !defined (ACE_LD_DECORATOR_STR) +#define ACE_LD_DECORATOR_STR ACE_TEXT( MPC_LIB_MODIFIER ) +#endif /* MPC_LIB_MODIFIER */ + +#ifndef ACE_GCC_CONSTRUCTOR_ATTRIBUTE +# define ACE_GCC_CONSTRUCTOR_ATTRIBUTE +#endif + +#ifndef ACE_GCC_DESTRUCTOR_ATTRIBUTE +# define ACE_GCC_DESTRUCTOR_ATTRIBUTE +#endif + +#ifndef ACE_DEPRECATED +# define ACE_DEPRECATED +#endif + +#endif /* ACE_CONFIG_MACROS_H */ diff --git a/dep/acelite/ace/config-minimal.h b/dep/acelite/ace/config-minimal.h new file mode 100644 index 00000000000..4cf2e8a487b --- /dev/null +++ b/dep/acelite/ace/config-minimal.h @@ -0,0 +1,39 @@ +/* -*- C++ -*- */ +// $Id: config-minimal.h 80826 2008-03-04 14:51:23Z wotte $ + +// This configuration file is designed to build only the minimal +// ACE_OS adaptation layer. + +#ifndef ACE_CONFIG_MINIMAL_H +#define ACE_CONFIG_MINIMAL_H +#include /**/ "ace/pre.h" + +#define ACE_HAS_MINIMAL_ACE_OS + +// Only instantiate the ACE_OS_Object_Manager. +#define ACE_MAIN_OBJECT_MANAGER \ + ACE_OS_Object_Manager ace_os_object_manager; + +#if !defined(ACE_USE_THREAD_MANAGER_ADAPTER) + // To prevent use of ACE_Thread_Exit functions in + // ACE_Thread_Adapter::invoke (). +# define ACE_USE_THREAD_MANAGER_ADAPTER +#endif /* ! ACE_USE_THREAD_MANAGER_ADAPTER */ + +#if defined (ACE_ASSERT) +# undef ACE_ASSERT +#endif /* ACE_ASSERT */ +#define ACE_ASSERT(x) + +#if defined (ACE_DEBUG) +# undef ACE_DEBUG +#endif /* ACE_DEBUG */ +#define ACE_DEBUG(x) + +#if defined (ACE_ERROR) +# undef ACE_ERROR +#endif /* ACE_ERROR */ +#define ACE_ERROR(x) + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_MINIMAL_H */ diff --git a/dep/acelite/ace/config-mvs.h b/dep/acelite/ace/config-mvs.h new file mode 100644 index 00000000000..3f438a776ba --- /dev/null +++ b/dep/acelite/ace/config-mvs.h @@ -0,0 +1,127 @@ +/* -*- C++ -*- */ +// $Id: config-mvs.h 88495 2010-01-12 19:23:11Z olli $ + +// Config file for MVS with OpenEdition + +#ifndef ACE_CONFIG_H +#define ACE_CONFIG_H +#include /**/ "ace/pre.h" + +// The following #defines are hacks to get around things +// that seem to be missing or different in MVS land +#define MAXPATHLEN 1024 /* sys/param.h not on MVS */ +#define NSIG 44 /* missing from Signal.h */ +#define MAXHOSTNAMELEN 256 /* missing form netdb.h */ +#define howmany __howmany /* MVS uses different names than most others */ +#define MAXNAMLEN __DIR_NAME_MAX +#if defined (log) /* log is a macro in math.h */ +# undef log /* conflicts with log function in ACE */ +#endif /* log */ + +#define ACE_MVS + +// Preprocesor requires an extra argument +#ifndef ACE_USING_MCPP_PREPROCESSOR +# define ACE_CC_PREPROCESSOR_ARGS "-+ -E" +#endif + +// See the README file in this directory +// for a description of the following ACE_ macros + +#if __COMPILER_VER__ >= 0x21020000 /* OS/390 r2 or higher */ +# define ACE_HAS_4_4BSD_SENDMSG_RECVMSG +# define ACE_HAS_UCONTEXT_T +#else /* __COMPILER_VER__ < 0x21020000 */ +# define ACE_LACKS_UCONTEXT_H +#endif /* __COMPILER_VER__ < 0x21020000 */ + +#if __COMPILER_VER__ < 0x22060000 /* before OS/390 r2.6 */ +# define ACE_LACKS_LONGLONG_T +#endif /* __COMPILER_VER__ < 0x22060000 */ + +#define ERRMAX __sys_nerr + +#define ACE_HAS_3_PARAM_WCSTOK +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES +#define ACE_HAS_CPLUSPLUS_HEADERS +#define ACE_HAS_DIRENT +#define ACE_HAS_GETPAGESIZE +#define ACE_HAS_GETRUSAGE +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT +#define ACE_HAS_LIMITED_RUSAGE_T +#define ACE_HAS_MSG +#define ACE_HAS_NONCONST_SELECT_TIMEVAL +#define ACE_HAS_NONSCALAR_THREAD_KEY_T +#define ACE_HAS_POLL +#define ACE_HAS_POSIX_NONBLOCK +#define ACE_HAS_POSIX_TIME +#define ACE_HAS_PTHREADS +#define ACE_HAS_PTHREAD_CONDATTR_SETKIND_NP +#define ACE_HAS_PTHREAD_MUTEXATTR_SETKIND_NP +#define ACE_HAS_SIGINFO_T +#define ACE_HAS_SIGWAIT +#define ACE_HAS_SIG_ATOMIC_T +#define ACE_HAS_SIG_C_FUNC +#define ACE_HAS_SOCKADDR_IN_SIN_LEN +#define ACE_HAS_SIZET_SOCKET_LEN +#define ACE_HAS_SSIZE_T +#define ACE_HAS_STRBUF_T +#define ACE_HAS_STRINGS +#define ACE_HAS_SYSV_IPC +#define ACE_HAS_TEMPLATE_TYPEDEFS +#define ACE_HAS_THREADS +#define ACE_HAS_THREAD_SPECIFIC_STORAGE +#define ACE_HAS_THR_C_DEST +#define ACE_HAS_THR_C_FUNC +#define ACE_HAS_TIMEZONE_GETTIMEOFDAY +#define ACE_HAS_UALARM +#define ACE_HAS_UTIME +#define ACE_HAS_VOIDPTR_MMAP +#define ACE_HAS_VOIDPTR_SOCKOPT +#define ACE_HAS_XPG4_MULTIBYTE_CHAR + +#define ACE_LACKS_CONDATTR_PSHARED +#define ACE_LACKS_INET_ATON +#define ACE_LACKS_MUTEXATTR_PSHARED +#define ACE_LACKS_IOSTREAM_FX +#define ACE_LACKS_LINEBUFFERED_STREAMBUF +#define ACE_LACKS_MADVISE +#define ACE_LACKS_MALLOC_H +#define ACE_LACKS_PARAM_H +#define ACE_LACKS_SYS_PARAM_H +#define ACE_LACKS_PLACEMENT_OPERATOR_DELETE +#define ACE_LACKS_PTHREAD_THR_SIGSETMASK +#define ACE_LACKS_READDIR_R +#define ACE_LACKS_RWLOCK_T +#define ACE_LACKS_SCHED_H +#define ACE_LACKS_SETSCHED +#define ACE_LACKS_SEMAPHORE_H +#define ACE_LACKS_SIGINFO_H +#define ACE_LACKS_STDINT_H +#define ACE_LACKS_SYS_SELECT_H +#define ACE_LACKS_SYS_SYSCTL_H +#define ACE_LACKS_SYSTIME_H +#define ACE_LACKS_NETINET_TCP_H +#define ACE_LACKS_TCP_H +#define ACE_LACKS_THREAD_PROCESS_SCOPING +#define ACE_LACKS_PTHREAD_ATTR_SETSTACKADDR +#define ACE_LACKS_TIMESPEC_T +#define ACE_LACKS_FD_MASK + +#if !defined (ACE_MT_SAFE) +# define ACE_MT_SAFE 1 +#endif + +#define ACE_NEEDS_DEV_IO_CONVERSION + +#define ACE_SIZEOF_FLOAT 4 +#define ACE_SIZEOF_DOUBLE 8 +#define ACE_SIZEOF_LONG_DOUBLE 16 +#define ACE_HAS_EBCDIC + +#define ACE_TEMPLATES_REQUIRE_SOURCE + +#define IN_CLASSD(a) ((((in_addr_t)(a)) & 0xf0000000) == 0xe0000000) +#define IN_MULTICAST(a) IN_CLASSD(a) +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_H */ diff --git a/dep/acelite/ace/config-netbsd.h b/dep/acelite/ace/config-netbsd.h new file mode 100644 index 00000000000..07b26c9cc1c --- /dev/null +++ b/dep/acelite/ace/config-netbsd.h @@ -0,0 +1,165 @@ +/* -*- C++ -*- */ +// $Id: config-netbsd.h 89494 2010-03-15 20:11:18Z olli $ + +#ifndef ACE_CONFIG_H +#define ACE_CONFIG_H + +#ifndef ACE_MT_SAFE +#define ACE_MT_SAFE 1 +#endif + +#if defined (__GNUG__) +# include "ace/config-g++-common.h" +#endif /* __GNUG__ */ + +#if defined(ACE_MT_SAFE) && (ACE_MT_SAFE != 0) +# define ACE_HAS_THREADS 1 +# define ACE_HAS_PTHREADS 1 +# define ACE_HAS_PTHREADS_UNIX98_EXT 1 +# define ACE_HAS_PTHREAD_RESUME_NP 1 +# define ACE_HAS_PTHREAD_SUSPEND_NP 1 +# define ACE_LACKS_PTHREAD_THR_SIGSETMASK 1 +# define ACE_LACKS_PTHREAD_YIELD 1 +#endif /* ACE_MT_SAFE */ + +#define ACE_HAS_CLOCK_SETTIME 1 +#define ACE_HAS_CLOCK_GETTIME 1 +#define ACE_HAS_SETTIMEOFDAY 1 +#define ACE_HAS_GETTIMEOFDAY 1 +#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R 1 +#define ACE_HAS_3_PARAM_WCSTOK 1 +#define ACE_HAS_3_PARAM_READDIR_R 1 +#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG 1 +#define ACE_HAS_ALT_CUSERID 1 +#define ACE_HAS_AUTOMATIC_INIT_FINI 1 +#define ACE_HAS_CLOCK_GETTIME 1 +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES 1 +#define ACE_HAS_DIRENT 1 +#define ACE_HAS_EXCEPTIONS 1 +#define ACE_HAS_GETIFADDRS 1 +#define ACE_HAS_GETPAGESIZE 1 +#define ACE_HAS_GETPROGNAME 1 +#define ACE_HAS_GETRUSAGE 1 +#define ACE_HAS_GETRUSAGE_PROTOTYPE 1 +#define ACE_HAS_GPERF 1 +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT 1 +#define ACE_HAS_IP_MULTICAST 1 +#define ACE_HAS_MSG 1 +#define ACE_HAS_NEW_NO_H 1 +#define ACE_HAS_NONCONST_SELECT_TIMEVAL 1 +#define ACE_HAS_ONLY_SCHED_OTHER 1 +#define ACE_HAS_POLL 1 +#define ACE_HAS_POSITION_INDEPENDENT_POINTERS 1 +#define ACE_HAS_POSIX_NONBLOCK 1 +#define ACE_HAS_POSIX_TIME 1 +#define ACE_HAS_P_READ_WRITE 1 +#define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS 1 +#define ACE_HAS_REENTRANT_FUNCTIONS 1 +#define ACE_HAS_SCANDIR 1 +#define ACE_HAS_SETPROGNAME 1 +#define ACE_HAS_SIGACTION_CONSTP2 1 +#define ACE_HAS_SIGINFO_T 1 +#define ACE_HAS_SIGSUSPEND 1 +#define ACE_HAS_SIGTIMEDWAIT 1 +#define ACE_HAS_SIGWAIT 1 +#define ACE_HAS_SIG_ATOMIC_T 1 +#define ACE_HAS_SIG_C_FUNC 1 +#define ACE_HAS_SOCKADDR_IN_SIN_LEN 1 +#define ACE_HAS_SOCKADDR_IN6_SIN6_LEN 1 +#define ACE_HAS_SOCKADDR_MSG_NAME 1 +#define ACE_HAS_SOCKLEN_T 1 +#define ACE_HAS_SSIZE_T 1 +#define ACE_HAS_STANDARD_CPP_LIBRARY 1 +#define ACE_HAS_STDEXCEPT_NO_H 1 +#define ACE_HAS_STRINGS 1 +#define ACE_HAS_STRING_CLASS 1 +#define ACE_HAS_SVR4_DYNAMIC_LINKING 1 +#define ACE_HAS_SYSV_IPC 1 +#define ACE_HAS_SYS_FILIO_H 1 +#define ACE_HAS_STRSIGNAL +#define ACE_HAS_SYS_SOCKIO_H 1 +#define ACE_HAS_SYS_SYSCALL_H 1 +#define ACE_HAS_SYSCTL +#define ACE_HAS_TERMIOS 1 +#define ACE_HAS_THREAD_SPECIFIC_STORAGE 1 +#define ACE_HAS_TIMEZONE 1 +#define ACE_HAS_TIMEZONE_GETTIMEOFDAY 1 +#define ACE_HAS_UALARM 1 +#define ACE_HAS_UCONTEXT_T 1 +#define ACE_HAS_VOIDPTR_MMAP 1 +#define ACE_HAS_VOIDPTR_SOCKOPT 1 +#define ACE_HAS_WCHAR 1 +#define ACE_HAS_XPG4_MULTIBYTE_CHAR 1 +#define ACE_IOCTL_TYPE_ARG2 u_long +#define ACE_LACKS_CONDATTR_PSHARED 1 +#define ACE_LACKS_GETHOSTENT 1 +#define ACE_LACKS_GETIPNODEBYADDR 1 +#define ACE_LACKS_GETIPNODEBYNAME 1 +#define ACE_LACKS_IOSTREAM_FX 1 +#define ACE_LACKS_ITOW 1 +#define ACE_LACKS_LINEBUFFERED_STREAMBUF 1 +#define ACE_LACKS_LOG2 1 +#define ACE_LACKS_MSG_ACCRIGHTS 1 +#define ACE_LACKS_MUTEXATTR_PSHARED 1 +#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS 1 +#define ACE_LACKS_PERFECT_MULTICAST_FILTERING 1 +#define ACE_LACKS_PRI_T 1 +#define ACE_LACKS_PTHREAD_THR_SIGSETMASK 1 +#define ACE_LACKS_PTHREAD_YIELD 1 +#define ACE_LACKS_PWD_REENTRANT_FUNCTIONS 1 +#define ACE_LACKS_RWLOCKATTR_PSHARED 1 +#define ACE_LACKS_RWLOCK_T 1 +#define ACE_LACKS_SETSCHED 1 +#define ACE_LACKS_SIGINFO_H 1 +#define ACE_LACKS_STROPTS_H 1 +#define ACE_LACKS_STRRECVFD 1 +#define ACE_LACKS_TIMEDWAIT_PROTOTYPES 1 +#define ACE_LACKS_TIMESPEC_T 1 +#define ACE_LACKS_UNBUFFERED_STREAMBUF 1 +#define ACE_LACKS_WCSDUP 1 +#define ACE_LACKS_WCSICMP 1 +#define ACE_LACKS_WCSNICMP 1 +#define ACE_SCANDIR_CMP_USES_CONST_VOIDPTR 1 +#define ACE_LACKS_ISCTYPE + +#if defined(__x86_64__) +#define ACE_SIZEOF_DOUBLE 8 +#define ACE_SIZEOF_FLOAT 4 +#define ACE_SIZEOF_INT 4 +#define ACE_SIZEOF_LONG 8 +#define ACE_SIZEOF_LONG_DOUBLE 16 +#define ACE_SIZEOF_LONG_LONG 8 +#define ACE_SIZEOF_SHORT 2 +#define ACE_SIZEOF_VOID_P 8 +#define ACE_SIZEOF_WCHAR 4 + +typedef unsigned long ACE_UINT64; +typedef signed long ACE_INT64; + +#define ACE_SSIZE_T_FORMAT_SPECIFIER_ASCII "%ld" +#define ACE_SIZE_T_FORMAT_SPECIFIER_ASCII "%lu" + +#elif defined(__i386__) + +#define ACE_SIZEOF_DOUBLE 8 +#define ACE_SIZEOF_FLOAT 4 +#define ACE_SIZEOF_INT 4 +#define ACE_SIZEOF_LONG 4 +#define ACE_SIZEOF_LONG_DOUBLE 12 +#define ACE_SIZEOF_LONG_LONG 8 +#define ACE_SIZEOF_SHORT 2 +#define ACE_SIZEOF_VOID_P 4 +#define ACE_SIZEOF_WCHAR 4 + +typedef unsigned long long ACE_UINT64; +typedef signed long long ACE_INT64; + +#else +# error unknown CPU architecture +#endif + +#endif /* ACE_CONFIG_H */ + +// Local Variables: +// mode:C++ +// End: diff --git a/dep/acelite/ace/config-openbsd.h b/dep/acelite/ace/config-openbsd.h new file mode 100644 index 00000000000..aab03106aab --- /dev/null +++ b/dep/acelite/ace/config-openbsd.h @@ -0,0 +1,208 @@ +/* -*- C++ -*- */ +// $Id: config-openbsd.h 89494 2010-03-15 20:11:18Z olli $ + +// The following configuration file is designed to work for OpenBSD +// platforms using GNU g++. + +#ifndef ACE_CONFIG_H +# define ACE_CONFIG_H +#include /**/ "ace/pre.h" + +// Platform specific directives +// gcc defines __OpenBSD__ automatically for us. +#include + +#if defined (ACE_HAS_THREADS) +# include /**/ +#endif /* ACE_HAS_THREADS */ + +#include "ace/config-posix.h" + +#if !defined (__ACE_INLINE__) +# define __ACE_INLINE__ +#endif /* !__ACE_INLINE__ */ + +#if defined (__GNUG__) +# include "ace/config-g++-common.h" +#endif /* __GNUG__ */ + + +#if defined (ACE_HAS_THREADS) + +# if !defined (_THREAD_SAFE) +# define _THREAD_SAFE +# endif /* _THREAD_SAFE */ + +// And they're even POSIX pthreads +# if !defined (ACE_MT_SAFE) +# define ACE_MT_SAFE 1 +# endif /* ! ACE_MT_SAFE */ + + +// Check if pthreads and native exceptions are being used together. +// This causes SEGVs to tbe thrown somewhat randomly for some +// reason. According to newsgroup postings, it appears to be an +// OpenBSD or gcc bug. +# if defined (ACE_USES_NATIVE_EXCEPTIONS) +# error "OpenBSD pthreads and native exceptions currently do not work. See OpenBSD bug #1750" +# endif /* ACE_USES_NATIVE_EXCEPTIONS */ + +#else +// OpenBSD really has readdir_r () in single threaded mode, +// but the #ifdefs in OS.i select one with the wrong parameter +// sets if the ACE_HAS_POSIX_STD isn't defined (which is defined +// when ACE_HAS_THREADS is defined.) +# define ACE_LACKS_READDIR_R + +#endif /* ACE_HAS_THREADS */ + + +#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R +#define ACE_HAS_3_PARAM_READDIR_R +#define ACE_HAS_3_PARAM_WCSTOK +#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG +#define ACE_HAS_ALLOCA +#define ACE_HAS_ALT_CUSERID +#define ACE_HAS_AUTOMATIC_INIT_FINI +#define ACE_HAS_CHARPTR_DL +#define ACE_HAS_CLOCK_GETTIME +#define ACE_HAS_CLOCK_SETTIME +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES +#define ACE_HAS_DIRENT +#define ACE_HAS_GETIFADDRS +#define ACE_HAS_GETPAGESIZE +#define ACE_HAS_GETRUSAGE +#define ACE_HAS_GPERF +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT +#define ACE_HAS_ICMP_SUPPORT 1 +#define ACE_HAS_IPV6 +#define ACE_HAS_IP_MULTICAST +#define ACE_HAS_MEMCHR +#define ACE_HAS_MKDIR +#define ACE_HAS_MSG +#define ACE_HAS_NANOSLEEP +#define ACE_HAS_NEW_NO_H +#define ACE_HAS_NONCONST_MSGSND +#define ACE_HAS_NONCONST_SELECT_TIMEVAL +#define ACE_HAS_NONCONST_SWAB +#define ACE_HAS_POLL +#define ACE_HAS_POSITION_INDEPENDENT_POINTERS 1 +#define ACE_HAS_POSIX_GETPWNAM_R +#define ACE_HAS_POSIX_NONBLOCK +#define ACE_HAS_POSIX_TIME +#define ACE_HAS_PTHREADS_STD +#define ACE_HAS_PTHREADS_UNIX98_EXT +#define ACE_HAS_PTHREAD_ATTR_SETCREATESUSPEND_NP +#define ACE_HAS_PTHREAD_GETCONCURRENCY +#define ACE_HAS_PTHREAD_MUTEXATTR_SETKIND_NP +#define ACE_HAS_PTHREAD_NP_H +#define ACE_HAS_PTHREAD_RESUME_NP +#define ACE_HAS_PTHREAD_SETCONCURRENCY +#define ACE_HAS_PTHREAD_SIGMASK_PROTOTYPE +#define ACE_HAS_PTHREAD_SUSPEND_NP +#define ACE_HAS_P_READ_WRITE +#define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS +#define ACE_HAS_REENTRANT_FUNCTIONS +#define ACE_HAS_RTLD_LAZY_V +#define ACE_HAS_SCANDIR +#define ACE_HAS_SEMUN +#define ACE_HAS_SIGACTION_CONSTP2 +#define ACE_HAS_SIGINFO_T +#define ACE_HAS_SIGSUSPEND +#define ACE_HAS_SIGWAIT +#define ACE_HAS_SIG_ATOMIC_T +#define ACE_HAS_SIG_C_FUNC +#define ACE_HAS_SOCKADDR_IN6_SIN6_LEN +#define ACE_HAS_SOCKADDR_IN_SIN_LEN +#define ACE_HAS_SOCKADDR_MSG_NAME +#define ACE_HAS_SOCKLEN_T +#define ACE_HAS_SSIZE_T +#define ACE_HAS_STRINGS +#define ACE_HAS_STRING_CLASS +#define ACE_HAS_SVR4_DYNAMIC_LINKING +#define ACE_HAS_SVR4_SIGNAL_T +#define ACE_HAS_SYSCTL +#define ACE_HAS_SYSV_IPC +#define ACE_HAS_SYS_FILIO_H +#define ACE_HAS_STRSIGNAL +#define ACE_HAS_SYS_SOCKIO_H +#define ACE_HAS_SYS_SYSCALL_H +#define ACE_HAS_TERMIOS +#define ACE_HAS_THREAD_SPECIFIC_STORAGE +#define ACE_HAS_TIMEZONE_GETTIMEOFDAY +#define ACE_HAS_UALARM +#define ACE_HAS_VASPRINTF +#define ACE_HAS_VOIDPTR_MMAP +#define ACE_HAS_VOIDPTR_SOCKOPT +#define ACE_HAS_VOID_UNSETENV +#define ACE_HAS_WCHAR +#define ACE_HAS_XPG4_MULTIBYTE_CHAR + +#define ACE_LACKS_CONDATTR_PSHARED +#define ACE_LACKS_GETIPNODEBYADDR +#define ACE_LACKS_GETIPNODEBYNAME +#define ACE_LACKS_GETPGID +#define ACE_LACKS_IOSTREAM_FX +#define ACE_LACKS_ISCTYPE +#define ACE_LACKS_ITOW +#define ACE_LACKS_LINEBUFFERED_STREAMBUF +#define ACE_LACKS_LOG2 +#define ACE_LACKS_MALLOC_H +#define ACE_LACKS_MSG_ACCRIGHTS +#define ACE_LACKS_MUTEXATTR_PSHARED +#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS +#define ACE_LACKS_PERFECT_MULTICAST_FILTERING +#define ACE_LACKS_PRI_T +#define ACE_LACKS_PTHREAD_THR_SIGSETMASK +#define ACE_LACKS_PWD_REENTRANT_FUNCTIONS +#define ACE_LACKS_RAND_REENTRANT_FUNCTIONS +#define ACE_LACKS_RLIMIT_PROTOTYPE +#define ACE_LACKS_RWLOCK_T +#define ACE_LACKS_SETPGID +#define ACE_LACKS_SETREGID +#define ACE_LACKS_SETREUID +#define ACE_LACKS_SETSCHED +#define ACE_LACKS_SIGINFO_H +#define ACE_LACKS_STDINT_H +#define ACE_LACKS_STROPTS_H +#define ACE_LACKS_STRRECVFD +#define ACE_LACKS_TERMIO_H +#define ACE_LACKS_THREAD_PROCESS_SCOPING +#define ACE_LACKS_TIMEDWAIT_PROTOTYPES +#define ACE_LACKS_TIMESPEC_T +#define ACE_LACKS_UCONTEXT_H +#define ACE_LACKS_UNBUFFERED_STREAMBUF +#define ACE_LACKS_U_LONGLONG_T +#define ACE_LACKS_WCHAR_H +#define ACE_LACKS_WCSCASECMP +#define ACE_LACKS_WCSDUP +#define ACE_LACKS_WCSNCASECMP +#define ACE_LACKS_WCSNICMP + +#define ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS +#define ACE_PAGE_SIZE 4096 +#define ACE_SCANDIR_CMP_USES_CONST_VOIDPTR +#define ACE_SCANDIR_SEL_LACKS_CONST + +// OpenBSD 3.6 +#if (OpenBSD < 200411) +# define ACE_USES_ASM_SYMBOL_IN_DLSYM +#endif + +// ucontext_t is in OpenBSD 3.5 and later. +#if (OpenBSD >= 200405) +# define ACE_HAS_UCONTEXT_T +#endif /* OpenBSD >= 200405 */ + +// Lacks perfect filtering, must bind group address. +#if !defined ACE_LACKS_PERFECT_MULTICAST_FILTERING +# define ACE_LACKS_PERFECT_MULTICAST_FILTERING +#endif /* ACE_LACKS_PERFECT_MULTICAST_FILTERING */ + +// OpenBSD's dlsym call segfaults when passed an invalid handle. +// It seems as if most other OSs detect this and just report an error. +#define ACE_HAS_DLSYM_SEGFAULT_ON_INVALID_HANDLE + +#include /**/ "ace/post.h" + +#endif /* ACE_CONFIG_H */ diff --git a/dep/acelite/ace/config-openvms.h b/dep/acelite/ace/config-openvms.h new file mode 100644 index 00000000000..ac57aad9707 --- /dev/null +++ b/dep/acelite/ace/config-openvms.h @@ -0,0 +1,198 @@ +/* -*- C++ -*- */ +// $Id: config-openvms.h 87167 2009-10-19 19:33:53Z olli $ + +// The following configuration file is designed to work for OpenVMS 7.3-2 + +#ifndef ACE_CONFIG_H +#define ACE_CONFIG_H + +#if !defined (ACE_USE_RCSID) +# define ACE_USE_RCSID 0 +#endif + +#ifdef __cplusplus +#pragma message disable CODCAUUNR +#pragma message disable CODEUNREACHABLE +//#pragma message disable DOLLARID +//#pragma message disable NOSIMPINT +//#pragma message disable NOSTDLONGLONG +#pragma message disable NARROWPTR +//#pragma message disable LONGEXTERN +#pragma message disable UNSCOMZER +#endif + +// Use a signed int to match POSIX +#define __SIGNED_INT_TIME_T + +#define ACE_OPENVMS __VMS_VER + +#define ACE_DLL_SUFFIX ACE_TEXT("") + +#define ACE_HAS_DUMP 1 + +// need this includes to ensure proper sequence of definitions so that +// f.i. HP C/C++ does not '#define ' memcpy, memmove etc. +#include +#include +#include +#undef memset +#undef memcpy +#undef memmove + +#if defined(__ia64__) + // on OpenVMS IA64 we need this get the singleton exported since we build + // ACE/TAO with the NOTEMPLATES export option which prohibits exporting + // of any template symbols unless explicitly exported + #define ACE_HAS_CUSTOM_EXPORT_MACROS + #define ACE_Proper_Export_Flag + #define ACE_Proper_Import_Flag + #define ACE_EXPORT_SINGLETON_DECLARATION(T) template class __declspec (dllexport) T + #define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) template class __declspec (dllexport) SINGLETON_TYPE; +#else + #define ACE_HAS_EXPLICIT_STATIC_TEMPLATE_MEMBER_INSTANTIATION +#endif + +#define ACE_DEFAULT_BASE_ADDR ((char*)(0x30000000)) + +#define ACE_MAX_UDP_PACKET_SIZE 65535 + +#define ACE_HAS_STDCPP_STL_INCLUDES 1 + +/* missing system headers */ +#define ACE_LACKS_STDINT_H 1 +#define ACE_LACKS_SYS_IPC_H 1 +#define ACE_LACKS_SYS_SEM_H 1 +#define ACE_LACKS_SEMAPHORE_H 1 +#define ACE_LACKS_SYS_SELECT_H 1 +#define ACE_LACKS_TERMIOS_H 1 +#define ACE_LACKS_SYS_SHM_H 1 +#define ACE_LACKS_SYS_MSG_H 1 +#define ACE_LACKS_REGEX_H 1 +#define ACE_LACKS_SEARCH_H 1 +#define ACE_LACKS_SCHED_H 1 +#define ACE_LACKS_SYS_SYSCTL_H 1 +#define ACE_LACKS_MALLOC_H 1 +#define ACE_LACKS_SYS_PARAM_H 1 +#define ACE_LACKS_SIGINFO_H 1 +#define ACE_LACKS_UCONTEXT_H 1 + +/* missing rtl functions */ +#define ACE_LACKS_SETPGID 1 +#define ACE_LACKS_SETREUID 1 +#define ACE_LACKS_SETREGID 1 +#define ACE_LACKS_FORK 1 +#define ACE_LACKS_GETPGID 1 +#define ACE_LACKS_SETSID 1 +#define ACE_LACKS_FCNTL 1 +#define ACE_LACKS_SETEGID 1 +#define ACE_LACKS_SETEUID 1 + +#define ACE_LACKS_REALPATH 1 + +#define ACE_LACKS_SYMLINKS 1 + +#define ACE_LACKS_PWD_REENTRANT_FUNCTIONS 1 +#define ACE_LACKS_RAND_REENTRANT_FUNCTIONS 1 + +#define ACE_HAS_P_READ_WRITE +#define ACE_HAS_CHARPTR_DL 1 +#define ACE_HAS_CLOCK_GETTIME 1 +#define ACE_HAS_CLOCK_SETTIME 1 +#define ACE_HAS_VOIDPTR_GETTIMEOFDAY 1 +#define ACE_HAS_DIRENT 1 +#define ACE_HAS_GETPAGESIZE 1 +#define ACE_HAS_MSG +#define ACE_HAS_NONCONST_SELECT_TIMEVAL 1 +#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R 1 +#define ACE_HAS_3_PARAM_WCSTOK 1 +#define ACE_HAS_SIGSUSPEND 1 +#define ACE_HAS_SIGWAIT 1 +#define ACE_HAS_SIGTIMEDWAIT 1 + +#define ACE_HAS_SIG_C_FUNC 1 +#define ACE_HAS_SIGISMEMBER_BUG +#define ACE_HAS_STRNLEN 1 +#define ACE_HAS_STREAMS 1 +#define ACE_HAS_UALARM 1 +#define ACE_HAS_VOIDPTR_MMAP 1 +#define ACE_HAS_VOIDPTR_SOCKOPT 1 +#define ACE_LACKS_LSTAT 1 +#define ACE_LACKS_MADVISE 1 +#define ACE_LACKS_MKFIFO 1 +#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS 1 +#define ACE_LACKS_READLINK 1 +#define ACE_LACKS_RLIMIT 1 +#define ACE_LACKS_RLIMIT_PROTOTYPE 1 +#define ACE_LACKS_SETSCHED +#define ACE_LACKS_SYSCALL 1 +#define ACE_LACKS_WCSTOULL 1 +#define ACE_LACKS_WCSTOLL + +/* (missing) standard data types */ +#define ACE_LACKS_CONST_TIMESPEC_PTR 1 +#define ACE_LACKS_SUSECONDS_T 1 +#define ACE_HAS_IDTYPE_T 1 +#define ACE_HAS_SIGINFO_T 1 +#define ACE_HAS_XPG4_MULTIBYTE_CHAR 1 +#define ACE_HAS_SIZET_SOCKET_LEN 1 +#define ACE_HAS_SSIZE_T 1 +#define ACE_LACKS_PRI_T 1 +#define ACE_LACKS_SEMBUF_T 1 +#define ACE_LACKS_STRRECVFD 1 +#define ACE_LACKS_T_ERRNO 1 + +/* POSIX threads ompatibilities */ +#define ACE_LACKS_RWLOCK_T 1 +#define ACE_LACKS_PTHREAD_KILL 1 +#define ACE_LACKS_THREAD_PROCESS_SCOPING 1 + +#define ACE_HAS_PTHREADS 1 +#define ACE_HAS_PTHREAD_PROCESS_ENUM 1 +#define ACE_LACKS_UNNAMED_SEMAPHORE 1 +#define ACE_MT_SAFE 1 +#define ACE_HAS_THREADS 1 +#define ACE_HAS_THREAD_SPECIFIC_STORAGE 1 +#define ACE_HAS_THR_C_DEST 1 +#define ACE_HAS_THR_C_FUNC 1 +#define ACE_LACKS_PTHREAD_SIGMASK 1 +#define ACE_LACKS_PTHREAD_THR_SIGSETMASK 1 +#define ACE_NEEDS_HUGE_THREAD_STACKSIZE (64U*1024) +#define ACE_HAS_PTHREAD_SETCONCURRENCY 1 +#define ACE_HAS_PTHREAD_GETCONCURRENCY 1 +#define ACE_HAS_PTHREAD_SCHEDPARAM 1 + +/* language/platform conformance */ +#define ACE_NEW_THROWS_EXCEPTIONS 1 +#define ACE_TEMPLATES_REQUIRE_SOURCE 1 +#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 +#define ACE_HAS_AUTOMATIC_INIT_FINI 1 +#define ACE_LACKS_UNIX_SIGNALS 1 + +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES 1 +#define ACE_HAS_CPLUSPLUS_HEADERS 1 +#define ACE_HAS_EXCEPTIONS 1 +#define ACE_LACKS_LINEBUFFERED_STREAMBUF 1 + +#define ACE_HAS_GPERF 1 +#define ACE_HAS_IP_MULTICAST 1 +#define ACE_LACKS_PERFECT_MULTICAST_FILTERING 1 +#define ACE_HAS_POSIX_NONBLOCK 1 +#define ACE_HAS_POSIX_TIME 1 +#define ACE_HAS_BROKEN_POSIX_TIME 1 +#define ACE_HAS_STANDARD_CPP_LIBRARY 1 +#define ACE_HAS_STRING_CLASS 1 +#define ACE_HAS_SVR4_DYNAMIC_LINKING 1 + +#define ACE_HAS_TEMPLATE_TYPEDEFS 1 +#define ACE_LACKS_NAMED_POSIX_SEM 1 +#define ACE_LACKS_SYSV_SHMEM 1 +#define ACE_LACKS_UNIX_DOMAIN_SOCKETS 1 +#define ACE_LACKS_UNIX_SYSLOG 1 +#define ACE_LACKS_ALPHASORT 1 +#define ACE_LACKS_ISCTYPE +#define ACE_LACKS_ISBLANK + +#define ACE_LACKS_SETENV +#define ACE_LACKS_UNSETENV + +#endif diff --git a/dep/acelite/ace/config-pharlap.h b/dep/acelite/ace/config-pharlap.h new file mode 100644 index 00000000000..dad0e91a913 --- /dev/null +++ b/dep/acelite/ace/config-pharlap.h @@ -0,0 +1,91 @@ +/* -*- C++ -*- */ +// $Id: config-pharlap.h 84373 2009-02-10 18:21:50Z johnnyw $ + +// This configuration file is for use with the PharLap Realtime ETS Kernel. +// It has been tested with PharLap TNT Embedded ToolSuite version 9.1. + +#ifndef ACE_CONFIG_PHARLAP_H +#define ACE_CONFIG_PHARLAP_H +#include /**/ "ace/pre.h" + +#define ACE_HAS_PHARLAP +// Some features are only available with the Realtime edition of ETS. +// Assume that if using ACE, the realtime version is also being used, but +// allow it to be turned off as well. +#ifndef ACE_HAS_PHARLAP_RT +# define ACE_HAS_PHARLAP_RT +#else +# if (ACE_HAS_PHARLAP_RT == 0) +# undef ACE_HAS_PHARLAP_RT +# endif +#endif + +// Fortunately, PharLap ETS offers much of the Win32 API. But it's still on +// Winsock 1.1 +#define ACE_HAS_WINSOCK2 0 +#define ACE_HAS_WINSOCK1 1 + +// The TSS implementation doesn't pass muster on the TSS_Test, but it works +// well with ACE's TSS emulation. +#define ACE_HAS_TSS_EMULATION + +#define ACE_LACKS_MMAP +#define ACE_LACKS_MPROTECT +#define ACE_LACKS_MSYNC +#define ACE_LACKS_TCP_NODELAY +#define ACE_LACKS_MSG_WFMO +#define ACE_LACKS_WIN32_MOVEFILEEX +#define ACE_LACKS_WIN32_REGISTRY +#define ACE_LACKS_WIN32_SECURITY_DESCRIPTORS +#define ACE_LACKS_WIN32_SERVICES +#define ACE_LACKS_WIN32_SETFILEPOINTEREX + +// There's no host table, by default. So using "localhost" won't work. +// If your system does have the ability to use "localhost" and you want to, +// define it before including this file. +#if !defined (ACE_LOCALHOST) +# define ACE_LOCALHOST "127.0.0.1" +#endif /* ACE_LOCALHOST */ + +// The normal Windows default stack size doesn't hold for ETS. Set what you +// want explicitly. +#if !defined (ACE_DEFAULT_THREAD_STACKSIZE) +# define ACE_DEFAULT_THREAD_STACKSIZE (1024*1024) +#endif /* ACE_DEFAULT_THREAD_STACKSIZE */ + +// Don't know how to get the page size at execution time. This is most likely +// the correct value. +#define ACE_PAGE_SIZE 4096 + +#if defined (ACE_HAS_PHARLAP_RT) +# define ACE_HAS_IP_MULTICAST + // ETS winsock doesn't define IP level socket options +//# define IP_TOS 8 +#endif /* ACE_HAS_PHARLAP_RT */ + +// Let the config-win32.h file do its thing +#undef ACE_CONFIG_H +#include "ace/config-win32.h" +// Now remove things that desktop/server Windows has but Pharlap ETS doesn't. +#undef ACE_HAS_INTERLOCKED_EXCHANGEADD +#undef ACE_HAS_WCHAR + +// PharLap's exports apparantly define LockFile, but it's documented as +// unsupported. LockFileEx is not present. +#define ACE_LACKS_FILELOCKS + +#include /**/ +#if defined (ACE_HAS_PHARLAP_RT) +# include /**/ +#define ACE_LACKS_IP_ADD_MEMBERSHIP +#endif /* ACE_HAS_PHARLAP_RT */ + +// Although IN_CLASSD is defined in both winsock.h and winsock2.h, it ends +// up undefined for Pharlap ETS builds. If this is the case, set things up +// so nothing looks like class D. +#if !defined (IN_CLASSD) +# define IN_CLASSD(i) (0) +#endif + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_PHARLAP_H */ diff --git a/dep/acelite/ace/config-posix-nonetworking.h b/dep/acelite/ace/config-posix-nonetworking.h new file mode 100644 index 00000000000..7edc31d0dab --- /dev/null +++ b/dep/acelite/ace/config-posix-nonetworking.h @@ -0,0 +1,86 @@ +/* -*- C -*- */ +// $Id: config-posix-nonetworking.h 80826 2008-03-04 14:51:23Z wotte $ + +/* The following configuration file is designed to work for RTEMS + platforms using GNU C. +*/ + +#ifndef ACE_CONFIG_POSIX_NONETWORKING_H +#define ACE_CONFIG_POSIX_NONETWORKING_H + +// Missing header files +# define ACE_LACKS_SYS_UIO_H +# define ACE_LACKS_SYS_SOCKET_H +# define ACE_LACKS_NETINET_IN_H +# define ACE_LACKS_NETDB_H +# define ACE_LACKS_ARPA_INET_H +# define ACE_LACKS_SYS_SELECT_H +# define ACE_LACKS_NET_IF_H +# define ACE_LACKS_SYSLOG_H +# define ACE_LACKS_SYS_UN_H +# define ACE_LACKS_MEMORY_H +# define ACE_LACKS_SYS_SYSCTL_H +# define ACE_LACKS_NETINET_TCP_H + +// Missing types +# define ACE_LACKS_IOVEC +# define ACE_LACKS_IN_ADDR +# define ACE_LACKS_SOCKADDR_IN +# define ACE_LACKS_SOCKADDR_UN +# define ACE_LACKS_HOSTENT +# define ACE_LACKS_SOCKADDR +# define ACE_LACKS_IP_MREQ +# define ACE_LACKS_PROTOENT +# define ACE_LACKS_SERVENT +# define ACE_LACKS_IFREQ +# define ACE_LACKS_IFCONF +# define ACE_LACKS_LINGER + +// Missing methods +# define ACE_LACKS_GETHOSTBYADDR +# define ACE_LACKS_GETHOSTBYNAME +# define ACE_LACKS_GETIPNODEBYADDR +# define ACE_LACKS_LISTEN +# define ACE_LACKS_BIND +# define ACE_LACKS_NTOHL +# define ACE_LACKS_HTONL +# define ACE_LACKS_HTONS +# define ACE_LACKS_NTOHS +# define ACE_LACKS_SELECT +# define ACE_LACKS_SOCKET +# define ACE_LACKS_SHUTDOWN +# define ACE_LACKS_SETSOCKOPT +# define ACE_LACKS_INET_ATON +# define ACE_LACKS_INET_ADDR +# define ACE_LACKS_INET_NTOA +# define ACE_LACKS_GET_BCAST_ADDR +# define ACE_LACKS_GETHOSTENT +# define ACE_LACKS_GETSERVBYNAME +# define ACE_LACKS_ACCEPT +# define ACE_LACKS_CONNECT +# define ACE_LACKS_GETPEERNAME +# define ACE_LACKS_GETSOCKNAME +# define ACE_LACKS_GETSOCKOPT +# define ACE_LACKS_RECV +# define ACE_LACKS_SEND +# define ACE_LACKS_SENDTO +# define ACE_LACKS_RECVFROM +# define ACE_LACKS_RECVMSG +# define ACE_LACKS_SENDMSG +# define ACE_LACKS_GETHOSTBYADDR_R +# define ACE_LACKS_GETPROTOBYNAME +# define ACE_LACKS_GETPROTOBYNUMBER +# define ACE_LACKS_GETSERVBYNAME +# define ACE_LACKS_READV +# define ACE_LACKS_WRITEV +# define ACE_LACKS_SOCKETPAIR +# undef ACE_HAS_MSG + +// Missing OS features +# define ACE_LACKS_UNIX_SYSLOG +# define ACE_LACKS_TCP_NODELAY + +// Missing ACE features +# define ACE_DISABLE_NOTIFY_PIPE_DEFAULT 1 + +#endif /* ACE_CONFIG_POSIX_NONETWORKING_H */ diff --git a/dep/acelite/ace/config-posix.h b/dep/acelite/ace/config-posix.h new file mode 100644 index 00000000000..09b4e0671f3 --- /dev/null +++ b/dep/acelite/ace/config-posix.h @@ -0,0 +1,73 @@ +/* -*- C++ -*- */ +// $Id: config-posix.h 82517 2008-08-05 19:36:26Z shuston $ + +#ifndef ACE_CONFIG_POSIX_H +#define ACE_CONFIG_POSIX_H + +#include + +/* The following POSIX constants are defined after is + * included. They are documented in: + * http://www.opengroup.org/onlinepubs/007904975/basedefs/unistd.h.html + */ +#if defined(_POSIX_REALTIME_SIGNALS) && (_POSIX_REALTIME_SIGNALS-0 != -1 ) +# if !defined(ACE_HAS_POSIX_REALTIME_SIGNALS) +# define ACE_HAS_POSIX_REALTIME_SIGNALS +# endif /* ACE_HAS_POSIX_REALTIME_SIGNALS */ +#endif /* _POSIX_REALTIME_SIGNALS */ + +#if defined(_POSIX_ASYNCHRONOUS_IO) && (_POSIX_ASYNCHRONOUS_IO-0 != -1 ) +# if !defined(ACE_HAS_AIO_CALLS) +# define ACE_HAS_AIO_CALLS +# endif /* ACE_HAS_AIO_CALLS */ +#endif /* _POSIX_ASYNCHRONOUS_IO */ + +#if !defined (ACE_MT_SAFE) || (ACE_MT_SAFE != 0) +# if defined(_POSIX_SEMAPHORES) && (_POSIX_SEMAPHORES-0 != -1 ) +# if !defined(ACE_HAS_POSIX_SEM) +# define ACE_HAS_POSIX_SEM +# endif /* ACE_HAS_POSIX_SEM */ +# if defined(ACE_HAS_POSIX_SEM) +# if !defined (ACE_HAS_POSIX_SEM_TIMEOUT) && \ + (defined (_POSIX_TIMEOUTS) && (_POSIX_TIMEOUTS-0 != -1)) +# define ACE_HAS_POSIX_SEM_TIMEOUT +# endif /* ACE_HAS_POSIX_SEM_TIMEOUT && _POSIX_TIMEOUTS */ +# endif /* ACE_HAS_POSIX_SEM */ +# endif /* ACE_HAS_POSIX_SEM */ +#endif /* !ACE_MT_SAFE */ + +#if defined(_POSIX_SHARED_MEMORY_OBJECTS) && (_POSIX_SHARED_MEMORY_OBJECTS-0 != -1 ) +# if !defined(ACE_HAS_SHM_OPEN) +# define ACE_HAS_SHM_OPEN +# endif /* ACE_HAS_SHM_OPEN */ +#endif /* _POSIX_SHARED_MEMORY_OBJECTS */ + +// Check if threading enabled/disable through platform_macros +#if !defined (ACE_MT_SAFE) || (ACE_MT_SAFE != 0) +// Allow the user to disable use of threads by setting ACE_HAS_THREADS to 0 +// before including this file. The platform config (not macros) file can +// often detect that the compiler was invoked with or without threads support +// and set this accordingly. +# if defined (ACE_HAS_THREADS) && (ACE_HAS_THREADS == 0) +# undef ACE_HAS_THREADS +# else +# if defined(_POSIX_THREADS) && (_POSIX_THREADS-0 != -1 ) +# if !defined(ACE_HAS_THREADS) +# define ACE_HAS_THREADS +# endif /* ACE_HAS_THREADS */ + +# if !defined(ACE_HAS_PTHREADS) +# define ACE_HAS_PTHREADS +# endif /* ACE_HAS_PTHREADS */ + +# endif /* _POSIX_THREADS */ +# endif /* ACE_HAS_THREADS */ +#endif /* !ACE_MT_SAFE */ + +#if defined(_POSIX_MESSAGE_PASSING) && (_POSIX_MESSAGE_PASSING-0 != -1 ) +# if !defined(ACE_HAS_POSIX_MESSAGE_PASSING) +# define ACE_HAS_POSIX_MESSAGE_PASSING +# endif /* ACE_HAS_POSIX_MESSAGE_PASSING */ +#endif /* _POSIX_MESSAGE_PASSING */ + +#endif /* ACE_CONFIG_POSIX_H */ diff --git a/dep/acelite/ace/config-qnx-neutrino.h b/dep/acelite/ace/config-qnx-neutrino.h new file mode 100644 index 00000000000..86525567c38 --- /dev/null +++ b/dep/acelite/ace/config-qnx-neutrino.h @@ -0,0 +1,136 @@ +// -*- C++ -*- +// $Id: config-qnx-neutrino.h 87167 2009-10-19 19:33:53Z olli $ +// The following configuration file is designed to work for Neutrino +// 2.0 (Beta) with GNU C++ and the POSIX (pthread) threads package. + +#ifndef ACE_CONFIG_H +#define ACE_CONFIG_H +#include /**/ "ace/pre.h" + +#define _POSIX_C_SOURCE 199506 +#define _QNX_SOURCE + +// These constants are in i386-nto/include/limits.h, but egcs +// picks up its own limits.h instead: +#define _POSIX_NAME_MAX 14 /* Max bytes in a filename */ +#define _POSIX_PATH_MAX 256 /* Num. bytes in pathname (excl. NULL) */ + +#if defined(__OPTIMIZE__) +# if defined(__X86__) + // string.h can't be used by ACE with __OPTIMIZE__. +# undef __OPTIMIZE__ +# include +# define __OPTIMIZE__ +# endif /* __X86__ */ +#endif /* __OPTIMIZE__ */ + +#include "ace/config-g++-common.h" + +// The following defines the Neutrino compiler. +// gcc should know to call g++ as necessary +#ifdef __GNUC__ +# define ACE_CC_NAME ACE_TEXT ("gcc") +#else +# define ACE_CC_NAME ACE_TEXT ("NTO compiler ??") +#endif + +// /usr/nto/include/float.h defines +// FLT_MAX_EXP 127 +// DBL_MAX_EXP 1023 +// ace expects 128 & 1024 respectively +// to set the following macros in ace/Basic_Types.h +// These macros are: +// #define ACE_SIZEOF_DOUBLE 8 +// #define ACE_SIZEOF_FLOAT 4 + +#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R +#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG +// Although ACE does have alloca() on this compiler/platform combination, it is +// disabled by default since it can be dangerous. Uncomment the following line +// if you ACE to use it. +//#define ACE_HAS_ALLOCA +#define ACE_HAS_ALLOCA_H +#define ACE_HAS_AUTOMATIC_INIT_FINI +#define ACE_HAS_CLOCK_GETTIME +#define ACE_HAS_CLOCK_SETTIME +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES +#define ACE_HAS_DIRENT +#define ACE_HAS_GETPAGESIZE +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT +#define ACE_HAS_NONSTATIC_OBJECT_MANAGER +#define ACE_HAS_INLINED_OSCALLS +#define ACE_HAS_IP_MULTICAST +#define ACE_HAS_MSG +#define ACE_HAS_MT_SAFE_MKTIME +#define ACE_HAS_MUTEX_TIMEOUTS +#define ACE_HAS_NONCONST_SELECT_TIMEVAL +#define ACE_HAS_NONCONST_SWAB +#define ACE_HAS_POSIX_SEM +#define ACE_HAS_POSIX_TIME +#define ACE_HAS_PTHREADS +#define ACE_HAS_P_READ_WRITE +#define ACE_HAS_REENTRANT_FUNCTIONS +#define ACE_HAS_SELECT_H +#define ACE_HAS_SIGINFO_T +#define ACE_HAS_SIGISMEMBER_BUG +#define ACE_HAS_SIGWAIT +#define ACE_HAS_SIG_ATOMIC_T +#define ACE_HAS_SOCKADDR_IN_SIN_LEN +#define ACE_HAS_SSIZE_T +#define ACE_HAS_STRINGS +#define ACE_HAS_SVR4_GETTIMEOFDAY +#define ACE_HAS_TERMIOS +#define ACE_HAS_THREADS +#define ACE_HAS_THREAD_SPECIFIC_STORAGE +#define ACE_HAS_THR_C_DEST +#define ACE_HAS_THR_C_FUNC +#define ACE_HAS_TIMEZONE_GETTIMEOFDAY +#define ACE_HAS_UALARM +#define ACE_HAS_UCONTEXT_T +#define ACE_HAS_VOIDPTR_MMAP +#define ACE_HAS_VOIDPTR_SOCKOPT +#define ACE_LACKS_CONDATTR_PSHARED +#define ACE_LACKS_CONST_TIMESPEC_PTR +#define ACE_LACKS_CUSERID +#define ACE_LACKS_FORK +#define ACE_LACKS_LINEBUFFERED_STREAMBUF +#define ACE_LACKS_MADVISE +#define ACE_LACKS_MUTEXATTR_PSHARED +#define ACE_LACKS_NAMED_POSIX_SEM +#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS +#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS +#define ACE_LACKS_POLL_H +#define ACE_LACKS_PTHREAD_THR_SIGSETMASK +#define ACE_LACKS_RWLOCK_T +#define ACE_LACKS_SBRK +#define ACE_LACKS_SEEKDIR +#define ACE_LACKS_SO_SNDBUF +#define ACE_LACKS_SO_RCVBUF +#define ACE_LACKS_SOCKETPAIR +#define ACE_LACKS_STROPTS_H +#define ACE_LACKS_STREAM_MODULES +#define ACE_LACKS_STRRECVFD +#define ACE_LACKS_SYSCALL +#define ACE_LACKS_SYS_MSG_H +#define ACE_LACKS_SYS_SHM_H +#define ACE_LACKS_SYSV_SHMEM +#define ACE_LACKS_TCP_NODELAY +#define ACE_LACKS_TELLDIR +#define ACE_LACKS_TIMESPEC_T +#define ACE_LACKS_TRUNCATE +#define ACE_LACKS_T_ERRNO +#define ACE_LACKS_UALARM_PROTOTYPE +#define ACE_LACKS_UCONTEXT_H +#define ACE_LACKS_UNIX_DOMAIN_SOCKETS +#define ACE_LACKS_U_LONGLONG_T +#define ACE_MT_SAFE 1 +#define ACE_NEEDS_FUNC_DEFINITIONS +#define ACE_NEEDS_HUGE_THREAD_STACKSIZE 65536 +#define ACE_TEMPLATES_REQUIRE_SOURCE +#define ACE_THR_PRI_FIFO_DEF 10 +#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 +#define ACE_HAS_SIGTIMEDWAIT +#define ACE_HAS_SIGSUSPEND + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_H */ diff --git a/dep/acelite/ace/config-qnx-rtp-62x.h b/dep/acelite/ace/config-qnx-rtp-62x.h new file mode 100644 index 00000000000..7fa7514a1c8 --- /dev/null +++ b/dep/acelite/ace/config-qnx-rtp-62x.h @@ -0,0 +1,131 @@ +// -*- C++ -*- +// $Id: config-qnx-rtp-62x.h 87167 2009-10-19 19:33:53Z olli $ +// The following configuration file is designed to work for QNX RTP 621 +// GNU C++ and the POSIX (pthread) threads package. You can get QNX +// RTP at http://get.qnx.com +#ifndef ACE_CONFIG_QNX_RTP_62x_H +#define ACE_CONFIG_QNX_RTP_62x_H +#include /**/ "ace/pre.h" +#include /**/ "ace/config-qnx-rtp-common.h" + +///////////////////////////////////////////////////////////////// +// Definition of the features that are available. +// +// ACE_HAS Section +///////////////////////////////////////////////////////////////// +#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R +#define ACE_HAS_3_PARAM_WCSTOK +#define ACE_HAS_3_PARAM_READDIR_R +#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG +// Although ACE does have alloca() on this compiler/platform combination, it is +// disabled by default since it can be dangerous. Uncomment the following line +// if you ACE to use it. +//#define ACE_HAS_ALLOCA +#define ACE_HAS_ALLOCA_H +#define ACE_HAS_ALT_CUSERID +#define ACE_HAS_AUTOMATIC_INIT_FINI +#define ACE_HAS_CLOCK_GETTIME +#define ACE_HAS_CLOCK_SETTIME +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES +#define ACE_HAS_DIRENT +#define ACE_HAS_GETPAGESIZE +#define ACE_HAS_GETIFADDRS +// Enable gperf, this is a hosted configuration. +#define ACE_HAS_GPERF +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT +//#define ACE_HAS_NONSTATIC_OBJECT_MANAGER +#define ACE_HAS_IP_MULTICAST +#define ACE_HAS_MSG +#define ACE_HAS_MT_SAFE_MKTIME +#define ACE_HAS_MUTEX_TIMEOUTS +#define ACE_HAS_NONCONST_SELECT_TIMEVAL +#define ACE_HAS_NONCONST_SWAB +#define ACE_HAS_POSIX_SEM +#define ACE_HAS_POSIX_TIME +#define ACE_HAS_PTHREADS +#define ACE_HAS_P_READ_WRITE +#define ACE_HAS_REENTRANT_FUNCTIONS +#define ACE_HAS_SELECT_H +#define ACE_HAS_SHM_OPEN +#define ACE_HAS_SIGINFO_T +#define ACE_HAS_SIGISMEMBER_BUG +#define ACE_HAS_SIGWAIT +#define ACE_HAS_SIG_ATOMIC_T +#define ACE_HAS_SOCKADDR_IN_SIN_LEN +#define ACE_HAS_SOCKLEN_T +#define ACE_HAS_SSIZE_T +#define ACE_HAS_STRINGS +#define ACE_HAS_SVR4_DYNAMIC_LINKING +#define ACE_HAS_SVR4_GETTIMEOFDAY +#define ACE_HAS_TERMIOS +#define ACE_HAS_THREADS +#define ACE_HAS_THREAD_SPECIFIC_STORAGE +#define ACE_HAS_THR_C_DEST +#define ACE_HAS_THR_C_FUNC +#define ACE_HAS_TIMEZONE_GETTIMEOFDAY +#define ACE_HAS_UALARM +#define ACE_HAS_UCONTEXT_T +#define ACE_HAS_VOIDPTR_MMAP +#define ACE_HAS_VOIDPTR_SOCKOPT + +///////////////////////////////////////////////////////////////// +// Definition of the features that are not available. +// +// ACE_LACKS Section +///////////////////////////////////////////////////////////////// +#define ACE_LACKS_CONST_TIMESPEC_PTR +#define ACE_LACKS_LINEBUFFERED_STREAMBUF +#define ACE_LACKS_MADVISE +// lacks mqueue mgr or speed-up named sem by shm emulation +#define ACE_LACKS_NAMED_POSIX_SEM +#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS +// Multicast_Tests reports for NTO 621 frames from unsubscribed groups +#define ACE_LACKS_PERFECT_MULTICAST_FILTERING 1 +#define ACE_LACKS_POLL_H +#define ACE_LACKS_PTHREAD_THR_SIGSETMASK +#define ACE_LACKS_RWLOCK_T +#define ACE_LACKS_SO_SNDBUF +#define ACE_LACKS_SO_RCVBUF +#define ACE_LACKS_STREAM_MODULES +#define ACE_LACKS_STROPTS_H +#define ACE_LACKS_STRPTIME +#define ACE_LACKS_STRRECVFD +#define ACE_LACKS_SYSCALL +#define ACE_LACKS_SYS_MSG_H +#define ACE_LACKS_SYSV_SHMEM +#define ACE_LACKS_SYS_SHM_H +#define ACE_LACKS_TIMESPEC_T +#define ACE_LACKS_T_ERRNO +#define ACE_LACKS_U_LONGLONG_T +#define ACE_LACKS_ALPHASORT +#define ACE_LACKS_FD_MASK +#define ACE_LACKS_NFDBITS +#define ACE_LACKS_ISCTYPE + +#define ACE_LACKS_RLIMIT // QNX rlimit syscalls don't work properly with ACE. + +#define ACE_MT_SAFE 1 +#define ACE_NEEDS_FUNC_DEFINITIONS +#define ACE_NEEDS_HUGE_THREAD_STACKSIZE 64000 +#define ACE_THR_PRI_FIFO_DEF 10 +#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 +#define ACE_HAS_SIGTIMEDWAIT +#define ACE_HAS_SIGSUSPEND + +#define ACE_HAS_BROKEN_PREALLOCATED_OBJECTS_AFTER_FORK 1 + +#define ACE_SIZEOF_WCHAR 4 + +// No prototypes +#define ACE_LACKS_ITOW +#define ACE_LACKS_WCSICMP +#define ACE_LACKS_WCSNICMP +#define ACE_LACKS_WCSDUP +// The default value of FD_SETSIZE is 32, but actually x86 NTO +// supports by default at least 1000 descriptors in fd_set. +#if defined( FD_SETSIZE ) +#undef FD_SETSIZE +#endif +#define FD_SETSIZE 1000 +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_QNX_RTP_62x_H*/ diff --git a/dep/acelite/ace/config-qnx-rtp-common.h b/dep/acelite/ace/config-qnx-rtp-common.h new file mode 100644 index 00000000000..79eb2397b4f --- /dev/null +++ b/dep/acelite/ace/config-qnx-rtp-common.h @@ -0,0 +1,50 @@ +// -*- C++ -*- +// $Id: config-qnx-rtp-common.h 85074 2009-04-10 03:17:24Z mesnier_p $ +// several macros common to various qnx neutrino version. + +#ifndef ACE_CONFIG_QNX_RTP_COMMON_H +#define ACE_CONFIG_QNX_RTP_COMMON_H +#include /**/ "ace/pre.h" + +#define _POSIX_C_SOURCE 199506 +#define _QNX_SOURCE + +// These constants are in i386-nto/include/limits.h, but egcs +// picks up its own limits.h instead: +#define _POSIX_NAME_MAX 14 /* Max bytes in a filename */ +#define _POSIX_PATH_MAX 256 /* Num. bytes in pathname (excl. NULL) */ + +#if defined(__OPTIMIZE__) +# if defined(__X86__) + // string.h can't be used by ACE with __OPTIMIZE__. +# undef __OPTIMIZE__ +# include +# define __OPTIMIZE__ +# endif /* __X86__ */ +#endif /* __OPTIMIZE__ */ + +#include "ace/config-g++-common.h" + +// The following defines the Neutrino compiler. +// gcc should know to call g++ as necessary +#ifdef __GNUC__ +# define ACE_CC_NAME ACE_TEXT ("gcc") +#else +# define ACE_CC_NAME ACE_TEXT ("QNX-RTP compiler ??") +#endif + +// /usr/nto/include/float.h defines +// FLT_MAX_EXP 127 +// DBL_MAX_EXP 1023 +// ace expects 128 & 1024 respectively +// to set the following macros in ace/Basic_Types.h +// These macros are: +#define ACE_SIZEOF_DOUBLE 8 +#define ACE_SIZEOF_FLOAT 4 + +// At least qnx 6.3.2 uses a void return for unsetenv +// This assumes that older versions do too. +#define ACE_HAS_VOID_UNSETENV + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_QNX_RTP_COMMON_H */ diff --git a/dep/acelite/ace/config-qnx-rtp-pre62x.h b/dep/acelite/ace/config-qnx-rtp-pre62x.h new file mode 100644 index 00000000000..504d3a3ac09 --- /dev/null +++ b/dep/acelite/ace/config-qnx-rtp-pre62x.h @@ -0,0 +1,152 @@ +// -*- C++ -*- +// $Id: config-qnx-rtp-pre62x.h 87167 2009-10-19 19:33:53Z olli $ +// The following configuration file is designed to work for QNX RTP +// GNU C++ and the POSIX (pthread) threads package. You can get QNX +// RTP at http://get.qnx.com + +#ifndef ACE_CONFIG_RTP_PRE62x_H +#define ACE_CONFIG_RTP_PRE62x_H +#include /**/ "ace/pre.h" +#include /**/ "ace/config-qnx-rtp-common.h" + +///////////////////////////////////////////////////////////////// +// Definition of the features that are available. +// +// ACE_HAS Section +///////////////////////////////////////////////////////////////// + +#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R +#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG +// Although ACE does have alloca() on this compiler/platform combination, it is +// disabled by default since it can be dangerous. Uncomment the following line +// if you ACE to use it. +//#define ACE_HAS_ALLOCA +#define ACE_HAS_ALLOCA_H +#define ACE_HAS_AUTOMATIC_INIT_FINI +#define ACE_HAS_CLOCK_GETTIME +#define ACE_HAS_CLOCK_SETTIME +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES +#define ACE_HAS_DIRENT +#define ACE_HAS_GETPAGESIZE +// Enable gperf, this is a hosted configuration. +#define ACE_HAS_GPERF +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT +//#define ACE_HAS_NONSTATIC_OBJECT_MANAGER +#define ACE_HAS_INLINED_OSCALLS +#define ACE_HAS_IP_MULTICAST +#define ACE_HAS_MSG +#define ACE_HAS_MT_SAFE_MKTIME +#define ACE_HAS_MUTEX_TIMEOUTS +#define ACE_HAS_NONCONST_SELECT_TIMEVAL +#define ACE_HAS_POSIX_SEM +#define ACE_HAS_POSIX_TIME +#define ACE_HAS_PTHREADS +#define ACE_HAS_P_READ_WRITE +#define ACE_HAS_REENTRANT_FUNCTIONS +#define ACE_HAS_SELECT_H +#define ACE_HAS_SIGINFO_T +#define ACE_HAS_SIGISMEMBER_BUG +#define ACE_HAS_SIGWAIT +#define ACE_HAS_SIG_ATOMIC_T +#define ACE_HAS_SOCKADDR_IN_SIN_LEN +// #define ACE_HAS_SIZET_SOCKET_LEN +#define ACE_HAS_SOCKLEN_T +#define ACE_HAS_SSIZE_T +#define ACE_HAS_STRINGS +#define ACE_HAS_SVR4_GETTIMEOFDAY +#define ACE_HAS_TERMIOS +#define ACE_HAS_THREADS +#define ACE_HAS_THREAD_SPECIFIC_STORAGE +#define ACE_HAS_THR_C_DEST +#define ACE_HAS_THR_C_FUNC +#define ACE_HAS_TIMEZONE_GETTIMEOFDAY +#define ACE_HAS_UALARM +#define ACE_HAS_UCONTEXT_T +#define ACE_HAS_VOIDPTR_MMAP +#define ACE_HAS_VOIDPTR_SOCKOPT + +///////////////////////////////////////////////////////////////// +// Definition of the features that are not available. +// +// ACE_LACKS Section +///////////////////////////////////////////////////////////////// +#define ACE_LACKS_CONDATTR_PSHARED +#define ACE_LACKS_CONST_TIMESPEC_PTR +#define ACE_LACKS_LINEBUFFERED_STREAMBUF +#define ACE_LACKS_MADVISE +#define ACE_LACKS_MUTEXATTR_PSHARED +#define ACE_LACKS_NAMED_POSIX_SEM +#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS +#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS +#define ACE_LACKS_PTHREAD_THR_SIGSETMASK +#define ACE_LACKS_RWLOCK_T +#define ACE_LACKS_SBRK +#define ACE_LACKS_SEEKDIR +#define ACE_LACKS_SO_SNDBUF +#define ACE_LACKS_SO_RCVBUF +#define ACE_LACKS_SOCKETPAIR +// Even if the QNX RTP docs says that socket pair are +// available, there is actually no implementation of +// soket-pairs. +#define ACE_LACKS_STREAM_MODULES +#define ACE_LACKS_STRRECVFD +#define ACE_LACKS_SYSCALL +#define ACE_LACKS_SYS_MSG_H +#define ACE_LACKS_SYSV_SHMEM +#define ACE_LACKS_ALPHASORT +//#define ACE_LACKS_TCP_NODELAY // Based on the QNX RTP documentation, this option seems to + // to be supported. +#define ACE_LACKS_TELLDIR +#define ACE_LACKS_TIMESPEC_T +#define ACE_LACKS_TRUNCATE +#define ACE_LACKS_T_ERRNO +#define ACE_LACKS_UALARM_PROTOTYPE +#define ACE_LACKS_UCONTEXT_H +#define ACE_LACKS_UNIX_DOMAIN_SOCKETS +#define ACE_LACKS_U_LONGLONG_T +#define ACE_LACKS_FD_MASK +#define ACE_LACKS_NFDBITS + +#define ACE_LACKS_RLIMIT // QNX rlimit syscalls don't work properly with ACE. + +#define ACE_MT_SAFE 1 +#define ACE_NEEDS_FUNC_DEFINITIONS +#define ACE_NEEDS_HUGE_THREAD_STACKSIZE 64000 +#define ACE_TEMPLATES_REQUIRE_SOURCE +#define ACE_THR_PRI_FIFO_DEF 10 +#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 +#define ACE_HAS_SIGTIMEDWAIT +#define ACE_HAS_SIGSUSPEND + +#define ACE_HAS_BROKEN_PREALLOCATED_OBJECTS_AFTER_FORK 1 + +#define ACE_SIZEOF_WCHAR 4 + +// Not really, but the prototype returns wchar_t instead of wchar_t * +#define ACE_LACKS_WCSSTR + +// No prototypes +#define ACE_LACKS_ITOW +#define ACE_LACKS_WCSICMP +#define ACE_LACKS_WCSNICMP +#define ACE_LACKS_WCSDUP + +// And these have prototypes but no implementation +#define ACE_LACKS_WCSLEN +#define ACE_LACKS_WCSNCMP +#define ACE_LACKS_WCSCPY +#define ACE_LACKS_WCSNCPY +#define ACE_LACKS_TOWLOWER +#define ACE_LACKS_TOWUPPER +#define ACE_LACKS_WCSCMP +#define ACE_LACKS_WCSCAT +#define ACE_LACKS_WCSNCAT +#define ACE_LACKS_WCSSPN +#define ACE_LACKS_WCSCHR +#define ACE_LACKS_WCSPBRK +#define ACE_LACKS_WCSRCHR + +#define ACE_LACKS_ACE_IOSTREAM + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_RTP_PRE62x_H */ diff --git a/dep/acelite/ace/config-qnx-rtp.h b/dep/acelite/ace/config-qnx-rtp.h new file mode 100644 index 00000000000..c55a4abb988 --- /dev/null +++ b/dep/acelite/ace/config-qnx-rtp.h @@ -0,0 +1,25 @@ +// -*- C++ -*- +// $Id: config-qnx-rtp.h 80826 2008-03-04 14:51:23Z wotte $ +// The following configuration file is designed to work for QNX RTP +// GNU C++ and the POSIX (pthread) threads package. You can get QNX +// RTP at http://get.qnx.com. +// This header is intended to switch between configuration for +// various NTO versions. +#ifndef ACE_CONFIG_QNX_RTP_H +#define ACE_CONFIG_QNX_RTP_H +#include /**/ "ace/pre.h" + +#include +#if !defined(_NTO_VERSION) +# error "Could not detect QNX version from macro _NTO_VERSION" +#else +# define ACE_NTO_VERS _NTO_VERSION +# if ACE_NTO_VERS < 620 +# include /**/ "ace/config-qnx-rtp-pre62x.h" +# else +# include /**/ "ace/config-qnx-rtp-62x.h" +# endif +#endif + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_QNX_RTP_H */ diff --git a/dep/acelite/ace/config-rtems.h b/dep/acelite/ace/config-rtems.h new file mode 100644 index 00000000000..d113a1434a4 --- /dev/null +++ b/dep/acelite/ace/config-rtems.h @@ -0,0 +1,164 @@ +/* -*- C -*- */ +// $Id: config-rtems.h 87169 2009-10-19 20:26:55Z olli $ + +/* The following configuration file is designed to work for RTEMS + platforms using GNU C. +*/ + +#ifndef ACE_CONFIG_H +#define ACE_CONFIG_H + +#if ! defined (__ACE_INLINE__) +#define __ACE_INLINE__ +#endif /* ! __ACE_INLINE__ */ + +// Needed to make some prototypes visible. +// #if ! defined (_GNU_SOURCE) +// #define _GNU_SOURCE +// #endif /* ! _GNU_SOURCE */ + +// First the machine specific part +// There are no known port specific issues with the RTEMS port of ACE. +// XXX Pentium and PowerPC have high res timer support in ACE. + +// Then the compiler specific parts +#if defined (__GNUG__) + // config-g-common.h undef's ACE_HAS_STRING_CLASS with -frepo, so + // this must appear before its #include. +# define ACE_HAS_STRING_CLASS +# include "ace/config-g++-common.h" +#else /* ! __GNUG__ */ +# ifdef __cplusplus /* Let it slide for C compilers. */ +# error unsupported compiler in ace/config-rtems.h +# endif /* __cplusplus */ +#endif /* ! __GNUG__ */ + +#include "ace/config-posix.h" + +// Completely common part :-) + +#define ACE_HAS_NONSTATIC_OBJECT_MANAGER + +#define ACE_LACKS_ALPHASORT +#define ACE_LACKS_REGEX_H +#define ACE_LACKS_STROPTS_H +#define ACE_LACKS_DLFCN_H +#define ACE_LACKS_SIGINFO_H +#define ACE_LACKS_SYS_IPC_H +#define ACE_LACKS_SYS_SEM_H +#define ACE_LACKS_STRINGS_H +#define ACE_LACKS_SYS_SHM_H +#define ACE_LACKS_SETEGID +#define ACE_LACKS_SETEUID +#define ACE_LACKS_POLL_H +#define ACE_HAS_NONCONST_SELECT_TIMEVAL +#define ACE_LACKS_STRCASECMP +#define ACE_LACKS_MKSTEMP +#define ACE_LACKS_STRDUP +#define ACE_LACKS_STRTOK_R +#define ACE_LACKS_RAND_REENTRANT_FUNCTIONS +#define ACE_LACKS_REALPATH +#define ACE_LACKS_TEMPNAM +#define ACE_LACKS_TZSET + +// Temporarily, enabling this results in compile errors with +// rtems 4.6.6. +#define ACE_LACKS_WCHAR_H + +#if !defined (ACE_MT_SAFE) +#define ACE_MT_SAFE 1 +#endif + +#if ACE_MT_SAFE +# define ACE_HAS_THREADS +# define ACE_HAS_PTHREADS +# define ACE_HAS_THREAD_SPECIFIC_STORAGE +# define ACE_HAS_PTHREAD_SCHEDPARAM +# define ACE_LACKS_THREAD_PROCESS_SCOPING +#else +# define ACE_HAS_POSIX_GETPWNAM_R +# define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R +#endif + +#define ACE_HAS_ALT_CUSERID +#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG +#define ACE_HAS_3_PARAM_READDIR_R +#define ACE_HAS_CLOCK_GETTIME +#define ACE_HAS_CLOCK_SETTIME +#define ACE_HAS_DIRENT +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT +#define ACE_HAS_MSG +#define ACE_HAS_MT_SAFE_MKTIME +#define ACE_HAS_NONCONST_READV +#define ACE_HAS_GETPAGESIZE +#define ACE_HAS_POSIX_SEM +#define ACE_HAS_POSIX_TIME +#define ACE_HAS_REENTRANT_FUNCTIONS +#define ACE_HAS_SIGACTION_CONSTP2 +#define ACE_HAS_SIGINFO_T +#define ACE_HAS_SIGSUSPEND +#define ACE_HAS_SSIZE_T +#define ACE_HAS_VOIDPTR_GETTIMEOFDAY +#define ACE_HAS_SYS_FILIO_H +#define ACE_HAS_TIMEZONE_GETTIMEOFDAY +#define ACE_LACKS_EXEC +#define ACE_LACKS_FILELOCKS +#define ACE_LACKS_FORK +#define ACE_LACKS_GETPGID +#define ACE_LACKS_TIMESPEC_T +#define ACE_LACKS_MADVISE +#define ACE_LACKS_MMAP +#define ACE_LACKS_MPROTECT +#define ACE_LACKS_MSYNC +#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS +#define ACE_LACKS_PTHREAD_THR_SIGSETMASK +#define ACE_LACKS_READDIR_R +#define ACE_LACKS_READLINK +#define ACE_LACKS_READV +#define ACE_LACKS_RLIMIT +#define ACE_LACKS_RLIMIT_PROTOTYPE +#define ACE_LACKS_RWLOCK_T +#define ACE_LACKS_SBRK +#define ACE_LACKS_SEMBUF_T +#define ACE_LACKS_SETREUID +#define ACE_LACKS_SETREUID_PROTOTYPE +#define ACE_LACKS_SETREGID +#define ACE_LACKS_SETREGID_PROTOTYPE +#define ACE_LACKS_STRPTIME +#define ACE_LACKS_STRRECVFD +#define ACE_LACKS_SI_ADDR +#define ACE_LACKS_SOCKETPAIR +#define ACE_LACKS_SYS_MSG_H +#define ACE_LACKS_SYSV_SHMEM +#define ACE_LACKS_SYSCALL +#define ACE_LACKS_UCONTEXT_H +#define ACE_HAS_NONCONST_WRITEV +#define ACE_LACKS_WRITEV +#define ACE_NEEDS_HUGE_THREAD_STACKSIZE 65536 +#define ACE_NEEDS_SCHED_H +#define ACE_HAS_POSIX_NONBLOCK +#define ACE_HAS_TERMIOS + +// rtems 4.7 or higher +#if (__RTEMS_MAJOR__ > 4) || (__RTEMS_MAJOR__ == 4 && __RTEMS_MINOR__ > 6) +# define ACE_HAS_UALARM +#else +# define ACE_HAS_NOTSUP_SC_PAGESIZE +# define ACE_LACKS_SUSECONDS_T +# define ACE_LACKS_INTPTR_T +# undef ACE_HAS_SHM_OPEN +# undef ACE_HAS_AIO_CALLS +#endif + +// __RTEMS_REVISION__ could also be used but this is broken according +// to the rtems people + +#if !defined (_POSIX_REALTIME_SIGNALS) +# define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES +#endif + +#if defined (ACE_LACKS_NETWORKING) +# include "ace/config-posix-nonetworking.h" +#endif + +#endif /* ACE_CONFIG_H */ diff --git a/dep/acelite/ace/config-sco-5.0.0-nothread.h b/dep/acelite/ace/config-sco-5.0.0-nothread.h new file mode 100644 index 00000000000..259bd55c273 --- /dev/null +++ b/dep/acelite/ace/config-sco-5.0.0-nothread.h @@ -0,0 +1,12 @@ +/* -*- C++ -*- */ +// $Id: config-sco-5.0.0-nothread.h 87268 2009-10-29 21:06:06Z olli $ + +#ifndef ACE_CONFIG_H +#define ACE_CONFIG_H +#include /**/ "ace/pre.h" + +#include "ace/config-g++-common.h" +#include "ace/config-sco-5.0.0.h" + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_H */ diff --git a/dep/acelite/ace/config-sco-5.0.0.h b/dep/acelite/ace/config-sco-5.0.0.h new file mode 100644 index 00000000000..61b68213bc1 --- /dev/null +++ b/dep/acelite/ace/config-sco-5.0.0.h @@ -0,0 +1,90 @@ +/* -*- C++ -*- */ +// $Id: config-sco-5.0.0.h 87167 2009-10-19 19:33:53Z olli $ + +#ifndef ACE_CONFIG_SCO_5_0_0_H +#define ACE_CONFIG_SCO_5_0_0_H +#include /**/ "ace/pre.h" + +// Compiling for SCO. +#if !defined (SCO) +#define SCO +#endif /* SCO */ + +#if defined (SCO) && !defined (MAXPATHLEN) +#define MAXPATHLEN 1023 +#endif /* SCO */ + +#define ACE_HAS_NONCONST_SELECT_TIMEVAL +#define ACE_LACKS_CONST_TIMESPEC_PTR +#define ACE_LACKS_SYSCALL +#define ACE_LACKS_STRRECVFD +#define ACE_NEEDS_FTRUNCATE +#define ACE_LACKS_MADVISE +#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS + +#define ACE_DEFAULT_CLOSE_ALL_HANDLES 0 + +// Platform supports System V IPC (most versions of UNIX, but not Win32) +#define ACE_HAS_SYSV_IPC +#define ACE_HAS_NONCONST_MSGSND +#define ACE_HAS_BIG_FD_SET +#define ACE_HAS_SVR4_DYNAMIC_LINKING +#define ACE_HAS_AUTOMATIC_INIT_FINI + +// Platform has POSIX terminal interface. +#define ACE_HAS_TERMIOS + +// Compiler/platform contains the file. +//#define ACE_HAS_SYS_SYSCALL_H + +// Fixes a problem with HP/UX not wrapping the mmap(2) header files +// with extern "C". +//#define ACE_HAS_BROKEN_MMAP_H + +// Prototypes for both signal() and struct sigaction are consistent. +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES + +// Compiler/platform has correctly prototyped header files. +#define ACE_HAS_CPLUSPLUS_HEADERS + +// Compiler/platform supports poll(). +// #define ACE_HAS_POLL + +// Platform supports POSIX O_NONBLOCK semantics. +#define ACE_HAS_POSIX_NONBLOCK + +// Compiler/platform defines the sig_atomic_t typedef +#define ACE_HAS_SIG_ATOMIC_T + +// Compiler supports the ssize_t typedef. +//#define ACE_HAS_SSIZE_T + +// Defines the page size of the system. +#define ACE_PAGE_SIZE 4096 + +#define ACE_HAS_TIMEZONE_GETTIMEOFDAY + +// Note, this only works if the flag is set above! +//#define ACE_HAS_GETRUSAGE + +// Platform uses int for select() rather than fd_set. +#define ACE_HAS_SELECT_H + +// Platform has prototypes for ACE_TLI. +#define ACE_HAS_TLI_PROTOTYPES +// Platform has the XLI version of ACE_TLI. +// #define ACE_HAS_XLI + +#define ACE_HAS_SIGINFO_T +#define ACE_HAS_UCONTEXT_T + +#define ACE_LACKS_STRCASECMP + +// #define ACE_HAS_POSIX_TIME +#define ACE_HAS_IP_MULTICAST +#define ACE_HAS_DIRENT +#define ACE_LACKS_READDIR_R +#define ACE_HAS_GPERF + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_SCO_5_0_0_H */ diff --git a/dep/acelite/ace/config-suncc-common.h b/dep/acelite/ace/config-suncc-common.h new file mode 100644 index 00000000000..3f0bae8a295 --- /dev/null +++ b/dep/acelite/ace/config-suncc-common.h @@ -0,0 +1,67 @@ +// -*- C++ -*- +// +// $Id: config-suncc-common.h 81935 2008-06-12 22:01:53Z jtc $ + +#ifndef ACE_SUNCC_COMMON_H +#define ACE_SUNCC_COMMON_H +#include /**/ "ace/pre.h" + +# define ACE_HAS_CPLUSPLUS_HEADERS +# define ACE_HAS_STDCPP_STL_INCLUDES +# define ACE_HAS_TEMPLATE_TYPEDEFS +# define ACE_HAS_STANDARD_CPP_LIBRARY 1 +# define ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR +# define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 +# define ACE_HAS_STRING_CLASS +# define ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS +# define ACE_HAS_THR_C_DEST 1 +# define ACE_LACKS_SWAB +#if defined (ACE_HAS_CUSTOM_EXPORT_MACROS) && ACE_HAS_CUSTOM_EXPORT_MACROS == 0 +# undef ACE_HAS_CUSTOM_EXPORT_MACROS +#else +# ifndef ACE_HAS_CUSTOM_EXPORT_MACROS +# define ACE_HAS_CUSTOM_EXPORT_MACROS +# endif /* !ACE_HAS_CUSTOM_EXPORT_MACROS */ +# define ACE_Proper_Export_Flag __attribute__ ((visibility("default"))) +# define ACE_Proper_Import_Flag +# define ACE_EXPORT_SINGLETON_DECLARATION(T) template class ACE_Proper_Export_Flag T +# define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) template class ACE_Proper_Export_Flag SINGLETON_TYPE ; +# define ACE_IMPORT_SINGLETON_DECLARATION(T) __extension__ extern template class T +# define ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) __extension__ extern template class SINGLETON_TYPE; +#endif /* ACE_HAS_CUSTOM_EXPORT_MACROS == 0 */ + +// __EXCEPTIONS is defined with -fexceptions, the egcs default. It +// is not defined with -fno-exceptions, the ACE default for g++. +// ACE_HAS_EXCEPTIONS is defined in +// include/makeinclude/wrapper_macros.GNU, so this really isn't +// necessary. Just in case . . . +# if defined (__EXCEPTIONS) && !defined (ACE_HAS_EXCEPTIONS) +# define ACE_HAS_EXCEPTIONS +# endif /* __EXCEPTIONS && ! ACE_HAS_EXCEPTIONS */ + +# if defined (ACE_HAS_EXCEPTIONS) +# define ACE_NEW_THROWS_EXCEPTIONS +# endif /* ACE_HAS_EXCEPTIONS */ + +#if (defined (i386) || defined (__i386__)) && !defined (ACE_SIZEOF_LONG_DOUBLE) +# define ACE_SIZEOF_LONG_DOUBLE 12 +#endif /* i386 */ + +#if defined (i386) || defined (__i386__) + // If running an Intel, assume that it's a Pentium so that + // ACE_OS::gethrtime () can use the RDTSC instruction. If running a + // 486 or lower, be sure to comment this out. (If not running an + // Intel CPU, this #define will not be seen because of the i386 + // protection, so it can be ignored.) +# define ACE_HAS_PENTIUM +#endif /* i386 */ + +#if !defined (ACE_LACKS_PRAGMA_ONCE) + // We define it with a -D with make depend. +# define ACE_LACKS_PRAGMA_ONCE +#endif /* ! ACE_LACKS_PRAGMA_ONCE */ + +#define ACE_TEMPLATES_REQUIRE_SOURCE + +#include /**/ "ace/post.h" +#endif /* ACE_SUNCC_COMMON_H */ diff --git a/dep/acelite/ace/config-sunos5.10.h b/dep/acelite/ace/config-sunos5.10.h new file mode 100644 index 00000000000..df6f095fec9 --- /dev/null +++ b/dep/acelite/ace/config-sunos5.10.h @@ -0,0 +1,66 @@ +/* -*- C++ -*- */ +// $Id: config-sunos5.10.h 89905 2010-04-16 13:04:47Z johnnyw $ + +// The following configuration file is designed to work for SunOS 5.10 +// (Solaris 10) platforms using the SunC++ 5.x (Sun Studio 8-10), or g++ +// compilers. + +#ifndef ACE_CONFIG_H + +// ACE_CONFIG_H is defined by one of the following #included headers. + +// #include the SunOS 5.9 config, then add any SunOS 5.10 updates below. +#include "ace/config-sunos5.9.h" + +// Solaris 10 can do sem_timedwait() (see ACE_OS::sema_wait). +#define ACE_HAS_POSIX_SEM_TIMEOUT + +#define ACE_HAS_SCANDIR + +// Solaris 10 offers a useable alphasort() unlike previous Solaris versions. +#if defined (ACE_LACKS_ALPHASORT) +# undef ACE_LACKS_ALPHASORT +#endif + +// Solaris 10 offers a useable log2() unlike previous Solaris versions. +#if defined (ACE_LACKS_LOG2) +# undef ACE_LACKS_LOG2 +#endif + +// Solaris 10 offers a useable isblank() unlike previous Solaris versions. +#if defined (ACE_LACKS_ISBLANK) +# undef ACE_LACKS_ISBLANK +#endif + +// Solaris 10 delivers pthread_attr_setstack +#if defined (ACE_LACKS_PTHREAD_ATTR_SETSTACK) +# undef ACE_LACKS_PTHREAD_ATTR_SETSTACK +#endif + +// Solaris 10 introduced printf() modifiers for [s]size_t types. +#if defined (ACE_SSIZE_T_FORMAT_SPECIFIER_ASCII) +# undef ACE_SSIZE_T_FORMAT_SPECIFIER_ASCII +# define ACE_SSIZE_T_FORMAT_SPECIFIER_ASCII "%zd" +#endif /* ACE_SSIZE_T_FORMAT_SPECIFIER_ASCII */ + +#if defined (ACE_SIZE_T_FORMAT_SPECIFIER_ASCII) +# undef ACE_SIZE_T_FORMAT_SPECIFIER_ASCII +# define ACE_SIZE_T_FORMAT_SPECIFIER_ASCII "%zu" +#endif /* ACE_SIZE_T_FORMAT_SPECIFIER_ASCII */ + +// Solaris 10 offers wcstoll() and wcstoull() +#if defined (ACE_LACKS_WCSTOLL) +# undef ACE_LACKS_WCSTOLL +#endif /* ACE_LACKS_WCSTOLL */ +#if defined (ACE_LACKS_WCSTOULL) +# undef ACE_LACKS_WCSTOULL +#endif /* ACE_LACKS_WCSTOULL */ + +#if defined (ACE_HAS_SCTP) && defined (ACE_HAS_LKSCTP) +# define ACE_HAS_VOID_PTR_SCTP_GETLADDRS +# define ACE_HAS_VOID_PTR_SCTP_GETPADDRS +#endif + +#define ACE_HAS_SOLARIS_ATOMIC_LIB + +#endif /* ACE_CONFIG_H */ diff --git a/dep/acelite/ace/config-sunos5.11.h b/dep/acelite/ace/config-sunos5.11.h new file mode 100644 index 00000000000..bbfd91c82fe --- /dev/null +++ b/dep/acelite/ace/config-sunos5.11.h @@ -0,0 +1,15 @@ +/* -*- C++ -*- */ +// $Id: config-sunos5.11.h 80826 2008-03-04 14:51:23Z wotte $ + +// The following configuration file is designed to work for SunOS 5.11 +// (Solaris 11) platforms using the SunC++ 5.x (Sun Studio 10-12), or g++ +// compilers. + +#ifndef ACE_CONFIG_H + +// ACE_CONFIG_H is defined by one of the following #included headers. + +// #include the SunOS 5.10 config, then add any SunOS 5.11 updates below. +#include "ace/config-sunos5.10.h" + +#endif /* ACE_CONFIG_H */ diff --git a/dep/acelite/ace/config-sunos5.4-g++.h b/dep/acelite/ace/config-sunos5.4-g++.h new file mode 100644 index 00000000000..a678389e78d --- /dev/null +++ b/dep/acelite/ace/config-sunos5.4-g++.h @@ -0,0 +1,176 @@ +/* -*- C++ -*- */ +// $Id: config-sunos5.4-g++.h 87268 2009-10-29 21:06:06Z olli $ + +// The following configuration file is designed to work for SunOS 5.4 +// platforms using the GNU g++ compiler. + +#ifndef ACE_CONFIG_H +#define ACE_CONFIG_H +#include /**/ "ace/pre.h" + +#if ! defined (__ACE_INLINE__) +# define __ACE_INLINE__ +#endif /* ! __ACE_INLINE__ */ + +// config-g++-common.h undef's ACE_HAS_STRING_CLASS with -frepo, so +// this must appear before its #include. +#define ACE_HAS_STRING_CLASS + +#include "ace/config-g++-common.h" + +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT + +// Platform supports pread() and pwrite() +#define ACE_HAS_P_READ_WRITE + +#define ACE_HAS_XPG4_MULTIBYTE_CHAR + +// Platform has POSIX terminal interface. +#define ACE_HAS_TERMIOS + +// Platform supports System V IPC (most versions of UNIX, but not Win32) +#define ACE_HAS_SYSV_IPC + +// Sun has the wrong prototype for sendmsg. +#define ACE_HAS_NONCONST_SENDMSG + +// The SunOS 5.x version of rand_r is inconsistent with the header files... +#define ACE_HAS_BROKEN_RANDR + +// Platform supports system configuration information. +#define ACE_HAS_SYS_SYSTEMINFO_H +#define ACE_HAS_SYSV_SYSINFO + +// Platform supports the POSIX regular expression library +#define ACE_HAS_REGEX + +// Platform supports recvmsg and sendmsg. +#define ACE_HAS_MSG + +// Compiler/platform contains the file. +#define ACE_HAS_SYS_SYSCALL_H + +// Compiler/platform correctly calls init()/fini() for shared libraries. +#define ACE_HAS_AUTOMATIC_INIT_FINI + +// Platform supports POSIX O_NONBLOCK semantics. +#define ACE_HAS_POSIX_NONBLOCK + +// Compiler/platform has correctly prototyped header files. +#define ACE_HAS_CPLUSPLUS_HEADERS + +// Compiler/platform supports SunOS high resolution timers. +#define ACE_HAS_HI_RES_TIMER + +// Platform supports IP multicast +#define ACE_HAS_IP_MULTICAST + +// Compiler/platform supports alloca() +// Although ACE does have alloca() on this compiler/platform combination, it is +// disabled by default since it can be dangerous. Uncomment the following line +// if you ACE to use it. +//#define ACE_HAS_ALLOCA + +// Compiler/platform has +#define ACE_HAS_ALLOCA_H + +// Platform contains . +#define ACE_HAS_POLL + +// Platform supports POSIX timers via timestruc_t. +#define ACE_HAS_POSIX_TIME + +// Platform supports the /proc file system. +#define ACE_HAS_PROC_FS + +// Platform supports the prusage_t struct. +#define ACE_HAS_PRUSAGE_T + +// Compiler/platform defines the sig_atomic_t typedef. +#define ACE_HAS_SIG_ATOMIC_T + +// Platform supports SVR4 extended signals. +#define ACE_HAS_SIGINFO_T +#define ACE_HAS_UCONTEXT_T + +// Compiler/platform provides the sockio.h file. +#define ACE_HAS_SYS_SOCKIO_H + +// Compiler supports the ssize_t typedef. +#define ACE_HAS_SSIZE_T + +// Platform supports STREAMS. +#define ACE_HAS_STREAMS + +// Platform supports STREAM pipes. +#define ACE_HAS_STREAM_PIPES + +// Compiler/platform supports struct strbuf. +#define ACE_HAS_STRBUF_T + +// Compiler/platform supports SVR4 dynamic linking semantics. +#define ACE_HAS_SVR4_DYNAMIC_LINKING + +// Compiler/platform supports SVR4 gettimeofday() prototype. +#define ACE_HAS_SVR4_GETTIMEOFDAY + +// Platform lacks pthread_sigaction +#define ACE_LACKS_PTHREAD_THR_SIGSETMASK + +// Compiler/platform supports SVR4 TLI (in particular, T_GETNAME stuff)... +#define ACE_HAS_SVR4_TLI + +// Platform provides header. +#define ACE_HAS_SYS_FILIO_H + +#define ACE_HAS_STRSIGNAL + +/* Turn off the following defines if you want to disable threading. */ +// Compile using multi-thread libraries. +#if !defined (ACE_MT_SAFE) +# define ACE_MT_SAFE 1 +# if !defined (_REENTRANT) +# define _REENTRANT +# endif /* _REENTRANT */ +#endif /* !ACE_MT_SAFE */ + +// Platform supports Solaris threads. +#define ACE_HAS_STHREADS + +// Platform supports threads. +#define ACE_HAS_THREADS + +// Compiler/platform has thread-specific storage +#define ACE_HAS_THREAD_SPECIFIC_STORAGE + +// Platform supports reentrant functions (i.e., all the POSIX *_r functions). +#define ACE_HAS_REENTRANT_FUNCTIONS + +/* end threading defines */ + +#define ACE_HAS_PRIOCNTL +#define ACE_NEEDS_LWP_PRIO_SET + +// Platform supports TLI timod STREAMS module. +#define ACE_HAS_TIMOD_H + +// Platform supports TLI tiuser header. +#define ACE_HAS_TIUSER_H + +// Platform provides TLI function prototypes. +#define ACE_HAS_TLI_PROTOTYPES + +// Platform supports TLI. +#define ACE_HAS_TLI + +// Use the poll() event demultiplexor rather than select(). +//#define ACE_USE_POLL + +// Defines the page size of the system. +#define ACE_PAGE_SIZE 4096 +#define ACE_HAS_IDTYPE_T +#define ACE_HAS_GPERF +#define ACE_HAS_DIRENT + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_H */ diff --git a/dep/acelite/ace/config-sunos5.4-sunc++-4.x.h b/dep/acelite/ace/config-sunos5.4-sunc++-4.x.h new file mode 100644 index 00000000000..d7d0862e328 --- /dev/null +++ b/dep/acelite/ace/config-sunos5.4-sunc++-4.x.h @@ -0,0 +1,186 @@ +/* -*- C++ -*- */ +// $Id: config-sunos5.4-sunc++-4.x.h 87250 2009-10-28 11:57:17Z olli $ + +// The following configuration file is designed to work for SunOS 5.4 +// platforms using the SunC++ 4.0.x compiler. + +#ifndef ACE_CONFIG_H +#define ACE_CONFIG_H +#include /**/ "ace/pre.h" + +#if ! defined (__ACE_INLINE__) +# define __ACE_INLINE__ +#endif /* ! __ACE_INLINE__ */ + +// Optimize ACE_Handle_Set for select(). +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT + +// Platform supports pread() and pwrite() +#define ACE_HAS_P_READ_WRITE + +#define ACE_HAS_XPG4_MULTIBYTE_CHAR + +// Platform supports System V IPC (most versions of UNIX, but not Win32) +#define ACE_HAS_SYSV_IPC + +// Sun has the wrong prototype for sendmsg. +#define ACE_HAS_NONCONST_SENDMSG + +// The SunOS 5.x version of rand_r is inconsistent with the header files... +#define ACE_HAS_BROKEN_RANDR + +// Platform supports system configuration information. +#define ACE_HAS_SYS_SYSTEMINFO_H +#define ACE_HAS_SYSV_SYSINFO + +// Platform supports the POSIX regular expression library. +#define ACE_HAS_REGEX + +// Platform supports recvmsg and sendmsg. +#define ACE_HAS_MSG + +// Compiler/platform contains the file. +#define ACE_HAS_SYS_SYSCALL_H + +// Platform has POSIX terminal interface. +#define ACE_HAS_TERMIOS + +// Compiler/platform correctly calls init()/fini() for shared libraries. +#define ACE_HAS_AUTOMATIC_INIT_FINI + +// Platform supports POSIX O_NONBLOCK semantics. +#define ACE_HAS_POSIX_NONBLOCK + +// Compiler/platform has correctly prototyped header files. +#define ACE_HAS_CPLUSPLUS_HEADERS + +// Compiler/platform supports SunOS high resolution timers. +#define ACE_HAS_HI_RES_TIMER + +// Platform supports IP multicast +#define ACE_HAS_IP_MULTICAST + +// Compiler/platform supports alloca() +// Although ACE does have alloca() on this compiler/platform combination, it is +// disabled by default since it can be dangerous. Uncomment the following line +// if you ACE to use it. +//#define ACE_HAS_ALLOCA + +// Compiler/platform has +#define ACE_HAS_ALLOCA_H + +// Platform contains . +#define ACE_HAS_POLL + +// Platform supports POSIX timers via timestruc_t. +#define ACE_HAS_POSIX_TIME + +// Platform supports the /proc file system. +#define ACE_HAS_PROC_FS + +// Platform supports the prusage_t struct. +#define ACE_HAS_PRUSAGE_T + +// Compiler/platform defines the sig_atomic_t typedef. +#define ACE_HAS_SIG_ATOMIC_T + +// Platform supports SVR4 extended signals. +#define ACE_HAS_SIGINFO_T +#define ACE_HAS_UCONTEXT_T + +// Compiler/platform provides the sockio.h file. +#define ACE_HAS_SYS_SOCKIO_H + +// Compiler supports the ssize_t typedef. +#define ACE_HAS_SSIZE_T + +// Platform supports STREAMS. +#define ACE_HAS_STREAMS + +// Platform supports STREAM pipes. +#define ACE_HAS_STREAM_PIPES + +// Compiler/platform supports struct strbuf. +#define ACE_HAS_STRBUF_T + +// Compiler/platform supports SVR4 dynamic linking semantics. +#define ACE_HAS_SVR4_DYNAMIC_LINKING + +// Compiler/platform supports SVR4 gettimeofday() prototype. +#define ACE_HAS_SVR4_GETTIMEOFDAY + +// Compiler/platform supports SVR4 signal typedef. +#define ACE_HAS_SVR4_SIGNAL_T + +// Platform lacks pthread_sigaction +#define ACE_LACKS_PTHREAD_THR_SIGSETMASK + +// Compiler/platform supports SVR4 ACE_TLI (in particular, T_GETNAME stuff)... +#define ACE_HAS_SVR4_TLI + +// Platform provides header. +#define ACE_HAS_SYS_FILIO_H + +#define ACE_HAS_STRSIGNAL + +/* Turn off the following defines if you want to disable threading. */ +// Compile using multi-thread libraries. +#if !defined (ACE_MT_SAFE) +# define ACE_MT_SAFE 1 +#endif + +// Platform supports Solaris threads. +#define ACE_HAS_STHREADS + +// Platform supports threads. +#define ACE_HAS_THREADS + +// Compiler/platform has thread-specific storage +#define ACE_HAS_THREAD_SPECIFIC_STORAGE + +// Platform supports reentrant functions (i.e., all the POSIX *_r functions). +#define ACE_HAS_REENTRANT_FUNCTIONS + +/* end threading defines */ + +#define ACE_HAS_PRIOCNTL +#define ACE_NEEDS_LWP_PRIO_SET + +// Reactor detects deadlock +// #define ACE_REACTOR_HAS_DEADLOCK_DETECTION + +// Platform supports ACE_TLI timod STREAMS module. +#define ACE_HAS_TIMOD_H + +// Platform supports ACE_TLI tiuser header. +#define ACE_HAS_TIUSER_H + +// Platform provides ACE_TLI function prototypes. +#define ACE_HAS_TLI_PROTOTYPES + +// Platform supports ACE_TLI. +#define ACE_HAS_TLI + +#define ACE_LACKS_LINEBUFFERED_STREAMBUF +#define ACE_LACKS_SIGNED_CHAR + +// Use the poll() event demultiplexor rather than select(). +//#define ACE_USE_POLL + +#define ACE_NEEDS_DEV_IO_CONVERSION + +// Defines the page size of the system. +#define ACE_PAGE_SIZE 4096 +#define ACE_HAS_IDTYPE_T + +#define ACE_HAS_GPERF +#define ACE_HAS_DIRENT + +# if defined (ACE_HAS_EXCEPTIONS) + // If exceptions are enabled and we are using Sun/CC then + // throws an exception instead of returning 0. +# define ACE_NEW_THROWS_EXCEPTIONS +# endif /* ACE_HAS_EXCEPTIONS */ + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_H */ diff --git a/dep/acelite/ace/config-sunos5.5.h b/dep/acelite/ace/config-sunos5.5.h new file mode 100644 index 00000000000..f16b50394bd --- /dev/null +++ b/dep/acelite/ace/config-sunos5.5.h @@ -0,0 +1,432 @@ +/* -*- C++ -*- */ +// $Id: config-sunos5.5.h 89494 2010-03-15 20:11:18Z olli $ + +// This configuration file is designed to work for SunOS 5.5 platforms +// using the following compilers: +// * Sun C++ 4.2 and later (including 5.x), patched as noted below +// * g++ 2.7.2 and later, including egcs +// * Green Hills 1.8.8 and later + +#ifndef ACE_CONFIG_H +#define ACE_CONFIG_H +#include /**/ "ace/pre.h" + +#define ACE_LACKS_STDINT_H + +// alphasort() is present on earlier Solaris versions but is marked as not for +// use on non-BSD systems and not supported for use in applications that use +// system libraries or with multiple threads. So it's mostly useless. +#define ACE_LACKS_ALPHASORT + +// Solaris doesn't support log2() +#define ACE_LACKS_LOG2 + +// SunOS 5.5 does not provide getloadavg() +#define ACE_LACKS_GETLOADAVG + +// Some SunOS releases define _POSIX_PTHREAD_SEMANTICS automatically. +// We need to be check if the user has manually defined the macro before +// including . +#if defined (_POSIX_PTHREAD_SEMANTICS) +# define ACE_HAS_POSIX_PTHREAD_SEMANTICS +#endif /* _POSIX_PTHREAD_SEMANTICS */ + +// Before we do anything, we should include to +// ensure that things are set up properly. +#include + +// Some SunOS releases define _POSIX_PTHREAD_SEMANTICS automatically. +// We need to undef if the macro is set and not defined by the user. +#if defined (_POSIX_PTHREAD_SEMANTICS) && \ + !defined (ACE_HAS_POSIX_PTHREAD_SEMANTICS) +# undef _POSIX_PTHREAD_SEMANTICS +#endif /* _POSIX_PTHREAD_SEMANTICS && !ACE_HAS_POSIX_PTHREAD_SEMANTICS */ + +// Sun has the posix defines so let this file sort out what Sun delivers +#include "ace/config-posix.h" + +// Compiler version-specific settings: +#if defined (__SUNPRO_CC) +# if (__SUNPRO_CC < 0x410) + // The following might not be necessary, but I can't tell: my build + // with Sun C++ 4.0.1 never completes. +# define ACE_NEEDS_DEV_IO_CONVERSION +# elif (__SUNPRO_CC >= 0x420) +# if (__SUNPRO_CC >= 0x500) + // string.h and memory.h conflict for memchr definitions +# define ACE_LACKS_MEMORY_H + // If -compat=4 is turned on, the old 4.2 settings for iostreams are used, + // but the newer, explicit instantiation is used (above) +# if (__SUNPRO_CC_COMPAT >= 5) +# define ACE_HAS_TEMPLATE_TYPEDEFS +# define ACE_HAS_STANDARD_CPP_LIBRARY 1 +# define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 +# define ACE_HAS_THR_C_DEST +# endif /* __SUNPRO_CC_COMPAT >= 5 */ +# if defined (ACE_HAS_EXCEPTIONS) +# define ACE_HAS_NEW_NOTHROW +# else + // See /opt/SUNWspro_5.0/SC5.0/include/CC/stdcomp.h: +# define _RWSTD_NO_EXCEPTIONS 1 +# endif /* ! ACE_HAS_EXCEPTIONS */ +# elif (__SUNPRO_CC == 0x420) || (__SUNPRO_CC == 0x410) +# define ACE_LACKS_PLACEMENT_OPERATOR_DELETE +# endif /* __SUNPRO_CC >= 0x500 */ +# endif /* __SUNPRO_CC >= 0x420 */ + +# define ACE_CAST_CONST const +# define ACE_HAS_HI_RES_TIMER +# define ACE_HAS_SIG_C_FUNC /* Sun CC 5.0 needs this, 4.2 doesn't mind. */ +# define ACE_HAS_XPG4_MULTIBYTE_CHAR +# define ACE_LACKS_LINEBUFFERED_STREAMBUF +# define ACE_LACKS_SIGNED_CHAR + + // ACE_HAS_EXCEPTIONS precludes -noex in + // include/makeinclude/platform_macros.GNU. But beware, we have + // seen problems with exception handling on multiprocessor + // UltraSparcs: threaded executables core dump when threads exit. + // This problem does not seem to appear on single-processor UltraSparcs. + // And, it is solved with the application of patch + // 104631-02 "C++ 4.2: Jumbo Patch for C++ 4.2 on Solaris SPARC" + // to Sun C++ 4.2. + // To provide optimum performance, ACE_HAS_EXCEPTIONS is disabled by + // default. It can be enabled by adding "exceptions=1" to the "make" + // invocation. See include/makeinclude/platform_sunos5_sunc++.GNU + // for details. + +# if defined (ACE_HAS_EXCEPTIONS) + // If exceptions are enabled and we are using Sun/CC then + // throws an exception instead of returning 0. +# define ACE_NEW_THROWS_EXCEPTIONS +# endif /* ACE_HAS_EXCEPTIONS */ + + /* If you want to disable threading with Sun CC, remove -mt + from your CFLAGS, e.g., using make threads=0. */ + + +// Take advantage of Sun Studio 8 (Sun C++ 5.5) or better symbol +// visibility to generate improved shared library binaries. +# if (__SUNPRO_CC > 0x540) + +# if defined (ACE_HAS_CUSTOM_EXPORT_MACROS) && ACE_HAS_CUSTOM_EXPORT_MACROS == 0 +# undef ACE_HAS_CUSTOM_EXPORT_MACROS +# else +# ifndef ACE_HAS_CUSTOM_EXPORT_MACROS +# define ACE_HAS_CUSTOM_EXPORT_MACROS +# endif /* !ACE_HAS_CUSTOM_EXPORT_MACROS */ +# define ACE_Proper_Export_Flag __symbolic +# define ACE_Proper_Import_Flag __global + +# define ACE_EXPORT_SINGLETON_DECLARATION(T) template class ACE_Proper_Export_Flag T +# define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) template class ACE_Proper_Export_Flag SINGLETON_TYPE ; + +// # define ACE_IMPORT_SINGLETON_DECLARATION(T) extern template class T +// # define ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) extern template class SINGLETON_TYPE; + +# endif /* ACE_HAS_CUSTOM_EXPORT_MACROS == 0 */ +# endif /* __SUNPRO_CC > 0x540 (> Sun C++ 5.4) */ + +#elif defined (__GNUG__) + // config-g++-common.h undef's ACE_HAS_STRING_CLASS with -frepo, so + // this must appear before its #include. +# define ACE_HAS_STRING_CLASS + +# include "ace/config-g++-common.h" + +# define ACE_HAS_HI_RES_TIMER +# define ACE_HAS_XPG4_MULTIBYTE_CHAR + +# if !defined (ACE_MT_SAFE) || ACE_MT_SAFE != 0 + // ACE_MT_SAFE is #defined below, for all compilers. +# if !defined (_REENTRANT) + /* If you want to disable threading, comment out the following + line. Or, add -DACE_MT_SAFE=0 to your CFLAGS, e.g., using + make threads=0. */ +# define _REENTRANT +# endif /* _REENTRANT */ +# endif /* !ACE_MT_SAFE */ + +#elif defined (ghs) + +# if !defined (ACE_MT_SAFE) || ACE_MT_SAFE != 0 + // ACE_MT_SAFE is #defined below, for all compilers. +# if !defined (_REENTRANT) + /* If you want to disable threading, comment out the following + line. Or, add -DACE_MT_SAFE=0 to your CFLAGS, e.g., using + make threads=0. */ +# define _REENTRANT +# endif /* _REENTRANT */ +# endif /* !ACE_MT_SAFE */ + +# define ACE_CONFIG_INCLUDE_GHS_COMMON +# include "ace/config-ghs-common.h" + + // To avoid warning about inconsistent declaration between Sun's + // stdlib.h and Green Hills' ctype.h. +# include + + // IOStream_Test never halts with Green Hills 1.8.9. +# define ACE_LACKS_ACE_IOSTREAM + +#else /* ! __SUNPRO_CC && ! __GNUG__ && ! ghs */ +# ifdef __cplusplus /* Let it slide for C compilers. */ +# error unsupported compiler in ace/config-sunos5.5.h +# endif /* __cplusplus */ +#endif /* ! __SUNPRO_CC && ! __GNUG__ && ! ghs */ + +#if !defined (__ACE_INLINE__) +// @note If you have link problems with undefined inline template +// functions with Sun C++, be sure that the #define of __ACE_INLINE__ +// below is not commented out. +# define __ACE_INLINE__ +#endif /* ! __ACE_INLINE__ */ + +// Platform supports the POSIX regular expression library. +// @note Please comment out the ACE_HAS_REGEX #define if you +// have link problems with g++ or egcs on SunOS 5.5. +#define ACE_HAS_REGEX + +// Optimize ACE_Handle_Set for select(). +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT + +// select()'s timeval arg is not declared as const and may be modified +#define ACE_HAS_NONCONST_SELECT_TIMEVAL + +// Platform supports pread() and pwrite() +#define ACE_HAS_P_READ_WRITE +#define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS +#define ACE_HAS_UALARM +#define ACE_LACKS_UALARM_PROTOTYPE + +// Platform supports System V IPC (most versions of UNIX, but not Win32) +#define ACE_HAS_SYSV_IPC + +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES + +// Platform supports system configuration information. +#define ACE_HAS_SYS_SYSTEMINFO_H +#define ACE_HAS_SYSV_SYSINFO + +// Platform supports recvmsg and sendmsg. +#define ACE_HAS_MSG + +// Compiler/platform contains the file. +#define ACE_HAS_SYS_SYSCALL_H + +// Platform has POSIX terminal interface. +#define ACE_HAS_TERMIOS + +// Compiler/platform correctly calls init()/fini() for shared libraries. +#define ACE_HAS_AUTOMATIC_INIT_FINI + +// Platform supports POSIX O_NONBLOCK semantics. +#define ACE_HAS_POSIX_NONBLOCK + +// Compiler/platform has correctly prototyped header files. +#define ACE_HAS_CPLUSPLUS_HEADERS + +// Platform supports IP multicast +#define ACE_HAS_IP_MULTICAST + +// This setting was determined by running the autoconf tests. If it doesn't +// work uniformly, will need some tweaking, possibly based on other +// XPG feature-test macros. +#define ACE_HAS_CONST_CHAR_SWAB + +// Compiler/platform supports alloca() +// Although ACE does have alloca() on this compiler/platform combination, it is +// disabled by default since it can be dangerous. Uncomment the following line +// if you ACE to use it. +//#define ACE_HAS_ALLOCA + +// Compiler/platform has +#define ACE_HAS_ALLOCA_H + +// Platform contains . +#define ACE_HAS_POLL + +// Platform supports POSIX timers via timestruc_t. +#define ACE_HAS_POSIX_TIME + +// ACE_HAS_CLOCK_GETTIME requires linking with -lposix4. +#define ACE_HAS_CLOCK_GETTIME +#define ACE_HAS_CLOCK_SETTIME + +// Platform supports the /proc file system. +#define ACE_HAS_PROC_FS + +// Platform supports the prusage_t struct. +#define ACE_HAS_PRUSAGE_T +#define ACE_HAS_GETRUSAGE + +// Compiler/platform defines the sig_atomic_t typedef. +#define ACE_HAS_SIG_ATOMIC_T + +// Platform supports SVR4 extended signals. +#define ACE_HAS_SIGINFO_T +#define ACE_HAS_UCONTEXT_T + +// Compiler/platform provides the sockio.h file. +#define ACE_HAS_SYS_SOCKIO_H + +// Compiler supports the ssize_t typedef. +#define ACE_HAS_SSIZE_T + +// Platform supports STREAMS. +#define ACE_HAS_STREAMS + +// Platform supports STREAM pipes. +#define ACE_HAS_STREAM_PIPES + +// Compiler/platform supports struct strbuf. +#define ACE_HAS_STRBUF_T + +// Compiler/platform supports SVR4 dynamic linking semantics. +#define ACE_HAS_SVR4_DYNAMIC_LINKING + +// Compiler/platform supports SVR4 gettimeofday() prototype. +#define ACE_HAS_SVR4_GETTIMEOFDAY + +// Compiler/platform supports SVR4 ACE_TLI (in particular, T_GETNAME stuff)... +#define ACE_HAS_SVR4_TLI + +// Platform provides header. +#define ACE_HAS_SYS_FILIO_H + +#define ACE_HAS_STRSIGNAL + +// SunOS 5.5.x does not support mkstemp +#define ACE_LACKS_MKSTEMP +#define ACE_LACKS_SYS_SYSCTL_H + +#if !(defined(_XOPEN_SOURCE) && (_XOPEN_VERSION - 0 >= 4)) +# define ACE_HAS_CHARPTR_SHMDT +#endif + +// Platform has posix getpwnam_r +#if (defined (_POSIX_C_SOURCE) && _POSIX_C_SOURCE - 0 >= 199506L) || \ + defined(_POSIX_PTHREAD_SEMANTICS) +# define ACE_HAS_POSIX_GETPWNAM_R +#endif /* _POSIX_C_SOURCE || _POSIX_PTHREAD_SEMANTICS */ + +#if !defined (ACE_MT_SAFE) || (ACE_MT_SAFE == 1) +#if defined (_REENTRANT) || \ + (defined (_POSIX_C_SOURCE) && (_POSIX_C_SOURCE - 0 >= 199506L)) || \ + defined (_POSIX_PTHREAD_SEMANTICS) + // Compile using multi-thread libraries. +# define ACE_HAS_THREADS + +# if !defined (ACE_MT_SAFE) +# define ACE_MT_SAFE 1 +# endif /* ACE_MT_SAFE */ + + // Platform supports POSIX pthreads *and* Solaris threads, by + // default! If you only want to use POSIX pthreads, add + // -D_POSIX_PTHREAD_SEMANTICS to your CFLAGS. Or, #define it right + // here. See the Intro (3) man page for information on + // -D_POSIX_PTHREAD_SEMANTICS. +# if defined (_POSIX_PTHREAD_SEMANTICS) +# define ACE_LACKS_RWLOCK_T +# else +# define ACE_HAS_STHREADS +# endif /* ! _POSIX_PTHREAD_SEMANTICS */ + +# define ACE_HAS_PTHREADS + // . . . but only supports SCHED_OTHER scheduling policy +# define ACE_HAS_ONLY_SCHED_OTHER +# define ACE_HAS_SIGWAIT +# define ACE_HAS_SIGTIMEDWAIT +# define ACE_HAS_SIGSUSPEND +# define ACE_LACKS_PTHREAD_ATTR_SETSTACK + + // Compiler/platform has thread-specific storage +# define ACE_HAS_THREAD_SPECIFIC_STORAGE + + // Platform supports reentrant functions (i.e., all the POSIX *_r functions). +# define ACE_HAS_REENTRANT_FUNCTIONS + +# define ACE_NEEDS_LWP_PRIO_SET +# define ACE_HAS_THR_YIELD +# define ACE_LACKS_PTHREAD_YIELD +#endif /* _REENTRANT || _POSIX_C_SOURCE >= 199506L || \ + _POSIX_PTHREAD_SEMANTICS */ +#endif /* !ACE_MT_SAFE || ACE_MT_SAFE == 1 */ + +#define ACE_HAS_PRIOCNTL + +// Platform supports ACE_TLI timod STREAMS module. +#define ACE_HAS_TIMOD_H + +// Platform supports ACE_TLI tiuser header. +#define ACE_HAS_TIUSER_H + +// Platform provides ACE_TLI function prototypes. +#define ACE_HAS_TLI_PROTOTYPES + +// Platform has broken t_error() prototype. +#define ACE_HAS_BROKEN_T_ERROR + +// Platform supports ACE_TLI. +#define ACE_HAS_TLI + +#define ACE_HAS_GETPAGESIZE 1 + +#define ACE_HAS_IDTYPE_T + +#define ACE_HAS_GPERF +#define ACE_HAS_DIRENT + +#define ACE_LACKS_ISCTYPE +#define ACE_LACKS_ISBLANK + +#if defined (__SUNPRO_CC) +# define ACE_CC_NAME ACE_TEXT ("SunPro C++") +# define ACE_CC_MAJOR_VERSION (__SUNPRO_CC >> 8) +# define ACE_CC_MINOR_VERSION (__SUNPRO_CC & 0x00ff) +# define ACE_CC_BETA_VERSION (0) +#elif defined (__GNUG__) +# define ACE_CC_MAJOR_VERSION __GNUC__ +# define ACE_CC_MINOR_VERSION __GNUC_MINOR__ +# define ACE_CC_BETA_VERSION (0) +# if __GNUC_MINOR__ >= 90 +# define ACE_CC_NAME ACE_TEXT ("egcs") +# else +# define ACE_CC_NAME ACE_TEXT ("g++") +# endif /* __GNUC_MINOR__ */ +#endif /* __GNUG__ */ + +#if defined (i386) && (_FILE_OFFSET_BITS==32) +# define ACE_HAS_X86_STAT_MACROS +#endif /* i386 && _FILE_OFFSET_BITS==32 */ + +#define ACE_MALLOC_ALIGN ((size_t)8) +#define ACE_LACKS_SETREUID_PROTOTYPE +#define ACE_LACKS_SETREGID_PROTOTYPE + +// Solaris does indeed implement the inet_aton() function, but it is +// found in `libresolv.*'. It doesn't seem worth it to link another +// library just for that function. Just use the emulation in ACE that +// has been used for years. +#define ACE_LACKS_INET_ATON + +// Solaris doesn't have wcstoull +#define ACE_LACKS_WCSTOLL +#define ACE_LACKS_WCSTOULL + +#if defined (_LARGEFILE_SOURCE) || (_FILE_OFFSET_BITS==64) +#undef ACE_HAS_PROC_FS +#undef ACE_HAS_PRUSAGE_T +#endif /* (_LARGEFILE_SOURCE) || (_FILE_OFFSET_BITS==64) */ + +#if defined (_POSIX_PTHREAD_SEMANTICS) || (_FILE_OFFSET_BITS == 64) || (_POSIX_C_SOURCE - 0 >= 199506L) +# define ACE_HAS_3_PARAM_READDIR_R +#endif + +// Sum of the iov_len values can't be larger then SSIZE_MAX +#define ACE_HAS_SOCK_BUF_SIZE_MAX + +#define ACE_LACKS_SETENV +#define ACE_LACKS_UNSETENV + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_H */ diff --git a/dep/acelite/ace/config-sunos5.6.h b/dep/acelite/ace/config-sunos5.6.h new file mode 100644 index 00000000000..d100627a212 --- /dev/null +++ b/dep/acelite/ace/config-sunos5.6.h @@ -0,0 +1,126 @@ +/* -*- C++ -*- */ +// $Id: config-sunos5.6.h 81935 2008-06-12 22:01:53Z jtc $ + +// The following configuration file is designed to work for SunOS 5.6 +// platforms using the SunC++ 4.x or g++ compilers. + +#ifndef ACE_CONFIG_H + +// ACE_CONFIG_H is defined by one of the following #included headers. + +// #include the SunOS 5.5 config file, then add SunOS 5.6 updates below. + +#include "ace/config-sunos5.5.h" + +#if (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE > 2) || \ + defined (__EXTENSIONS__) +// The asctime_r/ctime_r parameters change at POSIX.1c-1995 +# if (defined (_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199506L) +# define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R +# endif /* POSIX_C_SOURCE >= 199506L */ +# define ACE_HAS_SIGWAIT +// Hack 'cuz _POSIX_C_SOURCE > 2 and -DEXTENSIONS hides this. +# define ACE_LACKS_MADVISE_PROTOTYPE +#endif /* _POSIX_C_SOURCE > 2 || __EXTENSIONS__ */ + +// Support for the SunC++ 5.2 compiler. +// Do not undefine for compat mode < 5 +#if defined (__SUNPRO_CC) && __SUNPRO_CC > 0x510 +#if defined (__SUNPRO_CC_COMPAT) && (__SUNPRO_CC_COMPAT >= 5) +#ifdef ACE_LACKS_ACE_IOSTREAM +#undef ACE_LACKS_ACE_IOSTREAM +#endif /* ACE_LACKS_ACE_IOSTREAM */ +#endif /* defined (__SUNPRO_CC_COMPAT) && (__SUNPRO_CC_COMPAT >= 5) */ + +#ifndef ACE_LACKS_UNBUFFERED_STREAMBUF +#define ACE_LACKS_UNBUFFERED_STREAMBUF 1 +#endif /* ACE_LACKS_UNBUFFERED_STREAMBUF */ +#ifndef ACE_TEMPLATES_REQUIRE_SOURCE +#define ACE_TEMPLATES_REQUIRE_SOURCE 1 +#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ +#ifndef ACE_HAS_TEMPLATE_TYPEDEFS +#define ACE_HAS_TEMPLATE_TYPEDEFS 1 +#endif /* ACE_HAS_TEMPLATE_TYPEDEFS */ +// Forte 7 seems to botch this one... +#if __SUNPRO_CC == 0x540 +#undef ACE_HAS_TEMPLATE_TYPEDEFS +#endif +#ifndef ACE_HAS_THR_C_DEST +#define ACE_HAS_THR_C_DEST 1 +#endif /* ACE_HAS_THR_C_DEST */ +#ifndef ACE_HAS_THR_C_FUNC +#define ACE_HAS_THR_C_FUNC 1 +#endif /* ACE_HAS_THR_C_FUNC */ +#ifndef ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES 1 +#endif /* ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES */ +#ifndef ACE_HAS_SIG_C_FUNC +#define ACE_HAS_SIG_C_FUNC 1 +#endif /* ACE_HAS_SIG_C_FUNC */ +#ifndef ACE_HAS_STDCPP_STL_INCLUDES +#define ACE_HAS_STDCPP_STL_INCLUDES 1 +#endif /* ACE_HAS_STDCPP_STL_INCLUDES */ +#ifndef ACE_HAS_STRING_CLASS +#define ACE_HAS_STRING_CLASS 1 +#endif /* ACE_HAS_STRING_CLASS */ +#ifndef ACE_HAS_STANDARD_CPP_LIBRARY +#define ACE_HAS_STANDARD_CPP_LIBRARY 1 +#endif /* ACE_HAS_STANDARD_CPP_LIBRARY */ +#ifndef ACE_HAS_STDCPP_STL_INCLUDES +#define ACE_HAS_STDCPP_STL_INCLUDES 1 +#endif /* ACE_HAS_STDCPP_STL_INCLUDES */ +#ifndef ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB +#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 +#endif /* ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB */ +#ifndef ACE_LACKS_IOSTREAM_FX +#define ACE_LACKS_IOSTREAM_FX 1 +#endif /* ACE_LACKS_IOSTREAM_FX */ +#ifndef ACE_LACKS_LINEBUFFERED_STREAMBUF +#define ACE_LACKS_LINEBUFFERED_STREAMBUF 1 +#endif /* ACE_LACKS_LINEBUFFERED_STREAMBUF */ + +#endif /* defined (__SUNPRO_CC) && __SUNPRO_CC > 0x510 */ + +// SunOS 5.6 and above support mkstemp +#undef ACE_LACKS_MKSTEMP + + +// SunOS 5.6 has AIO calls. +#if !defined (ACE_HAS_AIO_CALLS) +#define ACE_HAS_AIO_CALLS +#endif /* ACE_HAS_AIO_CALLS */ + +#if !defined (ACE_HAS_POSIX_REALTIME_SIGNALS) +#define ACE_HAS_POSIX_REALTIME_SIGNALS +#endif /* ACE_HAS_POSIX_REALTIME_SIGNALS */ + +#if !defined (ACE_HAS_POSIX_MESSAGE_PASSING) +#define ACE_HAS_POSIX_MESSAGE_PASSING +#endif /* ACE_HAS_POSIX_MESSAGE_PASSING */ + +#if !defined (ACE_HAS_POSIX_SEM) +#define ACE_HAS_POSIX_SEM +#endif /* ACE_HAS_POSIX_SEM */ + +// Sunos 5.6's aio_* with RT signals is broken. +#if !defined (ACE_POSIX_AIOCB_PROACTOR) +#define ACE_POSIX_AIOCB_PROACTOR +#endif /* ACE_POSIX_AIOCB_PROACTOR */ + +// SunOS 5.6 has a buggy select +#define ACE_HAS_LIMITED_SELECT + +// SunOS 5.6 introduced shm_open, but need to turn on POSIX.1b or higher +// to pick it up. +#if defined (_POSIX_C_SOURCE) && (_POSIX_C_SOURCE > 2) +# define ACE_HAS_SHM_OPEN +#else +# undef ACE_HAS_SHM_OPEN +#endif /* _POSIX_C_SOURCE > 2 */ + +// The struct msghdr is conditional on SunOS 5.6 based on _XPG4_2 +#if defined(_XPG4_2) +# define ACE_HAS_4_4BSD_SENDMSG_RECVMSG +#endif /* _XPG4_2 */ + +#endif /* ACE_CONFIG_H */ diff --git a/dep/acelite/ace/config-sunos5.7.h b/dep/acelite/ace/config-sunos5.7.h new file mode 100644 index 00000000000..60e1d993a13 --- /dev/null +++ b/dep/acelite/ace/config-sunos5.7.h @@ -0,0 +1,78 @@ +/* -*- C++ -*- */ +// $Id: config-sunos5.7.h 80826 2008-03-04 14:51:23Z wotte $ + +// The following configuration file is designed to work for SunOS 5.7 +// (Solaris 7) platforms using the SunC++ 4.x, 5.x, or g++ compilers. + +#ifndef ACE_CONFIG_H + +// ACE_CONFIG_H is defined by one of the following #included headers. + +// #include the SunOS 5.6 config file, then add SunOS 5.7 updates below. + +#include "ace/config-sunos5.6.h" + +// This may be true for earlier Solaris versions, but I can only verify +// it for Solaris 7 and later. +#define ACE_HAS_VFWPRINTF +#if defined (ACE_HAS_SHM_OPEN) +# define ACE_SHM_OPEN_REQUIRES_ONE_SLASH +#endif + +// Sun began distributing with SunOS 5.7 +#define ACE_HAS_SYS_LOADAVG_H + +// SunOS 5.7 has getloadavg() +#undef ACE_LACKS_GETLOADAVG + +#if defined (ghs) + // SunOS 5.7's /usr/include/sys/procfs_isa.h needs uint64_t, + // but /usr/include/sys/int_types.h doesn't #define it because + // _NO_LONGLONG is # +# undef ACE_HAS_PROC_FS +# undef ACE_HAS_PRUSAGE_T + +#elif defined (__SUNPRO_CC) && (__SUNPRO_CC <= 0x530) + // Wide character methods are in std:: when using SunCC 5.3 +# define ACE_WCHAR_IN_STD_NAMESPACE +#endif /* __GNUG__ || ghs */ + +// SunOS 5.7 supports SCHED_FIFO and SCHED_RR, as well as SCHED_OTHER. +#undef ACE_HAS_ONLY_SCHED_OTHER + +// SunOS 5.7 gets this right . . . +#undef ACE_HAS_BROKEN_T_ERROR + +// And doesn't need to set LWP priorities, as shown by +// performance-tests/Misc/preempt. +#undef ACE_NEEDS_LWP_PRIO_SET + +// SunOS 5.7 can support Real-Time Signals and POSIX4 AIO operations +// are supported. + +#if !defined (ACE_HAS_AIO_CALLS) +#define ACE_HAS_AIO_CALLS +#endif /* !ACE_HAS_AIO_CALLS */ + +#ifdef ACE_HAS_LIMITED_SELECT +#undef ACE_HAS_LIMITED_SELECT +#endif /* ACE_HAS_LIMITED_SELECT */ + +// SunOS 5.7 has socklen_t +#define ACE_HAS_SOCKLEN_T + +#if defined (__sparcv9) +#define _LP64 +#define ACE_SIZEOF_LONG 8 /* Needed to circumvent compiler bug #4294969 */ +#endif /* __sparcv9 */ + +#if (defined(_XOPEN_SOURCE) && (_XOPEN_VERSION - 0 == 4)) /* XPG4 or XPG4v2 */ +// 2 parameter wcstok() +#else /* XPG4 or XPG4v2 */ +# define ACE_HAS_3_PARAM_WCSTOK +#endif + +// Solaris 7 started to support /dev/poll +#define ACE_HAS_DEV_POLL + +#endif /* ACE_CONFIG_H */ diff --git a/dep/acelite/ace/config-sunos5.8.h b/dep/acelite/ace/config-sunos5.8.h new file mode 100644 index 00000000000..eb83e91490b --- /dev/null +++ b/dep/acelite/ace/config-sunos5.8.h @@ -0,0 +1,39 @@ +/* -*- C++ -*- */ +// $Id: config-sunos5.8.h 80826 2008-03-04 14:51:23Z wotte $ + +// The following configuration file is designed to work for SunOS 5.8 +// (Solaris 8) platforms using the SunC++ 4.x, 5.x, 6.x, or g++ compilers. + +#ifndef ACE_CONFIG_H + +// ACE_CONFIG_H is defined by one of the following #included headers. + +// #include the SunOS 5.7 config, then add any SunOS 5.8 updates below. +#include "ace/config-sunos5.7.h" + +#undef ACE_WCHAR_IN_STD_NAMESPACE + +// This may be true for versions prior to Solaris 8 as well, but I don't +// have any to try it on. +#if !defined (ACE_HAS_TIMEZONE) +# define ACE_HAS_TIMEZONE +#endif + +// The range of thread priorities for 5.8 differs from 5.7 in the +// minimum priority for the SCHED_OTHER policy (i.e., +// ACE_THR_PRI_OTHER_MIN) +# define ACE_THR_PRI_OTHER_MIN (long) -20 + +# if defined (_POSIX_PTHREAD_SEMANTICS) +# ifdef ACE_LACKS_RWLOCK_T +# undef ACE_LACKS_RWLOCK_T +# endif /* ACE_LACKS_RWLOCK_T */ +# endif /* _POSIX_PTHREAD_SEMANTICS */ + +// This is no longer the case for Sun 5.9 onwards +# undef ACE_HAS_X86_STAT_MACROS + +// gethostbyaddr does not handle IPv6-mapped-IPv4 addresses +#define ACE_HAS_BROKEN_GETHOSTBYADDR_V4MAPPED + +#endif /* ACE_CONFIG_H */ diff --git a/dep/acelite/ace/config-sunos5.9.h b/dep/acelite/ace/config-sunos5.9.h new file mode 100644 index 00000000000..b8d09447eb2 --- /dev/null +++ b/dep/acelite/ace/config-sunos5.9.h @@ -0,0 +1,18 @@ +/* -*- C++ -*- */ +// $Id: config-sunos5.9.h 84213 2009-01-22 15:45:13Z johnnyw $ + +// The following configuration file is designed to work for SunOS 5.9 +// (Solaris 9) platforms using the SunC++ 5.x (Forte 6 and 7), or g++ +// compilers. + +#ifndef ACE_CONFIG_H + +// ACE_CONFIG_H is defined by one of the following #included headers. + +// #include the SunOS 5.8 config, then add any SunOS 5.9 updates below. +#include "ace/config-sunos5.8.h" + +#define ACE_HAS_SENDFILE 1 +#define ACE_LACKS_THR_CONCURRENCY_FUNCS + +#endif /* ACE_CONFIG_H */ diff --git a/dep/acelite/ace/config-tandem-nsk-mips-v2.h b/dep/acelite/ace/config-tandem-nsk-mips-v2.h new file mode 100644 index 00000000000..61747272087 --- /dev/null +++ b/dep/acelite/ace/config-tandem-nsk-mips-v2.h @@ -0,0 +1,394 @@ +// -*- C++ -*- +// +// $Id: config-tandem-nsk-mips-v2.h 87167 2009-10-19 19:33:53Z olli $ + +#ifndef ACE_CONFIG_NSK_H +#define ACE_CONFIG_NSK_H + +#include /**/ "ace/pre.h" + +// The following configuration file contains defines for Tandem NSK +// platform, MIPS processor, version 2 C++ compiler. + + +//========================================================================= +// Tandem NSK specific parts +//========================================================================= + + +// Disable pthread renaming of symbols such as "open" and "close" +#define _CMA_NOWRAPPERS_ 1 + +// Get Handle_Set.cpp to generate correct bit operations for NSK platform +#define ACE_TANDEM_NSK_BIT_ORDER + +// Use facilities provided by T1248 version of pthreads. +// (If not defined, will use old version of pthreads.) +#define ACE_TANDEM_T1248_PTHREADS + +// Use all available T1248 thread aware wrapper functions for providing +// non-blocking I/O. +// [@note this causes a significant performance degradation] +//#define ACE_TANDEM_T1248_PTHREADS_ALL_IO_WRAPPERS + + +// Need this include here because some symbols defined by pthreads +// (e.g. timespec_t) are needed before spthread.h is normally included +// by ACE +#ifdef ACE_TANDEM_T1248_PTHREADS +#include +#else +#include "pthread.h" +#include "dce/cma_dispatch_coop.h" +#endif + +// The following #defines are hacks to get around things +// that seem to be missing or different in Tandem land +#define NSIG 32 // missing from Signal.h + // note: on nsk TNS/R there is room in + // sigset_t for 128 signals but those + // above 31 are not valid. +#define MAXNAMLEN 248 // missing from dirent.h +#define ERRMAX 4218 // from errno.h + +// Following seems to be missing from G06.20 version of standard +// pthreads includes (it appeared in older version of standard pthreads) +// (SCHED_FIFO (aka cma_c_sched_fifo) used in Dynamic_Priority_Test) +#ifdef ACE_TANDEM_T1248_PTHREADS +typedef enum CMA_T_SCHED_POLICY { + cma_c_sched_fifo = 0, + cma_c_sched_rr = 1, + cma_c_sched_throughput = 2, + cma_c_sched_background = 3, + cma_c_sched_ada_low = 4 + } cma_t_sched_policy; +#endif + +// T1248 doesn't define these constants. They're defined in spt/cma.h +// (formerly dce/cma.h), but this header is not included or provided +// by T1248 G07-AAL. +#define cma_c_prio_fifo_min 16 +#define cma_c_prio_fifo_mid 24 +#define cma_c_prio_fifo_max 31 +#define cma_c_prio_rr_min 16 +#define cma_c_prio_rr_mid 24 +#define cma_c_prio_rr_max 31 +#define cma_c_prio_through_min 8 +#define cma_c_prio_through_mid 12 +#define cma_c_prio_through_max 15 +#define cma_c_prio_back_min 1 +#define cma_c_prio_back_mid 4 +#define cma_c_prio_back_max 7 + +// Enable NSK Pluggable Protocols +#define TAO_HAS_NSKPW 1 +#define TAO_HAS_NSKFS 1 + +//========================================================================= +// Platform specific parts +//========================================================================= + +// Platform lacks getpwnam_r() methods (e.g., SGI 6.2). +#define ACE_LACKS_PWD_REENTRANT_FUNCTIONS + +// Platform/compiler lacks {get,set}rlimit() function +#define ACE_LACKS_RLIMIT + +// The platform doesn't have mmap(2) +#define ACE_LACKS_MMAP + +// Platform lacks streambuf "linebuffered ()". [C++ iostream] +#define ACE_LACKS_LINEBUFFERED_STREAMBUF + +// Platform supports recvmsg and sendmsg +#define ACE_HAS_MSG + +// Platform defines ACE_HAS_MSG, but lacks msg_accrights{,len}. +#define ACE_LACKS_MSG_ACCRIGHTS + +// Platform supports sigsuspend() +#define ACE_HAS_SIGSUSPEND + +// Platform/compiler has the sigwait(2) prototype +#define ACE_HAS_SIGWAIT + +// Compiler/platform defines the sig_atomic_t typedef +#define ACE_HAS_SIG_ATOMIC_T + +// OS/compiler uses size_t * rather than int * for socket lengths +#define ACE_HAS_SIZET_SOCKET_LEN + +// OS/compiler uses void * arg 4 setsockopt() rather than const char * +#define ACE_HAS_VOIDPTR_SOCKOPT + +// The platform doesn't have mprotect(2) +#define ACE_LACKS_MPROTECT + +// Platform lacks msync() +#define ACE_LACKS_MSYNC + +// Platform does not support reentrant netdb functions (getprotobyname_r, +// getprotobynumber_r, gethostbyaddr_r, gethostbyname_r, getservbyname_r). +#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS Platform does not support + +// Platform lacks madvise() +#define ACE_LACKS_MADVISE + +// Platform lacks pri_t +#define ACE_LACKS_PRI_T + +// Platform lacks a working sbrk() +#define ACE_LACKS_SBRK + +// Platform doesn't have syscall() prototype +#define ACE_LACKS_SYSCALL + +// Platform lacks the inet_aton() function. +#define ACE_LACKS_INET_ATON + +// Compiler/platform has Dirent iterator functions +#define ACE_HAS_DIRENT + +// Platform uses ACE_HAS_DIRENT but does not have readdir_r() +#define ACE_LACKS_READDIR_R + +// Platform supports getpagesize() call (otherwise, +// ACE_PAGE_SIZE must be defined) +#define ACE_HAS_GETPAGESIZE + +// Platform supports IP multicast +#define ACE_HAS_IP_MULTICAST + +// Platform's select() uses non-const timeval* +#define ACE_HAS_NONCONST_SELECT_TIMEVAL + +// Platform supports POSIX O_NONBLOCK semantics +#define ACE_HAS_POSIX_NONBLOCK + +// Platform lacks named POSIX semaphores +#define ACE_LACKS_NAMED_POSIX_SEM + +// Platform has support for multi-byte character support compliant +// with the XPG4 Worldwide Portability Interface wide-character +// classification. +#define ACE_HAS_XPG4_MULTIBYTE_CHAR + +// No wcsstr function available for this compiler +#define ACE_LACKS_WCSSTR + +// No wctype.h available for this compiler +#define ACE_LACKS_WCTYPE_H + +// Platform supports the POSIX regular expression library. +// [Note Tandem NSK platform does have regular expresson support but it +// does not follow the assumptions made by ACE. To use it would need +// to make some ACE modifications.] +//#define ACE_HAS_REGEX + +// Platform doesn't have truncate() +#define ACE_LACKS_TRUNCATE + +// Platform lacks readers/writer locks. +#define ACE_LACKS_RWLOCK_T + +// Compiler's 'new' throws exception on failure (ANSI C++ behavior). +#define ACE_NEW_THROWS_EXCEPTIONS + +// Optimize ACE_Handle_Set::count_bits for select() operations (common +// case) +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT + +// Platform lacks setreuid() +#define ACE_LACKS_SETREUID + +// Platform lacks setregid() +#define ACE_LACKS_SETREGID + +// Compile using multi-thread libraries +#define ACE_MT_SAFE 1 + + + +// Platform supports System V IPC +#define ACE_HAS_SYSV_IPC + +#define ACE_LACKS_SO_SNDBUF +#define ACE_LACKS_SO_RCVBUF + +// Platform lacks the socketpair() call +#define ACE_LACKS_SOCKETPAIR + +// Platform limits the maximum socket message size. +#define ACE_HAS_SOCK_BUF_SIZE_MAX + +// hrtime_t is a basic type that doesn't require ACE_U64_TO_U32 conversion +#define ACE_HRTIME_T_IS_BASIC_TYPE + +// printf format specifiers for 64 bit integers +# define ACE_UINT64_FORMAT_SPECIFIER_ASCII "%Ld" +# define ACE_INT64_FORMAT_SPECIFIER_ASCII "%Ld" + +//========================================================================= +// Threads specific parts +//========================================================================= + +// Platform supports threads +#define ACE_HAS_THREADS + +// Platform supports POSIX Pthreads, of one form or another. This +// macro says the platform has a pthreads variety - should also define +// one of the below to say which one. Also may need some +// ACE_HAS_... thing for extensions. +#define ACE_HAS_PTHREADS + +// Standard pthreads supports only SCHED_FIFO +#define ACE_HAS_ONLY_SCHED_FIFO + +// Compiler/platform has thread-specific storage +#define ACE_HAS_THREAD_SPECIFIC_STORAGE + +// Platform has no implementation of pthread_condattr_setpshared(), +// even though it supports pthreads! +#define ACE_LACKS_CONDATTR_PSHARED + +// pthread_cond_timedwait does *not* reset the time argument when the +// lock is acquired. +#define ACE_LACKS_COND_TIMEDWAIT_RESET + +// Platform lacks pthread_attr_setsched() +#define ACE_LACKS_SETSCHED + +// Platform has pthread_mutexattr_setkind_np(). +#define ACE_HAS_PTHREAD_MUTEXATTR_SETKIND_NP + +// Platform lacks pthread_mutexattr_setpshared(). +#define ACE_LACKS_MUTEXATTR_PSHARED + +// Platform lacks pthread_attr_setscope() +#define ACE_LACKS_THREAD_PROCESS_SCOPING + +// Platform lacks pthread_attr_setstackaddr +#define ACE_LACKS_PTHREAD_ATTR_SETSTACKADDR + +// Defining ACE_HAS_UCONTEXT_T since G06.21 version of spthreads has +// a definition for it. +#ifdef ACE_TANDEM_T1248_PTHREADS +#define ACE_HAS_UCONTEXT_T +#endif + +#define ACE_LACKS_FD_MASK + +//========================================================================= +// Include file characteristics +//========================================================================= + +// Compiler/platform contains the file. +#define ACE_HAS_SYS_SYSCALL_H + +// Platform lacks malloc.h +#define ACE_LACKS_MALLOC_H + +// Platform lacks the siginfo.h include file +#define ACE_LACKS_SIGINFO_H + +// Platform doesn't define struct strrecvfd. +#define ACE_LACKS_STRRECVFD + +// Platform lacks the ucontext.h file +#define ACE_LACKS_UCONTEXT_H + +// Prototypes for both signal() and struct sigaction are consistent. +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES + +// Platform supports the POSIX struct timespec type +#define ACE_HAS_POSIX_TIME + +// Platform/compiler supports timezone * as second parameter to gettimeofday() +#define ACE_HAS_TIMEZONE_GETTIMEOFDAY + +// Platform has (which contains bzero() prototype) +#define ACE_HAS_STRINGS 1 + + +// OS/compiler omits the const from the iovec parameter in the +// writev() prototype. +#define ACE_HAS_NONCONST_WRITEV + +// Platform lacks +#define ACE_LACKS_STDINT_H + +// Platform lacks +#define ACE_LACKS_INTTYPES_H + +// Platform lacks +#define ACE_LACKS_SYS_SELECT_H + +// Platform lacks +#define ACE_LACKS_DLFCN_H + +// Platform lacks +#define ACE_LACKS_SEMAPHORE_H + +// Platform lacks +#define ACE_LACKS_POLL_H + +//========================================================================= +// Compiler specific parts +//========================================================================= + +// Compiler supports C++ exception handling +#define ACE_HAS_EXCEPTIONS + +// Compiler/platform has correctly prototyped header files +#define ACE_HAS_CPLUSPLUS_HEADERS + +// Compiler/platform does not support the unsigned long long datatype. +#define ACE_LACKS_LONGLONG_T + +// Compiler supports the ssize_t typedef +#define ACE_HAS_SSIZE_T + +// Platform/compiler supports Standard C++ Library +#define ACE_HAS_STANDARD_CPP_LIBRARY 0 + +// Compiler's template mechanism must see source code (i.e., +// .cpp files). +#define ACE_TEMPLATES_REQUIRE_SOURCE + +// Compiler implements templates that support typedefs inside +// of classes used as formal arguments to a template class. +#define ACE_HAS_TEMPLATE_TYPEDEFS + +// Platform has its standard c++ library in the namespace std. +#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 + +// Compiler doesn't support static data member templates +#define ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES + +// Platform lacks "signed char" type (broken!) +// Following will not be needed if use standard c library (G06.20 and later) +#define ACE_LACKS_SIGNED_CHAR + +//========================================================================= +// Build options +//========================================================================= + +// Disable the inclusion of RCS ids in the generated code. +#define ACE_USE_RCSID 0 + +// For debugging problems in os calls (but this doesn't work too well +// since output is not interleaved properly with output from ACE_TRACE +//# define ACE_OS_TRACE(X) ::printf(X) + +// Uncomment the following if timed message blocks are needed (e.g. +// for Dynamic_Priority_Test. Otherwise leave this disabled because +// enabling it adds overhead to message blocks and timed message blocks +// are "rarely used." +//#define ACE_HAS_TIMED_MESSAGE_BLOCKS + +// Uncomment the following if tokens library is needed. +//#define ACE_HAS_TOKENS_LIBRARY + +#include /**/ "ace/post.h" + +#endif /* ACE_CONFIG_NSK_H */ diff --git a/dep/acelite/ace/config-tandem-nsk-mips-v3.h b/dep/acelite/ace/config-tandem-nsk-mips-v3.h new file mode 100644 index 00000000000..e6c05a890b1 --- /dev/null +++ b/dep/acelite/ace/config-tandem-nsk-mips-v3.h @@ -0,0 +1,464 @@ +// -*- C++ -*- +// +// $Id: config-tandem-nsk-mips-v3.h 87167 2009-10-19 19:33:53Z olli $ + + +#ifndef ACE_CONFIG_NSK_H +#define ACE_CONFIG_NSK_H + +#include /**/ "ace/pre.h" + +// The following configuration file contains defines for Tandem NSK +// platform, MIPS processor, version 3 C++ compiler. + + +//========================================================================= +// Tandem NSK specific parts +//========================================================================= + + +// Disable pthread renaming of symbols such as "open" and "close" +#define _CMA_NOWRAPPERS_ 1 + +// Get Handle_Set.cpp to generate correct bit operations for NSK platform +#define ACE_TANDEM_NSK_BIT_ORDER + +// Use facilities provided by T1248 version of pthreads. +// (If not defined, will use old version of pthreads.) +#define ACE_TANDEM_T1248_PTHREADS + +// Use all available T1248 thread aware wrapper functions for providing +// non-blocking I/O. +// [Note: this causes a significant performance degradation] +//#define ACE_TANDEM_T1248_PTHREADS_ALL_IO_WRAPPERS + + +// Need this include here because some symbols defined by pthreads +// (e.g. timespec_t) are needed before spthread.h is normally included +// by ACE +#ifdef ACE_TANDEM_T1248_PTHREADS +#include +#else +#include "pthread.h" +#include "dce/cma_dispatch_coop.h" +#endif + +// The following #defines are hacks to get around things +// that seem to be missing or different in Tandem land +#define NSIG 32 // missing from Signal.h + // note: on nsk TNS/R there is room in + // sigset_t for 128 signals but those + // above 31 are not valid. +#define MAXNAMLEN 248 // missing from dirent.h +#define ERRMAX 4218 // from errno.h + +// Following seems to be missing from G06.20 version of standard +// pthreads includes (it appeared in older version of standard pthreads) +// (SCHED_FIFO (aka cma_c_sched_fifo) used in Dynamic_Priority_Test) +#ifdef ACE_TANDEM_T1248_PTHREADS +typedef enum CMA_T_SCHED_POLICY { + cma_c_sched_fifo = 0, + cma_c_sched_rr = 1, + cma_c_sched_throughput = 2, + cma_c_sched_background = 3, + cma_c_sched_ada_low = 4 + } cma_t_sched_policy; +#endif + +// T1248 doesn't define these constants. They're defined in spt/cma.h +// (formerly dce/cma.h), but this header is not included or provided +// by T1248 G07-AAL. +#define cma_c_prio_fifo_min 16 +#define cma_c_prio_fifo_mid 24 +#define cma_c_prio_fifo_max 31 +#define cma_c_prio_rr_min 16 +#define cma_c_prio_rr_mid 24 +#define cma_c_prio_rr_max 31 +#define cma_c_prio_through_min 8 +#define cma_c_prio_through_mid 12 +#define cma_c_prio_through_max 15 +#define cma_c_prio_back_min 1 +#define cma_c_prio_back_mid 4 +#define cma_c_prio_back_max 7 + +// Enable NSK Pluggable Protocols +#define TAO_HAS_NSKPW 1 +#define TAO_HAS_NSKFS 1 + +//========================================================================= +// Platform specific parts +//========================================================================= + +// Platform lacks getpwnam_r() methods (e.g., SGI 6.2). +#define ACE_LACKS_PWD_REENTRANT_FUNCTIONS + +// Platform/compiler lacks {get,set}rlimit() function +#define ACE_LACKS_RLIMIT + +// The platform doesn't have mmap(2) +#define ACE_LACKS_MMAP + +// Platform lacks streambuf "linebuffered ()". [C++ iostream] +#define ACE_LACKS_LINEBUFFERED_STREAMBUF + +// Platform supports recvmsg and sendmsg +#define ACE_HAS_MSG + +// Platform defines ACE_HAS_MSG, but lacks msg_accrights{,len}. +#define ACE_LACKS_MSG_ACCRIGHTS + +// Platform supports sigsuspend() +#define ACE_HAS_SIGSUSPEND + +// Platform/compiler has the sigwait(2) prototype +#define ACE_HAS_SIGWAIT + +// Compiler/platform defines the sig_atomic_t typedef +#define ACE_HAS_SIG_ATOMIC_T + +// OS/compiler uses size_t * rather than int * for socket lengths +#define ACE_HAS_SIZET_SOCKET_LEN + +// OS/compiler uses void * arg 4 setsockopt() rather than const char * +#define ACE_HAS_VOIDPTR_SOCKOPT + +// The platform doesn't have mprotect(2) +#define ACE_LACKS_MPROTECT + +// Platform lacks msync() +#define ACE_LACKS_MSYNC + +// Platform does not support reentrant netdb functions (getprotobyname_r, +// getprotobynumber_r, gethostbyaddr_r, gethostbyname_r, getservbyname_r). +#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS Platform does not support + +// Platform lacks madvise() +#define ACE_LACKS_MADVISE + +// Platform lacks pri_t +#define ACE_LACKS_PRI_T + +// Platform lacks a working sbrk() +#define ACE_LACKS_SBRK + +// Platform doesn't have syscall() prototype +#define ACE_LACKS_SYSCALL + +// Platform lacks the inet_aton() function. +#define ACE_LACKS_INET_ATON + +// Compiler/platform has Dirent iterator functions +#define ACE_HAS_DIRENT + +// Platform uses ACE_HAS_DIRENT but does not have readdir_r() +#define ACE_LACKS_READDIR_R + +// Platform supports getpagesize() call (otherwise, +// ACE_PAGE_SIZE must be defined) +#define ACE_HAS_GETPAGESIZE + +// Platform supports IP multicast +#define ACE_HAS_IP_MULTICAST + +// Platform's select() uses non-const timeval* +#define ACE_HAS_NONCONST_SELECT_TIMEVAL + +// Platform supports POSIX O_NONBLOCK semantics +#define ACE_HAS_POSIX_NONBLOCK + +// Platform lacks named POSIX semaphores +#define ACE_LACKS_NAMED_POSIX_SEM + +// Platform has support for multi-byte character support compliant +// with the XPG4 Worldwide Portability Interface wide-character +// classification. +#define ACE_HAS_XPG4_MULTIBYTE_CHAR + +// No wcsstr function available for this compiler +#define ACE_LACKS_WCSSTR + +// No wctype.h available for this compiler +#define ACE_LACKS_WCTYPE_H + +// Platform supports the POSIX regular expression library. +// [Note Tandem NSK platform does have regular expresson support but it +// does not follow the assumptions made by ACE. To use it would need +// to make some ACE modifications.] +//#define ACE_HAS_REGEX + +// Platform doesn't have truncate() +#define ACE_LACKS_TRUNCATE + +// Platform lacks readers/writer locks. +#define ACE_LACKS_RWLOCK_T + +// Compiler's 'new' throws exception on failure (ANSI C++ behavior). +#define ACE_NEW_THROWS_EXCEPTIONS + +// Optimize ACE_Handle_Set::count_bits for select() operations (common +// case) +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT + +// Platform lacks setreuid() +#define ACE_LACKS_SETREUID + +// Platform lacks setregid() +#define ACE_LACKS_SETREGID + +// Compile using multi-thread libraries +#define ACE_MT_SAFE 1 + + + +// Platform supports System V IPC +#define ACE_HAS_SYSV_IPC + +#define ACE_LACKS_SO_SNDBUF +#define ACE_LACKS_SO_RCVBUF + +// Platform lacks the socketpair() call +#define ACE_LACKS_SOCKETPAIR + +// Platform limits the maximum socket message size. +#define ACE_HAS_SOCK_BUF_SIZE_MAX + +// hrtime_t is a basic type that doesn't require ACE_U64_TO_U32 conversion +#define ACE_HRTIME_T_IS_BASIC_TYPE + +// printf format specifiers for 64 bit integers +# define ACE_UINT64_FORMAT_SPECIFIER_ASCII "%Ld" +# define ACE_INT64_FORMAT_SPECIFIER_ASCII "%Ld" + +// Use larger default buffer size for ease of interoperability +#define ACE_DEFAULT_CDR_BUFSIZE 4096 + +// Size of a wchar +#define ACE_SIZEOF_WCHAR 2 + +// Platform lacks time typedefs +#define ACE_LACKS_SUSECONDS_T +#define ACE_LACKS_USECONDS_T + +// Platform lacks setegid() and seteuid() +#define ACE_LACKS_SETEGID +#define ACE_LACKS_SETEUID + +// Platform lacks vsnprintf() +#define ACE_LACKS_VSNPRINTF + +// Platform lacks log2() +#define ACE_LACKS_LOG2 + +// Platform lacks alphasort() +#define ACE_LACKS_ALPHASORT + +#define ACE_LACKS_FD_MASK +#define ACE_LACKS_NFDBITS + +//========================================================================= +// Threads specific parts +//========================================================================= + +// Platform supports threads +#define ACE_HAS_THREADS + +// Platform supports POSIX Pthreads, of one form or another. This +// macro says the platform has a pthreads variety - should also define +// one of the below to say which one. Also may need some +// ACE_HAS_... thing for extensions. +#define ACE_HAS_PTHREADS + +// Standard pthreads supports only SCHED_FIFO +#define ACE_HAS_ONLY_SCHED_FIFO + +// Compiler/platform has thread-specific storage +#define ACE_HAS_THREAD_SPECIFIC_STORAGE + +// Platform has no implementation of pthread_condattr_setpshared(), +// even though it supports pthreads! +#define ACE_LACKS_CONDATTR_PSHARED + +// pthread_cond_timedwait does *not* reset the time argument when the +// lock is acquired. +#define ACE_LACKS_COND_TIMEDWAIT_RESET + +// Platform lacks pthread_attr_setsched() +#define ACE_LACKS_SETSCHED + +// Platform has pthread_getschedparam and pthread_setschedparam +// even when ACE_LACKS_SETSCHED is defined. +#define ACE_HAS_PTHREAD_SCHEDPARAM + +// Platform has pthread_mutexattr_setkind_np(). +#define ACE_HAS_PTHREAD_MUTEXATTR_SETKIND_NP + +// Platform lacks pthread_mutexattr_setpshared(). +#define ACE_LACKS_MUTEXATTR_PSHARED + +// Platform lacks pthread_attr_setscope() +#define ACE_LACKS_THREAD_PROCESS_SCOPING + +// Platform lacks pthread_attr_setstackaddr +#define ACE_LACKS_PTHREAD_ATTR_SETSTACKADDR + +// Platform lacks pthread_attr_setstack +#define ACE_LACKS_PTHREAD_ATTR_SETSTACK + +// Defining ACE_HAS_UCONTEXT_T since G06.21 version of spthreads has +// a definition for it. +#ifdef ACE_TANDEM_T1248_PTHREADS +#define ACE_HAS_UCONTEXT_T +#endif + +//========================================================================= +// Include file characteristics +//========================================================================= + +// Compiler/platform contains the file. +#define ACE_HAS_SYS_SYSCALL_H + +// Platform lacks malloc.h +#define ACE_LACKS_MALLOC_H + +// Platform lacks the siginfo.h include file +#define ACE_LACKS_SIGINFO_H + +// Platform doesn't define struct strrecvfd. +#define ACE_LACKS_STRRECVFD + +// Platform lacks the ucontext.h file +#define ACE_LACKS_UCONTEXT_H + +// Prototypes for both signal() and struct sigaction are consistent. +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES + +// Platform supports the POSIX struct timespec type +#define ACE_HAS_POSIX_TIME + +// Platform/compiler supports timezone * as second parameter to gettimeofday() +#define ACE_HAS_TIMEZONE_GETTIMEOFDAY + +// Platform has (which contains bzero() prototype) +#define ACE_HAS_STRINGS 1 + + +// OS/compiler omits the const from the iovec parameter in the +// writev() prototype. +#define ACE_HAS_NONCONST_WRITEV + +// Platform lacks +#define ACE_LACKS_STDINT_H + +// Platform lacks +#define ACE_LACKS_INTTYPES_H + +// Platform lacks +#define ACE_LACKS_SYS_SELECT_H + +// Platform lacks +#define ACE_LACKS_DLFCN_H + +// Platform lacks +#define ACE_LACKS_SEMAPHORE_H + +// Platform lacks +#define ACE_LACKS_POLL_H + +// Platform lacks +#define ACE_LACKS_SYS_SYSCTL_H + +//========================================================================= +// Compiler specific parts +//========================================================================= + +// Compiler supports C++ exception handling +#define ACE_HAS_EXCEPTIONS 1 + +// Compiler/platform has correctly prototyped header files +#define ACE_HAS_CPLUSPLUS_HEADERS + +// Compiler/platform does not support the unsigned long long datatype. +#define ACE_LACKS_UNSIGNEDLONGLONG_T + +// Compiler supports the ssize_t typedef +#define ACE_HAS_SSIZE_T + +// Platform/compiler supports Standard C++ Library +#define ACE_HAS_STANDARD_CPP_LIBRARY 1 + +// Compiler's template mechanism must see source code (i.e., +// .cpp files). +#define ACE_TEMPLATES_REQUIRE_SOURCE + +// Compiler implements templates that support typedefs inside +// of classes used as formal arguments to a template class. +#define ACE_HAS_TEMPLATE_TYPEDEFS + +// Platform/Compiler supports a String class +#define ACE_HAS_STRING_CLASS +#define ACE_HAS_STDCPP_STL_INCLUDES + +// Platform has its standard c++ library in the namespace std. +#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 + +// Compiler doesn't support static data member templates +#define ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES + +// Platform lacks "signed char" type (broken!) +// Following will not be needed if use standard c library (G06.20 and later) +#define ACE_LACKS_SIGNED_CHAR + +// Compiler can handle any operators in namespace +#define ACE_ANY_OPS_USE_NAMESPACE + +// Platform lacks intptr_t typedef +#define ACE_LACKS_INTPTR_T + +//========================================================================= +// C++ version3 import/export macros +//========================================================================= + +// Define the export macros needed to export symbols outside a DLL +// The ACE_IMPORT_SINGLETON_DECLARE macro has been modified to not explicitly +// instantiate the class template. +#if defined(USE_EXPLICIT_EXPORT) +#define ACE_LACKS_INLINE_FUNCTIONS + +#define ACE_HAS_CUSTOM_EXPORT_MACROS +#define ACE_Proper_Export_Flag export$ +#define ACE_Proper_Import_Flag import$ +#define ACE_EXPORT_SINGLETON_DECLARATION(T) template class export$ T +#define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) template class export$ SINGLETON_TYPE; +#define ACE_IMPORT_SINGLETON_DECLARATION(T) template class import$ T +#define ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) template class import$ SINGLETON_TYPE ; +#endif + + +//========================================================================= +// Build options +//========================================================================= + +// Disable the inclusion of RCS ids in the generated code. +#define ACE_USE_RCSID 0 + +// For debugging problems in os calls (but this doesn't work too well +// since output is not interleaved properly with output from ACE_TRACE +//# define ACE_OS_TRACE(X) ::printf(X) + +// Uncomment the following if timed message blocks are needed (e.g. +// for Dynamic_Priority_Test. Otherwise leave this disabled because +// enabling it adds overhead to message blocks and timed message blocks +// are "rarely used." +//#define ACE_HAS_TIMED_MESSAGE_BLOCKS + +// Uncomment the following if tokens library is needed. +//#define ACE_HAS_TOKENS_LIBRARY + +// NonStop CORBA uses the XML Service Configurator +#define ACE_HAS_XML_SVC_CONF + +#define ACE_LD_SEARCH_PATH "_RLD_LIB_PATH" + +#include /**/ "ace/post.h" + +#endif /* ACE_CONFIG_NSK_H */ diff --git a/dep/acelite/ace/config-tandem.h b/dep/acelite/ace/config-tandem.h new file mode 100644 index 00000000000..145c20abdaf --- /dev/null +++ b/dep/acelite/ace/config-tandem.h @@ -0,0 +1,191 @@ +/* -*- C++ -*- */ +// Testing TANDEM +// $Id: config-tandem.h 87167 2009-10-19 19:33:53Z olli $ + +// The following configuration file is designed to work for Tandems NonStop-UX +// 4.2MP platforms using the NCC 3.20 compiler. + +// Note this is a test version it might include several errors I +// have done a test and set/unset until I errors disappered. +// Some of the options that should be set aren't because of the simple fact +// that i haven't the time to check what is wrong. +// e.g. widecharacter are supported but a wcstok which only take 2 parameters +// are included by the compiler, to get the correct wcstok that takes 3 params +// we must set _XOPEN_SOURCE and we get ALOT of errors and warnings. +// So this config is done to get things to start to work it isn't finished. +// Janne (Jan.Perman@osd.Ericsson.se) + +#ifndef ACE_CONFIG_H +#define ACE_CONFIG_H +#include /**/ "ace/pre.h" + +#if ! defined (__ACE_INLINE__) +# define __ACE_INLINE__ +#endif /* ! __ACE_INLINE__ */ + +#define ACE_HAS_IDTYPE_T +// Optimize ACE_Handle_Set for select(). +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT + +// Tandem doesn't include this although they are defined +// in sys/time.h and sys/resource.h +#define ACE_LACKS_RLIMIT_PROTOTYPE // jjpp +// Tandem has a function to set t_errno (set_t_errno) +#define ACE_HAS_SET_T_ERRNO // jjpp + +//Platform supports System V IPC (most versions of UNIX, but not Win32) +#define ACE_HAS_SYSV_IPC + +// OS/compiler omits the const from the sendmsg() prototype. +#define ACE_HAS_NONCONST_SENDMSG + +//Platform supports system configuration information +#define ACE_HAS_SYS_SYSTEMINFO_H +#define ACE_HAS_SYSV_SYSINFO + +//Platform supports the POSIX regular expression library +#define ACE_HAS_REGEX + +// Platform supports recvmsg and sendmsg +#define ACE_HAS_MSG + +//Compiler/platform contains the file. +#define ACE_HAS_SYS_SYSCALL_H + +//Platform provides header +#define ACE_HAS_SYSENT_H + +// Platform has POSIX terminal interface. +#define ACE_HAS_TERMIOS + +//Platform supports POSIX O_NONBLOCK semantics +#define ACE_HAS_POSIX_NONBLOCK + +// Compiler/platform has correctly prototyped header files +#define ACE_HAS_CPLUSPLUS_HEADERS + +//Compiler/platform supports alloca() +// Although ACE does have alloca() on this compiler/platform combination, it is +// disabled by default since it can be dangerous. Uncomment the following line +// if you ACE to use it. +//#define ACE_HAS_ALLOCA + +//Compiler/platform has +#define ACE_HAS_ALLOCA_H + +//Platform contains +#define ACE_HAS_POLL + +// Platform supports the POSIX struct timespec type +#define ACE_HAS_POSIX_TIME // As i understand it, but i'm in deep water +//Platform supports the SVR4 timestruc_t type + +// To get this to work a patch in sys/signal must be made +// typedef void SIG_FUNC_TYPE(int); +//#if defined (__cplusplus) +// void (*sa_handler)(int); +//#else +// ... +//#endif +//#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES +#define ACE_HAS_TANDEM_SIGNALS +//Compiler/platform defines the sig_atomic_t typedef +#define ACE_HAS_SIG_ATOMIC_T +//Platform supports SVR4 extended signals +#define ACE_HAS_SIGINFO_T +//Platform supports ucontext_t (which is used in the extended signal API). +#define ACE_HAS_UCONTEXT_T + +// Platform/compiler has the sigwait(2) prototype +#define ACE_HAS_SIGWAIT + +//Compiler/platform provides the sockio.h file +#define ACE_HAS_SYS_SOCKIO_H + +// Compiler supports the ssize_t typedef +#define ACE_HAS_SSIZE_T // Limits.h must be included + +//Platform supports STREAMS +#define ACE_HAS_STREAMS + +#define ACE_HAS_STREAM_PIPES +//Platform supports STREAM pipes + +//Compiler/platform supports struct strbuf +#define ACE_HAS_STRBUF_T + +//Compiler/platform supports SVR4 dynamic linking semantics +#define ACE_HAS_SVR4_DYNAMIC_LINKING + +//Compiler/platform supports SVR4 TLI (in particular, T_GETNAME stuff)... +#define ACE_HAS_SVR4_TLI + +//Platform provides header +#define ACE_HAS_SYS_FILIO_H + +//Platform supports TLI timod STREAMS module +#define ACE_HAS_TIMOD_H +//Platform supports TLI tiuser header +#define ACE_HAS_TIUSER_H + +//Platform supports TLI +#define ACE_HAS_TLI +//Platform provides TLI function prototypes +#define ACE_HAS_TLI_PROTOTYPES + +//Platform lacks streambuf "linebuffered ()". +#define ACE_LACKS_LINEBUFFERED_STREAMBUF + +// Platform lacks "signed char" type (broken!) +#define ACE_LACKS_SIGNED_CHAR + + +#define ACE_PAGE_SIZE 4096 +// Defines the page size of the system (not used on Win32 or +// with ACE_HAS_GETPAGESIZE). + +/****** THREAD SPECIFIC **********/ +/* If you want to remove threading then comment out the following four #defines .*/ +#if !defined (ACE_MT_SAFE) + #define ACE_MT_SAFE 1 //Compile using multi-thread libraries +#endif +#define ACE_HAS_THREADS //Platform supports threads +#define ACE_HAS_STHREADS //Platform supports Solaris threads + +// Compiler/platform has threadspecific storage +#define ACE_HAS_THREAD_SPECIFIC_STORAGE +//Platform supports thr_keydelete (e.g,. UNIXWARE) + +#define ACE_HAS_THR_MINSTACK // Tandem uses thr_minstack instead of thr_min_stack +#define ACE_LACKS_PRI_T // Tandem lacks pri_t +#define ACE_HAS_THR_KEYDELETE + +//************************************* + +/*********************************/ + +/******* SIGNAL STUFF *******/ + +//Platform uses non-const char * in calls to gethostbyaddr, gethostbyname, +// getservbyname +#define ACE_HAS_NONCONST_GETBY +#define ACE_HAS_NONCONST_INET_ADDR +// Platform's select() uses non-const timeval* (only found on Linux right now) +#define ACE_HAS_NONCONST_SELECT_TIMEVAL +// And on Tandem :-) +//Uses ctime_r & asctime_r with only two parameters vs. three. +#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R +//Platform has special header for select(). +#define ACE_HAS_SELECT_H +// Platform/compiler supports Standard C++ Library +#define ACE_HAS_STANDARD_CPP_LIBRARY +//Platform lacks madvise() (e.g., Linux) +#define ACE_LACKS_MADVISE +//Compiler/platform lacks strcasecmp() (e.g., DG/UX, UNIXWARE, VXWORKS) +#define ACE_LACKS_STRCASECMP + +// Defines the page size of the system. +#define ACE_PAGE_SIZE 4096 + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_H */ diff --git a/dep/acelite/ace/config-tru64.h b/dep/acelite/ace/config-tru64.h new file mode 100644 index 00000000000..45a7aa6bd53 --- /dev/null +++ b/dep/acelite/ace/config-tru64.h @@ -0,0 +1,151 @@ +/* -*- C++ -*- */ +// $Id: config-tru64.h 87270 2009-10-29 21:47:47Z olli $ + +// The following configuration file is designed to work for the +// Digital UNIX V4.0a and later platforms. It relies on +// config-osf1-4.0.h, and adds deltas for newer platforms. + +#ifndef ACE_CONFIG_TRU64_H +#define ACE_CONFIG_TRU64_H +#include /**/ "ace/pre.h" + +#if !defined (__ACE_INLINE__) +# define __ACE_INLINE__ +#endif /* ! __ACE_INLINE__ */ + +// Compile using multi-thread libraries. +#if !defined (ACE_MT_SAFE) +# define ACE_MT_SAFE 1 +#endif /* ! ACE_MT_SAFE */ + +/*clearerr is not defined when _REENTRANT is not defined*/ +#if ACE_MT_SAFE == 0 +#define ACE_LACKS_CLEARERR +#endif /* ACE_MT_SAFE == 0 */ + +#include "ace/config-posix.h" + +// Configuration-specific #defines: +// 1) g++ or cxx +// 2) pthreads or DCE threads +#if defined (__GNUG__) + // g++ with pthreads + + // config-g++-common.h undef's ACE_HAS_STRING_CLASS with -frepo, so + // this must appear before its #include. +# define ACE_HAS_STRING_CLASS + +# include "ace/config-g++-common.h" + +# define ACE_HAS_REENTRANT_FUNCTIONS +#elif defined (__DECCXX) + +# define ACE_CONFIG_INCLUDE_CXX_COMMON +# include "ace/config-cxx-common.h" + +#elif defined (__rational__) +# define ACE_HAS_REENTRANT_FUNCTIONS +# define ACE_HAS_STRING_CLASS +# define ACE_LACKS_LINEBUFFERED_STREAMBUF +# define ACE_LACKS_SIGNED_CHAR + + // Exceptions are enabled by platform_osf1_4.0_rcc.GNU. +# define ACE_HAS_STDCPP_STL_INCLUDES +#else +# ifdef __cplusplus /* Let it slide for C compilers. */ +# error unsupported compiler on Digital Unix +# endif /* __cplusplus */ +#endif /* ! __GNUG__ && ! __DECCXX && ! __rational__ */ + +#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R +#define ACE_HAS_BROKEN_IF_HEADER +#if (ACE_MT_SAFE != 0) +# define ACE_HAS_PTHREADS +# define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS +#endif /* ACE_MT_SAFE != 0 */ +#define ACE_LACKS_T_ERRNO +#if !defined (DIGITAL_UNIX) +# define DIGITAL_UNIX 0x400 +#endif /* ! DIGITAL_UNIX */ + +#define ACE_SIZEOF_LONG 8 + +#define ACE_DEFAULT_BASE_ADDR ((char *) 0x80000000) +#define ACE_HAS_AUTOMATIC_INIT_FINI +#define ACE_HAS_NONCONST_SETRLIMIT +#define ACE_HAS_BROKEN_T_ERROR +#define ACE_HAS_NONCONST_WRITEV +#define ACE_HAS_CLOCK_GETTIME +#define ACE_HAS_CLOCK_SETTIME +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES +#define ACE_HAS_CPLUSPLUS_HEADERS +#define ACE_HAS_DIRENT +#define ACE_HAS_GETRUSAGE +#define ACE_HAS_GPERF +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT +#define ACE_HAS_IP_MULTICAST +#define ACE_HAS_LLSEEK +#define ACE_HAS_LONG_MAP_FAILED +#define ACE_HAS_MSG +#define ACE_HAS_NONCONST_SELECT_TIMEVAL +#define ACE_HAS_NONCONST_SENDMSG +#define ACE_HAS_OSF1_GETTIMEOFDAY +#define ACE_HAS_OSF_TIMOD_H +#define ACE_HAS_POLL +#define ACE_HAS_POSIX_NONBLOCK +#define ACE_HAS_POSIX_TIME +#define ACE_HAS_PRIOCNTL +#define ACE_HAS_SIGINFO_T +#define ACE_HAS_SIG_ATOMIC_T +#define ACE_HAS_SSIZE_T +#define ACE_HAS_STRBUF_T +#define ACE_HAS_STREAMS +#define ACE_HAS_STRPTIME +#define ACE_HAS_SVR4_DYNAMIC_LINKING +#define ACE_HAS_SVR4_SIGNAL_T +#define ACE_HAS_SYS_SYSCALL_H +#define ACE_HAS_SYSV_IPC +#if (ACE_MT_SAFE == 0) +// clearerr is not defined when _REENTRANT is not defined +#define ACE_LACKS_CLEARERR +#else /* ACE_MT_SAFE != 0 */ +#define ACE_HAS_THREADS +#define ACE_HAS_THREAD_SPECIFIC_STORAGE +#define ACE_LACKS_PTHREAD_ATTR_SETSTACKADDR +#endif /* ACE_MT_SAFE != 0 */ +#define ACE_HAS_TIUSER_H +#define ACE_HAS_XTI +#define ACE_HAS_TLI_PROTOTYPES +#define ACE_HAS_UALARM +#define ACE_HAS_UCONTEXT_T +#define ACE_LACKS_PRI_T +#define ACE_LACKS_RWLOCK_T +#define ACE_PAGE_SIZE 8192 +#define ACE_HAS_SIGTIMEDWAIT +#define ACE_HAS_SIGSUSPEND + +// DJT 6/10/96 All these broken macro's can now be removed with the +// approporiate ordering of the include files. The Platinum release +// now temporarily supports both forms. Platform's implementation of +// sendmsg() has a non-const msgheader parameter. +#define ACE_HAS_NONCONST_SENDMSG +#define ACE_HAS_IDTYPE_T +#define ACE_HAS_NONSTATIC_OBJECT_MANAGER + +#if DIGITAL_UNIX >= 0x500 +# define ACE_HAS_XPG4_MULTIBYTE_CHAR 1 +#endif /* DIGITAL_UNIX >= 0x500 */ + +#if DIGITAL_UNIX >= 0x40E +# define ACE_LACKS_STDINT_H +#endif /* DIGITAL_UNIX >= 0x40E */ + +#if (DIGITAL_UNIX >= 0x400) && (DIGITAL_UNIX < 0x500) +#define ACE_LACKS_PREAD_PROTOTYPE +#endif /* (DIGITAL_UNIX >= 0x400) && (DIGITAL_UNIX < 0x500) */ + +// gethostbyaddr does not handle IPv6-mapped-IPv4 addresses +#define ACE_HAS_BROKEN_GETHOSTBYADDR_V4MAPPED + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_TRU64_H */ diff --git a/dep/acelite/ace/config-unixware-7.1.0.h b/dep/acelite/ace/config-unixware-7.1.0.h new file mode 100644 index 00000000000..820e7fb763a --- /dev/null +++ b/dep/acelite/ace/config-unixware-7.1.0.h @@ -0,0 +1,406 @@ +/* -*- C++ -*- */ +// $Id: config-unixware-7.1.0.h 87268 2009-10-29 21:06:06Z olli $ + +#ifndef ACE_CONFIG_H +#define ACE_CONFIG_H + +/* ACE configuration header file */ + +/* Include the commong gnu config file */ +#include "config-g++-common.h" + +/* For unixware 7.1 && g++ 2.91.57, see if this fixes my problem */ +#ifndef UNIXWARE_7_1 +#define UNIXWARE_7_1 +#endif + +/* Define if you have alloca, as a function or macro. */ +#define HAVE_ALLOCA 1 + +/* Define if you have the strftime function. */ +#define HAVE_STRFTIME 1 + +/* Define if you have that is POSIX.1 compatible. */ +#define HAVE_SYS_WAIT_H 1 + +/* Define if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Define if lex declares yytext as a char * by default, not a char[]. */ +#define YYTEXT_POINTER 1 + +/* Define _REENTRANT if reentrant functions should be used. */ +#ifndef _REENTRANT +# define _REENTRANT 1 +#endif + +#define ACE_HAS_NEW_NO_H 1 +#define ACE_HAS_STDEXCEPT_NO_H 1 + +#define ACE_THREAD_MIN_PRIORITY 0 +#if defined (ACE_THREAD_MIN_PRIORITY) +# define PTHREAD_MIN_PRIORITY ACE_THREAD_MIN_PRIORITY +#endif /* #if defined (ACE_THREAD_MIN_PRIORITY) */ + +#define ACE_THREAD_MAX_PRIORITY 99 +#if defined (ACE_THREAD_MAX_PRIORITY) +# define PTHREAD_MAX_PRIORITY ACE_THREAD_MAX_PRIORITY +#endif /* #if defined (ACE_THREAD_MAX_PRIORITY) */ + +/* Specify sizes of given built-in types. If a size isn't defined here, + then ace/Basic_Types.h will attempt to deduce the size. */ +/* #undef ACE_SIZEOF_CHAR */ +#define ACE_SIZEOF_SHORT 2 +#define ACE_SIZEOF_INT 4 +#define ACE_SIZEOF_LONG 4 +#define ACE_SIZEOF_LONG_LONG 8 +#define ACE_SIZEOF_VOID_P 4 +#define ACE_SIZEOF_FLOAT 4 +#define ACE_SIZEOF_DOUBLE 8 +#define ACE_SIZEOF_LONG_DOUBLE 12 + +/* Enable ACE inlining */ +#define __ACE_INLINE__ 1 + +/* OS has priocntl (2) */ +#define ACE_HAS_PRIOCNTL 1 + +/* Platform has pread() and pwrite() support */ +#define ACE_HAS_P_READ_WRITE 1 + +/* Compiler/platform supports alloca() */ +// Although ACE does have alloca() on this compiler/platform combination, it is +// disabled by default since it can be dangerous. Uncomment the following line +// if you ACE to use it. +//#define ACE_HAS_ALLOCA 1 + +/* Compiler/platform correctly calls init()/fini() for shared libraries */ +#define ACE_HAS_AUTOMATIC_INIT_FINI 1 + +/* Platform doesn't cast MAP_FAILED to a (void *). */ +/* #undef ACE_HAS_BROKEN_MAP_FAILED */ +/* Staller: oh yes, let's do this! */ +#define ACE_HAS_BROKEN_MAP_FAILED + +/* Prototypes for both signal() and struct sigaction are consistent. */ +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES 1 + +/* Platform supports operations on directories via struct dirent, + readdir_r, etc. */ +#define ACE_HAS_DIRENT 1 + +/* Compiler supports C++ exception handling */ +// MM-Graz if ! defined inserted, to prevent warnings, because it is already +// defined in config-g++common.h +# if !defined (ACE_HAS_EXCEPTIONS) +#define ACE_HAS_EXCEPTIONS 1 +# endif + +/* Platform supports getpagesize() call (otherwise, ACE_PAGE_SIZE must be + defined, except on Win32) */ +#define ACE_HAS_GETPAGESIZE 1 + +/* Platform supports the getrusage() system call. */ +#define ACE_HAS_GETRUSAGE 1 + +/* Platform has a getrusage () prototype in sys/resource.h that differs from + the one in ace/OS.i. */ +#define ACE_HAS_GETRUSAGE_PROTOTYPE 1 + +/* The GPERF utility is compiled for this platform */ +#define ACE_HAS_GPERF 1 + +/* Optimize ACE_Handle_Set::count_bits for select() operations (common case) */ +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT 1 + +/* Compiler/platform supports idtype_t. */ +#define ACE_HAS_IDTYPE_T 1 + +/* Platform supports IP multicast */ +#define ACE_HAS_IP_MULTICAST 1 + +/* Platform supports thr_keydelete (e.g,. UNIXWARE) */ +#define ACE_HAS_THR_KEYDELETE 1 + +/* Platform calls thr_minstack() rather than thr_min_stack() (e.g., Tandem). */ +#define ACE_HAS_THR_MINSTACK 1 + +/* Platform supports recvmsg and sendmsg */ +#define ACE_HAS_MSG 1 + +/* Platform's select() uses non-const timeval* (only found on Linux right + now) */ +#define ACE_HAS_NONCONST_SELECT_TIMEVAL 1 + +/* Uses ctime_r & asctime_r with only two parameters vs. three. */ +#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R 1 + +/* Platform is an Intel Pentium microprocessor. */ +/* There is a problem with the gethrtime() because of (apparently) a problem + with the inline assembly instruction. Hopefully there is a way to resolve + that with an improvement to the assembler +*/ +#ifdef ACE_HAS_PENTIUM +#undef ACE_HAS_PENTIUM +#endif /* ACE_HAS_PENTIUM */ + + +/* Platform contains */ +#define ACE_HAS_POLL 1 + +/* Platform supports POSIX O_NONBLOCK semantics */ +#define ACE_HAS_POSIX_NONBLOCK 1 + +/* Platform supports the POSIX struct timespec type */ +#define ACE_HAS_POSIX_TIME 1 + +/* Platform supports the /proc file system and defines tid_t + in */ +#define ACE_HAS_PROC_FS 1 + +/* Platform supports POSIX Threads */ +#define ACE_HAS_PTHREADS 1 + +/* pthread.h declares an enum with PTHREAD_PROCESS_PRIVATE and + PTHREAD_PROCESS_SHARED values */ +#define ACE_HAS_PTHREAD_PROCESS_ENUM 1 + +/* Platform will recurse infinitely on thread exits from TSS cleanup routines + (e.g., AIX) */ +#define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS 1 + +/* Platform supports reentrant functions (i.e., all the POSIX *_r + functions). */ +#define ACE_HAS_REENTRANT_FUNCTIONS 1 + +/* Platform has support for multi-byte character support compliant with the + XPG4 Worldwide Portability Interface wide-character classification. */ +#define ACE_HAS_XPG4_MULTIBYTE_CHAR 1 + +/* Platform does not support reentrant netdb functions (getprotobyname_r, + getprotobynumber_r, gethostbyaddr_r, gethostbyname_r, getservbyname_r). */ +#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS 1 + +/* Platform supports the POSIX regular expression library */ +#define ACE_HAS_REGEX 1 + +/* Platform has special header for select(). */ +#define ACE_HAS_SELECT_H 1 + +/* Platform has a function to set t_errno (e.g., Tandem). */ +#define ACE_HAS_SET_T_ERRNO 1 + +/* Platform supports SVR4 extended signals */ +#define ACE_HAS_SIGINFO_T 1 + +/* Platform/compiler has the sigwait(2) prototype */ +#define ACE_HAS_SIGWAIT 1 + +/* Compiler/platform defines the sig_atomic_t typedef */ +#define ACE_HAS_SIG_ATOMIC_T 1 + +/* Platform supports new BSD inet_addr len field. */ +#define ACE_HAS_SOCKADDR_IN_SIN_LEN 1 + +/* OS/compiler uses size_t * rather than int * for socket lengths */ +#define ACE_HAS_SIZET_SOCKET_LEN 1 + +/* Compiler/platform provides the sys/sockio.h file */ +#define ACE_HAS_SYS_SOCKIO_H 1 + +/* Compiler supports the ssize_t typedef */ +#define ACE_HAS_SSIZE_T 1 + +/* Platform supports UNIX International Threads */ +#define ACE_HAS_STHREADS 1 + +/* Platform has thr_yield() */ +#define ACE_HAS_THR_YIELD 1 + +/* Compiler/platform supports struct strbuf */ +#define ACE_HAS_STRBUF_T 1 + +/* Platform supports STREAMS */ +#define ACE_HAS_STREAMS 1 + +/* Platform supports STREAM pipes */ +#define ACE_HAS_STREAM_PIPES 1 + +/* Platform/Compiler supports a String class (e.g., GNU or Win32). */ +#define ACE_HAS_STRING_CLASS 1 + +/* Platform has (which contains bzero() prototype) */ +#define ACE_HAS_STRINGS 1 + +/* Platform/compiler supports void * as second parameter to gettimeofday(). */ +#define ACE_HAS_VOIDPTR_GETTIMEOFDAY 1 + +/* Compiler/platform supports SVR4 dynamic linking semantics */ +#define ACE_HAS_SVR4_DYNAMIC_LINKING 1 + +/* Compiler/platform supports SVR4 TLI (in particular, T_GETNAME stuff)... */ +#define ACE_HAS_SVR4_TLI 1 + +/* Compiler/platform contains the file. */ +#define ACE_HAS_SYS_SYSCALL_H 1 + +/* Platform supports system configuration information */ +#define ACE_HAS_SYS_SYSTEMINFO_H +#define ACE_HAS_SYSV_SYSINFO 1 + +/* Platform supports System V IPC (most versions of UNIX, but not Win32) */ +#define ACE_HAS_SYSV_IPC 1 + +/* Platform provides header */ +#define ACE_HAS_SYS_FILIO_H 1 + +/* Platform provides header */ +#define ACE_HAS_SYS_XTI_H 1 + +/* Platform has POSIX terminal interface. */ +#define ACE_HAS_TERMIOS 1 + +/* Platform supports threads */ +#define ACE_HAS_THREADS 1 + +/* Compiler/platform has thread-specific storage */ +#define ACE_HAS_THREAD_SPECIFIC_STORAGE 1 + +/* Platform supports TLI timod STREAMS module */ +#define ACE_HAS_TIMOD_H 1 + +/* Platform supports TLI tiuser header */ +#define ACE_HAS_TIUSER_H 1 + +/* Platform supports TLI. Also see ACE_TLI_TCP_DEVICE. */ +#define ACE_HAS_TLI 1 + +/* Platform provides TLI function prototypes */ +#define ACE_HAS_TLI_PROTOTYPES 1 + +/* Platform supports ualarm() */ +#define ACE_HAS_UALARM 1 + +/* Platform supports ucontext_t (which is used in the extended signal API). */ +#define ACE_HAS_UCONTEXT_T 1 + +/* Platform has header file */ +#define ACE_HAS_UTIME 1 + +/* Platform requires void * for mmap(). */ +#define ACE_HAS_VOIDPTR_MMAP 1 + +/* Platform has XTI (X/Open-standardized superset of TLI). Implies + ACE_HAS_TLI but uses a different header file. */ +#define ACE_HAS_XTI 1 + +/* Platform can not build ace/IOStream{,_T}.cpp. This does not necessarily + mean that the platform does not support iostreams. */ +#define ACE_LACKS_ACE_IOSTREAM 1 + +/* Platform does not have u_longlong_t typedef */ +#define ACE_LACKS_U_LONGLONG_T 1 + +/* Platform lacks madvise() (e.g., Linux) */ +#define ACE_LACKS_MADVISE 1 + +/* Platform lacks pri_t (e.g., Tandem NonStop UNIX). */ +#define ACE_LACKS_PRI_T 1 + +/* Platform lacks pthread_thr_sigsetmask (e.g., MVS, HP/UX, and OSF/1 3.2) */ +#define ACE_LACKS_PTHREAD_THR_SIGSETMASK 1 + +/* Platfrom lack pthread_yield() support. */ +#define ACE_LACKS_PTHREAD_YIELD 1 + +/* Platform lacks readers/writer locks. */ +#define ACE_LACKS_RWLOCK_T 1 + +/* MIT pthreads platform lacks the timedwait prototypes */ +#define ACE_LACKS_TIMEDWAIT_PROTOTYPES 1 + +/* Platform does not define timepec_t as a typedef for struct timespec. */ +#define ACE_LACKS_TIMESPEC_T 1 + +/* Compile using multi-thread libraries */ +#define ACE_MT_SAFE 1 + +/* Platform needs to #include to get thread scheduling defs. */ +#define ACE_NEEDS_SCHED_H 1 + +/*********************************************************************/ +/* Compiler's template mechanim must see source code (i.e., .cpp files). This + is used for GNU G++. */ +/* Staller -> make 0 */ +// #undef ACE_TEMPLATES_REQUIRE_SOURCE + +/*********************************************************************/ + +/* The OS/platform supports the poll() event demultiplexor */ +#define ACE_USE_POLL 1 + +/* Platform has its standard c++ library in the namespace std. */ +#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 + +/* The number of bytes in a double. */ +#define SIZEOF_DOUBLE 8 + +/* The number of bytes in a float. */ +#define SIZEOF_FLOAT 4 + +/* The number of bytes in a int. */ +#define SIZEOF_INT 4 + +/* The number of bytes in a long. */ +#define SIZEOF_LONG 4 + +/* The number of bytes in a long double. */ +#define SIZEOF_LONG_DOUBLE 12 + +/* The number of bytes in a long long. */ +#define SIZEOF_LONG_LONG 8 + +/* The number of bytes in a short. */ +#define SIZEOF_SHORT 2 + +/* The number of bytes in a signed char. */ +#define SIZEOF_SIGNED_CHAR 1 + +/* The number of bytes in a void *. */ +#define SIZEOF_VOID_P 4 + +/* Define if you have the execv function. */ +#define HAVE_EXECV 1 + +/* Define if you have the execve function. */ +#define HAVE_EXECVE 1 + +/* Define if you have the execvp function. */ +#define HAVE_EXECVP 1 + +/* Define if you have the header file. */ +#define HAVE_DIRENT_H 1 + +/* Define if you have the header file. */ +#define HAVE_FSTREAM 1 + +/* Define if you have the header file. */ +#define HAVE_IOMANIP 1 + +/* Define if you have the header file. */ +#define HAVE_IOSTREAM 1 + +/* Define if you have the header file. */ +#define HAVE_PWD_H 1 + +/* Name of package */ +#define PACKAGE "ace" + +/* Added by Staller */ +#define ENUM_BOOLEAN // See file /usr/local/lib/gcc-lib/i486-pc-sysv5/egcs-2.91.60/include/sys/types.h +#define howmany(x, y) (((x)+((y)-1))/(y)) +#define ACE_HAS_BROKEN_T_ERROR // make a nasty warning disappear in OS.i +#define __USLC__ 1 +#define __IOCTL_VERSIONED__ // By Carlo! + +#endif /* ACE_CONFIG_H */ diff --git a/dep/acelite/ace/config-unixware-7.1.0.udk.h b/dep/acelite/ace/config-unixware-7.1.0.udk.h new file mode 100644 index 00000000000..ec668c19581 --- /dev/null +++ b/dep/acelite/ace/config-unixware-7.1.0.udk.h @@ -0,0 +1,457 @@ +/* -*- C++ -*- */ +#ifndef ACE_CONFIG_UNIXWARE_UDK_H +#define ACE_CONFIG_UNIXWARE_UDK_H + +// $Id: config-unixware-7.1.0.udk.h 87167 2009-10-19 19:33:53Z olli $ + +// Configuration for the unixware UDK compiler. derived from the unixware/g++ config +// which was itself derived from an autoconfig run. + +/* ACE configuration header file */ + +#define ACE_TEMPLATES_REQUIRE_SOURCE + +#ifndef UNIXWARE_7_1 +#define UNIXWARE_7_1 +#endif + +#define ACE_LACKS_PLACEMENT_OPERATOR_DELETE + +/* Define if you have the strftime function. */ +#define HAVE_STRFTIME 1 + +/* Define if you have that is POSIX.1 compatible. */ +#define HAVE_SYS_WAIT_H 1 + +/* Define if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Define if lex declares yytext as a char * by default, not a char[]. */ +#define YYTEXT_POINTER 1 + +/* Define _REENTRANT if reentrant functions should be used. */ +#ifndef _REENTRANT +# define _REENTRANT 1 +#endif + +#define ACE_HAS_NEW_NO_H 1 +#define ACE_HAS_STDEXCEPT_NO_H 1 + +/* + * TODO: These two next #defines have an #undef before them, in + * case the variable being defined already had a value. + * The #undefs are being picked up by configure, and are commented out! + */ +#define ACE_THREAD_MIN_PRIORITY 0 +#if defined (ACE_THREAD_MIN_PRIORITY) +/* # undef PTHREAD_MIN_PRIORITY */ +# define PTHREAD_MIN_PRIORITY ACE_THREAD_MIN_PRIORITY +#endif /* #if defined (ACE_THREAD_MIN_PRIORITY) */ + +#define ACE_THREAD_MAX_PRIORITY 99 +#if defined (ACE_THREAD_MAX_PRIORITY) +/* # undef PTHREAD_MAX_PRIORITY */ +# define PTHREAD_MAX_PRIORITY ACE_THREAD_MAX_PRIORITY +#endif /* #if defined (ACE_THREAD_MAX_PRIORITY) */ + + + +/* UnixWare specific configuration parameters */ +/* #undef UNIXWARE */ +/* #undef UNIXWARE_2_0 */ +/* #undef UNIXWARE_2_1 */ + +/* Specify sizes of given built-in types. If a size isn't defined here, + then ace/Basic_Types.h will attempt to deduce the size. */ +/* #undef ACE_SIZEOF_CHAR */ +#define ACE_SIZEOF_SHORT 2 +#define ACE_SIZEOF_INT 4 +#define ACE_SIZEOF_LONG 4 +#define ACE_SIZEOF_LONG_LONG 8 +#define ACE_SIZEOF_VOID_P 4 +#define ACE_SIZEOF_FLOAT 4 +#define ACE_SIZEOF_DOUBLE 8 +#define ACE_SIZEOF_LONG_DOUBLE 12 + +/* Enable ACE inlining */ +#define __ACE_INLINE__ 1 + +/* Platform supports Asynchronous IO calls */ +/* #define ACE_HAS_AIO_CALLS */ + +/* Specify this if you don't want threads to inherit parent thread's + ACE_Log_Msg properties. */ +/* #undef ACE_THREADS_DONT_INHERIT_LOG_MSG */ + +/* OS has priocntl (2) */ +#define ACE_HAS_PRIOCNTL 1 + +/* Platform has pread() and pwrite() support */ +#define ACE_HAS_P_READ_WRITE 1 + +/* Compiler/platform correctly calls init()/fini() for shared libraries */ +#define ACE_HAS_AUTOMATIC_INIT_FINI 1 + +/* Compiler handles explicit calling of template destructor correctly. + See "ace/OS.h" for details. */ +/* Staller: already defined by config-g++-common.h +#define ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR 1 +*/ + +/* Platform doesn't cast MAP_FAILED to a (void *). */ +/* #undef ACE_HAS_BROKEN_MAP_FAILED */ +/* Staller: oh yes, let's do this! */ +#define ACE_HAS_BROKEN_MAP_FAILED + + +/* Prototypes for both signal() and struct sigaction are consistent. */ +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES 1 + +/* Compiler/platform has correctly prototyped header files */ +#define ACE_HAS_CPLUSPLUS_HEADERS + +/* Platform supports operations on directories via struct dirent, + readdir_r, etc. */ +#define ACE_HAS_DIRENT + +/* Compiler supports C++ exception handling */ +# if !defined (ACE_HAS_EXCEPTIONS) +#define ACE_HAS_EXCEPTIONS +# endif + +/* Platform supports getpagesize() call (otherwise, ACE_PAGE_SIZE must be + defined, except on Win32) */ +#define ACE_HAS_GETPAGESIZE + +/* Platform supports the getrusage() system call. */ +#define ACE_HAS_GETRUSAGE + +/* Platform has a getrusage () prototype in sys/resource.h that differs from + the one in ace/OS.i. */ +#define ACE_HAS_GETRUSAGE_PROTOTYPE + +/* The GPERF utility is compiled for this platform */ +#define ACE_HAS_GPERF + +/* Optimize ACE_Handle_Set::count_bits for select() operations (common case) */ +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT 1 + +/* Compiler/platform supports SunOS high resolution timers */ +/* #undef ACE_HAS_HI_RES_TIMER */ + +/* Compiler/platform supports idtype_t. */ +#define ACE_HAS_IDTYPE_T + +/* Inline all the static class OS methods to remove call overhead */ +/* Note: This gets defined by OS.h if __ACE_INLINE__ is defined */ +/* #undef ACE_HAS_INLINED_OSCALLS */ + +/* Platform supports IP multicast */ +#define ACE_HAS_IP_MULTICAST + +/* Platform supports thr_keydelete (e.g,. UNIXWARE) */ +#define ACE_HAS_THR_KEYDELETE + +/* Platform calls thr_minstack() rather than thr_min_stack() (e.g., Tandem). */ +#define ACE_HAS_THR_MINSTACK + +/* Some files, such as ace/streams.h, want to include new style C++ stream + headers. These headers are iomanip, ios, iostream, istream, ostream, + fstream and streambuf. If _all_ of these headers aren't available, then + assume that only iostream.h and fstream.h are available. */ +/* #define ACE_USES_OLD_IOSTREAMS */ + +/* Platform supports recvmsg and sendmsg */ +#define ACE_HAS_MSG + +/* Platform's select() uses non-const timeval* (only found on Linux right + now) */ +#define ACE_HAS_NONCONST_SELECT_TIMEVAL + +/* Uses ctime_r & asctime_r with only two parameters vs. three. */ +#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R + + +/* Platform is an Intel Pentium microprocessor. */ +/* There is a problem with the gethrtime() because of (apparently) a problem + with the inline assembly instruction. Hopefully there is a way to resolve + that with an improvement to the assembler +*/ +#ifdef ACE_HAS_PENTIUM +//#undef ACE_HAS_PENTIUM +#endif /* ACE_HAS_PENTIUM */ + + +/* Platform contains */ +#define ACE_HAS_POLL + +/* Platform supports POSIX O_NONBLOCK semantics */ +#define ACE_HAS_POSIX_NONBLOCK + +/* Platform supports the POSIX struct timespec type */ +#define ACE_HAS_POSIX_TIME + +/* Platform supports the /proc file system and defines tid_t + in */ +#define ACE_HAS_PROC_FS + +/* Platform supports POSIX Threads */ +#define ACE_HAS_PTHREADS + +/* pthread.h declares an enum with PTHREAD_PROCESS_PRIVATE and + PTHREAD_PROCESS_SHARED values */ +#define ACE_HAS_PTHREAD_PROCESS_ENUM + +/* Platform will recurse infinitely on thread exits from TSS cleanup routines + (e.g., AIX) */ +#define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS + +/* Platform supports reentrant functions (i.e., all the POSIX *_r + functions). */ +#define ACE_HAS_REENTRANT_FUNCTIONS + +/* Platform has support for multi-byte character support compliant with the + XPG4 Worldwide Portability Interface wide-character classification. */ +#define ACE_HAS_XPG4_MULTIBYTE_CHAR + +/* Platform does not support reentrant netdb functions (getprotobyname_r, + getprotobynumber_r, gethostbyaddr_r, gethostbyname_r, getservbyname_r). */ +#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS + +/* Platform supports the POSIX regular expression library */ +#define ACE_HAS_REGEX + +/* Platform has special header for select(). */ +#define ACE_HAS_SELECT_H + +/* Platform has a function to set t_errno (e.g., Tandem). */ +#define ACE_HAS_SET_T_ERRNO + +/* Platform supports SVR4 extended signals */ +#define ACE_HAS_SIGINFO_T + +/* Platform/compiler has the sigwait(2) prototype */ +#define ACE_HAS_SIGWAIT + +/* Compiler/platform defines the sig_atomic_t typedef */ +#define ACE_HAS_SIG_ATOMIC_T + +/* Platform supports new BSD inet_addr len field. */ +#define ACE_HAS_SOCKADDR_IN_SIN_LEN + +/* OS/compiler uses size_t * rather than int * for socket lengths */ +#define ACE_HAS_SIZET_SOCKET_LEN + +/* Compiler/platform provides the sys/sockio.h file */ +#define ACE_HAS_SYS_SOCKIO_H + +/* Compiler supports the ssize_t typedef */ +#define ACE_HAS_SSIZE_T + +/* Platform supports UNIX International Threads */ +#define ACE_HAS_STHREADS + +/* Platform has thr_yield() */ +#define ACE_HAS_THR_YIELD + +/* Platform/compiler supports Standard C++ Library */ +/* It seems that UDK provides std-like declarations for only portions + such as +*/ +#define ACE_HAS_STANDARD_CPP_LIBRARY 0 + +/* Compiler/platform supports struct strbuf */ +#define ACE_HAS_STRBUF_T + +/* Platform supports STREAMS */ +#define ACE_HAS_STREAMS + +/* Platform supports STREAM pipes */ +#define ACE_HAS_STREAM_PIPES + +/* Platform/Compiler supports a String class (e.g., GNU or Win32). */ +#define ACE_HAS_STRING_CLASS + +/* Platform has (which contains bzero() prototype) */ +#define ACE_HAS_STRINGS + +/* Platform/compiler supports void * as second parameter to gettimeofday(). */ +#define ACE_HAS_VOIDPTR_GETTIMEOFDAY + +/* Compiler/platform supports SVR4 dynamic linking semantics */ +#define ACE_HAS_SVR4_DYNAMIC_LINKING + +/* Compiler/platform supports SVR4 TLI (in particular, T_GETNAME stuff)... */ +#define ACE_HAS_SVR4_TLI + +/* Compiler/platform contains the file. */ +#define ACE_HAS_SYS_SYSCALL_H + +/* Platform supports system configuration information */ +#define ACE_HAS_SYS_SYSTEMINFO_H +#define ACE_HAS_SYSV_SYSINFO 1 + +/* Platform supports System V IPC (most versions of UNIX, but not Win32) */ +#define ACE_HAS_SYSV_IPC 1 + +/* Platform provides header */ +#define ACE_HAS_SYS_FILIO_H 1 + +/* Platform provides header */ +#define ACE_HAS_SYS_XTI_H 1 + +/* Compiler implements templates that support typedefs inside of classes used + as formal arguments to a template class. */ +#define ACE_HAS_TEMPLATE_TYPEDEFS 1 + +/* Platform has POSIX terminal interface. */ +#define ACE_HAS_TERMIOS 1 + +/* Platform supports threads */ +#define ACE_HAS_THREADS 1 + +/* Compiler/platform has thread-specific storage */ +#define ACE_HAS_THREAD_SPECIFIC_STORAGE 1 + +/* Platform supports TLI timod STREAMS module */ +#define ACE_HAS_TIMOD_H 1 + +/* Platform supports TLI tiuser header */ +#define ACE_HAS_TIUSER_H 1 + +/* Platform supports TLI. Also see ACE_TLI_TCP_DEVICE. */ +#define ACE_HAS_TLI 1 + +/* Platform provides TLI function prototypes */ +#define ACE_HAS_TLI_PROTOTYPES 1 + +/* Platform supports ualarm() */ +#define ACE_HAS_UALARM 1 + +/* Platform supports ucontext_t (which is used in the extended signal API). */ +#define ACE_HAS_UCONTEXT_T 1 + +/* Platform has header file */ +#define ACE_HAS_UTIME 1 + +/* Prints out console message in ACE_NOTSUP. Useful for tracking down origin + of ACE_NOTSUP. */ +/* #undef ACE_HAS_VERBOSE_NOTSUP */ + +/* Platform requires void * for mmap(). */ +#define ACE_HAS_VOIDPTR_MMAP 1 + +/* Platform has XTI (X/Open-standardized superset of TLI). Implies + ACE_HAS_TLI but uses a different header file. */ +#define ACE_HAS_XTI 1 + +/* Platform can not build ace/IOStream{,_T}.cpp. This does not necessarily + mean that the platform does not support iostreams. */ +#define ACE_LACKS_ACE_IOSTREAM 1 + +/* Platform does not have u_longlong_t typedef */ +#define ACE_LACKS_U_LONGLONG_T 1 + +/* Platform lacks madvise() (e.g., Linux) */ +#define ACE_LACKS_MADVISE 1 + +/* Platform lacks pri_t (e.g., Tandem NonStop UNIX). */ +#define ACE_LACKS_PRI_T 1 + +/* Platform lacks pthread_thr_sigsetmask (e.g., MVS, HP/UX, and OSF/1 3.2) */ +#define ACE_LACKS_PTHREAD_THR_SIGSETMASK 1 + +/* Platfrom lack pthread_yield() support. */ +#define ACE_LACKS_PTHREAD_YIELD 1 + +/* Platform lacks readers/writer locks. */ +#define ACE_LACKS_RWLOCK_T 1 + +/* MIT pthreads platform lacks the timedwait prototypes */ +#define ACE_LACKS_TIMEDWAIT_PROTOTYPES 1 + +/* Platform does not define timepec_t as a typedef for struct timespec. */ +#define ACE_LACKS_TIMESPEC_T 1 + +/* Compile using multi-thread libraries */ +#define ACE_MT_SAFE 1 + +/* Platform needs to #include to get thread scheduling defs. */ +#define ACE_NEEDS_SCHED_H 1 + +/* The OS/platform supports the poll() event demultiplexor */ +#define ACE_USE_POLL 1 + +/* Platform has its standard c++ library in the namespace std. */ +#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 + +/* The number of bytes in a double. */ +#define SIZEOF_DOUBLE 8 + +/* The number of bytes in a float. */ +#define SIZEOF_FLOAT 4 + +/* The number of bytes in a int. */ +#define SIZEOF_INT 4 + +/* The number of bytes in a long. */ +#define SIZEOF_LONG 4 + +/* The number of bytes in a long double. */ +#define SIZEOF_LONG_DOUBLE 12 + +/* The number of bytes in a long long. */ +#define SIZEOF_LONG_LONG 8 + +/* The number of bytes in a short. */ +#define SIZEOF_SHORT 2 + +/* The number of bytes in a signed char. */ +#define SIZEOF_SIGNED_CHAR 1 + +/* The number of bytes in a void *. */ +#define SIZEOF_VOID_P 4 + +/* Define if you have the execv function. */ +#define HAVE_EXECV 1 + +/* Define if you have the execve function. */ +#define HAVE_EXECVE 1 + +/* Define if you have the execvp function. */ +#define HAVE_EXECVP 1 + +/* Define if you have the header file. */ +#define HAVE_DIRENT_H 1 + +/* Define if you have the header file. */ +#define HAVE_FSTREAM 1 + +/* Define if you have the header file. */ +#define HAVE_IOMANIP 1 + +/* Define if you have the header file. */ +#define HAVE_IOSTREAM 1 + +/* Define if you have the header file. */ +#define HAVE_PWD_H 1 + +/* Name of package */ +#define PACKAGE "ace" + +/* Version number of package */ +#define VERSION "4.6.37" + +/* Added by Staller */ +#define ENUM_BOOLEAN // See file /usr/local/lib/gcc-lib/i486-pc-sysv5/egcs-2.91.60/include/sys/types.h +/* Hat nix gebracht +#define ACE_DEFAULT_SELECT_REACTOR_SIZE 256 // this is like in linux config fileto avoid another error +*/ +#define howmany(x, y) (((x)+((y)-1))/(y)) +#define ACE_HAS_BROKEN_T_ERROR // let disappear a nasty warning from OS.i +#if !defined (__USLC__) +# define __USLC__ 1 +#endif + +#define __IOCTL_VERSIONED__ // By Carlo! +#endif /* ACE_UNIXWARE_UDK_H */ diff --git a/dep/acelite/ace/config-visualage.h b/dep/acelite/ace/config-visualage.h new file mode 100644 index 00000000000..4cef8108bc5 --- /dev/null +++ b/dep/acelite/ace/config-visualage.h @@ -0,0 +1,20 @@ +/* -*- C++ -*- */ +// $Id: config-visualage.h 80826 2008-03-04 14:51:23Z wotte $ + +// This configuration file automatically includes the proper +// configurations for IBM's VisualAge C++ compiler on Win32 and AIX. + +#ifndef CONFIG_VISUALAGE_H +#define CONFIG_VISUALAGE_H +#include /**/ "ace/pre.h" + +#ifdef __TOS_WIN__ + #include "ace/config-win32.h" +#elif __TOS_AIX__ + #include "ace/config-aix-4.x.h" +#else + #include "PLATFORM NOT SPECIFIED" +#endif /* __TOS_WIN__ */ + +#include /**/ "ace/post.h" +#endif //CONFIG_VISUALAGE_H diff --git a/dep/acelite/ace/config-vxworks.h b/dep/acelite/ace/config-vxworks.h new file mode 100644 index 00000000000..fd4e04193c0 --- /dev/null +++ b/dep/acelite/ace/config-vxworks.h @@ -0,0 +1,57 @@ +//* -*- C++ -*- */ +// $Id: config-vxworks.h 87036 2009-10-10 18:21:39Z johnnyw $ + +// The following configuration file is designed to work for VxWorks +// Based on ACE_VXWORKS it will select the correct config file + +#ifndef ACE_CONFIG_VXWORKS_H +#define ACE_CONFIG_VXWORKS_H +#include /**/ "ace/pre.h" + +// If ACE_VXWORKS is not defined try to figure out the VxWorks version +#if !defined (ACE_VXWORKS) +# include "vxWorks.h" +# if !defined (_WRS_VXWORKS_MAJOR) && !defined (_WRS_VXWORKS_MINOR) +# error You must define ACE_VXWORKS +# else +# if (_WRS_VXWORKS_MAJOR == 6) +# if (_WRS_VXWORKS_MINOR == 0) +# define ACE_VXWORKS 0x600 +# elif (_WRS_VXWORKS_MINOR == 1) +# define ACE_VXWORKS 0x610 +# elif (_WRS_VXWORKS_MINOR == 2) +# define ACE_VXWORKS 0x620 +# elif (_WRS_VXWORKS_MINOR == 3) +# define ACE_VXWORKS 0x630 +# elif (_WRS_VXWORKS_MINOR == 4) +# define ACE_VXWORKS 0x640 +# elif (_WRS_VXWORKS_MINOR == 5) +# define ACE_VXWORKS 0x650 +# elif (_WRS_VXWORKS_MINOR == 6) +# define ACE_VXWORKS 0x660 +# elif (_WRS_VXWORKS_MINOR == 7) +# define ACE_VXWORKS 0x670 +# elif (_WRS_VXWORKS_MINOR == 8) +# define ACE_VXWORKS 0x680 +# endif +# endif +# endif +#endif /* ! ACE_VXWORKS */ + +#if (ACE_VXWORKS == 0x640) +# include "ace/config-vxworks6.4.h" +#elif (ACE_VXWORKS == 0x650) +# include "ace/config-vxworks6.5.h" +#elif (ACE_VXWORKS == 0x660) +# include "ace/config-vxworks6.6.h" +#elif (ACE_VXWORKS == 0x670) +# include "ace/config-vxworks6.7.h" +#elif (ACE_VXWORKS == 0x680) +# include "ace/config-vxworks6.8.h" +#else +#error Unknown or unsupported VxWorks version +#endif + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_VXWORKS_H */ + diff --git a/dep/acelite/ace/config-vxworks6.4.h b/dep/acelite/ace/config-vxworks6.4.h new file mode 100644 index 00000000000..d1fad781985 --- /dev/null +++ b/dep/acelite/ace/config-vxworks6.4.h @@ -0,0 +1,350 @@ +//* -*- C++ -*- */ +// $Id: config-vxworks6.4.h 89494 2010-03-15 20:11:18Z olli $ + +// The following configuration file is designed to work for VxWorks +// 6.4 platforms using one of these compilers: +// 1) The GNU g++ compiler that is shipped with VxWorks 6.4 +// 2) The Diab compiler that is shipped with VxWorks 6.4 + +#ifndef ACE_CONFIG_VXWORKS_6_4_H +#define ACE_CONFIG_VXWORKS_6_4_H +#include /**/ "ace/pre.h" + +#if ! defined (VXWORKS) +# define VXWORKS +#endif /* ! VXWORKS */ + +#if ! defined (ACE_VXWORKS) +# define ACE_VXWORKS 0x640 +#endif /* ! ACE_VXWORKS */ + +#if !defined (__RTP__) + // Fix for wrong typedef of time_t in kernel mode + #ifndef _TIME_T + #define _TIME_T + typedef long time_t; + #endif +#endif + +#if ! defined (__ACE_INLINE__) +# define __ACE_INLINE__ +#endif /* ! __ACE_INLINE__ */ + +// Compiler-specific configuration. +#if defined (__GNUG__) +# include "ace/config-g++-common.h" + +# define ACE_LACKS_IOSTREAM_FX +# define ACE_LACKS_LINEBUFFERED_STREAMBUF + +# if defined (__RTP__) && !defined (_HAS_C9X) +// Workaround for the fact that under RTP the log2 method can't be used +// without this define set, see TSR560446 +# if !defined (_C99) +# define _C99 +# endif +# endif + +#elif defined (__DCC__) +# define ACE_HAS_STANDARD_CPP_LIBRARY 1 +# define ACE_TEMPLATES_REQUIRE_SOURCE +#else /* ! __GNUG__ && ! ghs && !__DCC__ */ +# ifdef __cplusplus /* Let it slide for C compilers. */ +# error unsupported compiler on VxWorks +# endif /* __cplusplus */ +#endif /* ! __GNUG__ && ! ghs */ + +// Needed include to get all VxWorks CPU types +#include "types/vxCpu.h" +#if defined __RTP__ + #if defined (_VX_CPU) && (_VX_CPU == _VX_PENTIUM || _VX_CPU == _VX_PENTIUM2 || _VX_CPU == _VX_PENTIUM3 || _VX_CPU == _VX_PENTIUM4) + // If running an Intel Pentium the + // ACE_OS::gethrtime () can use the RDTSC instruction. + # define ACE_HAS_PENTIUM + #endif +#else + #if defined (CPU) && (CPU == PENTIUM || CPU == PENTIUM2 || CPU == PENTIUM3 || CPU == PENTIUM4) + // If running an Intel Pentium the + // ACE_OS::gethrtime () can use the RDTSC instruction. + # define ACE_HAS_PENTIUM + #endif +#endif + +#if !defined __RTP__ +# if defined (TOOL) && (TOOL == gnu) +# if defined (CPU) && (CPU == PPC85XX || CPU == PPC604 || CPU == PPC603 || CPU == PPC32) +// These PPC's do lack log2 in kernel mode +# define ACE_LACKS_LOG2 +# endif +# endif +#endif + +// OS-specific configuration +#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG +#define ACE_HAS_3_PARAM_READDIR_R +#define ACE_HAS_NONCONST_GETBY +#define ACE_HAS_NONCONST_INET_ADDR +#define ACE_HAS_NONCONST_SWAB +#define ACE_USES_INETLIB_H +#define ACE_USES_SELECTLIB_H +#define ACE_LACKS_UNIX_SYSLOG +#define ACE_DEFAULT_MAX_SOCKET_BUFSIZ 32768 +#define ACE_DEFAULT_THREAD_KEYS 16 +#define ACE_HAS_BROKEN_ACCEPT_ADDR +#define ACE_HAS_NONCONST_SENDMSG +#define ACE_HAS_NONCONST_WRITEV +#define ACE_HAS_CHARPTR_DL +#define ACE_HAS_CLOCK_GETTIME +#define ACE_HAS_CLOCK_SETTIME +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES +#define ACE_HAS_CPLUSPLUS_HEADERS +#define ACE_HAS_DIRENT +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT +#define ACE_HAS_MSG +#define ACE_HAS_NONCONST_READV +#define ACE_HAS_NONCONST_SELECT_TIMEVAL +#define ACE_HAS_NONSTATIC_OBJECT_MANAGER +#define ACE_HAS_POSIX_NONBLOCK +#define ACE_HAS_POSIX_TIME +#define ACE_HAS_REENTRANT_FUNCTIONS +#define ACE_HAS_SIGACTION_CONSTP2 +#define ACE_HAS_SIGINFO_T +#define ACE_HAS_SIGWAIT +#define ACE_HAS_SIG_ATOMIC_T +#define ACE_HAS_SOCKADDR_IN_SIN_LEN +#define ACE_HAS_SOCKADDR_IN6_SIN6_LEN +#define ACE_HAS_THREADS +#define ACE_HAS_SYSCTL +#define ACE_LACKS_ALPHASORT +#define ACE_LACKS_EXEC +#define ACE_LACKS_RLIMIT +#define ACE_LACKS_FILELOCKS +#define ACE_LACKS_FORK +#define ACE_LACKS_GETHOSTENT +#define ACE_LACKS_GETSERVBYNAME +#define ACE_LACKS_GETPROTOBYNAME +#define ACE_LACKS_GETPROTOBYNUMBER +#define ACE_LACKS_GETIPNODEBYADDR +#define ACE_LACKS_GETIPNODEBYNAME_IPV6 +#define ACE_LACKS_LSTAT +#define ACE_LACKS_MADVISE +#define ACE_LACKS_MALLOC_H +#define ACE_LACKS_MEMORY_H +#define ACE_LACKS_MKFIFO +#define ACE_LACKS_MKSTEMP +#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS +#define ACE_LACKS_SYS_PARAM_H +#define ACE_LACKS_PWD_FUNCTIONS +#define ACE_LACKS_READLINK +#define ACE_LACKS_REALPATH +#define ACE_LACKS_PIPE +#define ACE_LACKS_RWLOCK_T +#define ACE_LACKS_SBRK +#define ACE_LACKS_SEEKDIR +#define ACE_LACKS_SEMBUF_T +#define ACE_LACKS_SIGINFO_H +#define ACE_LACKS_SI_ADDR +#define ACE_LACKS_SOCKETPAIR +#define ACE_LACKS_STRRECVFD +#define ACE_LACKS_SYSV_SHMEM +#define ACE_LACKS_TELLDIR +#define ACE_LACKS_TIMESPEC_T +#define ACE_LACKS_TRUNCATE +#define ACE_LACKS_UCONTEXT_H +#define ACE_LACKS_USECONDS_T +#define ACE_LACKS_UMASK +#define ACE_LACKS_STRPTIME +#define ACE_LACKS_MKTEMP +#define ACE_LACKS_TEMPNAM +#define ACE_PAGE_SIZE 4096 +#define ACE_THR_PRI_FIFO_DEF 101 +#define ACE_THR_PRI_OTHER_DEF ACE_THR_PRI_FIFO_DEF +#define ACE_HAS_SIGTIMEDWAIT +#define ACE_HAS_SIGSUSPEND +#define ACE_HAS_GETIFADDRS + +#define ACE_LACKS_SETEGID +#define ACE_LACKS_SETPGID +#define ACE_LACKS_SETREGID +#define ACE_LACKS_SETREUID +#define ACE_LACKS_SETSID +#define ACE_LACKS_SETUID +#define ACE_LACKS_SETEUID +#define ACE_LACKS_GETEUID +#define ACE_LACKS_GETUID +#define ACE_LACKS_GETPGID +#define ACE_LACKS_GETEGID +#define ACE_LACKS_GETGID +#define ACE_LACKS_SETGID + +#define ACE_LACKS_SYS_UIO_H +#define ACE_LACKS_SYS_IPC_H +#define ACE_LACKS_SYS_SEM_H +#define ACE_LACKS_STROPTS_H +#define ACE_LACKS_SYS_MSG_H +#define ACE_LACKS_PWD_H +#define ACE_LACKS_SYS_SHM_H +#define ACE_LACKS_TERMIOS_H +#define ACE_LACKS_POLL_H +#define ACE_LACKS_FCNTL + +// Some string things +#define ACE_LACKS_ITOW +#define ACE_LACKS_WCSDUP +#define ACE_LACKS_WCSICMP +#define ACE_LACKS_WCSNICMP +#define ACE_LACKS_STRTOLL +#define ACE_LACKS_WCSTOLL +#define ACE_LACKS_STRTOULL +#define ACE_LACKS_WCSTOULL + +#define ACE_HAS_CHARPTR_SOCKOPT +#define ACE_LACKS_SYMLINKS +#define ACE_LACKS_ISCTYPE + +#if defined __RTP__ + // We are building for RTP mode + #if !defined (ACE_AS_STATIC_LIBS) + # define ACE_HAS_SVR4_DYNAMIC_LINKING + #endif + #define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R + #define ACE_LACKS_REGEX_H + #if defined ACE_HAS_PENTIUM + // Bug to workaround VxWorks 6.4 x86 + # define ACE_LACKS_PUTENV + #endif + #define ACE_HAS_SETENV + #define ACE_LACKS_STRCASECMP + #define ACE_HAS_3_PARAM_WCSTOK + #define ACE_HAS_WCHAR + #define ACE_HAS_VFWPRINTF + #define ACE_SIZEOF_WCHAR 2 + #define ACE_HAS_SHM_OPEN + #if defined (ACE_AS_STATIC_LIBS) + # define ACE_HAS_AIO_CALLS + #endif + // VxWorks seems to either not define this or define as zero up till now + #if !defined (IOV_MAX) || (IOV_MAX == 0) + #define ACE_IOV_MAX 16 + #endif + #define ACE_LACKS_ISASCII +#else + // We are building for kernel mode + #define ACE_LACKS_SETENV + #define ACE_LACKS_UNSETENV + #define ACE_LACKS_SUSECONDS_T + #define ACE_LACKS_INTPTR_T + #define ACE_LACKS_INTTYPES_H + #define ACE_LACKS_STDINT_H + #define ACE_LACKS_UNAME + #define ACE_LACKS_UTSNAME_T + #define ACE_LACKS_RAND_REENTRANT_FUNCTIONS + #define ACE_LACKS_DLFCN_H + #define ACE_LACKS_WAIT + #define ACE_LACKS_WAITPID + #define ACE_LACKS_SYS_TIME_H + #define ACE_LACKS_SYS_SELECT_H + #define ACE_MKDIR_LACKS_MODE + #define ACE_HAS_SIZET_PTR_ASCTIME_R_AND_CTIME_R + #define ACE_LACKS_SEARCH_H + #define ACE_LACKS_SYSCONF + #define ACE_LACKS_GETPPID + #define ACE_LACKS_WCHAR_H + #define ACE_LACKS_WCTYPE_H + #define ACE_LACKS_WCSCAT + #define ACE_LACKS_WCSCHR + #define ACE_LACKS_WCSCMP + #define ACE_LACKS_WCSCPY + #define ACE_LACKS_WCSCSPN + #define ACE_LACKS_WCSLEN + #define ACE_LACKS_WCSNCAT + #define ACE_LACKS_WCSNCMP + #define ACE_LACKS_WCSNCPY + #define ACE_LACKS_WCSPBRK + #define ACE_LACKS_WCSRCHR + #define ACE_LACKS_WCSSPN + #define ACE_LACKS_WCSSTR + #define ACE_LACKS_WCSTOK + #define ACE_LACKS_TOWLOWER + #define ACE_LACKS_TOWUPPER + #define ACE_LACKS_WCSTOD + #define ACE_LACKS_WCSTOL + #define ACE_LACKS_WCSTOUL + #define ACE_LACKS_FGETWC + #define ACE_LACKS_FGETWS + #define ACE_LACKS_FPUTWS + #define ACE_HAS_IOCTL_INT_3_PARAM + #define ACE_LACKS_MMAP + #define ACE_LACKS_MSYNC + #define ACE_LACKS_MPROTECT + #if !defined (ACE_MAIN) + # define ACE_MAIN ace_main + #endif /* ! ACE_MAIN */ + #define ACE_LACKS_TZSET + #define ACE_LACKS_ISWCTYPE + #define ACE_LACKS_ISBLANK +#endif + +// It is possible to enable pthread support with VxWorks, when the user decides +// to use this, we need some more defines +#if defined ACE_HAS_PTHREADS +# define ACE_HAS_THREAD_SPECIFIC_STORAGE +# if !defined __RTP__ +# define ACE_LACKS_PTHREAD_ATTR_SETSTACK +# endif +# define ACE_HAS_PTHREAD_ATTR_SETNAME +# define ACE_HAS_POSIX_SEM +# define ACE_LACKS_MUTEXATTR_PSHARED +# define ACE_LACKS_CONDATTR_PSHARED +// Include this file, the sys/stat.h file shipped with VxWorks has old types +// and without this include we get a lot of compile errors. A TSR has been filed +// so that hopefully in the future we can zap this include +#include "types/vxTypesOld.h" +#else +# define ACE_LACKS_PTHREAD_H +# define ACE_HAS_VXTHREADS +# if !defined __RTP__ +// Only when building for kernel mode we can use TSS emulation, in rtp mode +// we can't use the WIND_TCB struct anymore +# define ACE_HAS_TSS_EMULATION +# if !defined (ACE_VXWORKS_SPARE) +# define ACE_VXWORKS_SPARE spare4 +# endif /* ! ACE_VXWORKS_SPARE */ +# endif +// VxWorks has no recursive mutexes. This was set in the past but it doesn't +// work with the pthread support, so only set it for the time being when pthread +// is disabled +# define ACE_HAS_RECURSIVE_MUTEXES +# define ACE_LACKS_COND_T +# define ACE_HAS_MUTEX_TIMEOUTS +#endif + +#if !defined (ACE_MT_SAFE) +# define ACE_MT_SAFE 1 +#endif + +// VxWorks defines the CPU define MAP, undef it to prevent problems with +// application code +#if defined (MAP) +#undef MAP +#endif /* MAP */ + +#if !defined (ACE_NEEDS_HUGE_THREAD_STACKSIZE) +# define ACE_NEEDS_HUGE_THREAD_STACKSIZE 65536 +#endif /* ACE_NEEDS_HUGE_THREAD_STACKSIZE */ + +#if !defined (ACE_NTRACE) +# define ACE_NTRACE 1 +#endif /* ACE_NTRACE */ + +// By default, don't include RCS Id strings in object code. +#if !defined (ACE_USE_RCSID) +#define ACE_USE_RCSID 0 +#endif /* !ACE_USE_RCSID */ + +#if defined (ACE_HAS_IP_MULTICAST) +# define ACE_LACKS_PERFECT_MULTICAST_FILTERING 1 +#endif /* ACE_HAS_IP_MULTICAST */ + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_VXWORKS_6_4_H */ diff --git a/dep/acelite/ace/config-vxworks6.5.h b/dep/acelite/ace/config-vxworks6.5.h new file mode 100644 index 00000000000..19273e6cad4 --- /dev/null +++ b/dep/acelite/ace/config-vxworks6.5.h @@ -0,0 +1,25 @@ +//* -*- C++ -*- */ +// $Id: config-vxworks6.5.h 80826 2008-03-04 14:51:23Z wotte $ + +// The following configuration file is designed to work for VxWorks +// 6.5 platforms using one of these compilers: +// 1) The GNU g++ compiler that is shipped with VxWorks 6.5 +// 2) The Diab compiler that is shipped with VxWorks 6.5 + +#ifndef ACE_CONFIG_VXWORKS_6_5_H +#define ACE_CONFIG_VXWORKS_6_5_H +#include /**/ "ace/pre.h" + +#if !defined (ACE_VXWORKS) +# define ACE_VXWORKS 0x650 +#endif /* ! ACE_VXWORKS */ + +#include "ace/config-vxworks6.4.h" + +#if defined (__RTP__) +# undef ACE_HAS_GETIFADDRS +#endif + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_VXWORKS_6_5_H */ + diff --git a/dep/acelite/ace/config-vxworks6.6.h b/dep/acelite/ace/config-vxworks6.6.h new file mode 100644 index 00000000000..eebce4432b6 --- /dev/null +++ b/dep/acelite/ace/config-vxworks6.6.h @@ -0,0 +1,34 @@ +//* -*- C++ -*- */ +// $Id: config-vxworks6.6.h 85143 2009-04-22 09:15:08Z johnnyw $ + +// The following configuration file is designed to work for VxWorks +// 6.6 platforms using one of these compilers: +// 1) The GNU g++ compiler that is shipped with VxWorks 6.6 +// 2) The Diab compiler that is shipped with VxWorks 6.6 + +#ifndef ACE_CONFIG_VXWORKS_6_6_H +#define ACE_CONFIG_VXWORKS_6_6_H +#include /**/ "ace/pre.h" + +#if !defined (ACE_VXWORKS) +# define ACE_VXWORKS 0x660 +#endif /* ! ACE_VXWORKS */ + +#include "ace/config-vxworks6.5.h" + +#if defined (ACE_HAS_PENTIUM) +# define ACE_LACKS_LOG2 +#endif + +#if !defined (__RTP__) +# undef ACE_HAS_IOCTL_INT_3_PARAM +# define ACE_HAS_TASKCPUAFFINITYSET +#endif + +#define ACE_HAS_VXATOMICLIB +#define ACE_HAS_CPUSET_T +#define ACE_HAS_VXCPULIB + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_VXWORKS_6_6_H */ + diff --git a/dep/acelite/ace/config-vxworks6.7.h b/dep/acelite/ace/config-vxworks6.7.h new file mode 100644 index 00000000000..eab429a2e94 --- /dev/null +++ b/dep/acelite/ace/config-vxworks6.7.h @@ -0,0 +1,23 @@ +//* -*- C++ -*- */ +// $Id: config-vxworks6.7.h 84971 2009-03-25 13:03:44Z johnnyw $ + +// The following configuration file is designed to work for VxWorks +// 6.7 platforms using one of these compilers: +// 1) The GNU g++ compiler that is shipped with VxWorks 6.7 +// 2) The Diab compiler that is shipped with VxWorks 6.7 + +#ifndef ACE_CONFIG_VXWORKS_6_7_H +#define ACE_CONFIG_VXWORKS_6_7_H +#include /**/ "ace/pre.h" + +#if !defined (ACE_VXWORKS) +# define ACE_VXWORKS 0x670 +#endif /* ! ACE_VXWORKS */ + +#include "ace/config-vxworks6.6.h" + +#undef ACE_HAS_NONCONST_INET_ADDR + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_VXWORKS_6_7_H */ + diff --git a/dep/acelite/ace/config-vxworks6.8.h b/dep/acelite/ace/config-vxworks6.8.h new file mode 100644 index 00000000000..ecad4752d95 --- /dev/null +++ b/dep/acelite/ace/config-vxworks6.8.h @@ -0,0 +1,21 @@ +//* -*- C++ -*- */ +// $Id: config-vxworks6.8.h 87036 2009-10-10 18:21:39Z johnnyw $ + +// The following configuration file is designed to work for VxWorks +// 6.8 platforms using one of these compilers: +// 1) The GNU g++ compiler that is shipped with VxWorks 6.8 +// 2) The Diab compiler that is shipped with VxWorks 6.8 + +#ifndef ACE_CONFIG_VXWORKS_6_8_H +#define ACE_CONFIG_VXWORKS_6_8_H +#include /**/ "ace/pre.h" + +#if !defined (ACE_VXWORKS) +# define ACE_VXWORKS 0x680 +#endif /* ! ACE_VXWORKS */ + +#include "ace/config-vxworks6.7.h" + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_VXWORKS_6_8_H */ + diff --git a/dep/acelite/ace/config-win32-borland.h b/dep/acelite/ace/config-win32-borland.h new file mode 100644 index 00000000000..c3ae460482b --- /dev/null +++ b/dep/acelite/ace/config-win32-borland.h @@ -0,0 +1,174 @@ +// -*- C++ -*- +//$Id: config-win32-borland.h 89292 2010-03-04 08:06:15Z johnnyw $ + +// The following configuration file contains defines for Borland compilers. + +#ifndef ACE_CONFIG_WIN32_BORLAND_H +#define ACE_CONFIG_WIN32_BORLAND_H +#include /**/ "ace/pre.h" + +#ifndef ACE_CONFIG_WIN32_H +#error Use config-win32.h in config.h instead of this header +#endif /* ACE_CONFIG_WIN32_H */ + +#define ACE_HAS_CUSTOM_EXPORT_MACROS +#define ACE_Proper_Export_Flag __declspec (dllexport) +#define ACE_Proper_Import_Flag __declspec (dllimport) +#define ACE_EXPORT_SINGLETON_DECLARATION(T) template class __declspec (dllexport) T +#define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) template class __declspec (dllexport) SINGLETON_TYPE; +#define ACE_IMPORT_SINGLETON_DECLARATION(T) template class __declspec (dllimport) T +#define ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) template class __declspec (dllimport) SINGLETON_TYPE ; + +// In later versions of C++Builder we will prefer inline functions by +// default. The debug configuration of ACE is built with functions +// out-of-line, so when linking your application against a debug ACE +// build, you can choose to use the out-of-line functions by adding +// ACE_NO_INLINE=1 to your project settings. +# if !defined (__ACE_INLINE__) +# define __ACE_INLINE__ 1 +# endif /* __ACE_INLINE__ */ + +# define ACE_CC_NAME ACE_TEXT ("Embarcadero C++ Builder") +# define ACE_CC_MAJOR_VERSION (__BORLANDC__ / 0x100) +# define ACE_CC_MINOR_VERSION (__BORLANDC__ % 0x100) +# define ACE_CC_BETA_VERSION (0) + +#ifndef ACE_USING_MCPP_PREPROCESSOR +# if (__BORLANDC__ >= 0x620) +# define ACE_CC_PREPROCESSOR_ARGS "-q -Sl -o%s" +# else +# define ACE_CC_PREPROCESSOR_ARGS "-q -P- -o%s" +# endif +#endif + +// Automatically define WIN32 macro if the compiler tells us it is our +// target platform. +# if defined (__WIN32__) && !defined (WIN32) +# define WIN32 1 +# endif + +// When building a VCL application, the main VCL header file should be +// included before anything else. You can define ACE_HAS_VCL=1 in your +// project settings to have this file included for you automatically. +# if defined (ACE_HAS_VCL) && (ACE_HAS_VCL != 0) +# include /**/ +# endif + +# define ACE_CC_PREPROCESSOR "CPP32.EXE" + +# include "ace/config-win32-common.h" + +# define ACE_WSTRING_HAS_USHORT_SUPPORT 1 +# define ACE_HAS_DIRENT + +#define ACE_USES_STD_NAMESPACE_FOR_STDC_LIB 1 + +#define ACE_NEEDS_DL_UNDERSCORE + +#define ACE_LACKS_TERMIOS_H +#define ACE_LACKS_NETINET_TCP_H +#define ACE_LACKS_REGEX_H +#define ACE_LACKS_SYS_MSG_H +#define ACE_LACKS_PWD_H +#define ACE_LACKS_POLL_H +#define ACE_LACKS_SYS_SHM_H +#define ACE_LACKS_STRINGS_H +#define ACE_LACKS_SEMAPHORE_H +#define ACE_LACKS_INTTYPES_H +#define ACE_LACKS_UCONTEXT_H +#define ACE_LACKS_SYS_SELECT_H +#define ACE_LACKS_SYS_TIME_H +#define ACE_LACKS_SYS_RESOURCE_H +#define ACE_LACKS_SYS_WAIT_H +#define ACE_LACKS_DLFCN_H +#define ACE_LACKS_SYS_MMAN_H +#define ACE_LACKS_SYS_UIO_H +#define ACE_LACKS_SYS_SOCKET_H +#define ACE_LACKS_NETINET_IN_H +#define ACE_LACKS_NETDB_H +#define ACE_LACKS_NET_IF_H +#define ACE_LACKS_SYS_IPC_H +#define ACE_LACKS_SYS_SEM_H +#define ACE_LACKS_SYS_IOCTL_H +#define ACE_LACKS_STROPTS_H + +#undef ACE_LACKS_STRUCT_DIR +#undef ACE_LACKS_CLOSEDIR +#undef ACE_LACKS_OPENDIR +#undef ACE_LACKS_READDIR +#undef ACE_LACKS_REWINDDIR + +#define ACE_HAS_WOPENDIR +#define ACE_HAS_WCLOSEDIR +#define ACE_HAS_WREADDIR +#define ACE_HAS_WREWINDDIR + +#define ACE_LACKS_STRRECVFD +#define ACE_USES_EXPLICIT_STD_NAMESPACE + +#define ACE_HAS_TIME_T_LONG_MISMATCH + +#define ACE_EXPORT_NESTED_CLASSES 1 +#define ACE_HAS_CPLUSPLUS_HEADERS 1 +#define ACE_HAS_EXCEPTIONS +#define ACE_HAS_NONCONST_SELECT_TIMEVAL +#define ACE_HAS_SIG_ATOMIC_T +#define ACE_HAS_STANDARD_CPP_LIBRARY 1 +#define ACE_HAS_STDCPP_STL_INCLUDES 1 +#define ACE_HAS_STRING_CLASS 1 +#define ACE_HAS_TEMPLATE_TYPEDEFS 1 +#define ACE_HAS_USER_MODE_MASKS 1 +#define ACE_LACKS_ACE_IOSTREAM 1 +#define ACE_LACKS_LINEBUFFERED_STREAMBUF 1 +#define ACE_HAS_NEW_NOTHROW +#define ACE_TEMPLATES_REQUIRE_SOURCE 1 +#define ACE_SIZEOF_LONG_DOUBLE 10 +#define ACE_UINT64_FORMAT_SPECIFIER_ASCII "%Lu" +#define ACE_INT64_FORMAT_SPECIFIER_ASCII "%Ld" +#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 +#define ACE_USES_STD_NAMESPACE_FOR_ABS 1 +#define ACE_ENDTHREADEX(STATUS) ::_endthreadex ((DWORD) STATUS) + +#if defined(ACE_MT_SAFE) && (ACE_MT_SAFE != 0) +// must have _MT defined to include multithreading +// features from win32 headers +# if !defined(__MT__) +// *** DO NOT *** defeat this error message by defining __MT__ yourself. +// You must link with the multi threaded libraries. Add -tWM to your +// compiler options +# error You must link against multi-threaded libraries when using ACE (check your project settings) +# endif /* !_MT && !ACE_HAS_WINCE */ +#endif /* ACE_MT_SAFE && ACE_MT_SAFE != 0 */ + +#if (__BORLANDC__ < 0x620) +# define ACE_LACKS_ISBLANK +# define ACE_LACKS_ISWBLANK +# define ACE_LACKS_PRAGMA_ONCE 1 +#endif + +#define ACE_LACKS_ISWCTYPE +#define ACE_LACKS_ISCTYPE + +#if (__BORLANDC__ < 0x620) +// Older Borland compilers can't handle assembly in inline methods or +// templates (E2211). When we build for pentium optimized and we are inlining +// then we disable inline assembly +# if defined (ACE_HAS_PENTIUM) && defined(__ACE_INLINE__) +# define ACE_LACKS_INLINE_ASSEMBLY +# endif +#endif + +#if (__BORLANDC__ == 0x621) +// C++ Builder 2010 wcsncat seems broken +# define ACE_LACKS_WCSNCAT +#endif + +#define ACE_WCSDUP_EQUIVALENT ::_wcsdup +#define ACE_STRCASECMP_EQUIVALENT ::stricmp +#define ACE_STRNCASECMP_EQUIVALENT ::strnicmp +#define ACE_WTOF_EQUIVALENT ::_wtof +#define ACE_FILENO_EQUIVALENT(X) (_get_osfhandle (::_fileno (X))) +#define ACE_HAS_ITOA 1 + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_WIN32_BORLAND_H */ diff --git a/dep/acelite/ace/config-win32-cegcc.h b/dep/acelite/ace/config-win32-cegcc.h new file mode 100644 index 00000000000..c29290d713f --- /dev/null +++ b/dep/acelite/ace/config-win32-cegcc.h @@ -0,0 +1,113 @@ +// -*- C++ -*- +// $Id: config-win32-cegcc.h 87167 2009-10-19 19:33:53Z olli $ + +// +// The following configuration file is designed to work for win32 +// platforms using gcc/g++ with mingw32 (http://www.mingw.org). +// + +#ifndef ACE_CONFIG_WIN32_CEGCC_H +#define ACE_CONFIG_WIN32_CEGCC_H +#include /**/ "ace/pre.h" + +#ifndef ACE_CONFIG_WIN32_H +# error Use config-win32.h in config.h instead of this header +#endif /* ACE_CONFIG_WIN32_H */ + +#define ACE_CC_NAME ACE_TEXT ("g++") +#define ACE_CC_PREPROCESSOR "cpp" +#define ACE_CC_PREPROCESOR_ARGS "" + +// Why all this is not in config-g++-common.h? +#define ACE_CC_MAJOR_VERSION __GNUC__ +#define ACE_CC_MINOR_VERSION __GNUC_MINOR__ +#define ACE_CC_BETA_VERSION (0) + +#if !defined (ACE_HAS_CEGCC) +# error You do not seem to be using cegcc +#endif + +// We trust the user: He must have used -mpentiumpro or -mpentium +// if that is what he wants. +#if defined(pentiumpro) || defined(pentium) +# define ACE_HAS_PENTIUM +#endif + +#include "ace/config-g++-common.h" + +#include /**/ +#include /**/ +#include /**/ <_mingw.h> + +#if (__MINGW32_MAJOR_VERSION > 3) || ((__MINGW32_MAJOR_VERSION == 3) && (__MINGW32_MINOR_VERSION >= 15)) +# undef ACE_LACKS_USECONDS_T +#endif + +#define ACE_HAS_USER_MODE_MASKS + +#define ACE_HAS_SSIZE_T +#undef ACE_LACKS_STRUCT_DIR +#undef ACE_LACKS_OPENDIR +#undef ACE_LACKS_CLOSEDIR +#undef ACE_LACKS_READDIR +#undef ACE_LACKS_TELLDIR +#undef ACE_LACKS_SEEKDIR +#undef ACE_LACKS_REWINDDIR + +#undef ACE_HAS_WTOF + +#define ACE_LACKS_SYS_SHM_H +#define ACE_LACKS_TERMIOS_H +#define ACE_LACKS_NETINET_TCP_H +#define ACE_LACKS_STRRECVFD +#define ACE_LACKS_STRPTIME +#define ACE_LACKS_POLL_H +#define ACE_LACKS_REGEX_H +#define ACE_LACKS_SYS_MSG_H +#define ACE_LACKS_PWD_H +#define ACE_LACKS_SEMAPHORE_H +#define ACE_LACKS_UCONTEXT_H +#define ACE_LACKS_SYS_SELECT_H +#define ACE_LACKS_SYS_RESOURCE_H +#define ACE_LACKS_SYS_WAIT_H +#define ACE_LACKS_DLFCN_H +#define ACE_LACKS_SYS_MMAN_H +#define ACE_LACKS_SYS_UIO_H +#define ACE_LACKS_SYS_SOCKET_H +#define ACE_LACKS_NETINET_IN_H +#define ACE_LACKS_NETDB_H +#define ACE_LACKS_NET_IF_H +#define ACE_LACKS_SYS_IPC_H +#define ACE_LACKS_SYS_SEM_H +#define ACE_LACKS_STROPTS_H +#define ACE_LACKS_SYS_IOCTL_H +#define ACE_LACKS_PDH_H +#define ACE_LACKS_PDHMSG_H +#define ACE_HAS_NONCONST_WCSDUP +#define ACE_HAS_WINSOCK2_GQOS +#define ACE_LACKS_CORRECT_ISWPRINT_TAB + +//Changes to compile on CE gcc. +#undef ACE_HAS_TYPES_H +#define ACE_LACKS_ERRNO_H +#undef ACE_LACKS_DEV_T +#define ACE_LACKS_ISCTYPE +#define ACE_HAS_NONCONST_WFDOPEN +#undef ACE_HAS_WTOI +#undef ACE_HAS_WTOL + +#define ACE_INT64_FORMAT_SPECIFIER_ASCII "%I64d" +#define ACE_UINT64_FORMAT_SPECIFIER_ASCII "%I64u" +#define ACE_ENDTHREADEX(STATUS) ExitThread ((DWORD) STATUS) + +#define ACE_Proper_Export_Flag __declspec (dllexport) +#define ACE_Proper_Import_Flag __declspec (dllimport) +#define ACE_EXPORT_SINGLETON_DECLARATION(T) template class __declspec (dllexport) T +#define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) template class __declspec (dllexport) SINGLETON_TYPE; +#define ACE_IMPORT_SINGLETON_DECLARATION(T) extern template class T +#define ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) extern template class SINGLETON_TYPE ; + +#define ACE_DLL_PREFIX ACE_TEXT ("lib") + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_WIN32_CEGCC_H */ diff --git a/dep/acelite/ace/config-win32-common.h b/dep/acelite/ace/config-win32-common.h new file mode 100644 index 00000000000..0160a3742a1 --- /dev/null +++ b/dep/acelite/ace/config-win32-common.h @@ -0,0 +1,701 @@ +/* -*- C++ -*- */ +// $Id: config-win32-common.h 88567 2010-01-15 10:21:49Z olli $ + + +#ifndef ACE_CONFIG_WIN32_COMMON_H +#define ACE_CONFIG_WIN32_COMMON_H +#include /**/ "ace/pre.h" + +#ifndef ACE_CONFIG_WIN32_H +#error Use config-win32.h in config.h instead of this header +#endif /* ACE_CONFIG_WIN32_H */ + + +// Windows Mobile (CE) stuff is primarily further restrictions to what's +// in the rest of this file. Also, it defined ACE_HAS_WINCE, which is used +// in this file. +#if defined (_WIN32_WCE) +# include "ace/config-WinCE.h" +#endif /* _WIN32_WCE */ + +// Complain if WIN32 is not already defined. +#if !defined (WIN32) && !defined (ACE_HAS_WINCE) +# error Please define WIN32 in your project settings. +#endif + +#define ACE_WIN32 +#if defined (_WIN64) || defined (WIN64) +# define ACE_WIN64 + +// Use 64-bit file offsets by default in the WIN64 case, similar to +// what 64-bit UNIX systems do. +// +// Note that _FILE_OFFSET_BITS is not recognized by Windows. It is, +// however, recognized by ACE. +# ifndef _FILE_OFFSET_BITS +# define _FILE_OFFSET_BITS 64 +# endif /* !_FILE_OFFSET_BITS */ +#endif /* _WIN64 || WIN64 */ + +#if !defined (_WIN32_WINNT) +# define _WIN32_WINNT 0x0501 // pretend it's at least Windows XP or Win2003 +#endif + +// If the invoking procedure turned off debugging by setting NDEBUG, then +// also set ACE_NDEBUG, unless the user has already set it. +#if defined (NDEBUG) +# if !defined (ACE_NDEBUG) +# define ACE_NDEBUG +# endif /* ACE_NDEBUG */ +#endif /* NDEBUG */ + +// Define ACE_HAS_MFC to 1, if you want ACE to use CWinThread. This should +// be defined, if your application uses MFC. +// Setting applies to : building ACE +// Runtime restrictions: MFC DLLs must be installed +// Additonal notes : If both ACE_HAS_MFC and ACE_MT_SAFE are +// defined, the MFC DLL (not the static lib) +// will be used from ACE. +#if !defined (ACE_HAS_MFC) +# define ACE_HAS_MFC 0 +#endif + +// ACE_USES_STATIC_MFC always implies ACE_HAS_MFC +#if defined (ACE_USES_STATIC_MFC) +# if defined (ACE_HAS_MFC) +# undef ACE_HAS_MFC +# endif +# define ACE_HAS_MFC 1 +#endif /* ACE_USES_STATIC_MFC */ + +// Define ACE_HAS_STRICT to 1 in your config.h file if you want to use +// STRICT type checking. It is disabled by default because it will +// break existing application code. However, if ACE_HAS_MFC is turned on, +// ACE_HAS_STRICT is required by MFC. +// Setting applies to : building ACE, linking with ACE +// Runtime restrictions: - +#if !defined (ACE_HAS_STRICT) +# define ACE_HAS_STRICT 0 +#endif + +// MFC itself defines STRICT. +#if defined (ACE_HAS_MFC) && (ACE_HAS_MFC != 0) +# undef ACE_HAS_STRICT +# define ACE_HAS_STRICT 1 +#endif + +// Turn off the following define if you want to disable threading. +// Compile using multi-thread libraries. +// Setting applies to : building ACE, linking with ACE +// Runtime restrictions: multithreaded runtime DLL must be installed +#if !defined (ACE_MT_SAFE) +# define ACE_MT_SAFE 1 +#endif + +// On winCE these classes do not exist. If they are +// introduced in the future, no changes need to be made +#if defined (ABOVE_NORMAL_PRIORITY_CLASS) && \ + defined (BELOW_NORMAL_PRIORITY_CLASS) && \ + defined (HIGH_PRIORITY_CLASS) && \ + defined (IDLE_PRIORITY_CLASS) && \ + defined (NORMAL_PRIORITY_CLASS) && \ + defined (REALTIME_PRIORITY_CLASS) +#define ACE_HAS_WIN32_PRIORITY_CLASS +#endif + +// Build ACE services as DLLs. If you write a library and want it to +// use ACE_Svc_Export, this will cause those macros to build dlls. If +// you want your ACE service to be a static library, comment out this +// line. As far as I know, the only reason to have a library be an +// ACE "service" is to leverage the ACE_Svc_Export macros. It's just +// as easy to define your own export macros. +// #if !defined (ACE_SVC_HAS_DLL) +// # define ACE_SVC_HAS_DLL 1 +// #endif + +// Define the special export macros needed to export symbols outside a dll +#if !defined(__BORLANDC__) && !defined (ACE_HAS_CUSTOM_EXPORT_MACROS) +#define ACE_HAS_CUSTOM_EXPORT_MACROS 1 +#define ACE_Proper_Export_Flag __declspec (dllexport) +#define ACE_Proper_Import_Flag __declspec (dllimport) +#define ACE_EXPORT_SINGLETON_DECLARATION(T) template class __declspec (dllexport) T +#define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) template class __declspec (dllexport) SINGLETON_TYPE; +#define ACE_IMPORT_SINGLETON_DECLARATION(T) extern template class T +#define ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) extern template class SINGLETON_TYPE ; +#endif /* !__BORLANDC__ */ + +// Define ACE_HAS_WINSOCK2 to 0 in your config.h file if you do *not* +// want to compile with WinSock 2.0. +// Setting applies to : building ACE +// Runtime restrictions: winsock2 must be installed. +// #define ACE_HAS_WINSOCK2 0 + +// By default, we use non-static object manager on Win32. That is, +// the object manager is allocated in main's stack memory. If this +// does not suit your need, i.e., if your programs depend on the use +// of static object manager, you neet to disable the behavior by adding +// +// #undef ACE_HAS_NONSTATIC_OBJECT_MANAGER +// +// in the config.h after including config-win32.h +// +// MFC users: the main function is defined within a MFC library and +// therefore, ACE won't be able to meddle with main function and +// instantiate the non-static object manager for you. To solve the +// problem, you'll need to instantiate the ACE_Object_Manager by +// either: +// +// 1. Using static object manager (as described above), however, using +// the non-static object manager is prefered, therefore, +// 2. Instantiate the non-static object manager yourself by either 1) +// call ACE::init () at the beginning and ACE::fini () at the end, +// _or_ 2) instantiate the ACE_Object_Manager in your CWinApp +// derived class. +// +// Optionally, you can #define +// ACE_DOESNT_INSTANTIATE_NONSTATIC_OBJECT_MANAGER in your +// ace/config.h and always take care of the business by yourself. +// ACE_DOESNT_INSTANTIATE_NONSTATIC_OBJECT_MANAGER has no effect when +// using static object managers. +#if !defined (ACE_HAS_NONSTATIC_OBJECT_MANAGER) +# define ACE_HAS_NONSTATIC_OBJECT_MANAGER +#endif /* ACE_HAS_NONSTATIC_OBJECT_MANAGER */ + +#define ACE_HAS_GPERF + +// By default, don't include RCS Id strings in object code. +#if !defined (ACE_USE_RCSID) +# define ACE_USE_RCSID 0 +#endif /* ! ACE_USE_RCSID */ + +// ---------------- platform features or lack of them ------------- + +// By default WIN32 has FD_SETSIZE of 64, which places the limit +// between 61 and 64 on the number of clients a server using the +// Select Reactor can support at the same time (i.e., 64 - standard in, +// out, error). Here we raise the limit to 1024. Adjust the definition +// below if you need to raise or lower it. + +#if !defined (FD_SETSIZE) +#define FD_SETSIZE 1024 +#endif /* FD_SETSIZE */ + + +// Windows doesn't like 65536 ;-) If 65536 is specified, it is +// silently ignored by the OS, i.e., setsockopt does not fail, and you +// get stuck with the default size of 8k. +#define ACE_DEFAULT_MAX_SOCKET_BUFSIZ 65535 + +// It seems like Win32 does not have a limit on the number of buffers +// that can be transferred by the scatter/gather type of I/O +// functions, e.g., WSASend and WSARecv. We are setting this to be 64 +// for now. The typically use case is to create an I/O vector array +// of size ACE_IOV_MAX on the stack and then filled in. Note that we +// probably don't want too big a value for ACE_IOV_MAX since it may +// mostly go to waste or the size of the activation record may become +// excessively large. +#if !defined (ACE_IOV_MAX) +# define ACE_IOV_MAX 64 +#endif /* ACE_IOV_MAX */ + +#if !defined (ACE_HAS_WINCE) +// Platform supports pread() and pwrite() +# define ACE_HAS_WTOF +#endif /* ! ACE_HAS_WINCE */ + +#define ACE_HAS_P_READ_WRITE + +#if !defined (ACE_HAS_WINCE) +# define ACE_HAS_DIRECT_H +# define ACE_HAS_PROCESS_H +# define ACE_HAS_IO_H +#endif /* ! ACE_HAS_WINCE */ + +#if !defined (__MINGW32__) +# define ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS +#endif /* __MINGW32__ */ + +#define ACE_DEFAULT_THREAD_PRIORITY 0 + +#define ACE_HAS_DIRENT +#define ACE_HAS_MSG +#define ACE_HAS_RECURSIVE_MUTEXES +#define ACE_HAS_SOCKADDR_MSG_NAME +#define ACE_HAS_THREAD_SAFE_ACCEPT + +/* LACKS dir-related facilities */ +#define ACE_LACKS_READDIR_R +#define ACE_LACKS_REWINDDIR +#define ACE_LACKS_SEEKDIR +#define ACE_LACKS_TELLDIR + +/* LACKS gid/pid/sid/uid facilities */ +#define ACE_LACKS_GETPGID +#define ACE_LACKS_GETPPID +#define ACE_LACKS_SETPGID +#define ACE_LACKS_SETREGID +#define ACE_LACKS_SETREUID +#define ACE_LACKS_SETSID +#define ACE_LACKS_SETEGID +#define ACE_LACKS_SETUID +#define ACE_LACKS_SETEUID +#define ACE_LACKS_GETGID +#define ACE_LACKS_GETEGID +#define ACE_LACKS_GETUID +#define ACE_LACKS_GETEUID +#define ACE_LACKS_SETGID + +/* LACKS miscellaneous */ +#define ACE_LACKS_ALARM +#define ACE_LACKS_ARPA_INET_H +#define ACE_LACKS_DUP2 +#define ACE_LACKS_FORK +#define ACE_LACKS_GETHOSTENT +#define ACE_LACKS_GETOPT +#define ACE_LACKS_GETIPNODEBYNAME_IPV6 +#define ACE_LACKS_KILL +#define ACE_LACKS_INET_ATON +#define ACE_LACKS_MADVISE +#define ACE_LACKS_MKFIFO +#define ACE_LACKS_MODE_MASKS +#define ACE_LACKS_PTHREAD_H +#define ACE_LACKS_PWD_FUNCTIONS +#define ACE_LACKS_READLINK +#define ACE_LACKS_RLIMIT +#define ACE_LACKS_SBRK +#define ACE_LACKS_SCHED_H +#define ACE_LACKS_SEMBUF_T +#define ACE_LACKS_SIGACTION +#define ACE_LACKS_SIGSET +#define ACE_LACKS_SOCKETPAIR +#define ACE_LACKS_SUSECONDS_T +#define ACE_LACKS_USECONDS_T +#define ACE_LACKS_SYS_PARAM_H +#define ACE_LACKS_SYS_SYSCTL_H +#define ACE_LACKS_SYSCONF +#define ACE_LACKS_SYSV_SHMEM +#define ACE_LACKS_UNISTD_H +#define ACE_LACKS_UNIX_SIGNALS +#define ACE_LACKS_UNIX_SYSLOG +#define ACE_LACKS_UTSNAME_T +#define ACE_LACKS_UNAME +#define ACE_LACKS_WAIT +#define ACE_LACKS_IOVEC +#define ACE_LACKS_LOG2 +#define ACE_LACKS_CADDR_T +#if !defined(__MINGW32__) && !defined (__BORLANDC__) +# define ACE_LACKS_MODE_T +#endif +#if !defined (__BORLANDC__) +# define ACE_LACKS_NLINK_T +# define ACE_LACKS_UID_T +# define ACE_LACKS_GID_T +#endif +#define ACE_LACKS_SETENV +#define ACE_LACKS_UNSETENV + +#define ACE_HAS_PDH_H +#define ACE_HAS_PDHMSG_H + +#define ACE_HAS_VFWPRINTF + +#define ACE_MKDIR_LACKS_MODE + +#define ACE_SIZEOF_LONG_LONG 8 +// Green Hills Native x86 does not support __int64 keyword +// Neither does mingw32. +#if !defined (ACE_LACKS_LONGLONG_T) && !defined (__MINGW32__) +#define ACE_INT64_TYPE signed __int64 +#define ACE_UINT64_TYPE unsigned __int64 +#endif /* (ghs) */ + +#if defined (__MINGW32__) +#define ACE_INT64_TYPE signed long long +#define ACE_UINT64_TYPE unsigned long long +#endif + +// Optimize ACE_Handle_Set for select(). +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT + +// Win32 has wide-char support. Use of the compiler-defined wchar_t type +// is controlled in compiler configs since it's a compiler switch. +#define ACE_HAS_WCHAR +#define ACE_HAS_WTOI +#define ACE_HAS_WTOL + +// Compiler/platform correctly calls init()/fini() for shared +// libraries. - applied for DLLs ? +//define ACE_HAS_AUTOMATIC_INIT_FINI + +// Platform supports POSIX O_NONBLOCK semantics. +//define ACE_HAS_POSIX_NONBLOCK + +// Platform contains . +//define ACE_HAS_POLL + +// Platform supports the /proc file system. +//define ACE_HAS_PROC_FS + +// Platform supports the rusage struct. +#define ACE_HAS_GETRUSAGE + +// Compiler/platform supports SVR4 signal typedef. +//define ACE_HAS_SVR4_SIGNAL_T + +// Platform provides header. +//define ACE_HAS_SYS_FILIO_H + +// Platform supports ACE_TLI timod STREAMS module. +//define ACE_HAS_TIMOD_H + +// Platform supports ACE_TLI tiuser header. +//define ACE_HAS_TIUSER_H + +// Platform provides ACE_TLI function prototypes. +// For Win32, this is not really true, but saves a lot of hassle! +#define ACE_HAS_TLI_PROTOTYPES + +// Platform supports ACE_TLI. +//define ACE_HAS_TLI + +// I'm pretty sure NT lacks these +#define ACE_LACKS_UNIX_DOMAIN_SOCKETS + +// Windows NT needs readv() and writev() +#define ACE_LACKS_WRITEV +#define ACE_LACKS_READV + +#if !defined (ACE_HAS_WTHREADS_CONDITION_VARIABLE) +# define ACE_LACKS_COND_T +#endif + +#define ACE_LACKS_RWLOCK_T + +#define ACE_LACKS_KEY_T + +// No system support for replacing any previous mappings. +#define ACE_LACKS_AUTO_MMAP_REPLACEMENT + +// ACE_HAS_PENTIUM is used to optimize some CDR operations; it's used for +// some other time-related things using g++, but not for VC. Current VC +// compilers set _M_IX86 > 400 by default so if you're not using a Pentium +// class CPU, set the project code generation options appropriately. +#if !defined(ACE_HAS_PENTIUM) && (_M_IX86 > 400) +# define ACE_HAS_PENTIUM +#endif + +#if defined(ACE_MT_SAFE) && (ACE_MT_SAFE != 0) +// Platform supports threads. +# define ACE_HAS_THREADS + +// Platform supports Windows32 threads. +# define ACE_HAS_WTHREADS + +// Compiler/platform has thread-specific storage +# define ACE_HAS_THREAD_SPECIFIC_STORAGE + +// Win32 doesn't have fcntl +#define ACE_LACKS_FCNTL + +#endif /* ACE_MT_SAFE && ACE_MT_SAFE != 0 */ + +#if !defined(_DEBUG) +// If we are making a release, and the user has not specified +// inline directives, we will default to inline +# if ! defined (__ACE_INLINE__) +# define __ACE_INLINE__ 1 +# endif /* __ACE_INLINE__ */ +#endif + +// If __ACE_INLINE__ is defined to be 0, we will undefine it +#if defined (__ACE_INLINE__) && (__ACE_INLINE__ == 0) +# undef __ACE_INLINE__ +#endif /* __ACE_INLINE__ */ + +// We are build ACE and want to use MFC (multithreaded) +#if defined(ACE_HAS_MFC) && (ACE_HAS_MFC != 0) && defined (_MT) +# if (ACE_HAS_DLL != 0) && defined(ACE_BUILD_DLL) && !defined (_WINDLL) +// force multithreaded MFC DLL +# define _WINDLL +# endif /* _AFXDLL */ +# if !defined (_AFXDLL) && !defined (ACE_USES_STATIC_MFC) +# define _AFXDLL +# endif /* _AFXDLL */ +#endif + +// and MFC's are mutually +// incompatible. is brain-dead about MFC; it doesn't check +// to see whether MFC stuff is anticipated or already in progress +// before doing its thing. ACE needs (practically always) , +// and winsock in turn needs support either from windows.h or from +// afxwin.h. One or the other, not both. +// +// The MSVC++ V4.0 environment defines preprocessor macros that +// indicate the programmer has chosen something from the +// Build-->Settings-->General-->MFC combo-box. defines a +// macro itself to protect against double inclusion. We'll take +// advantage of all this to select the proper support for winsock. - +// trl 26-July-1996 + +// This is necessary since MFC users apparently can't #include +// directly. +#if defined (ACE_HAS_MFC) && (ACE_HAS_MFC != 0) +# include /**/ /* He is doing MFC */ +// Windows.h will be included via afxwin.h->afx.h->afx_ver_.h->afxv_w32.h +// #define _INC_WINDOWS // Prevent winsock.h from including windows.h +#elif defined (ACE_HAS_WINCE) +# include /**/ +#endif + +#if !defined (_INC_WINDOWS) /* Already include windows.h ? */ +// Must define strict before including windows.h ! +# if defined (ACE_HAS_STRICT) && (ACE_HAS_STRICT != 0) && !defined (STRICT) +# define STRICT 1 +# endif /* ACE_HAS_STRICT */ + +# if !defined (WIN32_LEAN_AND_MEAN) && !defined (ACE_NO_WIN32_LEAN_AND_MEAN) +# define WIN32_LEAN_AND_MEAN +# endif /* WIN32_LEAN_AND_MEAN */ + +#endif /* !defined (_INC_WINDOWS) */ + +// Always use WS2 when available +#if !defined(ACE_HAS_WINSOCK2) +# define ACE_HAS_WINSOCK2 1 +#endif /* !defined(ACE_HAS_WINSOCK2) */ +// Not use WS1 by default +#if !defined(ACE_HAS_WINSOCK1) +# define ACE_HAS_WINSOCK1 0 +#endif /* !defined(ACE_HAS_WINSOCK1) */ + + +#if defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0) +# define ACE_HAS_ICMP_SUPPORT 1 +# if !defined (_WINSOCK2API_) +// will also include windows.h, if not present +# include /**/ +// WinCE 4 doesn't define the Exxx values without the WSA prefix, so do that +// here. This is all lifted from the #if 0'd out part of winsock2.h. +# if defined (_WIN32_WCE) && (_WIN32_WCE < 0x600) +# define EWOULDBLOCK WSAEWOULDBLOCK +# define EINPROGRESS WSAEINPROGRESS +# define EALREADY WSAEALREADY +# define ENOTSOCK WSAENOTSOCK +# define EDESTADDRREQ WSAEDESTADDRREQ +# define EMSGSIZE WSAEMSGSIZE +# define EPROTOTYPE WSAEPROTOTYPE +# define ENOPROTOOPT WSAENOPROTOOPT +# define EPROTONOSUPPORT WSAEPROTONOSUPPORT +# define ESOCKTNOSUPPORT WSAESOCKTNOSUPPORT +# define EOPNOTSUPP WSAEOPNOTSUPP +# define EPFNOSUPPORT WSAEPFNOSUPPORT +# define EAFNOSUPPORT WSAEAFNOSUPPORT +# define EADDRINUSE WSAEADDRINUSE +# define EADDRNOTAVAIL WSAEADDRNOTAVAIL +# define ENETDOWN WSAENETDOWN +# define ENETUNREACH WSAENETUNREACH +# define ENETRESET WSAENETRESET +# define ECONNABORTED WSAECONNABORTED +# define ECONNRESET WSAECONNRESET +# define ENOBUFS WSAENOBUFS +# define EISCONN WSAEISCONN +# define ENOTCONN WSAENOTCONN +# define ESHUTDOWN WSAESHUTDOWN +# define ETOOMANYREFS WSAETOOMANYREFS +# define ETIMEDOUT WSAETIMEDOUT +# define ECONNREFUSED WSAECONNREFUSED +# define ELOOP WSAELOOP +# define ENAMETOOLONG WSAENAMETOOLONG +# define EHOSTDOWN WSAEHOSTDOWN +# define EHOSTUNREACH WSAEHOSTUNREACH +# define ENOTEMPTY WSAENOTEMPTY +# define EPROCLIM WSAEPROCLIM +# define EUSERS WSAEUSERS +# define EDQUOT WSAEDQUOT +# define ESTALE WSAESTALE +# define EREMOTE WSAEREMOTE +# endif /* (_WIN32_WCE) && (_WIN32_WCE < 0x600) */ +# endif /* _WINSOCK2API */ + +# if defined (ACE_HAS_FORE_ATM_WS2) +# include /**/ +# endif /*ACE_HAS_FORE_ATM_WS2 */ + +// CE doesn't have Microsoft Winsock 2 extensions +# if !defined _MSWSOCK_ && !defined (ACE_HAS_WINCE) +# include /**/ +# endif /* _MSWSOCK_ */ + +# if defined (_MSC_VER) +# if defined (ACE_HAS_WINCE) +# pragma comment(lib, "ws2.lib") +# else +# pragma comment(lib, "ws2_32.lib") +# pragma comment(lib, "mswsock.lib") +# if defined (ACE_HAS_IPV6) +# pragma comment(lib, "iphlpapi.lib") +# endif +# endif /* ACE_HAS_WINCE */ +# endif /* _MSC_VER */ + +# define ACE_WSOCK_VERSION 2, 0 +#else +# if !defined (_WINSOCKAPI_) + // will also include windows.h, if not present +# include /**/ +# endif /* _WINSOCKAPI */ + +// PharLap ETS has its own winsock lib, so don't grab the one +// supplied with the OS. +# if defined (_MSC_VER) && !defined (_WIN32_WCE) && !defined (ACE_HAS_PHARLAP) +# pragma comment(lib, "wsock32.lib") +# endif /* _MSC_VER */ + +// We can't use recvmsg and sendmsg unless WinSock 2 is available +# define ACE_LACKS_RECVMSG +# define ACE_LACKS_SENDMSG + +// Version 1.1 of WinSock +# define ACE_WSOCK_VERSION 1, 1 +#endif /* ACE_HAS_WINSOCK2 */ + +// Platform supports IP multicast on Winsock 2 +#if defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0) +# define ACE_HAS_IP_MULTICAST +#endif /* ACE_HAS_WINSOCK2 */ + +#if !defined (ACE_HAS_WINCE) +# define ACE_HAS_INTERLOCKED_EXCHANGEADD +#endif +#define ACE_HAS_WIN32_TRYLOCK + +#if !defined (ACE_HAS_WINCE) && !defined (ACE_HAS_PHARLAP) +# define ACE_HAS_SIGNAL_OBJECT_AND_WAIT + +// If CancelIO is undefined get the updated sp2-sdk from MS +# define ACE_HAS_CANCEL_IO +# define ACE_HAS_WIN32_OVERLAPPED_IO +# define ACE_HAS_WIN32_NAMED_PIPES +#endif /* !defined (ACE_HAS_WINCE) && !ACE_HAS_PHARLAP */ + +#if !defined (ACE_SEH_DEFAULT_EXCEPTION_HANDLING_ACTION) +# define ACE_SEH_DEFAULT_EXCEPTION_HANDLING_ACTION EXCEPTION_CONTINUE_SEARCH +#endif /* ACE_SEH_DEFAULT_EXCEPTION_HANDLING_ACTION */ + +// ACE_HAS_QOS is defined in the qos.mpb base project. +// If qos=1 in default.features, then this macro will be defined. +#if defined (ACE_HAS_QOS) && !defined (ACE_HAS_WINSOCK2_GQOS) +# if defined (WINSOCK_VERSION) +# define ACE_HAS_WINSOCK2_GQOS 1 +# endif /* WINSOCK_VERSION */ +#endif /* ACE_HAS_WINSOCK2_GQOS */ + +// These are the defaults and can be overridden by a user's config.h +#if !defined (ACE_DEFAULT_FILE_PERMS) +# define ACE_DEFAULT_FILE_PERMS (FILE_SHARE_READ | FILE_SHARE_WRITE | \ + FILE_SHARE_DELETE) +// This alternate used to be used for pre-NT4 systems; may still be needed +// by knock-offs such as CE and Pharlap. +//# define ACE_DEFAULT_FILE_PERMS (FILE_SHARE_READ | FILE_SHARE_WRITE) +#endif /* !defined (ACE_DEFAULT_FILE_PERMS) */ + +#define ACE_SIZEOF_WCHAR 2 +#define ACE_HAS_MUTEX_TIMEOUTS +#define ACE_LACKS_STRUCT_DIR +#define ACE_LACKS_OPENDIR +#define ACE_LACKS_CLOSEDIR +#define ACE_LACKS_READDIR +#define ACE_LACKS_ALPHASORT +#define ACE_LACKS_MKSTEMP +#define ACE_LACKS_LSTAT +// Looks like Win32 has a non-const swab function +#define ACE_HAS_NONCONST_SWAB + +// If we are using winsock2 then the SO_REUSEADDR feature is broken +// SO_REUSEADDR=1 behaves like SO_REUSEPORT=1. (SO_REUSEPORT is an +// extension to sockets on some platforms) +// We define SO_REUSEPORT here so that ACE_OS::setsockopt() can still +// allow the user to specify that a socketaddr can *always* be reused. +#if defined (ACE_HAS_WINSOCK2) && ACE_HAS_WINSOCK2 != 0 && ! defined(SO_REUSEPORT) +#define SO_REUSEPORT 0x0400 // We just have to pick a value that won't conflict +#endif + +#if defined (ACE_WIN64) +// Data must be aligned on 8-byte boundaries, at a minimum. +# define ACE_MALLOC_ALIGN 8 +// Void pointers are 8 bytes +# define ACE_SIZEOF_VOID_P 8 +#endif /* ACE_WIN64 */ + +#if !defined (ACE_DISABLES_THREAD_LIBRARY_CALLS) +# define ACE_DISABLES_THREAD_LIBRARY_CALLS 0 +#endif /* ACE_DISABLES_THREAD_LIBRARY_CALLS */ + +#if !defined (ACE_HAS_WINCE) && !defined (ACE_HAS_PHARLAP) +# define ACE_HAS_LOG_MSG_NT_EVENT_LOG +#endif /* !ACE_HAS_WINCE && !ACE_HAS_PHARLAP */ + +#if !defined (ACE_HAS_WINCE) +# define ACE_HAS_LLSEEK +#endif /* !ACE_HAS_WINCE */ + +// Needed for obtaining the MAC address +// I dont believe this will work under CE, notice the +// check for ACE_HAS_WINCE. +# if !defined (ACE_HAS_WINCE) +# include +# if defined (_MSC_VER) +# pragma comment(lib, "netapi32.lib") // needed for obtaing MACaddress +# endif +# endif /* !ACE_HAS_WINCE */ + +#if !defined (WINVER) +# define WINVER 0x0400 // pretend it's at least WinNT 4.0 +#endif + +/////////////////////////////////////// +// windows version-specific definitions +// see: http://msdn2.microsoft.com/en-us/library/aa383745.aspx +// +// For TSS information +// see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/thread_local_storage.asp + +#if (WINVER>=0x0600) +// Windows Server 2008 definitions go here +// Windows Vista defintions go here +# if ! defined(ACE_DEFAULT_THREAD_KEYS) +# define ACE_DEFAULT_THREAD_KEYS 1088 +# endif // ! defined(ACE_DEFAULT_THREAD_KEYS) +#elif (WINVER>=0x0502) + // Windows Server 2003 SP1 definitions go here +# if ! defined(ACE_DEFAULT_THREAD_KEYS) +# define ACE_DEFAULT_THREAD_KEYS 1088 +# endif // ! defined(ACE_DEFAULT_THREAD_KEYS) +#elif (WINVER>=0x0501) +// Windows XP definitions go here +# if ! defined(ACE_DEFAULT_THREAD_KEYS) +# define ACE_DEFAULT_THREAD_KEYS 1088 +# endif // ! defined(ACE_DEFAULT_THREAD_KEYS) +#elif (WINVER>=0x0500) +// Windows 2000 definitions go here +# if ! defined(ACE_DEFAULT_THREAD_KEYS) +# define ACE_DEFAULT_THREAD_KEYS 1088 +# endif // ! defined(ACE_DEFAULT_THREAD_KEYS) +#elif (WINVER>=0x0410) +// Windows 98 definitions go here +# if ! defined(ACE_DEFAULT_THREAD_KEYS) +# define ACE_DEFAULT_THREAD_KEYS 80 +# endif // ! defined(ACE_DEFAULT_THREAD_KEYS) +#else +// antique windows +# if ! defined(ACE_DEFAULT_THREAD_KEYS) +# define ACE_DEFAULT_THREAD_KEYS 64 +# endif // ! defined(ACE_DEFAULT_THREAD_KEYS) +#endif + +#if !defined (ACE_DEFAULT_BACKLOG) +# define ACE_DEFAULT_BACKLOG SOMAXCONN +#endif /* ACE_DEFAULT_BACKLOG */ + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_WIN32_COMMON_H */ diff --git a/dep/acelite/ace/config-win32-dmc.h b/dep/acelite/ace/config-win32-dmc.h new file mode 100644 index 00000000000..db6c7e9c8dc --- /dev/null +++ b/dep/acelite/ace/config-win32-dmc.h @@ -0,0 +1,108 @@ +// -*- C++ -*- +// $Id: config-win32-dmc.h 87268 2009-10-29 21:06:06Z olli $ + +// The following configuration file contains defines for Digital Mars compilers. + +#ifndef ACE_CONFIG_WIN32_DMC_H +#define ACE_CONFIG_WIN32_DMC_H +#include /**/ "ace/pre.h" + +#ifndef ACE_CONFIG_WIN32_H +#error Use config-win32.h in config.h instead of this header +#endif /* ACE_CONFIG_WIN32_H */ + +#ifndef WIN32 +# define WIN32 +#endif /* WIN32 */ + +#undef _M_IX86 +// This turns on ACE_HAS_PENTIUM +#define _M_IX86 500 + +#if defined ACE_LACKS_STRUCT_DIR +# undef ACE_LACKS_STRUCT_DIR +#endif + +// Changed ACE_TEXT to ACE_TEXT in the following line +# define ACE_CC_NAME ACE_TEXT ("Digital Mars") +# define ACE_CC_MAJOR_VERSION (1) +# define ACE_CC_MINOR_VERSION (8) +# define ACE_CC_BETA_VERSION (9) +# ifndef ACE_USING_MCPP_PREPROCESSOR +# define ACE_CC_PREPROCESSOR "DMC.EXE" +# define ACE_CC_PREPROCESSOR_ARGS "-E" +# endif + +// Microsoft's standard cpp library auto_ptr doesn't have reset (). +# define ACE_AUTO_PTR_LACKS_RESET + +#define ACE_ENDTHREADEX(STATUS) ::_endthreadex ((DWORD) STATUS) + +// This section below was extracted from config-win32-msvc +#define ACE_HAS_ITOA +#define ACE_ITOA_EQUIVALENT ::_itoa +#define ACE_STRCASECMP_EQUIVALENT ::_stricmp +#define ACE_STRNCASECMP_EQUIVALENT ::_strnicmp +#define ACE_WCSDUP_EQUIVALENT ::_wcsdup +// This section above was extracted from config-win32-msvc + +# define ACE_EXPORT_NESTED_CLASSES 1 +# define ACE_HAS_CPLUSPLUS_HEADERS 1 +//# define ACE_HAS_EXCEPTIONS 1 +# define ACE_HAS_NONCONST_SELECT_TIMEVAL 1 +# define ACE_HAS_SIG_ATOMIC_T 1 +# define ACE_HAS_STANDARD_CPP_LIBRARY 0 +# define ACE_HAS_STDCPP_STL_INCLUDES 1 +# define ACE_HAS_STRING_CLASS 1 +# define ACE_HAS_TEMPLATE_TYPEDEFS 1 +# define ACE_HAS_USER_MODE_MASKS 1 +//# define ACE_LACKS_LINEBUFFERED_STREAMBUF 1 +# define ACE_LACKS_STRPTIME 1 +//# define ACE_LACKS_PRAGMA_ONCE 1 +//# define ACE_NEW_THROWS_EXCEPTIONS 1 +# define ACE_SIZEOF_LONG_DOUBLE 10 +# define ACE_TEMPLATES_REQUIRE_SOURCE 1 +// Changed ACE_TEXT to ACE_TEXT in the following two lines +# define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 +# define ACE_HAS_STRBUF_T +#define ACE_HAS_3_PARAM_WCSTOK +#define ACE_USES_OLD_IOSTREAMS +#define ACE_LACKS_UCONTEXT_H +#define ACE_LACKS_SYS_RESOURCE_H +#define ACE_LACKS_SYS_WAIT_H +#define ACE_LACKS_STRINGS_H +#define ACE_LACKS_SYS_IPC_H +#define ACE_LACKS_SYS_SEM_H +#define ACE_LACKS_SEMAPHORE_H +#define ACE_LACKS_SYS_MMAN_H +#define ACE_LACKS_SYS_UIO_H +#define ACE_LACKS_SYS_SOCKET_H +#define ACE_LACKS_NETINET_IN_H +#define ACE_LACKS_SYS_IOCTL_H +#define ACE_LACKS_SYS_SELECT_H +#define ACE_LACKS_NET_IF_H +#define ACE_LACKS_DLFCN_H +#define ACE_LACKS_NETDB_H +#define ACE_LACKS_SYS_SHM_H +#define ACE_LACKS_REGEX_H +#define ACE_LACKS_SYS_MSG_H +#define ACE_LACKS_NETINET_TCP_H +#define ACE_LACKS_UNISTD_H +#define ACE_LACKS_TERMIOS_H +#define ACE_LACKS_ACE_IOSTREAM +#define ACE_HAS_NONCONST_TEMPNAM + +// Typedefs which we expect DMC to do, but they don't do that +typedef long o_uid_t; +typedef long o_gid_t; + +#include "io.h" +#undef umask; +#undef tell; + +# if !defined (ACE_LD_DECORATOR_STR) && defined (_DEBUG) +# define ACE_LD_DECORATOR_STR ACE_TEXT ("d") +# endif + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_WIN32_DMC_H */ diff --git a/dep/acelite/ace/config-win32-ghs.h b/dep/acelite/ace/config-win32-ghs.h new file mode 100644 index 00000000000..0ac80bfbd11 --- /dev/null +++ b/dep/acelite/ace/config-win32-ghs.h @@ -0,0 +1,93 @@ +// -*- C++ -*- +// $Id: config-win32-ghs.h 87268 2009-10-29 21:06:06Z olli $ + +// The following configuration file contains defines for Green Hills compilers. + +#ifndef ACE_CONFIG_WIN32_GHS_H +#define ACE_CONFIG_WIN32_GHS_H +#include /**/ "ace/pre.h" + +#ifndef ACE_CONFIG_WIN32_H +#error Use config-win32.h in config.h instead of this header +#endif /* ACE_CONFIG_WIN32_H */ + +#ifndef WIN32 +# define WIN32 +#endif /* WIN32 */ + +#undef _M_IX86 +// This turns on ACE_HAS_PENTIUM +#define _M_IX86 500 +// GHS does not provide DLL support +#define ACE_HAS_DLL 0 +#define TAO_HAS_DLL 0 +#undef _DLL + +//Green Hills Native x86 does not support structural exceptions +# undef ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS +# undef ACE_HAS_WCHAR +# define ACE_CONFIG_INCLUDE_GHS_COMMON +# include "ace/config-ghs-common.h" + +// Changed ACE_TEXT to ACE_TEXT in the following line +# define ACE_CC_NAME ACE_TEXT ("Green Hills C++") +# define ACE_CC_MAJOR_VERSION (1) +# define ACE_CC_MINOR_VERSION (8) +# define ACE_CC_BETA_VERSION (9) +# ifndef ACE_USING_MCPP_PREPROCESSOR +# define ACE_CC_PREPROCESSOR "GCX.EXE" +# define ACE_CC_PREPROCESSOR_ARGS "-E" +# endif + +// GHS uses Microsoft's standard cpp library, which has auto_ptr. +# undef ACE_LACKS_AUTO_PTR +// Microsoft's standard cpp library auto_ptr doesn't have reset (). +# define ACE_AUTO_PTR_LACKS_RESET + +#define ACE_ENDTHREADEX(STATUS) ::_endthreadex ((DWORD) STATUS) + +// This section below was extracted from config-win32-msvc +#define ACE_HAS_ITOA +#define ACE_ITOA_EQUIVALENT ::_itoa +#define ACE_STRCASECMP_EQUIVALENT ::_stricmp +#define ACE_STRNCASECMP_EQUIVALENT ::_strnicmp +#define ACE_WCSDUP_EQUIVALENT ::_wcsdup +// This section above was extracted from config-win32-msvc + +# define ACE_EXPORT_NESTED_CLASSES 1 +# define ACE_HAS_CPLUSPLUS_HEADERS 1 +//# define ACE_HAS_EXCEPTIONS 1 +# define ACE_HAS_NONCONST_SELECT_TIMEVAL 1 +# define ACE_HAS_SIG_ATOMIC_T 1 +# define ACE_HAS_STANDARD_CPP_LIBRARY 1 +# define ACE_HAS_STDCPP_STL_INCLUDES 1 +# define ACE_HAS_STRING_CLASS 1 +# define ACE_HAS_TEMPLATE_TYPEDEFS 1 +# define ACE_HAS_USER_MODE_MASKS 1 +# define ACE_LACKS_ACE_IOSTREAM 1 +//# define ACE_LACKS_LINEBUFFERED_STREAMBUF 1 +# define ACE_LACKS_STRPTIME 1 +//# define ACE_LACKS_PRAGMA_ONCE 1 +# define ACE_LACKS_STRRECVFD 1 +//# define ACE_NEW_THROWS_EXCEPTIONS 1 +# define ACE_SIZEOF_LONG_DOUBLE 10 +# define ACE_TEMPLATES_REQUIRE_SOURCE 1 +# define ACE_UINT64_FORMAT_SPECIFIER_ASCII "%I64u" +# define ACE_INT64_FORMAT_SPECIFIER_ASCII "%I64d" +# define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 +// Set the following to zero to placate SString.h ACE_WString CTOR +# undef ACE_WSTRING_HAS_USHORT_SUPPORT + +// Green Hills Native x86 does not support __int64 keyword +# define ACE_LACKS_LONGLONG_T + +/* need to ensure these are included before */ +# include +# include + +# if !defined (ACE_LD_DECORATOR_STR) && defined (_DEBUG) +# define ACE_LD_DECORATOR_STR ACE_TEXT ("d") +# endif + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_WIN32_GHS_H */ diff --git a/dep/acelite/ace/config-win32-interix.h b/dep/acelite/ace/config-win32-interix.h new file mode 100644 index 00000000000..d0365ac0399 --- /dev/null +++ b/dep/acelite/ace/config-win32-interix.h @@ -0,0 +1,127 @@ +// -*- C++ -*- +// $Id: config-win32-interix.h 87578 2009-11-16 14:41:47Z olli $ + +// The following configuration file is designed to work for Interix +// platforms using GNU g++ (Interix == Microsoft's Services for Unix) + +#ifndef ACE_CONFIG_WIN32_INTERIX_H +#define ACE_CONFIG_WIN32_INTERIX_H + +#include /**/ "ace/pre.h" + +#include "ace/config-g++-common.h" + +#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R +#define ACE_HAS_3_PARAM_READDIR_R +#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG +#define ACE_HAS_AUTOMATIC_INIT_FINI +#define ACE_HAS_BROKEN_T_ERROR +#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES +#define ACE_HAS_DIRENT +#define ACE_HAS_EXCEPTIONS +#define ACE_HAS_GETPAGESIZE +#define ACE_HAS_GETRUSAGE +#define ACE_HAS_GETRUSAGE_PROTOTYPE +#define ACE_HAS_GPERF +#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT +#define ACE_HAS_ICMP_SUPPORT 1 +#define ACE_HAS_IP_MULTICAST +#define ACE_HAS_MEMCHR +#define ACE_HAS_MKDIR +#define ACE_HAS_MSG +#define ACE_HAS_NEW_NOTHROW +#define ACE_HAS_NEW_NO_H +#define ACE_HAS_NONCONST_SELECT_TIMEVAL +#define ACE_HAS_POLL +#define ACE_HAS_POSITION_INDEPENDENT_POINTERS 1 +#define ACE_HAS_POSIX_GETPWNAM_R +#define ACE_HAS_POSIX_NONBLOCK +#define ACE_HAS_POSIX_TIME +#define ACE_HAS_PTHREADS_STD +#define ACE_HAS_PTHREADS_UNIX98_EXT +#define ACE_HAS_PTHREAD_GETCONCURRENCY +#define ACE_HAS_PTHREAD_SETCONCURRENCY +#define ACE_HAS_PTHREAD_SIGMASK_PROTOTYPE +#define ACE_HAS_P_READ_WRITE +#define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS +#define ACE_HAS_REENTRANT_FUNCTIONS +#define ACE_HAS_RTLD_LAZY_V +#define ACE_HAS_SEMUN +#define ACE_HAS_SIGINFO_T +#define ACE_HAS_SIGSUSPEND +#define ACE_HAS_SIGWAIT +#define ACE_HAS_SIG_ATOMIC_T +#define ACE_HAS_SIG_C_FUNC +#define ACE_HAS_SOCKADDR_MSG_NAME +#define ACE_HAS_SOCKLEN_T +#define ACE_HAS_SSIZE_T +#define ACE_HAS_STANDARD_CPP_LIBRARY 1 +#define ACE_HAS_STDCPP_STL_INCLUDES +#define ACE_HAS_STREAMS +#define ACE_HAS_STRING_CLASS +#define ACE_HAS_STRSIGNAL +#define ACE_HAS_SVR4_DYNAMIC_LINKING +#define ACE_HAS_SVR4_GETTIMEOFDAY +#define ACE_HAS_SVR4_SIGNAL_T +#define ACE_HAS_SYSV_IPC +#define ACE_HAS_SYS_SYSCALL_H +#define ACE_HAS_TERMIOS +#define ACE_HAS_UALARM +#define ACE_HAS_UCONTEXT_T +#define ACE_HAS_VOIDPTR_GETTIMEOFDAY +#define ACE_HAS_NONSTATIC_OBJECT_MANAGER + +#define ACE_LACKS_GETPGID +#define ACE_LACKS_ISCTYPE +#define ACE_LACKS_LOG2 +#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS +#define ACE_LACKS_NET_IF_H +#define ACE_LACKS_PRAGMA_ONCE +#define ACE_LACKS_SETSCHED +#define ACE_LACKS_STRRECVFD +#define ACE_LACKS_SYS_SYSCTL_H +#define ACE_LACKS_TIMESPEC_T +#define ACE_LACKS_WCSTOK +#define ACE_LACKS_WCSTOLL +#define ACE_LACKS_WCSTOULL + +// These are probably not needed with gcc 4.x +#define ACE_LACKS_UNSETENV +#define ACE_LACKS_STRTOLL +#define ACE_LACKS_STRTOULL +#define ACE_LACKS_SETEGID +#define ACE_LACKS_SETEUID + + +#define ACE_PAGE_SIZE 4096 +#define ACE_SIZEOF_LONG_LONG 8 +#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 + +#if defined (ACE_HAS_THREADS) +# define ACE_HAS_MUTEX_TIMEOUTS +# define ACE_HAS_PTHREADS +# define ACE_MT_SAFE 1 +#else +# error "You need to enable threads for this Interix port." +#endif /* ACE_HAS_THREADS */ + +// Turns off the tracing feature. +#if !defined (ACE_NTRACE) +#define ACE_NTRACE 1 +#endif /* ACE_NTRACE */ + +// NOTE: In debugging some of the test apps they would all memory fault in using +// ACE_Errno_Guard. Upon inspection of that code it uses TSS to save ERRNO in +// a TSS pointer. Access to that pointer caused the fault. The work around here +// is to tell ACE we have TSS and use emulation. More investigation is needed to +// determine whether Interix TSS is broken or the correct semantics for usage under +// Interix simply need to be ported. +// To get around the issue ACE_HAS_TSS_EMULATION is defined to use TSS emulation +// however while many test programs that use TSS pass the TSS_Test program fails. +#define ACE_HAS_THREAD_SPECIFIC_STORAGE // We need thread specific storage even though... +#define ACE_HAS_TSS_EMULATION // It would appear to be broken in Interix! + + +#include /**/ "ace/post.h" + +#endif /* ACE_CONFIG_WIN32_INTERIX_H */ diff --git a/dep/acelite/ace/config-win32-mingw.h b/dep/acelite/ace/config-win32-mingw.h new file mode 100644 index 00000000000..0a0ff292f8c --- /dev/null +++ b/dep/acelite/ace/config-win32-mingw.h @@ -0,0 +1,105 @@ +// -*- C++ -*- +// $Id: config-win32-mingw.h 87167 2009-10-19 19:33:53Z olli $ + +// +// The following configuration file is designed to work for win32 +// platforms using gcc/g++ with mingw32 (http://www.mingw.org). +// + +#ifndef ACE_CONFIG_WIN32_MINGW_H +#define ACE_CONFIG_WIN32_MINGW_H +#include /**/ "ace/pre.h" + +#ifndef ACE_CONFIG_WIN32_H +# error Use config-win32.h in config.h instead of this header +#endif /* ACE_CONFIG_WIN32_H */ + +#define ACE_CC_NAME ACE_TEXT ("g++") +#define ACE_CC_PREPROCESSOR "cpp" +#define ACE_CC_PREPROCESOR_ARGS "" + +// Why all this is not in config-g++-common.h? +#define ACE_CC_MAJOR_VERSION __GNUC__ +#define ACE_CC_MINOR_VERSION __GNUC_MINOR__ +#define ACE_CC_BETA_VERSION (0) + +#if !defined(__MINGW32__) +# error You do not seem to be using mingw32 +#endif + +#include "ace/config-g++-common.h" + +#include /**/ <_mingw.h> +#include /**/ + +#define ACE_HAS_USER_MODE_MASKS + +#if (__MINGW32_MAJOR_VERSION < 2) +# error You need a newer version (>= 2.0) of mingw32/w32api +#endif + +#if (__MINGW32_MAJOR_VERSION >= 3) +# define ACE_HAS_SSIZE_T +# undef ACE_LACKS_STRUCT_DIR +# undef ACE_LACKS_OPENDIR +# undef ACE_LACKS_CLOSEDIR +# undef ACE_LACKS_READDIR +# undef ACE_LACKS_TELLDIR +# undef ACE_LACKS_SEEKDIR +# undef ACE_LACKS_REWINDDIR +#else +# define ACE_LACKS_DIRENT_H +#endif + +#if (__MINGW32_MAJOR_VERSION > 3) || ((__MINGW32_MAJOR_VERSION == 3) && (__MINGW32_MINOR_VERSION >= 15)) +# undef ACE_LACKS_USECONDS_T +#endif + +#undef ACE_HAS_WTOF + +#define ACE_LACKS_SYS_SHM_H +#define ACE_LACKS_TERMIOS_H +#define ACE_LACKS_NETINET_TCP_H +#define ACE_LACKS_STRRECVFD +#define ACE_LACKS_STRPTIME +#define ACE_LACKS_POLL_H +#define ACE_LACKS_REGEX_H +#define ACE_LACKS_SYS_MSG_H +#define ACE_LACKS_PWD_H +#define ACE_LACKS_SEMAPHORE_H +#define ACE_LACKS_UCONTEXT_H +#define ACE_LACKS_SYS_SELECT_H +#define ACE_LACKS_SYS_RESOURCE_H +#define ACE_LACKS_SYS_WAIT_H +#define ACE_LACKS_DLFCN_H +#define ACE_LACKS_SYS_MMAN_H +#define ACE_LACKS_SYS_UIO_H +#define ACE_LACKS_SYS_SOCKET_H +#define ACE_LACKS_NETINET_IN_H +#define ACE_LACKS_NETDB_H +#define ACE_LACKS_NET_IF_H +#define ACE_LACKS_SYS_IPC_H +#define ACE_LACKS_SYS_SEM_H +#define ACE_LACKS_STROPTS_H +#define ACE_LACKS_SYS_IOCTL_H +#define ACE_LACKS_PDH_H +#define ACE_LACKS_PDHMSG_H +#define ACE_HAS_NONCONST_WCSDUP +#define ACE_HAS_WINSOCK2_GQOS +#define ACE_ISCTYPE_EQUIVALENT ::_isctype + +// We trust the user: He must have used -mpentiumpro or -mpentium +// if that is what he wants. +#if defined(pentiumpro) || defined(pentium) +# define ACE_HAS_PENTIUM +#endif + +#define ACE_INT64_FORMAT_SPECIFIER_ASCII "%I64d" +#define ACE_UINT64_FORMAT_SPECIFIER_ASCII "%I64u" + +#define ACE_ENDTHREADEX(STATUS) ::_endthreadex ((DWORD) (STATUS)) + +#define ACE_DLL_PREFIX ACE_TEXT ("lib") + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_WIN32_MINGW_H */ diff --git a/dep/acelite/ace/config-win32-msvc-10.h b/dep/acelite/ace/config-win32-msvc-10.h new file mode 100644 index 00000000000..1867aa010f2 --- /dev/null +++ b/dep/acelite/ace/config-win32-msvc-10.h @@ -0,0 +1,153 @@ +/* -*- C++ -*- */ +//============================================================================= +/** + * @file config-win32-msvc-10.h + * + * $Id: config-win32-msvc-10.h 87224 2009-10-26 07:49:31Z olli $ + * + * @brief Microsoft Visual C++ 10.0 configuration file. + * + * This file is the ACE configuration file for Microsoft Visual C++ version 10. + * + * @note Do not include this file directly, include config-win32.h instead. + */ +//============================================================================= + +#ifndef ACE_CONFIG_WIN32_MSVC_10_H +#define ACE_CONFIG_WIN32_MSVC_10_H +#include /**/ "ace/pre.h" + +#ifndef ACE_CONFIG_WIN32_H +#error Use config-win32.h in config.h instead of this header +#endif /* ACE_CONFIG_WIN32_H */ + +#ifndef ACE_WIN32_VC10 +# define ACE_WIN32_VC10 +#endif + +// Visual C++ 9.0 (.NET) deprecated the old iostreams +#if !defined (ACE_HAS_STANDARD_CPP_LIBRARY) +#define ACE_HAS_STANDARD_CPP_LIBRARY 1 +#endif + +#if !defined (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB) +#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 +#endif + +// Windows' timeval is non-conformant (defined in terms of long instead of +// time_t) and VC9 (on desktop, not CE) changed time_t to a 64-bit value +// even when compiling a 32-bit application. Therefore, ace/Time_Value +// needs to rearrange a few things for this compiler. See Time_Value.h +// for complete details. +#if !defined (ACE_HAS_WINCE) +# define ACE_HAS_TIME_T_LONG_MISMATCH +#endif + +#define ACE_HAS_ITOA +#define ACE_HAS_HEADER_ALLOCATED_CLASS_STATIC_CONST_INT_STOREAGE +#define ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR + +#define ACE_ITOA_EQUIVALENT ::_itoa +#define ACE_STRCASECMP_EQUIVALENT ::_stricmp +#define ACE_STRNCASECMP_EQUIVALENT ::_strnicmp +#define ACE_WCSDUP_EQUIVALENT ::_wcsdup +#if defined (ACE_HAS_WINCE) +# define ACE_FILENO_EQUIVALENT ::_fileno +#else +# define ACE_FILENO_EQUIVALENT(X) (_get_osfhandle (::_fileno (X))) +#endif + +#ifndef ACE_HAS_EXCEPTIONS +# define ACE_HAS_EXCEPTIONS +#endif + +// Windows Mobile 6 doesn't do sig_atomic_t, but maybe future versions will. +# if !defined (_WIN32_WCE) || (_WIN32_WCE > 0x601) +# define ACE_HAS_SIG_ATOMIC_T +# endif /* !Win CE 6.0 or less */ + +#define ACE_LACKS_STRPTIME + +// Evaluate this with a WinCE build; maybe things have improved since VC8. +//#if !defined (ACE_HAS_WINCE) +# define ACE_HAS_INTRIN_H +# define ACE_HAS_INTRINSIC_INTERLOCKED +//#endif + +#if !defined (_WIN32_WCE) || (_WIN32_WCE >= 0x501) +# define ACE_HAS_INTRINSIC_BYTESWAP +#endif + +#define ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES +#define ACE_LACKS_STRRECVFD +#define ACE_HAS_CPLUSPLUS_HEADERS + +#define ACE_HAS_TEMPLATE_TYPEDEFS +#define ACE_TEMPLATES_REQUIRE_SOURCE + +// Platform provides ACE_TLI function prototypes. +// For Win32, this is not really true, but saves a lot of hassle! +#define ACE_HAS_TLI_PROTOTYPES + +// Platform support linebuffered streaming is broken +#define ACE_LACKS_LINEBUFFERED_STREAMBUF + +#if defined (ACE_HAS_STANDARD_CPP_LIBRARY) && (ACE_HAS_STANDARD_CPP_LIBRARY != 0) + +// Platform has its Standard C++ library in the namespace std +# if !defined (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB) +# define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 +# endif /* ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB */ + +// ace/iostream.h does not work with the standard cpp library (yet). +# if !defined (ACE_USES_OLD_IOSTREAMS) +# define ACE_LACKS_ACE_IOSTREAM +# endif /* ! ACE_USES_OLD_IOSTREAMS */ + +// Starting with MSVC 7.1, std::new throws std::bad_alloc on out-of-memory. +#define ACE_NEW_THROWS_EXCEPTIONS +#define ACE_HAS_NEW_NOTHROW + +#else + +// iostream header lacks ipfx (), isfx (), etc., declarations +# define ACE_LACKS_IOSTREAM_FX + +#endif + +// There are too many instances of this warning to fix it right now. +// Maybe in the future. + +// Disable warning of using Microsoft Extension. +# pragma warning(disable:4231) + +// 'class1' : inherits 'class2::member' via dominance +#pragma warning(disable:4250) + +// CE (at least thru Windows Mobile 5) doesn't have the new, secure CRT. +#if !defined (ACE_HAS_WINCE) && !defined (ACE_HAS_TR24731_2005_CRT) +# define ACE_HAS_TR24731_2005_CRT +#endif + +// On CE w/o MFC config-WinCE.h needs to declare a placement new. This +// triggers a warning that there's no placement delete, which can be ignored. +#if defined (ACE_HAS_WINCE) && !defined (ACE_HAS_MFC) +# pragma warning(disable:4291) +#endif + +// A template can not be exported. Only an instantiation may be exported. +#define ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION_EXPORT + +// At least for ACE_UNIMPLEMENTED_FUNC in class templates, this is needed to +// explicitly instantiate a template that has ACE_UNIMPLEMENTED_FUNC. +# define ACE_NEEDS_FUNC_DEFINITIONS + +// Windows Vista and Windows Server 2008 and newer do have native condition +// variables +#if defined (WIN32_WINNT) && (WIN32_WINNT >= 0x0600) +# define ACE_HAS_WTHREADS_CONDITION_VARIABLE +# undef ACE_LACKS_COND_T +#endif + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_WIN32_MSVC_10_H */ diff --git a/dep/acelite/ace/config-win32-msvc-7.h b/dep/acelite/ace/config-win32-msvc-7.h new file mode 100644 index 00000000000..30965d6772f --- /dev/null +++ b/dep/acelite/ace/config-win32-msvc-7.h @@ -0,0 +1,124 @@ +/* -*- C++ -*- */ +//============================================================================= +/** + * @file config-win32-msvc-7.h + * + * $Id: config-win32-msvc-7.h 87251 2009-10-28 12:00:12Z olli $ + * + * @brief Microsoft Visual C++ 7.0 configuration file. + * + * This file is the ACE configuration file for Microsoft Visual C++ version 7. + * + * @note Do not include this file directly, include config-win32.h instead. + * + * @author Darrell Brunsch + */ +//============================================================================= + +#ifndef ACE_CONFIG_WIN32_MSVC_7_H +#define ACE_CONFIG_WIN32_MSVC_7_H +#include /**/ "ace/pre.h" + +#ifndef ACE_CONFIG_WIN32_H +#error Use config-win32.h in config.h instead of this header +#endif /* ACE_CONFIG_WIN32_H */ + +// Visual C++ 7.0 (.NET) deprecated the old iostreams +#if !defined (ACE_HAS_STANDARD_CPP_LIBRARY) +#define ACE_HAS_STANDARD_CPP_LIBRARY 1 +#endif + +#if !defined (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB) +#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 +#endif + +// Win64 SDK compiler claims std::auto_ptr<>::reset not available. +#if defined (_WIN64) || defined (WIN64) +#define ACE_AUTO_PTR_LACKS_RESET +#endif + +#define ACE_HAS_ITOA +#define ACE_HAS_HEADER_ALLOCATED_CLASS_STATIC_CONST_INT_STOREAGE +#define ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR + +#define ACE_ITOA_EQUIVALENT ::_itoa +#define ACE_STRCASECMP_EQUIVALENT ::_stricmp +#define ACE_STRNCASECMP_EQUIVALENT ::_strnicmp +#define ACE_WCSDUP_EQUIVALENT ::_wcsdup + +#if !defined (ACE_HAS_WINCE) && !defined (ACE_HAS_EXCEPTIONS) +#define ACE_HAS_EXCEPTIONS +#endif /* ACE_HAS_WINCE */ + +#define ACE_LACKS_STRPTIME + +#define ACE_HAS_SIG_ATOMIC_T +#define ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES +#define ACE_LACKS_STRRECVFD +#define ACE_HAS_CPLUSPLUS_HEADERS + +#define ACE_HAS_TEMPLATE_TYPEDEFS +#define ACE_TEMPLATES_REQUIRE_SOURCE + +// Platform provides ACE_TLI function prototypes. +// For Win32, this is not really true, but saves a lot of hassle! +#define ACE_HAS_TLI_PROTOTYPES + +// Platform support linebuffered streaming is broken +#define ACE_LACKS_LINEBUFFERED_STREAMBUF + +#if !defined (ACE_HAS_WINCE) && !(defined (__INTEL_COMPILER) && (__INTEL_COMPILER == 900)) +# define ACE_HAS_INTRINSIC_INTERLOCKED +# define ACE_HAS_INTRINSIC_BYTESWAP +#endif + +#if defined (ACE_HAS_STANDARD_CPP_LIBRARY) && (ACE_HAS_STANDARD_CPP_LIBRARY != 0) + +// Platform has its Standard C++ library in the namespace std +# if !defined (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB) +# define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 +# endif /* ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB */ + +// ace/iostream.h does not work with the standard cpp library (yet). +# if !defined (ACE_USES_OLD_IOSTREAMS) +# define ACE_LACKS_ACE_IOSTREAM +# endif /* ! ACE_USES_OLD_IOSTREAMS */ + +// Starting with MSVC 7.1, std::new throws std::bad_alloc on out-of-memory. +// Since we don't support MSVC 7.0, don't test for it. +# define ACE_NEW_THROWS_EXCEPTIONS +# define ACE_HAS_NEW_NOTHROW + +#else + +// iostream header lacks ipfx (), isfx (), etc., declarations +# define ACE_LACKS_IOSTREAM_FX + +#endif + +// There are too many instances of this warning to fix it right now. +// Maybe in the future. +// 'this' : used in base member initializer list +#pragma warning(disable:4355) + +// 'class1' : inherits 'class2::member' via dominance +#pragma warning(disable:4250) + +// C++ Exception Specification ignored +#pragma warning(disable:4290) + +// Disable warning of using Microsoft Extension. +#pragma warning(disable:4231) + +// 'function' : unreferenced local function has been removed +#pragma warning(disable:4505) + +// A template can not be exported. Only an instantiation may be exported. +#define ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION_EXPORT + +// At least for ACE_UNIMPLEMENTED_FUNC in class templates, this is needed to +// explicitly instantiate a template that has ACE_UNIMPLEMENTED_FUNC. +# define ACE_NEEDS_FUNC_DEFINITIONS + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_WIN32_MSVC_7_H */ diff --git a/dep/acelite/ace/config-win32-msvc-8.h b/dep/acelite/ace/config-win32-msvc-8.h new file mode 100644 index 00000000000..fafdd62d422 --- /dev/null +++ b/dep/acelite/ace/config-win32-msvc-8.h @@ -0,0 +1,163 @@ +/* -*- C++ -*- */ +//============================================================================= +/** + * @file config-win32-msvc-8.h + * + * $Id: config-win32-msvc-8.h 87224 2009-10-26 07:49:31Z olli $ + * + * @brief Microsoft Visual C++ 8.0 configuration file. + * + * This file is the ACE configuration file for Microsoft Visual C++ version 8. + * + * @note Do not include this file directly, include config-win32.h instead. + * + * @author Darrell Brunsch + */ +//============================================================================= + +#ifndef ACE_CONFIG_WIN32_MSVC_8_H +#define ACE_CONFIG_WIN32_MSVC_8_H +#include /**/ "ace/pre.h" + +#ifndef ACE_CONFIG_WIN32_H +#error Use config-win32.h in config.h instead of this header +#endif /* ACE_CONFIG_WIN32_H */ + +#ifndef ACE_WIN32_VC8 +# define ACE_WIN32_VC8 +#endif + +// Visual C++ 8.0 (.NET) deprecated the old iostreams +#if !defined (ACE_HAS_STANDARD_CPP_LIBRARY) +#define ACE_HAS_STANDARD_CPP_LIBRARY 1 +#endif + +#if !defined (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB) +#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 +#endif + +// Windows' timeval is non-conformant (defined in terms of long instead of +// time_t) and VC8 (on desktop, not CE) changed time_t to a 64-bit value +// even when compiling a 32-bit application. Therefore, ace/Time_Value +// needs to rearrange a few things for this compiler. See Time_Value.h +// for complete details. +#if !defined (ACE_HAS_WINCE) +# define ACE_HAS_TIME_T_LONG_MISMATCH +#endif + +#define ACE_HAS_ITOA +#define ACE_HAS_HEADER_ALLOCATED_CLASS_STATIC_CONST_INT_STOREAGE +#define ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR + +#define ACE_ITOA_EQUIVALENT ::_itoa +#define ACE_STRCASECMP_EQUIVALENT ::_stricmp +#define ACE_STRNCASECMP_EQUIVALENT ::_strnicmp +#define ACE_WCSDUP_EQUIVALENT ::_wcsdup +#if defined (ACE_HAS_WINCE) +# define ACE_FILENO_EQUIVALENT ::_fileno +#else +# define ACE_FILENO_EQUIVALENT(X) (_get_osfhandle (::_fileno (X))) +#endif + +#ifndef ACE_HAS_EXCEPTIONS +# define ACE_HAS_EXCEPTIONS +#endif + +// Windows Mobile 6 doesn't do sig_atomic_t, but maybe future versions will. +// This has been true up thrugh the versions. We don't have any indication +// that this might be supported in the future, but it is an easy enough fix +// to bump the wince revision number when a new version is released. +# if !defined (_WIN32_WCE) || (_WIN32_WCE > 0x601) +# define ACE_HAS_SIG_ATOMIC_T +# endif /* !Win CE 6.0 or less */ + +#define ACE_LACKS_STRPTIME + +#if !defined (ACE_HAS_WINCE) +# define ACE_HAS_INTRIN_H +# define ACE_HAS_INTRINSIC_INTERLOCKED +#endif + +#if !defined (_WIN32_WCE) || (_WIN32_WCE >= 0x501) +# define ACE_HAS_INTRINSIC_BYTESWAP +#endif + +#define ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES +#define ACE_LACKS_STRRECVFD +#define ACE_HAS_CPLUSPLUS_HEADERS + +#define ACE_HAS_TEMPLATE_TYPEDEFS +#define ACE_TEMPLATES_REQUIRE_SOURCE + +// Platform provides ACE_TLI function prototypes. +// For Win32, this is not really true, but saves a lot of hassle! +#define ACE_HAS_TLI_PROTOTYPES + +// Platform support linebuffered streaming is broken +#define ACE_LACKS_LINEBUFFERED_STREAMBUF + +#if defined (ACE_HAS_STANDARD_CPP_LIBRARY) && (ACE_HAS_STANDARD_CPP_LIBRARY != 0) + +// Platform has its Standard C++ library in the namespace std +# if !defined (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB) +# define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 +# endif /* ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB */ + +// ace/iostream.h does not work with the standard cpp library (yet). +# if !defined (ACE_USES_OLD_IOSTREAMS) +# define ACE_LACKS_ACE_IOSTREAM +# endif /* ! ACE_USES_OLD_IOSTREAMS */ + +// Starting with MSVC 7.1, std::new throws std::bad_alloc on out-of-memory. +#define ACE_NEW_THROWS_EXCEPTIONS +#define ACE_HAS_NEW_NOTHROW + +#else + +// iostream header lacks ipfx (), isfx (), etc., declarations +# define ACE_LACKS_IOSTREAM_FX + +#endif + +// There are too many instances of this warning to fix it right now. +// Maybe in the future. + +// Disable warning of using Microsoft Extension. +#pragma warning(disable:4231) + +// 'class1' : inherits 'class2::member' via dominance +#pragma warning(disable:4250) + +// 'this' : used in base member initializer list +#pragma warning(disable:4355) + +// CE (at least thru Windows Mobile 5) doesn't have the new, secure CRT. +#if !defined (ACE_HAS_WINCE) && !defined (ACE_HAS_TR24731_2005_CRT) +# define ACE_HAS_TR24731_2005_CRT +#endif + +//Detect Platform SDK 64-bit (AMD64) compiler using _MSC_FULL_VER +#if (defined (_WIN64) || defined (WIN64)) && _MSC_FULL_VER < 140050000 +# define ACE_AUTO_PTR_LACKS_RESET +# define ACE_MSVC_USES_DOUBLE_UNDERSCORE_STAT64 +# define ACE_HAS_BROKEN_STD_REVERSE_ITERATOR +# define ACE_LACKS_NUMERIC_LIMITS_64_BIT_TYPES +# undef ACE_HAS_TR24731_2005_CRT +# undef ACE_HAS_INTRIN_H +#endif + +// On CE w/o MFC config-WinCE.h needs to declare a placement new. This +// triggers a warning that there's no placement delete, which can be ignored. +#if defined (ACE_HAS_WINCE) && !defined (ACE_HAS_MFC) +# pragma warning(disable:4291) +#endif + +// A template can not be exported. Only an instantiation may be exported. +#define ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION_EXPORT + +// At least for ACE_UNIMPLEMENTED_FUNC in class templates, this is needed to +// explicitly instantiate a template that has ACE_UNIMPLEMENTED_FUNC. +# define ACE_NEEDS_FUNC_DEFINITIONS + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_WIN32_MSVC_8_H */ diff --git a/dep/acelite/ace/config-win32-msvc-9.h b/dep/acelite/ace/config-win32-msvc-9.h new file mode 100644 index 00000000000..bd6bcf60fc4 --- /dev/null +++ b/dep/acelite/ace/config-win32-msvc-9.h @@ -0,0 +1,153 @@ +/* -*- C++ -*- */ +//============================================================================= +/** + * @file config-win32-msvc-9.h + * + * $Id: config-win32-msvc-9.h 87224 2009-10-26 07:49:31Z olli $ + * + * @brief Microsoft Visual C++ 9.0 configuration file. + * + * This file is the ACE configuration file for Microsoft Visual C++ version 9. + * + * @note Do not include this file directly, include config-win32.h instead. + */ +//============================================================================= + +#ifndef ACE_CONFIG_WIN32_MSVC_9_H +#define ACE_CONFIG_WIN32_MSVC_9_H +#include /**/ "ace/pre.h" + +#ifndef ACE_CONFIG_WIN32_H +#error Use config-win32.h in config.h instead of this header +#endif /* ACE_CONFIG_WIN32_H */ + +#ifndef ACE_WIN32_VC9 +# define ACE_WIN32_VC9 +#endif + +// Visual C++ 9.0 (.NET) deprecated the old iostreams +#if !defined (ACE_HAS_STANDARD_CPP_LIBRARY) +#define ACE_HAS_STANDARD_CPP_LIBRARY 1 +#endif + +#if !defined (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB) +#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 +#endif + +// Windows' timeval is non-conformant (defined in terms of long instead of +// time_t) and VC9 (on desktop, not CE) changed time_t to a 64-bit value +// even when compiling a 32-bit application. Therefore, ace/Time_Value +// needs to rearrange a few things for this compiler. See Time_Value.h +// for complete details. +#if !defined (ACE_HAS_WINCE) +# define ACE_HAS_TIME_T_LONG_MISMATCH +#endif + +#define ACE_HAS_ITOA +#define ACE_HAS_HEADER_ALLOCATED_CLASS_STATIC_CONST_INT_STOREAGE +#define ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR + +#define ACE_ITOA_EQUIVALENT ::_itoa +#define ACE_STRCASECMP_EQUIVALENT ::_stricmp +#define ACE_STRNCASECMP_EQUIVALENT ::_strnicmp +#define ACE_WCSDUP_EQUIVALENT ::_wcsdup +#if defined (ACE_HAS_WINCE) +# define ACE_FILENO_EQUIVALENT ::_fileno +#else +# define ACE_FILENO_EQUIVALENT(X) (_get_osfhandle (::_fileno (X))) +#endif + +#ifndef ACE_HAS_EXCEPTIONS +# define ACE_HAS_EXCEPTIONS +#endif + +// Windows Mobile 6 doesn't do sig_atomic_t, but maybe future versions will. +# if !defined (_WIN32_WCE) || (_WIN32_WCE > 0x601) +# define ACE_HAS_SIG_ATOMIC_T +# endif /* !Win CE 6.0 or less */ + +#define ACE_LACKS_STRPTIME + +// Evaluate this with a WinCE build; maybe things have improved since VC8. +#if !defined (ACE_HAS_WINCE) +# define ACE_HAS_INTRIN_H +# define ACE_HAS_INTRINSIC_INTERLOCKED +#endif + +#if !defined (_WIN32_WCE) || (_WIN32_WCE >= 0x501) +# define ACE_HAS_INTRINSIC_BYTESWAP +#endif + +#define ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES +#define ACE_LACKS_STRRECVFD +#define ACE_HAS_CPLUSPLUS_HEADERS + +#define ACE_HAS_TEMPLATE_TYPEDEFS +#define ACE_TEMPLATES_REQUIRE_SOURCE + +// Platform provides ACE_TLI function prototypes. +// For Win32, this is not really true, but saves a lot of hassle! +#define ACE_HAS_TLI_PROTOTYPES + +// Platform support linebuffered streaming is broken +#define ACE_LACKS_LINEBUFFERED_STREAMBUF + +#if defined (ACE_HAS_STANDARD_CPP_LIBRARY) && (ACE_HAS_STANDARD_CPP_LIBRARY != 0) + +// Platform has its Standard C++ library in the namespace std +# if !defined (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB) +# define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 +# endif /* ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB */ + +// ace/iostream.h does not work with the standard cpp library (yet). +# if !defined (ACE_USES_OLD_IOSTREAMS) +# define ACE_LACKS_ACE_IOSTREAM +# endif /* ! ACE_USES_OLD_IOSTREAMS */ + +// Starting with MSVC 7.1, std::new throws std::bad_alloc on out-of-memory. +#define ACE_NEW_THROWS_EXCEPTIONS +#define ACE_HAS_NEW_NOTHROW + +#else + +// iostream header lacks ipfx (), isfx (), etc., declarations +# define ACE_LACKS_IOSTREAM_FX + +#endif + +// There are too many instances of this warning to fix it right now. +// Maybe in the future. + +// Disable warning of using Microsoft Extension. +# pragma warning(disable:4231) + +// 'class1' : inherits 'class2::member' via dominance +#pragma warning(disable:4250) + +// CE (at least thru Windows Mobile 5) doesn't have the new, secure CRT. +#if !defined (ACE_HAS_WINCE) && !defined (ACE_HAS_TR24731_2005_CRT) +# define ACE_HAS_TR24731_2005_CRT +#endif + +// On CE w/o MFC config-WinCE.h needs to declare a placement new. This +// triggers a warning that there's no placement delete, which can be ignored. +#if defined (ACE_HAS_WINCE) && !defined (ACE_HAS_MFC) +# pragma warning(disable:4291) +#endif + +// A template can not be exported. Only an instantiation may be exported. +#define ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION_EXPORT + +// At least for ACE_UNIMPLEMENTED_FUNC in class templates, this is needed to +// explicitly instantiate a template that has ACE_UNIMPLEMENTED_FUNC. +# define ACE_NEEDS_FUNC_DEFINITIONS + +// Windows Vista and Windows Server 2008 and newer do have native condition +// variables +#if defined (WIN32_WINNT) && (WIN32_WINNT >= 0x0600) +# define ACE_HAS_WTHREADS_CONDITION_VARIABLE +# undef ACE_LACKS_COND_T +#endif + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_WIN32_MSVC_9_H */ diff --git a/dep/acelite/ace/config-win32-msvc.h b/dep/acelite/ace/config-win32-msvc.h new file mode 100644 index 00000000000..6f62477b9dd --- /dev/null +++ b/dep/acelite/ace/config-win32-msvc.h @@ -0,0 +1,175 @@ +//============================================================================= +/** + * @file config-win32-msvc.h + * + * $Id: config-win32-msvc.h 85785 2009-06-24 18:20:42Z mitza $ + * + * @brief Microsoft Visual C++ configuration file. + * + * This file is the ACE configuration file for Microsoft Visual C++ versions + * 5.0, 6.0, and 7.0 (.NET) + * + * @author Darrell Brunsch + */ +//============================================================================= + +#ifndef ACE_CONFIG_WIN32_MSVC_H +#define ACE_CONFIG_WIN32_MSVC_H +#include /**/ "ace/pre.h" + +#ifndef ACE_CONFIG_WIN32_H +#error Use config-win32.h in config.h instead of this header +#endif /* ACE_CONFIG_WIN32_H */ + +#define ACE_CC_NAME ACE_TEXT ("Visual C++") +#ifndef ACE_USING_MCPP_PREPROCESSOR +# define ACE_CC_PREPROCESSOR "CL.EXE" +# define ACE_CC_PREPROCESSOR_ARGS "-nologo -E" +#endif + +#define ACE_CC_MAJOR_VERSION (_MSC_VER / 100 - 6) +#define ACE_CC_MINOR_VERSION (_MSC_VER % 100) +#define ACE_CC_BETA_VERSION (0) + +#if !defined(_NATIVE_WCHAR_T_DEFINED) + #define ACE_LACKS_NATIVE_WCHAR_T +#endif + +// Win Mobile still does thread exits differently than PC Windows. +#if defined (_WIN32_WCE) +# define ACE_ENDTHREADEX(STATUS) ExitThread ((DWORD) STATUS) +#else +# define ACE_ENDTHREADEX(STATUS) ::_endthreadex ((DWORD) STATUS) +#endif /* _WIN32_WCE */ + +//FUZZ: disable check_for_msc_ver +#if (_MSC_VER >= 1600) +# include "ace/config-win32-msvc-10.h" +#elif (_MSC_VER >= 1500) +# include "ace/config-win32-msvc-9.h" +#elif (_MSC_VER >= 1400) +# include "ace/config-win32-msvc-8.h" +#elif (_MSC_VER >= 1310) +# include "ace/config-win32-msvc-7.h" +#else +# error This version of Microsoft Visual C++ is not supported. +#endif +//FUZZ: enable check_for_msc_ver + +// MFC changes the behavior of operator new at all MSVC versions from 6 up +// by throwing a static CMemoryException* instead of std::bad_alloc +// (see ace/OS_Memory.h). This MFC exception object needs to be cleaned up +// by calling its Delete() method. +#if defined (ACE_HAS_MFC) && (ACE_HAS_MFC == 1) +# if !defined (ACE_NEW_THROWS_EXCEPTIONS) +# define ACE_NEW_THROWS_EXCEPTIONS +# endif +# if defined (ACE_bad_alloc) +# undef ACE_bad_alloc +# endif +# define ACE_bad_alloc CMemoryException *e +# if defined (ACE_del_bad_alloc) +# undef ACE_del_bad_alloc +# endif +# define ACE_del_bad_alloc e->Delete(); +#endif /* ACE_HAS_MFC && ACE_HAS_MFC==1 */ + +#if defined(ACE_MT_SAFE) && (ACE_MT_SAFE != 0) +// must have _MT defined to include multithreading +// features from win32 headers +# if !defined(_MT) && !defined (ACE_HAS_WINCE) +// *** DO NOT *** defeat this error message by defining _MT yourself. +// On MSVC, this is changed by selecting the Multithreaded +// DLL or Debug Multithreaded DLL in the Project Settings +// under C++ Code Generation. +# error You must link against multi-threaded libraries when using ACE (check your project settings) +# endif /* !_MT && !ACE_HAS_WINCE */ +#endif /* ACE_MT_SAFE && ACE_MT_SAFE != 0 */ + +#include +// Although ACE does have alloca() on this compiler/platform combination, it is +// disabled by default since it can be dangerous. Uncomment the following line +// if you ACE to use it. +//#define ACE_HAS_ALLOCA 1 + +#define ACE_LACKS_DIRENT_H +#define ACE_LACKS_DLFCN_H +#define ACE_LACKS_INTTYPES_H +#define ACE_LACKS_NETDB_H +#define ACE_LACKS_NET_IF_H +#define ACE_LACKS_NETINET_IN_H +#define ACE_LACKS_STDINT_H +#define ACE_LACKS_STROPTS_H +#define ACE_LACKS_SYS_IOCTL_H +#define ACE_LACKS_SYS_IPC_H +#define ACE_LACKS_SYS_MMAN_H +#define ACE_LACKS_SYS_RESOURCE_H +#define ACE_LACKS_SYS_SELECT_H +#define ACE_LACKS_SYS_SEM_H +#define ACE_LACKS_SYS_SOCKET_H +#define ACE_LACKS_SYS_TIME_H +#define ACE_LACKS_SYS_UIO_H +#define ACE_LACKS_SYS_WAIT_H +#define ACE_LACKS_UCONTEXT_H + +#define ACE_LACKS_SEMAPHORE_H +#define ACE_LACKS_STRINGS_H +#define ACE_LACKS_PWD_H +#define ACE_LACKS_POLL_H +#define ACE_LACKS_SYS_SHM_H +#define ACE_LACKS_SYS_MSG_H +#define ACE_LACKS_NETINET_TCP_H +#define ACE_LACKS_TERMIOS_H +#define ACE_LACKS_REGEX_H + +#define ACE_INT64_FORMAT_SPECIFIER_ASCII "%I64d" +#define ACE_UINT64_FORMAT_SPECIFIER_ASCII "%I64u" + +#define ACE_STRTOLL_EQUIVALENT ::_strtoi64 +#define ACE_WCSTOLL_EQUIVALENT ::_wcstoi64 +#define ACE_STRTOULL_EQUIVALENT ::_strtoui64 +#define ACE_WCSTOULL_EQUIVALENT ::_wcstoui64 +#define ACE_WTOF_EQUIVALENT ::_wtof + +#define ACE_LACKS_ISBLANK +#define ACE_LACKS_ISWBLANK +#define ACE_LACKS_CORRECT_ISWPRINT_TAB +#define ACE_ISCTYPE_EQUIVALENT ::_isctype + +// Turn off warnings for /W4 +// To resume any of these warning: #pragma warning(default: 4xxx) +// which should be placed after these defines + +#if !defined (ALL_WARNINGS) && defined(_MSC_VER) && !defined(ghs) && !defined(__MINGW32__) +# pragma warning(disable: 4127) /* constant expression for TRACE/ASSERT */ +# pragma warning(disable: 4134) /* message map member fxn casts */ +# pragma warning(disable: 4511) /* private copy constructors are good to have */ +# pragma warning(disable: 4512) /* private operator= are good to have */ +# pragma warning(disable: 4514) /* unreferenced inlines are common */ +# pragma warning(disable: 4710) /* private constructors are disallowed */ +# pragma warning(disable: 4705) /* statement has no effect in optimized code */ +# pragma warning(disable: 4791) /* loss of debugging info in retail version */ +# pragma warning(disable: 4275) /* deriving exported class from non-exported */ +# pragma warning(disable: 4251) /* using non-exported as public in exported */ +# pragma warning(disable: 4786) /* identifier was truncated to '255' characters in the browser information */ +# pragma warning(disable: 4097) /* typedef-name used as synonym for class-name */ +# pragma warning(disable: 4800) /* converting int to boolean */ +# if defined (__INTEL_COMPILER) +# pragma warning(disable: 1744) /* field of class type without a DLL interface used in a class with a DLL interface */ +# pragma warning(disable: 1738) +# endif +#endif /* !ALL_WARNINGS && _MSV_VER && !ghs && !__MINGW32__ */ + +// STRICT type checking in WINDOWS.H enhances type safety for Windows +// programs by using distinct types to represent all the different +// HANDLES in Windows. So for example, STRICT prevents you from +// mistakenly passing an HPEN to a routine expecting an HBITMAP. +// Note that we only use this if we +# if defined (ACE_HAS_STRICT) && (ACE_HAS_STRICT != 0) +# if !defined (STRICT) /* may already be defined */ +# define STRICT +# endif /* !STRICT */ +# endif /* ACE_HAS_STRICT */ + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_WIN32_MSVC_H */ diff --git a/dep/acelite/ace/config-win32.h b/dep/acelite/ace/config-win32.h new file mode 100644 index 00000000000..af946518cae --- /dev/null +++ b/dep/acelite/ace/config-win32.h @@ -0,0 +1,55 @@ +/* -*- C++ -*- */ +//============================================================================= +/** + * @file config-win32.h + * + * $Id: config-win32.h 85057 2009-04-08 10:59:58Z msmit $ + * + * @brief Microsoft Windows configuration file. + * + * This file is the ACE configuration file for all of Microsoft Windows + * platforms that ACE runs on. Based on preprocessor definitions, it + * includes other more specific configuration files. + * + * @author Darrell Brunsch + */ +//============================================================================= + +#ifndef ACE_CONFIG_WIN32_H +#define ACE_CONFIG_WIN32_H +#include /**/ "ace/pre.h" + +// NOTE: Please do not add anything besides #include's here. Put other stuff +// (definitions, etc.) in the included headers + +// We need to ensure that for Borland vcl.h can be included before +// windows.h. So we will not include config-win32-common.h from here, +// but instead let it be included at the appropriate place in +// config-win32-borland.h. +#if !defined (__BORLANDC__) +# include "ace/config-win32-common.h" +#endif /* !__BORLANDC__ */ + +// Include the config-win32-* file specific to the compiler +#if defined (__BORLANDC__) +# include "ace/config-win32-borland.h" +#elif defined (_MSC_VER) +# include "ace/config-win32-msvc.h" +#elif defined (ghs) +# include "ace/config-win32-ghs.h" +#elif defined (ACE_HAS_CEGCC) //need to be prior to MINGW32 +# include "ace/config-win32-cegcc.h" +#elif defined (__MINGW32__) +# include "ace/config-win32-mingw.h" +#elif defined (__DMC__) +# include "ace/config-win32-dmc.h" +#else +# error Compiler is not supported +#endif + +// gethostbyaddr does not handle IPv6-mapped-IPv4 addresses +#define ACE_HAS_BROKEN_GETHOSTBYADDR_V4MAPPED + +#include /**/ "ace/post.h" +#endif /* ACE_CONFIG_WIN32_H */ + diff --git a/dep/acelite/ace/config.h.in b/dep/acelite/ace/config.h.in new file mode 100644 index 00000000000..aa09aa48bf6 --- /dev/null +++ b/dep/acelite/ace/config.h.in @@ -0,0 +1,2204 @@ +/* ace/config.h.in. Generated from configure.ac by autoheader. */ + + +#ifndef ACE_CONFIG_H +#define ACE_CONFIG_H + +// ACE configuration header file + + + + +/* Compiler/platform standard C++ auto_ptr implementation lacks reset() method + */ +#undef ACE_AUTO_PTR_LACKS_RESET + +/* Enable ACE_Timeprobes */ +#undef ACE_COMPILE_TIMEPROBES + +/* */ +#undef ACE_DEFAULT_BASE_ADDR + +/* */ +#undef ACE_DEFAULT_BASE_ADDRL + +/* */ +#undef ACE_DEFAULT_CLOSE_ALL_HANDLES + +/* */ +#undef ACE_DEFAULT_MAX_SOCKET_BUFSIZ + +/* The default number of handles the select()-based reactor should handle */ +#undef ACE_DEFAULT_SELECT_REACTOR_SIZE + +/* Number of TSS keys, with ACE_HAS_TSS_EMULATION _only_. Defaults to 64. */ +#undef ACE_DEFAULT_THREAD_KEYS + +/* Define this if you don't want debug version ACE search for debug version + DLLs first before looking for the DLL names specified. */ +#undef ACE_DISABLE_DEBUG_DLL_CHECK + +/* Do not include emulation for timed semaphore acquisitions. */ +#undef ACE_DISABLE_POSIX_SEM_TIMEOUT_EMULATION + +/* Define to 1 to disable swapping swapping CDR on read */ +#undef ACE_DISABLE_SWAP_ON_READ + +/* Define to DLL file suffix */ +#undef ACE_DLL_SUFFIX + +/* Define to 1 to enable swapping swapping CDR on write */ +#undef ACE_ENABLE_SWAP_ON_WRITE + +/* Compiler requires template args when explicitly calling template + destructor. */ +#undef ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS + +/* Define to 1 if the getsockname() and getpeername() return random values in + the sockaddr_in.sin_zero field. */ +#undef ACE_GETNAME_RETURNS_RANDOM_SIN_ZERO + +/* Uses ctime_r & asctime_r with only two parameters vs. three. */ +#undef ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R + +/* Define to 1 if platform has 2 parameter sched_getaffinity() */ +#undef ACE_HAS_2_PARAM_SCHED_GETAFFINITY + +/* Define to 1 if platform has 2 parameter sched_setaffinity() */ +#undef ACE_HAS_2_PARAM_SCHED_SETAFFINITY + +/* Define to 1 if platform has 3 parameter readdir_r() */ +#undef ACE_HAS_3_PARAM_READDIR_R + +/* Define to 1 if platform has 3 parameter wcstok() */ +#undef ACE_HAS_3_PARAM_WCSTOK + +/* Platform has BSD 4.4 sendmsg()/recvmsg() APIs. */ +#undef ACE_HAS_4_4BSD_SENDMSG_RECVMSG + +/* Platform supports Asynchronous IO calls */ +#undef ACE_HAS_AIO_CALLS + +/* Platform has AIX4 ::read_real_time() */ +#undef ACE_HAS_AIX_HI_RES_TIMER + +/* Compiler/platform supports alloca(). */ +#undef ACE_HAS_ALLOCA + +/* Compiler/platform has */ +#undef ACE_HAS_ALLOCA_H + +/* Define to 1 if system should use Alpha's cycle counter */ +#undef ACE_HAS_ALPHA_TIMER + +/* Use ACE's alternate cuserid() implementation since a system cuserid() may + not exist, or it is not desirable to use it. The implementation requires + ACE_LACKS_PWD_FUNCTIONS to be undefined and that the geteuid() system call + exists. */ +#undef ACE_HAS_ALT_CUSERID + +/* Compiler/platform correctly calls init()/fini() for shared libraries. */ +#undef ACE_HAS_AUTOMATIC_INIT_FINI + +/* Compiler/platform has "big" fd_set, i.e. large number of bits set in fd_set + passed back from select(). */ +#undef ACE_HAS_BIG_FD_SET + +/* Platform sendv() does not work properly with datagrams, i.e. it fails when + the iovec size is IOV_MAX. */ +#undef ACE_HAS_BROKEN_DGRAM_SENDV + +/* Platform doesn't cast MAP_FAILED to a (void *). */ +#undef ACE_HAS_BROKEN_MAP_FAILED + +/* HP/UX does not wrap the mmap(2) header files with extern "C". */ +#undef ACE_HAS_BROKEN_MMAP_H + +/* Platform headers don't support prototypes */ +#undef ACE_HAS_BROKEN_MSG_H + +/* Platform defines struct timespec in */ +#undef ACE_HAS_BROKEN_POSIX_TIME + +/* OS/compiler's header files are inconsistent with libC definition of + rand_r(). */ +#undef ACE_HAS_BROKEN_RANDR + +/* Compiler/platform has the wrong prototype for t_error(), i.e., t_error(char + *) rather than t_error(const char *). */ +#undef ACE_HAS_BROKEN_T_ERROR + +/* Platform has (which contains bzero() prototype) */ +#undef ACE_HAS_BSTRING + +/* Define to 1 if platform has bswap16(). */ +#undef ACE_HAS_BSWAP16 + +/* Define to 1 if platform has bswap32(). */ +#undef ACE_HAS_BSWAP32 + +/* Define to 1 if platform has bswap64(). */ +#undef ACE_HAS_BSWAP64 + +/* Define to 1 if platform has bswap_16(). */ +#undef ACE_HAS_BSWAP_16 + +/* Define to 1 if platform has bswap_32(). */ +#undef ACE_HAS_BSWAP_32 + +/* Define to 1 if platform has bswap_64(). */ +#undef ACE_HAS_BSWAP_64 + +/* Define to 1 if platform has the header file. */ +#undef ACE_HAS_BYTESEX_H + +/* Define to 1 if platform has the header file. */ +#undef ACE_HAS_BYTESWAP_H + +/* Platform supports the Win32 CancelIO() function. (WinNT 4.0 and beyond) */ +#undef ACE_HAS_CANCEL_IO + +/* OS/platform uses char * for dlopen/dlsym args, rather than const char *. */ +#undef ACE_HAS_CHARPTR_DL + +/* Define to 1 if arg 2 of 'shmat' is char *' */ +#undef ACE_HAS_CHARPTR_SHMAT + +/* Define to 1 if arg 1 of 'shmdt' is char *' */ +#undef ACE_HAS_CHARPTR_SHMDT + +/* OS/platform uses char * for sockopt, rather than const char * */ +#undef ACE_HAS_CHARPTR_SOCKOPT + +/* Define to 1 if platform has clock_gettime(). */ +#undef ACE_HAS_CLOCK_GETTIME + +/* Define to 1 if platform has clock_settime(). */ +#undef ACE_HAS_CLOCK_SETTIME + +/* OS header files have some problems with XTI (HP/UX 11). */ +#undef ACE_HAS_CONFLICTING_XTI_MACROS + +/* Prototypes for both signal() and struct sigaction are consistent. */ +#undef ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES + +/* Platform has swab(const char*, char*, ssize_t) variant. */ +#undef ACE_HAS_CONST_CHAR_SWAB + +/* Compiler/platform has correctly prototyped header files. */ +#undef ACE_HAS_CPLUSPLUS_HEADERS + +/* Define to 1 if the system has the type `cpu_set_t'. */ +#undef ACE_HAS_CPU_SET_T + +/* Platform defines custom DSO/DLL symbol export macros. */ +#undef ACE_HAS_CUSTOM_EXPORT_MACROS + +/* Platform supports /dev/poll character device. */ +#undef ACE_HAS_DEV_POLL + +/* Platform supports operations on directories via struct dirent, readdir_r, + etc. */ +#undef ACE_HAS_DIRENT + +/* Build ACE using the frigging PC DLL nonsense... */ +#undef ACE_HAS_DLL + +/* Define to 1 if the dlsym() call segfaults when passed an invalid handle. */ +#undef ACE_HAS_DLSYM_SEGFAULT_ON_INVALID_HANDLE + +/* Platform (Linux) supports event poll interface. */ +#undef ACE_HAS_EVENT_POLL + +/* Compiler supports C++ exception handling. */ +#undef ACE_HAS_EXCEPTIONS + +/* Platform has Fast-Light (FL) toolkit installed. */ +#undef ACE_HAS_FL + +/* Define to 1 if compiler has builtin atomic support */ +#undef ACE_HAS_GCC_ATOMIC_BUILTINS + +/* Define to 1 if platform has getifaddrs(). */ +#undef ACE_HAS_GETIFADDRS + +/* Platform supports getpagesize() call (otherwise, ACE_PAGE_SIZE must be + defined, except on Win32). */ +#undef ACE_HAS_GETPAGESIZE + +/* Define to 1 if platform has getprogname(). */ +#undef ACE_HAS_GETPROGNAME + +/* Define to 1 if platform has getrusage(). */ +#undef ACE_HAS_GETRUSAGE + +/* Define to 1 if platform has the declaration of getrusage(). */ +#undef ACE_HAS_GETRUSAGE_PROTOTYPE + +/* Enable use of GNU template repositories. GNU C++ w/repo patch and EGCS only + */ +#undef ACE_HAS_GNU_REPO + +/* The GPERF utility is compiled for this platform */ +#undef ACE_HAS_GPERF + +/* Optimize ACE_Handle_Set::count_bits for select() operations (common case) + */ +#undef ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT + +/* Define to 1 if system has SunOS high resolution timer. */ +#undef ACE_HAS_HI_RES_TIMER + +/* Define to 1 if platform has the header file. */ +#undef ACE_HAS_IA32INTRIN_H + +/* Define to 1 if platform has the header file. */ +#undef ACE_HAS_IA64INTRIN_H + +/* Defined to 1 if platform supports ICMP over raw sockets */ +#undef ACE_HAS_ICMP_SUPPORT + +/* Define to 1 if the system has the type `idtype_t'. */ +#undef ACE_HAS_IDTYPE_T + +/* Inline all the static class OS methods to remove call overhead Note: This + gets defined by OS.h if __ACE_INLINE__ is defined */ +#undef ACE_HAS_INLINED_OSCALLS + +/* Define to 1 if the system has the type `int16_t'. */ +#undef ACE_HAS_INT16_T + +/* Define to 1 if the system has the type `int32_t'. */ +#undef ACE_HAS_INT32_T + +/* Define to 1 if the system has the type `int64_t'. */ +#undef ACE_HAS_INT64_T + +/* Define to 1 if the system has the type `int8_t'. */ +#undef ACE_HAS_INT8_T + +/* Define to 1 if the system supports x86/x86_64 inline assembly */ +#undef ACE_HAS_INTEL_ASSEMBLY + +/* Platform supports the intrinsic interlocked optimizations. */ +#undef ACE_HAS_INTRINSIC_INTERLOCKED + +/* Define to 1 if platform has the header file. */ +#undef ACE_HAS_INTRIN_H + +/* Platform supports IPv6 */ +#undef ACE_HAS_IPV6 + +/* Platform supports IP multicast */ +#undef ACE_HAS_IP_MULTICAST + +/* Platform supports the very odd IRIX 6.2 threads... */ +#undef ACE_HAS_IRIX62_THREADS + +/* Define to 1 if platform has the declaration of isastream(). */ +#undef ACE_HAS_ISASTREAM_PROTOTYPE + +/* Define to 1 if platform has itoa(). */ +#undef ACE_HAS_ITOA + +/* The rusage_t structure has only two fields. */ +#undef ACE_HAS_LIMITED_RUSAGE_T + +/* Define to 1 if system has Linux version of sysinfo(). */ +#undef ACE_HAS_LINUX_SYSINFO + +/* Platform supports llseek(). This should not be defined if ACE_HAS_LSEEK64 + is defined. */ +#undef ACE_HAS_LLSEEK + +/* Platform defines MAP_FAILED as a long constant. */ +#undef ACE_HAS_LONG_MAP_FAILED + +/* Platform supports lseek64(). This should not be defined if ACE_HAS_LLSEEK + is defined. */ +#undef ACE_HAS_LSEEK64 + +/* */ +#undef ACE_HAS_LYNXOS4_SIGNALS + +/* Enabled malloc statistics collection. */ +#undef ACE_HAS_MALLOC_STATS + +/* Define to 1 if platform has memchr(). */ +#undef ACE_HAS_MEMCHR + +/* Define to 1 if unrolled ACE_OS::fast_memcpy() is faster than system + memcpy() */ +#undef ACE_HAS_MEMCPY_LOOP_UNROLL + +/* Platform supports Microsoft Foundation Classes */ +#undef ACE_HAS_MFC + +/* Define to 1 if platform has mkdir(). */ +#undef ACE_HAS_MKDIR + +/* Platform supports recvmsg and sendmsg */ +#undef ACE_HAS_MSG + +/* Platform supports MT safe mktime() call (do any of them?) */ +#undef ACE_HAS_MT_SAFE_MKTIME + +/* Sockets may be called in multi-threaded programs */ +#undef ACE_HAS_MT_SAFE_SOCKETS + +/* Compiler supports timed mutex acquisitions (e.g. + pthread_mutex_timedlock()). */ +#undef ACE_HAS_MUTEX_TIMEOUTS + +/* Define to 1 if platform has nanosleep(). */ +#undef ACE_HAS_NANOSLEEP + +/* Define to 1 if platform has the header file. */ +#undef ACE_HAS_NEW_H + +/* Compiler supports new (std::nothrow) */ +#undef ACE_HAS_NEW_NOTHROW + +/* Platform provides new style C++ header */ +#undef ACE_HAS_NEW_NO_H + +/* Define to 1 if system has nonconst FD_ISSET() macro. */ +#undef ACE_HAS_NONCONST_FD_ISSET + +/* Platform uses non-const char * in calls to gethostbyaddr, gethostbyname, + getservbyname */ +#undef ACE_HAS_NONCONST_GETBY + +/* Platform has a non-const parameter to msgsnd() (e.g., SCO). */ +#undef ACE_HAS_NONCONST_MSGSND + +/* Platform omits const qualifier from iovec parameter in readv() prototype. + */ +#undef ACE_HAS_NONCONST_READV + +/* Platform's select() uses non-const timeval* (only found on Linux right now) + */ +#undef ACE_HAS_NONCONST_SELECT_TIMEVAL + +/* Platform omits const qualifier from msghdr parameter in sendmsg() + prototype. */ +#undef ACE_HAS_NONCONST_SENDMSG + +/* Platform omits const qualifier from rlimit parameter in setrlimit() + prototype. */ +#undef ACE_HAS_NONCONST_SETRLIMIT + +/* Platform has swab(char*, char*, ssize_t) variant. */ +#undef ACE_HAS_NONCONST_SWAB + +/* Platform omits const qualifier from iovec parameter in writev() prototype. + */ +#undef ACE_HAS_NONCONST_WRITEV + +/* Causes the ACE_Object_Manager instance to be created in main (int, char + *[]), instead of as a static (global) instance. */ +#undef ACE_HAS_NONSTATIC_OBJECT_MANAGER + +/* Compiler/platform uses old malloc()/free() prototypes (ugh) */ +#undef ACE_HAS_OLD_MALLOC + +/* Platform, e.g., Solaris 2.5, only supports SCHED_OTHER POSIX scheduling + policy. */ +#undef ACE_HAS_ONLY_SCHED_OTHER + +/* Use the semaphore implementation of ACE_Message_Queue rather than the + emulated condition variable (NT and VxWorks). */ +#undef ACE_HAS_OPTIMIZED_MESSAGE_QUEUE + +/* timezone* 2nd parameter & no prototype */ +#undef ACE_HAS_OSF1_GETTIMEOFDAY + +/* Platform supports the OSF TLI timod STREAMS module */ +#undef ACE_HAS_OSF_TIMOD_H + +/* Define to 1 if platform has the header file. */ +#undef ACE_HAS_PDH_H + +/* Define to 1 if system is using Intel Pentium(tm) processor */ +#undef ACE_HAS_PENTIUM + +/* Platform contains */ +#undef ACE_HAS_POLL + +/* Platform supports "position-independent" features provided by + ACE_Based_Pointer<>. */ +#undef ACE_HAS_POSITION_INDEPENDENT_POINTERS + +/* Platform supports POSIX getpwnam_r() function */ +#undef ACE_HAS_POSIX_GETPWNAM_R + +/* Platform supports POSIX O_NONBLOCK semantics */ +#undef ACE_HAS_POSIX_NONBLOCK + +/* Platform supports POSIX realtime signals */ +#undef ACE_HAS_POSIX_REALTIME_SIGNALS + +/* Platform supports POSIX real-time semaphores (e.g., VxWorks and Solaris) */ +#undef ACE_HAS_POSIX_SEM + +/* Platform supports timed POSIX semaphore acquisitions (sem_timedwait()). */ +#undef ACE_HAS_POSIX_SEM_TIMEOUT + +/* Platform supports the POSIX struct timespec type */ +#undef ACE_HAS_POSIX_TIME + +/* Define to 1 if system should use PowerPC's cycle counter */ +#undef ACE_HAS_POWERPC_TIMER + +/* OS has priocntl (2) */ +#undef ACE_HAS_PRIOCNTL + +/* Platform supports the /proc file system and defines tid_t in + */ +#undef ACE_HAS_PROC_FS + +/* Define to 1 if the system has the type `prusage_t'. */ +#undef ACE_HAS_PRUSAGE_T + +/* Define to 1 if platform has POSIX threads */ +#undef ACE_HAS_PTHREADS + +/* Platform supports POSIX Threads .4a Draft 4 */ +#undef ACE_HAS_PTHREADS_DRAFT4 + +/* Platform supports POSIX Threads .4a Draft 6 */ +#undef ACE_HAS_PTHREADS_DRAFT6 + +/* Platform supports POSIX Threads .1c Draft 7 */ +#undef ACE_HAS_PTHREADS_DRAFT7 + +/* Platform supports POSIX.1c-1995 threads */ +#undef ACE_HAS_PTHREADS_STD + +/* Platform has the UNIX98 extensions to Pthreads (rwlocks) */ +#undef ACE_HAS_PTHREADS_UNIX98_EXT + +/* Define to 1 if platform has pthread_attr_setcreatesuspend_np(). */ +#undef ACE_HAS_PTHREAD_ATTR_SETCREATESUSPEND_NP + +/* Define to 1 if platform has pthread_condattr_setkind_np(). */ +#undef ACE_HAS_PTHREAD_CONDATTR_SETKIND_NP + +/* Define to 1 if platform has pthread_continue(). */ +#undef ACE_HAS_PTHREAD_CONTINUE + +/* Define to 1 if platform has pthread_continue_np(). */ +#undef ACE_HAS_PTHREAD_CONTINUE_NP + +/* Define to 1 if platform has pthread_getaffinity_np(). */ +#undef ACE_HAS_PTHREAD_GETAFFINITY_NP + +/* Define to 1 if platform has pthread_getconcurrency(). */ +#undef ACE_HAS_PTHREAD_GETCONCURRENCY + +/* Define to 1 if platform has pthread_mutexattr_setkind_np(). */ +#undef ACE_HAS_PTHREAD_MUTEXATTR_SETKIND_NP + +/* Define to 1 if platform has the header file. */ +#undef ACE_HAS_PTHREAD_NP_H + +/* pthread.h declares an enum with PTHREAD_PROCESS_PRIVATE and + PTHREAD_PROCESS_SHARED values */ +#undef ACE_HAS_PTHREAD_PROCESS_ENUM + +/* Define to 1 if platform has pthread_resume_np(). */ +#undef ACE_HAS_PTHREAD_RESUME_NP + +/* Define to 1 if platform has pthread_setaffinity_np(). */ +#undef ACE_HAS_PTHREAD_SETAFFINITY_NP + +/* Define to 1 if platform has pthread_setconcurrency(). */ +#undef ACE_HAS_PTHREAD_SETCONCURRENCY + +/* Define to 1 if platform has the declaration of pthread_sigmask(). */ +#undef ACE_HAS_PTHREAD_SIGMASK_PROTOTYPE + +/* Define to 1 if platform has pthread_suspend(). */ +#undef ACE_HAS_PTHREAD_SUSPEND + +/* Define to 1 if platform has pthread_suspend_np(). */ +#undef ACE_HAS_PTHREAD_SUSPEND_NP + +/* Purify'ing. Defined on command line. */ +#undef ACE_HAS_PURIFY + +/* Platform has pread() and pwrite() support. */ +#undef ACE_HAS_P_READ_WRITE + +/* Quantify'ing. Defined on command line. */ +#undef ACE_HAS_QUANTIFY + +/* Define to 1 to configure Reactor to use a user-space queue for + notifications */ +#undef ACE_HAS_REACTOR_NOTIFICATION_QUEUE + +/* Mutexes are inherently recursive (e.g., Win32) */ +#undef ACE_HAS_RECURSIVE_MUTEXES + +/* Platform will recurse infinitely on thread exits from TSS cleanup routines + (e.g., AIX) */ +#undef ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS + +/* Platform supports reentrant functions (i.e., all the POSIX *_r functions). + */ +#undef ACE_HAS_REENTRANT_FUNCTIONS + +/* Platform supports the POSIX regular expression library */ +#undef ACE_HAS_REGEX + +/* Platform has enum instead of int for first argument to ::{get,set}rlimit + (). The value of this macro is the enum definition, e.g., enum + __rlimit_resource, for Linux glibc 2.0. */ +#undef ACE_HAS_RLIMIT_RESOURCE_ENUM + +/* Platform has enum instead of int for first argument to ::getrusage (). The + value of this macro is the enum definition, e.g., enum __rusage_who, for + Linux glibc 2.0. */ +#undef ACE_HAS_RUSAGE_WHO_ENUM + +/* Define to 1 if platform has sched_getaffinity(). */ +#undef ACE_HAS_SCHED_GETAFFINITY + +/* Define to 1 if platform has sched_setaffinity(). */ +#undef ACE_HAS_SCHED_SETAFFINITY + +/* Define to 1 if platform has the header file. */ +#undef ACE_HAS_SELECT_H + +/* Compiler/platform defines a union semun for SysV shared memory */ +#undef ACE_HAS_SEMUN + +/* Define to 1 if platform has setprogname(). */ +#undef ACE_HAS_SETPROGNAME + +/* Define to 1 if platform has set_t_errno(). */ +#undef ACE_HAS_SET_T_ERRNO + +/* Platform has shm_open() */ +#undef ACE_HAS_SHM_OPEN + +/* Platform's sigaction() function takes const sigaction* as 2nd parameter */ +#undef ACE_HAS_SIGACTION_CONSTP2 + +/* Define to 1 if the system has the type `siginfo_t'. */ +#undef ACE_HAS_SIGINFO_T + +/* Platform has bug with sigismember() (HP/UX 11). */ +#undef ACE_HAS_SIGISMEMBER_BUG + +/* Platform supports the Win32 SignalObjectAndWait() function (WinNT 4.0 and + beyond). */ +#undef ACE_HAS_SIGNAL_OBJECT_AND_WAIT + +/* Define to 1 if platform has sigsuspend(). */ +#undef ACE_HAS_SIGSUSPEND + +/* Define to 1 if platform has sigtimedwait(). */ +#undef ACE_HAS_SIGTIMEDWAIT + +/* Define to 1 if `sigval_int' is a member of `union sigval'. */ +#undef ACE_HAS_SIGVAL_SIGVAL_INT + +/* Define to 1 if `sigval_ptr' is a member of `union sigval'. */ +#undef ACE_HAS_SIGVAL_SIGVAL_PTR + +/* Define to 1 if platform has sigwait(). */ +#undef ACE_HAS_SIGWAIT + +/* Define to 1 if the system has the type 'sig_atomic_t'. */ +#undef ACE_HAS_SIG_ATOMIC_T + +/* Compiler requires extern "C" functions for signals. */ +#undef ACE_HAS_SIG_C_FUNC + +/* OS/compiler uses size_t * rather than int * for socket lengths */ +#undef ACE_HAS_SIZET_SOCKET_LEN + +/* Define to 1 if `sin6_len' is a member of `sockaddr_in6'. */ +#undef ACE_HAS_SOCKADDR_IN6_SIN6_LEN + +/* Define to 1 if `sin_len' is a member of `sockaddr_in'. */ +#undef ACE_HAS_SOCKADDR_IN_SIN_LEN + +/* Platform requires (struct sockaddr *) for msg_name field of struct msghdr. + */ +#undef ACE_HAS_SOCKADDR_MSG_NAME + +/* Define to 1 if the system has the type `socklen_t'. */ +#undef ACE_HAS_SOCKLEN_T + +/* Define to 1 if the system has the type `ssize_t'. */ +#undef ACE_HAS_SSIZE_T + +/* Platform/compiler supports Standard C++ Library */ +#undef ACE_HAS_STANDARD_CPP_LIBRARY + +/* Platform has void (*)(...) prototype for pthread_key_create() destructor + (e.g., LynxOS). */ +#undef ACE_HAS_STDARG_THR_DEST + +/* */ +#undef ACE_HAS_STDCPP_STL_INCLUDES + +/* Platform provides C++ header */ +#undef ACE_HAS_STDEXCEPT_NO_H + +/* Define to 1 if platform has UNIX International Threads */ +#undef ACE_HAS_STHREADS + +/* Define to 1 if the system has the type `struct strbuf'. */ +#undef ACE_HAS_STRBUF_T + +/* Define to 1 use ACE's strdup() emulation */ +#undef ACE_HAS_STRDUP_EMULATION + +/* Platform supports STREAMS */ +#undef ACE_HAS_STREAMS + +/* Platform supports STREAM pipes */ +#undef ACE_HAS_STREAM_PIPES + +/* Use the STRICT compilation mode on Win32. */ +#undef ACE_HAS_STRICT + +/* Platform has (which contains bzero() prototype) */ +#undef ACE_HAS_STRINGS + +/* Platform/Compiler supports a String class (e.g., GNU or Win32). */ +#undef ACE_HAS_STRING_CLASS + +/* Define to 1 if platform has strnlen(). */ +#undef ACE_HAS_STRNLEN + +/* Define to 1 if platform has strsignal(). */ +#undef ACE_HAS_STRSIGNAL + +/* Compiler/platform has strange hostent API for socket *_r() calls */ +#undef ACE_HAS_STRUCT_NETDB_DATA + +/* Compiler/platform supports SVR4 dynamic linking semantics */ +#undef ACE_HAS_SVR4_DYNAMIC_LINKING + +/* Compiler/platform supports SVR4 gettimeofday() prototype but doesn't have a + prototype */ +#undef ACE_HAS_SVR4_GETTIMEOFDAY + +/* Compiler/platform supports SVR4 signal typedef. */ +#undef ACE_HAS_SVR4_SIGNAL_T + +/* Compiler/platform supports SVR4 TLI (in particular, T_GETNAME stuff). */ +#undef ACE_HAS_SVR4_TLI + +/* Define to 1 if platform has sysctl(). */ +#undef ACE_HAS_SYSCTL + +/* Define to 1 if platform has the header file. */ +#undef ACE_HAS_SYSENT_H + +/* Platform supports System V IPC (most versions of UNIX, but not Win32) */ +#undef ACE_HAS_SYSV_IPC + +/* Define to 1 if system has SysV version of sysinfo(). */ +#undef ACE_HAS_SYSV_SYSINFO + +/* Define to 1 if platform has the header file. */ +#undef ACE_HAS_SYS_FILIO_H + +/* Define to 1 if platform has the header file. */ +#undef ACE_HAS_SYS_LOADAVG_H + +/* Define to 1 if platform has the header file. */ +#undef ACE_HAS_SYS_PSTAT_H + +/* Compiler/platform supports _sys_siglist array */ +#undef ACE_HAS_SYS_SIGLIST + +/* Define to 1 if platform has the header file. */ +#undef ACE_HAS_SYS_SOCKIO_H + +/* Define to 1 if platform has the header file. */ +#undef ACE_HAS_SYS_SYSCALL_H + +/* Define to 1 if platform has the header file. */ +#undef ACE_HAS_SYS_SYSINFO_H + +/* Define to 1 if platform has the header file. */ +#undef ACE_HAS_SYS_SYSTEMINFO_H + +/* Platform provides header */ +#undef ACE_HAS_SYS_XTI_H + +/* */ +#undef ACE_HAS_TANDEM_SIGNALS + +/* Compiler implements templates that support typedefs inside of classes used + as formal arguments to a template class. */ +#undef ACE_HAS_TEMPLATE_TYPEDEFS + +/* Define to 1 if system supports SysV tty API. */ +#undef ACE_HAS_TERMIO + +/* Define to 1 if system supports POSIX tty API. */ +#undef ACE_HAS_TERMIOS + +/* Platform supports threads. */ +#undef ACE_HAS_THREADS + +/* Platform allows multiple threads to call accept() on the same port (e.g., + WinNT). */ +#undef ACE_HAS_THREAD_SAFE_ACCEPT + +/* Platform has thread_self() rather than pthread_self() (e.g., DCETHREADS and + AIX) */ +#undef ACE_HAS_THREAD_SELF + +/* Compiler/platform has thread-specific storage */ +#undef ACE_HAS_THREAD_SPECIFIC_STORAGE + +/* The pthread_keycreate() routine *must* take extern C functions. */ +#undef ACE_HAS_THR_C_DEST + +/* The pthread_create() routine *must* take extern C functions. */ +#undef ACE_HAS_THR_C_FUNC + +/* Platform supports thr_keydelete (e.g,. UNIXWARE) */ +#undef ACE_HAS_THR_KEYDELETE + +/* Platform calls thr_minstack() rather than thr_min_stack() (e.g., Tandem). + */ +#undef ACE_HAS_THR_MINSTACK + +/* Platform has thr_yield() */ +#undef ACE_HAS_THR_YIELD + +/* Define to 1 if platform has global timezone variable */ +#undef ACE_HAS_TIMEZONE + +/* Platform/compiler supports timezone * as second parameter to gettimeofday() + and has a prototype. */ +#undef ACE_HAS_TIMEZONE_GETTIMEOFDAY + +/* Platform supports TLI timod STREAMS module */ +#undef ACE_HAS_TIMOD_H + +/* Platform supports TLI tiuser header */ +#undef ACE_HAS_TIUSER_H + +/* Platform does not protect with extern "C" */ +#undef ACE_HAS_TIUSER_H_BROKEN_EXTERN_C + +/* Platform supports TLI. Also see ACE_TLI_TCP_DEVICE. */ +#undef ACE_HAS_TLI + +/* Platform provides TLI function prototypes */ +#undef ACE_HAS_TLI_PROTOTYPES + +/* ACE provides TSS emulation. See also ACE_DEFAULT_THREAD_KEYS. */ +#undef ACE_HAS_TSS_EMULATION + +/* Define to 1 if platform has ualarm(). */ +#undef ACE_HAS_UALARM + +/* Define to 1 if the system has the type `ucontext_t'. */ +#undef ACE_HAS_UCONTEXT_T + +/* Define to 1 if the system has the type `uint16_t'. */ +#undef ACE_HAS_UINT16_T + +/* Define to 1 if the system has the type `uint32_t'. */ +#undef ACE_HAS_UINT32_T + +/* Define to 1 if the system has the type `uint64_t'. */ +#undef ACE_HAS_UINT64_T + +/* Define to 1 if the system has the type `uint8_t'. */ +#undef ACE_HAS_UINT8_T + +/* Has inconsistent SVR4 signal stuff, but not the same as the other platforms + */ +#undef ACE_HAS_UNIXWARE_SVR4_SIGNAL_T + +/* Define to 1 if platform has vasprintf(). */ +#undef ACE_HAS_VASPRINTF + +/* Define to 1 if platform has vaswprintf(). */ +#undef ACE_HAS_VASWPRINTF + +/* Prints out console message in ACE_NOTSUP. Useful for tracking down origin + of ACE_NOTSUP. */ +#undef ACE_HAS_VERBOSE_NOTSUP + +/* Define to 1 if platform has vfwprintf(). */ +#undef ACE_HAS_VFWPRINTF + +/* Platform/compiler supports void * as second parameter to gettimeofday() and + has a prototype. */ +#undef ACE_HAS_VOIDPTR_GETTIMEOFDAY + +/* Platform requires void * for mmap(). */ +#undef ACE_HAS_VOIDPTR_MMAP + +/* OS/compiler uses void * arg 4 setsockopt() rather than const char * */ +#undef ACE_HAS_VOIDPTR_SOCKOPT + +/* Define to 1 if platform has vswprintf(). */ +#undef ACE_HAS_VSWPRINTF + +/* Platform/compiler supports wchar_t */ +#undef ACE_HAS_WCHAR + +/* Define to 1 use ACE's wcsdup() emulation */ +#undef ACE_HAS_WCSDUP_EMULATION + +/* Define to 1 if platform has wcsnlen(). */ +#undef ACE_HAS_WCSNLEN + +/* Platform/compiler supports Win32 structural exceptions. */ +#undef ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS + +/* The Win32 platform support TryEnterCriticalSection(). (WinNT 4.0 and + beyond) */ +#undef ACE_HAS_WIN32_TRYLOCK + +/* The Win32 platform supports WinSock 2.0. */ +#undef ACE_HAS_WINSOCK2 + +/* Compiler handles explicit calling of template destructor correctly. */ +#undef ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR + +/* Solaris for intel uses macros for fstat() and stat(), these are wrappers + for _fxstat() and _xstat() uses of the macros. Causes compile and runtime + problems. */ +#undef ACE_HAS_X86_STAT_MACROS + +/* Platform has the XLI version of TLI */ +#undef ACE_HAS_XLI + +/* Platform has support for multi-byte character support compliant with the + XPG4 Worldwide Portability Interface wide-character classification. */ +#undef ACE_HAS_XPG4_MULTIBYTE_CHAR + +/* Platform has Xt Intrinsics Toolkit */ +#undef ACE_HAS_XT + +/* Platform has XTI (X/Open-standardized superset of TLI). Implies ACE_HAS_TLI + but uses a different header file. */ +#undef ACE_HAS_XTI + +/* Define to 1 if platform has _InterlockedDecrement(). */ +#undef ACE_HAS__INTERLOCKEDDECREMENT + +/* Define to 1 if platform has _InterlockedExchangeAdd(). */ +#undef ACE_HAS__INTERLOCKEDEXCHANGEADD + +/* Define to 1 if platform has _InterlockedIncrement(). */ +#undef ACE_HAS__INTERLOCKEDINCREMENT + +/* Define to the *printf format specifier (e.g. "%lld") for ACE_INT64 */ +#undef ACE_INT64_FORMAT_SPECIFIER + +/* Define to signed 64 bit integer type */ +#undef ACE_INT64_TYPE + +/* Define to the type of arg 2 for `ioctl'. */ +#undef ACE_IOCTL_TYPE_ARG2 + +/* Define to 1 if platform lacks access(). */ +#undef ACE_LACKS_ACCESS + +/* Do not compile support for the "Codecs" ACE features. */ +#undef ACE_LACKS_ACE_CODECS + +/* Platform can not build ace/IOStream{,_T}.cpp. This does not necessarily + mean that the platform does not support iostreams. */ +#undef ACE_LACKS_ACE_IOSTREAM + +/* Do not compile support for the "other" ACE features, such as CORBA + handling, name services, and QoS. */ +#undef ACE_LACKS_ACE_OTHER + +/* Do not compile support for the ACE Service Configurator. */ +#undef ACE_LACKS_ACE_SVCCONF + +/* Do not compile support for the ACE Token feature. */ +#undef ACE_LACKS_ACE_TOKEN + +/* Do not compile support for the ACE UUID feature. */ +#undef ACE_LACKS_ACE_UUID + +/* Define to 1 if platform lacks alarm(). */ +#undef ACE_LACKS_ALARM + +/* Define to 1 if platform lacks alphasort(). */ +#undef ACE_LACKS_ALPHASORT + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_ARPA_INET_H + +/* Define to 1 if platform lacks asctime(). */ +#undef ACE_LACKS_ASCTIME + +/* Define to 1 if platform lacks asctime_r(). */ +#undef ACE_LACKS_ASCTIME_R + +/* No system support for replacing any previous mappings. */ +#undef ACE_LACKS_AUTO_MMAP_REPLACEMENT + +/* Platform lacks support for the standard C++ auto_ptr class */ +#undef ACE_LACKS_AUTO_PTR + +/* Define to 1 if platform lacks bsearch(). */ +#undef ACE_LACKS_BSEARCH + +/* Define to 1 to support unaligned CDR */ +#undef ACE_LACKS_CDR_ALIGNMENT + +/* Compiler does not have any istream operator>> for chars, u_chars, or signed + chars. */ +#undef ACE_LACKS_CHAR_RIGHT_SHIFTS + +/* Compiler does not have operator>> (istream &, u_char *) or operator>> + (istream &, signed char *) */ +#undef ACE_LACKS_CHAR_STAR_RIGHT_SHIFTS + +/* Define to 1 if platform lacks chdir(). */ +#undef ACE_LACKS_CHDIR + +/* Define to 1 if system lacks pthread_condattr_setpshared() */ +#undef ACE_LACKS_CONDATTR_PSHARED + +/* Platform lacks condition variables (e.g., Win32 and VxWorks) */ +#undef ACE_LACKS_COND_T + +/* pthread_cond_timedwait does *not* reset the time argument when the lock is + acquired. */ +#undef ACE_LACKS_COND_TIMEDWAIT_RESET + +/* Platform uses struct strbuf * rather than const struct strbuf * (e.g., + HP/UX 10.x) */ +#undef ACE_LACKS_CONST_STRBUF_PTR + +/* Platform forgot const in cond_timewait (e.g., HP/UX). */ +#undef ACE_LACKS_CONST_TIMESPEC_PTR + +/* Define to 1 if platform lacks difftime(). */ +#undef ACE_LACKS_DIFFTIME + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_DIRENT_H + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_DLFCN_H + +/* Define to 1 if platform lacks dup(). */ +#undef ACE_LACKS_DUP + +/* Define to 1 if platform lacks dup2(). */ +#undef ACE_LACKS_DUP2 + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_ERRNO_H + +/* Platform lacks the exec() family of system calls (e.g., Win32, VxWorks, + Chorus) */ +#undef ACE_LACKS_EXEC + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_EXECINFO_H + +/* Define to 1 if platform lacks fcntl(). */ +#undef ACE_LACKS_FCNTL + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_FCNTL_H + +/* Define to 1 if platform lacks fgetwc(). */ +#undef ACE_LACKS_FGETWC + +/* Define to 1 if platform lacks fgetws(). */ +#undef ACE_LACKS_FGETWS + +/* Define to 1 if the system lacks the type `struct flock'. */ +#undef ACE_LACKS_FILELOCKS + +/* Define to 1 if platform lacks fork(). */ +#undef ACE_LACKS_FORK + +/* Define to 1 if platform lacks fputws(). */ +#undef ACE_LACKS_FPUTWS + +/* Define to 1 if platform lacks fsync(). */ +#undef ACE_LACKS_FSYNC + +/* Define to 1 if platform lacks getcwd(). */ +#undef ACE_LACKS_GETCWD + +/* Define to 1 if platform lacks getegid(). */ +#undef ACE_LACKS_GETEGID + +/* Define to 1 if platform lacks geteuid(). */ +#undef ACE_LACKS_GETEUID + +/* Define to 1 if platform lacks getgid(). */ +#undef ACE_LACKS_GETGID + +/* Define to 1 if platform lacks gethostent(). */ +#undef ACE_LACKS_GETHOSTENT + +/* Define to 1 if platform lacks getipnodebyaddr(). */ +#undef ACE_LACKS_GETIPNODEBYADDR + +/* Define to 1 if platform lacks getipnodebyname(). */ +#undef ACE_LACKS_GETIPNODEBYNAME + +/* Define to 1 if platform lacks getopt(). */ +#undef ACE_LACKS_GETOPT + +/* Define to 1 if platform lacks the declaration of getopt(). */ +#undef ACE_LACKS_GETOPT_PROTOTYPE + +/* Define to 1 if platform lacks getpgid(). */ +#undef ACE_LACKS_GETPGID + +/* Define to 1 if platform lacks getpgid() declaration in . */ +#undef ACE_LACKS_GETPGID_PROTOTYPE + +/* Define to 1 if platform lacks getpid(). */ +#undef ACE_LACKS_GETPID + +/* Define to 1 if platform lacks getppid(). */ +#undef ACE_LACKS_GETPPID + +/* Platforms lacks getservbyname() (e.g., VxWorks and Chorus). */ +#undef ACE_LACKS_GETSERVBYNAME + +/* Define to 1 if platform lacks getuid(). */ +#undef ACE_LACKS_GETUID + +/* Define to 1 if platform lacks gmtime(). */ +#undef ACE_LACKS_GMTIME + +/* Define to 1 if platform lacks gmtime_r(). */ +#undef ACE_LACKS_GMTIME_R + +/* Define to 1 if platform lacks inet_aton(). */ +#undef ACE_LACKS_INET_ATON + +/* Platform can't handle "inline" keyword correctly. */ +#undef ACE_LACKS_INLINE_FUNCTIONS + +/* Define to 1 if the system lacks the type `intmax_t'. */ +#undef ACE_LACKS_INTMAX_T + +/* Define to 1 if the system lacks the type `intptr_t'. */ +#undef ACE_LACKS_INTPTR_T + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_INTTYPES_H + +/* iostream header does not declare ipfx (), opfx (), etc. */ +#undef ACE_LACKS_IOSTREAM_FX + +/* iostreams are not supported adequately on the given platform. */ +#undef ACE_LACKS_IOSTREAM_TOTALLY + +/* Define to 1 if platform lacks isatty(). */ +#undef ACE_LACKS_ISATTY + +/* Define to 1 if platform lacks isblank(). */ +#undef ACE_LACKS_ISBLANK + +/* Define to 1 if platform lacks isctype(). */ +#undef ACE_LACKS_ISCTYPE + +/* Define to 1 if platform lacks iswblank(). */ +#undef ACE_LACKS_ISWBLANK + +/* Define to 1 if platform lacks iswctype(). */ +#undef ACE_LACKS_ISWCTYPE + +/* Define to 1 if platform lacks itow(). */ +#undef ACE_LACKS_ITOW + +/* Define to 1 if the system lacks the type `key_t'. */ +#undef ACE_LACKS_KEY_T + +/* Define to 1 if platform lacks kill(). */ +#undef ACE_LACKS_KILL + +/* Platform lacks streambuf "linebuffered ()". */ +#undef ACE_LACKS_LINEBUFFERED_STREAMBUF + +/* Platform/compiler lacks the llseek() prototype. This should not be defined + if ACE_LACKS_LSEEK64_PROTOTYPE is defined. */ +#undef ACE_LACKS_LLSEEK_PROTOTYPE + +/* Define to 1 if platform lacks localtime(). */ +#undef ACE_LACKS_LOCALTIME + +/* Define to 1 if platform lacks log2(). */ +#undef ACE_LACKS_LOG2 + +/* Compiler/platform does not support the unsigned long long datatype. */ +#undef ACE_LACKS_LONGLONG_T + +/* Platform/compiler lacks the lseek64() prototype. This should not be defined + if ACE_LACKS_LLSEEK_PROTOTYPE is defined. */ +#undef ACE_LACKS_LSEEK64_PROTOTYPE + +/* Define to 1 if platform lacks lstat(). */ +#undef ACE_LACKS_LSTAT + +/* Define to 1 if platform lacks madvise(). */ +#undef ACE_LACKS_MADVISE + +/* Define to 1 if platform lacks the declaration of madvise(). */ +#undef ACE_LACKS_MADVISE_PROTOTYPE + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_MALLOC_H + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_MEMORY_H + +/* Define to 1 if platform lacks mkfifo(). */ +#undef ACE_LACKS_MKFIFO + +/* Define to 1 if platform lacks mkstemp(). */ +#undef ACE_LACKS_MKSTEMP + +/* Define to 1 if platform lacks the declaration of mkstemp(). */ +#undef ACE_LACKS_MKSTEMP_PROTOTYPE + +/* Define to 1 if platform lacks mktemp(). */ +#undef ACE_LACKS_MKTEMP + +/* Define to 1 if platform lacks the declaration of mktemp(). */ +#undef ACE_LACKS_MKTEMP_PROTOTYPE + +/* The platform doesn't have mmap(2) (e.g., SCO UNIX). */ +#undef ACE_LACKS_MMAP + +/* Platform/compiler doesn't have open() mode masks. */ +#undef ACE_LACKS_MODE_MASKS + +/* Platform does not have Motif X toolkit available */ +#undef ACE_LACKS_MOTIF + +/* Define to 1 if platform lacks mprotect(). */ +#undef ACE_LACKS_MPROTECT + +/* Platform defines ACE_HAS_MSG, but lacks msg_accrights{len}. */ +#undef ACE_LACKS_MSG_ACCRIGHTS + +/* Define to 1 if platform lacks msync(). */ +#undef ACE_LACKS_MSYNC + +/* Define to 1 if system lacks pthread_mutexattr_setpshared(). */ +#undef ACE_LACKS_MUTEXATTR_PSHARED + +/* Platform lacks named POSIX semaphores (e.g., Chorus) */ +#undef ACE_LACKS_NAMED_POSIX_SEM + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_NETDB_H + +/* Platform does not support reentrant netdb functions (getprotobyname_r, + getprotobynumber_r, gethostbyaddr_r, gethostbyname_r, getservbyname_r). */ +#undef ACE_LACKS_NETDB_REENTRANT_FUNCTIONS + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_NETINET_IN_H + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_NETINET_TCP_H + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_NET_IF_H + +/* OS requires non-null status pointer for pthread_join () */ +#undef ACE_LACKS_NULL_PTHREAD_STATUS + +/* Platform lacks std::numeric_limits<> */ +#undef ACE_LACKS_NUMERIC_LIMITS + +/* Define to 1 if platform lacks IGMPv3 "perfect" filtering of multicast + datagrams at the socket level. If defined, ACE_SOCK_Dgram_Mcast will bind + the first joined multicast group to the socket, and all future joins on + that socket will fail with an error. */ +#undef ACE_LACKS_PERFECT_MULTICAST_FILTERING + +/* Define to 1 if platform lacks pipe(). */ +#undef ACE_LACKS_PIPE + +/* Compiler doesn't support placement operator delete(void *, void *). */ +#undef ACE_LACKS_PLACEMENT_OPERATOR_DELETE + +/* Compiler complains about use of obsolete "pragma once" */ +#undef ACE_LACKS_PRAGMA_ONCE + +/* Platform/compiler lacks the pread() and pwrite() prototypes */ +#undef ACE_LACKS_PREAD_PROTOTYPE + +/* Define to 1 if the system lacks the type 'pri_t'. */ +#undef ACE_LACKS_PRI_T + +/* Define to 1 if platform lacks pthread_attr_setstack() */ +#undef ACE_LACKS_PTHREAD_ATTR_SETSTACK + +/* Define to 1 if platform lacks pthread_attr_setstackaddr(). */ +#undef ACE_LACKS_PTHREAD_ATTR_SETSTACKADDR + +/* Define to 1 if platform lacks pthread_attr_setstacksize(). */ +#undef ACE_LACKS_PTHREAD_ATTR_SETSTACKSIZE + +/* Platform lacks pthread_cancel() */ +#undef ACE_LACKS_PTHREAD_CANCEL + +/* Define to 1 if platform lacks pthread_sigmask(). */ +#undef ACE_LACKS_PTHREAD_SIGMASK + +/* Define to 1 if platform lacks pthread_thr_sigsetmask(). */ +#undef ACE_LACKS_PTHREAD_THR_SIGSETMASK + +/* Define to 1 if platform lacks pthread_yield(). */ +#undef ACE_LACKS_PTHREAD_YIELD + +/* Platform lacks, getpwnam(), etc. */ +#undef ACE_LACKS_PWD_FUNCTIONS + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_PWD_H + +/* Platform lacks getpwnam_r() methods (e.g., SGI 6.2). */ +#undef ACE_LACKS_PWD_REENTRANT_FUNCTIONS + +/* Define to 1 if platform lacks qsort(). */ +#undef ACE_LACKS_QSORT + +/* Define to 1 if platform lacks readdir_r(). */ +#undef ACE_LACKS_READDIR_R + +/* Define to 1 if platform lacks readlink(). */ +#undef ACE_LACKS_READLINK + +/* Define to 1 if platform lacks readv(). */ +#undef ACE_LACKS_READV + +/* Define to 1 if platform lacks realpath(). */ +#undef ACE_LACKS_REALPATH + +/* Define to 1 if platform lacks recvmsg(). */ +#undef ACE_LACKS_RECVMSG + +/* Define to 1 if platform lacks rename(). */ +#undef ACE_LACKS_RENAME + +/* Platform/compiler lacks {get,set}rlimit() function (e.g., VxWorks, Chorus, + and SCO UNIX) */ +#undef ACE_LACKS_RLIMIT + +/* Define to 1 if platform lacks the declaration of {get,set}rlimit(). */ +#undef ACE_LACKS_RLIMIT_PROTOTYPE + +/* Define to 1 if system lacks pthread_rwlockattr_setpshared(). */ +#undef ACE_LACKS_RWLOCKATTR_PSHARED + +/* Define to 1 if the system lacks the type `rwlock_t'. */ +#undef ACE_LACKS_RWLOCK_T + +/* Define to 1 if platform lacks sbrk(). */ +#undef ACE_LACKS_SBRK + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_SCHED_H + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_SEARCH_H + +/* Define to 1 if platform lacks seekdir(). */ +#undef ACE_LACKS_SEEKDIR + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_SEMAPHORE_H + +/* Define to 1 if the system lacks the type `struct sembuf'. */ +#undef ACE_LACKS_SEMBUF_T + +/* Define to 1 if platform lacks sendmsg(). */ +#undef ACE_LACKS_SENDMSG + +/* Platform lacks pthread_attr_setdetachstate() (e.g., HP/UX 10.x) */ +#undef ACE_LACKS_SETDETACH + +/* Define to 1 if platform lacks setegid(). */ +#undef ACE_LACKS_SETEGID + +/* Define to 1 if platform lacks setenv(). */ +#undef ACE_LACKS_SETENV + +/* Define to 1 if platform lacks seteuid(). */ +#undef ACE_LACKS_SETEUID + +/* Define to 1 if platform lacks setgid(). */ +#undef ACE_LACKS_SETGID + +/* Define to 1 if platform lacks setpgid(). */ +#undef ACE_LACKS_SETPGID + +/* Define to 1 if platform lacks setpgid() declaration in . */ +#undef ACE_LACKS_SETPGID_PROTOTYPE + +/* Define to 1 if platform lacks setregid(). */ +#undef ACE_LACKS_SETREGID + +/* Define to 1 if platform lacks setregid() declaration in . */ +#undef ACE_LACKS_SETREGID_PROTOTYPE + +/* Define to 1 if platform lacks setreuid(). */ +#undef ACE_LACKS_SETREUID + +/* Define to 1 if platform lacks setreuid() declaration in . */ +#undef ACE_LACKS_SETREUID_PROTOTYPE + +/* Platform lacks pthread_attr_setsched() (e.g. MVS) */ +#undef ACE_LACKS_SETSCHED + +/* Define to 1 if platform lacks setsid(). */ +#undef ACE_LACKS_SETSID + +/* Define to 1 if platform lacks setuid(). */ +#undef ACE_LACKS_SETUID + +/* Define to 1 if platform lacks sigaction(). */ +#undef ACE_LACKS_SIGACTION + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_SIGINFO_H + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_SIGNAL_H + +/* Platform lacks "signed char" type (broken!) */ +#undef ACE_LACKS_SIGNED_CHAR + +/* Define to 1 if the system lacks the type `sigset_t'. */ +#undef ACE_LACKS_SIGSET + +/* Define to 1 if `si_addr' is not a member of `siginfo_t'. */ +#undef ACE_LACKS_SI_ADDR + +/* Define to 1 if platform lacks socketpair(). */ +#undef ACE_LACKS_SOCKETPAIR + +/* Platform doesn't support SO_SNDBUF/SO_RCVBUF (used in TAO) */ +#undef ACE_LACKS_SOCKET_BUFSIZ + +/* Compiler doesn't support static data member templates */ +#undef ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_STDINT_H + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_STDLIB_H + +/* Define to 1 if platform lacks strcasecmp(). */ +#undef ACE_LACKS_STRCASECMP + +/* Define to 1 if platform lacks a declaration for strcasecmp() */ +#undef ACE_LACKS_STRCASECMP_PROTOTYPE + +/* Define to 1 if platform lacks strchr(). */ +#undef ACE_LACKS_STRCHR + +/* Define to 1 if platform lacks strdup(). */ +#undef ACE_LACKS_STRDUP + +/* Define to 1 if platform lacks strerror(). */ +#undef ACE_LACKS_STRERROR + +/* Define to 1 if platform lacks strftime(). */ +#undef ACE_LACKS_STRFTIME + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_STRINGS_H + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_STRING_H + +/* Define to 1 if platform lacks strncasecmp(). */ +#undef ACE_LACKS_STRNCASECMP + +/* Define to 1 if platform lacks a declaration for strncasecmp() */ +#undef ACE_LACKS_STRNCASECMP_PROTOTYPE + +/* Define to 1 if platform lacks the declaration of strnlen(). */ +#undef ACE_LACKS_STRNLEN_PROTOTYPE + +/* Platform lacks stropts.h */ +#undef ACE_LACKS_STROPTS_H + +/* Define to 1 if platform lacks strpbrk(). */ +#undef ACE_LACKS_STRPBRK + +/* Define to 1 if platform lacks strptime(). */ +#undef ACE_LACKS_STRPTIME + +/* Define to 1 if platform lacks the declaration of strptime(). */ +#undef ACE_LACKS_STRPTIME_PROTOTYPE + +/* Define to 1 if platform lacks strrchr(). */ +#undef ACE_LACKS_STRRCHR + +/* Define to 1 if the system lacks the type `struct strrecvfd'. */ +#undef ACE_LACKS_STRRECVFD + +/* Define to 1 if platform lacks strspn(). */ +#undef ACE_LACKS_STRSPN + +/* Define to 1 if platform lacks strtod(). */ +#undef ACE_LACKS_STRTOD + +/* Platform/compiler lacks the strtok_r() prototype */ +#undef ACE_LACKS_STRTOK_R_PROTOTYPE + +/* Define to 1 if platform lacks strtol(). */ +#undef ACE_LACKS_STRTOL + +/* Define to 1 if platform lacks strtoll(). */ +#undef ACE_LACKS_STRTOLL + +/* Define to 1 if platform lacks a declaration for strtoll() */ +#undef ACE_LACKS_STRTOLL_PROTOTYPE + +/* Define to 1 if platform lacks strtoul(). */ +#undef ACE_LACKS_STRTOUL + +/* Define to 1 if platform lacks strtoull(). */ +#undef ACE_LACKS_STRTOULL + +/* Define to 1 if platform lacks a declaration for strtoull() */ +#undef ACE_LACKS_STRTOULL_PROTOTYPE + +/* Define to 1 if the system lacks the type `struct dirent'. */ +#undef ACE_LACKS_STRUCT_DIR + +/* Define to 1 if the system lacks the type 'suseconds_t'. */ +#undef ACE_LACKS_SUSECONDS_T + +/* Define to 1 if platform lacks swab(). */ +#undef ACE_LACKS_SWAB + +/* Define to 1 if platform lacks syscall(). */ +#undef ACE_LACKS_SYSCALL + +/* Define to 1 if platform lacks sysconf(). */ +#undef ACE_LACKS_SYSCONF + +/* Define to 1 if platform lacks system(). */ +#undef ACE_LACKS_SYSTEM + +/* Platform lacks SYSV message queue prototypes */ +#undef ACE_LACKS_SYSV_MSQ_PROTOS + +/* Platform lacks System V shared memory (e.g., Win32 and VxWorks) */ +#undef ACE_LACKS_SYSV_SHMEM + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_SYS_IOCTL_H + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_SYS_IPC_H + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_SYS_MMAN_H + +/* Platform lacks sys/msg.h (e.g., Chorus and VxWorks) */ +#undef ACE_LACKS_SYS_MSG_H + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_SYS_PARAM_H + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_SYS_RESOURCE_H + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_SYS_SELECT_H + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_SYS_SEM_H + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_SYS_SHM_H + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_SYS_SOCKET_H + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_SYS_STAT_H + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_SYS_SYSCTL_H + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_SYS_TIME_H + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_SYS_TYPES_H + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_SYS_UIO_H + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_SYS_UN_H + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_SYS_WAIT_H + +/* OS does not support TCP_NODELAY */ +#undef ACE_LACKS_TCP_NODELAY + +/* Define to 1 if platform lacks telldir(). */ +#undef ACE_LACKS_TELLDIR + +/* Define to 1 if platform lacks tempnam(). */ +#undef ACE_LACKS_TEMPNAM + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_TERMIOS_H + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_TERMIO_H + +/* Platform lacks pthread_attr_setscope() */ +#undef ACE_LACKS_THREAD_PROCESS_SCOPING + +/* Define to 1 if platform lacks the declarations of recv_timedwait, + send_timedwait, etc. */ +#undef ACE_LACKS_TIMEDWAIT_PROTOTYPES + +/* Platform does not define timepec_t as a typedef for struct timespec. */ +#undef ACE_LACKS_TIMESPEC_T + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_TIME_H + +/* Define to 1 if platform lacks towlower(). */ +#undef ACE_LACKS_TOWLOWER + +/* Define to 1 if platform lacks towupper(). */ +#undef ACE_LACKS_TOWUPPER + +/* Define to 1 if platform lacks truncate(). */ +#undef ACE_LACKS_TRUNCATE + +/* Header files lack t_errno for TLI */ +#undef ACE_LACKS_T_ERRNO + +/* Define to 1 if platform lacks the declaration of ualarm(). */ +#undef ACE_LACKS_UALARM_PROTOTYPE + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_UCONTEXT_H + +/* Define to 1 if the system lacks the type `uintmax_t'. */ +#undef ACE_LACKS_UINTMAX_T + +/* Define to 1 if the system lacks the type `uintptr_t'. */ +#undef ACE_LACKS_UINTPTR_T + +/* Define to 1 if platform lacks umask(). */ +#undef ACE_LACKS_UMASK + +/* Define to 1 if platform lacks uname(). */ +#undef ACE_LACKS_UNAME + +/* */ +#undef ACE_LACKS_UNBUFFERED_STREAMBUF + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_UNISTD_H + +/* ACE platform has no UNIX domain sockets */ +#undef ACE_LACKS_UNIX_DOMAIN_SOCKETS + +/* Platform lacks full signal support (e.g., Win32 and Chorus). */ +#undef ACE_LACKS_UNIX_SIGNALS + +/* Define to 1 if platform lacks unlink(). */ +#undef ACE_LACKS_UNLINK + +/* Define to 1 if platform lacks unsetenv(). */ +#undef ACE_LACKS_UNSETENV + +/* Define to 1 if the system lacks the type 'useconds_t'. */ +#undef ACE_LACKS_USECONDS_T + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_UTIME_H + +/* Define to 1 if the system lacks the type `struct utsname'. */ +#undef ACE_LACKS_UTSNAME_T + +/* Define to 1 if the system lacks the type `u_long_long_t'. */ +#undef ACE_LACKS_U_LONGLONG_T + +/* Define to 1 if platform lacks vsnprintf(). */ +#undef ACE_LACKS_VSNPRINTF + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_WCHAR_H + +/* Define to 1 if the system lacks the type `wchar_t'. */ +#undef ACE_LACKS_WCHAR_T + +/* Define to 1 if platform lacks wcscasecmp(). */ +#undef ACE_LACKS_WCSCASECMP + +/* Define to 1 if platform lacks wcscat(). */ +#undef ACE_LACKS_WCSCAT + +/* Define to 1 if platform lacks wcschr(). */ +#undef ACE_LACKS_WCSCHR + +/* Define to 1 if platform lacks wcscmp(). */ +#undef ACE_LACKS_WCSCMP + +/* Define to 1 if platform lacks wcscpy(). */ +#undef ACE_LACKS_WCSCPY + +/* Define to 1 if platform lacks wcscspn(). */ +#undef ACE_LACKS_WCSCSPN + +/* Define to 1 if platform lacks wcsdup(). */ +#undef ACE_LACKS_WCSDUP + +/* Define to 1 if platform lacks wcslen(). */ +#undef ACE_LACKS_WCSLEN + +/* Define to 1 if platform lacks wcsncasecmp(). */ +#undef ACE_LACKS_WCSNCASECMP + +/* Define to 1 if platform lacks wcsncat(). */ +#undef ACE_LACKS_WCSNCAT + +/* Define to 1 if platform lacks wcsncmp(). */ +#undef ACE_LACKS_WCSNCMP + +/* Define to 1 if platform lacks wcsncpy(). */ +#undef ACE_LACKS_WCSNCPY + +/* Define to 1 if platform lacks wcsnicmp(). */ +#undef ACE_LACKS_WCSNICMP + +/* Define to 1 if platform lacks wcspbrk(). */ +#undef ACE_LACKS_WCSPBRK + +/* Define to 1 if platform lacks wcsrchr(). */ +#undef ACE_LACKS_WCSRCHR + +/* Define to 1 if platform lacks wcsspn(). */ +#undef ACE_LACKS_WCSSPN + +/* Define to 1 if platform lacks wcsstr(). */ +#undef ACE_LACKS_WCSSTR + +/* Define to 1 if platform lacks wcstod(). */ +#undef ACE_LACKS_WCSTOD + +/* Define to 1 if platform lacks wcstok(). */ +#undef ACE_LACKS_WCSTOK + +/* Define to 1 if platform lacks wcstol(). */ +#undef ACE_LACKS_WCSTOL + +/* Define to 1 if platform lacks wcstoll(). */ +#undef ACE_LACKS_WCSTOLL + +/* Define to 1 if platform lacks a declaration for wcstoll() */ +#undef ACE_LACKS_WCSTOLL_PROTOTYPE + +/* Define to 1 if platform lacks wcstoul(). */ +#undef ACE_LACKS_WCSTOUL + +/* Define to 1 if platform lacks wcstoull(). */ +#undef ACE_LACKS_WCSTOULL + +/* Define to 1 if platform lacks a declaration for wcstoull() */ +#undef ACE_LACKS_WCSTOULL_PROTOTYPE + +/* Define to 1 if platform lacks the header file. */ +#undef ACE_LACKS_WCTYPE_H + +/* Define to 1 if platform lacks writev(). */ +#undef ACE_LACKS_WRITEV + +/* Define to environment variable used for DLL search path */ +#undef ACE_LD_SEARCH_PATH + +/* typedef for ACE_LOFF_T */ +#undef ACE_LOFF_T_TYPEDEF + +/* Renames "main (int, char *[])", for platforms such as g++/VxWorks that + don't allow main. Requires the use of ACE_HAS_NONSTATIC_OBJECT_MANAGER. */ +#undef ACE_MAIN + +/* */ +#undef ACE_MALLOC_ALIGN + +/* */ +#undef ACE_MAP_PRIVATE + +/* Define to 1 if platform has 1 parameter mkdir() */ +#undef ACE_MKDIR_LACKS_MODE + +/* Compile using multi-thread libraries */ +#undef ACE_MT_SAFE + +/* Turns off debugging features */ +#undef ACE_NDEBUG + +/* Necessary with some compilers to pass ACE_TTY_IO as parameter to + DEV_Connector. */ +#undef ACE_NEEDS_DEV_IO_CONVERSION + +/* Compiler requires a definition for a "hidden" function, e.g., a private, + unimplemented copy constructor or assignment operator. The SGI C++ compiler + needs this, in template classes, with + ACE_HAS_TEMPLATE_INSTANTIATION_PRAGMA. */ +#undef ACE_NEEDS_FUNC_DEFINITIONS + +/* Required by platforms with small default stacks. */ +#undef ACE_NEEDS_HUGE_THREAD_STACKSIZE + +/* OS has LWPs, and when the priority of a bound thread is set, then the LWP + priority must be set also. */ +#undef ACE_NEEDS_LWP_PRIO_SET + +/* Platform needs to #include to get thread scheduling defs. */ +#undef ACE_NEEDS_SCHED_H + +/* Compiler's 'new' throws exception on failure (ANSI C++ behavior). */ +#undef ACE_NEW_THROWS_EXCEPTIONS + +/* Turns off the LM_DEBUG and LM_ERROR logging macros... */ +#undef ACE_NLOGGING + +/* Explicitly disable ACE inlining */ +#undef ACE_NO_INLINE + +/* Turns off the tracing feature. */ +#undef ACE_NTRACE + +/* Defines the page size of the system (not used on Win32 or with + ACE_HAS_GETPAGESIZE). */ +#undef ACE_PAGE_SIZE + +/* Flag that denotes the symbol should be exported from the DSO/DLL. */ +#undef ACE_Proper_Export_Flag + +/* Flag that denotes the symbol should be imported from the DSO/DLL. */ +#undef ACE_Proper_Import_Flag + +/* Platform redefines the t_... names (UnixWare) */ +#undef ACE_REDEFINES_XTI_FUNCTIONS + +/* shm_open() requires a leading slash in name */ +#undef ACE_SHM_OPEN_REQUIRES_ONE_SLASH + +/* Size of the native "double" type */ +#undef ACE_SIZEOF_DOUBLE + +/* Size of the native "float" type */ +#undef ACE_SIZEOF_FLOAT + +/* Size of the native "int" type */ +#undef ACE_SIZEOF_INT + +/* Size of the native "long" type */ +#undef ACE_SIZEOF_LONG + +/* Size of the native "long double" type */ +#undef ACE_SIZEOF_LONG_DOUBLE + +/* Size of the native "long long" type */ +#undef ACE_SIZEOF_LONG_LONG + +/* Size of the native "short" type */ +#undef ACE_SIZEOF_SHORT + +/* Size of the native "pointer to void" type */ +#undef ACE_SIZEOF_VOID_P + +/* Size of the native "wchar_t" type */ +#undef ACE_SIZEOF_WCHAR + +/* Define to the *printf format specifier (e.g. "%u") for size_t */ +#undef ACE_SIZE_T_FORMAT_SPECIFIER + +/* Define to the *printf format specifier (e.g. "%d") for ssize_t */ +#undef ACE_SSIZE_T_FORMAT_SPECIFIER + +/* Define to function that is equivalent to strcasecmp() */ +#undef ACE_STRCASECMP_EQUIVALENT + +/* Define to function that is equivalent to strdup() */ +#undef ACE_STRDUP_EQUIVALENT + +/* Define to function that is equivalent to strncasecmp() */ +#undef ACE_STRNCASECMP_EQUIVALENT + +/* Define to function that is equivalent to strtoll() */ +#undef ACE_STRTOLL_EQUIVALENT + +/* Define to function that is equivalent to strtoull() */ +#undef ACE_STRTOULL_EQUIVALENT + +/* Compiler's template mechanism must use a pragma. This is used for AIX's C++ + compiler. */ +#undef ACE_TEMPLATES_REQUIRE_PRAGMA + +/* Compiler's template mechanim must see source code (i.e., .cpp files). This + is used for GNU G++. */ +#undef ACE_TEMPLATES_REQUIRE_SOURCE + +/* Specify this if you don't want threads to inherit parent thread's + ACE_Log_Msg properties. */ +#undef ACE_THREADS_DONT_INHERIT_LOG_MSG + +/* */ +#undef ACE_THR_PRI_FIFO_DEF + +/* */ +#undef ACE_TIMER_SKEW + +/* Device the platform uses for TCP on TLI. Only needed if not /dev/tcp. */ +#undef ACE_TLI_TCP_DEVICE + +/* Define to the *printf format specifier (e.g. "%llu") for ACE_UINT64 */ +#undef ACE_UINT64_FORMAT_SPECIFIER + +/* Define to unsigned 64 bit integer type */ +#undef ACE_UINT64_TYPE + +/* Platform uses assembly symbols instead of C symbols in dlsym() */ +#undef ACE_USES_ASM_SYMBOL_IN_DLSYM + +/* Enable IPv6 support on platforms that don't have IPv6 turned on by default + */ +#undef ACE_USES_IPV4_IPV6_MIGRATION + +/* Some files, such as ace/streams.h, want to include new style C++ stream + headers. These headers are iomanip, ios, iostream, istream, ostream, + fstream and streambuf. If _all_ of these headers aren't available, then + assume that only iostream.h and fstream.h are available. */ +#undef ACE_USES_OLD_IOSTREAMS + +/* When linking MFC as a static library is desired */ +#undef ACE_USES_STATIC_MFC + +/* Platform has its standard C++ library in the namespace std. */ +#undef ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB + +/* ACE is built to use wide characters internally */ +#undef ACE_USES_WCHAR + +/* The OS/platform supports the poll() event demultiplexor */ +#undef ACE_USE_POLL + +/* Define to 1 to embed RCS ID strings into compiled object files. */ +#undef ACE_USE_RCSID + +/* For Win32: Use Select_Reactor as default implementation of Reactor instead + of WFMO_Reactor. */ +#undef ACE_USE_SELECT_REACTOR_FOR_REACTOR_IMPL + +/* Define to function that is equivalent to wcscasecmp() */ +#undef ACE_WCSCASECMP_EQUIVALENT + +/* Define to function that is equivalent to wcsdup() */ +#undef ACE_WCSDUP_EQUIVALENT + +/* Define to function that is equivalent to wcsncasecmp() */ +#undef ACE_WCSNCASECMP_EQUIVALENT + +/* Define to function that is equivalent to wcstoll() */ +#undef ACE_WCSTOLL_EQUIVALENT + +/* Define to function that is equivalent to wcstoull() */ +#undef ACE_WCSTOULL_EQUIVALENT + +/* Configure for use on Win32 */ +#undef ACE_WIN32 + +/* A parameter list indicating the version of WinSock (e.g., "1, 1" is version + 1.1). */ +#undef ACE_WSOCK_VERSION + +/* Define if building universal (internal helper macro) */ +#undef AC_APPLE_UNIVERSAL_BUILD + +/* Configure for use on AIX */ +#undef AIX + +/* Define to 1 if the `closedir' function returns void instead of `int'. */ +#undef CLOSEDIR_VOID + +/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP + systems. This function is required for `alloca.c' support on those systems. + */ +#undef CRAY_STACKSEG_END + +/* GNU Win32 environement */ +#undef CYGWIN32 + +/* Define to 1 if using `alloca.c'. */ +#undef C_ALLOCA + +/* */ +#undef DEC_CXX + +/* Configure for use on Digital Unix */ +#undef DIGITAL_UNIX + +/* Define to 1 if you have `alloca', as a function or macro. */ +#undef HAVE_ALLOCA + +/* Define to 1 if you have and it should be used (not on Ultrix). + */ +#undef HAVE_ALLOCA_H + +/* Define to 1 if you have the header file, and it defines `DIR'. + */ +#undef HAVE_DIRENT_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_DLFCN_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_FSTREAM + +/* Define to 1 if you have the header file. */ +#undef HAVE_FSTREAM_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_INTTYPES_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_IOMANIP + +/* Define to 1 if you have the header file. */ +#undef HAVE_IOS + +/* Define to 1 if you have the header file. */ +#undef HAVE_IOSTREAM + +/* Define to 1 if you have the header file. */ +#undef HAVE_IOSTREAM_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_ISTREAM + +/* Define to 1 if you have the `dld' library (-ldld). */ +#undef HAVE_LIBDLD + +/* Define to 1 if you have the header file. */ +#undef HAVE_MEMORY_H + +/* Define to 1 if you have the header file, and it defines `DIR'. */ +#undef HAVE_NDIR_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_OSTREAM + +/* Define to 1 if you have the header file. */ +#undef HAVE_STDINT_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STDLIB_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STREAMBUF + +/* Define to 1 if you have the `strftime' function. */ +#undef HAVE_STRFTIME + +/* Define to 1 if you have the header file. */ +#undef HAVE_STRINGS_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STRING_H + +/* Define to 1 if you have the header file, and it defines `DIR'. + */ +#undef HAVE_SYS_DIR_H + +/* Define to 1 if you have the header file, and it defines `DIR'. + */ +#undef HAVE_SYS_NDIR_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_STAT_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_TYPES_H + +/* Define to 1 if you have that is POSIX.1 compatible. */ +#undef HAVE_SYS_WAIT_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_UNISTD_H + +/* Configure for use on HP-UX */ +#undef HPUX + +/* Configure for use on HP-UX 10 */ +#undef HPUX_10 + +/* Configure for use on HP-UX 11 */ +#undef HPUX_11 + +/* */ +#undef IP_ADD_MEMBERSHIP + +/* */ +#undef IP_DROP_MEMBERSHIP + +/* Configure for use on Irix 5 */ +#undef IRIX5 + +/* Configure for use on Irix 6 */ +#undef IRIX6 + +/* Define to the sub-directory in which libtool stores uninstalled libraries. + */ +#undef LT_OBJDIR + +/* Define to the address where bug reports for this package should be sent. */ +#undef PACKAGE_BUGREPORT + +/* Define to the full name of this package. */ +#undef PACKAGE_NAME + +/* Define to the full name and version of this package. */ +#undef PACKAGE_STRING + +/* Define to the one symbol short name of this package. */ +#undef PACKAGE_TARNAME + +/* Define to the version of this package. */ +#undef PACKAGE_VERSION + +/* Maximum thread priority */ +#undef PTHREAD_MAX_PRIORITY + +/* Minimum thread priority */ +#undef PTHREAD_MIN_PRIORITY + +/* */ +#undef PTHREAD_STACK_MIN + +/* */ +#undef SCO + +/* The size of `double', as computed by sizeof. */ +#undef SIZEOF_DOUBLE + +/* The size of `float', as computed by sizeof. */ +#undef SIZEOF_FLOAT + +/* The size of `int', as computed by sizeof. */ +#undef SIZEOF_INT + +/* The size of `long', as computed by sizeof. */ +#undef SIZEOF_LONG + +/* The size of `long double', as computed by sizeof. */ +#undef SIZEOF_LONG_DOUBLE + +/* The size of `long long', as computed by sizeof. */ +#undef SIZEOF_LONG_LONG + +/* The size of `short', as computed by sizeof. */ +#undef SIZEOF_SHORT + +/* The size of `signed char', as computed by sizeof. */ +#undef SIZEOF_SIGNED_CHAR + +/* The size of `void *', as computed by sizeof. */ +#undef SIZEOF_VOID_P + +/* The size of `wchar_t', as computed by sizeof. */ +#undef SIZEOF_WCHAR_T + +/* If using the C implementation of alloca, define if you know the + direction of stack growth for your system; otherwise it will be + automatically deduced at runtime. + STACK_DIRECTION > 0 => grows toward higher addresses + STACK_DIRECTION < 0 => grows toward lower addresses + STACK_DIRECTION = 0 => direction of growth unknown */ +#undef STACK_DIRECTION + +/* Define to 1 if you have the ANSI C header files. */ +#undef STDC_HEADERS + +/* Configure for use on UnixWare */ +#undef UNIXWARE + +/* */ +#undef UNIXWARE_2_0 + +/* */ +#undef UNIXWARE_2_1 + +/* */ +#undef UNIXWARE_7_1 + +/* Configure for use on VxWorks */ +#undef VXWORKS + +/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most + significant byte first (like Motorola and SPARC, unlike Intel). */ +#if defined AC_APPLE_UNIVERSAL_BUILD +# if defined __BIG_ENDIAN__ +# define WORDS_BIGENDIAN 1 +# endif +#else +# ifndef WORDS_BIGENDIAN +# undef WORDS_BIGENDIAN +# endif +#endif + +/* Define to 1 if the X Window System is missing or not being used. */ +#undef X_DISPLAY_MISSING + +/* Define to 1 if `lex' declares `yytext' as a `char *' by default, not a + `char[]'. */ +#undef YYTEXT_POINTER + +/* Enable ACE inlining */ +#undef __ACE_INLINE__ + +/* */ +#undef __IOCTL_VERSIONED__ + +/* */ +#undef __NO_INCLUDE_WARN__ + + + + +#endif /* ACE_CONFIG_H */ + + +// Local Variables: +// mode:C++ +// End: + + diff --git a/dep/acelite/ace/gethrtime.cpp b/dep/acelite/ace/gethrtime.cpp new file mode 100644 index 00000000000..69de03153a1 --- /dev/null +++ b/dep/acelite/ace/gethrtime.cpp @@ -0,0 +1,60 @@ +// $Id: gethrtime.cpp 80826 2008-03-04 14:51:23Z wotte $ +// +// Build this file with g++. It can be linked in to a ACE application +// that was compiled with GreenHills. It wouldn't be necessary if I +// knew a way to correctly move values from registers to a 64-bit +// variable in GHS asm code. That's easy with g++ asm. + +#include "ace/config-all.h" + +ACE_RCSID(ace, gethrtime, "$Id: gethrtime.cpp 80826 2008-03-04 14:51:23Z wotte $") + +#if defined (ghs) && (defined (i386) || defined(__i386__)) + +#include "ace/OS_NS_time.h" + +extern "C" +ACE_hrtime_t +ACE_GETHRTIME_NAME (void) +{ +#if defined (ACE_HAS_PENTIUM) + // ACE_TRACE ("ACE_GETHRTIME_NAME"); + +#if defined (ACE_LACKS_LONGLONG_T) + double now; +#else /* ! ACE_LACKS_LONGLONG_T */ + ACE_hrtime_t now; +#endif /* ! ACE_LACKS_LONGLONG_T */ + + // Read the high-res tick counter directly into memory variable + // "now". The A constraint signifies a 64-bit int. +#if defined (__GNUG__) + asm volatile ("rdtsc" : "=A" (now) : : "memory"); +// #elif defined (ghs) +// The following doesn't work. For now, this file must be compile with g++. +// asm ("rdtsc"); +// asm ("movl %edx,-16(%ebp)"); +// asm ("movl %eax,-12(%ebp)"); +#else +# error unsupported compiler +#endif + +#if defined (ACE_LACKS_LONGLONG_T) + // ACE_U_LongLong doesn't have the same layout as now, so construct + // it "properly". + ACE_UINT32 least, most; + ACE_OS::memcpy (&least, &now, sizeof (ACE_UINT32)); + ACE_OS::memcpy (&most, (unsigned char *) &now + sizeof (ACE_UINT32), + sizeof (ACE_UINT32)); + + const ACE_hrtime_t ret (least, most); + return ret; +#else /* ! ACE_LACKS_LONGLONG_T */ + return now; +#endif /* ! ACE_LACKS_LONGLONG_T */ + +#else /* ! ACE_HAS_PENTIUM */ +# error This file can _only_ be compiled with ACE_HAS_PENTIUM. +#endif /* ! ACE_HAS_PENTIUM */ +} +#endif /* ghs */ diff --git a/dep/acelite/ace/iosfwd.h b/dep/acelite/ace/iosfwd.h new file mode 100644 index 00000000000..b9576ebae97 --- /dev/null +++ b/dep/acelite/ace/iosfwd.h @@ -0,0 +1,100 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file iosfwd.h + * + * $Id: iosfwd.h 89098 2010-02-21 21:51:41Z schmidt $ + * + * @author Irfan Pyarali + * + * This file contains the portability ugliness for the Standard C++ + * Library. As implementations of the "standard" emerge, this file + * will need to be updated. + * + * This files deals with forward declaration for the stream + * classes. Remember that since the new Standard C++ Library code + * for streams uses templates, simple forward declaration will not + * work. + */ +//============================================================================= + + +#ifndef ACE_IOSFWD_H +#define ACE_IOSFWD_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_IOSTREAM_TOTALLY) + +#if defined (__APPLE_CC__) +// Should this really be here? dhinton +// FUZZ: disable check_for_streams_include +# include "ace/streams.h" +#endif + +#if defined (ACE_HAS_STANDARD_CPP_LIBRARY) && \ + (ACE_HAS_STANDARD_CPP_LIBRARY != 0) + +# if !defined (ACE_USES_OLD_IOSTREAMS) +# include /**/ +#define ACE_HAS_CPP98_IOSTREAMS 1 +# else + // @note If these forward declarations don't work (e.g. aren't + // portable), we may have to include "ace/streams.h" as a last + // resort. Doing so would defeat the purpose of this header, + // unfortunately. + class ios; + class streambuf; + class istream; + class ostream; + class iostream; + class filebuf; + class ifstream; + class ofstream; + class fstream; +# endif /* ! ACE_USES_OLD_IOSTREAMS */ + +# if defined (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB) && \ + (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB != 0) + +# if !defined (ACE_USES_OLD_IOSTREAMS) + // Make these available in the global name space + using std::ios; + using std::streambuf; + using std::istream; + using std::ostream; + using std::iostream; + using std::filebuf; + using std::ifstream; + using std::ofstream; + using std::fstream; +# endif /* ! ACE_USES_OLD_IOSTREAMS */ + +# endif /* ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB */ + +#else /* ! ACE_HAS_STANDARD_CPP_LIBRARY */ + + class ios; + class streambuf; + class istream; + class ostream; + class iostream; + class filebuf; + class ifstream; + class ofstream; + class fstream; + +# endif /* ! ACE_HAS_STANDARD_CPP_LIBRARY */ + +#include /**/ "ace/post.h" + +#endif /* ACE_LACKS_IOSTREAM_TOTALLY */ + +#endif /* ACE_IOSFWD_H */ diff --git a/dep/acelite/ace/os_include/arpa/os_inet.h b/dep/acelite/ace/os_include/arpa/os_inet.h new file mode 100644 index 00000000000..b97f7c6e419 --- /dev/null +++ b/dep/acelite/ace/os_include/arpa/os_inet.h @@ -0,0 +1,74 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_inet.h + * + * definitions for internet operations + * + * $Id: os_inet.h 85015 2009-04-03 12:27:59Z johnnyw $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_ARPA_OS_INET_H +#define ACE_OS_INCLUDE_ARPA_OS_INET_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/netinet/os_in.h" + +#if !defined (ACE_LACKS_ARPA_INET_H) + extern "C" { +# include /**/ + } +#endif /* !ACE_LACKS_ARPA_INET_H */ + +#if defined (ACE_USES_INETLIB_H) +# include /**/ +#endif /* ACE_USES_INETLIB_H */ + +/** + * In some environments it is useful to swap the bytes on write, for + * instance: a fast server can be feeding a lot of slow clients that + * happen to have the wrong byte order. + * Because this is a rarely used feature we disable it by default to + * minimize footprint. + * This macro enables the functionality, but we still need a way to + * activate it on a per-connection basis. + */ +// #define ACE_ENABLE_SWAP_ON_WRITE + +/** + * In some environements we never need to swap bytes when reading, for + * instance embebbed systems (such as avionics) or homogenous + * networks. + * Setting this macro disables the capabilities to demarshall streams + * in the wrong byte order. + */ +// #define ACE_DISABLE_SWAP_ON_READ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#if defined (ACE_LACKS_INET_ATON_PROTOTYPE) + int inet_aton (const char *, struct in_addr *); +#endif /* ACE_LACKS_INET_ATON_PROTOTYPE */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_ARPA_OS_INET_H */ diff --git a/dep/acelite/ace/os_include/net/os_if.h b/dep/acelite/ace/os_include/net/os_if.h new file mode 100644 index 00000000000..3dcf5918f8c --- /dev/null +++ b/dep/acelite/ace/os_include/net/os_if.h @@ -0,0 +1,112 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_if.h + * + * sockets local interfaces + * + * $Id: os_if.h 88719 2010-01-26 12:55:03Z sowayaa $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_NET_OS_IF_H +#define ACE_OS_INCLUDE_NET_OS_IF_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_NET_IF_H) +# include /**/ +# if defined (ACE_HAS_NET_IF_DL_H) +# include /**/ +# endif /* ACE_HAS_NET_IF_DL_H */ +# if defined (HPUX) && defined (IOR) + /* HP-UX 11.11 defines IOR in /usr/include/pa/inline.h + and we don't want that definition. See IOP_IORC.h. + Thanks to Torsten Kopper for this patch.*/ +# undef IOR +# endif /* HPUX && IOR */ +#endif /* !ACE_LACKS_NET_IF_H */ + +#if defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0) +# include /**/ +#endif /* ACE_HAS_WINSOCK2 */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#if defined (ACE_HAS_BROKEN_IF_HEADER) + struct ifafilt; +#endif /* ACE_HAS_BROKEN_IF_HEADER */ + +#if defined (ACE_LACKS_IFREQ) +struct ifreq { +#define IFNAMSIZ 16 + char ifr_name[IFNAMSIZ]; /* if name, e.g. "en0" */ + union { + struct sockaddr ifru_addr; + struct sockaddr ifru_dstaddr; + struct sockaddr ifru_broadaddr; + short ifru_flags; + int ifru_metric; + int ifru_mtu; + int ifru_phys; + int ifru_media; + caddr_t ifru_data; + int (*ifru_tap)(struct ifnet *, struct ether_header *, struct mbuf *); + } ifr_ifru; +#define ifr_addr ifr_ifru.ifru_addr /* address */ +#define ifr_dstaddr ifr_ifru.ifru_dstaddr /* other end of p-to-p link */ +#define ifr_broadaddr ifr_ifru.ifru_broadaddr /* broadcast address */ +#define ifr_flags ifr_ifru.ifru_flags /* flags */ +#define ifr_metric ifr_ifru.ifru_metric /* metric */ +#define ifr_mtu ifr_ifru.ifru_mtu /* mtu */ +#define ifr_phys ifr_ifru.ifru_phys /* physical wire */ +#define ifr_media ifr_ifru.ifru_media /* physical media */ +#define ifr_data ifr_ifru.ifru_data /* for use by interface */ +#define ifr_tap ifr_ifru.ifru_tap /* tap function */ +}; +#endif /* ACE_LACKS_IFREQ */ + +#if defined (ACE_LACKS_IFCONF) +struct ifconf { + int ifc_len; + union { + caddr_t ifcu_buf; + struct ifreq *ifcu_req; + } ifc_ifcu; +#define ifc_buf ifc_ifcu.ifcu_buf /* buffer address */ +#define ifc_req ifc_ifcu.ifcu_req /* array of structures returned */ + }; +#endif /* ACE_LACKS_IFCONF */ + +#if !defined (IFF_UP) +# define IFF_UP 0x1 +#endif /* IFF_UP */ + +#if !defined (IFF_LOOPBACK) +# define IFF_LOOPBACK 0x8 +#endif /* IFF_LOOPBACK */ + +#if !defined (IFF_BROADCAST) +# define IFF_BROADCAST 0x2 +#endif /* IFF_BROADCAST */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_NET_OS_IF_H */ diff --git a/dep/acelite/ace/os_include/netinet/os_in.h b/dep/acelite/ace/os_include/netinet/os_in.h new file mode 100644 index 00000000000..dff894aadce --- /dev/null +++ b/dep/acelite/ace/os_include/netinet/os_in.h @@ -0,0 +1,179 @@ + +// -*- C++ -*- + +//============================================================================= +/** + * @file os_in.h + * + * Internet address family + * + * $Id: os_in.h 85438 2009-05-26 06:56:46Z johnnyw $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_NETINET_OS_IN_H +#define ACE_OS_INCLUDE_NETINET_OS_IN_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/os_inttypes.h" +#include "ace/os_include/sys/os_socket.h" + +#if defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0) +# include /**/ +#endif /* ACE_HAS_WINSOCK2 */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#if !defined (ACE_LACKS_NETINET_IN_H) +# include /**/ +#endif /* !ACE_LACKS_NETINET_IN_H */ + + +# if defined (ACE_HAS_PHARLAP_RT) +# define ACE_IPPROTO_TCP SOL_SOCKET +# else +# define ACE_IPPROTO_TCP IPPROTO_TCP +# endif /* ACE_HAS_PHARLAP_RT */ + +# if !defined (ACE_HAS_IP_MULTICAST) && defined (ACE_LACKS_IP_ADD_MEMBERSHIP) + // Even if ACE_HAS_IP_MULTICAST is not defined, if IP_ADD_MEMBERSHIP + // is defined, assume that the ip_mreq struct is also defined + // (presumably in netinet/in.h). + struct ip_mreq + { + /// IP multicast address of group + struct in_addr imr_multiaddr; + /// Local IP address of interface + struct in_addr imr_interface; + }; +# endif /* ! ACE_HAS_IP_MULTICAST && ACE_LACKS_IP_ADD_MEMBERSHIP */ + +# if defined (ACE_LACKS_IN_ADDR) + struct in_addr + { + u_long s_addr; + }; +# endif /* ACE_LACKS_IN_ADDR */ + +# if defined (ACE_LACKS_SOCKADDR_IN) + struct sockaddr_in + { + short sin_family; // e.g. AF_INET + unsigned short sin_port; // e.g. htons(3490) + struct in_addr sin_addr; // see struct in_addr, below + char sin_zero[8]; // zero this if you want to + }; +# endif /* ACE_LACKS_SOCKADDR_IN */ + +# if defined (ACE_LACKS_SOCKADDR_UN) + struct sockaddr_un { + u_char sun_len; /* sockaddr len including null */ + u_char sun_family; /* AF_UNIX */ + char sun_path[104]; /* path name (gag) */ + }; +#endif /* ACE_LACKS_SOCKADDR_UN */ + +# if defined (ACE_LACKS_IP_MREQ) + struct ip_mreq + { + struct in_addr imr_multiaddr; /* IP multicast address of group */ + struct in_addr imr_interface; /* local IP address of interface */ + }; +# endif /* ACE_LACKS_IP_MREQ */ + +#if !defined (IPPORT_RESERVED) +# define IPPORT_RESERVED 1024 +#endif /* !IPPORT_RESERVED */ + +#if !defined (IPPORT_USERRESERVED) +# define IPPORT_USERRESERVED 5000 +#endif /* !IPPORT_USERRESERVED */ + +// Define INET loopback address constant if it hasn't been defined +// Dotted Decimal 127.0.0.1 == Hexidecimal 0x7f000001 +#if !defined (INADDR_LOOPBACK) +# define INADDR_LOOPBACK ((ACE_UINT32) 0x7f000001) +#endif /* INADDR_LOOPBACK */ + +// The INADDR_NONE address is generally 255.255.255.255. +#if !defined (INADDR_NONE) +# define INADDR_NONE ((ACE_UINT32) 0xffffffff) +#endif /* INADDR_NONE */ + +// Define INET string length constants if they haven't been defined +// +// for IPv4 dotted-decimal +#if !defined (INET_ADDRSTRLEN) +# define INET_ADDRSTRLEN 16 +#endif /* INET_ADDRSTRLEN */ +// +// for IPv6 hex string +#if !defined (INET6_ADDRSTRLEN) +# define INET6_ADDRSTRLEN 46 +#endif /* INET6_ADDRSTRLEN */ + +# if !defined (IP_DROP_MEMBERSHIP) +# define IP_DROP_MEMBERSHIP 0 +# endif /* IP_DROP_MEMBERSHIP */ + +# if !defined (IP_ADD_MEMBERSHIP) +# define IP_ADD_MEMBERSHIP 0 +# define ACE_LACKS_IP_ADD_MEMBERSHIP +# endif /* IP_ADD_MEMBERSHIP */ + +# if !defined (IP_DEFAULT_MULTICAST_TTL) +# define IP_DEFAULT_MULTICAST_TTL 0 +# endif /* IP_DEFAULT_MULTICAST_TTL */ + +# if !defined (IP_DEFAULT_MULTICAST_LOOP) +# define IP_DEFAULT_MULTICAST_LOOP 0 +# endif /* IP_DEFAULT_MULTICAST_LOOP */ + +# if !defined (IP_MULTICAST_IF) +# define IP_MULTICAST_IF 0 +# endif /* IP_MULTICAST_IF */ + +# if !defined (IP_MULTICAST_TTL) +# define IP_MULTICAST_TTL 1 +# endif /* IP_MULTICAST_TTL */ + +# if !defined (IP_MULTICAST_LOOP) +# define IP_MULTICAST_LOOP 2 +# endif /* IP_MULTICAST_LOOP */ + +# if !defined (IP_MAX_MEMBERSHIPS) +# define IP_MAX_MEMBERSHIPS 0 +# endif /* IP_MAX_MEMBERSHIP */ + +# if !defined (IPPROTO_IP) +# define IPPROTO_IP 0 +# endif /* IPPROTO_IP */ + +# if !defined (IPPROTO_TCP) +# define IPPROTO_TCP 6 +# endif /* IPPROTO_TCP */ + +# if !defined (INADDR_ANY) +# define INADDR_ANY (u_long)0x00000000 +# endif /* INADDR_ANY */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_NETINET_OS_IN_H */ diff --git a/dep/acelite/ace/os_include/netinet/os_tcp.h b/dep/acelite/ace/os_include/netinet/os_tcp.h new file mode 100644 index 00000000000..aca6590bc94 --- /dev/null +++ b/dep/acelite/ace/os_include/netinet/os_tcp.h @@ -0,0 +1,46 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_tcp.h + * + * definitions for the Internet Transmission Control Protocol (TCP) + * + * $Id: os_tcp.h 88499 2010-01-12 19:34:34Z olli $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_NETINET_OS_TCP_H +#define ACE_OS_INCLUDE_NETINET_OS_TCP_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_NETINET_TCP_H) +# include /**/ +#endif /* !ACE_LACKS_NETINET_TCP_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +# if !defined (TCP_NODELAY) +# define TCP_NODELAY 0x01 +# endif /* TCP_NODELAY */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_NETINET_OS_TCP_H */ diff --git a/dep/acelite/ace/os_include/os_aio.h b/dep/acelite/ace/os_include/os_aio.h new file mode 100644 index 00000000000..4ec9fe9d127 --- /dev/null +++ b/dep/acelite/ace/os_include/os_aio.h @@ -0,0 +1,47 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_aio.h + * + * asynchronous input and output (REALTIME) + * + * $Id: os_aio.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_AIO_H +#define ACE_OS_INCLUDE_OS_AIO_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +// Inclusion of the header may make visible symbols defined in +// the headers , , , and . + +#include "ace/os_include/os_signal.h" // for sigevent + +#if !defined (ACE_LACKS_AIO_H) +# include /**/ +#endif /* !ACE_LACKS_AIO_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_AIO_H */ diff --git a/dep/acelite/ace/os_include/os_assert.h b/dep/acelite/ace/os_include/os_assert.h new file mode 100644 index 00000000000..fdca573fe8e --- /dev/null +++ b/dep/acelite/ace/os_include/os_assert.h @@ -0,0 +1,46 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_assert.h + * + * verify program assertion + * + * $Id: os_assert.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_ASSERT_H +#define ACE_OS_INCLUDE_OS_ASSERT_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_ASSERT_H) +# include /**/ +#endif /* !ACE_LACKS_ASSERT_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#if defined (ACE_LACKS_ASSERT_MACRO) +# define assert(expr) +#endif + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_ASSERT_H */ diff --git a/dep/acelite/ace/os_include/os_byteswap.h b/dep/acelite/ace/os_include/os_byteswap.h new file mode 100644 index 00000000000..b55754ee810 --- /dev/null +++ b/dep/acelite/ace/os_include/os_byteswap.h @@ -0,0 +1,41 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_byteswap.h + * + * Byteswap methods + * + * $Id: os_byteswap.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Johnny Willemsen + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_BYTESWAP_H +#define ACE_OS_INCLUDE_OS_BYTESWAP_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_BYTESWAP_H) +# include /**/ +#endif /* !ACE_HAS_INTRIN_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_BYTESWAP_H */ diff --git a/dep/acelite/ace/os_include/os_complex.h b/dep/acelite/ace/os_include/os_complex.h new file mode 100644 index 00000000000..5e6546f82df --- /dev/null +++ b/dep/acelite/ace/os_include/os_complex.h @@ -0,0 +1,42 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_complex.h + * + * complex arithmetic + * + * $Id: os_complex.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_COMPLEX_H +#define ACE_OS_INCLUDE_OS_COMPLEX_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_COMPLEX_H) +# include /**/ +#endif /* !ACE_LACKS_COMPLEX_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_COMPLEX_H */ diff --git a/dep/acelite/ace/os_include/os_cpio.h b/dep/acelite/ace/os_include/os_cpio.h new file mode 100644 index 00000000000..2c06e8eb2f5 --- /dev/null +++ b/dep/acelite/ace/os_include/os_cpio.h @@ -0,0 +1,42 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_cpio.h + * + * cpio archive values + * + * $Id: os_cpio.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_CPIO_H +#define ACE_OS_INCLUDE_OS_CPIO_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_CPIO_H) +# include /**/ +#endif /* !ACE_LACKS_CPIO_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_CPIO_H */ diff --git a/dep/acelite/ace/os_include/os_ctype.h b/dep/acelite/ace/os_include/os_ctype.h new file mode 100644 index 00000000000..4b5b65120c5 --- /dev/null +++ b/dep/acelite/ace/os_include/os_ctype.h @@ -0,0 +1,48 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_ctype.h + * + * character types + * + * $Id: os_ctype.h 83520 2008-11-03 08:54:08Z johnnyw $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_CTYPE_H +#define ACE_OS_INCLUDE_OS_CTYPE_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_CTYPE_H) +# include /**/ +#endif /* !ACE_LACKS_CTYPE_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +// @todo move the is* and is* emulation methods in ACE_OS here +// and let ACE_OS just call them. +#if !defined (ACE_HAS_CTYPE_T) +typedef int ctype_t; +#endif + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_CTYPE_H */ diff --git a/dep/acelite/ace/os_include/os_dirent.h b/dep/acelite/ace/os_include/os_dirent.h new file mode 100644 index 00000000000..034bacd006d --- /dev/null +++ b/dep/acelite/ace/os_include/os_dirent.h @@ -0,0 +1,110 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_dirent.h + * + * format of directory entries + * + * $Id: os_dirent.h 82985 2008-10-08 18:15:30Z johnnyw $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_DIRENT_H +#define ACE_OS_INCLUDE_OS_DIRENT_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_types.h" +#include "ace/os_include/os_limits.h" + +#if defined (ACE_VXWORKS) && (ACE_VXWORKS < 0x620) +# include "ace/os_include/os_unistd.h" // VxWorks needs this to compile +#endif /* ACE_VXWORKS */ + +#if !defined (ACE_LACKS_DIRENT_H) +# include /**/ +#endif /* !ACE_LACKS_DIRENT_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#if !defined (MAXNAMLEN) +# define MAXNAMLEN NAME_MAX +#endif /* !MAXNAMLEN */ + +// At least compile on some of the platforms without info yet. +#if !defined (ACE_HAS_DIRENT) +typedef int ACE_DIR; +struct dirent { +}; +#endif /* ACE_HAS_DIRENT */ + +#if defined (ACE_LACKS_STRUCT_DIR) +struct dirent { + unsigned short d_ino; + unsigned short d_off; + unsigned short d_reclen; + // This must be a ACE_TCHAR * and not a one element + // ACE_TCHAR array. It causes problems on wide + // character builds with Visual C++ 6.0. + ACE_TCHAR *d_name; +}; + +#define ACE_DIRENT dirent +#define ACE_HAS_TCHAR_DIRENT + +struct ACE_DIR { + /// The name of the directory we are looking into + ACE_TCHAR *directory_name_; + + /// Remember the handle between calls. + HANDLE current_handle_; + + /// The struct for the results + ACE_DIRENT *dirent_; + + /// The struct for intermediate results. + ACE_TEXT_WIN32_FIND_DATA fdata_; + + /// A flag to remember if we started reading already. + int started_reading_; +}; +#elif defined (ACE_WIN32) && (__BORLANDC__) && defined (ACE_USES_WCHAR) +#define ACE_HAS_TCHAR_DIRENT +#define ACE_DIRENT wdirent +typedef wDIR ACE_DIR; +#else +#define ACE_DIRENT dirent +typedef DIR ACE_DIR; +#endif /* ACE_LACKS_STRUCT_DIR */ + +#if defined (ACE_LACKS_SCANDIR_PROTOTYPE) +int scandir (const char *, + struct dirent ***, + int (*) (const struct dirent *), + int (*) (const void *, const void *)); +#endif /* ACE_LACKS_SCANDIR_PROTOTYPE */ + +#if defined (ACE_LACKS_ALPHASORT_PROTOTYPE) +int alphasort (const void *, const void *); +#endif /* ACE_LACKS_ALPHASORT_PROTOTYPE */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_DIRENT_H */ diff --git a/dep/acelite/ace/os_include/os_dlfcn.h b/dep/acelite/ace/os_include/os_dlfcn.h new file mode 100644 index 00000000000..0f74437fb80 --- /dev/null +++ b/dep/acelite/ace/os_include/os_dlfcn.h @@ -0,0 +1,101 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_dlfcn.h + * + * dynamic linking + * + * $Id: os_dlfcn.h 82273 2008-07-09 14:21:45Z jtc $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_DLFCN_H +#define ACE_OS_INCLUDE_OS_DLFCN_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_DLFCN_H) +# include /**/ +#endif /* !ACE_LACKS_DLFCN_H */ + +#if defined (__hpux) +# if defined(__GNUC__) || __cplusplus >= 199707L +# include /**/ +# else +# include /**/ +# endif /* (g++ || HP aC++) vs. HP C++ */ +#endif /* __hpux */ + +#if defined (ACE_VXWORKS) && !defined (__RTP__) +# include /**/ /* for module load */ +# include /**/ /* for module unload */ +# include /**/ /* for findSymbol */ +# include /**/ /* for global symbol table */ +#endif /* ACE_VXWORKS */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#if defined (_M_UNIX) + int _dlclose (void *); + char *_dlerror (void); + void *_dlopen (const char *, int); + void * _dlsym (void *, const char *); +#endif /* _M_UNIX */ + +/* Set the proper handle type for dynamically-loaded libraries. */ +/* Also define a default 'mode' for loading a library - the names and values */ +/* differ between OSes, so if you write code that uses the mode, be careful */ +/* of the platform differences. */ +#if defined (ACE_WIN32) + // Dynamic loading-related types - used for dlopen and family. + typedef HINSTANCE ACE_SHLIB_HANDLE; +# define ACE_SHLIB_INVALID_HANDLE 0 +# define ACE_DEFAULT_SHLIB_MODE 0 +#elif defined (ACE_HAS_SVR4_DYNAMIC_LINKING) + typedef void *ACE_SHLIB_HANDLE; +# define ACE_SHLIB_INVALID_HANDLE 0 + // This is needed to for dynamic_cast to work properly on objects passed to + // libraries. +# define ACE_DEFAULT_SHLIB_MODE RTLD_LAZY | RTLD_GLOBAL +#elif defined (__hpux) + typedef shl_t ACE_SHLIB_HANDLE; +# define ACE_SHLIB_INVALID_HANDLE 0 +# define ACE_DEFAULT_SHLIB_MODE BIND_DEFERRED | DYNAMIC_PATH +#else /* !ACE_WIN32 && !ACE_HAS_SVR4_DYNAMIC_LINKING && !__hpux */ + typedef void *ACE_SHLIB_HANDLE; +# define ACE_SHLIB_INVALID_HANDLE 0 +# define ACE_DEFAULT_SHLIB_MODE RTLD_LAZY +#endif /* ACE_WIN32 */ + +#if !defined (RTLD_LAZY) +#define RTLD_LAZY 1 +#endif /* !RTLD_LAZY */ + +#if !defined (RTLD_NOW) +#define RTLD_NOW 2 +#endif /* !RTLD_NOW */ + +#if !defined (RTLD_GLOBAL) +#define RTLD_GLOBAL 3 +#endif /* !RTLD_GLOBAL */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_DLFCN_H */ diff --git a/dep/acelite/ace/os_include/os_errno.h b/dep/acelite/ace/os_include/os_errno.h new file mode 100644 index 00000000000..4f5cfe6954c --- /dev/null +++ b/dep/acelite/ace/os_include/os_errno.h @@ -0,0 +1,458 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_errno.h + * + * system error numbers + * + * $Id: os_errno.h 91076 2010-07-13 14:20:35Z johnnyw $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_ERRNO_H +#define ACE_OS_INCLUDE_OS_ERRNO_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_ERRNO_H) +# include /**/ +#endif /* !ACE_LACKS_ERRNO_H */ + +#if defined (ACE_VXWORKS) +// Needed for VxWorks to pickup errnoSet() +#include /**/ +#endif /* ACE_VXWORKS */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#if defined (ACE_WIN32) + // error code mapping for windows + + // VC++ 10 has these error codes defined in errno.h, + // this will cause different errors in ACE. + // So we undef these error codes if they are wrongly defined +# if defined (EWOULDBLOCK) && (EWOULDBLOCK != WSAEWOULDBLOCK) +# undef EWOULDBLOCK +# endif /* EWOULDBLOCK */ +# if defined (EINPROGRESS) && (EINPROGRESS != WSAEINPROGRESS) +# undef EINPROGRESS +# endif /* EINPROGRESS */ +# if defined (EALREADY) && (EALREADY != WSAEALREADY) +# undef EALREADY +# endif /* EALREADY */ +# if defined (ENOTSOCK) && (ENOTSOCK != WSAENOTSOCK) +# undef ENOTSOCK +# endif /* ENOTSOCK */ +# if defined (EDESTADDRREQ) && (EDESTADDRREQ != WSAEDESTADDRREQ) +# undef EDESTADDRREQ +# endif /* EDESTADDRREQ */ +# if defined (EMSGSIZE) && (EMSGSIZE != WSAEMSGSIZE) +# undef EMSGSIZE +# endif /* EMSGSIZE */ +# if defined (EPROTOTYPE) && (EPROTOTYPE != WSAEPROTOTYPE) +# undef EPROTOTYPE +# endif /* EPROTOTYPE */ +# if defined (ENOPROTOOPT) && (ENOPROTOOPT != WSAENOPROTOOPT) +# undef ENOPROTOOPT +# endif /* ENOPROTOOPT */ +# if defined (EPROTONOSUPPORT) && (EPROTONOSUPPORT != WSAEPROTONOSUPPORT) +# undef EPROTONOSUPPORT +# endif /* EPROTONOSUPPORT */ +# if defined (ESOCKTNOSUPPORT) && (ESOCKTNOSUPPORT != WSAESOCKTNOSUPPORT) +# undef ESOCKTNOSUPPORT +# endif /* ESOCKTNOSUPPORT */ +# if defined (EOPNOTSUPP) && (EOPNOTSUPP != WSAEOPNOTSUPP) +# undef EOPNOTSUPP +# endif /* EOPNOTSUPP */ +# if defined (EPFNOSUPPORT) && (EPFNOSUPPORT != WSAEPFNOSUPPORT) +# undef EPFNOSUPPORT +# endif /* EPFNOSUPPORT */ +# if defined (EAFNOSUPPORT) && (EAFNOSUPPORT != WSAEAFNOSUPPORT) +# undef EAFNOSUPPORT +# endif /* EAFNOSUPPORT */ +# if defined (EADDRINUSE) && (EADDRINUSE != WSAEADDRINUSE) +# undef EADDRINUSE +# endif /* EADDRINUSE */ +# if defined (EADDRNOTAVAIL) && (EADDRNOTAVAIL != WSAEADDRNOTAVAIL) +# undef EADDRNOTAVAIL +# endif /* EADDRNOTAVAIL */ +# if defined (ENETDOWN) && (ENETDOWN != WSAENETDOWN) +# undef ENETDOWN +# endif /* ENETDOWN */ +# if defined (ENETUNREACH) && (ENETUNREACH != WSAENETUNREACH) +# undef ENETUNREACH +# endif /* ENETUNREACH */ +# if defined (ENETRESET) && (ENETRESET != WSAENETRESET) +# undef ENETRESET +# endif /* ENETRESET */ +# if defined (ECONNABORTED) && (ECONNABORTED != WSAECONNABORTED) +# undef ECONNABORTED +# endif /* ECONNABORTED */ +# if defined (ECONNRESET) && (ECONNRESET != WSAECONNRESET) +# undef ECONNRESET +# endif /* ECONNRESET */ +# if defined (ENOBUFS) && (ENOBUFS != WSAENOBUFS) +# undef ENOBUFS +# endif /* ENOBUFS */ +# if defined (EISCONN) && (EISCONN != WSAEISCONN) +# undef EISCONN +# endif /* EISCONN */ +# if defined (ENOTCONN) && (ENOTCONN != WSAENOTCONN) +# undef ENOTCONN +# endif /* ENOTCONN */ +# if defined (ESHUTDOWN) && (ESHUTDOWN != WSAESHUTDOWN) +# undef ESHUTDOWN +# endif /* ESHUTDOWN */ +# if defined (ETOOMANYREFS) && (ETOOMANYREFS != WSAETOOMANYREFS) +# undef ETOOMANYREFS +# endif /* ETOOMANYREFS */ +# if defined (ETIMEDOUT) && (ETIMEDOUT != WSAETIMEDOUT) +# undef ETIMEDOUT +# endif /* ETIMEDOUT */ +# if defined (ECONNREFUSED) && (ECONNREFUSED != WSAECONNREFUSED) +# undef ECONNREFUSED +# endif /* ECONNREFUSED */ +# if defined (ELOOP) && (ELOOP != WSAELOOP) +# undef ELOOP +# endif /* ELOOP */ +//# if defined (ENAMETOOLONG) && (ENAMETOOLONG != WSAENAMETOOLONG) +//# undef ENAMETOOLONG +//# endif /* ENAMETOOLONG */ +# if defined (EHOSTDOWN) && (EHOSTDOWN != WSAEHOSTDOWN) +# undef EHOSTDOWN +# endif /* EHOSTDOWN */ +# if defined (EHOSTUNREACH) && (EHOSTUNREACH != WSAEHOSTUNREACH) +# undef EHOSTUNREACH +# endif /* EHOSTUNREACH */ +//# if defined (ENOTEMPTY) && (ENOTEMPTY != WSAENOTEMPTY) +//# undef ENOTEMPTY +//# endif /* ENOTEMPTY */ +# if defined (EPROCLIM) && (EPROCLIM != WSAEPROCLIM) +# undef EPROCLIM +# endif /* EPROCLIM */ +# if defined (EUSERS) && (EUSERS != WSAEUSERS) +# undef EUSERS +# endif /* EUSERS */ +# if defined (EDQUOT) && (EDQUOT != WSAEDQUOT) +# undef EDQUOT +# endif /* EDQUOT */ +# if defined (ESTALE) && (ESTALE != WSAESTALE) +# undef ESTALE +# endif /* ESTALE */ +# if defined (EREMOTE) && (EREMOTE != WSAEREMOTE) +# undef EREMOTE +# endif /* EREMOTE */ + +# if !defined (ETIME) +# define ETIME ERROR_SEM_TIMEOUT +# endif /* !ETIME */ +# if !defined (EWOULDBLOCK) +# define EWOULDBLOCK WSAEWOULDBLOCK +# endif /* !EWOULDBLOCK */ +# if !defined (EINPROGRESS) +# define EINPROGRESS WSAEINPROGRESS +# endif /* !EINPROGRESS */ +# if !defined (EALREADY) +# define EALREADY WSAEALREADY +# endif /* !EALREADY */ +# if !defined (ENOTSOCK) +# define ENOTSOCK WSAENOTSOCK +# endif /* !ENOTSOCK */ +# if !defined (EDESTADDRREQ) +# define EDESTADDRREQ WSAEDESTADDRREQ +# endif /* !EDESTADDRREQ */ +# if !defined (EMSGSIZE) +# define EMSGSIZE WSAEMSGSIZE +# endif /* !EMSGSIZE */ +# if !defined (EPROTOTYPE) +# define EPROTOTYPE WSAEPROTOTYPE +# endif /* !EPROTOTYPE */ +# if !defined (ENOPROTOOPT) +# define ENOPROTOOPT WSAENOPROTOOPT +# endif /* !ENOPROTOOPT */ +# if !defined (EPROTONOSUPPORT) +# define EPROTONOSUPPORT WSAEPROTONOSUPPORT +# endif /* !EPROTONOSUPPORT */ +# if !defined (ESOCKTNOSUPPORT) +# define ESOCKTNOSUPPORT WSAESOCKTNOSUPPORT +# endif /* !ESOCKTNOSUPPORT */ +# if !defined (EOPNOTSUPP) +# define EOPNOTSUPP WSAEOPNOTSUPP +# endif /* !EOPNOTSUPP */ +# if !defined (EPFNOSUPPORT) +# define EPFNOSUPPORT WSAEPFNOSUPPORT +# endif /* !EPFNOSUPPORT */ +# if !defined (EAFNOSUPPORT) +# define EAFNOSUPPORT WSAEAFNOSUPPORT +# endif /* !EAFNOSUPPORT */ +# if !defined (EADDRINUSE) +# define EADDRINUSE WSAEADDRINUSE +# endif /* !EADDRINUSE */ +# if !defined (EADDRNOTAVAIL) +# define EADDRNOTAVAIL WSAEADDRNOTAVAIL +# endif /* !EADDRNOTAVAIL */ +# if !defined (ENETDOWN) +# define ENETDOWN WSAENETDOWN +# endif /* !ENETDOWN */ +# if !defined (ENETUNREACH) +# define ENETUNREACH WSAENETUNREACH +# endif /* !ENETUNREACH */ +# if !defined (ENETRESET) +# define ENETRESET WSAENETRESET +# endif /* !ENETRESET */ +# if !defined (ECONNABORTED) +# define ECONNABORTED WSAECONNABORTED +# endif /* !ECONNABORTED */ +# if !defined (ECONNRESET) +# define ECONNRESET WSAECONNRESET +# endif /* !ECONNRESET */ +# if !defined (ENOBUFS) +# define ENOBUFS WSAENOBUFS +# endif /* !ENOBUFS */ +# if !defined (EISCONN) +# define EISCONN WSAEISCONN +# endif /* !EISCONN */ +# if !defined (ENOTCONN) +# define ENOTCONN WSAENOTCONN +# endif /* !ENOTCONN */ +# if !defined (ESHUTDOWN) +# define ESHUTDOWN WSAESHUTDOWN +# endif /* !ESHUTDOWN */ +# if !defined (ETOOMANYREFS) +# define ETOOMANYREFS WSAETOOMANYREFS +# endif /* !ETOOMANYREFS */ +# if !defined (ETIMEDOUT) +# define ETIMEDOUT WSAETIMEDOUT +# endif /* !ETIMEDOUT */ +# if !defined (ECONNREFUSED) +# define ECONNREFUSED WSAECONNREFUSED +# endif /* !ECONNREFUSED */ +# if !defined (ELOOP) +# define ELOOP WSAELOOP +# endif /* !ELOOP */ +# if !defined (EHOSTDOWN) +# define EHOSTDOWN WSAEHOSTDOWN +# endif /* !EHOSTDOWN */ +# if !defined (EHOSTUNREACH) +# define EHOSTUNREACH WSAEHOSTUNREACH +# endif /* !EHOSTUNREACH */ +# if !defined (EPROCLIM) +# define EPROCLIM WSAEPROCLIM +# endif /* !EPROCLIM */ +# if !defined (EUSERS) +# define EUSERS WSAEUSERS +# endif /* !EUSERS */ +# if !defined (EDQUOT) +# define EDQUOT WSAEDQUOT +# endif /* !EDQUOT */ +# if !defined (ESTALE) +# define ESTALE WSAESTALE +# endif /* !ESTALE */ +# if !defined (EREMOTE) +# define EREMOTE WSAEREMOTE +# endif /* !EREMOTE */ + + // Grrr! ENAMETOOLONG and ENOTEMPTY are already defined by the horrible + // 'standard' library. + // #define ENAMETOOLONG WSAENAMETOOLONG +# if !defined (EADDRINUSE) +# define EADDRINUSE WSAEADDRINUSE +# endif /* EADDRINUSE*/ + + // CE needs this... +# if !defined (EPERM) +# define EPERM ERROR_ACCESS_DENIED +# endif +#endif /* ACE_WIN32 */ + +#if defined (ACE_HAS_H_ERRNO) +void herror (const char *str); +#endif /* ACE_HAS_H_ERRNO */ + +#if defined (ACE_LACKS_ERRNO_H) +# if !defined (EPERM) +# define EPERM 1 +# endif /* EPERM */ +# if !defined (ENOENT) +# define ENOENT 2 +# endif /* ENOENT */ +# if !defined (ESRCH) +# define ESRCH 3 +# endif /* ESRCH */ +# if !defined (EINTR) +# define EINTR 4 +# endif /* EINTR */ +# if !defined (EIO) +# define EIO 5 +# endif /* EIO */ +# if !defined (ENXIO) +# define ENXIO 6 +# endif /* ENXIO */ +# if !defined (E2BIG) +# define E2BIG 7 +# endif /* E2BIG */ +# if !defined (ENOEXEC) +# define ENOEXEC 8 +# endif /* ENOEXEC */ +# if !defined (EBADF) +# define EBADF 9 +# endif /* EBADF */ +# if !defined (ECHILD) +# define ECHILD 10 +# endif /* ECHILD */ +# if !defined (EAGAIN) +# define EAGAIN 11 +# endif /* EAGAIN */ +# if !defined (ENOMEM) +# define ENOMEM 12 +# endif /* ENOMEM */ +# if !defined (EACCES) +# define EACCES 13 +# endif /* EACCES */ +# if !defined (EFAULT) +# define EFAULT 14 +# endif /* EFAULT */ +# if !defined (EBUSY) +# define EBUSY 16 +# endif /* EBUSY */ +# if !defined (EEXIST) +# define EEXIST 17 +# endif /* EEXIST */ +# if !defined (EXDEV) +# define EXDEV 18 +# endif /* EXDEV */ +# if !defined (ENODEV) +# define ENODEV 19 +# endif /* ENODEV */ +# if !defined (ENOTDIR) +# define ENOTDIR 20 +# endif /* ENOTDIR */ +# if !defined (EISDIR) +# define EISDIR 21 +# endif /* EISDIR */ +# if !defined (EINVAL) +# define EINVAL 22 +# endif /* EINVAL */ +# if !defined (ENFILE) +# define ENFILE 23 +# endif /* ENFILE */ +# if !defined (EMFILE) +# define EMFILE 24 +# endif /* EMFILE */ +# if !defined (ENOTTY) +# define ENOTTY 25 +# endif /* ENOTTY */ +# if !defined (EFBIG) +# define EFBIG 27 +# endif /* EFBIG */ +# if !defined (ENOSPC) +# define ENOSPC 28 +# endif /* ENOSPC */ +# if !defined (ESPIPE) +# define ESPIPE 29 +# endif /* ESPIPE */ +# if !defined (EROFS) +# define EROFS 30 +# endif /* EROFS */ +# if !defined (EMLINK) +# define EMLINK 31 +# endif /* EMLINK */ +# if !defined (EPIPE) +# define EPIPE 32 +# endif /* EPIPE */ +# if !defined (EDOM) +# define EDOM 33 +# endif /* EDOM */ +# if !defined (ERANGE) +# define ERANGE 34 +# endif /* ERANGE */ +# if !defined (EDEADLK) +# define EDEADLK 36 +# endif /* EDEADLK */ +# if !defined (ENAMETOOLONG) +# define ENAMETOOLONG 38 +# endif /* ENAMETOOLONG */ +# if !defined (ENOLCK) +# define ENOLCK 39 +# endif /* ENOLCK */ +# if !defined (ENOSYS) +# define ENOSYS 40 +# endif /* ENOSYS */ +# if !defined (ENOTEMPTY) +# define ENOTEMPTY 41 +# endif /* ENOTEMPTY */ +#endif /* ACE_LACKS_ERRNO_H */ + +#if defined (ACE_LACKS_T_ERRNO) +extern int t_errno; +#endif /* ACE_LACKS_T_ERRNO */ + +#if !defined (ENOSYS) +# define ENOSYS EFAULT /* Operation not supported or unknown error. */ +#endif /* !ENOSYS */ + +#if !defined (ENOTSUP) +# define ENOTSUP ENOSYS /* Operation not supported. */ +#endif /* !ENOTSUP */ + +#if !defined (ESUCCESS) +# define ESUCCESS 0 +#endif /* !ESUCCESS */ + +#if !defined (EIDRM) +# define EIDRM 0 +#endif /* !EIDRM */ + +#if !defined (ENFILE) +# define ENFILE EMFILE /* No more socket descriptors are available. */ +#endif /* !ENFILE */ + +#if !defined (ECOMM) + // Not the same, but ECONNABORTED is provided on NT. +# define ECOMM ECONNABORTED +#endif /* ECOMM */ + +#if !defined (EDEADLK) +# define EDEADLK 1000 /* Some large number.... */ +#endif /* !EDEADLK */ + +#if !defined (ENXIO) /* Needed in SOCK_Dgram_Mcast */ +# define ENXIO 6 +#endif /* ENXIO */ + +#if !defined (ETIMEDOUT) && defined (ETIME) +# define ETIMEDOUT ETIME +#endif /* ETIMEDOUT */ + +#if !defined (ETIME) && defined (ETIMEDOUT) +# define ETIME ETIMEDOUT +#endif /* ETIMED */ + +#if !defined (EBUSY) +# define EBUSY ETIME +#endif /* EBUSY */ + +#if !defined (ECANCELED) +# define ECANCELED 125 +#endif /* ECANCELED */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_ERRNO_H */ diff --git a/dep/acelite/ace/os_include/os_fcntl.h b/dep/acelite/ace/os_include/os_fcntl.h new file mode 100644 index 00000000000..048ff62ae6e --- /dev/null +++ b/dep/acelite/ace/os_include/os_fcntl.h @@ -0,0 +1,106 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_fcntl.h + * + * file control options + * + * $Id: os_fcntl.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_FCNTL_H +#define ACE_OS_INCLUDE_OS_FCNTL_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_stat.h" +#include "ace/os_include/sys/os_types.h" + +#if !defined (ACE_LACKS_FCNTL_H) +# include /**/ +#endif /* !ACE_LACKS_FCNTL_H */ + +#if defined (ACE_VXWORKS) && (ACE_VXWORKS < 0x620) +// for creat(), open() +# include /**/ +#endif /* ACE_VXWORKS */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#if defined (__BORLANDC__) +# define _O_CREAT O_CREAT +# define _O_EXCL O_EXCL +# define _O_TRUNC O_TRUNC + // 0x0800 is used for O_APPEND. 0x08 looks free. +# define _O_TEMPORARY 0x08 /* see fcntl.h */ +# define _O_RDWR O_RDWR +# define _O_WRONLY O_WRONLY +# define _O_RDONLY O_RDONLY +# define _O_APPEND O_APPEND +# define _O_BINARY O_BINARY +# define _O_TEXT O_TEXT +#endif /* __BORLANDC__ */ + +#if defined (__DMC__) +# define _O_TEMPORARY 0x08 /* see fcntl.h */ +#endif /* __DMC__ */ + +// defined Win32 specific macros for UNIX platforms +#if !defined (O_BINARY) +# define O_BINARY 0 +#endif /* O_BINARY */ +#if !defined (_O_BINARY) +# define _O_BINARY O_BINARY +#endif /* _O_BINARY */ +#if !defined (O_TEXT) +# define O_TEXT 0 +#endif /* O_TEXT */ +#if !defined (_O_TEXT) +# define _O_TEXT O_TEXT +#endif /* _O_TEXT */ +#if !defined (O_RAW) +# define O_RAW 0 +#endif /* O_RAW */ +#if !defined (_O_RAW) +# define _O_RAW O_RAW +#endif /* _O_RAW */ + +#if defined (ACE_WIN32) +# define O_NDELAY 1 +#endif /* ACE_WIN32 */ + +# if !defined (O_NONBLOCK) +# define O_NONBLOCK 1 +# endif /* O_NONBLOCK */ + +#if defined (ACE_HAS_POSIX_NONBLOCK) +# define ACE_NONBLOCK O_NONBLOCK +#else +# define ACE_NONBLOCK O_NDELAY +#endif /* ACE_HAS_POSIX_NONBLOCK */ + +# if !defined (F_GETFL) +# define F_GETFL 0 +# endif /* F_GETFL */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_FCNTL_H */ diff --git a/dep/acelite/ace/os_include/os_fenv.h b/dep/acelite/ace/os_include/os_fenv.h new file mode 100644 index 00000000000..cbf5ab41100 --- /dev/null +++ b/dep/acelite/ace/os_include/os_fenv.h @@ -0,0 +1,42 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_fenv.h + * + * floating-point environment + * + * $Id: os_fenv.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_FENV_H +#define ACE_OS_INCLUDE_OS_FENV_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_FENV_H) +# include /**/ +#endif /* !ACE_LACKS_FENV_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_FENV_H */ diff --git a/dep/acelite/ace/os_include/os_float.h b/dep/acelite/ace/os_include/os_float.h new file mode 100644 index 00000000000..ac4b2f8f961 --- /dev/null +++ b/dep/acelite/ace/os_include/os_float.h @@ -0,0 +1,42 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_float.h + * + * floating types + * + * $Id: os_float.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_FLOAT_H +#define ACE_OS_INCLUDE_OS_FLOAT_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_FLOAT_H) +# include /**/ +#endif /* !ACE_LACKS_FLOAT_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_FLOAT_H */ diff --git a/dep/acelite/ace/os_include/os_fmtmsg.h b/dep/acelite/ace/os_include/os_fmtmsg.h new file mode 100644 index 00000000000..74251a950d6 --- /dev/null +++ b/dep/acelite/ace/os_include/os_fmtmsg.h @@ -0,0 +1,42 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_fmtmsg.h + * + * message display structures + * + * $Id: os_fmtmsg.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_FMTMSG_H +#define ACE_OS_INCLUDE_OS_FMTMSG_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_FMTMSG_H) +# include /**/ +#endif /* !ACE_LACKS_FMTMSG_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_FMTMSG_H */ diff --git a/dep/acelite/ace/os_include/os_fnmatch.h b/dep/acelite/ace/os_include/os_fnmatch.h new file mode 100644 index 00000000000..36726e293ae --- /dev/null +++ b/dep/acelite/ace/os_include/os_fnmatch.h @@ -0,0 +1,42 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_fnmatch.h + * + * filename-matching types + * + * $Id: os_fnmatch.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_FNMATCH_H +#define ACE_OS_INCLUDE_OS_FNMATCH_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_FNMATCH_H) +# include /**/ +#endif /* !ACE_LACKS_FNMATCH_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_FNMATCH_H */ diff --git a/dep/acelite/ace/os_include/os_ftw.h b/dep/acelite/ace/os_include/os_ftw.h new file mode 100644 index 00000000000..225d3251339 --- /dev/null +++ b/dep/acelite/ace/os_include/os_ftw.h @@ -0,0 +1,44 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_ftw.h + * + * file tree traversal + * + * $Id: os_ftw.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_FTW_H +#define ACE_OS_INCLUDE_OS_FTW_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_stat.h" + +#if !defined (ACE_LACKS_FTW_H) +# include /**/ +#endif /* !ACE_LACKS_FTW_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_FTW_H */ diff --git a/dep/acelite/ace/os_include/os_glob.h b/dep/acelite/ace/os_include/os_glob.h new file mode 100644 index 00000000000..0ced3a36234 --- /dev/null +++ b/dep/acelite/ace/os_include/os_glob.h @@ -0,0 +1,42 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_glob.h + * + * pathname pattern-matching types + * + * $Id: os_glob.h 81692 2008-05-14 12:25:02Z johnnyw $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_GLOB_H +#define ACE_OS_INCLUDE_OS_GLOB_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_GLOB_H) +# include /**/ +#endif /* !ACE_LACKS_GLOB_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_GLOB_H */ diff --git a/dep/acelite/ace/os_include/os_grp.h b/dep/acelite/ace/os_include/os_grp.h new file mode 100644 index 00000000000..74bb6e64737 --- /dev/null +++ b/dep/acelite/ace/os_include/os_grp.h @@ -0,0 +1,44 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_grp.h + * + * group structure + * + * $Id: os_grp.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_GRP_H +#define ACE_OS_INCLUDE_OS_GRP_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_types.h" // for gid_t + +#if !defined (ACE_LACKS_GRP_H) +# include /**/ +#endif /* !ACE_LACKS_GRP_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_GRP_H */ diff --git a/dep/acelite/ace/os_include/os_iconv.h b/dep/acelite/ace/os_include/os_iconv.h new file mode 100644 index 00000000000..33b061cd789 --- /dev/null +++ b/dep/acelite/ace/os_include/os_iconv.h @@ -0,0 +1,44 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_iconv.h + * + * codeset conversion facility + * + * $Id: os_iconv.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_ICONV_H +#define ACE_OS_INCLUDE_OS_ICONV_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_types.h" + +#if !defined (ACE_LACKS_ICONV_H) +# include /**/ +#endif /* !ACE_LACKS_ICONV_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_ICONV_H */ diff --git a/dep/acelite/ace/os_include/os_intrin.h b/dep/acelite/ace/os_include/os_intrin.h new file mode 100644 index 00000000000..37b669500e2 --- /dev/null +++ b/dep/acelite/ace/os_include/os_intrin.h @@ -0,0 +1,57 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_intrin.h + * + * Intrinsic methods + * + * $Id: os_intrin.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Johnny Willemsen + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_INTRIN_H +#define ACE_OS_INCLUDE_OS_INTRIN_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_INTRIN_H) +# include /**/ +#endif /* !ACE_HAS_INTRIN_H */ + +#if defined (ACE_HAS_IA64INTRIN_H) +# include /**/ +#endif /* !ACE_HAS_IA64INTRIN_H */ + +#if defined (ACE_HAS_IA32INTRIN_H) +# include /**/ +#endif /* !ACE_HAS_IA32INTRIN_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#if defined (_MSC_VER) && (_MSC_VER < 1400) && !(defined (__INTEL_COMPILER) && (__INTEL_COMPILER == 900)) +// See http://msdn2.microsoft.com/en-us/library/f24ya7ct(VS.71).aspx +LONG __cdecl _InterlockedIncrement (LONG volatile *Addend); +LONG __cdecl _InterlockedDecrement (LONG volatile *Addend); +LONG __cdecl _InterlockedExchange (LONG volatile *Target, LONG Value); +LONG __cdecl _InterlockedExchangeAdd (LONG volatile *Addend, LONG Value); +#endif //_MSC_VER + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_INTRIN_H */ diff --git a/dep/acelite/ace/os_include/os_inttypes.h b/dep/acelite/ace/os_include/os_inttypes.h new file mode 100644 index 00000000000..2f0c188699e --- /dev/null +++ b/dep/acelite/ace/os_include/os_inttypes.h @@ -0,0 +1,46 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_inttypes.h + * + * fixed size integer types + * + * $Id: os_inttypes.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_INTTYPES_H +#define ACE_OS_INCLUDE_OS_INTTYPES_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/os_stdint.h" + +#if !defined (ACE_LACKS_INTTYPES_H) +# include /**/ +#endif /* !ACE_LACKS_INTTYPES_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +// @todo if needbe, we can define the macros if they aren't available. + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_INTTYPES_H */ diff --git a/dep/acelite/ace/os_include/os_iso646.h b/dep/acelite/ace/os_include/os_iso646.h new file mode 100644 index 00000000000..0c5ab2ae4aa --- /dev/null +++ b/dep/acelite/ace/os_include/os_iso646.h @@ -0,0 +1,42 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_iso646.h + * + * alternative spellings + * + * $Id: os_iso646.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_ISO646_H +#define ACE_OS_INCLUDE_OS_ISO646_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_ISO646_H) +# include /**/ +#endif /* !ACE_LACKS_ISO646_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_ISO646_H */ diff --git a/dep/acelite/ace/os_include/os_kstat.h b/dep/acelite/ace/os_include/os_kstat.h new file mode 100644 index 00000000000..31836cd27d0 --- /dev/null +++ b/dep/acelite/ace/os_include/os_kstat.h @@ -0,0 +1,43 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_kstat.h + * + * $Id: os_kstat.h 81692 2008-05-14 12:25:02Z johnnyw $ + * + * @author Johnny Willemsen + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_KSTAT_H +#define ACE_OS_INCLUDE_OS_KSTAT_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_KSTAT) +# define ACE_HAS_KSTAT_H +#endif /* ACE_HAS_KSTAT */ + +#if defined (ACE_HAS_KSTAT_H) +# include +#endif /* ACE_HAS_KSTAT_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_KSTAT_H */ diff --git a/dep/acelite/ace/os_include/os_langinfo.h b/dep/acelite/ace/os_include/os_langinfo.h new file mode 100644 index 00000000000..bfcd67cc2dc --- /dev/null +++ b/dep/acelite/ace/os_include/os_langinfo.h @@ -0,0 +1,44 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_langinfo.h + * + * language information constants + * + * $Id: os_langinfo.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_LANGINFO_H +#define ACE_OS_INCLUDE_OS_LANGINFO_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/os_nl_types.h" + +#if !defined (ACE_LACKS_LANGINFO_H) +# include /**/ +#endif /* !ACE_LACKS_LANGINFO_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_LANGINFO_H */ diff --git a/dep/acelite/ace/os_include/os_libgen.h b/dep/acelite/ace/os_include/os_libgen.h new file mode 100644 index 00000000000..ca24a4d7f9b --- /dev/null +++ b/dep/acelite/ace/os_include/os_libgen.h @@ -0,0 +1,42 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_libgen.h + * + * definitions for pattern matching functions + * + * $Id: os_libgen.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_LIBGEN_H +#define ACE_OS_INCLUDE_OS_LIBGEN_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_LIBGEN_H) +# include /**/ +#endif /* !ACE_LACKS_LIBGEN_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_LIBGEN_H */ diff --git a/dep/acelite/ace/os_include/os_limits.h b/dep/acelite/ace/os_include/os_limits.h new file mode 100644 index 00000000000..a128efcc060 --- /dev/null +++ b/dep/acelite/ace/os_include/os_limits.h @@ -0,0 +1,143 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_limits.h + * + * implementation-defined constants + * + * $Id: os_limits.h 84972 2009-03-25 19:09:06Z johnnyw $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_LIMITS_H +#define ACE_OS_INCLUDE_OS_LIMITS_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/os_unistd.h" +#include "ace/os_include/os_stdio.h" // for FILENAME_MAX on Windows + +#if !defined (ACE_LACKS_LIMITS_H) +# include /**/ +#endif /* !ACE_LACKS_LIMITS_H */ + +#if !defined (ACE_LACKS_SYS_PARAM_H) +# include /**/ +#endif /* ACE_LACKS_SYS_PARAM_H */ + +// On VxWorks 5.5.1 _POSIX_TIMER_MAX is defined in time.h +#if defined (ACE_VXWORKS) && (ACE_VXWORKS < 0x620) +# include /**/ +#endif /* ACE_VXWORKS */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#if ! defined (howmany) +# define howmany(x, y) (((x)+((y)-1))/(y)) +#endif /* howmany */ + +#if !defined (NAME_MAX) +# if defined (MAXNAMLEN) +# define NAME_MAX MAXNAMLEN +# elif defined (MAXNAMELEN) +# define NAME_MAX MAXNAMELEN +# elif defined (FILENAME_MAX) +# define NAME_MAX FILENAME_MAX +# elif defined (_MAX_FNAME) +# define NAME_MAX _MAX_FNAME +# else /* _MAX_FNAME */ +# define NAME_MAX 256 +# endif /* MAXNAMLEN */ +#endif /* !NAME_MAX */ + +#if !defined (MAXNAMELEN) +# define MAXNAMELEN NAME_MAX +#endif /* MAXNAMELEN */ + +#if !defined (HOST_NAME_MAX) +# define HOST_NAME_MAX 256 +#endif /* !HOST_NAME_MAX */ + +// Note that we are using PATH_MAX instead of _POSIX_PATH_MAX, since +// _POSIX_PATH_MAX is the *minimun* maximum value for PATH_MAX and is +// defined by POSIX as 256. +#if !defined (PATH_MAX) +# if defined (_MAX_PATH) +# define PATH_MAX _MAX_PATH +# elif defined (MAX_PATH) +# define PATH_MAX MAX_PATH +# else /* !_MAX_PATH */ +# define PATH_MAX 1024 +# endif /* _MAX_PATH */ +#endif /* !PATH_MAX */ + +// Leaving this for backward compatibility, but PATH_MAX should always be +// used directly. +#if !defined (MAXPATHLEN) +# define MAXPATHLEN PATH_MAX +#endif /* !MAXPATHLEN */ + +// This is defined by XOPEN to be a minimum of 16. POSIX.1g +// also defines this value. platform-specific config.h can +// override this if need be. +#if !defined (IOV_MAX) +# define IOV_MAX 16 +#endif /* IOV_MAX */ + +#if !defined (ACE_IOV_MAX) +# define ACE_IOV_MAX IOV_MAX +#endif /* ACE_IOV_MAX */ + +#if defined (ACE_VXWORKS) && ((ACE_VXWORKS >= 0x620) && (ACE_VXWORKS <= 0x670)) && !defined (__RTP__) +# if defined (PIPE_BUF) && (PIPE_BUF == -1) +# undef PIPE_BUF +# endif +#endif /* ACE_VXWORKS */ + +#if !defined (PIPE_BUF) +# define PIPE_BUF 5120 +#endif /* PIPE_BUF */ + +#if defined (ACE_HAS_POSIX_REALTIME_SIGNALS) + // = Giving unique ACE scoped names for some important + // RTSignal-Related constants. Becuase sometimes, different + // platforms use different names for these constants. + + // Number of realtime signals provided in the system. + // _POSIX_RTSIG_MAX is the upper limit on the number of real time + // signals supported in a posix-4 compliant system. +# if defined (_POSIX_RTSIG_MAX) +# define ACE_RTSIG_MAX _POSIX_RTSIG_MAX +# else /* not _POSIX_RTSIG_MAX */ + // POSIX-4 compilant system has to provide atleast 8 RT signals. + // @@ Make sure the platform does *not* define this constant with + // some other name. If yes, use that instead of 8. +# define ACE_RTSIG_MAX 8 +# endif /* _POSIX_RTSIG_MAX */ +#endif /* ACE_HAS_POSIX_REALTIME_SIGNALS */ + + // The maximum number of concurrent timers per process. +# if !defined (_POSIX_TIMER_MAX) +# define _POSIX_TIMER_MAX 44 +# endif /* _POSIX_TIMER_MAX */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_LIMITS_H */ diff --git a/dep/acelite/ace/os_include/os_local.h b/dep/acelite/ace/os_include/os_local.h new file mode 100644 index 00000000000..b5752f9ab95 --- /dev/null +++ b/dep/acelite/ace/os_include/os_local.h @@ -0,0 +1,44 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_local.h + * + * category macros + * + * $Id: os_local.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_LOCAL_H +#define ACE_OS_INCLUDE_OS_LOCAL_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/os_stddef.h" + +#if !defined (ACE_LACKS_LOCAL_H) +# include /**/ +#endif /* !ACE_LACKS_LOCAL_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_LOCAL_H */ diff --git a/dep/acelite/ace/os_include/os_math.h b/dep/acelite/ace/os_include/os_math.h new file mode 100644 index 00000000000..6fb53cb1576 --- /dev/null +++ b/dep/acelite/ace/os_include/os_math.h @@ -0,0 +1,44 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_math.h + * + * mathematical declarations + * + * $Id: os_math.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_MATH_H +#define ACE_OS_INCLUDE_OS_MATH_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +// FUZZ: disable check_for_math_include + +#if !defined (ACE_LACKS_MATH_H) +# include /**/ +#endif /* !ACE_LACKS_MATH_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_MATH_H */ diff --git a/dep/acelite/ace/os_include/os_monetary.h b/dep/acelite/ace/os_include/os_monetary.h new file mode 100644 index 00000000000..6e956885ad6 --- /dev/null +++ b/dep/acelite/ace/os_include/os_monetary.h @@ -0,0 +1,44 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_monetary.h + * + * monetary types + * + * $Id: os_monetary.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_MONETARY_H +#define ACE_OS_INCLUDE_OS_MONETARY_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_types.h" + +#if !defined (ACE_LACKS_MONETARY_H) +# include /**/ +#endif /* !ACE_LACKS_MONETARY_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_MONETARY_H */ diff --git a/dep/acelite/ace/os_include/os_mqueue.h b/dep/acelite/ace/os_include/os_mqueue.h new file mode 100644 index 00000000000..7b3cbb9209a --- /dev/null +++ b/dep/acelite/ace/os_include/os_mqueue.h @@ -0,0 +1,44 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_mqueue.h + * + * message queues (REALTIME) + * + * $Id: os_mqueue.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_MQUEUE_H +#define ACE_OS_INCLUDE_OS_MQUEUE_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/os_signal.h" + +#if !defined (ACE_LACKS_MQUEUE_H) +# include /**/ +#endif /* !ACE_LACKS_MQUEUE_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_MQUEUE_H */ diff --git a/dep/acelite/ace/os_include/os_ndbm.h b/dep/acelite/ace/os_include/os_ndbm.h new file mode 100644 index 00000000000..042dcebf2ff --- /dev/null +++ b/dep/acelite/ace/os_include/os_ndbm.h @@ -0,0 +1,44 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_ndbm.h + * + * definitions for ndbm database operations + * + * $Id: os_ndbm.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_NDBM_H +#define ACE_OS_INCLUDE_OS_NDBM_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_types.h" + +#if !defined (ACE_LACKS_NDBM_H) +# include /**/ +#endif /* !ACE_LACKS_NDBM_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_NDBM_H */ diff --git a/dep/acelite/ace/os_include/os_netdb.h b/dep/acelite/ace/os_include/os_netdb.h new file mode 100644 index 00000000000..798bf9b7a2b --- /dev/null +++ b/dep/acelite/ace/os_include/os_netdb.h @@ -0,0 +1,100 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_netdb.h + * + * definitions for network database operations + * + * $Id: os_netdb.h 84660 2009-03-01 20:22:37Z olli $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_NETDB_H +#define ACE_OS_INCLUDE_OS_NETDB_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/netinet/os_in.h" +#include "ace/os_include/os_limits.h" + +#if defined (ACE_VXWORKS) && (ACE_VXWORKS < 0x620) +# include /**/ +#endif /* ACE_VXWORKS */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#if !defined (ACE_LACKS_NETDB_H) +# include /**/ +#endif /* !ACE_LACKS_NETDB_H */ + +#if defined (ACE_LACKS_HOSTENT) +struct hostent { + char *h_name; /* official name of host */ + char **h_aliases; /* alias list */ + int h_addrtype; /* host address type */ + int h_length; /* length of address */ + char **h_addr_list; /* list of addresses from name server */ +#define h_addr h_addr_list[0] /* address, for backward compatibility */ +}; +#endif /* ACE_LACKS_HOSTENT */ + +#if defined (ACE_LACKS_PROTOENT) +struct protoent { + char *p_name; /* official protocol name */ + char **p_aliases; /* alias list */ + int p_proto; /* protocol # */ +}; +#endif /* ACE_LACKS_PROTOENT */ + +#if defined (ACE_LACKS_SERVENT) +struct servent { + char *s_name; /* official service name */ + char **s_aliases; /* alias list */ + int s_port; /* port # */ + char *s_proto; /* protocol to use */ +}; +#endif /* ACE_LACKS_SERVENT */ + +#if defined (ACE_HAS_STRUCT_NETDB_DATA) + typedef char ACE_HOSTENT_DATA[sizeof(struct hostent_data)]; + typedef char ACE_SERVENT_DATA[sizeof(struct servent_data)]; + typedef char ACE_PROTOENT_DATA[sizeof(struct protoent_data)]; +#else +# if !defined ACE_HOSTENT_DATA_SIZE +# define ACE_HOSTENT_DATA_SIZE (4*1024) +# endif /*ACE_HOSTENT_DATA_SIZE */ +# if !defined ACE_SERVENT_DATA_SIZE +# define ACE_SERVENT_DATA_SIZE (4*1024) +# endif /*ACE_SERVENT_DATA_SIZE */ +# if !defined ACE_PROTOENT_DATA_SIZE +# define ACE_PROTOENT_DATA_SIZE (2*1024) +# endif /*ACE_PROTOENT_DATA_SIZE */ + typedef char ACE_HOSTENT_DATA[ACE_HOSTENT_DATA_SIZE]; + typedef char ACE_SERVENT_DATA[ACE_SERVENT_DATA_SIZE]; + typedef char ACE_PROTOENT_DATA[ACE_PROTOENT_DATA_SIZE]; +#endif /* ACE_HAS_STRUCT_NETDB_DATA */ + +# if !defined(MAXHOSTNAMELEN) +# define MAXHOSTNAMELEN HOST_NAME_MAX +# endif /* MAXHOSTNAMELEN */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_NETDB_H */ diff --git a/dep/acelite/ace/os_include/os_nl_types.h b/dep/acelite/ace/os_include/os_nl_types.h new file mode 100644 index 00000000000..e043f6ae6d3 --- /dev/null +++ b/dep/acelite/ace/os_include/os_nl_types.h @@ -0,0 +1,42 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_nl_types.h + * + * data types + * + * $Id: os_nl_types.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_NL_TYPES_H +#define ACE_OS_INCLUDE_OS_NL_TYPES_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_NL_TYPES_H) +# include /**/ +#endif /* !ACE_LACKS_nl_types_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_NL_TYPES_H */ diff --git a/dep/acelite/ace/os_include/os_pdh.h b/dep/acelite/ace/os_include/os_pdh.h new file mode 100644 index 00000000000..5c60c60d10e --- /dev/null +++ b/dep/acelite/ace/os_include/os_pdh.h @@ -0,0 +1,45 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_pdh.h + * + * definitions for the windows pdh API + * + * $Id: os_pdh.h 81614 2008-05-05 14:04:25Z johnnyw $ + * + * @author Johnny Willemsen + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_PDH_H +#define ACE_OS_INCLUDE_OS_PDH_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_PDH_H) && !defined (ACE_LACKS_PDH_H) +# include /**/ +#endif /* ACE_HAS_PDH_H && !ACE_LACKS_PDH_H */ + +#if defined (ACE_HAS_PDH_H) && !defined (ACE_LACKS_PDH_H) +# define ACE_HAS_WIN32_PDH +#endif + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_PDH_H */ diff --git a/dep/acelite/ace/os_include/os_pdhmsg.h b/dep/acelite/ace/os_include/os_pdhmsg.h new file mode 100644 index 00000000000..2156236e07c --- /dev/null +++ b/dep/acelite/ace/os_include/os_pdhmsg.h @@ -0,0 +1,41 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_pdhmsg.h + * + * definitions for the windows pdh API + * + * $Id: os_pdhmsg.h 81693 2008-05-14 12:35:01Z johnnyw $ + * + * @author Johnny Willemsen + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_PDHMSG_H +#define ACE_OS_INCLUDE_OS_PDHMSG_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_PDHMSG_H) && !defined (ACE_LACKS_PDHMSG_H) +# include /**/ +#endif /* ACE_HAS_PDH_H && !ACE_LACKS_PDH_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_PDHMSG_H */ diff --git a/dep/acelite/ace/os_include/os_poll.h b/dep/acelite/ace/os_include/os_poll.h new file mode 100644 index 00000000000..646c1bb853c --- /dev/null +++ b/dep/acelite/ace/os_include/os_poll.h @@ -0,0 +1,42 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_poll.h + * + * definitions for the poll() function + * + * $Id: os_poll.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_POLL_H +#define ACE_OS_INCLUDE_OS_POLL_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_POLL_H) +# include /**/ +#endif /* !ACE_LACKS_POLL_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_POLL_H */ diff --git a/dep/acelite/ace/os_include/os_pthread.h b/dep/acelite/ace/os_include/os_pthread.h new file mode 100644 index 00000000000..368f4254a34 --- /dev/null +++ b/dep/acelite/ace/os_include/os_pthread.h @@ -0,0 +1,424 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_pthread.h + * + * threads + * + * $Id: os_pthread.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_PTHREAD_H +#define ACE_OS_INCLUDE_OS_PTHREAD_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_PRIOCNTL) + // Need to #include thread.h before #defining THR_BOUND, etc., + // when building without threads on SunOS 5.x. +# if defined (sun) +# include /**/ +# endif /* sun */ + + // Need to #include these before #defining USYNC_PROCESS on SunOS 5.x. +# include /**/ +# include /**/ +#endif /* ACE_HAS_PRIOCNTL */ + +#include "ace/os_include/sys/os_types.h" + +// This needs to go here *first* to avoid problems with AIX. +# if defined (ACE_HAS_PTHREADS) +# define ACE_DONT_INCLUDE_ACE_SIGNAL_H +# include "ace/os_include/os_signal.h" +# undef ACE_DONT_INCLUDE_ACE_SIGNAL_H +# if defined (DIGITAL_UNIX) +# define pthread_self __pthread_self +extern "C" pthread_t pthread_self (void); +# endif /* DIGITAL_UNIX */ +# endif /* ACE_HAS_PTHREADS */ + + +#if !defined (ACE_LACKS_PTHREAD_H) + extern "C" { +# if defined (ACE_TANDEM_T1248_PTHREADS) +# include /**/ +# else +# include /**/ +# endif + } +#endif /* !ACE_LACKS_PTHREAD_H */ + +#if defined (ACE_HAS_PTHREAD_NP_H) +// FreeBSD declares _np (non-portable) pthread extensions in +# include /**/ +#endif + +// @todo: need to reoganize to put includes at the top and the rest of the +// code at the bottom. Also, move the classes out of this file. +#if defined (ACE_HAS_PTHREADS) +# define ACE_SCHED_OTHER SCHED_OTHER +# define ACE_SCHED_FIFO SCHED_FIFO +# define ACE_SCHED_RR SCHED_RR + +// Definitions for THREAD- and PROCESS-LEVEL priorities...some +// implementations define these while others don't. In order to +// further complicate matters, we don't redefine the default (*_DEF) +// values if they've already been defined, which allows individual +// programs to have their own ACE-wide "default". + +// PROCESS-level values +# if (defined (_POSIX_PRIORITY_SCHEDULING) || defined (ACE_TANDEM_T1248_PTHREADS)) \ + && !defined(_UNICOS) && !defined(UNIXWARE_7_1) +# define ACE_PROC_PRI_FIFO_MIN (sched_get_priority_min(SCHED_FIFO)) +# define ACE_PROC_PRI_RR_MIN (sched_get_priority_min(SCHED_RR)) +# if defined (HPUX) + // HP-UX's other is the SCHED_HPUX class, which uses historical + // values that have reverse semantics from POSIX (low value is + // more important priority). To use these in pthreads calls, + // the values need to be converted. The other scheduling classes + // don't need this special treatment. +# define ACE_PROC_PRI_OTHER_MIN \ + (sched_get_priority_min(SCHED_OTHER)) +# else +# define ACE_PROC_PRI_OTHER_MIN (sched_get_priority_min(SCHED_OTHER)) +# endif /* HPUX */ +# else /* UNICOS is missing a sched_get_priority_min() implementation, + SCO too */ +# define ACE_PROC_PRI_FIFO_MIN 0 +# define ACE_PROC_PRI_RR_MIN 0 +# define ACE_PROC_PRI_OTHER_MIN 0 +# endif + +# if defined (_POSIX_PRIORITY_SCHEDULING) && !defined(UNIXWARE_7_1) +# define ACE_PROC_PRI_FIFO_MAX (sched_get_priority_max(SCHED_FIFO)) +# define ACE_PROC_PRI_RR_MAX (sched_get_priority_max(SCHED_RR)) +# if defined (HPUX) +# define ACE_PROC_PRI_OTHER_MAX \ + (sched_get_priority_max(SCHED_OTHER)) +# else +# define ACE_PROC_PRI_OTHER_MAX (sched_get_priority_max(SCHED_OTHER)) +# endif /* HPUX */ +# else /* SCO missing sched_get_priority_max() implementation */ +# define ACE_PROC_PRI_FIFO_MAX 59 +# define ACE_PROC_PRI_RR_MAX 59 +# define ACE_PROC_PRI_OTHER_MAX 59 +# endif + +# if !defined(ACE_PROC_PRI_FIFO_DEF) +# define ACE_PROC_PRI_FIFO_DEF (ACE_PROC_PRI_FIFO_MIN + (ACE_PROC_PRI_FIFO_MAX - ACE_PROC_PRI_FIFO_MIN)/2) +# endif +# if !defined(ACE_PROC_PRI_RR_DEF) +# define ACE_PROC_PRI_RR_DEF (ACE_PROC_PRI_RR_MIN + (ACE_PROC_PRI_RR_MAX - ACE_PROC_PRI_RR_MIN)/2) +# endif +# if !defined(ACE_PROC_PRI_OTHER_DEF) +# define ACE_PROC_PRI_OTHER_DEF (ACE_PROC_PRI_OTHER_MIN + (ACE_PROC_PRI_OTHER_MAX - ACE_PROC_PRI_OTHER_MIN)/2) +# endif + +// THREAD-level values +# if defined(PRI_FIFO_MIN) && defined(PRI_FIFO_MAX) && defined(PRI_RR_MIN) && defined(PRI_RR_MAX) && defined(PRI_OTHER_MIN) && defined(PRI_OTHER_MAX) +# if !defined (ACE_THR_PRI_FIFO_MIN) +# define ACE_THR_PRI_FIFO_MIN (long) PRI_FIFO_MIN +# endif /* !ACE_THR_PRI_FIFO_MIN */ +# if !defined (ACE_THR_PRI_FIFO_MAX) +# define ACE_THR_PRI_FIFO_MAX (long) PRI_FIFO_MAX +# endif /* !ACE_THR_PRI_FIFO_MAX */ +# if !defined (ACE_THR_PRI_RR_MIN) +# define ACE_THR_PRI_RR_MIN (long) PRI_RR_MIN +# endif /* !ACE_THR_PRI_RR_MIN */ +# if !defined (ACE_THR_PRI_RR_MAX) +# define ACE_THR_PRI_RR_MAX (long) PRI_RR_MAX +# endif /* !ACE_THR_PRI_RR_MAX */ +# if !defined (ACE_THR_PRI_OTHER_MIN) +# define ACE_THR_PRI_OTHER_MIN (long) PRI_OTHER_MIN +# endif /* !ACE_THR_PRI_OTHER_MIN */ +# if !defined (ACE_THR_PRI_OTHER_MAX) +# define ACE_THR_PRI_OTHER_MAX (long) PRI_OTHER_MAX +# endif /* !ACE_THR_PRI_OTHER_MAX */ +# elif defined (AIX) + // AIX's priority range is 1 (low) to 127 (high). There aren't + // any preprocessor macros I can find. PRIORITY_MIN is for + // process priorities, as far as I can see, and does not apply + // to thread priority. The 1 to 127 range is from the + // pthread_attr_setschedparam man page (Steve Huston, 18-May-2001). +# if !defined (ACE_THR_PRI_FIFO_MIN) +# define ACE_THR_PRI_FIFO_MIN (long) 1 +# endif /* !ACE_THR_PRI_FIFO_MIN */ +# if !defined (ACE_THR_PRI_FIFO_MAX) +# define ACE_THR_PRI_FIFO_MAX (long) 127 +# endif /* !ACE_THR_PRI_FIFO_MAX */ +# if !defined (ACE_THR_PRI_RR_MIN) +# define ACE_THR_PRI_RR_MIN (long) 1 +# endif /* !ACE_THR_PRI_RR_MIN */ +# if !defined (ACE_THR_PRI_RR_MAX) +# define ACE_THR_PRI_RR_MAX (long) 127 +# endif /* !ACE_THR_PRI_RR_MAX */ +# if !defined (ACE_THR_PRI_OTHER_MIN) +# define ACE_THR_PRI_OTHER_MIN (long) 1 +# endif /* !ACE_THR_PRI_OTHER_MIN */ +# if !defined (ACE_THR_PRI_OTHER_MAX) +# define ACE_THR_PRI_OTHER_MAX (long) 127 +# endif /* !ACE_THR_PRI_OTHER_MAX */ +# elif defined (sun) +# if !defined (ACE_THR_PRI_FIFO_MIN) +# define ACE_THR_PRI_FIFO_MIN (long) 0 +# endif /* !ACE_THR_PRI_FIFO_MIN */ +# if !defined (ACE_THR_PRI_FIFO_MAX) +# define ACE_THR_PRI_FIFO_MAX (long) 59 +# endif /* !ACE_THR_PRI_FIFO_MAX */ +# if !defined (ACE_THR_PRI_RR_MIN) +# define ACE_THR_PRI_RR_MIN (long) 0 +# endif /* !ACE_THR_PRI_RR_MIN */ +# if !defined (ACE_THR_PRI_RR_MAX) +# define ACE_THR_PRI_RR_MAX (long) 59 +# endif /* !ACE_THR_PRI_RR_MAX */ +# if !defined (ACE_THR_PRI_OTHER_MIN) +# define ACE_THR_PRI_OTHER_MIN (long) 0 +# endif /* !ACE_THR_PRI_OTHER_MIN */ +# if !defined (ACE_THR_PRI_OTHER_MAX) +# define ACE_THR_PRI_OTHER_MAX (long) 127 +# endif /* !ACE_THR_PRI_OTHER_MAX */ +# else +# if !defined (ACE_THR_PRI_FIFO_MIN) +# define ACE_THR_PRI_FIFO_MIN (long) ACE_PROC_PRI_FIFO_MIN +# endif /* !ACE_THR_PRI_FIFO_MIN */ +# if !defined (ACE_THR_PRI_FIFO_MAX) +# define ACE_THR_PRI_FIFO_MAX (long) ACE_PROC_PRI_FIFO_MAX +# endif /* !ACE_THR_PRI_FIFO_MAX */ +# if !defined (ACE_THR_PRI_RR_MIN) +# define ACE_THR_PRI_RR_MIN (long) ACE_PROC_PRI_RR_MIN +# endif /* !ACE_THR_PRI_RR_MIN */ +# if !defined (ACE_THR_PRI_RR_MAX) +# define ACE_THR_PRI_RR_MAX (long) ACE_PROC_PRI_RR_MAX +# endif /* !ACE_THR_PRI_RR_MAX */ +# if !defined (ACE_THR_PRI_OTHER_MIN) +# define ACE_THR_PRI_OTHER_MIN (long) ACE_PROC_PRI_OTHER_MIN +# endif /* !ACE_THR_PRI_OTHER_MIN */ +# if !defined (ACE_THR_PRI_OTHER_MAX) +# define ACE_THR_PRI_OTHER_MAX (long) ACE_PROC_PRI_OTHER_MAX +# endif /* !ACE_THR_PRI_OTHER_MAX */ +# endif +# if !defined(ACE_THR_PRI_FIFO_DEF) +# define ACE_THR_PRI_FIFO_DEF ((ACE_THR_PRI_FIFO_MIN + ACE_THR_PRI_FIFO_MAX)/2) +# endif +# if !defined(ACE_THR_PRI_RR_DEF) +# define ACE_THR_PRI_RR_DEF ((ACE_THR_PRI_RR_MIN + ACE_THR_PRI_RR_MAX)/2) +# endif +# if !defined(ACE_THR_PRI_OTHER_DEF) +# define ACE_THR_PRI_OTHER_DEF ((ACE_THR_PRI_OTHER_MIN + ACE_THR_PRI_OTHER_MAX)/2) +# endif + // Typedefs to help compatibility with Windows NT and Pthreads. + typedef pthread_t ACE_hthread_t; + typedef pthread_t ACE_thread_t; + + // native TSS key type + typedef pthread_key_t ACE_OS_thread_key_t; + // TSS key type to be used by application +# if defined (ACE_HAS_TSS_EMULATION) + typedef u_int ACE_thread_key_t; +# else /* ! ACE_HAS_TSS_EMULATION */ + typedef ACE_OS_thread_key_t ACE_thread_key_t; +# endif /* ! ACE_HAS_TSS_EMULATION */ + +# if !defined (ACE_LACKS_COND_T) + typedef pthread_mutex_t ACE_mutex_t; + typedef pthread_cond_t ACE_cond_t; + typedef pthread_condattr_t ACE_condattr_t; + typedef pthread_mutexattr_t ACE_mutexattr_t; +# endif /* ! ACE_LACKS_COND_T */ + typedef pthread_mutex_t ACE_thread_mutex_t; + +# if !defined (PTHREAD_CANCEL_DISABLE) +# define PTHREAD_CANCEL_DISABLE 0 +# endif /* PTHREAD_CANCEL_DISABLE */ + +# if !defined (PTHREAD_CANCEL_ENABLE) +# define PTHREAD_CANCEL_ENABLE 0 +# endif /* PTHREAD_CANCEL_ENABLE */ + +# if !defined (PTHREAD_CANCEL_DEFERRED) +# define PTHREAD_CANCEL_DEFERRED 0 +# endif /* PTHREAD_CANCEL_DEFERRED */ + +# if !defined (PTHREAD_CANCEL_ASYNCHRONOUS) +# define PTHREAD_CANCEL_ASYNCHRONOUS 0 +# endif /* PTHREAD_CANCEL_ASYNCHRONOUS */ + +# define THR_CANCEL_DISABLE PTHREAD_CANCEL_DISABLE +# define THR_CANCEL_ENABLE PTHREAD_CANCEL_ENABLE +# define THR_CANCEL_DEFERRED PTHREAD_CANCEL_DEFERRED +# define THR_CANCEL_ASYNCHRONOUS PTHREAD_CANCEL_ASYNCHRONOUS + +# if !defined (PTHREAD_CREATE_JOINABLE) +# if defined (PTHREAD_CREATE_UNDETACHED) +# define PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED +# else +# define PTHREAD_CREATE_JOINABLE 0 +# endif /* PTHREAD_CREATE_UNDETACHED */ +# endif /* PTHREAD_CREATE_JOINABLE */ + +# if !defined (PTHREAD_CREATE_DETACHED) +# define PTHREAD_CREATE_DETACHED 1 +# endif /* PTHREAD_CREATE_DETACHED */ + +# if !defined (PTHREAD_PROCESS_PRIVATE) && !defined (ACE_HAS_PTHREAD_PROCESS_ENUM) +# if defined (PTHREAD_MUTEXTYPE_FAST) +# define PTHREAD_PROCESS_PRIVATE PTHREAD_MUTEXTYPE_FAST +# else +# define PTHREAD_PROCESS_PRIVATE 0 +# endif /* PTHREAD_MUTEXTYPE_FAST */ +# endif /* PTHREAD_PROCESS_PRIVATE */ + +# if !defined (PTHREAD_PROCESS_SHARED) && !defined (ACE_HAS_PTHREAD_PROCESS_ENUM) +# if defined (PTHREAD_MUTEXTYPE_FAST) +# define PTHREAD_PROCESS_SHARED PTHREAD_MUTEXTYPE_FAST +# else +# define PTHREAD_PROCESS_SHARED 1 +# endif /* PTHREAD_MUTEXTYPE_FAST */ +# endif /* PTHREAD_PROCESS_SHARED */ + +# if !defined (ACE_HAS_STHREADS) +# if !defined (USYNC_THREAD) +# define USYNC_THREAD PTHREAD_PROCESS_PRIVATE +# endif /* ! USYNC_THREAD */ +# if !defined (USYNC_PROCESS) +# define USYNC_PROCESS PTHREAD_PROCESS_SHARED +# endif /* ! USYNC_PROCESS */ +# endif /* ACE_HAS_STHREADS */ + + /* MM-Graz: prevent warnings */ +# if !defined (UNIXWARE_7_1) +# undef THR_BOUND +# undef THR_NEW_LWP +# undef THR_DETACHED +# undef THR_SUSPENDED +# undef THR_DAEMON + +# define THR_BOUND 0x00000001 +# define THR_NEW_LWP 0x00000002 +# define THR_DETACHED 0x00000040 +# define THR_SUSPENDED 0x00000080 +# define THR_DAEMON 0x00000100 +# define THR_SCHED_FIFO 0x00020000 +# define THR_SCHED_RR 0x00040000 +# define THR_SCHED_DEFAULT 0x00080000 +# endif /* UNIXWARE_7_1 */ + +# define THR_JOINABLE 0x00010000 + +# if defined (ACE_HAS_IRIX62_THREADS) +# define THR_SCOPE_SYSTEM 0x00100000 +# else +# define THR_SCOPE_SYSTEM THR_BOUND +# endif /*ACE_HAS_IRIX62_THREADS*/ + +# define THR_SCOPE_PROCESS 0x00200000 +# define THR_INHERIT_SCHED 0x00400000 +# define THR_EXPLICIT_SCHED 0x00800000 +# define THR_SCHED_IO 0x01000000 + +# if !defined (ACE_HAS_STHREADS) +# if !defined (ACE_HAS_POSIX_SEM) && !defined (ACE_USES_FIFO_SEM) + +// This needs to be moved out of here. +#include /**/ "ace/ACE_export.h" +/** + * @class ACE_sema_t + * + * @brief This is used to implement semaphores for platforms that support + * POSIX pthreads, but do *not* support POSIX semaphores, i.e., + * it's a different type than the POSIX . + */ +class ACE_Export ACE_sema_t +{ +public: + /// Serialize access to internal state. + ACE_mutex_t lock_; + + /// Block until there are no waiters. + ACE_cond_t count_nonzero_; + + /// Count of the semaphore. + u_long count_; + + /// Number of threads that have called . + u_long waiters_; +}; +# endif /* !ACE_HAS_POSIX_SEM */ + +# if defined (ACE_LACKS_PTHREAD_YIELD) && defined (ACE_HAS_THR_YIELD) + // If we are on Solaris we can just reuse the existing + // implementations of these synchronization types. +# if !defined (ACE_LACKS_RWLOCK_T) && !defined (ACE_HAS_PTHREADS_UNIX98_EXT) +# include /**/ + typedef rwlock_t ACE_rwlock_t; +# endif /* !ACE_LACKS_RWLOCK_T */ +# include /**/ +# endif /* (ACE_LACKS_PTHREAD_YIELD) && defined (ACE_HAS_THR_YIELD) */ + +# else +# if !defined (ACE_HAS_POSIX_SEM) + typedef sema_t ACE_sema_t; +# endif /* !ACE_HAS_POSIX_SEM */ +# endif /* !ACE_HAS_STHREADS */ + +# if defined (ACE_HAS_PTHREADS_UNIX98_EXT) + typedef pthread_rwlock_t ACE_rwlock_t; +# endif /* ACE_HAS_PTHREADS_UNIX98_EXT */ + +# if defined (__GLIBC__) && ((__GLIBC__ > 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2)) + + // glibc 2.2.x or better has pthread_mutex_timedlock() +# ifndef ACE_HAS_MUTEX_TIMEOUTS +# define ACE_HAS_MUTEX_TIMEOUTS +# endif /* ACE_HAS_MUTEX_TIMEOUTS */ + + // Use new pthread_attr_setstack if XPG6 support is enabled. +# if defined (_XOPEN_SOURCE) && (_XOPEN_SOURCE - 0) < 600 +# define ACE_LACKS_PTHREAD_ATTR_SETSTACK +# endif /* (_XOPEN_SOURCE - 0) < 600 */ + +# if !defined (_XOPEN_SOURCE) \ + || (defined (_XOPEN_SOURCE) && (_XOPEN_SOURCE - 0) < 600) + // pthread_mutex_timedlock() prototype is not visible if _XOPEN_SOURCE + // is not >= 600 (i.e. for XPG6). + extern "C" int pthread_mutex_timedlock (pthread_mutex_t *mutex, + const struct timespec * abstime); +# endif /* _XOPEN_SOURCE && _XOPEN_SOURCE < 600 */ + +# endif /* linux && ((__GLIBC__ > 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2)) */ + +#elif defined (ACE_HAS_STHREADS) +# if !defined (ACE_THR_PRI_FIFO_MIN) +# define ACE_THR_PRI_FIFO_MIN (long) 0 +# endif /* !ACE_THR_PRI_FIFO_MIN */ +# if !defined (ACE_THR_PRI_FIFO_MAX) +# define ACE_THR_PRI_FIFO_MAX (long) 59 +# endif /* !ACE_THR_PRI_FIFO_MAX */ +# if !defined (ACE_THR_PRI_RR_MIN) +# define ACE_THR_PRI_RR_MIN (long) 0 +# endif /* !ACE_THR_PRI_RR_MIN */ +# if !defined (ACE_THR_PRI_RR_MAX) +# define ACE_THR_PRI_RR_MAX (long) 59 +# endif /* !ACE_THR_PRI_RR_MAX */ +# if !defined (ACE_THR_PRI_OTHER_MIN) +# define ACE_THR_PRI_OTHER_MIN (long) 0 +# endif /* !ACE_THR_PRI_OTHER_MIN */ +# if !defined (ACE_THR_PRI_OTHER_MAX) +# define ACE_THR_PRI_OTHER_MAX (long) 127 +# endif /* !ACE_THR_PRI_OTHER_MAX */ +#endif /* ACE_HAS_PTHREADS */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_PTHREAD_H */ diff --git a/dep/acelite/ace/os_include/os_pwd.h b/dep/acelite/ace/os_include/os_pwd.h new file mode 100644 index 00000000000..b1bc94af381 --- /dev/null +++ b/dep/acelite/ace/os_include/os_pwd.h @@ -0,0 +1,58 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_pwd.h + * + * password structure + * + * $Id: os_pwd.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_PWD_H +#define ACE_OS_INCLUDE_OS_PWD_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_types.h" + +#if !defined (ACE_LACKS_PWD_H) +# include /**/ +#endif /* !ACE_LACKS_PWD_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#if !defined (ACE_WIN32) +// VAC++ doesn't correctly grok the ::getpwnam_r - the function is redefined +// in pwd.h, and that redefinition is used here +# if defined (_AIX) && defined (__IBMCPP__) && (__IBMCPP__ >= 400) + extern int _posix_getpwnam_r(const char *, struct passwd *, char *, + int, struct passwd **); +# endif /* AIX and VAC++ 4 */ +#endif /* !ACE_WIN32 */ + +#if defined (DIGITAL_UNIX) + extern int _Pgetpwnam_r (const char *, struct passwd *, + char *, size_t, struct passwd **); +#endif /* DIGITAL_UNIX */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_PWD_H */ diff --git a/dep/acelite/ace/os_include/os_regex.h b/dep/acelite/ace/os_include/os_regex.h new file mode 100644 index 00000000000..1c856da26f0 --- /dev/null +++ b/dep/acelite/ace/os_include/os_regex.h @@ -0,0 +1,48 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_regex.h + * + * regular expression matching types + * + * $Id: os_regex.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_REGEX_H +#define ACE_OS_INCLUDE_OS_REGEX_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_types.h" + +#if !defined (ACE_LACKS_REGEX_H) +# include /**/ +#endif /* !ACE_LACKS_REGEX_H */ + +#if defined (ACE_HAS_REGEX) +# include /**/ +#endif /* ACE_HAS_REGEX */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_REGEX_H */ diff --git a/dep/acelite/ace/os_include/os_sched.h b/dep/acelite/ace/os_include/os_sched.h new file mode 100644 index 00000000000..f06541b8ca8 --- /dev/null +++ b/dep/acelite/ace/os_include/os_sched.h @@ -0,0 +1,56 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_sched.h + * + * execution scheduling (REALTIME) + * + * $Id: os_sched.h 85102 2009-04-17 14:04:36Z johnnyw $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_SCHED_H +#define ACE_OS_INCLUDE_OS_SCHED_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/os_time.h" + +#if !defined (ACE_LACKS_SCHED_H) +# include /**/ +#endif /* !ACE_LACKS_SCHED_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#if !defined (__cpu_set_t_defined) || !defined (ACE_HAS_CPU_SET_T) +#if defined (ACE_HAS_CPUSET_T) + typedef cpuset_t cpu_set_t; +#else +# define ACE_CPU_SETSIZE 1024 + typedef struct + { + ACE_UINT32 bit_array_[ACE_CPU_SETSIZE / (8 * sizeof (ACE_UINT32))]; + } cpu_set_t; +#endif +#endif /* !ACE_HAS_CPU_SET_T || !__cpu_set_t_defined */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_SCHED_H */ diff --git a/dep/acelite/ace/os_include/os_search.h b/dep/acelite/ace/os_include/os_search.h new file mode 100644 index 00000000000..605fd365c09 --- /dev/null +++ b/dep/acelite/ace/os_include/os_search.h @@ -0,0 +1,44 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_search.h + * + * search tables + * + * $Id: os_search.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_SEARCH_H +#define ACE_OS_INCLUDE_OS_SEARCH_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_types.h" + +#if !defined (ACE_LACKS_SEARCH_H) +# include /**/ +#endif /* !ACE_LACKS_SEARCH_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_SEARCH_H */ diff --git a/dep/acelite/ace/os_include/os_semaphore.h b/dep/acelite/ace/os_include/os_semaphore.h new file mode 100644 index 00000000000..7fad7dafb4e --- /dev/null +++ b/dep/acelite/ace/os_include/os_semaphore.h @@ -0,0 +1,77 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_semaphore.h + * + * semaphores (REALTIME) + * + * $Id: os_semaphore.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_SEMAPHORE_H +#define ACE_OS_INCLUDE_OS_SEMAPHORE_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/os_time.h" + +#if !defined (ACE_LACKS_SEMAPHORE_H) +# include /**/ +#endif /* !ACE_LACKS_SEMAPHORE_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#if defined (ACE_HAS_POSIX_SEM) +# if !defined (SEM_FAILED) && !defined (ACE_LACKS_NAMED_POSIX_SEM) +# define SEM_FAILED ((sem_t *) -1) +# endif /* !SEM_FAILED */ + + typedef struct + { + /// Pointer to semaphore handle. This is allocated by ACE if we are + /// working with an unnamed POSIX semaphore or by the OS if we are + /// working with a named POSIX semaphore. + sem_t *sema_; + + /// Name of the semaphore (if this is non-NULL then this is a named + /// POSIX semaphore, else its an unnamed POSIX semaphore). + char *name_; + +# if defined (ACE_LACKS_NAMED_POSIX_SEM) + /// this->sema_ doesn't always get created dynamically if a platform + /// doesn't support named posix semaphores. We use this flag to + /// remember if we need to delete or not. + bool new_sema_; +# endif /* ACE_LACKS_NAMED_POSIX_SEM */ + +# if !defined (ACE_HAS_POSIX_SEM_TIMEOUT) && !defined (ACE_DISABLE_POSIX_SEM_TIMEOUT_EMULATION) + /// Serialize access to internal state. + ACE_mutex_t lock_; + + /// Block until there are no waiters. + ACE_cond_t count_nonzero_; +# endif /* !ACE_HAS_POSIX_SEM_TIMEOUT && !ACE_DISABLE_POSIX_SEM_TIMEOUT_EMULATION */ + } ACE_sema_t; +#endif /* ACE_HAS_POSIX_SEM */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_SEMAPHORE_H */ diff --git a/dep/acelite/ace/os_include/os_setjmp.h b/dep/acelite/ace/os_include/os_setjmp.h new file mode 100644 index 00000000000..2ab4a18a9f9 --- /dev/null +++ b/dep/acelite/ace/os_include/os_setjmp.h @@ -0,0 +1,42 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_setjmp.h + * + * stack environment declarations + * + * $Id: os_setjmp.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_SETJMP_H +#define ACE_OS_INCLUDE_OS_SETJMP_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_SETJMP_H) +# include /**/ +#endif /* !ACE_LACKS_SETJMP_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_SETJMP_H */ diff --git a/dep/acelite/ace/os_include/os_signal.h b/dep/acelite/ace/os_include/os_signal.h new file mode 100644 index 00000000000..dbda2a67b4e --- /dev/null +++ b/dep/acelite/ace/os_include/os_signal.h @@ -0,0 +1,249 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_signal.h + * + * signals + * + * $Id: os_signal.h 87480 2009-11-11 11:38:15Z olli $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_SIGNAL_H +#define ACE_OS_INCLUDE_OS_SIGNAL_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_types.h" + +#if !defined (ACE_LACKS_SIGNAL_H) + extern "C" { +# include /**/ + } +#endif /* !ACE_LACKS_SIGNAL_H */ + +// This must come after signal.h is #included. +#if defined (SCO) +# define SIGIO SIGPOLL +# include /**/ +#endif /* SCO */ + +#if defined (ACE_HAS_SIGINFO_T) +# if !defined (ACE_LACKS_SIGINFO_H) +# if defined (__QNX__) || defined (__OpenBSD__) || defined (__INTERIX) +# include /**/ +# else /* __QNX__ || __OpenBSD__ */ +# include /**/ +# endif /* __QNX__ || __OpenBSD__ */ +# endif /* ACE_LACKS_SIGINFO_H */ +#endif /* ACE_HAS_SIGINFO_T */ + +#if defined (ACE_VXWORKS) && (ACE_VXWORKS < 0x620) && !defined (__RTP__) +# include /**/ +#endif /* ACE_VXWORKS */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#if defined (ACE_LACKS_SIGSET) && !defined (__MINGW32__) + typedef u_int sigset_t; +#endif /* ACE_LACKS_SIGSET && !sigset_t */ + +#if !defined (ACE_HAS_SIG_ATOMIC_T) + typedef int sig_atomic_t; +#endif /* !ACE_HAS_SIG_ATOMIC_T */ + +# if !defined (SA_SIGINFO) +# define SA_SIGINFO 0 +# endif /* SA_SIGINFO */ + +# if !defined (SA_RESTART) +# define SA_RESTART 0 +# endif /* SA_RESTART */ + +#if !defined (SIGHUP) +# define SIGHUP 0 +#endif /* SIGHUP */ + +#if !defined (SIGINT) +# define SIGINT 0 +#endif /* SIGINT */ + +#if !defined (SIGSEGV) +# define SIGSEGV 0 +#endif /* SIGSEGV */ + +#if !defined (SIGIO) +# define SIGIO 0 +#endif /* SIGSEGV */ + +#if !defined (SIGUSR1) +# define SIGUSR1 0 +#endif /* SIGUSR1 */ + +#if !defined (SIGUSR2) +# define SIGUSR2 0 +#endif /* SIGUSR2 */ + +#if !defined (SIGCHLD) +# define SIGCHLD 0 +#endif /* SIGCHLD */ + +#if !defined (SIGCLD) +# define SIGCLD SIGCHLD +#endif /* SIGCLD */ + +#if !defined (SIGQUIT) +# define SIGQUIT 0 +#endif /* SIGQUIT */ + +#if !defined (SIGPIPE) +# define SIGPIPE 0 +#endif /* SIGPIPE */ + +#if !defined (SIGALRM) +# define SIGALRM 0 +#endif /* SIGALRM */ + +#if !defined (SIGABRT) +# define SIGABRT 0 +#endif /* SIGABRT */ + +#if !defined (SIGTERM) +# define SIGTERM 0 +#endif /* SIGTERM */ + +#if !defined (SIG_DFL) +# define SIG_DFL ((__sighandler_t) 0) +#endif /* SIG_DFL */ + +#if !defined (SIG_IGN) +# define SIG_IGN ((__sighandler_t) 1) /* ignore signal */ +#endif /* SIG_IGN */ + +#if !defined (SIG_ERR) +# define SIG_ERR ((__sighandler_t) -1) /* error return from signal */ +#endif /* SIG_ERR */ + +// These are used by the and +// methods. They must be unique and cannot +// conflict with the value of . We make the numbers +// negative here so they won't conflict with other values like SIGIO, +// etc. +# define ACE_SIGIO -1 +# define ACE_SIGURG -2 +# define ACE_CLOEXEC -3 + +#if defined (ACE_VXWORKS) +# define ACE_NSIG (_NSIGS + 1) +#elif defined (__Lynx__) || defined (ACE_HAS_RTEMS) +# define ACE_NSIG (NSIG + 1) +#else + // All other platforms set NSIG to one greater than the + // highest-numbered signal. +# define ACE_NSIG NSIG +#endif /* ACE_VXWORKS */ + +#if defined (ACE_HAS_WINCE) + typedef void (__cdecl * __sighandler_t)(int); +#endif + +#if defined (ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES) + // Prototypes for both signal() and struct sigaction are consistent.. + typedef void (*ACE_SignalHandler)(int); + typedef void (*ACE_SignalHandlerV)(int); +#elif defined (ACE_HAS_LYNXOS4_SIGNALS) || defined (ACE_HAS_TANDEM_SIGNALS) + typedef void (*ACE_SignalHandler)(...); + typedef void (*ACE_SignalHandlerV)(...); +#elif defined (ACE_HAS_SVR4_SIGNAL_T) + // SVR4 Signals are inconsistent (e.g., see struct sigaction).. + typedef void (*ACE_SignalHandler)(int); + typedef void (*ACE_SignalHandlerV)(void); +#elif defined (ACE_WIN32) + typedef void (__cdecl *ACE_SignalHandler)(int); + typedef void (__cdecl *ACE_SignalHandlerV)(int); +#elif defined (ACE_HAS_UNIXWARE_SVR4_SIGNAL_T) + typedef void (*ACE_SignalHandler)(int); + typedef void (*ACE_SignalHandlerV)(...); +#elif defined (INTEGRITY) + typedef void (*ACE_SignalHandler)(); + typedef void (*ACE_SignalHandlerV)(int); +#elif defined (ACE_HAS_RTEMS) + typedef void (*ACE_SignalHandler)(); + typedef void (*ACE_SignalHandlerV)(); +#else /* This is necessary for some older broken version of cfront */ +# if defined (SIG_PF) +# define ACE_SignalHandler SIG_PF +# else + typedef void (*ACE_SignalHandler)(int); +# endif /* SIG_PF */ + typedef void (*ACE_SignalHandlerV)(...); +#endif /* ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES */ + +#if defined (ACE_LACKS_SIGACTION) + struct sigaction + { + int sa_flags; + ACE_SignalHandlerV sa_handler; + sigset_t sa_mask; + }; +#endif /* ACE_LACKS_SIGACTION */ + +// Defining POSIX4 real-time signal range. +#if defined(ACE_HAS_POSIX_REALTIME_SIGNALS) +# define ACE_SIGRTMIN SIGRTMIN +# define ACE_SIGRTMAX SIGRTMAX +#else /* !ACE_HAS_POSIX_REALTIME_SIGNALS */ +# ifndef ACE_SIGRTMIN +# define ACE_SIGRTMIN 0 +# endif /* ACE_SIGRTMIN */ +# ifndef ACE_SIGRTMAX +# define ACE_SIGRTMAX 0 +# endif /* ACE_SIGRTMAX */ +#endif /* ACE_HAS_POSIX_REALTIME_SIGNALS */ + +#if defined (DIGITAL_UNIX) + // sigwait is yet another macro on Digital UNIX 4.0, just causing + // trouble when introducing member functions with the same name. + // Thanks to Thilo Kielmann" for + // this fix. +# if defined (__DECCXX_VER) +# undef sigwait + // cxx on Digital Unix 4.0 needs this declaration. With it, + // <::_Psigwait> works with cxx -pthread. g++ does _not_ need + // it. + int _Psigwait __((const sigset_t *set, int *sig)); +# endif /* __DECCXX_VER */ +#elif !defined (ACE_HAS_SIGWAIT) +# if defined(ACE_HAS_RTEMS) + int sigwait (const sigset_t *set, int *sig); +# else + int sigwait (sigset_t *set); +# endif /* ACE_HAS_RTEMS */ +#endif /* ! DIGITAL_UNIX && ! ACE_HAS_SIGWAIT */ + +#if !defined (ACE_HAS_PTHREAD_SIGMASK_PROTOTYPE) + int pthread_sigmask(int, const sigset_t *, sigset_t *); +#endif /*!ACE_HAS_PTHREAD_SIGMASK_PROTOTYPE */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include "ace/os_include/os_ucontext.h" + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_SIGNAL_H */ diff --git a/dep/acelite/ace/os_include/os_spawn.h b/dep/acelite/ace/os_include/os_spawn.h new file mode 100644 index 00000000000..0f825640ff9 --- /dev/null +++ b/dep/acelite/ace/os_include/os_spawn.h @@ -0,0 +1,46 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_spawn.h + * + * spawn (ADVANCED REALTIME) + * + * $Id: os_spawn.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_SPAWN_H +#define ACE_OS_INCLUDE_OS_SPAWN_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/os_signal.h" +#include "ace/os_include/sys/os_types.h" +#include "ace/os_include/os_sched.h" + +#if !defined (ACE_LACKS_SPAWN_H) +# include /**/ +#endif /* !ACE_LACKS_SPAWN_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_SPAWN_H */ diff --git a/dep/acelite/ace/os_include/os_stdarg.h b/dep/acelite/ace/os_include/os_stdarg.h new file mode 100644 index 00000000000..0e9d234b55e --- /dev/null +++ b/dep/acelite/ace/os_include/os_stdarg.h @@ -0,0 +1,50 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_stdarg.h + * + * handle variable argument list + * + * $Id: os_stdarg.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_STDARG_H +#define ACE_OS_INCLUDE_OS_STDARG_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_STDARG_H) +# include /**/ +#endif /* !ACE_LACKS_STDARG_H */ + +#if !defined (va_copy) +#if defined (__va_copy) +#define va_copy(d, s) __va_copy((d),(s)) +#else +#define va_copy(d, s) memcpy((void *)&(d),(void *)&(s),sizeof(va_list)) +#endif +#endif + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_STDARG_H */ diff --git a/dep/acelite/ace/os_include/os_stdbool.h b/dep/acelite/ace/os_include/os_stdbool.h new file mode 100644 index 00000000000..ddb3f8e0ddb --- /dev/null +++ b/dep/acelite/ace/os_include/os_stdbool.h @@ -0,0 +1,42 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_stdbool.h + * + * boolean type and values + * + * $Id: os_stdbool.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_STDBOOL_H +#define ACE_OS_INCLUDE_OS_STDBOOL_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_STDBOOL_H) +# include /**/ +#endif /* !ACE_LACKS_STDBOOL_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_STDBOOL_H */ diff --git a/dep/acelite/ace/os_include/os_stddef.h b/dep/acelite/ace/os_include/os_stddef.h new file mode 100644 index 00000000000..55ec501921d --- /dev/null +++ b/dep/acelite/ace/os_include/os_stddef.h @@ -0,0 +1,75 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_stddef.h + * + * standard type definitions + * + * $Id: os_stddef.h 89759 2010-04-06 06:07:24Z johnnyw $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +// From http://www.UNIX-systems.org/single_unix_specification/ + +#ifndef ACE_OS_INCLUDE_OS_STDDEF_H +#define ACE_OS_INCLUDE_OS_STDDEF_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_STDDEF_H) +# include /**/ +#endif /* !ACE_LACKS_STDDEF_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +// Signed integer type of the result of subtracting two pointers. +#if defined (ACE_LACKS_PTRDIFF_T) +# if !defined (ACE_PTRDIFF_T_TYPE) +# define ACE_PTRDIFF_T_TYPE unsigned long +# endif /* !ACE_PTRDIFF_T_TYPE */ + typedef ACE_PTRDIFF_T_TYPE ptrdiff_t; +#endif /* ACE_LACKS_PTRDIFF_T */ + +/* + Integer type whose range of values can represent distinct wide-character + codes for all members of the largest character set specified among the + locales supported by the compilation environment: the null character has + the code value 0 and each member of the portable character set has a code + value equal to its value when used as the lone character in an integer + character constant. +*/ +#if defined (ACE_LACKS_WCHAR_T) +# if !defined (ACE_WCHAR_T_TYPE) +# define ACE_WCHAR_T_TYPE long +# endif /* !ACE_WCHAR_T_TYPE */ + typedef ACE_WCHAR_T_TYPE wchar_t; +#endif /* ACE_LACKS_WCHAR_T */ + +// Unsigned integer type of the result of the sizeof operator. +#if defined (ACE_LACKS_SIZE_T) +# if !defined (ACE_SIZE_T_TYPE) +# define ACE_SIZE_T_TYPE unsigned int +# endif /* !ACE_SIZE_T_TYPE */ + typedef ACE_SIZE_T_TYPE size_t; +#endif /* ACE_LACKS_SIZE_T */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_STDDEF_H */ diff --git a/dep/acelite/ace/os_include/os_stdint.h b/dep/acelite/ace/os_include/os_stdint.h new file mode 100644 index 00000000000..ac6fec664c5 --- /dev/null +++ b/dep/acelite/ace/os_include/os_stdint.h @@ -0,0 +1,141 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_stdint.h + * + * integer types + * + * $Id: os_stdint.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_STDINT_H +#define ACE_OS_INCLUDE_OS_STDINT_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_STDINT_H) +# include /**/ +#endif /* !ACE_LACKS_STDINT_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +// BSD style types +#if defined (ACE_LACKS_SYS_TYPES_H) \ + || (defined (__GLIBC__) && !defined (_BSD_SOURCE)) + typedef unsigned char u_char; + typedef unsigned short u_short; + typedef unsigned int u_int; + typedef unsigned long u_long; + + typedef unsigned char uchar_t; + typedef unsigned short ushort_t; + typedef unsigned int uint_t; + typedef unsigned long ulong_t; +#endif /* ACE_LACKS_SYS_TYPES_H */ + +/* Define required types if missing */ + +#if defined (ACE_LACKS_INT8_T) +# if !defined (ACE_INT8_T_TYPE) +# define ACE_INT8_T_TYPE char +# endif /* !ACE_INT8_T_TYPE */ + typedef ACE_INT8_T_TYPE int8_t; +#endif /* ACE_LACKS_INT8_T */ + +#if defined (ACE_LACKS_UINT8_T) +# if !defined (ACE_UINT8_T_TYPE) +# define ACE_UINT8_T_TYPE unsigned char +# endif /* !ACE_UINT8_T_TYPE */ + typedef ACE_UINT8_T_TYPE int8_t; +#endif /* ACE_LACKS_UINT8_T */ + +#if defined (ACE_LACKS_INT16_T) +# if !defined (ACE_INT16_T_TYPE) +# define ACE_INT16_T_TYPE short +# endif /* !ACE_INT16_T_TYPE */ + typedef ACE_INT16_T_TYPE int16_t; +#endif /* ACE_LACKS_INT16_T */ + +#if defined (ACE_LACKS_UINT16_T) +# if !defined (ACE_UINT16_T_TYPE) +# define ACE_UINT16_T_TYPE unsigned short +# endif /* !ACE_UINT16_T_TYPE */ + typedef ACE_UINT16_T_TYPE int16_t; +#endif /* ACE_LACKS_UINT16_T */ + +#if defined (ACE_LACKS_INT32_T) +# if !defined (ACE_INT32_T_TYPE) +# define ACE_INT32_T_TYPE long +# endif /* !ACE_INT32_T_TYPE */ + typedef ACE_INT32_T_TYPE int32_t; +#endif /* ACE_LACKS_INT32_T */ + +#if defined (ACE_LACKS_UINT32_T) +# if !defined (ACE_UINT32_T_TYPE) +# define ACE_UINT32_T_TYPE unsigned long +# endif /* !ACE_UINT32_T_TYPE */ + typedef ACE_UINT32_T_TYPE int32_t; +#endif /* ACE_LACKS_UIN32_T */ + +// @todo pull in ACE class here +// 64 bit will be a problem, but stub it out for now +/* +If an implementation provides integer types with width 64 that meet +these requirements, then the following types are required: int64_t uint64_t + +In particular, this will be the case if any of the following are true: + +The implementation supports the _POSIX_V6_ILP32_OFFBIG programming +environment and the application is being built in the +_POSIX_V6_ILP32_OFFBIG programming environment (see the Shell and +Utilities volume of IEEE Std 1003.1-2001, c99, Programming Environments). + +The implementation supports the _POSIX_V6_LP64_OFF64 programming +environment and the application is being built in the +_POSIX_V6_LP64_OFF64 programming environment. + +The implementation supports the _POSIX_V6_LPBIG_OFFBIG programming +environment and the application is being built in the +_POSIX_V6_LPBIG_OFFBIG programming environment. +*/ +#if defined (ACE_LACKS_INT64_T) +# if !defined (ACE_INT64_T_TYPE) +# define ACE_INT64_T_TYPE long +# endif /* !ACE_INT64_T_TYPE */ + typedef ACE_INT64_T_TYPE int64_t; +#endif /* ACE_LACKS_INT64_T */ + +#if defined (ACE_LACKS_UINT64_T) +# if !defined (ACE_UINT64_T_TYPE) +# define ACE_UINT64_T_TYPE unsigned long +# endif /* !ACE_UINT64_T_TYPE */ + typedef ACE_UINT64_T_TYPE int64_t; +#endif /* ACE_LACKS_UIN64_T */ + +// @todo move the ACE_INT## typedefs here so that ACE_INT64 will +// always be available. + + +// @todo perhaps add macros + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_STDINT_H */ diff --git a/dep/acelite/ace/os_include/os_stdio.h b/dep/acelite/ace/os_include/os_stdio.h new file mode 100644 index 00000000000..e9f452024ff --- /dev/null +++ b/dep/acelite/ace/os_include/os_stdio.h @@ -0,0 +1,87 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_stdio.h + * + * standard buffered input/output + * + * $Id: os_stdio.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_STDIO_H +#define ACE_OS_INCLUDE_OS_STDIO_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +// NOTE: stdarg.h must be #included before stdio.h on LynxOS. +#include "ace/os_include/os_stdarg.h" +#include "ace/os_include/os_stddef.h" + +#if !defined (ACE_LACKS_STDIO_H) +# include /**/ +#endif /* !ACE_LACKS_STDIO_H */ + +#if defined (ACE_VXWORKS) +// for remove(), rename() +# include /**/ +// for remCurIdGet() +# include /**/ +# if defined (__RTP__) && ((ACE_VXWORKS >= 0x620) && (ACE_VXWORKS <= 0x650)) +# define L_cuserid _PARM_L_cuserid +# endif +#endif /* ACE_VXWORKS */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +# if defined (INTEGRITY) +# define ACE_MAX_USERID 32 +# elif defined (ACE_WIN32) +# define ACE_MAX_USERID 32 +# else +# if defined (_POSIX_SOURCE) && defined (L_cuserid) +# define ACE_MAX_USERID L_cuserid +# else +# define ACE_MAX_USERID 9 +# endif +# endif /* INTEGRITY */ + +#if defined (BUFSIZ) +# define ACE_STREAMBUF_SIZE BUFSIZ +#else +# define ACE_STREAMBUF_SIZE 1024 +#endif /* BUFSIZ */ + +#if defined (ACE_WIN32) + typedef OVERLAPPED ACE_OVERLAPPED; +#else + struct ACE_OVERLAPPED + { + unsigned long Internal; + unsigned long InternalHigh; + unsigned long Offset; + unsigned long OffsetHigh; + ACE_HANDLE hEvent; + }; +#endif /* ACE_WIN32 */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_STDIO_H */ diff --git a/dep/acelite/ace/os_include/os_stdlib.h b/dep/acelite/ace/os_include/os_stdlib.h new file mode 100644 index 00000000000..6a675d54e29 --- /dev/null +++ b/dep/acelite/ace/os_include/os_stdlib.h @@ -0,0 +1,85 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_stdlib.h + * + * standard library definitions + * + * $Id: os_stdlib.h 83948 2008-12-02 13:55:34Z jtc $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_STDLIB_H +#define ACE_OS_INCLUDE_OS_STDLIB_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/os_stddef.h" +#include "ace/os_include/sys/os_wait.h" + +#if defined (ACE_HAS_ALLOCA_H) +# include /**/ +#endif /* ACE_HAS_ALLOCA_H */ + +#if !defined (ACE_LACKS_STDLIB_H) +# include /**/ +#endif /* !ACE_LACKS_STDLIB_H */ + +#if defined (ACE_VXWORKS) && !defined (__RTP__) +# include /**/ +#endif /* ACE_VXWORKS */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + + typedef u_int ACE_RANDR_TYPE; +#if defined (ACE_HAS_BROKEN_RANDR) + // The SunOS 5.4.X version of rand_r is inconsistent with the header + // files... + int rand_r (ACE_RANDR_TYPE seed); +#else +#endif /* ACE_HAS_BROKEN_RANDR */ + +#if defined (DIGITAL_UNIX) + extern int _Prand_r (unsigned int *seedptr); +#endif /* DIGITAL_UNIX */ + +#if defined (ACE_LACKS_PUTENV_PROTOTYPE) + int putenv (char *); +#endif /* ACE_LACKS_PUTENV_PROTOTYPE */ + +#if defined (ACE_LACKS_MKTEMP_PROTOTYPE) + char *mktemp (char *); +#endif /* ACE_LACKS_MKTEMP_PROTOTYPE */ + +#if defined (ACE_LACKS_MKSTEMP_PROTOTYPE) + int mkstemp (char *); +#endif /* ACE_LACKS_MKSTEMP_PROTOTYPE */ + +#if defined (ACE_LACKS_STRTOLL_PROTOTYPE) + long long strtoll (const char *, char **, int); +#endif /* ACE_LACKS_STRTOLL_PROTOTYPE */ + +#if defined (ACE_LACKS_STRTOULL_PROTOTYPE) + unsigned long long strtoull (const char *, char **, int); +#endif /* ACE_LACKS_STRTOULL_PROTOTYPE */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_STDLIB_H */ diff --git a/dep/acelite/ace/os_include/os_string.h b/dep/acelite/ace/os_include/os_string.h new file mode 100644 index 00000000000..0aa2f7de7cc --- /dev/null +++ b/dep/acelite/ace/os_include/os_string.h @@ -0,0 +1,53 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_string.h + * + * string operations + * + * $Id: os_string.h 87216 2009-10-23 20:26:16Z olli $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_STRING_H +#define ACE_OS_INCLUDE_OS_STRING_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/os_stddef.h" + +#if !defined (ACE_LACKS_STRING_H) +# include /**/ +#endif /* !ACE_LACKS_STRING_H */ + + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#if defined (ACE_LACKS_STRTOK_R_PROTOTYPE) && !defined (_POSIX_SOURCE) + char *strtok_r (char *s, const char *delim, char **save_ptr); +#endif /* ACE_LACKS_STRTOK_R_PROTOTYPE */ + +#if defined (ACE_LACKS_STRNLEN_PROTOTYPE) + size_t strnlen(const char *s, size_t maxlen); +#endif /* ACE_LACKS_STRNLEN_PROTOTYPE */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_STRING_H */ diff --git a/dep/acelite/ace/os_include/os_strings.h b/dep/acelite/ace/os_include/os_strings.h new file mode 100644 index 00000000000..ba258b08cb9 --- /dev/null +++ b/dep/acelite/ace/os_include/os_strings.h @@ -0,0 +1,52 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_strings.h + * + * string operations + * + * $Id: os_strings.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_STRINGS_H +#define ACE_OS_INCLUDE_OS_STRINGS_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/os_stddef.h" + +#if !defined (ACE_LACKS_STRINGS_H) +# include /**/ +#endif /* !ACE_LACKS_STRINGS_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#if defined (ACE_LACKS_STRCASECMP_PROTOTYPE) + int strcasecmp(const char *, const char *); +#endif /* ACE_LACKS_STRCASECMP_PROTOTYPE */ + +#if defined (ACE_LACKS_STRNCASECMP_PROTOTYPE) + int strncasecmp(const char *, const char *, size_t); +#endif /* ACE_LACKS_STRNCASECMP_PROTOTYPE */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_STRINGS_H */ diff --git a/dep/acelite/ace/os_include/os_stropts.h b/dep/acelite/ace/os_include/os_stropts.h new file mode 100644 index 00000000000..e64717a9551 --- /dev/null +++ b/dep/acelite/ace/os_include/os_stropts.h @@ -0,0 +1,114 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_stropts.h + * + * STREAMS interface (STREAMS) + * + * $Id: os_stropts.h 84660 2009-03-01 20:22:37Z olli $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_STROPTS_H +#define ACE_OS_INCLUDE_OS_STROPTS_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/os_unistd.h" + +#if defined (ACE_HAS_TIMOD_H) +# include /**/ +#elif defined (ACE_HAS_OSF_TIMOD_H) +# include /**/ +#endif /* ACE_HAS_TIMOD_H */ + +#if !defined (ACE_LACKS_SYS_IOCTL_H) +# include /**/ +#endif /* !ACE_LACKS_IOCTL_H */ + +#if defined (ACE_HAS_SYS_FILIO_H) +# include /**/ +#endif /* ACE_HAS_SYS_FILIO_H */ + +#if defined (ACE_HAS_SYS_SOCKIO_H) +# include /**/ +#endif /* ACE_HAS_SOCKIO_H */ + +// This is sorta counter intuitive, but this is how it was done in OS.h +// @todo: fix this... dhinton +#if defined (ACE_HAS_STREAMS) +# if defined (AIX) +# if !defined (_XOPEN_EXTENDED_SOURCE) +# define _XOPEN_EXTENDED_SOURCE +# endif /* !_XOPEN_EXTENDED_SOURCE */ +# endif /* AIX */ +#endif /* ACE_HAS_STREAMS */ + +#if !defined (ACE_LACKS_STROPTS_H) +# include /**/ +#endif /* !ACE_LACKS_STROPTS_H */ + +// This is sorta counter intuitive, but this is how it was done in OS.h +// @todo: fix this... dhinton +#if defined (ACE_HAS_STREAMS) +# if defined (AIX) +# undef _XOPEN_EXTENDED_SOURCE +# endif /* AIX */ +#endif /* ACE_HAS_STREAMS */ + +#if defined (ACE_VXWORKS) +// for ioctl() +# include /**/ +#endif /* ACE_VXWORKS */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#if defined (ACE_LACKS_STRRECVFD) + struct strrecvfd {}; +#endif /* ACE_LACKS_STRRECVFD */ + +# if !defined (SIOCGIFBRDADDR) +# define SIOCGIFBRDADDR 0 +# endif /* SIOCGIFBRDADDR */ + +# if !defined (SIOCGIFADDR) +# define SIOCGIFADDR 0 +# endif /* SIOCGIFADDR */ + +# if !defined (ACE_HAS_STRBUF_T) +struct strbuf +{ + /// No. of bytes in buffer. + int maxlen; + /// No. of bytes returned. + int len; + /// Pointer to data. + void *buf; +}; +# endif /* ACE_HAS_STRBUF_T */ + +// These prototypes are chronically lacking from many versions of UNIX. +#if !defined (ACE_WIN32) && !defined (ACE_HAS_ISASTREAM_PROTOTYPE) + int isastream (int); +#endif /* !ACE_WIN32 && ACE_HAS_ISASTREAM_PROTOTYPE */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_STROPTS_H */ diff --git a/dep/acelite/ace/os_include/os_syslog.h b/dep/acelite/ace/os_include/os_syslog.h new file mode 100644 index 00000000000..d448b7491e5 --- /dev/null +++ b/dep/acelite/ace/os_include/os_syslog.h @@ -0,0 +1,42 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_syslog.h + * + * definitions for system error logging + * + * $Id: os_syslog.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_SYSLOG_H +#define ACE_OS_INCLUDE_OS_SYSLOG_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_SYSLOG_H) +# include /**/ +#endif /* !ACE_LACKS_SYSLOG_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_SYSLOG_H */ diff --git a/dep/acelite/ace/os_include/os_tar.h b/dep/acelite/ace/os_include/os_tar.h new file mode 100644 index 00000000000..007925022e8 --- /dev/null +++ b/dep/acelite/ace/os_include/os_tar.h @@ -0,0 +1,42 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_tar.h + * + * extended tar definitions + * + * $Id: os_tar.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_TAR_H +#define ACE_OS_INCLUDE_OS_TAR_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_TAR_H) +# include /**/ +#endif /* !ACE_LACKS_TAR_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_TAR_H */ diff --git a/dep/acelite/ace/os_include/os_termios.h b/dep/acelite/ace/os_include/os_termios.h new file mode 100644 index 00000000000..9dfd3862276 --- /dev/null +++ b/dep/acelite/ace/os_include/os_termios.h @@ -0,0 +1,46 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_termios.h + * + * define values for termios + * + * $Id: os_termios.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_TERMIOS_H +#define ACE_OS_INCLUDE_OS_TERMIOS_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_TERMIOS_H) +# include /**/ +#endif /* !ACE_LACKS_TERMIOS_H */ + +#if defined (HPUX) +# include /**/ +#endif /* HPUX */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_TERMIOS_H */ diff --git a/dep/acelite/ace/os_include/os_tgmath.h b/dep/acelite/ace/os_include/os_tgmath.h new file mode 100644 index 00000000000..6d9f2c2db23 --- /dev/null +++ b/dep/acelite/ace/os_include/os_tgmath.h @@ -0,0 +1,45 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_tgmath.h + * + * type-generic macros + * + * $Id: os_tgmath.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_TGMATH_H +#define ACE_OS_INCLUDE_OS_TGMATH_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/os_math.h" +#include "ace/os_include/os_complex.h" + +#if !defined (ACE_LACKS_TGMATH_H) +# include /**/ +#endif /* !ACE_LACKS_TGMATH_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_TGMATH_H */ diff --git a/dep/acelite/ace/os_include/os_time.h b/dep/acelite/ace/os_include/os_time.h new file mode 100644 index 00000000000..e10a3b3164b --- /dev/null +++ b/dep/acelite/ace/os_include/os_time.h @@ -0,0 +1,119 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_time.h + * + * time types + * + * $Id: os_time.h 87270 2009-10-29 21:47:47Z olli $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_TIME_H +#define ACE_OS_INCLUDE_OS_TIME_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +// @todo should we include anything from signal.h? +#include "ace/os_include/sys/os_types.h" + +// To get the proper select() signature, this is required for HP-UX, and +// maybe other platforms that offer both int and fdset forms of select(). +// For HP-UX, sys/time.h must be included before time.h, or +// _XOPEN_SOURCE_EXTENDED must be defined. It's not nice to require +// the preprocessor macro, so we force our select() preference this way. +#if !defined (ACE_LACKS_SYS_TIME_H) +# include /**/ +#endif /* !ACE_LACKS_SYS_TIME_H */ + +#if !defined (ACE_LACKS_TIME_H) +# include /**/ +#endif /* !ACE_LACKS_TIME_H */ + +# if defined (ACE_USES_STD_NAMESPACE_FOR_STDC_LIB) && \ + (ACE_USES_STD_NAMESPACE_FOR_STDC_LIB != 0) +using std::tm; +# if !defined (ACE_HAS_DINKUM_STL) +# if defined (ACE_WIN32) +using std::_timezone; +# else +using std::timezone; +# endif +# endif +using std::difftime; +# endif /* ACE_USES_STD_NAMESPACE_FOR_STDC_LIB */ + +# if !defined (ACE_HAS_POSIX_TIME) +// Definition per POSIX. +typedef struct timespec +{ + /// Seconds + time_t tv_sec; + /// Nanoseconds + long tv_nsec; +} timespec_t; +# elif defined (ACE_HAS_BROKEN_POSIX_TIME) +# if defined (ACE_OPENVMS) +# include /**/ +# else +// OSF/1 defines struct timespec in - Tom Marrs +# include /**/ +# endif +# endif /* !ACE_HAS_POSIX_TIME */ + +# if defined(ACE_LACKS_TIMESPEC_T) +typedef struct timespec timespec_t; +# endif /* ACE_LACKS_TIMESPEC_T */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +// There are a lot of threads-related macro definitions in the config files. +// They came in at different times and from different places and platform +// requirements as threads evolved. They are probably not all needed - some +// overlap or are otherwise confused. This is an attempt to start +// straightening them out. +#if defined (ACE_HAS_PTHREADS) /* POSIX.1c threads (pthreads) */ + // ... and 2-parameter asctime_r and ctime_r +# if !defined (ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R) && \ + !defined (ACE_HAS_STHREADS) && !defined (ACE_VXWORKS) +# define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R +# endif +#endif /* ACE_HAS_PTHREADS */ + +#if defined (ACE_LACKS_STRPTIME_PROTOTYPE) && !defined (_XOPEN_SOURCE) + extern char *strptime (const char *s, const char *fmt, struct tm *tp); +#endif /* ACE_LACKS_STRPTIME_PROTOTYPE */ + +#if defined (ACE_LACKS_CONST_TIMESPEC_PTR) +typedef struct timespec * ACE_TIMESPEC_PTR; +#else +typedef const struct timespec * ACE_TIMESPEC_PTR; +#endif /* ACE_LACKS_CONST_TIMESPEC_PTR */ + +#if defined (DIGITAL_UNIX) + extern char *_Pctime_r (const time_t *, char *); + extern struct tm *_Plocaltime_r (const time_t *, struct tm *); + extern struct tm *_Pgmtime_r (const time_t *, struct tm *); + extern char *_Pasctime_r (const struct tm *, char *); +#endif /* DIGITAL_UNIX */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_TIME_H */ diff --git a/dep/acelite/ace/os_include/os_trace.h b/dep/acelite/ace/os_include/os_trace.h new file mode 100644 index 00000000000..fd89d54b23b --- /dev/null +++ b/dep/acelite/ace/os_include/os_trace.h @@ -0,0 +1,44 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_trace.h + * + * tracing + * + * $Id: os_trace.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_TRACE_H +#define ACE_OS_INCLUDE_OS_TRACE_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_types.h" + +#if !defined (ACE_LACKS_TRACE_H) +# include /**/ +#endif /* !ACE_LACKS_TRACE_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_TRACE_H */ diff --git a/dep/acelite/ace/os_include/os_typeinfo.h b/dep/acelite/ace/os_include/os_typeinfo.h new file mode 100644 index 00000000000..3ad1b16ef77 --- /dev/null +++ b/dep/acelite/ace/os_include/os_typeinfo.h @@ -0,0 +1,39 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_typeinfo.h + * + * definitions for the typeinfo file + * + * $Id: os_typeinfo.h 84160 2009-01-14 14:13:58Z johnnyw $ + * + * @author Don Hinton Johnny Willemsen + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_TYPEINFO_H +#define ACE_OS_INCLUDE_OS_TYPEINFO_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +# include /**/ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_TYPEINFO_H */ diff --git a/dep/acelite/ace/os_include/os_ucontext.h b/dep/acelite/ace/os_include/os_ucontext.h new file mode 100644 index 00000000000..f62be80e5fc --- /dev/null +++ b/dep/acelite/ace/os_include/os_ucontext.h @@ -0,0 +1,48 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_ucontext.h + * + * user context + * + * $Id: os_ucontext.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_UCONTEXT_H +#define ACE_OS_INCLUDE_OS_UCONTEXT_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/os_signal.h" + +#if !defined (ACE_LACKS_UCONTEXT_H) +# include /**/ +#endif /* !ACE_LACKS_ucontext_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +# if !defined (ACE_HAS_UCONTEXT_T) +typedef int ucontext_t; +# endif /* ACE_HAS_UCONTEXT_T */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_UCONTEXT_H */ diff --git a/dep/acelite/ace/os_include/os_ulimit.h b/dep/acelite/ace/os_include/os_ulimit.h new file mode 100644 index 00000000000..8593c0d95a5 --- /dev/null +++ b/dep/acelite/ace/os_include/os_ulimit.h @@ -0,0 +1,42 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_ulimit.h + * + * ulimit commands + * + * $Id: os_ulimit.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_ULIMIT_H +#define ACE_OS_INCLUDE_OS_ULIMIT_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_ULIMIT_H) +# include /**/ +#endif /* !ACE_LACKS_ULIMIT_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_ULIMIT_H */ diff --git a/dep/acelite/ace/os_include/os_unistd.h b/dep/acelite/ace/os_include/os_unistd.h new file mode 100644 index 00000000000..ee685d26222 --- /dev/null +++ b/dep/acelite/ace/os_include/os_unistd.h @@ -0,0 +1,196 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_unistd.h + * + * standard symbolic constants and types + * + * $Id: os_unistd.h 87125 2009-10-15 17:34:25Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_UNISTD_H +#define ACE_OS_INCLUDE_OS_UNISTD_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_types.h" +#include "ace/os_include/os_inttypes.h" + +#if defined (ACE_HAS_PROCESS_H) +# include /**/ +#endif /* ACE_HAS_PROCESS_H */ + +#if defined (ACE_HAS_IO_H) +# include /**/ +#endif /* ACE_HAS_IO_H */ + +#if defined (ACE_HAS_SYS_SYSTEMINFO_H) +# include /**/ +#endif /* ACE_HAS_SYS_SYSTEMINFO_H */ + +#if !defined (ACE_LACKS_UNISTD_H) +# include /**/ +#endif /* !ACE_LACKS_UNISTD_H */ + +#if defined (ACE_VXWORKS) +# if !defined (__RTP__) + // for unlink(), close(), read(), write(), lseek(), chdir(), getcwd(), + // getwd(), and isatty() + # include /**/ +# endif +// for gethostname() +# include /**/ +#endif /* ACE_VXWORKS */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#if defined (ACE_WIN32) +// The following are #defines and #includes that are specific to +// WIN32. +# if defined (ACE_HAS_WINCE) +# define ACE_STDIN _fileno (stdin) +# define ACE_STDOUT _fileno (stdout) +# define ACE_STDERR _fileno (stderr) +# else +# define ACE_STDIN GetStdHandle (STD_INPUT_HANDLE) +# define ACE_STDOUT GetStdHandle (STD_OUTPUT_HANDLE) +# define ACE_STDERR GetStdHandle (STD_ERROR_HANDLE) +# endif // ACE_HAS_WINCE +// The following are #defines and #includes that are specific to UNIX. +#else /* !ACE_WIN32 */ +# if defined (STDIN_FILENO) +# define ACE_STDIN STDIN_FILENO +# else +# define ACE_STDIN 0 +# endif +# if defined (STDOUT_FILENO) +# define ACE_STDOUT STDOUT_FILENO +# else +# define ACE_STDOUT 1 +# endif +# if defined (STDERR_FILENO) +# define ACE_STDERR STDERR_FILENO +# else +# define ACE_STDERR 2 +# endif +#endif /* ACE_WIN32 */ + +#if (!defined (_BSD_SOURCE) && \ + !defined (_XOPEN_SOURCE) && !defined (_XOPEN_SOURCE_EXTENDED)) \ + || (defined (_XOPEN_SOURCE) && defined (__GNUC__)) + +# if defined (ACE_LACKS_SETREUID_PROTOTYPE) + extern int setreuid (uid_t ruid, uid_t euid); +# endif /* ACE_LACKS_SETREUID_PROTOTYPE */ + +# if defined (ACE_LACKS_SETREGID_PROTOTYPE) + extern int setregid (gid_t rgid, gid_t egid); +# endif /* ACE_LACKS_SETREGID_PROTOTYPE */ +#endif /* !_BSD_SOURCE && !_XOPEN_SOURCE && !_XOPEN_SOURCE_EXTENDED + || _XOPEN_SOURCE && __GNUC__ */ + + // for use by access() +# if !defined (R_OK) +# define R_OK 04 /* Test for Read permission. */ +# endif /* R_OK */ + +# if !defined (W_OK) +# define W_OK 02 /* Test for Write permission. */ +# endif /* W_OK */ + +# if !defined (X_OK) +# if defined (ACE_WIN32) + /* Windows has no test for X_OK - use R_OK instead */ +# define X_OK R_OK /* Test for eXecute permission. */ +# else /* ACE_WIN32 */ +# define X_OK 01 /* Test for eXecute permission. */ +# endif /* ACE_WIN32 */ +# endif /* X_OK */ + +# if !defined (F_OK) +# define F_OK 0 /* Test for existence of File. */ +# endif /* F_OK */ + +#if defined (ACE_LACKS_UALARM_PROTOTYPE) + u_int ualarm (u_int usecs, u_int interval); +#endif /* ACE_LACKS_UALARM_PROTOTYPE */ + +#if defined (ACE_LACKS_PREAD_PROTOTYPE) && (_XOPEN_SOURCE - 0) < 500 + // _XOPEN_SOURCE == 500 Single Unix conformance + // It seems that _XOPEN_SOURCE == 500 means that the prototypes are + // already defined in the system headers. + ssize_t pread (int fd, + void *buf, + size_t nbytes, + ACE_OFF_T offset); + + ssize_t pwrite (int fd, + const void *buf, + size_t n, + ACE_OFF_T offset); +#endif /* ACE_LACKS_PREAD_PROTOTYPE && (_XOPEN_SOURCE - 0) < 500 */ + +#if defined (ACE_LACKS_GETPGID_PROTOTYPE) && \ + !defined (_XOPEN_SOURCE) && !defined (_XOPEN_SOURCE_EXTENDED) + pid_t getpgid (pid_t pid); +#endif /* ACE_LACKS_GETPGID_PROTOTYPE && + !_XOPEN_SOURCE && !_XOPEN_SOURCE_EXTENDED */ + +#if !defined (_LARGEFILE64_SOURCE) +# if defined (ACE_LACKS_LSEEK64_PROTOTYPE) && \ + defined (ACE_LACKS_LLSEEK_PROTOTYPE) +# error Define either ACE_LACKS_LSEEK64_PROTOTYPE or ACE_LACKS_LLSEEK_PROTOTYPE, not both! +# elif defined (ACE_LACKS_LSEEK64_PROTOTYPE) + ACE_LOFF_T lseek64 (int fd, ACE_LOFF_T offset, int whence); +# elif defined (ACE_LACKS_LLSEEK_PROTOTYPE) + ACE_LOFF_T llseek (int fd, ACE_LOFF_T offset, int whence); +# endif +#endif /* _LARGEFILE64_SOURCE */ + +#if defined (__BORLANDC__) +# define _isatty isatty +#endif /* __BORLANDC__ */ + +# if defined (ACE_LACKS_TIMEDWAIT_PROTOTYPES) + + ssize_t read_timedwait (ACE_HANDLE handle, + char *buf, + size_t n, + struct timespec *timeout); + + ssize_t write_timedwait (ACE_HANDLE handle, + const void *buf, + size_t n, + struct timespec *timeout); + +# endif /* ACE_LACKS_TIMEDWAIT_PROTOTYPES */ + +#if defined (ACE_LACKS_SWAB_PROTOTYPE) + void swab(const void *, void *, ssize_t); +#endif /* ACE_LACKS_SWAB_PROTOTYPE */ + +#if defined (ACE_LACKS_GETOPT_PROTOTYPE) + int getopt(int, char * const [], const char *); +#endif /* ACE_LACKS_GETOPT_PROTOTYPE */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_UNISTD_H */ diff --git a/dep/acelite/ace/os_include/os_utime.h b/dep/acelite/ace/os_include/os_utime.h new file mode 100644 index 00000000000..703da8b1424 --- /dev/null +++ b/dep/acelite/ace/os_include/os_utime.h @@ -0,0 +1,44 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_utime.h + * + * access and modification times structure + * + * $Id: os_utime.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_UTIME_H +#define ACE_OS_INCLUDE_OS_UTIME_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_types.h" + +#if !defined (ACE_LACKS_UTIME_H) +# include /**/ +#endif /* !ACE_LACKS_UTIME_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_UTIME_H */ diff --git a/dep/acelite/ace/os_include/os_utmpx.h b/dep/acelite/ace/os_include/os_utmpx.h new file mode 100644 index 00000000000..74ef305d4c1 --- /dev/null +++ b/dep/acelite/ace/os_include/os_utmpx.h @@ -0,0 +1,44 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_utmpx.h + * + * user accounting database definitions + * + * $Id: os_utmpx.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_UTMPX_H +#define ACE_OS_INCLUDE_OS_UTMPX_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_time.h" + +#if !defined (ACE_LACKS_UTMPX_H) +# include /**/ +#endif /* !ACE_LACKS_UTMPX_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_UTMPX_H */ diff --git a/dep/acelite/ace/os_include/os_wchar.h b/dep/acelite/ace/os_include/os_wchar.h new file mode 100644 index 00000000000..37eab2e4ee0 --- /dev/null +++ b/dep/acelite/ace/os_include/os_wchar.h @@ -0,0 +1,57 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_wchar.h + * + * wide-character handling + * + * $Id: os_wchar.h 83948 2008-12-02 13:55:34Z jtc $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_WCHAR_H +#define ACE_OS_INCLUDE_OS_WCHAR_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +// ctype.h, string.h, stdarg.h, stdio.h, stdlib.h, time.h +#include "ace/os_include/os_stdio.h" +#include "ace/os_include/os_stdlib.h" +#include "ace/os_include/os_time.h" +#include "ace/os_include/os_string.h" +#include "ace/os_include/os_ctype.h" + +#if !defined (ACE_LACKS_WCHAR_H) +# include /**/ +#endif /* !ACE_LACKS_WCHAR_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#if defined (ACE_LACKS_WCSTOLL_PROTOTYPE) + long long wcstoll (const wchar_t *, wchar_t **, int); +#endif /* ACE_LACKS_WCSTOLL_PROTOTYPE */ + +#if defined (ACE_LACKS_WCSTOULL_PROTOTYPE) + unsigned long long wcstoull (const wchar_t *, wchar_t **, int); +#endif /* ACE_LACKS_WCSTOULL_PROTOTYPE */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_WCHAR_H */ diff --git a/dep/acelite/ace/os_include/os_wctype.h b/dep/acelite/ace/os_include/os_wctype.h new file mode 100644 index 00000000000..15aa295a677 --- /dev/null +++ b/dep/acelite/ace/os_include/os_wctype.h @@ -0,0 +1,45 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_wctype.h + * + * wide-character classification and mapping utilities + * + * $Id: os_wctype.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_WCTYPE_H +#define ACE_OS_INCLUDE_OS_WCTYPE_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +// ctype.h, string.h, stdarg.h, stdio.h, stdlib.h, time.h +#include "ace/os_include/os_wchar.h" + +#if !defined (ACE_LACKS_WCTYPE_H) +# include /**/ +#endif /* !ACE_LACKS_WCTYPE_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_WCTYPE_H */ diff --git a/dep/acelite/ace/os_include/os_wordexp.h b/dep/acelite/ace/os_include/os_wordexp.h new file mode 100644 index 00000000000..76960076df6 --- /dev/null +++ b/dep/acelite/ace/os_include/os_wordexp.h @@ -0,0 +1,44 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_wordexp.h + * + * word-expansion types + * + * $Id: os_wordexp.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_OS_WORDEXP_H +#define ACE_OS_INCLUDE_OS_WORDEXP_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/os_stddef.h" // size_t + +#if !defined (ACE_LACKS_WORDEXP_H) +# include /**/ +#endif /* !ACE_LACKS_WORDEXP_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_OS_WORDEXP_H */ diff --git a/dep/acelite/ace/os_include/sys/os_ipc.h b/dep/acelite/ace/os_include/sys/os_ipc.h new file mode 100644 index 00000000000..bea65e5e7d9 --- /dev/null +++ b/dep/acelite/ace/os_include/sys/os_ipc.h @@ -0,0 +1,74 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_ipc.h + * + * XSI interprocess communication access structure + * + * $Id: os_ipc.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_SYS_OS_IPC_H +#define ACE_OS_INCLUDE_SYS_OS_IPC_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_types.h" + +#if !defined (ACE_LACKS_SYS_IPC_H) +# include /**/ +#endif /* !ACE_LACKS_SYS_IPC_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#if defined (ACE_WIN32) +# define ACE_INVALID_SEM_KEY 0 +#else /* !ACE_WIN32 */ +# define ACE_INVALID_SEM_KEY -1 +#endif /* ACE_WIN32 */ + +#if !defined (IPC_PRIVATE) +# define IPC_PRIVATE ACE_INVALID_SEM_KEY +#endif /* IPC_PRIVATE */ + +#if !defined (IPC_STAT) +# define IPC_STAT 0 +#endif /* IPC_STAT */ + +#if !defined (IPC_CREAT) +# define IPC_CREAT 0 +#endif /* IPC_CREAT */ + +#if !defined (IPC_NOWAIT) +# define IPC_NOWAIT 0 +#endif /* IPC_NOWAIT */ + +#if !defined (IPC_RMID) +# define IPC_RMID 0 +#endif /* IPC_RMID */ + +#if !defined (IPC_EXCL) +# define IPC_EXCL 0 +#endif /* IPC_EXCL */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_SYS_OS_IPC_H */ diff --git a/dep/acelite/ace/os_include/sys/os_loadavg.h b/dep/acelite/ace/os_include/sys/os_loadavg.h new file mode 100644 index 00000000000..6eeeb69be0a --- /dev/null +++ b/dep/acelite/ace/os_include/sys/os_loadavg.h @@ -0,0 +1,41 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_loadavg.h + * + * loadavg functions + * + * $Id: os_loadavg.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Johnny Willemsen + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_SYS_OS_LOADAVG_H +#define ACE_OS_INCLUDE_SYS_OS_LOADAVG_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_SYS_LOADAVG_H) +# include /**/ +#endif /* ACE_HAS_SYS_LOADAVG_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_SYS_OS_LOADAVG_H */ diff --git a/dep/acelite/ace/os_include/sys/os_mman.h b/dep/acelite/ace/os_include/sys/os_mman.h new file mode 100644 index 00000000000..b39fc48cbc4 --- /dev/null +++ b/dep/acelite/ace/os_include/sys/os_mman.h @@ -0,0 +1,122 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_mman.h + * + * memory management declarations + * + * $Id: os_mman.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_SYS_OS_MMAN_H +#define ACE_OS_INCLUDE_SYS_OS_MMAN_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_types.h" + +#if defined (ACE_LACKS_MMAP) +# define ACE_LACKS_SYS_MMAN_H +#endif /* ACE_LACKS_MMAP */ + +#if !defined (ACE_LACKS_SYS_MMAN_H) + // Fixes a problem with HP/UX. +# if defined (ACE_HAS_BROKEN_MMAP_H) + extern "C" { +# endif /* ACE_HAS_BROKEN_MMAP_H */ +# include /**/ +# if defined (ACE_HAS_BROKEN_MMAP_H) + } +# endif /* ACE_HAS_BROKEN_MMAP_H */ +#endif /* ACE_LACKS_SYS_MMAN_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#if defined (ACE_LACKS_SYS_MMAN_H) && !defined (ACE_WIN32) +# define PROT_READ 0 +# define PROT_WRITE 0 +# define PROT_EXEC 0 +# define PROT_NONE 0 +# define PROT_RDWR 0 +# define MAP_PRIVATE 0 +# define MAP_SHARED 0 +# define MAP_FIXED 0 +#elif defined (ACE_WIN32) + // These two may be used for internal flags soon: +# define MAP_PRIVATE 1 +# define MAP_SHARED 2 +# define MAP_FIXED 4 + // MMAP flags +# define PROT_READ PAGE_READONLY +# define PROT_WRITE PAGE_READWRITE +# define PROT_RDWR PAGE_READWRITE +/* If we can find suitable use for these flags, here they are: +PAGE_WRITECOPY +PAGE_EXECUTE +PAGE_EXECUTE_READ +PAGE_EXECUTE_READWRITE +PAGE_EXECUTE_WRITECOPY +PAGE_GUARD +PAGE_NOACCESS +PAGE_NOCACHE */ +#endif /* !ACE_LACKS_SYS_MMAN_H && !ACE_WIN32*/ + +# if !defined (ACE_MAP_PRIVATE) +# define ACE_MAP_PRIVATE MAP_PRIVATE +# endif /* ! ACE_MAP_PRIVATE */ + +# if !defined (ACE_MAP_SHARED) +# define ACE_MAP_SHARED MAP_SHARED +# endif /* ! ACE_MAP_SHARED */ + +# if !defined (ACE_MAP_FIXED) +# define ACE_MAP_FIXED MAP_FIXED +# endif /* ! ACE_MAP_FIXED */ + +# if !defined (MAP_FAILED) || defined (ACE_HAS_BROKEN_MAP_FAILED) +# undef MAP_FAILED +# define MAP_FAILED ((void *) -1) +# elif defined (ACE_HAS_LONG_MAP_FAILED) +# undef MAP_FAILED +# define MAP_FAILED ((void *) -1L) +# endif /* !MAP_FAILED || ACE_HAS_BROKEN_MAP_FAILED */ + +#if !defined (PROT_RDWR) +# define PROT_RDWR (PROT_READ|PROT_WRITE) +#endif /* PROT_RDWR */ + +# if defined (ACE_WIN32) + // Needed to map calls to NT transparently. +# define MS_ASYNC 0 +# define MS_INVALIDATE 0 +# endif /* ACE_WIN32 */ + +# if !defined (MS_SYNC) +# define MS_SYNC 0x0 +# endif /* !MS_SYNC */ + +#if !defined (ACE_LACKS_MADVISE) && defined (ACE_LACKS_MADVISE_PROTOTYPE) + extern "C" int madvise(caddr_t, size_t, int); +#endif /* !ACE_LACKS_MADVISE && ACE_LACKS_MADVISE_PROTOTYPE */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_SYS_OS_MMAN_H */ diff --git a/dep/acelite/ace/os_include/sys/os_msg.h b/dep/acelite/ace/os_include/sys/os_msg.h new file mode 100644 index 00000000000..fa7edad1eb1 --- /dev/null +++ b/dep/acelite/ace/os_include/sys/os_msg.h @@ -0,0 +1,55 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_msg.h + * + * XSI message queue structures + * + * $Id: os_msg.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_SYS_OS_MSG_H +#define ACE_OS_INCLUDE_SYS_OS_MSG_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_ipc.h" + +#if !defined (ACE_LACKS_SYS_MSG_H) +# include /**/ +#endif /* !ACE_LACKS_SYS_MSG_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + + // Declare opaque type. Needed for ACE_OS wrappers on systems + // without SysV IPC. + struct msqid_ds; + +#if defined (ACE_LACKS_SYSV_MSQ_PROTOS) + int msgget (key_t, int); + int msgrcv (int, void *, size_t, long, int); + int msgsnd (int, const void *, size_t, int); + int msgctl (int, int, struct msqid_ds *); +#endif /* ACE_LACKS_SYSV_MSQ_PROTOS */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_SYS_OS_MSG_H */ diff --git a/dep/acelite/ace/os_include/sys/os_pstat.h b/dep/acelite/ace/os_include/sys/os_pstat.h new file mode 100644 index 00000000000..dcb3467b623 --- /dev/null +++ b/dep/acelite/ace/os_include/sys/os_pstat.h @@ -0,0 +1,42 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_pstat.h + * + * pstat functions + * + * $Id: os_pstat.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Johnny Willemsen + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_SYS_OS_PSTAT_H +#define ACE_OS_INCLUDE_SYS_OS_PSTAT_H + +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_SYS_PSTAT_H) +# include /**/ +# include /**/ +#endif /* ACE_HAS_SYS_PSTAT_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_SYS_OS_PSTAT_H */ diff --git a/dep/acelite/ace/os_include/sys/os_resource.h b/dep/acelite/ace/os_include/sys/os_resource.h new file mode 100644 index 00000000000..23486b616e2 --- /dev/null +++ b/dep/acelite/ace/os_include/sys/os_resource.h @@ -0,0 +1,104 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_resource.h + * + * definitions for XSI resource operations + * + * $Id: os_resource.h 81697 2008-05-14 18:33:11Z johnnyw $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_SYS_OS_RESOURCE_H +#define ACE_OS_INCLUDE_SYS_OS_RESOURCE_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_time.h" +#include "ace/os_include/sys/os_types.h" + +#if !defined (ACE_LACKS_SYS_RESOURCE_H) +# include /**/ +#endif /* !ACE_LACKS_SYS_RESOURCE_H */ + +#if defined (ACE_HAS_SYS_SYSTEMINFO_H) +# include /**/ +#endif /* ACE_HAS_SYS_SYSTEMINFO_H */ + +#if defined (ACE_HAS_SYS_SYSCALL_H) +# include /**/ +#endif /* ACE_HAS_SYS_SYSCALL_H */ + +// prusage_t is defined in +#if defined (ACE_HAS_PROC_FS) +# include /**/ +#endif /* ACE_HAS_PROC_FS */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +// There must be a better way to do this... +#if !defined (RLIMIT_NOFILE) && !defined (ACE_LACKS_RLIMIT_NOFILE) +# if defined (linux) || defined (AIX) || defined (SCO) +# if defined (RLIMIT_OFILE) +# define RLIMIT_NOFILE RLIMIT_OFILE +# else +# define RLIMIT_NOFILE 200 +# endif /* RLIMIT_OFILE */ +# endif /* defined (linux) || defined (AIX) || defined (SCO) */ +#endif /* RLIMIT_NOFILE */ + +#if defined (ACE_WIN32) +# define RUSAGE_SELF 1 + /// Fake the UNIX rusage structure. Perhaps we can add more to this + /// later on? + struct rusage + { + FILETIME ru_utime; + FILETIME ru_stime; + }; +#endif /* ACE_WIN32 */ + +#if defined (ACE_LACKS_RLIMIT_PROTOTYPE) + int getrlimit (int resource, struct rlimit *rlp); + int setrlimit (int resource, const struct rlimit *rlp); +#endif /* ACE_LACKS_RLIMIT_PROTOTYPE */ + +#if defined (ACE_HAS_PRUSAGE_T) + typedef prusage_t ACE_Rusage; +#elif defined (ACE_HAS_GETRUSAGE) + typedef rusage ACE_Rusage; +#else + typedef int ACE_Rusage; +#endif /* ACE_HAS_PRUSAGE_T */ + +#if !defined (ACE_WIN32) +// These prototypes are chronically lacking from many versions of UNIX. +# if !defined (ACE_HAS_GETRUSAGE_PROTOTYPE) + int getrusage (int who, struct rusage *rusage); +# endif /* ! ACE_HAS_GETRUSAGE_PROTOTYPE */ + +# if defined (ACE_LACKS_SYSCALL) + int syscall (int, ACE_HANDLE, struct rusage *); +# endif /* ACE_LACKS_SYSCALL */ +#endif /* !ACE_WIN32 */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_SYS_OS_RESOURCE_H */ diff --git a/dep/acelite/ace/os_include/sys/os_select.h b/dep/acelite/ace/os_include/sys/os_select.h new file mode 100644 index 00000000000..59473aff398 --- /dev/null +++ b/dep/acelite/ace/os_include/sys/os_select.h @@ -0,0 +1,61 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_select.h + * + * select types + * + * $Id: os_select.h 85015 2009-04-03 12:27:59Z johnnyw $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_SYS_OS_SELECT_H +#define ACE_OS_INCLUDE_SYS_OS_SELECT_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_time.h" +#include "ace/os_include/os_signal.h" +#include "ace/os_include/os_unistd.h" + +#if !defined (ACE_LACKS_SYS_SELECT_H) +# include /**/ +#endif /* !ACE_LACKS_SYS_SELECT_H */ + +#if defined (ACE_USES_SELECTLIB_H) && defined (ACE_LACKS_SYS_SELECT_H) +# include /**/ +#endif /* ACE_USES_SELECTLIB_H && ACE_LACKS_SYS_SELECT_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#if defined (ACE_LACKS_FD_MASK) + typedef long fd_mask; +#endif /* __QNX__ */ + +#if defined (ACE_WIN32) + // This will help until we figure out everything: +# define NFDBITS 32 /* only used in unused functions... */ +#elif defined (ACE_LACKS_NFDBITS) +# define NFDBITS (sizeof(fd_mask) * NBBY) /* bits per mask */ +#endif /* ACE_WIN32 */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_SYS_OS_SELECT_H */ diff --git a/dep/acelite/ace/os_include/sys/os_sem.h b/dep/acelite/ace/os_include/sys/os_sem.h new file mode 100644 index 00000000000..926092b7d06 --- /dev/null +++ b/dep/acelite/ace/os_include/sys/os_sem.h @@ -0,0 +1,90 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_sem.h + * + * XSI semaphore facility + * + * $Id: os_sem.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_SYS_OS_SEM_H +#define ACE_OS_INCLUDE_SYS_OS_SEM_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_ipc.h" + +#if !defined (ACE_LACKS_SYS_SEM_H) +# include /**/ +#endif /* !ACE_LACKS_SYS_SEM_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +# if !defined (GETVAL) +# define GETVAL 0 +# endif /* GETVAL */ + +# if !defined (SETVAL) +# define SETVAL 0 +# endif /* SETVAL */ + +# if !defined (GETALL) +# define GETALL 0 +# endif /* GETALL */ + +# if !defined (SETALL) +# define SETALL 0 +# endif /* SETALL */ + +# if !defined (SEM_UNDO) +# define SEM_UNDO 0 +# endif /* SEM_UNDO */ + +#if defined (ACE_LACKS_SEMBUF_T) + struct sembuf + { + /// semaphore # + unsigned short sem_num; + + /// semaphore operation + short sem_op; + + /// operation flags + short sem_flg; + }; +#endif /* ACE_LACKS_SEMBUF_T */ + +#if !defined (ACE_HAS_SEMUN) || (defined (__GLIBC__) && defined (_SEM_SEMUN_UNDEFINED)) + union semun + { + /// value for SETVAL + int val; + /// buffer for IPC_STAT & IPC_SET + struct semid_ds *buf; + /// array for GETALL & SETALL + u_short *array; + }; +#endif /* !ACE_HAS_SEMUN || (defined (__GLIBC__) && defined (_SEM_SEMUN_UNDEFINED)) */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_SYS_OS_SEM_H */ diff --git a/dep/acelite/ace/os_include/sys/os_shm.h b/dep/acelite/ace/os_include/sys/os_shm.h new file mode 100644 index 00000000000..79d502fec0d --- /dev/null +++ b/dep/acelite/ace/os_include/sys/os_shm.h @@ -0,0 +1,48 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_shm.h + * + * XSI shared memory facility + * + * $Id: os_shm.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_SYS_OS_SHM_H +#define ACE_OS_INCLUDE_SYS_OS_SHM_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_ipc.h" + +#if !defined (ACE_LACKS_SYS_SHM_H) +# include /**/ +#endif /* !ACE_LACKS_SYS_SHM_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + + // Declare opaque type. Needed for ACE_OS wrappers on systems + // without SysV IPC. + struct shmid_ds; + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_SYS_OS_SHM_H */ diff --git a/dep/acelite/ace/os_include/sys/os_socket.h b/dep/acelite/ace/os_include/sys/os_socket.h new file mode 100644 index 00000000000..676041747ba --- /dev/null +++ b/dep/acelite/ace/os_include/sys/os_socket.h @@ -0,0 +1,307 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_socket.h + * + * main sockets header + * + * $Id: os_socket.h 85015 2009-04-03 12:27:59Z johnnyw $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_SYS_OS_SOCKET_H +#define ACE_OS_INCLUDE_SYS_OS_SOCKET_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_uio.h" + +#if !defined (ACE_LACKS_SYS_SOCKET_H) +# include /**/ +#endif /* !ACE_LACKS_SYS_SOCKET_H */ + +#if defined (ACE_USES_SOCKLIB_H) +# include /**/ +#endif /* ACE_USES_SOCKLIB_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#if !defined (ACE_HAS_MSG) && !defined (SCO) + struct msghdr {}; +#endif /* ACE_HAS_MSG */ + +#if defined (ACE_HAS_MSG) && defined (ACE_LACKS_MSG_ACCRIGHTS) +# if !defined (msg_accrights) +# undef msg_control +# define msg_accrights msg_control +# endif /* ! msg_accrights */ + +# if !defined (msg_accrightslen) +# undef msg_controllen +# define msg_accrightslen msg_controllen +# endif /* ! msg_accrightslen */ +#endif /* ACE_HAS_MSG && ACE_LACKS_MSG_ACCRIGHTS */ + +# if defined (ACE_LACKS_SOCKADDR) + struct sockaddr { + u_char sa_len; /* total length */ + u_char sa_family; /* address family */ + char sa_data[14]; /* actually longer; address value */ + }; +# endif /* ACE_LACKS_SOCKADDR */ + +# if defined (ACE_LACKS_LINGER) + struct linger { + int l_onoff; /* option on/off */ + int l_linger; /* linger time */ + }; +# endif /* ACE_LACKS_LINGER */ + +#if defined (ACE_WIN32) + struct msghdr + { + /// Optional address + sockaddr * msg_name; + + /// Size of address + int msg_namelen; + + /// Scatter/gather array + iovec *msg_iov; + + /// # elements in msg_iov + int msg_iovlen; + + /// Access rights sent/received + caddr_t msg_accrights; + + int msg_accrightslen; + }; +#endif /* ACE_WIN32 */ + +#if defined (ACE_HAS_4_4BSD_SENDMSG_RECVMSG) + // Control message size to pass a file descriptor. +# define ACE_BSD_CONTROL_MSG_LEN sizeof (struct cmsghdr) + sizeof (ACE_HANDLE) +#endif /* ACE_HAS_4_4BSD_SENDMSG_RECVMSG */ + +// Increase the range of "address families". Please note that this +// must appear _after_ the include of sys/socket.h, for the AF_FILE +// definition on Linux/glibc2. +#if !defined (AF_ANY) +# define AF_ANY (-1) +#endif /* AF_ANY */ + +#if !defined (AF_UNSPEC) +# define AF_UNSPEC 0 +#endif /* AF_UNSPEC */ + +#if !defined (AF_LOCAL) +# define AF_LOCAL 1 +#endif /* AF_LOCAL */ + +#if !defined (AF_UNIX) +# define AF_UNIX AF_LOCAL +#endif /* AF_UNIX */ + +#if !defined (AF_INET) +# define AF_INET 2 +#endif /* AF_INET */ + +#if !defined (PF_INET) +# define PF_INET AF_INET +#endif /* PF_INET */ + +#if !defined (PF_LOCAL) +# define PF_LOCAL AF_LOCAL +#endif /* PF_LOCAL */ + +#if !defined (PF_UNIX) +# define PF_UNIX PF_LOCAL +#endif /* PF_UNIX */ + +#if !defined (AF_MAX) +# define AF_MAX 29 +#endif /* AF_MAX */ + +#if !defined (PF_UNSPEC) +# define PF_UNSPEC 0 +#endif /* PF_UNSPEC */ + +#define AF_SPIPE (AF_MAX + 1) +#if !defined (AF_FILE) +# define AF_FILE (AF_MAX + 2) +#endif /* ! AF_FILE */ +#define AF_DEV (AF_MAX + 3) +#define AF_UPIPE (AF_SPIPE) + +#if !defined (MSG_OOB) +# define MSG_OOB 0x1 +#endif /* MSG_OOB */ + +#if !defined (MSG_PEEK) +# define MSG_PEEK 0x2 +#endif /* MSG_PEEK */ + +#if !defined (SOCK_STREAM) +# define SOCK_STREAM 1 +#endif /* SOCK_STREAM */ + +#if !defined (SOCK_DGRAM) +# define SOCK_DGRAM 2 +#endif /* SOCK_DGRAM */ + +#if !defined (SOCK_SEQPACKET) +# define SOCK_SEQPACKET 5 +#endif /* SOCK_SEQPACKET */ + +#if !defined (SOL_SOCKET) +# define SOL_SOCKET 0xffff +#endif /* SOL_SOCKET */ + +#if !defined (SO_REUSEADDR) +# define SO_REUSEADDR 0x0004 +#endif /* SO_REUSEADDR */ + +#if !defined (SO_LINGER) +# define SO_LINGER 0x0080 +#endif /* SO_LINGER */ + +#if !defined (SO_SNDBUF) +# define SO_SNDBUF 0x1001 +#endif /* SO_SNDBUF */ + +#if !defined (SO_RCVBUF) +# define SO_RCVBUF 0x1002 +#endif /* SO_RCVBUF */ + +#if !defined (SO_BROADCAST) +# define SO_BROADCAST 0x0020 +#endif /* SO_BROADCAST */ + +#if !defined (SO_ERROR) +# define SO_ERROR 0x1007 +#endif /* SO_ERROR */ + +#if !defined (SCM_RIGHTS) +# define SCM_RIGHTS 0x01 +#endif /* SCM_RIGHTS */ + +#if defined (ACE_HAS_IPV6) +# if defined (ACE_USES_IPV4_IPV6_MIGRATION) +# define ACE_ADDRESS_FAMILY_INET AF_UNSPEC +# define ACE_PROTOCOL_FAMILY_INET PF_UNSPEC +# else +# define ACE_ADDRESS_FAMILY_INET AF_INET6 +# define ACE_PROTOCOL_FAMILY_INET PF_INET6 +# endif /* ACE_USES_IPV4_IPV6_MIGRATION */ +#else /* !ACE_HAS_IPV6 */ +# define ACE_ADDRESS_FAMILY_INET AF_INET +# define ACE_PROTOCOL_FAMILY_INET PF_INET +#endif /* ACE_HAS_IPV6 */ + +#if !defined (ACE_HAS_SOCK_BUF_SIZE_MAX_VALUE) +#define ACE_HAS_SOCK_BUF_SIZE_MAX_VALUE SSIZE_MAX +#endif /* ACE_HAS_SOCK_BUF_SIZE_MAX_VALUE */ + +#if defined (ACE_HAS_SOCKLEN_T) +# if defined (__hpux) + /* + ** HP-UX supplies the socklen_t type unless some feature set less than + ** _XOPEN_SOURCE_EXTENDED is specifically requested. However, it only + ** actually uses the socklen_t type in supplied socket functions if + ** _XOPEN_SOURCE_EXTENDED is specifically requested. So, for example, + ** the compile options ACE usually uses (includes -mt) cause _HPUX_SOURCE + ** to be set, which sets _INCLUDE_XOPEN_SOURCE_EXTENDED (causing socklen_t + ** to be defined) but _not_ _XOPEN_SOURCE_EXTENDED (causing socket functions + ** to use int, not socklen_t). React to this situation here... + */ +# if defined (_XOPEN_SOURCE_EXTENDED) +typedef socklen_t ACE_SOCKET_LEN; +# else +typedef int ACE_SOCKET_LEN; +# endif /* _XOPEN_SOURCE_EXTENDED */ +# else +typedef socklen_t ACE_SOCKET_LEN; +# endif /* __hpux */ +#elif defined (ACE_HAS_SIZET_SOCKET_LEN) +typedef size_t ACE_SOCKET_LEN; +#else +typedef int ACE_SOCKET_LEN; +#endif /* ACE_HAS_SIZET_SOCKET_LEN */ + +#if defined (ACE_HAS_NETLINK) +# include /**/ +# include /**/ +# define ACE_PROTOCOL_FAMILY_NETLINK AF_NETLINK +#endif + +#if defined (ACE_HAS_LKSCTP) +extern "C" +{ +#include /**/ +#include /**/ +} +#endif /* ACE_HAS_LKSCTP */ + +# if defined (ACE_LACKS_TIMEDWAIT_PROTOTYPES) + + ssize_t recv_timedwait (ACE_HANDLE handle, + char *buf, + int len, + int flags, + struct timespec *timeout); + + ssize_t recvmsg_timedwait (ACE_HANDLE handle, + struct msghdr *msg, + int flags, + struct timespec *timeout); + + ssize_t recvfrom_timedwait (ACE_HANDLE handle, + char *buf, + int len, + int flags, + struct sockaddr *addr, + int *addrlen, + struct timespec *timeout); + + ssize_t send_timedwait (ACE_HANDLE handle, + const char *buf, + int len, + int flags, + struct timespec *timeout); + + ssize_t sendmsg_timedwait (ACE_HANDLE handle, + const struct msghdr *msg, + int flags, + struct timespec *timeout); + + ssize_t sendto_timedwait (ACE_HANDLE handle, + const char *buf, + int len, + int flags, + const struct sockaddr *addr, + int addrlen, + struct timespec *timeout); + +# endif /* ACE_LACKS_TIMEDWAIT_PROTOTYPES */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_SYS_OS_SOCKET_H */ diff --git a/dep/acelite/ace/os_include/sys/os_stat.h b/dep/acelite/ace/os_include/sys/os_stat.h new file mode 100644 index 00000000000..19b126500c1 --- /dev/null +++ b/dep/acelite/ace/os_include/sys/os_stat.h @@ -0,0 +1,157 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_stat.h + * + * data returned by the stat() function + * + * $Id: os_stat.h 85057 2009-04-08 10:59:58Z msmit $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_SYS_OS_STAT_H +#define ACE_OS_INCLUDE_SYS_OS_STAT_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_types.h" + +#if defined (ACE_HAS_DIRECT_H) +# include /**/ +#endif /* ACE_HAS_DIRECT_H */ + +#if !defined (ACE_LACKS_SYS_STAT_H) +# include /**/ +#endif /* !ACE_LACKS_SYS_STAT_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#if defined (ACE_LACKS_MODE_MASKS) +// MODE MASKS + +// the following macros are for POSIX conformance. + +# if !defined (ACE_HAS_USER_MODE_MASKS) +# if !defined (S_IRWXU) +# define S_IRWXU 00700 /* read, write, execute: owner. */ +# endif /* !S_IRWXU */ +# if !defined (S_IRUSR) +# define S_IRUSR 00400 /* read permission: owner. */ +# endif /* !S_IRUSR */ +# if !defined (S_IWUSR) +# define S_IWUSR 00200 /* write permission: owner. */ +# endif /* !S_IWUSR */ +# if !defined (S_IXUSR) +# define S_IXUSR 00100 /* execute permission: owner. */ +# endif /* !S_IXUSR */ +# endif /* ACE_HAS_USER_MODE_MASKS */ + +# if !defined (S_IRWXG) +# define S_IRWXG 00070 +# endif /* S_IRWXG */ +# if !defined (S_IRGRP) +# define S_IRGRP 00040 +# endif /* S_IRGRP */ +# if !defined (S_IWGRP) +# define S_IWGRP 00020 +# endif /* S_IWGRP */ +# if !defined (S_IXGRP) +# define S_IXGRP 00010 +# endif /* S_IXGRP */ +# if !defined (S_IRWXO) +# define S_IRWXO 00007 +# endif /* S_IRWXO */ +# if !defined (S_IROTH) +# define S_IROTH 00004 +# endif /* S_IROTH */ +# if !defined (S_IWOTH) +# define S_IWOTH 00002 +# endif /* S_IWOTH */ +# if !defined (S_IXOTH) +# define S_IXOTH 00001 +# endif /* S_IXOTH */ + +// WinCE's S_IFLNK is defined with the other bits, below. +#if !defined (S_IFLNK) && !defined (ACE_HAS_WINCE) +#define S_IFLNK 0200000 +#endif /* S_IFLNK && !ACE_HAS_WINCE */ + +#endif /* ACE_LACKS_MODE_MASKS */ + +// Some systems (VxWorks) don't define S_ISLNK +#if !defined (S_ISLNK) +# if defined (S_IFLNK) +# define S_ISLNK(mode) (((mode)&S_IFLNK) == S_IFLNK) +# else +# define S_ISLNK(mode) 0 +# endif /* S_IFLNK */ +#endif /* S_ISLNK */ + +#if defined (ACE_HAS_WINCE) + +// Translate the WinCE bits into names expected by our callers. +// The dwFileAttributes parameter doesn't have protection info, so +// S_IFMT is the whole thing. Since there are no symbolic links, S_IFLNK is 0. +# define S_IFMT 0xFFFF +# define S_IFDIR FILE_ATTRIBUTE_DIRECTORY +# define S_IFREG FILE_ATTRIBUTE_NORMAL +# define S_IFLNK 0 + +# if !defined (__MINGW32__) + // Since CE does not have _stat by default as NT/2000 does, the 'stat' + // struct defined here will be used. Also note that CE file system + // struct is only for the CE 3.0 or later. + // Refer to the WCHAR.H from Visual C++ and WIBASE.H from eVC 3.0. + struct stat + { + /// always 0 on Windows platforms + dev_t st_dev; + + /// always 0 on Windows platforms + dev_t st_rdev; + + /// file attribute + mode_t st_mode; + + /// number of hard links + nlink_t st_nlink; + + /// time of last access + time_t st_atime; + + /// time of last data modification + time_t st_mtime; + + /// time of creation + time_t st_ctime; + + /// file size, in bytes + ACE_OFF_T st_size; + + // Following members do not have direct conversion in Window platforms. + //u_long st_blksize; // optimal blocksize for I/O + //u_long st_flags; // user defined flags for file + }; + #endif +#endif /* ACE_HAS_WINCE */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_SYS_OS_STAT_H */ diff --git a/dep/acelite/ace/os_include/sys/os_statvfs.h b/dep/acelite/ace/os_include/sys/os_statvfs.h new file mode 100644 index 00000000000..7988c4f5060 --- /dev/null +++ b/dep/acelite/ace/os_include/sys/os_statvfs.h @@ -0,0 +1,42 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_statvfs.h + * + * VFS File System information structure + * + * $Id: os_statvfs.h 81692 2008-05-14 12:25:02Z johnnyw $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_SYS_OS_STATVFS_H +#define ACE_OS_INCLUDE_SYS_OS_STATVFS_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_SYS_STATVFS_H) +# include /**/ +#endif /* !ACE_LACKS_SYS_STATVFS_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_SYS_OS_STATVFS_H */ diff --git a/dep/acelite/ace/os_include/sys/os_sysctl.h b/dep/acelite/ace/os_include/sys/os_sysctl.h new file mode 100644 index 00000000000..ee51cd7db65 --- /dev/null +++ b/dep/acelite/ace/os_include/sys/os_sysctl.h @@ -0,0 +1,41 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_sysctl.h + * + * declarations for sysctl + * + * $Id: os_sysctl.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Johnny Willemsen + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_SYS_OS_SYSCTL_H +#define ACE_OS_INCLUDE_SYS_OS_SYSCTL_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_SYS_SYSCTL_H) +# include /**/ +#endif /* !ACE_LACKS_SYS_SYSCTL_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_SYS_OS_SYSCTL_H */ diff --git a/dep/acelite/ace/os_include/sys/os_sysinfo.h b/dep/acelite/ace/os_include/sys/os_sysinfo.h new file mode 100644 index 00000000000..7aca1f44d1f --- /dev/null +++ b/dep/acelite/ace/os_include/sys/os_sysinfo.h @@ -0,0 +1,39 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_sysinfo.h + * + * $Id: os_sysinfo.h 81692 2008-05-14 12:25:02Z johnnyw $ + * + * @author Johnny Willemsen + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_SYS_OS_SYSINFO_H +#define ACE_OS_INCLUDE_SYS_OS_SYSINFO_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if defined (ACE_HAS_SYS_SYSINFO_H) +# include /**/ +#endif /* ACE_HAS_SYS_SYSINFO_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_SYS_OS_SYSINFO_H */ diff --git a/dep/acelite/ace/os_include/sys/os_time.h b/dep/acelite/ace/os_include/sys/os_time.h new file mode 100644 index 00000000000..937ceebaa13 --- /dev/null +++ b/dep/acelite/ace/os_include/sys/os_time.h @@ -0,0 +1,56 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_time.h + * + * time types + * + * $Id: os_time.h 85365 2009-05-18 08:27:42Z johnnyw $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_SYS_OS_TIME_H +#define ACE_OS_INCLUDE_SYS_OS_TIME_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_types.h" + +#if !defined (ACE_LACKS_SYS_TIME_H) +# include /**/ +#endif /* !ACE_LACKS_SYS_TIME_H */ + +#if defined (ACE_VXWORKS) && (ACE_VXWORKS == 0x620) +# include /**/ // VxWorks 6.2 defined timeval in time.h +#endif + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#if defined (ACE_HAS_SVR4_GETTIMEOFDAY) + int gettimeofday (struct timeval *tp, void * = 0); +#elif defined (ACE_HAS_OSF1_GETTIMEOFDAY) + int gettimeofday (struct timeval *tp, struct timezone * = 0); +#elif defined (ACE_HAS_VOIDPTR_GETTIMEOFDAY) +# define ACE_HAS_SVR4_GETTIMEOFDAY +#endif /* ACE_HAS_SVR4_GETTIMEOFDAY */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_SYS_OS_TIME_H */ diff --git a/dep/acelite/ace/os_include/sys/os_timeb.h b/dep/acelite/ace/os_include/sys/os_timeb.h new file mode 100644 index 00000000000..cf10566ed99 --- /dev/null +++ b/dep/acelite/ace/os_include/sys/os_timeb.h @@ -0,0 +1,44 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_timeb.h + * + * additional definitions for date and time + * + * $Id: os_timeb.h 83306 2008-10-17 12:19:53Z johnnyw $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_SYS_OS_TIMEB_H +#define ACE_OS_INCLUDE_SYS_OS_TIMEB_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_types.h" + +#if !defined (ACE_LACKS_SYS_TIMEB_H) +# include /**/ +#endif /* !ACE_LACKS_SYS_TIMEB_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_SYS_OS_TIMEB_H */ diff --git a/dep/acelite/ace/os_include/sys/os_times.h b/dep/acelite/ace/os_include/sys/os_times.h new file mode 100644 index 00000000000..617b416ec56 --- /dev/null +++ b/dep/acelite/ace/os_include/sys/os_times.h @@ -0,0 +1,44 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_times.h + * + * file access and modification times structure + * + * $Id: os_times.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_SYS_OS_TIMES_H +#define ACE_OS_INCLUDE_SYS_OS_TIMES_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_types.h" + +#if !defined (ACE_LACKS_SYS_TIMES_H) +# include /**/ +#endif /* !ACE_LACKS_SYS_TIMES_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_SYS_OS_TIMES_H */ diff --git a/dep/acelite/ace/os_include/sys/os_types.h b/dep/acelite/ace/os_include/sys/os_types.h new file mode 100644 index 00000000000..9638265378d --- /dev/null +++ b/dep/acelite/ace/os_include/sys/os_types.h @@ -0,0 +1,157 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_types.h + * + * data types + * + * $Id: os_types.h 88515 2010-01-13 08:47:38Z johnnyw $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_SYS_OS_TYPES_H +#define ACE_OS_INCLUDE_SYS_OS_TYPES_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/os_stddef.h" + +#if !defined (ACE_LACKS_SYS_TYPES_H) +# include /**/ +#endif /* !ACE_LACKS_SYS_TYPES_H */ + +#if defined (ACE_HAS_TYPES_H) +# include /**/ +#endif /* ACE_HAS_TYPES_H */ + +# if defined (ACE_USES_STD_NAMESPACE_FOR_STDC_LIB) && \ + (ACE_USES_STD_NAMESPACE_FOR_STDC_LIB != 0) +using std::time_t; +# endif /* ACE_USES_STD_NAMESPACE_FOR_STDC_LIB */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +typedef double ACE_timer_t; + +// todo: don't forget to clean this up! ;-) +#if !defined (ACE_HAS_CLOCK_GETTIME) && !(defined (_CLOCKID_T_) || defined (_CLOCKID_T)) + typedef int clockid_t; +# if !defined (CLOCK_REALTIME) +# define CLOCK_REALTIME 0 +# endif /* CLOCK_REALTIME */ +#endif /* ! ACE_HAS_CLOCK_GETTIME && ! _CLOCKID_T_ */ + +#if defined (ACE_LACKS_DEV_T) + typedef unsigned int dev_t; +#endif /* ACE_LACKS_DEV_T */ + +#if defined (ACE_HAS_WINCE) + typedef long off_t; +#endif + +#if defined(ACE_WIN32) && defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS==64) + typedef __int64 ACE_OFF_T; +#else + typedef off_t ACE_OFF_T; +#endif + +#if defined (ACE_SIZEOF_LONG) && ACE_SIZEOF_LONG == 8 + typedef off_t ACE_LOFF_T; +#elif defined (ACE_HAS_RTEMS) || defined (__FreeBSD__) || defined (__NetBSD__) || defined (__OpenBSD__) || defined (__APPLE__) || defined(ACE_MVS) || defined(__INTERIX) || \ + (defined (ACE_OPENVMS) && defined (_LARGEFILE)) + typedef off_t ACE_LOFF_T; +#elif defined (__sgi) || defined (AIX) || defined (HPUX) || defined (__QNX__) + typedef off64_t ACE_LOFF_T; +#elif defined (__sun) + typedef offset_t ACE_LOFF_T; +#elif defined (WIN32) + typedef __int64 ACE_LOFF_T; +#elif (defined (ACE_VXWORKS) && (ACE_VXWORKS <= 0x680)) || \ + defined (ACE_LYNXOS_MAJOR) || \ + (defined (ACE_OPENVMS) && !defined (_LARGEFILE)) || \ + defined (__TANDEM) + typedef long long ACE_LOFF_T; +#else + typedef loff_t ACE_LOFF_T; +#endif + +#if defined (ACE_LACKS_UID_T) +typedef long uid_t; +#endif /* ACE_LACKS_UID_T */ + +#if defined (ACE_LACKS_GID_T) +typedef long gid_t; +#endif /* ACE_LACKS_GID_T */ + +#if defined (ACE_LACKS_CADDR_T) +typedef char *caddr_t; +#endif /* ACE_LACKS_CADDR_T */ + +#if defined (ACE_LACKS_MODE_T) +typedef u_short mode_t; +#endif /* ACE_LACKS_MODE_T */ + +#if defined (ACE_LACKS_NLINK_T) +typedef DWORD nlink_t; +#endif /* ACE_LACKS_NLINK_T */ + +#if defined (ACE_LACKS_KEY_T) +# if defined (ACE_WIN32) + // Win32 doesn't use numeric values to name its semaphores, it uses + // strings! + typedef char *key_t; +# else + typedef int key_t; +# endif /* ACE_WIN32 */ +#endif /* ACE_LACKS_KEY_T */ + +#if !defined (ACE_HAS_SSIZE_T) +# if defined (ACE_WIN64) + typedef SSIZE_T ssize_t; +# else + typedef int ssize_t; +# endif /* ACE_WIN64 */ +#endif /* ACE_HAS_SSIZE_T */ + +#if defined (ACE_WIN32) + typedef DWORD ACE_exitcode; +#else + typedef int ACE_exitcode; +#endif /* ACE_WIN32 */ + +#if defined (ACE_LACKS_SUSECONDS_T) + typedef long suseconds_t; +#endif + +#if defined (ACE_LACKS_USECONDS_T) + typedef unsigned long useconds_t; +#endif + +#if defined (ACE_WIN32) && !defined(__MINGW32__) + typedef int pid_t; +#endif /* ACE_WIN32 */ + +# if !defined (ACE_INVALID_PID) +# define ACE_INVALID_PID ((pid_t) -1) +# endif /* ACE_INVALID_PID */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_SYS_OS_TYPES_H */ diff --git a/dep/acelite/ace/os_include/sys/os_uio.h b/dep/acelite/ace/os_include/sys/os_uio.h new file mode 100644 index 00000000000..7baaec57e75 --- /dev/null +++ b/dep/acelite/ace/os_include/sys/os_uio.h @@ -0,0 +1,77 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_uio.h + * + * definitions for vector I/O operations + * + * $Id: os_uio.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_SYS_OS_UIO_H +#define ACE_OS_INCLUDE_SYS_OS_UIO_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_types.h" +#include "ace/os_include/os_limits.h" + +#if !defined (ACE_LACKS_SYS_UIO_H) +# include /**/ +#endif /* !ACE_LACKS_SYS_UIO_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#if defined (ACE_LACKS_IOVEC) + /// The ordering of the fields in this struct is important. It has to + /// match those in WSABUF. + struct iovec + { + /// byte count to read/write + u_long iov_len; + /// data to be read/written + char *iov_base; + + // WSABUF is a Winsock2-only type. +# if defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0) + operator WSABUF &(void) { return *((WSABUF *) this); } +# endif /* defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0) */ + }; +#endif /* ACE_LACKS_IOVEC */ + + +# if defined (ACE_LACKS_TIMEDWAIT_PROTOTYPES) + + ssize_t readv_timedwait (ACE_HANDLE handle, + const iovec *iov, + int iovcnt, + struct timespec* timeout); + + ssize_t writev_timedwait (ACE_HANDLE handle, + const iovec *iov, + int iovcnt, + struct timespec *timeout); + +# endif /* ACE_LACKS_TIMEDWAIT_PROTOTYPES */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_SYS_OS_UIO_H */ diff --git a/dep/acelite/ace/os_include/sys/os_un.h b/dep/acelite/ace/os_include/sys/os_un.h new file mode 100644 index 00000000000..04a4da0bda9 --- /dev/null +++ b/dep/acelite/ace/os_include/sys/os_un.h @@ -0,0 +1,52 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_un.h + * + * definitions for UNIX domain sockets + * + * $Id: os_un.h 85015 2009-04-03 12:27:59Z johnnyw $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_SYS_OS_UN_H +#define ACE_OS_INCLUDE_SYS_OS_UN_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/sys/os_socket.h" + +#if !defined (ACE_LACKS_SYS_UN_H) +# include /**/ +#endif /* !ACE_LACKS_SYS_UN_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#if defined (ACE_LACKS_SOCKADDR_UN) +struct sockaddr_un { + short sun_family; // AF_UNIX. + char sun_path[108]; // path name. +}; +#endif /* ACE_LACKS_SOCKADDR_UN */ + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_SYS_OS_UN_H */ diff --git a/dep/acelite/ace/os_include/sys/os_utsname.h b/dep/acelite/ace/os_include/sys/os_utsname.h new file mode 100644 index 00000000000..d78d1e3463a --- /dev/null +++ b/dep/acelite/ace/os_include/sys/os_utsname.h @@ -0,0 +1,42 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_utsname.h + * + * system name structure + * + * $Id: os_utsname.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_SYS_OS_UTSNAME_H +#define ACE_OS_INCLUDE_SYS_OS_UTSNAME_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#if !defined (ACE_LACKS_SYS_UTSNAME_H) +# include /**/ +#endif /* !ACE_LACKS_SYS_UTSNAME_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_SYS_OS_UTSNAME_H */ diff --git a/dep/acelite/ace/os_include/sys/os_wait.h b/dep/acelite/ace/os_include/sys/os_wait.h new file mode 100644 index 00000000000..b7a219ac82e --- /dev/null +++ b/dep/acelite/ace/os_include/sys/os_wait.h @@ -0,0 +1,97 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file os_wait.h + * + * declarations for waiting + * + * $Id: os_wait.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Don Hinton + * @author This code was originally in various places including ace/OS.h. + */ +//============================================================================= + +#ifndef ACE_OS_INCLUDE_SYS_OS_WAIT_H +#define ACE_OS_INCLUDE_SYS_OS_WAIT_H + +#include /**/ "ace/pre.h" + +#include "ace/config-lite.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +#include "ace/os_include/os_signal.h" +#include "ace/os_include/sys/os_resource.h" + +#if !defined (ACE_LACKS_SYS_WAIT_H) +# include /**/ +#endif /* !ACE_LACKS_SYS_WAIT_H */ + +// Place all additions (especially function declarations) within extern "C" {} +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + + // Wrapping around wait status macros for platforms that + // lack them. + +# if !defined (WCOREDUMP) +# define WCOREDUMP(stat) 0 +# endif /* WCOREDUMP */ + +# if !defined (WNOHANG) +# define WNOHANG 0100 +# endif /* !WNOHANG */ + + // If the value of WIFEXITED(stat) is non-zero, this macro evaluates + // to the exit code that the child process exit(3C), or the value + // that the child process returned from main. Peaceful exit code is + // 0. +# if !defined (WEXITSTATUS) +# define WEXITSTATUS(stat) stat +# endif /* WEXITSTATUS */ + +# if !defined (WIFCONTINUED) +# define WIFCONTINUED(stat) 0 +# endif /* WIFCONTINUED */ + + // Evaluates to a non-zero value if status was returned for a child + // process that terminated normally. 0 means status wasn't + // returned. +# if !defined (WIFEXITED) +# define WIFEXITED(stat) 1 +# endif /* WIFEXITED */ + + // Evaluates to a non-zero value if status was returned for a child + // process that terminated due to the receipt of a signal. 0 means + // status wasnt returned. +# if !defined (WIFSIGNALED) +# define WIFSIGNALED(stat) 0 +# endif /* WIFSIGNALED */ + +# if !defined (WIFSTOPPED) +# define WIFSTOPPED(stat) 0 +# endif /* WIFSTOPPED */ + +# if !defined (WSTOPSIG) +# define WSTOPSIG(stat) 0 +# endif /* WSTOPSIG */ + + // If the value of WIFSIGNALED(stat) is non-zero, this macro + // evaluates to the number of the signal that caused the + // termination of the child process. +# if !defined (WTERMSIG) +# define WTERMSIG(stat) 0 +# endif /* WTERMSIG */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#include /**/ "ace/post.h" +#endif /* ACE_OS_INCLUDE_SYS_OS_WAIT_H */ diff --git a/dep/acelite/ace/post.h b/dep/acelite/ace/post.h new file mode 100644 index 00000000000..c393dfe50aa --- /dev/null +++ b/dep/acelite/ace/post.h @@ -0,0 +1,22 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file post.h + * + * $Id: post.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Christopher Kohlhoff + * + * This file restores the original alignment rules. + */ +//============================================================================= + +// No header guard +#if defined (_MSC_VER) +# pragma pack (pop) +#elif defined (__BORLANDC__) +# pragma option pop +# pragma nopushoptwarn +# pragma nopackwarning +#endif diff --git a/dep/acelite/ace/pre.h b/dep/acelite/ace/pre.h new file mode 100644 index 00000000000..7cc32d8ff30 --- /dev/null +++ b/dep/acelite/ace/pre.h @@ -0,0 +1,24 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file pre.h + * + * $Id: pre.h 80826 2008-03-04 14:51:23Z wotte $ + * + * @author Christopher Kohlhoff + * + * This file saves the original alignment rules and changes the alignment + * boundary to ACE's default. + */ +//============================================================================= + +// No header guard +#if defined (_MSC_VER) +# pragma warning (disable:4103) +# pragma pack (push, 8) +#elif defined (__BORLANDC__) +# pragma option push -a8 -b -Ve- -Vx- -w-rvl -w-rch -w-ccc -w-obs -w-aus -w-pia -w-inl -w-sig +# pragma nopushoptwarn +# pragma nopackwarning +#endif diff --git a/dep/acelite/ace/streams.h b/dep/acelite/ace/streams.h new file mode 100644 index 00000000000..396a67c712e --- /dev/null +++ b/dep/acelite/ace/streams.h @@ -0,0 +1,138 @@ +// -*- C++ -*- + +//============================================================================= +/** + * @file streams.h + * + * $Id: streams.h 82445 2008-07-28 13:40:01Z johnnyw $ + * + * @author Irfan Pyarali + * + * This file contains the portability ugliness for the Standard C++ + * Library. As implementations of the "standard" emerge, this file + * will need to be updated. + * + * This files deals with the streams includes. + * + * + */ +//============================================================================= + + +#ifndef ACE_STREAMS_H +#define ACE_STREAMS_H +#include /**/ "ace/pre.h" + +#include /**/ "ace/config-all.h" + +#if !defined (ACE_LACKS_PRAGMA_ONCE) +# pragma once +#endif /* ACE_LACKS_PRAGMA_ONCE */ + +// Do this so the #pragma warning in the MSVC headers do not +// affect our #pragma warning settings +#if defined (_MSC_VER) +#pragma warning(push) +#endif /* _MSC_VER*/ + + +#if !defined (ACE_LACKS_IOSTREAM_TOTALLY) + +# if defined (ACE_HAS_STANDARD_CPP_LIBRARY) && \ + (ACE_HAS_STANDARD_CPP_LIBRARY != 0) + +# if defined (_MSC_VER) +# pragma warning(disable: 4018 4114 4146 4245) +# pragma warning(disable: 4663 4664 4665 4511 4512) +# endif /* _MSC_VER */ + +# if defined (ACE_USES_OLD_IOSTREAMS) +# include /**/ +# include /**/ + // This has been commented as it is not needed and causes problems with Qt. + // (brunsch) But has been uncommented since it should be included. Qt + // probably should have some sort of macro that will prevent including this + // when it is used. +# include /**/ +# else +# include /**/ +# include /**/ +# include /**/ +# include /**/ +# include /**/ +# include /**/ +# include /**/ +# endif /* ACE_USES_OLD_IOSTREAMS */ + +# if defined (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB) && \ + (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB != 0) + +# if !defined (ACE_USES_OLD_IOSTREAMS) + // Make these available in the global name space + using std::ios; + using std::ios_base; + using std::streambuf; + using std::istream; + using std::ostream; + using std::iostream; + using std::filebuf; + using std::ifstream; + using std::ofstream; + using std::fstream; + + using std::cin; + using std::cout; + using std::cerr; + using std::clog; + + using std::endl; + using std::ends; + using std::flush; + + using std::ws; + + using std::resetiosflags; + using std::setfill; + using std::setiosflags; + using std::setprecision; + using std::setw; + + using std::dec; + using std::hex; + using std::oct; +# endif /* ! ACE_USES_OLD_IOSTREAMS */ + +# endif /* ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB */ + +# if defined (_MSC_VER) +# pragma warning(4: 4018 4114 4146 4245) +# pragma warning(4: 4663 4664 4665 4512 4511) +# endif /* _MSC_VER */ + +# else /* ! ACE_HAS_STANDARD_CPP_LIBRARY */ + +# include /**/ +# include /**/ +# include /**/ + +# if defined (ACE_WIN32) && !defined(__MINGW32__) +# if defined(_MSC_VER) // VSB +# include /**/ +# include /**/ +# include /**/ +# include /**/ +# endif /* _MSC_VER */ +# endif /* ACE_WIN32 && !__MINGW32__ */ + +# endif /* ! ACE_HAS_STANDARD_CPP_LIBRARY */ + +#endif /* ! ACE_LACKS_IOSTREAM_TOTALLY */ + +// Do this so the #pragma warning in the MSVC headers do not +// affect our #pragma warning settings +#if defined (_MSC_VER) +#pragma warning(pop) +#endif /* _MSC_VER */ + +#include /**/ "ace/post.h" +#endif /* ACE_STREAMS_H */ diff --git a/dep/acelite/ace/svc_export.h b/dep/acelite/ace/svc_export.h new file mode 100644 index 00000000000..18cf3a24c35 --- /dev/null +++ b/dep/acelite/ace/svc_export.h @@ -0,0 +1,44 @@ +// -*- C++ -*- +// $Id: svc_export.h 84495 2009-02-17 17:44:31Z johnnyw $ +// Definition for Win32 Export directives. + +// This file was generated by generate_export_file.pl +// but needed to be altered to support ACE_BUILD_SVC_DLL +// instead of ACE_SVC_BUILD_DLL which was already being +// used. + +// ------------------------------ +#if !defined (ACE_SVC_EXPORT_H) +#define ACE_SVC_EXPORT_H + +#include /**/ "ace/config-all.h" + +#if defined (ACE_AS_STATIC_LIBS) && !defined (ACE_SVC_HAS_DLL) +# define ACE_SVC_HAS_DLL 0 +#endif /* ACE_AS_STATIC_LIBS && ACE_SVC_HAS_DLL */ + +#if !defined (ACE_SVC_HAS_DLL) +#define ACE_SVC_HAS_DLL 1 +#endif /* ! ACE_SVC_HAS_DLL */ + +#if defined (ACE_SVC_HAS_DLL) +# if (ACE_SVC_HAS_DLL == 1) +# if defined (ACE_BUILD_SVC_DLL) || defined (ACE_SVC_BUILD_DLL) +# define ACE_Svc_Export ACE_Proper_Export_Flag +# define ACE_SVC_SINGLETON_DECLARATION(T) ACE_EXPORT_SINGLETON_DECLARATION (T) +# else +# define ACE_Svc_Export ACE_Proper_Import_Flag +# define ACE_SVC_SINGLETON_DECLARATION(T) ACE_IMPORT_SINGLETON_DECLARATION (T) +# endif /* ACE_BUILD_SVC_DLL */ +# else +# define ACE_Svc_Export +# define ACE_SVC_SINGLETON_DECLARATION(T) +# endif /* ! ACE_SVC_HAS_DLL == 1 */ +#else +# define ACE_Svc_Export +# define ACE_SVC_SINGLETON_DECLARATION(T) +#endif /* ACE_SVC_HAS_DLL */ + +#endif /* ACE_SVC_EXPORT_H */ + +// End of auto generated file. diff --git a/dep/bzip2/CMakeLists.txt b/dep/bzip2/CMakeLists.txt new file mode 100644 index 00000000000..05791e982aa --- /dev/null +++ b/dep/bzip2/CMakeLists.txt @@ -0,0 +1,22 @@ +# Copyright (C) 2008-2010 Trinity +# +# This file is free software; as a special exception the author gives +# unlimited permission to copy and/or distribute it, with or without +# modifications, as long as this notice is preserved. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the +# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +file(GLOB sources *.c) + +set(bzip2_STAT_SRCS + ${sources} +) + +include_directories( + ${CMAKE_SOURCE_DIR}/dep/zlib + ${CMAKE_CURRENT_SOURCE_DIR} +) + +add_library(bzip2 STATIC ${bzip2_STAT_SRCS}) diff --git a/dep/bzip2/blocksort.c b/dep/bzip2/blocksort.c new file mode 100644 index 00000000000..bd2dec157fa --- /dev/null +++ b/dep/bzip2/blocksort.c @@ -0,0 +1,1094 @@ + +/*-------------------------------------------------------------*/ +/*--- Block sorting machinery ---*/ +/*--- blocksort.c ---*/ +/*-------------------------------------------------------------*/ + +/* ------------------------------------------------------------------ + This file is part of bzip2/libbzip2, a program and library for + lossless, block-sorting data compression. + + bzip2/libbzip2 version 1.0.5 of 10 December 2007 + Copyright (C) 1996-2007 Julian Seward + + Please read the WARNING, DISCLAIMER and PATENTS sections in the + README file. + + This program is released under the terms of the license contained + in the file LICENSE. + ------------------------------------------------------------------ */ + + +#include "bzlib_private.h" + +/*---------------------------------------------*/ +/*--- Fallback O(N log(N)^2) sorting ---*/ +/*--- algorithm, for repetitive blocks ---*/ +/*---------------------------------------------*/ + +/*---------------------------------------------*/ +static +__inline__ +void fallbackSimpleSort ( UInt32* fmap, + UInt32* eclass, + Int32 lo, + Int32 hi ) +{ + Int32 i, j, tmp; + UInt32 ec_tmp; + + if (lo == hi) return; + + if (hi - lo > 3) { + for ( i = hi-4; i >= lo; i-- ) { + tmp = fmap[i]; + ec_tmp = eclass[tmp]; + for ( j = i+4; j <= hi && ec_tmp > eclass[fmap[j]]; j += 4 ) + fmap[j-4] = fmap[j]; + fmap[j-4] = tmp; + } + } + + for ( i = hi-1; i >= lo; i-- ) { + tmp = fmap[i]; + ec_tmp = eclass[tmp]; + for ( j = i+1; j <= hi && ec_tmp > eclass[fmap[j]]; j++ ) + fmap[j-1] = fmap[j]; + fmap[j-1] = tmp; + } +} + + +/*---------------------------------------------*/ +#define fswap(zz1, zz2) \ + { Int32 zztmp = zz1; zz1 = zz2; zz2 = zztmp; } + +#define fvswap(zzp1, zzp2, zzn) \ +{ \ + Int32 yyp1 = (zzp1); \ + Int32 yyp2 = (zzp2); \ + Int32 yyn = (zzn); \ + while (yyn > 0) { \ + fswap(fmap[yyp1], fmap[yyp2]); \ + yyp1++; yyp2++; yyn--; \ + } \ +} + + +#define fmin(a,b) ((a) < (b)) ? (a) : (b) + +#define fpush(lz,hz) { stackLo[sp] = lz; \ + stackHi[sp] = hz; \ + sp++; } + +#define fpop(lz,hz) { sp--; \ + lz = stackLo[sp]; \ + hz = stackHi[sp]; } + +#define FALLBACK_QSORT_SMALL_THRESH 10 +#define FALLBACK_QSORT_STACK_SIZE 100 + + +static +void fallbackQSort3 ( UInt32* fmap, + UInt32* eclass, + Int32 loSt, + Int32 hiSt ) +{ + Int32 unLo, unHi, ltLo, gtHi, n, m; + Int32 sp, lo, hi; + UInt32 med, r, r3; + Int32 stackLo[FALLBACK_QSORT_STACK_SIZE]; + Int32 stackHi[FALLBACK_QSORT_STACK_SIZE]; + + r = 0; + + sp = 0; + fpush ( loSt, hiSt ); + + while (sp > 0) { + + AssertH ( sp < FALLBACK_QSORT_STACK_SIZE - 1, 1004 ); + + fpop ( lo, hi ); + if (hi - lo < FALLBACK_QSORT_SMALL_THRESH) { + fallbackSimpleSort ( fmap, eclass, lo, hi ); + continue; + } + + /* Random partitioning. Median of 3 sometimes fails to + avoid bad cases. Median of 9 seems to help but + looks rather expensive. This too seems to work but + is cheaper. Guidance for the magic constants + 7621 and 32768 is taken from Sedgewick's algorithms + book, chapter 35. + */ + r = ((r * 7621) + 1) % 32768; + r3 = r % 3; + if (r3 == 0) med = eclass[fmap[lo]]; else + if (r3 == 1) med = eclass[fmap[(lo+hi)>>1]]; else + med = eclass[fmap[hi]]; + + unLo = ltLo = lo; + unHi = gtHi = hi; + + while (1) { + while (1) { + if (unLo > unHi) break; + n = (Int32)eclass[fmap[unLo]] - (Int32)med; + if (n == 0) { + fswap(fmap[unLo], fmap[ltLo]); + ltLo++; unLo++; + continue; + }; + if (n > 0) break; + unLo++; + } + while (1) { + if (unLo > unHi) break; + n = (Int32)eclass[fmap[unHi]] - (Int32)med; + if (n == 0) { + fswap(fmap[unHi], fmap[gtHi]); + gtHi--; unHi--; + continue; + }; + if (n < 0) break; + unHi--; + } + if (unLo > unHi) break; + fswap(fmap[unLo], fmap[unHi]); unLo++; unHi--; + } + + AssertD ( unHi == unLo-1, "fallbackQSort3(2)" ); + + if (gtHi < ltLo) continue; + + n = fmin(ltLo-lo, unLo-ltLo); fvswap(lo, unLo-n, n); + m = fmin(hi-gtHi, gtHi-unHi); fvswap(unLo, hi-m+1, m); + + n = lo + unLo - ltLo - 1; + m = hi - (gtHi - unHi) + 1; + + if (n - lo > hi - m) { + fpush ( lo, n ); + fpush ( m, hi ); + } else { + fpush ( m, hi ); + fpush ( lo, n ); + } + } +} + +#undef fmin +#undef fpush +#undef fpop +#undef fswap +#undef fvswap +#undef FALLBACK_QSORT_SMALL_THRESH +#undef FALLBACK_QSORT_STACK_SIZE + + +/*---------------------------------------------*/ +/* Pre: + nblock > 0 + eclass exists for [0 .. nblock-1] + ((UChar*)eclass) [0 .. nblock-1] holds block + ptr exists for [0 .. nblock-1] + + Post: + ((UChar*)eclass) [0 .. nblock-1] holds block + All other areas of eclass destroyed + fmap [0 .. nblock-1] holds sorted order + bhtab [ 0 .. 2+(nblock/32) ] destroyed +*/ + +#define SET_BH(zz) bhtab[(zz) >> 5] |= (1 << ((zz) & 31)) +#define CLEAR_BH(zz) bhtab[(zz) >> 5] &= ~(1 << ((zz) & 31)) +#define ISSET_BH(zz) (bhtab[(zz) >> 5] & (1 << ((zz) & 31))) +#define WORD_BH(zz) bhtab[(zz) >> 5] +#define UNALIGNED_BH(zz) ((zz) & 0x01f) + +static +void fallbackSort ( UInt32* fmap, + UInt32* eclass, + UInt32* bhtab, + Int32 nblock, + Int32 verb ) +{ + Int32 ftab[257]; + Int32 ftabCopy[256]; + Int32 H, i, j, k, l, r, cc, cc1; + Int32 nNotDone; + Int32 nBhtab; + UChar* eclass8 = (UChar*)eclass; + + /*-- + Initial 1-char radix sort to generate + initial fmap and initial BH bits. + --*/ + if (verb >= 4) + VPrintf0 ( " bucket sorting ...\n" ); + for (i = 0; i < 257; i++) ftab[i] = 0; + for (i = 0; i < nblock; i++) ftab[eclass8[i]]++; + for (i = 0; i < 256; i++) ftabCopy[i] = ftab[i]; + for (i = 1; i < 257; i++) ftab[i] += ftab[i-1]; + + for (i = 0; i < nblock; i++) { + j = eclass8[i]; + k = ftab[j] - 1; + ftab[j] = k; + fmap[k] = i; + } + + nBhtab = 2 + (nblock / 32); + for (i = 0; i < nBhtab; i++) bhtab[i] = 0; + for (i = 0; i < 256; i++) SET_BH(ftab[i]); + + /*-- + Inductively refine the buckets. Kind-of an + "exponential radix sort" (!), inspired by the + Manber-Myers suffix array construction algorithm. + --*/ + + /*-- set sentinel bits for block-end detection --*/ + for (i = 0; i < 32; i++) { + SET_BH(nblock + 2*i); + CLEAR_BH(nblock + 2*i + 1); + } + + /*-- the log(N) loop --*/ + H = 1; + while (1) { + + if (verb >= 4) + VPrintf1 ( " depth %6d has ", H ); + + j = 0; + for (i = 0; i < nblock; i++) { + if (ISSET_BH(i)) j = i; + k = fmap[i] - H; if (k < 0) k += nblock; + eclass[k] = j; + } + + nNotDone = 0; + r = -1; + while (1) { + + /*-- find the next non-singleton bucket --*/ + k = r + 1; + while (ISSET_BH(k) && UNALIGNED_BH(k)) k++; + if (ISSET_BH(k)) { + while (WORD_BH(k) == 0xffffffff) k += 32; + while (ISSET_BH(k)) k++; + } + l = k - 1; + if (l >= nblock) break; + while (!ISSET_BH(k) && UNALIGNED_BH(k)) k++; + if (!ISSET_BH(k)) { + while (WORD_BH(k) == 0x00000000) k += 32; + while (!ISSET_BH(k)) k++; + } + r = k - 1; + if (r >= nblock) break; + + /*-- now [l, r] bracket current bucket --*/ + if (r > l) { + nNotDone += (r - l + 1); + fallbackQSort3 ( fmap, eclass, l, r ); + + /*-- scan bucket and generate header bits-- */ + cc = -1; + for (i = l; i <= r; i++) { + cc1 = eclass[fmap[i]]; + if (cc != cc1) { SET_BH(i); cc = cc1; }; + } + } + } + + if (verb >= 4) + VPrintf1 ( "%6d unresolved strings\n", nNotDone ); + + H *= 2; + if (H > nblock || nNotDone == 0) break; + } + + /*-- + Reconstruct the original block in + eclass8 [0 .. nblock-1], since the + previous phase destroyed it. + --*/ + if (verb >= 4) + VPrintf0 ( " reconstructing block ...\n" ); + j = 0; + for (i = 0; i < nblock; i++) { + while (ftabCopy[j] == 0) j++; + ftabCopy[j]--; + eclass8[fmap[i]] = (UChar)j; + } + AssertH ( j < 256, 1005 ); +} + +#undef SET_BH +#undef CLEAR_BH +#undef ISSET_BH +#undef WORD_BH +#undef UNALIGNED_BH + + +/*---------------------------------------------*/ +/*--- The main, O(N^2 log(N)) sorting ---*/ +/*--- algorithm. Faster for "normal" ---*/ +/*--- non-repetitive blocks. ---*/ +/*---------------------------------------------*/ + +/*---------------------------------------------*/ +static +__inline__ +Bool mainGtU ( UInt32 i1, + UInt32 i2, + UChar* block, + UInt16* quadrant, + UInt32 nblock, + Int32* budget ) +{ + Int32 k; + UChar c1, c2; + UInt16 s1, s2; + + AssertD ( i1 != i2, "mainGtU" ); + /* 1 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + i1++; i2++; + /* 2 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + i1++; i2++; + /* 3 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + i1++; i2++; + /* 4 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + i1++; i2++; + /* 5 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + i1++; i2++; + /* 6 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + i1++; i2++; + /* 7 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + i1++; i2++; + /* 8 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + i1++; i2++; + /* 9 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + i1++; i2++; + /* 10 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + i1++; i2++; + /* 11 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + i1++; i2++; + /* 12 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + i1++; i2++; + + k = nblock + 8; + + do { + /* 1 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + s1 = quadrant[i1]; s2 = quadrant[i2]; + if (s1 != s2) return (s1 > s2); + i1++; i2++; + /* 2 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + s1 = quadrant[i1]; s2 = quadrant[i2]; + if (s1 != s2) return (s1 > s2); + i1++; i2++; + /* 3 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + s1 = quadrant[i1]; s2 = quadrant[i2]; + if (s1 != s2) return (s1 > s2); + i1++; i2++; + /* 4 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + s1 = quadrant[i1]; s2 = quadrant[i2]; + if (s1 != s2) return (s1 > s2); + i1++; i2++; + /* 5 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + s1 = quadrant[i1]; s2 = quadrant[i2]; + if (s1 != s2) return (s1 > s2); + i1++; i2++; + /* 6 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + s1 = quadrant[i1]; s2 = quadrant[i2]; + if (s1 != s2) return (s1 > s2); + i1++; i2++; + /* 7 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + s1 = quadrant[i1]; s2 = quadrant[i2]; + if (s1 != s2) return (s1 > s2); + i1++; i2++; + /* 8 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + s1 = quadrant[i1]; s2 = quadrant[i2]; + if (s1 != s2) return (s1 > s2); + i1++; i2++; + + if (i1 >= nblock) i1 -= nblock; + if (i2 >= nblock) i2 -= nblock; + + k -= 8; + (*budget)--; + } + while (k >= 0); + + return False; +} + + +/*---------------------------------------------*/ +/*-- + Knuth's increments seem to work better + than Incerpi-Sedgewick here. Possibly + because the number of elems to sort is + usually small, typically <= 20. +--*/ +static +Int32 incs[14] = { 1, 4, 13, 40, 121, 364, 1093, 3280, + 9841, 29524, 88573, 265720, + 797161, 2391484 }; + +static +void mainSimpleSort ( UInt32* ptr, + UChar* block, + UInt16* quadrant, + Int32 nblock, + Int32 lo, + Int32 hi, + Int32 d, + Int32* budget ) +{ + Int32 i, j, h, bigN, hp; + UInt32 v; + + bigN = hi - lo + 1; + if (bigN < 2) return; + + hp = 0; + while (incs[hp] < bigN) hp++; + hp--; + + for (; hp >= 0; hp--) { + h = incs[hp]; + + i = lo + h; + while (True) { + + /*-- copy 1 --*/ + if (i > hi) break; + v = ptr[i]; + j = i; + while ( mainGtU ( + ptr[j-h]+d, v+d, block, quadrant, nblock, budget + ) ) { + ptr[j] = ptr[j-h]; + j = j - h; + if (j <= (lo + h - 1)) break; + } + ptr[j] = v; + i++; + + /*-- copy 2 --*/ + if (i > hi) break; + v = ptr[i]; + j = i; + while ( mainGtU ( + ptr[j-h]+d, v+d, block, quadrant, nblock, budget + ) ) { + ptr[j] = ptr[j-h]; + j = j - h; + if (j <= (lo + h - 1)) break; + } + ptr[j] = v; + i++; + + /*-- copy 3 --*/ + if (i > hi) break; + v = ptr[i]; + j = i; + while ( mainGtU ( + ptr[j-h]+d, v+d, block, quadrant, nblock, budget + ) ) { + ptr[j] = ptr[j-h]; + j = j - h; + if (j <= (lo + h - 1)) break; + } + ptr[j] = v; + i++; + + if (*budget < 0) return; + } + } +} + + +/*---------------------------------------------*/ +/*-- + The following is an implementation of + an elegant 3-way quicksort for strings, + described in a paper "Fast Algorithms for + Sorting and Searching Strings", by Robert + Sedgewick and Jon L. Bentley. +--*/ + +#define mswap(zz1, zz2) \ + { Int32 zztmp = zz1; zz1 = zz2; zz2 = zztmp; } + +#define mvswap(zzp1, zzp2, zzn) \ +{ \ + Int32 yyp1 = (zzp1); \ + Int32 yyp2 = (zzp2); \ + Int32 yyn = (zzn); \ + while (yyn > 0) { \ + mswap(ptr[yyp1], ptr[yyp2]); \ + yyp1++; yyp2++; yyn--; \ + } \ +} + +static +__inline__ +UChar mmed3 ( UChar a, UChar b, UChar c ) +{ + UChar t; + if (a > b) { t = a; a = b; b = t; }; + if (b > c) { + b = c; + if (a > b) b = a; + } + return b; +} + +#define mmin(a,b) ((a) < (b)) ? (a) : (b) + +#define mpush(lz,hz,dz) { stackLo[sp] = lz; \ + stackHi[sp] = hz; \ + stackD [sp] = dz; \ + sp++; } + +#define mpop(lz,hz,dz) { sp--; \ + lz = stackLo[sp]; \ + hz = stackHi[sp]; \ + dz = stackD [sp]; } + + +#define mnextsize(az) (nextHi[az]-nextLo[az]) + +#define mnextswap(az,bz) \ + { Int32 tz; \ + tz = nextLo[az]; nextLo[az] = nextLo[bz]; nextLo[bz] = tz; \ + tz = nextHi[az]; nextHi[az] = nextHi[bz]; nextHi[bz] = tz; \ + tz = nextD [az]; nextD [az] = nextD [bz]; nextD [bz] = tz; } + + +#define MAIN_QSORT_SMALL_THRESH 20 +#define MAIN_QSORT_DEPTH_THRESH (BZ_N_RADIX + BZ_N_QSORT) +#define MAIN_QSORT_STACK_SIZE 100 + +static +void mainQSort3 ( UInt32* ptr, + UChar* block, + UInt16* quadrant, + Int32 nblock, + Int32 loSt, + Int32 hiSt, + Int32 dSt, + Int32* budget ) +{ + Int32 unLo, unHi, ltLo, gtHi, n, m, med; + Int32 sp, lo, hi, d; + + Int32 stackLo[MAIN_QSORT_STACK_SIZE]; + Int32 stackHi[MAIN_QSORT_STACK_SIZE]; + Int32 stackD [MAIN_QSORT_STACK_SIZE]; + + Int32 nextLo[3]; + Int32 nextHi[3]; + Int32 nextD [3]; + + sp = 0; + mpush ( loSt, hiSt, dSt ); + + while (sp > 0) { + + AssertH ( sp < MAIN_QSORT_STACK_SIZE - 2, 1001 ); + + mpop ( lo, hi, d ); + if (hi - lo < MAIN_QSORT_SMALL_THRESH || + d > MAIN_QSORT_DEPTH_THRESH) { + mainSimpleSort ( ptr, block, quadrant, nblock, lo, hi, d, budget ); + if (*budget < 0) return; + continue; + } + + med = (Int32) + mmed3 ( block[ptr[ lo ]+d], + block[ptr[ hi ]+d], + block[ptr[ (lo+hi)>>1 ]+d] ); + + unLo = ltLo = lo; + unHi = gtHi = hi; + + while (True) { + while (True) { + if (unLo > unHi) break; + n = ((Int32)block[ptr[unLo]+d]) - med; + if (n == 0) { + mswap(ptr[unLo], ptr[ltLo]); + ltLo++; unLo++; continue; + }; + if (n > 0) break; + unLo++; + } + while (True) { + if (unLo > unHi) break; + n = ((Int32)block[ptr[unHi]+d]) - med; + if (n == 0) { + mswap(ptr[unHi], ptr[gtHi]); + gtHi--; unHi--; continue; + }; + if (n < 0) break; + unHi--; + } + if (unLo > unHi) break; + mswap(ptr[unLo], ptr[unHi]); unLo++; unHi--; + } + + AssertD ( unHi == unLo-1, "mainQSort3(2)" ); + + if (gtHi < ltLo) { + mpush(lo, hi, d+1 ); + continue; + } + + n = mmin(ltLo-lo, unLo-ltLo); mvswap(lo, unLo-n, n); + m = mmin(hi-gtHi, gtHi-unHi); mvswap(unLo, hi-m+1, m); + + n = lo + unLo - ltLo - 1; + m = hi - (gtHi - unHi) + 1; + + nextLo[0] = lo; nextHi[0] = n; nextD[0] = d; + nextLo[1] = m; nextHi[1] = hi; nextD[1] = d; + nextLo[2] = n+1; nextHi[2] = m-1; nextD[2] = d+1; + + if (mnextsize(0) < mnextsize(1)) mnextswap(0,1); + if (mnextsize(1) < mnextsize(2)) mnextswap(1,2); + if (mnextsize(0) < mnextsize(1)) mnextswap(0,1); + + AssertD (mnextsize(0) >= mnextsize(1), "mainQSort3(8)" ); + AssertD (mnextsize(1) >= mnextsize(2), "mainQSort3(9)" ); + + mpush (nextLo[0], nextHi[0], nextD[0]); + mpush (nextLo[1], nextHi[1], nextD[1]); + mpush (nextLo[2], nextHi[2], nextD[2]); + } +} + +#undef mswap +#undef mvswap +#undef mpush +#undef mpop +#undef mmin +#undef mnextsize +#undef mnextswap +#undef MAIN_QSORT_SMALL_THRESH +#undef MAIN_QSORT_DEPTH_THRESH +#undef MAIN_QSORT_STACK_SIZE + + +/*---------------------------------------------*/ +/* Pre: + nblock > N_OVERSHOOT + block32 exists for [0 .. nblock-1 +N_OVERSHOOT] + ((UChar*)block32) [0 .. nblock-1] holds block + ptr exists for [0 .. nblock-1] + + Post: + ((UChar*)block32) [0 .. nblock-1] holds block + All other areas of block32 destroyed + ftab [0 .. 65536 ] destroyed + ptr [0 .. nblock-1] holds sorted order + if (*budget < 0), sorting was abandoned +*/ + +#define BIGFREQ(b) (ftab[((b)+1) << 8] - ftab[(b) << 8]) +#define SETMASK (1 << 21) +#define CLEARMASK (~(SETMASK)) + +static +void mainSort ( UInt32* ptr, + UChar* block, + UInt16* quadrant, + UInt32* ftab, + Int32 nblock, + Int32 verb, + Int32* budget ) +{ + Int32 i, j, k, ss, sb; + Int32 runningOrder[256]; + Bool bigDone[256]; + Int32 copyStart[256]; + Int32 copyEnd [256]; + UChar c1; + Int32 numQSorted; + UInt16 s; + if (verb >= 4) VPrintf0 ( " main sort initialise ...\n" ); + + /*-- set up the 2-byte frequency table --*/ + for (i = 65536; i >= 0; i--) ftab[i] = 0; + + j = block[0] << 8; + i = nblock-1; + for (; i >= 3; i -= 4) { + quadrant[i] = 0; + j = (j >> 8) | ( ((UInt16)block[i]) << 8); + ftab[j]++; + quadrant[i-1] = 0; + j = (j >> 8) | ( ((UInt16)block[i-1]) << 8); + ftab[j]++; + quadrant[i-2] = 0; + j = (j >> 8) | ( ((UInt16)block[i-2]) << 8); + ftab[j]++; + quadrant[i-3] = 0; + j = (j >> 8) | ( ((UInt16)block[i-3]) << 8); + ftab[j]++; + } + for (; i >= 0; i--) { + quadrant[i] = 0; + j = (j >> 8) | ( ((UInt16)block[i]) << 8); + ftab[j]++; + } + + /*-- (emphasises close relationship of block & quadrant) --*/ + for (i = 0; i < BZ_N_OVERSHOOT; i++) { + block [nblock+i] = block[i]; + quadrant[nblock+i] = 0; + } + + if (verb >= 4) VPrintf0 ( " bucket sorting ...\n" ); + + /*-- Complete the initial radix sort --*/ + for (i = 1; i <= 65536; i++) ftab[i] += ftab[i-1]; + + s = block[0] << 8; + i = nblock-1; + for (; i >= 3; i -= 4) { + s = (s >> 8) | (block[i] << 8); + j = ftab[s] -1; + ftab[s] = j; + ptr[j] = i; + s = (s >> 8) | (block[i-1] << 8); + j = ftab[s] -1; + ftab[s] = j; + ptr[j] = i-1; + s = (s >> 8) | (block[i-2] << 8); + j = ftab[s] -1; + ftab[s] = j; + ptr[j] = i-2; + s = (s >> 8) | (block[i-3] << 8); + j = ftab[s] -1; + ftab[s] = j; + ptr[j] = i-3; + } + for (; i >= 0; i--) { + s = (s >> 8) | (block[i] << 8); + j = ftab[s] -1; + ftab[s] = j; + ptr[j] = i; + } + + /*-- + Now ftab contains the first loc of every small bucket. + Calculate the running order, from smallest to largest + big bucket. + --*/ + for (i = 0; i <= 255; i++) { + bigDone [i] = False; + runningOrder[i] = i; + } + + { + Int32 vv; + Int32 h = 1; + do h = 3 * h + 1; while (h <= 256); + do { + h = h / 3; + for (i = h; i <= 255; i++) { + vv = runningOrder[i]; + j = i; + while ( BIGFREQ(runningOrder[j-h]) > BIGFREQ(vv) ) { + runningOrder[j] = runningOrder[j-h]; + j = j - h; + if (j <= (h - 1)) goto zero; + } + zero: + runningOrder[j] = vv; + } + } while (h != 1); + } + + /*-- + The main sorting loop. + --*/ + + numQSorted = 0; + + for (i = 0; i <= 255; i++) { + + /*-- + Process big buckets, starting with the least full. + Basically this is a 3-step process in which we call + mainQSort3 to sort the small buckets [ss, j], but + also make a big effort to avoid the calls if we can. + --*/ + ss = runningOrder[i]; + + /*-- + Step 1: + Complete the big bucket [ss] by quicksorting + any unsorted small buckets [ss, j], for j != ss. + Hopefully previous pointer-scanning phases have already + completed many of the small buckets [ss, j], so + we don't have to sort them at all. + --*/ + for (j = 0; j <= 255; j++) { + if (j != ss) { + sb = (ss << 8) + j; + if ( ! (ftab[sb] & SETMASK) ) { + Int32 lo = ftab[sb] & CLEARMASK; + Int32 hi = (ftab[sb+1] & CLEARMASK) - 1; + if (hi > lo) { + if (verb >= 4) + VPrintf4 ( " qsort [0x%x, 0x%x] " + "done %d this %d\n", + ss, j, numQSorted, hi - lo + 1 ); + mainQSort3 ( + ptr, block, quadrant, nblock, + lo, hi, BZ_N_RADIX, budget + ); + numQSorted += (hi - lo + 1); + if (*budget < 0) return; + } + } + ftab[sb] |= SETMASK; + } + } + + AssertH ( !bigDone[ss], 1006 ); + + /*-- + Step 2: + Now scan this big bucket [ss] so as to synthesise the + sorted order for small buckets [t, ss] for all t, + including, magically, the bucket [ss,ss] too. + This will avoid doing Real Work in subsequent Step 1's. + --*/ + { + for (j = 0; j <= 255; j++) { + copyStart[j] = ftab[(j << 8) + ss] & CLEARMASK; + copyEnd [j] = (ftab[(j << 8) + ss + 1] & CLEARMASK) - 1; + } + for (j = ftab[ss << 8] & CLEARMASK; j < copyStart[ss]; j++) { + k = ptr[j]-1; if (k < 0) k += nblock; + c1 = block[k]; + if (!bigDone[c1]) + ptr[ copyStart[c1]++ ] = k; + } + for (j = (ftab[(ss+1) << 8] & CLEARMASK) - 1; j > copyEnd[ss]; j--) { + k = ptr[j]-1; if (k < 0) k += nblock; + c1 = block[k]; + if (!bigDone[c1]) + ptr[ copyEnd[c1]-- ] = k; + } + } + + AssertH ( (copyStart[ss]-1 == copyEnd[ss]) + || + /* Extremely rare case missing in bzip2-1.0.0 and 1.0.1. + Necessity for this case is demonstrated by compressing + a sequence of approximately 48.5 million of character + 251; 1.0.0/1.0.1 will then die here. */ + (copyStart[ss] == 0 && copyEnd[ss] == nblock-1), + 1007 ) + + for (j = 0; j <= 255; j++) ftab[(j << 8) + ss] |= SETMASK; + + /*-- + Step 3: + The [ss] big bucket is now done. Record this fact, + and update the quadrant descriptors. Remember to + update quadrants in the overshoot area too, if + necessary. The "if (i < 255)" test merely skips + this updating for the last bucket processed, since + updating for the last bucket is pointless. + + The quadrant array provides a way to incrementally + cache sort orderings, as they appear, so as to + make subsequent comparisons in fullGtU() complete + faster. For repetitive blocks this makes a big + difference (but not big enough to be able to avoid + the fallback sorting mechanism, exponential radix sort). + + The precise meaning is: at all times: + + for 0 <= i < nblock and 0 <= j <= nblock + + if block[i] != block[j], + + then the relative values of quadrant[i] and + quadrant[j] are meaningless. + + else { + if quadrant[i] < quadrant[j] + then the string starting at i lexicographically + precedes the string starting at j + + else if quadrant[i] > quadrant[j] + then the string starting at j lexicographically + precedes the string starting at i + + else + the relative ordering of the strings starting + at i and j has not yet been determined. + } + --*/ + bigDone[ss] = True; + + if (i < 255) { + Int32 bbStart = ftab[ss << 8] & CLEARMASK; + Int32 bbSize = (ftab[(ss+1) << 8] & CLEARMASK) - bbStart; + Int32 shifts = 0; + + while ((bbSize >> shifts) > 65534) shifts++; + + for (j = bbSize-1; j >= 0; j--) { + Int32 a2update = ptr[bbStart + j]; + UInt16 qVal = (UInt16)(j >> shifts); + quadrant[a2update] = qVal; + if (a2update < BZ_N_OVERSHOOT) + quadrant[a2update + nblock] = qVal; + } + AssertH ( ((bbSize-1) >> shifts) <= 65535, 1002 ); + } + + } + + if (verb >= 4) + VPrintf3 ( " %d pointers, %d sorted, %d scanned\n", + nblock, numQSorted, nblock - numQSorted ); +} + +#undef BIGFREQ +#undef SETMASK +#undef CLEARMASK + + +/*---------------------------------------------*/ +/* Pre: + nblock > 0 + arr2 exists for [0 .. nblock-1 +N_OVERSHOOT] + ((UChar*)arr2) [0 .. nblock-1] holds block + arr1 exists for [0 .. nblock-1] + + Post: + ((UChar*)arr2) [0 .. nblock-1] holds block + All other areas of block destroyed + ftab [ 0 .. 65536 ] destroyed + arr1 [0 .. nblock-1] holds sorted order +*/ +void BZ2_blockSort ( EState* s ) +{ + UInt32* ptr = s->ptr; + UChar* block = s->block; + UInt32* ftab = s->ftab; + Int32 nblock = s->nblock; + Int32 verb = s->verbosity; + Int32 wfact = s->workFactor; + UInt16* quadrant; + Int32 budget; + Int32 budgetInit; + Int32 i; + + if (nblock < 10000) { + fallbackSort ( s->arr1, s->arr2, ftab, nblock, verb ); + } else { + /* Calculate the location for quadrant, remembering to get + the alignment right. Assumes that &(block[0]) is at least + 2-byte aligned -- this should be ok since block is really + the first section of arr2. + */ + i = nblock+BZ_N_OVERSHOOT; + if (i & 1) i++; + quadrant = (UInt16*)(&(block[i])); + + /* (wfact-1) / 3 puts the default-factor-30 + transition point at very roughly the same place as + with v0.1 and v0.9.0. + Not that it particularly matters any more, since the + resulting compressed stream is now the same regardless + of whether or not we use the main sort or fallback sort. + */ + if (wfact < 1 ) wfact = 1; + if (wfact > 100) wfact = 100; + budgetInit = nblock * ((wfact-1) / 3); + budget = budgetInit; + + mainSort ( ptr, block, quadrant, ftab, nblock, verb, &budget ); + if (verb >= 3) + VPrintf3 ( " %d work, %d block, ratio %5.2f\n", + budgetInit - budget, + nblock, + (float)(budgetInit - budget) / + (float)(nblock==0 ? 1 : nblock) ); + if (budget < 0) { + if (verb >= 2) + VPrintf0 ( " too repetitive; using fallback" + " sorting algorithm\n" ); + fallbackSort ( s->arr1, s->arr2, ftab, nblock, verb ); + } + } + + s->origPtr = -1; + for (i = 0; i < s->nblock; i++) + if (ptr[i] == 0) + { s->origPtr = i; break; }; + + AssertH( s->origPtr != -1, 1003 ); +} + + +/*-------------------------------------------------------------*/ +/*--- end blocksort.c ---*/ +/*-------------------------------------------------------------*/ diff --git a/dep/bzip2/bzlib.c b/dep/bzip2/bzlib.c new file mode 100644 index 00000000000..ef86c91e695 --- /dev/null +++ b/dep/bzip2/bzlib.c @@ -0,0 +1,1572 @@ + +/*-------------------------------------------------------------*/ +/*--- Library top-level functions. ---*/ +/*--- bzlib.c ---*/ +/*-------------------------------------------------------------*/ + +/* ------------------------------------------------------------------ + This file is part of bzip2/libbzip2, a program and library for + lossless, block-sorting data compression. + + bzip2/libbzip2 version 1.0.5 of 10 December 2007 + Copyright (C) 1996-2007 Julian Seward + + Please read the WARNING, DISCLAIMER and PATENTS sections in the + README file. + + This program is released under the terms of the license contained + in the file LICENSE. + ------------------------------------------------------------------ */ + +/* CHANGES + 0.9.0 -- original version. + 0.9.0a/b -- no changes in this file. + 0.9.0c -- made zero-length BZ_FLUSH work correctly in bzCompress(). + fixed bzWrite/bzRead to ignore zero-length requests. + fixed bzread to correctly handle read requests after EOF. + wrong parameter order in call to bzDecompressInit in + bzBuffToBuffDecompress. Fixed. +*/ + +#include "bzlib_private.h" + + +/*---------------------------------------------------*/ +/*--- Compression stuff ---*/ +/*---------------------------------------------------*/ + + +/*---------------------------------------------------*/ +#ifndef BZ_NO_STDIO +void BZ2_bz__AssertH__fail ( int errcode ) +{ + fprintf(stderr, + "\n\nbzip2/libbzip2: internal error number %d.\n" + "This is a bug in bzip2/libbzip2, %s.\n" + "Please report it to me at: jseward@bzip.org. If this happened\n" + "when you were using some program which uses libbzip2 as a\n" + "component, you should also report this bug to the author(s)\n" + "of that program. Please make an effort to report this bug;\n" + "timely and accurate bug reports eventually lead to higher\n" + "quality software. Thanks. Julian Seward, 10 December 2007.\n\n", + errcode, + BZ2_bzlibVersion() + ); + + if (errcode == 1007) { + fprintf(stderr, + "\n*** A special note about internal error number 1007 ***\n" + "\n" + "Experience suggests that a common cause of i.e. 1007\n" + "is unreliable memory or other hardware. The 1007 assertion\n" + "just happens to cross-check the results of huge numbers of\n" + "memory reads/writes, and so acts (unintendedly) as a stress\n" + "test of your memory system.\n" + "\n" + "I suggest the following: try compressing the file again,\n" + "possibly monitoring progress in detail with the -vv flag.\n" + "\n" + "* If the error cannot be reproduced, and/or happens at different\n" + " points in compression, you may have a flaky memory system.\n" + " Try a memory-test program. I have used Memtest86\n" + " (www.memtest86.com). At the time of writing it is free (GPLd).\n" + " Memtest86 tests memory much more thorougly than your BIOSs\n" + " power-on test, and may find failures that the BIOS doesn't.\n" + "\n" + "* If the error can be repeatably reproduced, this is a bug in\n" + " bzip2, and I would very much like to hear about it. Please\n" + " let me know, and, ideally, save a copy of the file causing the\n" + " problem -- without which I will be unable to investigate it.\n" + "\n" + ); + } + + exit(3); +} +#endif + + +/*---------------------------------------------------*/ +static +int bz_config_ok ( void ) +{ + if (sizeof(int) != 4) return 0; + if (sizeof(short) != 2) return 0; + if (sizeof(char) != 1) return 0; + return 1; +} + + +/*---------------------------------------------------*/ +static +void* default_bzalloc ( void* opaque, Int32 items, Int32 size ) +{ + void* v = malloc ( items * size ); + return v; +} + +static +void default_bzfree ( void* opaque, void* addr ) +{ + if (addr != NULL) free ( addr ); +} + + +/*---------------------------------------------------*/ +static +void prepare_new_block ( EState* s ) +{ + Int32 i; + s->nblock = 0; + s->numZ = 0; + s->state_out_pos = 0; + BZ_INITIALISE_CRC ( s->blockCRC ); + for (i = 0; i < 256; i++) s->inUse[i] = False; + s->blockNo++; +} + + +/*---------------------------------------------------*/ +static +void init_RL ( EState* s ) +{ + s->state_in_ch = 256; + s->state_in_len = 0; +} + + +static +Bool isempty_RL ( EState* s ) +{ + if (s->state_in_ch < 256 && s->state_in_len > 0) + return False; else + return True; +} + + +/*---------------------------------------------------*/ +int BZ_API(BZ2_bzCompressInit) + ( bz_stream* strm, + int blockSize100k, + int verbosity, + int workFactor ) +{ + Int32 n; + EState* s; + + if (!bz_config_ok()) return BZ_CONFIG_ERROR; + + if (strm == NULL || + blockSize100k < 1 || blockSize100k > 9 || + workFactor < 0 || workFactor > 250) + return BZ_PARAM_ERROR; + + if (workFactor == 0) workFactor = 30; + if (strm->bzalloc == NULL) strm->bzalloc = default_bzalloc; + if (strm->bzfree == NULL) strm->bzfree = default_bzfree; + + s = BZALLOC( sizeof(EState) ); + if (s == NULL) return BZ_MEM_ERROR; + s->strm = strm; + + s->arr1 = NULL; + s->arr2 = NULL; + s->ftab = NULL; + + n = 100000 * blockSize100k; + s->arr1 = BZALLOC( n * sizeof(UInt32) ); + s->arr2 = BZALLOC( (n+BZ_N_OVERSHOOT) * sizeof(UInt32) ); + s->ftab = BZALLOC( 65537 * sizeof(UInt32) ); + + if (s->arr1 == NULL || s->arr2 == NULL || s->ftab == NULL) { + if (s->arr1 != NULL) BZFREE(s->arr1); + if (s->arr2 != NULL) BZFREE(s->arr2); + if (s->ftab != NULL) BZFREE(s->ftab); + if (s != NULL) BZFREE(s); + return BZ_MEM_ERROR; + } + + s->blockNo = 0; + s->state = BZ_S_INPUT; + s->mode = BZ_M_RUNNING; + s->combinedCRC = 0; + s->blockSize100k = blockSize100k; + s->nblockMAX = 100000 * blockSize100k - 19; + s->verbosity = verbosity; + s->workFactor = workFactor; + + s->block = (UChar*)s->arr2; + s->mtfv = (UInt16*)s->arr1; + s->zbits = NULL; + s->ptr = (UInt32*)s->arr1; + + strm->state = s; + strm->total_in_lo32 = 0; + strm->total_in_hi32 = 0; + strm->total_out_lo32 = 0; + strm->total_out_hi32 = 0; + init_RL ( s ); + prepare_new_block ( s ); + return BZ_OK; +} + + +/*---------------------------------------------------*/ +static +void add_pair_to_block ( EState* s ) +{ + Int32 i; + UChar ch = (UChar)(s->state_in_ch); + for (i = 0; i < s->state_in_len; i++) { + BZ_UPDATE_CRC( s->blockCRC, ch ); + } + s->inUse[s->state_in_ch] = True; + switch (s->state_in_len) { + case 1: + s->block[s->nblock] = (UChar)ch; s->nblock++; + break; + case 2: + s->block[s->nblock] = (UChar)ch; s->nblock++; + s->block[s->nblock] = (UChar)ch; s->nblock++; + break; + case 3: + s->block[s->nblock] = (UChar)ch; s->nblock++; + s->block[s->nblock] = (UChar)ch; s->nblock++; + s->block[s->nblock] = (UChar)ch; s->nblock++; + break; + default: + s->inUse[s->state_in_len-4] = True; + s->block[s->nblock] = (UChar)ch; s->nblock++; + s->block[s->nblock] = (UChar)ch; s->nblock++; + s->block[s->nblock] = (UChar)ch; s->nblock++; + s->block[s->nblock] = (UChar)ch; s->nblock++; + s->block[s->nblock] = ((UChar)(s->state_in_len-4)); + s->nblock++; + break; + } +} + + +/*---------------------------------------------------*/ +static +void flush_RL ( EState* s ) +{ + if (s->state_in_ch < 256) add_pair_to_block ( s ); + init_RL ( s ); +} + + +/*---------------------------------------------------*/ +#define ADD_CHAR_TO_BLOCK(zs,zchh0) \ +{ \ + UInt32 zchh = (UInt32)(zchh0); \ + /*-- fast track the common case --*/ \ + if (zchh != zs->state_in_ch && \ + zs->state_in_len == 1) { \ + UChar ch = (UChar)(zs->state_in_ch); \ + BZ_UPDATE_CRC( zs->blockCRC, ch ); \ + zs->inUse[zs->state_in_ch] = True; \ + zs->block[zs->nblock] = (UChar)ch; \ + zs->nblock++; \ + zs->state_in_ch = zchh; \ + } \ + else \ + /*-- general, uncommon cases --*/ \ + if (zchh != zs->state_in_ch || \ + zs->state_in_len == 255) { \ + if (zs->state_in_ch < 256) \ + add_pair_to_block ( zs ); \ + zs->state_in_ch = zchh; \ + zs->state_in_len = 1; \ + } else { \ + zs->state_in_len++; \ + } \ +} + + +/*---------------------------------------------------*/ +static +Bool copy_input_until_stop ( EState* s ) +{ + Bool progress_in = False; + + if (s->mode == BZ_M_RUNNING) { + + /*-- fast track the common case --*/ + while (True) { + /*-- block full? --*/ + if (s->nblock >= s->nblockMAX) break; + /*-- no input? --*/ + if (s->strm->avail_in == 0) break; + progress_in = True; + ADD_CHAR_TO_BLOCK ( s, (UInt32)(*((UChar*)(s->strm->next_in))) ); + s->strm->next_in++; + s->strm->avail_in--; + s->strm->total_in_lo32++; + if (s->strm->total_in_lo32 == 0) s->strm->total_in_hi32++; + } + + } else { + + /*-- general, uncommon case --*/ + while (True) { + /*-- block full? --*/ + if (s->nblock >= s->nblockMAX) break; + /*-- no input? --*/ + if (s->strm->avail_in == 0) break; + /*-- flush/finish end? --*/ + if (s->avail_in_expect == 0) break; + progress_in = True; + ADD_CHAR_TO_BLOCK ( s, (UInt32)(*((UChar*)(s->strm->next_in))) ); + s->strm->next_in++; + s->strm->avail_in--; + s->strm->total_in_lo32++; + if (s->strm->total_in_lo32 == 0) s->strm->total_in_hi32++; + s->avail_in_expect--; + } + } + return progress_in; +} + + +/*---------------------------------------------------*/ +static +Bool copy_output_until_stop ( EState* s ) +{ + Bool progress_out = False; + + while (True) { + + /*-- no output space? --*/ + if (s->strm->avail_out == 0) break; + + /*-- block done? --*/ + if (s->state_out_pos >= s->numZ) break; + + progress_out = True; + *(s->strm->next_out) = s->zbits[s->state_out_pos]; + s->state_out_pos++; + s->strm->avail_out--; + s->strm->next_out++; + s->strm->total_out_lo32++; + if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++; + } + + return progress_out; +} + + +/*---------------------------------------------------*/ +static +Bool handle_compress ( bz_stream* strm ) +{ + Bool progress_in = False; + Bool progress_out = False; + EState* s = strm->state; + + while (True) { + + if (s->state == BZ_S_OUTPUT) { + progress_out |= copy_output_until_stop ( s ); + if (s->state_out_pos < s->numZ) break; + if (s->mode == BZ_M_FINISHING && + s->avail_in_expect == 0 && + isempty_RL(s)) break; + prepare_new_block ( s ); + s->state = BZ_S_INPUT; + if (s->mode == BZ_M_FLUSHING && + s->avail_in_expect == 0 && + isempty_RL(s)) break; + } + + if (s->state == BZ_S_INPUT) { + progress_in |= copy_input_until_stop ( s ); + if (s->mode != BZ_M_RUNNING && s->avail_in_expect == 0) { + flush_RL ( s ); + BZ2_compressBlock ( s, (Bool)(s->mode == BZ_M_FINISHING) ); + s->state = BZ_S_OUTPUT; + } + else + if (s->nblock >= s->nblockMAX) { + BZ2_compressBlock ( s, False ); + s->state = BZ_S_OUTPUT; + } + else + if (s->strm->avail_in == 0) { + break; + } + } + + } + + return progress_in || progress_out; +} + + +/*---------------------------------------------------*/ +int BZ_API(BZ2_bzCompress) ( bz_stream *strm, int action ) +{ + Bool progress; + EState* s; + if (strm == NULL) return BZ_PARAM_ERROR; + s = strm->state; + if (s == NULL) return BZ_PARAM_ERROR; + if (s->strm != strm) return BZ_PARAM_ERROR; + + preswitch: + switch (s->mode) { + + case BZ_M_IDLE: + return BZ_SEQUENCE_ERROR; + + case BZ_M_RUNNING: + if (action == BZ_RUN) { + progress = handle_compress ( strm ); + return progress ? BZ_RUN_OK : BZ_PARAM_ERROR; + } + else + if (action == BZ_FLUSH) { + s->avail_in_expect = strm->avail_in; + s->mode = BZ_M_FLUSHING; + goto preswitch; + } + else + if (action == BZ_FINISH) { + s->avail_in_expect = strm->avail_in; + s->mode = BZ_M_FINISHING; + goto preswitch; + } + else + return BZ_PARAM_ERROR; + + case BZ_M_FLUSHING: + if (action != BZ_FLUSH) return BZ_SEQUENCE_ERROR; + if (s->avail_in_expect != s->strm->avail_in) + return BZ_SEQUENCE_ERROR; + progress = handle_compress ( strm ); + if (s->avail_in_expect > 0 || !isempty_RL(s) || + s->state_out_pos < s->numZ) return BZ_FLUSH_OK; + s->mode = BZ_M_RUNNING; + return BZ_RUN_OK; + + case BZ_M_FINISHING: + if (action != BZ_FINISH) return BZ_SEQUENCE_ERROR; + if (s->avail_in_expect != s->strm->avail_in) + return BZ_SEQUENCE_ERROR; + progress = handle_compress ( strm ); + if (!progress) return BZ_SEQUENCE_ERROR; + if (s->avail_in_expect > 0 || !isempty_RL(s) || + s->state_out_pos < s->numZ) return BZ_FINISH_OK; + s->mode = BZ_M_IDLE; + return BZ_STREAM_END; + } + return BZ_OK; /*--not reached--*/ +} + + +/*---------------------------------------------------*/ +int BZ_API(BZ2_bzCompressEnd) ( bz_stream *strm ) +{ + EState* s; + if (strm == NULL) return BZ_PARAM_ERROR; + s = strm->state; + if (s == NULL) return BZ_PARAM_ERROR; + if (s->strm != strm) return BZ_PARAM_ERROR; + + if (s->arr1 != NULL) BZFREE(s->arr1); + if (s->arr2 != NULL) BZFREE(s->arr2); + if (s->ftab != NULL) BZFREE(s->ftab); + BZFREE(strm->state); + + strm->state = NULL; + + return BZ_OK; +} + + +/*---------------------------------------------------*/ +/*--- Decompression stuff ---*/ +/*---------------------------------------------------*/ + +/*---------------------------------------------------*/ +int BZ_API(BZ2_bzDecompressInit) + ( bz_stream* strm, + int verbosity, + int small ) +{ + DState* s; + + if (!bz_config_ok()) return BZ_CONFIG_ERROR; + + if (strm == NULL) return BZ_PARAM_ERROR; + if (small != 0 && small != 1) return BZ_PARAM_ERROR; + if (verbosity < 0 || verbosity > 4) return BZ_PARAM_ERROR; + + if (strm->bzalloc == NULL) strm->bzalloc = default_bzalloc; + if (strm->bzfree == NULL) strm->bzfree = default_bzfree; + + s = BZALLOC( sizeof(DState) ); + if (s == NULL) return BZ_MEM_ERROR; + s->strm = strm; + strm->state = s; + s->state = BZ_X_MAGIC_1; + s->bsLive = 0; + s->bsBuff = 0; + s->calculatedCombinedCRC = 0; + strm->total_in_lo32 = 0; + strm->total_in_hi32 = 0; + strm->total_out_lo32 = 0; + strm->total_out_hi32 = 0; + s->smallDecompress = (Bool)small; + s->ll4 = NULL; + s->ll16 = NULL; + s->tt = NULL; + s->currBlockNo = 0; + s->verbosity = verbosity; + + return BZ_OK; +} + + +/*---------------------------------------------------*/ +/* Return True iff data corruption is discovered. + Returns False if there is no problem. +*/ +static +Bool unRLE_obuf_to_output_FAST ( DState* s ) +{ + UChar k1; + + if (s->blockRandomised) { + + while (True) { + /* try to finish existing run */ + while (True) { + if (s->strm->avail_out == 0) return False; + if (s->state_out_len == 0) break; + *( (UChar*)(s->strm->next_out) ) = s->state_out_ch; + BZ_UPDATE_CRC ( s->calculatedBlockCRC, s->state_out_ch ); + s->state_out_len--; + s->strm->next_out++; + s->strm->avail_out--; + s->strm->total_out_lo32++; + if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++; + } + + /* can a new run be started? */ + if (s->nblock_used == s->save_nblock+1) return False; + + /* Only caused by corrupt data stream? */ + if (s->nblock_used > s->save_nblock+1) + return True; + + s->state_out_len = 1; + s->state_out_ch = s->k0; + BZ_GET_FAST(k1); BZ_RAND_UPD_MASK; + k1 ^= BZ_RAND_MASK; s->nblock_used++; + if (s->nblock_used == s->save_nblock+1) continue; + if (k1 != s->k0) { s->k0 = k1; continue; }; + + s->state_out_len = 2; + BZ_GET_FAST(k1); BZ_RAND_UPD_MASK; + k1 ^= BZ_RAND_MASK; s->nblock_used++; + if (s->nblock_used == s->save_nblock+1) continue; + if (k1 != s->k0) { s->k0 = k1; continue; }; + + s->state_out_len = 3; + BZ_GET_FAST(k1); BZ_RAND_UPD_MASK; + k1 ^= BZ_RAND_MASK; s->nblock_used++; + if (s->nblock_used == s->save_nblock+1) continue; + if (k1 != s->k0) { s->k0 = k1; continue; }; + + BZ_GET_FAST(k1); BZ_RAND_UPD_MASK; + k1 ^= BZ_RAND_MASK; s->nblock_used++; + s->state_out_len = ((Int32)k1) + 4; + BZ_GET_FAST(s->k0); BZ_RAND_UPD_MASK; + s->k0 ^= BZ_RAND_MASK; s->nblock_used++; + } + + } else { + + /* restore */ + UInt32 c_calculatedBlockCRC = s->calculatedBlockCRC; + UChar c_state_out_ch = s->state_out_ch; + Int32 c_state_out_len = s->state_out_len; + Int32 c_nblock_used = s->nblock_used; + Int32 c_k0 = s->k0; + UInt32* c_tt = s->tt; + UInt32 c_tPos = s->tPos; + char* cs_next_out = s->strm->next_out; + unsigned int cs_avail_out = s->strm->avail_out; + Int32 ro_blockSize100k = s->blockSize100k; + /* end restore */ + + UInt32 avail_out_INIT = cs_avail_out; + Int32 s_save_nblockPP = s->save_nblock+1; + unsigned int total_out_lo32_old; + + while (True) { + + /* try to finish existing run */ + if (c_state_out_len > 0) { + while (True) { + if (cs_avail_out == 0) goto return_notr; + if (c_state_out_len == 1) break; + *( (UChar*)(cs_next_out) ) = c_state_out_ch; + BZ_UPDATE_CRC ( c_calculatedBlockCRC, c_state_out_ch ); + c_state_out_len--; + cs_next_out++; + cs_avail_out--; + } + s_state_out_len_eq_one: + { + if (cs_avail_out == 0) { + c_state_out_len = 1; goto return_notr; + }; + *( (UChar*)(cs_next_out) ) = c_state_out_ch; + BZ_UPDATE_CRC ( c_calculatedBlockCRC, c_state_out_ch ); + cs_next_out++; + cs_avail_out--; + } + } + /* Only caused by corrupt data stream? */ + if (c_nblock_used > s_save_nblockPP) + return True; + + /* can a new run be started? */ + if (c_nblock_used == s_save_nblockPP) { + c_state_out_len = 0; goto return_notr; + }; + c_state_out_ch = c_k0; + BZ_GET_FAST_C(k1); c_nblock_used++; + if (k1 != c_k0) { + c_k0 = k1; goto s_state_out_len_eq_one; + }; + if (c_nblock_used == s_save_nblockPP) + goto s_state_out_len_eq_one; + + c_state_out_len = 2; + BZ_GET_FAST_C(k1); c_nblock_used++; + if (c_nblock_used == s_save_nblockPP) continue; + if (k1 != c_k0) { c_k0 = k1; continue; }; + + c_state_out_len = 3; + BZ_GET_FAST_C(k1); c_nblock_used++; + if (c_nblock_used == s_save_nblockPP) continue; + if (k1 != c_k0) { c_k0 = k1; continue; }; + + BZ_GET_FAST_C(k1); c_nblock_used++; + c_state_out_len = ((Int32)k1) + 4; + BZ_GET_FAST_C(c_k0); c_nblock_used++; + } + + return_notr: + total_out_lo32_old = s->strm->total_out_lo32; + s->strm->total_out_lo32 += (avail_out_INIT - cs_avail_out); + if (s->strm->total_out_lo32 < total_out_lo32_old) + s->strm->total_out_hi32++; + + /* save */ + s->calculatedBlockCRC = c_calculatedBlockCRC; + s->state_out_ch = c_state_out_ch; + s->state_out_len = c_state_out_len; + s->nblock_used = c_nblock_used; + s->k0 = c_k0; + s->tt = c_tt; + s->tPos = c_tPos; + s->strm->next_out = cs_next_out; + s->strm->avail_out = cs_avail_out; + /* end save */ + } + return False; +} + + + +/*---------------------------------------------------*/ +__inline__ Int32 BZ2_indexIntoF ( Int32 indx, Int32 *cftab ) +{ + Int32 nb, na, mid; + nb = 0; + na = 256; + do { + mid = (nb + na) >> 1; + if (indx >= cftab[mid]) nb = mid; else na = mid; + } + while (na - nb != 1); + return nb; +} + + +/*---------------------------------------------------*/ +/* Return True iff data corruption is discovered. + Returns False if there is no problem. +*/ +static +Bool unRLE_obuf_to_output_SMALL ( DState* s ) +{ + UChar k1; + + if (s->blockRandomised) { + + while (True) { + /* try to finish existing run */ + while (True) { + if (s->strm->avail_out == 0) return False; + if (s->state_out_len == 0) break; + *( (UChar*)(s->strm->next_out) ) = s->state_out_ch; + BZ_UPDATE_CRC ( s->calculatedBlockCRC, s->state_out_ch ); + s->state_out_len--; + s->strm->next_out++; + s->strm->avail_out--; + s->strm->total_out_lo32++; + if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++; + } + + /* can a new run be started? */ + if (s->nblock_used == s->save_nblock+1) return False; + + /* Only caused by corrupt data stream? */ + if (s->nblock_used > s->save_nblock+1) + return True; + + s->state_out_len = 1; + s->state_out_ch = s->k0; + BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK; + k1 ^= BZ_RAND_MASK; s->nblock_used++; + if (s->nblock_used == s->save_nblock+1) continue; + if (k1 != s->k0) { s->k0 = k1; continue; }; + + s->state_out_len = 2; + BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK; + k1 ^= BZ_RAND_MASK; s->nblock_used++; + if (s->nblock_used == s->save_nblock+1) continue; + if (k1 != s->k0) { s->k0 = k1; continue; }; + + s->state_out_len = 3; + BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK; + k1 ^= BZ_RAND_MASK; s->nblock_used++; + if (s->nblock_used == s->save_nblock+1) continue; + if (k1 != s->k0) { s->k0 = k1; continue; }; + + BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK; + k1 ^= BZ_RAND_MASK; s->nblock_used++; + s->state_out_len = ((Int32)k1) + 4; + BZ_GET_SMALL(s->k0); BZ_RAND_UPD_MASK; + s->k0 ^= BZ_RAND_MASK; s->nblock_used++; + } + + } else { + + while (True) { + /* try to finish existing run */ + while (True) { + if (s->strm->avail_out == 0) return False; + if (s->state_out_len == 0) break; + *( (UChar*)(s->strm->next_out) ) = s->state_out_ch; + BZ_UPDATE_CRC ( s->calculatedBlockCRC, s->state_out_ch ); + s->state_out_len--; + s->strm->next_out++; + s->strm->avail_out--; + s->strm->total_out_lo32++; + if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++; + } + + /* can a new run be started? */ + if (s->nblock_used == s->save_nblock+1) return False; + + /* Only caused by corrupt data stream? */ + if (s->nblock_used > s->save_nblock+1) + return True; + + s->state_out_len = 1; + s->state_out_ch = s->k0; + BZ_GET_SMALL(k1); s->nblock_used++; + if (s->nblock_used == s->save_nblock+1) continue; + if (k1 != s->k0) { s->k0 = k1; continue; }; + + s->state_out_len = 2; + BZ_GET_SMALL(k1); s->nblock_used++; + if (s->nblock_used == s->save_nblock+1) continue; + if (k1 != s->k0) { s->k0 = k1; continue; }; + + s->state_out_len = 3; + BZ_GET_SMALL(k1); s->nblock_used++; + if (s->nblock_used == s->save_nblock+1) continue; + if (k1 != s->k0) { s->k0 = k1; continue; }; + + BZ_GET_SMALL(k1); s->nblock_used++; + s->state_out_len = ((Int32)k1) + 4; + BZ_GET_SMALL(s->k0); s->nblock_used++; + } + + } +} + + +/*---------------------------------------------------*/ +int BZ_API(BZ2_bzDecompress) ( bz_stream *strm ) +{ + Bool corrupt; + DState* s; + if (strm == NULL) return BZ_PARAM_ERROR; + s = strm->state; + if (s == NULL) return BZ_PARAM_ERROR; + if (s->strm != strm) return BZ_PARAM_ERROR; + + while (True) { + if (s->state == BZ_X_IDLE) return BZ_SEQUENCE_ERROR; + if (s->state == BZ_X_OUTPUT) { + if (s->smallDecompress) + corrupt = unRLE_obuf_to_output_SMALL ( s ); else + corrupt = unRLE_obuf_to_output_FAST ( s ); + if (corrupt) return BZ_DATA_ERROR; + if (s->nblock_used == s->save_nblock+1 && s->state_out_len == 0) { + BZ_FINALISE_CRC ( s->calculatedBlockCRC ); + if (s->verbosity >= 3) + VPrintf2 ( " {0x%08x, 0x%08x}", s->storedBlockCRC, + s->calculatedBlockCRC ); + if (s->verbosity >= 2) VPrintf0 ( "]" ); + if (s->calculatedBlockCRC != s->storedBlockCRC) + return BZ_DATA_ERROR; + s->calculatedCombinedCRC + = (s->calculatedCombinedCRC << 1) | + (s->calculatedCombinedCRC >> 31); + s->calculatedCombinedCRC ^= s->calculatedBlockCRC; + s->state = BZ_X_BLKHDR_1; + } else { + return BZ_OK; + } + } + if (s->state >= BZ_X_MAGIC_1) { + Int32 r = BZ2_decompress ( s ); + if (r == BZ_STREAM_END) { + if (s->verbosity >= 3) + VPrintf2 ( "\n combined CRCs: stored = 0x%08x, computed = 0x%08x", + s->storedCombinedCRC, s->calculatedCombinedCRC ); + if (s->calculatedCombinedCRC != s->storedCombinedCRC) + return BZ_DATA_ERROR; + return r; + } + if (s->state != BZ_X_OUTPUT) return r; + } + } + + AssertH ( 0, 6001 ); + + return 0; /*NOTREACHED*/ +} + + +/*---------------------------------------------------*/ +int BZ_API(BZ2_bzDecompressEnd) ( bz_stream *strm ) +{ + DState* s; + if (strm == NULL) return BZ_PARAM_ERROR; + s = strm->state; + if (s == NULL) return BZ_PARAM_ERROR; + if (s->strm != strm) return BZ_PARAM_ERROR; + + if (s->tt != NULL) BZFREE(s->tt); + if (s->ll16 != NULL) BZFREE(s->ll16); + if (s->ll4 != NULL) BZFREE(s->ll4); + + BZFREE(strm->state); + strm->state = NULL; + + return BZ_OK; +} + + +#ifndef BZ_NO_STDIO +/*---------------------------------------------------*/ +/*--- File I/O stuff ---*/ +/*---------------------------------------------------*/ + +#define BZ_SETERR(eee) \ +{ \ + if (bzerror != NULL) *bzerror = eee; \ + if (bzf != NULL) bzf->lastErr = eee; \ +} + +typedef + struct { + FILE* handle; + Char buf[BZ_MAX_UNUSED]; + Int32 bufN; + Bool writing; + bz_stream strm; + Int32 lastErr; + Bool initialisedOk; + } + bzFile; + + +/*---------------------------------------------*/ +static Bool myfeof ( FILE* f ) +{ + Int32 c = fgetc ( f ); + if (c == EOF) return True; + ungetc ( c, f ); + return False; +} + + +/*---------------------------------------------------*/ +BZFILE* BZ_API(BZ2_bzWriteOpen) + ( int* bzerror, + FILE* f, + int blockSize100k, + int verbosity, + int workFactor ) +{ + Int32 ret; + bzFile* bzf = NULL; + + BZ_SETERR(BZ_OK); + + if (f == NULL || + (blockSize100k < 1 || blockSize100k > 9) || + (workFactor < 0 || workFactor > 250) || + (verbosity < 0 || verbosity > 4)) + { BZ_SETERR(BZ_PARAM_ERROR); return NULL; }; + + if (ferror(f)) + { BZ_SETERR(BZ_IO_ERROR); return NULL; }; + + bzf = malloc ( sizeof(bzFile) ); + if (bzf == NULL) + { BZ_SETERR(BZ_MEM_ERROR); return NULL; }; + + BZ_SETERR(BZ_OK); + bzf->initialisedOk = False; + bzf->bufN = 0; + bzf->handle = f; + bzf->writing = True; + bzf->strm.bzalloc = NULL; + bzf->strm.bzfree = NULL; + bzf->strm.opaque = NULL; + + if (workFactor == 0) workFactor = 30; + ret = BZ2_bzCompressInit ( &(bzf->strm), blockSize100k, + verbosity, workFactor ); + if (ret != BZ_OK) + { BZ_SETERR(ret); free(bzf); return NULL; }; + + bzf->strm.avail_in = 0; + bzf->initialisedOk = True; + return bzf; +} + + + +/*---------------------------------------------------*/ +void BZ_API(BZ2_bzWrite) + ( int* bzerror, + BZFILE* b, + void* buf, + int len ) +{ + Int32 n, n2, ret; + bzFile* bzf = (bzFile*)b; + + BZ_SETERR(BZ_OK); + if (bzf == NULL || buf == NULL || len < 0) + { BZ_SETERR(BZ_PARAM_ERROR); return; }; + if (!(bzf->writing)) + { BZ_SETERR(BZ_SEQUENCE_ERROR); return; }; + if (ferror(bzf->handle)) + { BZ_SETERR(BZ_IO_ERROR); return; }; + + if (len == 0) + { BZ_SETERR(BZ_OK); return; }; + + bzf->strm.avail_in = len; + bzf->strm.next_in = buf; + + while (True) { + bzf->strm.avail_out = BZ_MAX_UNUSED; + bzf->strm.next_out = bzf->buf; + ret = BZ2_bzCompress ( &(bzf->strm), BZ_RUN ); + if (ret != BZ_RUN_OK) + { BZ_SETERR(ret); return; }; + + if (bzf->strm.avail_out < BZ_MAX_UNUSED) { + n = BZ_MAX_UNUSED - bzf->strm.avail_out; + n2 = fwrite ( (void*)(bzf->buf), sizeof(UChar), + n, bzf->handle ); + if (n != n2 || ferror(bzf->handle)) + { BZ_SETERR(BZ_IO_ERROR); return; }; + } + + if (bzf->strm.avail_in == 0) + { BZ_SETERR(BZ_OK); return; }; + } +} + + +/*---------------------------------------------------*/ +void BZ_API(BZ2_bzWriteClose) + ( int* bzerror, + BZFILE* b, + int abandon, + unsigned int* nbytes_in, + unsigned int* nbytes_out ) +{ + BZ2_bzWriteClose64 ( bzerror, b, abandon, + nbytes_in, NULL, nbytes_out, NULL ); +} + + +void BZ_API(BZ2_bzWriteClose64) + ( int* bzerror, + BZFILE* b, + int abandon, + unsigned int* nbytes_in_lo32, + unsigned int* nbytes_in_hi32, + unsigned int* nbytes_out_lo32, + unsigned int* nbytes_out_hi32 ) +{ + Int32 n, n2, ret; + bzFile* bzf = (bzFile*)b; + + if (bzf == NULL) + { BZ_SETERR(BZ_OK); return; }; + if (!(bzf->writing)) + { BZ_SETERR(BZ_SEQUENCE_ERROR); return; }; + if (ferror(bzf->handle)) + { BZ_SETERR(BZ_IO_ERROR); return; }; + + if (nbytes_in_lo32 != NULL) *nbytes_in_lo32 = 0; + if (nbytes_in_hi32 != NULL) *nbytes_in_hi32 = 0; + if (nbytes_out_lo32 != NULL) *nbytes_out_lo32 = 0; + if (nbytes_out_hi32 != NULL) *nbytes_out_hi32 = 0; + + if ((!abandon) && bzf->lastErr == BZ_OK) { + while (True) { + bzf->strm.avail_out = BZ_MAX_UNUSED; + bzf->strm.next_out = bzf->buf; + ret = BZ2_bzCompress ( &(bzf->strm), BZ_FINISH ); + if (ret != BZ_FINISH_OK && ret != BZ_STREAM_END) + { BZ_SETERR(ret); return; }; + + if (bzf->strm.avail_out < BZ_MAX_UNUSED) { + n = BZ_MAX_UNUSED - bzf->strm.avail_out; + n2 = fwrite ( (void*)(bzf->buf), sizeof(UChar), + n, bzf->handle ); + if (n != n2 || ferror(bzf->handle)) + { BZ_SETERR(BZ_IO_ERROR); return; }; + } + + if (ret == BZ_STREAM_END) break; + } + } + + if ( !abandon && !ferror ( bzf->handle ) ) { + fflush ( bzf->handle ); + if (ferror(bzf->handle)) + { BZ_SETERR(BZ_IO_ERROR); return; }; + } + + if (nbytes_in_lo32 != NULL) + *nbytes_in_lo32 = bzf->strm.total_in_lo32; + if (nbytes_in_hi32 != NULL) + *nbytes_in_hi32 = bzf->strm.total_in_hi32; + if (nbytes_out_lo32 != NULL) + *nbytes_out_lo32 = bzf->strm.total_out_lo32; + if (nbytes_out_hi32 != NULL) + *nbytes_out_hi32 = bzf->strm.total_out_hi32; + + BZ_SETERR(BZ_OK); + BZ2_bzCompressEnd ( &(bzf->strm) ); + free ( bzf ); +} + + +/*---------------------------------------------------*/ +BZFILE* BZ_API(BZ2_bzReadOpen) + ( int* bzerror, + FILE* f, + int verbosity, + int small, + void* unused, + int nUnused ) +{ + bzFile* bzf = NULL; + int ret; + + BZ_SETERR(BZ_OK); + + if (f == NULL || + (small != 0 && small != 1) || + (verbosity < 0 || verbosity > 4) || + (unused == NULL && nUnused != 0) || + (unused != NULL && (nUnused < 0 || nUnused > BZ_MAX_UNUSED))) + { BZ_SETERR(BZ_PARAM_ERROR); return NULL; }; + + if (ferror(f)) + { BZ_SETERR(BZ_IO_ERROR); return NULL; }; + + bzf = malloc ( sizeof(bzFile) ); + if (bzf == NULL) + { BZ_SETERR(BZ_MEM_ERROR); return NULL; }; + + BZ_SETERR(BZ_OK); + + bzf->initialisedOk = False; + bzf->handle = f; + bzf->bufN = 0; + bzf->writing = False; + bzf->strm.bzalloc = NULL; + bzf->strm.bzfree = NULL; + bzf->strm.opaque = NULL; + + while (nUnused > 0) { + bzf->buf[bzf->bufN] = *((UChar*)(unused)); bzf->bufN++; + unused = ((void*)( 1 + ((UChar*)(unused)) )); + nUnused--; + } + + ret = BZ2_bzDecompressInit ( &(bzf->strm), verbosity, small ); + if (ret != BZ_OK) + { BZ_SETERR(ret); free(bzf); return NULL; }; + + bzf->strm.avail_in = bzf->bufN; + bzf->strm.next_in = bzf->buf; + + bzf->initialisedOk = True; + return bzf; +} + + +/*---------------------------------------------------*/ +void BZ_API(BZ2_bzReadClose) ( int *bzerror, BZFILE *b ) +{ + bzFile* bzf = (bzFile*)b; + + BZ_SETERR(BZ_OK); + if (bzf == NULL) + { BZ_SETERR(BZ_OK); return; }; + + if (bzf->writing) + { BZ_SETERR(BZ_SEQUENCE_ERROR); return; }; + + if (bzf->initialisedOk) + (void)BZ2_bzDecompressEnd ( &(bzf->strm) ); + free ( bzf ); +} + + +/*---------------------------------------------------*/ +int BZ_API(BZ2_bzRead) + ( int* bzerror, + BZFILE* b, + void* buf, + int len ) +{ + Int32 n, ret; + bzFile* bzf = (bzFile*)b; + + BZ_SETERR(BZ_OK); + + if (bzf == NULL || buf == NULL || len < 0) + { BZ_SETERR(BZ_PARAM_ERROR); return 0; }; + + if (bzf->writing) + { BZ_SETERR(BZ_SEQUENCE_ERROR); return 0; }; + + if (len == 0) + { BZ_SETERR(BZ_OK); return 0; }; + + bzf->strm.avail_out = len; + bzf->strm.next_out = buf; + + while (True) { + + if (ferror(bzf->handle)) + { BZ_SETERR(BZ_IO_ERROR); return 0; }; + + if (bzf->strm.avail_in == 0 && !myfeof(bzf->handle)) { + n = fread ( bzf->buf, sizeof(UChar), + BZ_MAX_UNUSED, bzf->handle ); + if (ferror(bzf->handle)) + { BZ_SETERR(BZ_IO_ERROR); return 0; }; + bzf->bufN = n; + bzf->strm.avail_in = bzf->bufN; + bzf->strm.next_in = bzf->buf; + } + + ret = BZ2_bzDecompress ( &(bzf->strm) ); + + if (ret != BZ_OK && ret != BZ_STREAM_END) + { BZ_SETERR(ret); return 0; }; + + if (ret == BZ_OK && myfeof(bzf->handle) && + bzf->strm.avail_in == 0 && bzf->strm.avail_out > 0) + { BZ_SETERR(BZ_UNEXPECTED_EOF); return 0; }; + + if (ret == BZ_STREAM_END) + { BZ_SETERR(BZ_STREAM_END); + return len - bzf->strm.avail_out; }; + if (bzf->strm.avail_out == 0) + { BZ_SETERR(BZ_OK); return len; }; + + } + + return 0; /*not reached*/ +} + + +/*---------------------------------------------------*/ +void BZ_API(BZ2_bzReadGetUnused) + ( int* bzerror, + BZFILE* b, + void** unused, + int* nUnused ) +{ + bzFile* bzf = (bzFile*)b; + if (bzf == NULL) + { BZ_SETERR(BZ_PARAM_ERROR); return; }; + if (bzf->lastErr != BZ_STREAM_END) + { BZ_SETERR(BZ_SEQUENCE_ERROR); return; }; + if (unused == NULL || nUnused == NULL) + { BZ_SETERR(BZ_PARAM_ERROR); return; }; + + BZ_SETERR(BZ_OK); + *nUnused = bzf->strm.avail_in; + *unused = bzf->strm.next_in; +} +#endif + + +/*---------------------------------------------------*/ +/*--- Misc convenience stuff ---*/ +/*---------------------------------------------------*/ + +/*---------------------------------------------------*/ +int BZ_API(BZ2_bzBuffToBuffCompress) + ( char* dest, + unsigned int* destLen, + char* source, + unsigned int sourceLen, + int blockSize100k, + int verbosity, + int workFactor ) +{ + bz_stream strm; + int ret; + + if (dest == NULL || destLen == NULL || + source == NULL || + blockSize100k < 1 || blockSize100k > 9 || + verbosity < 0 || verbosity > 4 || + workFactor < 0 || workFactor > 250) + return BZ_PARAM_ERROR; + + if (workFactor == 0) workFactor = 30; + strm.bzalloc = NULL; + strm.bzfree = NULL; + strm.opaque = NULL; + ret = BZ2_bzCompressInit ( &strm, blockSize100k, + verbosity, workFactor ); + if (ret != BZ_OK) return ret; + + strm.next_in = source; + strm.next_out = dest; + strm.avail_in = sourceLen; + strm.avail_out = *destLen; + + ret = BZ2_bzCompress ( &strm, BZ_FINISH ); + if (ret == BZ_FINISH_OK) goto output_overflow; + if (ret != BZ_STREAM_END) goto errhandler; + + /* normal termination */ + *destLen -= strm.avail_out; + BZ2_bzCompressEnd ( &strm ); + return BZ_OK; + + output_overflow: + BZ2_bzCompressEnd ( &strm ); + return BZ_OUTBUFF_FULL; + + errhandler: + BZ2_bzCompressEnd ( &strm ); + return ret; +} + + +/*---------------------------------------------------*/ +int BZ_API(BZ2_bzBuffToBuffDecompress) + ( char* dest, + unsigned int* destLen, + char* source, + unsigned int sourceLen, + int small, + int verbosity ) +{ + bz_stream strm; + int ret; + + if (dest == NULL || destLen == NULL || + source == NULL || + (small != 0 && small != 1) || + verbosity < 0 || verbosity > 4) + return BZ_PARAM_ERROR; + + strm.bzalloc = NULL; + strm.bzfree = NULL; + strm.opaque = NULL; + ret = BZ2_bzDecompressInit ( &strm, verbosity, small ); + if (ret != BZ_OK) return ret; + + strm.next_in = source; + strm.next_out = dest; + strm.avail_in = sourceLen; + strm.avail_out = *destLen; + + ret = BZ2_bzDecompress ( &strm ); + if (ret == BZ_OK) goto output_overflow_or_eof; + if (ret != BZ_STREAM_END) goto errhandler; + + /* normal termination */ + *destLen -= strm.avail_out; + BZ2_bzDecompressEnd ( &strm ); + return BZ_OK; + + output_overflow_or_eof: + if (strm.avail_out > 0) { + BZ2_bzDecompressEnd ( &strm ); + return BZ_UNEXPECTED_EOF; + } else { + BZ2_bzDecompressEnd ( &strm ); + return BZ_OUTBUFF_FULL; + }; + + errhandler: + BZ2_bzDecompressEnd ( &strm ); + return ret; +} + + +/*---------------------------------------------------*/ +/*-- + Code contributed by Yoshioka Tsuneo (tsuneo@rr.iij4u.or.jp) + to support better zlib compatibility. + This code is not _officially_ part of libbzip2 (yet); + I haven't tested it, documented it, or considered the + threading-safeness of it. + If this code breaks, please contact both Yoshioka and me. +--*/ +/*---------------------------------------------------*/ + +/*---------------------------------------------------*/ +/*-- + return version like "0.9.5d, 4-Sept-1999". +--*/ +const char * BZ_API(BZ2_bzlibVersion)(void) +{ + return BZ_VERSION; +} + + +#ifndef BZ_NO_STDIO +/*---------------------------------------------------*/ + +#if defined(_WIN32) || defined(OS2) || defined(MSDOS) +# include +# include +# define SET_BINARY_MODE(file) setmode(fileno(file),O_BINARY) +#else +# define SET_BINARY_MODE(file) +#endif +static +BZFILE * bzopen_or_bzdopen + ( const char *path, /* no use when bzdopen */ + int fd, /* no use when bzdopen */ + const char *mode, + int open_mode) /* bzopen: 0, bzdopen:1 */ +{ + int bzerr; + char unused[BZ_MAX_UNUSED]; + int blockSize100k = 9; + int writing = 0; + char mode2[10] = ""; + FILE *fp = NULL; + BZFILE *bzfp = NULL; + int verbosity = 0; + int workFactor = 30; + int smallMode = 0; + int nUnused = 0; + + if (mode == NULL) return NULL; + while (*mode) { + switch (*mode) { + case 'r': + writing = 0; break; + case 'w': + writing = 1; break; + case 's': + smallMode = 1; break; + default: + if (isdigit((int)(*mode))) { + blockSize100k = *mode-BZ_HDR_0; + } + } + mode++; + } + strcat(mode2, writing ? "w" : "r" ); + strcat(mode2,"b"); /* binary mode */ + + if (open_mode==0) { + if (path==NULL || strcmp(path,"")==0) { + fp = (writing ? stdout : stdin); + SET_BINARY_MODE(fp); + } else { + fp = fopen(path,mode2); + } + } else { +#ifdef BZ_STRICT_ANSI + fp = NULL; +#else + fp = fdopen(fd,mode2); +#endif + } + if (fp == NULL) return NULL; + + if (writing) { + /* Guard against total chaos and anarchy -- JRS */ + if (blockSize100k < 1) blockSize100k = 1; + if (blockSize100k > 9) blockSize100k = 9; + bzfp = BZ2_bzWriteOpen(&bzerr,fp,blockSize100k, + verbosity,workFactor); + } else { + bzfp = BZ2_bzReadOpen(&bzerr,fp,verbosity,smallMode, + unused,nUnused); + } + if (bzfp == NULL) { + if (fp != stdin && fp != stdout) fclose(fp); + return NULL; + } + return bzfp; +} + + +/*---------------------------------------------------*/ +/*-- + open file for read or write. + ex) bzopen("file","w9") + case path="" or NULL => use stdin or stdout. +--*/ +BZFILE * BZ_API(BZ2_bzopen) + ( const char *path, + const char *mode ) +{ + return bzopen_or_bzdopen(path,-1,mode,/*bzopen*/0); +} + + +/*---------------------------------------------------*/ +BZFILE * BZ_API(BZ2_bzdopen) + ( int fd, + const char *mode ) +{ + return bzopen_or_bzdopen(NULL,fd,mode,/*bzdopen*/1); +} + + +/*---------------------------------------------------*/ +int BZ_API(BZ2_bzread) (BZFILE* b, void* buf, int len ) +{ + int bzerr, nread; + if (((bzFile*)b)->lastErr == BZ_STREAM_END) return 0; + nread = BZ2_bzRead(&bzerr,b,buf,len); + if (bzerr == BZ_OK || bzerr == BZ_STREAM_END) { + return nread; + } else { + return -1; + } +} + + +/*---------------------------------------------------*/ +int BZ_API(BZ2_bzwrite) (BZFILE* b, void* buf, int len ) +{ + int bzerr; + + BZ2_bzWrite(&bzerr,b,buf,len); + if(bzerr == BZ_OK){ + return len; + }else{ + return -1; + } +} + + +/*---------------------------------------------------*/ +int BZ_API(BZ2_bzflush) (BZFILE *b) +{ + /* do nothing now... */ + return 0; +} + + +/*---------------------------------------------------*/ +void BZ_API(BZ2_bzclose) (BZFILE* b) +{ + int bzerr; + FILE *fp; + + if (b==NULL) {return;} + fp = ((bzFile *)b)->handle; + if(((bzFile*)b)->writing){ + BZ2_bzWriteClose(&bzerr,b,0,NULL,NULL); + if(bzerr != BZ_OK){ + BZ2_bzWriteClose(NULL,b,1,NULL,NULL); + } + }else{ + BZ2_bzReadClose(&bzerr,b); + } + if(fp!=stdin && fp!=stdout){ + fclose(fp); + } +} + + +/*---------------------------------------------------*/ +/*-- + return last error code +--*/ +static const char *bzerrorstrings[] = { + "OK" + ,"SEQUENCE_ERROR" + ,"PARAM_ERROR" + ,"MEM_ERROR" + ,"DATA_ERROR" + ,"DATA_ERROR_MAGIC" + ,"IO_ERROR" + ,"UNEXPECTED_EOF" + ,"OUTBUFF_FULL" + ,"CONFIG_ERROR" + ,"???" /* for future */ + ,"???" /* for future */ + ,"???" /* for future */ + ,"???" /* for future */ + ,"???" /* for future */ + ,"???" /* for future */ +}; + + +const char * BZ_API(BZ2_bzerror) (BZFILE *b, int *errnum) +{ + int err = ((bzFile *)b)->lastErr; + + if(err>0) err = 0; + *errnum = err; + return bzerrorstrings[err*-1]; +} +#endif + + +/*-------------------------------------------------------------*/ +/*--- end bzlib.c ---*/ +/*-------------------------------------------------------------*/ diff --git a/dep/bzip2/bzlib.h b/dep/bzip2/bzlib.h new file mode 100644 index 00000000000..c5b75d6d8ff --- /dev/null +++ b/dep/bzip2/bzlib.h @@ -0,0 +1,282 @@ + +/*-------------------------------------------------------------*/ +/*--- Public header file for the library. ---*/ +/*--- bzlib.h ---*/ +/*-------------------------------------------------------------*/ + +/* ------------------------------------------------------------------ + This file is part of bzip2/libbzip2, a program and library for + lossless, block-sorting data compression. + + bzip2/libbzip2 version 1.0.5 of 10 December 2007 + Copyright (C) 1996-2007 Julian Seward + + Please read the WARNING, DISCLAIMER and PATENTS sections in the + README file. + + This program is released under the terms of the license contained + in the file LICENSE. + ------------------------------------------------------------------ */ + + +#ifndef _BZLIB_H +#define _BZLIB_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define BZ_RUN 0 +#define BZ_FLUSH 1 +#define BZ_FINISH 2 + +#define BZ_OK 0 +#define BZ_RUN_OK 1 +#define BZ_FLUSH_OK 2 +#define BZ_FINISH_OK 3 +#define BZ_STREAM_END 4 +#define BZ_SEQUENCE_ERROR (-1) +#define BZ_PARAM_ERROR (-2) +#define BZ_MEM_ERROR (-3) +#define BZ_DATA_ERROR (-4) +#define BZ_DATA_ERROR_MAGIC (-5) +#define BZ_IO_ERROR (-6) +#define BZ_UNEXPECTED_EOF (-7) +#define BZ_OUTBUFF_FULL (-8) +#define BZ_CONFIG_ERROR (-9) + +typedef + struct { + char *next_in; + unsigned int avail_in; + unsigned int total_in_lo32; + unsigned int total_in_hi32; + + char *next_out; + unsigned int avail_out; + unsigned int total_out_lo32; + unsigned int total_out_hi32; + + void *state; + + void *(*bzalloc)(void *,int,int); + void (*bzfree)(void *,void *); + void *opaque; + } + bz_stream; + + +#ifndef BZ_IMPORT +#define BZ_EXPORT +#endif + +#ifndef BZ_NO_STDIO +/* Need a definitition for FILE */ +#include +#endif + +#ifdef _WIN32 +# include +# ifdef small + /* windows.h define small to char */ +# undef small +# endif +# ifdef BZ_EXPORT +# define BZ_API(func) WINAPI func +# define BZ_EXTERN extern +# else + /* import windows dll dynamically */ +# define BZ_API(func) (WINAPI * func) +# define BZ_EXTERN +# endif +#else +# define BZ_API(func) func +# define BZ_EXTERN extern +#endif + + +/*-- Core (low-level) library functions --*/ + +BZ_EXTERN int BZ_API(BZ2_bzCompressInit) ( + bz_stream* strm, + int blockSize100k, + int verbosity, + int workFactor + ); + +BZ_EXTERN int BZ_API(BZ2_bzCompress) ( + bz_stream* strm, + int action + ); + +BZ_EXTERN int BZ_API(BZ2_bzCompressEnd) ( + bz_stream* strm + ); + +BZ_EXTERN int BZ_API(BZ2_bzDecompressInit) ( + bz_stream *strm, + int verbosity, + int small + ); + +BZ_EXTERN int BZ_API(BZ2_bzDecompress) ( + bz_stream* strm + ); + +BZ_EXTERN int BZ_API(BZ2_bzDecompressEnd) ( + bz_stream *strm + ); + + + +/*-- High(er) level library functions --*/ + +#ifndef BZ_NO_STDIO +#define BZ_MAX_UNUSED 5000 + +typedef void BZFILE; + +BZ_EXTERN BZFILE* BZ_API(BZ2_bzReadOpen) ( + int* bzerror, + FILE* f, + int verbosity, + int small, + void* unused, + int nUnused + ); + +BZ_EXTERN void BZ_API(BZ2_bzReadClose) ( + int* bzerror, + BZFILE* b + ); + +BZ_EXTERN void BZ_API(BZ2_bzReadGetUnused) ( + int* bzerror, + BZFILE* b, + void** unused, + int* nUnused + ); + +BZ_EXTERN int BZ_API(BZ2_bzRead) ( + int* bzerror, + BZFILE* b, + void* buf, + int len + ); + +BZ_EXTERN BZFILE* BZ_API(BZ2_bzWriteOpen) ( + int* bzerror, + FILE* f, + int blockSize100k, + int verbosity, + int workFactor + ); + +BZ_EXTERN void BZ_API(BZ2_bzWrite) ( + int* bzerror, + BZFILE* b, + void* buf, + int len + ); + +BZ_EXTERN void BZ_API(BZ2_bzWriteClose) ( + int* bzerror, + BZFILE* b, + int abandon, + unsigned int* nbytes_in, + unsigned int* nbytes_out + ); + +BZ_EXTERN void BZ_API(BZ2_bzWriteClose64) ( + int* bzerror, + BZFILE* b, + int abandon, + unsigned int* nbytes_in_lo32, + unsigned int* nbytes_in_hi32, + unsigned int* nbytes_out_lo32, + unsigned int* nbytes_out_hi32 + ); +#endif + + +/*-- Utility functions --*/ + +BZ_EXTERN int BZ_API(BZ2_bzBuffToBuffCompress) ( + char* dest, + unsigned int* destLen, + char* source, + unsigned int sourceLen, + int blockSize100k, + int verbosity, + int workFactor + ); + +BZ_EXTERN int BZ_API(BZ2_bzBuffToBuffDecompress) ( + char* dest, + unsigned int* destLen, + char* source, + unsigned int sourceLen, + int small, + int verbosity + ); + + +/*-- + Code contributed by Yoshioka Tsuneo (tsuneo@rr.iij4u.or.jp) + to support better zlib compatibility. + This code is not _officially_ part of libbzip2 (yet); + I haven't tested it, documented it, or considered the + threading-safeness of it. + If this code breaks, please contact both Yoshioka and me. +--*/ + +BZ_EXTERN const char * BZ_API(BZ2_bzlibVersion) ( + void + ); + +#ifndef BZ_NO_STDIO +BZ_EXTERN BZFILE * BZ_API(BZ2_bzopen) ( + const char *path, + const char *mode + ); + +BZ_EXTERN BZFILE * BZ_API(BZ2_bzdopen) ( + int fd, + const char *mode + ); + +BZ_EXTERN int BZ_API(BZ2_bzread) ( + BZFILE* b, + void* buf, + int len + ); + +BZ_EXTERN int BZ_API(BZ2_bzwrite) ( + BZFILE* b, + void* buf, + int len + ); + +BZ_EXTERN int BZ_API(BZ2_bzflush) ( + BZFILE* b + ); + +BZ_EXTERN void BZ_API(BZ2_bzclose) ( + BZFILE* b + ); + +BZ_EXTERN const char * BZ_API(BZ2_bzerror) ( + BZFILE *b, + int *errnum + ); +#endif + +#ifdef __cplusplus +} +#endif + +#endif + +/*-------------------------------------------------------------*/ +/*--- end bzlib.h ---*/ +/*-------------------------------------------------------------*/ diff --git a/dep/bzip2/bzlib_private.h b/dep/bzip2/bzlib_private.h new file mode 100644 index 00000000000..23427879b18 --- /dev/null +++ b/dep/bzip2/bzlib_private.h @@ -0,0 +1,509 @@ + +/*-------------------------------------------------------------*/ +/*--- Private header file for the library. ---*/ +/*--- bzlib_private.h ---*/ +/*-------------------------------------------------------------*/ + +/* ------------------------------------------------------------------ + This file is part of bzip2/libbzip2, a program and library for + lossless, block-sorting data compression. + + bzip2/libbzip2 version 1.0.5 of 10 December 2007 + Copyright (C) 1996-2007 Julian Seward + + Please read the WARNING, DISCLAIMER and PATENTS sections in the + README file. + + This program is released under the terms of the license contained + in the file LICENSE. + ------------------------------------------------------------------ */ + + +#ifndef _BZLIB_PRIVATE_H +#define _BZLIB_PRIVATE_H + +#include + +#ifndef BZ_NO_STDIO +#include +#include +#include +#endif + +#include "bzlib.h" + + + +/*-- General stuff. --*/ + +#define BZ_VERSION "1.0.5, 10-Dec-2007" + +typedef char Char; +typedef unsigned char Bool; +typedef unsigned char UChar; +typedef int Int32; +typedef unsigned int UInt32; +typedef short Int16; +typedef unsigned short UInt16; + +#define True ((Bool)1) +#define False ((Bool)0) + +#ifndef __GNUC__ +#define __inline__ /* */ +#endif + +#ifndef BZ_NO_STDIO + +extern void BZ2_bz__AssertH__fail ( int errcode ); +#define AssertH(cond,errcode) \ + { if (!(cond)) BZ2_bz__AssertH__fail ( errcode ); } + +#if BZ_DEBUG +#define AssertD(cond,msg) \ + { if (!(cond)) { \ + fprintf ( stderr, \ + "\n\nlibbzip2(debug build): internal error\n\t%s\n", msg );\ + exit(1); \ + }} +#else +#define AssertD(cond,msg) /* */ +#endif + +#define VPrintf0(zf) \ + fprintf(stderr,zf) +#define VPrintf1(zf,za1) \ + fprintf(stderr,zf,za1) +#define VPrintf2(zf,za1,za2) \ + fprintf(stderr,zf,za1,za2) +#define VPrintf3(zf,za1,za2,za3) \ + fprintf(stderr,zf,za1,za2,za3) +#define VPrintf4(zf,za1,za2,za3,za4) \ + fprintf(stderr,zf,za1,za2,za3,za4) +#define VPrintf5(zf,za1,za2,za3,za4,za5) \ + fprintf(stderr,zf,za1,za2,za3,za4,za5) + +#else + +extern void bz_internal_error ( int errcode ); +#define AssertH(cond,errcode) \ + { if (!(cond)) bz_internal_error ( errcode ); } +#define AssertD(cond,msg) do { } while (0) +#define VPrintf0(zf) do { } while (0) +#define VPrintf1(zf,za1) do { } while (0) +#define VPrintf2(zf,za1,za2) do { } while (0) +#define VPrintf3(zf,za1,za2,za3) do { } while (0) +#define VPrintf4(zf,za1,za2,za3,za4) do { } while (0) +#define VPrintf5(zf,za1,za2,za3,za4,za5) do { } while (0) + +#endif + + +#define BZALLOC(nnn) (strm->bzalloc)(strm->opaque,(nnn),1) +#define BZFREE(ppp) (strm->bzfree)(strm->opaque,(ppp)) + + +/*-- Header bytes. --*/ + +#define BZ_HDR_B 0x42 /* 'B' */ +#define BZ_HDR_Z 0x5a /* 'Z' */ +#define BZ_HDR_h 0x68 /* 'h' */ +#define BZ_HDR_0 0x30 /* '0' */ + +/*-- Constants for the back end. --*/ + +#define BZ_MAX_ALPHA_SIZE 258 +#define BZ_MAX_CODE_LEN 23 + +#define BZ_RUNA 0 +#define BZ_RUNB 1 + +#define BZ_N_GROUPS 6 +#define BZ_G_SIZE 50 +#define BZ_N_ITERS 4 + +#define BZ_MAX_SELECTORS (2 + (900000 / BZ_G_SIZE)) + + + +/*-- Stuff for randomising repetitive blocks. --*/ + +extern Int32 BZ2_rNums[512]; + +#define BZ_RAND_DECLS \ + Int32 rNToGo; \ + Int32 rTPos \ + +#define BZ_RAND_INIT_MASK \ + s->rNToGo = 0; \ + s->rTPos = 0 \ + +#define BZ_RAND_MASK ((s->rNToGo == 1) ? 1 : 0) + +#define BZ_RAND_UPD_MASK \ + if (s->rNToGo == 0) { \ + s->rNToGo = BZ2_rNums[s->rTPos]; \ + s->rTPos++; \ + if (s->rTPos == 512) s->rTPos = 0; \ + } \ + s->rNToGo--; + + + +/*-- Stuff for doing CRCs. --*/ + +extern UInt32 BZ2_crc32Table[256]; + +#define BZ_INITIALISE_CRC(crcVar) \ +{ \ + crcVar = 0xffffffffL; \ +} + +#define BZ_FINALISE_CRC(crcVar) \ +{ \ + crcVar = ~(crcVar); \ +} + +#define BZ_UPDATE_CRC(crcVar,cha) \ +{ \ + crcVar = (crcVar << 8) ^ \ + BZ2_crc32Table[(crcVar >> 24) ^ \ + ((UChar)cha)]; \ +} + + + +/*-- States and modes for compression. --*/ + +#define BZ_M_IDLE 1 +#define BZ_M_RUNNING 2 +#define BZ_M_FLUSHING 3 +#define BZ_M_FINISHING 4 + +#define BZ_S_OUTPUT 1 +#define BZ_S_INPUT 2 + +#define BZ_N_RADIX 2 +#define BZ_N_QSORT 12 +#define BZ_N_SHELL 18 +#define BZ_N_OVERSHOOT (BZ_N_RADIX + BZ_N_QSORT + BZ_N_SHELL + 2) + + + + +/*-- Structure holding all the compression-side stuff. --*/ + +typedef + struct { + /* pointer back to the struct bz_stream */ + bz_stream* strm; + + /* mode this stream is in, and whether inputting */ + /* or outputting data */ + Int32 mode; + Int32 state; + + /* remembers avail_in when flush/finish requested */ + UInt32 avail_in_expect; + + /* for doing the block sorting */ + UInt32* arr1; + UInt32* arr2; + UInt32* ftab; + Int32 origPtr; + + /* aliases for arr1 and arr2 */ + UInt32* ptr; + UChar* block; + UInt16* mtfv; + UChar* zbits; + + /* for deciding when to use the fallback sorting algorithm */ + Int32 workFactor; + + /* run-length-encoding of the input */ + UInt32 state_in_ch; + Int32 state_in_len; + BZ_RAND_DECLS; + + /* input and output limits and current posns */ + Int32 nblock; + Int32 nblockMAX; + Int32 numZ; + Int32 state_out_pos; + + /* map of bytes used in block */ + Int32 nInUse; + Bool inUse[256]; + UChar unseqToSeq[256]; + + /* the buffer for bit stream creation */ + UInt32 bsBuff; + Int32 bsLive; + + /* block and combined CRCs */ + UInt32 blockCRC; + UInt32 combinedCRC; + + /* misc administratium */ + Int32 verbosity; + Int32 blockNo; + Int32 blockSize100k; + + /* stuff for coding the MTF values */ + Int32 nMTF; + Int32 mtfFreq [BZ_MAX_ALPHA_SIZE]; + UChar selector [BZ_MAX_SELECTORS]; + UChar selectorMtf[BZ_MAX_SELECTORS]; + + UChar len [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; + Int32 code [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; + Int32 rfreq [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; + /* second dimension: only 3 needed; 4 makes index calculations faster */ + UInt32 len_pack[BZ_MAX_ALPHA_SIZE][4]; + + } + EState; + + + +/*-- externs for compression. --*/ + +extern void +BZ2_blockSort ( EState* ); + +extern void +BZ2_compressBlock ( EState*, Bool ); + +extern void +BZ2_bsInitWrite ( EState* ); + +extern void +BZ2_hbAssignCodes ( Int32*, UChar*, Int32, Int32, Int32 ); + +extern void +BZ2_hbMakeCodeLengths ( UChar*, Int32*, Int32, Int32 ); + + + +/*-- states for decompression. --*/ + +#define BZ_X_IDLE 1 +#define BZ_X_OUTPUT 2 + +#define BZ_X_MAGIC_1 10 +#define BZ_X_MAGIC_2 11 +#define BZ_X_MAGIC_3 12 +#define BZ_X_MAGIC_4 13 +#define BZ_X_BLKHDR_1 14 +#define BZ_X_BLKHDR_2 15 +#define BZ_X_BLKHDR_3 16 +#define BZ_X_BLKHDR_4 17 +#define BZ_X_BLKHDR_5 18 +#define BZ_X_BLKHDR_6 19 +#define BZ_X_BCRC_1 20 +#define BZ_X_BCRC_2 21 +#define BZ_X_BCRC_3 22 +#define BZ_X_BCRC_4 23 +#define BZ_X_RANDBIT 24 +#define BZ_X_ORIGPTR_1 25 +#define BZ_X_ORIGPTR_2 26 +#define BZ_X_ORIGPTR_3 27 +#define BZ_X_MAPPING_1 28 +#define BZ_X_MAPPING_2 29 +#define BZ_X_SELECTOR_1 30 +#define BZ_X_SELECTOR_2 31 +#define BZ_X_SELECTOR_3 32 +#define BZ_X_CODING_1 33 +#define BZ_X_CODING_2 34 +#define BZ_X_CODING_3 35 +#define BZ_X_MTF_1 36 +#define BZ_X_MTF_2 37 +#define BZ_X_MTF_3 38 +#define BZ_X_MTF_4 39 +#define BZ_X_MTF_5 40 +#define BZ_X_MTF_6 41 +#define BZ_X_ENDHDR_2 42 +#define BZ_X_ENDHDR_3 43 +#define BZ_X_ENDHDR_4 44 +#define BZ_X_ENDHDR_5 45 +#define BZ_X_ENDHDR_6 46 +#define BZ_X_CCRC_1 47 +#define BZ_X_CCRC_2 48 +#define BZ_X_CCRC_3 49 +#define BZ_X_CCRC_4 50 + + + +/*-- Constants for the fast MTF decoder. --*/ + +#define MTFA_SIZE 4096 +#define MTFL_SIZE 16 + + + +/*-- Structure holding all the decompression-side stuff. --*/ + +typedef + struct { + /* pointer back to the struct bz_stream */ + bz_stream* strm; + + /* state indicator for this stream */ + Int32 state; + + /* for doing the final run-length decoding */ + UChar state_out_ch; + Int32 state_out_len; + Bool blockRandomised; + BZ_RAND_DECLS; + + /* the buffer for bit stream reading */ + UInt32 bsBuff; + Int32 bsLive; + + /* misc administratium */ + Int32 blockSize100k; + Bool smallDecompress; + Int32 currBlockNo; + Int32 verbosity; + + /* for undoing the Burrows-Wheeler transform */ + Int32 origPtr; + UInt32 tPos; + Int32 k0; + Int32 unzftab[256]; + Int32 nblock_used; + Int32 cftab[257]; + Int32 cftabCopy[257]; + + /* for undoing the Burrows-Wheeler transform (FAST) */ + UInt32 *tt; + + /* for undoing the Burrows-Wheeler transform (SMALL) */ + UInt16 *ll16; + UChar *ll4; + + /* stored and calculated CRCs */ + UInt32 storedBlockCRC; + UInt32 storedCombinedCRC; + UInt32 calculatedBlockCRC; + UInt32 calculatedCombinedCRC; + + /* map of bytes used in block */ + Int32 nInUse; + Bool inUse[256]; + Bool inUse16[16]; + UChar seqToUnseq[256]; + + /* for decoding the MTF values */ + UChar mtfa [MTFA_SIZE]; + Int32 mtfbase[256 / MTFL_SIZE]; + UChar selector [BZ_MAX_SELECTORS]; + UChar selectorMtf[BZ_MAX_SELECTORS]; + UChar len [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; + + Int32 limit [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; + Int32 base [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; + Int32 perm [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; + Int32 minLens[BZ_N_GROUPS]; + + /* save area for scalars in the main decompress code */ + Int32 save_i; + Int32 save_j; + Int32 save_t; + Int32 save_alphaSize; + Int32 save_nGroups; + Int32 save_nSelectors; + Int32 save_EOB; + Int32 save_groupNo; + Int32 save_groupPos; + Int32 save_nextSym; + Int32 save_nblockMAX; + Int32 save_nblock; + Int32 save_es; + Int32 save_N; + Int32 save_curr; + Int32 save_zt; + Int32 save_zn; + Int32 save_zvec; + Int32 save_zj; + Int32 save_gSel; + Int32 save_gMinlen; + Int32* save_gLimit; + Int32* save_gBase; + Int32* save_gPerm; + + } + DState; + + + +/*-- Macros for decompression. --*/ + +#define BZ_GET_FAST(cccc) \ + /* c_tPos is unsigned, hence test < 0 is pointless. */ \ + if (s->tPos >= (UInt32)100000 * (UInt32)s->blockSize100k) return True; \ + s->tPos = s->tt[s->tPos]; \ + cccc = (UChar)(s->tPos & 0xff); \ + s->tPos >>= 8; + +#define BZ_GET_FAST_C(cccc) \ + /* c_tPos is unsigned, hence test < 0 is pointless. */ \ + if (c_tPos >= (UInt32)100000 * (UInt32)ro_blockSize100k) return True; \ + c_tPos = c_tt[c_tPos]; \ + cccc = (UChar)(c_tPos & 0xff); \ + c_tPos >>= 8; + +#define SET_LL4(i,n) \ + { if (((i) & 0x1) == 0) \ + s->ll4[(i) >> 1] = (s->ll4[(i) >> 1] & 0xf0) | (n); else \ + s->ll4[(i) >> 1] = (s->ll4[(i) >> 1] & 0x0f) | ((n) << 4); \ + } + +#define GET_LL4(i) \ + ((((UInt32)(s->ll4[(i) >> 1])) >> (((i) << 2) & 0x4)) & 0xF) + +#define SET_LL(i,n) \ + { s->ll16[i] = (UInt16)(n & 0x0000ffff); \ + SET_LL4(i, n >> 16); \ + } + +#define GET_LL(i) \ + (((UInt32)s->ll16[i]) | (GET_LL4(i) << 16)) + +#define BZ_GET_SMALL(cccc) \ + /* c_tPos is unsigned, hence test < 0 is pointless. */ \ + if (s->tPos >= (UInt32)100000 * (UInt32)s->blockSize100k) return True; \ + cccc = BZ2_indexIntoF ( s->tPos, s->cftab ); \ + s->tPos = GET_LL(s->tPos); + + +/*-- externs for decompression. --*/ + +extern Int32 +BZ2_indexIntoF ( Int32, Int32* ); + +extern Int32 +BZ2_decompress ( DState* ); + +extern void +BZ2_hbCreateDecodeTables ( Int32*, Int32*, Int32*, UChar*, + Int32, Int32, Int32 ); + + +#endif + + +/*-- BZ_NO_STDIO seems to make NULL disappear on some platforms. --*/ + +#ifdef BZ_NO_STDIO +#ifndef NULL +#define NULL 0 +#endif +#endif + + +/*-------------------------------------------------------------*/ +/*--- end bzlib_private.h ---*/ +/*-------------------------------------------------------------*/ diff --git a/dep/bzip2/compress.c b/dep/bzip2/compress.c new file mode 100644 index 00000000000..8c80a079700 --- /dev/null +++ b/dep/bzip2/compress.c @@ -0,0 +1,672 @@ + +/*-------------------------------------------------------------*/ +/*--- Compression machinery (not incl block sorting) ---*/ +/*--- compress.c ---*/ +/*-------------------------------------------------------------*/ + +/* ------------------------------------------------------------------ + This file is part of bzip2/libbzip2, a program and library for + lossless, block-sorting data compression. + + bzip2/libbzip2 version 1.0.5 of 10 December 2007 + Copyright (C) 1996-2007 Julian Seward + + Please read the WARNING, DISCLAIMER and PATENTS sections in the + README file. + + This program is released under the terms of the license contained + in the file LICENSE. + ------------------------------------------------------------------ */ + + +/* CHANGES + 0.9.0 -- original version. + 0.9.0a/b -- no changes in this file. + 0.9.0c -- changed setting of nGroups in sendMTFValues() + so as to do a bit better on small files +*/ + +#include "bzlib_private.h" + + +/*---------------------------------------------------*/ +/*--- Bit stream I/O ---*/ +/*---------------------------------------------------*/ + +/*---------------------------------------------------*/ +void BZ2_bsInitWrite ( EState* s ) +{ + s->bsLive = 0; + s->bsBuff = 0; +} + + +/*---------------------------------------------------*/ +static +void bsFinishWrite ( EState* s ) +{ + while (s->bsLive > 0) { + s->zbits[s->numZ] = (UChar)(s->bsBuff >> 24); + s->numZ++; + s->bsBuff <<= 8; + s->bsLive -= 8; + } +} + + +/*---------------------------------------------------*/ +#define bsNEEDW(nz) \ +{ \ + while (s->bsLive >= 8) { \ + s->zbits[s->numZ] \ + = (UChar)(s->bsBuff >> 24); \ + s->numZ++; \ + s->bsBuff <<= 8; \ + s->bsLive -= 8; \ + } \ +} + + +/*---------------------------------------------------*/ +static +__inline__ +void bsW ( EState* s, Int32 n, UInt32 v ) +{ + bsNEEDW ( n ); + s->bsBuff |= (v << (32 - s->bsLive - n)); + s->bsLive += n; +} + + +/*---------------------------------------------------*/ +static +void bsPutUInt32 ( EState* s, UInt32 u ) +{ + bsW ( s, 8, (u >> 24) & 0xffL ); + bsW ( s, 8, (u >> 16) & 0xffL ); + bsW ( s, 8, (u >> 8) & 0xffL ); + bsW ( s, 8, u & 0xffL ); +} + + +/*---------------------------------------------------*/ +static +void bsPutUChar ( EState* s, UChar c ) +{ + bsW( s, 8, (UInt32)c ); +} + + +/*---------------------------------------------------*/ +/*--- The back end proper ---*/ +/*---------------------------------------------------*/ + +/*---------------------------------------------------*/ +static +void makeMaps_e ( EState* s ) +{ + Int32 i; + s->nInUse = 0; + for (i = 0; i < 256; i++) + if (s->inUse[i]) { + s->unseqToSeq[i] = s->nInUse; + s->nInUse++; + } +} + + +/*---------------------------------------------------*/ +static +void generateMTFValues ( EState* s ) +{ + UChar yy[256]; + Int32 i, j; + Int32 zPend; + Int32 wr; + Int32 EOB; + + /* + After sorting (eg, here), + s->arr1 [ 0 .. s->nblock-1 ] holds sorted order, + and + ((UChar*)s->arr2) [ 0 .. s->nblock-1 ] + holds the original block data. + + The first thing to do is generate the MTF values, + and put them in + ((UInt16*)s->arr1) [ 0 .. s->nblock-1 ]. + Because there are strictly fewer or equal MTF values + than block values, ptr values in this area are overwritten + with MTF values only when they are no longer needed. + + The final compressed bitstream is generated into the + area starting at + (UChar*) (&((UChar*)s->arr2)[s->nblock]) + + These storage aliases are set up in bzCompressInit(), + except for the last one, which is arranged in + compressBlock(). + */ + UInt32* ptr = s->ptr; + UChar* block = s->block; + UInt16* mtfv = s->mtfv; + + makeMaps_e ( s ); + EOB = s->nInUse+1; + + for (i = 0; i <= EOB; i++) s->mtfFreq[i] = 0; + + wr = 0; + zPend = 0; + for (i = 0; i < s->nInUse; i++) yy[i] = (UChar) i; + + for (i = 0; i < s->nblock; i++) { + UChar ll_i; + AssertD ( wr <= i, "generateMTFValues(1)" ); + j = ptr[i]-1; if (j < 0) j += s->nblock; + ll_i = s->unseqToSeq[block[j]]; + AssertD ( ll_i < s->nInUse, "generateMTFValues(2a)" ); + + if (yy[0] == ll_i) { + zPend++; + } else { + + if (zPend > 0) { + zPend--; + while (True) { + if (zPend & 1) { + mtfv[wr] = BZ_RUNB; wr++; + s->mtfFreq[BZ_RUNB]++; + } else { + mtfv[wr] = BZ_RUNA; wr++; + s->mtfFreq[BZ_RUNA]++; + } + if (zPend < 2) break; + zPend = (zPend - 2) / 2; + }; + zPend = 0; + } + { + register UChar rtmp; + register UChar* ryy_j; + register UChar rll_i; + rtmp = yy[1]; + yy[1] = yy[0]; + ryy_j = &(yy[1]); + rll_i = ll_i; + while ( rll_i != rtmp ) { + register UChar rtmp2; + ryy_j++; + rtmp2 = rtmp; + rtmp = *ryy_j; + *ryy_j = rtmp2; + }; + yy[0] = rtmp; + j = ryy_j - &(yy[0]); + mtfv[wr] = j+1; wr++; s->mtfFreq[j+1]++; + } + + } + } + + if (zPend > 0) { + zPend--; + while (True) { + if (zPend & 1) { + mtfv[wr] = BZ_RUNB; wr++; + s->mtfFreq[BZ_RUNB]++; + } else { + mtfv[wr] = BZ_RUNA; wr++; + s->mtfFreq[BZ_RUNA]++; + } + if (zPend < 2) break; + zPend = (zPend - 2) / 2; + }; + zPend = 0; + } + + mtfv[wr] = EOB; wr++; s->mtfFreq[EOB]++; + + s->nMTF = wr; +} + + +/*---------------------------------------------------*/ +#define BZ_LESSER_ICOST 0 +#define BZ_GREATER_ICOST 15 + +static +void sendMTFValues ( EState* s ) +{ + Int32 v, t, i, j, gs, ge, totc, bt, bc, iter; + Int32 nSelectors, alphaSize, minLen, maxLen, selCtr; + Int32 nGroups, nBytes; + + /*-- + UChar len [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; + is a global since the decoder also needs it. + + Int32 code[BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; + Int32 rfreq[BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; + are also globals only used in this proc. + Made global to keep stack frame size small. + --*/ + + + UInt16 cost[BZ_N_GROUPS]; + Int32 fave[BZ_N_GROUPS]; + + UInt16* mtfv = s->mtfv; + + if (s->verbosity >= 3) + VPrintf3( " %d in block, %d after MTF & 1-2 coding, " + "%d+2 syms in use\n", + s->nblock, s->nMTF, s->nInUse ); + + alphaSize = s->nInUse+2; + for (t = 0; t < BZ_N_GROUPS; t++) + for (v = 0; v < alphaSize; v++) + s->len[t][v] = BZ_GREATER_ICOST; + + /*--- Decide how many coding tables to use ---*/ + AssertH ( s->nMTF > 0, 3001 ); + if (s->nMTF < 200) nGroups = 2; else + if (s->nMTF < 600) nGroups = 3; else + if (s->nMTF < 1200) nGroups = 4; else + if (s->nMTF < 2400) nGroups = 5; else + nGroups = 6; + + /*--- Generate an initial set of coding tables ---*/ + { + Int32 nPart, remF, tFreq, aFreq; + + nPart = nGroups; + remF = s->nMTF; + gs = 0; + while (nPart > 0) { + tFreq = remF / nPart; + ge = gs-1; + aFreq = 0; + while (aFreq < tFreq && ge < alphaSize-1) { + ge++; + aFreq += s->mtfFreq[ge]; + } + + if (ge > gs + && nPart != nGroups && nPart != 1 + && ((nGroups-nPart) % 2 == 1)) { + aFreq -= s->mtfFreq[ge]; + ge--; + } + + if (s->verbosity >= 3) + VPrintf5( " initial group %d, [%d .. %d], " + "has %d syms (%4.1f%%)\n", + nPart, gs, ge, aFreq, + (100.0 * (float)aFreq) / (float)(s->nMTF) ); + + for (v = 0; v < alphaSize; v++) + if (v >= gs && v <= ge) + s->len[nPart-1][v] = BZ_LESSER_ICOST; else + s->len[nPart-1][v] = BZ_GREATER_ICOST; + + nPart--; + gs = ge+1; + remF -= aFreq; + } + } + + /*--- + Iterate up to BZ_N_ITERS times to improve the tables. + ---*/ + for (iter = 0; iter < BZ_N_ITERS; iter++) { + + for (t = 0; t < nGroups; t++) fave[t] = 0; + + for (t = 0; t < nGroups; t++) + for (v = 0; v < alphaSize; v++) + s->rfreq[t][v] = 0; + + /*--- + Set up an auxiliary length table which is used to fast-track + the common case (nGroups == 6). + ---*/ + if (nGroups == 6) { + for (v = 0; v < alphaSize; v++) { + s->len_pack[v][0] = (s->len[1][v] << 16) | s->len[0][v]; + s->len_pack[v][1] = (s->len[3][v] << 16) | s->len[2][v]; + s->len_pack[v][2] = (s->len[5][v] << 16) | s->len[4][v]; + } + } + + nSelectors = 0; + totc = 0; + gs = 0; + while (True) { + + /*--- Set group start & end marks. --*/ + if (gs >= s->nMTF) break; + ge = gs + BZ_G_SIZE - 1; + if (ge >= s->nMTF) ge = s->nMTF-1; + + /*-- + Calculate the cost of this group as coded + by each of the coding tables. + --*/ + for (t = 0; t < nGroups; t++) cost[t] = 0; + + if (nGroups == 6 && 50 == ge-gs+1) { + /*--- fast track the common case ---*/ + register UInt32 cost01, cost23, cost45; + register UInt16 icv; + cost01 = cost23 = cost45 = 0; + +# define BZ_ITER(nn) \ + icv = mtfv[gs+(nn)]; \ + cost01 += s->len_pack[icv][0]; \ + cost23 += s->len_pack[icv][1]; \ + cost45 += s->len_pack[icv][2]; \ + + BZ_ITER(0); BZ_ITER(1); BZ_ITER(2); BZ_ITER(3); BZ_ITER(4); + BZ_ITER(5); BZ_ITER(6); BZ_ITER(7); BZ_ITER(8); BZ_ITER(9); + BZ_ITER(10); BZ_ITER(11); BZ_ITER(12); BZ_ITER(13); BZ_ITER(14); + BZ_ITER(15); BZ_ITER(16); BZ_ITER(17); BZ_ITER(18); BZ_ITER(19); + BZ_ITER(20); BZ_ITER(21); BZ_ITER(22); BZ_ITER(23); BZ_ITER(24); + BZ_ITER(25); BZ_ITER(26); BZ_ITER(27); BZ_ITER(28); BZ_ITER(29); + BZ_ITER(30); BZ_ITER(31); BZ_ITER(32); BZ_ITER(33); BZ_ITER(34); + BZ_ITER(35); BZ_ITER(36); BZ_ITER(37); BZ_ITER(38); BZ_ITER(39); + BZ_ITER(40); BZ_ITER(41); BZ_ITER(42); BZ_ITER(43); BZ_ITER(44); + BZ_ITER(45); BZ_ITER(46); BZ_ITER(47); BZ_ITER(48); BZ_ITER(49); + +# undef BZ_ITER + + cost[0] = cost01 & 0xffff; cost[1] = cost01 >> 16; + cost[2] = cost23 & 0xffff; cost[3] = cost23 >> 16; + cost[4] = cost45 & 0xffff; cost[5] = cost45 >> 16; + + } else { + /*--- slow version which correctly handles all situations ---*/ + for (i = gs; i <= ge; i++) { + UInt16 icv = mtfv[i]; + for (t = 0; t < nGroups; t++) cost[t] += s->len[t][icv]; + } + } + + /*-- + Find the coding table which is best for this group, + and record its identity in the selector table. + --*/ + bc = 999999999; bt = -1; + for (t = 0; t < nGroups; t++) + if (cost[t] < bc) { bc = cost[t]; bt = t; }; + totc += bc; + fave[bt]++; + s->selector[nSelectors] = bt; + nSelectors++; + + /*-- + Increment the symbol frequencies for the selected table. + --*/ + if (nGroups == 6 && 50 == ge-gs+1) { + /*--- fast track the common case ---*/ + +# define BZ_ITUR(nn) s->rfreq[bt][ mtfv[gs+(nn)] ]++ + + BZ_ITUR(0); BZ_ITUR(1); BZ_ITUR(2); BZ_ITUR(3); BZ_ITUR(4); + BZ_ITUR(5); BZ_ITUR(6); BZ_ITUR(7); BZ_ITUR(8); BZ_ITUR(9); + BZ_ITUR(10); BZ_ITUR(11); BZ_ITUR(12); BZ_ITUR(13); BZ_ITUR(14); + BZ_ITUR(15); BZ_ITUR(16); BZ_ITUR(17); BZ_ITUR(18); BZ_ITUR(19); + BZ_ITUR(20); BZ_ITUR(21); BZ_ITUR(22); BZ_ITUR(23); BZ_ITUR(24); + BZ_ITUR(25); BZ_ITUR(26); BZ_ITUR(27); BZ_ITUR(28); BZ_ITUR(29); + BZ_ITUR(30); BZ_ITUR(31); BZ_ITUR(32); BZ_ITUR(33); BZ_ITUR(34); + BZ_ITUR(35); BZ_ITUR(36); BZ_ITUR(37); BZ_ITUR(38); BZ_ITUR(39); + BZ_ITUR(40); BZ_ITUR(41); BZ_ITUR(42); BZ_ITUR(43); BZ_ITUR(44); + BZ_ITUR(45); BZ_ITUR(46); BZ_ITUR(47); BZ_ITUR(48); BZ_ITUR(49); + +# undef BZ_ITUR + + } else { + /*--- slow version which correctly handles all situations ---*/ + for (i = gs; i <= ge; i++) + s->rfreq[bt][ mtfv[i] ]++; + } + + gs = ge+1; + } + if (s->verbosity >= 3) { + VPrintf2 ( " pass %d: size is %d, grp uses are ", + iter+1, totc/8 ); + for (t = 0; t < nGroups; t++) + VPrintf1 ( "%d ", fave[t] ); + VPrintf0 ( "\n" ); + } + + /*-- + Recompute the tables based on the accumulated frequencies. + --*/ + /* maxLen was changed from 20 to 17 in bzip2-1.0.3. See + comment in huffman.c for details. */ + for (t = 0; t < nGroups; t++) + BZ2_hbMakeCodeLengths ( &(s->len[t][0]), &(s->rfreq[t][0]), + alphaSize, 17 /*20*/ ); + } + + + AssertH( nGroups < 8, 3002 ); + AssertH( nSelectors < 32768 && + nSelectors <= (2 + (900000 / BZ_G_SIZE)), + 3003 ); + + + /*--- Compute MTF values for the selectors. ---*/ + { + UChar pos[BZ_N_GROUPS], ll_i, tmp2, tmp; + for (i = 0; i < nGroups; i++) pos[i] = i; + for (i = 0; i < nSelectors; i++) { + ll_i = s->selector[i]; + j = 0; + tmp = pos[j]; + while ( ll_i != tmp ) { + j++; + tmp2 = tmp; + tmp = pos[j]; + pos[j] = tmp2; + }; + pos[0] = tmp; + s->selectorMtf[i] = j; + } + }; + + /*--- Assign actual codes for the tables. --*/ + for (t = 0; t < nGroups; t++) { + minLen = 32; + maxLen = 0; + for (i = 0; i < alphaSize; i++) { + if (s->len[t][i] > maxLen) maxLen = s->len[t][i]; + if (s->len[t][i] < minLen) minLen = s->len[t][i]; + } + AssertH ( !(maxLen > 17 /*20*/ ), 3004 ); + AssertH ( !(minLen < 1), 3005 ); + BZ2_hbAssignCodes ( &(s->code[t][0]), &(s->len[t][0]), + minLen, maxLen, alphaSize ); + } + + /*--- Transmit the mapping table. ---*/ + { + Bool inUse16[16]; + for (i = 0; i < 16; i++) { + inUse16[i] = False; + for (j = 0; j < 16; j++) + if (s->inUse[i * 16 + j]) inUse16[i] = True; + } + + nBytes = s->numZ; + for (i = 0; i < 16; i++) + if (inUse16[i]) bsW(s,1,1); else bsW(s,1,0); + + for (i = 0; i < 16; i++) + if (inUse16[i]) + for (j = 0; j < 16; j++) { + if (s->inUse[i * 16 + j]) bsW(s,1,1); else bsW(s,1,0); + } + + if (s->verbosity >= 3) + VPrintf1( " bytes: mapping %d, ", s->numZ-nBytes ); + } + + /*--- Now the selectors. ---*/ + nBytes = s->numZ; + bsW ( s, 3, nGroups ); + bsW ( s, 15, nSelectors ); + for (i = 0; i < nSelectors; i++) { + for (j = 0; j < s->selectorMtf[i]; j++) bsW(s,1,1); + bsW(s,1,0); + } + if (s->verbosity >= 3) + VPrintf1( "selectors %d, ", s->numZ-nBytes ); + + /*--- Now the coding tables. ---*/ + nBytes = s->numZ; + + for (t = 0; t < nGroups; t++) { + Int32 curr = s->len[t][0]; + bsW ( s, 5, curr ); + for (i = 0; i < alphaSize; i++) { + while (curr < s->len[t][i]) { bsW(s,2,2); curr++; /* 10 */ }; + while (curr > s->len[t][i]) { bsW(s,2,3); curr--; /* 11 */ }; + bsW ( s, 1, 0 ); + } + } + + if (s->verbosity >= 3) + VPrintf1 ( "code lengths %d, ", s->numZ-nBytes ); + + /*--- And finally, the block data proper ---*/ + nBytes = s->numZ; + selCtr = 0; + gs = 0; + while (True) { + if (gs >= s->nMTF) break; + ge = gs + BZ_G_SIZE - 1; + if (ge >= s->nMTF) ge = s->nMTF-1; + AssertH ( s->selector[selCtr] < nGroups, 3006 ); + + if (nGroups == 6 && 50 == ge-gs+1) { + /*--- fast track the common case ---*/ + UInt16 mtfv_i; + UChar* s_len_sel_selCtr + = &(s->len[s->selector[selCtr]][0]); + Int32* s_code_sel_selCtr + = &(s->code[s->selector[selCtr]][0]); + +# define BZ_ITAH(nn) \ + mtfv_i = mtfv[gs+(nn)]; \ + bsW ( s, \ + s_len_sel_selCtr[mtfv_i], \ + s_code_sel_selCtr[mtfv_i] ) + + BZ_ITAH(0); BZ_ITAH(1); BZ_ITAH(2); BZ_ITAH(3); BZ_ITAH(4); + BZ_ITAH(5); BZ_ITAH(6); BZ_ITAH(7); BZ_ITAH(8); BZ_ITAH(9); + BZ_ITAH(10); BZ_ITAH(11); BZ_ITAH(12); BZ_ITAH(13); BZ_ITAH(14); + BZ_ITAH(15); BZ_ITAH(16); BZ_ITAH(17); BZ_ITAH(18); BZ_ITAH(19); + BZ_ITAH(20); BZ_ITAH(21); BZ_ITAH(22); BZ_ITAH(23); BZ_ITAH(24); + BZ_ITAH(25); BZ_ITAH(26); BZ_ITAH(27); BZ_ITAH(28); BZ_ITAH(29); + BZ_ITAH(30); BZ_ITAH(31); BZ_ITAH(32); BZ_ITAH(33); BZ_ITAH(34); + BZ_ITAH(35); BZ_ITAH(36); BZ_ITAH(37); BZ_ITAH(38); BZ_ITAH(39); + BZ_ITAH(40); BZ_ITAH(41); BZ_ITAH(42); BZ_ITAH(43); BZ_ITAH(44); + BZ_ITAH(45); BZ_ITAH(46); BZ_ITAH(47); BZ_ITAH(48); BZ_ITAH(49); + +# undef BZ_ITAH + + } else { + /*--- slow version which correctly handles all situations ---*/ + for (i = gs; i <= ge; i++) { + bsW ( s, + s->len [s->selector[selCtr]] [mtfv[i]], + s->code [s->selector[selCtr]] [mtfv[i]] ); + } + } + + + gs = ge+1; + selCtr++; + } + AssertH( selCtr == nSelectors, 3007 ); + + if (s->verbosity >= 3) + VPrintf1( "codes %d\n", s->numZ-nBytes ); +} + + +/*---------------------------------------------------*/ +void BZ2_compressBlock ( EState* s, Bool is_last_block ) +{ + if (s->nblock > 0) { + + BZ_FINALISE_CRC ( s->blockCRC ); + s->combinedCRC = (s->combinedCRC << 1) | (s->combinedCRC >> 31); + s->combinedCRC ^= s->blockCRC; + if (s->blockNo > 1) s->numZ = 0; + + if (s->verbosity >= 2) + VPrintf4( " block %d: crc = 0x%08x, " + "combined CRC = 0x%08x, size = %d\n", + s->blockNo, s->blockCRC, s->combinedCRC, s->nblock ); + + BZ2_blockSort ( s ); + } + + s->zbits = (UChar*) (&((UChar*)s->arr2)[s->nblock]); + + /*-- If this is the first block, create the stream header. --*/ + if (s->blockNo == 1) { + BZ2_bsInitWrite ( s ); + bsPutUChar ( s, BZ_HDR_B ); + bsPutUChar ( s, BZ_HDR_Z ); + bsPutUChar ( s, BZ_HDR_h ); + bsPutUChar ( s, (UChar)(BZ_HDR_0 + s->blockSize100k) ); + } + + if (s->nblock > 0) { + + bsPutUChar ( s, 0x31 ); bsPutUChar ( s, 0x41 ); + bsPutUChar ( s, 0x59 ); bsPutUChar ( s, 0x26 ); + bsPutUChar ( s, 0x53 ); bsPutUChar ( s, 0x59 ); + + /*-- Now the block's CRC, so it is in a known place. --*/ + bsPutUInt32 ( s, s->blockCRC ); + + /*-- + Now a single bit indicating (non-)randomisation. + As of version 0.9.5, we use a better sorting algorithm + which makes randomisation unnecessary. So always set + the randomised bit to 'no'. Of course, the decoder + still needs to be able to handle randomised blocks + so as to maintain backwards compatibility with + older versions of bzip2. + --*/ + bsW(s,1,0); + + bsW ( s, 24, s->origPtr ); + generateMTFValues ( s ); + sendMTFValues ( s ); + } + + + /*-- If this is the last block, add the stream trailer. --*/ + if (is_last_block) { + + bsPutUChar ( s, 0x17 ); bsPutUChar ( s, 0x72 ); + bsPutUChar ( s, 0x45 ); bsPutUChar ( s, 0x38 ); + bsPutUChar ( s, 0x50 ); bsPutUChar ( s, 0x90 ); + bsPutUInt32 ( s, s->combinedCRC ); + if (s->verbosity >= 2) + VPrintf1( " final combined CRC = 0x%08x\n ", s->combinedCRC ); + bsFinishWrite ( s ); + } +} + + +/*-------------------------------------------------------------*/ +/*--- end compress.c ---*/ +/*-------------------------------------------------------------*/ diff --git a/dep/bzip2/crctable.c b/dep/bzip2/crctable.c new file mode 100644 index 00000000000..215687b2c05 --- /dev/null +++ b/dep/bzip2/crctable.c @@ -0,0 +1,104 @@ + +/*-------------------------------------------------------------*/ +/*--- Table for doing CRCs ---*/ +/*--- crctable.c ---*/ +/*-------------------------------------------------------------*/ + +/* ------------------------------------------------------------------ + This file is part of bzip2/libbzip2, a program and library for + lossless, block-sorting data compression. + + bzip2/libbzip2 version 1.0.5 of 10 December 2007 + Copyright (C) 1996-2007 Julian Seward + + Please read the WARNING, DISCLAIMER and PATENTS sections in the + README file. + + This program is released under the terms of the license contained + in the file LICENSE. + ------------------------------------------------------------------ */ + + +#include "bzlib_private.h" + +/*-- + I think this is an implementation of the AUTODIN-II, + Ethernet & FDDI 32-bit CRC standard. Vaguely derived + from code by Rob Warnock, in Section 51 of the + comp.compression FAQ. +--*/ + +UInt32 BZ2_crc32Table[256] = { + + /*-- Ugly, innit? --*/ + + 0x00000000L, 0x04c11db7L, 0x09823b6eL, 0x0d4326d9L, + 0x130476dcL, 0x17c56b6bL, 0x1a864db2L, 0x1e475005L, + 0x2608edb8L, 0x22c9f00fL, 0x2f8ad6d6L, 0x2b4bcb61L, + 0x350c9b64L, 0x31cd86d3L, 0x3c8ea00aL, 0x384fbdbdL, + 0x4c11db70L, 0x48d0c6c7L, 0x4593e01eL, 0x4152fda9L, + 0x5f15adacL, 0x5bd4b01bL, 0x569796c2L, 0x52568b75L, + 0x6a1936c8L, 0x6ed82b7fL, 0x639b0da6L, 0x675a1011L, + 0x791d4014L, 0x7ddc5da3L, 0x709f7b7aL, 0x745e66cdL, + 0x9823b6e0L, 0x9ce2ab57L, 0x91a18d8eL, 0x95609039L, + 0x8b27c03cL, 0x8fe6dd8bL, 0x82a5fb52L, 0x8664e6e5L, + 0xbe2b5b58L, 0xbaea46efL, 0xb7a96036L, 0xb3687d81L, + 0xad2f2d84L, 0xa9ee3033L, 0xa4ad16eaL, 0xa06c0b5dL, + 0xd4326d90L, 0xd0f37027L, 0xddb056feL, 0xd9714b49L, + 0xc7361b4cL, 0xc3f706fbL, 0xceb42022L, 0xca753d95L, + 0xf23a8028L, 0xf6fb9d9fL, 0xfbb8bb46L, 0xff79a6f1L, + 0xe13ef6f4L, 0xe5ffeb43L, 0xe8bccd9aL, 0xec7dd02dL, + 0x34867077L, 0x30476dc0L, 0x3d044b19L, 0x39c556aeL, + 0x278206abL, 0x23431b1cL, 0x2e003dc5L, 0x2ac12072L, + 0x128e9dcfL, 0x164f8078L, 0x1b0ca6a1L, 0x1fcdbb16L, + 0x018aeb13L, 0x054bf6a4L, 0x0808d07dL, 0x0cc9cdcaL, + 0x7897ab07L, 0x7c56b6b0L, 0x71159069L, 0x75d48ddeL, + 0x6b93dddbL, 0x6f52c06cL, 0x6211e6b5L, 0x66d0fb02L, + 0x5e9f46bfL, 0x5a5e5b08L, 0x571d7dd1L, 0x53dc6066L, + 0x4d9b3063L, 0x495a2dd4L, 0x44190b0dL, 0x40d816baL, + 0xaca5c697L, 0xa864db20L, 0xa527fdf9L, 0xa1e6e04eL, + 0xbfa1b04bL, 0xbb60adfcL, 0xb6238b25L, 0xb2e29692L, + 0x8aad2b2fL, 0x8e6c3698L, 0x832f1041L, 0x87ee0df6L, + 0x99a95df3L, 0x9d684044L, 0x902b669dL, 0x94ea7b2aL, + 0xe0b41de7L, 0xe4750050L, 0xe9362689L, 0xedf73b3eL, + 0xf3b06b3bL, 0xf771768cL, 0xfa325055L, 0xfef34de2L, + 0xc6bcf05fL, 0xc27dede8L, 0xcf3ecb31L, 0xcbffd686L, + 0xd5b88683L, 0xd1799b34L, 0xdc3abdedL, 0xd8fba05aL, + 0x690ce0eeL, 0x6dcdfd59L, 0x608edb80L, 0x644fc637L, + 0x7a089632L, 0x7ec98b85L, 0x738aad5cL, 0x774bb0ebL, + 0x4f040d56L, 0x4bc510e1L, 0x46863638L, 0x42472b8fL, + 0x5c007b8aL, 0x58c1663dL, 0x558240e4L, 0x51435d53L, + 0x251d3b9eL, 0x21dc2629L, 0x2c9f00f0L, 0x285e1d47L, + 0x36194d42L, 0x32d850f5L, 0x3f9b762cL, 0x3b5a6b9bL, + 0x0315d626L, 0x07d4cb91L, 0x0a97ed48L, 0x0e56f0ffL, + 0x1011a0faL, 0x14d0bd4dL, 0x19939b94L, 0x1d528623L, + 0xf12f560eL, 0xf5ee4bb9L, 0xf8ad6d60L, 0xfc6c70d7L, + 0xe22b20d2L, 0xe6ea3d65L, 0xeba91bbcL, 0xef68060bL, + 0xd727bbb6L, 0xd3e6a601L, 0xdea580d8L, 0xda649d6fL, + 0xc423cd6aL, 0xc0e2d0ddL, 0xcda1f604L, 0xc960ebb3L, + 0xbd3e8d7eL, 0xb9ff90c9L, 0xb4bcb610L, 0xb07daba7L, + 0xae3afba2L, 0xaafbe615L, 0xa7b8c0ccL, 0xa379dd7bL, + 0x9b3660c6L, 0x9ff77d71L, 0x92b45ba8L, 0x9675461fL, + 0x8832161aL, 0x8cf30badL, 0x81b02d74L, 0x857130c3L, + 0x5d8a9099L, 0x594b8d2eL, 0x5408abf7L, 0x50c9b640L, + 0x4e8ee645L, 0x4a4ffbf2L, 0x470cdd2bL, 0x43cdc09cL, + 0x7b827d21L, 0x7f436096L, 0x7200464fL, 0x76c15bf8L, + 0x68860bfdL, 0x6c47164aL, 0x61043093L, 0x65c52d24L, + 0x119b4be9L, 0x155a565eL, 0x18197087L, 0x1cd86d30L, + 0x029f3d35L, 0x065e2082L, 0x0b1d065bL, 0x0fdc1becL, + 0x3793a651L, 0x3352bbe6L, 0x3e119d3fL, 0x3ad08088L, + 0x2497d08dL, 0x2056cd3aL, 0x2d15ebe3L, 0x29d4f654L, + 0xc5a92679L, 0xc1683bceL, 0xcc2b1d17L, 0xc8ea00a0L, + 0xd6ad50a5L, 0xd26c4d12L, 0xdf2f6bcbL, 0xdbee767cL, + 0xe3a1cbc1L, 0xe760d676L, 0xea23f0afL, 0xeee2ed18L, + 0xf0a5bd1dL, 0xf464a0aaL, 0xf9278673L, 0xfde69bc4L, + 0x89b8fd09L, 0x8d79e0beL, 0x803ac667L, 0x84fbdbd0L, + 0x9abc8bd5L, 0x9e7d9662L, 0x933eb0bbL, 0x97ffad0cL, + 0xafb010b1L, 0xab710d06L, 0xa6322bdfL, 0xa2f33668L, + 0xbcb4666dL, 0xb8757bdaL, 0xb5365d03L, 0xb1f740b4L +}; + + +/*-------------------------------------------------------------*/ +/*--- end crctable.c ---*/ +/*-------------------------------------------------------------*/ diff --git a/dep/bzip2/decompress.c b/dep/bzip2/decompress.c new file mode 100644 index 00000000000..bba5e0fa36d --- /dev/null +++ b/dep/bzip2/decompress.c @@ -0,0 +1,626 @@ + +/*-------------------------------------------------------------*/ +/*--- Decompression machinery ---*/ +/*--- decompress.c ---*/ +/*-------------------------------------------------------------*/ + +/* ------------------------------------------------------------------ + This file is part of bzip2/libbzip2, a program and library for + lossless, block-sorting data compression. + + bzip2/libbzip2 version 1.0.5 of 10 December 2007 + Copyright (C) 1996-2007 Julian Seward + + Please read the WARNING, DISCLAIMER and PATENTS sections in the + README file. + + This program is released under the terms of the license contained + in the file LICENSE. + ------------------------------------------------------------------ */ + + +#include "bzlib_private.h" + + +/*---------------------------------------------------*/ +static +void makeMaps_d ( DState* s ) +{ + Int32 i; + s->nInUse = 0; + for (i = 0; i < 256; i++) + if (s->inUse[i]) { + s->seqToUnseq[s->nInUse] = i; + s->nInUse++; + } +} + + +/*---------------------------------------------------*/ +#define RETURN(rrr) \ + { retVal = rrr; goto save_state_and_return; }; + +#define GET_BITS(lll,vvv,nnn) \ + case lll: s->state = lll; \ + while (True) { \ + if (s->bsLive >= nnn) { \ + UInt32 v; \ + v = (s->bsBuff >> \ + (s->bsLive-nnn)) & ((1 << nnn)-1); \ + s->bsLive -= nnn; \ + vvv = v; \ + break; \ + } \ + if (s->strm->avail_in == 0) RETURN(BZ_OK); \ + s->bsBuff \ + = (s->bsBuff << 8) | \ + ((UInt32) \ + (*((UChar*)(s->strm->next_in)))); \ + s->bsLive += 8; \ + s->strm->next_in++; \ + s->strm->avail_in--; \ + s->strm->total_in_lo32++; \ + if (s->strm->total_in_lo32 == 0) \ + s->strm->total_in_hi32++; \ + } + +#define GET_UCHAR(lll,uuu) \ + GET_BITS(lll,uuu,8) + +#define GET_BIT(lll,uuu) \ + GET_BITS(lll,uuu,1) + +/*---------------------------------------------------*/ +#define GET_MTF_VAL(label1,label2,lval) \ +{ \ + if (groupPos == 0) { \ + groupNo++; \ + if (groupNo >= nSelectors) \ + RETURN(BZ_DATA_ERROR); \ + groupPos = BZ_G_SIZE; \ + gSel = s->selector[groupNo]; \ + gMinlen = s->minLens[gSel]; \ + gLimit = &(s->limit[gSel][0]); \ + gPerm = &(s->perm[gSel][0]); \ + gBase = &(s->base[gSel][0]); \ + } \ + groupPos--; \ + zn = gMinlen; \ + GET_BITS(label1, zvec, zn); \ + while (1) { \ + if (zn > 20 /* the longest code */) \ + RETURN(BZ_DATA_ERROR); \ + if (zvec <= gLimit[zn]) break; \ + zn++; \ + GET_BIT(label2, zj); \ + zvec = (zvec << 1) | zj; \ + }; \ + if (zvec - gBase[zn] < 0 \ + || zvec - gBase[zn] >= BZ_MAX_ALPHA_SIZE) \ + RETURN(BZ_DATA_ERROR); \ + lval = gPerm[zvec - gBase[zn]]; \ +} + + +/*---------------------------------------------------*/ +Int32 BZ2_decompress ( DState* s ) +{ + UChar uc; + Int32 retVal; + Int32 minLen, maxLen; + bz_stream* strm = s->strm; + + /* stuff that needs to be saved/restored */ + Int32 i; + Int32 j; + Int32 t; + Int32 alphaSize; + Int32 nGroups; + Int32 nSelectors; + Int32 EOB; + Int32 groupNo; + Int32 groupPos; + Int32 nextSym; + Int32 nblockMAX; + Int32 nblock; + Int32 es; + Int32 N; + Int32 curr; + Int32 zt; + Int32 zn; + Int32 zvec; + Int32 zj; + Int32 gSel; + Int32 gMinlen; + Int32* gLimit; + Int32* gBase; + Int32* gPerm; + + if (s->state == BZ_X_MAGIC_1) { + /*initialise the save area*/ + s->save_i = 0; + s->save_j = 0; + s->save_t = 0; + s->save_alphaSize = 0; + s->save_nGroups = 0; + s->save_nSelectors = 0; + s->save_EOB = 0; + s->save_groupNo = 0; + s->save_groupPos = 0; + s->save_nextSym = 0; + s->save_nblockMAX = 0; + s->save_nblock = 0; + s->save_es = 0; + s->save_N = 0; + s->save_curr = 0; + s->save_zt = 0; + s->save_zn = 0; + s->save_zvec = 0; + s->save_zj = 0; + s->save_gSel = 0; + s->save_gMinlen = 0; + s->save_gLimit = NULL; + s->save_gBase = NULL; + s->save_gPerm = NULL; + } + + /*restore from the save area*/ + i = s->save_i; + j = s->save_j; + t = s->save_t; + alphaSize = s->save_alphaSize; + nGroups = s->save_nGroups; + nSelectors = s->save_nSelectors; + EOB = s->save_EOB; + groupNo = s->save_groupNo; + groupPos = s->save_groupPos; + nextSym = s->save_nextSym; + nblockMAX = s->save_nblockMAX; + nblock = s->save_nblock; + es = s->save_es; + N = s->save_N; + curr = s->save_curr; + zt = s->save_zt; + zn = s->save_zn; + zvec = s->save_zvec; + zj = s->save_zj; + gSel = s->save_gSel; + gMinlen = s->save_gMinlen; + gLimit = s->save_gLimit; + gBase = s->save_gBase; + gPerm = s->save_gPerm; + + retVal = BZ_OK; + + switch (s->state) { + + GET_UCHAR(BZ_X_MAGIC_1, uc); + if (uc != BZ_HDR_B) RETURN(BZ_DATA_ERROR_MAGIC); + + GET_UCHAR(BZ_X_MAGIC_2, uc); + if (uc != BZ_HDR_Z) RETURN(BZ_DATA_ERROR_MAGIC); + + GET_UCHAR(BZ_X_MAGIC_3, uc) + if (uc != BZ_HDR_h) RETURN(BZ_DATA_ERROR_MAGIC); + + GET_BITS(BZ_X_MAGIC_4, s->blockSize100k, 8) + if (s->blockSize100k < (BZ_HDR_0 + 1) || + s->blockSize100k > (BZ_HDR_0 + 9)) RETURN(BZ_DATA_ERROR_MAGIC); + s->blockSize100k -= BZ_HDR_0; + + if (s->smallDecompress) { + s->ll16 = BZALLOC( s->blockSize100k * 100000 * sizeof(UInt16) ); + s->ll4 = BZALLOC( + ((1 + s->blockSize100k * 100000) >> 1) * sizeof(UChar) + ); + if (s->ll16 == NULL || s->ll4 == NULL) RETURN(BZ_MEM_ERROR); + } else { + s->tt = BZALLOC( s->blockSize100k * 100000 * sizeof(Int32) ); + if (s->tt == NULL) RETURN(BZ_MEM_ERROR); + } + + GET_UCHAR(BZ_X_BLKHDR_1, uc); + + if (uc == 0x17) goto endhdr_2; + if (uc != 0x31) RETURN(BZ_DATA_ERROR); + GET_UCHAR(BZ_X_BLKHDR_2, uc); + if (uc != 0x41) RETURN(BZ_DATA_ERROR); + GET_UCHAR(BZ_X_BLKHDR_3, uc); + if (uc != 0x59) RETURN(BZ_DATA_ERROR); + GET_UCHAR(BZ_X_BLKHDR_4, uc); + if (uc != 0x26) RETURN(BZ_DATA_ERROR); + GET_UCHAR(BZ_X_BLKHDR_5, uc); + if (uc != 0x53) RETURN(BZ_DATA_ERROR); + GET_UCHAR(BZ_X_BLKHDR_6, uc); + if (uc != 0x59) RETURN(BZ_DATA_ERROR); + + s->currBlockNo++; + if (s->verbosity >= 2) + VPrintf1 ( "\n [%d: huff+mtf ", s->currBlockNo ); + + s->storedBlockCRC = 0; + GET_UCHAR(BZ_X_BCRC_1, uc); + s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); + GET_UCHAR(BZ_X_BCRC_2, uc); + s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); + GET_UCHAR(BZ_X_BCRC_3, uc); + s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); + GET_UCHAR(BZ_X_BCRC_4, uc); + s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); + + GET_BITS(BZ_X_RANDBIT, s->blockRandomised, 1); + + s->origPtr = 0; + GET_UCHAR(BZ_X_ORIGPTR_1, uc); + s->origPtr = (s->origPtr << 8) | ((Int32)uc); + GET_UCHAR(BZ_X_ORIGPTR_2, uc); + s->origPtr = (s->origPtr << 8) | ((Int32)uc); + GET_UCHAR(BZ_X_ORIGPTR_3, uc); + s->origPtr = (s->origPtr << 8) | ((Int32)uc); + + if (s->origPtr < 0) + RETURN(BZ_DATA_ERROR); + if (s->origPtr > 10 + 100000*s->blockSize100k) + RETURN(BZ_DATA_ERROR); + + /*--- Receive the mapping table ---*/ + for (i = 0; i < 16; i++) { + GET_BIT(BZ_X_MAPPING_1, uc); + if (uc == 1) + s->inUse16[i] = True; else + s->inUse16[i] = False; + } + + for (i = 0; i < 256; i++) s->inUse[i] = False; + + for (i = 0; i < 16; i++) + if (s->inUse16[i]) + for (j = 0; j < 16; j++) { + GET_BIT(BZ_X_MAPPING_2, uc); + if (uc == 1) s->inUse[i * 16 + j] = True; + } + makeMaps_d ( s ); + if (s->nInUse == 0) RETURN(BZ_DATA_ERROR); + alphaSize = s->nInUse+2; + + /*--- Now the selectors ---*/ + GET_BITS(BZ_X_SELECTOR_1, nGroups, 3); + if (nGroups < 2 || nGroups > 6) RETURN(BZ_DATA_ERROR); + GET_BITS(BZ_X_SELECTOR_2, nSelectors, 15); + if (nSelectors < 1) RETURN(BZ_DATA_ERROR); + for (i = 0; i < nSelectors; i++) { + j = 0; + while (True) { + GET_BIT(BZ_X_SELECTOR_3, uc); + if (uc == 0) break; + j++; + if (j >= nGroups) RETURN(BZ_DATA_ERROR); + } + s->selectorMtf[i] = j; + } + + /*--- Undo the MTF values for the selectors. ---*/ + { + UChar pos[BZ_N_GROUPS], tmp, v; + for (v = 0; v < nGroups; v++) pos[v] = v; + + for (i = 0; i < nSelectors; i++) { + v = s->selectorMtf[i]; + tmp = pos[v]; + while (v > 0) { pos[v] = pos[v-1]; v--; } + pos[0] = tmp; + s->selector[i] = tmp; + } + } + + /*--- Now the coding tables ---*/ + for (t = 0; t < nGroups; t++) { + GET_BITS(BZ_X_CODING_1, curr, 5); + for (i = 0; i < alphaSize; i++) { + while (True) { + if (curr < 1 || curr > 20) RETURN(BZ_DATA_ERROR); + GET_BIT(BZ_X_CODING_2, uc); + if (uc == 0) break; + GET_BIT(BZ_X_CODING_3, uc); + if (uc == 0) curr++; else curr--; + } + s->len[t][i] = curr; + } + } + + /*--- Create the Huffman decoding tables ---*/ + for (t = 0; t < nGroups; t++) { + minLen = 32; + maxLen = 0; + for (i = 0; i < alphaSize; i++) { + if (s->len[t][i] > maxLen) maxLen = s->len[t][i]; + if (s->len[t][i] < minLen) minLen = s->len[t][i]; + } + BZ2_hbCreateDecodeTables ( + &(s->limit[t][0]), + &(s->base[t][0]), + &(s->perm[t][0]), + &(s->len[t][0]), + minLen, maxLen, alphaSize + ); + s->minLens[t] = minLen; + } + + /*--- Now the MTF values ---*/ + + EOB = s->nInUse+1; + nblockMAX = 100000 * s->blockSize100k; + groupNo = -1; + groupPos = 0; + + for (i = 0; i <= 255; i++) s->unzftab[i] = 0; + + /*-- MTF init --*/ + { + Int32 ii, jj, kk; + kk = MTFA_SIZE-1; + for (ii = 256 / MTFL_SIZE - 1; ii >= 0; ii--) { + for (jj = MTFL_SIZE-1; jj >= 0; jj--) { + s->mtfa[kk] = (UChar)(ii * MTFL_SIZE + jj); + kk--; + } + s->mtfbase[ii] = kk + 1; + } + } + /*-- end MTF init --*/ + + nblock = 0; + GET_MTF_VAL(BZ_X_MTF_1, BZ_X_MTF_2, nextSym); + + while (True) { + + if (nextSym == EOB) break; + + if (nextSym == BZ_RUNA || nextSym == BZ_RUNB) { + + es = -1; + N = 1; + do { + if (nextSym == BZ_RUNA) es = es + (0+1) * N; else + if (nextSym == BZ_RUNB) es = es + (1+1) * N; + N = N * 2; + GET_MTF_VAL(BZ_X_MTF_3, BZ_X_MTF_4, nextSym); + } + while (nextSym == BZ_RUNA || nextSym == BZ_RUNB); + + es++; + uc = s->seqToUnseq[ s->mtfa[s->mtfbase[0]] ]; + s->unzftab[uc] += es; + + if (s->smallDecompress) + while (es > 0) { + if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); + s->ll16[nblock] = (UInt16)uc; + nblock++; + es--; + } + else + while (es > 0) { + if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); + s->tt[nblock] = (UInt32)uc; + nblock++; + es--; + }; + + continue; + + } else { + + if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); + + /*-- uc = MTF ( nextSym-1 ) --*/ + { + Int32 ii, jj, kk, pp, lno, off; + UInt32 nn; + nn = (UInt32)(nextSym - 1); + + if (nn < MTFL_SIZE) { + /* avoid general-case expense */ + pp = s->mtfbase[0]; + uc = s->mtfa[pp+nn]; + while (nn > 3) { + Int32 z = pp+nn; + s->mtfa[(z) ] = s->mtfa[(z)-1]; + s->mtfa[(z)-1] = s->mtfa[(z)-2]; + s->mtfa[(z)-2] = s->mtfa[(z)-3]; + s->mtfa[(z)-3] = s->mtfa[(z)-4]; + nn -= 4; + } + while (nn > 0) { + s->mtfa[(pp+nn)] = s->mtfa[(pp+nn)-1]; nn--; + }; + s->mtfa[pp] = uc; + } else { + /* general case */ + lno = nn / MTFL_SIZE; + off = nn % MTFL_SIZE; + pp = s->mtfbase[lno] + off; + uc = s->mtfa[pp]; + while (pp > s->mtfbase[lno]) { + s->mtfa[pp] = s->mtfa[pp-1]; pp--; + }; + s->mtfbase[lno]++; + while (lno > 0) { + s->mtfbase[lno]--; + s->mtfa[s->mtfbase[lno]] + = s->mtfa[s->mtfbase[lno-1] + MTFL_SIZE - 1]; + lno--; + } + s->mtfbase[0]--; + s->mtfa[s->mtfbase[0]] = uc; + if (s->mtfbase[0] == 0) { + kk = MTFA_SIZE-1; + for (ii = 256 / MTFL_SIZE-1; ii >= 0; ii--) { + for (jj = MTFL_SIZE-1; jj >= 0; jj--) { + s->mtfa[kk] = s->mtfa[s->mtfbase[ii] + jj]; + kk--; + } + s->mtfbase[ii] = kk + 1; + } + } + } + } + /*-- end uc = MTF ( nextSym-1 ) --*/ + + s->unzftab[s->seqToUnseq[uc]]++; + if (s->smallDecompress) + s->ll16[nblock] = (UInt16)(s->seqToUnseq[uc]); else + s->tt[nblock] = (UInt32)(s->seqToUnseq[uc]); + nblock++; + + GET_MTF_VAL(BZ_X_MTF_5, BZ_X_MTF_6, nextSym); + continue; + } + } + + /* Now we know what nblock is, we can do a better sanity + check on s->origPtr. + */ + if (s->origPtr < 0 || s->origPtr >= nblock) + RETURN(BZ_DATA_ERROR); + + /*-- Set up cftab to facilitate generation of T^(-1) --*/ + s->cftab[0] = 0; + for (i = 1; i <= 256; i++) s->cftab[i] = s->unzftab[i-1]; + for (i = 1; i <= 256; i++) s->cftab[i] += s->cftab[i-1]; + for (i = 0; i <= 256; i++) { + if (s->cftab[i] < 0 || s->cftab[i] > nblock) { + /* s->cftab[i] can legitimately be == nblock */ + RETURN(BZ_DATA_ERROR); + } + } + + s->state_out_len = 0; + s->state_out_ch = 0; + BZ_INITIALISE_CRC ( s->calculatedBlockCRC ); + s->state = BZ_X_OUTPUT; + if (s->verbosity >= 2) VPrintf0 ( "rt+rld" ); + + if (s->smallDecompress) { + + /*-- Make a copy of cftab, used in generation of T --*/ + for (i = 0; i <= 256; i++) s->cftabCopy[i] = s->cftab[i]; + + /*-- compute the T vector --*/ + for (i = 0; i < nblock; i++) { + uc = (UChar)(s->ll16[i]); + SET_LL(i, s->cftabCopy[uc]); + s->cftabCopy[uc]++; + } + + /*-- Compute T^(-1) by pointer reversal on T --*/ + i = s->origPtr; + j = GET_LL(i); + do { + Int32 tmp = GET_LL(j); + SET_LL(j, i); + i = j; + j = tmp; + } + while (i != s->origPtr); + + s->tPos = s->origPtr; + s->nblock_used = 0; + if (s->blockRandomised) { + BZ_RAND_INIT_MASK; + BZ_GET_SMALL(s->k0); s->nblock_used++; + BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; + } else { + BZ_GET_SMALL(s->k0); s->nblock_used++; + } + + } else { + + /*-- compute the T^(-1) vector --*/ + for (i = 0; i < nblock; i++) { + uc = (UChar)(s->tt[i] & 0xff); + s->tt[s->cftab[uc]] |= (i << 8); + s->cftab[uc]++; + } + + s->tPos = s->tt[s->origPtr] >> 8; + s->nblock_used = 0; + if (s->blockRandomised) { + BZ_RAND_INIT_MASK; + BZ_GET_FAST(s->k0); s->nblock_used++; + BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; + } else { + BZ_GET_FAST(s->k0); s->nblock_used++; + } + + } + + RETURN(BZ_OK); + + + + endhdr_2: + + GET_UCHAR(BZ_X_ENDHDR_2, uc); + if (uc != 0x72) RETURN(BZ_DATA_ERROR); + GET_UCHAR(BZ_X_ENDHDR_3, uc); + if (uc != 0x45) RETURN(BZ_DATA_ERROR); + GET_UCHAR(BZ_X_ENDHDR_4, uc); + if (uc != 0x38) RETURN(BZ_DATA_ERROR); + GET_UCHAR(BZ_X_ENDHDR_5, uc); + if (uc != 0x50) RETURN(BZ_DATA_ERROR); + GET_UCHAR(BZ_X_ENDHDR_6, uc); + if (uc != 0x90) RETURN(BZ_DATA_ERROR); + + s->storedCombinedCRC = 0; + GET_UCHAR(BZ_X_CCRC_1, uc); + s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); + GET_UCHAR(BZ_X_CCRC_2, uc); + s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); + GET_UCHAR(BZ_X_CCRC_3, uc); + s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); + GET_UCHAR(BZ_X_CCRC_4, uc); + s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); + + s->state = BZ_X_IDLE; + RETURN(BZ_STREAM_END); + + default: AssertH ( False, 4001 ); + } + + AssertH ( False, 4002 ); + + save_state_and_return: + + s->save_i = i; + s->save_j = j; + s->save_t = t; + s->save_alphaSize = alphaSize; + s->save_nGroups = nGroups; + s->save_nSelectors = nSelectors; + s->save_EOB = EOB; + s->save_groupNo = groupNo; + s->save_groupPos = groupPos; + s->save_nextSym = nextSym; + s->save_nblockMAX = nblockMAX; + s->save_nblock = nblock; + s->save_es = es; + s->save_N = N; + s->save_curr = curr; + s->save_zt = zt; + s->save_zn = zn; + s->save_zvec = zvec; + s->save_zj = zj; + s->save_gSel = gSel; + s->save_gMinlen = gMinlen; + s->save_gLimit = gLimit; + s->save_gBase = gBase; + s->save_gPerm = gPerm; + + return retVal; +} + + +/*-------------------------------------------------------------*/ +/*--- end decompress.c ---*/ +/*-------------------------------------------------------------*/ diff --git a/dep/bzip2/huffman.c b/dep/bzip2/huffman.c new file mode 100644 index 00000000000..87e79e38af0 --- /dev/null +++ b/dep/bzip2/huffman.c @@ -0,0 +1,205 @@ + +/*-------------------------------------------------------------*/ +/*--- Huffman coding low-level stuff ---*/ +/*--- huffman.c ---*/ +/*-------------------------------------------------------------*/ + +/* ------------------------------------------------------------------ + This file is part of bzip2/libbzip2, a program and library for + lossless, block-sorting data compression. + + bzip2/libbzip2 version 1.0.5 of 10 December 2007 + Copyright (C) 1996-2007 Julian Seward + + Please read the WARNING, DISCLAIMER and PATENTS sections in the + README file. + + This program is released under the terms of the license contained + in the file LICENSE. + ------------------------------------------------------------------ */ + + +#include "bzlib_private.h" + +/*---------------------------------------------------*/ +#define WEIGHTOF(zz0) ((zz0) & 0xffffff00) +#define DEPTHOF(zz1) ((zz1) & 0x000000ff) +#define MYMAX(zz2,zz3) ((zz2) > (zz3) ? (zz2) : (zz3)) + +#define ADDWEIGHTS(zw1,zw2) \ + (WEIGHTOF(zw1)+WEIGHTOF(zw2)) | \ + (1 + MYMAX(DEPTHOF(zw1),DEPTHOF(zw2))) + +#define UPHEAP(z) \ +{ \ + Int32 zz, tmp; \ + zz = z; tmp = heap[zz]; \ + while (weight[tmp] < weight[heap[zz >> 1]]) { \ + heap[zz] = heap[zz >> 1]; \ + zz >>= 1; \ + } \ + heap[zz] = tmp; \ +} + +#define DOWNHEAP(z) \ +{ \ + Int32 zz, yy, tmp; \ + zz = z; tmp = heap[zz]; \ + while (True) { \ + yy = zz << 1; \ + if (yy > nHeap) break; \ + if (yy < nHeap && \ + weight[heap[yy+1]] < weight[heap[yy]]) \ + yy++; \ + if (weight[tmp] < weight[heap[yy]]) break; \ + heap[zz] = heap[yy]; \ + zz = yy; \ + } \ + heap[zz] = tmp; \ +} + + +/*---------------------------------------------------*/ +void BZ2_hbMakeCodeLengths ( UChar *len, + Int32 *freq, + Int32 alphaSize, + Int32 maxLen ) +{ + /*-- + Nodes and heap entries run from 1. Entry 0 + for both the heap and nodes is a sentinel. + --*/ + Int32 nNodes, nHeap, n1, n2, i, j, k; + Bool tooLong; + + Int32 heap [ BZ_MAX_ALPHA_SIZE + 2 ]; + Int32 weight [ BZ_MAX_ALPHA_SIZE * 2 ]; + Int32 parent [ BZ_MAX_ALPHA_SIZE * 2 ]; + + for (i = 0; i < alphaSize; i++) + weight[i+1] = (freq[i] == 0 ? 1 : freq[i]) << 8; + + while (True) { + + nNodes = alphaSize; + nHeap = 0; + + heap[0] = 0; + weight[0] = 0; + parent[0] = -2; + + for (i = 1; i <= alphaSize; i++) { + parent[i] = -1; + nHeap++; + heap[nHeap] = i; + UPHEAP(nHeap); + } + + AssertH( nHeap < (BZ_MAX_ALPHA_SIZE+2), 2001 ); + + while (nHeap > 1) { + n1 = heap[1]; heap[1] = heap[nHeap]; nHeap--; DOWNHEAP(1); + n2 = heap[1]; heap[1] = heap[nHeap]; nHeap--; DOWNHEAP(1); + nNodes++; + parent[n1] = parent[n2] = nNodes; + weight[nNodes] = ADDWEIGHTS(weight[n1], weight[n2]); + parent[nNodes] = -1; + nHeap++; + heap[nHeap] = nNodes; + UPHEAP(nHeap); + } + + AssertH( nNodes < (BZ_MAX_ALPHA_SIZE * 2), 2002 ); + + tooLong = False; + for (i = 1; i <= alphaSize; i++) { + j = 0; + k = i; + while (parent[k] >= 0) { k = parent[k]; j++; } + len[i-1] = j; + if (j > maxLen) tooLong = True; + } + + if (! tooLong) break; + + /* 17 Oct 04: keep-going condition for the following loop used + to be 'i < alphaSize', which missed the last element, + theoretically leading to the possibility of the compressor + looping. However, this count-scaling step is only needed if + one of the generated Huffman code words is longer than + maxLen, which up to and including version 1.0.2 was 20 bits, + which is extremely unlikely. In version 1.0.3 maxLen was + changed to 17 bits, which has minimal effect on compression + ratio, but does mean this scaling step is used from time to + time, enough to verify that it works. + + This means that bzip2-1.0.3 and later will only produce + Huffman codes with a maximum length of 17 bits. However, in + order to preserve backwards compatibility with bitstreams + produced by versions pre-1.0.3, the decompressor must still + handle lengths of up to 20. */ + + for (i = 1; i <= alphaSize; i++) { + j = weight[i] >> 8; + j = 1 + (j / 2); + weight[i] = j << 8; + } + } +} + + +/*---------------------------------------------------*/ +void BZ2_hbAssignCodes ( Int32 *code, + UChar *length, + Int32 minLen, + Int32 maxLen, + Int32 alphaSize ) +{ + Int32 n, vec, i; + + vec = 0; + for (n = minLen; n <= maxLen; n++) { + for (i = 0; i < alphaSize; i++) + if (length[i] == n) { code[i] = vec; vec++; }; + vec <<= 1; + } +} + + +/*---------------------------------------------------*/ +void BZ2_hbCreateDecodeTables ( Int32 *limit, + Int32 *base, + Int32 *perm, + UChar *length, + Int32 minLen, + Int32 maxLen, + Int32 alphaSize ) +{ + Int32 pp, i, j, vec; + + pp = 0; + for (i = minLen; i <= maxLen; i++) + for (j = 0; j < alphaSize; j++) + if (length[j] == i) { perm[pp] = j; pp++; }; + + for (i = 0; i < BZ_MAX_CODE_LEN; i++) base[i] = 0; + for (i = 0; i < alphaSize; i++) base[length[i]+1]++; + + for (i = 1; i < BZ_MAX_CODE_LEN; i++) base[i] += base[i-1]; + + for (i = 0; i < BZ_MAX_CODE_LEN; i++) limit[i] = 0; + vec = 0; + + for (i = minLen; i <= maxLen; i++) { + vec += (base[i+1] - base[i]); + limit[i] = vec-1; + vec <<= 1; + } + for (i = minLen + 1; i <= maxLen; i++) + base[i] = ((limit[i-1] + 1) << 1) - base[i]; +} + + +/*-------------------------------------------------------------*/ +/*--- end huffman.c ---*/ +/*-------------------------------------------------------------*/ diff --git a/dep/bzip2/randtable.c b/dep/bzip2/randtable.c new file mode 100644 index 00000000000..068b76367bc --- /dev/null +++ b/dep/bzip2/randtable.c @@ -0,0 +1,84 @@ + +/*-------------------------------------------------------------*/ +/*--- Table for randomising repetitive blocks ---*/ +/*--- randtable.c ---*/ +/*-------------------------------------------------------------*/ + +/* ------------------------------------------------------------------ + This file is part of bzip2/libbzip2, a program and library for + lossless, block-sorting data compression. + + bzip2/libbzip2 version 1.0.5 of 10 December 2007 + Copyright (C) 1996-2007 Julian Seward + + Please read the WARNING, DISCLAIMER and PATENTS sections in the + README file. + + This program is released under the terms of the license contained + in the file LICENSE. + ------------------------------------------------------------------ */ + + +#include "bzlib_private.h" + + +/*---------------------------------------------*/ +Int32 BZ2_rNums[512] = { + 619, 720, 127, 481, 931, 816, 813, 233, 566, 247, + 985, 724, 205, 454, 863, 491, 741, 242, 949, 214, + 733, 859, 335, 708, 621, 574, 73, 654, 730, 472, + 419, 436, 278, 496, 867, 210, 399, 680, 480, 51, + 878, 465, 811, 169, 869, 675, 611, 697, 867, 561, + 862, 687, 507, 283, 482, 129, 807, 591, 733, 623, + 150, 238, 59, 379, 684, 877, 625, 169, 643, 105, + 170, 607, 520, 932, 727, 476, 693, 425, 174, 647, + 73, 122, 335, 530, 442, 853, 695, 249, 445, 515, + 909, 545, 703, 919, 874, 474, 882, 500, 594, 612, + 641, 801, 220, 162, 819, 984, 589, 513, 495, 799, + 161, 604, 958, 533, 221, 400, 386, 867, 600, 782, + 382, 596, 414, 171, 516, 375, 682, 485, 911, 276, + 98, 553, 163, 354, 666, 933, 424, 341, 533, 870, + 227, 730, 475, 186, 263, 647, 537, 686, 600, 224, + 469, 68, 770, 919, 190, 373, 294, 822, 808, 206, + 184, 943, 795, 384, 383, 461, 404, 758, 839, 887, + 715, 67, 618, 276, 204, 918, 873, 777, 604, 560, + 951, 160, 578, 722, 79, 804, 96, 409, 713, 940, + 652, 934, 970, 447, 318, 353, 859, 672, 112, 785, + 645, 863, 803, 350, 139, 93, 354, 99, 820, 908, + 609, 772, 154, 274, 580, 184, 79, 626, 630, 742, + 653, 282, 762, 623, 680, 81, 927, 626, 789, 125, + 411, 521, 938, 300, 821, 78, 343, 175, 128, 250, + 170, 774, 972, 275, 999, 639, 495, 78, 352, 126, + 857, 956, 358, 619, 580, 124, 737, 594, 701, 612, + 669, 112, 134, 694, 363, 992, 809, 743, 168, 974, + 944, 375, 748, 52, 600, 747, 642, 182, 862, 81, + 344, 805, 988, 739, 511, 655, 814, 334, 249, 515, + 897, 955, 664, 981, 649, 113, 974, 459, 893, 228, + 433, 837, 553, 268, 926, 240, 102, 654, 459, 51, + 686, 754, 806, 760, 493, 403, 415, 394, 687, 700, + 946, 670, 656, 610, 738, 392, 760, 799, 887, 653, + 978, 321, 576, 617, 626, 502, 894, 679, 243, 440, + 680, 879, 194, 572, 640, 724, 926, 56, 204, 700, + 707, 151, 457, 449, 797, 195, 791, 558, 945, 679, + 297, 59, 87, 824, 713, 663, 412, 693, 342, 606, + 134, 108, 571, 364, 631, 212, 174, 643, 304, 329, + 343, 97, 430, 751, 497, 314, 983, 374, 822, 928, + 140, 206, 73, 263, 980, 736, 876, 478, 430, 305, + 170, 514, 364, 692, 829, 82, 855, 953, 676, 246, + 369, 970, 294, 750, 807, 827, 150, 790, 288, 923, + 804, 378, 215, 828, 592, 281, 565, 555, 710, 82, + 896, 831, 547, 261, 524, 462, 293, 465, 502, 56, + 661, 821, 976, 991, 658, 869, 905, 758, 745, 193, + 768, 550, 608, 933, 378, 286, 215, 979, 792, 961, + 61, 688, 793, 644, 986, 403, 106, 366, 905, 644, + 372, 567, 466, 434, 645, 210, 389, 550, 919, 135, + 780, 773, 635, 389, 707, 100, 626, 958, 165, 504, + 920, 176, 193, 713, 857, 265, 203, 50, 668, 108, + 645, 990, 626, 197, 510, 357, 358, 850, 858, 364, + 936, 638 +}; + + +/*-------------------------------------------------------------*/ +/*--- end randtable.c ---*/ +/*-------------------------------------------------------------*/ diff --git a/dep/g3dlite/AABox.cpp b/dep/g3dlite/AABox.cpp new file mode 100644 index 00000000000..035497aa3c4 --- /dev/null +++ b/dep/g3dlite/AABox.cpp @@ -0,0 +1,366 @@ +/** + @file AABox.cpp + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2004-01-10 + @edited 2006-01-11 +*/ + +#include "G3D/platform.h" +#include "G3D/AABox.h" +#include "G3D/Box.h" +#include "G3D/Plane.h" +#include "G3D/Sphere.h" +#include "G3D/BinaryInput.h" +#include "G3D/BinaryOutput.h" + + +namespace G3D { + +const AABox& AABox::maxFinite() { + static const AABox b = AABox(Vector3::minFinite(), + Vector3::maxFinite()); + return b; +} + + +const AABox& AABox::large() { + static const AABox b = AABox(Vector3::minFinite() * 0.5f, + Vector3::maxFinite() * 0.5f); + return b; +} + + +const AABox& AABox::inf() { + static const AABox b = AABox(-Vector3::inf(), Vector3::inf()); + return b; +} + + +const AABox& AABox::zero() { + static const AABox b = AABox(Vector3::zero(), Vector3::zero()); + return b; +} + + +void AABox::serialize(class BinaryOutput& b) const { + b.writeVector3(lo); + b.writeVector3(hi); +} + + +void AABox::deserialize(class BinaryInput& b) { + lo = b.readVector3(); + hi = b.readVector3(); +} + + +void AABox::split(const Vector3::Axis& axis, float location, AABox& low, AABox& high) const { + // Low, medium, and high along the chosen axis + float L = G3D::min(location, lo[axis]); + float M = G3D::min(G3D::max(location, lo[axis]), hi[axis]); + float H = G3D::max(location, hi[axis]); + + // Copy over this box. + high = low = *this; + + // Now move the split points along the special axis + low.lo[axis] = L; + low.hi[axis] = M; + high.lo[axis] = M; + high.hi[axis] = H; +} + + +Vector3 AABox::randomSurfacePoint() const { + Vector3 extent = hi - lo; + float aXY = extent.x * extent.y; + float aYZ = extent.y * extent.z; + float aZX = extent.z * extent.x; + + float r = (float)uniformRandom(0.0f, aXY + aYZ + aZX); + + // Choose evenly between positive and negative face planes + float d = ((float)uniformRandom(0, 1) < 0.5f) ? 0.0f : 1.0f; + + // The probability of choosing a given face is proportional to + // its area. + if (r < aXY) { + return + lo + + Vector3( + (float)uniformRandom(0.0f, extent.x), + (float)uniformRandom(0.0f, extent.y), + d * extent.z); + } else if (r < aYZ) { + return + lo + + Vector3( + d * extent.x, + (float)uniformRandom(0, extent.y), + (float)uniformRandom(0, extent.z)); + } else { + return + lo + + Vector3( + (float)uniformRandom(0, extent.x), + d * extent.y, + (float)uniformRandom(0, extent.z)); + } +} + + +Vector3 AABox::randomInteriorPoint() const { + return Vector3( + (float)uniformRandom(lo.x, hi.x), + (float)uniformRandom(lo.y, hi.y), + (float)uniformRandom(lo.z, hi.z)); +} + + +bool AABox::intersects(const AABox& other) const { + // Must be overlap along all three axes. + // Try to find a separating axis. + + for (int a = 0; a < 3; ++a) { + + // |--------| + // |------| + + if ((lo[a] > other.hi[a]) || + (hi[a] < other.lo[a])) { + return false; + } + } + + return true; +} + +int AABox::dummy = 0; + +bool AABox::culledBy( + const Array& plane, + int& cullingPlane, + const uint32 _inMask, + uint32& childMask) const { + + uint32 inMask = _inMask; + assert(plane.size() < 31); + + childMask = 0; + + const bool finite = + (abs(lo.x) < G3D::finf()) && + (abs(hi.x) < G3D::finf()) && + (abs(lo.y) < G3D::finf()) && + (abs(hi.y) < G3D::finf()) && + (abs(lo.z) < G3D::finf()) && + (abs(hi.z) < G3D::finf()); + + // See if there is one plane for which all of the + // vertices are in the negative half space. + for (int p = 0; p < plane.size(); ++p) { + + // Only test planes that are not masked + if ((inMask & 1) != 0) { + + Vector3 corner; + + int numContained = 0; + int v = 0; + + // We can early-out only if we have found one point on each + // side of the plane (i.e. if we are straddling). That + // occurs when (numContained < v) && (numContained > 0) + for (v = 0; (v < 8) && ((numContained == v) || (numContained == 0)); ++v) { + // Unrolling these 3 if's into a switch decreases performance + // by about 2x + corner.x = (v & 1) ? hi.x : lo.x; + corner.y = (v & 2) ? hi.y : lo.y; + corner.z = (v & 4) ? hi.z : lo.z; + + if (finite) { // this branch is highly predictable + if (plane[p].halfSpaceContainsFinite(corner)) { + ++numContained; + } + } else { + if (plane[p].halfSpaceContains(corner)) { + ++numContained; + } + } + } + + if (numContained == 0) { + // Plane p culled the box + cullingPlane = p; + + // The caller should not recurse into the children, + // since the parent is culled. If they do recurse, + // make them only test against this one plane, which + // will immediately cull the volume. + childMask = 1 << p; + return true; + + } else if (numContained < v) { + // The bounding volume straddled the plane; we have + // to keep testing against this plane + childMask |= (1 << p); + } + } + + // Move on to the next bit. + inMask = inMask >> 1; + } + + // None of the planes could cull this box + cullingPlane = -1; + return false; +} + + +bool AABox::culledBy( + const Array& plane, + int& cullingPlane, + const uint32 _inMask) const { + + uint32 inMask = _inMask; + assert(plane.size() < 31); + + const bool finite = + (abs(lo.x) < G3D::finf()) && + (abs(hi.x) < G3D::finf()) && + (abs(lo.y) < G3D::finf()) && + (abs(hi.y) < G3D::finf()) && + (abs(lo.z) < G3D::finf()) && + (abs(hi.z) < G3D::finf()); + + // See if there is one plane for which all of the + // vertices are in the negative half space. + for (int p = 0; p < plane.size(); ++p) { + + // Only test planes that are not masked + if ((inMask & 1) != 0) { + + bool culled = true; + Vector3 corner; + + int v; + + // Assume this plane culls all points. See if there is a point + // not culled by the plane... early out when at least one point + // is in the positive half space. + for (v = 0; (v < 8) && culled; ++v) { + + // Unrolling these 3 if's into a switch decreases performance + // by about 2x + corner.x = (v & 1) ? hi.x : lo.x; + corner.y = (v & 2) ? hi.y : lo.y; + corner.z = (v & 4) ? hi.z : lo.z; + + if (finite) { // this branch is highly predictable + culled = ! plane[p].halfSpaceContainsFinite(corner); + } else { + culled = ! plane[p].halfSpaceContains(corner); + } + } + + if (culled) { + // Plane p culled the box + cullingPlane = p; + + return true; + } + } + + // Move on to the next bit. + inMask = inMask >> 1; + } + + // None of the planes could cull this box + cullingPlane = -1; + return false; +} + + +bool AABox::intersects(const class Sphere& sphere) const { + double d = 0; + + //find the square of the distance + //from the sphere to the box + for (int i = 0; i < 3; ++i) { + if (sphere.center[i] < lo[i]) { + d += square(sphere.center[i] - lo[i]); + } else if (sphere.center[i] > hi[i]) { + d += square(sphere.center[i] - hi[i]); + } + } + + return d <= square(sphere.radius); +} + +Vector3 AABox::corner(int index) const { + + // default constructor inits all components to 0 + Vector3 v; + + switch (index) + { + case 0: + v.x = lo.x; + v.y = lo.y; + v.z = hi.z; + break; + + case 1: + v.x = hi.x; + v.y = lo.y; + v.z = hi.z; + break; + + case 2: + v.x = hi.x; + v.y = hi.y; + v.z = hi.z; + break; + + case 3: + v.x = lo.x; + v.y = hi.y; + v.z = hi.z; + break; + + case 4: + v.x = lo.x; + v.y = lo.y; + v.z = lo.z; + break; + + case 5: + v.x = hi.x; + v.y = lo.y; + v.z = lo.z; + break; + + case 6: + v.x = hi.x; + v.y = hi.y; + v.z = lo.z; + break; + + case 7: + v.x = lo.x; + v.y = hi.y; + v.z = lo.z; + break; + + default: + debugAssertM(false, "Invalid corner index"); + break; + } + + return v; +} + + +} diff --git a/dep/g3dlite/Any.cpp b/dep/g3dlite/Any.cpp new file mode 100644 index 00000000000..de4d32e83ea --- /dev/null +++ b/dep/g3dlite/Any.cpp @@ -0,0 +1,1237 @@ +/** + @file Any.cpp + + @author Morgan McGuire + @author Shawn Yarbrough + + @created 2006-06-11 + @edited 2009-11-15 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ + +#include "G3D/Any.h" +#include "G3D/TextOutput.h" +#include "G3D/TextInput.h" +#include "G3D/stringutils.h" +#include +#include + +namespace G3D { + +void Any::beforeRead() const { + if (isPlaceholder()) { + // Tried to read from a placeholder--throw an exception as if + // the original operator[] had failed. + KeyNotFound e; + alwaysAssertM(m_data, "Corrupt placeholder"); + + e.filename = m_data->source.filename; + e.line = m_data->source.line; + e.character = m_data->source.character; + e.key = m_placeholderName; + e.message = + "This exception may have been thrown later than " + "the actual operator[] invocation."; + + throw e; + } +} + + +Any::Data* Any::Data::create(const Data* d) { + Data* p = create(d->type); + + p->comment = d->comment; + p->name = d->name; + + switch (d->type) { + case NONE: + case BOOLEAN: + case NUMBER: + // No clone needed + break; + + case STRING: + *(p->value.s) = *(d->value.s); + break; + + case ARRAY: + *(p->value.a) = *(d->value.a); + break; + + case TABLE: + *(p->value.t) = *(d->value.t); + // Note that placeholders may be copied; that is ok--they are still + // just placeholders. + break; + } + + return p; +} + + +Any::Data* Any::Data::create(Any::Type t) { + size_t s = sizeof(Data); + + switch (t) { + case NONE: + case BOOLEAN: + case NUMBER: + // No extra space needed + break; + + case STRING: + s += sizeof(std::string); + break; + + case ARRAY: + s += sizeof(AnyArray); + break; + + case TABLE: + s += sizeof(AnyTable); + break; + } + + // Allocate the data object + Data* p = new (MemoryManager::create()->alloc(s)) Data(t); + + // Create the (empyt) value object at the end of the Data object + switch (t) { + case NONE: + case BOOLEAN: + case NUMBER: + // No value + break; + + case STRING: + p->value.s = new (p + 1) std::string(); + break; + + case ARRAY: + p->value.a = new (p + 1) AnyArray(); + break; + + case TABLE: + p->value.t = new (p + 1) AnyTable(); + break; + } + + return p; +} + + +void Any::Data::destroy(Data* d) { + if (d != NULL) { + d->~Data(); + MemoryManager::create()->free(d); + } +} + + +Any::Data::~Data() { + debugAssertM(referenceCount.value() <= 0, "Deleted while still referenced."); + + // Destruct but do not deallocate children + switch (type) { + case STRING: + debugAssert(value.s != NULL); + value.s->~basic_string(); + break; + + case ARRAY: + debugAssert(value.a != NULL); + value.a->~Array(); + break; + + case TABLE: + debugAssert(value.t != NULL); + value.t->~Table(); + break; + + default: + // All other types should have a NULL value pointer (i.e., they were used just for name and comment fields) + debugAssertM(value.s == NULL, "Corrupt Any::Data::Value"); + } + + value.s = NULL; +} + + +////////////////////////////////////////////////////////////// + +bool Any::containsKey(const std::string& x) const { + beforeRead(); + verifyType(TABLE); + + Any* a = m_data->value.t->getPointer(x); + + // Don't return true for placeholder objects + return (a != NULL) && (! a->isPlaceholder()); +} + + +void Any::dropReference() { + if (m_data && m_data->referenceCount.decrement() <= 0) { + // This was the last reference to the shared data + Data::destroy(m_data); + } + m_data = NULL; +} + + +void Any::ensureMutable() { + if (m_data && (m_data->referenceCount.value() >= 1)) { + // Copy the data. We must do this before dropping the reference + // to avoid a race condition + Data* d = Data::create(m_data); + dropReference(); + m_data = d; + } +} + + +Any::Any() : m_type(NONE), m_data(NULL) { +} + + +Any::Any(TextInput& t) : m_type(NONE), m_data(NULL) { + deserialize(t); +} + + +Any::Any(const Any& x) : m_type(NONE), m_data(NULL) { + x.beforeRead(); + *this = x; +} + + +Any::Any(double x) : m_type(NUMBER), m_simpleValue(x), m_data(NULL) { +} + + +#ifdef G3D_32BIT +Any::Any(int64 x) : m_type(NUMBER), m_simpleValue((double)x), m_data(NULL) { +} +#endif // G3D_32BIT + + +Any::Any(long x) : m_type(NUMBER), m_simpleValue((double)x), m_data(NULL) { +} + + +Any::Any(int x) : m_type(NUMBER), m_simpleValue((double)x), m_data(NULL) { +} + + +Any::Any(short x) : m_type(NUMBER), m_simpleValue((double)x), m_data(NULL) { +} + + +Any::Any(bool x) : m_type(BOOLEAN), m_simpleValue(x), m_data(NULL) { +} + + +Any::Any(const std::string& s) : m_type(STRING), m_data(Data::create(STRING)) { + *(m_data->value.s) = s; +} + + +Any::Any(const char* s) : m_type(STRING), m_data(NULL) { + if (s == NULL) { + m_type = NONE; + } else { + ensureData(); + *(m_data->value.s) = s; + } +} + + +Any::Any(Type t, const std::string& name) : m_type(t), m_data(NULL) { + alwaysAssertM(t == ARRAY || t == TABLE, "Can only create ARRAY or TABLE from Type enum."); + + ensureData(); + if (name != "") { + m_data->name = name; + } +} + + +Any::~Any() { + dropReference(); +} + + +void Any::beforeWrite() { + if (isPlaceholder()) { + // This is no longer a placeholder + m_placeholderName = ""; + } +} + +Any& Any::operator=(const Any& x) { + x.beforeRead(); + + if (this == &x) { + return *this; + } + + beforeWrite(); + + dropReference(); + + m_type = x.m_type; + m_simpleValue = x.m_simpleValue; + + if (x.m_data != NULL) { + x.m_data->referenceCount.increment(); + m_data = x.m_data; + } + + return *this; +} + + +Any& Any::operator=(double x) { + *this = Any(x); + return *this; +} + + +Any& Any::operator=(int x) { + return (*this = Any(x)); +} + + +Any& Any::operator=(bool x) { + *this = Any(x); + return *this; +} + + +Any& Any::operator=(const std::string& x) { + *this = Any(x); + return *this; +} + + +Any& Any::operator=(const char* x) { + *this = Any(x); + return *this; +} + + +Any& Any::operator=(Type t) { + switch (t) { + case NONE: + *this = Any(); + break; + + case TABLE: + case ARRAY: + *this = Any(t); + break; + + default: + alwaysAssertM(false, "Can only assign NONE, TABLE, or ARRAY Type enum."); + } + + return *this; +} + + +Any::Type Any::type() const { + beforeRead(); + return m_type; +} + + +const std::string& Any::comment() const { + beforeRead(); + + static const std::string blank; + if (m_data != NULL) { + return m_data->comment; + } else { + return blank; + } +} + + +void Any::setComment(const std::string& c) { + beforeRead(); + ensureData(); + m_data->comment = c; +} + + +bool Any::isNone() const { + beforeRead(); + return (m_type == NONE); +} + + +double Any::number() const { + beforeRead(); + verifyType(NUMBER); + return m_simpleValue.n; +} + + +const std::string& Any::string() const { + beforeRead(); + verifyType(STRING); + return *(m_data->value.s); +} + + +bool Any::boolean() const { + beforeRead(); + verifyType(BOOLEAN); + return m_simpleValue.b; +} + + +const std::string& Any::name() const { + beforeRead(); + static const std::string blank; + if (m_data != NULL) { + return m_data->name; + } else { + return blank; + } +} + + +void Any::setName(const std::string& n) { + beforeRead(); + ensureData(); + m_data->name = n; +} + + +int Any::size() const { + beforeRead(); + verifyType(ARRAY, TABLE); + switch (m_type) { + case TABLE: + return m_data->value.t->size(); + + case ARRAY: + return m_data->value.a->size(); + + default:; + return 0; + } // switch (m_type) +} + + +int Any::length() const { + beforeRead(); + return size(); +} + + +void Any::resize(int n) { + beforeRead(); + alwaysAssertM(n >= 0, "Cannot resize less than 0."); + verifyType(ARRAY); + m_data->value.a->resize(n); +} + + +void Any::clear() { + beforeRead(); + verifyType(ARRAY, TABLE); + switch (m_type) { + case ARRAY: + m_data->value.a->clear(); + break; + + case TABLE: + m_data->value.t->clear(); + break; + + default:; + } +} + + +const Any& Any::operator[](int i) const { + beforeRead(); + verifyType(ARRAY); + debugAssert(m_data != NULL); + Array& array = *(m_data->value.a); + return array[i]; +} + + +Any& Any::next() { + beforeRead(); + verifyType(ARRAY); + int n = size(); + resize(n + 1); + return (*this)[n]; +} + + +Any& Any::operator[](int i) { + beforeRead(); + verifyType(ARRAY); + debugAssert(m_data != NULL); + Array& array = *(m_data->value.a); + return array[i]; +} + + +const Array& Any::array() const { + beforeRead(); + verifyType(ARRAY); + debugAssert(m_data != NULL); + return *(m_data->value.a); +} + + +void Any::append(const Any& x0) { + beforeRead(); + verifyType(ARRAY); + debugAssert(m_data != NULL); + m_data->value.a->append(x0); +} + + +void Any::append(const Any& x0, const Any& x1) { + beforeRead(); + append(x0); + append(x1); +} + + +void Any::append(const Any& x0, const Any& x1, const Any& x2) { + beforeRead(); + append(x0); + append(x1); + append(x2); +} + + +void Any::append(const Any& x0, const Any& x1, const Any& x2, const Any& x3) { + beforeRead(); + append(x0); + append(x1); + append(x2); + append(x3); +} + + +const Table& Any::table() const { + beforeRead(); + verifyType(TABLE); + debugAssert(m_data != NULL); + return *(m_data->value.t); +} + + +const Any& Any::operator[](const std::string& x) const { + beforeRead(); + verifyType(TABLE); + debugAssert(m_data != NULL); + const Table& table = *(m_data->value.t); + Any* value = table.getPointer(x); + if (value == NULL) { + KeyNotFound e; + if (m_data) { + e.filename = m_data->source.filename; + e.line = m_data->source.line; + e.character = m_data->source.character; + } + e.key = x; + throw e; + } + return *value; +} + + +Any& Any::operator[](const std::string& key) { + beforeRead(); + verifyType(TABLE); + + bool created = false; + Any& value = m_data->value.t->getCreate(key, created); + + if (created) { + // The entry was created by this method; do not allow it to be + // read before it is written. + value.m_placeholderName = key; + + // Write source data for the value + value.ensureData(); + value.m_data->source = source(); + } + + return value; +} + + +void Any::set(const std::string& k, const Any& v) { + beforeRead(); + v.beforeRead(); + verifyType(TABLE); + debugAssert(m_data != NULL); + Table& table = *(m_data->value.t); + table.set(k, v); +} + + +const Any& Any::get(const std::string& x, const Any& defaultVal) const { + beforeRead(); + defaultVal.beforeRead(); + try { + return operator[](x); + } catch(KeyNotFound) { + return defaultVal; + } +} + + +bool Any::operator==(const Any& x) const { + beforeRead(); + x.beforeRead(); + if (m_type != x.m_type) { + return false; + } + + switch (m_type) { + case NONE: + return true; + + case BOOLEAN: + return (m_simpleValue.b == x.m_simpleValue.b); + + case NUMBER: + return (m_simpleValue.n == x.m_simpleValue.n); + + case STRING: + debugAssert(m_data != NULL); + return (*(m_data->value.s) == *(x.m_data->value.s)); + + case TABLE: { + if (size() != x.size()) { + return false; + } + debugAssert(m_data != NULL); + if (m_data->name != x.m_data->name) { + return false; + } + Table& cmptable = *( m_data->value.t); + Table& xcmptable = *(x.m_data->value.t); + for (Table::Iterator it1 = cmptable.begin(), it2 = xcmptable.begin(); + it1 != cmptable.end() && it2 != xcmptable.end(); + ++it1, ++it2) { + if (*it1 != *it2) { + return false; + } + } + return true; + } + + case ARRAY: { + if (size() != x.size()) { + return false; + } + debugAssert(m_data != NULL); + if (m_data->name != x.m_data->name) { + return false; + } + + Array& cmparray = *( m_data->value.a); + Array& xcmparray = *(x.m_data->value.a); + + for (int ii = 0; ii < size(); ++ii) { + if (cmparray[ii] != xcmparray[ii]) { + return false; + } + } + return true; + } + + default: + alwaysAssertM(false, "Unknown type."); + return false; + } // switch (m_type) + +} + + +bool Any::operator!=(const Any& x) const { + beforeRead(); + x.beforeRead(); + return !operator==(x); +} + + +static void getDeserializeSettings(TextInput::Settings& settings) { + settings.cppBlockComments = true; + settings.cppLineComments = true; + settings.otherLineComments = true; + settings.otherCommentCharacter = '#'; + settings.generateCommentTokens = true; + settings.singleQuotedStrings = false; + settings.msvcSpecials = false; + settings.caseSensitive = false; +} + + +std::string Any::unparse() const { + beforeRead(); + TextOutput::Settings settings; + TextOutput to(settings); + serialize(to); + return to.commitString(); +} + + +void Any::parse(const std::string& src) { + beforeRead(); + TextInput::Settings settings; + getDeserializeSettings(settings); + + TextInput ti(TextInput::FROM_STRING, src, settings); + deserialize(ti); +} + + +void Any::load(const std::string& filename) { + beforeRead(); + TextInput::Settings settings; + getDeserializeSettings(settings); + + TextInput ti(filename, settings); + deserialize(ti); +} + + +void Any::save(const std::string& filename) const { + beforeRead(); + TextOutput::Settings settings; + settings.wordWrap = TextOutput::Settings::WRAP_NONE; + + TextOutput to(filename,settings); + serialize(to); + to.commit(); +} + + +static bool needsQuotes(const std::string& s) { + if (! isLetter(s[0]) && (s[0] != '_')) { + return true; + } + + for (int i = 0; i < (int)s.length(); ++i) { + char c = s[i]; + + // peek character + char p = (i == (int)s.length() - 1) ? '_' : s[i + 1]; + + // Identify separators + if ((c == '-' && p == '>') || + (c == ':' && p == ':')) { + // Skip over this symbol + ++i; + continue; + } + + if (! isDigit(c) && ! isLetter(c) & (c != '.')) { + // This is an illegal character for an identifier, so we need quotes + return true; + } + } + + return false; +} + + +// TODO: if the output will fit on one line, compress tables and arrays into a single line +void Any::serialize(TextOutput& to) const { + beforeRead(); + if (m_data && ! m_data->comment.empty()) { + to.printf("\n/* %s */\n", m_data->comment.c_str()); + } + + switch (m_type) { + case NONE: + to.writeSymbol("NONE"); + break; + + case BOOLEAN: + to.writeBoolean(m_simpleValue.b); + break; + + case NUMBER: + to.writeNumber(m_simpleValue.n); + break; + + case STRING: + debugAssert(m_data != NULL); + to.writeString(*(m_data->value.s)); + break; + + case TABLE: { + debugAssert(m_data != NULL); + if (! m_data->name.empty()) { + if (needsQuotes(m_data->name)) { + to.writeString(m_data->name); + } else { + to.writeSymbol(m_data->name); + } + } + to.writeSymbol("{"); + to.writeNewline(); + to.pushIndent(); + AnyTable& table = *(m_data->value.t); + Array keys; + table.getKeys(keys); + keys.sort(); + + for (int i = 0; i < keys.size(); ++i) { + + to.writeSymbol(keys[i]); + to.writeSymbol("="); + table[keys[i]].serialize(to); + + if (i < keys.size() - 1) { + to.writeSymbol(","); + } + to.writeNewline(); + + // Skip a line between table entries + to.writeNewline(); + } + + to.popIndent(); + to.writeSymbol("}"); + break; + } + + case ARRAY: { + debugAssert(m_data != NULL); + if (! m_data->name.empty()) { + // For arrays, leave no trailing space between the name and the paren + to.writeSymbol(format("%s(", m_data->name.c_str())); + } else { + to.writeSymbol("("); + } + to.writeNewline(); + to.pushIndent(); + Array& array = *(m_data->value.a); + for (int ii = 0; ii < size(); ++ii) { + array[ii].serialize(to); + if (ii < size() - 1) { + to.writeSymbol(","); + to.writeNewline(); + } + + // Put the close paren on an array right behind the last element + } + to.popIndent(); + to.writeSymbol(")"); + break; + } + } +} + + +void Any::deserializeComment(TextInput& ti, Token& token, std::string& comment) { + // Parse comments + while (token.type() == Token::COMMENT) { + comment += trimWhitespace(token.string()) + "\n"; + + // Allow comments to contain newlines. + do { + token = ti.read(); + comment += "\n"; + } while (token.type() == Token::NEWLINE); + } + + comment = trimWhitespace(comment); +} + +/** True if \a c is an open paren of some form */ +static bool isOpen(const char c) { + return c == '(' || c == '[' || c == '{'; +} + + +/** True if \a c is an open paren of some form */ +static bool isClose(const char c) { + return c == ')' || c == ']' || c == '}'; +} + + +/** True if \a s is a C++ name operator */ +static bool isNameOperator(const std::string& s) { + return s == "." || s == "::" || s == "->"; +} + + +void Any::deserializeName(TextInput& ti, Token& token, std::string& name) { + debugAssert(token.type() == Token::SYMBOL); + std::string s = token.string(); + while (! isOpen(s[0])) { + name += s; + + // Skip newlines and comments + token = ti.readSignificant(); + + if (token.type() != Token::SYMBOL) { + throw ParseError(ti.filename(), token.line(), token.character(), + "Expected symbol while parsing Any"); + } + s = token.string(); + } +} + + +void Any::deserialize(TextInput& ti) { + beforeRead(); + Token token = ti.read(); + deserialize(ti, token); + // Restore the last token + ti.push(token); +} + + +void Any::deserialize(TextInput& ti, Token& token) { + // Deallocate old data + dropReference(); + m_type = NONE; + m_simpleValue.b = false; + + // Skip leading newlines + while (token.type() == Token::NEWLINE) { + token = ti.read(); + } + + std::string comment; + if (token.type() == Token::COMMENT) { + deserializeComment(ti, token, comment); + } + + if (token.type() == Token::END) { + // There should never be a comment without an Any following it; even + // if the file ends with some commented out stuff, + // that should not happen after a comma, so we'd never read that + // far in a proper file. + throw ParseError(ti.filename(), token.line(), token.character(), + "File ended without a properly formed Any"); + } + + switch (token.type()) { + case Token::STRING: + m_type = STRING; + ensureData(); + *(m_data->value.s) = token.string(); + m_data->source.set(ti, token); + break; + + case Token::NUMBER: + m_type = NUMBER; + m_simpleValue.n = token.number(); + ensureData(); + m_data->source.set(ti, token); + break; + + case Token::BOOLEAN: + m_type = BOOLEAN; + m_simpleValue.b = token.boolean(); + ensureData(); + m_data->source.set(ti, token); + break; + + case Token::SYMBOL: + // Named Array, Named Table, Array, Table, or NONE + if (toUpper(token.string()) == "NONE") { + // Nothing left to do; we initialized to NONE originally + ensureData(); + m_data->source.set(ti, token); + } else { + // Array or Table + + // Parse the name + + // s must have at least one element or this would not have + // been parsed as a symbol + std::string name; + deserializeName(ti, token, name); + if (token.type() != Token::SYMBOL) { + throw ParseError(ti.filename(), token.line(), token.character(), + "Malformed Any TABLE or ARRAY; must start with [, (, or {"); + } + + if (isOpen(token.string()[0])) { + // Array or table + deserializeBody(ti, token); + } else { + throw ParseError(ti.filename(), token.line(), token.character(), + "Malformed Any TABLE or ARRAY; must start with [, (, or {"); + } + + if (! name.empty()) { + ensureData(); + m_data->name = name; + } + } // if NONE + break; + + default: + throw ParseError(ti.filename(), token.line(), token.character(), + "Unexpected token"); + + } // switch + + if (! comment.empty()) { + ensureData(); + m_data->comment = comment; + } + + if (m_type != ARRAY && m_type != TABLE) { + // Array and table already consumed their last token + token = ti.read(); + } +} + + +void Any::ensureData() { + if (m_data == NULL) { + m_data = Data::create(m_type); + } +} + + +static bool isSeparator(char c) { + return c == ',' || c == ';'; +} + + +void Any::readUntilCommaOrClose(TextInput& ti, Token& token) { + while (! ((token.type() == Token::SYMBOL) && + (isClose(token.string()[0])) || + isSeparator(token.string()[0]))) { + switch (token.type()) { + case Token::NEWLINE: + case Token::COMMENT: + // Consume + token = ti.read(); + break; + + default: + throw ParseError(ti.filename(), token.line(), token.character(), + "Expected a comma or close paren"); + } + } +} + + +void Any::deserializeBody(TextInput& ti, Token& token) { + char closeSymbol = '}'; + m_type = TABLE; + + const char c = token.string()[0]; + + if (c != '{') { + m_type = ARRAY; + // Chose the appropriate close symbol + closeSymbol = (c == '(') ? ')' : ']'; + } + + // Allocate the underlying data structure + ensureData(); + m_data->source.set(ti, token); + + // Consume the open token + token = ti.read(); + + while (! ((token.type() == Token::SYMBOL) && (token.string()[0] == closeSymbol))) { + + // Read any leading comment. This must be done here (and not in the recursive deserialize + // call) in case the body contains only a comment. + std::string comment; + deserializeComment(ti, token, comment); + + if ((token.type() == Token::SYMBOL) && (token.string()[0] == closeSymbol)) { + // We're done; this catches the case where the array is empty + break; + } + + // Pointer the value being read + Any a = NULL; + std::string key; + + if (m_type == TABLE) { + // Read the key + if (token.type() != Token::SYMBOL && token.type() != Token::STRING) { + throw ParseError(ti.filename(), token.line(), token.character(), "Expected a name"); + } + + key = token.string(); + // Consume everything up to the = sign + token = ti.readSignificant(); + + if ((token.type() != Token::SYMBOL) || (token.string() != "=")) { + throw ParseError(ti.filename(), token.line(), token.character(), "Expected ="); + } else { + // Consume (don't consume comments--we want the value pointed to by a to get those). + token = ti.read(); + } + } + a.deserialize(ti, token); + + if (! comment.empty()) { + // Prepend the comment we read earlier + a.ensureData(); + a.m_data->comment = trimWhitespace(comment + "\n" + a.m_data->comment); + } + + if (m_type == TABLE) { + set(key, a); + } else { + append(a); + } + + // Read until the comma or close paren, discarding trailing comments and newlines + readUntilCommaOrClose(ti, token); + + // Consume the comma + if (isSeparator(token.string()[0])) { + token = ti.read(); + } + } + + // Consume the close paren (to match other deserialize methods) + token = ti.read(); +} + + +Any::operator int() const { + beforeRead(); + return iRound(number()); +} + + +Any::operator float() const { + beforeRead(); + return float(number()); +} + + +Any::operator double() const { + beforeRead(); + return number(); +} + + +Any::operator bool() const { + beforeRead(); + return boolean(); +} + + +Any::operator std::string() const { + beforeRead(); + return string(); +} + + +const Any::Source& Any::source() const { + static Source s; + if (m_data) { + return m_data->source; + } else { + return s; + } +} + + +void Any::verify(bool value, const std::string& message) const { + beforeRead(); + if (! value) { + ParseError p; + if (m_data) { + p.filename = m_data->source.filename; + p.line = m_data->source.line; + p.character = m_data->source.character; + } + + if (name().empty()) { + p.message = "Parse error"; + } else { + p.message = "Parse error while reading the contents of " + name(); + } + + if (! message.empty()) { + p.message = p.message + ": " + message; + } + + throw p; + } +} + + +void Any::verifyName(const std::string& n) const { + beforeRead(); + verify(beginsWith(toUpper(name()), toUpper(n)), "Name must begin with " + n); +} + + +void Any::verifyType(Type t) const { + beforeRead(); + if (type() != t) { + verify(false, "Must have type " + toString(t)); + } +} + + +void Any::verifyType(Type t0, Type t1) const { + beforeRead(); + if (type() != t0 && type() != t1) { + verify(false, "Must have type " + toString(t0) + " or " + toString(t1)); + } +} + + +void Any::verifySize(int low, int high) const { + beforeRead(); + verifyType(ARRAY, TABLE); + if (size() < low || size() > high) { + verify(false, format("Size must be between %d and %d", low, high)); + } +} + + +void Any::verifySize(int s) const { + beforeRead(); + verifyType(ARRAY, TABLE); + if (size() != s) { + verify(false, format("Size must be %d", s)); + } +} + + +std::string Any::toString(Type t) { + switch(t) { + case NONE: return "NONE"; + case BOOLEAN: return "BOOLEAN"; + case NUMBER: return "NUMBER"; + case STRING: return "STRING"; + case ARRAY: return "ARRAY"; + case TABLE: return "TABLE"; + default: + alwaysAssertM(false, "Illegal Any::Type"); + return ""; + } +} + +} // namespace G3D + diff --git a/dep/g3dlite/BinaryFormat.cpp b/dep/g3dlite/BinaryFormat.cpp new file mode 100644 index 00000000000..d3991378f45 --- /dev/null +++ b/dep/g3dlite/BinaryFormat.cpp @@ -0,0 +1,81 @@ +/** + @file BinaryFormat.cpp + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2005-06-10 + @edited 2005-06-10 + */ + +#include "G3D/BinaryFormat.h" + +namespace G3D { + +int32 byteSize(BinaryFormat f) { + switch (f) { + case BOOL8_BINFMT: + case UINT8_BINFMT: + case INT8_BINFMT: + return 1; + + case UINT16_BINFMT: + case INT16_BINFMT: + return 2; + + case FLOAT16_BINFMT: + return 2; + + case UINT32_BINFMT: + case INT32_BINFMT: + case FLOAT32_BINFMT: + return 4; + + case FLOAT64_BINFMT: + case UINT64_BINFMT: + case INT64_BINFMT: + return 8; + + case INT128_BINFMT: + case UINT128_BINFMT: + return 16; + + case VECTOR2_BINFMT: + return 2 * 4; + + case VECTOR2INT16_BINFMT: + return 2 * 2; + + case VECTOR3_BINFMT: + return 3 * 4; + + case VECTOR3INT16_BINFMT: + return 3 * 2; + + case VECTOR4_BINFMT: + return 4 * 4; + + case VECTOR4INT16_BINFMT: + return 4 * 4; + + case COLOR3_BINFMT: + return 3 * 4; + + case COLOR3UINT8_BINFMT: + return 3 * 1; + + case COLOR3INT16_BINFMT: + return 3 * 2; + + case COLOR4_BINFMT: + return 4 * 4; + + case COLOR4UINT8_BINFMT: + return 4 * 1; + + case COLOR4INT16_BINFMT: + return 4 * 2; + + default: + return -1; + } +} +} diff --git a/dep/g3dlite/BinaryInput.cpp b/dep/g3dlite/BinaryInput.cpp new file mode 100644 index 00000000000..65a9976fe04 --- /dev/null +++ b/dep/g3dlite/BinaryInput.cpp @@ -0,0 +1,568 @@ +/** + @file BinaryInput.cpp + + @author Morgan McGuire, graphics3d.com + Copyright 2001-2007, Morgan McGuire. All rights reserved. + + @created 2001-08-09 + @edited 2005-02-24 + + +
+    {    
+    BinaryOutput b("c:/tmp/test.b", BinaryOutput::LITTLE_ENDIAN);
+
+    float f = 3.1415926;
+    int i = 1027221;
+    std::string s = "Hello World!";
+
+    b.writeFloat32(f);
+    b.writeInt32(i);
+    b.writeString(s);
+    b.commit();
+    
+
+    BinaryInput in("c:/tmp/test.b", BinaryInput::LITTLE_ENDIAN);
+
+    debugAssert(f == in.readFloat32());
+    int ii = in.readInt32();
+    debugAssert(i == ii);
+    debugAssert(s == in.readString());
+    }
+  
+ */ + +#include "G3D/platform.h" +#include "G3D/BinaryInput.h" +#include "G3D/Array.h" +#include "G3D/fileutils.h" +#include "G3D/Log.h" +#include + +#include + +namespace G3D { + +void BinaryInput::readBool8(std::vector& out, int64 n) { + out.resize((int)n); + // std::vector optimizes bool in a way that prevents fast reading + for (int64 i = 0; i < n ; ++i) { + out[i] = readBool8(); + } +} + + +void BinaryInput::readBool8(Array& out, int64 n) { + out.resize(n); + readBool8(out.begin(), n); +} + + +#define IMPLEMENT_READER(ucase, lcase)\ +void BinaryInput::read##ucase(std::vector& out, int64 n) {\ + out.resize(n);\ + read##ucase(&out[0], n);\ +}\ +\ +\ +void BinaryInput::read##ucase(Array& out, int64 n) {\ + out.resize(n);\ + read##ucase(out.begin(), n);\ +} + + +IMPLEMENT_READER(UInt8, uint8) +IMPLEMENT_READER(Int8, int8) +IMPLEMENT_READER(UInt16, uint16) +IMPLEMENT_READER(Int16, int16) +IMPLEMENT_READER(UInt32, uint32) +IMPLEMENT_READER(Int32, int32) +IMPLEMENT_READER(UInt64, uint64) +IMPLEMENT_READER(Int64, int64) +IMPLEMENT_READER(Float32, float32) +IMPLEMENT_READER(Float64, float64) + +#undef IMPLEMENT_READER + +// Data structures that are one byte per element can be +// directly copied, regardles of endian-ness. +#define IMPLEMENT_READER(ucase, lcase)\ +void BinaryInput::read##ucase(lcase* out, int64 n) {\ + if (sizeof(lcase) == 1) {\ + readBytes(out, n);\ + } else {\ + for (int64 i = 0; i < n ; ++i) {\ + out[i] = read##ucase();\ + }\ + }\ +} + +IMPLEMENT_READER(Bool8, bool) +IMPLEMENT_READER(UInt8, uint8) +IMPLEMENT_READER(Int8, int8) + +#undef IMPLEMENT_READER + + +#define IMPLEMENT_READER(ucase, lcase)\ +void BinaryInput::read##ucase(lcase* out, int64 n) {\ + if (m_swapBytes) {\ + for (int64 i = 0; i < n; ++i) {\ + out[i] = read##ucase();\ + }\ + } else {\ + readBytes(out, sizeof(lcase) * n);\ + }\ +} + + +IMPLEMENT_READER(UInt16, uint16) +IMPLEMENT_READER(Int16, int16) +IMPLEMENT_READER(UInt32, uint32) +IMPLEMENT_READER(Int32, int32) +IMPLEMENT_READER(UInt64, uint64) +IMPLEMENT_READER(Int64, int64) +IMPLEMENT_READER(Float32, float32) +IMPLEMENT_READER(Float64, float64) + +#undef IMPLEMENT_READER + +void BinaryInput::loadIntoMemory(int64 startPosition, int64 minLength) { + // Load the next section of the file + debugAssertM(m_filename != "", "Read past end of file."); + + int64 absPos = m_alreadyRead + m_pos; + + if (m_bufferLength < minLength) { + // The current buffer isn't big enough to hold the chunk we want to read. + // This happens if there was little memory available during the initial constructor + // read but more memory has since been freed. + m_bufferLength = minLength; + debugAssert(m_freeBuffer); + m_buffer = (uint8*)System::realloc(m_buffer, m_bufferLength); + if (m_buffer == NULL) { + throw "Tried to read a larger memory chunk than could fit in memory. (2)"; + } + } + + m_alreadyRead = startPosition; + +# ifdef G3D_WIN32 + FILE* file = fopen(m_filename.c_str(), "rb"); + debugAssert(file); + int ret = fseek(file, (off_t)m_alreadyRead, SEEK_SET); + debugAssert(ret == 0); + size_t toRead = (size_t)G3D::min(m_bufferLength, m_length - m_alreadyRead); + ret = fread(m_buffer, 1, toRead, file); + debugAssert(ret == toRead); + fclose(file); + file = NULL; + +# else + FILE* file = fopen(m_filename.c_str(), "rb"); + debugAssert(file); + int ret = fseeko(file, (off_t)m_alreadyRead, SEEK_SET); + debugAssert(ret == 0); + size_t toRead = (size_t)G3D::min(m_bufferLength, m_length - m_alreadyRead); + ret = fread(m_buffer, 1, toRead, file); + debugAssert((size_t)ret == (size_t)toRead); + fclose(file); + file = NULL; +# endif + + m_pos = absPos - m_alreadyRead; + debugAssert(m_pos >= 0); +} + + + +const bool BinaryInput::NO_COPY = false; + +static bool needSwapBytes(G3DEndian fileEndian) { + return (fileEndian != System::machineEndian()); +} + + +/** Helper used by the constructors for decompression */ +static uint32 readUInt32(const uint8* data, bool swapBytes) { + if (swapBytes) { + uint8 out[4]; + out[0] = data[3]; + out[1] = data[2]; + out[2] = data[1]; + out[3] = data[0]; + return *((uint32*)out); + } else { + return *((uint32*)data); + } +} + + +void BinaryInput::setEndian(G3DEndian e) { + m_fileEndian = e; + m_swapBytes = needSwapBytes(m_fileEndian); +} + + +BinaryInput::BinaryInput( + const uint8* data, + int64 dataLen, + G3DEndian dataEndian, + bool compressed, + bool copyMemory) : + m_filename(""), + m_bitPos(0), + m_bitString(0), + m_beginEndBits(0), + m_alreadyRead(0), + m_bufferLength(0), + m_pos(0) { + + m_freeBuffer = copyMemory || compressed; + + setEndian(dataEndian); + + if (compressed) { + // Read the decompressed size from the first 4 bytes + m_length = G3D::readUInt32(data, m_swapBytes); + + debugAssert(m_freeBuffer); + m_buffer = (uint8*)System::alignedMalloc(m_length, 16); + + unsigned long L = m_length; + // Decompress with zlib + int64 result = uncompress(m_buffer, (unsigned long*)&L, data + 4, dataLen - 4); + m_length = L; + m_bufferLength = L; + debugAssert(result == Z_OK); (void)result; + + } else { + m_length = dataLen; + m_bufferLength = m_length; + if (! copyMemory) { + debugAssert(!m_freeBuffer); + m_buffer = const_cast(data); + } else { + debugAssert(m_freeBuffer); + m_buffer = (uint8*)System::alignedMalloc(m_length, 16); + System::memcpy(m_buffer, data, dataLen); + } + } +} + + +BinaryInput::BinaryInput( + const std::string& filename, + G3DEndian fileEndian, + bool compressed) : + m_filename(filename), + m_bitPos(0), + m_bitString(0), + m_beginEndBits(0), + m_alreadyRead(0), + m_length(0), + m_bufferLength(0), + m_buffer(NULL), + m_pos(0), + m_freeBuffer(true) { + + setEndian(fileEndian); + + // Update global file tracker + _internal::currentFilesUsed.insert(m_filename); + + + if (! fileExists(m_filename, false)) { + std::string zipfile; + std::string internalfile; + if (zipfileExists(m_filename, zipfile, internalfile)) { + // Load from zipfile + void* v; + size_t s; + zipRead(filename, v, s); + m_buffer = reinterpret_cast(v); + m_bufferLength = m_length = s; + if (compressed) { + decompress(); + } + m_freeBuffer = true; + } else { + Log::common()->printf("Warning: File not found: %s\n", m_filename.c_str()); + } + return; + } + + // Figure out how big the file is and verify that it exists. + m_length = fileLength(m_filename); + + // Read the file into memory + FILE* file = fopen(m_filename.c_str(), "rb"); + + if (! file || (m_length == -1)) { + throw format("File not found: \"%s\"", m_filename.c_str()); + return; + } + + if (! compressed && (m_length > INITIAL_BUFFER_LENGTH)) { + // Read only a subset of the file so we don't consume + // all available memory. + m_bufferLength = INITIAL_BUFFER_LENGTH; + } else { + // Either the length is fine or the file is compressed + // and requires us to read the whole thing for zlib. + m_bufferLength = m_length; + } + + debugAssert(m_freeBuffer); + m_buffer = (uint8*)System::alignedMalloc(m_bufferLength, 16); + if (m_buffer == NULL) { + if (compressed) { + throw "Not enough memory to load compressed file. (1)"; + } + + // Try to allocate a small array; not much memory is available. + // Give up if we can't allocate even 1k. + while ((m_buffer == NULL) && (m_bufferLength > 1024)) { + m_bufferLength /= 2; + m_buffer = (uint8*)System::alignedMalloc(m_bufferLength, 16); + } + } + debugAssert(m_buffer); + + fread(m_buffer, m_bufferLength, sizeof(int8), file); + fclose(file); + file = NULL; + + if (compressed) { + if (m_bufferLength != m_length) { + throw "Not enough memory to load compressed file. (2)"; + } + + decompress(); + } +} + +void BinaryInput::decompress() { + // Decompress + // Use the existing buffer as the source, allocate + // a new buffer to use as the destination. + + int64 tempLength = m_length; + m_length = G3D::readUInt32(m_buffer, m_swapBytes); + + // The file couldn't have better than 500:1 compression + alwaysAssertM(m_length < m_bufferLength * 500, "Compressed file header is corrupted"); + + uint8* tempBuffer = m_buffer; + m_buffer = (uint8*)System::alignedMalloc(m_length, 16); + + debugAssert(m_buffer); + debugAssert(isValidHeapPointer(tempBuffer)); + debugAssert(isValidHeapPointer(m_buffer)); + + unsigned long L = m_length; + int64 result = uncompress(m_buffer, &L, tempBuffer + 4, tempLength - 4); + m_length = L; + m_bufferLength = m_length; + + debugAssertM(result == Z_OK, "BinaryInput/zlib detected corruption in " + m_filename); + (void)result; + + System::alignedFree(tempBuffer); +} + + +void BinaryInput::readBytes(void* bytes, int64 n) { + prepareToRead(n); + debugAssert(isValidPointer(bytes)); + + memcpy(bytes, m_buffer + m_pos, n); + m_pos += n; +} + + +BinaryInput::~BinaryInput() { + + if (m_freeBuffer) { + System::alignedFree(m_buffer); + } + m_buffer = NULL; +} + + +uint64 BinaryInput::readUInt64() { + prepareToRead(8); + uint8 out[8]; + + if (m_swapBytes) { + out[0] = m_buffer[m_pos + 7]; + out[1] = m_buffer[m_pos + 6]; + out[2] = m_buffer[m_pos + 5]; + out[3] = m_buffer[m_pos + 4]; + out[4] = m_buffer[m_pos + 3]; + out[5] = m_buffer[m_pos + 2]; + out[6] = m_buffer[m_pos + 1]; + out[7] = m_buffer[m_pos + 0]; + } else { + *(uint64*)out = *(uint64*)(m_buffer + m_pos); + } + + m_pos += 8; + return *(uint64*)out; +} + + +std::string BinaryInput::readString(int64 n) { + prepareToRead(n); + debugAssertM((m_pos + n) <= m_length, "Read past end of file"); + + char *s = (char*)System::alignedMalloc(n + 1, 16); + assert(s != NULL); + + memcpy(s, m_buffer + m_pos, n); + // There may not be a null, so make sure + // we add one. + s[n] = '\0'; + + std::string out = s; + System::alignedFree(s); + s = NULL; + + m_pos += n; + + return out; + +} + + +std::string BinaryInput::readString() { + int64 n = 0; + + if ((m_pos + m_alreadyRead + n) < (m_length - 1)) { + prepareToRead(1); + } + + if ( ((m_pos + m_alreadyRead + n) < (m_length - 1)) && + (m_buffer[m_pos + n] != '\0')) { + + ++n; + while ( ((m_pos + m_alreadyRead + n) < (m_length - 1)) && + (m_buffer[m_pos + n] != '\0')) { + + prepareToRead(1); + ++n; + } + } + + // Consume NULL + ++n; + + return readString(n); +} + + +std::string BinaryInput::readStringEven() { + std::string x = readString(); + if (hasMore() && (G3D::isOdd(x.length() + 1))) { + skip(1); + } + return x; +} + + +std::string BinaryInput::readString32() { + int len = readUInt32(); + return readString(len); +} + + +Vector4 BinaryInput::readVector4() { + float x = readFloat32(); + float y = readFloat32(); + float z = readFloat32(); + float w = readFloat32(); + return Vector4(x, y, z, w); +} + + +Vector3 BinaryInput::readVector3() { + float x = readFloat32(); + float y = readFloat32(); + float z = readFloat32(); + return Vector3(x, y, z); +} + + +Vector2 BinaryInput::readVector2() { + float x = readFloat32(); + float y = readFloat32(); + return Vector2(x, y); +} + + +Color4 BinaryInput::readColor4() { + float r = readFloat32(); + float g = readFloat32(); + float b = readFloat32(); + float a = readFloat32(); + return Color4(r, g, b, a); +} + + +Color3 BinaryInput::readColor3() { + float r = readFloat32(); + float g = readFloat32(); + float b = readFloat32(); + return Color3(r, g, b); +} + + +void BinaryInput::beginBits() { + debugAssert(m_beginEndBits == 0); + m_beginEndBits = 1; + m_bitPos = 0; + + debugAssertM(hasMore(), "Can't call beginBits when at the end of a file"); + m_bitString = readUInt8(); +} + + +uint32 BinaryInput::readBits(int numBits) { + debugAssert(m_beginEndBits == 1); + + uint32 out = 0; + + const int total = numBits; + while (numBits > 0) { + if (m_bitPos > 7) { + // Consume a new byte for reading. We do this at the beginning + // of the loop so that we don't try to read past the end of the file. + m_bitPos = 0; + m_bitString = readUInt8(); + } + + // Slide the lowest bit of the bitString into + // the correct position. + out |= (m_bitString & 1) << (total - numBits); + + // Shift over to the next bit + m_bitString = m_bitString >> 1; + ++m_bitPos; + --numBits; + } + + return out; +} + + +void BinaryInput::endBits() { + debugAssert(m_beginEndBits == 1); + if (m_bitPos == 0) { + // Put back the last byte we read + --m_pos; + } + m_beginEndBits = 0; + m_bitPos = 0; +} + +} diff --git a/dep/g3dlite/BinaryOutput.cpp b/dep/g3dlite/BinaryOutput.cpp new file mode 100644 index 00000000000..2de46c6d4bb --- /dev/null +++ b/dep/g3dlite/BinaryOutput.cpp @@ -0,0 +1,522 @@ +/** + @file BinaryOutput.cpp + + @author Morgan McGuire, graphics3d.com + Copyright 2002-2007, Morgan McGuire, All rights reserved. + + @created 2002-02-20 + @edited 2008-01-07 + */ + +#include "G3D/platform.h" +#include "G3D/BinaryOutput.h" +#include "G3D/fileutils.h" +#include "G3D/stringutils.h" +#include "G3D/Array.h" +#include + +#include + +// Largest memory buffer that the system will use for writing to +// disk. After this (or if the system runs out of memory) +// chunks of the file will be dumped to disk. +// +// Currently 400 MB +#define MAX_BINARYOUTPUT_BUFFER_SIZE 400000000 + +namespace G3D { + +void BinaryOutput::writeBool8(const std::vector& out, int n) { + for (int i = 0; i < n; ++i) { + writeBool8(out[i]); + } +} + + +void BinaryOutput::writeBool8(const Array& out, int n) { + writeBool8(out.getCArray(), n); +} + +#define IMPLEMENT_WRITER(ucase, lcase)\ +void BinaryOutput::write##ucase(const std::vector& out, int n) {\ + write##ucase(&out[0], n);\ +}\ +\ +\ +void BinaryOutput::write##ucase(const Array& out, int n) {\ + write##ucase(out.getCArray(), n);\ +} + + +IMPLEMENT_WRITER(UInt8, uint8) +IMPLEMENT_WRITER(Int8, int8) +IMPLEMENT_WRITER(UInt16, uint16) +IMPLEMENT_WRITER(Int16, int16) +IMPLEMENT_WRITER(UInt32, uint32) +IMPLEMENT_WRITER(Int32, int32) +IMPLEMENT_WRITER(UInt64, uint64) +IMPLEMENT_WRITER(Int64, int64) +IMPLEMENT_WRITER(Float32, float32) +IMPLEMENT_WRITER(Float64, float64) + +#undef IMPLEMENT_WRITER + +// Data structures that are one byte per element can be +// directly copied, regardles of endian-ness. +#define IMPLEMENT_WRITER(ucase, lcase)\ +void BinaryOutput::write##ucase(const lcase* out, int n) {\ + if (sizeof(lcase) == 1) {\ + writeBytes((void*)out, n);\ + } else {\ + for (int i = 0; i < n ; ++i) {\ + write##ucase(out[i]);\ + }\ + }\ +} + +IMPLEMENT_WRITER(Bool8, bool) +IMPLEMENT_WRITER(UInt8, uint8) +IMPLEMENT_WRITER(Int8, int8) + +#undef IMPLEMENT_WRITER + + +#define IMPLEMENT_WRITER(ucase, lcase)\ +void BinaryOutput::write##ucase(const lcase* out, int n) {\ + if (m_swapBytes) {\ + for (int i = 0; i < n; ++i) {\ + write##ucase(out[i]);\ + }\ + } else {\ + writeBytes((const void*)out, sizeof(lcase) * n);\ + }\ +} + + +IMPLEMENT_WRITER(UInt16, uint16) +IMPLEMENT_WRITER(Int16, int16) +IMPLEMENT_WRITER(UInt32, uint32) +IMPLEMENT_WRITER(Int32, int32) +IMPLEMENT_WRITER(UInt64, uint64) +IMPLEMENT_WRITER(Int64, int64) +IMPLEMENT_WRITER(Float32, float32) +IMPLEMENT_WRITER(Float64, float64) + +#undef IMPLEMENT_WRITER + + +void BinaryOutput::reallocBuffer(size_t bytes, size_t oldBufferLen) { + //debugPrintf("reallocBuffer(%d, %d)\n", bytes, oldBufferLen); + + size_t newBufferLen = (int)(m_bufferLen * 1.5) + 100; + uint8* newBuffer = NULL; + + if ((m_filename == "") || (newBufferLen < MAX_BINARYOUTPUT_BUFFER_SIZE)) { + // We're either writing to memory (in which case we *have* to try and allocate) + // or we've been asked to allocate a reasonable size buffer. + + //debugPrintf(" realloc(%d)\n", newBufferLen); + newBuffer = (uint8*)System::realloc(m_buffer, newBufferLen); + if (newBuffer != NULL) { + m_maxBufferLen = newBufferLen; + } + } + + if ((newBuffer == NULL) && (bytes > 0)) { + // Realloc failed; we're probably out of memory. Back out + // the entire call and try to dump some data to disk. + m_bufferLen = oldBufferLen; + reserveBytesWhenOutOfMemory(bytes); + } else { + m_buffer = newBuffer; + debugAssert(isValidHeapPointer(m_buffer)); + } +} + + +void BinaryOutput::reserveBytesWhenOutOfMemory(size_t bytes) { + if (m_filename == "") { + throw "Out of memory while writing to memory in BinaryOutput (no RAM left)."; + } else if ((int)bytes > (int)m_maxBufferLen) { + throw "Out of memory while writing to disk in BinaryOutput (could not create a large enough buffer)."; + } else { + + // Dump the contents to disk. In order to enable seeking backwards, + // we keep the last 10 MB in memory. + int writeBytes = m_bufferLen - 10 * 1024 * 1024; + + if (writeBytes < m_bufferLen / 3) { + // We're going to write less than 1/3 of the file; + // give up and just write the whole thing. + writeBytes = m_bufferLen; + } + debugAssert(writeBytes > 0); + + //debugPrintf("Writing %d bytes to disk\n", writeBytes); + + const char* mode = (m_alreadyWritten > 0) ? "ab" : "wb"; + FILE* file = fopen(m_filename.c_str(), mode); + debugAssert(file); + + size_t count = fwrite(m_buffer, 1, writeBytes, file); + debugAssert((int)count == writeBytes); (void)count; + + fclose(file); + file = NULL; + + // Record that we saved this data. + m_alreadyWritten += writeBytes; + m_bufferLen -= writeBytes; + m_pos -= writeBytes; + + debugAssert(m_bufferLen < m_maxBufferLen); + debugAssert(m_bufferLen >= 0); + debugAssert(m_pos >= 0); + debugAssert(m_pos <= m_bufferLen); + + // Shift the unwritten data back appropriately in the buffer. + debugAssert(isValidHeapPointer(m_buffer)); + System::memcpy(m_buffer, m_buffer + writeBytes, m_bufferLen); + debugAssert(isValidHeapPointer(m_buffer)); + + // *now* we allocate bytes (there should presumably be enough + // space in the buffer; if not, we'll come back through this + // code and dump the last 10MB to disk as well. Note that the + // bytes > maxBufferLen case above would already have triggered + // if this call couldn't succeed. + reserveBytes(bytes); + } +} + + +BinaryOutput::BinaryOutput() { + m_alreadyWritten = 0; + m_swapBytes = false; + m_pos = 0; + m_filename = ""; + m_buffer = NULL; + m_bufferLen = 0; + m_maxBufferLen = 0; + m_beginEndBits = 0; + m_bitString = 0; + m_bitPos = 0; + m_ok = true; + m_committed = false; +} + + +BinaryOutput::BinaryOutput( + const std::string& filename, + G3DEndian fileEndian) { + + m_pos = 0; + m_alreadyWritten = 0; + setEndian(fileEndian); + m_filename = filename; + m_buffer = NULL; + m_bufferLen = 0; + m_maxBufferLen = 0; + m_beginEndBits = 0; + m_bitString = 0; + m_bitPos = 0; + m_committed = false; + + m_ok = true; + /** Verify ability to write to disk */ + commit(false); + m_committed = false; +} + + +void BinaryOutput::reset() { + debugAssert(m_beginEndBits == 0); + alwaysAssertM(m_filename == "", + "Can only reset a BinaryOutput that writes to memory."); + + // Do not reallocate, just clear the size of the buffer. + m_pos = 0; + m_alreadyWritten = 0; + m_bufferLen = 0; + m_beginEndBits = 0; + m_bitString = 0; + m_bitPos = 0; + m_committed = false; +} + + +BinaryOutput::~BinaryOutput() { + debugAssert((m_buffer == NULL) || isValidHeapPointer(m_buffer)); + System::free(m_buffer); + m_buffer = NULL; + m_bufferLen = 0; + m_maxBufferLen = 0; +} + + +void BinaryOutput::setEndian(G3DEndian fileEndian) { + m_fileEndian = fileEndian; + m_swapBytes = (fileEndian != System::machineEndian()); +} + + +bool BinaryOutput::ok() const { + return m_ok; +} + + +void BinaryOutput::compress() { + if (m_alreadyWritten > 0) { + throw "Cannot compress huge files (part of this file has already been written to disk)."; + } + + // Old buffer size + int L = m_bufferLen; + uint8* convert = (uint8*)&L; + + // Zlib requires the output buffer to be this big + unsigned long newSize = iCeil(m_bufferLen * 1.01) + 12; + uint8* temp = (uint8*)System::malloc(newSize); + int result = compress2(temp, &newSize, m_buffer, m_bufferLen, 9); + + debugAssert(result == Z_OK); (void)result; + + // Write the header + if (m_swapBytes) { + m_buffer[0] = convert[3]; + m_buffer[1] = convert[2]; + m_buffer[2] = convert[1]; + m_buffer[3] = convert[0]; + } else { + m_buffer[0] = convert[0]; + m_buffer[1] = convert[1]; + m_buffer[2] = convert[2]; + m_buffer[3] = convert[3]; + } + + // Write the data + if ((int64)newSize + 4 > (int64)m_maxBufferLen) { + m_maxBufferLen = newSize + 4; + m_buffer = (uint8*)System::realloc(m_buffer, m_maxBufferLen); + } + m_bufferLen = newSize + 4; + System::memcpy(m_buffer + 4, temp, newSize); + m_pos = m_bufferLen; + + System::free(temp); +} + + +void BinaryOutput::commit(bool flush) { + debugAssertM(! m_committed, "Cannot commit twice"); + m_committed = true; + debugAssertM(m_beginEndBits == 0, "Missing endBits before commit"); + + // Make sure the directory exists. + std::string root, base, ext, path; + Array pathArray; + parseFilename(m_filename, root, pathArray, base, ext); + + path = root + stringJoin(pathArray, '/'); + if (! fileExists(path, false)) { + createDirectory(path); + } + + const char* mode = (m_alreadyWritten > 0) ? "ab" : "wb"; + + FILE* file = fopen(m_filename.c_str(), mode); + + m_ok = (file != NULL) && m_ok; + + if (m_ok) { + debugAssertM(file, std::string("Could not open '") + m_filename + "'"); + + if (m_buffer != NULL) { + m_alreadyWritten += m_bufferLen; + + int success = fwrite(m_buffer, m_bufferLen, 1, file); + (void)success; + debugAssertM(success == 1, std::string("Could not write to '") + m_filename + "'"); + } + if (flush) { + fflush(file); + } + fclose(file); + file = NULL; + } +} + + +void BinaryOutput::commit( + uint8* out) { + debugAssertM(! m_committed, "Cannot commit twice"); + m_committed = true; + + System::memcpy(out, m_buffer, m_bufferLen); +} + + +void BinaryOutput::writeUInt16(uint16 u) { + reserveBytes(2); + + uint8* convert = (uint8*)&u; + + if (m_swapBytes) { + m_buffer[m_pos] = convert[1]; + m_buffer[m_pos + 1] = convert[0]; + } else { + *(uint16*)(m_buffer + m_pos) = u; + } + + m_pos += 2; +} + + +void BinaryOutput::writeUInt32(uint32 u) { + reserveBytes(4); + + uint8* convert = (uint8*)&u; + + debugAssert(m_beginEndBits == 0); + + if (m_swapBytes) { + m_buffer[m_pos] = convert[3]; + m_buffer[m_pos + 1] = convert[2]; + m_buffer[m_pos + 2] = convert[1]; + m_buffer[m_pos + 3] = convert[0]; + } else { + *(uint32*)(m_buffer + m_pos) = u; + } + + m_pos += 4; +} + + +void BinaryOutput::writeUInt64(uint64 u) { + reserveBytes(8); + + uint8* convert = (uint8*)&u; + + if (m_swapBytes) { + m_buffer[m_pos] = convert[7]; + m_buffer[m_pos + 1] = convert[6]; + m_buffer[m_pos + 2] = convert[5]; + m_buffer[m_pos + 3] = convert[4]; + m_buffer[m_pos + 4] = convert[3]; + m_buffer[m_pos + 5] = convert[2]; + m_buffer[m_pos + 6] = convert[1]; + m_buffer[m_pos + 7] = convert[0]; + } else { + *(uint64*)(m_buffer + m_pos) = u; + } + + m_pos += 8; +} + + +void BinaryOutput::writeString(const char* s) { + // +1 is because strlen doesn't count the null + int len = strlen(s) + 1; + + debugAssert(m_beginEndBits == 0); + reserveBytes(len); + System::memcpy(m_buffer + m_pos, s, len); + m_pos += len; +} + + +void BinaryOutput::writeStringEven(const char* s) { + // +1 is because strlen doesn't count the null + int len = strlen(s) + 1; + + reserveBytes(len); + System::memcpy(m_buffer + m_pos, s, len); + m_pos += len; + + // Pad with another NULL + if ((len % 2) == 1) { + writeUInt8(0); + } +} + + +void BinaryOutput::writeString32(const char* s) { + writeUInt32(strlen(s) + 1); + writeString(s); +} + + +void BinaryOutput::writeVector4(const Vector4& v) { + writeFloat32(v.x); + writeFloat32(v.y); + writeFloat32(v.z); + writeFloat32(v.w); +} + + +void BinaryOutput::writeVector3(const Vector3& v) { + writeFloat32(v.x); + writeFloat32(v.y); + writeFloat32(v.z); +} + + +void BinaryOutput::writeVector2(const Vector2& v) { + writeFloat32(v.x); + writeFloat32(v.y); +} + + +void BinaryOutput::writeColor4(const Color4& v) { + writeFloat32(v.r); + writeFloat32(v.g); + writeFloat32(v.b); + writeFloat32(v.a); +} + + +void BinaryOutput::writeColor3(const Color3& v) { + writeFloat32(v.r); + writeFloat32(v.g); + writeFloat32(v.b); +} + + +void BinaryOutput::beginBits() { + debugAssertM(m_beginEndBits == 0, "Already in beginBits...endBits"); + m_bitString = 0x00; + m_bitPos = 0; + m_beginEndBits = 1; +} + + +void BinaryOutput::writeBits(uint32 value, int numBits) { + + while (numBits > 0) { + // Extract the current bit of value and + // insert it into the current byte + m_bitString |= (value & 1) << m_bitPos; + ++m_bitPos; + value = value >> 1; + --numBits; + + if (m_bitPos > 7) { + // We've reached the end of this byte + writeUInt8(m_bitString); + m_bitString = 0x00; + m_bitPos = 0; + } + } +} + + +void BinaryOutput::endBits() { + debugAssertM(m_beginEndBits == 1, "Not in beginBits...endBits"); + if (m_bitPos > 0) { + writeUInt8(m_bitString); + } + m_bitString = 0; + m_bitPos = 0; + m_beginEndBits = 0; +} + +} diff --git a/dep/g3dlite/Box.cpp b/dep/g3dlite/Box.cpp new file mode 100644 index 00000000000..f7c112ae3a5 --- /dev/null +++ b/dep/g3dlite/Box.cpp @@ -0,0 +1,393 @@ +/** + @file Box.cpp + Box class + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2001-06-02 + @edited 2006-02-05 +*/ + +#include "G3D/Box.h" +#include "G3D/debug.h" +#include "G3D/Plane.h" +#include "G3D/AABox.h" +#include "G3D/CoordinateFrame.h" + +namespace G3D { + +/** + Sets a field on four vertices. Used by the constructor. + */ +#define setMany(i0, i1, i2, i3, field, extreme) \ + _corner[i0].field = _corner[i1].field = \ + _corner[i2].field = _corner[i3].field = \ + (extreme).field + +Box::Box() { +} + + +Box::Box(const AABox& b) { + init(b.low(), b.high()); +} + +Box::Box(class BinaryInput& b) { + deserialize(b); +} + + +void Box::serialize(class BinaryOutput& b) const { + int i; + for (i = 0; i < 8; ++i) { + _corner[i].serialize(b); + } + + // Other state can be reconstructed +} + + +void Box::deserialize(class BinaryInput& b) { + int i; + + _center = Vector3::zero(); + for (i = 0; i < 8; ++i) { + _corner[i].deserialize(b); + _center += _corner[i]; + } + + _center = _center / 8; + + // Reconstruct other state from the corners + _axis[0] = _corner[5] - _corner[4]; + _axis[1] = _corner[7] - _corner[4]; + _axis[2] = _corner[0] - _corner[4]; + + for (i = 0; i < 3; ++i) { + _extent[i] = _axis[i].magnitude(); + _axis[i] /= _extent[i]; + } + + _volume = _extent.x * _extent.y * _extent.z; + + _area = 2 * + (_extent.x * _extent.y + + _extent.y * _extent.z + + _extent.z * _extent.x); +} + + +Box::Box( + const Vector3& min, + const Vector3& max) { + + init(min.min(max), min.max(max)); + +} + +void Box::init( + const Vector3& min, + const Vector3& max) { + + debugAssert( + (min.x <= max.x) && + (min.y <= max.y) && + (min.z <= max.z)); + + setMany(0, 1, 2, 3, z, max); + setMany(4, 5, 6, 7, z, min); + + setMany(1, 2, 5, 6, x, max); + setMany(0, 3, 4, 7, x, min); + + setMany(3, 2, 6, 7, y, max); + setMany(0, 1, 5, 4, y, min); + + _extent = max - min; + + _axis[0] = Vector3::unitX(); + _axis[1] = Vector3::unitY(); + _axis[2] = Vector3::unitZ(); + + if (_extent.isFinite()) { + _volume = _extent.x * _extent.y * _extent.z; + } else { + _volume = G3D::finf(); + } + + debugAssert(! isNaN(_extent.x)); + + _area = 2 * + (_extent.x * _extent.y + + _extent.y * _extent.z + + _extent.z * _extent.x); + + _center = (max + min) * 0.5f; + + // If the extent is infinite along an axis, make the center zero to avoid NaNs + for (int i = 0; i < 3; ++i) { + if (! G3D::isFinite(_extent[i])) { + _center[i] = 0.0f; + } + } +} + + +float Box::volume() const { + return _volume; +} + + +float Box::area() const { + return _area; +} + + +void Box::getLocalFrame(CoordinateFrame& frame) const { + + frame.rotation = Matrix3( + _axis[0][0], _axis[1][0], _axis[2][0], + _axis[0][1], _axis[1][1], _axis[2][1], + _axis[0][2], _axis[1][2], _axis[2][2]); + + frame.translation = _center; +} + + +CoordinateFrame Box::localFrame() const { + CoordinateFrame out; + getLocalFrame(out); + return out; +} + + +void Box::getFaceCorners(int f, Vector3& v0, Vector3& v1, Vector3& v2, Vector3& v3) const { + switch (f) { + case 0: + v0 = _corner[0]; v1 = _corner[1]; v2 = _corner[2]; v3 = _corner[3]; + break; + + case 1: + v0 = _corner[1]; v1 = _corner[5]; v2 = _corner[6]; v3 = _corner[2]; + break; + + case 2: + v0 = _corner[7]; v1 = _corner[6]; v2 = _corner[5]; v3 = _corner[4]; + break; + + case 3: + v0 = _corner[2]; v1 = _corner[6]; v2 = _corner[7]; v3 = _corner[3]; + break; + + case 4: + v0 = _corner[3]; v1 = _corner[7]; v2 = _corner[4]; v3 = _corner[0]; + break; + + case 5: + v0 = _corner[1]; v1 = _corner[0]; v2 = _corner[4]; v3 = _corner[5]; + break; + + default: + debugAssert((f >= 0) && (f < 6)); + } +} + + + +int Box::dummy = 0; + +bool Box::culledBy( + const Array& plane, + int& cullingPlane, + const uint32 _inMask, + uint32& childMask) const { + + uint32 inMask = _inMask; + assert(plane.size() < 31); + + childMask = 0; + + // See if there is one plane for which all of the + // vertices are in the negative half space. + for (int p = 0; p < plane.size(); ++p) { + + // Only test planes that are not masked + if ((inMask & 1) != 0) { + + Vector3 corner; + + int numContained = 0; + int v = 0; + + // We can early-out only if we have found one point on each + // side of the plane (i.e. if we are straddling). That + // occurs when (numContained < v) && (numContained > 0) + for (v = 0; (v < 8) && ((numContained == v) || (numContained == 0)); ++v) { + if (plane[p].halfSpaceContains(_corner[v])) { + ++numContained; + } + } + + if (numContained == 0) { + // Plane p culled the box + cullingPlane = p; + + // The caller should not recurse into the children, + // since the parent is culled. If they do recurse, + // make them only test against this one plane, which + // will immediately cull the volume. + childMask = 1 << p; + return true; + + } else if (numContained < v) { + // The bounding volume straddled the plane; we have + // to keep testing against this plane + childMask |= (1 << p); + } + } + + // Move on to the next bit. + inMask = inMask >> 1; + } + + // None of the planes could cull this box + cullingPlane = -1; + return false; +} + + +bool Box::culledBy( + const Array& plane, + int& cullingPlane, + const uint32 _inMask) const { + + uint32 inMask = _inMask; + assert(plane.size() < 31); + + // See if there is one plane for which all of the + // vertices are in the negative half space. + for (int p = 0; p < plane.size(); ++p) { + + // Only test planes that are not masked + if ((inMask & 1) != 0) { + + bool culled = true; + + int v; + + // Assume this plane culls all points. See if there is a point + // not culled by the plane... early out when at least one point + // is in the positive half space. + for (v = 0; (v < 8) && culled; ++v) { + culled = ! plane[p].halfSpaceContains(corner(v)); + } + + if (culled) { + // Plane p culled the box + cullingPlane = p; + + return true; + } + } + + // Move on to the next bit. + inMask = inMask >> 1; + } + + // None of the planes could cull this box + cullingPlane = -1; + return false; +} + + +bool Box::contains( + const Vector3& point) const { + + // Form axes from three edges, transform the point into that + // space, and perform 3 interval tests + + Vector3 u = _corner[4] - _corner[0]; + Vector3 v = _corner[3] - _corner[0]; + Vector3 w = _corner[1] - _corner[0]; + + Matrix3 M = Matrix3(u.x, v.x, w.x, + u.y, v.y, w.y, + u.z, v.z, w.z); + + // M^-1 * (point - _corner[0]) = point in unit cube's object space + // compute the inverse of M + Vector3 osPoint = M.inverse() * (point - _corner[0]); + + return + (osPoint.x >= 0) && + (osPoint.y >= 0) && + (osPoint.z >= 0) && + (osPoint.x <= 1) && + (osPoint.y <= 1) && + (osPoint.z <= 1); +} + +#undef setMany + + +void Box::getRandomSurfacePoint(Vector3& P, Vector3& N) const { + float aXY = _extent.x * _extent.y; + float aYZ = _extent.y * _extent.z; + float aZX = _extent.z * _extent.x; + + float r = (float)uniformRandom(0, aXY + aYZ + aZX); + + // Choose evenly between positive and negative face planes + float d = (uniformRandom(0, 1) < 0.5f) ? -1.0f : 1.0f; + + // The probability of choosing a given face is proportional to + // its area. + if (r < aXY) { + P = _axis[0] * (float)uniformRandom(-0.5, 0.5) * _extent.x + + _axis[1] * (float)uniformRandom(-0.5, 0.5) * _extent.y + + _center + _axis[2] * d * _extent.z * 0.5f; + N = _axis[2] * d; + } else if (r < aYZ) { + P = _axis[1] * (float)uniformRandom(-0.5, 0.5) * _extent.y + + _axis[2] * (float)uniformRandom(-0.5, 0.5) * _extent.z + + _center + _axis[0] * d * _extent.x * 0.5f; + N = _axis[0] * d; + } else { + P = _axis[2] * (float)uniformRandom(-0.5, 0.5) * _extent.z + + _axis[0] *(float) uniformRandom(-0.5, 0.5) * _extent.x + + _center + _axis[1] * d * _extent.y * 0.5f; + N = _axis[1] * d; + } +} + + +Vector3 Box::randomInteriorPoint() const { + Vector3 sum = _center; + + for (int a = 0; a < 3; ++a) { + sum += _axis[a] * (float)uniformRandom(-0.5, 0.5) * _extent[a]; + } + + return sum; +} + +Box Box::inf() { + return Box(-Vector3::inf(), Vector3::inf()); +} + +void Box::getBounds(class AABox& aabb) const { + + Vector3 lo = _corner[0]; + Vector3 hi = lo; + + for (int v = 1; v < 8; ++v) { + const Vector3& C = _corner[v]; + lo = lo.min(C); + hi = hi.max(C); + } + + aabb = AABox(lo, hi); +} + + +} // namespace diff --git a/dep/g3dlite/CMakeLists.txt b/dep/g3dlite/CMakeLists.txt new file mode 100644 index 00000000000..071fa4ed7ea --- /dev/null +++ b/dep/g3dlite/CMakeLists.txt @@ -0,0 +1,37 @@ +# Copyright (C) 2008-2010 Trinity +# +# This file is free software; as a special exception the author gives +# unlimited permission to copy and/or distribute it, with or without +# modifications, as long as this notice is preserved. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the +# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +file(GLOB sources *.cpp) + +set(g3dlib_STAT_SRCS + ${sources} +) +if(WIN32) + include_directories( + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_SOURCE_DIR}/dep/zlib + ) +else() + include_directories( + ${CMAKE_CURRENT_SOURCE_DIR} + ) +endif() + +add_library(g3dlib STATIC ${g3dlib_STAT_SRCS}) + +if(WIN32) + target_link_libraries(g3dlib + zlib + ) +else() + target_link_libraries(g3dlib + ${ZLIB_LIBRARIES} + ) +endif() diff --git a/dep/g3dlite/Capsule.cpp b/dep/g3dlite/Capsule.cpp new file mode 100644 index 00000000000..2ad3891c960 --- /dev/null +++ b/dep/g3dlite/Capsule.cpp @@ -0,0 +1,179 @@ +/** + @file Capsule.cpp + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2003-02-07 + @edited 2005-08-18 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ + +#include "G3D/Capsule.h" +#include "G3D/BinaryInput.h" +#include "G3D/BinaryOutput.h" +#include "G3D/LineSegment.h" +#include "G3D/Sphere.h" +#include "G3D/CoordinateFrame.h" +#include "G3D/Line.h" +#include "G3D/AABox.h" + +namespace G3D { + +Capsule::Capsule(class BinaryInput& b) { + deserialize(b); +} + + +Capsule::Capsule() { +} + + +Capsule::Capsule(const Vector3& _p1, const Vector3& _p2, float _r) + : p1(_p1), p2(_p2), _radius(_r) { +} + + +void Capsule::serialize(class BinaryOutput& b) const { + p1.serialize(b); + p2.serialize(b); + b.writeFloat64(_radius); +} + + +void Capsule::deserialize(class BinaryInput& b) { + p1.deserialize(b); + p2.deserialize(b); + _radius = b.readFloat64(); +} + + +Line Capsule::axis() const { + return Line::fromTwoPoints(p1, p2); +} + + +float Capsule::volume() const { + return + // Sphere volume + pow(_radius, 3) * pi() * 4 / 3 + + + // Cylinder volume + pow(_radius, 2) * (p1 - p2).magnitude(); +} + + +float Capsule::area() const { + + return + // Sphere area + pow(_radius, 2) * 4 * pi() + + + // Cylinder area + twoPi() * _radius * (p1 - p2).magnitude(); +} + + +void Capsule::getBounds(AABox& out) const { + Vector3 min = p1.min(p2) - (Vector3(1, 1, 1) * _radius); + Vector3 max = p1.max(p2) + (Vector3(1, 1, 1) * _radius); + + out = AABox(min, max); +} + + +bool Capsule::contains(const Vector3& p) const { + return LineSegment::fromTwoPoints(p1, p2).distanceSquared(p) <= square(radius()); +} + + +void Capsule::getRandomSurfacePoint(Vector3& p, Vector3& N) const { + float h = height(); + float r = radius(); + + // Create a random point on a standard capsule and then rotate to the global frame. + + // Relative areas + float capRelArea = sqrt(r) / 2.0f; + float sideRelArea = r * h; + + float r1 = uniformRandom(0, capRelArea * 2 + sideRelArea); + + if (r1 < capRelArea * 2) { + + // Select a point uniformly at random on a sphere + N = Sphere(Vector3::zero(), 1).randomSurfacePoint(); + p = N * r; + p.y += sign(p.y) * h / 2.0f; + } else { + // Side + float a = uniformRandom(0, (float)twoPi()); + N.x = cos(a); + N.y = 0; + N.z = sin(a); + p.x = N.x * r; + p.z = N.y * r; + p.y = uniformRandom(-h / 2.0f, h / 2.0f); + } + + // Transform to world space + CoordinateFrame cframe; + getReferenceFrame(cframe); + + p = cframe.pointToWorldSpace(p); + N = cframe.normalToWorldSpace(N); +} + + +void Capsule::getReferenceFrame(CoordinateFrame& cframe) const { + cframe.translation = center(); + + Vector3 Y = (p1 - p2).direction(); + Vector3 X = (abs(Y.dot(Vector3::unitX())) > 0.9) ? Vector3::unitY() : Vector3::unitX(); + Vector3 Z = X.cross(Y).direction(); + X = Y.cross(Z); + cframe.rotation.setColumn(0, X); + cframe.rotation.setColumn(1, Y); + cframe.rotation.setColumn(2, Z); +} + + +Vector3 Capsule::randomInteriorPoint() const { + float h = height(); + float r = radius(); + + // Create a random point in a standard capsule and then rotate to the global frame. + + Vector3 p; + + float hemiVolume = pi() * (r*r*r) * 4 / 6.0; + float cylVolume = pi() * square(r) * h; + + float r1 = uniformRandom(0, 2.0 * hemiVolume + cylVolume); + + if (r1 < 2.0 * hemiVolume) { + + p = Sphere(Vector3::zero(), r).randomInteriorPoint(); + + p.y += sign(p.y) * h / 2.0f; + + } else { + + // Select a point uniformly at random on a disk + float a = uniformRandom(0, (float)twoPi()); + float r2 = sqrt(uniformRandom(0, 1)) * r; + + p = Vector3(cos(a) * r2, + uniformRandom(-h / 2.0f, h / 2.0f), + sin(a) * r2); + } + + // Transform to world space + CoordinateFrame cframe; + getReferenceFrame(cframe); + + return cframe.pointToWorldSpace(p); +} + +} // namespace diff --git a/dep/g3dlite/CollisionDetection.cpp b/dep/g3dlite/CollisionDetection.cpp new file mode 100644 index 00000000000..77eef0a5500 --- /dev/null +++ b/dep/g3dlite/CollisionDetection.cpp @@ -0,0 +1,2455 @@ +/** + @file CollisionDetection.cpp + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @cite Bounce direction based on Paul Nettle's ftp://ftp.3dmaileffects.com/pub/FluidStudios/CollisionDetection/Fluid_Studios_Generic_Collision_Detection_for_Games_Using_Ellipsoids.pdf and comments by Max McGuire. Ray-sphere code by Eric Haines. + + @created 2001-11-24 + @edited 2008-12-29 + */ + +#include "G3D/CoordinateFrame.h" +#include "G3D/platform.h" +#include "G3D/CollisionDetection.h" +#include "G3D/debugAssert.h" +#include "G3D/vectorMath.h" +#include "G3D/Capsule.h" +#include "G3D/Plane.h" +#include "G3D/Line.h" +#include "G3D/LineSegment.h" +#include "G3D/Sphere.h" +#include "G3D/Box.h" +#include "G3D/Triangle.h" +#include "G3D/Vector3.h" +#include "G3D/AABox.h" + +#ifdef _MSC_VER +// Turn on fast floating-point optimizations +#pragma float_control( push ) +#pragma fp_contract( on ) +#pragma fenv_access( off ) +#pragma float_control( except, off ) +#pragma float_control( precise, off ) +#endif + + +namespace G3D { + +bool CollisionDetection::ignoreBool; +Vector3 CollisionDetection::ignore; +Array CollisionDetection::ignoreArray; + + + +Vector3 CollisionDetection::separatingAxisForSolidBoxSolidBox( + const int separatingAxisIndex, + const Box & box1, + const Box & box2) { + debugAssert(separatingAxisIndex >= 0); + debugAssert(separatingAxisIndex < 15); + Vector3 axis; + if (separatingAxisIndex < 3) { + axis = box1.axis(separatingAxisIndex); + } else if (separatingAxisIndex < 6) { + axis = box2.axis(separatingAxisIndex - 3); + } else { + int box1Index = (separatingAxisIndex - 6) / 3; + int box2Index = (separatingAxisIndex - 6) % 3; + axis = cross(box1.axis(box1Index), box2.axis(box2Index)); + } + return axis; +} + +#ifdef _MSC_VER +# pragma warning (push) +# pragma warning (disable : 4244) +#endif + +float CollisionDetection::projectedDistanceForSolidBoxSolidBox( + const int separatingAxisIndex, + const Vector3 & a, + const Vector3 & b, + const Vector3 & D, + const double* c, + const double* ca, + const double* ad, + const double* bd) +{ + (void)D; + + float R0 = 0.0f; + float R1 = 0.0f; + float R = 0.0f; + switch (separatingAxisIndex) { + case 0: + // A0 + R0 = a[0]; + R1 = b[0] * ca[0] + b[1] * ca[1] + b[2] * ca[2]; + R = fabs(ad[0]); + break; + case 1: + // A1 + R0 = a[1]; + R1 = b[0] * ca[3] + b[1] * ca[4] + b[2] * ca[5]; + R = fabs(ad[1]); + break; + case 2: + // A2 + R0 = a[2]; + R1 = b[0] * ca[6] + b[1] * ca[7] + b[2] * ca[8]; + R = fabs(ad[2]); + break; + case 3: + // B0 + R0 = a[0] * ca[0] + a[1] * ca[3] + a[2] * ca[6]; + R1 = b[0]; + R = fabs(bd[0]); + break; + case 4: + // B1 + R0 = a[0] * ca[1] + a[1] * ca[4] + a[2] * ca[7]; + R1 = b[1]; + R = fabs(bd[1]); + break; + case 5: + // B2 + R0 = a[0] * ca[2] + a[1] * ca[5] + a[2] * ca[8]; + R1 = b[2]; + R = fabs(bd[2]); + break; + case 6: + // A0 x B0 + R0 = a[1] * ca[6] + a[2] * ca[3]; + R1 = b[1] * ca[2] + b[2] * ca[1]; + R = fabs(c[3] * ad[2] - c[6] * ad[1]); + break; + case 7: + // A0 x B1 + R0 = a[1] * ca[7] + a[2] * ca[4]; + R1 = b[0] * ca[2] + b[2] * ca[0]; + R = fabs(c[4] * ad[2] - c[7] * ad[1]); + break; + case 8: + // A0 x B2 + R0 = a[1] * ca[8] + a[2] * ca[5]; + R1 = b[0] * ca[1] + b[1] * ca[0]; + R = fabs(c[5] * ad[2] - c[8] * ad[1]); + break; + case 9: + // A1 x B0 + R0 = a[0] * ca[6] + a[2] * ca[0]; + R1 = b[1] * ca[5] + b[2] * ca[4]; + R = fabs(c[6] * ad[0] - c[0] * ad[2]); + break; + case 10: + // A1 x B1 + R0 = a[0] * ca[7] + a[2] * ca[1]; + R1 = b[0] * ca[5] + b[2] * ca[3]; + R = fabs(c[7] * ad[0] - c[1] * ad[2]); + break; + case 11: + // A1 x B2 + R0 = a[0] * ca[8] + a[2] * ca[2]; + R1 = b[0] * ca[4] + b[1] * ca[3]; + R = fabs(c[8] * ad[0] - c[2] * ad[2]); + break; + case 12: + // A2 x B0 + R0 = a[0] * ca[3] + a[1] * ca[0]; + R1 = b[1] * ca[8] + b[2] * ca[7]; + R = fabs(c[0] * ad[1] - c[3] * ad[0]); + break; + case 13: + // A2 x B1 + R0 = a[0] * ca[4] + a[1] * ca[1]; + R1 = b[0] * ca[8] + b[2] * ca[6]; + R = fabs(c[1] * ad[1] - c[4] * ad[0]); + break; + case 14: + // A2 x B2 + R0 = a[0] * ca[5] + a[1] * ca[2]; + R1 = b[0] * ca[7] + b[1] * ca[6]; + R = fabs(c[2] * ad[1] - c[5] * ad[0]); + break; + default: + debugAssertM(false, "fell through switch statement"); + } + + return (R - (R0 + R1)); +} + + +bool CollisionDetection::parallelAxisForSolidBoxSolidBox( + const double* ca, + const double epsilon, + int & axis1, + int & axis2) { + const double parallelDot = 1.0 - epsilon; + for (int i = 0; i < 9; i++) { + if (ca[i] >= parallelDot) { + axis1 = i / 3; + axis2 = i % 3; + return true; + } + } + return false; +} + + + + +void CollisionDetection::fillSolidBoxSolidBoxInfo( + const Box & box1, + const Box & box2, + Vector3 & a, + Vector3 & b, + Vector3 & D, + double* c, + double* ca, + double* ad, + double* bd) { + // length between center and each side of box1 and box2 + a = box1.extent() * 0.5; + b = box2.extent() * 0.5; + + // difference between centers of box1 and box2 + D = box2.center() - box1.center(); + + // store the value of all possible dot products between the + // axes of box1 and box2, c_{row, col} in the Eberly paper + // corresponds to c[row * 3 + col] for this 9 element array. + // + // c[] holds signed values, ca[] hold absolute values + for (int i = 0; i < 9; i++) { + c[i] = dot(box1.axis(i / 3), box2.axis(i % 3)); + ca[i] = fabs(c[i]); + } + + // store all possible dot products between the axes of box1 and D, + // as well as the axes of box2 and D + for (int i = 0; i < 3; i++) { + ad[i] = dot(box1.axis(i), D); + bd[i] = dot(box2.axis(i), D); + } +} + + + +bool CollisionDetection::conservativeBoxBoxTest( + const Vector3 & a, const Vector3 & b, const Vector3 & D) { + // do a quick bounding sphere test because it is relatively + // cheap, (three dot products, two sqrts, and a few others) + double boxRadius1 = a.magnitude(); + double boxRadius2 = b.magnitude(); + return (D.squaredMagnitude() < square(boxRadius1 + boxRadius2)); +} + + + + +bool CollisionDetection::fixedSolidBoxIntersectsFixedSolidBox( + const Box& box1, + const Box& box2, + const int lastSeparatingAxis) { + // for explanations of the variable please refer to the + // paper and fillSolidBoxSolidBoxInfo() + Vector3 a; + Vector3 b; + Vector3 D; + double c[9]; + double ca[9]; + double ad[3]; + double bd[3]; + + fillSolidBoxSolidBoxInfo(box1, box2, a, b, D, c, ca, ad, bd); + + int dummy1, dummy2; + bool parallelAxes = parallelAxisForSolidBoxSolidBox(ca, 0.00001, + dummy1, dummy2); + + // check the separating axis from the last time step + if (lastSeparatingAxis != -1 && + (lastSeparatingAxis < 6 || !parallelAxes)) { + double projectedDistance = projectedDistanceForSolidBoxSolidBox( + lastSeparatingAxis, a, b, D, c, ca, ad, bd); + + // the separating axis from the last time step is still + // valid, the boxes do not intersect + if (projectedDistance > 0.0) { + return false; + } + } + + // test if the boxes can be separated by a plane normal to + // any of the three axes of box1, any of the three axes of box2, + // or any of the 9 possible cross products of axes from box1 + // and box2 + for (int i = 0; i < 15; i++) { + // do not need to check edge-edge cases if any two of + // the axes are parallel + if (parallelAxes && i == 6) { + return true; + } + + double projectedDistance = + projectedDistanceForSolidBoxSolidBox(i, a, b, D, c, ca, ad, bd); + + // found a separating axis, the boxes do not intersect + if (projectedDistance > 0.0) { + return false; + } + } + + return true; +} + + + +void CollisionDetection::closestPointsBetweenLineAndLine( + const Line & line1, + const Line & line2, + Vector3 & closest1, + Vector3 & closest2) { + // TODO make accessors for Line that don't make a copy of data + Vector3 P0 = line1.point(); + Vector3 u = line1.direction(); + Vector3 Q0 = line2.point(); + Vector3 v = line2.direction(); + Vector3 w0 = P0 - Q0; + + // a = 1.0, c = 1.0 + double b = dot(u, v); + double d = dot(u, w0); + double e = dot(v, w0); + double D = 1.0 - b * b; + double sc, tc; + + static const double epsilon = 0.00001; + + if (D < epsilon) { + // lines are parallel, choose P0 as one point, find the point + // on line2 that is closest to P0 + sc = 0.0; + tc = (b > 1.0) ? (d / b) : (e / 1.0); + } else { + // lines are not parallel + sc = (b * e - 1.0 * d) / D; + tc = (1.0 * e - b * d) / D; + } + + closest1 = P0 + (sc * u); + closest2 = Q0 + (tc * v); +} + + + +float CollisionDetection::penetrationDepthForFixedBoxFixedBox( + const Box& box1, + const Box& box2, + Array& contactPoints, + Array& contactNormals, + const int lastSeparatingAxis) { + + contactPoints.resize(0, DONT_SHRINK_UNDERLYING_ARRAY); + contactNormals.resize(0, DONT_SHRINK_UNDERLYING_ARRAY); + + Vector3 a; + Vector3 b; + Vector3 D; + double c[9]; + double ca[9]; + double ad[3]; + double bd[3]; + + debugAssert(lastSeparatingAxis >= -1); + debugAssert(lastSeparatingAxis < 15); + + fillSolidBoxSolidBoxInfo(box1, box2, a, b, D, c, ca, ad, bd); + + int axis1, axis2; + bool parallelAxes = parallelAxisForSolidBoxSolidBox(ca, 0.00001, + axis1, axis2); + + + // check the separating axis from the last time step + if (lastSeparatingAxis != -1 && + (lastSeparatingAxis < 6 || !parallelAxes)) { + float projectedDistance = projectedDistanceForSolidBoxSolidBox( + lastSeparatingAxis, a, b, D, c, ca, ad, bd); + + // the separating axis from the last time step is still + // valid, the boxes do not intersect + if (projectedDistance > 0.0) { + return -projectedDistance; + } + } + + // test if the boxes can be separated by a plane normal to + // any of the three axes of box1, any of the three axes of box2, + // (test 9 possible cross products later) + float penetration = -finf(); + int penetrationAxisIndex = -1; + + for (int i = 0; i < 6; i++) { + float projectedDistance = + projectedDistanceForSolidBoxSolidBox(i, a, b, D, c, ca, ad, bd); + + // found a separating axis, the boxes do not intersect + if (projectedDistance > 0.0) { + return -projectedDistance; + } + + // keep track of the axis that is least violated + if (projectedDistance > penetration) { + penetration = projectedDistance; + penetrationAxisIndex = i; + } + } + + + // for each edge-edge case we have to adjust the magnitude of + // penetration since we did not include the dot(L, L) denominator + // that can be smaller than 1.0 for the edge-edge cases. + if (!parallelAxes) { + double edgeDistances[9]; + + // run through edge-edge cases to see if we can find a separating axis + for (int i = 6; i < 15; i++) { + float projectedDistance = + projectedDistanceForSolidBoxSolidBox(i, a, b, D, c, ca, ad, bd); + + // found a separating axis, the boxes do not intersect, + // correct magnitude and return projected distance + if (projectedDistance > 0.0) { + Vector3 L = separatingAxisForSolidBoxSolidBox(i, box1, box2); + projectedDistance /= dot(L, L); + return -projectedDistance; + } + + edgeDistances[i - 6] = projectedDistance; + } + + // no separating axis found, the boxes do intersect, + // correct the magnitudes of the projectedDistance values + for (int i = 6; i < 15; i++) { + // find the negative penetration value with the smallest magnitude, + // the adjustment done for the edge-edge cases only increases + // magnitude by dividing by a number smaller than 1 and greater than 0 + float projectedDistance = (float)edgeDistances[i - 6]; + if (projectedDistance > penetration) { + Vector3 L = separatingAxisForSolidBoxSolidBox(i, box1, box2); + projectedDistance /= dot(L, L); + if (projectedDistance > penetration) { + penetration = projectedDistance; + penetrationAxisIndex = i; + } + } + } + } + + // get final separating axis vector + Vector3 L = separatingAxisForSolidBoxSolidBox(penetrationAxisIndex, + box1, box2); + + // set L to be the normal that faces away from box1 + if (dot(L, D) < 0) { + L = -L; + } + + Vector3 contactPoint; + + if (penetrationAxisIndex < 6) { + // vertex to face collision, find deepest colliding vertex + const Box* vertexBox; + const Box* faceBox; + Vector3 faceNormal = L; + + // L will be the outward facing normal for the faceBox + if (penetrationAxisIndex < 3) { + faceBox = & box1; + vertexBox = & box2; + if (dot(L, D) < 0) { + faceNormal = -L; + } + } else { + faceBox = & box2; + vertexBox = & box1; + if (dot(L, D) > 0) { + faceNormal = -L; + } + } + + // find the vertex that is farthest away in the direction + // face normal direction + int deepestPointIndex = 0; + float deepestPointDot = dot(faceNormal, vertexBox->corner(0)); + for (int i = 1; i < 8; i++) { + float dotProduct = dot(faceNormal, vertexBox->corner(i)); + if (dotProduct < deepestPointDot) { + deepestPointDot = dotProduct; + deepestPointIndex = i; + } + } + + // return the point half way between the deepest point and the + // contacting face + contactPoint = vertexBox->corner(deepestPointIndex) + + (-penetration * 0.5 * faceNormal); + } else { + // edge-edge case, find the two ege lines + int edge1 = (penetrationAxisIndex - 6) / 3; + int edge2 = (penetrationAxisIndex - 6) % 3; + Vector3 linePoint1 = box1.center(); + Vector3 linePoint2 = box2.center(); + Vector3 lineDir1; + Vector3 lineDir2; + + // find edge line by finding the edge axis, and the + // other two axes that are closest to the other box + for (int i = 0; i < 3; i++ ) { + if (i == edge1) { + lineDir1 = box1.axis(i); + } else { + Vector3 axis = box1.axis(i); + if (dot(axis, L) < 0) { + axis = -axis; + } + linePoint1 += axis * a[i]; + } + + if (i == edge2) { + lineDir2 = box2.axis(i); + } else { + Vector3 axis = box2.axis(i); + if (dot(axis, L) > 0) { + axis = -axis; + } + linePoint2 += axis * b[i]; + } + } + + // make lines from the two closest edges, and find + // the points that on each line that are closest to the other + Line line1 = Line::fromPointAndDirection(linePoint1, lineDir1); + Line line2 = Line::fromPointAndDirection(linePoint2, lineDir2); + Vector3 closest1; + Vector3 closest2; + + closestPointsBetweenLineAndLine(line1, line2, closest1, closest2); + + // take the average of the two closest edge points for the final + // contact point + contactPoint = (closest1 + closest2) * 0.5; + } + + contactPoints.push(contactPoint); + contactNormals.push(L); + + return -penetration; + +} + + + + +float CollisionDetection::penetrationDepthForFixedSphereFixedBox( + const Sphere& sphere, + const Box& box, + Array& contactPoints, + Array& contactNormals) { + + contactPoints.resize(0, DONT_SHRINK_UNDERLYING_ARRAY); + contactNormals.resize(0, DONT_SHRINK_UNDERLYING_ARRAY); + + // In its local coordinate frame, the box measures + // 2 * halfExtent[a] along dimesion a. + Vector3 halfExtent(box.extent(0), box.extent(1), box.extent(2)); + halfExtent *= 0.5f; + + CoordinateFrame boxFrame; + box.getLocalFrame(boxFrame); + + // Transform the sphere to the box's coordinate frame. + Vector3 center = boxFrame.pointToObjectSpace(sphere.center); + + // Find the square of the distance from the sphere to the box + + + // Distance along each axis from the closest side of the box + // to the sphere center. Negative values are *inside* the box. + Vector3 distOutsideBox; + + // Divide space up into the 27 regions corresponding + // to {+|-|0}X, {+|-|0}Y, {+|-|0}Z and classify the + // sphere center into one of them. + Vector3 centerRegion; + + // In the edge collision case, the edge is between vertices + // (constant + variable) and (constant - variable). + Vector3 constant, variable; + + int numNonZero = 0; + + // Iterate over axes + for (int a = 0; a < 3; ++a) { + // For each (box side), see which direction the sphere + // is outside the box (positive or negative). Add the + // square of that distance to the total distance from + // the box. + + float distanceFromLow = -halfExtent[a] - center[a]; + float distanceFromHigh = center[a] - halfExtent[a]; + + if (fabsf(distanceFromLow) < fabsf(distanceFromHigh)) { + distOutsideBox[a] = distanceFromLow; + } else { + distOutsideBox[a] = distanceFromHigh; + } + + if (distanceFromLow < 0.0) { + if (distanceFromHigh < 0.0) { + // Inside the box + centerRegion[a] = 0.0; + variable[a] = 1.0; + } else { + // Off the high side + centerRegion[a] = 1.0; + constant[a] = halfExtent[a]; + ++numNonZero; + } + } else if (distanceFromHigh < 0.0) { + // Off the low side + centerRegion[a] = -1.0; + constant[a] = -halfExtent[a]; + ++numNonZero; + } else { + debugAssertM(false, + "distanceFromLow and distanceFromHigh cannot both be positive"); + } + } + + // Squared distance between the outside of the box and the + // sphere center. + float d2 = Vector3::zero().max(distOutsideBox).squaredMagnitude(); + + if (d2 > square(sphere.radius)) { + // There is no penetration because the distance is greater + // than the radius of the sphere. This is the common case + // and we quickly exit. + return -1; + } + + // We know there is some penetration but need to classify it. + // + // Examine the region that contains the center of the sphere. If + // there is exactly one non-zero axis, the collision is with a + // plane. If there are exactly two non-zero axes, the collision + // is with an edge. If all three axes are non-zero, the collision is + // with a vertex. If there are no non-zero axes, the center is inside + // the box. + + double depth = -1; + switch (numNonZero) { + case 3: // Vertex collision + // The collision point is the vertex at constant, the normal + // is the vector from there to the sphere center. + contactNormals.append(boxFrame.normalToWorldSpace(constant - center)); + contactPoints.append(boxFrame.pointToWorldSpace(constant)); + depth = sphere.radius - sqrt(d2); + break; + + case 2: // Edge collision + { + // TODO: unwrapping the edge constructor and closest point + // code will probably make it faster. + + // Determine the edge + Line line = Line::fromPointAndDirection(constant, variable); + + // Penetration depth: + depth = sphere.radius - sqrt(d2); + + // The contact point is the closes point to the sphere on the line + Vector3 X = line.closestPoint(center); + contactNormals.append(boxFrame.normalToWorldSpace(X - center).direction()); + contactPoints.append(boxFrame.pointToWorldSpace(X)); + } + break; + + case 1: // Plane collision + { + // The plane normal is the centerRegion vector, + // so the sphere normal is the negative. Take + // it to world space from box-space. + + // Center region doesn't need to be normalized because + // it is known to contain only one non-zero value + // and that value is +/- 1. + Vector3 N = boxFrame.normalToWorldSpace(-centerRegion); + contactNormals.append(N); + + // Penetration depth: + depth = sphere.radius - sqrtf(d2); + + // Compute the contact point from the penetration depth + contactPoints.append(sphere.center + N * (sphere.radius - depth)); + } + break; + + case 0: // Volume collision + + // The sphere center is inside the box. This is an easy case + // to handle. Note that all axes of distOutsideBox must + // be negative. + + // Arbitratily choose the sphere center as a contact point + contactPoints.append(sphere.center); + + // Find the least-negative penetration axis. + // + // We could have computed this during the loop over the axes, + // but since volume collisions are rare (they only occur with + // large time steps), this case will seldom be executed and + // should not be optimized at the expense of the others. + if (distOutsideBox.x > distOutsideBox.y) { + if (distOutsideBox.x > distOutsideBox.z) { + // Smallest penetration on x-axis + // Chose normal based on which side we're closest to. + // Keep in mind that this is a normal to the sphere, + // so it is the inverse of the box normal. + if (center.x > 0) { + contactNormals.append(boxFrame.normalToWorldSpace(-Vector3::unitX())); + } else { + contactNormals.append(boxFrame.normalToWorldSpace(Vector3::unitX())); + } + depth = -distOutsideBox.x; + } else { + // Smallest penetration on z-axis + goto ZAXIS; + } + } else if (distOutsideBox.y > distOutsideBox.z) { + // Smallest penetration on y-axis + // Chose normal based on which side we're closest to. + // Keep in mind that this is a normal to the sphere, + // so it is the inverse of the box normal. + if (center.y > 0) { + contactNormals.append(boxFrame.normalToWorldSpace(-Vector3::unitY())); + } else { + contactNormals.append(boxFrame.normalToWorldSpace(Vector3::unitY())); + } + depth = -distOutsideBox.y; + } else { + // Smallest on z-axis +ZAXIS: + // Chose normal based on which side we're closest to. + // Keep in mind that this is a normal to the sphere, + // so it is the inverse of the box normal. + if (center.z > 0) { + contactNormals.append(boxFrame.normalToWorldSpace(-Vector3::unitZ())); + } else { + contactNormals.append(boxFrame.normalToWorldSpace(Vector3::unitZ())); + } + depth = -distOutsideBox.z; + } + break; + + default: + debugAssertM(false, "Fell through switch"); + break; + } + + return depth; +} + + +float CollisionDetection::penetrationDepthForFixedSphereFixedSphere( + const Sphere& sphereA, + const Sphere& sphereB, + Array& contactPoints, + Array& contactNormals) { + + Vector3 axis = sphereB.center - sphereA.center; + double radius = sphereA.radius + sphereB.radius; + double mag = axis.magnitude(); + axis /= mag; + double depth = -(mag - radius); + + contactPoints.resize(0, DONT_SHRINK_UNDERLYING_ARRAY); + contactNormals.resize(0, DONT_SHRINK_UNDERLYING_ARRAY); + + if (depth >= 0) { + contactPoints.append(sphereA.center + axis * (sphereA.radius - depth / 2)); + contactNormals.append(axis); + } + + return depth; +} + + +float CollisionDetection::penetrationDepthForFixedSphereFixedPlane( + const Sphere& sphereA, + const Plane& planeB, + Array& contactPoints, + Array& contactNormals) { + + Vector3 N; + double d; + + planeB.getEquation(N, d); + + double depth = -(sphereA.center.dot(N) + d - sphereA.radius); + + contactPoints.resize(0, DONT_SHRINK_UNDERLYING_ARRAY); + contactNormals.resize(0, DONT_SHRINK_UNDERLYING_ARRAY); + + if (depth >= 0) { + contactPoints.append(N * (depth - sphereA.radius) + sphereA.center); + contactNormals.append(N); + } + + return depth; +} + + +float CollisionDetection::penetrationDepthForFixedBoxFixedPlane( + const Box& box, + const Plane& plane, + Array& contactPoints, + Array& contactNormals) { + + Vector3 N; + double d; + + plane.getEquation(N, d); + + contactPoints.resize(0, DONT_SHRINK_UNDERLYING_ARRAY); + contactNormals.resize(0, DONT_SHRINK_UNDERLYING_ARRAY); + + float lowest = finf(); + for (int i = 0; i < 8; ++i) { + const Vector3 vertex = box.corner(i); + + float x = vertex.dot(N) + (float)d; + + if (x <= 0) { + // All vertices below the plane should be contact points. + contactPoints.append(vertex); + contactNormals.append(-N); + } + + lowest = min(lowest, x); + } + + // Depth should be a positive number + return -lowest; +} + + +float CollisionDetection::collisionTimeForMovingPointFixedPlane( + const Vector3& point, + const Vector3& velocity, + const Plane& plane, + Vector3& location, + Vector3& outNormal) { + + // Solve for the time at which normal.dot(point + velocity) + d == 0. + double d; + Vector3 normal; + plane.getEquation(normal, d); + + float vdotN = velocity.dot(normal); + float pdotN = point.dot(normal); + + if (fuzzyEq(pdotN + d, 0)) { + // The point is *in* the plane. + location = point; + outNormal = normal; + return 0; + } + + if (vdotN >= 0) { + // no collision will occur + location = Vector3::inf(); + return finf(); + } + + float t = -(pdotN + d) / vdotN; + if (t < 0) { + location = Vector3::inf(); + return finf(); + } else { + location = point + velocity * t; + outNormal = normal; + return t; + } +} + +bool __fastcall CollisionDetection::rayAABox( + const Ray& ray, + const Vector3& invDir, + const AABox& box, + const Vector3& boxCenter, + float boundingRadiusSquared, + Vector3& location, + bool& inside) { + + debugAssertM(fabs(ray.direction().squaredLength() - 1.0f) < 0.01f, format("Length = %f", ray.direction().length())); + { + // Pre-emptive partial bounding sphere test + const Vector3 L(boxCenter - ray.origin()); + float d = L.dot(ray.direction()); + + float L2 = L.dot(L); + float D2 = square(d); + float M2 = L2 - D2; + + if (((d < 0) && (L2 > boundingRadiusSquared)) || (M2 > boundingRadiusSquared)) { + inside = false; + return false; + } + // Passing here does not mean that the ray hits the bounding sphere; + // we would still have to perform more expensive tests to determine + // that. + } + + inside = true; + const Vector3& MinB = box.low(); + const Vector3& MaxB = box.high(); + Vector3 MaxT(-1.0f, -1.0f, -1.0f); + + // Find candidate planes. + for (int i = 0; i < 3; ++i) { + if (ray.origin()[i] < MinB[i]) { + location[i] = MinB[i]; + inside = false; + + // Calculate T distances to candidate planes + if (ray.direction()[i] != 0) { + MaxT[i] = (MinB[i] - ray.origin()[i]) * invDir[i]; + } + } else if (ray.origin()[i] > MaxB[i]) { + location[i] = MaxB[i]; + inside = false; + + // Calculate T distances to candidate planes + if (ray.direction()[i] != 0) { + MaxT[i] = (MaxB[i] - ray.origin()[i]) * invDir[i]; + } + } + } + + if (inside) { + // Ray origin inside bounding box + location = ray.origin(); + return true; + } + + // Get largest of the maxT's for final choice of intersection + int WhichPlane = 0; + if (MaxT[1] > MaxT[WhichPlane]) { + WhichPlane = 1; + } + + if (MaxT[2] > MaxT[WhichPlane]) { + WhichPlane = 2; + } + + // Check final candidate actually inside box + if (MaxT[WhichPlane] < 0.0f) { + // Miss the box + return false; + } + + for (int i = 0; i < 3; ++i) { + if (i != WhichPlane) { + location[i] = ray.origin()[i] + MaxT[WhichPlane] * ray.direction()[i]; + if ((location[i] < MinB[i]) || + (location[i] > MaxB[i])) { + // On this plane we're outside the box extents, so + // we miss the box + return false; + } + } + } + + return true; +} + +float CollisionDetection::collisionTimeForMovingPointFixedSphere( + const Vector3& point, + const Vector3& velocity, + const Sphere& sphere, + Vector3& location, + Vector3& outNormal, + bool solid) { + + if (solid && sphere.contains(point)) { + location = point; + outNormal = (point - sphere.center).direction(); + return 0.0f; + } + + float speed = velocity.magnitude(); + const Vector3& direction = velocity / speed; + + // length of the axis between the start and the sphere + const Vector3& L = sphere.center - point; + float d = L.dot(direction); + + float L2 = L.dot(L); + float R2 = square(sphere.radius); + float D2 = square(d); + + if ((d < 0.0f) && (L2 > R2)) { + location = Vector3::inf(); + return finf(); + } + + const float M2 = L2 - D2; + + if (M2 > R2) { + location = Vector3::inf(); + return finf(); + } + + float q = sqrt(R2 - M2); + float time; + + if (L2 > R2) { + time = d - q; + } else { + time = d + q; + } + + time /= speed; + + location = point + velocity * time; + outNormal = (location - sphere.center).direction(); + + return time; +} + + +float CollisionDetection::collisionTimeForMovingSphereFixedSphere( + const Sphere& movingSphere, + const Vector3& velocity, + const Sphere& fixedSphere, + Vector3& location, + Vector3& outNormal) { + + const Vector3& sep = (fixedSphere.center - movingSphere.center); + float sepLen = sep.squaredLength(); + if (sepLen < square(movingSphere.radius + fixedSphere.radius)) { + // Interpenetrating + outNormal = sep.directionOrZero(); + location = fixedSphere.center - outNormal * fixedSphere.radius; + return 0; + } + + float time = collisionTimeForMovingPointFixedSphere + (movingSphere.center, velocity, + Sphere(fixedSphere.center, fixedSphere.radius + movingSphere.radius), + location, outNormal); + + if (time < finf()) { + // Location is now the center of the moving sphere at the collision time. + // Adjust for the size of the moving sphere. Two spheres always collide + // along a line between their centers. + location += (location - fixedSphere.center) * movingSphere.radius / fixedSphere.radius; + } + + return time; +} + + +/* +float CollisionDetection::collisionTimeForMovingPointFixedTriangle( + const Vector3& point, + const Vector3& velocity, + const Triangle& triangle, + Vector3& outLocation, + Vector3& outNormal) { + + double time = collisionTimeForMovingPointFixedPlane(point, velocity, triangle.plane(), outLocation, outNormal); + + if (time == finf()) { + // No collision with the plane of the triangle. + return finf(); + } + + if (isPointInsideTriangle(triangle.vertex(0), triangle.vertex(1), triangle.vertex(2), triangle.normal(), outLocation, triangle.primaryAxis())) { + // Collision occured inside the triangle + return time; + } else { + // Missed the triangle + outLocation = Vector3::inf(); + return finf(); + } +}*/ + +/* +float CollisionDetection::collisionTimeForMovingPointFixedTriangle( + const Vector3& orig, + const Vector3& dir, + const Vector3& vert0, + const Vector3& vert1, + const Vector3& vert2) { + + // Barycenteric coords + double u, v; + #define EPSILON 0.000001 + #define CROSS(dest,v1,v2) \ + dest[0]=v1[1]*v2[2]-v1[2]*v2[1]; \ + dest[1]=v1[2]*v2[0]-v1[0]*v2[2]; \ + dest[2]=v1[0]*v2[1]-v1[1]*v2[0]; + + #define DOT(v1,v2) (v1[0]*v2[0]+v1[1]*v2[1]+v1[2]*v2[2]) + + #define SUB(dest,v1,v2) \ + dest[0]=v1[0]-v2[0]; \ + dest[1]=v1[1]-v2[1]; \ + dest[2]=v1[2]-v2[2]; + + double edge1[3], edge2[3], tvec[3], pvec[3], qvec[3]; + + // find vectors for two edges sharing vert0 + SUB(edge1, vert1, vert0); + SUB(edge2, vert2, vert0); + + // begin calculating determinant - also used to calculate U parameter + CROSS(pvec, dir, edge2); + + // if determinant is near zero, ray lies in plane of triangle + const double det = DOT(edge1, pvec); + + if (det < EPSILON) { + return finf(); + } + + // calculate distance from vert0 to ray origin + SUB(tvec, orig, vert0); + + // calculate U parameter and test bounds + u = DOT(tvec, pvec); + if ((u < 0.0) || (u > det)) { + // Hit the plane outside the triangle + return finf(); + } + + // prepare to test V parameter + CROSS(qvec, tvec, edge1); + + // calculate V parameter and test bounds + v = DOT(dir, qvec); + if ((v < 0.0) || (u + v > det)) { + // Hit the plane outside the triangle + return finf(); + } + + // calculate t, scale parameters, ray intersects triangle + // If we want u,v, we can compute this + // double t = DOT(edge2, qvec); + //const double inv_det = 1.0 / det; + //t *= inv_det; + //u *= inv_det; + //v *= inv_det; + // return t; + + // Case where we don't need correct (u, v): + + const double t = DOT(edge2, qvec); + + if (t >= 0) { + // Note that det must be positive + return t / det; + } else { + // We had to travel backwards in time to intersect + return finf(); + } + + #undef EPSILON + #undef CROSS + #undef DOT + #undef SUB +} +*/ + +float CollisionDetection::collisionTimeForMovingPointFixedBox( + const Vector3& point, + const Vector3& velocity, + const Box& box, + Vector3& location, + Vector3& outNormal) { + + double bestTime; + + Vector3 normal; + Vector3 v[4]; + + // Prime the loop + int f = 0; + box.getFaceCorners(f, v[0], v[1], v[2], v[3]); + bestTime = collisionTimeForMovingPointFixedRectangle(point, velocity, v[0], v[1], v[2], v[3], location, normal); + outNormal = normal; + + // Check other faces + for (f = 1; f < 6; ++f) { + Vector3 pos; + box.getFaceCorners(f, v[0], v[1], v[2], v[3]); + float time = collisionTimeForMovingPointFixedRectangle(point, velocity, v[0], v[1], v[2], v[3], pos, normal); + if (time < bestTime) { + bestTime = time; + outNormal = normal; + location = pos; + } + } + + return bestTime; +} + + +float CollisionDetection::collisionTimeForMovingPointFixedAABox( + const Vector3& origin, + const Vector3& dir, + const AABox& box, + Vector3& location, + bool& Inside, + Vector3& normal) { + + if (collisionLocationForMovingPointFixedAABox(origin, dir, box, location, Inside, normal)) { + return (location - origin).magnitude(); + } else { + return (float)finf(); + } +} + + +bool CollisionDetection::collisionLocationForMovingPointFixedAABox( + const Vector3& origin, + const Vector3& dir, + const AABox& box, + Vector3& location, + bool& Inside, + Vector3& normal) { + + // Integer representation of a floating-point value. + #define IR(x) ((uint32&)x) + + Inside = true; + const Vector3& MinB = box.low(); + const Vector3& MaxB = box.high(); + Vector3 MaxT(-1.0f, -1.0f, -1.0f); + + // Find candidate planes. + for (int i = 0; i < 3; ++i) { + if (origin[i] < MinB[i]) { + location[i] = MinB[i]; + Inside = false; + + // Calculate T distances to candidate planes + if (IR(dir[i])) { + MaxT[i] = (MinB[i] - origin[i]) / dir[i]; + } + } else if (origin[i] > MaxB[i]) { + location[i] = MaxB[i]; + Inside = false; + + // Calculate T distances to candidate planes + if (IR(dir[i])) { + MaxT[i] = (MaxB[i] - origin[i]) / dir[i]; + } + } + } + + if (Inside) { + // Ray origin inside bounding box + location = origin; + return false; + } + + // Get largest of the maxT's for final choice of intersection + int WhichPlane = 0; + if (MaxT[1] > MaxT[WhichPlane]) { + WhichPlane = 1; + } + + if (MaxT[2] > MaxT[WhichPlane]) { + WhichPlane = 2; + } + + // Check final candidate actually inside box + if (IR(MaxT[WhichPlane]) & 0x80000000) { + // Miss the box + return false; + } + + for (int i = 0; i < 3; ++i) { + if (i != WhichPlane) { + location[i] = origin[i] + MaxT[WhichPlane] * dir[i]; + if ((location[i] < MinB[i]) || + (location[i] > MaxB[i])) { + // On this plane we're outside the box extents, so + // we miss the box + return false; + } + } + } + + // Choose the normal to be the plane normal facing into the ray + normal = Vector3::zero(); + normal[WhichPlane] = (dir[WhichPlane] > 0) ? -1.0 : 1.0; + + return true; + + #undef IR +} + + + +float CollisionDetection::collisionTimeForMovingPointFixedRectangle( + const Vector3& point, + const Vector3& velocity, + const Vector3& v0, + const Vector3& v1, + const Vector3& v2, + const Vector3& v3, + Vector3& location, + Vector3& outNormal) { + + Plane plane = Plane(v0, v1, v2); + + float time = collisionTimeForMovingPointFixedPlane(point, velocity, plane, location, outNormal); + + if (time == finf()) { + // No collision is ever going to happen + return time; + } + + if (isPointInsideRectangle(v0, v1, v2, v3, plane.normal(), location)) { + // The intersection point is inside the rectangle; that is the location where + // the point hits the rectangle. + return time; + } else { + return finf(); + } +} + +/** Used by findRayCapsuleIntersection. + @cite From magic software http://www.magic-software.com/Source/Intersection3D/MgcIntr3DLinCap.cpp */ +static int findRayCapsuleIntersectionAux( + const Vector3& rkOrigin, + const Vector3& rkDirection, + const Capsule& rkCapsule, + double afT[2]) { + + Vector3 capsuleDirection = rkCapsule.point(1) - rkCapsule.point(0); + + // set up quadratic Q(t) = a*t^2 + 2*b*t + c + Vector3 kU, kV, kW = capsuleDirection; + float fWLength = kW.unitize(); + Vector3::generateOrthonormalBasis(kU, kV, kW); + Vector3 kD(kU.dot(rkDirection), kV.dot(rkDirection), kW.dot(rkDirection)); + float fDLength = kD.unitize(); + + float fEpsilon = 1e-6f; + + float fInvDLength = 1.0f/fDLength; + Vector3 kDiff = rkOrigin - rkCapsule.point(0); + Vector3 kP(kU.dot(kDiff),kV.dot(kDiff),kW.dot(kDiff)); + float fRadiusSqr = square(rkCapsule.radius()); + + float fInv, fA, fB, fC, fDiscr, fRoot, fT, fTmp; + + // Is the velocity parallel to the capsule direction? (or zero) + if ((abs(kD.z) >= 1.0f - fEpsilon) || (fDLength < fEpsilon)) { + + float fAxisDir = rkDirection.dot(capsuleDirection); + + fDiscr = fRadiusSqr - kP.x*kP.x - kP.y*kP.y; + if ((fAxisDir < 0) && (fDiscr >= 0.0f)) { + // Velocity anti-parallel to the capsule direction + fRoot = sqrt(fDiscr); + afT[0] = (kP.z + fRoot)*fInvDLength; + afT[1] = -(fWLength - kP.z + fRoot)*fInvDLength; + return 2; + } else if ((fAxisDir > 0) && (fDiscr >= 0.0f)) { + // Velocity parallel to the capsule direction + fRoot = sqrt(fDiscr); + afT[0] = -(kP.z + fRoot)*fInvDLength; + afT[1] = (fWLength - kP.z + fRoot)*fInvDLength; + return 2; + } else { + // sphere heading wrong direction, or no velocity at all + return 0; + } + } + + // test intersection with infinite cylinder + fA = kD.x*kD.x + kD.y*kD.y; + fB = kP.x*kD.x + kP.y*kD.y; + fC = kP.x*kP.x + kP.y*kP.y - fRadiusSqr; + fDiscr = fB*fB - fA*fC; + if (fDiscr < 0.0f) { + // line does not intersect infinite cylinder + return 0; + } + + int iQuantity = 0; + + if (fDiscr > 0.0f) { + // line intersects infinite cylinder in two places + fRoot = sqrt(fDiscr); + fInv = 1.0f/fA; + fT = (-fB - fRoot)*fInv; + fTmp = kP.z + fT*kD.z; + if ((0.0f <= fTmp) && (fTmp <= fWLength)) { + afT[iQuantity] = fT * fInvDLength; + iQuantity++; + } + + fT = (-fB + fRoot)*fInv; + fTmp = kP.z + fT*kD.z; + + if ((0.0f <= fTmp) && (fTmp <= fWLength)) { + afT[iQuantity++] = fT*fInvDLength; + } + + if (iQuantity == 2) { + // line intersects capsule wall in two places + return 2; + } + } else { + // line is tangent to infinite cylinder + fT = -fB/fA; + fTmp = kP.z + fT*kD.z; + if ((0.0f <= fTmp) && (fTmp <= fWLength)) { + afT[0] = fT*fInvDLength; + return 1; + } + } + + // test intersection with bottom hemisphere + // fA = 1 + fB += kP.z*kD.z; + fC += kP.z*kP.z; + fDiscr = fB*fB - fC; + if (fDiscr > 0.0f) { + fRoot = sqrt(fDiscr); + fT = -fB - fRoot; + fTmp = kP.z + fT*kD.z; + if (fTmp <= 0.0f) { + afT[iQuantity++] = fT*fInvDLength; + if (iQuantity == 2) { + return 2; + } + } + + fT = -fB + fRoot; + fTmp = kP.z + fT*kD.z; + if (fTmp <= 0.0f) { + afT[iQuantity++] = fT*fInvDLength; + if (iQuantity == 2) { + return 2; + } + } + } else if (fDiscr == 0.0f) { + fT = -fB; + fTmp = kP.z + fT*kD.z; + if (fTmp <= 0.0f) { + afT[iQuantity++] = fT*fInvDLength; + if (iQuantity == 2) { + return 2; + } + } + } + + // test intersection with top hemisphere + // fA = 1 + fB -= kD.z*fWLength; + fC += fWLength*(fWLength - 2.0f*kP.z); + + fDiscr = fB*fB - fC; + if (fDiscr > 0.0f) { + fRoot = sqrt(fDiscr); + fT = -fB - fRoot; + fTmp = kP.z + fT*kD.z; + if (fTmp >= fWLength) { + afT[iQuantity++] = fT*fInvDLength; + if (iQuantity == 2) { + return 2; + } + } + + fT = -fB + fRoot; + fTmp = kP.z + fT*kD.z; + if (fTmp >= fWLength) { + afT[iQuantity++] = fT*fInvDLength; + if (iQuantity == 2) { + return 2; + } + } + } else if (fDiscr == 0.0f) { + fT = -fB; + fTmp = kP.z + fT*kD.z; + if (fTmp >= fWLength) { + afT[iQuantity++] = fT*fInvDLength; + if (iQuantity == 2) { + return 2; + } + } + } + + return iQuantity; +} + + +/** Used by collisionTimeForMovingPointFixedCapsule. + @cite From magic software http://www.magic-software.com/Source/Intersection3D/MgcIntr3DLinCap.cpp + + @param rkRay The ray + @param rkCapsule The capsule + @param riQuantity The number of intersections found + @param akPoint The intersections found + @return True if there is at least one intersection + */ +static bool findRayCapsuleIntersection( + const Ray& rkRay, + const Capsule& rkCapsule, + int& riQuantity, + Vector3 akPoint[2]) { + + double afT[2]; + riQuantity = findRayCapsuleIntersectionAux(rkRay.origin(), rkRay.direction(), rkCapsule, afT); + + // Only return intersections that occur in the future + int iClipQuantity = 0; + int i; + for (i = 0; i < riQuantity; ++i) { + if (afT[i] >= 0.0f) { + akPoint[iClipQuantity] = rkRay.origin() + afT[i] * rkRay.direction(); + ++iClipQuantity; + } + } + + riQuantity = iClipQuantity; + return (riQuantity > 0); +} + +float CollisionDetection::collisionTimeForMovingPointFixedCapsule( + const Vector3& _point, + const Vector3& velocity, + const Capsule& capsule, + Vector3& location, + Vector3& outNormal) { + + float timeScale = velocity.magnitude(); + + if (timeScale == 0.0f) { + timeScale = 1; + } + + Vector3 direction = velocity / timeScale; + int numIntersections; + Vector3 intersection[2]; + findRayCapsuleIntersection(Ray::fromOriginAndDirection(_point, direction), capsule, numIntersections, intersection); + + if (numIntersections == 2) { + // A collision can only occur if there are two intersections. If there is one + // intersection, that one is exiting the capsule. + + // Find the entering intersection (the first one that occurs). + float d0 = (intersection[0] - _point).squaredMagnitude(); + float d1 = (intersection[1] - _point).squaredMagnitude(); + + // Compute the surface normal (if we aren't ignoring the result) + if (&outNormal != &ignore) { + Vector3 p2 = LineSegment::fromTwoPoints(capsule.point(0), capsule.point(1)).closestPoint(_point); + outNormal = (_point - p2).direction(); + } + + if (d0 > d1) { + location = intersection[1]; + return sqrt(d1) / timeScale; + } else { + location = intersection[0]; + return sqrt(d0) / timeScale; + } + } else { + // No entering intersection discovered; return no intersection. + location = Vector3::inf(); + return finf(); + } +} + + +float CollisionDetection::collisionTimeForMovingSphereFixedPlane( + const Sphere& sphere, + const Vector3& velocity, + const Plane& plane, + Vector3& location, + Vector3& outNormal) { + + if (sphere.radius == 0) { + // Optimization for zero radius sphere + return collisionTimeForMovingPointFixedPlane(sphere.center, velocity, plane, location, outNormal); + } + + // The collision point on the sphere will be the point at + // center - (radius * normal). Collisions only occur when + // the sphere is travelling into the plane. + + double d; + plane.getEquation(outNormal, d); + + double vdotN = velocity.dot(outNormal); + + if (fuzzyGt(vdotN, 0)) { + // No collision when the sphere is moving towards a backface. + location = Vector3::inf(); + return (float)finf(); + } + + float cdotN = sphere.center.dot(outNormal); + + // Distance from the center to the plane + float distance = cdotN + (float)d; + + // Where is the collision on the sphere? + Vector3 point = sphere.center - (sphere.radius * outNormal); + + if (fuzzyLe(G3D::abs(distance), sphere.radius)) { + // Already interpenetrating + location = sphere.center - distance * outNormal; + return 0; + } else { + return collisionTimeForMovingPointFixedPlane(point, velocity, plane, location, outNormal); + } + +} + + +float CollisionDetection::collisionTimeForMovingSphereFixedTriangle( + const class Sphere& sphere, + const Vector3& velocity, + const Triangle& triangle, + Vector3& outLocation, + float b[3]) { + + Vector3 dummy; + float time = collisionTimeForMovingSphereFixedPlane(sphere, velocity, triangle.plane(), + outLocation, dummy); + + if (time == finf()) { + // No collision is ever going to happen + return time; + } + + // We will hit the plane of the triangle at *time*. See if + // the intersection point actually is within the triangle. + + if (isPointInsideTriangle(triangle.vertex(0), triangle.vertex(1), triangle.vertex(2), triangle.normal(), + outLocation, b, triangle.primaryAxis())) { + + // The intersection point is inside the triangle; that is the location where + // the sphere hits the triangle. + +# ifdef G3D_DEBUG + { + // Internal consistency checks + debugAssertM(b[0] >= 0.0 && b[0] <= 1.0f, "Intersection is outside triangle."); + debugAssertM(b[1] >= 0.0 && b[1] <= 1.0f, "Intersection is outside triangle."); + debugAssertM(b[2] >= 0.0 && b[2] <= 1.0f, "Intersection is outside triangle."); + Vector3 blend = + b[0] * triangle.vertex(0) + + b[1] * triangle.vertex(1) + + b[2] * triangle.vertex(2); + debugAssertM(blend.fuzzyEq(outLocation), "Barycentric coords don't match intersection."); + // Call again so that we can debug the problem + // isPointInsideTriangle(triangle.vertex(0), triangle.vertex(1), triangle.vertex(2), triangle.normal(), + // outLocation, b, triangle.primaryAxis()); + } +# endif + + return time; + } + + // The collision (if it exists) is with a point on the triangle perimeter. + // Switch over to moving the triangle towards a fixed sphere and see at what time + // they will hit. + + // Closest point on the triangle to the sphere intersection with the plane. + int edgeIndex; + const Vector3& point = closestPointOnTrianglePerimeter(triangle._vertex, triangle.edgeDirection, + triangle.edgeMagnitude, outLocation, edgeIndex); + + float t = 0; + if (! sphere.contains(point)) { + // The point is outside the sphere--see when it will hit + t = collisionTimeForMovingPointFixedSphere(point, -velocity, sphere, dummy, dummy); + } + + if (t < finf()) { + outLocation = point; + // Compute Barycentric coords + + // Index of the next vertex + static const int next[] = {1, 2, 0}; + + // Project along the edge in question. + // Avoid sqrt by taking advantage of the existing edgeDirection unit vector. + b[next[edgeIndex]] = (outLocation - triangle._vertex[edgeIndex]).dot + (triangle.edgeDirection[edgeIndex]) / triangle.edgeMagnitude[edgeIndex]; + + b[edgeIndex] = 1.0f - b[next[edgeIndex]]; + + b[next[next[edgeIndex]]] = 0.0f; + +# ifdef G3D_DEBUG + { + // Internal consistency checks + for (int i = 0; i < 3; ++i) { + debugAssertM(fuzzyGe(b[i], 0.0f) && fuzzyLe(b[i], 1.0f), "Intersection is outside triangle."); + } + Vector3 blend = + b[0] * triangle.vertex(0) + + b[1] * triangle.vertex(1) + + b[2] * triangle.vertex(2); + debugAssertM(blend.fuzzyEq(outLocation), + format("Barycentric coords don't match intersection. %s != %s", + blend.toString().c_str(), + outLocation.toString().c_str())); + + // Call again so that we can debug the problem + collisionTimeForMovingPointFixedSphere(point, -velocity, sphere, dummy, dummy); + } +# endif + + // Due to tiny roundoffs, these values might be slightly out of bounds. + // Ensure that they are legal. Note that the above debugging code + // verifies that we are not clamping truly illegal values. + for (int i = 0; i < 3; ++i) { + b[i] = clamp(b[i], 0.0f, 1.0f); + } + } + + // The collision occured at the point, if it occured. The normal + // was the plane normal, computed above. + + return t; +} + + +float CollisionDetection::collisionTimeForMovingSphereFixedRectangle( + const Sphere& sphere, + const Vector3& velocity, + const Vector3& v0, + const Vector3& v1, + const Vector3& v2, + const Vector3& v3, + Vector3& location, + Vector3& outNormal) { + + Plane plane(v0, v1, v2); + + float time = collisionTimeForMovingSphereFixedPlane(sphere, velocity, plane, location, outNormal); + + if (time == finf()) { + // No collision is ever going to happen + return time; + } + + if (isPointInsideRectangle(v0, v1, v2, v3, plane.normal(), location)) { + // The intersection point is inside the rectangle; that is the location where + // the sphere hits the rectangle. + return time; + } + + // Switch over to moving the rectangle towards a fixed sphere and see at what time + // they will hit. + + Vector3 point = closestPointToRectanglePerimeter(v0, v1, v2, v3, sphere.center); + + Vector3 dummy; + double t = collisionTimeForMovingPointFixedSphere(point, -velocity, sphere, location, dummy); + + // Normal is the plane normal, location is the original location of the point. + location = point; + + return t; +} + + +float CollisionDetection::collisionTimeForMovingSphereFixedBox( + const Sphere& sphere, + const Vector3& velocity, + const Box& box, + Vector3& location, + Vector3& outNormal) { + + if (fixedSolidSphereIntersectsFixedSolidBox(sphere, box)) { + // TODO: Compute more useful location and normal? + location = sphere.center; + outNormal = Vector3::zero(); + return 0; + } + + float bestTime; + + Vector3 v[4]; + int f = 0; + box.getFaceCorners(f, v[0], v[1], v[2], v[3]); + bestTime = collisionTimeForMovingSphereFixedRectangle(sphere, velocity, v[0], v[1], v[2], v[3], location, outNormal); + + for (f = 1; f < 6; ++f) { + Vector3 pos, normal; + box.getFaceCorners(f, v[0], v[1], v[2], v[3]); + float time = collisionTimeForMovingSphereFixedRectangle(sphere, velocity, v[0], v[1], v[2], v[3], pos, normal); + if (time < bestTime) { + bestTime = time; + location = pos; + outNormal = normal; + } + } + + return bestTime; +} + + +float CollisionDetection::collisionTimeForMovingSphereFixedCapsule( + const Sphere& sphere, + const Vector3& velocity, + const Capsule& capsule, + Vector3& location, + Vector3& outNormal) { + + (void)outNormal; + + Capsule _capsule(capsule.point(0), capsule.point(1), capsule.radius() + sphere.radius); + + Vector3 normal; + double time = collisionTimeForMovingPointFixedCapsule(sphere.center, velocity, _capsule, location, normal); + + if (time < finf()) { + // Location is now the position of the center of the sphere at the time of collision. + // We have to adjust the collision location for the size of the sphere. + location -= sphere.radius * normal; + } + + return time; +} + + +Vector3 CollisionDetection::bounceDirection( + const Sphere& sphere, + const Vector3& velocity, + const float collisionTime, + const Vector3& collisionLocation, + const Vector3& collisionNormal) { + + // Location when the collision occurs + Vector3 sphereLocation = sphere.center + velocity * collisionTime; + + Vector3 normal = (sphereLocation - collisionLocation); + if (fuzzyEq(normal.squaredMagnitude(), 0)) { + normal = collisionNormal; + } else { + normal.unitize(); + } + + Vector3 direction = velocity.direction(); + + // Reflect direction about the normal + return direction - 2.0 * normal * normal.dot(direction); +} + + +Vector3 CollisionDetection::slideDirection( + const Sphere& sphere, + const Vector3& velocity, + const float collisionTime, + const Vector3& collisionLocation) { + + Vector3 sphereLocation = sphere.center + velocity * collisionTime; + Vector3 normal = (sphereLocation - collisionLocation).direction(); + Vector3 direction = velocity.direction(); + + // subtract off the part in the direction away from the normal. + return direction - normal * normal.dot(direction); +} + + +Vector3 CollisionDetection::closestPointOnLineSegment( + const Vector3& v0, + const Vector3& v1, + const Vector3& point) { + + const Vector3& edge = (v1 - v0); + float edgeLength = edge.magnitude(); + + if (edgeLength == 0) { + // The line segment is a point + return v0; + } + + return closestPointOnLineSegment(v0, v1, edge / edgeLength, edgeLength, point); +} + + +Vector3 CollisionDetection::closestPointOnLineSegment( + const Vector3& v0, + const Vector3& v1, + const Vector3& edgeDirection, + const float edgeLength, + const Vector3& point) { + + debugAssert((v1 - v0).direction().fuzzyEq(edgeDirection)); + debugAssert(fuzzyEq((v1 - v0).magnitude(), edgeLength)); + + // Vector towards the point + const Vector3& c = point - v0; + + // Projected onto the edge itself + float t = edgeDirection.dot(c); + + if (t <= 0) { + // Before the start + return v0; + } else if (t >= edgeLength) { + // After the end + return v1; + } else { + // At distance t along the edge + return v0 + edgeDirection * t; + } +} + + +Vector3 CollisionDetection::closestPointOnTrianglePerimeter( + const Vector3& v0, + const Vector3& v1, + const Vector3& v2, + const Vector3& point) { + + Vector3 v[3] = {v0, v1, v2}; + Vector3 edgeDirection[3] = {(v1 - v0), (v2 - v1), (v0 - v2)}; + float edgeLength[3]; + + for (int i = 0; i < 3; ++i) { + edgeLength[i] = edgeDirection[i].magnitude(); + edgeDirection[i] /= edgeLength[i]; + } + + int edgeIndex; + return closestPointOnTrianglePerimeter(v, edgeDirection, edgeLength, point, edgeIndex); +} + + +Vector3 CollisionDetection::closestPointOnTrianglePerimeter( + const Vector3 v[3], + const Vector3 edgeDirection[3], + const float edgeLength[3], + const Vector3& point, + int& edgeIndex) { + + // Closest point on segment from v[i] to v[i + 1] + Vector3 r[3]; + + // Distance squared from r[i] to point + float d[3]; + + // Index of the next point + static const int next[] = {1, 2, 0}; + + for (int i = 0; i < 3; ++i) { + r[i] = closestPointOnLineSegment(v[i], v[next[i]], edgeDirection[i], edgeLength[i], point); + d[i] = (r[i] - point).squaredMagnitude(); + } + + if (d[0] < d[1]) { + if (d[0] < d[2]) { + // Between v0 and v1 + edgeIndex = 0; + } else { + // Between v2 and v0 + edgeIndex = 2; + } + } else { + if (d[1] < d[2]) { + // Between v1 and v2 + edgeIndex = 1; + } else { + // Between v2 and v0 + edgeIndex = 2; + } + } + +# ifdef G3D_DEBUG + { + Vector3 diff = r[edgeIndex] - v[edgeIndex]; + debugAssertM(fuzzyEq(diff.direction().dot(edgeDirection[edgeIndex]), 1.0f) || + diff.fuzzyEq(Vector3::zero()), "Point not on correct triangle edge"); + float frac = diff.dot(edgeDirection[edgeIndex])/edgeLength[edgeIndex]; + debugAssertM(frac >= -0.000001, "Point off low side of edge."); + debugAssertM(frac <= 1.000001, "Point off high side of edge."); + } +# endif + + return r[edgeIndex]; +} + + +bool CollisionDetection::isPointInsideTriangle( + const Vector3& v0, + const Vector3& v1, + const Vector3& v2, + const Vector3& normal, + const Vector3& point, + float b[3], + Vector3::Axis primaryAxis) { + + if (primaryAxis == Vector3::DETECT_AXIS) { + primaryAxis = normal.primaryAxis(); + } + + // Check that the point is within the triangle using a Barycentric + // coordinate test on a two dimensional plane. + int i, j; + + switch (primaryAxis) { + case Vector3::X_AXIS: + i = Vector3::Y_AXIS; + j = Vector3::Z_AXIS; + break; + + case Vector3::Y_AXIS: + i = Vector3::Z_AXIS; + j = Vector3::X_AXIS; + break; + + case Vector3::Z_AXIS: + i = Vector3::X_AXIS; + j = Vector3::Y_AXIS; + break; + + default: + // This case is here to supress a warning on Linux + i = j = 0; + debugAssertM(false, "Should not get here."); + break; + } + + // See if all barycentric coordinates are non-negative + + // 2D area via cross product +# define AREA2(d, e, f) (((e)[i] - (d)[i]) * ((f)[j] - (d)[j]) - ((f)[i] - (d)[i]) * ((e)[j] - (d)[j])) + + // Area of the polygon + float area = AREA2(v0, v1, v2); + if (area == 0) { + // This triangle has zero area, so the point must not + // be in it unless the triangle point is the test point. + return (v0 == point); + } + + debugAssert(area != 0); + + float invArea = 1.0f / area; + + // (avoid normalization until absolutely necessary) + b[0] = AREA2(point, v1, v2) * invArea; + + if ((b[0] < 0.0f) || (b[0] > 1.0f)) { + return false; + } + + b[1] = AREA2(v0, point, v2) * invArea; + if ((b[1] < 0.0f) || (b[1] > 1.0f)) { + return false; + } + + b[2] = 1.0f - b[0] - b[1]; + +# undef AREA2 + + return (b[2] >= 0.0f) && (b[2] <= 1.0f); +} + + +bool CollisionDetection::isPointInsideRectangle( + const Vector3& v0, + const Vector3& v1, + const Vector3& v2, + const Vector3& v3, + const Vector3& normal, + const Vector3& point) { + + return isPointInsideTriangle(v0, v1, v2, normal, point) || + isPointInsideTriangle(v2, v3, v0, normal, point); +} + + +Vector3 CollisionDetection::closestPointToRectanglePerimeter( + const Vector3& v0, + const Vector3& v1, + const Vector3& v2, + const Vector3& v3, + const Vector3& point) { + + Vector3 r0 = closestPointOnLineSegment(v0, v1, point); + Vector3 r1 = closestPointOnLineSegment(v1, v2, point); + Vector3 r2 = closestPointOnLineSegment(v2, v3, point); + Vector3 r3 = closestPointOnLineSegment(v3, v0, point); + + double d0 = (r0 - point).squaredMagnitude(); + double d1 = (r1 - point).squaredMagnitude(); + double d2 = (r2 - point).squaredMagnitude(); + double d3 = (r3 - point).squaredMagnitude(); + + if (d0 < d1) { + if (d0 < d2) { + if (d0 < d3) { + return r0; + } else { + return r3; + } + } else { + if (d2 < d3) { + return r2; + } else { + return r3; + } + } + } else { + if (d1 < d2) { + if (d1 < d3) { + return r1; + } else { + return r3; + } + } else { + if (d2 < d3) { + return r2; + } else { + return r3; + } + } + } +} + + +Vector3 CollisionDetection::closestPointToRectangle( + const Vector3& v0, + const Vector3& v1, + const Vector3& v2, + const Vector3& v3, + const Vector3& point) { + + Plane plane(v0, v1, v2); + + // Project the point into the plane + double a, b, c, d; + plane.getEquation(a, b, c, d); + + double distance = a*point.x + b*point.y + c*point.z + d; + Vector3 planePoint = point - distance * plane.normal(); + + if (isPointInsideRectangle(v0, v1, v2, v3, plane.normal(), planePoint)) { + return planePoint; + } else { + return closestPointToRectanglePerimeter(v0, v1, v2, v3, planePoint); + } +} + + +bool CollisionDetection::fixedSolidSphereIntersectsFixedSolidSphere( + const Sphere& sphere1, + const Sphere& sphere2) { + + return (sphere1.center - sphere2.center).squaredMagnitude() < square(sphere1.radius + sphere2.radius); +} + + +bool CollisionDetection::fixedSolidSphereIntersectsFixedSolidBox( + const Sphere& sphere, + const Box& box) { + + // If the center of the sphere is within the box, the whole + // sphere is within the box. + if (box.contains(sphere.center)) { + return true; + } + + float r2 = square(sphere.radius); + + // Find the closest point on the surface of the box to the sphere. If + // this point is within the sphere's radius, they intersect. + int f; + for (f = 0; f < 6; ++f) { + Vector3 v0, v1, v2, v3; + box.getFaceCorners(f, v0, v1, v2, v3); + if ((closestPointToRectangle(v0, v1, v2, v3, sphere.center) - sphere.center).squaredMagnitude() <= r2) { + return true; + } + } + + return false; +} + + +bool CollisionDetection::movingSpherePassesThroughFixedBox( + const Sphere& sphere, + const Vector3& velocity, + const Box& box, + double timeLimit) { + + // If they intersect originally, they definitely pass through each other. + if (fixedSolidSphereIntersectsFixedSolidBox(sphere, box)) { + return true; + } + + // See if the sphere hits the box during the time period. + Vector3 dummy1, dummy2; + + return (collisionTimeForMovingSphereFixedBox(sphere, velocity, box, dummy1, dummy2) < timeLimit); +} + + +bool CollisionDetection::movingSpherePassesThroughFixedSphere( + const Sphere& sphere, + const Vector3& velocity, + const Sphere& fixedSphere, + double timeLimit) { + + if (fixedSolidSphereIntersectsFixedSolidSphere(sphere, fixedSphere)) { + return true; + } + + // Extend the fixed sphere by the radius of the moving sphere + Sphere bigFixed(fixedSphere.center, fixedSphere.radius + sphere.radius); + Vector3 dummy1, dummy2; + + // If the sphere collides with the other sphere during the time limit, it passes through + return (collisionTimeForMovingPointFixedSphere(sphere.center, velocity, bigFixed, dummy1, dummy2) < timeLimit); +} + + + +bool CollisionDetection::fixedSolidSphereIntersectsFixedTriangle( + const Sphere& sphere, + const Triangle& triangle) { + + // How far is the sphere from the plane of the triangle + const Plane& plane = triangle.plane(); + + // Does the closest point to the sphere center lie within the triangle? + Vector3 v = plane.closestPoint(sphere.center); + + // Is the closest point to the plane within the sphere? + if ((v - sphere.center).squaredLength() <= square(sphere.radius)) { + // Is it also within the triangle? + float b[3]; + if (isPointInsideTriangle(triangle.vertex(0), triangle.vertex(1), triangle.vertex(2), triangle.normal(), + v, b, triangle.primaryAxis())){ + // The closest point is inside the triangle + return true; + } + } + + // ignored + int edgeIndex; + + v = closestPointOnTrianglePerimeter(triangle._vertex, triangle.edgeDirection, triangle.edgeMagnitude, sphere.center, edgeIndex); + + // Is the closest point within the sphere? + return ((v - sphere.center).squaredLength() <= square(sphere.radius)); +} + + +//////////////////////////////////////////////////////////////////////////////// +// AABB-triangle overlap test code based on Tomas Akenine-Möller's +// http://www.cs.lth.se/home/Tomas_Akenine_Moller/code/tribox3.txt +// Ported 2008-12-28 + +#define X 0 +#define Y 1 +#define Z 2 + +#define FINDMINMAX(x0, x1, x2, min, max) \ + min = max = x0; \ + if(x1max) max=x1;\ + if(x2max) max=x2; + +static bool planeBoxOverlap(const Vector3& normal, const Vector3& vert, const Vector3& maxbox) { + Vector3 vmin, vmax; + float v; + + // for each axis + for(int a = 0; a < 3; ++a) { + v = vert[a]; + + if (normal[a] > 0.0f) { + vmin[a] = -maxbox[a] - v; + vmax[a] = maxbox[a] - v; + } else { + vmin[a] = maxbox[a] - v; + vmax[a] = -maxbox[a] - v; + } + } + + if (normal.dot(vmin) > 0.0f) { + return false; + } else if (normal.dot(vmax) >= 0.0f) { + return true; + } else { + return false; + } +} + +/*======================== X-tests ========================*/ + +#define AXISTEST_X01(a, b, fa, fb) \ + p0 = a*v0[Y] - b*v0[Z]; \ + p2 = a*v2[Y] - b*v2[Z]; \ + if(p0rad || max<-rad) return false; + + +#define AXISTEST_X2(a, b, fa, fb) \ + p0 = a*v0[Y] - b*v0[Z]; \ + p1 = a*v1[Y] - b*v1[Z]; \ + if(p0rad || max<-rad) return false; + +/*======================== Y-tests ========================*/ + +#define AXISTEST_Y02(a, b, fa, fb) \ + p0 = -a*v0[X] + b*v0[Z]; \ + p2 = -a*v2[X] + b*v2[Z]; \ + if(p0rad || max<-rad) return false; + +#define AXISTEST_Y1(a, b, fa, fb) \ + p0 = -a*v0[X] + b*v0[Z]; \ + p1 = -a*v1[X] + b*v1[Z]; \ + if(p0rad || max<-rad) return false; + +/*======================== Z-tests ========================*/ + +#define AXISTEST_Z12(a, b, fa, fb) \ + p1 = a*v1[X] - b*v1[Y]; \ + p2 = a*v2[X] - b*v2[Y]; \ + if(p2rad || max<-rad) return false; + +#define AXISTEST_Z0(a, b, fa, fb) \ + p0 = a*v0[X] - b*v0[Y]; \ + p1 = a*v1[X] - b*v1[Y]; \ + if(p0rad || max<-rad) return false; + +bool CollisionDetection::fixedSolidBoxIntersectsFixedTriangle( + const AABox& box, const Triangle& tri) { + + // use separating axis theorem to test overlap between triangle and box + // need to test for overlap in these directions: + // 1) the {x,y,z}-directions (actually, since we use the AABB of the triangle + // we do not even need to test these) + // 2) normal of the triangle + // 3) crossproduct(edge from tri, {x,y,z}-direction) + // this gives 3x3=9 more tests + + // This is the fastest branch (on Sun). + // Move the triangle to the object space of the box + // Triangle vertices in box object space + + const Vector3& boxcenter = box.center(); + const Vector3& boxhalfsize = box.extent() * 0.5f; + + const Vector3& v0 = tri.vertex(0) - boxcenter; + const Vector3& v1 = tri.vertex(1) - boxcenter; + const Vector3& v2 = tri.vertex(2) - boxcenter; + + // Compute triangle edges in object space + const Vector3& e0 = v1 - v0; + const Vector3& e1 = v2 - v1; + const Vector3& e2 = v0 - v2; + + // Bullet 3: + // test the 9 tests first (this was faster) + float min,max,p0,p1,p2,rad; + Vector3 fe; + + fe = abs(e0); + AXISTEST_X01(e0[Z], e0[Y], fe[Z], fe[Y]); + AXISTEST_Y02(e0[Z], e0[X], fe[Z], fe[X]); + AXISTEST_Z12(e0[Y], e0[X], fe[Y], fe[X]); + + fe = abs(e1); + AXISTEST_X01(e1[Z], e1[Y], fe[Z], fe[Y]); + AXISTEST_Y02(e1[Z], e1[X], fe[Z], fe[X]); + AXISTEST_Z0 (e1[Y], e1[X], fe[Y], fe[X]); + + fe = abs(e2); + AXISTEST_X2 (e2[Z], e2[Y], fe[Z], fe[Y]); + AXISTEST_Y1 (e2[Z], e2[X], fe[Z], fe[X]); + AXISTEST_Z12(e2[Y], e2[X], fe[Y], fe[X]); + + // Bullet 1: + // first test overlap in the {x,y,z}-directions + // find min, max of the triangle each direction, and test for overlap in + // that direction -- this is equivalent to testing a minimal AABB around + // the triangle against the AABB + + // test in X-direction + FINDMINMAX(v0[X],v1[X],v2[X],min,max); + if (min > boxhalfsize[X] || max < -boxhalfsize[X]) { + return false; + } + + // test in Y-direction + FINDMINMAX(v0[Y],v1[Y],v2[Y],min,max); + if (min > boxhalfsize[Y] || max < -boxhalfsize[Y]) { + return false; + } + + // test in Z-direction + FINDMINMAX(v0[Z],v1[Z],v2[Z],min,max); + if (min > boxhalfsize[Z] || max < -boxhalfsize[Z]) { + return false; + } + + // Bullet 2: + // test if the box intersects the plane of the triangle + // compute plane equation of triangle: normal*x+d=0 + + if (! planeBoxOverlap(tri.normal(), v0, boxhalfsize)) { + return false; + } + + // box and triangle overlap + return true; +} +#undef X +#undef Y +#undef Z + +//////////////////////////////////////////////////////////////////////////////// + + +} // namespace + +#ifdef _MSC_VER +// Turn off fast floating-point optimizations +#pragma float_control( pop ) +#pragma warning (pop) +#endif diff --git a/dep/g3dlite/CoordinateFrame.cpp b/dep/g3dlite/CoordinateFrame.cpp new file mode 100644 index 00000000000..9b639b62082 --- /dev/null +++ b/dep/g3dlite/CoordinateFrame.cpp @@ -0,0 +1,436 @@ +/** + @file CoordinateFrame.cpp + + Coordinate frame class + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2001-06-02 + @edited 2009-11-13 + + Copyright 2000-2010, Morgan McGuire. + All rights reserved. +*/ + +#include "G3D/platform.h" +#include "G3D/CoordinateFrame.h" +#include "G3D/Quat.h" +#include "G3D/Matrix4.h" +#include "G3D/Box.h" +#include "G3D/AABox.h" +#include "G3D/Sphere.h" +#include "G3D/Triangle.h" +#include "G3D/Ray.h" +#include "G3D/Capsule.h" +#include "G3D/Cylinder.h" +#include "G3D/UprightFrame.h" +#include "G3D/Any.h" +#include "G3D/stringutils.h" + +namespace G3D { + +CoordinateFrame::CoordinateFrame(const Any& any) { + any.verifyName("CFrame"); + if (toUpper(any.name()) == "CFRAME") { + any.verifyType(Any::TABLE, Any::ARRAY); + if (any.type() == Any::TABLE) { + rotation = any["rotation"]; + translation = any["translation"]; + } else { + any.verifySize(2); + rotation = any[0]; + translation = any[1]; + } + } else { + any.verifyName("CFrame::fromXYZYPRDegrees"); + any.verifyType(Any::ARRAY); + any.verifySize(3, 6); + + int s = any.size(); + + *this = fromXYZYPRDegrees(any[0], any[1], any[2], + (s > 3) ? any[3].number() : 0.0f, + (s > 4) ? any[4].number() : 0.0f, + (s > 5) ? any[5].number() : 0.0f); + } +} + + +CoordinateFrame::operator Any() const { + float x, y, z, yaw, pitch, roll; + getXYZYPRDegrees(x, y, z, yaw, pitch, roll); + Any a(Any::ARRAY, "CFrame::fromXYZYPRDegrees"); + a.append(x, y, z, yaw); + if ( ! G3D::fuzzyEq(yaw, 0.0f) || ! G3D::fuzzyEq(pitch, 0.0f) || ! G3D::fuzzyEq(roll, 0.0f)) { + a.append(yaw); + if (! G3D::fuzzyEq(pitch, 0.0f) || ! G3D::fuzzyEq(roll, 0.0f)) { + a.append(pitch); + if (! G3D::fuzzyEq(roll, 0.0f)) { + a.append(roll); + } + } + } + return a; +} + + +CoordinateFrame::CoordinateFrame(const class UprightFrame& f) { + *this = f.toCoordinateFrame(); +} + + +CoordinateFrame::CoordinateFrame() : + rotation(Matrix3::identity()), translation(Vector3::zero()) { +} + +CoordinateFrame CoordinateFrame::fromXYZYPRRadians(float x, float y, float z, float yaw, + float pitch, float roll) { + Matrix3 rotation = Matrix3::fromAxisAngle(Vector3::unitY(), yaw); + + rotation = Matrix3::fromAxisAngle(rotation.column(0), pitch) * rotation; + rotation = Matrix3::fromAxisAngle(rotation.column(2), roll) * rotation; + + const Vector3 translation(x, y, z); + + return CoordinateFrame(rotation, translation); +} + + +void CoordinateFrame::getXYZYPRRadians(float& x, float& y, float& z, + float& yaw, float& pitch, float& roll) const { + x = translation.x; + y = translation.y; + z = translation.z; + + const Vector3& look = lookVector(); + + if (abs(look.y) > 0.99f) { + // Looking nearly straight up or down + + yaw = G3D::pi() + atan2(look.x, look.z); + pitch = asin(look.y); + roll = 0.0f; + + } else { + + // Yaw cannot be affected by others, so pull it first + yaw = G3D::pi() + atan2(look.x, look.z); + + // Pitch is the elevation of the yaw vector + pitch = asin(look.y); + + Vector3 actualRight = rightVector(); + Vector3 expectedRight = look.cross(Vector3::unitY()); + + roll = 0;//acos(actualRight.dot(expectedRight)); TODO + } +} + + +void CoordinateFrame::getXYZYPRDegrees(float& x, float& y, float& z, + float& yaw, float& pitch, float& roll) const { + getXYZYPRRadians(x, y, z, yaw, pitch, roll); + yaw = toDegrees(yaw); + pitch = toDegrees(pitch); + roll = toDegrees(roll); +} + + +CoordinateFrame CoordinateFrame::fromXYZYPRDegrees(float x, float y, float z, + float yaw, float pitch, float roll) { + return fromXYZYPRRadians(x, y, z, toRadians(yaw), toRadians(pitch), toRadians(roll)); +} + + +Ray CoordinateFrame::lookRay() const { + return Ray::fromOriginAndDirection(translation, lookVector()); +} + + +bool CoordinateFrame::fuzzyEq(const CoordinateFrame& other) const { + + for (int c = 0; c < 3; ++c) { + for (int r = 0; r < 3; ++r) { + if (! G3D::fuzzyEq(other.rotation[r][c], rotation[r][c])) { + return false; + } + } + if (! G3D::fuzzyEq(translation[c], other.translation[c])) { + return false; + } + } + + return true; +} + + +bool CoordinateFrame::fuzzyIsIdentity() const { + const Matrix3& I = Matrix3::identity(); + + for (int c = 0; c < 3; ++c) { + for (int r = 0; r < 3; ++r) { + if (fuzzyNe(I[r][c], rotation[r][c])) { + return false; + } + } + if (fuzzyNe(translation[c], 0)) { + return false; + } + } + + return true; +} + + +bool CoordinateFrame::isIdentity() const { + return + (translation == Vector3::zero()) && + (rotation == Matrix3::identity()); +} + + +Matrix4 CoordinateFrame::toMatrix4() const { + return Matrix4(*this); +} + + +std::string CoordinateFrame::toXML() const { + return G3D::format( + "\n %lf,%lf,%lf,%lf,\n %lf,%lf,%lf,%lf,\n %lf,%lf,%lf,%lf,\n %lf,%lf,%lf,%lf\n\n", + rotation[0][0], rotation[0][1], rotation[0][2], translation.x, + rotation[1][0], rotation[1][1], rotation[1][2], translation.y, + rotation[2][0], rotation[2][1], rotation[2][2], translation.z, + 0.0, 0.0, 0.0, 1.0); +} + + +Plane CoordinateFrame::toObjectSpace(const Plane& p) const { + Vector3 N, P; + double d; + p.getEquation(N, d); + P = N * (float)d; + P = pointToObjectSpace(P); + N = normalToObjectSpace(N); + return Plane(N, P); +} + + +Plane CoordinateFrame::toWorldSpace(const Plane& p) const { + Vector3 N, P; + double d; + p.getEquation(N, d); + P = N * (float)d; + P = pointToWorldSpace(P); + N = normalToWorldSpace(N); + return Plane(N, P); +} + + +Triangle CoordinateFrame::toObjectSpace(const Triangle& t) const { + return Triangle(pointToObjectSpace(t.vertex(0)), + pointToObjectSpace(t.vertex(1)), + pointToObjectSpace(t.vertex(2))); +} + + +Triangle CoordinateFrame::toWorldSpace(const Triangle& t) const { + return Triangle(pointToWorldSpace(t.vertex(0)), + pointToWorldSpace(t.vertex(1)), + pointToWorldSpace(t.vertex(2))); +} + + +Cylinder CoordinateFrame::toWorldSpace(const Cylinder& c) const { + return Cylinder( + pointToWorldSpace(c.point(0)), + pointToWorldSpace(c.point(1)), + c.radius()); +} + + +Capsule CoordinateFrame::toWorldSpace(const Capsule& c) const { + return Capsule( + pointToWorldSpace(c.point(0)), + pointToWorldSpace(c.point(1)), + c.radius()); +} + + +Box CoordinateFrame::toWorldSpace(const AABox& b) const { + Box b2(b); + return toWorldSpace(b2); +} + + +Box CoordinateFrame::toWorldSpace(const Box& b) const { + Box out(b); + + for (int i = 0; i < 8; ++i) { + out._corner[i] = pointToWorldSpace(b._corner[i]); + debugAssert(! isNaN(out._corner[i].x)); + } + + for (int i = 0; i < 3; ++i) { + out._axis[i] = vectorToWorldSpace(b._axis[i]); + } + + out._center = pointToWorldSpace(b._center); + + return out; +} + + +Box CoordinateFrame::toObjectSpace(const Box &b) const { + return inverse().toWorldSpace(b); +} + + +Box CoordinateFrame::toObjectSpace(const AABox& b) const { + return toObjectSpace(Box(b)); +} + + +CoordinateFrame::CoordinateFrame(class BinaryInput& b) : rotation(Matrix3::zero()) { + deserialize(b); +} + + +void CoordinateFrame::deserialize(class BinaryInput& b) { + rotation.deserialize(b); + translation.deserialize(b); +} + + +void CoordinateFrame::serialize(class BinaryOutput& b) const { + rotation.serialize(b); + translation.serialize(b); +} + + +Sphere CoordinateFrame::toWorldSpace(const Sphere &b) const { + return Sphere(pointToWorldSpace(b.center), b.radius); +} + + +Sphere CoordinateFrame::toObjectSpace(const Sphere &b) const { + return Sphere(pointToObjectSpace(b.center), b.radius); +} + + +Ray CoordinateFrame::toWorldSpace(const Ray& r) const { + return Ray::fromOriginAndDirection(pointToWorldSpace(r.origin()), vectorToWorldSpace(r.direction())); +} + + +Ray CoordinateFrame::toObjectSpace(const Ray& r) const { + return Ray::fromOriginAndDirection(pointToObjectSpace(r.origin()), vectorToObjectSpace(r.direction())); +} + + +void CoordinateFrame::lookAt(const Vector3 &target) { + lookAt(target, Vector3::unitY()); +} + + +void CoordinateFrame::lookAt( + const Vector3& target, + Vector3 up) { + + up = up.direction(); + + Vector3 look = (target - translation).direction(); + if (fabs(look.dot(up)) > .99f) { + up = Vector3::unitX(); + if (fabs(look.dot(up)) > .99f) { + up = Vector3::unitY(); + } + } + + up -= look * look.dot(up); + up.unitize(); + + Vector3 z = -look; + Vector3 x = -z.cross(up); + x.unitize(); + + Vector3 y = z.cross(x); + + rotation.setColumn(0, x); + rotation.setColumn(1, y); + rotation.setColumn(2, z); +} + + +CoordinateFrame CoordinateFrame::lerp( + const CoordinateFrame& other, + float alpha) const { + + if (alpha == 1.0f) { + return other; + } else if (alpha == 0.0f) { + return *this; + } else { + Quat q1 = Quat(this->rotation); + Quat q2 = Quat(other.rotation); + + return CoordinateFrame( + q1.slerp(q2, alpha).toRotationMatrix(), + this->translation * (1 - alpha) + other.translation * alpha); + } +} + + +void CoordinateFrame::pointToWorldSpace(const Array& v, Array& vout) const { + vout.resize(v.size()); + + for (int i = v.size() - 1; i >= 0; --i) { + vout[i] = pointToWorldSpace(v[i]); + } +} + + +void CoordinateFrame::normalToWorldSpace(const Array& v, Array& vout) const { + vout.resize(v.size()); + + for (int i = v.size() - 1; i >= 0; --i) { + vout[i] = normalToWorldSpace(v[i]); + } +} + + +void CoordinateFrame::vectorToWorldSpace(const Array& v, Array& vout) const { + vout.resize(v.size()); + + for (int i = v.size() - 1; i >= 0; --i) { + vout[i] = vectorToWorldSpace(v[i]); + } +} + + +void CoordinateFrame::pointToObjectSpace(const Array& v, Array& vout) const { + vout.resize(v.size()); + + for (int i = v.size() - 1; i >= 0; --i) { + vout[i] = pointToObjectSpace(v[i]); + } +} + + +void CoordinateFrame::normalToObjectSpace(const Array& v, Array& vout) const { + vout.resize(v.size()); + + for (int i = v.size() - 1; i >= 0; --i) { + vout[i] = normalToObjectSpace(v[i]); + } +} + + +void CoordinateFrame::vectorToObjectSpace(const Array& v, Array& vout) const { + vout.resize(v.size()); + + for (int i = v.size() - 1; i >= 0; --i) { + vout[i] = vectorToObjectSpace(v[i]); + } +} + +} // namespace diff --git a/dep/g3dlite/Crypto.cpp b/dep/g3dlite/Crypto.cpp new file mode 100644 index 00000000000..c69b23375ce --- /dev/null +++ b/dep/g3dlite/Crypto.cpp @@ -0,0 +1,70 @@ +/** + @file Crypto.cpp + + @author Morgan McGuire, http://graphics.cs.williams.edu + + + @created 2006-03-28 + @edited 2006-04-06 + */ + +#include "G3D/platform.h" +#include "G3D/Crypto.h" +#include "G3D/g3dmath.h" +#include + +namespace G3D { + + +int Crypto::smallPrime(int n) { + debugAssert(n < numSmallPrimes() && n >= 0); + + // From: + // http://primes.utm.edu/lists/small/1000.txt + + static const int table[] = { + 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, + 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, + 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, + 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, + 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, + 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, + 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, + 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, + 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, + 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, + 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, + 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, + 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, + 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, + 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, + 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, + 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, + 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, + 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, + 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, + 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, + 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, + 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, + 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, + 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, + 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, + 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, + 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, + 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, + 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, + 1993, 1997, 1999}; + + return table[n]; +} + + +int Crypto::numSmallPrimes() { + return 303; +} + +uint32 Crypto::crc32(const void* byte, size_t numBytes) { + return ::crc32(::crc32(0, Z_NULL, 0), static_cast(byte), numBytes); +} + +} // G3D diff --git a/dep/g3dlite/Cylinder.cpp b/dep/g3dlite/Cylinder.cpp new file mode 100644 index 00000000000..7a7b9f9440d --- /dev/null +++ b/dep/g3dlite/Cylinder.cpp @@ -0,0 +1,176 @@ +/** + @file Cylinder.cpp + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2003-02-07 + @edited 2006-02-18 + + Copyright 2000-2006, Morgan McGuire. + All rights reserved. + */ + +#include "G3D/platform.h" +#include "G3D/Cylinder.h" +#include "G3D/BinaryInput.h" +#include "G3D/BinaryOutput.h" +#include "G3D/LineSegment.h" +#include "G3D/CoordinateFrame.h" +#include "G3D/Line.h" +#include "G3D/AABox.h" + +namespace G3D { + +Cylinder::Cylinder(class BinaryInput& b) { + deserialize(b); +} + + +Cylinder::Cylinder() { +} + + +Cylinder::Cylinder(const Vector3& _p1, const Vector3& _p2, float _r) + : p1(_p1), p2(_p2), mRadius(_r) { +} + + +void Cylinder::serialize(class BinaryOutput& b) const { + p1.serialize(b); + p2.serialize(b); + b.writeFloat64(mRadius); +} + + +void Cylinder::deserialize(class BinaryInput& b) { + p1.deserialize(b); + p2.deserialize(b); + mRadius = b.readFloat64(); +} + + +Line Cylinder::axis() const { + return Line::fromTwoPoints(p1, p2); +} + + + +float Cylinder::radius() const { + return mRadius; +} + + +float Cylinder::volume() const { + return + (float)pi() * square(mRadius) * (p1 - p2).magnitude(); +} + + +float Cylinder::area() const { + return + // Sides + (twoPi() * mRadius) * height() + + + // Caps + twoPi() * square(mRadius); +} + +void Cylinder::getBounds(AABox& out) const { + Vector3 min = p1.min(p2) - (Vector3(1, 1, 1) * mRadius); + Vector3 max = p1.max(p2) + (Vector3(1, 1, 1) * mRadius); + out = AABox(min, max); +} + +bool Cylinder::contains(const Vector3& p) const { + return LineSegment::fromTwoPoints(p1, p2).distanceSquared(p) <= square(mRadius); +} + + +void Cylinder::getReferenceFrame(CoordinateFrame& cframe) const { + cframe.translation = center(); + + Vector3 Y = (p1 - p2).direction(); + Vector3 X = (abs(Y.dot(Vector3::unitX())) > 0.9) ? Vector3::unitY() : Vector3::unitX(); + Vector3 Z = X.cross(Y).direction(); + X = Y.cross(Z); + cframe.rotation.setColumn(0, X); + cframe.rotation.setColumn(1, Y); + cframe.rotation.setColumn(2, Z); +} + + +void Cylinder::getRandomSurfacePoint(Vector3& p, Vector3& N) const { + float h = height(); + float r = radius(); + + // Create a random point on a standard cylinder and then rotate to the global frame. + + // Relative areas (factor of 2PI already taken out) + float capRelArea = square(r) / 2.0f; + float sideRelArea = r * h; + + float r1 = uniformRandom(0, capRelArea * 2 + sideRelArea); + + if (r1 < capRelArea * 2) { + + // Select a point uniformly at random on a disk + // @cite http://mathworld.wolfram.com/DiskPointPicking.html + float a = uniformRandom(0, (float)twoPi()); + float r2 = sqrt(uniformRandom(0, 1)) * r; + p.x = cos(a) * r2; + p.z = sin(a) * r2; + + N.x = 0; + N.z = 0; + if (r1 < capRelArea) { + // Top + p.y = h / 2.0f; + N.y = 1; + } else { + // Bottom + p.y = -h / 2.0f; + N.y = -1; + } + } else { + // Side + float a = uniformRandom(0, (float)twoPi()); + N.x = cos(a); + N.y = 0; + N.z = sin(a); + p.x = N.x * r; + p.z = N.y * r; + p.y = uniformRandom(-h / 2.0f, h / 2.0f); + } + + // Transform to world space + CoordinateFrame cframe; + getReferenceFrame(cframe); + + p = cframe.pointToWorldSpace(p); + N = cframe.normalToWorldSpace(N); +} + + +Vector3 Cylinder::randomInteriorPoint() const { + float h = height(); + float r = radius(); + + // Create a random point in a standard cylinder and then rotate to the global frame. + + // Select a point uniformly at random on a disk + // @cite http://mathworld.wolfram.com/DiskPointPicking.html + float a = uniformRandom(0, (float)twoPi()); + float r2 = sqrt(uniformRandom(0, 1)) * r; + + Vector3 p( cos(a) * r2, + uniformRandom(-h / 2.0f, h / 2.0f), + sin(a) * r2); + + // Transform to world space + CoordinateFrame cframe; + getReferenceFrame(cframe); + + return cframe.pointToWorldSpace(p); +} + +} // namespace diff --git a/dep/g3dlite/G3D/AABox.h b/dep/g3dlite/G3D/AABox.h new file mode 100644 index 00000000000..2e8da1f6098 --- /dev/null +++ b/dep/g3dlite/G3D/AABox.h @@ -0,0 +1,272 @@ +/** + @file AABox.h + + Axis-aligned box class + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2004-01-10 + @edited 2009-02-10 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_AABOX_H +#define G3D_AABOX_H + +#include "G3D/platform.h" +#include "G3D/Vector3.h" +#include "G3D/debug.h" +#include "G3D/Array.h" +#include "G3D/Plane.h" + +namespace G3D { + +/** + An axis-aligned box. + */ +class AABox { +private: + friend class Intersect; + + /** Optional argument placeholder */ + static int dummy; + + Vector3 lo; + Vector3 hi; + +public: + + /** Does not initialize the fields */ + inline AABox() {} + + /** + Constructs a zero-area AABox at v. + */ + inline explicit AABox(const Vector3& v) { + lo = hi = v; + } + + /** Assumes that low is less than or equal to high along each dimension. + To have this automatically enforced, use + AABox(low.min(high), low.max(high)); + */ + inline AABox(const Vector3& low, const Vector3& high) { + set(low, high); + } + + /** Assumes that low is less than or equal to high along each dimension. + */ + inline void set(const Vector3& low, const Vector3& high) { + debugAssert( + (low.x <= high.x) && + (low.y <= high.y) && + (low.z <= high.z)); + lo = low; + hi = high; + } + + /** + Grows to include the bounds of a + */ + inline void merge(const AABox& a) { + lo = lo.min(a.lo); + hi = hi.max(a.hi); + } + + inline void merge(const Vector3& a) { + lo = lo.min(a); + hi = hi.max(a); + } + + void serialize(class BinaryOutput& b) const; + + void deserialize(class BinaryInput& b); + + inline bool isFinite() const { + return lo.isFinite() && hi.isFinite(); + } + + inline const Vector3& low() const { + return lo; + } + + inline const Vector3& high() const { + return hi; + } + + /** + The largest possible finite box. + */ + static const AABox& maxFinite(); + + /** A large finite box. This is smaller than FLT_MAX + because it leaves room to add boxes together. */ + static const AABox& large(); + + static const AABox& inf(); + + static const AABox& zero(); + + /** + Returns the centroid of the box. + */ + inline Vector3 center() const { + return (lo + hi) * 0.5; + } + + Vector3 corner(int index) const; + + /** + Distance from corner(0) to the next corner along axis a. + */ + inline float extent(int a) const { + debugAssert(a < 3); + return hi[a] - lo[a]; + } + + + inline Vector3 extent() const { + return hi - lo; + } + + + /** + Splits the box into two AABoxes along the specified axis. low contains + the part that was closer to negative infinity along axis, high contains + the other part. Either may have zero volume. + */ + void split(const Vector3::Axis& axis, float location, AABox& low, AABox& high) const; + + /** + Conservative culling test for up to 32 planes. + Returns true if there exists a plane[p] for + which the entire object is in the negative half space + (opposite the plane normal). + + testMask and childMask + are used for optimizing bounding volume hierarchies. + The version of this method that produces childMask + is slower than the version without; it should only + be used for parent nodes. + + @param cullingPlaneIndex The index of the first plane for which + the entire object is in the negative half-space. The function + exits early when one plane is found. -1 when the function + returns false (i.e. when no plane culls the whole object). + + @param testMask If bit p is 0, the + bounding volume automatically passes the culling test for + plane[p] (i.e. it is known that the volume + is entirely within the positive half space). The function + must return false if testMask is 0 and test all planes + when testMask is -1 (0xFFFFFFFF). + + @param childMask Test mask for the children of this volume. + + */ + bool culledBy( + const Array& plane, + int32& cullingPlaneIndex, + const uint32 testMask, + uint32& childMask) const; + + /** + Conservative culling test that does not produce a mask for children. + */ + bool culledBy( + const Array& plane, + int32& cullingPlaneIndex = dummy, + const uint32 testMask = 0xFFFFFFFF) const; + + /** less than or equal to containment */ + inline bool contains(const AABox& other) const { + return + (other.hi.x <= hi.x) && + (other.hi.y <= hi.y) && + (other.hi.z <= hi.z) && + (other.lo.x >= lo.x) && + (other.lo.y >= lo.y) && + (other.lo.z >= lo.z); + } + + inline bool contains( + const Vector3& point) const { + return + (point.x >= lo.x) && + (point.y >= lo.y) && + (point.z >= lo.z) && + (point.x <= hi.x) && + (point.y <= hi.y) && + (point.z <= hi.z); + } + + inline float area() const { + Vector3 diag = hi - lo; + return 2.0f * (diag.x * diag.y + diag.y * diag.z + diag.x * diag.z); + } + + inline float volume() const { + Vector3 diag = hi - lo; + return diag.x * diag.y * diag.z; + } + + Vector3 randomInteriorPoint() const; + + Vector3 randomSurfacePoint() const; + + /** Returns true if there is any overlap */ + bool intersects(const AABox& other) const; + + /** Returns true if there is any overlap. + @cite Jim Arvo's algorithm from Graphics Gems II*/ + bool intersects(const class Sphere& other) const; + + /** Return the intersection of the two boxes */ + AABox intersect(const AABox& other) const { + Vector3 H = hi.min(other.hi); + Vector3 L = lo.max(other.lo).min(H); + return AABox(L, H); + } + + inline size_t hashCode() const { + return lo.hashCode() + hi.hashCode(); + } + + inline bool operator==(const AABox& b) const { + return (lo == b.lo) && (hi == b.hi); + } + + inline bool operator!=(const AABox& b) const { + return !((lo == b.lo) && (hi == b.hi)); + } + + inline AABox operator+(const Vector3& v) const { + AABox out; + out.lo = lo + v; + out.hi = hi + v; + return out; + } + + inline AABox operator-(const Vector3& v) const { + AABox out; + out.lo = lo - v; + out.hi = hi - v; + return out; + } + + void getBounds(AABox& out) const { + out = *this; + } +}; + +} + +template <> struct HashTrait { + static size_t hashCode(const G3D::AABox& key) { return key.hashCode(); } +}; + + + +#endif diff --git a/dep/g3dlite/G3D/Any.h b/dep/g3dlite/G3D/Any.h new file mode 100644 index 00000000000..49701202ca9 --- /dev/null +++ b/dep/g3dlite/G3D/Any.h @@ -0,0 +1,570 @@ +/** + @file Any.h + + @author Morgan McGuire, Shawn Yarbrough, and Corey Taylor + @maintainer Morgan McGuire + + @created 2006-06-11 + @edited 2009-12-16 + + Copyright 2000-2010, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_Any_h +#define G3D_Any_h + +#include "G3D/platform.h" +#include "G3D/Table.h" +#include "G3D/Array.h" +#include "G3D/AtomicInt32.h" +#include + +// needed for Token +#include "G3D/TextInput.h" + +#ifdef verify +#undef verify +#endif + +namespace G3D { + +class TextOutput; + +/** +\brief Easy loading and saving of human-readable configuration files. + +Encodes typed, structured data and can serialize it to a human +readable format that is very similar to the Python language's data +syntax. Well-suited for quickly creating human-readable file formats, +especially since deserialization and serialization preserve comments and +an Any can tell you what file and line it came from. + +The class is designed so that copying Anys generally is fast, even if +it is a large array or table. This is because data is shared between +copies until it is mutated, at which point an actual copy occurs. + +\section Example +Sample File: +
+{
+   shape = "round",
+
+   # in meters
+   radius = 3.7,
+
+   position = Vector3(1.0, -1.0, 0.0),
+   texture = { format = "RGB8", size = (320, 200)}
+}
+
+ +Sample code using: +
+Any x;
+x.load("ball.txt");
+if (x["shape"].string() == "round") {
+    x["density"] = 3;
+}
+x.save("ball.txt");
+
+ +The custom serialization format was chosen to be terse, easy for +humans to read, and easy for machines to parse. It was specifically +chosen over formats like XML, YAML, JSON, S-expressions, and Protocol +Buffers, although there is no reason you could not write readers and +writers for G3D::Any that support those. + +G3D::Any assumes that structures do not contain cycles; it is an +error to create a structure like: + +
+Any x(Any::ARRAY);
+x.array().append(x);    // don't do this!
+
+ +although no exception will be thrown at runtime during that append. + + +\section Parsing + +The primary use of Any is to create your own text file formats. +The Vector3 constructor is a good example of how to use the Any::verify +methods to provide good error checking while parsing such formats: + +
+Vector3::Vector3(const Any& any) {
+    any.verifyName("Vector3");
+    any.verifyType(Any::TABLE, Any::ARRAY);
+    any.verifySize(3);
+
+    if (any.type() == Any::ARRAY) {
+        x = any[0];
+        y = any[1];
+        z = any[2];
+    } else {
+        // Table
+        x = any["x"];
+        y = any["y"];
+        z = any["z"];
+    }
+}
+
+ +\section BNF +Serialized format BNF: + +
+identifier  ::= (letter | "_") (letter | digit | "_")*
+identifier-op ::= "::" | "->" | "."
+
+identifier-exp ::= [identifier-op] identifier (identifier-op identifier)*
+
+comment     ::= "#"  "\n"
+separator   ::= "," | ";"
+
+number      ::= 
+string      ::= 
+boolean     ::= "True" | "False"
+none        ::= "None"
+array       ::= "(" [value ("," value)*] ")"
+pair        ::= (identifier | string) "=" value
+table       ::= "{" [pair (separator pair)*] "}"
+named-array ::= identifier-exp tuple
+named-table ::= identifier-exp dict
+
+value       ::= [comment] (none | number | boolean | string | array | table | named-array | named-table)
+
+ +Except for single-line comments, whitespace is not significant. +All parsing is case-insensitive. + +The deserializer allows the substitution of [] for () when writing +tuples and ";" for ",". + +The serializer indents four spaces for each level of nesting. +Tables are written with the keys in alphabetic order. +*/ +class Any { +public: + + enum Type {NONE, BOOLEAN, NUMBER, STRING, ARRAY, TABLE}; + + static std::string toString(Type t); + + /** Where an Any came from in a file. Useful for throwing parsing errors */ + class Source { + public: + std::string filename; + int line; + int character; + + Source() : line(0), character(0) {} + + void set(const TextInput& ti, const Token& t) { + filename = ti.filename(); + line = t.line(); + character = t.character(); + } + }; + + typedef Array AnyArray; + typedef Table AnyTable; + +private: + + /** Called from deserialize() */ + static void deserializeComment(TextInput& ti, Token& token, std::string& comment); + + /** NONE, BOOLEAN, and NUMBER are stored directly in the Any */ + union SimpleValue { + bool b; + double n; + + inline SimpleValue() : n(0.0) {} + inline SimpleValue(bool x) : b(x) {} + inline SimpleValue(double x) : n(x) {} + }; + + class Data { + public: + /** ARRAY, TABLE, or STRING value only. NULL otherwise. */ + union Value { + std::string* s; + Array* a; + AnyTable* t; + inline Value() : s(NULL) {} + }; + + // Needed so that the destructor knows what is in Value + // and can call its destructor. + Type type; + + /** Always points to memory that is allocated with the Data, so + the destructor does not delete this. */ + Value value; + + std::string comment; + + std::string name; + + /** For STRING, ARRAY and TABLE types, m_value is shared between + multiple instances. Mutation is allowed only if the reference + count is exactly 1, otherwise the mutating instance must copy + the value. This is not used for other types. + */ + AtomicInt32 referenceCount; + + Source source; + + private: + + /** Called by create() */ + inline Data(Type t) : type(t), referenceCount(1) {} + + /** Called by destroy */ + ~Data(); + + public: + + /** Clones the argument */ + static Data* create(const Data* d); + static Data* create(Type t); + + /** Free d, invoking its destructor and freeing the memory for + the value. */ + static void destroy(Data* d); + + }; + + /** If not empty, this Any was created from operator[] on a table + and perhaps was not intended to exist. The name is needed to + format the error message if it is read from before it is + written to. + + The source of a placeholder object is that of the parent + object until it is written. + */ + std::string m_placeholderName; + + Type m_type; + SimpleValue m_simpleValue; + mutable Data* m_data; + + /** Called before every read operation to ensure that this object + is not a placeholder. */ + void beforeRead() const; + + /** Called before every write operation to wipe the placeholder + status. */ + void beforeWrite(); + + /** Decrements the reference count (if there is one). If the + reference count is zero after decrement, calls delete on @a m_data + and sets it to NULL. + */ + void dropReference(); + + /** Allocate the Data object if it does not exist */ + void ensureData(); + + /** If m_data is not NULL, ensure that it has a unique reference + and contains a valid m_data. This has a race condition if two + threads are both trying to modify the same Any + simultaneously.*/ + void ensureMutable(); + + /** Read an unnamed a TABLE or ARRAY. Token should be the open + paren token; it is the next token after the close on + return. Called from deserialize().*/ + void deserializeBody(TextInput& ti, Token& token); + + void deserialize(TextInput& ti, Token& token); + + /** Read the name of a named Array or Table. */ + static void deserializeName(TextInput& ti, Token& token, std::string& name); + + /** Read until a comma is consumed or a close paren is hit, and + return that token. Considers the passed in token to be the first + value read. */ + static void readUntilCommaOrClose(TextInput& ti, Token& token); + + /** Construct an Any that is a proxy for a table fetch from \a data. + This proxy can be copied exactly once on return from operator[].*/ + Any(const std::string& key, Data* data); + + inline bool isPlaceholder() const { + return ! m_placeholderName.empty(); + } + +public: + + /** Base class for all Any exceptions.*/ + class Exception { + public: + virtual ~Exception() {} + }; + + /** Thrown by operator[] when a key is not present in a const table. */ + class KeyNotFound : public ParseError { + public: + std::string key; + }; + + /** Thrown by operator[] when an array index is not present. */ + class IndexOutOfBounds : public Exception { + public: + int index; + int size; + inline IndexOutOfBounds() : index(0), size(0) {} + inline IndexOutOfBounds(int i, int s) : index(i), size(s) {} + }; + + /** NONE constructor */ + Any(); + + /** Deserialize */ + explicit Any(TextInput& t); + + Any(const Any& x); + + /** NUMBER constructor */ + Any(double x); + +#ifdef G3D_32BIT + /** NUMBER constructor */ + Any(int64 x); +#endif // G3D_32BIT + +#if 0 + /** NUMBER constructor */ + Any(int32 x); +#endif // 0 + + /** NUMBER constructor */ + Any(long x); + + /** NUMBER constructor */ + Any(int x); + + /** NUMBER constructor */ + Any(short x); + + /** BOOLEAN constructor */ + Any(bool x); + + /** STRING constructor */ + Any(const std::string& x); + + /** STRING constructor */ + Any(const char* x); + + /** \a t must be ARRAY or TABLE */ + Any(Type t, const std::string& name = ""); + + ~Any(); + + /** Removes the comment and name */ + Any& operator=(const Any& x); + + /** Removes the comment and name */ + Any& operator=(double x); + + /** Removes the comment and name */ + Any& operator=(int x); + + /** Removes the comment and name */ + Any& operator=(bool x); + + /** Removes the comment and name */ + Any& operator=(const std::string& x); + + /** Removes the comment and name */ + Any& operator=(const char* x); + + /** \a t must be ARRAY, TABLE, or NONE. Removes the comment and name */ + Any& operator=(Type t); + + Type type() const; + + /** Same as deserialize or load, but operates on a string instead + of a stream or file. + + \sa deserialize, load + */ + void parse(const std::string& src); + + std::string unparse() const; + + /** Comments appear before values when they are in serialized form.*/ + const std::string& comment() const; + void setComment(const std::string& c); + + /** True if this is the NONE value */ + bool isNone() const; + + /** Throws a ParseError exception if this is not a number */ + double number() const; + const std::string& string() const; + bool boolean() const; + + /** If this is named ARRAY or TABLE, returns the name. */ + const std::string& name() const; + + /** \brief Set the name used when serializing an ARRAY or TABLE. + + Only legal for ARRAY or TABLE. The \a name must begin with a letter + and contain only letters, numbers, underscores and scope operators. + +
+        a2z
+        hello
+        Foo::bar
+        color.red
+        this->that
+        __x
+        
+ + + The scope operators "::", "->", and + ".", may have spaces around them. The name may not + contain parentheses. + */ + void setName(const std::string& name); + + /** Number of elements if this is an ARRAY or TABLE */ + int size() const; + int length() const; + + /** For an array, returns the ith element */ + const Any& operator[](int i) const; + Any& operator[](int i); + + /** Directly exposes the underlying data structure for an ARRAY. */ + const Array& array() const; + void append(const Any& v0); + void append(const Any& v0, const Any& v1); + void append(const Any& v0, const Any& v1, const Any& v2); + void append(const Any& v0, const Any& v1, const Any& v2, const Any& v3); + + /** Directly exposes the underlying data structure for table.*/ + const Table& table() const; + + /** For a table, returns the element for \a key. Throws KeyNotFound + exception if the element does not exist. + */ + const Any& operator[](const std::string& key) const; + + // Needed to prevent the operator[](int) overload from catching + // string literals + inline const Any& operator[](const char* key) const { + return operator[](std::string(key)); + } + + /** + Fetch an element from a table. This can be used as: + +
+        a["key"] = value;  (create the key if it did not exist)
+        
+ + or + +
+        value = a["key"];  (throw an error if the key did not exist)
+        
+ + Note: + In order to cause elements to be correctly created in the + first case while still providing "key not found" errors in the + second case, the Any returned is a special object that delays + the actual fetch until the following assignment or method + call. This means that in the event of an error, the exception + may be thrown from a line other than the actual fetch. Use + the Any::get() or the const Any::operator[]() methods to avoid + this behavior and ensure error-checking at fetch time. + */ + Any& operator[](const std::string& key); + + /** \copydoc Any::operator[](const std::string&) */ + inline Any& operator[](const char* key) { + return operator[](std::string(key)); + } + + /** For a table, returns the element for key \a x and \a + defaultVal if it does not exist. */ + const Any& get(const std::string& key, const Any& defaultVal) const; + + /** Returns true if this key is in the TABLE. Illegal to call on an object that is not a TABLE. */ + bool containsKey(const std::string& key) const; + + /** For a table, assigns the element for key k. */ + void set(const std::string& key, const Any& val); + + /** for an ARRAY, resizes and returns the last element */ + Any& next(); + + + /** True if the Anys are exactly equal, ignoring comments. Applies deeply on arrays and tables. */ + bool operator==(const Any& x) const; + bool operator!=(const Any& x) const; + + operator int() const; + operator float() const; + operator double() const; + operator bool() const; + operator std::string() const; + + /** Resize to \a n elements, where new elements are NIL + It is an error to call this method if this is not an Any::ARRAY */ + void resize(int n); + + /** + Clears all entries. + This must be a TABLE or ARRAY */ + void clear(); + + /** Parse from a file. + \sa deserialize, parse */ + void load(const std::string& filename); + + /** Uses the serialize method. */ + void save(const std::string& filename) const; + + void serialize(TextOutput& to) const; + /** Parse from a stream. + \sa load, parse */ + void deserialize(TextInput& ti); + + const Source& source() const; + + /** Throws a ParseError if \a value is false. Useful for quickly + creating parse rules in classes that deserialize from Any. + */ + void verify(bool value, const std::string& message = "") const; + + /** Verifies that the name begins with identifier \a n. It may contain + identifier operators after this */ + void verifyName(const std::string& n) const; + + /** Verifies that the type is \a t. */ + void verifyType(Type t) const; + + /** Throws an exception if the type is not \a t0 or \a t1. */ + void verifyType(Type t0, Type t1) const; + + /** Verifies that the size is between \a low and \a high, inclusive */ + void verifySize(int low, int high) const; + + /** Verifies that the size is exactly \a s */ + void verifySize(int s) const; + +private: + + void deserializeTable(TextInput& ti); + void deserializeArray(TextInput& ti,const std::string& term); + +}; // class Any + +} // namespace G3D + +#endif diff --git a/dep/g3dlite/G3D/AnyVal.h b/dep/g3dlite/G3D/AnyVal.h new file mode 100644 index 00000000000..8c1bc72f206 --- /dev/null +++ b/dep/g3dlite/G3D/AnyVal.h @@ -0,0 +1,512 @@ +/** + @file AnyVal.h + @author Morgan McGuire + @created 2006-06-11 + @edited 2008-07-14 + */ + +#ifndef G3D_ANYVAL_H +#define G3D_ANYVAL_H + +#include "G3D/platform.h" +#include +#include "G3D/Array.h" +#include "G3D/TextInput.h" + +namespace G3D { +// Forward declarations for G3D types +class Vector2; +class Vector3; +class Vector4; +class Color1; +class Color3; +class Color4; +class Quat; +class Matrix2; +class Matrix3; +class Matrix4; +class CoordinateFrame; +class TextInput; +class TextOutput; +class BinaryInput; +class BinaryOutput; +class Rect2D; +class AABox; + +/** + \deprecated + Use the G3D::Any class instead. This is only provided for + backwards compatibility to G3D 7.xx. + + A generic value, useful for defining property trees that can + be loaded from and saved to disk. The values are intentionally + restricted to a small set. + + When written to files, the syntax is as follows. Note that you can + nest arrays and tables in order to create full tree (i.e., XML-like) + structures as configuration files: + + + + + + + + + + + + + + + + + + + + + + + +
NULLNil
doubleThe number in printf double format
booltrue or false
std::stringThe string in double-quotes (")
Rect2DR(x0,y0,x1,y1)
Color1C1(value)
Color3C3(r,g,b)
Color4C4(r,g,b,a)
Vector2V2(x,y)
Vector3V3(x,y,z)
Vector4V4(x,y,z,w)
QuatV(x,y,z,w)
AABoxAAB(low Vector3, high Vector3)
Matrix2M2(r0c0, r0c1, +
   
r1c0, r1c1)
Matrix3M3(r0c0, r0c1, r0c2, +
   
r1c0, r1c1, r1c2, +
   
r2c0, r2c1, r2c2)
Matrix4M4(r0c0, r0c1, r0c2, r0c3, +
   
r1c0, r1c1, r1c2, r1c3, +
   
r2c0, r2c1, r2c2, r2c3, +
   
r3c0, r3c1, r3c2, r3c3)
CoordinateFrameCF(r0c0, r0c1, r0c2, r0c3, +
   
r1c0, r1c1, r1c2, r1c3, +
   
r2c0, r2c1, r2c2, r2c3)
CoordinateFrameCF(V3(x, y, z), yaw deg, pitch deg, optional roll deg)
Array[element0, element1, ... , elementn-1]
Table{symbol0 = value0 +
 symbol1 = value1 +
 ... +
 symboln-1 = valuen-1}
+ + See also boost::any for a more general purpose but slightly harder to use + "any" for C++. + + The semantics of operator[] and the get() methods are slightly different; + operator[] acts more like a scripting language that automatically extends + arrays and tables instead of generating errors. get() has more strict semantics, + like a C++ class. + + AnyVal uses copy-on-mutate, so that AnyVal a = b semantically copies b (like int a = b would), although in practice + it delays the copy until one is mutated so that it is still fast to "copy" large arrays and tables. + + Reading example: +
+    AnyVal property = AnyVal::fromFile("c:/tmp/test.txt"));
+
+    Vector3 vel = property["angular velocity"]
+
+    Using defaults to handle errors:
+       If there was no "enabled" value, this will return the default instead of failing
+    bool enabled = property["enabled"].boolean(true);
+
+ 
+ + Writing to a file: +
+    AnyVal dict(AnyVal::TABLE);
+
+    dict["enabled"] = AnyVal(true);
+    dict["weight"] = 100;
+    dict["angular velocity"] = Vector3(1, -3, 4.5);
+
+    TextOutput t("c:/tmp/test.txt");
+    dict.serialize(t);
+    t.commit();
+  
+ + Example of a data file: +
+   {
+      heights = [1, 17, 32]
+      model = 
+        {
+           color = C3(1, 1, 1)
+           filename = "foo.md2"
+        }
+      position = V3(23, 14, 0)
+      name = "Elmer"
+   }
+  
+ +

+ What's the difference from boost::any? +
I think that AnyVal will be easier for novice C++ users. It addresses the problem that + even though G3D::TextInput makes reading configuration files extremely simple, many people + still don't use it. So AnyVal makes it ridiculously simple to read and write a tree of G3D + types to a file. + + AnyVal: +

+{
+AnyVal tree(TextInput("config.txt"));
+
+bool enabled = tree.get("enabled", false);
+Vector3 direction = tree.get("direction", Vector3::zero());
+...
+}
+
+ +boost: +
+{
+bool enabled = false;
+Vector3 direction;
+Table tree;
+
+ ...write lots of file parsing code...
+
+   if (tree.containsKey("enabled")) {
+      const boost::any& val = tree["enabled"];
+      try {
+        enabled = any_cast(val);
+      } catch(const boost::bad_any_cast &) {
+      }
+    }
+
+   if (tree.containsKey("direction")) {
+      const boost::any& val = tree["direction"];
+      try {
+        direction = any_cast(val);
+      } catch(const boost::bad_any_cast &) {
+      }
+    }
+   ...
+}
+
+ +\deprecated + */ +class AnyVal { +public: + + /** Array and table values are all Any.*/ + enum Type { + NIL, + NUMBER, + BOOLEAN, + STRING, + VECTOR2, + VECTOR3, + VECTOR4, + MATRIX2, + MATRIX3, + MATRIX4, + QUAT, + COORDINATEFRAME, + COORDINATEFRAME2D, + CFRAME = COORDINATEFRAME, + CFRAME2D = COORDINATEFRAME2D, + COLOR1, + COLOR3, + COLOR4, + RECT2D, + AABOX2D = RECT2D, + AABOX, + ARRAY, + TABLE}; + + /** Base class for all AnyVal exceptions.*/ + class Exception { + public: + virtual ~Exception() {} + }; + + /** Thrown when an inappropriate operation is performed (e.g., operator[] on a number) */ + class WrongType : public Exception { + public: + Type expected; + Type actual; + WrongType() : expected(NIL), actual(NIL) {} + WrongType(Type e, Type a) : expected(e), actual(a) {} + }; + + /** Thrown by operator[] when a key is not present. */ + class KeyNotFound : public Exception { + public: + std::string key; + KeyNotFound() {} + KeyNotFound(const std::string& k) : key(k) {} + }; + + class IndexOutOfBounds : public Exception { + public: + int index; + int size; + IndexOutOfBounds() : index(0), size(0) {} + IndexOutOfBounds(int i, int s) : index(i), size(s) {} + }; + + /** Thrown when deserialize() when the input is incorrectly formatted. */ + class CorruptText : public Exception { + public: + std::string message; + + /** Token where the problem occurred.*/ + G3D::Token token; + + CorruptText() {} + CorruptText(const std::string& s, const G3D::Token& t) : message(s), token(t) {} + }; + +private: + + Type m_type; + void* m_value; + + /** For table and array types, *m_value is shared between multiple + instances. Mutation is allowed only if the reference count is + exactly 1, otherwise the mutating instance must copy the + value. This is not used for other types. + */ + int* m_referenceCount; + + /** Decrements the reference count (if there is one). If the + reference count is zero or does not exist. Calls delete on @a + m_value and sets it to NULL. + */ + void deleteValue(); + + /** Returns a copy of the value. */ + void* copyValue() const; + + /** Assumes isSharedType. Ensures that this has a unique reference */ + void makeMutable(); + + /** True if this is a shared value between multiple instances. */ + inline bool isShared() const { + return m_referenceCount && (*m_referenceCount > 1); + } + + /** True when m_value is a double pointer */ + inline bool isSharedType() const { + return (m_type == TABLE) || (m_type == ARRAY); + } + +public: + + AnyVal(); + + /** Deserialize */ + explicit AnyVal(G3D::TextInput& t); + + static AnyVal fromFile(const std::string& filename); + + void load(const std::string& filename); + + void save(const std::string& filename) const; + + ///** Deserialize */ + //explicit AnyVal(G3D::BinaryInput& t); + + /** Construct a number */ + AnyVal(double); + AnyVal(int); + + // Explicit to avoid ambiguity with the 'double' constructor + // when an integer type is constructed + AnyVal(bool); + AnyVal(const G3D::Vector2&); + AnyVal(const G3D::Vector3&); + AnyVal(const G3D::Vector4&); + + AnyVal(const G3D::Color1&); + AnyVal(const G3D::Color3&); + AnyVal(const G3D::Color4&); + + AnyVal(const std::string&); + AnyVal(const char*); + + AnyVal(const G3D::Quat&); + + AnyVal(const G3D::Rect2D&); + AnyVal(const G3D::AABox&); + + AnyVal(const G3D::CoordinateFrame&); + AnyVal(const G3D::Matrix2&); + AnyVal(const G3D::Matrix3&); + AnyVal(const G3D::Matrix4&); + + AnyVal(const AnyVal&); + + AnyVal(Type arrayOrTable); + + AnyVal& operator=(const AnyVal&); + + /** Frees the underlying storage */ + ~AnyVal(); + + Type type() const; + + bool isNil() const { + return type() == NIL; + } + + void serialize(G3D::TextOutput& t) const; + //void serialize(G3D::BinaryOutput& t) const; + void deserialize(G3D::TextInput& t); + //void deserialize(G3D::BinaryInput& t); + + /** Array dereference. If the index is out of bounds, IndexOutOfBounds is thrown */ + const AnyVal& operator[](int) const; + + /** Extend this array by one element. */ + void append(const AnyVal&); + + /** If the index is out of bounds, the array is resized. If the index is negative, + IndexOutOfBounds is thrown.*/ + AnyVal& operator[](int); + + /** If @a i is out of bounds or this is not an ARRAY, defaultVal is returned.*/ + const AnyVal& get(int i, const AnyVal& defaultVal) const; + + /** If out of bounds, IndexOutOfBounds is thrown. */ + const AnyVal& get(int i) const; + + /** Returns defaultVal if this is not a TABLE or the key is not found. */ + const AnyVal& get(const std::string& key, const AnyVal& defaultVal) const; + + /** Throws KeyNotFound exception if the key is not present.*/ + const AnyVal& get(const std::string& key) const; + + /** Table reference */ + const AnyVal& operator[](const std::string&) const; + + /** Table reference. If the element does not exist, it is created. */ + AnyVal& operator[](const std::string&); + + /** Table reference */ + const AnyVal& operator[](const char*) const; + + /** Table reference. If the element does not exist, it is created. */ + AnyVal& operator[](const char*); + + /** If this value is not a number throws a WrongType exception. */ + double number() const; + + /** If this value is not a number, returns defaultVal. */ + double number(double defaultVal) const; + + operator double () const { + return number(); + } + + operator float () const { + return (float)number(); + } + + bool boolean() const; + bool boolean(bool b) const; + + operator bool() const { + return boolean(); + } + + const std::string& string() const; + const std::string& string(const std::string& defaultVal) const; + + operator const std::string& () const { + return string(); + } + + const G3D::Rect2D& rect2D() const; + const G3D::Rect2D& rect2D(const G3D::Rect2D& defaultVal) const; + + operator const Rect2D& () const { + return rect2D(); + } + + const G3D::AABox& aabox() const; + const G3D::AABox& aabox(const G3D::AABox& defaultVal) const; + + operator const AABox& () const { + return aabox(); + } + + const G3D::Vector2& vector2() const; + const G3D::Vector2& vector2(const G3D::Vector2& defaultVal) const; + + operator const Vector2& () const { + return vector2(); + } + + const G3D::Vector3& vector3() const; + const G3D::Vector3& vector3(const G3D::Vector3& defaultVal) const; + + operator const Vector3& () { + return vector3(); + } + + const G3D::Vector4& vector4() const; + const G3D::Vector4& vector4(const G3D::Vector4& defaultVal) const; + + operator const Vector4& () const { + return vector4(); + } + + const G3D::Color1& color1() const; + const G3D::Color1& color1(const G3D::Color1& defaultVal) const; + + const G3D::Color3& color3() const; + const G3D::Color3& color3(const G3D::Color3& defaultVal) const; + + operator const Color3& () const { + return color3(); + } + + const G3D::Color4& color4() const; + const G3D::Color4& color4(const G3D::Color4& defaultVal) const; + + operator const Color4& () const { + return color4(); + } + + const G3D::CoordinateFrame& coordinateFrame() const; + const G3D::CoordinateFrame& coordinateFrame(const G3D::CoordinateFrame& defaultVal) const; + + operator const CoordinateFrame& () const { + return coordinateFrame(); + } + + const G3D::Matrix2& matrix2() const; + const G3D::Matrix2& matrix2(const G3D::Matrix2& defaultVal) const; + + operator const Matrix2& () const { + return matrix2(); + } + + const G3D::Matrix3& matrix3() const; + const G3D::Matrix3& matrix3(const G3D::Matrix3& defaultVal) const; + + operator const Matrix3& () const { + return matrix3(); + } + + const G3D::Matrix4& matrix4() const; + const G3D::Matrix4& matrix4(const G3D::Matrix4& defaultVal) const; + + operator const Matrix4& () const { + return matrix4(); + } + + const G3D::Quat& quat() const; + const G3D::Quat& quat(const G3D::Quat& defaultVal) const; + + operator const Quat& () const { + return quat(); + } + + std::string toString() const; + + /** Number of elements for an array or table.*/ + int size() const; + + /** For a table, returns the keys. */ + void getKeys(G3D::Array&) const; +}; + +} + +#endif diff --git a/dep/g3dlite/G3D/AreaMemoryManager.h b/dep/g3dlite/G3D/AreaMemoryManager.h new file mode 100644 index 00000000000..d8d8f710359 --- /dev/null +++ b/dep/g3dlite/G3D/AreaMemoryManager.h @@ -0,0 +1,93 @@ +/** + @file AreaMemoryManager.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2009-01-20 + @edited 2009-05-29 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ + + +#ifndef G3D_AreaMemoryManager_h +#define G3D_AreaMemoryManager_h + +#include "G3D/platform.h" +#include "G3D/g3dmath.h" +#include "G3D/Array.h" +#include "G3D/MemoryManager.h" + +namespace G3D { + +/** + \brief Allocates memory in large blocks and then frees it as an area. + + Useful for ensuring cache coherence and for reducing the time cost of + multiple allocations and deallocations. + + Not threadsafe + */ +class AreaMemoryManager : public MemoryManager { +private: + + class Buffer { + private: + uint8* m_first; + size_t m_size; + size_t m_used; + + public: + + Buffer(size_t size); + + ~Buffer(); + + /** Returns NULL if out of space */ + void* alloc(size_t s); + }; + + size_t m_sizeHint; + + /** The underlying array is stored in regular MemoryManager heap memory */ + Array m_bufferArray; + + AreaMemoryManager(size_t sizeHint); + +public: + + typedef ReferenceCountedPointer Ref; + + /** + \param sizeHint Total amount of memory expected to be allocated. + The allocator will allocate memory from the system in increments + of this size. + */ + static AreaMemoryManager::Ref create(size_t sizeHint = 10 * 1024 * 1024); + + /** Invokes deallocateAll. */ + ~AreaMemoryManager(); + + size_t bytesAllocated() const; + + /** Allocates memory out of the buffer pool. + @param s must be no larger than sizeHint */ + virtual void* alloc(size_t s); + + /** Ignored. */ + virtual void free(void* x); + + virtual bool isThreadsafe() const; + + /** Deletes all previously allocated memory. Because delete is not + invoked on objects in this memory, it is not safe to simply + free memory containing C++ objects that expect their destructors + to be called. */ + void deallocateAll(); +}; + +typedef AreaMemoryManager CoherentAllocator; +} + +#endif diff --git a/dep/g3dlite/G3D/Array.h b/dep/g3dlite/G3D/Array.h new file mode 100644 index 00000000000..cc9e1d9dd01 --- /dev/null +++ b/dep/g3dlite/G3D/Array.h @@ -0,0 +1,1274 @@ +/** + @file Array.h + + @maintainer Morgan McGuire, graphics3d.com + @cite Portions written by Aaron Orenstein, a@orenstein.name + + @created 2001-03-11 + @edited 2009-05-29 + + Copyright 2000-2009, Morgan McGuire, http://graphics.cs.williams.edu + All rights reserved. + */ + +#ifndef G3D_Array_h +#define G3D_Array_h + +#include "G3D/platform.h" +#include "G3D/debug.h" +#include "G3D/System.h" +#include "G3D/MemoryManager.h" +#ifdef G3D_DEBUG +// For formatting error messages +# include "G3D/format.h" +#endif +#include +#include + +#ifdef _MSC_VER +# include + +# pragma warning (push) + // debug information too long +# pragma warning( disable : 4312) +# pragma warning( disable : 4786) +#endif + + +namespace G3D { + +/** + Constant for passing to Array::resize + */ +const bool DONT_SHRINK_UNDERLYING_ARRAY = false; + +/** Constant for Array::sort */ +const int SORT_INCREASING = 1; +/** Constant for Array::sort */ +const int SORT_DECREASING = -1; + +/** + \brief Dynamic 1D array tuned for performance. + + Objects must have a default constructor (constructor that + takes no arguments) in order to be used with this template. + You will get the error "no appropriate default constructor found" + if they do not. + + Do not use with objects that overload placement operator new, + since the speed of Array is partly due to pooled allocation. + + Array is highly optimized compared to std::vector. + Array operations are less expensive than on std::vector and for large + amounts of data, Array consumes only 1.5x the total size of the + data, while std::vector consumes 2.0x. The default + array takes up zero heap space. The first resize (or append) + operation grows it to a reasonable internal size so it is efficient + to append to small arrays. + + Then Array needs to copy + data internally on a resize operation it correctly invokes copy + constructors of the elements (the MSVC6 implementation of + std::vector uses realloc, which can create memory leaks for classes + containing references and pointers). Array provides a guaranteed + safe way to access the underlying data as a flat C array -- + Array::getCArray. Although (T*)std::vector::begin() can be used for + this purpose, it is not guaranteed to succeed on all platforms. + + To serialize an array, see G3D::serialize. + + The template parameter MIN_ELEMENTS indicates the smallest number of + elements that will be allocated. The default of 10 is designed to avoid + the overhead of repeatedly allocating the array as it grows from 1, to 2, and so on. + If you are creating a lot of small Arrays, however, you may want to set this smaller + to reduce the memory cost. Once the array has been allocated, it will never + deallocate the underlying array unless MIN_ELEMENTS is set to 0, MIN_BYTES is 0, and the array + is empty. + + Do not subclass an Array. + + \sa G3D::SmallArray + */ +template +class Array { +private: + /** 0...num-1 are initialized elements, num...numAllocated-1 are not */ + T* data; + + int num; + int numAllocated; + + MemoryManager::Ref m_memoryManager; + + /** \param n Number of elements + */ + void init(int n, const MemoryManager::Ref& m) { + m_memoryManager = m; + debugAssert(n >= 0); + this->num = 0; + this->numAllocated = 0; + data = NULL; + if (n > 0) { + resize(n); + } else { + data = NULL; + } + } + + void _copy(const Array &other) { + init(other.num, MemoryManager::create()); + for (int i = 0; i < num; i++) { + data[i] = other.data[i]; + } + } + + /** + Returns true iff address points to an element of this array. + Used by append. + */ + inline bool inArray(const T* address) { + return (address >= data) && (address < data + num); + } + + + /** Only compiled if you use the sort procedure. */ + static bool __cdecl compareGT(const T& a, const T& b) { + return a > b; + } + + + /** + Allocates a new array of size numAllocated (not a parameter to the method) + and then copies at most oldNum elements from the old array to it. Destructors are + called for oldNum elements of the old array. + */ + void realloc(int oldNum) { + T* oldData = data; + + // The allocation is separate from the constructor invocation because we don't want + // to pay for the cost of constructors until the newly allocated + // elements are actually revealed to the application. They + // will be constructed in the resize() method. + + data = (T*)m_memoryManager->alloc(sizeof(T) * numAllocated); + alwaysAssertM(data, "Memory manager returned NULL: out of memory?"); + + // Call the copy constructors + {const int N = G3D::min(oldNum, numAllocated); + const T* end = data + N; + T* oldPtr = oldData; + for (T* ptr = data; ptr < end; ++ptr, ++oldPtr) { + + // Use placement new to invoke the constructor at the location + // that we determined. Use the copy constructor to make the assignment. + const T* constructed = new (ptr) T(*oldPtr); + + (void)constructed; + debugAssertM(constructed == ptr, + "new returned a different address than the one provided by Array."); + }} + + // Call destructors on the old array (if there is no destructor, this will compile away) + {const T* end = oldData + oldNum; + for (T* ptr = oldData; ptr < end; ++ptr) { + ptr->~T(); + }} + + m_memoryManager->free(oldData); + } + +public: + + /** + G3D C++ STL style iterator variable. Call begin() to get + the first iterator, pre-increment (++i) the iterator to get to + the next value. Use dereference (*i) to access the element. + */ + typedef T* Iterator; + /** G3D C++ STL style const iterator in same style as Iterator. */ + typedef const T* ConstIterator; + + /** stl porting compatibility helper */ + typedef Iterator iterator; + /** stl porting compatibility helper */ + typedef ConstIterator const_iterator; + /** stl porting compatibility helper */ + typedef T value_type; + /** stl porting compatibility helper */ + typedef int size_type; + /** stl porting compatibility helper */ + typedef int difference_type; + + /** + C++ STL style iterator method. Returns the first iterator element. + Do not change the size of the array while iterating. + */ + Iterator begin() { + return data; + } + + ConstIterator begin() const { + return data; + } + /** + C++ STL style iterator method. Returns one after the last iterator + element. + */ + ConstIterator end() const { + return data + num; + } + + Iterator end() { + return data + num; + } + + /** + The array returned is only valid until the next append() or resize call, or + the Array is deallocated. + */ + T* getCArray() { + return data; + } + + /** + The array returned is only valid until the next append() or resize call, or + the Array is deallocated. + */ + const T* getCArray() const { + return data; + } + + /** Creates a zero length array (no heap allocation occurs until resize). */ + Array() : num(0) { + init(0, MemoryManager::create()); + debugAssert(num >= 0); + } + + + /** Creates an array containing v0. */ + Array(const T& v0) { + init(1, MemoryManager::create()); + (*this)[0] = v0; + } + + /** Creates an array containing v0 and v1. */ + Array(const T& v0, const T& v1) { + init(2, MemoryManager::create()); + (*this)[0] = v0; + (*this)[1] = v1; + } + + /** Creates an array containing v0...v2. */ + Array(const T& v0, const T& v1, const T& v2) { + init(3, MemoryManager::create()); + (*this)[0] = v0; + (*this)[1] = v1; + (*this)[2] = v2; + } + + /** Creates an array containing v0...v3. */ + Array(const T& v0, const T& v1, const T& v2, const T& v3) { + init(4, MemoryManager::create()); + (*this)[0] = v0; + (*this)[1] = v1; + (*this)[2] = v2; + (*this)[3] = v3; + } + + /** Creates an array containing v0...v4. */ + Array(const T& v0, const T& v1, const T& v2, const T& v3, const T& v4) { + init(5, MemoryManager::create()); + (*this)[0] = v0; + (*this)[1] = v1; + (*this)[2] = v2; + (*this)[3] = v3; + (*this)[4] = v4; + } + + + /** + Copy constructor + */ + Array(const Array& other) : num(0) { + _copy(other); + debugAssert(num >= 0); + } + + /** + Destructor does not delete() the objects if T is a pointer type + (e.g. T = int*) instead, it deletes the pointers themselves and + leaves the objects. Call deleteAll if you want to dealocate + the objects referenced. Do not call deleteAll if T is not a pointer + type (e.g. do call Array::deleteAll, do not call Array::deleteAll). + */ + ~Array() { + // Invoke the destructors on the elements + for (int i = 0; i < num; i++) { + (data + i)->~T(); + } + + m_memoryManager->free(data); + // Set to 0 in case this Array is global and gets referenced during app exit + data = NULL; + num = 0; + numAllocated = 0; + } + + /** + Removes all elements. Use resize(0, false) or fastClear if you want to + remove all elements without deallocating the underlying array + so that future append() calls will be faster. + */ + void clear(bool shrink = true) { + resize(0, shrink); + } + + void clearAndSetMemoryManager(const MemoryManager::Ref& m) { + clear(); + debugAssert(data == NULL); + m_memoryManager = m; + } + + /** resize(0, false) + @deprecated*/ + void fastClear() { + clear(false); + } + + /** + Assignment operator. + */ + Array& operator=(const Array& other) { + debugAssert(num >= 0); + resize(other.num); for (int i = 0; i < num; ++i) { + data[i] = other[i]; + } + debugAssert(num >= 0); + return *this; + } + + Array& operator=(const std::vector& other) { + resize((int)other.size()); + for (int i = 0; i < num; ++i) { + data[i] = other[i]; + } + return *this; + } + + inline MemoryManager::Ref memoryManager() const { + return m_memoryManager; + } + + /** + Number of elements in the array. + */ + inline int size() const { + return num; + } + + /** + Number of elements in the array. (Same as size; this is just + here for convenience). + */ + inline int length() const { + return size(); + } + + /** + Swaps element index with the last element in the array then + shrinks the array by one. + */ + void fastRemove(int index, bool shrinkIfNecessary = false) { + debugAssert(index >= 0); + debugAssert(index < num); + data[index] = data[num - 1]; + resize(size() - 1, shrinkIfNecessary); + } + + + /** + Inserts at the specified index and shifts all other elements up by one. + */ + void insert(int n, const T& value) { + // Add space for the extra element + resize(num + 1, false); + + for (int i = num - 1; i > n; --i) { + data[i] = data[i - 1]; + } + data[n] = value; + } + + /** @param shrinkIfNecessary if false, memory will never be + reallocated when the array shrinks. This makes resizing much + faster but can waste memory. + */ + void resize(int n, bool shrinkIfNecessary = true) { + debugAssert(n >= 0); + if (num == n) { + return; + } + + int oldNum = num; + num = n; + + // Call the destructors on newly hidden elements if there are any + for (int i = num; i < oldNum; ++i) { + (data + i)->~T(); + } + + // Once allocated, always maintain MIN_ELEMENTS elements or 32 bytes, whichever is higher. + const int minSize = std::max(MIN_ELEMENTS, (int)(MIN_BYTES / sizeof(T))); + + if ((MIN_ELEMENTS == 0) && (MIN_BYTES == 0) && (n == 0) && shrinkIfNecessary) { + // Deallocate the array completely + numAllocated = 0; + m_memoryManager->free(data); + data = NULL; + return; + } + + if (num > numAllocated) { + // Grow the underlying array + + if (numAllocated == 0) { + // First allocation; grow to exactly the size requested to avoid wasting space. + numAllocated = n; + debugAssert(oldNum == 0); + realloc(oldNum); + } else { + + if (num < minSize) { + // Grow to at least the minimum size + numAllocated = minSize; + + } else { + + // Increase the underlying size of the array. Grow aggressively + // up to 64k, less aggressively up to 400k, and then grow relatively + // slowly (1.5x per resize) to avoid excessive space consumption. + // + // These numbers are tweaked according to performance tests. + + float growFactor = 3.0; + + int oldSizeBytes = numAllocated * sizeof(T); + if (oldSizeBytes > 400000) { + // Avoid bloat + growFactor = 1.5; + } else if (oldSizeBytes > 64000) { + // This is what std:: uses at all times + growFactor = 2.0; + } + + numAllocated = (num - numAllocated) + (int)(numAllocated * growFactor); + + if (numAllocated < minSize) { + numAllocated = minSize; + } + } + + realloc(oldNum); + } + + } else if ((num <= numAllocated / 3) && shrinkIfNecessary && (num > minSize)) { + // Shrink the underlying array + + // Only copy over old elements that still remain after resizing + // (destructors were called for others if we're shrinking) + realloc(iMin(num, oldNum)); + + } + + // Call the constructors on newly revealed elements. + // Do not use parens because we don't want the intializer + // invoked for POD types. + for (int i = oldNum; i < num; ++i) { + new (data + i) T; + } + } + + /** + Add an element to the end of the array. Will not shrink the underlying array + under any circumstances. It is safe to append an element that is already + in the array. + */ + inline void append(const T& value) { + + if (num < numAllocated) { + // This is a simple situation; just stick it in the next free slot using + // the copy constructor. + new (data + num) T(value); + ++num; + } else if (inArray(&value)) { + // The value was in the original array; resizing + // is dangerous because it may move the value + // we have a reference to. + T tmp = value; + append(tmp); + } else { + // Here we run the empty initializer where we don't have to, but + // this simplifies the computation. + resize(num + 1, DONT_SHRINK_UNDERLYING_ARRAY); + data[num - 1] = value; + } + } + + + inline void append(const T& v1, const T& v2) { + if (inArray(&v1) || inArray(&v2)) { + // Copy into temporaries so that the references won't break when + // the array resizes. + T t1 = v1; + T t2 = v2; + append(t1, t2); + } else if (num + 1 < numAllocated) { + // This is a simple situation; just stick it in the next free slot using + // the copy constructor. + new (data + num) T(v1); + new (data + num + 1) T(v2); + num += 2; + } else { + // Resize the array. Note that neither value is already in the array. + resize(num + 2, DONT_SHRINK_UNDERLYING_ARRAY); + data[num - 2] = v1; + data[num - 1] = v2; + } + } + + + inline void append(const T& v1, const T& v2, const T& v3) { + if (inArray(&v1) || inArray(&v2) || inArray(&v3)) { + T t1 = v1; + T t2 = v2; + T t3 = v3; + append(t1, t2, t3); + } else if (num + 2 < numAllocated) { + // This is a simple situation; just stick it in the next free slot using + // the copy constructor. + new (data + num) T(v1); + new (data + num + 1) T(v2); + new (data + num + 2) T(v3); + num += 3; + } else { + resize(num + 3, DONT_SHRINK_UNDERLYING_ARRAY); + data[num - 3] = v1; + data[num - 2] = v2; + data[num - 1] = v3; + } + } + + + inline void append(const T& v1, const T& v2, const T& v3, const T& v4) { + if (inArray(&v1) || inArray(&v2) || inArray(&v3) || inArray(&v4)) { + T t1 = v1; + T t2 = v2; + T t3 = v3; + T t4 = v4; + append(t1, t2, t3, t4); + } else if (num + 3 < numAllocated) { + // This is a simple situation; just stick it in the next free slot using + // the copy constructor. + new (data + num) T(v1); + new (data + num + 1) T(v2); + new (data + num + 2) T(v3); + new (data + num + 3) T(v4); + num += 4; + } else { + resize(num + 4, DONT_SHRINK_UNDERLYING_ARRAY); + data[num - 4] = v1; + data[num - 3] = v2; + data[num - 2] = v3; + data[num - 1] = v4; + } + } + + /** + Returns true if the given element is in the array. + */ + bool contains(const T& e) const { + for (int i = 0; i < size(); ++i) { + if ((*this)[i] == e) { + return true; + } + } + + return false; + } + + /** + Append the elements of array. Cannot be called with this array + as an argument. + */ + void append(const Array& array) { + debugAssert(this != &array); + int oldNum = num; + int arrayLength = array.length(); + + resize(num + arrayLength, false); + + for (int i = 0; i < arrayLength; i++) { + data[oldNum + i] = array.data[i]; + } + } + + /** + Pushes a new element onto the end and returns its address. + This is the same as A.resize(A.size() + 1, false); A.last() + */ + inline T& next() { + resize(num + 1, false); + return last(); + } + + /** + Pushes an element onto the end (appends) + */ + inline void push(const T& value) { + append(value); + } + + inline void push(const Array& array) { + append(array); + } + + /** Alias to provide std::vector compatibility */ + inline void push_back(const T& v) { + push(v); + } + + /** "The member function removes the last element of the controlled sequence, which must be non-empty." + For compatibility with std::vector. */ + inline void pop_back() { + pop(); + } + + /** + "The member function returns the storage currently allocated to hold the controlled + sequence, a value at least as large as size()" + For compatibility with std::vector. + */ + int capacity() const { + return numAllocated; + } + + /** + "The member function returns a reference to the first element of the controlled sequence, + which must be non-empty." + For compatibility with std::vector. + */ + T& front() { + return (*this)[0]; + } + + /** + "The member function returns a reference to the first element of the controlled sequence, + which must be non-empty." + For compatibility with std::vector. + */ + const T& front() const { + return (*this)[0]; + } + + /** + "The member function returns a reference to the last element of the controlled sequence, + which must be non-empty." + For compatibility with std::vector. + */ + T& back() { + return (*this)[size()-1]; + } + + /** + "The member function returns a reference to the last element of the controlled sequence, + which must be non-empty." + For compatibility with std::vector. + */ + const T& back() const { + return (*this)[size()-1]; + } + + /** + Removes the last element and returns it. By default, shrinks the underlying array. + */ + inline T pop(bool shrinkUnderlyingArrayIfNecessary = true) { + debugAssert(num > 0); + T temp = data[num - 1]; + resize(num - 1, shrinkUnderlyingArrayIfNecessary); + return temp; + } + + /** Pops the last element and discards it without returning anything. Faster than pop. + By default, does not shrink the underlying array.*/ + inline void popDiscard(bool shrinkUnderlyingArrayIfNecessary = false) { + debugAssert(num > 0); + resize(num - 1, shrinkUnderlyingArrayIfNecessary); + } + + + /** + "The member function swaps the controlled sequences between *this and str." + Note that this is slower than the optimal std implementation. + + For compatibility with std::vector. + */ + void swap(Array& str) { + Array temp = str; + str = *this; + *this = temp; + } + + + /** + Performs bounds checks in debug mode + */ + inline T& operator[](int n) { + debugAssertM((n >= 0) && (n < num), format("Array index out of bounds. n = %d, size() = %d", n, num)); + debugAssert(data!=NULL); + return data[n]; + } + + inline T& operator[](unsigned int n) { + debugAssertM(n < (unsigned int)num, format("Array index out of bounds. n = %d, size() = %d", n, num)); + return data[n]; + } + + /** + Performs bounds checks in debug mode + */ + inline const T& operator[](int n) const { + debugAssert((n >= 0) && (n < num)); + debugAssert(data!=NULL); + return data[n]; + } + + inline const T& operator[](unsigned int n) const { + debugAssert((n < (unsigned int)num)); + debugAssert(data!=NULL); + return data[n]; + } + + inline T& randomElement() { + debugAssert(num > 0); + debugAssert(data!=NULL); + return data[iRandom(0, num - 1)]; + } + + inline const T& randomElement() const { + debugAssert(num > 0); + debugAssert(data!=NULL); + return data[iRandom(0, num - 1)]; + } + + /** + Returns the last element, performing a check in + debug mode that there is at least one element. + */ + inline const T& last() const { + debugAssert(num > 0); + debugAssert(data!=NULL); + return data[num - 1]; + } + + /** Returns element lastIndex() */ + inline T& last() { + debugAssert(num > 0); + debugAssert(data!=NULL); + return data[num - 1]; + } + + /** Returns size() - 1 */ + inline int lastIndex() const { + debugAssertM(num > 0, "Array is empty"); + return num - 1; + } + + inline int firstIndex() const { + debugAssertM(num > 0, "Array is empty"); + return 0; + } + + /** Returns element firstIndex(), performing a check in debug mode to ensure that there is at least one */ + inline T& first() { + debugAssertM(num > 0, "Array is empty"); + return data[0]; + } + + inline const T& first() const { + debugAssertM(num > 0, "Array is empty"); + return data[0]; + } + + /** Returns iFloor(size() / 2), throws an assertion in debug mode if the array is empty */ + inline int middleIndex() const { + debugAssertM(num > 0, "Array is empty"); + return num >> 1; + } + + /** Returns element middleIndex() */ + inline const T& middle() const { + debugAssertM(num > 0, "Array is empty"); + return data[num >> 1]; + } + + /** Returns element middleIndex() */ + inline T& middle() { + debugAssertM(num > 0, "Array is empty"); + return data[num >> 1]; + } + + /** + Calls delete on all objects[0...size-1] + and sets the size to zero. + */ + void deleteAll() { + for (int i = 0; i < num; i++) { + delete data[i]; + } + resize(0); + } + + /** + Returns the index of (the first occurance of) an index or -1 if + not found. Searches from the right. + */ + int rfindIndex(const T& value) const { + for (int i = num -1 ; i >= 0; --i) { + if (data[i] == value) { + return i; + } + } + return -1; + } + + /** + Returns the index of (the first occurance of) an index or -1 if + not found. + */ + int findIndex(const T& value) const { + for (int i = 0; i < num; ++i) { + if (data[i] == value) { + return i; + } + } + return -1; + } + + /** + Finds an element and returns the iterator to it. If the element + isn't found then returns end(). + */ + Iterator find(const T& value) { + for (int i = 0; i < num; ++i) { + if (data[i] == value) { + return data + i; + } + } + return end(); + } + + ConstIterator find(const T& value) const { + for (int i = 0; i < num; ++i) { + if (data[i] == value) { + return data + i; + } + } + return end(); + } + + /** + Removes count elements from the array + referenced either by index or Iterator. + */ + void remove(Iterator element, int count = 1) { + debugAssert((element >= begin()) && (element < end())); + debugAssert((count > 0) && (element + count) <= end()); + Iterator last = end() - count; + + while(element < last) { + element[0] = element[count]; + ++element; + } + + resize(num - count); + } + + void remove(int index, int count = 1) { + debugAssert((index >= 0) && (index < num)); + debugAssert((count > 0) && (index + count <= num)); + + remove(begin() + index, count); + } + + /** + Reverse the elements of the array in place. + */ + void reverse() { + T temp; + + int n2 = num / 2; + for (int i = 0; i < n2; ++i) { + temp = data[num - 1 - i]; + data[num - 1 - i] = data[i]; + data[i] = temp; + } + } + + /** + Sort using a specific less-than function, e.g.: + +
+    bool __cdecl myLT(const MyClass& elem1, const MyClass& elem2) {
+        return elem1.x < elem2.x;
+    }
+    
+ + Note that for pointer arrays, the const must come + after the class name, e.g., Array uses: + +
+    bool __cdecl myLT(MyClass*const& elem1, MyClass*const& elem2) {
+        return elem1->x < elem2->x;
+    }
+    
+ + or a functor, e.g., +
+bool
+less_than_functor::operator()( const double& lhs, const double& rhs ) const
+{
+return( lhs < rhs? true : false );
+}
+
+ */ + // void sort(bool (__cdecl *lessThan)(const T& elem1, const T& elem2)) { + // std::sort(data, data + num, lessThan); + //} + template + void sort(const LessThan& lessThan) { + // Using std::sort, which according to http://www.open-std.org/JTC1/SC22/WG21/docs/D_4.cpp + // was 2x faster than qsort for arrays around size 2000 on intel core2 with gcc + std::sort(data, data + num, lessThan); + } + + /** + Sorts the array in increasing order using the > or < operator. To + invoke this method on Array, T must override those operator. + You can overide these operators as follows: + + bool T::operator>(const T& other) const { + return ...; + } + bool T::operator<(const T& other) const { + return ...; + } + + */ + void sort(int direction = SORT_INCREASING) { + if (direction == SORT_INCREASING) { + std::sort(data, data + num); + } else { + std::sort(data, data + num, compareGT); + } + } + + /** + Sorts elements beginIndex through and including endIndex. + */ + void sortSubArray(int beginIndex, int endIndex, int direction = SORT_INCREASING) { + if (direction == SORT_INCREASING) { + std::sort(data + beginIndex, data + endIndex + 1); + } else { + std::sort(data + beginIndex, data + endIndex + 1, compareGT); + } + } + + void sortSubArray(int beginIndex, int endIndex, bool (__cdecl *lessThan)(const T& elem1, const T& elem2)) { + std::sort(data + beginIndex, data + endIndex + 1, lessThan); + } + + /** + The StrictWeakOrdering can be either a class that overloads the function call operator() or + a function pointer of the form bool (__cdecl *lessThan)(const T& elem1, const T& elem2) + */ + template + void sortSubArray(int beginIndex, int endIndex, StrictWeakOrdering& lessThan) { + std::sort(data + beginIndex, data + endIndex + 1, lessThan); + } + + /** Uses < and == to evaluate operator(); this is the default comparator for Array::partition. */ + class DefaultComparator { + public: + inline int operator()(const T& A, const T& B) const { + if (A < B) { + return 1; + } else if (A == B) { + return 0; + } else { + return -1; + } + } + }; + + /** The output arrays are resized with fastClear() so that if they are already of the same size + as this array no memory is allocated during partitioning. + + @param comparator A function, or class instance with an overloaded operator() that compares + two elements of type T and returns 0 if they are equal, -1 if the second is smaller, + and 1 if the first is smaller (i.e., following the conventions of std::string::compare). For example: + +
+        int compare(int A, int B) {
+            if (A < B) {
+                return 1;
+            } else if (A == B) {
+                return 0;
+            } else {
+                return -1;
+            }
+        }
+        
+ */ + template + void partition( + const T& partitionElement, + Array& ltArray, + Array& eqArray, + Array& gtArray, + const Comparator& comparator) const { + + // Make sure all arrays are independent + debugAssert(<Array != this); + debugAssert(&eqArray != this); + debugAssert(>Array != this); + debugAssert(<Array != &eqArray); + debugAssert(<Array != >Array); + debugAssert(&eqArray != >Array); + + // Clear the arrays + ltArray.fastClear(); + eqArray.fastClear(); + gtArray.fastClear(); + + // Form a table of buckets for lt, eq, and gt + Array* bucket[3] = {<Array, &eqArray, >Array}; + + for (int i = 0; i < num; ++i) { + int c = comparator(partitionElement, data[i]); + debugAssertM(c >= -1 && c <= 1, "Comparator returned an illegal value."); + + // Insert into the correct bucket, 0, 1, or 2 + bucket[c + 1]->append(data[i]); + } + } + + /** + Uses < and == on elements to perform a partition. See partition(). + */ + void partition( + const T& partitionElement, + Array& ltArray, + Array& eqArray, + Array& gtArray) const { + + partition(partitionElement, ltArray, eqArray, gtArray, typename Array::DefaultComparator()); + } + + /** + Paritions the array into those below the median, those above the median, and those elements + equal to the median in expected O(n) time using quickselect. If the array has an even + number of different elements, the median for partition purposes is the largest value + less than the median. + + @param tempArray used for working scratch space + @param comparator see parition() for a discussion.*/ + template + void medianPartition( + Array& ltMedian, + Array& eqMedian, + Array& gtMedian, + Array& tempArray, + const Comparator& comparator) const { + + ltMedian.fastClear(); + eqMedian.fastClear(); + gtMedian.fastClear(); + + // Handle trivial cases first + switch (size()) { + case 0: + // Array is empty; no parition is possible + return; + + case 1: + // One element + eqMedian.append(first()); + return; + + case 2: + { + // Two element array; median is the smaller + int c = comparator(first(), last()); + + switch (c) { + case -1: + // first was bigger + eqMedian.append(last()); + gtMedian.append(first()); + break; + + case 0: + // Both equal to the median + eqMedian.append(first(), last()); + break; + + case 1: + // Last was bigger + eqMedian.append(first()); + gtMedian.append(last()); + break; + } + } + return; + } + + // All other cases use a recursive randomized median + + // Number of values less than all in the current arrays + int ltBoost = 0; + + // Number of values greater than all in the current arrays + int gtBoost = 0; + + // For even length arrays, force the gt array to be one larger than the + // lt array: + // [1 2 3] size = 3, choose half = (s + 1) /2 + // + int lowerHalfSize, upperHalfSize; + if (isEven(size())) { + lowerHalfSize = size() / 2; + upperHalfSize = lowerHalfSize + 1; + } else { + lowerHalfSize = upperHalfSize = (size() + 1) / 2; + } + const T* xPtr = NULL; + + // Maintain pointers to the arrays; we'll switch these around during sorting + // to avoid copies. + const Array* source = this; + Array* lt = <Median; + Array* eq = &eqMedian; + Array* gt = >Median; + Array* extra = &tempArray; + + while (true) { + // Choose a random element -- choose the middle element; this is theoretically + // suboptimal, but for loosly sorted array is actually the best strategy + + xPtr = &(source->middle()); + if (source->size() == 1) { + // Done; there's only one element left + break; + } + const T& x = *xPtr; + + // Note: partition (fast) clears the arrays for us + source->partition(x, *lt, *eq, *gt, comparator); + + int L = lt->size() + ltBoost + eq->size(); + int U = gt->size() + gtBoost + eq->size(); + if ((L >= lowerHalfSize) && + (U >= upperHalfSize)) { + + // x must be the partition median + break; + + } else if (L < lowerHalfSize) { + + // x must be smaller than the median. Recurse into the 'gt' array. + ltBoost += lt->size() + eq->size(); + + // The new gt array will be the old source array, unless + // that was the this pointer (i.e., unless we are on the + // first iteration) + Array* newGt = (source == this) ? extra : const_cast*>(source); + + // Now set up the gt array as the new source + source = gt; + gt = newGt; + + } else { + + // x must be bigger than the median. Recurse into the 'lt' array. + gtBoost += gt->size() + eq->size(); + + // The new lt array will be the old source array, unless + // that was the this pointer (i.e., unless we are on the + // first iteration) + Array* newLt = (source == this) ? extra : const_cast*>(source); + + // Now set up the lt array as the new source + source = lt; + lt = newLt; + } + } + + // Now that we know the median, make a copy of it (since we're about to destroy the array that it + // points into). + T median = *xPtr; + xPtr = NULL; + + // Partition the original array (note that this fast clears for us) + partition(median, ltMedian, eqMedian, gtMedian, comparator); + } + + /** + Computes a median partition using the default comparator and a dynamically allocated temporary + working array. If the median is not in the array, it is chosen to be the largest value smaller + than the true median. + */ + void medianPartition( + Array& ltMedian, + Array& eqMedian, + Array& gtMedian) const { + + Array temp; + medianPartition(ltMedian, eqMedian, gtMedian, temp, DefaultComparator()); + } + + + /** Redistributes the elements so that the new order is statistically independent + of the original order. O(n) time.*/ + void randomize() { + T temp; + + for (int i = size() - 1; i >= 0; --i) { + int x = iRandom(0, i); + + temp = data[i]; + data[i] = data[x]; + data[x] = temp; + } + } + + +}; + + +/** Array::contains for C-arrays */ +template bool contains(const T* array, int len, const T& e) { + for (int i = len - 1; i >= 0; --i) { + if (array[i] == e) { + return true; + } + } + return false; +} + +} // namespace + +#ifdef _MSC_VER +# pragma warning (pop) +#endif + +#endif diff --git a/dep/g3dlite/G3D/AtomicInt32.h b/dep/g3dlite/G3D/AtomicInt32.h new file mode 100644 index 00000000000..2d63f998355 --- /dev/null +++ b/dep/g3dlite/G3D/AtomicInt32.h @@ -0,0 +1,164 @@ +/** + @file AtomicInt32.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2005-09-01 + @edited 2006-06-21 + */ +#ifndef G3D_ATOMICINT32_H +#define G3D_ATOMICINT32_H + +#include "G3D/platform.h" +#include "G3D/g3dmath.h" + +#if defined(G3D_OSX) +# include +#endif + +namespace G3D { + +/** + An integer that may safely be used on different threads without + external locking. + + On Win32, Linux, FreeBSD, and Mac OS X this is implemented without locks. + + BETA API This is unsupported and may change + */ +class AtomicInt32 { +private: +# if defined(G3D_WIN32) + volatile long m_value; +# elif defined(G3D_OSX) + int32_t m_value; +# else + volatile int32 m_value; +# endif + + +public: + + /** Initial value is undefined. */ + AtomicInt32() {} + + /** Atomic set */ + explicit AtomicInt32(const int32 x) { + m_value = x; + } + + /** Atomic set */ + AtomicInt32(const AtomicInt32& x) { + m_value = x.m_value; + } + + /** Atomic set */ + const AtomicInt32& operator=(const int32 x) { + m_value = x; + return *this; + } + + /** Atomic set */ + void operator=(const AtomicInt32& x) { + m_value = x.m_value; + } + + /** Returns the current value */ + int32 value() const { + return m_value; + } + + /** Returns the old value, before the add. */ + int32 add(const int32 x) { +# if defined(G3D_WIN32) + + return InterlockedExchangeAdd(&m_value, x); + +# elif defined(G3D_LINUX) || defined(G3D_FREEBSD) + + int32 old; + asm volatile ("lock; xaddl %0,%1" + : "=r"(old), "=m"(m_value) /* outputs */ + : "0"(x), "m"(m_value) /* inputs */ + : "memory", "cc"); + return old; + +# elif defined(G3D_OSX) + + int32 old = m_value; + OSAtomicAdd32(x, &m_value); + return old; + +# endif + } + + /** Returns old value. */ + int32 sub(const int32 x) { + return add(-x); + } + + void increment() { +# if defined(G3D_WIN32) + // Note: returns the newly incremented value + InterlockedIncrement(&m_value); +# elif defined(G3D_LINUX) || defined(G3D_FREEBSD) + add(1); +# elif defined(G3D_OSX) + // Note: returns the newly incremented value + OSAtomicIncrement32(&m_value); +# endif + } + + /** Returns zero if the result is zero after decrement, non-zero otherwise.*/ + int32 decrement() { +# if defined(G3D_WIN32) + // Note: returns the newly decremented value + return InterlockedDecrement(&m_value); +# elif defined(G3D_LINUX) || defined(G3D_FREEBSD) + unsigned char nz; + + asm volatile ("lock; decl %1;\n\t" + "setnz %%al" + : "=a" (nz) + : "m" (m_value) + : "memory", "cc"); + return nz; +# elif defined(G3D_OSX) + // Note: returns the newly decremented value + return OSAtomicDecrement32(&m_value); +# endif + } + + + /** Atomic test-and-set: if *this == comperand then *this := exchange else do nothing. + In both cases, returns the old value of *this. + + Performs an atomic comparison of this with the Comperand value. + If this is equal to the Comperand value, the Exchange value is stored in this. + Otherwise, no operation is performed. + + Under VC6 the sign bit may be lost. + */ + int32 compareAndSet(const int32 comperand, const int32 exchange) { +# if defined(G3D_WIN32) + return InterlockedCompareExchange(&m_value, exchange, comperand); +# elif defined(G3D_LINUX) || defined(G3D_FREEBSD) || defined(G3D_OSX) + // Based on Apache Portable Runtime + // http://koders.com/c/fid3B6631EE94542CDBAA03E822CA780CBA1B024822.aspx + int32 ret; + asm volatile ("lock; cmpxchgl %1, %2" + : "=a" (ret) + : "r" (exchange), "m" (m_value), "0"(comperand) + : "memory", "cc"); + return ret; + + // Note that OSAtomicCompareAndSwap32 does not return a useful value for us + // so it can't satisfy the cmpxchgl contract. +# endif + } + +}; + +} // namespace + +#endif diff --git a/dep/g3dlite/G3D/BinaryFormat.h b/dep/g3dlite/G3D/BinaryFormat.h new file mode 100644 index 00000000000..f6719a1c540 --- /dev/null +++ b/dep/g3dlite/G3D/BinaryFormat.h @@ -0,0 +1,140 @@ +/** + @file BinaryFormat.h + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @author 2005-06-03 + @edited 2005-06-03 + + Copyright 2000-2005, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_BINARYFORMAT_H +#define G3D_BINARYFORMAT_H + +#include "G3D/platform.h" +#include "G3D/g3dmath.h" + +namespace G3D { + +class Vector2; +class Vector2int16; +class Vector3; +class Vector3int16; +class Vector4; +class Vector4int16; +class Color3; +class Color3uint8; +class Color4; +class Color4uint8; + +/** + Some values like float16 and int128 have no current CPU data structure that implements them but are useful + for file formats and for GPUs. + + CHUNK_BINFMT data follows the protocol. + */ +// Must be packed int 16 bits for the chunk reader +// We can't name these just "INT8" etc. because some libraries #define names like that +enum BinaryFormat { + FIRST_BINFMT = 1000, + + BOOL8_BINFMT, + UINT8_BINFMT, INT8_BINFMT, UINT16_BINFMT, INT16_BINFMT, UINT32_BINFMT, INT32_BINFMT, UINT64_BINFMT, INT64_BINFMT, UINT128_BINFMT, INT128_BINFMT, + FLOAT16_BINFMT, FLOAT32_BINFMT, FLOAT64_BINFMT, + VECTOR2_BINFMT, VECTOR2INT16_BINFMT, + VECTOR3_BINFMT, VECTOR3INT16_BINFMT, + VECTOR4_BINFMT, VECTOR4INT16_BINFMT, + COLOR3_BINFMT, COLOR3UINT8_BINFMT, COLOR3INT16_BINFMT, + COLOR4_BINFMT, COLOR4UINT8_BINFMT, COLOR4INT16_BINFMT, + STRING_BINFMT, STRINGEVEN_BINFMT, STRING8_BINFMT, STRING16_BINFMT, STRING32_BINFMT, + + CHUNK_BINFMT, + + CUSTOM_BINFMT, + + LAST_BINFMT +}; + +} + +/** A macro that maps G3D types to format constants. + (e.g. binaryFormatOf(Vector3) == VECTOR3_BINFMT). +*/ +// This implementation is designed to meet the following constraints: +// 1. Work around the many MSVC++ partial template bugs +// 2. Work for primitive types (e.g. int) +#define binaryFormatOf(T) (G3D::_internal::_BinaryFormat::x()) + +namespace G3D { +namespace _internal { + + +template class _BinaryFormat { +public: + static BinaryFormat x() { + return CUSTOM_BINFMT; + } +}; +}} + + +/** + Macro to declare the underlying format (as will be returned by glFormatOf) + of a type. For example, + +
+    DECLARE_BINARYFORMATOF(Vector4, VECTOR4_BINFMT)
+  
+ + Use this so you can make vertex arrays of your own classes and not just + the standard ones. + */ +#define DECLARE_BINARYFORMATOF(CType, EnumType) \ +namespace G3D { \ + namespace _internal { \ + template<> class _BinaryFormat { \ + public: \ + static BinaryFormat x() { \ + return EnumType; \ + } \ + }; \ + } \ +} + +DECLARE_BINARYFORMATOF( bool, BOOL8_BINFMT ) + +DECLARE_BINARYFORMATOF( uint8, UINT8_BINFMT ) +DECLARE_BINARYFORMATOF( int8, INT8_BINFMT ) +DECLARE_BINARYFORMATOF( uint16, UINT16_BINFMT ) +DECLARE_BINARYFORMATOF( int16, INT16_BINFMT ) +DECLARE_BINARYFORMATOF( uint32, UINT32_BINFMT ) +DECLARE_BINARYFORMATOF( int32, INT32_BINFMT ) +DECLARE_BINARYFORMATOF( uint64, UINT64_BINFMT ) +DECLARE_BINARYFORMATOF( int64, INT64_BINFMT ) + +DECLARE_BINARYFORMATOF( float32, FLOAT32_BINFMT ) +DECLARE_BINARYFORMATOF( float64, FLOAT64_BINFMT ) + +DECLARE_BINARYFORMATOF( Vector2, VECTOR2_BINFMT ) +DECLARE_BINARYFORMATOF( Vector2int16, VECTOR2INT16_BINFMT ) +DECLARE_BINARYFORMATOF( Vector3, VECTOR3_BINFMT ) +DECLARE_BINARYFORMATOF( Vector3int16, VECTOR3INT16_BINFMT ) +DECLARE_BINARYFORMATOF( Vector4, VECTOR4_BINFMT ) +DECLARE_BINARYFORMATOF( Vector4int16, VECTOR4INT16_BINFMT ) + +DECLARE_BINARYFORMATOF( Color3, COLOR3_BINFMT ) +DECLARE_BINARYFORMATOF( Color3uint8, COLOR3UINT8_BINFMT ) +DECLARE_BINARYFORMATOF( Color4, COLOR4_BINFMT ) +DECLARE_BINARYFORMATOF( Color4uint8, COLOR4UINT8_BINFMT ) + +namespace G3D { + +/** Returns -1 if the format is custom, otherwise the byte size + of a single element in this format.*/ +int32 byteSize(BinaryFormat f); + + +} //G3D + +#endif diff --git a/dep/g3dlite/G3D/BinaryInput.h b/dep/g3dlite/G3D/BinaryInput.h new file mode 100644 index 00000000000..1dac93ea55e --- /dev/null +++ b/dep/g3dlite/G3D/BinaryInput.h @@ -0,0 +1,441 @@ +/** + @file BinaryInput.h + + @maintainer Morgan McGuire, graphics3d.com + + @created 2001-08-09 + @edited 2006-07-19 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_BinaryInput_h +#define G3D_BinaryInput_h + +#ifdef _MSC_VER +// Disable conditional expression is constant, which occurs incorrectly on inlined functions +# pragma warning(push) +# pragma warning( disable : 4127 ) +#endif + +#include +#include +#include +#include +#include +#include +#include "G3D/platform.h" +#include "G3D/Array.h" +#include "G3D/Color4.h" +#include "G3D/Color3.h" +#include "G3D/Vector4.h" +#include "G3D/Vector3.h" +#include "G3D/Vector2.h" +#include "G3D/g3dmath.h" +#include "G3D/debug.h" +#include "G3D/System.h" + + +namespace G3D { + +#if defined(G3D_WIN32) || defined(G3D_LINUX) + // Allow writing of integers to non-word aligned locations. + // This is legal on x86, but not on other platforms. + #define G3D_ALLOW_UNALIGNED_WRITES +#endif + +/** + Sequential or random access byte-order independent binary file access. + Files compressed with zlib and beginning with an unsigned 32-bit int + size are transparently decompressed when the compressed = true flag is + specified to the constructor. + + For every readX method there are also versions that operate on a whole + Array, std::vector, or C-array. e.g. readFloat32(Array& array, n) + These methods resize the array or std::vector to the appropriate size + before reading. For a C-array, they require the pointer to reference + a memory block at least large enough to hold n elements. + + Most classes define serialize/deserialize methods that use BinaryInput, + BinaryOutput, TextInput, and TextOutput. There are text serializer + functions for primitive types (e.g. int, std::string, float, double) but not + binary serializers-- you must call the BinaryInput::readInt32 or + other appropriate function. This is because it would be very hard to + debug the error sequence: serialize(1.0, bo); ... float f; deserialize(f, bi); + in which a double is serialized and then deserialized as a float. + */ +class BinaryInput { +private: + + // The initial buffer will be no larger than this, but + // may grow if a large memory read occurs. 50 MB + enum {INITIAL_BUFFER_LENGTH = 50000000}; + + /** + is the file big or little endian + */ + G3DEndian m_fileEndian; + std::string m_filename; + + bool m_swapBytes; + + /** Next position to read from in bitString during readBits. */ + int m_bitPos; + + /** Bits currently being read by readBits. + Contains at most 8 (low) bits. Note that + beginBits/readBits actually consumes one extra byte, which + will be restored by writeBits.*/ + uint32 m_bitString; + + /** 1 when between beginBits and endBits, 0 otherwise. */ + int m_beginEndBits; + + /** When operating on huge files, we cannot load the whole file into memory. + This is the file position to which buffer[0] corresponds. + */ + int64 m_alreadyRead; + + /** + Length of the entire file, in bytes. + For the length of the buffer, see bufferLength + */ + int64 m_length; + + /** Length of the array referenced by buffer. May go past the end of the file!*/ + int64 m_bufferLength; + uint8* m_buffer; + + /** + Next byte in file, relative to buffer. + */ + int64 m_pos; + + /** + When true, the buffer is freed in the destructor. + */ + bool m_freeBuffer; + + /** Ensures that we are able to read at least minLength from startPosition (relative + to start of file). */ + void loadIntoMemory(int64 startPosition, int64 minLength = 0); + + /** Verifies that at least this number of bytes can be read.*/ + inline void prepareToRead(int64 nbytes) { + debugAssertM(m_length > 0, m_filename + " not found or corrupt."); + debugAssertM(m_pos + nbytes + m_alreadyRead <= m_length, "Read past end of file."); + + if (m_pos + nbytes > m_bufferLength) { + loadIntoMemory(m_pos + m_alreadyRead, nbytes); + } + } + + // Not implemented on purpose, don't use + BinaryInput(const BinaryInput&); + BinaryInput& operator=(const BinaryInput&); + bool operator==(const BinaryInput&); + + /** Buffer is compressed; replace it with a decompressed version */ + void decompress(); +public: + + /** false, constant to use with the copyMemory option */ + static const bool NO_COPY; + + /** + If the file cannot be opened, a zero length buffer is presented. + Automatically opens files that are inside zipfiles. + + @param compressed Set to true if and only if the file was + compressed using BinaryOutput's zlib compression. This has + nothing to do with whether the input is in a zipfile. + */ + BinaryInput( + const std::string& filename, + G3DEndian fileEndian, + bool compressed = false); + + /** + Creates input stream from an in memory source. + Unless you specify copyMemory = false, the data is copied + from the pointer, so you may deallocate it as soon as the + object is constructed. It is an error to specify copyMemory = false + and compressed = true. + + To decompress part of a file, you can follow the following paradigm: + +
+        BinaryInput master(...);
+
+        // read from master to point where compressed data exists.
+
+        BinaryInput subset(master.getCArray() + master.getPosition(), 
+                           master.length() - master.getPosition(),
+                           master.endian(), true, true);
+
+        // Now read from subset (it is ok for master to go out of scope)
+     
+ */ + BinaryInput( + const uint8* data, + int64 dataLen, + G3DEndian dataEndian, + bool compressed = false, + bool copyMemory = true); + + virtual ~BinaryInput(); + + /** Change the endian-ness of the file. This only changes the + interpretation of the file for future read calls; the + underlying data is unmodified.*/ + void setEndian(G3DEndian endian); + + G3DEndian endian() const { + return m_fileEndian; + } + + std::string getFilename() const { + return m_filename; + } + + /** + Returns a pointer to the internal memory buffer. + May throw an exception for huge files. + */ + const uint8* getCArray() const { + if (m_alreadyRead > 0) { + throw "Cannot getCArray for a huge file"; + } + return m_buffer; + } + + /** + Performs bounds checks in debug mode. [] are relative to + the start of the file, not the current position. + Seeks to the new position before reading (and leaves + that as the current position) + */ + inline uint8 operator[](int64 n) { + setPosition(n); + return readUInt8(); + } + + /** + Returns the length of the file in bytes. + */ + inline int64 getLength() const { + return m_length; + } + + inline int64 size() const { + return getLength(); + } + + /** + Returns the current byte position in the file, + where 0 is the beginning and getLength() - 1 is the end. + */ + inline int64 getPosition() const { + return m_pos + m_alreadyRead; + } + + /** + Sets the position. Cannot set past length. + May throw a char* when seeking backwards more than 10 MB on a huge file. + */ + inline void setPosition(int64 p) { + debugAssertM(p <= m_length, "Read past end of file"); + m_pos = p - m_alreadyRead; + if ((m_pos < 0) || (m_pos > m_bufferLength)) { + loadIntoMemory(m_pos + m_alreadyRead); + } + } + + /** + Goes back to the beginning of the file. + */ + inline void reset() { + setPosition(0); + } + + inline int8 readInt8() { + prepareToRead(1); + return m_buffer[m_pos++]; + } + + inline bool readBool8() { + return (readInt8() != 0); + } + + inline uint8 readUInt8() { + prepareToRead(1); + return ((uint8*)m_buffer)[m_pos++]; + } + + uint16 inline readUInt16() { + prepareToRead(2); + + m_pos += 2; + if (m_swapBytes) { + uint8 out[2]; + out[0] = m_buffer[m_pos - 1]; + out[1] = m_buffer[m_pos - 2]; + return *(uint16*)out; + } else { + #ifdef G3D_ALLOW_UNALIGNED_WRITES + return *(uint16*)(&m_buffer[m_pos - 2]); + #else + uint8 out[2]; + out[0] = m_buffer[m_pos - 2]; + out[1] = m_buffer[m_pos - 1]; + return *(uint16*)out; + #endif + } + + } + + inline int16 readInt16() { + uint16 a = readUInt16(); + return *(int16*)&a; + } + + inline uint32 readUInt32() { + prepareToRead(4); + + m_pos += 4; + if (m_swapBytes) { + uint8 out[4]; + out[0] = m_buffer[m_pos - 1]; + out[1] = m_buffer[m_pos - 2]; + out[2] = m_buffer[m_pos - 3]; + out[3] = m_buffer[m_pos - 4]; + return *(uint32*)out; + } else { + #ifdef G3D_ALLOW_UNALIGNED_WRITES + return *(uint32*)(&m_buffer[m_pos - 4]); + #else + uint8 out[4]; + out[0] = m_buffer[m_pos - 4]; + out[1] = m_buffer[m_pos - 3]; + out[2] = m_buffer[m_pos - 2]; + out[3] = m_buffer[m_pos - 1]; + return *(uint32*)out; + #endif + } + } + + + inline int32 readInt32() { + uint32 a = readUInt32(); + return *(int32*)&a; + } + + uint64 readUInt64(); + + inline int64 readInt64() { + uint64 a = readUInt64(); + return *(int64*)&a; + } + + inline float32 readFloat32() { + union { + uint32 a; + float32 b; + }; + a = readUInt32(); + return b; + } + + inline float64 readFloat64() { + union { + uint64 a; + float64 b; + }; + a = readUInt64(); + return b; + } + + void readBytes(void* bytes, int64 n); + + /** + Reads an n character string. The string is not + required to end in NULL in the file but will + always be a proper std::string when returned. + */ + std::string readString(int64 n); + + /** + Reads until NULL or the end of the file is encountered. + */ + std::string readString(); + + /** + Reads until NULL or the end of the file is encountered. + If the string has odd length (including NULL), reads + another byte. + */ + std::string readStringEven(); + + + std::string readString32(); + + Vector4 readVector4(); + Vector3 readVector3(); + Vector2 readVector2(); + + Color4 readColor4(); + Color3 readColor3(); + + /** + Skips ahead n bytes. + */ + inline void skip(int64 n) { + setPosition(m_pos + m_alreadyRead + n); + } + + /** + Returns true if the position is not at the end of the file + */ + inline bool hasMore() const { + return m_pos + m_alreadyRead < m_length; + } + + /** Prepares for bit reading via readBits. Only readBits can be + called between beginBits and endBits without corrupting the + data stream. */ + void beginBits(); + + /** Can only be called between beginBits and endBits */ + uint32 readBits(int numBits); + + /** Ends bit-reading. */ + void endBits(); + +# define DECLARE_READER(ucase, lcase)\ + void read##ucase(lcase* out, int64 n);\ + void read##ucase(std::vector& out, int64 n);\ + void read##ucase(Array& out, int64 n); + + DECLARE_READER(Bool8, bool) + DECLARE_READER(UInt8, uint8) + DECLARE_READER(Int8, int8) + DECLARE_READER(UInt16, uint16) + DECLARE_READER(Int16, int16) + DECLARE_READER(UInt32, uint32) + DECLARE_READER(Int32, int32) + DECLARE_READER(UInt64, uint64) + DECLARE_READER(Int64, int64) + DECLARE_READER(Float32, float32) + DECLARE_READER(Float64, float64) +# undef DECLARE_READER +}; + + +} + +#ifdef _MSC_VER +# pragma warning(pop) +#endif + +#endif diff --git a/dep/g3dlite/G3D/BinaryOutput.h b/dep/g3dlite/G3D/BinaryOutput.h new file mode 100644 index 00000000000..d81ec56a67b --- /dev/null +++ b/dep/g3dlite/G3D/BinaryOutput.h @@ -0,0 +1,421 @@ +/** + @file BinaryOutput.h + + @maintainer Morgan McGuire, graphics3d.com + + @created 2001-08-09 + @edited 2008-01-24 + + Copyright 2000-2006, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_BINARYOUTPUT_H +#define G3D_BINARYOUTPUT_H + +#include "G3D/platform.h" +#include +#include +#include +#include +#include +#include "G3D/Color4.h" +#include "G3D/Color3.h" +#include "G3D/Vector4.h" +#include "G3D/Vector3.h" +#include "G3D/Vector2.h" +#include "G3D/g3dmath.h" +#include "G3D/debug.h" +#include "G3D/BinaryInput.h" +#include "G3D/System.h" + +#ifdef _MSC_VER +# pragma warning (push) +// Conditional is constant (wrong in inline) +# pragma warning (disable : 4127) +#endif +namespace G3D { + +/** + Sequential or random access byte-order independent binary file access. + + The compress() call can be used to compress with zlib. + + Any method call can trigger an out of memory error (thrown as char*) + when writing to "" instead of a file. + + Compressed writing and seeking backwards is not supported for huge files + (i.e., BinaryOutput may have to dump the contents to disk if they + exceed available RAM). + */ +class BinaryOutput { +private: + std::string m_filename; + + bool m_committed; + + /** 0 outside of beginBits...endBits, 1 inside */ + int m_beginEndBits; + + /** The current string of bits being built up by beginBits...endBits. + This string is treated semantically, as if the lowest bit was + on the left and the highest was on the right.*/ + int8 m_bitString; + + /** Position (from the lowest bit) currently used in bitString.*/ + int m_bitPos; + + // True if the file endianess does not match the machine endian + bool m_swapBytes; + + G3DEndian m_fileEndian; + + uint8* m_buffer; + + /** Size of the elements used */ + int m_bufferLen; + + /** Underlying size of memory allocaded */ + int m_maxBufferLen; + + /** Next byte in file */ + int m_pos; + + /** is this initialized? */ + bool m_init; + + /** Number of bytes already written to the file.*/ + size_t m_alreadyWritten; + + bool m_ok; + + void reserveBytesWhenOutOfMemory(size_t bytes); + + void reallocBuffer(size_t bytes, size_t oldBufferLen); + + /** + Make sure at least bytes can be written, resizing if + necessary. + */ + inline void reserveBytes(int bytes) { + debugAssert(bytes > 0); + size_t oldBufferLen = (size_t)m_bufferLen; + + m_bufferLen = iMax(m_bufferLen, (m_pos + bytes)); + if (m_bufferLen > m_maxBufferLen) { + reallocBuffer(bytes, oldBufferLen); + } + } + + // Not implemented on purpose, don't use + BinaryOutput(const BinaryOutput&); + BinaryOutput& operator=(const BinaryOutput&); + bool operator==(const BinaryOutput&); + +public: + + /** + You must call setEndian() if you use this (memory) constructor. + */ + BinaryOutput(); + + /** + Doesn't actually open the file; commit() does that. + Use "" as the filename if you're going to commit + to memory. + */ + BinaryOutput( + const std::string& filename, + G3DEndian fileEndian); + + ~BinaryOutput(); + + /** Compresses the data in the buffer in place, + preceeding it with a little-endian uint32 indicating + the uncompressed size. + + Call immediately before commit(). + + Cannot be used for huge files (ones where the data + was already written to disk)-- will throw char*. + */ + void compress(); + + /** True if no errors have been encountered.*/ + bool ok() const; + + /** + Returns a pointer to the internal memory buffer. + */ + inline const uint8* getCArray() const { + return m_buffer; + } + + void setEndian(G3DEndian fileEndian); + + G3DEndian endian() const { + return m_fileEndian; + } + + std::string getFilename() const { + return m_filename; + } + + /** + Write the bytes to disk. It is ok to call this + multiple times; it will just overwrite the previous file. + + Parent directories are created as needed if they do + not exist. + + Not called from the destructor; you must call + it yourself. + + @param flush If true (default) the file is ready for reading when the method returns, otherwise + the method returns immediately and writes the file in the background. + */ + void commit(bool flush = true); + + /** + Write the bytes to memory (which must be of + at least size() bytes). + */ + void commit(uint8*); + + /** + A memory BinaryOutput may be reset so that it can be written to again + without allocating new memory. The underlying array will not be deallocated, + but the reset structure will act like a newly intialized one. + */ + void reset(); + + + inline int length() const { + return (int)m_bufferLen + (int)m_alreadyWritten; + } + + inline int size() const { + return length(); + } + + /** + Sets the length of the file to n, padding + with 0's past the current end. Does not + change the position of the next byte to be + written unless n < size(). + + Throws char* when resetting a huge file to be shorter + than its current length. + */ + inline void setLength(int n) { + n = n - (int)m_alreadyWritten; + + if (n < 0) { + throw "Cannot resize huge files to be shorter."; + } + + if (n < m_bufferLen) { + m_pos = n; + } + if (n > m_bufferLen) { + reserveBytes(n - m_bufferLen); + } + } + + /** + Returns the current byte position in the file, + where 0 is the beginning and getLength() - 1 is the end. + */ + inline int64 position() const { + return (int64)m_pos + (int64)m_alreadyWritten; + } + + + /** + Sets the position. Can set past length, in which case + the file is padded with zeros up to one byte before the + next to be written. + + May throw a char* exception when seeking backwards on a huge file. + */ + inline void setPosition(int64 p) { + p = p - (int64)m_alreadyWritten; + + if (p > m_bufferLen) { + setLength((int)(p + (int64)m_alreadyWritten)); + } + + if (p < 0) { + throw "Cannot seek more than 10 MB backwards on huge files."; + } + + m_pos = (int)p; + } + + + void writeBytes( + const void* b, + int count) { + + reserveBytes(count); + debugAssert(m_pos >= 0); + debugAssert(m_bufferLen >= count); + System::memcpy(m_buffer + m_pos, b, count); + m_pos += count; + } + + /** + Writes a signed 8-bit integer to the current position. + */ + inline void writeInt8(int8 i) { + reserveBytes(1); + m_buffer[m_pos] = *(uint8*)&i; + m_pos++; + } + + inline void writeBool8(bool b) { + writeInt8(b ? 1 : 0); + } + + inline void writeUInt8(uint8 i) { + reserveBytes(1); + m_buffer[m_pos] = i; + m_pos++; + } + + void writeUInt16(uint16 u); + + inline void writeInt16(int16 i) { + writeUInt16(*(uint16*)&i); + } + + void writeUInt32(uint32 u); + + inline void writeInt32(int32 i) { + debugAssert(m_beginEndBits == 0); + writeUInt32(*(uint32*)&i); + } + + void writeUInt64(uint64 u); + + inline void writeInt64(int64 i) { + writeUInt64(*(uint64*)&i); + } + + inline void writeFloat32(float32 f) { + debugAssert(m_beginEndBits == 0); + union { + float32 a; + uint32 b; + }; + a = f; + writeUInt32(b); + } + + inline void writeFloat64(float64 f) { + union { + float64 a; + uint64 b; + }; + a = f; + writeUInt64(b); + } + + /** + Write a string with NULL termination. + */ + inline void writeString(const std::string& s) { + writeString(s.c_str()); + } + + void writeString(const char* s); + + /** + Write a string, ensuring that the total length + including NULL is even. + */ + void writeStringEven(const std::string& s) { + writeStringEven(s.c_str()); + } + + void writeStringEven(const char* s); + + + void writeString32(const char* s); + + /** + Write a string with a 32-bit length field in front + of it. + */ + void writeString32(const std::string& s) { + writeString32(s.c_str()); + } + + void writeVector4(const Vector4& v); + + void writeVector3(const Vector3& v); + + void writeVector2(const Vector2& v); + + void writeColor4(const Color4& v); + + void writeColor3(const Color3& v); + + /** + Skips ahead n bytes. + */ + inline void skip(int n) { + if (m_pos + n > m_bufferLen) { + setLength((int)m_pos + (int)m_alreadyWritten + n); + } + m_pos += n; + } + + /** Call before a series of BinaryOutput::writeBits calls. Only writeBits + can be called between beginBits and endBits without corrupting the stream.*/ + void beginBits(); + + /** Write numBits from bitString to the output stream. Bits are numbered from + low to high. + + Can only be + called between beginBits and endBits. Bits written are semantically + little-endian, regardless of the actual endian-ness of the system. That is, + writeBits(0xABCD, 16) writes 0xCD to the first byte and + 0xAB to the second byte. However, if used with BinaryInput::readBits, the ordering + is transparent to the caller. + */ + void writeBits(uint32 bitString, int numBits); + + /** Call after a series of BinaryOutput::writeBits calls. This will + finish out with zeros the last byte into which bits were written.*/ + void endBits(); + + +# define DECLARE_WRITER(ucase, lcase)\ + void write##ucase(const lcase* out, int n);\ + void write##ucase(const std::vector& out, int n);\ + void write##ucase(const Array& out, int n); + + DECLARE_WRITER(Bool8, bool) + DECLARE_WRITER(UInt8, uint8) + DECLARE_WRITER(Int8, int8) + DECLARE_WRITER(UInt16, uint16) + DECLARE_WRITER(Int16, int16) + DECLARE_WRITER(UInt32, uint32) + DECLARE_WRITER(Int32, int32) + DECLARE_WRITER(UInt64, uint64) + DECLARE_WRITER(Int64, int64) + DECLARE_WRITER(Float32, float32) + DECLARE_WRITER(Float64, float64) +# undef DECLARE_WRITER + +}; + +} + +#ifdef _MSC_VER +# pragma warning (pop) +#endif + +#endif diff --git a/dep/g3dlite/G3D/BoundsTrait.h b/dep/g3dlite/G3D/BoundsTrait.h new file mode 100644 index 00000000000..15e1418010c --- /dev/null +++ b/dep/g3dlite/G3D/BoundsTrait.h @@ -0,0 +1,20 @@ +/** + @file BoundsTrait.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + @created 2008-10-01 + @edited 2008-10-01 + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_BOUNDSTRAIT_H +#define G3D_BOUNDSTRAIT_H + +#include "G3D/platform.h" + +template +struct BoundsTrait{}; + +#endif + diff --git a/dep/g3dlite/G3D/Box.h b/dep/g3dlite/G3D/Box.h new file mode 100644 index 00000000000..82af9125b05 --- /dev/null +++ b/dep/g3dlite/G3D/Box.h @@ -0,0 +1,195 @@ +/** + @file Box.h + + Box class + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @cite Portions based on Dave Eberly's Magic Software Library at http://www.magic-software.com + @created 2001-06-02 + @edited 2007-06-05 + + Copyright 2000-2006, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_BOX_H +#define G3D_BOX_H + +#include "G3D/platform.h" +#include "G3D/Vector3.h" +#include "G3D/Array.h" +#include "G3D/Plane.h" + +namespace G3D { + +class CoordinateFrame; + +/** + An arbitrary 3D box, useful as a bounding box. + + + To construct a box from a coordinate frame, center and extent, use the idiom: + + Box box = cframe.toObjectSpace(Box(center - extent/2, center + extent/2)); + */ +class Box { +private: + + static int32 dummy; + + friend class CoordinateFrame; + + /** +
+       3    2       7    6
+    
+       0    1       4    5
+
+       front    back (seen through front)
+      
+ */ + Vector3 _corner[8]; + + /** + Unit axes. + */ + Vector3 _axis[3]; + + Vector3 _center; + + /** + Extent along each axis. + */ + Vector3 _extent; + + float _area; + float _volume; + + void init( + const Vector3& min, + const Vector3& max); + +public: + + /** + Does not initialize the fields. + */ + Box(); + + /** + Constructs a box from two opposite corners. + */ + Box( + const Vector3& min, + const Vector3& max); + + static Box inf(); + + Box(class BinaryInput& b); + + Box(const class AABox& b); + + void serialize(class BinaryOutput& b) const; + void deserialize(class BinaryInput& b); + + /** + Returns the object to world transformation for + this box. localFrame().worldToObject(...) takes + objects into the space where the box axes are + (1,0,0), (0,1,0), (0,0,1). Note that there + is no scaling in this transformation. + */ + CoordinateFrame localFrame() const; + + void getLocalFrame(CoordinateFrame& frame) const; + + /** + Returns the centroid of the box. + */ + inline Vector3 center() const { + return _center; + } + + + inline Vector3 corner(int i) const { + debugAssert(i < 8); + return _corner[i]; + } + + /** + Unit length. + */ + inline Vector3 axis(int a) const { + debugAssert(a < 3); + return _axis[a]; + } + + /** + Distance from corner(0) to the next corner + along the box's local axis a. + */ + inline float extent(int a) const { + debugAssert(a < 3); + return (float)_extent[a]; + } + + inline Vector3 extent() const { + return _extent; + } + + /** + Returns the four corners of a face (0 <= f < 6). + The corners are returned to form a counter clockwise quad facing outwards. + */ + void getFaceCorners( + int f, + Vector3& v0, + Vector3& v1, + Vector3& v2, + Vector3& v3) const; + + + /** + See AABox::culledBy + */ + bool culledBy + ( + const Array& plane, + int32& cullingPlaneIndex, + const uint32 testMask, + uint32& childMask) const; + + /** + Conservative culling test that does not produce a mask for children. + */ + bool culledBy + ( + const Array& plane, + int32& cullingPlaneIndex = dummy, + const uint32 testMask = -1) const; + + bool contains( + const Vector3& point) const; + + float area() const; + + float volume() const; + + void getRandomSurfacePoint(Vector3& P, Vector3& N = Vector3::ignore()) const; + + /** + Uniformly distributed on the interior (includes surface) + */ + Vector3 randomInteriorPoint() const; + + void getBounds(class AABox&) const; + + bool isFinite() const { + return G3D::isFinite(_volume); + } +}; + +} + +#endif diff --git a/dep/g3dlite/G3D/Box2D.h b/dep/g3dlite/G3D/Box2D.h new file mode 100644 index 00000000000..80accad89dd --- /dev/null +++ b/dep/g3dlite/G3D/Box2D.h @@ -0,0 +1,121 @@ +/** + @file Box2D.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2001-06-02 + @edited 2008-12-27 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_Box2D_h +#define G3D_Box2D_h + +#include "G3D/platform.h" +#include "G3D/Vector2.h" + +namespace G3D { + +class CoordinateFrame; +typedef class CoordinateFrame CFrame; +class Rect2D; +typedef class Rect2D AABox2D; + +/** + 2D oriented box + @cite http://www.flipcode.com/archives/2D_OBB_Intersection.shtml + */ +class Box2D { +private: + /** Corners of the box, where 0 is the lower left. */ + Vector2 m_corner[4]; + + /** Two edges of the box extended away from corner[0], with length + = 1 / extentSquared */ + Vector2 m_axisin[2]; + + /** Two edges of the box extended away from corner[0], with unit length */ + Vector2 m_axis[2]; + + /** Centroid of the box */ + Vector2 m_center; + + /** origin[a] = m_corner[0].dot(m_axisin[a]); */ + float origin[2]; + + /** Surface area */ + float m_area; + + Vector2 m_extent; + + /** Returns true if other overlaps one dimension of this. */ + bool overlaps1Way(const Box2D& other) const; + + + /** Updates the axes after the m_corners move. Assumes the + m_corners actually form a rectangle. */ + void computeAxes(); + +public: + + /** + @param center World-space center + @param w Width along object-space x-axis + @param h Height along object-space y-axis + @param angle Counter-clockwise angle from object-space x-axis in radians + */ + Box2D(const Vector2& center = Vector2(0, 0), float w = 0, float h = 0, float angle = 0); + + Box2D(const AABox2D& b); + + Box2D(const Vector2& min, const Vector2& max); + + /** Transform @a b by @a frame, discarding the Z components, and + compute the new box.*/ + Box2D(const CFrame& frame, Box2D& b); + + inline bool contains(const Vector2& v) const { + // Take to object space: + const Vector2& p = v - m_center; + float x = p.dot(m_axisin[0]); + float y = p.dot(m_axisin[1]); + + // Must be within extent/2 on both axes in object space + return (abs(x) <= 0.5f) && (abs(y) <= 0.5f); + } + + /** @brief Distance from corner(0) to the next corner along the box's local axis a. */ + inline const Vector2& extent() const { + return m_extent; + } + + /** @brief Unit length vector along axis @a a */ + inline const Vector2& axis(int a) const { + debugAssert(a == 0 || a == 1); + return m_axis[a]; + } + + /** @brief Surface area */ + inline float area() const { + return m_area; + } + + inline const Vector2& corner(int i) const { + debugAssert(i >=0 && i <= 3); + return m_corner[i]; + } + + inline const Vector2& center() const { + return m_center; + } + + /** Returns true if the intersection of the boxes is non-empty. */ + inline bool overlaps(const Box2D& other) const { + return overlaps1Way(other) && other.overlaps1Way(*this); + } +}; + +} // G3D +#endif diff --git a/dep/g3dlite/G3D/BumpMapPreprocess.h b/dep/g3dlite/G3D/BumpMapPreprocess.h new file mode 100644 index 00000000000..955f99e61b2 --- /dev/null +++ b/dep/g3dlite/G3D/BumpMapPreprocess.h @@ -0,0 +1,61 @@ +/** + \file BumpMapPreprocess.h + + \maintainer Morgan McGuire, http://graphics.cs.williams.edu + + \created 2010-01-28 + \edited 2010-01-28 + + Copyright 2000-2010, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_BumpMapPreprocess_h +#define G3D_BumpMapPreprocess_h + +#include "G3D/platform.h" + +namespace G3D { +class Any; + +/** +Not in the BumpMap class to avoid a circular dependency between Texture and BumpMap. +G3D::GImage::computeNormalMap(). +*/ +class BumpMapPreprocess { +public: + + /** If true, the elevations are box filtered after computing normals + and before uploading, which produces better results for parallax offset mapping + Defaults to false. */ + bool lowPassFilter; + + /** Height of the maximum ("white") value, in pixels, for the purpose of computing normals. + A value of 255 means that a 255 x 255 bump image with a full black-to-white gradient + will produce a 45-degree ramp (this also results in "cubic" voxels). + A negative value means to set zExtentPixels to -zExtentPixels * max(width, height). + The default is -0.02. + */ + float zExtentPixels; + + /** After computing normals, scale the height by |N.z|, a trick that reduces texture swim in steep areas for parallax offset + mapping. Defaults to false.*/ + bool scaleZByNz; + + BumpMapPreprocess() : lowPassFilter(false), zExtentPixels(-0.02f), scaleZByNz(false) {} + + BumpMapPreprocess(const Any& any); + + operator Any() const; + + bool operator==(const BumpMapPreprocess& other) const { + return + (lowPassFilter == other.lowPassFilter) && + (zExtentPixels == other.zExtentPixels) && + (scaleZByNz == other.scaleZByNz); + } +}; + +} + +#endif diff --git a/dep/g3dlite/G3D/Capsule.h b/dep/g3dlite/G3D/Capsule.h new file mode 100644 index 00000000000..baeea3aa82b --- /dev/null +++ b/dep/g3dlite/G3D/Capsule.h @@ -0,0 +1,90 @@ +/** + @file Capsule.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2003-02-07 + @edited 2005-08-20 + + Copyright 2000-2006, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_CAPSULE_H +#define G3D_CAPSULE_H + +#include "G3D/platform.h" +#include "G3D/g3dmath.h" +#include "G3D/Vector3.h" + +namespace G3D { + +class Line; +class AABox; +/** + A shape formed by extruding a sphere along a line segment. + */ +class Capsule { +private: + Vector3 p1; + Vector3 p2; + + float _radius; +public: + + + /** Uninitialized */ + Capsule(); + Capsule(class BinaryInput& b); + Capsule(const Vector3& _p1, const Vector3& _p2, float _r); + void serialize(class BinaryOutput& b) const; + void deserialize(class BinaryInput& b); + + /** The line down the center of the capsule */ + Line axis() const; + + inline float radius() const { + return _radius; + } + + /** Argument may be 0 or 1 */ + inline Vector3 point(int i) const { + debugAssert(i == 0 || i == 1); + return (i == 0) ? p1 : p2; + } + + /** Distance between the sphere centers. The total extent of the cylinder is + 2r + h. */ + inline float height() const { + return (p1 - p2).magnitude(); + } + + inline Vector3 center() const { + return (p1 + p2) / 2.0; + } + + /** Get a reference frame in which the center of mass is the origin and Y is the axis of the capsule.*/ + void getReferenceFrame(class CoordinateFrame& cframe) const; + + /** + Returns true if the point is inside the capsule or on its surface. + */ + bool contains(const Vector3& p) const; + + float volume() const; + + float area() const; + + /** Get axis aligned bounding box */ + void getBounds(AABox& out) const; + + /** Random world space point with outward facing normal. */ + void getRandomSurfacePoint(Vector3& P, Vector3& N) const; + + /** Point selected uniformly at random over the volume. */ + Vector3 randomInteriorPoint() const; +}; + +} // namespace + +#endif diff --git a/dep/g3dlite/G3D/CollisionDetection.h b/dep/g3dlite/G3D/CollisionDetection.h new file mode 100644 index 00000000000..c8fcf5534c2 --- /dev/null +++ b/dep/g3dlite/G3D/CollisionDetection.h @@ -0,0 +1,1205 @@ +/** + @file CollisionDetection.h + + + Moving collision detection for simple primitives. + + @author Morgan McGuire, http://graphics.cs.williams.edu + @cite Spherical collision based on Paul Nettle's + ftp://ftp.3dmaileffects.com/pub/FluidStudios/CollisionDetection/Fluid_Studios_Generic_Collision_Detection_for_Games_Using_Ellipsoids.pdf + and comments by Max McGuire. Ray-sphere intersection by Eric Haines. + Box-Box intersection written by Kevin Egan. + Thanks to Max McGuire of Iron Lore for various bug fixes. + Box-Triangle by Tomas Akenine-Moller + + @created 2001-11-19 + @edited 2008-12-19 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_COLLISIONDETECTION_H +#define G3D_COLLISIONDETECTION_H + +#include "G3D/platform.h" +#include "G3D/Vector3.h" +#include "G3D/Plane.h" +#include "G3D/Box.h" +#include "G3D/Triangle.h" +#include "G3D/Array.h" +#include "G3D/Ray.h" +#include "G3D/Line.h" + +namespace G3D { + + +/** + Collision detection primitives and tools for building + higher order collision detection schemes. + + These routines provide moving and static collision detection. + Moving collision detection allows the calculation of collisions that + occur during a period of time -- as opposed to the intersection of + two static bodies. + + Moving collision detection routines detect collisions between + only static primitives and moving spheres or points. Since the + reference frame can be user defined, these functions can be used to + detect the collision between two moving bodies by subtracting + the velocity vector of one object from the velocity vector of the + sphere or point the detection is to occur with. This unified + velocity vector will act as if both objects are moving simultaneously. + + Collisions are detected for single-sided objects only. That is, + no collision is detected when leaving a primitive or passing + through a plane or triangle opposite the normal... except for the + point-sphere calculation or when otherwise noted. + + For a sphere, the collision location returned is the point in world + space where the surface of the sphere and the fixed object meet. + It is not the position of the center of the sphere at + the time of the collision. + + The collision normal returned is the surface normal to the fixed + object at the collision location. + +

+ Static Collision Detection: (Neither object is moving) + + + + + + + + + + + + + + +
Vector3LineSegmentRay *LinePlaneTriangleSphereCylinderCapsuleAABoxBox
Vector3\link Vector3::operator== V3::==\endlink \link Vector3::fuzzyEq V3::fuzzy \endlink \link G3D::distance distance \endlink
LineSegment\link LineSegment::closestPoint LS::closestPoint\endlink \link LineSegment::distance LS::distance\endlink \link CollisionDetection::closestPointOnLineSegment CD\endlink
Ray *Ray::closestPoint Ray::distance
LineLine::closestPoint Line::distance\link CollisionDetection::closestPointsBetweenLineAndLine CD\endlink
Plane
Triangle
SphereSphere::contains\link CollisionDetection::collisionTimeForMovingPointFixedSphere CD \endlink, \link Ray::intersectionTime R::time\endlink
CylinderCylinder::contains
CapsuleCapsule::contains
AABoxAABox::contains\link CollisionDetection::fixedSolidBoxIntersectsFixedTriangle CD\endlink
BoxBox::contains(treat as Ray)\link CollisionDetection::collisionTimeForMovingPointFixedBox CD\endlink(treat as Ray)\link CollisionDetection::penetrationDepthForFixedBoxFixedPlane CD \endlink\link CollisionDetection::penetrationDepthForFixedBoxFixedPlane CD\endlink\link CollisionDetection::penetrationDepthForFixedSphereFixedBox CD\endlinkNone (use OPCODE)\link CollisionDetection::movingSpherePassesThroughFixedBox CD \endlink\link CollisionDetection::penetrationDepthForFixedBoxFixedBox CD\endlink\link CollisionDetection::penetrationDepthForFixedBoxFixedBox CD\endlink
+ +

+ Moving Collision Detection: + + * Note: Moving collision detection against certain primitives is equivalent to static collision + detection against a bigger primitive. Ray, Line Segment == ``moving Point''; Capsule ==``moving Sphere''; Plane == ``moving Line'' + + @deprecated Routines moving to the G3D::Intersect class in G3D 8.0 + */ +class CollisionDetection { +private: + + /** + Default parameter if value passed to a function as reference is + not to be calculated. Must be explicitly supported by function. + */ + static Vector3 ignore; + + /** + Default parameter if value passed to a function as reference is + not to be calculated. Must be explicitly supported by function. + */ + static bool ignoreBool; + + /** + Default parameter if value passed to a function as reference is + not to be calculated. Must be explicitly supported by function. + */ + static Array ignoreArray; + + + // Static class! + CollisionDetection() {} + virtual ~CollisionDetection() {} + +public: + + /** + Converts an index [0, 15] to the corresponding separating axis. + Does not return normalized vector in the edge-edge case + (indices 6 through 15). + + @param separatingAxisIndex Separating axis. + @param box1 Box 1. + @param box2 Box 2. + + @return Axis that separates the two boxes. + */ + static Vector3 separatingAxisForSolidBoxSolidBox( + const int separatingAxisIndex, + const Box & box1, + const Box & box2); + + /** + Tests whether two boxes have axes that are parallel to + each other. If they are, axis1 and axis2 are set to be + the parallel axes for both box1 and box2 respectively. + + @param ca Dot products of each of the boxes axes + @param epsilon Fudge factor (small unit by which the dot + products may vary and still be considered + zero). + @param axis1 Parallel Axis 1. [Post Condition] + @param axis2 Parallel Axis 2. [Post Condition] + + @return true - If boxes have a parallel axis + @return false - otherwise. + */ + static bool parallelAxisForSolidBoxSolidBox( + const double* ca, + const double epsilon, + int & axis1, + int & axis2); + + /** + Calculates the projected distance between the two boxes along + the specified separating axis, negative distances correspond + to an overlap along that separating axis. The distance is not + divided by denominator dot(L, L), see + penetrationDepthForFixedSphereFixedBox() for more details + + @param separatingAxisIndex + @param a Box 1's bounding sphere vector + @param b Box 2's bounding sphere vector + @param D Vector between Box 1 and Box 2's center points + @param c Pointer to array of dot products of the axes of Box 1 + and Box 2. + @param ca Pointer to array of unsigned dot products of the axes + of Box 1 and Box 2. + @param ad Pointer to array of dot products of Box 1 axes and D. + @param bd Pointer to array of dot products of Box 2 axes and D. + + @return Projected distance between the two boxes along the + specified separating axis. + */ + static float projectedDistanceForSolidBoxSolidBox( + const int separatingAxisIndex, + const Vector3 & a, + const Vector3 & b, + const Vector3 & D, + const double* c, + const double* ca, + const double* ad, + const double* bd); + + + /** + Creates a set of standard information about two boxes in order to + solve for their collision. This information includes a vector to + the radius of the bounding sphere for each box, the vector between + each boxes' center and a series of dot products between differing + important vectors. These dot products include those between the axes + of both boxes (signed and unsigned values), and the dot products + between all the axes of box1 and the boxes' center vector and box2 + and the boxes' center vector. + + @pre The following space requirements must be met: + - c[] 9 elements + - ca[] 9 elements + - ad[] 3 elements + - bd[] 3 elements + + @cite dobted from David Eberly's papers, variables used in this function + correspond to variables used in pages 6 and 7 in the pdf + http://www.magic-software.com/Intersection.html + http://www.magic-software.com/Documentation/DynamicCollisionDetection.pdf + + @note Links are out-dated. (Kept to preserve origin and authorship) + + @param box1 Box 1 + @param box2 Box 2 + @param a Box 1's bounding sphere vector + @param b Box 2's bounding sphere vector + @param D Vector between Box 1 and Box 2's center points + @param c Pointer to array of dot products of the axes of Box 1 + and Box 2. + @param ca Pointer to array of unsigned dot products of the axes + of Box 1 and Box 2. + @param ad Pointer to array of dot products of Box 1 axes and D. + @param bd Pointer to array of dot products of Box 2 axes and D. + */ + static void fillSolidBoxSolidBoxInfo( + const Box & box1, + const Box & box2, + Vector3 & a, + Vector3 & b, + Vector3 & D, + double* c, + double* ca, + double* ad, + double* bd); + + /** + Performs a simple bounding sphere check between two boxes to determine + whether these boxes could possibly intersect. This is a very + cheap operation (three dot products, two sqrts and a few others). If + it returns true, an intersection is possible, but not necessarily + guaranteed. + + @param a Vector from box A's center to an outer vertex + @param b Vector from box B's center to an outer vertex + @param D Distance between the centers of the two boxes + + @return true - if possible intersection + @return false - otherwise (This does not guarantee an intersection) + */ + static bool conservativeBoxBoxTest( + const Vector3 & a, + const Vector3 & b, + const Vector3 & D); + + /** + Determines whether two fixed solid boxes intersect. + + @note To speed up collision detection, the lastSeparatingAxis from + the previous time step can be passed in and that plane can be + checked first. If the separating axis was not saved, or if the + two boxes intersected then lastSeparatingAxis should equal -1. + + @cite Adobted from David Eberly's papers, variables used in this function + correspond to variables used in pages 6 and 7 in the pdf + http://www.magic-software.com/Intersection.html + http://www.magic-software.com/Documentation/DynamicCollisionDetection.pdf + + @param box1 Box 1. + @param box2 Box 2. + @param lastSeparatingAxis Last separating axis. + (optimization - see note) + + @return true - Intersection. + @return false - otherwise. + */ + static bool fixedSolidBoxIntersectsFixedSolidBox( + const Box& box1, + const Box& box2, + const int lastSeparatingAxis = -1); + + /** + Calculates the closest points on two lines with each other. If the + lines are parallel then using the starting point, else calculate the + closest point on each line to the other. + + @note This is very similiar to calculating the intersection of two lines. + Logically then, the two points calculated would be identical if calculated + with inifinite precision, but with the finite precision of floating point + calculations, these values could (will) differ as the line slope approaches + zero or inifinity. + + @cite variables and algorithm based on derivation at the following website: + http://softsurfer.com/Archive/algorithm_0106/algorithm_0106.htm + + @param line1 Line 1. + @param line2 Line 2. + @param closest1 Closest point on line 1. + @param closest2 Closest point on line 2. + */ + static void closestPointsBetweenLineAndLine( + const Line & line1, + const Line & line2, + Vector3 & closest1, + Vector3 & closest2); + + /** + Calculates the depth of penetration between two fixed boxes. + Contact normal faces away from box1 and into box2. If there is + contact, only one contact point is returned. The minimally + violated separating plane is computed + - if the separating axis corresponds to a face + the contact point is half way between the deepest vertex + and the face + - if the separating axis corresponds to two edges + the contact point is the midpoint of the smallest line + segment between the two edge lines + + @note This is very similiar to calculating the intersection of two lines. + Logically then, the two points calculated would be identical if calculated + with inifinite precision, but with the finite precision of floating point + calculations, these values could (will) differ as the line slope approaches + zero or inifinity. + + @cite adobted from David Eberly's papers, variables used in this function + correspond to variables used in pages 6 and 7 in the pdf + http://www.magic-software.com/Intersection.html + http://www.magic-software.com/Documentation/DynamicCollisionDetection.pdf + + @param box1 Box 1 + @param box2 Box 2 + @param contactPoints Contact point between boxes. [Post Condition] + @param contactNormals Surface normal at contact point. [Post Condition] + @param lastSeparatingAxis Last separating axis. (Used for optimization) + + @return Depth of penetration between the two boxes. If there is no + intersection between the boxes, then a negative value is returned. + */ + static float penetrationDepthForFixedBoxFixedBox( + const Box& box1, + const Box& box2, + Array& contactPoints, + Array& contactNormals, + const int lastSeparatingAxis = -1); + + /** + Calculates the depth of penetration between two fixed spheres as well + as the deepest point of Sphere A that penetrates Sphere B. The normal + returned points away from the object A, although it may + represent a perpendicular to either the faces of object B or object A + depending on their relative orientations. + + @param sphereA Fixed Sphere A. + @param sphereB Fixed Sphere B. + @param contactPoints Sphere A's deepest point that penetrates Sphere B. + [Post Condition] + @param contactNormals Normal at penetration point. [Post Condition] + + @return Depth of penetration. If there is no intersection between the + objects then the depth will be a negative value. + */ + static float penetrationDepthForFixedSphereFixedSphere( + const class Sphere& sphereA, + const Sphere& sphereB, + Array& contactPoints, + Array& contactNormals = ignoreArray); + + /** + Calculates the depth of penetration between a fixed sphere and a fixed + box as well as the deepest point of the sphere that penetrates the box + and the normal at that intersection. + + @note There are three possible intersections between a sphere and box. + - Sphere completely contained in the box + - Sphere intersects one edge + - Sphere intersects one vertex + + The contact point and contact normal vary for each of these situations. + - Sphere contained in Box: + - Normal is based on side of least penetration (as is the depth calculation). + - Point is based on center of sphere + - Sphere intersects one edge + - Normal is based on vector from the box center to the point of depth. + - Point is closest point to the sphere on the line + - Sphere intersects one vertex + - Normal is based on vector from the box center to the vertex of penetration. + - Point is vertex of penetration. + + @cite Adapted from Jim Arvo's method in Graphics Gems + See also http://www.win.tue.nl/~gino/solid/gdc2001depth.pdf + + @param sphere Fixed Sphere. + @param box Fixed Box. + @param contactPoints Sphere point that penetrates the box. [Post Condition] + @param contactNormals Normal at the penetration point. [Post Condition] + + @return Depth of penetration. If there is no intersection between the + objects then the depth will be a negative value. + */ + static float penetrationDepthForFixedSphereFixedBox( + const Sphere& sphere, + const Box& box, + Array& contactPoints, + Array& contactNormals = ignoreArray); + + /** + Calculates the depth of penetration between a Fixed Sphere and a Fixed + Plane as well as the deepest point of the sphere that penetrates the plane + and the plane normal at that intersection. + + @param sphereA Fixed Sphere. + @param planeB Fixed Plane. + @param contactPoints Sphere point that penetrates the plane. + [Post Condition] + @param contactNormals Normal at penetration point. [Post Condition] + + @return Depth of penetration. If there is no intersection between the + objects then the depth will be a negative value. + */ + static float penetrationDepthForFixedSphereFixedPlane( + const Sphere& sphereA, + const class Plane& planeB, + Array& contactPoints, + Array& contactNormals = ignoreArray); + + /** + Calculates the depth of penetration between a fixed box and a fixed + plane as well as the vertexes of the box that penetrate the plane + and the plane normals at those intersections. + + @param box Fixed Box. + @param plane Fixed Plane. + @param contactPoints Box points that penetrate the plane. + [Post Condition] + @param contactNormals Normals at penetration points [Post Condition] + + @return Depth of penetration. If there is no intersection between the + objects then the depth will be a negative value. + */ + static float penetrationDepthForFixedBoxFixedPlane( + const Box& box, + const Plane& plane, + Array& contactPoints, + Array& contactNormals = ignoreArray); + + /** + Calculates time between the intersection of a moving point and a fixed + plane. + + @note This is only a one sided collision test. The side defined by + the plane's surface normal is the only one tested. For a two sided + collision, call the function once for each side's surface normal. + + @param point Moving point. + @param velocity Point's velocity. + @param plane Fixed plane. + @param location Location of collision. [Post Condition] + (Infinite vector on no collision) + @param outNormal Plane's surface normal. [Post Condition] + + @return Time til collision. If there is no collision then the return + value will be inf(). + */ + static float collisionTimeForMovingPointFixedPlane( + const Vector3& point, + const Vector3& velocity, + const class Plane& plane, + Vector3& outLocation, + Vector3& outNormal = ignore); + + /** + Calculates time between the intersection of a moving point and a fixed + triangle. + + @note This is only a one sided collision test. The side defined by + the triangle's surface normal is the only one tested. For a two sided + collision, call the function once for each side's surface normal. + + @param orig Moving point. + @param dir Point's velocity. + @param v0 Triangle vertex 1. + @param v1 Triangle vertex 2. + @param v2 Triangle vertex 3 + + @return Time til collision. If there is no collision then the return + value will be inf(). + */ + inline static float collisionTimeForMovingPointFixedTriangle( + const Vector3& orig, + const Vector3& dir, + const Vector3& v0, + const Vector3& v1, + const Vector3& v2) { + return Ray::fromOriginAndDirection(orig, dir).intersectionTime(v0, v1, v2); + } + + /** + Calculates time between the intersection of a moving point and a fixed + triangle. + + @note This is only a one sided collision test. The side defined by + the triangle's surface normal is the only one tested. For a two sided + collision, call the function once for each side's surface normal. + + @param orig Moving point. + @param dir Point's velocity. + @param v0 Triangle vertex 1. + @param v1 Triangle vertex 2. + @param v2 Triangle vertex 3 + @param location Location of collision. [Post Condition] + (Infinite vector on no collision) + + @return Time til collision. If there is no collision then the return + value will be inf(). + */ + inline static float collisionTimeForMovingPointFixedTriangle( + const Vector3& orig, + const Vector3& dir, + const Vector3& v0, + const Vector3& v1, + const Vector3& v2, + Vector3& location) { + float t = collisionTimeForMovingPointFixedTriangle(orig, dir, v0, v1, v2); + if (t < finf()) { + location = orig + dir * t; + } + return t; + } + + /** + Calculates time between the intersection of a moving point and a fixed + triangle. + + @note This is only a one sided collision test. The side defined by + the triangle's surface normal is the only one tested. For a two sided + collision, call the function once for each side's surface normal. + + @param orig Moving point. + @param dir Point's velocity. + @param tri Fixed triangle. + @param location Location of collision. [Post Condition] + (Infinite vector on no collision) + @param normal Triangle's surface normal. [Post Condition] + + @return Time til collision. If there is no collision then the return + value will be inf(). + */ + inline static float collisionTimeForMovingPointFixedTriangle( + const Vector3& orig, + const Vector3& dir, + const Triangle& tri, + Vector3& location = ignore, + Vector3& normal = ignore) { + + float t = collisionTimeForMovingPointFixedTriangle( + orig, dir, tri.vertex(0), tri.vertex(1), tri.vertex(2)); + + if ((t < finf()) && (&location != &ignore)) { + location = orig + dir * t; + normal = tri.normal(); + } + return t; + } + + /** + Calculates time between the intersection of a moving point and a fixed + triangle. + + @note This is only a one sided collision test. The side defined by + the triangle's surface normal is the only one tested. For a two sided + collision, call the function once for each side's surface normal. + + @param orig Moving point. + @param dir Point's velocity. + @param v0 Triangle vertex 1. + @param v1 Triangle vertex 2. + @param v2 Triangle vertex 3 + @param location Location of collision. [Post Condition] + (Infinite vector on no collision) + @param normal Triangle's surface normal. [Post Condition] + + @return Time til collision. If there is no collision then the return + value will be inf(). + */ + inline static float collisionTimeForMovingPointFixedTriangle( + const Vector3& orig, + const Vector3& dir, + const Vector3& v0, + const Vector3& v1, + const Vector3& v2, + Vector3& location, + Vector3& normal) { + float t = collisionTimeForMovingPointFixedTriangle(orig, dir, v0, v1, v2); + if (t < finf()) { + location = orig + dir * t; + normal = (v1 - v0).cross(v2 - v0).direction(); + } + return t; + } + + /** + If the ray origin is inside the box, returns inf() but inside + is set to true. + Beta API + + @cite Andrew Woo, from "Graphics Gems", Academic Press, 1990 + @cite Optimized code by Pierre Terdiman, 2000 (~20-30% faster on Celeron 500) + @cite Epsilon value added by Klaus Hartmann + @cite http://www.codercorner.com/RayAABB.cpp + */ + static float collisionTimeForMovingPointFixedAABox( + const Vector3& point, + const Vector3& velocity, + const class AABox& box, + Vector3& outLocation, + bool& inside = ignoreBool, + Vector3& outNormal = ignore); + + /** + Calculates time between the intersection of a moving point and a fixed + Axis-Aligned Box (AABox). + + @note Avoids the sqrt from collisionTimeForMovingPointFixedAABox. + + @param point Moving point. + @param velocity Sphere's velocity. + @param box Fixed AAbox. + @param location Location of collision. [Post Condition] + @param Inside Does the ray originate inside the box? [Post Condition] + @param normal Box's surface normal to collision [Post Condition] + + @return Time til collision. If there is no collision then the return + value will be inf(). + */ + static bool collisionLocationForMovingPointFixedAABox( + const Vector3& point, + const Vector3& velocity, + const class AABox& box, + Vector3& outLocation, + bool& inside = ignoreBool, + Vector3& normal = ignore); + + + /** + @brief Calculates intersection of a ray and a static + Axis-Aligned Box (AABox). + + @note Avoids the sqrt from collisionTimeForMovingPointFixedAABox; + early-out branches and operations optimized for Intel Core2 architecture. + + @param invDir 1/dir + @param location Location of collision. [Post Condition] + @param inside Does the ray originate inside the box? [Post Condition] + + @return True if the ray hits the box + */ + static bool __fastcall rayAABox( + const Ray& ray, + const Vector3& invDir, + const AABox& box, + const Vector3& boxCenter, + float boundingRadiusSquared, + Vector3& location, + bool& inside); + + /** + Calculates time between the intersection of a moving point and a fixed + sphere. + + @note When ray is starts inside the rectangle, the exiting intersection + is detected. + + @param point Moving point. + @param velocity Point's velocity. + @param sphere Fixed Sphere. + @param outLocation Location of collision. [Post Condition] + @param outNormal Sphere's surface normal to collision [Post Condition] + \param solid If true, rays inside the sphere immediately intersect (good for collision detection). If false, they hit the opposite side of the sphere (good for ray tracing). + + @return Time until collision. If there is no collision then the return + value will be inf(). + */ + static float collisionTimeForMovingPointFixedSphere( + const Vector3& point, + const Vector3& velocity, + const class Sphere& sphere, + Vector3& outLocation, + Vector3& outNormal = ignore, + bool solid = false); + + /** + Calculates time between the intersection of a moving point and a fixed + box. + + @note If the point is already inside the box, no collision: inf is returned. + + @param point Moving point. + @param velocity Sphere's velocity. + @param box Fixed box. + @param location Position of collision. [Post Condition] + @param outNormal Box's surface normal to collision [Post Condition] + + @return Time til collision. If there is no collision then the return + value will be inf(). + */ + static float collisionTimeForMovingPointFixedBox( + const Vector3& point, + const Vector3& velocity, + const class Box& box, + Vector3& outLocation, + Vector3& outNormal = ignore); + + /** + Calculates time between the intersection of a moving point and a fixed + rectangle defined by the points v0, v1, v2, & v3. + + @note This is only a one sided collision test. The side defined by + the rectangle's surface normal is the only one tested. For a two sided + collision, call the function once for each side's surface normal. + + @param point Moving point. + @param velocity Sphere's velocity. + @param v0 Rectangle vertex 1. + @param v1 Rectangle vertex 2. + @param v2 Rectangle vertex 3 + @param v3 Rectangle vertex 4. + @param location Location of collision [Post Condition] + @param outNormal Rectangle's surface normal. [Post Condition] + + @return Time til collision. If there is no collision then the return + value will be inf(). + */ + static float collisionTimeForMovingPointFixedRectangle( + const Vector3& point, + const Vector3& velocity, + const Vector3& v0, + const Vector3& v1, + const Vector3& v2, + const Vector3& v3, + Vector3& outLocation, + Vector3& outNormal = ignore); + + /** + Calculates time between the intersection of a moving point and a fixed + capsule. + + @param point Moving point. + @param velocity Point's velocity. + @param capsule Fixed capsule. + @param outLocation Location of collision. [Post Condition] + @param outNormal Capsule's surface normal to collision [Post Condition] + + @return Time til collision. If there is no collision then the return + value will be inf(). + */ + static float collisionTimeForMovingPointFixedCapsule( + const Vector3& point, + const Vector3& velocity, + const class Capsule& capsule, + Vector3& outLocation, + Vector3& outNormal = ignore); + + /** + Calculates time between the intersection of a moving sphere and a fixed + triangle. + + @param sphere Moving sphere. + @param velocity Sphere's velocity. + @param plane Fixed Plane. + @param outLocation Location of collision -- not center position of sphere + at the collision time. [Post Condition] + @param outNormal Box's surface normal to collision [Post Condition] + + @return Time til collision. If there is no collision then the return + value will be inf(). + */ + static float collisionTimeForMovingSphereFixedPlane( + const class Sphere& sphere, + const Vector3& velocity, + const class Plane& plane, + Vector3& outLocation, + Vector3& outNormal = ignore); + + /** + Calculates time between the intersection of a moving sphere and a fixed + triangle. + + @param sphere Moving sphere. + @param velocity Sphere's velocity. + @param triangle Fixed Triangle. (collisions can happen on the back side of the triangle) + @param outLocation Location of collision, if collision occurs -- not center position of sphere + at the collision time. If there is interpenetration at the start, this point may be inside + the sphere. + @param b Barycentric coordinates. These are not valid unless collision occurs. + + @return Time til collision. If there is no collision then the return + value will be inf(). + */ + static float collisionTimeForMovingSphereFixedTriangle( + const class Sphere& sphere, + const Vector3& velocity, + const Triangle& triangle, + Vector3& outLocation, + float b[3] = (float*)&ignore); + + /** + Calculates time between the intersection of a moving sphere and a fixed + rectangle defined by the points v0, v1, v2, & v3. + + @param sphere Moving sphere. + @param velocity Sphere's velocity. + @param v0 Rectangle vertex 1. + @param v1 Rectangle vertex 2. + @param v2 Rectangle vertex 3 + @param v3 Rectangle vertex 4. + @param outLocation Location of collision -- not center position of sphere + at the collision time. [Post Condition] + @param outNormal Box's surface normal to collision [Post Condition] + + @return Time til collision. If there is no collision then the return + value will be inf(). + */ + static float collisionTimeForMovingSphereFixedRectangle( + const class Sphere& sphere, + const Vector3& velocity, + const Vector3& v0, + const Vector3& v1, + const Vector3& v2, + const Vector3& v3, + Vector3& outLocation, + Vector3& outNormal = ignore); + + /** + Calculates time between the intersection of a moving sphere and a fixed + box. + + @note This function will not detect an intersection between a moving object + that is already interpenetrating the fixed object. + + @param sphere Moving sphere. + @param velocity Sphere's velocity. + @param box Fixed box. + @param location Location of collision -- not center position of sphere + at the collision time. [Post Condition] + @param outNormal Box's surface normal to collision [Post Condition] + + @return Time til collision. If there is no collision then the return + value will be inf(). + */ + static float collisionTimeForMovingSphereFixedBox( + const class Sphere& sphere, + const Vector3& velocity, + const class Box& box, + Vector3& outLocation, + Vector3& outNormal = ignore); + + /** Calculates time between the intersection of a moving sphere + and a fixed sphere. + + If they are already interpenetrating, returns 0 and @a + location is the closest point on the surface of the fixed sphere + to the center of the moving sphere. + + @param sphere Moving sphere. + @param velocity Sphere's velocity. + @param fixedSphere Fixed Sphere. + @param outLocation Location of collision -- not center position of sphere + at the collision time. [Post Condition] + @param outNormal Moving sphere's surface normal to collision [Post Condition] + + @return Time until collision. If there is no collision then the return + value will be inf(). + */ + static float collisionTimeForMovingSphereFixedSphere( + const Sphere& sphere, + const Vector3& velocity, + const Sphere& fixedSphere, + Vector3& outLocation, + Vector3& outNormal = ignore); + + /** + Calculates time between the intersection of a moving sphere and a fixed + capsule. + + @note This won't detect a collision if the sphere is already + interpenetrating the capsule. + + @param sphere Moving sphere. + @param velocity Sphere's velocity. + @param capsule Fixed capsule. + @param location Location of collision -- not center position of sphere + at the collision time. [Post Condition] + @param outNormal Capsule's surface normal to the collision [Post Condition] + + @return Time til collision. If there is no collision then the return + value will be inf(). + */ + static float collisionTimeForMovingSphereFixedCapsule( + const class Sphere& sphere, + const Vector3& velocity, + const class Capsule& capsule, + Vector3& outLocation, + Vector3& outNormal = ignore); + + /** + Finds the direction of bounce that a sphere would have when it + intersects an object with the given time of collision, the + collision location and the collision normal. + + @note This function works like a pong style ball bounce. + + @param sphere Moving sphere. + @param velocity Sphere's velocity. + @param collisionTime Time of collision. + @param collisionLocation Collision location. + @param collisionNormal Surface collision normal. + + @return Direction of bounce. + */ + static Vector3 bounceDirection( + const class Sphere& sphere, + const Vector3& velocity, + const float collisionTime, + const Vector3& collisionLocation, + const Vector3& collisionNormal); + + /** + Finds the direction of slide given a moving sphere, its velocity, the + time of collision and the collision location. This function works as + if the sphere intersects the surface and continues to hug it. + + @note The result will work well for calculating the movement of a player + who collides with an object and continues moving along the object instead + of just bouncing off it. + + @param sphere Moving sphere. + @param velocity Sphere's velocity. + @param collisionTime Time of collision + @param collisionLocation Collision location. + + @return Direction of slide. + */ + static Vector3 slideDirection( + const class Sphere& sphere, + const Vector3& velocity, + const float collisionTime, + const Vector3& collisionLocation); + + /** + Finds the closest point on a line segment to a given point. + + @param v0 line vertex 1. + @param v1 line vertex 2. + @param point External point. + + @return Closests point to point on the line segment. + */ + static Vector3 closestPointOnLineSegment( + const Vector3& v0, + const Vector3& v1, + const Vector3& point); + + /** + Finds the closest point on a line segment to a given point. + + @note This is an optimization to closestPointOnLineSegment. Edge length + and direction can be used in this function if already pre-calculated. This + prevents doing the same work twice. + + @param v0 line vertex 0. + @param v1 line vertex 1. + @param edgeDirection The direction of the segment (unit length). + @param edgeLength The length of the segment. + @param point External point. + + @return Closests point to point on the line segment. + */ + static Vector3 closestPointOnLineSegment( + const Vector3& v0, + const Vector3& v1, + const Vector3& edgeDirection, + float edgeLength, + const Vector3& point); + + /** + Finds the closest point on the perimeter of the triangle to an external point; + given a triangle defined by three points v0, v1, & v2, and the external point. + + @param v0 Triangle vertex 0. + @param v1 Triangle vertex 1. + @param v2 Triangle vertex 2. + @param point External point. + + @return Closests point to point on the perimeter of the + triangle. + */ + static Vector3 closestPointOnTrianglePerimeter( + const Vector3& v0, + const Vector3& v1, + const Vector3& v2, + const Vector3& point); + + /** + Finds the closest point on the perimeter of the triangle to an external point; + given a triangle defined by the array of points v, its edge directions and + their lengths, as well as the external point. + + @note This is an optimization to closestPointToTrianglePerimeter. Edge length + and direction can be used in this function if already pre-calculated. This + prevents doing the same work twice. + + @param v Triangle vertices. + @param point External point. + @param edgeIndex The point lies on the edge between v[edgeIndex] and v[(edgeIndex + 1) % 3] + + @return Closest point to point on the perimeter of the + triangle. + */ + static Vector3 closestPointOnTrianglePerimeter( + const Vector3 v[3], + const Vector3 edgeDirection[3], + const float edgeLength[3], + const Vector3& point, + int& edgeIndex); + + /** + Tests whether a point is contained within the triangle defined by + v0, v1, and v2 and its plane's normal. + + @param v0 Triangle vertex 0. + @param v1 Triangle vertex 1. + @param v2 Triangle vertex 2. + @param normal Normal to triangle's plane. + @param point The point in question. + @param primaryAxis Primary axis of triangle. This will be detected + if not given. This parameter is provided as an optimization. + @param b Barycentric coordinates; b[i] is the weight on v[i] + + @return true - if point is inside the triangle. + @return false - otherwise + */ + static bool isPointInsideTriangle( + const Vector3& v0, + const Vector3& v1, + const Vector3& v2, + const Vector3& normal, + const Vector3& point, + float b[3], + Vector3::Axis primaryAxis = Vector3::DETECT_AXIS); + + inline static bool isPointInsideTriangle( + const Vector3& v0, + const Vector3& v1, + const Vector3& v2, + const Vector3& normal, + const Vector3& point, + Vector3::Axis primaryAxis = Vector3::DETECT_AXIS) { + + float b[3]; + return isPointInsideTriangle(v0, v1, v2, normal, point, b, primaryAxis); + } + + /** + Tests for the intersection of a moving sphere and a fixed box in a + given time limit. + + @note Returns true if any part of the sphere is inside the box + during the time period (inf means "ever"). Useful for + performing bounding-box collision detection. + + @param sphere Moving sphere. + @param velocity Velocity of moving sphere. + @param box Fixed box. + @param timeLimit Time limit for intersection test. + + @return true - if the two objects will touch. + @return false - if there is no intersection. + */ + static bool movingSpherePassesThroughFixedBox( + const Sphere& sphere, + const Vector3& velocity, + const Box& box, + double timeLimit = inf()); + + /** + Tests for the intersection of a moving sphere and a fixed sphere in a + given time limit. + + @note This function will not detect an intersection between a moving object + that is already interpenetrating the fixed object. + + @param sphere Moving sphere. + @param velocity Velocity of moving sphere. + @param fixedSphere Fixed sphere. + @param timeLimit Time limit for intersection test. + + @return true - if the two spheres will touch. + @return false - if there is no intersection. + */ + static bool movingSpherePassesThroughFixedSphere( + const Sphere& sphere, + const Vector3& velocity, + const Sphere& fixedSphere, + double timeLimit = inf()); + + /** + Tests for the intersection of two fixed spheres. + + @param sphere1 Fixed sphere 1. + @param sphere2 Fixed sphere 2. + + @return true - if the two spheres touch. + @return false - if there is no intersection. + */ + static bool fixedSolidSphereIntersectsFixedSolidSphere( + const Sphere& sphere1, + const Sphere& sphere2); + + /** + Tests for the intersection of a fixed sphere and a fixed box. + + @param sphere Fixed sphere. + @param box Fixed box. + + @return true - if the two objects touch. + @return false - if there is no intersection. + */ + static bool fixedSolidSphereIntersectsFixedSolidBox( + const Sphere& sphere, + const Box& box); + + static bool fixedSolidSphereIntersectsFixedTriangle( + const Sphere& sphere, + const Triangle& triangle); + + static bool fixedSolidBoxIntersectsFixedTriangle( + const AABox& box, + const Triangle& triangle); + + /** + Tests whether a point is inside a rectangle defined by the vertexes + v0, v1, v2, & v3, and the rectangle's plane normal. + + @param v0 Rectangle vertex 1. + @param v1 Rectangle vertex 2. + @param v2 Rectangle vertex 3. + @param v3 Rectangle vertex 4. + @param normal Normal to rectangle's plane. + @param point The point in question. + + @return true - if point is inside the rectangle. + @return false - otherwise + */ + static bool isPointInsideRectangle( + const Vector3& v0, + const Vector3& v1, + const Vector3& v2, + const Vector3& v3, + const Vector3& normal, + const Vector3& point); + + /** + Finds the closest point on the perimeter of the rectangle to an + external point; given a rectangle defined by four points v0, v1, + v2, & v3, and the external point. + + @param v0 Rectangle vertex 1. + @param v1 Rectangle vertex 2. + @param v2 Rectangle vertex 3. + @param v3 Rectangle vertex 4. + @param point External point. + + @return Closests point to point on the perimeter of the + rectangle. + */ + static Vector3 closestPointToRectanglePerimeter( + const Vector3& v0, + const Vector3& v1, + const Vector3& v2, + const Vector3& v3, + const Vector3& point); + + /** + Finds the closest point in the rectangle to an external point; Given + a rectangle defined by four points v0, v1, v2, & v3, and the external + point. + + @param v0 Rectangle vertex 1. + @param v1 Rectangle vertex 2. + @param v2 Rectangle vertex 3 + @param v3 Rectangle vertex 4. + @param point External point. + + @return Closet point in the rectangle to the external point. + */ + static Vector3 closestPointToRectangle( + const Vector3& v0, + const Vector3& v1, + const Vector3& v2, + const Vector3& v3, + const Vector3& point); +}; + +} // namespace + +#endif // G3D_COLLISIONDETECTION_H diff --git a/dep/g3dlite/G3D/Color1.h b/dep/g3dlite/G3D/Color1.h new file mode 100644 index 00000000000..0f68c84b363 --- /dev/null +++ b/dep/g3dlite/G3D/Color1.h @@ -0,0 +1,144 @@ +/** + @file Color1.h + + Monochrome Color class + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + @created 2007-01-31 + @edited 2009-03-20 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_COLOR1_H +#define G3D_COLOR1_H + +#include "G3D/platform.h" +#include "G3D/g3dmath.h" +#include "G3D/HashTrait.h" +#include + +namespace G3D { + +/** + Monochrome color. This is just a float, but it has nice semantics + because a scaling by 255 automatically occurs when switching between + fixed point (Color1uint8) and floating point (Color1) formats. + */ +class Color1 { +private: + // Hidden operators + bool operator<(const Color1&) const; + bool operator>(const Color1&) const; + bool operator<=(const Color1&) const; + bool operator>=(const Color1&) const; + +public: + float value; + + /** + Initializes to 0 + */ + inline Color1() : value(0) {} + + Color1(class BinaryInput& bi); + + inline explicit Color1(float v) : value(v) { + } + + inline bool isZero() const { + return value == 0.0f; + } + + inline bool isOne() const { + return value == 1.0f; + } + + static const Color1& one(); + + static const Color1& zero(); + + /** Returns the value three times */ + class Color3 rgb() const; + + Color1 (const class Color1uint8& other); + + void serialize(class BinaryOutput& bo) const; + void deserialize(class BinaryInput& bi); + + Color1 operator+ (const Color1& other) const { + return Color1(value + other.value); + } + + Color1 operator+ (const float other) const { + return Color1(value + other); + } + + Color1& operator+= (const Color1 other) { + value += other.value; + return *this; + } + + Color1& operator-= (const Color1 other) { + value -= other.value; + return *this; + } + + Color1 operator- (const Color1& other) const { + return Color1(value - other.value); + } + + Color1 operator- (const float other) const { + return Color1(value - other); + } + + Color1 operator- () const { + return Color1(-value); + } + + Color1 operator* (const Color1& other) const { + return Color1(value * other.value); + } + + Color1 operator* (const float other) const { + return Color1(value * other); + } + + Color1 operator/ (const Color1& other) const { + return Color1(value / other.value); + } + + Color1 operator/ (const float other) const { + return Color1(value / other); + } + + inline Color1 max(const Color1& other) const { + return Color1(G3D::max(value, other.value)); + } + + inline Color1 min(const Color1& other) const { + return Color1(G3D::min(value, other.value)); + } + + inline Color1 lerp(const Color1& other, float a) const { + return Color1(value + (other.value - value) * a); + + } + + inline size_t hashCode() const { + return (size_t)(value * 0xFFFFFF); + } +}; + +} + +template <> +struct HashTrait { + static size_t hashCode(const G3D::Color1& key) { + return key.hashCode(); + } +}; + + +#endif diff --git a/dep/g3dlite/G3D/Color1uint8.h b/dep/g3dlite/G3D/Color1uint8.h new file mode 100644 index 00000000000..092099d0d17 --- /dev/null +++ b/dep/g3dlite/G3D/Color1uint8.h @@ -0,0 +1,91 @@ +/** + @file Color1uint8.h + + @maintainer Morgan McGuire, graphics3d.com + + @created 2007-01-30 + @edited 2007-01-30 + + Copyright 2000-2007, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_COLOR1UINT8_H +#define G3D_COLOR1UINT8_H + +#include "G3D/platform.h" +#include "G3D/g3dmath.h" + +namespace G3D { + +/** + Represents a Color1 as a packed integer. Convenient + for creating unsigned int vertex arrays. + + WARNING: Integer color formats are different than + integer vertex formats. The color channels are automatically + scaled by 255 (because OpenGL automatically scales integer + colors back by this factor). So Color3(1,1,1) == Color3uint8(255,255,255) + but Vector3(1,1,1) == Vector3int16(1,1,1). + + Note: + Conversion of a float32 to uint8 is accomplished by min(iFloor(f * 256)) and + back to float32 by u / 255.0f. This gives equal size intervals. +Consider a number line from 0 to 1 and a corresponding one from 0 to 255. If we use iRound(x * 255), then the mapping for three critical intervals are: + +

+let s = 0.5/255
+  float             int       size
+[0, s)           -> 0          s
+[s, s * 3)       -> 1         2*s
+(1 - s, 1]       -> 255        s
+
+ +If we use max(floor(x * 256), 255), then we get: + +
+let s = 1/256
+  float             int           size
+[0, s)           -> 0               s
+[s, 2 * s)       -> 1               s
+(1 - s, 1]       -> 255             s
+
+and the intervals are all the same size, thus giving equal precision to all values. + */ +G3D_BEGIN_PACKED_CLASS(1) +class Color1uint8 { +private: + // Hidden operators + bool operator<(const Color1uint8&) const; + bool operator>(const Color1uint8&) const; + bool operator<=(const Color1uint8&) const; + bool operator>=(const Color1uint8&) const; + +public: + + uint8 value; + + Color1uint8() : value(0) {} + + explicit Color1uint8(const uint8 _v) : value(_v) {} + + Color1uint8(const class Color1& c); + + Color1uint8(class BinaryInput& bi); + + void serialize(class BinaryOutput& bo) const; + + void deserialize(class BinaryInput& bi); + + inline bool operator==(const Color1uint8& other) const { + return value == other.value; + } + + inline bool operator!=(const Color1uint8& other) const { + return value != other.value; + } + +} +G3D_END_PACKED_CLASS(1) +} +#endif diff --git a/dep/g3dlite/G3D/Color3.h b/dep/g3dlite/G3D/Color3.h new file mode 100644 index 00000000000..bffe434fc27 --- /dev/null +++ b/dep/g3dlite/G3D/Color3.h @@ -0,0 +1,432 @@ +/** + @file Color3.h + + Color class + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + @cite Portions based on Dave Eberly's Magic Software Library + at http://www.magic-software.com + + @created 2001-06-02 + @edited 2009-04-28 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_Color3_h +#define G3D_Color3_h + +#include "G3D/platform.h" +#include "G3D/g3dmath.h" +#include "G3D/HashTrait.h" +#include "G3D/Color1.h" +#include + +namespace G3D { +class Any; + +/** + Do not subclass-- this implementation makes assumptions about the + memory layout. + */ +class Color3 { +private: + // Hidden operators + bool operator<(const Color3&) const; + bool operator>(const Color3&) const; + bool operator<=(const Color3&) const; + bool operator>=(const Color3&) const; + +public: + /** + Does not initialize fields. + */ + Color3(); + + /** \param any Must be in one of the following forms: + - Color3(#, #, #) + - Color3::fromARGB(#) + - Color3{r = #, g = #, b = #) + - Color3::one() + - Color3::zero() + */ + Color3(const Any& any); + + /** Converts the Color3 to an Any. */ + operator Any() const; + + explicit Color3(class BinaryInput& bi); + + Color3(float r, float g, float b); + Color3(float v) : r(v), g(v), b(v) {} + + explicit Color3(const class Vector3& v); + + explicit Color3(const float value[3]); + + /** Returns this color */ + const Color3& rgb() const { + return *this; + } + + /** + Initialize from another color. + */ + Color3 (const Color3& other); + + Color3 (const class Color3uint8& other); + + inline bool isZero() const { + return (r == 0.0f) && (g == 0.0f) && (b == 0.0f); + } + + inline bool isOne() const { + return (r == 1.0f) && (g == 1.0f) && (b == 1.0f); + } + + bool isFinite() const; + + /** + Initialize from an HTML-style color (e.g. 0xFF0000 == RED) + */ + static Color3 fromARGB(uint32); + + /** Returns one of the color wheel colors (e.g. RED, GREEN, CYAN). + Does not include white, black, or gray. */ + static const Color3& wheelRandom(); + + /** Generate colors according to the ANSI color set, mod 16. + \sa pastelMap */ + static Color3 ansiMap(uint32 i); + + /** + Generate colors using a hash such that adjacent values + are unlikely to have similar colors. + + Useful for rendering with + stable but arbitrary colors, e.g., when debugging a mesh + algorithm. + + \sa ansiMap + */ + static Color3 pastelMap(uint32 i); + + /** + * Channel value. + */ + float r, g, b; + + void serialize(class BinaryOutput& bo) const; + void deserialize(class BinaryInput& bi); + + // access vector V as V[0] = V.r, V[1] = V.g, V[2] = V.b + // + // WARNING. These member functions rely on + // (1) Color3 not having virtual functions + // (2) the data packed in a 3*sizeof(float) memory block + const float& operator[] (int i) const; + float& operator[] (int i); + + // assignment and comparison + Color3& operator= (const Color3& rkVector); + bool operator== (const Color3& rkVector) const; + bool operator!= (const Color3& rkVector) const; + size_t hashCode() const; + + // arithmetic operations + Color3 operator+ (const Color3& rkVector) const; + Color3 operator- (const Color3& rkVector) const; + inline Color3 operator* (float s) const { + return Color3(r * s, g * s, b * s); + } + Color3 operator* (const Color3& rkVector) const; + inline Color3 operator/ (float fScalar) const { + return (*this) * (1.0f / fScalar); + } + Color3 operator- () const; + + // arithmetic updates + Color3& operator+= (const Color3& rkVector); + Color3& operator-= (const Color3& rkVector); + Color3& operator*= (const Color3& rkVector); + Color3& operator*= (float fScalar); + Color3& operator/= (float fScalar); + + bool fuzzyEq(const Color3& other) const; + bool fuzzyNe(const Color3& other) const; + + // vector operations + float length () const; + Color3 direction() const; + float squaredLength () const; + float dot (const Color3& rkVector) const; + float unitize (float fTolerance = 1e-06); + Color3 cross (const Color3& rkVector) const; + Color3 unitCross (const Color3& rkVector) const; + + inline Color3 pow(const Color3& other) const { + return Color3(::pow(r, other.r), ::pow(g, other.g), ::pow(b, other.b)); + } + + inline Color3 pow(float other) const { + return Color3(::pow(r, other), ::pow(g, other), ::pow(b, other)); + } + + inline Color3 max(const Color3& other) const { + return Color3(G3D::max(r, other.r), G3D::max(g, other.g), G3D::max(b, other.b)); + } + + inline Color3 min(const Color3& other) const { + return Color3(G3D::min(r, other.r), G3D::min(g, other.g), G3D::min(b, other.b)); + } + + /** Smallest element */ + inline float min() const { + return G3D::min(G3D::min(r, g), b); + } + + /** Largest element */ + inline float max() const { + return G3D::max(G3D::max(r, g), b); + } + + inline Color3 lerp(const Color3& other, float a) const { + return (*this) + (other - *this) * a; + + } + + inline float sum() const { + return r + g + b; + } + + inline float average() const { + return sum() / 3.0f; + } + + + /** + * Converts from HSV to RGB , note: toHSV(fromHSV(_hsv)) may not be _hsv, if it is at a grey point or black point. + * The components of _hsv should lie in the unit interval. + * @cite Alvy Ray Smith SIGGRAPH 1978 "Color Gamut Transform Pairs" + **/ + static Color3 fromHSV(const Vector3& _hsv); + static Vector3 toHSV(const Color3& _rgb); + + /** Duplicates the matlab jet colormap maps [0,1] --> (r,g,b) where blue is close to 0 and red is close to 1. */ + static Color3 jetColorMap(const float& val); + + /** Returns colors with maximum saturation and value @param hue [0, 1]*/ + static Color3 rainbowColorMap(float hue); + + std::string toString() const; + + /** Random unit vector */ + static Color3 random(); + + // Special values. + // Intentionally not inlined: see Matrix3::identity() for details. + static const Color3& red(); + static const Color3& green(); + static const Color3& blue(); + static const Color3& purple(); + static const Color3& cyan(); + static const Color3& yellow(); + static const Color3& brown(); + static const Color3& orange(); + static const Color3& black(); + static const Color3& gray(); + static const Color3& white(); + + static const Color3& zero(); + static const Color3& one(); + + inline Color3 bgr() const { + return Color3(b, g, r); + } +}; + +inline G3D::Color3 operator* (float s, const G3D::Color3& c) { + return c * s; +} + +inline G3D::Color3 operator* (G3D::Color1& s, const G3D::Color3& c) { + return c * s.value; +} + +inline G3D::Color3 operator* (const G3D::Color3& c, G3D::Color1& s) { + return c * s.value; +} + + +//---------------------------------------------------------------------------- +inline Color3::Color3 () { +} + +//---------------------------------------------------------------------------- + +inline Color3::Color3(float fX, float fY, float fZ) { + r = fX; + g = fY; + b = fZ; +} + +//---------------------------------------------------------------------------- +inline Color3::Color3(const float afCoordinate[3]) { + r = afCoordinate[0]; + g = afCoordinate[1]; + b = afCoordinate[2]; +} + +//---------------------------------------------------------------------------- +inline Color3::Color3 (const Color3& rkVector) { + r = rkVector.r; + g = rkVector.g; + b = rkVector.b; +} + +//---------------------------------------------------------------------------- +inline float& Color3::operator[] (int i) { + return ((float*)this)[i]; +} + +//---------------------------------------------------------------------------- + +inline const float& Color3::operator[] (int i) const { + return ((float*)this)[i]; +} + +//---------------------------------------------------------------------------- + +inline bool Color3::fuzzyEq(const Color3& other) const { + return G3D::fuzzyEq((*this - other).squaredLength(), 0); +} + +//---------------------------------------------------------------------------- + +inline bool Color3::fuzzyNe(const Color3& other) const { + return G3D::fuzzyNe((*this - other).squaredLength(), 0); +} + + +//---------------------------------------------------------------------------- +inline Color3& Color3::operator= (const Color3& rkVector) { + r = rkVector.r; + g = rkVector.g; + b = rkVector.b; + return *this; +} + +//---------------------------------------------------------------------------- +inline bool Color3::operator== (const Color3& rkVector) const { + return ( r == rkVector.r && g == rkVector.g && b == rkVector.b ); +} + +//---------------------------------------------------------------------------- +inline bool Color3::operator!= (const Color3& rkVector) const { + return ( r != rkVector.r || g != rkVector.g || b != rkVector.b ); +} + +//---------------------------------------------------------------------------- +inline Color3 Color3::operator+ (const Color3& rkVector) const { + return Color3(r + rkVector.r, g + rkVector.g, b + rkVector.b); +} + +//---------------------------------------------------------------------------- +inline Color3 Color3::operator- (const Color3& rkVector) const { + return Color3(r -rkVector.r, g - rkVector.g, b - rkVector.b); +} + +//---------------------------------------------------------------------------- +inline Color3 Color3::operator* (const Color3& rkVector) const { + return Color3(r * rkVector.r, g * rkVector.g, b * rkVector.b); +} + +//---------------------------------------------------------------------------- +inline Color3 Color3::operator- () const { + return Color3( -r, -g, -b); +} + +//---------------------------------------------------------------------------- +inline Color3& Color3::operator+= (const Color3& rkVector) { + r += rkVector.r; + g += rkVector.g; + b += rkVector.b; + return *this; +} + +//---------------------------------------------------------------------------- +inline Color3& Color3::operator-= (const Color3& rkVector) { + r -= rkVector.r; + g -= rkVector.g; + b -= rkVector.b; + return *this; +} + +//---------------------------------------------------------------------------- +inline Color3& Color3::operator*= (float fScalar) { + r *= fScalar; + g *= fScalar; + b *= fScalar; + return *this; +} + +//---------------------------------------------------------------------------- +inline Color3& Color3::operator*= (const Color3& rkVector) { + r *= rkVector.r; + g *= rkVector.g; + b *= rkVector.b; + return *this; +} +//---------------------------------------------------------------------------- +inline float Color3::squaredLength () const { + return r*r + g*g + b*b; +} + +//---------------------------------------------------------------------------- +inline float Color3::length () const { + return sqrtf(r*r + g*g + b*b); +} + +//---------------------------------------------------------------------------- +inline Color3 Color3::direction () const { + float lenSquared = r * r + g * g + b * b; + + if (lenSquared != 1.0f) { + return *this / sqrtf(lenSquared); + } else { + return *this; + } +} + +//---------------------------------------------------------------------------- +inline float Color3::dot (const Color3& rkVector) const { + return r*rkVector.r + g*rkVector.g + b*rkVector.b; +} + +//---------------------------------------------------------------------------- +inline Color3 Color3::cross (const Color3& rkVector) const { + return Color3(g*rkVector.b - b*rkVector.g, b*rkVector.r - r*rkVector.b, + r*rkVector.g - g*rkVector.r); +} + +//---------------------------------------------------------------------------- +inline Color3 Color3::unitCross (const Color3& rkVector) const { + Color3 kCross(g*rkVector.b - b*rkVector.g, b*rkVector.r - r*rkVector.b, + r*rkVector.g - g*rkVector.r); + kCross.unitize(); + return kCross; +} + + +} // namespace + + +template <> struct HashTrait { + static size_t hashCode(const G3D::Color3& key) { + return key.hashCode(); + } +}; + + +#endif diff --git a/dep/g3dlite/G3D/Color3uint8.h b/dep/g3dlite/G3D/Color3uint8.h new file mode 100644 index 00000000000..bd4b00d7fd6 --- /dev/null +++ b/dep/g3dlite/G3D/Color3uint8.h @@ -0,0 +1,110 @@ +/** + @file Color3uint8.h + + @maintainer Morgan McGuire, graphics3d.com + + @created 2003-04-07 + @edited 2006-06-24 + + Copyright 2000-2006, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_COLOR3UINT8_H +#define G3D_COLOR3UINT8_H + +#include "G3D/platform.h" +#include "G3D/g3dmath.h" + +namespace G3D { + +/** + Represents a Color3 as a packed integer. Convenient + for creating unsigned int vertex arrays. Used by + G3D::GImage as the underlying format. + + WARNING: Integer color formats are different than + integer vertex formats. The color channels are automatically + scaled by 255 (because OpenGL automatically scales integer + colors back by this factor). So Color3(1,1,1) == Color3uint8(255,255,255) + but Vector3(1,1,1) == Vector3int16(1,1,1). + */ + +G3D_BEGIN_PACKED_CLASS(1) + +class Color3uint8 { +private: + // Hidden operators + bool operator<(const Color3uint8&) const; + bool operator>(const Color3uint8&) const; + bool operator<=(const Color3uint8&) const; + bool operator>=(const Color3uint8&) const; + +public: + uint8 r; + uint8 g; + uint8 b; + + Color3uint8() : r(0), g(0), b(0) {} + + Color3uint8(const uint8 _r, const uint8 _g, const uint8 _b) : r(_r), g(_g), b(_b) {} + + Color3uint8(const class Color3& c); + + Color3uint8(class BinaryInput& bi); + + inline static Color3uint8 fromARGB(uint32 i) { + Color3uint8 c; + c.r = (i >> 16) & 0xFF; + c.g = (i >> 8) & 0xFF; + c.b = i & 0xFF; + return c; + } + + inline Color3uint8 bgr() const { + return Color3uint8(b, g, r); + } + + /** + Returns the color packed into a uint32 + (the upper byte is 0xFF) + */ + inline uint32 asUInt32() const { + return (0xFF << 24) + ((uint32)r << 16) + ((uint32)g << 8) + b; + } + + void serialize(class BinaryOutput& bo) const; + + void deserialize(class BinaryInput& bi); + + // access vector V as V[0] = V.r, V[1] = V.g, V[2] = V.b + // + // WARNING. These member functions rely on + // (1) Color3 not having virtual functions + // (2) the data packed in a 3*sizeof(uint8) memory block + uint8& operator[] (int i) const { + debugAssert((unsigned int)i < 3); + return ((uint8*)this)[i]; + } + + operator uint8* () { + return (G3D::uint8*)this; + } + + operator const uint8* () const { + return (uint8*)this; + } + + bool operator==(const Color3uint8& other) const { + return (other.r == r) && (other.g == g) && (other.b == b); + } + + bool operator!=(const Color3uint8& other) const { + return (other.r != r) && (other.g != g) && (other.b != b); + } +} +G3D_END_PACKED_CLASS(1) + +} // namespace G3D + +#endif diff --git a/dep/g3dlite/G3D/Color4.h b/dep/g3dlite/G3D/Color4.h new file mode 100644 index 00000000000..d8858abbce2 --- /dev/null +++ b/dep/g3dlite/G3D/Color4.h @@ -0,0 +1,338 @@ +/** + @file Color4.h + + Color class + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + @cite Portions based on Dave Eberly's Magic Software Library + at http://www.magic-software.com + + @created 2002-06-25 + @edited 2009-11-15 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_Color4_h +#define G3D_Color4_h + +#include "G3D/platform.h" +#include "G3D/g3dmath.h" +#include "G3D/Color3.h" +#include + +namespace G3D { + +class Any; + +/** + Do not subclass-- this implementation makes assumptions about the + memory layout. + */ +class Color4 { +private: + // Hidden operators + bool operator<(const Color4&) const; + bool operator>(const Color4&) const; + bool operator<=(const Color4&) const; + bool operator>=(const Color4&) const; + +public: + + /** \param any Must be in one of the following forms: + - Color4(#, #, #, #) + - Color4::fromARGB(#) + - Color4{r = #, g = #, b = #, a = #) + */ + Color4(const Any& any); + + /** Converts the Color4 to an Any. */ + operator Any() const; + + /** + * Does not initialize fields. + */ + Color4 (); + + Color4(const Color3& c3, float a = 1.0); + + Color4(const class Color4uint8& c); + + Color4(class BinaryInput& bi); + + Color4(const class Vector4& v); + + Color4(float r, float g, float b, float a = 1.0); + + static const Color4& one(); + + Color4(float value[4]); + + /** + * Initialize from another color. + */ + Color4(const Color4& other); + + + inline bool isZero() const { + return (r == 0.0f) && (g == 0.0f) && (b == 0.0f) && (a == 0.0f); + } + + inline bool isOne() const { + return (r == 1.0f) && (g == 1.0f) && (b == 1.0f) && (a == 1.0f); + } + + void serialize(class BinaryOutput& bo) const; + void deserialize(class BinaryInput& bi); + + /** + Initialize from an HTML-style color (e.g. 0xFFFF0000 == RED) + */ + static Color4 fromARGB(uint32); + + /** + * Channel values. + */ + float r, g, b, a; + + inline Color3 rgb() const { + return Color3(r, g, b); + } + + // access vector V as V[0] = V.r, V[1] = V.g, V[2] = V.b, v[3] = V.a + // + // WARNING. These member functions rely on + // (1) Color4 not having virtual functions + // (2) the data packed in a 3*sizeof(float) memory block + float& operator[] (int i) const; + + // assignment and comparison + Color4& operator= (const Color4& rkVector); + bool operator== (const Color4& rkVector) const; + bool operator!= (const Color4& rkVector) const; + size_t hashCode() const; + + // arithmetic operations + Color4 operator+ (const Color4& rkVector) const; + Color4 operator- (const Color4& rkVector) const; + Color4 operator* (float fScalar) const; + inline Color4 operator* (const Color4& k) const { + return Color4(r*k.r, g*k.g, b*k.b, a * k.a); + } + Color4 operator/ (float fScalar) const; + Color4 operator- () const; + friend Color4 operator* (double fScalar, const Color4& rkVector); + + // arithmetic updates + Color4& operator+= (const Color4& rkVector); + Color4& operator-= (const Color4& rkVector); + Color4& operator*= (float fScalar); + Color4& operator/= (float fScalar); + + bool fuzzyEq(const Color4& other) const; + bool fuzzyNe(const Color4& other) const; + + std::string toString() const; + + inline Color4 max(const Color4& other) const { + return Color4(G3D::max(r, other.r), G3D::max(g, other.g), G3D::max(b, other.b), G3D::max(a, other.a)); + } + + inline Color4 min(const Color4& other) const { + return Color4(G3D::min(r, other.r), G3D::min(g, other.g), G3D::min(b, other.b), G3D::min(a, other.a)); + } + + /** r + g + b + a */ + inline float sum() const { + return r + g + b + a; + } + + inline Color4 lerp(const Color4& other, float a) const { + return (*this) + (other - *this) * a; + + } + + // Special values. + // Intentionally not inlined: see Matrix3::identity() for details. + static const Color4& zero(); + static const Color4& clear(); + + static const Color4& inf(); + static const Color4& nan(); + + inline bool isFinite() const { + return G3D::isFinite(r) && G3D::isFinite(g) && G3D::isFinite(b) && G3D::isFinite(a); + } + + inline Color3 bgr() const { + return Color3(b, g, r); + } +}; + +/** + Extends the c3 with alpha = 1.0 + */ +Color4 operator*(const Color3& c3, const Color4& c4); + + +inline Color4 operator*(const Color3& c3, const Color4& c4) { + return Color4(c3.r * c4.r, c3.g * c4.g, c3.b * c4.b, c4.a); +} + +//---------------------------------------------------------------------------- + +inline Color4::Color4 () { + // For efficiency in construction of large arrays of vectors, the + // default constructor does not initialize the vector. +} + +//---------------------------------------------------------------------------- + +inline Color4::Color4(const Color3& c3, float a) { + r = c3.r; + g = c3.g; + b = c3.b; + this->a = a; +} + +//---------------------------------------------------------------------------- + +inline Color4::Color4( + float r, + float g, + float b, + float a) : + r(r), g(g), b(b), a(a) { +} + +//---------------------------------------------------------------------------- +inline Color4::Color4 (float afCoordinate[4]) { + r = afCoordinate[0]; + g = afCoordinate[1]; + b = afCoordinate[2]; + a = afCoordinate[3]; +} + +//---------------------------------------------------------------------------- + +inline Color4::Color4( + const Color4& other) { + + r = other.r; + g = other.g; + b = other.b; + a = other.a; +} + +//---------------------------------------------------------------------------- + +inline float& Color4::operator[] (int i) const { + return ((float*)this)[i]; +} + +//---------------------------------------------------------------------------- + +inline bool Color4::fuzzyEq(const Color4& other) const { + Color4 dif = (*this - other); + return G3D::fuzzyEq(dif.r * dif.r + dif.g * dif.g + dif.b * dif.b + dif.a * dif.a, 0); +} + +//---------------------------------------------------------------------------- + +inline bool Color4::fuzzyNe(const Color4& other) const { + Color4 dif = (*this - other); + return G3D::fuzzyNe(dif.r * dif.r + dif.g * dif.g + dif.b * dif.b + dif.a * dif.a, 0); +} + + +//---------------------------------------------------------------------------- +inline Color4& Color4::operator= (const Color4& other) { + r = other.r; + g = other.g; + b = other.b; + a = other.a; + return *this; +} + +//---------------------------------------------------------------------------- + +inline bool Color4::operator== (const Color4& other) const { + return ( r == other.r && g == other.g && b == other.b && a == other.a); +} + +//---------------------------------------------------------------------------- + +inline bool Color4::operator!= (const Color4& other) const { + return ( r != other.r || g != other.g || b != other.b || a != other.a); +} + +//---------------------------------------------------------------------------- +inline Color4 Color4::operator+ (const Color4& other) const { + return Color4(r + other.r, g + other.g, b + other.b, a + other.a); +} + +//---------------------------------------------------------------------------- +inline Color4 Color4::operator- (const Color4& other) const { + return Color4(r - other.r, g - other.g, b - other.b, a - other.a); +} + +//---------------------------------------------------------------------------- + +inline Color4 Color4::operator* (float fScalar) const { + return Color4(fScalar * r, fScalar * g, fScalar * b, fScalar * a); +} + +//---------------------------------------------------------------------------- + +inline Color4 Color4::operator- () const { + return Color4(-r, -g, -b, -a); +} + +//---------------------------------------------------------------------------- + +inline Color4 operator* (float fScalar, const Color4& other) { + return Color4(fScalar * other.r, fScalar * other.g, + fScalar * other.b, fScalar * other.a); +} + +//---------------------------------------------------------------------------- + +inline Color4& Color4::operator+= (const Color4& other) { + r += other.r; + g += other.g; + b += other.b; + a += other.a; + return *this; +} + +//---------------------------------------------------------------------------- + +inline Color4& Color4::operator-= (const Color4& other) { + r -= other.r; + g -= other.g; + b -= other.b; + a -= other.a; + return *this; +} + +//---------------------------------------------------------------------------- + +inline Color4& Color4::operator*= (float fScalar) { + r *= fScalar; + g *= fScalar; + b *= fScalar; + a *= fScalar; + return *this; +} + +} // namespace + +template <> +struct HashTrait { + static size_t hashCode(const G3D::Color4& key) { + return key.hashCode(); + } +}; + +#endif diff --git a/dep/g3dlite/G3D/Color4uint8.h b/dep/g3dlite/G3D/Color4uint8.h new file mode 100644 index 00000000000..ab8c0729276 --- /dev/null +++ b/dep/g3dlite/G3D/Color4uint8.h @@ -0,0 +1,115 @@ +/** + @file Color4uint8.h + + @maintainer Morgan McGuire, graphics3d.com + + @created 2003-04-07 + @edited 2006-03-24 + + Copyright 2000-2006, Morgan McGuire. + All rights reserved. + */ + +#ifndef COLOR4UINT8_H +#define COLOR4UINT8_H + +#include "G3D/g3dmath.h" +#include "G3D/platform.h" +#include "G3D/Color3uint8.h" + +namespace G3D { + +/** + Represents a Color4 as a packed integer. Convenient + for creating unsigned int vertex arrays. Used by + G3D::GImage as the underlying format. + + WARNING: Integer color formats are different than + integer vertex formats. The color channels are automatically + scaled by 255 (because OpenGL automatically scales integer + colors back by this factor). So Color4(1,1,1) == Color4uint8(255,255,255) + but Vector3(1,1,1) == Vector3int16(1,1,1). + + */ +G3D_BEGIN_PACKED_CLASS(1) +class Color4uint8 { +private: + // Hidden operators + bool operator<(const Color4uint8&) const; + bool operator>(const Color4uint8&) const; + bool operator<=(const Color4uint8&) const; + bool operator>=(const Color4uint8&) const; + +public: + uint8 r; + uint8 g; + uint8 b; + uint8 a; + + Color4uint8() : r(0), g(0), b(0), a(0) {} + + Color4uint8(const class Color4& c); + + Color4uint8(const uint8 _r, const uint8 _g, const uint8 _b, const uint8 _a) : r(_r), g(_g), b(_b), a(_a) {} + + Color4uint8(const Color3uint8& c, const uint8 _a) : r(c.r), g(c.g), b(c.b), a(_a) {} + + Color4uint8(class BinaryInput& bi); + + inline static Color4uint8 fromARGB(uint32 i) { + Color4uint8 c; + c.a = (i >> 24) & 0xFF; + c.r = (i >> 16) & 0xFF; + c.g = (i >> 8) & 0xFF; + c.b = i & 0xFF; + return c; + } + + inline uint32 asUInt32() const { + return ((uint32)a << 24) + ((uint32)r << 16) + ((uint32)g << 8) + b; + } + + // access vector V as V[0] = V.r, V[1] = V.g, V[2] = V.b + // + // WARNING. These member functions rely on + // (1) Color4uint8 not having virtual functions + // (2) the data packed in a 3*sizeof(uint8) memory block + uint8& operator[] (int i) const { + return ((uint8*)this)[i]; + } + + operator uint8* () { + return (uint8*)this; + } + + operator const uint8* () const { + return (uint8*)this; + } + + + inline Color3uint8 bgr() const { + return Color3uint8(b, g, r); + } + + void serialize(class BinaryOutput& bo) const; + + void deserialize(class BinaryInput& bi); + + inline Color3uint8 rgb() const { + return Color3uint8(r, g, b); + } + + bool operator==(const Color4uint8& other) const { + return *reinterpret_cast(this) == *reinterpret_cast(&other); + } + + bool operator!=(const Color4uint8& other) const { + return *reinterpret_cast(this) != *reinterpret_cast(&other); + } + +} +G3D_END_PACKED_CLASS(1) + +} // namespace G3D + +#endif diff --git a/dep/g3dlite/G3D/Cone.h b/dep/g3dlite/G3D/Cone.h new file mode 100644 index 00000000000..d801a9b348f --- /dev/null +++ b/dep/g3dlite/G3D/Cone.h @@ -0,0 +1,68 @@ +/** + @file Cone.h + + Cone class + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + @cite Portions based on Dave Eberly's Magic Software Library at http://www.magic-software.com + + @created 2001-06-02 + @edited 2006-02-23 + + Copyright 2000-2006, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_CONE_H +#define G3D_CONE_H + +#include "G3D/platform.h" +#include "G3D/g3dmath.h" +#include "G3D/Vector3.h" + +namespace G3D { + +/** + An infinite cone. + */ +class Cone { + +private: + Vector3 tip; + Vector3 direction; + + /** Angle from the center line to the edge. */ + float angle; + +public: + + /** + @param angle Angle from the center line to the edge, in radians + */ + Cone(const Vector3& tip, const Vector3& direction, float angle); + + /** + Forms the smallest cone that contains the box. Undefined if + the tip is inside or on the box. + */ + Cone(const Vector3& tip, const class Box& box); + + virtual ~Cone() {} + + /** + Returns true if the cone touches, intersects, or contains b. + + If c.intersects(s) and c.intersects(Sphere(s.center, s.radius * 2) + then the sphere s is entirely within cone c. + */ + bool intersects(const class Sphere& s) const; + + /** + True if v is a point inside the cone. + */ + bool contains(const class Vector3& v) const; +}; + +} // namespace + +#endif diff --git a/dep/g3dlite/G3D/ConvexPolyhedron.h b/dep/g3dlite/G3D/ConvexPolyhedron.h new file mode 100644 index 00000000000..a6fdd62cf90 --- /dev/null +++ b/dep/g3dlite/G3D/ConvexPolyhedron.h @@ -0,0 +1,180 @@ +/** + @file ConvexPolyhedron.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2001-11-11 + @edited 2006-04-10 + + Copyright 2000-2006, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_CONVEXPOLYHEDRON_H +#define G3D_CONVEXPOLYHEDRON_H + +#include "G3D/platform.h" +#include "G3D/Vector3.h" +#include "G3D/Vector2.h" +#include "G3D/CoordinateFrame.h" +#include "G3D/Plane.h" +#include "G3D/Line.h" +#include "G3D/Array.h" + +namespace G3D { + +class DirectedEdge { +public: + Vector3 start; + Vector3 stop; +}; + +class ConvexPolygon { +private: + + friend class ConvexPolyhedron; + + Array _vertex; + +public: + + ConvexPolygon() {} + ConvexPolygon(const Vector3& v0, const Vector3& v1, const Vector3& v2); + ConvexPolygon(const Array& __vertex); + virtual ~ConvexPolygon() {} + + /** + Counter clockwise winding order. + */ + inline const Vector3& vertex(int i) const { + return _vertex[i]; + } + + inline void setVertex(int i, const Vector3& v) { + _vertex[i] = v; + } + + /** + Zero vertices indicates an empty polygon (zero area). + */ + inline int numVertices() const { + return _vertex.size(); + } + + inline void setNumVertices(int n) { + _vertex.resize(n); + } + + /** + O(n) in the number of edges + */ + bool isEmpty() const; + + /** + Cuts the polygon at the plane. If the polygon is entirely above or below + the plane, one of the returned polygons will be empty. + + @param above The part of the polygon above (on the side the + normal points to or in the plane) the plane + @param below The part of the polygon below the plane. + @param newEdge If a new edge was introduced, this is that edge (on the above portion; the below portion is the opposite winding. + */ + void cut(const Plane& plane, ConvexPolygon &above, ConvexPolygon &below, DirectedEdge& newEdge); + void cut(const Plane& plane, ConvexPolygon &above, ConvexPolygon &below); + + /** + When a cut plane grazes a vertex in the polygon, two near-identical vertices may be created. + The closeness of these two points can cause a number of problems, such as ConvexPolygon::normal() + returning an infinite vector. It should be noted, however, that not all applications are + sensitive to near-identical vertices. + + removeDuplicateVertices() detects and eliminates redundant vertices. + */ + void removeDuplicateVertices(); + + /** + O(n) in the number of edges + */ + float getArea() const; + + inline Vector3 normal() const { + debugAssert(_vertex.length() >= 3); + return (_vertex[1] - _vertex[0]).cross(_vertex[2] - _vertex[0]).direction(); + } + + /** + Returns the same polygon with inverse winding. + */ + ConvexPolygon inverse() const; +}; + + + +class ConvexPolyhedron { +public: + /** + Zero faces indicates an empty polyhedron + */ + Array face; + + ConvexPolyhedron() {} + ConvexPolyhedron(const Array& _face); + + /** + O(n) in the number of edges + */ + bool isEmpty() const; + + /** + O(n) in the number of edges + */ + float getVolume() const; + + /** + Cuts the polyhedron at the plane. If the polyhedron is entirely above or below + the plane, one of the returned polyhedra will be empty. + + @param above The part of the polyhedron above (on the side the + normal points to or in the plane) the plane + @param below The part of the polyhedron below the plane. + */ + void cut(const Plane& plane, ConvexPolyhedron &above, ConvexPolyhedron &below); +}; + +/** + + */ +class ConvexPolygon2D { +private: + + Array m_vertex; + +public: + + ConvexPolygon2D() {} + + /** + Points are counter-clockwise in a Y = down, X = right coordinate + system. + + @param reverse If true, the points are reversed (i.e. winding direction is changed) + before the polygon is created. + */ + ConvexPolygon2D(const Array& pts, bool reverse = false); + + inline int numVertices() const { + return m_vertex.size(); + } + + inline const Vector2& vertex(int index) const { + debugAssert((index >= 0) && (index <= m_vertex.size())); + return m_vertex[index]; + } + + /** @param reverseWinding If true, the winding direction of the polygon is reversed for this test.*/ + bool contains(const Vector2& p, bool reverseWinding = false) const; +}; + + +} // namespace +#endif diff --git a/dep/g3dlite/G3D/CoordinateFrame.h b/dep/g3dlite/G3D/CoordinateFrame.h new file mode 100644 index 00000000000..7ed4d0acc65 --- /dev/null +++ b/dep/g3dlite/G3D/CoordinateFrame.h @@ -0,0 +1,331 @@ +/** + @file CoordinateFrame.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2001-03-04 + @edited 2009-04-29 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. +*/ + +#ifndef G3D_CFrame_h +#define G3D_CFrame_h + +#include "G3D/platform.h" +#include "G3D/Vector3.h" +#include "G3D/Vector4.h" +#include "G3D/Matrix3.h" +#include "G3D/Array.h" +#include +#include +#include +#include +#include + +#ifdef _MSC_VER +// Turn off "conditional expression is constant" warning; MSVC generates this +// for debug assertions in inlined methods. +# pragma warning (disable : 4127) +#endif + + +namespace G3D { +class Any; + +/** + A rigid body RT (rotation-translation) transformation. + +CoordinateFrame abstracts a 4x4 matrix that maps object space to world space: + + v_world = C * v_object + +CoordinateFrame::rotation is the upper 3x3 submatrix, CoordinateFrame::translation +is the right 3x1 column. The 4th row is always [0 0 0 1], so it isn't stored. +So you don't have to remember which way the multiplication and transformation work, +it provides explicit toWorldSpace and toObjectSpace methods. Also, points, vectors +(directions), and surface normals transform differently, so they have separate methods. + +Some helper functions transform whole primitives like boxes in and out of object space. + +Convert to Matrix4 using CoordinateFrame::toMatrix4. You can construct a CoordinateFrame +from a Matrix4 using Matrix4::approxCoordinateFrame, however, because a Matrix4 is more +general than a CoordinateFrame, some information may be lost. + +@sa G3D::UprightFrame, G3D::PhysicsFrame, G3D::Matrix4, G3D::Quat +*/ +class CoordinateFrame { +public: + + /** Takes object space points to world space. */ + Matrix3 rotation; + + /** Takes object space points to world space. */ + Vector3 translation; + + /** \param any Must be in one of the following forms: + - CFrame((matrix3 expr), (vector3 expr)) + - CFrame::fromXYZYPRDegrees(#, #, #, #, #, #) + - CFrame { rotation = (matrix3 expr), translation = (vector3 expr) } + */ + CoordinateFrame(const Any& any); + + /** Converts the CFrame to an Any. */ + operator Any() const; + + inline bool operator==(const CoordinateFrame& other) const { + return (translation == other.translation) && (rotation == other.rotation); + } + + inline bool operator!=(const CoordinateFrame& other) const { + return !(*this == other); + } + + bool fuzzyEq(const CoordinateFrame& other) const; + + bool fuzzyIsIdentity() const; + + bool isIdentity() const; + + /** + Initializes to the identity coordinate frame. + */ + CoordinateFrame(); + + CoordinateFrame(const Vector3& _translation) : + rotation(Matrix3::identity()), translation(_translation) { + } + + CoordinateFrame(const Matrix3 &rotation, const Vector3 &translation) : + rotation(rotation), translation(translation) { + } + + CoordinateFrame(const Matrix3 &rotation) : + rotation(rotation), translation(Vector3::zero()) { + } + + CoordinateFrame(const class UprightFrame& f); + + static CoordinateFrame fromXYZYPRRadians(float x, float y, float z, float yaw = 0.0f, float pitch = 0.0f, float roll = 0.0f); + + /** Construct a coordinate frame from translation = (x,y,z) and + rotations (in that order) about Y, object space X, object space + Z. Note that because object-space axes are used, these are not + equivalent to Euler angles; they are known as Tait-Bryan + rotations and are more convenient for intuitive positioning.*/ + static CoordinateFrame fromXYZYPRDegrees(float x, float y, float z, float yaw = 0.0f, float pitch = 0.0f, float roll = 0.0f); + + CoordinateFrame(class BinaryInput& b); + + void deserialize(class BinaryInput& b); + + void serialize(class BinaryOutput& b) const; + + CoordinateFrame(const CoordinateFrame &other) : + rotation(other.rotation), translation(other.translation) {} + + /** + Computes the inverse of this coordinate frame. + */ + inline CoordinateFrame inverse() const { + CoordinateFrame out; + out.rotation = rotation.transpose(); + out.translation = -out.rotation * translation; + return out; + } + + inline ~CoordinateFrame() {} + + /** See also Matrix4::approxCoordinateFrame */ + class Matrix4 toMatrix4() const; + + void getXYZYPRRadians(float& x, float& y, float& z, float& yaw, float& pitch, float& roll) const; + void getXYZYPRDegrees(float& x, float& y, float& z, float& yaw, float& pitch, float& roll) const; + + + /** + Produces an XML serialization of this coordinate frame. + @deprecated + */ + std::string toXML() const; + + /** + Returns the heading of the lookVector as an angle in radians relative to + the world -z axis. That is, a counter-clockwise heading where north (-z) + is 0 and west (-x) is PI/2. + + Note that the heading ignores the Y axis, so an inverted + object has an inverted heading. + */ + inline float getHeading() const { + Vector3 look = rotation.column(2); + float angle = -(float) atan2(-look.x, look.z); + return angle; + } + + /** + Takes the coordinate frame into object space. + this->inverse() * c + */ + inline CoordinateFrame toObjectSpace(const CoordinateFrame& c) const { + return this->inverse() * c; + } + + inline Vector4 toObjectSpace(const Vector4& v) const { + return this->inverse().toWorldSpace(v); + } + + inline Vector4 toWorldSpace(const Vector4& v) const { + return Vector4(rotation * Vector3(v.x, v.y, v.z) + translation * v.w, v.w); + } + + /** + Transforms the point into world space. + */ + inline Vector3 pointToWorldSpace(const Vector3& v) const { + return Vector3( + rotation[0][0] * v[0] + rotation[0][1] * v[1] + rotation[0][2] * v[2] + translation[0], + rotation[1][0] * v[0] + rotation[1][1] * v[1] + rotation[1][2] * v[2] + translation[1], + rotation[2][0] * v[0] + rotation[2][1] * v[1] + rotation[2][2] * v[2] + translation[2]); + } + + /** + Transforms the point into object space. Assumes that the rotation matrix is orthonormal. + */ + inline Vector3 pointToObjectSpace(const Vector3& v) const { + float p[3]; + p[0] = v[0] - translation[0]; + p[1] = v[1] - translation[1]; + p[2] = v[2] - translation[2]; + debugAssert(G3D::fuzzyEq(rotation.determinant(), 1.0f)); + return Vector3( + rotation[0][0] * p[0] + rotation[1][0] * p[1] + rotation[2][0] * p[2], + rotation[0][1] * p[0] + rotation[1][1] * p[1] + rotation[2][1] * p[2], + rotation[0][2] * p[0] + rotation[1][2] * p[1] + rotation[2][2] * p[2]); + } + + /** + Transforms the vector into world space (no translation). + */ + inline Vector3 vectorToWorldSpace(const Vector3& v) const { + return rotation * v; + } + + inline Vector3 normalToWorldSpace(const Vector3& v) const { + return rotation * v; + } + + class Ray toObjectSpace(const Ray& r) const; + + Ray toWorldSpace(const Ray& r) const; + + /** + Transforms the vector into object space (no translation). + */ + inline Vector3 vectorToObjectSpace(const Vector3 &v) const { + // Multiply on the left (same as rotation.transpose() * v) + return v * rotation; + } + + inline Vector3 normalToObjectSpace(const Vector3 &v) const { + // Multiply on the left (same as rotation.transpose() * v) + return v * rotation; + } + + void pointToWorldSpace(const Array& v, Array& vout) const; + + void normalToWorldSpace(const Array& v, Array& vout) const; + + void vectorToWorldSpace(const Array& v, Array& vout) const; + + void pointToObjectSpace(const Array& v, Array& vout) const; + + void normalToObjectSpace(const Array& v, Array& vout) const; + + void vectorToObjectSpace(const Array& v, Array& vout) const; + + class Box toWorldSpace(const class AABox& b) const; + + class Box toWorldSpace(const class Box& b) const; + + class Cylinder toWorldSpace(const class Cylinder& b) const; + + class Capsule toWorldSpace(const class Capsule& b) const; + + class Plane toWorldSpace(const class Plane& p) const; + + class Sphere toWorldSpace(const class Sphere& b) const; + + class Triangle toWorldSpace(const class Triangle& t) const; + + class Box toObjectSpace(const AABox& b) const; + + class Box toObjectSpace(const Box& b) const; + + class Plane toObjectSpace(const Plane& p) const; + + class Sphere toObjectSpace(const Sphere& b) const; + + Triangle toObjectSpace(const Triangle& t) const; + + /** Compose: create the transformation that is other followed by this.*/ + CoordinateFrame operator*(const CoordinateFrame &other) const { + return CoordinateFrame(rotation * other.rotation, + pointToWorldSpace(other.translation)); + } + + CoordinateFrame operator+(const Vector3& v) const { + return CoordinateFrame(rotation, translation + v); + } + + CoordinateFrame operator-(const Vector3& v) const { + return CoordinateFrame(rotation, translation - v); + } + + void lookAt(const Vector3& target); + + void lookAt( + const Vector3& target, + Vector3 up); + + /** The direction this camera is looking (its negative z axis)*/ + inline Vector3 lookVector() const { + return -rotation.column(2); + } + + /** Returns the ray starting at the camera origin travelling in direction CoordinateFrame::lookVector. */ + class Ray lookRay() const; + + /** Up direction for this camera (its y axis). */ + inline Vector3 upVector() const { + return rotation.column(1); + } + + inline Vector3 rightVector() const { + return rotation.column(0); + } + + /** + If a viewer looks along the look vector, this is the viewer's "left". + Useful for strafing motions and building alternative coordinate frames. + */ + inline Vector3 leftVector() const { + return -rotation.column(0); + } + + /** + Linearly interpolates between two coordinate frames, using + Quat::slerp for the rotations. + */ + CoordinateFrame lerp( + const CoordinateFrame& other, + float alpha) const; + +}; + +typedef CoordinateFrame CFrame; + +} // namespace + +#endif diff --git a/dep/g3dlite/G3D/Crypto.h b/dep/g3dlite/G3D/Crypto.h new file mode 100644 index 00000000000..56c816a4977 --- /dev/null +++ b/dep/g3dlite/G3D/Crypto.h @@ -0,0 +1,96 @@ +/** + @file Crypto.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + + @created 2006-03-29 + @edited 2006-04-06 + */ + +#ifndef G3D_CRYPTO_H +#define G3D_CRYPTO_H + +#include "G3D/platform.h" +#include "G3D/g3dmath.h" +#include + +namespace G3D { + +/** See G3D::Crypto::md5 */ +class MD5Hash { +private: + + uint8 value[16]; + +public: + + MD5Hash() { + for (int i = 0; i < 16; ++i) { + value[i] = 0; + } + } + + explicit MD5Hash(class BinaryInput& b); + + uint8& operator[](int i) { + return value[i]; + } + + const uint8& operator[](int i) const { + return value[i]; + } + + bool operator==(const MD5Hash& other) const { + bool match = true; + for (int i = 0; i < 16; ++i) { + match = match && (other.value[i] == value[i]); + } + return match; + } + + inline bool operator!=(const MD5Hash& other) const { + return !(*this == other); + } + + void deserialize(class BinaryInput& b); + + void serialize(class BinaryOutput& b) const; +}; + + +/** Cryptography and hashing helper functions */ +class Crypto { +public: + + /** + Computes the CRC32 value of a byte array. CRC32 is designed to be a hash + function that produces different values for similar strings. + + This implementation is compatible with PKZIP and GZIP. + + Based on http://www.gamedev.net/reference/programming/features/crc32/ + */ + static uint32 crc32(const void* bytes, size_t numBytes); + + /** + Computes the MD5 hash (message digest) of a byte stream, as defined by + http://www.ietf.org/rfc/rfc1321.txt. + + @cite Based on implementation by L. Peter Deutsch, ghost@aladdin.com + */ + MD5Hash md5(const void* bytes, size_t numBytes); + + /** + Returns the nth prime less than 2000 in constant time. The first prime has index + 0 and is the number 2. + */ + static int smallPrime(int n); + + /** Returns 1 + the largest value that can be passed to smallPrime. */ + static int numSmallPrimes(); +}; + +} + +#endif diff --git a/dep/g3dlite/G3D/Cylinder.h b/dep/g3dlite/G3D/Cylinder.h new file mode 100644 index 00000000000..85eba77b794 --- /dev/null +++ b/dep/g3dlite/G3D/Cylinder.h @@ -0,0 +1,92 @@ +/** + @file Cylinder.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2003-02-07 + @edited 2005-09-26 + + Copyright 2000-2005, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_Cylinder_H +#define G3D_Cylinder_H + +#include "G3D/platform.h" +#include "G3D/g3dmath.h" +#include "G3D/Vector3.h" + +namespace G3D { + +class Line; +class AABox; +/** + Right cylinder + */ +class Cylinder { +private: + Vector3 p1; + Vector3 p2; + + float mRadius; + +public: + + /** Uninitialized */ + Cylinder(); + Cylinder(class BinaryInput& b); + Cylinder(const Vector3& _p1, const Vector3& _p2, float _r); + void serialize(class BinaryOutput& b) const; + void deserialize(class BinaryInput& b); + + /** The line down the center of the Cylinder */ + Line axis() const; + + /** + A reference frame in which the center of mass is at the origin and + the Y-axis is the cylinder's axis. If the cylinder is transformed, this reference frame + may freely rotate around its axis.*/ + void getReferenceFrame(class CoordinateFrame& cframe) const; + + /** Returns point 0 or 1 */ + inline const Vector3& point(int i) const { + debugAssert(i >= 0 && i <= 1); + return (i == 0) ? p1 : p2; + } + + /** + Returns true if the point is inside the Cylinder or on its surface. + */ + bool contains(const Vector3& p) const; + + float area() const; + + float volume() const; + + float radius() const; + + /** Center of mass */ + inline Vector3 center() const { + return (p1 + p2) / 2.0f; + } + + inline float height() const { + return (p1 - p2).magnitude(); + } + + /** + Get close axis aligned bounding box. + With vertical world orientation, the top and bottom might not be very tight. */ + void getBounds(AABox& out) const; + + /** Random world space point with outward facing normal. */ + void getRandomSurfacePoint(Vector3& P, Vector3& N) const; + + /** Point selected uniformly at random over the volume. */ + Vector3 randomInteriorPoint() const; +}; + +} // namespace + +#endif diff --git a/dep/g3dlite/G3D/EqualsTrait.h b/dep/g3dlite/G3D/EqualsTrait.h new file mode 100644 index 00000000000..349cb5088fb --- /dev/null +++ b/dep/g3dlite/G3D/EqualsTrait.h @@ -0,0 +1,26 @@ +/** + @file EqualsTrait.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + @created 2008-10-01 + @edited 2008-10-01 + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_EQUALSTRAIT_H +#define G3D_EQUALSTRAIT_H + +#include "G3D/platform.h" + +/** Default implementation of EqualsTrait. + @see G3D::Table for specialization requirements. +*/ +template struct EqualsTrait { + static bool equals(const Key& a, const Key& b) { + return a == b; + } +}; + +#endif + diff --git a/dep/g3dlite/G3D/G3D.h b/dep/g3dlite/G3D/G3D.h new file mode 100644 index 00000000000..5b56b9c71dc --- /dev/null +++ b/dep/g3dlite/G3D/G3D.h @@ -0,0 +1,162 @@ +/** + @file G3D.h + + This header includes all of the G3D libraries in + appropriate namespaces. + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2001-08-25 + @edited 2010-01-30 + + Copyright 2000-2010, Morgan McGuire. + All rights reserved. +*/ + +#ifndef G3D_G3D_h +#define G3D_G3D_h + +#define NOMINMAX 1 +#ifdef min + #undef min +#endif +#ifdef max + #undef max +#endif + +#include "G3D/platform.h" +#include "G3D/units.h" +#include "G3D/ParseError.h" +#include "G3D/Random.h" +#include "G3D/Array.h" +#include "G3D/SmallArray.h" +#include "G3D/Queue.h" +#include "G3D/Crypto.h" +#include "G3D/format.h" +#include "G3D/Vector2.h" +#include "G3D/Vector3.h" +#include "G3D/Vector4.h" +#include "G3D/Color1.h" +#include "G3D/Color3.h" +#include "G3D/Color4.h" +#include "G3D/Matrix2.h" +#include "G3D/Matrix3.h" +#include "G3D/Matrix4.h" +#include "G3D/CoordinateFrame.h" +#include "G3D/PhysicsFrame.h" +#include "G3D/Plane.h" +#include "G3D/Line.h" +#include "G3D/Ray.h" +#include "G3D/Sphere.h" +#include "G3D/Box.h" +#include "G3D/Box2D.h" +#include "G3D/AABox.h" +#include "G3D/WrapMode.h" +#include "G3D/Cone.h" +#include "G3D/Quat.h" +#include "G3D/stringutils.h" +#include "G3D/prompt.h" +#include "G3D/Table.h" +#include "G3D/Set.h" +#include "G3D/GUniqueID.h" +#include "G3D/BinaryFormat.h" +#include "G3D/BinaryInput.h" +#include "G3D/BinaryOutput.h" +#include "G3D/debug.h" +#include "G3D/g3dfnmatch.h" +#include "G3D/G3DGameUnits.h" +#include "G3D/g3dmath.h" +#include "G3D/uint128.h" +#include "G3D/fileutils.h" +#include "G3D/ReferenceCount.h" +#include "G3D/Welder.h" +#include "G3D/GMutex.h" +#include "G3D/PrecomputedRandom.h" +#include "G3D/MemoryManager.h" +#include "G3D/AreaMemoryManager.h" +#include "G3D/BumpMapPreprocess.h" + +template struct HashTrait< G3D::ReferenceCountedPointer > { + static size_t hashCode(G3D::ReferenceCountedPointer key) { return reinterpret_cast( key.pointer() ); } +}; + +#include "G3D/GImage.h" +#include "G3D/CollisionDetection.h" +#include "G3D/Intersect.h" +#include "G3D/Log.h" +#include "G3D/serialize.h" +#include "G3D/TextInput.h" +#include "G3D/NetAddress.h" +#include "G3D/NetworkDevice.h" +#include "G3D/System.h" +#include "G3D/splinefunc.h" +#include "G3D/Spline.h" +#include "G3D/UprightFrame.h" +#include "G3D/LineSegment.h" +#include "G3D/Capsule.h" +#include "G3D/Cylinder.h" +#include "G3D/Triangle.h" +#include "G3D/Color3uint8.h" +#include "G3D/Color4uint8.h" +#include "G3D/Vector2int16.h" +#include "G3D/Vector3int16.h" +#include "G3D/Vector3int32.h" +#include "G3D/Vector4int8.h" +#include "G3D/ConvexPolyhedron.h" +#include "G3D/MeshAlg.h" +#include "G3D/vectorMath.h" +#include "G3D/Rect2D.h" +#include "G3D/GCamera.h" +#include "G3D/GLight.h" +#include "G3D/KDTree.h" +#include "G3D/PointKDTree.h" +#include "G3D/TextOutput.h" +#include "G3D/MeshBuilder.h" +#include "G3D/Stopwatch.h" +#include "G3D/AtomicInt32.h" +#include "G3D/GThread.h" +#include "G3D/ThreadSet.h" +#include "G3D/RegistryUtil.h" +#include "G3D/Any.h" +#include "G3D/PointHashGrid.h" +#include "G3D/Map2D.h" +#include "G3D/Image1.h" +#include "G3D/Image1uint8.h" +#include "G3D/Image3.h" +#include "G3D/Image3uint8.h" +#include "G3D/Image4.h" +#include "G3D/Image4uint8.h" +#include "G3D/filter.h" +#include "G3D/WeakCache.h" +#include "G3D/Pointer.h" +#include "G3D/Matrix.h" +#include "G3D/ImageFormat.h" + +#ifdef _MSC_VER +# pragma comment(lib, "zlib") +# pragma comment(lib, "ws2_32") +# pragma comment(lib, "winmm") +# pragma comment(lib, "imagehlp") +# pragma comment(lib, "gdi32") +# pragma comment(lib, "user32") +# pragma comment(lib, "kernel32") +# pragma comment(lib, "version") +# pragma comment(lib, "advapi32") +# pragma comment(lib, "png") +# pragma comment(lib, "jpeg") +# pragma comment(lib, "zip") +# ifdef _DEBUG + // Don't link against G3D when building G3D itself. +# ifndef G3D_BUILDING_LIBRARY_DLL +# pragma comment(lib, "G3Dd.lib") +# endif +# else + // Don't link against G3D when building G3D itself. +# ifndef G3D_BUILDING_LIBRARY_DLL +# pragma comment(lib, "G3D.lib") +# endif +# endif +#endif + +#endif + diff --git a/dep/g3dlite/G3D/G3DAll.h b/dep/g3dlite/G3D/G3DAll.h new file mode 100644 index 00000000000..1176fe742e7 --- /dev/null +++ b/dep/g3dlite/G3D/G3DAll.h @@ -0,0 +1,26 @@ +/** + @file G3DAll.h + + Includes all G3D and GLG3D files and uses the G3D namespace. + + This requires OpenGL and SDL headers. If you don't want all of this, + \#include separately. + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2002-01-01 + @edited 2006-08-13 + + Copyright 2000-2006, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_G3DALL_H +#define G3D_G3DALL_H + +#include "G3D/G3D.h" +#include "GLG3D/GLG3D.h" + +using namespace G3D; + +#endif diff --git a/dep/g3dlite/G3D/G3DGameUnits.h b/dep/g3dlite/G3D/G3DGameUnits.h new file mode 100644 index 00000000000..e2bc2c811e8 --- /dev/null +++ b/dep/g3dlite/G3D/G3DGameUnits.h @@ -0,0 +1,42 @@ +/** + @file G3DGameUnits.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + @created 2002-10-05 + @edited 2006-11-10 + */ + +#ifndef G3D_GAMEUNITS_H +#define G3D_GAMEUNITS_H + +#include "G3D/platform.h" + +namespace G3D { +/** + Time, in seconds. + */ +typedef double GameTime; +typedef double SimTime; + +/** + Actual wall clock time in seconds. + */ +typedef double RealTime; + +enum AMPM {AM, PM}; + +/** \deprecated */ +enum {SECOND=1, MINUTE=60, HOUR = 60*60, DAY=24*60*60, SUNRISE=24*60*60/4, SUNSET=24*60*60*3/4, MIDNIGHT=0, METER=1, KILOMETER=1000}; + +/** + Converts a 12 hour clock time into the number of seconds since + midnight. Note that 12:00 PM is noon and 12:00 AM is midnight. + + Example: toSeconds(10, 00, AM) + */ +SimTime toSeconds(int hour, int minute, double seconds, AMPM ap); +SimTime toSeconds(int hour, int minute, AMPM ap); + +} + +#endif diff --git a/dep/g3dlite/G3D/GCamera.h b/dep/g3dlite/G3D/GCamera.h new file mode 100644 index 00000000000..018fbc85d59 --- /dev/null +++ b/dep/g3dlite/G3D/GCamera.h @@ -0,0 +1,337 @@ +/** + @file GCamera.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2005-07-20 + @edited 2009-04-20 +*/ + +#ifndef G3D_GCamera_H +#define G3D_GCamera_H + +#include "G3D/platform.h" +#include "G3D/CoordinateFrame.h" +#include "G3D/Vector3.h" +#include "G3D/Plane.h" +#include "G3D/debugAssert.h" + +namespace G3D { + +class Matrix4; +class Rect2D; +class Any; + +/** + Abstraction of a pinhole camera. + + The area a camera sees is called a frustum. It is bounded by the + near plane, the far plane, and the sides of the view frame projected + into the scene. It has the shape of a pyramid with the top cut off. + + Cameras can project points from 3D to 2D. The "unit" projection + matches OpenGL. It maps the entire view frustum to a cube of unit + radius (i.e., edges of length 2) centered at the origin. The + non-unit projection then maps that cube to the specified pixel + viewport in X and Y and the range [0, 1] in Z. The projection is + reversable as long as the projected Z value is known. + + All viewport arguments are the pixel bounds of the viewport-- e.g., + RenderDevice::viewport(). + */ +class GCamera { + +public: + /** + Stores the direction of the field of view + */ + enum FOVDirection {HORIZONTAL, VERTICAL}; + +private: + + /** Full field of view (in radians) */ + float m_fieldOfView; + + /** Clipping plane, *not* imaging plane. Negative numbers. */ + float m_nearPlaneZ; + + /** Negative */ + float m_farPlaneZ; + + /** Stores the camera's location and orientation */ + CoordinateFrame m_cframe; + + /** Horizontal or Vertical */ + FOVDirection m_direction; + +public: + + /** Must be of the format produced by the Any cast, e.g., + +
+        GCamera {
+            coordinateFrame = CFrame::fromXYZYPRDegrees(-13.3f, 8.0f, -1.9f, 246.6f, -3),
+            nearPlaneZ = -0.5,
+            farPlaneZ = -50,
+            fovDirection = "HORIZONTAL",
+            fovAngleDegrees = 90
+        }
+ + Missing fields are filled from the default GCamera constructor. + */ + GCamera(const Any& any); + + operator Any() const; + + class Frustum { + public: + class Face { + public: + /** Counter clockwise indices into vertexPos */ + int vertexIndex[4]; + + /** The plane containing the face. */ + Plane plane; + }; + + /** The vertices, in homogeneous space. If w == 0, + a vertex is at infinity. */ + Array vertexPos; + + /** The faces in the frustum. When the + far plane is at infinity, there are 5 faces, + otherwise there are 6. The faces are in the order + N,R,L,B,T,[F]. + */ + Array faceArray; + }; + + GCamera(); + + GCamera(const Matrix4& proj, const CFrame& frame); + + virtual ~GCamera(); + + /** Returns the current coordinate frame */ + const CoordinateFrame& coordinateFrame() const { + return m_cframe; + } + + /** Sets c to the camera's coordinate frame */ + void getCoordinateFrame(CoordinateFrame& c) const; + + /** Sets a new coordinate frame for the camera */ + void setCoordinateFrame(const CoordinateFrame& c); + + /** Sets \a P equal to the camera's projection matrix. This is the + matrix that maps points to the homogeneous clip cube that + varies from -1 to 1 on all axes. The projection matrix does + not include the camera transform. + + This is the matrix that a RenderDevice (or OpenGL) uses as the projection matrix. + @sa RenderDevice::setProjectionAndCameraMatrix, RenderDevice::setProjectionMatrix, Matrix4::perspectiveProjection + */ + void getProjectUnitMatrix(const Rect2D& viewport, Matrix4& P) const; + + /** Sets \a P equal to the matrix that transforms points to pixel + coordinates on the given viewport. A point correspoinding to + the top-left corner of the viewport in camera space will + transform to viewport.x0y0() and the bottom-right to viewport.x1y1(). */ + void getProjectPixelMatrix(const Rect2D& viewport, Matrix4& P) const; + + /** Converts projected points from OpenGL standards + (-1, 1) to normal 3D coordinate standards (0, 1) + + \deprecated + */ // TODO: Remove + Vector3 convertFromUnitToNormal(const Vector3& in, const Rect2D& viewport) const; + + /** + Sets the field of view, in radians. The + initial angle is toRadians(55). Must specify + the direction of the angle. + + This is the full angle, i.e., from the left side of the + viewport to the right side. + */ + void setFieldOfView(float angle, FOVDirection direction); + + /** Returns the current full field of view angle (from the left side of the + viewport to the right side) and direction */ + inline void getFieldOfView(float& angle, FOVDirection& direction) const { + angle = m_fieldOfView; + direction = m_direction; + } + + /** + Projects a world space point onto a width x height screen. The + returned coordinate uses pixmap addressing: x = right and y = + down. The resulting z value is 0 at the near plane, 1 at the far plane, + and is a linear compression of unit cube projection. + + If the point is behind the camera, Vector3::inf() is returned. + */ + Vector3 project(const G3D::Vector3& point, + const class Rect2D& viewport) const; + + /** + Projects a world space point onto a unit cube. The resulting + x,y,z values range between -1 and 1, where z is -1 + at the near plane and 1 at the far plane and varies hyperbolically in between. + + If the point is behind the camera, Vector3::inf() is returned. + */ + Vector3 projectUnit(const G3D::Vector3& point, + const class Rect2D& viewport) const; + + /** + Gives the world-space coordinates of screen space point v, where + v.x is in pixels from the left, v.y is in pixels from + the top, and v.z is on the range 0 (near plane) to 1 (far plane). + */ + Vector3 unproject(const Vector3& v, const Rect2D& viewport) const; + + /** + Gives the world-space coordinates of unit cube point v, where + v varies from -1 to 1 on all axes. The unproject first + transforms the point into a pixel location for the viewport, then calls unproject + */ + Vector3 unprojectUnit(const Vector3& v, const Rect2D& viewport) const; + + /** + Returns the pixel area covered by a shape of the given + world space area at the given z value (z must be negative). + */ + float worldToScreenSpaceArea(float area, float z, const class Rect2D& viewport) const; + + /** + Returns the world space 3D viewport corners. These + are at the near clipping plane. The corners are constructed + from the nearPlaneZ, viewportWidth, and viewportHeight. + "left" and "right" are from the GCamera's perspective. + */ + void getNearViewportCorners(const class Rect2D& viewport, + Vector3& outUR, Vector3& outUL, + Vector3& outLL, Vector3& outLR) const; + + /** + Returns the world space 3D viewport corners. These + are at the Far clipping plane. The corners are constructed + from the nearPlaneZ, farPlaneZ, viewportWidth, and viewportHeight. + "left" and "right" are from the GCamera's perspective. + */ + void getFarViewportCorners(const class Rect2D& viewport, + Vector3& outUR, Vector3& outUL, + Vector3& outLL, Vector3& outLR) const; + + /** + Returns the image plane depth, assumes imagePlane + is the same as the near clipping plane. + returns a positive number. + */ + float imagePlaneDepth() const; + + /** + Returns the world space ray passing through the center of pixel + (x, y) on the image plane. The pixel x and y axes are opposite + the 3D object space axes: (0,0) is the upper left corner of the screen. + They are in viewport coordinates, not screen coordinates. + + The ray origin is at the origin. To start it at the image plane, + move it forward by imagePlaneDepth/ray.direction.z + + Integer (x, y) values correspond to + the upper left corners of pixels. If you want to cast rays + through pixel centers, add 0.5 to x and y. + */ + Ray worldRay( + float x, + float y, + const class Rect2D& viewport) const; + + /** + Returns a negative z-value. + */ + inline float nearPlaneZ() const { + return m_nearPlaneZ; + } + + /** + Returns a negative z-value. + */ + inline float farPlaneZ() const { + return m_farPlaneZ; + } + + /** + Sets a new value for the far clipping plane + Expects a negative value + */ + inline void setFarPlaneZ(float z) { + debugAssert(z < 0); + m_farPlaneZ = z; + } + + /** + Sets a new value for the near clipping plane + Expects a negative value + */ + inline void setNearPlaneZ(float z) { + debugAssert(z < 0); + m_nearPlaneZ = z; + } + + /** + Returns the camera space width of the viewport at the near plane. + */ + float viewportWidth(const class Rect2D& viewport) const; + + /** + Returns the camera space height of the viewport at the near plane. + */ + float viewportHeight(const class Rect2D& viewport) const; + + void setPosition(const Vector3& t); + + /** Rotate the camera in place to look at the target. Does not + persistently look at that location when the camera moves; + i.e., if you move the camera and still want it to look at the + old target, you must call lookAt again after moving the + camera.)*/ + void lookAt(const Vector3& position, const Vector3& up = Vector3::unitY()); + + /** + Returns the clipping planes of the frustum, in world space. + The planes have normals facing into the view frustum. + + The plane order is guaranteed to be: + Near, Right, Left, Top, Bottom, [Far] + + If the far plane is at infinity, the resulting array will have + 5 planes, otherwise there will be 6. + + The viewport is used only to determine the aspect ratio of the screen; the + absolute dimensions and xy values don't matter. + */ + void getClipPlanes + ( + const Rect2D& viewport, + Array& outClip) const; + + /** + Returns the world space view frustum, which is a truncated pyramid describing + the volume of space seen by this camera. + */ + void frustum(const Rect2D& viewport, GCamera::Frustum& f) const; + + GCamera::Frustum frustum(const Rect2D& viewport) const; + + /** Read and Write camera parameters */ + void serialize(class BinaryOutput& bo) const; + void deserialize(class BinaryInput& bi); + +}; + +} // namespace G3D + +#endif diff --git a/dep/g3dlite/G3D/GImage.h b/dep/g3dlite/G3D/GImage.h new file mode 100644 index 00000000000..8ae11134fc9 --- /dev/null +++ b/dep/g3dlite/G3D/GImage.h @@ -0,0 +1,607 @@ +/** + \file GImage.h + + See G3D::GImage for details. + + @cite JPEG compress/decompressor is the IJG library, used in accordance with their license. + @cite JPG code by John Chisholm, using the IJG Library + @cite TGA code by Morgan McGuire + @cite BMP code by John Chisholm, based on code by Edward "CGameProgrammer" Resnick mailto:cgp@gdnmail.net at ftp://ftp.flipcode.com/cotd/LoadPicture.txt + @cite PCX format described in the ZSOFT PCX manual http://www.nist.fss.ru/hr/doc/spec/pcx.htm#2 + @cite PNG compress/decompressor is the libpng library, used in accordance with their license. + @cite PPM code by Morgan McGuire based on http://netpbm.sourceforge.net/doc/ppm.html + + \maintainer Morgan McGuire, http://graphics.cs.williams.edu + + \created 2002-05-27 + \edited 2010-01-04 + + Copyright 2000-2010, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_GImage_h +#define G3D_GImage_h + +#include "G3D/platform.h" +#include +#include "G3D/Array.h" +#include "G3D/g3dmath.h" +#include "G3D/stringutils.h" +#include "G3D/Color1uint8.h" +#include "G3D/Color3uint8.h" +#include "G3D/Color4uint8.h" +#include "G3D/MemoryManager.h" +#include "G3D/BumpMapPreprocess.h" + +namespace G3D { +class BinaryInput; +class BinaryOutput; + + +/** + Interface to image compression & file formats. + + Supported formats (decode and encode): Color JPEG, PNG, + (Uncompressed)TGA 24, (Uncompressed)TGA 32, BMP 1, BMP 4, BMP 8, BMP + 24, PPM (P6), and PPM ASCII (P1, P2, P3), which includes PPM, PGM, + and PBM. 8-bit paletted PCX, 24-bit PCX, and ICO are supported for + decoding only. + + Sample usage: + + \verbatim + // Loading from disk: + G3D::GImage im1("test.jpg"); + + // Loading from memory: + G3D::GImage im2(data, length); + + // im.pixel is a pointer to RGB color data. If you want + // an alpha channel, call RGBtoRGBA or RGBtoARGB for + // conversion. + + // Saving to memory: + G3D::GImage im3(width, height); + // (Set the pixels of im3...) + uint8* data2; + int len2; + im3.encode(G3D::GImage::JPEG, data2, len2); + + // Saving to disk + im3.save("out.jpg"); + \endverbatim + + The free Image Magick Magick Wand API + (http://www.imagemagick.org/www/api/magick_wand.html) provides a more powerful + API for image manipulation and wider set of image load/save formats. It is + recommended over GImage (we don't include it directly in G3D because their license + is more restrictive than the BSD one). + + */ +class GImage { +private: + + /** Used exclusively for allocating m_byte; this may be an + implementation that allocates directly on a GPU.*/ + MemoryManager::Ref m_memMan; + uint8* m_byte; + + int m_channels; + int m_width; + int m_height; + +public: + + class Error { + public: + Error( + const std::string& reason, + const std::string& filename = "") : + reason(reason), filename(filename) {} + + std::string reason; + std::string filename; + }; + + /** PGM, PPM, and PBM all come in two versions and are classified as PPM_* files */ + enum Format {JPEG, BMP, TGA, PCX, ICO, PNG, + PPM_BINARY, PGM_BINARY = PPM_BINARY, + PPM_ASCII, PGM_ASCII = PPM_ASCII, + AUTODETECT, UNKNOWN}; + + + /** + The number of channels; either 3 (RGB) or 4 (RGBA) + */ + inline int channels() const { + return m_channels; + } + + inline int width() const { + return m_width; + } + + inline int height() const { + return m_height; + } + + inline const uint8* byte() const { + return m_byte; + } + + /** Returns a pointer to the underlying data, which is stored + in row-major order without row padding. + e.g., uint8* ptr = image.rawData(); + */ + template + inline const Type* rawData() const { + return (Type*)m_byte; + } + + /** \copybrief GImage::rawData() const */ + template + inline Type* rawData() { + return (Type*)m_byte; + } + + inline const Color1uint8* pixel1() const { + debugAssertM(m_channels == 1, format("Tried to call GImage::pixel1 on an image with %d channels", m_channels)); + return (Color1uint8*)m_byte; + } + + inline Color1uint8* pixel1() { + debugAssertM(m_channels == 1, format("Tried to call GImage::pixel1 on an image with %d channels", m_channels)); + return (Color1uint8*)m_byte; + } + + /** Returns a pointer to the upper left pixel + as Color4uint8. + */ + inline const Color4uint8* pixel4() const { + debugAssertM(m_channels == 4, format("Tried to call GImage::pixel4 on an image with %d channels", m_channels)); + return (Color4uint8*)m_byte; + } + + inline Color4uint8* pixel4() { + debugAssert(m_channels == 4); + return (Color4uint8*)m_byte; + } + + /** Returns a pointer to the upper left pixel + as Color3uint8. + */ + inline const Color3uint8* pixel3() const { + debugAssertM(m_channels == 3, format("Tried to call GImage::pixel3 on an image with %d channels", m_channels)); + return (Color3uint8*)m_byte; + } + + inline Color3uint8* pixel3() { + debugAssert(m_channels == 3); + return (Color3uint8*)m_byte; + } + + /** Returns the pixel at (x, y), where (0,0) is the upper left. */ + inline const Color1uint8& pixel1(int x, int y) const { + debugAssert(x >= 0 && x < m_width); + debugAssert(y >= 0 && y < m_height); + return pixel1()[x + y * m_width]; + } + + /** Returns the pixel at (x, y), where (0,0) is the upper left. */ + inline Color1uint8& pixel1(int x, int y) { + debugAssert(x >= 0 && x < m_width); + debugAssert(y >= 0 && y < m_height); + return pixel1()[x + y * m_width]; + } + + /** Returns the pixel at (x, y), where (0,0) is the upper left. */ + inline const Color3uint8& pixel3(int x, int y) const { + debugAssert(x >= 0 && x < m_width); + debugAssert(y >= 0 && y < m_height); + return pixel3()[x + y * m_width]; + } + + inline Color3uint8& pixel3(int x, int y) { + debugAssert(x >= 0 && x < m_width); + debugAssert(y >= 0 && y < m_height); + return pixel3()[x + y * m_width]; + } + + /** Returns the pixel at (x, y), where (0,0) is the upper left. */ + inline const Color4uint8& pixel4(int x, int y) const { + debugAssert(x >= 0 && x < m_width); + debugAssert(y >= 0 && y < m_height); + return pixel4()[x + y * m_width]; + } + + inline Color4uint8& pixel4(int x, int y) { + debugAssert(x >= 0 && x < m_width); + debugAssert(y >= 0 && y < m_height); + return pixel4()[x + y * m_width]; + } + + inline uint8* byte() { + return m_byte; + } + +private: + + void encodeBMP( + BinaryOutput& out) const; + + /** + The TGA file will be either 24- or 32-bit depending + on the number of channels. + */ + void encodeTGA( + BinaryOutput& out) const; + + /** + Converts this image into a JPEG + */ + void encodeJPEG( + BinaryOutput& out) const; + + /** + Converts this image into a JPEG + */ + void encodePNG( + BinaryOutput& out) const; + + void encodePPM( + BinaryOutput& out) const; + + void encodePPMASCII( + BinaryOutput& out) const; + + void decodeTGA( + BinaryInput& input); + + void decodeBMP( + BinaryInput& input); + + void decodeJPEG( + BinaryInput& input); + + void decodePCX( + BinaryInput& input); + + void decodeICO( + BinaryInput& input); + + void decodePNG( + BinaryInput& input); + + void decodePPM( + BinaryInput& input); + + void decodePPMASCII( + BinaryInput& input); + + /** + Given [maybe] a filename, memory buffer, and [maybe] a format, + returns the most likely format of this file. + */ + static Format resolveFormat( + const std::string& filename, + const uint8* data, + int dataLen, + Format maybeFormat); + + void _copy( + const GImage& other); + +public: + + /** Predicts the image file format of \a filename */ + static Format resolveFormat(const std::string& filename); + + void flipHorizontal(); + void flipVertical(); + void rotate90CW(int numTimes = 1); + + /** + Create an empty image of the given size. + \sa load() + */ + GImage( + int width = 0, + int height = 0, + int channels = 3, + const MemoryManager::Ref& m = MemoryManager::create()); + + /** + Load an encoded image from disk and decode it. + Throws GImage::Error if something goes wrong. + */ + GImage( + const std::string& filename, + Format format = AUTODETECT, + const MemoryManager::Ref& m = MemoryManager::create()); + + /** + Decodes an image stored in a buffer. + */ + GImage( + const unsigned char*data, + int length, + Format format = AUTODETECT, + const MemoryManager::Ref& m = MemoryManager::create()); + + GImage( + const GImage& other, + const MemoryManager::Ref& m = MemoryManager::create()); + + GImage& operator=(const GImage& other); + + /** + Returns a new GImage that has 4 channels. RGB is + taken from this GImage and the alpha from the red + channel of the supplied image. The new GImage is passed + as a reference parameter for speed. + */ + void insertRedAsAlpha(const GImage& alpha, GImage& output) const; + + /** + Returns a new GImage with 3 channels, removing + the alpha channel if there is one. The new GImage + is passed as a reference parameter for speed. + */ + void stripAlpha(GImage& output) const; + + /** + Loads an image from disk (clearing the old one first), + using the existing memory manager. + */ + void load( + const std::string& filename, + Format format = AUTODETECT); + + /** + Frees memory and resets to a 0x0 image. + */ + void clear(); + + /** + Deallocates the pixels. + */ + virtual ~GImage(); + + /** + Resizes the internal buffer to (\a width x \a height) with the + number of \a channels specified. + + \param zero If true, all data is set to 0 (black). + */ + void resize(int width, int height, int channels, bool zero = true); + + /** + Copies src sub-image data into dest at a certain offset. + The dest variable must already contain an image that is large + enough to contain the src sub-image at the specified offset. + Returns true on success and false if the src sub-image cannot + completely fit within dest at the specified offset. Both + src and dest must have the same number of channels. + */ + static bool pasteSubImage( + GImage& dest, + const GImage& src, + int destX, + int destY, + int srcX, + int srcY, + int srcWidth, + int srcHeight); + + /** + creates dest from src sub-image data. + Returns true on success and false if the src sub-image + is not within src. + */ + static bool copySubImage(GImage & dest, const GImage & src, + int srcX, int srcY, int srcWidth, int srcHeight); + + void convertToRGBA(); + + void convertToRGB(); + + /** Averages color channels if they exist */ + void convertToL8(); + + /** + Returns true if format is supported. Format + should be an extension string (e.g. "BMP"). + */ + static bool supportedFormat( + const std::string& format); + + /** + Converts a string to an enum, returns UNKNOWN if not recognized. + */ + static Format stringToFormat( + const std::string& format); + + /** + Encode and save to disk. + */ + void save( + const std::string& filename, + Format format = AUTODETECT) const; + + /** + The caller must delete the returned buffer. + TODO: provide a memory manager + */ + void encode( + Format format, + uint8*& outData, + int& outLength) const; + + /** + Does not commit the BinaryOutput when done. + */ + void encode( + Format format, + BinaryOutput& out) const; + + /** + Decodes the buffer into this image. + @param format Must be the correct format. + */ + void decode( + BinaryInput& input, + Format format); + + /** Returns the size of this object in bytes */ + int sizeInMemory() const; + + /** Ok for in == out */ + static void R8G8B8_to_Y8U8V8(int width, int height, const uint8* in, uint8* out); + + /** Ok for in == out */ + static void Y8U8V8_to_R8G8B8(int width, int height, const uint8* in, uint8* out); + + /** + @param in RGB buffer of numPixels * 3 bytes + @param out Buffer of numPixels * 4 bytes + @param numPixels Number of RGB pixels to convert + */ + static void RGBtoRGBA( + const uint8* in, + uint8* out, + int numPixels); + + static void RGBtoARGB( + const uint8* in, + uint8* out, + int numPixels); + + static void LtoRGB + (const uint8* in, + uint8* out, + int numPixels); + + static void LtoRGBA + (const uint8* in, + uint8* out, + int numPixels); + + /** Safe for in == out */ + static void RGBtoBGR( + const uint8* in, + uint8* out, + int numPixels); + + /** + Win32 32-bit HDC format. + */ + static void RGBtoBGRA( + const uint8* in, + uint8* out, + int numPixels); + + static void RGBAtoRGB( + const uint8* in, + uint8* out, + int numPixels); + /** + Uses the red channel of the second image as an alpha channel. + */ + static void RGBxRGBtoRGBA( + const uint8* colorRGB, + const uint8* alphaRGB, + uint8* out, + int numPixels); + + /** + Flips the image along the vertical axis. + Safe for in == out. + */ + static void flipRGBVertical( + const uint8* in, + uint8* out, + int width, + int height); + + static void flipRGBAVertical( + const uint8* in, + uint8* out, + int width, + int height); + + /** + Given a tangent space bump map, computes a new image where the + RGB channels are a tangent space normal map and the alpha channel + is the original bump map. Assumes the input image is tileable. + + In the resulting image, x = red = tangent, y = green = binormal, and z = blue = normal. + + Particularly useful as part of the idiom: +
+ 	    GImage normal;
+	    computeNormalMap(GImage(filename), normal);
+	    return Texture::fromGImage(filename, normal);
+    
+ + */ + static void computeNormalMap( + const class GImage& bump, + class GImage& normal, + const BumpMapPreprocess& preprocess = BumpMapPreprocess()); + + static void computeNormalMap + (int width, + int height, + int channels, + const uint8* src, + GImage& normal, + const BumpMapPreprocess& preprocess = BumpMapPreprocess()); + + /** + Bayer demosaicing using the filter proposed in + + HIGH-QUALITY LINEAR INTERPOLATION FOR DEMOSAICING OF BAYER-PATTERNED COLOR IMAGES + Henrique S. Malvar, Li-wei He, and Ross Cutler + + The filter wraps at the image boundaries. + + Assumes in != out. + */ + static void BAYER_G8B8_R8G8_to_R8G8B8_MHC(int w, int h, const uint8* in, uint8* _out); + static void BAYER_G8R8_B8G8_to_R8G8B8_MHC(int w, int h, const uint8* in, uint8* _out); + static void BAYER_R8G8_G8B8_to_R8G8B8_MHC(int w, int h, const uint8* in, uint8* _out); + static void BAYER_B8G8_G8R8_to_R8G8B8_MHC(int w, int h, const uint8* in, uint8* _out); + + /** Fast conversion; the output has 1/2 the size of the input in each direction. Assumes in != out. + See G3D::BAYER_G8B8_R8G8_to_R8G8B8_MHC for a much better result. */ + static void BAYER_G8B8_R8G8_to_Quarter_R8G8B8 + (int inWidth, + int inHeight, + const uint8* in, + uint8* out); + + /** Attempt to undo fast conversion of G3D::BAYER_G8B8_R8G8_to_Quarter_R8G8B8; + the green channel will lose data. Assumes in != out + The input should have size 3 * inWidth * inHeight. The output should have size + 2 * inWidth * 2 * inHeight. + */ + static void Quarter_R8G8B8_to_BAYER_G8B8_R8G8 + (int inWidth, + int inHeight, + const uint8* in, + uint8* out); + + /** Overwrites every pixel with one of the two colors in a checkerboard pattern. + The fields used from the two colors depend on the current number of channels in @a im. + */ + static void makeCheckerboard + (GImage& im, + int checkerSize = 1, + const Color4uint8& color1 = Color4uint8(255,255,255,255), + const Color4uint8& color2 = Color4uint8(0,0,0,255)); +}; + +} + +#endif diff --git a/dep/g3dlite/G3D/GLight.h b/dep/g3dlite/G3D/GLight.h new file mode 100644 index 00000000000..3a95f1a8114 --- /dev/null +++ b/dep/g3dlite/G3D/GLight.h @@ -0,0 +1,106 @@ +/** + @file GLight.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2003-11-12 + @edited 2009-11-08 +*/ + +#ifndef G3D_GLight_h +#define G3D_GLight_h + +#include "G3D/platform.h" +#include "G3D/Vector4.h" +#include "G3D/Vector3.h" +#include "G3D/Color4.h" + +namespace G3D { +class Any; + +/** + A light representation that closely follows the OpenGL light format. + */ +class GLight { +public: + /** World space position (for a directional light, w = 0 */ + Vector4 position; + + /** For a spot or directional light, this is the "right vector" that will be used when constructing + a reference frame(). */ + Vector3 rightDirection; + + /** Direction in which the light faces, if a spot light. This is the "look vector" of the light source. */ + Vector3 spotDirection; + + /** In degrees. 180 = no cutoff (point/dir). Values less than 90 = spot light */ + float spotCutoff; + + /** If true, G3D::SuperShader will render a cone of light large + enough to encompass the entire square that bounds the cutoff + angle. This produces a square prism instead of a cone of light + when used with a G3D::ShadowMap. for an unshadowed light this + has no effect.*/ + bool spotSquare; + + /** Constant, linear, quadratic */ + float attenuation[3]; + + /** May be outside the range [0, 1] */ + Color3 color; + + /** If false, this light is ignored */ + bool enabled; + + /** If false, this light does not create specular highlights + (useful when using negative lights). */ + bool specular; + + /** If false, this light does not create diffuse illumination + (useful when rendering a specular-only pass). */ + bool diffuse; + + GLight(); + + /** Accepted forms: + - GLight::directional( vector3, color3, [bool, [bool]]) + - GLight::spot(vector3, vector3, #, color3, [#, [#, [#, [#, [bool, [bool]]]]) + - GLight::point(vector3, color3, [#, [#, [#, [#, [bool, [bool]]]]) + - GLight { [all fields] } + */ + GLight(const Any& any); + + /** Converts the Color3 to an Any. */ + operator Any() const; + + /** @param toLight will be normalized */ + static GLight directional(const Vector3& toLight, const Color3& color, bool specular = true, bool diffuse = true); + + static GLight point(const Vector3& pos, const Color3& color, float constAtt = 1, float linAtt = 0, float quadAtt = 0.5f, bool specular = true, bool diffuse = true); + + /** @param pointDirection Will be normalized. Points in the + direction that light propagates. + + @param cutOffAngleDegrees Must be on the range [0, 90]. This + is the angle from the point direction to the edge of the light + cone. I.e., a value of 45 produces a light with a 90-degree + cone of view. + */ + static GLight spot(const Vector3& pos, const Vector3& pointDirection, float cutOffAngleDegrees, + const Color3& color, float constAtt = 1, float linAtt = 0, float quadAtt = 0, + bool specular = true, bool diffuse = true); + + /** Returns the sphere within which this light has some noticable effect. May be infinite. + @param cutoff The value at which the light intensity is considered negligible. */ + class Sphere effectSphere(float cutoff = 30.0f / 255) const; + + /** Computes a reference frame (e.g., for use with G3D::ShadowMap */ + class CoordinateFrame frame() const; + + bool operator==(const GLight& other) const; + bool operator!=(const GLight& other) const; +}; + +} // namespace +#endif + diff --git a/dep/g3dlite/G3D/GMutex.h b/dep/g3dlite/G3D/GMutex.h new file mode 100644 index 00000000000..3469b812736 --- /dev/null +++ b/dep/g3dlite/G3D/GMutex.h @@ -0,0 +1,123 @@ +/** + @file GMutex.h + + @created 2005-09-22 + @edited 2009-03-25 + */ + +#ifndef G3D_GMutex_h +#define G3D_GMutex_h + +#include "G3D/platform.h" +#include "G3D/AtomicInt32.h" +#include "G3D/debugAssert.h" +#include + +#ifndef G3D_WIN32 +# include +# include +#endif + + +namespace G3D { + +/** + \brief A mutual exclusion lock that busy-waits when locking. + + On a machine with one (significant) thread per processor core, + a spinlock may be substantially faster than a mutex. + + \sa G3D::GThread, G3D::GMutex, G3D::AtomicInt32 + */ +class Spinlock { +private: + + AtomicInt32 x; + +public: + + inline Spinlock() : x(0) {} + + /** Busy waits until the lock is unlocked, then locks it + exclusively. Returns true if the lock succeeded on the first + try (indicating no contention). */ + inline bool lock() { + bool first = true; + while (x.compareAndSet(0, 1) == 1) { + first = false; +# ifdef G3D_WIN32 + Sleep(0); +# else + usleep(0); +# endif + } + return first; + } + + inline void unlock() { + x.compareAndSet(1, 0); + } + +}; + +/** + \brief Mutual exclusion lock used for synchronization. + + @sa G3D::GThread, G3D::AtomicInt32, G3D::Spinlock +*/ +class GMutex { +private: +# ifdef G3D_WIN32 + CRITICAL_SECTION m_handle; +# else + pthread_mutex_t m_handle; + pthread_mutexattr_t m_attr; +# endif + + // Not implemented on purpose, don't use + GMutex(const GMutex &mlock); + GMutex &operator=(const GMutex &); + bool operator==(const GMutex&); + +public: + GMutex(); + ~GMutex(); + + /** Locks the mutex or blocks until available. */ + void lock(); + + /** Locks the mutex if it not already locked. + Returns true if lock successful, false otherwise. */ + bool tryLock(); + + /** Unlocks the mutex. */ + void unlock(); +}; + + +/** + Automatically locks while in scope. +*/ +class GMutexLock { +private: + GMutex* m; + + // Not implemented on purpose, don't use + GMutexLock(const GMutexLock &mlock); + GMutexLock &operator=(const GMutexLock &); + bool operator==(const GMutexLock&); + +public: + GMutexLock(GMutex* mutex) { + m = mutex; + m->lock(); + } + + ~GMutexLock() { + m->unlock(); + } +}; + +} // G3D + +#endif diff --git a/dep/g3dlite/G3D/GThread.h b/dep/g3dlite/G3D/GThread.h new file mode 100644 index 00000000000..58437efc3fb --- /dev/null +++ b/dep/g3dlite/G3D/GThread.h @@ -0,0 +1,121 @@ +/** + @file GThread.h + + @created 2005-09-22 + @edited 2007-01-31 + + */ + +#ifndef G3D_GTHREAD_H +#define G3D_GTHREAD_H + +#include "G3D/platform.h" +#include "G3D/ReferenceCount.h" +#include + +#ifndef G3D_WIN32 +# include +# include +#endif + + +namespace G3D { + +typedef ReferenceCountedPointer GThreadRef; + +/** + Platform independent thread implementation. You can either subclass and + override GThread::threadMain or call the create method with a method. + + Beware of reference counting and threads. If circular references exist between + GThread subclasses then neither class will ever be deallocated. Also, + dropping all pointers (and causing deallocation) of a GThread does NOT + stop the underlying process. + + @sa G3D::GMutex, G3D::Spinlock, G3D::AtomicInt32 +*/ +class GThread : public ReferenceCountedObject { +private: + // "Status" is a reserved work on FreeBSD + enum GStatus {STATUS_CREATED, STATUS_STARTED, STATUS_RUNNING, STATUS_COMPLETED}; + + // Not implemented on purpose, don't use + GThread(const GThread &); + GThread& operator=(const GThread&); + bool operator==(const GThread&); + +#ifdef G3D_WIN32 + static DWORD WINAPI internalThreadProc(LPVOID param); +#else + static void* internalThreadProc(void* param); +#endif //G3D_WIN32 + + volatile GStatus m_status; + + // Thread handle to hold HANDLE and pthread_t +#ifdef G3D_WIN32 + HANDLE m_handle; + HANDLE m_event; +#else + pthread_t m_handle; +#endif //G3D_WIN32 + + std::string m_name; + +protected: + + /** Overriden by the thread implementor */ + virtual void threadMain() = 0; + +public: + typedef ReferenceCountedPointer Ref; + enum SpawnBehavior {USE_NEW_THREAD, USE_CURRENT_THREAD}; + + GThread(const std::string& name); + + virtual ~GThread(); + + /** Constructs a basic GThread without requiring a subclass. + + @param proc The global or static function for the threadMain() */ + static GThreadRef create(const std::string& name, void (*proc)(void*), void* param = NULL); + + /** Starts the thread and executes threadMain(). Returns false if + the thread failed to start (either because it was already started + or because the OS refused). + + @param behavior If USE_CURRENT_THREAD, rather than spawning a new thread, this routine + runs threadMain on the current thread. + */ + bool start(SpawnBehavior behavior = USE_NEW_THREAD); + + /** Terminates the thread without notifying or + waiting for a cancelation point. */ + void terminate(); + + /** + Returns true if threadMain is currently executing. This will + only be set when the thread is actually running and might not + be set when start() returns. */ + bool running() const; + + /** True after start() has been called, even through the thread + may have already completed(), or be currently running().*/ + bool started() const; + + /** Returns true if the thread has exited. */ + bool completed() const; + + /** Waits for the thread to finish executing. */ + void waitForCompletion(); + + /** Returns thread name */ + inline const std::string& name() { + return m_name; + } +}; + + +} // namespace G3D + +#endif //G3D_GTHREAD_H diff --git a/dep/g3dlite/G3D/GUniqueID.h b/dep/g3dlite/G3D/GUniqueID.h new file mode 100644 index 00000000000..c8b775c2e66 --- /dev/null +++ b/dep/g3dlite/G3D/GUniqueID.h @@ -0,0 +1,69 @@ +/** + @file GUniqueID.h + @author Morgan McGuire, http://graphics.cs.williams.edu + */ +#ifndef G3D_GUNIQUEID_H +#define G3D_GUNIQUEID_H + +#include "G3D/platform.h" +#include "G3D/g3dmath.h" +#include "G3D/Table.h" + +namespace G3D { + +/** Globally unique identifiers. The probability of two different + programs generating the same value from UniqueID::create is + vanishingly small. + + UniqueIDs optionally contain a 10-bit application specific tag + that distinguishes their type. +*/ +class GUniqueID { +private: + + uint64 id; + +public: + + GUniqueID() : id(0) {} + + bool uninitialized() const { + return id == 0; + } + + uint16 tag() const { + return id >> 54; + } + + operator uint64() const { + return id; + } + + bool operator==(const GUniqueID& other) const { + return id == other.id; + } + + bool operator!=(const GUniqueID& other) const { + return id != other.id; + } + + void serialize(class BinaryOutput& b) const; + + void deserialize(class BinaryInput& b); + + void serialize(class TextOutput& t) const; + + void deserialize(class TextInput& t); + + /** Create a new ID */ + static GUniqueID create(uint16 tag = 0); +}; + +} // G3D + +/** For Table and Set */ +template<> struct HashTrait { + static size_t hashCode(G3D::GUniqueID id) { return (size_t)(G3D::uint64)id; } +}; + +#endif diff --git a/dep/g3dlite/G3D/HashTrait.h b/dep/g3dlite/G3D/HashTrait.h new file mode 100644 index 00000000000..ca35da48643 --- /dev/null +++ b/dep/g3dlite/G3D/HashTrait.h @@ -0,0 +1,92 @@ +/** + @file HashTrait.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + @created 2008-10-01 + @edited 2009-11-01 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_HashTrait_h +#define G3D_HashTrait_h + +#include "G3D/platform.h" +#include "G3D/Crypto.h" +#include "G3D/g3dmath.h" +#include "G3D/uint128.h" + +/** Must be specialized for custom types. + @see G3D::Table for specialization requirements. +*/ +template struct HashTrait{}; + +template struct HashTrait { + static size_t hashCode(const void* k) { return reinterpret_cast(k); } +}; + +#if 0 +template <> struct HashTrait { + static size_t hashCode(int k) { return static_cast(k); } +}; +#endif + +template <> struct HashTrait { + static size_t hashCode(G3D::int16 k) { return static_cast(k); } +}; + +template <> struct HashTrait { + static size_t hashCode(G3D::uint16 k) { return static_cast(k); } +}; + +//template <> struct HashTrait { +// static size_t hashCode(int k) { return static_cast(k); } +//}; + +template <> struct HashTrait { + static size_t hashCode(G3D::int32 k) { return static_cast(k); } +}; + +template <> struct HashTrait { + static size_t hashCode(G3D::uint32 k) { return static_cast(k); } +}; + +#if 0 +template <> struct HashTrait { + static size_t hashCode(G3D::uint32 k) { return static_cast(k); } +}; +#endif + +template <> struct HashTrait { + static size_t hashCode(G3D::int64 k) { return static_cast(k); } +}; + +template <> struct HashTrait { + static size_t hashCode(G3D::uint64 k) { return static_cast(k); } +}; + +template <> struct HashTrait { + static size_t hashCode(const std::string& k) { return static_cast(G3D::Crypto::crc32(k.c_str(), k.size())); } +}; + +template <> struct HashTrait { + // Use the FNV-1 hash (http://isthe.com/chongo/tech/comp/fnv/#FNV-1). + static size_t hashCode(G3D::uint128 key) { + static const G3D::uint128 FNV_PRIME_128(1 << 24, 0x159); + static const G3D::uint128 FNV_OFFSET_128(0xCF470AAC6CB293D2ULL, 0xF52F88BF32307F8FULL); + + G3D::uint128 hash = FNV_OFFSET_128; + G3D::uint128 mask(0, 0xFF); + for (int i = 0; i < 16; ++i) { + hash *= FNV_PRIME_128; + hash ^= (mask & key); + key >>= 8; + } + + G3D::uint64 foldedHash = hash.hi ^ hash.lo; + return static_cast((foldedHash >> 32) ^ (foldedHash & 0xFFFFFFFF)); + } +}; + +#endif diff --git a/dep/g3dlite/G3D/Image1.h b/dep/g3dlite/G3D/Image1.h new file mode 100644 index 00000000000..711e83f2079 --- /dev/null +++ b/dep/g3dlite/G3D/Image1.h @@ -0,0 +1,81 @@ +/** + @file Image1.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2007-01-31 + @edited 2007-01-31 +*/ + + +#ifndef G3D_IMAGE1_H +#define G3D_IMAGE1_H + +#include "G3D/platform.h" +#include "G3D/Map2D.h" +#include "G3D/Color1.h" +#include "G3D/GImage.h" + +namespace G3D { + +typedef ReferenceCountedPointer Image1Ref; + +/** + Luminance image with 32-bit floating point storage. + + See also G3D::Image1uint8, G3D::GImage. + */ +class Image1 : public Map2D { +public: + + typedef Image1 Type; + typedef ReferenceCountedPointer Ref; + typedef Color1 Storage; + typedef Color1 Compute; + +protected: + + Image1(int w, int h, WrapMode wrap); + + void copyGImage(const class GImage& im); + void copyArray(const Color1* src, int w, int h); + void copyArray(const Color3* src, int w, int h); + void copyArray(const Color4* src, int w, int h); + void copyArray(const Color1uint8* src, int w, int h); + void copyArray(const Color3uint8* src, int w, int h); + void copyArray(const Color4uint8* src, int w, int h); + +public: + + const class ImageFormat* format() const; + + /** Creates an all-zero width x height image. */ + static Ref createEmpty(int width, int height, WrapMode wrap = WrapMode::ERROR); + + /** Creates a 0 x 0 image. */ + static Ref createEmpty(WrapMode wrap = WrapMode::ERROR); + + static Ref fromFile(const std::string& filename, WrapMode wrap = WrapMode::ERROR, GImage::Format fmt = GImage::AUTODETECT); + + static Ref fromArray(const class Color1uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color3uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color4uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color1* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color3* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color4* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + + static Ref fromImage1uint8(const ReferenceCountedPointer& im); + + static Ref fromGImage(const class GImage& im, WrapMode wrap = WrapMode::ERROR); + + /** Loads from any of the file formats supported by G3D::GImage. If there is an alpha channel on the input, + it is stripped. */ + void load(const std::string& filename, GImage::Format fmt = GImage::AUTODETECT); + + /** Saves in any of the formats supported by G3D::GImage. */ + void save(const std::string& filename, GImage::Format fmt = GImage::AUTODETECT); +}; + +} // G3D + +#endif diff --git a/dep/g3dlite/G3D/Image1uint8.h b/dep/g3dlite/G3D/Image1uint8.h new file mode 100644 index 00000000000..f32e022e92a --- /dev/null +++ b/dep/g3dlite/G3D/Image1uint8.h @@ -0,0 +1,80 @@ +/** + @file Image1uint8.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2007-01-31 + @edited 2007-01-31 +*/ + +#ifndef G3D_IMAGE1UINT8_H +#define G3D_IMAGE1UINT8_H + +#include "G3D/platform.h" +#include "G3D/Map2D.h" +#include "G3D/Color1uint8.h" +#include "G3D/Color1.h" +#include "G3D/GImage.h" + +namespace G3D { + +typedef ReferenceCountedPointer Image1uint8Ref; + +/** + Compact storage for luminance 8-bit images. + + See also G3D::Image3, G3D::GImage + */ +class Image1uint8 : public Map2D { +public: + + typedef Image1uint8 Type; + typedef Image1uint8Ref Ref; + +protected: + + Image1uint8(int w, int h, WrapMode wrap); + + void copyGImage(const class GImage& im); + void copyArray(const Color1* src, int w, int h); + void copyArray(const Color3* src, int w, int h); + void copyArray(const Color4* src, int w, int h); + void copyArray(const Color1uint8* src, int w, int h); + void copyArray(const Color3uint8* src, int w, int h); + void copyArray(const Color4uint8* src, int w, int h); + +public: + + const class ImageFormat* format() const; + + /** Creates an all-zero width x height image. */ + static Ref createEmpty(int width, int height, WrapMode wrap = WrapMode::ERROR); + + /** Creates a 0 x 0 image. */ + static Ref createEmpty(WrapMode wrap = WrapMode::ERROR); + + static Ref fromFile(const std::string& filename, WrapMode wrap = WrapMode::ERROR, GImage::Format fmt = GImage::AUTODETECT); + + static Ref fromGImage(const class GImage& im, WrapMode wrap = WrapMode::ERROR); + + static Ref fromArray(const class Color1uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color3uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color4uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color1* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color3* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color4* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + + static Ref fromImage1(const ReferenceCountedPointer& im); + static Ref fromImage3uint8(const ReferenceCountedPointer& im); + + /** Loads from any of the file formats supported by G3D::GImage. If there is an alpha channel on the input, + it is stripped. */ + void load(const std::string& filename, GImage::Format fmt = GImage::AUTODETECT); + + /** Saves in any of the formats supported by G3D::GImage. */ + void save(const std::string& filename, GImage::Format fmt = GImage::AUTODETECT); +}; + +} // G3D + +#endif diff --git a/dep/g3dlite/G3D/Image3.h b/dep/g3dlite/G3D/Image3.h new file mode 100644 index 00000000000..13cb8fa7faf --- /dev/null +++ b/dep/g3dlite/G3D/Image3.h @@ -0,0 +1,81 @@ +/** + @file Image3.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2007-01-31 + @edited 2007-01-31 +*/ + + +#ifndef G3D_IMAGE3_H +#define G3D_IMAGE3_H + +#include "G3D/platform.h" +#include "G3D/Map2D.h" +#include "G3D/Color3.h" +#include "G3D/GImage.h" + +namespace G3D { + +typedef ReferenceCountedPointer Image3Ref; + +/** + RGB image with 32-bit floating point storage for each channel. + + See also G3D::Image3uint8, G3D::GImage. + */ +class Image3 : public Map2D { +public: + + typedef Image3 Type; + typedef ReferenceCountedPointer Ref; + typedef Color3 Storage; + typedef Color3 Compute; + +protected: + + Image3(int w, int h, WrapMode wrap); + + void copyGImage(const class GImage& im); + void copyArray(const Color1* src, int w, int h); + void copyArray(const Color3* src, int w, int h); + void copyArray(const Color4* src, int w, int h); + void copyArray(const Color1uint8* src, int w, int h); + void copyArray(const Color3uint8* src, int w, int h); + void copyArray(const Color4uint8* src, int w, int h); + +public: + + const class ImageFormat* format() const; + + /** Creates an all-zero width x height image. */ + static Ref createEmpty(int width, int height, WrapMode wrap = WrapMode::ERROR); + + /** Creates a 0 x 0 image. */ + static Ref createEmpty(WrapMode wrap = WrapMode::ERROR); + + static Ref fromFile(const std::string& filename, WrapMode wrap = WrapMode::ERROR, GImage::Format fmt = GImage::AUTODETECT); + + static Ref fromArray(const class Color1uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color3uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color4uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color1* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color3* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color4* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + + static Ref fromImage3uint8(const ReferenceCountedPointer& im); + + static Ref fromGImage(const class GImage& im, WrapMode wrap = WrapMode::ERROR); + + /** Loads from any of the file formats supported by G3D::GImage. If there is an alpha channel on the input, + it is stripped. */ + void load(const std::string& filename, GImage::Format fmt = GImage::AUTODETECT); + + /** Saves in any of the formats supported by G3D::GImage. */ + void save(const std::string& filename, GImage::Format fmt = GImage::AUTODETECT); +}; + +} // G3D + +#endif diff --git a/dep/g3dlite/G3D/Image3uint8.h b/dep/g3dlite/G3D/Image3uint8.h new file mode 100644 index 00000000000..d4fdbc169ca --- /dev/null +++ b/dep/g3dlite/G3D/Image3uint8.h @@ -0,0 +1,85 @@ +/** + @file Image3uint8.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2007-01-31 + @edited 2007-01-31 +*/ + +#ifndef G3D_IMAGE3UINT8_H +#define G3D_IMAGE3UINT8_H + +#include "G3D/platform.h" +#include "G3D/Map2D.h" +#include "G3D/Color3uint8.h" +#include "G3D/Color3.h" +#include "G3D/GImage.h" + +namespace G3D { + +typedef ReferenceCountedPointer Image3uint8Ref; + +/** + Compact storage for RGB 8-bit per channel images. + + See also G3D::Image3, G3D::GImage + */ +class Image3uint8 : public Map2D { +public: + + typedef Image3uint8 Type; + typedef Image3uint8Ref Ref; + +protected: + + Image3uint8(int w, int h, WrapMode wrap); + + void copyGImage(const class GImage& im); + void copyArray(const Color1* src, int w, int h); + void copyArray(const Color3* src, int w, int h); + void copyArray(const Color4* src, int w, int h); + void copyArray(const Color1uint8* src, int w, int h); + void copyArray(const Color3uint8* src, int w, int h); + void copyArray(const Color4uint8* src, int w, int h); + +public: + + const class ImageFormat* format() const; + + /** Creates an all-zero width x height image. */ + static Ref createEmpty(int width, int height, WrapMode wrap = WrapMode::ERROR); + + + /** Creates a 0 x 0 image. */ + static Ref createEmpty(WrapMode wrap = WrapMode::ERROR); + + + static Ref fromFile(const std::string& filename, WrapMode wrap = WrapMode::ERROR, GImage::Format fmt = GImage::AUTODETECT); + + static Ref fromGImage(const class GImage& im, WrapMode wrap = WrapMode::ERROR); + + static Ref fromArray(const class Color1uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color3uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color4uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color1* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color3* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color4* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + + static Ref fromImage3(const ReferenceCountedPointer& im); + static Ref fromImage1uint8(const ReferenceCountedPointer& im); + + /** Loads from any of the file formats supported by G3D::GImage. If there is an alpha channel on the input, + it is stripped. */ + void load(const std::string& filename, GImage::Format fmt = GImage::AUTODETECT); + + /** Saves in any of the formats supported by G3D::GImage. */ + void save(const std::string& filename, GImage::Format fmt = GImage::AUTODETECT); + + /** Extracts color channel 0 <= c <= 2 and returns it as a new monochrome image. */ + ReferenceCountedPointer getChannel(int c) const; +}; + +} // G3D + +#endif diff --git a/dep/g3dlite/G3D/Image4.h b/dep/g3dlite/G3D/Image4.h new file mode 100644 index 00000000000..21d7f1e79b1 --- /dev/null +++ b/dep/g3dlite/G3D/Image4.h @@ -0,0 +1,86 @@ +/** + @file Image4.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2007-01-31 + @edited 2007-01-31 +*/ + + +#ifndef G3D_IMAGE4_H +#define G3D_IMAGE4_H + +#include "G3D/platform.h" +#include "G3D/Map2D.h" +#include "G3D/Color4.h" +#include "G3D/GImage.h" + +namespace G3D { + +typedef ReferenceCountedPointer Image4Ref; + +/** + RGBA image with 32-bit floating point storage for each channel. + + Whenever a method needs to convert from RGB to RGBA, A=1 is assumed. + + Bilinear interpolation on Image4 is about 8x faster than on + Image4uint8 due to the large cost of converting int->float on modern + machines. + + @sa G3D::Image4uint8, G3D::GImage. + */ +class Image4 : public Map2D { +public: + + typedef Image4 Type; + typedef ReferenceCountedPointer Ref; + typedef Color4 Storage; + typedef Color4 Compute; + +protected: + + Image4(int w, int h, WrapMode wrap); + + void copyGImage(const class GImage& im); + void copyArray(const Color1* src, int w, int h); + void copyArray(const Color3* src, int w, int h); + void copyArray(const Color4* src, int w, int h); + void copyArray(const Color1uint8* src, int w, int h); + void copyArray(const Color3uint8* src, int w, int h); + void copyArray(const Color4uint8* src, int w, int h); + +public: + + const class ImageFormat* format() const; + + /** Creates an all-zero width x height image. */ + static Ref createEmpty(int width, int height, WrapMode wrap = WrapMode::ERROR); + + /** Creates a 0 x 0 image. */ + static Ref createEmpty(WrapMode wrap = WrapMode::ERROR); + + static Ref fromFile(const std::string& filename, WrapMode wrap = WrapMode::ERROR, GImage::Format fmt = GImage::AUTODETECT); + + static Ref fromArray(const class Color1uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color3uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color4uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color1* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color3* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color4* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + + static Ref fromImage4uint8(const ReferenceCountedPointer& im); + + static Ref fromGImage(const class GImage& im, WrapMode wrap = WrapMode::ERROR); + + /** Loads from any of the file formats supported by G3D::GImage. */ + void load(const std::string& filename, GImage::Format fmt = GImage::AUTODETECT); + + /** Saves in any of the formats supported by G3D::GImage. */ + void save(const std::string& filename, GImage::Format fmt = GImage::AUTODETECT); +}; + +} // G3D + +#endif diff --git a/dep/g3dlite/G3D/Image4uint8.h b/dep/g3dlite/G3D/Image4uint8.h new file mode 100644 index 00000000000..46df6b490b4 --- /dev/null +++ b/dep/g3dlite/G3D/Image4uint8.h @@ -0,0 +1,85 @@ +/** + @file Image4uint8.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2007-01-31 + @edited 2007-01-31 +*/ + +#ifndef G3D_IMAGE4UINT8_H +#define G3D_IMAGE4UINT8_H + +#include "G3D/platform.h" +#include "G3D/Map2D.h" +#include "G3D/Color4uint8.h" +#include "G3D/Color4.h" +#include "G3D/GImage.h" +#include "G3D/Image1uint8.h" + +namespace G3D { + +typedef ReferenceCountedPointer Image4uint8Ref; + +/** + Compact storage for RGBA 8-bit per channel images. + + See also G3D::Image4, G3D::GImage + */ +class Image4uint8 : public Map2D { +public: + + typedef Image4uint8 Type; + typedef Image4uint8Ref Ref; + +protected: + + Image4uint8(int w, int h, WrapMode wrap); + + void copyGImage(const class GImage& im); + void copyArray(const Color1* src, int w, int h); + void copyArray(const Color3* src, int w, int h); + void copyArray(const Color4* src, int w, int h); + void copyArray(const Color1uint8* src, int w, int h); + void copyArray(const Color3uint8* src, int w, int h); + void copyArray(const Color4uint8* src, int w, int h); + +public: + + const class ImageFormat* format() const; + + /** Creates an all-zero width x height image. */ + static Ref createEmpty(int width, int height, WrapMode wrap = WrapMode::ERROR); + + + /** Creates a 0 x 0 image. */ + static Ref createEmpty(WrapMode wrap = WrapMode::ERROR); + + + static Ref fromFile(const std::string& filename, WrapMode wrap = WrapMode::ERROR, GImage::Format fmt = GImage::AUTODETECT); + + static Ref fromGImage(const class GImage& im, WrapMode wrap = WrapMode::ERROR); + + static Ref fromArray(const class Color1uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color3uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color4uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color1* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color3* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + static Ref fromArray(const class Color4* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); + + static Ref fromImage4(const ReferenceCountedPointer& im); + + /** Loads from any of the file formats supported by G3D::GImage. If there is an alpha channel on the input, + it is stripped. */ + void load(const std::string& filename, GImage::Format fmt = GImage::AUTODETECT); + + /** Saves in any of the formats supported by G3D::GImage. */ + void save(const std::string& filename, GImage::Format fmt = GImage::AUTODETECT); + + /** Extracts color channel 0 <= c <= 3 and returns it as a new monochrome image. */ + ReferenceCountedPointer getChannel(int c) const; +}; + +} // G3D + +#endif diff --git a/dep/g3dlite/G3D/ImageFormat.h b/dep/g3dlite/G3D/ImageFormat.h new file mode 100644 index 00000000000..7f098322d26 --- /dev/null +++ b/dep/g3dlite/G3D/ImageFormat.h @@ -0,0 +1,419 @@ +/** + @file ImageFormat.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2003-05-23 + @edited 2010-01-01 +*/ + +#ifndef GLG3D_ImageFormat_H +#define GLG3D_ImageFormat_H + +#include "G3D/platform.h" +#include "G3D/Table.h" +#include "G3D/enumclass.h" + +namespace G3D { + +/** Information about common image formats. + Don't construct these; use the methods provided. + + For most formats, the number indicates the number of bits per channel and a suffix of "F" indicates + floating point. This does not hold for the YUV and DXT formats.*/ +class ImageFormat { +public: + + // Must update ImageFormat::name() when this enum changes. + enum Code { + CODE_NONE = -1, + CODE_L8, + CODE_L16, + CODE_L16F, + CODE_L32F, + + CODE_A8, + CODE_A16, + CODE_A16F, + CODE_A32F, + + CODE_LA4, + CODE_LA8, + CODE_LA16, + CODE_LA16F, + CODE_LA32F, + + CODE_RGB5, + CODE_RGB5A1, + CODE_RGB8, + CODE_RGB10, + CODE_RGB10A2, + CODE_RGB16, + CODE_RGB16F, + CODE_RGB32F, + CODE_R11G11B10F, + CODE_RGB9E5F, + + CODE_RGB8I, + CODE_RGB8UI, + + CODE_ARGB8, + CODE_BGR8, + + CODE_RG8, + CODE_RG8I, + CODE_RG8UI, + + CODE_RGBA8, + CODE_RGBA16, + CODE_RGBA16F, + CODE_RGBA32F, + + CODE_RGBA32UI, + + CODE_BAYER_RGGB8, + CODE_BAYER_GRBG8, + CODE_BAYER_GBRG8, + CODE_BAYER_BGGR8, + CODE_BAYER_RGGB32F, + CODE_BAYER_GRBG32F, + CODE_BAYER_GBRG32F, + CODE_BAYER_BGGR32F, + + CODE_HSV8, + CODE_HSV32F, + + CODE_YUV420_PLANAR, + CODE_YUV422, + CODE_YUV444, + + CODE_RGB_DXT1, + CODE_RGBA_DXT1, + CODE_RGBA_DXT3, + CODE_RGBA_DXT5, + + CODE_SRGB8, + CODE_SRGBA8, + + CODE_SL8, + CODE_SLA8, + + CODE_SRGB_DXT1, + CODE_SRGBA_DXT1, + CODE_SRGBA_DXT3, + CODE_SRGBA_DXT5, + + CODE_DEPTH16, + CODE_DEPTH24, + CODE_DEPTH32, + CODE_DEPTH32F, + + CODE_STENCIL1, + CODE_STENCIL4, + CODE_STENCIL8, + CODE_STENCIL16, + + CODE_DEPTH24_STENCIL8, + + CODE_NUM + }; + + enum ColorSpace { + COLOR_SPACE_NONE, + COLOR_SPACE_RGB, + COLOR_SPACE_HSV, + COLOR_SPACE_YUV, + COLOR_SPACE_SRGB + }; + + enum BayerPattern { + BAYER_PATTERN_NONE, + BAYER_PATTERN_RGGB, + BAYER_PATTERN_GRBG, + BAYER_PATTERN_GBRG, + BAYER_PATTERN_BGGR + }; + + /** Number of channels (1 for a depth texture). */ + int numComponents; + bool compressed; + + /** Useful for serializing. */ + Code code; + + ColorSpace colorSpace; + + /** If this is a Bayer format, what is the pattern. */ + BayerPattern bayerPattern; + + /** The OpenGL format equivalent to this one, e.g, GL_RGB8 Zero if there is no equivalent. This is actually a GLenum */ + int openGLFormat; + + /** The OpenGL base format equivalent to this one (e.g., GL_RGB, GL_ALPHA). Zero if there is no equivalent. */ + int openGLBaseFormat; + + int luminanceBits; + + /** Number of bits per pixel storage for alpha values; Zero for compressed textures and non-RGB. */ + int alphaBits; + + /** Number of bits per pixel storage for red values; Zero for compressed textures and non-RGB. */ + int redBits; + + /** Number of bits per pixel storage for green values; Zero for compressed textures and non-RGB. */ + int greenBits; + + /** Number of bits per pixel storage for blue values; Zero for compressed textures and non-RGB. */ + int blueBits; + + /** Number of bits per pixel */ + int stencilBits; + + /** Number of depth bits (for depth textures; e.g. shadow maps) */ + int depthBits; + + /** Amount of CPU memory per pixel when packed into an array, discounting any end-of-row padding. */ + int cpuBitsPerPixel; + + /** Amount of CPU memory per pixel when packed into an array, discounting any end-of-row padding. + @deprecated Use cpuBitsPerPixel*/ + int packedBitsPerTexel; + + /** + Amount of GPU memory per pixel on most graphics cards, for formats supported by OpenGL. This is + only an estimate--the actual amount of memory may be different on your actual card. + + This may be greater than the sum of the per-channel bits + because graphics cards need to pad to the nearest 1, 2, or + 4 bytes. + */ + int openGLBitsPerPixel; + + /** @deprecated Use openGLBitsPerPixel */ + int hardwareBitsPerTexel; + + /** The OpenGL bytes (type) format of the data buffer used with this texture format, e.g., GL_UNSIGNED_BYTE */ + int openGLDataFormat; + + /** True if there is no alpha channel for this texture. */ + bool opaque; + + /** True if the bit depths specified are for float formats. */ + bool floatingPoint; + + /** Human readable name of this format.*/ + const std::string& name() const; + + /** Takes the same values that name() returns */ + static const ImageFormat* fromString(const std::string& s); + +private: + + ImageFormat + (int numComponents, + bool compressed, + int glFormat, + int glBaseFormat, + int luminanceBits, + int alphaBits, + int redBits, + int greenBits, + int blueBits, + int depthBits, + int stencilBits, + int hardwareBitsPerTexel, + int packedBitsPerTexel, + int glDataFormat, + bool opaque, + bool floatingPoint, + Code code, + ColorSpace colorSpace, + BayerPattern bayerPattern = BAYER_PATTERN_NONE); + +public: + + static const ImageFormat* L8(); + + static const ImageFormat* L16(); + + static const ImageFormat* L16F(); + + static const ImageFormat* L32F(); + + static const ImageFormat* A8(); + + static const ImageFormat* A16(); + + static const ImageFormat* A16F(); + + static const ImageFormat* A32F(); + + static const ImageFormat* LA4(); + + static const ImageFormat* LA8(); + + static const ImageFormat* LA16(); + + static const ImageFormat* LA16F(); + + static const ImageFormat* LA32F(); + + static const ImageFormat* BGR8(); + + static const ImageFormat* RG8(); + static const ImageFormat* RG8I(); + static const ImageFormat* RG8UI(); + + static const ImageFormat* RGB5(); + + static const ImageFormat* RGB5A1(); + + static const ImageFormat* RGB8(); + + static const ImageFormat* RGB10(); + + static const ImageFormat* RGB10A2(); + + static const ImageFormat* RGB16(); + + static const ImageFormat* RGB16F(); + + static const ImageFormat* RGB32F(); + + static const ImageFormat* RGBA8(); + + static const ImageFormat* RGBA16(); + + static const ImageFormat* RGBA16F(); + + static const ImageFormat* RGBA32F(); + + static const ImageFormat* RGBA32UI(); + + static const ImageFormat* R11G11B10F(); + + static const ImageFormat* RGB9E5F(); + + static const ImageFormat* RGB8I(); + + static const ImageFormat* RGB8UI(); + + static const ImageFormat* RGB_DXT1(); + + static const ImageFormat* RGBA_DXT1(); + + static const ImageFormat* RGBA_DXT3(); + + static const ImageFormat* RGBA_DXT5(); + + static const ImageFormat* SRGB8(); + + static const ImageFormat* SRGBA8(); + + static const ImageFormat* SL8(); + + static const ImageFormat* SLA8(); + + static const ImageFormat* SRGB_DXT1(); + + static const ImageFormat* SRGBA_DXT1(); + + static const ImageFormat* SRGBA_DXT3(); + + static const ImageFormat* SRGBA_DXT5(); + + static const ImageFormat* DEPTH16(); + + static const ImageFormat* DEPTH24(); + + static const ImageFormat* DEPTH32(); + + static const ImageFormat* DEPTH32F(); + + static const ImageFormat* STENCIL1(); + + static const ImageFormat* STENCIL4(); + + static const ImageFormat* STENCIL8(); + + static const ImageFormat* STENCIL16(); + + static const ImageFormat* DEPTH24_STENCIL8(); + + static const ImageFormat* YUV420_PLANAR(); + + static const ImageFormat* YUV422(); + + static const ImageFormat* YUV444(); + + /** + NULL pointer; indicates that the G3D::Texture class should choose + either RGBA8 or RGB8 depending on the presence of an alpha channel + in the input. + */ + static const ImageFormat* AUTO() { return NULL; } + + /** Returns DEPTH16, DEPTH24, or DEPTH32 according to the bits + specified. You can use "glGetInteger(GL_DEPTH_BITS)" to match + the screen's format.*/ + static const ImageFormat* depth(int depthBits = 24); + + /** Returns STENCIL1, STENCIL4, STENCIL8 or STENCIL16 according to the bits + specified. You can use "glGetInteger(GL_STENCIL_BITS)" to match + the screen's format.*/ + static const ImageFormat* stencil(int bits = 8); + + /** Returns the matching ImageFormat* identified by the Code. May return NULL + if this format's code is reserved but not yet implemented by G3D. */ + static const ImageFormat* fromCode(ImageFormat::Code code); + + + + /** For use with ImageFormat::convert. */ + class BayerAlgorithm { + public: + enum Value { + NEAREST, + BILINEAR, + MHC, + HIGH_QUALITY = MHC + }; + private: + + Value value; + + public: + + G3D_DECLARE_ENUM_CLASS_METHODS(BayerAlgorithm); + }; + + /** Converts between arbitrary formats on the CPU. Not all format conversions are supported or directly supported. + Formats without direct conversions will attempt to convert through RGBA first. + + A conversion routine might only support source or destination padding or y inversion or none. + If support is needed and not available in any of the direct conversion routines, then no conversion is done. + + YUV422 expects data in YUY2 format (Y, U, Y2, v). Most YUV formats require width and heights that are multiples of 2. + + Returns true if a conversion was available, false if none occurred. + */ + static bool convert(const Array& srcBytes, int srcWidth, int srcHeight, const ImageFormat* srcFormat, int srcRowPadBits, + const Array& dstBytes, const ImageFormat* dstFormat, int dstRowPadBits, + bool invertY = false, BayerAlgorithm bayerAlg = BayerAlgorithm::HIGH_QUALITY); + + /* Checks if a conversion between two formats is available. */ + static bool conversionAvailable(const ImageFormat* srcFormat, int srcRowPadBits, const ImageFormat* dstFormat, int dstRowPadBits, bool invertY = false); +}; + +typedef ImageFormat TextureFormat; + +} + +template <> +struct HashTrait { + static size_t hashCode(const G3D::ImageFormat* key) { return reinterpret_cast(key); } +}; + + + +#endif diff --git a/dep/g3dlite/G3D/Intersect.h b/dep/g3dlite/G3D/Intersect.h new file mode 100644 index 00000000000..4a3c8fb4540 --- /dev/null +++ b/dep/g3dlite/G3D/Intersect.h @@ -0,0 +1,55 @@ +/** + @file Intersect.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2009-06-29 + @edited 2009-06-29 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + + From the G3D Innovation Engine + http://g3d.sf.net + */ +#ifndef G3D_Intersect +#define G3D_Intersect + +#include "G3D/platform.h" +#include "G3D/Ray.h" +#include "G3D/AABox.h" + +namespace G3D { + +/** + @beta + */ +class Intersect { +public: + + /** \brief Returns true if the intersection of the ray and the solid box is non-empty. + + \cite "Fast Ray / Axis-Aligned Bounding Box Overlap Tests using Ray Slopes" + by Martin Eisemann, Thorsten Grosch, Stefan Müller and Marcus Magnor + Computer Graphics Lab, TU Braunschweig, Germany and + University of Koblenz-Landau, Germany + */ + static bool __fastcall rayAABox(const Ray& ray, const AABox& box); + + /** \brief Returns true if the intersection of the ray and the solid box is non-empty. + + \param time If there is an intersection, set to the time to that intersection. If the ray origin is inside the box, + this is a negative value indicating the distance backwards from the ray origin to the first intersection. + \a time is not set if there is no intersection. + + \cite Slope-Mul method from "Fast Ray / Axis-Aligned Bounding Box Overlap Tests using Ray Slopes" + by Martin Eisemann, Thorsten Grosch, Stefan Müller and Marcus Magnor + Computer Graphics Lab, TU Braunschweig, Germany and + University of Koblenz-Landau, Germany + */ + static bool __fastcall rayAABox(const Ray& ray, const AABox& box, float& time); +}; + +} + +#endif diff --git a/dep/g3dlite/G3D/KDTree.h b/dep/g3dlite/G3D/KDTree.h new file mode 100644 index 00000000000..4785ef2baea --- /dev/null +++ b/dep/g3dlite/G3D/KDTree.h @@ -0,0 +1,1667 @@ +/** + @file KDTree.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2004-01-11 + @edited 2009-12-28 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_KDTREE_H +#define G3D_KDTREE_H + +#include "G3D/platform.h" +#include "G3D/Array.h" +#include "G3D/Table.h" +#include "G3D/Vector2.h" +#include "G3D/Vector3.h" +#include "G3D/Vector4.h" +#include "G3D/AABox.h" +#include "G3D/Sphere.h" +#include "G3D/Box.h" +#include "G3D/Triangle.h" +#include "G3D/Ray.h" +#include "G3D/GCamera.h" +#include "G3D/BinaryInput.h" +#include "G3D/BinaryOutput.h" +#include "G3D/CollisionDetection.h" +#include "G3D/GCamera.h" +#include "G3D/BoundsTrait.h" +#include + +// If defined, in debug mode the tree is checked for consistency +// as a way of detecting corruption due to implementation bugs +// #define VERIFY_TREE + +template<> struct BoundsTrait { + static void getBounds(const G3D::Vector2& v, G3D::AABox& out) { out = G3D::AABox(G3D::Vector3(v, 0)); } +}; + +template<> struct BoundsTrait { + static void getBounds(const G3D::Vector3& v, G3D::AABox& out) { out = G3D::AABox(v); } +}; + +template<> struct BoundsTrait { + static void getBounds(const G3D::Vector4& v, G3D::AABox& out) { out = G3D::AABox(v.xyz()); } +}; + +template<> struct BoundsTrait { + static void getBounds(const G3D::AABox& v, G3D::AABox& out) { out = v; } +}; + +template<> struct BoundsTrait { + static void getBounds(const G3D::Sphere& s, G3D::AABox& out) { s.getBounds(out); } +}; + +template<> struct BoundsTrait { + static void getBounds(const G3D::Box& b, G3D::AABox& out) { b.getBounds(out); } +}; + +template<> struct BoundsTrait { + static void getBounds(const G3D::Vector2*& v, G3D::AABox& out) { out = G3D::AABox(G3D::Vector3(*v, 0)); } +}; + +template<> struct BoundsTrait { + static void getBounds(const G3D::Vector3*& v, G3D::AABox& out) { out = G3D::AABox(*v); } +}; + +template<> struct BoundsTrait { + static void getBounds(const G3D::Vector4*& v, G3D::AABox& out) { out = G3D::AABox(v->xyz()); } +}; + +template<> struct BoundsTrait { + static void getBounds(const G3D::AABox*& v, G3D::AABox& out) { out = *v; } +}; + +template<> struct BoundsTrait { + static void getBounds(const G3D::Sphere*& s, G3D::AABox& out) { s->getBounds(out); } +}; + +template<> struct BoundsTrait { + static void getBounds(const G3D::Box*& b, G3D::AABox& out) { b->getBounds(out); } +}; + + +template<> struct BoundsTrait { + static void getBounds(const G3D::Triangle*& t, G3D::AABox& out) { t->getBounds(out); } +}; + +namespace G3D { + namespace _internal { + + /** + Wraps a pointer value so that it can be treated as the instance itself; + convenient for inserting pointers into a Table but using the + object equality instead of pointer equality. + */ + template + class Indirector { + public: + Type* handle; + + inline Indirector(Type* h) : handle(h) {} + + inline Indirector() : handle(NULL) {} + + /** Returns true iff the values referenced by the handles are equivalent. */ + inline bool operator==(const Indirector& m) const { + return *handle == *(m.handle); + } + + inline bool operator==(const Type& m) const { + return *handle == m; + } + + inline size_t hashCode() const { + return handle->hashCode(); + } + }; + } // namespace internal +} // namespace G3D + +template struct HashTrait > { + static size_t hashCode(const G3D::_internal::Indirector& key) { return key.hashCode(); } +}; + +namespace G3D { + +/** + A set that supports spatial queries using a KD tree (axis-aligned + BSP tree) for speed. + + KDTree allows you to quickly find objects in 3D that lie within + a box or along a ray. For large sets of objects it is much faster + than testing each object for a collision. + + KDTree is as powerful as but more general than a Quad Tree, Oct + Tree, or regular KD tree that cycles through axes, but less general than an unconstrained BSP tree + (which is much slower to create). + + Internally, objects + are arranged into a tree according to their + axis-aligned bounds. This increases the cost of insertion to + O(log n) but allows fast overlap queries. + + Template Parameters +
The template parameter T must be one for which + the following functions are all overloaded: + +
+  T::T(); // public constructor of no arguments
+  template <> struct HashTrait { static size_t hashCode(int key); };
+  template<> struct BoundsTrait { static void getBounds(const T& obj, G3D::AABox& out); };
+ 
+ + G3D provides these for common classes like G3D::Vector3 and G3D::Sphere. + If you use a custom class, or a pointer to a custom class, you will need + to define those functions. + + Moving %Set Members +
It is important that objects do not move without updating the + KDTree. If the axis-aligned bounds of an object are about + to change, KDTree::remove it before they change and + KDTree::insert it again afterward. For objects + where the hashCode and == operator are invariant with respect + to the 3D position, + you can use the KDTree::update method as a shortcut to + insert/remove an object in one step after it has moved. + + + Note: Do not mutate any value once it has been inserted into KDTree. Values + are copied interally. All KDTree iterators convert to pointers to constant + values to reinforce this. + + If you want to mutate the objects you intend to store in a KDTree + simply insert pointers to your objects instead of the objects + themselves, and ensure that the above operations are defined. (And + actually, because values are copied, if your values are large you may + want to insert pointers anyway, to save space and make the balance + operation faster.) + + Dimensions + Although designed as a 3D-data structure, you can use the KDTree + for data distributed along 2 or 1 axes by simply returning bounds + that are always zero along one or more dimensions. + +*/ +template< class T, + class BoundsFunc = BoundsTrait, + class HashFunc = HashTrait, + class EqualsFunc = EqualsTrait > +class KDTree { +protected: +#define TreeType KDTree + + /** Wrapper for a value that includes a cache of its bounds. + Except for the test value used in a set-query operation, there + is only ever one instance of the handle associated with any + value and the memberTable and Nodes maintain pointers to that + heap-allocated value. + */ + class Handle { + public: + /** The bounds of each object are constrained to AABox::large */ + AABox bounds; + + /** Center of bounds. We cache this value to avoid recomputing it + during the median sort, and because MSVC 6 std::sort goes into + an infinite loop if we compute the midpoint on the fly (possibly + a floating point roundoff issue, where B& point, + int beginIndex, + int endIndex) { + + Vector3 lo = Vector3::inf(); + Vector3 hi = -lo; + + debugAssertM(beginIndex <= endIndex, "No points"); + for (int p = beginIndex; p <= endIndex; ++p) { + // This code is written with the vector min and max expanded + // because otherwise it compiles incorrectly with -O3 on + // gcc 3.4 + + const Vector3& pLo = point[p]->bounds.low(); + const Vector3& pHi = point[p]->bounds.high(); + for (int a = 0; a < 3; ++a) { + lo[a] = G3D::min(lo[a], pLo[a]); + hi[a] = G3D::max(hi[a], pHi[a]); + } + } + + return AABox(lo, hi); + } + + /** Compares centers */ + class CenterComparator { + public: + Vector3::Axis sortAxis; + + CenterComparator(Vector3::Axis a) : sortAxis(a) {} + + inline int operator()(Handle* A, const Handle* B) const { + float a = A->center[sortAxis]; + float b = B->center[sortAxis]; + + if (a < b) { + return 1; + } else if (a > b) { + return -1; + } else { + return 0; + } + } + }; + + + /** Compares bounds for strict >, <, or overlap*/ + class BoundsComparator { + public: + Vector3::Axis sortAxis; + + BoundsComparator(Vector3::Axis a) : sortAxis(a) {} + + inline int operator()(Handle* A, const Handle* B) const { + const AABox& a = A->bounds; + const AABox& b = B->bounds; + + if (a.high()[sortAxis] < b.low()[sortAxis]) { + return 1; + } else if (a.low()[sortAxis] > b.high()[sortAxis]) { + return -1; + } else { + return 0; + } + } + }; + + + /** Compares bounds to the sort location */ + class Comparator { + public: + Vector3::Axis sortAxis; + float sortLocation; + + Comparator(Vector3::Axis a, float l) : sortAxis(a), sortLocation(l) {} + + inline int operator()(Handle* ignore, const Handle* handle) const { + (void)ignore; + const AABox& box = handle->bounds; + debugAssert(ignore == NULL); + + if (box.high()[sortAxis] < sortLocation) { + // Box is strictly below the sort location + return -1; + } else if (box.low()[sortAxis] > sortLocation) { + // Box is strictly above the sort location + return 1; + } else { + // Box overlaps the sort location + return 0; + } + } + }; + + // Using System::malloc with this class provided no speed improvement. + class Node { + public: + + /** Spatial bounds on all values at this node and its children, based purely on + the parent's splitting planes. May be infinite. */ + AABox splitBounds; + + Vector3::Axis splitAxis; + + /** Location along the specified axis */ + float splitLocation; + + /** child[0] contains all values strictly + smaller than splitLocation along splitAxis. + + child[1] contains all values strictly + larger. + + Both may be NULL if there are not enough + values to bother recursing. + */ + Node* child[2]; + + /** Array of values at this node (i.e., values + straddling the split plane + all values if + this is a leaf node). + + This is an array of pointers because that minimizes + data movement during tree building, which accounts + for about 15% of the time cost of tree building. + */ + Array valueArray; + + /** For each object in the value array, a copy of its bounds. + Packing these into an array at the node level + instead putting them in the valueArray improves + cache coherence, which is about a 3x performance + increase when performing intersection computations. + */ + Array boundsArray; + + /** Creates node with NULL children */ + Node() { + splitAxis = Vector3::X_AXIS; + splitLocation = 0; + splitBounds = AABox(-Vector3::inf(), Vector3::inf()); + for (int i = 0; i < 2; ++i) { + child[i] = NULL; + } + } + + /** + Doesn't clone children. + */ + Node(const Node& other) : valueArray(other.valueArray), boundsArray(other.boundsArray) { + splitAxis = other.splitAxis; + splitLocation = other.splitLocation; + splitBounds = other.splitBounds; + for (int i = 0; i < 2; ++i) { + child[i] = NULL; + } + } + + /** Copies the specified subarray of pt into point, NULLs the children. + Assumes a second pass will set splitBounds. */ + Node(const Array& pt) : valueArray(pt) { + splitAxis = Vector3::X_AXIS; + splitLocation = 0; + for (int i = 0; i < 2; ++i) { + child[i] = NULL; + } + + boundsArray.resize(valueArray.size()); + for (int i = 0; i < valueArray.size(); ++i) { + boundsArray[i] = valueArray[i]->bounds; + } + } + + /** Deletes the children (but not the values) */ + ~Node() { + for (int i = 0; i < 2; ++i) { + delete child[i]; + } + } + + /** Returns true if this node is a leaf (no children) */ + inline bool isLeaf() const { + return (child[0] == NULL) && (child[1] == NULL); + } + + + /** + Recursively appends all handles and children's handles + to the array. + */ + void getHandles(Array& handleArray) const { + handleArray.append(valueArray); + for (int i = 0; i < 2; ++i) { + if (child[i] != NULL) { + child[i]->getHandles(handleArray); + } + } + } + + void verifyNode(const Vector3& lo, const Vector3& hi) { + // debugPrintf("Verifying: split %d @ %f [%f, %f, %f], [%f, %f, %f]\n", + // splitAxis, splitLocation, lo.x, lo.y, lo.z, hi.x, hi.y, hi.z); + + debugAssertM(lo == splitBounds.low(), + format("lo = %s, splitBounds.lo = %s", + lo.toString().c_str(), splitBounds.low().toString().c_str())); + debugAssert(hi == splitBounds.high()); + + for (int i = 0; i < valueArray.length(); ++i) { + const AABox& b = valueArray[i]->bounds; + debugAssert(b == boundsArray[i]); + + for(int axis = 0; axis < 3; ++axis) { + debugAssert(b.low()[axis] <= b.high()[axis]); + debugAssert(b.low()[axis] >= lo[axis]); + debugAssert(b.high()[axis] <= hi[axis]); + } + } + + if (child[0] || child[1]) { + debugAssert(lo[splitAxis] < splitLocation); + debugAssert(hi[splitAxis] > splitLocation); + } + + Vector3 newLo = lo; + newLo[splitAxis] = splitLocation; + Vector3 newHi = hi; + newHi[splitAxis] = splitLocation; + + if (child[0] != NULL) { + child[0]->verifyNode(lo, newHi); + } + + if (child[1] != NULL) { + child[1]->verifyNode(newLo, hi); + } + } + + + /** + Stores the locations of the splitting planes (the structure but not the content) + so that the tree can be quickly rebuilt from a previous configuration without + calling balance. + */ + static void serializeStructure(const Node* n, BinaryOutput& bo) { + if (n == NULL) { + bo.writeUInt8(0); + } else { + bo.writeUInt8(1); + n->splitBounds.serialize(bo); + serialize(n->splitAxis, bo); + bo.writeFloat32(n->splitLocation); + for (int c = 0; c < 2; ++c) { + serializeStructure(n->child[c], bo); + } + } + } + + /** Clears the member table */ + static Node* deserializeStructure(BinaryInput& bi) { + if (bi.readUInt8() == 0) { + return NULL; + } else { + Node* n = new Node(); + n->splitBounds.deserialize(bi); + deserialize(n->splitAxis, bi); + n->splitLocation = bi.readFloat32(); + for (int c = 0; c < 2; ++c) { + n->child[c] = deserializeStructure(bi); + } + return n; + } + } + + /** Returns the deepest node that completely contains bounds. */ + Node* findDeepestContainingNode(const AABox& bounds) { + + // See which side of the splitting plane the bounds are on + if (bounds.high()[splitAxis] < splitLocation) { + // Bounds are on the low side. Recurse into the child + // if it exists. + if (child[0] != NULL) { + return child[0]->findDeepestContainingNode(bounds); + } + } else if (bounds.low()[splitAxis] > splitLocation) { + // Bounds are on the high side, recurse into the child + // if it exists. + if (child[1] != NULL) { + return child[1]->findDeepestContainingNode(bounds); + } + } + + // There was no containing child, so this node is the + // deepest containing node. + return this; + } + + + /** Appends all members that intersect the box. + If useSphere is true, members that pass the box test + face a second test against the sphere. */ + void getIntersectingMembers( + const AABox& box, + const Sphere& sphere, + Array& members, + bool useSphere) const { + + // Test all values at this node + for (int v = 0; v < boundsArray.size(); ++v) { + const AABox& bounds = boundsArray[v]; + if (bounds.intersects(box) && + (! useSphere || bounds.intersects(sphere))) { + members.append(& (valueArray[v]->value)); + } + } + + // If the left child overlaps the box, recurse into it + if ((child[0] != NULL) && (box.low()[splitAxis] < splitLocation)) { + child[0]->getIntersectingMembers(box, sphere, members, useSphere); + } + + // If the right child overlaps the box, recurse into it + if ((child[1] != NULL) && (box.high()[splitAxis] > splitLocation)) { + child[1]->getIntersectingMembers(box, sphere, members, useSphere); + } + } + + /** + Recurse through the tree, assigning splitBounds fields. + */ + void assignSplitBounds(const AABox& myBounds) { + splitBounds = myBounds; + + AABox childBounds[2]; + myBounds.split(splitAxis, splitLocation, childBounds[0], childBounds[1]); + +# if defined(G3D_DEBUG) && defined(VERIFY_TREE) + // Verify the split + for (int v = 0; v < boundsArray.size(); ++v) { + const AABox& bounds = boundsArray[v]; + debugAssert(myBounds.contains(bounds)); + } +# endif + + for (int c = 0; c < 2; ++c) { + if (child[c]) { + child[c]->assignSplitBounds(childBounds[c]); + } + } + } + + /** Returns true if the ray intersects this node */ + bool intersects(const Ray& ray, float distance) const { + // See if the ray will ever hit this node or its children + Vector3 location; + bool alreadyInsideBounds = false; + bool rayWillHitBounds = + CollisionDetection::collisionLocationForMovingPointFixedAABox( + ray.origin(), ray.direction(), splitBounds, location, alreadyInsideBounds); + + bool canHitThisNode = (alreadyInsideBounds || + (rayWillHitBounds && ((location - ray.origin()).squaredLength() < square(distance)))); + + return canHitThisNode; + } + + template + void intersectRay( + const Ray& ray, + RayCallback& intersectCallback, + float& distance, + bool intersectCallbackIsFast) const { + + if (! intersects(ray, distance)) { + // The ray doesn't hit this node, so it can't hit the children of the node. + return; + } + + // Test for intersection against every object at this node. + for (int v = 0; v < valueArray.size(); ++v) { + bool canHitThisObject = true; + + if (! intersectCallbackIsFast) { + // See if + Vector3 location; + const AABox& bounds = boundsArray[v]; + bool alreadyInsideBounds = false; + bool rayWillHitBounds = + CollisionDetection::collisionLocationForMovingPointFixedAABox( + ray.origin(), ray.direction(), bounds, location, alreadyInsideBounds); + + canHitThisObject = (alreadyInsideBounds || + (rayWillHitBounds && ((location - ray.origin()).squaredLength() < square(distance)))); + } + + if (canHitThisObject) { + // It is possible that this ray hits this object. Look for the intersection using the + // callback. + const T& value = valueArray[v]->value; + intersectCallback(ray, value, distance); + } + } + + // There are three cases to consider next: + // + // 1. the ray can start on one side of the splitting plane and never enter the other, + // 2. the ray can start on one side and enter the other, and + // 3. the ray can travel exactly down the splitting plane + + enum {NONE = -1}; + int firstChild = NONE; + int secondChild = NONE; + + if (ray.origin()[splitAxis] < splitLocation) { + + // The ray starts on the small side + firstChild = 0; + + if (ray.direction()[splitAxis] > 0) { + // The ray will eventually reach the other side + secondChild = 1; + } + + } else if (ray.origin()[splitAxis] > splitLocation) { + + // The ray starts on the large side + firstChild = 1; + + if (ray.direction()[splitAxis] < 0) { + secondChild = 0; + } + } else { + // The ray starts on the splitting plane + if (ray.direction()[splitAxis] < 0) { + // ...and goes to the small side + firstChild = 0; + } else if (ray.direction()[splitAxis] > 0) { + // ...and goes to the large side + firstChild = 1; + } + } + + // Test on the side closer to the ray origin. + if ((firstChild != NONE) && child[firstChild]) { + child[firstChild]->intersectRay(ray, intersectCallback, distance, intersectCallbackIsFast); + } + + if (ray.direction()[splitAxis] != 0) { + // See if there was an intersection before hitting the splitting plane. + // If so, there is no need to look on the far side and recursion terminates. + float distanceToSplittingPlane = (splitLocation - ray.origin()[splitAxis]) / ray.direction()[splitAxis]; + if (distanceToSplittingPlane > distance) { + // We aren't going to hit anything else before hitting the splitting plane, + // so don't bother looking on the far side of the splitting plane at the other + // child. + return; + } + } + + // Test on the side farther from the ray origin. + if ((secondChild != NONE) && child[secondChild]) { + child[secondChild]->intersectRay(ray, intersectCallback, distance, intersectCallbackIsFast); + } + + } + }; + + + /** + Recursively subdivides the subarray. + + Clears the source array as soon as it is no longer needed. + + Call assignSplitBounds() on the root node after making a tree. + */ + Node* makeNode( + Array& source, + int valuesPerNode, + int numMeanSplits, + Array& temp) { + + Node* node = NULL; + + if (source.size() <= valuesPerNode) { + // Make a new leaf node + node = new Node(source); + + // Set the pointers in the memberTable + for (int i = 0; i < source.size(); ++i) { + memberTable.set(Member(source[i]), node); + } + source.clear(); + + } else { + // Make a new internal node + node = new Node(); + + const AABox& bounds = computeBounds(source, 0, source.size() - 1); + const Vector3& extent = bounds.high() - bounds.low(); + + Vector3::Axis splitAxis = extent.primaryAxis(); + + float splitLocation; + + // Arrays for holding the children + Array lt, gt; + + if (numMeanSplits <= 0) { + + source.medianPartition(lt, node->valueArray, gt, temp, CenterComparator(splitAxis)); + + // Choose the split location to be the center of whatever fell in the center + splitLocation = node->valueArray[0]->center[splitAxis]; + + // Some of the elements in the lt or gt array might really overlap the split location. + // Move them as needed. + for (int i = 0; i < lt.size(); ++i) { + const AABox& bounds = lt[i]->bounds; + if ((bounds.low()[splitAxis] <= splitLocation) && (bounds.high()[splitAxis] >= splitLocation)) { + node->valueArray.append(lt[i]); + // Remove this element and process the new one that + // is swapped in in its place. + lt.fastRemove(i); --i; + } + } + + for (int i = 0; i < gt.size(); ++i) { + const AABox& bounds = gt[i]->bounds; + if ((bounds.low()[splitAxis] <= splitLocation) && (bounds.high()[splitAxis] >= splitLocation)) { + node->valueArray.append(gt[i]); + // Remove this element and process the new one that + // is swapped in in its place. + gt.fastRemove(i); --i; + } + } + + if ((node->valueArray.size() > (source.size() / 2)) && + (source.size() > 6)) { + // This was a bad partition; we ended up putting the splitting plane right in the middle of most of the + // objects. We could try to split on a different axis, or use a different partition (e.g., the extents mean, + // or geometric mean). This implementation falls back on the extents mean, since that case is already handled + // below. + numMeanSplits = 1; + } + } + + // Note: numMeanSplits may have been increased by the code in the previous case above in order to + // force a re-partition. + + if (numMeanSplits > 0) { + // Split along the mean + splitLocation = + bounds.high()[splitAxis] * 0.5f + + bounds.low()[splitAxis] * 0.5f; + + debugAssertM(isFinite(splitLocation), + "Internal error: split location must be finite."); + + source.partition(NULL, lt, node->valueArray, gt, Comparator(splitAxis, splitLocation)); + + // The Comparator ensures that elements are strictly on the correct side of the split + } + + +# if defined(G3D_DEBUG) && defined(VERIFY_TREE) + debugAssert(lt.size() + node->valueArray.size() + gt.size() == source.size()); + // Verify that all objects ended up on the correct side of the split. + // (i.e., make sure that the Array partition was correct) + for (int i = 0; i < lt.size(); ++i) { + const AABox& bounds = lt[i]->bounds; + debugAssert(bounds.high()[splitAxis] < splitLocation); + } + + for (int i = 0; i < gt.size(); ++i) { + const AABox& bounds = gt[i]->bounds; + debugAssert(bounds.low()[splitAxis] > splitLocation); + } + + for (int i = 0; i < node->valueArray.size(); ++i) { + const AABox& bounds = node->valueArray[i]->bounds; + debugAssert(bounds.high()[splitAxis] >= splitLocation); + debugAssert(bounds.low()[splitAxis] <= splitLocation); + } +# endif + + // The source array is no longer needed + source.clear(); + + node->splitAxis = splitAxis; + node->splitLocation = splitLocation; + + // Update the bounds array and member table + node->boundsArray.resize(node->valueArray.size()); + for (int i = 0; i < node->valueArray.size(); ++i) { + Handle* v = node->valueArray[i]; + node->boundsArray[i] = v->bounds; + memberTable.set(Member(v), node); + } + + if (lt.size() > 0) { + node->child[0] = makeNode(lt, valuesPerNode, numMeanSplits - 1, temp); + } + + if (gt.size() > 0) { + node->child[1] = makeNode(gt, valuesPerNode, numMeanSplits - 1, temp); + } + + } + + return node; + } + + /** + Recursively clone the passed in node tree, setting + pointers for members in the memberTable as appropriate. + called by the assignment operator. + */ + Node* cloneTree(Node* src) { + Node* dst = new Node(*src); + + // Make back pointers + for (int i = 0; i < dst->valueArray.size(); ++i) { + memberTable.set(Member(dst->valueArray[i]), dst); + } + + // Clone children + for (int i = 0; i < 2; ++i) { + if (src->child[i] != NULL) { + dst->child[i] = cloneTree(src->child[i]); + } + } + + return dst; + } + + /** + Wrapper for a Handle; used to create a memberTable that acts like Table but + stores only Handle* internally to avoid memory copies. + */ + typedef _internal::Indirector Member; + + typedef Table MemberTable; + + /** Maps members to the node containing them */ + MemberTable memberTable; + + Node* root; + +public: + + /** To construct a balanced tree, insert the elements and then call + KDTree::balance(). */ + KDTree() : root(NULL) {} + + + KDTree(const KDTree& src) : root(NULL) { + *this = src; + } + + + KDTree& operator=(const KDTree& src) { + delete root; + // Clone tree takes care of filling out the memberTable. + root = cloneTree(src.root); + return *this; + } + + + ~KDTree() { + clear(); + } + + /** + Throws out all elements of the set. + */ + void clear() { + typedef typename Table<_internal::Indirector, Node*>::Iterator It; + + // Delete all handles stored in the member table + It cur = memberTable.begin(); + It end = memberTable.end(); + while (cur != end) { + delete cur->key.handle; + cur->key.handle = NULL; + ++cur; + } + memberTable.clear(); + + // Delete the tree structure itself + delete root; + root = NULL; + } + + int size() const { + return memberTable.size(); + } + + /** + Inserts an object into the set if it is not + already present. O(log n) time. Does not + cause the tree to be balanced. + */ + void insert(const T& value) { + if (contains(value)) { + // Already in the set + return; + } + + Handle* h = new Handle(value); + + if (root == NULL) { + // This is the first node; create a root node + root = new Node(); + } + + Node* node = root->findDeepestContainingNode(h->bounds); + + // Insert into the node + node->valueArray.append(h); + node->boundsArray.append(h->bounds); + + // Insert into the node table + Member m(h); + memberTable.set(m, node); + } + + /** Inserts each elements in the array in turn. If the tree + begins empty (no structure and no elements), this is faster + than inserting each element in turn. You still need to balance + the tree at the end.*/ + void insert(const Array& valueArray) { + if (root == NULL) { + // Optimized case for an empty tree; don't bother + // searching or reallocating the root node's valueArray + // as we incrementally insert. + root = new Node(); + root->valueArray.resize(valueArray.size()); + root->boundsArray.resize(root->valueArray.size()); + for (int i = 0; i < valueArray.size(); ++i) { + // Insert in opposite order so that we have the exact same + // data structure as if we inserted each (i.e., order is reversed + // from array). + Handle* h = new Handle(valueArray[i]); + int j = valueArray.size() - i - 1; + root->valueArray[j] = h; + root->boundsArray[j] = h->bounds; + memberTable.set(Member(h), root); + } + + } else { + // Insert at appropriate tree depth. + for (int i = 0; i < valueArray.size(); ++i) { + insert(valueArray[i]); + } + } + } + + + /** + Returns true if this object is in the set, otherwise + returns false. O(1) time. + */ + bool contains(const T& value) { + // Temporarily create a handle and member + Handle h(value); + return memberTable.containsKey(Member(&h)); + } + + + /** + Removes an object from the set in O(1) time. + It is an error to remove members that are not already + present. May unbalance the tree. + + Removing an element never causes a node (split plane) to be removed... + nodes are only changed when the tree is rebalanced. This behavior + is desirable because it allows the split planes to be serialized, + and then deserialized into an empty tree which can be repopulated. + */ + void remove(const T& value) { + debugAssertM(contains(value), + "Tried to remove an element from a " + "KDTree that was not present"); + + // Get the list of elements at the node + Handle h(value); + Member m(&h); + + Array& list = memberTable[m]->valueArray; + + Handle* ptr = NULL; + + // Find the element and remove it + for (int i = list.length() - 1; i >= 0; --i) { + if (list[i]->value == value) { + // This was the element. Grab the pointer so that + // we can delete it below + ptr = list[i]; + + // Remove the handle from the node + list.fastRemove(i); + + // Remove the corresponding bounds + memberTable[m]->boundsArray.fastRemove(i); + break; + } + } + + // Remove the member + memberTable.remove(m); + + // Delete the handle data structure + delete ptr; + ptr = NULL; + } + + + /** + If the element is in the set, it is removed. + The element is then inserted. + + This is useful when the == and hashCode methods + on T are independent of the bounds. In + that case, you may call update(v) to insert an + element for the first time and call update(v) + again every time it moves to keep the tree + up to date. + */ + void update(const T& value) { + if (contains(value)) { + remove(value); + } + insert(value); + } + + + /** + Rebalances the tree (slow). Call when objects + have moved substantially from their original positions + (which unbalances the tree and causes the spatial + queries to be slow). + + @param valuesPerNode Maximum number of elements to put at + a node. + + @param numMeanSplits numMeanSplits = 0 gives a + fully axis aligned BSP-tree, where the balance operation attempts to balance + the tree so that every splitting plane has an equal number of left + and right children (i.e. it is a median split along that axis). + This tends to maximize average performance. + + You can override this behavior by + setting a number of mean (average) splits. numMeanSplits = MAX_INT + creates a full oct-tree, which tends to optimize peak performance at the expense of + average performance. It tends to have better clustering behavior when + members are not uniformly distributed. + */ + void balance(int valuesPerNode = 5, int numMeanSplits = 3) { + if (root == NULL) { + // Tree is empty + return; + } + + // Get all handles and delete the old tree structure + Node* oldRoot = root; + for (int c = 0; c < 2; ++c) { + if (root->child[c] != NULL) { + root->child[c]->getHandles(root->valueArray); + + // Delete the child; this will delete all structure below it + delete root->child[c]; + root->child[c] = NULL; + } + } + + Array temp; + // Make a new root. Work with a copy of the value array because + // makeNode clears the source array as it progresses + Array copy(oldRoot->valueArray); + root = makeNode(copy, valuesPerNode, numMeanSplits, temp); + + // Throw away the old root node + delete oldRoot; + oldRoot = NULL; + + // Walk the tree, assigning splitBounds. We start with unbounded + // space. This will override the current member table. + const AABox& LARGE = AABox::large(); + root->assignSplitBounds(LARGE); + +# ifdef _DEBUG + { + // Ensure that the balanced tree is still correct + root->verifyNode(LARGE.low(), LARGE.high()); + } +# endif + } + + + /** Clear, set the contents to the values in the array, and then balance */ + void setContents(const Array& array, int valuesPerNode = 5, int numMeanSplits = 3) { + clear(); + insert(array); + balance(valuesPerNode, numMeanSplits); + } + + +protected: + + /** + @param parentMask The mask that this node returned from culledBy. + */ + static void getIntersectingMembers( + const Array& plane, + Array& members, + Node* node, + uint32 parentMask) { + + int dummy; + + if (parentMask == 0) { + // None of these planes can cull anything + for (int v = node->valueArray.size() - 1; v >= 0; --v) { + members.append(& (node->valueArray[v]->value)); + } + + // Iterate through child nodes + for (int c = 0; c < 2; ++c) { + if (node->child[c]) { + getIntersectingMembers(plane, members, node->child[c], 0); + } + } + } else { + + // Test values at this node against remaining planes + for (int v = node->boundsArray.size() - 1; v >= 0; --v) { + if (! node->boundsArray[v].culledBy(plane, dummy, parentMask)) { + members.append(&(node->valueArray[v]->value)); + } + } + + uint32 childMask = 0xFFFFFF; + + // Iterate through child nodes + for (int c = 0; c < 2; ++c) { + if (node->child[c] && + ! node->child[c]->splitBounds.culledBy(plane, dummy, parentMask, childMask)) { + // This node was not culled + getIntersectingMembers(plane, members, node->child[c], childMask); + } + } + } + } + +public: + + /** + Returns all members inside the set of planes. + @param members The results are appended to this array. + */ + void getIntersectingMembers(const Array& plane, Array& members) const { + if (root == NULL) { + return; + } + + getIntersectingMembers(plane, members, root, 0xFFFFFF); + } + + void getIntersectingMembers(const Array& plane, Array& members) const { + Array temp; + getIntersectingMembers(plane, temp, root, 0xFFFFFF); + for (int i = 0; i < temp.size(); ++i) { + members.append(*temp[i]); + } + } + + /** + Typically used to find all visible + objects inside the view frustum (see also GCamera::getClipPlanes)... i.e. all objects + not culled by frustum. + + Example: +
+        Array  visible;
+        tree.getIntersectingMembers(camera.frustum(), visible);
+        // ... Draw all objects in the visible array.
+      
+ @param members The results are appended to this array. + */ + void getIntersectingMembers(const GCamera::Frustum& frustum, Array& members) const { + Array plane; + + for (int i = 0; i < frustum.faceArray.size(); ++i) { + plane.append(frustum.faceArray[i].plane); + } + + getIntersectingMembers(plane, members); + } + + void getIntersectingMembers(const GCamera::Frustum& frustum, Array& members) const { + Array temp; + getIntersectingMembers(frustum, temp); + for (int i = 0; i < temp.size(); ++i) { + members.append(*temp[i]); + } + } + + /** + C++ STL style iterator variable. See beginBoxIntersection(). + The iterator overloads the -> (dereference) operator, so this + acts like a pointer to the current member. + */ + // This iterator turns Node::getIntersectingMembers into a + // coroutine. It first translates that method from recursive to + // stack based, then captures the system state (analogous to a Scheme + // continuation) after each element is appended to the member array, + // and allowing the computation to be restarted. + class BoxIntersectionIterator { + private: + friend class TreeType; + + /** True if this is the "end" iterator instance */ + bool isEnd; + + /** The box that we're testing against. */ + AABox box; + + /** Node that we're currently looking at. Undefined if isEnd + is true. */ + Node* node; + + /** Nodes waiting to be processed */ + // We could use backpointers within the tree and careful + // state management to avoid ever storing the stack-- but + // it is much easier this way and only inefficient if the + // caller uses post increment (which they shouldn't!). + Array stack; + + /** The next index of current->valueArray to return. + Undefined when isEnd is true.*/ + int nextValueArrayIndex; + + BoxIntersectionIterator() : isEnd(true) {} + + BoxIntersectionIterator(const AABox& b, const Node* root) : + isEnd(root == NULL), box(b), + node(const_cast(root)), nextValueArrayIndex(-1) { + + // We intentionally start at the "-1" index of the current + // node so we can use the preincrement operator to move + // ourselves to element 0 instead of repeating all of the + // code from the preincrement method. Note that this might + // cause us to become the "end" instance. + ++(*this); + } + + public: + + inline bool operator!=(const BoxIntersectionIterator& other) const { + return ! (*this == other); + } + + bool operator==(const BoxIntersectionIterator& other) const { + if (isEnd) { + return other.isEnd; + } else if (other.isEnd) { + return false; + } else { + // Two non-end iterators; see if they match. This is kind of + // silly; users shouldn't call == on iterators in general unless + // one of them is the end iterator. + if ((box != other.box) || (node != other.node) || + (nextValueArrayIndex != other.nextValueArrayIndex) || + (stack.length() != other.stack.length())) { + return false; + } + + // See if the stacks are the same + for (int i = 0; i < stack.length(); ++i) { + if (stack[i] != other.stack[i]) { + return false; + } + } + + // We failed to find a difference; they must be the same + return true; + } + } + + /** + Pre increment. + */ + BoxIntersectionIterator& operator++() { + ++nextValueArrayIndex; + + bool foundIntersection = false; + while (! isEnd && ! foundIntersection) { + + // Search for the next node if we've exhausted this one + while ((! isEnd) && (nextValueArrayIndex >= node->valueArray.length())) { + // If we entered this loop, then the iterator has exhausted the elements at + // node (possibly because it just switched to a child node with no members). + // This loop continues until it finds a node with members or reaches + // the end of the whole intersection search. + + // If the right child overlaps the box, push it onto the stack for + // processing. + if ((node->child[1] != NULL) && + (box.high()[node->splitAxis] > node->splitLocation)) { + stack.push(node->child[1]); + } + + // If the left child overlaps the box, push it onto the stack for + // processing. + if ((node->child[0] != NULL) && + (box.low()[node->splitAxis] < node->splitLocation)) { + stack.push(node->child[0]); + } + + if (stack.length() > 0) { + // Go on to the next node (which may be either one of the ones we + // just pushed, or one from farther back the tree). + node = stack.pop(); + nextValueArrayIndex = 0; + } else { + // That was the last node; we're done iterating + isEnd = true; + } + } + + // Search for the next intersection at this node until we run out of children + while (! isEnd && ! foundIntersection && (nextValueArrayIndex < node->valueArray.length())) { + if (box.intersects(node->boundsArray[nextValueArrayIndex])) { + foundIntersection = true; + } else { + ++nextValueArrayIndex; + // If we exhaust this node, we'll loop around the master loop + // to find a new node. + } + } + } + + return *this; + } + + private: + /** + Post increment (much slower than preincrement!). + Intentionally overloaded to preclude accidentally slow code. + */ + BoxIntersectionIterator operator++(int); + /*{ + BoxIntersectionIterator old = *this; + ++this; + return old; + }*/ + + public: + + /** Overloaded dereference operator so the iterator can masquerade as a pointer + to a member */ + const T& operator*() const { + alwaysAssertM(! isEnd, "Can't dereference the end element of an iterator"); + return node->valueArray[nextValueArrayIndex]->value; + } + + /** Overloaded dereference operator so the iterator can masquerade as a pointer + to a member */ + T const * operator->() const { + alwaysAssertM(! isEnd, "Can't dereference the end element of an iterator"); + return &(stack.last()->valueArray[nextValueArrayIndex]->value); + } + + /** Overloaded cast operator so the iterator can masquerade as a pointer + to a member */ + operator T*() const { + alwaysAssertM(! isEnd, "Can't dereference the end element of an iterator"); + return &(stack.last()->valueArray[nextValueArrayIndex]->value); + } + }; + + + /** + Iterates through the members that intersect the box + */ + BoxIntersectionIterator beginBoxIntersection(const AABox& box) const { + return BoxIntersectionIterator(box, root); + } + + BoxIntersectionIterator endBoxIntersection() const { + // The "end" iterator instance + return BoxIntersectionIterator(); + } + + /** + Appends all members whose bounds intersect the box. + See also KDTree::beginBoxIntersection. + */ + void getIntersectingMembers(const AABox& box, Array& members) const { + if (root == NULL) { + return; + } + root->getIntersectingMembers(box, Sphere(Vector3::zero(), 0), members, false); + } + + void getIntersectingMembers(const AABox& box, Array& members) const { + Array temp; + getIntersectingMembers(box, temp); + for (int i = 0; i < temp.size(); ++i) { + members.append(*temp[i]); + } + } + + + /** + Invoke a callback for every member along a ray until the closest intersection is found. + + @param callback either a function or an instance of a class with an overloaded operator() of the form: + + void callback(const Ray& ray, const T& object, float& distance). If the ray hits the object + before travelling distance distance, updates distance with the new distance to + the intersection, otherwise leaves it unmodified. A common example is: + +
+     class Entity {
+     public:
+
+                void intersect(const Ray& ray, float& maxDist, Vector3& outLocation, Vector3& outNormal) {
+                    float d = maxDist;
+
+                    // ... search for intersection distance d
+
+                    if ((d > 0) && (d < maxDist)) {
+                        // Intersection occured
+                        maxDist = d;
+                        outLocation = ...;
+                        outNormal = ...;
+                    }
+                }
+            };
+
+            // Finds the surface normal and location of the first intersection with the scene
+            class Intersection {
+            public:
+                Entity*     closestEntity;
+                Vector3     hitLocation;
+                Vector3     hitNormal;
+
+                void operator()(const Ray& ray, const Entity* entity, float& distance) {
+                    entity->intersect(ray, distance, hitLocation, hitNormal);
+                }
+            };
+
+            KDTree scene;
+
+            Intersection intersection;
+            float distance = finf();
+            scene.intersectRay(camera.worldRay(x, y), intersection, distance);
+          
+ + + @param distance When the method is invoked, this is the maximum + distance that the tree should search for an intersection. On + return, this is set to the distance to the first intersection + encountered. + + @param intersectCallbackIsFast If false, each object's bounds are + tested before the intersectCallback is invoked. If the + intersect callback runs at the same speed or faster than + AABox-ray intersection, set this to true. + */ + template + void intersectRay( + const Ray& ray, + RayCallback& intersectCallback, + float& distance, + bool intersectCallbackIsFast = false) const { + + root->intersectRay(ray, intersectCallback, distance, intersectCallbackIsFast); + } + + + /** + @brief Finds all members whose bounding boxes intersect the sphere. The actual + elements may not intersect the sphere. + + @param members The results are appended to this array. + */ + void getIntersectingMembers(const Sphere& sphere, Array& members) const { + if (root == NULL) { + return; + } + + AABox box; + sphere.getBounds(box); + root->getIntersectingMembers(box, sphere, members, true); + } + + void getIntersectingMembers(const Sphere& sphere, Array& members) const { + Array temp; + getIntersectingMembers(sphere, temp); + for (int i = 0; i < temp.size(); ++i) { + members.append(*temp[i]); + } + } + + /** + Stores the locations of the splitting planes (the structure but not the content) + so that the tree can be quickly rebuilt from a previous configuration without + calling balance. + */ + void serializeStructure(BinaryOutput& bo) const { + Node::serializeStructure(root, bo); + } + + /** Clears the member table */ + void deserializeStructure(BinaryInput& bi) { + clear(); + root = Node::deserializeStructure(bi); + } + + /** + Returns an array of all members of the set. See also KDTree::begin. + */ + void getMembers(Array& members) const { + Array temp; + memberTable.getKeys(temp); + for (int i = 0; i < temp.size(); ++i) { + members.append(*(temp.handle)); + } + } + + + /** If a value that is EqualsFunc to @a value is present, returns a pointer to the + version stored in the data structure, otherwise returns NULL. + */ + const T* getPointer(const T& value) const { + // Temporarily create a handle and member + Handle h(value); + const Member* member = memberTable.getKeyPointer(Member(&h)); + if (member == NULL) { + // Not found + return NULL; + } else { + return &(member->handle->value); + } + } + + + /** + C++ STL style iterator variable. See begin(). + Overloads the -> (dereference) operator, so this acts like a pointer + to the current member. + */ + class Iterator { + private: + friend class TreeType; + + // Note: this is a Table iterator, we are currently defining + // Set iterator + typename Table::Iterator it; + + Iterator(const typename Table::Iterator& it) : it(it) {} + + public: + + inline bool operator!=(const Iterator& other) const { + return !(*this == other); + } + + bool operator==(const Iterator& other) const { + return it == other.it; + } + + /** + Pre increment. + */ + Iterator& operator++() { + ++it; + return *this; + } + + private: + /** + Post increment (slower than preincrement). Intentionally unimplemented to prevent slow code. + */ + Iterator operator++(int);/* { + Iterator old = *this; + ++(*this); + return old; + }*/ + public: + + const T& operator*() const { + return it->key.handle->value; + } + + T* operator->() const { + return &(it->key.handle->value); + } + + operator T*() const { + return &(it->key.handle->value); + } + }; + + + /** + C++ STL style iterator method. Returns the first member. + Use preincrement (++entry) to get to the next element (iteration + order is arbitrary). + Do not modify the set while iterating. + */ + Iterator begin() const { + return Iterator(memberTable.begin()); + } + + + /** + C++ STL style iterator method. Returns one after the last iterator + element. + */ + Iterator end() const { + return Iterator(memberTable.end()); + } +#undef TreeType +}; + + +} + +#endif diff --git a/dep/g3dlite/G3D/Line.h b/dep/g3dlite/G3D/Line.h new file mode 100644 index 00000000000..3579a6becec --- /dev/null +++ b/dep/g3dlite/G3D/Line.h @@ -0,0 +1,105 @@ +/** + @file Line.h + + Line class + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2001-06-02 + @edited 2006-02-28 + */ + +#ifndef G3D_LINE_H +#define G3D_LINE_H + +#include "G3D/platform.h" +#include "G3D/Vector3.h" + +namespace G3D { + +class Plane; + +/** + An infinite 3D line. + */ +class Line { +protected: + + Vector3 _point; + Vector3 _direction; + + Line(const Vector3& point, const Vector3& direction) { + _point = point; + _direction = direction.direction(); + } + +public: + + /** Undefined (provided for creating Array only) */ + inline Line() {} + + Line(class BinaryInput& b); + + void serialize(class BinaryOutput& b) const; + + void deserialize(class BinaryInput& b); + + virtual ~Line() {} + + /** + Constructs a line from two (not equal) points. + */ + static Line fromTwoPoints(const Vector3 &point1, const Vector3 &point2) { + return Line(point1, point2 - point1); + } + + /** + Creates a line from a point and a (nonzero) direction. + */ + static Line fromPointAndDirection(const Vector3& point, const Vector3& direction) { + return Line(point, direction); + } + + /** + Returns the closest point on the line to point. + */ + Vector3 closestPoint(const Vector3& pt) const; + + /** + Returns the distance between point and the line + */ + double distance(const Vector3& point) const { + return (closestPoint(point) - point).magnitude(); + } + + /** Returns a point on the line */ + Vector3 point() const; + + /** Returns the direction (or negative direction) of the line */ + Vector3 direction() const; + + /** + Returns the point where the line and plane intersect. If there + is no intersection, returns a point at infinity. + */ + Vector3 intersection(const Plane &plane) const; + + + /** Finds the closest point to the two lines. + + @param minDist Returns the minimum distance between the lines. + + @cite http://objectmix.com/graphics/133793-coordinates-closest-points-pair-skew-lines.html + */ + Vector3 closestPoint(const Line& B, float& minDist) const; + + inline Vector3 closestPoint(const Line& B) const { + float m; + return closestPoint(B, m); + } +}; + +};// namespace + + +#endif diff --git a/dep/g3dlite/G3D/LineSegment.h b/dep/g3dlite/G3D/LineSegment.h new file mode 100644 index 00000000000..70210ec7e00 --- /dev/null +++ b/dep/g3dlite/G3D/LineSegment.h @@ -0,0 +1,115 @@ +/** + @file LineSegment.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2003-02-08 + @edited 2008-02-02 + */ + +#ifndef G3D_LINESEGMENT_H +#define G3D_LINESEGMENT_H + +#include "G3D/platform.h" +#include "G3D/Vector3.h" + +namespace G3D { + +/** + An finite segment of an infinite 3D line. + */ +class LineSegment { +protected: + + Vector3 _point; + + /** Not normalized */ + Vector3 direction; + + LineSegment(const Vector3& __point, const Vector3& _direction) : _point(__point), direction(_direction) { + } + +public: + + inline LineSegment() : _point(Vector3::zero()), direction(Vector3::zero()) {} + + LineSegment(class BinaryInput& b); + + void serialize(class BinaryOutput& b) const; + + void deserialize(class BinaryInput& b); + + virtual ~LineSegment() {} + + /** + * Constructs a line from two (not equal) points. + */ + static LineSegment fromTwoPoints(const Vector3 &point1, const Vector3 &point2) { + return LineSegment(point1, point2 - point1); + } + + /** Call with 0 or 1 */ + Vector3 point(int i) const; + + inline float length() const { + return direction.magnitude(); + } + + /** + * Returns the closest point on the line segment to point. + */ + Vector3 closestPoint(const Vector3 &point) const; + + /** + Returns the distance between point and the line + */ + double distance(const Vector3& p) const { + return (closestPoint(p) - p).magnitude(); + } + + double distanceSquared(const Vector3& p) const { + return (closestPoint(p) - p).squaredMagnitude(); + } + + /** Returns true if some part of this segment is inside the sphere */ + bool intersectsSolidSphere(const class Sphere& s) const; + + Vector3 randomPoint() const; + +}; + + +class LineSegment2D { +private: + + Vector2 m_origin; + + /** Not normalized */ + Vector2 m_direction; + + /** Length of m_direction */ + float m_length; + +public: + + LineSegment2D() {} + + static LineSegment2D fromTwoPoints(const Vector2& p0, const Vector2& p1); + + /** Returns the intersection of these segements (including + testing endpoints), or Vector2::inf() if they do not intersect. */ + Vector2 intersection(const LineSegment2D& other) const; + + Vector2 point(int i) const; + + Vector2 closestPoint(const Vector2& Q) const; + + float distance(const Vector2& p) const; + + float length() const; +}; + +} // namespace + + +#endif diff --git a/dep/g3dlite/G3D/Log.h b/dep/g3dlite/G3D/Log.h new file mode 100644 index 00000000000..d252d0c1a17 --- /dev/null +++ b/dep/g3dlite/G3D/Log.h @@ -0,0 +1,109 @@ +/** + @file Log.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + @cite Backtrace by Aaron Orenstein + @created 2001-08-04 + @edited 2005-11-04 + */ + +#ifndef G3D_LOG_H +#define G3D_LOG_H + +#include +#include +#include "G3D/platform.h" + +#ifndef G3D_WIN32 + #include +#endif + +namespace G3D { + +/** Prints to the common system log, log.txt, which is usually + in the working directory of the program. If your disk is + not writable or is slow, it will attempt to write to "c:/tmp/log.txt" or + "c:/temp/log.txt" on Windows systems instead. + + Unlike printf or debugPrintf, + this function guarantees that all output is committed before it returns. + This is very useful for debugging a crash, which might hide the last few + buffered print statements otherwise. + + Many G3D routines write useful warnings and debugging information to the + system log, which makes it a good first place to go when tracking down + a problem. + */ +void logPrintf(const char* fmt, ...); + +/** Does not flush the buffer; follow up with a logPrintf to force the flush. */ +void logLazyPrintf(const char* fmt, ...); + +/** + System log for debugging purposes. The first log opened + is the "common log" and can be accessed with the static + method common(). If you access common() and a common log + does not yet exist, one is created for you. + */ +class Log { +private: + + /** + Log messages go here. + */ + FILE* logFile; + + std::string filename; + + static Log* commonLog; + + int stripFromStackBottom; + +public: + + /** + @param stripFromStackBottom Number of call stacks to strip from the + bottom of the stack when printing a trace. Useful for hiding + routines like "main" and "WinMain". If the specified file cannot + be opened for some reason, tries to open "c:/tmp/log.txt" or + "c:/temp/log.txt" instead. + */ + Log(const std::string& filename = "log.txt", + int stripFromStackBottom = 0); + + virtual ~Log(); + + /** + Returns the handle to the file log. + */ + FILE* getFile() const; + + /** + Marks the beginning of a logfile section. + */ + void section(const std::string& s); + + /** + Given arguments like printf, writes characters to the debug text overlay. + */ + // We want G3D_CHECK_PRINTF_ARGS here, but that conflicts with the + // overload. + void __cdecl printf(const char* fmt, ...) G3D_CHECK_PRINTF_METHOD_ARGS; + + void __cdecl vprintf(const char*, va_list argPtr) G3D_CHECK_VPRINTF_METHOD_ARGS; + /** Does not flush */ + void __cdecl lazyvprintf(const char*, va_list argPtr) G3D_CHECK_VPRINTF_METHOD_ARGS; + + static Log* common(); + + static std::string getCommonLogFilename(); + + void print(const std::string& s); + + + void println(const std::string& s); +}; + +} + +#endif diff --git a/dep/g3dlite/G3D/Map2D.h b/dep/g3dlite/G3D/Map2D.h new file mode 100644 index 00000000000..9af9f7242c1 --- /dev/null +++ b/dep/g3dlite/G3D/Map2D.h @@ -0,0 +1,667 @@ +/** + @file Map2D.h + + More flexible support than provided by G3D::GImage. + + @maintainer Morgan McGuire, morgan@cs.brown.edu + @created 2004-10-10 + @edited 2009-03-24 + */ +#ifndef G3D_Map2D_h +#define G3D_Map2D_h + +#include "G3D/platform.h" +#include "G3D/g3dmath.h" +#include "G3D/Array.h" +#include "G3D/vectorMath.h" +#include "G3D/Vector2int16.h" +#include "G3D/ReferenceCount.h" +#include "G3D/AtomicInt32.h" +#include "G3D/GThread.h" +#include "G3D/Rect2D.h" +#include "G3D/WrapMode.h" + +#include + +namespace G3D { +namespace _internal { + +/** The default compute type for a type is the type itself. */ +template class _GetComputeType { +public: + typedef Storage Type; +}; + +} // _internal +} // G3D + +// This weird syntax is needed to support VC6, which doesn't +// properly implement template overloading. +#define DECLARE_COMPUTE_TYPE(StorageType, ComputeType) \ +namespace G3D { \ + namespace _internal { \ + template<> class _GetComputeType < StorageType > { \ + public: \ + typedef ComputeType Type; \ + }; \ + } \ +} + +DECLARE_COMPUTE_TYPE( float32, float64) +DECLARE_COMPUTE_TYPE( float64, float64) + +DECLARE_COMPUTE_TYPE( int8, float32) +DECLARE_COMPUTE_TYPE( int16, float32) +DECLARE_COMPUTE_TYPE( int32, float64) +DECLARE_COMPUTE_TYPE( int64, float64) + +DECLARE_COMPUTE_TYPE( uint8, float32) +DECLARE_COMPUTE_TYPE( uint16, float32) +DECLARE_COMPUTE_TYPE( uint32, float64) +DECLARE_COMPUTE_TYPE( uint64, float64) + +DECLARE_COMPUTE_TYPE( Vector2, Vector2) +DECLARE_COMPUTE_TYPE( Vector2int16, Vector2) + +DECLARE_COMPUTE_TYPE( Vector3, Vector3) +DECLARE_COMPUTE_TYPE( Vector3int16, Vector3) + +DECLARE_COMPUTE_TYPE( Vector4, Vector4) + +DECLARE_COMPUTE_TYPE( Color3, Color3) +DECLARE_COMPUTE_TYPE( Color3uint8, Color3) + +DECLARE_COMPUTE_TYPE( Color4, Color4) +DECLARE_COMPUTE_TYPE( Color4uint8, Color4) +#undef DECLARE_COMPUTE_TYPE + +namespace G3D { + +/** + Map of values across a discrete 2D plane. Can be thought of as a generic class for 2D images, + allowing flexibility as to pixel format and convenient methods. + In fact, the "pixels" can be any values + on a grid that can be sensibly interpolated--RGB colors, scalars, 4D vectors, and so on. + + Other "image" classes in G3D: + + G3D::GImage - Supports file formats, fast, Color3uint8 and Color4uint8 formats. No interpolation. + + G3D::Texture::Ref - Represents image on the graphics card (not directly readable on the CPU). Supports 2D, 3D, and a variety of interpolation methods, loads file formats. + + G3D::Image3 - A subclass of Map2D that supports image loading and saving and conversion to Texture. + + G3D::Image4 - A subclass of Map2D that supports image loading and saving and conversion to Texture. + + G3D::Image3uint8 - A subclass of Map2D that supports image loading and saving and conversion to Texture. + + G3D::Image4uint8 - A subclass of Map2D that supports image loading and saving and conversion to Texture. + + There are two type parameters-- the first (@ Storage) is the type + used to store the "pixel" values efficiently and + the second (@a Compute) is + the type operated on by computation. The Compute::Compute(Storage&) constructor + is used to convert between storage and computation types. + @a Storage is often an integer version of @a Compute, for example + Map2D. By default, the computation type is: + +
+     Storage       Computation
+
+     uint8          float32
+     uint16         float32
+     uint32         float64
+     uint64         float64
+
+     int8           float32
+     int16          float32
+     int32          float64
+     int64          float64
+
+     float32        float64
+     float64        float64
+
+     Vector2        Vector2
+     Vector2int16   Vector2
+
+     Vector3        Vector3
+     Vector3int16   Vector3
+
+     Vector4        Vector4
+
+     Color3         Color3
+     Color3uint8    Color3
+
+     Color4         Color4
+     Color4uint8    Color4
+    
+ Any other storage type defaults to itself as the computation type. + + The computation type can be any that + supports lerp, +, -, *, /, and an empty constructor. + + Assign value: + + im->set(x, y, 7); or + im->get(x, y) = 7; + + Read value: + + int c = im(x, y); + + Can also sample with nearest neighbor, bilinear, and bicubic + interpolation. + + Sampling follows OpenGL conventions, where + pixel values represent grid points and (0.5, 0.5) is half-way + between two vertical and two horizontal grid points. + To draw an image of dimensions w x h with nearest neighbor + sampling, render pixels from [0, 0] to [w - 1, h - 1]. + + Under the WrapMode::CLAMP wrap mode, the value of bilinear interpolation + becomes constant outside [1, w - 2] horizontally. Nearest neighbor + interpolation is constant outside [0, w - 1] and bicubic outside + [3, w - 4]. The class does not offer quadratic interpolation because + the interpolation filter could not center over a pixel. + + @author Morgan McGuire, http://graphics.cs.williams.edu + */ +template< typename Storage, +typename Compute = typename G3D::_internal::_GetComputeType::Type> +class Map2D : public ReferenceCountedObject { + +// +// It doesn't make sense to automatically convert from Compute back to Storage +// because the rounding rule (and scaling) is application dependent. +// Thus the interpolation methods all return type Compute. +// + +public: + + typedef Storage StorageType; + typedef Compute ComputeType; + typedef Map2D Type; + typedef ReferenceCountedPointer Ref; + +protected: + + Storage ZERO; + + /** Width, in pixels. */ + uint32 w; + + /** Height, in pixels. */ + uint32 h; + + WrapMode _wrapMode; + + /** 0 if no mutating method has been invoked + since the last call to setChanged(); */ + AtomicInt32 m_changed; + + Array data; + + /** Handles the exceptional cases from get */ + const Storage& slowGet(int x, int y, WrapMode wrap) { + switch (wrap) { + case WrapMode::CLAMP: + return fastGet(iClamp(x, 0, w - 1), iClamp(y, 0, h - 1)); + + case WrapMode::TILE: + return fastGet(iWrap(x, w), iWrap(y, h)); + + case WrapMode::ZERO: + return ZERO; + + case WrapMode::ERROR: + alwaysAssertM(((uint32)x < w) && ((uint32)y < h), + format("Index out of bounds: (%d, %d), w = %d, h = %d", + x, y, w, h)); + + // intentionally fall through + case WrapMode::IGNORE: + // intentionally fall through + default: + { + static Storage temp; + return temp; + } + } + } + +public: + + /** Unsafe access to the underlying data structure with no wrapping support; requires that (x, y) is in bounds. */ + inline const Storage& fastGet(int x, int y) const { + debugAssert(((uint32)x < w) && ((uint32)y < h)); + return data[x + y * w]; + } + + /** Unsafe access to the underlying data structure with no wrapping support; requires that (x, y) is in bounds. */ + inline void fastSet(int x, int y, const Storage& v) { + debugAssert(((uint32)x < w) && ((uint32)y < h)); + data[x + y * w] = v; + } + +protected: + + /** Given four control points and a value on the range [0, 1) + evaluates the Catmull-rom spline between the times of the + middle two control points */ + Compute bicubic(const Compute* ctrl, double s) const { + + // f = B * S * ctrl' + + // B matrix: Catmull-Rom spline basis + static const double B[4][4] = { + { 0.0, -0.5, 1.0, -0.5}, + { 1.0, 0.0, -2.5, 1.5}, + { 0.0, 0.5, 2.0, -1.5}, + { 0.0, 0.0, -0.5, 0.5}}; + + // S: Powers of the fraction + double S[4]; + double s2 = s * s; + S[0] = 1.0; + S[1] = s; + S[2] = s2; + S[3] = s2 * s; + + Compute sum(ZERO); + + for (int c = 0; c < 4; ++c) { + double coeff = 0.0; + for (int power = 0; power < 4; ++power) { + coeff += B[c][power] * S[power]; + } + sum += ctrl[c] * coeff; + } + + return sum; + } + + + Map2D(int w, int h, WrapMode wrap) : w(0), h(0), _wrapMode(wrap), m_changed(1) { + ZERO = Storage(Compute(Storage()) * 0); + resize(w, h); + } + +public: + + /** + Although Map2D is not threadsafe (except for the setChanged() method), + you can use this mutex to create your own threadsafe access to a Map2D. + Not used by the default implementation. + */ + GMutex mutex; + + static Ref create(int w = 0, int h = 0, WrapMode wrap = WrapMode::ERROR) { + return new Map2D(w, h, wrap); + } + + /** Resizes without clearing, leaving garbage. + */ + void resize(uint32 newW, uint32 newH) { + if ((newW != w) || (newH != h)) { + w = newW; + h = newH; + data.resize(w * h); + setChanged(true); + } + } + + /** + Returns true if this map has been written to since the last call to setChanged(false). + This is useful if you are caching a texture map other value that must be recomputed + whenever this changes. + */ + bool changed() { + return m_changed.value() != 0; + } + + /** Set/unset the changed flag. */ + void setChanged(bool c) { + m_changed = c ? 1 : 0; + } + + /** Returns a pointer to the underlying row-major data. There is no padding at the end of the row. + Be careful--this will be reallocated during a resize. You should call setChanged(true) if you mutate the array.*/ + Storage* getCArray() { + return data.getCArray(); + } + + + const Storage* getCArray() const { + return data.getCArray(); + } + + + /** Row-major array. You should call setChanged(true) if you mutate the array. */ + Array& getArray() { + return data; + } + + + const Array& getArray() const { + return data; + } + + /** is (x, y) strictly within the image bounds, or will it trigger some kind of wrap mode */ + inline bool inBounds(int x, int y) const { + return (((uint32)x < w) && ((uint32)y < h)); + } + + /** is (x, y) strictly within the image bounds, or will it trigger some kind of wrap mode */ + inline bool inBounds(const Vector2int16& v) const { + return inBounds(v.x, v.y); + } + + /** Get the value at (x, y). + + Note that the type of image->get(x, y) is + the storage type, not the computation + type. If the constructor promoting Storage to Compute rescales values + (as, for example Color3(Color3uint8&) does), this will not match the value + returned by Map2D::nearest. + */ + inline const Storage& get(int x, int y, WrapMode wrap) const { + if (((uint32)x < w) && ((uint32)y < h)) { + return data[x + y * w]; + } else { + // Remove the const to allow a slowGet on this object + // (we're returning a const reference so this is ok) + return const_cast(this)->slowGet(x, y, wrap); + } +# ifndef G3D_WIN32 + // gcc gives a useless warning that the above code might reach the end of the function; + // we use this line to supress the warning. + return ZERO; +# endif + } + + inline const Storage& get(int x, int y) const { + return get(x, y, _wrapMode); + } + + inline const Storage& get(const Vector2int16& p) const { + return get(p.x, p.y, _wrapMode); + } + + inline const Storage& get(const Vector2int16& p, WrapMode wrap) const { + return get(p.x, p.y, wrap); + } + + inline Storage& get(int x, int y, WrapMode wrap) { + return const_cast(const_cast(this)->get(x, y, wrap)); +# ifndef G3D_WIN32 + // gcc gives a useless warning that the above code might reach the end of the function; + // we use this line to supress the warning. + return ZERO; +# endif + } + + inline Storage& get(int x, int y) { + return const_cast(const_cast(this)->get(x, y)); +# ifndef G3D_WIN32 + // gcc gives a useless warning that the above code might reach the end of the function; + // we use this line to supress the warning. + return ZERO; +# endif + } + + inline Storage& get(const Vector2int16& p) { + return get(p.x, p.y); + } + + /** Sets the changed flag to true */ + inline void set(const Vector2int16& p, const Storage& v) { + set(p.x, p.y, v); + } + + /** Sets the changed flag to true */ + void set(int x, int y, const Storage& v, WrapMode wrap) { + setChanged(true); + if (((uint32)x < w) && ((uint32)y < h)) { + // In bounds, wrapping isn't an issue. + data[x + y * w] = v; + } else { + const_cast(slowGet(x, y, wrap)) = v; + } + } + + void set(int x, int y, const Storage& v) { + set(x, y, v, _wrapMode); + } + + + void setAll(const Storage& v) { + for(int i = 0; i < data.size(); ++i) { + data[i] = v; + } + setChanged(true); + } + + /** flips if @a flip is true*/ + void maybeFlipVertical(bool flip) { + if (flip) { + flipVertical(); + } + } + + virtual void flipVertical() { + int halfHeight = h/2; + Storage* d = data.getCArray(); + for (int y = 0; y < halfHeight; ++y) { + int o1 = y * w; + int o2 = (h - y - 1) * w; + for (int x = 0; x < (int)w; ++x) { + int i1 = o1 + x; + int i2 = o2 + x; + Storage temp = d[i1]; + d[i1] = d[i2]; + d[i2] = temp; + } + } + setChanged(true); + } + + virtual void flipHorizontal() { + int halfWidth = w / 2; + Storage* d = data.getCArray(); + for (int x = 0; x < halfWidth; ++x) { + for (int y = 0; y < (int)h; ++y) { + int i1 = y * w + x; + int i2 = y * w + (w - x - 1); + Storage temp = d[i1]; + d[i1] = d[i2]; + d[i2] = temp; + } + } + setChanged(true); + } + + /** + Crops this map so that it only contains pixels between (x, y) and (x + w - 1, y + h - 1) inclusive. + */ + virtual void crop(int newX, int newY, int newW, int newH) { + alwaysAssertM(newX + newW <= (int)w, "Cannot grow when cropping"); + alwaysAssertM(newY + newH <= (int)h, "Cannot grow when cropping"); + alwaysAssertM(newX >= 0 && newY >= 0, "Origin out of bounds."); + + // Always safe to copy towards the upper left, provided + // that we're iterating towards the lower right. This lets us avoid + // reallocating the underlying array. + for (int y = 0; y < newH; ++y) { + for (int x = 0; x < newW; ++x) { + data[x + y * newW] = data[(x + newX) + (y + newY) * w]; + } + } + + resize(newW, newH); + } + + /** iRounds to the nearest x0 and y0. */ + virtual void crop(const Rect2D& rect) { + crop(iRound(rect.x0()), iRound(rect.y0()), iRound(rect.x1()) - iRound(rect.x0()), iRound(rect.y1()) - iRound(rect.y0())); + } + + /** Returns the nearest neighbor. Pixel values are considered + to be at the upper left corner, so image->nearest(x, y) == image(x, y) + */ + inline Compute nearest(float x, float y, WrapMode wrap) const { + int ix = iRound(x); + int iy = iRound(y); + return Compute(get(ix, iy, wrap)); + } + + inline Compute nearest(float x, float y) const { + return nearest(x, y, _wrapMode); + } + + inline Compute nearest(const Vector2& p) const { + return nearest(p.x, p.y); + } + + /** Returns the average value of all elements of the map */ + Compute average() const { + if ((w == 0) || (h == 0)) { + return ZERO; + } + + // To avoid overflows, compute the average of row averages + + Compute rowSum = ZERO; + for (unsigned int y = 0; y < h; ++y) { + Compute sum = ZERO; + int offset = y * w; + for (unsigned int x = 0; x < w; ++x) { + sum += Compute(data[offset + x]); + } + rowSum += sum * (1.0f / w); + } + + return rowSum * (1.0f / h); + } + + /** + Needs to access elements from (floor(x), floor(y)) + to (floor(x) + 1, floor(y) + 1) and will use + the wrap mode appropriately (possibly generating + out of bounds errors). + + Guaranteed to match nearest(x, y) at integers. */ + Compute bilinear(float x, float y, WrapMode wrap) const { + const int i = iFloor(x); + const int j = iFloor(y); + + const float fX = x - i; + const float fY = y - j; + + // Horizontal interpolation, first row + const Compute& t0 = get(i, j, wrap); + const Compute& t1 = get(i + 1, j, wrap); + + // Horizontal interpolation, second row + const Compute& t2 = get(i, j + 1, wrap); + const Compute& t3 = get(i + 1, j + 1, wrap); + + const Compute& A = lerp(t0, t1, fX); + const Compute& B = lerp(t2, t3, fX); + + // Vertical interpolation + return lerp(A, B, fY); + } + + Compute bilinear(float x, float y) const { + return bilinear(x, y, _wrapMode); + } + + inline Compute bilinear(const Vector2& p) const { + return bilinear(p.x, p.y, _wrapMode); + } + + inline Compute bilinear(const Vector2& p, WrapMode wrap) const { + return bilinear(p.x, p.y, wrap); + } + + /** + Uses Catmull-Rom splines to interpolate between grid + values. Guaranteed to match nearest(x, y) at integers. + */ + Compute bicubic(float x, float y, WrapMode wrap) const { + int i = iFloor(x); + int j = iFloor(y); + float fX = x - i; + float fY = y - j; + + Compute vsample[4]; + for (int v = 0; v < 4; ++v) { + + // Horizontal interpolation + Compute hsample[4]; + for (int u = 0; u < 4; ++u) { + hsample[u] = Compute(get(i + u - 1, j + v - 1, wrap)); + } + + vsample[v] = bicubic(hsample, fX); + } + + // Vertical interpolation + return bicubic(vsample, fY); + } + + Compute bicubic(float x, float y) const { + return bicubic(x, y, _wrapMode); + } + + inline Compute bicubic(const Vector2& p, WrapMode wrap) const { + return bicubic(p.x, p.y, wrap); + } + + inline Compute bicubic(const Vector2& p) const { + return bicubic(p.x, p.y, _wrapMode); + } + + /** Pixel width */ + inline int32 width() const { + return (int32)w; + } + + + /** Pixel height */ + inline int32 height() const { + return (int32)h; + } + + + /** Dimensions in pixels */ + Vector2int16 size() const { + return Vector2int16(w, h); + } + + /** Rectangle from (0, 0) to (w, h) */ + Rect2D rect2DBounds() const { + return Rect2D::xywh(0, 0, w, h); + } + + /** Number of bytes occupied by the image data and this structure */ + size_t sizeInMemory() const { + return data.size() * sizeof(Storage) + sizeof(*this); + } + + + WrapMode wrapMode() const { + return _wrapMode; + } + + + void setWrapMode(WrapMode m) { + _wrapMode = m; + } +}; + + + +} + +#endif // G3D_IMAGE_H diff --git a/dep/g3dlite/G3D/Matrix.h b/dep/g3dlite/G3D/Matrix.h new file mode 100644 index 00000000000..3c5394d9a76 --- /dev/null +++ b/dep/g3dlite/G3D/Matrix.h @@ -0,0 +1,634 @@ +/** + @file Matrix.h + @author Morgan McGuire, http://graphics.cs.williams.edu + + @created 2005-10-23 + @edited 2007-07-18 + */ + +#ifndef G3D_MATRIX_H +#define G3D_MATRIX_H + +#include "G3D/g3dmath.h" +#include "G3D/Vector3.h" +#include "G3D/Vector4.h" +#include "G3D/Matrix3.h" +#include "G3D/Matrix4.h" +#include "G3D/ReferenceCount.h" + +namespace G3D { + +/** + N x M matrix. + + The actual data is tracked internally by a reference counted pointer; + it is efficient to pass and assign Matrix objects because no data is actually copied. + This avoids the headache of pointers and allows natural math notation: + +
+    Matrix A, B, C;
+    // ...
+
+    C = A * f(B);
+    C = C.inverse();
+
+    A = Matrix::identity(4);
+    C = A;
+    C.set(0, 0, 2.0); // Triggers a copy of the data so that A remains unchanged.
+
+    // etc.
+
+  
+ + The Matrix::debugNumCopyOps and Matrix::debugNumAllocOps counters + increment every time an operation forces the copy and allocation of matrices. You + can use these to detect slow operations when efficiency is a major concern. + + Some methods accept an output argument instead of returning a value. For example, + A = B.transpose() can also be invoked as B.transpose(A). + The latter may be more efficient, since Matrix may be able to re-use the storage of + A (if it has approximatly the right size and isn't currently shared with another matrix). + + @sa G3D::Matrix3, G3D::Matrix4, G3D::Vector2, G3D::Vector3, G3D::Vector4, G3D::CoordinateFrame + + @beta + */ +class Matrix { +public: + /** + Internal precision. Currently float, but this may become a templated class in the future + to allow operations like Matrix and Matrix. + + Not necessarily a plain-old-data type (e.g., could ComplexFloat), but must be something + with no constructor, that can be safely memcpyd, and that has a bit pattern of all zeros + when zero.*/ + typedef float T; + + /** Incremented every time the elements of a matrix are copied. Useful for profiling your + own code that uses Matrix to determine when it is slow due to copying.*/ + static int debugNumCopyOps; + + /** Incremented every time a new matrix object is allocated. Useful for profiling your + own code that uses Matrix to determine when it is slow due to allocation.*/ + static int debugNumAllocOps; + +private: +public: + + /** Used internally by Matrix. + + Does not throw exceptions-- assumes the caller has taken care of + argument checking. */ + class Impl : public ReferenceCountedObject { + public: + + static void* operator new(size_t size) { + return System::malloc(size); + } + + static void operator delete(void* p) { + System::free(p); + } + + ~Impl(); + + private: + friend class Matrix; + + /** elt[r][c] = the element. Pointers into data.*/ + T** elt; + + /** Row major data for the entire matrix. */ + T* data; + + /** The number of rows */ + int R; + + /** The number of columns */ + int C; + + int dataSize; + + /** If R*C is much larger or smaller than the current, deletes all previous data + and resets to random data. Otherwise re-uses existing memory and just resets + R, C, and the row pointers. */ + void setSize(int newRows, int newCols); + + inline Impl() : elt(NULL), data(NULL), R(0), C(0), dataSize(0) {} + + Impl(const Matrix3& M); + + Impl(const Matrix4& M); + + inline Impl(int r, int c) : elt(NULL), data(NULL), R(0), C(0), dataSize(0) { + setSize(r, c); + } + + Impl& operator=(const Impl& m); + + inline Impl(const Impl& B) : elt(NULL), data(NULL), R(0), C(0), dataSize(0) { + // Use the assignment operator + *this = B; + } + + void setZero(); + + inline void set(int r, int c, T v) { + debugAssert(r < R); + debugAssert(c < C); + elt[r][c] = v; + } + + inline const T& get(int r, int c) const { + debugAssert(r < R); + debugAssert(c < C); + return elt[r][c]; + } + + /** Multiplies this by B and puts the result in out. */ + void mul(const Impl& B, Impl& out) const; + + /** Ok if out == this or out == B */ + void add(const Impl& B, Impl& out) const; + + /** Ok if out == this or out == B */ + void add(T B, Impl& out) const; + + /** Ok if out == this or out == B */ + void sub(const Impl& B, Impl& out) const; + + /** Ok if out == this or out == B */ + void sub(T B, Impl& out) const; + + /** B - this */ + void lsub(T B, Impl& out) const; + + /** Ok if out == this or out == B */ + void arrayMul(const Impl& B, Impl& out) const; + + /** Ok if out == this or out == B */ + void mul(T B, Impl& out) const; + + /** Ok if out == this or out == B */ + void arrayDiv(const Impl& B, Impl& out) const; + + /** Ok if out == this or out == B */ + void div(T B, Impl& out) const; + + void negate(Impl& out) const; + + /** Slow way of computing an inverse; for reference */ + void inverseViaAdjoint(Impl& out) const; + + /** Use Gaussian elimination with pivots to solve for the inverse destructively in place. */ + void inverseInPlaceGaussJordan(); + + void adjoint(Impl& out) const; + + /** Matrix of all cofactors */ + void cofactor(Impl& out) const; + + /** + Cofactor [r][c] is defined as C[r][c] = -1 ^(r+c) * det(A[r][c]), + where A[r][c] is the (R-1)x(C-1) matrix formed by removing row r and + column c from the original matrix. + */ + T cofactor(int r, int c) const; + + /** Ok if out == this or out == B */ + void transpose(Impl& out) const; + + T determinant() const; + + /** Determinant computed without the given row and column */ + T determinant(int r, int c) const; + + void arrayLog(Impl& out) const; + + void arrayExp(Impl& out) const; + + void arraySqrt(Impl& out) const; + + void arrayCos(Impl& out) const; + + void arraySin(Impl& out) const; + + void swapRows(int r0, int r1); + + void swapAndNegateCols(int c0, int c1); + + void mulRow(int r, const T& v); + + void abs(Impl& out) const; + + /** Makes a (R-1)x(C-1) copy of this matrix */ + void withoutRowAndCol(int excludeRow, int excludeCol, Impl& out) const; + + bool anyNonZero() const; + + bool allNonZero() const; + + void setRow(int r, const T* vals); + + void setCol(int c, const T* vals); + }; +private: + + typedef ReferenceCountedPointer ImplRef; + + ImplRef impl; + + inline Matrix(ImplRef i) : impl(i) {} + inline Matrix(Impl* i) : impl(ImplRef(i)) {} + + /** Used by SVD */ + class SortRank { + public: + T value; + int col; + + inline bool operator>(const SortRank& x) const { + return x.value > value; + } + + inline bool operator<(const SortRank& x) const { + return x.value < value; + } + + inline bool operator>=(const SortRank& x) const { + return x.value >= value; + } + + inline bool operator<=(const SortRank& x) const { + return x.value <= value; + } + + inline bool operator==(const SortRank& x) const { + return x.value == value; + } + + inline bool operator!=(const SortRank& x) const { + return x.value != value; + } + }; + + Matrix vectorPseudoInverse() const; + Matrix partitionPseudoInverse() const; + Matrix colPartPseudoInverse() const; + Matrix rowPartPseudoInverse() const; + + Matrix col2PseudoInverse(const Matrix& B) const; + Matrix col3PseudoInverse(const Matrix& B) const; + Matrix col4PseudoInverse(const Matrix& B) const; + Matrix row2PseudoInverse(const Matrix& B) const; + Matrix row3PseudoInverse(const Matrix& B) const; + Matrix row4PseudoInverse(const Matrix& B) const; + +public: + + Matrix() : impl(new Impl(0, 0)) {} + + Matrix(const Matrix3& M) : impl(new Impl(M)) {} + + Matrix(const Matrix4& M) : impl(new Impl(M)) {} + + template + static Matrix fromDiagonal(const Array& d) { + Matrix D = zero(d.length(), d.length()); + for (int i = 0; i < d.length(); ++i) { + D.set(i, i, d[i]); + } + return D; + } + + static Matrix fromDiagonal(const Matrix& d); + + /** Returns a new matrix that is all zero. */ + Matrix(int R, int C) : impl(new Impl(R, C)) { + impl->setZero(); + } + + /** Returns a new matrix that is all zero. */ + static Matrix zero(int R, int C); + + /** Returns a new matrix that is all one. */ + static Matrix one(int R, int C); + + /** Returns a new identity matrix */ + static Matrix identity(int N); + + /** Uniformly distributed values between zero and one. */ + static Matrix random(int R, int C); + + /** The number of rows */ + inline int rows() const { + return impl->R; + } + + /** Number of columns */ + inline int cols() const { + return impl->C; + } + + /** Generally more efficient than A * B */ + Matrix& operator*=(const T& B); + + /** Generally more efficient than A / B */ + Matrix& operator/=(const T& B); + + /** Generally more efficient than A + B */ + Matrix& operator+=(const T& B); + + /** Generally more efficient than A - B */ + Matrix& operator-=(const T& B); + + /** No performance advantage over A * B because + matrix multiplication requires intermediate + storage. */ + Matrix& operator*=(const Matrix& B); + + /** Generally more efficient than A + B */ + Matrix& operator+=(const Matrix& B); + + /** Generally more efficient than A - B */ + Matrix& operator-=(const Matrix& B); + + /** Returns a new matrix that is a subset of this one, + from r1:r2 to c1:c2, inclusive.*/ + Matrix subMatrix(int r1, int r2, int c1, int c2) const; + + /** Matrix multiplication. To perform element-by-element multiplication, + see arrayMul. */ + inline Matrix operator*(const Matrix& B) const { + Matrix C(impl->R, B.impl->C); + impl->mul(*B.impl, *C.impl); + return C; + } + + /** See also A *= B, which is more efficient in many cases */ + inline Matrix operator*(const T& B) const { + Matrix C(impl->R, impl->C); + impl->mul(B, *C.impl); + return C; + } + + /** See also A += B, which is more efficient in many cases */ + inline Matrix operator+(const Matrix& B) const { + Matrix C(impl->R, impl->C); + impl->add(*B.impl, *C.impl); + return C; + } + + /** See also A -= B, which is more efficient in many cases */ + inline Matrix operator-(const Matrix& B) const { + Matrix C(impl->R, impl->C); + impl->sub(*B.impl, *C.impl); + return C; + } + + /** See also A += B, which is more efficient in many cases */ + inline Matrix operator+(const T& v) const { + Matrix C(impl->R, impl->C); + impl->add(v, *C.impl); + return C; + } + + /** See also A -= B, which is more efficient in many cases */ + inline Matrix operator-(const T& v) const { + Matrix C(impl->R, impl->C); + impl->sub(v, *C.impl); + return C; + } + + + Matrix operator>(const T& scalar) const; + + Matrix operator<(const T& scalar) const; + + Matrix operator>=(const T& scalar) const; + + Matrix operator<=(const T& scalar) const; + + Matrix operator==(const T& scalar) const; + + Matrix operator!=(const T& scalar) const; + + /** scalar B - this */ + inline Matrix lsub(const T& B) const { + Matrix C(impl->R, impl->C); + impl->lsub(B, *C.impl); + return C; + } + + inline Matrix arrayMul(const Matrix& B) const { + Matrix C(impl->R, impl->C); + impl->arrayMul(*B.impl, *C.impl); + return C; + } + + Matrix3 toMatrix3() const; + + Matrix4 toMatrix4() const; + + Vector2 toVector2() const; + + Vector3 toVector3() const; + + Vector4 toVector4() const; + + /** Mutates this */ + void arrayMulInPlace(const Matrix& B); + + /** Mutates this */ + void arrayDivInPlace(const Matrix& B); + + // Declares an array unary method and its explicit-argument counterpart +# define DECLARE_METHODS_1(method)\ + inline Matrix method() const {\ + Matrix C(impl->R, impl->C);\ + impl->method(*C.impl);\ + return C;\ + }\ + void method(Matrix& out) const; + + + DECLARE_METHODS_1(abs) + DECLARE_METHODS_1(arrayLog) + DECLARE_METHODS_1(arrayExp) + DECLARE_METHODS_1(arraySqrt) + DECLARE_METHODS_1(arrayCos) + DECLARE_METHODS_1(arraySin) + DECLARE_METHODS_1(negate) + +# undef DECLARE_METHODS_1 + + inline Matrix operator-() const { + return negate(); + } + + /** + A-1 computed using the Gauss-Jordan algorithm, + for square matrices. + Run time is O(R3), where R is the + number of rows. + */ + inline Matrix inverse() const { + Impl* A = new Impl(*impl); + A->inverseInPlaceGaussJordan(); + return Matrix(A); + } + + inline T determinant() const { + return impl->determinant(); + } + + /** + AT + */ + inline Matrix transpose() const { + Impl* A = new Impl(cols(), rows()); + impl->transpose(*A); + return Matrix(A); + } + + /** Transpose in place; more efficient than transpose */ + void transpose(Matrix& out) const; + + inline Matrix adjoint() const { + Impl* A = new Impl(cols(), rows()); + impl->adjoint(*A); + return Matrix(A); + } + + /** + (ATA)-1AT) computed + using SVD. + + @param tolerance Use -1 for automatic tolerance. + */ + Matrix pseudoInverse(float tolerance = -1) const; + + /** Called from pseudoInverse when the matrix has size > 4 along some dimension.*/ + Matrix svdPseudoInverse(float tolerance = -1) const; + + /** + (ATA)-1AT) computed + using Gauss-Jordan elimination. + */ + inline Matrix gaussJordanPseudoInverse() const { + Matrix trans = transpose(); + return (trans * (*this)).inverse() * trans; + } + + /** Singular value decomposition. Factors into three matrices + such that @a this = @a U * fromDiagonal(@a d) * @a V.transpose(). + + The matrix must have at least as many rows as columns. + + Run time is O(C2*R). + + @param sort If true (default), the singular values + are arranged so that D is sorted from largest to smallest. + */ + void svd(Matrix& U, Array& d, Matrix& V, bool sort = true) const; + + void set(int r, int c, T v); + + void setCol(int c, const Matrix& vec); + + void setRow(int r, const Matrix& vec); + + Matrix col(int c) const; + + Matrix row(int r) const; + + T get(int r, int c) const; + + Vector2int16 size() const { + return Vector2int16(rows(), cols()); + } + + int numElements() const { + return rows() * cols(); + } + + void swapRows(int r0, int r1); + + /** Swaps columns c0 and c1 and negates both */ + void swapAndNegateCols(int c0, int c1); + + void mulRow(int r, const T& v); + + /** Returns true if any element is non-zero */ + bool anyNonZero() const; + + /** Returns true if all elements are non-zero */ + bool allNonZero() const; + + inline bool allZero() const { + return !anyNonZero(); + } + + inline bool anyZero() const { + return !allNonZero(); + } + + /** Serializes in Matlab source format */ + void serialize(TextOutput& t) const; + + std::string toString(const std::string& name) const; + + std::string toString() const { + static const std::string name = ""; + return toString(name); + } + + /** 2-norm squared: sum(squares). (i.e., dot product with itself) */ + double normSquared() const; + + /** 2-norm (sqrt(sum(squares)) */ + double norm() const; + + /** + Low-level SVD functionality. Useful for applications that do not want + to construct a Matrix but need to perform the SVD operation. + + this = U * D * V' + + Assumes that rows >= cols + + @return NULL on success, a string describing the error on failure. + @param U rows x cols matrix to be decomposed, gets overwritten with U, a rows x cols matrix with orthogonal columns. + @param D vector of singular values of a (diagonal of the D matrix). Length cols. + @param V returns the right orthonormal transformation matrix, size cols x cols + + @cite Based on Dianne Cook's implementation, which is adapted from + svdecomp.c in XLISP-STAT 2.1, which is code from Numerical Recipes + adapted by Luke Tierney and David Betz. The Numerical Recipes code + is adapted from Forsythe et al, who based their code on Golub and + Reinsch's original implementation. + */ + static const char* svdCore(float** U, int rows, int cols, float* D, float** V); + +}; + +} + +inline G3D::Matrix operator-(const G3D::Matrix::T& v, const G3D::Matrix& M) { + return M.lsub(v); +} + +inline G3D::Matrix operator*(const G3D::Matrix::T& v, const G3D::Matrix& M) { + return M * v; +} + +inline G3D::Matrix operator+(const G3D::Matrix::T& v, const G3D::Matrix& M) { + return M + v; +} + +inline G3D::Matrix abs(const G3D::Matrix& M) { + return M.abs(); +} + +#endif + diff --git a/dep/g3dlite/G3D/Matrix2.h b/dep/g3dlite/G3D/Matrix2.h new file mode 100644 index 00000000000..eaf4aefa220 --- /dev/null +++ b/dep/g3dlite/G3D/Matrix2.h @@ -0,0 +1,69 @@ +#ifndef G3D_MATRIX2_H +#define G3D_MATRIX2_H + +#include "G3D/platform.h" +#include "G3D/Vector2.h" + +namespace G3D { + +/** @beta */ +class Matrix2 { +private: + + float data[2][2]; + +public: + + inline Matrix2() { + data[0][0] = 1.0f; data[0][1] = 0.0f; + data[1][0] = 0.0f; data[1][1] = 1.0f; + } + + inline Matrix2(float v00, float v01, float v10, float v11) { + data[0][0] = v00; data[0][1] = v01; + data[1][0] = v10; data[1][1] = v11; + } + + inline Vector2 operator*(const Vector2& v) const { + return Vector2(data[0][0] * v[0] + data[0][1] * v[1], + data[1][0] * v[0] + data[1][1] * v[1]); + } + + inline Matrix2 inverse() const { + return Matrix2(data[0][0], data[1][0], + data[0][1], data[1][1]) * (1.0f / determinant()); + } + + inline Matrix2 transpose() const { + return Matrix2(data[0][0], data[1][0], + data[0][1], data[1][1]); + } + + inline float determinant() const { + return data[0][0] * data[1][1] - data[0][1] * data[1][0]; + } + + inline Matrix2 operator*(float f) const { + return Matrix2(data[0][0] * f, data[0][1] * f, + data[1][0] * f, data[1][1] * f); + } + + inline Matrix2 operator/(float f) const { + return Matrix2(data[0][0] / f, data[0][1] / f, + data[1][0] / f, data[1][1] / f); + } + + inline float* operator[](int i) { + debugAssert(i >= 0 && i <= 2); + return data[i]; + } + + inline const float* operator[](int i) const { + debugAssert(i >= 0 && i <= 1); + return data[i]; + } +}; + +} + +#endif diff --git a/dep/g3dlite/G3D/Matrix3.h b/dep/g3dlite/G3D/Matrix3.h new file mode 100644 index 00000000000..06ec7e67474 --- /dev/null +++ b/dep/g3dlite/G3D/Matrix3.h @@ -0,0 +1,366 @@ +/** + @file Matrix3.h + + 3x3 matrix class + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @cite Portions based on Dave Eberly's Magic Software Library at
http://www.magic-software.com + + @created 2001-06-02 + @edited 2006-04-05 + */ + +#ifndef G3D_Matrix3_h +#define G3D_Matrix3_h + +#include "G3D/platform.h" +#include "G3D/Vector3.h" +#include "G3D/Vector4.h" +#include "G3D/debugAssert.h" + +#include + +namespace G3D { + +#ifdef _MSC_VER +// Turn off "conditional expression is constant" warning; MSVC generates this +// for debug assertions in inlined methods. +# pragma warning (disable : 4127) +#endif + +class Any; + +/** + 3x3 matrix. Do not subclass. + */ +class Matrix3 { +private: + + float elt[3][3]; + + // Hidden operators + bool operator<(const Matrix3&) const; + bool operator>(const Matrix3&) const; + bool operator<=(const Matrix3&) const; + bool operator>=(const Matrix3&) const; + +public: + + Matrix3(const Any& any); + + operator Any() const; + + /** Initial values are undefined for performance. See also + Matrix3::zero(), Matrix3::identity(), Matrix3::fromAxisAngle, etc.*/ + inline Matrix3() {} + + Matrix3 (class BinaryInput& b); + Matrix3 (const float aafEntry[3][3]); + Matrix3 (const Matrix3& rkMatrix); + Matrix3 (float fEntry00, float fEntry01, float fEntry02, + float fEntry10, float fEntry11, float fEntry12, + float fEntry20, float fEntry21, float fEntry22); + + bool fuzzyEq(const Matrix3& b) const; + + /** Constructs a matrix from a quaternion. + @cite Graphics Gems II, p. 351--354 + @cite Implementation from Watt and Watt, pg 362*/ + Matrix3(const class Quat& q); + + void serialize(class BinaryOutput& b) const; + void deserialize(class BinaryInput& b); + + /** Returns true if column(0).cross(column(1)).dot(column(2)) > 0. */ + bool isRightHanded() const; + + /** + Sets all elements. + */ + void set(float fEntry00, float fEntry01, float fEntry02, + float fEntry10, float fEntry11, float fEntry12, + float fEntry20, float fEntry21, float fEntry22); + + /** + * member access, allows use of construct mat[r][c] + */ + inline float* operator[] (int iRow) { + debugAssert(iRow >= 0); + debugAssert(iRow < 3); + return (float*)&elt[iRow][0]; + } + + inline const float* operator[] (int iRow) const { + debugAssert(iRow >= 0); + debugAssert(iRow < 3); + return (const float*)&elt[iRow][0]; + } + + inline operator float* () { + return (float*)&elt[0][0]; + } + + inline operator const float* () const{ + return (const float*)&elt[0][0]; + } + + Vector3 column(int c) const; + const Vector3& row(int r) const; + + void setColumn(int iCol, const Vector3 &vector); + void setRow(int iRow, const Vector3 &vector); + + // assignment and comparison + inline Matrix3& operator= (const Matrix3& rkMatrix) { + memcpy(elt, rkMatrix.elt, 9 * sizeof(float)); + return *this; + } + + bool operator== (const Matrix3& rkMatrix) const; + bool operator!= (const Matrix3& rkMatrix) const; + + // arithmetic operations + Matrix3 operator+ (const Matrix3& rkMatrix) const; + Matrix3 operator- (const Matrix3& rkMatrix) const; + /** Matrix-matrix multiply */ + Matrix3 operator* (const Matrix3& rkMatrix) const; + Matrix3 operator- () const; + + Matrix3& operator+= (const Matrix3& rkMatrix); + Matrix3& operator-= (const Matrix3& rkMatrix); + Matrix3& operator*= (const Matrix3& rkMatrix); + + /** + * matrix * vector [3x3 * 3x1 = 3x1] + */ + inline Vector3 operator* (const Vector3& v) const { + Vector3 kProd; + + for (int r = 0; r < 3; ++r) { + kProd[r] = + elt[r][0] * v[0] + + elt[r][1] * v[1] + + elt[r][2] * v[2]; + } + + return kProd; + } + + + /** + * vector * matrix [1x3 * 3x3 = 1x3] + */ + friend Vector3 operator* (const Vector3& rkVector, + const Matrix3& rkMatrix); + + /** + * matrix * scalar + */ + Matrix3 operator* (float fScalar) const; + + /** scalar * matrix */ + friend Matrix3 operator* (double fScalar, const Matrix3& rkMatrix); + friend Matrix3 operator* (float fScalar, const Matrix3& rkMatrix); + friend Matrix3 operator* (int fScalar, const Matrix3& rkMatrix); + + Matrix3& operator*= (float k); + Matrix3& operator/= (float k); + + +private: + /** Multiplication where out != A and out != B */ + static void _mul(const Matrix3& A, const Matrix3& B, Matrix3& out); +public: + + /** Optimized implementation of out = A * B. It is safe (but slow) to call + with A, B, and out possibly pointer equal to one another.*/ + // This is a static method so that it is not ambiguous whether "this" + // is an input or output argument. + inline static void mul(const Matrix3& A, const Matrix3& B, Matrix3& out) { + if ((&out == &A) || (&out == &B)) { + // We need a temporary anyway, so revert to the stack method. + out = A * B; + } else { + // Optimized in-place multiplication. + _mul(A, B, out); + } + } + +private: + static void _transpose(const Matrix3& A, Matrix3& out); +public: + + /** Optimized implementation of out = A.transpose(). It is safe (but slow) to call + with A and out possibly pointer equal to one another. + + Note that A.transpose() * v can be computed + more efficiently as v * A. + */ + inline static void transpose(const Matrix3& A, Matrix3& out) { + if (&A == &out) { + out = A.transpose(); + } else { + _transpose(A, out); + } + } + + /** Returns true if the rows and column L2 norms are 1.0 and the rows are orthogonal. */ + bool isOrthonormal() const; + + Matrix3 transpose () const; + bool inverse (Matrix3& rkInverse, float fTolerance = 1e-06) const; + Matrix3 inverse (float fTolerance = 1e-06) const; + float determinant () const; + + /** singular value decomposition */ + void singularValueDecomposition (Matrix3& rkL, Vector3& rkS, + Matrix3& rkR) const; + /** singular value decomposition */ + void singularValueComposition (const Matrix3& rkL, + const Vector3& rkS, const Matrix3& rkR); + + /** Gram-Schmidt orthonormalization (applied to columns of rotation matrix) */ + void orthonormalize(); + + /** orthogonal Q, diagonal D, upper triangular U stored as (u01,u02,u12) */ + void qDUDecomposition (Matrix3& rkQ, Vector3& rkD, + Vector3& rkU) const; + + /** + Polar decomposition of a matrix. Based on pseudocode from Nicholas J + Higham, "Computing the Polar Decomposition -- with Applications Siam + Journal of Science and Statistical Computing, Vol 7, No. 4, October + 1986. + + Decomposes A into R*S, where R is orthogonal and S is symmetric. + + Ken Shoemake's "Matrix animation and polar decomposition" + in Proceedings of the conference on Graphics interface '92 + seems to be better known in the world of graphics, but Higham's version + uses a scaling constant that can lead to faster convergence than + Shoemake's when the initial matrix is far from orthogonal. + */ + void polarDecomposition(Matrix3 &R, Matrix3 &S) const; + + /** + * Matrix norms. + */ + float spectralNorm () const; + + float squaredFrobeniusNorm() const; + + float frobeniusNorm() const; + + float l1Norm() const; + + float lInfNorm() const; + + float diffOneNorm(const Matrix3 &y) const; + + /** matrix must be orthonormal */ + void toAxisAngle(Vector3& rkAxis, float& rfRadians) const; + + static Matrix3 fromDiagonal(const Vector3& d) { + return Matrix3(d.x, 0, 0, + 0, d.y, 0, + 0, 0, d.z); + } + + static Matrix3 fromAxisAngle(const Vector3& rkAxis, float fRadians); + + /** + * The matrix must be orthonormal. The decomposition is yaw*pitch*roll + * where yaw is rotation about the Up vector, pitch is rotation about the + * right axis, and roll is rotation about the Direction axis. + */ + bool toEulerAnglesXYZ (float& rfYAngle, float& rfPAngle, + float& rfRAngle) const; + bool toEulerAnglesXZY (float& rfYAngle, float& rfPAngle, + float& rfRAngle) const; + bool toEulerAnglesYXZ (float& rfYAngle, float& rfPAngle, + float& rfRAngle) const; + bool toEulerAnglesYZX (float& rfYAngle, float& rfPAngle, + float& rfRAngle) const; + bool toEulerAnglesZXY (float& rfYAngle, float& rfPAngle, + float& rfRAngle) const; + bool toEulerAnglesZYX (float& rfYAngle, float& rfPAngle, + float& rfRAngle) const; + static Matrix3 fromEulerAnglesXYZ (float fYAngle, float fPAngle, float fRAngle); + static Matrix3 fromEulerAnglesXZY (float fYAngle, float fPAngle, float fRAngle); + static Matrix3 fromEulerAnglesYXZ (float fYAngle, float fPAngle, float fRAngle); + static Matrix3 fromEulerAnglesYZX (float fYAngle, float fPAngle, float fRAngle); + static Matrix3 fromEulerAnglesZXY (float fYAngle, float fPAngle, float fRAngle); + static Matrix3 fromEulerAnglesZYX (float fYAngle, float fPAngle, float fRAngle); + + /** eigensolver, matrix must be symmetric */ + void eigenSolveSymmetric (float afEigenvalue[3], + Vector3 akEigenvector[3]) const; + + static void tensorProduct (const Vector3& rkU, const Vector3& rkV, + Matrix3& rkProduct); + std::string toString() const; + + static const float EPSILON; + + // Special values. + // The unguaranteed order of initialization of static variables across + // translation units can be a source of annoying bugs, so now the static + // special values (like Vector3::ZERO, Color3::WHITE, ...) are wrapped + // inside static functions that return references to them. + // These functions are intentionally not inlined, because: + // "You might be tempted to write [...] them as inline functions + // inside their respective header files, but this is something you + // must definitely not do. An inline function can be duplicated + // in every file in which it appears œóõ½ and this duplication + // includes the static object definition. Because inline functions + // automatically default to internal linkage, this would result in + // having multiple static objects across the various translation + // units, which would certainly cause problems. So you must + // ensure that there is only one definition of each wrapping + // function, and this means not making the wrapping functions inline", + // according to Chapter 10 of "Thinking in C++, 2nd ed. Volume 1" by Bruce Eckel, + // http://www.mindview.net/ + static const Matrix3& zero(); + static const Matrix3& identity(); + +protected: + + // support for eigensolver + void tridiagonal (float afDiag[3], float afSubDiag[3]); + bool qLAlgorithm (float afDiag[3], float afSubDiag[3]); + + // support for singular value decomposition + static const float ms_fSvdEpsilon; + static const int ms_iSvdMaxIterations; + static void bidiagonalize (Matrix3& kA, Matrix3& kL, + Matrix3& kR); + static void golubKahanStep (Matrix3& kA, Matrix3& kL, + Matrix3& kR); + + // support for spectral norm + static float maxCubicRoot (float afCoeff[3]); + +}; + + +//---------------------------------------------------------------------------- +/** v * M == M.transpose() * v */ +inline Vector3 operator* (const Vector3& rkPoint, const Matrix3& rkMatrix) { + Vector3 kProd; + + for (int r = 0; r < 3; ++r) { + kProd[r] = + rkPoint[0] * rkMatrix.elt[0][r] + + rkPoint[1] * rkMatrix.elt[1][r] + + rkPoint[2] * rkMatrix.elt[2][r]; + } + + return kProd; +} + + +} // namespace + +#endif + diff --git a/dep/g3dlite/G3D/Matrix4.h b/dep/g3dlite/G3D/Matrix4.h new file mode 100644 index 00000000000..9ce87d875b8 --- /dev/null +++ b/dep/g3dlite/G3D/Matrix4.h @@ -0,0 +1,249 @@ +/** + @file Matrix4.h + + 4x4 matrix class + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2003-10-02 + @edited 2009-10-20 + */ + +#ifndef G3D_Matrix4_h +#define G3D_Matrix4_h + +#ifdef _MSC_VER +// Disable conditional expression is constant, which occurs incorrectly on inlined functions +# pragma warning (push) +# pragma warning( disable : 4127 ) +#endif + +#include "G3D/platform.h" +#include "G3D/debugAssert.h" +#include "G3D/Matrix3.h" +#include "G3D/Vector3.h" + +namespace G3D { + +class Any; + +/** + A 4x4 matrix. + + See also G3D::CoordinateFrame, G3D::Matrix3, G3D::Quat + */ +class Matrix4 { +private: + + float elt[4][4]; + + /** + Computes the determinant of the 3x3 matrix that lacks excludeRow + and excludeCol. + */ + float subDeterminant(int excludeRow, int excludeCol) const; + + // Hidden operators + bool operator<(const Matrix4&) const; + bool operator>(const Matrix4&) const; + bool operator<=(const Matrix4&) const; + bool operator>=(const Matrix4&) const; + +public: + /** Must be of the form: Matrix4(#, #, # .... #)*/ + Matrix4(const Any& any); + + operator Any() const; + + Matrix4( + float r1c1, float r1c2, float r1c3, float r1c4, + float r2c1, float r2c2, float r2c3, float r2c4, + float r3c1, float r3c2, float r3c3, float r3c4, + float r4c1, float r4c2, float r4c3, float r4c4); + + /** + init should be row major. + */ + Matrix4(const float* init); + + /** + a is the upper left 3x3 submatrix and b is the upper right 3x1 submatrix. The last row of the created matrix is (0,0,0,1). + */ + Matrix4(const class Matrix3& upper3x3, const class Vector3& lastCol = Vector3::zero()); + + Matrix4(const class CoordinateFrame& c); + + Matrix4(const double* init); + + Matrix4(); + + /** Produces an RT transformation that nearly matches this Matrix4. + Because a Matrix4 may not be precisely a rotation and translation, + this may introduce error. */ + class CoordinateFrame approxCoordinateFrame() const; + + // Special values. + // Intentionally not inlined: see Matrix3::identity() for details. + static const Matrix4& identity(); + static const Matrix4& zero(); + + /** If this is a perspective projection matrix created by + Matrix4::perspectiveProjection, extract its parameters. */ + void getPerspectiveProjectionParameters + (float& left, + float& right, + float& bottom, + float& top, + float& nearval, + float& farval, + float updirection = -1.0f) const; + + inline float* operator[](int r) { + debugAssert(r >= 0); + debugAssert(r < 4); + return (float*)&elt[r]; + } + + inline const float* operator[](int r) const { + debugAssert(r >= 0); + debugAssert(r < 4); + return (const float*)&elt[r]; + } + + inline operator float* () { + return (float*)&elt[0][0]; + } + + inline operator const float* () const { + return (const float*)&elt[0][0]; + } + + Matrix4 operator*(const Matrix4& other) const; + + class Matrix3 upper3x3() const; + + /** Homogeneous multiplication. Let k = M * [v w]^T. result = k.xyz() / k.w */ + class Vector3 homoMul(const class Vector3& v, float w) const; + + /** + Constructs an orthogonal projection matrix from the given parameters. + Near and far are the NEGATIVE of the near and far plane Z values + (to follow OpenGL conventions). + + \param upDirection Use -1.0 for 2D Y increasing downwards (the G3D 8.x default convention), + 1.0 for 2D Y increasing upwards (the G3D 7.x default and OpenGL convention) + */ + static Matrix4 orthogonalProjection( + float left, + float right, + float bottom, + float top, + float nearval, + float farval, + float upDirection = -1.0f); + + + /** \param upDirection Use -1.0 for 2D Y increasing downwards (the G3D 8.x default convention), + 1.0 for 2D Y increasing upwards (the G3D 7.x default and OpenGL convention) + */ + static Matrix4 orthogonalProjection( + const class Rect2D& rect, + float nearval, + float farval, + float upDirection = -1.0f); + + /** \param upDirection Use -1.0 for 2D Y increasing downwards (the G3D 8.x default convention), + 1.0 for 2D Y increasing upwards (the G3D 7.x default and OpenGL convention) + */ + static Matrix4 perspectiveProjection( + float left, + float right, + float bottom, + float top, + float nearval, + float farval, + float upDirection = -1.0f); + + void setRow(int r, const class Vector4& v); + void setColumn(int c, const Vector4& v); + + const Vector4& row(int r) const; + Vector4 column(int c) const; + + Matrix4 operator*(const float s) const; + Vector4 operator*(const Vector4& vector) const; + + Matrix4 transpose() const; + + bool operator!=(const Matrix4& other) const; + bool operator==(const Matrix4& other) const; + + float determinant() const; + Matrix4 inverse() const; + + /** + Transpose of the cofactor matrix (used in computing the inverse). + Note: This is in fact only one type of adjoint. More generally, + an adjoint of a matrix is any mapping of a matrix which possesses + certain properties. This returns the so-called adjugate + or classical adjoint. + */ + Matrix4 adjoint() const; + Matrix4 cofactor() const; + + /** Serializes row-major */ + void serialize(class BinaryOutput& b) const; + void deserialize(class BinaryInput& b); + + std::string toString() const; + + /** 3D scale matrix */ + inline static Matrix4 scale(const Vector3& v) { + return Matrix4(v.x, 0, 0, 0, + 0, v.y, 0, 0, + 0, 0, v.z, 0, + 0, 0, 0, 1); + } + + /** 3D scale matrix */ + inline static Matrix4 scale(float x, float y, float z) { + return scale(Vector3(x, y, z)); + } + + /** 3D scale matrix */ + inline static Matrix4 scale(float s) { + return scale(s,s,s); + } + + /** 3D translation matrix */ + inline static Matrix4 translation(const Vector3& v) { + return Matrix4(Matrix3::identity(), v); + } + + inline static Matrix4 translation(float x, float y, float z) { + return Matrix4(Matrix3::identity(), Vector3(x, y, z)); + } + + /** Create a rotation matrix that rotates \a deg degrees around the Y axis */ + inline static Matrix4 yawDegrees(float deg) { + return Matrix4(Matrix3::fromAxisAngle(Vector3::unitY(), toRadians(deg))); + } + + inline static Matrix4 pitchDegrees(float deg) { + return Matrix4(Matrix3::fromAxisAngle(Vector3::unitX(), toRadians(deg))); + } + + inline static Matrix4 rollDegrees(float deg) { + return Matrix4(Matrix3::fromAxisAngle(Vector3::unitZ(), toRadians(deg))); + } +}; + + + +} // namespace + +#ifdef _MSC_VER +# pragma warning (pop) +#endif + +#endif diff --git a/dep/g3dlite/G3D/MemoryManager.h b/dep/g3dlite/G3D/MemoryManager.h new file mode 100644 index 00000000000..15bf6d8be43 --- /dev/null +++ b/dep/g3dlite/G3D/MemoryManager.h @@ -0,0 +1,93 @@ +/** + @file MemoryManager.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + @created 2009-04-20 + @edited 2009-04-20 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ +#ifndef G3D_MemoryManager_h +#define G3D_MemoryManager_h + +#include "G3D/platform.h" +#include "G3D/ReferenceCount.h" + +namespace G3D { + +/** + Abstraction of memory management. + Default implementation uses G3D::System::malloc and is threadsafe. + + \sa CRTMemoryManager, AlignedMemoryManager, AreaMemoryManager */ +class MemoryManager : public ReferenceCountedObject { +protected: + + MemoryManager(); + +public: + + typedef ReferenceCountedPointer Ref; + + /** Return a pointer to \a s bytes of memory that are unused by + the rest of the program. The contents of the memory are + undefined */ + virtual void* alloc(size_t s); + + /** Invoke to declare that this memory will no longer be used by + the program. The memory manager is not required to actually + reuse or release this memory. */ + virtual void free(void* ptr); + + /** Returns true if this memory manager is threadsafe (i.e., alloc + and free can be called asychronously) */ + virtual bool isThreadsafe() const; + + /** Return the instance. There's only one instance of the default + MemoryManager; it is cached after the first creation. */ + static MemoryManager::Ref create(); +}; + +/** + Allocates memory on 16-byte boundaries. + \sa MemoryManager, CRTMemoryManager, AreaMemoryManager */ +class AlignedMemoryManager : public MemoryManager { +protected: + + AlignedMemoryManager(); + +public: + + typedef ReferenceCountedPointer Ref; + + + virtual void* alloc(size_t s); + + virtual void free(void* ptr); + + virtual bool isThreadsafe() const; + + static AlignedMemoryManager::Ref create(); +}; + + +/** MemoryManager implemented using the C runtime. */ +class CRTMemoryManager : public MemoryManager { +protected: + CRTMemoryManager(); + +public: + typedef ReferenceCountedPointer Ref; + virtual void* alloc(size_t s); + virtual void free(void* ptr); + virtual bool isThreadsafe() const; + + /** There's only one instance of this memory manager; it is + cached after the first creation. */ + static CRTMemoryManager::Ref create(); +}; + +} + +#endif diff --git a/dep/g3dlite/G3D/MeshAlg.h b/dep/g3dlite/G3D/MeshAlg.h new file mode 100644 index 00000000000..1decea10105 --- /dev/null +++ b/dep/g3dlite/G3D/MeshAlg.h @@ -0,0 +1,683 @@ +/** + @file MeshAlg.h + + Indexed Mesh algorithms. + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2003-09-14 + @edited 2010-01-18 +*/ + +#ifndef G3D_MeshAlg_h +#define G3D_MeshAlg_h + +#include "G3D/platform.h" +#include "G3D/Array.h" +#include "G3D/Vector3.h" +#include "G3D/CoordinateFrame.h" +#include "G3D/SmallArray.h" +#include "G3D/constants.h" +#include "G3D/Image1.h" + +#ifdef G3D_WIN32 +// Turn off "conditional expression is constant" warning; MSVC generates this +// for debug assertions in inlined methods. +#pragma warning (disable : 4127) +#endif + +namespace G3D { + +/** + Indexed mesh algorithms. You have to build your own mesh class. +

+ No mesh class is provided with G3D because there isn't an "ideal" + mesh format-- one application needs keyframed animation, another + skeletal animation, a third texture coordinates, a fourth + cannot precompute information, etc. Instead of compromising, this + class implements the hard parts of mesh computation and you can write + your own ideal mesh class on top of it. + + \sa G3D::ArticulatedModel, G3D::IFSModel + */ +class MeshAlg { +public: + + /** \deprecated */ + typedef PrimitiveType Primitive; + + /** Adjacency information for a vertex. + Does not contain the vertex position or normal, + which are stored in the MeshAlg::Geometry object. + Vertexs must be stored in an array + parallel to (indexed in the same way as) + MeshAlg::Geometry::vertexArray. + */ + class Vertex { + public: + Vertex() {} + + /** + Array of edges adjacent to this vertex. + Let e = edgeIndex[i]. + edge[(e >= 0) ? e : ~e].vertexIndex[0] == this + vertex index. + + Edges may be listed multiple times if they are + degenerate. + */ + SmallArray edgeIndex; + + /** + Returns true if e or ~e is in the edgeIndex list. + */ + inline bool inEdge(int e) const { + return edgeIndex.contains(~e) || edgeIndex.contains(e); + } + + /** + Array of faces containing this vertex. Faces + may be listed multiple times if they are degenerate. + */ + SmallArray faceIndex; + + inline bool inFace(int f) const { + debugAssert(f >= 0); + return faceIndex.contains(f); + } + }; + + + /** + Oriented, indexed triangle. + */ + class Face { + public: + Face(); + + /** + Used by Edge::faceIndex to indicate a missing face. + This is a large negative value. + */ + static const int NONE; + + + /** + Vertices in the face in counter-clockwise order. + Degenerate faces may include the same vertex multiple times. + */ + int vertexIndex[3]; + + inline bool containsVertex(int v) const { + return contains(vertexIndex, 3, v); + } + + /** + Edge indices in counter-clockwise order. Edges are + undirected, so it is important to know which way + each edge is pointing in a face. This is encoded + using negative indices. + + If edgeIndex[i] >= 0 then this face + contains the directed edge + between vertex indices + edgeArray[face.edgeIndex[i]].vertexIndex[0] + and + edgeArray[face.edgeIndex[i]].vertexIndex[1]. + + If edgeIndex[i] < 0 then + ~edgeIndex[i] (i.e. the two's + complement of) is used and this face contains the directed + edge between vertex indices + edgeArray[~face.edgeIndex[i]].vertexIndex[0] + and + edgeArray[~face.edgeIndex[i]].vertexIndex[1]. + + Degenerate faces may include the same edge multiple times. + */ + // Temporarily takes on the value Face::NONE during adjacency + // computation to indicate an edge that has not yet been assigned. + int edgeIndex[3]; + + inline bool containsEdge(int e) const { + if (e < 0) { + e = ~e; + } + return contains(edgeIndex, 3, e) || contains(edgeIndex, 3, ~e); + } + + /** Contains the forward edge e if e >= 0 and the backward edge + ~e otherwise. */ + inline bool containsDirectedEdge(int e) const { + return contains(edgeIndex, 3, e); + } + }; + + + /** Oriented, indexed edge */ + class Edge { + public: + Edge(); + + /** Degenerate edges may include the same vertex times. */ + int vertexIndex[2]; + + inline bool containsVertex(int v) const { + return contains(vertexIndex, 2, v); + } + + /** + The edge is directed forward in face 0 + backward in face 1. Face index of MeshAlg::Face::NONE + indicates a boundary (a.k.a. crack, broken) edge. + */ + int faceIndex[2]; + + /** Returns true if f is contained in the faceIndex array in either slot. + To see if it is forward in that face, just check edge.faceIndex[0] == f.*/ + inline bool inFace(int f) const { + return contains(faceIndex, 2, f); + } + + /** + Returns true if either faceIndex is NONE. + */ + inline bool boundary() const { + return (faceIndex[0] == Face::NONE) || + (faceIndex[1] == Face::NONE); + } + + /** + Returns the reversed edge. + */ + inline Edge reverse() const { + Edge e; + e.vertexIndex[0] = vertexIndex[1]; + e.vertexIndex[1] = vertexIndex[0]; + e.faceIndex[0] = faceIndex[1]; + e.faceIndex[1] = faceIndex[0]; + return e; + } + }; + + + /** + Convenient for passing around the per-vertex data that changes under + animation. The faces and edges are needed to interpret + these values. + */ + class Geometry { + public: + /** Vertex positions */ + Array vertexArray; + + /** Vertex normals */ + Array normalArray; + + /** + Assignment is optimized using SSE. + */ + Geometry& operator=(const Geometry& src); + + void clear() { + vertexArray.clear(); + normalArray.clear(); + } + }; + + /** + Given a set of vertices and a set of indices for traversing them + to create triangles, computes other mesh properties. + + Colocated vertices are treated as separate. To have + colocated vertices collapsed (necessary for many algorithms, + like shadowing), weld the mesh before computing adjacency. + + Recent change: In version 6.00, colocated vertices were automatically + welded by this routine and degenerate faces and edges were removed. That + is no longer the case. + + Where two faces meet, there are two opposite directed edges. These + are collapsed into a single bidirectional edge in the edgeArray. + If four faces meet exactly at the same edge, that edge will appear + twice in the array, and so on. If an edge is a boundary of the mesh + (i.e. if the edge has only one adjacent face) it will appear in the + array with one face index set to MeshAlg::Face::NONE. + + @param vertexGeometry %Vertex positions to use when deciding colocation. + @param indexArray Order to traverse vertices to make triangles + @param faceArray Output + @param edgeArray Output. Sorted so that boundary edges are at the end of the array. + @param vertexArray Output + */ + static void computeAdjacency( + const Array& vertexGeometry, + const Array& indexArray, + Array& faceArray, + Array& edgeArray, + Array& vertexArray); + + /** + @deprecated Use the other version of computeAdjacency, which takes Array. + @param facesAdjacentToVertex Output adjacentFaceArray[v] is an array of + indices for faces touching vertex index v + */ + static void computeAdjacency( + const Array& vertexArray, + const Array& indexArray, + Array& faceArray, + Array& edgeArray, + Array< Array >& facesAdjacentToVertex); + + /** + Computes some basic mesh statistics including: min, max mean and median, + edge lengths; and min, mean, median, and max face area. + + @param vertexArray %Vertex positions to use when deciding colocation. + @param indexArray Order to traverse vertices to make triangles + @param minEdgeLength Minimum edge length + @param meanEdgeLength Mean edge length + @param medianEdgeLength Median edge length + @param maxEdgeLength Max edge length + @param minFaceArea Minimum face area + @param meanFaceArea Mean face area + @param medianFaceArea Median face area + @param maxFaceArea Max face area + */ + static void computeAreaStatistics( + const Array& vertexArray, + const Array& indexArray, + double& minEdgeLength, + double& meanEdgeLength, + double& medianEdgeLength, + double& maxEdgeLength, + double& minFaceArea, + double& meanFaceArea, + double& medianFaceArea, + double& maxFaceArea); + +private: + + /** Helper for weldAdjacency */ + static void weldBoundaryEdges( + Array& faceArray, + Array& edgeArray, + Array& vertexArray); + +public: + + /** + Computes tangent and binormal vectors, + which provide a (mostly) consistent + parameterization over the surface for + effects like bump mapping. In the resulting coordinate frame, + T = x (varies with texture s coordinate), B = y (varies with negative texture t coordinate), + and N = z for a right-handed coordinate frame. If a billboard is vertical on the screen + in view of the camera, the tangent space matches the camera's coordinate frame. + + The vertex, texCoord, tangent, and binormal + arrays are parallel arrays. + + The resulting tangent and binormal might not be exactly + perpendicular to each other. They are guaranteed to + be perpendicular to the normal. + + @cite Max McGuire + */ + static void computeTangentSpaceBasis( + const Array& vertexArray, + const Array& texCoordArray, + const Array& vertexNormalArray, + const Array& faceArray, + Array& tangent, + Array& binormal); + + /** @deprecated */ + static void computeNormals( + const Array& vertexArray, + const Array& faceArray, + const Array< Array >& adjacentFaceArray, + Array& vertexNormalArray, + Array& faceNormalArray); + + /** + Vertex normals are weighted by the area of adjacent faces. + Nelson Max showed this is superior to uniform weighting for + general meshes in jgt. + + @param vertexNormalArray Output. Unit length + @param faceNormalArray Output. Degenerate faces produce zero magnitude normals. Unit length + @see weld + */ + static void computeNormals( + const Array& vertexGeometry, + const Array& faceArray, + const Array& vertexArray, + Array& vertexNormalArray, + Array& faceNormalArray); + + /** Computes unit length normals in place using the other computeNormals methods. + If you already have a face array use another method; it will be faster. + @see weld*/ + static void computeNormals( + Geometry& geometry, + const Array& indexArray); + + /** + Computes face normals only. Significantly faster (especially if + normalize is false) than computeNormals. + @see weld + */ + static void computeFaceNormals( + const Array& vertexArray, + const Array& faceArray, + Array& faceNormals, + bool normalize = true); + + /** + Classifies each face as a backface or a front face relative + to the observer point P (which is at infinity when P.w = 0). + A face with normal exactly perpendicular to the observer vector + may be classified as either a front or a back face arbitrarily. + */ + static void identifyBackfaces( + const Array& vertexArray, + const Array& faceArray, + const Vector4& P, + Array& backface); + + /** A faster version of identifyBackfaces for the case where + face normals have already been computed */ + static void identifyBackfaces( + const Array& vertexArray, + const Array& faceArray, + const Vector4& P, + Array& backface, + const Array& faceNormals); + + /** + Welds nearby and colocated elements of the oldVertexArray together so that + newVertexArray contains no vertices within radius of one another. + Every vertex in newVertexPositions also appears in oldVertexPositions. + This is useful for downsampling meshes and welding cracks created by artist errors + or numerical imprecision. + + The two integer arrays map indices back and forth between the arrays according to: +

+     oldVertexArray[toOld[ni]] == newVertexArray[ni]
+     oldVertexArray[oi] == newVertexArray[toNew[ni]]
+     
+ + Note that newVertexPositions is never longer than oldVertexPositions + and is shorter when vertices are welded. + + Welding with a large radius will effectively compute a lower level of detail for + the mesh. + + The welding method runs in roughly linear time in the length of oldVertexArray-- + a uniform spatial grid is used to achieve nearly constant time vertex collapses + for uniformly distributed vertices. + + It is sometimes desirable to keep the original vertex ordering but + identify the unique vertices. The following code computes + array canonical s.t. canonical[v] = first occurance of + a vertex near oldVertexPositions[v] in oldVertexPositions. + +
+        Array canonical(oldVertexPositions.size()), toNew, toOld;
+        computeWeld(oldVertexPositions, Array(), toNew, toOld, radius);
+        for (int v = 0; v < canonical.size(); ++v) {
+            canonical[v] = toOld[toNew[v]];
+        }
+     
+ + See also G3D::MeshAlg::weldAdjacency. + + @cite The method is that described as the 'Grouper' in Baum, Mann, Smith, and Winget, + Making Radiosity Usable: Automatic Preprocessing and Meshing Techniques for + the Generation of Accurate Radiosity Solutions, Computer Graphics vol 25, no 4, July 1991. + + @deprecated Use weld. + */ + static void computeWeld( + const Array& oldVertexPositions, + Array& newVertexPositions, + Array& toNew, + Array& toOld, + double radius = fuzzyEpsilon); + + /** + Modifies the face, edge, and vertex arrays in place so that + colocated (within radius) vertices are treated as identical. + Note that the vertexArray and corresponding geometry will + contain elements that are no longer used. In the vertexArray, + these elements are initialized to MeshAlg::Vertex() but not + removed (because removal would change the indexing). + + This is a good preprocessing step for algorithms that are only + concerned with the shape of a mesh (e.g. cartoon rendering, fur, shadows) + and not the indexing of the vertices. + + Use this method when you have already computed adjacency information + and want to collapse colocated vertices within that data without + disturbing the actual mesh vertices or indexing scheme. + + If you have not computed adjacency already, use MeshAlg::computeWeld + instead and compute adjacency information after welding. + + @deprecated Use weld. + + @param faceArray Mutated in place. Size is maintained (degenerate + faces are not removed). + @param edgeArray Mutated in place. May shrink if boundary edges + are welded together. + @param vertexArray Mutated in place. Size is maintained (duplicate + vertices contain no adjacency info). + */ + static void weldAdjacency( + const Array& originalGeometry, + Array& faceArray, + Array& edgeArray, + Array& vertexArray, + double radius = fuzzyEpsilon); + + + /** + Counts the number of edges (in an edge array returned from + MeshAlg::computeAdjacency) that have only one adjacent face. + */ + static int countBoundaryEdges(const Array& edgeArray); + + + /** + Generates an array of integers from start to start + n - 1 that have run numbers + in series then omit the next skip before the next run. Useful for turning + a triangle list into an indexed face set. + + Example: +
+       createIndexArray(10, x);
+       // x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
+
+       createIndexArray(5, x, 2);
+       // x = [2, 3, 4, 5, 6, 7] 
+
+       createIndexArray(6, x, 0, 2, 1);
+       // x = [0, 1, 3, 4, 6, 7]
+     
+ */ + static void createIndexArray( + int n, + Array& array, + int start = 0, + int run = 1, + int skip = 0); + + /** + Computes a conservative, near-optimal axis aligned bounding box and sphere. + + @cite The bounding sphere uses the method from J. Ritter. An effcient bounding sphere. In Andrew S. Glassner, editor, Graphics Gems. Academic Press, Boston, MA, 1990. + + */ + static void computeBounds(const Array& vertex, class AABox& box, class Sphere& sphere); + + /** Computes bounds for a subset of the vertices. It is ok if vertices appear more than once in the index array. */ + static void computeBounds(const Array& vertex, const Array& index, class AABox& box, class Sphere& sphere); + + /** + In debug mode, asserts that the adjacency references between the + face, edge, and vertex array are consistent. + */ + static void debugCheckConsistency( + const Array& faceArray, + const Array& edgeArray, + const Array& vertexArray); + + /** + Generates a unit square in the X-Z plane composed of a grid of wCells x hCells + squares and then transforms it by xform. + + @param vertex Output vertices + @param texCoord Output texture coordinates + @param index Output triangle list indices + @param textureScale Lower-right texture coordinate + @param spaceCentered If true, the coordinates generated are centered at the origin before the transformation. + @param twoSided If true, matching top and bottom planes are generated. + \param elevation If non-NULL, values from this image are used as elevations. Apply an \a xform to adjust the scale + */ + static void generateGrid( + Array& vertex, + Array& texCoord, + Array& index, + int wCells = 10, + int hCells = 10, + const Vector2& textureScale = Vector2(1,1), + bool spaceCentered = true, + bool twoSided = true, + const CoordinateFrame& xform = CoordinateFrame(), + const Image1::Ref& elevation = NULL); + + /** Converts quadlist (QUADS), + triangle fan (TRIANGLE_FAN), + tristrip(TRIANGLE_STRIP), and quadstrip (QUAD_STRIP) indices into + triangle list (TRIANGLES) indices and appends them to outIndices. */ + template + static void toIndexedTriList( + const Array& inIndices, + MeshAlg::Primitive inType, + Array& outIndices) { + + debugAssert( + inType == PrimitiveType::TRIANGLE_STRIP || + inType == PrimitiveType::TRIANGLE_FAN || + inType == PrimitiveType::QUADS || + inType == PrimitiveType::QUAD_STRIP); + + const int inSize = inIndices.size(); + + switch(inType) { + case PrimitiveType::TRIANGLE_FAN: + { + debugAssert(inSize >= 3); + + int N = outIndices.size(); + outIndices.resize(N + (inSize - 2) * 3); + + for (IndexType i = 1, outIndex = N; i <= (inSize - 2); ++i, outIndex += 3) { + outIndices[outIndex] = inIndices[0]; + outIndices[outIndex + 1] = inIndices[i]; + outIndices[outIndex + 2] = inIndices[i + 1]; + } + + break; + } + + case PrimitiveType::TRIANGLE_STRIP: + { + debugAssert(inSize >= 3); + + int N = outIndices.size(); + outIndices.resize(N + (inSize - 2) * 3); + + bool atEven = false; + for (IndexType i = 0, outIndex = N; i <= (inSize - 2); ++i, outIndex += 3) { + if (atEven) { + outIndices[outIndex] = inIndices[i + 1]; + outIndices[outIndex + 1] = inIndices[i]; + outIndices[outIndex + 2] = inIndices[i + 2]; + atEven = false; + } else { + outIndices[outIndex] = inIndices[i]; + outIndices[outIndex + 1] = inIndices[i + 1]; + outIndices[outIndex + 2] = inIndices[i + 2]; + atEven = true; + } + } + + break; + } + + case PrimitiveType::QUADS: + { + debugAssert(inIndices.size() >= 4); + + int N = outIndices.size(); + outIndices.resize(N + (inSize / 4) * 3); + + for (IndexType i = 0, outIndex = N; i <= (inSize - 4); i += 4, outIndex += 6) { + outIndices[outIndex] = inIndices[i]; + outIndices[outIndex + 1] = inIndices[i + 1]; + outIndices[outIndex + 2] = inIndices[i + 3]; + outIndices[outIndex + 3] = inIndices[i + 1]; + outIndices[outIndex + 4] = inIndices[i + 2]; + outIndices[outIndex + 5] = inIndices[i + 3]; + } + + break; + } + + case PrimitiveType::QUAD_STRIP: + { + debugAssert(inIndices.size() >= 4); + + int N = outIndices.size(); + outIndices.resize(N + (inSize - 2) * 3); + + for (IndexType i = 0, outIndex = N; i <= (inSize - 2); i += 2, outIndex += 6) { + outIndices[outIndex] = inIndices[i]; + outIndices[outIndex + 1] = inIndices[i + 1]; + outIndices[outIndex + 2] = inIndices[i + 2]; + outIndices[outIndex + 3] = inIndices[i + 2]; + outIndices[outIndex + 4] = inIndices[i + 1]; + outIndices[outIndex + 5] = inIndices[i + 3]; + } + break; + } + default: + alwaysAssertM(false, "Illegal argument"); + } + } + +protected: + + /** + Helper for computeAdjacency. If a directed edge with index e already + exists from i0 to i1 then e is returned. If a directed edge with index e + already exists from i1 to i0, ~e is returned (the complement) and + edgeArray[e] is set to f. Otherwise, a new edge is created from i0 to i1 + with first face index f and its index is returned. + + @param vertexArray Vertex positions to use when deciding colocation. + + @param area Area of face f. When multiple edges of the same direction + are found between the same vertices (usually because of degenerate edges) + the face with larger area is kept in the edge table. + */ + static int findEdgeIndex( + const Array& vertexArray, + Array& geometricEdgeArray, + int i0, int i1, int f, double area); +}; +} +#endif + diff --git a/dep/g3dlite/G3D/MeshBuilder.h b/dep/g3dlite/G3D/MeshBuilder.h new file mode 100644 index 00000000000..9920d59d7d3 --- /dev/null +++ b/dep/g3dlite/G3D/MeshBuilder.h @@ -0,0 +1,82 @@ +/** + @file MeshBuilder.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2002-02-27 + @edited 2004-10-04 + */ +#ifndef G3D_MESHBUILDER_H +#define G3D_MESHBUILDER_H + +#include "G3D/platform.h" +#include "G3D/Array.h" +#include "G3D/Vector3.h" +#include "G3D/Triangle.h" + +namespace G3D { + +/** + Allows creation of optimized watertight meshes from unoptimized polygon soups. + See also G3D::MeshAlg for algorithms that operate on the output. + */ +class MeshBuilder { +public: + + /** + Set setWeldRadius to AUTO_WELD to weld vertices closer than 1/2 + the smallest edge length in a model. + */ + enum {AUTO_WELD = -100}; + +private: + /** Indices of vertices in or near a grid cell. */ + typedef Array List; + + std::string name; + + /** + All of the triangles, as a long triangle list. + */ + Array triList; + + void centerTriList(); + void computeBounds(Vector3& min, Vector3& max); + + bool _twoSided; + + /** Collapse radius */ + double close; + +public: + + inline MeshBuilder(bool twoSided = false) : _twoSided(twoSided), close(AUTO_WELD) {} + + /** Writes the model to the arrays, which can then be used with + G3D::IFSModel::save and G3D::MeshAlg */ + void commit(std::string& name, Array& indexArray, Array& vertexArray); + + /** + Adds a new triangle to the model. (Counter clockwise) + */ + void addTriangle(const Vector3& a, const Vector3& b, const Vector3& c); + + /** + Adds two new triangles to the model. (Counter clockwise) + */ + void addQuad(const Vector3& a, const Vector3& b, const Vector3& c, const Vector3& d); + + void addTriangle(const Triangle& t); + + void setName(const std::string& n); + + /** Vertices within this distance are considered identical. + Use AUTO_WELD (the default) to have the distance be a function of the model size.*/ + void setWeldRadius(double r) { + close = r; + } +}; + +} // namespace + +#endif diff --git a/dep/g3dlite/G3D/NetAddress.h b/dep/g3dlite/G3D/NetAddress.h new file mode 100644 index 00000000000..8ed20a06690 --- /dev/null +++ b/dep/g3dlite/G3D/NetAddress.h @@ -0,0 +1,132 @@ +#ifndef G3D_NETADDRESS_H +#define G3D_NETADDRESS_H + +#include "G3D/platform.h" +#include "G3D/Table.h" + +/** These control the version of Winsock used by G3D. + Version 2.0 is standard for G3D 6.09 and later. + Version 1.1 is standard for G3D 6.08 and earlier. + */ +#define G3D_WINSOCK_MAJOR_VERSION 2 +#define G3D_WINSOCK_MINOR_VERSION 0 + +#ifdef G3D_WIN32 +# if (G3D_WINSOCK_MAJOR_VERSION == 2) +# include +# elif (G3D_WINSOCK_MAJOR_VERSION == 1) +# include +# endif +#else +# include +# include +# include +# ifndef SOCKADDR_IN +# define SOCKADDR_IN struct sockaddr_in +# endif +# ifndef SOCKET +# define SOCKET int +# endif +#endif + +#include "G3D/g3dmath.h" + +namespace G3D { + +class NetAddress { +private: + friend class NetworkDevice; + friend class LightweightConduit; + friend class ReliableConduit; + + /** Host byte order */ + void init(uint32 host, uint16 port); + void init(const std::string& hostname, uint16 port); + NetAddress(const SOCKADDR_IN& a); + NetAddress(const struct in_addr& addr, uint16 port = 0); + + SOCKADDR_IN addr; + +public: + /** + In host byte order + */ + NetAddress(uint32 host, uint16 port = 0); + + /** + @param port Specified in host byte order (i.e., don't worry about endian issues) + */ + NetAddress(const std::string& hostname, uint16 port); + + /** + @param hostnameAndPort in the form "hostname:port" or "ip:port" + */ + NetAddress(const std::string& hostnameAndPort); + + /** + @deprecated Use G3D::NetworkDevice::broadcastAddressArray() + + @brief Creates a UDP broadcast address for use with a + G3D::LightweightConduit. + + UDP broadcast allows one machine to send a packet to all machines + on the same local network. The IP portion of the address is + 0xFFFFFFFF, which indicates "broadcast" to the underlying socket + API. This feature is not available with the connection-based TCP + protocol abstracted by G3D::ReliableConduit; use multisend + instead. + */ + static NetAddress broadcastAddress(uint16 port); + + NetAddress(); + + void serialize(class BinaryOutput& b) const; + void deserialize(class BinaryInput& b); + + /** @brief Returns true if this is not an illegal address. */ + bool ok() const; + + /** @brief Returns a value in host format (i.e., don't worry about + endian issues) */ + inline uint32 ip() const { + return ntohl(addr.sin_addr.s_addr); + //return ntohl(addr.sin_addr.S_un.S_addr); + } + + inline uint16 port() const { + return ntohs(addr.sin_port); + } + + std::string ipString() const; + std::string toString() const; + +}; + +std::ostream& operator<<(std::ostream& os, const NetAddress&); + +} // namespace G3D + +template <> struct HashTrait { + static size_t hashCode(const G3D::NetAddress& key) { + return static_cast(key.ip() + (static_cast(key.port()) << 16)); + } +}; + +namespace G3D { + +/** + Two addresses may point to the same computer but be != because + they have different IP's. + */ +inline bool operator==(const NetAddress& a, const NetAddress& b) { + return (a.ip() == b.ip()) && (a.port() == b.port()); +} + + +inline bool operator!=(const NetAddress& a, const NetAddress& b) { + return !(a == b); +} + +} // namespace G3D + +#endif diff --git a/dep/g3dlite/G3D/NetworkDevice.h b/dep/g3dlite/G3D/NetworkDevice.h new file mode 100644 index 00000000000..ea3290cbc09 --- /dev/null +++ b/dep/g3dlite/G3D/NetworkDevice.h @@ -0,0 +1,738 @@ +/** + @file NetworkDevice.h + + These classes abstract networking from the socket level to a + serialized messaging style that is more appropriate for games. The + performance has been tuned for sending many small messages. The + message protocol contains a header that prevents them from being used + with raw UDP/TCP (e.g. connecting to an HTTP server). + + LightweightConduit and ReliableConduits have different interfaces + because they have different semantics. You would never want to + interchange them without rewriting the surrounding code. + + NetworkDevice creates conduits because they need access to a global + log pointer and because I don't want non-reference counted conduits + being created. + + Be careful with threads and reference counting. The reference + counters are not threadsafe, and are also not updated correctly if a + thread is explicitly killed. Since the conduits will be passed by + const XConduitRef& most of the time this doesn't appear as a major + problem. With non-blocking conduits, you should need few threads + anyway. + + LightweightConduits preceed each message with a 4-byte host order + unsigned integer that is the message type. This does not appear in + the message serialization/deserialization. + + ReliableConduits preceed each message with two 4-byte host order + unsigned integers. The first is the message type and the second + indicates the length of the rest of the data. The size does not + include the size of the header itself. The minimum message is 9 + bytes:a 4-byte type, a 4-byte header equal to "1", and one byte of data. + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + @created 2002-11-22 + @edited 2006-11-25 + */ + +#ifndef G3D_NETWORKDEVICE_H +#define G3D_NETWORKDEVICE_H + +#include "G3D/platform.h" +#include "G3D/NetAddress.h" + +#include +#include +#include "G3D/g3dmath.h" + +#include "G3D/ReferenceCount.h" +#include "G3D/Array.h" +#include "G3D/BinaryOutput.h" + +namespace G3D { + +class TextOutput; + +class Conduit : public ReferenceCountedObject { +protected: + friend class NetworkDevice; + friend class NetListener; + + uint64 mSent; + uint64 mReceived; + uint64 bSent; + uint64 bReceived; + + SOCKET sock; + + /** + Used for serialization. One per socket + to make this threadsafe. + */ + BinaryOutput binaryOutput; + + Conduit(); + +public: + + virtual ~Conduit(); + uint64 bytesSent() const; + uint64 messagesSent() const; + uint64 bytesReceived() const; + uint64 messagesReceived() const; + + /** + If true, receive will return true. + */ + virtual bool messageWaiting(); + + /** + Returns the type of the waiting message (i.e. the type supplied + with send). The return value is zero when there is no message + waiting. + + One way to use this is to have a Table mapping message types to + pre-allocated subclasses so receiving looks like: + +
+         // My base class for messages.
+         class Message {
+             virtual void serialize(BinaryOutput&) const;
+             virtual void deserialize(BinaryInput&);
+             virtual void process() = 0;
+         };
+
+         Message* m = table[conduit->waitingMessageType()];
+         conduit->receive(m);
+         m->process();
+     
+ + Another is to simply switch on the message type: + +
+         switch (conduit->waitingMessageType()) {
+         case 0:
+            // No message
+            break;
+
+         case ENTITY_SPAWN_MSG:
+            {
+               EntitySpawnMsg m;
+               condiut->receive(m);
+               spawnEntity(m.id, m.position, m.modelID);
+            }
+            break;
+            ...
+         }
+      
+ */ + virtual uint32 waitingMessageType() = 0; + + /** Returns true if the connection is ok. */ + bool ok() const; +}; + +typedef ReferenceCountedPointer ReliableConduitRef; + +#ifdef __GNUC__ +// Workaround for a known bug in gcc 4.x where htonl produces +// a spurrious warning. +// http://gcc.gnu.org/ml/gcc-bugs/2005-10/msg03270.html +uint32 gcchtonl(uint32); +#endif + +// Messaging and stream APIs must be supported on a single class because +// sometimes an application will switch modes on a single socket. For +// example, when transferring 3D level geometry during handshaking with +// a game server. +/** + A conduit that guarantees messages will arrive, intact and in order. + Create on the client using NetworkDevice::createReliableConduit and + on the server using NetListener::waitForConnection. Set the reference + counted pointer to NULL to disconnect. + + To construct a ReliableConduit: +
    +
  1. Create a G3D::NetworkDevice (if you are using G3D::GApp, it creates + one for you) on the client and on the server. +
  2. On the server, create a G3D::NetListener using + G3D::NetworkDevice::createListener +
  3. On the server, invoke G3D::NetListener::waitForConnection. +
  4. On the client, call G3D::NetworkDevice::createReliableConduit. + You will need the server's G3D::NetAddress. Consider using + G3D::Discovery::Client to find it via broadcasting. +
+ + */ +class ReliableConduit : public Conduit { +private: + friend class NetworkDevice; + friend class NetListener; + + enum State {RECEIVING, HOLDING, NO_MESSAGE} state; + + NetAddress addr; + + /** + Type of the incoming message. + */ + uint32 messageType; + + /** + Total size of the incoming message (read from the header). + */ + uint32 messageSize; + + /** Shared buffer for receiving messages. */ + void* receiveBuffer; + + /** Total size of the receiveBuffer. */ + size_t receiveBufferTotalSize; + + /** Size occupied by the current message... so far. This will be + equal to messageSize when the whole message has arrived. + */ + size_t receiveBufferUsedSize; + + ReliableConduit(const NetAddress& addr); + + ReliableConduit(const SOCKET& sock, + const NetAddress& addr); + + template static void serializeMessage + (uint32 t, const T& m, BinaryOutput& b) { + + b.writeUInt32(t); + + // Reserve space for the 4 byte size header + b.writeUInt32(0); + + size_t L = b.length(); + m.serialize(b); + if ((size_t)b.length() == L) { + // No data was created by serialization. + // We need to send at least one byte because receive assumes that + // a zero length message is an error. + b.writeUInt8(0xFF); + } + + uint32 len = b.size() - 8; + + // We send the length first to tell recv how much data to read. + // Here we abuse BinaryOutput a bit and write directly into + // its buffer, violating the abstraction. + // Note that we write to the second set of 4 bytes, which is + // the size field. + uint32* lenPtr = ((uint32*)b.getCArray()) + 1; + #if defined(__GNUC__) + *lenPtr = gcchtonl(len); + #else + *lenPtr = htonl(len); + #endif + } + + + void sendBuffer(const BinaryOutput& b); + + /** Accumulates whatever part of the message (not the header) is + still waiting on the socket into the receiveBuffer during + state = RECEIVING mode. Closes the socket if anything goes + wrong. When receiveBufferUsedSize == messageSize, the entire + message has arrived. */ + void receiveIntoBuffer(); + + /** Receives the messageType and messageSize from the socket. */ + void receiveHeader(); + +public: + + /** + Client invokes this to connect to a server. The call blocks until the + conduit is opened. The conduit will not be ok() if it fails. + */ + static ReliableConduitRef create(const NetAddress& address); + + /** Closes the socket. */ + ~ReliableConduit(); + + + // The message is actually copied from the socket to an internal buffer during + // this call. Receive only deserializes. + virtual bool messageWaiting(); + + /** + Serializes the message and schedules it to be sent as soon as possible, + and then returns immediately. The message can be any class with + a serialize and deserialize method. On the receiving side, + use G3D::ReliableConduit::waitingMessageType() to detect the incoming + message and then invoke G3D::ReliableConduit::receive(msg) where msg + is of the same class as the message that was sent. + + The actual data sent across the network is preceeded by the + message type and the size of the serialized message as a 32-bit + integer. The size is sent because TCP is a stream protocol and + doesn't have a concept of discrete messages. + */ + template inline void send(uint32 type, const T& message) { + binaryOutput.reset(); + serializeMessage(type, message, binaryOutput); + sendBuffer(binaryOutput); + } + + /** Sends an empty message with the given type. Useful for sending + commands that have no parameters. */ + void send(uint32 type); + + /** Send the same message to a number of conduits. Useful for sending + data from a server to many clients (only serializes once). */ + template + inline static void multisend( + const Array& array, + uint32 type, + const T& m) { + + if (array.size() > 0) { + array[0]->binaryOutput.reset(); + serializeMessage(type, m, array[0]->binaryOutput); + + for (int i = 0; i < array.size(); ++i) { + array[i]->sendBuffer(array[0]->binaryOutput); + } + } + } + + virtual uint32 waitingMessageType(); + + /** + If a message is waiting, deserializes the waiting message into + message and returns true, otherwise returns false. You can + determine the type of the message (and therefore, the class + of message) using G3D::ReliableConduit::waitingMessageType(). + */ + template inline bool receive(T& message) { + if (! messageWaiting()) { + return false; + } + + debugAssert(state == HOLDING); + // Deserialize + BinaryInput b((uint8*)receiveBuffer, receiveBufferUsedSize, G3D_LITTLE_ENDIAN, BinaryInput::NO_COPY); + message.deserialize(b); + + // Don't let anyone read this message again. We leave the buffer + // allocated for the next caller, however. + receiveBufferUsedSize = 0; + state = NO_MESSAGE; + messageType = 0; + messageSize = 0; + + // Potentially read the next message. + messageWaiting(); + + return true; + } + + /** Removes the current message from the queue. */ + inline void receive() { + if (! messageWaiting()) { + return; + } + receiveBufferUsedSize = 0; + state = NO_MESSAGE; + messageType = 0; + messageSize = 0; + + // Potentially read the next message. + messageWaiting(); + } + + NetAddress address() const; +}; + + +typedef ReferenceCountedPointer LightweightConduitRef; + +/** + Provides fast but unreliable transfer of messages. On a LAN, + LightweightConduit will probably never drop messages but you + might get your messages out of order. On an internet + connection it might drop messages altogether. Messages are never + corrupted, however. LightweightConduit requires a little less setup + and overhead than ReliableConduit. ReliableConduit guarantees + message delivery and order but requires a persistent connection. + + To set up a LightweightConduit (assuming you have already made + subclasses of G3D::NetMessage based on your application's + pcommunication protocol): + +[Server Side] +
    +
  1. Call LightweightConduit::create(port, true, false), +where port is the port on which you will receive messages. + +
  2. Poll LightweightConduit::messageWaiting from your main loop. When +it is true (or, equivalently, when LightweightConduit::waitingMessageType +is non-zero) there is an incoming message. + +
  3. To read the incoming message, call LightweightConduit::receive with +the appropriate class type, which mist have a deserialize method. +LightweightConduit::waitingMessageType tells you what class is +needed (you make up your own message constants for your program; numbers +under 1000 are reserved for G3D's internal use). + +
  4. When done, simply set the G3D::LightweightConduitRef to NULL or let +it go out of scope and the conduit cleans itself up automatically. +
+ +[Client Side] +
    +
  1. Call G3D::LightweightConduit::create(). If you will +broadcast to all servers on a LAN, set the third optional argument to +true (the default is false for no broadcast). You can also set up the +receive port as if it was a server to send and receive from a single +LightweightConduit. + +
  2. To send, call G3D::LightweightConduit::send with the target address +and a pointer to an instance of the message you want to send. + +
  3. When done, simply set the G3D::LightweightConduitRef to NULL or let +it go out of scope and the conduit cleans itself up automatically. + +
+ */ +class LightweightConduit : public Conduit { +private: + friend class NetworkDevice; + + /** + True when waitingForMessageType has read the message + from the network into messageType/messageStream. + */ + bool alreadyReadMessage; + + /** + Origin of the received message. + */ + NetAddress messageSender; + + /** + The type of the last message received. + */ + uint32 messageType; + + /** + The message received (the type has already been read off). + */ + Array messageBuffer; + + LightweightConduit(uint16 receivePort, bool enableReceive, bool enableBroadcast); + + void sendBuffer(const NetAddress& a, BinaryOutput& b); + + /** Maximum transmission unit (packet size in bytes) for this socket. + May vary between sockets. */ + int MTU; + + + template + void serializeMessage( + uint32 type, + const T& m, + BinaryOutput& b) const { + + debugAssert(type != 0); + b.writeUInt32(type); + m.serialize(b); + b.writeUInt32(1); + + debugAssertM(b.size() < MTU, + format("This LightweightConduit is limited to messages of " + "%d bytes (Ethernet hardware limit; this is the " + "'UDP MTU')", maxMessageSize())); + + if (b.size() >= MTU) { + throw LightweightConduit::PacketSizeException( + format("This LightweightConduit is limited to messages of " + "%d bytes (Ethernet hardware limit; this is the " + "'UDP MTU')", maxMessageSize()), + b.size() - 4, // Don't count the type header + maxMessageSize()); + } + } + +public: + + static LightweightConduitRef create(uint16 receivePort, bool enableReceive, bool enableBroadcast); + + class PacketSizeException { + public: + std::string message; + int serializedPacketSize; + int maxMessageSize; + + inline PacketSizeException(const std::string& m, int s, int b) : + message(m), + serializedPacketSize(s), + maxMessageSize(b) {} + }; + + /** Closes the socket. */ + ~LightweightConduit(); + + /** The maximum length of a message that can be sent + (G3D places a small header at the front of each UDP packet; + this is already taken into account by the value returned). + */ + inline int maxMessageSize() const { + return MTU - 4; + } + + + template inline void send(const NetAddress& a, uint32 type, const T& msg) { + binaryOutput.reset(); + serializeMessage(type, msg, binaryOutput); + sendBuffer(a, binaryOutput); + } + + /** Send the same message to multiple addresses (only serializes once). + Useful when server needs to send to a known list of addresses + (unlike direct UDP broadcast to all addresses on the subnet) */ + template inline void send(const Array& a, uint32 type, const T& m) { + binaryOutput.reset(); + serializeMessage(type, m, binaryOutput); + + for (int i = 0; i < a.size(); ++i) { + sendBuffer(a[i], binaryOutput); + } + } + + bool receive(NetAddress& sender); + + template inline bool receive(NetAddress& sender, T& message) { + bool r = receive(sender); + if (r) { + BinaryInput b((messageBuffer.getCArray() + 4), + messageBuffer.size() - 4, + G3D_LITTLE_ENDIAN, BinaryInput::NO_COPY); + message.deserialize(b); + } + + return r; + } + + inline bool receive() { + static NetAddress ignore; + return receive(ignore); + } + + virtual uint32 waitingMessageType(); + + + virtual bool messageWaiting(); +}; + +/////////////////////////////////////////////////////////////////////////////// + +typedef ReferenceCountedPointer NetListenerRef; + +/** + Runs on the server listening for clients trying to make reliable connections. + */ +class NetListener : public ReferenceCountedObject { +private: + + friend class NetworkDevice; + + SOCKET sock; + + /** Port is in host byte order. */ + NetListener(uint16 port); + +public: + + static NetListenerRef create(const uint16 port); + + ~NetListener(); + + /** Block until a connection is received. Returns NULL if + something went wrong. */ + ReliableConduitRef waitForConnection(); + + /** True if a client is waiting (i.e. waitForConnection will + return immediately). */ + bool clientWaiting() const; + + bool ok() const; +}; + + +/////////////////////////////////////////////////////////////////////////////// + +/** + @brief Abstraction of network (socket) functionality. + + An abstraction over sockets that provides a message-based network + infrastructure optimized for sending many small (~500 bytes) messages. + All functions always return immediately. + + Create only one NetworkDevice per process (a WinSock restriction). + + NetworkDevice is technically not thread safe. However, as long as + you use different conduits on different threads (or lock conduits + before sending), you will encounter no problems sharing the single + NetworkDevice across multiple threads. That is, do not invoke the same + Conduit's send or receive method on two threads at once. + + This assumes that the underlying WinSock/BSD sockets implementation + is thread safe. That is not guaranteed, but in practice seems + to always be true (see + http://tangentsoft.net/wskfaq/intermediate.html#threadsafety) + +
+ + IP networks use "network byte order" (big-endian) for + communicating integers. "Host byte order" is the endian-ness of + the local machine (typically little-endian; see + System::endian). The C functions htonl() and ntohl() convert 32-bit + values between these formats. G3D only ever exposes host byte order, + so programmers rarely need to be aware of the distinction. + + */ +class NetworkDevice { +public: + + /** @brief Description of an ethernet or wireless ethernet adapter.*/ + class EthernetAdapter { + public: + /** Reverse-DNS of the ip address.*/ + std::string hostname; + + /** Name of the adapter */ + std::string name; + + /** IP address in host byte order.*/ + uint32 ip; + + /** Subnet mask in host byte order.*/ + uint32 subnet; + + /** UDP broadcast address in host byte order.*/ + uint32 broadcast; + + /** MAC (hardware) address, if known */ + uint8 mac[6]; + + EthernetAdapter(); + + /** Produces a text description of this adapter */ + void describe(TextOutput& t) const; + }; + +private: + + friend class Conduit; + friend class LightweightConduit; + friend class ReliableConduit; + friend class NetListener; + + bool initialized; + + Array m_adapterArray; + + /** Broadcast addresses available on this machine, + extracted from m_adapterArray.*/ + Array m_broadcastAddresses; + + /** Utility method. */ + void closesocket(SOCKET& sock) const; + + /** Utility method. Returns true on success.*/ + bool bind(SOCKET sock, const NetAddress& addr) const; + + /** The global instance */ + static NetworkDevice* s_instance; + + NetworkDevice(); + + bool init(); + + void _cleanup(); + + /** Called from init to update m_adapterArray and + m_broadcastAddresses. */ + void addAdapter(const EthernetAdapter& a); + +public: + + /** Prints an IP address to a string. + @param ip In host byte order.*/ + static std::string formatIP(uint32 ip); + + /** Prints a MAC address to a string. */ + static std::string formatMAC(const uint8 mac[6]); + + ~NetworkDevice(); + + /** Returns the available ethernet adapters for the current + machine that are online. Does not include the loopback adapter + for localhost.*/ + inline const Array& adapterArray() const { + return m_adapterArray; + } + + /** Returns the (unique) IP addresses for UDP broadcasting + extracted from adapterArray(). All are in host byte order. */ + inline const Array& broadcastAddressArray() const { + return m_broadcastAddresses; + } + + /** + Returns NULL if there was a problem initializing the network. + */ + static NetworkDevice* instance(); + + /** + Shuts down the network device (destroying the global instance). + */ + static void cleanup(); + + /** + Prints a human-readable description of this machine + to the text output stream. + */ + void describeSystem( + TextOutput& t); + + void describeSystem( + std::string& s); + + /** Returns the name (or one of the names) of this computer */ + std::string localHostName() const; + + /** There is often more than one address for the local host. This + returns all of them. + @deprecated Use adapterArray() + */ + void localHostAddresses(Array& array) const; +}; + + +#ifdef __GNUC__ +inline uint32 gcchtonl(uint32 x) { + // This pragma fools gcc into surpressing all error messages, + // including the bogus one that it creates for htonl +# pragma GCC system_header + return htonl(x); +} +#endif + +} // G3D namespace + +#ifndef _WIN32 +#undef SOCKADDR_IN +#undef SOCKET +#endif + +#endif diff --git a/dep/g3dlite/G3D/ParseError.h b/dep/g3dlite/G3D/ParseError.h new file mode 100644 index 00000000000..f02948e3d29 --- /dev/null +++ b/dep/g3dlite/G3D/ParseError.h @@ -0,0 +1,59 @@ +/** + @file ParseError.h + + @maintainer Morgan McGuire + + @created 2009-11-15 + @edited 2009-11-15 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ +#ifndef G3D_ParseError_h +#define G3D_ParseError_h + +#include "G3D/platform.h" +#include "G3D/g3dmath.h" +#include + +namespace G3D { + +/** Thrown by TextInput, Any, and other parsers on unexpected input. */ +class ParseError { +public: + enum {UNKNOWN = -1}; + + /** Empty means unknown */ + std::string filename; + + /** For a binary file, the location of the parse error. -1 if unknown.*/ + int64 byte; + + /** For a text file, the line number is the line number of start of token which caused the exception. 1 is + the first line of the file. -1 means unknown. Note that you can use + TextInput::Settings::startingLineNumberOffset to shift the effective line + number that is reported by that class. + */ + int line; + + /** Character number (in the line) of the start of the token which caused the + exception. 1 is the character in the line. May be -1 if unknown. + */ + int character; + + std::string message; + + ParseError() : byte(UNKNOWN), line(UNKNOWN), character(UNKNOWN) {} + + virtual ~ParseError() {} + + ParseError(const std::string& f, int l, int c, const std::string& m) : + filename (f), byte(UNKNOWN), line(l), character(c), message(m) {} + + ParseError(const std::string& f, int64 b, const std::string& m) : + filename (f), byte(b), line(UNKNOWN), character(UNKNOWN), message(m) {} +}; + +} + +#endif diff --git a/dep/g3dlite/G3D/PhysicsFrame.h b/dep/g3dlite/G3D/PhysicsFrame.h new file mode 100644 index 00000000000..a5a9305b83e --- /dev/null +++ b/dep/g3dlite/G3D/PhysicsFrame.h @@ -0,0 +1,74 @@ +/** + @file PhysicsFrame.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2002-07-08 + @edited 2006-01-10 +*/ + +#ifndef G3D_PHYSICSFRAME_H +#define G3D_PHYSICSFRAME_H + +#include "G3D/platform.h" +#include "G3D/Vector3.h" +#include "G3D/Matrix3.h" +#include "G3D/Quat.h" +#include "G3D/CoordinateFrame.h" +#include +#include + + +namespace G3D { + +/** + An RT transformation using a quaternion; suitable for + physics integration. + + This interface is in "Beta" and will change in the next release. + */ +class PhysicsFrame { +public: + + Quat rotation; + + /** + Takes object space points to world space. + */ + Vector3 translation; + + /** + Initializes to the identity frame. + */ + PhysicsFrame(); + + /** + Purely translational force + */ + PhysicsFrame(const Vector3& translation) : translation(translation) {} + + PhysicsFrame(const CoordinateFrame& coordinateFrame); + + /** Compose: create the transformation that is other followed by this.*/ + PhysicsFrame operator*(const PhysicsFrame& other) const; + + virtual ~PhysicsFrame() {} + + CoordinateFrame toCoordinateFrame() const; + + /** + Linear interpolation (spherical linear for the rotations). + */ + PhysicsFrame lerp( + const PhysicsFrame& other, + float alpha) const; + + void deserialize(class BinaryInput& b); + + void serialize(class BinaryOutput& b) const; + +}; + +} // namespace + +#endif diff --git a/dep/g3dlite/G3D/Plane.h b/dep/g3dlite/G3D/Plane.h new file mode 100644 index 00000000000..360bcd2bc75 --- /dev/null +++ b/dep/g3dlite/G3D/Plane.h @@ -0,0 +1,161 @@ +/** + @file Plane.h + + Plane class + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2001-06-02 + @edited 2004-07-18 +*/ + +#ifndef G3D_PLANE_H +#define G3D_PLANE_H + +#include "G3D/platform.h" +#include "G3D/Vector3.h" +#include "G3D/Vector4.h" +#include "G3D/debugAssert.h" + +namespace G3D { + +/** + An infinite 2D plane in 3D space. + */ +class Plane { +private: + + /** normal.Dot(x,y,z) = distance */ + Vector3 _normal; + float _distance; + + /** + Assumes the normal has unit length. + */ + Plane(const Vector3& n, float d) : _normal(n), _distance(d) { + } + +public: + + Plane() : _normal(Vector3::unitY()), _distance(0) { + } + + /** + Constructs a plane from three points. + */ + Plane( + const Vector3& point0, + const Vector3& point1, + const Vector3& point2); + + /** + Constructs a plane from three points, where at most two are + at infinity (w = 0, not xyz = inf). + */ + Plane( + Vector4 point0, + Vector4 point1, + Vector4 point2); + + /** + The normal will be unitized. + */ + Plane( + const Vector3& __normal, + const Vector3& point); + + static Plane fromEquation(float a, float b, float c, float d); + + Plane(class BinaryInput& b); + void serialize(class BinaryOutput& b) const; + void deserialize(class BinaryInput& b); + + virtual ~Plane() {} + + /** + Returns true if point is on the side the normal points to or + is in the plane. + */ + inline bool halfSpaceContains(Vector3 point) const { + // Clamp to a finite range for testing + point = point.clamp(Vector3::minFinite(), Vector3::maxFinite()); + + // We can get away with putting values *at* the limits of the float32 range into + // a dot product, since the dot product is carried out on float64. + return _normal.dot(point) >= _distance; + } + + /** + Returns true if point is on the side the normal points to or + is in the plane. + */ + inline bool halfSpaceContains(const Vector4& point) const { + if (point.w == 0) { + return _normal.dot(point.xyz()) > 0; + } else { + return halfSpaceContains(point.xyz() / point.w); + } + } + + /** + Returns true if point is on the side the normal points to or + is in the plane. Only call on finite points. Faster than halfSpaceContains. + */ + inline bool halfSpaceContainsFinite(const Vector3& point) const { + debugAssert(point.isFinite()); + return _normal.dot(point) >= _distance; + } + + /** + Returns true if the point is nearly in the plane. + */ + inline bool fuzzyContains(const Vector3 &point) const { + return fuzzyEq(point.dot(_normal), _distance); + } + + inline const Vector3& normal() const { + return _normal; + } + + /** + Returns distance from point to plane. Distance is negative if point is behind (not in plane in direction opposite normal) the plane. + */ + inline float distance(const Vector3& x) const { + return (_normal.dot(x) - _distance); + } + + inline Vector3 closestPoint(const Vector3& x) const { + return x + (_normal * (-distance(x))); + } + + /** Returns normal * distance from origin */ + Vector3 center() const { + return _normal * _distance; + } + + /** + Inverts the facing direction of the plane so the new normal + is the inverse of the old normal. + */ + void flip(); + + /** + Returns the equation in the form: + + normal.Dot(Vector3(x, y, z)) + d = 0 + */ + void getEquation(Vector3 &normal, double& d) const; + void getEquation(Vector3 &normal, float& d) const; + + /** + ax + by + cz + d = 0 + */ + void getEquation(double& a, double& b, double& c, double& d) const; + void getEquation(float& a, float& b, float& c, float& d) const; + + std::string toString() const; +}; + +} // namespace + +#endif diff --git a/dep/g3dlite/G3D/PointHashGrid.h b/dep/g3dlite/G3D/PointHashGrid.h new file mode 100644 index 00000000000..0db9e677321 --- /dev/null +++ b/dep/g3dlite/G3D/PointHashGrid.h @@ -0,0 +1,917 @@ +/** + @file PointHashGrid.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + @created 2008-07-01 + @edited 2009-05-28 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. +*/ +#ifndef G3D_PointHashGrid_h +#define G3D_PointHashGrid_h + +#include "G3D/platform.h" +#include "G3D/EqualsTrait.h" +#include "G3D/HashTrait.h" +#include "G3D/Vector3.h" +#include "G3D/Vector3int32.h" +#include "G3D/Array.h" +#include "G3D/Table.h" +#include "G3D/AABox.h" +#include "G3D/Sphere.h" +#include "G3D/SmallArray.h" + +namespace G3D { + +/** + Storage of data in a sparse 3D grid of point-based data. The + space cost for n elements is O(n). For data with + approximately uniform density (with respect to the radius hint), + the time cost of searching for neighbors is O(1). + + Value must be supported by a G3D::PositionTrait, + G3D::EqualsTrait, and G3D::HashFunc. overrides are provided for + common G3D classes like G3D::Vector3. +*/ +template, + class EqualsFunc = EqualsTrait, + class HashFunc = HashTrait > +class PointHashGrid { +private: + +#define ThisType PointHashGrid + + /** A value annotated with precomputed position and hash code.*/ + class Entry { + public: + Vector3 position; + Value value; + }; + + /** One cell of the grid. */ + typedef Array Cell; + typedef Table CellTable; + + /** The cube of +/-1 along each dimension. Initialized by initOffsetArray.*/ + Vector3int32 m_offsetArray[3*3*3]; + + /** Incremented every time the data structure is mutated. + Used by the iterators to determine if the data structure + has changed since iteration began. */ + int m_epoch; + + /** Extent of a cell along one dimension. */ + float m_cellWidth; + + /** 1.0 / cell width */ + float m_invCellWidth; + + /** Conservative bounds; the actual data may be smaller. */ + AABox m_bounds; + + /** Number of elements. */ + int m_size; + + /** Non-empty cells indexed by grid position. Actual 3D position is + position * m_cellWidth*/ + CellTable m_data; + + MemoryManager::Ref m_memoryManager; + + /** Intentionally unimplemented: prevent copy construction. */ + PointHashGrid(const ThisType&); + + + /** Intentionally unimplemented: prevent assignment. */ + PointHashGrid& operator=(const ThisType&); + + + /** Locate the cell and index within that cell containing v. Called by + remove() and contains(). */ + bool find(const Value& v, + Vector3int32& foundCellCoord, + Cell*& foundCell, + int& index) { + + Vector3 pos; + PosFunc::getPosition(v, pos); + + Vector3int32 cellCoord; + getCellCoord(pos, cellCoord); + for (int i = 0; i < 27; ++i) { + Vector3int32 c = cellCoord + m_offsetArray[i]; + Cell* cell = m_data.getPointer(c); + if (cell != NULL) { + // The cell exists + for (int j = 0; j < cell->size(); ++j) { + if (EqualsFunc::equals((*cell)[j].value, v)) { + foundCell = cell; + index = j; + foundCellCoord = c; + return true; + } + } + } + } + + // Not found + return false; + } + + /** Given a real-space position, returns the cell coord + containing it.*/ + inline void getCellCoord(const Vector3& pos, Vector3int32& cellCoord) const { + for (int a = 0; a < 3; ++a) { + cellCoord[a] = iFloor(pos[a] * m_invCellWidth); + } + } + + /** Initializes m_offsetArray. */ + void initOffsetArray() { + int i = 0; + Vector3int32 d; + for (d.x = -1; d.x <= +1; ++d.x) { + for (d.y = -1; d.y <= +1; ++d.y) { + for (d.z = -1; d.z <= +1; ++d.z) { + m_offsetArray[i] = d; + ++i; + } + } + } + + // Put (0, 0, 0) first, so that contains() is most likely to find + // the value quickly. + i = (1 * 3 + 1) * 3 + 1; + debugAssert(m_offsetArray[i] == Vector3int32(0,0,0)); + Vector3int32 temp = m_offsetArray[0]; + m_offsetArray[0] = m_offsetArray[i]; + m_offsetArray[i] = temp; + } + +public: + + /** + @param radiusHint the radius that will typically be used with + beginSphereIntersection and beginBoxIntersection. If two Values are equal, + their positions must be within this radius as well. + */ + PointHashGrid(float radiusHint, const MemoryManager::Ref& m = MemoryManager::create()) : m_size(0), m_memoryManager(m) { + initOffsetArray(); + m_data.clearAndSetMemoryManager(m_memoryManager); + + debugAssertM(radiusHint > 0, "Cell radius must be positive"); + m_cellWidth = radiusHint; + m_invCellWidth = 1.0f / m_cellWidth; + } + + /** + If radiusHint is negative, it is automatically chosen to put + about 5 values in each grid cell (which means about 27 * 5 + values for each beginIntersection call). + */ + PointHashGrid(const Array& init, float radiusHint = -1.0f, const MemoryManager::Ref& m = MemoryManager::create()) : m_size(0), m_memoryManager(m) { + initOffsetArray(); + m_data.clearAndSetMemoryManager(m_memoryManager); + + Vector3 lo(Vector3::inf()); + Vector3 hi(-lo); + + // Compute bounds + Array entry(init.size()); + for (int i = 0; i < entry.size(); ++i) { + const Value& value = init[i]; + Vector3 pos = m_posFunc(value); + + entry[i].value = value; + entry[i].hashCode = m_hashFunc(value); + entry[i].position = pos; + + lo = lo.min(pos); + hi = hi.max(pos); + } + + m_bounds = AABox(lo, hi); + + if (radiusHint <= 0) { + // Compute a good cell width based on the bounds. + // + // N numPerCell + // ----- = --------- + // volume r^3 + + float numPerCell = 5; + radiusHint = + (float)pow(numPerCell * m_bounds.volume() / init.size(), 1.0 / 3.0); + + if (radiusHint == 0) { + // Volume must have been zero because all points were colocated. + radiusHint = 0.1f; + } + } + + insert(init); + } + + /** Returns the number of elements. */ + inline int size() const { + return m_size; + } + + /** Returns a conservative bounding box around the contents. This is + conservative because it is not updated when elements are removed. */ + const AABox& conservativeBoxBounds() const { + return m_bounds; + } + + /** Insert @a v at position @a p given by getPosition(v, p). + Multiple elements that are equal may be inserted; all copies will be + in the data structure. */ + void insert(const Value& v) { + Vector3 pos; + PosFunc::getPosition(v, pos); + Vector3int32 cellCoord; + getCellCoord(pos, cellCoord); + + // See if the cell already exists + Cell& cell = m_data.getCreate(cellCoord); + + if (cell.size() == 0) { + // Use the same memory manager as for the whole class + cell.clearAndSetMemoryManager(m_memoryManager); + } + + Entry& entry = cell.next(); + entry.value = v; + entry.position = pos; + + // Update the bounds + if (size() == 0) { + m_bounds = AABox(pos); + } else { + m_bounds.merge(pos); + } + + ++m_size; + ++m_epoch; + } + + + /** Inserts all elements of the array. */ + void insert(const Array& v) { + for (int i = 0; i < v.size(); ++i) { + insert(v[i]); + } + } + + + /** If there are multiple copies of an element, you must + delete them multiple times. + + @param shrinkIfNecessary If true, deallocate underlying data + structures as they are emptied. False increases performace at + the cost of memory overhead for dynamic structures. + + @return true if the element was found. + */ + bool remove(const Value& v, bool shrinkIfNecessary = true) { + Cell* cell = NULL; + int index = 0; + Vector3int32 cellCoord; + + if (find(v, cellCoord, cell, index)) { + cell->fastRemove(index, shrinkIfNecessary); + --m_size; + ++m_epoch; + + if ((cell->size() == 0) && shrinkIfNecessary) { + // Remove the cell itself + + // Drop our pointer, which is about to dangle + cell = NULL; + bool success = m_data.remove(cellCoord); + debugAssertM(success, "Data structure corrupt: " + "tried to remove a cell that doesn't exist."); + } + + return true; + + } else { + return false; + } + } + + /** Removes all elements of @v. */ + void remove(const Array& v, bool shrink = true) { + for (int i = 0; i < v.size(); ++i) { + remove(v[i], shrink); + } + } + + /////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////// + + class Iterator { + private: + friend class ThisType; + + bool m_isEnd; + + const ThisType* m_grid; + + typename CellTable::Iterator m_tableIterator; + + /** Index within m_tableIterator->value of the current value. */ + int m_arrayIndex; + + const int m_epoch; + + /** End iterator. Note that the m_tableIterator is initialized to the end iterator + of a temporary value! This is ok because we'll never look at the value of the + m_tableIterator, since we're initializing the "end" Iterator.*/ + Iterator() : m_isEnd(true), m_grid(NULL), m_tableIterator(CellTable().end()), + m_arrayIndex(0), m_epoch(0) {} + + Iterator(const ThisType* grid) : + m_isEnd(false), + m_grid(grid), + m_tableIterator( grid->m_data.begin() ), + m_arrayIndex(0), + m_epoch(grid->m_epoch) { } + + private: + + const Value& value() const { + debugAssert(! m_isEnd); + debugAssertM(m_tableIterator->value.size() > m_arrayIndex, + "No more elements"); + return m_tableIterator->value[m_arrayIndex].value; + } + + public: + + inline bool operator!=(const Iterator& other) const { + if (other.m_isEnd && m_isEnd) { + return false; + } else { + return (m_isEnd != other.m_isEnd) || + (m_tableIterator != other.m_tableIterator) || + (m_arrayIndex != other.m_arrayIndex); + } + } + + bool operator==(const Iterator& other) const { + return !(*this != other); + } + + /** Preincrement */ + Iterator& operator++() { + debugAssert(! m_isEnd); + debugAssertM(m_epoch == m_grid->m_epoch, + "It is illegal to mutate the HashGrid " + "while iterating through it."); + + ++m_arrayIndex; + + if (m_arrayIndex >= m_tableIterator->value.size()) { + // Move on to the next cell + ++m_tableIterator; + m_arrayIndex = 0; + + // Check to see if we're at the end + m_isEnd = (m_tableIterator == m_grid->m_data.end()); + } + + return *this; + } + + /** Post increment (slower) */ + Iterator operator++(int) { + debugAssert(! m_isEnd); + Iterator old = *this; + ++(*this); + return old; + } + + const Value& operator*() const { return value(); } + const Value* operator->() const { return &value(); } + operator Value*() const { return &value(); } + }; // Iterator + + + /** Iterate through all members. It is an error to mutate the HashGrid + while iterating through it. Each member can be accessed by "dereferencing" + the iterator: + +
+        for (Grid::Iterator i = grid.begin(); i != grid.end(), ++i) {
+        const Value& = *i;
+        ...
+        }
+        
+ */ + Iterator begin() const { + return Iterator(this); + } + + const Iterator& end() const { + static const Iterator it; + return it; + } + + /////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////// + + // Forward declaration required by older gcc versions for friend declaration in BoxIterator + class SphereIterator; + class BoxIterator { + private: + friend class ThisType; + friend class SphereIterator; + + bool m_isEnd; + + const ThisType* m_grid; + + /** Lower bound on the boxes covered, inclusive. */ + Vector3int32 m_lo; + + /** Upper bound on the boxes covered, inclusive.*/ + Vector3int32 m_hi; + + /** If true, test values against m_box before returning them.*/ + bool m_exact; + + /** The underlying box in 3D space */ + AABox m_box; + + /** The iterator winds through the 3D grid between m_lo and (m_lo + m_extent) in + Z,Y,X-major order. This is the index keeping track of how + far it has come */ + Vector3int32 m_current; + + /** The current cell. */ + Cell* m_cell; + + /** Index within m_cell of the current value */ + int m_arrayIndex; + + const int m_epoch; + + + /** Called from advance() */ + void advanceCell() { + do { + ++m_current.x; + if (m_current.x > m_hi.x) { + m_current.x = m_lo.x; + ++m_current.y; + if (m_current.y > m_hi.y) { + m_current.y = m_lo.y; + ++m_current.z; + if (m_current.z > m_hi.z) { + m_isEnd = true; + return; + } + } + } + + // Pick up the new cell + m_cell = m_grid->m_data.getPointer(m_current); + // Keep advancing if the cell does not exist + } while ((m_cell == NULL) || (m_cell->size() == 0)); + } + + /** Advance to the next value */ + void advance() { + debugAssert(! m_isEnd); + + do { + ++m_arrayIndex; + bool inConstructor = (m_cell == NULL); + if (inConstructor || m_arrayIndex >= m_cell->size()) { + advanceCell(); + m_arrayIndex = 0; + + if (m_isEnd) { + // Ran out of values + return; + } + debugAssert(m_cell != NULL); + } + + // Advance until we have a value that can be returned, either + // because we don't care about exactness or because it is + // guaranteed to be within the box. + } while (m_exact && ! m_box.contains(position())); + } + + + /** End iterator */ + BoxIterator() : m_isEnd(true), m_grid(NULL), m_exact(true), m_current(0,0,0), m_cell(NULL), m_arrayIndex(0), m_epoch(0) {} + + /** Begin iterator */ + BoxIterator(const ThisType* grid, bool exact, const AABox& box) : + m_isEnd(false), + m_grid(grid), + m_exact(exact), + m_box(box), + m_current(-1, 0 ,0), + m_cell(NULL), + m_arrayIndex(0), + m_epoch(grid->m_epoch) { + + m_grid->getCellCoord(box.low(), m_lo); + m_grid->getCellCoord(box.high(), m_hi); + + // Get to the first value + m_current = m_lo; + // Back up one so that advancing takes us to the first + --m_current.x; + advance(); + } + + const Value& value() const { + debugAssert(! m_isEnd); + return (*m_cell)[m_arrayIndex].value; + } + + /** Used by SphereIterator::advance() */ + const Vector3& position() const { + debugAssert(! m_isEnd); + return (*m_cell)[m_arrayIndex].position; + } + + // Intentionally unimplemented + BoxIterator& operator=(const BoxIterator&); + + public: + + inline bool operator!=(const BoxIterator& other) const { + if (other.m_isEnd && m_isEnd) { + return false; + } else { + return (m_isEnd != other.m_isEnd) || + (m_cell != other.m_cell) || + (m_arrayIndex != other.m_arrayIndex); + } + } + + bool operator==(const BoxIterator& other) const { + return !(*this != other); + } + + /** Preincrement */ + BoxIterator& operator++() { + debugAssert(! m_isEnd); + debugAssertM(m_epoch == m_grid->m_epoch, + "It is illegal to mutate the HashGrid " + "while iterating through it."); + + advance(); + + return *this; + } + + /** Post increment (slower) */ + BoxIterator operator++(int) { + Iterator old = *this; + ++(*this); + return old; + } + + const Value& operator*() const { return value(); } + const Value* operator->() const { return &value(); } + operator Value*() const { return &value(); } + + bool hasMore() const { + return ! m_isEnd; + } + }; // BoxIterator + + /** + Finds all values whose positions are within @a box. It is an error to + mutate the PointHashGrid while iterating through it. + + @param exact If false, the iterator will execute more quickly but will likely return some + values that lie outside the box. Set exact = false if you are going to test the + results against the yourself box anyway. + */ + BoxIterator beginBoxIntersection(const AABox& box, bool exact = true) const { + return BoxIterator(this, exact, box); + } + + const BoxIterator& endBoxIntersection() const { + static const BoxIterator it; + return it; + } + + /////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////// + + class SphereIterator { + private: + + friend class ThisType; + + bool m_isEnd; + Sphere m_sphere; + BoxIterator m_boxIterator; + + SphereIterator() : m_isEnd(true) {} + + void advance() { + if (! m_boxIterator.hasMore()) { + m_isEnd = true; + return; + } + + while (! m_sphere.contains(m_boxIterator.position())) { + ++m_boxIterator; + + if (! m_boxIterator.hasMore()) { + m_isEnd = true; + return; + } + } + } + + static AABox getBoundingBox(const Sphere& s) { + AABox box; + s.getBounds(box); + return box; + } + + SphereIterator(const ThisType* grid, const Sphere& sphere) : + m_isEnd(false), + m_sphere(sphere), + m_boxIterator(grid, false, getBoundingBox(sphere)) { + + // Find the first element that is actually in the sphere, + // not just the box. + advance(); + } + + const Value& value() const { + return *m_boxIterator; + } + + // TODO: if the sphere is very big compared to radius, check each + // cell's box to see if the cell itself is actually inside the sphere + // before iterating through it, since there may be many boxes outside the sphere. + + // Intentionally unimplemented + SphereIterator& operator=(const SphereIterator&); + public: + + inline bool operator!=(const SphereIterator& other) const { + if (other.m_isEnd && m_isEnd) { + return false; + } else { + return + (m_isEnd != other.m_isEnd) || + (m_sphere != other.m_sphere) || + (m_boxIterator != other.m_boxIterator); + } + } + + bool operator==(const SphereIterator& other) const { + return !(*this != other); + } + + + + /** Preincrement */ + SphereIterator& operator++() { + debugAssert(! m_isEnd); + + ++m_boxIterator; + advance(); + + return *this; + } + + /** Post increment (slower) */ + SphereIterator operator++(int) { + Iterator old = *this; + ++(*this); + return old; + } + + const Value& operator*() const { return value(); } + const Value* operator->() const { return &value(); } + operator Value*() const { return &value(); } + + bool hasMore() const { + return ! m_isEnd; + } + }; // SphereIterator + + /** + Finds all values whose positions are within @a sphere. It is an error + to mutate the HashGrid while iterating through it. + */ + SphereIterator beginSphereIntersection(const Sphere& sphere) const { + return SphereIterator(this, sphere); + } + + const SphereIterator& endSphereIntersection() const { + static const SphereIterator it; + return it; + } + + /////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////// + + /** + Dereference to access the bounds() and size() [element count] of the underlying + cell objet. + + Example: +
+       for(PointHashGrid::CellIterator iter = grid.beginCells(); iter != grid.endCells(); ++iter) {	
+       entriesFound += iter->size();
+       }
+       
+ */ + class CellIterator { + private: + friend class ThisType; + + bool m_isEnd; + const ThisType* m_grid; + typename CellTable::Iterator m_tableIterator; + const int m_epoch; + + + Cell& cell() { + return m_tableIterator->value; + } + + public: + + class CellObject { + friend class CellIterator; + private: + const CellIterator* m_parent; + + CellObject() : m_parent(NULL) {} + + public: + + /** Returns the bounds on this cell */ + AABox bounds() const { + const Vector3int32& k = m_parent->m_tableIterator->key; + return AABox(Vector3(k) * m_parent->m_cellWidth, + Vector3(k + Vector3int32(1, 1, 1)) * m_parent->m_cellWidth); + } + + /** Number of elements inside this cell */ + int size() const { + debugAssert(! m_parent->m_isEnd); + return m_parent->m_tableIterator->value.size(); + } + }; + + private: + /** Used to make the indirection work.*/ + CellObject m_indirection; + + /** End iterator. Note that the m_tableIterator is initialized to the end iterator + of a temporary value! This is ok because we'll never look at the value of the + m_tableIterator, since we're initializing the "end" Iterator.*/ + CellIterator() : + m_isEnd(true), + m_grid(NULL), + m_tableIterator( CellTable().end() ), + m_epoch(0) {} + + CellIterator(const ThisType* grid) : + m_isEnd(false), + m_grid(grid), + m_tableIterator( grid->m_data.begin()), + m_epoch(grid->m_epoch) { + m_indirection.m_parent = this; + m_isEnd = ! m_tableIterator.hasMore(); + } + + // Intentionally unimplemented + CellIterator& operator=(const CellIterator&); + + public: + + const CellObject& operator*() const { return m_indirection; } + const CellObject* operator->() const { return &m_indirection; } + operator CellObject*() const { return &m_indirection; } + + inline bool operator!=(const CellIterator& other) const { + // != is called more often than == during iteration + return !( + (m_isEnd && other.m_isEnd) || + ((m_isEnd == other.m_isEnd) && + (m_tableIterator != other.m_tableIterator))); + } + + bool operator==(const CellIterator& other) const { + return !(*this != other); + } + + /** Preincrement */ + CellIterator& operator++() { + debugAssertM(m_epoch == m_grid->m_epoch, + "It is illegal to mutate the HashGrid while " + "iterating through it."); + ++m_tableIterator; + m_isEnd = ! m_tableIterator.hasMore(); + return *this; + } + + /** Post increment (slower) */ + CellIterator operator++(int) { + Iterator old = *this; + ++(*this); + return old; + } + + bool hasMore() const { + return ! m_isEnd; + } + }; // CellIterator + + /** Iterates through the non-empty cells. This is intended primarily for + debugging and visualizing the data structure.*/ + CellIterator beginCells() const { + return CellIterator(this); + } + + const CellIterator& endCells() const { + static const CellIterator it; + return it; + } + + /////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////// + + /** Returns true if there is a value that is exactly equal to @a v. This will + check all neighboring cells to avoid roundoff error at cell boundaries. + */ + bool contains(const Value& v) const { + Cell* cell = NULL; + int index = 0; + Vector3int32 cellCoord; + return const_cast(this)->find(v, cellCoord, cell, index); + } + + /** Calls delete on all of the values, which are assumed to be pointers. + This is a helper to avoid requiring you to iterate through the data + structure, removing and deleting each one. Clears the PointHashGrid at the + end. + + Using objects (instead of pointers) or reference counted pointers is + recommended over using pointers and this deleteAll method.*/ + void deleteAll() { + for (Iterator it = begin(); it.hasMore(); ++it) { + delete *it; + } + clear(); + } + + void clearAndSetMemoryManager(const MemoryManager::Ref& m) { + ++m_epoch; + m_size = 0; + m_bounds = AABox(); + + m_data.clearAndSetMemoryManager(m); + m_memoryManager = m; + } + + /** Removes all data. + @param shrink If true, underlying structures are deallocated as + they are freed.*/ + void clear(bool shrink = true) { + m_size = 0; + m_bounds = AABox(); + if (! shrink) { + // Remove all data + for (CellIterator it = beginCells(); it.hasMore(); ++it) { + it.cell().clear(true); + } + } else { + m_data.clear(); + } + ++m_epoch; + } + + int debugGetDeepestBucketSize() const { + return m_data.debugGetDeepestBucketSize(); + } + + float debugGetAverageBucketSize() const { + return m_data.debugGetAverageBucketSize(); + } +#undef ThisType +}; + +} // G3D +#endif diff --git a/dep/g3dlite/G3D/PointKDTree.h b/dep/g3dlite/G3D/PointKDTree.h new file mode 100644 index 00000000000..151cbd5f2f3 --- /dev/null +++ b/dep/g3dlite/G3D/PointKDTree.h @@ -0,0 +1,1185 @@ +/** + @file PointKDTree.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2004-01-11 + @edited 2008-11-02 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + + */ + +#ifndef X_PointKDTree_H +#define X_PointKDTree_H + +#include "G3D/platform.h" +#include "G3D/Array.h" +#include "G3D/Table.h" +#include "G3D/Vector2.h" +#include "G3D/Vector3.h" +#include "G3D/Vector4.h" +#include "G3D/AABox.h" +#include "G3D/Sphere.h" +#include "G3D/Box.h" +#include "G3D/BinaryInput.h" +#include "G3D/BinaryOutput.h" +#include "G3D/CollisionDetection.h" +#include "G3D/GCamera.h" +#include "G3D/PositionTrait.h" +#include + +namespace G3D { + +/** + A set data structure that supports spatial queries using an axis-aligned + BSP tree for speed. + + PointKDTree allows you to quickly find points in 3D that lie within + a box or sphere. For large sets of objects it is much faster + than testing each object for a collision. See also G3D::KDTree; this class + is optimized for point sets, e.g.,for use in photon mapping and mesh processing. + + Template Parameters + +
+ +
The template parameter T must be one for which + the following functions are overloaded: + +
+      T::T(); (public constructor of no arguments)
+
+       template<> struct PositionTrait {
+         static void getPosition(const T& v, G3D::Vector3& p);};
+
+       template <> struct HashTrait {
+         static size_t hashCode(const T& key);};
+
+       template<> struct EqualsTrait {
+           static bool equals(const T& a, const T& b); };
+    
+ +

+ + G3D provides these for the Vector2, Vector3, and Vector4 classes. + If you use a custom class, or a pointer to a custom class, you will need + to define those functions. + + Moving %Set Members +

It is important that objects do not move without updating the + PointKDTree. If the position of an object is about + to change, PointKDTree::remove it before they change and + PointKDTree::insert it again afterward. For objects + where the hashCode and == operator are invariant with respect + to the 3D position, + you can use the PointKDTree::update method as a shortcut to + insert/remove an object in one step after it has moved. + + + Note: Do not mutate any value once it has been inserted into PointKDTree. Values + are copied interally. All PointKDTree iterators convert to pointers to constant + values to reinforce this. + + If you want to mutate the objects you intend to store in a PointKDTree + simply insert pointers to your objects instead of the objects + themselves, and ensure that the above operations are defined. (And + actually, because values are copied, if your values are large you may + want to insert pointers anyway, to save space and make the balance + operation faster.) + + Dimensions + Although designed as a 3D-data structure, you can use the PointKDTree + for data distributed along 2 or 1 axes by simply returning bounds + that are always zero along one or more dimensions. + +*/ +template, + class HashFunc = HashTrait, + class EqualsFunc = EqualsTrait > +class PointKDTree { +protected: +#define TreeType PointKDTree + + // Unlike the KDTree, the PointKDTree assumes that T elements are + // small and keeps the handle and cached position together instead of + // placing them in separate bounds arrays. Also note that a copy of T + // is kept in the member table and that there is no indirection. + class Handle { + private: + Vector3 m_position; + + public: + T value; + + inline Handle() {} + inline Handle(const T& v) : value(v) { + PositionFunc::getPosition(v, m_position); + } + + /** Used by makeNode to create fake handles for partitioning. */ + void setPosition(const Vector3& v) { + m_position = v; + } + + inline const Vector3& position() const { + return m_position; + } + }; + + /** Returns the bounds of the sub array. Used by makeNode. */ + static AABox computeBounds( + const Array& point) { + + if (point.size() == 0) { + return AABox(Vector3::inf(), Vector3::inf()); + } + + AABox bounds(point[0].position()); + + for (int p = 0; p < point.size(); ++p) { + bounds.merge(point[p].position()); + } + + return bounds; + } + + class Node { + public: + + /** Spatial bounds on all values at this node and its children, based purely on + the parent's splitting planes. May be infinite */ + AABox splitBounds; + + Vector3::Axis splitAxis; + + /** Location along the specified axis */ + float splitLocation; + + /** child[0] contains all values strictly + smaller than splitLocation along splitAxis. + + child[1] contains all values strictly + larger. + + Both may be NULL if there are not enough + values to bother recursing. + */ + Node* child[2]; + + /** Values if this is a leaf node). */ + Array valueArray; + + /** Creates node with NULL children */ + Node() { + splitAxis = Vector3::X_AXIS; + splitLocation = 0; + splitBounds = AABox(-Vector3::inf(), Vector3::inf()); + for (int i = 0; i < 2; ++i) { + child[i] = NULL; + } + } + + /** + Doesn't clone children. + */ + Node(const Node& other) : valueArray(other.valueArray) { + splitAxis = other.splitAxis; + splitLocation = other.splitLocation; + splitBounds = other.splitBounds; + for (int i = 0; i < 2; ++i) { + child[i] = NULL; + } + } + + /** Copies the specified subarray of pt into point, NULLs the children. + Assumes a second pass will set splitBounds. */ + Node(const Array& pt) { + splitAxis = Vector3::X_AXIS; + splitLocation = 0; + for (int i = 0; i < 2; ++i) { + child[i] = NULL; + } + valueArray = pt; + } + + + /** Deletes the children (but not the values) */ + ~Node() { + for (int i = 0; i < 2; ++i) { + delete child[i]; + } + } + + + /** Returns true if this node is a leaf (no children) */ + inline bool isLeaf() const { + return (child[0] == NULL) && (child[1] == NULL); + } + + + /** + Recursively appends all handles and children's handles + to the array. + */ + void getHandles(Array& handleArray) const { + handleArray.append(valueArray); + for (int i = 0; i < 2; ++i) { + if (child[i] != NULL) { + child[i]->getHandles(handleArray); + } + } + } + + + void verifyNode(const Vector3& lo, const Vector3& hi) { + // debugPrintf("Verifying: split %d @ %f [%f, %f, %f], [%f, %f, %f]\n", + // splitAxis, splitLocation, lo.x, lo.y, lo.z, hi.x, hi.y, hi.z); + + debugAssert(lo == splitBounds.low()); + debugAssert(hi == splitBounds.high()); + + for (int i = 0; i < valueArray.length(); ++i) { + const Vector3& b = valueArray[i].position(); + debugAssert(splitBounds.contains(b)); + } + + if (child[0] || child[1]) { + debugAssert(lo[splitAxis] < splitLocation); + debugAssert(hi[splitAxis] > splitLocation); + } + + Vector3 newLo = lo; + newLo[splitAxis] = splitLocation; + Vector3 newHi = hi; + newHi[splitAxis] = splitLocation; + + if (child[0] != NULL) { + child[0]->verifyNode(lo, newHi); + } + + if (child[1] != NULL) { + child[1]->verifyNode(newLo, hi); + } + } + + + /** + Stores the locations of the splitting planes (the structure but not the content) + so that the tree can be quickly rebuilt from a previous configuration without + calling balance. + */ + static void serializeStructure(const Node* n, BinaryOutput& bo) { + if (n == NULL) { + bo.writeUInt8(0); + } else { + bo.writeUInt8(1); + n->splitBounds.serialize(bo); + serialize(n->splitAxis, bo); + bo.writeFloat32(n->splitLocation); + for (int c = 0; c < 2; ++c) { + serializeStructure(n->child[c], bo); + } + } + } + + /** Clears the member table */ + static Node* deserializeStructure(BinaryInput& bi) { + if (bi.readUInt8() == 0) { + return NULL; + } else { + Node* n = new Node(); + n->splitBounds.deserialize(bi); + deserialize(n->splitAxis, bi); + n->splitLocation = bi.readFloat32(); + for (int c = 0; c < 2; ++c) { + n->child[c] = deserializeStructure(bi); + } + } + } + + /** Returns the deepest node that completely contains bounds. */ + Node* findDeepestContainingNode(const Vector3& point) { + + // See which side of the splitting plane the bounds are on + if (point[splitAxis] < splitLocation) { + // Point is on the low side. Recurse into the child + // if it exists. + if (child[0] != NULL) { + return child[0]->findDeepestContainingNode(point); + } + } else if (point[splitAxis] > splitLocation) { + // Point is on the high side, recurse into the child + // if it exists. + if (child[1] != NULL) { + return child[1]->findDeepestContainingNode(point); + } + } + + // There was no containing child, so this node is the + // deepest containing node. + return this; + } + + /** Appends all members that intersect the box. + If useSphere is true, members are tested against the sphere instead. */ + void getIntersectingMembers( + const AABox& sphereBounds, + const Sphere& sphere, + Array& members) const { + + // Test all values at this node. Extract the + // underlying C array for speed + const int N = valueArray.size(); + const Handle* handleArray = valueArray.getCArray(); + + const float r2 = square(sphere.radius); + + // Copy the sphere center so that it is on the stack near the radius + const Vector3 center = sphere.center; + for (int v = 0; v < N; ++v) { + if ((center - handleArray[v].position()).squaredLength() <= r2) { + members.append(handleArray[v].value); + } + } + + // If the left child overlaps the box, recurse into it + if (child[0] && (sphereBounds.low()[splitAxis] < splitLocation)) { + child[0]->getIntersectingMembers(sphereBounds, sphere, members); + } + + // If the right child overlaps the box, recurse into it + if (child[1] && (sphereBounds.high()[splitAxis] > splitLocation)) { + child[1]->getIntersectingMembers(sphereBounds, sphere, members); + } + } + + /** Appends all members that intersect the box. + If useSphere is true, members are tested against the sphere instead. + + Implemented using both box and sphere tests to simplify the implementation + of a future beginSphereInteresection iterator using the same underlying + BoxIterator class. + */ + void getIntersectingMembers( + const AABox& box, + const Sphere& sphere, + Array& members, + bool useSphere) const { + + // Test all values at this node + for (int v = 0; v < valueArray.size(); ++v) { + if ((useSphere && sphere.contains(valueArray[v].position())) || + (! useSphere && box.contains(valueArray[v].position()))) { + members.append(valueArray[v].value); + } + } + + // If the left child overlaps the box, recurse into it + if ((child[0] != NULL) && (box.low()[splitAxis] < splitLocation)) { + child[0]->getIntersectingMembers(box, sphere, members, useSphere); + } + + // If the right child overlaps the box, recurse into it + if ((child[1] != NULL) && (box.high()[splitAxis] > splitLocation)) { + child[1]->getIntersectingMembers(box, sphere, members, useSphere); + } + } + + /** + Recurse through the tree, assigning splitBounds fields. + */ + void assignSplitBounds(const AABox& myBounds) { + splitBounds = myBounds; + +# ifdef G3D_DEBUG + if (child[0] || child[1]) { + debugAssert(splitBounds.high()[splitAxis] > splitLocation); + debugAssert(splitBounds.low()[splitAxis] < splitLocation); + } +# endif + + AABox childBounds[2]; + myBounds.split(splitAxis, splitLocation, childBounds[0], childBounds[1]); + + for (int c = 0; c < 2; ++c) { + if (child[c]) { + child[c]->assignSplitBounds(childBounds[c]); + } + } + } + }; + + class AxisComparator { + private: + Vector3::Axis sortAxis; + + public: + + AxisComparator(Vector3::Axis s) : sortAxis(s) {} + + inline int operator()(const Handle& A, const Handle& B) const { + if (A.position()[sortAxis] > B.position()[sortAxis]) { + return -1; + } else if (A.position()[sortAxis] < B.position()[sortAxis]) { + return 1; + } else { + return 0; + } + } + }; + + /** + Recursively subdivides the subarray. + + The source array will be cleared after it is used + + Call assignSplitBounds() on the root node after making a tree. + */ + Node* makeNode( + Array& source, + Array& temp, + int valuesPerNode, + int numMeanSplits) { + + Node* node = NULL; + + if (source.size() <= valuesPerNode) { + // Make a new leaf node + node = new Node(source); + + // Set the pointers in the memberTable + for (int i = 0; i < source.size(); ++i) { + memberTable.set(source[i].value, node); + } + + } else { + // Make a new internal node + node = new Node(); + + const AABox bounds = computeBounds(source); + const Vector3 extent = bounds.high() - bounds.low(); + + Vector3::Axis splitAxis = extent.primaryAxis(); + + float splitLocation; + + Array lt, gt; + + if (numMeanSplits <= 0) { + source.medianPartition(lt, node->valueArray, gt, temp, AxisComparator(splitAxis)); + splitLocation = node->valueArray[0].position()[splitAxis]; + + if ((node->valueArray.size() > source.size() / 2) && + (source.size() > 10)) { + // Our median split put an awful lot of points on the splitting plane. Try a mean + // split instead + numMeanSplits = 1; + } + } + + if (numMeanSplits > 0) { + // Compute the mean along the axis + + splitLocation = (bounds.high()[splitAxis] + + bounds.low()[splitAxis]) / 2.0; + + Handle splitHandle; + Vector3 v; + v[splitAxis] = splitLocation; + splitHandle.setPosition(v); + + source.partition(splitHandle, lt, node->valueArray, gt, AxisComparator(splitAxis)); + } + +# if defined(G3D_DEBUG) && defined(VERIFY_TREE) + for (int i = 0; i < lt.size(); ++i) { + const Vector3& v = lt[i].position(); + debugAssert(v[splitAxis] < splitLocation); + } + for (int i = 0; i < gt.size(); ++i) { + debugAssert(gt[i].position()[splitAxis] > splitLocation); + } + for (int i = 0; i < node->valueArray.size(); ++i) { + debugAssert(node->valueArray[i].position()[splitAxis] == splitLocation); + } +# endif + + node->splitAxis = splitAxis; + node->splitLocation = splitLocation; + + // Throw away the source array to save memory + source.fastClear(); + + if (lt.size() > 0) { + node->child[0] = makeNode(lt, temp, valuesPerNode, numMeanSplits - 1); + } + + if (gt.size() > 0) { + node->child[1] = makeNode(gt, temp, valuesPerNode, numMeanSplits - 1); + } + + // Add the values stored at this interior node to the member table + for(int i = 0; i < node->valueArray.size(); ++i) { + memberTable.set(node->valueArray[i].value, node); + } + + } + + return node; + } + + /** + Recursively clone the passed in node tree, setting + pointers for members in the memberTable as appropriate. + called by the assignment operator. + */ + Node* cloneTree(Node* src) { + Node* dst = new Node(*src); + + // Make back pointers + for (int i = 0; i < dst->valueArray.size(); ++i) { + memberTable.set(dst->valueArray[i].value, dst); + } + + // Clone children + for (int i = 0; i < 2; ++i) { + if (src->child[i] != NULL) { + dst->child[i] = cloneTree(src->child[i]); + } + } + + return dst; + } + + /** Maps members to the node containing them */ + typedef Table MemberTable; + MemberTable memberTable; + + Node* root; + +public: + + /** To construct a balanced tree, insert the elements and then call + PointKDTree::balance(). */ + PointKDTree() : root(NULL) {} + + + PointKDTree(const PointKDTree& src) : root(NULL) { + *this = src; + } + + + PointKDTree& operator=(const PointKDTree& src) { + delete root; + // Clone tree takes care of filling out the memberTable. + root = cloneTree(src.root); + return *this; + } + + + ~PointKDTree() { + clear(); + } + + /** + Throws out all elements of the set and erases the structure of the tree. + */ + void clear() { + memberTable.clear(); + delete root; + root = NULL; + } + + /** Removes all elements of the set while maintaining the structure of the tree */ + void clearData() { + memberTable.clear(); + Array stack; + stack.push(root); + while (stack.size() > 0) { + Node* node = stack.pop(); + node->valueArray.fastClear(); + + for (int i = 0; i < 2; ++i) { + if (node->child[i] != NULL) { + stack.push(node->child[i]); + } + } + } + } + + + int size() const { + return memberTable.size(); + } + + /** + Inserts an object into the set if it is not + already present. O(log n) time. Does not + cause the tree to be balanced. + */ + void insert(const T& value) { + if (contains(value)) { + // Already in the set + return; + } + + Handle h(value); + + if (root == NULL) { + // This is the first node; create a root node + root = new Node(); + } + + Node* node = root->findDeepestContainingNode(h.position()); + + // Insert into the node + node->valueArray.append(h); + + // Insert into the node table + memberTable.set(value, node); + } + + /** Inserts each elements in the array in turn. If the tree + begins empty (no structure and no elements), this is faster + than inserting each element in turn. You still need to balance + the tree at the end.*/ + void insert(const Array& valueArray) { + // Pre-size the member table to avoid multiple allocations + memberTable.setSizeHint(valueArray.size() + size()); + + if (root == NULL) { + // Optimized case for an empty tree; don't bother + // searching or reallocating the root node's valueArray + // as we incrementally insert. + root = new Node(); + root->valueArray.resize(valueArray.size()); + for (int i = 0; i < valueArray.size(); ++i) { + // Insert in opposite order so that we have the exact same + // data structure as if we inserted each (i.e., order is reversed + // from array). + root->valueArray[valueArray.size() - i - 1] = Handle(valueArray[i]); + memberTable.set(valueArray[i], root); + } + } else { + // Insert at appropriate tree depth. + for (int i = 0; i < valueArray.size(); ++i) { + insert(valueArray[i]); + } + } + } + + + /** + Returns true if this object is in the set, otherwise + returns false. O(1) time. + */ + bool contains(const T& value) { + return memberTable.containsKey(value); + } + + + /** + Removes an object from the set in O(1) time. + It is an error to remove members that are not already + present. May unbalance the tree. + + Removing an element never causes a node (split plane) to be removed... + nodes are only changed when the tree is rebalanced. This behavior + is desirable because it allows the split planes to be serialized, + and then deserialized into an empty tree which can be repopulated. + */ + void remove(const T& value) { + debugAssertM(contains(value), + "Tried to remove an element from a " + "PointKDTree that was not present"); + + Array& list = memberTable[value]->valueArray; + + // Find the element and remove it + for (int i = list.length() - 1; i >= 0; --i) { + if (list[i].value == value) { + list.fastRemove(i); + break; + } + } + memberTable.remove(value); + } + + + /** + If the element is in the set, it is removed. + The element is then inserted. + + This is useful when the == and hashCode methods + on T are independent of the bounds. In + that case, you may call update(v) to insert an + element for the first time and call update(v) + again every time it moves to keep the tree + up to date. + */ + void update(const T& value) { + if (contains(value)) { + remove(value); + } + insert(value); + } + + + /** + Rebalances the tree (slow). Call when objects + have moved substantially from their original positions + (which unbalances the tree and causes the spatial + queries to be slow). + + @param valuesPerNode Maximum number of elements to put at + a node. + + @param numMeanSplits numMeanSplits = 0 gives a + fully axis aligned BSP-tree, where the balance operation attempts to balance + the tree so that every splitting plane has an equal number of left + and right children (i.e. it is a median split along that axis). + This tends to maximize average performance; all querries will return in the same amount of time. + + You can override this behavior by + setting a number of mean (average) splits. numMeanSplits = MAX_INT + creates a full oct-tree, which tends to optimize peak performance (some areas of the scene will terminate after few recursive splits) at the expense of + peak performance. + */ + void balance(int valuesPerNode = 40, int numMeanSplits = 3) { + if (root == NULL) { + // Tree is empty + return; + } + + Array handleArray; + root->getHandles(handleArray); + + // Delete the old tree + clear(); + + Array temp; + root = makeNode(handleArray, temp, valuesPerNode, numMeanSplits); + temp.fastClear(); + + // Walk the tree, assigning splitBounds. We start with unbounded + // space. + root->assignSplitBounds(AABox::maxFinite()); + +# ifdef _DEBUG + root->verifyNode(Vector3::minFinite(), Vector3::maxFinite()); +# endif + } + +private: + + /** + Returns the elements + + @param parentMask The mask that this node returned from culledBy. + */ + static void getIntersectingMembers( + const Array& plane, + Array& members, + Node* node, + uint32 parentMask) { + + int dummy; + + if (parentMask == 0) { + // None of these planes can cull anything + for (int v = node->valueArray.size() - 1; v >= 0; --v) { + members.append(node->valueArray[v].value); + } + + // Iterate through child nodes + for (int c = 0; c < 2; ++c) { + if (node->child[c]) { + getIntersectingMembers(plane, members, node->child[c], 0); + } + } + } else { + + if (node->valueArray.size() > 0) { + // This is a leaf; check the points + debugAssertM(node->child[0] == NULL, "Malformed Point tree"); + debugAssertM(node->child[1] == NULL, "Malformed Point tree"); + + // Test values at this node against remaining planes + for (int p = 0; p < plane.size(); ++p) { + if ((parentMask >> p) & 1 != 0) { + // Test against this plane + const Plane& curPlane = plane[p]; + for (int v = node->valueArray.size() - 1; v >= 0; --v) { + if (curPlane.halfSpaceContains(node->valueArray[v].position())) { + members.append(node->valueArray[v].value); + } + } + } + } + } else { + + uint32 childMask = 0xFFFFFF; + + // Iterate through child nodes + for (int c = 0; c < 2; ++c) { + if (node->child[c] && + ! node->child[c]->splitBounds.culledBy(plane, dummy, parentMask, childMask)) { + // This node was not culled + getIntersectingMembers(plane, members, node->child[c], childMask); + } + } + } + } + } + +public: + + /** + Returns all members inside the set of planes. + @param members The results are appended to this array. + */ + void getIntersectingMembers(const Array& plane, Array& members) const { + if (root == NULL) { + return; + } + + getIntersectingMembers(plane, members, root, 0xFFFFFF); + } + + /** + Typically used to find all visible + objects inside the view frustum (see also GCamera::getClipPlanes)... i.e. all objects + not culled by frustum. + + Example: +
+        Array  visible;
+        tree.getIntersectingMembers(camera.frustum(), visible);
+        // ... Draw all objects in the visible array.
+      
+ @param members The results are appended to this array. + */ + void getIntersectingMembers(const GCamera::Frustum& frustum, Array& members) const { + Array plane; + + for (int i = 0; i < frustum.faceArray.size(); ++i) { + plane.append(frustum.faceArray[i].plane); + } + + getIntersectingMembers(plane, members); + } + + /** + C++ STL style iterator variable. See beginBoxIntersection(). + The iterator overloads the -> (dereference) operator, so this + acts like a pointer to the current member. + */ + // This iterator turns Node::getIntersectingMembers into a + // coroutine. It first translates that method from recursive to + // stack based, then captures the system state (analogous to a Scheme + // continuation) after each element is appended to the member array, + // and allowing the computation to be restarted. + class BoxIntersectionIterator { + private: + friend class TreeType; + + /** True if this is the "end" iterator instance */ + bool isEnd; + + /** The box that we're testing against. */ + AABox box; + + /** Node that we're currently looking at. Undefined if isEnd + is true. */ + Node* node; + + /** Nodes waiting to be processed */ + // We could use backpointers within the tree and careful + // state management to avoid ever storing the stack-- but + // it is much easier this way and only inefficient if the + // caller uses post increment (which they shouldn't!). + Array stack; + + /** The next index of current->valueArray to return. + Undefined when isEnd is true.*/ + int nextValueArrayIndex; + + BoxIntersectionIterator() : isEnd(true) {} + + BoxIntersectionIterator(const AABox& b, const Node* root) : + isEnd(root == NULL), box(b), + node(const_cast(root)), nextValueArrayIndex(-1) { + + // We intentionally start at the "-1" index of the current + // node so we can use the preincrement operator to move + // ourselves to element 0 instead of repeating all of the + // code from the preincrement method. Note that this might + // cause us to become the "end" instance. + ++(*this); + } + + public: + + inline bool operator!=(const BoxIntersectionIterator& other) const { + return ! (*this == other); + } + + bool operator==(const BoxIntersectionIterator& other) const { + if (isEnd) { + return other.isEnd; + } else if (other.isEnd) { + return false; + } else { + // Two non-end iterators; see if they match. This is kind of + // silly; users shouldn't call == on iterators in general unless + // one of them is the end iterator. + if ((box != other.box) || (node != other.node) || + (nextValueArrayIndex != other.nextValueArrayIndex) || + (stack.length() != other.stack.length())) { + return false; + } + + // See if the stacks are the same + for (int i = 0; i < stack.length(); ++i) { + if (stack[i] != other.stack[i]) { + return false; + } + } + + // We failed to find a difference; they must be the same + return true; + } + } + + /** + Pre increment. + */ + BoxIntersectionIterator& operator++() { + ++nextValueArrayIndex; + + bool foundIntersection = false; + while (! isEnd && ! foundIntersection) { + + // Search for the next node if we've exhausted this one + while ((! isEnd) && (nextValueArrayIndex >= node->valueArray.length())) { + // If we entered this loop, then the iterator has exhausted the elements at + // node (possibly because it just switched to a child node with no members). + // This loop continues until it finds a node with members or reaches + // the end of the whole intersection search. + + // If the right child overlaps the box, push it onto the stack for + // processing. + if ((node->child[1] != NULL) && + (box.high()[node->splitAxis] > node->splitLocation)) { + stack.push(node->child[1]); + } + + // If the left child overlaps the box, push it onto the stack for + // processing. + if ((node->child[0] != NULL) && + (box.low()[node->splitAxis] < node->splitLocation)) { + stack.push(node->child[0]); + } + + if (stack.length() > 0) { + // Go on to the next node (which may be either one of the ones we + // just pushed, or one from farther back the tree). + node = stack.pop(); + nextValueArrayIndex = 0; + } else { + // That was the last node; we're done iterating + isEnd = true; + } + } + + // Search for the next intersection at this node until we run out of children + while (! isEnd && ! foundIntersection && (nextValueArrayIndex < node->valueArray.length())) { + if (box.intersects(node->valueArray[nextValueArrayIndex].bounds)) { + foundIntersection = true; + } else { + ++nextValueArrayIndex; + // If we exhaust this node, we'll loop around the master loop + // to find a new node. + } + } + } + + return *this; + } + + /** + Post increment (much slower than preincrement!). + */ + BoxIntersectionIterator operator++(int) { + BoxIntersectionIterator old = *this; + ++this; + return old; + } + + /** Overloaded dereference operator so the iterator can masquerade as a pointer + to a member */ + const T& operator*() const { + alwaysAssertM(! isEnd, "Can't dereference the end element of an iterator"); + return node->valueArray[nextValueArrayIndex].value; + } + + /** Overloaded dereference operator so the iterator can masquerade as a pointer + to a member */ + T const * operator->() const { + alwaysAssertM(! isEnd, "Can't dereference the end element of an iterator"); + return &(stack.last()->valueArray[nextValueArrayIndex].value); + } + + /** Overloaded cast operator so the iterator can masquerade as a pointer + to a member */ + operator T*() const { + alwaysAssertM(! isEnd, "Can't dereference the end element of an iterator"); + return &(stack.last()->valueArray[nextValueArrayIndex].value); + } + }; + + + /** + Iterates through the members that intersect the box + */ + BoxIntersectionIterator beginBoxIntersection(const AABox& box) const { + return BoxIntersectionIterator(box, root); + } + + BoxIntersectionIterator endBoxIntersection() const { + // The "end" iterator instance + return BoxIntersectionIterator(); + } + + /** + Appends all members whose bounds intersect the box. + See also PointKDTree::beginBoxIntersection. + */ + void getIntersectingMembers(const AABox& box, Array& members) const { + if (root == NULL) { + return; + } + root->getIntersectingMembers(box, Sphere(Vector3::zero(), 0), members, false); + } + + + /** + @param members The results are appended to this array. + */ + void getIntersectingMembers(const Sphere& sphere, Array& members) const { + if (root == NULL) { + return; + } + + AABox box; + sphere.getBounds(box); + root->getIntersectingMembers(box, sphere, members); + + } + + + /** + Stores the locations of the splitting planes (the structure but not the content) + so that the tree can be quickly rebuilt from a previous configuration without + calling balance. + */ + void serializeStructure(BinaryOutput& bo) const { + Node::serializeStructure(root, bo); + } + + /** Clears the member table */ + void deserializeStructure(BinaryInput& bi) { + clear(); + root = Node::deserializeStructure(bi); + } + + /** + Returns an array of all members of the set. See also PointKDTree::begin. + */ + void getMembers(Array& members) const { + memberTable.getKeys(members); + } + + + /** + C++ STL style iterator variable. See begin(). + Overloads the -> (dereference) operator, so this acts like a pointer + to the current member. + */ + class Iterator { + private: + friend class TreeType; + + // Note: this is a Table iterator, we are currently defining + // Set iterator + typename MemberTable::Iterator it; + + Iterator(const typename MemberTable::Iterator& it) : it(it) {} + + public: + inline bool operator!=(const Iterator& other) const { + return !(*this == other); + } + + bool operator==(const Iterator& other) const { + return it == other.it; + } + + /** + Pre increment. + */ + Iterator& operator++() { + ++it; + return *this; + } + + /** + Post increment (slower than preincrement). + */ + Iterator operator++(int) { + Iterator old = *this; + ++(*this); + return old; + } + + const T& operator*() const { + return it->key; + } + + T* operator->() const { + return &(it->key); + } + + operator T*() const { + return &(it->key); + } + }; + + + /** + C++ STL style iterator method. Returns the first member. + Use preincrement (++entry) to get to the next element (iteration + order is arbitrary). + Do not modify the set while iterating. + */ + Iterator begin() const { + return Iterator(memberTable.begin()); + } + + + /** + C++ STL style iterator method. Returns one after the last iterator + element. + */ + Iterator end() const { + return Iterator(memberTable.end()); + } +#undef TreeType +}; + +} + +#endif diff --git a/dep/g3dlite/G3D/Pointer.h b/dep/g3dlite/G3D/Pointer.h new file mode 100644 index 00000000000..6e35062a746 --- /dev/null +++ b/dep/g3dlite/G3D/Pointer.h @@ -0,0 +1,292 @@ +/** + @file Pointer.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2007-05-16 + @edited 2009-03-26 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ +#ifndef G3D_Pointer_h +#define G3D_Pointer_h + +#include "G3D/debugAssert.h" +#include "G3D/ReferenceCount.h" + +namespace G3D { + +/** + Acts like a pointer to a value of type ValueType (i.e., + ValueType*), but can operate through accessor methods as well as on + a value in memory. This is useful for implementing scripting + languages and other applications that need to connect existing APIs + by reference. + + Because the accessors require values to be passed by value (instead of by reference) + this is primarily useful for objects whose memory size is small. + +
+   class Foo {
+   public:
+      void setEnabled(bool b);
+      bool getEnabled() const;
+   };
+
+   Foo  f;
+   bool b;
+   
+   Pointer p1(&b);
+   Pointer p2(&f, &Foo::getEnabled, &Foo::setEnabled);
+
+   *p1 = true;
+   *p2 = false;
+   *p2 = *p1; \/\/ Value assignment
+   p2 = p1; \/\/ Pointer aliasing
+
+   \/\/ Or, equivalently:
+   p1.setValue(true);
+   p2.setValue(false);
+
+   p2.setValue(p1.getValue());
+   p2 = p1;
+   
+ + Note: Because of the way that dereference is implemented, you cannot pass *p through a function + that takes varargs (...), e.g., printf("%d", *p) will produce a compile-time error. Instead use + printf("%d",(bool)*p) or printf("%d", p.getValue()). + + */ +template +class Pointer { +private: + + class Interface { + public: + virtual ~Interface() {}; + virtual void set(ValueType b) = 0; + virtual ValueType get() const = 0; + virtual Interface* clone() const = 0; + virtual bool isNull() const = 0; + }; + + class Memory : public Interface { + private: + + ValueType* value; + + public: + + Memory(ValueType* value) : value(value) { + //debugAssert(value != NULL); + } + + virtual void set(ValueType v) { + *value = v; + } + + virtual ValueType get() const { + return *value; + } + + virtual Interface* clone() const { + return new Memory(value); + } + + virtual bool isNull() const { + return value == NULL; + } + }; + + template + class Accessor : public Interface { + private: + + T* object; + GetMethod getMethod; + SetMethod setMethod; + + public: + + Accessor(T* object, + GetMethod getMethod, + SetMethod setMethod) : object(object), getMethod(getMethod), setMethod(setMethod) { + debugAssert(object != NULL); + } + + virtual void set(ValueType v) { + (object->*setMethod)(v); + } + + virtual ValueType get() const { + return (object->*getMethod)(); + } + + virtual Interface* clone() const { + return new Accessor(object, getMethod, setMethod); + } + + virtual bool isNull() const { + return object == NULL; + } + }; + + + template + class RefAccessor : public Interface { + private: + + ReferenceCountedPointer object; + GetMethod getMethod; + SetMethod setMethod; + + public: + + RefAccessor( + const ReferenceCountedPointer& object, + GetMethod getMethod, + SetMethod setMethod) : object(object), getMethod(getMethod), setMethod(setMethod) { + + debugAssert(object != NULL); + } + + virtual void set(ValueType v) { + (object.pointer()->*setMethod)(v); + } + + virtual ValueType get() const { + return (object.pointer()->*getMethod)(); + } + + virtual Interface* clone() const { + return new RefAccessor(object, getMethod, setMethod); + } + + virtual bool isNull() const { + return object.isNull(); + } + }; + + + Interface* m_interface; + +public: + + Pointer() : m_interface(NULL) {}; + + /** Allows implicit cast from real pointer */ + Pointer(ValueType* v) : m_interface(new Memory(v)) {} + + inline bool isNull() const { + return (m_interface == NULL) || m_interface->isNull(); + } + + // Assignment + inline Pointer& operator=(const Pointer& r) { + delete m_interface; + if (r.m_interface != NULL) { + m_interface = r.m_interface->clone(); + } else { + m_interface = NULL; + } + return this[0]; + } + + Pointer(const Pointer& p) : m_interface(NULL) { + this[0] = p; + } + + template + Pointer(const ReferenceCountedPointer& object, + ValueType (Class::*getMethod)() const, + void (Class::*setMethod)(ValueType)) : + m_interface(new RefAccessor(object, getMethod, setMethod)) {} + + template + Pointer(const ReferenceCountedPointer& object, + const ValueType& (Class::*getMethod)() const, + void (Class::*setMethod)(ValueType)) : + m_interface(new RefAccessor(object, getMethod, setMethod)) {} + + template + Pointer(const ReferenceCountedPointer& object, + ValueType (Class::*getMethod)() const, + void (Class::*setMethod)(const ValueType&)) : + m_interface(new RefAccessor(object, getMethod, setMethod)) {} + + template + Pointer(const ReferenceCountedPointer& object, + const ValueType& (Class::*getMethod)() const, + void (Class::*setMethod)(const ValueType&)) : + m_interface(new RefAccessor(object, getMethod, setMethod)) {} + + template + Pointer(Class* object, + const ValueType& (Class::*getMethod)() const, + void (Class::*setMethod)(const ValueType&)) : + m_interface(new Accessor(object, getMethod, setMethod)) {} + + template + Pointer(Class* object, + ValueType (Class::*getMethod)() const, + void (Class::*setMethod)(const ValueType&)) : + m_interface(new Accessor(object, getMethod, setMethod)) {} + + template + Pointer(Class* object, + const ValueType& (Class::*getMethod)() const, + void (Class::*setMethod)(ValueType)) : + m_interface(new Accessor(object, getMethod, setMethod)) {} + + template + Pointer(Class* object, + ValueType (Class::*getMethod)() const, + void (Class::*setMethod)(ValueType)) : + m_interface(new Accessor(object, getMethod, setMethod)) {} + + ~Pointer() { + delete m_interface; + } + + inline const ValueType getValue() const { + debugAssert(m_interface != NULL); + return m_interface->get(); + } + + inline void setValue(const ValueType& v) { + debugAssert(m_interface != NULL); + m_interface->set(v); + } + + class IndirectValue { + private: + + friend class Pointer; + Pointer* pointer; + IndirectValue(Pointer* p) : pointer(p) {} + + public: + + void operator=(const ValueType& v) { + pointer->setValue(v); + } + + operator ValueType() const { + return pointer->getValue(); + } + + }; + + inline IndirectValue operator*() { + return IndirectValue(this); + } + + inline const ValueType operator*() const { + return getValue(); + } +}; + +} + +#endif diff --git a/dep/g3dlite/G3D/PositionTrait.h b/dep/g3dlite/G3D/PositionTrait.h new file mode 100644 index 00000000000..67a4f64138a --- /dev/null +++ b/dep/g3dlite/G3D/PositionTrait.h @@ -0,0 +1,7 @@ +#ifndef G3D_POSITIONTRAIT_H +#define G3D_POSITIONTRAIT_H + +template +struct PositionTrait{}; + +#endif diff --git a/dep/g3dlite/G3D/PrecomputedRandom.h b/dep/g3dlite/G3D/PrecomputedRandom.h new file mode 100644 index 00000000000..411d128c582 --- /dev/null +++ b/dep/g3dlite/G3D/PrecomputedRandom.h @@ -0,0 +1,110 @@ +/** + @file PrecomputedRandom.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2009-03-31 + @edited 2009-03-31 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ +#ifndef G3D_PrecomputedRandom_h +#define G3D_PrecomputedRandom_h + +#include "G3D/platform.h" +#include "G3D/Random.h" + +namespace G3D { + +/** Fast random numbers using a precomputed data table. + + e.g., generates cosHemi about 13x faster than Random. + This is useful for quickly generating seeded random + numbers for reproducibility. G3D::Random takes a long + time to seed; this is instantaneous (providing the + precomputed data is already available.) + + Not threadsafe.*/ +class PrecomputedRandom : public Random { +public: + /** Put the cosHemi and the uniform together so that when + alternating between them we stay in cache. This is also packed + into a good size for SIMD and GPU operations.*/ + class HemiUniformData { + public: + float cosHemiX; + float cosHemiY; + float cosHemiZ; + float uniform; + }; + + class SphereBitsData { + public: + float sphereX; + float sphereY; + float sphereZ; + uint32 bits; + }; + +protected: + + /** Array of 2^n elements. */ + const HemiUniformData* m_hemiUniform; + const SphereBitsData* m_sphereBits; + + /** 2^n - 1; the AND mask for computing a fast modulo */ + int m_modMask; + + int m_index; + + /** If true, free m_hemiUniform and m_sphereBits in destructor */ + bool m_freeData; + +public: + + /* + \param dataSize Must be a power of 2 + \param data Will NOT be deleted by the destructor. + */ + PrecomputedRandom(const HemiUniformData* data1, const SphereBitsData* data2, int dataSize, uint32 seed = 0xF018A4D2); + + /** + \param dataSize Number of random numbers that can be requested before periodicity. Must be a power of 2. + */ + PrecomputedRandom(int dataSize, uint32 seed = 0xF018A4D2); + + ~PrecomputedRandom(); + + /** Each bit is random. Subclasses can choose to override just + this method and the other methods will all work automatically. */ + virtual uint32 bits(); + + // integer is inherited + + /** Uniform random float on the range [min, max] */ + virtual float uniform(float low, float high); + + /** Uniform random float on the range [0, 1] */ + virtual float uniform(); + + // gaussian is inherited + + /** Returns 3D unit vectors distributed according to + a cosine distribution about the z axis. */ + virtual void cosHemi(float& x, float& y, float& z); + + /** Returns 3D unit vectors distributed according to a cosine + power distribution (\f$ \mbox{cos}^k \theta \f$) about + the z-axis. */ + virtual void cosPowHemi(const float k, float& x, float& y, float& z); + + // hemi is inherited + + /** Returns 3D unit vectors uniformly distributed on the sphere */ + virtual void sphere(float& x, float& y, float& z); +}; + +} + +#endif diff --git a/dep/g3dlite/G3D/Quat.h b/dep/g3dlite/G3D/Quat.h new file mode 100644 index 00000000000..9ef3d57b301 --- /dev/null +++ b/dep/g3dlite/G3D/Quat.h @@ -0,0 +1,725 @@ +/** + @file Quat.h + + Quaternion + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2002-01-23 + @edited 2009-05-10 + */ + +#ifndef G3D_Quat_h +#define G3D_Quat_h + +#include "G3D/platform.h" +#include "G3D/g3dmath.h" +#include "G3D/Vector3.h" +#include "G3D/Matrix3.h" +#include + +namespace G3D { + +/** + Unit quaternions are used in computer graphics to represent + rotation about an axis. Any 3x3 rotation matrix can + be stored as a quaternion. + + A quaternion represents the sum of a real scalar and + an imaginary vector: ix + jy + kz + w. A unit quaternion + representing a rotation by A about axis v has the form + [sin(A/2)*v, cos(A/2)]. For a unit quaternion, q.conj() == q.inverse() + is a rotation by -A about v. -q is the same rotation as q + (negate both the axis and angle). + + A non-unit quaterion q represents the same rotation as + q.unitize() (Dam98 pg 28). + + Although quaternion-vector operations (eg. Quat + Vector3) are + well defined, they are not supported by this class because + they typically are bugs when they appear in code. + + Do not subclass. + + BETA API -- subject to change + @cite Erik B. Dam, Martin Koch, Martin Lillholm, Quaternions, Interpolation and Animation. Technical Report DIKU-TR-98/5, Department of Computer Science, University of Copenhagen, Denmark. 1998. + */ +class Quat { +private: + // Hidden operators + bool operator<(const Quat&) const; + bool operator>(const Quat&) const; + bool operator<=(const Quat&) const; + bool operator>=(const Quat&) const; + +public: + + /** + q = [sin(angle / 2) * axis, cos(angle / 2)] + + In Watt & Watt's notation, s = w, v = (x, y, z) + In the Real-Time Rendering notation, u = (x, y, z), w = w + */ + float x, y, z, w; + + /** + Initializes to a zero degree rotation. + */ + inline Quat() : x(0), y(0), z(0), w(1) {} + + Quat( + const Matrix3& rot); + + inline Quat(float _x, float _y, float _z, float _w) : + x(_x), y(_y), z(_z), w(_w) {} + + /** Defaults to a pure vector quaternion */ + inline Quat(const Vector3& v, float _w = 0) : x(v.x), y(v.y), z(v.z), w(_w) { + } + + /** + The real part of the quaternion. + */ + inline const float& real() const { + return w; + } + + inline float& real() { + return w; + } + + /** Note: two quats can represent the Quat::sameRotation and not be equal. */ + bool fuzzyEq(const Quat& q) { + return G3D::fuzzyEq(x, q.x) && G3D::fuzzyEq(y, q.y) && G3D::fuzzyEq(z, q.z) && G3D::fuzzyEq(w, q.w); + } + + /** True if these quaternions represent the same rotation (note that every rotation is + represented by two values; q and -q). + */ + bool sameRotation(const Quat& q) { + return fuzzyEq(q) || fuzzyEq(-q); + } + + inline Quat operator-() const { + return Quat(-x, -y, -z, -w); + } + + /** + Returns the imaginary part (x, y, z) + */ + inline const Vector3& imag() const { + return *(reinterpret_cast(this)); + } + + inline Vector3& imag() { + return *(reinterpret_cast(this)); + } + + /** q = [sin(angle/2)*axis, cos(angle/2)] */ + static Quat fromAxisAngleRotation( + const Vector3& axis, + float angle); + + /** Returns the axis and angle of rotation represented + by this quaternion (i.e. q = [sin(angle/2)*axis, cos(angle/2)]) */ + void toAxisAngleRotation( + Vector3& axis, + double& angle) const; + + void toAxisAngleRotation( + Vector3& axis, + float& angle) const { + double d; + toAxisAngleRotation(axis, d); + angle = (float)d; + } + + Matrix3 toRotationMatrix() const; + + void toRotationMatrix( + Matrix3& rot) const; + + /** + Spherical linear interpolation: linear interpolation along the + shortest (3D) great-circle route between two quaternions. + + Note: Correct rotations are expected between 0 and PI in the right order. + + @cite Based on Game Physics -- David Eberly pg 538-540 + @param threshold Critical angle between between rotations at which + the algorithm switches to normalized lerp, which is more + numerically stable in those situations. 0.0 will always slerp. + */ + Quat slerp( + const Quat& other, + float alpha, + float threshold = 0.05f) const; + + /** Normalized linear interpolation of quaternion components. */ + Quat nlerp(const Quat& other, float alpha) const; + + /** + Negates the imaginary part. + */ + inline Quat conj() const { + return Quat(-x, -y, -z, w); + } + + inline float sum() const { + return x + y + z + w; + } + + inline float average() const { + return sum() / 4.0f; + } + + inline Quat operator*(float s) const { + return Quat(x * s, y * s, z * s, w * s); + } + + inline Quat& operator*=(float s) { + x *= s; + y *= s; + z *= s; + w *= s; + return *this; + } + + /** @cite Based on Watt & Watt, page 360 */ + friend Quat operator* (float s, const Quat& q); + + inline Quat operator/(float s) const { + return Quat(x / s, y / s, z / s, w / s); + } + + inline float dot(const Quat& other) const { + return (x * other.x) + (y * other.y) + (z * other.z) + (w * other.w); + } + + /** Note that q-1 = q.conj() for a unit quaternion. + @cite Dam99 page 13 */ + inline Quat inverse() const { + return conj() / dot(*this); + } + + Quat operator-(const Quat& other) const; + + Quat operator+(const Quat& other) const; + + /** + Quaternion multiplication (composition of rotations). + Note that this does not commute. + */ + Quat operator*(const Quat& other) const; + + /* (*this) * other.inverse() */ + Quat operator/(const Quat& other) const { + return (*this) * other.inverse(); + } + + + /** Is the magnitude nearly 1.0? */ + inline bool isUnit(float tolerance = 1e-5) const { + return abs(dot(*this) - 1.0f) < tolerance; + } + + + inline float magnitude() const { + return sqrtf(dot(*this)); + } + + inline Quat log() const { + if ((x == 0) && (y == 0) && (z == 0)) { + if (w > 0) { + return Quat(0, 0, 0, ::logf(w)); + } else if (w < 0) { + // Log of a negative number. Multivalued, any number of the form + // (PI * v, ln(-q.w)) + return Quat((float)pi(), 0, 0, ::logf(-w)); + } else { + // log of zero! + return Quat((float)nan(), (float)nan(), (float)nan(), (float)nan()); + } + } else { + // Partly imaginary. + float imagLen = sqrtf(x * x + y * y + z * z); + float len = sqrtf(imagLen * imagLen + w * w); + float theta = atan2f(imagLen, (float)w); + float t = theta / imagLen; + return Quat(t * x, t * y, t * z, ::logf(len)); + } + } + /** log q = [Av, 0] where q = [sin(A) * v, cos(A)]. + Only for unit quaternions + debugAssertM(isUnit(), "Log only defined for unit quaternions"); + // Solve for A in q = [sin(A)*v, cos(A)] + Vector3 u(x, y, z); + double len = u.magnitude(); + + if (len == 0.0) { + return + } + double A = atan2((double)w, len); + Vector3 v = u / len; + + return Quat(v * A, 0); + } + */ + + /** exp q = [sin(A) * v, cos(A)] where q = [Av, 0]. + Only defined for pure-vector quaternions */ + inline Quat exp() const { + debugAssertM(w == 0, "exp only defined for vector quaternions"); + Vector3 u(x, y, z); + float A = u.magnitude(); + Vector3 v = u / A; + return Quat(sinf(A) * v, cosf(A)); + } + + + /** + Raise this quaternion to a power. For a rotation, this is + the effect of rotating x times as much as the original + quaterion. + + Note that q.pow(a).pow(b) == q.pow(a + b) + @cite Dam98 pg 21 + */ + inline Quat pow(float x) const { + return (log() * x).exp(); + } + + inline void unitize() { + float mag2 = dot(*this); + if (! G3D::fuzzyEq(mag2, 1.0f)) { + *this *= rsq(mag2); + } + } + + /** + Returns a unit quaterion obtained by dividing through by + the magnitude. + */ + inline Quat toUnit() const { + Quat x = *this; + x.unitize(); + return x; + } + + /** + The linear algebra 2-norm, sqrt(q dot q). This matches + the value used in Dam's 1998 tech report but differs from the + n(q) value used in Eberly's 1999 paper, which is the square of the + norm. + */ + inline float norm() const { + return magnitude(); + } + + // access quaternion as q[0] = q.x, q[1] = q.y, q[2] = q.z, q[3] = q.w + // + // WARNING. These member functions rely on + // (1) Quat not having virtual functions + // (2) the data packed in a 4*sizeof(float) memory block + const float& operator[] (int i) const; + float& operator[] (int i); + + /** Generate uniform random unit quaternion (i.e. random "direction") + @cite From "Uniform Random Rotations", Ken Shoemake, Graphics Gems III. + */ + static Quat unitRandom(); + + void deserialize(class BinaryInput& b); + void serialize(class BinaryOutput& b) const; + + // 2-char swizzles + + Vector2 xx() const; + Vector2 yx() const; + Vector2 zx() const; + Vector2 wx() const; + Vector2 xy() const; + Vector2 yy() const; + Vector2 zy() const; + Vector2 wy() const; + Vector2 xz() const; + Vector2 yz() const; + Vector2 zz() const; + Vector2 wz() const; + Vector2 xw() const; + Vector2 yw() const; + Vector2 zw() const; + Vector2 ww() const; + + // 3-char swizzles + + Vector3 xxx() const; + Vector3 yxx() const; + Vector3 zxx() const; + Vector3 wxx() const; + Vector3 xyx() const; + Vector3 yyx() const; + Vector3 zyx() const; + Vector3 wyx() const; + Vector3 xzx() const; + Vector3 yzx() const; + Vector3 zzx() const; + Vector3 wzx() const; + Vector3 xwx() const; + Vector3 ywx() const; + Vector3 zwx() const; + Vector3 wwx() const; + Vector3 xxy() const; + Vector3 yxy() const; + Vector3 zxy() const; + Vector3 wxy() const; + Vector3 xyy() const; + Vector3 yyy() const; + Vector3 zyy() const; + Vector3 wyy() const; + Vector3 xzy() const; + Vector3 yzy() const; + Vector3 zzy() const; + Vector3 wzy() const; + Vector3 xwy() const; + Vector3 ywy() const; + Vector3 zwy() const; + Vector3 wwy() const; + Vector3 xxz() const; + Vector3 yxz() const; + Vector3 zxz() const; + Vector3 wxz() const; + Vector3 xyz() const; + Vector3 yyz() const; + Vector3 zyz() const; + Vector3 wyz() const; + Vector3 xzz() const; + Vector3 yzz() const; + Vector3 zzz() const; + Vector3 wzz() const; + Vector3 xwz() const; + Vector3 ywz() const; + Vector3 zwz() const; + Vector3 wwz() const; + Vector3 xxw() const; + Vector3 yxw() const; + Vector3 zxw() const; + Vector3 wxw() const; + Vector3 xyw() const; + Vector3 yyw() const; + Vector3 zyw() const; + Vector3 wyw() const; + Vector3 xzw() const; + Vector3 yzw() const; + Vector3 zzw() const; + Vector3 wzw() const; + Vector3 xww() const; + Vector3 yww() const; + Vector3 zww() const; + Vector3 www() const; + + // 4-char swizzles + + Vector4 xxxx() const; + Vector4 yxxx() const; + Vector4 zxxx() const; + Vector4 wxxx() const; + Vector4 xyxx() const; + Vector4 yyxx() const; + Vector4 zyxx() const; + Vector4 wyxx() const; + Vector4 xzxx() const; + Vector4 yzxx() const; + Vector4 zzxx() const; + Vector4 wzxx() const; + Vector4 xwxx() const; + Vector4 ywxx() const; + Vector4 zwxx() const; + Vector4 wwxx() const; + Vector4 xxyx() const; + Vector4 yxyx() const; + Vector4 zxyx() const; + Vector4 wxyx() const; + Vector4 xyyx() const; + Vector4 yyyx() const; + Vector4 zyyx() const; + Vector4 wyyx() const; + Vector4 xzyx() const; + Vector4 yzyx() const; + Vector4 zzyx() const; + Vector4 wzyx() const; + Vector4 xwyx() const; + Vector4 ywyx() const; + Vector4 zwyx() const; + Vector4 wwyx() const; + Vector4 xxzx() const; + Vector4 yxzx() const; + Vector4 zxzx() const; + Vector4 wxzx() const; + Vector4 xyzx() const; + Vector4 yyzx() const; + Vector4 zyzx() const; + Vector4 wyzx() const; + Vector4 xzzx() const; + Vector4 yzzx() const; + Vector4 zzzx() const; + Vector4 wzzx() const; + Vector4 xwzx() const; + Vector4 ywzx() const; + Vector4 zwzx() const; + Vector4 wwzx() const; + Vector4 xxwx() const; + Vector4 yxwx() const; + Vector4 zxwx() const; + Vector4 wxwx() const; + Vector4 xywx() const; + Vector4 yywx() const; + Vector4 zywx() const; + Vector4 wywx() const; + Vector4 xzwx() const; + Vector4 yzwx() const; + Vector4 zzwx() const; + Vector4 wzwx() const; + Vector4 xwwx() const; + Vector4 ywwx() const; + Vector4 zwwx() const; + Vector4 wwwx() const; + Vector4 xxxy() const; + Vector4 yxxy() const; + Vector4 zxxy() const; + Vector4 wxxy() const; + Vector4 xyxy() const; + Vector4 yyxy() const; + Vector4 zyxy() const; + Vector4 wyxy() const; + Vector4 xzxy() const; + Vector4 yzxy() const; + Vector4 zzxy() const; + Vector4 wzxy() const; + Vector4 xwxy() const; + Vector4 ywxy() const; + Vector4 zwxy() const; + Vector4 wwxy() const; + Vector4 xxyy() const; + Vector4 yxyy() const; + Vector4 zxyy() const; + Vector4 wxyy() const; + Vector4 xyyy() const; + Vector4 yyyy() const; + Vector4 zyyy() const; + Vector4 wyyy() const; + Vector4 xzyy() const; + Vector4 yzyy() const; + Vector4 zzyy() const; + Vector4 wzyy() const; + Vector4 xwyy() const; + Vector4 ywyy() const; + Vector4 zwyy() const; + Vector4 wwyy() const; + Vector4 xxzy() const; + Vector4 yxzy() const; + Vector4 zxzy() const; + Vector4 wxzy() const; + Vector4 xyzy() const; + Vector4 yyzy() const; + Vector4 zyzy() const; + Vector4 wyzy() const; + Vector4 xzzy() const; + Vector4 yzzy() const; + Vector4 zzzy() const; + Vector4 wzzy() const; + Vector4 xwzy() const; + Vector4 ywzy() const; + Vector4 zwzy() const; + Vector4 wwzy() const; + Vector4 xxwy() const; + Vector4 yxwy() const; + Vector4 zxwy() const; + Vector4 wxwy() const; + Vector4 xywy() const; + Vector4 yywy() const; + Vector4 zywy() const; + Vector4 wywy() const; + Vector4 xzwy() const; + Vector4 yzwy() const; + Vector4 zzwy() const; + Vector4 wzwy() const; + Vector4 xwwy() const; + Vector4 ywwy() const; + Vector4 zwwy() const; + Vector4 wwwy() const; + Vector4 xxxz() const; + Vector4 yxxz() const; + Vector4 zxxz() const; + Vector4 wxxz() const; + Vector4 xyxz() const; + Vector4 yyxz() const; + Vector4 zyxz() const; + Vector4 wyxz() const; + Vector4 xzxz() const; + Vector4 yzxz() const; + Vector4 zzxz() const; + Vector4 wzxz() const; + Vector4 xwxz() const; + Vector4 ywxz() const; + Vector4 zwxz() const; + Vector4 wwxz() const; + Vector4 xxyz() const; + Vector4 yxyz() const; + Vector4 zxyz() const; + Vector4 wxyz() const; + Vector4 xyyz() const; + Vector4 yyyz() const; + Vector4 zyyz() const; + Vector4 wyyz() const; + Vector4 xzyz() const; + Vector4 yzyz() const; + Vector4 zzyz() const; + Vector4 wzyz() const; + Vector4 xwyz() const; + Vector4 ywyz() const; + Vector4 zwyz() const; + Vector4 wwyz() const; + Vector4 xxzz() const; + Vector4 yxzz() const; + Vector4 zxzz() const; + Vector4 wxzz() const; + Vector4 xyzz() const; + Vector4 yyzz() const; + Vector4 zyzz() const; + Vector4 wyzz() const; + Vector4 xzzz() const; + Vector4 yzzz() const; + Vector4 zzzz() const; + Vector4 wzzz() const; + Vector4 xwzz() const; + Vector4 ywzz() const; + Vector4 zwzz() const; + Vector4 wwzz() const; + Vector4 xxwz() const; + Vector4 yxwz() const; + Vector4 zxwz() const; + Vector4 wxwz() const; + Vector4 xywz() const; + Vector4 yywz() const; + Vector4 zywz() const; + Vector4 wywz() const; + Vector4 xzwz() const; + Vector4 yzwz() const; + Vector4 zzwz() const; + Vector4 wzwz() const; + Vector4 xwwz() const; + Vector4 ywwz() const; + Vector4 zwwz() const; + Vector4 wwwz() const; + Vector4 xxxw() const; + Vector4 yxxw() const; + Vector4 zxxw() const; + Vector4 wxxw() const; + Vector4 xyxw() const; + Vector4 yyxw() const; + Vector4 zyxw() const; + Vector4 wyxw() const; + Vector4 xzxw() const; + Vector4 yzxw() const; + Vector4 zzxw() const; + Vector4 wzxw() const; + Vector4 xwxw() const; + Vector4 ywxw() const; + Vector4 zwxw() const; + Vector4 wwxw() const; + Vector4 xxyw() const; + Vector4 yxyw() const; + Vector4 zxyw() const; + Vector4 wxyw() const; + Vector4 xyyw() const; + Vector4 yyyw() const; + Vector4 zyyw() const; + Vector4 wyyw() const; + Vector4 xzyw() const; + Vector4 yzyw() const; + Vector4 zzyw() const; + Vector4 wzyw() const; + Vector4 xwyw() const; + Vector4 ywyw() const; + Vector4 zwyw() const; + Vector4 wwyw() const; + Vector4 xxzw() const; + Vector4 yxzw() const; + Vector4 zxzw() const; + Vector4 wxzw() const; + Vector4 xyzw() const; + Vector4 yyzw() const; + Vector4 zyzw() const; + Vector4 wyzw() const; + Vector4 xzzw() const; + Vector4 yzzw() const; + Vector4 zzzw() const; + Vector4 wzzw() const; + Vector4 xwzw() const; + Vector4 ywzw() const; + Vector4 zwzw() const; + Vector4 wwzw() const; + Vector4 xxww() const; + Vector4 yxww() const; + Vector4 zxww() const; + Vector4 wxww() const; + Vector4 xyww() const; + Vector4 yyww() const; + Vector4 zyww() const; + Vector4 wyww() const; + Vector4 xzww() const; + Vector4 yzww() const; + Vector4 zzww() const; + Vector4 wzww() const; + Vector4 xwww() const; + Vector4 ywww() const; + Vector4 zwww() const; + Vector4 wwww() const; +}; + +inline Quat exp(const Quat& q) { + return q.exp(); +} + +inline Quat log(const Quat& q) { + return q.log(); +} + +inline G3D::Quat operator*(double s, const G3D::Quat& q) { + return q * (float)s; +} + +inline G3D::Quat operator*(float s, const G3D::Quat& q) { + return q * s; +} + +inline float& Quat::operator[] (int i) { + debugAssert(i >= 0); + debugAssert(i < 4); + return ((float*)this)[i]; +} + +inline const float& Quat::operator[] (int i) const { + debugAssert(i >= 0); + debugAssert(i < 4); + return ((float*)this)[i]; +} + +inline Quat Quat::operator-(const Quat& other) const { + return Quat(x - other.x, y - other.y, z - other.z, w - other.w); +} + +inline Quat Quat::operator+(const Quat& other) const { + return Quat(x + other.x, y + other.y, z + other.z, w + other.w); +} + +} // Namespace G3D + +// Outside the namespace to avoid overloading confusion for C++ +inline G3D::Quat pow(const G3D::Quat& q, double x) { + return q.pow((float)x); +} + + +#endif diff --git a/dep/g3dlite/G3D/Quat.inl b/dep/g3dlite/G3D/Quat.inl new file mode 100644 index 00000000000..9e4c861d93b --- /dev/null +++ b/dep/g3dlite/G3D/Quat.inl @@ -0,0 +1,36 @@ +/** + Quat.inl + + @cite Quaternion implementation based on Watt & Watt page 363. + Thanks to Max McGuire for slerp optimizations. + + @maintainer Morgan McGuire, matrix@graphics3d.com + + @created 2002-01-23 + @edited 2004-03-04 + */ + +namespace G3D { + +inline float& Quat::operator[] (int i) { + debugAssert(i >= 0); + debugAssert(i < 4); + return ((float*)this)[i]; +} + +inline const float& Quat::operator[] (int i) const { + debugAssert(i >= 0); + debugAssert(i < 4); + return ((float*)this)[i]; +} + +inline Quat Quat::operator-(const Quat& other) const { + return Quat(x - other.x, y - other.y, z - other.z, w - other.w); +} + +inline Quat Quat::operator+(const Quat& other) const { + return Quat(x + other.x, y + other.y, z + other.z, w + other.w); +} + +} + diff --git a/dep/g3dlite/G3D/Queue.h b/dep/g3dlite/G3D/Queue.h new file mode 100644 index 00000000000..36573265d1a --- /dev/null +++ b/dep/g3dlite/G3D/Queue.h @@ -0,0 +1,364 @@ +/** + @file Queue.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2002-07-09 + @edited 2008-12-20 + */ + +#ifndef G3D_QUEUE_H +#define G3D_QUEUE_H + +#include "G3D/platform.h" +#include "G3D/System.h" +#include "G3D/debug.h" + +namespace G3D { + +/** + Locate the indices of the break between of the two + sections of the circular queue. These are used to + construct two for loops that iterate over the whole + sequence without using the modulo operator. + + [0 ... secondEnd) [head .... firstEnd) + */ +#define FIND_ENDS \ + int firstEnd = head + num;\ + int secondEnd = 0;\ + if (firstEnd > numAllocated) {\ + secondEnd = firstEnd - numAllocated;\ + firstEnd = numAllocated;\ + } + + +/** + Dynamic queue that uses a circular buffer for performance. + + Faster than std::deque for objects with constructors. + */ +template +class Queue { +private: + // + // |<---- num ---->| + // [ | | | | | | | | | | | | | ] + // ^ + // | + // head + // + // + + /** + Only num elements are initialized. + */ + T* data; + + /** + Index of the next element to be dequeue-d in data. + */ + int head; + + /** + Number of elements (including head) that are visible and initialized. + */ + int num; + + /** + Size of data array in elements. + */ + int numAllocated; + + /** If a clear was needed, assumes it already occured */ + void _copy(const Queue& other) { + debugAssert(data == NULL); + data = (T*)System::malloc(sizeof(T) * other.numAllocated); + debugAssert(data); + head = other.head; + num = other.num; + numAllocated = other.numAllocated; + + FIND_ENDS; + + for (int i = head; i < firstEnd; ++i) { + new (data + i)T(other.data[i]); + } + + for (int i = 0; i < secondEnd; ++i) { + new (data + i)T(other.data[i]); + } + } + + + /** + Computes a data array index from a queue position. The queue position + may be negative. + */ + inline int index(int i) const { + return (head + i + numAllocated) % numAllocated; + } + + /** + Allocates newSize elements and repacks the array. + */ + void repackAndRealloc(int newSize) { + // TODO: shrink queue + T* old = data; + data = (T*)System::malloc(newSize * sizeof(T)); + debugAssert(data != NULL); + + FIND_ENDS; + + int j = 0; + for (int i = head; i < firstEnd; ++i, ++j) { + new (data + j)T(old[i]); + (old + i)->~T(); + } + + for (int i = 0; i < secondEnd; ++i, ++j) { + new (data + j)T(old[i]); + (old + i)->~T(); + } + + head = 0; + System::free(old); + numAllocated = newSize; + } + + /** + Ensure that there is at least one element between + the tail and head, wrapping around in the circular + buffer. + */ + inline void reserveSpace() { + if (num == numAllocated) { + repackAndRealloc(numAllocated * 3 + 20); + } + } + +public: + + Queue() : + data(NULL), + head(0), + num(0), + numAllocated(0) { + } + + + /** + Copy constructor + */ + Queue(const Queue& other) : data(NULL) { + _copy(other); + } + + + /** + Destructor does not delete() the objects if T is a pointer type + (e.g. T = int*) instead, it deletes the pointers themselves and + leaves the objects. Call deleteAll if you want to dealocate + the objects referenced. + */ + virtual ~Queue() { + clear(); + } + + /** + Insert a new element into the front of the queue + (a traditional queue only uses pushBack). + */ + inline void pushFront(const T& e) { + reserveSpace(); + + // Get the index of head-1 + int i = index(-1); + + // Call the constructor on the newly exposed element. + new (data + i)T(e); + + // Reassign the head to point to this index + head = i; + ++num; + } + + /** + Insert a new element at the end of the queue. + */ + inline void pushBack(const T& e) { + reserveSpace(); + + // Get the index of 1+tail + int i = index(num); + + // Initialize that element + new (data + i)T(e); + ++num; + } + + /** + pushBack + */ + inline void enqueue(const T& e) { + pushBack(e); + } + + + /** + Remove the last element from the queue. The queue will never + shrink in size. (A typical queue only uses popFront). + */ + inline T popBack() { + int tail = index(num - 1); + T result(data[tail]); + + // Call the destructor + (data + tail)->~T(); + --num; + + return result; + } + + /** + Remove the next element from the head of the queue. The queue will never + shrink in size. */ + inline T popFront() { + T result(data[head]); + // Call the destructor + (data + head)->~T(); + head = (head + 1) % numAllocated; + --num; + return result; + } + + + /** + popFront + */ + inline T dequeue() { + return popFront(); + } + + /** + Removes all elements (invoking their destructors). + + @param freeStorage If false, the underlying array is not deallocated + (allowing fast push in the future), however, the size of the Queue + is reported as zero. + + */ + void clear(bool freeStorage = true) { + + FIND_ENDS; + + // Invoke the destructors on the elements + int i; + for (i = head; i < firstEnd; ++i) { + (data + i)->~T(); + } + + for (i = 0; i < secondEnd; ++i) { + (data + i)->~T(); + } + + num = 0; + head = 0; + if (freeStorage) { + numAllocated = 0; + System::free(data); + data = NULL; + } + } + + /** Clear without freeing the underlying array. */ + void fastClear() { + clear(false); + } + + /** + Assignment operator. + */ + Queue& operator=(const Queue& other) { + clear(); + _copy(other); + return *this; + } + + /** + Number of elements in the queue. + */ + inline int size() const { + return num; + } + + /** + Number of elements in the queue. + */ + inline int length() const { + return size(); + } + + /** + Performs bounds checks in debug mode + */ + inline T& operator[](int n) { + debugAssert((n >= 0) && (n < num)); + return data[index(n)]; + } + + /** + Performs bounds checks in debug mode + */ + inline const T& operator[](int n) const { + debugAssert((n >= 0) && (n < num)); + return data[index(n)]; + } + + + /** Returns the back element */ + inline const T& last() const { + return (*this)[size() - 1]; + } + + inline T& last() { + return (*this)[size() - 1]; + } + + /** + Returns true if the given element is in the queue. + */ + bool contains(const T& e) const { + for (int i = 0; i < size(); ++i) { + if ((*this)[i] == e) { + return true; + } + } + + return false; + } + + /** + Calls delete on all objects[0...size-1] + and sets the queue size to zero. + */ + void deleteAll() { + FIND_ENDS; + + int i; + for (i = 0; i < secondEnd; ++i) { + delete data[i]; + } + + for (i = head; i < firstEnd; ++i) { + delete data[i]; + } + clear(); + } +}; + +#undef FIND_ENDS + +}; // namespace + +#endif diff --git a/dep/g3dlite/G3D/Random.h b/dep/g3dlite/G3D/Random.h new file mode 100644 index 00000000000..54491d06f1b --- /dev/null +++ b/dep/g3dlite/G3D/Random.h @@ -0,0 +1,139 @@ +/** + @file Random.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2009-01-02 + @edited 2009-03-20 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ +#ifndef G3D_Random_h +#define G3D_Random_h + +#include "G3D/platform.h" +#include "G3D/g3dmath.h" +#include "G3D/GMutex.h" + +namespace G3D { + +/** Random number generator. + + Threadsafe. + + Useful for generating consistent random numbers across platforms + and when multiple threads are involved. + + Uses the Fast Mersenne Twister (FMT-19937) algorithm. + + On average, uniform() runs about 2x-3x faster than rand(). + + @cite http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/index.html + + On OS X, Random is about 10x faster than drand48() (which is + threadsafe) and 4x faster than rand() (which is not threadsafe). + */ +class Random { +protected: + + /** Constants (important for the algorithm; do not modify) */ + enum { + N = 624, + M = 397, + R = 31, + U = 11, + S = 7, + T = 15, + L = 18, + A = 0x9908B0DF, + B = 0x9D2C5680, + C = 0xEFC60000}; + + /** + Prevents multiple overlapping calls to generate(). + */ + Spinlock lock; + + /** State vector (these are the next N values that will be returned) */ + uint32* state; + + /** Index into state */ + int index; + + bool m_threadsafe; + + /** Generate the next N ints, and store them for readback later. + Called from bits() */ + virtual void generate(); + + /** For subclasses. The void* parameter is just to distinguish this from the + public constructor.*/ + Random(void*); + +public: + + /** \param threadsafe Set to false if you know that this random + will only be used on a single thread. This eliminates the + lock and improves performance on some platforms. + */ + Random(uint32 seed = 0xF018A4D2, bool threadsafe = true); + + virtual ~Random(); + + /** Each bit is random. Subclasses can choose to override just + this method and the other methods will all work automatically. */ + virtual uint32 bits(); + + /** Uniform random integer on the range [min, max] */ + virtual int integer(int min, int max); + + /** Uniform random float on the range [min, max] */ + virtual inline float uniform(float low, float high) { + // We could compute the ratio in double precision here for + // about 1.5x slower performance and slightly better + // precision. + return low + (high - low) * ((float)bits() / (float)0xFFFFFFFFUL); + } + + /** Uniform random float on the range [0, 1] */ + virtual inline float uniform() { + // We could compute the ratio in double precision here for + // about 1.5x slower performance and slightly better + // precision. + const float norm = 1.0f / (float)0xFFFFFFFFUL; + return (float)bits() * norm; + } + + /** Normally distributed reals. */ + virtual float gaussian(float mean, float stdev); + + /** Returns 3D unit vectors distributed according to + a cosine distribution about the z-axis. */ + virtual void cosHemi(float& x, float& y, float& z); + + /** Returns 3D unit vectors distributed according to a cosine + power distribution (\f$ \cos^k \theta \f$) about + the z-axis. */ + virtual void cosPowHemi(const float k, float& x, float& y, float& z); + + /** Returns 3D unit vectors uniformly distributed on the + hemisphere about the z-axis. */ + virtual void hemi(float& x, float& y, float& z); + + /** Returns 3D unit vectors uniformly distributed on the sphere */ + virtual void sphere(float& x, float& y, float& z); + + /** + A shared instance for when the performance and features but not + consistency of the class are desired. It is slightly (10%) + faster to use a distinct instance than to use the common one. + + Threadsafe. + */ + static Random& common(); +}; + +} + +#endif diff --git a/dep/g3dlite/G3D/Ray.h b/dep/g3dlite/G3D/Ray.h new file mode 100644 index 00000000000..bfee9243343 --- /dev/null +++ b/dep/g3dlite/G3D/Ray.h @@ -0,0 +1,371 @@ +/** + @file Ray.h + + Ray class + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2002-07-12 + @edited 2009-06-29 + */ + +#ifndef G3D_Ray_h +#define G3D_Ray_h + +#include "G3D/platform.h" +#include "G3D/Vector3.h" +#include "G3D/Triangle.h" + +namespace G3D { + +/** + A 3D Ray. + */ +class Ray { +private: + friend class Intersect; + + Vector3 m_origin; + + /** Unit length */ + Vector3 m_direction; + + /** 1.0 / direction */ + Vector3 m_invDirection; + + + // The following are for the "ray slope" optimization from + // "Fast Ray / Axis-Aligned Bounding Box Overlap Tests using Ray Slopes" + // by Martin Eisemann, Thorsten Grosch, Stefan Müller and Marcus Magnor + // Computer Graphics Lab, TU Braunschweig, Germany and + // University of Koblenz-Landau, Germany*/ + enum Classification {MMM, MMP, MPM, MPP, PMM, PMP, PPM, PPP, POO, MOO, OPO, OMO, OOP, OOM, OMM, OMP, OPM, OPP, MOM, MOP, POM, POP, MMO, MPO, PMO, PPO}; Classification classification; + // ray slope + float ibyj, jbyi, kbyj, jbyk, ibyk, kbyi; + // Precomputed components + float c_xy, c_xz, c_yx, c_yz, c_zx, c_zy; + +public: + + void set(const Vector3& origin, const Vector3& direction); + + inline const Vector3& origin() const { + return m_origin; + } + + /** Unit direction vector. */ + inline const Vector3& direction() const { + return m_direction; + } + + /** Component-wise inverse of direction vector. May have inf() components */ + inline const Vector3& invDirection() const { + return m_invDirection; + } + + inline Ray() { + set(Vector3::zero(), Vector3::unitX()); + } + + inline Ray(const Vector3& origin, const Vector3& direction) { + set(origin, direction); + } + + Ray(class BinaryInput& b); + + void serialize(class BinaryOutput& b) const; + void deserialize(class BinaryInput& b); + + /** + Creates a Ray from a origin and a (nonzero) unit direction. + */ + static Ray fromOriginAndDirection(const Vector3& point, const Vector3& direction) { + return Ray(point, direction); + } + + /** Advances the origin along the direction by @a distance */ + inline Ray bump(float distance) const { + return Ray(m_origin + m_direction * distance, m_direction); + } + + /** Advances the origin along the @a bumpDirection by @a distance and returns the new ray*/ + inline Ray bump(float distance, const Vector3& bumpDirection) const { + return Ray(m_origin + bumpDirection * distance, m_direction); + } + + /** + Returns the closest point on the Ray to point. + */ + Vector3 closestPoint(const Vector3& point) const { + float t = m_direction.dot(point - m_origin); + if (t < 0) { + return m_origin; + } else { + return m_origin + m_direction * t; + } + } + + /** + Returns the closest distance between point and the Ray + */ + float distance(const Vector3& point) const { + return (closestPoint(point) - point).magnitude(); + } + + /** + Returns the point where the Ray and plane intersect. If there + is no intersection, returns a point at infinity. + + Planes are considered one-sided, so the ray will not intersect + a plane where the normal faces in the traveling direction. + */ + Vector3 intersection(const class Plane& plane) const; + + /** + Returns the distance until intersection with the sphere or the (solid) ball bounded by the sphere. + Will be 0 if inside the sphere, inf if there is no intersection. + + The ray direction is not normalized. If the ray direction + has unit length, the distance from the origin to intersection + is equal to the time. If the direction does not have unit length, + the distance = time * direction.length(). + + See also the G3D::CollisionDetection "movingPoint" methods, + which give more information about the intersection. + + \param solid If true, rays inside the sphere immediately intersect (good for collision detection). If false, they hit the opposite side of the sphere (good for ray tracing). + */ + float intersectionTime(const class Sphere& sphere, bool solid = false) const; + + float intersectionTime(const class Plane& plane) const; + + float intersectionTime(const class Box& box) const; + + float intersectionTime(const class AABox& box) const; + + /** + The three extra arguments are the weights of vertices 0, 1, and 2 + at the intersection point; they are useful for texture mapping + and interpolated normals. + */ + float intersectionTime( + const Vector3& v0, const Vector3& v1, const Vector3& v2, + const Vector3& edge01, const Vector3& edge02, + double& w0, double& w1, double& w2) const; + + /** + Ray-triangle intersection for a 1-sided triangle. Fastest version. + @cite http://www.acm.org/jgt/papers/MollerTrumbore97/ + http://www.graphics.cornell.edu/pubs/1997/MT97.html + */ + inline float intersectionTime( + const Vector3& vert0, + const Vector3& vert1, + const Vector3& vert2, + const Vector3& edge01, + const Vector3& edge02) const; + + + inline float intersectionTime( + const Vector3& vert0, + const Vector3& vert1, + const Vector3& vert2) const { + + return intersectionTime(vert0, vert1, vert2, vert1 - vert0, vert2 - vert0); + } + + + inline float intersectionTime( + const Vector3& vert0, + const Vector3& vert1, + const Vector3& vert2, + double& w0, + double& w1, + double& w2) const { + + return intersectionTime(vert0, vert1, vert2, vert1 - vert0, vert2 - vert0, w0, w1, w2); + } + + /* One-sided triangle + */ + inline float intersectionTime(const Triangle& triangle) const { + return intersectionTime( + triangle.vertex(0), triangle.vertex(1), triangle.vertex(2), + triangle.edge01(), triangle.edge02()); + } + + inline float intersectionTime( + const Triangle& triangle, + double& w0, + double& w1, + double& w2) const { + return intersectionTime(triangle.vertex(0), triangle.vertex(1), triangle.vertex(2), + triangle.edge01(), triangle.edge02(), w0, w1, w2); + } + + /** Refracts about the normal + using G3D::Vector3::refractionDirection + and bumps the ray slightly from the newOrigin. */ + Ray refract( + const Vector3& newOrigin, + const Vector3& normal, + float iInside, + float iOutside) const; + + /** Reflects about the normal + using G3D::Vector3::reflectionDirection + and bumps the ray slightly from + the newOrigin. */ + Ray reflect( + const Vector3& newOrigin, + const Vector3& normal) const; +}; + + +#define EPSILON 0.000001 +#define CROSS(dest,v1,v2) \ + dest[0]=v1[1]*v2[2]-v1[2]*v2[1]; \ + dest[1]=v1[2]*v2[0]-v1[0]*v2[2]; \ + dest[2]=v1[0]*v2[1]-v1[1]*v2[0]; + +#define DOT(v1,v2) (v1[0]*v2[0]+v1[1]*v2[1]+v1[2]*v2[2]) + +#define SUB(dest,v1,v2) \ + dest[0]=v1[0]-v2[0]; \ + dest[1]=v1[1]-v2[1]; \ + dest[2]=v1[2]-v2[2]; + +inline float Ray::intersectionTime( + const Vector3& vert0, + const Vector3& vert1, + const Vector3& vert2, + const Vector3& edge1, + const Vector3& edge2) const { + + (void)vert1; + (void)vert2; + + // Barycenteric coords + float u, v; + + float tvec[3], pvec[3], qvec[3]; + + // begin calculating determinant - also used to calculate U parameter + CROSS(pvec, m_direction, edge2); + + // if determinant is near zero, ray lies in plane of triangle + const float det = DOT(edge1, pvec); + + if (det < EPSILON) { + return finf(); + } + + // calculate distance from vert0 to ray origin + SUB(tvec, m_origin, vert0); + + // calculate U parameter and test bounds + u = DOT(tvec, pvec); + if ((u < 0.0f) || (u > det)) { + // Hit the plane outside the triangle + return finf(); + } + + // prepare to test V parameter + CROSS(qvec, tvec, edge1); + + // calculate V parameter and test bounds + v = DOT(m_direction, qvec); + if ((v < 0.0f) || (u + v > det)) { + // Hit the plane outside the triangle + return finf(); + } + + + // Case where we don't need correct (u, v): + const float t = DOT(edge2, qvec); + + if (t >= 0.0f) { + // Note that det must be positive + return t / det; + } else { + // We had to travel backwards in time to intersect + return finf(); + } +} + + +inline float Ray::intersectionTime( + const Vector3& vert0, + const Vector3& vert1, + const Vector3& vert2, + const Vector3& edge1, + const Vector3& edge2, + double& w0, + double& w1, + double& w2) const { + + (void)vert1; + (void)vert2; + + // Barycenteric coords + float u, v; + + float tvec[3], pvec[3], qvec[3]; + + // begin calculating determinant - also used to calculate U parameter + CROSS(pvec, m_direction, edge2); + + // if determinant is near zero, ray lies in plane of triangle + const float det = DOT(edge1, pvec); + + if (det < EPSILON) { + return finf(); + } + + // calculate distance from vert0 to ray origin + SUB(tvec, m_origin, vert0); + + // calculate U parameter and test bounds + u = DOT(tvec, pvec); + if ((u < 0.0f) || (u > det)) { + // Hit the plane outside the triangle + return finf(); + } + + // prepare to test V parameter + CROSS(qvec, tvec, edge1); + + // calculate V parameter and test bounds + v = DOT(m_direction, qvec); + if ((v < 0.0f) || (u + v > det)) { + // Hit the plane outside the triangle + return finf(); + } + + float t = DOT(edge2, qvec); + + if (t >= 0) { + const float inv_det = 1.0f / det; + t *= inv_det; + u *= inv_det; + v *= inv_det; + + w0 = (1.0f - u - v); + w1 = u; + w2 = v; + + return t; + } else { + // We had to travel backwards in time to intersect + return finf(); + } +} + +#undef EPSILON +#undef CROSS +#undef DOT +#undef SUB + +}// namespace + +#endif diff --git a/dep/g3dlite/G3D/Rect2D.h b/dep/g3dlite/G3D/Rect2D.h new file mode 100644 index 00000000000..2fb58c50465 --- /dev/null +++ b/dep/g3dlite/G3D/Rect2D.h @@ -0,0 +1,417 @@ +/** + @file Rect2D.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2003-11-13 + @created 2009-11-16 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_Rect2D_h +#define G3D_Rect2D_h + +// Linux defines this as a macro +#ifdef border +#undef border +#endif + +#include "G3D/platform.h" +#include "G3D/Array.h" +#include "G3D/Vector2.h" + +#ifdef _MSC_VER +// Turn off "conditional expression is constant" warning; MSVC generates this +// for debug assertions in inlined methods. +# pragma warning (disable : 4127) +#endif + + +namespace G3D { + +class Any; + +/** + If you are using this class for pixel rectangles, keep in mind that the last + pixel you can draw to is at x0() + width() - 1. + */ +class Rect2D { +private: + Vector2 min, max; + + /** + Returns true if the whole polygon is clipped. + @param p Value of the point + @param axis Index [0 or 1] of the axis to clip along? + @param clipGreater Are we clipping greater than or less than the line? + @param inPoly Polygon being clipped + @param outPoly The clipped polygon + */ + template + static bool clipSide2D( + const float p, bool clipGreater, int axis, + const Array& inPoly, Array& outPoly) { + + outPoly.clear(); + int i0 = -1; + + Vector2 pt1; + bool c1 = true; + + float negate = clipGreater ? -1 : 1; + + // Find a point that is not clipped + for (i0 = 0; (i0 < inPoly.length()) && c1; ++i0) { + pt1 = inPoly[i0]; + c1 = (negate * pt1[axis]) < (negate * p); + } + + // We incremented i0 one time to many + --i0; + + if (c1) { + // We could not find an unclipped point + return true; + } + + outPoly.append(pt1); + + // for each point in inPoly, + // if the point is outside the side and the previous one was also outside, continue + // if the point is outside the side and the previous one was inside, cut the line + // if the point is inside the side and the previous one was also inside, append the points + // if the point is inside the side and the previous one was outside, cut the line + for (int i = 1; i <= inPoly.length(); ++i) { + T pt2 = inPoly[(i + i0) % inPoly.length()]; + bool c2 = (negate * pt2[axis]) < (negate * p); + + if (c1 ^ c2) { + + if (!c1 && c2 && (i > 1)) { + // Unclipped to clipped trasition and not the first iteration + outPoly.append(pt1); + } + + // only one point is clipped, find where the line crosses the clipping plane + + + float alpha; + if (pt2[axis] == pt1[axis]) { + alpha = 0; + } else { + alpha = (p - pt1[axis]) / (pt2[axis] - pt1[axis]); + } + outPoly.append(pt1.lerp(pt2, alpha)); + } else if (! (c1 || c2) && (i != 1)) { + // neither point is clipped (don't do this the first time + // because we appended the first pt before the loop) + outPoly.append(pt1); + } + + pt1 = pt2; + c1 = c2; + } + + return false; + } + +public: + + /** \param any Must either Rect2D::xywh(#, #, #, #) or Rect2D::xyxy(#, #, #, #)*/ + Rect2D(const Any& any); + + /** Converts the Rect2D to an Any. */ + operator Any() const; + + Rect2D() : min(0, 0), max(0, 0) {} + + /** Creates a rectangle at 0,0 with the given width and height*/ + Rect2D(const Vector2& wh) : min(0, 0), max(wh.x, wh.y) {} + + /** Computes a rectangle that contains both @a a and @a b. + Note that even if @a or @b has zero area, its origin will be included.*/ + Rect2D(const Rect2D& a, const Rect2D& b) { + min = a.min.min(b.min); + max = a.max.max(b.max); + } + + /** @brief Uniformly random point on the interior */ + Vector2 randomPoint() const { + return Vector2(uniformRandom(0, max.x - min.x) + min.x, + uniformRandom(0, max.y - min.y) + min.y); + } + + float width() const { + return max.x - min.x; + } + + float height() const { + return max.y - min.y; + } + + float x0() const { + return min.x; + } + + float x1() const { + return max.x; + } + + float y0() const { + return min.y; + } + + float y1() const { + return max.y; + } + + /** Min, min corner */ + Vector2 x0y0() const { + return min; + } + + Vector2 x1y0() const { + return Vector2(max.x, min.y); + } + + Vector2 x0y1() const { + return Vector2(min.x, max.y); + } + + /** Max,max corner */ + Vector2 x1y1() const { + return max; + } + + /** Width and height */ + Vector2 wh() const { + return max - min; + } + + Vector2 center() const { + return (max + min) * 0.5; + } + + float area() const { + return width() * height(); + } + + bool isFinite() const { + return (min.isFinite() && max.isFinite()); + } + + Rect2D lerp(const Rect2D& other, float alpha) const { + Rect2D out; + + out.min = min.lerp(other.min, alpha); + out.max = max.lerp(other.max, alpha); + + return out; + } + + static Rect2D xyxy(float x0, float y0, float x1, float y1) { + Rect2D r; + + r.min.x = G3D::min(x0, x1); + r.min.y = G3D::min(y0, y1); + r.max.x = G3D::max(x0, x1); + r.max.y = G3D::max(y0, y1); + + return r; + } + + static Rect2D xyxy(const Vector2& v0, const Vector2& v1) { + Rect2D r; + + r.min = v0.min(v1); + r.max = v0.max(v1); + + return r; + } + + static Rect2D xywh(float x, float y, float w, float h) { + return xyxy(x, y, x + w, y + h); + } + + static Rect2D xywh(const Vector2& v, const Vector2& w) { + return xyxy(v.x, v.y, v.x + w.x, v.y + w.y); + } + + /** Constructs a Rect2D with infinite boundaries. + Use isFinite() to test either min or max. + */ + static Rect2D inf() { + return xyxy(Vector2::inf(), Vector2::inf()); + } + + bool contains(const Vector2& v) const { + return (v.x >= min.x) && (v.y >= min.y) && (v.x <= max.x) && (v.y <= max.y); + } + + bool contains(const Rect2D& r) const { + return (min.x <= r.min.x) && (min.y <= r.min.y) && + (max.x >= r.max.x) && (max.y >= r.max.y); + } + + /** True if there is non-zero area to the intersection between @a this and @a r. + Note that two rectangles that are adjacent do not intersect because there is + zero area to the overlap, even though one of them "contains" the corners of the other.*/ + bool intersects(const Rect2D& r) const { + return (min.x < r.max.x) && (min.y < r.max.y) && + (max.x > r.min.x) && (max.y > r.min.y); + } + + /** Like intersection, but counts the adjacent case as touching. */ + bool intersectsOrTouches(const Rect2D& r) const { + return (min.x <= r.max.x) && (min.y <= r.max.y) && + (max.x >= r.min.x) && (max.y >= r.min.y); + } + + Rect2D operator*(float s) const { + return xyxy(min.x * s, min.y * s, max.x * s, max.y * s); + } + + Rect2D operator/(float s) const { + return xyxy(min / s, max / s); + } + + Rect2D operator/(const Vector2& s) const { + return xyxy(min / s, max / s); + } + + Rect2D operator+(const Vector2& v) const { + return xyxy(min + v, max + v); + } + + Rect2D operator-(const Vector2& v) const { + return xyxy(min - v, max - v); + } + + bool operator==(const Rect2D& other) const { + return (min == other.min) && (max == other.max); + } + + bool operator!=(const Rect2D& other) const { + return (min != other.min) || (max != other.max); + } + + /** Returns the corners in the order: (min,min), (max,min), (max,max), (min,max). */ + Vector2 corner(int i) const { + debugAssert(i >= 0 && i < 4); + switch (i & 3) { + case 0: + return Vector2(min.x, min.y); + case 1: + return Vector2(max.x, min.y); + case 2: + return Vector2(max.x, max.y); + case 3: + return Vector2(min.x, max.y); + default: + // Should never get here + return Vector2(0, 0); + } + } + + + /** @deprecated + @sa expand() */ + Rect2D border(float delta) const { + return Rect2D::xywh(x0() + delta, + y0() + delta, + width() - 2.0f * delta, + height() - 2.0f * delta); + } + + /** Returns a new Rect2D that is bigger/smaller by the specified amount + (negative is shrink.) */ + Rect2D expand(float delta) const { + float newX = x0() - delta; + float newY = y0() - delta; + float newW = width() + 2.0f * delta; + float newH = height() + 2.0f * delta; + + if (newW < 0.0f) { + newX = (x0() + width()) / 2.0f; + newW = 0.0f; + } + + if (newH < 0.0f) { + newY = (y0() + height()) / 2.0f; + newH = 0.0f; + } + return Rect2D::xywh(newX, newY, newW, newH); + } + + /** + Clips so that the rightmost point of the outPoly is at rect.x1 (e.g. a 800x600 window produces + rightmost point 799, not 800). The results are suitable for pixel rendering if iRounded. + Templated so that it will work for Vector2,3,4 (the z and w components are interpolated linearly). + The template parameter must define T.lerp and contain x and y components. + + If the entire polygon is clipped by a single side, the result will be empty. + The result might also have zero area but not be empty. + */ + template + void clip(const Array& inPoly, Array& outPoly) const { + + const bool greaterThan = true; + const bool lessThan = false; + const int X = 0; + const int Y = 1; + + Array temp; + + bool entirelyClipped = + clipSide2D(x0(), lessThan, X, inPoly, temp) || + clipSide2D(x1(), greaterThan, X, temp, outPoly) || + clipSide2D(y0(), lessThan, Y, outPoly, temp) || + clipSide2D(y1(), greaterThan, Y, temp, outPoly); + + if (entirelyClipped) { + outPoly.clear(); + } + } + + + /** Returns the largest, centered Rect2D that can fit inside this + while maintaining the aspect ratio of x:y. Convenient for + displaying images in odd-shaped windows. + */ + Rect2D largestCenteredSubRect(float ww, float hh) const { + float textureAspect = hh / ww; + float viewAspect = height() / width(); + + if (viewAspect > textureAspect) { + // The view is too tall + float h = width() * textureAspect; + float y = (height() - h) / 2; + return Rect2D::xywh(0, y, width(), h) + corner(0); + } else { + // The view is too wide + float w = height() / textureAspect; + float x = (width() - w) / 2; + return Rect2D::xywh(x, 0, w, height()) + corner(0); + } + } + + /** + Returns the overlap region between the two rectangles. This may have zero area + if they do not intersect. See the two-Rect2D constructor for a way to compute + a union-like rectangle. + */ + Rect2D intersect(const Rect2D& other) const { + if (intersects(other)) { + return Rect2D::xyxy(min.max(other.min), max.min(other.max)); + }else{ + return Rect2D::xywh(0, 0, 0, 0); + } + } +}; + +typedef Rect2D AABox2D; +} + +#endif diff --git a/dep/g3dlite/G3D/ReferenceCount.h b/dep/g3dlite/G3D/ReferenceCount.h new file mode 100644 index 00000000000..84591c6d8e5 --- /dev/null +++ b/dep/g3dlite/G3D/ReferenceCount.h @@ -0,0 +1,570 @@ +/** + @file ReferenceCount.h + + Reference Counting Garbage Collector for C++ + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + @cite Adapted and extended from Justin Miller's "RGC" class that appeared in BYTE magazine. + @cite See also http://www.jelovic.com/articles/cpp_without_memory_errors_slides.htm + + @created 2001-10-23 + @edited 2009-04-25 +*/ +#ifndef G3D_ReferenceCount_h +#define G3D_ReferenceCount_h + +#include "G3D/platform.h" +#include "G3D/debug.h" +#include "G3D/AtomicInt32.h" + +namespace G3D { + +#ifdef _MSC_VER +// Turn off "conditional expression is constant" warning; MSVC generates this +// for debug assertions in inlined methods. +# pragma warning (disable : 4127) +#endif + +/** Base class for WeakReferenceCountedPointer */ +class _WeakPtr { +public: + inline virtual ~_WeakPtr() {} + +protected: + friend class ReferenceCountedObject; + + /** Called by ReferenceCountedObject to tell a weak pointer that its underlying object was collected. */ + virtual void objectCollected() = 0; +}; + +/** Used internally by ReferenceCountedObject */ +class _WeakPtrLinkedList { +public: + _WeakPtr* weakPtr; + _WeakPtrLinkedList* next; + + inline _WeakPtrLinkedList() : weakPtr(NULL), next(NULL) {} + + /** Inserts this node into the head of the list that previously had n as its head. */ + inline _WeakPtrLinkedList(_WeakPtr* p, _WeakPtrLinkedList* n) : weakPtr(p), next(n) {} +}; + +/** + Objects that are reference counted inherit from this. Subclasses + must have a public destructor (the default destructor is fine) + and publicly inherit ReferenceCountedObject. + + Multiple inheritance from a reference counted object is dangerous-- use + at your own risk. + + ReferenceCountedPointer and ReferenceCountedObject are threadsafe. + You can create and drop references on multiple threads without + violating integrity. WeakReferenceCountedPointer is not + threadsafe. Introducing a weak pointer destroys all thread safety, + even for strong pointers to the same object (this is inherent in the + design of the class; we cannot fix it without slowing down the + performance of reference counted objects.) + + Usage Example + +
+
+class Foo : public G3D::ReferenceCountedObject {
+public:
+    int x;
+};
+
+class Bar : public Foo {};
+
+typedef G3D::ReferenceCountedPointer FooRef;
+typedef G3D::WeakReferenceCountedPointer WeakFooRef;
+typedef G3D::ReferenceCountedPointer BarRef;
+
+
+int main(int argc, char *argv[]) {
+
+    WeakFooRef x;
+
+    {
+        FooRef a = new Foo();
+
+        // Reference count == 1
+
+        x = a;
+        // Weak references do not increase count
+
+        {
+            FooRef b = a;
+            // Reference count == 2
+        }
+
+        // Reference count == 1
+    }
+    // No more strong references; object automatically deleted.
+    // x is set to NULL automatically.
+
+    // Example of using dynamic cast on reference counted objects
+    BarRef b = new Bar();
+
+    // No cast needed to go down the heirarchy.
+    FooRef f = b;
+
+    // We can't cast the reference object because it is a class.
+    // Instead we must extract the pointer and cast that:
+    b = dynamic_cast(&*f);
+
+    return 0;
+}
+
+ */ +class ReferenceCountedObject { +public: + + /** + The long name is to keep this from accidentally conflicting with + a subclass's variable name. Do not use or explicitly manipulate + this value--its type may change in the future and is not part + of the supported API. + */ + AtomicInt32 ReferenceCountedObject_refCount; + + /** + Linked list of all weak pointers that reference this (some may be + on the stack!). Do not use or explicitly manipulate this value. + */ + _WeakPtrLinkedList* ReferenceCountedObject_weakPointer; + +protected: + + ReferenceCountedObject(); + +public: + + /** Automatically called immediately before the object is deleted. + This is not called from the destructor because it needs to be invoked + before the subclass destructor. + */ + void ReferenceCountedObject_zeroWeakPointers(); + + virtual ~ReferenceCountedObject(); + + + /** + Note: copies will initially start out with 0 + references and 0 weak references like any other object. + */ + ReferenceCountedObject(const ReferenceCountedObject& notUsed); + + ReferenceCountedObject& operator=(const ReferenceCountedObject& other); +}; + + + +/** + Use ReferenceCountedPointer in place of T* in your program. + T must subclass ReferenceCountedObject. +@deprecated To be replaced by boost::shared_ptr in 7.0 + */ +template +class ReferenceCountedPointer { +private: + + T* m_pointer; + +public: + typedef T element_type; + + inline T* pointer() const { + return m_pointer; + } + +private: + + /** Nulls out the pointer and drops a reference. If the reference + count hits zero. */ + void zeroPointer() { + if (m_pointer != NULL) { + + ReferenceCountedObject* pointer = ((ReferenceCountedObject*)m_pointer); + debugAssert(G3D::isValidHeapPointer(m_pointer)); + debugAssertM(pointer->ReferenceCountedObject_refCount.value() > 0, + "Dangling reference detected."); + + // Only delete if this instance caused the count to hit + // exactly zero. If there is a race condition, the value + // may be zero after decrement returns, but only one of + // the instances will get a zero return value. + if (pointer->ReferenceCountedObject_refCount.decrement() == 0) { + // We held the last reference, so delete the object. + // This test is threadsafe because there is no way for + // the reference count to increase after the last + // reference was dropped (assuming the application does + // not voilate the class abstraction). + //debugPrintf(" delete 0x%x\n", m_pointer); + + // We must zero the weak pointers *before* deletion in case there + // are cycles of weak references. + // Note that since there are no strong references at this point, + // it is perfectly fair to zero the weak pointers anyway. + pointer->ReferenceCountedObject_zeroWeakPointers(); + delete pointer; + } + + m_pointer = NULL; + } + } + + /** Non-atomic (except for the referencec increment). Can only be + called in contexts like the copy constructor or initial + constructor where it is known that the reference count will + not hit zero on some other thread. */ + void setPointer(T* x) { + if (x != m_pointer) { + zeroPointer(); + + if (x != NULL) { + debugAssert(G3D::isValidHeapPointer(x)); + + m_pointer = x; + + // Note that the ref count can be zero if this is the + // first pointer to it + ReferenceCountedObject* pointer = (ReferenceCountedObject*)m_pointer; + debugAssertM(pointer->ReferenceCountedObject_refCount.value() >= 0, + "Negative reference count detected."); + pointer->ReferenceCountedObject_refCount.increment(); + } + } + } + +public: + + inline ReferenceCountedPointer() : m_pointer(NULL) {} + + /** + Allow silent cast to the base class. + +
+        SubRef  s = new Sub();
+        BaseRef b = s;
+      
+ + i.e., compile-time subtyping rule + RCP<T> <: RCP<S> if T <: S + */ + template + inline ReferenceCountedPointer(const ReferenceCountedPointer& p) : + m_pointer(NULL) { + setPointer(p.pointer()); + } + +# if (! defined(MSC_VER) || (MSC_VER >= 1300)) + /** + Explicit cast to a subclass. Acts like dynamic cast; the result will be NULL if + the cast cannot succeed. Not supported on VC6. +
+        SubRef  s = new Sub();
+        BaseRef b = s;
+        s = b.downcast();   // Note that the template argument is the object type, not the pointer type.
+      
+ */ + template + ReferenceCountedPointer downcast() { + return ReferenceCountedPointer(dynamic_cast(m_pointer)); + } + + template + const ReferenceCountedPointer downcast() const { + return ReferenceCountedPointer(dynamic_cast(m_pointer)); + } +# endif + + // We need an explicit version of the copy constructor as well or + // the default copy constructor will be used. + inline ReferenceCountedPointer(const ReferenceCountedPointer& p) : m_pointer(NULL) { + setPointer(p.m_pointer); + } + + /** Allows construction from a raw pointer. That object will thereafter be + reference counted -- do not call delete on it. + + Use of const allows downcast on const references */ + inline ReferenceCountedPointer(const T* p) : m_pointer(NULL) { + // only const constructor is defined to remove ambiguity using NULL + setPointer(const_cast(p)); + } + + + inline ~ReferenceCountedPointer() { + zeroPointer(); + } + + inline size_t hashCode() const { + return reinterpret_cast(m_pointer);; + } + + inline const ReferenceCountedPointer& operator=(const ReferenceCountedPointer& p) { + setPointer(p.m_pointer); + return *this; + } + + inline ReferenceCountedPointer& operator=(T* p) { + setPointer(p); + return *this; + } + + inline bool operator==(const ReferenceCountedPointer& y) const { + return (m_pointer == y.m_pointer); + } + + inline bool operator!=(const ReferenceCountedPointer& y) const { + return (m_pointer != y.m_pointer); + } + + bool operator < (const ReferenceCountedPointer& y) const { + return (m_pointer < y.m_pointer); + } + + bool operator > (const ReferenceCountedPointer& y) const { + return (m_pointer > y.m_pointer); + } + + bool operator <= (const ReferenceCountedPointer& y) const { + return (m_pointer <= y.m_pointer); + } + + bool operator >= (const ReferenceCountedPointer& y) const { + return (m_pointer >= y.m_pointer); + } + + inline T& operator*() const { + debugAssertM(m_pointer != NULL, "Dereferenced a NULL ReferenceCountedPointer"); + return (*m_pointer); + } + + inline T* operator->() const { + debugAssertM(m_pointer != NULL, "Dereferenced a NULL ReferenceCountedPointer"); + return m_pointer; + } + + inline bool isNull() const { + return (m_pointer == NULL); + } + + inline bool notNull() const { + return (m_pointer != NULL); + } + + // TODO: distinguish between last strong and last any pointer + /** + Returns true if this is the last reference to an object. + Useful for flushing memoization caches-- a cache that holds the last + reference is unnecessarily keeping an object alive. + + Not threadsafe. + + @deprecated Use WeakReferenceCountedPointer for caches + */ + inline int isLastReference() const { + return (m_pointer->ReferenceCountedObject_refCount.value() == 1); + } +}; + + +/** + A weak pointer allows the object it references to be garbage collected. + Weak pointers are commonly used in caches, where it is important to hold + a pointer to an object without keeping that object alive solely for the + cache's benefit (i.e., the object can be collected as soon as all + pointers to it outside the cache are gone). They are also convenient + for adding back-pointers in tree and list structures. + + Weak pointers may become NULL at any point (when their target is collected). + Therefore the only way to reference the target is to convert to a strong + pointer and then check that it is not NULL. + +@deprecated To be replaced by boost::weak_ptr in 7.0 + */ +template +class WeakReferenceCountedPointer : public _WeakPtr { +private: + + /** NULL if the object has been collected. */ + T* pointer; + +public: + /** + Creates a strong pointer, which prevents the object from being + garbage collected. The strong pointer may be NULL, which means + that the underlying. + */ + // There is intentionally no way to check if the + // WeakReferenceCountedPointer has a null reference without + // creating a strong pointer since there is no safe way to use + // that information-- the pointer could be collected by a + // subsequent statement. + ReferenceCountedPointer createStrongPtr() const { + // TODO: What if the object's destructor is called while we + // are in this method? + return ReferenceCountedPointer(pointer); + } + +private: + + /** Thread issues: safe because this is only called when another + object is guaranteed to keep p alive for the duration of this + call. */ + void setPointer(T* p) { + // TODO: must prevent the object from being collected while in + // this method + + zeroPointer(); + pointer = p; + + if (pointer != NULL) { + // TODO: threadsafe: must update the list atomically + + // Add myself to the head of my target's list of weak pointers + _WeakPtrLinkedList* head = + new _WeakPtrLinkedList + (this, + pointer->ReferenceCountedObject_weakPointer); + + pointer->ReferenceCountedObject_weakPointer = head; + } else { + + } + } + + + /** + Removes this from its target's list of weak pointers. Called + when the weak pointer goes out of scope. + + Thread issues: depends on the thread safety of createStrongPtr. + */ + void zeroPointer() { + // Grab a strong reference to prevent the object from being collected while we + // are traversing its list. + ReferenceCountedPointer strong = createStrongPtr(); + + // If the following test fails then the object was collected before we + // reached it. + if (strong.notNull()) { + debugAssertM(((ReferenceCountedObject*)pointer)->ReferenceCountedObject_weakPointer != NULL, + "Weak pointer exists without a backpointer from the object."); + + // Remove myself from my target's list of weak pointers + _WeakPtrLinkedList** node = &((ReferenceCountedObject*)pointer)->ReferenceCountedObject_weakPointer; + while ((*node)->weakPtr != this) { + node = &((*node)->next); + debugAssertM(*node != NULL, + "Weak pointer exists without a backpointer from the object (2)."); + } + + // Node must now point at the node for me. Remove node and + // close the linked list behind it. + _WeakPtrLinkedList* temp = *node; + *node = temp->next; + + // Now delete the node corresponding to me + delete temp; + } + + pointer = NULL; + } + +public: + + WeakReferenceCountedPointer() : pointer(0) {} + + /** + Allow compile time subtyping rule + RCP<T> <: RCP<S> if T <: S + */ + template + inline WeakReferenceCountedPointer(const WeakReferenceCountedPointer& p) : pointer(0) { + // Threadsafe: the object cannot be collected while the other pointer exists. + setPointer(p.pointer); + } + + template + inline WeakReferenceCountedPointer(const ReferenceCountedPointer& p) : pointer(0) { + // Threadsafe: the object cannot be collected while the other + // pointer exists. + setPointer(p.pointer()); + } + + // Gets called a *lot* when weak pointers are on the stack + WeakReferenceCountedPointer( + const WeakReferenceCountedPointer& weakPtr) : pointer(0) { + setPointer(weakPtr.pointer); + } + + WeakReferenceCountedPointer( + const ReferenceCountedPointer& strongPtr) : pointer(0) { + setPointer(strongPtr.pointer()); + } + + ~WeakReferenceCountedPointer() { + zeroPointer(); + } + + WeakReferenceCountedPointer& operator=(const WeakReferenceCountedPointer& other) { + // Threadsafe: the object cannot be collected while the other pointer exists. + + // I now point at other's target + setPointer(other.pointer); + + return *this; + } + + WeakReferenceCountedPointer& operator=(const ReferenceCountedPointer& other) { + + // Threadsafe: the object cannot be collected while the other pointer exists. + + // I now point at other's target + setPointer(other.pointer()); + + return *this; + } + + bool operator==(const WeakReferenceCountedPointer& other) const { + return pointer == other.pointer; + } + + bool operator!=(const WeakReferenceCountedPointer& other) const { + return pointer != other.pointer; + } + + bool operator < (const WeakReferenceCountedPointer& y) const { + return (pointer < y.pointer); + } + + bool operator > (const WeakReferenceCountedPointer& y) const { + return (pointer > y.pointer); + } + + bool operator <= (const WeakReferenceCountedPointer& y) const { + return (pointer <= y.pointer); + } + + bool operator >= (const ReferenceCountedPointer& y) const { + return (pointer >= y.pointer); + } + +protected: + + /** Invoked by the destructor on ReferenceCountedPointer. */ + void objectCollected() { + debugAssertM(pointer != NULL, + "Removed a weak pointer twice."); + pointer = NULL; + } + +}; + +} // namespace + +#endif + diff --git a/dep/g3dlite/G3D/RegistryUtil.h b/dep/g3dlite/G3D/RegistryUtil.h new file mode 100644 index 00000000000..4b47be5f4bd --- /dev/null +++ b/dep/g3dlite/G3D/RegistryUtil.h @@ -0,0 +1,97 @@ +/** + @file RegistryUtil.h + + @created 2006-04-06 + @edited 2006-04-06 + + Copyright 2000-2006, Morgan McGuire. + All rights reserved. +*/ + +#ifndef G3D_REGISTRYUTIL_H +#define G3D_REGISTRYUTIL_H + +#include "G3D/platform.h" +#include "G3D/g3dmath.h" + +// This file is only used on Windows +#ifdef G3D_WIN32 + +#include + +namespace G3D { + +/** + Provides generalized Windows registry querying. + + All key names are one string in the format: + "[base key]\[sub-keys]" + + A value must now be provided for every query. + An empty value string will use the (Default) value. + + [base key] can be any of the following: + HKEY_CLASSES_ROOT + HKEY_CURRENT_CONFIG + HKEY_CURRENT_USER + HKEY_LOCAL_MACHINE + HKEY_PERFORMANCE_DATA + HKEY_PERFORMANCE_NLSTEXT + HKEY_PERFORMANCE_TEXT + HKEY_USERS + + valueExists() should be used to validate a key+value before reading or writing + to ensure that a debug assert or false return is for a different error during + reads and writes. + + All read and write calls will assert when a key will not open for reasons other + that it does not exist. All read and write calls will assert when the value cannot + be read or written for any reason. +*/ +class RegistryUtil { + +public: + /** returns true if the key exists and the current user has permission to read */ + static bool keyExists(const std::string& key); + + /** returns true if the key exists and the current user has permission to read */ + static bool valueExists(const std::string& key, const std::string& value); + + /** returns false if the key could not be read for any reason. */ + static bool readInt32(const std::string& key, const std::string& value, int32& data); + + /** + Reads an arbitrary amount of data from a binary registry key. + returns false if the key could not be read for any reason. + + @beta + @param data pointer to the output buffer of sufficient size. Pass NULL as data in order to have available data size returned in dataSize. + @param dataSize size of the output buffer. When NULL is passed for data, contains the size of available data on successful return. + */ + static bool readBytes(const std::string& key, const std::string& value, uint8* data, uint32& dataSize); + + /** returns false if the key could not be read for any reason. */ + static bool readString(const std::string& key, const std::string& value, std::string& data); + + /** returns false if the key could not be written for any reason. */ + static bool writeInt32(const std::string& key, const std::string& value, int32 data); + + /** + Writes an arbitrary amount of data to a binary registry key. + returns false if the key could not be written for any reason. + + @param data pointer to the input buffer + @param dataSize size of the input buffer that should be written + */ + static bool writeBytes(const std::string& key, const std::string& value, const uint8* data, uint32 dataSize); + + /** returns false if the key could not be written for any reason. */ + static bool writeString(const std::string& key, const std::string& value, const std::string& data); + +}; + +} // namespace G3D + +#endif // G3D_WIN32 + +#endif // G3D_REGISTRYTUIL_H diff --git a/dep/g3dlite/G3D/Set.h b/dep/g3dlite/G3D/Set.h new file mode 100644 index 00000000000..9a8e1b619bb --- /dev/null +++ b/dep/g3dlite/G3D/Set.h @@ -0,0 +1,186 @@ +/** + @file Set.h + + Hash set + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2001-12-09 + @edited 2009-06-10 + */ + +#ifndef G3D_Set_h +#define G3D_Set_h + +#include "G3D/platform.h" +#include "G3D/Table.h" +#include "G3D/MemoryManager.h" +#include +#include + +namespace G3D { + +/** + An unordered data structure that has at most one of each element. + Provides O(1) time insert, remove, and member test (contains). + + Set uses G3D::Table internally, which means that the template type T + must define a hashCode and operator== function. See G3D::Table for + a discussion of these functions. + */ +// There is not copy constructor or assignment operator defined because +// the default ones are correct for Set. +template, class EqualsFunc = EqualsTrait > +class Set { + + /** + If an object is a member, it is contained in + this table. + */ + Table memberTable; + +public: + + void clearAndSetMemoryManager(const MemoryManager::Ref& m) { + memberTable.clearAndSetMemoryManager(m); + } + + virtual ~Set() {} + + int size() const { + return (int)memberTable.size(); + } + + bool contains(const T& member) const { + return memberTable.containsKey(member); + } + + /** + Inserts into the table if not already present. + */ + void insert(const T& member) { + memberTable.set(member, true); + } + + /** + Returns true if the element was present and removed. Returns false + if the element was not present. + */ + bool remove(const T& member) { + return memberTable.remove(member); + } + + /** If @a member is present, sets @a removed to the element + being removed and returns true. Otherwise returns false + and does not write to @a removed. This is useful when building + efficient hashed data structures that wrap Set. + */ + bool getRemove(const T& member, T& removed) { + bool ignore; + return memberTable.getRemove(member, removed, ignore); + } + + /** If a value that is EqualsFunc to @a member is present, returns a pointer to the + version stored in the data structure, otherwise returns NULL. + */ + const T* getPointer(const T& member) const { + return memberTable.getKeyPointer(member); + } + + Array getMembers() const { + return memberTable.getKeys(); + } + + void getMembers(Array& keyArray) const { + memberTable.getKeys(keyArray); + } + + void clear() { + memberTable.clear(); + } + + void deleteAll() { + getMembers().deleteAll(); + clear(); + } + + /** + C++ STL style iterator variable. See begin(). + */ + class Iterator { + private: + friend class Set; + + // Note: this is a Table iterator, we are currently defining + // Set iterator + typename Table::Iterator it; + + Iterator(const typename Table::Iterator& it) : it(it) {} + + public: + inline bool operator!=(const Iterator& other) const { + return !(*this == other); + } + + bool hasMore() const { + return it.hasMore(); + } + + bool operator==(const Iterator& other) const { + return it == other.it; + } + + /** + Pre increment. + */ + Iterator& operator++() { + ++it; + return *this; + } + + /** + Post increment (slower than preincrement). + */ + Iterator operator++(int) { + Iterator old = *this; + ++(*this); + return old; + } + + const T& operator*() const { + return it->key; + } + + T* operator->() const { + return &(it->key); + } + + operator T*() const { + return &(it->key); + } + }; + + + /** + C++ STL style iterator method. Returns the first member. + Use preincrement (++entry) to get to the next element. + Do not modify the set while iterating. + */ + Iterator begin() const { + return Iterator(memberTable.begin()); + } + + + /** + C++ STL style iterator method. Returns one after the last iterator + element. + */ + const Iterator end() const { + return Iterator(memberTable.end()); + } +}; + +} + +#endif + diff --git a/dep/g3dlite/G3D/SmallArray.h b/dep/g3dlite/G3D/SmallArray.h new file mode 100644 index 00000000000..41f9959e264 --- /dev/null +++ b/dep/g3dlite/G3D/SmallArray.h @@ -0,0 +1,155 @@ +/** + @file SmallArray.h + + @created 2009-04-26 + @edited 2009-04-26 + + Copyright 2000-2009, Morgan McGuire, http://graphics.cs.williams.edu + All rights reserved. + */ +#ifndef G3D_SmallArray_h +#define G3D_SmallArray_h + +#include "G3D/platform.h" +#include "G3D/Array.h" + +namespace G3D { + +/** Embeds \a N elements to reduce allocation time and increase + memory coherence when working with arrays of arrays. + Offers a limited subset of the functionality of G3D::Array.*/ +template +class SmallArray { +private: + int m_size; + + /** First N elements */ + T m_embedded[N]; + + /** Remaining elements */ + Array m_rest; + +public: + + SmallArray() : m_size(0) {} + + inline int size() const { + return m_size; + } + + void resize(int n, bool shrinkIfNecessary = true) { + m_rest.resize(std::max(0, n - N), shrinkIfNecessary); + m_size = n; + } + + void clear(bool shrinkIfNecessary = true) { + resize(0, shrinkIfNecessary); + } + + inline T& operator[](int i) { + debugAssert(i < m_size && i >= 0); + if (i < N) { + return m_embedded[i]; + } else { + return m_rest[i - N]; + } + } + + inline const T& operator[](int i) const { + debugAssert(i < m_size && i >= 0); + if (i < N) { + return m_embedded[i]; + } else { + return m_rest[i - N]; + } + } + + inline void push(const T& v) { + ++m_size; + if (m_size <= N) { + m_embedded[m_size - 1] = v; + } else { + m_rest.append(v); + } + } + + inline void append(const T& v) { + push(v); + } + + void fastRemove(int i) { + debugAssert(i < m_size && i >= 0); + if (i < N) { + if (m_size <= N) { + // Exclusively embedded + m_embedded[i] = m_embedded[m_size - 1]; + } else { + // Move one down from the rest array + m_embedded[i] = m_rest.pop(); + } + } else { + // Removing from the rest array + m_rest.fastRemove(i - N); + } + --m_size; + } + + T pop() { + debugAssert(m_size > 0); + if (m_size <= N) { + // Popping from embedded, don't need a temporary + --m_size; + return m_embedded[m_size]; + } else { + // Popping from rest + --m_size; + return m_rest.pop(); + } + } + + inline void popDiscard() { + debugAssert(m_size > 0); + if (m_size > N) { + m_rest.popDiscard(); + } + --m_size; + } + + inline T& next() { + ++m_size; + if (m_size <= N) { + return m_embedded[m_size - 1]; + } else { + return m_rest.next(); + } + } + + bool contains(const T& value) const { + for (int i = std::min(m_size, N) - 1; i >= 0; --i) { + if (m_embedded[i] == value) { + return true; + } + } + return m_rest.contains(value); + } + + template + SmallArray& operator=(const Array& src) { + resize(src.size()); + for (int i = 0; i < src.size(); ++i) { + (*this)[i] = src[i]; + } + return *this; + } + + inline const T& last() const { + return (*this)[size() - 1]; + } + + inline T& last() { + return (*this)[size() - 1]; + } +}; + +} +#endif diff --git a/dep/g3dlite/G3D/Sphere.h b/dep/g3dlite/G3D/Sphere.h new file mode 100644 index 00000000000..595b61c4bf1 --- /dev/null +++ b/dep/g3dlite/G3D/Sphere.h @@ -0,0 +1,148 @@ +/** + @file Sphere.h + + Sphere class + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2001-06-02 + @edited 2008-10-07 + */ + +#ifndef G3D_SPHERE_H +#define G3D_SPHERE_H + +#include "G3D/platform.h" +#include "G3D/Vector3.h" +#include "G3D/Array.h" +#include "G3D/Sphere.h" + +namespace G3D { + +/** + Sphere. + */ +class Sphere { +private: + + static int32 dummy; + +public: + Vector3 center; + float radius; + + Sphere() { + center = Vector3::zero(); + radius = 0; + } + + Sphere(class BinaryInput& b); + void serialize(class BinaryOutput& b) const; + void deserialize(class BinaryInput& b); + + Sphere( + const Vector3& center, + float radius) { + + this->center = center; + this->radius = radius; + } + + virtual ~Sphere() {} + + bool operator==(const Sphere& other) const { + return (center == other.center) && (radius == other.radius); + } + + bool operator!=(const Sphere& other) const { + return !((center == other.center) && (radius == other.radius)); + } + + /** + Returns true if point is less than or equal to radius away from + the center. + */ + bool contains(const Vector3& point) const; + + bool contains(const Sphere& other) const; + + /** + @deprecated Use culledBy(Array&) + */ + bool culledBy( + const class Plane* plane, + int numPlanes, + int32& cullingPlaneIndex, + const uint32 testMask, + uint32& childMask) const; + + /** + @deprecated Use culledBy(Array&) + */ + bool culledBy( + const class Plane* plane, + int numPlanes, + int32& cullingPlaneIndex = dummy, + const uint32 testMask = 0xFFFFFFFF) const; + + /** + See AABox::culledBy + */ + bool culledBy( + const Array& plane, + int32& cullingPlaneIndex, + const uint32 testMask, + uint32& childMask) const; + + /** + Conservative culling test that does not produce a mask for children. + */ + bool culledBy( + const Array& plane, + int32& cullingPlaneIndex = dummy, + const uint32 testMask = 0xFFFFFFFF) const; + + virtual std::string toString() const; + + float volume() const; + + float area() const; + + /** + Uniformly distributed on the surface. + */ + Vector3 randomSurfacePoint() const; + + /** + Uniformly distributed on the interior (includes surface) + */ + Vector3 randomInteriorPoint() const; + + void getBounds(class AABox& out) const; + + bool intersects(const Sphere& other) const; + + /** Translates the sphere */ + Sphere operator+(const Vector3& v) const { + return Sphere(center + v, radius); + } + + /** Translates the sphere */ + Sphere operator-(const Vector3& v) const { + return Sphere(center - v, radius); + } + + /** Sets this to the smallest sphere that encapsulates both */ + void merge(const Sphere& s); +}; + +} + +template <> struct HashTrait { + static size_t hashCode(const G3D::Sphere& key) { + return static_cast(key.center.hashCode() + (key.radius * 13)); + } +}; + + +#endif diff --git a/dep/g3dlite/G3D/Spline.h b/dep/g3dlite/G3D/Spline.h new file mode 100644 index 00000000000..fdd29e69ce9 --- /dev/null +++ b/dep/g3dlite/G3D/Spline.h @@ -0,0 +1,367 @@ +/** + @file Spline.h + + @author Morgan McGuire, http://graphics.cs.williams.edu + */ + +#ifndef G3D_SPLINE_H +#define G3D_SPLINE_H + +#include "G3D/platform.h" +#include "G3D/Array.h" +#include "G3D/g3dmath.h" +#include "G3D/Matrix4.h" +#include "G3D/Vector4.h" + +namespace G3D { + +/** Common implementation code for all G3D::Spline template parameters */ +class SplineBase { +public: + + /** Times at which control points occur. Must have the same + number of elements as Spline::control. */ + Array time; + + /** If cyclic, then the control points will be assumed to wrap around. + If not cyclic, then the tangents at the ends of the spline + point to the final control points.*/ + bool cyclic; + + /** For a cyclic spline, this is the time elapsed between the last + control point and the first. If less than or equal to zero this is + assumed to be: + + (time[0] - time[1] + . + time[time.size() - 1] - time[time.size() - 2]) / 2. + */ + float finalInterval; + + SplineBase() : cyclic(true), finalInterval(-1) {} + + virtual ~SplineBase() {} + + /** See specification for Spline::finalInterval; this handles the + non-positive case. Returns 0 if not cyclic. */ + float getFinalInterval() const; + + /** Returns the amount of time covered by this spline in one + period. For a cyclic spline, this contains the final + interval.*/ + float duration() const; + + /** Computes the derivative spline basis from the control point version. */ + static Matrix4 computeBasis(); + +protected: + + /** Assumes that t0 <= s < tn. called by computeIndex. */ + void computeIndexInBounds(float s, int& i, float& u) const; + +public: + + /** + Given a time @a s, finds @a i and 0 <= @a u < 1 such that + @a s = time[@a i] * @a u + time[@a i + 1] * (1 - @a u). Note that + @a i may be outside the bounds of the time and control arrays; + use getControl to handle wraparound and extrapolation issues. + + This function takes expected O(1) time for control points with + uniform time sampled control points or for uniformly + distributed random time samples, but may take O( log time.size() ) time + in the worst case. + + Called from evaluate(). + */ + void computeIndex(float s, int& i, float& u) const; +}; + + +/** + Smooth parameteric curve implemented using a piecewise 3rd-order + Catmull-Rom spline curve. The spline is considered infinite and may + either continue linearly from the specified control points or cycle + through them. Control points are spaced uniformly in time at unit + intervals by default, but irregular spacing may be explicitly + specified. + + The dimension of the spline can be set by varying the Control + template parameter. For a 1D function, use Spline. For a + curve in the plane, Spline. Note that any template + parameter that supports operator+(Control) and operator*(float) can + be used; you can make splines out of G3D::Vector4, G3D::Matrix3, or + your own classes. + + To provide shortest-path interpolation, subclass G3D::Spline and + override ensureShortestPath(). To provide normalization of + interpolated points (e.g., projecting Quats onto the unit + hypersphere) override correct(). + + See Real Time Rendering, 2nd edition, ch 12 for a general discussion + of splines and their properties. + + @sa G3D::UprightSpline, G3D::QuatSpline + */ +template +class Spline : public SplineBase { +protected: + /** The additive identity control point. */ + Control zero; + +public: + + /** Control points. Must have the same number of elements as + Spline::time.*/ + Array control; + + Spline() { + static Control x; + // Hide the fact from C++ that we are using an + // uninitialized variable here by pointer arithmetic. + // This is ok because any type that is a legal control + // point also supports multiplication by float. + zero = *(&x) * 0.0f; + } + + /** Appends a control point at a specific time that must be + greater than that of the previous point. */ + void append(float t, const Control& c) { + debugAssertM((time.size() == 0) || (t > time.last()), + "Control points must have monotonically increasing times."); + time.append(t); + control.append(c); + debugAssert(control.size() == time.size()); + } + + + /** Appends control point spaced in time based on the previous + control point, or spaced at unit intervals if this is the + first control point. */ + void append(const Control& c) { + switch (time.size()) { + case 0: + append(0, c); + break; + + case 1: + if (time[0] == 0) { + append(1, c); + } else { + append(time[0], c); + } + break; + + default: + append(2 * time[time.size() - 1] - time[time.size() - 2], c); + } + debugAssert(control.size() == time.size()); + } + + /** Erases all control points and times, but retains the state of + cyclic and finalInterval. + */ + void clear() { + control.clear(); + time.clear(); + } + + + /** Number of control points */ + int size() const { + debugAssert(time.size() == control.size()); + return control.size(); + } + + + /** Returns the requested control point and time sample based on + array index. If the array index is out of bounds, wraps (for + a cyclic spline) or linearly extrapolates (for a non-cyclic + spline), assuming time intervals follow the first or last + sample recorded. + + Calls correct() on the control point if it was extrapolated. + + Returns 0 if there are no control points. + + @sa Spline::control and Spline::time for the underlying + control point array; Spline::computeIndex to find the index + given a time. + */ + void getControl(int i, float& t, Control& c) const { + int N = control.size(); + if (N == 0) { + c = zero; + t = 0; + } else if (cyclic) { + c = control[iWrap(i, N)]; + + if (i < 0) { + // Wrapped around bottom + + // Number of times we wrapped around the cyclic array + int wraps = (N + 1 - i) / N; + int j = (i + wraps * N) % N; + t = time[j] - wraps * duration(); + + } else if (i < N) { + + t = time[i]; + + } else { + // Wrapped around top + + // Number of times we wrapped around the cyclic array + int wraps = i / N; + int j = i % N; + t = time[j] + wraps * duration(); + } + + } else if (i < 0) { + // Are there enough points to extrapolate? + if (N >= 2) { + // Step away from control point 0 + float dt = time[1] - time[0]; + + // Extrapolate (note; i is negative) + c = control[1] * float(i) + control[0] * float(1 - i); + correct(c); + t = dt * i + time[0]; + + } else { + // Just clamp + c = control[0]; + + // Only 1 time; assume 1s intervals + t = time[0] + i; + } + + } else if (i >= N) { + if (N >= 2) { + float dt = time[N - 1] - time[N - 2]; + + // Extrapolate + c = control[N - 1] * float(i - N + 2) + control[N - 2] * -float(i - N + 1); + correct(c); + t = time[N - 1] + dt * (i - N + 1); + + } else { + // Return the last, clamping + c = control.last(); + // Only 1 time; assume 1s intervals + t = time[0] + i; + } + } else { + // In bounds + c = control[i]; + t = time[i]; + } + } + +protected: + + /** Returns a series of N control points and times, fixing + boundary issues. The indices may be assumed to be treated + cyclically. */ + void getControls(int i, float* T, Control* A, int N) const { + for (int j = 0; j < N; ++j) { + getControl(i + j, T[j], A[j]); + } + ensureShortestPath(A, N); + } + + /** + Mutates the array of N control points. It is useful to override this + method by one that wraps the values if they are angles or quaternions + for which "shortest path" interpolation is significant. + */ + virtual void ensureShortestPath(Control* A, int N) const { (void)A; (void) N;} + + /** Normalize or otherwise adjust this interpolated Control. */ + virtual void correct(Control& A) const { (void)A; } + +public: + + + /** + Return the position at time s. The spline is defined outside + of the time samples by extrapolation or cycling. + */ + Control evaluate(float s) const { + debugAssertM(control.size() == time.size(), "Corrupt spline: wrong number of control points."); + + /* + @cite http://www.gamedev.net/reference/articles/article1497.asp + Derivation of basis matrix follows. + + Given control points with positions p[i] at times t[i], 0 <= i <= 3, find the position + at time t[1] <= s <= t[2]. + + Let u = s - t[0] + Let U = [u^0 u^1 u^2 u^3] = [1 u u^2 u^3] + Let dt0 = t[0] - t[-1] + Let dt1 = t[1] - t[0] + Let dt2 = t[2] - t[1] + */ + + // Index of the first control point (i.e., the u = 0 point) + int i = 0; + // Fractional part of the time + float u = 0; + + computeIndex(s, i, u); + + Control p[4]; + float t[4]; + getControls(i - 1, t, p, 4); + float dt0 = t[1] - t[0]; + float dt1 = t[2] - t[1]; + float dt2 = t[3] - t[2]; + + static const Matrix4 basis = computeBasis(); + + // Powers of u + Vector4 uvec((float)(u*u*u), (float)(u*u), (float)u, 1.0f); + + // Compute the weights on each of the control points. + const Vector4& weights = uvec * basis; + + // Compute the weighted sum of the neighboring control points. + Control sum; + + const Control& p0 = p[0]; + const Control& p1 = p[1]; + const Control& p2 = p[2]; + const Control& p3 = p[3]; + + const Control& dp0 = p1 + (p0*-1.0f); + const Control& dp1 = p2 + (p1*-1.0f); + const Control& dp2 = p3 + (p2*-1.0f); + + // The factor of 1/2 from averaging two time intervals is + // already factored into the basis + + // tan1 = (dp0 / dt0 + dp1 / dt1) * ((dt0 + dt1) * 0.5); + // The last term normalizes for unequal time intervals + float x = (dt0 + dt1) * 0.5f; + float n0 = x / dt0; + float n1 = x / dt1; + float n2 = x / dt2; + const Control& dp1n1 = dp1 * n1; + const Control& tan1 = dp0 * n0 + dp1n1; + const Control& tan2 = dp1n1 + dp2 * n2; + + sum = + tan1 * weights[0]+ + p1 * weights[1] + + p2 * weights[2] + + tan2 * weights[3]; + + + correct(sum); + return sum; + } +}; + +} + +#endif diff --git a/dep/g3dlite/G3D/Stopwatch.h b/dep/g3dlite/G3D/Stopwatch.h new file mode 100644 index 00000000000..3f2aa9c8d86 --- /dev/null +++ b/dep/g3dlite/G3D/Stopwatch.h @@ -0,0 +1,144 @@ +/** + @file Stopwatch.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2005-10-05 + @edited 2009-05-10 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_Stopwatch_h +#define G3D_Stopwatch_h + +#include "G3D/platform.h" +#include "G3D/Queue.h" +#include "G3D/G3DGameUnits.h" +#include "G3D/g3dmath.h" + +namespace G3D { + +/** + \brief Accurately measure durations and framerates. + + Example 1: For profiling code in the context of a rendering loop: +
+      sw.tick();
+      ...timed code...
+      sw.tock();
+
+      screenPrintf("%f\n", sw.smoothFPS());
+    
+ + + Example 2: For profiling pieces of a sequence: +
+    Stopwatch sw;
+    slowOperation();
+    sw.after("slowOperation");
+    kdTree.balance();
+    sw.after("Balance tree");
+   
+ */ +class Stopwatch { +private: + + std::string myName; + double startTime; + std::string prevMark; + double prevTime; + + /** True between tick and tock */ + bool inBetween; + + /** The initial cycle count. */ + uint64 cycleStart; + + /** The time at which tick was called. */ + RealTime timeStart; + + /** The time at which the previous tock was called, -1 if never. */ + RealTime lastTockTime; + + RealTime lastDuration; + int64 lastCycleCount; + + /** Frames per second. */ + double m_fps; + + /** Weighted fps */ + double emwaFPS; + double m_smoothFPS; + + /** Weighted duration */ + RealTime emwaDuration; + + /** The overhead for calling into the class. */ + int64 cycleOverhead; + + /** Called from the constructor. */ + void computeOverhead(); + +public: + + Stopwatch(const std::string& name = "Stopwatch"); + + /** Returns the number of times that tick was called per wall-clock second; + e.g. frames-per-second. */ + double FPS() const { + return m_fps; + } + + /** Amount of time between the most recent tick and tock calls. 0 if tick has + never been called. */ + RealTime elapsedTime() const { + return lastDuration; + } + + /** Time-smoothed value that is stable to the nearest 1%. + This is useful if you are displaying elapsed time in real-time + and want a stable number.*/ + RealTime smoothElapsedTime() const { + return emwaDuration; + } + + /** Time-smoothed value of fps that is stable to the nearest integer for fps > 10 and + to the first decimal place for fps <= 10. + This is useful if you + are displaying the frame rate in real-time and want a stable (readable) number.*/ + double smoothFPS() const { + return m_smoothFPS; + } + + /** The elapsed cycle time between tick and tock. An attempt is made to factor out all + tick/tock overhead, so that back-to-back calls should return zero. + Unreliable on non-x86 platforms.*/ + uint64 elapsedCycles() const { + return lastCycleCount; + } + + /** Call at the beginning of the period that you want timed. */ + void tick(); + + /** Call at the end of the period that you want timed. */ + void tock(); + + + /** Reset the start time used by after() and the emwa value.*/ + void reset(); + + /** Call after an operation has completed, with the name of the operation, to + print a debug message listing the time since the previous after() call. */ + void after(const std::string& s = ""); + +}; + +/** Because it is hard to remember the proper capitalization. */ +typedef Stopwatch StopWatch; + +} + +#endif + diff --git a/dep/g3dlite/G3D/System.h b/dep/g3dlite/G3D/System.h new file mode 100644 index 00000000000..56ef9c8e3dc --- /dev/null +++ b/dep/g3dlite/G3D/System.h @@ -0,0 +1,507 @@ +/** + @file System.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @cite Rob Wyatt http://www.gamasutra.com/features/wyatts_world/19990709/processor_detection_01.htm + @cite Benjamin Jurke http://www.flipcode.com/cgi-bin/msg.cgi?showThread=COTD-ProcessorDetectionClass&forum=cotd&id=-1 + @cite Michael Herf http://www.stereopsis.com/memcpy.html + + @created 2003-01-25 + @edited 2008-10-14 + */ + +#ifndef G3D_System_h +#define G3D_System_h + +#include "G3D/platform.h" +#include "G3D/g3dmath.h" +#include "G3D/G3DGameUnits.h" +#include "G3D/BinaryFormat.h" +#include + +#ifdef G3D_OSX +# include +#endif + +namespace G3D { + +/** + Routine used by the demos to find the data. Searches in + ../data, ../../data, etc. up to 5 levels back. Checks + common locations like \verbatim c:\libraries\g3d-\data \endverbatim + and some hard-coded paths on the Brown University file + system. + + @deprecated + */ +std::string demoFindData(bool errorIfNotFound = true); + +/** G3D, SDL, and IJG libraries require license documentation + to be distributed with your program. This generates the + string that must appear in your documentation. + Your program can be commercial, closed-source under + any license you want. + @deprecated Use System::license +*/ +std::string license(); + +/** +@brief The order in which the bytes of an integer are stored on a +machine. + +Intel/AMD chips tend to be G3D_LITTLE_ENDIAN, Mac PPC's and Suns are +G3D_BIG_ENDIAN. However, this is primarily used to specify the byte +order of file formats, which are fixed. +*/ +enum G3DEndian { + G3D_BIG_ENDIAN, + G3D_LITTLE_ENDIAN +}; + +/** + @brief OS and processor abstraction. + + The first time any method is called the processor will be analyzed. + Future calls are then fast. + + Timing function overview: + System::getCycleCount + - actual cycle count + + System::getTick + - High-resolution time in seconds since program started + + System::getLocalTime + - High-resolution time in seconds since Jan 1, 1970 + (because it is stored in a double, this may be less + accurate than getTick) + */ +class System { +public: + /** + @param size Size of memory that the system was trying to allocate + + @param recoverable If true, the system will attempt to allocate again + if the callback returns true. If false, malloc is going to return + NULL and this invocation is just to notify the application. + + @return Return true to force malloc to attempt allocation again if the + error was recoverable. + */ + typedef bool (*OutOfMemoryCallback)(size_t size, bool recoverable); + +private: + + bool m_initialized; + int m_cpuSpeed; + bool m_hasCPUID; + bool m_hasRDTSC; + bool m_hasMMX; + bool m_hasSSE; + bool m_hasSSE2; + bool m_hasSSE3; + bool m_has3DNOW; + bool m_has3DNOW2; + bool m_hasAMDMMX; + std::string m_cpuVendor; + int m_numCores; + + /** this holds the data directory set by the application (currently + GApp) for use by findDataFile */ + std::string m_appDataDir; + + G3DEndian m_machineEndian; + std::string m_cpuArch; + std::string m_operatingSystem; + +# ifdef G3D_WIN32 + /** Used by getTick() for timing */ + LARGE_INTEGER m_start; + LARGE_INTEGER m_counterFrequency; +#else + struct timeval m_start; +#endif + + std::string m_version; + OutOfMemoryCallback m_outOfMemoryCallback; + +#ifdef G3D_OSX + /** In Cycles/Second */ + SInt32 m_OSXCPUSpeed; + double m_secondsPerNS; +#endif + + /** The Real-World time of System::getTick() time 0. Set by initTime */ + RealTime m_realWorldGetTickTime0; + + uint32 m_highestCPUIDFunction; + + /** @brief Used for the singleton instance only. */ + System(); + + /** @brief The singleton instance. + + Used instead of a global variable to ensure that the order of + intialization is correct, which is critical because other + globals may allocate memory using System::malloc. + */ + static System& instance(); + + enum CPUIDFunction { + CPUID_VENDOR_ID = 0x00000000, + CPUID_PROCESSOR_FEATURES = 0x00000001, + CPUID_NUM_CORES = 0x00000004, + CPUID_GET_HIGHEST_FUNCTION = 0x80000000, + CPUID_EXTENDED_FEATURES = 0x80000001}; + + /** Helper macro to call cpuid functions and return all values + + See http://software.intel.com/en-us/articles/intel-64-architecture-processor-topology-enumeration/ + or http://www.amd.com/us-en/assets/content_type/white_papers_and_tech_docs/25481.pdf + + for description of the arguments. + */ + static void cpuid(CPUIDFunction func, uint32& areg, uint32& breg, uint32& creg, uint32& dreg); + + void init(); + + /** Called from init() */ + void getStandardProcessorExtensions(); + + /** Called from init() */ + void initTime(); + +public: + + /** Returns the speed of processor 0 in MHz. + Always returns 0 on linux.*/ + inline static int cpuSpeedMHz() { + return instance().m_cpuSpeed; + } + + /** Returns the number of logical processor cores (i.e., the + number of execution units for threads) */ + inline static int numCores() { + return instance().m_numCores; + } + + inline static bool hasCPUID() { + return instance().m_hasCPUID; + } + + inline static bool hasRDTSC() { + return instance().m_hasRDTSC; + } + + inline static bool hasSSE() { + return instance().m_hasSSE; + } + + inline static bool hasSSE2() { + return instance().m_hasSSE2; + } + + inline static bool hasSSE3() { + return instance().m_hasSSE3; + } + + inline static bool hasMMX() { + return instance().m_hasMMX; + } + + inline static bool has3DNow() { + return instance().m_has3DNOW; + } + + inline static const std::string& cpuVendor() { + return instance().m_cpuVendor; + } + + /** + Returns the endianness of this machine. + */ + inline static G3DEndian machineEndian() { + return instance().m_machineEndian; + } + + /** e.g., "Windows", "GNU/Linux" */ + inline static const std::string& operatingSystem() { + return instance().m_operatingSystem; + } + + /** e.g., 80686 */ + inline static const std::string& cpuArchitecture() { + return instance().m_cpuArch; + } + + /** + Returns the current date as a string in the form YYYY-MM-DD + */ + static std::string currentDateString(); + + /** + Guarantees that the start of the array is aligned to the + specified number of bytes. + */ + static void* alignedMalloc(size_t bytes, size_t alignment); + + /** + Uses pooled storage to optimize small allocations (1 byte to 5 + kilobytes). Can be 10x to 100x faster than calling ::malloc or + new. + + The result must be freed with free. + + Threadsafe on Win32. + + @sa calloc realloc OutOfMemoryCallback free + */ + static void* malloc(size_t bytes); + + static void* calloc(size_t n, size_t x); + + /** + Version of realloc that works with System::malloc. + */ + static void* realloc(void* block, size_t bytes); + + /** Returns a string describing how well System::malloc is using + its internal pooled storage. "heap" memory was slow to + allocate; the other data sizes are comparatively fast.*/ + static std::string mallocPerformance(); + static void resetMallocPerformanceCounters(); + + /** + Returns a string describing the current usage of the buffer pools used for + optimizing System::malloc. + */ + static std::string mallocStatus(); + + /** + Free data allocated with System::malloc. + + Threadsafe on Win32. + */ + static void free(void* p); + + /** + Frees memory allocated with alignedMalloc. + */ + static void alignedFree(void* ptr); + + /** An implementation of memcpy that may be up to 2x as fast as the C library + one on some processors. Guaranteed to have the same behavior as memcpy + in all cases. */ + static void memcpy(void* dst, const void* src, size_t numBytes); + + /** An implementation of memset that may be up to 2x as fast as the C library + one on some processors. Guaranteed to have the same behavior as memset + in all cases. */ + static void memset(void* dst, uint8 value, size_t numBytes); + + /** + Returns the fully qualified filename for the currently running executable. + + This is more reliable than arg[0], which may be intentionally set + to an incorrect value by a calling program, relative to a now + non-current directory, or obfuscated by sym-links. + + @cite Linux version written by Nicolai Haehnle , http://www.flipcode.com/cgi-bin/msg.cgi?showThread=COTD-getexename&forum=cotd&id=-1 + */ + static std::string currentProgramFilename(); + + /** Name of this program. Note that you can mutate this string to + set your app name explicitly.*/ + static std::string& appName(); + + /** G3D Version string */ + inline static const std::string& version() { + return instance().m_version; + } + + /** + @brief The optimization status of the G3D library (not the program compiled against it) + + Either "Debug" or "Release", depending on whether _DEBUG was + defined at compile-time for the library. + */ + static const std::string& build(); + + /** + Causes the current thread to yield for the specified duration + and consume almost no CPU. + The sleep will be extremely precise; it uses System::time() + to calibrate the exact yeild time. + */ + static void sleep(RealTime t); + + /** + Clears the console. + Console programs only. + */ + static void consoleClearScreen(); + + /** + Returns true if a key is waiting. + Console programs only. + */ + static bool consoleKeyPressed(); + + /** + Blocks until a key is read (use consoleKeyPressed to determine if + a key is waiting to be read) then returns the character code for + that key. + */ + static int consoleReadKey(); + + /** + The actual time (measured in seconds since + Jan 1 1970 midnight). + + Adjusted for local timezone and daylight savings + time. This is as accurate and fast as getCycleCount(). + */ + static RealTime time(); + + /** + To count the number of cycles a given operation takes: + +
+     unsigned long count;
+     System::beginCycleCount(count);
+     ...
+     System::endCycleCount(count);
+     // count now contains the cycle count for the intervening operation.
+     
+ */ + /* static void beginCycleCount(uint64& cycleCount); + static void endCycleCount(uint64& cycleCount); + + static uint64 getCycleCount(); */ + + inline static void setOutOfMemoryCallback(OutOfMemoryCallback c) { + instance().m_outOfMemoryCallback = c; + } + + /** + When System::malloc fails to allocate memory because the system is + out of memory, it invokes this handler (if it is not NULL). + The argument to the callback is the amount of memory that malloc + was trying to allocate when it ran out. If the callback returns + true, System::malloc will attempt to allocate the memory again. + If the callback returns false, then System::malloc will return NULL. + + You can use outOfMemoryCallback to free data structures or to + register the failure. + */ + inline static OutOfMemoryCallback outOfMemoryCallback() { + return instance().m_outOfMemoryCallback; + } + + /** Set an environment variable for the current process */ + static void setEnv(const std::string& name, const std::string& value); + + /** Get an environment variable for the current process. Returns NULL if the variable doesn't exist. */ + static const char* getEnv(const std::string& name); + + /** + Prints a human-readable description of this machine + to the text output stream. Either argument may be NULL. + */ + static void describeSystem( + class TextOutput& t); + + static void describeSystem( + std::string& s); + + /** On Win32, returns the clipboard text contents. Does nothing on other + platforms (yet) */ + static std::string getClipboardText(); + + /** Copies the text to the clipboard on Win32. */ + static void setClipboardText(const std::string& s); + + /** + Tries to locate the resource by looking in related directories. + If found, returns the full path to the resource, otherwise + returns the empty string. + */ + static std::string findDataFile(const std::string& full, bool errorIfNotFound = true); + + /** + Sets the path that the application is using as its data directory. + Used by findDataDir as an initial search location. GApp sets this + upon constrution. + */ + static void setAppDataDir(const std::string& path); + +}; + +/* don't need that for MaNGOS, not portable to Win64... +#ifdef _MSC_VER + inline uint64 System::getCycleCount() { + uint32 timehi, timelo; + + // Use the assembly instruction rdtsc, which gets the current + // cycle count (since the process started) and puts it in edx:eax. + __asm + { + rdtsc; + mov timehi, edx; + mov timelo, eax; + } + + return ((uint64)timehi << 32) + (uint64)timelo; + } + +#elif defined(G3D_LINUX) + + inline uint64 System::getCycleCount() { + uint32 timehi, timelo; + + __asm__ __volatile__ ( + "rdtsc " + : "=a" (timelo), + "=d" (timehi) + : ); + + return ((uint64)timehi << 32) + (uint64)timelo; + } + +#elif defined(G3D_OSX) + + inline uint64 System::getCycleCount() { + //Note: To put off extra processing until the end, this does not + //return the actual clock cycle count. It is a bus cycle count. + //When endCycleCount() is called, it converts the two into a difference + //of clock cycles + + return (uint64) UnsignedWideToUInt64(UpTime()); + //return (uint64) mach_absolute_time(); + } + +#endif + +inline void System::beginCycleCount(uint64& cycleCount) { + cycleCount = getCycleCount(); +} + + +inline void System::endCycleCount(uint64& cycleCount) { +#ifndef G3D_OSX + cycleCount = getCycleCount() - cycleCount; +#else + AbsoluteTime end = UpTime(); + Nanoseconds diffNS = + AbsoluteDeltaToNanoseconds(end, UInt64ToUnsignedWide(cycleCount)); + cycleCount = + (uint64) ((double) (instance().m_OSXCPUSpeed) * + (double) UnsignedWideToUInt64(diffNS) * instance().m_secondsPerNS); +#endif +} + */ + +} // namespace + +#endif diff --git a/dep/g3dlite/G3D/Table.h b/dep/g3dlite/G3D/Table.h new file mode 100644 index 00000000000..287efa94d97 --- /dev/null +++ b/dep/g3dlite/G3D/Table.h @@ -0,0 +1,924 @@ +/** + @file Table.h + + Templated hash table class. + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + @created 2001-04-22 + @edited 2010-01-28 + Copyright 2000-2010, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_Table_h +#define G3D_Table_h + +#include +#include + +#include "G3D/platform.h" +#include "G3D/Array.h" +#include "G3D/debug.h" +#include "G3D/System.h" +#include "G3D/g3dmath.h" +#include "G3D/EqualsTrait.h" +#include "G3D/HashTrait.h" +#include "G3D/MemoryManager.h" + +#ifdef _MSC_VER +# pragma warning (push) + // Debug name too long warning +# pragma warning (disable : 4786) +#endif + +namespace G3D { + +/** + An unordered data structure mapping keys to values. + + There are two ways of definining custom hash functions (G3D provides built-in ones for most classes): + +
+ class Foo {
+ public:
+     std::string     name;
+     int             index;
+     static size_t hashCode(const Foo& key) {
+          return HashTrait::hashCode(key.name) + key.index;
+     }
+  };
+
+  template<> struct HashTrait {
+       static size_t hashCode(const Foo& key) { return HashTrait::hashCode(key.name) + key.index; }
+  }; 
+
+
+  // Use Foo::hashCode
+  Table fooTable1;
+
+  // Use HashTrait
+  Table      fooTable2;
+  
+ + + Key must be a pointer, an int, a std::string or provide overloads for: + +
+    template<> struct HashTrait {
+        static size_t hashCode(const Key& key) { return reinterpret_cast( ... ); }
+    }; 
+  
+ + and one of + +
+    template<> struct EqualsTrait{
+         static bool equals(const Key& a, const Key& b) { return ... ; }
+    };
+
+
+    bool operator==(const Key&, const Key&);
+  
+ + G3D pre-defines HashTrait specializations for common types (like int and std::string). + If you use a Table with a different type you must write those functions yourself. For example, + an enum would use: + +
+    template<> struct HashTrait {
+        static size_t equals(const MyEnum& key) const { return reinterpret_cast( key ); }
+    };
+  
+ + And rely on the default enum operator==. + + + Periodically check that debugGetLoad() is low (> 0.1). When it gets near + 1.0 your hash function is badly designed and maps too many inputs to + the same output. + */ +template, class EqualsFunc = EqualsTrait > +class Table { +public: + + /** + The pairs returned by iterator. + */ + class Entry { + public: + Key key; + Value value; + Entry() {} + Entry(const Key& k) : key(k) {} + Entry(const Key& k, const Value& v) : key(k), value(v) {} + bool operator==(const Entry &peer) const { return (key == peer.key && value == peer.value); } + bool operator!=(const Entry &peer) const { return !operator==(peer); } + }; + +private: + + typedef Table ThisType; + + /** + Linked list nodes used internally by HashTable. + */ + class Node { + public: + Entry entry; + size_t hashCode; + Node* next; + + private: + + // Private to require use of the allocator + Node(const Key& k, const Value& v, size_t h, Node* n) + : entry(k, v), hashCode(h), next(n) { + } + + Node(const Key& k, size_t h, Node* n) + : entry(k), hashCode(h), next(n) { + } + + public: + + static Node* create(const Key& k, const Value& v, size_t h, Node* n, MemoryManager::Ref& mm) { + Node* node = (Node*)mm->alloc(sizeof(Node)); + return new (node) Node(k, v, h, n); + } + + static Node* create(const Key& k, size_t hashCode, Node* n, MemoryManager::Ref& mm) { + Node* node = (Node*)mm->alloc(sizeof(Node)); + return new (node) Node(k, hashCode, n); + } + + static void destroy(Node* n, MemoryManager::Ref& mm) { + n->~Node(); + mm->free(n); + } + + /** + Clones a whole chain; + */ + Node* clone(MemoryManager::Ref& mm) { + return create(this->entry.key, this->entry.value, hashCode, (next == NULL) ? NULL : next->clone(mm), mm); + } + }; + + void checkIntegrity() const { +# ifdef G3D_DEBUG + debugAssert(m_bucket == NULL || isValidHeapPointer(m_bucket)); + for (size_t b = 0; b < m_numBuckets; ++b) { + Node* node = m_bucket[b]; + debugAssert(node == NULL || isValidHeapPointer(node)); + while (node != NULL) { + debugAssert(node == NULL || isValidHeapPointer(node)); + node = node->next; + } + } +# endif + } + + /** Number of elements in the table.*/ + size_t m_size; + + /** + Array of Node*. + + We don't use Array because Table is lower-level than Array. + Some elements may be NULL. + */ + Node** m_bucket; + + /** + Length of the m_bucket array. + */ + size_t m_numBuckets; + + MemoryManager::Ref m_memoryManager; + + void* alloc(size_t s) const { + return m_memoryManager->alloc(s); + } + + void free(void* p) const { + return m_memoryManager->free(p); + } + + /** + Re-hashes for a larger m_bucket size. + */ + void resize(size_t newSize) { + + // Hang onto the old m_bucket array + Node** oldBucket = m_bucket; + + // Allocate a new m_bucket array with the new size + m_bucket = (Node**)alloc(sizeof(Node*) * newSize); + // Set all pointers to NULL + System::memset(m_bucket, 0, newSize * sizeof(Node*)); + debugAssertM(m_bucket != NULL, "MemoryManager::alloc returned NULL. Out of memory."); + // Move each node to its new hash location + for (size_t b = 0; b < m_numBuckets; ++b) { + Node* node = oldBucket[b]; + + // There is a linked list of nodes at this m_bucket + while (node != NULL) { + // Hang onto the old next pointer + Node* nextNode = node->next; + + // Insert at the head of the list for m_bucket[i] + size_t i = node->hashCode % newSize; + node->next = m_bucket[i]; + m_bucket[i] = node; + + // Move on to the next node + node = nextNode; + } + + // Drop the old pointer for cleanliness when debugging + oldBucket[b] = NULL; + } + + // Delete the old storage + free(oldBucket); + this->m_numBuckets = newSize; + + checkIntegrity(); + } + + + void copyFrom(const ThisType& h) { + if (&h == this) { + return; + } + + debugAssert(m_bucket == NULL); + m_size = h.m_size; + m_numBuckets = h.m_numBuckets; + m_bucket = (Node**)alloc(sizeof(Node*) * m_numBuckets); + // No need to NULL elements since we're about to overwrite them + + for (size_t b = 0; b < m_numBuckets; ++b) { + if (h.m_bucket[b] != NULL) { + m_bucket[b] = h.m_bucket[b]->clone(m_memoryManager); + } else { + m_bucket[b] = NULL; + } + } + + checkIntegrity(); + } + + /** + Frees the heap structures for the nodes. + */ + void freeMemory() { + checkIntegrity(); + + for (size_t b = 0; b < m_numBuckets; b++) { + Node* node = m_bucket[b]; + while (node != NULL) { + Node* next = node->next; + Node::destroy(node, m_memoryManager); + node = next; + } + m_bucket[b] = NULL; + } + free(m_bucket); + m_bucket = NULL; + m_numBuckets = 0; + m_size = 0; + } + +public: + + /** + Creates an empty hash table using the default MemoryManager. + */ + Table() : m_bucket(NULL) { + m_memoryManager = MemoryManager::create(); + m_numBuckets = 0; + m_size = 0; + m_bucket = NULL; + checkIntegrity(); + } + + /** Changes the internal memory manager to m */ + void clearAndSetMemoryManager(const MemoryManager::Ref& m) { + clear(); + debugAssert(m_bucket == NULL); + m_memoryManager = m; + } + + /** + Recommends that the table resize to anticipate at least this number of elements. + */ + void setSizeHint(size_t n) { + size_t s = n * 3; + if (s > m_numBuckets) { + resize(s); + } + } + + /** + Destroys all of the memory allocated by the table, but does not + call delete on keys or values if they are pointers. If you want to + deallocate things that the table points at, use getKeys() and Array::deleteAll() + to delete them. + */ + virtual ~Table() { + freeMemory(); + } + + /** Uses the default memory manager */ + Table(const ThisType& h) { + m_memoryManager = MemoryManager::create(); + m_numBuckets = 0; + m_size = 0; + m_bucket = NULL; + this->copyFrom(h); + checkIntegrity(); + } + + + Table& operator=(const ThisType& h) { + // No need to copy if the argument is this + if (this != &h) { + // Free the existing nodes + freeMemory(); + this->copyFrom(h); + checkIntegrity(); + } + return *this; + } + + /** + Returns the length of the deepest m_bucket. + */ + size_t debugGetDeepestBucketSize() const { + size_t deepest = 0; + + for (size_t b = 0; b < m_numBuckets; b++) { + size_t count = 0; + Node* node = m_bucket[b]; + while (node != NULL) { + node = node->next; + ++count; + } + + if (count > deepest) { + deepest = count; + } + } + + return deepest; + } + + /** + Returns the average size of non-empty buckets. + */ + float debugGetAverageBucketSize() const { + size_t num = 0; + size_t count = 0; + + for (size_t b = 0; b < m_numBuckets; b++) { + Node* node = m_bucket[b]; + if (node != NULL) { + ++num; + while (node != NULL) { + node = node->next; + ++count; + } + } + } + + return (float)((double)count / num); + } + + /** + A small load (close to zero) means the hash table is acting very + efficiently most of the time. A large load (close to 1) means + the hash table is acting poorly-- all operations will be very slow. + A large load will result from a bad hash function that maps too + many keys to the same code. + */ + double debugGetLoad() const { + return debugGetDeepestBucketSize() / (double)size(); + } + + /** + Returns the number of buckets. + */ + size_t debugGetNumBuckets() const { + return m_numBuckets; + } + + /** + C++ STL style iterator variable. See begin(). + */ + class Iterator { + private: + friend class Table; + + /** + Bucket index. + */ + size_t index; + + /** + Linked list node. + */ + Node* node; + ThisType* table; + size_t m_numBuckets; + Node** m_bucket; + bool isDone; + + /** + Creates the end iterator. + */ + Iterator(const ThisType* table) : table(const_cast(table)) { + isDone = true; + } + + Iterator(const ThisType* table, size_t m_numBuckets, Node** m_bucket) : + table(const_cast(table)), + m_numBuckets(m_numBuckets), + m_bucket(m_bucket) { + + if (m_numBuckets == 0) { + // Empty table + isDone = true; + return; + } + + index = 0; + node = m_bucket[index]; + isDone = false; + findNext(); + } + + /** + Finds the next element, setting isDone if one can't be found. + Looks at the current element first. + */ + void findNext() { + while (node == NULL) { + index++; + if (index >= m_numBuckets) { + isDone = true; + break; + } else { + node = m_bucket[index]; + } + } + } + + public: + inline bool operator!=(const Iterator& other) const { + return !(*this == other); + } + + bool operator==(const Iterator& other) const { + if (other.isDone || isDone) { + // Common case; check against isDone. + return (isDone == other.isDone) && (other.table == table); + } else { + return + (table == other.table) && + (node == other.node) && + (index == other.index); + } + } + + /** + Pre increment. + */ + Iterator& operator++() { + node = node->next; + findNext(); + return *this; + } + + /** + Post increment (slower than preincrement). + */ + Iterator operator++(int) { + Iterator old = *this; + ++(*this); + return old; + } + + const Entry& operator*() const { + return node->entry; + } + + Entry* operator->() const { + return &(node->entry); + } + + operator Entry*() const { + return &(node->entry); + } + + bool hasMore() const { + return ! isDone; + } + }; + + + /** + C++ STL style iterator method. Returns the first Entry, which + contains a key and value. Use preincrement (++entry) to get to + the next element. Do not modify the table while iterating. + */ + Iterator begin() const { + return Iterator(this, m_numBuckets, m_bucket); + } + + /** + C++ STL style iterator method. Returns one after the last iterator + element. + */ + const Iterator end() const { + return Iterator(this); + } + + /** + Removes all elements + */ + void clear() { + freeMemory(); + m_numBuckets = 0; + m_size = 0; + m_bucket = NULL; + } + + + /** + Returns the number of keys. + */ + size_t size() const { + return m_size; + } + + + /** + If you insert a pointer into the key or value of a table, you are + responsible for deallocating the object eventually. Inserting + key into a table is O(1), but may cause a potentially slow rehashing. + */ + void set(const Key& key, const Value& value) { + getCreateEntry(key).value = value; + } + +private: + + /** Helper for remove() and getRemove() */ + bool remove(const Key& key, Key& removedKey, Value& removedValue, bool updateRemoved) { + if (m_numBuckets == 0) { + return false; + } + size_t code = HashFunc::hashCode(key); + size_t b = code % m_numBuckets; + + // Go to the m_bucket + Node* n = m_bucket[b]; + + if (n == NULL) { + return false; + } + + Node* previous = NULL; + + // Try to find the node + do { + if ((code == n->hashCode) && EqualsFunc::equals(n->entry.key, key)) { + // This is the node; remove it + + // Replace the previous's next pointer + if (previous == NULL) { + m_bucket[b] = n->next; + } else { + previous->next = n->next; + } + + if (updateRemoved) { + removedKey = n->entry.key; + removedValue = n->entry.value; + } + // Delete the node + Node::destroy(n, m_memoryManager); + --m_size; + return true; + } + + previous = n; + n = n->next; + } while (n != NULL); + + return false; + //alwaysAssertM(false, "Tried to remove a key that was not in the table."); + } + +public: + + /** If @a member is present, sets @a removed to the element + being removed and returns true. Otherwise returns false + and does not write to @a removed. */ + bool getRemove(const Key& key, Key& removedKey, Value& removedValue) { + return remove(key, removedKey, removedValue, true); + } + + /** + Removes an element from the table if it is present. + @return true if the element was found and removed, otherwise false + */ + bool remove(const Key& key) { + Key x; + Value v; + return remove(key, x, v, false); + } + +private: + + Entry* getEntryPointer(const Key& key) const { + if (m_numBuckets == 0) { + return NULL; + } + + size_t code = HashFunc::hashCode(key); + size_t b = code % m_numBuckets; + + Node* node = m_bucket[b]; + + while (node != NULL) { + if ((node->hashCode == code) && EqualsFunc::equals(node->entry.key, key)) { + return &(node->entry); + } + node = node->next; + } + + return NULL; + } + +public: + + /** If a value that is EqualsFunc to @a member is present, returns a pointer to the + version stored in the data structure, otherwise returns NULL. + */ + const Key* getKeyPointer(const Key& key) const { + const Entry* e = getEntryPointer(key); + if (e == NULL) { + return NULL; + } else { + return &(e->key); + } + } + + /** + Returns the value associated with key. + @deprecated Use get(key, val) or getPointer(key) + */ + Value& get(const Key& key) const { + Entry* e = getEntryPointer(key); + debugAssertM(e != NULL, "Key not found"); + return e->value; + } + + + /** Returns a pointer to the element if it exists, or NULL if it does not. + Note that if your value type is a pointer, the return value is + a pointer to a pointer. Do not remove the element while holding this + pointer. + + It is easy to accidentally mis-use this method. Consider making + a Table and using get(key, val) instead, which makes you manage + the memory for the values yourself and is less likely to result in + pointer errors. + */ + Value* getPointer(const Key& key) const { + if (m_numBuckets == 0) { + return NULL; + } + + size_t code = HashFunc::hashCode(key); + size_t b = code % m_numBuckets; + + Node* node = m_bucket[b]; + + while (node != NULL) { + if ((node->hashCode == code) && EqualsFunc::equals(node->entry.key, key)) { + // found key + return &(node->entry.value); + } + node = node->next; + } + + // Failed to find key + return NULL; + } + + /** + If the key is present in the table, val is set to the associated value and returns true. + If the key is not present, returns false. + */ + bool get(const Key& key, Value& val) const { + Value* v = getPointer(key); + if (v != NULL) { + val = *v; + return true; + } else { + return false; + } + } + + + + /** Called by getCreate() and set() + + \param created Set to true if the entry was created by this method. + */ + Entry& getCreateEntry(const Key& key, bool& created) { + created = false; + + if (m_numBuckets == 0) { + resize(10); + } + + size_t code = HashFunc::hashCode(key); + size_t b = code % m_numBuckets; + + // Go to the m_bucket + Node* n = m_bucket[b]; + + // No m_bucket, so this must be the first + if (n == NULL) { + m_bucket[b] = Node::create(key, code, NULL, m_memoryManager); + ++m_size; + created = true; + return m_bucket[b]->entry; + } + + size_t bucketLength = 1; + + // Sometimes a bad hash code will cause all elements + // to collide. Detect this case and don't rehash when + // it occurs; nothing good will come from the rehashing. + bool allSameCode = true; + + // Try to find the node + do { + allSameCode = allSameCode && (code == n->hashCode); + + if ((code == n->hashCode) && EqualsFunc::equals(n->entry.key, key)) { + // This is the a pre-existing node + return n->entry; + } + + n = n->next; + ++bucketLength; + } while (n != NULL); + + const size_t maxBucketLength = 3; + // (Don't bother changing the size of the table if all entries + // have the same hashcode--they'll still collide) + if ((bucketLength > maxBucketLength) && + ! allSameCode && + (m_numBuckets < m_size * 15)) { + + // This m_bucket was really large; rehash if all elements + // don't have the same hashcode the number of buckets is + // reasonable. + + // Back off the scale factor as the number of buckets gets + // large + float f = 3.0f; + if (m_numBuckets > 1000000) { + f = 1.5f; + } else if (m_numBuckets > 100000) { + f = 2.0f; + } + int newSize = iMax((int)(m_numBuckets * f) + 1, (int)(m_size * f)); + resize(newSize); + } + + // Not found; insert at the head. + b = code % m_numBuckets; + m_bucket[b] = Node::create(key, code, m_bucket[b], m_memoryManager); + ++m_size; + created = true; + return m_bucket[b]->entry; + } + + Entry& getCreateEntry(const Key& key) { + bool ignore; + return getCreateEntry(key, ignore); + } + + + /** Returns the current value that key maps to, creating it if necessary.*/ + Value& getCreate(const Key& key) { + return getCreateEntry(key).value; + } + + /** \param created True if the element was created. */ + Value& getCreate(const Key& key, bool& created) { + return getCreateEntry(key, created).value; + } + + + /** + Returns true if key is in the table. + */ + bool containsKey(const Key& key) const { + if (m_numBuckets == 0) { + return false; + } + + size_t code = HashFunc::hashCode(key); + size_t b = code % m_numBuckets; + + Node* node = m_bucket[b]; + + while (node != NULL) { + if ((node->hashCode == code) && EqualsFunc::equals(node->entry.key, key)) { + return true; + } + node = node->next; + } while (node != NULL); + + return false; + } + + + /** + Short syntax for get. + */ + inline Value& operator[](const Key &key) const { + return get(key); + } + + /** + Returns an array of all of the keys in the table. + You can iterate over the keys to get the values. + @deprecated + */ + Array getKeys() const { + Array keyArray; + getKeys(keyArray); + return keyArray; + } + + void getKeys(Array& keyArray) const { + keyArray.resize(0, DONT_SHRINK_UNDERLYING_ARRAY); + for (size_t i = 0; i < m_numBuckets; i++) { + Node* node = m_bucket[i]; + while (node != NULL) { + keyArray.append(node->entry.key); + node = node->next; + } + } + } + + /** + Calls delete on all of the keys and then clears the table. + */ + void deleteKeys() { + for (size_t i = 0; i < m_numBuckets; i++) { + Node* node = m_bucket[i]; + while (node != NULL) { + delete node->entry.key; + node = node->next; + } + } + clear(); + } + + /** + Calls delete on all of the values. This is unsafe-- + do not call unless you know that each value appears + at most once. + + Does not clear the table, so you are left with a table + of NULL pointers. + */ + void deleteValues() { + for (size_t i = 0; i < m_numBuckets; ++i) { + Node* node = m_bucket[i]; + while (node != NULL) { + delete node->entry.value; + node->entry.value = NULL; + node = node->next; + } + } + } +}; + +} // namespace + +#ifdef _MSC_VER +# pragma warning (pop) +#endif + +#endif diff --git a/dep/g3dlite/G3D/TextInput.h b/dep/g3dlite/G3D/TextInput.h new file mode 100644 index 00000000000..33eb8c48e53 --- /dev/null +++ b/dep/g3dlite/G3D/TextInput.h @@ -0,0 +1,801 @@ +/** + @file TextInput.h + + Simple text lexer/tokenizer. + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @cite Based on a lexer written by Aaron Orenstein. + + @created 2002-11-27 + @edited 2009-11-24 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_TextInput_h +#define G3D_TextInput_h + +#include "G3D/platform.h" +#include "G3D/Array.h" +#include "G3D/Set.h" +#include "G3D/ParseError.h" +#include +#include +#include +#include + +namespace G3D { + +/** + For use with TextInput. + */ +class Token { +public: + + /** + More detailed type information than Type. + */ + enum ExtendedType { + DOUBLE_QUOTED_TYPE, + SINGLE_QUOTED_TYPE, + SYMBOL_TYPE, + FLOATING_POINT_TYPE, + INTEGER_TYPE, + BOOLEAN_TYPE, + LINE_COMMENT_TYPE, + BLOCK_COMMENT_TYPE, + NEWLINE_TYPE, + END_TYPE + }; + + /** + Strings are enclosed in quotes, symbols are not. + */ + enum Type { + STRING = DOUBLE_QUOTED_TYPE, + SYMBOL = SYMBOL_TYPE, + NUMBER = FLOATING_POINT_TYPE, + BOOLEAN = BOOLEAN_TYPE, + COMMENT = LINE_COMMENT_TYPE, + NEWLINE = NEWLINE_TYPE, + END = END_TYPE + }; + +private: + + friend class TextInput; + + /** + Holds the actual value, which might be any type. If a number, it will be + parsed at runtime. + */ + std::string _string; + + bool _bool; + int _line; + int _character; + Type _type; + ExtendedType _extendedType; + +public: + + Token() : + _string(""), + _bool(false), + _line(0), + _character(0), + _type(END), + _extendedType(END_TYPE) {} + + Token(Type t, ExtendedType e, const std::string& s, int L, int c) + : _string(s), _bool(false), _line(L), _character(c), _type(t), _extendedType(e) {} + + Token(Type t, ExtendedType e, const std::string& s, bool b, int L, int c) + : _string(s), _bool(b), _line(L), _character(c), _type(t), _extendedType(e) {} + + Type type() const { + return _type; + } + + ExtendedType extendedType() const { + return _extendedType; + } + + /** + The value of a single or double quote string (not including the quotes), + the name of a symbol, or the exact textual representation of a number as + parsed from the input. + */ + const std::string& string() const { + return _string; + } + + bool boolean() const { + return _bool; + } + + /** + Starting line of the input from which this token was parsed. Starts + at 1. + */ + int line() const { + return _line; + } + + /** + Starting character position in the input line from which this token was + parsed. Starts at 1. + */ + int character() const { + return _character; + } + + /** Return the numeric value for a number type, or zero if this is + not a number type. + */ + double number() const; +}; + + +/** + A simple style tokenizer for reading text files. TextInput handles a + superset of C++,Java, Matlab, and Bash code text including single + line comments, block comments, quoted strings with escape sequences, + and operators. TextInput recognizes several categories of tokens, + which are separated by white space, quotation marks, or the end of a + recognized operator: + +
    +
  • Token::SINGLE_QUOTED_TYPE string of characters surrounded by single quotes, e.g., 'x', '\\0', 'foo'. +
  • Token::DOUBLE_QUOTED_TYPE string of characters surrounded by double quotes, e.g., "x", "abc\txyz", "b o b". +
  • Token::SYMBOL_TYPE legal C++ operators, keywords, and identifiers. e.g., >=, Foo, _X, class, { +
  • Token::INTEGER_TYPE numbers without decimal places or exponential notation. e.g., 10, 0x17F, 32, 0, -155 +
  • Token::FLOATING_POINT_TYPE numbers with decimal places or exponential notation. e.g., 1e3, -1.2, .4, 0.5 +
  • Token::BOOLEAN_TYPE special symbols like "true" and "false"; the exact details can be configured in TextInput::Settings +
  • Token::LINE_COMMENT_TYPE (disabled by default); generated for line comments as specified by TextInput::Settings +
  • Token::BLOCK_COMMENT_TYPE (disabled by default); generated for c-style block comments as specified by TextInput::Settings +
  • Token::NEWLINE_TYPE (disabled by default); generated for any of "\\r", "\\n" or "\\r\\n" +
+ +

The special ".." and "..." tokens are always recognized in + addition to normal C++ operators. Additional tokens can be made + available by changing the Settings. + + Negative numbers are handled specially because of the ambiguity between unary minus and negative numbers-- + see the note on TextInput::read. + + TextInput does not have helper functions for types with non-obvious + formatting, or helpers that would be redundant. Use the serialize + methods instead for parsing specific types like int, Vector3, and + Color3. + + Inside quoted strings escape sequences are converted. Thus the + string token for ["a\\nb"] is 'a', followed by a newline, followed by + 'b'. Outside of quoted strings, escape sequences are not converted, + so the token sequence for [a\\nb] is symbol 'a', symbol '\\', symbol + 'nb' (this matches what a C++ parser would do). The exception is + that a specified TextInput::Settings::otherCommentCharacter preceeded + by a backslash is assumed to be an escaped comment character and is + returned as a symbol token instead of being parsed as a comment + (this is what a LaTex or VRML parser would do). + + Examples + +

+  TextInput ti(TextInput::FROM_STRING, "name = \"Max\", height = 6");
+
+  Token t;
+
+  t = ti.read(); 
+  debugAssert(t.type == Token::SYMBOL);
+  debugAssert(t.sval == "name");
+
+  ti.read();
+  debugAssert(t.type == Token::SYMBOL);
+  debugAssert(t.sval == "=");
+
+  std::string name = ti.read().sval;
+  ti.read();
+  
+ +
+  TextInput ti(TextInput::FROM_STRING, "name = \"Max\", height = 6");
+  ti.readSymbols("name", "=");
+  std::string name = ti.readString();
+  ti.readSymbols(",", "height", "=");
+  double height = ti. readNumber();
+  
+ + Assumes that the file is not modified once opened. + */ +class TextInput { +public: + + /** Tokenizer configuration options. */ + class Settings { + public: + /** If true, C-style slash-star marks a multi-line comment. + + See generateCommentTokens for rules on how this is applied. + + Default is true. + */ + bool cppBlockComments; + + /** If true, // begins a single line comment. + + See generateCommentTokens for rules on how this is applied. + + Default is true. + */ + bool cppLineComments; + + /** If true, otherCommentCharacter and otherCommentCharacter2 + are used to begin single line comments in the same way + cppLineComments is. + + See generateCommentTokens for rules on how this is applied. + + Default is true. + */ + bool otherLineComments; + + /** If true, \\r, \\n, \\t, \\0, \\\\ and other escape sequences inside + strings are converted to the equivalent C++ escaped character. + If false, backslashes are treated literally. It is convenient to + set to false if reading Windows paths, for example, like + c:\\foo\\bar. + + Default is true. + */ + bool escapeSequencesInStrings; + + /** If not '\\0', specifies a character that begins single line + comments ('#' and '%' are popular choices). This is independent + of the cppLineComments flag. If the character appears in text with + a backslash in front of it, it is considered escaped and is not + treated as a comment character. + + Default is '\\0'. + */ + char otherCommentCharacter; + + /** Another (optional) 1-comment character. Useful for files that + support multiple comment syntaxes. Default is '\\0'. + */ + char otherCommentCharacter2; + + /** If true, comments enabled by cppBlockComments, cppLineComments + and otherLineComments will generate their respective tokens. + If false, the same settings will enable parsing and ignoring + comments + + Default is false. + */ + bool generateCommentTokens; + + /** If true, newlines will generate tokens. + If false, newlines will be discarded as whitespace when parsed + outside of other tokens. + + Default is false. + */ + bool generateNewlineTokens; + + /** If true, "-1" parses as the number -1 instead of the + symbol "-" followed by the number 1. Default is true.*/ + bool signedNumbers; + + /** If true, strings can be marked with single quotes (e.g., + 'aaa'). If false, the quote character is parsed as a + symbol. Default is true. Backquote (`) is always parsed + as a symbol. */ + bool singleQuotedStrings; + + /** The character to use as a single quote. Defaults to "'" (backquote), + occasionally useful to set to "`" (forward quote) or to "," (comma) for + reading CSV files. */ + char singleQuoteCharacter; + + /** If set to a non-empty string, that string will be used in + place of the real file name (or in place of a pseudonym + constructed from the buffer if given FROM_STRING) in + tokens and exceptions. + + Default is empty. + */ + std::string sourceFileName; + + + /** Added to the line number reported by peekLineNumber and in + exceptions. Useful for concatenating files that are + parsed separately. Default is zero. */ + int startingLineNumberOffset; + + /** + Parse -1.#IND00 as the floating point number returned by + nan(), -1.#INF00 as -inf(), and 1.#INF00 as inf(). Note + that the C99 standard specifies that a variety of formats + like "NaN" and "nan" are to be used; these are easier to + parse yourself and not currently supported by readNumber. + + An alternative to specifying msvcSpecials is to read numbers as: +
+            Token x = t.read();
+            Token y = t.peek();
+            if ((x.string() == "-1.") && 
+                (y.string() == "#INF00") && 
+                (y.character() == x.character() + 3) &&
+                (y.line() == x.line()) {
+                t.read();
+                return nan();
+            }
+            // ... similar cases for inf
+          
+ + If the single-comment character was #, the floating point + special format overrides the comment and will be parsed + instead. + + If signedNumbers is false msvcSpecials will not be parsed. + + Default is true. */ + bool msvcSpecials; + + /** + Parse the following set of useful proof symbols: + + => + ::> + <:: + :> + <: + |- + ::= + := + <- + + Default is false. + */ + bool proofSymbols; + + /** + When parsing booleans and msvcSpecials, is case significant? + Default is {true} + */ + bool caseSensitive; + + /** All symbols that will become the 'true' boolean token. See also caseSensitive. + Clear this value to disable parsing of true booleans. + + Default is {true}. + */ + Set trueSymbols; + + /** See trueSymbols. Default is {false}*/ + Set falseSymbols; + + Settings(); + }; + +private: + + std::deque stack; + + /** + Characters to be tokenized. + */ + Array buffer; + + /** + Offset of current character (the next character to consumed) in + input buffer. + */ + int currentCharOffset; + + /** + Line number of next character to be consumed from the input buffer. (1 + indicates first line of input.) + + Note that this is the line number of the @e next character to be + consumed from the input, not the line number of the @e last character + consumed! + */ + int lineNumber; + + /** + Character number (within the line) of the next character to be consumed + from the input buffer. (1 indicates first character of the line). + + Note that this is the character number of the @e next character to be + consumed from the input, not the character number of the @e last + character consumed! + */ + int charNumber; + + /** Configuration options. This includes the file name that will be + reported in tokens and exceptions. */ + Settings options; + + void init(); + + /** + Consumes the next character from the input buffer, and returns that + character. Updates lineNumber and charNumber to reflect the location of + the next character in the input buffer. + + Note: you shouldn't be using the return value of this function in most + cases. In general, you should peekInputChar() to get the next + character, determine what to do with it, then consume it with this + function (or with eatAndPeekInputChar()). Given that usage, in most + instances you already know what this function would return! + */ + int eatInputChar(); + + /** + Returns the next character from the input buffer, without consuming any + characters. Can also be used to look deeper into the input buffer. + Does not modify lineNumber or charNumber. + + @param distance Index of the character in the input buffer to peek at, + relative to the next character. Default is 0, for the next character in + the input buffer. + */ + int peekInputChar(int distance = 0); + + /** + Helper function to consume the next character in the input buffer and + peek at the one following (without consuming it). + */ + inline int eatAndPeekInputChar() { + eatInputChar(); + return peekInputChar(0); + } + + /** + Read the next token, returning an END token if no more input is + available. + */ + Token nextToken(); + + /** + Helper for nextToken. Appends characters to t._string until the end + delimiter is reached. + + When called, the next character in the input buffer should be first the + first character after the opening delimiter character. + */ + void parseQuotedString(unsigned char delimiter, Token& t); + +public: + + class TokenException : public ParseError { + public: + /** Name of file being parsed when exception occurred. + \deprecated Use filename + */ + std::string sourceFile; + + virtual ~TokenException() {} + + protected: + + TokenException( + const std::string& src, + int ln, + int ch); + + }; + + /** While parsing a number of the form 1.\#IN?00, ? was + not 'D' or 'F'. */ + class BadMSVCSpecial : public TokenException { + public: + + BadMSVCSpecial( + const std::string& src, + int ln, + int ch); + }; + + /** Thrown by the read methods. */ + class WrongTokenType : public TokenException { + public: + Token::Type expected; + Token::Type actual; + + WrongTokenType( + const std::string& src, + int ln, + int ch, + Token::Type e, + Token::Type a); + }; + + class WrongSymbol : public TokenException { + public: + std::string expected; + std::string actual; + + WrongSymbol( + const std::string& src, + int ln, + int ch, + const std::string& e, + const std::string& a); + }; + + + /** String read from input did not match expected string. */ + class WrongString : public TokenException { + public: + std::string expected; + std::string actual; + + WrongString( + const std::string& src, + int ln, + int ch, + const std::string& e, + const std::string& a); + }; + + TextInput(const std::string& filename, const Settings& settings = Settings()); + + enum FS {FROM_STRING}; + /** Creates input directly from a string. The first argument must be + TextInput::FROM_STRING. + */ + TextInput(FS fs, const std::string& str, const Settings& settings = Settings()); + + /** Returns true while there are tokens remaining. */ + bool hasMore(); + + /** Read the next token (which will be the END token if ! hasMore()). + + Signed numbers can be handled in one of two modes. If the option + TextInput::Settings::signedNumbers is true, + A '+' or '-' immediately before a number is prepended onto that number and + if there is intervening whitespace, it is read as a separate symbol. + + If TextInput::Settings::signedNumbers is false, + read() does not distinguish between a plus or minus symbol next + to a number and a positive/negative number itself. For example, "x - 1" and "x -1" + will be parsed the same way by read(). + + In both cases, readNumber() will contract a leading "-" or "+" onto + a number. + */ + Token read(); + + /** Calls read() until the result is not a newline or comment */ + Token readSignificant(); + + /** Read one token (or possibly two) as a number or throws + WrongTokenType, and returns the number. + + If the first token in the input is a number, it is returned directly. + + If TextInput::Settings::signedNumbers is false and the input stream + contains a '+' or '-' symbol token immediately followed by a number + token, both tokens will be consumed and a single token will be + returned by this method. + + WrongTokenType will be thrown if one of the input conditions + described above is not satisfied. When an exception is thrown, no + tokens are consumed. + */ + double readNumber(); + + bool readBoolean(); + + /** Reads a string token or throws WrongTokenType, and returns the token. + + Use this method (rather than readString) if you want the token's + location as well as its value. + + WrongTokenType will be thrown if the next token in the input stream + is not a string. When an exception is thrown, no tokens are + consumed. + */ + Token readStringToken(); + + /** Like readStringToken, but returns the token's string. + + Use this method (rather than readStringToken) if you want the token's + value but don't really care about its location in the input. Use of + readStringToken is encouraged for better error reporting. + */ + std::string readString(); + + /** Reads a specific string token or throws either WrongTokenType or + WrongString. If the next token in the input is a string matching @p + s, it will be consumed. + + Use this method if you want to match a specific string from the + input. In that case, typically error reporting related to the token + is only going to occur because of a mismatch, so no location + information is needed by the caller. + + WrongTokenType will be thrown if the next token in the input stream + is not a string. WrongString will be thrown if the next token in the + input stream is a string but does not match the @p s parameter. When + an exception is thrown, no tokens are consumed. + */ + void readString(const std::string& s); + + /** Reads a comment token or throws WrongTokenType, and returns the token. + + Use this method (rather than readComment) if you want the token's + location as well as its value. + + WrongTokenType will be thrown if the next token in the input stream + is not a comment. When an exception is thrown, no tokens are + consumed. + */ + Token readCommentToken(); + + /** Like readCommentToken, but returns the token's string. + + Use this method (rather than readCommentToken) if you want the token's + value but don't really care about its location in the input. Use of + readCommentToken is encouraged for better error reporting. + */ + std::string readComment(); + + /** Reads a specific comment token or throws either WrongTokenType or + WrongString. If the next token in the input is a comment matching @p + s, it will be consumed. + + Use this method if you want to match a specific comment from the + input. In that case, typically error reporting related to the token + is only going to occur because of a mismatch, so no location + information is needed by the caller. + + WrongTokenType will be thrown if the next token in the input stream + is not a comment. WrongString will be thrown if the next token in the + input stream is a comment but does not match the @p s parameter. When + an exception is thrown, no tokens are consumed. + */ + void readComment(const std::string& s); + + /** Reads a newline token or throws WrongTokenType, and returns the token. + + Use this method (rather than readNewline) if you want the token's + location as well as its value. + + WrongTokenType will be thrown if the next token in the input stream + is not a newline. When an exception is thrown, no tokens are + consumed. + */ + Token readNewlineToken(); + + /** Like readNewlineToken, but returns the token's string. + + Use this method (rather than readNewlineToken) if you want the token's + value but don't really care about its location in the input. Use of + readNewlineToken is encouraged for better error reporting. + */ + std::string readNewline(); + + /** Reads a specific newline token or throws either WrongTokenType or + WrongString. If the next token in the input is a newline matching @p + s, it will be consumed. + + Use this method if you want to match a specific newline from the + input. In that case, typically error reporting related to the token + is only going to occur because of a mismatch, so no location + information is needed by the caller. + + WrongTokenType will be thrown if the next token in the input stream + is not a newline. WrongString will be thrown if the next token in the + input stream is a newlin but does not match the @p s parameter. When + an exception is thrown, no tokens are consumed. + */ + void readNewline(const std::string& s); + + /** Reads a symbol token or throws WrongTokenType, and returns the token. + + Use this method (rather than readSymbol) if you want the token's + location as well as its value. + + WrongTokenType will be thrown if the next token in the input stream + is not a symbol. When an exception is thrown, no tokens are + consumed. + */ + Token readSymbolToken(); + + /** Like readSymbolToken, but returns the token's string. + + Use this method (rather than readSymbolToken) if you want the token's + value but don't really care about its location in the input. Use of + readSymbolToken is encouraged for better error reporting. + */ + std::string readSymbol(); + + /** Reads a specific symbol token or throws either WrongTokenType or + WrongSymbol. If the next token in the input is a symbol matching @p + symbol, it will be consumed. + + Use this method if you want to match a specific symbol from the + input. In that case, typically error reporting related to the token + is only going to occur because of a mismatch, so no location + information is needed by the caller. + + WrongTokenType will be thrown if the next token in the input stream + is not a symbol. WrongSymbol will be thrown if the next token in the + input stream is a symbol but does not match the @p symbol parameter. + When an exception is thrown, no tokens are consumed. + */ + void readSymbol(const std::string& symbol); + + + /** Read a series of two specific symbols. See readSymbol. */ + inline void readSymbols(const std::string& s1, const std::string& s2) { + readSymbol(s1); + readSymbol(s2); + } + + /** Read a series of three specific symbols. See readSymbol. */ + inline void readSymbols( + const std::string& s1, + const std::string& s2, + const std::string& s3) { + readSymbol(s1); + readSymbol(s2); + readSymbol(s3); + } + + /** Read a series of four specific symbols. See readSymbol. */ + inline void readSymbols( + const std::string& s1, + const std::string& s2, + const std::string& s3, + const std::string& s4) { + readSymbol(s1); + readSymbol(s2); + readSymbol(s3); + readSymbol(s4); + } + + /** Return a copy of the next token in the input stream, but don't remove + it from the input stream. + */ + Token peek(); + + /** Returns the line number for the @e next token. See also peek. */ + int peekLineNumber(); + + /** Returns the character number (relative to the line) for the @e next + token in the input stream. See also peek. + */ + int peekCharacterNumber(); + + /** Take a previously read token and push it back at the front of the + input stream. + + Can be used in the case where more than one token of read-ahead is + needed (i.e., when peek doesn't suffice). + */ + void push(const Token& t); + + /** Returns the filename from which this input is drawn, or the first few + characters of the string if created from a string. + If settings::filename is non-empty that will replace the + true filename.*/ + const std::string& filename() const; +}; + +void deserialize(bool& b, TextInput& ti); +void deserialize(int& b, TextInput& ti); +void deserialize(uint8& b, TextInput& ti); +void deserialize(double& b, TextInput& ti); +void deserialize(float& b, TextInput& ti); +void deserialize(std::string& b, TextInput& ti); + +} // namespace + +#endif + diff --git a/dep/g3dlite/G3D/TextOutput.h b/dep/g3dlite/G3D/TextOutput.h new file mode 100644 index 00000000000..4c22b7d5653 --- /dev/null +++ b/dep/g3dlite/G3D/TextOutput.h @@ -0,0 +1,249 @@ +/** + @file TextOutput.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + @created 2004-06-21 + @edited 2006-10-24 + + Copyright 2000-2007, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_TEXTOUTPUT_H +#define G3D_TEXTOUTPUT_H + +#include "G3D/platform.h" +#include "G3D/Array.h" +#include + +namespace G3D { + +/** + Convenient formatting of ASCII text written to a file. +

+ + The core writeString, writeNumber, and writeSymbol methods map to TextInput's + methods. Number and Symbol each print an additional space that is used to + separate adjacent tokens. + + TextOutput::printf allows arbitrary text to be conveniently dumped + en-masse. Use [de]serialize(bool, TextOutput) and other overloads to read/write + primitive types in a standardized manner and + +

+ When a word-wrap line break occurs, all whitespace between words is replaced + with a single newline (the newline may be two characters-- see + G3D::TextOutput::Options::NewlineStyle). Word wrapping occurs against + the number of columns specified by Options::numColumns, minus the current + indent level. + + Indenting adds the specified number of spaces immediately after a newline. + If a newline was followed by spaces in the original string, these are added + to the indent spaces. Indenting will indent blank lines and will leave + indents after the last newline of a file (if the indent level is non-zero at the end). + +

Serialization/Marshalling +

Text serialization is accomplished using TextOutput by defining the pair of + methods: + +
+  void serialize(TextOutput& to) const;
+  void deserialize(TextInput& ti);
+  
+ + See also G3D::TextInput. + +

+ BETA API +

This API is subject to change in future versions. + */ +class TextOutput { +public: + + class Settings { + public: + /** + WRAP_NONE Word wrapping is disabled + WRAP_WITHOUT_BREAKING Word-wrap, but don't break continuous lines that + are longer than numColumns (default) + WRAP_ALWAYS Wrap even if it means breaking a continuous line or + a quoted string. + + Word wrapping is only allowed at whitespaces ('\\n', '\\r', '\\t', ' '); it + will not occur after commas, punctuation, minus signs, or any other characters + */ + enum WordWrapMode {WRAP_NONE, WRAP_WITHOUT_BREAKING, WRAP_ALWAYS}; + + /** Defaults to WRAP_WITHOUT_BREAKING */ + WordWrapMode wordWrap; + + /** Is word-wrapping allowed to insert newlines inside double quotes? + Default: false */ + bool allowWordWrapInsideDoubleQuotes; + + /** Number of columns for word wrapping. Default: 8 */ + int numColumns; + + /** Number of spaces in each indent. Default: 4 */ + int spacesPerIndent; + + /** Style of newline used by word wrapping and by (optional) conversion. + default: Windows: NEWLINE_WINDOWS, Linux, OS X: NEWLINE_UNIX. + */ + enum NewlineStyle {NEWLINE_WINDOWS, NEWLINE_UNIX}; + + NewlineStyle newlineStyle; + + /** If true, all newlines are converted to NewlineStyle regardless of + how they start out. Default: true. */ + bool convertNewlines; + + /** Used by writeBoolean */ + std::string trueSymbol; + + /** Used by writeBoolean */ + std::string falseSymbol; + + Settings() : + wordWrap(WRAP_WITHOUT_BREAKING), + allowWordWrapInsideDoubleQuotes(false), + numColumns(80), + spacesPerIndent(4), + convertNewlines(true), + trueSymbol("true"), + falseSymbol("false") { + #ifdef G3D_WIN32 + newlineStyle = NEWLINE_WINDOWS; + #else + newlineStyle = NEWLINE_UNIX; + #endif + } + }; + +private: + + /** Used by indentAndAppend to tell when we are writing the + first character of a new line. + + So that push/popIndent work correctly, we cannot indent + immediately after writing a newline. Instead we must + indent on writing the first character after that + newline. + */ + bool startingNewLine; + + /** Number of characters at the end of the buffer since the last newline */ + int currentColumn; + + /** True if we have seen an open " and no close ".*/ + bool inDQuote; + + /** Empty if there is none */ + std::string filename; + + Array data; + + Settings option; + + /** Number of indents to prepend before each line. Always set using setIndentLevel.*/ + int indentLevel; + + void setIndentLevel(int i); + + /** Actual number of spaces to indent. */ + int indentSpaces; + + /** the newline character(s) */ + std::string newline; + + void setOptions(const Settings& _opt); + + /** Converts to the desired newlines. Called from vprintf */ + void convertNewlines(const std::string& in, std::string& out); + + /** Called from vprintf */ + void wordWrapIndentAppend(const std::string& str); + + /** Appends the character to data, indenting whenever a newline is encountered. + Called from wordWrapIndentAppend */ + void indentAppend(char c); + +public: + + explicit TextOutput(const std::string& filename, const Settings& options = Settings()); + + /** Constructs a text output that can later be commited to a string instead of a file.*/ + explicit TextOutput(const Settings& options = Settings()); + + /** Commit to the filename specified on the constructor. + Not called from the destructor; you must call + it yourself. + @param flush If true (default) the file is ready for reading when the method returns, otherwise + the method returns immediately and writes the file in the background.*/ + void commit(bool flush = true); + + /** Commits to this string */ + void commitString(std::string& string); + + /** Increase indent level by 1 */ + void pushIndent(); + + void popIndent(); + + /** Produces a new string that contains the output */ + std::string commitString(); + + /** Writes a quoted string. Special characters in the string (e.g., \\, \\t, \\n) are escaped so that + TextInput will produce the identical string on reading.*/ + void writeString(const std::string& string); + + void writeBoolean(bool b); + + void writeNumber(double n); + + void writeNumber(int n); + + void writeNewline(); + void writeNewlines(int numLines); + + /** The symbol is written without quotes. Symbols are required to begin with a + letter or underscore and contain only letters, underscores, and numbers + or be a C++ symbol (e.g. "{", "(", "++", etc.) + so that they may be properly parsed by TextInput::readSymbol. Symbols are + printed with a trailing space.*/ + void writeSymbol(const std::string& string); + + /** Convenient idiom for writing multiple symbols in a row, e.g. + writeSymbols("name", "="); The empty symbols are not written. + */ + void writeSymbols( + const std::string& a, + const std::string& b = "", + const std::string& c = "", + const std::string& d = "", + const std::string& e = "", + const std::string& f = ""); + + /** Normal printf conventions. Note that the output will be reformatted + for word-wrapping and newlines */ + void __cdecl printf(const char* fmt, ...) + G3D_CHECK_PRINTF_METHOD_ARGS; + + // Can't pass by reference because that confuses va_start + void __cdecl printf(const std::string fmt, ...); + void __cdecl vprintf(const char* fmt, va_list argPtr) + G3D_CHECK_VPRINTF_METHOD_ARGS; +}; + +// Primitive serializers +void serialize(const bool& b, TextOutput& to); +void serialize(const int& b, TextOutput& to); +void serialize(const uint8& b, TextOutput& to); +void serialize(const double& b, TextOutput& to); +void serialize(const float& b, TextOutput& to); +void serialize(const std::string& b, TextOutput& to); +void serialize(const char* b, TextOutput& to); + +} + +#endif diff --git a/dep/g3dlite/G3D/ThreadSet.h b/dep/g3dlite/G3D/ThreadSet.h new file mode 100644 index 00000000000..121f1415a1d --- /dev/null +++ b/dep/g3dlite/G3D/ThreadSet.h @@ -0,0 +1,87 @@ +#ifndef G3D_THREADSET_H +#define G3D_THREADSET_H + +#include "G3D/platform.h" +#include "G3D/Array.h" +#include "G3D/ReferenceCount.h" +#include "G3D/GThread.h" +#include "G3D/GMutex.h" + +namespace G3D { + +/** Manages a set of threads. All methods are threadsafe except for + the iterator begin/end. + + @beta*/ +class ThreadSet : public ReferenceCountedObject { +public: + /** Intended to allow future use with a template parameter.*/ + typedef GThread Thread; + + typedef ReferenceCountedPointer ThreadRef; + typedef ReferenceCountedPointer Ref; + typedef Array::Iterator Iterator; + typedef Array::ConstIterator ConstIterator; + +private: + + /** Protects m_thread */ + GMutex m_lock; + + /** Threads in the set */ + Array m_thread; + +public: + + /** Total number of threads (some of which may be completed). */ + int size() const; + + /** Number of threads that have been started */ + int numStarted() const; + + /** Start all threads that are not currently started. + + @param lastThreadBehavior If USE_CURRENT_THREAD, takes the last unstarted thread and executes it manually on + the current thread. This helps to take full advantage of the machine when + running a large number of jobs and avoids the overhead of a thread start for single-thread groups. + Note that this forces start() to block until + that thread is complete. + */ + void start(GThread::SpawnBehavior lastThreadBehavior = GThread::USE_NEW_THREAD) const; + + /** Terminate all threads that are currently started */ + void terminate() const; + + /** Waits until all started threads have completed. */ + void waitForCompletion() const; + + /** Remove all (not stopping them) */ + void clear(); + + /** Removes completed threads and returns the new size.*/ + int removeCompleted(); + + /** Inserts a new thread, if it is not already present, and + returns the new number of threads.*/ + int insert(const ThreadRef& t); + + /** Removes a thread. Returns true if the thread was present and + removed. */ + bool remove(const ThreadRef& t); + + bool contains(const ThreadRef& t) const; + + /** It is an error to mutate the ThreadSet while iterating through it. */ + Iterator begin(); + + Iterator end(); + + ConstIterator begin() const; + + ConstIterator end() const; +}; + + +} // namespace G3D + +#endif diff --git a/dep/g3dlite/G3D/Triangle.h b/dep/g3dlite/G3D/Triangle.h new file mode 100644 index 00000000000..590dbaad946 --- /dev/null +++ b/dep/g3dlite/G3D/Triangle.h @@ -0,0 +1,160 @@ +/** + @file Triangle.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2003-04-05 + @edited 2008-10-06 + + @cite Random point method by Greg Turk, Generating random points in triangles. In A. S. Glassner, ed., Graphics Gems, pp. 24-28. Academic Press, 1990 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_TRIANGLE_H +#define G3D_TRIANGLE_H + +#include "G3D/platform.h" +#include "G3D/g3dmath.h" +#include "G3D/Vector3.h" +#include "G3D/Plane.h" +#include "G3D/BoundsTrait.h" +#include "G3D/debugAssert.h" +#include + +namespace G3D { + +/** + A generic triangle representation. This should not be used + as the underlying triangle for creating models; it is intended + for providing fast property queries but requires a lot of + storage and is mostly immutable. + */ +class Triangle { +private: + friend class CollisionDetection; + friend class Ray; + + Vector3 _vertex[3]; + + /** edgeDirection[i] is the normalized vector v[i+1] - v[i] */ + Vector3 edgeDirection[3]; + float edgeMagnitude[3]; + Plane _plane; + Vector3::Axis _primaryAxis; + + /** vertex[1] - vertex[0] */ + Vector3 _edge01; + + /** vertex[2] - vertex[0] */ + Vector3 _edge02; + + float _area; + + void init(const Vector3& v0, const Vector3& v1, const Vector3& v2); + +public: + + Triangle(class BinaryInput& b); + void serialize(class BinaryOutput& b); + void deserialize(class BinaryInput& b); + + Triangle(); + + Triangle(const Vector3& v0, const Vector3& v1, const Vector3& v2); + + ~Triangle(); + + /** 0, 1, or 2 */ + inline const Vector3& vertex(int n) const { + debugAssert((n >= 0) && (n < 3)); + return _vertex[n]; + } + + /** vertex[1] - vertex[0] */ + inline const Vector3& edge01() const { + return _edge01; + } + + /** vertex[2] - vertex[0] */ + inline const Vector3& edge02() const { + return _edge02; + } + + float area() const; + + Vector3::Axis primaryAxis() const { + return _primaryAxis; + } + + const Vector3& normal() const; + + /** Barycenter */ + Vector3 center() const; + + const Plane& plane() const; + + /** Returns a random point in the triangle. */ + Vector3 randomPoint() const; + + inline void getRandomSurfacePoint + (Vector3& P, + Vector3& N = Vector3::ignore()) const { + P = randomPoint(); + N = normal(); + } + + /** + For two triangles to be equal they must have + the same vertices in the same order. + That is, vertex[0] == vertex[0], etc. + */ + inline bool operator==(const Triangle& other) const { + for (int i = 0; i < 3; ++i) { + if (_vertex[i] != other._vertex[i]) { + return false; + } + } + + return true; + } + + inline size_t hashCode() const { + return + _vertex[0].hashCode() + + (_vertex[1].hashCode() >> 2) + + (_vertex[2].hashCode() >> 3); + } + + void getBounds(class AABox&) const; + + /** + @brief Intersect the ray at distance less than @a distance. + + @param distance Set to the maximum distance (can be G3D::inf()) + to search for an intersection. On return, this is the smaller + of the distance to the intersection, if one exists, and the original + value. + + @param baryCoord If a triangle is hit before @a distance, a + the barycentric coordinates of the hit location on the triangle. + Otherwise, unmodified. + + @return True if there was an intersection before the original distance. + */ + bool intersect(const class Ray& ray, float& distance, float baryCoord[3]) const; +}; + +} // namespace G3D + +template <> struct HashTrait { + static size_t hashCode(const G3D::Triangle& key) { return key.hashCode(); } +}; + + +template<> struct BoundsTrait { + static void getBounds(const G3D::Triangle& t, G3D::AABox& out) { t.getBounds(out); } +}; + +#endif diff --git a/dep/g3dlite/G3D/UprightFrame.h b/dep/g3dlite/G3D/UprightFrame.h new file mode 100644 index 00000000000..ad5157cb14b --- /dev/null +++ b/dep/g3dlite/G3D/UprightFrame.h @@ -0,0 +1,83 @@ +/** + @file UprightFrame.h + + @author Morgan McGuire, http://graphics.cs.williams.edu + */ + +#ifndef G3D_UPRIGHTFRAME_H +#define G3D_UPRIGHTFRAME_H + +#include "G3D/platform.h" +#include "G3D/Spline.h" +#include "G3D/Vector3.h" +#include "G3D/CoordinateFrame.h" + +namespace G3D { + +/** + Coordinate frame expressed in Euler angles. + Unlike a G3D::Quat, UprightFrame always keeps the reference frame from rolling about its own z axis. + Particularly useful for cameras. + + @sa G3D::CoordinateFrame, G3D::Matrix4, G3D::PhysicsFrame, G3D::UprightSpline, G3D::UprightSplineManipulator + */ +class UprightFrame { +public: + + Vector3 translation; + + /** -pi/2 < pitch < pi/2 in radians about the X-axis */ + float pitch; + + /** In radians about the Y-axis */ + float yaw; + + inline UprightFrame(const Vector3& t = Vector3::zero(), float p = 0, float y = 0) + : translation(t), pitch(p), yaw(y) {} + + UprightFrame(const CoordinateFrame& cframe); + + CoordinateFrame toCoordinateFrame() const; + + /** Supports implicit cast to CoordinateFrame */ + inline operator CoordinateFrame() const { + return toCoordinateFrame(); + } + + /** Required for use with spline */ + UprightFrame operator+(const UprightFrame& other) const; + + /** Required for use with spline */ + UprightFrame operator*(const float k) const; + + /** + Unwraps the yaw values in the elements of the array such that + they still represent the same angles but strictly increase/decrease + without wrapping about zero. For use with Spline + */ + static void unwrapYaw(UprightFrame* a, int N); + + void serialize(class BinaryOutput& b) const; + void deserialize(class BinaryInput& b); +}; + +/** Shortest-path linear velocity spline for camera positions. Always keeps the camera from rolling. +@sa G3D::UprightSplineManipulator, G3D::UprightFrame +*/ +class UprightSpline : public Spline { +protected: + + virtual void ensureShortestPath(UprightFrame* A, int N) const { + UprightFrame::unwrapYaw(A, N); + } + +public: + + void serialize(class BinaryOutput& b) const; + void deserialize(class BinaryInput& b); + +}; + +} + +#endif diff --git a/dep/g3dlite/G3D/Vector2.h b/dep/g3dlite/G3D/Vector2.h new file mode 100644 index 00000000000..dba7353785e --- /dev/null +++ b/dep/g3dlite/G3D/Vector2.h @@ -0,0 +1,454 @@ +/** + @file Vector2.h + + 2D vector class + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2001-06-02 + @edited 2008-11-30 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. +*/ + +#ifndef G3D_VECTOR2_H +#define G3D_VECTOR2_H + +#include + +#include "G3D/platform.h" +#include "G3D/g3dmath.h" +#include "G3D/Table.h" +#include "G3D/HashTrait.h" +#include "G3D/Vector2int16.h" +#include "G3D/Random.h" + +namespace G3D { + +class Vector2; +class Vector3; +class Vector4; +class Any; + +/** + Do not subclass-- this implementation makes assumptions about the + memory layout. + */ +class Vector2 { +private: + // Hidden operators + bool operator<(const Vector2&) const; + bool operator>(const Vector2&) const; + bool operator<=(const Vector2&) const; + bool operator>=(const Vector2&) const; + +public: + float x; + float y; + + /** \param any Must either Vector2(#, #) or Vector2 {x = #, y = #}*/ + Vector2(const Any& any); + + /** Converts the Vector2 to an Any. */ + operator Any() const; + + /** Creates the zero vector */ + Vector2(); + Vector2(class TextInput& t); + Vector2(class BinaryInput& b); + Vector2(float x, float y); + Vector2(float coordinate[2]); + Vector2(double coordinate[2]); + Vector2(const Vector2& other); + Vector2(const Vector2int16& other); + + void serialize(class BinaryOutput& b) const; + void deserialize(class BinaryInput& b); + + void serialize(class TextOutput& t) const; + void deserialize(class TextInput& t); + + float& operator[](int i); + const float& operator[](int i) const; + + // assignment and comparison + Vector2& operator=(const Vector2& other); + bool operator==(const Vector2& other) const; + bool operator!=(const Vector2& other) const; + size_t hashCode() const; + bool fuzzyEq(const Vector2& other) const; + bool fuzzyNe(const Vector2& other) const; + + /** Returns true if this vector has finite length */ + bool isFinite() const; + + /** Returns true if this vector has length == 0 */ + bool isZero() const; + + /** Returns true if this vector has length == 1 */ + bool isUnit() const; + + // arithmetic operations + Vector2 operator+(const Vector2& v) const; + Vector2 operator-(const Vector2& v) const; + Vector2 operator*(float s) const; + + /** Array (pointwise) multiplication */ + Vector2 operator*(const Vector2& v) const; + + /** Array division */ + Vector2 operator/(const Vector2& v) const; + Vector2 operator/(float s) const; + + /** Unary minus */ + Vector2 operator-() const; + + /** x + y */ + inline float sum() const { + return x + y; + } + + /** + Linear interpolation + */ + inline Vector2 lerp(const Vector2& v, float alpha) const { + return (*this) + (v - *this) * alpha; + } + + inline Vector2 clamp(const Vector2& low, const Vector2& high) const { + return Vector2( + G3D::clamp(x, low.x, high.x), + G3D::clamp(y, low.y, high.y)); + } + + inline Vector2 clamp(float low, float high) const { + return Vector2( + (float)G3D::clamp(x, low, high), + (float)G3D::clamp(y, low, high)); + } + + // arithmetic updates + Vector2& operator+=(const Vector2&); + Vector2& operator-=(const Vector2&); + Vector2& operator*=(float); + Vector2& operator/=(float); + Vector2& operator*=(const Vector2&); + Vector2& operator/=(const Vector2&); + + // vector operations + + /** */ + float length() const; + + /** Returns a unit-length vector */ + Vector2 direction() const; + + /** + Potentially less accurate but faster than direction(). + Only works if System::hasSSE is true. + */ + Vector2 fastDirection() const { + return direction(); + } + + float squaredLength() const; + float dot(const Vector2& s) const; + + /** + Make this vector have unit length and return the old length. + If the vector length was less than tolerance, do not normalize. + */ + float unitize(float fTolerance = 1e-06); + + Vector2 min(const Vector2& v) const; + Vector2 max(const Vector2& v) const; + + /** Uniformly distributed random vector on the unit sphere */ + static Vector2 random(Random& r = Random::common()); + + // Special values. + // Intentionally not inlined: see Matrix3::identity() for details. + static const Vector2& zero(); + static const Vector2& one(); + static const Vector2& unitX(); + static const Vector2& unitY(); + static const Vector2& inf(); + static const Vector2& nan(); + /** smallest (most negative) representable vector */ + static const Vector2& minFinite(); + /** Largest representable vector */ + static const Vector2& maxFinite(); + + std::string toString() const; + + // 2-char swizzles + + Vector2 xx() const; + Vector2 yx() const; + Vector2 xy() const; + Vector2 yy() const; + + // 3-char swizzles + + Vector3 xxx() const; + Vector3 yxx() const; + Vector3 xyx() const; + Vector3 yyx() const; + Vector3 xxy() const; + Vector3 yxy() const; + Vector3 xyy() const; + Vector3 yyy() const; + + // 4-char swizzles + + Vector4 xxxx() const; + Vector4 yxxx() const; + Vector4 xyxx() const; + Vector4 yyxx() const; + Vector4 xxyx() const; + Vector4 yxyx() const; + Vector4 xyyx() const; + Vector4 yyyx() const; + Vector4 xxxy() const; + Vector4 yxxy() const; + Vector4 xyxy() const; + Vector4 yyxy() const; + Vector4 xxyy() const; + Vector4 yxyy() const; + Vector4 xyyy() const; + Vector4 yyyy() const; + +}; + +inline Vector2 operator*(double s, const Vector2& v) { + return v * (float)s; +} + +inline Vector2 operator*(float s, const Vector2& v) { + return v * s; +} + +inline Vector2 operator*(int s, const Vector2& v) { + return v * (float)s; +} + + +inline Vector2::Vector2 () : x(0.0f), y(0.0f) { +} + + +inline Vector2::Vector2(float _x, float _y) : x(_x), y(_y) { +} + + +inline Vector2::Vector2 (float afCoordinate[2]) { + x = afCoordinate[0]; + y = afCoordinate[1]; +} + + + +inline Vector2::Vector2 (double afCoordinate[2]) { + x = (float)afCoordinate[0]; + y = (float)afCoordinate[1]; +} + + +inline Vector2::Vector2 (const Vector2& rkVector) { + x = rkVector.x; + y = rkVector.y; +} + + +inline Vector2::Vector2 (const Vector2int16& v) : x(v.x), y(v.y) { +} + + +inline float& Vector2::operator[] (int i) { + return ((float*)this)[i]; +} + + +inline const float& Vector2::operator[] (int i) const { + return ((float*)this)[i]; +} + + +inline Vector2& Vector2::operator= (const Vector2& rkVector) { + x = rkVector.x; + y = rkVector.y; + return *this; +} + + +inline bool Vector2::operator== (const Vector2& rkVector) const { + return ( x == rkVector.x && y == rkVector.y); +} + + +inline bool Vector2::operator!= (const Vector2& rkVector) const { + return ( x != rkVector.x || y != rkVector.y); +} + + +inline Vector2 Vector2::operator+ (const Vector2& rkVector) const { + return Vector2(x + rkVector.x, y + rkVector.y); +} + + +inline Vector2 Vector2::operator- (const Vector2& rkVector) const { + return Vector2(x - rkVector.x, y - rkVector.y); +} + + +inline Vector2 Vector2::operator* (float fScalar) const { + return Vector2(fScalar*x, fScalar*y); +} + + + +inline Vector2 Vector2::operator- () const { + return Vector2( -x, -y); +} + + + +inline Vector2& Vector2::operator+= (const Vector2& rkVector) { + x += rkVector.x; + y += rkVector.y; + return *this; +} + + + +inline Vector2& Vector2::operator-= (const Vector2& rkVector) { + x -= rkVector.x; + y -= rkVector.y; + return *this; +} + + + +inline Vector2& Vector2::operator*= (float fScalar) { + x *= fScalar; + y *= fScalar; + return *this; +} + + + + +inline Vector2& Vector2::operator*= (const Vector2& rkVector) { + x *= rkVector.x; + y *= rkVector.y; + return *this; +} + + + +inline Vector2& Vector2::operator/= (const Vector2& rkVector) { + x /= rkVector.x; + y /= rkVector.y; + return *this; +} + + +inline Vector2 Vector2::operator* (const Vector2& rkVector) const { + return Vector2(x * rkVector.x, y * rkVector.y); +} + + + +inline Vector2 Vector2::operator/ (const Vector2& rkVector) const { + return Vector2(x / rkVector.x, y / rkVector.y); +} + + +inline float Vector2::squaredLength () const { + return x*x + y*y; +} + + +inline float Vector2::length () const { + return sqrtf(x*x + y*y); +} + + +inline Vector2 Vector2::direction () const { + float lenSquared = x * x + y * y; + + if (lenSquared != 1.0f) { + return *this / sqrtf(lenSquared); + } else { + return *this; + } +} + + + +inline float Vector2::dot (const Vector2& rkVector) const { + return x*rkVector.x + y*rkVector.y; +} + + + +inline Vector2 Vector2::min(const Vector2 &v) const { + return Vector2(G3D::min(v.x, x), G3D::min(v.y, y)); +} + + + +inline Vector2 Vector2::max(const Vector2 &v) const { + return Vector2(G3D::max(v.x, x), G3D::max(v.y, y)); +} + + + +inline bool Vector2::fuzzyEq(const Vector2& other) const { + return G3D::fuzzyEq((*this - other).squaredLength(), 0); +} + + + +inline bool Vector2::fuzzyNe(const Vector2& other) const { + return G3D::fuzzyNe((*this - other).squaredLength(), 0); +} + + + +inline bool Vector2::isFinite() const { + return G3D::isFinite(x) && G3D::isFinite(y); +} + + + +inline bool Vector2::isZero() const { + return (x == 0.0f) && (y == 0.0f); +} + + + +inline bool Vector2::isUnit() const { + return squaredLength() == 1.0f; +} + +} // namespace G3D + +template <> +struct HashTrait { + static size_t hashCode(const G3D::Vector2& key) { + return key.hashCode(); + } +}; + + +// Intentionally outside namespace to avoid operator overloading confusion +inline G3D::Vector2 operator*(double s, const G3D::Vector2& v) { + return v * (float)s; +} +inline G3D::Vector2 operator*(int s, const G3D::Vector2& v) { + return v * (float)s; +} + +#endif diff --git a/dep/g3dlite/G3D/Vector2.inl b/dep/g3dlite/G3D/Vector2.inl new file mode 100644 index 00000000000..4f7c55a39cf --- /dev/null +++ b/dep/g3dlite/G3D/Vector2.inl @@ -0,0 +1,18 @@ +/** + @file Vector2.inl + + @maintainer Morgan McGuire, matrix@graphics3d.com + @cite Portions by Laura Wollstadt, graphics3d.com + + @cite Portions based on Dave Eberly'x Magic Software Library + at http://www.magic-software.com + + @created 2001-06-02 + @edited 2006-01-14 + + Copyright 2000-2006, Morgan McGuire. + All rights reserved. + */ + +} + diff --git a/dep/g3dlite/G3D/Vector2int16.h b/dep/g3dlite/G3D/Vector2int16.h new file mode 100644 index 00000000000..ba72266d75a --- /dev/null +++ b/dep/g3dlite/G3D/Vector2int16.h @@ -0,0 +1,127 @@ +/** + @file Vector2int16.h + + @maintainer Morgan McGuire, matrix@brown.edu + + @created 2003-08-09 + @edited 2004-01-03 + + Copyright 2000-2006, Morgan McGuire. + All rights reserved. + */ + +#ifndef VECTOR2INT16_H +#define VECTOR2INT16_H + +#include "G3D/platform.h" +#include "G3D/g3dmath.h" +#include "G3D/HashTrait.h" + +namespace G3D { + +/** + \class Vector2int16 + A Vector2 that packs its fields into uint16s. + */ +G3D_BEGIN_PACKED_CLASS(2) +class Vector2int16 { +private: + // Hidden operators + bool operator<(const Vector2int16&) const; + bool operator>(const Vector2int16&) const; + bool operator<=(const Vector2int16&) const; + bool operator>=(const Vector2int16&) const; + +public: + G3D::int16 x; + G3D::int16 y; + + Vector2int16() : x(0), y(0) {} + Vector2int16(G3D::int16 _x, G3D::int16 _y) : x(_x), y(_y){} + Vector2int16(const class Vector2& v); + Vector2int16(class BinaryInput& bi); + + inline G3D::int16& operator[] (int i) { + debugAssert(((unsigned int)i) <= 1); + return ((G3D::int16*)this)[i]; + } + + inline const G3D::int16& operator[] (int i) const { + debugAssert(((unsigned int)i) <= 1); + return ((G3D::int16*)this)[i]; + } + + inline Vector2int16 operator+(const Vector2int16& other) const { + return Vector2int16(x + other.x, y + other.y); + } + + inline Vector2int16 operator-(const Vector2int16& other) const { + return Vector2int16(x - other.x, y - other.y); + } + + inline Vector2int16 operator*(const Vector2int16& other) const { + return Vector2int16(x * other.x, y * other.y); + } + + inline Vector2int16 operator*(const int s) const { + return Vector2int16(x * s, y * s); + } + + inline Vector2int16& operator+=(const Vector2int16& other) { + x += other.x; + y += other.y; + return *this; + } + + /** Shifts both x and y */ + inline Vector2int16 operator>>(const int s) const { + return Vector2int16(x >> s, y >> s); + } + + /** Shifts both x and y */ + inline Vector2int16 operator<<(const int s) const { + return Vector2int16(x << s, y << s); + } + + inline Vector2int16& operator-=(const Vector2int16& other) { + x -= other.x; + y -= other.y; + return *this; + } + + inline Vector2int16& operator*=(const Vector2int16& other) { + x *= other.x; + y *= other.y; + return *this; + } + + Vector2int16 clamp(const Vector2int16& lo, const Vector2int16& hi); + + inline bool operator== (const Vector2int16& rkVector) const { + return ((int32*)this)[0] == ((int32*)&rkVector)[0]; + } + + inline bool operator!= (const Vector2int16& rkVector) const { + return ((int32*)this)[0] != ((int32*)&rkVector)[0]; + } + + Vector2int16 max(const Vector2int16& v) const { + return Vector2int16(iMax(x, v.x), iMax(y, v.y)); + } + + Vector2int16 min(const Vector2int16& v) const { + return Vector2int16(iMin(x, v.x), iMin(y, v.y)); + } + + void serialize(class BinaryOutput& bo) const; + void deserialize(class BinaryInput& bi); +} +G3D_END_PACKED_CLASS(2) + +} + +template<> struct HashTrait { + static size_t hashCode(const G3D::Vector2int16& key) { return static_cast(key.x + ((int)key.y << 16)); } +}; + +#endif diff --git a/dep/g3dlite/G3D/Vector3.h b/dep/g3dlite/G3D/Vector3.h new file mode 100644 index 00000000000..4825efb9985 --- /dev/null +++ b/dep/g3dlite/G3D/Vector3.h @@ -0,0 +1,798 @@ +/** + @file Vector3.h + + 3D vector class + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2001-06-02 + @edited 2009-11-01 + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_Vector3_h +#define G3D_Vector3_h + +#include "G3D/platform.h" +#include "G3D/g3dmath.h" +#include "G3D/Random.h" +#include "G3D/Vector2.h" +#include "G3D/Table.h" +#include "G3D/HashTrait.h" +#include "G3D/PositionTrait.h" +#include "G3D/Vector2.h" +#include +#include + +namespace G3D { + +class Vector2; +class Vector4; +class Vector4int8; +class Vector3int32; +class Any; + +/** + Swizzles + Vector classes have swizzle operators, e.g. v.xy(), that + allow selection of arbitrary sub-fields. These cannot be used as write + masks. Examples + +
+Vector3 v(1, 2, 3);
+Vector3 j;
+Vector2 b;
+
+b = v.xz();
+j = b.xx();
+
+ + + Warning + + Do not subclass-- this implementation makes assumptions about the + memory layout. + */ +class Vector3 { +public: + + // coordinates + float x, y, z; + +private: + + // Hidden operators + bool operator<(const Vector3&) const; + bool operator>(const Vector3&) const; + bool operator<=(const Vector3&) const; + bool operator>=(const Vector3&) const; + +public: + /** Initializes to zero */ + Vector3(); + + /** \param any Must either Vector3(#, #, #) or Vector3 {x = #, y = #, z = #}*/ + Vector3(const Any& any); + + /** Converts the Vector3 to an Any. */ + operator Any() const; + + /** Divides by 127 */ + Vector3(const Vector4int8&); + Vector3(const class Vector3int32& v); + explicit Vector3(class BinaryInput& b); + Vector3(float _x, float _y, float _z); + explicit Vector3(const class Vector2& v, float _z); + explicit Vector3(float coordinate[3]); + explicit Vector3(double coordinate[3]); + Vector3(const class Vector3int16& v); + explicit Vector3(class TextInput& t); + explicit Vector3(const class Color3& c); + + /** Format is three float32's */ + void serialize(class BinaryOutput& b) const; + void deserialize(class BinaryInput& b); + + /** Format is "(%f, %f, %f)" */ + void serialize(class TextOutput& t) const; + void deserialize(class TextInput& t); + + // access vector V as V[0] = V.x, V[1] = V.y, V[2] = V.z + // + // WARNING. These member functions rely on + // (1) Vector3 not having virtual functions + // (2) the data packed in a 3*sizeof(float) memory block + const float& __fastcall operator[] (int i) const; + float& operator[] (int i); + + enum Axis {X_AXIS=0, Y_AXIS=1, Z_AXIS=2, DETECT_AXIS=-1}; + + /** + Returns the largest dimension. Particularly convenient for determining + which plane to project a triangle onto for point-in-polygon tests. + */ + Axis primaryAxis() const; + + // assignment and comparison + Vector3& __fastcall operator= (const Vector3& rkVector); + bool operator== (const Vector3& rkVector) const; + bool operator!= (const Vector3& rkVector) const; + size_t hashCode() const; + bool fuzzyEq(const Vector3& other) const; + bool fuzzyNe(const Vector3& other) const; + + /** Returns true if this vector has finite length. */ + bool isFinite() const; + + /** Returns true if this vector has length ~= 0 */ + bool isZero() const; + + /** Returns true if this vector has length ~= 1 */ + bool isUnit() const; + + // arithmetic operations + Vector3 __fastcall operator+ (const Vector3& v) const; + Vector3 __fastcall operator- (const Vector3& v) const; + Vector3 __fastcall operator* (float s) const; + inline Vector3 __fastcall operator/ (float s) const { + return *this * (1.0f / s); + } + Vector3 __fastcall operator* (const Vector3& v) const; + Vector3 __fastcall operator/ (const Vector3& v) const; + Vector3 __fastcall operator- () const; + + // arithmetic updates + Vector3& __fastcall operator+= (const Vector3& v); + Vector3& __fastcall operator-= (const Vector3& v); + Vector3& __fastcall operator*= (float s); + inline Vector3& __fastcall operator/= (float s) { + return (*this *= (1.0f / s)); + } + Vector3& __fastcall operator*= (const Vector3& v); + Vector3& __fastcall operator/= (const Vector3& v); + + /** Same as magnitude */ + float length() const; + + float magnitude() const; + + /** + The result is a nan vector if the length is almost zero. + */ + Vector3 direction() const; + + /** + Potentially less accurate but faster than direction(). + Only works if System::hasSSE is true. + */ + Vector3 fastDirection() const; + + /** + Reflect this vector about the (not necessarily unit) normal. + Assumes that both the before and after vectors point away from + the base of the normal. + + Note that if used for a collision or ray reflection you + must negate the resulting vector to get a direction pointing + away from the collision. + +
+       V'    N      V
+                 
+         r   ^   -,
+          \  |  /
+            \|/
+     
+ + See also Vector3::reflectionDirection + */ + Vector3 reflectAbout(const Vector3& normal) const; + + /** + See also G3D::Ray::reflect. + The length is 1. +
+       V'    N       V
+                 
+         r   ^    /
+          \  |  /
+            \|'-
+     
+ */ + Vector3 reflectionDirection(const Vector3& normal) const; + + + /** + Returns Vector3::zero() if the length is nearly zero, otherwise + returns a unit vector. + */ + inline Vector3 directionOrZero() const { + float mag = magnitude(); + if (G3D::fuzzyEq(mag, 0.0f)) { + return Vector3::zero(); + } else if (G3D::fuzzyEq(mag, 1.0f)) { + return *this; + } else { + return *this * (1.0f / mag); + } + } + + /** + Returns the direction of a refracted ray, + where iExit is the index of refraction for the + previous material and iEnter is the index of refraction + for the new material. Like Vector3::reflectionDirection, + the result has length 1 and is + pointed away from the intersection. + + Returns Vector3::zero() in the case of total internal refraction. + + @param iOutside The index of refraction (eta) outside + (on the positive normal side) of the surface. + + @param iInside The index of refraction (eta) inside + (on the negative normal side) of the surface. + + See also G3D::Ray::refract. +
+              N      V
+                  
+              ^    /
+              |  /
+              |'-
+          __--
+     V'<--
+     
+ */ + Vector3 refractionDirection( + const Vector3& normal, + float iInside, + float iOutside) const; + + /** Synonym for direction */ + inline Vector3 unit() const { + return direction(); + } + + /** Returns a normalized vector. May be computed with lower + precision than unit */ + inline Vector3 fastUnit() const { + return fastDirection(); + } + + /** Same as squaredMagnitude */ + float squaredLength() const; + + float squaredMagnitude () const; + + float __fastcall dot(const Vector3& rkVector) const; + + float unitize(float tolerance = 1e-06); + + /** Cross product. Note that two cross products in a row + can be computed more cheaply: v1 x (v2 x v3) = (v1 dot v3) v2 - (v1 dot v2) v3. + */ + Vector3 __fastcall cross(const Vector3& rkVector) const; + Vector3 unitCross(const Vector3& rkVector) const; + + /** + Returns a matrix such that v.cross() * w = v.cross(w). +
+     [ 0  -v.z  v.y ]
+     [ v.z  0  -v.x ]
+     [ -v.y v.x  0  ]
+     
+ */ + class Matrix3 cross() const; + + Vector3 __fastcall min(const Vector3 &v) const; + Vector3 __fastcall max(const Vector3 &v) const; + + /** Smallest element */ + inline float min() const { + return G3D::min(G3D::min(x, y), z); + } + + /** Largest element */ + inline float max() const { + return G3D::max(G3D::max(x, y), z); + } + + std::string toString() const; + + inline Vector3 clamp(const Vector3& low, const Vector3& high) const { + return Vector3( + G3D::clamp(x, low.x, high.x), + G3D::clamp(y, low.y, high.y), + G3D::clamp(z, low.z, high.z)); + } + + inline Vector3 clamp(float low, float high) const { + return Vector3( + G3D::clamp(x, low, high), + G3D::clamp(y, low, high), + G3D::clamp(z, low, high)); + } + + /** + Linear interpolation + */ + inline Vector3 lerp(const Vector3& v, float alpha) const { + return (*this) + (v - *this) * alpha; + } + + /** Gram-Schmidt orthonormalization. */ + static void orthonormalize (Vector3 akVector[3]); + + /** \brief Random unit vector, uniformly distributed on the sphere. + + Distribution rendered by G3D::DirectionHistogram: + \image html vector3-random.png + */ + static Vector3 random(Random& r = Random::common()); + + /** \brief Random unit vector, distributed according to \f$\max(\cos \theta,0)\f$. + + That is, so that the probability of \f$\vec{V}\f$ is proportional + to \f$\max(\vec{v} \cdot \vec{n}, 0)\f$. Useful in photon mapping for + Lambertian scattering. + + Distribution rendered by G3D::DirectionHistogram: + \image html vector3-coshemirandom.png + + \param n Unit vector at the center of the distribution. + + @cite Henrik Wann Jensen, Realistic Image Synthesis using Photon Mapping eqn 2.24 + */ + static Vector3 cosHemiRandom(const Vector3& n, Random& r = Random::common()); + + /** \brief Random unit vector, distributed according to \f$\max(\cos^k \theta,0)\f$. + + That is, so that the probability of \f$\vec{V}\f$ is + proportional to \f$\max((\vec{v} \cdot \vec{n})^k, 0)\f$. + Useful in photon mapping for glossy scattering. + + Distribution rendered by G3D::DirectionHistogram: + \image html vector3-cospowhemirandom.png + + \param n Unit vector at the center of the distribution. + + @cite Ashikhmin and Shirley, An anisotropic Phong BRDF model, Journal of Graphics Tools, 2002 + */ + static Vector3 cosPowHemiRandom(const Vector3& n, const float k, Random& r = Random::common()); + + /** + \brief Random vector distributed over the hemisphere about normal. + + Distribution rendered by G3D::DirectionHistogram: + \image html vector3-hemirandom.png + */ + static Vector3 hemiRandom(const Vector3& normal, Random& r = Random::common()); + + /** Input W must be initialize to a nonzero vector, output is {U,V,W} + an orthonormal basis. A hint is provided about whether or not W + is already unit length. + @deprecated Use getTangents + */ + static void generateOrthonormalBasis (Vector3& rkU, Vector3& rkV, + Vector3& rkW, bool bUnitLengthW = true); + + inline float sum() const { + return x + y + z; + } + + inline float average() const { + return sum() / 3.0f; + } + + // Special values. + static const Vector3& zero(); + static const Vector3& one(); + static const Vector3& unitX(); + static const Vector3& unitY(); + static const Vector3& unitZ(); + static const Vector3& inf(); + static const Vector3& nan(); + + /** Smallest (most negative) representable vector */ + static const Vector3& minFinite(); + + /** Largest representable vector */ + static const Vector3& maxFinite(); + + + /** Creates two orthonormal tangent vectors X and Y such that + if Z = this, X x Y = Z.*/ + inline void getTangents(Vector3& X, Vector3& Y) const { + debugAssertM(G3D::fuzzyEq(length(), 1.0f), + "makeAxes requires Z to have unit length"); + + // Choose another vector not perpendicular + X = (abs(x) < 0.9f) ? Vector3::unitX() : Vector3::unitY(); + + // Remove the part that is parallel to Z + X -= *this * this->dot(X); + X /= X.length(); + + Y = this->cross(X); + } + + + // 2-char swizzles + + Vector2 xx() const; + Vector2 yx() const; + Vector2 zx() const; + Vector2 xy() const; + Vector2 yy() const; + Vector2 zy() const; + Vector2 xz() const; + Vector2 yz() const; + Vector2 zz() const; + + // 3-char swizzles + + Vector3 xxx() const; + Vector3 yxx() const; + Vector3 zxx() const; + Vector3 xyx() const; + Vector3 yyx() const; + Vector3 zyx() const; + Vector3 xzx() const; + Vector3 yzx() const; + Vector3 zzx() const; + Vector3 xxy() const; + Vector3 yxy() const; + Vector3 zxy() const; + Vector3 xyy() const; + Vector3 yyy() const; + Vector3 zyy() const; + Vector3 xzy() const; + Vector3 yzy() const; + Vector3 zzy() const; + Vector3 xxz() const; + Vector3 yxz() const; + Vector3 zxz() const; + Vector3 xyz() const; + Vector3 yyz() const; + Vector3 zyz() const; + Vector3 xzz() const; + Vector3 yzz() const; + Vector3 zzz() const; + + // 4-char swizzles + + Vector4 xxxx() const; + Vector4 yxxx() const; + Vector4 zxxx() const; + Vector4 xyxx() const; + Vector4 yyxx() const; + Vector4 zyxx() const; + Vector4 xzxx() const; + Vector4 yzxx() const; + Vector4 zzxx() const; + Vector4 xxyx() const; + Vector4 yxyx() const; + Vector4 zxyx() const; + Vector4 xyyx() const; + Vector4 yyyx() const; + Vector4 zyyx() const; + Vector4 xzyx() const; + Vector4 yzyx() const; + Vector4 zzyx() const; + Vector4 xxzx() const; + Vector4 yxzx() const; + Vector4 zxzx() const; + Vector4 xyzx() const; + Vector4 yyzx() const; + Vector4 zyzx() const; + Vector4 xzzx() const; + Vector4 yzzx() const; + Vector4 zzzx() const; + Vector4 xxxy() const; + Vector4 yxxy() const; + Vector4 zxxy() const; + Vector4 xyxy() const; + Vector4 yyxy() const; + Vector4 zyxy() const; + Vector4 xzxy() const; + Vector4 yzxy() const; + Vector4 zzxy() const; + Vector4 xxyy() const; + Vector4 yxyy() const; + Vector4 zxyy() const; + Vector4 xyyy() const; + Vector4 yyyy() const; + Vector4 zyyy() const; + Vector4 xzyy() const; + Vector4 yzyy() const; + Vector4 zzyy() const; + Vector4 xxzy() const; + Vector4 yxzy() const; + Vector4 zxzy() const; + Vector4 xyzy() const; + Vector4 yyzy() const; + Vector4 zyzy() const; + Vector4 xzzy() const; + Vector4 yzzy() const; + Vector4 zzzy() const; + Vector4 xxxz() const; + Vector4 yxxz() const; + Vector4 zxxz() const; + Vector4 xyxz() const; + Vector4 yyxz() const; + Vector4 zyxz() const; + Vector4 xzxz() const; + Vector4 yzxz() const; + Vector4 zzxz() const; + Vector4 xxyz() const; + Vector4 yxyz() const; + Vector4 zxyz() const; + Vector4 xyyz() const; + Vector4 yyyz() const; + Vector4 zyyz() const; + Vector4 xzyz() const; + Vector4 yzyz() const; + Vector4 zzyz() const; + Vector4 xxzz() const; + Vector4 yxzz() const; + Vector4 zxzz() const; + Vector4 xyzz() const; + Vector4 yyzz() const; + Vector4 zyzz() const; + Vector4 xzzz() const; + Vector4 yzzz() const; + Vector4 zzzz() const; + + /** Can be passed to ignore a vector3 parameter */ + static Vector3& ignore(); +}; + +inline G3D::Vector3 operator*(float s, const G3D::Vector3& v) { + return v * s; +} + +inline G3D::Vector3 operator*(double s, const G3D::Vector3& v) { + return v * (float)s; +} + +inline G3D::Vector3 operator*(int s, const G3D::Vector3& v) { + return v * (float)s; +} + +std::ostream& operator<<(std::ostream& os, const Vector3&); + + +void serialize(const Vector3::Axis& a, class BinaryOutput& bo); +void deserialize(Vector3::Axis& a, class BinaryInput& bo); + + +//---------------------------------------------------------------------------- +inline Vector3::Vector3() : x(0.0f), y(0.0f), z(0.0f) { +} + +//---------------------------------------------------------------------------- + +inline Vector3::Vector3 (float fX, float fY, float fZ) : x(fX), y(fY), z(fZ) { +} + +//---------------------------------------------------------------------------- +inline Vector3::Vector3 (float V[3]) : x(V[0]), y(V[1]), z(V[2]){ +} + +//---------------------------------------------------------------------------- +inline Vector3::Vector3 (double V[3]) : x((float)V[0]), y((float)V[1]), z((float)V[2]){ +} + +//---------------------------------------------------------------------------- +inline const float& Vector3::operator[] (int i) const { + return ((float*)this)[i]; +} + +inline float& Vector3::operator[] (int i) { + return ((float*)this)[i]; +} + + +//---------------------------------------------------------------------------- +inline Vector3& Vector3::operator= (const Vector3& rkVector) { + x = rkVector.x; + y = rkVector.y; + z = rkVector.z; + return *this; +} + +//---------------------------------------------------------------------------- + +inline bool Vector3::fuzzyEq(const Vector3& other) const { + return G3D::fuzzyEq((*this - other).squaredMagnitude(), 0); +} + +//---------------------------------------------------------------------------- + +inline bool Vector3::fuzzyNe(const Vector3& other) const { + return G3D::fuzzyNe((*this - other).squaredMagnitude(), 0); +} + +//---------------------------------------------------------------------------- + +inline bool Vector3::isFinite() const { + return G3D::isFinite(x) && G3D::isFinite(y) && G3D::isFinite(z); +} + +//---------------------------------------------------------------------------- +inline bool Vector3::operator== (const Vector3& rkVector) const { + return ( x == rkVector.x && y == rkVector.y && z == rkVector.z ); +} + +//---------------------------------------------------------------------------- +inline bool Vector3::operator!= (const Vector3& rkVector) const { + return ( x != rkVector.x || y != rkVector.y || z != rkVector.z ); +} + +//---------------------------------------------------------------------------- +inline Vector3 Vector3::operator+ (const Vector3& rkVector) const { + return Vector3(x + rkVector.x, y + rkVector.y, z + rkVector.z); +} + +//---------------------------------------------------------------------------- +inline Vector3 Vector3::operator- (const Vector3& rkVector) const { + return Vector3(x - rkVector.x, y - rkVector.y, z - rkVector.z); +} + +//---------------------------------------------------------------------------- +inline Vector3 Vector3::operator* (const Vector3& rkVector) const { + return Vector3(x * rkVector.x, y * rkVector.y, z * rkVector.z); +} + +inline Vector3 Vector3::operator*(float f) const { + return Vector3(x * f, y * f, z * f); +} + +//---------------------------------------------------------------------------- +inline Vector3 Vector3::operator/ (const Vector3& rkVector) const { + return Vector3(x / rkVector.x, y / rkVector.y, z / rkVector.z); +} + +//---------------------------------------------------------------------------- +inline Vector3 Vector3::operator- () const { + return Vector3(-x, -y, -z); +} + +//---------------------------------------------------------------------------- +inline Vector3& Vector3::operator+= (const Vector3& rkVector) { + x += rkVector.x; + y += rkVector.y; + z += rkVector.z; + return *this; +} + +//---------------------------------------------------------------------------- +inline Vector3& Vector3::operator-= (const Vector3& rkVector) { + x -= rkVector.x; + y -= rkVector.y; + z -= rkVector.z; + return *this; +} + +//---------------------------------------------------------------------------- +inline Vector3& Vector3::operator*= (float fScalar) { + x *= fScalar; + y *= fScalar; + z *= fScalar; + return *this; +} + +//---------------------------------------------------------------------------- +inline Vector3& Vector3::operator*= (const Vector3& rkVector) { + x *= rkVector.x; + y *= rkVector.y; + z *= rkVector.z; + return *this; +} + +//---------------------------------------------------------------------------- +inline Vector3& Vector3::operator/= (const Vector3& rkVector) { + x /= rkVector.x; + y /= rkVector.y; + z /= rkVector.z; + return *this; +} + +//---------------------------------------------------------------------------- +inline float Vector3::squaredMagnitude () const { + return x*x + y*y + z*z; +} + +//---------------------------------------------------------------------------- +inline float Vector3::squaredLength () const { + return squaredMagnitude(); +} + +//---------------------------------------------------------------------------- +inline float Vector3::magnitude() const { + return ::sqrtf(x*x + y*y + z*z); +} + +//---------------------------------------------------------------------------- +inline float Vector3::length() const { + return magnitude(); +} + +//---------------------------------------------------------------------------- +inline Vector3 Vector3::direction () const { + const float lenSquared = squaredMagnitude(); + const float invSqrt = 1.0f / sqrtf(lenSquared); + return Vector3(x * invSqrt, y * invSqrt, z * invSqrt); +} + +//---------------------------------------------------------------------------- + +inline Vector3 Vector3::fastDirection () const { + float lenSquared = x * x + y * y + z * z; + float invSqrt = rsq(lenSquared); + return Vector3(x * invSqrt, y * invSqrt, z * invSqrt); +} + +//---------------------------------------------------------------------------- +inline float Vector3::dot (const Vector3& rkVector) const { + return x*rkVector.x + y*rkVector.y + z*rkVector.z; +} + +//---------------------------------------------------------------------------- +inline Vector3 Vector3::cross (const Vector3& rkVector) const { + return Vector3(y*rkVector.z - z*rkVector.y, z*rkVector.x - x*rkVector.z, + x*rkVector.y - y*rkVector.x); +} + +//---------------------------------------------------------------------------- +inline Vector3 Vector3::unitCross (const Vector3& rkVector) const { + Vector3 kCross(y*rkVector.z - z*rkVector.y, z*rkVector.x - x*rkVector.z, + x*rkVector.y - y*rkVector.x); + kCross.unitize(); + return kCross; +} + +//---------------------------------------------------------------------------- +inline Vector3 Vector3::min(const Vector3 &v) const { + return Vector3(G3D::min(v.x, x), G3D::min(v.y, y), G3D::min(v.z, z)); +} + +//---------------------------------------------------------------------------- +inline Vector3 Vector3::max(const Vector3 &v) const { + return Vector3(G3D::max(v.x, x), G3D::max(v.y, y), G3D::max(v.z, z)); +} + +//---------------------------------------------------------------------------- +inline bool Vector3::isZero() const { + return G3D::fuzzyEq(squaredMagnitude(), 0.0f); +} + +//---------------------------------------------------------------------------- + +inline bool Vector3::isUnit() const { + return G3D::fuzzyEq(squaredMagnitude(), 1.0f); +} + +} // namespace G3D + + +template <> +struct HashTrait { + static size_t hashCode(const G3D::Vector3& key) { + return key.hashCode(); + } +}; + + +template<> struct PositionTrait { + static void getPosition(const G3D::Vector2& v, G3D::Vector3& p) { p = G3D::Vector3(v, 0); } +}; + +template<> struct PositionTrait { + static void getPosition(const G3D::Vector3& v, G3D::Vector3& p) { p = v; } +}; + + +#endif diff --git a/dep/g3dlite/G3D/Vector3.inl b/dep/g3dlite/G3D/Vector3.inl new file mode 100644 index 00000000000..9211c2a70fd --- /dev/null +++ b/dep/g3dlite/G3D/Vector3.inl @@ -0,0 +1,249 @@ +/** + @file Vector3.inl + + @maintainer Morgan McGuire, matrix@graphics3d.com + + @cite Portions based on Dave Eberly's Magic Software Library at http://www.magic-software.com + + @created 2001-06-02 + @edited 2004-05-21 + Copyright 2000-2004, Morgan McGuire. + All rights reserved. + */ + +//---------------------------------------------------------------------------- +#ifdef SSE + // If you receive an error on this line, it is because you do not have the file + // xmmintrin.h needed for MMX & SSE extensions. Download and install + // + // http://download.microsoft.com/download/vstudio60ent/SP5/Wideband-Full/WIN98Me/EN-US/vs6sp5.exe + // and + // http://download.microsoft.com/download/vb60ent/Update/6/W9X2KXP/EN-US/vcpp5.exe + // + // to get this file. +# include +#endif + +inline unsigned int hashCode(const G3D::Vector3& v) { + return v.hashCode(); +} + +namespace G3D { + +//---------------------------------------------------------------------------- +inline Vector3::Vector3() : x(0.0f), y(0.0f), z(0.0f) { +} + +//---------------------------------------------------------------------------- + +inline Vector3::Vector3 (float fX, float fY, float fZ) : x(fX), y(fY), z(fZ) { +} + +//---------------------------------------------------------------------------- +inline Vector3::Vector3 (float V[3]) : x(V[0]), y(V[1]), z(V[2]){ +} +//---------------------------------------------------------------------------- +inline Vector3::Vector3 (double V[3]) : x((float)V[0]), y((float)V[1]), z((float)V[2]){ +} + +//---------------------------------------------------------------------------- +inline Vector3::Vector3 (const Vector3& V) : x(V.x), y(V.y), z(V.z) { +} + +//---------------------------------------------------------------------------- + +//inline Vector3::Vector3 (const __m128& m) { + // Cast from SSE packed floats +// *this = *(Vector3*)&m; +//} + +//---------------------------------------------------------------------------- +inline const float& Vector3::operator[] (int i) const { + return ((float*)this)[i]; +} + +inline float& Vector3::operator[] (int i) { + return ((float*)this)[i]; +} + +//---------------------------------------------------------------------------- +inline Vector3& Vector3::operator= (const Vector3& rkVector) { + x = rkVector.x; + y = rkVector.y; + z = rkVector.z; + return *this; +} + +//---------------------------------------------------------------------------- + +inline bool Vector3::fuzzyEq(const Vector3& other) const { + return G3D::fuzzyEq((*this - other).squaredMagnitude(), 0); +} + +//---------------------------------------------------------------------------- + +inline bool Vector3::fuzzyNe(const Vector3& other) const { + return G3D::fuzzyNe((*this - other).squaredMagnitude(), 0); +} + +//---------------------------------------------------------------------------- + +inline bool Vector3::isFinite() const { + return G3D::isFinite(x) && G3D::isFinite(y) && G3D::isFinite(z); +} + +//---------------------------------------------------------------------------- +inline bool Vector3::operator== (const Vector3& rkVector) const { + return ( x == rkVector.x && y == rkVector.y && z == rkVector.z ); +} + +//---------------------------------------------------------------------------- +inline bool Vector3::operator!= (const Vector3& rkVector) const { + return ( x != rkVector.x || y != rkVector.y || z != rkVector.z ); +} + +//---------------------------------------------------------------------------- +inline Vector3 Vector3::operator+ (const Vector3& rkVector) const { + return Vector3(x + rkVector.x, y + rkVector.y, z + rkVector.z); +} + +//---------------------------------------------------------------------------- +inline Vector3 Vector3::operator- (const Vector3& rkVector) const { + return Vector3(x - rkVector.x, y - rkVector.y, z - rkVector.z); +} + +//---------------------------------------------------------------------------- +inline Vector3 Vector3::operator* (const Vector3& rkVector) const { + return Vector3(x * rkVector.x, y * rkVector.y, z * rkVector.z); +} + +inline Vector3 Vector3::operator*(float f) const { + return Vector3(x * f, y * f, z * f); +} + +//---------------------------------------------------------------------------- +inline Vector3 Vector3::operator/ (const Vector3& rkVector) const { + return Vector3(x / rkVector.x, y / rkVector.y, z / rkVector.z); +} + +//---------------------------------------------------------------------------- +inline Vector3 Vector3::operator- () const { + return Vector3(-x, -y, -z); +} + +//---------------------------------------------------------------------------- +inline Vector3& Vector3::operator+= (const Vector3& rkVector) { + x += rkVector.x; + y += rkVector.y; + z += rkVector.z; + return *this; +} + +//---------------------------------------------------------------------------- +inline Vector3& Vector3::operator-= (const Vector3& rkVector) { + x -= rkVector.x; + y -= rkVector.y; + z -= rkVector.z; + return *this; +} + +//---------------------------------------------------------------------------- +inline Vector3& Vector3::operator*= (float fScalar) { + x *= fScalar; + y *= fScalar; + z *= fScalar; + return *this; +} + +//---------------------------------------------------------------------------- +inline Vector3& Vector3::operator*= (const Vector3& rkVector) { + x *= rkVector.x; + y *= rkVector.y; + z *= rkVector.z; + return *this; +} + +//---------------------------------------------------------------------------- +inline Vector3& Vector3::operator/= (const Vector3& rkVector) { + x /= rkVector.x; + y /= rkVector.y; + z /= rkVector.z; + return *this; +} + +//---------------------------------------------------------------------------- +inline float Vector3::squaredMagnitude () const { + return x*x + y*y + z*z; +} + +//---------------------------------------------------------------------------- +inline float Vector3::squaredLength () const { + return squaredMagnitude(); +} + +//---------------------------------------------------------------------------- +inline float Vector3::magnitude() const { + return sqrtf(x*x + y*y + z*z); +} + +//---------------------------------------------------------------------------- +inline float Vector3::length() const { + return magnitude(); +} + +//---------------------------------------------------------------------------- +inline Vector3 Vector3::direction () const { + float lenSquared = squaredMagnitude(); + float invSqrt = 1.0f / sqrtf(lenSquared); + return Vector3(x * invSqrt, y * invSqrt, z * invSqrt); +} + +//---------------------------------------------------------------------------- + +inline Vector3 Vector3::fastDirection () const { + float lenSquared = x * x + y * y + z * z; + float invSqrt = rsq(lenSquared); + return Vector3(x * invSqrt, y * invSqrt, z * invSqrt); +} + +//---------------------------------------------------------------------------- +inline float Vector3::dot (const Vector3& rkVector) const { + return x*rkVector.x + y*rkVector.y + z*rkVector.z; +} + +//---------------------------------------------------------------------------- +inline Vector3 Vector3::cross (const Vector3& rkVector) const { + return Vector3(y*rkVector.z - z*rkVector.y, z*rkVector.x - x*rkVector.z, + x*rkVector.y - y*rkVector.x); +} + +//---------------------------------------------------------------------------- +inline Vector3 Vector3::unitCross (const Vector3& rkVector) const { + Vector3 kCross(y*rkVector.z - z*rkVector.y, z*rkVector.x - x*rkVector.z, + x*rkVector.y - y*rkVector.x); + kCross.unitize(); + return kCross; +} + +//---------------------------------------------------------------------------- +inline Vector3 Vector3::min(const Vector3 &v) const { + return Vector3(G3D::min(v.x, x), G3D::min(v.y, y), G3D::min(v.z, z)); +} + +//---------------------------------------------------------------------------- +inline Vector3 Vector3::max(const Vector3 &v) const { + return Vector3(G3D::max(v.x, x), G3D::max(v.y, y), G3D::max(v.z, z)); +} + +//---------------------------------------------------------------------------- +inline bool Vector3::isZero() const { + return G3D::fuzzyEq(squaredMagnitude(), 0.0f); +} + +//---------------------------------------------------------------------------- + +inline bool Vector3::isUnit() const { + return G3D::fuzzyEq(squaredMagnitude(), 1.0f); +} + +} // namespace diff --git a/dep/g3dlite/G3D/Vector3int16.h b/dep/g3dlite/G3D/Vector3int16.h new file mode 100644 index 00000000000..3197ea49d1a --- /dev/null +++ b/dep/g3dlite/G3D/Vector3int16.h @@ -0,0 +1,127 @@ +/** + @file Vector3int16.h + + @maintainer Morgan McGuire, matrix@brown.edu + + @created 2003-04-07 + @edited 2003-06-24 + Copyright 2000-2004, Morgan McGuire. + All rights reserved. + */ + +#ifndef VECTOR3INT16_H +#define VECTOR3INT16_H + +#include "G3D/platform.h" +#include "G3D/g3dmath.h" +#include "G3D/HashTrait.h" + +#ifdef _MSC_VER +// Turn off "conditional expression is constant" warning; MSVC generates this +// for debug assertions in inlined methods. +#pragma warning (disable : 4127) +#endif + + +namespace G3D { + +/** + \class Vector3int16 + A Vector3 that packs its fields into uint16s. + */ +G3D_BEGIN_PACKED_CLASS(2) +class Vector3int16 { +private: + // Hidden operators + bool operator<(const Vector3int16&) const; + bool operator>(const Vector3int16&) const; + bool operator<=(const Vector3int16&) const; + bool operator>=(const Vector3int16&) const; + +public: + G3D::int16 x; + G3D::int16 y; + G3D::int16 z; + + Vector3int16() : x(0), y(0), z(0) {} + Vector3int16(G3D::int16 _x, G3D::int16 _y, G3D::int16 _z) : x(_x), y(_y), z(_z) {} + Vector3int16(const class Vector3& v); + Vector3int16(class BinaryInput& bi); + + void serialize(class BinaryOutput& bo) const; + void deserialize(class BinaryInput& bi); + + inline G3D::int16& operator[] (int i) { + debugAssert(i <= 2); + return ((G3D::int16*)this)[i]; + } + + inline const G3D::int16& operator[] (int i) const { + debugAssert(i <= 2); + return ((G3D::int16*)this)[i]; + } + + inline Vector3int16 operator+(const Vector3int16& other) const { + return Vector3int16(x + other.x, y + other.y, z + other.z); + } + + inline Vector3int16 operator-(const Vector3int16& other) const { + return Vector3int16(x - other.x, y - other.y, z - other.z); + } + + inline Vector3int16 operator*(const Vector3int16& other) const { + return Vector3int16(x * other.x, y * other.y, z * other.z); + } + + inline Vector3int16 operator*(const int s) const { + return Vector3int16(int16(x * s), int16(y * s), int16(z * s)); + } + + inline Vector3int16& operator+=(const Vector3int16& other) { + x += other.x; + y += other.y; + z += other.y; + return *this; + } + + inline Vector3int16& operator-=(const Vector3int16& other) { + x -= other.x; + y -= other.y; + z -= other.z; + return *this; + } + + inline Vector3int16& operator*=(const Vector3int16& other) { + x *= other.x; + y *= other.y; + z *= other.z; + return *this; + } + + inline bool operator== (const Vector3int16& rkVector) const { + return ( x == rkVector.x && y == rkVector.y && z == rkVector.z ); + } + + inline bool operator!= (const Vector3int16& rkVector) const { + return ( x != rkVector.x || y != rkVector.y || z != rkVector.z ); + } + + Vector3int16 max(const Vector3int16& v) const { + return Vector3int16(std::max(x, v.x), std::max(y, v.y), std::max(z, v.z)); + } + + Vector3int16 min(const Vector3int16& v) const { + return Vector3int16(std::min(x, v.x), std::min(y, v.y), std::min(z, v.z)); + } + + std::string toString() const; +} +G3D_END_PACKED_CLASS(2) + +} + +template <> struct HashTrait { + static size_t hashCode(const G3D::Vector3int16& key) { return static_cast(key.x + ((int)key.y << 5) + ((int)key.z << 10)); } +}; + +#endif diff --git a/dep/g3dlite/G3D/Vector3int32.h b/dep/g3dlite/G3D/Vector3int32.h new file mode 100644 index 00000000000..2f256ea0300 --- /dev/null +++ b/dep/g3dlite/G3D/Vector3int32.h @@ -0,0 +1,128 @@ +/** + @file Vector3int32.h + + @maintainer Morgan McGuire, matrix@brown.edu + + @created 2008-07-01 + @edited 2008-07-01 + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ + +#ifndef VECTOR3INT32_H +#define VECTOR3INT32_H + +#include "G3D/platform.h" +#include "G3D/g3dmath.h" +#include "G3D/HashTrait.h" + +namespace G3D { + +/** + \ Vector3int32 + A Vector3 that packs its fields into uint32s. + */ +G3D_BEGIN_PACKED_CLASS(4) +class Vector3int32 { +private: + // Hidden operators + bool operator<(const Vector3int32&) const; + bool operator>(const Vector3int32&) const; + bool operator<=(const Vector3int32&) const; + bool operator>=(const Vector3int32&) const; + +public: + G3D::int32 x; + G3D::int32 y; + G3D::int32 z; + + Vector3int32() : x(0), y(0), z(0) {} + Vector3int32(int _x, int _y, int _z) : x(_x), y(_y), z(_z) {} + Vector3int32(const class Vector3int16& v); + Vector3int32(const class Vector3& v); + Vector3int32(class BinaryInput& bi); + + void serialize(class BinaryOutput& bo) const; + void deserialize(class BinaryInput& bi); + + inline G3D::int32& operator[] (int i) { + debugAssert(i <= 2); + return ((G3D::int32*)this)[i]; + } + + inline const G3D::int32& operator[] (int i) const { + debugAssert(i <= 2); + return ((G3D::int32*)this)[i]; + } + + inline Vector3int32 operator+(const Vector3int32& other) const { + return Vector3int32(x + other.x, y + other.y, z + other.z); + } + + inline Vector3int32 operator-(const Vector3int32& other) const { + return Vector3int32(x - other.x, y - other.y, z - other.z); + } + + inline Vector3int32 operator*(const Vector3int32& other) const { + return Vector3int32(x * other.x, y * other.y, z * other.z); + } + + inline Vector3int32 operator*(const int s) const { + return Vector3int32(x * s, y * s, z * s); + } + + inline Vector3int32& operator+=(const Vector3int32& other) { + x += other.x; + y += other.y; + z += other.y; + return *this; + } + + inline Vector3int32& operator-=(const Vector3int32& other) { + x -= other.x; + y -= other.y; + z -= other.z; + return *this; + } + + inline Vector3int32& operator*=(const Vector3int32& other) { + x *= other.x; + y *= other.y; + z *= other.z; + return *this; + } + + inline bool operator== (const Vector3int32& rkVector) const { + return ( x == rkVector.x && y == rkVector.y && z == rkVector.z ); + } + + inline bool operator!= (const Vector3int32& rkVector) const { + return ( x != rkVector.x || y != rkVector.y || z != rkVector.z ); + } + + Vector3int32 max(const Vector3int32& v) const { + return Vector3int32(iMax(x, v.x), iMax(y, v.y), iMax(z, v.z)); + } + + Vector3int32 min(const Vector3int32& v) const { + return Vector3int32(iMin(x, v.x), iMin(y, v.y), iMin(z, v.z)); + } + + std::string toString() const; +} +G3D_END_PACKED_CLASS(4) + +} + +template <> struct HashTrait { + static size_t hashCode(const G3D::Vector3int32& key) { + // Mask for the top bit of a uint32 + const G3D::uint32 top = (1UL << 31); + // Mask for the bottom 10 bits of a uint32 + const G3D::uint32 bot = 0x000003FF; + return static_cast(((key.x & top) | ((key.y & top) >> 1) | ((key.z & top) >> 2)) | + (((key.x & bot) << 19) ^ ((key.y & bot) << 10) ^ (key.z & bot))); + } +}; + +#endif diff --git a/dep/g3dlite/G3D/Vector4.h b/dep/g3dlite/G3D/Vector4.h new file mode 100644 index 00000000000..5e511451f86 --- /dev/null +++ b/dep/g3dlite/G3D/Vector4.h @@ -0,0 +1,716 @@ +/** + @file Vector4.h + + Homogeneous vector class. + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2002-07-09 + @edited 2008-11-01 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_Vector4_h +#define G3D_Vector4_h + +#include "G3D/platform.h" +#include "G3D/g3dmath.h" +#include "G3D/Vector3.h" +#include "G3D/Vector2.h" +#include "G3D/Table.h" +#include "G3D/HashTrait.h" +#include "G3D/PositionTrait.h" +#include + +namespace G3D { + +class Vector2; +class Vector3; +class Vector4; +class Vector4int8; +class Any; + +/** + Do not subclass-- this implementation makes assumptions about the + memory layout. + */ +class Vector4 { +private: + // Hidden operators + bool operator<(const Vector4&) const; + bool operator>(const Vector4&) const; + bool operator<=(const Vector4&) const; + bool operator>=(const Vector4&) const; + +public: + + /** \param any Must either Vector4(#, #, #, #) or Vector3 {x = #, y = #, z = #, w =#}*/ + Vector4(const Any& any); + + /** Converts the Vector4 to an Any. */ + operator Any() const; + + // construction + Vector4(); + Vector4(float fX, float fY, float fZ, float fW); + Vector4(float afCoordinate[4]); + Vector4(const Vector4& rkVector); + Vector4(const class Color4& c); + Vector4(const Vector3& rkVector, float fW); + Vector4(const Vector2& v1, const Vector2& v2); + Vector4(const Vector2& v1, float fz, float fw); + + /** Divides by 127 when converting */ + Vector4(const Vector4int8&); + + Vector4(class BinaryInput& b); + void serialize(class BinaryOutput& b) const; + void deserialize(class BinaryInput& b); + + // coordinates + float x, y, z, w; + + // access vector V as V[0] = V.x, V[1] = V.y, V[2] = V.z, etc. + // + // WARNING. These member functions rely on + // (1) Vector4 not having virtual functions + // (2) the data packed in a 4*sizeof(float) memory block + float& operator[] (int i); + const float& operator[] (int i) const; + + // assignment and comparison + Vector4& operator= (const Vector4& rkVector); + bool operator== (const Vector4& rkVector) const; + bool operator!= (const Vector4& rkVector) const; + + static const Vector4& zero(); + + inline void set(float _x, float _y, float _z, float _w) { + x = _x; + y = _y; + z = _z; + w = _w; + } + + inline void set(const Vector3& v, float _w) { + x = v.x; + y = v.y; + z = v.z; + w = _w; + } + + inline void set(const Vector2& v, float _z, float _w) { + x = v.x; + y = v.y; + z = _z; + w = _w; + } + + size_t hashCode() const; + bool fuzzyEq(const Vector4& other) const; + bool fuzzyNe(const Vector4& other) const; + + static const Vector4& inf(); + static const Vector4& nan(); + + /** sqrt(this->dot(*this)) */ + float length() const; + float squaredLength() const; + + inline float sum() const { + return x + y + z + w; + } + + /** Returns true if this vector has finite length */ + bool isFinite() const; + + /** Returns true if this vector has length == 0 */ + bool isZero() const; + + /** Returns true if this vector has length == 1 */ + bool isUnit() const; + + // arithmetic operations + Vector4 operator+ (const Vector4& rkVector) const; + Vector4 operator- (const Vector4& rkVector) const; + + inline Vector4 operator*(const Vector4& rkVector) const { + return Vector4(x * rkVector.x, y * rkVector.y, z * rkVector.z, w * rkVector.w); + } + + inline Vector4 operator/(const Vector4& rkVector) const { + return Vector4(x / rkVector.x, y / rkVector.y, z / rkVector.z, w / rkVector.w); + } + + Vector4 operator*(const class Matrix4& M) const; + + Vector4 operator* (float fScalar) const; + Vector4 operator/ (float fScalar) const; + Vector4 operator- () const; + friend Vector4 operator* (float, const Vector4& rkVector); + + // arithmetic updates + Vector4& operator+= (const Vector4& rkVector); + Vector4& operator-= (const Vector4& rkVector); + Vector4& operator*= (float fScalar); + Vector4& operator/= (float fScalar); + + inline Vector4 clamp(const Vector4& low, const Vector4& high) const { + return Vector4( + G3D::clamp(x, low.x, high.x), + G3D::clamp(y, low.y, high.y), + G3D::clamp(z, low.z, high.z), + G3D::clamp(w, low.w, high.w)); + } + + inline Vector4 clamp(float low, float high) const { + return Vector4( + G3D::clamp(x, low, high), + G3D::clamp(y, low, high), + G3D::clamp(z, low, high), + G3D::clamp(w, low, high)); + } + + float dot (const Vector4& rkVector) const; + + Vector4 min(const Vector4& v) const; + Vector4 max(const Vector4& v) const; + + std::string toString() const; + + /** + Linear interpolation + */ + Vector4 lerp(const Vector4& v, float alpha) const; + + // 2-char swizzles + + Vector2 xx() const; + Vector2 yx() const; + Vector2 zx() const; + Vector2 wx() const; + Vector2 xy() const; + Vector2 yy() const; + Vector2 zy() const; + Vector2 wy() const; + Vector2 xz() const; + Vector2 yz() const; + Vector2 zz() const; + Vector2 wz() const; + Vector2 xw() const; + Vector2 yw() const; + Vector2 zw() const; + Vector2 ww() const; + + // 3-char swizzles + + Vector3 xxx() const; + Vector3 yxx() const; + Vector3 zxx() const; + Vector3 wxx() const; + Vector3 xyx() const; + Vector3 yyx() const; + Vector3 zyx() const; + Vector3 wyx() const; + Vector3 xzx() const; + Vector3 yzx() const; + Vector3 zzx() const; + Vector3 wzx() const; + Vector3 xwx() const; + Vector3 ywx() const; + Vector3 zwx() const; + Vector3 wwx() const; + Vector3 xxy() const; + Vector3 yxy() const; + Vector3 zxy() const; + Vector3 wxy() const; + Vector3 xyy() const; + Vector3 yyy() const; + Vector3 zyy() const; + Vector3 wyy() const; + Vector3 xzy() const; + Vector3 yzy() const; + Vector3 zzy() const; + Vector3 wzy() const; + Vector3 xwy() const; + Vector3 ywy() const; + Vector3 zwy() const; + Vector3 wwy() const; + Vector3 xxz() const; + Vector3 yxz() const; + Vector3 zxz() const; + Vector3 wxz() const; + Vector3 xyz() const; + Vector3 yyz() const; + Vector3 zyz() const; + Vector3 wyz() const; + Vector3 xzz() const; + Vector3 yzz() const; + Vector3 zzz() const; + Vector3 wzz() const; + Vector3 xwz() const; + Vector3 ywz() const; + Vector3 zwz() const; + Vector3 wwz() const; + Vector3 xxw() const; + Vector3 yxw() const; + Vector3 zxw() const; + Vector3 wxw() const; + Vector3 xyw() const; + Vector3 yyw() const; + Vector3 zyw() const; + Vector3 wyw() const; + Vector3 xzw() const; + Vector3 yzw() const; + Vector3 zzw() const; + Vector3 wzw() const; + Vector3 xww() const; + Vector3 yww() const; + Vector3 zww() const; + Vector3 www() const; + + // 4-char swizzles + + Vector4 xxxx() const; + Vector4 yxxx() const; + Vector4 zxxx() const; + Vector4 wxxx() const; + Vector4 xyxx() const; + Vector4 yyxx() const; + Vector4 zyxx() const; + Vector4 wyxx() const; + Vector4 xzxx() const; + Vector4 yzxx() const; + Vector4 zzxx() const; + Vector4 wzxx() const; + Vector4 xwxx() const; + Vector4 ywxx() const; + Vector4 zwxx() const; + Vector4 wwxx() const; + Vector4 xxyx() const; + Vector4 yxyx() const; + Vector4 zxyx() const; + Vector4 wxyx() const; + Vector4 xyyx() const; + Vector4 yyyx() const; + Vector4 zyyx() const; + Vector4 wyyx() const; + Vector4 xzyx() const; + Vector4 yzyx() const; + Vector4 zzyx() const; + Vector4 wzyx() const; + Vector4 xwyx() const; + Vector4 ywyx() const; + Vector4 zwyx() const; + Vector4 wwyx() const; + Vector4 xxzx() const; + Vector4 yxzx() const; + Vector4 zxzx() const; + Vector4 wxzx() const; + Vector4 xyzx() const; + Vector4 yyzx() const; + Vector4 zyzx() const; + Vector4 wyzx() const; + Vector4 xzzx() const; + Vector4 yzzx() const; + Vector4 zzzx() const; + Vector4 wzzx() const; + Vector4 xwzx() const; + Vector4 ywzx() const; + Vector4 zwzx() const; + Vector4 wwzx() const; + Vector4 xxwx() const; + Vector4 yxwx() const; + Vector4 zxwx() const; + Vector4 wxwx() const; + Vector4 xywx() const; + Vector4 yywx() const; + Vector4 zywx() const; + Vector4 wywx() const; + Vector4 xzwx() const; + Vector4 yzwx() const; + Vector4 zzwx() const; + Vector4 wzwx() const; + Vector4 xwwx() const; + Vector4 ywwx() const; + Vector4 zwwx() const; + Vector4 wwwx() const; + Vector4 xxxy() const; + Vector4 yxxy() const; + Vector4 zxxy() const; + Vector4 wxxy() const; + Vector4 xyxy() const; + Vector4 yyxy() const; + Vector4 zyxy() const; + Vector4 wyxy() const; + Vector4 xzxy() const; + Vector4 yzxy() const; + Vector4 zzxy() const; + Vector4 wzxy() const; + Vector4 xwxy() const; + Vector4 ywxy() const; + Vector4 zwxy() const; + Vector4 wwxy() const; + Vector4 xxyy() const; + Vector4 yxyy() const; + Vector4 zxyy() const; + Vector4 wxyy() const; + Vector4 xyyy() const; + Vector4 yyyy() const; + Vector4 zyyy() const; + Vector4 wyyy() const; + Vector4 xzyy() const; + Vector4 yzyy() const; + Vector4 zzyy() const; + Vector4 wzyy() const; + Vector4 xwyy() const; + Vector4 ywyy() const; + Vector4 zwyy() const; + Vector4 wwyy() const; + Vector4 xxzy() const; + Vector4 yxzy() const; + Vector4 zxzy() const; + Vector4 wxzy() const; + Vector4 xyzy() const; + Vector4 yyzy() const; + Vector4 zyzy() const; + Vector4 wyzy() const; + Vector4 xzzy() const; + Vector4 yzzy() const; + Vector4 zzzy() const; + Vector4 wzzy() const; + Vector4 xwzy() const; + Vector4 ywzy() const; + Vector4 zwzy() const; + Vector4 wwzy() const; + Vector4 xxwy() const; + Vector4 yxwy() const; + Vector4 zxwy() const; + Vector4 wxwy() const; + Vector4 xywy() const; + Vector4 yywy() const; + Vector4 zywy() const; + Vector4 wywy() const; + Vector4 xzwy() const; + Vector4 yzwy() const; + Vector4 zzwy() const; + Vector4 wzwy() const; + Vector4 xwwy() const; + Vector4 ywwy() const; + Vector4 zwwy() const; + Vector4 wwwy() const; + Vector4 xxxz() const; + Vector4 yxxz() const; + Vector4 zxxz() const; + Vector4 wxxz() const; + Vector4 xyxz() const; + Vector4 yyxz() const; + Vector4 zyxz() const; + Vector4 wyxz() const; + Vector4 xzxz() const; + Vector4 yzxz() const; + Vector4 zzxz() const; + Vector4 wzxz() const; + Vector4 xwxz() const; + Vector4 ywxz() const; + Vector4 zwxz() const; + Vector4 wwxz() const; + Vector4 xxyz() const; + Vector4 yxyz() const; + Vector4 zxyz() const; + Vector4 wxyz() const; + Vector4 xyyz() const; + Vector4 yyyz() const; + Vector4 zyyz() const; + Vector4 wyyz() const; + Vector4 xzyz() const; + Vector4 yzyz() const; + Vector4 zzyz() const; + Vector4 wzyz() const; + Vector4 xwyz() const; + Vector4 ywyz() const; + Vector4 zwyz() const; + Vector4 wwyz() const; + Vector4 xxzz() const; + Vector4 yxzz() const; + Vector4 zxzz() const; + Vector4 wxzz() const; + Vector4 xyzz() const; + Vector4 yyzz() const; + Vector4 zyzz() const; + Vector4 wyzz() const; + Vector4 xzzz() const; + Vector4 yzzz() const; + Vector4 zzzz() const; + Vector4 wzzz() const; + Vector4 xwzz() const; + Vector4 ywzz() const; + Vector4 zwzz() const; + Vector4 wwzz() const; + Vector4 xxwz() const; + Vector4 yxwz() const; + Vector4 zxwz() const; + Vector4 wxwz() const; + Vector4 xywz() const; + Vector4 yywz() const; + Vector4 zywz() const; + Vector4 wywz() const; + Vector4 xzwz() const; + Vector4 yzwz() const; + Vector4 zzwz() const; + Vector4 wzwz() const; + Vector4 xwwz() const; + Vector4 ywwz() const; + Vector4 zwwz() const; + Vector4 wwwz() const; + Vector4 xxxw() const; + Vector4 yxxw() const; + Vector4 zxxw() const; + Vector4 wxxw() const; + Vector4 xyxw() const; + Vector4 yyxw() const; + Vector4 zyxw() const; + Vector4 wyxw() const; + Vector4 xzxw() const; + Vector4 yzxw() const; + Vector4 zzxw() const; + Vector4 wzxw() const; + Vector4 xwxw() const; + Vector4 ywxw() const; + Vector4 zwxw() const; + Vector4 wwxw() const; + Vector4 xxyw() const; + Vector4 yxyw() const; + Vector4 zxyw() const; + Vector4 wxyw() const; + Vector4 xyyw() const; + Vector4 yyyw() const; + Vector4 zyyw() const; + Vector4 wyyw() const; + Vector4 xzyw() const; + Vector4 yzyw() const; + Vector4 zzyw() const; + Vector4 wzyw() const; + Vector4 xwyw() const; + Vector4 ywyw() const; + Vector4 zwyw() const; + Vector4 wwyw() const; + Vector4 xxzw() const; + Vector4 yxzw() const; + Vector4 zxzw() const; + Vector4 wxzw() const; + Vector4 xyzw() const; + Vector4 yyzw() const; + Vector4 zyzw() const; + Vector4 wyzw() const; + Vector4 xzzw() const; + Vector4 yzzw() const; + Vector4 zzzw() const; + Vector4 wzzw() const; + Vector4 xwzw() const; + Vector4 ywzw() const; + Vector4 zwzw() const; + Vector4 wwzw() const; + Vector4 xxww() const; + Vector4 yxww() const; + Vector4 zxww() const; + Vector4 wxww() const; + Vector4 xyww() const; + Vector4 yyww() const; + Vector4 zyww() const; + Vector4 wyww() const; + Vector4 xzww() const; + Vector4 yzww() const; + Vector4 zzww() const; + Vector4 wzww() const; + Vector4 xwww() const; + Vector4 ywww() const; + Vector4 zwww() const; + Vector4 wwww() const; + +}; + + +//---------------------------------------------------------------------------- +inline Vector4::Vector4() { + x = y = z = w = 0; +} + +//---------------------------------------------------------------------------- + +inline Vector4::Vector4 (float fX, float fY, float fZ, float fW) { + x = fX; + y = fY; + z = fZ; + w = fW; +} + +//---------------------------------------------------------------------------- +inline Vector4::Vector4 (float afCoordinate[4]) { + x = afCoordinate[0]; + y = afCoordinate[1]; + z = afCoordinate[2]; + w = afCoordinate[3]; +} + +//---------------------------------------------------------------------------- +inline Vector4::Vector4(const Vector4& rkVector) { + x = rkVector.x; + y = rkVector.y; + z = rkVector.z; + w = rkVector.w; +} +//---------------------------------------------------------------------------- +inline Vector4::Vector4(const Vector3& rkVector, float fW) { + x = rkVector.x; + y = rkVector.y; + z = rkVector.z; + w = fW; +} + +//---------------------------------------------------------------------------- +inline float& Vector4::operator[] (int i) { + return ((float*)this)[i]; +} + +//---------------------------------------------------------------------------- +inline const float& Vector4::operator[] (int i) const { + return ((float*)this)[i]; +} + +//---------------------------------------------------------------------------- +inline Vector4& Vector4::operator= (const Vector4& rkVector) { + x = rkVector.x; + y = rkVector.y; + z = rkVector.z; + w = rkVector.w; + return *this; +} + +//---------------------------------------------------------------------------- +inline bool Vector4::operator== (const Vector4& rkVector) const { + return ( (x == rkVector.x) && (y == rkVector.y) && (z == rkVector.z) && (w == rkVector.w)); +} + +//---------------------------------------------------------------------------- +inline bool Vector4::operator!= (const Vector4& rkVector) const { + return ( x != rkVector.x || y != rkVector.y || z != rkVector.z || w != rkVector.w); +} + +//---------------------------------------------------------------------------- +inline Vector4 Vector4::operator+ (const Vector4& rkVector) const { + return Vector4(x + rkVector.x, y + rkVector.y, z + rkVector.z, w + rkVector.w); +} + +//---------------------------------------------------------------------------- +inline Vector4 Vector4::operator- (const Vector4& rkVector) const { + return Vector4(x - rkVector.x, y - rkVector.y, z - rkVector.z, w - rkVector.w); +} + +//---------------------------------------------------------------------------- +inline Vector4 Vector4::operator* (float fScalar) const { + return Vector4(fScalar*x, fScalar*y, fScalar*z, fScalar*w); +} + +//---------------------------------------------------------------------------- +inline Vector4 Vector4::operator- () const { + return Vector4( -x, -y, -z, -w); +} + +//---------------------------------------------------------------------------- +inline Vector4& Vector4::operator+= (const Vector4& rkVector) { + x += rkVector.x; + y += rkVector.y; + z += rkVector.z; + w += rkVector.w; + return *this; +} + +//---------------------------------------------------------------------------- +inline Vector4& Vector4::operator-= (const Vector4& rkVector) { + x -= rkVector.x; + y -= rkVector.y; + z -= rkVector.z; + w -= rkVector.w; + return *this; +} + +//---------------------------------------------------------------------------- + +inline Vector4 Vector4::lerp(const Vector4& v, float alpha) const { + return (*this) + (v - *this) * alpha; +} + + +//---------------------------------------------------------------------------- +inline Vector4& Vector4::operator*= (float fScalar) { + x *= fScalar; + y *= fScalar; + z *= fScalar; + w *= fScalar; + return *this; +} + + +//---------------------------------------------------------------------------- +inline float Vector4::dot(const Vector4& rkVector) const { + return x*rkVector.x + y*rkVector.y + z*rkVector.z + w*rkVector.w; +} + +//---------------------------------------------------------------------------- +inline Vector4 Vector4::min(const Vector4 &v) const { + return Vector4(G3D::min(v.x, x), G3D::min(v.y, y), G3D::min(v.z, z), G3D::min(v.w, w)); +} + +//---------------------------------------------------------------------------- +inline Vector4 Vector4::max(const Vector4 &v) const { + return Vector4(G3D::max(v.x, x), G3D::max(v.y, y), G3D::max(v.z, z), G3D::max(v.w, w)); +} + +//---------------------------------------------------------------------------- +inline bool Vector4::isZero() const { + return (x == 0.0f) && (y == 0.0f) && (z == 0.0f) && (w == 0.0f); +} + +//---------------------------------------------------------------------------- + +inline bool Vector4::isFinite() const { + return G3D::isFinite(x) && G3D::isFinite(y) && G3D::isFinite(z) && G3D::isFinite(w); +} + +//---------------------------------------------------------------------------- + +inline bool Vector4::isUnit() const { + return squaredLength() == 1.0; +} + +//---------------------------------------------------------------------------- + +inline float Vector4::length() const { + return sqrtf(squaredLength()); +} + +//---------------------------------------------------------------------------- + +inline float Vector4::squaredLength() const { + return x * x + y * y + z * z + w * w; +} + +} + +template <> struct HashTrait { + static size_t hashCode(const G3D::Vector4& key) { return key.hashCode(); } +}; + + +template<> struct PositionTrait { + static void getPosition(const G3D::Vector4& v, G3D::Vector3& p) { p = v.xyz(); } +}; + +inline G3D::Vector4 operator* (float s, const G3D::Vector4& v) { + return v * s; +} + +#endif diff --git a/dep/g3dlite/G3D/Vector4.inl b/dep/g3dlite/G3D/Vector4.inl new file mode 100644 index 00000000000..576cca83b56 --- /dev/null +++ b/dep/g3dlite/G3D/Vector4.inl @@ -0,0 +1,191 @@ +/** + @file Vector4.inl + + @maintainer Morgan McGuire, matrix@graphics3d.com + + @created 2002-07-09 + @edited 2003-02-10 + */ + +//---------------------------------------------------------------------------- + +inline unsigned int hashCode(const G3D::Vector4& v) { + return v.hashCode(); +} + +namespace G3D { + +//---------------------------------------------------------------------------- +inline Vector4::Vector4() { + x = y = z = w = 0; +} + +//---------------------------------------------------------------------------- + +inline Vector4::Vector4 (float fX, float fY, float fZ, float fW) { + x = fX; + y = fY; + z = fZ; + w = fW; +} + +//---------------------------------------------------------------------------- +inline Vector4::Vector4 (float afCoordinate[4]) { + x = afCoordinate[0]; + y = afCoordinate[1]; + z = afCoordinate[2]; + w = afCoordinate[3]; +} + +//---------------------------------------------------------------------------- +inline Vector4::Vector4(const Vector4& rkVector) { + x = rkVector.x; + y = rkVector.y; + z = rkVector.z; + w = rkVector.w; +} +//---------------------------------------------------------------------------- +inline Vector4::Vector4(const Vector3& rkVector, float fW) { + x = rkVector.x; + y = rkVector.y; + z = rkVector.z; + w = fW; +} + +//---------------------------------------------------------------------------- +inline float& Vector4::operator[] (int i) { + return ((float*)this)[i]; +} + +//---------------------------------------------------------------------------- +inline const float& Vector4::operator[] (int i) const { + return ((float*)this)[i]; +} + +//---------------------------------------------------------------------------- +inline Vector4::operator float* () { + return (float*)this; +} + +inline Vector4::operator const float* () const { + return (float*)this; +} + +//---------------------------------------------------------------------------- +inline Vector4& Vector4::operator= (const Vector4& rkVector) { + x = rkVector.x; + y = rkVector.y; + z = rkVector.z; + w = rkVector.w; + return *this; +} + +//---------------------------------------------------------------------------- +inline bool Vector4::operator== (const Vector4& rkVector) const { + return ( (x == rkVector.x) && (y == rkVector.y) && (z == rkVector.z) && (w == rkVector.w)); +} + +//---------------------------------------------------------------------------- +inline bool Vector4::operator!= (const Vector4& rkVector) const { + return ( x != rkVector.x || y != rkVector.y || z != rkVector.z || w != rkVector.w); +} + +//---------------------------------------------------------------------------- +inline Vector4 Vector4::operator+ (const Vector4& rkVector) const { + return Vector4(x + rkVector.x, y + rkVector.y, z + rkVector.z, w + rkVector.w); +} + +//---------------------------------------------------------------------------- +inline Vector4 Vector4::operator- (const Vector4& rkVector) const { + return Vector4(x - rkVector.x, y - rkVector.y, z - rkVector.z, w - rkVector.w); +} + +//---------------------------------------------------------------------------- +inline Vector4 Vector4::operator* (float fScalar) const { + return Vector4(fScalar*x, fScalar*y, fScalar*z, fScalar*w); +} + +//---------------------------------------------------------------------------- +inline Vector4 Vector4::operator- () const { + return Vector4( -x, -y, -z, -w); +} + +//---------------------------------------------------------------------------- +inline Vector4& Vector4::operator+= (const Vector4& rkVector) { + x += rkVector.x; + y += rkVector.y; + z += rkVector.z; + w += rkVector.w; + return *this; +} + +//---------------------------------------------------------------------------- +inline Vector4& Vector4::operator-= (const Vector4& rkVector) { + x -= rkVector.x; + y -= rkVector.y; + z -= rkVector.z; + w -= rkVector.w; + return *this; +} + +//---------------------------------------------------------------------------- + +inline Vector4 Vector4::lerp(const Vector4& v, float alpha) const { + return (*this) + (v - *this) * alpha; +} + +//---------------------------------------------------------------------------- +inline Vector4& Vector4::operator*= (float fScalar) { + x *= fScalar; + y *= fScalar; + z *= fScalar; + w *= fScalar; + return *this; +} + +//---------------------------------------------------------------------------- +inline float Vector4::dot(const Vector4& rkVector) const { + return x*rkVector.x + y*rkVector.y + z*rkVector.z + w*rkVector.w; +} + +//---------------------------------------------------------------------------- +inline Vector4 Vector4::min(const Vector4 &v) const { + return Vector4(G3D::min(v.x, x), G3D::min(v.y, y), G3D::min(v.z, z), G3D::min(v.w, w)); +} + +//---------------------------------------------------------------------------- +inline Vector4 Vector4::max(const Vector4 &v) const { + return Vector4(G3D::max(v.x, x), G3D::max(v.y, y), G3D::max(v.z, z), G3D::max(v.w, w)); +} + +//---------------------------------------------------------------------------- +inline bool Vector4::isZero() const { + return (x == 0.0f) && (y == 0.0f) && (z == 0.0f) && (w == 0.0f); +} + +//---------------------------------------------------------------------------- + +inline bool Vector4::isFinite() const { + return G3D::isFinite(x) && G3D::isFinite(y) && G3D::isFinite(z) && G3D::isFinite(w); +} + +//---------------------------------------------------------------------------- + +inline bool Vector4::isUnit() const { + return squaredLength() == 1.0; +} + +//---------------------------------------------------------------------------- + +inline float Vector4::length() const { + return sqrtf(squaredLength()); +} + +//---------------------------------------------------------------------------- + +inline float Vector4::squaredLength() const { + return x * x + y * y + z * z + w * w; +} + +} + diff --git a/dep/g3dlite/G3D/Vector4int8.h b/dep/g3dlite/G3D/Vector4int8.h new file mode 100644 index 00000000000..544b693e8b3 --- /dev/null +++ b/dep/g3dlite/G3D/Vector4int8.h @@ -0,0 +1,113 @@ +/** + @file Vector4int8.h + + Homogeneous vector class. + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2007-02-09 + @edited 2007-02-09 + + Copyright 2000-2007, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_VECTOR4INT8_H +#define G3D_VECTOR4INT8_H + +#include "G3D/platform.h" +#include "G3D/g3dmath.h" + +namespace G3D { + +class Vector3; +class Vector4; + +/** + Homogeneous vector stored efficiently in four signed int8s. + + */ +class Vector4int8 { +private: + // Hidden operators + bool operator<(const Vector4int8&) const; + bool operator>(const Vector4int8&) const; + bool operator<=(const Vector4int8&) const; + bool operator>=(const Vector4int8&) const; + + + /** For fast operations, treat this packed data structure as + an int32 */ + inline uint32& asInt32() { + return *reinterpret_cast(this); + } + + inline const uint32& asInt32() const { + return *reinterpret_cast(this); + } + +public: + // construction + inline Vector4int8() : x(0), y(0), z(0), w(0) {} + + /** Multiplies the source by 127 and clamps to (-128, 127) when converting */ + Vector4int8(const Vector4& source); + + /** Multiplies the source by 127 and clamps to (-128, 127) when converting */ + Vector4int8(const Vector3& source, int8 w); + + inline Vector4int8(int8 x, int8 y, int8 z, int8 w) : x(x), y(y), z(z), w(w) {} + + Vector4int8(class BinaryInput& b); + void serialize(class BinaryOutput& b) const; + void deserialize(class BinaryInput& b); + + // coordinates + int8 x, y, z, w; + + inline operator int8* () { + return reinterpret_cast(this); + } + + inline operator const int8* () const { + return reinterpret_cast(this); + } + + // access vector V as V[0] = V.x, V[1] = V.y, V[2] = V.z, etc. + // + // WARNING. These member functions rely on + // (1) Vector4int8 not having virtual functions + // (2) the data packed in a 4*sizeof(int8) memory block + inline int8& operator[] (int i) { + debugAssert(i >= 0 && i <= 4); + return ((int8*)this)[i]; + } + + const int8& operator[] (int i) const { + debugAssert(i >= 0 && i <= 4); + return ((const int8*)this)[i]; + } + + // assignment and comparison + Vector4int8& operator= (const Vector4int8& other) { + asInt32() = other.asInt32(); + return *this; + } + + inline bool operator== (const Vector4int8& other) const { + return asInt32() == other.asInt32(); + } + + inline bool operator!= (const Vector4int8& other) const { + return ! (*this == other); + } + + inline unsigned int hashCode() const { + return asInt32(); + } +}; + +} // namespace G3D + + +#endif diff --git a/dep/g3dlite/G3D/WeakCache.h b/dep/g3dlite/G3D/WeakCache.h new file mode 100644 index 00000000000..f9fdc4bbd5b --- /dev/null +++ b/dep/g3dlite/G3D/WeakCache.h @@ -0,0 +1,122 @@ +/** + @file WeakCache.h + + @maintainer Morgan McGuire, graphics3d.com + + @created 2007-05-16 + @edited 2007-05-16 + + Copyright 2000-2007, Morgan McGuire. + All rights reserved. + */ +#ifndef G3D_WEAKCACHE_H +#define G3D_WEAKCACHE_H + +#include "G3D/ReferenceCount.h" +#include "G3D/Table.h" + +namespace G3D { + +/** + A cache that does not prevent its members from being garbage collected. + Useful to avoid loading or computing an expression twice. Useful + for memoization and dynamic programming. + + Maintains a table of weak pointers. Weak pointers do not prevent + an object from being garbage collected. If the object is garbage + collected, the cache removes its reference. + + There are no "contains" or "iterate" methods because elements can be + flushed from the cache at any time if they are garbage collected. + + Example: +
+      WeakCache textureCache;
+
+      TextureRef loadTexture(std::string s) {
+          TextureRef t = textureCache[s];
+
+          if (t.isNull()) {
+              t = Texture::fromFile(s);
+              textureCache.set(s, t);
+          }
+
+          return t;
+      }
+      
+      
+    
+ */ +template +class WeakCache { + typedef WeakReferenceCountedPointer ValueWeakRef; + +private: + + Table table; + +public: + /** + Returns NULL if the object is not in the cache + */ + ValueRef operator[](const Key& k) { + if (table.containsKey(k)) { + ValueWeakRef w = table[k]; + ValueRef s = w.createStrongPtr(); + if (s.isNull()) { + // This object has been collected; clean out its key + table.remove(k); + } + return s; + } else { + return NULL; + } + } + + void set(const Key& k, ValueRef v) { + table.set(k, v); + } + + /** Removes k from the cache or does nothing if it is not currently in the cache.*/ + void remove(const Key& k) { + if (table.containsKey(k)) { + table.remove(k); + } + } +}; + +#if 0 // To turn off all WeakCaching +template +class WeakCache { +private: + + Table table; + +public: + /** + Returns NULL if the object is not in the cache + */ + ValueRef operator[](const Key& k) { + if (table.containsKey(k)) { + return table[k]; + } else { + return NULL; + } + } + + void set(const Key& k, ValueRef v) { + table.set(k, v); + } + + /** Removes k from the cache or does nothing if it is not currently in the cache.*/ + void remove(const Key& k) { + if (table.containsKey(k)) { + table.remove(k); + } + } +}; +#endif + +} +#endif + diff --git a/dep/g3dlite/G3D/Welder.h b/dep/g3dlite/G3D/Welder.h new file mode 100644 index 00000000000..2c2554da7b6 --- /dev/null +++ b/dep/g3dlite/G3D/Welder.h @@ -0,0 +1,82 @@ +#ifndef G3D_Welder_h +#define G3D_Welder_h + +#include "G3D/platform.h" +#include "G3D/Array.h" +#include "G3D/Vector3.h" +#include "G3D/Vector2.h" + +namespace G3D { + +class Any; + +class Welder { +private: + + Welder() {} + +public: + + class Settings { + public: + /** Surfaces with normals that are within this angle of each + other are considered to be curved. Default value is toRadians(70.0f).*/ + float normalSmoothingAngle; + float vertexWeldRadius; + float textureWeldRadius; + float normalWeldRadius; + + inline Settings(float normalSmoothAngle = toRadians(70.0f)) : + normalSmoothingAngle(normalSmoothAngle), + vertexWeldRadius(0.0001f), + textureWeldRadius(0.0001f), + normalWeldRadius(0.01f) {} + + + Settings(const Any& any); + operator Any() const; + }; + +/** + Mutates geometry, texCoord, and indexArray so that the output has collocated vertices collapsed (welded). + + @param vertices Input and output + @param textureCoords Input and output + @param normals Output only + @param indices Input and output. This is an array of trilist indices. + @param oldToNewIndex Output argument + @param normalSmoothingAngle Varies from 0 (flat shading) to toRadians(180) for extremely smooth shading. Default is toRadians(70) + */ + static void weld( + Array& vertices, + Array& textureCoords, + Array& normals, + Array*>& indices, + const Settings& settings); + + /** + Mutates geometry, texCoord, and indexArray so that the output has collocated vertices collapsed (welded). + + @param vertices Input and output + @param textureCoords Input and output + @param normals Output only + @param indices Input and output. This is an array of trilist indices. + @param oldToNewIndex Output argument + @param normalSmoothingAngle Varies from 0 (flat shading) to toRadians(180) for extremely smooth shading. Default is toRadians(70) + */ + inline static void weld( + Array& vertices, + Array& textureCoords, + Array& normals, + Array& indices, + const Settings& settings) { + + Array*> meta; + meta.append(&indices); + weld(vertices, textureCoords, normals, meta, settings); + } +}; + +} + +#endif diff --git a/dep/g3dlite/G3D/WrapMode.h b/dep/g3dlite/G3D/WrapMode.h new file mode 100644 index 00000000000..8ef38a77c23 --- /dev/null +++ b/dep/g3dlite/G3D/WrapMode.h @@ -0,0 +1,93 @@ +/** + @file WrapMode.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2007-04-17 + @edited 2007-04-17 + + Copyright 2000-2010, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_WrapMode_h +#define G3D_WrapMode_h + +#include "G3D/platform.h" +#include "G3D/enumclass.h" + +#ifdef IGNORE +# undef IGNORE +#endif +#ifdef ZERO +# undef ZERO +#endif +#ifdef ERROR +# undef ERROR +#endif + +namespace G3D { + +/** + Describes the behavior of G3D::Texture, G3D::Map2D, G3D::Image3, + etc. when accessing an out-of-bounds pixel. Not all classes support + all modes. + + Refer to these as scoped enums, e.g., WrapMode m = WrapMode::CLAMP;. + + WrapMode::IGNORE silently discards attempts to write to out + of bounds locations and returns an undefined value for reading + from out of bounds locations. + + WrapMode::ERROR generates an error when the + pixel indices are out of bounds + + WrapMode::CLAMP makes out of bounds pixels equal to the last in-range pixel along that dimension. + + WrapMode::TILE computes out of bounds pixels modulo the dimension + + WrapMode::ZERO treats out of bounds values as the zero value, which varies in definition + according to the class used. For example, with a G3D::Texture, ZERO = Color4(0,0,0,0). + + Uses the "Intelligent Enum" design pattern + http://www.codeguru.com/cpp/cpp/cpp_mfc/article.php/c4001/ + */ +class WrapMode { +public: + /** Don't use this enum; use WrapMode instances instead. */ + enum Value { + CLAMP, + TILE, + ZERO, + IGNORE, + ERROR + }; + +private: + + Value value; + +public: + + G3D_DECLARE_ENUM_CLASS_METHODS(WrapMode); + + inline const char* toString() const { + static const char* s[] = {"CLAMP", "TILE", "ZERO", "IGNORE", "ERROR"}; + return s[value]; + } + + inline explicit WrapMode(const std::string& x) : value(ERROR) { + static const char* s[] = {"CLAMP", "TILE", "ZERO", "IGNORE", "ERROR"}; + for (int i = 0; i < 5; ++i) { + if (x == s[i]) { + value = (Value)i; + } + } + } +}; + +} // namespace G3D + +G3D_DECLARE_ENUM_CLASS_HASHCODE(G3D::WrapMode); + +#endif diff --git a/dep/g3dlite/G3D/constants.h b/dep/g3dlite/G3D/constants.h new file mode 100644 index 00000000000..dd5cb3649e5 --- /dev/null +++ b/dep/g3dlite/G3D/constants.h @@ -0,0 +1,129 @@ +/** + @file G3D/constants.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + @created 2009-05-20 + @edited 2009-05-20 +*/ +#ifndef G3D_constants_h +#define G3D_constants_h + +#include "G3D/platform.h" +#include "G3D/enumclass.h" + +namespace G3D { + +/** These are defined to have the same value as the equivalent OpenGL + constant. */ +class PrimitiveType { +public: + enum Value { + POINTS = 0x0000, + LINES = 0x0001, + LINE_STRIP = 0x0003, + TRIANGLES = 0x0004, + TRIANGLE_STRIP = 0x0005, + TRIANGLE_FAN = 0x0006, + QUADS = 0x0007, + QUAD_STRIP = 0x0008 + }; + +private: + + Value value; + +public: + + G3D_DECLARE_ENUM_CLASS_METHODS(PrimitiveType); +}; + + +/** Values for SuperSurface::GPUGeom::refractionHint. */ +class RefractionQuality { +public: + enum Value { + /** No refraction; a translucent object will appear as if it had the same index of refraction + as the surrounding medium and objects will be undistorted in the background. */ + NONE = 0, + + /** Use a static environment map (cube or paraboloid) for computing transmissivity.*/ + STATIC_ENV = 25, + + /** Use a dynamically rendered 2D environment map; distort the background. This looks good for many scenes + but avoids the cost of rendering a cube map for DYNAMIC_ENV. */ + DYNAMIC_FLAT = 50, + + /** Use a dynamically rendered 2D environment map that is re-captured per transparent object. This works well + for transparent objects that are separated by a significant camera space z distance but overlap in screen space.*/ + DYNAMIC_FLAT_MULTILAYER = 55, + + /** Render a dynamic environment map */ + DYNAMIC_ENV = 75, + + /** Use the best method available, ideally true ray tracing. */ + BEST = 100 + }; + +private: + + /** Used for to/from string conversion. Last is the emtpy string as a sentinel */ + static const std::string str[7]; + static const Value enm[6]; + Value value; + +public: + G3D_DECLARE_ENUM_CLASS_METHODS(RefractionQuality); + + RefractionQuality(const class Any&); + RefractionQuality& operator=(const Any&); + operator Any() const; + const std::string& toString() const; +}; + + +/** Values for SuperSurface::GPUGeom::mirrorHint. */ +class MirrorQuality { +public: + + enum Value { + /** Reflections are black */ + NONE = 0, + + /** Use a static environment map. This is what most games use */ + STATIC_ENV = 25, + + /** Planar reflection, typically for water or glass windows. This assumes that the mirror is flat; + it is distinct from RefractionQuality::DYNAMIC_FLAT, which assumes the background is flat.*/ + DYNAMIC_PLANAR = 50, + + /** Render a dynamic environment map. */ + DYNAMIC_ENV = 75, + + /** Use the best method available, ideally true ray tracing. */ + BEST = 100 + }; + +private: + + /** Used for to/from string conversion. Last is the emtpy string as a sentinel */ + static const std::string str[6]; + static const Value enm[5]; + + Value value; + +public: + G3D_DECLARE_ENUM_CLASS_METHODS(MirrorQuality); + MirrorQuality(const class Any&); + MirrorQuality& operator=(const Any&); + operator Any() const; + const std::string& toString() const; +}; + +} // namespace G3D + +G3D_DECLARE_ENUM_CLASS_HASHCODE(G3D::PrimitiveType) +G3D_DECLARE_ENUM_CLASS_HASHCODE(G3D::RefractionQuality) +G3D_DECLARE_ENUM_CLASS_HASHCODE(G3D::MirrorQuality) + +#endif + diff --git a/dep/g3dlite/G3D/debug.h b/dep/g3dlite/G3D/debug.h new file mode 100644 index 00000000000..a7697fe9c01 --- /dev/null +++ b/dep/g3dlite/G3D/debug.h @@ -0,0 +1,66 @@ +/** + @file debug.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2001-08-26 + @edited 2006-02-16 + + Copyright 2000-2006, Morgan McGuire. + All rights reserved. +*/ + +#ifndef G3D_DEBUG_H +#define G3D_DEBUG_H + +#include "G3D/platform.h" +#ifdef _MSC_VER + #include +#endif + +#include "G3D/debugPrintf.h" +#include "G3D/debugAssert.h" + +namespace G3D { + +#ifdef _MSC_VER + // Turn off 64-bit warnings +# pragma warning(push) +# pragma warning( disable : 4312) +# pragma warning( disable : 4267) +# pragma warning( disable : 4311) +#endif + + +/** + Useful for debugging purposes. + */ +inline bool isValidHeapPointer(const void* x) { + #ifdef _MSC_VER + return + (x != (void*)0xcccccccc) && (x != (void*)0xdeadbeef) && (x != (void*)0xfeeefeee); + #else + return x != NULL; + #endif +} + +/** + Returns true if the pointer is likely to be + a valid pointer (instead of an arbitrary number). + Useful for debugging purposes. + */ +inline bool isValidPointer(const void* x) { + #ifdef _MSC_VER + return x != ((void*)0xcccccccc) && (x != (void*)0xdeadbeef) && (x != (void*)0xfeeefeee); + #else + return x != NULL; + #endif +} + +#ifdef _MSC_VER +# pragma warning(pop) +#endif + +} + +#endif diff --git a/dep/g3dlite/G3D/debugAssert.h b/dep/g3dlite/G3D/debugAssert.h new file mode 100644 index 00000000000..432e97e679d --- /dev/null +++ b/dep/g3dlite/G3D/debugAssert.h @@ -0,0 +1,233 @@ +/** + @file debugAssert.h + + debugAssert(expression); + debugAssertM(expression, message); + + @cite + John Robbins, Microsoft Systems Journal Bugslayer Column, Feb 1999. + + http://msdn.microsoft.com/library/periodic/period99/feb99_BUGSLAYE_BUGSLAYE.htm + + @cite + Douglas Cox, An assert() Replacement, Code of The Day, flipcode, Sept 19, 2000 + + http://www.flipcode.com/cgi-bin/msg.cgi?showThread=COTD-AssertReplace&forum=cotd&id=-1 + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2001-08-26 + @edited 2006-01-12 + + Copyright 2000-2006, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_DEBUGASSERT_H +#define G3D_DEBUGASSERT_H + +#include +#include "G3D/platform.h" + +#include + +#ifdef _MSC_VER +// conditional expression is constant +# pragma warning (disable : 4127) +#endif + +#ifdef G3D_LINUX + // Needed so we can define a global display + // pointer for debugAssert. +#if SOMEONE_MADE_THIS_USEFUL + #include + #include + #include +#endif +#endif + + +/** + @def debugBreak() + + Break at the current location (i.e. don't push a procedure stack frame + before breaking). + */ + +/** + @def debugAssert(exp) + Breaks if the expression is false. If G3D_DEBUG_NOGUI is defined, prompts at + the console, otherwise pops up a dialog. The user may then break (debug), + ignore, or halt the program. + + The assertion is also posted to the clipboard under Win32. + */ + +/** + @def debugAssertM(exp, msg) + Breaks if the expression is false and displays a message. If G3D_DEBUG_NOGUI + is defined, prompts at the console, otherwise pops up a dialog. The user may + then break (debug), ignore, or halt the program. + + The assertion is also posted to the clipboard under Win32. + */ + +/** + @def alwaysAssertM(exp, msg) + Same as debugAssertM except that it asserts in release builds as well. + */ + +namespace G3D { +typedef bool (*AssertionHook)( + const char* _expression, + const std::string& message, + const char* filename, + int lineNumber, + bool useGuiPrompt); + +/** + Allows customization of the global function invoked when a debugAssert fails. + The initial value is G3D::_internal::_handleDebugAssert_. G3D will invoke + rawBreak if the hook returns true. If NULL, assertions are not handled. +*/ +void setAssertionHook(AssertionHook hook); + +AssertionHook assertionHook(); + +/** + Called by alwaysAssertM in case of failure in release mode. If returns + true then the program exits with -1 (you can replace this with your own + version that throws an exception or has other failure modes). + */ +void setFailureHook(AssertionHook hook); +AssertionHook failureHook(); + +namespace _internal { + extern AssertionHook _debugHook; + extern AssertionHook _failureHook; +} // internal +} // G3D + +/** + @def __debugPromptShowDialog__ + @internal + */ + +#ifdef G3D_DEBUG + +# if defined(_MSC_VER) +# define rawBreak() ::DebugBreak(); +# elif defined(__i386__) + // gcc on intel +# define rawBreak() __asm__ __volatile__ ( "int $3" ); +# else + // some other gcc +# define rawBreak() ::abort() +# endif + + +# define debugBreak() G3D::_internal::_releaseInputGrab_(); rawBreak(); G3D::_internal::_restoreInputGrab_(); +# define debugAssert(exp) debugAssertM(exp, "Debug assertion failure") + + #ifdef G3D_DEBUG_NOGUI + #define __debugPromptShowDialog__ false + #else + #define __debugPromptShowDialog__ true + #endif + + #define debugAssertM(exp, message) do { \ + if (!(exp)) { \ + G3D::_internal::_releaseInputGrab_(); \ + if ((G3D::_internal::_debugHook != NULL) && \ + G3D::_internal::_debugHook((const char*)(#exp), message, __FILE__, __LINE__, __debugPromptShowDialog__)) { \ + rawBreak(); \ + } \ + G3D::_internal::_restoreInputGrab_(); \ + } \ + } while (0) + + #define alwaysAssertM debugAssertM + +#else // Release + #ifdef G3D_DEBUG_NOGUI + #define __debugPromptShowDialog__ false + #else + #define __debugPromptShowDialog__ true + #endif + + // In the release build, just define away assertions. + #define rawBreak() do {} while (0) + #define debugAssert(exp) do {} while (0) + #define debugAssertM(exp, message) do {} while (0) + #define debugBreak() do {} while (0) + + // But keep the 'always' assertions + #define alwaysAssertM(exp, message) { \ + if (!(exp)) { \ + G3D::_internal::_releaseInputGrab_(); \ + if ((G3D::_internal::_failureHook != NULL) && \ + G3D::_internal::_failureHook(#exp, message, __FILE__, __LINE__, __debugPromptShowDialog__)) { \ + ::exit(-1); \ + } \ + G3D::_internal::_restoreInputGrab_(); \ + } \ + } + +#endif // if debug + + + +namespace G3D { namespace _internal { + +#ifdef G3D_LINUX +#if SOMEONE_MADE_THIS_USEFUL + /** + A pointer to the X11 display. Initially NULL. If set to a + non-null value (e.g. by SDLWindow), debugAssert attempts to use + this display to release the mouse/input grab when an assertion + fails. + */ + extern Display* x11Display; + + /** + A pointer to the X11 window. Initially NULL. If set to a + non-null value (e.g. by SDLWindow), debugAssert attempts to use + this window to release the mouse/input grab when an assertion + fails. + */ + extern Window x11Window; +#endif +#endif + +/** + Pops up an assertion dialog or prints an assertion + + ignoreAlways - return result of pressing the ignore button. + useGuiPrompt - if true, shows a dialog + */ +bool _handleDebugAssert_( + const char* expression, + const std::string& message, + const char* filename, + int lineNumber, + bool useGuiPrompt); + +bool _handleErrorCheck_( + const char* expression, + const std::string& message, + const char* filename, + int lineNumber, + bool useGuiPrompt); + +/** Attempts to give the user back their mouse and keyboard if they + were locked to the current window. + @internal*/ +void _releaseInputGrab_(); + +/** Attempts to restore the state before _releaseInputGrab_. + @internal*/ +void _restoreInputGrab_(); + +}; }; // namespace + +#endif diff --git a/dep/g3dlite/G3D/debugPrintf.h b/dep/g3dlite/G3D/debugPrintf.h new file mode 100644 index 00000000000..b42151cae9e --- /dev/null +++ b/dep/g3dlite/G3D/debugPrintf.h @@ -0,0 +1,62 @@ +/** + @file debugPrintf.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2001-08-26 + @edited 2007-07-20 + + Copyright 2000-2007, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_DEBUGPRINTF_H +#define G3D_DEBUGPRINTF_H + +#include "G3D/platform.h" +#include +#include +#include "G3D/format.h" +#include + +namespace G3D { + +typedef void (*ConsolePrintHook)(const std::string&); + +namespace _internal { + extern ConsolePrintHook _consolePrintHook; +} + +/** Called by consolePrintf after the log and terminal have been written to. + Used by GConsole to intercept printing routines.*/ +void setConsolePrintHook(ConsolePrintHook h); + +ConsolePrintHook consolePrintHook(); + +/** + Sends output to the log and to the last GConsole instantiated. + + Guarantees that the output has been flushed by the time the routine + returns. + @sa G3D::logPrintf, G3D::screenPrintf + @return The string that was printed + */ +std::string __cdecl consolePrintf(const char* fmt ...) G3D_CHECK_PRINTF_ARGS; +std::string consolePrint(const std::string&); + +/** + Under visual studio, appears in the VS debug pane. + On unix-based operating systems the output is sent to stderr. + + Also sends output to the console (G3D::consolePrintf) if there is a consolePrintHook, + and log (G3D::logPrintf), and flushes before returning. + + @return The string that was printed +*/ +std::string __cdecl debugPrintf(const char* fmt ...) G3D_CHECK_PRINTF_ARGS; +std::string debugPrint(const std::string&); + +} // namespace G3D + +#endif + diff --git a/dep/g3dlite/G3D/enumclass.h b/dep/g3dlite/G3D/enumclass.h new file mode 100644 index 00000000000..c7dfe45f14f --- /dev/null +++ b/dep/g3dlite/G3D/enumclass.h @@ -0,0 +1,147 @@ +/** + @file G3D/enumclass.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + @created 2007-01-27 + @edited 2007-07-20 +*/ +#ifndef G3D_enumclass_h +#define G3D_enumclass_h + +#include "G3D/HashTrait.h" +#include "G3D/BinaryInput.h" +#include "G3D/BinaryOutput.h" + +/** +\def G3D_DECLARE_ENUM_CLASS_METHODS + + \brief Creates a series of methods that turn a class into a scoped enumeration. + + Uses the "Intelligent Enum" design pattern + http://www.codeguru.com/cpp/cpp/cpp_mfc/article.php/c4001/ + + Enum classes are initialized to their zero value by default. + + See GLG3D/GKey.h for an example. + \sa G3D_DECLARE_ENUM_CLASS_HASHCODE + */ +#define G3D_DECLARE_ENUM_CLASS_METHODS(Classname)\ + inline Classname(char v) : value((Value)v) {}\ +\ + inline Classname() : value((Value)0) {}\ +\ + inline Classname(const Value v) : value(v) {}\ +\ + explicit inline Classname(int v) : value((Value)v) {}\ +\ + /** Support cast back to the Value type, which is needed to allow implicit assignment inside unions. */\ + /*inline operator Value() const { + return value; + }*/\ +\ + inline operator int() const {\ + return (int)value;\ + }\ +\ + inline bool operator== (const Classname other) const {\ + return value == other.value;\ + }\ +\ + inline bool operator== (const Classname::Value other) const {\ + return value == other;\ + }\ +\ + inline bool operator!= (const Classname other) const {\ + return value != other.value;\ + }\ +\ + inline bool operator!= (const Classname::Value other) const {\ + return value != other;\ + }\ +\ + inline bool operator< (const Classname other) const {\ + return value < other.value;\ + }\ +\ + inline bool operator> (const Classname other) const {\ + return value > other.value;\ + }\ +\ + inline bool operator>= (const Classname other) const {\ + return value >= other.value;\ + }\ +\ + inline bool operator<= (const Classname other) const {\ + return value <= other.value;\ + }\ +\ + inline bool operator< (const Value other) const {\ + return value < other;\ + }\ +\ + inline bool operator> (const Value other) const {\ + return value > other;\ + }\ +\ + inline bool operator<= (const Value other) const {\ + return value <= other;\ + }\ +\ + inline bool operator>= (const Value other) const {\ + return value >= other;\ + }\ +\ + inline Classname& operator-- () {\ + value = (Value)((int)value - 1);\ + return *this;\ + }\ +\ + inline Classname& operator++ () {\ + value = (Value)((int)value + 1);\ + return *this;\ + }\ +\ + inline Classname& operator+= (const int x) {\ + value = (Value)((int)value + x);\ + return *this;\ + }\ +\ + inline Classname& operator-= (const int x) {\ + value = (Value)((int)value - x);\ + return *this;\ + }\ +\ + inline Classname operator+ (const int x) const {\ + return Classname((int)value + x);\ + }\ +\ + inline Classname operator- (const int x) const {\ + return Classname((int)value - x);\ + }\ +\ + inline unsigned int hashCode() const {\ + return (unsigned int)value;\ + }\ +\ + inline void serialize(BinaryOutput& b) const {\ + b.writeInt32(value);\ + }\ +\ + inline void deserialize(BinaryInput& b) {\ + value = (Value)b.readInt32();\ + } + +/** \def G3D_DECLARE_ENUM_CLASS_HASHCODE +*/ +#define G3D_DECLARE_ENUM_CLASS_HASHCODE(Classname)\ +template <> struct HashTrait \ +{ \ + static size_t hashCode(Classname::Value key) { return static_cast(key); } \ +}; \ + \ +template <> struct HashTrait \ +{ \ + static size_t hashCode(Classname key) { return static_cast(key.hashCode()); } \ +}; + +#endif diff --git a/dep/g3dlite/G3D/fileutils.h b/dep/g3dlite/G3D/fileutils.h new file mode 100644 index 00000000000..9e49777d93a --- /dev/null +++ b/dep/g3dlite/G3D/fileutils.h @@ -0,0 +1,254 @@ +/** + @file fileutils.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @author 2002-06-06 + @edited 2010-02-06 + + Copyright 2000-2010, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_fileUtils_h +#define G3D_fileUtils_h + +#include "G3D/platform.h" +#include +#include +#include "G3D/Array.h" +#include "G3D/Set.h" +#include "G3D/g3dmath.h" + +#ifdef G3D_WIN32 +// For chdir, mkdir, etc. +# include +#endif + +namespace G3D { + + namespace _internal { + extern Set currentFilesUsed; + } + +/** Returns all the files used by G3D and GLG3D during the current execution. */ +Array filesUsed(); + +std::string readWholeFile( + const std::string& filename); + + +/** Reads from a zip file and decompresses the desired contents + into memory. Does not support recursive zip calls (i.e. a .zip + stored within another .zip) + + @param file the path, of the format C:\\...\\something.zip\\...\\desiredfile.ext + @param data a pointer to the memory where the file will be stored + @param length the size of the file decompressed to memory */ +void zipRead(const std::string& file, + void*& data, + size_t& length); + + +/** Closes the contents of a zip file that had been decompressed to + memory. Must be called in tandem with zipRead() to avoid memory + leaks. + + @param data the pointer to the decompressed file in memory */ +void zipClose(void* data); + + +/** + @param flush If true (default), the file is ready for reading as soon + as the function returns. If false, the function returns immediately and + writes the file in the background. + */ +void writeWholeFile( + const std::string& filename, + const std::string& str, + bool flush = true); + +/** + Creates the directory (which may optionally end in a /) + and any parents needed to reach it. + */ +void createDirectory( + const std::string& dir); + +/** + Fully qualifies a filename. The filename may contain wildcards, + in which case the wildcards will be preserved in the returned value. + */ +std::string resolveFilename(const std::string& filename); + +/** + Appends all files matching filespec to the files array. The names + will not contain paths unless includePath == true. These may be + relative to the current directory unless the filespec is fully qualified + (can be done with resolveFilename). + Wildcards can only appear to the right of the last slash in filespec. + Works with .zip files used as paths, if filespec is passed in the form + C:\\...\\something.zip\\* Does not work recursively with zipfiles (a + .zip within a .zip will not work) + */ +void getFiles( + const std::string& filespec, + Array& files, + bool includePath = false); + +/** + Appends all directories matching filespec to the files array. The names + will not contain paths unless includePath == true. These may be + relative to the current directory unless the filespec is fully qualified + (can be done with resolveFilename). + Does not append special directories "." or "..". + Works with .zip files used as paths, if filespec is passed in the form + C:\\...\\something.zip\\* Does not work recursively with zipfiles (a + .zip within a .zip will not work) + */ +void getDirs( + const std::string& filespec, + Array& files, + bool includePath = false); + + +/** Returns true if the specified path exists and is a directory */ +bool isDirectory(const std::string& filespec); + + +/** Returns true if the specified filename exists and is a zipfile */ +bool isZipfile(const std::string& filename); + + +/** Returns the length of the file. If + filename specifies a path that contains a zipfile, but the + contents within are specified correctly, returns the + uncompressed size of the requested file. Returns -1 if + the file does not exist. + + @param filename the path to test, may contain .zip +*/ +int64 fileLength(const std::string& filename); + +/** + Copies the file + */ +void copyFile( + const std::string& source, + const std::string& dest); + +/** Returns a temporary file that is open for read/write access. This + tries harder than the ANSI tmpfile, so it may succeed when that fails. */ +FILE* createTempFile(); + +/** + Returns true if the given file (or directory) exists. + + \param filename the path to test. must not end in a trailing slash. + \param lookInZipfiles if the path does not exist, calls zipfileExists() + \param trustCache If true and \a lookInZipfiles is true, cache directory and zipfile contents + so that subsequent calls to the same directory are fast. + + \sa G3D::clearFileSystemCache, G3D::zipfileExists + */ +bool fileExists +(const std::string& filename, + bool lookInZipfiles = true, + bool trustCache = true); + + +/** Clears the cache used by fileExists */ +void clearFileSystemCache(); + +/** + Returns true if the given file (or directory) exists + within a zipfile. Called if fileExists initially + returns false and the lookInZipfiles flag has been set. + Must not end in a trailing slash. Does not work for recursive + zipfiles (.zips within another .zip) + + @param filename the path to test + @param outZipfile the path to the .zip file + @param outInternalFile the path (within the .zip) where the desired file is located, if valid + + */ +bool zipfileExists +(const std::string& filename, + std::string& outZipfile, + std::string& outInternalFile); + +bool zipfileExists(const std::string& filename); + +/** + Parses a filename into four useful pieces. + + Examples: + + c:\\a\\b\\d.e + root = "c:\\" + path = "a" "b" + base = "d" + ext = "e" + + /a/b/d.e + root = "/" + path = "a" "b" + base = "d" + ext = "e" + + /a/b + root = "/" + path = "a" + base = "b" + ext = "e" + + */ +void parseFilename( + const std::string& filename, + std::string& drive, + Array& path, + std::string& base, + std::string& ext); + + +/** + Returns the part of the filename that includes the base and ext from + parseFilename (i.e. everything to the right of the path). + */ +std::string filenameBaseExt(const std::string& filename); + +/** + Returns the extension on a filename. + */ +std::string filenameExt(const std::string& filename); + + +/** Returns the portion of a filename to the left of the last period + and to the right of the last slash or colon. + */ +std::string filenameBase(const std::string& filename); + +/** Creates a unique filename base in the current directory using the + specified prefix and suffix.*/ +std::string generateFilenameBase(const std::string& prefix = "", const std::string& suffix = ""); + +/** + Returns the drive (if Win32) and path from a filename, including + a slash if there was one. + filenamePath(f) + filenameBaseExt(f) == f + */ +std::string filenamePath(const std::string& filename); + +/** Returns true if '*' or '?' appears in the string */ +bool filenameContainsWildcards(const std::string& filename); + +/** Returns true if dst does not exist or src is newer than dst. Works on both files and directories. */ +bool fileIsNewer(const std::string& src, const std::string& dst); + +/** Appends file onto dirname, ensuring a / if needed. */ +std::string pathConcat(const std::string& dirname, const std::string& file); + +} // namespace + +#endif + diff --git a/dep/g3dlite/G3D/filter.h b/dep/g3dlite/G3D/filter.h new file mode 100644 index 00000000000..609477b79c9 --- /dev/null +++ b/dep/g3dlite/G3D/filter.h @@ -0,0 +1,29 @@ +/** + @file G3D/filter.h + + @author Morgan McGuire, http://graphics.cs.williams.edu + @created 2007-03-01 + @edited 2007-03-01 + + Copyright 2000-2007, Morgan McGuire. + All rights reserved. + */ +#ifndef G3D_FILTER_H +#define G3D_FILTER_H + +#include "G3D/platform.h" +#include "G3D/Array.h" +#include "G3D/g3dmath.h" + +namespace G3D { +/** + Generates a set of 1D gaussian filter coefficients of size N. The coefficients + are centered on element (N-1)/2 and have standard deviation given by std. The coefficients + are normalized such that the sum across coeff is 1.0. + + Matches the results returned by Matlab fspecial('gaussian', [1, N], std) + */ +void gaussian1D(Array& coeff, int N = 5, float std = 0.5f); +} + +#endif diff --git a/dep/g3dlite/G3D/format.h b/dep/g3dlite/G3D/format.h new file mode 100644 index 00000000000..3c7f0678876 --- /dev/null +++ b/dep/g3dlite/G3D/format.h @@ -0,0 +1,44 @@ +/** + @file format.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @author 2000-09-09 + @edited 2005-11-03 + + Copyright 2000-2005, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_FORMAT_H +#define G3D_FORMAT_H + +#include "G3D/platform.h" +#include +#include +#include + +namespace G3D { + +/** + Produces a string from arguments of the style of printf. This avoids + problems with buffer overflows when using sprintf and makes it easy + to use the result functionally. This function is fast when the resulting + string is under 160 characters (not including terminator) and slower + when the string is longer. + */ +std::string __cdecl format( + const char* fmt + ...) G3D_CHECK_PRINTF_ARGS; + +/** + Like format, but can be called with the argument list from a ... function. + */ +std::string vformat( + const char* fmt, + va_list argPtr) G3D_CHECK_VPRINTF_ARGS; + + +} // namespace + +#endif diff --git a/dep/g3dlite/G3D/g3dfnmatch.h b/dep/g3dlite/G3D/g3dfnmatch.h new file mode 100644 index 00000000000..464b3927eee --- /dev/null +++ b/dep/g3dlite/G3D/g3dfnmatch.h @@ -0,0 +1,83 @@ +/*- + * Copyright (c) 1992, 1993 + *The Regents of the University of California. 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + *This product includes software developed by the University of + *California, Berkeley and its contributors. + * 4. Neither the name of the University 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 REGENTS 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 REGENTS 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. + * + *@(#)fnmatch.h8.1 (Berkeley) 6/2/93 + * + * From FreeBSD fnmatch.h 1.7 + * $Id: g3dfnmatch.h,v 1.1 2010/02/06 06:51:28 morgan3d Exp $ + */ +#ifndef G3D_g3dfnmatch_h +#define G3D_g3dfnmatch_h + +#include "G3D/platform.h" + +namespace G3D { + +#if defined(G3D_WIN32) + +# if ! defined(FNM_NOMATCH) +# define FNM_NOMATCH 1 /* Match failed. */ +# define FNM_NOESCAPE 0x01 /* Disable backslash escaping. */ +# define FNM_PATHNAME 0x02 /* Slash must be matched by slash. */ +# define FNM_PERIOD 0x04 /* Period must be matched by period. */ +# define FNM_LEADING_DIR 0x08 /* Ignore / after Imatch. */ +# define FNM_CASEFOLD 0x10 /* Case insensitive search. */ +# define FNM_PREFIX_DIRS 0x20 /* Directory prefixes of pattern match too. */ +# endif + +#else + + // On non-windows systems, include fnmatch directly +# include +#endif + + +/** + Function fnmatch() as specified in POSIX 1003.2-1992, section B.6. + Compares a filename or pathname to a pattern. + +The fnmatch() function checks whether the string argument matches the pattern argument, which is a shell wildcard pattern. +The flags argument modifies the behaviour; it is the bitwise OR of zero or more of the following flags: + +- FNM_NOESCAPE If this flag is set, treat backslash as an ordinary character, instead of an escape character. +- FNM_PATHNAME If this flag is set, match a slash in string only with a slash in pattern and not by an asterisk (*) or a question mark (?) metacharacter, nor by a bracket expression ([]) containing a slash. +- FNM_PERIOD If this flag is set, a leading period in string has to be matched exactly by a period in pattern. A period is considered to be leading if it is the first character in string, or if both FNM_PATHNAME is set and the period immediately follows a slash. +- FNM_FILE_NAME This is a GNU synonym for FNM_PATHNAME. +- FNM_LEADING_DIR If this flag (a GNU extension) is set, the pattern is considered to be matched if it matches an initial segment of string which is followed by a slash. This flag is mainly for the internal use of glibc and is only implemented in certain cases. +- FNM_CASEFOLD If this flag (a GNU extension) is set, the pattern is matched case-insensitively. + +\return Zero if \a string matches \a pattern, FNM_NOMATCH if there is no match or another non-zero value if there is an error + + */ +int g3dfnmatch(const char *pattern, const char *string, int flags); +} +#endif diff --git a/dep/g3dlite/G3D/g3dmath.h b/dep/g3dlite/G3D/g3dmath.h new file mode 100644 index 00000000000..d16214ebb37 --- /dev/null +++ b/dep/g3dlite/G3D/g3dmath.h @@ -0,0 +1,845 @@ +/** + @file g3dmath.h + + Math util class. + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + @cite highestBit by Jukka Liimatta + + @created 2001-06-02 + @edited 2009-04-07 + + Copyright 2000-2006, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_g3dmath_h +#define G3D_g3dmath_h + +#ifdef _MSC_VER +// Disable conditional expression is constant, which occurs incorrectly on inlined functions +# pragma warning (push) +# pragma warning (disable : 4127) +// disable: "C++ exception handler used" +# pragma warning (disable : 4530) +#endif + +#include "G3D/platform.h" +#include +#include +#include +#include + +#ifdef _MSC_VER + // Visual Studio is missing inttypes.h +# ifndef PRId64 +# define PRId64 "I64d" +# endif +#else +#include +#endif + +/*These defines enable functionality introduced with the 1999 ISO C +**standard. They must be defined before the inclusion of math.h to +**engage them. If optimisation is enabled, these functions will be +**inlined. With optimisation switched off, you have to link in the +**maths library using -lm. +*/ + +#define _ISOC9X_SOURCE1 +#define _ISOC99_SOURCE1 +#define __USE_ISOC9X1 +#define __USE_ISOC991 + +#include + +#include "G3D/debug.h" + +#undef min +#undef max + +namespace G3D { + +#ifdef _MSC_VER +inline double __fastcall drand48() { + return ::rand() / double(RAND_MAX); +} + +#if !defined(_WIN64) + +/** + Win32 implementation of the C99 fast rounding routines. + + @cite routines are + Copyright (C) 2001 Erik de Castro Lopo + + Permission to use, copy, modify, distribute, and sell this file for any + purpose is hereby granted without fee, provided that the above copyright + and this permission notice appear in all copies. No representations are + made about the suitability of this software for any purpose. It is + provided "as is" without express or implied warranty. +*/ + +__inline long int lrint (double flt) { + int intgr; + + _asm { + fld flt + fistp intgr + }; + + return intgr; +} + +__inline long int lrintf(float flt) { + int intgr; + + _asm { + fld flt + fistp intgr + }; + + return intgr; +} + +#else + + __inline long int lrint (double flt) { + return (long int)floor(flt+0.5f); + } + + __inline long int lrintf(float flt) { + return (long int)floorf(flt+0.5f); + } + +#endif + +#endif + + +#define fuzzyEpsilon (0.00001f) +/** + This value should not be tested against directly, instead + G3D::isNan() and G3D::isFinite() will return reliable results. */ +double inf(); + +/** This value should not be tested against directly, instead + G3D::isNan() and G3D::isFinite() will return reliable results. */ +double nan(); + +float finf(); + +float fnan(); + +inline double pi() { + return 3.1415926535898; +} + +inline double halfPi() { + return 1.57079633; +} + +inline double twoPi() { + return 6.28318531; +} + +typedef signed char int8; +typedef unsigned char uint8; +typedef short int16; +typedef unsigned short uint16; +typedef int int32; +typedef unsigned int uint32; + +#ifdef _MSC_EXTENSIONS + typedef __int64 int64; + typedef unsigned __int64 uint64; +#elif ! defined(_MSC_VER) + typedef int64_t int64; + typedef uint64_t uint64; +#else + typedef long long int64; + typedef unsigned long long uint64; +#endif + +typedef float float32; +typedef double float64; + +int iAbs(int iValue); +int iCeil(double fValue); + +/** + Clamps the value to the range [low, hi] (inclusive) + */ +int iClamp(int val, int low, int hi); +int16 iClamp(int16 val, int16 low, int16 hi); +double clamp(double val, double low, double hi); +float clamp(float val, float low, float hi); + +/** + Returns a + (b - a) * f; + */ +inline double lerp(double a, double b, double f) { + return a + (b - a) * f; +} + +inline float lerp(float a, float b, float f) { + return a + (b - a) * f; +} + +/** + Wraps the value to the range [0, hi) (exclusive + on the high end). This is like the clock arithmetic + produced by % (modulo) except the result is guaranteed + to be positive. + */ +int iWrap(int val, int hi); + +int iFloor(double fValue); + +int iSign(int iValue); +int iSign(double fValue); + +inline int iSign(float f) { + return iSign((double)f); +} + + +/** + Fast round to integer using the lrint routine. + Typically 6x faster than casting to integer. + */ +inline int iRound(double fValue) { + return lrint(fValue); +} + +/** + Fast round to integer using the lrint routine. + Typically 6x faster than casting to integer. + */ +inline int iRound(float f) { + return lrintf(f); +} + +/** + Returns a random number uniformly at random between low and hi + (inclusive). + @deprecated Use Random::integer + */ +int iRandom(int low, int hi); + +double abs (double fValue); +double aCos (double fValue); +double aSin (double fValue); +double aTan (double fValue); +double aTan2 (double fY, double fX); +double sign (double fValue); +double square (double fValue); + +/** + Returns true if the argument is a finite real number. + */ +bool isFinite(double x); + +/** + Returns true if the argument is NaN (not a number). + You can't use x == nan to test this because all + comparisons against nan return false. + */ +bool isNaN(double x); +bool isNaN(float x); +inline bool isNaN(int x) { + (void)x; + return false; +} + +/** + Computes x % 3. + */ +int iMod3(int x); + +/** + Uniform random number between low and hi, inclusive. [low, hi] + @deprecated + @sa Random::uniform + */ +float uniformRandom(float low = 0.0f, float hi = 1.0f); + +/** + Normally distributed random number. + + @deprecated + @sa Random::gaussian + */ +float gaussRandom(float mean = 0.0f, float stdev = 1.0f); + + +/** Returns x5 */ +template +inline T pow5(T x) { + const T y = x * x; + return y * y * x; +} + + +template +inline T min(const T& x, const T& y) { + return std::min(x, y); +} + +template +inline T min(const T& x, const T& y, const T& z) { + return std::min(std::min(x, y), z); +} + +template +inline T min(const T& x, const T& y, const T& z, const T& w) { + return std::min(std::min(x, y), std::min(z, w)); +} + +template +inline T max(const T& x, const T& y) { + return std::max(x, y); +} + +template +inline T max(const T& x, const T& y, const T& z) { + return std::max(std::max(x, y), z); +} + +template +inline T max(const T& x, const T& y, const T& z, const T& w) { + return std::max(std::max(x, y), std::max(z, w)); +} + +int iMin(int x, int y); +int iMax(int x, int y); + +double square(double x); +double sumSquares(double x, double y); +double sumSquares(double x, double y, double z); +double distance(double x, double y); +double distance(double x, double y, double z); + +/** + Returnes the 0-based index of the highest 1 bit from + the left. -1 means the number was 0. + + @cite Based on code by jukka@liimatta.org + */ +int highestBit(uint32 x); + +/** + Note that fuzzyEq(a, b) && fuzzyEq(b, c) does not imply + fuzzyEq(a, c), although that will be the case on some + occasions. + */ +bool fuzzyEq(double a, double b); + +/** True if a is definitely not equal to b. + Guaranteed false if a == b. + Possibly false when a != b.*/ +bool fuzzyNe(double a, double b); + +/** Is a strictly greater than b? (Guaranteed false if a <= b). + (Possibly false if a > b) */ +bool fuzzyGt(double a, double b); + +/** Is a near or greater than b? */ +bool fuzzyGe(double a, double b); + +/** Is a strictly less than b? (Guaranteed false if a >= b)*/ +bool fuzzyLt(double a, double b); + +/** Is a near or less than b? */ +bool fuzzyLe(double a, double b); + +/** + Computes 1 / sqrt(x). + */ +inline float rsq(float x) { + return 1.0f / sqrtf(x); +} + +/** + Return the next power of 2 higher than the input + If the input is already a power of 2, the output will be the same + as the input. + */ +int ceilPow2(unsigned int in); + +/** Returns 2^x */ +inline int pow2(unsigned int x) { + return 1 << x; +} + +inline double log2(double x) { + return ::log(x) * 1.442695; +} + +inline float log2(float x) { + return ::logf(x) * 1.442695f; +} + +inline double log2(int x) { + return log2((double)x); +} + + +/** + * True if num is a power of two. + */ +bool isPow2(int num); + +bool isOdd(int num); +bool isEven(int num); + +double toRadians(double deg); +double toDegrees(double rad); + +/** + Returns true if x is not exactly equal to 0.0f. + */ +inline bool any(float x) { + return x != 0; +} + +/** + Returns true if x is not exactly equal to 0.0f. + */ +inline bool all(float x) { + return x != 0; +} + +/** + v / v (for DirectX/Cg support) + */ +inline float normalize(float v) { + return v / v; +} + +/** + a * b (for DirectX/Cg support) + */ +inline float dot(float a, float b) { + return a * b; +} + + +/** + a * b (for DirectX/Cg support) + */ +inline float mul(float a, float b) { + return a * b; +} + +/** + 2^x + */ +inline double exp2(double x) { + return pow(2.0, x); +} + +inline float exp2(float x) { + return powf(2.0f, x); +} + +/** @deprecated Use rsq */ +inline double rsqrt(double x) { + return 1.0 / sqrt(x); +} + +/** @deprecated Use rsq */ +inline float rsqrt(float x) { + // TODO: default this to using the SSE2 instruction + return 1.0 / sqrtf(x); +} + +/** + sin(x)/x + */ +inline double sinc(double x) { + double r = sin(x) / x; + + if (isNaN(r)) { + return 1.0; + } else { + return r; + } +} + +/** + Computes a floating point modulo; the result is t wrapped to the range [lo, hi). + */ +inline float wrap(float t, float lo, float hi) { + if ((t >= lo) && (t < hi)) { + return t; + } + + debugAssert(hi > lo); + + float interval = hi - lo; + + return t - interval * iFloor((t - lo) / interval); +} + + +inline double wrap(double t, double lo, double hi) { + if ((t >= lo) && (t < hi)) { + return t; + } + + debugAssert(hi > lo); + + double interval = hi - lo; + + return t - interval * iFloor((t - lo) / interval); +} + +inline double wrap(double t, double hi) { + return wrap(t, 0.0, hi); +} + + +inline bool isFinite(double x) { + return ! isNaN(x) && (x < G3D::inf()) && (x > -G3D::inf()); +} + +inline bool isFinite(float x) { + return ! isNaN(x) && (x < G3D::finf()) && (x > -G3D::finf()); +} + +//---------------------------------------------------------------------------- +inline int iAbs (int iValue) { + return ( iValue >= 0 ? iValue : -iValue ); +} + +//---------------------------------------------------------------------------- +inline int iCeil (double fValue) { + return int(::ceil(fValue)); +} + +//---------------------------------------------------------------------------- + +inline int iClamp(int val, int low, int hi) { + debugAssert(low <= hi); + if (val <= low) { + return low; + } else if (val >= hi) { + return hi; + } else { + return val; + } +} + +//---------------------------------------------------------------------------- + +inline int16 iClamp(int16 val, int16 low, int16 hi) { + debugAssert(low <= hi); + if (val <= low) { + return low; + } else if (val >= hi) { + return hi; + } else { + return val; + } +} + +//---------------------------------------------------------------------------- + +inline double clamp(double val, double low, double hi) { + debugAssert(low <= hi); + if (val <= low) { + return low; + } else if (val >= hi) { + return hi; + } else { + return val; + } +} + +inline float clamp(float val, float low, float hi) { + debugAssert(low <= hi); + if (val <= low) { + return low; + } else if (val >= hi) { + return hi; + } else { + return val; + } +} +//---------------------------------------------------------------------------- + +inline int iWrap(int val, int hi) { + if (val < 0) { + return ((val % hi) + hi) % hi; + } else { + return val % hi; + } +} + +//---------------------------------------------------------------------------- +inline int iFloor (double fValue) { + return int(::floor(fValue)); +} + +//---------------------------------------------------------------------------- +inline int iSign (int iValue) { + return ( iValue > 0 ? + 1 : ( iValue < 0 ? -1 : 0 ) ); +} + +inline int iSign (double fValue) { + return ( fValue > 0.0 ? + 1 : ( fValue < 0.0 ? -1 : 0 ) ); +} + +//---------------------------------------------------------------------------- +inline double abs (double fValue) { + return double(::fabs(fValue)); +} + +//---------------------------------------------------------------------------- +inline double aCos (double fValue) { + if ( -1.0 < fValue ) { + if ( fValue < 1.0 ) + return double(::acos(fValue)); + else + return 0.0; + } else { + return pi(); + } +} + +//---------------------------------------------------------------------------- +inline double aSin (double fValue) { + if ( -1.0 < fValue ) { + if ( fValue < 1.0 ) { + return double(::asin(fValue)); + } else { + return -halfPi(); + } + } else { + return halfPi(); + } +} + +//---------------------------------------------------------------------------- +inline double aTan (double fValue) { + return double(::atan(fValue)); +} + +//---------------------------------------------------------------------------- +inline double aTan2 (double fY, double fX) { + return double(::atan2(fY, fX)); +} + +//---------------------------------------------------------------------------- +inline double sign (double fValue) { + if (fValue > 0.0) { + return 1.0; + } + + if (fValue < 0.0) { + return -1.0; + } + + return 0.0; +} + +inline float sign (float fValue) { + if (fValue > 0.0f) { + return 1.0f; + } + + if (fValue < 0.0f) { + return -1.0f; + } + + return 0.0f; +} + + +inline float uniformRandom(float low, float hi) { + return (hi - low) * float(::rand()) / float(RAND_MAX) + low; +} + +inline double square(double x) { + return x * x; +} + +inline float square(float x) { + return x * x; +} + +inline int square(int x) { + return x * x; +} + +//---------------------------------------------------------------------------- +inline double sumSquares(double x, double y) { + return x*x + y*y; +} + +//---------------------------------------------------------------------------- +inline float sumSquares(float x, float y) { + return x*x + y*y; +} + +//---------------------------------------------------------------------------- +inline double sumSquares(double x, double y, double z) { + return x*x + y*y + z*z; +} + +//---------------------------------------------------------------------------- +inline float sumSquares(float x, float y, float z) { + return x*x + y*y + z*z; +} + +//---------------------------------------------------------------------------- +inline double distance(double x, double y) { + return sqrt(sumSquares(x, y)); +} + +//---------------------------------------------------------------------------- +inline float distance(float x, float y) { + return sqrt(sumSquares(x, y)); +} + +//---------------------------------------------------------------------------- +inline double distance(double x, double y, double z) { + return sqrt(sumSquares(x, y, z)); +} + +//---------------------------------------------------------------------------- +inline float distance(float x, float y, float z) { + return sqrt(sumSquares(x, y, z)); +} + +//---------------------------------------------------------------------------- + +/** @deprecated use G3D::min */ +inline int iMin(int x, int y) { + return (x >= y) ? y : x; +} + +//---------------------------------------------------------------------------- +/** @deprecated use G3D::min */ +inline int iMax(int x, int y) { + return (x >= y) ? x : y; +} + +//---------------------------------------------------------------------------- +inline int ceilPow2(unsigned int in) { + in -= 1; + + in |= in >> 16; + in |= in >> 8; + in |= in >> 4; + in |= in >> 2; + in |= in >> 1; + + return in + 1; +} + +inline bool isPow2(int num) { + return ((num & -num) == num); +} + +inline bool isOdd(int num) { + return (num & 1) == 1; +} + +inline bool isEven(int num) { + return (num & 1) == 0; +} + +inline double toRadians(double deg) { + return deg * pi() / 180.0; +} + +inline double toDegrees(double rad) { + return rad * 180.0 / pi(); +} + +inline float toRadians(float deg) { + return deg * (float)pi() / 180.0f; +} + +inline float toDegrees(float rad) { + return rad * 180.0f / (float)pi(); +} + +inline float toRadians(int deg) { + return deg * (float)pi() / 180.0f; +} + +inline float toDegrees(int rad) { + return rad * 180.0f / (float)pi(); +} +/** + Computes an appropriate epsilon for comparing a and b. + */ +inline double eps(double a, double b) { + // For a and b to be nearly equal, they must have nearly + // the same magnitude. This means that we can ignore b + // since it either has the same magnitude or the comparison + // will fail anyway. + (void)b; + const double aa = abs(a) + 1.0; + if (aa == inf()) { + return fuzzyEpsilon; + } else { + return fuzzyEpsilon * aa; + } +} + +inline bool fuzzyEq(double a, double b) { + return (a == b) || (abs(a - b) <= eps(a, b)); +} + +inline bool fuzzyNe(double a, double b) { + return ! fuzzyEq(a, b); +} + +inline bool fuzzyGt(double a, double b) { + return a > b + eps(a, b); +} + +inline bool fuzzyGe(double a, double b) { + return a > b - eps(a, b); +} + +inline bool fuzzyLt(double a, double b) { + return a < b - eps(a, b); +} + +inline bool fuzzyLe(double a, double b) { + return a < b + eps(a, b); +} + +inline int iMod3(int x) { + return x % 3; +} + +/** + Given a 32-bit integer, returns the integer with the bytes in the opposite order. + */ +inline uint32 flipEndian32(const uint32 x) { + return (x << 24) | ((x & 0xFF00) << 8) | + ((x & 0xFF0000) >> 8) | ((x & 0xFF000000) >> 24); +} + +/** + Given a 16-bit integer, returns the integer with the bytes in the opposite order. + */ +inline uint16 flipEndian16(const uint16 x) { + return (x << 8) | ((x & 0xFF00) >> 8); +} + + +} // namespace + +#ifdef _MSC_VER +# pragma warning (pop) +#endif + +#endif + diff --git a/dep/g3dlite/G3D/g3dmath.inl b/dep/g3dlite/G3D/g3dmath.inl new file mode 100644 index 00000000000..9bf661a7ebc --- /dev/null +++ b/dep/g3dlite/G3D/g3dmath.inl @@ -0,0 +1,288 @@ +/** + @file g3dmath.inl + + @maintainer Morgan McGuire, matrix@graphics3d.com + + @created 2001-06-02 + @edited 2006-01-14 + */ + +#include + +#ifdef _MSC_VER +// Disable conditional expression is constant, which occurs incorrectly on inlined functions +# pragma warning (push) +# pragma warning( disable : 4127 ) +#endif + +namespace G3D { + +inline bool isNaN(double x) { + bool b1 = (x < 0.0); + bool b2 = (x >= 0.0); + bool b3 = !(b1 || b2); + return b3; +} + +inline bool isFinite(double x) { + return ! isNaN(x) && (x < G3D::inf()) && (x > -G3D::inf()); +} + +//---------------------------------------------------------------------------- +inline int iAbs (int iValue) { + return ( iValue >= 0 ? iValue : -iValue ); +} + +//---------------------------------------------------------------------------- +inline int iCeil (double fValue) { + return int(::ceil(fValue)); +} + +//---------------------------------------------------------------------------- + +inline int iClamp(int val, int low, int hi) { + debugAssert(low <= hi); + if (val <= low) { + return low; + } else if (val >= hi) { + return hi; + } else { + return val; + } +} + +//---------------------------------------------------------------------------- + +inline double clamp(double val, double low, double hi) { + debugAssert(low <= hi); + if (val <= low) { + return low; + } else if (val >= hi) { + return hi; + } else { + return val; + } +} + +inline float clamp(float val, float low, float hi) { + debugAssert(low <= hi); + if (val <= low) { + return low; + } else if (val >= hi) { + return hi; + } else { + return val; + } +} +//---------------------------------------------------------------------------- + +inline int iWrap(int val, int hi) { + if (val < 0) { + return ((val % hi) + hi) % hi; + } else { + return val % hi; + } +} + +//---------------------------------------------------------------------------- +inline int iFloor (double fValue) { + return int(::floor(fValue)); +} + +//---------------------------------------------------------------------------- +inline int iSign (int iValue) { + return ( iValue > 0 ? + 1 : ( iValue < 0 ? -1 : 0 ) ); +} + +inline int iSign (double fValue) { + return ( fValue > 0.0 ? + 1 : ( fValue < 0.0 ? -1 : 0 ) ); +} + +//---------------------------------------------------------------------------- +inline double abs (double fValue) { + return double(::fabs(fValue)); +} + +//---------------------------------------------------------------------------- +inline double aCos (double fValue) { + if ( -1.0 < fValue ) { + if ( fValue < 1.0 ) + return double(::acos(fValue)); + else + return 0.0; + } else { + return G3D_PI; + } +} + +//---------------------------------------------------------------------------- +inline double aSin (double fValue) { + if ( -1.0 < fValue ) { + if ( fValue < 1.0 ) { + return double(::asin(fValue)); + } else { + return -G3D_HALF_PI; + } + } else { + return G3D_HALF_PI; + } +} + +//---------------------------------------------------------------------------- +inline double aTan (double fValue) { + return double(::atan(fValue)); +} + +//---------------------------------------------------------------------------- +inline double aTan2 (double fY, double fX) { + return double(::atan2(fY, fX)); +} + +//---------------------------------------------------------------------------- +inline double sign (double fValue) { + if (fValue > 0.0) { + return 1.0; + } + + if (fValue < 0.0) { + return -1.0; + } + + return 0.0; +} + +inline double G3D_DEPRECATED unitRandom () { + return double(::rand()) / double(RAND_MAX); +} + +inline float uniformRandom(float low, float hi) { + return (hi - low) * float(::rand()) / float(RAND_MAX) + low; +} + +//---------------------------------------------------------------------------- +inline double G3D_DEPRECATED symmetricRandom () { + return 2.0 * double(::rand()) / double(RAND_MAX) - 1.0; +} + +//---------------------------------------------------------------------------- +inline double square(double x) { + return x * x; +} + +//---------------------------------------------------------------------------- +inline double sumSquares(double x, double y) { + return x*x + y*y; +} + +//---------------------------------------------------------------------------- +inline double sumSquares(double x, double y, double z) { + return x*x + y*y + z*z; +} + +//---------------------------------------------------------------------------- +inline double distance(double x, double y) { + return sqrt(sumSquares(x, y)); +} + +//---------------------------------------------------------------------------- +inline double distance(double x, double y, double z) { + return sqrt(sumSquares(x, y, z)); +} + +//---------------------------------------------------------------------------- + +/** @deprecated use G3D::min */ +inline int iMin(int x, int y) { + return (x >= y) ? y : x; +} + +//---------------------------------------------------------------------------- +/** @deprecated use G3D::min */ +inline int iMax(int x, int y) { + return (x >= y) ? x : y; +} + +//---------------------------------------------------------------------------- +inline int ceilPow2(unsigned int in) { + in -= 1; + + in |= in >> 16; + in |= in >> 8; + in |= in >> 4; + in |= in >> 2; + in |= in >> 1; + + return in + 1; +} + +inline bool isPow2(int num) { + return ((num & -num) == num); +} + +inline bool isOdd(int num) { + return (num & 1) == 1; +} + +inline bool isEven(int num) { + return (num & 1) == 0; +} + +inline double toRadians(double deg) { + return deg * G3D_PI / 180.0; +} + +inline double toDegrees(double rad) { + return rad * 180.0 / G3D_PI; +} + +/** + Computes an appropriate epsilon for comparing a and b. + */ +inline double eps(double a, double b) { + // For a and b to be nearly equal, they must have nearly + // the same magnitude. This means that we can ignore b + // since it either has the same magnitude or the comparison + // will fail anyway. + (void)b; + const double aa = abs(a) + 1; + if (aa == inf()) { + return fuzzyEpsilon; + } else { + return fuzzyEpsilon * aa; + } +} + +inline bool fuzzyEq(double a, double b) { + return (a == b) || (abs(a - b) <= eps(a, b)); +} + +inline bool fuzzyNe(double a, double b) { + return ! fuzzyEq(a, b); +} + +inline bool fuzzyGt(double a, double b) { + return a > b + eps(a, b); +} + +inline bool fuzzyGe(double a, double b) { + return a > b - eps(a, b); +} + +inline bool fuzzyLt(double a, double b) { + return a < b - eps(a, b); +} + +inline bool fuzzyLe(double a, double b) { + return a < b + eps(a, b); +} + +inline int iMod3(int x) { + return x % 3; +} + +} // namespace G3D + +#ifdef _MSC_VER +// Disable conditional expression is constant, which occurs incorrectly on inlined functions +# pragma warning (pop) +#endif diff --git a/dep/g3dlite/G3D/platform.h b/dep/g3dlite/G3D/platform.h new file mode 100644 index 00000000000..11ba0127a16 --- /dev/null +++ b/dep/g3dlite/G3D/platform.h @@ -0,0 +1,331 @@ +/** + @file platform.h + + \#defines for platform specific issues. + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2003-06-09 + @edited 2010-01-11 + */ + +#ifndef G3D_platform_h +#define G3D_platform_h + +/** + The version number of G3D in the form: MmmBB -> + version M.mm [beta BB] + */ +#define G3D_VER 80004 + +// fatal error for unsupported architectures +#if defined(__powerpc__) +# error PowerPC is not supported by G3D! +#endif + +#if defined(G3D_RELEASEDEBUG) +# define G3D_DEBUGRELEASE +#endif + +#if defined(G3D_DEBUGRELEASE) && defined(_DEBUG) +# undef _DEBUG +#endif + +/** @def G3D_DEBUG() + Defined if G3D is built in debug mode. */ +#if !defined(G3D_DEBUG) && (defined(_DEBUG) || defined(G3D_DEBUGRELEASE)) +# define G3D_DEBUG +#endif + +#ifndef _MSC_VER +/// Fast call is a register-based optimized calling convention supported only by Visual C++ +#define __fastcall + +#endif + +#ifdef _MSC_VER + #define G3D_WIN32 +#elif defined(__FreeBSD__) || defined(__OpenBSD__) + #define G3D_FREEBSD + #define G3D_LINUX +#elif defined(__linux__) + #define G3D_LINUX +#elif defined(__APPLE__) + #define G3D_OSX + + // Prevent OS X fp.h header from being included; it defines + // pi as a constant, which creates a conflict with G3D +#define __FP__ +#else + #error Unknown platform +#endif + +// Detect 64-bit under various compilers +#if (defined(_M_X64) || defined(_WIN64) || defined(__LP64__) || defined(_LP64)) +# define G3D_64BIT + #if defined(WIN32) + #include + #endif +#else +# define G3D_32BIT +#endif + +// Strongly encourage inlining on gcc +#ifdef __GNUC__ +#define inline __inline__ +#endif + + +// Verify that the supported compilers are being used and that this is a known +// processor. + +#ifdef G3D_LINUX +# ifndef __GNUC__ +# error G3D only supports the gcc compiler on Linux. +# endif +#endif + +#ifdef G3D_OSX +# ifndef __GNUC__ +# error G3D only supports the gcc compiler on OS X. +# endif + +# if defined(__i386__) +# define G3D_OSX_INTEL +# elif defined(__PPC__) +# define G3D_OSX_PPC +# else +# define G3D_OSX_UNKNOWN +# endif + +#endif + + +#ifdef _MSC_VER +// Microsoft Visual C++ 8.0 ("Express") = 1400 +// Microsoft Visual C++ 7.1 ("2003") _MSC_VER = 1310 +// Microsoft Visual C++ 7.0 ("2002") _MSC_VER = 1300 +// Microsoft Visual C++ 6.0 _MSC_VER = 1200 +// Microsoft Visual C++ 5.0 _MSC_VER = 1100 + +// Turn off warnings about deprecated C routines +# pragma warning (disable : 4996) + +// Turn off "conditional expression is constant" warning; MSVC generates this +// for debug assertions in inlined methods. +# pragma warning (disable : 4127) + +/** @def G3D_DEPRECATED() + Creates deprecated warning. */ +# define G3D_DEPRECATED __declspec(deprecated) + +// Prevent Winsock conflicts by hiding the winsock API +# ifndef _WINSOCKAPI_ +# define _G3D_INTERNAL_HIDE_WINSOCK_ +# define _WINSOCKAPI_ +# endif + +// Disable 'name too long for browse information' warning +# pragma warning (disable : 4786) +// TODO: remove +# pragma warning (disable : 4244) + +# define restrict + +/** @def G3D_CHECK_PRINTF_METHOD_ARGS() + Enables printf parameter validation on gcc. */ +# define G3D_CHECK_PRINTF_ARGS + +/** @def G3D_CHECK_PRINTF_METHOD_ARGS() + Enables printf parameter validation on gcc. */ +# define G3D_CHECK_VPRINTF_ARGS + +/** @def G3D_CHECK_PRINTF_METHOD_ARGS() + Enables printf parameter validation on gcc. */ +# define G3D_CHECK_PRINTF_METHOD_ARGS + +/** @def G3D_CHECK_PRINTF_METHOD_ARGS() + Enables printf parameter validation on gcc. */ +# define G3D_CHECK_VPRINTF_METHOD_ARGS + + // On MSVC, we need to link against the multithreaded DLL version of + // the C++ runtime because that is what SDL and ZLIB are compiled + // against. This is not the default for MSVC, so we set the following + // defines to force correct linking. + // + // For documentation on compiler options, see: + // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccore/html/_core_.2f.md.2c_2f.ml.2c_2f.mt.2c_2f.ld.asp + // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccore98/HTML/_core_Compiler_Reference.asp + // + + // DLL runtime + #ifndef _DLL + #define _DLL + #endif + + // Multithreaded runtime + #ifndef _MT + #define _MT 1 + #endif + + // Ensure that we aren't forced into the static lib + #ifdef _STATIC_CPPLIB + #undef _STATIC_CPPLIB + #endif + + #ifdef _DEBUG + #pragma comment (linker, "/NODEFAULTLIB:LIBCMTD.LIB") + #pragma comment (linker, "/NODEFAULTLIB:LIBCPMTD.LIB") + #pragma comment (linker, "/NODEFAULTLIB:LIBCPD.LIB") + #pragma comment (linker, "/DEFAULTLIB:MSVCPRTD.LIB") + #pragma comment(linker, "/NODEFAULTLIB:LIBCD.LIB") + #pragma comment(linker, "/DEFAULTLIB:MSVCRTD.LIB") + #else + #pragma comment(linker, "/NODEFAULTLIB:LIBC.LIB") + #pragma comment(linker, "/DEFAULTLIB:MSVCRT.LIB") + #pragma comment (linker, "/NODEFAULTLIB:LIBCMT.LIB") + #pragma comment (linker, "/NODEFAULTLIB:LIBCPMT.LIB") + #pragma comment(linker, "/NODEFAULTLIB:LIBCP.LIB") + #pragma comment (linker, "/DEFAULTLIB:MSVCPRT.LIB") + #endif + + // Now set up external linking + +# ifdef _DEBUG + // zlib was linked against the release MSVCRT; force + // the debug version. +# pragma comment(linker, "/NODEFAULTLIB:MSVCRT.LIB") +# endif + + +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN 1 +# endif + + +# define NOMINMAX 1 +# ifndef _WIN32_WINNT +# define _WIN32_WINNT 0x0500 +# endif +# include +# undef WIN32_LEAN_AND_MEAN +# undef NOMINMAX + +# ifdef _G3D_INTERNAL_HIDE_WINSOCK_ +# undef _G3D_INTERNAL_HIDE_WINSOCK_ +# undef _WINSOCKAPI_ +# endif + + +/** @def G3D_START_AT_MAIN() + Defines necessary wrapper around WinMain on Windows to allow transfer of execution to main(). */ +# define G3D_START_AT_MAIN()\ +int WINAPI G3D_WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int sw);\ +int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int sw) {\ + return G3D_WinMain(hInst, hPrev, szCmdLine, sw);\ +} + +#else + +/** @def G3D_START_AT_MAIN() + Defines necessary wrapper around WinMain on Windows to allow transfer of execution to main(). */ +# define G3D_START_AT_MAIN() + +#endif // win32 + +#ifdef __GNUC__ + +# include + +# if __STDC_VERSION__ < 199901 +# define restrict __restrict__ +# endif + +/** @def G3D_DEPRECATED() + Creates deprecated warning. */ +# define G3D_DEPRECATED __attribute__((__deprecated__)) + +// setup function calling conventions +# if defined(__i386__) && ! defined(__x86_64__) + +# ifndef __cdecl +# define __cdecl __attribute__((cdecl)) +# endif + +# ifndef __stdcall +# define __stdcall __attribute__((stdcall)) +# endif + +# elif defined(__x86_64__) + +# ifndef __cdecl +# define __cdecl +# endif + +# ifndef __stdcall +# define __stdcall +# endif +# endif // calling conventions + +/** @def G3D_CHECK_PRINTF_METHOD_ARGS() + Enables printf parameter validation on gcc. */ +# define G3D_CHECK_PRINTF_METHOD_ARGS __attribute__((__format__(__printf__, 2, 3))) + +/** @def G3D_CHECK_PRINTF_METHOD_ARGS() + Enables printf parameter validation on gcc. */ +# define G3D_CHECK_VPRINTF_METHOD_ARGS __attribute__((__format__(__printf__, 2, 0))) + +/** @def G3D_CHECK_PRINTF_METHOD_ARGS() + Enables printf parameter validation on gcc. */ +# define G3D_CHECK_PRINTF_ARGS __attribute__((__format__(__printf__, 1, 2))) + +/** @def G3D_CHECK_PRINTF_METHOD_ARGS() + Enables printf parameter validation on gcc. */ +# define G3D_CHECK_VPRINTF_ARGS __attribute__((__format__(__printf__, 1, 0))) +#endif + + +/** + @def STR(expression) + + Creates a string from the expression. Frequently used with G3D::Shader + to express shading programs inline. + + STR(this becomes a string)\verbatim
\endverbatim evaluates the same as \verbatim\endverbatim"this becomes a string"
+ */
+#define STR(x) #x
+
+/** @def PRAGMA(expression)
+    \#pragma may not appear inside a macro, so this uses the pragma operator
+    to create an equivalent statement.*/
+#ifdef _MSC_VER
+// Microsoft's version http://msdn.microsoft.com/en-us/library/d9x1s805.aspx
+#    define PRAGMA(x) __pragma(x)
+#else
+// C99 standard http://www.delorie.com/gnu/docs/gcc/cpp_45.html
+#    define PRAGMA(x) _Pragma(#x)
+#endif
+
+/** @def G3D_BEGIN_PACKED_CLASS(byteAlign)
+    Switch to tight alignment
+    See G3D::Color3uint8 for an example.*/
+#ifdef _MSC_VER
+#    define G3D_BEGIN_PACKED_CLASS(byteAlign)  PRAGMA( pack(push, byteAlign) )
+#else
+#    define G3D_BEGIN_PACKED_CLASS(byteAlign)
+#endif
+
+/** @def G3D_END_PACKED_CLASS(byteAlign)
+    End switch to tight alignment
+    See G3D::Color3uint8 for an example.*/
+#ifdef _MSC_VER
+#    define G3D_END_PACKED_CLASS(byteAlign)  ; PRAGMA( pack(pop) )
+#elif defined(__GNUC__)
+#    define G3D_END_PACKED_CLASS(byteAlign)  __attribute((aligned(byteAlign))) ;
+#else
+#    define G3D_END_PACKED_CLASS(byteAlign)  ;
+#endif
+
+
+// Header guard
+#endif
diff --git a/dep/g3dlite/G3D/prompt.h b/dep/g3dlite/G3D/prompt.h
new file mode 100644
index 00000000000..c6df628099e
--- /dev/null
+++ b/dep/g3dlite/G3D/prompt.h
@@ -0,0 +1,67 @@
+/** 
+ @file prompt.h
+ 
+ @maintainer Morgan McGuire, http://graphics.cs.williams.edu
+ @cite   Windows GUI code by Max McGuire
+
+ @created 2001-08-26
+ @edited  2006-08-13
+ */
+
+#ifndef G3D_PROMPT_H
+#define G3D_PROMPT_H
+
+#include "platform.h"
+#include 
+
+namespace G3D {
+
+/**
+  Prints a prompt to stdout and waits for user input.  The return value is
+  the number of the user's choice (the first is 0, if there are no
+  choices, returns 0). 
+ 
+  @param useGui Under Win32, use a GUI, not stdout prompt.
+  @param windowTitle The title for the prompt window
+  @param promptx The text string to prompt the user with
+  @param choice  An array of strings that are the choices the user may make
+  @param numChoices The length of choice.
+
+  @cite Windows dialog interface by Max McGuire, mmcguire@ironlore.com
+  @cite Font setting code by Kurt Miller, kurt@flipcode.com
+ */
+int prompt(
+    const char*     windowTitle,
+    const char*     promptx,
+    const char**    choice,
+    int             numChoices,
+    bool            useGui);
+
+/**
+  Prints a prompt and waits for user input.  The return value is
+  the number of the user's choice (the first is 0, if there are no
+  choices, returns 0).
+  

Uses GUI under Win32, stdout prompt otherwise. + */ +inline int prompt( + const char* windowTitle, + const char* promptx, + const char** choice, + int numChoices) { + + return prompt(windowTitle, promptx, choice, numChoices, true); +} + + +/** + Displays a GUI prompt with "Ok" as the only choice. + */ +void msgBox( + const std::string& message, + const std::string& title = "Message"); + + +}; // namespace + +#endif + diff --git a/dep/g3dlite/G3D/serialize.h b/dep/g3dlite/G3D/serialize.h new file mode 100644 index 00000000000..2382c0ee0fd --- /dev/null +++ b/dep/g3dlite/G3D/serialize.h @@ -0,0 +1,30 @@ +#ifndef G3D_SERIALIZE_H +#define G3D_SERIALIZE_H + +#include "G3D/BinaryInput.h" +#include "G3D/BinaryOutput.h" +#include "G3D/Array.h" + +namespace G3D { + + +template +void serialize(const Array& array, BinaryOutput& b) { + b.writeInt32(array.size()); + for (int i = 0; i < array.size(); ++i) { + serialize(array[i], b); + } +} + +template +void deserialize(Array& array, BinaryInput& b) { + int N = b.readInt32(); + array.resize(N); + for (int i = 0; i < array.size(); ++i) { + deserialize(array[i], b); + } +} + +} + +#endif diff --git a/dep/g3dlite/G3D/splinefunc.h b/dep/g3dlite/G3D/splinefunc.h new file mode 100644 index 00000000000..3f3a018c292 --- /dev/null +++ b/dep/g3dlite/G3D/splinefunc.h @@ -0,0 +1,118 @@ +/** + @file spline.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2004-07-25 + @edited 2007-05-05 + */ + +#ifndef G3D_SPLINEFUNC_H +#define G3D_SPLINEFUNC_H + +#include "G3D/platform.h" +#include "G3D/debug.h" +#include "G3D/Array.h" +#include "G3D/g3dmath.h" + +namespace G3D { + +/** + Interpolates a property according to a piecewise linear spline. This provides + C0 continuity but the derivatives are not smooth. +

+ Example: + + const double times[] = {MIDNIGHT, SUNRISE - HOUR, SUNRISE, SUNRISE + sunRiseAndSetTime / 4, SUNRISE + sunRiseAndSetTime, SUNSET - sunRiseAndSetTime, SUNSET - sunRiseAndSetTime / 2, SUNSET, SUNSET + HOUR/2, DAY}; + const Color3 color[] = {Color3(0, .0, .1), Color3(0, .0, .1), Color3::black(), Color3::black(), Color3::white() * .25, Color3::white() * .25, Color3(.5, .2, .2), Color3(.05, .05, .1), Color3(0, .0, .1), Color3(0, .0, .1)}; + ambient = linearSpline(time, times, color, 10); + + + See also G3D::Spline + + @param x The spline is a function of x; this is the sample to choose. + @param controlX controlX[i], controlY[i] is a control points. It is assumed + that controlX are strictly increasing. XType must support + the "<" operator and a subtraction operator that returns + a number. + @param controlY YType must support multiplication and addition. + @param numControl The number of control points. + */ +template +YType linearSpline(double x, const XType* controlX, const YType* controlY, int numControl) { + debugAssert(numControl >= 1); + + // Off the beginning + if ((numControl == 1) || (x < controlX[0])) { + return controlY[0]; + } + + for (int i = 1; i < numControl; ++i) { + if (x < controlX[i]) { + const double alpha = (double)(controlX[i] - x) / (controlX[i] - controlX[i - 1]); + return controlY[i] * (1 - alpha) + controlY[i - 1] * alpha; + } + } + + // Off the end + return controlY[numControl - 1]; +} + + + /** See also G3D::Spline*/ +template YType cyclicCatmullRomSpline( + double t, + const YType* controlY, + int numPoints) { + + debugAssert(numPoints >= 3); + + t = wrap(t, numPoints); + + // Find the indices of adjacent control points + int i = iFloor(t); + + // Compute the distance from the control point + t = t - i; + + // Shift back one point for correct indexing + i += numPoints - 1; + + // Pick up four control points + const YType& P0 = controlY[(i + 0) % numPoints]; + const YType& P1 = controlY[(i + 1) % numPoints]; + const YType& P2 = controlY[(i + 2) % numPoints]; + const YType& P3 = controlY[(i + 3) % numPoints]; + + return 0.5 * ((2 * P1) + + (-P0 + P2) * t + + (2*P0 - 5*P1 + 4*P2 - P3) * t*t + + (-P0 + 3*P1- 3*P2 + P3) * t*t*t); +} + +/** + A cubic spline with regularly spaced + control points. The spline interpolates + the control points. The spline + will wrap from the last point back to the first. + + The t parameter is on the range [0, controlY.size()], + where integers correspond to control points exactly. + + See also G3D::Spline + + @cite http://www.mvps.org/directx/articles/catmull/ +*/ +template YType cyclicCatmullRomSpline( + double t, + const Array& controlY) { + + int numPoints = controlY.size(); + return cyclicCatmullRomSpline(t, controlY.getCArray(), numPoints); +} + +} + +#endif + + diff --git a/dep/g3dlite/G3D/stringutils.h b/dep/g3dlite/G3D/stringutils.h new file mode 100644 index 00000000000..e15a757a7a6 --- /dev/null +++ b/dep/g3dlite/G3D/stringutils.h @@ -0,0 +1,140 @@ +/** + @file stringutils.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @author 2000-09-09 + @edited 2008-08-05 + */ + +#ifndef G3D_STRINGUTILS_H +#define G3D_STRINGUTILS_H + +#include "G3D/platform.h" +#include "G3D/Array.h" +#include + +namespace G3D { + +extern const char* NEWLINE; + +/** Separates a comma-separated line, properly escaping commas within + double quotes (") and super quotes ("""). This matches Microsoft Excel's + CSV output. + + \param stripQuotes If true, strips leading and trailing " and """ + + \sa G3D::stringSplit, G3D::TextInput, G3D::readWholeFile +*/ +void parseCommaSeparated(const std::string s, Array& array, bool stripQuotes = true); + +/** + Returns true if the test string begins with the pattern string. + */ +bool beginsWith( + const std::string& test, + const std::string& pattern); + +/** + Returns true if the test string ends with the pattern string. + */ +bool endsWith( + const std::string& test, + const std::string& pattern); + +/** + Produces a new string that is the input string + wrapped at a certain number of columns (where + the line is broken at the latest space before the + column limit.) Platform specific NEWLINEs + are inserted to wrap. + */ +std::string wordWrap( + const std::string& input, + int numCols); + +/** + A comparison function for passing to Array::sort. + */ +int stringCompare( + const std::string& s1, + const std::string& s2); + +int stringPtrCompare( + const std::string* s1, + const std::string* s2); + +/** + Returns a new string that is an uppercase version of x. + */ +std::string toUpper( + const std::string& x); + +std::string toLower( + const std::string& x); + +/** + Splits x at each occurance of splitChar. + */ +G3D::Array stringSplit( + const std::string& x, + char splitChar); + +/** + joinChar is not inserted at the beginning or end, just in between + elements. + */ +std::string stringJoin( + const G3D::Array& a, + char joinChar); + +std::string stringJoin( + const G3D::Array& a, + const std::string& joinStr); + +/** + Strips whitespace from both ends of the string. + */ +std::string trimWhitespace( + const std::string& s); + +/** These standard C functions are renamed for clarity/naming + conventions and to return bool, not int. + */ +inline bool isWhiteSpace(const unsigned char c) { + return isspace(c) != 0; +} + +/** These standard C functions are renamed for clarity/naming + conventions and to return bool, not int. + */ +inline bool isNewline(const unsigned char c) { + return (c == '\n') || (c == '\r'); +} + +/** These standard C functions are renamed for clarity/naming + conventions and to return bool, not int. + */ +inline bool isDigit(const unsigned char c) { + return isdigit(c) != 0; +} + +/** These standard C functions are renamed for clarity/naming + conventions and to return bool, not int. + */ +inline bool isLetter(const unsigned char c) { + return isalpha(c) != 0; +} + +inline bool isSlash(const unsigned char c) { + return (c == '\\') || (c == '/'); +} + +inline bool isQuote(const unsigned char c) { + return (c == '\'') || (c == '\"'); +} + +}; // namespace + +#endif + diff --git a/dep/g3dlite/G3D/uint128.h b/dep/g3dlite/G3D/uint128.h new file mode 100644 index 00000000000..da1af3ec272 --- /dev/null +++ b/dep/g3dlite/G3D/uint128.h @@ -0,0 +1,51 @@ +/** + @file uint128.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + @author Kyle Whitson + + @created 2008-07-17 + @edited 2008-07-17 + */ + +#ifndef G3D_UINT128_H +#define G3D_UINT128_H + +#include "G3D/g3dmath.h" + +namespace G3D { + +/** Limited functionality 128-bit unsigned integer. This is primarily to support FNV hashing and other + cryptography applications. See the GMP library for high-precision C++ math support. */ +class uint128 { +public: + + G3D::uint64 hi; + G3D::uint64 lo; + + uint128(const uint64& lo); + + uint128(const uint64& hi, const uint64& lo); + + uint128& operator+=(const uint128& x); + + uint128& operator*=(const uint128& x); + + uint128& operator^=(const uint128& x); + + uint128& operator&=(const uint128& x); + + uint128& operator|=(const uint128& x); + + bool operator==(const uint128& x); + + uint128& operator>>=(const int x); + + uint128& operator<<=(const int x); + + uint128 operator&(const uint128& x); + +}; +} + +#endif diff --git a/dep/g3dlite/G3D/units.h b/dep/g3dlite/G3D/units.h new file mode 100644 index 00000000000..2e30304dc62 --- /dev/null +++ b/dep/g3dlite/G3D/units.h @@ -0,0 +1,126 @@ +/** + @file units.h + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2009-08-21 + @edited 2009-08-21 + */ +#ifndef G3D_units_h +#define G3D_units_h + +#include "G3D/platform.h" + +namespace G3D { +/** Use using namespace G3D::units; to include all units + into your program. The units system is specifically designed not to + be general but to support commonly used units efficiently and + clearly. See http://en.wikipedia.org/wiki/SI_prefix for interesting facts + about SI/metric units and full definitions.*/ +namespace units { + +/** 1e-9 m */ +inline float nanometers() { + return 1e-9f; +} + +/** 1e-6 m */ +inline float micrometers() { + return 1e-6f; +} + +/** 0.001 m */ +inline float millimeters() { + return 0.001f; +} + +/** 0.01 m */ +inline float centimeters() { + return 0.01f; +} + +/** SI base unit of distance measure. */ +inline float meters() { + return 1.0f; +} + +/** 1000 m */ +inline float kilometers() { + return 100.0f; +} + +/** 0.0254 m */ +inline float inches() { + return 0.0254f; +} + +/** 0.3048 m */ +inline float feet() { + return 0.3048f; +} + +/** 0.9144 m */ +inline float yards() { + return 0.9144f; +} + +/** 1609.344 m */ +inline float miles() { + return 1609.344f; +} + +///////////////////////////////////////////////////////////// + +/** SI base unit of angular measure. */ +inline float radians() { + return 1.0f; +} + +/** pi/180 */ +inline float degrees() { + return 0.0174532925f; +} + +////////////////////////////////////////////////////////////// + +/** 1e-9 s */ +inline float nanoseconds() { + return 1e-9f; +} + +/** 1e-3 s */ +inline float milliseconds() { + return 1e-3f; +} + +/** Base unit of time */ +inline float seconds() { + return 1.0; +} + +/** 60 s */ +inline float minutes() { + return 60.0f; +} + +/** 3600 s */ +inline float hours() { + return 3600.0f; +} + +/** 86400 s */ +inline float days() { + return 86400.0f; +} + +/** 31556926 s */ +inline float years() { + return 31556926.0f; +} + +/////////////////////////////////////////// + +} +} + +#endif diff --git a/dep/g3dlite/G3D/vectorMath.h b/dep/g3dlite/G3D/vectorMath.h new file mode 100644 index 00000000000..ac6d2b32e9d --- /dev/null +++ b/dep/g3dlite/G3D/vectorMath.h @@ -0,0 +1,235 @@ +/** + @file vectorMath.h + + Function aliases for popular vector methods. + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created: 2001-06-02 + @edited: 2004-02-02 + Copyright 2000-2004, Morgan McGuire. + All rights reserved. + */ + +#ifndef G3D_VECTORMATH_H +#define G3D_VECTORMATH_H + +#include "G3D/platform.h" +#include "G3D/g3dmath.h" +#include "G3D/Vector2.h" +#include "G3D/Vector3.h" +#include "G3D/Vector4.h" +#include "G3D/Matrix3.h" +#include "G3D/Matrix4.h" +#include "G3D/Color1.h" +#include "G3D/Color3.h" +#include "G3D/Color4.h" + + +namespace G3D { + + +inline Matrix4 mul(const Matrix4& a, const Matrix4& b) { + return a * b; +} + +inline Vector4 mul(const Matrix4& m, const Vector4& v) { + return m * v; +} + +inline Vector3 mul(const Matrix3& m, const Vector3& v) { + return m * v; +} + +inline Matrix3 mul(const Matrix3& a, const Matrix3& b) { + return a * b; +} + +inline float dot(const Vector2& a, const Vector2& b) { + return a.dot(b); +} + +inline float dot(const Vector3& a, const Vector3& b) { + return a.dot(b); +} + +inline float dot(const Vector4& a, const Vector4& b) { + return a.dot(b); +} + +inline Vector2 normalize(const Vector2& v) { + return v / v.length(); +} + +inline Vector3 normalize(const Vector3& v) { + return v / v.magnitude(); +} + +inline Vector4 normalize(const Vector4& v) { + return v / v.length(); +} + +inline Vector2 abs(const Vector2& v) { + return Vector2(::fabsf(v.x), ::fabsf(v.y)); +} + +inline Vector3 abs(const Vector3& v) { + return Vector3(::fabsf(v.x), ::fabsf(v.y), ::fabsf(v.z)); +} + +inline Vector4 abs(const Vector4& v) { + return Vector4(::fabsf(v.x), ::fabsf(v.y), ::fabsf(v.z), ::fabsf(v.w)); +} + +inline bool all(const Vector2& v) { + return (v.x != 0) && (v.y != 0); +} + +inline bool all(const Vector3& v) { + return (v.x != 0) && (v.y != 0) && (v.z != 0); +} + +inline bool all(const Vector4& v) { + return (v.x != 0) && (v.y != 0) && (v.z != 0) && (v.w != 0); +} + +inline bool any(const Vector2& v) { + return (v.x != 0) || (v.y != 0); +} + +inline bool any(const Vector3& v) { + return (v.x != 0) || (v.y != 0) || (v.z != 0); +} + +inline bool any(const Vector4& v) { + return (v.x != 0) || (v.y != 0) || (v.z != 0) || (v.w != 0); +} + +inline Vector2 clamp(const Vector2& v, const Vector2& a, const Vector2& b) { + return v.clamp(a, b); +} + +inline Vector3 clamp(const Vector3& v, const Vector3& a, const Vector3& b) { + return v.clamp(a, b); +} + +inline Vector4 clamp(const Vector4& v, const Vector4& a, const Vector4& b) { + return v.clamp(a, b); +} + +inline Vector2 lerp(const Vector2& v1, const Vector2& v2, float f) { + return v1.lerp(v2, f); +} + +inline Vector3 lerp(const Vector3& v1, const Vector3& v2, float f) { + return v1.lerp(v2, f); +} + +inline Vector4 lerp(const Vector4& v1, const Vector4& v2, float f) { + return v1.lerp(v2, f); +} + +inline Color1 lerp(const Color1& v1, const Color1& v2, float f) { + return v1.lerp(v2, f); +} + +inline Color3 lerp(const Color3& v1, const Color3& v2, float f) { + return v1.lerp(v2, f); +} + +inline Color4 lerp(const Color4& v1, const Color4& v2, float f) { + return v1.lerp(v2, f); +} + +inline Vector3 cross(const Vector3& v1, const Vector3& v2) { + return v1.cross(v2); +} + +inline double determinant(const Matrix3& m) { + return m.determinant(); +} + +inline double determinant(const Matrix4& m) { + return m.determinant(); +} + +inline Vector2 min(const Vector2& v1, const Vector2& v2) { + return v1.min(v2); +} + +inline Vector3 min(const Vector3& v1, const Vector3& v2) { + return v1.min(v2); +} + +inline Vector4 min(const Vector4& v1, const Vector4& v2) { + return v1.min(v2); +} + +inline Color3 min(const Color3& v1, const Color3& v2) { + return v1.min(v2); +} + +inline Color4 min(const Color4& v1, const Color4& v2) { + return v1.min(v2); +} + +inline Vector2 max(const Vector2& v1, const Vector2& v2) { + return v1.max(v2); +} + +inline Vector3 max(const Vector3& v1, const Vector3& v2) { + return v1.max(v2); +} + +inline Vector4 max(const Vector4& v1, const Vector4& v2) { + return v1.max(v2); +} + +inline Color3 max(const Color3& v1, const Color3& v2) { + return v1.max(v2); +} + +inline Color4 max(const Color4& v1, const Color4& v2) { + return v1.max(v2); +} + +inline Vector2 sign(const Vector2& v) { + return Vector2((float)sign(v.x), (float)sign(v.y)); +} + +inline Vector3 sign(const Vector3& v) { + return Vector3((float)sign(v.x), (float)sign(v.y), (float)sign(v.z)); +} + +inline Vector4 sign(const Vector4& v) { + return Vector4((float)sign(v.x), (float)sign(v.y), (float)sign(v.z), (float)sign(v.w)); +} + +inline float length(float v) { + return ::fabsf(v); +} + +inline float length(const Vector2& v) { + return v.length(); +} + +inline float length(const Vector3& v) { + return v.magnitude(); +} + +inline float length(const Vector4& v) { + return v.length(); +} + +/** + Computes the log of each component. Useful for + inverting the monitor gamma function or simulating + perceptual response. + */ +inline Color3 log(const Color3& c) { + return Color3(::logf(c.r), ::logf(c.g), ::logf(c.b)); +} + +} + +#endif diff --git a/dep/g3dlite/Line.cpp b/dep/g3dlite/Line.cpp new file mode 100644 index 00000000000..195ae7197f2 --- /dev/null +++ b/dep/g3dlite/Line.cpp @@ -0,0 +1,89 @@ +/** + @file Line.cpp + + Line class + + @maintainer Morgan McGuire, graphics3d.com + + @created 2001-06-02 + @edited 2006-01-28 + */ + +#include "G3D/Line.h" +#include "G3D/Plane.h" + +namespace G3D { + +Vector3 Line::intersection(const Plane& plane) const { + float d; + Vector3 normal = plane.normal(); + plane.getEquation(normal, d); + float rate = _direction.dot(normal); + + if (rate == 0) { + + return Vector3::inf(); + + } else { + float t = -(d + _point.dot(normal)) / rate; + + return _point + _direction * t; + } +} + + +Line::Line(class BinaryInput& b) { + deserialize(b); +} + + +void Line::serialize(class BinaryOutput& b) const { + _point.serialize(b); + _direction.serialize(b); +} + + +void Line::deserialize(class BinaryInput& b) { + _point.deserialize(b); + _direction.deserialize(b); +} + + +Vector3 Line::closestPoint(const Vector3& pt) const { + float t = _direction.dot(pt - _point); + return _point + _direction * t; +} + + +Vector3 Line::point() const { + return _point; +} + + +Vector3 Line::direction() const { + return _direction; +} + + +Vector3 Line::closestPoint(const Line& B, float& minDist) const { + const Vector3& P1 = _point; + const Vector3& U1 = _direction; + + Vector3 P2 = B.point(); + Vector3 U2 = B.direction(); + + const Vector3& P21 = P2 - P1; + const Vector3& M = U2.cross(U1); + float m2 = M.length(); + + Vector3 R = P21.cross(M) / m2; + + float t1 = R.dot(U2); + + minDist = abs(P21.dot(M)) / sqrt(m2); + + return P1 + t1 * U1; +} + +} + diff --git a/dep/g3dlite/LineSegment.cpp b/dep/g3dlite/LineSegment.cpp new file mode 100644 index 00000000000..754600ad554 --- /dev/null +++ b/dep/g3dlite/LineSegment.cpp @@ -0,0 +1,236 @@ +/** + @file LineSegment.cpp + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2003-02-08 + @edited 2008-02-02 + */ + +#include "G3D/platform.h" +#include "G3D/LineSegment.h" +#include "G3D/Sphere.h" +#include "G3D/debug.h" + +namespace G3D { + + +Vector3 LineSegment::closestPoint(const Vector3& p) const { + + // The vector from the end of the capsule to the point in question. + Vector3 v(p - _point); + + // Projection of v onto the line segment scaled by + // the length of direction. + float t = direction.dot(v); + + // Avoid some square roots. Derivation: + // t/direction.length() <= direction.length() + // t <= direction.squaredLength() + + if ((t >= 0) && (t <= direction.squaredMagnitude())) { + + // The point falls within the segment. Normalize direction, + // divide t by the length of direction. + return _point + direction * t / direction.squaredMagnitude(); + + } else { + + // The point does not fall within the segment; see which end is closer. + + // Distance from 0, squared + float d0Squared = v.squaredMagnitude(); + + // Distance from 1, squared + float d1Squared = (v - direction).squaredMagnitude(); + + if (d0Squared < d1Squared) { + + // Point 0 is closer + return _point; + + } else { + + // Point 1 is closer + return _point + direction; + + } + } + +} + +Vector3 LineSegment::point(int i) const { + switch (i) { + case 0: + return _point; + + case 1: + return _point + direction; + + default: + debugAssertM(i == 0 || i == 1, "Argument to point must be 0 or 1"); + return _point; + } +} + + +bool LineSegment::intersectsSolidSphere(const class Sphere& s) const { + return distanceSquared(s.center) <= square(s.radius); +} + + +LineSegment::LineSegment(class BinaryInput& b) { + deserialize(b); +} + + +void LineSegment::serialize(class BinaryOutput& b) const { + _point.serialize(b); + direction.serialize(b); +} + + +void LineSegment::deserialize(class BinaryInput& b) { + _point.deserialize(b); + direction.deserialize(b); +} + + +Vector3 LineSegment::randomPoint() const { + return _point + uniformRandom(0, 1) * direction; +} + + +///////////////////////////////////////////////////////////////////////////////////// + +LineSegment2D LineSegment2D::fromTwoPoints(const Vector2& p0, const Vector2& p1) { + LineSegment2D s; + s.m_origin = p0; + s.m_direction = p1 - p0; + s.m_length = s.m_direction.length(); + return s; +} + + +Vector2 LineSegment2D::point(int i) const { + debugAssert(i == 0 || i == 1); + if (i == 0) { + return m_origin; + } else { + return m_direction + m_origin; + } +} + + +Vector2 LineSegment2D::closestPoint(const Vector2& Q) const { + // Two constants that appear in the result + const Vector2 k1(m_origin - Q); + const Vector2& k2 = m_direction; + + if (fuzzyEq(m_length, 0)) { + // This line segment has no length + return m_origin; + } + + // Time [0, 1] at which we hit the closest point travelling from p0 to p1. + // Derivation can be obtained by minimizing the expression + // ||P0 + (P1 - P0)t - Q||. + const float t = -k1.dot(k2) / (m_length * m_length); + + if (t < 0) { + // Clipped to low end point + return m_origin; + } else if (t > 1) { + // Clipped to high end point + return m_origin + m_direction; + } else { + // Subsitute into the line equation to find + // the point on the segment. + return m_origin + k2 * t; + } +} + + +float LineSegment2D::distance(const Vector2& p) const { + Vector2 closest = closestPoint(p); + return (closest - p).length(); +} + + +float LineSegment2D::length() const { + return m_length; +} + + +Vector2 LineSegment2D::intersection(const LineSegment2D& other) const { + + if ((m_origin == other.m_origin) || + (m_origin == other.m_origin + other.m_direction)) { + return m_origin; + } + + if (m_origin + m_direction == other.m_origin) { + return other.m_origin; + } + + // Note: Now that we've checked the endpoints, all other parallel lines can now be assumed + // to not intersect (within numerical precision) + + Vector2 dir1 = m_direction; + Vector2 dir2 = other.m_direction; + Vector2 origin1 = m_origin; + Vector2 origin2 = other.m_origin; + + if (dir1.x == 0) { + // Avoid an upcoming divide by zero + dir1 = dir1.yx(); + dir2 = dir2.yx(); + origin1 = origin1.yx(); + origin2 = origin2.yx(); + } + + // t1 = ((other.m_origin.x - m_origin.x) + other.m_direction.x * t2) / m_direction.x + // + // ((other.m_origin.x - m_origin.x) + other.m_direction.x * t2) * m_direction.y / m_direction.x = + // (other.m_origin.y - m_origin.y) + other.m_direction.y * t2 + // + // m = m_direction.y / m_direction.x + // d = other.m_origin - m_origin + // + // (d.x + other.m_direction.x * t2) * m = d.y + other.m_direction.y * t2 + // + // d.x * m + other.m_direction.x * m * t2 = d.y + other.m_direction.y * t2 + // + // d.x * m - d.y = (other.m_direction.y - other.m_direction.x * m) * t2 + // + // (d.x * m - d.y) / (other.m_direction.y - other.m_direction.x * m) = t2 + // + + Vector2 d = origin2 - origin1; + float m = dir1.y / dir1.x; + + float t2 = (d.x * m - d.y) / (dir2.y - dir2.x * m); + if (! isFinite(t2)) { + // Parallel lines: no intersection + return Vector2::inf(); + } + + if ((t2 < 0.0f) || (t2 > 1.0f)) { + // Intersection occurs past the end of the line segments + return Vector2::inf(); + } + + float t1 = (d.x + dir2.x * t2) / dir1.x; + if ((t1 < 0.0f) || (t1 > 1.0f)) { + // Intersection occurs past the end of the line segments + return Vector2::inf(); + } + + // Return the intersection point (computed from non-transposed + // variables even if we flipped above) + return m_origin + m_direction * t1; + +} + +} + diff --git a/dep/g3dlite/Log.cpp b/dep/g3dlite/Log.cpp new file mode 100644 index 00000000000..07614fcf563 --- /dev/null +++ b/dep/g3dlite/Log.cpp @@ -0,0 +1,146 @@ +/** + @file Log.cpp + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + @created 2001-08-04 + @edited 2009-01-15 + */ + +#include "G3D/platform.h" +#include "G3D/Log.h" +#include "G3D/format.h" +#include "G3D/Array.h" +#include "G3D/fileutils.h" +#include + +#ifdef G3D_WIN32 + #include +#else + #include +#endif + +namespace G3D { + +void logPrintf(const char* fmt, ...) { + va_list arg_list; + va_start(arg_list, fmt); + Log::common()->vprintf(fmt, arg_list); + va_end(arg_list); +} + + +void logLazyPrintf(const char* fmt, ...) { + va_list arg_list; + va_start(arg_list, fmt); + Log::common()->lazyvprintf(fmt, arg_list); + va_end(arg_list); +} + +Log* Log::commonLog = NULL; + +Log::Log(const std::string& filename, int stripFromStackBottom) : + stripFromStackBottom(stripFromStackBottom) { + + this->filename = filename; + + logFile = fopen(filename.c_str(), "w"); + + if (logFile == NULL) { + std::string drive, base, ext; + Array path; + parseFilename(filename, drive, path, base, ext); + std::string logName = base + ((ext != "") ? ("." + ext) : ""); + + // Write time is greater than 1ms. This may be a network drive.... try another file. + #ifdef G3D_WIN32 + logName = std::string(std::getenv("TEMP")) + logName; + #else + logName = std::string("/tmp/") + logName; + #endif + + logFile = fopen(logName.c_str(), "w"); + } + + // Use a large buffer (although we flush in logPrintf) + setvbuf(logFile, NULL, _IOFBF, 2048); + + fprintf(logFile, "Application Log\n"); + time_t t; + time(&t); + fprintf(logFile, "Start: %s\n", ctime(&t)); + fflush(logFile); + + if (commonLog == NULL) { + commonLog = this; + } +} + + +Log::~Log() { + section("Shutdown"); + println("Closing log file"); + + // Make sure we don't leave a dangling pointer + if (Log::commonLog == this) { + Log::commonLog = NULL; + } + + fclose(logFile); +} + + +FILE* Log::getFile() const { + return logFile; +} + + +Log* Log::common() { + if (commonLog == NULL) { + commonLog = new Log(); + } + return commonLog; +} + + +std::string Log::getCommonLogFilename() { + return common()->filename; +} + + +void Log::section(const std::string& s) { + fprintf(logFile, "_____________________________________________________\n"); + fprintf(logFile, "\n ### %s ###\n\n", s.c_str()); +} + + +void __cdecl Log::printf(const char* fmt, ...) { + va_list arg_list; + va_start(arg_list, fmt); + print(vformat(fmt, arg_list)); + va_end(arg_list); +} + + +void __cdecl Log::vprintf(const char* fmt, va_list argPtr) { + vfprintf(logFile, fmt, argPtr); + fflush(logFile); +} + + +void __cdecl Log::lazyvprintf(const char* fmt, va_list argPtr) { + vfprintf(logFile, fmt, argPtr); +} + + +void Log::print(const std::string& s) { + fprintf(logFile, "%s", s.c_str()); + fflush(logFile); +} + + +void Log::println(const std::string& s) { + fprintf(logFile, "%s\n", s.c_str()); + fflush(logFile); +} + +} diff --git a/dep/g3dlite/Matrix3.cpp b/dep/g3dlite/Matrix3.cpp new file mode 100644 index 00000000000..b32d938f0f9 --- /dev/null +++ b/dep/g3dlite/Matrix3.cpp @@ -0,0 +1,1927 @@ +/** + @file Matrix3.cpp + + 3x3 matrix class + + @author Morgan McGuire, graphics3d.com + + @created 2001-06-02 + @edited 2009-11-15 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. +*/ + +#include "G3D/platform.h" +#include +#include +#include "G3D/Matrix3.h" +#include "G3D/g3dmath.h" +#include "G3D/BinaryInput.h" +#include "G3D/BinaryOutput.h" +#include "G3D/Quat.h" +#include "G3D/Any.h" + +namespace G3D { + +const float Matrix3::EPSILON = 1e-06f; + +Matrix3::Matrix3(const Any& any) { + any.verifyName("Matrix3"); + any.verifyType(Any::ARRAY); + any.verifySize(9); + + for (int r = 0; r < 3; ++r) { + for (int c = 0; c < 3; ++c) { + elt[r][c] = any[r * 3 + c]; + } + } +} + + +Matrix3::operator Any() const { + Any any(Any::ARRAY, "Matrix3"); + any.resize(9); + for (int r = 0; r < 3; ++r) { + for (int c = 0; c < 3; ++c) { + any[r * 3 + c] = elt[r][c]; + } + } + + return any; +} + +const Matrix3& Matrix3::zero() { + static Matrix3 m(0, 0, 0, 0, 0, 0, 0, 0, 0); + return m; +} + +const Matrix3& Matrix3::identity() { + static Matrix3 m(1, 0, 0, 0, 1, 0, 0, 0, 1); + return m; +} + + +const float Matrix3::ms_fSvdEpsilon = 1e-04f; +const int Matrix3::ms_iSvdMaxIterations = 32; + +Matrix3::Matrix3(BinaryInput& b) { + deserialize(b); +} + +bool Matrix3::fuzzyEq(const Matrix3& b) const { + for (int r = 0; r < 3; ++r) { + for (int c = 0; c < 3; ++c) { + if (! G3D::fuzzyEq(elt[r][c], b[r][c])) { + return false; + } + } + } + return true; +} + + +bool Matrix3::isRightHanded() const{ + + const Vector3& X = column(0); + const Vector3& Y = column(1); + const Vector3& Z = column(2); + + const Vector3& W = X.cross(Y); + + return W.dot(Z) > 0.0f; +} + + +bool Matrix3::isOrthonormal() const { + const Vector3& X = column(0); + const Vector3& Y = column(1); + const Vector3& Z = column(2); + + return + (G3D::fuzzyEq(X.dot(Y), 0.0f) && + G3D::fuzzyEq(Y.dot(Z), 0.0f) && + G3D::fuzzyEq(X.dot(Z), 0.0f) && + G3D::fuzzyEq(X.squaredMagnitude(), 1.0f) && + G3D::fuzzyEq(Y.squaredMagnitude(), 1.0f) && + G3D::fuzzyEq(Z.squaredMagnitude(), 1.0f)); +} + +//---------------------------------------------------------------------------- +Matrix3::Matrix3(const Quat& _q) { + // Implementation from Watt and Watt, pg 362 + // See also http://www.flipcode.com/documents/matrfaq.html#Q54 + Quat q = _q; + q.unitize(); + float xx = 2.0f * q.x * q.x; + float xy = 2.0f * q.x * q.y; + float xz = 2.0f * q.x * q.z; + float xw = 2.0f * q.x * q.w; + + float yy = 2.0f * q.y * q.y; + float yz = 2.0f * q.y * q.z; + float yw = 2.0f * q.y * q.w; + + float zz = 2.0f * q.z * q.z; + float zw = 2.0f * q.z * q.w; + + set(1.0f - yy - zz, xy - zw, xz + yw, + xy + zw, 1.0f - xx - zz, yz - xw, + xz - yw, yz + xw, 1.0f - xx - yy); +} + +//---------------------------------------------------------------------------- + +Matrix3::Matrix3 (const float aafEntry[3][3]) { + memcpy(elt, aafEntry, 9*sizeof(float)); +} + +//---------------------------------------------------------------------------- +Matrix3::Matrix3 (const Matrix3& rkMatrix) { + memcpy(elt, rkMatrix.elt, 9*sizeof(float)); +} + +//---------------------------------------------------------------------------- +Matrix3::Matrix3( + float fEntry00, float fEntry01, float fEntry02, + float fEntry10, float fEntry11, float fEntry12, + float fEntry20, float fEntry21, float fEntry22) { + set(fEntry00, fEntry01, fEntry02, + fEntry10, fEntry11, fEntry12, + fEntry20, fEntry21, fEntry22); +} + +void Matrix3::set( + float fEntry00, float fEntry01, float fEntry02, + float fEntry10, float fEntry11, float fEntry12, + float fEntry20, float fEntry21, float fEntry22) { + + elt[0][0] = fEntry00; + elt[0][1] = fEntry01; + elt[0][2] = fEntry02; + elt[1][0] = fEntry10; + elt[1][1] = fEntry11; + elt[1][2] = fEntry12; + elt[2][0] = fEntry20; + elt[2][1] = fEntry21; + elt[2][2] = fEntry22; +} + + +void Matrix3::deserialize(BinaryInput& b) { + int r,c; + for (c = 0; c < 3; ++c) { + for (r = 0; r < 3; ++r) { + elt[r][c] = b.readFloat32(); + } + } +} + + +void Matrix3::serialize(BinaryOutput& b) const { + int r,c; + for (c = 0; c < 3; ++c) { + for (r = 0; r < 3; ++r) { + b.writeFloat32(elt[r][c]); + } + } +} + + +//---------------------------------------------------------------------------- +Vector3 Matrix3::column (int iCol) const { + assert((0 <= iCol) && (iCol < 3)); + return Vector3(elt[0][iCol], elt[1][iCol], + elt[2][iCol]); +} + + +const Vector3& Matrix3::row (int iRow) const { + assert((0 <= iRow) && (iRow < 3)); + return *reinterpret_cast(elt[iRow]); +} + + +void Matrix3::setColumn(int iCol, const Vector3 &vector) { + debugAssert((iCol >= 0) && (iCol < 3)); + elt[0][iCol] = vector.x; + elt[1][iCol] = vector.y; + elt[2][iCol] = vector.z; +} + + +void Matrix3::setRow(int iRow, const Vector3 &vector) { + debugAssert((iRow >= 0) && (iRow < 3)); + elt[iRow][0] = vector.x; + elt[iRow][1] = vector.y; + elt[iRow][2] = vector.z; +} + + +//---------------------------------------------------------------------------- +bool Matrix3::operator== (const Matrix3& rkMatrix) const { + for (int iRow = 0; iRow < 3; iRow++) { + for (int iCol = 0; iCol < 3; iCol++) { + if ( elt[iRow][iCol] != rkMatrix.elt[iRow][iCol] ) + return false; + } + } + + return true; +} + +//---------------------------------------------------------------------------- +bool Matrix3::operator!= (const Matrix3& rkMatrix) const { + return !operator==(rkMatrix); +} + +//---------------------------------------------------------------------------- +Matrix3 Matrix3::operator+ (const Matrix3& rkMatrix) const { + Matrix3 kSum; + + for (int iRow = 0; iRow < 3; iRow++) { + for (int iCol = 0; iCol < 3; iCol++) { + kSum.elt[iRow][iCol] = elt[iRow][iCol] + + rkMatrix.elt[iRow][iCol]; + } + } + + return kSum; +} + +//---------------------------------------------------------------------------- +Matrix3 Matrix3::operator- (const Matrix3& rkMatrix) const { + Matrix3 kDiff; + + for (int iRow = 0; iRow < 3; iRow++) { + for (int iCol = 0; iCol < 3; iCol++) { + kDiff.elt[iRow][iCol] = elt[iRow][iCol] - + rkMatrix.elt[iRow][iCol]; + } + } + + return kDiff; +} + +//---------------------------------------------------------------------------- +Matrix3 Matrix3::operator* (const Matrix3& rkMatrix) const { + Matrix3 kProd; + + for (int iRow = 0; iRow < 3; iRow++) { + for (int iCol = 0; iCol < 3; iCol++) { + kProd.elt[iRow][iCol] = + elt[iRow][0] * rkMatrix.elt[0][iCol] + + elt[iRow][1] * rkMatrix.elt[1][iCol] + + elt[iRow][2] * rkMatrix.elt[2][iCol]; + } + } + + return kProd; +} + +Matrix3& Matrix3::operator+= (const Matrix3& rkMatrix) { + for (int iRow = 0; iRow < 3; iRow++) { + for (int iCol = 0; iCol < 3; iCol++) { + elt[iRow][iCol] = elt[iRow][iCol] + rkMatrix.elt[iRow][iCol]; + } + } + + return *this; +} + +Matrix3& Matrix3::operator-= (const Matrix3& rkMatrix) { + for (int iRow = 0; iRow < 3; iRow++) { + for (int iCol = 0; iCol < 3; iCol++) { + elt[iRow][iCol] = elt[iRow][iCol] - rkMatrix.elt[iRow][iCol]; + } + } + + return *this; +} + +Matrix3& Matrix3::operator*= (const Matrix3& rkMatrix) { + Matrix3 mulMat; + for (int iRow = 0; iRow < 3; iRow++) { + for (int iCol = 0; iCol < 3; iCol++) { + mulMat.elt[iRow][iCol] = + elt[iRow][0] * rkMatrix.elt[0][iCol] + + elt[iRow][1] * rkMatrix.elt[1][iCol] + + elt[iRow][2] * rkMatrix.elt[2][iCol]; + } + } + + *this = mulMat; + return *this; +} + +//---------------------------------------------------------------------------- +Matrix3 Matrix3::operator- () const { + Matrix3 kNeg; + + for (int iRow = 0; iRow < 3; iRow++) { + for (int iCol = 0; iCol < 3; iCol++) { + kNeg[iRow][iCol] = -elt[iRow][iCol]; + } + } + + return kNeg; +} + +//---------------------------------------------------------------------------- +Matrix3 Matrix3::operator* (float fScalar) const { + Matrix3 kProd; + + for (int iRow = 0; iRow < 3; iRow++) { + for (int iCol = 0; iCol < 3; iCol++) { + kProd[iRow][iCol] = fScalar * elt[iRow][iCol]; + } + } + + return kProd; +} + +Matrix3& Matrix3::operator/= (float fScalar) { + return *this *= (1.0f / fScalar); +} + +Matrix3& Matrix3::operator*= (float fScalar) { + + for (int iRow = 0; iRow < 3; iRow++) { + for (int iCol = 0; iCol < 3; iCol++) { + elt[iRow][iCol] *= fScalar; + } + } + + return *this; +} + +//---------------------------------------------------------------------------- +Matrix3 operator* (double fScalar, const Matrix3& rkMatrix) { + Matrix3 kProd; + + for (int iRow = 0; iRow < 3; iRow++) { + for (int iCol = 0; iCol < 3; iCol++) { + kProd[iRow][iCol] = fScalar * rkMatrix.elt[iRow][iCol]; + } + } + + return kProd; +} + +Matrix3 operator* (float fScalar, const Matrix3& rkMatrix) { + return (double)fScalar * rkMatrix; +} + + +Matrix3 operator* (int fScalar, const Matrix3& rkMatrix) { + return (double)fScalar * rkMatrix; +} +//---------------------------------------------------------------------------- +Matrix3 Matrix3::transpose () const { + Matrix3 kTranspose; + + for (int iRow = 0; iRow < 3; iRow++) { + for (int iCol = 0; iCol < 3; iCol++) { + kTranspose[iRow][iCol] = elt[iCol][iRow]; + } + } + + return kTranspose; +} + +//---------------------------------------------------------------------------- +bool Matrix3::inverse (Matrix3& rkInverse, float fTolerance) const { + // Invert a 3x3 using cofactors. This is about 8 times faster than + // the Numerical Recipes code which uses Gaussian elimination. + + rkInverse[0][0] = elt[1][1] * elt[2][2] - + elt[1][2] * elt[2][1]; + rkInverse[0][1] = elt[0][2] * elt[2][1] - + elt[0][1] * elt[2][2]; + rkInverse[0][2] = elt[0][1] * elt[1][2] - + elt[0][2] * elt[1][1]; + rkInverse[1][0] = elt[1][2] * elt[2][0] - + elt[1][0] * elt[2][2]; + rkInverse[1][1] = elt[0][0] * elt[2][2] - + elt[0][2] * elt[2][0]; + rkInverse[1][2] = elt[0][2] * elt[1][0] - + elt[0][0] * elt[1][2]; + rkInverse[2][0] = elt[1][0] * elt[2][1] - + elt[1][1] * elt[2][0]; + rkInverse[2][1] = elt[0][1] * elt[2][0] - + elt[0][0] * elt[2][1]; + rkInverse[2][2] = elt[0][0] * elt[1][1] - + elt[0][1] * elt[1][0]; + + float fDet = + elt[0][0] * rkInverse[0][0] + + elt[0][1] * rkInverse[1][0] + + elt[0][2] * rkInverse[2][0]; + + if ( G3D::abs(fDet) <= fTolerance ) + return false; + + float fInvDet = 1.0 / fDet; + + for (int iRow = 0; iRow < 3; iRow++) { + for (int iCol = 0; iCol < 3; iCol++) + rkInverse[iRow][iCol] *= fInvDet; + } + + return true; +} + +//---------------------------------------------------------------------------- +Matrix3 Matrix3::inverse (float fTolerance) const { + Matrix3 kInverse = Matrix3::zero(); + inverse(kInverse, fTolerance); + return kInverse; +} + +//---------------------------------------------------------------------------- +float Matrix3::determinant () const { + float fCofactor00 = elt[1][1] * elt[2][2] - + elt[1][2] * elt[2][1]; + float fCofactor10 = elt[1][2] * elt[2][0] - + elt[1][0] * elt[2][2]; + float fCofactor20 = elt[1][0] * elt[2][1] - + elt[1][1] * elt[2][0]; + + float fDet = + elt[0][0] * fCofactor00 + + elt[0][1] * fCofactor10 + + elt[0][2] * fCofactor20; + + return fDet; +} + +//---------------------------------------------------------------------------- +void Matrix3::bidiagonalize (Matrix3& kA, Matrix3& kL, + Matrix3& kR) { + float afV[3], afW[3]; + float fLength, fSign, fT1, fInvT1, fT2; + bool bIdentity; + + // map first column to (*,0,0) + fLength = sqrt(kA[0][0] * kA[0][0] + kA[1][0] * kA[1][0] + + kA[2][0] * kA[2][0]); + + if ( fLength > 0.0 ) { + fSign = (kA[0][0] > 0.0 ? 1.0 : -1.0); + fT1 = kA[0][0] + fSign * fLength; + fInvT1 = 1.0 / fT1; + afV[1] = kA[1][0] * fInvT1; + afV[2] = kA[2][0] * fInvT1; + + fT2 = -2.0 / (1.0 + afV[1] * afV[1] + afV[2] * afV[2]); + afW[0] = fT2 * (kA[0][0] + kA[1][0] * afV[1] + kA[2][0] * afV[2]); + afW[1] = fT2 * (kA[0][1] + kA[1][1] * afV[1] + kA[2][1] * afV[2]); + afW[2] = fT2 * (kA[0][2] + kA[1][2] * afV[1] + kA[2][2] * afV[2]); + kA[0][0] += afW[0]; + kA[0][1] += afW[1]; + kA[0][2] += afW[2]; + kA[1][1] += afV[1] * afW[1]; + kA[1][2] += afV[1] * afW[2]; + kA[2][1] += afV[2] * afW[1]; + kA[2][2] += afV[2] * afW[2]; + + kL[0][0] = 1.0 + fT2; + kL[0][1] = kL[1][0] = fT2 * afV[1]; + kL[0][2] = kL[2][0] = fT2 * afV[2]; + kL[1][1] = 1.0 + fT2 * afV[1] * afV[1]; + kL[1][2] = kL[2][1] = fT2 * afV[1] * afV[2]; + kL[2][2] = 1.0 + fT2 * afV[2] * afV[2]; + bIdentity = false; + } else { + kL = Matrix3::identity(); + bIdentity = true; + } + + // map first row to (*,*,0) + fLength = sqrt(kA[0][1] * kA[0][1] + kA[0][2] * kA[0][2]); + + if ( fLength > 0.0 ) { + fSign = (kA[0][1] > 0.0 ? 1.0 : -1.0); + fT1 = kA[0][1] + fSign * fLength; + afV[2] = kA[0][2] / fT1; + + fT2 = -2.0 / (1.0 + afV[2] * afV[2]); + afW[0] = fT2 * (kA[0][1] + kA[0][2] * afV[2]); + afW[1] = fT2 * (kA[1][1] + kA[1][2] * afV[2]); + afW[2] = fT2 * (kA[2][1] + kA[2][2] * afV[2]); + kA[0][1] += afW[0]; + kA[1][1] += afW[1]; + kA[1][2] += afW[1] * afV[2]; + kA[2][1] += afW[2]; + kA[2][2] += afW[2] * afV[2]; + + kR[0][0] = 1.0; + kR[0][1] = kR[1][0] = 0.0; + kR[0][2] = kR[2][0] = 0.0; + kR[1][1] = 1.0 + fT2; + kR[1][2] = kR[2][1] = fT2 * afV[2]; + kR[2][2] = 1.0 + fT2 * afV[2] * afV[2]; + } else { + kR = Matrix3::identity(); + } + + // map second column to (*,*,0) + fLength = sqrt(kA[1][1] * kA[1][1] + kA[2][1] * kA[2][1]); + + if ( fLength > 0.0 ) { + fSign = (kA[1][1] > 0.0 ? 1.0 : -1.0); + fT1 = kA[1][1] + fSign * fLength; + afV[2] = kA[2][1] / fT1; + + fT2 = -2.0 / (1.0 + afV[2] * afV[2]); + afW[1] = fT2 * (kA[1][1] + kA[2][1] * afV[2]); + afW[2] = fT2 * (kA[1][2] + kA[2][2] * afV[2]); + kA[1][1] += afW[1]; + kA[1][2] += afW[2]; + kA[2][2] += afV[2] * afW[2]; + + float fA = 1.0 + fT2; + float fB = fT2 * afV[2]; + float fC = 1.0 + fB * afV[2]; + + if ( bIdentity ) { + kL[0][0] = 1.0; + kL[0][1] = kL[1][0] = 0.0; + kL[0][2] = kL[2][0] = 0.0; + kL[1][1] = fA; + kL[1][2] = kL[2][1] = fB; + kL[2][2] = fC; + } else { + for (int iRow = 0; iRow < 3; iRow++) { + float fTmp0 = kL[iRow][1]; + float fTmp1 = kL[iRow][2]; + kL[iRow][1] = fA * fTmp0 + fB * fTmp1; + kL[iRow][2] = fB * fTmp0 + fC * fTmp1; + } + } + } +} + +//---------------------------------------------------------------------------- +void Matrix3::golubKahanStep (Matrix3& kA, Matrix3& kL, + Matrix3& kR) { + float fT11 = kA[0][1] * kA[0][1] + kA[1][1] * kA[1][1]; + float fT22 = kA[1][2] * kA[1][2] + kA[2][2] * kA[2][2]; + float fT12 = kA[1][1] * kA[1][2]; + float fTrace = fT11 + fT22; + float fDiff = fT11 - fT22; + float fDiscr = sqrt(fDiff * fDiff + 4.0 * fT12 * fT12); + float fRoot1 = 0.5 * (fTrace + fDiscr); + float fRoot2 = 0.5 * (fTrace - fDiscr); + + // adjust right + float fY = kA[0][0] - (G3D::abs(fRoot1 - fT22) <= + G3D::abs(fRoot2 - fT22) ? fRoot1 : fRoot2); + float fZ = kA[0][1]; + float fInvLength = 1.0 / sqrt(fY * fY + fZ * fZ); + float fSin = fZ * fInvLength; + float fCos = -fY * fInvLength; + + float fTmp0 = kA[0][0]; + float fTmp1 = kA[0][1]; + kA[0][0] = fCos * fTmp0 - fSin * fTmp1; + kA[0][1] = fSin * fTmp0 + fCos * fTmp1; + kA[1][0] = -fSin * kA[1][1]; + kA[1][1] *= fCos; + + int iRow; + + for (iRow = 0; iRow < 3; iRow++) { + fTmp0 = kR[0][iRow]; + fTmp1 = kR[1][iRow]; + kR[0][iRow] = fCos * fTmp0 - fSin * fTmp1; + kR[1][iRow] = fSin * fTmp0 + fCos * fTmp1; + } + + // adjust left + fY = kA[0][0]; + + fZ = kA[1][0]; + + fInvLength = 1.0 / sqrt(fY * fY + fZ * fZ); + + fSin = fZ * fInvLength; + + fCos = -fY * fInvLength; + + kA[0][0] = fCos * kA[0][0] - fSin * kA[1][0]; + + fTmp0 = kA[0][1]; + + fTmp1 = kA[1][1]; + + kA[0][1] = fCos * fTmp0 - fSin * fTmp1; + + kA[1][1] = fSin * fTmp0 + fCos * fTmp1; + + kA[0][2] = -fSin * kA[1][2]; + + kA[1][2] *= fCos; + + int iCol; + + for (iCol = 0; iCol < 3; iCol++) { + fTmp0 = kL[iCol][0]; + fTmp1 = kL[iCol][1]; + kL[iCol][0] = fCos * fTmp0 - fSin * fTmp1; + kL[iCol][1] = fSin * fTmp0 + fCos * fTmp1; + } + + // adjust right + fY = kA[0][1]; + + fZ = kA[0][2]; + + fInvLength = 1.0 / sqrt(fY * fY + fZ * fZ); + + fSin = fZ * fInvLength; + + fCos = -fY * fInvLength; + + kA[0][1] = fCos * kA[0][1] - fSin * kA[0][2]; + + fTmp0 = kA[1][1]; + + fTmp1 = kA[1][2]; + + kA[1][1] = fCos * fTmp0 - fSin * fTmp1; + + kA[1][2] = fSin * fTmp0 + fCos * fTmp1; + + kA[2][1] = -fSin * kA[2][2]; + + kA[2][2] *= fCos; + + for (iRow = 0; iRow < 3; iRow++) { + fTmp0 = kR[1][iRow]; + fTmp1 = kR[2][iRow]; + kR[1][iRow] = fCos * fTmp0 - fSin * fTmp1; + kR[2][iRow] = fSin * fTmp0 + fCos * fTmp1; + } + + // adjust left + fY = kA[1][1]; + + fZ = kA[2][1]; + + fInvLength = 1.0 / sqrt(fY * fY + fZ * fZ); + + fSin = fZ * fInvLength; + + fCos = -fY * fInvLength; + + kA[1][1] = fCos * kA[1][1] - fSin * kA[2][1]; + + fTmp0 = kA[1][2]; + + fTmp1 = kA[2][2]; + + kA[1][2] = fCos * fTmp0 - fSin * fTmp1; + + kA[2][2] = fSin * fTmp0 + fCos * fTmp1; + + for (iCol = 0; iCol < 3; iCol++) { + fTmp0 = kL[iCol][1]; + fTmp1 = kL[iCol][2]; + kL[iCol][1] = fCos * fTmp0 - fSin * fTmp1; + kL[iCol][2] = fSin * fTmp0 + fCos * fTmp1; + } +} + +//---------------------------------------------------------------------------- +void Matrix3::singularValueDecomposition (Matrix3& kL, Vector3& kS, + Matrix3& kR) const { + int iRow, iCol; + + Matrix3 kA = *this; + bidiagonalize(kA, kL, kR); + + for (int i = 0; i < ms_iSvdMaxIterations; i++) { + float fTmp, fTmp0, fTmp1; + float fSin0, fCos0, fTan0; + float fSin1, fCos1, fTan1; + + bool bTest1 = (G3D::abs(kA[0][1]) <= + ms_fSvdEpsilon * (G3D::abs(kA[0][0]) + G3D::abs(kA[1][1]))); + bool bTest2 = (G3D::abs(kA[1][2]) <= + ms_fSvdEpsilon * (G3D::abs(kA[1][1]) + G3D::abs(kA[2][2]))); + + if ( bTest1 ) { + if ( bTest2 ) { + kS[0] = kA[0][0]; + kS[1] = kA[1][1]; + kS[2] = kA[2][2]; + break; + } else { + // 2x2 closed form factorization + fTmp = (kA[1][1] * kA[1][1] - kA[2][2] * kA[2][2] + + kA[1][2] * kA[1][2]) / (kA[1][2] * kA[2][2]); + fTan0 = 0.5 * (fTmp + sqrt(fTmp * fTmp + 4.0)); + fCos0 = 1.0 / sqrt(1.0 + fTan0 * fTan0); + fSin0 = fTan0 * fCos0; + + for (iCol = 0; iCol < 3; iCol++) { + fTmp0 = kL[iCol][1]; + fTmp1 = kL[iCol][2]; + kL[iCol][1] = fCos0 * fTmp0 - fSin0 * fTmp1; + kL[iCol][2] = fSin0 * fTmp0 + fCos0 * fTmp1; + } + + fTan1 = (kA[1][2] - kA[2][2] * fTan0) / kA[1][1]; + fCos1 = 1.0 / sqrt(1.0 + fTan1 * fTan1); + fSin1 = -fTan1 * fCos1; + + for (iRow = 0; iRow < 3; iRow++) { + fTmp0 = kR[1][iRow]; + fTmp1 = kR[2][iRow]; + kR[1][iRow] = fCos1 * fTmp0 - fSin1 * fTmp1; + kR[2][iRow] = fSin1 * fTmp0 + fCos1 * fTmp1; + } + + kS[0] = kA[0][0]; + kS[1] = fCos0 * fCos1 * kA[1][1] - + fSin1 * (fCos0 * kA[1][2] - fSin0 * kA[2][2]); + kS[2] = fSin0 * fSin1 * kA[1][1] + + fCos1 * (fSin0 * kA[1][2] + fCos0 * kA[2][2]); + break; + } + } else { + if ( bTest2 ) { + // 2x2 closed form factorization + fTmp = (kA[0][0] * kA[0][0] + kA[1][1] * kA[1][1] - + kA[0][1] * kA[0][1]) / (kA[0][1] * kA[1][1]); + fTan0 = 0.5 * ( -fTmp + sqrt(fTmp * fTmp + 4.0)); + fCos0 = 1.0 / sqrt(1.0 + fTan0 * fTan0); + fSin0 = fTan0 * fCos0; + + for (iCol = 0; iCol < 3; iCol++) { + fTmp0 = kL[iCol][0]; + fTmp1 = kL[iCol][1]; + kL[iCol][0] = fCos0 * fTmp0 - fSin0 * fTmp1; + kL[iCol][1] = fSin0 * fTmp0 + fCos0 * fTmp1; + } + + fTan1 = (kA[0][1] - kA[1][1] * fTan0) / kA[0][0]; + fCos1 = 1.0 / sqrt(1.0 + fTan1 * fTan1); + fSin1 = -fTan1 * fCos1; + + for (iRow = 0; iRow < 3; iRow++) { + fTmp0 = kR[0][iRow]; + fTmp1 = kR[1][iRow]; + kR[0][iRow] = fCos1 * fTmp0 - fSin1 * fTmp1; + kR[1][iRow] = fSin1 * fTmp0 + fCos1 * fTmp1; + } + + kS[0] = fCos0 * fCos1 * kA[0][0] - + fSin1 * (fCos0 * kA[0][1] - fSin0 * kA[1][1]); + kS[1] = fSin0 * fSin1 * kA[0][0] + + fCos1 * (fSin0 * kA[0][1] + fCos0 * kA[1][1]); + kS[2] = kA[2][2]; + break; + } else { + golubKahanStep(kA, kL, kR); + } + } + } + + // positize diagonal + for (iRow = 0; iRow < 3; iRow++) { + if ( kS[iRow] < 0.0 ) { + kS[iRow] = -kS[iRow]; + + for (iCol = 0; iCol < 3; iCol++) + kR[iRow][iCol] = -kR[iRow][iCol]; + } + } +} + +//---------------------------------------------------------------------------- +void Matrix3::singularValueComposition (const Matrix3& kL, + const Vector3& kS, const Matrix3& kR) { + int iRow, iCol; + Matrix3 kTmp; + + // product S*R + for (iRow = 0; iRow < 3; iRow++) { + for (iCol = 0; iCol < 3; iCol++) + kTmp[iRow][iCol] = kS[iRow] * kR[iRow][iCol]; + } + + // product L*S*R + for (iRow = 0; iRow < 3; iRow++) { + for (iCol = 0; iCol < 3; iCol++) { + elt[iRow][iCol] = 0.0; + + for (int iMid = 0; iMid < 3; iMid++) + elt[iRow][iCol] += kL[iRow][iMid] * kTmp[iMid][iCol]; + } + } +} + +//---------------------------------------------------------------------------- +void Matrix3::orthonormalize () { + // Algorithm uses Gram-Schmidt orthogonalization. If 'this' matrix is + // M = [m0|m1|m2], then orthonormal output matrix is Q = [q0|q1|q2], + // + // q0 = m0/|m0| + // q1 = (m1-(q0*m1)q0)/|m1-(q0*m1)q0| + // q2 = (m2-(q0*m2)q0-(q1*m2)q1)/|m2-(q0*m2)q0-(q1*m2)q1| + // + // where |V| indicates length of vector V and A*B indicates dot + // product of vectors A and B. + + // compute q0 + float fInvLength = 1.0 / sqrt(elt[0][0] * elt[0][0] + + elt[1][0] * elt[1][0] + + elt[2][0] * elt[2][0]); + + elt[0][0] *= fInvLength; + elt[1][0] *= fInvLength; + elt[2][0] *= fInvLength; + + // compute q1 + float fDot0 = + elt[0][0] * elt[0][1] + + elt[1][0] * elt[1][1] + + elt[2][0] * elt[2][1]; + + elt[0][1] -= fDot0 * elt[0][0]; + elt[1][1] -= fDot0 * elt[1][0]; + elt[2][1] -= fDot0 * elt[2][0]; + + fInvLength = 1.0 / sqrt(elt[0][1] * elt[0][1] + + elt[1][1] * elt[1][1] + + elt[2][1] * elt[2][1]); + + elt[0][1] *= fInvLength; + elt[1][1] *= fInvLength; + elt[2][1] *= fInvLength; + + // compute q2 + float fDot1 = + elt[0][1] * elt[0][2] + + elt[1][1] * elt[1][2] + + elt[2][1] * elt[2][2]; + + fDot0 = + elt[0][0] * elt[0][2] + + elt[1][0] * elt[1][2] + + elt[2][0] * elt[2][2]; + + elt[0][2] -= fDot0 * elt[0][0] + fDot1 * elt[0][1]; + elt[1][2] -= fDot0 * elt[1][0] + fDot1 * elt[1][1]; + elt[2][2] -= fDot0 * elt[2][0] + fDot1 * elt[2][1]; + + fInvLength = 1.0 / sqrt(elt[0][2] * elt[0][2] + + elt[1][2] * elt[1][2] + + elt[2][2] * elt[2][2]); + + elt[0][2] *= fInvLength; + elt[1][2] *= fInvLength; + elt[2][2] *= fInvLength; +} + +//---------------------------------------------------------------------------- +void Matrix3::qDUDecomposition (Matrix3& kQ, + Vector3& kD, Vector3& kU) const { + // Factor M = QR = QDU where Q is orthogonal, D is diagonal, + // and U is upper triangular with ones on its diagonal. Algorithm uses + // Gram-Schmidt orthogonalization (the QR algorithm). + // + // If M = [ m0 | m1 | m2 ] and Q = [ q0 | q1 | q2 ], then + // + // q0 = m0/|m0| + // q1 = (m1-(q0*m1)q0)/|m1-(q0*m1)q0| + // q2 = (m2-(q0*m2)q0-(q1*m2)q1)/|m2-(q0*m2)q0-(q1*m2)q1| + // + // where |V| indicates length of vector V and A*B indicates dot + // product of vectors A and B. The matrix R has entries + // + // r00 = q0*m0 r01 = q0*m1 r02 = q0*m2 + // r10 = 0 r11 = q1*m1 r12 = q1*m2 + // r20 = 0 r21 = 0 r22 = q2*m2 + // + // so D = diag(r00,r11,r22) and U has entries u01 = r01/r00, + // u02 = r02/r00, and u12 = r12/r11. + + // Q = rotation + // D = scaling + // U = shear + + // D stores the three diagonal entries r00, r11, r22 + // U stores the entries U[0] = u01, U[1] = u02, U[2] = u12 + + // build orthogonal matrix Q + float fInvLength = 1.0 / sqrt(elt[0][0] * elt[0][0] + + elt[1][0] * elt[1][0] + + elt[2][0] * elt[2][0]); + kQ[0][0] = elt[0][0] * fInvLength; + kQ[1][0] = elt[1][0] * fInvLength; + kQ[2][0] = elt[2][0] * fInvLength; + + float fDot = kQ[0][0] * elt[0][1] + kQ[1][0] * elt[1][1] + + kQ[2][0] * elt[2][1]; + kQ[0][1] = elt[0][1] - fDot * kQ[0][0]; + kQ[1][1] = elt[1][1] - fDot * kQ[1][0]; + kQ[2][1] = elt[2][1] - fDot * kQ[2][0]; + fInvLength = 1.0 / sqrt(kQ[0][1] * kQ[0][1] + kQ[1][1] * kQ[1][1] + + kQ[2][1] * kQ[2][1]); + kQ[0][1] *= fInvLength; + kQ[1][1] *= fInvLength; + kQ[2][1] *= fInvLength; + + fDot = kQ[0][0] * elt[0][2] + kQ[1][0] * elt[1][2] + + kQ[2][0] * elt[2][2]; + kQ[0][2] = elt[0][2] - fDot * kQ[0][0]; + kQ[1][2] = elt[1][2] - fDot * kQ[1][0]; + kQ[2][2] = elt[2][2] - fDot * kQ[2][0]; + fDot = kQ[0][1] * elt[0][2] + kQ[1][1] * elt[1][2] + + kQ[2][1] * elt[2][2]; + kQ[0][2] -= fDot * kQ[0][1]; + kQ[1][2] -= fDot * kQ[1][1]; + kQ[2][2] -= fDot * kQ[2][1]; + fInvLength = 1.0 / sqrt(kQ[0][2] * kQ[0][2] + kQ[1][2] * kQ[1][2] + + kQ[2][2] * kQ[2][2]); + kQ[0][2] *= fInvLength; + kQ[1][2] *= fInvLength; + kQ[2][2] *= fInvLength; + + // guarantee that orthogonal matrix has determinant 1 (no reflections) + float fDet = kQ[0][0] * kQ[1][1] * kQ[2][2] + kQ[0][1] * kQ[1][2] * kQ[2][0] + + kQ[0][2] * kQ[1][0] * kQ[2][1] - kQ[0][2] * kQ[1][1] * kQ[2][0] - + kQ[0][1] * kQ[1][0] * kQ[2][2] - kQ[0][0] * kQ[1][2] * kQ[2][1]; + + if ( fDet < 0.0 ) { + for (int iRow = 0; iRow < 3; iRow++) + for (int iCol = 0; iCol < 3; iCol++) + kQ[iRow][iCol] = -kQ[iRow][iCol]; + } + + // build "right" matrix R + Matrix3 kR; + + kR[0][0] = kQ[0][0] * elt[0][0] + kQ[1][0] * elt[1][0] + + kQ[2][0] * elt[2][0]; + + kR[0][1] = kQ[0][0] * elt[0][1] + kQ[1][0] * elt[1][1] + + kQ[2][0] * elt[2][1]; + + kR[1][1] = kQ[0][1] * elt[0][1] + kQ[1][1] * elt[1][1] + + kQ[2][1] * elt[2][1]; + + kR[0][2] = kQ[0][0] * elt[0][2] + kQ[1][0] * elt[1][2] + + kQ[2][0] * elt[2][2]; + + kR[1][2] = kQ[0][1] * elt[0][2] + kQ[1][1] * elt[1][2] + + kQ[2][1] * elt[2][2]; + + kR[2][2] = kQ[0][2] * elt[0][2] + kQ[1][2] * elt[1][2] + + kQ[2][2] * elt[2][2]; + + // the scaling component + kD[0] = kR[0][0]; + + kD[1] = kR[1][1]; + + kD[2] = kR[2][2]; + + // the shear component + float fInvD0 = 1.0 / kD[0]; + + kU[0] = kR[0][1] * fInvD0; + + kU[1] = kR[0][2] * fInvD0; + + kU[2] = kR[1][2] / kD[1]; +} + +//---------------------------------------------------------------------------- +void Matrix3::polarDecomposition(Matrix3 &R, Matrix3 &S) const{ + /* + Polar decomposition of a matrix. Based on pseudocode from + Nicholas J Higham, "Computing the Polar Decomposition -- with + Applications Siam Journal of Science and Statistical Computing, Vol 7, No. 4, + October 1986. + + Decomposes A into R*S, where R is orthogonal and S is symmetric. + + Ken Shoemake's "Matrix animation and polar decomposition" + in Proceedings of the conference on Graphics interface '92 + seems to be better known in the world of graphics, but Higham's version + uses a scaling constant that can lead to faster convergence than + Shoemake's when the initial matrix is far from orthogonal. + */ + + Matrix3 X = *this; + Matrix3 tmp = X.inverse(); + Matrix3 Xit = tmp.transpose(); + int iter = 0; + + const int MAX_ITERS = 100; + + const double eps = 50 * std::numeric_limits::epsilon(); + const float BigEps = 50 * eps; + + /* Higham suggests using OneNorm(Xit-X) < eps * OneNorm(X) + * as the convergence criterion, but OneNorm(X) should quickly + * settle down to something between 1 and 1.7, so just comparing + * with eps seems sufficient. + *--------------------------------------------------------------- */ + + double resid = X.diffOneNorm(Xit); + while (resid > eps && iter < MAX_ITERS) { + + tmp = X.inverse(); + Xit = tmp.transpose(); + + if (resid < BigEps) { + // close enough use simple iteration + X += Xit; + X *= 0.5f; + } + else { + // not close to convergence, compute acceleration factor + float gamma = sqrt( sqrt( + (Xit.l1Norm()* Xit.lInfNorm())/(X.l1Norm()*X.lInfNorm()) ) ); + + X *= 0.5f * gamma; + tmp = Xit; + tmp *= 0.5f / gamma; + X += tmp; + } + + resid = X.diffOneNorm(Xit); + iter++; + } + + R = X; + tmp = R.transpose(); + + S = tmp * (*this); + + // S := (S + S^t)/2 one more time to make sure it is symmetric + tmp = S.transpose(); + + S += tmp; + S *= 0.5f; + +#ifdef G3D_DEBUG + // Check iter limit + assert(iter < MAX_ITERS); + + // Check A = R*S + tmp = R*S; + resid = tmp.diffOneNorm(*this); + assert(resid < eps); + + // Check R is orthogonal + tmp = R*R.transpose(); + resid = tmp.diffOneNorm(Matrix3::identity()); + assert(resid < eps); + + // Check that S is symmetric + tmp = S.transpose(); + resid = tmp.diffOneNorm(S); + assert(resid < eps); +#endif +} + +//---------------------------------------------------------------------------- +float Matrix3::maxCubicRoot (float afCoeff[3]) { + // Spectral norm is for A^T*A, so characteristic polynomial + // P(x) = c[0]+c[1]*x+c[2]*x^2+x^3 has three positive float roots. + // This yields the assertions c[0] < 0 and c[2]*c[2] >= 3*c[1]. + + // quick out for uniform scale (triple root) + const float fOneThird = 1.0f / 3.0f; + const float fEpsilon = 1e-06f; + float fDiscr = afCoeff[2] * afCoeff[2] - 3.0f * afCoeff[1]; + + if ( fDiscr <= fEpsilon ) + return -fOneThird*afCoeff[2]; + + // Compute an upper bound on roots of P(x). This assumes that A^T*A + // has been scaled by its largest entry. + float fX = 1.0f; + + float fPoly = afCoeff[0] + fX * (afCoeff[1] + fX * (afCoeff[2] + fX)); + + if ( fPoly < 0.0f ) { + // uses a matrix norm to find an upper bound on maximum root + fX = G3D::abs(afCoeff[0]); + float fTmp = 1.0 + G3D::abs(afCoeff[1]); + + if ( fTmp > fX ) + fX = fTmp; + + fTmp = 1.0 + G3D::abs(afCoeff[2]); + + if ( fTmp > fX ) + fX = fTmp; + } + + // Newton's method to find root + float fTwoC2 = 2.0f * afCoeff[2]; + + for (int i = 0; i < 16; i++) { + fPoly = afCoeff[0] + fX * (afCoeff[1] + fX * (afCoeff[2] + fX)); + + if ( G3D::abs(fPoly) <= fEpsilon ) + return fX; + + float fDeriv = afCoeff[1] + fX * (fTwoC2 + 3.0f * fX); + + fX -= fPoly / fDeriv; + } + + return fX; +} + +//---------------------------------------------------------------------------- +float Matrix3::spectralNorm () const { + Matrix3 kP; + int iRow, iCol; + float fPmax = 0.0; + + for (iRow = 0; iRow < 3; iRow++) { + for (iCol = 0; iCol < 3; iCol++) { + kP[iRow][iCol] = 0.0; + + for (int iMid = 0; iMid < 3; iMid++) { + kP[iRow][iCol] += + elt[iMid][iRow] * elt[iMid][iCol]; + } + + if ( kP[iRow][iCol] > fPmax ) + fPmax = kP[iRow][iCol]; + } + } + + float fInvPmax = 1.0 / fPmax; + + for (iRow = 0; iRow < 3; iRow++) { + for (iCol = 0; iCol < 3; iCol++) + kP[iRow][iCol] *= fInvPmax; + } + + float afCoeff[3]; + afCoeff[0] = -(kP[0][0] * (kP[1][1] * kP[2][2] - kP[1][2] * kP[2][1]) + + kP[0][1] * (kP[2][0] * kP[1][2] - kP[1][0] * kP[2][2]) + + kP[0][2] * (kP[1][0] * kP[2][1] - kP[2][0] * kP[1][1])); + afCoeff[1] = kP[0][0] * kP[1][1] - kP[0][1] * kP[1][0] + + kP[0][0] * kP[2][2] - kP[0][2] * kP[2][0] + + kP[1][1] * kP[2][2] - kP[1][2] * kP[2][1]; + afCoeff[2] = -(kP[0][0] + kP[1][1] + kP[2][2]); + + float fRoot = maxCubicRoot(afCoeff); + float fNorm = sqrt(fPmax * fRoot); + return fNorm; +} + +//---------------------------------------------------------------------------- +float Matrix3::squaredFrobeniusNorm() const { + float norm2 = 0; + const float* e = &elt[0][0]; + + for (int i = 0; i < 9; ++i){ + norm2 += (*e) * (*e); + } + + return norm2; +} + +//---------------------------------------------------------------------------- +float Matrix3::frobeniusNorm() const { + return sqrtf(squaredFrobeniusNorm()); +} + +//---------------------------------------------------------------------------- +float Matrix3::l1Norm() const { + // The one norm of a matrix is the max column sum in absolute value. + float oneNorm = 0; + for (int c = 0; c < 3; ++c) { + + float f = fabs(elt[0][c])+ fabs(elt[1][c]) + fabs(elt[2][c]); + + if (f > oneNorm) { + oneNorm = f; + } + } + return oneNorm; +} + +//---------------------------------------------------------------------------- +float Matrix3::lInfNorm() const { + // The infinity norm of a matrix is the max row sum in absolute value. + float infNorm = 0; + + for (int r = 0; r < 3; ++r) { + + float f = fabs(elt[r][0]) + fabs(elt[r][1])+ fabs(elt[r][2]); + + if (f > infNorm) { + infNorm = f; + } + } + return infNorm; +} + +//---------------------------------------------------------------------------- +float Matrix3::diffOneNorm(const Matrix3 &y) const{ + float oneNorm = 0; + + for (int c = 0; c < 3; ++c){ + + float f = fabs(elt[0][c] - y[0][c]) + fabs(elt[1][c] - y[1][c]) + + fabs(elt[2][c] - y[2][c]); + + if (f > oneNorm) { + oneNorm = f; + } + } + return oneNorm; +} + +//---------------------------------------------------------------------------- +void Matrix3::toAxisAngle (Vector3& rkAxis, float& rfRadians) const { + // + // Let (x,y,z) be the unit-length axis and let A be an angle of rotation. + // The rotation matrix is R = I + sin(A)*P + (1-cos(A))*P^2 (Rodrigues' formula) where + // I is the identity and + // + // +- -+ + // P = | 0 -z +y | + // | +z 0 -x | + // | -y +x 0 | + // +- -+ + // + // If A > 0, R represents a counterclockwise rotation about the axis in + // the sense of looking from the tip of the axis vector towards the + // origin. Some algebra will show that + // + // cos(A) = (trace(R)-1)/2 and R - R^t = 2*sin(A)*P + // + // In the event that A = pi, R-R^t = 0 which prevents us from extracting + // the axis through P. Instead note that R = I+2*P^2 when A = pi, so + // P^2 = (R-I)/2. The diagonal entries of P^2 are x^2-1, y^2-1, and + // z^2-1. We can solve these for axis (x,y,z). Because the angle is pi, + // it does not matter which sign you choose on the square roots. + + float fTrace = elt[0][0] + elt[1][1] + elt[2][2]; + float fCos = 0.5f * (fTrace - 1.0f); + rfRadians = G3D::aCos(fCos); // in [0,PI] + + if ( rfRadians > 0.0 ) { + if ( rfRadians < pi() ) { + rkAxis.x = elt[2][1] - elt[1][2]; + rkAxis.y = elt[0][2] - elt[2][0]; + rkAxis.z = elt[1][0] - elt[0][1]; + rkAxis.unitize(); + } else { + // angle is PI + float fHalfInverse; + + if ( elt[0][0] >= elt[1][1] ) { + // r00 >= r11 + if ( elt[0][0] >= elt[2][2] ) { + // r00 is maximum diagonal term + rkAxis.x = 0.5 * sqrt(elt[0][0] - + elt[1][1] - elt[2][2] + 1.0); + fHalfInverse = 0.5 / rkAxis.x; + rkAxis.y = fHalfInverse * elt[0][1]; + rkAxis.z = fHalfInverse * elt[0][2]; + } else { + // r22 is maximum diagonal term + rkAxis.z = 0.5 * sqrt(elt[2][2] - + elt[0][0] - elt[1][1] + 1.0); + fHalfInverse = 0.5 / rkAxis.z; + rkAxis.x = fHalfInverse * elt[0][2]; + rkAxis.y = fHalfInverse * elt[1][2]; + } + } else { + // r11 > r00 + if ( elt[1][1] >= elt[2][2] ) { + // r11 is maximum diagonal term + rkAxis.y = 0.5 * sqrt(elt[1][1] - + elt[0][0] - elt[2][2] + 1.0); + fHalfInverse = 0.5 / rkAxis.y; + rkAxis.x = fHalfInverse * elt[0][1]; + rkAxis.z = fHalfInverse * elt[1][2]; + } else { + // r22 is maximum diagonal term + rkAxis.z = 0.5 * sqrt(elt[2][2] - + elt[0][0] - elt[1][1] + 1.0); + fHalfInverse = 0.5 / rkAxis.z; + rkAxis.x = fHalfInverse * elt[0][2]; + rkAxis.y = fHalfInverse * elt[1][2]; + } + } + } + } else { + // The angle is 0 and the matrix is the identity. Any axis will + // work, so just use the x-axis. + rkAxis.x = 1.0; + rkAxis.y = 0.0; + rkAxis.z = 0.0; + } +} + +//---------------------------------------------------------------------------- +Matrix3 Matrix3::fromAxisAngle (const Vector3& _axis, float fRadians) { + Vector3 axis = _axis.direction(); + + Matrix3 m; + float fCos = cos(fRadians); + float fSin = sin(fRadians); + float fOneMinusCos = 1.0 - fCos; + float fX2 = square(axis.x); + float fY2 = square(axis.y); + float fZ2 = square(axis.z); + float fXYM = axis.x * axis.y * fOneMinusCos; + float fXZM = axis.x * axis.z * fOneMinusCos; + float fYZM = axis.y * axis.z * fOneMinusCos; + float fXSin = axis.x * fSin; + float fYSin = axis.y * fSin; + float fZSin = axis.z * fSin; + + m.elt[0][0] = fX2 * fOneMinusCos + fCos; + m.elt[0][1] = fXYM - fZSin; + m.elt[0][2] = fXZM + fYSin; + + m.elt[1][0] = fXYM + fZSin; + m.elt[1][1] = fY2 * fOneMinusCos + fCos; + m.elt[1][2] = fYZM - fXSin; + + m.elt[2][0] = fXZM - fYSin; + m.elt[2][1] = fYZM + fXSin; + m.elt[2][2] = fZ2 * fOneMinusCos + fCos; + + return m; +} + +//---------------------------------------------------------------------------- +bool Matrix3::toEulerAnglesXYZ (float& rfXAngle, float& rfYAngle, + float& rfZAngle) const { + // rot = cy*cz -cy*sz sy + // cz*sx*sy+cx*sz cx*cz-sx*sy*sz -cy*sx + // -cx*cz*sy+sx*sz cz*sx+cx*sy*sz cx*cy + + if ( elt[0][2] < 1.0f ) { + if ( elt[0][2] > -1.0f ) { + rfXAngle = G3D::aTan2( -elt[1][2], elt[2][2]); + rfYAngle = (float) G3D::aSin(elt[0][2]); + rfZAngle = G3D::aTan2( -elt[0][1], elt[0][0]); + return true; + } else { + // WARNING. Not unique. XA - ZA = -atan2(r10,r11) + rfXAngle = -G3D::aTan2(elt[1][0], elt[1][1]); + rfYAngle = -(float)halfPi(); + rfZAngle = 0.0f; + return false; + } + } else { + // WARNING. Not unique. XAngle + ZAngle = atan2(r10,r11) + rfXAngle = G3D::aTan2(elt[1][0], elt[1][1]); + rfYAngle = (float)halfPi(); + rfZAngle = 0.0f; + return false; + } +} + +//---------------------------------------------------------------------------- +bool Matrix3::toEulerAnglesXZY (float& rfXAngle, float& rfZAngle, + float& rfYAngle) const { + // rot = cy*cz -sz cz*sy + // sx*sy+cx*cy*sz cx*cz -cy*sx+cx*sy*sz + // -cx*sy+cy*sx*sz cz*sx cx*cy+sx*sy*sz + + if ( elt[0][1] < 1.0f ) { + if ( elt[0][1] > -1.0f ) { + rfXAngle = G3D::aTan2(elt[2][1], elt[1][1]); + rfZAngle = (float) asin( -elt[0][1]); + rfYAngle = G3D::aTan2(elt[0][2], elt[0][0]); + return true; + } else { + // WARNING. Not unique. XA - YA = atan2(r20,r22) + rfXAngle = G3D::aTan2(elt[2][0], elt[2][2]); + rfZAngle = (float)halfPi(); + rfYAngle = 0.0; + return false; + } + } else { + // WARNING. Not unique. XA + YA = atan2(-r20,r22) + rfXAngle = G3D::aTan2( -elt[2][0], elt[2][2]); + rfZAngle = -(float)halfPi(); + rfYAngle = 0.0f; + return false; + } +} + +//---------------------------------------------------------------------------- +bool Matrix3::toEulerAnglesYXZ (float& rfYAngle, float& rfXAngle, + float& rfZAngle) const { + // rot = cy*cz+sx*sy*sz cz*sx*sy-cy*sz cx*sy + // cx*sz cx*cz -sx + // -cz*sy+cy*sx*sz cy*cz*sx+sy*sz cx*cy + + if ( elt[1][2] < 1.0 ) { + if ( elt[1][2] > -1.0 ) { + rfYAngle = G3D::aTan2(elt[0][2], elt[2][2]); + rfXAngle = (float) asin( -elt[1][2]); + rfZAngle = G3D::aTan2(elt[1][0], elt[1][1]); + return true; + } else { + // WARNING. Not unique. YA - ZA = atan2(r01,r00) + rfYAngle = G3D::aTan2(elt[0][1], elt[0][0]); + rfXAngle = (float)halfPi(); + rfZAngle = 0.0; + return false; + } + } else { + // WARNING. Not unique. YA + ZA = atan2(-r01,r00) + rfYAngle = G3D::aTan2( -elt[0][1], elt[0][0]); + rfXAngle = -(float)halfPi(); + rfZAngle = 0.0f; + return false; + } +} + +//---------------------------------------------------------------------------- +bool Matrix3::toEulerAnglesYZX (float& rfYAngle, float& rfZAngle, + float& rfXAngle) const { + // rot = cy*cz sx*sy-cx*cy*sz cx*sy+cy*sx*sz + // sz cx*cz -cz*sx + // -cz*sy cy*sx+cx*sy*sz cx*cy-sx*sy*sz + + if ( elt[1][0] < 1.0 ) { + if ( elt[1][0] > -1.0 ) { + rfYAngle = G3D::aTan2( -elt[2][0], elt[0][0]); + rfZAngle = (float) asin(elt[1][0]); + rfXAngle = G3D::aTan2( -elt[1][2], elt[1][1]); + return true; + } else { + // WARNING. Not unique. YA - XA = -atan2(r21,r22); + rfYAngle = -G3D::aTan2(elt[2][1], elt[2][2]); + rfZAngle = -(float)halfPi(); + rfXAngle = 0.0; + return false; + } + } else { + // WARNING. Not unique. YA + XA = atan2(r21,r22) + rfYAngle = G3D::aTan2(elt[2][1], elt[2][2]); + rfZAngle = (float)halfPi(); + rfXAngle = 0.0f; + return false; + } +} + +//---------------------------------------------------------------------------- +bool Matrix3::toEulerAnglesZXY (float& rfZAngle, float& rfXAngle, + float& rfYAngle) const { + // rot = cy*cz-sx*sy*sz -cx*sz cz*sy+cy*sx*sz + // cz*sx*sy+cy*sz cx*cz -cy*cz*sx+sy*sz + // -cx*sy sx cx*cy + + if ( elt[2][1] < 1.0 ) { + if ( elt[2][1] > -1.0 ) { + rfZAngle = G3D::aTan2( -elt[0][1], elt[1][1]); + rfXAngle = (float) asin(elt[2][1]); + rfYAngle = G3D::aTan2( -elt[2][0], elt[2][2]); + return true; + } else { + // WARNING. Not unique. ZA - YA = -atan(r02,r00) + rfZAngle = -G3D::aTan2(elt[0][2], elt[0][0]); + rfXAngle = -(float)halfPi(); + rfYAngle = 0.0f; + return false; + } + } else { + // WARNING. Not unique. ZA + YA = atan2(r02,r00) + rfZAngle = G3D::aTan2(elt[0][2], elt[0][0]); + rfXAngle = (float)halfPi(); + rfYAngle = 0.0f; + return false; + } +} + +//---------------------------------------------------------------------------- +bool Matrix3::toEulerAnglesZYX (float& rfZAngle, float& rfYAngle, + float& rfXAngle) const { + // rot = cy*cz cz*sx*sy-cx*sz cx*cz*sy+sx*sz + // cy*sz cx*cz+sx*sy*sz -cz*sx+cx*sy*sz + // -sy cy*sx cx*cy + + if ( elt[2][0] < 1.0 ) { + if ( elt[2][0] > -1.0 ) { + rfZAngle = atan2f(elt[1][0], elt[0][0]); + rfYAngle = asinf(-(double)elt[2][1]); + rfXAngle = atan2f(elt[2][1], elt[2][2]); + return true; + } else { + // WARNING. Not unique. ZA - XA = -atan2(r01,r02) + rfZAngle = -G3D::aTan2(elt[0][1], elt[0][2]); + rfYAngle = (float)halfPi(); + rfXAngle = 0.0f; + return false; + } + } else { + // WARNING. Not unique. ZA + XA = atan2(-r01,-r02) + rfZAngle = G3D::aTan2( -elt[0][1], -elt[0][2]); + rfYAngle = -(float)halfPi(); + rfXAngle = 0.0f; + return false; + } +} + +//---------------------------------------------------------------------------- +Matrix3 Matrix3::fromEulerAnglesXYZ (float fYAngle, float fPAngle, + float fRAngle) { + float fCos, fSin; + + fCos = cosf(fYAngle); + fSin = sinf(fYAngle); + Matrix3 kXMat(1.0f, 0.0f, 0.0f, 0.0f, fCos, -fSin, 0.0, fSin, fCos); + + fCos = cosf(fPAngle); + fSin = sinf(fPAngle); + Matrix3 kYMat(fCos, 0.0f, fSin, 0.0f, 1.0f, 0.0f, -fSin, 0.0f, fCos); + + fCos = cosf(fRAngle); + fSin = sinf(fRAngle); + Matrix3 kZMat(fCos, -fSin, 0.0f, fSin, fCos, 0.0f, 0.0f, 0.0f, 1.0f); + + return kXMat * (kYMat * kZMat); +} + +//---------------------------------------------------------------------------- +Matrix3 Matrix3::fromEulerAnglesXZY (float fYAngle, float fPAngle, + float fRAngle) { + + float fCos, fSin; + + fCos = cosf(fYAngle); + fSin = sinf(fYAngle); + Matrix3 kXMat(1.0, 0.0, 0.0, 0.0, fCos, -fSin, 0.0, fSin, fCos); + + fCos = cosf(fPAngle); + fSin = sinf(fPAngle); + Matrix3 kZMat(fCos, -fSin, 0.0, fSin, fCos, 0.0, 0.0, 0.0, 1.0); + + fCos = cosf(fRAngle); + fSin = sinf(fRAngle); + Matrix3 kYMat(fCos, 0.0, fSin, 0.0, 1.0, 0.0, -fSin, 0.0, fCos); + + return kXMat * (kZMat * kYMat); +} + +//---------------------------------------------------------------------------- +Matrix3 Matrix3::fromEulerAnglesYXZ( + float fYAngle, + float fPAngle, + float fRAngle) { + + float fCos, fSin; + + fCos = cos(fYAngle); + fSin = sin(fYAngle); + Matrix3 kYMat(fCos, 0.0f, fSin, 0.0f, 1.0f, 0.0f, -fSin, 0.0f, fCos); + + fCos = cos(fPAngle); + fSin = sin(fPAngle); + Matrix3 kXMat(1.0f, 0.0f, 0.0f, 0.0f, fCos, -fSin, 0.0f, fSin, fCos); + + fCos = cos(fRAngle); + fSin = sin(fRAngle); + Matrix3 kZMat(fCos, -fSin, 0.0f, fSin, fCos, 0.0f, 0.0f, 0.0f, 1.0f); + + return kYMat * (kXMat * kZMat); +} + +//---------------------------------------------------------------------------- +Matrix3 Matrix3::fromEulerAnglesYZX( + float fYAngle, + float fPAngle, + float fRAngle) { + + float fCos, fSin; + + fCos = cos(fYAngle); + fSin = sin(fYAngle); + Matrix3 kYMat(fCos, 0.0f, fSin, 0.0f, 1.0f, 0.0f, -fSin, 0.0f, fCos); + + fCos = cos(fPAngle); + fSin = sin(fPAngle); + Matrix3 kZMat(fCos, -fSin, 0.0f, fSin, fCos, 0.0f, 0.0f, 0.0f, 1.0f); + + fCos = cos(fRAngle); + fSin = sin(fRAngle); + Matrix3 kXMat(1.0f, 0.0f, 0.0f, 0.0f, fCos, -fSin, 0.0f, fSin, fCos); + + return kYMat * (kZMat * kXMat); +} + +//---------------------------------------------------------------------------- +Matrix3 Matrix3::fromEulerAnglesZXY (float fYAngle, float fPAngle, + float fRAngle) { + float fCos, fSin; + + fCos = cos(fYAngle); + fSin = sin(fYAngle); + Matrix3 kZMat(fCos, -fSin, 0.0, fSin, fCos, 0.0, 0.0, 0.0, 1.0); + + fCos = cos(fPAngle); + fSin = sin(fPAngle); + Matrix3 kXMat(1.0, 0.0, 0.0, 0.0, fCos, -fSin, 0.0, fSin, fCos); + + fCos = cos(fRAngle); + fSin = sin(fRAngle); + Matrix3 kYMat(fCos, 0.0, fSin, 0.0, 1.0, 0.0, -fSin, 0.0, fCos); + + return kZMat * (kXMat * kYMat); +} + +//---------------------------------------------------------------------------- +Matrix3 Matrix3::fromEulerAnglesZYX (float fYAngle, float fPAngle, + float fRAngle) { + float fCos, fSin; + + fCos = cos(fYAngle); + fSin = sin(fYAngle); + Matrix3 kZMat(fCos, -fSin, 0.0, fSin, fCos, 0.0, 0.0, 0.0, 1.0); + + fCos = cos(fPAngle); + fSin = sin(fPAngle); + Matrix3 kYMat(fCos, 0.0, fSin, 0.0, 1.0, 0.0, -fSin, 0.0, fCos); + + fCos = cos(fRAngle); + fSin = sin(fRAngle); + Matrix3 kXMat(1.0, 0.0, 0.0, 0.0, fCos, -fSin, 0.0, fSin, fCos); + + return kZMat * (kYMat * kXMat); +} + +//---------------------------------------------------------------------------- +void Matrix3::tridiagonal (float afDiag[3], float afSubDiag[3]) { + // Householder reduction T = Q^t M Q + // Input: + // mat, symmetric 3x3 matrix M + // Output: + // mat, orthogonal matrix Q + // diag, diagonal entries of T + // subd, subdiagonal entries of T (T is symmetric) + + float fA = elt[0][0]; + float fB = elt[0][1]; + float fC = elt[0][2]; + float fD = elt[1][1]; + float fE = elt[1][2]; + float fF = elt[2][2]; + + afDiag[0] = fA; + afSubDiag[2] = 0.0; + + if ( G3D::abs(fC) >= EPSILON ) { + float fLength = sqrt(fB * fB + fC * fC); + float fInvLength = 1.0 / fLength; + fB *= fInvLength; + fC *= fInvLength; + float fQ = 2.0 * fB * fE + fC * (fF - fD); + afDiag[1] = fD + fC * fQ; + afDiag[2] = fF - fC * fQ; + afSubDiag[0] = fLength; + afSubDiag[1] = fE - fB * fQ; + elt[0][0] = 1.0; + elt[0][1] = 0.0; + elt[0][2] = 0.0; + elt[1][0] = 0.0; + elt[1][1] = fB; + elt[1][2] = fC; + elt[2][0] = 0.0; + elt[2][1] = fC; + elt[2][2] = -fB; + } else { + afDiag[1] = fD; + afDiag[2] = fF; + afSubDiag[0] = fB; + afSubDiag[1] = fE; + elt[0][0] = 1.0; + elt[0][1] = 0.0; + elt[0][2] = 0.0; + elt[1][0] = 0.0; + elt[1][1] = 1.0; + elt[1][2] = 0.0; + elt[2][0] = 0.0; + elt[2][1] = 0.0; + elt[2][2] = 1.0; + } +} + +//---------------------------------------------------------------------------- +bool Matrix3::qLAlgorithm (float afDiag[3], float afSubDiag[3]) { + // QL iteration with implicit shifting to reduce matrix from tridiagonal + // to diagonal + + for (int i0 = 0; i0 < 3; i0++) { + const int iMaxIter = 32; + int iIter; + + for (iIter = 0; iIter < iMaxIter; iIter++) { + int i1; + + for (i1 = i0; i1 <= 1; i1++) { + float fSum = G3D::abs(afDiag[i1]) + + G3D::abs(afDiag[i1 + 1]); + + if ( G3D::abs(afSubDiag[i1]) + fSum == fSum ) + break; + } + + if ( i1 == i0 ) + break; + + float fTmp0 = (afDiag[i0 + 1] - afDiag[i0]) / (2.0 * afSubDiag[i0]); + + float fTmp1 = sqrt(fTmp0 * fTmp0 + 1.0); + + if ( fTmp0 < 0.0 ) + fTmp0 = afDiag[i1] - afDiag[i0] + afSubDiag[i0] / (fTmp0 - fTmp1); + else + fTmp0 = afDiag[i1] - afDiag[i0] + afSubDiag[i0] / (fTmp0 + fTmp1); + + float fSin = 1.0; + + float fCos = 1.0; + + float fTmp2 = 0.0; + + for (int i2 = i1 - 1; i2 >= i0; i2--) { + float fTmp3 = fSin * afSubDiag[i2]; + float fTmp4 = fCos * afSubDiag[i2]; + + if (G3D::abs(fTmp3) >= G3D::abs(fTmp0)) { + fCos = fTmp0 / fTmp3; + fTmp1 = sqrt(fCos * fCos + 1.0); + afSubDiag[i2 + 1] = fTmp3 * fTmp1; + fSin = 1.0 / fTmp1; + fCos *= fSin; + } else { + fSin = fTmp3 / fTmp0; + fTmp1 = sqrt(fSin * fSin + 1.0); + afSubDiag[i2 + 1] = fTmp0 * fTmp1; + fCos = 1.0 / fTmp1; + fSin *= fCos; + } + + fTmp0 = afDiag[i2 + 1] - fTmp2; + fTmp1 = (afDiag[i2] - fTmp0) * fSin + 2.0 * fTmp4 * fCos; + fTmp2 = fSin * fTmp1; + afDiag[i2 + 1] = fTmp0 + fTmp2; + fTmp0 = fCos * fTmp1 - fTmp4; + + for (int iRow = 0; iRow < 3; iRow++) { + fTmp3 = elt[iRow][i2 + 1]; + elt[iRow][i2 + 1] = fSin * elt[iRow][i2] + + fCos * fTmp3; + elt[iRow][i2] = fCos * elt[iRow][i2] - + fSin * fTmp3; + } + } + + afDiag[i0] -= fTmp2; + afSubDiag[i0] = fTmp0; + afSubDiag[i1] = 0.0; + } + + if ( iIter == iMaxIter ) { + // should not get here under normal circumstances + return false; + } + } + + return true; +} + +//---------------------------------------------------------------------------- +void Matrix3::eigenSolveSymmetric (float afEigenvalue[3], + Vector3 akEigenvector[3]) const { + Matrix3 kMatrix = *this; + float afSubDiag[3]; + kMatrix.tridiagonal(afEigenvalue, afSubDiag); + kMatrix.qLAlgorithm(afEigenvalue, afSubDiag); + + for (int i = 0; i < 3; i++) { + akEigenvector[i][0] = kMatrix[0][i]; + akEigenvector[i][1] = kMatrix[1][i]; + akEigenvector[i][2] = kMatrix[2][i]; + } + + // make eigenvectors form a right--handed system + Vector3 kCross = akEigenvector[1].cross(akEigenvector[2]); + + float fDet = akEigenvector[0].dot(kCross); + + if ( fDet < 0.0 ) { + akEigenvector[2][0] = - akEigenvector[2][0]; + akEigenvector[2][1] = - akEigenvector[2][1]; + akEigenvector[2][2] = - akEigenvector[2][2]; + } +} + +//---------------------------------------------------------------------------- +void Matrix3::tensorProduct (const Vector3& rkU, const Vector3& rkV, + Matrix3& rkProduct) { + for (int iRow = 0; iRow < 3; iRow++) { + for (int iCol = 0; iCol < 3; iCol++) { + rkProduct[iRow][iCol] = rkU[iRow] * rkV[iCol]; + } + } +} + +//---------------------------------------------------------------------------- + +// Runs in 52 cycles on AMD, 76 cycles on Intel Centrino +// +// The loop unrolling is necessary for performance. +// I was unable to improve performance further by flattening the matrices +// into float*'s instead of 2D arrays. +// +// -morgan +void Matrix3::_mul(const Matrix3& A, const Matrix3& B, Matrix3& out) { + const float* ARowPtr = A.elt[0]; + float* outRowPtr = out.elt[0]; + outRowPtr[0] = + ARowPtr[0] * B.elt[0][0] + + ARowPtr[1] * B.elt[1][0] + + ARowPtr[2] * B.elt[2][0]; + outRowPtr[1] = + ARowPtr[0] * B.elt[0][1] + + ARowPtr[1] * B.elt[1][1] + + ARowPtr[2] * B.elt[2][1]; + outRowPtr[2] = + ARowPtr[0] * B.elt[0][2] + + ARowPtr[1] * B.elt[1][2] + + ARowPtr[2] * B.elt[2][2]; + + ARowPtr = A.elt[1]; + outRowPtr = out.elt[1]; + + outRowPtr[0] = + ARowPtr[0] * B.elt[0][0] + + ARowPtr[1] * B.elt[1][0] + + ARowPtr[2] * B.elt[2][0]; + outRowPtr[1] = + ARowPtr[0] * B.elt[0][1] + + ARowPtr[1] * B.elt[1][1] + + ARowPtr[2] * B.elt[2][1]; + outRowPtr[2] = + ARowPtr[0] * B.elt[0][2] + + ARowPtr[1] * B.elt[1][2] + + ARowPtr[2] * B.elt[2][2]; + + ARowPtr = A.elt[2]; + outRowPtr = out.elt[2]; + + outRowPtr[0] = + ARowPtr[0] * B.elt[0][0] + + ARowPtr[1] * B.elt[1][0] + + ARowPtr[2] * B.elt[2][0]; + outRowPtr[1] = + ARowPtr[0] * B.elt[0][1] + + ARowPtr[1] * B.elt[1][1] + + ARowPtr[2] * B.elt[2][1]; + outRowPtr[2] = + ARowPtr[0] * B.elt[0][2] + + ARowPtr[1] * B.elt[1][2] + + ARowPtr[2] * B.elt[2][2]; +} + +//---------------------------------------------------------------------------- +void Matrix3::_transpose(const Matrix3& A, Matrix3& out) { + out[0][0] = A.elt[0][0]; + out[0][1] = A.elt[1][0]; + out[0][2] = A.elt[2][0]; + out[1][0] = A.elt[0][1]; + out[1][1] = A.elt[1][1]; + out[1][2] = A.elt[2][1]; + out[2][0] = A.elt[0][2]; + out[2][1] = A.elt[1][2]; + out[2][2] = A.elt[2][2]; +} + +//----------------------------------------------------------------------------- +std::string Matrix3::toString() const { + return G3D::format("[%g, %g, %g; %g, %g, %g; %g, %g, %g]", + elt[0][0], elt[0][1], elt[0][2], + elt[1][0], elt[1][1], elt[1][2], + elt[2][0], elt[2][1], elt[2][2]); +} + + + +} // namespace + diff --git a/dep/g3dlite/Matrix4.cpp b/dep/g3dlite/Matrix4.cpp new file mode 100644 index 00000000000..cd38a1a3602 --- /dev/null +++ b/dep/g3dlite/Matrix4.cpp @@ -0,0 +1,523 @@ +/** + @file Matrix4.cpp + + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2003-10-02 + @edited 2010-01-29 + */ + +#include "G3D/platform.h" +#include "G3D/Matrix4.h" +#include "G3D/Matrix3.h" +#include "G3D/Vector4.h" +#include "G3D/Vector3.h" +#include "G3D/BinaryInput.h" +#include "G3D/BinaryOutput.h" +#include "G3D/CoordinateFrame.h" +#include "G3D/Rect2D.h" +#include "G3D/Any.h" +#include "G3D/stringutils.h" + +namespace G3D { + + +Matrix4::Matrix4(const Any& any) { + any.verifyName("Matrix4"); + any.verifyType(Any::ARRAY); + + const std::string& name = toLower(any.name()); + if (name == "matrix4") { + any.verifySize(16); + + for (int r = 0; r < 4; ++r) { + for (int c = 0; c < 4; ++c) { + elt[r][c] = any[r * 4 + c]; + } + } + } else if (name == "matrix4::scale") { + if (any.size() == 1) { + *this = scale(any[0].number()); + } else if (any.size() == 3) { + *this = scale(any[0], any[1], any[2]); + } else { + any.verify(false, "Matrix4::scale() takes either 1 or 3 arguments"); + } + } else { + any.verify(false, "Expected Matrix4 constructor"); + } +} + + +Matrix4::operator Any() const { + Any any(Any::ARRAY, "Matrix4"); + any.resize(16); + for (int r = 0; r < 4; ++r) { + for (int c = 0; c < 4; ++c) { + any[r * 4 + c] = elt[r][c]; + } + } + + return any; +} + +const Matrix4& Matrix4::identity() { + static Matrix4 m( + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1); + return m; +} + + +const Matrix4& Matrix4::zero() { + static Matrix4 m( + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0); + return m; +} + + +Matrix4::Matrix4(const class CoordinateFrame& cframe) { + for (int r = 0; r < 3; ++r) { + for (int c = 0; c < 3; ++c) { + elt[r][c] = cframe.rotation[r][c]; + } + elt[r][3] = cframe.translation[r]; + } + elt[3][0] = 0.0f; + elt[3][1] = 0.0f; + elt[3][2] = 0.0f; + elt[3][3] = 1.0f; +} + +Matrix4::Matrix4(const Matrix3& upper3x3, const Vector3& lastCol) { + for (int r = 0; r < 3; ++r) { + for (int c = 0; c < 3; ++c) { + elt[r][c] = upper3x3[r][c]; + } + elt[r][3] = lastCol[r]; + } + elt[3][0] = 0.0f; + elt[3][1] = 0.0f; + elt[3][2] = 0.0f; + elt[3][3] = 1.0f; +} + + +Matrix3 Matrix4::upper3x3() const { + return Matrix3(elt[0][0], elt[0][1], elt[0][2], + elt[1][0], elt[1][1], elt[1][2], + elt[2][0], elt[2][1], elt[2][2]); +} + + +Matrix4 Matrix4::orthogonalProjection( + const class Rect2D& rect, + float nearval, + float farval, + float upDirection) { + return Matrix4::orthogonalProjection(rect.x0(), rect.x1(), rect.y1(), rect.y0(), nearval, farval, upDirection); +} + + +Matrix4 Matrix4::orthogonalProjection( + float left, + float right, + float bottom, + float top, + float nearval, + float farval, + float upDirection) { + + // Adapted from Mesa. Note that Microsoft (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/opengl/glfunc03_8qnj.asp) + // and Linux (http://www.xfree86.org/current/glOrtho.3.html) have different matrices shown in their documentation. + + float x, y, z; + float tx, ty, tz; + + x = 2.0f / (right-left); + y = 2.0f / (top-bottom); + z = -2.0f / (farval-nearval); + tx = -(right+left) / (right-left); + ty = -(top+bottom) / (top-bottom); + tz = -(farval+nearval) / (farval-nearval); + + y *= upDirection; + ty *= upDirection; + + return + Matrix4( x , 0.0f, 0.0f, tx, + 0.0f, y , 0.0f, ty, + 0.0f, 0.0f, z , tz, + 0.0f, 0.0f, 0.0f, 1.0f); +} + + +Matrix4 Matrix4::perspectiveProjection( + float left, + float right, + float bottom, + float top, + float nearval, + float farval, + float upDirection) { + + float x, y, a, b, c, d; + + x = (2.0f*nearval) / (right-left); + y = (2.0f*nearval) / (top-bottom); + a = (right+left) / (right-left); + b = (top+bottom) / (top-bottom); + + if (farval >= finf()) { + // Infinite view frustum + c = -1.0f; + d = -2.0f * nearval; + } else { + c = -(farval+nearval) / (farval-nearval); + d = -(2.0f*farval*nearval) / (farval-nearval); + } + + debugAssertM(abs(upDirection) == 1.0f, "upDirection must be -1 or +1"); + y *= upDirection; + b *= upDirection; + + return Matrix4( + x, 0, a, 0, + 0, y, b, 0, + 0, 0, c, d, + 0, 0, -1, 0); +} + + +void Matrix4::getPerspectiveProjectionParameters( + float& left, + float& right, + float& bottom, + float& top, + float& nearval, + float& farval, + float upDirection) const { + + debugAssertM(abs(upDirection) == 1.0f, "upDirection must be -1 or +1"); + + float x = elt[0][0]; + float y = elt[1][1] * upDirection; + float a = elt[0][2]; + float b = elt[1][2] * upDirection; + float c = elt[2][2]; + float d = elt[2][3]; + + // Verify that this really is a projection matrix + debugAssertM(elt[3][2] == -1, "Not a projection matrix"); + debugAssertM(elt[0][1] == 0, "Not a projection matrix"); + debugAssertM(elt[0][3] == 0, "Not a projection matrix"); + debugAssertM(elt[1][3] == 0, "Not a projection matrix"); + debugAssertM(elt[3][3] == 0, "Not a projection matrix"); + debugAssertM(elt[1][0] == 0, "Not a projection matrix"); + debugAssertM(elt[2][0] == 0, "Not a projection matrix"); + debugAssertM(elt[2][1] == 0, "Not a projection matrix"); + debugAssertM(elt[3][0] == 0, "Not a projection matrix"); + debugAssertM(elt[3][1] == 0, "Not a projection matrix"); + + if (c == -1) { + farval = finf(); + nearval = -d / 2.0f; + } else { + nearval = d * ((c - 1.0f) / (c + 1.0f) - 1.0f) / (-2.0f * (c - 1.0f) / (c + 1.0f)); + farval = nearval * ((c - 1.0f) / (c + 1.0f)); + } + + + left = (a - 1.0f) * nearval / x; + right = 2.0f * nearval / x + left; + + bottom = (b - 1.0f) * nearval / y; + top = 2.0f * nearval / y + bottom; +} + + +Matrix4::Matrix4( + float r1c1, float r1c2, float r1c3, float r1c4, + float r2c1, float r2c2, float r2c3, float r2c4, + float r3c1, float r3c2, float r3c3, float r3c4, + float r4c1, float r4c2, float r4c3, float r4c4) { + elt[0][0] = r1c1; elt[0][1] = r1c2; elt[0][2] = r1c3; elt[0][3] = r1c4; + elt[1][0] = r2c1; elt[1][1] = r2c2; elt[1][2] = r2c3; elt[1][3] = r2c4; + elt[2][0] = r3c1; elt[2][1] = r3c2; elt[2][2] = r3c3; elt[2][3] = r3c4; + elt[3][0] = r4c1; elt[3][1] = r4c2; elt[3][2] = r4c3; elt[3][3] = r4c4; +} + +/** + init should be row major. + */ +Matrix4::Matrix4(const float* init) { + for (int r = 0; r < 4; ++r) { + for (int c = 0; c < 4; ++c) { + elt[r][c] = init[r * 4 + c]; + } + } +} + + +Matrix4::Matrix4(const double* init) { + for (int r = 0; r < 4; ++r) { + for (int c = 0; c < 4; ++c) { + elt[r][c] = (float)init[r * 4 + c]; + } + } +} + + +Matrix4::Matrix4() { + for (int r = 0; r < 4; ++r) { + for (int c = 0; c < 4; ++c) { + elt[r][c] = 0; + } + } +} + + +void Matrix4::setRow(int r, const Vector4& v) { + for (int c = 0; c < 4; ++c) { + elt[r][c] = v[c]; + } +} + + +void Matrix4::setColumn(int c, const Vector4& v) { + for (int r = 0; r < 4; ++r) { + elt[r][c] = v[r]; + } +} + + +const Vector4& Matrix4::row(int r) const { + return reinterpret_cast(elt[r])[0]; +} + + +Vector4 Matrix4::column(int c) const { + Vector4 v; + for (int r = 0; r < 4; ++r) { + v[r] = elt[r][c]; + } + return v; +} + + +Matrix4 Matrix4::operator*(const Matrix4& other) const { + Matrix4 result; + for (int r = 0; r < 4; ++r) { + for (int c = 0; c < 4; ++c) { + for (int i = 0; i < 4; ++i) { + result.elt[r][c] += elt[r][i] * other.elt[i][c]; + } + } + } + + return result; +} + + +Matrix4 Matrix4::operator*(const float s) const { + Matrix4 result; + for (int r = 0; r < 4; ++r) { + for (int c = 0; c < 4; ++c) { + result.elt[r][c] = elt[r][c] * s; + } + } + + return result; +} + + +Vector3 Matrix4::homoMul(const class Vector3& v, float w) const { + Vector4 r = (*this) * Vector4(v, w); + return r.xyz() * (1.0f / r.w); +} + + +Vector4 Matrix4::operator*(const Vector4& vector) const { + Vector4 result(0,0,0,0); + for (int r = 0; r < 4; ++r) { + for (int c = 0; c < 4; ++c) { + result[r] += elt[r][c] * vector[c]; + } + } + + return result; +} + + +Matrix4 Matrix4::transpose() const { + Matrix4 result; + for (int r = 0; r < 4; ++r) { + for (int c = 0; c < 4; ++c) { + result.elt[c][r] = elt[r][c]; + } + } + + return result; +} + + +bool Matrix4::operator!=(const Matrix4& other) const { + return ! (*this == other); +} + + +bool Matrix4::operator==(const Matrix4& other) const { + + // If the bit patterns are identical, they must be + // the same matrix. If not, they *might* still have + // equal elements due to floating point weirdness. + if (memcmp(this, &other, sizeof(Matrix4) == 0)) { + return true; + } + + for (int r = 0; r < 4; ++r) { + for (int c = 0; c < 4; ++c) { + if (elt[r][c] != other.elt[r][c]) { + return false; + } + } + } + + return true; +} + + +float Matrix4::determinant() const { + // Determinant is the dot product of the first row and the first row + // of cofactors (i.e. the first col of the adjoint matrix) + return cofactor().row(0).dot(row(0)); +} + + +Matrix4 Matrix4::adjoint() const { + return cofactor().transpose(); +} + + +Matrix4 Matrix4::inverse() const { + // Inverse = adjoint / determinant + + Matrix4 A = adjoint(); + + // Determinant is the dot product of the first row and the first row + // of cofactors (i.e. the first col of the adjoint matrix) + float det = A.column(0).dot(row(0)); + + return A * (1.0f / det); +} + + +Matrix4 Matrix4::cofactor() const { + Matrix4 out; + + // We'll use i to incrementally compute -1 ^ (r+c) + int i = 1; + + for (int r = 0; r < 4; ++r) { + for (int c = 0; c < 4; ++c) { + // Compute the determinant of the 3x3 submatrix + float det = subDeterminant(r, c); + out.elt[r][c] = i * det; + i = -i; + } + i = -i; + } + + return out; +} + + +float Matrix4::subDeterminant(int excludeRow, int excludeCol) const { + // Compute non-excluded row and column indices + int row[3]; + int col[3]; + + for (int i = 0; i < 3; ++i) { + row[i] = i; + col[i] = i; + + if (i >= excludeRow) { + ++row[i]; + } + if (i >= excludeCol) { + ++col[i]; + } + } + + // Compute the first row of cofactors + float cofactor00 = + elt[row[1]][col[1]] * elt[row[2]][col[2]] - + elt[row[1]][col[2]] * elt[row[2]][col[1]]; + + float cofactor10 = + elt[row[1]][col[2]] * elt[row[2]][col[0]] - + elt[row[1]][col[0]] * elt[row[2]][col[2]]; + + float cofactor20 = + elt[row[1]][col[0]] * elt[row[2]][col[1]] - + elt[row[1]][col[1]] * elt[row[2]][col[0]]; + + // Product of the first row and the cofactors along the first row + return + elt[row[0]][col[0]] * cofactor00 + + elt[row[0]][col[1]] * cofactor10 + + elt[row[0]][col[2]] * cofactor20; +} + + +CoordinateFrame Matrix4::approxCoordinateFrame() const { + CoordinateFrame cframe; + + for (int r = 0; r < 3; ++r) { + for (int c = 0; c < 3; ++c) { + cframe.rotation[r][c] = elt[r][c]; + } + cframe.translation[r] = elt[r][3]; + } + + // Ensure that the rotation matrix is orthonormal + cframe.rotation.orthonormalize(); + + return cframe; +} + + +void Matrix4::serialize(class BinaryOutput& b) const { + for (int r = 0; r < 4; ++r) { + for (int c = 0; c < 4; ++c) { + b.writeFloat32(elt[r][c]); + } + } +} + + +void Matrix4::deserialize(class BinaryInput& b) { + for (int r = 0; r < 4; ++r) { + for (int c = 0; c < 4; ++c) { + elt[r][c] = b.readFloat32(); + } + } +} + +std::string Matrix4::toString() const { + return G3D::format("[%g, %g, %g, %g; %g, %g, %g, %g; %g, %g, %g, %g; %g, %g, %g, %g]", + elt[0][0], elt[0][1], elt[0][2], elt[0][3], + elt[1][0], elt[1][1], elt[1][2], elt[1][3], + elt[2][0], elt[2][1], elt[2][2], elt[2][3], + elt[3][0], elt[3][1], elt[3][2], elt[3][3]); +} + +} // namespace + + diff --git a/dep/g3dlite/MemoryManager.cpp b/dep/g3dlite/MemoryManager.cpp new file mode 100644 index 00000000000..240188a1f0e --- /dev/null +++ b/dep/g3dlite/MemoryManager.cpp @@ -0,0 +1,91 @@ +/** + @file MemoryManager.cpp + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + @created 2009-04-20 + @edited 2009-05-29 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ + +#include "G3D/MemoryManager.h" +#include "G3D/System.h" + +namespace G3D { + +MemoryManager::MemoryManager() {} + + +void* MemoryManager::alloc(size_t s) { + return System::malloc(s); +} + + +void MemoryManager::free(void* ptr) { + System::free(ptr); +} + + +bool MemoryManager::isThreadsafe() const { + return true; +} + + +MemoryManager::Ref MemoryManager::create() { + static MemoryManager::Ref m = new MemoryManager(); + return m; +} + + +/////////////////////////////////////////////////// + +AlignedMemoryManager::AlignedMemoryManager() {} + + +void* AlignedMemoryManager::alloc(size_t s) { + return System::alignedMalloc(s, 16); +} + + +void AlignedMemoryManager::free(void* ptr) { + System::alignedFree(ptr); +} + + +bool AlignedMemoryManager::isThreadsafe() const { + return true; +} + + +AlignedMemoryManager::Ref AlignedMemoryManager::create() { + static AlignedMemoryManager::Ref m = new AlignedMemoryManager(); + return m; +} + + +/////////////////////////////////////////////////// + +CRTMemoryManager::CRTMemoryManager() {} + + +void* CRTMemoryManager::alloc(size_t s) { + return ::malloc(s); +} + + +void CRTMemoryManager::free(void* ptr) { + return ::free(ptr); +} + + +bool CRTMemoryManager::isThreadsafe() const { + return true; +} + + +CRTMemoryManager::Ref CRTMemoryManager::create() { + static CRTMemoryManager::Ref m = new CRTMemoryManager(); + return m; +} +} diff --git a/dep/g3dlite/Plane.cpp b/dep/g3dlite/Plane.cpp new file mode 100644 index 00000000000..9b7991c0333 --- /dev/null +++ b/dep/g3dlite/Plane.cpp @@ -0,0 +1,149 @@ +/** + @file Plane.cpp + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2003-02-06 + @edited 2006-01-29 + */ + +#include "G3D/platform.h" +#include "G3D/Plane.h" +#include "G3D/BinaryOutput.h" +#include "G3D/BinaryInput.h" +#include "G3D/stringutils.h" + +namespace G3D { + +Plane::Plane(class BinaryInput& b) { + deserialize(b); +} + + +void Plane::serialize(class BinaryOutput& b) const { + _normal.serialize(b); + b.writeFloat64(_distance); +} + + +void Plane::deserialize(class BinaryInput& b) { + _normal.deserialize(b); + _distance = (float)b.readFloat64(); +} + + +Plane::Plane( + Vector4 point0, + Vector4 point1, + Vector4 point2) { + + debugAssertM( + point0.w != 0 || + point1.w != 0 || + point2.w != 0, + "At least one point must be finite."); + + // Rotate the points around so that the finite points come first. + + while ((point0.w == 0) && + ((point1.w == 0) || (point2.w != 0))) { + Vector4 temp = point0; + point0 = point1; + point1 = point2; + point2 = temp; + } + + Vector3 dir1; + Vector3 dir2; + + if (point1.w == 0) { + // 1 finite, 2 infinite points; the plane must contain + // the direction of the two direcitons + dir1 = point1.xyz(); + dir2 = point2.xyz(); + } else if (point2.w != 0) { + // 3 finite points, the plane must contain the directions + // betwseen the points. + dir1 = point1.xyz() - point0.xyz(); + dir2 = point2.xyz() - point0.xyz(); + } else { + // 2 finite, 1 infinite point; the plane must contain + // the direction between the first two points and the + // direction of the third point. + dir1 = point1.xyz() - point0.xyz(); + dir2 = point2.xyz(); + } + + _normal = dir1.cross(dir2).direction(); + _distance = _normal.dot(point0.xyz()); +} + + +Plane::Plane( + const Vector3& point0, + const Vector3& point1, + const Vector3& point2) { + + _normal = (point1 - point0).cross(point2 - point0).direction(); + _distance = _normal.dot(point0); +} + + +Plane::Plane( + const Vector3& __normal, + const Vector3& point) { + + _normal = __normal.direction(); + _distance = _normal.dot(point); +} + + +Plane Plane::fromEquation(float a, float b, float c, float d) { + Vector3 n(a, b, c); + float magnitude = n.magnitude(); + d /= magnitude; + n /= magnitude; + return Plane(n, -d); +} + + +void Plane::flip() { + _normal = -_normal; + _distance = -_distance; +} + + +void Plane::getEquation(Vector3& n, float& d) const { + double _d; + getEquation(n, _d); + d = (float)_d; +} + +void Plane::getEquation(Vector3& n, double& d) const { + n = _normal; + d = -_distance; +} + + +void Plane::getEquation(float& a, float& b, float& c, float& d) const { + double _a, _b, _c, _d; + getEquation(_a, _b, _c, _d); + a = (float)_a; + b = (float)_b; + c = (float)_c; + d = (float)_d; +} + +void Plane::getEquation(double& a, double& b, double& c, double& d) const { + a = _normal.x; + b = _normal.y; + c = _normal.z; + d = -_distance; +} + + +std::string Plane::toString() const { + return format("Plane(%g, %g, %g, %g)", _normal.x, _normal.y, _normal.z, _distance); +} + +} diff --git a/dep/g3dlite/Quat.cpp b/dep/g3dlite/Quat.cpp new file mode 100644 index 00000000000..225c5b51acc --- /dev/null +++ b/dep/g3dlite/Quat.cpp @@ -0,0 +1,583 @@ +/** + @file Quat.cpp + + Quaternion implementation based on Watt & Watt page 363 + + @author Morgan McGuire, graphics3d.com + + @created 2002-01-23 + @edited 2006-01-31 + */ + +#include "G3D/Quat.h" +#include "G3D/BinaryInput.h" +#include "G3D/BinaryOutput.h" + +namespace G3D { + +Quat Quat::fromAxisAngleRotation( + const Vector3& axis, + float angle) { + + Quat q; + + q.w = cos(angle / 2.0f); + q.imag() = axis.direction() * sin(angle / 2.0f); + + return q; +} + + +Quat::Quat( + const Matrix3& rot) { + + static const int plus1mod3[] = {1, 2, 0}; + + // Find the index of the largest diagonal component + // These ? operations hopefully compile to conditional + // move instructions instead of branches. + int i = (rot[1][1] > rot[0][0]) ? 1 : 0; + i = (rot[2][2] > rot[i][i]) ? 2 : i; + + // Find the indices of the other elements + int j = plus1mod3[i]; + int k = plus1mod3[j]; + + // Index the elements of the vector part of the quaternion as a float* + float* v = (float*)(this); + + // If we attempted to pre-normalize and trusted the matrix to be + // perfectly orthonormal, the result would be: + // + // double c = sqrt((rot[i][i] - (rot[j][j] + rot[k][k])) + 1.0) + // v[i] = -c * 0.5 + // v[j] = -(rot[i][j] + rot[j][i]) * 0.5 / c + // v[k] = -(rot[i][k] + rot[k][i]) * 0.5 / c + // w = (rot[j][k] - rot[k][j]) * 0.5 / c + // + // Since we're going to pay the sqrt anyway, we perform a post normalization, which also + // fixes any poorly normalized input. Multiply all elements by 2*c in the above, giving: + + // nc2 = -c^2 + double nc2 = ((rot[j][j] + rot[k][k]) - rot[i][i]) - 1.0; + v[i] = nc2; + w = (rot[j][k] - rot[k][j]); + v[j] = -(rot[i][j] + rot[j][i]); + v[k] = -(rot[i][k] + rot[k][i]); + + // We now have the correct result with the wrong magnitude, so normalize it: + float s = sqrt(x*x + y*y + z*z + w*w); + if (s > 0.00001f) { + s = 1.0f / s; + x *= s; + y *= s; + z *= s; + w *= s; + } else { + // The quaternion is nearly zero. Make it 0 0 0 1 + x = 0.0f; + y = 0.0f; + z = 0.0f; + w = 1.0f; + } +} + + +void Quat::toAxisAngleRotation( + Vector3& axis, + double& angle) const { + + // Decompose the quaternion into an angle and an axis. + + axis = Vector3(x, y, z); + angle = 2 * acos(w); + + float len = sqrt(1.0f - w * w); + + if (fuzzyGt(abs(len), 0.0f)) { + axis /= len; + } + + // Reduce the range of the angle. + + if (angle < 0) { + angle = -angle; + axis = -axis; + } + + while (angle > twoPi()) { + angle -= twoPi(); + } + + if (abs(angle) > pi()) { + angle -= twoPi(); + } + + // Make the angle positive. + + if (angle < 0.0f) { + angle = -angle; + axis = -axis; + } +} + + +Matrix3 Quat::toRotationMatrix() const { + Matrix3 out = Matrix3::zero(); + + toRotationMatrix(out); + + return out; +} + + +void Quat::toRotationMatrix( + Matrix3& rot) const { + + rot = Matrix3(*this); +} + + +Quat Quat::slerp( + const Quat& _quat1, + float alpha, + float threshold) const { + + // From: Game Physics -- David Eberly pg 538-540 + // Modified to include lerp for small angles, which + // is a common practice. + + // See also: + // http://number-none.com/product/Understanding%20Slerp,%20Then%20Not%20Using%20It/index.html + + const Quat& quat0 = *this; + Quat quat1 = _quat1; + + // angle between quaternion rotations + float phi; + float cosphi = quat0.dot(quat1); + + + if (cosphi < 0) { + // Change the sign and fix the dot product; we need to + // loop the other way to get the shortest path + quat1 = -quat1; + cosphi = -cosphi; + } + + // Using G3D::aCos will clamp the angle to 0 and pi + phi = static_cast(G3D::aCos(cosphi)); + + if (phi >= threshold) { + // For large angles, slerp + float scale0, scale1; + + scale0 = sin((1.0f - alpha) * phi); + scale1 = sin(alpha * phi); + + return ( (quat0 * scale0) + (quat1 * scale1) ) / sin(phi); + } else { + // For small angles, linear interpolate + return quat0.nlerp(quat1, alpha); + } +} + + +Quat Quat::nlerp( + const Quat& quat1, + float alpha) const { + + Quat result = (*this) * (1.0f - alpha) + quat1 * alpha; + return result / result.magnitude(); +} + + +Quat Quat::operator*(const Quat& other) const { + + // Following Watt & Watt, page 360 + const Vector3& v1 = imag(); + const Vector3& v2 = other.imag(); + float s1 = w; + float s2 = other.w; + + return Quat(s1*v2 + s2*v1 + v1.cross(v2), s1*s2 - v1.dot(v2)); +} + + +// From "Uniform Random Rotations", Ken Shoemake, Graphics Gems III. +Quat Quat::unitRandom() { + float x0 = uniformRandom(); + float r1 = sqrtf(1 - x0), + r2 = sqrtf(x0); + float t1 = (float)G3D::twoPi() * uniformRandom(); + float t2 = (float)G3D::twoPi() * uniformRandom(); + float c1 = cosf(t1), + s1 = sinf(t1); + float c2 = cosf(t2), + s2 = sinf(t2); + return Quat(s1 * r1, c1 * r1, s2 * r2, c2 * r2); +} + + +void Quat::deserialize(class BinaryInput& b) { + x = b.readFloat32(); + y = b.readFloat32(); + z = b.readFloat32(); + w = b.readFloat32(); +} + + +void Quat::serialize(class BinaryOutput& b) const { + b.writeFloat32(x); + b.writeFloat32(y); + b.writeFloat32(z); + b.writeFloat32(w); +} + + +// 2-char swizzles + +Vector2 Quat::xx() const { return Vector2 (x, x); } +Vector2 Quat::yx() const { return Vector2 (y, x); } +Vector2 Quat::zx() const { return Vector2 (z, x); } +Vector2 Quat::wx() const { return Vector2 (w, x); } +Vector2 Quat::xy() const { return Vector2 (x, y); } +Vector2 Quat::yy() const { return Vector2 (y, y); } +Vector2 Quat::zy() const { return Vector2 (z, y); } +Vector2 Quat::wy() const { return Vector2 (w, y); } +Vector2 Quat::xz() const { return Vector2 (x, z); } +Vector2 Quat::yz() const { return Vector2 (y, z); } +Vector2 Quat::zz() const { return Vector2 (z, z); } +Vector2 Quat::wz() const { return Vector2 (w, z); } +Vector2 Quat::xw() const { return Vector2 (x, w); } +Vector2 Quat::yw() const { return Vector2 (y, w); } +Vector2 Quat::zw() const { return Vector2 (z, w); } +Vector2 Quat::ww() const { return Vector2 (w, w); } + +// 3-char swizzles + +Vector3 Quat::xxx() const { return Vector3 (x, x, x); } +Vector3 Quat::yxx() const { return Vector3 (y, x, x); } +Vector3 Quat::zxx() const { return Vector3 (z, x, x); } +Vector3 Quat::wxx() const { return Vector3 (w, x, x); } +Vector3 Quat::xyx() const { return Vector3 (x, y, x); } +Vector3 Quat::yyx() const { return Vector3 (y, y, x); } +Vector3 Quat::zyx() const { return Vector3 (z, y, x); } +Vector3 Quat::wyx() const { return Vector3 (w, y, x); } +Vector3 Quat::xzx() const { return Vector3 (x, z, x); } +Vector3 Quat::yzx() const { return Vector3 (y, z, x); } +Vector3 Quat::zzx() const { return Vector3 (z, z, x); } +Vector3 Quat::wzx() const { return Vector3 (w, z, x); } +Vector3 Quat::xwx() const { return Vector3 (x, w, x); } +Vector3 Quat::ywx() const { return Vector3 (y, w, x); } +Vector3 Quat::zwx() const { return Vector3 (z, w, x); } +Vector3 Quat::wwx() const { return Vector3 (w, w, x); } +Vector3 Quat::xxy() const { return Vector3 (x, x, y); } +Vector3 Quat::yxy() const { return Vector3 (y, x, y); } +Vector3 Quat::zxy() const { return Vector3 (z, x, y); } +Vector3 Quat::wxy() const { return Vector3 (w, x, y); } +Vector3 Quat::xyy() const { return Vector3 (x, y, y); } +Vector3 Quat::yyy() const { return Vector3 (y, y, y); } +Vector3 Quat::zyy() const { return Vector3 (z, y, y); } +Vector3 Quat::wyy() const { return Vector3 (w, y, y); } +Vector3 Quat::xzy() const { return Vector3 (x, z, y); } +Vector3 Quat::yzy() const { return Vector3 (y, z, y); } +Vector3 Quat::zzy() const { return Vector3 (z, z, y); } +Vector3 Quat::wzy() const { return Vector3 (w, z, y); } +Vector3 Quat::xwy() const { return Vector3 (x, w, y); } +Vector3 Quat::ywy() const { return Vector3 (y, w, y); } +Vector3 Quat::zwy() const { return Vector3 (z, w, y); } +Vector3 Quat::wwy() const { return Vector3 (w, w, y); } +Vector3 Quat::xxz() const { return Vector3 (x, x, z); } +Vector3 Quat::yxz() const { return Vector3 (y, x, z); } +Vector3 Quat::zxz() const { return Vector3 (z, x, z); } +Vector3 Quat::wxz() const { return Vector3 (w, x, z); } +Vector3 Quat::xyz() const { return Vector3 (x, y, z); } +Vector3 Quat::yyz() const { return Vector3 (y, y, z); } +Vector3 Quat::zyz() const { return Vector3 (z, y, z); } +Vector3 Quat::wyz() const { return Vector3 (w, y, z); } +Vector3 Quat::xzz() const { return Vector3 (x, z, z); } +Vector3 Quat::yzz() const { return Vector3 (y, z, z); } +Vector3 Quat::zzz() const { return Vector3 (z, z, z); } +Vector3 Quat::wzz() const { return Vector3 (w, z, z); } +Vector3 Quat::xwz() const { return Vector3 (x, w, z); } +Vector3 Quat::ywz() const { return Vector3 (y, w, z); } +Vector3 Quat::zwz() const { return Vector3 (z, w, z); } +Vector3 Quat::wwz() const { return Vector3 (w, w, z); } +Vector3 Quat::xxw() const { return Vector3 (x, x, w); } +Vector3 Quat::yxw() const { return Vector3 (y, x, w); } +Vector3 Quat::zxw() const { return Vector3 (z, x, w); } +Vector3 Quat::wxw() const { return Vector3 (w, x, w); } +Vector3 Quat::xyw() const { return Vector3 (x, y, w); } +Vector3 Quat::yyw() const { return Vector3 (y, y, w); } +Vector3 Quat::zyw() const { return Vector3 (z, y, w); } +Vector3 Quat::wyw() const { return Vector3 (w, y, w); } +Vector3 Quat::xzw() const { return Vector3 (x, z, w); } +Vector3 Quat::yzw() const { return Vector3 (y, z, w); } +Vector3 Quat::zzw() const { return Vector3 (z, z, w); } +Vector3 Quat::wzw() const { return Vector3 (w, z, w); } +Vector3 Quat::xww() const { return Vector3 (x, w, w); } +Vector3 Quat::yww() const { return Vector3 (y, w, w); } +Vector3 Quat::zww() const { return Vector3 (z, w, w); } +Vector3 Quat::www() const { return Vector3 (w, w, w); } + +// 4-char swizzles + +Vector4 Quat::xxxx() const { return Vector4 (x, x, x, x); } +Vector4 Quat::yxxx() const { return Vector4 (y, x, x, x); } +Vector4 Quat::zxxx() const { return Vector4 (z, x, x, x); } +Vector4 Quat::wxxx() const { return Vector4 (w, x, x, x); } +Vector4 Quat::xyxx() const { return Vector4 (x, y, x, x); } +Vector4 Quat::yyxx() const { return Vector4 (y, y, x, x); } +Vector4 Quat::zyxx() const { return Vector4 (z, y, x, x); } +Vector4 Quat::wyxx() const { return Vector4 (w, y, x, x); } +Vector4 Quat::xzxx() const { return Vector4 (x, z, x, x); } +Vector4 Quat::yzxx() const { return Vector4 (y, z, x, x); } +Vector4 Quat::zzxx() const { return Vector4 (z, z, x, x); } +Vector4 Quat::wzxx() const { return Vector4 (w, z, x, x); } +Vector4 Quat::xwxx() const { return Vector4 (x, w, x, x); } +Vector4 Quat::ywxx() const { return Vector4 (y, w, x, x); } +Vector4 Quat::zwxx() const { return Vector4 (z, w, x, x); } +Vector4 Quat::wwxx() const { return Vector4 (w, w, x, x); } +Vector4 Quat::xxyx() const { return Vector4 (x, x, y, x); } +Vector4 Quat::yxyx() const { return Vector4 (y, x, y, x); } +Vector4 Quat::zxyx() const { return Vector4 (z, x, y, x); } +Vector4 Quat::wxyx() const { return Vector4 (w, x, y, x); } +Vector4 Quat::xyyx() const { return Vector4 (x, y, y, x); } +Vector4 Quat::yyyx() const { return Vector4 (y, y, y, x); } +Vector4 Quat::zyyx() const { return Vector4 (z, y, y, x); } +Vector4 Quat::wyyx() const { return Vector4 (w, y, y, x); } +Vector4 Quat::xzyx() const { return Vector4 (x, z, y, x); } +Vector4 Quat::yzyx() const { return Vector4 (y, z, y, x); } +Vector4 Quat::zzyx() const { return Vector4 (z, z, y, x); } +Vector4 Quat::wzyx() const { return Vector4 (w, z, y, x); } +Vector4 Quat::xwyx() const { return Vector4 (x, w, y, x); } +Vector4 Quat::ywyx() const { return Vector4 (y, w, y, x); } +Vector4 Quat::zwyx() const { return Vector4 (z, w, y, x); } +Vector4 Quat::wwyx() const { return Vector4 (w, w, y, x); } +Vector4 Quat::xxzx() const { return Vector4 (x, x, z, x); } +Vector4 Quat::yxzx() const { return Vector4 (y, x, z, x); } +Vector4 Quat::zxzx() const { return Vector4 (z, x, z, x); } +Vector4 Quat::wxzx() const { return Vector4 (w, x, z, x); } +Vector4 Quat::xyzx() const { return Vector4 (x, y, z, x); } +Vector4 Quat::yyzx() const { return Vector4 (y, y, z, x); } +Vector4 Quat::zyzx() const { return Vector4 (z, y, z, x); } +Vector4 Quat::wyzx() const { return Vector4 (w, y, z, x); } +Vector4 Quat::xzzx() const { return Vector4 (x, z, z, x); } +Vector4 Quat::yzzx() const { return Vector4 (y, z, z, x); } +Vector4 Quat::zzzx() const { return Vector4 (z, z, z, x); } +Vector4 Quat::wzzx() const { return Vector4 (w, z, z, x); } +Vector4 Quat::xwzx() const { return Vector4 (x, w, z, x); } +Vector4 Quat::ywzx() const { return Vector4 (y, w, z, x); } +Vector4 Quat::zwzx() const { return Vector4 (z, w, z, x); } +Vector4 Quat::wwzx() const { return Vector4 (w, w, z, x); } +Vector4 Quat::xxwx() const { return Vector4 (x, x, w, x); } +Vector4 Quat::yxwx() const { return Vector4 (y, x, w, x); } +Vector4 Quat::zxwx() const { return Vector4 (z, x, w, x); } +Vector4 Quat::wxwx() const { return Vector4 (w, x, w, x); } +Vector4 Quat::xywx() const { return Vector4 (x, y, w, x); } +Vector4 Quat::yywx() const { return Vector4 (y, y, w, x); } +Vector4 Quat::zywx() const { return Vector4 (z, y, w, x); } +Vector4 Quat::wywx() const { return Vector4 (w, y, w, x); } +Vector4 Quat::xzwx() const { return Vector4 (x, z, w, x); } +Vector4 Quat::yzwx() const { return Vector4 (y, z, w, x); } +Vector4 Quat::zzwx() const { return Vector4 (z, z, w, x); } +Vector4 Quat::wzwx() const { return Vector4 (w, z, w, x); } +Vector4 Quat::xwwx() const { return Vector4 (x, w, w, x); } +Vector4 Quat::ywwx() const { return Vector4 (y, w, w, x); } +Vector4 Quat::zwwx() const { return Vector4 (z, w, w, x); } +Vector4 Quat::wwwx() const { return Vector4 (w, w, w, x); } +Vector4 Quat::xxxy() const { return Vector4 (x, x, x, y); } +Vector4 Quat::yxxy() const { return Vector4 (y, x, x, y); } +Vector4 Quat::zxxy() const { return Vector4 (z, x, x, y); } +Vector4 Quat::wxxy() const { return Vector4 (w, x, x, y); } +Vector4 Quat::xyxy() const { return Vector4 (x, y, x, y); } +Vector4 Quat::yyxy() const { return Vector4 (y, y, x, y); } +Vector4 Quat::zyxy() const { return Vector4 (z, y, x, y); } +Vector4 Quat::wyxy() const { return Vector4 (w, y, x, y); } +Vector4 Quat::xzxy() const { return Vector4 (x, z, x, y); } +Vector4 Quat::yzxy() const { return Vector4 (y, z, x, y); } +Vector4 Quat::zzxy() const { return Vector4 (z, z, x, y); } +Vector4 Quat::wzxy() const { return Vector4 (w, z, x, y); } +Vector4 Quat::xwxy() const { return Vector4 (x, w, x, y); } +Vector4 Quat::ywxy() const { return Vector4 (y, w, x, y); } +Vector4 Quat::zwxy() const { return Vector4 (z, w, x, y); } +Vector4 Quat::wwxy() const { return Vector4 (w, w, x, y); } +Vector4 Quat::xxyy() const { return Vector4 (x, x, y, y); } +Vector4 Quat::yxyy() const { return Vector4 (y, x, y, y); } +Vector4 Quat::zxyy() const { return Vector4 (z, x, y, y); } +Vector4 Quat::wxyy() const { return Vector4 (w, x, y, y); } +Vector4 Quat::xyyy() const { return Vector4 (x, y, y, y); } +Vector4 Quat::yyyy() const { return Vector4 (y, y, y, y); } +Vector4 Quat::zyyy() const { return Vector4 (z, y, y, y); } +Vector4 Quat::wyyy() const { return Vector4 (w, y, y, y); } +Vector4 Quat::xzyy() const { return Vector4 (x, z, y, y); } +Vector4 Quat::yzyy() const { return Vector4 (y, z, y, y); } +Vector4 Quat::zzyy() const { return Vector4 (z, z, y, y); } +Vector4 Quat::wzyy() const { return Vector4 (w, z, y, y); } +Vector4 Quat::xwyy() const { return Vector4 (x, w, y, y); } +Vector4 Quat::ywyy() const { return Vector4 (y, w, y, y); } +Vector4 Quat::zwyy() const { return Vector4 (z, w, y, y); } +Vector4 Quat::wwyy() const { return Vector4 (w, w, y, y); } +Vector4 Quat::xxzy() const { return Vector4 (x, x, z, y); } +Vector4 Quat::yxzy() const { return Vector4 (y, x, z, y); } +Vector4 Quat::zxzy() const { return Vector4 (z, x, z, y); } +Vector4 Quat::wxzy() const { return Vector4 (w, x, z, y); } +Vector4 Quat::xyzy() const { return Vector4 (x, y, z, y); } +Vector4 Quat::yyzy() const { return Vector4 (y, y, z, y); } +Vector4 Quat::zyzy() const { return Vector4 (z, y, z, y); } +Vector4 Quat::wyzy() const { return Vector4 (w, y, z, y); } +Vector4 Quat::xzzy() const { return Vector4 (x, z, z, y); } +Vector4 Quat::yzzy() const { return Vector4 (y, z, z, y); } +Vector4 Quat::zzzy() const { return Vector4 (z, z, z, y); } +Vector4 Quat::wzzy() const { return Vector4 (w, z, z, y); } +Vector4 Quat::xwzy() const { return Vector4 (x, w, z, y); } +Vector4 Quat::ywzy() const { return Vector4 (y, w, z, y); } +Vector4 Quat::zwzy() const { return Vector4 (z, w, z, y); } +Vector4 Quat::wwzy() const { return Vector4 (w, w, z, y); } +Vector4 Quat::xxwy() const { return Vector4 (x, x, w, y); } +Vector4 Quat::yxwy() const { return Vector4 (y, x, w, y); } +Vector4 Quat::zxwy() const { return Vector4 (z, x, w, y); } +Vector4 Quat::wxwy() const { return Vector4 (w, x, w, y); } +Vector4 Quat::xywy() const { return Vector4 (x, y, w, y); } +Vector4 Quat::yywy() const { return Vector4 (y, y, w, y); } +Vector4 Quat::zywy() const { return Vector4 (z, y, w, y); } +Vector4 Quat::wywy() const { return Vector4 (w, y, w, y); } +Vector4 Quat::xzwy() const { return Vector4 (x, z, w, y); } +Vector4 Quat::yzwy() const { return Vector4 (y, z, w, y); } +Vector4 Quat::zzwy() const { return Vector4 (z, z, w, y); } +Vector4 Quat::wzwy() const { return Vector4 (w, z, w, y); } +Vector4 Quat::xwwy() const { return Vector4 (x, w, w, y); } +Vector4 Quat::ywwy() const { return Vector4 (y, w, w, y); } +Vector4 Quat::zwwy() const { return Vector4 (z, w, w, y); } +Vector4 Quat::wwwy() const { return Vector4 (w, w, w, y); } +Vector4 Quat::xxxz() const { return Vector4 (x, x, x, z); } +Vector4 Quat::yxxz() const { return Vector4 (y, x, x, z); } +Vector4 Quat::zxxz() const { return Vector4 (z, x, x, z); } +Vector4 Quat::wxxz() const { return Vector4 (w, x, x, z); } +Vector4 Quat::xyxz() const { return Vector4 (x, y, x, z); } +Vector4 Quat::yyxz() const { return Vector4 (y, y, x, z); } +Vector4 Quat::zyxz() const { return Vector4 (z, y, x, z); } +Vector4 Quat::wyxz() const { return Vector4 (w, y, x, z); } +Vector4 Quat::xzxz() const { return Vector4 (x, z, x, z); } +Vector4 Quat::yzxz() const { return Vector4 (y, z, x, z); } +Vector4 Quat::zzxz() const { return Vector4 (z, z, x, z); } +Vector4 Quat::wzxz() const { return Vector4 (w, z, x, z); } +Vector4 Quat::xwxz() const { return Vector4 (x, w, x, z); } +Vector4 Quat::ywxz() const { return Vector4 (y, w, x, z); } +Vector4 Quat::zwxz() const { return Vector4 (z, w, x, z); } +Vector4 Quat::wwxz() const { return Vector4 (w, w, x, z); } +Vector4 Quat::xxyz() const { return Vector4 (x, x, y, z); } +Vector4 Quat::yxyz() const { return Vector4 (y, x, y, z); } +Vector4 Quat::zxyz() const { return Vector4 (z, x, y, z); } +Vector4 Quat::wxyz() const { return Vector4 (w, x, y, z); } +Vector4 Quat::xyyz() const { return Vector4 (x, y, y, z); } +Vector4 Quat::yyyz() const { return Vector4 (y, y, y, z); } +Vector4 Quat::zyyz() const { return Vector4 (z, y, y, z); } +Vector4 Quat::wyyz() const { return Vector4 (w, y, y, z); } +Vector4 Quat::xzyz() const { return Vector4 (x, z, y, z); } +Vector4 Quat::yzyz() const { return Vector4 (y, z, y, z); } +Vector4 Quat::zzyz() const { return Vector4 (z, z, y, z); } +Vector4 Quat::wzyz() const { return Vector4 (w, z, y, z); } +Vector4 Quat::xwyz() const { return Vector4 (x, w, y, z); } +Vector4 Quat::ywyz() const { return Vector4 (y, w, y, z); } +Vector4 Quat::zwyz() const { return Vector4 (z, w, y, z); } +Vector4 Quat::wwyz() const { return Vector4 (w, w, y, z); } +Vector4 Quat::xxzz() const { return Vector4 (x, x, z, z); } +Vector4 Quat::yxzz() const { return Vector4 (y, x, z, z); } +Vector4 Quat::zxzz() const { return Vector4 (z, x, z, z); } +Vector4 Quat::wxzz() const { return Vector4 (w, x, z, z); } +Vector4 Quat::xyzz() const { return Vector4 (x, y, z, z); } +Vector4 Quat::yyzz() const { return Vector4 (y, y, z, z); } +Vector4 Quat::zyzz() const { return Vector4 (z, y, z, z); } +Vector4 Quat::wyzz() const { return Vector4 (w, y, z, z); } +Vector4 Quat::xzzz() const { return Vector4 (x, z, z, z); } +Vector4 Quat::yzzz() const { return Vector4 (y, z, z, z); } +Vector4 Quat::zzzz() const { return Vector4 (z, z, z, z); } +Vector4 Quat::wzzz() const { return Vector4 (w, z, z, z); } +Vector4 Quat::xwzz() const { return Vector4 (x, w, z, z); } +Vector4 Quat::ywzz() const { return Vector4 (y, w, z, z); } +Vector4 Quat::zwzz() const { return Vector4 (z, w, z, z); } +Vector4 Quat::wwzz() const { return Vector4 (w, w, z, z); } +Vector4 Quat::xxwz() const { return Vector4 (x, x, w, z); } +Vector4 Quat::yxwz() const { return Vector4 (y, x, w, z); } +Vector4 Quat::zxwz() const { return Vector4 (z, x, w, z); } +Vector4 Quat::wxwz() const { return Vector4 (w, x, w, z); } +Vector4 Quat::xywz() const { return Vector4 (x, y, w, z); } +Vector4 Quat::yywz() const { return Vector4 (y, y, w, z); } +Vector4 Quat::zywz() const { return Vector4 (z, y, w, z); } +Vector4 Quat::wywz() const { return Vector4 (w, y, w, z); } +Vector4 Quat::xzwz() const { return Vector4 (x, z, w, z); } +Vector4 Quat::yzwz() const { return Vector4 (y, z, w, z); } +Vector4 Quat::zzwz() const { return Vector4 (z, z, w, z); } +Vector4 Quat::wzwz() const { return Vector4 (w, z, w, z); } +Vector4 Quat::xwwz() const { return Vector4 (x, w, w, z); } +Vector4 Quat::ywwz() const { return Vector4 (y, w, w, z); } +Vector4 Quat::zwwz() const { return Vector4 (z, w, w, z); } +Vector4 Quat::wwwz() const { return Vector4 (w, w, w, z); } +Vector4 Quat::xxxw() const { return Vector4 (x, x, x, w); } +Vector4 Quat::yxxw() const { return Vector4 (y, x, x, w); } +Vector4 Quat::zxxw() const { return Vector4 (z, x, x, w); } +Vector4 Quat::wxxw() const { return Vector4 (w, x, x, w); } +Vector4 Quat::xyxw() const { return Vector4 (x, y, x, w); } +Vector4 Quat::yyxw() const { return Vector4 (y, y, x, w); } +Vector4 Quat::zyxw() const { return Vector4 (z, y, x, w); } +Vector4 Quat::wyxw() const { return Vector4 (w, y, x, w); } +Vector4 Quat::xzxw() const { return Vector4 (x, z, x, w); } +Vector4 Quat::yzxw() const { return Vector4 (y, z, x, w); } +Vector4 Quat::zzxw() const { return Vector4 (z, z, x, w); } +Vector4 Quat::wzxw() const { return Vector4 (w, z, x, w); } +Vector4 Quat::xwxw() const { return Vector4 (x, w, x, w); } +Vector4 Quat::ywxw() const { return Vector4 (y, w, x, w); } +Vector4 Quat::zwxw() const { return Vector4 (z, w, x, w); } +Vector4 Quat::wwxw() const { return Vector4 (w, w, x, w); } +Vector4 Quat::xxyw() const { return Vector4 (x, x, y, w); } +Vector4 Quat::yxyw() const { return Vector4 (y, x, y, w); } +Vector4 Quat::zxyw() const { return Vector4 (z, x, y, w); } +Vector4 Quat::wxyw() const { return Vector4 (w, x, y, w); } +Vector4 Quat::xyyw() const { return Vector4 (x, y, y, w); } +Vector4 Quat::yyyw() const { return Vector4 (y, y, y, w); } +Vector4 Quat::zyyw() const { return Vector4 (z, y, y, w); } +Vector4 Quat::wyyw() const { return Vector4 (w, y, y, w); } +Vector4 Quat::xzyw() const { return Vector4 (x, z, y, w); } +Vector4 Quat::yzyw() const { return Vector4 (y, z, y, w); } +Vector4 Quat::zzyw() const { return Vector4 (z, z, y, w); } +Vector4 Quat::wzyw() const { return Vector4 (w, z, y, w); } +Vector4 Quat::xwyw() const { return Vector4 (x, w, y, w); } +Vector4 Quat::ywyw() const { return Vector4 (y, w, y, w); } +Vector4 Quat::zwyw() const { return Vector4 (z, w, y, w); } +Vector4 Quat::wwyw() const { return Vector4 (w, w, y, w); } +Vector4 Quat::xxzw() const { return Vector4 (x, x, z, w); } +Vector4 Quat::yxzw() const { return Vector4 (y, x, z, w); } +Vector4 Quat::zxzw() const { return Vector4 (z, x, z, w); } +Vector4 Quat::wxzw() const { return Vector4 (w, x, z, w); } +Vector4 Quat::xyzw() const { return Vector4 (x, y, z, w); } +Vector4 Quat::yyzw() const { return Vector4 (y, y, z, w); } +Vector4 Quat::zyzw() const { return Vector4 (z, y, z, w); } +Vector4 Quat::wyzw() const { return Vector4 (w, y, z, w); } +Vector4 Quat::xzzw() const { return Vector4 (x, z, z, w); } +Vector4 Quat::yzzw() const { return Vector4 (y, z, z, w); } +Vector4 Quat::zzzw() const { return Vector4 (z, z, z, w); } +Vector4 Quat::wzzw() const { return Vector4 (w, z, z, w); } +Vector4 Quat::xwzw() const { return Vector4 (x, w, z, w); } +Vector4 Quat::ywzw() const { return Vector4 (y, w, z, w); } +Vector4 Quat::zwzw() const { return Vector4 (z, w, z, w); } +Vector4 Quat::wwzw() const { return Vector4 (w, w, z, w); } +Vector4 Quat::xxww() const { return Vector4 (x, x, w, w); } +Vector4 Quat::yxww() const { return Vector4 (y, x, w, w); } +Vector4 Quat::zxww() const { return Vector4 (z, x, w, w); } +Vector4 Quat::wxww() const { return Vector4 (w, x, w, w); } +Vector4 Quat::xyww() const { return Vector4 (x, y, w, w); } +Vector4 Quat::yyww() const { return Vector4 (y, y, w, w); } +Vector4 Quat::zyww() const { return Vector4 (z, y, w, w); } +Vector4 Quat::wyww() const { return Vector4 (w, y, w, w); } +Vector4 Quat::xzww() const { return Vector4 (x, z, w, w); } +Vector4 Quat::yzww() const { return Vector4 (y, z, w, w); } +Vector4 Quat::zzww() const { return Vector4 (z, z, w, w); } +Vector4 Quat::wzww() const { return Vector4 (w, z, w, w); } +Vector4 Quat::xwww() const { return Vector4 (x, w, w, w); } +Vector4 Quat::ywww() const { return Vector4 (y, w, w, w); } +Vector4 Quat::zwww() const { return Vector4 (z, w, w, w); } +Vector4 Quat::wwww() const { return Vector4 (w, w, w, w); } +} + diff --git a/dep/g3dlite/Random.cpp b/dep/g3dlite/Random.cpp new file mode 100644 index 00000000000..2dda744a1ac --- /dev/null +++ b/dep/g3dlite/Random.cpp @@ -0,0 +1,212 @@ +/** + @file Random.cpp + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2009-01-02 + @edited 2009-03-29 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ +#include "G3D/Random.h" + +namespace G3D { + +Random& Random::common() { + static Random r; + return r; +} + +Random::Random(void* x) : state(NULL), m_threadsafe(false) { + (void)x; +} + + +Random::Random(uint32 seed, bool threadsafe) : m_threadsafe(threadsafe) { + const uint32 X = 1812433253UL; + + state = new uint32[N]; + state[0] = seed; + for (index = 1; index < (int)N; ++index) { + state[index] = X * (state[index - 1] ^ (state[index - 1] >> 30)) + index; + } +} + + +Random::~Random() { + delete[] state; + state = NULL; +} + + +uint32 Random::bits() { + // See http://en.wikipedia.org/wiki/Mersenne_twister + + // Make a local copy of the index variable to ensure that it + // is not out of bounds + int localIndex = index; + + // Automatically checks for index < 0 if corrupted + // by unsynchronized threads. + if ((unsigned int)localIndex >= (unsigned int)N) { + generate(); + localIndex = 0; + } + // Increment the global index. It may go out of bounds on + // multiple threads, but the above check ensures that the + // array index actually used never goes out of bounds. + // It doesn't matter if we grab the same array index twice + // on two threads, since the distribution of random numbers + // will still be uniform. + ++index; + // Return the next random in the sequence + uint32 r = state[localIndex]; + + // Temper the result + r ^= r >> U; + r ^= (r << S) & B; + r ^= (r << T) & C; + r ^= r >> L; + + return r; +} + + +/** Generate the next N ints, and store them for readback later */ +void Random::generate() { + // Lower R bits + static const uint32 LOWER_MASK = (1LU << R) - 1; + + // Upper (32 - R) bits + static const uint32 UPPER_MASK = 0xFFFFFFFF << R; + static const uint32 mag01[2] = {0UL, (uint32)A}; + + if (m_threadsafe) { + bool contention = ! lock.lock(); + if (contention) { + // Another thread just generated a set of numbers; no need for + // this thread to do it too + lock.unlock(); + return; + } + } + + // First N - M + for (unsigned int i = 0; i < N - M; ++i) { + uint32 x = (state[i] & UPPER_MASK) | (state[i + 1] & LOWER_MASK); + state[i] = state[i + M] ^ (x >> 1) ^ mag01[x & 1]; + } + + // Rest + for (unsigned int i = N - M + 1; i < N - 1; ++i) { + uint32 x = (state[i] & UPPER_MASK) | (state[i + 1] & LOWER_MASK); + state[i] = state[i + (M - N)] ^ (x >> 1) ^ mag01[x & 1]; + } + + uint32 y = (state[N - 1] & UPPER_MASK) | (state[0] & LOWER_MASK); + state[N - 1] = state[M - 1] ^ (y >> 1) ^ mag01[y & 1]; + index = 0; + + if (m_threadsafe) { + lock.unlock(); + } +} + + +int Random::integer(int low, int high) { + int r = iFloor(low + (high - low + 1) * (double)bits() / 0xFFFFFFFFUL); + + // There is a *very small* chance of generating + // a number larger than high. + if (r > high) { + return high; + } else { + return r; + } +} + + +float Random::gaussian(float mean, float stdev) { + + // Using Box-Mueller method from http://www.taygeta.com/random/gaussian.html + // Modified to specify standard deviation and mean of distribution + float w, x1, x2; + + // Loop until w is less than 1 so that log(w) is negative + do { + x1 = uniform(-1.0, 1.0); + x2 = uniform(-1.0, 1.0); + + w = float(square(x1) + square(x2)); + } while (w > 1.0f); + + // Transform to gassian distribution + // Multiply by sigma (stdev ^ 2) and add mean. + return x2 * (float)square(stdev) * sqrtf((-2.0f * logf(w) ) / w) + mean; +} + + +void Random::cosHemi(float& x, float& y, float& z) { + const float e1 = uniform(); + const float e2 = uniform(); + + // Jensen's method + const float sin_theta = sqrtf(1.0f - e1); + const float cos_theta = sqrtf(e1); + const float phi = 6.28318531f * e2; + + x = cos(phi) * sin_theta; + y = sin(phi) * sin_theta; + z = cos_theta; + + // We could also use Malley's method (pbrt p.657), since they are the same cost: + // + // r = sqrt(e1); + // t = 2*pi*e2; + // x = cos(t)*r; + // y = sin(t)*r; + // z = sqrt(1.0 - x*x + y*y); +} + + +void Random::cosPowHemi(const float k, float& x, float& y, float& z) { + const float e1 = uniform(); + const float e2 = uniform(); + + const float cos_theta = pow(e1, 1.0f / (k + 1.0f)); + const float sin_theta = sqrtf(1.0f - square(cos_theta)); + const float phi = 6.28318531f * e2; + + x = cos(phi) * sin_theta; + y = sin(phi) * sin_theta; + z = cos_theta; +} + + +void Random::hemi(float& x, float& y, float& z) { + sphere(x, y, z); + z = fabsf(z); +} + + +void Random::sphere(float& x, float& y, float& z) { + // Squared magnitude + float m2; + + // Rejection sample + do { + x = uniform() * 2.0f - 1.0f, + y = uniform() * 2.0f - 1.0f, + z = uniform() * 2.0f - 1.0f; + m2 = x*x + y*y + z*z; + } while (m2 >= 1.0f); + + // Divide by magnitude to produce a unit vector + float s = rsqrt(m2); + x *= s; + y *= s; + z *= s; +} + +} // G3D diff --git a/dep/g3dlite/Ray.cpp b/dep/g3dlite/Ray.cpp new file mode 100644 index 00000000000..0436ef0b323 --- /dev/null +++ b/dep/g3dlite/Ray.cpp @@ -0,0 +1,218 @@ +/** + @file Ray.cpp + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2002-07-12 + @edited 2004-03-19 + */ + +#include "G3D/platform.h" +#include "G3D/Ray.h" +#include "G3D/Plane.h" +#include "G3D/Sphere.h" +#include "G3D/CollisionDetection.h" + +namespace G3D { + +void Ray::set(const Vector3& origin, const Vector3& direction) { + m_origin = origin; + m_direction = direction; + debugAssert(direction.isUnit()); + + m_invDirection = Vector3::one() / direction; + + // ray slope + ibyj = m_direction.x * m_invDirection.y; + jbyi = m_direction.y * m_invDirection.x; + jbyk = m_direction.y * m_invDirection.z; + kbyj = m_direction.z * m_invDirection.y; + ibyk = m_direction.x * m_invDirection.z; + kbyi = m_direction.z * m_invDirection.x; + + // precomputed terms + c_xy = m_origin.y - jbyi * m_origin.x; + c_xz = m_origin.z - kbyi * m_origin.x; + c_yx = m_origin.x - ibyj * m_origin.y; + c_yz = m_origin.z - kbyj * m_origin.y; + c_zx = m_origin.x - ibyk * m_origin.z; + c_zy = m_origin.y - jbyk * m_origin.z; + + //ray slope classification + if (m_direction.x < 0) { + if (m_direction.y < 0) { + if (m_direction.z < 0) { + classification = MMM; + } else if (m_direction.z > 0) { + classification = MMP; + } else { //(m_direction.z >= 0) + classification = MMO; + } + } else { //(m_direction.y >= 0) + if (m_direction.z < 0) { + if (m_direction.y == 0) { + classification = MOM; + } else { + classification = MPM; + } + } else { //(m_direction.z >= 0) + if ((m_direction.y == 0) && (m_direction.z == 0)) { + classification = MOO; + } else if (m_direction.z == 0) { + classification = MPO; + } else if (m_direction.y == 0) { + classification = MOP; + } else { + classification = MPP; + } + } + } + } else { //(m_direction.x >= 0) + if (m_direction.y < 0) { + if (m_direction.z < 0) { + if (m_direction.x == 0) { + classification = OMM; + } else { + classification = PMM; + } + } else { //(m_direction.z >= 0) + if ((m_direction.x == 0) && (m_direction.z == 0)) { + classification = OMO; + } else if (m_direction.z == 0) { + classification = PMO; + } else if (m_direction.x == 0) { + classification = OMP; + } else { + classification = PMP; + } + } + } else { //(m_direction.y >= 0) + if (m_direction.z < 0) { + if ((m_direction.x == 0) && (m_direction.y == 0)) { + classification = OOM; + } else if (m_direction.x == 0) { + classification = OPM; + } else if (m_direction.y == 0) { + classification = POM; + } else { + classification = PPM; + } + } else { //(m_direction.z > 0) + if (m_direction.x == 0) { + if (m_direction.y == 0) { + classification = OOP; + } else if (m_direction.z == 0) { + classification = OPO; + } else { + classification = OPP; + } + } else { + if ((m_direction.y == 0) && (m_direction.z == 0)) { + classification = POO; + } else if (m_direction.y == 0) { + classification = POP; + } else if (m_direction.z == 0) { + classification = PPO; + } else { + classification = PPP; + } + } + } + } + } +} + +Ray::Ray(class BinaryInput& b) { + deserialize(b); +} + + +void Ray::serialize(class BinaryOutput& b) const { + m_origin.serialize(b); + m_direction.serialize(b); +} + + +void Ray::deserialize(class BinaryInput& b) { + m_origin.deserialize(b); + m_direction.deserialize(b); + set(m_origin, m_direction); +} + + +Ray Ray::refract( + const Vector3& newOrigin, + const Vector3& normal, + float iInside, + float iOutside) const { + + Vector3 D = m_direction.refractionDirection(normal, iInside, iOutside); + return Ray(newOrigin + (m_direction + normal * (float)sign(m_direction.dot(normal))) * 0.001f, D); +} + + +Ray Ray::reflect( + const Vector3& newOrigin, + const Vector3& normal) const { + + Vector3 D = m_direction.reflectionDirection(normal); + return Ray(newOrigin + (D + normal) * 0.001f, D); +} + + +Vector3 Ray::intersection(const Plane& plane) const { + float d; + Vector3 normal = plane.normal(); + plane.getEquation(normal, d); + float rate = m_direction.dot(normal); + + if (rate >= 0.0f) { + return Vector3::inf(); + } else { + float t = -(d + m_origin.dot(normal)) / rate; + return m_origin + m_direction * t; + } +} + + +float Ray::intersectionTime(const class Sphere& sphere, bool solid) const { + Vector3 dummy; + return CollisionDetection::collisionTimeForMovingPointFixedSphere( + m_origin, m_direction, sphere, dummy, dummy, solid); +} + + +float Ray::intersectionTime(const class Plane& plane) const { + Vector3 dummy; + return CollisionDetection::collisionTimeForMovingPointFixedPlane( + m_origin, m_direction, plane, dummy); +} + + +float Ray::intersectionTime(const class Box& box) const { + Vector3 dummy; + float time = CollisionDetection::collisionTimeForMovingPointFixedBox( + m_origin, m_direction, box, dummy); + + if ((time == finf()) && (box.contains(m_origin))) { + return 0.0f; + } else { + return time; + } +} + + +float Ray::intersectionTime(const class AABox& box) const { + Vector3 dummy; + bool inside; + float time = CollisionDetection::collisionTimeForMovingPointFixedAABox( + m_origin, m_direction, box, dummy, inside); + + if ((time == finf()) && inside) { + return 0.0f; + } else { + return time; + } +} + +} diff --git a/dep/g3dlite/ReferenceCount.cpp b/dep/g3dlite/ReferenceCount.cpp new file mode 100644 index 00000000000..2e1f117e0d9 --- /dev/null +++ b/dep/g3dlite/ReferenceCount.cpp @@ -0,0 +1,61 @@ +/** + @file ReferenceCount.cpp + + Reference Counting Garbage Collector for C++ + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + @cite Adapted and extended from Justin Miller's "RGC" class that appeared in BYTE magazine. + @cite See also http://www.jelovic.com/articles/cpp_without_memory_errors_slides.htm + + @created 2001-10-23 + @edited 2009-04-25 +*/ +#include "G3D/platform.h" +#include "G3D/ReferenceCount.h" + +namespace G3D { + +ReferenceCountedObject::ReferenceCountedObject() : + ReferenceCountedObject_refCount(0), + ReferenceCountedObject_weakPointer(0) { + + debugAssertM(isValidHeapPointer(this), + "Reference counted objects must be allocated on the heap."); +} + +void ReferenceCountedObject::ReferenceCountedObject_zeroWeakPointers() { + // Tell all of my weak pointers that I'm gone. + + _WeakPtrLinkedList* node = ReferenceCountedObject_weakPointer; + + while (node != NULL) { + // Notify the weak pointer that it is going away + node->weakPtr->objectCollected(); + + // Free the node and advance + _WeakPtrLinkedList* tmp = node; + node = node->next; + delete tmp; + } +} + +ReferenceCountedObject::~ReferenceCountedObject() {} + + +ReferenceCountedObject::ReferenceCountedObject(const ReferenceCountedObject& notUsed) : + ReferenceCountedObject_refCount(0), + ReferenceCountedObject_weakPointer(0) { + (void)notUsed; + debugAssertM(G3D::isValidHeapPointer(this), + "Reference counted objects must be allocated on the heap."); +} + +ReferenceCountedObject& ReferenceCountedObject::operator=(const ReferenceCountedObject& other) { + (void)other; + // Nothing changes when I am assigned; the reference count on + // both objects is the same (although my super-class probably + // changes). + return *this; +} + +} // G3D diff --git a/dep/g3dlite/RegistryUtil.cpp b/dep/g3dlite/RegistryUtil.cpp new file mode 100644 index 00000000000..fc4cebc2ee5 --- /dev/null +++ b/dep/g3dlite/RegistryUtil.cpp @@ -0,0 +1,290 @@ +/** + @file RegistryUtil.cpp + + @created 2006-04-06 + @edited 2006-04-24 + + Copyright 2000-2006, Morgan McGuire. + All rights reserved. +*/ + +#include "G3D/platform.h" + +// This file is only used on Windows +#ifdef G3D_WIN32 + +#include "G3D/RegistryUtil.h" +#include "G3D/System.h" + +namespace G3D { + +// static helpers +static HKEY getRootKeyFromString(const char* str, size_t length); + + +bool RegistryUtil::keyExists(const std::string& key) { + size_t pos = key.find('\\', 0); + if (pos == std::string::npos) { + return false; + } + + HKEY hkey = getRootKeyFromString(key.c_str(), pos); + + if (hkey == NULL) { + return false; + } + + HKEY openKey; + int32 result = RegOpenKeyExA(hkey, (key.c_str() + pos + 1), 0, KEY_READ, &openKey); + + debugAssert(result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND); + + if (result == ERROR_SUCCESS) { + RegCloseKey(openKey); + return true; + } else { + return false; + } +} + +bool RegistryUtil::valueExists(const std::string& key, const std::string& value) { + size_t pos = key.find('\\', 0); + if (pos == std::string::npos) { + return false; + } + + HKEY hkey = getRootKeyFromString(key.c_str(), pos); + + if ( hkey == NULL ) { + return false; + } + + HKEY openKey; + int32 result = RegOpenKeyExA(hkey, (key.c_str() + pos + 1), 0, KEY_READ, &openKey); + debugAssert(result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND); + + if (result == ERROR_SUCCESS) { + uint32 dataSize = 0; + result = RegQueryValueExA(openKey, value.c_str(), NULL, NULL, NULL, reinterpret_cast(&dataSize)); + + debugAssert(result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND); + RegCloseKey(openKey); + } + return (result == ERROR_SUCCESS); +} + + +bool RegistryUtil::readInt32(const std::string& key, const std::string& value, int32& data) { + size_t pos = key.find('\\', 0); + if (pos == std::string::npos) { + return false; + } + + HKEY hkey = getRootKeyFromString(key.c_str(), pos); + + if ( hkey == NULL ) { + return false; + } + + HKEY openKey; + int32 result = RegOpenKeyExA(hkey, (key.c_str() + pos + 1), 0, KEY_READ, &openKey); + debugAssert(result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND); + + if (result == ERROR_SUCCESS) { + uint32 dataSize = sizeof(int32); + result = RegQueryValueExA(openKey, value.c_str(), NULL, NULL, reinterpret_cast(&data), reinterpret_cast(&dataSize)); + + debugAssertM(result == ERROR_SUCCESS, "Could not read registry key value."); + + RegCloseKey(openKey); + } + return (result == ERROR_SUCCESS); +} + +bool RegistryUtil::readBytes(const std::string& key, const std::string& value, uint8* data, uint32& dataSize) { + size_t pos = key.find('\\', 0); + if (pos == std::string::npos) { + return false; + } + + HKEY hkey = getRootKeyFromString(key.c_str(), pos); + + if (hkey == NULL) { + return false; + } + + HKEY openKey; + int32 result = RegOpenKeyExA(hkey, (key.c_str() + pos + 1), 0, KEY_READ, &openKey); + debugAssert(result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND); + + if (result == ERROR_SUCCESS) { + if (data == NULL) { + result = RegQueryValueExA(openKey, value.c_str(), NULL, NULL, NULL, reinterpret_cast(&dataSize)); + } else { + result = RegQueryValueExA(openKey, value.c_str(), NULL, NULL, reinterpret_cast(&data), reinterpret_cast(&dataSize)); + } + + debugAssertM(result == ERROR_SUCCESS, "Could not read registry key value."); + + RegCloseKey(openKey); + } + return (result == ERROR_SUCCESS); +} + +bool RegistryUtil::readString(const std::string& key, const std::string& value, std::string& data) { + size_t pos = key.find('\\', 0); + if (pos == std::string::npos) { + return false; + } + + HKEY hkey = getRootKeyFromString(key.c_str(), pos); + + if (hkey == NULL) { + return false; + } + + HKEY openKey; + int32 result = RegOpenKeyExA(hkey, (key.c_str() + pos + 1), 0, KEY_READ, &openKey); + debugAssert(result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND); + + if (result == ERROR_SUCCESS) { + uint32 dataSize = 0; + + result = RegQueryValueExA(openKey, value.c_str(), NULL, NULL, NULL, reinterpret_cast(&dataSize)); + debugAssertM(result == ERROR_SUCCESS, "Could not read registry key value."); + + // increment datasize to allow for non null-terminated strings in registry + dataSize += 1; + + if (result == ERROR_SUCCESS) { + char* tmpStr = static_cast(System::malloc(dataSize)); + System::memset(tmpStr, 0, dataSize); + + result = RegQueryValueExA(openKey, value.c_str(), NULL, NULL, reinterpret_cast(tmpStr), reinterpret_cast(&dataSize)); + debugAssertM(result == ERROR_SUCCESS, "Could not read registry key value."); + + if (result == ERROR_SUCCESS) { + data = tmpStr; + } + + RegCloseKey(openKey); + System::free(tmpStr); + } + } + return (result == ERROR_SUCCESS); +} + +bool RegistryUtil::writeInt32(const std::string& key, const std::string& value, int32 data) { + size_t pos = key.find('\\', 0); + if (pos == std::string::npos) { + return false; + } + + HKEY hkey = getRootKeyFromString(key.c_str(), pos); + + if (hkey == NULL) { + return false; + } + + HKEY openKey; + int32 result = RegOpenKeyExA(hkey, (key.c_str() + pos + 1), 0, KEY_WRITE, &openKey); + debugAssert(result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND); + + if (result == ERROR_SUCCESS) { + result = RegSetValueExA(openKey, value.c_str(), 0, REG_DWORD, reinterpret_cast(&data), sizeof(int32)); + + debugAssertM(result == ERROR_SUCCESS, "Could not write registry key value."); + + RegCloseKey(openKey); + } + return (result == ERROR_SUCCESS); +} + +bool RegistryUtil::writeBytes(const std::string& key, const std::string& value, const uint8* data, uint32 dataSize) { + debugAssert(data); + + size_t pos = key.find('\\', 0); + if (pos == std::string::npos) { + return false; + } + + HKEY hkey = getRootKeyFromString(key.c_str(), pos); + + if (hkey == NULL) { + return false; + } + + HKEY openKey; + int32 result = RegOpenKeyExA(hkey, (key.c_str() + pos + 1), 0, KEY_WRITE, &openKey); + debugAssert(result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND); + + if (result == ERROR_SUCCESS) { + if (data) { + result = RegSetValueExA(openKey, value.c_str(), 0, REG_BINARY, reinterpret_cast(data), dataSize); + } + + debugAssertM(result == ERROR_SUCCESS, "Could not write registry key value."); + + RegCloseKey(openKey); + } + return (result == ERROR_SUCCESS); +} + +bool RegistryUtil::writeString(const std::string& key, const std::string& value, const std::string& data) { + size_t pos = key.find('\\', 0); + if (pos == std::string::npos) { + return false; + } + + HKEY hkey = getRootKeyFromString(key.c_str(), pos); + + if (hkey == NULL) { + return false; + } + + HKEY openKey; + int32 result = RegOpenKeyExA(hkey, (key.c_str() + pos + 1), 0, KEY_WRITE, &openKey); + debugAssert(result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND); + + if (result == ERROR_SUCCESS) { + result = RegSetValueExA(openKey, value.c_str(), 0, REG_SZ, reinterpret_cast(data.c_str()), (data.size() + 1)); + debugAssertM(result == ERROR_SUCCESS, "Could not write registry key value."); + + RegCloseKey(openKey); + } + return (result == ERROR_SUCCESS); +} + + +// static helpers +static HKEY getRootKeyFromString(const char* str, size_t length) { + debugAssert(str); + + if (str) { + if ( strncmp(str, "HKEY_CLASSES_ROOT", length) == 0 ) { + return HKEY_CLASSES_ROOT; + } else if ( strncmp(str, "HKEY_CURRENT_CONFIG", length) == 0 ) { + return HKEY_CURRENT_CONFIG; + } else if ( strncmp(str, "HKEY_CURRENT_USER", length) == 0 ) { + return HKEY_CURRENT_USER; + } else if ( strncmp(str, "HKEY_LOCAL_MACHINE", length) == 0 ) { + return HKEY_LOCAL_MACHINE; + } else if ( strncmp(str, "HKEY_PERFORMANCE_DATA", length) == 0 ) { + return HKEY_PERFORMANCE_DATA; + } else if ( strncmp(str, "HKEY_PERFORMANCE_NLSTEXT", length) == 0 ) { + return HKEY_PERFORMANCE_NLSTEXT; + } else if ( strncmp(str, "HKEY_PERFORMANCE_TEXT", length) == 0 ) { + return HKEY_PERFORMANCE_TEXT; + } else if ( strncmp(str, "HKEY_CLASSES_ROOT", length) == 0 ) { + return HKEY_CLASSES_ROOT; + } else { + return NULL; + } + } else { + return NULL; + } +} + +} // namespace G3D + +#endif // G3D_WIN32 diff --git a/dep/g3dlite/Sphere.cpp b/dep/g3dlite/Sphere.cpp new file mode 100644 index 00000000000..4ed0811cb29 --- /dev/null +++ b/dep/g3dlite/Sphere.cpp @@ -0,0 +1,223 @@ +/** + @file Sphere.cpp + + Sphere class + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2001-04-17 + @edited 2009-01-20 + */ + +#include "G3D/platform.h" +#include "G3D/Sphere.h" +#include "G3D/stringutils.h" +#include "G3D/BinaryOutput.h" +#include "G3D/BinaryInput.h" +#include "G3D/AABox.h" +#include "G3D/Plane.h" + +namespace G3D { + +int32 Sphere::dummy; + +Sphere::Sphere(class BinaryInput& b) { + deserialize(b); +} + + +void Sphere::serialize(class BinaryOutput& b) const { + center.serialize(b); + b.writeFloat64(radius); +} + + +void Sphere::deserialize(class BinaryInput& b) { + center.deserialize(b); + radius = (float)b.readFloat64(); +} + + +std::string Sphere::toString() const { + return format("Sphere(<%g, %g, %g>, %g)", + center.x, center.y, center.z, radius); +} + + +bool Sphere::contains(const Vector3& point) const { + float distance = (center - point).squaredMagnitude(); + return distance <= square(radius); +} + + +bool Sphere::contains(const Sphere& other) const { + float distance = (center - other.center).squaredMagnitude(); + return (radius >= other.radius) && (distance <= square(radius - other.radius)); +} + + +bool Sphere::intersects(const Sphere& other) const { + return (other.center - center).length() <= (radius + other.radius); +} + + +void Sphere::merge(const Sphere& other) { + if (other.contains(*this)) { + *this = other; + } else if (! contains(other)) { + // The farthest distance is along the axis between the centers, which + // must not be colocated since neither contains the other. + Vector3 toMe = center - other.center; + // Get a point on the axis from each + toMe = toMe.direction(); + const Vector3& A = center + toMe * radius; + const Vector3& B = other.center - toMe * other.radius; + + // Now just bound the A->B segment + center = (A + B) * 0.5f; + radius = (A - B).length(); + } + // (if this contains other, we're done) +} + + +bool Sphere::culledBy( + const Array& plane, + int& cullingPlaneIndex, + const uint32 inMask, + uint32& outMask) const { + + return culledBy(plane.getCArray(), plane.size(), cullingPlaneIndex, inMask, outMask); +} + + +bool Sphere::culledBy( + const Array& plane, + int& cullingPlaneIndex, + const uint32 inMask) const { + + return culledBy(plane.getCArray(), plane.size(), cullingPlaneIndex, inMask); +} + + +bool Sphere::culledBy( + const class Plane* plane, + int numPlanes, + int& cullingPlane, + const uint32 _inMask, + uint32& childMask) const { + + if (radius == finf()) { + // No plane can cull the infinite box + return false; + } + + uint32 inMask = _inMask; + assert(numPlanes < 31); + + childMask = 0; + + // See if there is one plane for which all of the + // vertices are in the negative half space. + for (int p = 0; p < numPlanes; p++) { + + // Only test planes that are not masked + if ((inMask & 1) != 0) { + + bool culledLow = ! plane[p].halfSpaceContainsFinite(center + plane[p].normal() * radius); + bool culledHigh = ! plane[p].halfSpaceContainsFinite(center - plane[p].normal() * radius); + + if (culledLow) { + // Plane p culled the sphere + cullingPlane = p; + + // The caller should not recurse into the children, + // since the parent is culled. If they do recurse, + // make them only test against this one plane, which + // will immediately cull the volume. + childMask = 1 << p; + return true; + + } else if (culledHigh) { + // The bounding volume straddled the plane; we have + // to keep testing against this plane + childMask |= (1 << p); + } + } + + // Move on to the next bit. + inMask = inMask >> 1; + } + + // None of the planes could cull this box + cullingPlane = -1; + return false; +} + + +bool Sphere::culledBy( + const class Plane* plane, + int numPlanes, + int& cullingPlane, + const uint32 _inMask) const { + + uint32 inMask = _inMask; + assert(numPlanes < 31); + + // See if there is one plane for which all of the + // vertices are in the negative half space. + for (int p = 0; p < numPlanes; p++) { + + // Only test planes that are not masked + if ((inMask & 1) != 0) { + bool culled = ! plane[p].halfSpaceContains(center + plane[p].normal() * radius); + if (culled) { + // Plane p culled the sphere + cullingPlane = p; + return true; + } + } + + // Move on to the next bit. + inMask = inMask >> 1; + } + + // None of the planes could cull this box + cullingPlane = -1; + return false; +} + + +Vector3 Sphere::randomSurfacePoint() const { + return Vector3::random() * radius + center; +} + + +Vector3 Sphere::randomInteriorPoint() const { + Vector3 result; + do { + result = Vector3(uniformRandom(-1, 1), + uniformRandom(-1, 1), + uniformRandom(-1, 1)); + } while (result.squaredMagnitude() >= 1.0f); + + return result * radius + center; +} + + +float Sphere::volume() const { + return (float)pi() * (4.0f / 3.0f) * powf((float)radius, 3.0f); +} + + +float Sphere::area() const { + return (float)pi() * 4.0f * powf((float)radius, 2.0f); +} + + +void Sphere::getBounds(AABox& out) const { + Vector3 extent(radius, radius, radius); + out = AABox(center - extent, center + extent); +} + +} // namespace diff --git a/dep/g3dlite/System.cpp b/dep/g3dlite/System.cpp new file mode 100644 index 00000000000..e03c4e8c6fa --- /dev/null +++ b/dep/g3dlite/System.cpp @@ -0,0 +1,1746 @@ +/** + @file System.cpp + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + Note: every routine must call init() first. + + There are two kinds of detection used in this file. At compile + time, the _MSC_VER #define is used to determine whether x86 assembly + can be used at all. At runtime, processor detection is used to + determine if we can safely call the routines that use that assembly. + + @created 2003-01-25 + @edited 2010-01-03 + */ + +#include "G3D/platform.h" +#include "G3D/System.h" +#include "G3D/debug.h" +#include "G3D/fileutils.h" +#include "G3D/TextOutput.h" +#include "G3D/G3DGameUnits.h" +#include "G3D/Crypto.h" +#include "G3D/prompt.h" +#include "G3D/stringutils.h" +#include "G3D/Log.h" +#include "G3D/Table.h" +#include "G3D/GMutex.h" +#include "G3D/units.h" +#include + +#include +#include + +// Uncomment the following line to turn off G3D::System memory +// allocation and use the operating system's malloc. +//#define NO_BUFFERPOOL + +#if defined(__i386__) || defined(__x86_64__) || defined(G3D_WIN32) +# define G3D_NOT_OSX_PPC +#endif + +#include + +#ifdef G3D_WIN32 + +# include +# include +# include "G3D/RegistryUtil.h" + +#elif defined(G3D_LINUX) + +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include + +#elif defined(G3D_OSX) + + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + + #include + #include +#endif + +// SIMM include +#ifdef __SSE__ +#include +#endif + +namespace G3D { + + +/** Checks if the CPUID command is available on the processor (called from init) */ +static bool checkForCPUID(); + +/** Called from init */ +static void getG3DVersion(std::string& s); + +/** Called from init */ +static G3DEndian checkEndian(); + + +System& System::instance() { + static System thesystem; + return thesystem; +} + + +System::System() : + m_initialized(false), + m_cpuSpeed(0), + m_hasCPUID(false), + m_hasRDTSC(false), + m_hasMMX(false), + m_hasSSE(false), + m_hasSSE2(false), + m_hasSSE3(false), + m_has3DNOW(false), + m_has3DNOW2(false), + m_hasAMDMMX(false), + m_cpuVendor("Uninitialized"), + m_numCores(1), + m_machineEndian(G3D_LITTLE_ENDIAN), + m_cpuArch("Uninitialized"), + m_operatingSystem("Uninitialized"), + m_version("Uninitialized"), + m_outOfMemoryCallback(NULL), + m_realWorldGetTickTime0(0), + m_highestCPUIDFunction(0) { + + init(); +} + + +void System::init() { + // NOTE: Cannot use most G3D data structures or utility functions + // in here because they are not initialized. + + if (m_initialized) { + return; + } else { + m_initialized = true; + } + + getG3DVersion(m_version); + + m_machineEndian = checkEndian(); + + m_hasCPUID = checkForCPUID(); + // Process the CPUID information + if (m_hasCPUID) { + // We read the standard CPUID level 0x00000000 which should + // be available on every x86 processor. This fills out + // a string with the processor vendor tag. + unsigned int eaxreg = 0, ebxreg = 0, ecxreg = 0, edxreg = 0; + + cpuid(CPUID_VENDOR_ID, eaxreg, ebxreg, ecxreg, edxreg); + + { + char c[100]; + // Then we connect the single register values to the vendor string + *((unsigned int*) c) = ebxreg; + *((unsigned int*) (c + 4)) = edxreg; + *((unsigned int*) (c + 8)) = ecxreg; + c[12] = '\0'; + m_cpuVendor = c; + } + + switch (ebxreg) { + case 0x756E6547: // GenuineIntel + m_cpuArch = "Intel Processor"; + break; + + case 0x68747541: // AuthenticAMD + m_cpuArch = "AMD Processor"; + break; + + case 0x69727943: // CyrixInstead + m_cpuArch = "Cyrix Processor"; + break; + + default: + m_cpuArch = "Unknown Processor Vendor"; + break; + } + + + unsigned int highestFunction = eaxreg; + if (highestFunction >= CPUID_NUM_CORES) { + cpuid(CPUID_NUM_CORES, eaxreg, ebxreg, ecxreg, edxreg); + // Number of cores is in (eax>>26) + 1 + m_numCores = (eaxreg >> 26) + 1; + } + + cpuid(CPUID_GET_HIGHEST_FUNCTION, m_highestCPUIDFunction, ebxreg, ecxreg, edxreg); + } + + + // Get the operating system name (also happens to read some other information) +# ifdef G3D_WIN32 + // Note that this overrides some of the values computed above + bool success = RegistryUtil::readInt32 + ("HKEY_LOCAL_MACHINE\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", + "~MHz", m_cpuSpeed); + + SYSTEM_INFO systemInfo; + GetSystemInfo(&systemInfo); + const char* arch = NULL; + switch (systemInfo.wProcessorArchitecture) { + case PROCESSOR_ARCHITECTURE_INTEL: + arch = "Intel"; + break; + + case PROCESSOR_ARCHITECTURE_MIPS: + arch = "MIPS"; + break; + + case PROCESSOR_ARCHITECTURE_ALPHA: + arch = "Alpha"; + break; + + case PROCESSOR_ARCHITECTURE_PPC: + arch = "Power PC"; + break; + + default: + arch = "Unknown"; + } + + m_numCores = systemInfo.dwNumberOfProcessors; + uint32 maxAddr = (uint32)systemInfo.lpMaximumApplicationAddress; + { + char c[1024]; + sprintf(c, "%d x %d-bit %s processor", + systemInfo.dwNumberOfProcessors, + (int)(::log((double)maxAddr) / ::log(2.0) + 2.0), + arch); + m_cpuArch = c; + } + + OSVERSIONINFO osVersionInfo; + osVersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); + success = GetVersionEx(&osVersionInfo) != 0; + + if (success) { + char c[1000]; + sprintf(c, "Windows %d.%d build %d Platform %d %s", + osVersionInfo.dwMajorVersion, + osVersionInfo.dwMinorVersion, + osVersionInfo.dwBuildNumber, + osVersionInfo.dwPlatformId, + osVersionInfo.szCSDVersion); + m_operatingSystem = c; + } else { + m_operatingSystem = "Windows"; + } + +# elif defined(G3D_LINUX) || defined(G3D_FREEBSD) + + { + // Find the operating system using the 'uname' command + FILE* f = popen("uname -a", "r"); + + int len = 100; + char* r = (char*)::malloc(len * sizeof(char)); + fgets(r, len, f); + // Remove trailing newline + if (r[strlen(r) - 1] == '\n') { + r[strlen(r) - 1] = '\0'; + } + fclose(f); + + m_operatingSystem = r; + ::free(r); + } + +# elif defined(G3D_OSX) + + // Operating System: + SInt32 macVersion; + Gestalt(gestaltSystemVersion, &macVersion); + + int major = (macVersion >> 8) & 0xFF; + int minor = (macVersion >> 4) & 0xF; + int revision = macVersion & 0xF; + + { + char c[1000]; + sprintf(c, "OS X %x.%x.%x", major, minor, revision); + m_operatingSystem = c; + } + + // Clock Cycle Timing Information: + Gestalt('pclk', &m_OSXCPUSpeed); + m_cpuSpeed = iRound((double)m_OSXCPUSpeed / (1024 * 1024)); + m_secondsPerNS = 1.0 / 1.0e9; + + // System Architecture: + const NXArchInfo* pInfo = NXGetLocalArchInfo(); + + if (pInfo) { + m_cpuArch = pInfo->description; + + switch (pInfo->cputype) { + case CPU_TYPE_POWERPC: + switch(pInfo->cpusubtype){ + case CPU_SUBTYPE_POWERPC_750: + case CPU_SUBTYPE_POWERPC_7400: + case CPU_SUBTYPE_POWERPC_7450: + m_cpuVendor = "Motorola"; + break; + case CPU_SUBTYPE_POWERPC_970: + m_cpuVendor = "IBM"; + break; + } + break; + + case CPU_TYPE_I386: + m_cpuVendor = "Intel"; + break; + } + } +# endif + + initTime(); + + getStandardProcessorExtensions(); +} + + +void getG3DVersion(std::string& s) { + char cstr[100]; + if ((G3D_VER % 100) != 0) { + sprintf(cstr, "G3D %d.%02d beta %d", + G3D_VER / 10000, + (G3D_VER / 100) % 100, + G3D_VER % 100); + } else { + sprintf(cstr, "G3D %d.%02d", + G3D_VER / 10000, + (G3D_VER / 100) % 100); + } + s = cstr; +} + +#if 0 // TODO: delete +struct Directory { + std::string path; + Array contents; +}; + +static bool maybeAddDirectory(const std::string& newPath, Array& directoryArray, bool recurse = true) { + if (fileExists(newPath)) { + Directory& d = directoryArray.next(); + d.path = newPath; + getFiles(pathConcat(newPath, "*"), d.contents); + Array dirs; + getDirs(pathConcat(newPath, "*"), dirs); + d.contents.append(dirs); + + if (recurse) { + // Look for subdirectories + static const std::string subdirs[] = + {"font", "gui", "SuperShader", "cubemap", "icon", "material", "image", "md2", "md3", "ifs", "3ds", "sky", ""}; + + for (int j = 0; j < dirs.size(); ++j) { + for (int i = 0; ! subdirs[i].empty(); ++i) { + if (dirs[j] == subdirs[i]) { + maybeAddDirectory(pathConcat(newPath, dirs[j]), directoryArray, false); + } + } + } + } + return true; + } else { + return false; + } +} +#endif + +std::string System::findDataFile +(const std::string& full, + bool errorIfNotFound) { + + // Places where specific files were most recently found. This is + // used to cache seeking of common files. + static Table lastFound; + + // First check if the file exists as requested. This will go + // through the FileSystemCache, so most calls do not touch disk. + if (fileExists(full)) { + return full; + } + + // Now check where we previously found this file. + std::string* last = lastFound.getPointer(full); + if (last != NULL) { + if (fileExists(*last)) { + // Even if cwd has changed the file is still present. + // We won't notice if it has been deleted, however. + return *last; + } else { + // Remove this from the cache it is invalid + lastFound.remove(full); + } + } + + // Places to look + static Array directoryArray; + + if (directoryArray.size() == 0) { + // Initialize the directory array + RealTime t0 = System::time(); + + Array baseDirArray; + + std::string initialAppDataDir(instance().m_appDataDir); + + baseDirArray.append(""); + if (! initialAppDataDir.empty()) { + baseDirArray.append(initialAppDataDir); + } + + const char* g3dPath = getenv("G3DDATA"); + + if (g3dPath && (initialAppDataDir != g3dPath)) { + baseDirArray.append(g3dPath); + } + + static const std::string subdirs[] = + {"font", "gui", "SuperShader", "cubemap", "icon", "material", "image", "md2", "md3", "ifs", "3ds", "sky", ""}; + for (int j = 0; j < baseDirArray.size(); ++j) { + std::string d = baseDirArray[j]; + if (fileExists(d)) { + directoryArray.append(d); + for (int i = 0; ! subdirs[i].empty(); ++i) { + const std::string& p = pathConcat(d, subdirs[i]); + if (fileExists(p)) { + directoryArray.append(p); + } + } + } + } + + logLazyPrintf("Initializing System::findDataFile took %fs\n", System::time() - t0); + } + + for (int i = 0; i < directoryArray.size(); ++i) { + const std::string& p = pathConcat(directoryArray[i], full); + if (fileExists(p)) { + lastFound.set(full, p); + return p; + } + } + + if (errorIfNotFound) { + // Generate an error message + std::string locations; + for (int i = 0; i < directoryArray.size(); ++i) { + locations += pathConcat(directoryArray[i], full) + "\n"; + } + alwaysAssertM(false, "Could not find '" + full + "' in:\n" + locations); + } + + // Not found + return ""; +} + + +void System::setAppDataDir(const std::string& path) { + instance().m_appDataDir = path; +} + + +std::string demoFindData(bool errorIfNotFound) { + static const char* g3dPath = getenv("G3DDATA"); + if (g3dPath) { + return g3dPath; +# ifdef G3D_WIN32 + } else if (fileExists("../data")) { + // G3D install on Windows + return "../data"; + } else if (fileExists("../data-files")) { + // G3D source on Windows + return "../data-files"; +# else + } else if (fileExists("../../../../data")) { + // G3D install on Unix + return "../../../../data"; + } else if (fileExists("../../../../data-files")) { + // G3D source on Unix + return "../../../../data-files"; +# endif + } else { + return ""; + } +} + + +const std::string& System::build() { + const static std::string b = +# ifdef _DEBUG + "Debug"; +# else + "Release"; +# endif + + return b; +} + + +static G3DEndian checkEndian() { + int32 a = 1; + if (*(uint8*)&a == 1) { + return G3D_LITTLE_ENDIAN; + } else { + return G3D_BIG_ENDIAN; + } +} + + +static bool checkForCPUID() { + // all known supported architectures have cpuid + // add cases for incompatible architectures if they are added + // e.g., if we ever support __powerpc__ being defined again + + return true; +} + + +void System::getStandardProcessorExtensions() { +#if ! defined(G3D_OSX) || defined(G3D_OSX_INTEL) + if (! m_hasCPUID) { + return; + } + + uint32 eaxreg = 0, ebxreg = 0, ecxreg = 0, features = 0; + + cpuid(CPUID_PROCESSOR_FEATURES, eaxreg, ebxreg, ecxreg, features); + +# define checkBit(var, bit) ((var & (1 << bit)) ? true : false) + + m_hasRDTSC = checkBit(features, 4); + m_hasMMX = checkBit(features, 23); + m_hasSSE = checkBit(features, 25); + m_hasSSE2 = checkBit(features, 26); + // Bit 28 is HTT; not checked by G3D + + m_hasSSE3 = checkBit(ecxreg, 0); + + if (m_highestCPUIDFunction >= CPUID_EXTENDED_FEATURES) { + cpuid(CPUID_EXTENDED_FEATURES, eaxreg, ebxreg, ecxreg, features); + m_hasAMDMMX = checkBit(features, 22); // Only on AMD + m_has3DNOW = checkBit(features, 31); // Only on AMD + m_has3DNOW2 = checkBit(features, 30); // Only on AMD + } else { + m_hasAMDMMX = false; + m_has3DNOW = false; + m_has3DNOW2 = false; + } + +# undef checkBit +#endif +} + +#if defined(G3D_WIN32) && !defined(G3D_64BIT) + #pragma message("Port System::memcpy SIMD to all platforms") +/** Michael Herf's fast memcpy */ +void memcpyMMX(void* dst, const void* src, int nbytes) { + int remainingBytes = nbytes; + + if (nbytes > 64) { + _asm { + mov esi, src + mov edi, dst + mov ecx, nbytes + shr ecx, 6 // 64 bytes per iteration + + loop1: + movq mm1, 0[ESI] // Read in source data + movq mm2, 8[ESI] + movq mm3, 16[ESI] + movq mm4, 24[ESI] + movq mm5, 32[ESI] + movq mm6, 40[ESI] + movq mm7, 48[ESI] + movq mm0, 56[ESI] + + movntq 0[EDI], mm1 // Non-temporal stores + movntq 8[EDI], mm2 + movntq 16[EDI], mm3 + movntq 24[EDI], mm4 + movntq 32[EDI], mm5 + movntq 40[EDI], mm6 + movntq 48[EDI], mm7 + movntq 56[EDI], mm0 + + add esi, 64 + add edi, 64 + dec ecx + jnz loop1 + + emms + } + remainingBytes -= ((nbytes >> 6) << 6); + } + + if (remainingBytes > 0) { + // Memcpy the rest + memcpy((uint8*)dst + (nbytes - remainingBytes), + (const uint8*)src + (nbytes - remainingBytes), remainingBytes); + } +} +#endif + +void System::memcpy(void* dst, const void* src, size_t numBytes) { +#if defined(G3D_WIN32) && !defined(G3D_64BIT) + memcpyMMX(dst, src, numBytes); +#else + ::memcpy(dst, src, numBytes); +#endif +} + + +/** Michael Herf's fastest memset. n32 must be filled with the same + character repeated. */ +#if defined(G3D_WIN32) && !defined(G3D_64BIT) + #pragma message("Port System::memfill SIMD to all platforms") + +// On x86 processors, use MMX +void memfill(void *dst, int n32, unsigned long i) { + + int originalSize = i; + int bytesRemaining = i; + + if (i > 16) { + + bytesRemaining = i % 16; + i -= bytesRemaining; + __asm { + movq mm0, n32 + punpckldq mm0, mm0 + mov edi, dst + + loopwrite: + + movntq 0[edi], mm0 + movntq 8[edi], mm0 + + add edi, 16 + sub i, 16 + jg loopwrite + + emms + } + } + + if (bytesRemaining > 0) { + ::memset((uint8*)dst + (originalSize - bytesRemaining), n32, bytesRemaining); + } +} +#endif + + +void System::memset(void* dst, uint8 value, size_t numBytes) { +#if defined(G3D_WIN32) && !defined(G3D_64BIT) + uint32 v = value; + v = v + (v << 8) + (v << 16) + (v << 24); + G3D::memfill(dst, v, numBytes); +#else + ::memset(dst, value, numBytes); +#endif +} + + +/** Removes the 'd' that icompile / Morgan's VC convention appends. */ +static std::string computeAppName(const std::string& start) { + if (start.size() < 2) { + return start; + } + + if (start[start.size() - 1] == 'd') { + // Maybe remove the 'd'; see if ../ or ../../ has the same name + char tmp[1024]; + getcwd(tmp, sizeof(tmp)); + std::string drive, base, ext; + Array path; + parseFilename(tmp, drive, path, base, ext); + + std::string shortName = start.substr(0, start.size() - 1); + + if ((path.size() > 1) && (toLower(path.last()) == toLower(shortName))) { + return shortName; + } + + if ((path.size() > 2) && (toLower(path[path.size() - 2]) == toLower(shortName))) { + return shortName; + } + } + + return start; +} + + +std::string& System::appName() { + static std::string n = computeAppName(filenameBase(currentProgramFilename())); + return n; +} + + +std::string System::currentProgramFilename() { + char filename[2048]; + +# ifdef G3D_WIN32 + { + GetModuleFileNameA(NULL, filename, sizeof(filename)); + } +# elif defined(G3D_OSX) + { + // Run the 'ps' program to extract the program name + // from the process ID. + int pid; + FILE* fd; + char cmd[80]; + pid = getpid(); + sprintf(cmd, "ps -p %d -o comm=\"\"", pid); + + fd = popen(cmd, "r"); + int s = fread(filename, 1, sizeof(filename), fd); + // filename will contain a newline. Overwrite it: + filename[s - 1] = '\0'; + } +# else + { + int ret = readlink("/proc/self/exe", filename, sizeof(filename)); + + // In case of an error, leave the handling up to the caller + if (ret == -1) { + return ""; + } + + debugAssert((int)sizeof(filename) > ret); + + // Ensure proper NULL termination + filename[ret] = 0; + } + #endif + + return filename; +} + + +void System::sleep(RealTime t) { + + // Overhead of calling this function, measured from a previous run. + static const RealTime OVERHEAD = 0.00006f; + + RealTime now = time(); + RealTime wakeupTime = now + t - OVERHEAD; + + RealTime remainingTime = wakeupTime - now; + RealTime sleepTime = 0; + + // On Windows, a "time slice" is measured in quanta of 3-5 ms (http://support.microsoft.com/kb/259025) + // Sleep(0) yields the remainder of the time slice, which could be a long time. + // A 1 ms minimum time experimentally kept the "Empty GApp" at nearly no CPU load at 100 fps, + // yet nailed the frame timing perfectly. + static RealTime minRealSleepTime = 3 * units::milliseconds(); + + while (remainingTime > 0) { + + if (remainingTime > minRealSleepTime * 2.5) { + // Safe to use Sleep with a time... sleep for half the remaining time + sleepTime = max(remainingTime * 0.5, 0.0005); + } else if (remainingTime > minRealSleepTime) { + // Safe to use Sleep with a zero time; + // causes the program to yield only + // the current time slice, and then return. + sleepTime = 0; + } else { + // Not safe to use Sleep; busy wait + sleepTime = -1; + } + + if (sleepTime >= 0) { + #ifdef G3D_WIN32 + // Translate to milliseconds + Sleep((int)(sleepTime * 1e3)); + #else + // Translate to microseconds + usleep((int)(sleepTime * 1e6)); + #endif + } + + now = time(); + remainingTime = wakeupTime - now; + } +} + + +void System::consoleClearScreen() { +# ifdef G3D_WIN32 + system("cls"); +# else + system("clear"); +# endif +} + + +bool System::consoleKeyPressed() { + #ifdef G3D_WIN32 + + return _kbhit() != 0; + + #else + + static const int STDIN = 0; + static bool initialized = false; + + if (! initialized) { + // Use termios to turn off line buffering + termios term; + tcgetattr(STDIN, &term); + term.c_lflag &= ~ICANON; + tcsetattr(STDIN, TCSANOW, &term); + setbuf(stdin, NULL); + initialized = true; + } + + #ifdef G3D_LINUX + + int bytesWaiting; + ioctl(STDIN, FIONREAD, &bytesWaiting); + return bytesWaiting; + + #else + + timeval timeout; + fd_set rdset; + + FD_ZERO(&rdset); + FD_SET(STDIN, &rdset); + timeout.tv_sec = 0; + timeout.tv_usec = 0; + + return select(STDIN + 1, &rdset, NULL, NULL, &timeout); + #endif + #endif +} + + +int System::consoleReadKey() { +# ifdef G3D_WIN32 + return _getch(); +# else + char c; + read(0, &c, 1); + return c; +# endif +} + + +void System::initTime() { + #ifdef G3D_WIN32 + if (QueryPerformanceFrequency(&m_counterFrequency)) { + QueryPerformanceCounter(&m_start); + } + + struct _timeb t; + _ftime(&t); + + m_realWorldGetTickTime0 = (RealTime)t.time - t.timezone * G3D::MINUTE + (t.dstflag ? G3D::HOUR : 0); + + #else + gettimeofday(&m_start, NULL); + // "sse" = "seconds since epoch". The time + // function returns the seconds since the epoch + // GMT (perhaps more correctly called UTC). + time_t gmt = ::time(NULL); + + // No call to free or delete is needed, but subsequent + // calls to asctime, ctime, mktime, etc. might overwrite + // local_time_vals. + tm* localTimeVals = localtime(&gmt); + + time_t local = gmt; + + if (localTimeVals) { + // tm_gmtoff is already corrected for daylight savings. + local = local + localTimeVals->tm_gmtoff; + } + + m_realWorldGetTickTime0 = local; + #endif +} + + +RealTime System::time() { +# ifdef G3D_WIN32 + LARGE_INTEGER now; + QueryPerformanceCounter(&now); + + return ((RealTime)(now.QuadPart - instance().m_start.QuadPart) / + instance().m_counterFrequency.QuadPart) + instance().m_realWorldGetTickTime0; +# else + // Linux resolution defaults to 100Hz. + // There is no need to do a separate RDTSC call as gettimeofday + // actually uses RDTSC when on systems that support it, otherwise + // it uses the system clock. + struct timeval now; + gettimeofday(&now, NULL); + + return (now.tv_sec - instance().m_start.tv_sec) + + (now.tv_usec - instance().m_start.tv_usec) / 1e6 + + instance().m_realWorldGetTickTime0; +# endif +} + + +//////////////////////////////////////////////////////////////// + +#define REALPTR_TO_USERPTR(x) ((uint8*)(x) + sizeof (void *)) +#define USERPTR_TO_REALPTR(x) ((uint8*)(x) - sizeof (void *)) +#define REALBLOCK_SIZE(x) ((x) + sizeof (void *)) + +class BufferPool { +public: + + /** Only store buffers up to these sizes (in bytes) in each pool-> + Different pools have different management strategies. + + A large block is preallocated for tiny buffers; they are used with + tremendous frequency. Other buffers are allocated as demanded. + Tiny buffers are 128 bytes long because that seems to align well with + cache sizes on many machines. + */ + enum {tinyBufferSize = 128, smallBufferSize = 1024, medBufferSize = 4096}; + + /** + Most buffers we're allowed to store. + 250000 * 128 = 32 MB (preallocated) + 10000 * 1024 = 10 MB (allocated on demand) + 1024 * 4096 = 4 MB (allocated on demand) + */ + enum {maxTinyBuffers = 250000, maxSmallBuffers = 10000, maxMedBuffers = 1024}; + +private: + + class MemBlock { + public: + void* ptr; + size_t bytes; + + inline MemBlock() : ptr(NULL), bytes(0) {} + inline MemBlock(void* p, size_t b) : ptr(p), bytes(b) {} + }; + + MemBlock smallPool[maxSmallBuffers]; + int smallPoolSize; + + MemBlock medPool[maxMedBuffers]; + int medPoolSize; + + /** The tiny pool is a single block of storage into which all tiny + objects are allocated. This provides better locality for + small objects and avoids the search time, since all tiny + blocks are exactly the same size. */ + void* tinyPool[maxTinyBuffers]; + int tinyPoolSize; + + /** Pointer to the data in the tiny pool */ + void* tinyHeap; + + Spinlock m_lock; + + void lock() { + m_lock.lock(); + } + + void unlock() { + m_lock.unlock(); + } + +#if 0 //-----------------------------------------------old mutex +# ifdef G3D_WIN32 + CRITICAL_SECTION mutex; +# else + pthread_mutex_t mutex; +# endif + + /** Provide synchronization between threads */ + void lock() { +# ifdef G3D_WIN32 + EnterCriticalSection(&mutex); +# else + pthread_mutex_lock(&mutex); +# endif + } + + void unlock() { +# ifdef G3D_WIN32 + LeaveCriticalSection(&mutex); +# else + pthread_mutex_unlock(&mutex); +# endif + } +#endif //-------------------------------------------old mutex + + /** + Malloc out of the tiny heap. Returns NULL if allocation failed. + */ + inline void* tinyMalloc(size_t bytes) { + // Note that we ignore the actual byte size + // and create a constant size block. + (void)bytes; + assert(tinyBufferSize >= bytes); + + void* ptr = NULL; + + if (tinyPoolSize > 0) { + --tinyPoolSize; + + // Return the old last pointer from the freelist + ptr = tinyPool[tinyPoolSize]; + +# ifdef G3D_DEBUG + if (tinyPoolSize > 0) { + assert(tinyPool[tinyPoolSize - 1] != ptr); + // "System::malloc heap corruption detected: " + // "the last two pointers on the freelist are identical (during tinyMalloc)."); + } +# endif + + // NULL out the entry to help detect corruption + tinyPool[tinyPoolSize] = NULL; + } + + return ptr; + } + + /** Returns true if this is a pointer into the tiny heap. */ + bool inTinyHeap(void* ptr) { + return + (ptr >= tinyHeap) && + (ptr < (uint8*)tinyHeap + maxTinyBuffers * tinyBufferSize); + } + + void tinyFree(void* ptr) { + assert(ptr); + assert(tinyPoolSize < maxTinyBuffers); + // "Tried to free a tiny pool buffer when the tiny pool freelist is full."); + +# ifdef G3D_DEBUG + if (tinyPoolSize > 0) { + void* prevOnHeap = tinyPool[tinyPoolSize - 1]; + assert(prevOnHeap != ptr); +// "System::malloc heap corruption detected: " +// "the last two pointers on the freelist are identical (during tinyFree)."); + } +# endif + + assert(tinyPool[tinyPoolSize] == NULL); + + // Put the pointer back into the free list + tinyPool[tinyPoolSize] = ptr; + ++tinyPoolSize; + + } + + void flushPool(MemBlock* pool, int& poolSize) { + for (int i = 0; i < poolSize; ++i) { + ::free(pool[i].ptr); + pool[i].ptr = NULL; + pool[i].bytes = 0; + } + poolSize = 0; + } + + + /** Allocate out of a specific pool-> Return NULL if no suitable + memory was found. + + */ + void* malloc(MemBlock* pool, int& poolSize, size_t bytes) { + + // OPT: find the smallest block that satisfies the request. + + // See if there's something we can use in the buffer pool-> + // Search backwards since usually we'll re-use the last one. + for (int i = (int)poolSize - 1; i >= 0; --i) { + if (pool[i].bytes >= bytes) { + // We found a suitable entry in the pool-> + + // No need to offset the pointer; it is already offset + void* ptr = pool[i].ptr; + + // Remove this element from the pool + --poolSize; + pool[i] = pool[poolSize]; + + return ptr; + } + } + + return NULL; + } + +public: + + /** Count of memory allocations that have occurred. */ + int totalMallocs; + int mallocsFromTinyPool; + int mallocsFromSmallPool; + int mallocsFromMedPool; + + /** Amount of memory currently allocated (according to the application). + This does not count the memory still remaining in the buffer pool, + but does count extra memory required for rounding off to the size + of a buffer. + Primarily useful for detecting leaks.*/ + // TODO: make me an atomic int! + volatile int bytesAllocated; + + BufferPool() { + totalMallocs = 0; + + mallocsFromTinyPool = 0; + mallocsFromSmallPool = 0; + mallocsFromMedPool = 0; + + bytesAllocated = true; + + tinyPoolSize = 0; + tinyHeap = NULL; + + smallPoolSize = 0; + + medPoolSize = 0; + + + // Initialize the tiny heap as a bunch of pointers into one + // pre-allocated buffer. + tinyHeap = ::malloc(maxTinyBuffers * tinyBufferSize); + for (int i = 0; i < maxTinyBuffers; ++i) { + tinyPool[i] = (uint8*)tinyHeap + (tinyBufferSize * i); + } + tinyPoolSize = maxTinyBuffers; + +#if 0 ///---------------------------------- old mutex +# ifdef G3D_WIN32 + InitializeCriticalSection(&mutex); +# else + pthread_mutex_init(&mutex, NULL); +# endif +#endif ///---------------------------------- old mutex + } + + + ~BufferPool() { + ::free(tinyHeap); +#if 0 //-------------------------------- old mutex +# ifdef G3D_WIN32 + DeleteCriticalSection(&mutex); +# else + // No destruction on pthreads +# endif +#endif //--------------------------------old mutex + } + + + void* realloc(void* ptr, size_t bytes) { + if (ptr == NULL) { + return malloc(bytes); + } + + if (inTinyHeap(ptr)) { + if (bytes <= tinyBufferSize) { + // The old pointer actually had enough space. + return ptr; + } else { + // Free the old pointer and malloc + + void* newPtr = malloc(bytes); + System::memcpy(newPtr, ptr, tinyBufferSize); + tinyFree(ptr); + return newPtr; + + } + } else { + // In one of our heaps. + + // See how big the block really was + size_t realSize = *(uint32*)USERPTR_TO_REALPTR(ptr); + if (bytes <= realSize) { + // The old block was big enough. + return ptr; + } + + // Need to reallocate + void* newPtr = malloc(bytes); + System::memcpy(newPtr, ptr, realSize); + free(ptr); + return newPtr; + } + } + + + void* malloc(size_t bytes) { + lock(); + ++totalMallocs; + + if (bytes <= tinyBufferSize) { + + void* ptr = tinyMalloc(bytes); + + if (ptr) { + ++mallocsFromTinyPool; + unlock(); + return ptr; + } + + } + + // Failure to allocate a tiny buffer is allowed to flow + // through to a small buffer + if (bytes <= smallBufferSize) { + + void* ptr = malloc(smallPool, smallPoolSize, bytes); + + if (ptr) { + ++mallocsFromSmallPool; + unlock(); + return ptr; + } + + } else if (bytes <= medBufferSize) { + // Note that a small allocation failure does *not* fall + // through into a medium allocation because that would + // waste the medium buffer's resources. + + void* ptr = malloc(medPool, medPoolSize, bytes); + + if (ptr) { + ++mallocsFromMedPool; + unlock(); + debugAssertM(ptr != NULL, "BufferPool::malloc returned NULL"); + return ptr; + } + } + + bytesAllocated += REALBLOCK_SIZE(bytes); + unlock(); + + // Heap allocate + + // Allocate 4 extra bytes for our size header (unfortunate, + // since malloc already added its own header). + void* ptr = ::malloc(REALBLOCK_SIZE(bytes)); + + if (ptr == NULL) { + // Flush memory pools to try and recover space + flushPool(smallPool, smallPoolSize); + flushPool(medPool, medPoolSize); + ptr = ::malloc(REALBLOCK_SIZE(bytes)); + } + + if (ptr == NULL) { + if ((System::outOfMemoryCallback() != NULL) && + (System::outOfMemoryCallback()(REALBLOCK_SIZE(bytes), true) == true)) { + // Re-attempt the malloc + ptr = ::malloc(REALBLOCK_SIZE(bytes)); + } + } + + if (ptr == NULL) { + if (System::outOfMemoryCallback() != NULL) { + // Notify the application + System::outOfMemoryCallback()(REALBLOCK_SIZE(bytes), false); + } +# ifdef G3D_DEBUG + debugPrintf("::malloc(%d) returned NULL\n", (int)REALBLOCK_SIZE(bytes)); +# endif + debugAssertM(ptr != NULL, + "::malloc returned NULL. Either the " + "operating system is out of memory or the " + "heap is corrupt."); + return NULL; + } + + *(uint32*)ptr = bytes; + + return REALPTR_TO_USERPTR(ptr); + } + + + void free(void* ptr) { + if (ptr == NULL) { + // Free does nothing on null pointers + return; + } + + assert(isValidPointer(ptr)); + + if (inTinyHeap(ptr)) { + lock(); + tinyFree(ptr); + unlock(); + return; + } + + uint32 bytes = *(uint32*)USERPTR_TO_REALPTR(ptr); + + lock(); + if (bytes <= smallBufferSize) { + if (smallPoolSize < maxSmallBuffers) { + smallPool[smallPoolSize] = MemBlock(ptr, bytes); + ++smallPoolSize; + unlock(); + return; + } + } else if (bytes <= medBufferSize) { + if (medPoolSize < maxMedBuffers) { + medPool[medPoolSize] = MemBlock(ptr, bytes); + ++medPoolSize; + unlock(); + return; + } + } + bytesAllocated -= REALBLOCK_SIZE(bytes); + unlock(); + + // Free; the buffer pools are full or this is too big to store. + ::free(USERPTR_TO_REALPTR(ptr)); + } + + std::string performance() const { + if (totalMallocs > 0) { + int pooled = mallocsFromTinyPool + + mallocsFromSmallPool + + mallocsFromMedPool; + + int total = totalMallocs; + + return format("malloc performance: %5.1f%% <= %db, %5.1f%% <= %db, " + "%5.1f%% <= %db, %5.1f%% > %db", + 100.0 * mallocsFromTinyPool / total, + BufferPool::tinyBufferSize, + 100.0 * mallocsFromSmallPool / total, + BufferPool::smallBufferSize, + 100.0 * mallocsFromMedPool / total, + BufferPool::medBufferSize, + 100.0 * (1.0 - (double)pooled / total), + BufferPool::medBufferSize); + } else { + return "No System::malloc calls made yet."; + } + } + + std::string status() const { + return format("preallocated shared buffers: %5d/%d x %db", + maxTinyBuffers - tinyPoolSize, maxTinyBuffers, tinyBufferSize); + } +}; + +// Dynamically allocated because we need to ensure that +// the buffer pool is still around when the last global variable +// is deallocated. +static BufferPool* bufferpool = NULL; + +std::string System::mallocPerformance() { +#ifndef NO_BUFFERPOOL + return bufferpool->performance(); +#else + return "NO_BUFFERPOOL"; +#endif +} + +std::string System::mallocStatus() { +#ifndef NO_BUFFERPOOL + return bufferpool->status(); +#else + return "NO_BUFFERPOOL"; +#endif +} + + +void System::resetMallocPerformanceCounters() { +#ifndef NO_BUFFERPOOL + bufferpool->totalMallocs = 0; + bufferpool->mallocsFromMedPool = 0; + bufferpool->mallocsFromSmallPool = 0; + bufferpool->mallocsFromTinyPool = 0; +#endif +} + + +#ifndef NO_BUFFERPOOL +inline void initMem() { + // Putting the test here ensures that the system is always + // initialized, even when globals are being allocated. + static bool initialized = false; + if (! initialized) { + bufferpool = new BufferPool(); + initialized = true; + } +} +#endif + + +void* System::malloc(size_t bytes) { +#ifndef NO_BUFFERPOOL + initMem(); + return bufferpool->malloc(bytes); +#else + return ::malloc(bytes); +#endif +} + +void* System::calloc(size_t n, size_t x) { +#ifndef NO_BUFFERPOOL + void* b = System::malloc(n * x); + debugAssertM(b != NULL, "System::malloc returned NULL"); + debugAssertM(isValidHeapPointer(b), "System::malloc returned an invalid pointer"); + System::memset(b, 0, n * x); + return b; +#else + return ::calloc(n, x); +#endif +} + + +void* System::realloc(void* block, size_t bytes) { +#ifndef NO_BUFFERPOOL + initMem(); + return bufferpool->realloc(block, bytes); +#else + return ::realloc(block, bytes); +#endif +} + + +void System::free(void* p) { +#ifndef NO_BUFFERPOOL + bufferpool->free(p); +#else + return ::free(p); +#endif +} + + +void* System::alignedMalloc(size_t bytes, size_t alignment) { + + alwaysAssertM(isPow2(alignment), "alignment must be a power of 2"); + + // We must align to at least a word boundary. + alignment = iMax(alignment, sizeof(void *)); + + // Pad the allocation size with the alignment size and the + // size of the redirect pointer. + size_t totalBytes = bytes + alignment + sizeof(void*); + + size_t truePtr = (size_t)System::malloc(totalBytes); + + if (truePtr == 0) { + // malloc returned NULL + return NULL; + } + + debugAssert(isValidHeapPointer((void*)truePtr)); + #ifdef G3D_WIN32 + // The blocks we return will not be valid Win32 debug heap + // pointers because they are offset + // debugAssert(_CrtIsValidPointer((void*)truePtr, totalBytes, TRUE) ); + #endif + + // The return pointer will be the next aligned location (we must at least + // leave space for the redirect pointer, however). + size_t alignedPtr = truePtr + sizeof(void*); + + // 2^n - 1 has the form 1111... in binary. + uint32 bitMask = (alignment - 1); + + // Advance forward until we reach an aligned location. + while ((alignedPtr & bitMask) != 0) { + alignedPtr += sizeof(void*); + } + + debugAssert(alignedPtr - truePtr + bytes <= totalBytes); + + // Immediately before the aligned location, write the true array location + // so that we can free it correctly. + size_t* redirectPtr = (size_t *)(alignedPtr - sizeof(void *)); + redirectPtr[0] = truePtr; + + debugAssert(isValidHeapPointer((void*)truePtr)); + + #ifdef G3D_WIN32 + debugAssert( _CrtIsValidPointer((void*)alignedPtr, bytes, TRUE) ); + #endif + return (void *)alignedPtr; +} + + +void System::alignedFree(void* _ptr) { + if (_ptr == NULL) { + return; + } + + size_t alignedPtr = (size_t)_ptr; + + // Back up one word from the pointer the user passed in. + // We now have a pointer to a pointer to the true start + // of the memory block. + size_t* redirectPtr = (size_t*)(alignedPtr - sizeof(void *)); + + // Dereference that pointer so that ptr = true start + void* truePtr = (void*)redirectPtr[0]; + + debugAssert(isValidHeapPointer((void*)truePtr)); + System::free(truePtr); +} + + +void System::setEnv(const std::string& name, const std::string& value) { + std::string cmd = name + "=" + value; +# ifdef G3D_WIN32 + _putenv(cmd.c_str()); +# else + // Many linux implementations of putenv expect char* + putenv(const_cast(cmd.c_str())); +# endif +} + + +const char* System::getEnv(const std::string& name) { + return getenv(name.c_str()); +} + + +static void var(TextOutput& t, const std::string& name, const std::string& val) { + t.writeSymbols(name,"="); + t.writeString(val); + t.writeNewline(); +} + + +static void var(TextOutput& t, const std::string& name, const bool val) { + t.writeSymbols(name, "=", val ? "Yes" : "No"); + t.writeNewline(); +} + + +static void var(TextOutput& t, const std::string& name, const int val) { + t.writeSymbols(name,"="); + t.writeNumber(val); + t.writeNewline(); +} + + +void System::describeSystem( + std::string& s) { + + TextOutput t; + describeSystem(t); + t.commitString(s); +} + +void System::describeSystem( + TextOutput& t) { + + t.writeSymbols("App", "{"); + t.writeNewline(); + t.pushIndent(); + { + var(t, "Name", System::currentProgramFilename()); + char cwd[1024]; + getcwd(cwd, 1024); + var(t, "cwd", std::string(cwd)); + } + t.popIndent(); + t.writeSymbols("}"); + t.writeNewline(); + t.writeNewline(); + + t.writeSymbols("OS", "{"); + t.writeNewline(); + t.pushIndent(); + { + var(t, "Name", System::operatingSystem()); + } + t.popIndent(); + t.writeSymbols("}"); + t.writeNewline(); + t.writeNewline(); + + t.writeSymbols("CPU", "{"); + t.writeNewline(); + t.pushIndent(); + { + var(t, "Vendor", System::cpuVendor()); + var(t, "Architecture", System::cpuArchitecture()); + var(t, "hasCPUID", System::hasCPUID()); + var(t, "hasMMX", System::hasMMX()); + var(t, "hasSSE", System::hasSSE()); + var(t, "hasSSE2", System::hasSSE2()); + var(t, "hasSSE3", System::hasSSE3()); + var(t, "has3DNow", System::has3DNow()); + var(t, "hasRDTSC", System::hasRDTSC()); + var(t, "numCores", System::numCores()); + } + t.popIndent(); + t.writeSymbols("}"); + t.writeNewline(); + t.writeNewline(); + + t.writeSymbols("G3D", "{"); + t.writeNewline(); + t.pushIndent(); + { + var(t, "Link version", G3D_VER); + var(t, "Compile version", System::version()); + } + t.popIndent(); + t.writeSymbols("}"); + t.writeNewline(); + t.writeNewline(); +} + + +void System::setClipboardText(const std::string& s) { +# ifdef G3D_WIN32 + if (OpenClipboard(NULL)) { + HGLOBAL hMem = GlobalAlloc(GHND | GMEM_DDESHARE, s.size() + 1); + if (hMem) { + char *pMem = (char*)GlobalLock(hMem); + strcpy(pMem, s.c_str()); + GlobalUnlock(hMem); + + EmptyClipboard(); + SetClipboardData(CF_TEXT, hMem); + } + + CloseClipboard(); + GlobalFree(hMem); + } +# endif +} + + +std::string System::getClipboardText() { + std::string s; + +# ifdef G3D_WIN32 + if (OpenClipboard(NULL)) { + HANDLE h = GetClipboardData(CF_TEXT); + + if (h) { + char* temp = (char*)GlobalLock(h); + if (temp) { + s = temp; + } + temp = NULL; + GlobalUnlock(h); + } + CloseClipboard(); + } +# endif + return s; +} + + +std::string System::currentDateString() { + time_t t1; + ::time(&t1); + tm* t = localtime(&t1); + return format("%d-%02d-%02d", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday); +} + +#ifdef _MSC_VER + +// VC on Intel +void System::cpuid(CPUIDFunction func, uint32& areg, uint32& breg, uint32& creg, uint32& dreg) { +#if !defined(G3D_64BIT) + // Can't copy from assembler direct to a function argument (which is on the stack) in VC. + uint32 a,b,c,d; + + // Intel assembler syntax + __asm { + mov eax, func // eax <- func + mov ecx, 0 + cpuid + mov a, eax + mov b, ebx + mov c, ecx + mov d, edx + } + areg = a; + breg = b; + creg = c; + dreg = d; +#else + int CPUInfo[4]; + __cpuid(CPUInfo, func); + memcpy(&areg, &CPUInfo[0], 4); + memcpy(&breg, &CPUInfo[1], 4); + memcpy(&creg, &CPUInfo[2], 4); + memcpy(&dreg, &CPUInfo[3], 4); +#endif +} + +#elif defined(G3D_OSX) && ! defined(G3D_OSX_INTEL) + +// non-intel OS X; no CPUID +void System::cpuid(CPUIDFunction func, uint32& eax, uint32& ebx, uint32& ecx, uint32& edx) { + eax = 0; + ebx = 0; + ecx = 0; + edx = 0; +} + +#else + +// See http://sam.zoy.org/blog/2007-04-13-shlib-with-non-pic-code-have-inline-assembly-and-pic-mix-well +// for a discussion of why the second version saves ebx; it allows 32-bit code to compile with the -fPIC option. +// On 64-bit x86, PIC code has a dedicated rip register for PIC so there is no ebx conflict. +void System::cpuid(CPUIDFunction func, uint32& eax, uint32& ebx, uint32& ecx, uint32& edx) { +#if ! defined(__PIC__) || defined(__x86_64__) + // AT&T assembler syntax + asm volatile( + "movl $0, %%ecx \n\n" /* Wipe ecx */ + "cpuid \n\t" + : "=a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx) + : "a"(func)); +#else + // AT&T assembler syntax + asm volatile( + "pushl %%ebx \n\t" /* save ebx */ + "movl $0, %%ecx \n\n" /* Wipe ecx */ + "cpuid \n\t" + "movl %%ebx, %1 \n\t" /* save what cpuid just put in %ebx */ + "popl %%ebx \n\t" /* restore the old ebx */ + : "=a"(eax), "=r"(ebx), "=c"(ecx), "=d"(edx) + : "a"(func)); +#endif +} + +#endif + +} // namespace diff --git a/dep/g3dlite/TextInput.cpp b/dep/g3dlite/TextInput.cpp new file mode 100644 index 00000000000..7276d8c66b2 --- /dev/null +++ b/dep/g3dlite/TextInput.cpp @@ -0,0 +1,1136 @@ +/** + @file TextInput.cpp + + @author Morgan McGuire, graphics3d.com + + @cite Based on a lexer written by Aaron Orenstein. + + @created 2001-11-27 + @edited 2008-07-14 + */ + +#include "G3D/fileutils.h" +#include "G3D/TextInput.h" +#include "G3D/BinaryInput.h" +#include "G3D/stringutils.h" + +#ifdef _MSC_VER +# pragma warning (push) +// conversion from 'int' to 'char', possible loss of data (TODO: fix underlying problems) +# pragma warning (disable: 4244) +#endif + +namespace G3D { + +Token TextInput::readSignificant() { + Token t; + do { + t = read(); + } while ((t.type() == Token::COMMENT) || (t.type() == Token::NEWLINE)); + return t; +} + + +double Token::number() const { + if (_type == NUMBER) { + std::string s = toLower(_string); + if (s == "-1.#ind00") { + return nan(); + } + + if (s == "1.#inf00") { + return inf(); + } + + if (s == "-1.#inf00") { + return -inf(); + } + + double n; + if ((_string.length() > 2) && + (_string[0] == '0') && + (_string[1] == 'x')) { + // Hex + uint32 i; + sscanf(_string.c_str(), "%x", &i); + n = i; + } else { + sscanf(_string.c_str(), "%lg", &n); + } + return n; + } else { + return 0.0; + } +} + + +TextInput::Settings::Settings () : + cppBlockComments(true), + cppLineComments(true), + otherLineComments(true), + escapeSequencesInStrings(true), + otherCommentCharacter('\0'), + otherCommentCharacter2('\0'), + generateCommentTokens(false), + generateNewlineTokens(false), + signedNumbers(true), + singleQuotedStrings(true), + singleQuoteCharacter('\''), + sourceFileName(), + startingLineNumberOffset(0), + msvcSpecials(true), + proofSymbols(false), + caseSensitive(true) +{ + trueSymbols.insert("true"); + falseSymbols.insert("false"); +} + + +Token TextInput::peek() { + if (stack.size() == 0) { + Token t = nextToken(); + push(t); + } + + return stack.front(); +} + + +int TextInput::peekLineNumber() { + return peek().line(); +} + + +int TextInput::peekCharacterNumber() { + return peek().character(); +} + + +Token TextInput::read() { + if (stack.size() > 0) { + Token t = stack.front(); + stack.pop_front(); + return t; + } else { + return nextToken(); + } +} + +static void toUpper(Set& set) { + Array symbols; + set.getMembers(symbols); + set.clear(); + for (int i = 0; i < symbols.size(); ++i) { + set.insert(toUpper(symbols[i])); + } +} + +void TextInput::init() { + currentCharOffset = 0; + charNumber = 1; + lineNumber = 1 + options.startingLineNumberOffset; + + if (! options.caseSensitive) { + // Convert true and false symbols to all uppercase for fast comparisons + toUpper(options.trueSymbols); + toUpper(options.falseSymbols); + } +} + + +void TextInput::push(const Token& t) { + stack.push_front(t); +} + + +bool TextInput::hasMore() { + return (peek()._type != Token::END); +} + + +int TextInput::eatInputChar() { + // Don't go off the end + if (currentCharOffset >= buffer.length()) { + return EOF; + } + + unsigned char c = buffer[currentCharOffset]; + ++currentCharOffset; + + // update lineNumber and charNumber to reflect the location of the *next* + // character which will be read. + + // increment line number for \r, \n and \r\n which matches Token::NEWLINE parsing + if (c == '\r') { + ++lineNumber; + charNumber = 1; + + // check for \r\n + if (currentCharOffset < buffer.length()) { + unsigned char c2 = buffer[currentCharOffset]; + if (c2 == '\n') { + c = c2; + ++currentCharOffset; + } + } + } else if (c == '\n') { + ++lineNumber; + charNumber = 1; + } else { + ++charNumber; + } + + return c; +} + +int TextInput::peekInputChar(int distance) { + // Don't go off the end + if ((currentCharOffset + distance) >= buffer.length()) { + return EOF; + } + + unsigned char c = buffer[currentCharOffset + distance]; + return c; +} + + +Token TextInput::nextToken() { + Token t; + + t._line = lineNumber; + t._character = charNumber; + t._type = Token::END; + t._extendedType = Token::END_TYPE; + + int c = peekInputChar(); + if (c == EOF) { + return t; + } + + // loop through white space, newlines and comments + // found before other tokens + bool whitespaceDone = false; + while (! whitespaceDone) { + whitespaceDone = true; + + // generate newlines tokens for '\n' and '\r' and '\r\n' + if (options.generateNewlineTokens && isNewline(c)) { + t._type = Token::NEWLINE; + t._extendedType = Token::NEWLINE_TYPE; + t._string = c; + + int c2 = peekInputChar(1); + if (c == '\r' && c2 == '\n') { + t._string += c2; + } + + eatInputChar(); + return t; + } else { + // Consume whitespace + while (isWhiteSpace(c)) { + c = eatAndPeekInputChar(); + } + } + + // update line and character number to include discarded whitespace + t._line = lineNumber; + t._character = charNumber; + + int c2 = peekInputChar(1); + + // parse comments and generate tokens if enabled + std::string commentString; + + // check for line comments first + bool isLineComment = false; + if (options.cppLineComments && (c == '/' && c2 == '/')) { + // set start of line comment and eat markers + isLineComment = true; + eatInputChar(); + eatInputChar(); + } else if ( options.otherCommentCharacter && + (options.otherCommentCharacter != '\0' && c == options.otherCommentCharacter) ) { + // set start of line comment and eat markers + isLineComment = true; + eatInputChar(); + } else if ( options.otherCommentCharacter && + (options.otherCommentCharacter2 != '\0' && c == options.otherCommentCharacter2) ) { + // set start of line comment and eat markers + isLineComment = true; + eatInputChar(); + } + + if (isLineComment) { + + // consume line comment to newline or EOF + c = peekInputChar(); + while (! isNewline(c) && c != EOF) { + // build comment string for token + commentString += c; + + c = eatAndPeekInputChar(); + } + + if (options.generateCommentTokens) { + t._type = Token::COMMENT; + t._extendedType = Token::LINE_COMMENT_TYPE; + t._string = commentString; + return t; + } else { + // There is whitespace after the comment (in particular, the + // newline that terminates the comment). There might also be + // whitespace at the start of the next line. + whitespaceDone = false; + } + + } else if (options.cppBlockComments && (c == '/' && c2 == '*')) { + // consume block comment to end-marker or EOF + + // consume both start-comment chars, can't let the trailing one + // help close the comment. + eatInputChar(); + eatInputChar(); + + c = peekInputChar(); + c2 = peekInputChar(1); + while (! ((c == '*') && (c2 == '/')) && (c != EOF)) { + commentString += c; + + eatInputChar(); + c = c2; + c2 = peekInputChar(1); + } + eatInputChar(); // eat closing '*' + eatInputChar(); // eat closing '/' + + c = peekInputChar(); + + if (options.generateCommentTokens) { + t._type = Token::COMMENT; + t._extendedType = Token::BLOCK_COMMENT_TYPE; + t._string = commentString; + return t; + } else { + // There is whitespace after the comment (in particular, the + // newline that terminates the comment). There might also be + // whitespace at the start of the next line. + whitespaceDone = false; + } + } + + } // while (! whitespaceDone) + + t._line = lineNumber; + t._character = charNumber; + + // handle EOF + if (c == EOF) { + return t; + } + + // Extended ASCII parses as itself, except for EOF + if (c > 127 && c < 255) { + t._type = Token::SYMBOL; + t._extendedType = Token::SYMBOL_TYPE; + t._string = c; + c = eatAndPeekInputChar(); + } + + + // Perform appropriate setup for a symbol (including setting up the token + // string to start with c), eat the input character, and overwrite + // 'c' with the peeked next input character. +#define SETUP_SYMBOL(c) \ + { \ + t._type = Token::SYMBOL; \ + t._extendedType = Token::SYMBOL_TYPE; \ + t._string = c; \ + c = eatAndPeekInputChar(); \ + } + + switch (c) { + + case '@': // Simple symbols -> just themselves. + case '(': + case ')': + case ',': + case ';': + case '{': + case '}': + case '[': + case ']': + case '#': + case '$': + case '?': + case '%': + SETUP_SYMBOL(c); + return t; + + case '-': // negative number, -, --, -=, or -> + SETUP_SYMBOL(c); + + switch (c) { + case '>': // -> + case '-': // -- + case '=': // -= + t._string += c; + eatInputChar(); + return t; + } + + if (options.signedNumbers + && (isDigit(c) || (c == '.' && isDigit(peekInputChar(1))))) { + + // Negative number. 'c' is still the first digit, and is + // the next input char. + + goto numLabel; + } + + // plain - + return t; + + case '+': // positive number, +, ++, or += + SETUP_SYMBOL(c); + + switch (c) { + case '+': // ++ + case '=': // += + t._string += c; + eatInputChar(); + return t; + } + + if (options.signedNumbers + && (isDigit(c) || (c == '.' && isDigit(peekInputChar(1))))) { + + // Positive number. 'c' is still the first digit, and is + // the next input char. + + goto numLabel; + } + + return t; + + case ':': // : or :: or ::> or ::= or := or :> + SETUP_SYMBOL(c); + + if (c == ':') { + t._string += c; + eatInputChar(); + + if (options.proofSymbols) { + c = peekInputChar(0); + + if ((c == '>') || (c == '=')) { + t._string += c; + eatInputChar(); + } + } + } + else if (options.proofSymbols && (c == '=' || c == '>')) { + t._string += c; + eatInputChar(); + } + return t; + + case '=': // = or == or => + SETUP_SYMBOL(c); + + if (c == '=') { + t._string += c; + eatInputChar(); + return t; + } else if (options.proofSymbols && (c == '>')) { + t._string += c; + eatInputChar(); + return t; + } + return t; + + case '*': // * or *= + case '/': // / or /= + case '!': // ! or != + case '~': // ~ or ~= + case '^': // ^ or ^= + SETUP_SYMBOL(c); + + if (c == '=') { + t._string += c; + eatInputChar(); + return t; + } + return t; + + case '>': // >, >>,or >= + case '<': // <<, <<, or <= or <- or <: + case '|': // ||, ||, or |= or |- + case '&': // &, &&, or &= + { + int orig_c = c; + SETUP_SYMBOL(c); + + if ((c == '=') || (orig_c == c)) { + t._string += c; + eatInputChar(); + return t; + } else if (options.proofSymbols) { + if ((orig_c == '<') && (c == '-')) { + t._string += c; + eatInputChar(); + } else if ((orig_c == '|') && (c == '-')) { + t._string += c; + eatInputChar(); + } else if ((orig_c == '<') && (c == ':')) { + t._string += c; + + c = eatAndPeekInputChar(); + + if (c == ':') { + t._string += c; + eatInputChar(); + } + } + } + } + return t; + + case '\\': // backslash or escaped comment char. + SETUP_SYMBOL(c); + + if ((options.otherCommentCharacter != '\0' + && c == options.otherCommentCharacter) + || (options.otherCommentCharacter2 != '\0' + && c == options.otherCommentCharacter2)) { + + // escaped comment character. Return the raw comment + // char (no backslash). + + t._string = c; + eatInputChar(); + return t; + } + return t; + + case '.': // number, ., .., or ... + if (isDigit(peekInputChar(1))) { + // We're parsing a float that began without a leading zero + goto numLabel; + } + + SETUP_SYMBOL(c); + + if (c == '.') { // .. or ... + t._string += c; + c = eatAndPeekInputChar(); + + if (c == '.') { // ... + t._string += c; + eatInputChar(); + } + return t; + } + + return t; + + } // switch (c) + +#undef SETUP_SYMBOL + +numLabel: + if (isDigit(c) || (c == '.')) { + + // A number. Note-- single dots have been + // parsed already, so a . indicates a number + // less than 1 in floating point form. + + // [0-9]*(\.[0-9][f]) or [0-9]+ or 0x[0-9,A-F]+ + + if (t._string != "-") { + // If we picked up a leading "-" sign above, keep it, + // otherwise drop the string parsed thus far + t._string = ""; + } + t._type = Token::NUMBER; + if (c == '.') { + t._extendedType = Token::FLOATING_POINT_TYPE; + } else { + t._extendedType = Token::INTEGER_TYPE; + } + + if ((c == '0') && (peekInputChar(1) == 'x')) { + // Hex number + t._string += "0x"; + + // skip the 0x + eatInputChar(); + eatInputChar(); + + c = peekInputChar(); + while (isDigit(c) || ((c >= 'A') && (c <= 'F')) || ((c >= 'a') && (c <= 'f'))) { + t._string += c; + c = eatAndPeekInputChar(); + } + + } else { + // Non-hex number + + // Read the part before the decimal. + while (isDigit(c)) { + t._string += c; + c = eatAndPeekInputChar(); + } + + // True if we are reading a floating-point special type + bool isSpecial = false; + + // Read the decimal, if one exists + if (c == '.') { + t._extendedType = Token::FLOATING_POINT_TYPE; + + // The '.' character was a decimal point, not the start of a + // method or range operator + t._string += c; + c = eatAndPeekInputChar(); + + // Floating point specials (msvc format only) + if (options.msvcSpecials && (c == '#')) { + isSpecial = true; + // We are reading a floating point special value + // of the form -1.#IND00, -1.#INF00, or 1.#INF00 + c = eatAndPeekInputChar(); + char test = c; + if (! options.caseSensitive) { + test = toupper(c); + } + if (test != 'I') { + throw BadMSVCSpecial + ( + "Incorrect floating-point special (inf or nan) " + "format.", + t.line(), charNumber); + } + c = eatAndPeekInputChar(); + test = c; + if (! options.caseSensitive) { + test = toupper(c); + } + if (test != 'N') { + throw BadMSVCSpecial + ( + "Incorrect floating-point special (inf or nan) " + "format.", + t.line(), charNumber); + } + t._string += "#IN"; + c = eatAndPeekInputChar(); + test = c; + if (! options.caseSensitive) { + test = toupper(c); + } + if ((test != 'F') && (test != 'D')) { + throw BadMSVCSpecial + ( + "Incorrect floating-point special (inf or nan) " + "format.", + t.line(), charNumber); + } + t._string += c; + for (int j = 0; j < 2; ++j) { + c = eatAndPeekInputChar(); + if (c != '0') { + throw BadMSVCSpecial + ( + "Incorrect floating-point special (inf or" + "nan) format.", + t.line(), charNumber); + } + t._string += (char)c; + } + + } else { + + // Read the part after the decimal + while (isDigit((char)c)) { + t._string += (char)c; + c = eatAndPeekInputChar(); + } + } + } + + if (! isSpecial && ((c == 'e') || (c == 'E'))) { + // Read exponent + t._extendedType = Token::FLOATING_POINT_TYPE; + t._string += c; + + c = eatAndPeekInputChar(); + if ((c == '-') || (c == '+')) { + t._string += c; + c = eatAndPeekInputChar(); + } + + while (isDigit(c)) { + t._string += c; + c = eatAndPeekInputChar(); + } + } + + if (! isSpecial && (t._extendedType == Token::FLOATING_POINT_TYPE) && (c == 'f')) { + // Trailing f on a float + t._string += c; + c = eatAndPeekInputChar(); + } + } + return t; + + } else if (isLetter(c) || (c == '_')) { + // Identifier or keyword + // [A-Za-z_][A-Za-z_0-9]* + + t._type = Token::SYMBOL; + t._extendedType = Token::SYMBOL_TYPE; + t._string = ""; + do { + t._string += c; + c = eatAndPeekInputChar(); + } while (isLetter(c) || isDigit(c) || (c == '_')); + + // See if this symbol is actually a boolean + if ((options.trueSymbols.size() > 0) || (options.falseSymbols.size() > 0)) { + std::string str = t._string; + if (! options.caseSensitive) { + str = toUpper(str); + } + if (options.trueSymbols.contains(str)) { + t._type = Token::BOOLEAN; + t._extendedType = Token::BOOLEAN_TYPE; + t._bool = true; + } else if (options.falseSymbols.contains(str)) { + t._type = Token::BOOLEAN; + t._extendedType = Token::BOOLEAN_TYPE; + t._bool = false; + } + } + + return t; + + } else if (c == '\"') { + + // Discard the double-quote. + eatInputChar(); + + // Double quoted string + parseQuotedString('\"', t); + return t; + + } else if (c == options.singleQuoteCharacter) { + + // Discard the single-quote. + eatInputChar(); + + if (options.singleQuotedStrings) { + // Single quoted string + parseQuotedString(options.singleQuoteCharacter, t); + } else { + t._string = c; + t._type = Token::SYMBOL; + t._extendedType = Token::SYMBOL_TYPE; + } + return t; + + } // end of special case tokens + + if (c == EOF) { + t._type = Token::END; + t._extendedType = Token::END_TYPE; + t._string = ""; + return t; + } + + // Some unknown token + debugAssertM(false, + format("Unrecognized token type beginning with character '%c' (ASCII %d)", + c, c)); + return t; +} + + +void TextInput::parseQuotedString(unsigned char delimiter, Token& t) { + + t._type = Token::STRING; + + if (delimiter == options.singleQuoteCharacter) { + t._extendedType = Token::SINGLE_QUOTED_TYPE; + } else { + t._extendedType = Token::DOUBLE_QUOTED_TYPE; + } + + while (true) { + // We're definitely going to consume the next input char, so we get + // it right now. This makes the condition handling below a bit easier. + int c = eatInputChar(); + + if (c == EOF) { + // END inside a quoted string. (We finish the string.) + break; + } + + if (options.escapeSequencesInStrings && (c == '\\')) { + // An escaped character. We're definitely going to consume it, + // so we get it (and consume it) now. + + c = eatInputChar(); + + switch (c) { + case 'r': + t._string += '\r'; + break; + case 'n': + t._string += '\n'; + break; + case 't': + t._string += '\t'; + break; + case '0': + t._string += '\0'; + break; + + case '\\': + case '\"': + t._string += (char)c; + break; + + default: + if (c == options.singleQuoteCharacter) { + t._string += (char)c; + break; + } + + if (((c == options.otherCommentCharacter) && + (options.otherCommentCharacter != '\0')) || + ((c == options.otherCommentCharacter2) && + (options.otherCommentCharacter2 != '\0'))) { + t._string += c; + } + // otherwise, some illegal escape sequence; skip it. + break; + + } // switch + + } else if (c == delimiter) { + // End of the string. Already consumed the character. + break; + } else { + // All other chars, go on to the string. Already consumed the + // character. + t._string += (char)c; + } + + } +} + +bool TextInput::readBoolean() { + Token t(read()); + + if (t._type == Token::BOOLEAN) { + return t.boolean(); + } + + // Push initial token back, and throw an error. We intentionally + // indicate that the wrong type is the type of the initial token. + // Logically, the number started there. + push(t); + throw WrongTokenType(options.sourceFileName, t.line(), t.character(), + Token::BOOLEAN, t._type); +} + +double TextInput::readNumber() { + Token t(read()); + + if (t._type == Token::NUMBER) { + return t.number(); + } + + // Even if signedNumbers is disabled, readNumber attempts to + // read a signed number, so we handle that case here. + if (! options.signedNumbers + && (t._type == Token::SYMBOL) + && ((t._string == "-") + || (t._string == "+"))) { + + Token t2(read()); + + if ((t2._type == Token::NUMBER) + && (t2._character == t._character + 1)) { + + if (t._string == "-") { + return -t2.number(); + } else { + return t2.number(); + } + } + + // push back the second token. + push(t2); + } + + // Push initial token back, and throw an error. We intentionally + // indicate that the wrong type is the type of the initial token. + // Logically, the number started there. + push(t); + throw WrongTokenType(options.sourceFileName, t.line(), t.character(), + Token::NUMBER, t._type); +} + + +Token TextInput::readStringToken() { + Token t(read()); + + if (t._type == Token::STRING) { // fast path + return t; + } + + push(t); + throw WrongTokenType(options.sourceFileName, t.line(), t.character(), + Token::STRING, t._type); +} + +std::string TextInput::readString() { + return readStringToken()._string; +} + +void TextInput::readString(const std::string& s) { + Token t(readStringToken()); + + if (t._string == s) { // fast path + return; + } + + push(t); + throw WrongString(options.sourceFileName, t.line(), t.character(), + s, t._string); +} + +Token TextInput::readCommentToken() { + Token t(read()); + + if (t._type == Token::COMMENT) { // fast path + return t; + } + + push(t); + throw WrongTokenType(options.sourceFileName, t.line(), t.character(), + Token::COMMENT, t._type); +} + +std::string TextInput::readComment() { + return readCommentToken()._string; +} + +void TextInput::readComment(const std::string& s) { + Token t(readCommentToken()); + + if (t._string == s) { // fast path + return; + } + + push(t); + throw WrongString(options.sourceFileName, t.line(), t.character(), + s, t._string); +} + +Token TextInput::readNewlineToken() { + Token t(read()); + + if (t._type == Token::NEWLINE) { // fast path + return t; + } + + push(t); + throw WrongTokenType(options.sourceFileName, t.line(), t.character(), + Token::NEWLINE, t._type); +} + +std::string TextInput::readNewline() { + return readNewlineToken()._string; +} + +void TextInput::readNewline(const std::string& s) { + Token t(readNewlineToken()); + + if (t._string == s) { // fast path + return; + } + + push(t); + throw WrongString(options.sourceFileName, t.line(), t.character(), + s, t._string); +} + +Token TextInput::readSymbolToken() { + Token t(read()); + + if (t._type == Token::SYMBOL) { // fast path + return t; + } + + push(t); + throw WrongTokenType(options.sourceFileName, t.line(), t.character(), + Token::SYMBOL, t._type); +} + + +std::string TextInput::readSymbol() { + return readSymbolToken()._string; +} + +void TextInput::readSymbol(const std::string& symbol) { + Token t(readSymbolToken()); + + if (t._string == symbol) { // fast path + return; + } + + push(t); + throw WrongSymbol(options.sourceFileName, t.line(), t.character(), + symbol, t._string); +} + + +TextInput::TextInput(const std::string& filename, const Settings& opt) : options(opt) { + init(); + std::string input = readWholeFile(filename); + + if (options.sourceFileName.empty()) { + options.sourceFileName = filename; + } + int n = input.size(); + buffer.resize(n); + System::memcpy(buffer.getCArray(), input.c_str(), n); +} + + +TextInput::TextInput(FS fs, const std::string& str, const Settings& opt) : options(opt) { + (void)fs; + init(); + if (options.sourceFileName.empty()) { + if (str.length() < 14) { + options.sourceFileName = std::string("\"") + str + "\""; + } else { + options.sourceFileName = std::string("\"") + str.substr(0, 10) + "...\""; + } + } + buffer.resize(str.length()); // we don't bother copying trailing NUL. + System::memcpy(buffer.getCArray(), str.c_str(), buffer.size()); +} + + +const std::string& TextInput::filename() const { + return options.sourceFileName; +} + +/////////////////////////////////////////////////////////////////////////////////// + +TextInput::TokenException::TokenException( + const std::string& src, + int ln, + int ch) : ParseError(src, ln, ch, format("%s(%d) : ", src.c_str(), ln)), + sourceFile(src) { +} + +/////////////////////////////////////////////////////////////////////////////////// + +static const char* tokenTypeToString(Token::Type t) { + switch (t) { + case Token::SYMBOL: + return "Token::SYMBOL"; + case Token::STRING: + return "Token::STRING"; + case Token::NUMBER: + return "Token::NUMBER"; + case Token::END: + return "Token::END"; + default: + debugAssertM(false, "Fell through switch"); + return "?"; + } +} + +TextInput::WrongTokenType::WrongTokenType( + const std::string& src, + int ln, + int ch, + Token::Type e, + Token::Type a) : + TokenException(src, ln, ch), expected(e), actual(a) { + + message += format("Expected token of type %s, found type %s.", + tokenTypeToString(e), tokenTypeToString(a)); +} + + +TextInput::BadMSVCSpecial::BadMSVCSpecial( + const std::string& src, + int ln, + int ch) : + TokenException(src, ln, ch) { +} + + +TextInput::WrongSymbol::WrongSymbol( + const std::string& src, + int ln, + int ch, + const std::string& e, + const std::string& a) : + TokenException(src, ln, ch), expected(e), actual(a) { + + message += format("Expected symbol '%s', found symbol '%s'.", + e.c_str(), a.c_str()); +} + + +TextInput::WrongString::WrongString( + const std::string& src, + int ln, + int ch, + const std::string& e, + const std::string& a) : + TokenException(src, ln, ch), expected(e), actual(a) { + + message += format("Expected string '%s', found string '%s'.", + e.c_str(), a.c_str()); +} + + +void deserialize(bool& b, TextInput& ti) { + b = ti.readSymbol() == "true"; +} + + +void deserialize(int& b, TextInput& ti) { + b = iRound(ti.readNumber()); +} + + +void deserialize(uint8& b, TextInput& ti) { + b = (uint8)iRound(ti.readNumber()); +} + + +void deserialize(double& b, TextInput& ti) { + b = ti.readNumber(); +} + + +void deserialize(float& b, TextInput& ti) { + b = (float)ti.readNumber(); +} + +} // namespace + +#ifdef _MSC_VER +# pragma warning (pop) +#endif diff --git a/dep/g3dlite/TextOutput.cpp b/dep/g3dlite/TextOutput.cpp new file mode 100644 index 00000000000..11347252eba --- /dev/null +++ b/dep/g3dlite/TextOutput.cpp @@ -0,0 +1,452 @@ +/** + @file TextOutput.cpp + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + @created 2004-06-21 + @edited 2006-08-14 + + Copyright 2000-2006, Morgan McGuire. + All rights reserved. + */ + +#include "G3D/TextOutput.h" +#include "G3D/Log.h" +#include "G3D/fileutils.h" + +namespace G3D { + +TextOutput::TextOutput(const TextOutput::Settings& opt) : + startingNewLine(true), + currentColumn(0), + inDQuote(false), + filename(""), + indentLevel(0) +{ + setOptions(opt); +} + + +TextOutput::TextOutput(const std::string& fil, const TextOutput::Settings& opt) : + startingNewLine(true), + currentColumn(0), + inDQuote(false), + filename(fil), + indentLevel(0) +{ + + setOptions(opt); +} + + +void TextOutput::setIndentLevel(int i) { + indentLevel = i; + + // If there were more pops than pushes, don't let that take us below 0 indent. + // Don't ever indent more than the number of columns. + indentSpaces = + iClamp(option.spacesPerIndent * indentLevel, + 0, + option.numColumns - 1); +} + + +void TextOutput::setOptions(const Settings& _opt) { + option = _opt; + + debugAssert(option.numColumns > 1); + + setIndentLevel(indentLevel); + + newline = (option.newlineStyle == Settings::NEWLINE_WINDOWS) ? "\r\n" : "\n"; +} + + +void TextOutput::pushIndent() { + setIndentLevel(indentLevel + 1); +} + + +void TextOutput::popIndent() { + setIndentLevel(indentLevel - 1); +} + + +static std::string escape(const std::string& string) { + std::string result = ""; + + for (std::string::size_type i = 0; i < string.length(); ++i) { + char c = string.at(i); + switch (c) { + case '\0': + result += "\\0"; + break; + + case '\r': + result += "\\r"; + break; + + case '\n': + result += "\\n"; + break; + + case '\t': + result += "\\t"; + break; + + case '\\': + result += "\\\\"; + break; + + default: + result += c; + } + } + + return result; +} + +void TextOutput::writeString(const std::string& string) { + // Convert special characters to escape sequences + this->printf("\"%s\"", escape(string).c_str()); +} + + +void TextOutput::writeBoolean(bool b) { + this->printf("%s ", b ? option.trueSymbol.c_str() : option.falseSymbol.c_str()); +} + +void TextOutput::writeNumber(double n) { + this->printf("%f ", n); +} + + +void TextOutput::writeNumber(int n) { + this->printf("%d ", n); +} + + +void TextOutput::writeSymbol(const std::string& string) { + if (string.size() > 0) { + // TODO: check for legal symbols? + this->printf("%s ", string.c_str()); + } +} + +void TextOutput::writeSymbols( + const std::string& a, + const std::string& b, + const std::string& c, + const std::string& d, + const std::string& e, + const std::string& f) { + + writeSymbol(a); + writeSymbol(b); + writeSymbol(c); + writeSymbol(d); + writeSymbol(e); + writeSymbol(f); +} + + +void TextOutput::printf(const std::string formatString, ...) { + va_list argList; + va_start(argList, formatString); + this->vprintf(formatString.c_str(), argList); + va_end(argList); +} + + +void TextOutput::printf(const char* formatString, ...) { + va_list argList; + va_start(argList, formatString); + this->vprintf(formatString, argList); + va_end(argList); +} + + +void TextOutput::convertNewlines(const std::string& in, std::string& out) { + // TODO: can be significantly optimized in cases where + // single characters are copied in order by walking through + // the array and copying substrings as needed. + + if (option.convertNewlines) { + out = ""; + for (uint32 i = 0; i < in.size(); ++i) { + if (in[i] == '\n') { + // Unix newline + out += newline; + } else if ((in[i] == '\r') && (i + 1 < in.size()) && (in[i + 1] == '\n')) { + // Windows newline + out += newline; + ++i; + } else { + out += in[i]; + } + } + } else { + out = in; + } +} + + +void TextOutput::writeNewline() { + for (uint32 i = 0; i < newline.size(); ++i) { + indentAppend(newline[i]); + } +} + + +void TextOutput::writeNewlines(int numLines) { + for (int i = 0; i < numLines; ++i) { + writeNewline(); + } +} + + +void TextOutput::wordWrapIndentAppend(const std::string& str) { + // TODO: keep track of the last space character we saw so we don't + // have to always search. + + if ((option.wordWrap == Settings::WRAP_NONE) || + (currentColumn + (int)str.size() <= option.numColumns)) { + // No word-wrapping is needed + + // Add one character at a time. + // TODO: optimize for strings without newlines to add multiple + // characters. + for (uint32 i = 0; i < str.size(); ++i) { + indentAppend(str[i]); + } + return; + } + + // Number of columns to wrap against + int cols = option.numColumns - indentSpaces; + + // Copy forward until we exceed the column size, + // and then back up and try to insert newlines as needed. + for (uint32 i = 0; i < str.size(); ++i) { + + indentAppend(str[i]); + if ((str[i] == '\r') && (i + 1 < str.size()) && (str[i + 1] == '\n')) { + // \r\n, we need to hit the \n to enter word wrapping. + ++i; + indentAppend(str[i]); + } + + if (currentColumn >= cols) { + debugAssertM(str[i] != '\n' && str[i] != '\r', + "Should never enter word-wrapping on a newline character"); + + // True when we're allowed to treat a space as a space. + bool unquotedSpace = option.allowWordWrapInsideDoubleQuotes || ! inDQuote; + + // Cases: + // + // 1. Currently in a series of spaces that ends with a newline + // strip all spaces and let the newline + // flow through. + // + // 2. Currently in a series of spaces that does not end with a newline + // strip all spaces and replace them with single newline + // + // 3. Not in a series of spaces + // search backwards for a space, then execute case 2. + + // Index of most recent space + uint32 lastSpace = data.size() - 1; + + // How far back we had to look for a space + uint32 k = 0; + uint32 maxLookBackward = currentColumn - indentSpaces; + + // Search backwards (from current character), looking for a space. + while ((k < maxLookBackward) && + (lastSpace > 0) && + (! ((data[lastSpace] == ' ') && unquotedSpace))) { + --lastSpace; + ++k; + + if ((data[lastSpace] == '\"') && !option.allowWordWrapInsideDoubleQuotes) { + unquotedSpace = ! unquotedSpace; + } + } + + if (k == maxLookBackward) { + // We couldn't find a series of spaces + + if (option.wordWrap == Settings::WRAP_ALWAYS) { + // Strip the last character we wrote, force a newline, + // and replace the last character; + data.pop(); + writeNewline(); + indentAppend(str[i]); + } else { + // Must be Settings::WRAP_WITHOUT_BREAKING + // + // Don't write the newline; we'll come back to + // the word wrap code after writing another character + } + } else { + // We found a series of spaces. If they continue + // to the new string, strip spaces off both. Otherwise + // strip spaces from data only and insert a newline. + + // Find the start of the spaces. firstSpace is the index of the + // first non-space, looking backwards from lastSpace. + uint32 firstSpace = lastSpace; + while ((k < maxLookBackward) && + (firstSpace > 0) && + (data[firstSpace] == ' ')) { + --firstSpace; + ++k; + } + + if (k == maxLookBackward) { + ++firstSpace; + } + + if (lastSpace == (uint32)data.size() - 1) { + // Spaces continued up to the new string + data.resize(firstSpace + 1); + writeNewline(); + + // Delete the spaces from the new string + while ((i < str.size() - 1) && (str[i + 1] == ' ')) { + ++i; + } + } else { + // Spaces were somewhere in the middle of the old string. + // replace them with a newline. + + // Copy over the characters that should be saved + Array temp; + for (uint32 j = lastSpace + 1; j < (uint32)data.size(); ++j) { + char c = data[j]; + + if (c == '\"') { + // Undo changes to quoting (they will be re-done + // when we paste these characters back on). + inDQuote = !inDQuote; + } + temp.append(c); + } + + // Remove those characters and replace with a newline. + data.resize(firstSpace + 1); + writeNewline(); + + // Write them back + for (uint32 j = 0; j < (uint32)temp.size(); ++j) { + indentAppend(temp[j]); + } + + // We are now free to continue adding from the + // new string, which may or may not begin with spaces. + + } // if spaces included new string + } // if hit indent + } // if line exceeded + } // iterate over str +} + + +void TextOutput::indentAppend(char c) { + + if (startingNewLine) { + for (int j = 0; j < indentSpaces; ++j) { + data.push(' '); + } + startingNewLine = false; + currentColumn = indentSpaces; + } + + data.push(c); + + // Don't increment the column count on return character + // newline is taken care of below. + if (c != '\r') { + ++currentColumn; + } + + if (c == '\"') { + inDQuote = ! inDQuote; + } + + startingNewLine = (c == '\n'); + if (startingNewLine) { + currentColumn = 0; + } +} + + +void TextOutput::vprintf(const char* formatString, va_list argPtr) { + std::string str = vformat(formatString, argPtr); + + std::string clean; + convertNewlines(str, clean); + wordWrapIndentAppend(clean); +} + + +void TextOutput::commit(bool flush) { + std::string p = filenamePath(filename); + if (! fileExists(p, false)) { + createDirectory(p); + } + + FILE* f = fopen(filename.c_str(), "wb"); + debugAssertM(f, "Could not open \"" + filename + "\""); + fwrite(data.getCArray(), 1, data.size(), f); + if (flush) { + fflush(f); + } + fclose(f); +} + + +void TextOutput::commitString(std::string& out) { + // Null terminate + data.push('\0'); + out = data.getCArray(); + data.pop(); +} + + +std::string TextOutput::commitString() { + std::string str; + commitString(str); + return str; +} + + + +///////////////////////////////////////////////////////////////////// + +void serialize(const float& b, TextOutput& to) { + to.writeNumber(b); +} + + +void serialize(const bool& b, TextOutput& to) { + to.writeSymbol(b ? "true" : "false"); +} + + +void serialize(const int& b, TextOutput& to) { + to.writeNumber(b); +} + + +void serialize(const uint8& b, TextOutput& to) { + to.writeNumber(b); +} + + +void serialize(const double& b, TextOutput& to) { + to.writeNumber(b); +} + + +} diff --git a/dep/g3dlite/Triangle.cpp b/dep/g3dlite/Triangle.cpp new file mode 100644 index 00000000000..253438ad5fb --- /dev/null +++ b/dep/g3dlite/Triangle.cpp @@ -0,0 +1,186 @@ +/** + @file Triangle.cpp + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2001-04-06 + @edited 2008-12-28 + + Copyright 2000-2009, Morgan McGuire. + All rights reserved. + */ + +#include "G3D/platform.h" +#include "G3D/Triangle.h" +#include "G3D/Plane.h" +#include "G3D/BinaryInput.h" +#include "G3D/BinaryOutput.h" +#include "G3D/debugAssert.h" +#include "G3D/AABox.h" +#include "G3D/Ray.h" + +namespace G3D { + + +void Triangle::init(const Vector3& v0, const Vector3& v1, const Vector3& v2) { + + _plane = Plane(v0, v1, v2); + _vertex[0] = v0; + _vertex[1] = v1; + _vertex[2] = v2; + + static int next[] = {1,2,0}; + + for (int i = 0; i < 3; ++i) { + const Vector3& e = _vertex[next[i]] - _vertex[i]; + edgeMagnitude[i] = e.magnitude(); + + if (edgeMagnitude[i] == 0) { + edgeDirection[i] = Vector3::zero(); + } else { + edgeDirection[i] = e / (float)edgeMagnitude[i]; + } + } + + _edge01 = _vertex[1] - _vertex[0]; + _edge02 = _vertex[2] - _vertex[0]; + + _primaryAxis = _plane.normal().primaryAxis(); + _area = 0.5f * edgeDirection[0].cross(edgeDirection[2]).magnitude() * (edgeMagnitude[0] * edgeMagnitude[2]); + //0.5f * (_vertex[1] - _vertex[0]).cross(_vertex[2] - _vertex[0]).dot(_plane.normal()); +} + + +Triangle::Triangle() { + init(Vector3::zero(), Vector3::zero(), Vector3::zero()); +} + + +Triangle::Triangle(const Vector3& v0, const Vector3& v1, const Vector3& v2) { + init(v0, v1, v2); +} + + +Triangle::~Triangle() { +} + + +Triangle::Triangle(class BinaryInput& b) { + deserialize(b); +} + + +void Triangle::serialize(class BinaryOutput& b) { + _vertex[0].serialize(b); + _vertex[1].serialize(b); + _vertex[2].serialize(b); +} + + +void Triangle::deserialize(class BinaryInput& b) { + _vertex[0].deserialize(b); + _vertex[1].deserialize(b); + _vertex[2].deserialize(b); + init(_vertex[0], _vertex[1], _vertex[2]); +} + + +float Triangle::area() const { + return _area; +} + + +const Vector3& Triangle::normal() const { + return _plane.normal(); +} + + +const Plane& Triangle::plane() const { + return _plane; +} + + +Vector3 Triangle::center() const { + return (_vertex[0] + _vertex[1] + _vertex[2]) / 3.0; +} + +Vector3 Triangle::randomPoint() const { + // Choose a random point in the parallelogram + + float s = uniformRandom(); + float t = uniformRandom(); + + if (t > 1.0f - s) { + // Outside the triangle; reflect about the + // diagonal of the parallelogram + t = 1.0f - t; + s = 1.0f - s; + } + + return _edge01 * s + _edge02 * t + _vertex[0]; +} + + +void Triangle::getBounds(AABox& out) const { + Vector3 lo = _vertex[0]; + Vector3 hi = lo; + + for (int i = 1; i < 3; ++i) { + lo = lo.min(_vertex[i]); + hi = hi.max(_vertex[i]); + } + + out = AABox(lo, hi); +} + + +bool Triangle::intersect(const Ray& ray, float& distance, float baryCoord[3]) const { + static const float EPS = 1e-5f; + + // See RTR2 ch. 13.7 for the algorithm. + + const Vector3& e1 = edge01(); + const Vector3& e2 = edge02(); + const Vector3 p(ray.direction().cross(e2)); + const float a = e1.dot(p); + + if (abs(a) < EPS) { + // Determinant is ill-conditioned; abort early + return false; + } + + const float f = 1.0f / a; + const Vector3 s(ray.origin() - vertex(0)); + const float u = f * s.dot(p); + + if ((u < 0.0f) || (u > 1.0f)) { + // We hit the plane of the m_geometry, but outside the m_geometry + return false; + } + + const Vector3 q(s.cross(e1)); + const float v = f * ray.direction().dot(q); + + if ((v < 0.0f) || ((u + v) > 1.0f)) { + // We hit the plane of the triangle, but outside the triangle + return false; + } + + const float t = f * e2.dot(q); + + if ((t > 0.0f) && (t < distance)) { + // This is a new hit, closer than the previous one + distance = t; + + baryCoord[0] = 1.0 - u - v; + baryCoord[1] = u; + baryCoord[2] = v; + + return true; + } else { + // This hit is after the previous hit, so ignore it + return false; + } +} + +} // G3D diff --git a/dep/g3dlite/UprightFrame.cpp b/dep/g3dlite/UprightFrame.cpp new file mode 100644 index 00000000000..c80264bf4e8 --- /dev/null +++ b/dep/g3dlite/UprightFrame.cpp @@ -0,0 +1,132 @@ +/** + @file UprightFrame.cpp + Box class + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2007-05-02 + @edited 2007-05-05 +*/ + +#include "G3D/UprightFrame.h" +#include "G3D/BinaryInput.h" +#include "G3D/BinaryOutput.h" + +namespace G3D { + +UprightFrame::UprightFrame(const CoordinateFrame& cframe) { + Vector3 look = cframe.lookVector(); + + yaw = G3D::pi() + atan2(look.x, look.z); + pitch = asin(look.y); + + translation = cframe.translation; +} + + +CoordinateFrame UprightFrame::toCoordinateFrame() const { + CoordinateFrame cframe; + + Matrix3 P(Matrix3::fromAxisAngle(Vector3::unitX(), pitch)); + Matrix3 Y(Matrix3::fromAxisAngle(Vector3::unitY(), yaw)); + + cframe.rotation = Y * P; + cframe.translation = translation; + + return cframe; +} + + +UprightFrame UprightFrame::operator+(const UprightFrame& other) const { + return UprightFrame(translation + other.translation, pitch + other.pitch, yaw + other.yaw); +} + + +UprightFrame UprightFrame::operator*(const float k) const { + return UprightFrame(translation * k, pitch * k, yaw * k); +} + + +void UprightFrame::unwrapYaw(UprightFrame* a, int N) { + // Use the first point to establish the wrapping convention + for (int i = 1; i < N; ++i) { + const float prev = a[i - 1].yaw; + float& cur = a[i].yaw; + + // No two angles should be more than pi (i.e., 180-degrees) apart. + if (abs(cur - prev) > G3D::pi()) { + // These angles must have wrapped at zero, causing them + // to be interpolated the long way. + + // Find canonical [0, 2pi] versions of these numbers + float p = wrap(prev, twoPi()); + float c = wrap(cur, twoPi()); + + // Find the difference -pi < diff < pi between the current and previous values + float diff = c - p; + if (diff < -G3D::pi()) { + diff += twoPi(); + } else if (diff > G3D::pi()) { + diff -= twoPi(); + } + + // Offset the current from the previous by the difference + // between them. + cur = prev + diff; + } + } +} + + +void UprightFrame::serialize(class BinaryOutput& b) const { + translation.serialize(b); + b.writeFloat32(pitch); + b.writeFloat32(yaw); +} + + +void UprightFrame::deserialize(class BinaryInput& b) { + translation.deserialize(b); + pitch = b.readFloat32(); + yaw = b.readFloat32(); +} + + +void UprightSpline::serialize(class BinaryOutput& b) const { + b.writeBool8(cyclic); + + b.writeInt32(control.size()); + for (int i = 0; i < control.size(); ++i) { + control[i].serialize(b); + } + b.writeInt32(time.size()); + for (int i = 0; i < time.size(); ++i) { + b.writeFloat32(time[i]); + } +} + + +void UprightSpline::deserialize(class BinaryInput& b) { + cyclic = b.readBool8(); + + control.resize(b.readInt32()); + for (int i = 0; i < control.size(); ++i) { + control[i].deserialize(b); + } + + if (b.hasMore()) { + time.resize(b.readInt32()); + for (int i = 0; i < time.size(); ++i) { + time[i] = b.readFloat32(); + } + debugAssert(time.size() == control.size()); + } else { + // Import legacy path + time.resize(control.size()); + for (int i = 0; i < time.size(); ++i) { + time[i] = i; + } + } +} + +} diff --git a/dep/g3dlite/Vector2.cpp b/dep/g3dlite/Vector2.cpp new file mode 100644 index 00000000000..ec0737c3755 --- /dev/null +++ b/dep/g3dlite/Vector2.cpp @@ -0,0 +1,224 @@ +/** + @file Vector2.cpp + + 2D vector class, used for texture coordinates primarily. + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @cite Portions based on Dave Eberly'x Magic Software Library + at http://www.magic-software.com + + @created 2001-06-02 + @edited 2009-11-16 + */ + +#include "G3D/platform.h" +#include +#include "G3D/Vector2.h" +#include "G3D/g3dmath.h" +#include "G3D/format.h" +#include "G3D/BinaryInput.h" +#include "G3D/BinaryOutput.h" +#include "G3D/TextInput.h" +#include "G3D/TextOutput.h" +#include "G3D/Any.h" + +namespace G3D { + + +Vector2::Vector2(const Any& any) { + any.verifyName("Vector2"); + any.verifyType(Any::TABLE, Any::ARRAY); + any.verifySize(2); + + if (any.type() == Any::ARRAY) { + x = any[0]; + y = any[1]; + } else { + // Table + x = any["x"]; + y = any["y"]; + } +} + + +Vector2::operator Any() const { + Any any(Any::ARRAY, "Vector2"); + any.append(x, y); + return any; +} + + +const Vector2& Vector2::one() { + static const Vector2 v(1, 1); return v; +} + + +const Vector2& Vector2::zero() { + static Vector2 v(0, 0); + return v; +} + +const Vector2& Vector2::unitX() { + static Vector2 v(1, 0); + return v; +} + +const Vector2& Vector2::unitY() { + static Vector2 v(0, 1); + return v; +} + +const Vector2& Vector2::inf() { + static Vector2 v((float)G3D::finf(), (float)G3D::finf()); + return v; +} + + +const Vector2& Vector2::nan() { + static Vector2 v((float)G3D::fnan(), (float)G3D::fnan()); + return v; +} + + +const Vector2& Vector2::minFinite() { + static Vector2 v(-FLT_MAX, -FLT_MAX); + return v; +} + + +const Vector2& Vector2::maxFinite() { + static Vector2 v(FLT_MAX, FLT_MAX); + return v; +} + + +size_t Vector2::hashCode() const { + unsigned int xhash = (*(int*)(void*)(&x)); + unsigned int yhash = (*(int*)(void*)(&y)); + + return xhash + (yhash * 37); +} + + +Vector2::Vector2(BinaryInput& b) { + deserialize(b); +} + + +void Vector2::deserialize(BinaryInput& b) { + x = b.readFloat32(); + y = b.readFloat32(); +} + + +void Vector2::serialize(BinaryOutput& b) const { + b.writeFloat32(x); + b.writeFloat32(y); +} + + +void Vector2::deserialize(TextInput& t) { + t.readSymbol("("); + x = (float)t.readNumber(); + t.readSymbol(","); + y = (float)t.readNumber(); + t.readSymbol(")"); +} + + +void Vector2::serialize(TextOutput& t) const { + t.writeSymbol("("); + t.writeNumber(x); + t.writeSymbol(","); + t.writeNumber(y); + t.writeSymbol(")"); +} + +//---------------------------------------------------------------------------- + +Vector2 Vector2::random(G3D::Random& r) { + Vector2 result; + + do { + result = Vector2(r.uniform(-1, 1), r.uniform(-1, 1)); + + } while (result.squaredLength() >= 1.0f); + + result.unitize(); + + return result; +} + + +Vector2 Vector2::operator/ (float k) const { + return *this * (1.0f / k); +} + +Vector2& Vector2::operator/= (float k) { + this->x /= k; + this->y /= k; + return *this; +} + +//---------------------------------------------------------------------------- +float Vector2::unitize (float fTolerance) { + float fLength = length(); + + if (fLength > fTolerance) { + float fInvLength = 1.0f / fLength; + x *= fInvLength; + y *= fInvLength; + } else { + fLength = 0.0; + } + + return fLength; +} + +//---------------------------------------------------------------------------- + +std::string Vector2::toString() const { + return G3D::format("(%g, %g)", x, y); +} + +// 2-char swizzles + +Vector2 Vector2::xx() const { return Vector2 (x, x); } +Vector2 Vector2::yx() const { return Vector2 (y, x); } +Vector2 Vector2::xy() const { return Vector2 (x, y); } +Vector2 Vector2::yy() const { return Vector2 (y, y); } + +// 3-char swizzles + +Vector3 Vector2::xxx() const { return Vector3 (x, x, x); } +Vector3 Vector2::yxx() const { return Vector3 (y, x, x); } +Vector3 Vector2::xyx() const { return Vector3 (x, y, x); } +Vector3 Vector2::yyx() const { return Vector3 (y, y, x); } +Vector3 Vector2::xxy() const { return Vector3 (x, x, y); } +Vector3 Vector2::yxy() const { return Vector3 (y, x, y); } +Vector3 Vector2::xyy() const { return Vector3 (x, y, y); } +Vector3 Vector2::yyy() const { return Vector3 (y, y, y); } + +// 4-char swizzles + +Vector4 Vector2::xxxx() const { return Vector4 (x, x, x, x); } +Vector4 Vector2::yxxx() const { return Vector4 (y, x, x, x); } +Vector4 Vector2::xyxx() const { return Vector4 (x, y, x, x); } +Vector4 Vector2::yyxx() const { return Vector4 (y, y, x, x); } +Vector4 Vector2::xxyx() const { return Vector4 (x, x, y, x); } +Vector4 Vector2::yxyx() const { return Vector4 (y, x, y, x); } +Vector4 Vector2::xyyx() const { return Vector4 (x, y, y, x); } +Vector4 Vector2::yyyx() const { return Vector4 (y, y, y, x); } +Vector4 Vector2::xxxy() const { return Vector4 (x, x, x, y); } +Vector4 Vector2::yxxy() const { return Vector4 (y, x, x, y); } +Vector4 Vector2::xyxy() const { return Vector4 (x, y, x, y); } +Vector4 Vector2::yyxy() const { return Vector4 (y, y, x, y); } +Vector4 Vector2::xxyy() const { return Vector4 (x, x, y, y); } +Vector4 Vector2::yxyy() const { return Vector4 (y, x, y, y); } +Vector4 Vector2::xyyy() const { return Vector4 (x, y, y, y); } +Vector4 Vector2::yyyy() const { return Vector4 (y, y, y, y); } + + + +} // namespace diff --git a/dep/g3dlite/Vector3.cpp b/dep/g3dlite/Vector3.cpp new file mode 100644 index 00000000000..a53fa8269b7 --- /dev/null +++ b/dep/g3dlite/Vector3.cpp @@ -0,0 +1,507 @@ +/** + @file Vector3.cpp + + 3D vector class + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @cite Portions based on Dave Eberly's Magic Software Library at http://www.magic-software.com + + @created 2001-06-02 + @edited 2009-11-27 + */ + +#include +#include +#include "G3D/Vector3.h" +#include "G3D/g3dmath.h" +#include "G3D/stringutils.h" +#include "G3D/BinaryInput.h" +#include "G3D/BinaryOutput.h" +#include "G3D/TextInput.h" +#include "G3D/TextOutput.h" +#include "G3D/Vector3int16.h" +#include "G3D/Matrix3.h" +#include "G3D/Vector2.h" +#include "G3D/Color3.h" +#include "G3D/Vector4int8.h" +#include "G3D/Vector3int32.h" +#include "G3D/Any.h" + +namespace G3D { + +Vector3::Vector3(const Any& any) { + any.verifyName("Vector3"); + any.verifyType(Any::TABLE, Any::ARRAY); + any.verifySize(3); + + if (any.type() == Any::ARRAY) { + x = any[0]; + y = any[1]; + z = any[2]; + } else { + // Table + x = any["x"]; + y = any["y"]; + z = any["z"]; + } +} + +Vector3::operator Any() const { + Any any(Any::ARRAY, "Vector3"); + any.append(x, y, z); + return any; +} + +Vector3::Vector3(const class Color3& v) : x(v.r), y(v.g), z(v.b) {} + +Vector3::Vector3(const class Vector3int32& v) : x((float)v.x), y((float)v.y), z((float)v.z) {} + +Vector3::Vector3(const Vector4int8& v) : x(v.x / 127.0f), y(v.y / 127.0f), z(v.z / 127.0f) {} + +Vector3::Vector3(const class Vector2& v, float _z) : x(v.x), y(v.y), z(_z) { +} + +Vector3& Vector3::ignore() { + static Vector3 v; + return v; +} + +const Vector3& Vector3::zero() { static const Vector3 v(0, 0, 0); return v; } +const Vector3& Vector3::one() { static const Vector3 v(1, 1, 1); return v; } +const Vector3& Vector3::unitX() { static const Vector3 v(1, 0, 0); return v; } +const Vector3& Vector3::unitY() { static const Vector3 v(0, 1, 0); return v; } +const Vector3& Vector3::unitZ() { static const Vector3 v(0, 0, 1); return v; } +const Vector3& Vector3::inf() { static const Vector3 v((float)G3D::finf(), (float)G3D::finf(), (float)G3D::finf()); return v; } +const Vector3& Vector3::nan() { static const Vector3 v((float)G3D::fnan(), (float)G3D::fnan(), (float)G3D::fnan()); return v; } +const Vector3& Vector3::minFinite(){ static const Vector3 v(-FLT_MAX, -FLT_MAX, -FLT_MAX); return v; } +const Vector3& Vector3::maxFinite(){ static const Vector3 v(FLT_MAX, FLT_MAX, FLT_MAX); return v; } + +Vector3::Axis Vector3::primaryAxis() const { + + Axis a = X_AXIS; + + double nx = abs(x); + double ny = abs(y); + double nz = abs(z); + + if (nx > ny) { + if (nx > nz) { + a = X_AXIS; + } else { + a = Z_AXIS; + } + } else { + if (ny > nz) { + a = Y_AXIS; + } else { + a = Z_AXIS; + } + } + + return a; +} + + +size_t Vector3::hashCode() const { + unsigned int xhash = (*(int*)(void*)(&x)); + unsigned int yhash = (*(int*)(void*)(&y)); + unsigned int zhash = (*(int*)(void*)(&z)); + + return xhash + (yhash * 37) + (zhash * 101); +} + +std::ostream& operator<<(std::ostream& os, const Vector3& v) { + return os << v.toString(); +} + + +//---------------------------------------------------------------------------- + +double frand() { + return rand() / (double) RAND_MAX; +} + +Vector3::Vector3(TextInput& t) { + deserialize(t); +} + +Vector3::Vector3(BinaryInput& b) { + deserialize(b); +} + + +Vector3::Vector3(const class Vector3int16& v) { + x = v.x; + y = v.y; + z = v.z; +} + + +void Vector3::deserialize(BinaryInput& b) { + x = b.readFloat32(); + y = b.readFloat32(); + z = b.readFloat32(); +} + + +void Vector3::deserialize(TextInput& t) { + t.readSymbol("("); + x = (float)t.readNumber(); + t.readSymbol(","); + y = (float)t.readNumber(); + t.readSymbol(","); + z = (float)t.readNumber(); + t.readSymbol(")"); +} + + +void Vector3::serialize(TextOutput& t) const { + t.writeSymbol("("); + t.writeNumber(x); + t.writeSymbol(","); + t.writeNumber(y); + t.writeSymbol(","); + t.writeNumber(z); + t.writeSymbol(")"); +} + + +void Vector3::serialize(BinaryOutput& b) const { + b.writeFloat32(x); + b.writeFloat32(y); + b.writeFloat32(z); +} + + +Vector3 Vector3::random(Random& r) { + Vector3 result; + r.sphere(result.x, result.y, result.z); + return result; +} + + +float Vector3::unitize(float fTolerance) { + float fMagnitude = magnitude(); + + if (fMagnitude > fTolerance) { + float fInvMagnitude = 1.0f / fMagnitude; + x *= fInvMagnitude; + y *= fInvMagnitude; + z *= fInvMagnitude; + } else { + fMagnitude = 0.0f; + } + + return fMagnitude; +} + + +Vector3 Vector3::reflectAbout(const Vector3& normal) const { + Vector3 out; + + Vector3 N = normal.direction(); + + // 2 * normal.dot(this) * normal - this + return N * 2 * this->dot(N) - *this; +} + + +Vector3 Vector3::cosHemiRandom(const Vector3& normal, Random& r) { + debugAssertM(G3D::fuzzyEq(normal.length(), 1.0f), + "cosHemiRandom requires its argument to have unit length"); + + float x, y, z; + r.cosHemi(x, y, z); + + // Make a coordinate system + const Vector3& Z = normal; + + Vector3 X, Y; + normal.getTangents(X, Y); + + return + x * X + + y * Y + + z * Z; +} + + +Vector3 Vector3::cosPowHemiRandom(const Vector3& normal, const float k, Random& r) { + debugAssertM(G3D::fuzzyEq(normal.length(), 1.0f), + "cosPowHemiRandom requires its argument to have unit length"); + + float x, y, z; + r.cosPowHemi(k, x, y, z); + + // Make a coordinate system + const Vector3& Z = normal; + + Vector3 X, Y; + normal.getTangents(X, Y); + + return + x * X + + y * Y + + z * Z; +} + + +Vector3 Vector3::hemiRandom(const Vector3& normal, Random& r) { + const Vector3& V = Vector3::random(r); + + if (V.dot(normal) < 0) { + return -V; + } else { + return V; + } +} + +//---------------------------------------------------------------------------- + +Vector3 Vector3::reflectionDirection(const Vector3& normal) const { + return -reflectAbout(normal).direction(); +} + +//---------------------------------------------------------------------------- + +Vector3 Vector3::refractionDirection( + const Vector3& normal, + float iInside, + float iOutside) const { + + // From pg. 24 of Henrik Wann Jensen. Realistic Image Synthesis + // Using Photon Mapping. AK Peters. ISBN: 1568811470. July 2001. + + // Invert the directions from Wann Jensen's formulation + // and normalize the vectors. + const Vector3 W = -direction(); + Vector3 N = normal.direction(); + + float h1 = iOutside; + float h2 = iInside; + + if (normal.dot(*this) > 0.0f) { + h1 = iInside; + h2 = iOutside; + N = -N; + } + + const float hRatio = h1 / h2; + const float WdotN = W.dot(N); + + float det = 1.0f - (float)square(hRatio) * (1.0f - (float)square(WdotN)); + + if (det < 0) { + // Total internal reflection + return Vector3::zero(); + } else { + return -hRatio * (W - WdotN * N) - N * sqrt(det); + } +} + +//---------------------------------------------------------------------------- +void Vector3::orthonormalize (Vector3 akVector[3]) { + // If the input vectors are v0, v1, and v2, then the Gram-Schmidt + // orthonormalization produces vectors u0, u1, and u2 as follows, + // + // u0 = v0/|v0| + // u1 = (v1-(u0*v1)u0)/|v1-(u0*v1)u0| + // u2 = (v2-(u0*v2)u0-(u1*v2)u1)/|v2-(u0*v2)u0-(u1*v2)u1| + // + // where |A| indicates length of vector A and A*B indicates dot + // product of vectors A and B. + + // compute u0 + akVector[0].unitize(); + + // compute u1 + float fDot0 = akVector[0].dot(akVector[1]); + akVector[1] -= akVector[0] * fDot0; + akVector[1].unitize(); + + // compute u2 + float fDot1 = akVector[1].dot(akVector[2]); + fDot0 = akVector[0].dot(akVector[2]); + akVector[2] -= akVector[0] * fDot0 + akVector[1] * fDot1; + akVector[2].unitize(); +} + +//---------------------------------------------------------------------------- +void Vector3::generateOrthonormalBasis (Vector3& rkU, Vector3& rkV, + Vector3& rkW, bool bUnitLengthW) { + if ( !bUnitLengthW ) + rkW.unitize(); + + if ( G3D::abs(rkW.x) >= G3D::abs(rkW.y) + && G3D::abs(rkW.x) >= G3D::abs(rkW.z) ) { + rkU.x = -rkW.y; + rkU.y = + rkW.x; + rkU.z = 0.0; + } else { + rkU.x = 0.0; + rkU.y = + rkW.z; + rkU.z = -rkW.y; + } + + rkU.unitize(); + rkV = rkW.cross(rkU); +} + +//---------------------------------------------------------------------------- + +std::string Vector3::toString() const { + return G3D::format("(%g, %g, %g)", x, y, z); +} + + +//---------------------------------------------------------------------------- + +Matrix3 Vector3::cross() const { + return Matrix3( 0, -z, y, + z, 0, -x, + -y, x, 0); +} + + +void serialize(const Vector3::Axis& a, class BinaryOutput& bo) { + bo.writeUInt8((uint8)a); +} + +void deserialize(Vector3::Axis& a, class BinaryInput& bi) { + a = (Vector3::Axis)bi.readUInt8(); +} + +//---------------------------------------------------------------------------- +// 2-char swizzles + +Vector2 Vector3::xx() const { return Vector2 (x, x); } +Vector2 Vector3::yx() const { return Vector2 (y, x); } +Vector2 Vector3::zx() const { return Vector2 (z, x); } +Vector2 Vector3::xy() const { return Vector2 (x, y); } +Vector2 Vector3::yy() const { return Vector2 (y, y); } +Vector2 Vector3::zy() const { return Vector2 (z, y); } +Vector2 Vector3::xz() const { return Vector2 (x, z); } +Vector2 Vector3::yz() const { return Vector2 (y, z); } +Vector2 Vector3::zz() const { return Vector2 (z, z); } + +// 3-char swizzles + +Vector3 Vector3::xxx() const { return Vector3 (x, x, x); } +Vector3 Vector3::yxx() const { return Vector3 (y, x, x); } +Vector3 Vector3::zxx() const { return Vector3 (z, x, x); } +Vector3 Vector3::xyx() const { return Vector3 (x, y, x); } +Vector3 Vector3::yyx() const { return Vector3 (y, y, x); } +Vector3 Vector3::zyx() const { return Vector3 (z, y, x); } +Vector3 Vector3::xzx() const { return Vector3 (x, z, x); } +Vector3 Vector3::yzx() const { return Vector3 (y, z, x); } +Vector3 Vector3::zzx() const { return Vector3 (z, z, x); } +Vector3 Vector3::xxy() const { return Vector3 (x, x, y); } +Vector3 Vector3::yxy() const { return Vector3 (y, x, y); } +Vector3 Vector3::zxy() const { return Vector3 (z, x, y); } +Vector3 Vector3::xyy() const { return Vector3 (x, y, y); } +Vector3 Vector3::yyy() const { return Vector3 (y, y, y); } +Vector3 Vector3::zyy() const { return Vector3 (z, y, y); } +Vector3 Vector3::xzy() const { return Vector3 (x, z, y); } +Vector3 Vector3::yzy() const { return Vector3 (y, z, y); } +Vector3 Vector3::zzy() const { return Vector3 (z, z, y); } +Vector3 Vector3::xxz() const { return Vector3 (x, x, z); } +Vector3 Vector3::yxz() const { return Vector3 (y, x, z); } +Vector3 Vector3::zxz() const { return Vector3 (z, x, z); } +Vector3 Vector3::xyz() const { return Vector3 (x, y, z); } +Vector3 Vector3::yyz() const { return Vector3 (y, y, z); } +Vector3 Vector3::zyz() const { return Vector3 (z, y, z); } +Vector3 Vector3::xzz() const { return Vector3 (x, z, z); } +Vector3 Vector3::yzz() const { return Vector3 (y, z, z); } +Vector3 Vector3::zzz() const { return Vector3 (z, z, z); } + +// 4-char swizzles + +Vector4 Vector3::xxxx() const { return Vector4 (x, x, x, x); } +Vector4 Vector3::yxxx() const { return Vector4 (y, x, x, x); } +Vector4 Vector3::zxxx() const { return Vector4 (z, x, x, x); } +Vector4 Vector3::xyxx() const { return Vector4 (x, y, x, x); } +Vector4 Vector3::yyxx() const { return Vector4 (y, y, x, x); } +Vector4 Vector3::zyxx() const { return Vector4 (z, y, x, x); } +Vector4 Vector3::xzxx() const { return Vector4 (x, z, x, x); } +Vector4 Vector3::yzxx() const { return Vector4 (y, z, x, x); } +Vector4 Vector3::zzxx() const { return Vector4 (z, z, x, x); } +Vector4 Vector3::xxyx() const { return Vector4 (x, x, y, x); } +Vector4 Vector3::yxyx() const { return Vector4 (y, x, y, x); } +Vector4 Vector3::zxyx() const { return Vector4 (z, x, y, x); } +Vector4 Vector3::xyyx() const { return Vector4 (x, y, y, x); } +Vector4 Vector3::yyyx() const { return Vector4 (y, y, y, x); } +Vector4 Vector3::zyyx() const { return Vector4 (z, y, y, x); } +Vector4 Vector3::xzyx() const { return Vector4 (x, z, y, x); } +Vector4 Vector3::yzyx() const { return Vector4 (y, z, y, x); } +Vector4 Vector3::zzyx() const { return Vector4 (z, z, y, x); } +Vector4 Vector3::xxzx() const { return Vector4 (x, x, z, x); } +Vector4 Vector3::yxzx() const { return Vector4 (y, x, z, x); } +Vector4 Vector3::zxzx() const { return Vector4 (z, x, z, x); } +Vector4 Vector3::xyzx() const { return Vector4 (x, y, z, x); } +Vector4 Vector3::yyzx() const { return Vector4 (y, y, z, x); } +Vector4 Vector3::zyzx() const { return Vector4 (z, y, z, x); } +Vector4 Vector3::xzzx() const { return Vector4 (x, z, z, x); } +Vector4 Vector3::yzzx() const { return Vector4 (y, z, z, x); } +Vector4 Vector3::zzzx() const { return Vector4 (z, z, z, x); } +Vector4 Vector3::xxxy() const { return Vector4 (x, x, x, y); } +Vector4 Vector3::yxxy() const { return Vector4 (y, x, x, y); } +Vector4 Vector3::zxxy() const { return Vector4 (z, x, x, y); } +Vector4 Vector3::xyxy() const { return Vector4 (x, y, x, y); } +Vector4 Vector3::yyxy() const { return Vector4 (y, y, x, y); } +Vector4 Vector3::zyxy() const { return Vector4 (z, y, x, y); } +Vector4 Vector3::xzxy() const { return Vector4 (x, z, x, y); } +Vector4 Vector3::yzxy() const { return Vector4 (y, z, x, y); } +Vector4 Vector3::zzxy() const { return Vector4 (z, z, x, y); } +Vector4 Vector3::xxyy() const { return Vector4 (x, x, y, y); } +Vector4 Vector3::yxyy() const { return Vector4 (y, x, y, y); } +Vector4 Vector3::zxyy() const { return Vector4 (z, x, y, y); } +Vector4 Vector3::xyyy() const { return Vector4 (x, y, y, y); } +Vector4 Vector3::yyyy() const { return Vector4 (y, y, y, y); } +Vector4 Vector3::zyyy() const { return Vector4 (z, y, y, y); } +Vector4 Vector3::xzyy() const { return Vector4 (x, z, y, y); } +Vector4 Vector3::yzyy() const { return Vector4 (y, z, y, y); } +Vector4 Vector3::zzyy() const { return Vector4 (z, z, y, y); } +Vector4 Vector3::xxzy() const { return Vector4 (x, x, z, y); } +Vector4 Vector3::yxzy() const { return Vector4 (y, x, z, y); } +Vector4 Vector3::zxzy() const { return Vector4 (z, x, z, y); } +Vector4 Vector3::xyzy() const { return Vector4 (x, y, z, y); } +Vector4 Vector3::yyzy() const { return Vector4 (y, y, z, y); } +Vector4 Vector3::zyzy() const { return Vector4 (z, y, z, y); } +Vector4 Vector3::xzzy() const { return Vector4 (x, z, z, y); } +Vector4 Vector3::yzzy() const { return Vector4 (y, z, z, y); } +Vector4 Vector3::zzzy() const { return Vector4 (z, z, z, y); } +Vector4 Vector3::xxxz() const { return Vector4 (x, x, x, z); } +Vector4 Vector3::yxxz() const { return Vector4 (y, x, x, z); } +Vector4 Vector3::zxxz() const { return Vector4 (z, x, x, z); } +Vector4 Vector3::xyxz() const { return Vector4 (x, y, x, z); } +Vector4 Vector3::yyxz() const { return Vector4 (y, y, x, z); } +Vector4 Vector3::zyxz() const { return Vector4 (z, y, x, z); } +Vector4 Vector3::xzxz() const { return Vector4 (x, z, x, z); } +Vector4 Vector3::yzxz() const { return Vector4 (y, z, x, z); } +Vector4 Vector3::zzxz() const { return Vector4 (z, z, x, z); } +Vector4 Vector3::xxyz() const { return Vector4 (x, x, y, z); } +Vector4 Vector3::yxyz() const { return Vector4 (y, x, y, z); } +Vector4 Vector3::zxyz() const { return Vector4 (z, x, y, z); } +Vector4 Vector3::xyyz() const { return Vector4 (x, y, y, z); } +Vector4 Vector3::yyyz() const { return Vector4 (y, y, y, z); } +Vector4 Vector3::zyyz() const { return Vector4 (z, y, y, z); } +Vector4 Vector3::xzyz() const { return Vector4 (x, z, y, z); } +Vector4 Vector3::yzyz() const { return Vector4 (y, z, y, z); } +Vector4 Vector3::zzyz() const { return Vector4 (z, z, y, z); } +Vector4 Vector3::xxzz() const { return Vector4 (x, x, z, z); } +Vector4 Vector3::yxzz() const { return Vector4 (y, x, z, z); } +Vector4 Vector3::zxzz() const { return Vector4 (z, x, z, z); } +Vector4 Vector3::xyzz() const { return Vector4 (x, y, z, z); } +Vector4 Vector3::yyzz() const { return Vector4 (y, y, z, z); } +Vector4 Vector3::zyzz() const { return Vector4 (z, y, z, z); } +Vector4 Vector3::xzzz() const { return Vector4 (x, z, z, z); } +Vector4 Vector3::yzzz() const { return Vector4 (y, z, z, z); } +Vector4 Vector3::zzzz() const { return Vector4 (z, z, z, z); } + + + + + + +} // namespace diff --git a/dep/g3dlite/Vector4.cpp b/dep/g3dlite/Vector4.cpp new file mode 100644 index 00000000000..f6abc1a6e0c --- /dev/null +++ b/dep/g3dlite/Vector4.cpp @@ -0,0 +1,520 @@ +/** + @file Vector4.cpp + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2001-07-09 + @edited 2009-11-29 + */ + +#include +#include +#include "G3D/Vector4.h" +#include "G3D/Color4.h" +#include "G3D/g3dmath.h" +#include "G3D/stringutils.h" +#include "G3D/BinaryInput.h" +#include "G3D/BinaryOutput.h" +#include "G3D/Vector4int8.h" +#include "G3D/Matrix4.h" +#include "G3D/Any.h" + +namespace G3D { + +Vector4::Vector4(const Any& any) { + any.verifyName("Vector4"); + any.verifyType(Any::TABLE, Any::ARRAY); + any.verifySize(4); + + if (any.type() == Any::ARRAY) { + x = any[0]; + y = any[1]; + z = any[2]; + w = any[3]; + } else { + // Table + x = any["x"]; + y = any["y"]; + z = any["z"]; + w = any["w"]; + } +} + +Vector4::operator Any() const { + Any any(Any::ARRAY, "Vector4"); + any.append(x, y, z, w); + return any; +} + + +Vector4::Vector4(const Vector4int8& v) : x(v.x / 127.0f), y(v.y / 127.0f), z(v.z / 127.0f), w(v.w / 127.0f) { +} + + +const Vector4& Vector4::inf() { + static const Vector4 v((float)G3D::finf(), (float)G3D::finf(), (float)G3D::finf(), (float)G3D::finf()); + return v; +} + + +const Vector4& Vector4::zero() { + static const Vector4 v(0,0,0,0); + return v; +} + +const Vector4& Vector4::nan() { + static Vector4 v((float)G3D::fnan(), (float)G3D::fnan(), (float)G3D::fnan(), (float)G3D::fnan()); + return v; +} + + +size_t Vector4::hashCode() const { + unsigned int xhash = (*(int*)(void*)(&x)); + unsigned int yhash = (*(int*)(void*)(&y)); + unsigned int zhash = (*(int*)(void*)(&z)); + unsigned int whash = (*(int*)(void*)(&w)); + + return xhash + (yhash * 37) + (zhash * 101) + (whash * 241); +} + + +Vector4::Vector4(const class Color4& c) { + x = c.r; + y = c.g; + z = c.b; + w = c.a; +} + + +Vector4::Vector4(const Vector2& v1, const Vector2& v2) { + x = v1.x; + y = v1.y; + z = v2.x; + w = v2.y; +} + + +Vector4::Vector4(const Vector2& v1, float fz, float fw) { + x = v1.x; + y = v1.y; + z = fz; + w = fw; +} + +Vector4::Vector4(BinaryInput& b) { + deserialize(b); +} + + +void Vector4::deserialize(BinaryInput& b) { + x = b.readFloat32(); + y = b.readFloat32(); + z = b.readFloat32(); + w = b.readFloat32(); +} + + +void Vector4::serialize(BinaryOutput& b) const { + b.writeFloat32(x); + b.writeFloat32(y); + b.writeFloat32(z); + b.writeFloat32(w); +} + +//---------------------------------------------------------------------------- + +Vector4 Vector4::operator*(const Matrix4& M) const { + Vector4 result; + for (int i = 0; i < 4; ++i) { + result[i] = 0.0f; + for (int j = 0; j < 4; ++j) { + result[i] += (*this)[j] * M[j][i]; + } + } + return result; +} + + +Vector4 Vector4::operator/ (float fScalar) const { + Vector4 kQuot; + + if ( fScalar != 0.0 ) { + float fInvScalar = 1.0f / fScalar; + kQuot.x = fInvScalar * x; + kQuot.y = fInvScalar * y; + kQuot.z = fInvScalar * z; + kQuot.w = fInvScalar * w; + return kQuot; + } else { + return Vector4::inf(); + } +} + +//---------------------------------------------------------------------------- +Vector4& Vector4::operator/= (float fScalar) { + if (fScalar != 0.0f) { + float fInvScalar = 1.0f / fScalar; + x *= fInvScalar; + y *= fInvScalar; + z *= fInvScalar; + w *= fInvScalar; + } else { + *this = Vector4::inf(); + } + + return *this; +} + + +//---------------------------------------------------------------------------- + +std::string Vector4::toString() const { + return G3D::format("(%g, %g, %g, %g)", x, y, z, w); +} +// 2-char swizzles + +Vector2 Vector4::xx() const { return Vector2 (x, x); } +Vector2 Vector4::yx() const { return Vector2 (y, x); } +Vector2 Vector4::zx() const { return Vector2 (z, x); } +Vector2 Vector4::wx() const { return Vector2 (w, x); } +Vector2 Vector4::xy() const { return Vector2 (x, y); } +Vector2 Vector4::yy() const { return Vector2 (y, y); } +Vector2 Vector4::zy() const { return Vector2 (z, y); } +Vector2 Vector4::wy() const { return Vector2 (w, y); } +Vector2 Vector4::xz() const { return Vector2 (x, z); } +Vector2 Vector4::yz() const { return Vector2 (y, z); } +Vector2 Vector4::zz() const { return Vector2 (z, z); } +Vector2 Vector4::wz() const { return Vector2 (w, z); } +Vector2 Vector4::xw() const { return Vector2 (x, w); } +Vector2 Vector4::yw() const { return Vector2 (y, w); } +Vector2 Vector4::zw() const { return Vector2 (z, w); } +Vector2 Vector4::ww() const { return Vector2 (w, w); } + +// 3-char swizzles + +Vector3 Vector4::xxx() const { return Vector3 (x, x, x); } +Vector3 Vector4::yxx() const { return Vector3 (y, x, x); } +Vector3 Vector4::zxx() const { return Vector3 (z, x, x); } +Vector3 Vector4::wxx() const { return Vector3 (w, x, x); } +Vector3 Vector4::xyx() const { return Vector3 (x, y, x); } +Vector3 Vector4::yyx() const { return Vector3 (y, y, x); } +Vector3 Vector4::zyx() const { return Vector3 (z, y, x); } +Vector3 Vector4::wyx() const { return Vector3 (w, y, x); } +Vector3 Vector4::xzx() const { return Vector3 (x, z, x); } +Vector3 Vector4::yzx() const { return Vector3 (y, z, x); } +Vector3 Vector4::zzx() const { return Vector3 (z, z, x); } +Vector3 Vector4::wzx() const { return Vector3 (w, z, x); } +Vector3 Vector4::xwx() const { return Vector3 (x, w, x); } +Vector3 Vector4::ywx() const { return Vector3 (y, w, x); } +Vector3 Vector4::zwx() const { return Vector3 (z, w, x); } +Vector3 Vector4::wwx() const { return Vector3 (w, w, x); } +Vector3 Vector4::xxy() const { return Vector3 (x, x, y); } +Vector3 Vector4::yxy() const { return Vector3 (y, x, y); } +Vector3 Vector4::zxy() const { return Vector3 (z, x, y); } +Vector3 Vector4::wxy() const { return Vector3 (w, x, y); } +Vector3 Vector4::xyy() const { return Vector3 (x, y, y); } +Vector3 Vector4::yyy() const { return Vector3 (y, y, y); } +Vector3 Vector4::zyy() const { return Vector3 (z, y, y); } +Vector3 Vector4::wyy() const { return Vector3 (w, y, y); } +Vector3 Vector4::xzy() const { return Vector3 (x, z, y); } +Vector3 Vector4::yzy() const { return Vector3 (y, z, y); } +Vector3 Vector4::zzy() const { return Vector3 (z, z, y); } +Vector3 Vector4::wzy() const { return Vector3 (w, z, y); } +Vector3 Vector4::xwy() const { return Vector3 (x, w, y); } +Vector3 Vector4::ywy() const { return Vector3 (y, w, y); } +Vector3 Vector4::zwy() const { return Vector3 (z, w, y); } +Vector3 Vector4::wwy() const { return Vector3 (w, w, y); } +Vector3 Vector4::xxz() const { return Vector3 (x, x, z); } +Vector3 Vector4::yxz() const { return Vector3 (y, x, z); } +Vector3 Vector4::zxz() const { return Vector3 (z, x, z); } +Vector3 Vector4::wxz() const { return Vector3 (w, x, z); } +Vector3 Vector4::xyz() const { return Vector3 (x, y, z); } +Vector3 Vector4::yyz() const { return Vector3 (y, y, z); } +Vector3 Vector4::zyz() const { return Vector3 (z, y, z); } +Vector3 Vector4::wyz() const { return Vector3 (w, y, z); } +Vector3 Vector4::xzz() const { return Vector3 (x, z, z); } +Vector3 Vector4::yzz() const { return Vector3 (y, z, z); } +Vector3 Vector4::zzz() const { return Vector3 (z, z, z); } +Vector3 Vector4::wzz() const { return Vector3 (w, z, z); } +Vector3 Vector4::xwz() const { return Vector3 (x, w, z); } +Vector3 Vector4::ywz() const { return Vector3 (y, w, z); } +Vector3 Vector4::zwz() const { return Vector3 (z, w, z); } +Vector3 Vector4::wwz() const { return Vector3 (w, w, z); } +Vector3 Vector4::xxw() const { return Vector3 (x, x, w); } +Vector3 Vector4::yxw() const { return Vector3 (y, x, w); } +Vector3 Vector4::zxw() const { return Vector3 (z, x, w); } +Vector3 Vector4::wxw() const { return Vector3 (w, x, w); } +Vector3 Vector4::xyw() const { return Vector3 (x, y, w); } +Vector3 Vector4::yyw() const { return Vector3 (y, y, w); } +Vector3 Vector4::zyw() const { return Vector3 (z, y, w); } +Vector3 Vector4::wyw() const { return Vector3 (w, y, w); } +Vector3 Vector4::xzw() const { return Vector3 (x, z, w); } +Vector3 Vector4::yzw() const { return Vector3 (y, z, w); } +Vector3 Vector4::zzw() const { return Vector3 (z, z, w); } +Vector3 Vector4::wzw() const { return Vector3 (w, z, w); } +Vector3 Vector4::xww() const { return Vector3 (x, w, w); } +Vector3 Vector4::yww() const { return Vector3 (y, w, w); } +Vector3 Vector4::zww() const { return Vector3 (z, w, w); } +Vector3 Vector4::www() const { return Vector3 (w, w, w); } + +// 4-char swizzles + +Vector4 Vector4::xxxx() const { return Vector4 (x, x, x, x); } +Vector4 Vector4::yxxx() const { return Vector4 (y, x, x, x); } +Vector4 Vector4::zxxx() const { return Vector4 (z, x, x, x); } +Vector4 Vector4::wxxx() const { return Vector4 (w, x, x, x); } +Vector4 Vector4::xyxx() const { return Vector4 (x, y, x, x); } +Vector4 Vector4::yyxx() const { return Vector4 (y, y, x, x); } +Vector4 Vector4::zyxx() const { return Vector4 (z, y, x, x); } +Vector4 Vector4::wyxx() const { return Vector4 (w, y, x, x); } +Vector4 Vector4::xzxx() const { return Vector4 (x, z, x, x); } +Vector4 Vector4::yzxx() const { return Vector4 (y, z, x, x); } +Vector4 Vector4::zzxx() const { return Vector4 (z, z, x, x); } +Vector4 Vector4::wzxx() const { return Vector4 (w, z, x, x); } +Vector4 Vector4::xwxx() const { return Vector4 (x, w, x, x); } +Vector4 Vector4::ywxx() const { return Vector4 (y, w, x, x); } +Vector4 Vector4::zwxx() const { return Vector4 (z, w, x, x); } +Vector4 Vector4::wwxx() const { return Vector4 (w, w, x, x); } +Vector4 Vector4::xxyx() const { return Vector4 (x, x, y, x); } +Vector4 Vector4::yxyx() const { return Vector4 (y, x, y, x); } +Vector4 Vector4::zxyx() const { return Vector4 (z, x, y, x); } +Vector4 Vector4::wxyx() const { return Vector4 (w, x, y, x); } +Vector4 Vector4::xyyx() const { return Vector4 (x, y, y, x); } +Vector4 Vector4::yyyx() const { return Vector4 (y, y, y, x); } +Vector4 Vector4::zyyx() const { return Vector4 (z, y, y, x); } +Vector4 Vector4::wyyx() const { return Vector4 (w, y, y, x); } +Vector4 Vector4::xzyx() const { return Vector4 (x, z, y, x); } +Vector4 Vector4::yzyx() const { return Vector4 (y, z, y, x); } +Vector4 Vector4::zzyx() const { return Vector4 (z, z, y, x); } +Vector4 Vector4::wzyx() const { return Vector4 (w, z, y, x); } +Vector4 Vector4::xwyx() const { return Vector4 (x, w, y, x); } +Vector4 Vector4::ywyx() const { return Vector4 (y, w, y, x); } +Vector4 Vector4::zwyx() const { return Vector4 (z, w, y, x); } +Vector4 Vector4::wwyx() const { return Vector4 (w, w, y, x); } +Vector4 Vector4::xxzx() const { return Vector4 (x, x, z, x); } +Vector4 Vector4::yxzx() const { return Vector4 (y, x, z, x); } +Vector4 Vector4::zxzx() const { return Vector4 (z, x, z, x); } +Vector4 Vector4::wxzx() const { return Vector4 (w, x, z, x); } +Vector4 Vector4::xyzx() const { return Vector4 (x, y, z, x); } +Vector4 Vector4::yyzx() const { return Vector4 (y, y, z, x); } +Vector4 Vector4::zyzx() const { return Vector4 (z, y, z, x); } +Vector4 Vector4::wyzx() const { return Vector4 (w, y, z, x); } +Vector4 Vector4::xzzx() const { return Vector4 (x, z, z, x); } +Vector4 Vector4::yzzx() const { return Vector4 (y, z, z, x); } +Vector4 Vector4::zzzx() const { return Vector4 (z, z, z, x); } +Vector4 Vector4::wzzx() const { return Vector4 (w, z, z, x); } +Vector4 Vector4::xwzx() const { return Vector4 (x, w, z, x); } +Vector4 Vector4::ywzx() const { return Vector4 (y, w, z, x); } +Vector4 Vector4::zwzx() const { return Vector4 (z, w, z, x); } +Vector4 Vector4::wwzx() const { return Vector4 (w, w, z, x); } +Vector4 Vector4::xxwx() const { return Vector4 (x, x, w, x); } +Vector4 Vector4::yxwx() const { return Vector4 (y, x, w, x); } +Vector4 Vector4::zxwx() const { return Vector4 (z, x, w, x); } +Vector4 Vector4::wxwx() const { return Vector4 (w, x, w, x); } +Vector4 Vector4::xywx() const { return Vector4 (x, y, w, x); } +Vector4 Vector4::yywx() const { return Vector4 (y, y, w, x); } +Vector4 Vector4::zywx() const { return Vector4 (z, y, w, x); } +Vector4 Vector4::wywx() const { return Vector4 (w, y, w, x); } +Vector4 Vector4::xzwx() const { return Vector4 (x, z, w, x); } +Vector4 Vector4::yzwx() const { return Vector4 (y, z, w, x); } +Vector4 Vector4::zzwx() const { return Vector4 (z, z, w, x); } +Vector4 Vector4::wzwx() const { return Vector4 (w, z, w, x); } +Vector4 Vector4::xwwx() const { return Vector4 (x, w, w, x); } +Vector4 Vector4::ywwx() const { return Vector4 (y, w, w, x); } +Vector4 Vector4::zwwx() const { return Vector4 (z, w, w, x); } +Vector4 Vector4::wwwx() const { return Vector4 (w, w, w, x); } +Vector4 Vector4::xxxy() const { return Vector4 (x, x, x, y); } +Vector4 Vector4::yxxy() const { return Vector4 (y, x, x, y); } +Vector4 Vector4::zxxy() const { return Vector4 (z, x, x, y); } +Vector4 Vector4::wxxy() const { return Vector4 (w, x, x, y); } +Vector4 Vector4::xyxy() const { return Vector4 (x, y, x, y); } +Vector4 Vector4::yyxy() const { return Vector4 (y, y, x, y); } +Vector4 Vector4::zyxy() const { return Vector4 (z, y, x, y); } +Vector4 Vector4::wyxy() const { return Vector4 (w, y, x, y); } +Vector4 Vector4::xzxy() const { return Vector4 (x, z, x, y); } +Vector4 Vector4::yzxy() const { return Vector4 (y, z, x, y); } +Vector4 Vector4::zzxy() const { return Vector4 (z, z, x, y); } +Vector4 Vector4::wzxy() const { return Vector4 (w, z, x, y); } +Vector4 Vector4::xwxy() const { return Vector4 (x, w, x, y); } +Vector4 Vector4::ywxy() const { return Vector4 (y, w, x, y); } +Vector4 Vector4::zwxy() const { return Vector4 (z, w, x, y); } +Vector4 Vector4::wwxy() const { return Vector4 (w, w, x, y); } +Vector4 Vector4::xxyy() const { return Vector4 (x, x, y, y); } +Vector4 Vector4::yxyy() const { return Vector4 (y, x, y, y); } +Vector4 Vector4::zxyy() const { return Vector4 (z, x, y, y); } +Vector4 Vector4::wxyy() const { return Vector4 (w, x, y, y); } +Vector4 Vector4::xyyy() const { return Vector4 (x, y, y, y); } +Vector4 Vector4::yyyy() const { return Vector4 (y, y, y, y); } +Vector4 Vector4::zyyy() const { return Vector4 (z, y, y, y); } +Vector4 Vector4::wyyy() const { return Vector4 (w, y, y, y); } +Vector4 Vector4::xzyy() const { return Vector4 (x, z, y, y); } +Vector4 Vector4::yzyy() const { return Vector4 (y, z, y, y); } +Vector4 Vector4::zzyy() const { return Vector4 (z, z, y, y); } +Vector4 Vector4::wzyy() const { return Vector4 (w, z, y, y); } +Vector4 Vector4::xwyy() const { return Vector4 (x, w, y, y); } +Vector4 Vector4::ywyy() const { return Vector4 (y, w, y, y); } +Vector4 Vector4::zwyy() const { return Vector4 (z, w, y, y); } +Vector4 Vector4::wwyy() const { return Vector4 (w, w, y, y); } +Vector4 Vector4::xxzy() const { return Vector4 (x, x, z, y); } +Vector4 Vector4::yxzy() const { return Vector4 (y, x, z, y); } +Vector4 Vector4::zxzy() const { return Vector4 (z, x, z, y); } +Vector4 Vector4::wxzy() const { return Vector4 (w, x, z, y); } +Vector4 Vector4::xyzy() const { return Vector4 (x, y, z, y); } +Vector4 Vector4::yyzy() const { return Vector4 (y, y, z, y); } +Vector4 Vector4::zyzy() const { return Vector4 (z, y, z, y); } +Vector4 Vector4::wyzy() const { return Vector4 (w, y, z, y); } +Vector4 Vector4::xzzy() const { return Vector4 (x, z, z, y); } +Vector4 Vector4::yzzy() const { return Vector4 (y, z, z, y); } +Vector4 Vector4::zzzy() const { return Vector4 (z, z, z, y); } +Vector4 Vector4::wzzy() const { return Vector4 (w, z, z, y); } +Vector4 Vector4::xwzy() const { return Vector4 (x, w, z, y); } +Vector4 Vector4::ywzy() const { return Vector4 (y, w, z, y); } +Vector4 Vector4::zwzy() const { return Vector4 (z, w, z, y); } +Vector4 Vector4::wwzy() const { return Vector4 (w, w, z, y); } +Vector4 Vector4::xxwy() const { return Vector4 (x, x, w, y); } +Vector4 Vector4::yxwy() const { return Vector4 (y, x, w, y); } +Vector4 Vector4::zxwy() const { return Vector4 (z, x, w, y); } +Vector4 Vector4::wxwy() const { return Vector4 (w, x, w, y); } +Vector4 Vector4::xywy() const { return Vector4 (x, y, w, y); } +Vector4 Vector4::yywy() const { return Vector4 (y, y, w, y); } +Vector4 Vector4::zywy() const { return Vector4 (z, y, w, y); } +Vector4 Vector4::wywy() const { return Vector4 (w, y, w, y); } +Vector4 Vector4::xzwy() const { return Vector4 (x, z, w, y); } +Vector4 Vector4::yzwy() const { return Vector4 (y, z, w, y); } +Vector4 Vector4::zzwy() const { return Vector4 (z, z, w, y); } +Vector4 Vector4::wzwy() const { return Vector4 (w, z, w, y); } +Vector4 Vector4::xwwy() const { return Vector4 (x, w, w, y); } +Vector4 Vector4::ywwy() const { return Vector4 (y, w, w, y); } +Vector4 Vector4::zwwy() const { return Vector4 (z, w, w, y); } +Vector4 Vector4::wwwy() const { return Vector4 (w, w, w, y); } +Vector4 Vector4::xxxz() const { return Vector4 (x, x, x, z); } +Vector4 Vector4::yxxz() const { return Vector4 (y, x, x, z); } +Vector4 Vector4::zxxz() const { return Vector4 (z, x, x, z); } +Vector4 Vector4::wxxz() const { return Vector4 (w, x, x, z); } +Vector4 Vector4::xyxz() const { return Vector4 (x, y, x, z); } +Vector4 Vector4::yyxz() const { return Vector4 (y, y, x, z); } +Vector4 Vector4::zyxz() const { return Vector4 (z, y, x, z); } +Vector4 Vector4::wyxz() const { return Vector4 (w, y, x, z); } +Vector4 Vector4::xzxz() const { return Vector4 (x, z, x, z); } +Vector4 Vector4::yzxz() const { return Vector4 (y, z, x, z); } +Vector4 Vector4::zzxz() const { return Vector4 (z, z, x, z); } +Vector4 Vector4::wzxz() const { return Vector4 (w, z, x, z); } +Vector4 Vector4::xwxz() const { return Vector4 (x, w, x, z); } +Vector4 Vector4::ywxz() const { return Vector4 (y, w, x, z); } +Vector4 Vector4::zwxz() const { return Vector4 (z, w, x, z); } +Vector4 Vector4::wwxz() const { return Vector4 (w, w, x, z); } +Vector4 Vector4::xxyz() const { return Vector4 (x, x, y, z); } +Vector4 Vector4::yxyz() const { return Vector4 (y, x, y, z); } +Vector4 Vector4::zxyz() const { return Vector4 (z, x, y, z); } +Vector4 Vector4::wxyz() const { return Vector4 (w, x, y, z); } +Vector4 Vector4::xyyz() const { return Vector4 (x, y, y, z); } +Vector4 Vector4::yyyz() const { return Vector4 (y, y, y, z); } +Vector4 Vector4::zyyz() const { return Vector4 (z, y, y, z); } +Vector4 Vector4::wyyz() const { return Vector4 (w, y, y, z); } +Vector4 Vector4::xzyz() const { return Vector4 (x, z, y, z); } +Vector4 Vector4::yzyz() const { return Vector4 (y, z, y, z); } +Vector4 Vector4::zzyz() const { return Vector4 (z, z, y, z); } +Vector4 Vector4::wzyz() const { return Vector4 (w, z, y, z); } +Vector4 Vector4::xwyz() const { return Vector4 (x, w, y, z); } +Vector4 Vector4::ywyz() const { return Vector4 (y, w, y, z); } +Vector4 Vector4::zwyz() const { return Vector4 (z, w, y, z); } +Vector4 Vector4::wwyz() const { return Vector4 (w, w, y, z); } +Vector4 Vector4::xxzz() const { return Vector4 (x, x, z, z); } +Vector4 Vector4::yxzz() const { return Vector4 (y, x, z, z); } +Vector4 Vector4::zxzz() const { return Vector4 (z, x, z, z); } +Vector4 Vector4::wxzz() const { return Vector4 (w, x, z, z); } +Vector4 Vector4::xyzz() const { return Vector4 (x, y, z, z); } +Vector4 Vector4::yyzz() const { return Vector4 (y, y, z, z); } +Vector4 Vector4::zyzz() const { return Vector4 (z, y, z, z); } +Vector4 Vector4::wyzz() const { return Vector4 (w, y, z, z); } +Vector4 Vector4::xzzz() const { return Vector4 (x, z, z, z); } +Vector4 Vector4::yzzz() const { return Vector4 (y, z, z, z); } +Vector4 Vector4::zzzz() const { return Vector4 (z, z, z, z); } +Vector4 Vector4::wzzz() const { return Vector4 (w, z, z, z); } +Vector4 Vector4::xwzz() const { return Vector4 (x, w, z, z); } +Vector4 Vector4::ywzz() const { return Vector4 (y, w, z, z); } +Vector4 Vector4::zwzz() const { return Vector4 (z, w, z, z); } +Vector4 Vector4::wwzz() const { return Vector4 (w, w, z, z); } +Vector4 Vector4::xxwz() const { return Vector4 (x, x, w, z); } +Vector4 Vector4::yxwz() const { return Vector4 (y, x, w, z); } +Vector4 Vector4::zxwz() const { return Vector4 (z, x, w, z); } +Vector4 Vector4::wxwz() const { return Vector4 (w, x, w, z); } +Vector4 Vector4::xywz() const { return Vector4 (x, y, w, z); } +Vector4 Vector4::yywz() const { return Vector4 (y, y, w, z); } +Vector4 Vector4::zywz() const { return Vector4 (z, y, w, z); } +Vector4 Vector4::wywz() const { return Vector4 (w, y, w, z); } +Vector4 Vector4::xzwz() const { return Vector4 (x, z, w, z); } +Vector4 Vector4::yzwz() const { return Vector4 (y, z, w, z); } +Vector4 Vector4::zzwz() const { return Vector4 (z, z, w, z); } +Vector4 Vector4::wzwz() const { return Vector4 (w, z, w, z); } +Vector4 Vector4::xwwz() const { return Vector4 (x, w, w, z); } +Vector4 Vector4::ywwz() const { return Vector4 (y, w, w, z); } +Vector4 Vector4::zwwz() const { return Vector4 (z, w, w, z); } +Vector4 Vector4::wwwz() const { return Vector4 (w, w, w, z); } +Vector4 Vector4::xxxw() const { return Vector4 (x, x, x, w); } +Vector4 Vector4::yxxw() const { return Vector4 (y, x, x, w); } +Vector4 Vector4::zxxw() const { return Vector4 (z, x, x, w); } +Vector4 Vector4::wxxw() const { return Vector4 (w, x, x, w); } +Vector4 Vector4::xyxw() const { return Vector4 (x, y, x, w); } +Vector4 Vector4::yyxw() const { return Vector4 (y, y, x, w); } +Vector4 Vector4::zyxw() const { return Vector4 (z, y, x, w); } +Vector4 Vector4::wyxw() const { return Vector4 (w, y, x, w); } +Vector4 Vector4::xzxw() const { return Vector4 (x, z, x, w); } +Vector4 Vector4::yzxw() const { return Vector4 (y, z, x, w); } +Vector4 Vector4::zzxw() const { return Vector4 (z, z, x, w); } +Vector4 Vector4::wzxw() const { return Vector4 (w, z, x, w); } +Vector4 Vector4::xwxw() const { return Vector4 (x, w, x, w); } +Vector4 Vector4::ywxw() const { return Vector4 (y, w, x, w); } +Vector4 Vector4::zwxw() const { return Vector4 (z, w, x, w); } +Vector4 Vector4::wwxw() const { return Vector4 (w, w, x, w); } +Vector4 Vector4::xxyw() const { return Vector4 (x, x, y, w); } +Vector4 Vector4::yxyw() const { return Vector4 (y, x, y, w); } +Vector4 Vector4::zxyw() const { return Vector4 (z, x, y, w); } +Vector4 Vector4::wxyw() const { return Vector4 (w, x, y, w); } +Vector4 Vector4::xyyw() const { return Vector4 (x, y, y, w); } +Vector4 Vector4::yyyw() const { return Vector4 (y, y, y, w); } +Vector4 Vector4::zyyw() const { return Vector4 (z, y, y, w); } +Vector4 Vector4::wyyw() const { return Vector4 (w, y, y, w); } +Vector4 Vector4::xzyw() const { return Vector4 (x, z, y, w); } +Vector4 Vector4::yzyw() const { return Vector4 (y, z, y, w); } +Vector4 Vector4::zzyw() const { return Vector4 (z, z, y, w); } +Vector4 Vector4::wzyw() const { return Vector4 (w, z, y, w); } +Vector4 Vector4::xwyw() const { return Vector4 (x, w, y, w); } +Vector4 Vector4::ywyw() const { return Vector4 (y, w, y, w); } +Vector4 Vector4::zwyw() const { return Vector4 (z, w, y, w); } +Vector4 Vector4::wwyw() const { return Vector4 (w, w, y, w); } +Vector4 Vector4::xxzw() const { return Vector4 (x, x, z, w); } +Vector4 Vector4::yxzw() const { return Vector4 (y, x, z, w); } +Vector4 Vector4::zxzw() const { return Vector4 (z, x, z, w); } +Vector4 Vector4::wxzw() const { return Vector4 (w, x, z, w); } +Vector4 Vector4::xyzw() const { return Vector4 (x, y, z, w); } +Vector4 Vector4::yyzw() const { return Vector4 (y, y, z, w); } +Vector4 Vector4::zyzw() const { return Vector4 (z, y, z, w); } +Vector4 Vector4::wyzw() const { return Vector4 (w, y, z, w); } +Vector4 Vector4::xzzw() const { return Vector4 (x, z, z, w); } +Vector4 Vector4::yzzw() const { return Vector4 (y, z, z, w); } +Vector4 Vector4::zzzw() const { return Vector4 (z, z, z, w); } +Vector4 Vector4::wzzw() const { return Vector4 (w, z, z, w); } +Vector4 Vector4::xwzw() const { return Vector4 (x, w, z, w); } +Vector4 Vector4::ywzw() const { return Vector4 (y, w, z, w); } +Vector4 Vector4::zwzw() const { return Vector4 (z, w, z, w); } +Vector4 Vector4::wwzw() const { return Vector4 (w, w, z, w); } +Vector4 Vector4::xxww() const { return Vector4 (x, x, w, w); } +Vector4 Vector4::yxww() const { return Vector4 (y, x, w, w); } +Vector4 Vector4::zxww() const { return Vector4 (z, x, w, w); } +Vector4 Vector4::wxww() const { return Vector4 (w, x, w, w); } +Vector4 Vector4::xyww() const { return Vector4 (x, y, w, w); } +Vector4 Vector4::yyww() const { return Vector4 (y, y, w, w); } +Vector4 Vector4::zyww() const { return Vector4 (z, y, w, w); } +Vector4 Vector4::wyww() const { return Vector4 (w, y, w, w); } +Vector4 Vector4::xzww() const { return Vector4 (x, z, w, w); } +Vector4 Vector4::yzww() const { return Vector4 (y, z, w, w); } +Vector4 Vector4::zzww() const { return Vector4 (z, z, w, w); } +Vector4 Vector4::wzww() const { return Vector4 (w, z, w, w); } +Vector4 Vector4::xwww() const { return Vector4 (x, w, w, w); } +Vector4 Vector4::ywww() const { return Vector4 (y, w, w, w); } +Vector4 Vector4::zwww() const { return Vector4 (z, w, w, w); } +Vector4 Vector4::wwww() const { return Vector4 (w, w, w, w); } + + +}; // namespace diff --git a/dep/g3dlite/debugAssert.cpp b/dep/g3dlite/debugAssert.cpp new file mode 100644 index 00000000000..a87161b261f --- /dev/null +++ b/dep/g3dlite/debugAssert.cpp @@ -0,0 +1,389 @@ +/** + @file debugAssert.cpp + + Windows implementation of assertion routines. + + @maintainer Morgan McGuire, graphics3d.com + + @created 2001-08-26 + @edited 2009-06-02 + */ + +#include "G3D/debugAssert.h" +#include "G3D/platform.h" +#ifdef G3D_WIN32 + #include +#endif +#include "G3D/format.h" +#include "G3D/prompt.h" +#include +#include "G3D/debugPrintf.h" +#include "G3D/Log.h" + +#include + +#ifdef _MSC_VER + // disable: "C++ exception handler used" +# pragma warning (push) +# pragma warning (disable : 4530) +#endif + +using namespace std; + +namespace G3D { namespace _internal { + +ConsolePrintHook _consolePrintHook; +AssertionHook _debugHook = _handleDebugAssert_; +AssertionHook _failureHook = _handleErrorCheck_; + +#ifdef G3D_LINUX +#if SOMEONE_MADE_THIS_USEFUL + Display* x11Display = NULL; + Window x11Window = 0; +#endif +#endif + + +#ifdef G3D_WIN32 +static void postToClipboard(const char *text) { + if (OpenClipboard(NULL)) { + HGLOBAL hMem = GlobalAlloc(GHND | GMEM_DDESHARE, strlen(text) + 1); + if (hMem) { + char *pMem = (char*)GlobalLock(hMem); + strcpy(pMem, text); + GlobalUnlock(hMem); + + EmptyClipboard(); + SetClipboardData(CF_TEXT, hMem); + } + + CloseClipboard(); + GlobalFree(hMem); + } +} +#endif + +/** + outTitle should be set before the call + */ +static void createErrorMessage( + const char* expression, + const std::string& message, + const char* filename, + int lineNumber, + std::string& outTitle, + std::string& outMessage) { + + std::string le = ""; + const char* newline = "\n"; + + #ifdef G3D_WIN32 + newline = "\r\n"; + + // The last error value. (Which is preserved across the call). + DWORD lastErr = GetLastError(); + + // The decoded message from FormatMessage + LPTSTR formatMsg = NULL; + + if (NULL == formatMsg) { + FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_IGNORE_INSERTS | + FORMAT_MESSAGE_FROM_SYSTEM, + NULL, + lastErr, + 0, + (LPTSTR)&formatMsg, + 0, + NULL); + } + + // Make sure the message got translated into something. + LPTSTR realLastErr; + if (NULL != formatMsg) { + realLastErr = formatMsg; + } else { + realLastErr = _T("Last error code does not exist."); + } + + if (lastErr != 0) { + le = G3D::format("Last Error (0x%08X): %s\r\n\r\n", lastErr, (LPCSTR)realLastErr); + } + + // Get rid of the allocated memory from FormatMessage. + if (NULL != formatMsg) { + LocalFree((LPVOID)formatMsg); + } + + char modulePath[MAX_PATH]; + GetModuleFileNameA(NULL, modulePath, MAX_PATH); + + const char* moduleName = strrchr(modulePath, '\\'); + outTitle = outTitle + string(" - ") + string(moduleName ? (moduleName + 1) : modulePath); + + #endif + + // Build the message. + outMessage = + G3D::format("%s%s%sExpression: %s%s%s:%d%s%s%s", + message.c_str(), newline, newline, expression, newline, + filename, lineNumber, newline, newline, le.c_str()); +} + + +bool _handleDebugAssert_( + const char* expression, + const std::string& message, + const char* filename, + int lineNumber, + bool useGuiPrompt) { + + std::string dialogTitle = "Assertion Failure"; + std::string dialogText = ""; + createErrorMessage(expression, message, filename, lineNumber, dialogTitle, dialogText); + + #ifdef G3D_WIN32 + DWORD lastErr = GetLastError(); + postToClipboard(dialogText.c_str()); + debugPrintf("\n%s\n", dialogText.c_str()); + #endif + + const int cBreak = 0; + const int cIgnore = 1; + const int cAbort = 2; + + static const char* choices[] = {"Debug", "Ignore", "Exit"}; + + // Log the error + Log::common()->print(std::string("\n**************************\n\n") + dialogTitle + "\n" + dialogText); + + int result = G3D::prompt(dialogTitle.c_str(), dialogText.c_str(), (const char**)choices, 3, useGuiPrompt); + +# ifdef G3D_WIN32 + // Put the incoming last error back. + SetLastError(lastErr); +# endif + + switch (result) { + // -1 shouldn't actually occur because it means + // that we're in release mode. + case -1: + case cBreak: + return true; + break; + + case cIgnore: + return false; + break; + + case cAbort: + exit(-1); + break; + } + + // Should never get here + return false; +} + + +bool _handleErrorCheck_( + const char* expression, + const std::string& message, + const char* filename, + int lineNumber, + bool useGuiPrompt) { + + std::string dialogTitle = "Critical Error"; + std::string dialogText = ""; + + createErrorMessage(expression, message, filename, lineNumber, dialogTitle, dialogText); + + // Log the error + Log::common()->print(std::string("\n**************************\n\n") + dialogTitle + "\n" + dialogText); + #ifdef G3D_WIN32 + DWORD lastErr = GetLastError(); + (void)lastErr; + postToClipboard(dialogText.c_str()); + debugPrintf("\n%s\n", dialogText.c_str()); + #endif + + static const char* choices[] = {"Ok"}; + + const std::string& m = + std::string("An internal error has occured in this program and it will now close. " + "The specific error is below. More information has been saved in \"") + + Log::getCommonLogFilename() + "\".\n" + dialogText; + + int result = G3D::prompt("Error", m.c_str(), (const char**)choices, 1, useGuiPrompt); + (void)result; + + return true; +} + + +#ifdef G3D_WIN32 +static HCURSOR oldCursor; +static RECT oldCursorRect; +static POINT oldCursorPos; +static int oldShowCursorCount; +#endif + +void _releaseInputGrab_() { + #ifdef G3D_WIN32 + + GetCursorPos(&oldCursorPos); + + // Stop hiding the cursor if the application hid it. + oldShowCursorCount = ShowCursor(true) - 1; + + if (oldShowCursorCount < -1) { + for (int c = oldShowCursorCount; c < -1; ++c) { + ShowCursor(true); + } + } + + // Set the default cursor in case the application + // set the cursor to NULL. + oldCursor = GetCursor(); + SetCursor(LoadCursor(NULL, IDC_ARROW)); + + // Allow the cursor full access to the screen + GetClipCursor(&oldCursorRect); + ClipCursor(NULL); + + #elif defined(G3D_LINUX) +#if SOMEONE_MADE_THIS_USEFUL + if (x11Display != NULL) { + XUngrabPointer(x11Display, CurrentTime); + XUngrabKeyboard(x11Display, CurrentTime); + if (x11Window != 0) { + //XUndefineCursor(x11Display, x11Window); + // TODO: Note that we leak this cursor; it should be + // freed in the restore code. + Cursor c = XCreateFontCursor(x11Display, 68); + XDefineCursor(x11Display, x11Window, c); + } + XSync(x11Display, false); + XAllowEvents(x11Display, AsyncPointer, CurrentTime); + XFlush(x11Display); + } +#endif + #elif defined(G3D_OSX) + // TODO: OS X + #endif +} + + +void _restoreInputGrab_() { + #ifdef G3D_WIN32 + + // Restore the old clipping region + ClipCursor(&oldCursorRect); + + SetCursorPos(oldCursorPos.x, oldCursorPos.y); + + // Restore the old cursor + SetCursor(oldCursor); + + // Restore old visibility count + if (oldShowCursorCount < 0) { + for (int c = 0; c > oldShowCursorCount; --c) { + ShowCursor(false); + } + } + + #elif defined(G3D_LINUX) + // TODO: Linux + #elif defined(G3D_OSX) + // TODO: OS X + #endif +} + + +}; // internal namespace + +void setAssertionHook(AssertionHook hook) { + G3D::_internal::_debugHook = hook; +} + +AssertionHook assertionHook() { + return G3D::_internal::_debugHook; +} + +void setFailureHook(AssertionHook hook) { + G3D::_internal::_failureHook = hook; +} + +AssertionHook failureHook() { + return G3D::_internal::_failureHook; +} + + +void setConsolePrintHook(ConsolePrintHook h) { + G3D::_internal::_consolePrintHook = h; +} + +ConsolePrintHook consolePrintHook() { + return G3D::_internal::_consolePrintHook; +} + + +std::string __cdecl debugPrint(const std::string& s) { +# ifdef G3D_WIN32 + const int MAX_STRING_LEN = 1024; + + // Windows can't handle really long strings sent to + // the console, so we break the string. + if (s.size() < MAX_STRING_LEN) { + OutputDebugStringA(s.c_str()); + } else { + for (unsigned int i = 0; i < s.size(); i += MAX_STRING_LEN) { + std::string sub = s.substr(i, MAX_STRING_LEN); + OutputDebugStringA(sub.c_str()); + } + } +# else + fprintf(stderr, "%s", s.c_str()); + fflush(stderr); +# endif + + return s; +} + +std::string __cdecl debugPrintf(const char* fmt ...) { + va_list argList; + va_start(argList, fmt); + std::string s = G3D::vformat(fmt, argList); + va_end(argList); + + return debugPrint(s); +// return debugPrint(consolePrint(s)); +} + +std::string consolePrint(const std::string& s) { + FILE* L = Log::common()->getFile(); + fprintf(L, "%s", s.c_str()); + + if (consolePrintHook()) { + consolePrintHook()(s); + } + + fflush(L); + return s; +} + + +std::string __cdecl consolePrintf(const char* fmt ...) { + va_list argList; + va_start(argList, fmt); + std::string s = G3D::vformat(fmt, argList); + va_end(argList); + + return consolePrint(s); +} + +} // namespace + +#ifdef _MSC_VER +# pragma warning (pop) +#endif diff --git a/dep/g3dlite/fileutils.cpp b/dep/g3dlite/fileutils.cpp new file mode 100644 index 00000000000..3f5eb579ba9 --- /dev/null +++ b/dep/g3dlite/fileutils.cpp @@ -0,0 +1,1165 @@ +/** + @file fileutils.cpp + + @author Morgan McGuire, graphics3d.com + + @author 2002-06-06 + @edited 2010-02-05 + */ + +#include +#include +#include "G3D/platform.h" +#include "G3D/fileutils.h" +#include "G3D/BinaryInput.h" +#include "G3D/BinaryOutput.h" +#include "G3D/g3dmath.h" +#include "G3D/stringutils.h" +#include "G3D/Set.h" +#include "G3D/g3dfnmatch.h" + +#include +#include +#if _HAVE_ZIP + #include "zip.h" +#endif + +#ifdef G3D_WIN32 + // Needed for _getcwd + #include + #include +#else + #include + #include + #include + #define _getcwd getcwd + #define _stat stat +#endif + + +namespace G3D { + +namespace _internal { + Set currentFilesUsed; +} + +std::string pathConcat(const std::string& dirname, const std::string& file) { + // Ensure that the directory ends in a slash + if ((dirname.size() != 0) && + (dirname[dirname.size() - 1] != '/') && + (dirname[dirname.size() - 1] != '\\') && + (dirname[dirname.size() - 1] != ':')) { + return dirname + '/' + file; + } else { + return dirname + file; + } +} + +std::string resolveFilename(const std::string& filename) { + if (filename.size() >= 1) { + if ((filename[0] == '/') || (filename[0] == '\\')) { + // Already resolved + return filename; + } else { + + #ifdef G3D_WIN32 + if ((filename.size() >= 2) && (filename[1] == ':')) { + // There is a drive spec on the front. + if ((filename.size() >= 3) && ((filename[2] == '\\') || + (filename[2] == '/'))) { + // Already fully qualified + return filename; + } else { + // The drive spec is relative to the + // working directory on that drive. + debugAssertM(false, "Files of the form d:path are" + " not supported (use a fully qualified" + " name)."); + return filename; + } + } + #endif + } + } + + char buffer[1024]; + + // Prepend the working directory. + _getcwd(buffer, 1024); + + return format("%s/%s", buffer, filename.c_str()); +} + +bool zipfileExists(const std::string& filename) { + std::string outZipfile; + std::string outInternalFile; + return zipfileExists(filename, outZipfile, outInternalFile); +} + +std::string readWholeFile( + const std::string& filename) { + + _internal::currentFilesUsed.insert(filename); + + std::string s; + + debugAssert(filename != ""); + if (fileExists(filename, false)) { + + int64 length = fileLength(filename); + + char* buffer = (char*)System::alignedMalloc(length + 1, 16); + debugAssert(buffer); + FILE* f = fopen(filename.c_str(), "rb"); + debugAssert(f); + int ret = fread(buffer, 1, length, f); + debugAssert(ret == length);(void)ret; + fclose(f); + + buffer[length] = '\0'; + s = std::string(buffer); + + System::alignedFree(buffer); + + } else if (zipfileExists(filename)) { + + void* zipBuffer; + size_t length; + zipRead(filename, zipBuffer, length); + + char* buffer = (char*)System::alignedMalloc(length + 1, 16); + System::memcpy(buffer,zipBuffer, length + 1); + zipClose(zipBuffer); + + buffer[length] = '\0'; + s = std::string(buffer); + System::alignedFree(buffer); + } else { + debugAssertM(false, filename + " not found"); + } + + return s; +} + + +void zipRead(const std::string& file, + void*& data, + size_t& length) { + std::string zip, desiredFile; +#if _HAVE_ZIP + if (zipfileExists(file, zip, desiredFile)) { + struct zip *z = zip_open( zip.c_str(), ZIP_CHECKCONS, NULL ); + { + struct zip_stat info; + zip_stat_init( &info ); // TODO: Docs unclear if zip_stat_init is required. + zip_stat( z, desiredFile.c_str(), ZIP_FL_NOCASE, &info ); + length = info.size; + // sets machines up to use MMX, if they want + data = System::alignedMalloc(length, 16); + struct zip_file *zf = zip_fopen( z, desiredFile.c_str(), ZIP_FL_NOCASE ); + { + int test = zip_fread( zf, data, length ); + debugAssertM((size_t)test == length, + desiredFile + " was corrupt because it unzipped to the wrong size."); + (void)test; + } + zip_fclose( zf ); + } + zip_close( z ); + } else { + data = NULL; + } +#else + data = NULL; +#endif +} + + +void zipClose(void* data) { + System::alignedFree(data); +} + + +int64 fileLength(const std::string& filename) { + struct _stat st; + int result = _stat(filename.c_str(), &st); + + if (result == -1) { +#if _HAVE_ZIP + std::string zip, contents; + if(zipfileExists(filename, zip, contents)){ + int64 requiredMem; + + struct zip *z = zip_open( zip.c_str(), ZIP_CHECKCONS, NULL ); + debugAssertM(z != NULL, zip + ": zip open failed."); + { + struct zip_stat info; + zip_stat_init( &info ); // TODO: Docs unclear if zip_stat_init is required. + int success = zip_stat( z, contents.c_str(), ZIP_FL_NOCASE, &info ); + debugAssertM(success == 0, zip + ": " + contents + ": zip stat failed."); + requiredMem = info.size; + } + zip_close( z ); + return requiredMem; + } else { + return -1; + } +#else + return -1; +#endif + } + + return st.st_size; +} + +/** Used by robustTmpfile. Returns nonzero if fread, fwrite, and fseek all +succeed on the file. + @author Morgan McGuire, http://graphics.cs.williams.edu */ +static int isFileGood(FILE* f) { + + int x, n, result; + + /* Must be a valid file handle */ + if (f == NULL) { + return 0; + } + + /* Try to write */ + x = 1234; + n = fwrite(&x, sizeof(int), 1, f); + + if (n != 1) { + return 0; + } + + /* Seek back to the beginning */ + result = fseek(f, 0, SEEK_SET); + if (result != 0) { + return 0; + } + + /* Read */ + n = fread(&x, sizeof(int), 1, f); + if (n != 1) { + return 0; + } + + /* Seek back to the beginning again */ + fseek(f, 0, SEEK_SET); + + return 1; +} + +FILE* createTempFile() { + FILE* t = NULL; + +//# ifdef G3D_WIN32 + t = tmpfile(); +//# else +// // On Unix, tmpfile generates a warning for any code that links against it. +// const char* tempfilename = "/tmp/g3dtemp.XXXXXXXX"; +// mktemp(tempfilename); +// t = fopen(tempfilename, "w"); +//# endif + +# ifdef _WIN32 + char* n = NULL; +# endif + char name[256]; + + if (isFileGood(t)) { + return t; + } + +# ifdef G3D_WIN32 + /* tmpfile failed; try the tmpnam routine */ + t = fopen(tmpnam(NULL), "w+"); + if (isFileGood(t)) { + return t; + } + + n = _tempnam("c:/tmp/", "t"); + /* Try to create something in C:\tmp */ + t = fopen(n, "w+"); + if (isFileGood(t)) { + return t; + } + + /* Try c:\temp */ + n = _tempnam("c:/temp/", "t"); + t = fopen(n, "w+"); + if (isFileGood(t)) { + return t; + } + + /* try the current directory */ + n = _tempnam("./", "t"); + t = fopen(n, "w+"); + if (isFileGood(t)) { + return t; + } + + sprintf(name, "%s/tmp%d", "c:/temp", rand()); + t = fopen(name, "w+"); + if (isFileGood(t)) { + return t; + } + + /* Try some hardcoded paths */ + sprintf(name, "%s/tmp%d", "c:/tmp", rand()); + t = fopen(name, "w+"); + if (isFileGood(t)) { + return t; + } +# else + sprintf(name, "%s/tmp%d", "/tmp", rand()); + t = fopen(name, "w+"); + if (isFileGood(t)) { + return t; + } +#endif + + sprintf(name, "tmp%d", rand()); + t = fopen(name, "w+"); + if (isFileGood(t)) { + return t; + } + + fprintf(stderr, "Unable to create a temporary file; robustTmpfile returning NULL\n"); + + return NULL; +} + +/////////////////////////////////////////////////////////////////////////////// +void writeWholeFile( + const std::string& filename, + const std::string& str, + bool flush) { + + // Make sure the directory exists. + std::string root, base, ext, path; + Array pathArray; + parseFilename(filename, root, pathArray, base, ext); + + path = root + stringJoin(pathArray, '/'); + if (! fileExists(path, false)) { + createDirectory(path); + } + + FILE* file = fopen(filename.c_str(), "wb"); + + debugAssert(file); + + fwrite(str.c_str(), str.size(), 1, file); + + if (flush) { + fflush(file); + } + fclose(file); +} + +/////////////////////////////////////////////////////////////////////////////// + +/** + Creates the directory (which may optionally end in a /) + and any parents needed to reach it. + */ +void createDirectory( + const std::string& dir) { + + if (dir == "") { + return; + } + + std::string d; + + // Add a trailing / if there isn't one. + switch (dir[dir.size() - 1]) { + case '/': + case '\\': + d = dir; + break; + + default: + d = dir + "/"; + } + + // If it already exists, do nothing + if (fileExists(d.substr(0, d.size() - 1)), false) { + return; + } + + // Parse the name apart + std::string root, base, ext; + Array path; + + std::string lead; + parseFilename(d, root, path, base, ext); + debugAssert(base == ""); + debugAssert(ext == ""); + + // Begin with an extra period so "c:\" becomes "c:\.\" after + // appending a path and "c:" becomes "c:.\", not root: "c:\" + std::string p = root + "."; + + // Create any intermediate that doesn't exist + for (int i = 0; i < path.size(); ++i) { + p += "/" + path[i]; + if (! fileExists(p, false)) { + // Windows only requires one argument to mkdir, + // where as unix also requires the permissions. +# ifndef G3D_WIN32 + mkdir(p.c_str(), 0777); +# else + _mkdir(p.c_str()); +# endif + } + } +} + +/////////////////////////////////////////////////////////////////////////////// + +class FileSystemCache { +private: + + Table > m_files; + +public: + + bool fileExists(const std::string& filename) { + const std::string& path = resolveFilename(filenamePath(filename)); + const std::string& name = filenameBaseExt(filename); + + bool neverBeforeSeen = false; + Array& fileList = m_files.getCreate(path, neverBeforeSeen); + if (neverBeforeSeen) { + if (! G3D::fileExists(path, true, false)) { + // The path itself doesn't exist... back out our insertion (which makes fileList& invalid) + m_files.remove(path); + return false; + } + + std::string spec = pathConcat(path, "*"); + + // Will automatically recurse into zipfiles + getFiles(spec, fileList); + getDirs(spec, fileList); + +# ifdef G3D_WIN32 + { + // Case insensitive + for (int i = 0; i < fileList.size(); ++i) { + fileList[i] = toLower(fileList[i]); + } + } +# endif + } + + if (filenameContainsWildcards(name)) { + // See if anything matches + for (int i = 0; i < fileList.size(); ++i) { + if (g3dfnmatch(name.c_str(), fileList[i].c_str(), 0) == 0) { + return true; + } + } + return false; + } else { + // On windows, this is a lower-lower comparison, so it is case insensitive + return fileList.contains(name); + } + } + + void clear() { + m_files.clear(); + } + + static FileSystemCache& instance() { + static FileSystemCache i; + return i; + } +}; + + +void clearFileSystemCache() { + FileSystemCache::instance().clear(); +} + +bool fileExists +(const std::string& _filename, + bool lookInZipfiles, + bool trustCache) { + + if (_filename.empty()) { + return false; + } + + // Remove trailing slash from directories + const std::string& filename = (endsWith(_filename, "/") || endsWith(_filename, "\\")) ? _filename.substr(0, _filename.length() - 1) : _filename; + + if (trustCache && lookInZipfiles) { +# ifdef G3D_WIN32 + // Case insensitive + return FileSystemCache::instance().fileExists(toLower(filename)); +# else + return FileSystemCache::instance().fileExists(filename); +# endif + } + + // Useful for debugging + //char curdir[1024]; _getcwd(curdir, 1024); + + struct _stat st; + int ret = _stat(filename.c_str(), &st); + + // _stat returns zero on success + bool exists = (ret == 0); + + if (! exists && lookInZipfiles) { + // Does not exist standalone, but might exist in a zipfile + + // These output arguments will be ignored + std::string zipDir, internalPath; + return zipfileExists(filename, zipDir, internalPath); + } else { + return exists; + } +} + +/////////////////////////////////////////////////////////////////////////////// + +#if _HAVE_ZIP +/* Helper methods for zipfileExists()*/ +// Given a string (the drive) and an array (the path), computes the directory +static void _zip_resolveDirectory(std::string& completeDir, const std::string& drive, const Array& path, const int length){ + completeDir = drive; + int tempLength; + // if the given length is longer than the array, we correct it + if(length > path.length()){ + tempLength = path.length(); + } else{ + tempLength = length; + } + + for(int t = 0; t < tempLength; ++t){ + if(t > 0){ + completeDir += "/"; + } + completeDir += path[t]; + } +} + + +// assumes that zipDir references a .zip file +static bool _zip_zipContains(const std::string& zipDir, const std::string& desiredFile){ + struct zip *z = zip_open( zipDir.c_str(), ZIP_CHECKCONS, NULL ); + //the last parameter, an int, determines case sensitivity: + //1 is sensitive, 2 is not, 0 is default + int test = zip_name_locate( z, desiredFile.c_str(), ZIP_FL_NOCASE ); + zip_close( z ); + if(test == -1){ + return false; + } + return true; +} +#endif + +// If no zipfile exists, outZipfile and outInternalFile are unchanged +bool zipfileExists(const std::string& filename, std::string& outZipfile, + std::string& outInternalFile){ +#if _HAVE_ZIP + Array path; + std::string drive, base, ext, zipfile, infile; + parseFilename(filename, drive, path, base, ext); + + // Put the filename back together + if ((base != "") && (ext != "")) { + infile = base + "." + ext; + } else { + infile = base + ext; + } + + // Remove "." from path + for (int i = 0; i < path.length(); ++i) { + if (path[i] == ".") { + path.remove(i); + --i; + } + } + + // Remove ".." from path + for (int i = 1; i < path.length(); ++i) { + if ((path[i] == "..") && (i > 0) && (path[i - 1] != "..")) { + // Remove both i and i - 1 + path.remove(i - 1, 2); + i -= 2; + } + } + + // Walk the path backwards, accumulating pieces onto the infile until + // we find a zipfile that contains it + for (int t = 0; t < path.length(); ++t){ + _zip_resolveDirectory(zipfile, drive, path, path.length() - t); + if (t > 0) { + infile = path[path.length() - t] + "/" + infile; + } + + if (endsWith(zipfile, "..")) { + return false; + } + + if (fileExists(zipfile, false)) { + // test if it actually is a zipfile + // if not, return false, a bad + // directory structure has been given, + // not a .zip + if (isZipfile(zipfile)){ + + if (_zip_zipContains(zipfile, infile)){ + outZipfile = zipfile; + outInternalFile = infile; + return true; + } else { + return false; + } + } else { + // the directory structure was valid but did not point to a .zip + return false; + } + } + + } +#endif + // not a valid directory structure ever, + // obviously no .zip was found within the path + return false; +} + +/////////////////////////////////////////////////////////////////////////////// + +std::string generateFilenameBase(const std::string& prefix, const std::string& suffix) { + Array exist; + + // Note "template" is a reserved word in C++ + std::string templat = prefix + System::currentDateString() + "_"; + getFiles(templat + "*", exist); + + // Remove extensions + for (int i = 0; i < exist.size(); ++i) { + exist[i] = filenameBase(exist[i]); + } + + int num = 0; + std::string result; + templat += "%03d" + suffix; + do { + result = format(templat.c_str(), num); + ++num; + } while (exist.contains(result)); + + return result; +} + +/////////////////////////////////////////////////////////////////////////////// + +void copyFile( + const std::string& source, + const std::string& dest) { + + #ifdef G3D_WIN32 + CopyFileA(source.c_str(), dest.c_str(), FALSE); + #else + // TODO: don't use BinaryInput and BinaryOutput + // Read it all in, then dump it out + BinaryInput in(source, G3D_LITTLE_ENDIAN); + BinaryOutput out(dest, G3D_LITTLE_ENDIAN); + out.writeBytes(in.getCArray(), in.size()); + out.commit(false); + #endif +} + +////////////////////////////////////////////////////////////////////////////// + +void parseFilename( + const std::string& filename, + std::string& root, + Array& path, + std::string& base, + std::string& ext) { + + std::string f = filename; + + root = ""; + path.clear(); + base = ""; + ext = ""; + + if (f == "") { + // Empty filename + return; + } + + // See if there is a root/drive spec. + if ((f.size() >= 2) && (f[1] == ':')) { + + if ((f.size() > 2) && isSlash(f[2])) { + + // e.g. c:\foo + root = f.substr(0, 3); + f = f.substr(3, f.size() - 3); + + } else { + + // e.g. c:foo + root = f.substr(2); + f = f.substr(2, f.size() - 2); + + } + + } else if ((f.size() >= 2) & isSlash(f[0]) && isSlash(f[1])) { + + // e.g. //foo + root = f.substr(0, 2); + f = f.substr(2, f.size() - 2); + + } else if (isSlash(f[0])) { + + root = f.substr(0, 1); + f = f.substr(1, f.size() - 1); + + } + + // Pull the extension off + { + // Find the period + size_t i = f.rfind('.'); + + if (i != std::string::npos) { + // Make sure it is after the last slash! + size_t j = iMax(f.rfind('/'), f.rfind('\\')); + if ((j == std::string::npos) || (i > j)) { + ext = f.substr(i + 1, f.size() - i - 1); + f = f.substr(0, i); + } + } + } + + // Pull the basename off + { + // Find the last slash + size_t i = iMax(f.rfind('/'), f.rfind('\\')); + + if (i == std::string::npos) { + + // There is no slash; the basename is the whole thing + base = f; + f = ""; + + } else if ((i != std::string::npos) && (i < f.size() - 1)) { + + base = f.substr(i + 1, f.size() - i - 1); + f = f.substr(0, i); + + } + } + + // Parse what remains into path. + size_t prev, cur = 0; + + while (cur < f.size()) { + prev = cur; + + // Allow either slash + size_t i = f.find('/', prev + 1); + size_t j = f.find('\\', prev + 1); + if (i == std::string::npos) { + i = f.size(); + } + + if (j == std::string::npos) { + j = f.size(); + } + + cur = iMin(i, j); + + if (cur == std::string::npos) { + cur = f.size(); + } + + path.append(f.substr(prev, cur - prev)); + ++cur; + } +} + + +/** + Helper for getFileList and getDirectoryList. + + @param wantFiles If false, returns the directories, otherwise + returns the files. + @param includePath If true, the names include paths + */ +static void getFileOrDirListNormal +(const std::string& filespec, + Array& files, + bool wantFiles, + bool includePath) { + + bool test = wantFiles ? true : false; + + std::string path = ""; + + // Find the place where the path ends and the file-spec begins + size_t i = filespec.rfind('/'); + size_t j = filespec.rfind('\\'); + + // Drive letters on Windows can separate a path + size_t k = filespec.rfind(':'); + + if (((j != std::string::npos) && (j > i)) || + (i == std::string::npos)) { + i = j; + } + + if (((k != std::string::npos) && (k > i)) || + (i == std::string::npos)) { + i = k; + } + + // If there is a path, pull it off + if (i != std::string::npos) { + path = filespec.substr(0, i + 1); + } + + std::string prefix = path; + + if (path.size() > 0) { + // Strip the trailing character + path = path.substr(0, path.size() - 1); + } + +# ifdef G3D_WIN32 + { + struct _finddata_t fileinfo; + + long handle = _findfirst(filespec.c_str(), &fileinfo); + int result = handle; + + while (result != -1) { + if ((((fileinfo.attrib & _A_SUBDIR) == 0) == test) && + strcmp(fileinfo.name, ".") && + strcmp(fileinfo.name, "..")) { + + if (includePath) { + files.append(prefix + fileinfo.name); + } else { + files.append(fileinfo.name); + } + } + + result = _findnext(handle, &fileinfo); + } + } +# else + { + if (path == "") { + // Empty paths don't work on Unix + path = "."; + } + + // Unix implementation + DIR* dir = opendir(path.c_str()); + + if (dir != NULL) { + struct dirent* entry = readdir(dir); + + while (entry != NULL) { + + // Exclude '.' and '..' + if ((strcmp(entry->d_name, ".") != 0) && + (strcmp(entry->d_name, "..") != 0)) { + + // Form a name with a path + std::string filename = prefix + entry->d_name; + // See if this is a file or a directory + struct _stat st; + bool exists = _stat(filename.c_str(), &st) != -1; + + if (exists && + + // Make sure it has the correct type + (((st.st_mode & S_IFDIR) == 0) == test) && + + // Make sure it matches the wildcard + (fnmatch(filespec.c_str(), + filename.c_str(), + FNM_PATHNAME) == 0)) { + + if (includePath) { + files.append(filename); + } else { + files.append(entry->d_name); + } + } + } + + entry = readdir(dir); + } + closedir(dir); + } + } +# endif +} + +#if _HAVE_ZIP +/** + @param path The zipfile name (no trailing slash) + @param prefix Directory inside the zipfile. No leading slash, must have trailing slash if non-empty. + @param file Name inside the zipfile that we are testing to see if it matches prefix + "*" + */ +static void _zip_addEntry(const std::string& path, + const std::string& prefix, + const std::string& file, + Set& files, + bool wantFiles, + bool includePath) { + + // Make certain we are within the desired parent folder (prefix) + if (beginsWith(file, prefix)) { + // validityTest was prefix/file + + // Extract everything to the right of the prefix + std::string s = file.substr(prefix.length()); + + if (s == "") { + // This was the name of the prefix + return; + } + + // See if there are any slashes + size_t slashPos = s.find('/'); + + bool add = false; + + if (slashPos == std::string::npos) { + // No slashes, so s must be a file + add = wantFiles; + } else if (! wantFiles) { + // Not all zipfiles list directories as explicit entries. + // Because of this, if we're looking for directories and see + // any path longer than prefix, we must add the subdirectory. + // The Set will fix duplicates for us. + s = s.substr(0, slashPos); + add = true; + } + + if (add) { + if (includePath) { + files.insert(path + "/" + prefix + s); + } else { + files.insert(s); + } + } + } +} +#endif + +static void getFileOrDirListZip(const std::string& path, + const std::string& prefix, + Array& files, + bool wantFiles, + bool includePath){ +#if _HAVE_ZIP + struct zip *z = zip_open( path.c_str(), ZIP_CHECKCONS, NULL ); + + Set fileSet; + + int count = zip_get_num_files( z ); + for( int i = 0; i < count; ++i ) { + struct zip_stat info; + zip_stat_init( &info ); // TODO: Docs unclear if zip_stat_init is required. + zip_stat_index( z, i, ZIP_FL_NOCASE, &info ); + _zip_addEntry(path, prefix, info.name, fileSet, wantFiles, includePath); + } + + zip_close( z ); + + fileSet.getMembers(files); +#endif +} + + +static void determineFileOrDirList( + const std::string& filespec, + Array& files, + bool wantFiles, + bool includePath) { + + // if it is a .zip, prefix will specify the folder within + // whose contents we want to see + std::string prefix = ""; + std::string path = filenamePath(filespec); + + if ((path.size() > 0) && isSlash(path[path.size() - 1])) { + // Strip the trailing slash + path = path.substr(0, path.length() -1); + } + + if ((path == "") || fileExists(path, false)) { + if ((path != "") && isZipfile(path)) { + // .zip should only work if * is specified as the Base + Ext + // Here, we have been asked for the root's contents + debugAssertM(filenameBaseExt(filespec) == "*", "Can only call getFiles/getDirs on zipfiles using '*' wildcard"); + getFileOrDirListZip(path, prefix, files, wantFiles, includePath); + } else { + // It is a normal directory + getFileOrDirListNormal(filespec, files, wantFiles, includePath); + } + } else if (zipfileExists(filenamePath(filespec), path, prefix)) { + // .zip should only work if * is specified as the Base + Ext + // Here, we have been asked for the contents of a folder within the .zip + debugAssertM(filenameBaseExt(filespec) == "*", "Can only call getFiles/getDirs on zipfiles using '*' wildcard"); + getFileOrDirListZip(path, prefix, files, wantFiles, includePath); + } +} + + +void getFiles(const std::string& filespec, + Array& files, + bool includePath) { + + determineFileOrDirList(filespec, files, true, includePath); +} + + +void getDirs( + const std::string& filespec, + Array& files, + bool includePath) { + + determineFileOrDirList(filespec, files, false, includePath); +} + + +std::string filenameBaseExt(const std::string& filename) { + int i = filename.rfind("/"); + int j = filename.rfind("\\"); + + if ((j > i) && (j >= 0)) { + i = j; + } + +# ifdef G3D_WIN32 + j = filename.rfind(":"); + if ((i == -1) && (j >= 0)) { + i = j; + } +# endif + + if (i == -1) { + return filename; + } else { + return filename.substr(i + 1, filename.length() - i); + } +} + + +std::string filenameBase(const std::string& s) { + std::string drive; + std::string base; + std::string ext; + Array path; + + parseFilename(s, drive, path, base, ext); + return base; +} + + +std::string filenameExt(const std::string& filename) { + int i = filename.rfind("."); + if (i >= 0) { + return filename.substr(i + 1, filename.length() - i); + } else { + return ""; + } +} + + +std::string filenamePath(const std::string& filename) { + int i = filename.rfind("/"); + int j = filename.rfind("\\"); + + if ((j > i) && (j >= 0)) { + i = j; + } + +# ifdef G3D_WIN32 + j = filename.rfind(":"); + if ((i == -1) && (j >= 0)) { + i = j; + } +# endif + + if (i == -1) { + return ""; + } else { + return filename.substr(0, i+1); + } +} + + +bool isZipfile(const std::string& filename) { + + FILE* f = fopen(filename.c_str(), "r"); + if (f == NULL) { + return false; + } + uint8 header[4]; + fread(header, 4, 1, f); + + const uint8 zipHeader[4] = {0x50, 0x4b, 0x03, 0x04}; + for (int i = 0; i < 4; ++i) { + if (header[i] != zipHeader[i]) { + fclose(f); + return false; + } + } + + fclose(f); + return true; +} + + +bool isDirectory(const std::string& filename) { + struct _stat st; + bool exists = _stat(filename.c_str(), &st) != -1; + return exists && ((st.st_mode & S_IFDIR) != 0); +} + + +bool filenameContainsWildcards(const std::string& filename) { + return (filename.find('*') != std::string::npos) || (filename.find('?') != std::string::npos); +} + + +bool fileIsNewer(const std::string& src, const std::string& dst) { + struct _stat sts; + bool sexists = _stat(src.c_str(), &sts) != -1; + + struct _stat dts; + bool dexists = _stat(dst.c_str(), &dts) != -1; + + return sexists && ((! dexists) || (sts.st_mtime > dts.st_mtime)); +} + + +Array filesUsed() { + Array f; + _internal::currentFilesUsed.getMembers(f); + return f; +} + +} + +#ifndef G3D_WIN32 + #undef _stat +#endif diff --git a/dep/g3dlite/format.cpp b/dep/g3dlite/format.cpp new file mode 100644 index 00000000000..d9d1b516393 --- /dev/null +++ b/dep/g3dlite/format.cpp @@ -0,0 +1,164 @@ +/** + @file format.cpp + + @author Morgan McGuire, graphics3d.com + + @created 2000-09-09 + @edited 2006-08-14 +*/ + +#include "G3D/format.h" +#include "G3D/platform.h" +#include "G3D/System.h" + +#ifdef _MSC_VER + // disable: "C++ exception handler used" +# pragma warning (push) +# pragma warning (disable : 4530) +#endif // _MSC_VER + +// If your platform does not have vsnprintf, you can find a +// implementation at http://www.ijs.si/software/snprintf/ + +namespace G3D { + +std::string __cdecl format(const char* fmt,...) { + va_list argList; + va_start(argList,fmt); + std::string result = vformat(fmt, argList); + va_end(argList); + + return result; +} + +#if defined(_MSC_VER) && (_MSC_VER >= 1300) +// Both MSVC seems to use the non-standard vsnprintf +// so we are using vscprintf to determine buffer size, however +// only MSVC7 and up headers include vscprintf for some reason. +std::string vformat(const char *fmt, va_list argPtr) { + // We draw the line at a 1MB string. + const int maxSize = 1000000; + + // If the string is less than 161 characters, + // allocate it on the stack because this saves + // the malloc/free time. + const int bufSize = 161; + char stackBuffer[bufSize]; + + // MSVC does not support va_copy + int actualSize = _vscprintf(fmt, argPtr) + 1; + + if (actualSize > bufSize) { + + // Now use the heap. + char* heapBuffer = NULL; + + if (actualSize < maxSize) { + + heapBuffer = (char*)System::malloc(maxSize + 1); + _vsnprintf(heapBuffer, maxSize, fmt, argPtr); + heapBuffer[maxSize] = '\0'; + } else { + heapBuffer = (char*)System::malloc(actualSize); + vsprintf(heapBuffer, fmt, argPtr); + } + + std::string formattedString(heapBuffer); + System::free(heapBuffer); + return formattedString; + } else { + + vsprintf(stackBuffer, fmt, argPtr); + return std::string(stackBuffer); + } +} + +#elif defined(_MSC_VER) && (_MSC_VER < 1300) + +std::string vformat(const char *fmt, va_list argPtr) { + // We draw the line at a 1MB string. + const int maxSize = 1000000; + + // If the string is less than 161 characters, + // allocate it on the stack because this saves + // the malloc/free time. + const int bufSize = 161; + char stackBuffer[bufSize]; + + // MSVC6 doesn't support va_copy, however it also seems to compile + // correctly if we just pass our argument list along. Note that + // this whole code block is only compiled if we're on MSVC6 anyway + int actualWritten = _vsnprintf(stackBuffer, bufSize, fmt, argPtr); + + // Not a big enough buffer, bufSize characters written + if (actualWritten == -1) { + + int heapSize = 512; + double powSize = 1.0; + char* heapBuffer = (char*)System::malloc(heapSize); + + while ((_vsnprintf(heapBuffer, heapSize, fmt, argPtr) == -1) && + (heapSize < maxSize)) { + + heapSize = iCeil(heapSize * ::pow((double)2.0, powSize++)); + heapBuffer = (char*)System::realloc(heapBuffer, heapSize); + } + + heapBuffer[heapSize-1] = '\0'; + + std::string heapString(heapBuffer); + System::free(heapBuffer); + + return heapString; + } else { + + return std::string(stackBuffer); + } +} + +#else + +// glibc 2.1 has been updated to the C99 standard +std::string vformat(const char* fmt, va_list argPtr) { + // If the string is less than 161 characters, + // allocate it on the stack because this saves + // the malloc/free time. The number 161 is chosen + // to support two lines of text on an 80 character + // console (plus the null terminator). + const int bufSize = 161; + char stackBuffer[bufSize]; + + va_list argPtrCopy; + va_copy(argPtrCopy, argPtr); + int numChars = vsnprintf(stackBuffer, bufSize, fmt, argPtrCopy); + va_end(argPtrCopy); + + if (numChars >= bufSize) { + // We didn't allocate a big enough string. + char* heapBuffer = (char*)System::malloc((numChars + 1) * sizeof(char)); + + debugAssert(heapBuffer); + int numChars2 = vsnprintf(heapBuffer, numChars + 1, fmt, argPtr); + debugAssert(numChars2 == numChars); + (void)numChars2; + + std::string result(heapBuffer); + + System::free(heapBuffer); + + return result; + + } else { + + return std::string(stackBuffer); + + } +} + +#endif + +} // namespace + +#ifdef _MSC_VER +# pragma warning (pop) +#endif diff --git a/dep/g3dlite/g3dfnmatch.cpp b/dep/g3dlite/g3dfnmatch.cpp new file mode 100644 index 00000000000..39ef7b31914 --- /dev/null +++ b/dep/g3dlite/g3dfnmatch.cpp @@ -0,0 +1,204 @@ +/*- +* Copyright (c) 1992, 1993 +*The Regents of the University of California. 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. All advertising materials mentioning features or use of this software +* must display the following acknowledgement: +*This product includes software developed by the University of +*California, Berkeley and its contributors. +* 4. Neither the name of the University 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 REGENTS 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 REGENTS 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. +* +*@(#)fnmatch.h8.1 (Berkeley) 6/2/93 +* +* From FreeBSD fnmatch.h 1.7 +* $Id: g3dfnmatch.cpp,v 1.2 2010/02/06 10:03:24 corey_taylor Exp $ +*/ +#include "G3D/g3dfnmatch.h" + +#ifdef G3D_WIN32 + +#include +#include +#include + +namespace G3D { + +#define EOS '\0' + +static const char *rangematch(const char *, char, int); + +int g3dfnmatch(const char *pattern, const char *string, int flags) +{ + const char *stringstart; + char c, test; + + for (stringstart = string;;) + switch (c = *pattern++) { + case EOS: + if ((flags & FNM_LEADING_DIR) && *string == '/') + return (0); + return (*string == EOS ? 0 : FNM_NOMATCH); + case '?': + if (*string == EOS) + return (FNM_NOMATCH); + if (*string == '/' && (flags & FNM_PATHNAME)) + return (FNM_NOMATCH); + if (*string == '.' && (flags & FNM_PERIOD) && + (string == stringstart || + ((flags & FNM_PATHNAME) && *(string - 1) == '/'))) + return (FNM_NOMATCH); + ++string; + break; + case '*': + c = *pattern; + /* Collapse multiple stars. */ + while (c == '*') + c = *++pattern; + + if (*string == '.' && (flags & FNM_PERIOD) && + (string == stringstart || + ((flags & FNM_PATHNAME) && *(string - 1) == '/'))) + return (FNM_NOMATCH); + + /* Optimize for pattern with * at end or before /. */ + if (c == EOS) + if (flags & FNM_PATHNAME) + return ((flags & FNM_LEADING_DIR) || + strchr(string, '/') == NULL ? + 0 : FNM_NOMATCH); + else + return (0); + else if (c == '/' && flags & FNM_PATHNAME) { + if ((string = strchr(string, '/')) == NULL) + return (FNM_NOMATCH); + break; + } + + /* General case, use recursion. */ + while ((test = *string) != EOS) { + if (!rangematch(pattern, *string, flags & ~FNM_PERIOD)) + return (0); + if (test == '/' && flags & FNM_PATHNAME) + break; + ++string; + } + return (FNM_NOMATCH); + case '[': + if (*string == EOS) + return (FNM_NOMATCH); + if (*string == '/' && flags & FNM_PATHNAME) + return (FNM_NOMATCH); + if ((pattern = + rangematch(pattern, *string, flags)) == NULL) + return (FNM_NOMATCH); + ++string; + break; + case '\\': + if (!(flags & FNM_NOESCAPE)) { + if ((c = *pattern++) == EOS) { + c = '\\'; + --pattern; + } + } + /* FALLTHROUGH */ + default: + if (c == *string) + ; + else if ((flags & FNM_CASEFOLD) && + (tolower((unsigned char)c) == + tolower((unsigned char)*string))) + ; + else if ((flags & FNM_PREFIX_DIRS) && *string == EOS && + ((c == '/' && string != stringstart) || + (string == stringstart+1 && *stringstart == '/'))) + return (0); + else + return (FNM_NOMATCH); + string++; + break; + } + /* NOTREACHED */ +} + +static const char * +rangematch(const char *pattern, char test, int flags) +{ + int negate, ok; + char c, c2; + + /* + * A bracket expression starting with an unquoted circumflex + * character produces unspecified results (IEEE 1003.2-1992, + * 3.13.2). This implementation treats it like '!', for + * consistency with the regular expression syntax. + * J.T. Conklin (conklin@ngai.kaleida.com) + */ + if ( (negate = (*pattern == '!' || *pattern == '^')) ) + ++pattern; + + if (flags & FNM_CASEFOLD) + test = tolower((unsigned char)test); + + for (ok = 0; (c = *pattern++) != ']';) { + if (c == '\\' && !(flags & FNM_NOESCAPE)) + c = *pattern++; + if (c == EOS) + return (NULL); + + if (flags & FNM_CASEFOLD) + c = tolower((unsigned char)c); + + if (*pattern == '-' + && (c2 = *(pattern+1)) != EOS && c2 != ']') { + pattern += 2; + if (c2 == '\\' && !(flags & FNM_NOESCAPE)) + c2 = *pattern++; + if (c2 == EOS) + return (NULL); + + if (flags & FNM_CASEFOLD) + c2 = tolower((unsigned char)c2); + + if ((unsigned char)c <= (unsigned char)test && + (unsigned char)test <= (unsigned char)c2) + ok = 1; + } else if (c == test) + ok = 1; + } + return (ok == negate ? NULL : pattern); +} + +} + +#else + +namespace G3D { +int g3dfnmatch(const char * a, const char *b, int c) { + return fnmatch(a, b, c); +} +} + +#endif + diff --git a/dep/g3dlite/g3dmath.cpp b/dep/g3dlite/g3dmath.cpp new file mode 100644 index 00000000000..ad85e9efb9b --- /dev/null +++ b/dep/g3dlite/g3dmath.cpp @@ -0,0 +1,108 @@ +/** + @file g3dmath.cpp + + @author Morgan McGuire, graphics3d.com + + @created 2001-06-02 + @edited 2004-02-24 + */ + +#include "G3D/g3dmath.h" +#include +#include + +namespace G3D { + +float gaussRandom(float mean, float stdev) { + + // Using Box-Mueller method from http://www.taygeta.com/random/gaussian.html + // Modified to specify standard deviation and mean of distribution + float w, x1, x2; + + // Loop until w is less than 1 so that log(w) is negative + do { + x1 = uniformRandom(-1.0, 1.0); + x2 = uniformRandom(-1.0, 1.0); + + w = float(square(x1) + square(x2)); + } while (w > 1.0f); + + // Transform to gassian distribution + // Multiply by sigma (stdev ^ 2) and add mean. + return x2 * (float)square(stdev) * sqrtf((-2.0f * logf(w) ) / w) + mean; +} + +/** + This value should not be tested against directly, instead + G3D::isNan() and G3D::isFinite() will return reliable results. */ +double inf() { + return std::numeric_limits::infinity(); +} + +bool isNaN(float x) { + static const float n = nan(); + return memcmp(&x, &n, sizeof(float)) == 0; +} + +bool isNaN(double x) { + static const double n = nan(); + return memcmp(&x, &n, sizeof(double)) == 0; +} + + +/** + This value should not be tested against directly, instead + G3D::isNan() and G3D::isFinite() will return reliable results. */ +float finf() { + return std::numeric_limits::infinity(); +} + +/** This value should not be tested against directly, instead + G3D::isNan() and G3D::isFinite() will return reliable results. */ +double nan() { + // double is a standard type and should have quiet NaN + return std::numeric_limits::quiet_NaN(); +} + +float fnan() { + // double is a standard type and should have quiet NaN + return std::numeric_limits::quiet_NaN(); +} + + +int highestBit(uint32 x) { + // Binary search. + int base = 0; + + if (x & 0xffff0000) { + base = 16; + x >>= 16; + } + if (x & 0x0000ff00) { + base += 8; + x >>= 8; + } + if (x & 0x000000f0) { + base += 4; + x >>= 4; + } + + static const int lut[] = {-1,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3}; + return base + lut[x]; +} + + +int iRandom(int low, int high) { + int r = iFloor(low + (high - low + 1) * (double)rand() / RAND_MAX); + + // There is a *very small* chance of generating + // a number larger than high. + if (r > high) { + return high; + } else { + return r; + } +} + + +} diff --git a/dep/g3dlite/prompt.cpp b/dep/g3dlite/prompt.cpp new file mode 100644 index 00000000000..6a28e6462b4 --- /dev/null +++ b/dep/g3dlite/prompt.cpp @@ -0,0 +1,729 @@ +/** + @file prompt.cpp + + @author Morgan McGuire, http://graphics.cs.williams.edu + @cite Windows dialog interface by Max McGuire, mmcguire@ironlore.com + @cite Font setting code by Kurt Miller, kurt@flipcode.com + + @created 2000-08-26 + @edited 2005-01-14 + */ + +#include "G3D/prompt.h" +#include "G3D/platform.h" + +#include + +#ifdef G3D_WIN32 +# include +# include +#else +# define _getch getchar +#endif + +#ifdef G3D_OSX + +/*#ifdef __LP64__ +# undef __LP64__ +#endif +*/ + +# include + +/* +#ifdef G3D_64BIT +# define __LP64__ +#endif +*/ + +#endif + +namespace G3D { + +#ifdef G3D_WIN32 + +namespace _internal { +/** + Generic Win32 dialog facility. + @author Max McGuire + */ +class DialogTemplate { +public: + + DialogTemplate(LPCSTR caption, DWORD style, + int x, int y, int w, int h, + LPCSTR font = NULL, WORD fontSize = 8) { + + usedBufferLength = sizeof(DLGTEMPLATE); + totalBufferLength = usedBufferLength; + + dialogTemplate = (DLGTEMPLATE*)malloc(totalBufferLength); + + dialogTemplate->style = style; + + if (font != NULL) { + dialogTemplate->style |= DS_SETFONT; + } + + dialogTemplate->x = (short)x; + dialogTemplate->y = (short)y; + dialogTemplate->cx = (short)w; + dialogTemplate->cy = (short)h; + dialogTemplate->cdit = 0; + + dialogTemplate->dwExtendedStyle = 0; + + // The dialog box doesn't have a menu or a special class + AppendData("\0", 2); + AppendData("\0", 2); + + // Add the dialog's caption to the template + + AppendString(caption); + + if (font != NULL) { + AppendData(&fontSize, sizeof(WORD)); + AppendString(font); + } + } + + void AddComponent(LPCSTR type, LPCSTR caption, DWORD style, DWORD exStyle, int x, int y, int w, int h, WORD id) { + + DLGITEMTEMPLATE item; + + item.style = style; + item.x = (short)x; + item.y = (short)y; + item.cx = (short)w; + item.cy = (short)h; + item.id = id; + + item.dwExtendedStyle = exStyle; + + AppendData(&item, sizeof(DLGITEMTEMPLATE)); + + AppendString(type); + AppendString(caption); + + WORD creationDataLength = 0; + AppendData(&creationDataLength, sizeof(WORD)); + + // Increment the component count + dialogTemplate->cdit++; + + } + + + void AddButton(LPCSTR caption, DWORD style, DWORD exStyle, int x, int y, int w, int h, WORD id) { + + AddStandardComponent(0x0080, caption, style, exStyle, x, y, w, h, id); + + WORD creationDataLength = 0; + AppendData(&creationDataLength, sizeof(WORD)); + + } + + + void AddEditBox(LPCSTR caption, DWORD style, DWORD exStyle, int x, int y, int w, int h, WORD id) { + + AddStandardComponent(0x0081, caption, style, exStyle, x, y, w, h, id); + + WORD creationDataLength = 0; + AppendData(&creationDataLength, sizeof(WORD)); + + } + + + void AddStatic(LPCSTR caption, DWORD style, DWORD exStyle, int x, int y, int w, int h, WORD id) { + + AddStandardComponent(0x0082, caption, style, exStyle, x, y, w, h, id); + + WORD creationDataLength = 0; + AppendData(&creationDataLength, sizeof(WORD)); + + } + + + void AddListBox(LPCSTR caption, DWORD style, DWORD exStyle, int x, int y, int w, int h, WORD id) { + + AddStandardComponent(0x0083, caption, style, exStyle, x, y, w, h, id); + + WORD creationDataLength = sizeof(WORD) + 5 * sizeof(WCHAR); + AppendData(&creationDataLength, sizeof(WORD)); + + AppendString("TEST"); + + } + + + void AddScrollBar(LPCSTR caption, DWORD style, DWORD exStyle, int x, int y, int w, int h, WORD id) { + + AddStandardComponent(0x0084, caption, style, exStyle, x, y, w, h, id); + + WORD creationDataLength = 0; + AppendData(&creationDataLength, sizeof(WORD)); + + } + + + void AddComboBox(LPCSTR caption, DWORD style, DWORD exStyle, int x, int y, int w, int h, WORD id) { + + AddStandardComponent(0x0085, caption, style, exStyle, x, y, w, h, id); + + WORD creationDataLength = 0; + AppendData(&creationDataLength, sizeof(WORD)); + + } + + + /** + * + * Returns a pointer to the Win32 dialog template which the object + * represents. This pointer may become invalid if additional components + * are added to the template. + * + */ + operator const DLGTEMPLATE*() const { + return dialogTemplate; + } + + virtual ~DialogTemplate() { + free(dialogTemplate); + } + +protected: + + void AddStandardComponent(WORD type, LPCSTR caption, DWORD style, DWORD exStyle, + int x, int y, int w, int h, WORD id, LPSTR font = NULL, WORD fontSize = 8) { + + DLGITEMTEMPLATE item; + + // DWORD align the beginning of the component data + + AlignData(sizeof(DWORD)); + + item.style = style; + if (font != NULL) { + item.style |= DS_SETFONT; + } + item.x = (short)x; + item.y = (short)y; + item.cx = (short)w; + item.cy = (short)h; + item.id = id; + + item.dwExtendedStyle = exStyle; + + AppendData(&item, sizeof(DLGITEMTEMPLATE)); + + WORD preType = 0xFFFF; + + AppendData(&preType, sizeof(WORD)); + AppendData(&type, sizeof(WORD)); + + AppendString(caption); + + if (font != NULL) { + AppendData(&fontSize, sizeof(WORD)); + AppendString(font); + } + + // Increment the component count + dialogTemplate->cdit++; + } + + + void AlignData(int size) { + + int paddingSize = usedBufferLength % size; + + if (paddingSize != 0) { + EnsureSpace(paddingSize); + usedBufferLength += paddingSize; + } + + } + + void AppendString(LPCSTR string) { + + int length = MultiByteToWideChar(CP_ACP, 0, string, -1, NULL, 0); + + WCHAR* wideString = (WCHAR*)malloc(sizeof(WCHAR) * length); + MultiByteToWideChar(CP_ACP, 0, string, -1, wideString, length); + + AppendData(wideString, length * sizeof(WCHAR)); + free(wideString); + + } + + void AppendData(const void* data, int dataLength) { + + EnsureSpace(dataLength); + + memcpy((char*)dialogTemplate + usedBufferLength, data, dataLength); + usedBufferLength += dataLength; + + } + + void EnsureSpace(int length) { + if (length + usedBufferLength > totalBufferLength) { + totalBufferLength += length * 2; + + void* newBuffer = malloc(totalBufferLength); + memcpy(newBuffer, dialogTemplate, usedBufferLength); + + free(dialogTemplate); + dialogTemplate = (DLGTEMPLATE*)newBuffer; + } + } + +private: + + DLGTEMPLATE* dialogTemplate; + + int totalBufferLength; + int usedBufferLength; + +}; + + +struct PromptParams { + const char* message; + const char* title; +}; + +/** + * Constants for controls. + */ +#define IDC_MESSAGE 1000 +#define IDC_BUTTON0 2000 + +INT_PTR CALLBACK PromptDlgProc(HWND hDlg, UINT msg, + WPARAM wParam, LPARAM lParam) { + switch(msg) { + case WM_INITDIALOG: + { + PromptParams *params = (PromptParams*)lParam; + ::SetWindowTextA(::GetDlgItem(hDlg, IDC_MESSAGE), params->message); + + ::SetFocus(::GetDlgItem(hDlg, IDC_BUTTON0)); + + SetWindowTextA(hDlg, params->title); + + HFONT hfont = + CreateFontA(16, 0, 0, 0, FW_NORMAL, + FALSE, FALSE, FALSE, + ANSI_CHARSET,OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS, + PROOF_QUALITY, FIXED_PITCH | FF_MODERN, "Courier New"); + + SendDlgItemMessage(hDlg, IDC_MESSAGE, WM_SETFONT, (WPARAM)hfont, MAKELPARAM(TRUE,0)); + + + break; + } + case WM_COMMAND: + { + int choiceNumber = LOWORD(wParam) - IDC_BUTTON0; + if ((choiceNumber >= 0) && (choiceNumber < 10)) { + EndDialog(hDlg, choiceNumber); + return TRUE; + } + } + + break; + + case WM_NCDESTROY: + // Under SDL 1.2.6 we get a NCDESTROY message for no reason and the + // window is immediately closed. This is here to debug the problem. + (void)0; + break; + + } + + return FALSE; +} + +}; // namespace _internal + + +using namespace _internal; + +/** + * Show a dialog prompt. + */ +static int guiPrompt( + const char* windowTitle, + const char* prompt, + const char** choice, + int numChoices) { + + int width = 280; + int height = 128; + + const int buttonSpacing = 2; + const int buttonWidth = + (width - buttonSpacing * 2 - + buttonSpacing * (numChoices - 1)) / numChoices; + const int buttonHeight = 13; + + + DialogTemplate dialogTemplate( + windowTitle, + WS_CAPTION | DS_CENTER | WS_SYSMENU, + 10, 10, width, height, + "Tahoma"); + + dialogTemplate.AddEditBox( + "Edit", WS_VISIBLE | ES_READONLY | ES_OEMCONVERT | ES_MULTILINE | WS_TABSTOP, WS_EX_STATICEDGE, + 2, 2, width - 4, height - buttonHeight - 7, IDC_MESSAGE); + + int i; + for (i = 0; i < numChoices; i++) { + + int x = buttonSpacing + i * (buttonWidth + buttonSpacing); + int y = height - buttonHeight - buttonSpacing; + + dialogTemplate.AddButton(choice[i], WS_VISIBLE | WS_TABSTOP, 0, + x, y, buttonWidth, buttonHeight, IDC_BUTTON0 + (WORD)i); + + } + + // Convert all single \n characters to \r\n for proper printing + int strLen = 0; + const char* pStr = prompt; + + while (*pStr != '\0') { + if ((*pStr == '\n') && (pStr != prompt)) { + if (*(pStr - 1) != '\r') { + ++strLen; + } + } + ++strLen; + ++pStr; + } + + char* newStr = (char*)malloc(strLen + 1); + + const char* pStr2 = prompt; + char* pNew = newStr; + + while (*pStr2 != '\0') { + if ((*pStr2 == '\n') && (pStr2 != prompt)) { + if (*(pStr2 - 1) != '\r') { + *pNew = '\r'; + ++pNew; + } + } + *pNew = *pStr2; + ++pNew; + ++pStr2; + } + + *pNew = '\0'; + + PromptParams params; + params.message = newStr;; + params.title = windowTitle; + + HMODULE module = GetModuleHandle(0); + int ret = DialogBoxIndirectParam(module, dialogTemplate, NULL, (DLGPROC) PromptDlgProc, (DWORD)¶ms); + + free(newStr); + + /* + For debugging when DialogBoxIndirectParam fails: + + // The last error value. (Which is preserved across the call). + DWORD lastErr = GetLastError(); + + // The decoded message from FormatMessage + LPTSTR formatMsg = NULL; + + if (NULL == formatMsg) { + FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_IGNORE_INSERTS | + FORMAT_MESSAGE_FROM_SYSTEM, + NULL, + lastErr, + 0, + (LPTSTR)&formatMsg, + 0, + NULL); + } + + // Make sure the message got translated into something. + LPTSTR realLastErr; + if (NULL != formatMsg) { + realLastErr = formatMsg; + } else { + realLastErr = "Last error code does not exist."; + } + + // Get rid of the allocated memory from FormatMessage. + if (NULL != formatMsg) { + LocalFree((LPVOID)formatMsg); + } + */ + + return ret; +} + +#endif + + +/** + * Show a prompt on stdout + */ +static int textPrompt( + const char* windowTitle, + const char* prompt, + const char** choice, + int numChoices) { + + printf("\n___________________________________________________\n"); + printf("%s\n", windowTitle); + printf("%s", prompt); + + if (numChoices > 10) { + numChoices = 10; + } + + int c = -1; + if (numChoices > 1) { + printf("\n"); + printf("Choose an option by number:"); + + while ((c < 0) || (c >= numChoices)) { + printf("\n"); + + for (int i = 0; i < numChoices; i++) { + if (numChoices <= 3) { + printf(" (%d) %s ", i, choice[i]); + } else { + printf(" (%d) %s\n", i, choice[i]); + } + } + + printf("\n> "); + c = _getch() - '0'; + + if ((c < 0) || (c >= numChoices)) { + printf("'%d' is not a valid choice.", c); + } else { + printf("%d", c); + } + } + + } else if (numChoices == 1) { + + printf("\nPress any key for '%s'...", choice[0]); + _getch(); + c = 0; + + } else { + + printf("\nPress any key..."); + _getch(); + c = 0; + } + + printf("\n___________________________________________________\n"); + return c; +} + +#ifdef G3D_OSX + +// See http://developer.apple.com/documentation/Carbon/Reference/Carbon_Event_Manager_Ref/index.html + +#define CARBON_COMMANDID_START 128 +#define CARBON_BUTTON_SPACING 12 +#define CARBON_BUTTON_HEIGHT 20 +#define CARBON_BUTTON_MINWIDTH 69 +#define CARBON_WINDOW_PADDING 20 + +struct CallbackData { + WindowRef refWindow; + + /** Index of this particular button */ + int myIndex; + + /** Buttons store their index into here when pressed. */ + int* whichButton; +}; + +/** + Assumes that userData is a pointer to a carbon_evt_data_t. + + */ +static pascal OSStatus DoCommandEvent(EventHandlerCallRef handlerRef, EventRef event, void* userData) { + // See http://developer.apple.com/documentation/Carbon/Conceptual/HandlingWindowsControls/index.html + + CallbackData& callbackData = *(CallbackData*)userData; + +# pragma unused(handlerRef) + + callbackData.whichButton[0] = callbackData.myIndex; + + // If we get here we can close the window + ::QuitAppModalLoopForWindow(callbackData.refWindow); + + // Return noErr to indicate that we handled the event + return noErr; +} + +static int guiPrompt +(const char* windowTitle, + const char* prompt, + const char** choice, + int numChoices) { + + WindowRef window; + + int iNumButtonRows = 0; + int iButtonWidth = -1; + OSStatus err = noErr; + + // Determine number of rows of buttons + while (iButtonWidth < CARBON_BUTTON_MINWIDTH) { + ++iNumButtonRows; + iButtonWidth = + (550 - (CARBON_WINDOW_PADDING*2 + + (CARBON_BUTTON_SPACING*numChoices))) / + (numChoices/iNumButtonRows); + } + + // Window Variables + Rect rectWin = {0, 0, 200 + ((iNumButtonRows-1) * (CARBON_BUTTON_HEIGHT+CARBON_BUTTON_SPACING)), 550}; // top, left, bottom, right + CFStringRef szWindowTitle = CFStringCreateWithCString(kCFAllocatorDefault, windowTitle, kCFStringEncodingUTF8); + + window = NULL; + + err = CreateNewWindow(kMovableAlertWindowClass, kWindowStandardHandlerAttribute|kWindowCompositingAttribute, &rectWin, &window); + err = SetWindowTitleWithCFString(window, szWindowTitle); + err = SetThemeWindowBackground(window, kThemeBrushAlertBackgroundActive, false); + assert(err == noErr); + + // Event Handler Variables + EventTypeSpec buttonSpec[] = {{ kEventClassControl, kEventControlHit }, { kEventClassCommand, kEventCommandProcess }}; + EventHandlerUPP buttonHandler = NewEventHandlerUPP(DoCommandEvent); + + // Static Text Variables + Rect rectStatic = {20, 20, 152, 530}; + CFStringRef szStaticText = CFStringCreateWithCString(kCFAllocatorDefault, prompt, kCFStringEncodingUTF8); + ControlRef refStaticText = NULL; + err = CreateStaticTextControl(window, &rectStatic, szStaticText, NULL, &refStaticText); + + // Button Variables + Rect bounds[numChoices]; + CFStringRef caption[numChoices]; + ControlRef button[numChoices]; + + int whichButton=-1; + CallbackData callbackData[numChoices]; + + // Create the Buttons and assign event handlers + for (int i = 0; i < numChoices; ++i) { + bounds[i].top = 160 + ((CARBON_BUTTON_HEIGHT+CARBON_BUTTON_SPACING)*(i%iNumButtonRows)); + bounds[i].right = 530 - ((iButtonWidth+CARBON_BUTTON_SPACING)*(i/iNumButtonRows)); + bounds[i].left = bounds[i].right - iButtonWidth; + bounds[i].bottom = bounds[i].top + CARBON_BUTTON_HEIGHT; + + // Convert the button captions to Apple strings + caption[i] = CFStringCreateWithCString(kCFAllocatorDefault, choice[i], kCFStringEncodingUTF8); + + err = CreatePushButtonControl(window, &bounds[i], caption[i], &button[i]); + assert(err == noErr); + + err = SetControlCommandID(button[i], CARBON_COMMANDID_START + i); + assert(err == noErr); + + callbackData[i].refWindow = window; + callbackData[i].myIndex = i; + callbackData[i].whichButton = &whichButton; + + err = InstallControlEventHandler(button[i], buttonHandler, + GetEventTypeCount(buttonSpec), buttonSpec, + &callbackData[i], NULL); + assert(err == noErr); + } + + // Show Dialog + err = RepositionWindow(window, NULL, kWindowCenterOnMainScreen); + ShowWindow(window); + BringToFront(window); + err = ActivateWindow(window, true); + + // Hack to get our window/process to the front... + ProcessSerialNumber psn = { 0, kCurrentProcess}; + TransformProcessType(&psn, kProcessTransformToForegroundApplication); + SetFrontProcess (&psn); + + // Run in Modal State + err = RunAppModalLoopForWindow(window); + + // Dispose of Button Related Data + for (int i = 0; i < numChoices; ++i) { + // Dispose of controls + DisposeControl(button[i]); + + // Release CFStrings + CFRelease(caption[i]); + } + + // Dispose of Other Controls + DisposeControl(refStaticText); + + // Dispose of Event Handlers + DisposeEventHandlerUPP(buttonHandler); + + // Dispose of Window + DisposeWindow(window); + + // Release CFStrings + CFRelease(szWindowTitle); + CFRelease(szStaticText); + + // Return Selection + return whichButton; +} + +#endif + +int prompt( + const char* windowTitle, + const char* prompt, + const char** choice, + int numChoices, + bool useGui) { + + #ifdef G3D_WIN32 + if (useGui) { + // Build the message box + return guiPrompt(windowTitle, prompt, choice, numChoices); + } + #endif + + #ifdef G3D_OSX + if (useGui){ + //Will default to text prompt if numChoices > 4 + return guiPrompt(windowTitle, prompt, choice, numChoices); + } + #endif + return textPrompt(windowTitle, prompt, choice, numChoices); +} + + +void msgBox( + const std::string& message, + const std::string& title) { + + const char *choice[] = {"Ok"}; + prompt(title.c_str(), message.c_str(), choice, 1, true); +} + +#ifndef G3D_WIN32 + #undef _getch +#endif + +};// namespace + diff --git a/dep/g3dlite/stringutils.cpp b/dep/g3dlite/stringutils.cpp new file mode 100644 index 00000000000..c3876ebb6a4 --- /dev/null +++ b/dep/g3dlite/stringutils.cpp @@ -0,0 +1,275 @@ +/** + @file stringutils.cpp + + @maintainer Morgan McGuire, http://graphics.cs.williams.edu + + @created 2000-09-09 + @edited 2008-01-10 +*/ + +#include "G3D/platform.h" +#include "G3D/stringutils.h" +#include "G3D/BinaryInput.h" +#include + +namespace G3D { + +#ifdef _MSC_VER + // disable: "C++ exception handler used" +# pragma warning (push) +# pragma warning (disable : 4530) +#endif +#ifdef G3D_WIN32 + const char* NEWLINE = "\r\n"; +#else + const char* NEWLINE = "\n"; + static bool iswspace(int ch) { return (ch==' ' || ch=='\t' || ch=='\n' || ch=='\r'); } +#endif + +void parseCommaSeparated(const std::string s, Array& array, bool stripQuotes) { + array.fastClear(); + if (s == "") { + return; + } + + size_t begin = 0; + const char delimiter = ','; + const char quote = '\"'; + do { + size_t end = begin; + // Find the next comma, or the end of the string + bool inQuotes = false; + while ((end < s.length()) && (inQuotes || (s[end] != delimiter))) { + if (s[end] == quote) { + if ((end < s.length() - 2) && (s[end + 1] == quote) && (s[end + 2]) == quote) { + // Skip over the superquote + end += 2; + } + inQuotes = ! inQuotes; + } + ++end; + } + array.append(s.substr(begin, end - begin)); + begin = end + 1; + } while (begin < s.length()); + + if (stripQuotes) { + for (int i = 0; i < array.length(); ++i) { + std::string& t = array[i]; + int L = t.length(); + if ((L > 1) && (t[0] == quote) && (t[L - 1] == quote)) { + if ((L > 6) && (t[1] == quote) && (t[2] == quote) && (t[L - 3] == quote) && (t[L - 2] == quote)) { + // Triple-quote + t = t.substr(3, L - 6); + } else { + // Double-quote + t = t.substr(1, L - 2); + } + } + } + } +} + +bool beginsWith( + const std::string& test, + const std::string& pattern) { + + if (test.size() >= pattern.size()) { + for (int i = 0; i < (int)pattern.size(); ++i) { + if (pattern[i] != test[i]) { + return false; + } + } + return true; + } else { + return false; + } +} + + +bool endsWith( + const std::string& test, + const std::string& pattern) { + + if (test.size() >= pattern.size()) { + int te = test.size() - 1; + int pe = pattern.size() - 1; + for (int i = pattern.size() - 1; i >= 0; --i) { + if (pattern[pe - i] != test[te - i]) { + return false; + } + } + return true; + } else { + return false; + } +} + + +std::string wordWrap( + const std::string& input, + int numCols) { + + std::string output; + size_t c = 0; + int len; + + // Don't make lines less than this length + int minLength = numCols / 4; + size_t inLen = input.size(); + + bool first = true; + while (c < inLen) { + if (first) { + first = false; + } else { + output += NEWLINE; + } + + if ((int)inLen - (int)c - 1 < numCols) { + // The end + output += input.substr(c, inLen - c); + break; + } + + len = numCols; + + // Look at character c + numCols, see if it is a space. + while ((len > minLength) && + (input[c + len] != ' ')) { + len--; + } + + if (len == minLength) { + // Just crop + len = numCols; + + } + + output += input.substr(c, len); + c += len; + if (c < input.size()) { + // Collapse multiple spaces. + while ((input[c] == ' ') && (c < input.size())) { + c++; + } + } + } + + return output; +} + + +int stringCompare( + const std::string& s1, + const std::string& s2) { + + return stringPtrCompare(&s1, &s2); +} + + +int stringPtrCompare( + const std::string* s1, + const std::string* s2) { + + return s1->compare(*s2); +} + + +std::string toUpper(const std::string& x) { + std::string result = x; + std::transform(result.begin(), result.end(), result.begin(), toupper); + return result; +} + + +std::string toLower(const std::string& x) { + std::string result = x; + std::transform(result.begin(), result.end(), result.begin(), tolower); + return result; +} + + +Array stringSplit( + const std::string& x, + char splitChar) { + + Array out; + + // Pointers to the beginning and end of the substring + const char* start = x.c_str(); + const char* stop = start; + + while ((stop = strchr(start, splitChar))) { + out.append(std::string(start, stop - start)); + start = stop + 1; + } + + // Append the last one + out.append(std::string(start)); + + return out; +} + + +std::string stringJoin( + const Array& a, + char joinChar) { + + std::string out; + + for (int i = 0; i < (int)a.size() - 1; ++i) { + out += a[i] + joinChar; + } + + if (a.size() > 0) { + return out + a.last(); + } else { + return out; + } +} + + +std::string stringJoin( + const Array& a, + const std::string& joinStr) { + + std::string out; + + for (int i = 0; i < (int)a.size() - 1; ++i) { + out += a[i] + joinStr; + } + + if (a.size() > 0) { + return out + a.last(); + } else { + return out; + } +} + + +std::string trimWhitespace( + const std::string& s) { + + size_t left = 0; + + // Trim from left + while ((left < s.length()) && iswspace(s[left])) { + ++left; + } + + int right = s.length() - 1; + // Trim from right + while ((right > (int)left) && iswspace(s[right])) { + --right; + } + + return s.substr(left, right - left + 1); +} + +}; // namespace + +#undef NEWLINE +#ifdef _MSC_VER +# pragma warning (pop) +#endif diff --git a/dep/gsoap/CMakeLists.txt b/dep/gsoap/CMakeLists.txt new file mode 100644 index 00000000000..915eeed9b21 --- /dev/null +++ b/dep/gsoap/CMakeLists.txt @@ -0,0 +1,11 @@ +file(GLOB sources *.cpp *.h) + +set(gsoap_STAT_SRCS + ${sources} +) + +include_directories( + ${CMAKE_CURRENT_SOURCE_DIR} +) + +add_library(gsoap STATIC ${gsoap_STAT_SRCS}) diff --git a/dep/gsoap/soapC.cpp b/dep/gsoap/soapC.cpp new file mode 100644 index 00000000000..7b964aff6a9 --- /dev/null +++ b/dep/gsoap/soapC.cpp @@ -0,0 +1,1645 @@ +/* soapC.cpp + Generated by gSOAP 2.7.10 from stub.h + Copyright(C) 2000-2008, Robert van Engelen, Genivia Inc. All Rights Reserved. + This part of the software is released under one of the following licenses: + GPL, the gSOAP public license, or Genivia's license for commercial use. +*/ + +#include "soapH.h" + +SOAP_SOURCE_STAMP("@(#) soapC.cpp ver 2.7.10 2010-02-18 18:41:56 GMT") + + +#ifndef WITH_NOGLOBAL + +SOAP_FMAC3 void SOAP_FMAC4 soap_serializeheader(struct soap *soap) +{ + if (soap->header) + soap_serialize_SOAP_ENV__Header(soap, soap->header); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_putheader(struct soap *soap) +{ + if (soap->header) + { soap->part = SOAP_IN_HEADER; + if (soap_out_SOAP_ENV__Header(soap, "SOAP-ENV:Header", 0, soap->header, NULL)) + return soap->error; + soap->part = SOAP_END_HEADER; + } + return SOAP_OK; +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_getheader(struct soap *soap) +{ + soap->part = SOAP_IN_HEADER; + soap->header = soap_in_SOAP_ENV__Header(soap, "SOAP-ENV:Header", NULL, NULL); + soap->part = SOAP_END_HEADER; + return soap->header == NULL; +} + +SOAP_FMAC3 void SOAP_FMAC4 soap_header(struct soap *soap) +{ + if (!soap->header) + { soap->header = soap_new_SOAP_ENV__Header(soap, -1); + soap_default_SOAP_ENV__Header(soap, soap->header); + } +} + +SOAP_FMAC3 void SOAP_FMAC4 soap_fault(struct soap *soap) +{ + if (!soap->fault) + { soap->fault = soap_new_SOAP_ENV__Fault(soap, -1); + soap_default_SOAP_ENV__Fault(soap, soap->fault); + } + if (soap->version == 2 && !soap->fault->SOAP_ENV__Code) + { soap->fault->SOAP_ENV__Code = soap_new_SOAP_ENV__Code(soap, -1); + soap_default_SOAP_ENV__Code(soap, soap->fault->SOAP_ENV__Code); + } + if (soap->version == 2 && !soap->fault->SOAP_ENV__Reason) + { soap->fault->SOAP_ENV__Reason = soap_new_SOAP_ENV__Reason(soap, -1); + soap_default_SOAP_ENV__Reason(soap, soap->fault->SOAP_ENV__Reason); + } +} + +SOAP_FMAC3 void SOAP_FMAC4 soap_serializefault(struct soap *soap) +{ + soap_fault(soap); + if (soap->fault) + soap_serialize_SOAP_ENV__Fault(soap, soap->fault); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_putfault(struct soap *soap) +{ + if (soap->fault) + return soap_put_SOAP_ENV__Fault(soap, soap->fault, "SOAP-ENV:Fault", NULL); + return SOAP_OK; +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_getfault(struct soap *soap) +{ + return (soap->fault = soap_get_SOAP_ENV__Fault(soap, NULL, "SOAP-ENV:Fault", NULL)) == NULL; +} + +SOAP_FMAC3 const char ** SOAP_FMAC4 soap_faultcode(struct soap *soap) +{ + soap_fault(soap); + if (soap->version == 2) + return (const char**)&soap->fault->SOAP_ENV__Code->SOAP_ENV__Value; + return (const char**)&soap->fault->faultcode; +} + +SOAP_FMAC3 const char ** SOAP_FMAC4 soap_faultsubcode(struct soap *soap) +{ + soap_fault(soap); + if (soap->version == 2) + { if (!soap->fault->SOAP_ENV__Code->SOAP_ENV__Subcode) + { soap->fault->SOAP_ENV__Code->SOAP_ENV__Subcode = soap_new_SOAP_ENV__Code(soap, -1); + soap_default_SOAP_ENV__Code(soap, soap->fault->SOAP_ENV__Code->SOAP_ENV__Subcode); + } + return (const char**)&soap->fault->SOAP_ENV__Code->SOAP_ENV__Subcode->SOAP_ENV__Value; + } + return (const char**)&soap->fault->faultcode; +} + +SOAP_FMAC3 const char ** SOAP_FMAC4 soap_faultstring(struct soap *soap) +{ + soap_fault(soap); + if (soap->version == 2) + return (const char**)&soap->fault->SOAP_ENV__Reason->SOAP_ENV__Text; + return (const char**)&soap->fault->faultstring; +} + +SOAP_FMAC3 const char ** SOAP_FMAC4 soap_faultdetail(struct soap *soap) +{ + soap_fault(soap); + if (soap->version == 1) + { if (!soap->fault->detail) + { soap->fault->detail = (struct SOAP_ENV__Detail*)soap_malloc(soap, sizeof(struct SOAP_ENV__Detail)); + soap_default_SOAP_ENV__Detail(soap, soap->fault->detail); + } + return (const char**)&soap->fault->detail->__any; + } + if (!soap->fault->SOAP_ENV__Detail) + { soap->fault->SOAP_ENV__Detail = soap_new_SOAP_ENV__Detail(soap, -1); + soap_default_SOAP_ENV__Detail(soap, soap->fault->SOAP_ENV__Detail); + } + return (const char**)&soap->fault->SOAP_ENV__Detail->__any; +} + +#endif + +#ifndef WITH_NOIDREF +SOAP_FMAC3 int SOAP_FMAC4 soap_getindependent(struct soap *soap) +{ + int t; + for (;;) + if (!soap_getelement(soap, &t)) + if (soap->error || soap_ignore_element(soap)) + break; + if (soap->error == SOAP_NO_TAG || soap->error == SOAP_EOF) + soap->error = SOAP_OK; + return soap->error; +} +#endif + +#ifndef WITH_NOIDREF + +#ifdef __cplusplus +extern "C" { +#endif +SOAP_FMAC3 void * SOAP_FMAC4 soap_getelement(struct soap *soap, int *type) +{ + if (soap_peek_element(soap)) + return NULL; + if (!*soap->id || !(*type = soap_lookup_type(soap, soap->id))) + *type = soap_lookup_type(soap, soap->href); + switch (*type) + { + case SOAP_TYPE_byte: + return soap_in_byte(soap, NULL, NULL, "xsd:byte"); + case SOAP_TYPE_int: + return soap_in_int(soap, NULL, NULL, "xsd:int"); + case SOAP_TYPE_ns1__executeCommand: + return soap_in_ns1__executeCommand(soap, NULL, NULL, "ns1:executeCommand"); + case SOAP_TYPE_ns1__executeCommandResponse: + return soap_in_ns1__executeCommandResponse(soap, NULL, NULL, "ns1:executeCommandResponse"); + case SOAP_TYPE_PointerTostring: + return soap_in_PointerTostring(soap, NULL, NULL, "xsd:string"); + case SOAP_TYPE_string: + { char **s; + s = soap_in_string(soap, NULL, NULL, "xsd:string"); + return s ? *s : NULL; + } + default: + { const char *t = soap->type; + if (!*t) + t = soap->tag; + if (!soap_match_tag(soap, t, "xsd:byte")) + { *type = SOAP_TYPE_byte; + return soap_in_byte(soap, NULL, NULL, NULL); + } + if (!soap_match_tag(soap, t, "xsd:int")) + { *type = SOAP_TYPE_int; + return soap_in_int(soap, NULL, NULL, NULL); + } + if (!soap_match_tag(soap, t, "ns1:executeCommand")) + { *type = SOAP_TYPE_ns1__executeCommand; + return soap_in_ns1__executeCommand(soap, NULL, NULL, NULL); + } + if (!soap_match_tag(soap, t, "ns1:executeCommandResponse")) + { *type = SOAP_TYPE_ns1__executeCommandResponse; + return soap_in_ns1__executeCommandResponse(soap, NULL, NULL, NULL); + } + if (!soap_match_tag(soap, t, "xsd:string")) + { char **s; + *type = SOAP_TYPE_string; + s = soap_in_string(soap, NULL, NULL, NULL); + return s ? *s : NULL; + } + t = soap->tag; + if (!soap_match_tag(soap, t, "xsd:QName")) + { char **s; + *type = SOAP_TYPE__QName; + s = soap_in__QName(soap, NULL, NULL, NULL); + return s ? *s : NULL; + } + } + } + soap->error = SOAP_TAG_MISMATCH; + return NULL; +} + +#ifdef __cplusplus +} +#endif +#endif + +SOAP_FMAC3 int SOAP_FMAC4 soap_ignore_element(struct soap *soap) +{ + if (!soap_peek_element(soap)) + { int t; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unexpected element '%s' in input (level=%u, %d)\n", soap->tag, soap->level, soap->body)); + if (soap->mustUnderstand && !soap->other) + return soap->error = SOAP_MUSTUNDERSTAND; + if (((soap->mode & SOAP_XML_STRICT) && soap->part != SOAP_IN_HEADER) || !soap_match_tag(soap, soap->tag, "SOAP-ENV:")) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "REJECTING element '%s'\n", soap->tag)); + return soap->error = SOAP_TAG_MISMATCH; + } + if (!*soap->id || !soap_getelement(soap, &t)) + { soap->peeked = 0; + if (soap->fignore) + soap->error = soap->fignore(soap, soap->tag); + else + soap->error = SOAP_OK; + DBGLOG(TEST, if (!soap->error) SOAP_MESSAGE(fdebug, "IGNORING element '%s'\n", soap->tag)); + if (!soap->error && soap->body) + { soap->level++; + while (!soap_ignore_element(soap)) + ; + if (soap->error == SOAP_NO_TAG) + soap->error = soap_element_end_in(soap, NULL); + } + } + } + return soap->error; +} + +#ifndef WITH_NOIDREF +SOAP_FMAC3 int SOAP_FMAC4 soap_putindependent(struct soap *soap) +{ + int i; + struct soap_plist *pp; + if (soap->version == 1 && soap->encodingStyle && !(soap->mode & (SOAP_XML_TREE | SOAP_XML_GRAPH))) + for (i = 0; i < SOAP_PTRHASH; i++) + for (pp = soap->pht[i]; pp; pp = pp->next) + if (pp->mark1 == 2 || pp->mark2 == 2) + if (soap_putelement(soap, pp->ptr, "id", pp->id, pp->type)) + return soap->error; + return SOAP_OK; +} +#endif + +#ifndef WITH_NOIDREF + +#ifdef __cplusplus +extern "C" { +#endif +SOAP_FMAC3 int SOAP_FMAC4 soap_putelement(struct soap *soap, const void *ptr, const char *tag, int id, int type) +{ + switch (type) + { + case SOAP_TYPE_byte: + return soap_out_byte(soap, tag, id, (const char *)ptr, "xsd:byte"); + case SOAP_TYPE_int: + return soap_out_int(soap, tag, id, (const int *)ptr, "xsd:int"); + case SOAP_TYPE_ns1__executeCommand: + return soap_out_ns1__executeCommand(soap, tag, id, (const struct ns1__executeCommand *)ptr, "ns1:executeCommand"); + case SOAP_TYPE_ns1__executeCommandResponse: + return soap_out_ns1__executeCommandResponse(soap, tag, id, (const struct ns1__executeCommandResponse *)ptr, "ns1:executeCommandResponse"); + case SOAP_TYPE_PointerTostring: + return soap_out_PointerTostring(soap, tag, id, (char **const*)ptr, "xsd:string"); + case SOAP_TYPE__QName: + return soap_out_string(soap, "xsd:QName", id, (char*const*)&ptr, NULL); + case SOAP_TYPE_string: + return soap_out_string(soap, tag, id, (char*const*)&ptr, "xsd:string"); + } + return SOAP_OK; +} + +#ifdef __cplusplus +} +#endif +#endif + +#ifndef WITH_NOIDREF + +#ifdef __cplusplus +extern "C" { +#endif +SOAP_FMAC3 void SOAP_FMAC4 soap_markelement(struct soap *soap, const void *ptr, int type) +{ + (void)soap; (void)ptr; (void)type; /* appease -Wall -Werror */ + switch (type) + { + case SOAP_TYPE_ns1__executeCommand: + soap_serialize_ns1__executeCommand(soap, (const struct ns1__executeCommand *)ptr); + break; + case SOAP_TYPE_ns1__executeCommandResponse: + soap_serialize_ns1__executeCommandResponse(soap, (const struct ns1__executeCommandResponse *)ptr); + break; + case SOAP_TYPE_PointerTostring: + soap_serialize_PointerTostring(soap, (char **const*)ptr); + break; + case SOAP_TYPE__QName: + soap_serialize_string(soap, (char*const*)&ptr); + break; + case SOAP_TYPE_string: + soap_serialize_string(soap, (char*const*)&ptr); + break; + } +} + +#ifdef __cplusplus +} +#endif +#endif + +SOAP_FMAC3 void * SOAP_FMAC4 soap_instantiate(struct soap *soap, int t, const char *type, const char *arrayType, size_t *n) +{ + switch (t) + { + case SOAP_TYPE_ns1__executeCommandResponse: + return (void*)soap_instantiate_ns1__executeCommandResponse(soap, -1, type, arrayType, n); + case SOAP_TYPE_ns1__executeCommand: + return (void*)soap_instantiate_ns1__executeCommand(soap, -1, type, arrayType, n); +#ifndef WITH_NOGLOBAL + case SOAP_TYPE_SOAP_ENV__Header: + return (void*)soap_instantiate_SOAP_ENV__Header(soap, -1, type, arrayType, n); +#endif +#ifndef WITH_NOGLOBAL + case SOAP_TYPE_SOAP_ENV__Code: + return (void*)soap_instantiate_SOAP_ENV__Code(soap, -1, type, arrayType, n); +#endif +#ifndef WITH_NOGLOBAL + case SOAP_TYPE_SOAP_ENV__Detail: + return (void*)soap_instantiate_SOAP_ENV__Detail(soap, -1, type, arrayType, n); +#endif +#ifndef WITH_NOGLOBAL + case SOAP_TYPE_SOAP_ENV__Reason: + return (void*)soap_instantiate_SOAP_ENV__Reason(soap, -1, type, arrayType, n); +#endif +#ifndef WITH_NOGLOBAL + case SOAP_TYPE_SOAP_ENV__Fault: + return (void*)soap_instantiate_SOAP_ENV__Fault(soap, -1, type, arrayType, n); +#endif + } + return NULL; +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_fdelete(struct soap_clist *p) +{ switch (p->type) + { + case SOAP_TYPE_ns1__executeCommandResponse: + if (p->size < 0) + delete (struct ns1__executeCommandResponse*)p->ptr; + else + delete[] (struct ns1__executeCommandResponse*)p->ptr; + break; + case SOAP_TYPE_ns1__executeCommand: + if (p->size < 0) + delete (struct ns1__executeCommand*)p->ptr; + else + delete[] (struct ns1__executeCommand*)p->ptr; + break; + case SOAP_TYPE_SOAP_ENV__Header: + if (p->size < 0) + delete (struct SOAP_ENV__Header*)p->ptr; + else + delete[] (struct SOAP_ENV__Header*)p->ptr; + break; + case SOAP_TYPE_SOAP_ENV__Code: + if (p->size < 0) + delete (struct SOAP_ENV__Code*)p->ptr; + else + delete[] (struct SOAP_ENV__Code*)p->ptr; + break; + case SOAP_TYPE_SOAP_ENV__Detail: + if (p->size < 0) + delete (struct SOAP_ENV__Detail*)p->ptr; + else + delete[] (struct SOAP_ENV__Detail*)p->ptr; + break; + case SOAP_TYPE_SOAP_ENV__Reason: + if (p->size < 0) + delete (struct SOAP_ENV__Reason*)p->ptr; + else + delete[] (struct SOAP_ENV__Reason*)p->ptr; + break; + case SOAP_TYPE_SOAP_ENV__Fault: + if (p->size < 0) + delete (struct SOAP_ENV__Fault*)p->ptr; + else + delete[] (struct SOAP_ENV__Fault*)p->ptr; + break; + default: return SOAP_ERR; + } + return SOAP_OK; +} + +SOAP_FMAC3 void* SOAP_FMAC4 soap_class_id_enter(struct soap *soap, const char *id, void *p, int t, size_t n, const char *type, const char *arrayType) +{ return soap_id_enter(soap, id, p, t, n, 0, type, arrayType, soap_instantiate); +} + +SOAP_FMAC3 void SOAP_FMAC4 soap_default_byte(struct soap *soap, char *a) +{ (void)soap; /* appease -Wall -Werror */ +#ifdef SOAP_DEFAULT_byte + *a = SOAP_DEFAULT_byte; +#else + *a = (char)0; +#endif +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_put_byte(struct soap *soap, const char *a, const char *tag, const char *type) +{ + register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_byte); + if (soap_out_byte(soap, tag, id, a, type)) + return soap->error; + return soap_putindependent(soap); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_out_byte(struct soap *soap, const char *tag, int id, const char *a, const char *type) +{ + return soap_outbyte(soap, tag, id, a, type, SOAP_TYPE_byte); +} + +SOAP_FMAC3 char * SOAP_FMAC4 soap_get_byte(struct soap *soap, char *p, const char *tag, const char *type) +{ + if ((p = soap_in_byte(soap, tag, p, type))) + if (soap_getindependent(soap)) + return NULL; + return p; +} + +SOAP_FMAC3 char * SOAP_FMAC4 soap_in_byte(struct soap *soap, const char *tag, char *a, const char *type) +{ + return soap_inbyte(soap, tag, a, type, SOAP_TYPE_byte); +} + +SOAP_FMAC3 void SOAP_FMAC4 soap_default_int(struct soap *soap, int *a) +{ (void)soap; /* appease -Wall -Werror */ +#ifdef SOAP_DEFAULT_int + *a = SOAP_DEFAULT_int; +#else + *a = (int)0; +#endif +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_put_int(struct soap *soap, const int *a, const char *tag, const char *type) +{ + register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_int); + if (soap_out_int(soap, tag, id, a, type)) + return soap->error; + return soap_putindependent(soap); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_out_int(struct soap *soap, const char *tag, int id, const int *a, const char *type) +{ + return soap_outint(soap, tag, id, a, type, SOAP_TYPE_int); +} + +SOAP_FMAC3 int * SOAP_FMAC4 soap_get_int(struct soap *soap, int *p, const char *tag, const char *type) +{ + if ((p = soap_in_int(soap, tag, p, type))) + if (soap_getindependent(soap)) + return NULL; + return p; +} + +SOAP_FMAC3 int * SOAP_FMAC4 soap_in_int(struct soap *soap, const char *tag, int *a, const char *type) +{ + return soap_inint(soap, tag, a, type, SOAP_TYPE_int); +} + +#ifndef WITH_NOGLOBAL + +SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Fault(struct soap *soap, struct SOAP_ENV__Fault *a) +{ + (void)soap; (void)a; /* appease -Wall -Werror */ + soap_default__QName(soap, &a->faultcode); + soap_default_string(soap, &a->faultstring); + soap_default_string(soap, &a->faultactor); + a->detail = NULL; + a->SOAP_ENV__Code = NULL; + a->SOAP_ENV__Reason = NULL; + soap_default_string(soap, &a->SOAP_ENV__Node); + soap_default_string(soap, &a->SOAP_ENV__Role); + a->SOAP_ENV__Detail = NULL; +} + +SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Fault(struct soap *soap, const struct SOAP_ENV__Fault *a) +{ + (void)soap; (void)a; /* appease -Wall -Werror */ + soap_serialize__QName(soap, &a->faultcode); + soap_serialize_string(soap, &a->faultstring); + soap_serialize_string(soap, &a->faultactor); + soap_serialize_PointerToSOAP_ENV__Detail(soap, &a->detail); + soap_serialize_PointerToSOAP_ENV__Code(soap, &a->SOAP_ENV__Code); + soap_serialize_PointerToSOAP_ENV__Reason(soap, &a->SOAP_ENV__Reason); + soap_serialize_string(soap, &a->SOAP_ENV__Node); + soap_serialize_string(soap, &a->SOAP_ENV__Role); + soap_serialize_PointerToSOAP_ENV__Detail(soap, &a->SOAP_ENV__Detail); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Fault(struct soap *soap, const struct SOAP_ENV__Fault *a, const char *tag, const char *type) +{ + register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_SOAP_ENV__Fault); + if (soap_out_SOAP_ENV__Fault(soap, tag, id, a, type)) + return soap->error; + return soap_putindependent(soap); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Fault(struct soap *soap, const char *tag, int id, const struct SOAP_ENV__Fault *a, const char *type) +{ + const char *soap_tmp_faultcode = soap_QName2s(soap, a->faultcode); + if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_SOAP_ENV__Fault), type)) + return soap->error; + if (soap_out__QName(soap, "faultcode", -1, (char*const*)&soap_tmp_faultcode, "")) + return soap->error; + if (soap_out_string(soap, "faultstring", -1, &a->faultstring, "")) + return soap->error; + if (soap_out_string(soap, "faultactor", -1, &a->faultactor, "")) + return soap->error; + if (soap_out_PointerToSOAP_ENV__Detail(soap, "detail", -1, &a->detail, "")) + return soap->error; + if (soap_out_PointerToSOAP_ENV__Code(soap, "SOAP-ENV:Code", -1, &a->SOAP_ENV__Code, "")) + return soap->error; + if (soap_out_PointerToSOAP_ENV__Reason(soap, "SOAP-ENV:Reason", -1, &a->SOAP_ENV__Reason, "")) + return soap->error; + if (soap_out_string(soap, "SOAP-ENV:Node", -1, &a->SOAP_ENV__Node, "")) + return soap->error; + if (soap_out_string(soap, "SOAP-ENV:Role", -1, &a->SOAP_ENV__Role, "")) + return soap->error; + if (soap_out_PointerToSOAP_ENV__Detail(soap, "SOAP-ENV:Detail", -1, &a->SOAP_ENV__Detail, "")) + return soap->error; + return soap_element_end_out(soap, tag); +} + +SOAP_FMAC3 struct SOAP_ENV__Fault * SOAP_FMAC4 soap_get_SOAP_ENV__Fault(struct soap *soap, struct SOAP_ENV__Fault *p, const char *tag, const char *type) +{ + if ((p = soap_in_SOAP_ENV__Fault(soap, tag, p, type))) + if (soap_getindependent(soap)) + return NULL; + return p; +} + +SOAP_FMAC3 struct SOAP_ENV__Fault * SOAP_FMAC4 soap_in_SOAP_ENV__Fault(struct soap *soap, const char *tag, struct SOAP_ENV__Fault *a, const char *type) +{ + short soap_flag_faultcode = 1, soap_flag_faultstring = 1, soap_flag_faultactor = 1, soap_flag_detail = 1, soap_flag_SOAP_ENV__Code = 1, soap_flag_SOAP_ENV__Reason = 1, soap_flag_SOAP_ENV__Node = 1, soap_flag_SOAP_ENV__Role = 1, soap_flag_SOAP_ENV__Detail = 1; + if (soap_element_begin_in(soap, tag, 0, type)) + return NULL; + a = (struct SOAP_ENV__Fault *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_SOAP_ENV__Fault, sizeof(struct SOAP_ENV__Fault), 0, NULL, NULL, NULL); + if (!a) + return NULL; + soap_default_SOAP_ENV__Fault(soap, a); + if (soap->body && !*soap->href) + { + for (;;) + { soap->error = SOAP_TAG_MISMATCH; + if (soap_flag_faultcode && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) + if (soap_in__QName(soap, "faultcode", &a->faultcode, "")) + { soap_flag_faultcode--; + continue; + } + if (soap_flag_faultstring && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) + if (soap_in_string(soap, "faultstring", &a->faultstring, "xsd:string")) + { soap_flag_faultstring--; + continue; + } + if (soap_flag_faultactor && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) + if (soap_in_string(soap, "faultactor", &a->faultactor, "xsd:string")) + { soap_flag_faultactor--; + continue; + } + if (soap_flag_detail && soap->error == SOAP_TAG_MISMATCH) + if (soap_in_PointerToSOAP_ENV__Detail(soap, "detail", &a->detail, "")) + { soap_flag_detail--; + continue; + } + if (soap_flag_SOAP_ENV__Code && soap->error == SOAP_TAG_MISMATCH) + if (soap_in_PointerToSOAP_ENV__Code(soap, "SOAP-ENV:Code", &a->SOAP_ENV__Code, "")) + { soap_flag_SOAP_ENV__Code--; + continue; + } + if (soap_flag_SOAP_ENV__Reason && soap->error == SOAP_TAG_MISMATCH) + if (soap_in_PointerToSOAP_ENV__Reason(soap, "SOAP-ENV:Reason", &a->SOAP_ENV__Reason, "")) + { soap_flag_SOAP_ENV__Reason--; + continue; + } + if (soap_flag_SOAP_ENV__Node && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) + if (soap_in_string(soap, "SOAP-ENV:Node", &a->SOAP_ENV__Node, "xsd:string")) + { soap_flag_SOAP_ENV__Node--; + continue; + } + if (soap_flag_SOAP_ENV__Role && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) + if (soap_in_string(soap, "SOAP-ENV:Role", &a->SOAP_ENV__Role, "xsd:string")) + { soap_flag_SOAP_ENV__Role--; + continue; + } + if (soap_flag_SOAP_ENV__Detail && soap->error == SOAP_TAG_MISMATCH) + if (soap_in_PointerToSOAP_ENV__Detail(soap, "SOAP-ENV:Detail", &a->SOAP_ENV__Detail, "")) + { soap_flag_SOAP_ENV__Detail--; + continue; + } + if (soap->error == SOAP_TAG_MISMATCH) + soap->error = soap_ignore_element(soap); + if (soap->error == SOAP_NO_TAG) + break; + if (soap->error) + return NULL; + } + if (soap_element_end_in(soap, tag)) + return NULL; + } + else + { a = (struct SOAP_ENV__Fault *)soap_id_forward(soap, soap->href, (void*)a, 0, SOAP_TYPE_SOAP_ENV__Fault, 0, sizeof(struct SOAP_ENV__Fault), 0, NULL); + if (soap->body && soap_element_end_in(soap, tag)) + return NULL; + } + return a; +} + +SOAP_FMAC5 struct SOAP_ENV__Fault * SOAP_FMAC6 soap_new_SOAP_ENV__Fault(struct soap *soap, int n) +{ return soap_instantiate_SOAP_ENV__Fault(soap, n, NULL, NULL, NULL); +} + +SOAP_FMAC5 void SOAP_FMAC6 soap_delete_SOAP_ENV__Fault(struct soap *soap, struct SOAP_ENV__Fault *p) +{ soap_delete(soap, p); +} + +SOAP_FMAC3 struct SOAP_ENV__Fault * SOAP_FMAC4 soap_instantiate_SOAP_ENV__Fault(struct soap *soap, int n, const char *type, const char *arrayType, size_t *size) +{ + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "soap_instantiate_SOAP_ENV__Fault(%d, %s, %s)\n", n, type?type:"", arrayType?arrayType:"")); + struct soap_clist *cp = soap_link(soap, NULL, SOAP_TYPE_SOAP_ENV__Fault, n, soap_fdelete); + if (!cp) + return NULL; + if (n < 0) + { cp->ptr = (void*)new struct SOAP_ENV__Fault; + if (size) + *size = sizeof(struct SOAP_ENV__Fault); + } + else + { cp->ptr = (void*)new struct SOAP_ENV__Fault[n]; + if (!cp->ptr) + { soap->error = SOAP_EOM; + return NULL; + } + if (size) + *size = n * sizeof(struct SOAP_ENV__Fault); + } + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Instantiated location=%p\n", cp->ptr)); + return (struct SOAP_ENV__Fault*)cp->ptr; +} +SOAP_FMAC3 void SOAP_FMAC4 soap_copy_SOAP_ENV__Fault(struct soap *soap, int st, int tt, void *p, size_t len, const void *q, size_t n) +{ + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copying struct SOAP_ENV__Fault %p -> %p\n", q, p)); + *(struct SOAP_ENV__Fault*)p = *(struct SOAP_ENV__Fault*)q; +} + +#endif + +#ifndef WITH_NOGLOBAL + +SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Reason(struct soap *soap, struct SOAP_ENV__Reason *a) +{ + (void)soap; (void)a; /* appease -Wall -Werror */ + soap_default_string(soap, &a->SOAP_ENV__Text); +} + +SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Reason(struct soap *soap, const struct SOAP_ENV__Reason *a) +{ + (void)soap; (void)a; /* appease -Wall -Werror */ + soap_serialize_string(soap, &a->SOAP_ENV__Text); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Reason(struct soap *soap, const struct SOAP_ENV__Reason *a, const char *tag, const char *type) +{ + register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_SOAP_ENV__Reason); + if (soap_out_SOAP_ENV__Reason(soap, tag, id, a, type)) + return soap->error; + return soap_putindependent(soap); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Reason(struct soap *soap, const char *tag, int id, const struct SOAP_ENV__Reason *a, const char *type) +{ + if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_SOAP_ENV__Reason), type)) + return soap->error; + if (soap_out_string(soap, "SOAP-ENV:Text", -1, &a->SOAP_ENV__Text, "")) + return soap->error; + return soap_element_end_out(soap, tag); +} + +SOAP_FMAC3 struct SOAP_ENV__Reason * SOAP_FMAC4 soap_get_SOAP_ENV__Reason(struct soap *soap, struct SOAP_ENV__Reason *p, const char *tag, const char *type) +{ + if ((p = soap_in_SOAP_ENV__Reason(soap, tag, p, type))) + if (soap_getindependent(soap)) + return NULL; + return p; +} + +SOAP_FMAC3 struct SOAP_ENV__Reason * SOAP_FMAC4 soap_in_SOAP_ENV__Reason(struct soap *soap, const char *tag, struct SOAP_ENV__Reason *a, const char *type) +{ + short soap_flag_SOAP_ENV__Text = 1; + if (soap_element_begin_in(soap, tag, 0, type)) + return NULL; + a = (struct SOAP_ENV__Reason *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_SOAP_ENV__Reason, sizeof(struct SOAP_ENV__Reason), 0, NULL, NULL, NULL); + if (!a) + return NULL; + soap_default_SOAP_ENV__Reason(soap, a); + if (soap->body && !*soap->href) + { + for (;;) + { soap->error = SOAP_TAG_MISMATCH; + if (soap_flag_SOAP_ENV__Text && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) + if (soap_in_string(soap, "SOAP-ENV:Text", &a->SOAP_ENV__Text, "xsd:string")) + { soap_flag_SOAP_ENV__Text--; + continue; + } + if (soap->error == SOAP_TAG_MISMATCH) + soap->error = soap_ignore_element(soap); + if (soap->error == SOAP_NO_TAG) + break; + if (soap->error) + return NULL; + } + if (soap_element_end_in(soap, tag)) + return NULL; + } + else + { a = (struct SOAP_ENV__Reason *)soap_id_forward(soap, soap->href, (void*)a, 0, SOAP_TYPE_SOAP_ENV__Reason, 0, sizeof(struct SOAP_ENV__Reason), 0, NULL); + if (soap->body && soap_element_end_in(soap, tag)) + return NULL; + } + return a; +} + +SOAP_FMAC5 struct SOAP_ENV__Reason * SOAP_FMAC6 soap_new_SOAP_ENV__Reason(struct soap *soap, int n) +{ return soap_instantiate_SOAP_ENV__Reason(soap, n, NULL, NULL, NULL); +} + +SOAP_FMAC5 void SOAP_FMAC6 soap_delete_SOAP_ENV__Reason(struct soap *soap, struct SOAP_ENV__Reason *p) +{ soap_delete(soap, p); +} + +SOAP_FMAC3 struct SOAP_ENV__Reason * SOAP_FMAC4 soap_instantiate_SOAP_ENV__Reason(struct soap *soap, int n, const char *type, const char *arrayType, size_t *size) +{ + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "soap_instantiate_SOAP_ENV__Reason(%d, %s, %s)\n", n, type?type:"", arrayType?arrayType:"")); + struct soap_clist *cp = soap_link(soap, NULL, SOAP_TYPE_SOAP_ENV__Reason, n, soap_fdelete); + if (!cp) + return NULL; + if (n < 0) + { cp->ptr = (void*)new struct SOAP_ENV__Reason; + if (size) + *size = sizeof(struct SOAP_ENV__Reason); + } + else + { cp->ptr = (void*)new struct SOAP_ENV__Reason[n]; + if (!cp->ptr) + { soap->error = SOAP_EOM; + return NULL; + } + if (size) + *size = n * sizeof(struct SOAP_ENV__Reason); + } + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Instantiated location=%p\n", cp->ptr)); + return (struct SOAP_ENV__Reason*)cp->ptr; +} +SOAP_FMAC3 void SOAP_FMAC4 soap_copy_SOAP_ENV__Reason(struct soap *soap, int st, int tt, void *p, size_t len, const void *q, size_t n) +{ + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copying struct SOAP_ENV__Reason %p -> %p\n", q, p)); + *(struct SOAP_ENV__Reason*)p = *(struct SOAP_ENV__Reason*)q; +} + +#endif + +#ifndef WITH_NOGLOBAL + +SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Detail(struct soap *soap, struct SOAP_ENV__Detail *a) +{ + (void)soap; (void)a; /* appease -Wall -Werror */ + a->__type = 0; + a->fault = NULL; + a->__any = NULL; +} + +SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Detail(struct soap *soap, const struct SOAP_ENV__Detail *a) +{ + (void)soap; (void)a; /* appease -Wall -Werror */ + soap_markelement(soap, a->fault, a->__type); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Detail(struct soap *soap, const struct SOAP_ENV__Detail *a, const char *tag, const char *type) +{ + register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_SOAP_ENV__Detail); + if (soap_out_SOAP_ENV__Detail(soap, tag, id, a, type)) + return soap->error; + return soap_putindependent(soap); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Detail(struct soap *soap, const char *tag, int id, const struct SOAP_ENV__Detail *a, const char *type) +{ + if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_SOAP_ENV__Detail), type)) + return soap->error; + if (soap_putelement(soap, a->fault, "fault", -1, a->__type)) + return soap->error; + soap_outliteral(soap, "-any", &a->__any, NULL); + return soap_element_end_out(soap, tag); +} + +SOAP_FMAC3 struct SOAP_ENV__Detail * SOAP_FMAC4 soap_get_SOAP_ENV__Detail(struct soap *soap, struct SOAP_ENV__Detail *p, const char *tag, const char *type) +{ + if ((p = soap_in_SOAP_ENV__Detail(soap, tag, p, type))) + if (soap_getindependent(soap)) + return NULL; + return p; +} + +SOAP_FMAC3 struct SOAP_ENV__Detail * SOAP_FMAC4 soap_in_SOAP_ENV__Detail(struct soap *soap, const char *tag, struct SOAP_ENV__Detail *a, const char *type) +{ + short soap_flag_fault = 1, soap_flag___any = 1; + if (soap_element_begin_in(soap, tag, 0, type)) + return NULL; + a = (struct SOAP_ENV__Detail *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_SOAP_ENV__Detail, sizeof(struct SOAP_ENV__Detail), 0, NULL, NULL, NULL); + if (!a) + return NULL; + soap_default_SOAP_ENV__Detail(soap, a); + if (soap->body && !*soap->href) + { + for (;;) + { soap->error = SOAP_TAG_MISMATCH; + if (soap_flag_fault && soap->error == SOAP_TAG_MISMATCH) + if ((a->fault = soap_getelement(soap, &a->__type))) + { soap_flag_fault = 0; + continue; + } + if (soap_flag___any && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) + if (soap_inliteral(soap, "-any", &a->__any)) + { soap_flag___any--; + continue; + } + if (soap->error == SOAP_TAG_MISMATCH) + soap->error = soap_ignore_element(soap); + if (soap->error == SOAP_NO_TAG) + break; + if (soap->error) + return NULL; + } + if (soap_element_end_in(soap, tag)) + return NULL; + } + else + { a = (struct SOAP_ENV__Detail *)soap_id_forward(soap, soap->href, (void*)a, 0, SOAP_TYPE_SOAP_ENV__Detail, 0, sizeof(struct SOAP_ENV__Detail), 0, NULL); + if (soap->body && soap_element_end_in(soap, tag)) + return NULL; + } + return a; +} + +SOAP_FMAC5 struct SOAP_ENV__Detail * SOAP_FMAC6 soap_new_SOAP_ENV__Detail(struct soap *soap, int n) +{ return soap_instantiate_SOAP_ENV__Detail(soap, n, NULL, NULL, NULL); +} + +SOAP_FMAC5 void SOAP_FMAC6 soap_delete_SOAP_ENV__Detail(struct soap *soap, struct SOAP_ENV__Detail *p) +{ soap_delete(soap, p); +} + +SOAP_FMAC3 struct SOAP_ENV__Detail * SOAP_FMAC4 soap_instantiate_SOAP_ENV__Detail(struct soap *soap, int n, const char *type, const char *arrayType, size_t *size) +{ + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "soap_instantiate_SOAP_ENV__Detail(%d, %s, %s)\n", n, type?type:"", arrayType?arrayType:"")); + struct soap_clist *cp = soap_link(soap, NULL, SOAP_TYPE_SOAP_ENV__Detail, n, soap_fdelete); + if (!cp) + return NULL; + if (n < 0) + { cp->ptr = (void*)new struct SOAP_ENV__Detail; + if (size) + *size = sizeof(struct SOAP_ENV__Detail); + } + else + { cp->ptr = (void*)new struct SOAP_ENV__Detail[n]; + if (!cp->ptr) + { soap->error = SOAP_EOM; + return NULL; + } + if (size) + *size = n * sizeof(struct SOAP_ENV__Detail); + } + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Instantiated location=%p\n", cp->ptr)); + return (struct SOAP_ENV__Detail*)cp->ptr; +} +SOAP_FMAC3 void SOAP_FMAC4 soap_copy_SOAP_ENV__Detail(struct soap *soap, int st, int tt, void *p, size_t len, const void *q, size_t n) +{ + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copying struct SOAP_ENV__Detail %p -> %p\n", q, p)); + *(struct SOAP_ENV__Detail*)p = *(struct SOAP_ENV__Detail*)q; +} + +#endif + +#ifndef WITH_NOGLOBAL + +SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Code(struct soap *soap, struct SOAP_ENV__Code *a) +{ + (void)soap; (void)a; /* appease -Wall -Werror */ + soap_default__QName(soap, &a->SOAP_ENV__Value); + a->SOAP_ENV__Subcode = NULL; +} + +SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Code(struct soap *soap, const struct SOAP_ENV__Code *a) +{ + (void)soap; (void)a; /* appease -Wall -Werror */ + soap_serialize__QName(soap, &a->SOAP_ENV__Value); + soap_serialize_PointerToSOAP_ENV__Code(soap, &a->SOAP_ENV__Subcode); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Code(struct soap *soap, const struct SOAP_ENV__Code *a, const char *tag, const char *type) +{ + register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_SOAP_ENV__Code); + if (soap_out_SOAP_ENV__Code(soap, tag, id, a, type)) + return soap->error; + return soap_putindependent(soap); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Code(struct soap *soap, const char *tag, int id, const struct SOAP_ENV__Code *a, const char *type) +{ + const char *soap_tmp_SOAP_ENV__Value = soap_QName2s(soap, a->SOAP_ENV__Value); + if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_SOAP_ENV__Code), type)) + return soap->error; + if (soap_out__QName(soap, "SOAP-ENV:Value", -1, (char*const*)&soap_tmp_SOAP_ENV__Value, "")) + return soap->error; + if (soap_out_PointerToSOAP_ENV__Code(soap, "SOAP-ENV:Subcode", -1, &a->SOAP_ENV__Subcode, "")) + return soap->error; + return soap_element_end_out(soap, tag); +} + +SOAP_FMAC3 struct SOAP_ENV__Code * SOAP_FMAC4 soap_get_SOAP_ENV__Code(struct soap *soap, struct SOAP_ENV__Code *p, const char *tag, const char *type) +{ + if ((p = soap_in_SOAP_ENV__Code(soap, tag, p, type))) + if (soap_getindependent(soap)) + return NULL; + return p; +} + +SOAP_FMAC3 struct SOAP_ENV__Code * SOAP_FMAC4 soap_in_SOAP_ENV__Code(struct soap *soap, const char *tag, struct SOAP_ENV__Code *a, const char *type) +{ + short soap_flag_SOAP_ENV__Value = 1, soap_flag_SOAP_ENV__Subcode = 1; + if (soap_element_begin_in(soap, tag, 0, type)) + return NULL; + a = (struct SOAP_ENV__Code *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_SOAP_ENV__Code, sizeof(struct SOAP_ENV__Code), 0, NULL, NULL, NULL); + if (!a) + return NULL; + soap_default_SOAP_ENV__Code(soap, a); + if (soap->body && !*soap->href) + { + for (;;) + { soap->error = SOAP_TAG_MISMATCH; + if (soap_flag_SOAP_ENV__Value && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) + if (soap_in__QName(soap, "SOAP-ENV:Value", &a->SOAP_ENV__Value, "")) + { soap_flag_SOAP_ENV__Value--; + continue; + } + if (soap_flag_SOAP_ENV__Subcode && soap->error == SOAP_TAG_MISMATCH) + if (soap_in_PointerToSOAP_ENV__Code(soap, "SOAP-ENV:Subcode", &a->SOAP_ENV__Subcode, "")) + { soap_flag_SOAP_ENV__Subcode--; + continue; + } + if (soap->error == SOAP_TAG_MISMATCH) + soap->error = soap_ignore_element(soap); + if (soap->error == SOAP_NO_TAG) + break; + if (soap->error) + return NULL; + } + if (soap_element_end_in(soap, tag)) + return NULL; + } + else + { a = (struct SOAP_ENV__Code *)soap_id_forward(soap, soap->href, (void*)a, 0, SOAP_TYPE_SOAP_ENV__Code, 0, sizeof(struct SOAP_ENV__Code), 0, NULL); + if (soap->body && soap_element_end_in(soap, tag)) + return NULL; + } + return a; +} + +SOAP_FMAC5 struct SOAP_ENV__Code * SOAP_FMAC6 soap_new_SOAP_ENV__Code(struct soap *soap, int n) +{ return soap_instantiate_SOAP_ENV__Code(soap, n, NULL, NULL, NULL); +} + +SOAP_FMAC5 void SOAP_FMAC6 soap_delete_SOAP_ENV__Code(struct soap *soap, struct SOAP_ENV__Code *p) +{ soap_delete(soap, p); +} + +SOAP_FMAC3 struct SOAP_ENV__Code * SOAP_FMAC4 soap_instantiate_SOAP_ENV__Code(struct soap *soap, int n, const char *type, const char *arrayType, size_t *size) +{ + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "soap_instantiate_SOAP_ENV__Code(%d, %s, %s)\n", n, type?type:"", arrayType?arrayType:"")); + struct soap_clist *cp = soap_link(soap, NULL, SOAP_TYPE_SOAP_ENV__Code, n, soap_fdelete); + if (!cp) + return NULL; + if (n < 0) + { cp->ptr = (void*)new struct SOAP_ENV__Code; + if (size) + *size = sizeof(struct SOAP_ENV__Code); + } + else + { cp->ptr = (void*)new struct SOAP_ENV__Code[n]; + if (!cp->ptr) + { soap->error = SOAP_EOM; + return NULL; + } + if (size) + *size = n * sizeof(struct SOAP_ENV__Code); + } + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Instantiated location=%p\n", cp->ptr)); + return (struct SOAP_ENV__Code*)cp->ptr; +} +SOAP_FMAC3 void SOAP_FMAC4 soap_copy_SOAP_ENV__Code(struct soap *soap, int st, int tt, void *p, size_t len, const void *q, size_t n) +{ + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copying struct SOAP_ENV__Code %p -> %p\n", q, p)); + *(struct SOAP_ENV__Code*)p = *(struct SOAP_ENV__Code*)q; +} + +#endif + +#ifndef WITH_NOGLOBAL + +SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Header(struct soap *soap, struct SOAP_ENV__Header *a) +{ + (void)soap; (void)a; /* appease -Wall -Werror */ +} + +SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Header(struct soap *soap, const struct SOAP_ENV__Header *a) +{ + (void)soap; (void)a; /* appease -Wall -Werror */ +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Header(struct soap *soap, const struct SOAP_ENV__Header *a, const char *tag, const char *type) +{ + register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_SOAP_ENV__Header); + if (soap_out_SOAP_ENV__Header(soap, tag, id, a, type)) + return soap->error; + return soap_putindependent(soap); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Header(struct soap *soap, const char *tag, int id, const struct SOAP_ENV__Header *a, const char *type) +{ + if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_SOAP_ENV__Header), type)) + return soap->error; + return soap_element_end_out(soap, tag); +} + +SOAP_FMAC3 struct SOAP_ENV__Header * SOAP_FMAC4 soap_get_SOAP_ENV__Header(struct soap *soap, struct SOAP_ENV__Header *p, const char *tag, const char *type) +{ + if ((p = soap_in_SOAP_ENV__Header(soap, tag, p, type))) + if (soap_getindependent(soap)) + return NULL; + return p; +} + +SOAP_FMAC3 struct SOAP_ENV__Header * SOAP_FMAC4 soap_in_SOAP_ENV__Header(struct soap *soap, const char *tag, struct SOAP_ENV__Header *a, const char *type) +{ + if (soap_element_begin_in(soap, tag, 0, type)) + return NULL; + a = (struct SOAP_ENV__Header *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_SOAP_ENV__Header, sizeof(struct SOAP_ENV__Header), 0, NULL, NULL, NULL); + if (!a) + return NULL; + soap_default_SOAP_ENV__Header(soap, a); + if (soap->body && !*soap->href) + { + for (;;) + { soap->error = SOAP_TAG_MISMATCH; + if (soap->error == SOAP_TAG_MISMATCH) + soap->error = soap_ignore_element(soap); + if (soap->error == SOAP_NO_TAG) + break; + if (soap->error) + return NULL; + } + if (soap_element_end_in(soap, tag)) + return NULL; + } + else + { a = (struct SOAP_ENV__Header *)soap_id_forward(soap, soap->href, (void*)a, 0, SOAP_TYPE_SOAP_ENV__Header, 0, sizeof(struct SOAP_ENV__Header), 0, NULL); + if (soap->body && soap_element_end_in(soap, tag)) + return NULL; + } + return a; +} + +SOAP_FMAC5 struct SOAP_ENV__Header * SOAP_FMAC6 soap_new_SOAP_ENV__Header(struct soap *soap, int n) +{ return soap_instantiate_SOAP_ENV__Header(soap, n, NULL, NULL, NULL); +} + +SOAP_FMAC5 void SOAP_FMAC6 soap_delete_SOAP_ENV__Header(struct soap *soap, struct SOAP_ENV__Header *p) +{ soap_delete(soap, p); +} + +SOAP_FMAC3 struct SOAP_ENV__Header * SOAP_FMAC4 soap_instantiate_SOAP_ENV__Header(struct soap *soap, int n, const char *type, const char *arrayType, size_t *size) +{ + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "soap_instantiate_SOAP_ENV__Header(%d, %s, %s)\n", n, type?type:"", arrayType?arrayType:"")); + struct soap_clist *cp = soap_link(soap, NULL, SOAP_TYPE_SOAP_ENV__Header, n, soap_fdelete); + if (!cp) + return NULL; + if (n < 0) + { cp->ptr = (void*)new struct SOAP_ENV__Header; + if (size) + *size = sizeof(struct SOAP_ENV__Header); + } + else + { cp->ptr = (void*)new struct SOAP_ENV__Header[n]; + if (!cp->ptr) + { soap->error = SOAP_EOM; + return NULL; + } + if (size) + *size = n * sizeof(struct SOAP_ENV__Header); + } + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Instantiated location=%p\n", cp->ptr)); + return (struct SOAP_ENV__Header*)cp->ptr; +} +SOAP_FMAC3 void SOAP_FMAC4 soap_copy_SOAP_ENV__Header(struct soap *soap, int st, int tt, void *p, size_t len, const void *q, size_t n) +{ + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copying struct SOAP_ENV__Header %p -> %p\n", q, p)); + *(struct SOAP_ENV__Header*)p = *(struct SOAP_ENV__Header*)q; +} + +#endif + +SOAP_FMAC3 void SOAP_FMAC4 soap_default_ns1__executeCommand(struct soap *soap, struct ns1__executeCommand *a) +{ + (void)soap; (void)a; /* appease -Wall -Werror */ + soap_default_string(soap, &a->command); +} + +SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_ns1__executeCommand(struct soap *soap, const struct ns1__executeCommand *a) +{ + (void)soap; (void)a; /* appease -Wall -Werror */ + soap_serialize_string(soap, &a->command); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_put_ns1__executeCommand(struct soap *soap, const struct ns1__executeCommand *a, const char *tag, const char *type) +{ + register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_ns1__executeCommand); + if (soap_out_ns1__executeCommand(soap, tag, id, a, type)) + return soap->error; + return soap_putindependent(soap); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_out_ns1__executeCommand(struct soap *soap, const char *tag, int id, const struct ns1__executeCommand *a, const char *type) +{ + if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_ns1__executeCommand), type)) + return soap->error; + if (soap_out_string(soap, "command", -1, &a->command, "")) + return soap->error; + return soap_element_end_out(soap, tag); +} + +SOAP_FMAC3 struct ns1__executeCommand * SOAP_FMAC4 soap_get_ns1__executeCommand(struct soap *soap, struct ns1__executeCommand *p, const char *tag, const char *type) +{ + if ((p = soap_in_ns1__executeCommand(soap, tag, p, type))) + if (soap_getindependent(soap)) + return NULL; + return p; +} + +SOAP_FMAC3 struct ns1__executeCommand * SOAP_FMAC4 soap_in_ns1__executeCommand(struct soap *soap, const char *tag, struct ns1__executeCommand *a, const char *type) +{ + short soap_flag_command = 1; + if (soap_element_begin_in(soap, tag, 0, type)) + return NULL; + a = (struct ns1__executeCommand *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_ns1__executeCommand, sizeof(struct ns1__executeCommand), 0, NULL, NULL, NULL); + if (!a) + return NULL; + soap_default_ns1__executeCommand(soap, a); + if (soap->body && !*soap->href) + { + for (;;) + { soap->error = SOAP_TAG_MISMATCH; + if (soap_flag_command && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) + if (soap_in_string(soap, "command", &a->command, "xsd:string")) + { soap_flag_command--; + continue; + } + if (soap->error == SOAP_TAG_MISMATCH) + soap->error = soap_ignore_element(soap); + if (soap->error == SOAP_NO_TAG) + break; + if (soap->error) + return NULL; + } + if (soap_element_end_in(soap, tag)) + return NULL; + } + else + { a = (struct ns1__executeCommand *)soap_id_forward(soap, soap->href, (void*)a, 0, SOAP_TYPE_ns1__executeCommand, 0, sizeof(struct ns1__executeCommand), 0, NULL); + if (soap->body && soap_element_end_in(soap, tag)) + return NULL; + } + return a; +} + +SOAP_FMAC5 struct ns1__executeCommand * SOAP_FMAC6 soap_new_ns1__executeCommand(struct soap *soap, int n) +{ return soap_instantiate_ns1__executeCommand(soap, n, NULL, NULL, NULL); +} + +SOAP_FMAC5 void SOAP_FMAC6 soap_delete_ns1__executeCommand(struct soap *soap, struct ns1__executeCommand *p) +{ soap_delete(soap, p); +} + +SOAP_FMAC3 struct ns1__executeCommand * SOAP_FMAC4 soap_instantiate_ns1__executeCommand(struct soap *soap, int n, const char *type, const char *arrayType, size_t *size) +{ + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "soap_instantiate_ns1__executeCommand(%d, %s, %s)\n", n, type?type:"", arrayType?arrayType:"")); + struct soap_clist *cp = soap_link(soap, NULL, SOAP_TYPE_ns1__executeCommand, n, soap_fdelete); + if (!cp) + return NULL; + if (n < 0) + { cp->ptr = (void*)new struct ns1__executeCommand; + if (size) + *size = sizeof(struct ns1__executeCommand); + } + else + { cp->ptr = (void*)new struct ns1__executeCommand[n]; + if (!cp->ptr) + { soap->error = SOAP_EOM; + return NULL; + } + if (size) + *size = n * sizeof(struct ns1__executeCommand); + } + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Instantiated location=%p\n", cp->ptr)); + return (struct ns1__executeCommand*)cp->ptr; +} +SOAP_FMAC3 void SOAP_FMAC4 soap_copy_ns1__executeCommand(struct soap *soap, int st, int tt, void *p, size_t len, const void *q, size_t n) +{ + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copying struct ns1__executeCommand %p -> %p\n", q, p)); + *(struct ns1__executeCommand*)p = *(struct ns1__executeCommand*)q; +} + +SOAP_FMAC3 void SOAP_FMAC4 soap_default_ns1__executeCommandResponse(struct soap *soap, struct ns1__executeCommandResponse *a) +{ + (void)soap; (void)a; /* appease -Wall -Werror */ + a->result = NULL; +} + +SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_ns1__executeCommandResponse(struct soap *soap, const struct ns1__executeCommandResponse *a) +{ + (void)soap; (void)a; /* appease -Wall -Werror */ + soap_serialize_PointerTostring(soap, &a->result); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_put_ns1__executeCommandResponse(struct soap *soap, const struct ns1__executeCommandResponse *a, const char *tag, const char *type) +{ + register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_ns1__executeCommandResponse); + if (soap_out_ns1__executeCommandResponse(soap, tag, id, a, type)) + return soap->error; + return soap_putindependent(soap); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_out_ns1__executeCommandResponse(struct soap *soap, const char *tag, int id, const struct ns1__executeCommandResponse *a, const char *type) +{ + if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_ns1__executeCommandResponse), type)) + return soap->error; + if (soap_out_PointerTostring(soap, "result", -1, &a->result, "")) + return soap->error; + return soap_element_end_out(soap, tag); +} + +SOAP_FMAC3 struct ns1__executeCommandResponse * SOAP_FMAC4 soap_get_ns1__executeCommandResponse(struct soap *soap, struct ns1__executeCommandResponse *p, const char *tag, const char *type) +{ + if ((p = soap_in_ns1__executeCommandResponse(soap, tag, p, type))) + if (soap_getindependent(soap)) + return NULL; + return p; +} + +SOAP_FMAC3 struct ns1__executeCommandResponse * SOAP_FMAC4 soap_in_ns1__executeCommandResponse(struct soap *soap, const char *tag, struct ns1__executeCommandResponse *a, const char *type) +{ + short soap_flag_result = 1; + if (soap_element_begin_in(soap, tag, 0, type)) + return NULL; + a = (struct ns1__executeCommandResponse *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_ns1__executeCommandResponse, sizeof(struct ns1__executeCommandResponse), 0, NULL, NULL, NULL); + if (!a) + return NULL; + soap_default_ns1__executeCommandResponse(soap, a); + if (soap->body && !*soap->href) + { + for (;;) + { soap->error = SOAP_TAG_MISMATCH; + if (soap_flag_result && soap->error == SOAP_TAG_MISMATCH) + if (soap_in_PointerTostring(soap, "result", &a->result, "xsd:string")) + { soap_flag_result--; + continue; + } + if (soap->error == SOAP_TAG_MISMATCH) + soap->error = soap_ignore_element(soap); + if (soap->error == SOAP_NO_TAG) + break; + if (soap->error) + return NULL; + } + if (soap_element_end_in(soap, tag)) + return NULL; + } + else + { a = (struct ns1__executeCommandResponse *)soap_id_forward(soap, soap->href, (void*)a, 0, SOAP_TYPE_ns1__executeCommandResponse, 0, sizeof(struct ns1__executeCommandResponse), 0, NULL); + if (soap->body && soap_element_end_in(soap, tag)) + return NULL; + } + return a; +} + +SOAP_FMAC5 struct ns1__executeCommandResponse * SOAP_FMAC6 soap_new_ns1__executeCommandResponse(struct soap *soap, int n) +{ return soap_instantiate_ns1__executeCommandResponse(soap, n, NULL, NULL, NULL); +} + +SOAP_FMAC5 void SOAP_FMAC6 soap_delete_ns1__executeCommandResponse(struct soap *soap, struct ns1__executeCommandResponse *p) +{ soap_delete(soap, p); +} + +SOAP_FMAC3 struct ns1__executeCommandResponse * SOAP_FMAC4 soap_instantiate_ns1__executeCommandResponse(struct soap *soap, int n, const char *type, const char *arrayType, size_t *size) +{ + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "soap_instantiate_ns1__executeCommandResponse(%d, %s, %s)\n", n, type?type:"", arrayType?arrayType:"")); + struct soap_clist *cp = soap_link(soap, NULL, SOAP_TYPE_ns1__executeCommandResponse, n, soap_fdelete); + if (!cp) + return NULL; + if (n < 0) + { cp->ptr = (void*)new struct ns1__executeCommandResponse; + if (size) + *size = sizeof(struct ns1__executeCommandResponse); + } + else + { cp->ptr = (void*)new struct ns1__executeCommandResponse[n]; + if (!cp->ptr) + { soap->error = SOAP_EOM; + return NULL; + } + if (size) + *size = n * sizeof(struct ns1__executeCommandResponse); + } + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Instantiated location=%p\n", cp->ptr)); + return (struct ns1__executeCommandResponse*)cp->ptr; +} +SOAP_FMAC3 void SOAP_FMAC4 soap_copy_ns1__executeCommandResponse(struct soap *soap, int st, int tt, void *p, size_t len, const void *q, size_t n) +{ + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copying struct ns1__executeCommandResponse %p -> %p\n", q, p)); + *(struct ns1__executeCommandResponse*)p = *(struct ns1__executeCommandResponse*)q; +} + +#ifndef WITH_NOGLOBAL + +SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerToSOAP_ENV__Reason(struct soap *soap, struct SOAP_ENV__Reason *const*a) +{ + if (!soap_reference(soap, *a, SOAP_TYPE_SOAP_ENV__Reason)) + soap_serialize_SOAP_ENV__Reason(soap, *a); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerToSOAP_ENV__Reason(struct soap *soap, struct SOAP_ENV__Reason *const*a, const char *tag, const char *type) +{ + register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_PointerToSOAP_ENV__Reason); + if (soap_out_PointerToSOAP_ENV__Reason(soap, tag, id, a, type)) + return soap->error; + return soap_putindependent(soap); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerToSOAP_ENV__Reason(struct soap *soap, const char *tag, int id, struct SOAP_ENV__Reason *const*a, const char *type) +{ + id = soap_element_id(soap, tag, id, *a, NULL, 0, type, SOAP_TYPE_SOAP_ENV__Reason); + if (id < 0) + return soap->error; + return soap_out_SOAP_ENV__Reason(soap, tag, id, *a, type); +} + +SOAP_FMAC3 struct SOAP_ENV__Reason ** SOAP_FMAC4 soap_get_PointerToSOAP_ENV__Reason(struct soap *soap, struct SOAP_ENV__Reason **p, const char *tag, const char *type) +{ + if ((p = soap_in_PointerToSOAP_ENV__Reason(soap, tag, p, type))) + if (soap_getindependent(soap)) + return NULL; + return p; +} + +SOAP_FMAC3 struct SOAP_ENV__Reason ** SOAP_FMAC4 soap_in_PointerToSOAP_ENV__Reason(struct soap *soap, const char *tag, struct SOAP_ENV__Reason **a, const char *type) +{ + if (soap_element_begin_in(soap, tag, 1, NULL)) + return NULL; + if (!a) + if (!(a = (struct SOAP_ENV__Reason **)soap_malloc(soap, sizeof(struct SOAP_ENV__Reason *)))) + return NULL; + *a = NULL; + if (!soap->null && *soap->href != '#') + { soap_revert(soap); + if (!(*a = soap_in_SOAP_ENV__Reason(soap, tag, *a, type))) + return NULL; + } + else + { a = (struct SOAP_ENV__Reason **)soap_id_lookup(soap, soap->href, (void**)a, SOAP_TYPE_SOAP_ENV__Reason, sizeof(struct SOAP_ENV__Reason), 0); + if (soap->body && soap_element_end_in(soap, tag)) + return NULL; + } + return a; +} + +#endif + +#ifndef WITH_NOGLOBAL + +SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerToSOAP_ENV__Detail(struct soap *soap, struct SOAP_ENV__Detail *const*a) +{ + if (!soap_reference(soap, *a, SOAP_TYPE_SOAP_ENV__Detail)) + soap_serialize_SOAP_ENV__Detail(soap, *a); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerToSOAP_ENV__Detail(struct soap *soap, struct SOAP_ENV__Detail *const*a, const char *tag, const char *type) +{ + register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_PointerToSOAP_ENV__Detail); + if (soap_out_PointerToSOAP_ENV__Detail(soap, tag, id, a, type)) + return soap->error; + return soap_putindependent(soap); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerToSOAP_ENV__Detail(struct soap *soap, const char *tag, int id, struct SOAP_ENV__Detail *const*a, const char *type) +{ + id = soap_element_id(soap, tag, id, *a, NULL, 0, type, SOAP_TYPE_SOAP_ENV__Detail); + if (id < 0) + return soap->error; + return soap_out_SOAP_ENV__Detail(soap, tag, id, *a, type); +} + +SOAP_FMAC3 struct SOAP_ENV__Detail ** SOAP_FMAC4 soap_get_PointerToSOAP_ENV__Detail(struct soap *soap, struct SOAP_ENV__Detail **p, const char *tag, const char *type) +{ + if ((p = soap_in_PointerToSOAP_ENV__Detail(soap, tag, p, type))) + if (soap_getindependent(soap)) + return NULL; + return p; +} + +SOAP_FMAC3 struct SOAP_ENV__Detail ** SOAP_FMAC4 soap_in_PointerToSOAP_ENV__Detail(struct soap *soap, const char *tag, struct SOAP_ENV__Detail **a, const char *type) +{ + if (soap_element_begin_in(soap, tag, 1, NULL)) + return NULL; + if (!a) + if (!(a = (struct SOAP_ENV__Detail **)soap_malloc(soap, sizeof(struct SOAP_ENV__Detail *)))) + return NULL; + *a = NULL; + if (!soap->null && *soap->href != '#') + { soap_revert(soap); + if (!(*a = soap_in_SOAP_ENV__Detail(soap, tag, *a, type))) + return NULL; + } + else + { a = (struct SOAP_ENV__Detail **)soap_id_lookup(soap, soap->href, (void**)a, SOAP_TYPE_SOAP_ENV__Detail, sizeof(struct SOAP_ENV__Detail), 0); + if (soap->body && soap_element_end_in(soap, tag)) + return NULL; + } + return a; +} + +#endif + +#ifndef WITH_NOGLOBAL + +SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerToSOAP_ENV__Code(struct soap *soap, struct SOAP_ENV__Code *const*a) +{ + if (!soap_reference(soap, *a, SOAP_TYPE_SOAP_ENV__Code)) + soap_serialize_SOAP_ENV__Code(soap, *a); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerToSOAP_ENV__Code(struct soap *soap, struct SOAP_ENV__Code *const*a, const char *tag, const char *type) +{ + register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_PointerToSOAP_ENV__Code); + if (soap_out_PointerToSOAP_ENV__Code(soap, tag, id, a, type)) + return soap->error; + return soap_putindependent(soap); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerToSOAP_ENV__Code(struct soap *soap, const char *tag, int id, struct SOAP_ENV__Code *const*a, const char *type) +{ + id = soap_element_id(soap, tag, id, *a, NULL, 0, type, SOAP_TYPE_SOAP_ENV__Code); + if (id < 0) + return soap->error; + return soap_out_SOAP_ENV__Code(soap, tag, id, *a, type); +} + +SOAP_FMAC3 struct SOAP_ENV__Code ** SOAP_FMAC4 soap_get_PointerToSOAP_ENV__Code(struct soap *soap, struct SOAP_ENV__Code **p, const char *tag, const char *type) +{ + if ((p = soap_in_PointerToSOAP_ENV__Code(soap, tag, p, type))) + if (soap_getindependent(soap)) + return NULL; + return p; +} + +SOAP_FMAC3 struct SOAP_ENV__Code ** SOAP_FMAC4 soap_in_PointerToSOAP_ENV__Code(struct soap *soap, const char *tag, struct SOAP_ENV__Code **a, const char *type) +{ + if (soap_element_begin_in(soap, tag, 1, NULL)) + return NULL; + if (!a) + if (!(a = (struct SOAP_ENV__Code **)soap_malloc(soap, sizeof(struct SOAP_ENV__Code *)))) + return NULL; + *a = NULL; + if (!soap->null && *soap->href != '#') + { soap_revert(soap); + if (!(*a = soap_in_SOAP_ENV__Code(soap, tag, *a, type))) + return NULL; + } + else + { a = (struct SOAP_ENV__Code **)soap_id_lookup(soap, soap->href, (void**)a, SOAP_TYPE_SOAP_ENV__Code, sizeof(struct SOAP_ENV__Code), 0); + if (soap->body && soap_element_end_in(soap, tag)) + return NULL; + } + return a; +} + +#endif + +SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerTostring(struct soap *soap, char **const*a) +{ + if (!soap_reference(soap, *a, SOAP_TYPE_string)) + soap_serialize_string(soap, *a); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerTostring(struct soap *soap, char **const*a, const char *tag, const char *type) +{ + register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_PointerTostring); + if (soap_out_PointerTostring(soap, tag, id, a, type)) + return soap->error; + return soap_putindependent(soap); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerTostring(struct soap *soap, const char *tag, int id, char **const*a, const char *type) +{ + id = soap_element_id(soap, tag, id, *a, NULL, 0, type, SOAP_TYPE_string); + if (id < 0) + return soap->error; + return soap_out_string(soap, tag, id, *a, type); +} + +SOAP_FMAC3 char *** SOAP_FMAC4 soap_get_PointerTostring(struct soap *soap, char ***p, const char *tag, const char *type) +{ + if ((p = soap_in_PointerTostring(soap, tag, p, type))) + if (soap_getindependent(soap)) + return NULL; + return p; +} + +SOAP_FMAC3 char *** SOAP_FMAC4 soap_in_PointerTostring(struct soap *soap, const char *tag, char ***a, const char *type) +{ + if (soap_element_begin_in(soap, tag, 1, NULL)) + return NULL; + if (!a) + if (!(a = (char ***)soap_malloc(soap, sizeof(char **)))) + return NULL; + *a = NULL; + if (!soap->null && *soap->href != '#') + { soap_revert(soap); + if (!(*a = soap_in_string(soap, tag, *a, type))) + return NULL; + } + else + { a = (char ***)soap_id_lookup(soap, soap->href, (void**)a, SOAP_TYPE_string, sizeof(char *), 1); + if (soap->body && soap_element_end_in(soap, tag)) + return NULL; + } + return a; +} + +SOAP_FMAC3 void SOAP_FMAC4 soap_default__QName(struct soap *soap, char **a) +{ soap_default_string(soap, a); +} + +SOAP_FMAC3 void SOAP_FMAC4 soap_serialize__QName(struct soap *soap, char *const*a) +{ soap_serialize_string(soap, a); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_put__QName(struct soap *soap, char *const*a, const char *tag, const char *type) +{ + register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE__QName); + if (soap_out__QName(soap, tag, id, a, type)) + return soap->error; + return soap_putindependent(soap); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_out__QName(struct soap *soap, const char *tag, int id, char *const*a, const char *type) +{ + return soap_outstring(soap, tag, id, a, type, SOAP_TYPE__QName); +} + +SOAP_FMAC3 char ** SOAP_FMAC4 soap_get__QName(struct soap *soap, char **p, const char *tag, const char *type) +{ + if ((p = soap_in__QName(soap, tag, p, type))) + if (soap_getindependent(soap)) + return NULL; + return p; +} + +SOAP_FMAC3 char * * SOAP_FMAC4 soap_in__QName(struct soap *soap, const char *tag, char **a, const char *type) +{ + return soap_instring(soap, tag, a, type, SOAP_TYPE__QName, 2, -1, -1); +} + +SOAP_FMAC3 void SOAP_FMAC4 soap_default_string(struct soap *soap, char **a) +{ (void)soap; /* appease -Wall -Werror */ +#ifdef SOAP_DEFAULT_string + *a = SOAP_DEFAULT_string; +#else + *a = (char *)0; +#endif +} + +SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_string(struct soap *soap, char *const*a) +{ + soap_reference(soap, *a, SOAP_TYPE_string); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_put_string(struct soap *soap, char *const*a, const char *tag, const char *type) +{ + register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_string); + if (soap_out_string(soap, tag, id, a, type)) + return soap->error; + return soap_putindependent(soap); +} + +SOAP_FMAC3 int SOAP_FMAC4 soap_out_string(struct soap *soap, const char *tag, int id, char *const*a, const char *type) +{ + return soap_outstring(soap, tag, id, a, type, SOAP_TYPE_string); +} + +SOAP_FMAC3 char ** SOAP_FMAC4 soap_get_string(struct soap *soap, char **p, const char *tag, const char *type) +{ + if ((p = soap_in_string(soap, tag, p, type))) + if (soap_getindependent(soap)) + return NULL; + return p; +} + +SOAP_FMAC3 char * * SOAP_FMAC4 soap_in_string(struct soap *soap, const char *tag, char **a, const char *type) +{ + return soap_instring(soap, tag, a, type, SOAP_TYPE_string, 1, -1, -1); +} + +/* End of soapC.cpp */ + diff --git a/dep/gsoap/soapH.h b/dep/gsoap/soapH.h new file mode 100644 index 00000000000..ae135516be7 --- /dev/null +++ b/dep/gsoap/soapH.h @@ -0,0 +1,239 @@ +/* soapH.h + Generated by gSOAP 2.7.10 from stub.h + Copyright(C) 2000-2008, Robert van Engelen, Genivia Inc. All Rights Reserved. + This part of the software is released under one of the following licenses: + GPL, the gSOAP public license, or Genivia's license for commercial use. +*/ + +#ifndef soapH_H +#define soapH_H +#include "soapStub.h" +#ifndef WITH_NOIDREF + +#ifdef __cplusplus +extern "C" { +#endif +SOAP_FMAC3 void SOAP_FMAC4 soap_markelement(struct soap*, const void*, int); +SOAP_FMAC3 int SOAP_FMAC4 soap_putelement(struct soap*, const void*, const char*, int, int); +SOAP_FMAC3 void *SOAP_FMAC4 soap_getelement(struct soap*, int*); + +#ifdef __cplusplus +} +#endif +SOAP_FMAC3 int SOAP_FMAC4 soap_putindependent(struct soap*); +SOAP_FMAC3 int SOAP_FMAC4 soap_getindependent(struct soap*); +#endif +SOAP_FMAC3 int SOAP_FMAC4 soap_ignore_element(struct soap*); + +SOAP_FMAC3 void * SOAP_FMAC4 soap_instantiate(struct soap*, int, const char*, const char*, size_t*); +SOAP_FMAC3 int SOAP_FMAC4 soap_fdelete(struct soap_clist*); +SOAP_FMAC3 void* SOAP_FMAC4 soap_class_id_enter(struct soap*, const char*, void*, int, size_t, const char*, const char*); + +#ifndef SOAP_TYPE_byte +#define SOAP_TYPE_byte (3) +#endif +SOAP_FMAC3 void SOAP_FMAC4 soap_default_byte(struct soap*, char *); +SOAP_FMAC3 int SOAP_FMAC4 soap_put_byte(struct soap*, const char *, const char*, const char*); +SOAP_FMAC3 int SOAP_FMAC4 soap_out_byte(struct soap*, const char*, int, const char *, const char*); +SOAP_FMAC3 char * SOAP_FMAC4 soap_get_byte(struct soap*, char *, const char*, const char*); +SOAP_FMAC3 char * SOAP_FMAC4 soap_in_byte(struct soap*, const char*, char *, const char*); + +#ifndef SOAP_TYPE_int +#define SOAP_TYPE_int (1) +#endif +SOAP_FMAC3 void SOAP_FMAC4 soap_default_int(struct soap*, int *); +SOAP_FMAC3 int SOAP_FMAC4 soap_put_int(struct soap*, const int *, const char*, const char*); +SOAP_FMAC3 int SOAP_FMAC4 soap_out_int(struct soap*, const char*, int, const int *, const char*); +SOAP_FMAC3 int * SOAP_FMAC4 soap_get_int(struct soap*, int *, const char*, const char*); +SOAP_FMAC3 int * SOAP_FMAC4 soap_in_int(struct soap*, const char*, int *, const char*); + +#ifndef WITH_NOGLOBAL + +#ifndef SOAP_TYPE_SOAP_ENV__Fault +#define SOAP_TYPE_SOAP_ENV__Fault (18) +#endif +SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Fault(struct soap*, struct SOAP_ENV__Fault *); +SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Fault(struct soap*, const struct SOAP_ENV__Fault *); +SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Fault(struct soap*, const struct SOAP_ENV__Fault *, const char*, const char*); +SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Fault(struct soap*, const char*, int, const struct SOAP_ENV__Fault *, const char*); +SOAP_FMAC3 struct SOAP_ENV__Fault * SOAP_FMAC4 soap_get_SOAP_ENV__Fault(struct soap*, struct SOAP_ENV__Fault *, const char*, const char*); +SOAP_FMAC3 struct SOAP_ENV__Fault * SOAP_FMAC4 soap_in_SOAP_ENV__Fault(struct soap*, const char*, struct SOAP_ENV__Fault *, const char*); +SOAP_FMAC5 struct SOAP_ENV__Fault * SOAP_FMAC6 soap_new_SOAP_ENV__Fault(struct soap*, int); +SOAP_FMAC5 void SOAP_FMAC6 soap_delete_SOAP_ENV__Fault(struct soap*, struct SOAP_ENV__Fault*); +SOAP_FMAC3 struct SOAP_ENV__Fault * SOAP_FMAC4 soap_instantiate_SOAP_ENV__Fault(struct soap*, int, const char*, const char*, size_t*); +SOAP_FMAC3 void SOAP_FMAC4 soap_copy_SOAP_ENV__Fault(struct soap*, int, int, void*, size_t, const void*, size_t); + +#endif + +#ifndef WITH_NOGLOBAL + +#ifndef SOAP_TYPE_SOAP_ENV__Reason +#define SOAP_TYPE_SOAP_ENV__Reason (17) +#endif +SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Reason(struct soap*, struct SOAP_ENV__Reason *); +SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Reason(struct soap*, const struct SOAP_ENV__Reason *); +SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Reason(struct soap*, const struct SOAP_ENV__Reason *, const char*, const char*); +SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Reason(struct soap*, const char*, int, const struct SOAP_ENV__Reason *, const char*); +SOAP_FMAC3 struct SOAP_ENV__Reason * SOAP_FMAC4 soap_get_SOAP_ENV__Reason(struct soap*, struct SOAP_ENV__Reason *, const char*, const char*); +SOAP_FMAC3 struct SOAP_ENV__Reason * SOAP_FMAC4 soap_in_SOAP_ENV__Reason(struct soap*, const char*, struct SOAP_ENV__Reason *, const char*); +SOAP_FMAC5 struct SOAP_ENV__Reason * SOAP_FMAC6 soap_new_SOAP_ENV__Reason(struct soap*, int); +SOAP_FMAC5 void SOAP_FMAC6 soap_delete_SOAP_ENV__Reason(struct soap*, struct SOAP_ENV__Reason*); +SOAP_FMAC3 struct SOAP_ENV__Reason * SOAP_FMAC4 soap_instantiate_SOAP_ENV__Reason(struct soap*, int, const char*, const char*, size_t*); +SOAP_FMAC3 void SOAP_FMAC4 soap_copy_SOAP_ENV__Reason(struct soap*, int, int, void*, size_t, const void*, size_t); + +#endif + +#ifndef WITH_NOGLOBAL + +#ifndef SOAP_TYPE_SOAP_ENV__Detail +#define SOAP_TYPE_SOAP_ENV__Detail (14) +#endif +SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Detail(struct soap*, struct SOAP_ENV__Detail *); +SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Detail(struct soap*, const struct SOAP_ENV__Detail *); +SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Detail(struct soap*, const struct SOAP_ENV__Detail *, const char*, const char*); +SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Detail(struct soap*, const char*, int, const struct SOAP_ENV__Detail *, const char*); +SOAP_FMAC3 struct SOAP_ENV__Detail * SOAP_FMAC4 soap_get_SOAP_ENV__Detail(struct soap*, struct SOAP_ENV__Detail *, const char*, const char*); +SOAP_FMAC3 struct SOAP_ENV__Detail * SOAP_FMAC4 soap_in_SOAP_ENV__Detail(struct soap*, const char*, struct SOAP_ENV__Detail *, const char*); +SOAP_FMAC5 struct SOAP_ENV__Detail * SOAP_FMAC6 soap_new_SOAP_ENV__Detail(struct soap*, int); +SOAP_FMAC5 void SOAP_FMAC6 soap_delete_SOAP_ENV__Detail(struct soap*, struct SOAP_ENV__Detail*); +SOAP_FMAC3 struct SOAP_ENV__Detail * SOAP_FMAC4 soap_instantiate_SOAP_ENV__Detail(struct soap*, int, const char*, const char*, size_t*); +SOAP_FMAC3 void SOAP_FMAC4 soap_copy_SOAP_ENV__Detail(struct soap*, int, int, void*, size_t, const void*, size_t); + +#endif + +#ifndef WITH_NOGLOBAL + +#ifndef SOAP_TYPE_SOAP_ENV__Code +#define SOAP_TYPE_SOAP_ENV__Code (12) +#endif +SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Code(struct soap*, struct SOAP_ENV__Code *); +SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Code(struct soap*, const struct SOAP_ENV__Code *); +SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Code(struct soap*, const struct SOAP_ENV__Code *, const char*, const char*); +SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Code(struct soap*, const char*, int, const struct SOAP_ENV__Code *, const char*); +SOAP_FMAC3 struct SOAP_ENV__Code * SOAP_FMAC4 soap_get_SOAP_ENV__Code(struct soap*, struct SOAP_ENV__Code *, const char*, const char*); +SOAP_FMAC3 struct SOAP_ENV__Code * SOAP_FMAC4 soap_in_SOAP_ENV__Code(struct soap*, const char*, struct SOAP_ENV__Code *, const char*); +SOAP_FMAC5 struct SOAP_ENV__Code * SOAP_FMAC6 soap_new_SOAP_ENV__Code(struct soap*, int); +SOAP_FMAC5 void SOAP_FMAC6 soap_delete_SOAP_ENV__Code(struct soap*, struct SOAP_ENV__Code*); +SOAP_FMAC3 struct SOAP_ENV__Code * SOAP_FMAC4 soap_instantiate_SOAP_ENV__Code(struct soap*, int, const char*, const char*, size_t*); +SOAP_FMAC3 void SOAP_FMAC4 soap_copy_SOAP_ENV__Code(struct soap*, int, int, void*, size_t, const void*, size_t); + +#endif + +#ifndef WITH_NOGLOBAL + +#ifndef SOAP_TYPE_SOAP_ENV__Header +#define SOAP_TYPE_SOAP_ENV__Header (11) +#endif +SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Header(struct soap*, struct SOAP_ENV__Header *); +SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Header(struct soap*, const struct SOAP_ENV__Header *); +SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Header(struct soap*, const struct SOAP_ENV__Header *, const char*, const char*); +SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Header(struct soap*, const char*, int, const struct SOAP_ENV__Header *, const char*); +SOAP_FMAC3 struct SOAP_ENV__Header * SOAP_FMAC4 soap_get_SOAP_ENV__Header(struct soap*, struct SOAP_ENV__Header *, const char*, const char*); +SOAP_FMAC3 struct SOAP_ENV__Header * SOAP_FMAC4 soap_in_SOAP_ENV__Header(struct soap*, const char*, struct SOAP_ENV__Header *, const char*); +SOAP_FMAC5 struct SOAP_ENV__Header * SOAP_FMAC6 soap_new_SOAP_ENV__Header(struct soap*, int); +SOAP_FMAC5 void SOAP_FMAC6 soap_delete_SOAP_ENV__Header(struct soap*, struct SOAP_ENV__Header*); +SOAP_FMAC3 struct SOAP_ENV__Header * SOAP_FMAC4 soap_instantiate_SOAP_ENV__Header(struct soap*, int, const char*, const char*, size_t*); +SOAP_FMAC3 void SOAP_FMAC4 soap_copy_SOAP_ENV__Header(struct soap*, int, int, void*, size_t, const void*, size_t); + +#endif + +#ifndef SOAP_TYPE_ns1__executeCommand +#define SOAP_TYPE_ns1__executeCommand (10) +#endif +SOAP_FMAC3 void SOAP_FMAC4 soap_default_ns1__executeCommand(struct soap*, struct ns1__executeCommand *); +SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_ns1__executeCommand(struct soap*, const struct ns1__executeCommand *); +SOAP_FMAC3 int SOAP_FMAC4 soap_put_ns1__executeCommand(struct soap*, const struct ns1__executeCommand *, const char*, const char*); +SOAP_FMAC3 int SOAP_FMAC4 soap_out_ns1__executeCommand(struct soap*, const char*, int, const struct ns1__executeCommand *, const char*); +SOAP_FMAC3 struct ns1__executeCommand * SOAP_FMAC4 soap_get_ns1__executeCommand(struct soap*, struct ns1__executeCommand *, const char*, const char*); +SOAP_FMAC3 struct ns1__executeCommand * SOAP_FMAC4 soap_in_ns1__executeCommand(struct soap*, const char*, struct ns1__executeCommand *, const char*); +SOAP_FMAC5 struct ns1__executeCommand * SOAP_FMAC6 soap_new_ns1__executeCommand(struct soap*, int); +SOAP_FMAC5 void SOAP_FMAC6 soap_delete_ns1__executeCommand(struct soap*, struct ns1__executeCommand*); +SOAP_FMAC3 struct ns1__executeCommand * SOAP_FMAC4 soap_instantiate_ns1__executeCommand(struct soap*, int, const char*, const char*, size_t*); +SOAP_FMAC3 void SOAP_FMAC4 soap_copy_ns1__executeCommand(struct soap*, int, int, void*, size_t, const void*, size_t); + +#ifndef SOAP_TYPE_ns1__executeCommandResponse +#define SOAP_TYPE_ns1__executeCommandResponse (9) +#endif +SOAP_FMAC3 void SOAP_FMAC4 soap_default_ns1__executeCommandResponse(struct soap*, struct ns1__executeCommandResponse *); +SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_ns1__executeCommandResponse(struct soap*, const struct ns1__executeCommandResponse *); +SOAP_FMAC3 int SOAP_FMAC4 soap_put_ns1__executeCommandResponse(struct soap*, const struct ns1__executeCommandResponse *, const char*, const char*); +SOAP_FMAC3 int SOAP_FMAC4 soap_out_ns1__executeCommandResponse(struct soap*, const char*, int, const struct ns1__executeCommandResponse *, const char*); +SOAP_FMAC3 struct ns1__executeCommandResponse * SOAP_FMAC4 soap_get_ns1__executeCommandResponse(struct soap*, struct ns1__executeCommandResponse *, const char*, const char*); +SOAP_FMAC3 struct ns1__executeCommandResponse * SOAP_FMAC4 soap_in_ns1__executeCommandResponse(struct soap*, const char*, struct ns1__executeCommandResponse *, const char*); +SOAP_FMAC5 struct ns1__executeCommandResponse * SOAP_FMAC6 soap_new_ns1__executeCommandResponse(struct soap*, int); +SOAP_FMAC5 void SOAP_FMAC6 soap_delete_ns1__executeCommandResponse(struct soap*, struct ns1__executeCommandResponse*); +SOAP_FMAC3 struct ns1__executeCommandResponse * SOAP_FMAC4 soap_instantiate_ns1__executeCommandResponse(struct soap*, int, const char*, const char*, size_t*); +SOAP_FMAC3 void SOAP_FMAC4 soap_copy_ns1__executeCommandResponse(struct soap*, int, int, void*, size_t, const void*, size_t); + +#ifndef WITH_NOGLOBAL + +#ifndef SOAP_TYPE_PointerToSOAP_ENV__Reason +#define SOAP_TYPE_PointerToSOAP_ENV__Reason (20) +#endif +SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerToSOAP_ENV__Reason(struct soap*, struct SOAP_ENV__Reason *const*); +SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerToSOAP_ENV__Reason(struct soap*, struct SOAP_ENV__Reason *const*, const char*, const char*); +SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerToSOAP_ENV__Reason(struct soap*, const char *, int, struct SOAP_ENV__Reason *const*, const char *); +SOAP_FMAC3 struct SOAP_ENV__Reason ** SOAP_FMAC4 soap_get_PointerToSOAP_ENV__Reason(struct soap*, struct SOAP_ENV__Reason **, const char*, const char*); +SOAP_FMAC3 struct SOAP_ENV__Reason ** SOAP_FMAC4 soap_in_PointerToSOAP_ENV__Reason(struct soap*, const char*, struct SOAP_ENV__Reason **, const char*); + +#endif + +#ifndef WITH_NOGLOBAL + +#ifndef SOAP_TYPE_PointerToSOAP_ENV__Detail +#define SOAP_TYPE_PointerToSOAP_ENV__Detail (19) +#endif +SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerToSOAP_ENV__Detail(struct soap*, struct SOAP_ENV__Detail *const*); +SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerToSOAP_ENV__Detail(struct soap*, struct SOAP_ENV__Detail *const*, const char*, const char*); +SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerToSOAP_ENV__Detail(struct soap*, const char *, int, struct SOAP_ENV__Detail *const*, const char *); +SOAP_FMAC3 struct SOAP_ENV__Detail ** SOAP_FMAC4 soap_get_PointerToSOAP_ENV__Detail(struct soap*, struct SOAP_ENV__Detail **, const char*, const char*); +SOAP_FMAC3 struct SOAP_ENV__Detail ** SOAP_FMAC4 soap_in_PointerToSOAP_ENV__Detail(struct soap*, const char*, struct SOAP_ENV__Detail **, const char*); + +#endif + +#ifndef WITH_NOGLOBAL + +#ifndef SOAP_TYPE_PointerToSOAP_ENV__Code +#define SOAP_TYPE_PointerToSOAP_ENV__Code (13) +#endif +SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerToSOAP_ENV__Code(struct soap*, struct SOAP_ENV__Code *const*); +SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerToSOAP_ENV__Code(struct soap*, struct SOAP_ENV__Code *const*, const char*, const char*); +SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerToSOAP_ENV__Code(struct soap*, const char *, int, struct SOAP_ENV__Code *const*, const char *); +SOAP_FMAC3 struct SOAP_ENV__Code ** SOAP_FMAC4 soap_get_PointerToSOAP_ENV__Code(struct soap*, struct SOAP_ENV__Code **, const char*, const char*); +SOAP_FMAC3 struct SOAP_ENV__Code ** SOAP_FMAC4 soap_in_PointerToSOAP_ENV__Code(struct soap*, const char*, struct SOAP_ENV__Code **, const char*); + +#endif + +#ifndef SOAP_TYPE_PointerTostring +#define SOAP_TYPE_PointerTostring (7) +#endif +SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerTostring(struct soap*, char **const*); +SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerTostring(struct soap*, char **const*, const char*, const char*); +SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerTostring(struct soap*, const char *, int, char **const*, const char *); +SOAP_FMAC3 char *** SOAP_FMAC4 soap_get_PointerTostring(struct soap*, char ***, const char*, const char*); +SOAP_FMAC3 char *** SOAP_FMAC4 soap_in_PointerTostring(struct soap*, const char*, char ***, const char*); + +#ifndef SOAP_TYPE__QName +#define SOAP_TYPE__QName (5) +#endif +SOAP_FMAC3 void SOAP_FMAC4 soap_default__QName(struct soap*, char **); +SOAP_FMAC3 void SOAP_FMAC4 soap_serialize__QName(struct soap*, char *const*); +SOAP_FMAC3 int SOAP_FMAC4 soap_put__QName(struct soap*, char *const*, const char*, const char*); +SOAP_FMAC3 int SOAP_FMAC4 soap_out__QName(struct soap*, const char*, int, char*const*, const char*); +SOAP_FMAC3 char ** SOAP_FMAC4 soap_get__QName(struct soap*, char **, const char*, const char*); +SOAP_FMAC3 char * * SOAP_FMAC4 soap_in__QName(struct soap*, const char*, char **, const char*); + +#ifndef SOAP_TYPE_string +#define SOAP_TYPE_string (4) +#endif +SOAP_FMAC3 void SOAP_FMAC4 soap_default_string(struct soap*, char **); +SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_string(struct soap*, char *const*); +SOAP_FMAC3 int SOAP_FMAC4 soap_put_string(struct soap*, char *const*, const char*, const char*); +SOAP_FMAC3 int SOAP_FMAC4 soap_out_string(struct soap*, const char*, int, char*const*, const char*); +SOAP_FMAC3 char ** SOAP_FMAC4 soap_get_string(struct soap*, char **, const char*, const char*); +SOAP_FMAC3 char * * SOAP_FMAC4 soap_in_string(struct soap*, const char*, char **, const char*); + +#endif + +/* End of soapH.h */ + diff --git a/dep/gsoap/soapServer.cpp b/dep/gsoap/soapServer.cpp new file mode 100644 index 00000000000..e3eeb8fb3d7 --- /dev/null +++ b/dep/gsoap/soapServer.cpp @@ -0,0 +1,127 @@ +/* soapServer.cpp + Generated by gSOAP 2.7.10 from stub.h + Copyright(C) 2000-2008, Robert van Engelen, Genivia Inc. All Rights Reserved. + This part of the software is released under one of the following licenses: + GPL, the gSOAP public license, or Genivia's license for commercial use. +*/ +#include "soapH.h" + +SOAP_SOURCE_STAMP("@(#) soapServer.cpp ver 2.7.10 2010-02-18 18:41:56 GMT") + + +SOAP_FMAC5 int SOAP_FMAC6 soap_serve(struct soap *soap) +{ +#ifndef WITH_FASTCGI + unsigned int k = soap->max_keep_alive; +#endif + + do + { +#ifdef WITH_FASTCGI + if (FCGI_Accept() < 0) + { + soap->error = SOAP_EOF; + return soap_send_fault(soap); + } +#endif + + soap_begin(soap); + +#ifndef WITH_FASTCGI + if (soap->max_keep_alive > 0 && !--k) + soap->keep_alive = 0; +#endif + + if (soap_begin_recv(soap)) + { if (soap->error < SOAP_STOP) + { +#ifdef WITH_FASTCGI + soap_send_fault(soap); +#else + return soap_send_fault(soap); +#endif + } + soap_closesock(soap); + + continue; + } + + if (soap_envelope_begin_in(soap) + || soap_recv_header(soap) + || soap_body_begin_in(soap) + || soap_serve_request(soap) + || (soap->fserveloop && soap->fserveloop(soap))) + { +#ifdef WITH_FASTCGI + soap_send_fault(soap); +#else + return soap_send_fault(soap); +#endif + } + +#ifdef WITH_FASTCGI + soap_destroy(soap); + soap_end(soap); + } while (1); +#else + } while (soap->keep_alive); +#endif + return SOAP_OK; +} + +#ifndef WITH_NOSERVEREQUEST +SOAP_FMAC5 int SOAP_FMAC6 soap_serve_request(struct soap *soap) +{ + soap_peek_element(soap); + if (!soap_match_tag(soap, soap->tag, "ns1:executeCommand")) + return soap_serve_ns1__executeCommand(soap); + return soap->error = SOAP_NO_METHOD; +} +#endif + +SOAP_FMAC5 int SOAP_FMAC6 soap_serve_ns1__executeCommand(struct soap *soap) +{ struct ns1__executeCommand soap_tmp_ns1__executeCommand; + struct ns1__executeCommandResponse soap_tmp_ns1__executeCommandResponse; + char * soap_tmp_string; + soap_default_ns1__executeCommandResponse(soap, &soap_tmp_ns1__executeCommandResponse); + soap_tmp_string = NULL; + soap_tmp_ns1__executeCommandResponse.result = &soap_tmp_string; + soap_default_ns1__executeCommand(soap, &soap_tmp_ns1__executeCommand); + soap->encodingStyle = NULL; + if (!soap_get_ns1__executeCommand(soap, &soap_tmp_ns1__executeCommand, "ns1:executeCommand", NULL)) + return soap->error; + if (soap_body_end_in(soap) + || soap_envelope_end_in(soap) + || soap_end_recv(soap)) + return soap->error; + soap->error = ns1__executeCommand(soap, soap_tmp_ns1__executeCommand.command, &soap_tmp_string); + if (soap->error) + return soap->error; + soap_serializeheader(soap); + soap_serialize_ns1__executeCommandResponse(soap, &soap_tmp_ns1__executeCommandResponse); + if (soap_begin_count(soap)) + return soap->error; + if (soap->mode & SOAP_IO_LENGTH) + { if (soap_envelope_begin_out(soap) + || soap_putheader(soap) + || soap_body_begin_out(soap) + || soap_put_ns1__executeCommandResponse(soap, &soap_tmp_ns1__executeCommandResponse, "ns1:executeCommandResponse", "") + || soap_body_end_out(soap) + || soap_envelope_end_out(soap)) + return soap->error; + }; + if (soap_end_count(soap) + || soap_response(soap, SOAP_OK) + || soap_envelope_begin_out(soap) + || soap_putheader(soap) + || soap_body_begin_out(soap) + || soap_put_ns1__executeCommandResponse(soap, &soap_tmp_ns1__executeCommandResponse, "ns1:executeCommandResponse", "") + || soap_body_end_out(soap) + || soap_envelope_end_out(soap) + || soap_end_send(soap)) + return soap->error; + return soap_closesock(soap); +} + +/* End of soapServer.cpp */ + diff --git a/dep/gsoap/soapStub.h b/dep/gsoap/soapStub.h new file mode 100644 index 00000000000..eaa35c247bc --- /dev/null +++ b/dep/gsoap/soapStub.h @@ -0,0 +1,184 @@ +/* soapStub.h + Generated by gSOAP 2.7.10 from stub.h + Copyright(C) 2000-2008, Robert van Engelen, Genivia Inc. All Rights Reserved. + This part of the software is released under one of the following licenses: + GPL, the gSOAP public license, or Genivia's license for commercial use. +*/ + +#ifndef soapStub_H +#define soapStub_H +#include "stdsoap2.h" + +/******************************************************************************\ + * * + * Enumerations * + * * +\******************************************************************************/ + + +/******************************************************************************\ + * * + * Classes and Structs * + * * +\******************************************************************************/ + + +#if 0 /* volatile type: do not redeclare here */ + +#endif + +#ifndef SOAP_TYPE_ns1__executeCommandResponse +#define SOAP_TYPE_ns1__executeCommandResponse (9) +/* ns1:executeCommandResponse */ +struct ns1__executeCommandResponse +{ +public: + char **result; /* SOAP 1.2 RPC return element (when namespace qualified) */ /* optional element of type xsd:string */ +}; +#endif + +#ifndef SOAP_TYPE_ns1__executeCommand +#define SOAP_TYPE_ns1__executeCommand (10) +/* ns1:executeCommand */ +struct ns1__executeCommand +{ +public: + char *command; /* optional element of type xsd:string */ +}; +#endif + +#ifndef SOAP_TYPE_SOAP_ENV__Header +#define SOAP_TYPE_SOAP_ENV__Header (11) +/* SOAP Header: */ +struct SOAP_ENV__Header +{ +#ifdef WITH_NOEMPTYSTRUCT +private: + char dummy; /* dummy member to enable compilation */ +#endif +}; +#endif + +#ifndef SOAP_TYPE_SOAP_ENV__Code +#define SOAP_TYPE_SOAP_ENV__Code (12) +/* SOAP Fault Code: */ +struct SOAP_ENV__Code +{ +public: + char *SOAP_ENV__Value; /* optional element of type xsd:QName */ + struct SOAP_ENV__Code *SOAP_ENV__Subcode; /* optional element of type SOAP-ENV:Code */ +}; +#endif + +#ifndef SOAP_TYPE_SOAP_ENV__Detail +#define SOAP_TYPE_SOAP_ENV__Detail (14) +/* SOAP-ENV:Detail */ +struct SOAP_ENV__Detail +{ +public: + int __type; /* any type of element (defined below) */ + void *fault; /* transient */ + char *__any; +}; +#endif + +#ifndef SOAP_TYPE_SOAP_ENV__Reason +#define SOAP_TYPE_SOAP_ENV__Reason (17) +/* SOAP-ENV:Reason */ +struct SOAP_ENV__Reason +{ +public: + char *SOAP_ENV__Text; /* optional element of type xsd:string */ +}; +#endif + +#ifndef SOAP_TYPE_SOAP_ENV__Fault +#define SOAP_TYPE_SOAP_ENV__Fault (18) +/* SOAP Fault: */ +struct SOAP_ENV__Fault +{ +public: + char *faultcode; /* optional element of type xsd:QName */ + char *faultstring; /* optional element of type xsd:string */ + char *faultactor; /* optional element of type xsd:string */ + struct SOAP_ENV__Detail *detail; /* optional element of type SOAP-ENV:Detail */ + struct SOAP_ENV__Code *SOAP_ENV__Code; /* optional element of type SOAP-ENV:Code */ + struct SOAP_ENV__Reason *SOAP_ENV__Reason; /* optional element of type SOAP-ENV:Reason */ + char *SOAP_ENV__Node; /* optional element of type xsd:string */ + char *SOAP_ENV__Role; /* optional element of type xsd:string */ + struct SOAP_ENV__Detail *SOAP_ENV__Detail; /* optional element of type SOAP-ENV:Detail */ +}; +#endif + +/******************************************************************************\ + * * + * Types with Custom Serializers * + * * +\******************************************************************************/ + + +/******************************************************************************\ + * * + * Typedefs * + * * +\******************************************************************************/ + +#ifndef SOAP_TYPE__QName +#define SOAP_TYPE__QName (5) +typedef char *_QName; +#endif + +#ifndef SOAP_TYPE__XML +#define SOAP_TYPE__XML (6) +typedef char *_XML; +#endif + + +/******************************************************************************\ + * * + * Typedef Synonyms * + * * +\******************************************************************************/ + + +/******************************************************************************\ + * * + * Externals * + * * +\******************************************************************************/ + + +/******************************************************************************\ + * * + * Service Operations * + * * +\******************************************************************************/ + + +SOAP_FMAC5 int SOAP_FMAC6 ns1__executeCommand(struct soap*, char *command, char **result); + +/******************************************************************************\ + * * + * Stubs * + * * +\******************************************************************************/ + + +SOAP_FMAC5 int SOAP_FMAC6 soap_call_ns1__executeCommand(struct soap *soap, const char *soap_endpoint, const char *soap_action, char *command, char **result); + +/******************************************************************************\ + * * + * Skeletons * + * * +\******************************************************************************/ + +SOAP_FMAC5 int SOAP_FMAC6 soap_serve(struct soap*); + +SOAP_FMAC5 int SOAP_FMAC6 soap_serve_request(struct soap*); + +SOAP_FMAC5 int SOAP_FMAC6 soap_serve_ns1__executeCommand(struct soap*); + +#endif + +/* End of soapStub.h */ + diff --git a/dep/gsoap/stdsoap2.cpp b/dep/gsoap/stdsoap2.cpp new file mode 100644 index 00000000000..199d3118f23 --- /dev/null +++ b/dep/gsoap/stdsoap2.cpp @@ -0,0 +1,15198 @@ +/* + stdsoap2.c[pp] 2.7.15 + + gSOAP runtime engine + +gSOAP XML Web services tools +Copyright (C) 2000-2009, Robert van Engelen, Genivia Inc., All Rights Reserved. +This part of the software is released under ONE of the following licenses: +GPL, or the gSOAP public license, or Genivia's license for commercial use. +-------------------------------------------------------------------------------- +Contributors: + +Wind River Systems Inc., for the following additions under gSOAP public license: + - vxWorks compatible +-------------------------------------------------------------------------------- +gSOAP public license. + +The contents of this file are subject to the gSOAP Public License Version 1.3 +(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.cs.fsu.edu/~engelen/soaplicense.html +Software distributed under the License is distributed on an "AS IS" basis, +WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License +for the specific language governing rights and limitations under the License. + +The Initial Developer of the Original Code is Robert A. van Engelen. +Copyright (C) 2000-2009, Robert van Engelen, Genivia Inc., All Rights Reserved. +-------------------------------------------------------------------------------- +GPL license. + +This program is free software; you can redistribute it and/or modify it under +the terms of the GNU General Public License as published by the Free Software +Foundation; either version 2 of the License, or (at your option) any later +version. + +This program is distributed in the hope that it will be useful, but WITHOUT ANY +WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A +PARTICULAR PURPOSE. See the GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along with +this program; if not, write to the Free Software Foundation, Inc., 59 Temple +Place, Suite 330, Boston, MA 02111-1307 USA + +Author contact information: +engelen@genivia.com / engelen@acm.org + +This program is released under the GPL with the additional exemption that +compiling, linking, and/or using OpenSSL is allowed. +-------------------------------------------------------------------------------- +A commercial use license is available from Genivia, Inc., contact@genivia.com +-------------------------------------------------------------------------------- + +Installation note: + +Win32 build needs winsock.dll (Visual C++ "wsock32.lib") +To do this in Visual C++ 6.0, go to "Project", "settings", select the "Link" +tab (the project file needs to be selected in the file view) and add +"wsock32.lib" to the "Object/library modules" entry + +On Mac OS X with gcc (GCC) 3.1 20020420 (prerelease) you MUST compile with +-fstack_check when using -O2 because gcc 3.1 has a bug that smashes the stack +when locally allocated data exceeds 64K. + +*/ + +#ifdef AS400 +# pragma convert(819) /* EBCDIC to ASCII */ +#endif + +#include "stdsoap2.h" + +#ifdef __BORLANDC__ +# pragma warn -8060 +#else +# ifdef WIN32 +# ifdef UNDER_CE +# pragma comment(lib, "winsock.lib") +# else +# pragma comment(lib, "wsock32.lib") +# endif +# pragma warning(disable : 4996) /* disable deprecation warnings */ +# endif +#endif + +#ifdef __cplusplus +SOAP_SOURCE_STAMP("@(#) stdsoap2.cpp ver 2.7.15 2009-11-07 00:00:00 GMT") +extern "C" { +#else +SOAP_SOURCE_STAMP("@(#) stdsoap2.c ver 2.7.15 2009-11-07 00:00:00 GMT") +#endif + +/* 8bit character representing unknown/nonrepresentable character data (e.g. not supported by current locale with multibyte support enabled) */ +#ifndef SOAP_UNKNOWN_CHAR +#define SOAP_UNKNOWN_CHAR (127) +#endif + +/* EOF=-1 */ +#define SOAP_LT (soap_wchar)(-2) /* XML character '<' */ +#define SOAP_TT (soap_wchar)(-3) /* XML character '' */ +#define SOAP_QT (soap_wchar)(-5) /* XML character '"' */ +#define SOAP_AP (soap_wchar)(-6) /* XML character ''' */ + +#define soap_blank(c) ((c) >= 0 && (c) <= 32) +#define soap_notblank(c) ((c) > 32) + +#if defined(WIN32) && !defined(UNDER_CE) +#define soap_hash_ptr(p) ((PtrToUlong(p) >> 3) & (SOAP_PTRHASH - 1)) +#else +#define soap_hash_ptr(p) ((size_t)(((unsigned long)(p) >> 3) & (SOAP_PTRHASH-1))) +#endif + +#ifndef PALM_1 +static void soap_init_logs(struct soap*); +#endif +#ifdef SOAP_DEBUG +static void soap_close_logfile(struct soap*, int); +static void soap_set_logfile(struct soap*, int, const char*); +#endif + +#ifdef SOAP_MEM_DEBUG +static void soap_init_mht(struct soap*); +static void soap_free_mht(struct soap*); +static void soap_track_unlink(struct soap*, const void*); +#endif + +#ifndef PALM_2 +static int soap_set_error(struct soap*, const char*, const char*, const char*, const char*, int); +static int soap_copy_fault(struct soap*, const char*, const char*, const char*, const char*); +static int soap_getattrval(struct soap*, char*, size_t, soap_wchar); +#endif + +#ifndef PALM_1 +static void soap_free_ns(struct soap *soap); +static soap_wchar soap_char(struct soap*); +static soap_wchar soap_get_pi(struct soap*); +static int soap_isxdigit(int); +static void *fplugin(struct soap*, const char*); +static char *soap_get_http_body(struct soap*); +static size_t soap_count_attachments(struct soap *soap); +static int soap_try_connect_command(struct soap*, int http_command, const char *endpoint, const char *action); +#ifndef WITH_NOIDREF +static void soap_update_ptrs(struct soap*, char*, char*, char*, char*); +static int soap_has_copies(struct soap*, const char*, const char*); +static void soap_init_iht(struct soap*); +static void soap_free_iht(struct soap*); +static void soap_init_pht(struct soap*); +static void soap_free_pht(struct soap*); +#endif +#endif + +#ifndef WITH_LEAN +static const char *soap_set_validation_fault(struct soap*, const char*, const char*); +static int soap_isnumeric(struct soap*, const char*); +static struct soap_nlist *soap_push_ns(struct soap *soap, const char *id, const char *ns, short utilized); +static void soap_utilize_ns(struct soap *soap, const char *tag, size_t n); +#endif + +#ifndef WITH_LEANER +#ifndef PALM_1 +static struct soap_multipart *soap_new_multipart(struct soap*, struct soap_multipart**, struct soap_multipart**, char*, size_t); +static int soap_putdimefield(struct soap*, const char*, size_t); +static char *soap_getdimefield(struct soap*, size_t); +static void soap_select_mime_boundary(struct soap*); +static int soap_valid_mime_boundary(struct soap*); +static void soap_resolve_attachment(struct soap*, struct soap_multipart*); +#endif +#endif + +#ifdef WITH_GZIP +static int soap_getgziphdr(struct soap*); +#endif + +#ifdef WITH_OPENSSL +int soap_ssl_init_done = 0; + +static int ssl_auth_init(struct soap*); +static int ssl_verify_callback(int, X509_STORE_CTX*); +static int ssl_verify_callback_allow_expired_certificate(int, X509_STORE_CTX*); +static int ssl_password(char*, int, int, void *); +/* The callback below is included for future references: +static DH *ssl_tmp_dh(SSL*, int, int); +*/ +#endif + +#if !defined(WITH_NOHTTP) || !defined(WITH_LEANER) +#ifndef PALM_1 +static const char *soap_decode(char*, size_t, const char*, const char*); +#endif +#endif + +#ifndef WITH_NOHTTP +#ifndef PALM_1 +static soap_wchar soap_getchunkchar(struct soap*); +static const char *http_error(struct soap*, int); +static int http_get(struct soap*); +static int http_405(struct soap*); +static int http_post(struct soap*, const char*, const char*, int, const char*, const char*, size_t); +static int http_send_header(struct soap*, const char*); +static int http_post_header(struct soap*, const char*, const char*); +static int http_response(struct soap*, int, size_t); +static int http_parse(struct soap*); +static int http_parse_header(struct soap*, const char*, const char*); +#endif +#endif + +#ifndef WITH_NOIO + +#ifndef PALM_1 +static int fsend(struct soap*, const char*, size_t); +static size_t frecv(struct soap*, char*, size_t); +static int tcp_init(struct soap*); +static const char *tcp_error(struct soap*); +#ifndef WITH_IPV6 +static int tcp_gethost(struct soap*, const char *addr, struct in_addr *inaddr); +#endif +static SOAP_SOCKET tcp_connect(struct soap*, const char *endpoint, const char *host, int port); +static SOAP_SOCKET tcp_accept(struct soap*, SOAP_SOCKET, struct sockaddr*, int*); +static int tcp_select(struct soap*, SOAP_SOCKET, int, int); +static int tcp_disconnect(struct soap*); +static int tcp_closesocket(struct soap*, SOAP_SOCKET); +static int tcp_shutdownsocket(struct soap*, SOAP_SOCKET, int); +static const char *soap_strerror(struct soap*); +#endif + +#define SOAP_TCP_SELECT_RCV 0x1 +#define SOAP_TCP_SELECT_SND 0x2 +#define SOAP_TCP_SELECT_ERR 0x4 +#define SOAP_TCP_SELECT_ALL 0x7 + +#if defined(WIN32) + #define SOAP_SOCKBLOCK(fd) \ + { u_long blocking = 0; \ + ioctlsocket(fd, FIONBIO, &blocking); \ + } + #define SOAP_SOCKNONBLOCK(fd) \ + { u_long nonblocking = 1; \ + ioctlsocket(fd, FIONBIO, &nonblocking); \ + } +#elif defined(VXWORKS) + #define SOAP_SOCKBLOCK(fd) \ + { u_long blocking = 0; \ + ioctl(fd, FIONBIO, (int)(&blocking)); \ + } + #define SOAP_SOCKNONBLOCK(fd) \ + { u_long nonblocking = 1; \ + ioctl(fd, FIONBIO, (int)(&nonblocking)); \ + } +#elif defined(PALM) + #define SOAP_SOCKBLOCK(fd) fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0)&~O_NONBLOCK); + #define SOAP_SOCKNONBLOCK(fd) fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0)|O_NONBLOCK); +#elif defined(SYMBIAN) + #define SOAP_SOCKBLOCK(fd) \ + { long blocking = 0; \ + ioctl(fd, 0/*FIONBIO*/, &blocking); \ + } + #define SOAP_SOCKNONBLOCK(fd) \ + { long nonblocking = 1; \ + ioctl(fd, 0/*FIONBIO*/, &nonblocking); \ + } +#else + #define SOAP_SOCKBLOCK(fd) fcntl(fd, F_SETFL, fcntl(fd, F_GETFL)&~O_NONBLOCK); + #define SOAP_SOCKNONBLOCK(fd) fcntl(fd, F_SETFL, fcntl(fd, F_GETFL)|O_NONBLOCK); +#endif + +#endif + +#if defined(PALM) && !defined(PALM_2) +unsigned short errno; +#endif + +#ifndef PALM_1 +static const char soap_env1[42] = "http://schemas.xmlsoap.org/soap/envelope/"; +static const char soap_enc1[42] = "http://schemas.xmlsoap.org/soap/encoding/"; +static const char soap_env2[40] = "http://www.w3.org/2003/05/soap-envelope"; +static const char soap_enc2[40] = "http://www.w3.org/2003/05/soap-encoding"; +static const char soap_rpc[35] = "http://www.w3.org/2003/05/soap-rpc"; +#endif + +#ifndef PALM_1 +const struct soap_double_nan soap_double_nan = {0xFFFFFFFF, 0xFFFFFFFF}; +static const char soap_base64o[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +static const char soap_base64i[81] = "\76XXX\77\64\65\66\67\70\71\72\73\74\75XXXXXXX\00\01\02\03\04\05\06\07\10\11\12\13\14\15\16\17\20\21\22\23\24\25\26\27\30\31XXXXXX\32\33\34\35\36\37\40\41\42\43\44\45\46\47\50\51\52\53\54\55\56\57\60\61\62\63"; +#endif + +#ifndef WITH_LEAN +static const char soap_indent[11] = "\n\t\t\t\t\t\t\t\t\t"; +/* Alternative indentation form for SOAP_XML_INDENT: +static const char soap_indent[21] = "\n "; +*/ +#endif + +#ifndef SOAP_CANARY +# define SOAP_CANARY (0xC0DE) +#endif + +static const char soap_padding[4] = "\0\0\0"; +#define SOAP_STR_PADDING (soap_padding) +#define SOAP_STR_EOS (soap_padding) +#define SOAP_NON_NULL (soap_padding) + +#ifndef WITH_LEAN +static const struct soap_code_map html_entity_codes[] = /* entities for XHTML parsing */ +{ { 160, "nbsp" }, + { 161, "iexcl" }, + { 162, "cent" }, + { 163, "pound" }, + { 164, "curren" }, + { 165, "yen" }, + { 166, "brvbar" }, + { 167, "sect" }, + { 168, "uml" }, + { 169, "copy" }, + { 170, "ordf" }, + { 171, "laquo" }, + { 172, "not" }, + { 173, "shy" }, + { 174, "reg" }, + { 175, "macr" }, + { 176, "deg" }, + { 177, "plusmn" }, + { 178, "sup2" }, + { 179, "sup3" }, + { 180, "acute" }, + { 181, "micro" }, + { 182, "para" }, + { 183, "middot" }, + { 184, "cedil" }, + { 185, "sup1" }, + { 186, "ordm" }, + { 187, "raquo" }, + { 188, "frac14" }, + { 189, "frac12" }, + { 190, "frac34" }, + { 191, "iquest" }, + { 192, "Agrave" }, + { 193, "Aacute" }, + { 194, "Acirc" }, + { 195, "Atilde" }, + { 196, "Auml" }, + { 197, "Aring" }, + { 198, "AElig" }, + { 199, "Ccedil" }, + { 200, "Egrave" }, + { 201, "Eacute" }, + { 202, "Ecirc" }, + { 203, "Euml" }, + { 204, "Igrave" }, + { 205, "Iacute" }, + { 206, "Icirc" }, + { 207, "Iuml" }, + { 208, "ETH" }, + { 209, "Ntilde" }, + { 210, "Ograve" }, + { 211, "Oacute" }, + { 212, "Ocirc" }, + { 213, "Otilde" }, + { 214, "Ouml" }, + { 215, "times" }, + { 216, "Oslash" }, + { 217, "Ugrave" }, + { 218, "Uacute" }, + { 219, "Ucirc" }, + { 220, "Uuml" }, + { 221, "Yacute" }, + { 222, "THORN" }, + { 223, "szlig" }, + { 224, "agrave" }, + { 225, "aacute" }, + { 226, "acirc" }, + { 227, "atilde" }, + { 228, "auml" }, + { 229, "aring" }, + { 230, "aelig" }, + { 231, "ccedil" }, + { 232, "egrave" }, + { 233, "eacute" }, + { 234, "ecirc" }, + { 235, "euml" }, + { 236, "igrave" }, + { 237, "iacute" }, + { 238, "icirc" }, + { 239, "iuml" }, + { 240, "eth" }, + { 241, "ntilde" }, + { 242, "ograve" }, + { 243, "oacute" }, + { 244, "ocirc" }, + { 245, "otilde" }, + { 246, "ouml" }, + { 247, "divide" }, + { 248, "oslash" }, + { 249, "ugrave" }, + { 250, "uacute" }, + { 251, "ucirc" }, + { 252, "uuml" }, + { 253, "yacute" }, + { 254, "thorn" }, + { 255, "yuml" }, + { 0, NULL } +}; +#endif + +#ifndef WITH_NOIO +#ifndef WITH_LEAN +static const struct soap_code_map h_error_codes[] = +{ +#ifdef HOST_NOT_FOUND + { HOST_NOT_FOUND, "Host not found" }, +#endif +#ifdef TRY_AGAIN + { TRY_AGAIN, "Try Again" }, +#endif +#ifdef NO_RECOVERY + { NO_RECOVERY, "No Recovery" }, +#endif +#ifdef NO_DATA + { NO_DATA, "No Data" }, +#endif +#ifdef NO_ADDRESS + { NO_ADDRESS, "No Address" }, +#endif + { 0, NULL } +}; +#endif +#endif + +#ifndef WITH_NOHTTP +#ifndef WITH_LEAN +static const struct soap_code_map h_http_error_codes[] = +{ { 200, "OK" }, + { 201, "Created" }, + { 202, "Accepted" }, + { 203, "Non-Authoritative Information" }, + { 204, "No Content" }, + { 205, "Reset Content" }, + { 206, "Partial Content" }, + { 300, "Multiple Choices" }, + { 301, "Moved Permanently" }, + { 302, "Found" }, + { 303, "See Other" }, + { 304, "Not Modified" }, + { 305, "Use Proxy" }, + { 307, "Temporary Redirect" }, + { 400, "Bad Request" }, + { 401, "Unauthorized" }, + { 402, "Payment Required" }, + { 403, "Forbidden" }, + { 404, "Not Found" }, + { 405, "Method Not Allowed" }, + { 406, "Not Acceptable" }, + { 407, "Proxy Authentication Required" }, + { 408, "Request Time-out" }, + { 409, "Conflict" }, + { 410, "Gone" }, + { 411, "Length Required" }, + { 412, "Precondition Failed" }, + { 413, "Request Entity Too Large" }, + { 414, "Request-URI Too Large" }, + { 415, "Unsupported Media Type" }, + { 416, "Requested range not satisfiable" }, + { 417, "Expectation Failed" }, + { 500, "Internal Server Error" }, + { 501, "Not Implemented" }, + { 502, "Bad Gateway" }, + { 503, "Service Unavailable" }, + { 504, "Gateway Time-out" }, + { 505, "HTTP Version not supported" }, + { 0, NULL } +}; +#endif +#endif + +#ifdef WITH_OPENSSL +static const struct soap_code_map h_ssl_error_codes[] = +{ +#define _SSL_ERROR(e) { e, #e } + _SSL_ERROR(SSL_ERROR_SSL), + _SSL_ERROR(SSL_ERROR_ZERO_RETURN), + _SSL_ERROR(SSL_ERROR_WANT_READ), + _SSL_ERROR(SSL_ERROR_WANT_WRITE), + _SSL_ERROR(SSL_ERROR_WANT_CONNECT), + _SSL_ERROR(SSL_ERROR_WANT_X509_LOOKUP), + _SSL_ERROR(SSL_ERROR_SYSCALL), + { 0, NULL } +}; +#endif + +#ifndef WITH_LEANER +static const struct soap_code_map mime_codes[] = +{ { SOAP_MIME_7BIT, "7bit" }, + { SOAP_MIME_8BIT, "8bit" }, + { SOAP_MIME_BINARY, "binary" }, + { SOAP_MIME_QUOTED_PRINTABLE, "quoted-printable" }, + { SOAP_MIME_BASE64, "base64" }, + { SOAP_MIME_IETF_TOKEN, "ietf-token" }, + { SOAP_MIME_X_TOKEN, "x-token" }, + { 0, NULL } +}; +#endif + +#ifdef WIN32 +static int tcp_done = 0; +#endif + +#if defined(HP_UX) && defined(HAVE_GETHOSTBYNAME_R) +extern int h_errno; +#endif + +/******************************************************************************/ +#ifndef WITH_NOIO +#ifndef PALM_1 +static int +fsend(struct soap *soap, const char *s, size_t n) +{ register int nwritten, err; +#if defined(__cplusplus) && !defined(WITH_LEAN) && !defined(WITH_COMPAT) + if (soap->os) + { soap->os->write(s, (std::streamsize)n); + if (soap->os->good()) + return SOAP_OK; + soap->errnum = 0; + return SOAP_EOF; + } +#endif + while (n) + { if (soap_valid_socket(soap->socket)) + { +#ifndef WITH_LEAN + if (soap->send_timeout) + { for (;;) + { register int r; +#ifdef WITH_OPENSSL + if (soap->ssl) + r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_ALL, soap->send_timeout); + else +#endif + r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_SND | SOAP_TCP_SELECT_ERR, soap->send_timeout); + if (r > 0) + break; + if (!r) + return SOAP_EOF; + err = soap->errnum; + if (!err) + return soap->error; + if (err != SOAP_EINTR && err != SOAP_EAGAIN && err != SOAP_EWOULDBLOCK) + return SOAP_EOF; + } + } +#endif +#ifdef WITH_OPENSSL + if (soap->ssl) + nwritten = SSL_write(soap->ssl, s, (int)n); + else if (soap->bio) + nwritten = BIO_write(soap->bio, s, (int)n); + else +#endif +#ifndef WITH_LEAN + if ((soap->omode & SOAP_IO_UDP)) + { if (soap->peerlen) + nwritten = sendto(soap->socket, (char*)s, (SOAP_WINSOCKINT)n, soap->socket_flags, (struct sockaddr*)&soap->peer, (SOAP_WINSOCKINT)soap->peerlen); + else + nwritten = send(soap->socket, s, (SOAP_WINSOCKINT)n, soap->socket_flags); + /* retry and back-off algorithm */ + /* TODO: this is not very clear from specs so verify and limit conditions under which we should loop (e.g. ENOBUFS) */ + if (nwritten < 0) + { int udp_repeat; + int udp_delay; + if ((soap->connect_flags & SO_BROADCAST)) + udp_repeat = 3; /* SOAP-over-UDP MULTICAST_UDP_REPEAT - 1 */ + else + udp_repeat = 1; /* SOAP-over-UDP UNICAST_UDP_REPEAT - 1 */ + udp_delay = (soap_random % 201) + 50; /* UDP_MIN_DELAY .. UDP_MAX_DELAY */ + do + { tcp_select(soap, soap->socket, SOAP_TCP_SELECT_ERR, -1000 * udp_delay); + if (soap->peerlen) + nwritten = sendto(soap->socket, s, (SOAP_WINSOCKINT)n, soap->socket_flags, (struct sockaddr*)&soap->peer, (SOAP_WINSOCKINT)soap->peerlen); + else + nwritten = send(soap->socket, s, (SOAP_WINSOCKINT)n, soap->socket_flags); + udp_delay <<= 1; + if (udp_delay > 500) /* UDP_UPPER_DELAY */ + udp_delay = 500; + } + while (nwritten < 0 && --udp_repeat > 0); + } + } + else +#endif +#if !defined(PALM) && !defined(AS400) + nwritten = send(soap->socket, s, (int)n, soap->socket_flags); +#else + nwritten = send(soap->socket, (void*)s, n, soap->socket_flags); +#endif + if (nwritten <= 0) + { +#if defined(WITH_OPENSSL) || !defined(WITH_LEAN) + register int r = 0; +#endif + err = soap_socket_errno(soap->socket); +#ifdef WITH_OPENSSL + if (soap->ssl && (r = SSL_get_error(soap->ssl, nwritten)) != SSL_ERROR_NONE && r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE) + { soap->errnum = err; + return SOAP_EOF; + } +#endif + if (err == SOAP_EWOULDBLOCK || err == SOAP_EAGAIN) + { +#ifndef WITH_LEAN +#ifdef WITH_OPENSSL + if (soap->ssl && r == SSL_ERROR_WANT_READ) + r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, soap->send_timeout ? soap->send_timeout : -10000); + else + r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_SND | SOAP_TCP_SELECT_ERR, soap->send_timeout ? soap->send_timeout : -10000); +#else + r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_SND | SOAP_TCP_SELECT_ERR, soap->send_timeout ? soap->send_timeout : -10000); +#endif + if (!r && soap->send_timeout) + return SOAP_EOF; + if (r < 0 && soap->errnum != SOAP_EINTR) + return SOAP_EOF; +#endif + } + else if (err && err != SOAP_EINTR) + { soap->errnum = err; + return SOAP_EOF; + } + nwritten = 0; /* and call write() again */ + } + } + else + { +#ifdef WITH_FASTCGI + nwritten = fwrite((void*)s, 1, n, stdout); + fflush(stdout); +#else +#ifdef UNDER_CE + nwritten = fwrite(s, 1, n, soap->sendfd); +#else +#ifdef VXWORKS +#ifdef WMW_RPM_IO + if (soap->rpmreqid) + nwritten = (httpBlockPut(soap->rpmreqid, s, n) == 0) ? n : -1; + else +#endif + nwritten = fwrite(s, sizeof(char), n, fdopen(soap->sendfd, "w")); +#else +#ifdef WIN32 + nwritten = _write(soap->sendfd, s, (unsigned int)n); +#else + nwritten = write(soap->sendfd, s, (unsigned int)n); +#endif +#endif +#endif +#endif + if (nwritten <= 0) + { +#ifndef WITH_FASTCGI + err = soap_errno; +#else + err = EOF; +#endif + if (err && err != SOAP_EINTR && err != SOAP_EWOULDBLOCK && err != SOAP_EAGAIN) + { soap->errnum = err; + return SOAP_EOF; + } + nwritten = 0; /* and call write() again */ + } + } + n -= nwritten; + s += nwritten; + } + return SOAP_OK; +} +#endif +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_send_raw(struct soap *soap, const char *s, size_t n) +{ if (!n) + return SOAP_OK; + if (soap->mode & SOAP_IO_LENGTH) + { soap->count += n; +#ifndef WITH_LEANER + if (soap->fpreparesend && (soap->mode & SOAP_IO) != SOAP_IO_STORE) + return soap->error = soap->fpreparesend(soap, s, n); +#endif + return SOAP_OK; + } + if (soap->mode & SOAP_IO) + { register size_t i = SOAP_BUFLEN - soap->bufidx; + while (n >= i) + { memcpy(soap->buf + soap->bufidx, s, i); + soap->bufidx = SOAP_BUFLEN; + if (soap_flush(soap)) + return soap->error; + s += i; + n -= i; + i = SOAP_BUFLEN; + } + memcpy(soap->buf + soap->bufidx, s, n); + soap->bufidx += n; + return SOAP_OK; + } + return soap_flush_raw(soap, s, n); +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_flush(struct soap *soap) +{ register size_t n = soap->bufidx; + if (n) + { soap->bufidx = 0; +#ifdef WITH_ZLIB + if (soap->mode & SOAP_ENC_ZLIB) + { soap->d_stream->next_in = (Byte*)soap->buf; + soap->d_stream->avail_in = (unsigned int)n; +#ifdef WITH_GZIP + soap->z_crc = crc32(soap->z_crc, (Byte*)soap->buf, (unsigned int)n); +#endif + do + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Deflating %u bytes\n", soap->d_stream->avail_in)); + if (deflate(soap->d_stream, Z_NO_FLUSH) != Z_OK) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unable to deflate: %s\n", soap->d_stream->msg?soap->d_stream->msg:SOAP_STR_EOS)); + return soap->error = SOAP_ZLIB_ERROR; + } + if (!soap->d_stream->avail_out) + { if (soap_flush_raw(soap, soap->z_buf, SOAP_BUFLEN)) + return soap->error; + soap->d_stream->next_out = (Byte*)soap->z_buf; + soap->d_stream->avail_out = SOAP_BUFLEN; + } + } while (soap->d_stream->avail_in); + } + else +#endif + return soap_flush_raw(soap, soap->buf, n); + } + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_flush_raw(struct soap *soap, const char *s, size_t n) +{ if ((soap->mode & SOAP_IO) == SOAP_IO_STORE) + { register char *t; + if (!(t = (char*)soap_push_block(soap, NULL, n))) + return soap->error = SOAP_EOM; + memcpy(t, s, n); +#ifndef WITH_LEANER + if (soap->fpreparesend) + return soap->error = soap->fpreparesend(soap, s, n); +#endif + return SOAP_OK; + } +#ifndef WITH_LEANER + if ((soap->mode & SOAP_IO) == SOAP_IO_CHUNK) + { char t[16]; + sprintf(t, "\r\n%lX\r\n" + (soap->chunksize ? 0 : 2), (unsigned long)n); + DBGMSG(SENT, t, strlen(t)); + if ((soap->error = soap->fsend(soap, t, strlen(t)))) + return soap->error; + soap->chunksize += n; + } + DBGMSG(SENT, s, n); +#endif + return soap->error = soap->fsend(soap, s, n); +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_send(struct soap *soap, const char *s) +{ if (s) + return soap_send_raw(soap, s, strlen(s)); + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_send2(struct soap *soap, const char *s1, const char *s2) +{ if (soap_send(soap, s1)) + return soap->error; + return soap_send(soap, s2); +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_send3(struct soap *soap, const char *s1, const char *s2, const char *s3) +{ if (soap_send(soap, s1) + || soap_send(soap, s2)) + return soap->error; + return soap_send(soap, s3); +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIO +#ifndef PALM_1 +static size_t +frecv(struct soap *soap, char *s, size_t n) +{ register int r; +#ifndef WITH_LEAN + register int retries = 100; /* max 100 retries with non-blocking sockets */ +#endif + soap->errnum = 0; +#if defined(__cplusplus) && !defined(WITH_LEAN) && !defined(WITH_COMPAT) + if (soap->is) + { if (soap->is->good()) + return soap->is->read(s, (std::streamsize)n).gcount(); + return 0; + } +#endif + if (soap_valid_socket(soap->socket)) + { for (;;) + { +#ifdef WITH_OPENSSL + register int err = 0; +#endif +#ifndef WITH_LEAN +#ifdef WITH_OPENSSL + if (soap->recv_timeout && !soap->ssl) /* SSL: sockets are nonblocking */ +#else + if (soap->recv_timeout) +#endif + { for (;;) + { r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, soap->recv_timeout); + if (r > 0) + break; + if (!r) + return 0; + r = soap->errnum; + if (r != SOAP_EINTR && r != SOAP_EAGAIN && r != SOAP_EWOULDBLOCK) + return 0; + } + } +#endif +#ifdef WITH_OPENSSL + if (soap->ssl) + { r = SSL_read(soap->ssl, s, (int)n); + if (r > 0) + return (size_t)r; + err = SSL_get_error(soap->ssl, r); + if (err != SSL_ERROR_NONE && err != SSL_ERROR_WANT_READ && err != SSL_ERROR_WANT_WRITE) + return 0; + } + else if (soap->bio) + { r = BIO_read(soap->bio, s, (int)n); + if (r > 0) + return (size_t)r; + return 0; + } + else +#endif + { +#ifndef WITH_LEAN + if ((soap->omode & SOAP_IO_UDP)) + { SOAP_SOCKLEN_T k = (SOAP_SOCKLEN_T)sizeof(soap->peer); + memset((void*)&soap->peer, 0, sizeof(soap->peer)); + r = recvfrom(soap->socket, s, (SOAP_WINSOCKINT)n, soap->socket_flags, (struct sockaddr*)&soap->peer, &k); /* portability note: see SOAP_SOCKLEN_T definition in stdsoap2.h */ + soap->peerlen = (size_t)k; +#ifndef WITH_IPV6 + soap->ip = ntohl(soap->peer.sin_addr.s_addr); +#endif + } + else +#endif + r = recv(soap->socket, s, (int)n, soap->socket_flags); +#ifdef PALM + /* CycleSyncDisplay(curStatusMsg); */ +#endif + if (r >= 0) + return (size_t)r; + r = soap_socket_errno(soap->socket); + if (r != SOAP_EINTR && r != SOAP_EAGAIN && r != SOAP_EWOULDBLOCK) + { soap->errnum = r; + return 0; + } + } +#ifndef WITH_LEAN + { +#ifdef WITH_OPENSSL + if (soap->ssl && err == SSL_ERROR_WANT_WRITE) + r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_SND | SOAP_TCP_SELECT_ERR, soap->recv_timeout ? soap->recv_timeout : 5); + else + r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, soap->recv_timeout ? soap->recv_timeout : 5); +#else + r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, soap->recv_timeout ? soap->recv_timeout : 5); +#endif + if (!r && soap->recv_timeout) + return 0; + if (r < 0) + { r = soap->errnum; + if (r != SOAP_EINTR && r != SOAP_EAGAIN && r != SOAP_EWOULDBLOCK) + return 0; + } + if (retries-- <= 0) + return 0; + } +#endif +#ifdef PALM + r = soap_socket_errno(soap->socket); + if (r != SOAP_EINTR && retries-- <= 0) + { soap->errnum = r; + return 0; + } +#endif + } + } +#ifdef WITH_FASTCGI + return fread(s, 1, n, stdin); +#else +#ifdef UNDER_CE + return fread(s, 1, n, soap->recvfd); +#else +#ifdef WMW_RPM_IO + if (soap->rpmreqid) + r = httpBlockRead(soap->rpmreqid, s, n); + else +#endif +#ifdef WIN32 + r = _read(soap->recvfd, s, (unsigned int)n); +#else + r = read(soap->recvfd, s, (unsigned int)n); +#endif + if (r >= 0) + return (size_t)r; + soap->errnum = soap_errno; + return 0; +#endif +#endif +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOHTTP +#ifndef PALM_1 +static soap_wchar +soap_getchunkchar(struct soap *soap) +{ if (soap->bufidx < soap->buflen) + return soap->buf[soap->bufidx++]; + soap->bufidx = 0; + soap->buflen = soap->chunkbuflen = soap->frecv(soap, soap->buf, SOAP_BUFLEN); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Read %u bytes from socket %d\n", (unsigned int)soap->buflen, soap->socket)); + DBGMSG(RECV, soap->buf, soap->buflen); + if (soap->buflen) + return soap->buf[soap->bufidx++]; + return EOF; +} +#endif +#endif + +/******************************************************************************/ +#ifndef PALM_1 +static int +soap_isxdigit(int c) +{ return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_recv_raw(struct soap *soap) +{ register size_t ret; +#if !defined(WITH_LEANER) || defined(WITH_ZLIB) + register int r; +#endif +#ifdef WITH_ZLIB + if (soap->mode & SOAP_ENC_ZLIB) + { if (soap->d_stream->next_out == Z_NULL) + return EOF; + if (soap->d_stream->avail_in || !soap->d_stream->avail_out) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Inflating\n")); + soap->d_stream->next_out = (Byte*)soap->buf; + soap->d_stream->avail_out = SOAP_BUFLEN; + r = inflate(soap->d_stream, Z_NO_FLUSH); + if (r == Z_NEED_DICT && soap->z_dict) + r = inflateSetDictionary(soap->d_stream, (const Bytef*)soap->z_dict, soap->z_dict_len); + if (r == Z_OK || r == Z_STREAM_END) + { soap->bufidx = 0; + ret = soap->buflen = SOAP_BUFLEN - soap->d_stream->avail_out; + if (soap->zlib_in == SOAP_ZLIB_GZIP) + soap->z_crc = crc32(soap->z_crc, (Byte*)soap->buf, (unsigned int)ret); + if (r == Z_STREAM_END) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Inflated %lu->%lu bytes\n", soap->d_stream->total_in, soap->d_stream->total_out)); + soap->z_ratio_in = (float)soap->d_stream->total_in / (float)soap->d_stream->total_out; + soap->d_stream->next_out = Z_NULL; + } + if (ret) + { soap->count += ret; + DBGLOG(RECV, SOAP_MESSAGE(fdebug, "\n---- decompressed ----\n")); + DBGMSG(RECV, soap->buf, ret); + DBGLOG(RECV, SOAP_MESSAGE(fdebug, "\n----\n")); + return SOAP_OK; + } + } + else if (r != Z_BUF_ERROR) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Inflate error: %s\n", soap->d_stream->msg?soap->d_stream->msg:SOAP_STR_EOS)); + soap->d_stream->next_out = Z_NULL; + soap->error = SOAP_ZLIB_ERROR; + return EOF; + } + } +zlib_again: + if ((soap->mode & SOAP_IO) == SOAP_IO_CHUNK && !soap->chunksize) + { memcpy(soap->buf, soap->z_buf, SOAP_BUFLEN); + soap->buflen = soap->z_buflen; + } + DBGLOG(RECV, SOAP_MESSAGE(fdebug, "\n---- compressed ----\n")); + } +#endif +#ifndef WITH_NOHTTP + if ((soap->mode & SOAP_IO) == SOAP_IO_CHUNK) /* read HTTP chunked transfer */ + { for (;;) + { register soap_wchar c; + char *t, tmp[8]; + if (soap->chunksize) + { soap->buflen = ret = soap->frecv(soap, soap->buf, soap->chunksize > SOAP_BUFLEN ? SOAP_BUFLEN : soap->chunksize); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Getting chunk: read %u bytes\n", (unsigned int)ret)); + DBGMSG(RECV, soap->buf, ret); + soap->bufidx = 0; + soap->chunksize -= ret; + break; + } + t = tmp; + if (!soap->chunkbuflen) + { soap->chunkbuflen = ret = soap->frecv(soap, soap->buf, SOAP_BUFLEN); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Read %u bytes (chunked) from socket %d\n", (unsigned int)ret, soap->socket)); + DBGMSG(RECV, soap->buf, ret); + soap->bufidx = 0; + if (!ret) + return soap->ahead = EOF; + } + else + soap->bufidx = soap->buflen; + soap->buflen = soap->chunkbuflen; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Getting chunk size (idx=%u len=%u)\n", (unsigned int)soap->bufidx, (unsigned int)soap->buflen)); + while (!soap_isxdigit((int)(c = soap_getchunkchar(soap)))) + { if ((int)c == EOF) + return soap->ahead = EOF; + } + do + *t++ = (char)c; + while (soap_isxdigit((int)(c = soap_getchunkchar(soap))) && t - tmp < 7); + while ((int)c != EOF && c != '\n') + c = soap_getchunkchar(soap); + if ((int)c == EOF) + return soap->ahead = EOF; + *t = '\0'; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Chunk size = %s (hex)\n", tmp)); + soap->chunksize = soap_strtoul(tmp, &t, 16); + if (!soap->chunksize) + { soap->chunkbuflen = 0; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "End of chunked message\n")); + while ((int)c != EOF && c != '\n') + c = soap_getchunkchar(soap); + ret = 0; + soap->ahead = EOF; + break; + } + soap->buflen = soap->bufidx + soap->chunksize; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Moving buf len to idx=%u len=%u (%s)\n", (unsigned int)soap->bufidx, (unsigned int)soap->buflen, tmp)); + if (soap->buflen > soap->chunkbuflen) + { soap->buflen = soap->chunkbuflen; + soap->chunksize -= soap->buflen - soap->bufidx; + soap->chunkbuflen = 0; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Passed end of buffer for chunked HTTP (%u bytes left)\n", (unsigned int)(soap->buflen - soap->bufidx))); + } + else if (soap->chunkbuflen) + soap->chunksize = 0; + ret = soap->buflen - soap->bufidx; + if (ret) + break; + } + } + else +#endif + { soap->bufidx = 0; + soap->buflen = ret = soap->frecv(soap, soap->buf, SOAP_BUFLEN); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Read %u bytes from socket %d\n", (unsigned int)ret, soap->socket)); + DBGMSG(RECV, soap->buf, ret); + } +#ifndef WITH_LEANER + if (soap->fpreparerecv && (r = soap->fpreparerecv(soap, soap->buf, ret))) + return soap->error = r; +#endif +#ifdef WITH_ZLIB + if (soap->mode & SOAP_ENC_ZLIB) + { memcpy(soap->z_buf, soap->buf, SOAP_BUFLEN); + soap->d_stream->next_in = (Byte*)(soap->z_buf + soap->bufidx); + soap->d_stream->avail_in = (unsigned int)ret; + soap->d_stream->next_out = (Byte*)soap->buf; + soap->d_stream->avail_out = SOAP_BUFLEN; + r = inflate(soap->d_stream, Z_NO_FLUSH); + if (r == Z_NEED_DICT && soap->z_dict) + r = inflateSetDictionary(soap->d_stream, (const Bytef*)soap->z_dict, soap->z_dict_len); + if (r == Z_OK || r == Z_STREAM_END) + { soap->bufidx = 0; + soap->z_buflen = soap->buflen; + soap->buflen = SOAP_BUFLEN - soap->d_stream->avail_out; + if (soap->zlib_in == SOAP_ZLIB_GZIP) + soap->z_crc = crc32(soap->z_crc, (Byte*)soap->buf, (unsigned int)soap->buflen); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Inflated %u bytes\n", (unsigned int)soap->buflen)); + if (ret && !soap->buflen && r != Z_STREAM_END) + goto zlib_again; + ret = soap->buflen; + if (r == Z_STREAM_END) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Inflated total %lu->%lu bytes\n", soap->d_stream->total_in, soap->d_stream->total_out)); + soap->z_ratio_in = (float)soap->d_stream->total_in / (float)soap->d_stream->total_out; + soap->d_stream->next_out = Z_NULL; + } + DBGLOG(RECV, SOAP_MESSAGE(fdebug, "\n---- decompressed ----\n")); + DBGMSG(RECV, soap->buf, ret); + } + else + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unable to inflate: (%d) %s\n", r, soap->d_stream->msg?soap->d_stream->msg:SOAP_STR_EOS)); + soap->d_stream->next_out = Z_NULL; + soap->error = SOAP_ZLIB_ERROR; + return EOF; + } + } +#endif + soap->count += ret; + return !ret; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_recv(struct soap *soap) +{ +#ifndef WITH_LEANER + if (soap->mode & SOAP_ENC_DIME) + { if (soap->dime.buflen) + { char *s; + int i; + unsigned char tmp[12]; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "DIME hdr for chunked DIME is in buffer\n")); + soap->count += soap->dime.buflen - soap->buflen; + soap->buflen = soap->dime.buflen; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Skip padding (%ld bytes)\n", -(long)soap->dime.size&3)); + for (i = -(long)soap->dime.size&3; i > 0; i--) + { soap->bufidx++; + if (soap->bufidx >= soap->buflen) + if (soap_recv_raw(soap)) + return EOF; + } + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Get DIME hdr for next chunk\n")); + s = (char*)tmp; + for (i = 12; i > 0; i--) + { *s++ = soap->buf[soap->bufidx++]; + if (soap->bufidx >= soap->buflen) + if (soap_recv_raw(soap)) + return EOF; + } + soap->dime.flags = tmp[0] & 0x7; + soap->dime.size = ((size_t)tmp[8] << 24) | ((size_t)tmp[9] << 16) | ((size_t)tmp[10] << 8) | ((size_t)tmp[11]); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Get DIME chunk (%u bytes)\n", (unsigned int)soap->dime.size)); + if (soap->dime.flags & SOAP_DIME_CF) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "More chunking\n")); + soap->dime.chunksize = soap->dime.size; + if (soap->buflen - soap->bufidx >= soap->dime.size) + { soap->dime.buflen = soap->buflen; + soap->buflen = soap->bufidx + soap->dime.chunksize; + } + else + soap->dime.chunksize -= soap->buflen - soap->bufidx; + } + else + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Last chunk\n")); + soap->dime.buflen = 0; + soap->dime.chunksize = 0; + } + soap->count = soap->buflen - soap->bufidx; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "%u bytes remaining\n", (unsigned int)soap->count)); + return SOAP_OK; + } + if (soap->dime.chunksize) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Get next DIME hdr for chunked DIME (%u bytes chunk)\n", (unsigned int)soap->dime.chunksize)); + if (soap_recv_raw(soap)) + return EOF; + if (soap->buflen - soap->bufidx >= soap->dime.chunksize) + { soap->dime.buflen = soap->buflen; + soap->count -= soap->buflen - soap->bufidx - soap->dime.chunksize; + soap->buflen = soap->bufidx + soap->dime.chunksize; + } + else + soap->dime.chunksize -= soap->buflen - soap->bufidx; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "%lu bytes remaining, count=%u\n", (unsigned long)(soap->buflen-soap->bufidx), (unsigned int)soap->count)); + return SOAP_OK; + } + } +#endif + return soap_recv_raw(soap); +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +soap_wchar +SOAP_FMAC2 +soap_getchar(struct soap *soap) +{ register soap_wchar c; + c = soap->ahead; + if (c) + { if (c != EOF) + soap->ahead = 0; + return c; + } + return soap_get1(soap); +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +const struct soap_code_map* +SOAP_FMAC2 +soap_code(const struct soap_code_map *code_map, const char *str) +{ if (code_map && str) + { while (code_map->string) + { if (!strcmp(str, code_map->string)) /* case sensitive */ + return code_map; + code_map++; + } + } + return NULL; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +long +SOAP_FMAC2 +soap_code_int(const struct soap_code_map *code_map, const char *str, long other) +{ if (code_map) + { while (code_map->string) + { if (!soap_tag_cmp(str, code_map->string)) /* case insensitive */ + return code_map->code; + code_map++; + } + } + return other; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +const char* +SOAP_FMAC2 +soap_code_str(const struct soap_code_map *code_map, long code) +{ if (!code_map) + return NULL; + while (code_map->code != code && code_map->string) + code_map++; + return code_map->string; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +long +SOAP_FMAC2 +soap_code_bits(const struct soap_code_map *code_map, const char *str) +{ register long bits = 0; + if (code_map) + { while (str && *str) + { const struct soap_code_map *p; + for (p = code_map; p->string; p++) + { register size_t n = strlen(p->string); + if (!strncmp(p->string, str, n) && soap_blank(str[n])) + { bits |= p->code; + str += n; + while (*str > 0 && *str <= 32) + str++; + break; + } + } + if (!p->string) + return 0; + } + } + return bits; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +const char* +SOAP_FMAC2 +soap_code_list(struct soap *soap, const struct soap_code_map *code_map, long code) +{ register char *t = soap->tmpbuf; + if (code_map) + { while (code_map->string) + { if (code_map->code & code) + { register const char *s = code_map->string; + if (t != soap->tmpbuf) + *t++ = ' '; + while (*s && t < soap->tmpbuf + sizeof(soap->tmpbuf) - 1) + *t++ = *s++; + if (t == soap->tmpbuf + sizeof(soap->tmpbuf) - 1) + break; + } + code_map++; + } + } + *t = '\0'; + return soap->tmpbuf; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +static soap_wchar +soap_char(struct soap *soap) +{ char tmp[8]; + register int i; + register soap_wchar c; + register char *s = tmp; + for (i = 0; i < 7; i++) + { c = soap_get1(soap); + if (c == ';' || (int)c == EOF) + break; + *s++ = (char)c; + } + *s = '\0'; + if (*tmp == '#') + { if (tmp[1] == 'x' || tmp[1] == 'X') + return soap_strtol(tmp + 2, NULL, 16); + return atol(tmp + 1); + } + if (!strcmp(tmp, "lt")) + return '<'; + if (!strcmp(tmp, "gt")) + return '>'; + if (!strcmp(tmp, "amp")) + return '&'; + if (!strcmp(tmp, "quot")) + return '"'; + if (!strcmp(tmp, "apos")) + return '\''; +#ifndef WITH_LEAN + return (soap_wchar)soap_code_int(html_entity_codes, tmp, SOAP_UNKNOWN_CHAR); +#else + return SOAP_UNKNOWN_CHAR; /* use this to represent unknown code */ +#endif +} +#endif + +/******************************************************************************/ +#ifdef WITH_LEAN +#ifndef PALM_1 +soap_wchar +soap_get0(struct soap *soap) +{ if (soap->bufidx >= soap->buflen && soap_recv(soap)) + return EOF; + return (unsigned char)soap->buf[soap->bufidx]; +} +#endif +#endif + +/******************************************************************************/ +#ifdef WITH_LEAN +#ifndef PALM_1 +soap_wchar +soap_get1(struct soap *soap) +{ if (soap->bufidx >= soap->buflen && soap_recv(soap)) + return EOF; + return (unsigned char)soap->buf[soap->bufidx++]; +} +#endif +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +soap_wchar +SOAP_FMAC2 +soap_get(struct soap *soap) +{ register soap_wchar c; + c = soap->ahead; + if (c) + { if ((int)c != EOF) + soap->ahead = 0; + } + else + c = soap_get1(soap); + while ((int)c != EOF) + { if (soap->cdata) + { if (c == ']') + { c = soap_get1(soap); + if (c == ']') + { c = soap_get0(soap); + if (c == '>') + { soap->cdata = 0; + soap_get1(soap); + c = soap_get1(soap); + } + else + { soap_unget(soap, ']'); + return ']'; + } + } + else + { soap_revget1(soap); + return ']'; + } + } + else + return c; + } + switch (c) + { case '<': + do c = soap_get1(soap); + while (soap_blank(c)); + if (c == '!' || c == '?' || c == '%') + { register int k = 1; + if (c == '!') + { c = soap_get1(soap); + if (c == '[') + { do c = soap_get1(soap); + while ((int)c != EOF && c != '['); + if ((int)c == EOF) + break; + soap->cdata = 1; + c = soap_get1(soap); + continue; + } + if (c == '-' && (c = soap_get1(soap)) == '-') + { do + { c = soap_get1(soap); + if (c == '-' && (c = soap_get1(soap)) == '-') + break; + } while ((int)c != EOF); + } + } + else if (c == '?') + c = soap_get_pi(soap); + while ((int)c != EOF) + { if (c == '<') + k++; + else if (c == '>') + { if (--k <= 0) + break; + } + c = soap_get1(soap); + } + if ((int)c == EOF) + break; + c = soap_get1(soap); + continue; + } + if (c == '/') + return SOAP_TT; + soap_revget1(soap); + return SOAP_LT; + case '>': + return SOAP_GT; + case '"': + return SOAP_QT; + case '\'': + return SOAP_AP; + case '&': + return soap_char(soap) | 0x80000000; + } + break; + } + return c; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +static soap_wchar +soap_get_pi(struct soap *soap) +{ char buf[64]; + register char *s = buf; + register int i = sizeof(buf); + register soap_wchar c = soap_getchar(soap); + /* This is a quick way to parse XML PI and we could use a callback instead to + * enable applications to intercept processing instructions */ + while ((int)c != EOF && c != '?') + { if (--i > 0) + { if (soap_blank(c)) + c = ' '; + *s++ = (char)c; + } + c = soap_getchar(soap); + } + *s = '\0'; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "XML PI \n", buf)); + if (!strncmp(buf, "xml ", 4)) + { s = strstr(buf, " encoding="); + if (s && s[10]) + { if (!soap_tag_cmp(s + 11, "iso-8859-1*") + || !soap_tag_cmp(s + 11, "latin1*")) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Switching to latin1 encoding\n")); + soap->mode |= SOAP_ENC_LATIN; + } + else if (!soap_tag_cmp(s + 11, "utf-8*")) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Switching to utf-8 encoding\n")); + soap->mode &= ~SOAP_ENC_LATIN; + } + } + } + if ((int)c != EOF) + c = soap_getchar(soap); + return c; +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_move(struct soap *soap, long n) +{ DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Moving %ld bytes forward\n", (long)n)); + for (; n > 0; n--) + if ((int)soap_getchar(soap) == EOF) + return SOAP_EOF; + return SOAP_OK; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +SOAP_FMAC1 +size_t +SOAP_FMAC2 +soap_tell(struct soap *soap) +{ return soap->count - soap->buflen + soap->bufidx - (soap->ahead != 0); +} +#endif +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_pututf8(struct soap *soap, register unsigned long c) +{ char tmp[16]; + if (c < 0x80 && c > 0) + { *tmp = (char)c; + return soap_send_raw(soap, tmp, 1); + } +#ifndef WITH_LEAN + if (c >= 0x80) + { register char *t = tmp; + if (c < 0x0800) + *t++ = (char)(0xC0 | ((c >> 6) & 0x1F)); + else + { if (c < 0x010000) + *t++ = (char)(0xE0 | ((c >> 12) & 0x0F)); + else + { if (c < 0x200000) + *t++ = (char)(0xF0 | ((c >> 18) & 0x07)); + else + { if (c < 0x04000000) + *t++ = (char)(0xF8 | ((c >> 24) & 0x03)); + else + { *t++ = (char)(0xFC | ((c >> 30) & 0x01)); + *t++ = (char)(0x80 | ((c >> 24) & 0x3F)); + } + *t++ = (char)(0x80 | ((c >> 18) & 0x3F)); + } + *t++ = (char)(0x80 | ((c >> 12) & 0x3F)); + } + *t++ = (char)(0x80 | ((c >> 6) & 0x3F)); + } + *t++ = (char)(0x80 | (c & 0x3F)); + *t = '\0'; + } +#else + sprintf(tmp, "&#%lu;", c); +#endif + return soap_send(soap, tmp); +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +soap_wchar +SOAP_FMAC2 +soap_getutf8(struct soap *soap) +{ register soap_wchar c, c1, c2, c3, c4; + c = soap->ahead; + if (c > 0x7F) + { soap->ahead = 0; + return c; + } + c = soap_get(soap); + if (c < 0x80 || (soap->mode & SOAP_ENC_LATIN)) + return c; + c1 = soap_get1(soap); + if (c1 < 0x80) + { soap_revget1(soap); /* doesn't look like this is UTF8 */ + return c; + } + c1 &= 0x3F; + if (c < 0xE0) + return ((soap_wchar)(c & 0x1F) << 6) | c1; + c2 = (soap_wchar)soap_get1(soap) & 0x3F; + if (c < 0xF0) + return ((soap_wchar)(c & 0x0F) << 12) | (c1 << 6) | c2; + c3 = (soap_wchar)soap_get1(soap) & 0x3F; + if (c < 0xF8) + return ((soap_wchar)(c & 0x07) << 18) | (c1 << 12) | (c2 << 6) | c3; + c4 = (soap_wchar)soap_get1(soap) & 0x3F; + if (c < 0xFC) + return ((soap_wchar)(c & 0x03) << 24) | (c1 << 18) | (c2 << 12) | (c3 << 6) | c4; + return ((soap_wchar)(c & 0x01) << 30) | (c1 << 24) | (c2 << 18) | (c3 << 12) | (c4 << 6) | (soap_wchar)(soap_get1(soap) & 0x3F); +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_puthex(struct soap *soap, const unsigned char *s, int n) +{ char d[2]; + register int i; +#ifdef WITH_DOM + if ((soap->mode & SOAP_XML_DOM) && soap->dom) + { if (!(soap->dom->data = soap_s2hex(soap, s, NULL, n))) + return soap->error; + return SOAP_OK; + } +#endif + for (i = 0; i < n; i++) + { register int m = *s++; + d[0] = (char)((m >> 4) + (m > 159 ? '7' : '0')); + m &= 0x0F; + d[1] = (char)(m + (m > 9 ? '7' : '0')); + if (soap_send_raw(soap, d, 2)) + return soap->error; + } + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +unsigned char* +SOAP_FMAC2 +soap_gethex(struct soap *soap, int *n) +{ +#ifdef WITH_DOM + if ((soap->mode & SOAP_XML_DOM) && soap->dom) + { soap->dom->data = soap_string_in(soap, 0, -1, -1); + return (unsigned char*)soap_hex2s(soap, soap->dom->data, NULL, 0, n); + } +#endif +#ifdef WITH_FAST + soap->labidx = 0; + for (;;) + { register char *s; + register size_t i, k; + if (soap_append_lab(soap, NULL, 0)) + return NULL; + s = soap->labbuf + soap->labidx; + k = soap->lablen - soap->labidx; + soap->labidx = soap->lablen; + for (i = 0; i < k; i++) + { register char d1, d2; + register soap_wchar c; + c = soap_get(soap); + if (soap_isxdigit(c)) + { d1 = (char)c; + c = soap_get(soap); + if (soap_isxdigit(c)) + d2 = (char)c; + else + { soap->error = SOAP_TYPE; + return NULL; + } + } + else + { unsigned char *p; + soap_unget(soap, c); + if (n) + *n = (int)(soap->lablen + i - k); + p = (unsigned char*)soap_malloc(soap, soap->lablen + i - k); + if (p) + memcpy(p, soap->labbuf, soap->lablen + i - k); + return p; + } + *s++ = ((d1 >= 'A' ? (d1 & 0x7) + 9 : d1 - '0') << 4) + (d2 >= 'A' ? (d2 & 0x7) + 9 : d2 - '0'); + } + } +#else + if (soap_new_block(soap) == NULL) + return NULL; + for (;;) + { register int i; + register char *s = (char*)soap_push_block(soap, NULL, SOAP_BLKLEN); + if (!s) + { soap_end_block(soap, NULL); + return NULL; + } + for (i = 0; i < SOAP_BLKLEN; i++) + { register char d1, d2; + register soap_wchar c = soap_get(soap); + if (soap_isxdigit(c)) + { d1 = (char)c; + c = soap_get(soap); + if (soap_isxdigit(c)) + d2 = (char)c; + else + { soap_end_block(soap, NULL); + soap->error = SOAP_TYPE; + return NULL; + } + } + else + { unsigned char *p; + soap_unget(soap, c); + if (n) + *n = (int)soap_size_block(soap, NULL, i); + p = (unsigned char*)soap_save_block(soap, NULL, 0); + return p; + } + *s++ = ((d1 >= 'A' ? (d1 & 0x7) + 9 : d1 - '0') << 4) + (d2 >= 'A' ? (d2 & 0x7) + 9 : d2 - '0'); + } + } +#endif +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_putbase64(struct soap *soap, const unsigned char *s, int n) +{ register int i; + register unsigned long m; + char d[4]; + if (!s) + return SOAP_OK; +#ifdef WITH_DOM + if ((soap->mode & SOAP_XML_DOM) && soap->dom) + { if (!(soap->dom->data = soap_s2base64(soap, s, NULL, n))) + return soap->error; + return SOAP_OK; + } +#endif + for (; n > 2; n -= 3, s += 3) + { m = s[0]; + m = (m << 8) | s[1]; + m = (m << 8) | s[2]; + for (i = 4; i > 0; m >>= 6) + d[--i] = soap_base64o[m & 0x3F]; + if (soap_send_raw(soap, d, 4)) + return soap->error; + } + if (n > 0) + { m = 0; + for (i = 0; i < n; i++) + m = (m << 8) | *s++; + for (; i < 3; i++) + m <<= 8; + for (i++; i > 0; m >>= 6) + d[--i] = soap_base64o[m & 0x3F]; + for (i = 3; i > n; i--) + d[i] = '='; + if (soap_send_raw(soap, d, 4)) + return soap->error; + } + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +unsigned char* +SOAP_FMAC2 +soap_getbase64(struct soap *soap, int *n, int malloc_flag) +{ +#ifdef WITH_DOM + if ((soap->mode & SOAP_XML_DOM) && soap->dom) + { soap->dom->data = soap_string_in(soap, 0, -1, -1); + return (unsigned char*)soap_base642s(soap, soap->dom->data, NULL, 0, n); + } +#endif +#ifdef WITH_FAST + soap->labidx = 0; + for (;;) + { register size_t i, k; + register char *s; + if (soap_append_lab(soap, NULL, 2)) + return NULL; + s = soap->labbuf + soap->labidx; + k = soap->lablen - soap->labidx; + soap->labidx = 3 * (soap->lablen / 3); + if (!s) + return NULL; + if (k > 2) + { for (i = 0; i < k - 2; i += 3) + { register unsigned long m = 0; + register int j = 0; + do + { register soap_wchar c = soap_get(soap); + if (c == '=' || c < 0) + { unsigned char *p; + switch (j) + { case 2: + *s++ = (char)((m >> 4) & 0xFF); + i++; + break; + case 3: + *s++ = (char)((m >> 10) & 0xFF); + *s++ = (char)((m >> 2) & 0xFF); + i += 2; + } + if (n) + *n = (int)(soap->lablen + i - k); + p = (unsigned char*)soap_malloc(soap, soap->lablen + i - k); + if (p) + memcpy(p, soap->labbuf, soap->lablen + i - k); + if (c >= 0) + { while ((int)((c = soap_get(soap)) != EOF) && c != SOAP_LT && c != SOAP_TT) + ; + } + soap_unget(soap, c); + return p; + } + c -= '+'; + if (c >= 0 && c <= 79) + { register int b = soap_base64i[c]; + if (b >= 64) + { soap->error = SOAP_TYPE; + return NULL; + } + m = (m << 6) + b; + j++; + } + else if (!soap_blank(c + '+')) + { soap->error = SOAP_TYPE; + return NULL; + } + } while (j < 4); + *s++ = (char)((m >> 16) & 0xFF); + *s++ = (char)((m >> 8) & 0xFF); + *s++ = (char)(m & 0xFF); + } + } + } +#else + if (soap_new_block(soap) == NULL) + return NULL; + for (;;) + { register int i; + register char *s = (char*)soap_push_block(soap, NULL, 3 * SOAP_BLKLEN); /* must be multiple of 3 */ + if (!s) + { soap_end_block(soap, NULL); + return NULL; + } + for (i = 0; i < SOAP_BLKLEN; i++) + { register unsigned long m = 0; + register int j = 0; + do + { register soap_wchar c = soap_get(soap); + if (c == '=' || c < 0) + { unsigned char *p; + i *= 3; + switch (j) + { case 2: + *s++ = (char)((m >> 4) & 0xFF); + i++; + break; + case 3: + *s++ = (char)((m >> 10) & 0xFF); + *s++ = (char)((m >> 2) & 0xFF); + i += 2; + } + if (n) + *n = (int)soap_size_block(soap, NULL, i); + p = (unsigned char*)soap_save_block(soap, NULL, 0); + if (c >= 0) + { while ((int)((c = soap_get(soap)) != EOF) && c != SOAP_LT && c != SOAP_TT) + ; + } + soap_unget(soap, c); + return p; + } + c -= '+'; + if (c >= 0 && c <= 79) + { int b = soap_base64i[c]; + if (b >= 64) + { soap->error = SOAP_TYPE; + return NULL; + } + m = (m << 6) + b; + j++; + } + else if (!soap_blank(c)) + { soap->error = SOAP_TYPE; + return NULL; + } + } while (j < 4); + *s++ = (char)((m >> 16) & 0xFF); + *s++ = (char)((m >> 8) & 0xFF); + *s++ = (char)(m & 0xFF); + } + } +#endif +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_xop_forward(struct soap *soap, unsigned char **ptr, int *size, char **id, char **type, char **options) +{ /* Check MTOM xop:Include element (within hex/base64Binary) */ + /* TODO: this code to be obsoleted with new import/xop.h conventions */ + int body = soap->body; /* should save type too? */ + if (!soap_peek_element(soap)) + { if (!soap_element_begin_in(soap, "xop:Include", 0, NULL) && *soap->href) + { if (soap_dime_forward(soap, ptr, size, id, type, options)) + return soap->error; + } + if (soap->body && soap_element_end_in(soap, NULL)) + return soap->error; + } + soap->body = body; + return SOAP_OK; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_dime_forward(struct soap *soap, unsigned char **ptr, int *size, char **id, char **type, char **options) +{ struct soap_xlist *xp; + *ptr = NULL; + *size = 0; + *id = NULL; + *type = NULL; + *options = NULL; + if (!*soap->href) + return SOAP_OK; + *id = soap_strdup(soap, soap->href); + xp = (struct soap_xlist*)SOAP_MALLOC(soap, sizeof(struct soap_xlist)); + if (!xp) + return soap->error = SOAP_EOM; + xp->next = soap->xlist; + xp->ptr = ptr; + xp->size = size; + xp->id = *id; + xp->type = type; + xp->options = options; + soap->xlist = xp; + return SOAP_OK; +} +#endif +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +char * +SOAP_FMAC2 +soap_strdup(struct soap *soap, const char *s) +{ char *t = NULL; + if (s && (t = (char*)soap_malloc(soap, strlen(s) + 1))) + strcpy(t, s); + return t; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +wchar_t * +SOAP_FMAC2 +soap_wstrdup(struct soap *soap, const wchar_t *s) +{ wchar_t *t = NULL; + if (s) + { size_t n = 0; + while (s[n]) + n++; + if ((t = (wchar_t*)soap_malloc(soap, sizeof(wchar_t)*(n+1)))) + memcpy(t, s, sizeof(wchar_t)*(n+1)); + } + return t; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +struct soap_blist* +SOAP_FMAC2 +soap_new_block(struct soap *soap) +{ struct soap_blist *p; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "New block sequence (prev=%p)\n", soap->blist)); + if (!(p = (struct soap_blist*)SOAP_MALLOC(soap, sizeof(struct soap_blist)))) + { soap->error = SOAP_EOM; + return NULL; + } + p->next = soap->blist; + p->ptr = NULL; + p->size = 0; + soap->blist = p; + return p; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +void* +SOAP_FMAC2 +soap_push_block(struct soap *soap, struct soap_blist *b, size_t n) +{ char *p; + if (!b) + b = soap->blist; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Push block of %u bytes (%u bytes total)\n", (unsigned int)n, (unsigned int)b->size + (unsigned int)n)); + if (!(p = (char*)SOAP_MALLOC(soap, n + sizeof(char*) + sizeof(size_t)))) + { soap->error = SOAP_EOM; + return NULL; + } + *(char**)p = b->ptr; + *(size_t*)(p + sizeof(char*)) = n; + b->ptr = p; + b->size += n; + return p + sizeof(char*) + sizeof(size_t); +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_pop_block(struct soap *soap, struct soap_blist *b) +{ char *p; + if (!b) + b = soap->blist; + if (!b->ptr) + return; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Pop block\n")); + p = b->ptr; + b->size -= *(size_t*)(p + sizeof(char*)); + b->ptr = *(char**)p; + SOAP_FREE(soap, p); +} +#endif + +/******************************************************************************/ +#ifndef WITH_NOIDREF +#ifndef PALM_1 +static void +soap_update_ptrs(struct soap *soap, char *start, char *end, char *p1, char *p2) +{ int i; + register struct soap_ilist *ip = NULL; + register struct soap_flist *fp = NULL; +#ifndef WITH_LEANER + register struct soap_xlist *xp = NULL; +#endif + register void *p, **q; + for (i = 0; i < SOAP_IDHASH; i++) + { for (ip = soap->iht[i]; ip; ip = ip->next) + { if (ip->ptr && (char*)ip->ptr >= start && (char*)ip->ptr < end) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Update id='%s' %p -> %p\n", ip->id, ip->ptr, (char*)ip->ptr + (p1-p2))); + ip->ptr = (char*)ip->ptr + (p1-p2); + } + for (q = &ip->link; q; q = (void**)p) + { p = *q; + if (p && (char*)p >= start && (char*)p < end) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Link update id='%s' %p\n", ip->id, p)); + *q = (char*)p + (p1-p2); + } + } + for (q = &ip->copy; q; q = (void**)p) + { p = *q; + if (p && (char*)p >= start && (char*)p < end) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copy chain update id='%s' %p\n", ip->id, p)); + *q = (char*)p + (p1-p2); + } + } + for (fp = ip->flist; fp; fp = fp->next) + { if ((char*)fp->ptr >= start && (char*)fp->ptr < end) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copy list update id='%s' %p\n", ip->id, fp)); + fp->ptr = (char*)fp->ptr + (p1-p2); + } + } + } + } +#ifndef WITH_LEANER + for (xp = soap->xlist; xp; xp = xp->next) + { if (xp->ptr && (char*)xp->ptr >= start && (char*)xp->ptr < end) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Update id='%s' %p -> %p\n", xp->id?xp->id:SOAP_STR_EOS, xp->ptr, (char*)xp->ptr + (p1-p2))); + xp->ptr = (unsigned char**)((char*)xp->ptr + (p1-p2)); + xp->size = (int*)((char*)xp->size + (p1-p2)); + xp->type = (char**)((char*)xp->type + (p1-p2)); + xp->options = (char**)((char*)xp->options + (p1-p2)); + } + } +#endif +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIDREF +#ifndef PALM_1 +static int +soap_has_copies(struct soap *soap, register const char *start, register const char *end) +{ register int i; + register struct soap_ilist *ip = NULL; + register struct soap_flist *fp = NULL; + register const char *p; + for (i = 0; i < SOAP_IDHASH; i++) + { for (ip = soap->iht[i]; ip; ip = ip->next) + { for (p = (const char*)ip->copy; p; p = *(const char**)p) + if (p >= start && p < end) + return SOAP_ERR; + for (fp = ip->flist; fp; fp = fp->next) + if ((const char*)fp->ptr >= start && (const char*)fp->ptr < end) + return SOAP_ERR; + } + } + return SOAP_OK; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIDREF +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_resolve(struct soap *soap) +{ register int i; + register struct soap_ilist *ip = NULL; + register struct soap_flist *fp = NULL; + short flag; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Resolving forwarded data\n")); + for (i = 0; i < SOAP_IDHASH; i++) + { for (ip = soap->iht[i]; ip; ip = ip->next) + { if (ip->ptr) + { register void *p, **q, *r; + q = (void**)ip->link; + ip->link = NULL; + r = ip->ptr; + DBGLOG(TEST, if (q) SOAP_MESSAGE(fdebug, "Traversing link chain to resolve id='%s'\n", ip->id)); + while (q) + { p = *q; + *q = r; + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "... link %p -> %p\n", q, r)); + q = (void**)p; + } + } + else if (*ip->id == '#') + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Missing data for id='%s'\n", ip->id)); + strcpy(soap->id, ip->id + 1); + return soap->error = SOAP_MISSING_ID; + } + } + } + do + { flag = 0; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Resolution phase\n")); + for (i = 0; i < SOAP_IDHASH; i++) + { for (ip = soap->iht[i]; ip; ip = ip->next) + { if (ip->ptr && !soap_has_copies(soap, (const char*)ip->ptr, (const char*)ip->ptr + ip->size)) + { if (ip->copy) + { register void *p, **q = (void**)ip->copy; + DBGLOG(TEST, if (q) SOAP_MESSAGE(fdebug, "Traversing copy chain to resolve id='%s'\n", ip->id)); + ip->copy = NULL; + do + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "... copy %p -> %p (%u bytes)\n", ip->ptr, q, (unsigned int)ip->size)); + p = *q; + memcpy(q, ip->ptr, ip->size); + q = (void**)p; + } while (q); + flag = 1; + } + for (fp = ip->flist; fp; fp = ip->flist) + { register unsigned int k = fp->level; + register void *p = ip->ptr; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Resolving forwarded data type=%d location=%p level=%u,%u id='%s'\n", ip->type, p, ip->level, fp->level, ip->id)); + while (ip->level < k) + { register void **q = (void**)soap_malloc(soap, sizeof(void*)); + if (!q) + return soap->error; + *q = p; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Descending one level, new location=%p holds=%p...\n", q, *q)); + p = (void*)q; + k--; + } + if (fp->fcopy) + fp->fcopy(soap, ip->type, fp->type, fp->ptr, fp->len, p, ip->size); + else + soap_fcopy(soap, ip->type, fp->type, fp->ptr, fp->len, p, ip->size); + ip->flist = fp->next; + SOAP_FREE(soap, fp); + flag = 1; + } + } + } + } + } while (flag); +#ifdef SOAP_DEBUG + for (i = 0; i < SOAP_IDHASH; i++) + { for (ip = soap->iht[i]; ip; ip = ip->next) + { if (ip->copy || ip->flist) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Resolution error: forwarded data for id='%s' could not be propagated, please report this problem to the developers\n", ip->id)); + } + } + } +#endif + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Resolution done\n")); + return SOAP_OK; +} +#endif +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +size_t +SOAP_FMAC2 +soap_size_block(struct soap *soap, struct soap_blist *b, size_t n) +{ if (!b) + b = soap->blist; + if (b->ptr) + { b->size -= *(size_t*)(b->ptr + sizeof(char*)) - n; + *(size_t*)(b->ptr + sizeof(char*)) = n; + } + return b->size; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +char* +SOAP_FMAC2 +soap_first_block(struct soap *soap, struct soap_blist *b) +{ char *p, *q, *r; + if (!b) + b = soap->blist; + p = b->ptr; + if (!p) + return NULL; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "First block\n")); + r = NULL; + do + { q = *(char**)p; + *(char**)p = r; + r = p; + p = q; + } while (p); + b->ptr = r; + return r + sizeof(char*) + sizeof(size_t); +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +char* +SOAP_FMAC2 +soap_next_block(struct soap *soap, struct soap_blist *b) +{ char *p; + if (!b) + b = soap->blist; + p = b->ptr; + if (p) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Next block\n")); + b->ptr = *(char**)p; + SOAP_FREE(soap, p); + if (b->ptr) + return b->ptr + sizeof(char*) + sizeof(size_t); + } + return NULL; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +size_t +SOAP_FMAC2 +soap_block_size(struct soap *soap, struct soap_blist *b) +{ if (!b) + b = soap->blist; + return *(size_t*)(b->ptr + sizeof(char*)); +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_end_block(struct soap *soap, struct soap_blist *b) +{ char *p, *q; + if (!b) + b = soap->blist; + if (b) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "End of block sequence, free all remaining blocks\n")); + for (p = b->ptr; p; p = q) + { q = *(char**)p; + SOAP_FREE(soap, p); + } + if (soap->blist == b) + soap->blist = b->next; + else + { struct soap_blist *bp; + for (bp = soap->blist; bp; bp = bp->next) + { if (bp->next == b) + { bp->next = b->next; + break; + } + } + } + SOAP_FREE(soap, b); + } + DBGLOG(TEST, if (soap->blist) SOAP_MESSAGE(fdebug, "Restore previous block sequence\n")); +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +char* +SOAP_FMAC2 +soap_save_block(struct soap *soap, struct soap_blist *b, char *p, int flag) +{ register size_t n; + register char *q, *s; + if (!b) + b = soap->blist; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Save all blocks in contiguous memory space of %u bytes (%p->%p)\n", (unsigned int)b->size, b->ptr, p)); + if (b->size) + { if (!p) + p = (char*)soap_malloc(soap, b->size); + if (p) + { for (s = p, q = soap_first_block(soap, b); q; q = soap_next_block(soap, b)) + { n = soap_block_size(soap, b); +#ifndef WITH_NOIDREF + if (flag) + soap_update_ptrs(soap, q, q + n, s, q); +#endif + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copy %u bytes from %p to %p\n", (unsigned int)n, q, s)); + memcpy(s, q, n); + s += n; + } + } + else + soap->error = SOAP_EOM; + } + soap_end_block(soap, b); + return p; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +char * +SOAP_FMAC2 +soap_putsize(struct soap *soap, const char *type, int size) +{ return soap_putsizes(soap, type, &size, 1); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +char * +SOAP_FMAC2 +soap_putsizes(struct soap *soap, const char *type, const int *size, int dim) +{ return soap_putsizesoffsets(soap, type, size, NULL, dim); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +char * +SOAP_FMAC2 +soap_putsizesoffsets(struct soap *soap, const char *type, const int *size, const int *offset, int dim) +{ int i; + if (!type) + return NULL; + if (soap->version == 2) + { sprintf(soap->type, "%s[%d", type, size[0]); + for (i = 1; i < dim; i++) + sprintf(soap->type + strlen(soap->type), " %d", size[i]); + } + else + { if (offset) + { sprintf(soap->type, "%s[%d", type, size[0] + offset[0]); + for (i = 1; i < dim; i++) + sprintf(soap->type + strlen(soap->type), ",%d", size[i] + offset[i]); + } + else + { sprintf(soap->type, "%s[%d", type, size[0]); + for (i = 1; i < dim; i++) + sprintf(soap->type + strlen(soap->type), ",%d", size[i]); + } + strcat(soap->type, "]"); + } + return soap->type; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +char * +SOAP_FMAC2 +soap_putoffset(struct soap *soap, int offset) +{ return soap_putoffsets(soap, &offset, 1); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +char * +SOAP_FMAC2 +soap_putoffsets(struct soap *soap, const int *offset, int dim) +{ register int i; + sprintf(soap->arrayOffset, "[%d", offset[0]); + for (i = 1; i < dim; i++) + sprintf(soap->arrayOffset + strlen(soap->arrayOffset), ",%d", offset[i]); + strcat(soap->arrayOffset, "]"); + return soap->arrayOffset; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_size(const int *size, int dim) +{ register int i, n = size[0]; + for (i = 1; i < dim; i++) + n *= size[i]; + return n; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_getoffsets(const char *attr, const int *size, int *offset, int dim) +{ register int i, j = 0; + if (offset) + for (i = 0; i < dim && attr && *attr; i++) + { attr++; + j *= size[i]; + j += offset[i] = (int)atol(attr); + attr = strchr(attr, ','); + } + else + for (i = 0; i < dim && attr && *attr; i++) + { attr++; + j *= size[i]; + j += (int)atol(attr); + attr = strchr(attr, ','); + } + return j; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_getsize(const char *attr1, const char *attr2, int *j) +{ register int n, k; + char *s; + *j = 0; + if (!*attr1) + return -1; + if (*attr1 == '[') + attr1++; + n = 1; + for (;;) + { k = (int)soap_strtol(attr1, &s, 10); + n *= k; + if (k < 0 || n > SOAP_MAXARRAYSIZE || s == attr1) + return -1; + attr1 = strchr(s, ','); + if (!attr1) + attr1 = strchr(s, ' '); + if (attr2 && *attr2) + { attr2++; + *j *= k; + k = (int)soap_strtol(attr2, &s, 10); + *j += k; + if (k < 0) + return -1; + attr2 = s; + } + if (!attr1) + break; + attr1++; + } + return n - *j; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_getsizes(const char *attr, int *size, int dim) +{ register int i, k, n; + if (!*attr) + return -1; + i = (int)strlen(attr); + n = 1; + do + { for (i = i-1; i >= 0; i--) + if (attr[i] == '[' || attr[i] == ',' || attr[i] == ' ') + break; + k = (int)atol(attr + i + 1); + n *= size[--dim] = k; + if (k < 0 || n > SOAP_MAXARRAYSIZE) + return -1; + } while (i >= 0 && attr[i] != '['); + return n; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_getposition(const char *attr, int *pos) +{ register int i, n; + if (!*attr) + return -1; + n = 0; + i = 1; + do + { pos[n++] = (int)atol(attr + i); + while (attr[i] && attr[i] != ',' && attr[i] != ']') + i++; + if (attr[i] == ',') + i++; + } while (n < SOAP_MAXDIMS && attr[i] && attr[i] != ']'); + return n; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +struct soap_nlist * +SOAP_FMAC2 +soap_push_namespace(struct soap *soap, const char *id, const char *ns) +{ register struct soap_nlist *np; + register struct Namespace *p; + register short i = -1; + register size_t n, k; + n = strlen(id); + k = strlen(ns) + 1; + p = soap->local_namespaces; + if (p) + { for (i = 0; p->id; p++, i++) + { if (p->ns && !strcmp(ns, p->ns)) + { if (p->out) + { SOAP_FREE(soap, p->out); + p->out = NULL; + } + break; + } + if (p->out) + { if (!strcmp(ns, p->out)) + break; + } + else if (p->in) + { if (!soap_tag_cmp(ns, p->in)) + { if ((p->out = (char*)SOAP_MALLOC(soap, k))) + strcpy(p->out, ns); + break; + } + } + } + if (!p || !p->id) + i = -1; + } + if (i >= 0) + k = 0; + np = (struct soap_nlist*)SOAP_MALLOC(soap, sizeof(struct soap_nlist) + n + k); + if (!np) + { soap->error = SOAP_EOM; + return NULL; + } + np->next = soap->nlist; + soap->nlist = np; + np->level = soap->level; + np->index = i; + strcpy(np->id, id); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Push namespace binding (level=%u) '%s' '%s'\n", soap->level, id, ns)); + if (i < 0) + { np->ns = strcpy(np->id + n + 1, ns); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Push NOT OK: no match found for '%s' in namespace mapping table (added to stack anyway)\n", ns)); + } + else + { np->ns = NULL; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Push OK ('%s' matches '%s' in namespace table)\n", id, p->id)); + } + return np; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_pop_namespace(struct soap *soap) +{ register struct soap_nlist *np, *nq; + for (np = soap->nlist; np && np->level >= soap->level; np = nq) + { nq = np->next; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Pop namespace binding (level=%u) '%s'\n", soap->level, np->id)); + SOAP_FREE(soap, np); + } + soap->nlist = np; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_match_namespace(struct soap *soap, const char *id1, const char *id2, size_t n1, size_t n2) +{ register struct soap_nlist *np = soap->nlist; + while (np && (strncmp(np->id, id1, n1) || np->id[n1])) + np = np->next; + if (np) + { if (np->index < 0 + || (soap->local_namespaces[np->index].id + && (strncmp(soap->local_namespaces[np->index].id, id2, n2) + || soap->local_namespaces[np->index].id[n2]))) + return SOAP_NAMESPACE; + return SOAP_OK; + } + if (n1 == 3 && n1 == n2 && !strncmp(id1, "xml", 3) && !strncmp(id1, id2, 3)) + return SOAP_OK; + return soap->error = SOAP_SYNTAX_ERROR; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +const char* +SOAP_FMAC2 +soap_current_namespace(struct soap *soap, const char *tag) +{ register struct soap_nlist *np; + register const char *s; + if (!tag || !strncmp(tag, "xml", 3)) + return NULL; + np = soap->nlist; + if (!(s = strchr(tag, ':'))) + { while (np && *np->id) /* find default namespace, if present */ + np = np->next; + } + else + { while (np && (strncmp(np->id, tag, s - tag) || np->id[s - tag])) + np = np->next; + if (!np) + soap->error = SOAP_NAMESPACE; + } + if (np) + { if (np->index >= 0) + return soap->namespaces[np->index].ns; + if (np->ns) + return soap_strdup(soap, np->ns); + } + return NULL; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_tag_cmp(const char *s, const char *t) +{ for (;;) + { register int c1 = *s; + register int c2 = *t; + if (!c1 || c1 == '"') + break; + if (c2 != '-') + { if (c1 != c2) + { if (c1 >= 'A' && c1 <= 'Z') + c1 += 'a' - 'A'; + if (c2 >= 'A' && c2 <= 'Z') + c2 += 'a' - 'A'; + } + if (c1 != c2) + { if (c2 != '*') + return 1; + c2 = *++t; + if (!c2) + return 0; + if (c2 >= 'A' && c2 <= 'Z') + c2 += 'a' - 'A'; + for (;;) + { c1 = *s; + if (!c1 || c1 == '"') + break; + if (c1 >= 'A' && c1 <= 'Z') + c1 += 'a' - 'A'; + if (c1 == c2 && !soap_tag_cmp(s + 1, t + 1)) + return 0; + s++; + } + break; + } + } + s++; + t++; + } + if (*t == '*' && !t[1]) + return 0; + return *t; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_match_tag(struct soap *soap, const char *tag1, const char *tag2) +{ register const char *s, *t; + register int err; + if (!tag1 || !tag2 || !*tag2) + return SOAP_OK; + s = strchr(tag1, ':'); + t = strchr(tag2, ':'); + if (t) + { if (s) + { if (t[1] && SOAP_STRCMP(s + 1, t + 1)) + return SOAP_TAG_MISMATCH; + if (t != tag2 && (err = soap_match_namespace(soap, tag1, tag2, s - tag1, t - tag2))) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Tags '%s' and '%s' match but namespaces differ\n", tag1, tag2)); + if (err == SOAP_NAMESPACE) + return SOAP_TAG_MISMATCH; + return err; + } + } + else if (SOAP_STRCMP(tag1, t + 1)) + { return SOAP_TAG_MISMATCH; + } + else if (t != tag2 && (err = soap_match_namespace(soap, tag1, tag2, 0, t - tag2))) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Tags '%s' and '%s' match but namespaces differ\n", tag1, tag2)); + if (err == SOAP_NAMESPACE) + return SOAP_TAG_MISMATCH; + return err; + } + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Tags and (default) namespaces match: '%s' '%s'\n", tag1, tag2)); + return SOAP_OK; + } + if (s) + { if (SOAP_STRCMP(s + 1, tag2)) + return SOAP_TAG_MISMATCH; + } + else if (SOAP_STRCMP(tag1, tag2)) + return SOAP_TAG_MISMATCH; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Tags match: '%s' '%s'\n", tag1, tag2)); + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_match_array(struct soap *soap, const char *type) +{ if (*soap->arrayType) + if (soap_match_tag(soap, soap->arrayType, type) + && soap_match_tag(soap, soap->arrayType, "xsd:anyType") + && soap_match_tag(soap, soap->arrayType, "xsd:ur-type") + ) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Array type mismatch: '%s' '%s'\n", soap->arrayType, type)); + return SOAP_TAG_MISMATCH; + } + return SOAP_OK; +} +#endif + +/******************************************************************************\ + * + * SSL + * +\******************************************************************************/ + +#ifdef WITH_OPENSSL +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_rand() +{ unsigned char buf[4]; + if (!soap_ssl_init_done) + soap_ssl_init(); + RAND_pseudo_bytes(buf, 4); + return *(int*)buf; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_ssl_server_context(struct soap *soap, unsigned short flags, const char *keyfile, const char *password, const char *cafile, const char *capath, const char *dhfile, const char *randfile, const char *sid) +{ int err; + soap->keyfile = keyfile; + soap->password = password; + soap->cafile = cafile; + soap->capath = capath; + soap->dhfile = dhfile; + soap->randfile = randfile; + soap->ssl_flags = flags | (dhfile == NULL ? SOAP_SSL_RSA : 0); + if (!(err = soap->fsslauth(soap))) + { if (sid) + SSL_CTX_set_session_id_context(soap->ctx, (unsigned char*)sid, (unsigned int)strlen(sid)); + } + return err; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_ssl_client_context(struct soap *soap, unsigned short flags, const char *keyfile, const char *password, const char *cafile, const char *capath, const char *randfile) +{ soap->keyfile = keyfile; + soap->password = password; + soap->cafile = cafile; + soap->capath = capath; + soap->dhfile = NULL; + soap->ssl_flags = flags; + soap->randfile = randfile; + soap->fsslverify = (flags & SOAP_SSL_ALLOW_EXPIRED_CERTIFICATE) == 0 ? ssl_verify_callback : ssl_verify_callback_allow_expired_certificate; + return soap->fsslauth(soap); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_ssl_init() +{ /* Note: for MT systems, the main program MUST call soap_ssl_init() before any threads are started */ + if (!soap_ssl_init_done) + { soap_ssl_init_done = 1; + SSL_library_init(); +#ifndef WITH_LEAN + SSL_load_error_strings(); +#endif + if (!RAND_load_file("/dev/urandom", 1024)) + { char buf[1024]; + RAND_seed(buf, sizeof(buf)); + while (!RAND_status()) + { int r = rand(); + RAND_seed(&r, sizeof(int)); + } + } + } +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +const char * +SOAP_FMAC2 +soap_ssl_error(struct soap *soap, int ret) +{ int err = SSL_get_error(soap->ssl, ret); + const char *msg = soap_code_str(h_ssl_error_codes, err); + if (msg) + strcpy(soap->msgbuf, msg); + else + return ERR_error_string(err, soap->msgbuf); + if (ERR_peek_error()) + { unsigned long r; + strcat(soap->msgbuf, "\n"); + while ((r = ERR_get_error())) + ERR_error_string_n(r, soap->msgbuf + strlen(soap->msgbuf), sizeof(soap->msgbuf) - strlen(soap->msgbuf)); + } + else + { switch (ret) + { case 0: + strcpy(soap->msgbuf, "EOF was observed that violates the protocol. The client probably provided invalid authentication information."); + break; + case -1: + sprintf(soap->msgbuf, "Error observed by underlying BIO: %s", strerror(errno)); + break; + } + } + return soap->msgbuf; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +static int +ssl_password(char *buf, int num, int rwflag, void *userdata) +{ if (num < (int)strlen((char*)userdata) + 1) + return 0; + return (int)strlen(strcpy(buf, (char*)userdata)); +} +#endif + +/******************************************************************************/ +/* This callback is included for future references. It should not be deleted +#ifndef PALM_2 +static DH * +ssl_tmp_dh(SSL *ssl, int is_export, int keylength) +{ static DH *dh512 = NULL; + static DH *dh1024 = NULL; + DH *dh; + switch (keylength) + { case 512: + if (!dh512) + { BIO *bio = BIO_new_file("dh512.pem", "r"); + if (bio) + { dh512 = PEM_read_bio_DHparams(bio, NULL, NULL, NULL); + BIO_free(bio); + return dh512; + } + } + else + return dh512; + default: + if (!dh1024) + { BIO *bio = BIO_new_file("dh1024.pem", "r"); + if (bio) + { dh1024 = PEM_read_bio_DHparams(bio, NULL, NULL, NULL); + BIO_free(bio); + } + } + dh = dh1024; + } + return dh; +} +#endif +*/ + +/******************************************************************************/ +#ifndef PALM_1 +static int +ssl_auth_init(struct soap *soap) +{ long flags; + int mode; + if (!soap_ssl_init_done) + soap_ssl_init(); + ERR_clear_error(); + if (!soap->ctx) + { if (!(soap->ctx = SSL_CTX_new(SSLv23_method()))) + return soap_set_receiver_error(soap, "SSL error", "Can't setup context", SOAP_SSL_ERROR); + /* Alters the behavior of SSL read/write: + SSL_CTX_set_mode(soap->ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_AUTO_RETRY); + */ + } + if (soap->randfile) + { if (!RAND_load_file(soap->randfile, -1)) + return soap_set_receiver_error(soap, "SSL error", "Can't load randomness", SOAP_SSL_ERROR); + } + if (soap->cafile || soap->capath) + { if (!SSL_CTX_load_verify_locations(soap->ctx, soap->cafile, soap->capath)) + return soap_set_receiver_error(soap, "SSL error", "Can't read CA file and directory", SOAP_SSL_ERROR); + if (soap->cafile && (soap->ssl_flags & SOAP_SSL_REQUIRE_CLIENT_AUTHENTICATION)) + SSL_CTX_set_client_CA_list(soap->ctx, SSL_load_client_CA_file(soap->cafile)); + } + if (!(soap->ssl_flags & SOAP_SSL_NO_DEFAULT_CA_PATH)) + { if (!SSL_CTX_set_default_verify_paths(soap->ctx)) + return soap_set_receiver_error(soap, "SSL error", "Can't read default CA file and/or directory", SOAP_SSL_ERROR); + } +/* This code assumes a typical scenario, see alternative code below */ + if (soap->keyfile) + { if (!SSL_CTX_use_certificate_chain_file(soap->ctx, soap->keyfile)) + return soap_set_receiver_error(soap, "SSL error", "Can't read certificate key file", SOAP_SSL_ERROR); + if (soap->password) + { SSL_CTX_set_default_passwd_cb_userdata(soap->ctx, (void*)soap->password); + SSL_CTX_set_default_passwd_cb(soap->ctx, ssl_password); + } + if (!SSL_CTX_use_PrivateKey_file(soap->ctx, soap->keyfile, SSL_FILETYPE_PEM)) + return soap_set_receiver_error(soap, "SSL error", "Can't read key file", SOAP_SSL_ERROR); + } +/* Suggested alternative approach to check the key file for certs (cafile=NULL): + if (soap->password) + { SSL_CTX_set_default_passwd_cb_userdata(soap->ctx, (void*)soap->password); + SSL_CTX_set_default_passwd_cb(soap->ctx, ssl_password); + } + if (!soap->cafile || !SSL_CTX_use_certificate_chain_file(soap->ctx, soap->cafile)) + { if (soap->keyfile) + { if (!SSL_CTX_use_certificate_chain_file(soap->ctx, soap->keyfile)) + return soap_set_receiver_error(soap, "SSL error", "Can't read certificate or key file", SOAP_SSL_ERROR); + if (!SSL_CTX_use_PrivateKey_file(soap->ctx, soap->keyfile, SSL_FILETYPE_PEM)) + return soap_set_receiver_error(soap, "SSL error", "Can't read key file", SOAP_SSL_ERROR); + } + } +*/ + if ((soap->ssl_flags & SOAP_SSL_RSA)) + { RSA *rsa = RSA_generate_key(1024, RSA_F4, NULL, NULL); + if (!SSL_CTX_set_tmp_rsa(soap->ctx, rsa)) + { if (rsa) + RSA_free(rsa); + return soap_set_receiver_error(soap, "SSL error", "Can't set RSA key", SOAP_SSL_ERROR); + } + RSA_free(rsa); + } + else if (soap->dhfile) + { DH *dh = 0; + BIO *bio; + bio = BIO_new_file(soap->dhfile, "r"); + if (!bio) + return soap_set_receiver_error(soap, "SSL error", "Can't read DH file", SOAP_SSL_ERROR); + dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL); + BIO_free(bio); + if (SSL_CTX_set_tmp_dh(soap->ctx, dh) < 0) + { if (dh) + DH_free(dh); + return soap_set_receiver_error(soap, "SSL error", "Can't set DH parameters", SOAP_SSL_ERROR); + } + DH_free(dh); + } + flags = (SSL_OP_ALL | SSL_OP_NO_SSLv2); + if ((soap->ssl_flags & SOAP_SSLv3)) + flags |= SSL_OP_NO_TLSv1; + if ((soap->ssl_flags & SOAP_TLSv1)) + flags |= SSL_OP_NO_SSLv3; +#ifdef SSL_OP_NO_TICKET + /* TLS extension is enabled by default in OPENSSL v0.9.8k + Disable it by adding SSL_OP_NO_TICKET */ + flags |= SSL_OP_NO_TICKET; +#endif + SSL_CTX_set_options(soap->ctx, flags); + if ((soap->ssl_flags & SOAP_SSL_REQUIRE_CLIENT_AUTHENTICATION)) + mode = (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT); + else if ((soap->ssl_flags & SOAP_SSL_REQUIRE_SERVER_AUTHENTICATION)) + mode = SSL_VERIFY_PEER; + else + mode = SSL_VERIFY_NONE; + SSL_CTX_set_verify(soap->ctx, mode, soap->fsslverify); +#if (OPENSSL_VERSION_NUMBER < 0x00905100L) + SSL_CTX_set_verify_depth(soap->ctx, 1); +#else + SSL_CTX_set_verify_depth(soap->ctx, 9); +#endif + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +static int +ssl_verify_callback(int ok, X509_STORE_CTX *store) +{ +#ifdef SOAP_DEBUG + if (!ok) + { char data[256]; + X509 *cert = X509_STORE_CTX_get_current_cert(store); + fprintf(stderr, "SSL verify error or warning with certificate at depth %d: %s\n", X509_STORE_CTX_get_error_depth(store), X509_verify_cert_error_string(X509_STORE_CTX_get_error(store))); + X509_NAME_oneline(X509_get_issuer_name(cert), data, sizeof(data)); + fprintf(stderr, "certificate issuer %s\n", data); + X509_NAME_oneline(X509_get_subject_name(cert), data, sizeof(data)); + fprintf(stderr, "certificate subject %s\n", data); + } +#endif + /* Note: return 1 to continue, but unsafe progress will be terminated by SSL */ + return ok; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +static int +ssl_verify_callback_allow_expired_certificate(int ok, X509_STORE_CTX *store) +{ ok = ssl_verify_callback(ok, store); + if (ok == 0 && X509_STORE_CTX_get_error(store) == X509_V_ERR_CERT_HAS_EXPIRED) + { +#ifdef SOAP_DEBUG + fprintf(stderr, "ignoring certificate expiration\n"); +#endif + X509_STORE_CTX_set_error(store, X509_V_OK); + ok = 1; + } + /* Note: return 1 to continue, but unsafe progress will be terminated by SSL */ + return ok; +} +#endif + +/******************************************************************************/ +#ifndef WITH_NOIO +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_ssl_accept(struct soap *soap) +{ BIO *bio; + int retries, r, s; + if (!soap_valid_socket(soap->socket)) + return soap_set_receiver_error(soap, "SSL error", "No socket in soap_ssl_accept()", SOAP_SSL_ERROR); + if (!soap->ctx && (soap->error = soap->fsslauth(soap))) + return SOAP_SSL_ERROR; + if (!soap->ssl) + { soap->ssl = SSL_new(soap->ctx); + if (!soap->ssl) + return soap_set_receiver_error(soap, "SSL error", "SSL_new() failed in soap_ssl_accept()", SOAP_SSL_ERROR); + } + else + SSL_clear(soap->ssl); + soap->imode |= SOAP_ENC_SSL; + soap->omode |= SOAP_ENC_SSL; + /* Set SSL sockets to non-blocking */ + SOAP_SOCKNONBLOCK(soap->socket) + bio = BIO_new_socket((int)soap->socket, BIO_NOCLOSE); + SSL_set_bio(soap->ssl, bio, bio); + retries = 100; /* SSL_accept timeout: 10 sec retries, 100 times 0.1 sec */ + while ((r = SSL_accept(soap->ssl)) <= 0) + { int err = SSL_get_error(soap->ssl, r); + if (err == SSL_ERROR_WANT_ACCEPT || err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) + { if (err == SSL_ERROR_WANT_READ) + s = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, -100000); + else + s = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_SND | SOAP_TCP_SELECT_ERR, -100000); + if (s < 0 && soap->errnum != SOAP_EINTR) + break; + } + else + { soap->errnum = soap_socket_errno(soap->socket); + break; + } + if (retries-- <= 0) + break; + } + if (r <= 0) + { soap_set_receiver_error(soap, soap_ssl_error(soap, r), "SSL_accept() failed in soap_ssl_accept()", SOAP_SSL_ERROR); + soap_closesock(soap); + return SOAP_SSL_ERROR; + } + if ((soap->ssl_flags & SOAP_SSL_REQUIRE_CLIENT_AUTHENTICATION)) + { X509 *peer; + int err; + if ((err = SSL_get_verify_result(soap->ssl)) != X509_V_OK) + { soap_closesock(soap); + return soap_set_sender_error(soap, X509_verify_cert_error_string(err), "SSL certificate presented by peer cannot be verified in soap_ssl_accept()", SOAP_SSL_ERROR); + } + peer = SSL_get_peer_certificate(soap->ssl); + if (!peer) + { soap_closesock(soap); + return soap_set_sender_error(soap, "SSL error", "No SSL certificate was presented by the peer in soap_ssl_accept()", SOAP_SSL_ERROR); + } + X509_free(peer); + } + return SOAP_OK; +} +#endif +#endif + +/******************************************************************************/ +#endif /* WITH_OPENSSL */ + +/******************************************************************************/ +#ifndef WITH_NOIO +#ifndef PALM_1 +static int +tcp_init(struct soap *soap) +{ soap->errmode = 1; +#ifdef WIN32 + if (tcp_done) + return 0; + else + { WSADATA w; + if (WSAStartup(MAKEWORD(1, 1), &w)) + return -1; + tcp_done = 1; + } +#endif + return 0; +} +#endif +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_done(struct soap *soap) +{ +#ifdef SOAP_DEBUG + int i; +#endif + if (soap_check_state(soap)) + return; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Done with context\n")); + soap_free_temp(soap); + while (soap->clist) + { struct soap_clist *p = soap->clist->next; + SOAP_FREE(soap, soap->clist); + soap->clist = p; + } + if (soap->state == SOAP_INIT) + soap->omode &= ~SOAP_IO_UDP; /* to force close the socket */ + soap->keep_alive = 0; /* to force close the socket */ + soap_closesock(soap); +#ifdef WITH_COOKIES + soap_free_cookies(soap); +#endif + while (soap->plugins) + { register struct soap_plugin *p = soap->plugins->next; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Removing plugin '%s'\n", soap->plugins->id)); + if (soap->plugins->fcopy || soap->state == SOAP_INIT) + soap->plugins->fdelete(soap, soap->plugins); + SOAP_FREE(soap, soap->plugins); + soap->plugins = p; + } + soap->fplugin = fplugin; + soap->fmalloc = NULL; +#ifndef WITH_NOHTTP + soap->fpost = http_post; + soap->fget = http_get; + soap->fput = http_405; + soap->fdel = http_405; + soap->fhead = http_405; + soap->fform = NULL; + soap->fposthdr = http_post_header; + soap->fresponse = http_response; + soap->fparse = http_parse; + soap->fparsehdr = http_parse_header; +#endif + soap->fheader = NULL; +#ifndef WITH_NOIO +#ifndef WITH_IPV6 + soap->fresolve = tcp_gethost; +#else + soap->fresolve = NULL; +#endif + soap->faccept = tcp_accept; + soap->fopen = tcp_connect; + soap->fclose = tcp_disconnect; + soap->fclosesocket = tcp_closesocket; + soap->fshutdownsocket = tcp_shutdownsocket; + soap->fsend = fsend; + soap->frecv = frecv; + soap->fpoll = soap_poll; +#else + soap->fopen = NULL; + soap->fclose = NULL; + soap->fpoll = NULL; +#endif +#ifndef WITH_LEANER + soap->fprepareinit = NULL; + soap->fpreparesend = NULL; + soap->fpreparerecv = NULL; + soap->fpreparefinal = NULL; +#endif + soap->fseterror = NULL; + soap->fignore = NULL; + soap->fserveloop = NULL; +#ifdef WITH_OPENSSL + if (soap->session) + { SSL_SESSION_free(soap->session); + soap->session = NULL; + } +#endif + if (soap->state == SOAP_INIT) + { if (soap_valid_socket(soap->master)) + { soap->fclosesocket(soap, soap->master); + soap->master = SOAP_INVALID_SOCKET; + } + } +#ifdef WITH_OPENSSL + if (soap->ssl) + { SSL_free(soap->ssl); + soap->ssl = NULL; + } + if (soap->state == SOAP_INIT) + { if (soap->ctx) + { SSL_CTX_free(soap->ctx); + soap->ctx = NULL; + } + } +#endif +#ifdef WITH_OPENSSL + ERR_remove_state(0); +#endif +#ifdef WITH_C_LOCALE + freelocale(soap->c_locale); +#endif +#ifdef WITH_ZLIB + if (soap->d_stream) + { SOAP_FREE(soap, (void*)soap->d_stream); + soap->d_stream = NULL; + } + if (soap->z_buf) + { SOAP_FREE(soap, (void*)soap->z_buf); + soap->z_buf = NULL; + } +#endif +#ifdef SOAP_DEBUG + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Free logfiles\n")); + for (i = 0; i < SOAP_MAXLOGS; i++) + { if (soap->logfile[i]) + { SOAP_FREE(soap, (void*)soap->logfile[i]); + soap->logfile[i] = NULL; + } + soap_close_logfile(soap, i); + } + soap->state = SOAP_NONE; +#endif +#ifdef SOAP_MEM_DEBUG + soap_free_mht(soap); +#endif +} +#endif + +/******************************************************************************/ +#ifndef WITH_NOIO +#ifndef PALM_2 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_cleanup(struct soap *soap) +{ soap_done(soap); +#ifdef WIN32 + if (!tcp_done) + return; + tcp_done = 0; + WSACleanup(); +#endif +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIO +#ifndef PALM_1 +static const char* +tcp_error(struct soap *soap) +{ register const char *msg = NULL; + switch (soap->errmode) + { case 0: + msg = soap_strerror(soap); + break; + case 1: + msg = "WSAStartup failed"; + break; + case 2: + { +#ifndef WITH_LEAN + msg = soap_code_str(h_error_codes, soap->errnum); + if (!msg) +#endif + { sprintf(soap->msgbuf, "TCP/UDP IP error %d", soap->errnum); + msg = soap->msgbuf; + } + } + } + return msg; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOHTTP +#ifndef PALM_1 +static const char* +http_error(struct soap *soap, int status) +{ register const char *msg = SOAP_STR_EOS; +#ifndef WITH_LEAN + msg = soap_code_str(h_http_error_codes, status); + if (!msg) + msg = SOAP_STR_EOS; +#endif + return msg; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_IPV6 +#ifndef WITH_NOIO +#ifndef PALM_1 +static int +tcp_gethost(struct soap *soap, const char *addr, struct in_addr *inaddr) +{ soap_int32 iadd = -1; + struct hostent hostent, *host = &hostent; +#ifdef VXWORKS + int hostint; + /* inet_addr(), and hostGetByName() expect "char *"; addr is a "const char *". */ + iadd = inet_addr((char*)addr); +#else +#if defined(_AIX43) || ((defined(TRU64) || defined(HP_UX)) && defined(HAVE_GETHOSTBYNAME_R)) + struct hostent_data ht_data; +#endif +#ifdef AS400 + iadd = inet_addr((void*)addr); +#else + iadd = inet_addr(addr); +#endif +#endif + if (iadd != -1) + { memcpy(inaddr, &iadd, sizeof(iadd)); + return SOAP_OK; + } +#if defined(__GLIBC__) || (defined(HAVE_GETHOSTBYNAME_R) && (defined(FREEBSD) || defined(__FreeBSD__))) + if (gethostbyname_r(addr, &hostent, soap->buf, SOAP_BUFLEN, &host, &soap->errnum) < 0) + host = NULL; +#elif defined(_AIX43) || ((defined(TRU64) || defined(HP_UX)) && defined(HAVE_GETHOSTBYNAME_R)) + memset((void*)&ht_data, 0, sizeof(ht_data)); + if (gethostbyname_r(addr, &hostent, &ht_data) < 0) + { host = NULL; + soap->errnum = h_errno; + } +#elif defined(HAVE_GETHOSTBYNAME_R) + host = gethostbyname_r(addr, &hostent, soap->buf, SOAP_BUFLEN, &soap->errnum); +#elif defined(VXWORKS) + /* If the DNS resolver library resolvLib has been configured in the vxWorks + * image, a query for the host IP address is sent to the DNS server, if the + * name was not found in the local host table. */ + hostint = hostGetByName((char*)addr); + if (hostint == ERROR) + { host = NULL; + soap->errnum = soap_errno; + } +#else +#ifdef AS400 + if (!(host = gethostbyname((void*)addr))) + soap->errnum = h_errno; +#else + if (!(host = gethostbyname(addr))) + soap->errnum = h_errno; +#endif +#endif + if (!host) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Host name not found\n")); + return SOAP_ERR; + } +#ifdef VXWORKS + inaddr->s_addr = hostint; +#else + memcpy(inaddr, host->h_addr, host->h_length); +#endif + return SOAP_OK; +} +#endif +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIO +#ifndef PALM_1 +static SOAP_SOCKET +tcp_connect(struct soap *soap, const char *endpoint, const char *host, int port) +{ +#ifdef WITH_IPV6 + struct addrinfo hints, *res, *ressave; +#endif + SOAP_SOCKET fd; + int err = 0; +#ifndef WITH_LEAN + int len = SOAP_BUFLEN; + int set = 1; + int retries; +#endif + if (soap_valid_socket(soap->socket)) + soap->fclosesocket(soap, soap->socket); + soap->socket = SOAP_INVALID_SOCKET; + if (tcp_init(soap)) + { soap->errnum = 0; + soap_set_sender_error(soap, tcp_error(soap), "TCP init failed in tcp_connect()", SOAP_TCP_ERROR); + return SOAP_INVALID_SOCKET; + } + soap->errmode = 0; +#ifdef WITH_IPV6 + memset((void*)&hints, 0, sizeof(hints)); + hints.ai_family = PF_UNSPEC; +#ifndef WITH_LEAN + if ((soap->omode & SOAP_IO_UDP)) + hints.ai_socktype = SOCK_DGRAM; + else +#endif + hints.ai_socktype = SOCK_STREAM; + soap->errmode = 2; + if (soap->proxy_host) + err = getaddrinfo(soap->proxy_host, soap_int2s(soap, soap->proxy_port), &hints, &res); + else + err = getaddrinfo(host, soap_int2s(soap, port), &hints, &res); + if (err) + { soap_set_sender_error(soap, SOAP_GAI_STRERROR(err), "getaddrinfo failed in tcp_connect()", SOAP_TCP_ERROR); + return SOAP_INVALID_SOCKET; + } + ressave = res; +again: + fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); + soap->errmode = 0; +#else +#ifndef WITH_LEAN +again: +#endif +#ifndef WITH_LEAN + if ((soap->omode & SOAP_IO_UDP)) + fd = socket(AF_INET, SOCK_DGRAM, 0); + else +#endif + fd = socket(AF_INET, SOCK_STREAM, 0); +#endif + if (!soap_valid_socket(fd)) + { +#ifdef WITH_IPV6 + if (res->ai_next) + { res = res->ai_next; + goto again; + } +#endif + soap->errnum = soap_socket_errno(fd); + soap_set_sender_error(soap, tcp_error(soap), "socket failed in tcp_connect()", SOAP_TCP_ERROR); +#ifdef WITH_IPV6 + freeaddrinfo(ressave); +#endif + return SOAP_INVALID_SOCKET; + } +#ifdef SOCKET_CLOSE_ON_EXEC +#ifdef WIN32 +#ifndef UNDER_CE + SetHandleInformation((HANDLE)fd, HANDLE_FLAG_INHERIT, 0); +#endif +#else + fcntl(fd, F_SETFD, 1); +#endif +#endif +#ifndef WITH_LEAN + if (soap->connect_flags == SO_LINGER) + { struct linger linger; + memset((void*)&linger, 0, sizeof(linger)); + linger.l_onoff = 1; + linger.l_linger = soap->linger_time; + if (setsockopt(fd, SOL_SOCKET, SO_LINGER, (char*)&linger, sizeof(struct linger))) + { soap->errnum = soap_socket_errno(fd); + soap_set_sender_error(soap, tcp_error(soap), "setsockopt SO_LINGER failed in tcp_connect()", SOAP_TCP_ERROR); + soap->fclosesocket(soap, fd); +#ifdef WITH_IPV6 + freeaddrinfo(ressave); +#endif + return SOAP_INVALID_SOCKET; + } + } + else if (soap->connect_flags && setsockopt(fd, SOL_SOCKET, soap->connect_flags, (char*)&set, sizeof(int))) + { soap->errnum = soap_socket_errno(fd); + soap_set_sender_error(soap, tcp_error(soap), "setsockopt failed in tcp_connect()", SOAP_TCP_ERROR); + soap->fclosesocket(soap, fd); +#ifdef WITH_IPV6 + freeaddrinfo(ressave); +#endif + return SOAP_INVALID_SOCKET; + } + if ((soap->keep_alive || soap->tcp_keep_alive) && setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (char*)&set, sizeof(int))) + { soap->errnum = soap_socket_errno(fd); + soap_set_sender_error(soap, tcp_error(soap), "setsockopt SO_KEEPALIVE failed in tcp_connect()", SOAP_TCP_ERROR); + soap->fclosesocket(soap, fd); +#ifdef WITH_IPV6 + freeaddrinfo(ressave); +#endif + return SOAP_INVALID_SOCKET; + } + if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char*)&len, sizeof(int))) + { soap->errnum = soap_socket_errno(fd); + soap_set_sender_error(soap, tcp_error(soap), "setsockopt SO_SNDBUF failed in tcp_connect()", SOAP_TCP_ERROR); + soap->fclosesocket(soap, fd); +#ifdef WITH_IPV6 + freeaddrinfo(ressave); +#endif + return SOAP_INVALID_SOCKET; + } + if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char*)&len, sizeof(int))) + { soap->errnum = soap_socket_errno(fd); + soap_set_sender_error(soap, tcp_error(soap), "setsockopt SO_RCVBUF failed in tcp_connect()", SOAP_TCP_ERROR); + soap->fclosesocket(soap, fd); +#ifdef WITH_IPV6 + freeaddrinfo(ressave); +#endif + return SOAP_INVALID_SOCKET; + } +#ifdef TCP_KEEPIDLE + if (soap->tcp_keep_idle && setsockopt((SOAP_SOCKET)fd, IPPROTO_TCP, TCP_KEEPIDLE, (char*)&(soap->tcp_keep_idle), sizeof(int))) + { soap->errnum = soap_socket_errno(fd); + soap_set_sender_error(soap, tcp_error(soap), "setsockopt TCP_KEEPIDLE failed in tcp_connect()", SOAP_TCP_ERROR); + soap->fclosesocket(soap, (SOAP_SOCKET)fd); +#ifdef WITH_IPV6 + freeaddrinfo(ressave); +#endif + return SOAP_INVALID_SOCKET; + } +#endif +#ifdef TCP_KEEPINTVL + if (soap->tcp_keep_intvl && setsockopt((SOAP_SOCKET)fd, IPPROTO_TCP, TCP_KEEPINTVL, (char*)&(soap->tcp_keep_intvl), sizeof(int))) + { soap->errnum = soap_socket_errno(fd); + soap_set_sender_error(soap, tcp_error(soap), "setsockopt TCP_KEEPINTVL failed in tcp_connect()", SOAP_TCP_ERROR); + soap->fclosesocket(soap, (SOAP_SOCKET)fd); +#ifdef WITH_IPV6 + freeaddrinfo(ressave); +#endif + return SOAP_INVALID_SOCKET; + } +#endif +#ifdef TCP_KEEPCNT + if (soap->tcp_keep_cnt && setsockopt((SOAP_SOCKET)fd, IPPROTO_TCP, TCP_KEEPCNT, (char*)&(soap->tcp_keep_cnt), sizeof(int))) + { soap->errnum = soap_socket_errno(fd); + soap_set_sender_error(soap, tcp_error(soap), "setsockopt TCP_KEEPCNT failed in tcp_connect()", SOAP_TCP_ERROR); + soap->fclosesocket(soap, (SOAP_SOCKET)fd); +#ifdef WITH_IPV6 + freeaddrinfo(ressave); +#endif + return SOAP_INVALID_SOCKET; + } +#endif +#ifdef TCP_NODELAY + if (!(soap->omode & SOAP_IO_UDP) && setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char*)&set, sizeof(int))) + { soap->errnum = soap_socket_errno(fd); + soap_set_sender_error(soap, tcp_error(soap), "setsockopt TCP_NODELAY failed in tcp_connect()", SOAP_TCP_ERROR); + soap->fclosesocket(soap, fd); +#ifdef WITH_IPV6 + freeaddrinfo(ressave); +#endif + return SOAP_INVALID_SOCKET; + } +#endif +#ifdef WITH_IPV6 + if ((soap->omode & SOAP_IO_UDP) && soap->ipv6_multicast_if) + { struct sockaddr_in6 *in6addr = (struct sockaddr_in6*)res->ai_addr; + in6addr->sin6_scope_id = soap->ipv6_multicast_if; + } +#endif +#ifdef IP_MULTICAST_TTL + if ((soap->omode & SOAP_IO_UDP) && soap->ipv4_multicast_if && !soap->ipv6_multicast_if) + { if (soap->ipv4_multicast_ttl > 0) + { char ttl = (char)(soap->ipv4_multicast_ttl); + if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, (char*)&ttl, sizeof(ttl))) + { soap->errnum = soap_socket_errno(fd); + soap_set_sender_error(soap, tcp_error(soap), "setsockopt IP_MULTICAST_TTL failed in tcp_connect()", SOAP_TCP_ERROR); + soap->fclosesocket(soap, fd); + return SOAP_INVALID_SOCKET; + } + } +#ifndef WINDOWS + if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, (char*)soap->ipv4_multicast_if, sizeof(struct in_addr))) + { soap->errnum = soap_socket_errno(fd); + soap_set_sender_error(soap, tcp_error(soap), "setsockopt IP_MULTICAST_IF failed in tcp_connect()", SOAP_TCP_ERROR); + soap->fclosesocket(soap, fd); + return SOAP_INVALID_SOCKET; + } +#else +#ifndef IP_MULTICAST_IF +#define IP_MULTICAST_IF 2 +#endif + if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, (char*)soap->ipv4_multicast_if, sizeof(struct in_addr))) + { soap->errnum = soap_socket_errno(fd); + soap_set_sender_error(soap, tcp_error(soap), "setsockopt IP_MULTICAST_IF failed in tcp_connect()", SOAP_TCP_ERROR); + soap->fclosesocket(soap, fd); + return SOAP_INVALID_SOCKET; + } +#endif + } +#endif +#endif + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Opening socket %d to host='%s' port=%d\n", fd, host, port)); +#ifndef WITH_IPV6 + soap->peerlen = sizeof(soap->peer); + memset((void*)&soap->peer, 0, sizeof(soap->peer)); + soap->peer.sin_family = AF_INET; + soap->errmode = 2; + if (soap->proxy_host) + { if (soap->fresolve(soap, soap->proxy_host, &soap->peer.sin_addr)) + { soap_set_sender_error(soap, tcp_error(soap), "get proxy host by name failed in tcp_connect()", SOAP_TCP_ERROR); + soap->fclosesocket(soap, fd); + return SOAP_INVALID_SOCKET; + } + soap->peer.sin_port = htons((short)soap->proxy_port); + } + else + { if (soap->fresolve(soap, host, &soap->peer.sin_addr)) + { soap_set_sender_error(soap, tcp_error(soap), "get host by name failed in tcp_connect()", SOAP_TCP_ERROR); + soap->fclosesocket(soap, fd); + return SOAP_INVALID_SOCKET; + } + soap->peer.sin_port = htons((short)port); + } + soap->errmode = 0; +#ifndef WITH_LEAN + if ((soap->omode & SOAP_IO_UDP)) + return fd; +#endif +#else + if ((soap->omode & SOAP_IO_UDP)) + { memcpy(&soap->peer, res->ai_addr, res->ai_addrlen); + soap->peerlen = res->ai_addrlen; + freeaddrinfo(ressave); + return fd; + } +#endif +#ifndef WITH_LEAN + if (soap->connect_timeout) + SOAP_SOCKNONBLOCK(fd) + else + SOAP_SOCKBLOCK(fd) + retries = 10; +#endif + for (;;) + { +#ifdef WITH_IPV6 + if (connect(fd, res->ai_addr, (int)res->ai_addrlen)) +#else + if (connect(fd, (struct sockaddr*)&soap->peer, sizeof(soap->peer))) +#endif + { err = soap_socket_errno(fd); +#ifndef WITH_LEAN + if (err == SOAP_EADDRINUSE) + { soap->fclosesocket(soap, fd); + if (retries-- > 0) + goto again; + } + else if (soap->connect_timeout && (err == SOAP_EINPROGRESS || err == SOAP_EAGAIN || err == SOAP_EWOULDBLOCK)) + { + SOAP_SOCKLEN_T k; + for (;;) + { register int r; + r = tcp_select(soap, fd, SOAP_TCP_SELECT_SND, soap->connect_timeout); + if (r > 0) + break; + if (!r) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Connect timeout\n")); + soap_set_sender_error(soap, "Timeout", "connect failed in tcp_connect()", SOAP_TCP_ERROR); + soap->fclosesocket(soap, fd); +#ifdef WITH_IPV6 + freeaddrinfo(ressave); +#endif + return SOAP_INVALID_SOCKET; + } + r = soap->errnum; + if (r != SOAP_EINTR) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not connect to host\n")); + soap_set_sender_error(soap, tcp_error(soap), "connect failed in tcp_connect()", SOAP_TCP_ERROR); + soap->fclosesocket(soap, fd); +#ifdef WITH_IPV6 + freeaddrinfo(ressave); +#endif + return SOAP_INVALID_SOCKET; + } + } + k = (SOAP_SOCKLEN_T)sizeof(soap->errnum); + if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, (char*)&soap->errnum, &k) && !soap->errnum) /* portability note: see SOAP_SOCKLEN_T definition in stdsoap2.h */ + break; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not connect to host\n")); + if (!soap->errnum) + soap->errnum = soap_socket_errno(fd); + soap_set_sender_error(soap, tcp_error(soap), "connect failed in tcp_connect()", SOAP_TCP_ERROR); + soap->fclosesocket(soap, fd); +#ifdef WITH_IPV6 + freeaddrinfo(ressave); +#endif + return SOAP_INVALID_SOCKET; + } +#endif +#ifdef WITH_IPV6 + if (res->ai_next) + { res = res->ai_next; + soap->fclosesocket(soap, fd); + goto again; + } +#endif + if (err && err != SOAP_EINTR) + { soap->errnum = err; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not connect to host\n")); + soap_set_sender_error(soap, tcp_error(soap), "connect failed in tcp_connect()", SOAP_TCP_ERROR); + soap->fclosesocket(soap, fd); +#ifdef WITH_IPV6 + freeaddrinfo(ressave); +#endif + return SOAP_INVALID_SOCKET; + } + } + else + break; + } +#ifdef WITH_IPV6 + soap->peerlen = 0; /* IPv6: already connected so use send() */ + freeaddrinfo(ressave); +#endif +#ifndef WITH_LEAN + if (soap->recv_timeout || soap->send_timeout) + SOAP_SOCKNONBLOCK(fd) + else + SOAP_SOCKBLOCK(fd) +#endif + soap->socket = fd; + soap->imode &= ~SOAP_ENC_SSL; + soap->omode &= ~SOAP_ENC_SSL; + if (!soap_tag_cmp(endpoint, "https:*")) + { +#ifdef WITH_OPENSSL + BIO *bio; + int r; + if (soap->proxy_host) + { soap_mode m = soap->mode; /* preserve settings */ + soap_mode om = soap->omode; /* make sure we only parse HTTP */ + size_t n = soap->count; /* save the content length */ + const char *userid, *passwd; + soap->omode &= ~SOAP_ENC; /* mask IO and ENC */ + soap->omode |= SOAP_IO_BUFFER; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Connecting to %s proxy server\n", soap->proxy_http_version)); + sprintf(soap->tmpbuf, "CONNECT %s:%d HTTP/%s", host, port, soap->proxy_http_version); + if (soap_begin_send(soap) + || (soap->error = soap->fposthdr(soap, soap->tmpbuf, NULL))) + { soap->fclosesocket(soap, fd); + return SOAP_INVALID_SOCKET; + } +#ifndef WITH_LEAN + if (soap->proxy_userid && soap->proxy_passwd && strlen(soap->proxy_userid) + strlen(soap->proxy_passwd) < 761) + { sprintf(soap->tmpbuf + 262, "%s:%s", soap->proxy_userid, soap->proxy_passwd); + strcpy(soap->tmpbuf, "Basic "); + soap_s2base64(soap, (const unsigned char*)(soap->tmpbuf + 262), soap->tmpbuf + 6, (int)strlen(soap->tmpbuf + 262)); + if ((soap->error = soap->fposthdr(soap, "Proxy-Authorization", soap->tmpbuf))) + { soap->fclosesocket(soap, fd); + return soap->error; + } + } +#endif + if ((soap->error = soap->fposthdr(soap, NULL, NULL)) + || soap_flush(soap)) + { soap->fclosesocket(soap, fd); + return SOAP_INVALID_SOCKET; + } + soap->omode = om; + om = soap->imode; + soap->imode &= ~SOAP_ENC; /* mask IO and ENC */ + userid = soap->userid; /* preserve */ + passwd = soap->passwd; /* preserve */ + if ((soap->error = soap->fparse(soap))) + { soap->fclosesocket(soap, fd); + return SOAP_INVALID_SOCKET; + } + soap->userid = userid; /* restore */ + soap->passwd = passwd; /* restore */ + soap->imode = om; /* restore */ + soap->count = n; /* restore */ + if (soap_begin_send(soap)) + { soap->fclosesocket(soap, fd); + return SOAP_INVALID_SOCKET; + } + if (endpoint) + strncpy(soap->endpoint, endpoint, sizeof(soap->endpoint)-1); /* restore */ + soap->mode = m; + } + if (!soap->ctx && (soap->error = soap->fsslauth(soap))) + { soap_set_sender_error(soap, "SSL error", "SSL authentication failed in tcp_connect(): check password, key file, and ca file.", SOAP_SSL_ERROR); + soap->fclosesocket(soap, fd); + return SOAP_INVALID_SOCKET; + } + if (!soap->ssl) + { soap->ssl = SSL_new(soap->ctx); + if (!soap->ssl) + { soap->fclosesocket(soap, fd); + soap->error = SOAP_SSL_ERROR; + return SOAP_INVALID_SOCKET; + } + } + else + SSL_clear(soap->ssl); + if (soap->session) + { if (!strcmp(soap->session_host, host) && soap->session_port == port) + SSL_set_session(soap->ssl, soap->session); + SSL_SESSION_free(soap->session); + soap->session = NULL; + } + soap->imode |= SOAP_ENC_SSL; + soap->omode |= SOAP_ENC_SSL; + bio = BIO_new_socket((int)fd, BIO_NOCLOSE); + SSL_set_bio(soap->ssl, bio, bio); +#ifndef WITH_LEAN + /* Connect timeout: set SSL sockets to non-blocking */ + if (soap->connect_timeout) + SOAP_SOCKNONBLOCK(fd) + else + SOAP_SOCKBLOCK(fd) + retries = 100; /* SSL connect timeout: 10 sec retries, 100 times 0.1 sec */ +#endif + /* Try connecting until success or timeout (when nonblocking) */ + do + { if ((r = SSL_connect(soap->ssl)) <= 0) + { int err = SSL_get_error(soap->ssl, r); + if (err == SSL_ERROR_WANT_CONNECT || err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) + { register int s; + if (err == SSL_ERROR_WANT_READ) + s = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, -100000); + else + s = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_SND | SOAP_TCP_SELECT_ERR, -100000); + if (s < 0 && soap->errnum != SOAP_EINTR) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "SSL_connect/select error in tcp_connect\n")); + soap_set_sender_error(soap, soap_ssl_error(soap, r), "SSL_connect failed in tcp_connect()", SOAP_TCP_ERROR); + soap->fclosesocket(soap, fd); + return SOAP_INVALID_SOCKET; + } + if (s == 0 && retries-- <= 0) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "SSL connect timeout\n")); + soap_set_sender_error(soap, "Timeout", "SSL connect failed in tcp_connect()", SOAP_TCP_ERROR); + soap->fclosesocket(soap, fd); + return SOAP_INVALID_SOCKET; + } + } + else + { soap_set_sender_error(soap, soap_ssl_error(soap, r), "SSL_connect error in tcp_connect()", SOAP_SSL_ERROR); + soap->fclosesocket(soap, fd); + return SOAP_INVALID_SOCKET; + } + } + } while (!SSL_is_init_finished(soap->ssl)); +#ifndef WITH_LEAN + /* Set SSL sockets to nonblocking */ + SOAP_SOCKNONBLOCK(fd) +#endif + /* Check server credentials when required */ + if ((soap->ssl_flags & SOAP_SSL_REQUIRE_SERVER_AUTHENTICATION)) + { int err; + if ((err = SSL_get_verify_result(soap->ssl)) != X509_V_OK) + { soap_set_sender_error(soap, X509_verify_cert_error_string(err), "SSL certificate presented by peer cannot be verified in tcp_connect()", SOAP_SSL_ERROR); + soap->fclosesocket(soap, fd); + return SOAP_INVALID_SOCKET; + } + if (!(soap->ssl_flags & SOAP_SSL_SKIP_HOST_CHECK)) + { X509_NAME *subj; + int ext_count; + int ok = 0; + X509 *peer; + peer = SSL_get_peer_certificate(soap->ssl); + if (!peer) + { soap_set_sender_error(soap, "SSL error", "No SSL certificate was presented by the peer in tcp_connect()", SOAP_SSL_ERROR); + soap->fclosesocket(soap, fd); + return SOAP_INVALID_SOCKET; + } + ext_count = X509_get_ext_count(peer); + if (ext_count > 0) + { int i; + for (i = 0; i < ext_count; i++) + { X509_EXTENSION *ext = X509_get_ext(peer, i); + const char *ext_str = OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(ext))); + if (ext_str && !strcmp(ext_str, "subjectAltName")) + { X509V3_EXT_METHOD *meth = X509V3_EXT_get(ext); + void *ext_data; +#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) + const unsigned char *data; +#else + unsigned char *data; +#endif + STACK_OF(CONF_VALUE) *val; + int j; + if (!meth) + break; + data = ext->value->data; +#if (OPENSSL_VERSION_NUMBER > 0x00907000L) + if (meth->it) + ext_data = ASN1_item_d2i(NULL, &data, ext->value->length, ASN1_ITEM_ptr(meth->it)); + else + { /* OpenSSL not perfectly portable at this point (?): + Some compilers appear to prefer + meth->d2i(NULL, (const unsigned char**)&data, ... + and others prefer + meth->d2i(NULL, &data, ext->value->length); + */ + ext_data = meth->d2i(NULL, &data, ext->value->length); + } +#else + ext_data = meth->d2i(NULL, &data, ext->value->length); +#endif + if (ext_data) + { val = meth->i2v(meth, ext_data, NULL); + if (val) + { for (j = 0; j < sk_CONF_VALUE_num(val); j++) + { CONF_VALUE *nval = sk_CONF_VALUE_value(val, j); + if (nval && !strcmp(nval->name, "DNS") && !strcmp(nval->value, host)) + { ok = 1; + break; + } + } + sk_CONF_VALUE_pop_free(val, X509V3_conf_free); + } +#if (OPENSSL_VERSION_NUMBER > 0x00907000L) + if (meth->it) + ASN1_item_free((ASN1_VALUE*)ext_data, ASN1_ITEM_ptr(meth->it)); + else + meth->ext_free(ext_data); +#else + meth->ext_free(ext_data); +#endif + } + } + if (ok) + break; + } + } + if (!ok && (subj = X509_get_subject_name(peer))) + { int i = -1; + do + { ASN1_STRING *name; + i = X509_NAME_get_index_by_NID(subj, NID_commonName, i); + if (i == -1) + break; + name = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subj, i)); + if (name) + { if (!soap_tag_cmp(host, (const char*)name)) + ok = 1; + else + { unsigned char *tmp = NULL; + ASN1_STRING_to_UTF8(&tmp, name); + if (tmp) + { if (!soap_tag_cmp(host, (const char*)tmp)) + ok = 1; + OPENSSL_free(tmp); + } + } + } + } while (!ok); + } + X509_free(peer); + if (!ok) + { soap_set_sender_error(soap, "SSL error", "SSL certificate host name mismatch in tcp_connect()", SOAP_SSL_ERROR); + soap->fclosesocket(soap, fd); + return SOAP_INVALID_SOCKET; + } + } + } +#else + soap->fclosesocket(soap, fd); + soap->error = SOAP_SSL_ERROR; + return SOAP_INVALID_SOCKET; +#endif + } + return fd; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIO +#ifndef PALM_1 +SOAP_FMAC1 +SOAP_SOCKET +SOAP_FMAC2 +soap_bind(struct soap *soap, const char *host, int port, int backlog) +{ +#ifdef WITH_IPV6 + struct addrinfo *addrinfo = NULL; + struct addrinfo hints; + struct addrinfo res; + int err; +#ifdef IPV6_V6ONLY + int unset = 0; +#ifdef SOL_IP + int level = SOL_IP; +#else + int level = IPPROTO_IPV6; +#endif +#endif +#endif +#ifndef WITH_LEAN + int len = SOAP_BUFLEN; + int set = 1; +#endif + if (soap_valid_socket(soap->master)) + { soap->fclosesocket(soap, soap->master); + soap->master = SOAP_INVALID_SOCKET; + } + soap->socket = SOAP_INVALID_SOCKET; + soap->errmode = 1; + if (tcp_init(soap)) + { soap_set_receiver_error(soap, tcp_error(soap), "TCP init failed in soap_bind()", SOAP_TCP_ERROR); + return SOAP_INVALID_SOCKET; + } +#ifdef WITH_IPV6 + memset((void*)&hints, 0, sizeof(hints)); + hints.ai_family = PF_UNSPEC; +#ifndef WITH_LEAN + if ((soap->omode & SOAP_IO_UDP)) + hints.ai_socktype = SOCK_DGRAM; + else +#endif + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags = AI_PASSIVE; + soap->errmode = 2; + err = getaddrinfo(host, soap_int2s(soap, port), &hints, &addrinfo); + if (addrinfo) + { res = *addrinfo; + memcpy(&soap->peer, addrinfo->ai_addr, addrinfo->ai_addrlen); + soap->peerlen = addrinfo->ai_addrlen; + res.ai_addr = (struct sockaddr*)&soap->peer; + res.ai_addrlen = soap->peerlen; + freeaddrinfo(addrinfo); + } + if (err || !addrinfo) + { soap_set_receiver_error(soap, SOAP_GAI_STRERROR(err), "getaddrinfo failed in soap_bind()", SOAP_TCP_ERROR); + return SOAP_INVALID_SOCKET; + } + soap->master = (int)socket(res.ai_family, res.ai_socktype, res.ai_protocol); +#else +#ifndef WITH_LEAN + if ((soap->omode & SOAP_IO_UDP)) + soap->master = (int)socket(AF_INET, SOCK_DGRAM, 0); + else +#endif + soap->master = (int)socket(AF_INET, SOCK_STREAM, 0); +#endif + soap->errmode = 0; + if (!soap_valid_socket(soap->master)) + { soap->errnum = soap_socket_errno(soap->master); + soap_set_receiver_error(soap, tcp_error(soap), "socket failed in soap_bind()", SOAP_TCP_ERROR); + return SOAP_INVALID_SOCKET; + } +#ifndef WITH_LEAN + if ((soap->omode & SOAP_IO_UDP)) + soap->socket = soap->master; +#endif +#ifdef SOCKET_CLOSE_ON_EXEC +#ifdef WIN32 +#ifndef UNDER_CE + SetHandleInformation((HANDLE)soap->master, HANDLE_FLAG_INHERIT, 0); +#endif +#else + fcntl(soap->master, F_SETFD, 1); +#endif +#endif +#ifndef WITH_LEAN + if (soap->bind_flags && setsockopt(soap->master, SOL_SOCKET, soap->bind_flags, (char*)&set, sizeof(int))) + { soap->errnum = soap_socket_errno(soap->master); + soap_set_receiver_error(soap, tcp_error(soap), "setsockopt failed in soap_bind()", SOAP_TCP_ERROR); + return SOAP_INVALID_SOCKET; + } + if (((soap->imode | soap->omode) & SOAP_IO_KEEPALIVE) && setsockopt(soap->master, SOL_SOCKET, SO_KEEPALIVE, (char*)&set, sizeof(int))) + { soap->errnum = soap_socket_errno(soap->master); + soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_KEEPALIVE failed in soap_bind()", SOAP_TCP_ERROR); + return SOAP_INVALID_SOCKET; + } + if (setsockopt(soap->master, SOL_SOCKET, SO_SNDBUF, (char*)&len, sizeof(int))) + { soap->errnum = soap_socket_errno(soap->master); + soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_SNDBUF failed in soap_bind()", SOAP_TCP_ERROR); + return SOAP_INVALID_SOCKET; + } + if (setsockopt(soap->master, SOL_SOCKET, SO_RCVBUF, (char*)&len, sizeof(int))) + { soap->errnum = soap_socket_errno(soap->master); + soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_RCVBUF failed in soap_bind()", SOAP_TCP_ERROR); + return SOAP_INVALID_SOCKET; + } +#ifdef TCP_NODELAY + if (!(soap->omode & SOAP_IO_UDP) && setsockopt(soap->master, IPPROTO_TCP, TCP_NODELAY, (char*)&set, sizeof(int))) + { soap->errnum = soap_socket_errno(soap->master); + soap_set_receiver_error(soap, tcp_error(soap), "setsockopt TCP_NODELAY failed in soap_bind()", SOAP_TCP_ERROR); + return SOAP_INVALID_SOCKET; + } +#endif +#endif +#ifdef WITH_IPV6 +#ifdef IPV6_V6ONLY + if (setsockopt(soap->master, level, IPV6_V6ONLY, (char*)&unset, sizeof(int))) + { soap->errnum = soap_socket_errno(soap->master); + soap_set_receiver_error(soap, tcp_error(soap), "setsockopt IPV6_V6ONLY failed in soap_bind()", SOAP_TCP_ERROR); + return SOAP_INVALID_SOCKET; + } +#endif + soap->errmode = 0; + if (bind(soap->master, res.ai_addr, (int)res.ai_addrlen)) + { soap->errnum = soap_socket_errno(soap->master); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not bind to host\n")); + soap_closesock(soap); + soap_set_receiver_error(soap, tcp_error(soap), "bind failed in soap_bind()", SOAP_TCP_ERROR); + return SOAP_INVALID_SOCKET; + } +#else + soap->peerlen = sizeof(soap->peer); + memset((void*)&soap->peer, 0, sizeof(soap->peer)); + soap->peer.sin_family = AF_INET; + soap->errmode = 2; + if (host) + { if (soap->fresolve(soap, host, &soap->peer.sin_addr)) + { soap_set_receiver_error(soap, tcp_error(soap), "get host by name failed in soap_bind()", SOAP_TCP_ERROR); + return SOAP_INVALID_SOCKET; + } + } + else + soap->peer.sin_addr.s_addr = htonl(INADDR_ANY); + soap->peer.sin_port = htons((short)port); + soap->errmode = 0; + if (bind(soap->master, (struct sockaddr*)&soap->peer, (int)soap->peerlen)) + { soap->errnum = soap_socket_errno(soap->master); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not bind to host\n")); + soap_closesock(soap); + soap_set_receiver_error(soap, tcp_error(soap), "bind failed in soap_bind()", SOAP_TCP_ERROR); + return SOAP_INVALID_SOCKET; + } +#endif + if (!(soap->omode & SOAP_IO_UDP) && listen(soap->master, backlog)) + { soap->errnum = soap_socket_errno(soap->master); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not bind to host\n")); + soap_closesock(soap); + soap_set_receiver_error(soap, tcp_error(soap), "listen failed in soap_bind()", SOAP_TCP_ERROR); + return SOAP_INVALID_SOCKET; + } + return soap->master; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIO +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_poll(struct soap *soap) +{ +#ifndef WITH_LEAN + register int r; + if (soap_valid_socket(soap->socket)) + { r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_ALL, 0); + if (r > 0 && (r & SOAP_TCP_SELECT_ERR)) + r = -1; + } + else if (soap_valid_socket(soap->master)) + r = tcp_select(soap, soap->master, SOAP_TCP_SELECT_SND, 0); + else + return SOAP_OK; + if (r > 0) + { +#ifdef WITH_OPENSSL + if (soap->imode & SOAP_ENC_SSL) + { + if (soap_valid_socket(soap->socket) + && (r & SOAP_TCP_SELECT_SND) + && (!(r & SOAP_TCP_SELECT_RCV) + || SSL_peek(soap->ssl, soap->tmpbuf, 1) > 0)) + return SOAP_OK; + } + else +#endif + if (soap_valid_socket(soap->socket) + && (r & SOAP_TCP_SELECT_SND) + && (!(r & SOAP_TCP_SELECT_RCV) + || recv(soap->socket, soap->tmpbuf, 1, MSG_PEEK) > 0)) + return SOAP_OK; + } + else if (r < 0) + { if ((soap_valid_socket(soap->master) || soap_valid_socket(soap->socket)) && soap_socket_errno(soap->master) != SOAP_EINTR) + { soap_set_receiver_error(soap, tcp_error(soap), "select failed in soap_poll()", SOAP_TCP_ERROR); + return soap->error = SOAP_TCP_ERROR; + } + } + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Polling: other end down on socket=%d select=%d\n", soap->socket, r)); + return SOAP_EOF; +#else + return SOAP_OK; +#endif +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEAN +#ifndef WITH_NOIO +#ifndef PALM_1 +static int +tcp_select(struct soap *soap, SOAP_SOCKET s, int flags, int timeout) +{ register int r; + struct timeval tv; + fd_set fd[3], *rfd, *sfd, *efd; + soap->errnum = 0; +#ifndef WIN32 + /* if fd max set size exceeded, use poll() when available */ +#if defined(__QNX__) || defined(QNX) /* select() is not MT safe on some QNX */ + if (1) +#else + if ((int)s >= (int)FD_SETSIZE) +#endif +#ifdef HAVE_POLL + { struct pollfd pollfd; + int retries = 0; + pollfd.fd = (int)s; + pollfd.events = 0; + if (flags & SOAP_TCP_SELECT_RCV) + pollfd.events |= POLLIN; + if (flags & SOAP_TCP_SELECT_SND) + pollfd.events |= POLLOUT; + if (flags & SOAP_TCP_SELECT_ERR) + pollfd.events |= POLLERR; + if (timeout < 0) + timeout /= -1000; /* -usec -> ms */ + else if (timeout <= 1000000) /* avoid overflow */ + timeout *= 1000; /* sec -> ms */ + else + { retries = timeout / 1000000; + timeout = 1000000000; + } + do r = poll(&pollfd, 1, timeout); + while (r == 0 && retries--); + if (r > 0) + { r = 0; + if ((flags & SOAP_TCP_SELECT_RCV) && (pollfd.revents & POLLIN)) + r |= SOAP_TCP_SELECT_RCV; + if ((flags & SOAP_TCP_SELECT_SND) && (pollfd.revents & POLLOUT)) + r |= SOAP_TCP_SELECT_SND; + if ((flags & SOAP_TCP_SELECT_ERR) && (pollfd.revents & POLLERR)) + r |= SOAP_TCP_SELECT_ERR; + } + else if (r < 0) + soap->errnum = soap_socket_errno(s); + return r; + } +#else + { soap->error = SOAP_FD_EXCEEDED; + return -1; + } +#endif +#endif + rfd = sfd = efd = NULL; + if (flags & SOAP_TCP_SELECT_RCV) + { rfd = &fd[0]; + FD_ZERO(rfd); + FD_SET(s, rfd); + } + if (flags & SOAP_TCP_SELECT_SND) + { sfd = &fd[1]; + FD_ZERO(sfd); + FD_SET(s, sfd); + } + if (flags & SOAP_TCP_SELECT_ERR) + { efd = &fd[2]; + FD_ZERO(efd); + FD_SET(s, efd); + } + if (timeout >= 0) + { tv.tv_sec = timeout; + tv.tv_usec = 0; + } + else + { tv.tv_sec = -timeout / 1000000; + tv.tv_usec = -timeout % 1000000; + } + r = select((int)s + 1, rfd, sfd, efd, &tv); + if (r > 0) + { r = 0; + if ((flags & SOAP_TCP_SELECT_RCV) && FD_ISSET(s, rfd)) + r |= SOAP_TCP_SELECT_RCV; + if ((flags & SOAP_TCP_SELECT_SND) && FD_ISSET(s, sfd)) + r |= SOAP_TCP_SELECT_SND; + if ((flags & SOAP_TCP_SELECT_ERR) && FD_ISSET(s, efd)) + r |= SOAP_TCP_SELECT_ERR; + } + else if (r < 0) + soap->errnum = soap_socket_errno(s); + return r; +} +#endif +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIO +#ifndef PALM_1 +static SOAP_SOCKET +tcp_accept(struct soap *soap, SOAP_SOCKET s, struct sockaddr *a, int *n) +{ SOAP_SOCKET fd; + fd = accept(s, a, (SOAP_SOCKLEN_T*)n); /* portability note: see SOAP_SOCKLEN_T definition in stdsoap2.h */ +#ifdef SOCKET_CLOSE_ON_EXEC +#ifdef WIN32 +#ifndef UNDER_CE + SetHandleInformation((HANDLE)fd, HANDLE_FLAG_INHERIT, 0); +#endif +#else + fcntl(fd, F_SETFD, FD_CLOEXEC); +#endif +#endif + return fd; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIO +#ifndef PALM_1 +SOAP_FMAC1 +SOAP_SOCKET +SOAP_FMAC2 +soap_accept(struct soap *soap) +{ int n = (int)sizeof(soap->peer); +#ifndef WITH_LEAN + int len = SOAP_BUFLEN; + int set = 1; +#endif + soap->error = SOAP_OK; +#ifndef WITH_LEAN + if ((soap->omode & SOAP_IO_UDP)) + return soap->socket = soap->master; +#endif + memset((void*)&soap->peer, 0, sizeof(soap->peer)); + soap->socket = SOAP_INVALID_SOCKET; + soap->errmode = 0; + soap->keep_alive = 0; + if (soap_valid_socket(soap->master)) + { register int err; + for (;;) + { +#ifndef WITH_LEAN + if (soap->accept_timeout || soap->send_timeout || soap->recv_timeout) + { for (;;) + { register int r; + r = tcp_select(soap, soap->master, SOAP_TCP_SELECT_ALL, soap->accept_timeout ? soap->accept_timeout : 60); + if (r > 0) + break; + if (!r && soap->accept_timeout) + { soap_set_receiver_error(soap, "Timeout", "accept failed in soap_accept()", SOAP_TCP_ERROR); + return SOAP_INVALID_SOCKET; + } + if (r < 0) + { r = soap->errnum; + if (r != SOAP_EINTR) + { soap_closesock(soap); + soap_set_sender_error(soap, tcp_error(soap), "accept failed in soap_accept()", SOAP_TCP_ERROR); + return SOAP_INVALID_SOCKET; + } + } + } + } + if (soap->accept_timeout || soap->send_timeout || soap->recv_timeout) + SOAP_SOCKNONBLOCK(soap->master) + else + SOAP_SOCKBLOCK(soap->master) +#endif + soap->socket = soap->faccept(soap, soap->master, (struct sockaddr*)&soap->peer, &n); + soap->peerlen = (size_t)n; + if (soap_valid_socket(soap->socket)) + { +#ifdef WITH_IPV6 +/* Use soap->host to store the numeric form of the remote host */ + getnameinfo((struct sockaddr*)&soap->peer, n, soap->host, sizeof(soap->host), NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV); + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Accept socket %d from %s\n", soap->socket, soap->host)); + soap->ip = 0; /* info stored in soap->peer and soap->host */ + soap->port = 0; /* info stored in soap->peer and soap->host */ +#else + soap->ip = ntohl(soap->peer.sin_addr.s_addr); + soap->port = (int)ntohs(soap->peer.sin_port); /* does not return port number on some systems */ + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Accept socket %d at port %d from IP %d.%d.%d.%d\n", soap->socket, soap->port, (int)(soap->ip>>24)&0xFF, (int)(soap->ip>>16)&0xFF, (int)(soap->ip>>8)&0xFF, (int)soap->ip&0xFF)); +#endif +#ifndef WITH_LEAN + if (soap->accept_flags == SO_LINGER) + { struct linger linger; + memset((void*)&linger, 0, sizeof(linger)); + linger.l_onoff = 1; + linger.l_linger = soap->linger_time; + if (setsockopt(soap->socket, SOL_SOCKET, SO_LINGER, (char*)&linger, sizeof(struct linger))) + { soap->errnum = soap_socket_errno(soap->socket); + soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_LINGER failed in soap_accept()", SOAP_TCP_ERROR); + soap_closesock(soap); + return SOAP_INVALID_SOCKET; + } + } + else if (soap->accept_flags && setsockopt(soap->socket, SOL_SOCKET, soap->accept_flags, (char*)&set, sizeof(int))) + { soap->errnum = soap_socket_errno(soap->socket); + soap_set_receiver_error(soap, tcp_error(soap), "setsockopt failed in soap_accept()", SOAP_TCP_ERROR); + soap_closesock(soap); + return SOAP_INVALID_SOCKET; + } + if (((soap->imode | soap->omode) & SOAP_IO_KEEPALIVE) && setsockopt(soap->socket, SOL_SOCKET, SO_KEEPALIVE, (char*)&set, sizeof(int))) + { soap->errnum = soap_socket_errno(soap->socket); + soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_KEEPALIVE failed in soap_accept()", SOAP_TCP_ERROR); + soap_closesock(soap); + return SOAP_INVALID_SOCKET; + } + if (setsockopt(soap->socket, SOL_SOCKET, SO_SNDBUF, (char*)&len, sizeof(int))) + { soap->errnum = soap_socket_errno(soap->socket); + soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_SNDBUF failed in soap_accept()", SOAP_TCP_ERROR); + soap_closesock(soap); + return SOAP_INVALID_SOCKET; + } + if (setsockopt(soap->socket, SOL_SOCKET, SO_RCVBUF, (char*)&len, sizeof(int))) + { soap->errnum = soap_socket_errno(soap->socket); + soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_RCVBUF failed in soap_accept()", SOAP_TCP_ERROR); + soap_closesock(soap); + return SOAP_INVALID_SOCKET; + } +#ifdef TCP_NODELAY + if (!(soap->omode & SOAP_IO_UDP) && setsockopt(soap->socket, IPPROTO_TCP, TCP_NODELAY, (char*)&set, sizeof(int))) + { soap->errnum = soap_socket_errno(soap->socket); + soap_set_receiver_error(soap, tcp_error(soap), "setsockopt TCP_NODELAY failed in soap_accept()", SOAP_TCP_ERROR); + soap_closesock(soap); + return SOAP_INVALID_SOCKET; + } +#endif +#endif + soap->keep_alive = (((soap->imode | soap->omode) & SOAP_IO_KEEPALIVE) != 0); + return soap->socket; + } + err = soap_socket_errno(soap->socket); + if (err != 0 && err != SOAP_EINTR && err != SOAP_EAGAIN && err != SOAP_EWOULDBLOCK) + { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Accept failed from %s\n", soap->host)); + soap->errnum = err; + soap_set_receiver_error(soap, tcp_error(soap), "accept failed in soap_accept()", SOAP_TCP_ERROR); + soap_closesock(soap); + return SOAP_INVALID_SOCKET; + } + } + } + else + { soap->errnum = 0; + soap_set_receiver_error(soap, tcp_error(soap), "no master socket in soap_accept()", SOAP_TCP_ERROR); + return SOAP_INVALID_SOCKET; + } +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIO +#ifndef PALM_1 +static int +tcp_disconnect(struct soap *soap) +{ +#ifdef WITH_OPENSSL + if (soap->ssl) + { int r, s = 0; + if (soap->session) + { SSL_SESSION_free(soap->session); + soap->session = NULL; + } + if (*soap->host) + { soap->session = SSL_get1_session(soap->ssl); + if (soap->session) + { strcpy(soap->session_host, soap->host); + soap->session_port = soap->port; + } + } + r = SSL_shutdown(soap->ssl); + /* SSL shutdown does not work when reads are pending */ + while (SSL_want_read(soap->ssl)) + { SSL_read(soap->ssl, NULL, 0); + if (soap_socket_errno(soap->socket) != SOAP_EAGAIN) + { r = SSL_shutdown(soap->ssl); + break; + } + } + if (r == 0) + { if (soap_valid_socket(soap->socket)) + { if (!soap->fshutdownsocket(soap, soap->socket, 1)) + { /* + wait up to 10 seconds for close_notify to be sent by peer (if peer not + present, this avoids calling SSL_shutdown() which has a lengthy return + timeout) + */ + r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, 10); + if (r <= 0 && soap->errnum != SOAP_EINTR) + { soap->errnum = 0; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Connection lost...\n")); + soap->fclosesocket(soap, soap->socket); + soap->socket = SOAP_INVALID_SOCKET; + ERR_remove_state(0); + return SOAP_OK; + } + } + } + } + if (r != 1) + { s = ERR_get_error(); + if (s) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Shutdown failed: %d\n", SSL_get_error(soap->ssl, r))); + if (soap_valid_socket(soap->socket) && !(soap->omode & SOAP_IO_UDP)) + { soap->fclosesocket(soap, soap->socket); + soap->socket = SOAP_INVALID_SOCKET; + } + } + } + SSL_free(soap->ssl); + soap->ssl = NULL; + if (s) + return SOAP_SSL_ERROR; + ERR_remove_state(0); + } +#endif + if (soap_valid_socket(soap->socket) && !(soap->omode & SOAP_IO_UDP)) + { soap->fshutdownsocket(soap, soap->socket, 2); + soap->fclosesocket(soap, soap->socket); + soap->socket = SOAP_INVALID_SOCKET; + } + return SOAP_OK; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIO +#ifndef PALM_1 +static int +tcp_closesocket(struct soap *soap, SOAP_SOCKET fd) +{ DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Close socket %d\n", (int)fd)); + return soap_closesocket(fd); +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIO +#ifndef PALM_1 +static int +tcp_shutdownsocket(struct soap *soap, SOAP_SOCKET fd, int how) +{ DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Shutdown socket %d how=%d\n", (int)fd, how)); + return shutdown(fd, how); +} +#endif +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_closesock(struct soap *soap) +{ register int status = soap->error; + if (status == SOAP_EOF || status == SOAP_TCP_ERROR || status == SOAP_SSL_ERROR || !soap->keep_alive) + { if (soap->fclose && (soap->error = soap->fclose(soap))) + return soap->error; + soap->keep_alive = 0; + } +#ifdef WITH_ZLIB + if (soap->zlib_state == SOAP_ZLIB_DEFLATE) + deflateEnd(soap->d_stream); + else if (soap->zlib_state == SOAP_ZLIB_INFLATE) + inflateEnd(soap->d_stream); + soap->zlib_state = SOAP_ZLIB_NONE; +#endif + return soap->error = status; +} +#endif + +/******************************************************************************/ +#ifndef WITH_NOIDREF +#ifndef PALM_2 +SOAP_FMAC1 +size_t +SOAP_FMAC2 +soap_hash(register const char *s) +{ register size_t h = 0; + while (*s) + h = 65599*h + *s++; + return h % SOAP_IDHASH; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIDREF +#ifndef PALM_1 +static void +soap_init_pht(struct soap *soap) +{ register int i; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Initializing pointer hashtable\n")); + soap->pblk = NULL; + soap->pidx = 0; + for (i = 0; i < (int)SOAP_PTRHASH; i++) + soap->pht[i] = NULL; +} +#endif +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +struct soap* +SOAP_FMAC2 +soap_new1(soap_mode mode) +{ return soap_new2(mode, mode); +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +struct soap* +SOAP_FMAC2 +soap_new() +{ return soap_new2(SOAP_IO_DEFAULT, SOAP_IO_DEFAULT); +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +struct soap* +SOAP_FMAC2 +soap_new2(soap_mode imode, soap_mode omode) +{ struct soap *soap = (struct soap*)malloc(sizeof(struct soap)); + if (soap) + soap_init2(soap, imode, omode); + return soap; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_free(struct soap *soap) +{ soap_done(soap); + free(soap); +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_del(struct soap *soap) +{ free(soap); +} +#endif + +/******************************************************************************/ +#ifndef WITH_NOIDREF +#ifndef PALM_1 +static void +soap_free_pht(struct soap *soap) +{ register struct soap_pblk *pb, *next; + register int i; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Free pointer hashtable\n")); + for (pb = soap->pblk; pb; pb = next) + { next = pb->next; + SOAP_FREE(soap, pb); + } + soap->pblk = NULL; + soap->pidx = 0; + for (i = 0; i < (int)SOAP_PTRHASH; i++) + soap->pht[i] = NULL; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIDREF +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_embed(struct soap *soap, const void *p, const struct soap_array *a, int n, const char *tag, int type) +{ register int i; + struct soap_plist *pp; + if (soap->version == 2) + soap->encoding = 1; + if (a) + i = soap_array_pointer_lookup(soap, p, a, n, type, &pp); + else + i = soap_pointer_lookup(soap, p, type, &pp); + if (i) + { if (soap_is_embedded(soap, pp) + || soap_is_single(soap, pp)) + return 0; + soap_set_embedded(soap, pp); + } + return i; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIDREF +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_pointer_lookup(struct soap *soap, const void *p, int type, struct soap_plist **ppp) +{ register struct soap_plist *pp; + *ppp = NULL; + if (p) + { for (pp = soap->pht[soap_hash_ptr(p)]; pp; pp = pp->next) + { if (pp->ptr == p && pp->type == type) + { *ppp = pp; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Lookup location=%p type=%d id=%d\n", p, type, pp->id)); + return pp->id; + } + } + } + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Lookup location=%p type=%d: not found\n", p, type)); + return 0; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIDREF +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_pointer_enter(struct soap *soap, const void *p, const struct soap_array *a, int n, int type, struct soap_plist **ppp) +{ register size_t h; + register struct soap_plist *pp; + if (!soap->pblk || soap->pidx >= SOAP_PTRBLK) + { register struct soap_pblk *pb = (struct soap_pblk*)SOAP_MALLOC(soap, sizeof(struct soap_pblk)); + if (!pb) + { soap->error = SOAP_EOM; + return 0; + } + pb->next = soap->pblk; + soap->pblk = pb; + soap->pidx = 0; + } + *ppp = pp = &soap->pblk->plist[soap->pidx++]; + if (a) + h = soap_hash_ptr(a->__ptr); + else + h = soap_hash_ptr(p); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Pointer enter location=%p array=%p size=%d dim=%d type=%d id=%d\n", p, a?a->__ptr:NULL, a?a->__size:0, n, type, soap->idnum+1)); + pp->next = soap->pht[h]; + pp->type = type; + pp->mark1 = 0; + pp->mark2 = 0; + pp->ptr = p; + pp->array = a; + soap->pht[h] = pp; + pp->id = ++soap->idnum; + return pp->id; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIDREF +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_array_pointer_lookup(struct soap *soap, const void *p, const struct soap_array *a, int n, int type, struct soap_plist **ppp) +{ register struct soap_plist *pp; + *ppp = NULL; + if (!p || !a->__ptr) + return 0; + for (pp = soap->pht[soap_hash_ptr(a->__ptr)]; pp; pp = pp->next) + { if (pp->type == type && pp->array && pp->array->__ptr == a->__ptr) + { register int i; + for (i = 0; i < n; i++) + if (((const int*)&pp->array->__size)[i] != ((const int*)&a->__size)[i]) + break; + if (i == n) + { *ppp = pp; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Array lookup location=%p type=%d id=%d\n", a->__ptr, type, pp->id)); + return pp->id; + } + } + } + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Array lookup location=%p type=%d: not found\n", a->__ptr, type)); + return 0; +} +#endif +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_begin_count(struct soap *soap) +{ soap_free_ns(soap); +#ifndef WITH_LEANER + if ((soap->mode & SOAP_ENC_DIME) || (soap->omode & SOAP_ENC_DIME)) + soap->mode = soap->omode | SOAP_IO_LENGTH | SOAP_ENC_DIME; + else +#endif + { soap->mode = soap->omode; + if ((soap->mode & SOAP_IO) == SOAP_IO_STORE + || (((soap->mode & SOAP_IO) == SOAP_IO_CHUNK || (soap->mode & SOAP_ENC_XML)) +#ifndef WITH_LEANER + && !soap->fpreparesend +#endif + )) + soap->mode &= ~SOAP_IO_LENGTH; + else + soap->mode |= SOAP_IO_LENGTH; + } +#ifdef WITH_ZLIB + if ((soap->mode & SOAP_ENC_ZLIB) && (soap->mode & SOAP_IO) == SOAP_IO_FLUSH) + { if (!(soap->mode & SOAP_ENC_DIME)) + soap->mode &= ~SOAP_IO_LENGTH; + if (soap->mode & SOAP_ENC_XML) + soap->mode |= SOAP_IO_BUFFER; + else + soap->mode |= SOAP_IO_STORE; + } +#endif + if (!soap->encodingStyle && !(soap->mode & SOAP_XML_GRAPH)) + soap->mode |= SOAP_XML_TREE; +#ifndef WITH_LEANER + if ((soap->mode & SOAP_ENC_MTOM) && (soap->mode & SOAP_ENC_DIME)) + soap->mode |= SOAP_ENC_MIME; + else if (!(soap->mode & SOAP_ENC_MIME)) + soap->mode &= ~SOAP_ENC_MTOM; + if (soap->mode & SOAP_ENC_MIME) + soap_select_mime_boundary(soap); + soap->dime.list = soap->dime.last; /* keep track of last DIME attachment */ +#endif + soap->count = 0; + soap->ns = 0; + soap->null = 0; + soap->position = 0; + soap->mustUnderstand = 0; + soap->encoding = 0; + soap->part = SOAP_BEGIN; + soap->idnum = 0; + soap_clr_attr(soap); + soap_set_local_namespaces(soap); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Begin count phase (socket=%d mode=0x%x count=%lu)\n", soap->socket, soap->mode, (unsigned long)soap->count)); +#ifndef WITH_LEANER + soap->dime.count = 0; /* count # of attachments */ + soap->dime.size = 0; /* accumulate total size of attachments */ + if (soap->fprepareinit && (soap->mode & SOAP_IO) != SOAP_IO_STORE) + return soap->error = soap->fprepareinit(soap); +#endif + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_end_count(struct soap *soap) +{ +#ifndef WITH_LEANER + if (soap->fpreparefinal) + return soap->error = soap->fpreparefinal(soap); +#endif + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "End of count phase\n")); + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_begin_send(struct soap *soap) +{ DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Initializing for output\n")); + soap_free_ns(soap); + soap->error = SOAP_OK; + soap->mode = soap->omode | (soap->mode & (SOAP_IO_LENGTH | SOAP_ENC_DIME)); +#ifdef WITH_ZLIB + if ((soap->mode & SOAP_ENC_ZLIB) && (soap->mode & SOAP_IO) == SOAP_IO_FLUSH) + { if (soap->mode & SOAP_ENC_XML) + soap->mode |= SOAP_IO_BUFFER; + else + soap->mode |= SOAP_IO_STORE; + } +#endif +#ifndef WITH_LEAN + if ((soap->mode & SOAP_IO_UDP)) + { soap->mode |= SOAP_ENC_XML; + if (soap->count > SOAP_BUFLEN) + return soap->error = SOAP_UDP_ERROR; + } +#endif + if ((soap->mode & SOAP_IO) == SOAP_IO_FLUSH && soap_valid_socket(soap->socket)) + { if (soap->count || (soap->mode & SOAP_IO_LENGTH) || (soap->mode & SOAP_ENC_XML)) + soap->mode |= SOAP_IO_BUFFER; + else + soap->mode |= SOAP_IO_STORE; + } + soap->mode &= ~SOAP_IO_LENGTH; + if ((soap->mode & SOAP_IO) == SOAP_IO_STORE) + if (soap_new_block(soap) == NULL) + return soap->error; + if (!(soap->mode & SOAP_IO_KEEPALIVE)) + soap->keep_alive = 0; + if (!soap->encodingStyle && !(soap->mode & SOAP_XML_GRAPH)) + soap->mode |= SOAP_XML_TREE; +#ifndef WITH_LEANER + if ((soap->mode & SOAP_ENC_MTOM) && (soap->mode & SOAP_ENC_DIME)) + { soap->mode |= SOAP_ENC_MIME; + soap->mode &= ~SOAP_ENC_DIME; + } + else if (!(soap->mode & SOAP_ENC_MIME)) + soap->mode &= ~SOAP_ENC_MTOM; + if (soap->mode & SOAP_ENC_MIME) + soap_select_mime_boundary(soap); +#ifdef WIN32 +#ifndef UNDER_CE +#ifndef WITH_FASTCGI + if (!soap_valid_socket(soap->socket)) /* Set win32 stdout or soap->sendfd to BINARY, e.g. to support DIME */ +#ifdef __BORLANDC__ + setmode(soap->sendfd, _O_BINARY); +#else + _setmode(soap->sendfd, _O_BINARY); +#endif +#endif +#endif +#endif +#endif + if (soap->mode & SOAP_IO) + { soap->bufidx = 0; + soap->buflen = 0; + } + soap->chunksize = 0; + soap->ns = 0; + soap->null = 0; + soap->position = 0; + soap->mustUnderstand = 0; + soap->encoding = 0; + soap->idnum = 0; + soap->level = 0; + soap_clr_attr(soap); + soap_set_local_namespaces(soap); +#ifdef WITH_ZLIB + soap->z_ratio_out = 1.0; + if ((soap->mode & SOAP_ENC_ZLIB) && soap->zlib_state != SOAP_ZLIB_DEFLATE) + { if (!soap->z_buf) + soap->z_buf = (char*)SOAP_MALLOC(soap, SOAP_BUFLEN); + soap->d_stream->next_out = (Byte*)soap->z_buf; + soap->d_stream->avail_out = SOAP_BUFLEN; +#ifdef WITH_GZIP + if (soap->zlib_out != SOAP_ZLIB_DEFLATE) + { memcpy(soap->z_buf, "\37\213\10\0\0\0\0\0\0\377", 10); + soap->d_stream->next_out = (Byte*)soap->z_buf + 10; + soap->d_stream->avail_out = SOAP_BUFLEN - 10; + soap->z_crc = crc32(0L, NULL, 0); + soap->zlib_out = SOAP_ZLIB_GZIP; + if (soap->z_dict) + *((Byte*)soap->z_buf + 2) = 0xff; + if (deflateInit2(soap->d_stream, soap->z_level, Z_DEFLATED, -MAX_WBITS, 8, Z_DEFAULT_STRATEGY) != Z_OK) + return soap->error = SOAP_ZLIB_ERROR; + } + else +#endif + if (deflateInit(soap->d_stream, soap->z_level) != Z_OK) + return soap->error = SOAP_ZLIB_ERROR; + if (soap->z_dict) + { if (deflateSetDictionary(soap->d_stream, (const Bytef*)soap->z_dict, soap->z_dict_len) != Z_OK) + return soap->error = SOAP_ZLIB_ERROR; + } + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Deflate initialized\n")); + soap->zlib_state = SOAP_ZLIB_DEFLATE; + } +#endif +#ifdef WITH_OPENSSL + if (soap->ssl) + ERR_clear_error(); +#endif + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Begin send phase (socket=%d mode=0x%x count=%lu)\n", soap->socket, soap->mode, (unsigned long)soap->count)); + soap->part = SOAP_BEGIN; +#ifndef WITH_LEANER + if (soap->fprepareinit && (soap->mode & SOAP_IO) == SOAP_IO_STORE) + soap->fprepareinit(soap); +#endif + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef WITH_NOIDREF +#ifndef PALM_2 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_embedded(struct soap *soap, const void *p, int t) +{ struct soap_plist *pp; + if (soap_pointer_lookup(soap, p, t, &pp)) + { pp->mark1 = 1; + pp->mark2 = 1; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Embedded %p type=%d mark set to 1\n", p, t)); + } +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIDREF +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_reference(struct soap *soap, const void *p, int t) +{ struct soap_plist *pp; + if (!p || (soap->mode & SOAP_XML_TREE)) + return 1; + if (soap_pointer_lookup(soap, p, t, &pp)) + { if (pp->mark1 == 0) + { pp->mark1 = 2; + pp->mark2 = 2; + } + } + else if (soap_pointer_enter(soap, p, NULL, 0, t, &pp)) + { pp->mark1 = 0; + pp->mark2 = 0; + } + else + return 1; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Reference %p type=%d (%d %d)\n", p, t, (int)pp->mark1, (int)pp->mark2)); + return pp->mark1; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIDREF +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_array_reference(struct soap *soap, const void *p, const struct soap_array *a, int n, int t) +{ register int i; + struct soap_plist *pp; + if (!p || !a->__ptr) + return 1; + i = soap_array_pointer_lookup(soap, p, a, n, t, &pp); + if (i) + { if (pp->mark1 == 0) + { pp->mark1 = 2; + pp->mark2 = 2; + } + } + else if (!soap_pointer_enter(soap, p, a, n, t, &pp)) + return 1; + else + { pp->mark1 = 0; + pp->mark2 = 0; + } + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Array reference %p ptr=%p dim=%d type=%d (%d %d)\n", p, a->__ptr, n, t, (int)pp->mark1, (int)pp->mark2)); + return pp->mark1; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIDREF +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_embedded_id(struct soap *soap, int id, const void *p, int t) +{ struct soap_plist *pp = NULL; + if (soap->mode & SOAP_XML_TREE) + return id; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Embedded_id %p type=%d id=%d\n", p, t, id)); + if (soap->version == 1 && soap->encodingStyle && !(soap->mode & SOAP_XML_GRAPH) && soap->part != SOAP_IN_HEADER) + { if (id < 0) + { id = soap_pointer_lookup(soap, p, t, &pp); + if (id) + { if (soap->mode & SOAP_IO_LENGTH) + pp->mark1 = 2; + else + pp->mark2 = 2; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Embedded_id multiref id=%d %p type=%d = (%d %d)\n", id, p, t, (int)pp->mark1, (int)pp->mark2)); + } + return -1; + } + return id; + } + if (id < 0) + id = soap_pointer_lookup(soap, p, t, &pp); + else if (id && !soap_pointer_lookup(soap, p, t, &pp)) + return 0; + if (id && pp) + { if (soap->mode & SOAP_IO_LENGTH) + pp->mark1 = 1; + else + pp->mark2 = 1; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Embedded_id embedded ref id=%d %p type=%d = (%d %d)\n", id, p, t, (int)pp->mark1, (int)pp->mark2)); + } + return id; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIDREF +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_is_embedded(struct soap *soap, struct soap_plist *pp) +{ if (!pp) + return 0; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Is embedded? %d %d\n", (int)pp->mark1, (int)pp->mark2)); + if (soap->version == 1 && soap->encodingStyle && !(soap->mode & SOAP_XML_GRAPH) && soap->part != SOAP_IN_HEADER) + { if (soap->mode & SOAP_IO_LENGTH) + return pp->mark1 != 0; + return pp->mark2 != 0; + } + if (soap->mode & SOAP_IO_LENGTH) + return pp->mark1 == 1; + return pp->mark2 == 1; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIDREF +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_is_single(struct soap *soap, struct soap_plist *pp) +{ if (soap->part == SOAP_IN_HEADER) + return 1; + if (!pp) + return 0; + if (soap->mode & SOAP_IO_LENGTH) + return pp->mark1 == 0; + return pp->mark2 == 0; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIDREF +#ifndef PALM_2 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_set_embedded(struct soap *soap, struct soap_plist *pp) +{ if (!pp) + return; + if (soap->mode & SOAP_IO_LENGTH) + pp->mark1 = 1; + else + pp->mark2 = 1; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_attachment(struct soap *soap, const char *tag, int id, const void *p, const struct soap_array *a, const char *aid, const char *atype, const char *aoptions, int n, const char *type, int t) +{ +#ifndef WITH_NOIDREF + struct soap_plist *pp; + int i; + if (!p || !a->__ptr || (!aid && !atype)) + return soap_element_id(soap, tag, id, p, a, n, type, t); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Attachment tag='%s' id='%s' (%d) type='%s'\n", tag, aid?aid:SOAP_STR_EOS, id, atype?atype:SOAP_STR_EOS)); + i = soap_array_pointer_lookup(soap, p, a, n, t, &pp); + if (!i) + { i = soap_pointer_enter(soap, p, a, n, t, &pp); + if (!i) + { soap->error = SOAP_EOM; + return -1; + } + } + if (id <= 0) + id = i; + if (!aid) + { sprintf(soap->tmpbuf, soap->dime_id_format, id); + aid = soap_strdup(soap, soap->tmpbuf); + } + /* Add MTOM xop:Include element when necessary */ + /* TODO: this code to be obsoleted with new import/xop.h conventions */ + if ((soap->mode & SOAP_ENC_MTOM) && strcmp(tag, "xop:Include")) + { if (soap_element_begin_out(soap, tag, 0, type) + || soap_element_href(soap, "xop:Include", 0, "href", aid) + || soap_element_end_out(soap, tag)) + return soap->error; + } + else if (soap_element_href(soap, tag, 0, "href", aid)) + return soap->error; + if (soap->mode & SOAP_IO_LENGTH) + { if (pp->mark1 != 3) + { struct soap_multipart *content; + if (soap->mode & SOAP_ENC_MTOM) + content = soap_new_multipart(soap, &soap->mime.first, &soap->mime.last, (char*)a->__ptr, a->__size); + else + content = soap_new_multipart(soap, &soap->dime.first, &soap->dime.last, (char*)a->__ptr, a->__size); + if (!content) + { soap->error = SOAP_EOM; + return -1; + } + if (!strncmp(aid, "cid:", 4)) /* RFC 2111 */ + { if (soap->mode & SOAP_ENC_MTOM) + { char *s = (char*)soap_malloc(soap, strlen(aid) - 1); + if (s) + { *s = '<'; + strcpy(s + 1, aid + 4); + strcat(s, ">"); + content->id = s; + } + } + else + content->id = aid + 4; + } + else + content->id = aid; + content->type = atype; + content->options = aoptions; + content->encoding = SOAP_MIME_BINARY; + pp->mark1 = 3; + } + } + else + pp->mark2 = 3; +#endif + return -1; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIDREF +#ifndef PALM_1 +static void +soap_init_iht(struct soap *soap) +{ register int i; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Initializing ID hashtable\n")); + for (i = 0; i < SOAP_IDHASH; i++) + soap->iht[i] = NULL; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIDREF +#ifndef PALM_1 +static void +soap_free_iht(struct soap *soap) +{ register int i; + register struct soap_ilist *ip = NULL, *p = NULL; + register struct soap_flist *fp = NULL, *fq = NULL; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Free ID hashtable\n")); + for (i = 0; i < SOAP_IDHASH; i++) + { for (ip = soap->iht[i]; ip; ip = p) + { for (fp = ip->flist; fp; fp = fq) + { fq = fp->next; + SOAP_FREE(soap, fp); + } + p = ip->next; + SOAP_FREE(soap, ip); + } + soap->iht[i] = NULL; + } +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIDREF +#ifndef PALM_2 +SOAP_FMAC1 +struct soap_ilist * +SOAP_FMAC2 +soap_lookup(struct soap *soap, const char *id) +{ register struct soap_ilist *ip = NULL; + for (ip = soap->iht[soap_hash(id)]; ip; ip = ip->next) + if (!strcmp(ip->id, id)) + return ip; + return NULL; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIDREF +#ifndef PALM_2 +SOAP_FMAC1 +struct soap_ilist * +SOAP_FMAC2 +soap_enter(struct soap *soap, const char *id) +{ register size_t h; + register struct soap_ilist *ip; + ip = (struct soap_ilist*)SOAP_MALLOC(soap, sizeof(struct soap_ilist) + strlen(id)); + if (ip) + { h = soap_hash(id); + strcpy(ip->id, id); + ip->next = soap->iht[h]; + soap->iht[h] = ip; + } + return ip; +} +#endif +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +void* +SOAP_FMAC2 +soap_malloc(struct soap *soap, size_t n) +{ register char *p; + if (!n) + return (void*)SOAP_NON_NULL; + if (!soap) + return SOAP_MALLOC(soap, n); + if (soap->fmalloc) + p = (char*)soap->fmalloc(soap, n); + else + { n += sizeof(short); + n += (-(long)n) & (sizeof(void*)-1); /* align at 4-, 8- or 16-byte boundary */ + if (!(p = (char*)SOAP_MALLOC(soap, n + sizeof(void*) + sizeof(size_t)))) + { soap->error = SOAP_EOM; + return NULL; + } + /* set the canary to detect corruption */ + *(short*)(p + n - sizeof(short)) = (short)SOAP_CANARY; + /* keep chain of alloced cells for destruction */ + *(void**)(p + n) = soap->alist; + *(size_t*)(p + n + sizeof(void*)) = n; + soap->alist = p + n; + } + soap->alloced = 1; + return p; +} +#endif + +/******************************************************************************/ +#ifdef SOAP_MEM_DEBUG +static void +soap_init_mht(struct soap *soap) +{ register int i; + for (i = 0; i < (int)SOAP_PTRHASH; i++) + soap->mht[i] = NULL; +} +#endif + +/******************************************************************************/ +#ifdef SOAP_MEM_DEBUG +static void +soap_free_mht(struct soap *soap) +{ register int i; + register struct soap_mlist *mp, *mq; + for (i = 0; i < (int)SOAP_PTRHASH; i++) + { for (mp = soap->mht[i]; mp; mp = mq) + { mq = mp->next; + if (mp->live) + fprintf(stderr, "%s(%d): malloc() = %p not freed (memory leak or forgot to call soap_end()?)\n", mp->file, mp->line, mp->ptr); + free(mp); + } + soap->mht[i] = NULL; + } +} +#endif + +/******************************************************************************/ +#ifdef SOAP_MEM_DEBUG +SOAP_FMAC1 +void* +SOAP_FMAC2 +soap_track_malloc(struct soap *soap, const char *file, int line, size_t size) +{ register void *p = malloc(size); + if (soap) + { register size_t h = soap_hash_ptr(p); + register struct soap_mlist *mp = (struct soap_mlist*)malloc(sizeof(struct soap_mlist)); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "%s(%d): malloc(%lu) = %p\n", file, line, (unsigned long)size, p)); + mp->next = soap->mht[h]; + mp->ptr = p; + mp->file = file; + mp->line = line; + mp->live = 1; + soap->mht[h] = mp; + } + return p; +} +#endif + +/******************************************************************************/ +#ifdef SOAP_MEM_DEBUG +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_track_free(struct soap *soap, const char *file, int line, void *p) +{ register size_t h = soap_hash_ptr(p); + register struct soap_mlist *mp; + for (mp = soap->mht[h]; mp; mp = mp->next) + if (mp->ptr == p) + break; + if (mp) + { if (mp->live) + { free(p); + if (soap->fdebug[SOAP_INDEX_TEST]) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "%s(%d): free(%p)\n", file, line, p)); + } + mp->live = 0; + } + else + fprintf(stderr, "%s(%d): free(%p) double free of pointer malloced at %s(%d)\n", file, line, p, mp->file, mp->line); + } + else + fprintf(stderr, "%s(%d): free(%p) pointer not malloced\n", file, line, p); +} +#endif + +/******************************************************************************/ +#ifdef SOAP_MEM_DEBUG +static void +soap_track_unlink(struct soap *soap, const void *p) +{ register size_t h = soap_hash_ptr(p); + register struct soap_mlist *mp; + for (mp = soap->mht[h]; mp; mp = mp->next) + if (mp->ptr == p) + break; + if (mp) + mp->live = 0; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_dealloc(struct soap *soap, void *p) +{ if (soap_check_state(soap)) + return; + if (p) + { register char **q; + for (q = (char**)&soap->alist; *q; q = *(char***)q) + { + if (*(short*)(char*)(*q - sizeof(short)) != (short)SOAP_CANARY) + { +#ifdef SOAP_MEM_DEBUG + fprintf(stderr, "Data corruption in dynamic allocation (see logs)\n"); +#endif + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Data corruption:\n")); + DBGHEX(TEST, *q - 200, 200); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "\n")); + soap->error = SOAP_MOE; + return; + } + if (p == (void*)(*q - *(size_t*)(*q + sizeof(void*)))) + { *q = **(char***)q; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Freed data at %p\n", p)); + SOAP_FREE(soap, p); + return; + } + } + soap_delete(soap, p); + } + else + { register char *q; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Free all soap_malloc() data\n")); + while (soap->alist) + { q = (char*)soap->alist; + if (*(short*)(char*)(q - sizeof(short)) != (short)SOAP_CANARY) + { +#ifdef SOAP_MEM_DEBUG + fprintf(stderr, "Data corruption in dynamic allocation (see logs)\n"); +#endif + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Data corruption:\n")); + DBGHEX(TEST, q - 200, 200); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "\n")); + soap->error = SOAP_MOE; + return; + } + soap->alist = *(void**)q; + q -= *(size_t*)(q + sizeof(void*)); + SOAP_FREE(soap, q); + } + /* we must assume these were deallocated: */ + soap->action = NULL; + soap->fault = NULL; + soap->header = NULL; + soap->userid = NULL; + soap->passwd = NULL; + soap->authrealm = NULL; + soap->http_content = NULL; +#ifndef WITH_LEANER + soap_clr_mime(soap); +#endif + } +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_delete(struct soap *soap, void *p) +{ register struct soap_clist **cp; + if (soap_check_state(soap)) + return; + cp = &soap->clist; + if (p) + { while (*cp) + { if (p == (*cp)->ptr) + { register struct soap_clist *q = *cp; + *cp = q->next; + if (q->fdelete(q)) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not dealloc data %p: deletion callback failed for object type %d\n", q->ptr, q->type)); +#ifdef SOAP_MEM_DEBUG + fprintf(stderr, "new(object type = %d) = %p not freed: deletion callback failed\n", q->type, q->ptr); +#endif + } + SOAP_FREE(soap, q); + return; + } + cp = &(*cp)->next; + } + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not dealloc data %p: address not in list\n", p)); + } + else + { while (*cp) + { register struct soap_clist *q = *cp; + *cp = q->next; + if (q->fdelete(q)) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not dealloc data %p: deletion callback failed for object type %d\n", q->ptr, q->type)); +#ifdef SOAP_MEM_DEBUG + fprintf(stderr, "new(object type = %d) = %p not freed: deletion callback failed\n", q->type, q->ptr); +#endif + } + SOAP_FREE(soap, q); + } + } + soap->fault = NULL; /* this was possibly deallocated */ + soap->header = NULL; /* this was possibly deallocated */ +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_delegate_deletion(struct soap *soap, struct soap *soap_to) +{ register struct soap_clist *cp; + register char **q; +#ifdef SOAP_MEM_DEBUG + register void *p; + register struct soap_mlist **mp, *mq; + size_t h; +#endif + for (q = (char**)&soap->alist; *q; q = *(char***)q) + { + if (*(short*)(char*)(*q - sizeof(short)) != (short)SOAP_CANARY) + { +#ifdef SOAP_MEM_DEBUG + fprintf(stderr, "Data corruption in dynamic allocation (see logs)\n"); +#endif + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Data corruption:\n")); + DBGHEX(TEST, *q - 200, 200); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "\n")); + soap->error = SOAP_MOE; + return; + } +#ifdef SOAP_MEM_DEBUG + p = (void*)(*q - *(size_t*)(*q + sizeof(void*))); + h = soap_hash_ptr(p); + for (mp = &soap->mht[h]; *mp; mp = &(*mp)->next) + { if ((*mp)->ptr == p) + { mq = *mp; + *mp = mq->next; + mq->next = soap_to->mht[h]; + soap_to->mht[h] = mq; + break; + } + } +#endif + } + *q = (char*)soap_to->alist; + soap_to->alist = soap->alist; + soap->alist = NULL; + cp = soap_to->clist; + if (cp) + { while (cp->next) + cp = cp->next; + cp->next = soap->clist; + } + else + soap_to->clist = soap->clist; + soap->clist = NULL; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +struct soap_clist * +SOAP_FMAC2 +soap_link(struct soap *soap, void *p, int t, int n, int (*fdelete)(struct soap_clist*)) +{ register struct soap_clist *cp; + if ((cp = (struct soap_clist*)SOAP_MALLOC(soap, sizeof(struct soap_clist)))) + { cp->next = soap->clist; + cp->type = t; + cp->size = n; + cp->ptr = p; + cp->fdelete = fdelete; + soap->clist = cp; + } + return cp; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_unlink(struct soap *soap, const void *p) +{ register char **q; + register struct soap_clist **cp; + if (!soap || !p) + return; + for (q = (char**)&soap->alist; *q; q = *(char***)q) + { if (p == (void*)(*q - *(size_t*)(*q + sizeof(void*)))) + { *q = **(char***)q; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unlinked data %p\n", p)); +#ifdef SOAP_MEM_DEBUG + soap_track_unlink(soap, p); +#endif + return; + } + } + for (cp = &soap->clist; *cp; cp = &(*cp)->next) + { if (p == (*cp)->ptr) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unlinked class instance %p\n", p)); + q = (char**)*cp; + *cp = (*cp)->next; + SOAP_FREE(soap, q); + return; + } + } +} +#endif + +/******************************************************************************/ +#ifndef WITH_NOIDREF +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_lookup_type(struct soap *soap, const char *id) +{ register struct soap_ilist *ip; + if (id && *id) + { ip = soap_lookup(soap, id); + if (ip) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Lookup id='%s' type=%d\n", id, ip->type)); + return ip->type; + } + } + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "lookup type id='%s' NOT FOUND! Need to get it from xsi:type\n", id)); + return 0; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIDREF +#ifndef PALM_2 +SOAP_FMAC1 +void* +SOAP_FMAC2 +soap_id_lookup(struct soap *soap, const char *id, void **p, int t, size_t n, unsigned int k) +{ struct soap_ilist *ip; + void **q; + if (!p || !id || !*id) + return p; + ip = soap_lookup(soap, id); /* lookup pointer to hash table entry for string id */ + if (!ip) + { if (!(ip = soap_enter(soap, id))) /* new hash table entry for string id */ + return NULL; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Forwarding first href='%s' type=%d %p (%u bytes)\n", id, t, p, (unsigned int)n)); + ip->type = t; + ip->size = n; + ip->link = p; + ip->copy = NULL; + ip->flist = NULL; + ip->ptr = NULL; + ip->level = k; + *p = NULL; + } + else if (ip->ptr) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Resolved href='%s' type=%d location=%p (%u bytes)\n", id, t, ip->ptr, (unsigned int)n)); + if (ip->type != t) + { strcpy(soap->id, id); + soap->error = SOAP_HREF; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Type incompatibility: href='%s' id-type=%d href-type=%d\n", id, ip->type, t)); + return NULL; + } + while (ip->level < k) + { q = (void**)soap_malloc(soap, sizeof(void*)); + if (!q) + return NULL; + *p = (void*)q; + p = q; + k--; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Descending one level...\n")); + } + *p = ip->ptr; + } + else if (ip->level > k) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Resolving level %u pointers to href='%s'\n", ip->level, id)); + while (ip->level > k) + { void *s, **r = &ip->link; + q = (void**)ip->link; + while (q) + { *r = (void*)soap_malloc(soap, sizeof(void*)); + if (!*r) + return NULL; + s = *q; + *q = *r; + r = (void**)*r; + q = (void**)s; + } + *r = NULL; + ip->size = n; + ip->copy = NULL; + ip->level = ip->level - 1; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Descending one level...\n")); + } + q = (void**)ip->link; + ip->link = p; + *p = (void*)q; + } + else + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Forwarded href='%s' type=%d location=%p (%u bytes)\n", id, t, p, (unsigned int)n)); + while (ip->level < k) + { q = (void**)soap_malloc(soap, sizeof(void*)); + if (!q) + return NULL; + *p = q; + p = q; + k--; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Descending one level...\n")); + } + q = (void**)ip->link; + ip->link = p; + *p = (void*)q; + } + return p; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIDREF +#ifndef PALM_2 +SOAP_FMAC1 +void* +SOAP_FMAC2 +soap_id_forward(struct soap *soap, const char *href, void *p, size_t len, int st, int tt, size_t n, unsigned int k, void (*fcopy)(struct soap*, int, int, void*, size_t, const void*, size_t)) +{ struct soap_ilist *ip; + if (!p || !href || !*href) + return p; + ip = soap_lookup(soap, href); /* lookup pointer to hash table entry for string id */ + if (!ip) + { if (!(ip = soap_enter(soap, href))) /* new hash table entry for string id */ + return NULL; + ip->type = st; + ip->size = n; + ip->link = NULL; + ip->copy = NULL; + ip->ptr = NULL; + ip->level = 0; + ip->flist = NULL; + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "New entry href='%s' type=%d size=%lu level=%d location=%p\n", href, st, (unsigned long)n, k, p)); + } + else if (ip->type != st || (ip->level == k && ip->size != n)) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Type incompatibility id='%s' expect type=%d size=%lu level=%u got type=%d size=%lu\n", href, ip->type, (unsigned long)ip->size, k, st, (unsigned long)n)); + strcpy(soap->id, href); + soap->error = SOAP_HREF; + return NULL; + } + if (fcopy || n < sizeof(void*) || *href != '#') + { register struct soap_flist *fp = (struct soap_flist*)SOAP_MALLOC(soap, sizeof(struct soap_flist)); + if (!fp) + { soap->error = SOAP_EOM; + return NULL; + } + fp->next = ip->flist; + fp->type = tt; + fp->ptr = p; + fp->level = k; + fp->len = len; + if (fcopy) + fp->fcopy = fcopy; + else + fp->fcopy = soap_fcopy; + ip->flist = fp; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Forwarding type=%d (target type=%d) size=%lu location=%p level=%u len=%lu href='%s'\n", st, tt, (unsigned long)n, p, k, (unsigned long)len, href)); + } + else + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Forwarding copying address %p for type=%d href='%s'\n", p, st, href)); + *(void**)p = ip->copy; + ip->copy = p; + } + return p; +} +#endif +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +void* +SOAP_FMAC2 +soap_id_enter(struct soap *soap, const char *id, void *p, int t, size_t n, unsigned int k, const char *type, const char *arrayType, void *(*finstantiate)(struct soap*, int, const char*, const char*, size_t*)) +{ +#ifndef WITH_NOIDREF + struct soap_ilist *ip; +#endif + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Enter id='%s' type=%d loc=%p size=%lu level=%u\n", id, t, p, (unsigned long)n, k)); + soap->alloced = 0; + if (!p) + { if (finstantiate) + p = finstantiate(soap, t, type, arrayType, &n); + else + p = soap_malloc(soap, n); + if (p) + soap->alloced = 1; + } +#ifndef WITH_NOIDREF + if (!id || !*id) +#endif + return p; +#ifndef WITH_NOIDREF + ip = soap_lookup(soap, id); /* lookup pointer to hash table entry for string id */ + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Lookup entry id='%s for location=%p'\n", id, p)); + if (!ip) + { if (!(ip = soap_enter(soap, id))) /* new hash table entry for string id */ + return NULL; + ip->type = t; + ip->link = NULL; + ip->copy = NULL; + ip->flist = NULL; + ip->size = n; + ip->ptr = p; + ip->level = k; + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "New entry id='%s' type=%d size=%lu level=%u location=%p\n", id, t, (unsigned long)n, k, p)); + } + else if ((ip->type != t || (ip->level == k && ip->size != n)) && (ip->copy || ip->flist)) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Type incompatibility id='%s' expect type=%d size=%lu level=%u got type=%d size=%lu\n", id, ip->type, (unsigned long)ip->size, k, t, (unsigned long)n)); + strcpy(soap->id, id); + soap->error = SOAP_HREF; + return NULL; + } + else if (ip->ptr) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Multiply defined id='%s'\n", id)); + strcpy(soap->id, id); + soap->error = SOAP_DUPLICATE_ID; + return NULL; + } + else + { ip->size = n; + ip->ptr = p; + ip->level = k; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Update entry id='%s' type=%d location=%p size=%lu level=%u\n", id, t, p, (unsigned long)n, k)); + } + return ip->ptr; +#endif +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_fcopy(struct soap *soap, int st, int tt, void *p, size_t len, const void *q, size_t n) +{ DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Copying data type=%d (target type=%d) %p -> %p (%lu bytes)\n", st, tt, q, p, (unsigned long)n)); + memcpy(p, q, n); +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_end_send(struct soap *soap) +{ +#ifndef WITH_LEANER + if (soap->dime.list) + { /* SOAP body referenced attachments must appear first */ + soap->dime.last->next = soap->dime.first; + soap->dime.first = soap->dime.list->next; + soap->dime.list->next = NULL; + soap->dime.last = soap->dime.list; + } + if (soap_putdime(soap) || soap_putmime(soap)) + return soap->error; + soap->mime.list = NULL; + soap->mime.first = NULL; + soap->mime.last = NULL; + soap->dime.list = NULL; + soap->dime.first = NULL; + soap->dime.last = NULL; +#endif + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "End send\n")); + if (soap->mode & SOAP_IO) /* need to flush the remaining data in buffer */ + { if (soap_flush(soap)) +#ifdef WITH_ZLIB + { if (soap->mode & SOAP_ENC_ZLIB && soap->zlib_state == SOAP_ZLIB_DEFLATE) + { soap->zlib_state = SOAP_ZLIB_NONE; + deflateEnd(soap->d_stream); + } + return soap->error; + } +#else + return soap->error; +#endif +#ifdef WITH_ZLIB + if (soap->mode & SOAP_ENC_ZLIB) + { int r; + soap->d_stream->avail_in = 0; + do + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Deflating remainder\n")); + r = deflate(soap->d_stream, Z_FINISH); + if (soap->d_stream->avail_out != SOAP_BUFLEN) + { if (soap_flush_raw(soap, soap->z_buf, SOAP_BUFLEN - soap->d_stream->avail_out)) + { soap->zlib_state = SOAP_ZLIB_NONE; + deflateEnd(soap->d_stream); + return soap->error; + } + soap->d_stream->next_out = (Byte*)soap->z_buf; + soap->d_stream->avail_out = SOAP_BUFLEN; + } + } while (r == Z_OK); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Deflated total %lu->%lu bytes\n", soap->d_stream->total_in, soap->d_stream->total_out)); + soap->z_ratio_out = (float)soap->d_stream->total_out / (float)soap->d_stream->total_in; + soap->mode &= ~SOAP_ENC_ZLIB; + soap->zlib_state = SOAP_ZLIB_NONE; + if (deflateEnd(soap->d_stream) != Z_OK || r != Z_STREAM_END) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unable to end deflate: %s\n", soap->d_stream->msg?soap->d_stream->msg:SOAP_STR_EOS)); + return soap->error = SOAP_ZLIB_ERROR; + } +#ifdef WITH_GZIP + if (soap->zlib_out != SOAP_ZLIB_DEFLATE) + { soap->z_buf[0] = soap->z_crc & 0xFF; + soap->z_buf[1] = (soap->z_crc >> 8) & 0xFF; + soap->z_buf[2] = (soap->z_crc >> 16) & 0xFF; + soap->z_buf[3] = (soap->z_crc >> 24) & 0xFF; + soap->z_buf[4] = soap->d_stream->total_in & 0xFF; + soap->z_buf[5] = (soap->d_stream->total_in >> 8) & 0xFF; + soap->z_buf[6] = (soap->d_stream->total_in >> 16) & 0xFF; + soap->z_buf[7] = (soap->d_stream->total_in >> 24) & 0xFF; + if (soap_flush_raw(soap, soap->z_buf, 8)) + return soap->error; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "gzip crc32=%lu\n", (unsigned long)soap->z_crc)); + } +#endif + } +#endif + if ((soap->mode & SOAP_IO) == SOAP_IO_STORE) + { char *p; +#ifndef WITH_NOHTTP + if (!(soap->mode & SOAP_ENC_XML)) + { soap->mode--; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Sending buffered message of length %u\n", (unsigned int)soap->blist->size)); + if (soap->status >= SOAP_POST) + soap->error = soap->fpost(soap, soap->endpoint, soap->host, soap->port, soap->path, soap->action, soap->blist->size); + else if (soap->status != SOAP_STOP) + soap->error = soap->fresponse(soap, soap->status, soap->blist->size); + if (soap->error || soap_flush(soap)) + return soap->error; + soap->mode++; + } +#endif + for (p = soap_first_block(soap, NULL); p; p = soap_next_block(soap, NULL)) + { DBGMSG(SENT, p, soap_block_size(soap, NULL)); + if ((soap->error = soap->fsend(soap, p, soap_block_size(soap, NULL)))) + { soap_end_block(soap, NULL); + return soap->error; + } + } + soap_end_block(soap, NULL); + } +#ifndef WITH_LEANER + else if ((soap->mode & SOAP_IO) == SOAP_IO_CHUNK) + { DBGMSG(SENT, "\r\n0\r\n\r\n", 7); + if ((soap->error = soap->fsend(soap, "\r\n0\r\n\r\n", 7))) + return soap->error; + } +#endif + } +#ifdef WITH_TCPFIN +#ifdef WITH_OPENSSL + if (!soap->ssl && soap_valid_socket(soap->socket) && !soap->keep_alive && !(soap->omode & SOAP_IO_UDP)) + soap->fshutdownsocket(soap, soap->socket, 1); /* Send TCP FIN */ +#else + if (soap_valid_socket(soap->socket) && !soap->keep_alive && !(soap->omode & SOAP_IO_UDP)) + soap->fshutdownsocket(soap, soap->socket, 1); /* Send TCP FIN */ +#endif +#endif + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "End of send phase\n")); + soap->omode &= ~SOAP_XML_SEC; + soap->count = 0; + soap->part = SOAP_END; + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_end_recv(struct soap *soap) +{ soap->part = SOAP_END; +#ifndef WITH_LEANER + if ((soap->mode & SOAP_ENC_DIME) && soap_getdime(soap)) + { soap->dime.first = NULL; + soap->dime.last = NULL; + return soap->error; + } + soap->dime.list = soap->dime.first; + soap->dime.first = NULL; + soap->dime.last = NULL; + /* Check if MIME attachments and mime-post-check flag is set, if set call soap_resolve() and return */ + if (soap->mode & SOAP_ENC_MIME) + { +#ifndef WITH_NOIDREF + if (soap->mode & SOAP_MIME_POSTCHECK) + { soap_resolve(soap); + return SOAP_OK; + } +#endif + if (soap_getmime(soap)) + return soap->error; + } + soap->mime.list = soap->mime.first; + soap->mime.first = NULL; + soap->mime.last = NULL; + soap->mime.boundary = NULL; + if (soap->xlist) + { struct soap_multipart *content; + for (content = soap->mime.list; content; content = content->next) + soap_resolve_attachment(soap, content); + } +#endif + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "End of receive message ok\n")); +#ifdef WITH_ZLIB + if (soap->mode & SOAP_ENC_ZLIB) + { /* Make sure end of compressed content is reached */ + while (soap->d_stream->next_out != Z_NULL) + if ((int)soap_get1(soap) == EOF) + break; + soap->mode &= ~SOAP_ENC_ZLIB; + memcpy(soap->buf, soap->z_buf, SOAP_BUFLEN); + soap->bufidx = (char*)soap->d_stream->next_in - soap->z_buf; + soap->buflen = soap->z_buflen; + soap->zlib_state = SOAP_ZLIB_NONE; + if (inflateEnd(soap->d_stream) != Z_OK) + return soap->error = SOAP_ZLIB_ERROR; + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Inflate end ok\n")); +#ifdef WITH_GZIP + if (soap->zlib_in == SOAP_ZLIB_GZIP) + { soap_wchar c; + short i; + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Inflate gzip crc check\n")); + for (i = 0; i < 8; i++) + { if ((int)(c = soap_get1(soap)) == EOF) + return soap->error = SOAP_EOF; + soap->z_buf[i] = (char)c; + } + if (soap->z_crc != ((uLong)(unsigned char)soap->z_buf[0] | ((uLong)(unsigned char)soap->z_buf[1] << 8) | ((uLong)(unsigned char)soap->z_buf[2] << 16) | ((uLong)(unsigned char)soap->z_buf[3] << 24))) + { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Gzip error: crc check failed, message corrupted? (crc32=%lu)\n", (unsigned long)soap->z_crc)); + return soap->error = SOAP_ZLIB_ERROR; + } + if (soap->d_stream->total_out != ((uLong)(unsigned char)soap->z_buf[4] | ((uLong)(unsigned char)soap->z_buf[5] << 8) | ((uLong)(unsigned char)soap->z_buf[6] << 16) | ((uLong)(unsigned char)soap->z_buf[7] << 24))) + { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Gzip error: incorrect message length\n")); + return soap->error = SOAP_ZLIB_ERROR; + } + } + soap->zlib_in = SOAP_ZLIB_NONE; +#endif + } +#endif + if ((soap->mode & SOAP_IO) == SOAP_IO_CHUNK) + while ((int)soap_getchar(soap) != EOF) /* advance to last chunk */ + ; + if (soap->fdisconnect && (soap->error = soap->fdisconnect(soap))) + return soap->error; +#ifndef WITH_NOIDREF + if (soap_resolve(soap)) + return soap->error; +#endif +#ifndef WITH_LEANER + if (soap->xlist) + { if (soap->mode & SOAP_ENC_MTOM) + return soap->error = SOAP_MIME_HREF; + return soap->error = SOAP_DIME_HREF; + } +#endif + soap_free_ns(soap); + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_free_temp(struct soap *soap) +{ register struct soap_attribute *tp, *tq; + register struct Namespace *ns; + soap_free_ns(soap); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Free any remaining temp blocks\n")); + while (soap->blist) + soap_end_block(soap, NULL); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Free attribute storage\n")); + for (tp = soap->attributes; tp; tp = tq) + { tq = tp->next; + if (tp->value) + SOAP_FREE(soap, tp->value); + SOAP_FREE(soap, tp); + } + soap->attributes = NULL; +#ifdef WITH_FAST + if (soap->labbuf) + SOAP_FREE(soap, soap->labbuf); + soap->labbuf = NULL; + soap->lablen = 0; + soap->labidx = 0; +#endif + ns = soap->local_namespaces; + if (ns) + { for (; ns->id; ns++) + { if (ns->out) + { if (soap->encodingStyle == ns->out) + soap->encodingStyle = SOAP_STR_EOS; + SOAP_FREE(soap, ns->out); + ns->out = NULL; + } + if (soap->encodingStyle == ns->ns) + soap->encodingStyle = SOAP_STR_EOS; + } + SOAP_FREE(soap, soap->local_namespaces); + soap->local_namespaces = NULL; + } +#ifndef WITH_LEANER + while (soap->xlist) + { struct soap_xlist *xp = soap->xlist->next; + SOAP_FREE(soap, soap->xlist); + soap->xlist = xp; + } +#endif +#ifndef WITH_NOIDREF + soap_free_pht(soap); + soap_free_iht(soap); +#endif +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +static void +soap_free_ns(struct soap *soap) +{ register struct soap_nlist *np, *nq; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Free namespace stack\n")); + for (np = soap->nlist; np; np = nq) + { nq = np->next; + SOAP_FREE(soap, np); + } + soap->nlist = NULL; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +#if !defined(WITH_LEAN) || defined(SOAP_DEBUG) +static void +soap_init_logs(struct soap *soap) +{ int i; + for (i = 0; i < SOAP_MAXLOGS; i++) + { soap->logfile[i] = NULL; + soap->fdebug[i] = NULL; + } +} +#endif +#endif + +/******************************************************************************/ +#if !defined(WITH_LEAN) || defined(SOAP_DEBUG) +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_open_logfile(struct soap *soap, int i) +{ if (soap->logfile[i]) + soap->fdebug[i] = fopen(soap->logfile[i], i < 2 ? "ab" : "a"); +} +#endif + +/******************************************************************************/ +#ifdef SOAP_DEBUG +static void +soap_close_logfile(struct soap *soap, int i) +{ if (soap->fdebug[i]) + { fclose(soap->fdebug[i]); + soap->fdebug[i] = NULL; + } +} +#endif + +/******************************************************************************/ +#ifdef SOAP_DEBUG +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_close_logfiles(struct soap *soap) +{ int i; + for (i = 0; i < SOAP_MAXLOGS; i++) + soap_close_logfile(soap, i); +} +#endif + +/******************************************************************************/ +#ifdef SOAP_DEBUG +static void +soap_set_logfile(struct soap *soap, int i, const char *logfile) +{ const char *s; + char *t = NULL; + soap_close_logfile(soap, i); + s = soap->logfile[i]; + soap->logfile[i] = logfile; + if (s) + SOAP_FREE(soap, (void*)s); + if (logfile) + if ((t = (char*)SOAP_MALLOC(soap, strlen(logfile) + 1))) + strcpy(t, logfile); + soap->logfile[i] = t; +} +#endif + +/******************************************************************************/ +#ifdef SOAP_DEBUG +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_set_recv_logfile(struct soap *soap, const char *logfile) +{ soap_set_logfile(soap, SOAP_INDEX_RECV, logfile); +} +#endif + +/******************************************************************************/ +#ifdef SOAP_DEBUG +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_set_sent_logfile(struct soap *soap, const char *logfile) +{ soap_set_logfile(soap, SOAP_INDEX_SENT, logfile); +} +#endif + +/******************************************************************************/ +#ifdef SOAP_DEBUG +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_set_test_logfile(struct soap *soap, const char *logfile) +{ soap_set_logfile(soap, SOAP_INDEX_TEST, logfile); +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +struct soap* +SOAP_FMAC2 +soap_copy(const struct soap *soap) +{ return soap_copy_context((struct soap*)malloc(sizeof(struct soap)), soap); +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +struct soap* +SOAP_FMAC2 +soap_copy_context(struct soap *copy, const struct soap *soap) +{ if (soap_check_state(soap)) + return NULL; + if (copy) + { register struct soap_plugin *p = NULL; +#ifdef __cplusplus + *copy = *soap; +#else + memcpy(copy, soap, sizeof(struct soap)); +#endif + copy->state = SOAP_COPY; + copy->error = SOAP_OK; + copy->userid = NULL; + copy->passwd = NULL; + copy->nlist = NULL; + copy->blist = NULL; + copy->clist = NULL; + copy->alist = NULL; + copy->attributes = NULL; + copy->labbuf = NULL; + copy->lablen = 0; + copy->labidx = 0; +#ifdef SOAP_MEM_DEBUG + soap_init_mht(copy); +#endif +#if !defined(WITH_LEAN) || defined(SOAP_DEBUG) + soap_init_logs(copy); +#endif +#ifdef SOAP_DEBUG + soap_set_test_logfile(copy, soap->logfile[SOAP_INDEX_TEST]); + soap_set_sent_logfile(copy, soap->logfile[SOAP_INDEX_SENT]); + soap_set_recv_logfile(copy, soap->logfile[SOAP_INDEX_RECV]); +#endif +#ifdef WITH_C_LOCALE + copy->c_locale = duplocale(soap->c_locale); +#else + copy->c_locale = NULL; +#endif +#ifdef WITH_OPENSSL + copy->bio = NULL; + copy->ssl = NULL; + copy->session = NULL; +#endif +#ifdef WITH_ZLIB + copy->d_stream = (z_stream*)SOAP_MALLOC(copy, sizeof(z_stream)); + copy->d_stream->zalloc = Z_NULL; + copy->d_stream->zfree = Z_NULL; + copy->d_stream->opaque = Z_NULL; + copy->z_buf = NULL; +#endif + copy->local_namespaces = NULL; +#ifndef WITH_NOIDREF + soap_init_iht(copy); + soap_init_pht(copy); +#endif + copy->header = NULL; + copy->fault = NULL; + copy->action = NULL; +#ifndef WITH_LEAN +#ifdef WITH_COOKIES + copy->cookies = soap_copy_cookies(copy, soap); +#else + copy->cookies = NULL; +#endif +#endif + copy->plugins = NULL; + for (p = soap->plugins; p; p = p->next) + { register struct soap_plugin *q = (struct soap_plugin*)SOAP_MALLOC(copy, sizeof(struct soap_plugin)); + if (!q) + return NULL; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copying plugin '%s'\n", p->id)); + *q = *p; + if (p->fcopy && p->fcopy(copy, q, p)) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not copy plugin '%s'\n", p->id)); + SOAP_FREE(copy, q); + return NULL; + } + q->next = copy->plugins; + copy->plugins = q; + } + } + return copy; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_copy_stream(struct soap *copy, struct soap *soap) +{ copy->mode = soap->mode; + copy->imode = soap->imode; + copy->omode = soap->omode; + copy->socket = soap->socket; + copy->recv_timeout = soap->recv_timeout; + copy->send_timeout = soap->send_timeout; +#if defined(__cplusplus) && !defined(WITH_LEAN) + copy->os = soap->os; + copy->is = soap->is; +#endif + copy->sendfd = soap->sendfd; + copy->recvfd = soap->recvfd; + copy->bufidx = soap->bufidx; + copy->buflen = soap->buflen; + copy->ahead = soap->ahead; + copy->cdata = soap->cdata; + copy->chunksize = soap->chunksize; + copy->chunkbuflen = soap->chunkbuflen; + copy->keep_alive = soap->keep_alive; + copy->tcp_keep_alive = soap->tcp_keep_alive; + copy->tcp_keep_idle = soap->tcp_keep_idle; + copy->tcp_keep_intvl = soap->tcp_keep_intvl; + copy->tcp_keep_cnt = soap->tcp_keep_cnt; + copy->max_keep_alive = soap->max_keep_alive; +#ifndef WITH_NOIO + copy->peer = soap->peer; + copy->peerlen = soap->peerlen; +#endif +#ifdef WITH_OPENSSL + copy->bio = soap->bio; + copy->ssl = soap->ssl; + copy->ctx = soap->ctx; +#endif +#ifdef WITH_ZLIB + copy->zlib_state = soap->zlib_state; + copy->zlib_in = soap->zlib_in; + copy->zlib_out = soap->zlib_out; + copy->d_stream = (z_stream*)SOAP_MALLOC(copy, sizeof(z_stream)); + memcpy(copy->d_stream, soap->d_stream, sizeof(z_stream)); + copy->z_crc = soap->z_crc; + copy->z_ratio_in = soap->z_ratio_in; + copy->z_ratio_out = soap->z_ratio_out; + copy->z_buf = NULL; + copy->z_buflen = soap->z_buflen; + copy->z_level = soap->z_level; + if (soap->z_buf && soap->zlib_state != SOAP_ZLIB_NONE) + { copy->z_buf = (char*)SOAP_MALLOC(copy, SOAP_BUFLEN); + memcpy(copy->z_buf, soap->z_buf, sizeof(soap->z_buf)); + } + copy->z_dict = soap->z_dict; + copy->z_dict_len = soap->z_dict_len; +#endif + memcpy(copy->buf, soap->buf, sizeof(soap->buf)); +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_init(struct soap *soap) +{ soap->state = SOAP_INIT; +#ifdef SOAP_MEM_DEBUG + soap_init_mht(soap); +#endif +#if !defined(WITH_LEAN) || defined(SOAP_DEBUG) + soap_init_logs(soap); +#endif +#ifdef SOAP_DEBUG + soap_set_test_logfile(soap, "TEST.log"); + soap_set_sent_logfile(soap, "SENT.log"); + soap_set_recv_logfile(soap, "RECV.log"); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Initializing context\n")); +#endif + soap->version = 0; + soap_imode(soap, SOAP_IO_DEFAULT); + soap_omode(soap, SOAP_IO_DEFAULT); + soap->plugins = NULL; + soap->user = NULL; + soap->userid = NULL; + soap->passwd = NULL; +#ifndef WITH_NOHTTP + soap->fpost = http_post; + soap->fget = http_get; + soap->fput = http_405; + soap->fdel = http_405; + soap->fhead = http_405; + soap->fform = NULL; + soap->fposthdr = http_post_header; + soap->fresponse = http_response; + soap->fparse = http_parse; + soap->fparsehdr = http_parse_header; +#endif + soap->fheader = NULL; + soap->fconnect = NULL; + soap->fdisconnect = NULL; +#ifndef WITH_NOIO + soap->ipv6_multicast_if = 0; + soap->ipv4_multicast_if = NULL; +#ifndef WITH_IPV6 + soap->fresolve = tcp_gethost; +#else + soap->fresolve = NULL; +#endif + soap->faccept = tcp_accept; + soap->fopen = tcp_connect; + soap->fclose = tcp_disconnect; + soap->fclosesocket = tcp_closesocket; + soap->fshutdownsocket = tcp_shutdownsocket; + soap->fsend = fsend; + soap->frecv = frecv; + soap->fpoll = soap_poll; +#else + soap->fopen = NULL; + soap->fclose = NULL; + soap->fpoll = NULL; +#endif + soap->fseterror = NULL; + soap->fignore = NULL; + soap->fserveloop = NULL; + soap->fplugin = fplugin; + soap->fmalloc = NULL; +#ifndef WITH_LEANER + soap->fprepareinit = NULL; + soap->fpreparesend = NULL; + soap->fpreparerecv = NULL; + soap->fpreparefinal = NULL; + soap->fdimereadopen = NULL; + soap->fdimewriteopen = NULL; + soap->fdimereadclose = NULL; + soap->fdimewriteclose = NULL; + soap->fdimeread = NULL; + soap->fdimewrite = NULL; + soap->fmimereadopen = NULL; + soap->fmimewriteopen = NULL; + soap->fmimereadclose = NULL; + soap->fmimewriteclose = NULL; + soap->fmimeread = NULL; + soap->fmimewrite = NULL; +#endif + soap->float_format = "%.9G"; /* Alternative: use "%G" */ + soap->double_format = "%.17lG"; /* Alternative: use "%lG" */ + soap->dime_id_format = "cid:id%d"; /* default DIME id format */ + soap->http_version = "1.1"; + soap->proxy_http_version = "1.0"; + soap->http_content = NULL; + soap->actor = NULL; + soap->lang = "en"; + soap->keep_alive = 0; + soap->tcp_keep_alive = 0; + soap->tcp_keep_idle = 0; + soap->tcp_keep_intvl = 0; + soap->tcp_keep_cnt = 0; + soap->max_keep_alive = SOAP_MAXKEEPALIVE; + soap->recv_timeout = 0; + soap->send_timeout = 0; + soap->connect_timeout = 0; + soap->accept_timeout = 0; + soap->socket_flags = 0; + soap->connect_flags = 0; + soap->bind_flags = 0; + soap->accept_flags = 0; + soap->linger_time = 0; + soap->ip = 0; + soap->labbuf = NULL; + soap->lablen = 0; + soap->labidx = 0; + soap->encodingStyle = SOAP_STR_EOS; +#ifndef WITH_NONAMESPACES + soap->namespaces = namespaces; +#else + soap->namespaces = NULL; +#endif + soap->local_namespaces = NULL; + soap->nlist = NULL; + soap->blist = NULL; + soap->clist = NULL; + soap->alist = NULL; + soap->attributes = NULL; + soap->header = NULL; + soap->fault = NULL; + soap->master = SOAP_INVALID_SOCKET; + soap->socket = SOAP_INVALID_SOCKET; + soap->os = NULL; + soap->is = NULL; +#ifndef WITH_LEANER + soap->dom = NULL; + soap->dime.list = NULL; + soap->dime.first = NULL; + soap->dime.last = NULL; + soap->mime.list = NULL; + soap->mime.first = NULL; + soap->mime.last = NULL; + soap->mime.boundary = NULL; + soap->mime.start = NULL; + soap->xlist = NULL; +#endif +#ifndef UNDER_CE + soap->recvfd = 0; + soap->sendfd = 1; +#else + soap->recvfd = stdin; + soap->sendfd = stdout; +#endif + soap->host[0] = '\0'; + soap->port = 0; + soap->action = NULL; + soap->proxy_host = NULL; + soap->proxy_port = 8080; + soap->proxy_userid = NULL; + soap->proxy_passwd = NULL; + soap->authrealm = NULL; + soap->prolog = NULL; +#ifdef WITH_ZLIB + soap->zlib_state = SOAP_ZLIB_NONE; + soap->zlib_in = SOAP_ZLIB_NONE; + soap->zlib_out = SOAP_ZLIB_NONE; + soap->d_stream = (z_stream*)SOAP_MALLOC(soap, sizeof(z_stream)); + soap->d_stream->zalloc = Z_NULL; + soap->d_stream->zfree = Z_NULL; + soap->d_stream->opaque = Z_NULL; + soap->z_buf = NULL; + soap->z_level = 6; + soap->z_dict = NULL; + soap->z_dict_len = 0; +#endif +#ifndef WITH_LEAN + soap->c14ninclude = NULL; + soap->c14nexclude = NULL; + soap->cookies = NULL; + soap->cookie_domain = NULL; + soap->cookie_path = NULL; + soap->cookie_max = 32; +#endif +#ifdef WMW_RPM_IO + soap->rpmreqid = NULL; +#endif +#ifdef PALM + palmNetLibOpen(); +#endif +#ifndef WITH_NOIDREF + soap_init_iht(soap); + soap_init_pht(soap); +#endif +#ifdef WITH_OPENSSL + if (!soap_ssl_init_done) + { soap_ssl_init(); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Initializing OpenSSL, version=%ld\n", (long)OPENSSL_VERSION_NUMBER)); + } + soap->fsslauth = ssl_auth_init; + soap->fsslverify = ssl_verify_callback; + soap->bio = NULL; + soap->ssl = NULL; + soap->ctx = NULL; + soap->ssl_flags = SOAP_SSL_DEFAULT; + soap->keyfile = NULL; + soap->password = NULL; + soap->dhfile = NULL; + soap->cafile = NULL; + soap->capath = NULL; + soap->crlfile = NULL; + soap->randfile = NULL; + soap->session = NULL; +#endif +#ifdef WITH_C_LOCALE + soap->c_locale = newlocale(LC_ALL_MASK, "C", NULL); +#else + soap->c_locale = NULL; +#endif + soap_begin(soap); +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_init1(struct soap *soap, soap_mode mode) +{ soap_init2(soap, mode, mode); +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_init2(struct soap *soap, soap_mode imode, soap_mode omode) +{ soap_init(soap); + soap_imode(soap, imode); + soap_omode(soap, omode); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_begin(struct soap *soap) +{ DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Reinitializing context\n")); + if (!soap->keep_alive) + { soap->buflen = 0; + soap->bufidx = 0; + } + soap->keep_alive = (((soap->imode | soap->omode) & SOAP_IO_KEEPALIVE) != 0); + soap->null = 0; + soap->position = 0; + soap->encoding = 0; + soap->mustUnderstand = 0; + soap->mode = 0; + soap->ns = 0; + soap->part = SOAP_END; + soap->alloced = 0; + soap->count = 0; + soap->length = 0; + soap->cdata = 0; + soap->error = SOAP_OK; + soap->peeked = 0; + soap->ahead = 0; + soap->idnum = 0; + soap->level = 0; + soap->endpoint[0] = '\0'; +#ifndef WITH_LEANER + soap->dime.chunksize = 0; + soap->dime.buflen = 0; +#endif + soap_free_temp(soap); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_end(struct soap *soap) +{ if (soap_check_state(soap)) + return; + soap_free_temp(soap); + soap_dealloc(soap, NULL); + while (soap->clist) + { register struct soap_clist *cp = soap->clist->next; + SOAP_FREE(soap, soap->clist); + soap->clist = cp; + } + soap_closesock(soap); +#ifdef SOAP_DEBUG + soap_close_logfiles(soap); +#endif +#ifdef PALM + palmNetLibClose(); +#endif +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_set_namespaces(struct soap *soap, const struct Namespace *p) +{ register struct Namespace *ns = soap->local_namespaces; + register struct soap_nlist *np, *nq, *nr; + register unsigned int level = soap->level; + soap->namespaces = p; + soap->local_namespaces = NULL; + soap_set_local_namespaces(soap); + /* reverse the namespace list */ + np = soap->nlist; + soap->nlist = NULL; + if (np) + { nq = np->next; + np->next = NULL; + while (nq) + { nr = nq->next; + nq->next = np; + np = nq; + nq = nr; + } + } + /* then push on new stack */ + while (np) + { register const char *s; + soap->level = np->level; /* preserve element nesting level */ + s = np->ns; + if (!s && np->index >= 0 && ns) + { s = ns[np->index].out; + if (!s) + s = ns[np->index].ns; + } + if (s && soap_push_namespace(soap, np->id, s) == NULL) + return soap->error; + nq = np; + np = np->next; + SOAP_FREE(soap, nq); + } + if (ns) + { register int i; + for (i = 0; ns[i].id; i++) + { if (ns[i].out) + { SOAP_FREE(soap, ns[i].out); + ns[i].out = NULL; + } + } + SOAP_FREE(soap, ns); + } + soap->level = level; /* restore level */ + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_set_local_namespaces(struct soap *soap) +{ if (soap->namespaces && !soap->local_namespaces) + { register const struct Namespace *ns1; + register struct Namespace *ns2; + register size_t n = 1; + for (ns1 = soap->namespaces; ns1->id; ns1++) + n++; + n *= sizeof(struct Namespace); + ns2 = (struct Namespace*)SOAP_MALLOC(soap, n); + if (ns2) + { memcpy(ns2, soap->namespaces, n); + if (ns2[0].ns) + { if (!strcmp(ns2[0].ns, soap_env1)) + soap->version = 1; + else + soap->version = 2; + } + soap->local_namespaces = ns2; + } + } +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEAN +#ifndef PALM_1 +SOAP_FMAC1 +const char * +SOAP_FMAC2 +soap_strsearch(const char *big, const char *little) +{ register size_t n = strlen(little); + register const char *s = big; + while (s) + { if (!strncmp(s, little, n) && (s[n] == '\0' || s[n] == ' ')) + return s; + s = strchr(s, ' '); + if (s) + s++; + } + return NULL; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEAN +#ifndef PALM_1 +SOAP_FMAC1 +struct soap_nlist * +SOAP_FMAC2 +soap_lookup_ns(struct soap *soap, const char *tag, size_t n) +{ register struct soap_nlist *np; + for (np = soap->nlist; np; np = np->next) + { if (!strncmp(np->id, tag, n) && !np->id[n]) + return np; + } + return NULL; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEAN +static struct soap_nlist * +soap_push_ns(struct soap *soap, const char *id, const char *ns, short utilized) +{ register struct soap_nlist *np; + size_t n, k; + if (soap_strsearch(soap->c14nexclude, id)) + return NULL; + if (!utilized) + { for (np = soap->nlist; np; np = np->next) + { if (!strcmp(np->id, id) && (!np->ns || !strcmp(np->ns, ns))) + break; + } + if (np) + { if ((np->level < soap->level || !np->ns) && np->index == 1) + utilized = 1; + else + return NULL; + } + } + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Adding namespace binding (level=%u) '%s' '%s' utilized=%d\n", soap->level, id, ns?ns:"(null)", utilized)); + n = strlen(id); + if (ns) + k = strlen(ns); + else + k = 0; + np = (struct soap_nlist*)SOAP_MALLOC(soap, sizeof(struct soap_nlist) + n + k + 1); + if (!np) + { soap->error = SOAP_EOM; + return NULL; + } + np->next = soap->nlist; + soap->nlist = np; + strcpy(np->id, id); + if (ns) + np->ns = strcpy(np->id + n + 1, ns); + else + np->ns = NULL; + np->level = soap->level; + np->index = utilized; + return np; +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEAN +static void +soap_utilize_ns(struct soap *soap, const char *tag, size_t n) +{ register struct soap_nlist *np = soap_lookup_ns(soap, tag, n); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Utilizing namespace of '%s'\n", tag)); + if (np) + { if (np->index == 0) + soap_push_ns(soap, np->id, np->ns, 1); + } + else if (strncmp(tag, "xml", 3)) + { strncpy(soap->tmpbuf, tag, n); + soap->tmpbuf[n] = '\0'; + soap_push_ns(soap, soap->tmpbuf, NULL, 1); + } +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_element(struct soap *soap, const char *tag, int id, const char *type) +{ + register const char *s; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Element begin tag='%s' id='%d' type='%s'\n", tag, id, type?type:SOAP_STR_EOS)); +#ifdef WITH_DOM + if (soap->part == SOAP_BEGIN_SECURITY && (soap->mode & SOAP_XML_CANONICAL) && !(soap->mode & SOAP_DOM_ASIS)) + { register struct soap_nlist *np; + /* wsu:Id found: clear xmlns renderings, so re-emit them for exc-c14n */ + for (np = soap->nlist; np; np = np->next) + { if (np->index == 2) + np->index = 0; + } + } + if (soap->mode & SOAP_XML_DOM) + { register struct soap_dom_element *elt = (struct soap_dom_element*)soap_malloc(soap, sizeof(struct soap_dom_element)); + if (!elt) + return soap->error; + elt->soap = soap; + elt->next = NULL; + elt->prnt = soap->dom; + elt->name = soap_strdup(soap, tag); + elt->elts = NULL; + elt->atts = NULL; + elt->nstr = NULL; + elt->data = NULL; + elt->wide = NULL; + elt->node = NULL; + elt->type = 0; + elt->head = NULL; + elt->tail = NULL; + if (soap->dom) + { struct soap_dom_element *p = soap->dom->elts; + if (p) + { while (p->next) + p = p->next; + p->next = elt; + } + else + soap->dom->elts = elt; + } + soap->dom = elt; + } + else + { +#endif + soap->level++; +#ifndef WITH_LEAN + if (!soap->ns) + { if (!(soap->mode & SOAP_XML_CANONICAL) + && soap_send(soap, soap->prolog ? soap->prolog : "\n")) + return soap->error; + } + else if (soap->mode & SOAP_XML_INDENT) + { if (soap->ns == 1 && soap_send_raw(soap, soap_indent, soap->level < sizeof(soap_indent) ? soap->level : sizeof(soap_indent) - 1)) + return soap->error; + soap->body = 1; + } + if ((soap->mode & SOAP_XML_DEFAULTNS) && (s = strchr(tag, ':'))) + { struct Namespace *ns = soap->local_namespaces; + size_t n = s - tag; + if (soap_send_raw(soap, "<", 1) + || soap_send(soap, s + 1)) + return soap->error; + if (soap->nlist && !strncmp(soap->nlist->id, tag, n) && !soap->nlist->id[n]) + ns = NULL; + for (; ns && ns->id; ns++) + { if (*ns->id && (ns->out || ns->ns) && !strncmp(ns->id, tag, n) && !ns->id[n]) + { soap_push_ns(soap, ns->id, ns->out ? ns->out : ns->ns, 0); + if (soap_attribute(soap, "xmlns", ns->out ? ns->out : ns->ns)) + return soap->error; + break; + } + } + } + else +#endif + if (soap_send_raw(soap, "<", 1) + || soap_send(soap, tag)) + return soap->error; +#ifdef WITH_DOM + } +#endif + if (!soap->ns) + { struct Namespace *ns; + int k = -1; +#ifndef WITH_LEAN + if ((soap->mode & SOAP_XML_DEFAULTNS)) + k = 4; /* only produce the first four required entries */ +#endif + for (ns = soap->local_namespaces; ns && ns->id && k; ns++, k--) + { if (*ns->id && (ns->out || ns->ns)) + { sprintf(soap->tmpbuf, "xmlns:%s", ns->id); + if (soap_attribute(soap, soap->tmpbuf, ns->out ? ns->out : ns->ns)) + return soap->error; + } + } + } + soap->ns = 1; /* namespace table control: ns = 0 or 2 to start, then 1 to stop dumping the table */ +#ifndef WITH_LEAN + if (soap->mode & SOAP_XML_CANONICAL) + { const char *t = strchr(tag, ':'); + if (t) + soap_utilize_ns(soap, tag, t - tag); + } +#endif + if (id > 0) + { sprintf(soap->tmpbuf, "_%d", id); + if (soap_attribute(soap, "id", soap->tmpbuf)) + return soap->error; + } + if (type && *type && (!(soap->mode & SOAP_XML_SEC) || soap->part == SOAP_IN_BODY)) + { if (soap_attribute(soap, "xsi:type", type)) + return soap->error; +#ifndef WITH_LEAN + if (soap->mode & SOAP_XML_CANONICAL) + { const char *t = strchr(type, ':'); + if (t) + soap_utilize_ns(soap, type, t - type); + } +#endif + } + if (soap->null && soap->position > 0) + { register int i; + sprintf(soap->tmpbuf, "[%d", soap->positions[0]); + for (i = 1; i < soap->position; i++) + sprintf(soap->tmpbuf + strlen(soap->tmpbuf), ",%d", soap->positions[i]); + strcat(soap->tmpbuf, "]"); + if (soap_attribute(soap, "SOAP-ENC:position", soap->tmpbuf)) + return soap->error; + } + if (soap->mustUnderstand) + { if (soap->actor && *soap->actor) + { if (soap_attribute(soap, soap->version == 2 ? "SOAP-ENV:role" : "SOAP-ENV:actor", soap->actor)) + return soap->error; + } + if (soap_attribute(soap, "SOAP-ENV:mustUnderstand", soap->version == 2 ? "true" : "1")) + return soap->error; + soap->mustUnderstand = 0; + } + if (soap->encoding) + { if (soap->encodingStyle && soap->local_namespaces) + { if (!*soap->encodingStyle) + { if (soap->local_namespaces[1].out) + soap->encodingStyle = soap->local_namespaces[1].out; + else + soap->encodingStyle = soap->local_namespaces[1].ns; + } + if (soap->encodingStyle && soap_attribute(soap, "SOAP-ENV:encodingStyle", soap->encodingStyle)) + return soap->error; + } + soap->encoding = 0; + } + soap->null = 0; + soap->position = 0; + if (soap->part == SOAP_BEGIN_SECURITY && (soap->mode & SOAP_XML_CANONICAL)) + soap->part = SOAP_IN_SECURITY; + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_element_begin_out(struct soap *soap, const char *tag, int id, const char *type) +{ if (*tag == '-') + return SOAP_OK; + if (soap_element(soap, tag, id, type)) + return soap->error; + return soap_element_start_end_out(soap, NULL); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +#ifndef HAVE_STRRCHR +SOAP_FMAC1 +char* +SOAP_FMAC2 +soap_strrchr(const char *s, int t) +{ register char *r = NULL; + while (*s) + if (*s++ == t) + r = (char*)s - 1; + return r; +} +#endif +#endif + +/******************************************************************************/ +#ifndef PALM_2 +#ifndef HAVE_STRTOL +SOAP_FMAC1 +long +SOAP_FMAC2 +soap_strtol(const char *s, char **t, int b) +{ register long n = 0; + register int c; + while (*s > 0 && *s <= 32) + s++; + if (b == 10) + { short neg = 0; + if (*s == '-') + { s++; + neg = 1; + } + else if (*s == '+') + s++; + while ((c = *s) && c >= '0' && c <= '9') + { if (n >= 214748364 && (n > 214748364 || c >= '8')) + break; + n *= 10; + n += c - '0'; + s++; + } + if (neg) + n = -n; + } + else /* b == 16 and value is always positive */ + { while ((c = *s)) + { if (c >= '0' && c <= '9') + c -= '0'; + else if (c >= 'A' && c <= 'F') + c -= 'A' - 10; + else if (c >= 'a' && c <= 'f') + c -= 'a' - 10; + if (n > 0x07FFFFFF) + break; + n <<= 4; + n += c; + s++; + } + } + if (t) + *t = (char*)s; + return n; +} +#endif +#endif + +/******************************************************************************/ +#ifndef PALM_2 +#ifndef HAVE_STRTOUL +SOAP_FMAC1 +unsigned long +SOAP_FMAC2 +soap_strtoul(const char *s, char **t, int b) +{ unsigned long n = 0; + register int c; + while (*s > 0 && *s <= 32) + s++; + if (b == 10) + { if (*s == '+') + s++; + while ((c = *s) && c >= '0' && c <= '9') + { if (n >= 429496729 && (n > 429496729 || c >= '6')) + break; + n *= 10; + n += c - '0'; + s++; + } + } + else /* b == 16 */ + { while ((c = *s)) + { if (c >= '0' && c <= '9') + c -= '0'; + else if (c >= 'A' && c <= 'F') + c -= 'A' - 10; + else if (c >= 'a' && c <= 'f') + c -= 'a' - 10; + if (n > 0x0FFFFFFF) + break; + n <<= 4; + n += c; + s++; + } + } + if (t) + *t = (char*)s; + return n; +} +#endif +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_array_begin_out(struct soap *soap, const char *tag, int id, const char *type, const char *offset) +{ if (!type || !*type) + return soap_element_begin_out(soap, tag, id, NULL); + if (soap_element(soap, tag, id, "SOAP-ENC:Array")) + return soap->error; + if (soap->version == 2) + { const char *s; + s = soap_strrchr(type, '['); + if ((size_t)(s - type) < sizeof(soap->tmpbuf)) + { strncpy(soap->tmpbuf, type, s - type); + soap->tmpbuf[s - type] = '\0'; + if (soap_attribute(soap, "SOAP-ENC:itemType", soap->tmpbuf)) + return soap->error; + if (s && (soap_attribute(soap, "SOAP-ENC:arraySize", s + 1))) + return soap->error; + } + } + else + { if (offset && soap_attribute(soap, "SOAP-ENC:offset", offset)) + return soap->error; + if (soap_attribute(soap, "SOAP-ENC:arrayType", type)) + return soap->error; + } +#ifndef WITH_LEAN + if ((soap->mode & SOAP_XML_CANONICAL)) + { const char *s = strchr(type, ':'); + if (s) + soap_utilize_ns(soap, type, s - type); + } +#endif + return soap_element_start_end_out(soap, NULL); +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_element_start_end_out(struct soap *soap, const char *tag) +{ register struct soap_attribute *tp; +#ifndef WITH_LEAN + if (soap->mode & SOAP_XML_CANONICAL) + { struct soap_nlist *np; + for (tp = soap->attributes; tp; tp = tp->next) + { if (tp->visible && tp->name) + { const char *s = strchr(tp->name, ':'); + if (s) + soap_utilize_ns(soap, tp->name, s - tp->name); + } + } + for (np = soap->nlist; np; np = np->next) + { if (np->index == 1 && np->ns) + { sprintf(soap->tmpbuf, "xmlns:%s", np->id); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Enabling utilized binding (level=%u) %s='%s'\n", np->level, soap->tmpbuf, np->ns)); + soap_set_attr(soap, soap->tmpbuf, np->ns); + np->index = 2; + } + } + } +#endif +#ifdef WITH_DOM + if ((soap->mode & SOAP_XML_DOM) && soap->dom) + { register struct soap_dom_attribute **att; + att = &soap->dom->atts; + for (tp = soap->attributes; tp; tp = tp->next) + { if (tp->visible) + { *att = (struct soap_dom_attribute*)soap_malloc(soap, sizeof(struct soap_dom_attribute)); + if (!*att) + return soap->error; + (*att)->next = NULL; + (*att)->nstr = NULL; + (*att)->name = soap_strdup(soap, tp->name); + (*att)->data = soap_strdup(soap, tp->value); + (*att)->wide = NULL; + (*att)->soap = soap; + att = &(*att)->next; + tp->visible = 0; + } + } + return SOAP_OK; + } +#endif + for (tp = soap->attributes; tp; tp = tp->next) + { if (tp->visible) + { const char *s; +#ifndef WITH_LEAN + if ((soap->mode & SOAP_XML_DEFAULTNS) && (s = strchr(tp->name, ':'))) + { size_t n = s - tp->name; + if (soap->nlist && !strncmp(soap->nlist->id, tp->name, n) && !soap->nlist->id[n]) + s++; + else + s = tp->name; + if (soap_send(soap, " ") || soap_send(soap, s)) + return soap->error; + } + else +#endif + if (soap_send(soap, " ") || soap_send(soap, tp->name)) + return soap->error; + if (tp->visible == 2 && tp->value) + if (soap_send_raw(soap, "=\"", 2) + || soap_string_out(soap, tp->value, 1) + || soap_send_raw(soap, "\"", 1)) + return soap->error; + tp->visible = 0; + } + } + if (tag) + { +#ifndef WITH_LEAN + if (soap->mode & SOAP_XML_CANONICAL) + { if (soap_send_raw(soap, ">", 1) + || soap_element_end_out(soap, tag)) + return soap->error; + return SOAP_OK; + } +#endif + soap->level--; /* decrement level just before /> */ + if (soap_send_raw(soap, "/>", 2)) + return soap->error; + return SOAP_OK; + } + return soap_send_raw(soap, ">", 1); +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_element_end_out(struct soap *soap, const char *tag) +{ const char *s; + if (*tag == '-') + return SOAP_OK; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Element ending tag='%s'\n", tag)); +#ifdef WITH_DOM + if ((soap->mode & SOAP_XML_DOM) && soap->dom) + { if (soap->dom->prnt) + soap->dom = soap->dom->prnt; + return SOAP_OK; + } +#endif +#ifndef WITH_LEAN + if (soap->mode & SOAP_XML_CANONICAL) + soap_pop_namespace(soap); + if (soap->mode & SOAP_XML_INDENT) + { if (!soap->body) + { if (soap_send_raw(soap, soap_indent, soap->level < sizeof(soap_indent) ? soap->level : sizeof(soap_indent) - 1)) + return soap->error; + } + soap->body = 0; + } + if ((soap->mode & SOAP_XML_DEFAULTNS) && (s = strchr(tag, ':'))) + { soap_pop_namespace(soap); + tag = s + 1; + } +#endif + if (soap_send_raw(soap, "error; + soap->level--; /* decrement level just before > */ + return soap_send_raw(soap, ">", 1); +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_element_ref(struct soap *soap, const char *tag, int id, int href) +{ register int n = 0; + const char *s = "href"; + if (soap->version == 2) + { s = "SOAP-ENC:ref"; + n = 1; + } + sprintf(soap->href, "#_%d", href); + return soap_element_href(soap, tag, id, s, soap->href + n); +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_element_href(struct soap *soap, const char *tag, int id, const char *ref, const char *val) +{ DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Element '%s' reference %s='%s'\n", tag, ref, val)); + if (soap_element(soap, tag, id, NULL) + || soap_attribute(soap, ref, val) + || soap_element_start_end_out(soap, tag)) + return soap->error; + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_element_null(struct soap *soap, const char *tag, int id, const char *type) +{ struct soap_attribute *tp; + for (tp = soap->attributes; tp; tp = tp->next) + if (tp->visible) + break; + if (tp || (soap->version == 2 && soap->position > 0) || id > 0 || (soap->mode & SOAP_XML_NIL)) + { if (soap_element(soap, tag, id, type)) + return soap->error; + if (!tp && soap_attribute(soap, "xsi:nil", "true")) + return soap->error; + return soap_element_start_end_out(soap, tag); + } + soap->null = 1; + soap->position = 0; + soap->mustUnderstand = 0; + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_element_id(struct soap *soap, const char *tag, int id, const void *p, const struct soap_array *a, int n, const char *type, int t) +{ if (!p) + { soap_element_null(soap, tag, id, type); + return -1; + } +#ifndef WITH_NOIDREF + if (soap->mode & SOAP_XML_TREE) + return 0; + if (id < 0) + { struct soap_plist *pp; + if (a) + id = soap_array_pointer_lookup(soap, p, a, n, t, &pp); + else + id = soap_pointer_lookup(soap, p, t, &pp); + if (id) + { if (soap_is_embedded(soap, pp)) + { soap_element_ref(soap, tag, 0, id); + return -1; + } + if (soap_is_single(soap, pp)) + return 0; + soap_set_embedded(soap, pp); + } + } + return id; +#else + return 0; +#endif +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_element_result(struct soap *soap, const char *tag) +{ if (soap->version == 2 && soap->encodingStyle) + { if (soap_element(soap, "SOAP-RPC:result", 0, NULL) + || soap_attribute(soap, "xmlns:SOAP-RPC", soap_rpc) + || soap_element_start_end_out(soap, NULL) + || soap_string_out(soap, tag, 0) + || soap_element_end_out(soap, "SOAP-RPC:result")) + return soap->error; + } + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_check_result(struct soap *soap, const char *tag) +{ if (soap->version == 2 && soap->encodingStyle) + { soap_instring(soap, ":result", NULL, NULL, 0, 2, -1, -1); + /* just ignore content for compliance reasons, but should compare tag to element's QName value? */ + } +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_attribute(struct soap *soap, const char *name, const char *value) +{ + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Attribute '%s'='%s'\n", name, value)); +#ifdef WITH_DOM + if ((soap->mode & SOAP_XML_DOM) && !(soap->mode & SOAP_XML_CANONICAL) && soap->dom) + { register struct soap_dom_attribute *a = (struct soap_dom_attribute*)soap_malloc(soap, sizeof(struct soap_dom_attribute)); + if (!a) + return soap->error; + a->next = soap->dom->atts; + a->nstr = NULL; + a->name = soap_strdup(soap, name); + a->data = soap_strdup(soap, value); + a->wide = NULL; + a->soap = soap; + soap->dom->atts = a; + return SOAP_OK; + } +#endif +#ifndef WITH_LEAN + if (soap->mode & SOAP_XML_CANONICAL) + { /* TODO: consider using this code to handle default namespace bindings + if (!strncmp(name, "xmlns", 5) && (name[5] == ':' || name[5] == '\0')) + { if (name[5] == ':') + soap_push_ns(soap, name + 6, value, 0); + else + soap_push_ns(soap, "", value, 0); + } + */ + if (!strncmp(name, "xmlns:", 6)) + soap_push_ns(soap, name + 6, value, 0); + else if (soap_set_attr(soap, name, value)) + return soap->error; + } + else +#endif + { if (soap_send(soap, " ") || soap_send(soap, name)) + return soap->error; + if (value) + if (soap_send_raw(soap, "=\"", 2) + || soap_string_out(soap, value, 1) + || soap_send_raw(soap, "\"", 1)) + return soap->error; + } + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_element_begin_in(struct soap *soap, const char *tag, int nillable, const char *type) +{ if (!soap_peek_element(soap)) + { if (soap->other) + return soap->error = SOAP_TAG_MISMATCH; + if (tag && *tag == '-') + return SOAP_OK; + if (!(soap->error = soap_match_tag(soap, soap->tag, tag))) + { soap->peeked = 0; + if (type && *soap->type && soap_match_tag(soap, soap->type, type)) + return soap->error = SOAP_TYPE; + if (!nillable && soap->null && (soap->mode & SOAP_XML_STRICT)) + return soap->error = SOAP_NULL; + if (soap->body) + soap->level++; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Begin element found (level=%u) '%s'='%s'\n", soap->level, soap->tag, tag?tag:SOAP_STR_EOS )); + } + } + else if (soap->error == SOAP_NO_TAG && tag && *tag == '-') + soap->error = SOAP_OK; + return soap->error; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_element_end_in(struct soap *soap, const char *tag) +{ register soap_wchar c; + register char *s; + register int n = 0; + if (tag && *tag == '-') + return SOAP_OK; + if (soap->error == SOAP_NO_TAG) + soap->error = SOAP_OK; +#ifdef WITH_DOM + /* this whitespace or mixed content is not insignificant for DOM */ + if ((soap->mode & SOAP_XML_DOM) && soap->dom) + { if (!soap->peeked && !soap_string_in(soap, 3, -1, -1)) + return soap->error; + if (soap->dom->prnt) + soap->dom = soap->dom->prnt; + } +#endif + if (soap->peeked) + { if (*soap->tag) + n++; + soap->peeked = 0; + } + do + { while (((c = soap_get(soap)) != SOAP_TT)) + { if ((int)c == EOF) + return soap->error = SOAP_EOF; + if (c == SOAP_LT) + n++; + else if (c == '/') + { c = soap_get(soap); + if (c == SOAP_GT) + n--; + else + soap_unget(soap, c); + } + } + } while (n--); + s = soap->tag; + n = sizeof(soap->tag); + while (soap_notblank(c = soap_get(soap))) + { if (--n > 0) + *s++ = (char)c; + } + *s = '\0'; + if ((int)c == EOF) + return soap->error = SOAP_EOF; + while (soap_blank(c)) + c = soap_get(soap); + if (c != SOAP_GT) + return soap->error = SOAP_SYNTAX_ERROR; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "End element found (level=%u) '%s'='%s'\n", soap->level, soap->tag, tag?tag:SOAP_STR_EOS)); +#ifndef WITH_LEAN + if (tag && (soap->mode & SOAP_XML_STRICT)) + { soap_pop_namespace(soap); + if (soap_match_tag(soap, soap->tag, tag)) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "End element tag name does not match\n")); + return soap->error = SOAP_SYNTAX_ERROR; + } + } +#endif + soap->level--; + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +const char * +SOAP_FMAC2 +soap_attr_value(struct soap *soap, const char *name, int flag) +{ register struct soap_attribute *tp; + if (*name == '-') + return SOAP_STR_EOS; + for (tp = soap->attributes; tp; tp = tp->next) + { if (tp->visible && !soap_match_tag(soap, tp->name, name)) + break; + } + if (tp) + { if (flag == 2 && (soap->mode & SOAP_XML_STRICT)) + soap->error = SOAP_PROHIBITED; + else + return tp->value; + } + else if (flag == 1 && (soap->mode & SOAP_XML_STRICT)) + soap->error = SOAP_REQUIRED; + else + soap->error = SOAP_OK; + return NULL; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_set_attr(struct soap *soap, const char *name, const char *value) +{ register struct soap_attribute *tp; + if (*name == '-') + return SOAP_OK; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Set attribute %s='%s'\n", name, value?value:SOAP_STR_EOS)); + for (tp = soap->attributes; tp; tp = tp->next) + { if (!strcmp(tp->name, name)) + break; + } + if (!tp) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Allocate attribute %s\n", name)); + if (!(tp = (struct soap_attribute*)SOAP_MALLOC(soap, sizeof(struct soap_attribute) + strlen(name)))) + return soap->error = SOAP_EOM; + tp->ns = NULL; +#ifndef WITH_LEAN + if (soap->mode & SOAP_XML_CANONICAL) + { struct soap_attribute **tpp = &soap->attributes; + const char *s = strchr(name, ':'); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Inserting attribute %s for c14n\n", name)) + if (!strncmp(name, "xmlns", 5)) + { for (; *tpp; tpp = &(*tpp)->next) + if (strncmp((*tpp)->name, "xmlns", 5) || strcmp((*tpp)->name + 5, name + 5) > 0) + break; + } + else if (!s) + { for (; *tpp; tpp = &(*tpp)->next) + if (strncmp((*tpp)->name, "xmlns", 5) && ((*tpp)->ns || strcmp((*tpp)->name, name) > 0)) + break; + } + else + { int k; + for (; *tpp; tpp = &(*tpp)->next) + { if (!strncmp((*tpp)->name, "xmlns:", 6) && !strncmp((*tpp)->name + 6, name, s - name) && !(*tpp)->name[6 + s - name]) + { if (!tp->ns) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Canonicalization: prefix %s=%p (%s)\n", name, (*tpp)->ns, (*tpp)->ns)); + tp->ns = (*tpp)->ns; + } + } + else if (strncmp((*tpp)->name, "xmlns", 5) && (*tpp)->ns && tp->ns && ((k = strcmp((*tpp)->ns, tp->ns)) > 0 || (!k && strcmp((*tpp)->name, name) > 0))) + break; + } + } + tp->next = *tpp; + *tpp = tp; + } + else +#endif + { tp->next = soap->attributes; + soap->attributes = tp; + } + strcpy(tp->name, name); + tp->value = NULL; + } + else if (tp->visible) + { return SOAP_OK; + } + else if (value && tp->value && tp->size <= strlen(value)) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Free attribute value of %s (free %p)\n", name, tp->value)); + SOAP_FREE(soap, tp->value); + tp->value = NULL; + tp->ns = NULL; + } + if (value) + { if (!tp->value) + { tp->size = strlen(value) + 1; + if (!(tp->value = (char*)SOAP_MALLOC(soap, tp->size))) + return soap->error = SOAP_EOM; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Allocate attribute value for %s (%p)\n", tp->name, tp->value)); + } + strcpy(tp->value, value); + if (!strncmp(tp->name, "xmlns:", 6)) + tp->ns = tp->value; + tp->visible = 2; +#ifndef WITH_LEAN + if (!strcmp(name, "wsu:Id")) + { soap->part = SOAP_BEGIN_SECURITY; + strncpy(soap->id, value, sizeof(soap->id)); + soap->id[sizeof(soap->id)-1] = '\0'; + } +#endif + } + else + tp->visible = 1; + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_clr_attr(struct soap *soap) +{ register struct soap_attribute *tp; +#ifndef WITH_LEAN + if ((soap->mode & SOAP_XML_CANONICAL)) + { while (soap->attributes) + { tp = soap->attributes->next; + if (soap->attributes->value) + SOAP_FREE(soap, soap->attributes->value); + SOAP_FREE(soap, soap->attributes); + soap->attributes = tp; + } + } + else +#endif + { for (tp = soap->attributes; tp; tp = tp->next) + tp->visible = 0; + } +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +static int +soap_getattrval(struct soap *soap, char *s, size_t n, soap_wchar d) +{ register size_t i; + for (i = 0; i < n; i++) + { register soap_wchar c = soap_get(soap); + switch (c) + { + case SOAP_TT: + *s++ = '<'; + soap_unget(soap, '/'); + break; + case SOAP_LT: + *s++ = '<'; + break; + case SOAP_GT: + if (d == ' ') + { soap_unget(soap, c); + *s = '\0'; + return SOAP_OK; + } + *s++ = '>'; + break; + case SOAP_QT: + if (c == d) + { *s = '\0'; + return SOAP_OK; + } + *s++ = '"'; + break; + case SOAP_AP: + if (c == d) + { *s = '\0'; + return SOAP_OK; + } + *s++ = '\''; + break; + case '\t': + case '\n': + case '\r': + case ' ': + case '/': + if (d == ' ') + { soap_unget(soap, c); + *s = '\0'; + return SOAP_OK; + } + default: + if ((int)c == EOF) + return soap->error = SOAP_EOF; + *s++ = (char)c; + } + } + return soap->error = SOAP_EOM; +} +#endif + +/******************************************************************************/ +#ifdef WITH_FAST +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_store_lab(struct soap *soap, const char *s, size_t n) +{ soap->labidx = 0; + return soap_append_lab(soap, s, n); +} +#endif +#endif + +/******************************************************************************/ +#ifdef WITH_FAST +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_append_lab(struct soap *soap, const char *s, size_t n) +{ if (soap->labidx + n >= soap->lablen) + { register char *t = soap->labbuf; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Enlarging look-aside buffer to append data, old size=%lu", (unsigned long)soap->lablen)); + if (soap->lablen == 0) + soap->lablen = SOAP_LABLEN; + while (soap->labidx + n >= soap->lablen) + soap->lablen <<= 1; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, ", new size=%lu\n", (unsigned long)soap->lablen)); + soap->labbuf = (char*)SOAP_MALLOC(soap, soap->lablen); + if (!soap->labbuf) + { if (t) + SOAP_FREE(soap, t); + return soap->error = SOAP_EOM; + } + if (t) + { memcpy(soap->labbuf, t, soap->labidx); + SOAP_FREE(soap, t); + } + } + if (s) + { memcpy(soap->labbuf + soap->labidx, s, n); + soap->labidx += n; + } + return SOAP_OK; +} +#endif +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_peek_element(struct soap *soap) +{ +#ifdef WITH_DOM + register struct soap_dom_attribute **att = NULL; + register char *lead = NULL; +#endif + register struct soap_attribute *tp, *tq = NULL; + register const char *t; + register char *s; + register soap_wchar c; + register int i; + if (soap->peeked) + { if (!*soap->tag) + return soap->error = SOAP_NO_TAG; + return SOAP_OK; + } + soap->peeked = 1; + soap->id[0] = '\0'; + soap->href[0] = '\0'; + soap->type[0] = '\0'; + soap->arrayType[0] = '\0'; + soap->arraySize[0] = '\0'; + soap->arrayOffset[0] = '\0'; + soap->other = 0; + soap->root = -1; + soap->position = 0; + soap->null = 0; + soap->mustUnderstand = 0; + /* skip BOM */ + if ((c = soap_getchar(soap)) != 0xEF || (c = soap_get1(soap)) != 0xBB || (c = soap_get1(soap)) != 0xBF) + soap_unget(soap, c); + c = soap_get(soap); +#ifdef WITH_DOM + /* whitespace leading to start tag is not insignificant for DOM */ + if (soap_blank(c)) + { soap->labidx = 0; + do + { if (soap_append_lab(soap, NULL, 0)) + return soap->error; + s = soap->labbuf + soap->labidx; + i = soap->lablen - soap->labidx; + soap->labidx = soap->lablen; + while (soap_blank(c) && i--) + { *s++ = c; + c = soap_get(soap); + } + } + while (soap_blank(c)); + *s = '\0'; + if (*soap->labbuf) + lead = soap->labbuf; + } +#else + /* skip space */ + while (soap_blank(c)) + c = soap_get(soap); +#endif + if (c != SOAP_LT) + { *soap->tag = '\0'; + if ((int)c == EOF) + return soap->error = SOAP_EOF; + soap_unget(soap, c); +#ifdef WITH_DOM + /* whitespace leading to end tag is not insignificant for DOM */ + if ((soap->mode & SOAP_XML_DOM) && soap->dom) + soap->dom->tail = soap_strdup(soap, lead); +#endif + return soap->error = SOAP_NO_TAG; + } + s = soap->tag; + do c = soap_get1(soap); + while (soap_blank(c)); + i = sizeof(soap->tag); + while (c != '>' && c != '/' && soap_notblank(c) && (int)c != EOF) + { if (--i > 0) + *s++ = (char)c; + c = soap_get1(soap); + } + while (soap_blank(c)) + c = soap_get1(soap); + *s = '\0'; +#ifdef WITH_DOM + if (soap->mode & SOAP_XML_DOM) + { register struct soap_dom_element *elt; + elt = (struct soap_dom_element*)soap_malloc(soap, sizeof(struct soap_dom_element)); + if (!elt) + return soap->error; + elt->next = NULL; + elt->nstr = NULL; + elt->name = soap_strdup(soap, soap->tag); + elt->prnt = soap->dom; + elt->elts = NULL; + elt->atts = NULL; + elt->data = NULL; + elt->wide = NULL; + elt->type = 0; + elt->node = NULL; + elt->head = soap_strdup(soap, lead); + elt->tail = NULL; + elt->soap = soap; + if (soap->dom) + { struct soap_dom_element *p = soap->dom->elts; + if (p) + { while (p->next) + p = p->next; + p->next = elt; + } + else + soap->dom->elts = elt; + } + soap->dom = elt; + att = &elt->atts; + } +#endif + soap_pop_namespace(soap); + for (tp = soap->attributes; tp; tp = tp->next) + tp->visible = 0; + while ((int)c != EOF && c != '>' && c != '/') + { s = soap->tmpbuf; + i = sizeof(soap->tmpbuf); + while (c != '=' && c != '>' && c != '/' && soap_notblank(c) && (int)c != EOF) + { if (--i > 0) + *s++ = (char)c; + c = soap_get1(soap); + } + *s = '\0'; + if (i == sizeof(soap->tmpbuf)) + return soap->error = SOAP_SYNTAX_ERROR; +#ifdef WITH_DOM + /* add attribute name to dom */ + if (att) + { *att = (struct soap_dom_attribute*)soap_malloc(soap, sizeof(struct soap_dom_attribute)); + if (!*att) + return soap->error; + (*att)->next = NULL; + (*att)->nstr = NULL; + (*att)->name = soap_strdup(soap, soap->tmpbuf); + (*att)->data = NULL; + (*att)->wide = NULL; + (*att)->soap = soap; + } +#endif + if (!strncmp(soap->tmpbuf, "xmlns", 5)) + { if (soap->tmpbuf[5] == ':') + t = soap->tmpbuf + 6; + else if (soap->tmpbuf[5]) + t = NULL; + else + t = SOAP_STR_EOS; + } + else + t = NULL; + tq = NULL; + for (tp = soap->attributes; tp; tq = tp, tp = tp->next) + { if (!SOAP_STRCMP(tp->name, soap->tmpbuf)) + break; + } + if (!tp) + { tp = (struct soap_attribute*)SOAP_MALLOC(soap, sizeof(struct soap_attribute) + strlen(soap->tmpbuf)); + if (!tp) + return soap->error = SOAP_EOM; + strcpy(tp->name, soap->tmpbuf); + tp->value = NULL; + tp->size = 0; + /* if attribute name is qualified, append it to the end of the list */ + if (tq && strchr(soap->tmpbuf, ':')) + { tq->next = tp; + tp->next = NULL; + } + else + { tp->next = soap->attributes; + soap->attributes = tp; + } + } + while (soap_blank(c)) + c = soap_get1(soap); + if (c == '=') + { do c = soap_getutf8(soap); + while (soap_blank(c)); + if (c != SOAP_QT && c != SOAP_AP) + { soap_unget(soap, c); + c = ' '; /* blank delimiter */ + } + if (soap_getattrval(soap, tp->value, tp->size, c)) + { +#ifdef WITH_FAST + if (soap->error != SOAP_EOM) + return soap->error; + soap->error = SOAP_OK; + if (soap_store_lab(soap, tp->value, tp->size)) + return soap->error; + if (tp->value) + SOAP_FREE(soap, tp->value); + for (;;) + { if (soap_getattrval(soap, soap->labbuf + soap->labidx, soap->lablen - soap->labidx, c)) + { if (soap->error != SOAP_EOM) + return soap->error; + soap->error = SOAP_OK; + soap->labidx = soap->lablen; + if (soap_append_lab(soap, NULL, 0)) + return soap->error; + } + else + break; + } + if (soap->labidx) + tp->size = soap->lablen; + else + { tp->size = strlen(soap->labbuf) + 1; + if (tp->size < SOAP_LABLEN) + tp->size = SOAP_LABLEN; + } + if (!(tp->value = (char*)SOAP_MALLOC(soap, tp->size))) + return soap->error = SOAP_EOM; + strcpy(tp->value, soap->labbuf); +#else + size_t n; + if (soap->error != SOAP_EOM) + return soap->error; + soap->error = SOAP_OK; + if (soap_new_block(soap) == NULL) + return soap->error; + for (;;) + { if (!(s = (char*)soap_push_block(soap, NULL, SOAP_BLKLEN))) + return soap->error; + if (soap_getattrval(soap, s, SOAP_BLKLEN, c)) + { if (soap->error != SOAP_EOM) + return soap->error; + soap->error = SOAP_OK; + } + else + break; + } + n = tp->size + soap->blist->size; + if (!(s = (char*)SOAP_MALLOC(soap, n))) + return soap->error = SOAP_EOM; + if (tp->value) + { memcpy(s, tp->value, tp->size); + SOAP_FREE(soap, tp->value); + } + soap_save_block(soap, NULL, s + tp->size, 0); + tp->value = s; + tp->size = n; +#endif + } + do c = soap_get1(soap); + while (soap_blank(c)); + tp->visible = 2; /* seen this attribute w/ value */ +#ifdef WITH_DOM + if (att) + (*att)->data = soap_strdup(soap, tp->value); +#endif + } + else + tp->visible = 1; /* seen this attribute w/o value */ +#ifdef WITH_DOM + if (att) + att = &(*att)->next; +#endif + if (t && tp->value) + { if (soap_push_namespace(soap, t, tp->value) == NULL) + return soap->error; + } + } +#ifdef WITH_DOM + if (att) + { soap->dom->nstr = soap_current_namespace(soap, soap->tag); + for (att = &soap->dom->atts; *att; att = &(*att)->next) + (*att)->nstr = soap_current_namespace(soap, (*att)->name); + } +#endif + if ((int)c == EOF) + return soap->error = SOAP_EOF; + if (!(soap->body = (c != '/'))) + do c = soap_get1(soap); + while (soap_blank(c)); +#ifdef WITH_DOM + if (soap->mode & SOAP_XML_DOM) + { if (!soap->body && soap->dom->prnt) + soap->dom = soap->dom->prnt; + } +#endif + for (tp = soap->attributes; tp; tp = tp->next) + { if (tp->visible && tp->value) + { +#ifndef WITH_NOIDREF + if (!strcmp(tp->name, "id")) + { if ((soap->version > 0 && !(soap->mode & SOAP_XML_TREE)) + || (soap->mode & SOAP_XML_GRAPH)) + { *soap->id = '#'; + strncpy(soap->id + 1, tp->value, sizeof(soap->id) - 2); + soap->id[sizeof(soap->id)-1] = '\0'; + } + } + else if (!strcmp(tp->name, "href")) + { if (soap->version == 1 + || (soap->mode & SOAP_XML_GRAPH) + || (soap->mode & SOAP_ENC_MTOM) + || (soap->mode & SOAP_ENC_DIME)) + { strncpy(soap->href, tp->value, sizeof(soap->href) - 1); + soap->href[sizeof(soap->href)-1] = '\0'; + } + } + else +#endif + if (!soap_match_tag(soap, tp->name, "xsi:type")) + { strncpy(soap->type, tp->value, sizeof(soap->type) - 1); + soap->type[sizeof(soap->type)-1] = '\0'; + } + else if ((!soap_match_tag(soap, tp->name, "xsi:null") + || !soap_match_tag(soap, tp->name, "xsi:nil")) + && (!strcmp(tp->value, "1") + || !strcmp(tp->value, "true"))) + { soap->null = 1; + } + else if (soap->version == 1) + { if (!soap_match_tag(soap, tp->name, "SOAP-ENC:arrayType")) + { s = soap_strrchr(tp->value, '['); + if (s && (size_t)(s - tp->value) < sizeof(soap->arrayType)) + { strncpy(soap->arrayType, tp->value, s - tp->value); + soap->arrayType[s - tp->value] = '\0'; + strncpy(soap->arraySize, s, sizeof(soap->arraySize) - 1); + } + else + strncpy(soap->arrayType, tp->value, sizeof(soap->arrayType) - 1); + soap->arraySize[sizeof(soap->arrayType)-1] = '\0'; + soap->arrayType[sizeof(soap->arrayType)-1] = '\0'; + } + else if (!soap_match_tag(soap, tp->name, "SOAP-ENC:offset")) + strncpy(soap->arrayOffset, tp->value, sizeof(soap->arrayOffset)); + else if (!soap_match_tag(soap, tp->name, "SOAP-ENC:position")) + soap->position = soap_getposition(tp->value, soap->positions); + else if (!soap_match_tag(soap, tp->name, "SOAP-ENC:root")) + soap->root = ((!strcmp(tp->value, "1") || !strcmp(tp->value, "true"))); + else if (!soap_match_tag(soap, tp->name, "SOAP-ENV:mustUnderstand") + && (!strcmp(tp->value, "1") || !strcmp(tp->value, "true"))) + soap->mustUnderstand = 1; + else if (!soap_match_tag(soap, tp->name, "SOAP-ENV:actor")) + { if ((!soap->actor || strcmp(soap->actor, tp->value)) + && strcmp(tp->value, "http://schemas.xmlsoap.org/soap/actor/next")) + soap->other = 1; + } + } + else if (soap->version == 2) + { +#ifndef WITH_NOIDREF + if (!strcmp(tp->name, "ref") + || !soap_match_tag(soap, tp->name, "SOAP-ENC:ref")) + { *soap->href = '#'; + strncpy(soap->href + 1, tp->value, sizeof(soap->href) - 2); + soap->href[sizeof(soap->href)-1] = '\0'; + } + else +#endif + if (!soap_match_tag(soap, tp->name, "SOAP-ENC:itemType")) + strncpy(soap->arrayType, tp->value, sizeof(soap->arrayType) - 1); + else if (!soap_match_tag(soap, tp->name, "SOAP-ENC:arraySize")) + strncpy(soap->arraySize, tp->value, sizeof(soap->arraySize) - 1); + else if (!soap_match_tag(soap, tp->name, "SOAP-ENV:mustUnderstand") + && (!strcmp(tp->value, "1") || !strcmp(tp->value, "true"))) + soap->mustUnderstand = 1; + else if (!soap_match_tag(soap, tp->name, "SOAP-ENV:role")) + { if ((!soap->actor || strcmp(soap->actor, tp->value)) + && strcmp(tp->value, "http://www.w3.org/2003/05/soap-envelope/role/next")) + soap->other = 1; + } + } + else + { if (!soap_match_tag(soap, tp->name, "wsdl:required") && !strcmp(tp->value, "true")) + soap->mustUnderstand = 1; + } + } + } + return soap->error = SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_retry(struct soap *soap) +{ soap->error = SOAP_OK; + soap_revert(soap); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_revert(struct soap *soap) +{ if (!soap->peeked) + { soap->peeked = 1; + if (soap->body) + soap->level--; + } + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Reverting last element (level=%u)\n", soap->level)); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_string_out(struct soap *soap, const char *s, int flag) +{ register const char *t; + register soap_wchar c; + register soap_wchar mask = (soap_wchar)0xFFFFFF80UL; +#ifdef WITH_DOM + if ((soap->mode & SOAP_XML_DOM) && soap->dom) + { soap->dom->data = soap_strdup(soap, s); + return SOAP_OK; + } +#endif + if (soap->mode & SOAP_C_UTFSTRING) + mask = 0; + t = s; + while ((c = *t++)) + { switch (c) + { + case 0x09: + if (flag) + { if (soap_send_raw(soap, s, t - s - 1) || soap_send_raw(soap, " ", 5)) + return soap->error; + s = t; + } + break; + case 0x0A: + if (flag || !(soap->mode & SOAP_XML_CANONICAL)) + { if (soap_send_raw(soap, s, t - s - 1) || soap_send_raw(soap, " ", 5)) + return soap->error; + s = t; + } + break; + case 0x0D: + if (soap_send_raw(soap, s, t - s - 1) || soap_send_raw(soap, " ", 5)) + return soap->error; + s = t; + break; + case '&': + if (soap_send_raw(soap, s, t - s - 1) || soap_send_raw(soap, "&", 5)) + return soap->error; + s = t; + break; + case '<': + if (soap_send_raw(soap, s, t - s - 1) || soap_send_raw(soap, "<", 4)) + return soap->error; + s = t; + break; + case '>': + if (!flag) + { if (soap_send_raw(soap, s, t - s - 1) || soap_send_raw(soap, ">", 4)) + return soap->error; + s = t; + } + break; + case '"': + if (flag) + { if (soap_send_raw(soap, s, t - s - 1) || soap_send_raw(soap, """, 6)) + return soap->error; + s = t; + } + break; + default: +#ifndef WITH_LEANER +#ifdef HAVE_MBTOWC + if (soap->mode & SOAP_C_MBSTRING) + { wchar_t wc; + register int m = mbtowc(&wc, t - 1, MB_CUR_MAX); + if (m > 0 && wc != c) + { if (soap_send_raw(soap, s, t - s - 1) || soap_pututf8(soap, wc)) + return soap->error; + s = t += m - 1; + continue; + } + } +#endif +#endif +#ifndef WITH_NOSTRINGTOUTF8 + if ((c & mask) || !(c & 0xFFFFFFE0UL)) + { if (soap_send_raw(soap, s, t - s - 1) || soap_pututf8(soap, (unsigned char)c)) + return soap->error; + s = t; + } +#endif + } + } + return soap_send_raw(soap, s, t - s - 1); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +char * +SOAP_FMAC2 +soap_string_in(struct soap *soap, int flag, long minlen, long maxlen) +{ register char *s; + char *t = NULL; + register size_t i; + register long l = 0; + register int n = 0, f = 0, m = 0; + register soap_wchar c; +#if !defined(WITH_LEANER) && defined(HAVE_WCTOMB) + char buf[MB_LEN_MAX > 8 ? MB_LEN_MAX : 8]; +#else + char buf[8]; +#endif + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Reading string content, flag=%d\n", flag)); + if (soap->peeked && *soap->tag) + { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "String content includes tag '%s' and attributes\n", soap->tag)); +#ifndef WITH_LEAN + struct soap_attribute *tp; + t = soap->tmpbuf; + *t = '<'; + t[sizeof(soap->tmpbuf)-1] = '\0'; + strncpy(t + 1, soap->tag, sizeof(soap->tmpbuf) - 2); + t += strlen(t); + for (tp = soap->attributes; tp; tp = tp->next) + { if (tp->visible) + { if (t >= soap->tmpbuf + sizeof(soap->tmpbuf) - 2) + break; + *t++ = ' '; + strcpy(t, tp->name); + t += strlen(t); + if (t >= soap->tmpbuf + sizeof(soap->tmpbuf) - 2) + break; /* too many or large attribute values */ + if (tp->value) + { *t++ = '='; + *t++ = '"'; + strcpy(t, tp->value); + t += strlen(t); + *t++ = '"'; + } + } + } + if (!soap->body) + *t++ = '/'; + *t++ = '>'; + *t = '\0'; + t = soap->tmpbuf; + m = (int)strlen(soap->tmpbuf); +#endif + if (soap->body) + n = 1; + f = 1; + soap->peeked = 0; + } +#ifdef WITH_CDATA + if (!flag) + { register int state = 0; +#ifdef WITH_FAST + soap->labidx = 0; /* use look-aside buffer */ +#else + if (soap_new_block(soap) == NULL) + return NULL; +#endif + for (;;) + { +#ifdef WITH_FAST + register size_t k; + if (soap_append_lab(soap, NULL, 0)) /* allocate more space in look-aside buffer if necessary */ + return NULL; + s = soap->labbuf + soap->labidx; /* space to populate */ + k = soap->lablen - soap->labidx; /* number of bytes available */ + soap->labidx = soap->lablen; /* claim this space */ +#else + register size_t k = SOAP_BLKLEN; + if (!(s = (char*)soap_push_block(soap, NULL, k))) + return NULL; +#endif + for (i = 0; i < k; i++) + { if (m > 0) + { *s++ = *t++; /* copy multibyte characters */ + m--; + continue; + } + c = soap_getchar(soap); + if ((int)c == EOF) + goto end; + if (c >= 0x80 && state != 1 && !(soap->mode & SOAP_ENC_LATIN)) + { soap_unget(soap, c); + c = soap_getutf8(soap); + if (soap->mode & SOAP_C_UTFSTRING) + { c &= 0x7FFFFFFF; + t = buf; + if (c < 0x0800) + *t++ = (char)(0xC0 | ((c >> 6) & 0x1F)); + else + { if (c < 0x010000) + *t++ = (char)(0xE0 | ((c >> 12) & 0x0F)); + else + { if (c < 0x200000) + *t++ = (char)(0xF0 | ((c >> 18) & 0x07)); + else + { if (c < 0x04000000) + *t++ = (char)(0xF8 | ((c >> 24) & 0x03)); + else + { *t++ = (char)(0xFC | ((c >> 30) & 0x01)); + *t++ = (char)(0x80 | ((c >> 24) & 0x3F)); + } + *t++ = (char)(0x80 | ((c >> 18) & 0x3F)); + } + *t++ = (char)(0x80 | ((c >> 12) & 0x3F)); + } + *t++ = (char)(0x80 | ((c >> 6) & 0x3F)); + } + *t++ = (char)(0x80 | (c & 0x3F)); + m = (int)(t - buf) - 1; + t = buf; + *s++ = *t++; + continue; + } + } + switch (state) + { case 1: + if (c == ']') + state = 4; + *s++ = c; + continue; + case 2: + if (c == '-') + state = 6; + *s++ = c; + continue; + case 3: + if (c == '?') + state = 8; + *s++ = c; + continue; + /* CDATA */ + case 4: + if (c == ']') + state = 5; + else + state = 1; + *s++ = c; + continue; + case 5: + if (c == '>') + state = 0; + else + state = 1; + *s++ = c; + continue; + /* comment */ + case 6: + if (c == '-') + state = 7; + else + state = 2; + *s++ = c; + continue; + case 7: + if (c == '>') + state = 0; + else + state = 2; + *s++ = c; + continue; + /* PI */ + case 8: + if (c == '>') + state = 0; + else + state = 3; + *s++ = c; + continue; + } + switch (c) + { + case SOAP_TT: + if (n == 0) + goto end; + n--; + *s++ = '<'; + t = (char*)"/"; + m = 1; + break; + case SOAP_LT: + if (f && n == 0) + goto end; + n++; + *s++ = '<'; + break; + case '/': + if (n > 0) + { c = soap_getchar(soap); + if (c == '>') + n--; + soap_unget(soap, c); + } + *s++ = '/'; + break; + case '<': + c = soap_getchar(soap); + if (c == '/') + { if (n == 0) + { c = SOAP_TT; + goto end; + } + n--; + } + else if (c == '!') + { c = soap_getchar(soap); + if (c == '[') + { do c = soap_getchar(soap); + while ((int)c != EOF && c != '['); + if ((int)c == EOF) + goto end; + t = (char*)"![CDATA["; + m = 8; + state = 1; + } + else if (c == '-') + { if ((c = soap_getchar(soap)) == '-') + state = 2; + t = (char*)"!-"; + m = 2; + soap_unget(soap, c); + } + else + { t = (char*)"!"; + m = 1; + soap_unget(soap, c); + } + *s++ = '<'; + break; + } + else if (c == '?') + state = 3; + else if (f && n == 0) + { soap_revget1(soap); + c = '<'; + goto end; + } + else + n++; + soap_unget(soap, c); + *s++ = '<'; + break; + case '>': + *s++ = '>'; + break; + case '"': + *s++ = '"'; + break; + default: +#ifndef WITH_LEANER +#ifdef HAVE_WCTOMB + if (soap->mode & SOAP_C_MBSTRING) + { m = wctomb(buf, c & 0x7FFFFFFF); + if (m >= 1 && m <= (int)MB_CUR_MAX) + { t = buf; + *s++ = *t++; + m--; + } + else + { *s++ = SOAP_UNKNOWN_CHAR; + m = 0; + } + } + else +#endif +#endif + *s++ = (char)(c & 0xFF); + } + l++; + if ((soap->mode & SOAP_XML_STRICT) && maxlen >= 0 && l > maxlen) + { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "String too long: maxlen=%ld\n", maxlen)); + soap->error = SOAP_LENGTH; + return NULL; + } + } + } + } +#endif +#ifdef WITH_FAST + soap->labidx = 0; /* use look-aside buffer */ +#else + if (soap_new_block(soap) == NULL) + return NULL; +#endif + for (;;) + { +#ifdef WITH_FAST + register size_t k; + if (soap_append_lab(soap, NULL, 0)) /* allocate more space in look-aside buffer if necessary */ + return NULL; + s = soap->labbuf + soap->labidx; /* space to populate */ + k = soap->lablen - soap->labidx; /* number of bytes available */ + soap->labidx = soap->lablen; /* claim this space */ +#else + register size_t k = SOAP_BLKLEN; + if (!(s = (char*)soap_push_block(soap, NULL, k))) + return NULL; +#endif + for (i = 0; i < k; i++) + { if (m > 0) + { *s++ = *t++; /* copy multibyte characters */ + m--; + continue; + } + if (soap->mode & SOAP_C_UTFSTRING) + { if (((c = soap_get(soap)) & 0x80000000) && c >= -0x7FFFFF80 && c < SOAP_AP) + { c &= 0x7FFFFFFF; + t = buf; + if (c < 0x0800) + *t++ = (char)(0xC0 | ((c >> 6) & 0x1F)); + else + { if (c < 0x010000) + *t++ = (char)(0xE0 | ((c >> 12) & 0x0F)); + else + { if (c < 0x200000) + *t++ = (char)(0xF0 | ((c >> 18) & 0x07)); + else + { if (c < 0x04000000) + *t++ = (char)(0xF8 | ((c >> 24) & 0x03)); + else + { *t++ = (char)(0xFC | ((c >> 30) & 0x01)); + *t++ = (char)(0x80 | ((c >> 24) & 0x3F)); + } + *t++ = (char)(0x80 | ((c >> 18) & 0x3F)); + } + *t++ = (char)(0x80 | ((c >> 12) & 0x3F)); + } + *t++ = (char)(0x80 | ((c >> 6) & 0x3F)); + } + *t++ = (char)(0x80 | (c & 0x3F)); + m = (int)(t - buf) - 1; + t = buf; + *s++ = *t++; + continue; + } + } + else + c = soap_getutf8(soap); + switch (c) + { + case SOAP_TT: + if (n == 0) + goto end; + n--; + *s++ = '<'; + t = (char*)"/"; + m = 1; + break; + case SOAP_LT: + if (f && n == 0) + goto end; + n++; + *s++ = '<'; + break; + case SOAP_GT: + *s++ = '>'; + break; + case SOAP_QT: + *s++ = '"'; + break; + case SOAP_AP: + *s++ = '\''; + break; + case '/': + if (n > 0) + { c = soap_get(soap); + if (c == SOAP_GT) + n--; + soap_unget(soap, c); + } + *s++ = '/'; + break; + case (soap_wchar)('<' | 0x80000000): + if (flag) + *s++ = '<'; + else + { *s++ = '&'; + t = (char*)"lt;"; + m = 3; + } + break; + case (soap_wchar)('>' | 0x80000000): + if (flag) + *s++ = '>'; + else + { *s++ = '&'; + t = (char*)"gt;"; + m = 3; + } + break; + case (soap_wchar)('&' | 0x80000000): + if (flag) + *s++ = '&'; + else + { *s++ = '&'; + t = (char*)"amp;"; + m = 4; + } + break; + case (soap_wchar)('"' | 0x80000000): + if (flag) + *s++ = '"'; + else + { *s++ = '&'; + t = (char*)"quot;"; + m = 5; + } + break; + case (soap_wchar)('\'' | 0x80000000): + if (flag) + *s++ = '\''; + else + { *s++ = '&'; + t = (char*)"apos;"; + m = 5; + } + break; + default: + if ((int)c == EOF) + goto end; +#ifndef WITH_LEANER +#ifdef HAVE_WCTOMB + if (soap->mode & SOAP_C_MBSTRING) + { m = wctomb(buf, c & 0x7FFFFFFF); + if (m >= 1 && m <= (int)MB_CUR_MAX) + { t = buf; + *s++ = *t++; + m--; + } + else + { *s++ = SOAP_UNKNOWN_CHAR; + m = 0; + } + } + else +#endif +#endif + *s++ = (char)(c & 0xFF); + } + l++; + if ((soap->mode & SOAP_XML_STRICT) && maxlen >= 0 && l > maxlen) + { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "String too long: maxlen=%ld\n", maxlen)); + soap->error = SOAP_LENGTH; + return NULL; + } + } + } +end: + soap_unget(soap, c); + *s = '\0'; +#ifdef WITH_FAST + t = soap_strdup(soap, soap->labbuf); +#else + soap_size_block(soap, NULL, i+1); + t = soap_save_block(soap, NULL, 0); +#endif + if ((soap->mode & SOAP_XML_STRICT) && l < minlen) + { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "String too short: %ld chars, minlen=%ld\n", l, minlen)); + soap->error = SOAP_LENGTH; + return NULL; + } +#ifdef WITH_DOM + if ((soap->mode & SOAP_XML_DOM) && soap->dom) + { if (flag == 3) + soap->dom->tail = t; + else + soap->dom->data = t; + } +#endif + if (flag == 2) + if (soap_s2QName(soap, t, &t, minlen, maxlen)) + return NULL; + return t; +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_wstring_out(struct soap *soap, const wchar_t *s, int flag) +{ const char *t; + char tmp; + register soap_wchar c; +#ifdef WITH_DOM + if ((soap->mode & SOAP_XML_DOM) && soap->dom) + { wchar_t *r = (wchar_t*)s; + int n = 1; + while (*r++) + n++; + soap->dom->wide = r = (wchar_t*)soap_malloc(soap, n * sizeof(wchar_t)); + while (n--) + *r++ = *s++; + return SOAP_OK; + } +#endif + while ((c = *s++)) + { switch (c) + { + case 0x09: + if (flag) + t = " "; + else + t = "\t"; + break; + case 0x0A: + if (flag || !(soap->mode & SOAP_XML_CANONICAL)) + t = " "; + else + t = "\n"; + break; + case 0x0D: + t = " "; + break; + case '&': + t = "&"; + break; + case '<': + t = "<"; + break; + case '>': + if (flag) + t = ">"; + else + t = ">"; + break; + case '"': + if (flag) + t = """; + else + t = "\""; + break; + default: + if (c >= 0x20 && c < 0x80) + { tmp = (char)c; + if (soap_send_raw(soap, &tmp, 1)) + return soap->error; + } + else if (soap_pututf8(soap, (unsigned long)c)) + return soap->error; + continue; + } + if (soap_send(soap, t)) + return soap->error; + } + return SOAP_OK; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_2 +SOAP_FMAC1 +wchar_t * +SOAP_FMAC2 +soap_wstring_in(struct soap *soap, int flag, long minlen, long maxlen) +{ wchar_t *s; + register int i, n = 0, f = 0; + register long l = 0; + register soap_wchar c; + char *t = NULL; + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Reading wide string content\n")); + if (soap->peeked) + { if (*soap->tag) + { +#ifndef WITH_LEAN + struct soap_attribute *tp; + t = soap->tmpbuf; + *t = '<'; + t[sizeof(soap->tmpbuf)-1] = '\0'; + strncpy(t + 1, soap->tag, sizeof(soap->tmpbuf) - 2); + t += strlen(t); + for (tp = soap->attributes; tp; tp = tp->next) + { if (tp->visible) + { if (t >= soap->tmpbuf + sizeof(soap->tmpbuf) - 2) + break; + *t++ = ' '; + strcpy(t, tp->name); + t += strlen(t); + if (t >= soap->tmpbuf + sizeof(soap->tmpbuf) - 2) + break; + if (tp->value) + { *t++ = '='; + *t++ = '"'; + strcpy(t, tp->value); + t += strlen(t); + *t++ = '"'; + } + } + } + if (!soap->body) + *t++ = '/'; + *t++ = '>'; + *t = '\0'; + t = soap->tmpbuf; +#endif + if (soap->body) + n = 1; + f = 1; + soap->peeked = 0; + } + } + if (soap_new_block(soap) == NULL) + return NULL; + for (;;) + { if (!(s = (wchar_t*)soap_push_block(soap, NULL, sizeof(wchar_t)*SOAP_BLKLEN))) + return NULL; + for (i = 0; i < SOAP_BLKLEN; i++) + { if (t) + { *s++ = (wchar_t)*t++; + if (!*t) + t = NULL; + continue; + } + c = soap_getutf8(soap); + switch (c) + { + case SOAP_TT: + if (n == 0) + goto end; + n--; + *s++ = '<'; + soap_unget(soap, '/'); + break; + case SOAP_LT: + if (f && n == 0) + goto end; + n++; + *s++ = '<'; + break; + case SOAP_GT: + *s++ = '>'; + break; + case SOAP_QT: + *s++ = '"'; + break; + case SOAP_AP: + *s++ = '\''; + break; + case '/': + if (n > 0) + { c = soap_getutf8(soap); + if (c == SOAP_GT) + n--; + soap_unget(soap, c); + } + *s++ = '/'; + break; + case '<': + if (flag) + *s++ = (soap_wchar)'<'; + else + { *s++ = (soap_wchar)'&'; + t = (char*)"lt;"; + } + break; + case '>': + if (flag) + *s++ = (soap_wchar)'>'; + else + { *s++ = (soap_wchar)'&'; + t = (char*)"gt;"; + } + break; + case '"': + if (flag) + *s++ = (soap_wchar)'"'; + else + { *s++ = (soap_wchar)'&'; + t = (char*)"quot;"; + } + break; + default: + if ((int)c == EOF) + goto end; + *s++ = (wchar_t)c & 0x7FFFFFFF; + } + l++; + if ((soap->mode & SOAP_XML_STRICT) && maxlen >= 0 && l > maxlen) + { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "String too long: maxlen=%ld\n", maxlen)); + soap->error = SOAP_LENGTH; + return NULL; + } + } + } +end: + soap_unget(soap, c); + *s = '\0'; + soap_size_block(soap, NULL, sizeof(wchar_t) * (i + 1)); + if ((soap->mode & SOAP_XML_STRICT) && l < minlen) + { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "String too short: %ld chars, minlen=%ld\n", l, minlen)); + soap->error = SOAP_LENGTH; + return NULL; + } + s = (wchar_t*)soap_save_block(soap, NULL, NULL, 0); +#ifdef WITH_DOM + if ((soap->mode & SOAP_XML_DOM) && soap->dom) + soap->dom->wide = s; +#endif + return s; +} +#endif +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +const char* +SOAP_FMAC2 +soap_int2s(struct soap *soap, int n) +{ return soap_long2s(soap, (long)n); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_outint(struct soap *soap, const char *tag, int id, const int *p, const char *type, int n) +{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type) + || soap_string_out(soap, soap_long2s(soap, (long)*p), 0)) + return soap->error; + return soap_element_end_out(soap, tag); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_s2int(struct soap *soap, const char *s, int *p) +{ if (s) + { char *r; +#ifndef WITH_NOIO +#ifndef WITH_LEAN + soap_reset_errno; +#endif +#endif + *p = (int)soap_strtol(s, &r, 10); + if ((s == r && (soap->mode & SOAP_XML_STRICT)) || *r +#ifndef WITH_NOIO +#ifndef WITH_LEAN + || soap_errno == SOAP_ERANGE +#endif +#endif + ) + soap->error = SOAP_TYPE; + } + return soap->error; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int * +SOAP_FMAC2 +soap_inint(struct soap *soap, const char *tag, int *p, const char *type, int t) +{ if (soap_element_begin_in(soap, tag, 0, NULL)) + return NULL; +#ifndef WITH_LEAN + if (*soap->type + && soap_match_tag(soap, soap->type, type) + && soap_match_tag(soap, soap->type, ":int") + && soap_match_tag(soap, soap->type, ":short") + && soap_match_tag(soap, soap->type, ":byte")) + { soap->error = SOAP_TYPE; + soap_revert(soap); + return NULL; + } +#endif + p = (int*)soap_id_enter(soap, soap->id, p, t, sizeof(int), 0, NULL, NULL, NULL); + if (*soap->href) + p = (int*)soap_id_forward(soap, soap->href, p, 0, t, 0, sizeof(int), 0, NULL); + else if (p) + { if (soap_s2int(soap, soap_value(soap), p)) + return NULL; + } + if (soap->body && soap_element_end_in(soap, tag)) + return NULL; + return p; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +const char* +SOAP_FMAC2 +soap_long2s(struct soap *soap, long n) +{ sprintf(soap->tmpbuf, "%ld", n); + return soap->tmpbuf; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_outlong(struct soap *soap, const char *tag, int id, const long *p, const char *type, int n) +{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type) + || soap_string_out(soap, soap_long2s(soap, *p), 0)) + return soap->error; + return soap_element_end_out(soap, tag); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_s2long(struct soap *soap, const char *s, long *p) +{ if (s) + { char *r; +#ifndef WITH_NOIO +#ifndef WITH_LEAN + soap_reset_errno; +#endif +#endif + *p = soap_strtol(s, &r, 10); + if ((s == r && (soap->mode & SOAP_XML_STRICT)) || *r +#ifndef WITH_NOIO +#ifndef WITH_LEAN + || soap_errno == SOAP_ERANGE +#endif +#endif + ) + soap->error = SOAP_TYPE; + } + return soap->error; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +long * +SOAP_FMAC2 +soap_inlong(struct soap *soap, const char *tag, long *p, const char *type, int t) +{ if (soap_element_begin_in(soap, tag, 0, NULL)) + return NULL; +#ifndef WITH_LEAN + if (*soap->type + && soap_match_tag(soap, soap->type, type) + && soap_match_tag(soap, soap->type, ":int") + && soap_match_tag(soap, soap->type, ":short") + && soap_match_tag(soap, soap->type, ":byte")) + { soap->error = SOAP_TYPE; + soap_revert(soap); + return NULL; + } +#endif + p = (long*)soap_id_enter(soap, soap->id, p, t, sizeof(long), 0, NULL, NULL, NULL); + if (*soap->href) + p = (long*)soap_id_forward(soap, soap->href, p, 0, t, 0, sizeof(long), 0, NULL); + else if (p) + { if (soap_s2long(soap, soap_value(soap), p)) + return NULL; + } + if (soap->body && soap_element_end_in(soap, tag)) + return NULL; + return p; +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEAN +SOAP_FMAC1 +const char* +SOAP_FMAC2 +soap_LONG642s(struct soap *soap, LONG64 n) +{ sprintf(soap->tmpbuf, SOAP_LONG_FORMAT, n); + return soap->tmpbuf; +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEAN +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_outLONG64(struct soap *soap, const char *tag, int id, const LONG64 *p, const char *type, int n) +{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type) + || soap_string_out(soap, soap_LONG642s(soap, *p), 0)) + return soap->error; + return soap_element_end_out(soap, tag); +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEAN +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_s2LONG64(struct soap *soap, const char *s, LONG64 *p) +{ if (s) + { +#ifdef HAVE_STRTOLL + char *r; +#ifndef WITH_NOIO +#ifndef WITH_LEAN + soap_reset_errno; +#endif +#endif + *p = strtoll(s, &r, 10); + if ((s == r && (soap->mode & SOAP_XML_STRICT)) || *r +#ifndef WITH_NOIO +#ifndef WITH_LEAN + || soap_errno == SOAP_ERANGE +#endif +#endif + ) +#else +# ifdef HAVE_SSCANF + if (sscanf(s, SOAP_LONG_FORMAT, p) != 1) +# endif +#endif + soap->error = SOAP_TYPE; + } + return soap->error; +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEAN +SOAP_FMAC1 +LONG64 * +SOAP_FMAC2 +soap_inLONG64(struct soap *soap, const char *tag, LONG64 *p, const char *type, int t) +{ if (soap_element_begin_in(soap, tag, 0, NULL)) + return NULL; +#ifndef WITH_LEAN + if (*soap->type + && soap_match_tag(soap, soap->type, type) + && soap_match_tag(soap, soap->type, ":integer") + && soap_match_tag(soap, soap->type, ":positiveInteger") + && soap_match_tag(soap, soap->type, ":negativeInteger") + && soap_match_tag(soap, soap->type, ":nonPositiveInteger") + && soap_match_tag(soap, soap->type, ":nonNegativeInteger") + && soap_match_tag(soap, soap->type, ":long") + && soap_match_tag(soap, soap->type, ":int") + && soap_match_tag(soap, soap->type, ":short") + && soap_match_tag(soap, soap->type, ":byte")) + { soap->error = SOAP_TYPE; + soap_revert(soap); + return NULL; + } +#endif + p = (LONG64*)soap_id_enter(soap, soap->id, p, t, sizeof(LONG64), 0, NULL, NULL, NULL); + if (*soap->href) + p = (LONG64*)soap_id_forward(soap, soap->href, p, 0, t, 0, sizeof(LONG64), 0, NULL); + else if (p) + { if (soap_s2LONG64(soap, soap_value(soap), p)) + return NULL; + } + if (soap->body && soap_element_end_in(soap, tag)) + return NULL; + return p; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +const char* +SOAP_FMAC2 +soap_byte2s(struct soap *soap, char n) +{ return soap_long2s(soap, (long)n); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_outbyte(struct soap *soap, const char *tag, int id, const char *p, const char *type, int n) +{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type) + || soap_string_out(soap, soap_long2s(soap, (long)*p), 0)) + return soap->error; + return soap_element_end_out(soap, tag); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_s2byte(struct soap *soap, const char *s, char *p) +{ if (s) + { long n; + char *r; + n = soap_strtol(s, &r, 10); + if (s == r || *r || n < -128 || n > 127) + soap->error = SOAP_TYPE; + *p = (char)n; + } + return soap->error; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +char * +SOAP_FMAC2 +soap_inbyte(struct soap *soap, const char *tag, char *p, const char *type, int t) +{ if (soap_element_begin_in(soap, tag, 0, NULL)) + return NULL; +#ifndef WITH_LEAN + if (*soap->type + && soap_match_tag(soap, soap->type, type) + && soap_match_tag(soap, soap->type, ":byte")) + { soap->error = SOAP_TYPE; + soap_revert(soap); + return NULL; + } +#endif + p = (char*)soap_id_enter(soap, soap->id, p, t, sizeof(char), 0, NULL, NULL, NULL); + if (*soap->href) + p = (char*)soap_id_forward(soap, soap->href, p, 0, t, 0, sizeof(char), 0, NULL); + else if (p) + { if (soap_s2byte(soap, soap_value(soap), p)) + return NULL; + } + if (soap->body && soap_element_end_in(soap, tag)) + return NULL; + return p; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +const char* +SOAP_FMAC2 +soap_short2s(struct soap *soap, short n) +{ return soap_long2s(soap, (long)n); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_outshort(struct soap *soap, const char *tag, int id, const short *p, const char *type, int n) +{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type) + || soap_string_out(soap, soap_long2s(soap, (long)*p), 0)) + return soap->error; + return soap_element_end_out(soap, tag); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_s2short(struct soap *soap, const char *s, short *p) +{ if (s) + { long n; + char *r; + n = soap_strtol(s, &r, 10); + if (s == r || *r || n < -32768 || n > 32767) + soap->error = SOAP_TYPE; + *p = (short)n; + } + return soap->error; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +short * +SOAP_FMAC2 +soap_inshort(struct soap *soap, const char *tag, short *p, const char *type, int t) +{ if (soap_element_begin_in(soap, tag, 0, NULL)) + return NULL; +#ifndef WITH_LEAN + if (*soap->type + && soap_match_tag(soap, soap->type, type) + && soap_match_tag(soap, soap->type, ":short") + && soap_match_tag(soap, soap->type, ":byte")) + { soap->error = SOAP_TYPE; + soap_revert(soap); + return NULL; + } +#endif + p = (short*)soap_id_enter(soap, soap->id, p, t, sizeof(short), 0, NULL, NULL, NULL); + if (*soap->href) + p = (short*)soap_id_forward(soap, soap->href, p, 0, t, 0, sizeof(short), 0, NULL); + else if (p) + { if (soap_s2short(soap, soap_value(soap), p)) + return NULL; + } + if (soap->body && soap_element_end_in(soap, tag)) + return NULL; + return p; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +const char* +SOAP_FMAC2 +soap_float2s(struct soap *soap, float n) +{ char *s; + if (soap_isnan((double)n)) + return "NaN"; + if (soap_ispinff(n)) + return "INF"; + if (soap_isninff(n)) + return "-INF"; + s = soap->tmpbuf; +#if defined(HAVE_SPRINTF_L) + sprintf_l(s, soap->c_locale, soap->float_format, n); +#else + sprintf(s, soap->float_format, n); + s = strchr(s, ','); /* convert decimal comma to DP */ + if (s) + *s = '.'; +#endif + return soap->tmpbuf; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_outfloat(struct soap *soap, const char *tag, int id, const float *p, const char *type, int n) +{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type) + || soap_string_out(soap, soap_float2s(soap, *p), 0)) + return soap->error; + return soap_element_end_out(soap, tag); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_s2float(struct soap *soap, const char *s, float *p) +{ if (s) + { if (!*s) + return soap->error = SOAP_TYPE; + if (!soap_tag_cmp(s, "INF")) + *p = FLT_PINFTY; + else if (!soap_tag_cmp(s, "+INF")) + *p = FLT_PINFTY; + else if (!soap_tag_cmp(s, "-INF")) + *p = FLT_NINFTY; + else if (!soap_tag_cmp(s, "NaN")) + *p = FLT_NAN; + else + { +/* On some systems strtof requires -std=c99 or does not even link: so we try to use strtod first */ +#if defined(HAVE_STRTOD_L) + char *r; + *p = (float)strtod_l(s, &r, soap->c_locale); + if (*r) +#elif defined(HAVE_STRTOD) + char *r; + *p = (float)strtod(s, &r); + if (*r) +#elif defined(HAVE_STRTOF_L) + char *r; + *p = strtof_l((char*)s, &r, soap->c_locale); + if (*r) +#elif defined(HAVE_STRTOF) + char *r; + *p = strtof((char*)s, &r); + if (*r) +#endif + { +#if defined(HAVE_SSCANF_L) && !defined(HAVE_STRTOF_L) && !defined(HAVE_STRTOD_L) + if (sscanf_l(s, soap->c_locale, "%g", p) != 1) + soap->error = SOAP_TYPE; +#elif defined(HAVE_SSCANF) + if (sscanf(s, "%g", p) != 1) + soap->error = SOAP_TYPE; +#else + soap->error = SOAP_TYPE; +#endif + } + } + } + return soap->error; +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEAN +static int soap_isnumeric(struct soap *soap, const char *type) +{ if (soap_match_tag(soap, soap->type, type) + && soap_match_tag(soap, soap->type, ":float") + && soap_match_tag(soap, soap->type, ":double") + && soap_match_tag(soap, soap->type, ":decimal") + && soap_match_tag(soap, soap->type, ":integer") + && soap_match_tag(soap, soap->type, ":positiveInteger") + && soap_match_tag(soap, soap->type, ":negativeInteger") + && soap_match_tag(soap, soap->type, ":nonPositiveInteger") + && soap_match_tag(soap, soap->type, ":nonNegativeInteger") + && soap_match_tag(soap, soap->type, ":long") + && soap_match_tag(soap, soap->type, ":int") + && soap_match_tag(soap, soap->type, ":short") + && soap_match_tag(soap, soap->type, ":byte") + && soap_match_tag(soap, soap->type, ":unsignedLong") + && soap_match_tag(soap, soap->type, ":unsignedInt") + && soap_match_tag(soap, soap->type, ":unsignedShort") + && soap_match_tag(soap, soap->type, ":unsignedByte")) + { soap->error = SOAP_TYPE; + soap_revert(soap); + return SOAP_ERR; + } + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +float * +SOAP_FMAC2 +soap_infloat(struct soap *soap, const char *tag, float *p, const char *type, int t) +{ if (soap_element_begin_in(soap, tag, 0, NULL)) + return NULL; +#ifndef WITH_LEAN + if (*soap->type != '\0' && soap_isnumeric(soap, type)) + return NULL; +#endif + p = (float*)soap_id_enter(soap, soap->id, p, t, sizeof(float), 0, NULL, NULL, NULL); + if (*soap->href) + p = (float*)soap_id_forward(soap, soap->href, p, 0, t, 0, sizeof(float), 0, NULL); + else if (p) + { if (soap_s2float(soap, soap_value(soap), p)) + return NULL; + } + if (soap->body && soap_element_end_in(soap, tag)) + return NULL; + return p; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +const char* +SOAP_FMAC2 +soap_double2s(struct soap *soap, double n) +{ char *s; + if (soap_isnan(n)) + return "NaN"; + if (soap_ispinfd(n)) + return "INF"; + if (soap_isninfd(n)) + return "-INF"; + s = soap->tmpbuf; +#if defined(HAVE_SPRINTF_L) + sprintf_l(s, soap->c_locale, soap->double_format, n); +#else + sprintf(s, soap->double_format, n); + s = strchr(s, ','); /* convert decimal comma to DP */ + if (s) + *s = '.'; +#endif + return soap->tmpbuf; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_outdouble(struct soap *soap, const char *tag, int id, const double *p, const char *type, int n) +{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type) + || soap_string_out(soap, soap_double2s(soap, *p), 0)) + return soap->error; + return soap_element_end_out(soap, tag); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_s2double(struct soap *soap, const char *s, double *p) +{ if (s) + { if (!*s) + return soap->error = SOAP_TYPE; + if (!soap_tag_cmp(s, "INF")) + *p = DBL_PINFTY; + else if (!soap_tag_cmp(s, "+INF")) + *p = DBL_PINFTY; + else if (!soap_tag_cmp(s, "-INF")) + *p = DBL_NINFTY; + else if (!soap_tag_cmp(s, "NaN")) + *p = DBL_NAN; + else + { +#if defined(HAVE_STRTOD_L) + char *r; + *p = strtod_l(s, &r, soap->c_locale); + if (*r) +#elif defined(HAVE_STRTOD) + char *r; + *p = strtod(s, &r); + if (*r) +#endif + { +#if defined(HAVE_SSCANF_L) && !defined(HAVE_STRTOF_L) && !defined(HAVE_STRTOD_L) + if (sscanf_l(s, soap->c_locale, "%lg", p) != 1) + soap->error = SOAP_TYPE; +#elif defined(HAVE_SSCANF) + if (sscanf(s, "%lg", p) != 1) + soap->error = SOAP_TYPE; +#else + soap->error = SOAP_TYPE; +#endif + } + } + } + return soap->error; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +double * +SOAP_FMAC2 +soap_indouble(struct soap *soap, const char *tag, double *p, const char *type, int t) +{ if (soap_element_begin_in(soap, tag, 0, NULL)) + return NULL; +#ifndef WITH_LEAN + if (*soap->type != '\0' && soap_isnumeric(soap, type)) + return NULL; +#endif + p = (double*)soap_id_enter(soap, soap->id, p, t, sizeof(double), 0, NULL, NULL, NULL); + if (*soap->href) + p = (double*)soap_id_forward(soap, soap->href, p, 0, t, 0, sizeof(double), 0, NULL); + else if (p) + { if (soap_s2double(soap, soap_value(soap), p)) + return NULL; + } + if (soap->body && soap_element_end_in(soap, tag)) + return NULL; + return p; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +const char* +SOAP_FMAC2 +soap_unsignedByte2s(struct soap *soap, unsigned char n) +{ return soap_unsignedLong2s(soap, (unsigned long)n); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_outunsignedByte(struct soap *soap, const char *tag, int id, const unsigned char *p, const char *type, int n) +{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type) + || soap_string_out(soap, soap_unsignedLong2s(soap, (unsigned long)*p), 0)) + return soap->error; + return soap_element_end_out(soap, tag); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_s2unsignedByte(struct soap *soap, const char *s, unsigned char *p) +{ if (s) + { unsigned long n; + char *r; + n = soap_strtoul(s, &r, 10); + if (s == r || *r || n > 255) + soap->error = SOAP_TYPE; + *p = (unsigned char)n; + } + return soap->error; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +unsigned char * +SOAP_FMAC2 +soap_inunsignedByte(struct soap *soap, const char *tag, unsigned char *p, const char *type, int t) +{ if (soap_element_begin_in(soap, tag, 0, NULL)) + return NULL; +#ifndef WITH_LEAN + if (*soap->type + && soap_match_tag(soap, soap->type, type) + && soap_match_tag(soap, soap->type, ":unsignedByte")) + { soap->error = SOAP_TYPE; + soap_revert(soap); + return NULL; + } +#endif + p = (unsigned char*)soap_id_enter(soap, soap->id, p, t, sizeof(unsigned char), 0, NULL, NULL, NULL); + if (*soap->href) + p = (unsigned char*)soap_id_forward(soap, soap->href, p, 0, t, 0, sizeof(unsigned char), 0, NULL); + else if (p) + { if (soap_s2unsignedByte(soap, soap_value(soap), p)) + return NULL; + } + if (soap->body && soap_element_end_in(soap, tag)) + return NULL; + return p; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +const char* +SOAP_FMAC2 +soap_unsignedShort2s(struct soap *soap, unsigned short n) +{ return soap_unsignedLong2s(soap, (unsigned long)n); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_outunsignedShort(struct soap *soap, const char *tag, int id, const unsigned short *p, const char *type, int n) +{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type) + || soap_string_out(soap, soap_unsignedLong2s(soap, (unsigned long)*p), 0)) + return soap->error; + return soap_element_end_out(soap, tag); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_s2unsignedShort(struct soap *soap, const char *s, unsigned short *p) +{ if (s) + { unsigned long n; + char *r; + n = soap_strtoul(s, &r, 10); + if (s == r || *r || n > 65535) + soap->error = SOAP_TYPE; + *p = (unsigned short)n; + } + return soap->error; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +unsigned short * +SOAP_FMAC2 +soap_inunsignedShort(struct soap *soap, const char *tag, unsigned short *p, const char *type, int t) +{ if (soap_element_begin_in(soap, tag, 0, NULL)) + return NULL; +#ifndef WITH_LEAN + if (*soap->type + && soap_match_tag(soap, soap->type, type) + && soap_match_tag(soap, soap->type, ":unsignedShort") + && soap_match_tag(soap, soap->type, ":unsignedByte")) + { soap->error = SOAP_TYPE; + soap_revert(soap); + return NULL; + } +#endif + p = (unsigned short*)soap_id_enter(soap, soap->id, p, t, sizeof(unsigned short), 0, NULL, NULL, NULL); + if (*soap->href) + p = (unsigned short*)soap_id_forward(soap, soap->href, p, 0, t, 0, sizeof(unsigned short), 0, NULL); + else if (p) + { if (soap_s2unsignedShort(soap, soap_value(soap), p)) + return NULL; + } + if (soap->body && soap_element_end_in(soap, tag)) + return NULL; + return p; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +const char* +SOAP_FMAC2 +soap_unsignedInt2s(struct soap *soap, unsigned int n) +{ return soap_unsignedLong2s(soap, (unsigned long)n); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_outunsignedInt(struct soap *soap, const char *tag, int id, const unsigned int *p, const char *type, int n) +{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type) + || soap_string_out(soap, soap_unsignedLong2s(soap, (unsigned long)*p), 0)) + return soap->error; + return soap_element_end_out(soap, tag); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_s2unsignedInt(struct soap *soap, const char *s, unsigned int *p) +{ if (s) + { char *r; +#ifndef WITH_NOIO +#ifndef WITH_LEAN + soap_reset_errno; +#endif +#endif + *p = (unsigned int)soap_strtoul(s, &r, 10); + if ((s == r && (soap->mode & SOAP_XML_STRICT)) || *r +#ifndef WITH_NOIO +#ifndef WITH_LEAN + || soap_errno == SOAP_ERANGE +#endif +#endif + ) + soap->error = SOAP_TYPE; + } + return soap->error; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +unsigned int * +SOAP_FMAC2 +soap_inunsignedInt(struct soap *soap, const char *tag, unsigned int *p, const char *type, int t) +{ if (soap_element_begin_in(soap, tag, 0, NULL)) + return NULL; +#ifndef WITH_LEAN + if (*soap->type + && soap_match_tag(soap, soap->type, type) + && soap_match_tag(soap, soap->type, ":unsignedInt") + && soap_match_tag(soap, soap->type, ":unsignedShort") + && soap_match_tag(soap, soap->type, ":unsignedByte")) + { soap->error = SOAP_TYPE; + soap_revert(soap); + return NULL; + } +#endif + p = (unsigned int*)soap_id_enter(soap, soap->id, p, t, sizeof(unsigned int), 0, NULL, NULL, NULL); + if (*soap->href) + p = (unsigned int*)soap_id_forward(soap, soap->href, p, 0, t, 0, sizeof(unsigned int), 0, NULL); + else if (p) + { if (soap_s2unsignedInt(soap, soap_value(soap), p)) + return NULL; + } + if (soap->body && soap_element_end_in(soap, tag)) + return NULL; + return p; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +const char* +SOAP_FMAC2 +soap_unsignedLong2s(struct soap *soap, unsigned long n) +{ sprintf(soap->tmpbuf, "%lu", n); + return soap->tmpbuf; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_outunsignedLong(struct soap *soap, const char *tag, int id, const unsigned long *p, const char *type, int n) +{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type) + || soap_string_out(soap, soap_unsignedLong2s(soap, *p), 0)) + return soap->error; + return soap_element_end_out(soap, tag); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_s2unsignedLong(struct soap *soap, const char *s, unsigned long *p) +{ if (s) + { char *r; +#ifndef WITH_NOIO +#ifndef WITH_LEAN + soap_reset_errno; +#endif +#endif + *p = soap_strtoul(s, &r, 10); + if ((s == r && (soap->mode & SOAP_XML_STRICT)) || *r +#ifndef WITH_NOIO +#ifndef WITH_LEAN + || soap_errno == SOAP_ERANGE +#endif +#endif + ) + soap->error = SOAP_TYPE; + } + return soap->error; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +unsigned long * +SOAP_FMAC2 +soap_inunsignedLong(struct soap *soap, const char *tag, unsigned long *p, const char *type, int t) +{ if (soap_element_begin_in(soap, tag, 0, NULL)) + return NULL; +#ifndef WITH_LEAN + if (*soap->type + && soap_match_tag(soap, soap->type, type) + && soap_match_tag(soap, soap->type, ":unsignedInt") + && soap_match_tag(soap, soap->type, ":unsignedShort") + && soap_match_tag(soap, soap->type, ":unsignedByte")) + { soap->error = SOAP_TYPE; + soap_revert(soap); + return NULL; + } +#endif + p = (unsigned long*)soap_id_enter(soap, soap->id, p, t, sizeof(unsigned long), 0, NULL, NULL, NULL); + if (*soap->href) + p = (unsigned long*)soap_id_forward(soap, soap->href, p, 0, t, 0, sizeof(unsigned long), 0, NULL); + else if (p) + { if (soap_s2unsignedLong(soap, soap_value(soap), p)) + return NULL; + } + if (soap->body && soap_element_end_in(soap, tag)) + return NULL; + return p; +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEAN +SOAP_FMAC1 +const char* +SOAP_FMAC2 +soap_ULONG642s(struct soap *soap, ULONG64 n) +{ sprintf(soap->tmpbuf, SOAP_ULONG_FORMAT, n); + return soap->tmpbuf; +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEAN +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_outULONG64(struct soap *soap, const char *tag, int id, const ULONG64 *p, const char *type, int n) +{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type) + || soap_string_out(soap, soap_ULONG642s(soap, *p), 0)) + return soap->error; + return soap_element_end_out(soap, tag); +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEAN +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_s2ULONG64(struct soap *soap, const char *s, ULONG64 *p) +{ if (s) + { +#ifdef HAVE_STRTOULL + char *r; +#ifndef WITH_NOIO +#ifndef WITH_LEAN + soap_reset_errno; +#endif +#endif + *p = strtoull(s, &r, 10); + if ((s == r && (soap->mode & SOAP_XML_STRICT)) || *r +#ifndef WITH_NOIO +#ifndef WITH_LEAN + || soap_errno == SOAP_ERANGE +#endif +#endif + ) +#else +#ifdef HAVE_SSCANF + if (sscanf(s, SOAP_ULONG_FORMAT, p) != 1) +#endif +#endif + soap->error = SOAP_TYPE; + } + return soap->error; +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEAN +SOAP_FMAC1 +ULONG64 * +SOAP_FMAC2 +soap_inULONG64(struct soap *soap, const char *tag, ULONG64 *p, const char *type, int t) +{ if (soap_element_begin_in(soap, tag, 0, NULL)) + return NULL; + if (*soap->type + && soap_match_tag(soap, soap->type, type) + && soap_match_tag(soap, soap->type, ":positiveInteger") + && soap_match_tag(soap, soap->type, ":nonNegativeInteger") + && soap_match_tag(soap, soap->type, ":unsignedLong") + && soap_match_tag(soap, soap->type, ":unsignedInt") + && soap_match_tag(soap, soap->type, ":unsignedShort") + && soap_match_tag(soap, soap->type, ":unsignedByte")) + { soap->error = SOAP_TYPE; + soap_revert(soap); + return NULL; + } + p = (ULONG64*)soap_id_enter(soap, soap->id, p, t, sizeof(ULONG64), 0, NULL, NULL, NULL); + if (*soap->href) + p = (ULONG64*)soap_id_forward(soap, soap->href, p, 0, t, 0, sizeof(ULONG64), 0, NULL); + else if (p) + { if (soap_s2ULONG64(soap, soap_value(soap), p)) + return NULL; + } + if (soap->body && soap_element_end_in(soap, tag)) + return NULL; + return p; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_s2string(struct soap *soap, const char *s, char **t, long minlen, long maxlen) +{ if (s) + { if (!(*t = soap_strdup(soap, s))) + return soap->error = SOAP_EOM; + if (!(soap->mode & (SOAP_ENC_LATIN | SOAP_C_UTFSTRING))) + { char *r = *t; + /* remove non-ASCII chars */ + for (s = *t; *s; s++) + if (!(*s & 0x80)) + *r++ = *s; + *r = '\0'; + } + if ((soap->mode & SOAP_XML_STRICT)) + { long l = (long)strlen(*t); + if ((maxlen >= 0 && l > maxlen) || l < minlen) + soap->error = SOAP_LENGTH; + } + } + return soap->error; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_s2QName(struct soap *soap, const char *s, char **t, long minlen, long maxlen) +{ if (s) + { soap->labidx = 0; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Normalized namespace(s) of QNames '%s'", s)); + /* convert (by prefix normalize prefix) all QNames in s */ + for (;;) + { size_t n; + struct soap_nlist *np; + register const char *p; + /* skip blanks */ + while (*s && soap_blank(*s)) + s++; + if (!*s) + break; + /* find next QName */ + n = 1; + while (s[n] && !soap_blank(s[n])) + n++; + np = soap->nlist; + /* if there is no namespace stack, or prefix is "xml" then copy string */ + if (!np || !strncmp(s, "xml:", 4)) + { soap_append_lab(soap, s, n); + } + else /* we normalize the QName by replacing its prefix */ + { for (p = s; *p && p < s + n; p++) + if (*p == ':') + break; + if (*p == ':') + { size_t k = p - s; + while (np && (strncmp(np->id, s, k) || np->id[k])) + np = np->next; + p++; + } + else + { while (np && *np->id) + np = np->next; + p = s; + } + /* replace prefix */ + if (np) + { if (np->index >= 0 && soap->local_namespaces) + { const char *q = soap->local_namespaces[np->index].id; + if (q) + soap_append_lab(soap, q, strlen(q)); + } + else if (np->ns) + { soap_append_lab(soap, "\"", 1); + soap_append_lab(soap, np->ns, strlen(np->ns)); + soap_append_lab(soap, "\"", 1); + } + else + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "\nNamespace prefix of '%s' not defined (index=%d, URI=%s)\n", s, np->index, np->ns?np->ns:SOAP_STR_EOS)); + return soap->error = SOAP_NAMESPACE; + } + } + else if (s[n]) /* no namespace, part of string */ + { soap_append_lab(soap, s, n); + } + else /* no namespace: assume "" namespace */ + { soap_append_lab(soap, "\"\"", 2); + } + soap_append_lab(soap, ":", 1); + soap_append_lab(soap, p, n - (p-s)); + } + /* advance to next and add spacing */ + s += n; + if (*s) + soap_append_lab(soap, " ", 1); + } + soap_append_lab(soap, SOAP_STR_EOS, 1); + *t = soap_strdup(soap, soap->labbuf); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, " into '%s'\n", *t)); + if ((soap->mode & SOAP_XML_STRICT)) + { long l = (long)soap->labidx - 1; + if ((maxlen >= 0 && l > maxlen) || l < minlen) + soap->error = SOAP_LENGTH; + } + } + return soap->error; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +const char* +SOAP_FMAC2 +soap_QName2s(struct soap *soap, const char *s) +{ const char *t = NULL; + if (s) + { soap->labidx = 0; + for (;;) + { size_t n; + /* skip blanks */ + while (*s && soap_blank(*s)) + s++; + if (!*s) + break; + /* find next QName */ + n = 1; + while (s[n] && !soap_blank(s[n])) + n++; + /* normal prefix: pass string as is */ + if (*s != '"') + { soap_append_lab(soap, s, n); +#ifndef WITH_LEAN + if ((soap->mode & SOAP_XML_CANONICAL)) + { const char *r = strchr(s, ':'); + if (r) + soap_utilize_ns(soap, s, r - s); + } +#endif + } + else /* URL-based string prefix */ + { const char *q; + s++; + q = strchr(s, '"'); + if (q) + { struct Namespace *p = soap->local_namespaces; + if (p) + { for (; p->id; p++) + { if (p->ns) + if (!soap_tag_cmp(s, p->ns)) + break; + if (p->in) + if (!soap_tag_cmp(s, p->in)) + break; + } + } + /* URL is in the namespace table? */ + if (p && p->id) + { soap_append_lab(soap, p->id, strlen(p->id)); + } + else /* not in namespace table: create xmlns binding */ + { char *r = soap_strdup(soap, s); + r[q-s] = '\0'; + sprintf(soap->tmpbuf, "xmlns:_%d", soap->idnum++); + soap_set_attr(soap, soap->tmpbuf, r); + soap_append_lab(soap, soap->tmpbuf + 6, strlen(soap->tmpbuf + 6)); + } + soap_append_lab(soap, q + 1, n - (q-s) - 1); + } + } + /* advance to next and add spacing */ + s += n; + if (*s) + soap_append_lab(soap, " ", 1); + } + soap_append_lab(soap, SOAP_STR_EOS, 1); + t = soap_strdup(soap, soap->labbuf); + } + return t; +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEAN +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_s2wchar(struct soap *soap, const char *s, wchar_t **t, long minlen, long maxlen) +{ if (s) + { wchar_t *r; + *t = r = (wchar_t*)soap_malloc(soap, sizeof(wchar_t) * (strlen(s) + 1)); + if (!r) + return soap->error; + if (soap->mode & SOAP_ENC_LATIN) + { while (*s) + *r++ = (wchar_t)*s++; + } + else + { /* Convert UTF8 to wchar */ + while (*s) + { register soap_wchar c, c1, c2, c3, c4; + c = (unsigned char)*s++; + if (c < 0x80) + *r++ = (wchar_t)c; + else + { c1 = (soap_wchar)*s++ & 0x3F; + if (c < 0xE0) + *r++ = (wchar_t)(((soap_wchar)(c & 0x1F) << 6) | c1); + else + { c2 = (soap_wchar)*s++ & 0x3F; + if (c < 0xF0) + *r++ = (wchar_t)(((soap_wchar)(c & 0x0F) << 12) | (c1 << 6) | c2); + else + { c3 = (soap_wchar)*s++ & 0x3F; + if (c < 0xF8) + *r++ = (wchar_t)(((soap_wchar)(c & 0x07) << 18) | (c1 << 12) | (c2 << 6) | c3); + else + { c4 = (soap_wchar)*s++ & 0x3F; + if (c < 0xFC) + *r++ = (wchar_t)(((soap_wchar)(c & 0x03) << 24) | (c1 << 18) | (c2 << 12) | (c3 << 6) | c4); + else + *r++ = (wchar_t)(((soap_wchar)(c & 0x01) << 30) | (c1 << 24) | (c2 << 18) | (c3 << 12) | (c4 << 6) | (soap_wchar)(*s++ & 0x3F)); + } + } + } + } + } + } + *r = L'\0'; + if ((soap->mode & SOAP_XML_STRICT)) + { long l = (long)(r - *t); + if ((maxlen >= 0 && l > maxlen) || l < minlen) + soap->error = SOAP_LENGTH; + } + } + return soap->error; +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEAN +SOAP_FMAC1 +const char* +SOAP_FMAC2 +soap_wchar2s(struct soap *soap, const wchar_t *s) +{ register soap_wchar c; + register char *r, *t; + const wchar_t *q = s; + size_t n = 0; + while ((c = *q++)) + { if (c > 0 && c < 0x80) + n++; + else + n += 6; + } + r = t = (char*)soap_malloc(soap, n + 1); + if (r) + { /* Convert wchar to UTF8 */ + while ((c = *s++)) + { if (c > 0 && c < 0x80) + *t++ = (char)c; + else + { if (c < 0x0800) + *t++ = (char)(0xC0 | ((c >> 6) & 0x1F)); + else + { if (c < 0x010000) + *t++ = (char)(0xE0 | ((c >> 12) & 0x0F)); + else + { if (c < 0x200000) + *t++ = (char)(0xF0 | ((c >> 18) & 0x07)); + else + { if (c < 0x04000000) + *t++ = (char)(0xF8 | ((c >> 24) & 0x03)); + else + { *t++ = (char)(0xFC | ((c >> 30) & 0x01)); + *t++ = (char)(0x80 | ((c >> 24) & 0x3F)); + } + *t++ = (char)(0x80 | ((c >> 18) & 0x3F)); + } + *t++ = (char)(0x80 | ((c >> 12) & 0x3F)); + } + *t++ = (char)(0x80 | ((c >> 6) & 0x3F)); + } + *t++ = (char)(0x80 | (c & 0x3F)); + } + } + *t = '\0'; + } + return r; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_outstring(struct soap *soap, const char *tag, int id, char *const*p, const char *type, int n) +{ id = soap_element_id(soap, tag, id, *p, NULL, 0, type, n); + if (id < 0) + return soap->error; + if (!**p && (soap->mode & SOAP_C_NILSTRING)) + return soap_element_null(soap, tag, id, type); + if (soap_element_begin_out(soap, tag, id, type) + || soap_string_out(soap, *p, 0) + || soap_element_end_out(soap, tag)) + return soap->error; + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +char ** +SOAP_FMAC2 +soap_instring(struct soap *soap, const char *tag, char **p, const char *type, int t, int flag, long minlen, long maxlen) +{ if (soap_element_begin_in(soap, tag, 1, NULL)) + { if (!tag || *tag != '-' || soap->error != SOAP_NO_TAG) + return NULL; + soap->error = SOAP_OK; + } + if (!p) + { if (!(p = (char**)soap_malloc(soap, sizeof(char*)))) + return NULL; + } + if (soap->null) + *p = NULL; + else if (soap->body) + { *p = soap_string_in(soap, flag, minlen, maxlen); + if (!*p || !(char*)soap_id_enter(soap, soap->id, *p, t, sizeof(char*), 0, NULL, NULL, NULL)) + return NULL; + if (!**p && tag && *tag == '-') + { soap->error = SOAP_NO_TAG; + return NULL; + } + } + else if (tag && *tag == '-') + { soap->error = SOAP_NO_TAG; + return NULL; + } + else + *p = soap_strdup(soap, SOAP_STR_EOS); + if (*soap->href) + p = (char**)soap_id_lookup(soap, soap->href, (void**)p, t, sizeof(char**), 0); + if (soap->body && soap_element_end_in(soap, tag)) + return NULL; + return p; +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_outwstring(struct soap *soap, const char *tag, int id, wchar_t *const*p, const char *type, int n) +{ id = soap_element_id(soap, tag, id, *p, NULL, 0, type, n); + if (id < 0) + return soap->error; + if (!**p && (soap->mode & SOAP_C_NILSTRING)) + return soap_element_null(soap, tag, id, type); + if (soap_element_begin_out(soap, tag, id, type) + || soap_wstring_out(soap, *p, 0) + || soap_element_end_out(soap, tag)) + return soap->error; + return SOAP_OK; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_2 +SOAP_FMAC1 +wchar_t ** +SOAP_FMAC2 +soap_inwstring(struct soap *soap, const char *tag, wchar_t **p, const char *type, int t, long minlen, long maxlen) +{ if (soap_element_begin_in(soap, tag, 1, NULL)) + { if (!tag || *tag != '-' || soap->error != SOAP_NO_TAG) + return NULL; + soap->error = SOAP_OK; + } + if (!p) + { if (!(p = (wchar_t**)soap_malloc(soap, sizeof(wchar_t*)))) + return NULL; + } + if (soap->body) + { *p = soap_wstring_in(soap, 1, minlen, maxlen); + if (!*p || !(wchar_t*)soap_id_enter(soap, soap->id, *p, t, sizeof(wchar_t*), 0, NULL, NULL, NULL)) + return NULL; + if (!**p && tag && *tag == '-') + { soap->error = SOAP_NO_TAG; + return NULL; + } + } + else if (tag && *tag == '-') + { soap->error = SOAP_NO_TAG; + return NULL; + } + else if (soap->null) + *p = NULL; + else + *p = soap_wstrdup(soap, (wchar_t*)SOAP_STR_EOS); + if (*soap->href) + p = (wchar_t**)soap_id_lookup(soap, soap->href, (void**)p, t, sizeof(wchar_t**), 0); + if (soap->body && soap_element_end_in(soap, tag)) + return NULL; + return p; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEAN +SOAP_FMAC1 +time_t +SOAP_FMAC2 +soap_timegm(struct tm *T) +{ +#if defined(HAVE_TIMEGM) + return timegm(T); +#else + time_t t, g, z; + struct tm tm; + t = mktime(T); + if (t == (time_t)-1) + return (time_t)-1; +#ifdef HAVE_GMTIME_R + gmtime_r(&t, &tm); +#else + tm = *gmtime(&t); +#endif + tm.tm_isdst = 0; + g = mktime(&tm); + if (g == (time_t)-1) + return (time_t)-1; + z = g - t; + return t - z; +#endif +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEAN +SOAP_FMAC1 +const char* +SOAP_FMAC2 +soap_dateTime2s(struct soap *soap, time_t n) +{ struct tm T, *pT = &T; +#if defined(HAVE_GMTIME_R) + if (gmtime_r(&n, pT)) + strftime(soap->tmpbuf, sizeof(soap->tmpbuf), "%Y-%m-%dT%H:%M:%SZ", pT); +#elif defined(HAVE_GMTIME) + if ((pT = gmtime(&n))) + strftime(soap->tmpbuf, sizeof(soap->tmpbuf), "%Y-%m-%dT%H:%M:%SZ", pT); +#elif defined(HAVE_GETTIMEOFDAY) + struct timezone tz; + memset((void*)&tz, 0, sizeof(tz)); +#if defined(HAVE_LOCALTIME_R) + if (localtime_r(&n, pT)) + { struct timeval tv; + gettimeofday(&tv, &tz); + strftime(soap->tmpbuf, sizeof(soap->tmpbuf), "%Y-%m-%dT%H:%M:%S", pT); + sprintf(soap->tmpbuf + strlen(soap->tmpbuf), "%+03d:%02d", -tz.tz_minuteswest/60+(pT->tm_isdst!=0), abs(tz.tz_minuteswest)%60); + } +#else + if ((pT = localtime(&n))) + { struct timeval tv; + gettimeofday(&tv, &tz); + strftime(soap->tmpbuf, sizeof(soap->tmpbuf), "%Y-%m-%dT%H:%M:%S", pT); + sprintf(soap->tmpbuf + strlen(soap->tmpbuf), "%+03d:%02d", -tz.tz_minuteswest/60+(pT->tm_isdst!=0), abs(tz.tz_minuteswest)%60); + } +#endif +#elif defined(HAVE_FTIME) + struct timeb t; + memset((void*)&t, 0, sizeof(t)); +#if defined(HAVE_LOCALTIME_R) + if (localtime_r(&n, pT)) + { +#ifdef __BORLANDC__ + ::ftime(&t); +#else + ftime(&t); +#endif + strftime(soap->tmpbuf, sizeof(soap->tmpbuf), "%Y-%m-%dT%H:%M:%S", pT); + sprintf(soap->tmpbuf + strlen(soap->tmpbuf), "%+03d:%02d", -t.timezone/60+(pT->tm_isdst!=0), abs(t.timezone)%60); + } +#else + if ((pT = localtime(&n))) + { +#ifdef __BORLANDC__ + ::ftime(&t); +#else + ftime(&t); +#endif + strftime(soap->tmpbuf, sizeof(soap->tmpbuf), "%Y-%m-%dT%H:%M:%S", pT); + sprintf(soap->tmpbuf + strlen(soap->tmpbuf), "%+03d:%02d", -t.timezone/60+(pT->tm_isdst!=0), abs(t.timezone)%60); + } +#endif +#elif defined(HAVE_LOCALTIME_R) + if (localtime_r(&n, pT)) + strftime(soap->tmpbuf, sizeof(soap->tmpbuf), "%Y-%m-%dT%H:%M:%S", pT); +#else + if ((pT = localtime(&n))) + strftime(soap->tmpbuf, sizeof(soap->tmpbuf), "%Y-%m-%dT%H:%M:%S", pT); +#endif + else + strcpy(soap->tmpbuf, "1969-12-31T23:59:59Z"); + return soap->tmpbuf; +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEAN +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_outdateTime(struct soap *soap, const char *tag, int id, const time_t *p, const char *type, int n) +{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type) + || soap_string_out(soap, soap_dateTime2s(soap, *p), 0)) + return soap->error; + return soap_element_end_out(soap, tag); +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEAN +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_s2dateTime(struct soap *soap, const char *s, time_t *p) +{ if (s) + { char zone[32]; + struct tm T; + const char *t; + *zone = '\0'; + memset((void*)&T, 0, sizeof(T)); + if (strchr(s, '-')) + t = "%d-%d-%dT%d:%d:%d%31s"; + else if (strchr(s, ':')) + t = "%4d%2d%2dT%d:%d:%d%31s"; + else /* parse non-XSD-standard alternative ISO 8601 format */ + t = "%4d%2d%2dT%2d%2d%2d%31s"; + if (sscanf(s, t, &T.tm_year, &T.tm_mon, &T.tm_mday, &T.tm_hour, &T.tm_min, &T.tm_sec, zone) < 6) + return soap->error = SOAP_TYPE; + if (T.tm_year == 1) + T.tm_year = 70; + else + T.tm_year -= 1900; + T.tm_mon--; + if (*zone == '.') + { for (s = zone + 1; *s; s++) + if (*s < '0' || *s > '9') + break; + } + else + s = zone; + if (*s) + { +#ifndef WITH_NOZONE + if (*s == '+' || *s == '-') + { int h = 0, m = 0; + if (s[3] == ':') + { /* +hh:mm */ + sscanf(s, "%d:%d", &h, &m); + if (h < 0) + m = -m; + } + else /* +hhmm */ + { m = (int)atol(s); + h = m / 100; + m = m % 100; + } + T.tm_min -= m; + T.tm_hour -= h; + /* put hour and min in range */ + T.tm_hour += T.tm_min / 60; + T.tm_min %= 60; + if (T.tm_min < 0) + { T.tm_min += 60; + T.tm_hour--; + } + T.tm_mday += T.tm_hour / 24; + T.tm_hour %= 24; + if (T.tm_hour < 0) + { T.tm_hour += 24; + T.tm_mday--; + } + /* note: day of the month may be out of range, timegm() handles it */ + } +#endif + *p = soap_timegm(&T); + } + else /* no UTC or timezone, so assume we got a localtime */ + { T.tm_isdst = -1; + *p = mktime(&T); + } + } + return soap->error; +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEAN +SOAP_FMAC1 +time_t * +SOAP_FMAC2 +soap_indateTime(struct soap *soap, const char *tag, time_t *p, const char *type, int t) +{ if (soap_element_begin_in(soap, tag, 0, NULL)) + return NULL; + if (*soap->type + && soap_match_tag(soap, soap->type, type) + && soap_match_tag(soap, soap->type, ":dateTime")) + { soap->error = SOAP_TYPE; + soap_revert(soap); + return NULL; + } + p = (time_t*)soap_id_enter(soap, soap->id, p, t, sizeof(time_t), 0, NULL, NULL, NULL); + if (*soap->href) + p = (time_t*)soap_id_forward(soap, soap->href, p, 0, t, 0, sizeof(time_t), 0, NULL); + else if (p) + { if (soap_s2dateTime(soap, soap_value(soap), p)) + return NULL; + } + if (soap->body && soap_element_end_in(soap, tag)) + return NULL; + return p; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_outliteral(struct soap *soap, const char *tag, char *const*p, const char *type) +{ int i; + const char *t = NULL; + if (tag && *tag != '-') + { if (soap->local_namespaces && (t = strchr(tag, ':'))) + { strncpy(soap->tmpbuf, tag, t-tag); + soap->tmpbuf[t-tag] = '\0'; + for (i = 0; soap->local_namespaces[i].id; i++) + if (!strcmp(soap->tmpbuf, soap->local_namespaces[i].id)) + break; + t++; + if (soap_element(soap, t, 0, type) + || soap_attribute(soap, "xmlns", soap->local_namespaces[i].ns ? soap->local_namespaces[i].ns : SOAP_STR_EOS) + || soap_element_start_end_out(soap, NULL)) + return soap->error; + } + else + { t = tag; + if (soap_element_begin_out(soap, t, 0, type)) + return soap->error; + } + } + if (p && *p) + { if (soap_send(soap, *p)) + return soap->error; + } + if (t) + return soap_element_end_out(soap, t); + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +char ** +SOAP_FMAC2 +soap_inliteral(struct soap *soap, const char *tag, char **p) +{ if (soap_element_begin_in(soap, tag, 1, NULL)) + { if (soap->error != SOAP_NO_TAG || soap_unget(soap, soap_get(soap)) == SOAP_TT) + return NULL; + soap->error = SOAP_OK; + } + if (!p) + { if (!(p = (char**)soap_malloc(soap, sizeof(char*)))) + return NULL; + } + if (soap->body || (tag && *tag == '-')) + { *p = soap_string_in(soap, 0, -1, -1); + if (!*p) + return NULL; + if (!**p && tag && *tag == '-') + { soap->error = SOAP_NO_TAG; + return NULL; + } + } + else if (soap->null) + *p = NULL; + else + *p = soap_strdup(soap, SOAP_STR_EOS); + if (soap->body && soap_element_end_in(soap, tag)) + return NULL; + return p; +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_outwliteral(struct soap *soap, const char *tag, wchar_t *const*p, const char *type) +{ int i; + const char *t = NULL; + if (tag && *tag != '-') + { if (soap->local_namespaces && (t = strchr(tag, ':'))) + { strncpy(soap->tmpbuf, tag, t-tag); + soap->tmpbuf[t-tag] = '\0'; + for (i = 0; soap->local_namespaces[i].id; i++) + if (!strcmp(soap->tmpbuf, soap->local_namespaces[i].id)) + break; + t++; + if (soap_element(soap, t, 0, type) + || soap_attribute(soap, "xmlns", soap->local_namespaces[i].ns ? soap->local_namespaces[i].ns : SOAP_STR_EOS) + || soap_element_start_end_out(soap, NULL)) + return soap->error; + } + else + { t = tag; + if (soap_element_begin_out(soap, t, 0, type)) + return soap->error; + } + if (soap_send(soap, soap->tmpbuf)) + return soap->error; + } + if (p) + { wchar_t c; + const wchar_t *s = *p; + while ((c = *s++)) + { if (soap_pututf8(soap, (unsigned long)c)) + return soap->error; + } + } + if (t) + return soap_element_end_out(soap, t); + return SOAP_OK; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_2 +SOAP_FMAC1 +wchar_t ** +SOAP_FMAC2 +soap_inwliteral(struct soap *soap, const char *tag, wchar_t **p) +{ if (soap_element_begin_in(soap, tag, 1, NULL)) + { if (soap->error != SOAP_NO_TAG || soap_unget(soap, soap_get(soap)) == SOAP_TT) + return NULL; + soap->error = SOAP_OK; + } + if (!p) + { if (!(p = (wchar_t**)soap_malloc(soap, sizeof(wchar_t*)))) + return NULL; + } + if (soap->body) + { *p = soap_wstring_in(soap, 0, -1, -1); + if (!*p) + return NULL; + if (!**p && tag && *tag == '-') + { soap->error = SOAP_NO_TAG; + return NULL; + } + } + else if (tag && *tag == '-') + { soap->error = SOAP_NO_TAG; + return NULL; + } + else if (soap->null) + *p = NULL; + else + *p = soap_wstrdup(soap, (wchar_t*)SOAP_STR_EOS); + if (soap->body && soap_element_end_in(soap, tag)) + return NULL; + return p; +} +#endif +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +const char * +SOAP_FMAC2 +soap_value(struct soap *soap) +{ register size_t i; + register soap_wchar c = 0; + register char *s = soap->tmpbuf; + if (!soap->body) + return SOAP_STR_EOS; + do c = soap_get(soap); + while (soap_blank(c)); + for (i = 0; i < sizeof(soap->tmpbuf) - 1; i++) + { if (c == SOAP_TT || (int)c == EOF) + break; + *s++ = (char)c; + c = soap_get(soap); + } + for (s--; i > 0; i--, s--) + { if (!soap_blank(*s)) + break; + } + s[1] = '\0'; + if ((int)c == EOF || c == SOAP_TT) + soap_unget(soap, c); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Element content value='%s'\n", soap->tmpbuf)); +#ifdef WITH_DOM + if ((soap->mode & SOAP_XML_DOM) && soap->dom) + soap->dom->data = soap_strdup(soap, soap->tmpbuf); +#endif + return soap->tmpbuf; /* return non-null pointer */ +} +#endif + +/******************************************************************************/ +#if !defined(WITH_LEANER) || !defined(WITH_NOHTTP) +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_getline(struct soap *soap, char *s, int len) +{ int i = len; + soap_wchar c = 0; + for (;;) + { while (--i > 0) + { c = soap_getchar(soap); + if (c == '\r' || c == '\n') + break; + if ((int)c == EOF) + return soap->error = SOAP_EOF; + *s++ = (char)c; + } + if (c != '\n') + c = soap_getchar(soap); /* got \r or something else, now get \n */ + if (c == '\n') + { *s = '\0'; + if (i+1 == len) /* empty line: end of HTTP/MIME header */ + break; + c = soap_get0(soap); + if (c != ' ' && c != '\t') /* HTTP line continuation? */ + break; + } + else if ((int)c == EOF) + return soap->error = SOAP_EOF; + if (i < 0) + return soap->error = SOAP_HDR; + } + return SOAP_OK; +} +#endif +#endif + +/******************************************************************************/ +#ifndef PALM_1 +static size_t +soap_count_attachments(struct soap *soap) +{ +#ifndef WITH_LEANER + register struct soap_multipart *content; + register size_t count = soap->count; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Calculating the message size with attachments, current count=%lu\n", (unsigned long)count)); + if ((soap->mode & SOAP_ENC_DIME) && !(soap->mode & SOAP_ENC_MTOM)) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Calculating the size of DIME attachments\n")); + for (content = soap->dime.first; content; content = content->next) + { count += 12 + ((content->size+3)&(~3)); + if (content->id) + count += ((strlen(content->id)+3)&(~3)); + if (content->type) + count += ((strlen(content->type)+3)&(~3)); + if (content->options) + count += ((((unsigned char)content->options[2] << 8) | ((unsigned char)content->options[3]))+7)&(~3); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Size of DIME attachment content is %lu bytes\n", (unsigned long)content->size)); + } + } + if ((soap->mode & SOAP_ENC_MIME) && soap->mime.boundary) + { register size_t n = strlen(soap->mime.boundary); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Calculating the size of MIME attachments\n")); + for (content = soap->mime.first; content; content = content->next) + { register const char *s; + /* count \r\n--boundary\r\n */ + count += 6 + n; + /* count Content-Type: ...\r\n */ + if (content->type) + count += 16 + strlen(content->type); + /* count Content-Transfer-Encoding: ...\r\n */ + s = soap_code_str(mime_codes, content->encoding); + if (s) + count += 29 + strlen(s); + /* count Content-ID: ...\r\n */ + if (content->id) + count += 14 + strlen(content->id); + /* count Content-Location: ...\r\n */ + if (content->location) + count += 20 + strlen(content->location); + /* count Content-Description: ...\r\n */ + if (content->description) + count += 23 + strlen(content->description); + /* count \r\n...content */ + count += 2 + content->size; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Size of MIME attachment content is %lu bytes\n", (unsigned long)content->size)); + } + /* count \r\n--boundary-- */ + count += 6 + n; + } + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "New count is %lu bytes\n", (unsigned long)count)); + return count; +#else + return soap->count; +#endif +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +static int +soap_putdimefield(struct soap *soap, const char *s, size_t n) +{ if (soap_send_raw(soap, s, n)) + return soap->error; + return soap_send_raw(soap, SOAP_STR_PADDING, -(long)n&3); +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +SOAP_FMAC1 +char * +SOAP_FMAC2 +soap_dime_option(struct soap *soap, unsigned short optype, const char *option) +{ size_t n; + char *s = NULL; + if (option) + { n = strlen(option); + s = (char*)soap_malloc(soap, n + 5); + if (s) + { s[0] = (char)(optype >> 8); + s[1] = (char)(optype & 0xFF); + s[2] = (char)(n >> 8); + s[3] = (char)(n & 0xFF); + strcpy(s + 4, option); + } + } + return s; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_putdimehdr(struct soap *soap) +{ unsigned char tmp[12]; + size_t optlen = 0, idlen = 0, typelen = 0; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Put DIME header id='%s'\n", soap->dime.id?soap->dime.id:SOAP_STR_EOS)); + if (soap->dime.options) + optlen = (((unsigned char)soap->dime.options[2] << 8) | ((unsigned char)soap->dime.options[3])) + 4; + if (soap->dime.id) + { idlen = strlen(soap->dime.id); + if (idlen > 0x0000FFFF) + idlen = 0x0000FFFF; + } + if (soap->dime.type) + { typelen = strlen(soap->dime.type); + if (typelen > 0x0000FFFF) + typelen = 0x0000FFFF; + } + tmp[0] = SOAP_DIME_VERSION | (soap->dime.flags & 0x7); + tmp[1] = soap->dime.flags & 0xF0; + tmp[2] = (char)(optlen >> 8); + tmp[3] = (char)(optlen & 0xFF); + tmp[4] = (char)(idlen >> 8); + tmp[5] = (char)(idlen & 0xFF); + tmp[6] = (char)(typelen >> 8); + tmp[7] = (char)(typelen & 0xFF); + tmp[8] = (char)(soap->dime.size >> 24); + tmp[9] = (char)((soap->dime.size >> 16) & 0xFF); + tmp[10] = (char)((soap->dime.size >> 8) & 0xFF); + tmp[11] = (char)(soap->dime.size & 0xFF); + if (soap_send_raw(soap, (char*)tmp, 12) + || soap_putdimefield(soap, soap->dime.options, optlen) + || soap_putdimefield(soap, soap->dime.id, idlen) + || soap_putdimefield(soap, soap->dime.type, typelen)) + return soap->error; + return SOAP_OK; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_putdime(struct soap *soap) +{ struct soap_multipart *content; + if (!(soap->mode & SOAP_ENC_DIME)) + return SOAP_OK; + for (content = soap->dime.first; content; content = content->next) + { void *handle; + soap->dime.size = content->size; + soap->dime.id = content->id; + soap->dime.type = content->type; + soap->dime.options = content->options; + soap->dime.flags = SOAP_DIME_VERSION | SOAP_DIME_MEDIA; + if (soap->fdimereadopen && ((handle = soap->fdimereadopen(soap, (void*)content->ptr, content->id, content->type, content->options)) || soap->error)) + { size_t size = content->size; + if (!handle) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "fdimereadopen failed\n")); + return soap->error; + } + if (!size && ((soap->mode & SOAP_ENC_XML) || (soap->mode & SOAP_IO) == SOAP_IO_CHUNK || (soap->mode & SOAP_IO) == SOAP_IO_STORE)) + { size_t chunksize = sizeof(soap->tmpbuf); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Chunked streaming DIME\n")); + do + { size = soap->fdimeread(soap, handle, soap->tmpbuf, chunksize); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "fdimeread returned %lu bytes\n", (unsigned long)size)); + if (size < chunksize) + { soap->dime.flags &= ~SOAP_DIME_CF; + if (!content->next) + soap->dime.flags |= SOAP_DIME_ME; + } + else + soap->dime.flags |= SOAP_DIME_CF; + soap->dime.size = size; + if (soap_putdimehdr(soap) + || soap_putdimefield(soap, soap->tmpbuf, size)) + break; + if (soap->dime.id) + { soap->dime.flags &= ~(SOAP_DIME_MB | SOAP_DIME_MEDIA); + soap->dime.id = NULL; + soap->dime.type = NULL; + soap->dime.options = NULL; + } + } while (size >= chunksize); + } + else + { if (!content->next) + soap->dime.flags |= SOAP_DIME_ME; + if (soap_putdimehdr(soap)) + return soap->error; + do + { size_t bufsize; + if (size < sizeof(soap->tmpbuf)) + bufsize = size; + else + bufsize = sizeof(soap->tmpbuf); + if (!(bufsize = soap->fdimeread(soap, handle, soap->tmpbuf, bufsize))) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "fdimeread failed: insufficient data (%lu bytes remaining from %lu bytes)\n", (unsigned long)size, (unsigned long)content->size)); + soap->error = SOAP_EOF; + break; + } + if (soap_send_raw(soap, soap->tmpbuf, bufsize)) + break; + size -= bufsize; + } while (size); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "fdimereadclose\n")); + soap_send_raw(soap, SOAP_STR_PADDING, -(long)soap->dime.size&3); + } + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "fdimereadclose\n")); + if (soap->fdimereadclose) + soap->fdimereadclose(soap, handle); + } + else + { if (!content->next) + soap->dime.flags |= SOAP_DIME_ME; + if (soap_putdimehdr(soap) + || soap_putdimefield(soap, (char*)content->ptr, content->size)) + return soap->error; + } + } + return SOAP_OK; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +static char * +soap_getdimefield(struct soap *soap, size_t n) +{ register soap_wchar c; + register size_t i; + register char *s; + register char *p = NULL; + if (n) + { p = (char*)soap_malloc(soap, n + 1); + if (p) + { s = p; + for (i = n; i > 0; i--) + { if ((int)(c = soap_get1(soap)) == EOF) + { soap->error = SOAP_EOF; + return NULL; + } + *s++ = (char)c; + } + *s = '\0'; + if ((soap->error = soap_move(soap, -(long)n&3))) + return NULL; + } + else + soap->error = SOAP_EOM; + } + return p; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_getdimehdr(struct soap *soap) +{ register soap_wchar c; + register char *s; + register int i; + unsigned char tmp[12]; + size_t optlen, idlen, typelen; + if (!(soap->mode & SOAP_ENC_DIME)) + return soap->error = SOAP_DIME_END; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Get DIME header\n")); + if (soap->dime.buflen || soap->dime.chunksize) + { if (soap_move(soap, (long)(soap->dime.size - soap_tell(soap)))) + return soap->error = SOAP_EOF; + soap_unget(soap, soap_getchar(soap)); /* skip padding and get hdr */ + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "... From chunked\n")); + return SOAP_OK; + } + s = (char*)tmp; + for (i = 12; i > 0; i--) + { if ((int)(c = soap_getchar(soap)) == EOF) + return soap->error = SOAP_EOF; + *s++ = (char)c; + } + if ((tmp[0] & 0xF8) != SOAP_DIME_VERSION) + return soap->error = SOAP_DIME_MISMATCH; + soap->dime.flags = (tmp[0] & 0x7) | (tmp[1] & 0xF0); + optlen = (tmp[2] << 8) | tmp[3]; + idlen = (tmp[4] << 8) | tmp[5]; + typelen = (tmp[6] << 8) | tmp[7]; + soap->dime.size = (tmp[8] << 24) | (tmp[9] << 16) | (tmp[10] << 8) | tmp[11]; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "DIME size=%lu flags=0x%X\n", (unsigned long)soap->dime.size, soap->dime.flags)); + if (!(soap->dime.options = soap_getdimefield(soap, optlen)) && soap->error) + return soap->error; + if (!(soap->dime.id = soap_getdimefield(soap, idlen)) && soap->error) + return soap->error; + if (!(soap->dime.type = soap_getdimefield(soap, typelen)) && soap->error) + return soap->error; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "DIME id=%s, type=%s, options=%s\n", soap->dime.id?soap->dime.id:SOAP_STR_EOS, soap->dime.type?soap->dime.type:"", soap->dime.options?soap->dime.options+4:SOAP_STR_EOS)); + if (soap->dime.flags & SOAP_DIME_ME) + soap->mode &= ~SOAP_ENC_DIME; + return SOAP_OK; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_getdime(struct soap *soap) +{ while (soap->dime.flags & SOAP_DIME_CF) + { if (soap_getdimehdr(soap)) + return soap->error; + if (soap_move(soap, (long)soap->dime.size)) + return soap->error = SOAP_EOF; + } + if (soap_move(soap, (long)(((soap->dime.size+3)&(~3))-soap_tell(soap)))) + return soap->error = SOAP_EOF; + for (;;) + { register struct soap_multipart *content; + if (soap_getdimehdr(soap)) + break; + if (soap->fdimewriteopen && ((soap->dime.ptr = (char*)soap->fdimewriteopen(soap, soap->dime.id, soap->dime.type, soap->dime.options)) || soap->error)) + { const char *id, *type, *options; + size_t size, n; + if (!soap->dime.ptr) + return soap->error; + id = soap->dime.id; + type = soap->dime.type; + options = soap->dime.options; + for (;;) + { size = soap->dime.size; + for (;;) + { n = soap->buflen - soap->bufidx; + if (size < n) + n = size; + if ((soap->error = soap->fdimewrite(soap, (void*)soap->dime.ptr, soap->buf + soap->bufidx, n))) + break; + size -= n; + if (!size) + { soap->bufidx += n; + break; + } + if (soap_recv(soap)) + { soap->error = SOAP_EOF; + goto end; + } + } + if (soap_move(soap, -(long)soap->dime.size&3)) + { soap->error = SOAP_EOF; + break; + } + if (!(soap->dime.flags & SOAP_DIME_CF)) + break; + if (soap_getdimehdr(soap)) + break; + } +end: + if (soap->fdimewriteclose) + soap->fdimewriteclose(soap, (void*)soap->dime.ptr); + soap->dime.size = 0; + soap->dime.id = id; + soap->dime.type = type; + soap->dime.options = options; + } + else if (soap->dime.flags & SOAP_DIME_CF) + { const char *id, *type, *options; + id = soap->dime.id; + type = soap->dime.type; + options = soap->dime.options; + if (soap_new_block(soap) == NULL) + return SOAP_EOM; + for (;;) + { register soap_wchar c; + register size_t i; + register char *s; + s = (char*)soap_push_block(soap, NULL, soap->dime.size); + if (!s) + return soap->error = SOAP_EOM; + for (i = soap->dime.size; i > 0; i--) + { if ((int)(c = soap_get1(soap)) == EOF) + return soap->error = SOAP_EOF; + *s++ = (char)c; + } + if (soap_move(soap, -(long)soap->dime.size&3)) + return soap->error = SOAP_EOF; + if (!(soap->dime.flags & SOAP_DIME_CF)) + break; + if (soap_getdimehdr(soap)) + return soap->error; + } + soap->dime.size = soap->blist->size++; /* allocate one more for '\0' */ + if (!(soap->dime.ptr = soap_save_block(soap, NULL, NULL, 0))) + return soap->error; + soap->dime.ptr[soap->dime.size] = '\0'; /* force 0-terminated */ + soap->dime.id = id; + soap->dime.type = type; + soap->dime.options = options; + } + else + soap->dime.ptr = soap_getdimefield(soap, soap->dime.size); + content = soap_new_multipart(soap, &soap->dime.first, &soap->dime.last, soap->dime.ptr, soap->dime.size); + if (!content) + return soap->error = SOAP_EOM; + content->id = soap->dime.id; + content->type = soap->dime.type; + content->options = soap->dime.options; + if (soap->error) + return soap->error; + soap_resolve_attachment(soap, content); + } + if (soap->error != SOAP_DIME_END) + return soap->error; + return soap->error = SOAP_OK; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_getmimehdr(struct soap *soap) +{ struct soap_multipart *content; + do + { if (soap_getline(soap, soap->msgbuf, sizeof(soap->msgbuf))) + return soap->error; + } + while (!*soap->msgbuf); + if (soap->msgbuf[0] == '-' && soap->msgbuf[1] == '-') + { char *s = soap->msgbuf + strlen(soap->msgbuf) - 1; + /* remove white space */ + while (soap_blank(*s)) + s--; + s[1] = '\0'; + if (soap->mime.boundary) + { if (strcmp(soap->msgbuf + 2, soap->mime.boundary)) + return soap->error = SOAP_MIME_ERROR; + } + else + soap->mime.boundary = soap_strdup(soap, soap->msgbuf + 2); + if (soap_getline(soap, soap->msgbuf, sizeof(soap->msgbuf))) + return soap->error; + } + if (soap_set_mime_attachment(soap, NULL, 0, SOAP_MIME_NONE, NULL, NULL, NULL, NULL)) + return soap->error = SOAP_EOM; + content = soap->mime.last; + for (;;) + { register char *key = soap->msgbuf; + register char *val; + if (!*key) + break; + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "MIME header: %s\n", key)); + val = strchr(soap->msgbuf, ':'); + if (val) + { *val = '\0'; + do val++; + while (*val && *val <= 32); + if (!soap_tag_cmp(key, "Content-ID")) + content->id = soap_strdup(soap, val); + else if (!soap_tag_cmp(key, "Content-Location")) + content->location = soap_strdup(soap, val); + else if (!soap_tag_cmp(key, "Content-Disposition")) + content->id = soap_strdup(soap, soap_get_header_attribute(soap, val, "name")); + else if (!soap_tag_cmp(key, "Content-Type")) + content->type = soap_strdup(soap, val); + else if (!soap_tag_cmp(key, "Content-Description")) + content->description = soap_strdup(soap, val); + else if (!soap_tag_cmp(key, "Content-Transfer-Encoding")) + content->encoding = (enum soap_mime_encoding)soap_code_int(mime_codes, val, (long)SOAP_MIME_NONE); + } + if (soap_getline(soap, key, sizeof(soap->msgbuf))) + return soap->error; + } + return SOAP_OK; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_getmime(struct soap *soap) +{ while (soap_get_mime_attachment(soap, NULL)) + ; + return soap->error; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_post_check_mime_attachments(struct soap *soap) +{ soap->imode |= SOAP_MIME_POSTCHECK; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_check_mime_attachments(struct soap *soap) +{ if (soap->mode & SOAP_MIME_POSTCHECK) + return soap_get_mime_attachment(soap, NULL) != NULL; + return 0; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +SOAP_FMAC1 +struct soap_multipart * +SOAP_FMAC2 +soap_get_mime_attachment(struct soap *soap, void *handle) +{ register soap_wchar c = 0; + register size_t i, m = 0; + register char *s, *t = NULL; + register struct soap_multipart *content; + register short flag = 0; + if (!(soap->mode & SOAP_ENC_MIME)) + return NULL; + content = soap->mime.last; + if (!content) + { if (soap_getmimehdr(soap)) + return NULL; + content = soap->mime.last; + } + else if (content != soap->mime.first) + { if (soap->fmimewriteopen && ((content->ptr = (char*)soap->fmimewriteopen(soap, (void*)handle, content->id, content->type, content->description, content->encoding)) || soap->error)) + { if (!content->ptr) + return NULL; + } + } + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Parsing MIME content id=%s type=%s\n", content->id?content->id:SOAP_STR_EOS, content->type?content->type:SOAP_STR_EOS)); + if (!content->ptr && soap_new_block(soap) == NULL) + { soap->error = SOAP_EOM; + return NULL; + } + for (;;) + { if (content->ptr) + s = soap->tmpbuf; + else if (!(s = (char*)soap_push_block(soap, NULL, sizeof(soap->tmpbuf)))) + { soap->error = SOAP_EOM; + return NULL; + } + for (i = 0; i < sizeof(soap->tmpbuf); i++) + { if (m > 0) + { *s++ = *t++; + m--; + } + else + { if (!flag) + { c = soap_get1(soap); + if ((int)c == EOF) + { soap->error = SOAP_EOF; + return NULL; + } + } + if (flag || c == '\r') + { t = soap->msgbuf; + memset(t, 0, sizeof(soap->msgbuf)); + strcpy(t, "\n--"); + if (soap->mime.boundary) + strncat(t, soap->mime.boundary, sizeof(soap->msgbuf)-4); + do c = soap_getchar(soap); + while (c == *t++); + if ((int)c == EOF) + { soap->error = SOAP_EOF; + return NULL; + } + if (!*--t) + goto end; + *t = (char)c; + flag = (c == '\r'); + m = t - soap->msgbuf + 1 - flag; + t = soap->msgbuf; + c = '\r'; + } + *s++ = (char)c; + } + } + if (content->ptr && soap->fmimewrite) + { if ((soap->error = soap->fmimewrite(soap, (void*)content->ptr, soap->tmpbuf, i))) + break; + } + } +end: + *s = '\0'; /* force 0-terminated */ + if (content->ptr) + { if (!soap->error && soap->fmimewrite) + soap->error = soap->fmimewrite(soap, (void*)content->ptr, soap->tmpbuf, i); + if (soap->fmimewriteclose) + soap->fmimewriteclose(soap, (void*)content->ptr); + if (soap->error) + return NULL; + } + else + { content->size = soap_size_block(soap, NULL, i+1)-1; + content->ptr = soap_save_block(soap, NULL, NULL, 0); + } + soap_resolve_attachment(soap, content); + if (c == '-' && soap_getchar(soap) == '-') + { soap->mode &= ~SOAP_ENC_MIME; + if ((soap->mode & SOAP_MIME_POSTCHECK) && soap_end_recv(soap)) + return NULL; + } + else + { while (c != '\r' && (int)c != EOF && soap_blank(c)) + c = soap_getchar(soap); + if (c != '\r' || soap_getchar(soap) != '\n') + { soap->error = SOAP_MIME_ERROR; + return NULL; + } + if (soap_getmimehdr(soap)) + return NULL; + } + return content; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_match_cid(struct soap *soap, const char *s, const char *t) +{ register size_t n; + if (!s) + return 1; + if (!strcmp(s, t)) + return 0; + if (!strncmp(s, "cid:", 4)) + s += 4; + n = strlen(t); + if (*t == '<') + { t++; + n -= 2; + } + if (!strncmp(s, t, n) && !s[n]) + return 0; + soap_decode(soap->tmpbuf, sizeof(soap->tmpbuf), s, SOAP_STR_EOS); + if (!strncmp(soap->tmpbuf, t, n) && !soap->tmpbuf[n]) + return 0; + return 1; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +static void +soap_resolve_attachment(struct soap *soap, struct soap_multipart *content) +{ if (content->id) + { register struct soap_xlist **xp = &soap->xlist; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Resolving attachment data for id=%s\n", content->id)); + while (*xp) + { register struct soap_xlist *xq = *xp; + if (!soap_match_cid(soap, xq->id, content->id)) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Found matching attachment %s for content id=%s\n", xq->id, content->id)); + *xp = xq->next; + *xq->ptr = (unsigned char*)content->ptr; + *xq->size = (int)content->size; + *xq->type = (char*)content->type; + if (content->options) + *xq->options = (char*)content->options; + else + *xq->options = (char*)content->description; + SOAP_FREE(soap, xq); + } + else + xp = &(*xp)->next; + } + } +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_putmimehdr(struct soap *soap, struct soap_multipart *content) +{ const char *s; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "MIME attachment type=%s\n", content->type?content->type:SOAP_STR_EOS)); + if (soap_send3(soap, "\r\n--", soap->mime.boundary, "\r\n")) + return soap->error; + if (content->type && soap_send3(soap, "Content-Type: ", content->type, "\r\n")) + return soap->error; + s = soap_code_str(mime_codes, content->encoding); + if (s && soap_send3(soap, "Content-Transfer-Encoding: ", s, "\r\n")) + return soap->error; + if (content->id && soap_send3(soap, "Content-ID: ", content->id, "\r\n")) + return soap->error; + if (content->location && soap_send3(soap, "Content-Location: ", content->location, "\r\n")) + return soap->error; + if (content->description && soap_send3(soap, "Content-Description: ", content->description, "\r\n")) + return soap->error; + return soap_send_raw(soap, "\r\n", 2); +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_putmime(struct soap *soap) +{ struct soap_multipart *content; + if (!(soap->mode & SOAP_ENC_MIME) || !soap->mime.boundary) + return SOAP_OK; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Sending MIME attachments\n")); + for (content = soap->mime.first; content; content = content->next) + { void *handle; + if (soap->fmimereadopen && ((handle = soap->fmimereadopen(soap, (void*)content->ptr, content->id, content->type, content->description)) || soap->error)) + { size_t size = content->size; + if (!handle) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "fmimereadopen failed\n")); + return soap->error; + } + if (soap_putmimehdr(soap, content)) + return soap->error; + if (!size) + { if ((soap->mode & SOAP_ENC_XML) || (soap->mode & SOAP_IO) == SOAP_IO_CHUNK || (soap->mode & SOAP_IO) == SOAP_IO_STORE) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Chunked streaming MIME\n")); + do + { size = soap->fmimeread(soap, handle, soap->tmpbuf, sizeof(soap->tmpbuf)); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "fmimeread returned %lu bytes\n", (unsigned long)size)); + if (soap_send_raw(soap, soap->tmpbuf, size)) + break; + } while (size); + } + else + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Error: cannot chunk streaming MIME (no HTTP chunking)\n")); + } + } + else + { do + { size_t bufsize; + if (size < sizeof(soap->tmpbuf)) + bufsize = size; + else + bufsize = sizeof(soap->tmpbuf); + if (!(bufsize = soap->fmimeread(soap, handle, soap->tmpbuf, bufsize))) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "fmimeread failed: insufficient data (%lu bytes remaining from %lu bytes)\n", (unsigned long)size, (unsigned long)content->size)); + soap->error = SOAP_EOF; + break; + } + if (soap_send_raw(soap, soap->tmpbuf, bufsize)) + break; + size -= bufsize; + } while (size); + } + if (soap->fmimereadclose) + soap->fmimereadclose(soap, handle); + } + else + { if (soap_putmimehdr(soap, content) + || soap_send_raw(soap, content->ptr, content->size)) + return soap->error; + } + } + return soap_send3(soap, "\r\n--", soap->mime.boundary, "--"); +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_set_dime(struct soap *soap) +{ soap->omode |= SOAP_ENC_DIME; + soap->dime.first = NULL; + soap->dime.last = NULL; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_set_mime(struct soap *soap, const char *boundary, const char *start) +{ soap->omode |= SOAP_ENC_MIME; + soap->mime.first = NULL; + soap->mime.last = NULL; + soap->mime.boundary = soap_strdup(soap, boundary); + soap->mime.start = soap_strdup(soap, start); +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_clr_dime(struct soap *soap) +{ soap->omode &= ~SOAP_ENC_DIME; + soap->dime.first = NULL; + soap->dime.last = NULL; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_clr_mime(struct soap *soap) +{ soap->omode &= ~SOAP_ENC_MIME; + soap->mime.first = NULL; + soap->mime.last = NULL; + soap->mime.boundary = NULL; + soap->mime.start = NULL; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +static struct soap_multipart* +soap_new_multipart(struct soap *soap, struct soap_multipart **first, struct soap_multipart **last, char *ptr, size_t size) +{ struct soap_multipart *content; + content = (struct soap_multipart*)soap_malloc(soap, sizeof(struct soap_multipart)); + if (content) + { content->next = NULL; + content->ptr = ptr; + content->size = size; + content->id = NULL; + content->type = NULL; + content->options = NULL; + content->encoding = SOAP_MIME_NONE; + content->location = NULL; + content->description = NULL; + if (!*first) + *first = content; + if (*last) + (*last)->next = content; + *last = content; + } + return content; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_set_dime_attachment(struct soap *soap, char *ptr, size_t size, const char *type, const char *id, unsigned short optype, const char *option) +{ struct soap_multipart *content = soap_new_multipart(soap, &soap->dime.first, &soap->dime.last, ptr, size); + if (!content) + return SOAP_EOM; + content->id = soap_strdup(soap, id); + content->type = soap_strdup(soap, type); + content->options = soap_dime_option(soap, optype, option); + return SOAP_OK; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_set_mime_attachment(struct soap *soap, char *ptr, size_t size, enum soap_mime_encoding encoding, const char *type, const char *id, const char *location, const char *description) +{ struct soap_multipart *content = soap_new_multipart(soap, &soap->mime.first, &soap->mime.last, ptr, size); + if (!content) + return SOAP_EOM; + content->id = soap_strdup(soap, id); + content->type = soap_strdup(soap, type); + content->encoding = encoding; + content->location = soap_strdup(soap, location); + content->description = soap_strdup(soap, description); + return SOAP_OK; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +SOAP_FMAC1 +struct soap_multipart* +SOAP_FMAC2 +soap_next_multipart(struct soap_multipart *content) +{ if (content) + return content->next; + return NULL; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +static void +soap_select_mime_boundary(struct soap *soap) +{ while (!soap->mime.boundary || soap_valid_mime_boundary(soap)) + { register char *s = soap->mime.boundary; + register size_t n = 0; + if (s) + n = strlen(s); + if (n < 16) + { n = 64; + s = soap->mime.boundary = (char*)soap_malloc(soap, n + 1); + if (!s) + return; + } + strcpy(s, "=="); + s += 2; + n -= 4; + while (n) + { *s++ = soap_base64o[soap_random & 0x3F]; + n--; + } + strcpy(s, "=="); + } + if (!soap->mime.start) + soap->mime.start = ""; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEANER +#ifndef PALM_1 +static int +soap_valid_mime_boundary(struct soap *soap) +{ register struct soap_multipart *content; + register size_t k; + if (soap->fmimeread) + return SOAP_OK; + k = strlen(soap->mime.boundary); + for (content = soap->mime.first; content; content = content->next) + { if (content->ptr && content->size >= k) + { register const char *p = (const char*)content->ptr; + register size_t i; + for (i = 0; i < content->size - k; i++, p++) + { if (!strncmp(p, soap->mime.boundary, k)) + return SOAP_ERR; + } + } + } + return SOAP_OK; +} +#endif +#endif + +/******************************************************************************\ + * + * HTTP cookie handling + * +\******************************************************************************/ + +#ifdef WITH_COOKIES +/******************************************************************************/ +SOAP_FMAC1 +size_t +SOAP_FMAC2 +soap_encode_cookie(const char *s, char *t, size_t len) +{ register int c; + register size_t n = len; + while ((c = *s++) && --n > 0) + { if (c > ' ' && c < 128 && !strchr("()<>@,;:\\\"/[]?={}#!$&'*+", c)) + *t++ = c; + else if (n > 2) + { *t++ = '%'; + *t++ = (c >> 4) + (c > 159 ? '7' : '0'); + c &= 0xF; + *t++ = c + (c > 9 ? '7' : '0'); + n -= 2; + } + else + break; + } + *t = '\0'; + return len - n; +} + +/******************************************************************************/ +SOAP_FMAC1 +struct soap_cookie* +SOAP_FMAC2 +soap_cookie(struct soap *soap, const char *name, const char *domain, const char *path) +{ struct soap_cookie *p; + if (!domain) + domain = soap->cookie_domain; + if (!path) + path = soap->cookie_path; + if (!path) + path = SOAP_STR_EOS; + else if (*path == '/') + path++; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Search cookie %s domain=%s path=%s\n", name, domain?domain:"(null)", path?path:"(null)")); + for (p = soap->cookies; p; p = p->next) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Cookie in database: %s=%s domain=%s path=%s env=%hd\n", p->name, p->value?p->value:"(null)", p->domain?p->domain:"(null)", p->path?p->path:"(null)", p->env)); + if (!strcmp(p->name, name) + && p->domain + && p->path + && !strcmp(p->domain, domain) + && (!*p->path || !strncmp(p->path, path, strlen(p->path)))) + break; + } + return p; +} + +/******************************************************************************/ +SOAP_FMAC1 +struct soap_cookie* +SOAP_FMAC2 +soap_set_cookie(struct soap *soap, const char *name, const char *value, const char *domain, const char *path) +{ struct soap_cookie **p, *q; + int n; + if (!domain) + domain = soap->cookie_domain; + if (!path) + path = soap->cookie_path; + if (!path) + path = SOAP_STR_EOS; + else if (*path == '/') + path++; + q = soap_cookie(soap, name, domain, path); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Set %scookie: %s=%s domain=%s path=%s\n", q ? SOAP_STR_EOS : "new ", name, value?value:"(null)", domain?domain:"(null)", path?path:"(null)")); + if (!q) + { if ((q = (struct soap_cookie*)SOAP_MALLOC(soap, sizeof(struct soap_cookie)))) + { if ((q->name = (char*)SOAP_MALLOC(soap, strlen(name)+1))) + strcpy(q->name, name); + q->value = NULL; + q->domain = NULL; + q->path = NULL; + q->expire = 0; + q->maxage = -1; + q->version = 1; + q->secure = 0; + q->modified = 0; + for (p = &soap->cookies, n = soap->cookie_max; *p && n; p = &(*p)->next, n--) + if (!strcmp((*p)->name, name) && (*p)->path && path && strcmp((*p)->path, path) < 0) + break; + if (n) + { q->next = *p; + *p = q; + } + else + { SOAP_FREE(soap, q->name); + SOAP_FREE(soap, q); + q = NULL; + } + } + } + else + q->modified = 1; + if (q) + { if (q->value) + { if (!value || strcmp(value, q->value)) + { SOAP_FREE(soap, q->value); + q->value = NULL; + } + } + if (value && *value && !q->value && (q->value = (char*)SOAP_MALLOC(soap, strlen(value)+1))) + strcpy(q->value, value); + if (q->domain) + { if (!domain || strcmp(domain, q->domain)) + { SOAP_FREE(soap, q->domain); + q->domain = NULL; + } + } + if (domain && !q->domain && (q->domain = (char*)SOAP_MALLOC(soap, strlen(domain)+1))) + strcpy(q->domain, domain); + if (q->path) + { if (!path || strncmp(path, q->path, strlen(q->path))) + { SOAP_FREE(soap, q->path); + q->path = NULL; + } + } + if (path && !q->path && (q->path = (char*)SOAP_MALLOC(soap, strlen(path)+1))) + strcpy(q->path, path); + q->session = 1; + q->env = 0; + } + return q; +} + +/******************************************************************************/ +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_clr_cookie(struct soap *soap, const char *name, const char *domain, const char *path) +{ struct soap_cookie **p, *q; + if (!domain) + domain = soap->cookie_domain; + if (!domain) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Error in clear cookie %s: cookie domain not set\n", name?name:"(null)")); + return; + } + if (!path) + path = soap->cookie_path; + if (!path) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Error in clear cookie %s: cookie path not set\n", name?name:"(null)")); + return; + } + if (*path == '/') + path++; + for (p = &soap->cookies, q = *p; q; q = *p) + { if (!strcmp(q->name, name) && !strcmp(q->domain, domain) && !strncmp(q->path, path, strlen(q->path))) + { if (q->value) + SOAP_FREE(soap, q->value); + if (q->domain) + SOAP_FREE(soap, q->domain); + if (q->path) + SOAP_FREE(soap, q->path); + *p = q->next; + SOAP_FREE(soap, q); + } + else + p = &q->next; + } +} + +/******************************************************************************/ +SOAP_FMAC1 +char * +SOAP_FMAC2 +soap_cookie_value(struct soap *soap, const char *name, const char *domain, const char *path) +{ struct soap_cookie *p; + if ((p = soap_cookie(soap, name, domain, path))) + return p->value; + return NULL; +} + +/******************************************************************************/ +SOAP_FMAC1 +char * +SOAP_FMAC2 +soap_env_cookie_value(struct soap *soap, const char *name, const char *domain, const char *path) +{ struct soap_cookie *p; + if ((p = soap_cookie(soap, name, domain, path)) && p->env) + return p->value; + return NULL; +} + +/******************************************************************************/ +SOAP_FMAC1 +time_t +SOAP_FMAC2 +soap_cookie_expire(struct soap *soap, const char *name, const char *domain, const char *path) +{ struct soap_cookie *p; + if ((p = soap_cookie(soap, name, domain, path))) + return p->expire; + return -1; +} + +/******************************************************************************/ +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_set_cookie_expire(struct soap *soap, const char *name, long expire, const char *domain, const char *path) +{ struct soap_cookie *p; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Set cookie expiration max-age %ld: %s domain=%s path=%s\n", expire, name, domain?domain:"(null)", path?path:"(null)")); + if ((p = soap_cookie(soap, name, domain, path))) + { p->maxage = expire; + p->modified = 1; + return SOAP_OK; + } + return SOAP_ERR; +} + +/******************************************************************************/ +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_set_cookie_session(struct soap *soap, const char *name, const char *domain, const char *path) +{ struct soap_cookie *p; + if ((p = soap_cookie(soap, name, domain, path))) + { p->session = 1; + p->modified = 1; + return SOAP_OK; + } + return SOAP_ERR; +} + +/******************************************************************************/ +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_clr_cookie_session(struct soap *soap, const char *name, const char *domain, const char *path) +{ struct soap_cookie *p; + if ((p = soap_cookie(soap, name, domain, path))) + { p->session = 0; + p->modified = 1; + return SOAP_OK; + } + return SOAP_ERR; +} + +/******************************************************************************/ +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_putsetcookies(struct soap *soap) +{ struct soap_cookie *p; + char *s, tmp[4096]; + const char *t; + for (p = soap->cookies; p; p = p->next) + { + if (p->modified +#ifdef WITH_OPENSSL + || (!p->env && !soap->ssl == !p->secure) +#endif + ) + { s = tmp; + if (p->name) + s += soap_encode_cookie(p->name, s, tmp-s+4064); + if (p->value && *p->value) + { *s++ = '='; + s += soap_encode_cookie(p->value, s, tmp-s+4064); + } + if (p->domain && (int)strlen(p->domain) < tmp-s+4064) + { strcpy(s, ";Domain="); + strcat(s, p->domain); + } + else if (soap->cookie_domain && (int)strlen(soap->cookie_domain) < tmp-s+4064) + { strcpy(s, ";Domain="); + strcat(s, soap->cookie_domain); + } + strcat(s, ";Path=/"); + s += strlen(s); + if (p->path) + t = p->path; + else + t = soap->cookie_path; + if (t) + { if (*t == '/') + t++; + if ((int)strlen(t) < tmp-s+4064) + { if (strchr(t, '%')) /* already URL encoded? */ + { strcpy(s, t); + s += strlen(s); + } + else + s += soap_encode_cookie(t, s, tmp-s+4064); + } + } + if (p->version > 0 && s-tmp < 4060) + { sprintf(s, ";Version=%u", p->version); + s += strlen(s); + } + if (p->maxage >= 0 && s-tmp < 4060) + { sprintf(s, ";Max-Age=%ld", p->maxage); + s += strlen(s); + } + if (s-tmp < 4073 + && (p->secure +#ifdef WITH_OPENSSL + || soap->ssl +#endif + )) + strcpy(s, ";Secure"); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Set-Cookie: %s\n", tmp)); + if ((soap->error = soap->fposthdr(soap, "Set-Cookie", tmp))) + return soap->error; + } + } + return SOAP_OK; +} + +/******************************************************************************/ +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_putcookies(struct soap *soap, const char *domain, const char *path, int secure) +{ struct soap_cookie **p, *q; + unsigned int version = 0; + time_t now = time(NULL); + char *s, tmp[4096]; + p = &soap->cookies; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Sending cookies for domain=%s path=%s\n", domain, path)); + if (*path == '/') + path++; + while ((q = *p)) + { if (q->expire && now > q->expire) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Cookie %s expired\n", q->name)); + SOAP_FREE(soap, q->name); + if (q->value) + SOAP_FREE(soap, q->value); + if (q->domain) + SOAP_FREE(soap, q->domain); + if (q->path) + SOAP_FREE(soap, q->path); + *p = q->next; + SOAP_FREE(soap, q); + } + else + { int flag; + char *t = q->domain; + size_t n = 0; + if (!t) + flag = 1; + else + { const char *r = strchr(t, ':'); + if (r) + n = r - t; + else + n = strlen(t); + flag = !strncmp(t, domain, n); + } + /* domain-level cookies, cannot compile when WITH_NOIO set */ +#ifndef WITH_NOIO + if (!flag) + { struct hostent *hostent = gethostbyname((char*)domain); + if (hostent) + { const char *r = strchr(hostent->h_name, '.'); + if (!r) + r = hostent->h_name; + flag = !strncmp(t, r, n); + } + } +#endif + if (flag + && (!q->path || !strncmp(q->path, path, strlen(q->path))) + && (!q->secure || secure)) + { s = tmp; + if (q->version != version) + { sprintf(s, "$Version=%u;", q->version); + version = q->version; + } + if (q->name) + s += soap_encode_cookie(q->name, s, tmp-s+4080); + if (q->value && *q->value) + { *s++ = '='; + s += soap_encode_cookie(q->value, s, tmp-s+4080); + } + if (q->path && *q->path && (int)strlen(q->path) < tmp-s+4080) + { sprintf(s, ";$Path=\"/%s\"", (*q->path == '/' ? q->path + 1 : q->path)); + s += strlen(s); + } + if (q->domain && (int)strlen(q->domain) < tmp-s+4080) + sprintf(s, ";$Domain=\"%s\"", q->domain); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Cookie: %s\n", tmp)); + if ((soap->error = soap->fposthdr(soap, "Cookie", tmp))) + return soap->error; + } + p = &q->next; + } + } + return SOAP_OK; +} + +/******************************************************************************/ +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_getcookies(struct soap *soap, const char *val) +{ struct soap_cookie *p = NULL, *q; + const char *s; + char *t, tmp[4096]; /* cookie size is up to 4096 bytes [RFC2109] */ + char *domain = NULL; + char *path = NULL; + unsigned int version = 0; + time_t now = time(NULL); + if (!val) + return; + s = val; + while (*s) + { s = soap_decode_key(tmp, sizeof(tmp), s); + if (!soap_tag_cmp(tmp, "$Version")) + { if ((s = soap_decode_val(tmp, sizeof(tmp), s))) + { if (p) + p->version = (int)atol(tmp); + else + version = (int)atol(tmp); + } + } + else if (!soap_tag_cmp(tmp, "$Path")) + { s = soap_decode_val(tmp, sizeof(tmp), s); + if (*tmp) + { if ((t = (char*)SOAP_MALLOC(soap, strlen(tmp)+1))) + strcpy(t, tmp); + } + else + t = NULL; + if (p) + { if (p->path) + SOAP_FREE(soap, p->path); + p->path = t; + } + else + { if (path) + SOAP_FREE(soap, path); + path = t; + } + } + else if (!soap_tag_cmp(tmp, "$Domain")) + { s = soap_decode_val(tmp, sizeof(tmp), s); + if (*tmp) + { if ((t = (char*)SOAP_MALLOC(soap, strlen(tmp)+1))) + strcpy(t, tmp); + } + else + t = NULL; + if (p) + { if (p->domain) + SOAP_FREE(soap, p->domain); + p->domain = t; + } + else + { if (domain) + SOAP_FREE(soap, domain); + domain = t; + } + } + else if (p && !soap_tag_cmp(tmp, "Path")) + { if (p->path) + SOAP_FREE(soap, p->path); + s = soap_decode_val(tmp, sizeof(tmp), s); + if (*tmp) + { if ((p->path = (char*)SOAP_MALLOC(soap, strlen(tmp)+1))) + strcpy(p->path, tmp); + } + else + p->path = NULL; + } + else if (p && !soap_tag_cmp(tmp, "Domain")) + { if (p->domain) + SOAP_FREE(soap, p->domain); + s = soap_decode_val(tmp, sizeof(tmp), s); + if (*tmp) + { if ((p->domain = (char*)SOAP_MALLOC(soap, strlen(tmp)+1))) + strcpy(p->domain, tmp); + } + else + p->domain = NULL; + } + else if (p && !soap_tag_cmp(tmp, "Version")) + { s = soap_decode_val(tmp, sizeof(tmp), s); + p->version = (unsigned int)atol(tmp); + } + else if (p && !soap_tag_cmp(tmp, "Max-Age")) + { s = soap_decode_val(tmp, sizeof(tmp), s); + p->expire = now + atol(tmp); + } + else if (p && !soap_tag_cmp(tmp, "Expires")) + { struct tm T; + char a[3]; + static const char mns[] = "anebarprayunulugepctovec"; + s = soap_decode_val(tmp, sizeof(tmp), s); + if (strlen(tmp) > 20) + { memset((void*)&T, 0, sizeof(T)); + a[0] = tmp[4]; + a[1] = tmp[5]; + a[2] = '\0'; + T.tm_mday = (int)atol(a); + a[0] = tmp[8]; + a[1] = tmp[9]; + T.tm_mon = (int)(strstr(mns, a) - mns) / 2; + a[0] = tmp[11]; + a[1] = tmp[12]; + T.tm_year = 100 + (int)atol(a); + a[0] = tmp[13]; + a[1] = tmp[14]; + T.tm_hour = (int)atol(a); + a[0] = tmp[16]; + a[1] = tmp[17]; + T.tm_min = (int)atol(a); + a[0] = tmp[19]; + a[1] = tmp[20]; + T.tm_sec = (int)atol(a); + p->expire = soap_timegm(&T); + } + } + else if (p && !soap_tag_cmp(tmp, "Secure")) + p->secure = 1; + else + { if (p) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Got environment cookie %s=%s domain=%s path=%s expire=%ld secure=%d\n", p->name, p->value?p->value:"(null)", p->domain?p->domain:"(null)", p->path?p->path:"(null)", p->expire, p->secure)); + if ((q = soap_set_cookie(soap, p->name, p->value, p->domain, p->path))) + { q->version = p->version; + q->expire = p->expire; + q->secure = p->secure; + q->env = 1; + } + if (p->name) + SOAP_FREE(soap, p->name); + if (p->value) + SOAP_FREE(soap, p->value); + if (p->domain) + SOAP_FREE(soap, p->domain); + if (p->path) + SOAP_FREE(soap, p->path); + SOAP_FREE(soap, p); + } + if ((p = (struct soap_cookie*)SOAP_MALLOC(soap, sizeof(struct soap_cookie)))) + { p->name = (char*)SOAP_MALLOC(soap, strlen(tmp)+1); + strcpy(p->name, tmp); + s = soap_decode_val(tmp, sizeof(tmp), s); + if (*tmp) + { p->value = (char*)SOAP_MALLOC(soap, strlen(tmp)+1); + strcpy(p->value, tmp); + } + else + p->value = NULL; + if (domain) + p->domain = domain; + else if (*soap->host) + { p->domain = (char*)SOAP_MALLOC(soap, strlen(soap->host)+1); + strcpy(p->domain, soap->host); + } + else + p->domain = NULL; + if (path) + p->path = path; + else if (soap->path && *soap->path) + { p->path = (char*)SOAP_MALLOC(soap, strlen(soap->path)+1); + strcpy(p->path, soap->path); + } + else + { p->path = (char*)SOAP_MALLOC(soap, 2); + strcpy(p->path, "/"); + } + p->expire = 0; + p->secure = 0; + p->version = version; + } + } + } + if (p) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Got environment cookie %s=%s domain=%s path=%s expire=%ld secure=%d\n", p->name, p->value?p->value:"(null)", p->domain?p->domain:"(null)", p->path?p->path:"(null)", p->expire, p->secure)); + if ((q = soap_set_cookie(soap, p->name, p->value, p->domain, p->path))) + { q->version = p->version; + q->expire = p->expire; + q->secure = p->secure; + q->env = 1; + } + if (p->name) + SOAP_FREE(soap, p->name); + if (p->value) + SOAP_FREE(soap, p->value); + if (p->domain) + SOAP_FREE(soap, p->domain); + if (p->path) + SOAP_FREE(soap, p->path); + SOAP_FREE(soap, p); + } + if (domain) + SOAP_FREE(soap, domain); + if (path) + SOAP_FREE(soap, path); +} + +/******************************************************************************/ +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_getenv_cookies(struct soap *soap) +{ struct soap_cookie *p; + const char *s; + char key[4096], val[4096]; /* cookie size is up to 4096 bytes [RFC2109] */ + if (!(s = getenv("HTTP_COOKIE"))) + return SOAP_ERR; + do + { s = soap_decode_key(key, sizeof(key), s); + s = soap_decode_val(val, sizeof(val), s); + p = soap_set_cookie(soap, key, val, NULL, NULL); + if (p) + p->env = 1; + } while (*s); + return SOAP_OK; +} + +/******************************************************************************/ +SOAP_FMAC1 +struct soap_cookie* +SOAP_FMAC2 +soap_copy_cookies(struct soap *copy, const struct soap *soap) +{ struct soap_cookie *p, **q, *r; + q = &r; + for (p = soap->cookies; p; p = p->next) + { if (!(*q = (struct soap_cookie*)SOAP_MALLOC(copy, sizeof(struct soap_cookie)))) + return r; + **q = *p; + if (p->name) + { if (((*q)->name = (char*)SOAP_MALLOC(copy, strlen(p->name)+1))) + strcpy((*q)->name, p->name); + } + if (p->value) + { if (((*q)->value = (char*)SOAP_MALLOC(copy, strlen(p->value)+1))) + strcpy((*q)->value, p->value); + } + if (p->domain) + { if (((*q)->domain = (char*)SOAP_MALLOC(copy, strlen(p->domain)+1))) + strcpy((*q)->domain, p->domain); + } + if (p->path) + { if (((*q)->path = (char*)SOAP_MALLOC(copy, strlen(p->path)+1))) + strcpy((*q)->path, p->path); + } + q = &(*q)->next; + } + *q = NULL; + return r; +} + +/******************************************************************************/ +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_free_cookies(struct soap *soap) +{ struct soap_cookie *p; + for (p = soap->cookies; p; p = soap->cookies) + { soap->cookies = p->next; + SOAP_FREE(soap, p->name); + if (p->value) + SOAP_FREE(soap, p->value); + if (p->domain) + SOAP_FREE(soap, p->domain); + if (p->path) + SOAP_FREE(soap, p->path); + SOAP_FREE(soap, p); + } +} + +/******************************************************************************/ +#endif /* WITH_COOKIES */ + +/******************************************************************************/ +#ifdef WITH_GZIP +#ifndef PALM_1 +static int +soap_getgziphdr(struct soap *soap) +{ int i; + soap_wchar c = 0, f = 0; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Get gzip header\n")); + for (i = 0; i < 9; i++) + { if ((int)(c = soap_get1(soap) == EOF)) + return soap->error = SOAP_EOF; + if (i == 1 && c == 8) + soap->z_dict = 0; + if (i == 2) + f = c; + } + if (f & 0x04) /* FEXTRA */ + { for (i = soap_get1(soap) | (soap_get1(soap) << 8); i; i--) + { if ((int)soap_get1(soap) == EOF) + return soap->error = SOAP_EOF; + } + } + if (f & 0x08) /* FNAME */ + { do + c = soap_get1(soap); + while (c && (int)c != EOF); + } + if ((int)c != EOF && (f & 0x10)) /* FCOMMENT */ + { do + c = soap_get1(soap); + while (c && (int)c != EOF); + } + if ((int)c != EOF && (f & 0x01)) /* FHCRC */ + { if ((int)(c = soap_get1(soap)) != EOF) + c = soap_get1(soap); + } + if ((int)c == EOF) + return soap->error = SOAP_EOF; + return SOAP_OK; +} +#endif +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_begin_recv(struct soap *soap) +{ soap_wchar c; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Initializing for input\n")); + soap->error = SOAP_OK; + soap_free_temp(soap); + soap_set_local_namespaces(soap); + soap->version = 0; /* don't assume we're parsing SOAP content by default */ +#ifndef WITH_NOIDREF + soap_free_iht(soap); +#endif + if ((soap->imode & SOAP_IO) == SOAP_IO_CHUNK) + soap->omode |= SOAP_IO_CHUNK; + soap->imode &= ~(SOAP_IO | SOAP_ENC_MIME); + soap->mode = soap->imode; + if (!soap->keep_alive) + { soap->buflen = 0; + soap->bufidx = 0; + } + if (!(soap->mode & SOAP_IO_KEEPALIVE)) + soap->keep_alive = 0; + soap->ahead = 0; + soap->peeked = 0; + soap->level = 0; + soap->part = SOAP_BEGIN; + soap->alloced = 0; + soap->count = 0; + soap->length = 0; + soap->cdata = 0; + *soap->endpoint = '\0'; + soap->action = NULL; + soap->header = NULL; + soap->fault = NULL; + soap->status = 0; +#ifndef WITH_LEANER + soap->dom = NULL; + soap->dime.chunksize = 0; + soap->dime.buflen = 0; + soap->dime.list = NULL; + soap->dime.first = NULL; + soap->dime.last = NULL; + soap->mime.list = NULL; + soap->mime.first = NULL; + soap->mime.last = NULL; + soap->mime.boundary = NULL; + soap->mime.start = NULL; +#endif +#ifdef WIN32 +#ifndef UNDER_CE +#ifndef WITH_FASTCGI + if (!soap_valid_socket(soap->socket)) +#ifdef __BORLANDC__ + setmode(soap->recvfd, _O_BINARY); +#else + _setmode(soap->recvfd, _O_BINARY); +#endif +#endif +#endif +#endif +#ifdef WITH_ZLIB + soap->mode &= ~SOAP_ENC_ZLIB; + soap->zlib_in = SOAP_ZLIB_NONE; + soap->zlib_out = SOAP_ZLIB_NONE; + soap->d_stream->next_in = Z_NULL; + soap->d_stream->avail_in = 0; + soap->d_stream->next_out = (Byte*)soap->buf; + soap->d_stream->avail_out = SOAP_BUFLEN; + soap->z_ratio_in = 1.0; +#endif +#ifdef WITH_OPENSSL + if (soap->ssl) + ERR_clear_error(); +#endif +#ifndef WITH_LEANER + if (soap->fprepareinit) + soap->fprepareinit(soap); +#endif + c = soap_getchar(soap); +#ifdef WITH_GZIP + if (c == 0x1F) + { if (soap_getgziphdr(soap)) + return soap->error; + if (inflateInit2(soap->d_stream, -MAX_WBITS) != Z_OK) + return soap->error = SOAP_ZLIB_ERROR; + if (soap->z_dict) + { if (inflateSetDictionary(soap->d_stream, (const Bytef*)soap->z_dict, soap->z_dict_len) != Z_OK) + return soap->error = SOAP_ZLIB_ERROR; + } + soap->zlib_state = SOAP_ZLIB_INFLATE; + soap->mode |= SOAP_ENC_ZLIB; + soap->zlib_in = SOAP_ZLIB_GZIP; + soap->z_crc = crc32(0L, NULL, 0); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "gzip initialized\n")); + if (!soap->z_buf) + soap->z_buf = (char*)SOAP_MALLOC(soap, SOAP_BUFLEN); + memcpy(soap->z_buf, soap->buf, SOAP_BUFLEN); + /* should not chunk over plain transport, so why bother to check? */ + /* if ((soap->mode & SOAP_IO) == SOAP_IO_CHUNK) */ + /* soap->z_buflen = soap->bufidx; */ + /* else */ + soap->d_stream->next_in = (Byte*)(soap->z_buf + soap->bufidx); + soap->d_stream->avail_in = soap->buflen - soap->bufidx; + soap->z_buflen = soap->buflen; + soap->buflen = soap->bufidx; + c = soap_getchar(soap); + } +#endif +#ifndef WITH_LEANER + if (c == '-' && soap_get0(soap) == '-') + soap->mode |= SOAP_ENC_MIME; + else if ((c & 0xFFFC) == (SOAP_DIME_VERSION | SOAP_DIME_MB) && (soap_get0(soap) & 0xFFF0) == 0x20) + soap->mode |= SOAP_ENC_DIME; + else +#endif + { /* skip BOM */ + if (c == 0xEF && (c = soap_getchar(soap)) == 0xBB && (c = soap_getchar(soap)) == 0xBF) + c = soap_getchar(soap); + /* skip space */ + while (soap_blank(c)) + c = soap_getchar(soap); + } + if ((int)c == EOF) + return soap->error = SOAP_EOF; + soap_unget(soap, c); +#ifndef WITH_NOHTTP + /* if not XML or MIME/DIME/ZLIB, assume HTTP header */ + if (c != '<' && !(soap->mode & (SOAP_ENC_MIME | SOAP_ENC_DIME | SOAP_ENC_ZLIB))) + { soap_mode m = soap->imode; + soap->mode &= ~SOAP_IO; + soap->error = soap->fparse(soap); + if (soap->error && soap->error < SOAP_STOP) + { soap->keep_alive = 0; /* force close later */ + return soap->error; + } + if (soap->error == SOAP_STOP) + return soap->error; + soap->mode = soap->imode; /* if imode is changed, effectuate */ + soap->imode = m; /* restore imode */ +#ifdef WITH_ZLIB + soap->mode &= ~SOAP_ENC_ZLIB; +#endif + if ((soap->mode & SOAP_IO) == SOAP_IO_CHUNK) + { soap->chunkbuflen = soap->buflen; + soap->buflen = soap->bufidx; + soap->chunksize = 0; + } +#ifndef WITH_LEANER + else if (soap->fpreparerecv && soap->buflen != soap->bufidx) + soap->fpreparerecv(soap, soap->buf + soap->bufidx, soap->buflen - soap->bufidx); +#endif + /* Note: fparse should not use soap_unget to push back last char */ + if (soap_get0(soap) == (int)EOF) + { if (soap->status == 200) + return soap->error = SOAP_NO_DATA; /* HTTP OK: always expect data */ + return soap->error = soap->status; + } +#ifdef WITH_ZLIB + if (soap->zlib_in != SOAP_ZLIB_NONE) + { +#ifdef WITH_GZIP + if (soap->zlib_in != SOAP_ZLIB_DEFLATE) + { c = soap_get1(soap); + if (c == 0x1F) + { if (soap_getgziphdr(soap)) + return soap->error; + if (inflateInit2(soap->d_stream, -MAX_WBITS) != Z_OK) + return soap->error = SOAP_ZLIB_ERROR; + soap->z_crc = crc32(0L, NULL, 0); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "gzip initialized\n")); + } + else + { soap_revget1(soap); + if (inflateInit(soap->d_stream) != Z_OK) + return soap->error = SOAP_ZLIB_ERROR; + soap->zlib_in = SOAP_ZLIB_DEFLATE; + } + } + else +#endif + if (inflateInit(soap->d_stream) != Z_OK) + return soap->error = SOAP_ZLIB_ERROR; + if (soap->z_dict) + { if (inflateSetDictionary(soap->d_stream, (const Bytef*)soap->z_dict, soap->z_dict_len) != Z_OK) + return soap->error = SOAP_ZLIB_ERROR; + } + soap->zlib_state = SOAP_ZLIB_INFLATE; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Inflate initialized\n")); + soap->mode |= SOAP_ENC_ZLIB; + if (!soap->z_buf) + soap->z_buf = (char*)SOAP_MALLOC(soap, SOAP_BUFLEN); + memcpy(soap->z_buf, soap->buf, SOAP_BUFLEN); + soap->d_stream->next_in = (Byte*)(soap->z_buf + soap->bufidx); + soap->d_stream->avail_in = soap->buflen - soap->bufidx; + soap->z_buflen = soap->buflen; + soap->buflen = soap->bufidx; + } +#endif + if (soap->error) + { if (soap->error == SOAP_FORM && soap->fform) + { soap->error = soap->fform(soap); + if (soap->error == SOAP_OK) + soap->error = SOAP_STOP; /* prevents further processing */ + } + return soap->error; + } + } +#endif +#ifndef WITH_LEANER + if (soap->mode & SOAP_ENC_MIME) + { if (soap_getmimehdr(soap)) + return soap->error; + if (soap->mime.start) + { do + { if (!soap->mime.last->id) + break; + if (!soap_match_cid(soap, soap->mime.start, soap->mime.last->id)) + break; + } while (soap_get_mime_attachment(soap, NULL)); + } + if (soap_get_header_attribute(soap, soap->mime.first->type, "application/dime")) + soap->mode |= SOAP_ENC_DIME; + } + if (soap->mode & SOAP_ENC_DIME) + { if (soap_getdimehdr(soap)) + return soap->error; + if (soap->dime.flags & SOAP_DIME_CF) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Chunked DIME SOAP message\n")); + soap->dime.chunksize = soap->dime.size; + if (soap->buflen - soap->bufidx >= soap->dime.chunksize) + { soap->dime.buflen = soap->buflen; + soap->buflen = soap->bufidx + soap->dime.chunksize; + } + else + soap->dime.chunksize -= soap->buflen - soap->bufidx; + } + soap->count = soap->buflen - soap->bufidx; + } +#endif + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef WITH_NOHTTP +#ifndef PALM_1 +static int +http_parse(struct soap *soap) +{ char header[SOAP_HDRLEN], *s; + unsigned short httpcmd = 0, status = 0; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Waiting for HTTP request/response...\n")); + *soap->endpoint = '\0'; + soap->length = 0; + soap->userid = NULL; + soap->passwd = NULL; + soap->action = NULL; + soap->authrealm = NULL; + soap->proxy_from = NULL; + soap->http_content = NULL; + soap->status = 0; + do + { if (soap_getline(soap, soap->msgbuf, sizeof(soap->msgbuf))) + { if (soap->error == SOAP_EOF) + return SOAP_EOF; + return soap->error = 414; + } + if ((s = strchr(soap->msgbuf, ' '))) + { soap->status = (unsigned short)soap_strtoul(s, &s, 10); + if (!soap_blank(*s)) + soap->status = 0; + } + else + soap->status = 0; + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "HTTP status: %s\n", soap->msgbuf)); + for (;;) + { if (soap_getline(soap, header, SOAP_HDRLEN)) + { if (soap->error == SOAP_EOF) + { soap->error = SOAP_OK; + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "EOF in HTTP header, continue anyway\n")); + break; + } + return soap->error; + } + if (!*header) + break; + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "HTTP header: %s\n", header)); + s = strchr(header, ':'); + if (s) + { char *t; + *s = '\0'; + do s++; + while (*s && *s <= 32); + if (*s == '"') + s++; + t = s + strlen(s) - 1; + while (t > s && *t <= 32) + t--; + if (t >= s && *t == '"') + t--; + t[1] = '\0'; + if ((soap->error = soap->fparsehdr(soap, header, s))) + { if (soap->error < SOAP_STOP) + return soap->error; + status = soap->error; + soap->error = SOAP_OK; + } + } + } + } while (soap->status == 100); + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Finished HTTP header parsing, status = %d\n", soap->status)); + s = strstr(soap->msgbuf, "HTTP/"); + if (s && s[7] != '1') + { if (soap->keep_alive == 1) + soap->keep_alive = 0; + if (soap->status == 0 && (soap->omode & SOAP_IO) == SOAP_IO_CHUNK) /* soap->status == 0 for HTTP request */ + { soap->imode |= SOAP_IO_CHUNK; + soap->omode = (soap->omode & ~SOAP_IO) | SOAP_IO_STORE; + } + } + if (soap->keep_alive < 0) + soap->keep_alive = 1; + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Keep alive connection = %d\n", soap->keep_alive)); + if (soap->status == 0) + { size_t l = 0; + if (s) + { if (!strncmp(soap->msgbuf, "POST ", l = 5)) + httpcmd = 1; + else if (!strncmp(soap->msgbuf, "GET ", l = 4)) + httpcmd = 2; + else if (!strncmp(soap->msgbuf, "PUT ", l = 4)) + httpcmd = 3; + else if (!strncmp(soap->msgbuf, "DELETE ", l = 7)) + httpcmd = 4; + else if (!strncmp(soap->msgbuf, "HEAD ", l = 5)) + httpcmd = 5; + } + if (s && httpcmd) + { size_t m = strlen(soap->endpoint); + size_t n = m + (s - soap->msgbuf) - l - 1; + if (m > n) + m = n; + if (n >= sizeof(soap->endpoint)) + n = sizeof(soap->endpoint) - 1; + strncpy(soap->path, soap->msgbuf + l, n - m); + soap->path[n - m] = '\0'; + strcat(soap->endpoint, soap->path); + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Target endpoint='%s'\n", soap->endpoint)); + if (httpcmd > 1) + { switch (httpcmd) + { case 2: soap->error = soap->fget(soap); break; + case 3: soap->error = soap->fput(soap); break; + case 4: soap->error = soap->fdel(soap); break; + case 5: soap->error = soap->fhead(soap); break; + default: soap->error = 405; break; + } + if (soap->error == SOAP_OK) + soap->error = SOAP_STOP; /* prevents further processing */ + return soap->error; + } + if (status) + return soap->error = status; + } + else if (status) + return soap->error = status; + else if (s) + return soap->error = 405; + } + /* Status OK (HTTP 200) */ + if (soap->status == 0 || soap->status == 200) + return SOAP_OK; + /* Status 201 (Created), 202 (Accepted), ... and HTTP 400 and 500 errors + may not have a body. When content length, content type, or chunking is + used assume there is a message to parse, either XML or HTTP. + */ + if (soap->length > 0 || soap->http_content || (soap->imode & SOAP_IO) == SOAP_IO_CHUNK) + { if (((soap->status > 200 && soap->status <= 299) || soap->status == 400 || soap->status == 500)) + return SOAP_OK; + /* force close afterwards in soap_closesock() */ + soap->keep_alive = 0; + /* read HTTP body for error details */ + s = soap_get_http_body(soap); + if (s) + return soap_set_receiver_error(soap, soap->msgbuf, s, soap->status); + } + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "HTTP error %d\n", soap->status)); + return soap_set_receiver_error(soap, "HTTP Error", soap->msgbuf, soap->status); +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOHTTP +#ifndef PALM_1 +static int +http_parse_header(struct soap *soap, const char *key, const char *val) +{ if (!soap_tag_cmp(key, "Host")) + { +#ifdef WITH_OPENSSL + if (soap->imode & SOAP_ENC_SSL) + strcpy(soap->endpoint, "https://"); + else +#endif + strcpy(soap->endpoint, "http://"); + strncat(soap->endpoint, val, sizeof(soap->endpoint) - 8); + soap->endpoint[sizeof(soap->endpoint) - 1] = '\0'; + } +#ifndef WITH_LEANER + else if (!soap_tag_cmp(key, "Content-Type")) + { const char *action; + soap->http_content = soap_strdup(soap, val); + if (soap_get_header_attribute(soap, val, "application/dime")) + soap->imode |= SOAP_ENC_DIME; + else if (soap_get_header_attribute(soap, val, "multipart/related") + || soap_get_header_attribute(soap, val, "multipart/form-data")) + { soap->mime.boundary = soap_strdup(soap, soap_get_header_attribute(soap, val, "boundary")); + soap->mime.start = soap_strdup(soap, soap_get_header_attribute(soap, val, "start")); + soap->imode |= SOAP_ENC_MIME; + } + action = soap_get_header_attribute(soap, val, "action"); + if (action) + { if (*action == '"') + { soap->action = soap_strdup(soap, action + 1); + soap->action[strlen(soap->action) - 1] = '\0'; + } + else + soap->action = soap_strdup(soap, action); + } + } +#endif + else if (!soap_tag_cmp(key, "Content-Length")) + { soap->length = soap_strtoul(val, NULL, 10); + } + else if (!soap_tag_cmp(key, "Content-Encoding")) + { if (!soap_tag_cmp(val, "deflate")) +#ifdef WITH_ZLIB + soap->zlib_in = SOAP_ZLIB_DEFLATE; +#else + return SOAP_ZLIB_ERROR; +#endif + else if (!soap_tag_cmp(val, "gzip")) +#ifdef WITH_GZIP + soap->zlib_in = SOAP_ZLIB_GZIP; +#else + return SOAP_ZLIB_ERROR; +#endif + } +#ifdef WITH_ZLIB + else if (!soap_tag_cmp(key, "Accept-Encoding")) + { +#ifdef WITH_GZIP + if (strchr(val, '*') || soap_get_header_attribute(soap, val, "gzip")) + soap->zlib_out = SOAP_ZLIB_GZIP; + else +#endif + if (strchr(val, '*') || soap_get_header_attribute(soap, val, "deflate")) + soap->zlib_out = SOAP_ZLIB_DEFLATE; + else + soap->zlib_out = SOAP_ZLIB_NONE; + } +#endif + else if (!soap_tag_cmp(key, "Transfer-Encoding")) + { soap->imode &= ~SOAP_IO; + if (!soap_tag_cmp(val, "chunked")) + soap->imode |= SOAP_IO_CHUNK; + } + else if (!soap_tag_cmp(key, "Connection")) + { if (!soap_tag_cmp(val, "keep-alive")) + soap->keep_alive = -soap->keep_alive; + else if (!soap_tag_cmp(val, "close")) + soap->keep_alive = 0; + } +#ifndef WITH_LEAN + else if (!soap_tag_cmp(key, "Authorization")) + { if (!soap_tag_cmp(val, "Basic *")) + { int n; + char *s; + soap_base642s(soap, val + 6, soap->tmpbuf, sizeof(soap->tmpbuf) - 1, &n); + soap->tmpbuf[n] = '\0'; + if ((s = strchr(soap->tmpbuf, ':'))) + { *s = '\0'; + soap->userid = soap_strdup(soap, soap->tmpbuf); + soap->passwd = soap_strdup(soap, s + 1); + } + } + } + else if (!soap_tag_cmp(key, "WWW-Authenticate")) + { soap->authrealm = soap_strdup(soap, soap_get_header_attribute(soap, val + 6, "realm")); + } + else if (!soap_tag_cmp(key, "Expect")) + { if (!soap_tag_cmp(val, "100-continue")) + { if ((soap->error = soap->fposthdr(soap, "HTTP/1.1 100 Continue", NULL)) + || (soap->error = soap->fposthdr(soap, NULL, NULL))) + return soap->error; + } + } +#endif + else if (!soap_tag_cmp(key, "SOAPAction")) + { if (*val == '"') + { soap->action = soap_strdup(soap, val + 1); + soap->action[strlen(soap->action) - 1] = '\0'; + } + else + soap->action = soap_strdup(soap, val); + } + else if (!soap_tag_cmp(key, "Location")) + { strncpy(soap->endpoint, val, sizeof(soap->endpoint)); + soap->endpoint[sizeof(soap->endpoint) - 1] = '\0'; + } + else if (!soap_tag_cmp(key, "X-Forwarded-For")) + { soap->proxy_from = soap_strdup(soap, val); + } +#ifdef WITH_COOKIES + else if (!soap_tag_cmp(key, "Cookie") + || !soap_tag_cmp(key, "Cookie2") + || !soap_tag_cmp(key, "Set-Cookie") + || !soap_tag_cmp(key, "Set-Cookie2")) + { soap_getcookies(soap, val); + } +#endif + return SOAP_OK; +} +#endif +#endif + +/******************************************************************************/ +#if !defined(WITH_NOHTTP) || !defined(WITH_LEANER) +#ifndef PALM_1 +SOAP_FMAC1 +const char* +SOAP_FMAC2 +soap_get_header_attribute(struct soap *soap, const char *line, const char *key) +{ register const char *s = line; + if (s) + { while (*s) + { register short flag; + s = soap_decode_key(soap->tmpbuf, sizeof(soap->tmpbuf), s); + flag = soap_tag_cmp(soap->tmpbuf, key); + s = soap_decode_val(soap->tmpbuf, sizeof(soap->tmpbuf), s); + if (!flag) + return soap->tmpbuf; + } + } + return NULL; +} +#endif +#endif + +/******************************************************************************/ +#if !defined(WITH_NOHTTP) || !defined(WITH_LEANER) +#ifndef PALM_1 +SOAP_FMAC1 +const char* +SOAP_FMAC2 +soap_decode_key(char *buf, size_t len, const char *val) +{ return soap_decode(buf, len, val, "=,;"); +} +#endif +#endif + +/******************************************************************************/ +#if !defined(WITH_NOHTTP) || !defined(WITH_LEANER) +#ifndef PALM_1 +SOAP_FMAC1 +const char* +SOAP_FMAC2 +soap_decode_val(char *buf, size_t len, const char *val) +{ if (*val != '=') + { *buf = '\0'; + return val; + } + return soap_decode(buf, len, val + 1, ",;"); +} +#endif +#endif + +/******************************************************************************/ +#if !defined(WITH_NOHTTP) || !defined(WITH_LEANER) +#ifndef PALM_1 +static const char* +soap_decode(char *buf, size_t len, const char *val, const char *sep) +{ const char *s; + char *t = buf; + for (s = val; *s; s++) + if (*s != ' ' && *s != '\t' && !strchr(sep, *s)) + break; + if (*s == '"') + { s++; + while (*s && *s != '"' && --len) + *t++ = *s++; + } + else + { while (*s && !soap_blank(*s) && !strchr(sep, *s) && --len) + { if (*s == '%') + { *t++ = ((s[1] >= 'A' ? (s[1] & 0x7) + 9 : s[1] - '0') << 4) + + (s[2] >= 'A' ? (s[2] & 0x7) + 9 : s[2] - '0'); + s += 3; + } + else + *t++ = *s++; + } + } + *t = '\0'; + while (*s && !strchr(sep, *s)) + s++; + return s; +} +#endif +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_envelope_begin_out(struct soap *soap) +{ +#ifndef WITH_LEANER + size_t n = 0; + if ((soap->mode & SOAP_ENC_MIME) && soap->mime.boundary && soap->mime.start && strlen(soap->mime.boundary) + strlen(soap->mime.start) < sizeof(soap->tmpbuf) - 80 ) + { const char *s; + if ((soap->mode & SOAP_ENC_DIME) && !(soap->mode & SOAP_ENC_MTOM)) + s = "application/dime"; + else if (soap->version == 2) + { if (soap->mode & SOAP_ENC_MTOM) + s = "application/xop+xml; charset=utf-8; type=\"application/soap+xml\""; + else + s = "application/soap+xml; charset=utf-8"; + } + else if (soap->mode & SOAP_ENC_MTOM) + s = "application/xop+xml; charset=utf-8; type=\"text/xml\""; + else + s = "text/xml; charset=utf-8"; + sprintf(soap->tmpbuf, "--%s\r\nContent-Type: %s\r\nContent-Transfer-Encoding: binary\r\nContent-ID: %s\r\n\r\n", soap->mime.boundary, s, soap->mime.start); + n = strlen(soap->tmpbuf); + if (soap_send_raw(soap, soap->tmpbuf, n)) + return soap->error; + } + if (soap->mode & SOAP_IO_LENGTH) + soap->dime.size = soap->count; /* DIME in MIME correction */ + if (!(soap->mode & SOAP_IO_LENGTH) && (soap->mode & SOAP_ENC_DIME)) + { if (soap_putdimehdr(soap)) + return soap->error; + } +#endif + soap->part = SOAP_IN_ENVELOPE; + return soap_element_begin_out(soap, "SOAP-ENV:Envelope", 0, NULL); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_envelope_end_out(struct soap *soap) +{ if (soap_element_end_out(soap, "SOAP-ENV:Envelope")) + return soap->error; +#ifndef WITH_LEANER + if ((soap->mode & SOAP_IO_LENGTH) && (soap->mode & SOAP_ENC_DIME) && !(soap->mode & SOAP_ENC_MTOM)) + { soap->dime.size = soap->count - soap->dime.size; /* DIME in MIME correction */ + sprintf(soap->id, soap->dime_id_format, 0); + soap->dime.id = soap->id; + if (soap->local_namespaces) + { if (soap->local_namespaces[0].out) + soap->dime.type = (char*)soap->local_namespaces[0].out; + else + soap->dime.type = (char*)soap->local_namespaces[0].ns; + } + soap->dime.options = NULL; + soap->dime.flags = SOAP_DIME_MB | SOAP_DIME_ABSURI; + if (!soap->dime.first) + soap->dime.flags |= SOAP_DIME_ME; + soap->count += 12 + ((strlen(soap->dime.id)+3)&(~3)) + (soap->dime.type ? ((strlen(soap->dime.type)+3)&(~3)) : 0); + } + if ((soap->mode & SOAP_ENC_DIME) && !(soap->mode & SOAP_ENC_MTOM)) + return soap_send_raw(soap, SOAP_STR_PADDING, -(long)soap->dime.size&3); +#endif + soap->part = SOAP_END_ENVELOPE; + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +static char* +soap_get_http_body(struct soap *soap) +{ +#ifndef WITH_LEAN + register size_t l = 0, n = 0; + register char *s; + /* get HTML body of HTTP error content */ + if (!(soap->mode & SOAP_ENC_ZLIB) && (soap->mode & SOAP_IO) != SOAP_IO_CHUNK) + { n = soap->length; + if (!n) + return NULL; + } +#ifdef WITH_FAST + soap->labidx = 0; /* use look-aside buffer */ +#else + if (soap_new_block(soap) == NULL) + return NULL; +#endif + for (;;) + { +#ifdef WITH_FAST + register size_t i, k; + if (soap_append_lab(soap, NULL, 0)) /* allocate more space in look-aside buffer if necessary */ + return NULL; + s = soap->labbuf + soap->labidx; /* space to populate */ + k = soap->lablen - soap->labidx; /* number of bytes available */ + soap->labidx = soap->lablen; /* claim this space */ +#else + register size_t i, k = SOAP_BLKLEN; + if (!(s = (char*)soap_push_block(soap, NULL, k))) + return NULL; +#endif + for (i = 0; i < k; i++) + { register soap_wchar c = soap_getchar(soap); + if ((int)c == EOF) + goto end; + *s++ = (char)(c & 0xFF); + l++; + if (n > 0 && l >= n) + goto end; + } + } +end: + *s = '\0'; +#ifdef WITH_FAST + s = soap_strdup(soap, soap->labbuf); +#else + soap_size_block(soap, NULL, i+1); + s = soap_save_block(soap, NULL, 0); +#endif + return s; +#else + return NULL; +#endif +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_envelope_begin_in(struct soap *soap) +{ register struct Namespace *p; + soap->part = SOAP_IN_ENVELOPE; + if (soap_element_begin_in(soap, "SOAP-ENV:Envelope", 0, NULL)) + { if (soap->error == SOAP_TAG_MISMATCH + && !soap_element_begin_in(soap, "Envelope", 0, NULL)) + soap->error = SOAP_VERSIONMISMATCH; + else if (soap->status) + soap->error = soap->status; + return soap->error; + } + p = soap->local_namespaces; + if (p) + { const char *ns = p[0].out; + if (!ns) + ns = p[0].ns; + if (!strcmp(ns, soap_env1)) + { soap->version = 1; /* make sure we use SOAP 1.1 */ + if (p[1].out) + SOAP_FREE(soap, p[1].out); + if ((p[1].out = (char*)SOAP_MALLOC(soap, sizeof(soap_enc1)))) + strcpy(p[1].out, soap_enc1); + } + else if (!strcmp(ns, soap_env2)) + { soap->version = 2; /* make sure we use SOAP 1.2 */ + if (p[1].out) + SOAP_FREE(soap, p[1].out); + if ((p[1].out = (char*)SOAP_MALLOC(soap, sizeof(soap_enc2)))) + strcpy(p[1].out, soap_enc2); + } + } + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_envelope_end_in(struct soap *soap) +{ soap->part = SOAP_END_ENVELOPE; + return soap_element_end_in(soap, "SOAP-ENV:Envelope"); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_body_begin_out(struct soap *soap) +{ soap->part = SOAP_IN_BODY; + if (soap->version == 1) + soap->encoding = 1; +#ifndef WITH_LEAN + if ((soap->mode & SOAP_XML_SEC) && soap_set_attr(soap, "wsu:Id", "Body")) + return soap->error; +#endif + if (soap_element(soap, "SOAP-ENV:Body", 0, NULL)) + return soap->error; + return soap_element_start_end_out(soap, NULL); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_body_end_out(struct soap *soap) +{ if (soap_element_end_out(soap, "SOAP-ENV:Body")) + return soap->error; + soap->part = SOAP_END_BODY; + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_body_begin_in(struct soap *soap) +{ soap->part = SOAP_IN_BODY; + if (soap_element_begin_in(soap, "SOAP-ENV:Body", 0, NULL)) + return soap->error; + if (!soap->body) + soap->part = SOAP_NO_BODY; + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_body_end_in(struct soap *soap) +{ if (soap->part == SOAP_NO_BODY) + return SOAP_OK; + soap->part = SOAP_END_BODY; + return soap_element_end_in(soap, "SOAP-ENV:Body"); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_recv_header(struct soap *soap) +{ if (soap_getheader(soap) && soap->error == SOAP_TAG_MISMATCH) + soap->error = SOAP_OK; + if (soap->error == SOAP_OK && soap->fheader) + soap->error = soap->fheader(soap); + return soap->error; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_set_endpoint(struct soap *soap, const char *endpoint) +{ register const char *s; + register size_t i, n; + soap->endpoint[0] = '\0'; + soap->host[0] = '\0'; + soap->path[0] = '/'; + soap->path[1] = '\0'; + soap->port = 80; + if (!endpoint || !*endpoint) + return; +#ifdef WITH_OPENSSL + if (!soap_tag_cmp(endpoint, "https:*")) + soap->port = 443; +#endif + strncpy(soap->endpoint, endpoint, sizeof(soap->endpoint) - 1); + soap->endpoint[sizeof(soap->endpoint) - 1] = '\0'; + s = strchr(endpoint, ':'); + if (s && s[1] == '/' && s[2] == '/') + s += 3; + else + s = endpoint; + n = strlen(s); + if (n >= sizeof(soap->host)) + n = sizeof(soap->host) - 1; +#ifdef WITH_IPV6 + if (s[0] == '[') + { s++; + for (i = 0; i < n; i++) + { if (s[i] == ']') + { s++; + --n; + break; + } + soap->host[i] = s[i]; + } + } + else + { for (i = 0; i < n; i++) + { soap->host[i] = s[i]; + if (s[i] == '/' || s[i] == ':') + break; + } + } +#else + for (i = 0; i < n; i++) + { soap->host[i] = s[i]; + if (s[i] == '/' || s[i] == ':') + break; + } +#endif + soap->host[i] = '\0'; + if (s[i] == ':') + { soap->port = (int)atol(s + i + 1); + for (i++; i < n; i++) + if (s[i] == '/') + break; + } + if (i < n && s[i]) + { strncpy(soap->path, s + i, sizeof(soap->path)); + soap->path[sizeof(soap->path) - 1] = '\0'; + } +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_connect(struct soap *soap, const char *endpoint, const char *action) +{ return soap_connect_command(soap, SOAP_POST, endpoint, action); +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_connect_command(struct soap *soap, int http_command, const char *endpoints, const char *action) +{ char *endpoint; + const char *s; + if (endpoints && (s = strchr(endpoints, ' '))) + { endpoint = (char*)SOAP_MALLOC(soap, strlen(endpoints) + 1); + for (;;) + { strncpy(endpoint, endpoints, s - endpoints); + endpoint[s - endpoints] = '\0'; + if (soap_try_connect_command(soap, http_command, endpoint, action) != SOAP_TCP_ERROR) + break; + if (!*s) + break; + soap->error = SOAP_OK; + while (*s == ' ') + s++; + endpoints = s; + s = strchr(endpoints, ' '); + if (!s) + s = endpoints + strlen(endpoints); + } + SOAP_FREE(soap, endpoint); + } + else + soap_try_connect_command(soap, http_command, endpoints, action); + return soap->error; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +static int +soap_try_connect_command(struct soap *soap, int http_command, const char *endpoint, const char *action) +{ char host[sizeof(soap->host)]; + int port; + size_t count; + soap->error = SOAP_OK; + strcpy(host, soap->host); /* save previous host name: if != then reconnect */ + port = soap->port; /* save previous port to compare */ + soap->status = http_command; + soap_set_endpoint(soap, endpoint); +#ifndef WITH_LEANER + if (soap->fconnect) + { if ((soap->error = soap->fconnect(soap, endpoint, soap->host, soap->port))) + return soap->error; + } + else +#endif + if (soap->fopen && *soap->host) + { if (!soap->keep_alive || !soap_valid_socket(soap->socket) || strcmp(soap->host, host) || soap->port != port || !soap->fpoll || soap->fpoll(soap)) + { soap->keep_alive = 0; /* to force close */ + soap->omode &= ~SOAP_IO_UDP; /* to force close */ + soap_closesock(soap); + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Connect/reconnect to host='%s' path='%s' port=%d\n", soap->host, soap->path, soap->port)); +#ifndef WITH_LEAN + if (!strncmp(endpoint, "soap.udp:", 9)) + soap->omode |= SOAP_IO_UDP; +#endif + soap->socket = soap->fopen(soap, endpoint, soap->host, soap->port); + if (soap->error) + return soap->error; + soap->keep_alive = ((soap->omode & SOAP_IO_KEEPALIVE) != 0); + } + } + count = soap_count_attachments(soap); + if (soap_begin_send(soap)) + return soap->error; + if (http_command == SOAP_GET) + { soap->mode &= ~SOAP_IO; + soap->mode |= SOAP_IO_BUFFER; + } +#ifndef WITH_NOHTTP + soap->action = soap_strdup(soap, action); + if ((soap->mode & SOAP_IO) != SOAP_IO_STORE && !(soap->mode & SOAP_ENC_XML) && endpoint) + { unsigned int k = soap->mode; + soap->mode &= ~(SOAP_IO | SOAP_ENC_ZLIB); + if ((k & SOAP_IO) != SOAP_IO_FLUSH) + soap->mode |= SOAP_IO_BUFFER; + if ((soap->error = soap->fpost(soap, endpoint, soap->host, soap->port, soap->path, action, count))) + return soap->error; +#ifndef WITH_LEANER + if ((k & SOAP_IO) == SOAP_IO_CHUNK) + { if (soap_flush(soap)) + return soap->error; + } +#endif + soap->mode = k; + } + if (http_command == SOAP_GET) + return soap_end_send(soap); +#endif + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEAN +SOAP_FMAC1 +char* +SOAP_FMAC2 +soap_s2base64(struct soap *soap, const unsigned char *s, char *t, int n) +{ register int i; + register unsigned long m; + register char *p; + if (!t) + t = (char*)soap_malloc(soap, (n + 2) / 3 * 4 + 1); + if (!t) + return NULL; + p = t; + t[0] = '\0'; + if (!s) + return p; + for (; n > 2; n -= 3, s += 3) + { m = s[0]; + m = (m << 8) | s[1]; + m = (m << 8) | s[2]; + for (i = 4; i > 0; m >>= 6) + t[--i] = soap_base64o[m & 0x3F]; + t += 4; + } + t[0] = '\0'; + if (n > 0) + { m = 0; + for (i = 0; i < n; i++) + m = (m << 8) | *s++; + for (; i < 3; i++) + m <<= 8; + for (i++; i > 0; m >>= 6) + t[--i] = soap_base64o[m & 0x3F]; + for (i = 3; i > n; i--) + t[i] = '='; + t[4] = '\0'; + } + return p; +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEAN +SOAP_FMAC1 +const char* +SOAP_FMAC2 +soap_base642s(struct soap *soap, const char *s, char *t, size_t l, int *n) +{ register int i, j, c; + register unsigned long m; + register const char *p; + if (!s || !*s) + { if (n) + *n = 0; + if (soap->error) + return NULL; + return SOAP_NON_NULL; + } + if (!t) + { l = (strlen(s) + 3) / 4 * 3; + t = (char*)soap_malloc(soap, l); + } + if (!t) + return NULL; + p = t; + if (n) + *n = 0; + for (;;) + { for (i = 0; i < SOAP_BLKLEN; i++) + { m = 0; + j = 0; + while (j < 4) + { c = *s++; + if (c == '=' || !c) + { i *= 3; + switch (j) + { case 2: + *t++ = (char)((m >> 4) & 0xFF); + i++; + break; + case 3: + *t++ = (char)((m >> 10) & 0xFF); + *t++ = (char)((m >> 2) & 0xFF); + i += 2; + } + if (n) + *n += i; + return p; + } + c -= '+'; + if (c >= 0 && c <= 79) + { int b = soap_base64i[c]; + if (b >= 64) + { soap->error = SOAP_TYPE; + return NULL; + } + m = (m << 6) + b; + j++; + } + else if (!soap_blank(c + '+')) + { soap->error = SOAP_TYPE; + return NULL; + } + } + *t++ = (char)((m >> 16) & 0xFF); + *t++ = (char)((m >> 8) & 0xFF); + *t++ = (char)(m & 0xFF); + if (l < 3) + { if (n) + *n += i; + return p; + } + l -= 3; + } + if (n) + *n += 3 * SOAP_BLKLEN; + } +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEAN +SOAP_FMAC1 +char* +SOAP_FMAC2 +soap_s2hex(struct soap *soap, const unsigned char *s, char *t, int n) +{ register char *p; + if (!t) + t = (char*)soap_malloc(soap, 2 * n + 1); + if (!t) + return NULL; + p = t; + t[0] = '\0'; + if (s) + { for (; n > 0; n--) + { register int m = *s++; + *t++ = (char)((m >> 4) + (m > 159 ? 'a' - 10 : '0')); + m &= 0x0F; + *t++ = (char)(m + (m > 9 ? 'a' - 10 : '0')); + } + } + *t++ = '\0'; + return p; +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEAN +SOAP_FMAC1 +const char* +SOAP_FMAC2 +soap_hex2s(struct soap *soap, const char *s, char *t, size_t l, int *n) +{ register const char *p; + if (!s || !*s) + { if (n) + *n = 0; + if (soap->error) + return NULL; + return SOAP_NON_NULL; + } + if (!t) + { l = strlen(s) / 2; + t = (char*)soap_malloc(soap, l); + } + if (!t) + return NULL; + p = t; + while (l) + { register int d1, d2; + d1 = *s++; + if (!d1) + break; + d2 = *s++; + if (!d2) + break; + *t++ = ((d1 >= 'A' ? (d1 & 0x7) + 9 : d1 - '0') << 4) + (d2 >= 'A' ? (d2 & 0x7) + 9 : d2 - '0'); + l--; + } + if (n) + *n = (int)(t - p); + return p; +} +#endif + +/******************************************************************************/ +#ifndef WITH_NOHTTP +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_puthttphdr(struct soap *soap, int status, size_t count) +{ if (soap->status != SOAP_GET) + { register const char *s = "text/xml; charset=utf-8"; + register int err = SOAP_OK; +#ifndef WITH_LEANER + register const char *r = NULL; +#endif + if ((status == SOAP_FILE || soap->status == SOAP_POST_FILE) && soap->http_content) + s = soap->http_content; + else if (status == SOAP_HTML) + s = "text/html; charset=utf-8"; + else if (count || ((soap->omode & SOAP_IO) == SOAP_IO_CHUNK)) + { if (soap->version == 2) + s = "application/soap+xml; charset=utf-8"; + } +#ifndef WITH_LEANER + if (soap->mode & (SOAP_ENC_DIME | SOAP_ENC_MTOM)) + { if (soap->mode & SOAP_ENC_MTOM) + { if (soap->version == 2) + r = "application/soap+xml"; + else + r = "text/xml"; + s = "application/xop+xml"; + } + else + s = "application/dime"; + } + if ((soap->mode & SOAP_ENC_MIME) && soap->mime.boundary && strlen(soap->mime.boundary) + strlen(soap->mime.start ? soap->mime.start : SOAP_STR_EOS) < sizeof(soap->tmpbuf) - 80) + { register const char *t = strchr(s, ';'); + sprintf(soap->tmpbuf, "multipart/related; charset=utf-8; boundary=\"%s\"; type=\"", soap->mime.boundary); + if (t) + { strncat(soap->tmpbuf, s, t - s); + soap->tmpbuf[sizeof(soap->tmpbuf)-1] = '\0'; + } + else + strcat(soap->tmpbuf, s); + if (soap->mime.start) + { strcat(soap->tmpbuf, "\"; start=\""); + strcat(soap->tmpbuf, soap->mime.start); + } + strcat(soap->tmpbuf, "\""); + if (r) + { strcat(soap->tmpbuf, "; start-info=\""); + strcat(soap->tmpbuf, r); + strcat(soap->tmpbuf, "\""); + } + s = soap->tmpbuf; + } +#endif + if (s && (err = soap->fposthdr(soap, "Content-Type", s))) + return err; +#ifdef WITH_ZLIB + if ((soap->omode & SOAP_ENC_ZLIB)) + { +#ifdef WITH_GZIP + err = soap->fposthdr(soap, "Content-Encoding", soap->zlib_out == SOAP_ZLIB_DEFLATE ? "deflate" : "gzip"); +#else + err = soap->fposthdr(soap, "Content-Encoding", "deflate"); +#endif + if (err) + return err; + } +#endif +#ifndef WITH_LEANER + if ((soap->omode & SOAP_IO) == SOAP_IO_CHUNK) + err = soap->fposthdr(soap, "Transfer-Encoding", "chunked"); + else +#endif + if (s) + { sprintf(soap->tmpbuf, "%lu", (unsigned long)count); + err = soap->fposthdr(soap, "Content-Length", soap->tmpbuf); + } + if (err) + return err; + } + return soap->fposthdr(soap, "Connection", soap->keep_alive ? "keep-alive" : "close"); +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOHTTP +#ifndef PALM_1 +static int +http_get(struct soap *soap) +{ return SOAP_GET_METHOD; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOHTTP +#ifndef PALM_1 +static int +http_405(struct soap *soap) +{ return 405; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOHTTP +#ifndef PALM_1 +static int +http_post(struct soap *soap, const char *endpoint, const char *host, int port, const char *path, const char *action, size_t count) +{ register const char *s; + register int err; + if (soap->status == SOAP_GET) + s = "GET"; + else + s = "POST"; +#ifdef PALM + if (!endpoint || (soap_tag_cmp(endpoint, "http:*") && soap_tag_cmp(endpoint, "https:*") && strncmp(endpoint, "httpg:", 6)) && strncmp(endpoint, "_beam:", 6) && strncmp(endpoint, "_local:", 7) && strncmp(endpoint, "_btobex:", 8)) +#else + if (!endpoint || (soap_tag_cmp(endpoint, "http:*") && soap_tag_cmp(endpoint, "https:*") && strncmp(endpoint, "httpg:", 6))) +#endif + return SOAP_OK; + if (strlen(endpoint) + strlen(soap->http_version) > sizeof(soap->tmpbuf) - 80) + return soap->error = SOAP_EOM; + if (soap->proxy_host && soap_tag_cmp(endpoint, "https:*")) + sprintf(soap->tmpbuf, "%s %s HTTP/%s", s, endpoint, soap->http_version); + else + sprintf(soap->tmpbuf, "%s /%s HTTP/%s", s, (*path == '/' ? path + 1 : path), soap->http_version); + if ((err = soap->fposthdr(soap, soap->tmpbuf, NULL))) + return err; +#ifdef WITH_OPENSSL + if ((soap->ssl && soap->port != 443) || (!soap->ssl && soap->port != 80)) + sprintf(soap->tmpbuf, "%s:%d", host, port); + else + strcpy(soap->tmpbuf, host); +#else + if (port != 80) + sprintf(soap->tmpbuf, "%s:%d", host, port); + else + strcpy(soap->tmpbuf, host); +#endif + if ((err = soap->fposthdr(soap, "Host", soap->tmpbuf)) + || (err = soap->fposthdr(soap, "User-Agent", "gSOAP/2.7")) + || (err = soap_puthttphdr(soap, SOAP_OK, count))) + return err; +#ifdef WITH_ZLIB +#ifdef WITH_GZIP + if ((err = soap->fposthdr(soap, "Accept-Encoding", "gzip, deflate"))) +#else + if ((err = soap->fposthdr(soap, "Accept-Encoding", "deflate"))) +#endif + return err; +#endif +#ifndef WITH_LEAN + if (soap->userid && soap->passwd && strlen(soap->userid) + strlen(soap->passwd) < 761) + { sprintf(soap->tmpbuf + 262, "%s:%s", soap->userid, soap->passwd); + strcpy(soap->tmpbuf, "Basic "); + soap_s2base64(soap, (const unsigned char*)(soap->tmpbuf + 262), soap->tmpbuf + 6, (int)strlen(soap->tmpbuf + 262)); + if ((err = soap->fposthdr(soap, "Authorization", soap->tmpbuf))) + return err; + } + if (soap->proxy_userid && soap->proxy_passwd && strlen(soap->proxy_userid) + strlen(soap->proxy_passwd) < 761) + { sprintf(soap->tmpbuf + 262, "%s:%s", soap->proxy_userid, soap->proxy_passwd); + strcpy(soap->tmpbuf, "Basic "); + soap_s2base64(soap, (const unsigned char*)(soap->tmpbuf + 262), soap->tmpbuf + 6, (int)strlen(soap->tmpbuf + 262)); + if ((err = soap->fposthdr(soap, "Proxy-Authorization", soap->tmpbuf))) + return err; + } +#endif +#ifdef WITH_COOKIES +#ifdef WITH_OPENSSL + if (soap_putcookies(soap, host, path, soap->ssl != NULL)) + return soap->error; +#else + if (soap_putcookies(soap, host, path, 0)) + return soap->error; +#endif +#endif + if (soap->status != SOAP_GET && (soap->version == 1 || (action && *action))) + { sprintf(soap->tmpbuf, "\"%s\"", action && strlen(action) < sizeof(soap->tmpbuf) - 3 ? action : SOAP_STR_EOS); + if ((err = soap->fposthdr(soap, "SOAPAction", soap->tmpbuf))) + return err; + } + return soap->fposthdr(soap, NULL, NULL); +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOHTTP +#ifndef PALM_1 +static int +http_send_header(struct soap *soap, const char *s) +{ register const char *t; + do + { t = strchr(s, '\n'); /* disallow \n in HTTP headers */ + if (!t) + t = s + strlen(s); + if (soap_send_raw(soap, s, t - s)) + return soap->error; + s = t + 1; + } while (*t); + return SOAP_OK; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOHTTP +#ifndef PALM_1 +static int +http_post_header(struct soap *soap, const char *key, const char *val) +{ if (key) + { if (http_send_header(soap, key)) + return soap->error; + if (val && (soap_send_raw(soap, ": ", 2) || http_send_header(soap, val))) + return soap->error; + } + return soap_send_raw(soap, "\r\n", 2); +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOHTTP +#ifndef PALM_1 +static int +http_response(struct soap *soap, int status, size_t count) +{ register int err; +#ifdef WMW_RPM_IO + if (soap->rpmreqid) + httpOutputEnable(soap->rpmreqid); +#endif + if (strlen(soap->http_version) > 4) + return soap->error = SOAP_EOM; + if (!status || status == SOAP_HTML || status == SOAP_FILE) + { const char *s; + if (count || ((soap->omode & SOAP_IO) == SOAP_IO_CHUNK)) + s = "200 OK"; + else + s = "202 ACCEPTED"; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Status = %s\n", s)); +#ifdef WMW_RPM_IO + if (soap->rpmreqid || soap_valid_socket(soap->master) || soap_valid_socket(soap->socket)) /* RPM behaves as if standalone */ +#else + if (soap_valid_socket(soap->master) || soap_valid_socket(soap->socket)) /* standalone application (socket) or CGI (stdin/out)? */ +#endif + { sprintf(soap->tmpbuf, "HTTP/%s %s", soap->http_version, s); + if ((err = soap->fposthdr(soap, soap->tmpbuf, NULL))) + return err; + } + else if ((err = soap->fposthdr(soap, "Status", s))) /* CGI header */ + return err; + } + else if (status >= 200 && status < 600) + { sprintf(soap->tmpbuf, "HTTP/%s %d %s", soap->http_version, status, http_error(soap, status)); + if ((err = soap->fposthdr(soap, soap->tmpbuf, NULL))) + return err; +#ifndef WITH_LEAN + if (status == 401) + { sprintf(soap->tmpbuf, "Basic realm=\"%s\"", (soap->authrealm && strlen(soap->authrealm) < sizeof(soap->tmpbuf) - 14) ? soap->authrealm : "gSOAP Web Service"); + if ((err = soap->fposthdr(soap, "WWW-Authenticate", soap->tmpbuf))) + return err; + } + else if ((status >= 301 && status <= 303) || status == 307) + { if ((err = soap->fposthdr(soap, "Location", soap->endpoint))) + return err; + } +#endif + } + else + { const char *s = *soap_faultcode(soap); + if (status >= SOAP_GET_METHOD && status <= SOAP_HTTP_METHOD) + s = "405 Method Not Allowed"; + else if (soap->version == 2 && (!s || !strcmp(s, "SOAP-ENV:Sender"))) + s = "400 Bad Request"; + else + s = "500 Internal Server Error"; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Error %s (status=%d)\n", s, status)); +#ifdef WMW_RPM_IO + if (soap->rpmreqid || soap_valid_socket(soap->master) || soap_valid_socket(soap->socket)) /* RPM behaves as if standalone */ +#else + if (soap_valid_socket(soap->master) || soap_valid_socket(soap->socket)) /* standalone application */ +#endif + { sprintf(soap->tmpbuf, "HTTP/%s %s", soap->http_version, s); + if ((err = soap->fposthdr(soap, soap->tmpbuf, NULL))) + return err; + } + else if ((err = soap->fposthdr(soap, "Status", s))) /* CGI */ + return err; + } + if ((err = soap->fposthdr(soap, "Server", "gSOAP/2.7")) + || (err = soap_puthttphdr(soap, status, count))) + return err; +#ifdef WITH_COOKIES + if (soap_putsetcookies(soap)) + return soap->error; +#endif + return soap->fposthdr(soap, NULL, NULL); +} +#endif +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_response(struct soap *soap, int status) +{ register size_t count; + if (!(soap->omode & (SOAP_ENC_XML | SOAP_IO_STORE /* this tests for chunking too */)) + && (status == SOAP_HTML || status == SOAP_FILE)) + soap->omode = (soap->omode & ~SOAP_IO) | SOAP_IO_STORE; + soap->status = status; + count = soap_count_attachments(soap); + if (soap_begin_send(soap)) + return soap->error; +#ifndef WITH_NOHTTP + if ((soap->mode & SOAP_IO) != SOAP_IO_STORE && !(soap->mode & SOAP_ENC_XML)) + { register int n = soap->mode; + soap->mode &= ~(SOAP_IO | SOAP_ENC_ZLIB); + if ((n & SOAP_IO) != SOAP_IO_FLUSH) + soap->mode |= SOAP_IO_BUFFER; + if ((soap->error = soap->fresponse(soap, status, count))) + return soap->error; +#ifndef WITH_LEANER + if ((n & SOAP_IO) == SOAP_IO_CHUNK) + { if (soap_flush(soap)) + return soap->error; + } +#endif + soap->mode = n; + } +#endif + return SOAP_OK; +} +#endif + +/******************************************************************************/ +#ifndef WITH_LEAN +static const char* +soap_set_validation_fault(struct soap *soap, const char *s, const char *t) +{ if (*soap->tag) + sprintf(soap->msgbuf, "Validation constraint violation: %s%s in element '%s'", s, t?t:SOAP_STR_EOS, soap->tag); + else + sprintf(soap->msgbuf, "Validation constraint violation: %s%s", s, t?t:SOAP_STR_EOS); + return soap->msgbuf; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_set_fault(struct soap *soap) +{ const char **c = soap_faultcode(soap); + const char **s = soap_faultstring(soap); + if (soap->fseterror) + soap->fseterror(soap, c, s); + if (!*c) + { if (soap->version == 2) + *c = "SOAP-ENV:Sender"; + else + *c = "SOAP-ENV:Client"; + } + if (*s) + return; + switch (soap->error) + { +#ifndef WITH_LEAN + case SOAP_CLI_FAULT: + *s = "Client fault"; + break; + case SOAP_SVR_FAULT: + *s = "Server fault"; + break; + case SOAP_TAG_MISMATCH: + *s = soap_set_validation_fault(soap, "tag name or namespace mismatch", NULL); + break; + case SOAP_TYPE: + *s = soap_set_validation_fault(soap, "data type mismatch ", soap->type); + break; + case SOAP_SYNTAX_ERROR: + *s = "Well-formedness violation"; + break; + case SOAP_NO_TAG: + *s = "No XML element tag"; + break; + case SOAP_MUSTUNDERSTAND: + *c = "SOAP-ENV:MustUnderstand"; + sprintf(soap->msgbuf, "The data in element '%s' must be understood but cannot be handled", soap->tag); + *s = soap->msgbuf; + break; + case SOAP_VERSIONMISMATCH: + *c = "SOAP-ENV:VersionMismatch"; + *s = "Invalid SOAP message or SOAP version mismatch"; + break; + case SOAP_DATAENCODINGUNKNOWN: + *c = "SOAP-ENV:DataEncodingUnknown"; + *s = "Unsupported SOAP data encoding"; + break; + case SOAP_NAMESPACE: + *s = soap_set_validation_fault(soap, "namespace error", NULL); + break; + case SOAP_USER_ERROR: + *s = "User error"; + break; + case SOAP_FATAL_ERROR: + *s = "Fatal error"; + break; + case SOAP_NO_METHOD: + sprintf(soap->msgbuf, "Method '%s' not implemented: method name or namespace not recognized", soap->tag); + *s = soap->msgbuf; + break; + case SOAP_NO_DATA: + *s = "Data required for operation"; + break; + case SOAP_GET_METHOD: + *s = "HTTP GET method not implemented"; + break; + case SOAP_PUT_METHOD: + *s = "HTTP PUT method not implemented"; + break; + case SOAP_HEAD_METHOD: + *s = "HTTP HEAD method not implemented"; + break; + case SOAP_HTTP_METHOD: + *s = "HTTP method not implemented"; + break; + case SOAP_EOM: + *s = "Out of memory"; + break; + case SOAP_MOE: + *s = "Memory overflow or memory corruption error"; + break; + case SOAP_HDR: + *s = "Header line too long"; + break; + case SOAP_IOB: + *s = "Array index out of bounds"; + break; + case SOAP_NULL: + *s = soap_set_validation_fault(soap, "nil not allowed", NULL); + break; + case SOAP_DUPLICATE_ID: + *s = soap_set_validation_fault(soap, "multiple definitions of id ", soap->id); + if (soap->version == 2) + *soap_faultsubcode(soap) = "SOAP-ENC:DuplicateID"; + break; + case SOAP_MISSING_ID: + *s = soap_set_validation_fault(soap, "missing id for ref ", soap->id); + if (soap->version == 2) + *soap_faultsubcode(soap) = "SOAP-ENC:MissingID"; + break; + case SOAP_HREF: + *s = soap_set_validation_fault(soap, "incompatible object type ref/id pair ", soap->id); + break; + case SOAP_FAULT: + break; +#ifndef WITH_NOIO + case SOAP_UDP_ERROR: + *s = "Message too large for UDP packet"; + break; + case SOAP_TCP_ERROR: + *s = tcp_error(soap); + break; +#endif + case SOAP_HTTP_ERROR: + *s = "An HTTP processing error occurred"; + break; + case SOAP_SSL_ERROR: +#ifdef WITH_OPENSSL + *s = "SSL error"; +#else + *s = "OpenSSL not installed: recompile with -DWITH_OPENSSL"; +#endif + break; + case SOAP_PLUGIN_ERROR: + *s = "Plugin registry error"; + break; + case SOAP_DIME_ERROR: + *s = "DIME format error"; + break; + case SOAP_DIME_HREF: + *s = "DIME href to missing attachment"; + break; + case SOAP_DIME_MISMATCH: + *s = "DIME version/transmission error"; + break; + case SOAP_DIME_END: + *s = "End of DIME error"; + break; + case SOAP_MIME_ERROR: + *s = "MIME format error"; + break; + case SOAP_MIME_HREF: + *s = "MIME href to missing attachment"; + break; + case SOAP_MIME_END: + *s = "End of MIME error"; + break; + case SOAP_ZLIB_ERROR: +#ifdef WITH_ZLIB + sprintf(soap->msgbuf, "Zlib/gzip error: '%s'", soap->d_stream->msg?soap->d_stream->msg:SOAP_STR_EOS); + *s = soap->msgbuf; +#else + *s = "Zlib/gzip not installed for (de)compression: recompile with -DWITH_GZIP"; +#endif + break; + case SOAP_REQUIRED: + *s = soap_set_validation_fault(soap, "missing required attribute", NULL); + break; + case SOAP_PROHIBITED: + *s = soap_set_validation_fault(soap, "prohibited attribute present", NULL); + break; + case SOAP_OCCURS: + *s = soap_set_validation_fault(soap, "occurrence violation", NULL); + break; + case SOAP_LENGTH: + *s = soap_set_validation_fault(soap, "content range or length violation", NULL); + break; + case SOAP_FD_EXCEEDED: + *s = "Maximum number of open connections was reached (no define HAVE_POLL): increase FD_SETSIZE"; + break; + case SOAP_STOP: + *s = "Stopped: no response sent"; + break; +#endif + case SOAP_EOF: +#ifndef WITH_NOIO + strcpy(soap->msgbuf, soap_strerror(soap)); +#ifndef WITH_LEAN + if (strlen(soap->msgbuf) + 25 < sizeof(soap->msgbuf)) + { memmove(soap->msgbuf + 25, soap->msgbuf, strlen(soap->msgbuf) + 1); + memcpy(soap->msgbuf, "End of file or no input: ", 25); + } +#endif + *s = soap->msgbuf; + break; +#else + *s = "End of file or no input"; + break; +#endif + default: +#ifndef WITH_NOHTTP +#ifndef WITH_LEAN + if (soap->error > 200 && soap->error < 600) + { sprintf(soap->msgbuf, "HTTP Error: %d %s", soap->error, http_error(soap, soap->error)); + *s = soap->msgbuf; + } + else +#endif +#endif + { sprintf(soap->msgbuf, "Error %d", soap->error); + *s = soap->msgbuf; + } + } +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_send_fault(struct soap *soap) +{ register int status = soap->error; + if (status == SOAP_STOP) + return status; + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Sending back fault struct for error code %d\n", soap->error)); + soap->keep_alive = 0; /* to terminate connection */ + soap_set_fault(soap); + if (soap->error < 200 && soap->error != SOAP_FAULT) + soap->header = NULL; + if (status != SOAP_EOF || (!soap->recv_timeout && !soap->send_timeout)) + { int r = 1; +#ifndef WITH_NOIO + if (soap->fpoll && soap->fpoll(soap)) + r = 0; +#ifndef WITH_LEAN + else if (soap_valid_socket(soap->socket)) + { r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_SND, 0); + if (r > 0) + { if (!(r & SOAP_TCP_SELECT_SND) + || ((r & SOAP_TCP_SELECT_RCV) + && recv(soap->socket, soap->tmpbuf, 1, MSG_PEEK) < 0)) + r = 0; + } + } +#endif +#endif + if (r > 0) + { soap->error = SOAP_OK; + soap_serializeheader(soap); + soap_serializefault(soap); + soap_begin_count(soap); + if (soap->mode & SOAP_IO_LENGTH) + { soap_envelope_begin_out(soap); + soap_putheader(soap); + soap_body_begin_out(soap); + soap_putfault(soap); + soap_body_end_out(soap); + soap_envelope_end_out(soap); + } + soap_end_count(soap); + if (soap_response(soap, status) + || soap_envelope_begin_out(soap) + || soap_putheader(soap) + || soap_body_begin_out(soap) + || soap_putfault(soap) + || soap_body_end_out(soap) + || soap_envelope_end_out(soap)) + return soap_closesock(soap); + soap_end_send(soap); + } + } + soap->error = status; + return soap_closesock(soap); +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_recv_fault(struct soap *soap) +{ register int status = soap->error; + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Receiving SOAP Fault\n")); + soap->error = SOAP_OK; + if (soap_getfault(soap)) + { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Error: soap_get_soapfault() failed. Is this a SOAP message at all?\n")); + *soap_faultcode(soap) = (soap->version == 2 ? "SOAP-ENV:Sender" : "SOAP-ENV:Client"); + soap->error = status; + soap_set_fault(soap); + } + else + { register const char *s = *soap_faultcode(soap); + if (!soap_match_tag(soap, s, "SOAP-ENV:Server") || !soap_match_tag(soap, s, "SOAP-ENV:Receiver")) + status = SOAP_SVR_FAULT; + else if (!soap_match_tag(soap, s, "SOAP-ENV:Client") || !soap_match_tag(soap, s, "SOAP-ENV:Sender")) + status = SOAP_CLI_FAULT; + else if (!soap_match_tag(soap, s, "SOAP-ENV:MustUnderstand")) + status = SOAP_MUSTUNDERSTAND; + else if (!soap_match_tag(soap, s, "SOAP-ENV:VersionMismatch")) + status = SOAP_VERSIONMISMATCH; + else + { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Fault code %s\n", s)); + status = SOAP_FAULT; + } + if (soap_body_end_in(soap) + || soap_envelope_end_in(soap) + || soap_end_recv(soap)) + return soap_closesock(soap); + soap->error = status; + } + return soap_closesock(soap); +} +#endif + +/******************************************************************************/ +#ifndef WITH_NOHTTP +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_send_empty_response(struct soap *soap, int httpstatuscode) +{ register soap_mode m = soap->omode; + soap->count = 0; + if ((m & SOAP_IO) == SOAP_IO_CHUNK) + soap->omode = (m & ~SOAP_IO) | SOAP_IO_BUFFER; + if (soap_response(soap, httpstatuscode) || soap_end_send(soap)) + { soap->omode = m; + return soap_closesock(soap); + } + soap->omode = m; + return SOAP_OK; +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOHTTP +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_recv_empty_response(struct soap *soap) +{ if (!soap_begin_recv(soap)) + soap_end_recv(soap); + else if (soap->error == SOAP_NO_DATA || soap->error == 202) + soap->error = SOAP_OK; + return soap_closesock(soap); +} +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_NOIO +#ifndef PALM_1 +static const char* +soap_strerror(struct soap *soap) +{ register int err = soap->errnum; + if (err) + { +#ifndef WIN32 + return strerror(err); +#else +#ifndef UNDER_CE + DWORD len; + *soap->msgbuf = '\0'; + len = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)soap->msgbuf, (DWORD)sizeof(soap->msgbuf), NULL); +#else + DWORD i, len; + *soap->msgbuf = '\0'; + len = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, 0, (LPTSTR)soap->msgbuf, (DWORD)(sizeof(soap->msgbuf)/sizeof(TCHAR)), NULL); + for (i = 0; i <= len; i++) + { if (((TCHAR*)soap->msgbuf)[i] < 0x80) + soap->msgbuf[i] = (char)((TCHAR*)soap->msgbuf)[i]; + else + soap->msgbuf[i] = '?'; + } +#endif + return soap->msgbuf; +#endif + } +#ifndef WITH_LEAN + if (soap->recv_timeout > 0) + { if (soap->send_timeout > 0) + sprintf(soap->msgbuf, "Operation interrupted or timed out after %ds send or %ds receive delay", soap->send_timeout, soap->recv_timeout); + else + sprintf(soap->msgbuf, "Operation interrupted or timed out after %ds receive delay", soap->recv_timeout); + return soap->msgbuf; + } +#endif + return "Operation interrupted or timed out"; +} +#endif +#endif + +/******************************************************************************/ +#ifndef PALM_2 +static int +soap_set_error(struct soap *soap, const char *faultcode, const char *faultsubcodeQName, const char *faultstring, const char *faultdetailXML, int soaperror) +{ *soap_faultcode(soap) = faultcode; + if (faultsubcodeQName) + *soap_faultsubcode(soap) = faultsubcodeQName; + *soap_faultstring(soap) = faultstring; + if (faultdetailXML && *faultdetailXML) + { register const char **s = soap_faultdetail(soap); + if (s) + *s = faultdetailXML; + } + return soap->error = soaperror; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_set_sender_error(struct soap *soap, const char *faultstring, const char *faultdetailXML, int soaperror) +{ return soap_set_error(soap, soap->version == 2 ? "SOAP-ENV:Sender" : "SOAP-ENV:Client", NULL, faultstring, faultdetailXML, soaperror); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_set_receiver_error(struct soap *soap, const char *faultstring, const char *faultdetailXML, int soaperror) +{ return soap_set_error(soap, soap->version == 2 ? "SOAP-ENV:Receiver" : "SOAP-ENV:Server", NULL, faultstring, faultdetailXML, soaperror); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +static int +soap_copy_fault(struct soap *soap, const char *faultcode, const char *faultsubcodeQName, const char *faultstring, const char *faultdetailXML) +{ char *r = NULL, *s = NULL, *t = NULL; + if (faultsubcodeQName) + r = soap_strdup(soap, faultsubcodeQName); + if (faultstring) + s = soap_strdup(soap, faultstring); + if (faultdetailXML) + t = soap_strdup(soap, faultdetailXML); + return soap_set_error(soap, faultcode, r, s, t, SOAP_FAULT); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_sender_fault(struct soap *soap, const char *faultstring, const char *faultdetailXML) +{ return soap_sender_fault_subcode(soap, NULL, faultstring, faultdetailXML); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_sender_fault_subcode(struct soap *soap, const char *faultsubcodeQName, const char *faultstring, const char *faultdetailXML) +{ return soap_copy_fault(soap, soap->version == 2 ? "SOAP-ENV:Sender" : "SOAP-ENV:Client", faultsubcodeQName, faultstring, faultdetailXML); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_receiver_fault(struct soap *soap, const char *faultstring, const char *faultdetailXML) +{ return soap_receiver_fault_subcode(soap, NULL, faultstring, faultdetailXML); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_receiver_fault_subcode(struct soap *soap, const char *faultsubcodeQName, const char *faultstring, const char *faultdetailXML) +{ return soap_copy_fault(soap, soap->version == 2 ? "SOAP-ENV:Receiver" : "SOAP-ENV:Server", faultsubcodeQName, faultstring, faultdetailXML); +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +#ifndef WITH_NOSTDLIB +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_print_fault(struct soap *soap, FILE *fd) +{ if (soap_check_state(soap)) + fprintf(fd, "Error: soap struct state not initialized\n"); + else if (soap->error) + { const char *c, *v = NULL, *s, **d; + d = soap_faultcode(soap); + if (!*d) + soap_set_fault(soap); + c = *d; + if (soap->version == 2) + v = *soap_faultsubcode(soap); + s = *soap_faultstring(soap); + d = soap_faultdetail(soap); + fprintf(fd, "%s%d fault: %s [%s]\n\"%s\"\nDetail: %s\n", soap->version ? "SOAP 1." : "Error ", soap->version ? (int)soap->version : soap->error, c, v ? v : "no subcode", s ? s : "[no reason]", d && *d ? *d : "[no detail]"); + } +} +#endif +#endif + +/******************************************************************************/ +#ifdef __cplusplus +#ifndef WITH_LEAN +#ifndef WITH_NOSTDLIB +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_stream_fault(struct soap *soap, std::ostream& os) +{ if (soap_check_state(soap)) + os << "Error: soap struct state not initialized\n"; + else if (soap->error) + { const char *c, *v = NULL, *s, **d; + d = soap_faultcode(soap); + if (!*d) + soap_set_fault(soap); + c = *d; + if (soap->version == 2) + v = *soap_faultsubcode(soap); + s = *soap_faultstring(soap); + d = soap_faultdetail(soap); + os << (soap->version ? "SOAP 1." : "Error ") + << (soap->version ? (int)soap->version : soap->error) + << " fault: " << c + << "[" << (v ? v : "no subcode") << "]" + << std::endl + << "\"" << (s ? s : "[no reason]") << "\"" + << std::endl + << "Detail: " << (d && *d ? *d : "[no detail]") + << std::endl; + } +} +#endif +#endif +#endif + +/******************************************************************************/ +#ifndef WITH_LEAN +#ifndef WITH_NOSTDLIB +SOAP_FMAC1 +char* +SOAP_FMAC2 +soap_sprint_fault(struct soap *soap, char *buf, size_t len) +{ if (soap_check_state(soap)) + strncpy(buf, "Error: soap struct not initialized", len); + else if (soap->error) + { const char *c, *v = NULL, *s, **d; + d = soap_faultcode(soap); + if (!*d) + soap_set_fault(soap); + c = *d; + if (soap->version == 2) + v = *soap_faultsubcode(soap); + s = *soap_faultstring(soap); + d = soap_faultdetail(soap); +#ifdef WIN32 + _snprintf +#else + snprintf +#endif + (buf, len, "%s%d fault: %s [%s]\n\"%s\"\nDetail: %s\n", soap->version ? "SOAP 1." : "Error ", soap->version ? (int)soap->version : soap->error, c, v ? v : "no subcode", s ? s : "[no reason]", d && *d ? *d : "[no detail]"); + } + return buf; +} +#endif +#endif + +/******************************************************************************/ +#ifndef PALM_1 +#ifndef WITH_NOSTDLIB +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_print_fault_location(struct soap *soap, FILE *fd) +{ +#ifndef WITH_LEAN + int i, j, c1, c2; + if (soap->error && soap->bufidx <= soap->buflen && soap->buflen > 0 && soap->buflen <= SOAP_BUFLEN) + { i = (int)soap->bufidx - 1; + if (i <= 0) + i = 0; + c1 = soap->buf[i]; + soap->buf[i] = '\0'; + if ((int)soap->buflen >= i + 1024) + j = i + 1023; + else + j = (int)soap->buflen - 1; + c2 = soap->buf[j]; + soap->buf[j] = '\0'; + fprintf(fd, "%s%c\n\n", soap->buf, c1); + if (soap->bufidx < soap->buflen) + fprintf(fd, "%s\n", soap->buf + soap->bufidx); + soap->buf[i] = c1; + soap->buf[j] = c2; + } +#endif +} +#endif +#endif + +/******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_register_plugin_arg(struct soap *soap, int (*fcreate)(struct soap*, struct soap_plugin*, void*), void *arg) +{ register struct soap_plugin *p; + register int r; + if (!(p = (struct soap_plugin*)SOAP_MALLOC(soap, sizeof(struct soap_plugin)))) + return soap->error = SOAP_EOM; + p->id = NULL; + p->data = NULL; + p->fcopy = NULL; + p->fdelete = NULL; + r = fcreate(soap, p, arg); + if (!r && p->fdelete) + { p->next = soap->plugins; + soap->plugins = p; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Registered '%s' plugin\n", p->id)); + return SOAP_OK; + } + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not register plugin '%s': plugin returned error %d (or fdelete callback not set)\n", p->id?p->id:"?", r)); + SOAP_FREE(soap, p); + return r; +} +#endif + +/******************************************************************************/ +#ifndef PALM_1 +static void * +fplugin(struct soap *soap, const char *id) +{ register struct soap_plugin *p; + for (p = soap->plugins; p; p = p->next) + if (p->id == id || !strcmp(p->id, id)) + return p->data; + return NULL; +} +#endif + +/******************************************************************************/ +#ifndef PALM_2 +SOAP_FMAC1 +void * +SOAP_FMAC2 +soap_lookup_plugin(struct soap *soap, const char *id) +{ return soap->fplugin(soap, id); +} +#endif + +/******************************************************************************/ +#ifdef __cplusplus +} +#endif + +/******************************************************************************\ + * + * C++ soap struct methods + * +\******************************************************************************/ + +#ifdef __cplusplus +soap::soap() +{ soap_init(this); +} +#endif + +/******************************************************************************/ +#ifdef __cplusplus +soap::soap(soap_mode m) +{ soap_init1(this, m); +} +#endif + +/******************************************************************************/ +#ifdef __cplusplus +soap::soap(soap_mode im, soap_mode om) +{ soap_init2(this, im, om); +} +#endif + +/******************************************************************************/ +#ifdef __cplusplus +soap::soap(const struct soap& soap) +{ soap_copy_context(this, &soap); +} +#endif + +/******************************************************************************/ +#ifdef __cplusplus +soap::~soap() +{ soap_destroy(this); + soap_end(this); + soap_done(this); +} +#endif + +/******************************************************************************/ diff --git a/dep/gsoap/stdsoap2.h b/dep/gsoap/stdsoap2.h new file mode 100644 index 00000000000..0aa8e409578 --- /dev/null +++ b/dep/gsoap/stdsoap2.h @@ -0,0 +1,2360 @@ +/* + stdsoap2.h 2.7.15 + + gSOAP runtime engine + +gSOAP XML Web services tools +Copyright (C) 2000-2009, Robert van Engelen, Genivia Inc., All Rights Reserved. +This part of the software is released under ONE of the following licenses: +GPL, or the gSOAP public license, or Genivia's license for commercial use. +-------------------------------------------------------------------------------- +Contributors: + +Wind River Systems, Inc., for the following additions + - vxWorks compatible +-------------------------------------------------------------------------------- +gSOAP public license. + +The contents of this file are subject to the gSOAP Public License Version 1.3 +(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.cs.fsu.edu/~engelen/soaplicense.html +Software distributed under the License is distributed on an "AS IS" basis, +WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License +for the specific language governing rights and limitations under the License. + +The Initial Developer of the Original Code is Robert A. van Engelen. +Copyright (C) 2000-2009, Robert van Engelen, Genivia Inc., All Rights Reserved. +-------------------------------------------------------------------------------- +GPL license. + +This program is free software; you can redistribute it and/or modify it under +the terms of the GNU General Public License as published by the Free Software +Foundation; either version 2 of the License, or (at your option) any later +version. + +This program is distributed in the hope that it will be useful, but WITHOUT ANY +WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A +PARTICULAR PURPOSE. See the GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along with +this program; if not, write to the Free Software Foundation, Inc., 59 Temple +Place, Suite 330, Boston, MA 02111-1307 USA + +Author contact information: +engelen@genivia.com / engelen@acm.org + +This program is released under the GPL with the additional exemption that +compiling, linking, and/or using OpenSSL is allowed. +-------------------------------------------------------------------------------- +A commercial use license is available from Genivia, Inc., contact@genivia.com +-------------------------------------------------------------------------------- +*/ + +#ifdef WITH_SOAPDEFS_H +# include "soapdefs.h" /* include user-defined stuff */ +#endif + +#ifndef _THREAD_SAFE +# define _THREAD_SAFE +#endif + +#ifndef OPENSERVER +# ifndef _REENTRANT +# define _REENTRANT +# endif +#endif + +#ifndef SOAP_FMAC1 /* stdsoap2.h declaration macro */ +# define SOAP_FMAC1 +#endif + +#ifndef SOAP_FMAC2 /* stdsoap2.h declaration macro */ +# define SOAP_FMAC2 +#endif + +#ifndef SOAP_FMAC3 /* (de)serializer declaration macro */ +# define SOAP_FMAC3 +#endif + +#ifndef SOAP_FMAC3S /* string converter for (de)serializer declaration macro */ +# define SOAP_FMAC3S SOAP_FMAC3 +#endif + +#ifndef SOAP_FMAC4 /* (de)serializer declaration macro */ +# define SOAP_FMAC4 +#endif + +#ifndef SOAP_FMAC4S /* string converter for (de)serializer declaration macro */ +# define SOAP_FMAC4S SOAP_FMAC4 +#endif + +#ifndef SOAP_FMAC5 /* stub/skeleton declaration macro */ +# define SOAP_FMAC5 +#endif + +#ifndef SOAP_FMAC6 /* stub/skeleton declaration macro */ +# define SOAP_FMAC6 +#endif + +#ifndef SOAP_CMAC /* class declaration macro */ +# define SOAP_CMAC +#endif + +#ifndef SOAP_NMAC /* namespace table declaration macro */ +# define SOAP_NMAC +#endif + +#ifndef SOAP_SOURCE_STAMP +# define SOAP_SOURCE_STAMP(str) +#endif + +/* gSOAP 2.7.4 and higher: fast look-aside buffering is stable */ +#ifndef WITH_FAST +# define WITH_FAST +#endif + +/* gSOAP 2.7.15 and higher: always retain CDATA in literal XML, unless WITH_LEAN or WITH_NOCDATA */ +#ifndef WITH_LEAN +# ifndef WITH_NOCDATA +# ifndef WITH_CDATA +# define WITH_CDATA +# endif +# endif +#endif + +#ifdef WITH_LEANER +# ifndef WITH_LEAN +# define WITH_LEAN +# endif +#endif + +#ifdef WITH_LEAN +# ifdef WITH_COOKIES +# error "Cannot build WITH_LEAN code WITH_COOKIES enabled" +# endif +#endif + +#ifndef STDSOAP_H +#define STDSOAP_H + +#if defined(__vxworks) || defined(__VXWORKS__) +# ifndef VXWORKS +# define VXWORKS +# endif +#endif + +#ifdef _WIN32 +# ifndef WIN32 +# define WIN32 +# endif +#endif + +#ifdef _WIN32_WCE +# ifndef UNDER_CE +# define UNDER_CE _WIN32_WCE +# endif +#endif + +#ifdef UNDER_CE +# ifndef WIN32 +# define WIN32 +# endif +#endif + +#ifdef __BORLANDC__ +# ifdef __WIN32__ +# ifndef WIN32 +# define WIN32 +# endif +# endif +#endif + +#ifdef __CYGWIN__ +# ifndef CYGWIN +# define CYGWIN +# endif +#endif + +#ifdef __SYMBIAN32__ +# define SYMBIAN +# undef WIN32 +#endif + +#if defined(__palmos__) || defined(PALM_GCC) || defined(__PALMOS_TRAPS__) +# ifndef PALM +# define PALM +# endif +#endif + +#if defined(__hpux) +# ifndef HP_UX +# define HP_UX +# endif +#endif + +#if defined(__digital__) && defined(__unix__) +# ifndef TRU64 +# define TRU64 +# endif +#endif + +#ifdef __MVS__ +# ifndef OS390 +# define OS390 +# endif +#endif + +#ifdef HAVE_CONFIG_H +# include "config.h" +# if defined(WITH_OPENSSL) +# ifndef HAVE_OPENSSL_SSL_H +# undef WITH_OPENSSL +# endif +# endif +# if defined(WITH_ZLIB) || defined(WITH_GZIP) +# ifndef HAVE_ZLIB_H +# undef WITH_ZLIB +# undef WITH_GZIP +# endif +# endif +#else +# if defined(UNDER_CE) +# define WITH_LEAN +# define HAVE_SSCANF +# elif defined(WIN32) +# define HAVE_STRRCHR +# define HAVE_STRTOD +# define HAVE_SSCANF +# define HAVE_STRTOL +# define HAVE_STRTOUL +# define HAVE_SYS_TIMEB_H +# define HAVE_FTIME +# define HAVE_GMTIME +# define HAVE_WCTOMB +# define HAVE_MBTOWC +# define SOAP_LONG_FORMAT "%I64d" +# define SOAP_ULONG_FORMAT "%I64u" +# elif defined(CYGWIN) +# define HAVE_POLL +# define HAVE_STRRCHR +# define HAVE_STRTOD +# define HAVE_SSCANF +# define HAVE_STRTOL +# define HAVE_STRTOUL +# define HAVE_SYS_TIMEB_H +# define HAVE_FTIME +# define HAVE_RAND_R +# define HAVE_GMTIME_R +# define HAVE_LOCALTIME_R +# define HAVE_WCTOMB +# define HAVE_MBTOWC +# elif defined(__APPLE__) +# define HAVE_POLL +# define HAVE_STRRCHR +# define HAVE_STRTOD +# define HAVE_SSCANF +# define HAVE_STRTOD_L +# define HAVE_SSCANF_L +# define HAVE_SPRINTF_L +# define HAVE_STRTOL +# define HAVE_STRTOUL +# define HAVE_RAND_R +# define HAVE_GMTIME_R +# define HAVE_LOCALTIME_R +# define HAVE_TIMEGM +# define HAVE_WCTOMB +# define HAVE_MBTOWC +# elif defined(_AIX43) +# define HAVE_STRRCHR +# define HAVE_STRTOD +# define HAVE_SSCANF +# define HAVE_STRTOL +# define HAVE_STRTOUL +# define HAVE_SYS_TIMEB_H +# define HAVE_FTIME +# define HAVE_RAND_R +# define HAVE_GMTIME_R +# define HAVE_LOCALTIME_R +# define HAVE_WCTOMB +# define HAVE_MBTOWC +# elif defined(_AIX41) +# define HAVE_STRRCHR +# define HAVE_STRTOD +# define HAVE_SSCANF +# define HAVE_STRTOL +# define HAVE_STRTOUL +# define HAVE_SYS_TIMEB_H +# define HAVE_WCTOMB +# define HAVE_MBTOWC +# elif defined(HP_UX) +# define HAVE_STRRCHR +# define HAVE_STRTOD +# define HAVE_SSCANF +# define HAVE_STRTOL +# define HAVE_STRTOUL +# define HAVE_SYS_TIMEB_H +# define HAVE_FTIME +# define HAVE_RAND_R +# define HAVE_GMTIME_R +# define HAVE_LOCALTIME_R +# define HAVE_WCTOMB +# define HAVE_MBTOWC +# elif defined(FREEBSD) || defined(__FreeBSD__) || defined(OPENBSD) +# define HAVE_POLL +# define HAVE_STRRCHR +# define HAVE_STRTOD +# define HAVE_SSCANF +# define HAVE_STRTOD_L +# define HAVE_SSCANF_L +# define HAVE_SPRINTF_L +# define HAVE_STRTOL +# define HAVE_STRTOUL +# define HAVE_STRTOLL +# define HAVE_STRTOULL +# define HAVE_GETTIMEOFDAY +# define HAVE_RAND_R +# define HAVE_GMTIME_R +# define HAVE_LOCALTIME_R +# define HAVE_WCTOMB +# define HAVE_MBTOWC +# define SOAP_LONG_FORMAT "%qd" +# define SOAP_ULONG_FORMAT "%qu" +# elif defined(__VMS) +# define HAVE_STRRCHR +# define HAVE_STRTOD +# define HAVE_SSCANF +# define HAVE_STRTOL +# define HAVE_STRTOUL +# define HAVE_SYS_TIMEB_H +# define HAVE_FTIME +# define HAVE_RAND_R +# define HAVE_GMTIME_R +# define HAVE_LOCALTIME_R +# define HAVE_WCTOMB +# define HAVE_MBTOWC +# elif defined(__GLIBC__) || defined(__GNU__) +# define HAVE_POLL +# define HAVE_STRRCHR +# define HAVE_STRTOD +# define HAVE_SSCANF +# define HAVE_STRTOD_L +# define HAVE_SSCANF_L +# define HAVE_SPRINTF_L +# define HAVE_STRTOL +# define HAVE_STRTOUL +# define HAVE_STRTOLL +# define HAVE_STRTOULL +# define HAVE_SYS_TIMEB_H +# define HAVE_FTIME +# define HAVE_RAND_R +# define HAVE_GMTIME_R +# define HAVE_LOCALTIME_R +# define HAVE_TIMEGM +# define HAVE_WCTOMB +# define HAVE_MBTOWC +# define HAVE_ISNAN +# elif defined(TRU64) +# define HAVE_STRRCHR +# define HAVE_STRTOD +# define HAVE_SSCANF +# define HAVE_STRTOL +# define HAVE_STRTOUL +# define HAVE_GETTIMEOFDAY +# define HAVE_SYS_TIMEB_H +# define HAVE_RAND_R +# define HAVE_GMTIME_R +# define HAVE_LOCALTIME_R +# define __USE_STD_IOSTREAM +# define HAVE_WCTOMB +# define HAVE_MBTOWC +# define SOAP_LONG_FORMAT "%ld" +# define SOAP_ULONG_FORMAT "%lu" +# elif defined(MAC_CARBON) +# define WITH_NOIO +# define HAVE_STRRCHR +# define HAVE_STRTOD +# define HAVE_SSCANF +# define HAVE_STRTOD_L +# define HAVE_SSCANF_L +# define HAVE_SPRINTF_L +# define HAVE_STRTOL +# define HAVE_STRTOUL +# define HAVE_FTIME +# define HAVE_RAND_R +# define HAVE_GETHOSTBYNAME_R +# define HAVE_GMTIME_R +# define HAVE_LOCALTIME_R +# define HAVE_WCTOMB +# define HAVE_MBTOWC +# elif defined(PALM) +# define WITH_LEAN +# define HAVE_STRTOD /* strtod() is defined in palmFunctions.h */ +# include /* Needs to be included before unix headers */ +# include +# define IGNORE_STDIO_STUBS +# include +# define O_NONBLOCK FNONBIO +# include +# include "palmFunctions.h" +# elif defined(SYMBIAN) +# define WITH_LEAN +# define WITH_NONAMESPACES +# define HAVE_STRTOD /* use STRTOD since sscanf doesn't seem to work */ +# include +# include +# elif defined(VXWORKS) +# ifdef _WRS_KERNEL +# define _POSIX_THREADS 1 +# endif +# define HAVE_STRRCHR +# define HAVE_STRTOD +# define HAVE_SSCANF +# define HAVE_STRTOL +# define HAVE_STRTOUL +# define HAVE_GMTIME +# define HAVE_LOCALTIME +# define HAVE_MKTIME +# elif defined(OS390) +# define HAVE_STRRCHR +# define HAVE_STRTOD +# define HAVE_SSCANF +# define HAVE_STRTOL +# define HAVE_STRTOUL +# define HAVE_SYS_TIMEB_H +# define HAVE_FTIME +# define HAVE_RAND_R +# define HAVE_GMTIME_R +# define HAVE_LOCALTIME_R +# define HAVE_WCTOMB +# define HAVE_MBTOWC +# elif defined(AS400) +# define HAVE_STRRCHR +# define HAVE_STRTOD +# define HAVE_SSCANF +# define HAVE_STRTOL +# define HAVE_STRTOUL +# define HAVE_SYS_TIMEB_H +# define HAVE_FTIME +# define HAVE_RAND_R +# define HAVE_GMTIME_R +# define HAVE_LOCALTIME_R +# define HAVE_WCTOMB +# define HAVE_MBTOWC +# elif defined(__QNX__) || defined(QNX) +/* QNX does not have a working version of strtof */ +# undef HAVE_STRTOF +# define HAVE_POLL +# define HAVE_STRRCHR +# define HAVE_STRTOD +# define HAVE_SSCANF +# define HAVE_STRTOL +# define HAVE_STRTOUL +# define HAVE_SYS_TIMEB_H +# define HAVE_FTIME +# define HAVE_RAND_R +# define HAVE_GETHOSTBYNAME_R +# define HAVE_GMTIME_R +# define HAVE_LOCALTIME_R +# define HAVE_WCTOMB +# define HAVE_MBTOWC +# define LONG64 long +# define ULONG64 unsigned LONG64 +# define SOAP_LONG_FORMAT "%ld" +# define SOAP_ULONG_FORMAT "%lu" +# else +/* Default asumptions on supported functions */ +# define HAVE_STRRCHR +# define HAVE_STRTOD +# define HAVE_SSCANF +# define HAVE_STRTOL +# define HAVE_STRTOUL +# define HAVE_SYS_TIMEB_H +# define HAVE_FTIME +# define HAVE_RAND_R +# define HAVE_GETHOSTBYNAME_R +# define HAVE_GMTIME_R +# define HAVE_LOCALTIME_R +# define HAVE_WCTOMB +# define HAVE_MBTOWC +# endif +#endif + +/* native Win and HP-UX compilers don't like empty structs */ +#if defined(WIN32) || defined(HP_UX) +# define WITH_NOEMPTYSTRUCT +#endif + +#ifdef HP_UX +# undef HAVE_STRTOLL +# undef HAVE_STRTOULL +#endif + +/* older OpenVMS TCP/IP stacks cannot handle 65536 bytes */ +#ifdef __VMS +# ifndef SOAP_BUFLEN +# define SOAP_BUFLEN (65535) +# endif +#endif + +#ifdef WITH_C_LOCALE +# include +#else +# undef HAVE_STRTOF_L +# undef HAVE_STRTOD_L +# undef HAVE_SSCANF_L +# undef HAVE_SPRINTF_L +#endif + +#ifndef WITH_NOSTDLIB +# include +# ifndef PALM +# include +# include +# endif +# include +# include +#endif + +#ifdef HAVE_POLL +# include +#endif + +#if defined(__cplusplus) && !defined(WITH_LEAN) && !defined(WITH_COMPAT) +# include +# include +#endif + +#ifdef WITH_NOHTTP +# ifndef WITH_NOIO +# define WITH_NOIO +# undef WITH_COOKIES +# endif +#endif + +/* Suggestion when SOAP_FD_EXCEEDED error occurs: + Some systems allow increasing FD_SETSIZE before including sys/types.h: +#define FD_SETSIZE (2048) +*/ + +#ifndef UNDER_CE +# ifndef PALM +# ifndef WITH_NOIO +# include +# include +# endif +# ifndef WITH_LEAN +# ifdef HAVE_SYS_TIMEB_H +# include /* for ftime() */ +# endif +# include +# endif +# endif +#endif + +#ifdef OPENSERVER +# include +# include +# include + extern int h_errno; +#endif + +#ifndef WITH_NOIO +# ifndef WIN32 +# ifndef PALM +# include +# ifdef VXWORKS +# include +# include +# ifndef _WRS_KERNEL +# include +# endif +# else +# ifndef SYMBIAN +# include +# endif +# endif +# ifdef SUN_OS +# include /* SUN */ +# include /* SUN < 2.8 (?) */ +# endif +# ifdef VXWORKS +# ifdef _WRS_KERNEL +# include +# endif +# else +# include +# endif +# include +# ifdef OS390 +# include +# else +# include /* TCP_NODELAY */ +# endif +# include +# endif +# endif +#endif + +#ifdef WIN32 +# define SOAP_WINSOCKINT int +#else +# define SOAP_WINSOCKINT size_t +#endif + +#ifdef WIN32 +# ifndef UNDER_CE +# include +# include +# endif +# ifdef WITH_IPV6 +# include /* Visual Studio 2005 users: you must install the Platform SDK (R2) */ +# include +# include +# define SOAP_GAI_STRERROR gai_strerrorA +# else +# ifndef __BORLANDC__ +# include /* Visual Studio 2005 users: you must install the Platform SDK (R2) */ +/* # include */ /* Alternative: use winsock2 (not available with eVC) */ +# else +# include /* Borland C */ +# endif +# endif +#else +# ifdef VXWORKS +# include +# include +# include +# endif +# ifndef WITH_NOIO +# ifndef PALM +# include +# include +# include +# include +# ifdef _AIX41 +# include +# endif +# endif +# endif +#endif + +#ifdef WITH_FASTCGI +# include +#endif + +#ifdef WITH_OPENSSL +# define OPENSSL_NO_KRB5 +# include +# include +# include +# include +# include +# ifndef ALLOW_OLD_VERSIONS +# if (OPENSSL_VERSION_NUMBER < 0x00905100L) +# error "Must use OpenSSL 0.9.6 or later" +# endif +# endif +#endif + +#ifdef WITH_GZIP +# ifndef WITH_ZLIB +# define WITH_ZLIB +# endif +#endif + +#ifdef WITH_CASEINSENSITIVETAGS +# define SOAP_STRCMP soap_tag_cmp /* case insensitve XML element/attribute names */ +#else +# define SOAP_STRCMP strcmp /* case sensitive XML element/attribute names */ +#endif + +#ifdef WITH_ZLIB +# include +#endif + +#ifndef WITH_NOSTDLIB +# ifndef PALM +# include /* for isnan() */ +# endif +#endif + +/* #define DEBUG */ /* Uncomment to debug sending (in file SENT.log) receiving (in file RECV.log) and messages (in file TEST.log) */ + +#ifdef __cplusplus +extern "C" { +#endif + +/* Portability: define SOAP_SOCKLEN_T */ +#if defined(_AIX) +# if defined(_AIX43) +# define SOAP_SOCKLEN_T socklen_t +# else +# define SOAP_SOCKLEN_T int +# endif +#elif defined(SOCKLEN_T) +# define SOAP_SOCKLEN_T SOCKLEN_T +#elif defined(__socklen_t_defined) || defined(_SOCKLEN_T) || defined(CYGWIN) || defined(FREEBSD) || defined(__FreeBSD__) || defined(OPENBSD) || defined(__QNX__) || defined(QNX) || defined(OS390) +# define SOAP_SOCKLEN_T socklen_t +#elif defined(IRIX) || defined(WIN32) || defined(__APPLE__) || defined(HP_UX) || defined(SUN_OS) || defined(OPENSERVER) || defined(TRU64) || defined(VXWORKS) +# define SOAP_SOCKLEN_T int +#else +# define SOAP_SOCKLEN_T size_t +#endif + +#ifndef SOAP_SOCKET +# ifdef WIN32 +# define SOAP_SOCKET SOCKET +# define soap_closesocket(n) closesocket(n) +# else +# define SOAP_SOCKET int +# define soap_closesocket(n) close(n) +# endif +#endif + +#define SOAP_INVALID_SOCKET ((SOAP_SOCKET)-1) +#define soap_valid_socket(n) ((n) != SOAP_INVALID_SOCKET) + +#ifndef SOAP_GAI_STRERROR +# define SOAP_GAI_STRERROR gai_strerror +#endif + +#ifndef FD_SETSIZE +# define FD_SETSIZE (1024) +#endif + +#if defined(SYMBIAN) +# define LONG64 long +# define ULONG64 unsigned LONG64 +#elif !defined(WIN32) || defined(CYGWIN) || defined(__GLIBC__) || defined(__GNU__) +# ifndef LONG64 +# if defined(HAVE_STDINT_H) +# include +# define LONG64 int64_t +# define ULONG64 uint64_t +# elif defined(__GLIBC__) +# include +# if (__WORDSIZE == 64) +# define LONG64 int64_t +# define ULONG64 uint64_t +# ifndef SOAP_LONG_FORMAT +# define SOAP_LONG_FORMAT "%ld" +# endif +# ifndef SOAP_ULONG_FORMAT +# define SOAP_ULONG_FORMAT "%lu" +# endif +# else +# define LONG64 long long +# define ULONG64 unsigned LONG64 +# endif +# else +# define LONG64 long long +# define ULONG64 unsigned LONG64 +# endif +# endif +#elif defined(UNDER_CE) +# define LONG64 __int64 +# define ULONG64 unsigned LONG64 +#elif defined(__BORLANDC__) +# define LONG64 __int64 +# define ULONG64 unsigned LONG64 +#endif + +#ifndef SOAP_LONG_FORMAT +# define SOAP_LONG_FORMAT "%lld" /* printf format for 64 bit ints */ +#endif + +#ifndef SOAP_ULONG_FORMAT +# define SOAP_ULONG_FORMAT "%llu" /* printf format for unsigned 64 bit ints */ +#endif + +#if defined(WIN32) && !defined(CYGWIN) +# define soap_int32 __int32 +#elif defined(SYMBIAN) +# define soap_int32 long +#elif defined(PALM) +# define soap_int32 Int32 +#elif defined(_AIX) +# if defined(_AIX43) +# define soap_int32 int32_t +# else +# define soap_int32 signed int +# endif +#else +# define soap_int32 int32_t +#endif + +#ifdef WIN32 +# define SOAP_ERANGE ERANGE +# define SOAP_EINTR WSAEINTR +# define SOAP_EAGAIN WSAEWOULDBLOCK +# define SOAP_EWOULDBLOCK WSAEWOULDBLOCK +# define SOAP_EINPROGRESS WSAEINPROGRESS +# define SOAP_EADDRINUSE WSAEADDRINUSE +#else +# define SOAP_ERANGE ERANGE +# define SOAP_EINTR EINTR +# define SOAP_EAGAIN EAGAIN +# define SOAP_EADDRINUSE EADDRINUSE +# ifdef SYMBIAN +# define SOAP_EWOULDBLOCK 9898 +# define SOAP_EINPROGRESS 9899 +# else +# define SOAP_EWOULDBLOCK EWOULDBLOCK +# define SOAP_EINPROGRESS EINPROGRESS +# endif +#endif + +#ifdef WIN32 +# ifdef UNDER_CE +# define soap_errno GetLastError() +# define soap_socket_errno(s) GetLastError() +# define soap_reset_errno SetLastError(0) +# else +# define soap_errno GetLastError() +# define soap_socket_errno(s) WSAGetLastError() +# define soap_reset_errno SetLastError(0) +# endif +#else +# ifndef WITH_NOIO +# define soap_errno errno +# define soap_socket_errno(s) errno +# define soap_reset_errno (errno = 0) +# else +# define soap_errno 0 +# define soap_socket_errno(s) 0 +# define soap_reset_errno +# endif +#endif + +#ifndef SOAP_BUFLEN +# if !defined(WITH_LEAN) || defined(WITH_UDP) +# define SOAP_BUFLEN (65536) /* buffer length for socket packets, also used by gethostbyname_r and UDP messages, so don't make this too small */ +# else +# define SOAP_BUFLEN (2048) /* lean size */ +# endif +#endif +#ifndef SOAP_LABLEN +# define SOAP_LABLEN (256) /* initial look-aside buffer length */ +#endif +#ifndef SOAP_PTRBLK +# define SOAP_PTRBLK (32) /* block allocation for pointer hash table chains */ +#endif +#ifndef SOAP_PTRHASH +# ifndef WITH_LEAN +# define SOAP_PTRHASH (1024) /* size of pointer analysis hash table (must be power of 2) */ +# else +# define SOAP_PTRHASH (32) +# endif +#endif +#ifndef SOAP_IDHASH +# ifndef WITH_LEAN +# define SOAP_IDHASH (1999) /* prime size of hash table for parsed id/ref */ +# else +# define SOAP_IDHASH (19) /* 19, 199 */ +# endif +#endif +#ifndef SOAP_BLKLEN +# ifndef WITH_LEAN +# define SOAP_BLKLEN (256) /* size of blocks to collect long strings and XML attributes */ +# else +# define SOAP_BLKLEN (32) +# endif +#endif +#ifndef SOAP_TAGLEN +# ifndef WITH_LEAN +# define SOAP_TAGLEN (1024) /* maximum length of XML element tag/attribute name or host/path name + 1 */ +# else +# define SOAP_TAGLEN (64) +# endif +#endif +#ifndef SOAP_HDRLEN +# ifndef WITH_LEAN +# define SOAP_HDRLEN (8192) /* maximum length of HTTP header line (must be >4096 to read cookies) */ +# else +# define SOAP_HDRLEN (1024) +# endif +#endif +#ifndef SOAP_MAXDIMS +# ifndef WITH_LEAN +# define SOAP_MAXDIMS (16) /* maximum array dimensions (array nestings) must be less than 64 to protect soap->tmpbuf */ +# else +# define SOAP_MAXDIMS (4) +# endif +#endif + +#ifndef SOAP_MAXLOGS +# define SOAP_MAXLOGS (3) /* max number of debug logs per struct soap environment */ +# define SOAP_INDEX_RECV (0) +# define SOAP_INDEX_SENT (1) +# define SOAP_INDEX_TEST (2) +#endif + +/* Max iterations in soap_serve() to keep server connection alive */ +#ifndef SOAP_MAXKEEPALIVE +# define SOAP_MAXKEEPALIVE (100) +#endif + +/* Trusted max size of inbound SOAP array for compound array allocation. + Increase if necessary to allow larger arrays. +*/ +#ifndef SOAP_MAXARRAYSIZE +# define SOAP_MAXARRAYSIZE (1000000) +#endif + +#ifdef VXWORKS +# ifdef __INCmathh +# include +# ifndef HAVE_ISNAN +# define HAVE_ISNAN +# endif +# define soap_isnan(num) isNan(num) +# endif +#endif + +#ifdef WIN32 +# include +# ifndef HAVE_ISNAN +# define HAVE_ISNAN +# endif +# define soap_isnan(num) _isnan(num) +#endif + +#ifdef SUN_OS +# define HAVE_ISNAN +#endif + +#ifdef __APPLE__ +# ifdef __cplusplus +# ifndef isnan +extern "C" int isnan(double); +# endif +# endif +# define HAVE_ISNAN +#endif + +#if !defined(HAVE_ISNAN) && (defined(_MATH_H) || defined(_MATH_INCLUDED)) +# define HAVE_ISNAN +#endif + +extern const struct soap_double_nan { unsigned int n1, n2; } soap_double_nan; + +#ifdef VXWORKS +# ifndef FLT_MAX +# define FLT_MAX _ARCH_FLT_MAX +# endif +# ifndef DBL_MAX +# define DBL_MAX _ARCH_DBL_MAX +# endif +#endif + +#ifndef FLT_NAN +# define FLT_NAN (*(float*)(void*)&soap_double_nan) +#endif + +#ifndef FLT_PINFTY +# if defined(FLT_MAX) +# define FLT_PINFTY FLT_MAX +# elif defined(HUGE_VALF) +# define FLT_PINFTY (float)HUGE_VALF +# elif defined(HUGE_VAL) +# define FLT_PINFTY (float)HUGE_VAL +# elif defined(FLOAT_MAX) +# define FLT_PINFTY FLOAT_MAX +# else +# define FLT_PINFTY (3.40282347e+38F) +# endif +#endif + +#ifndef FLT_NINFTY +# define FLT_NINFTY (-FLT_PINFTY) +#endif + +#ifndef DBL_NAN +# define DBL_NAN (*(double*)(void*)&soap_double_nan) +#endif + +#ifndef DBL_PINFTY +# if defined(DBL_MAX) +# define DBL_PINFTY DBL_MAX +# elif defined(HUGE_VALF) +# define DBL_PINFTY (double)HUGE_VALF +# elif defined(HUGE_VAL) +# define DBL_PINFTY (double)HUGE_VAL +# elif defined(DOUBLE_MAX) +# define DBL_PINFTY DOUBLE_MAX +# else +# define DBL_PINFTY (1.7976931348623157e+308) +# endif +#endif + +#ifndef DBL_NINFTY +# define DBL_NINFTY (-DBL_PINFTY) +#endif + +#ifndef soap_isnan +# ifdef HAVE_ISNAN +# define soap_isnan(n) isnan(n) +# else +# define soap_isnan(n) (0) +# endif +#endif + +#define soap_ispinfd(n) ((n) >= DBL_PINFTY) +#define soap_ispinff(n) ((n) >= FLT_PINFTY) +#define soap_isninfd(n) ((n) <= DBL_NINFTY) +#define soap_isninff(n) ((n) <= FLT_NINFTY) + +/* gSOAP error codes */ + +#define SOAP_EOF EOF +#define SOAP_ERR EOF +#define SOAP_OK 0 +#define SOAP_CLI_FAULT 1 +#define SOAP_SVR_FAULT 2 +#define SOAP_TAG_MISMATCH 3 +#define SOAP_TYPE 4 +#define SOAP_SYNTAX_ERROR 5 +#define SOAP_NO_TAG 6 +#define SOAP_IOB 7 +#define SOAP_MUSTUNDERSTAND 8 +#define SOAP_NAMESPACE 9 +#define SOAP_USER_ERROR 10 +#define SOAP_FATAL_ERROR 11 +#define SOAP_FAULT 12 +#define SOAP_NO_METHOD 13 +#define SOAP_NO_DATA 14 +#define SOAP_GET_METHOD 15 +#define SOAP_PUT_METHOD 16 +#define SOAP_DEL_METHOD 17 +#define SOAP_HEAD_METHOD 18 +#define SOAP_HTTP_METHOD 19 +#define SOAP_EOM 20 +#define SOAP_MOE 21 +#define SOAP_HDR 22 +#define SOAP_NULL 23 +#define SOAP_DUPLICATE_ID 24 +#define SOAP_MISSING_ID 25 +#define SOAP_HREF 26 +#define SOAP_UDP_ERROR 27 +#define SOAP_TCP_ERROR 28 +#define SOAP_HTTP_ERROR 29 +#define SOAP_SSL_ERROR 30 +#define SOAP_ZLIB_ERROR 31 +#define SOAP_DIME_ERROR 32 +#define SOAP_DIME_HREF 33 +#define SOAP_DIME_MISMATCH 34 +#define SOAP_DIME_END 35 +#define SOAP_MIME_ERROR 36 +#define SOAP_MIME_HREF 37 +#define SOAP_MIME_END 38 +#define SOAP_VERSIONMISMATCH 39 +#define SOAP_PLUGIN_ERROR 40 +#define SOAP_DATAENCODINGUNKNOWN 41 +#define SOAP_REQUIRED 42 +#define SOAP_PROHIBITED 43 +#define SOAP_OCCURS 44 +#define SOAP_LENGTH 45 +#define SOAP_FD_EXCEEDED 46 + +#define soap_xml_error_check(e) ((e) == SOAP_TAG_MISMATCH || (e) == SOAP_NO_TAG || (e) == SOAP_SYNTAX_ERROR || (e) == SOAP_NAMESPACE || (e) == SOAP_DUPLICATE_ID || (e) == SOAP_MISSING_ID || (e) == SOAP_REQUIRED || (e) == SOAP_PROHIBITED || (e) == SOAP_OCCURS || (e) == SOAP_LENGTH || (e) == SOAP_NULL || (e) == SOAP_HREF) +#define soap_soap_error_check(e) ((e) == SOAP_CLI_FAULT || (e) == SOAP_SVR_FAULT || (e) == SOAP_VERSIONMISMATCH || (e) == SOAP_MUSTUNDERSTAND || (e) == SOAP_FAULT || (e) == SOAP_NO_METHOD) +#define soap_tcp_error_check(e) ((e) == SOAP_EOF || (e) == SOAP_TCP_ERROR) +#define soap_ssl_error_check(e) ((e) == SOAP_SSL_ERROR) +#define soap_zlib_error_check(e) ((e) == SOAP_ZLIB_ERROR) +#define soap_http_error_check(e) ((e) == SOAP_HTTP_ERROR || (e) == SOAP_NO_DATA || ((e) >= SOAP_GET_METHOD && (e) <= SOAP_HTTP_METHOD) || ((e) >= 100 && (e) < 600)) + +/* gSOAP HTTP response status codes 100 to 599 are reserved */ + +/* Codes 600 to 999 are user definable */ + +/* Exceptional gSOAP HTTP server response status codes >= 1000 */ + +#define SOAP_STOP 1000 /* No HTTP response */ +#define SOAP_FORM 1001 /* Form request/response */ +#define SOAP_HTML 1002 /* Custom HTML response */ +#define SOAP_FILE 1003 /* Custom file-based response */ + +/* gSOAP HTTP method codes (client) */ + +#define SOAP_POST 2000 /* POST request */ +#define SOAP_POST_FILE 2001 /* Custom file-based POST request */ +#define SOAP_GET 2002 /* GET request */ + +/* gSOAP DIME */ + +#define SOAP_DIME_CF 0x01 +#define SOAP_DIME_ME 0x02 +#define SOAP_DIME_MB 0x04 +#define SOAP_DIME_VERSION 0x08 /* DIME version 1 */ +#define SOAP_DIME_MEDIA 0x10 +#define SOAP_DIME_ABSURI 0x20 + +/* gSOAP ZLIB */ + +#define SOAP_ZLIB_NONE 0x00 +#define SOAP_ZLIB_DEFLATE 0x01 +#define SOAP_ZLIB_INFLATE 0x02 +#define SOAP_ZLIB_GZIP 0x02 + +/* gSOAP transport, connection, and content encoding modes */ + +typedef soap_int32 soap_mode; + +#define SOAP_IO 0x00000003 /* IO mask */ +#define SOAP_IO_FLUSH 0x00000000 /* flush output immediately, no buffering */ +#define SOAP_IO_BUFFER 0x00000001 /* buffer output in packets of size SOAP_BUFLEN */ +#define SOAP_IO_STORE 0x00000002 /* store entire output to determine length for transport */ +#define SOAP_IO_CHUNK 0x00000003 /* use HTTP chunked transfer AND buffer packets */ + +#define SOAP_IO_UDP 0x00000004 /* TCP or UDP */ + +#define SOAP_IO_LENGTH 0x00000008 /* calc message length (internal) */ +#define SOAP_IO_KEEPALIVE 0x00000010 /* keep connection alive */ + +#define SOAP_ENC_LATIN 0x00000020 /* accept iso-8859-1 encoding */ +#define SOAP_ENC_XML 0x00000040 /* plain XML encoding, no HTTP header */ +#define SOAP_ENC_DIME 0x00000080 +#define SOAP_ENC_MIME 0x00000100 +#define SOAP_ENC_MTOM 0x00000200 +#define SOAP_ENC_ZLIB 0x00000400 +#define SOAP_ENC_SSL 0x00000800 + +#define SOAP_ENC 0x00000FFF /* IO and ENC mask */ + +#define SOAP_XML_STRICT 0x00001000 /* apply strict validation */ +#define SOAP_XML_INDENT 0x00002000 /* emit indented XML */ +#define SOAP_XML_DEFAULTNS 0x00004000 /* emit xmlns="..." namesp. */ +#define SOAP_XML_CANONICAL 0x00008000 /* EXC C14N canonical XML */ +#define SOAP_XML_TREE 0x00010000 /* emit XML tree (no id/ref) */ +#define SOAP_XML_GRAPH 0x00020000 /* see DOM manual */ +#define SOAP_XML_NIL 0x00040000 /* serialize NULLs as xsi:nil */ +#define SOAP_XML_DOM 0x00080000 + +#define SOAP_C_NOIOB 0x00100000 /* don't fault on array index out of bounds (just ignore) */ +#define SOAP_C_UTFSTRING 0x00200000 /* (de)serialize strings with UTF8 content */ +#define SOAP_C_MBSTRING 0x00400000 /* (de)serialize strings with multi-byte content */ +#define SOAP_C_NILSTRING 0x00800000 /* serialize empty strings as nil (omitted) */ + +#define SOAP_DOM_TREE 0x01000000 +#define SOAP_DOM_NODE 0x02000000 +#define SOAP_DOM_ASIS 0x04000000 + +#define SOAP_MIME_POSTCHECK 0x10000000 /* MIME flag (internal) */ + +#define SOAP_XML_SEC 0x80000000 /* reserved for WS security */ + +/* WITH_XMLNS backward compatibility: always use XML default namespaces */ +#ifdef WITH_XMLNS +# define SOAP_IO_DEFAULT (SOAP_IO_FLUSH | SOAP_XML_DEFAULTNS) +#else +# define SOAP_IO_DEFAULT SOAP_IO_FLUSH +#endif + +/* SSL client/server authentication settings */ + +#define SOAP_SSL_NO_AUTHENTICATION 0x00 /* for testing purposes */ +#define SOAP_SSL_REQUIRE_SERVER_AUTHENTICATION 0x01 /* client requires server to authenticate */ +#define SOAP_SSL_REQUIRE_CLIENT_AUTHENTICATION 0x02 /* server requires client to authenticate */ +#define SOAP_SSL_SKIP_HOST_CHECK 0x04 /* client does not check the common name of the host in certificate */ +#define SOAP_SSL_ALLOW_EXPIRED_CERTIFICATE 0x08 /* client does not check the expiration date of the host certificate */ +#define SOAP_SSL_NO_DEFAULT_CA_PATH 0x10 /* don't use default_verify_paths */ +#define SOAP_SSL_RSA 0x20 /* use RSA */ +#define SOAP_SSLv3 0x40 /* SSL v3 only */ +#define SOAP_TLSv1 0x80 /* TLS v1 only */ +#define SOAP_SSLv3_TLSv1 0x00 /* SSL v3 and TLS v1 support by default */ + +#define SOAP_SSL_DEFAULT (SOAP_SSL_REQUIRE_SERVER_AUTHENTICATION | SOAP_SSLv3_TLSv1) + +/* state */ + +#define SOAP_NONE 0 +#define SOAP_INIT 1 +#define SOAP_COPY 2 + +#define soap_check_state(soap) (!(soap) || ((soap)->state != SOAP_INIT && (soap)->state != SOAP_COPY)) + +/* part */ + +#define SOAP_BEGIN 0 +#define SOAP_IN_ENVELOPE 2 +#define SOAP_IN_HEADER 3 +#define SOAP_END_HEADER 4 +#define SOAP_NO_BODY 5 +#define SOAP_IN_BODY 6 +#define SOAP_END_BODY 7 +#define SOAP_END_ENVELOPE 8 +#define SOAP_END 9 +#define SOAP_BEGIN_SECURITY 10 +#define SOAP_IN_SECURITY 11 +#define SOAP_END_SECURITY 12 + +/* DEBUG macros */ + +#ifndef WITH_LEAN +# ifdef DEBUG +# ifndef SOAP_DEBUG +# define SOAP_DEBUG +# endif +# ifndef SOAP_MEM_DEBUG +# define SOAP_MEM_DEBUG +# endif +# endif +#endif + +#ifdef SOAP_MEM_DEBUG +# ifndef SOAP_MALLOC +# define SOAP_MALLOC(soap, size) soap_track_malloc(soap, __FILE__, __LINE__, size) +# endif +# ifndef SOAP_FREE +# define SOAP_FREE(soap, ptr) soap_track_free(soap, __FILE__, __LINE__, ptr) +# endif +#endif + +#ifndef SOAP_MALLOC /* use libc malloc */ +# define SOAP_MALLOC(soap, size) malloc(size) +#endif + +#ifndef SOAP_FREE /* use libc free */ +# define SOAP_FREE(soap, ptr) free(ptr) +#endif + +#ifdef SOAP_DEBUG +# ifndef SOAP_MESSAGE +# define SOAP_MESSAGE fprintf +# endif +# ifndef DBGLOG +# define DBGLOG(DBGFILE, CMD) \ +{ if (soap)\ + { if (!soap->fdebug[SOAP_INDEX_##DBGFILE])\ + soap_open_logfile((struct soap*)soap, SOAP_INDEX_##DBGFILE);\ + if (soap->fdebug[SOAP_INDEX_##DBGFILE])\ + { FILE *fdebug = soap->fdebug[SOAP_INDEX_##DBGFILE];\ + CMD;\ + fflush(fdebug);\ + }\ + }\ +} +# endif +# ifndef DBGMSG +# define DBGMSG(DBGFILE, MSG, LEN) \ +{ if (soap)\ + { if (!soap->fdebug[SOAP_INDEX_##DBGFILE])\ + soap_open_logfile((struct soap*)soap, SOAP_INDEX_##DBGFILE);\ + if (soap->fdebug[SOAP_INDEX_##DBGFILE])\ + { fwrite((MSG), 1, (LEN), soap->fdebug[SOAP_INDEX_##DBGFILE]);\ + fflush(soap->fdebug[SOAP_INDEX_##DBGFILE]);\ + }\ + }\ +} +# endif +# ifndef DBGFUN +# define DBGFUN(FNAME) DBGLOG(TEST, SOAP_MESSAGE(fdebug, "%s(%d): %s()\n", __FILE__, __LINE__, FNAME)) +# define DBGFUN1(FNAME, FMT, ARG) DBGLOG(TEST, SOAP_MESSAGE(fdebug, "%s(%d): %s("FMT")\n", __FILE__, __LINE__, FNAME, (ARG))) +# define DBGFUN2(FNAME, FMT1, ARG1, FMT2, ARG2) DBGLOG(TEST, SOAP_MESSAGE(fdebug, "%s(%d): %s("FMT1", "FMT2")\n", __FILE__, __LINE__, FNAME, (ARG1), (ARG2))) +# define DBGFUN3(FNAME, FMT1, ARG1, FMT2, ARG2, FMT3, ARG3) DBGLOG(TEST, SOAP_MESSAGE(fdebug, "%s(%d): %s("FMT1", "FMT2", "FMT3")\n", __FILE__, __LINE__, FNAME, (ARG1), (ARG2), (ARG3))) +# endif +# ifndef DBGHEX +# define DBGHEX(DBGFILE, MSG, LEN) \ +{ if (soap)\ + { if (!soap->fdebug[SOAP_INDEX_##DBGFILE])\ + soap_open_logfile(soap, SOAP_INDEX_##DBGFILE);\ + if (soap->fdebug[SOAP_INDEX_##DBGFILE])\ + { int i; char *s;\ + for (s = (char*)(MSG), i = (LEN); i; i--)\ + fprintf(soap->fdebug[SOAP_INDEX_##DBGFILE], "%2.2X ", (int)*s++&0xFF);\ + fflush(soap->fdebug[SOAP_INDEX_##DBGFILE]);\ + }\ + }\ +} +# endif +#else +# define DBGLOG(DBGFILE, CMD) +# define DBGMSG(DBGFILE, MSG, LEN) +# define DBGFUN(FNAME) +# define DBGFUN1(FNAME, FMT, ARG) +# define DBGFUN2(FNAME, FMT1, ARG1, FMT2, ARG2) +# define DBGFUN3(FNAME, FMT1, ARG1, FMT2, ARG2, FMT3, ARG3) +# define DBGHEX(DBGFILE, MSG, LEN) +#endif + +/* UCS-4 requires 32 bits (0-7FFFFFFF, the sign bit is used by gSOAP to distinguish XML entities) */ +typedef soap_int32 soap_wchar; + +/* namespace table row */ +struct Namespace +{ const char *id; + const char *ns; + const char *in; + char *out; +}; + +/* namespace stack */ +struct soap_nlist +{ struct soap_nlist *next; + unsigned int level; /* nesting depth level */ + short index; /* corresponding entry in ns mapping table */ + const char *ns; /* only set when parsed ns URI is not in the ns mapping table */ + char id[1]; /* the actual string value flows into the allocated region below this struct */ +}; + +/* block stack for nested block allocations */ +struct soap_blist +{ struct soap_blist *next; + char *ptr; + size_t size; +}; + +/* array layout */ +struct soap_array +{ void *__ptr; + int __size; +}; + +/* pointer serialization management */ +struct soap_plist +{ struct soap_plist *next; + const void *ptr; + const struct soap_array *array; + int type; + int id; + char mark1; + char mark2; +}; + +/* block allocation for pointer serialization management */ +struct soap_pblk +{ struct soap_pblk *next; + struct soap_plist plist[SOAP_PTRBLK]; +}; + +#ifdef SOAP_MEM_DEBUG +/* malloc/free tracking for debugging */ +struct soap_mlist +{ struct soap_mlist *next; + const void *ptr; + const char *file; + int line; + short live; +}; +#endif + +/* class allocation list */ +struct soap_clist +{ struct soap_clist *next; + void *ptr; + int type; + int size; + int (*fdelete)(struct soap_clist*); +}; + +/* attributes */ +struct soap_attribute +{ struct soap_attribute *next; + char *value; + size_t size; + char *ns; + short visible; + char name[1]; /* the actual name string flows into the allocated region below this struct */ +}; + +#ifndef WITH_LEAN +struct soap_cookie +{ struct soap_cookie *next; + char *name; + char *value; + char *domain; + char *path; + time_t expire; /* client-side: local time to expire */ + long maxage; /* server-side: seconds to expire */ + unsigned int version; + short secure; + short session; /* server-side */ + short env; /* server-side: got cookie from client and should not be (re)send */ + short modified; /* server-side: client cookie was modified and should be send */ +}; +#endif + +SOAP_FMAC1 struct soap_multipart* SOAP_FMAC2 soap_next_multipart(struct soap_multipart*); + +#ifdef __cplusplus + +class soap_multipart_iterator +{ public: + struct soap_multipart *content; + bool operator==(const soap_multipart_iterator& iter) const + { return (bool)(content == iter.content); } + bool operator!=(const soap_multipart_iterator& iter) const + { return (bool)(content != iter.content); } + struct soap_multipart &operator*() const + { return *content; } + soap_multipart_iterator &operator++() + { content = soap_next_multipart(content); return *this; } + soap_multipart_iterator() : content(NULL) + { } + soap_multipart_iterator(struct soap_multipart *p) : content(p) + { } +}; +#endif + +#ifndef WITH_LEANER +struct soap_dime +{ size_t count; + size_t size; + size_t chunksize; + size_t buflen; + char flags; + char *ptr; + const char *id; + const char *type; + const char *options; + struct soap_multipart *list; /* list of DIME attachments received */ + struct soap_multipart *first, *last; /* temporary in/out queue */ +#ifdef __cplusplus + soap_multipart_iterator begin() + { soap_multipart_iterator iter(list); return iter; }; + soap_multipart_iterator end() + { soap_multipart_iterator iter(NULL); return iter; }; +#endif +}; +#endif + +#ifndef WITH_LEANER +struct soap_mime +{ char *boundary; /* MIME boundary */ + const char *start; /* MIME start ID */ + struct soap_multipart *list; /* list of MIME attachments received */ + struct soap_multipart *first, *last; /* temporary in/out queue */ +#ifdef __cplusplus + soap_multipart_iterator begin() + { soap_multipart_iterator iter(list); return iter; }; + soap_multipart_iterator end() + { soap_multipart_iterator iter(NULL); return iter; }; +#endif +}; +#endif + +#ifndef WITH_LEANER +/* RFC2045 MIME content transfer encodings */ +enum soap_mime_encoding +{ SOAP_MIME_NONE, + SOAP_MIME_7BIT, + SOAP_MIME_8BIT, + SOAP_MIME_BINARY, + SOAP_MIME_QUOTED_PRINTABLE, + SOAP_MIME_BASE64, + SOAP_MIME_IETF_TOKEN, + SOAP_MIME_X_TOKEN +}; +#endif + +#ifndef WITH_LEANER +/* DIME/MIME multipart list */ +struct soap_multipart +{ struct soap_multipart *next; + char *ptr; /* points to raw data content */ + size_t size; /* size of data content */ + const char *id; /* DIME/MIME content ID or form data name */ + const char *type; /* DIME/MIME type (MIME type format) */ + const char *options; /* DIME options */ + enum soap_mime_encoding encoding; /* MIME Content-Transfer-Encoding */ + const char *location; /* MIME Content-Location (optional) */ + const char *description; /* MIME Content-Description (optional) */ +#ifdef __cplusplus + typedef soap_multipart_iterator iterator; +#endif +}; +#endif + +#ifndef WITH_LEANER +/* attachment DIME and MTOM XOP forwarding */ +struct soap_xlist +{ struct soap_xlist *next; + unsigned char **ptr; + int *size; + char *id; + char **type; + char **options; +}; +#endif + +/******************************************************************************/ + +#ifndef WITH_LEANER +#ifdef __cplusplus +class soap_dom_attribute_iterator +{ public: + struct soap_dom_attribute *att; + const char *nstr; + const char *name; + bool operator==(const soap_dom_attribute_iterator&) const; + bool operator!=(const soap_dom_attribute_iterator&) const; + struct soap_dom_attribute &operator*() const; + soap_dom_attribute_iterator &operator++(); + soap_dom_attribute_iterator(); + soap_dom_attribute_iterator(struct soap_dom_attribute*); + ~soap_dom_attribute_iterator(); +}; +#endif +#endif + +#ifndef WITH_LEANER +struct soap_dom_attribute +{ struct soap_dom_attribute *next; + const char *nstr; + char *name; + char *data; + wchar_t *wide; + struct soap *soap; +#ifdef __cplusplus + typedef soap_dom_attribute_iterator iterator; + struct soap_dom_attribute &set(const char *nstr, const char *name); /* set namespace and name */ + struct soap_dom_attribute &set(const char *data); /* set data */ + soap_dom_attribute_iterator begin(); + soap_dom_attribute_iterator end(); + soap_dom_attribute_iterator find(const char *nstr, const char *name); + void unlink(); + soap_dom_attribute(); + soap_dom_attribute(struct soap *soap); + soap_dom_attribute(struct soap *soap, const char *nstr, const char *name, const char *data); + ~soap_dom_attribute(); +#endif +}; +#endif + +#ifndef WITH_LEANER +#ifdef __cplusplus +class soap_dom_element_iterator +{ public: + struct soap_dom_element *elt; + const char *nstr; + const char *name; + int type; + bool operator==(const soap_dom_element_iterator&) const; + bool operator!=(const soap_dom_element_iterator&) const; + struct soap_dom_element &operator*() const; + soap_dom_element_iterator &operator++(); + soap_dom_element_iterator(); + soap_dom_element_iterator(struct soap_dom_element*); + ~soap_dom_element_iterator(); +}; +#endif +#endif + +#ifndef WITH_LEANER +struct soap_dom_element +{ struct soap_dom_element *next; /* next sibling */ + struct soap_dom_element *prnt; /* parent */ + struct soap_dom_element *elts; /* list of child elements */ + struct soap_dom_attribute *atts; /* list of attributes */ + const char *nstr; /* namespace string */ + char *name; /* element tag name */ + char *data; /* element content data (with SOAP_C_UTFSTRING flag set) */ + wchar_t *wide; /* element content data */ + int type; /* optional: serialized C/C++ data type */ + void *node; /* optional: pointer to serialized C/C++ data */ + char *head; /* leading content before start tag */ + char *tail; /* leading content before end tag */ + struct soap *soap; /* soap context that manages this node */ +#ifdef __cplusplus + typedef soap_dom_element_iterator iterator; + struct soap_dom_element &set(const char *nstr, const char *name); + struct soap_dom_element &set(const char *data); + struct soap_dom_element &set(void *node, int type); + struct soap_dom_element &add(struct soap_dom_element*); + struct soap_dom_element &add(struct soap_dom_element&); + struct soap_dom_element &add(struct soap_dom_attribute*); + struct soap_dom_element &add(struct soap_dom_attribute&); + soap_dom_element_iterator begin(); + soap_dom_element_iterator end(); + soap_dom_element_iterator find(const char *nstr, const char *name); + soap_dom_element_iterator find(int type); + void unlink(); + soap_dom_element(); + soap_dom_element(struct soap *soap); + soap_dom_element(struct soap *soap, const char *nstr, const char *name); + soap_dom_element(struct soap *soap, const char *nstr, const char *name, const char *data); + soap_dom_element(struct soap *soap, const char *nstr, const char *name, void *node, int type); + ~soap_dom_element(); +#endif +}; +SOAP_FMAC1 struct soap_dom_element * SOAP_FMAC2 soap_dom_next_element(struct soap_dom_element *elt); +SOAP_FMAC1 struct soap_dom_attribute * SOAP_FMAC2 soap_dom_next_attribute(struct soap_dom_attribute *att); +#endif + +#if defined(__cplusplus) && !defined(WITH_LEAN) && !defined(WITH_COMPAT) +} +extern std::ostream &operator<<(std::ostream&, const struct soap_dom_element&); +extern std::istream &operator>>(std::istream&, struct soap_dom_element&); +extern "C" { +#endif + +/******************************************************************************/ + +#ifdef WIN32 +# ifdef SOAP_STD_EXPORTS +# define SOAP_STD_API __declspec(dllexport) +# else +# define SOAP_STD_API +# endif +#else +# define SOAP_STD_API +#endif + +struct SOAP_STD_API soap +{ short state; /* 0 = uninitialized, 1 = initialized, 2 = copy of another soap struct */ + short version; /* 1 = SOAP1.1 and 2 = SOAP1.2 (set automatically from namespace URI in nsmap table) */ + soap_mode mode; + soap_mode imode; + soap_mode omode; + const char *float_format; /* user-definable format string for floats (<1024 chars) */ + const char *double_format; /* user-definable format string for doubles (<1024 chars) */ + const char *dime_id_format; /* user-definable format string for integer DIME id ( 0, gives socket recv timeout in seconds, < 0 in usec */ + int send_timeout; /* when > 0, gives socket send timeout in seconds, < 0 in usec */ + int connect_timeout; /* when > 0, gives socket connect() timeout in seconds, < 0 in usec */ + int accept_timeout; /* when > 0, gives socket accept() timeout in seconds, < 0 in usec */ + int socket_flags; /* socket recv() and send() flags, e.g. set to MSG_NOSIGNAL to disable sigpipe */ + int connect_flags; /* connect() SOL_SOCKET sockopt flags, e.g. set to SO_DEBUG to debug socket */ + int bind_flags; /* bind() SOL_SOCKET sockopt flags, e.g. set to SO_REUSEADDR to enable reuse */ + int accept_flags; /* accept() SOL_SOCKET sockopt flags */ + unsigned short linger_time; /* linger time for SO_LINGER option */ + const struct Namespace *namespaces; /* Pointer to global namespace mapping table */ + struct Namespace *local_namespaces; /* Local namespace mapping table */ + struct soap_nlist *nlist; /* namespace stack */ + struct soap_blist *blist; /* block allocation stack */ + struct soap_clist *clist; /* class instance allocation list */ + void *alist; /* memory allocation (malloc) list */ + struct soap_ilist *iht[SOAP_IDHASH]; + struct soap_plist *pht[SOAP_PTRHASH]; + struct soap_pblk *pblk; /* plist block allocation */ + short pidx; /* plist block allocation */ + struct SOAP_ENV__Header *header; + struct SOAP_ENV__Fault *fault; + int idnum; + void *user; /* to pass user-defined data */ + struct soap_plugin *plugins; /* linked list of plug-in data */ + const char *userid; /* HTTP Basic authorization userid */ + const char *passwd; /* HTTP Basic authorization passwd */ + int (*fpost)(struct soap*, const char*, const char*, int, const char*, const char*, size_t); + int (*fget)(struct soap*); + int (*fput)(struct soap*); + int (*fdel)(struct soap*); + int (*fhead)(struct soap*); + int (*fform)(struct soap*); + int (*fposthdr)(struct soap*, const char*, const char*); + int (*fresponse)(struct soap*, int, size_t); + int (*fparse)(struct soap*); + int (*fparsehdr)(struct soap*, const char*, const char*); + int (*fheader)(struct soap*); + int (*fresolve)(struct soap*, const char*, struct in_addr* inaddr); + int (*fconnect)(struct soap*, const char*, const char*, int); + int (*fdisconnect)(struct soap*); + int (*fclosesocket)(struct soap*, SOAP_SOCKET); + int (*fshutdownsocket)(struct soap*, SOAP_SOCKET, int); + SOAP_SOCKET (*fopen)(struct soap*, const char*, const char*, int); + SOAP_SOCKET (*faccept)(struct soap*, SOAP_SOCKET, struct sockaddr*, int *n); + int (*fclose)(struct soap*); + int (*fsend)(struct soap*, const char*, size_t); + size_t (*frecv)(struct soap*, char*, size_t); + int (*fpoll)(struct soap*); + void (*fseterror)(struct soap*, const char **c, const char **s); + int (*fignore)(struct soap*, const char*); + int (*fserveloop)(struct soap*); + void *(*fplugin)(struct soap*, const char*); + void *(*fmalloc)(struct soap*, size_t); +#ifndef WITH_LEANER + int (*fprepareinit)(struct soap*); + int (*fpreparesend)(struct soap*, const char*, size_t); + int (*fpreparerecv)(struct soap*, const char*, size_t); + int (*fpreparefinal)(struct soap*); + void *(*fdimereadopen)(struct soap*, void*, const char*, const char*, const char*); + void *(*fdimewriteopen)(struct soap*, const char*, const char*, const char*); + void (*fdimereadclose)(struct soap*, void*); + void (*fdimewriteclose)(struct soap*, void*); + size_t (*fdimeread)(struct soap*, void*, char*, size_t); + int (*fdimewrite)(struct soap*, void*, const char*, size_t); + void *(*fmimereadopen)(struct soap*, void*, const char*, const char*, const char*); + void *(*fmimewriteopen)(struct soap*, void*, const char*, const char*, const char*, enum soap_mime_encoding); + void (*fmimereadclose)(struct soap*, void*); + void (*fmimewriteclose)(struct soap*, void*); + size_t (*fmimeread)(struct soap*, void*, char*, size_t); + int (*fmimewrite)(struct soap*, void*, const char*, size_t); +#endif + SOAP_SOCKET master; + SOAP_SOCKET socket; +#if defined(__cplusplus) && !defined(WITH_LEAN) && !defined(WITH_COMPAT) + std::ostream *os; + std::istream *is; +#else + void *os; /* preserve struct size */ + void *is; /* preserve struct size */ +#endif +#ifndef UNDER_CE + int sendfd; + int recvfd; +#else + FILE *sendfd; + FILE *recvfd; +#endif + size_t bufidx; /* index in soap.buf[] */ + size_t buflen; /* length of soap.buf[] content */ + soap_wchar ahead; /* parser lookahead */ + short cdata; /* CDATA parser state */ + short body; /* parsed XML element has a body or not */ + unsigned int level; /* XML nesting level */ + size_t count; /* message length counter */ + size_t length; /* message length as set by HTTP header */ + char *labbuf; /* look-aside buffer */ + size_t lablen; /* look-aside buffer allocated length */ + size_t labidx; /* look-aside buffer index to available part */ + char buf[SOAP_BUFLEN];/* send and receive buffer */ + char msgbuf[1024]; /* in/out buffer for HTTP/MIME headers >=1024 bytes */ + char tmpbuf[1024]; /* in/out buffer for HTTP/MIME headers, simpleType values, element and attribute tag names, and DIME must be >=1024 bytes */ + char tag[SOAP_TAGLEN]; + char id[SOAP_TAGLEN]; + char href[SOAP_TAGLEN]; + char type[SOAP_TAGLEN]; + char arrayType[SOAP_TAGLEN]; + char arraySize[SOAP_TAGLEN]; + char arrayOffset[SOAP_TAGLEN]; + short other; + short position; + int positions[SOAP_MAXDIMS]; + short root; + struct soap_attribute *attributes; /* attribute list */ + short encoding; /* when set, output encodingStyle */ + short mustUnderstand; /* a mustUnderstand element was parsed or is output */ + short null; /* parsed XML is xsi:nil */ + short ns; /* when not set, output full xmlns bindings */ + short part; /* parsing state */ + short alloced; + short peeked; + size_t chunksize; + size_t chunkbuflen; + char endpoint[SOAP_TAGLEN]; + char path[SOAP_TAGLEN]; + char host[SOAP_TAGLEN]; + char *action; + char *authrealm; /* HTTP authentication realm */ + char *prolog; /* XML declaration prolog */ + unsigned long ip; /* IP number */ + int port; /* port number */ + short keep_alive; /* connection should be kept open */ + short tcp_keep_alive; /* enable SO_KEEPALIVE */ + unsigned int tcp_keep_idle; /* set TCP_KEEPIDLE */ + unsigned int tcp_keep_intvl; /* set TCP_KEEPINTVL */ + unsigned int tcp_keep_cnt; /* set TCP_KEEPCNT */ + unsigned int max_keep_alive; /* maximum keep-alive session (default=100) */ + const char *proxy_http_version;/* HTTP version of proxy "1.0" or "1.1" */ + const char *proxy_host; /* Proxy Server host name */ + int proxy_port; /* Proxy Server port (default = 8080) */ + const char *proxy_userid; /* Proxy Authorization user name */ + const char *proxy_passwd; /* Proxy Authorization password */ + const char *proxy_from; /* X-Forwarding-For header returned by proxy */ + int status; /* -1 when request, else error code to be returned by server */ + int error; + int errmode; + int errnum; +#ifndef WITH_LEANER + struct soap_dom_element *dom; + struct soap_dime dime; + struct soap_mime mime; + struct soap_xlist *xlist; +#endif +#if !defined(WITH_LEAN) || defined(SOAP_DEBUG) + const char *logfile[SOAP_MAXLOGS]; + FILE *fdebug[SOAP_MAXLOGS]; + struct soap_mlist *mht[SOAP_PTRHASH]; +#endif +#ifndef WITH_LEAN + const char *c14ninclude; + const char *c14nexclude; + struct soap_cookie *cookies; + const char *cookie_domain; + const char *cookie_path; + int cookie_max; +#endif +#ifndef WITH_NOIO + int ipv6_multicast_if; /* always include this to keep the soap struct size the same in v4 and v6 */ + char* ipv4_multicast_if; /* always include this to keep the soap struct size the same in v4 and v6 */ + int ipv4_multicast_ttl; /* multicast scope */ +#ifdef WITH_IPV6 + struct sockaddr_storage peer; /* IPv6: set by soap_accept and by UDP recv */ +#else + struct sockaddr_in peer; /* IPv4: set by soap_connect/soap_accept and by UDP recv */ +#endif +#endif + size_t peerlen; +#ifdef WITH_OPENSSL + int (*fsslauth)(struct soap*); + int (*fsslverify)(int, X509_STORE_CTX*); + BIO *bio; + SSL *ssl; + SSL_CTX *ctx; + SSL_SESSION *session; +#else + void *fsslauth; /* dummy members, to preserve struct size */ + void *fsslverify; + void *bio; + void *ssl; + void *ctx; + void *session; +#endif + unsigned short ssl_flags; + const char *keyfile; + const char *password; + const char *dhfile; + const char *cafile; + const char *capath; + const char *crlfile; + const char *randfile; + char session_host[SOAP_TAGLEN]; + int session_port; +#ifdef WITH_C_LOCALE + locale_t c_locale; /* set to C locale by default */ +#else + void *c_locale; +#endif +#ifdef WITH_ZLIB + z_stream *d_stream; /* decompression stream */ + uLong z_crc; /* internal gzip crc */ +#else + void *d_stream; /* dummy members, to preserve struct size */ + soap_int32 z_crc; +#endif + const char *z_dict; /* support for zlib static dictionaries */ + unsigned int z_dict_len; + short zlib_state; /* SOAP_ZLIB_NONE, SOAP_ZLIB_DEFLATE, or SOAP_ZLIB_INFLATE */ + short zlib_in; /* SOAP_ZLIB_NONE, SOAP_ZLIB_DEFLATE, or SOAP_ZLIB_GZIP */ + short zlib_out; /* SOAP_ZLIB_NONE, SOAP_ZLIB_DEFLATE, or SOAP_ZLIB_GZIP */ + char *z_buf; /* buffer */ + size_t z_buflen; + unsigned short z_level; /* compression level to be used (0=none, 1=fast to 9=best) */ + float z_ratio_in; /* detected compression ratio compressed_length/length of inbound message */ + float z_ratio_out; /* detected compression ratio compressed_length/length of outbound message */ +#ifdef WMW_RPM_IO + void *rpmreqid; +#endif +#ifdef __cplusplus + soap(); + soap(soap_mode); + soap(soap_mode, soap_mode); + soap(const struct soap&); + virtual ~soap(); +#else + void (*dummy)(); +#endif +}; + +struct soap_code_map +{ long code; + const char *string; +}; + +/* forwarding list */ +struct soap_flist +{ struct soap_flist *next; + int type; + void *ptr; + unsigned int level; + size_t len; + void (*fcopy)(struct soap*, int, int, void*, size_t, const void*, size_t); +}; + +/* id-ref forwarding list */ +struct soap_ilist +{ struct soap_ilist *next; + int type; + size_t size; + void *link; + void *copy; + struct soap_flist *flist; + void *ptr; + unsigned int level; + char id[1]; /* the actual id string value flows into the allocated region below this struct */ +}; + +struct soap_plugin +{ struct soap_plugin *next; + const char *id; + void *data; + int (*fcopy)(struct soap *soap, struct soap_plugin *dst, struct soap_plugin *src); + void (*fdelete)(struct soap *soap, struct soap_plugin *p); /* should delete fields of plugin only and not free(p) */ +}; + +#ifndef WITH_NONAMESPACES +extern SOAP_NMAC struct Namespace namespaces[]; +#endif + +#ifndef WITH_LEAN +# define soap_get0(soap) (((soap)->bufidx>=(soap)->buflen && soap_recv(soap)) ? EOF : (unsigned char)(soap)->buf[(soap)->bufidx]) +# define soap_get1(soap) (((soap)->bufidx>=(soap)->buflen && soap_recv(soap)) ? EOF : (unsigned char)(soap)->buf[(soap)->bufidx++]) +#else +soap_wchar soap_get0(struct soap*); +soap_wchar soap_get1(struct soap*); +#endif + +#define soap_revget1(soap) ((soap)->bufidx--) +#define soap_unget(soap, c) ((soap)->ahead = c) +#define soap_register_plugin(soap, plugin) soap_register_plugin_arg(soap, plugin, NULL) +#define soap_imode(soap, n) ((soap)->mode = (soap)->imode = (n)) +#define soap_set_imode(soap, n) ((soap)->imode |= (n)) +#define soap_clr_imode(soap, n) ((soap)->imode &= ~(n)) +#define soap_omode(soap, n) ((soap)->mode = (soap)->omode = (n)) +#define soap_set_omode(soap, n) ((soap)->omode |= (n)) +#define soap_clr_omode(soap, n) ((soap)->omode &= ~(n)) +#define soap_set_mode(soap, n) ((soap)->imode |= (n), (soap)->omode |= (n)) +#define soap_clr_mode(soap, n) ((soap)->imode &= ~(n), (soap)->omode &= ~(n)) +#define soap_destroy(soap) soap_delete((soap), NULL) + +#ifdef HAVE_STRRCHR +# define soap_strrchr(s, t) strrchr(s, t) +#else + SOAP_FMAC1 char* SOAP_FMAC2 soap_strrchr(const char *s, int t); +#endif + +#ifdef HAVE_STRTOL +# define soap_strtol(s, t, b) strtol(s, t, b) +#else + SOAP_FMAC1 long SOAP_FMAC2 soap_strtol(const char *s, char **t, int b); +#endif + +#ifdef HAVE_STRTOUL +# define soap_strtoul(s, t, b) strtoul(s, t, b) +#else + SOAP_FMAC1 unsigned long SOAP_FMAC2 soap_strtoul(const char *s, char **t, int b); +#endif + +#if defined(WITH_OPENSSL) +# define soap_random soap_rand() +SOAP_FMAC1 int SOAP_FMAC2 soap_rand(void); +#elif defined(HAVE_RANDOM) +# define soap_random (int)random() +#else +# define soap_random rand() +#endif + +#ifdef WITH_NOIDREF +# define soap_embedded(s, p, t) (0) +# define soap_id_lookup(s, i, p, t, n, k) (p) +# define soap_id_forward(s, h, p, len, st, tt, n, k, fc) (p) +# define soap_reference(s, a, t) (1) +# define soap_array_reference(s, p, a, n, t) (1) +# define soap_embed(s, p, a, n, t, pp) (0) +# define soap_embedded_id(s, i, p, t) (i) +# define soap_is_embedded(s, p) (0) +# define soap_is_single(s, p) (1) +# define soap_lookup_type(s, i) (0) +# define soap_getindependent(s) (0) +# define soap_putindependent(s) (0) +# define soap_getelement(s, n) (n) +# define soap_putelement(s, p, t, i, n) (0) +# define soap_markelement(s, p, n) (0) +#endif + +SOAP_FMAC1 void SOAP_FMAC2 soap_header(struct soap*); +SOAP_FMAC1 void SOAP_FMAC2 soap_fault(struct soap*); +SOAP_FMAC1 const char** SOAP_FMAC2 soap_faultcode(struct soap*); +SOAP_FMAC1 const char** SOAP_FMAC2 soap_faultsubcode(struct soap*); +SOAP_FMAC1 const char** SOAP_FMAC2 soap_faultstring(struct soap*); +SOAP_FMAC1 const char** SOAP_FMAC2 soap_faultdetail(struct soap*); +SOAP_FMAC1 void SOAP_FMAC2 soap_serializeheader(struct soap*); +SOAP_FMAC1 int SOAP_FMAC2 soap_putheader(struct soap*); +SOAP_FMAC1 int SOAP_FMAC2 soap_getheader(struct soap*); +SOAP_FMAC1 void SOAP_FMAC2 soap_serializefault(struct soap*); +SOAP_FMAC1 int SOAP_FMAC2 soap_putfault(struct soap*); +SOAP_FMAC1 int SOAP_FMAC2 soap_getfault(struct soap*); + +SOAP_FMAC1 void SOAP_FMAC2 soap_ssl_init(); +SOAP_FMAC1 int SOAP_FMAC2 soap_poll(struct soap*); +SOAP_FMAC1 int SOAP_FMAC2 soap_connect_command(struct soap*, int, const char*, const char*); +SOAP_FMAC1 int SOAP_FMAC2 soap_connect(struct soap*, const char*, const char*); +SOAP_FMAC1 SOAP_SOCKET SOAP_FMAC2 soap_bind(struct soap*, const char*, int, int); +SOAP_FMAC1 SOAP_SOCKET SOAP_FMAC2 soap_accept(struct soap*); +SOAP_FMAC1 int SOAP_FMAC2 soap_ssl_accept(struct soap*); +SOAP_FMAC1 const char * SOAP_FMAC2 soap_ssl_error(struct soap*, int); + +SOAP_FMAC1 int SOAP_FMAC2 soap_ssl_server_context(struct soap*, unsigned short, const char*, const char*, const char*, const char*, const char*, const char*, const char*); +SOAP_FMAC1 int SOAP_FMAC2 soap_ssl_client_context(struct soap*, unsigned short, const char*, const char*, const char*, const char*, const char*); + +SOAP_FMAC1 int SOAP_FMAC2 soap_puthttphdr(struct soap*, int status, size_t count); + +SOAP_FMAC1 const char* SOAP_FMAC2 soap_get_header_attribute(struct soap*, const char*, const char*); +SOAP_FMAC1 const char* SOAP_FMAC2 soap_decode_key(char*, size_t, const char*); +SOAP_FMAC1 const char* SOAP_FMAC2 soap_decode_val(char*, size_t, const char*); + +SOAP_FMAC1 size_t SOAP_FMAC2 soap_hash(const char*); +SOAP_FMAC1 void SOAP_FMAC2 soap_set_endpoint(struct soap*, const char*); +SOAP_FMAC1 int SOAP_FMAC2 soap_flush_raw(struct soap*, const char*, size_t); +SOAP_FMAC1 int SOAP_FMAC2 soap_flush(struct soap*); +SOAP_FMAC1 soap_wchar SOAP_FMAC2 soap_get(struct soap*); +SOAP_FMAC1 soap_wchar SOAP_FMAC2 soap_getchar(struct soap*); +SOAP_FMAC1 int SOAP_FMAC2 soap_tag_cmp(const char*, const char*); +SOAP_FMAC1 void SOAP_FMAC2 soap_set_fault(struct soap*); +SOAP_FMAC1 int SOAP_FMAC2 soap_sender_fault(struct soap*, const char*, const char*); +SOAP_FMAC1 int SOAP_FMAC2 soap_sender_fault_subcode(struct soap*, const char*, const char*, const char*); +SOAP_FMAC1 int SOAP_FMAC2 soap_receiver_fault(struct soap*, const char*, const char*); +SOAP_FMAC1 int SOAP_FMAC2 soap_receiver_fault_subcode(struct soap*, const char*, const char*, const char*); +SOAP_FMAC1 int SOAP_FMAC2 soap_set_sender_error(struct soap*, const char*, const char*, int); +SOAP_FMAC1 int SOAP_FMAC2 soap_set_receiver_error(struct soap*, const char*, const char*, int); + +SOAP_FMAC1 int SOAP_FMAC2 soap_send_raw(struct soap*, const char*, size_t); +SOAP_FMAC1 int SOAP_FMAC2 soap_recv_raw(struct soap*); +SOAP_FMAC1 int SOAP_FMAC2 soap_recv(struct soap*); +SOAP_FMAC1 int SOAP_FMAC2 soap_send(struct soap*, const char*); +SOAP_FMAC1 int SOAP_FMAC2 soap_send2(struct soap*, const char*, const char*); +SOAP_FMAC1 int SOAP_FMAC2 soap_send3(struct soap*, const char*, const char*, const char*); + +SOAP_FMAC1 int SOAP_FMAC2 soap_pututf8(struct soap*, unsigned long); +SOAP_FMAC1 soap_wchar SOAP_FMAC2 soap_getutf8(struct soap*); + +SOAP_FMAC1 int SOAP_FMAC2 soap_putbase64(struct soap*, const unsigned char*, int); +SOAP_FMAC1 unsigned char* SOAP_FMAC2 soap_getbase64(struct soap*, int*, int); +SOAP_FMAC1 int SOAP_FMAC2 soap_puthex(struct soap*, const unsigned char*, int); +SOAP_FMAC1 unsigned char* SOAP_FMAC2 soap_gethex(struct soap*, int*); + +#ifndef WITH_LEANER +SOAP_FMAC1 int SOAP_FMAC2 soap_xop_forward(struct soap*, unsigned char**, int*, char**, char**, char**); +SOAP_FMAC1 int SOAP_FMAC2 soap_dime_forward(struct soap*, unsigned char**, int*, char**, char**, char**); +#endif + +#ifndef WITH_NOIDREF +SOAP_FMAC1 int SOAP_FMAC2 soap_pointer_lookup_id(struct soap*, void *p, int t, struct soap_plist**); +SOAP_FMAC1 int SOAP_FMAC2 soap_pointer_lookup(struct soap*, const void *p, int t, struct soap_plist**); +SOAP_FMAC1 int SOAP_FMAC2 soap_pointer_enter(struct soap*, const void *p, const struct soap_array *a, int n, int t, struct soap_plist**); +SOAP_FMAC1 int SOAP_FMAC2 soap_array_pointer_lookup(struct soap*, const void *p, const struct soap_array *a, int n, int t, struct soap_plist**); +SOAP_FMAC1 int SOAP_FMAC2 soap_embed(struct soap *soap, const void *p, const struct soap_array *a, int n, const char *tag, int type); +SOAP_FMAC1 struct soap_ilist* SOAP_FMAC2 soap_lookup(struct soap*, const char*); +SOAP_FMAC1 struct soap_ilist* SOAP_FMAC2 soap_enter(struct soap*, const char*); +SOAP_FMAC1 int SOAP_FMAC2 soap_resolve(struct soap*); +SOAP_FMAC1 void SOAP_FMAC2 soap_embedded(struct soap*, const void *p, int t); +SOAP_FMAC1 int SOAP_FMAC2 soap_reference(struct soap*, const void *p, int t); +SOAP_FMAC1 int SOAP_FMAC2 soap_array_reference(struct soap*, const void *p, const struct soap_array *a, int n, int t); +SOAP_FMAC1 int SOAP_FMAC2 soap_embedded_id(struct soap*, int id, const void *p, int t); +SOAP_FMAC1 int SOAP_FMAC2 soap_is_embedded(struct soap*, struct soap_plist*); +SOAP_FMAC1 int SOAP_FMAC2 soap_is_single(struct soap*, struct soap_plist*); +SOAP_FMAC1 void SOAP_FMAC2 soap_set_embedded(struct soap*, struct soap_plist*); +#endif + +SOAP_FMAC1 int SOAP_FMAC2 soap_begin_count(struct soap*); +SOAP_FMAC1 int SOAP_FMAC2 soap_end_count(struct soap*); +SOAP_FMAC1 int SOAP_FMAC2 soap_begin_send(struct soap*); +SOAP_FMAC1 int SOAP_FMAC2 soap_end_send(struct soap*); + +SOAP_FMAC1 const struct soap_code_map* SOAP_FMAC2 soap_code(const struct soap_code_map*, const char*); +SOAP_FMAC1 long SOAP_FMAC2 soap_code_int(const struct soap_code_map*, const char*, long); +SOAP_FMAC1 const char* SOAP_FMAC2 soap_code_str(const struct soap_code_map*, long); +SOAP_FMAC1 long SOAP_FMAC2 soap_code_bits(const struct soap_code_map*, const char*); +SOAP_FMAC1 const char* SOAP_FMAC2 soap_code_list(struct soap*, const struct soap_code_map*, long); + +SOAP_FMAC1 int SOAP_FMAC2 soap_getline(struct soap*, char*, int); +SOAP_FMAC1 int SOAP_FMAC2 soap_begin_recv(struct soap*); +SOAP_FMAC1 int SOAP_FMAC2 soap_end_recv(struct soap*); + +SOAP_FMAC1 void* SOAP_FMAC2 soap_malloc(struct soap*, size_t); +SOAP_FMAC1 void SOAP_FMAC2 soap_dealloc(struct soap*, void*); +SOAP_FMAC1 struct soap_clist * SOAP_FMAC2 soap_link(struct soap*, void*, int, int, int (*fdelete)(struct soap_clist*)); +SOAP_FMAC1 void SOAP_FMAC2 soap_unlink(struct soap*, const void*); +SOAP_FMAC1 void SOAP_FMAC2 soap_free_temp(struct soap*); +SOAP_FMAC1 void SOAP_FMAC2 soap_del(struct soap*); + +SOAP_FMAC1 void* SOAP_FMAC2 soap_track_malloc(struct soap*, const char*, int, size_t); +SOAP_FMAC1 void SOAP_FMAC2 soap_track_free(struct soap*, const char*, int, void*); + +#ifndef WITH_NOIDREF +SOAP_FMAC1 int SOAP_FMAC2 soap_lookup_type(struct soap*, const char *id); +SOAP_FMAC1 void* SOAP_FMAC2 soap_id_lookup(struct soap*, const char *id, void **p, int t, size_t n, unsigned int k); +SOAP_FMAC1 void* SOAP_FMAC2 soap_id_forward(struct soap*, const char *id, void *p, size_t len, int st, int tt, size_t n, unsigned int k, void(*fcopy)(struct soap*, int, int, void*, size_t, const void*, size_t)); +#endif +SOAP_FMAC1 void* SOAP_FMAC2 soap_id_enter(struct soap*, const char *id, void *p, int t, size_t n, unsigned int k, const char *type, const char *arrayType, void *(*finstantiate)(struct soap*, int, const char*, const char*, size_t*)); +SOAP_FMAC1 void SOAP_FMAC2 soap_fcopy(struct soap *soap, int st, int tt, void *p, size_t, const void *q, size_t n); + +SOAP_FMAC1 int SOAP_FMAC2 soap_size(const int *, int); +SOAP_FMAC1 int SOAP_FMAC2 soap_getoffsets(const char *, const int *, int *, int); +SOAP_FMAC1 int SOAP_FMAC2 soap_getsize(const char *, const char *, int *); +SOAP_FMAC1 int SOAP_FMAC2 soap_getsizes(const char *, int *, int); +SOAP_FMAC1 int SOAP_FMAC2 soap_getposition(const char *, int *); + +SOAP_FMAC1 char* SOAP_FMAC2 soap_putsize(struct soap*, const char *, int); +SOAP_FMAC1 char* SOAP_FMAC2 soap_putsizesoffsets(struct soap*, const char *, const int *, const int *, int); +SOAP_FMAC1 char* SOAP_FMAC2 soap_putsizes(struct soap*, const char *, const int *, int); +SOAP_FMAC1 char* SOAP_FMAC2 soap_putoffset(struct soap*, int); +SOAP_FMAC1 char* SOAP_FMAC2 soap_putoffsets(struct soap*, const int *, int); + +SOAP_FMAC1 int SOAP_FMAC2 soap_closesock(struct soap*); + +SOAP_FMAC1 struct soap *SOAP_FMAC2 soap_new(void); +SOAP_FMAC1 struct soap *SOAP_FMAC2 soap_new1(soap_mode); +SOAP_FMAC1 struct soap *SOAP_FMAC2 soap_new2(soap_mode, soap_mode); +SOAP_FMAC1 void SOAP_FMAC2 soap_free(struct soap*); +SOAP_FMAC1 struct soap *SOAP_FMAC2 soap_copy(const struct soap*); +SOAP_FMAC1 struct soap *SOAP_FMAC2 soap_copy_context(struct soap*, const struct soap*); +SOAP_FMAC1 void SOAP_FMAC2 soap_copy_stream(struct soap*, struct soap*); +SOAP_FMAC1 void SOAP_FMAC2 soap_init(struct soap*); +SOAP_FMAC1 void SOAP_FMAC2 soap_init1(struct soap*, soap_mode); +SOAP_FMAC1 void SOAP_FMAC2 soap_init2(struct soap*, soap_mode, soap_mode); +SOAP_FMAC1 void SOAP_FMAC2 soap_done(struct soap*); +SOAP_FMAC1 void SOAP_FMAC2 soap_cleanup(struct soap*); +SOAP_FMAC1 void SOAP_FMAC2 soap_begin(struct soap*); +SOAP_FMAC1 void SOAP_FMAC2 soap_end(struct soap*); +SOAP_FMAC1 void SOAP_FMAC2 soap_delete(struct soap*, void*); +SOAP_FMAC1 void SOAP_FMAC2 soap_delegate_deletion(struct soap*, struct soap*); + +/* API functions available with DEBUG or SOAP_DEBUG defined: */ +SOAP_FMAC1 void SOAP_FMAC2 soap_set_recv_logfile(struct soap*, const char*); +SOAP_FMAC1 void SOAP_FMAC2 soap_set_sent_logfile(struct soap*, const char*); +SOAP_FMAC1 void SOAP_FMAC2 soap_set_test_logfile(struct soap*, const char*); +SOAP_FMAC1 void SOAP_FMAC2 soap_close_logfiles(struct soap*); +SOAP_FMAC1 void SOAP_FMAC2 soap_open_logfile(struct soap*, int); +/* */ + +SOAP_FMAC1 const char* SOAP_FMAC2 soap_value(struct soap*); + +SOAP_FMAC1 int SOAP_FMAC2 soap_match_tag(struct soap*, const char*, const char *); +SOAP_FMAC1 int SOAP_FMAC2 soap_match_array(struct soap*, const char*); + +SOAP_FMAC1 int SOAP_FMAC2 soap_element(struct soap*, const char*, int, const char*); +SOAP_FMAC1 int SOAP_FMAC2 soap_element_begin_out(struct soap*, const char *tag, int id, const char *type); +SOAP_FMAC1 int SOAP_FMAC2 soap_array_begin_out(struct soap*, const char *tag, int id, const char *type, const char *offset); +SOAP_FMAC1 int SOAP_FMAC2 soap_element_ref(struct soap*, const char *tag, int id, int href); +SOAP_FMAC1 int SOAP_FMAC2 soap_element_href(struct soap*, const char *tag, int id, const char *ref, const char *val); +SOAP_FMAC1 int SOAP_FMAC2 soap_element_null(struct soap*, const char *tag, int id, const char *type); +SOAP_FMAC1 int SOAP_FMAC2 soap_element_id(struct soap*, const char *tag, int id, const void *p, const struct soap_array *a, int d, const char *type, int n); +SOAP_FMAC1 int SOAP_FMAC2 soap_element_result(struct soap*, const char *tag); +SOAP_FMAC1 void SOAP_FMAC2 soap_check_result(struct soap*, const char *tag); +SOAP_FMAC1 int SOAP_FMAC2 soap_element_end_out(struct soap*, const char *tag); +SOAP_FMAC1 int SOAP_FMAC2 soap_element_start_end_out(struct soap*, const char *tag); + +SOAP_FMAC1 int SOAP_FMAC2 soap_attribute(struct soap*, const char*, const char*); + +SOAP_FMAC1 int SOAP_FMAC2 soap_element_begin_in(struct soap*, const char *tag, int nillable, const char *type); + +SOAP_FMAC1 int SOAP_FMAC2 soap_element_end_in(struct soap*, const char *tag); + +SOAP_FMAC1 int SOAP_FMAC2 soap_peek_element(struct soap*); + +SOAP_FMAC1 void SOAP_FMAC2 soap_retry(struct soap*); +SOAP_FMAC1 void SOAP_FMAC2 soap_revert(struct soap*); + +SOAP_FMAC1 char* SOAP_FMAC2 soap_strdup(struct soap*, const char*); +SOAP_FMAC1 wchar_t* SOAP_FMAC2 soap_wstrdup(struct soap*, const wchar_t*); +SOAP_FMAC1 const char * SOAP_FMAC2 soap_strsearch(const char *big, const char *little); + +SOAP_FMAC1 int SOAP_FMAC2 soap_string_out(struct soap*, const char *s, int flag); +SOAP_FMAC1 char* SOAP_FMAC2 soap_string_in(struct soap*, int, long, long); + +#ifndef WITH_LEANER +SOAP_FMAC1 int SOAP_FMAC2 soap_wstring_out(struct soap*, const wchar_t *s, int flag); +SOAP_FMAC1 wchar_t* SOAP_FMAC2 soap_wstring_in(struct soap*, int, long, long); +#endif + +SOAP_FMAC1 int SOAP_FMAC2 soap_match_namespace(struct soap*, const char *, const char*, size_t n1, size_t n2); + +SOAP_FMAC1 int SOAP_FMAC2 soap_set_namespaces(struct soap*, const struct Namespace*); +SOAP_FMAC1 void SOAP_FMAC2 soap_set_local_namespaces(struct soap*); + +SOAP_FMAC1 void SOAP_FMAC2 soap_pop_namespace(struct soap*); +SOAP_FMAC1 struct soap_nlist* SOAP_FMAC2 soap_push_namespace(struct soap*, const char *,const char *); +SOAP_FMAC1 const char* SOAP_FMAC2 soap_current_namespace(struct soap *soap, const char *tag); + +SOAP_FMAC1 struct soap_nlist* SOAP_FMAC2 soap_lookup_ns(struct soap *soap, const char *tag, size_t n); + +SOAP_FMAC1 int SOAP_FMAC2 soap_store_lab(struct soap*, const char*, size_t); +SOAP_FMAC1 int SOAP_FMAC2 soap_append_lab(struct soap*, const char*, size_t); + +SOAP_FMAC1 struct soap_blist* SOAP_FMAC2 soap_new_block(struct soap*); +SOAP_FMAC1 void* SOAP_FMAC2 soap_push_block(struct soap*, struct soap_blist*, size_t); +SOAP_FMAC1 void SOAP_FMAC2 soap_pop_block(struct soap*, struct soap_blist*); +SOAP_FMAC1 size_t SOAP_FMAC2 soap_size_block(struct soap*, struct soap_blist*, size_t); +SOAP_FMAC1 char* SOAP_FMAC2 soap_first_block(struct soap*, struct soap_blist*); +SOAP_FMAC1 char* SOAP_FMAC2 soap_next_block(struct soap*, struct soap_blist*); +SOAP_FMAC1 size_t SOAP_FMAC2 soap_block_size(struct soap*, struct soap_blist*); +SOAP_FMAC1 char* SOAP_FMAC2 soap_save_block(struct soap*, struct soap_blist*, char*, int); +SOAP_FMAC1 void SOAP_FMAC2 soap_end_block(struct soap*, struct soap_blist*); + +SOAP_FMAC1 int SOAP_FMAC2 soap_envelope_begin_out(struct soap*); +SOAP_FMAC1 int soap_envelope_end_out(struct soap*); + +SOAP_FMAC1 int SOAP_FMAC2 soap_envelope_begin_in(struct soap*); +SOAP_FMAC1 int SOAP_FMAC2 soap_envelope_end_in(struct soap*); + +SOAP_FMAC1 int SOAP_FMAC2 soap_body_begin_out(struct soap*); +SOAP_FMAC1 int SOAP_FMAC2 soap_body_end_out(struct soap*); + +SOAP_FMAC1 int SOAP_FMAC2 soap_body_begin_in(struct soap*); +SOAP_FMAC1 int SOAP_FMAC2 soap_body_end_in(struct soap*); + +SOAP_FMAC1 int SOAP_FMAC2 soap_recv_header(struct soap*); + +SOAP_FMAC1 int SOAP_FMAC2 soap_response(struct soap*, int); + +SOAP_FMAC1 int SOAP_FMAC2 soap_send_empty_response(struct soap*, int status); +SOAP_FMAC1 int SOAP_FMAC2 soap_recv_empty_response(struct soap*); + +SOAP_FMAC1 int SOAP_FMAC2 soap_send_fault(struct soap*); +SOAP_FMAC1 int SOAP_FMAC2 soap_recv_fault(struct soap*); + +#ifndef WITH_NOSTDLIB +SOAP_FMAC1 void SOAP_FMAC2 soap_print_fault(struct soap*, FILE*); +SOAP_FMAC1 void SOAP_FMAC2 soap_print_fault_location(struct soap*, FILE*); +# ifndef WITH_LEAN +# ifdef __cplusplus +SOAP_FMAC1 void SOAP_FMAC2 soap_stream_fault(struct soap*, std::ostream&); +# endif +SOAP_FMAC1 char* SOAP_FMAC2 soap_sprint_fault(struct soap*, char*, size_t); +# endif +#endif + +SOAP_FMAC1 int SOAP_FMAC2 soap_s2byte(struct soap*, const char*, char*); +SOAP_FMAC1 int SOAP_FMAC2 soap_s2short(struct soap*, const char*, short*); +SOAP_FMAC1 int SOAP_FMAC2 soap_s2int(struct soap*, const char*, int*); +SOAP_FMAC1 int SOAP_FMAC2 soap_s2long(struct soap*, const char*, long*); +SOAP_FMAC1 int SOAP_FMAC2 soap_s2LONG64(struct soap*, const char*, LONG64*); +SOAP_FMAC1 int SOAP_FMAC2 soap_s2float(struct soap*, const char*, float*); +SOAP_FMAC1 int SOAP_FMAC2 soap_s2double(struct soap*, const char*, double*); +SOAP_FMAC1 int SOAP_FMAC2 soap_s2unsignedByte(struct soap*, const char*, unsigned char*); +SOAP_FMAC1 int SOAP_FMAC2 soap_s2unsignedShort(struct soap*, const char*, unsigned short*); +SOAP_FMAC1 int SOAP_FMAC2 soap_s2unsignedInt(struct soap*, const char*, unsigned int*); +SOAP_FMAC1 int SOAP_FMAC2 soap_s2unsignedLong(struct soap*, const char*, unsigned long*); +SOAP_FMAC1 int SOAP_FMAC2 soap_s2ULONG64(struct soap*, const char*, ULONG64*); +SOAP_FMAC1 int SOAP_FMAC2 soap_s2string(struct soap*, const char*, char**, long minlen, long maxlen); +SOAP_FMAC1 int SOAP_FMAC2 soap_s2QName(struct soap*, const char*, char**, long minlen, long maxlen); + +#ifndef WITH_LEAN +SOAP_FMAC1 int SOAP_FMAC2 soap_s2wchar(struct soap*, const char*, wchar_t**, long minlen, long maxlen); +SOAP_FMAC1 int SOAP_FMAC2 soap_s2dateTime(struct soap*, const char*, time_t*); +SOAP_FMAC1 char* SOAP_FMAC2 soap_s2base64(struct soap*, const unsigned char*, char*, int); +SOAP_FMAC1 char* SOAP_FMAC2 soap_s2hex(struct soap*, const unsigned char*, char*, int); +#endif + +SOAP_FMAC1 const char* SOAP_FMAC2 soap_byte2s(struct soap*, char); +SOAP_FMAC1 const char* SOAP_FMAC2 soap_short2s(struct soap*, short); +SOAP_FMAC1 const char* SOAP_FMAC2 soap_int2s(struct soap*, int); +SOAP_FMAC1 const char* SOAP_FMAC2 soap_long2s(struct soap*, long); +SOAP_FMAC1 const char* SOAP_FMAC2 soap_LONG642s(struct soap*, LONG64); +SOAP_FMAC1 const char* SOAP_FMAC2 soap_float2s(struct soap*, float); +SOAP_FMAC1 const char* SOAP_FMAC2 soap_double2s(struct soap*, double); +SOAP_FMAC1 const char* SOAP_FMAC2 soap_unsignedByte2s(struct soap*, unsigned char); +SOAP_FMAC1 const char* SOAP_FMAC2 soap_unsignedShort2s(struct soap*, unsigned short); +SOAP_FMAC1 const char* SOAP_FMAC2 soap_unsignedInt2s(struct soap*, unsigned int); +SOAP_FMAC1 const char* SOAP_FMAC2 soap_unsignedLong2s(struct soap*, unsigned long); +SOAP_FMAC1 const char* SOAP_FMAC2 soap_ULONG642s(struct soap*, ULONG64); +SOAP_FMAC1 const char* SOAP_FMAC2 soap_QName2s(struct soap*, const char*); + +#ifndef WITH_LEAN +SOAP_FMAC1 const char* SOAP_FMAC2 soap_wchar2s(struct soap*, const wchar_t*); +SOAP_FMAC1 const char* SOAP_FMAC2 soap_dateTime2s(struct soap*, time_t); +SOAP_FMAC1 const char* SOAP_FMAC2 soap_base642s(struct soap*, const char*, char*, size_t, int*); +SOAP_FMAC1 const char* SOAP_FMAC2 soap_hex2s(struct soap*, const char*, char*, size_t, int*); +#endif + + +SOAP_FMAC1 int* SOAP_FMAC2 soap_inint(struct soap*, const char *tag, int *p, const char *, int); +SOAP_FMAC1 char* SOAP_FMAC2 soap_inbyte(struct soap*, const char *tag, char *p, const char *, int); +SOAP_FMAC1 long* SOAP_FMAC2 soap_inlong(struct soap*, const char *tag, long *p, const char *, int); +SOAP_FMAC1 LONG64* SOAP_FMAC2 soap_inLONG64(struct soap*, const char *tag, LONG64 *p, const char *, int); +SOAP_FMAC1 short* SOAP_FMAC2 soap_inshort(struct soap*, const char *tag, short *p, const char *, int); +SOAP_FMAC1 float* SOAP_FMAC2 soap_infloat(struct soap*, const char *tag, float *p, const char *, int); +SOAP_FMAC1 double* SOAP_FMAC2 soap_indouble(struct soap*, const char *tag, double *p, const char *, int); +SOAP_FMAC1 unsigned char* SOAP_FMAC2 soap_inunsignedByte(struct soap*, const char *tag, unsigned char *p, const char *, int); +SOAP_FMAC1 unsigned short* SOAP_FMAC2 soap_inunsignedShort(struct soap*, const char *tag, unsigned short *p, const char *, int); +SOAP_FMAC1 unsigned int* SOAP_FMAC2 soap_inunsignedInt(struct soap*, const char *tag, unsigned int *p, const char *, int); +SOAP_FMAC1 unsigned long* SOAP_FMAC2 soap_inunsignedLong(struct soap*, const char *tag, unsigned long *p, const char *, int); +SOAP_FMAC1 ULONG64* SOAP_FMAC2 soap_inULONG64(struct soap*, const char *tag, ULONG64 *p, const char *, int); +SOAP_FMAC1 char** SOAP_FMAC2 soap_instring(struct soap*, const char *tag, char **p, const char *, int, int, long, long); +SOAP_FMAC1 char** SOAP_FMAC2 soap_inliteral(struct soap*, const char *tag, char **p); + +#ifndef WITH_LEAN +SOAP_FMAC1 time_t* SOAP_FMAC2 soap_indateTime(struct soap*, const char *tag, time_t *p, const char *, int); +SOAP_FMAC1 time_t SOAP_FMAC2 soap_timegm(struct tm*); +#endif + +#ifndef WITH_LEANER +SOAP_FMAC1 wchar_t** SOAP_FMAC2 soap_inwstring(struct soap*, const char *tag, wchar_t **p, const char *, int, long, long); +SOAP_FMAC1 wchar_t** SOAP_FMAC2 soap_inwliteral(struct soap*, const char *tag, wchar_t **p); +#endif + +SOAP_FMAC1 int SOAP_FMAC2 soap_outbyte(struct soap*, const char *tag, int id, const char *p, const char *, int); +SOAP_FMAC1 int SOAP_FMAC2 soap_outshort(struct soap*, const char *tag, int id, const short *p, const char *, int); +SOAP_FMAC1 int SOAP_FMAC2 soap_outint(struct soap*, const char *tag, int id, const int *p, const char *, int); +SOAP_FMAC1 int SOAP_FMAC2 soap_outlong(struct soap*, const char *tag, int id, const long *p, const char *, int); +SOAP_FMAC1 int SOAP_FMAC2 soap_outLONG64(struct soap*, const char *tag, int id, const LONG64 *p, const char *, int); +SOAP_FMAC1 int SOAP_FMAC2 soap_outfloat(struct soap*, const char *tag, int id, const float *p, const char *, int); +SOAP_FMAC1 int SOAP_FMAC2 soap_outdouble(struct soap*, const char *tag, int id, const double *p, const char *, int); +SOAP_FMAC1 int SOAP_FMAC2 soap_outunsignedByte(struct soap*, const char *tag, int id, const unsigned char *p, const char *, int); +SOAP_FMAC1 int SOAP_FMAC2 soap_outunsignedShort(struct soap*, const char *tag, int id, const unsigned short *p, const char *, int); +SOAP_FMAC1 int SOAP_FMAC2 soap_outunsignedInt(struct soap*, const char *tag, int id, const unsigned int *p, const char *, int); +SOAP_FMAC1 int SOAP_FMAC2 soap_outunsignedLong(struct soap*, const char *tag, int id, const unsigned long *p, const char *, int); +SOAP_FMAC1 int SOAP_FMAC2 soap_outULONG64(struct soap*, const char *tag, int id, const ULONG64 *p, const char *, int); +SOAP_FMAC1 int SOAP_FMAC2 soap_outstring(struct soap*, const char *tag, int id, char *const*p, const char *, int); +SOAP_FMAC1 int SOAP_FMAC2 soap_outliteral(struct soap*, const char *tag, char *const*p, const char *type); + +#ifndef WITH_LEAN +SOAP_FMAC1 int SOAP_FMAC2 soap_outdateTime(struct soap*, const char *tag, int id, const time_t *p, const char *, int); +#endif + +#ifndef WITH_LEANER +SOAP_FMAC1 int SOAP_FMAC2 soap_outwstring(struct soap*, const char *tag, int id, wchar_t *const*p, const char *, int); +SOAP_FMAC1 int SOAP_FMAC2 soap_outwliteral(struct soap*, const char *tag, wchar_t *const*p, const char *type); +#endif + +#ifndef WITH_LEANER +SOAP_FMAC1 int SOAP_FMAC2 soap_attachment(struct soap *, const char*, int, const void*, const struct soap_array*, const char*, const char*, const char*, int, const char*, int); +SOAP_FMAC1 int SOAP_FMAC2 soap_move(struct soap*, long); +SOAP_FMAC1 size_t SOAP_FMAC2 soap_tell(struct soap*); +SOAP_FMAC1 char* SOAP_FMAC2 soap_dime_option(struct soap*, unsigned short, const char*); +SOAP_FMAC1 int SOAP_FMAC2 soap_getdimehdr(struct soap*); +SOAP_FMAC1 int SOAP_FMAC2 soap_getdime(struct soap*); +SOAP_FMAC1 int SOAP_FMAC2 soap_putdimehdr(struct soap*); +SOAP_FMAC1 int SOAP_FMAC2 soap_putdime(struct soap*); +SOAP_FMAC1 int SOAP_FMAC2 soap_getmimehdr(struct soap*); +SOAP_FMAC1 int SOAP_FMAC2 soap_getmime(struct soap*); +SOAP_FMAC1 int SOAP_FMAC2 soap_putmimehdr(struct soap*, struct soap_multipart*); +SOAP_FMAC1 int SOAP_FMAC2 soap_putmime(struct soap*); +SOAP_FMAC1 void SOAP_FMAC2 soap_set_dime(struct soap*); +SOAP_FMAC1 void SOAP_FMAC2 soap_set_mime(struct soap*, const char *boundary, const char *start); +SOAP_FMAC1 void SOAP_FMAC2 soap_clr_dime(struct soap*); +SOAP_FMAC1 void SOAP_FMAC2 soap_clr_mime(struct soap*); +SOAP_FMAC1 int SOAP_FMAC2 soap_set_dime_attachment(struct soap*, char *ptr, size_t size, const char *type, const char *id, unsigned short optype, const char *option); +SOAP_FMAC1 int SOAP_FMAC2 soap_set_mime_attachment(struct soap*, char *ptr, size_t size, enum soap_mime_encoding encoding, const char *type, const char *id, const char *location, const char *description); +SOAP_FMAC1 void SOAP_FMAC2 soap_post_check_mime_attachments(struct soap *soap); +SOAP_FMAC1 int SOAP_FMAC2 soap_check_mime_attachments(struct soap *soap); +SOAP_FMAC1 struct soap_multipart* SOAP_FMAC2 soap_get_mime_attachment(struct soap *soap, void *handle); +SOAP_FMAC1 int SOAP_FMAC2 soap_match_cid(struct soap*, const char*, const char*); +#endif + +SOAP_FMAC1 int SOAP_FMAC2 soap_register_plugin_arg(struct soap*, int (*fcreate)(struct soap*, struct soap_plugin*, void*), void*); +SOAP_FMAC1 void* SOAP_FMAC2 soap_lookup_plugin(struct soap*, const char*); + +SOAP_FMAC1 const char* SOAP_FMAC2 soap_attr_value(struct soap *soap, const char *name, int flag); +SOAP_FMAC1 int SOAP_FMAC2 soap_set_attr(struct soap *soap, const char *name, const char *value); +SOAP_FMAC1 void SOAP_FMAC2 soap_clr_attr(struct soap *soap); + +#ifdef WITH_COOKIES +SOAP_FMAC1 void SOAP_FMAC2 soap_getcookies(struct soap *soap, const char *val); +SOAP_FMAC1 size_t SOAP_FMAC2 soap_encode_cookie(const char*, char*, size_t); +SOAP_FMAC1 extern struct soap_cookie* SOAP_FMAC2 soap_set_cookie(struct soap*, const char*, const char*, const char*, const char*); +SOAP_FMAC1 extern struct soap_cookie* SOAP_FMAC2 soap_cookie(struct soap*, const char*, const char*, const char*); +SOAP_FMAC1 extern char* SOAP_FMAC2 soap_cookie_value(struct soap*, const char*, const char*, const char*); +SOAP_FMAC1 extern char* SOAP_FMAC2 soap_env_cookie_value(struct soap*, const char*, const char*, const char*); +SOAP_FMAC1 extern time_t SOAP_FMAC2 soap_cookie_expire(struct soap*, const char*, const char*, const char*); +SOAP_FMAC1 extern int SOAP_FMAC2 soap_set_cookie_expire(struct soap*, const char*, long, const char*, const char*); +SOAP_FMAC1 extern int SOAP_FMAC2 soap_set_cookie_session(struct soap*, const char*, const char*, const char*); +SOAP_FMAC1 extern int SOAP_FMAC2 soap_clr_cookie_session(struct soap*, const char*, const char*, const char*); +SOAP_FMAC1 extern void SOAP_FMAC2 soap_clr_cookie(struct soap*, const char*, const char*, const char*); +SOAP_FMAC1 extern int SOAP_FMAC2 soap_getenv_cookies(struct soap*); +SOAP_FMAC1 extern struct soap_cookie* SOAP_FMAC2 soap_copy_cookies(struct soap*, const struct soap*); +SOAP_FMAC1 extern void SOAP_FMAC2 soap_free_cookies(struct soap*); +#endif + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif diff --git a/dep/jemalloc/CMakeLists.txt b/dep/jemalloc/CMakeLists.txt new file mode 100644 index 00000000000..d560c6ba675 --- /dev/null +++ b/dep/jemalloc/CMakeLists.txt @@ -0,0 +1,25 @@ +# Copyright (C) 2008-2010 Trinity +# +# This file is free software; as a special exception the author gives +# unlimited permission to copy and/or distribute it, with or without +# modifications, as long as this notice is preserved. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the +# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +file(GLOB sources *.c) + +set(jemalloc_STAT_SRC + ${sources} +) + +include_directories( + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/include + ${CMAKE_CURRENT_SOURCE_DIR}/include/internal +) + +add_definitions(-D_GNU_SOURCE -D_REENTRANT) + +add_library(jemalloc STATIC ${sources}) diff --git a/dep/jemalloc/arena.c b/dep/jemalloc/arena.c new file mode 100644 index 00000000000..e74b4701907 --- /dev/null +++ b/dep/jemalloc/arena.c @@ -0,0 +1,2446 @@ +#define JEMALLOC_ARENA_C_ +#include "jemalloc/internal/jemalloc_internal.h" + +/******************************************************************************/ +/* Data. */ + +size_t opt_lg_qspace_max = LG_QSPACE_MAX_DEFAULT; +size_t opt_lg_cspace_max = LG_CSPACE_MAX_DEFAULT; +ssize_t opt_lg_dirty_mult = LG_DIRTY_MULT_DEFAULT; +uint8_t const *small_size2bin; + +/* Various bin-related settings. */ +unsigned nqbins; +unsigned ncbins; +unsigned nsbins; +unsigned nbins; +size_t qspace_max; +size_t cspace_min; +size_t cspace_max; +size_t sspace_min; +size_t sspace_max; + +size_t lg_mspace; +size_t mspace_mask; + +/* + * const_small_size2bin is a static constant lookup table that in the common + * case can be used as-is for small_size2bin. For dynamically linked programs, + * this avoids a page of memory overhead per process. + */ +#define S2B_1(i) i, +#define S2B_2(i) S2B_1(i) S2B_1(i) +#define S2B_4(i) S2B_2(i) S2B_2(i) +#define S2B_8(i) S2B_4(i) S2B_4(i) +#define S2B_16(i) S2B_8(i) S2B_8(i) +#define S2B_32(i) S2B_16(i) S2B_16(i) +#define S2B_64(i) S2B_32(i) S2B_32(i) +#define S2B_128(i) S2B_64(i) S2B_64(i) +#define S2B_256(i) S2B_128(i) S2B_128(i) +/* + * The number of elements in const_small_size2bin is dependent on page size + * and on the definition for SUBPAGE. If SUBPAGE changes, the '- 255' must also + * change, along with the addition/removal of static lookup table element + * definitions. + */ +static const uint8_t const_small_size2bin[STATIC_PAGE_SIZE - 255] = { + S2B_1(0xffU) /* 0 */ +#if (LG_QUANTUM == 4) +/* 16-byte quantum **********************/ +# ifdef JEMALLOC_TINY +# if (LG_TINY_MIN == 2) + S2B_4(0) /* 4 */ + S2B_4(1) /* 8 */ + S2B_8(2) /* 16 */ +# define S2B_QMIN 2 +# elif (LG_TINY_MIN == 3) + S2B_8(0) /* 8 */ + S2B_8(1) /* 16 */ +# define S2B_QMIN 1 +# else +# error "Unsupported LG_TINY_MIN" +# endif +# else + S2B_16(0) /* 16 */ +# define S2B_QMIN 0 +# endif + S2B_16(S2B_QMIN + 1) /* 32 */ + S2B_16(S2B_QMIN + 2) /* 48 */ + S2B_16(S2B_QMIN + 3) /* 64 */ + S2B_16(S2B_QMIN + 4) /* 80 */ + S2B_16(S2B_QMIN + 5) /* 96 */ + S2B_16(S2B_QMIN + 6) /* 112 */ + S2B_16(S2B_QMIN + 7) /* 128 */ +# define S2B_CMIN (S2B_QMIN + 8) +#else +/* 8-byte quantum ***********************/ +# ifdef JEMALLOC_TINY +# if (LG_TINY_MIN == 2) + S2B_4(0) /* 4 */ + S2B_4(1) /* 8 */ +# define S2B_QMIN 1 +# else +# error "Unsupported LG_TINY_MIN" +# endif +# else + S2B_8(0) /* 8 */ +# define S2B_QMIN 0 +# endif + S2B_8(S2B_QMIN + 1) /* 16 */ + S2B_8(S2B_QMIN + 2) /* 24 */ + S2B_8(S2B_QMIN + 3) /* 32 */ + S2B_8(S2B_QMIN + 4) /* 40 */ + S2B_8(S2B_QMIN + 5) /* 48 */ + S2B_8(S2B_QMIN + 6) /* 56 */ + S2B_8(S2B_QMIN + 7) /* 64 */ + S2B_8(S2B_QMIN + 8) /* 72 */ + S2B_8(S2B_QMIN + 9) /* 80 */ + S2B_8(S2B_QMIN + 10) /* 88 */ + S2B_8(S2B_QMIN + 11) /* 96 */ + S2B_8(S2B_QMIN + 12) /* 104 */ + S2B_8(S2B_QMIN + 13) /* 112 */ + S2B_8(S2B_QMIN + 14) /* 120 */ + S2B_8(S2B_QMIN + 15) /* 128 */ +# define S2B_CMIN (S2B_QMIN + 16) +#endif +/****************************************/ + S2B_64(S2B_CMIN + 0) /* 192 */ + S2B_64(S2B_CMIN + 1) /* 256 */ + S2B_64(S2B_CMIN + 2) /* 320 */ + S2B_64(S2B_CMIN + 3) /* 384 */ + S2B_64(S2B_CMIN + 4) /* 448 */ + S2B_64(S2B_CMIN + 5) /* 512 */ +# define S2B_SMIN (S2B_CMIN + 6) + S2B_256(S2B_SMIN + 0) /* 768 */ + S2B_256(S2B_SMIN + 1) /* 1024 */ + S2B_256(S2B_SMIN + 2) /* 1280 */ + S2B_256(S2B_SMIN + 3) /* 1536 */ + S2B_256(S2B_SMIN + 4) /* 1792 */ + S2B_256(S2B_SMIN + 5) /* 2048 */ + S2B_256(S2B_SMIN + 6) /* 2304 */ + S2B_256(S2B_SMIN + 7) /* 2560 */ + S2B_256(S2B_SMIN + 8) /* 2816 */ + S2B_256(S2B_SMIN + 9) /* 3072 */ + S2B_256(S2B_SMIN + 10) /* 3328 */ + S2B_256(S2B_SMIN + 11) /* 3584 */ + S2B_256(S2B_SMIN + 12) /* 3840 */ +#if (STATIC_PAGE_SHIFT == 13) + S2B_256(S2B_SMIN + 13) /* 4096 */ + S2B_256(S2B_SMIN + 14) /* 4352 */ + S2B_256(S2B_SMIN + 15) /* 4608 */ + S2B_256(S2B_SMIN + 16) /* 4864 */ + S2B_256(S2B_SMIN + 17) /* 5120 */ + S2B_256(S2B_SMIN + 18) /* 5376 */ + S2B_256(S2B_SMIN + 19) /* 5632 */ + S2B_256(S2B_SMIN + 20) /* 5888 */ + S2B_256(S2B_SMIN + 21) /* 6144 */ + S2B_256(S2B_SMIN + 22) /* 6400 */ + S2B_256(S2B_SMIN + 23) /* 6656 */ + S2B_256(S2B_SMIN + 24) /* 6912 */ + S2B_256(S2B_SMIN + 25) /* 7168 */ + S2B_256(S2B_SMIN + 26) /* 7424 */ + S2B_256(S2B_SMIN + 27) /* 7680 */ + S2B_256(S2B_SMIN + 28) /* 7936 */ +#endif +}; +#undef S2B_1 +#undef S2B_2 +#undef S2B_4 +#undef S2B_8 +#undef S2B_16 +#undef S2B_32 +#undef S2B_64 +#undef S2B_128 +#undef S2B_256 +#undef S2B_QMIN +#undef S2B_CMIN +#undef S2B_SMIN + +/******************************************************************************/ +/* Function prototypes for non-inline static functions. */ + +static void arena_run_split(arena_t *arena, arena_run_t *run, size_t size, + bool large, bool zero); +static arena_chunk_t *arena_chunk_alloc(arena_t *arena); +static void arena_chunk_dealloc(arena_t *arena, arena_chunk_t *chunk); +static arena_run_t *arena_run_alloc(arena_t *arena, size_t size, bool large, + bool zero); +static void arena_purge(arena_t *arena); +static void arena_run_dalloc(arena_t *arena, arena_run_t *run, bool dirty); +static void arena_run_trim_head(arena_t *arena, arena_chunk_t *chunk, + arena_run_t *run, size_t oldsize, size_t newsize); +static void arena_run_trim_tail(arena_t *arena, arena_chunk_t *chunk, + arena_run_t *run, size_t oldsize, size_t newsize, bool dirty); +static arena_run_t *arena_bin_nonfull_run_get(arena_t *arena, arena_bin_t *bin); +static void *arena_bin_malloc_hard(arena_t *arena, arena_bin_t *bin); +static size_t arena_bin_run_size_calc(arena_bin_t *bin, size_t min_run_size); +static void arena_dalloc_bin_run(arena_t *arena, arena_chunk_t *chunk, + arena_run_t *run, arena_bin_t *bin); +static void arena_ralloc_large_shrink(arena_t *arena, arena_chunk_t *chunk, + void *ptr, size_t size, size_t oldsize); +static bool arena_ralloc_large_grow(arena_t *arena, arena_chunk_t *chunk, + void *ptr, size_t size, size_t oldsize); +static bool arena_ralloc_large(void *ptr, size_t size, size_t oldsize); +#ifdef JEMALLOC_TINY +static size_t pow2_ceil(size_t x); +#endif +static bool small_size2bin_init(void); +#ifdef JEMALLOC_DEBUG +static void small_size2bin_validate(void); +#endif +static bool small_size2bin_init_hard(void); + +/******************************************************************************/ + +static inline int +arena_run_comp(arena_chunk_map_t *a, arena_chunk_map_t *b) +{ + uintptr_t a_mapelm = (uintptr_t)a; + uintptr_t b_mapelm = (uintptr_t)b; + + assert(a != NULL); + assert(b != NULL); + + return ((a_mapelm > b_mapelm) - (a_mapelm < b_mapelm)); +} + +/* Generate red-black tree functions. */ +rb_gen(static JEMALLOC_ATTR(unused), arena_run_tree_, arena_run_tree_t, + arena_chunk_map_t, u.rb_link, arena_run_comp) + +static inline int +arena_avail_comp(arena_chunk_map_t *a, arena_chunk_map_t *b) +{ + int ret; + size_t a_size = a->bits & ~PAGE_MASK; + size_t b_size = b->bits & ~PAGE_MASK; + + assert((a->bits & CHUNK_MAP_KEY) == CHUNK_MAP_KEY || (a->bits & + CHUNK_MAP_DIRTY) == (b->bits & CHUNK_MAP_DIRTY)); + + ret = (a_size > b_size) - (a_size < b_size); + if (ret == 0) { + uintptr_t a_mapelm, b_mapelm; + + if ((a->bits & CHUNK_MAP_KEY) != CHUNK_MAP_KEY) + a_mapelm = (uintptr_t)a; + else { + /* + * Treat keys as though they are lower than anything + * else. + */ + a_mapelm = 0; + } + b_mapelm = (uintptr_t)b; + + ret = (a_mapelm > b_mapelm) - (a_mapelm < b_mapelm); + } + + return (ret); +} + +/* Generate red-black tree functions. */ +rb_gen(static JEMALLOC_ATTR(unused), arena_avail_tree_, arena_avail_tree_t, + arena_chunk_map_t, u.rb_link, arena_avail_comp) + +static inline void * +arena_run_reg_alloc(arena_run_t *run, arena_bin_t *bin) +{ + void *ret; + + assert(run->magic == ARENA_RUN_MAGIC); + assert(run->nfree > 0); + + run->nfree--; + ret = run->avail; + if (ret != NULL) { + run->avail = *(void **)ret; + /* Double free can cause assertion failure.*/ + assert(ret != NULL); + /* Write-after free can cause assertion failure. */ + assert((uintptr_t)ret >= (uintptr_t)run + + (uintptr_t)bin->reg0_offset); + assert((uintptr_t)ret < (uintptr_t)run->next); + assert(((uintptr_t)ret - ((uintptr_t)run + + (uintptr_t)bin->reg0_offset)) % (uintptr_t)bin->reg_size == + 0); + return (ret); + } + ret = run->next; + run->next = (void *)((uintptr_t)ret + (uintptr_t)bin->reg_size); + assert(ret != NULL); + return (ret); +} + +static inline void +arena_run_reg_dalloc(arena_run_t *run, void *ptr) +{ + + assert(run->nfree < run->bin->nregs); + /* Freeing an interior pointer can cause assertion failure. */ + assert(((uintptr_t)ptr - ((uintptr_t)run + + (uintptr_t)run->bin->reg0_offset)) % (uintptr_t)run->bin->reg_size + == 0); + + *(void **)ptr = run->avail; + run->avail = ptr; + run->nfree++; +} + +static void +arena_run_split(arena_t *arena, arena_run_t *run, size_t size, bool large, + bool zero) +{ + arena_chunk_t *chunk; + size_t old_ndirty, run_ind, total_pages, need_pages, rem_pages, i; + size_t flag_dirty; + arena_avail_tree_t *runs_avail; + + chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(run); + old_ndirty = chunk->ndirty; + run_ind = (unsigned)(((uintptr_t)run - (uintptr_t)chunk) + >> PAGE_SHIFT); + flag_dirty = chunk->map[run_ind].bits & CHUNK_MAP_DIRTY; + runs_avail = (flag_dirty != 0) ? &arena->runs_avail_dirty : + &arena->runs_avail_clean; + total_pages = (chunk->map[run_ind].bits & ~PAGE_MASK) >> + PAGE_SHIFT; + assert((chunk->map[run_ind+total_pages-1].bits & CHUNK_MAP_DIRTY) == + flag_dirty); + need_pages = (size >> PAGE_SHIFT); + assert(need_pages > 0); + assert(need_pages <= total_pages); + rem_pages = total_pages - need_pages; + + arena_avail_tree_remove(runs_avail, &chunk->map[run_ind]); + arena->nactive += need_pages; + + /* Keep track of trailing unused pages for later use. */ + if (rem_pages > 0) { + if (flag_dirty != 0) { + chunk->map[run_ind+need_pages].bits = (rem_pages << + PAGE_SHIFT) | CHUNK_MAP_DIRTY; + chunk->map[run_ind+total_pages-1].bits = (rem_pages << + PAGE_SHIFT) | CHUNK_MAP_DIRTY; + } else { + chunk->map[run_ind+need_pages].bits = (rem_pages << + PAGE_SHIFT) | (chunk->map[run_ind+need_pages].bits & + CHUNK_MAP_ZEROED); + chunk->map[run_ind+total_pages-1].bits = (rem_pages << + PAGE_SHIFT) | + (chunk->map[run_ind+total_pages-1].bits & + CHUNK_MAP_ZEROED); + } + arena_avail_tree_insert(runs_avail, + &chunk->map[run_ind+need_pages]); + } + + /* Update dirty page accounting. */ + if (flag_dirty != 0) { + chunk->ndirty -= need_pages; + arena->ndirty -= need_pages; + } + + /* + * Update the page map separately for large vs. small runs, since it is + * possible to avoid iteration for large mallocs. + */ + if (large) { + if (zero) { + if (flag_dirty == 0) { + /* + * The run is clean, so some pages may be + * zeroed (i.e. never before touched). + */ + for (i = 0; i < need_pages; i++) { + if ((chunk->map[run_ind + i].bits & + CHUNK_MAP_ZEROED) == 0) { + memset((void *)((uintptr_t) + chunk + ((run_ind + i) << + PAGE_SHIFT)), 0, + PAGE_SIZE); + } + } + } else { + /* + * The run is dirty, so all pages must be + * zeroed. + */ + memset((void *)((uintptr_t)chunk + (run_ind << + PAGE_SHIFT)), 0, (need_pages << + PAGE_SHIFT)); + } + } + + /* + * Set the last element first, in case the run only contains one + * page (i.e. both statements set the same element). + */ + chunk->map[run_ind+need_pages-1].bits = CHUNK_MAP_LARGE | + CHUNK_MAP_ALLOCATED | flag_dirty; + chunk->map[run_ind].bits = size | CHUNK_MAP_LARGE | +#ifdef JEMALLOC_PROF + CHUNK_MAP_CLASS_MASK | +#endif + CHUNK_MAP_ALLOCATED | flag_dirty; + } else { + assert(zero == false); + /* + * Propagate the dirty flag to the allocated small run, so that + * arena_dalloc_bin_run() has the ability to conditionally trim + * clean pages. + */ + chunk->map[run_ind].bits = CHUNK_MAP_ALLOCATED | flag_dirty; + for (i = 1; i < need_pages - 1; i++) { + chunk->map[run_ind + i].bits = (i << PAGE_SHIFT) + | CHUNK_MAP_ALLOCATED; + } + chunk->map[run_ind + need_pages - 1].bits = ((need_pages - 1) << + PAGE_SHIFT) | CHUNK_MAP_ALLOCATED | flag_dirty; + } +} + +static arena_chunk_t * +arena_chunk_alloc(arena_t *arena) +{ + arena_chunk_t *chunk; + size_t i; + + if (arena->spare != NULL) { + arena_avail_tree_t *runs_avail; + + chunk = arena->spare; + arena->spare = NULL; + + /* Insert the run into the appropriate runs_avail_* tree. */ + if ((chunk->map[arena_chunk_header_npages].bits & + CHUNK_MAP_DIRTY) == 0) + runs_avail = &arena->runs_avail_clean; + else + runs_avail = &arena->runs_avail_dirty; + arena_avail_tree_insert(runs_avail, + &chunk->map[arena_chunk_header_npages]); + } else { + bool zero; + size_t zeroed; + + zero = false; + malloc_mutex_unlock(&arena->lock); + chunk = (arena_chunk_t *)chunk_alloc(chunksize, &zero); + malloc_mutex_lock(&arena->lock); + if (chunk == NULL) + return (NULL); +#ifdef JEMALLOC_STATS + arena->stats.mapped += chunksize; +#endif + + chunk->arena = arena; + ql_elm_new(chunk, link_dirty); + chunk->dirtied = false; + + /* + * Claim that no pages are in use, since the header is merely + * overhead. + */ + chunk->ndirty = 0; + + /* + * Initialize the map to contain one maximal free untouched run. + * Mark the pages as zeroed iff chunk_alloc() returned a zeroed + * chunk. + */ + zeroed = zero ? CHUNK_MAP_ZEROED : 0; + for (i = 0; i < arena_chunk_header_npages; i++) + chunk->map[i].bits = 0; + chunk->map[i].bits = arena_maxclass | zeroed; + for (i++; i < chunk_npages-1; i++) + chunk->map[i].bits = zeroed; + chunk->map[chunk_npages-1].bits = arena_maxclass | zeroed; + + /* Insert the run into the runs_avail_clean tree. */ + arena_avail_tree_insert(&arena->runs_avail_clean, + &chunk->map[arena_chunk_header_npages]); + } + + return (chunk); +} + +static void +arena_chunk_dealloc(arena_t *arena, arena_chunk_t *chunk) +{ + arena_avail_tree_t *runs_avail; + + while (arena->spare != NULL) { + arena_chunk_t *spare = arena->spare; + + arena->spare = NULL; + if (spare->dirtied) { + ql_remove(&chunk->arena->chunks_dirty, spare, + link_dirty); + arena->ndirty -= spare->ndirty; + } + malloc_mutex_unlock(&arena->lock); + chunk_dealloc((void *)spare, chunksize); + malloc_mutex_lock(&arena->lock); +#ifdef JEMALLOC_STATS + arena->stats.mapped -= chunksize; +#endif + } + + /* + * Remove run from the appropriate runs_avail_* tree, so that the arena + * does not use it. + */ + if ((chunk->map[arena_chunk_header_npages].bits & + CHUNK_MAP_DIRTY) == 0) + runs_avail = &arena->runs_avail_clean; + else + runs_avail = &arena->runs_avail_dirty; + arena_avail_tree_remove(runs_avail, + &chunk->map[arena_chunk_header_npages]); + + arena->spare = chunk; +} + +static arena_run_t * +arena_run_alloc(arena_t *arena, size_t size, bool large, bool zero) +{ + arena_chunk_t *chunk; + arena_run_t *run; + arena_chunk_map_t *mapelm, key; + + assert(size <= arena_maxclass); + assert((size & PAGE_MASK) == 0); + + /* Search the arena's chunks for the lowest best fit. */ + key.bits = size | CHUNK_MAP_KEY; + mapelm = arena_avail_tree_nsearch(&arena->runs_avail_dirty, &key); + if (mapelm != NULL) { + arena_chunk_t *run_chunk = CHUNK_ADDR2BASE(mapelm); + size_t pageind = ((uintptr_t)mapelm - (uintptr_t)run_chunk->map) + / sizeof(arena_chunk_map_t); + + run = (arena_run_t *)((uintptr_t)run_chunk + (pageind << + PAGE_SHIFT)); + arena_run_split(arena, run, size, large, zero); + return (run); + } + mapelm = arena_avail_tree_nsearch(&arena->runs_avail_clean, &key); + if (mapelm != NULL) { + arena_chunk_t *run_chunk = CHUNK_ADDR2BASE(mapelm); + size_t pageind = ((uintptr_t)mapelm - (uintptr_t)run_chunk->map) + / sizeof(arena_chunk_map_t); + + run = (arena_run_t *)((uintptr_t)run_chunk + (pageind << + PAGE_SHIFT)); + arena_run_split(arena, run, size, large, zero); + return (run); + } + + /* + * No usable runs. Create a new chunk from which to allocate the run. + */ + chunk = arena_chunk_alloc(arena); + if (chunk != NULL) { + run = (arena_run_t *)((uintptr_t)chunk + + (arena_chunk_header_npages << PAGE_SHIFT)); + arena_run_split(arena, run, size, large, zero); + return (run); + } + + /* + * arena_chunk_alloc() failed, but another thread may have made + * sufficient memory available while this one dropped arena->lock in + * arena_chunk_alloc(), so search one more time. + */ + mapelm = arena_avail_tree_nsearch(&arena->runs_avail_dirty, &key); + if (mapelm != NULL) { + arena_chunk_t *run_chunk = CHUNK_ADDR2BASE(mapelm); + size_t pageind = ((uintptr_t)mapelm - (uintptr_t)run_chunk->map) + / sizeof(arena_chunk_map_t); + + run = (arena_run_t *)((uintptr_t)run_chunk + (pageind << + PAGE_SHIFT)); + arena_run_split(arena, run, size, large, zero); + return (run); + } + mapelm = arena_avail_tree_nsearch(&arena->runs_avail_clean, &key); + if (mapelm != NULL) { + arena_chunk_t *run_chunk = CHUNK_ADDR2BASE(mapelm); + size_t pageind = ((uintptr_t)mapelm - (uintptr_t)run_chunk->map) + / sizeof(arena_chunk_map_t); + + run = (arena_run_t *)((uintptr_t)run_chunk + (pageind << + PAGE_SHIFT)); + arena_run_split(arena, run, size, large, zero); + return (run); + } + + return (NULL); +} + +static inline void +arena_maybe_purge(arena_t *arena) +{ + + /* Enforce opt_lg_dirty_mult. */ + if (opt_lg_dirty_mult >= 0 && arena->ndirty > arena->npurgatory && + (arena->ndirty - arena->npurgatory) > chunk_npages && + (arena->nactive >> opt_lg_dirty_mult) < (arena->ndirty - + arena->npurgatory)) + arena_purge(arena); +} + +static inline void +arena_chunk_purge(arena_t *arena, arena_chunk_t *chunk) +{ + ql_head(arena_chunk_map_t) mapelms; + arena_chunk_map_t *mapelm; + size_t pageind, flag_zeroed; +#ifdef JEMALLOC_DEBUG + size_t ndirty; +#endif +#ifdef JEMALLOC_STATS + size_t nmadvise; +#endif + + ql_new(&mapelms); + + flag_zeroed = +#ifdef JEMALLOC_SWAP + swap_enabled ? 0 : +#endif + CHUNK_MAP_ZEROED; + + /* + * If chunk is the spare, temporarily re-allocate it, 1) so that its + * run is reinserted into runs_avail_dirty, and 2) so that it cannot be + * completely discarded by another thread while arena->lock is dropped + * by this thread. Note that the arena_run_dalloc() call will + * implicitly deallocate the chunk, so no explicit action is required + * in this function to deallocate the chunk. + * + * Note that once a chunk contains dirty pages, it cannot again contain + * a single run unless 1) it is a dirty run, or 2) this function purges + * dirty pages and causes the transition to a single clean run. Thus + * (chunk == arena->spare) is possible, but it is not possible for + * this function to be called on the spare unless it contains a dirty + * run. + */ + if (chunk == arena->spare) { + assert((chunk->map[arena_chunk_header_npages].bits & + CHUNK_MAP_DIRTY) != 0); + arena_chunk_alloc(arena); + } + + /* Temporarily allocate all free dirty runs within chunk. */ + for (pageind = arena_chunk_header_npages; pageind < chunk_npages;) { + mapelm = &chunk->map[pageind]; + if ((mapelm->bits & CHUNK_MAP_ALLOCATED) == 0) { + size_t npages; + + npages = mapelm->bits >> PAGE_SHIFT; + assert(pageind + npages <= chunk_npages); + if (mapelm->bits & CHUNK_MAP_DIRTY) { + size_t i; + + arena_avail_tree_remove( + &arena->runs_avail_dirty, mapelm); + + /* + * Update internal elements in the page map, so + * that CHUNK_MAP_ZEROED is properly set. + * madvise(..., MADV_DONTNEED) results in + * zero-filled pages for anonymous mappings, + * but not for file-backed mappings. + */ + mapelm->bits = (npages << PAGE_SHIFT) | + CHUNK_MAP_LARGE | CHUNK_MAP_ALLOCATED | + flag_zeroed; + for (i = 1; i < npages - 1; i++) { + chunk->map[pageind + i].bits = + flag_zeroed; + } + if (npages > 1) { + chunk->map[pageind + npages - 1].bits = + (npages << PAGE_SHIFT) | + CHUNK_MAP_LARGE | CHUNK_MAP_ALLOCATED | + flag_zeroed; + } + + arena->nactive += npages; + /* Append to list for later processing. */ + ql_elm_new(mapelm, u.ql_link); + ql_tail_insert(&mapelms, mapelm, u.ql_link); + } + + pageind += npages; + } else { + /* Skip allocated run. */ + if (mapelm->bits & CHUNK_MAP_LARGE) + pageind += mapelm->bits >> PAGE_SHIFT; + else { + arena_run_t *run = (arena_run_t *)((uintptr_t) + chunk + (uintptr_t)(pageind << PAGE_SHIFT)); + + assert((mapelm->bits >> PAGE_SHIFT) == 0); + assert(run->magic == ARENA_RUN_MAGIC); + pageind += run->bin->run_size >> PAGE_SHIFT; + } + } + } + assert(pageind == chunk_npages); + +#ifdef JEMALLOC_DEBUG + ndirty = chunk->ndirty; +#endif +#ifdef JEMALLOC_STATS + arena->stats.purged += chunk->ndirty; +#endif + arena->ndirty -= chunk->ndirty; + chunk->ndirty = 0; + ql_remove(&arena->chunks_dirty, chunk, link_dirty); + chunk->dirtied = false; + + malloc_mutex_unlock(&arena->lock); +#ifdef JEMALLOC_STATS + nmadvise = 0; +#endif + ql_foreach(mapelm, &mapelms, u.ql_link) { + size_t pageind = ((uintptr_t)mapelm - (uintptr_t)chunk->map) / + sizeof(arena_chunk_map_t); + size_t npages = mapelm->bits >> PAGE_SHIFT; + + assert(pageind + npages <= chunk_npages); +#ifdef JEMALLOC_DEBUG + assert(ndirty >= npages); + ndirty -= npages; +#endif + madvise((void *)((uintptr_t)chunk + (pageind << PAGE_SHIFT)), + (npages << PAGE_SHIFT), MADV_DONTNEED); +#ifdef JEMALLOC_STATS + nmadvise++; +#endif + } +#ifdef JEMALLOC_DEBUG + assert(ndirty == 0); +#endif + malloc_mutex_lock(&arena->lock); +#ifdef JEMALLOC_STATS + arena->stats.nmadvise += nmadvise; +#endif + + /* Deallocate runs. */ + for (mapelm = ql_first(&mapelms); mapelm != NULL; + mapelm = ql_first(&mapelms)) { + size_t pageind = ((uintptr_t)mapelm - (uintptr_t)chunk->map) / + sizeof(arena_chunk_map_t); + arena_run_t *run = (arena_run_t *)((uintptr_t)chunk + + (uintptr_t)(pageind << PAGE_SHIFT)); + + ql_remove(&mapelms, mapelm, u.ql_link); + arena_run_dalloc(arena, run, false); + } +} + +static void +arena_purge(arena_t *arena) +{ + arena_chunk_t *chunk; + size_t npurgatory; +#ifdef JEMALLOC_DEBUG + size_t ndirty = 0; + + ql_foreach(chunk, &arena->chunks_dirty, link_dirty) { + assert(chunk->dirtied); + ndirty += chunk->ndirty; + } + assert(ndirty == arena->ndirty); +#endif + assert(arena->ndirty > arena->npurgatory); + assert(arena->ndirty > chunk_npages); + assert((arena->nactive >> opt_lg_dirty_mult) < arena->ndirty); + +#ifdef JEMALLOC_STATS + arena->stats.npurge++; +#endif + + /* + * Compute the minimum number of pages that this thread should try to + * purge, and add the result to arena->npurgatory. This will keep + * multiple threads from racing to reduce ndirty below the threshold. + */ + npurgatory = (arena->ndirty - arena->npurgatory) - (arena->nactive >> + opt_lg_dirty_mult); + arena->npurgatory += npurgatory; + + while (npurgatory > 0) { + /* Get next chunk with dirty pages. */ + chunk = ql_first(&arena->chunks_dirty); + if (chunk == NULL) { + /* + * This thread was unable to purge as many pages as + * originally intended, due to races with other threads + * that either did some of the purging work, or re-used + * dirty pages. + */ + arena->npurgatory -= npurgatory; + return; + } + while (chunk->ndirty == 0) { + ql_remove(&arena->chunks_dirty, chunk, link_dirty); + chunk->dirtied = false; + chunk = ql_first(&arena->chunks_dirty); + if (chunk == NULL) { + /* Same logic as for above. */ + arena->npurgatory -= npurgatory; + return; + } + } + + if (chunk->ndirty > npurgatory) { + /* + * This thread will, at a minimum, purge all the dirty + * pages in chunk, so set npurgatory to reflect this + * thread's commitment to purge the pages. This tends + * to reduce the chances of the following scenario: + * + * 1) This thread sets arena->npurgatory such that + * (arena->ndirty - arena->npurgatory) is at the + * threshold. + * 2) This thread drops arena->lock. + * 3) Another thread causes one or more pages to be + * dirtied, and immediately determines that it must + * purge dirty pages. + * + * If this scenario *does* play out, that's okay, + * because all of the purging work being done really + * needs to happen. + */ + arena->npurgatory += chunk->ndirty - npurgatory; + npurgatory = chunk->ndirty; + } + + arena->npurgatory -= chunk->ndirty; + npurgatory -= chunk->ndirty; + arena_chunk_purge(arena, chunk); + } +} + +static void +arena_run_dalloc(arena_t *arena, arena_run_t *run, bool dirty) +{ + arena_chunk_t *chunk; + size_t size, run_ind, run_pages, flag_dirty; + arena_avail_tree_t *runs_avail; + + chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(run); + run_ind = (size_t)(((uintptr_t)run - (uintptr_t)chunk) + >> PAGE_SHIFT); + assert(run_ind >= arena_chunk_header_npages); + assert(run_ind < chunk_npages); + if ((chunk->map[run_ind].bits & CHUNK_MAP_LARGE) != 0) + size = chunk->map[run_ind].bits & ~PAGE_MASK; + else + size = run->bin->run_size; + run_pages = (size >> PAGE_SHIFT); + arena->nactive -= run_pages; + + /* + * The run is dirty if the caller claims to have dirtied it, as well as + * if it was already dirty before being allocated. + */ + if ((chunk->map[run_ind].bits & CHUNK_MAP_DIRTY) != 0) + dirty = true; + flag_dirty = dirty ? CHUNK_MAP_DIRTY : 0; + runs_avail = dirty ? &arena->runs_avail_dirty : + &arena->runs_avail_clean; + + /* Mark pages as unallocated in the chunk map. */ + if (dirty) { + chunk->map[run_ind].bits = size | flag_dirty; + chunk->map[run_ind+run_pages-1].bits = size | flag_dirty; + + chunk->ndirty += run_pages; + arena->ndirty += run_pages; + } else { + chunk->map[run_ind].bits = size | (chunk->map[run_ind].bits & + CHUNK_MAP_ZEROED); + chunk->map[run_ind+run_pages-1].bits = size | + (chunk->map[run_ind+run_pages-1].bits & CHUNK_MAP_ZEROED); + } + + /* Try to coalesce forward. */ + if (run_ind + run_pages < chunk_npages && + (chunk->map[run_ind+run_pages].bits & CHUNK_MAP_ALLOCATED) == 0 && + (chunk->map[run_ind+run_pages].bits & CHUNK_MAP_DIRTY) == + flag_dirty) { + size_t nrun_size = chunk->map[run_ind+run_pages].bits & + ~PAGE_MASK; + + /* + * Remove successor from runs_avail; the coalesced run is + * inserted later. + */ + arena_avail_tree_remove(runs_avail, + &chunk->map[run_ind+run_pages]); + + size += nrun_size; + run_pages = size >> PAGE_SHIFT; + + assert((chunk->map[run_ind+run_pages-1].bits & ~PAGE_MASK) + == nrun_size); + chunk->map[run_ind].bits = size | (chunk->map[run_ind].bits & + CHUNK_MAP_FLAGS_MASK); + chunk->map[run_ind+run_pages-1].bits = size | + (chunk->map[run_ind+run_pages-1].bits & + CHUNK_MAP_FLAGS_MASK); + } + + /* Try to coalesce backward. */ + if (run_ind > arena_chunk_header_npages && (chunk->map[run_ind-1].bits & + CHUNK_MAP_ALLOCATED) == 0 && (chunk->map[run_ind-1].bits & + CHUNK_MAP_DIRTY) == flag_dirty) { + size_t prun_size = chunk->map[run_ind-1].bits & ~PAGE_MASK; + + run_ind -= prun_size >> PAGE_SHIFT; + + /* + * Remove predecessor from runs_avail; the coalesced run is + * inserted later. + */ + arena_avail_tree_remove(runs_avail, &chunk->map[run_ind]); + + size += prun_size; + run_pages = size >> PAGE_SHIFT; + + assert((chunk->map[run_ind].bits & ~PAGE_MASK) == prun_size); + chunk->map[run_ind].bits = size | (chunk->map[run_ind].bits & + CHUNK_MAP_FLAGS_MASK); + chunk->map[run_ind+run_pages-1].bits = size | + (chunk->map[run_ind+run_pages-1].bits & + CHUNK_MAP_FLAGS_MASK); + } + + /* Insert into runs_avail, now that coalescing is complete. */ + arena_avail_tree_insert(runs_avail, &chunk->map[run_ind]); + + /* + * Deallocate chunk if it is now completely unused. The bit + * manipulation checks whether the first run is unallocated and extends + * to the end of the chunk. + */ + if ((chunk->map[arena_chunk_header_npages].bits & (~PAGE_MASK | + CHUNK_MAP_ALLOCATED)) == arena_maxclass) + arena_chunk_dealloc(arena, chunk); + + /* + * It is okay to do dirty page processing even if the chunk was + * deallocated above, since in that case it is the spare. Waiting + * until after possible chunk deallocation to do dirty processing + * allows for an old spare to be fully deallocated, thus decreasing the + * chances of spuriously crossing the dirty page purging threshold. + */ + if (dirty) { + if (chunk->dirtied == false) { + ql_tail_insert(&arena->chunks_dirty, chunk, link_dirty); + chunk->dirtied = true; + } + arena_maybe_purge(arena); + } +} + +static void +arena_run_trim_head(arena_t *arena, arena_chunk_t *chunk, arena_run_t *run, + size_t oldsize, size_t newsize) +{ + size_t pageind = ((uintptr_t)run - (uintptr_t)chunk) >> PAGE_SHIFT; + size_t head_npages = (oldsize - newsize) >> PAGE_SHIFT; + size_t flags = chunk->map[pageind].bits & CHUNK_MAP_FLAGS_MASK; + + assert(oldsize > newsize); + + /* + * Update the chunk map so that arena_run_dalloc() can treat the + * leading run as separately allocated. + */ + assert(chunk->map[pageind].bits & CHUNK_MAP_LARGE); + assert(chunk->map[pageind].bits & CHUNK_MAP_ALLOCATED); + chunk->map[pageind].bits = (oldsize - newsize) | flags; + chunk->map[pageind+head_npages].bits = newsize | flags; + + arena_run_dalloc(arena, run, false); +} + +static void +arena_run_trim_tail(arena_t *arena, arena_chunk_t *chunk, arena_run_t *run, + size_t oldsize, size_t newsize, bool dirty) +{ + size_t pageind = ((uintptr_t)run - (uintptr_t)chunk) >> PAGE_SHIFT; + size_t npages = newsize >> PAGE_SHIFT; + size_t flags = chunk->map[pageind].bits & CHUNK_MAP_FLAGS_MASK; + + assert(oldsize > newsize); + + /* + * Update the chunk map so that arena_run_dalloc() can treat the + * trailing run as separately allocated. + */ + assert(chunk->map[pageind].bits & CHUNK_MAP_LARGE); + assert(chunk->map[pageind].bits & CHUNK_MAP_ALLOCATED); + chunk->map[pageind].bits = newsize | flags; + chunk->map[pageind+npages-1].bits = newsize | flags; + chunk->map[pageind+npages].bits = (oldsize - newsize) | flags; + + arena_run_dalloc(arena, (arena_run_t *)((uintptr_t)run + newsize), + dirty); +} + +static arena_run_t * +arena_bin_nonfull_run_get(arena_t *arena, arena_bin_t *bin) +{ + arena_chunk_map_t *mapelm; + arena_run_t *run; + + /* Look for a usable run. */ + mapelm = arena_run_tree_first(&bin->runs); + if (mapelm != NULL) { + arena_chunk_t *chunk; + size_t pageind; + + /* run is guaranteed to have available space. */ + arena_run_tree_remove(&bin->runs, mapelm); + + chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(mapelm); + pageind = (((uintptr_t)mapelm - (uintptr_t)chunk->map) / + sizeof(arena_chunk_map_t)); + run = (arena_run_t *)((uintptr_t)chunk + (uintptr_t)((pageind - + (mapelm->bits >> PAGE_SHIFT)) + << PAGE_SHIFT)); +#ifdef JEMALLOC_STATS + bin->stats.reruns++; +#endif + return (run); + } + /* No existing runs have any space available. */ + + /* Allocate a new run. */ + malloc_mutex_unlock(&bin->lock); + /******************************/ + malloc_mutex_lock(&arena->lock); + run = arena_run_alloc(arena, bin->run_size, false, false); + if (run != NULL) { + /* Initialize run internals. */ + run->bin = bin; + run->avail = NULL; + run->next = (void *)(((uintptr_t)run) + + (uintptr_t)bin->reg0_offset); + run->nfree = bin->nregs; +#ifdef JEMALLOC_DEBUG + run->magic = ARENA_RUN_MAGIC; +#endif + } + malloc_mutex_unlock(&arena->lock); + /********************************/ + malloc_mutex_lock(&bin->lock); + if (run != NULL) { +#ifdef JEMALLOC_STATS + bin->stats.nruns++; + bin->stats.curruns++; + if (bin->stats.curruns > bin->stats.highruns) + bin->stats.highruns = bin->stats.curruns; +#endif + return (run); + } + + /* + * arena_run_alloc() failed, but another thread may have made + * sufficient memory available while this one dopped bin->lock above, + * so search one more time. + */ + mapelm = arena_run_tree_first(&bin->runs); + if (mapelm != NULL) { + arena_chunk_t *chunk; + size_t pageind; + + /* run is guaranteed to have available space. */ + arena_run_tree_remove(&bin->runs, mapelm); + + chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(mapelm); + pageind = (((uintptr_t)mapelm - (uintptr_t)chunk->map) / + sizeof(arena_chunk_map_t)); + run = (arena_run_t *)((uintptr_t)chunk + (uintptr_t)((pageind - + (mapelm->bits >> PAGE_SHIFT)) + << PAGE_SHIFT)); +#ifdef JEMALLOC_STATS + bin->stats.reruns++; +#endif + return (run); + } + + return (NULL); +} + +/* Re-fill bin->runcur, then call arena_run_reg_alloc(). */ +static void * +arena_bin_malloc_hard(arena_t *arena, arena_bin_t *bin) +{ + void *ret; + arena_run_t *run; + + bin->runcur = NULL; + run = arena_bin_nonfull_run_get(arena, bin); + if (bin->runcur != NULL && bin->runcur->nfree > 0) { + /* + * Another thread updated runcur while this one ran without the + * bin lock in arena_bin_nonfull_run_get(). + */ + assert(bin->runcur->magic == ARENA_RUN_MAGIC); + assert(bin->runcur->nfree > 0); + ret = arena_run_reg_alloc(bin->runcur, bin); + if (run != NULL) { + malloc_mutex_unlock(&bin->lock); + malloc_mutex_lock(&arena->lock); + arena_run_dalloc(arena, run, false); + malloc_mutex_unlock(&arena->lock); + malloc_mutex_lock(&bin->lock); + } + return (ret); + } + + if (run == NULL) + return (NULL); + + bin->runcur = run; + + assert(bin->runcur->magic == ARENA_RUN_MAGIC); + assert(bin->runcur->nfree > 0); + + return (arena_run_reg_alloc(bin->runcur, bin)); +} + +#ifdef JEMALLOC_PROF +void +arena_prof_accum(arena_t *arena, uint64_t accumbytes) +{ + + if (prof_interval != 0) { + arena->prof_accumbytes += accumbytes; + if (arena->prof_accumbytes >= prof_interval) { + prof_idump(); + arena->prof_accumbytes -= prof_interval; + } + } +} +#endif + +#ifdef JEMALLOC_TCACHE +void +arena_tcache_fill_small(arena_t *arena, tcache_bin_t *tbin, size_t binind +# ifdef JEMALLOC_PROF + , uint64_t prof_accumbytes +# endif + ) +{ + unsigned i, nfill; + arena_bin_t *bin; + arena_run_t *run; + void *ptr; + + assert(tbin->ncached == 0); + +#ifdef JEMALLOC_PROF + malloc_mutex_lock(&arena->lock); + arena_prof_accum(arena, prof_accumbytes); + malloc_mutex_unlock(&arena->lock); +#endif + bin = &arena->bins[binind]; + malloc_mutex_lock(&bin->lock); + for (i = 0, nfill = (tbin->ncached_max >> 1); i < nfill; i++) { + if ((run = bin->runcur) != NULL && run->nfree > 0) + ptr = arena_run_reg_alloc(run, bin); + else + ptr = arena_bin_malloc_hard(arena, bin); + if (ptr == NULL) + break; + *(void **)ptr = tbin->avail; + tbin->avail = ptr; + } +#ifdef JEMALLOC_STATS + bin->stats.allocated += (i - tbin->ncached) * bin->reg_size; + bin->stats.nmalloc += i; + bin->stats.nrequests += tbin->tstats.nrequests; + bin->stats.nfills++; + tbin->tstats.nrequests = 0; +#endif + malloc_mutex_unlock(&bin->lock); + tbin->ncached = i; + if (tbin->ncached > tbin->high_water) + tbin->high_water = tbin->ncached; +} +#endif + +/* + * Calculate bin->run_size such that it meets the following constraints: + * + * *) bin->run_size >= min_run_size + * *) bin->run_size <= arena_maxclass + * *) run header overhead <= RUN_MAX_OVRHD (or header overhead relaxed). + * *) run header size < PAGE_SIZE + * + * bin->nregs and bin->reg0_offset are also calculated here, since these + * settings are all interdependent. + */ +static size_t +arena_bin_run_size_calc(arena_bin_t *bin, size_t min_run_size) +{ + size_t try_run_size, good_run_size; + uint32_t try_nregs, good_nregs; + uint32_t try_hdr_size, good_hdr_size; +#ifdef JEMALLOC_PROF + uint32_t try_cnt0_offset, good_cnt0_offset; +#endif + uint32_t try_reg0_offset, good_reg0_offset; + + assert(min_run_size >= PAGE_SIZE); + assert(min_run_size <= arena_maxclass); + + /* + * Calculate known-valid settings before entering the run_size + * expansion loop, so that the first part of the loop always copies + * valid settings. + * + * The do..while loop iteratively reduces the number of regions until + * the run header and the regions no longer overlap. A closed formula + * would be quite messy, since there is an interdependency between the + * header's mask length and the number of regions. + */ + try_run_size = min_run_size; + try_nregs = ((try_run_size - sizeof(arena_run_t)) / bin->reg_size) + + 1; /* Counter-act try_nregs-- in loop. */ + do { + try_nregs--; + try_hdr_size = sizeof(arena_run_t); +#ifdef JEMALLOC_PROF + if (opt_prof && prof_promote == false) { + /* Pad to a quantum boundary. */ + try_hdr_size = QUANTUM_CEILING(try_hdr_size); + try_cnt0_offset = try_hdr_size; + /* Add space for one (prof_thr_cnt_t *) per region. */ + try_hdr_size += try_nregs * sizeof(prof_thr_cnt_t *); + } else + try_cnt0_offset = 0; +#endif + try_reg0_offset = try_run_size - (try_nregs * bin->reg_size); + } while (try_hdr_size > try_reg0_offset); + + /* run_size expansion loop. */ + do { + /* + * Copy valid settings before trying more aggressive settings. + */ + good_run_size = try_run_size; + good_nregs = try_nregs; + good_hdr_size = try_hdr_size; +#ifdef JEMALLOC_PROF + good_cnt0_offset = try_cnt0_offset; +#endif + good_reg0_offset = try_reg0_offset; + + /* Try more aggressive settings. */ + try_run_size += PAGE_SIZE; + try_nregs = ((try_run_size - sizeof(arena_run_t)) / + bin->reg_size) + 1; /* Counter-act try_nregs-- in loop. */ + do { + try_nregs--; + try_hdr_size = sizeof(arena_run_t); +#ifdef JEMALLOC_PROF + if (opt_prof && prof_promote == false) { + /* Pad to a quantum boundary. */ + try_hdr_size = QUANTUM_CEILING(try_hdr_size); + try_cnt0_offset = try_hdr_size; + /* + * Add space for one (prof_thr_cnt_t *) per + * region. + */ + try_hdr_size += try_nregs * + sizeof(prof_thr_cnt_t *); + } +#endif + try_reg0_offset = try_run_size - (try_nregs * + bin->reg_size); + } while (try_hdr_size > try_reg0_offset); + } while (try_run_size <= arena_maxclass + && try_run_size <= arena_maxclass + && RUN_MAX_OVRHD * (bin->reg_size << 3) > RUN_MAX_OVRHD_RELAX + && (try_reg0_offset << RUN_BFP) > RUN_MAX_OVRHD * try_run_size + && try_hdr_size < PAGE_SIZE); + + assert(good_hdr_size <= good_reg0_offset); + + /* Copy final settings. */ + bin->run_size = good_run_size; + bin->nregs = good_nregs; +#ifdef JEMALLOC_PROF + bin->cnt0_offset = good_cnt0_offset; +#endif + bin->reg0_offset = good_reg0_offset; + + return (good_run_size); +} + +void * +arena_malloc_small(arena_t *arena, size_t size, bool zero) +{ + void *ret; + arena_bin_t *bin; + arena_run_t *run; + size_t binind; + + binind = small_size2bin[size]; + assert(binind < nbins); + bin = &arena->bins[binind]; + size = bin->reg_size; + + malloc_mutex_lock(&bin->lock); + if ((run = bin->runcur) != NULL && run->nfree > 0) + ret = arena_run_reg_alloc(run, bin); + else + ret = arena_bin_malloc_hard(arena, bin); + + if (ret == NULL) { + malloc_mutex_unlock(&bin->lock); + return (NULL); + } + +#ifdef JEMALLOC_STATS + bin->stats.allocated += size; + bin->stats.nmalloc++; + bin->stats.nrequests++; +#endif + malloc_mutex_unlock(&bin->lock); +#ifdef JEMALLOC_PROF + if (isthreaded == false) { + malloc_mutex_lock(&arena->lock); + arena_prof_accum(arena, size); + malloc_mutex_unlock(&arena->lock); + } +#endif + + if (zero == false) { +#ifdef JEMALLOC_FILL + if (opt_junk) + memset(ret, 0xa5, size); + else if (opt_zero) + memset(ret, 0, size); +#endif + } else + memset(ret, 0, size); + + return (ret); +} + +void * +arena_malloc_large(arena_t *arena, size_t size, bool zero) +{ + void *ret; + + /* Large allocation. */ + size = PAGE_CEILING(size); + malloc_mutex_lock(&arena->lock); + ret = (void *)arena_run_alloc(arena, size, true, zero); + if (ret == NULL) { + malloc_mutex_unlock(&arena->lock); + return (NULL); + } +#ifdef JEMALLOC_STATS + arena->stats.nmalloc_large++; + arena->stats.nrequests_large++; + arena->stats.allocated_large += size; + arena->stats.lstats[(size >> PAGE_SHIFT) - 1].nmalloc++; + arena->stats.lstats[(size >> PAGE_SHIFT) - 1].nrequests++; + arena->stats.lstats[(size >> PAGE_SHIFT) - 1].curruns++; + if (arena->stats.lstats[(size >> PAGE_SHIFT) - 1].curruns > + arena->stats.lstats[(size >> PAGE_SHIFT) - 1].highruns) { + arena->stats.lstats[(size >> PAGE_SHIFT) - 1].highruns = + arena->stats.lstats[(size >> PAGE_SHIFT) - 1].curruns; + } +#endif +#ifdef JEMALLOC_PROF + arena_prof_accum(arena, size); +#endif + malloc_mutex_unlock(&arena->lock); + + if (zero == false) { +#ifdef JEMALLOC_FILL + if (opt_junk) + memset(ret, 0xa5, size); + else if (opt_zero) + memset(ret, 0, size); +#endif + } + + return (ret); +} + +void * +arena_malloc(size_t size, bool zero) +{ + + assert(size != 0); + assert(QUANTUM_CEILING(size) <= arena_maxclass); + + if (size <= small_maxclass) { +#ifdef JEMALLOC_TCACHE + tcache_t *tcache; + + if ((tcache = tcache_get()) != NULL) + return (tcache_alloc_small(tcache, size, zero)); + else + +#endif + return (arena_malloc_small(choose_arena(), size, zero)); + } else { +#ifdef JEMALLOC_TCACHE + if (size <= tcache_maxclass) { + tcache_t *tcache; + + if ((tcache = tcache_get()) != NULL) + return (tcache_alloc_large(tcache, size, zero)); + else { + return (arena_malloc_large(choose_arena(), + size, zero)); + } + } else +#endif + return (arena_malloc_large(choose_arena(), size, zero)); + } +} + +/* Only handles large allocations that require more than page alignment. */ +void * +arena_palloc(arena_t *arena, size_t alignment, size_t size, size_t alloc_size) +{ + void *ret; + size_t offset; + arena_chunk_t *chunk; + + assert((size & PAGE_MASK) == 0); + assert((alignment & PAGE_MASK) == 0); + + malloc_mutex_lock(&arena->lock); + ret = (void *)arena_run_alloc(arena, alloc_size, true, false); + if (ret == NULL) { + malloc_mutex_unlock(&arena->lock); + return (NULL); + } + + chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ret); + + offset = (uintptr_t)ret & (alignment - 1); + assert((offset & PAGE_MASK) == 0); + assert(offset < alloc_size); + if (offset == 0) + arena_run_trim_tail(arena, chunk, ret, alloc_size, size, false); + else { + size_t leadsize, trailsize; + + leadsize = alignment - offset; + if (leadsize > 0) { + arena_run_trim_head(arena, chunk, ret, alloc_size, + alloc_size - leadsize); + ret = (void *)((uintptr_t)ret + leadsize); + } + + trailsize = alloc_size - leadsize - size; + if (trailsize != 0) { + /* Trim trailing space. */ + assert(trailsize < alloc_size); + arena_run_trim_tail(arena, chunk, ret, size + trailsize, + size, false); + } + } + +#ifdef JEMALLOC_STATS + arena->stats.nmalloc_large++; + arena->stats.nrequests_large++; + arena->stats.allocated_large += size; + arena->stats.lstats[(size >> PAGE_SHIFT) - 1].nmalloc++; + arena->stats.lstats[(size >> PAGE_SHIFT) - 1].nrequests++; + arena->stats.lstats[(size >> PAGE_SHIFT) - 1].curruns++; + if (arena->stats.lstats[(size >> PAGE_SHIFT) - 1].curruns > + arena->stats.lstats[(size >> PAGE_SHIFT) - 1].highruns) { + arena->stats.lstats[(size >> PAGE_SHIFT) - 1].highruns = + arena->stats.lstats[(size >> PAGE_SHIFT) - 1].curruns; + } +#endif + malloc_mutex_unlock(&arena->lock); + +#ifdef JEMALLOC_FILL + if (opt_junk) + memset(ret, 0xa5, size); + else if (opt_zero) + memset(ret, 0, size); +#endif + return (ret); +} + +/* Return the size of the allocation pointed to by ptr. */ +size_t +arena_salloc(const void *ptr) +{ + size_t ret; + arena_chunk_t *chunk; + size_t pageind, mapbits; + + assert(ptr != NULL); + assert(CHUNK_ADDR2BASE(ptr) != ptr); + + chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); + pageind = (((uintptr_t)ptr - (uintptr_t)chunk) >> PAGE_SHIFT); + mapbits = chunk->map[pageind].bits; + assert((mapbits & CHUNK_MAP_ALLOCATED) != 0); + if ((mapbits & CHUNK_MAP_LARGE) == 0) { + arena_run_t *run = (arena_run_t *)((uintptr_t)chunk + + (uintptr_t)((pageind - (mapbits >> PAGE_SHIFT)) << + PAGE_SHIFT)); + assert(run->magic == ARENA_RUN_MAGIC); + assert(((uintptr_t)ptr - ((uintptr_t)run + + (uintptr_t)run->bin->reg0_offset)) % run->bin->reg_size == + 0); + ret = run->bin->reg_size; + } else { + assert(((uintptr_t)ptr & PAGE_MASK) == 0); + ret = mapbits & ~PAGE_MASK; + assert(ret != 0); + } + + return (ret); +} + +#ifdef JEMALLOC_PROF +void +arena_prof_promoted(const void *ptr, size_t size) +{ + arena_chunk_t *chunk; + size_t pageind, binind; + + assert(ptr != NULL); + assert(CHUNK_ADDR2BASE(ptr) != ptr); + assert(isalloc(ptr) == PAGE_SIZE); + + chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); + pageind = (((uintptr_t)ptr - (uintptr_t)chunk) >> PAGE_SHIFT); + binind = small_size2bin[size]; + assert(binind < nbins); + chunk->map[pageind].bits = (chunk->map[pageind].bits & + ~CHUNK_MAP_CLASS_MASK) | (binind << CHUNK_MAP_CLASS_SHIFT); +} + +size_t +arena_salloc_demote(const void *ptr) +{ + size_t ret; + arena_chunk_t *chunk; + size_t pageind, mapbits; + + assert(ptr != NULL); + assert(CHUNK_ADDR2BASE(ptr) != ptr); + + chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); + pageind = (((uintptr_t)ptr - (uintptr_t)chunk) >> PAGE_SHIFT); + mapbits = chunk->map[pageind].bits; + assert((mapbits & CHUNK_MAP_ALLOCATED) != 0); + if ((mapbits & CHUNK_MAP_LARGE) == 0) { + arena_run_t *run = (arena_run_t *)((uintptr_t)chunk + + (uintptr_t)((pageind - (mapbits >> PAGE_SHIFT)) << + PAGE_SHIFT)); + assert(run->magic == ARENA_RUN_MAGIC); + assert(((uintptr_t)ptr - ((uintptr_t)run + + (uintptr_t)run->bin->reg0_offset)) % run->bin->reg_size == + 0); + ret = run->bin->reg_size; + } else { + assert(((uintptr_t)ptr & PAGE_MASK) == 0); + ret = mapbits & ~PAGE_MASK; + if (prof_promote && ret == PAGE_SIZE && (mapbits & + CHUNK_MAP_CLASS_MASK) != CHUNK_MAP_CLASS_MASK) { + size_t binind = ((mapbits & CHUNK_MAP_CLASS_MASK) >> + CHUNK_MAP_CLASS_SHIFT); + assert(binind < nbins); + ret = chunk->arena->bins[binind].reg_size; + } + assert(ret != 0); + } + + return (ret); +} + +static inline unsigned +arena_run_regind(arena_run_t *run, arena_bin_t *bin, const void *ptr, + size_t size) +{ + unsigned shift, diff, regind; + + assert(run->magic == ARENA_RUN_MAGIC); + + /* + * Avoid doing division with a variable divisor if possible. Using + * actual division here can reduce allocator throughput by over 20%! + */ + diff = (unsigned)((uintptr_t)ptr - (uintptr_t)run - bin->reg0_offset); + + /* Rescale (factor powers of 2 out of the numerator and denominator). */ + shift = ffs(size) - 1; + diff >>= shift; + size >>= shift; + + if (size == 1) { + /* The divisor was a power of 2. */ + regind = diff; + } else { + /* + * To divide by a number D that is not a power of two we + * multiply by (2^21 / D) and then right shift by 21 positions. + * + * X / D + * + * becomes + * + * (X * size_invs[D - 3]) >> SIZE_INV_SHIFT + * + * We can omit the first three elements, because we never + * divide by 0, and 1 and 2 are both powers of two, which are + * handled above. + */ +#define SIZE_INV_SHIFT 21 +#define SIZE_INV(s) (((1U << SIZE_INV_SHIFT) / (s)) + 1) + static const unsigned size_invs[] = { + SIZE_INV(3), + SIZE_INV(4), SIZE_INV(5), SIZE_INV(6), SIZE_INV(7), + SIZE_INV(8), SIZE_INV(9), SIZE_INV(10), SIZE_INV(11), + SIZE_INV(12), SIZE_INV(13), SIZE_INV(14), SIZE_INV(15), + SIZE_INV(16), SIZE_INV(17), SIZE_INV(18), SIZE_INV(19), + SIZE_INV(20), SIZE_INV(21), SIZE_INV(22), SIZE_INV(23), + SIZE_INV(24), SIZE_INV(25), SIZE_INV(26), SIZE_INV(27), + SIZE_INV(28), SIZE_INV(29), SIZE_INV(30), SIZE_INV(31) + }; + + if (size <= ((sizeof(size_invs) / sizeof(unsigned)) + 2)) + regind = (diff * size_invs[size - 3]) >> SIZE_INV_SHIFT; + else + regind = diff / size; +#undef SIZE_INV +#undef SIZE_INV_SHIFT + } + assert(diff == regind * size); + assert(regind < bin->nregs); + + return (regind); +} + +prof_thr_cnt_t * +arena_prof_cnt_get(const void *ptr) +{ + prof_thr_cnt_t *ret; + arena_chunk_t *chunk; + size_t pageind, mapbits; + + assert(ptr != NULL); + assert(CHUNK_ADDR2BASE(ptr) != ptr); + + chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); + pageind = (((uintptr_t)ptr - (uintptr_t)chunk) >> PAGE_SHIFT); + mapbits = chunk->map[pageind].bits; + assert((mapbits & CHUNK_MAP_ALLOCATED) != 0); + if ((mapbits & CHUNK_MAP_LARGE) == 0) { + if (prof_promote) + ret = (prof_thr_cnt_t *)(uintptr_t)1U; + else { + arena_run_t *run = (arena_run_t *)((uintptr_t)chunk + + (uintptr_t)((pageind - (mapbits >> PAGE_SHIFT)) << + PAGE_SHIFT)); + arena_bin_t *bin = run->bin; + unsigned regind; + + assert(run->magic == ARENA_RUN_MAGIC); + regind = arena_run_regind(run, bin, ptr, bin->reg_size); + ret = *(prof_thr_cnt_t **)((uintptr_t)run + + bin->cnt0_offset + (regind * + sizeof(prof_thr_cnt_t *))); + } + } else + ret = chunk->map[pageind].prof_cnt; + + return (ret); +} + +void +arena_prof_cnt_set(const void *ptr, prof_thr_cnt_t *cnt) +{ + arena_chunk_t *chunk; + size_t pageind, mapbits; + + assert(ptr != NULL); + assert(CHUNK_ADDR2BASE(ptr) != ptr); + + chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); + pageind = (((uintptr_t)ptr - (uintptr_t)chunk) >> PAGE_SHIFT); + mapbits = chunk->map[pageind].bits; + assert((mapbits & CHUNK_MAP_ALLOCATED) != 0); + if ((mapbits & CHUNK_MAP_LARGE) == 0) { + if (prof_promote == false) { + arena_run_t *run = (arena_run_t *)((uintptr_t)chunk + + (uintptr_t)((pageind - (mapbits >> PAGE_SHIFT)) << + PAGE_SHIFT)); + arena_bin_t *bin = run->bin; + unsigned regind; + + assert(run->magic == ARENA_RUN_MAGIC); + regind = arena_run_regind(run, bin, ptr, bin->reg_size); + + *((prof_thr_cnt_t **)((uintptr_t)run + bin->cnt0_offset + + (regind * sizeof(prof_thr_cnt_t *)))) = cnt; + } else + assert((uintptr_t)cnt == (uintptr_t)1U); + } else + chunk->map[pageind].prof_cnt = cnt; +} +#endif + +static void +arena_dalloc_bin_run(arena_t *arena, arena_chunk_t *chunk, arena_run_t *run, + arena_bin_t *bin) +{ + size_t npages, run_ind, past; + + /* Dissociate run from bin. */ + if (run == bin->runcur) + bin->runcur = NULL; + else if (bin->nregs != 1) { + size_t run_pageind = (((uintptr_t)run - (uintptr_t)chunk)) >> + PAGE_SHIFT; + arena_chunk_map_t *run_mapelm = &chunk->map[run_pageind]; + /* + * This block's conditional is necessary because if the run + * only contains one region, then it never gets inserted into + * the non-full runs tree. + */ + arena_run_tree_remove(&bin->runs, run_mapelm); + } + + malloc_mutex_unlock(&bin->lock); + /******************************/ + npages = bin->run_size >> PAGE_SHIFT; + run_ind = (size_t)(((uintptr_t)run - (uintptr_t)chunk) >> PAGE_SHIFT); + past = (size_t)(((uintptr_t)run->next - (uintptr_t)1U - + (uintptr_t)chunk) >> PAGE_SHIFT) + 1; + malloc_mutex_lock(&arena->lock); + + /* + * If the run was originally clean, and some pages were never touched, + * trim the clean pages before deallocating the dirty portion of the + * run. + */ + if ((chunk->map[run_ind].bits & CHUNK_MAP_DIRTY) == 0 && past - run_ind + < npages) { + /* + * Trim clean pages. Convert to large run beforehand. Set the + * last map element first, in case this is a one-page run. + */ + chunk->map[run_ind+npages-1].bits = CHUNK_MAP_LARGE | + (chunk->map[run_ind].bits & CHUNK_MAP_FLAGS_MASK); + chunk->map[run_ind].bits = bin->run_size | CHUNK_MAP_LARGE | + (chunk->map[run_ind].bits & CHUNK_MAP_FLAGS_MASK); + arena_run_trim_tail(arena, chunk, run, (npages << PAGE_SHIFT), + ((npages - (past - run_ind)) << PAGE_SHIFT), false); + npages = past - run_ind; + } +#ifdef JEMALLOC_DEBUG + run->magic = 0; +#endif + arena_run_dalloc(arena, run, true); + malloc_mutex_unlock(&arena->lock); + /****************************/ + malloc_mutex_lock(&bin->lock); +#ifdef JEMALLOC_STATS + bin->stats.curruns--; +#endif +} + +void +arena_dalloc_bin(arena_t *arena, arena_chunk_t *chunk, void *ptr, + arena_chunk_map_t *mapelm) +{ + size_t pageind; + arena_run_t *run; + arena_bin_t *bin; +#if (defined(JEMALLOC_FILL) || defined(JEMALLOC_STATS)) + size_t size; +#endif + + pageind = (((uintptr_t)ptr - (uintptr_t)chunk) >> PAGE_SHIFT); + run = (arena_run_t *)((uintptr_t)chunk + (uintptr_t)((pageind - + (mapelm->bits >> PAGE_SHIFT)) << PAGE_SHIFT)); + assert(run->magic == ARENA_RUN_MAGIC); + bin = run->bin; +#if (defined(JEMALLOC_FILL) || defined(JEMALLOC_STATS)) + size = bin->reg_size; +#endif + +#ifdef JEMALLOC_FILL + if (opt_junk) + memset(ptr, 0x5a, size); +#endif + + arena_run_reg_dalloc(run, ptr); + + if (run->nfree == bin->nregs) + arena_dalloc_bin_run(arena, chunk, run, bin); + else if (run->nfree == 1 && run != bin->runcur) { + /* + * Make sure that bin->runcur always refers to the lowest + * non-full run, if one exists. + */ + if (bin->runcur == NULL) + bin->runcur = run; + else if ((uintptr_t)run < (uintptr_t)bin->runcur) { + /* Switch runcur. */ + if (bin->runcur->nfree > 0) { + arena_chunk_t *runcur_chunk = + CHUNK_ADDR2BASE(bin->runcur); + size_t runcur_pageind = + (((uintptr_t)bin->runcur - + (uintptr_t)runcur_chunk)) >> PAGE_SHIFT; + arena_chunk_map_t *runcur_mapelm = + &runcur_chunk->map[runcur_pageind]; + + /* Insert runcur. */ + arena_run_tree_insert(&bin->runs, + runcur_mapelm); + } + bin->runcur = run; + } else { + size_t run_pageind = (((uintptr_t)run - + (uintptr_t)chunk)) >> PAGE_SHIFT; + arena_chunk_map_t *run_mapelm = + &chunk->map[run_pageind]; + + assert(arena_run_tree_search(&bin->runs, run_mapelm) == + NULL); + arena_run_tree_insert(&bin->runs, run_mapelm); + } + } + +#ifdef JEMALLOC_STATS + bin->stats.allocated -= size; + bin->stats.ndalloc++; +#endif +} + +#ifdef JEMALLOC_STATS +void +arena_stats_merge(arena_t *arena, size_t *nactive, size_t *ndirty, + arena_stats_t *astats, malloc_bin_stats_t *bstats, + malloc_large_stats_t *lstats) +{ + unsigned i; + + malloc_mutex_lock(&arena->lock); + *nactive += arena->nactive; + *ndirty += arena->ndirty; + + astats->mapped += arena->stats.mapped; + astats->npurge += arena->stats.npurge; + astats->nmadvise += arena->stats.nmadvise; + astats->purged += arena->stats.purged; + astats->allocated_large += arena->stats.allocated_large; + astats->nmalloc_large += arena->stats.nmalloc_large; + astats->ndalloc_large += arena->stats.ndalloc_large; + astats->nrequests_large += arena->stats.nrequests_large; + + for (i = 0; i < nlclasses; i++) { + lstats[i].nmalloc += arena->stats.lstats[i].nmalloc; + lstats[i].ndalloc += arena->stats.lstats[i].ndalloc; + lstats[i].nrequests += arena->stats.lstats[i].nrequests; + lstats[i].highruns += arena->stats.lstats[i].highruns; + lstats[i].curruns += arena->stats.lstats[i].curruns; + } + malloc_mutex_unlock(&arena->lock); + + for (i = 0; i < nbins; i++) { + arena_bin_t *bin = &arena->bins[i]; + + malloc_mutex_lock(&bin->lock); + bstats[i].allocated += bin->stats.allocated; + bstats[i].nmalloc += bin->stats.nmalloc; + bstats[i].ndalloc += bin->stats.ndalloc; + bstats[i].nrequests += bin->stats.nrequests; +#ifdef JEMALLOC_TCACHE + bstats[i].nfills += bin->stats.nfills; + bstats[i].nflushes += bin->stats.nflushes; +#endif + bstats[i].nruns += bin->stats.nruns; + bstats[i].reruns += bin->stats.reruns; + bstats[i].highruns += bin->stats.highruns; + bstats[i].curruns += bin->stats.curruns; + malloc_mutex_unlock(&bin->lock); + } +} +#endif + +void +arena_dalloc_large(arena_t *arena, arena_chunk_t *chunk, void *ptr) +{ + + /* Large allocation. */ +#ifdef JEMALLOC_FILL +# ifndef JEMALLOC_STATS + if (opt_junk) +# endif +#endif + { +#if (defined(JEMALLOC_FILL) || defined(JEMALLOC_STATS)) + size_t pageind = ((uintptr_t)ptr - (uintptr_t)chunk) >> + PAGE_SHIFT; + size_t size = chunk->map[pageind].bits & ~PAGE_MASK; +#endif + +#ifdef JEMALLOC_FILL +# ifdef JEMALLOC_STATS + if (opt_junk) +# endif + memset(ptr, 0x5a, size); +#endif +#ifdef JEMALLOC_STATS + arena->stats.ndalloc_large++; + arena->stats.allocated_large -= size; + arena->stats.lstats[(size >> PAGE_SHIFT) - 1].ndalloc++; + arena->stats.lstats[(size >> PAGE_SHIFT) - 1].curruns--; +#endif + } + + arena_run_dalloc(arena, (arena_run_t *)ptr, true); +} + +static void +arena_ralloc_large_shrink(arena_t *arena, arena_chunk_t *chunk, void *ptr, + size_t size, size_t oldsize) +{ + + assert(size < oldsize); + + /* + * Shrink the run, and make trailing pages available for other + * allocations. + */ + malloc_mutex_lock(&arena->lock); + arena_run_trim_tail(arena, chunk, (arena_run_t *)ptr, oldsize, size, + true); +#ifdef JEMALLOC_STATS + arena->stats.ndalloc_large++; + arena->stats.allocated_large -= oldsize; + arena->stats.lstats[(oldsize >> PAGE_SHIFT) - 1].ndalloc++; + arena->stats.lstats[(oldsize >> PAGE_SHIFT) - 1].curruns--; + + arena->stats.nmalloc_large++; + arena->stats.nrequests_large++; + arena->stats.allocated_large += size; + arena->stats.lstats[(size >> PAGE_SHIFT) - 1].nmalloc++; + arena->stats.lstats[(size >> PAGE_SHIFT) - 1].nrequests++; + arena->stats.lstats[(size >> PAGE_SHIFT) - 1].curruns++; + if (arena->stats.lstats[(size >> PAGE_SHIFT) - 1].curruns > + arena->stats.lstats[(size >> PAGE_SHIFT) - 1].highruns) { + arena->stats.lstats[(size >> PAGE_SHIFT) - 1].highruns = + arena->stats.lstats[(size >> PAGE_SHIFT) - 1].curruns; + } +#endif + malloc_mutex_unlock(&arena->lock); +} + +static bool +arena_ralloc_large_grow(arena_t *arena, arena_chunk_t *chunk, void *ptr, + size_t size, size_t oldsize) +{ + size_t pageind = ((uintptr_t)ptr - (uintptr_t)chunk) >> PAGE_SHIFT; + size_t npages = oldsize >> PAGE_SHIFT; + + assert(oldsize == (chunk->map[pageind].bits & ~PAGE_MASK)); + + /* Try to extend the run. */ + assert(size > oldsize); + malloc_mutex_lock(&arena->lock); + if (pageind + npages < chunk_npages && (chunk->map[pageind+npages].bits + & CHUNK_MAP_ALLOCATED) == 0 && (chunk->map[pageind+npages].bits & + ~PAGE_MASK) >= size - oldsize) { + /* + * The next run is available and sufficiently large. Split the + * following run, then merge the first part with the existing + * allocation. + */ + arena_run_split(arena, (arena_run_t *)((uintptr_t)chunk + + ((pageind+npages) << PAGE_SHIFT)), size - oldsize, true, + false); + + chunk->map[pageind].bits = size | CHUNK_MAP_LARGE | + CHUNK_MAP_ALLOCATED; + chunk->map[pageind+npages].bits = CHUNK_MAP_LARGE | + CHUNK_MAP_ALLOCATED; + +#ifdef JEMALLOC_STATS + arena->stats.ndalloc_large++; + arena->stats.allocated_large -= oldsize; + arena->stats.lstats[(oldsize >> PAGE_SHIFT) - 1].ndalloc++; + arena->stats.lstats[(oldsize >> PAGE_SHIFT) - 1].curruns--; + + arena->stats.nmalloc_large++; + arena->stats.nrequests_large++; + arena->stats.allocated_large += size; + arena->stats.lstats[(size >> PAGE_SHIFT) - 1].nmalloc++; + arena->stats.lstats[(size >> PAGE_SHIFT) - 1].nrequests++; + arena->stats.lstats[(size >> PAGE_SHIFT) - 1].curruns++; + if (arena->stats.lstats[(size >> PAGE_SHIFT) - 1].curruns > + arena->stats.lstats[(size >> PAGE_SHIFT) - 1].highruns) { + arena->stats.lstats[(size >> PAGE_SHIFT) - 1].highruns = + arena->stats.lstats[(size >> PAGE_SHIFT) - 1].curruns; + } +#endif + malloc_mutex_unlock(&arena->lock); + return (false); + } + malloc_mutex_unlock(&arena->lock); + + return (true); +} + +/* + * Try to resize a large allocation, in order to avoid copying. This will + * always fail if growing an object, and the following run is already in use. + */ +static bool +arena_ralloc_large(void *ptr, size_t size, size_t oldsize) +{ + size_t psize; + + psize = PAGE_CEILING(size); + if (psize == oldsize) { + /* Same size class. */ +#ifdef JEMALLOC_FILL + if (opt_junk && size < oldsize) { + memset((void *)((uintptr_t)ptr + size), 0x5a, oldsize - + size); + } +#endif + return (false); + } else { + arena_chunk_t *chunk; + arena_t *arena; + + chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); + arena = chunk->arena; + assert(arena->magic == ARENA_MAGIC); + + if (psize < oldsize) { +#ifdef JEMALLOC_FILL + /* Fill before shrinking in order avoid a race. */ + if (opt_junk) { + memset((void *)((uintptr_t)ptr + size), 0x5a, + oldsize - size); + } +#endif + arena_ralloc_large_shrink(arena, chunk, ptr, psize, + oldsize); + return (false); + } else { + bool ret = arena_ralloc_large_grow(arena, chunk, ptr, + psize, oldsize); +#ifdef JEMALLOC_FILL + if (ret == false && opt_zero) { + memset((void *)((uintptr_t)ptr + oldsize), 0, + size - oldsize); + } +#endif + return (ret); + } + } +} + +void * +arena_ralloc(void *ptr, size_t size, size_t oldsize) +{ + void *ret; + size_t copysize; + + /* Try to avoid moving the allocation. */ + if (oldsize <= arena_maxclass) { + if (oldsize <= small_maxclass) { + if (size <= small_maxclass && small_size2bin[size] == + small_size2bin[oldsize]) + goto IN_PLACE; + } else { + assert(size <= arena_maxclass); + if (size > small_maxclass) { + if (arena_ralloc_large(ptr, size, oldsize) == + false) + return (ptr); + } + } + } + + /* + * If we get here, then size and oldsize are different enough that we + * need to move the object. In that case, fall back to allocating new + * space and copying. + */ + ret = arena_malloc(size, false); + if (ret == NULL) + return (NULL); + + /* Junk/zero-filling were already done by arena_malloc(). */ + copysize = (size < oldsize) ? size : oldsize; + memcpy(ret, ptr, copysize); + idalloc(ptr); + return (ret); +IN_PLACE: +#ifdef JEMALLOC_FILL + if (opt_junk && size < oldsize) + memset((void *)((uintptr_t)ptr + size), 0x5a, oldsize - size); + else if (opt_zero && size > oldsize) + memset((void *)((uintptr_t)ptr + oldsize), 0, size - oldsize); +#endif + return (ptr); +} + +bool +arena_new(arena_t *arena, unsigned ind) +{ + unsigned i; + arena_bin_t *bin; + size_t prev_run_size; + + arena->ind = ind; + + if (malloc_mutex_init(&arena->lock)) + return (true); + +#ifdef JEMALLOC_STATS + memset(&arena->stats, 0, sizeof(arena_stats_t)); + arena->stats.lstats = (malloc_large_stats_t *)base_alloc(nlclasses * + sizeof(malloc_large_stats_t)); + if (arena->stats.lstats == NULL) + return (true); + memset(arena->stats.lstats, 0, nlclasses * + sizeof(malloc_large_stats_t)); +# ifdef JEMALLOC_TCACHE + ql_new(&arena->tcache_ql); +# endif +#endif + +#ifdef JEMALLOC_PROF + arena->prof_accumbytes = 0; +#endif + + /* Initialize chunks. */ + ql_new(&arena->chunks_dirty); + arena->spare = NULL; + + arena->nactive = 0; + arena->ndirty = 0; + arena->npurgatory = 0; + + arena_avail_tree_new(&arena->runs_avail_clean); + arena_avail_tree_new(&arena->runs_avail_dirty); + + /* Initialize bins. */ + prev_run_size = PAGE_SIZE; + + i = 0; +#ifdef JEMALLOC_TINY + /* (2^n)-spaced tiny bins. */ + for (; i < ntbins; i++) { + bin = &arena->bins[i]; + if (malloc_mutex_init(&bin->lock)) + return (true); + bin->runcur = NULL; + arena_run_tree_new(&bin->runs); + + bin->reg_size = (1U << (LG_TINY_MIN + i)); + + prev_run_size = arena_bin_run_size_calc(bin, prev_run_size); + +#ifdef JEMALLOC_STATS + memset(&bin->stats, 0, sizeof(malloc_bin_stats_t)); +#endif + } +#endif + + /* Quantum-spaced bins. */ + for (; i < ntbins + nqbins; i++) { + bin = &arena->bins[i]; + if (malloc_mutex_init(&bin->lock)) + return (true); + bin->runcur = NULL; + arena_run_tree_new(&bin->runs); + + bin->reg_size = (i - ntbins + 1) << LG_QUANTUM; + + prev_run_size = arena_bin_run_size_calc(bin, prev_run_size); + +#ifdef JEMALLOC_STATS + memset(&bin->stats, 0, sizeof(malloc_bin_stats_t)); +#endif + } + + /* Cacheline-spaced bins. */ + for (; i < ntbins + nqbins + ncbins; i++) { + bin = &arena->bins[i]; + if (malloc_mutex_init(&bin->lock)) + return (true); + bin->runcur = NULL; + arena_run_tree_new(&bin->runs); + + bin->reg_size = cspace_min + ((i - (ntbins + nqbins)) << + LG_CACHELINE); + + prev_run_size = arena_bin_run_size_calc(bin, prev_run_size); + +#ifdef JEMALLOC_STATS + memset(&bin->stats, 0, sizeof(malloc_bin_stats_t)); +#endif + } + + /* Subpage-spaced bins. */ + for (; i < nbins; i++) { + bin = &arena->bins[i]; + if (malloc_mutex_init(&bin->lock)) + return (true); + bin->runcur = NULL; + arena_run_tree_new(&bin->runs); + + bin->reg_size = sspace_min + ((i - (ntbins + nqbins + ncbins)) + << LG_SUBPAGE); + + prev_run_size = arena_bin_run_size_calc(bin, prev_run_size); + +#ifdef JEMALLOC_STATS + memset(&bin->stats, 0, sizeof(malloc_bin_stats_t)); +#endif + } + +#ifdef JEMALLOC_DEBUG + arena->magic = ARENA_MAGIC; +#endif + + return (false); +} + +#ifdef JEMALLOC_TINY +/* Compute the smallest power of 2 that is >= x. */ +static size_t +pow2_ceil(size_t x) +{ + + x--; + x |= x >> 1; + x |= x >> 2; + x |= x >> 4; + x |= x >> 8; + x |= x >> 16; +#if (SIZEOF_PTR == 8) + x |= x >> 32; +#endif + x++; + return (x); +} +#endif + +#ifdef JEMALLOC_DEBUG +static void +small_size2bin_validate(void) +{ + size_t i, size, binind; + + assert(small_size2bin[0] == 0xffU); + i = 1; +# ifdef JEMALLOC_TINY + /* Tiny. */ + for (; i < (1U << LG_TINY_MIN); i++) { + size = pow2_ceil(1U << LG_TINY_MIN); + binind = ffs((int)(size >> (LG_TINY_MIN + 1))); + assert(small_size2bin[i] == binind); + } + for (; i < qspace_min; i++) { + size = pow2_ceil(i); + binind = ffs((int)(size >> (LG_TINY_MIN + 1))); + assert(small_size2bin[i] == binind); + } +# endif + /* Quantum-spaced. */ + for (; i <= qspace_max; i++) { + size = QUANTUM_CEILING(i); + binind = ntbins + (size >> LG_QUANTUM) - 1; + assert(small_size2bin[i] == binind); + } + /* Cacheline-spaced. */ + for (; i <= cspace_max; i++) { + size = CACHELINE_CEILING(i); + binind = ntbins + nqbins + ((size - cspace_min) >> + LG_CACHELINE); + assert(small_size2bin[i] == binind); + } + /* Sub-page. */ + for (; i <= sspace_max; i++) { + size = SUBPAGE_CEILING(i); + binind = ntbins + nqbins + ncbins + ((size - sspace_min) + >> LG_SUBPAGE); + assert(small_size2bin[i] == binind); + } +} +#endif + +static bool +small_size2bin_init(void) +{ + + if (opt_lg_qspace_max != LG_QSPACE_MAX_DEFAULT + || opt_lg_cspace_max != LG_CSPACE_MAX_DEFAULT + || sizeof(const_small_size2bin) != small_maxclass + 1) + return (small_size2bin_init_hard()); + + small_size2bin = const_small_size2bin; +#ifdef JEMALLOC_DEBUG + assert(sizeof(const_small_size2bin) == small_maxclass + 1); + small_size2bin_validate(); +#endif + return (false); +} + +static bool +small_size2bin_init_hard(void) +{ + size_t i, size, binind; + uint8_t *custom_small_size2bin; + + assert(opt_lg_qspace_max != LG_QSPACE_MAX_DEFAULT + || opt_lg_cspace_max != LG_CSPACE_MAX_DEFAULT + || sizeof(const_small_size2bin) != small_maxclass + 1); + + custom_small_size2bin = (uint8_t *)base_alloc(small_maxclass + 1); + if (custom_small_size2bin == NULL) + return (true); + + custom_small_size2bin[0] = 0xffU; + i = 1; +#ifdef JEMALLOC_TINY + /* Tiny. */ + for (; i < (1U << LG_TINY_MIN); i++) { + size = pow2_ceil(1U << LG_TINY_MIN); + binind = ffs((int)(size >> (LG_TINY_MIN + 1))); + custom_small_size2bin[i] = binind; + } + for (; i < qspace_min; i++) { + size = pow2_ceil(i); + binind = ffs((int)(size >> (LG_TINY_MIN + 1))); + custom_small_size2bin[i] = binind; + } +#endif + /* Quantum-spaced. */ + for (; i <= qspace_max; i++) { + size = QUANTUM_CEILING(i); + binind = ntbins + (size >> LG_QUANTUM) - 1; + custom_small_size2bin[i] = binind; + } + /* Cacheline-spaced. */ + for (; i <= cspace_max; i++) { + size = CACHELINE_CEILING(i); + binind = ntbins + nqbins + ((size - cspace_min) >> + LG_CACHELINE); + custom_small_size2bin[i] = binind; + } + /* Sub-page. */ + for (; i <= sspace_max; i++) { + size = SUBPAGE_CEILING(i); + binind = ntbins + nqbins + ncbins + ((size - sspace_min) >> + LG_SUBPAGE); + custom_small_size2bin[i] = binind; + } + + small_size2bin = custom_small_size2bin; +#ifdef JEMALLOC_DEBUG + small_size2bin_validate(); +#endif + return (false); +} + +bool +arena_boot(void) +{ + size_t header_size; + + /* Set variables according to the value of opt_lg_[qc]space_max. */ + qspace_max = (1U << opt_lg_qspace_max); + cspace_min = CACHELINE_CEILING(qspace_max); + if (cspace_min == qspace_max) + cspace_min += CACHELINE; + cspace_max = (1U << opt_lg_cspace_max); + sspace_min = SUBPAGE_CEILING(cspace_max); + if (sspace_min == cspace_max) + sspace_min += SUBPAGE; + assert(sspace_min < PAGE_SIZE); + sspace_max = PAGE_SIZE - SUBPAGE; + +#ifdef JEMALLOC_TINY + assert(LG_QUANTUM >= LG_TINY_MIN); +#endif + assert(ntbins <= LG_QUANTUM); + nqbins = qspace_max >> LG_QUANTUM; + ncbins = ((cspace_max - cspace_min) >> LG_CACHELINE) + 1; + nsbins = ((sspace_max - sspace_min) >> LG_SUBPAGE) + 1; + nbins = ntbins + nqbins + ncbins + nsbins; + + /* + * The small_size2bin lookup table uses uint8_t to encode each bin + * index, so we cannot support more than 256 small size classes. This + * limit is difficult to exceed (not even possible with 16B quantum and + * 4KiB pages), and such configurations are impractical, but + * nonetheless we need to protect against this case in order to avoid + * undefined behavior. + * + * Further constrain nbins to 255 if prof_promote is true, since all + * small size classes, plus a "not small" size class must be stored in + * 8 bits of arena_chunk_map_t's bits field. + */ +#ifdef JEMALLOC_PROF + if (opt_prof && prof_promote) { + if (nbins > 255) { + char line_buf[UMAX2S_BUFSIZE]; + malloc_write(": Too many small size classes ("); + malloc_write(umax2s(nbins, 10, line_buf)); + malloc_write(" > max 255)\n"); + abort(); + } + } else +#endif + if (nbins > 256) { + char line_buf[UMAX2S_BUFSIZE]; + malloc_write(": Too many small size classes ("); + malloc_write(umax2s(nbins, 10, line_buf)); + malloc_write(" > max 256)\n"); + abort(); + } + + if (small_size2bin_init()) + return (true); + + /* + * Compute the header size such that it is large enough to contain the + * page map. + */ + header_size = sizeof(arena_chunk_t) + + (sizeof(arena_chunk_map_t) * (chunk_npages - 1)); + arena_chunk_header_npages = (header_size >> PAGE_SHIFT) + + ((header_size & PAGE_MASK) != 0); + arena_maxclass = chunksize - (arena_chunk_header_npages << PAGE_SHIFT); + + return (false); +} diff --git a/dep/jemalloc/base.c b/dep/jemalloc/base.c new file mode 100644 index 00000000000..605197eaced --- /dev/null +++ b/dep/jemalloc/base.c @@ -0,0 +1,106 @@ +#define JEMALLOC_BASE_C_ +#include "jemalloc/internal/jemalloc_internal.h" + +/******************************************************************************/ +/* Data. */ + +malloc_mutex_t base_mtx; + +/* + * Current pages that are being used for internal memory allocations. These + * pages are carved up in cacheline-size quanta, so that there is no chance of + * false cache line sharing. + */ +static void *base_pages; +static void *base_next_addr; +static void *base_past_addr; /* Addr immediately past base_pages. */ +static extent_node_t *base_nodes; + +/******************************************************************************/ +/* Function prototypes for non-inline static functions. */ + +static bool base_pages_alloc(size_t minsize); + +/******************************************************************************/ + +static bool +base_pages_alloc(size_t minsize) +{ + size_t csize; + bool zero; + + assert(minsize != 0); + csize = CHUNK_CEILING(minsize); + zero = false; + base_pages = chunk_alloc(csize, &zero); + if (base_pages == NULL) + return (true); + base_next_addr = base_pages; + base_past_addr = (void *)((uintptr_t)base_pages + csize); + + return (false); +} + +void * +base_alloc(size_t size) +{ + void *ret; + size_t csize; + + /* Round size up to nearest multiple of the cacheline size. */ + csize = CACHELINE_CEILING(size); + + malloc_mutex_lock(&base_mtx); + /* Make sure there's enough space for the allocation. */ + if ((uintptr_t)base_next_addr + csize > (uintptr_t)base_past_addr) { + if (base_pages_alloc(csize)) { + malloc_mutex_unlock(&base_mtx); + return (NULL); + } + } + /* Allocate. */ + ret = base_next_addr; + base_next_addr = (void *)((uintptr_t)base_next_addr + csize); + malloc_mutex_unlock(&base_mtx); + + return (ret); +} + +extent_node_t * +base_node_alloc(void) +{ + extent_node_t *ret; + + malloc_mutex_lock(&base_mtx); + if (base_nodes != NULL) { + ret = base_nodes; + base_nodes = *(extent_node_t **)ret; + malloc_mutex_unlock(&base_mtx); + } else { + malloc_mutex_unlock(&base_mtx); + ret = (extent_node_t *)base_alloc(sizeof(extent_node_t)); + } + + return (ret); +} + +void +base_node_dealloc(extent_node_t *node) +{ + + malloc_mutex_lock(&base_mtx); + *(extent_node_t **)node = base_nodes; + base_nodes = node; + malloc_mutex_unlock(&base_mtx); +} + +bool +base_boot(void) +{ + + base_nodes = NULL; + if (malloc_mutex_init(&base_mtx)) + return (true); + + return (false); +} diff --git a/dep/jemalloc/chunk.c b/dep/jemalloc/chunk.c new file mode 100644 index 00000000000..e6e3bcd195a --- /dev/null +++ b/dep/jemalloc/chunk.c @@ -0,0 +1,150 @@ +#define JEMALLOC_CHUNK_C_ +#include "jemalloc/internal/jemalloc_internal.h" + +/******************************************************************************/ +/* Data. */ + +size_t opt_lg_chunk = LG_CHUNK_DEFAULT; +#ifdef JEMALLOC_SWAP +bool opt_overcommit = true; +#endif + +#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) +malloc_mutex_t chunks_mtx; +chunk_stats_t stats_chunks; +#endif + +/* Various chunk-related settings. */ +size_t chunksize; +size_t chunksize_mask; /* (chunksize - 1). */ +size_t chunk_npages; +size_t arena_chunk_header_npages; +size_t arena_maxclass; /* Max size class for arenas. */ + +/******************************************************************************/ + +/* + * If the caller specifies (*zero == false), it is still possible to receive + * zeroed memory, in which case *zero is toggled to true. arena_chunk_alloc() + * takes advantage of this to avoid demanding zeroed chunks, but taking + * advantage of them if they are returned. + */ +void * +chunk_alloc(size_t size, bool *zero) +{ + void *ret; + + assert(size != 0); + assert((size & chunksize_mask) == 0); + +#ifdef JEMALLOC_SWAP + if (swap_enabled) { + ret = chunk_alloc_swap(size, zero); + if (ret != NULL) + goto RETURN; + } + + if (swap_enabled == false || opt_overcommit) { +#endif +#ifdef JEMALLOC_DSS + ret = chunk_alloc_dss(size, zero); + if (ret != NULL) + goto RETURN; +#endif + ret = chunk_alloc_mmap(size); + if (ret != NULL) { + *zero = true; + goto RETURN; + } +#ifdef JEMALLOC_SWAP + } +#endif + + /* All strategies for allocation failed. */ + ret = NULL; +RETURN: +#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) + if (ret != NULL) { +# ifdef JEMALLOC_PROF + bool udump; +# endif + malloc_mutex_lock(&chunks_mtx); +# ifdef JEMALLOC_STATS + stats_chunks.nchunks += (size / chunksize); +# endif + stats_chunks.curchunks += (size / chunksize); + if (stats_chunks.curchunks > stats_chunks.highchunks) { + stats_chunks.highchunks = stats_chunks.curchunks; +# ifdef JEMALLOC_PROF + udump = true; +# endif + } +# ifdef JEMALLOC_PROF + else + udump = false; +# endif + malloc_mutex_unlock(&chunks_mtx); +# ifdef JEMALLOC_PROF + if (opt_prof && opt_prof_udump && udump) + prof_udump(); +# endif + } +#endif + + assert(CHUNK_ADDR2BASE(ret) == ret); + return (ret); +} + +void +chunk_dealloc(void *chunk, size_t size) +{ + + assert(chunk != NULL); + assert(CHUNK_ADDR2BASE(chunk) == chunk); + assert(size != 0); + assert((size & chunksize_mask) == 0); + +#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) + malloc_mutex_lock(&chunks_mtx); + stats_chunks.curchunks -= (size / chunksize); + malloc_mutex_unlock(&chunks_mtx); +#endif + +#ifdef JEMALLOC_SWAP + if (swap_enabled && chunk_dealloc_swap(chunk, size) == false) + return; +#endif +#ifdef JEMALLOC_DSS + if (chunk_dealloc_dss(chunk, size) == false) + return; +#endif + chunk_dealloc_mmap(chunk, size); +} + +bool +chunk_boot(void) +{ + + /* Set variables according to the value of opt_lg_chunk. */ + chunksize = (1LU << opt_lg_chunk); + assert(chunksize >= PAGE_SIZE); + chunksize_mask = chunksize - 1; + chunk_npages = (chunksize >> PAGE_SHIFT); + +#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) + if (malloc_mutex_init(&chunks_mtx)) + return (true); + memset(&stats_chunks, 0, sizeof(chunk_stats_t)); +#endif + +#ifdef JEMALLOC_SWAP + if (chunk_swap_boot()) + return (true); +#endif +#ifdef JEMALLOC_DSS + if (chunk_dss_boot()) + return (true); +#endif + + return (false); +} diff --git a/dep/jemalloc/chunk_dss.c b/dep/jemalloc/chunk_dss.c new file mode 100644 index 00000000000..d9bd63c3ac4 --- /dev/null +++ b/dep/jemalloc/chunk_dss.c @@ -0,0 +1,268 @@ +#define JEMALLOC_CHUNK_DSS_C_ +#include "jemalloc/internal/jemalloc_internal.h" +#ifdef JEMALLOC_DSS +/******************************************************************************/ +/* Data. */ + +malloc_mutex_t dss_mtx; + +/* Base address of the DSS. */ +static void *dss_base; +/* Current end of the DSS, or ((void *)-1) if the DSS is exhausted. */ +static void *dss_prev; +/* Current upper limit on DSS addresses. */ +static void *dss_max; + +/* + * Trees of chunks that were previously allocated (trees differ only in node + * ordering). These are used when allocating chunks, in an attempt to re-use + * address space. Depending on function, different tree orderings are needed, + * which is why there are two trees with the same contents. + */ +static extent_tree_t dss_chunks_szad; +static extent_tree_t dss_chunks_ad; + +/******************************************************************************/ +/* Function prototypes for non-inline static functions. */ + +static void *chunk_recycle_dss(size_t size, bool *zero); +static extent_node_t *chunk_dealloc_dss_record(void *chunk, size_t size); + +/******************************************************************************/ + +static void * +chunk_recycle_dss(size_t size, bool *zero) +{ + extent_node_t *node, key; + + key.addr = NULL; + key.size = size; + malloc_mutex_lock(&dss_mtx); + node = extent_tree_szad_nsearch(&dss_chunks_szad, &key); + if (node != NULL) { + void *ret = node->addr; + + /* Remove node from the tree. */ + extent_tree_szad_remove(&dss_chunks_szad, node); + if (node->size == size) { + extent_tree_ad_remove(&dss_chunks_ad, node); + base_node_dealloc(node); + } else { + /* + * Insert the remainder of node's address range as a + * smaller chunk. Its position within dss_chunks_ad + * does not change. + */ + assert(node->size > size); + node->addr = (void *)((uintptr_t)node->addr + size); + node->size -= size; + extent_tree_szad_insert(&dss_chunks_szad, node); + } + malloc_mutex_unlock(&dss_mtx); + + if (*zero) + memset(ret, 0, size); + return (ret); + } + malloc_mutex_unlock(&dss_mtx); + + return (NULL); +} + +void * +chunk_alloc_dss(size_t size, bool *zero) +{ + void *ret; + + ret = chunk_recycle_dss(size, zero); + if (ret != NULL) + return (ret); + + /* + * sbrk() uses a signed increment argument, so take care not to + * interpret a huge allocation request as a negative increment. + */ + if ((intptr_t)size < 0) + return (NULL); + + malloc_mutex_lock(&dss_mtx); + if (dss_prev != (void *)-1) { + intptr_t incr; + + /* + * The loop is necessary to recover from races with other + * threads that are using the DSS for something other than + * malloc. + */ + do { + /* Get the current end of the DSS. */ + dss_max = sbrk(0); + + /* + * Calculate how much padding is necessary to + * chunk-align the end of the DSS. + */ + incr = (intptr_t)size + - (intptr_t)CHUNK_ADDR2OFFSET(dss_max); + if (incr == (intptr_t)size) + ret = dss_max; + else { + ret = (void *)((intptr_t)dss_max + incr); + incr += size; + } + + dss_prev = sbrk(incr); + if (dss_prev == dss_max) { + /* Success. */ + dss_max = (void *)((intptr_t)dss_prev + incr); + malloc_mutex_unlock(&dss_mtx); + *zero = true; + return (ret); + } + } while (dss_prev != (void *)-1); + } + malloc_mutex_unlock(&dss_mtx); + + return (NULL); +} + +static extent_node_t * +chunk_dealloc_dss_record(void *chunk, size_t size) +{ + extent_node_t *xnode, *node, *prev, key; + + xnode = NULL; + while (true) { + key.addr = (void *)((uintptr_t)chunk + size); + node = extent_tree_ad_nsearch(&dss_chunks_ad, &key); + /* Try to coalesce forward. */ + if (node != NULL && node->addr == key.addr) { + /* + * Coalesce chunk with the following address range. + * This does not change the position within + * dss_chunks_ad, so only remove/insert from/into + * dss_chunks_szad. + */ + extent_tree_szad_remove(&dss_chunks_szad, node); + node->addr = chunk; + node->size += size; + extent_tree_szad_insert(&dss_chunks_szad, node); + break; + } else if (xnode == NULL) { + /* + * It is possible that base_node_alloc() will cause a + * new base chunk to be allocated, so take care not to + * deadlock on dss_mtx, and recover if another thread + * deallocates an adjacent chunk while this one is busy + * allocating xnode. + */ + malloc_mutex_unlock(&dss_mtx); + xnode = base_node_alloc(); + malloc_mutex_lock(&dss_mtx); + if (xnode == NULL) + return (NULL); + } else { + /* Coalescing forward failed, so insert a new node. */ + node = xnode; + xnode = NULL; + node->addr = chunk; + node->size = size; + extent_tree_ad_insert(&dss_chunks_ad, node); + extent_tree_szad_insert(&dss_chunks_szad, node); + break; + } + } + /* Discard xnode if it ended up unused do to a race. */ + if (xnode != NULL) + base_node_dealloc(xnode); + + /* Try to coalesce backward. */ + prev = extent_tree_ad_prev(&dss_chunks_ad, node); + if (prev != NULL && (void *)((uintptr_t)prev->addr + prev->size) == + chunk) { + /* + * Coalesce chunk with the previous address range. This does + * not change the position within dss_chunks_ad, so only + * remove/insert node from/into dss_chunks_szad. + */ + extent_tree_szad_remove(&dss_chunks_szad, prev); + extent_tree_ad_remove(&dss_chunks_ad, prev); + + extent_tree_szad_remove(&dss_chunks_szad, node); + node->addr = prev->addr; + node->size += prev->size; + extent_tree_szad_insert(&dss_chunks_szad, node); + + base_node_dealloc(prev); + } + + return (node); +} + +bool +chunk_dealloc_dss(void *chunk, size_t size) +{ + bool ret; + + malloc_mutex_lock(&dss_mtx); + if ((uintptr_t)chunk >= (uintptr_t)dss_base + && (uintptr_t)chunk < (uintptr_t)dss_max) { + extent_node_t *node; + + /* Try to coalesce with other unused chunks. */ + node = chunk_dealloc_dss_record(chunk, size); + if (node != NULL) { + chunk = node->addr; + size = node->size; + } + + /* Get the current end of the DSS. */ + dss_max = sbrk(0); + + /* + * Try to shrink the DSS if this chunk is at the end of the + * DSS. The sbrk() call here is subject to a race condition + * with threads that use brk(2) or sbrk(2) directly, but the + * alternative would be to leak memory for the sake of poorly + * designed multi-threaded programs. + */ + if ((void *)((uintptr_t)chunk + size) == dss_max + && (dss_prev = sbrk(-(intptr_t)size)) == dss_max) { + /* Success. */ + dss_max = (void *)((intptr_t)dss_prev - (intptr_t)size); + + if (node != NULL) { + extent_tree_szad_remove(&dss_chunks_szad, node); + extent_tree_ad_remove(&dss_chunks_ad, node); + base_node_dealloc(node); + } + } else + madvise(chunk, size, MADV_DONTNEED); + + ret = false; + goto RETURN; + } + + ret = true; +RETURN: + malloc_mutex_unlock(&dss_mtx); + return (ret); +} + +bool +chunk_dss_boot(void) +{ + + if (malloc_mutex_init(&dss_mtx)) + return (true); + dss_base = sbrk(0); + dss_prev = dss_base; + dss_max = dss_base; + extent_tree_szad_new(&dss_chunks_szad); + extent_tree_ad_new(&dss_chunks_ad); + + return (false); +} + +/******************************************************************************/ +#endif /* JEMALLOC_DSS */ diff --git a/dep/jemalloc/chunk_mmap.c b/dep/jemalloc/chunk_mmap.c new file mode 100644 index 00000000000..8f0711384e3 --- /dev/null +++ b/dep/jemalloc/chunk_mmap.c @@ -0,0 +1,201 @@ +#define JEMALLOC_CHUNK_MMAP_C_ +#include "jemalloc/internal/jemalloc_internal.h" + +/******************************************************************************/ +/* Data. */ + +/* + * Used by chunk_alloc_mmap() to decide whether to attempt the fast path and + * potentially avoid some system calls. We can get away without TLS here, + * since the state of mmap_unaligned only affects performance, rather than + * correct function. + */ +static +#ifndef NO_TLS + __thread +#endif + bool mmap_unaligned +#ifndef NO_TLS + JEMALLOC_ATTR(tls_model("initial-exec")) +#endif + ; + +/******************************************************************************/ +/* Function prototypes for non-inline static functions. */ + +static void *pages_map(void *addr, size_t size); +static void pages_unmap(void *addr, size_t size); +static void *chunk_alloc_mmap_slow(size_t size, bool unaligned); + +/******************************************************************************/ + +static void * +pages_map(void *addr, size_t size) +{ + void *ret; + + /* + * We don't use MAP_FIXED here, because it can cause the *replacement* + * of existing mappings, and we only want to create new mappings. + */ + ret = mmap(addr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, + -1, 0); + assert(ret != NULL); + + if (ret == MAP_FAILED) + ret = NULL; + else if (addr != NULL && ret != addr) { + /* + * We succeeded in mapping memory, but not in the right place. + */ + if (munmap(ret, size) == -1) { + char buf[STRERROR_BUF]; + + strerror_r(errno, buf, sizeof(buf)); + malloc_write(": Error in munmap(): "); + malloc_write(buf); + malloc_write("\n"); + if (opt_abort) + abort(); + } + ret = NULL; + } + + assert(ret == NULL || (addr == NULL && ret != addr) + || (addr != NULL && ret == addr)); + return (ret); +} + +static void +pages_unmap(void *addr, size_t size) +{ + + if (munmap(addr, size) == -1) { + char buf[STRERROR_BUF]; + + strerror_r(errno, buf, sizeof(buf)); + malloc_write(": Error in munmap(): "); + malloc_write(buf); + malloc_write("\n"); + if (opt_abort) + abort(); + } +} + +static void * +chunk_alloc_mmap_slow(size_t size, bool unaligned) +{ + void *ret; + size_t offset; + + /* Beware size_t wrap-around. */ + if (size + chunksize <= size) + return (NULL); + + ret = pages_map(NULL, size + chunksize); + if (ret == NULL) + return (NULL); + + /* Clean up unneeded leading/trailing space. */ + offset = CHUNK_ADDR2OFFSET(ret); + if (offset != 0) { + /* Note that mmap() returned an unaligned mapping. */ + unaligned = true; + + /* Leading space. */ + pages_unmap(ret, chunksize - offset); + + ret = (void *)((uintptr_t)ret + + (chunksize - offset)); + + /* Trailing space. */ + pages_unmap((void *)((uintptr_t)ret + size), + offset); + } else { + /* Trailing space only. */ + pages_unmap((void *)((uintptr_t)ret + size), + chunksize); + } + + /* + * If mmap() returned an aligned mapping, reset mmap_unaligned so that + * the next chunk_alloc_mmap() execution tries the fast allocation + * method. + */ + if (unaligned == false) + mmap_unaligned = false; + + return (ret); +} + +void * +chunk_alloc_mmap(size_t size) +{ + void *ret; + + /* + * Ideally, there would be a way to specify alignment to mmap() (like + * NetBSD has), but in the absence of such a feature, we have to work + * hard to efficiently create aligned mappings. The reliable, but + * slow method is to create a mapping that is over-sized, then trim the + * excess. However, that always results in at least one call to + * pages_unmap(). + * + * A more optimistic approach is to try mapping precisely the right + * amount, then try to append another mapping if alignment is off. In + * practice, this works out well as long as the application is not + * interleaving mappings via direct mmap() calls. If we do run into a + * situation where there is an interleaved mapping and we are unable to + * extend an unaligned mapping, our best option is to switch to the + * slow method until mmap() returns another aligned mapping. This will + * tend to leave a gap in the memory map that is too small to cause + * later problems for the optimistic method. + * + * Another possible confounding factor is address space layout + * randomization (ASLR), which causes mmap(2) to disregard the + * requested address. mmap_unaligned tracks whether the previous + * chunk_alloc_mmap() execution received any unaligned or relocated + * mappings, and if so, the current execution will immediately fall + * back to the slow method. However, we keep track of whether the fast + * method would have succeeded, and if so, we make a note to try the + * fast method next time. + */ + + if (mmap_unaligned == false) { + size_t offset; + + ret = pages_map(NULL, size); + if (ret == NULL) + return (NULL); + + offset = CHUNK_ADDR2OFFSET(ret); + if (offset != 0) { + mmap_unaligned = true; + /* Try to extend chunk boundary. */ + if (pages_map((void *)((uintptr_t)ret + size), + chunksize - offset) == NULL) { + /* + * Extension failed. Clean up, then revert to + * the reliable-but-expensive method. + */ + pages_unmap(ret, size); + ret = chunk_alloc_mmap_slow(size, true); + } else { + /* Clean up unneeded leading space. */ + pages_unmap(ret, chunksize - offset); + ret = (void *)((uintptr_t)ret + (chunksize - + offset)); + } + } + } else + ret = chunk_alloc_mmap_slow(size, false); + + return (ret); +} + +void +chunk_dealloc_mmap(void *chunk, size_t size) +{ + + pages_unmap(chunk, size); +} diff --git a/dep/jemalloc/chunk_swap.c b/dep/jemalloc/chunk_swap.c new file mode 100644 index 00000000000..b8c880f0a17 --- /dev/null +++ b/dep/jemalloc/chunk_swap.c @@ -0,0 +1,383 @@ +#define JEMALLOC_CHUNK_SWAP_C_ +#include "jemalloc/internal/jemalloc_internal.h" +#ifdef JEMALLOC_SWAP +/******************************************************************************/ +/* Data. */ + +malloc_mutex_t swap_mtx; +bool swap_enabled; +bool swap_prezeroed; +size_t swap_nfds; +int *swap_fds; +#ifdef JEMALLOC_STATS +size_t swap_avail; +#endif + +/* Base address of the mmap()ed file(s). */ +static void *swap_base; +/* Current end of the space in use (<= swap_max). */ +static void *swap_end; +/* Absolute upper limit on file-backed addresses. */ +static void *swap_max; + +/* + * Trees of chunks that were previously allocated (trees differ only in node + * ordering). These are used when allocating chunks, in an attempt to re-use + * address space. Depending on function, different tree orderings are needed, + * which is why there are two trees with the same contents. + */ +static extent_tree_t swap_chunks_szad; +static extent_tree_t swap_chunks_ad; + +/******************************************************************************/ +/* Function prototypes for non-inline static functions. */ + +static void *chunk_recycle_swap(size_t size, bool *zero); +static extent_node_t *chunk_dealloc_swap_record(void *chunk, size_t size); + +/******************************************************************************/ + +static void * +chunk_recycle_swap(size_t size, bool *zero) +{ + extent_node_t *node, key; + + key.addr = NULL; + key.size = size; + malloc_mutex_lock(&swap_mtx); + node = extent_tree_szad_nsearch(&swap_chunks_szad, &key); + if (node != NULL) { + void *ret = node->addr; + + /* Remove node from the tree. */ + extent_tree_szad_remove(&swap_chunks_szad, node); + if (node->size == size) { + extent_tree_ad_remove(&swap_chunks_ad, node); + base_node_dealloc(node); + } else { + /* + * Insert the remainder of node's address range as a + * smaller chunk. Its position within swap_chunks_ad + * does not change. + */ + assert(node->size > size); + node->addr = (void *)((uintptr_t)node->addr + size); + node->size -= size; + extent_tree_szad_insert(&swap_chunks_szad, node); + } +#ifdef JEMALLOC_STATS + swap_avail -= size; +#endif + malloc_mutex_unlock(&swap_mtx); + + if (*zero) + memset(ret, 0, size); + return (ret); + } + malloc_mutex_unlock(&swap_mtx); + + return (NULL); +} + +void * +chunk_alloc_swap(size_t size, bool *zero) +{ + void *ret; + + assert(swap_enabled); + + ret = chunk_recycle_swap(size, zero); + if (ret != NULL) + return (ret); + + malloc_mutex_lock(&swap_mtx); + if ((uintptr_t)swap_end + size <= (uintptr_t)swap_max) { + ret = swap_end; + swap_end = (void *)((uintptr_t)swap_end + size); +#ifdef JEMALLOC_STATS + swap_avail -= size; +#endif + malloc_mutex_unlock(&swap_mtx); + + if (swap_prezeroed) + *zero = true; + else if (*zero) + memset(ret, 0, size); + } else { + malloc_mutex_unlock(&swap_mtx); + return (NULL); + } + + return (ret); +} + +static extent_node_t * +chunk_dealloc_swap_record(void *chunk, size_t size) +{ + extent_node_t *xnode, *node, *prev, key; + + xnode = NULL; + while (true) { + key.addr = (void *)((uintptr_t)chunk + size); + node = extent_tree_ad_nsearch(&swap_chunks_ad, &key); + /* Try to coalesce forward. */ + if (node != NULL && node->addr == key.addr) { + /* + * Coalesce chunk with the following address range. + * This does not change the position within + * swap_chunks_ad, so only remove/insert from/into + * swap_chunks_szad. + */ + extent_tree_szad_remove(&swap_chunks_szad, node); + node->addr = chunk; + node->size += size; + extent_tree_szad_insert(&swap_chunks_szad, node); + break; + } else if (xnode == NULL) { + /* + * It is possible that base_node_alloc() will cause a + * new base chunk to be allocated, so take care not to + * deadlock on swap_mtx, and recover if another thread + * deallocates an adjacent chunk while this one is busy + * allocating xnode. + */ + malloc_mutex_unlock(&swap_mtx); + xnode = base_node_alloc(); + malloc_mutex_lock(&swap_mtx); + if (xnode == NULL) + return (NULL); + } else { + /* Coalescing forward failed, so insert a new node. */ + node = xnode; + xnode = NULL; + node->addr = chunk; + node->size = size; + extent_tree_ad_insert(&swap_chunks_ad, node); + extent_tree_szad_insert(&swap_chunks_szad, node); + break; + } + } + /* Discard xnode if it ended up unused do to a race. */ + if (xnode != NULL) + base_node_dealloc(xnode); + + /* Try to coalesce backward. */ + prev = extent_tree_ad_prev(&swap_chunks_ad, node); + if (prev != NULL && (void *)((uintptr_t)prev->addr + prev->size) == + chunk) { + /* + * Coalesce chunk with the previous address range. This does + * not change the position within swap_chunks_ad, so only + * remove/insert node from/into swap_chunks_szad. + */ + extent_tree_szad_remove(&swap_chunks_szad, prev); + extent_tree_ad_remove(&swap_chunks_ad, prev); + + extent_tree_szad_remove(&swap_chunks_szad, node); + node->addr = prev->addr; + node->size += prev->size; + extent_tree_szad_insert(&swap_chunks_szad, node); + + base_node_dealloc(prev); + } + + return (node); +} + +bool +chunk_dealloc_swap(void *chunk, size_t size) +{ + bool ret; + + assert(swap_enabled); + + malloc_mutex_lock(&swap_mtx); + if ((uintptr_t)chunk >= (uintptr_t)swap_base + && (uintptr_t)chunk < (uintptr_t)swap_max) { + extent_node_t *node; + + /* Try to coalesce with other unused chunks. */ + node = chunk_dealloc_swap_record(chunk, size); + if (node != NULL) { + chunk = node->addr; + size = node->size; + } + + /* + * Try to shrink the in-use memory if this chunk is at the end + * of the in-use memory. + */ + if ((void *)((uintptr_t)chunk + size) == swap_end) { + swap_end = (void *)((uintptr_t)swap_end - size); + + if (node != NULL) { + extent_tree_szad_remove(&swap_chunks_szad, + node); + extent_tree_ad_remove(&swap_chunks_ad, node); + base_node_dealloc(node); + } + } else + madvise(chunk, size, MADV_DONTNEED); + + ret = false; + goto RETURN; + } + + ret = true; +RETURN: +#ifdef JEMALLOC_STATS + swap_avail += size; +#endif + malloc_mutex_unlock(&swap_mtx); + return (ret); +} + +bool +chunk_swap_enable(const int *fds, unsigned nfds, bool prezeroed) +{ + bool ret; + unsigned i; + off_t off; + void *vaddr; + size_t cumsize, voff; + size_t sizes[nfds]; + + malloc_mutex_lock(&swap_mtx); + + /* Get file sizes. */ + for (i = 0, cumsize = 0; i < nfds; i++) { + off = lseek(fds[i], 0, SEEK_END); + if (off == ((off_t)-1)) { + ret = true; + goto RETURN; + } + if (PAGE_CEILING(off) != off) { + /* Truncate to a multiple of the page size. */ + off &= ~PAGE_MASK; + if (ftruncate(fds[i], off) != 0) { + ret = true; + goto RETURN; + } + } + sizes[i] = off; + if (cumsize + off < cumsize) { + /* + * Cumulative file size is greater than the total + * address space. Bail out while it's still obvious + * what the problem is. + */ + ret = true; + goto RETURN; + } + cumsize += off; + } + + /* Round down to a multiple of the chunk size. */ + cumsize &= ~chunksize_mask; + if (cumsize == 0) { + ret = true; + goto RETURN; + } + + /* + * Allocate a chunk-aligned region of anonymous memory, which will + * be the final location for the memory-mapped files. + */ + vaddr = chunk_alloc_mmap(cumsize); + if (vaddr == NULL) { + ret = true; + goto RETURN; + } + + /* Overlay the files onto the anonymous mapping. */ + for (i = 0, voff = 0; i < nfds; i++) { + void *addr = mmap((void *)((uintptr_t)vaddr + voff), sizes[i], + PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fds[i], 0); + if (addr == MAP_FAILED) { + char buf[STRERROR_BUF]; + + strerror_r(errno, buf, sizeof(buf)); + malloc_write( + ": Error in mmap(..., MAP_FIXED, ...): "); + malloc_write(buf); + malloc_write("\n"); + if (opt_abort) + abort(); + if (munmap(vaddr, voff) == -1) { + strerror_r(errno, buf, sizeof(buf)); + malloc_write(": Error in munmap(): "); + malloc_write(buf); + malloc_write("\n"); + } + ret = true; + goto RETURN; + } + assert(addr == (void *)((uintptr_t)vaddr + voff)); + + /* + * Tell the kernel that the mapping will be accessed randomly, + * and that it should not gratuitously sync pages to the + * filesystem. + */ +#ifdef MADV_RANDOM + madvise(addr, sizes[i], MADV_RANDOM); +#endif +#ifdef MADV_NOSYNC + madvise(addr, sizes[i], MADV_NOSYNC); +#endif + + voff += sizes[i]; + } + + swap_prezeroed = prezeroed; + swap_base = vaddr; + swap_end = swap_base; + swap_max = (void *)((uintptr_t)vaddr + cumsize); + + /* Copy the fds array for mallctl purposes. */ + swap_fds = (int *)base_alloc(nfds * sizeof(int)); + if (swap_fds == NULL) { + ret = true; + goto RETURN; + } + memcpy(swap_fds, fds, nfds * sizeof(int)); + swap_nfds = nfds; + +#ifdef JEMALLOC_STATS + swap_avail = cumsize; +#endif + + swap_enabled = true; + + ret = false; +RETURN: + malloc_mutex_unlock(&swap_mtx); + return (ret); +} + +bool +chunk_swap_boot(void) +{ + + if (malloc_mutex_init(&swap_mtx)) + return (true); + + swap_enabled = false; + swap_prezeroed = false; /* swap.* mallctl's depend on this. */ + swap_nfds = 0; + swap_fds = NULL; +#ifdef JEMALLOC_STATS + swap_avail = 0; +#endif + swap_base = NULL; + swap_end = NULL; + swap_max = NULL; + + extent_tree_szad_new(&swap_chunks_szad); + extent_tree_ad_new(&swap_chunks_ad); + + return (false); +} + +/******************************************************************************/ +#endif /* JEMALLOC_SWAP */ diff --git a/dep/jemalloc/ckh.c b/dep/jemalloc/ckh.c new file mode 100644 index 00000000000..a0c4162aa19 --- /dev/null +++ b/dep/jemalloc/ckh.c @@ -0,0 +1,601 @@ +/* + ******************************************************************************* + * Implementation of (2^1+,2) cuckoo hashing, where 2^1+ indicates that each + * hash bucket contains 2^n cells, for n >= 1, and 2 indicates that two hash + * functions are employed. The original cuckoo hashing algorithm was described + * in: + * + * Pagh, R., F.F. Rodler (2004) Cuckoo Hashing. Journal of Algorithms + * 51(2):122-144. + * + * Generalization of cuckoo hashing was discussed in: + * + * Erlingsson, U., M. Manasse, F. McSherry (2006) A cool and practical + * alternative to traditional hash tables. In Proceedings of the 7th + * Workshop on Distributed Data and Structures (WDAS'06), Santa Clara, CA, + * January 2006. + * + * This implementation uses precisely two hash functions because that is the + * fewest that can work, and supporting multiple hashes is an implementation + * burden. Here is a reproduction of Figure 1 from Erlingsson et al. (2006) + * that shows approximate expected maximum load factors for various + * configurations: + * + * | #cells/bucket | + * #hashes | 1 | 2 | 4 | 8 | + * --------+-------+-------+-------+-------+ + * 1 | 0.006 | 0.006 | 0.03 | 0.12 | + * 2 | 0.49 | 0.86 |>0.93< |>0.96< | + * 3 | 0.91 | 0.97 | 0.98 | 0.999 | + * 4 | 0.97 | 0.99 | 0.999 | | + * + * The number of cells per bucket is chosen such that a bucket fits in one cache + * line. So, on 32- and 64-bit systems, we use (8,2) and (4,2) cuckoo hashing, + * respectively. + * + ******************************************************************************/ +#define CKH_C_ +#include "jemalloc/internal/jemalloc_internal.h" + +/******************************************************************************/ +/* Function prototypes for non-inline static functions. */ + +static bool ckh_grow(ckh_t *ckh); +static void ckh_shrink(ckh_t *ckh); + +/******************************************************************************/ + +/* + * Search bucket for key and return the cell number if found; SIZE_T_MAX + * otherwise. + */ +JEMALLOC_INLINE size_t +ckh_bucket_search(ckh_t *ckh, size_t bucket, const void *key) +{ + ckhc_t *cell; + unsigned i; + + for (i = 0; i < (ZU(1) << LG_CKH_BUCKET_CELLS); i++) { + cell = &ckh->tab[(bucket << LG_CKH_BUCKET_CELLS) + i]; + if (cell->key != NULL && ckh->keycomp(key, cell->key)) + return ((bucket << LG_CKH_BUCKET_CELLS) + i); + } + + return (SIZE_T_MAX); +} + +/* + * Search table for key and return cell number if found; SIZE_T_MAX otherwise. + */ +JEMALLOC_INLINE size_t +ckh_isearch(ckh_t *ckh, const void *key) +{ + size_t hash1, hash2, bucket, cell; + + assert(ckh != NULL); + assert(ckh->magic = CKH_MAGIG); + + ckh->hash(key, ckh->lg_curbuckets, &hash1, &hash2); + + /* Search primary bucket. */ + bucket = hash1 & ((ZU(1) << ckh->lg_curbuckets) - 1); + cell = ckh_bucket_search(ckh, bucket, key); + if (cell != SIZE_T_MAX) + return (cell); + + /* Search secondary bucket. */ + bucket = hash2 & ((ZU(1) << ckh->lg_curbuckets) - 1); + cell = ckh_bucket_search(ckh, bucket, key); + return (cell); +} + +JEMALLOC_INLINE bool +ckh_try_bucket_insert(ckh_t *ckh, size_t bucket, const void *key, + const void *data) +{ + ckhc_t *cell; + unsigned offset, i; + + /* + * Cycle through the cells in the bucket, starting at a random position. + * The randomness avoids worst-case search overhead as buckets fill up. + */ + prn32(offset, LG_CKH_BUCKET_CELLS, ckh->prn_state, CKH_A, CKH_C); + for (i = 0; i < (ZU(1) << LG_CKH_BUCKET_CELLS); i++) { + cell = &ckh->tab[(bucket << LG_CKH_BUCKET_CELLS) + + ((i + offset) & ((ZU(1) << LG_CKH_BUCKET_CELLS) - 1))]; + if (cell->key == NULL) { + cell->key = key; + cell->data = data; + ckh->count++; + return (false); + } + } + + return (true); +} + +/* + * No space is available in bucket. Randomly evict an item, then try to find an + * alternate location for that item. Iteratively repeat this + * eviction/relocation procedure until either success or detection of an + * eviction/relocation bucket cycle. + */ +JEMALLOC_INLINE bool +ckh_evict_reloc_insert(ckh_t *ckh, size_t argbucket, void const **argkey, + void const **argdata) +{ + const void *key, *data, *tkey, *tdata; + ckhc_t *cell; + size_t hash1, hash2, bucket, tbucket; + unsigned i; + + bucket = argbucket; + key = *argkey; + data = *argdata; + while (true) { + /* + * Choose a random item within the bucket to evict. This is + * critical to correct function, because without (eventually) + * evicting all items within a bucket during iteration, it + * would be possible to get stuck in an infinite loop if there + * were an item for which both hashes indicated the same + * bucket. + */ + prn32(i, LG_CKH_BUCKET_CELLS, ckh->prn_state, CKH_A, CKH_C); + cell = &ckh->tab[(bucket << LG_CKH_BUCKET_CELLS) + i]; + assert(cell->key != NULL); + + /* Swap cell->{key,data} and {key,data} (evict). */ + tkey = cell->key; tdata = cell->data; + cell->key = key; cell->data = data; + key = tkey; data = tdata; + +#ifdef CKH_COUNT + ckh->nrelocs++; +#endif + + /* Find the alternate bucket for the evicted item. */ + ckh->hash(key, ckh->lg_curbuckets, &hash1, &hash2); + tbucket = hash2 & ((ZU(1) << ckh->lg_curbuckets) - 1); + if (tbucket == bucket) { + tbucket = hash1 & ((ZU(1) << ckh->lg_curbuckets) - 1); + /* + * It may be that (tbucket == bucket) still, if the + * item's hashes both indicate this bucket. However, + * we are guaranteed to eventually escape this bucket + * during iteration, assuming pseudo-random item + * selection (true randomness would make infinite + * looping a remote possibility). The reason we can + * never get trapped forever is that there are two + * cases: + * + * 1) This bucket == argbucket, so we will quickly + * detect an eviction cycle and terminate. + * 2) An item was evicted to this bucket from another, + * which means that at least one item in this bucket + * has hashes that indicate distinct buckets. + */ + } + /* Check for a cycle. */ + if (tbucket == argbucket) { + *argkey = key; + *argdata = data; + return (true); + } + + bucket = tbucket; + if (ckh_try_bucket_insert(ckh, bucket, key, data) == false) + return (false); + } +} + +JEMALLOC_INLINE bool +ckh_try_insert(ckh_t *ckh, void const**argkey, void const**argdata) +{ + size_t hash1, hash2, bucket; + const void *key = *argkey; + const void *data = *argdata; + + ckh->hash(key, ckh->lg_curbuckets, &hash1, &hash2); + + /* Try to insert in primary bucket. */ + bucket = hash1 & ((ZU(1) << ckh->lg_curbuckets) - 1); + if (ckh_try_bucket_insert(ckh, bucket, key, data) == false) + return (false); + + /* Try to insert in secondary bucket. */ + bucket = hash2 & ((ZU(1) << ckh->lg_curbuckets) - 1); + if (ckh_try_bucket_insert(ckh, bucket, key, data) == false) + return (false); + + /* + * Try to find a place for this item via iterative eviction/relocation. + */ + return (ckh_evict_reloc_insert(ckh, bucket, argkey, argdata)); +} + +/* + * Try to rebuild the hash table from scratch by inserting all items from the + * old table into the new. + */ +JEMALLOC_INLINE bool +ckh_rebuild(ckh_t *ckh, ckhc_t *aTab) +{ + size_t count, i, nins; + const void *key, *data; + + count = ckh->count; + ckh->count = 0; + for (i = nins = 0; nins < count; i++) { + if (aTab[i].key != NULL) { + key = aTab[i].key; + data = aTab[i].data; + if (ckh_try_insert(ckh, &key, &data)) { + ckh->count = count; + return (true); + } + nins++; + } + } + + return (false); +} + +static bool +ckh_grow(ckh_t *ckh) +{ + bool ret; + ckhc_t *tab, *ttab; + size_t lg_curcells; + unsigned lg_prevbuckets; + +#ifdef CKH_COUNT + ckh->ngrows++; +#endif + + /* + * It is possible (though unlikely, given well behaved hashes) that the + * table will have to be doubled more than once in order to create a + * usable table. + */ + lg_prevbuckets = ckh->lg_curbuckets; + lg_curcells = ckh->lg_curbuckets + LG_CKH_BUCKET_CELLS; + while (true) { + lg_curcells++; + tab = (ckhc_t *) ipalloc((ZU(1) << LG_CACHELINE), + sizeof(ckhc_t) << lg_curcells); + if (tab == NULL) { + ret = true; + goto RETURN; + } + memset(tab, 0, sizeof(ckhc_t) << lg_curcells); + /* Swap in new table. */ + ttab = ckh->tab; + ckh->tab = tab; + tab = ttab; + ckh->lg_curbuckets = lg_curcells - LG_CKH_BUCKET_CELLS; + + if (ckh_rebuild(ckh, tab) == false) { + idalloc(tab); + break; + } + + /* Rebuilding failed, so back out partially rebuilt table. */ + idalloc(ckh->tab); + ckh->tab = tab; + ckh->lg_curbuckets = lg_prevbuckets; + } + + ret = false; +RETURN: + return (ret); +} + +static void +ckh_shrink(ckh_t *ckh) +{ + ckhc_t *tab, *ttab; + size_t lg_curcells; + unsigned lg_prevbuckets; + + /* + * It is possible (though unlikely, given well behaved hashes) that the + * table rebuild will fail. + */ + lg_prevbuckets = ckh->lg_curbuckets; + lg_curcells = ckh->lg_curbuckets + LG_CKH_BUCKET_CELLS - 1; + tab = (ckhc_t *)ipalloc((ZU(1) << LG_CACHELINE), + sizeof(ckhc_t) << lg_curcells); + if (tab == NULL) { + /* + * An OOM error isn't worth propagating, since it doesn't + * prevent this or future operations from proceeding. + */ + return; + } + memset(tab, 0, sizeof(ckhc_t) << lg_curcells); + /* Swap in new table. */ + ttab = ckh->tab; + ckh->tab = tab; + tab = ttab; + ckh->lg_curbuckets = lg_curcells - LG_CKH_BUCKET_CELLS; + + if (ckh_rebuild(ckh, tab) == false) { + idalloc(tab); +#ifdef CKH_COUNT + ckh->nshrinks++; +#endif + return; + } + + /* Rebuilding failed, so back out partially rebuilt table. */ + idalloc(ckh->tab); + ckh->tab = tab; + ckh->lg_curbuckets = lg_prevbuckets; +#ifdef CKH_COUNT + ckh->nshrinkfails++; +#endif +} + +bool +ckh_new(ckh_t *ckh, size_t minitems, ckh_hash_t *hash, ckh_keycomp_t *keycomp) +{ + bool ret; + size_t mincells; + unsigned lg_mincells; + + assert(minitems > 0); + assert(hash != NULL); + assert(keycomp != NULL); + +#ifdef CKH_COUNT + ckh->ngrows = 0; + ckh->nshrinks = 0; + ckh->nshrinkfails = 0; + ckh->ninserts = 0; + ckh->nrelocs = 0; +#endif + ckh->prn_state = 42; /* Value doesn't really matter. */ + ckh->count = 0; + + /* + * Find the minimum power of 2 that is large enough to fit aBaseCount + * entries. We are using (2+,2) cuckoo hashing, which has an expected + * maximum load factor of at least ~0.86, so 0.75 is a conservative load + * factor that will typically allow 2^aLgMinItems to fit without ever + * growing the table. + */ + assert(LG_CKH_BUCKET_CELLS > 0); + mincells = ((minitems + (3 - (minitems % 3))) / 3) << 2; + for (lg_mincells = LG_CKH_BUCKET_CELLS; + (ZU(1) << lg_mincells) < mincells; + lg_mincells++) + ; /* Do nothing. */ + ckh->lg_minbuckets = lg_mincells - LG_CKH_BUCKET_CELLS; + ckh->lg_curbuckets = lg_mincells - LG_CKH_BUCKET_CELLS; + ckh->hash = hash; + ckh->keycomp = keycomp; + + ckh->tab = (ckhc_t *)ipalloc((ZU(1) << LG_CACHELINE), + sizeof(ckhc_t) << lg_mincells); + if (ckh->tab == NULL) { + ret = true; + goto RETURN; + } + memset(ckh->tab, 0, sizeof(ckhc_t) << lg_mincells); + +#ifdef JEMALLOC_DEBUG + ckh->magic = CKH_MAGIG; +#endif + + ret = false; +RETURN: + return (ret); +} + +void +ckh_delete(ckh_t *ckh) +{ + + assert(ckh != NULL); + assert(ckh->magic = CKH_MAGIG); + +#ifdef CKH_VERBOSE + malloc_printf( + "%s(%p): ngrows: %"PRIu64", nshrinks: %"PRIu64"," + " nshrinkfails: %"PRIu64", ninserts: %"PRIu64"," + " nrelocs: %"PRIu64"\n", __func__, ckh, + (unsigned long long)ckh->ngrows, + (unsigned long long)ckh->nshrinks, + (unsigned long long)ckh->nshrinkfails, + (unsigned long long)ckh->ninserts, + (unsigned long long)ckh->nrelocs); +#endif + + idalloc(ckh->tab); +#ifdef JEMALLOC_DEBUG + memset(ckh, 0x5a, sizeof(ckh_t)); +#endif +} + +size_t +ckh_count(ckh_t *ckh) +{ + + assert(ckh != NULL); + assert(ckh->magic = CKH_MAGIG); + + return (ckh->count); +} + +bool +ckh_iter(ckh_t *ckh, size_t *tabind, void **key, void **data) +{ + size_t i, ncells; + + for (i = *tabind, ncells = (ZU(1) << (ckh->lg_curbuckets + + LG_CKH_BUCKET_CELLS)); i < ncells; i++) { + if (ckh->tab[i].key != NULL) { + if (key != NULL) + *key = (void *)ckh->tab[i].key; + if (data != NULL) + *data = (void *)ckh->tab[i].data; + *tabind = i + 1; + return (false); + } + } + + return (true); +} + +bool +ckh_insert(ckh_t *ckh, const void *key, const void *data) +{ + bool ret; + + assert(ckh != NULL); + assert(ckh->magic = CKH_MAGIG); + assert(ckh_search(ckh, key, NULL, NULL)); + +#ifdef CKH_COUNT + ckh->ninserts++; +#endif + + while (ckh_try_insert(ckh, &key, &data)) { + if (ckh_grow(ckh)) { + ret = true; + goto RETURN; + } + } + + ret = false; +RETURN: + return (ret); +} + +bool +ckh_remove(ckh_t *ckh, const void *searchkey, void **key, void **data) +{ + size_t cell; + + assert(ckh != NULL); + assert(ckh->magic = CKH_MAGIG); + + cell = ckh_isearch(ckh, searchkey); + if (cell != SIZE_T_MAX) { + if (key != NULL) + *key = (void *)ckh->tab[cell].key; + if (data != NULL) + *data = (void *)ckh->tab[cell].data; + ckh->tab[cell].key = NULL; + ckh->tab[cell].data = NULL; /* Not necessary. */ + + ckh->count--; + /* Try to halve the table if it is less than 1/4 full. */ + if (ckh->count < (ZU(1) << (ckh->lg_curbuckets + + LG_CKH_BUCKET_CELLS - 2)) && ckh->lg_curbuckets + > ckh->lg_minbuckets) { + /* Ignore error due to OOM. */ + ckh_shrink(ckh); + } + + return (false); + } + + return (true); +} + +bool +ckh_search(ckh_t *ckh, const void *searchkey, void **key, void **data) +{ + size_t cell; + + assert(ckh != NULL); + assert(ckh->magic = CKH_MAGIG); + + cell = ckh_isearch(ckh, searchkey); + if (cell != SIZE_T_MAX) { + if (key != NULL) + *key = (void *)ckh->tab[cell].key; + if (data != NULL) + *data = (void *)ckh->tab[cell].data; + return (false); + } + + return (true); +} + +void +ckh_string_hash(const void *key, unsigned minbits, size_t *hash1, size_t *hash2) +{ + size_t ret1, ret2; + uint64_t h; + + assert(minbits <= 32 || (SIZEOF_PTR == 8 && minbits <= 64)); + assert(hash1 != NULL); + assert(hash2 != NULL); + + h = hash(key, strlen((const char *)key), 0x94122f335b332aeaLLU); + if (minbits <= 32) { + /* + * Avoid doing multiple hashes, since a single hash provides + * enough bits. + */ + ret1 = h & ZU(0xffffffffU); + ret2 = h >> 32; + } else { + ret1 = h; + ret2 = hash(key, strlen((const char *)key), + 0x8432a476666bbc13U); + } + + *hash1 = ret1; + *hash2 = ret2; +} + +bool +ckh_string_keycomp(const void *k1, const void *k2) +{ + + assert(k1 != NULL); + assert(k2 != NULL); + + return (strcmp((char *)k1, (char *)k2) ? false : true); +} + +void +ckh_pointer_hash(const void *key, unsigned minbits, size_t *hash1, + size_t *hash2) +{ + size_t ret1, ret2; + uint64_t h; + + assert(minbits <= 32 || (SIZEOF_PTR == 8 && minbits <= 64)); + assert(hash1 != NULL); + assert(hash2 != NULL); + + h = hash(&key, sizeof(void *), 0xd983396e68886082LLU); + if (minbits <= 32) { + /* + * Avoid doing multiple hashes, since a single hash provides + * enough bits. + */ + ret1 = h & ZU(0xffffffffU); + ret2 = h >> 32; + } else { + assert(SIZEOF_PTR == 8); + ret1 = h; + ret2 = hash(&key, sizeof(void *), 0x5e2be9aff8709a5dLLU); + } + + *hash1 = ret1; + *hash2 = ret2; +} + +bool +ckh_pointer_keycomp(const void *k1, const void *k2) +{ + + return ((k1 == k2) ? true : false); +} diff --git a/dep/jemalloc/ctl.c b/dep/jemalloc/ctl.c new file mode 100644 index 00000000000..ffb732d5bef --- /dev/null +++ b/dep/jemalloc/ctl.c @@ -0,0 +1,1482 @@ +#define JEMALLOC_CTL_C_ +#include "jemalloc/internal/jemalloc_internal.h" + +/******************************************************************************/ +/* Data. */ + +static malloc_mutex_t ctl_mtx; +static bool ctl_initialized; +static uint64_t ctl_epoch; +static ctl_stats_t ctl_stats; + +/******************************************************************************/ +/* Function prototypes for non-inline static functions. */ + +#define CTL_PROTO(n) \ +static int n##_ctl(const size_t *mib, size_t miblen, void *oldp, \ + size_t *oldlenp, void *newp, size_t newlen); + +#define INDEX_PROTO(n) \ +const ctl_node_t *n##_index(const size_t *mib, size_t miblen, \ + size_t i); + +#ifdef JEMALLOC_STATS +static bool ctl_arena_init(ctl_arena_stats_t *astats); +#endif +static void ctl_arena_clear(ctl_arena_stats_t *astats); +#ifdef JEMALLOC_STATS +static void ctl_arena_stats_amerge(ctl_arena_stats_t *cstats, + arena_t *arena); +static void ctl_arena_stats_smerge(ctl_arena_stats_t *sstats, + ctl_arena_stats_t *astats); +#endif +static void ctl_arena_refresh(arena_t *arena, unsigned i); +static void ctl_refresh(void); +static bool ctl_init(void); +static int ctl_lookup(const char *name, ctl_node_t const **nodesp, + size_t *mibp, size_t *depthp); + +CTL_PROTO(version) +CTL_PROTO(epoch) +#ifdef JEMALLOC_TCACHE +CTL_PROTO(tcache_flush) +#endif +CTL_PROTO(config_debug) +CTL_PROTO(config_dss) +CTL_PROTO(config_dynamic_page_shift) +CTL_PROTO(config_fill) +CTL_PROTO(config_lazy_lock) +CTL_PROTO(config_prof) +CTL_PROTO(config_prof_libgcc) +CTL_PROTO(config_prof_libunwind) +CTL_PROTO(config_stats) +CTL_PROTO(config_swap) +CTL_PROTO(config_sysv) +CTL_PROTO(config_tcache) +CTL_PROTO(config_tiny) +CTL_PROTO(config_tls) +CTL_PROTO(config_xmalloc) +CTL_PROTO(opt_abort) +#ifdef JEMALLOC_FILL +CTL_PROTO(opt_junk) +#endif +#ifdef JEMALLOC_SYSV +CTL_PROTO(opt_sysv) +#endif +#ifdef JEMALLOC_XMALLOC +CTL_PROTO(opt_xmalloc) +#endif +#ifdef JEMALLOC_ZERO +CTL_PROTO(opt_zero) +#endif +#ifdef JEMALLOC_TCACHE +CTL_PROTO(opt_tcache) +CTL_PROTO(opt_lg_tcache_gc_sweep) +#endif +#ifdef JEMALLOC_PROF +CTL_PROTO(opt_prof) +CTL_PROTO(opt_prof_active) +CTL_PROTO(opt_lg_prof_bt_max) +CTL_PROTO(opt_lg_prof_sample) +CTL_PROTO(opt_lg_prof_interval) +CTL_PROTO(opt_prof_udump) +CTL_PROTO(opt_prof_leak) +#endif +CTL_PROTO(opt_stats_print) +CTL_PROTO(opt_lg_qspace_max) +CTL_PROTO(opt_lg_cspace_max) +CTL_PROTO(opt_lg_dirty_mult) +CTL_PROTO(opt_lg_chunk) +#ifdef JEMALLOC_SWAP +CTL_PROTO(opt_overcommit) +#endif +CTL_PROTO(arenas_bin_i_size) +CTL_PROTO(arenas_bin_i_nregs) +CTL_PROTO(arenas_bin_i_run_size) +INDEX_PROTO(arenas_bin_i) +CTL_PROTO(arenas_lrun_i_size) +INDEX_PROTO(arenas_lrun_i) +CTL_PROTO(arenas_narenas) +CTL_PROTO(arenas_initialized) +CTL_PROTO(arenas_quantum) +CTL_PROTO(arenas_cacheline) +CTL_PROTO(arenas_subpage) +CTL_PROTO(arenas_pagesize) +CTL_PROTO(arenas_chunksize) +#ifdef JEMALLOC_TINY +CTL_PROTO(arenas_tspace_min) +CTL_PROTO(arenas_tspace_max) +#endif +CTL_PROTO(arenas_qspace_min) +CTL_PROTO(arenas_qspace_max) +CTL_PROTO(arenas_cspace_min) +CTL_PROTO(arenas_cspace_max) +CTL_PROTO(arenas_sspace_min) +CTL_PROTO(arenas_sspace_max) +#ifdef JEMALLOC_TCACHE +CTL_PROTO(arenas_tcache_max) +#endif +CTL_PROTO(arenas_ntbins) +CTL_PROTO(arenas_nqbins) +CTL_PROTO(arenas_ncbins) +CTL_PROTO(arenas_nsbins) +CTL_PROTO(arenas_nbins) +#ifdef JEMALLOC_TCACHE +CTL_PROTO(arenas_nhbins) +#endif +CTL_PROTO(arenas_nlruns) +#ifdef JEMALLOC_PROF +CTL_PROTO(prof_active) +CTL_PROTO(prof_dump) +CTL_PROTO(prof_interval) +#endif +#ifdef JEMALLOC_STATS +CTL_PROTO(stats_chunks_current) +CTL_PROTO(stats_chunks_total) +CTL_PROTO(stats_chunks_high) +CTL_PROTO(stats_huge_allocated) +CTL_PROTO(stats_huge_nmalloc) +CTL_PROTO(stats_huge_ndalloc) +CTL_PROTO(stats_arenas_i_small_allocated) +CTL_PROTO(stats_arenas_i_small_nmalloc) +CTL_PROTO(stats_arenas_i_small_ndalloc) +CTL_PROTO(stats_arenas_i_small_nrequests) +CTL_PROTO(stats_arenas_i_large_allocated) +CTL_PROTO(stats_arenas_i_large_nmalloc) +CTL_PROTO(stats_arenas_i_large_ndalloc) +CTL_PROTO(stats_arenas_i_large_nrequests) +CTL_PROTO(stats_arenas_i_bins_j_allocated) +CTL_PROTO(stats_arenas_i_bins_j_nmalloc) +CTL_PROTO(stats_arenas_i_bins_j_ndalloc) +CTL_PROTO(stats_arenas_i_bins_j_nrequests) +#ifdef JEMALLOC_TCACHE +CTL_PROTO(stats_arenas_i_bins_j_nfills) +CTL_PROTO(stats_arenas_i_bins_j_nflushes) +#endif +CTL_PROTO(stats_arenas_i_bins_j_nruns) +CTL_PROTO(stats_arenas_i_bins_j_nreruns) +CTL_PROTO(stats_arenas_i_bins_j_highruns) +CTL_PROTO(stats_arenas_i_bins_j_curruns) +INDEX_PROTO(stats_arenas_i_bins_j) +CTL_PROTO(stats_arenas_i_lruns_j_nmalloc) +CTL_PROTO(stats_arenas_i_lruns_j_ndalloc) +CTL_PROTO(stats_arenas_i_lruns_j_nrequests) +CTL_PROTO(stats_arenas_i_lruns_j_highruns) +CTL_PROTO(stats_arenas_i_lruns_j_curruns) +INDEX_PROTO(stats_arenas_i_lruns_j) +#endif +CTL_PROTO(stats_arenas_i_pactive) +CTL_PROTO(stats_arenas_i_pdirty) +#ifdef JEMALLOC_STATS +CTL_PROTO(stats_arenas_i_mapped) +CTL_PROTO(stats_arenas_i_npurge) +CTL_PROTO(stats_arenas_i_nmadvise) +CTL_PROTO(stats_arenas_i_purged) +#endif +INDEX_PROTO(stats_arenas_i) +#ifdef JEMALLOC_STATS +CTL_PROTO(stats_allocated) +CTL_PROTO(stats_active) +CTL_PROTO(stats_mapped) +#endif +#ifdef JEMALLOC_SWAP +# ifdef JEMALLOC_STATS +CTL_PROTO(swap_avail) +# endif +CTL_PROTO(swap_prezeroed) +CTL_PROTO(swap_nfds) +CTL_PROTO(swap_fds) +#endif + +/******************************************************************************/ +/* mallctl tree. */ + +/* Maximum tree depth. */ +#define CTL_MAX_DEPTH 6 + +#define NAME(n) true, {.named = {n +#define CHILD(c) sizeof(c##_node) / sizeof(ctl_node_t), c##_node}}, NULL +#define CTL(c) 0, NULL}}, c##_ctl + +/* + * Only handles internal indexed nodes, since there are currently no external + * ones. + */ +#define INDEX(i) false, {.indexed = {i##_index}}, NULL + +#ifdef JEMALLOC_TCACHE +static const ctl_node_t tcache_node[] = { + {NAME("flush"), CTL(tcache_flush)} +}; +#endif + +static const ctl_node_t config_node[] = { + {NAME("debug"), CTL(config_debug)}, + {NAME("dss"), CTL(config_dss)}, + {NAME("dynamic_page_shift"), CTL(config_dynamic_page_shift)}, + {NAME("fill"), CTL(config_fill)}, + {NAME("lazy_lock"), CTL(config_lazy_lock)}, + {NAME("prof"), CTL(config_prof)}, + {NAME("prof_libgcc"), CTL(config_prof_libgcc)}, + {NAME("prof_libunwind"), CTL(config_prof_libunwind)}, + {NAME("stats"), CTL(config_stats)}, + {NAME("swap"), CTL(config_swap)}, + {NAME("sysv"), CTL(config_sysv)}, + {NAME("tcache"), CTL(config_tcache)}, + {NAME("tiny"), CTL(config_tiny)}, + {NAME("tls"), CTL(config_tls)}, + {NAME("xmalloc"), CTL(config_xmalloc)} +}; + +static const ctl_node_t opt_node[] = { + {NAME("abort"), CTL(opt_abort)}, +#ifdef JEMALLOC_FILL + {NAME("junk"), CTL(opt_junk)}, +#endif +#ifdef JEMALLOC_SYSV + {NAME("sysv"), CTL(opt_sysv)}, +#endif +#ifdef JEMALLOC_XMALLOC + {NAME("xmalloc"), CTL(opt_xmalloc)}, +#endif +#ifdef JEMALLOC_ZERO + {NAME("zero"), CTL(opt_zero)}, +#endif +#ifdef JEMALLOC_TCACHE + {NAME("tcache"), CTL(opt_tcache)}, + {NAME("lg_tcache_gc_sweep"), CTL(opt_lg_tcache_gc_sweep)}, +#endif +#ifdef JEMALLOC_PROF + {NAME("prof"), CTL(opt_prof)}, + {NAME("prof_active"), CTL(opt_prof_active)}, + {NAME("lg_prof_bt_max"), CTL(opt_lg_prof_bt_max)}, + {NAME("lg_prof_sample"), CTL(opt_lg_prof_sample)}, + {NAME("lg_prof_interval"), CTL(opt_lg_prof_interval)}, + {NAME("prof_udump"), CTL(opt_prof_udump)}, + {NAME("prof_leak"), CTL(opt_prof_leak)}, +#endif + {NAME("stats_print"), CTL(opt_stats_print)}, + {NAME("lg_qspace_max"), CTL(opt_lg_qspace_max)}, + {NAME("lg_cspace_max"), CTL(opt_lg_cspace_max)}, + {NAME("lg_dirty_mult"), CTL(opt_lg_dirty_mult)}, + {NAME("lg_chunk"), CTL(opt_lg_chunk)} +#ifdef JEMALLOC_SWAP + , + {NAME("overcommit"), CTL(opt_overcommit)} +#endif +}; + +static const ctl_node_t arenas_bin_i_node[] = { + {NAME("size"), CTL(arenas_bin_i_size)}, + {NAME("nregs"), CTL(arenas_bin_i_nregs)}, + {NAME("run_size"), CTL(arenas_bin_i_run_size)} +}; +static const ctl_node_t super_arenas_bin_i_node[] = { + {NAME(""), CHILD(arenas_bin_i)} +}; + +static const ctl_node_t arenas_bin_node[] = { + {INDEX(arenas_bin_i)} +}; + +static const ctl_node_t arenas_lrun_i_node[] = { + {NAME("size"), CTL(arenas_lrun_i_size)} +}; +static const ctl_node_t super_arenas_lrun_i_node[] = { + {NAME(""), CHILD(arenas_lrun_i)} +}; + +static const ctl_node_t arenas_lrun_node[] = { + {INDEX(arenas_lrun_i)} +}; + +static const ctl_node_t arenas_node[] = { + {NAME("narenas"), CTL(arenas_narenas)}, + {NAME("initialized"), CTL(arenas_initialized)}, + {NAME("quantum"), CTL(arenas_quantum)}, + {NAME("cacheline"), CTL(arenas_cacheline)}, + {NAME("subpage"), CTL(arenas_subpage)}, + {NAME("pagesize"), CTL(arenas_pagesize)}, + {NAME("chunksize"), CTL(arenas_chunksize)}, +#ifdef JEMALLOC_TINY + {NAME("tspace_min"), CTL(arenas_tspace_min)}, + {NAME("tspace_max"), CTL(arenas_tspace_max)}, +#endif + {NAME("qspace_min"), CTL(arenas_qspace_min)}, + {NAME("qspace_max"), CTL(arenas_qspace_max)}, + {NAME("cspace_min"), CTL(arenas_cspace_min)}, + {NAME("cspace_max"), CTL(arenas_cspace_max)}, + {NAME("sspace_min"), CTL(arenas_sspace_min)}, + {NAME("sspace_max"), CTL(arenas_sspace_max)}, +#ifdef JEMALLOC_TCACHE + {NAME("tcache_max"), CTL(arenas_tcache_max)}, +#endif + {NAME("ntbins"), CTL(arenas_ntbins)}, + {NAME("nqbins"), CTL(arenas_nqbins)}, + {NAME("ncbins"), CTL(arenas_ncbins)}, + {NAME("nsbins"), CTL(arenas_nsbins)}, + {NAME("nbins"), CTL(arenas_nbins)}, +#ifdef JEMALLOC_TCACHE + {NAME("nhbins"), CTL(arenas_nhbins)}, +#endif + {NAME("bin"), CHILD(arenas_bin)}, + {NAME("nlruns"), CTL(arenas_nlruns)}, + {NAME("lrun"), CHILD(arenas_lrun)} +}; + +#ifdef JEMALLOC_PROF +static const ctl_node_t prof_node[] = { + {NAME("active"), CTL(prof_active)}, + {NAME("dump"), CTL(prof_dump)}, + {NAME("interval"), CTL(prof_interval)} +}; +#endif + +#ifdef JEMALLOC_STATS +static const ctl_node_t stats_chunks_node[] = { + {NAME("current"), CTL(stats_chunks_current)}, + {NAME("total"), CTL(stats_chunks_total)}, + {NAME("high"), CTL(stats_chunks_high)} +}; + +static const ctl_node_t stats_huge_node[] = { + {NAME("allocated"), CTL(stats_huge_allocated)}, + {NAME("nmalloc"), CTL(stats_huge_nmalloc)}, + {NAME("ndalloc"), CTL(stats_huge_ndalloc)} +}; + +static const ctl_node_t stats_arenas_i_small_node[] = { + {NAME("allocated"), CTL(stats_arenas_i_small_allocated)}, + {NAME("nmalloc"), CTL(stats_arenas_i_small_nmalloc)}, + {NAME("ndalloc"), CTL(stats_arenas_i_small_ndalloc)}, + {NAME("nrequests"), CTL(stats_arenas_i_small_nrequests)} +}; + +static const ctl_node_t stats_arenas_i_large_node[] = { + {NAME("allocated"), CTL(stats_arenas_i_large_allocated)}, + {NAME("nmalloc"), CTL(stats_arenas_i_large_nmalloc)}, + {NAME("ndalloc"), CTL(stats_arenas_i_large_ndalloc)}, + {NAME("nrequests"), CTL(stats_arenas_i_large_nrequests)} +}; + +static const ctl_node_t stats_arenas_i_bins_j_node[] = { + {NAME("allocated"), CTL(stats_arenas_i_bins_j_allocated)}, + {NAME("nmalloc"), CTL(stats_arenas_i_bins_j_nmalloc)}, + {NAME("ndalloc"), CTL(stats_arenas_i_bins_j_ndalloc)}, + {NAME("nrequests"), CTL(stats_arenas_i_bins_j_nrequests)}, +#ifdef JEMALLOC_TCACHE + {NAME("nfills"), CTL(stats_arenas_i_bins_j_nfills)}, + {NAME("nflushes"), CTL(stats_arenas_i_bins_j_nflushes)}, +#endif + {NAME("nruns"), CTL(stats_arenas_i_bins_j_nruns)}, + {NAME("nreruns"), CTL(stats_arenas_i_bins_j_nreruns)}, + {NAME("highruns"), CTL(stats_arenas_i_bins_j_highruns)}, + {NAME("curruns"), CTL(stats_arenas_i_bins_j_curruns)} +}; +static const ctl_node_t super_stats_arenas_i_bins_j_node[] = { + {NAME(""), CHILD(stats_arenas_i_bins_j)} +}; + +static const ctl_node_t stats_arenas_i_bins_node[] = { + {INDEX(stats_arenas_i_bins_j)} +}; + +static const ctl_node_t stats_arenas_i_lruns_j_node[] = { + {NAME("nmalloc"), CTL(stats_arenas_i_lruns_j_nmalloc)}, + {NAME("ndalloc"), CTL(stats_arenas_i_lruns_j_ndalloc)}, + {NAME("nrequests"), CTL(stats_arenas_i_lruns_j_nrequests)}, + {NAME("highruns"), CTL(stats_arenas_i_lruns_j_highruns)}, + {NAME("curruns"), CTL(stats_arenas_i_lruns_j_curruns)} +}; +static const ctl_node_t super_stats_arenas_i_lruns_j_node[] = { + {NAME(""), CHILD(stats_arenas_i_lruns_j)} +}; + +static const ctl_node_t stats_arenas_i_lruns_node[] = { + {INDEX(stats_arenas_i_lruns_j)} +}; +#endif + +static const ctl_node_t stats_arenas_i_node[] = { + {NAME("pactive"), CTL(stats_arenas_i_pactive)}, + {NAME("pdirty"), CTL(stats_arenas_i_pdirty)} +#ifdef JEMALLOC_STATS + , + {NAME("mapped"), CTL(stats_arenas_i_mapped)}, + {NAME("npurge"), CTL(stats_arenas_i_npurge)}, + {NAME("nmadvise"), CTL(stats_arenas_i_nmadvise)}, + {NAME("purged"), CTL(stats_arenas_i_purged)}, + {NAME("small"), CHILD(stats_arenas_i_small)}, + {NAME("large"), CHILD(stats_arenas_i_large)}, + {NAME("bins"), CHILD(stats_arenas_i_bins)}, + {NAME("lruns"), CHILD(stats_arenas_i_lruns)} +#endif +}; +static const ctl_node_t super_stats_arenas_i_node[] = { + {NAME(""), CHILD(stats_arenas_i)} +}; + +static const ctl_node_t stats_arenas_node[] = { + {INDEX(stats_arenas_i)} +}; + +static const ctl_node_t stats_node[] = { +#ifdef JEMALLOC_STATS + {NAME("allocated"), CTL(stats_allocated)}, + {NAME("active"), CTL(stats_active)}, + {NAME("mapped"), CTL(stats_mapped)}, + {NAME("chunks"), CHILD(stats_chunks)}, + {NAME("huge"), CHILD(stats_huge)}, +#endif + {NAME("arenas"), CHILD(stats_arenas)} +}; + +#ifdef JEMALLOC_SWAP +static const ctl_node_t swap_node[] = { +# ifdef JEMALLOC_STATS + {NAME("avail"), CTL(swap_avail)}, +# endif + {NAME("prezeroed"), CTL(swap_prezeroed)}, + {NAME("nfds"), CTL(swap_nfds)}, + {NAME("fds"), CTL(swap_fds)} +}; +#endif + +static const ctl_node_t root_node[] = { + {NAME("version"), CTL(version)}, + {NAME("epoch"), CTL(epoch)}, +#ifdef JEMALLOC_TCACHE + {NAME("tcache"), CHILD(tcache)}, +#endif + {NAME("config"), CHILD(config)}, + {NAME("opt"), CHILD(opt)}, + {NAME("arenas"), CHILD(arenas)}, +#ifdef JEMALLOC_PROF + {NAME("prof"), CHILD(prof)}, +#endif + {NAME("stats"), CHILD(stats)} +#ifdef JEMALLOC_SWAP + , + {NAME("swap"), CHILD(swap)} +#endif +}; +static const ctl_node_t super_root_node[] = { + {NAME(""), CHILD(root)} +}; + +#undef NAME +#undef CHILD +#undef CTL +#undef INDEX + +/******************************************************************************/ + +#ifdef JEMALLOC_STATS +static bool +ctl_arena_init(ctl_arena_stats_t *astats) +{ + + if (astats->bstats == NULL) { + astats->bstats = (malloc_bin_stats_t *)base_alloc(nbins * + sizeof(malloc_bin_stats_t)); + if (astats->bstats == NULL) + return (true); + } + if (astats->lstats == NULL) { + astats->lstats = (malloc_large_stats_t *)base_alloc(nlclasses * + sizeof(malloc_large_stats_t)); + if (astats->lstats == NULL) + return (true); + } + + return (false); +} +#endif + +static void +ctl_arena_clear(ctl_arena_stats_t *astats) +{ + + astats->pactive = 0; + astats->pdirty = 0; +#ifdef JEMALLOC_STATS + memset(&astats->astats, 0, sizeof(arena_stats_t)); + astats->allocated_small = 0; + astats->nmalloc_small = 0; + astats->ndalloc_small = 0; + astats->nrequests_small = 0; + memset(astats->bstats, 0, nbins * sizeof(malloc_bin_stats_t)); + memset(astats->lstats, 0, nlclasses * sizeof(malloc_large_stats_t)); +#endif +} + +#ifdef JEMALLOC_STATS +static void +ctl_arena_stats_amerge(ctl_arena_stats_t *cstats, arena_t *arena) +{ + unsigned i; + + arena_stats_merge(arena, &cstats->pactive, &cstats->pdirty, + &cstats->astats, cstats->bstats, cstats->lstats); + + for (i = 0; i < nbins; i++) { + cstats->allocated_small += cstats->bstats[i].allocated; + cstats->nmalloc_small += cstats->bstats[i].nmalloc; + cstats->ndalloc_small += cstats->bstats[i].ndalloc; + cstats->nrequests_small += cstats->bstats[i].nrequests; + } +} + +static void +ctl_arena_stats_smerge(ctl_arena_stats_t *sstats, ctl_arena_stats_t *astats) +{ + unsigned i; + + sstats->pactive += astats->pactive; + sstats->pdirty += astats->pdirty; + + sstats->astats.mapped += astats->astats.mapped; + sstats->astats.npurge += astats->astats.npurge; + sstats->astats.nmadvise += astats->astats.nmadvise; + sstats->astats.purged += astats->astats.purged; + + sstats->allocated_small += astats->allocated_small; + sstats->nmalloc_small += astats->nmalloc_small; + sstats->ndalloc_small += astats->ndalloc_small; + sstats->nrequests_small += astats->nrequests_small; + + sstats->astats.allocated_large += astats->astats.allocated_large; + sstats->astats.nmalloc_large += astats->astats.nmalloc_large; + sstats->astats.ndalloc_large += astats->astats.ndalloc_large; + sstats->astats.nrequests_large += astats->astats.nrequests_large; + + for (i = 0; i < nlclasses; i++) { + sstats->lstats[i].nmalloc += astats->lstats[i].nmalloc; + sstats->lstats[i].ndalloc += astats->lstats[i].ndalloc; + sstats->lstats[i].nrequests += astats->lstats[i].nrequests; + sstats->lstats[i].highruns += astats->lstats[i].highruns; + sstats->lstats[i].curruns += astats->lstats[i].curruns; + } + + for (i = 0; i < nbins; i++) { + sstats->bstats[i].allocated += astats->bstats[i].allocated; + sstats->bstats[i].nmalloc += astats->bstats[i].nmalloc; + sstats->bstats[i].ndalloc += astats->bstats[i].ndalloc; + sstats->bstats[i].nrequests += astats->bstats[i].nrequests; +#ifdef JEMALLOC_TCACHE + sstats->bstats[i].nfills += astats->bstats[i].nfills; + sstats->bstats[i].nflushes += astats->bstats[i].nflushes; +#endif + sstats->bstats[i].nruns += astats->bstats[i].nruns; + sstats->bstats[i].reruns += astats->bstats[i].reruns; + sstats->bstats[i].highruns += astats->bstats[i].highruns; + sstats->bstats[i].curruns += astats->bstats[i].curruns; + } +} +#endif + +static void +ctl_arena_refresh(arena_t *arena, unsigned i) +{ + ctl_arena_stats_t *astats = &ctl_stats.arenas[i]; + ctl_arena_stats_t *sstats = &ctl_stats.arenas[narenas]; + + ctl_arena_clear(astats); + +#ifdef JEMALLOC_STATS + ctl_arena_stats_amerge(astats, arena); + /* Merge into sum stats as well. */ + ctl_arena_stats_smerge(sstats, astats); +#else + astats->pactive += arena->nactive; + astats->pdirty += arena->ndirty; + /* Merge into sum stats as well. */ + sstats->pactive += arena->nactive; + sstats->pdirty += arena->ndirty; +#endif +} + +static void +ctl_refresh(void) +{ + unsigned i; + arena_t *tarenas[narenas]; + +#ifdef JEMALLOC_STATS + malloc_mutex_lock(&chunks_mtx); + ctl_stats.chunks.current = stats_chunks.curchunks; + ctl_stats.chunks.total = stats_chunks.nchunks; + ctl_stats.chunks.high = stats_chunks.highchunks; + malloc_mutex_unlock(&chunks_mtx); + + malloc_mutex_lock(&huge_mtx); + ctl_stats.huge.allocated = huge_allocated; + ctl_stats.huge.nmalloc = huge_nmalloc; + ctl_stats.huge.ndalloc = huge_ndalloc; + malloc_mutex_unlock(&huge_mtx); +#endif + + /* + * Clear sum stats, since they will be merged into by + * ctl_arena_refresh(). + */ + ctl_arena_clear(&ctl_stats.arenas[narenas]); + + malloc_mutex_lock(&arenas_lock); + memcpy(tarenas, arenas, sizeof(arena_t *) * narenas); + malloc_mutex_unlock(&arenas_lock); + for (i = 0; i < narenas; i++) { + bool initialized = (tarenas[i] != NULL); + + ctl_stats.arenas[i].initialized = initialized; + if (initialized) + ctl_arena_refresh(tarenas[i], i); + } + +#ifdef JEMALLOC_STATS + ctl_stats.allocated = ctl_stats.arenas[narenas].allocated_small + + ctl_stats.arenas[narenas].astats.allocated_large + + ctl_stats.huge.allocated; + ctl_stats.active = (ctl_stats.arenas[narenas].pactive << PAGE_SHIFT) + + ctl_stats.huge.allocated; + ctl_stats.mapped = (ctl_stats.chunks.current << opt_lg_chunk); + +# ifdef JEMALLOC_SWAP + malloc_mutex_lock(&swap_mtx); + ctl_stats.swap_avail = swap_avail; + malloc_mutex_unlock(&swap_mtx); +# endif +#endif + + ctl_epoch++; +} + +static bool +ctl_init(void) +{ + + if (ctl_initialized == false) { +#ifdef JEMALLOC_STATS + unsigned i; +#endif + + /* + * Allocate space for one extra arena stats element, which + * contains summed stats across all arenas. + */ + ctl_stats.arenas = (ctl_arena_stats_t *)base_alloc( + (narenas + 1) * sizeof(ctl_arena_stats_t)); + if (ctl_stats.arenas == NULL) + return (true); + memset(ctl_stats.arenas, 0, (narenas + 1) * + sizeof(ctl_arena_stats_t)); + + /* + * Initialize all stats structures, regardless of whether they + * ever get used. Lazy initialization would allow errors to + * cause inconsistent state to be viewable by the application. + */ +#ifdef JEMALLOC_STATS + for (i = 0; i <= narenas; i++) { + if (ctl_arena_init(&ctl_stats.arenas[i])) + return (true); + } +#endif + ctl_stats.arenas[narenas].initialized = true; + + ctl_epoch = 0; + ctl_refresh(); + ctl_initialized = true; + } + + return (false); +} + +static int +ctl_lookup(const char *name, ctl_node_t const **nodesp, size_t *mibp, + size_t *depthp) +{ + int ret; + const char *elm, *tdot, *dot; + size_t elen, i, j; + const ctl_node_t *node; + + elm = name; + /* Equivalent to strchrnul(). */ + dot = ((tdot = strchr(elm, '.')) != NULL) ? tdot : strchr(elm, '\0'); + elen = (size_t)((uintptr_t)dot - (uintptr_t)elm); + if (elen == 0) { + ret = ENOENT; + goto RETURN; + } + node = super_root_node; + for (i = 0; i < *depthp; i++) { + assert(node->named); + assert(node->u.named.nchildren > 0); + if (node->u.named.children[0].named) { + const ctl_node_t *pnode = node; + + /* Children are named. */ + for (j = 0; j < node->u.named.nchildren; j++) { + const ctl_node_t *child = + &node->u.named.children[j]; + if (strlen(child->u.named.name) == elen + && strncmp(elm, child->u.named.name, + elen) == 0) { + node = child; + if (nodesp != NULL) + nodesp[i] = node; + mibp[i] = j; + break; + } + } + if (node == pnode) { + ret = ENOENT; + goto RETURN; + } + } else { + unsigned long index; + const ctl_node_t *inode; + + /* Children are indexed. */ + index = strtoul(elm, NULL, 10); + if (index == ULONG_MAX) { + ret = ENOENT; + goto RETURN; + } + + inode = &node->u.named.children[0]; + node = inode->u.indexed.index(mibp, *depthp, + index); + if (node == NULL) { + ret = ENOENT; + goto RETURN; + } + + if (nodesp != NULL) + nodesp[i] = node; + mibp[i] = (size_t)index; + } + + if (node->ctl != NULL) { + /* Terminal node. */ + if (*dot != '\0') { + /* + * The name contains more elements than are + * in this path through the tree. + */ + ret = ENOENT; + goto RETURN; + } + /* Complete lookup successful. */ + *depthp = i + 1; + break; + } + + /* Update elm. */ + if (*dot == '\0') { + /* No more elements. */ + ret = ENOENT; + goto RETURN; + } + elm = &dot[1]; + dot = ((tdot = strchr(elm, '.')) != NULL) ? tdot : + strchr(elm, '\0'); + elen = (size_t)((uintptr_t)dot - (uintptr_t)elm); + } + + ret = 0; +RETURN: + return (ret); +} + +int +ctl_byname(const char *name, void *oldp, size_t *oldlenp, void *newp, + size_t newlen) +{ + int ret; + size_t depth; + ctl_node_t const *nodes[CTL_MAX_DEPTH]; + size_t mib[CTL_MAX_DEPTH]; + + malloc_mutex_lock(&ctl_mtx); + if (ctl_init()) { + ret = EAGAIN; + goto RETURN; + } + + depth = CTL_MAX_DEPTH; + ret = ctl_lookup(name, nodes, mib, &depth); + if (ret != 0) + goto RETURN; + + if (nodes[depth-1]->ctl == NULL) { + /* The name refers to a partial path through the ctl tree. */ + ret = ENOENT; + goto RETURN; + } + ret = nodes[depth-1]->ctl(mib, depth, oldp, oldlenp, newp, newlen); + +RETURN: + malloc_mutex_unlock(&ctl_mtx); + return(ret); +} + +int +ctl_nametomib(const char *name, size_t *mibp, size_t *miblenp) +{ + int ret; + + malloc_mutex_lock(&ctl_mtx); + if (ctl_init()) { + ret = EAGAIN; + goto RETURN; + } + + ret = ctl_lookup(name, NULL, mibp, miblenp); + +RETURN: + malloc_mutex_unlock(&ctl_mtx); + return(ret); +} + +int +ctl_bymib(const size_t *mib, size_t miblen, void *oldp, size_t *oldlenp, + void *newp, size_t newlen) +{ + int ret; + const ctl_node_t *node; + size_t i; + + malloc_mutex_lock(&ctl_mtx); + if (ctl_init()) { + ret = EAGAIN; + goto RETURN; + } + + /* Iterate down the tree. */ + node = super_root_node; + for (i = 0; i < miblen; i++) { + if (node->u.named.children[0].named) { + /* Children are named. */ + if (node->u.named.nchildren <= mib[i]) { + ret = ENOENT; + goto RETURN; + } + node = &node->u.named.children[mib[i]]; + } else { + const ctl_node_t *inode; + + /* Indexed element. */ + inode = &node->u.named.children[0]; + node = inode->u.indexed.index(mib, miblen, mib[i]); + if (node == NULL) { + ret = ENOENT; + goto RETURN; + } + } + } + + /* Call the ctl function. */ + if (node->ctl == NULL) { + /* Partial MIB. */ + ret = ENOENT; + goto RETURN; + } + ret = node->ctl(mib, miblen, oldp, oldlenp, newp, newlen); + +RETURN: + malloc_mutex_unlock(&ctl_mtx); + return(ret); +} + +bool +ctl_boot(void) +{ + + if (malloc_mutex_init(&ctl_mtx)) + return (true); + + ctl_initialized = false; + + return (false); +} + +/******************************************************************************/ +/* *_ctl() functions. */ + +#define READONLY() do { \ + if (newp != NULL || newlen != 0) { \ + ret = EPERM; \ + goto RETURN; \ + } \ +} while (0) + +#define WRITEONLY() do { \ + if (oldp != NULL || oldlenp != NULL) { \ + ret = EPERM; \ + goto RETURN; \ + } \ +} while (0) + +#define VOID() do { \ + READONLY(); \ + WRITEONLY(); \ +} while (0) + +#define READ(v, t) do { \ + if (oldp != NULL && oldlenp != NULL) { \ + if (*oldlenp != sizeof(t)) { \ + size_t copylen = (sizeof(t) <= *oldlenp) \ + ? sizeof(t) : *oldlenp; \ + memcpy(oldp, (void *)&v, copylen); \ + ret = EINVAL; \ + goto RETURN; \ + } else \ + *(t *)oldp = v; \ + } \ +} while (0) + +#define WRITE(v, t) do { \ + if (newp != NULL) { \ + if (newlen != sizeof(t)) { \ + ret = EINVAL; \ + goto RETURN; \ + } \ + v = *(t *)newp; \ + } \ +} while (0) + +#define CTL_RO_GEN(n, v, t) \ +static int \ +n##_ctl(const size_t *mib, size_t miblen, void *oldp, size_t *oldlenp, \ + void *newp, size_t newlen) \ +{ \ + int ret; \ + t oldval; \ + \ + READONLY(); \ + oldval = v; \ + READ(oldval, t); \ + \ + ret = 0; \ +RETURN: \ + return (ret); \ +} + +#define CTL_RO_TRUE_GEN(n) \ +static int \ +n##_ctl(const size_t *mib, size_t miblen, void *oldp, size_t *oldlenp, \ + void *newp, size_t newlen) \ +{ \ + int ret; \ + bool oldval; \ + \ + READONLY(); \ + oldval = true; \ + READ(oldval, bool); \ + \ + ret = 0; \ +RETURN: \ + return (ret); \ +} + +#define CTL_RO_FALSE_GEN(n) \ +static int \ +n##_ctl(const size_t *mib, size_t miblen, void *oldp, size_t *oldlenp, \ + void *newp, size_t newlen) \ +{ \ + int ret; \ + bool oldval; \ + \ + READONLY(); \ + oldval = false; \ + READ(oldval, bool); \ + \ + ret = 0; \ +RETURN: \ + return (ret); \ +} + +CTL_RO_GEN(version, JEMALLOC_VERSION, const char *) + +static int +epoch_ctl(const size_t *mib, size_t miblen, void *oldp, size_t *oldlenp, + void *newp, size_t newlen) +{ + int ret; + uint64_t newval; + + newval = 0; + WRITE(newval, uint64_t); + if (newval != 0) + ctl_refresh(); + READ(ctl_epoch, uint64_t); + + ret = 0; +RETURN: + return (ret); +} + +#ifdef JEMALLOC_TCACHE +static int +tcache_flush_ctl(const size_t *mib, size_t miblen, void *oldp, size_t *oldlenp, + void *newp, size_t newlen) +{ + int ret; + tcache_t *tcache; + + VOID(); + + tcache = tcache_tls; + if (tcache == NULL) { + ret = 0; + goto RETURN; + } + tcache_destroy(tcache); + tcache_tls = NULL; + + ret = 0; +RETURN: + return (ret); +} +#endif + +/******************************************************************************/ + +#ifdef JEMALLOC_DEBUG +CTL_RO_TRUE_GEN(config_debug) +#else +CTL_RO_FALSE_GEN(config_debug) +#endif + +#ifdef JEMALLOC_DSS +CTL_RO_TRUE_GEN(config_dss) +#else +CTL_RO_FALSE_GEN(config_dss) +#endif + +#ifdef JEMALLOC_DYNAMIC_PAGE_SHIFT +CTL_RO_TRUE_GEN(config_dynamic_page_shift) +#else +CTL_RO_FALSE_GEN(config_dynamic_page_shift) +#endif + +#ifdef JEMALLOC_FILL +CTL_RO_TRUE_GEN(config_fill) +#else +CTL_RO_FALSE_GEN(config_fill) +#endif + +#ifdef JEMALLOC_LAZY_LOCK +CTL_RO_TRUE_GEN(config_lazy_lock) +#else +CTL_RO_FALSE_GEN(config_lazy_lock) +#endif + +#ifdef JEMALLOC_PROF +CTL_RO_TRUE_GEN(config_prof) +#else +CTL_RO_FALSE_GEN(config_prof) +#endif + +#ifdef JEMALLOC_PROF_LIBGCC +CTL_RO_TRUE_GEN(config_prof_libgcc) +#else +CTL_RO_FALSE_GEN(config_prof_libgcc) +#endif + +#ifdef JEMALLOC_PROF_LIBUNWIND +CTL_RO_TRUE_GEN(config_prof_libunwind) +#else +CTL_RO_FALSE_GEN(config_prof_libunwind) +#endif + +#ifdef JEMALLOC_STATS +CTL_RO_TRUE_GEN(config_stats) +#else +CTL_RO_FALSE_GEN(config_stats) +#endif + +#ifdef JEMALLOC_SWAP +CTL_RO_TRUE_GEN(config_swap) +#else +CTL_RO_FALSE_GEN(config_swap) +#endif + +#ifdef JEMALLOC_SYSV +CTL_RO_TRUE_GEN(config_sysv) +#else +CTL_RO_FALSE_GEN(config_sysv) +#endif + +#ifdef JEMALLOC_TCACHE +CTL_RO_TRUE_GEN(config_tcache) +#else +CTL_RO_FALSE_GEN(config_tcache) +#endif + +#ifdef JEMALLOC_TINY +CTL_RO_TRUE_GEN(config_tiny) +#else +CTL_RO_FALSE_GEN(config_tiny) +#endif + +#ifdef JEMALLOC_TLS +CTL_RO_TRUE_GEN(config_tls) +#else +CTL_RO_FALSE_GEN(config_tls) +#endif + +#ifdef JEMALLOC_XMALLOC +CTL_RO_TRUE_GEN(config_xmalloc) +#else +CTL_RO_FALSE_GEN(config_xmalloc) +#endif + +/******************************************************************************/ + +CTL_RO_GEN(opt_abort, opt_abort, bool) +#ifdef JEMALLOC_FILL +CTL_RO_GEN(opt_junk, opt_junk, bool) +#endif +#ifdef JEMALLOC_SYSV +CTL_RO_GEN(opt_sysv, opt_sysv, bool) +#endif +#ifdef JEMALLOC_XMALLOC +CTL_RO_GEN(opt_xmalloc, opt_xmalloc, bool) +#endif +#ifdef JEMALLOC_ZERO +CTL_RO_GEN(opt_zero, opt_zero, bool) +#endif +#ifdef JEMALLOC_TCACHE +CTL_RO_GEN(opt_tcache, opt_tcache, bool) +CTL_RO_GEN(opt_lg_tcache_gc_sweep, opt_lg_tcache_gc_sweep, ssize_t) +#endif +#ifdef JEMALLOC_PROF +CTL_RO_GEN(opt_prof, opt_prof, bool) +CTL_RO_GEN(opt_prof_active, opt_prof_active, bool) +CTL_RO_GEN(opt_lg_prof_bt_max, opt_lg_prof_bt_max, size_t) +CTL_RO_GEN(opt_lg_prof_sample, opt_lg_prof_sample, size_t) +CTL_RO_GEN(opt_lg_prof_interval, opt_lg_prof_interval, ssize_t) +CTL_RO_GEN(opt_prof_udump, opt_prof_udump, bool) +CTL_RO_GEN(opt_prof_leak, opt_prof_leak, bool) +#endif +CTL_RO_GEN(opt_stats_print, opt_stats_print, bool) +CTL_RO_GEN(opt_lg_qspace_max, opt_lg_qspace_max, size_t) +CTL_RO_GEN(opt_lg_cspace_max, opt_lg_cspace_max, size_t) +CTL_RO_GEN(opt_lg_dirty_mult, opt_lg_dirty_mult, ssize_t) +CTL_RO_GEN(opt_lg_chunk, opt_lg_chunk, size_t) +#ifdef JEMALLOC_SWAP +CTL_RO_GEN(opt_overcommit, opt_overcommit, bool) +#endif + +/******************************************************************************/ + +CTL_RO_GEN(arenas_bin_i_size, arenas[0]->bins[mib[2]].reg_size, size_t) +CTL_RO_GEN(arenas_bin_i_nregs, arenas[0]->bins[mib[2]].nregs, uint32_t) +CTL_RO_GEN(arenas_bin_i_run_size, arenas[0]->bins[mib[2]].run_size, size_t) +const ctl_node_t * +arenas_bin_i_index(const size_t *mib, size_t miblen, size_t i) +{ + + if (i > nbins) + return (NULL); + return (super_arenas_bin_i_node); +} + +CTL_RO_GEN(arenas_lrun_i_size, ((mib[2]+1) << PAGE_SHIFT), size_t) +const ctl_node_t * +arenas_lrun_i_index(const size_t *mib, size_t miblen, size_t i) +{ + + if (i > nlclasses) + return (NULL); + return (super_arenas_lrun_i_node); +} + +CTL_RO_GEN(arenas_narenas, narenas, unsigned) + +static int +arenas_initialized_ctl(const size_t *mib, size_t miblen, void *oldp, + size_t *oldlenp, void *newp, size_t newlen) +{ + int ret; + unsigned nread, i; + + READONLY(); + if (*oldlenp != narenas * sizeof(bool)) { + ret = EINVAL; + nread = (*oldlenp < narenas * sizeof(bool)) + ? (*oldlenp / sizeof(bool)) : narenas; + } else { + ret = 0; + nread = narenas; + } + + for (i = 0; i < nread; i++) + ((bool *)oldp)[i] = ctl_stats.arenas[i].initialized; + +RETURN: + return (ret); +} + +CTL_RO_GEN(arenas_quantum, QUANTUM, size_t) +CTL_RO_GEN(arenas_cacheline, CACHELINE, size_t) +CTL_RO_GEN(arenas_subpage, SUBPAGE, size_t) +CTL_RO_GEN(arenas_pagesize, PAGE_SIZE, size_t) +CTL_RO_GEN(arenas_chunksize, chunksize, size_t) +#ifdef JEMALLOC_TINY +CTL_RO_GEN(arenas_tspace_min, (1U << LG_TINY_MIN), size_t) +CTL_RO_GEN(arenas_tspace_max, (qspace_min >> 1), size_t) +#endif +CTL_RO_GEN(arenas_qspace_min, qspace_min, size_t) +CTL_RO_GEN(arenas_qspace_max, qspace_max, size_t) +CTL_RO_GEN(arenas_cspace_min, cspace_min, size_t) +CTL_RO_GEN(arenas_cspace_max, cspace_max, size_t) +CTL_RO_GEN(arenas_sspace_min, sspace_min, size_t) +CTL_RO_GEN(arenas_sspace_max, sspace_max, size_t) +#ifdef JEMALLOC_TCACHE +CTL_RO_GEN(arenas_tcache_max, tcache_maxclass, size_t) +#endif +CTL_RO_GEN(arenas_ntbins, ntbins, unsigned) +CTL_RO_GEN(arenas_nqbins, nqbins, unsigned) +CTL_RO_GEN(arenas_ncbins, ncbins, unsigned) +CTL_RO_GEN(arenas_nsbins, nsbins, unsigned) +CTL_RO_GEN(arenas_nbins, nbins, unsigned) +#ifdef JEMALLOC_TCACHE +CTL_RO_GEN(arenas_nhbins, nhbins, unsigned) +#endif +CTL_RO_GEN(arenas_nlruns, nlclasses, size_t) + +/******************************************************************************/ + +#ifdef JEMALLOC_PROF +static int +prof_active_ctl(const size_t *mib, size_t miblen, void *oldp, size_t *oldlenp, + void *newp, size_t newlen) +{ + int ret; + bool oldval; + + oldval = opt_prof_active; + if (newp != NULL) { + /* + * The memory barriers will tend to make opt_prof_active + * propagate faster on systems with weak memory ordering. + */ + mb_write(); + WRITE(opt_prof_active, bool); + mb_write(); + } + READ(oldval, bool); + + ret = 0; +RETURN: + return (ret); +} + +static int +prof_dump_ctl(const size_t *mib, size_t miblen, void *oldp, size_t *oldlenp, + void *newp, size_t newlen) +{ + int ret; + const char *filename = NULL; + + WRITEONLY(); + WRITE(filename, const char *); + + if (prof_mdump(filename)) { + ret = EFAULT; + goto RETURN; + } + + ret = 0; +RETURN: + return (ret); +} + +CTL_RO_GEN(prof_interval, prof_interval, uint64_t) +#endif + +/******************************************************************************/ + +#ifdef JEMALLOC_STATS +CTL_RO_GEN(stats_chunks_current, ctl_stats.chunks.current, size_t) +CTL_RO_GEN(stats_chunks_total, ctl_stats.chunks.total, uint64_t) +CTL_RO_GEN(stats_chunks_high, ctl_stats.chunks.high, size_t) +CTL_RO_GEN(stats_huge_allocated, huge_allocated, size_t) +CTL_RO_GEN(stats_huge_nmalloc, huge_nmalloc, uint64_t) +CTL_RO_GEN(stats_huge_ndalloc, huge_ndalloc, uint64_t) +CTL_RO_GEN(stats_arenas_i_small_allocated, + ctl_stats.arenas[mib[2]].allocated_small, size_t) +CTL_RO_GEN(stats_arenas_i_small_nmalloc, + ctl_stats.arenas[mib[2]].nmalloc_small, uint64_t) +CTL_RO_GEN(stats_arenas_i_small_ndalloc, + ctl_stats.arenas[mib[2]].ndalloc_small, uint64_t) +CTL_RO_GEN(stats_arenas_i_small_nrequests, + ctl_stats.arenas[mib[2]].nrequests_small, uint64_t) +CTL_RO_GEN(stats_arenas_i_large_allocated, + ctl_stats.arenas[mib[2]].astats.allocated_large, size_t) +CTL_RO_GEN(stats_arenas_i_large_nmalloc, + ctl_stats.arenas[mib[2]].astats.nmalloc_large, uint64_t) +CTL_RO_GEN(stats_arenas_i_large_ndalloc, + ctl_stats.arenas[mib[2]].astats.ndalloc_large, uint64_t) +CTL_RO_GEN(stats_arenas_i_large_nrequests, + ctl_stats.arenas[mib[2]].astats.nrequests_large, uint64_t) + +CTL_RO_GEN(stats_arenas_i_bins_j_allocated, + ctl_stats.arenas[mib[2]].bstats[mib[4]].allocated, size_t) +CTL_RO_GEN(stats_arenas_i_bins_j_nmalloc, + ctl_stats.arenas[mib[2]].bstats[mib[4]].nmalloc, uint64_t) +CTL_RO_GEN(stats_arenas_i_bins_j_ndalloc, + ctl_stats.arenas[mib[2]].bstats[mib[4]].ndalloc, uint64_t) +CTL_RO_GEN(stats_arenas_i_bins_j_nrequests, + ctl_stats.arenas[mib[2]].bstats[mib[4]].nrequests, uint64_t) +#ifdef JEMALLOC_TCACHE +CTL_RO_GEN(stats_arenas_i_bins_j_nfills, + ctl_stats.arenas[mib[2]].bstats[mib[4]].nfills, uint64_t) +CTL_RO_GEN(stats_arenas_i_bins_j_nflushes, + ctl_stats.arenas[mib[2]].bstats[mib[4]].nflushes, uint64_t) +#endif +CTL_RO_GEN(stats_arenas_i_bins_j_nruns, + ctl_stats.arenas[mib[2]].bstats[mib[4]].nruns, uint64_t) +CTL_RO_GEN(stats_arenas_i_bins_j_nreruns, + ctl_stats.arenas[mib[2]].bstats[mib[4]].reruns, uint64_t) +CTL_RO_GEN(stats_arenas_i_bins_j_highruns, + ctl_stats.arenas[mib[2]].bstats[mib[4]].highruns, size_t) +CTL_RO_GEN(stats_arenas_i_bins_j_curruns, + ctl_stats.arenas[mib[2]].bstats[mib[4]].curruns, size_t) + +const ctl_node_t * +stats_arenas_i_bins_j_index(const size_t *mib, size_t miblen, size_t j) +{ + + if (j > nbins) + return (NULL); + return (super_stats_arenas_i_bins_j_node); +} + +CTL_RO_GEN(stats_arenas_i_lruns_j_nmalloc, + ctl_stats.arenas[mib[2]].lstats[mib[4]].nmalloc, uint64_t) +CTL_RO_GEN(stats_arenas_i_lruns_j_ndalloc, + ctl_stats.arenas[mib[2]].lstats[mib[4]].ndalloc, uint64_t) +CTL_RO_GEN(stats_arenas_i_lruns_j_nrequests, + ctl_stats.arenas[mib[2]].lstats[mib[4]].nrequests, uint64_t) +CTL_RO_GEN(stats_arenas_i_lruns_j_curruns, + ctl_stats.arenas[mib[2]].lstats[mib[4]].curruns, size_t) +CTL_RO_GEN(stats_arenas_i_lruns_j_highruns, + ctl_stats.arenas[mib[2]].lstats[mib[4]].highruns, size_t) + +const ctl_node_t * +stats_arenas_i_lruns_j_index(const size_t *mib, size_t miblen, size_t j) +{ + + if (j > nlclasses) + return (NULL); + return (super_stats_arenas_i_lruns_j_node); +} + +#endif +CTL_RO_GEN(stats_arenas_i_pactive, ctl_stats.arenas[mib[2]].pactive, size_t) +CTL_RO_GEN(stats_arenas_i_pdirty, ctl_stats.arenas[mib[2]].pdirty, size_t) +#ifdef JEMALLOC_STATS +CTL_RO_GEN(stats_arenas_i_mapped, ctl_stats.arenas[mib[2]].astats.mapped, + size_t) +CTL_RO_GEN(stats_arenas_i_npurge, ctl_stats.arenas[mib[2]].astats.npurge, + uint64_t) +CTL_RO_GEN(stats_arenas_i_nmadvise, ctl_stats.arenas[mib[2]].astats.nmadvise, + uint64_t) +CTL_RO_GEN(stats_arenas_i_purged, ctl_stats.arenas[mib[2]].astats.purged, + uint64_t) +#endif + +const ctl_node_t * +stats_arenas_i_index(const size_t *mib, size_t miblen, size_t i) +{ + + if (ctl_stats.arenas[i].initialized == false) + return (NULL); + return (super_stats_arenas_i_node); +} + +#ifdef JEMALLOC_STATS +CTL_RO_GEN(stats_allocated, ctl_stats.allocated, size_t) +CTL_RO_GEN(stats_active, ctl_stats.active, size_t) +CTL_RO_GEN(stats_mapped, ctl_stats.mapped, size_t) +#endif + +/******************************************************************************/ + +#ifdef JEMALLOC_SWAP +# ifdef JEMALLOC_STATS +CTL_RO_GEN(swap_avail, ctl_stats.swap_avail, size_t) +# endif + +static int +swap_prezeroed_ctl(const size_t *mib, size_t miblen, void *oldp, + size_t *oldlenp, void *newp, size_t newlen) +{ + int ret; + + if (swap_enabled) { + READONLY(); + } else { + /* + * swap_prezeroed isn't actually used by the swap code until it + * is set during a successful chunk_swap_enabled() call. We + * use it here to store the value that we'll pass to + * chunk_swap_enable() in a swap.fds mallctl(). This is not + * very clean, but the obvious alternatives are even worse. + */ + WRITE(swap_prezeroed, bool); + } + + READ(swap_prezeroed, bool); + + ret = 0; +RETURN: + return (ret); +} + +CTL_RO_GEN(swap_nfds, swap_nfds, size_t) + +static int +swap_fds_ctl(const size_t *mib, size_t miblen, void *oldp, size_t *oldlenp, + void *newp, size_t newlen) +{ + int ret; + + if (swap_enabled) { + READONLY(); + } else if (newp != NULL) { + size_t nfds = newlen / sizeof(int); + + { + int fds[nfds]; + + memcpy(fds, newp, nfds * sizeof(int)); + if (chunk_swap_enable(fds, nfds, swap_prezeroed)) { + ret = EFAULT; + goto RETURN; + } + } + } + + if (oldp != NULL && oldlenp != NULL) { + if (*oldlenp != swap_nfds * sizeof(int)) { + size_t copylen = (swap_nfds * sizeof(int) <= *oldlenp) + ? swap_nfds * sizeof(int) : *oldlenp; + + memcpy(oldp, swap_fds, copylen); + ret = EINVAL; + goto RETURN; + } else + memcpy(oldp, swap_fds, *oldlenp); + } + + ret = 0; +RETURN: + return (ret); +} +#endif diff --git a/dep/jemalloc/extent.c b/dep/jemalloc/extent.c new file mode 100644 index 00000000000..3c04d3aa5d1 --- /dev/null +++ b/dep/jemalloc/extent.c @@ -0,0 +1,41 @@ +#define JEMALLOC_EXTENT_C_ +#include "jemalloc/internal/jemalloc_internal.h" + +/******************************************************************************/ + +#if (defined(JEMALLOC_SWAP) || defined(JEMALLOC_DSS)) +static inline int +extent_szad_comp(extent_node_t *a, extent_node_t *b) +{ + int ret; + size_t a_size = a->size; + size_t b_size = b->size; + + ret = (a_size > b_size) - (a_size < b_size); + if (ret == 0) { + uintptr_t a_addr = (uintptr_t)a->addr; + uintptr_t b_addr = (uintptr_t)b->addr; + + ret = (a_addr > b_addr) - (a_addr < b_addr); + } + + return (ret); +} + +/* Generate red-black tree functions. */ +rb_gen(, extent_tree_szad_, extent_tree_t, extent_node_t, link_szad, + extent_szad_comp) +#endif + +static inline int +extent_ad_comp(extent_node_t *a, extent_node_t *b) +{ + uintptr_t a_addr = (uintptr_t)a->addr; + uintptr_t b_addr = (uintptr_t)b->addr; + + return ((a_addr > b_addr) - (a_addr < b_addr)); +} + +/* Generate red-black tree functions. */ +rb_gen(, extent_tree_ad_, extent_tree_t, extent_node_t, link_ad, + extent_ad_comp) diff --git a/dep/jemalloc/hash.c b/dep/jemalloc/hash.c new file mode 100644 index 00000000000..6a13d7a03c0 --- /dev/null +++ b/dep/jemalloc/hash.c @@ -0,0 +1,2 @@ +#define HASH_C_ +#include "jemalloc/internal/jemalloc_internal.h" diff --git a/dep/jemalloc/huge.c b/dep/jemalloc/huge.c new file mode 100644 index 00000000000..d35aa5cdd00 --- /dev/null +++ b/dep/jemalloc/huge.c @@ -0,0 +1,298 @@ +#define JEMALLOC_HUGE_C_ +#include "jemalloc/internal/jemalloc_internal.h" + +/******************************************************************************/ +/* Data. */ + +#ifdef JEMALLOC_STATS +uint64_t huge_nmalloc; +uint64_t huge_ndalloc; +size_t huge_allocated; +#endif + +malloc_mutex_t huge_mtx; + +/******************************************************************************/ + +/* Tree of chunks that are stand-alone huge allocations. */ +static extent_tree_t huge; + +void * +huge_malloc(size_t size, bool zero) +{ + void *ret; + size_t csize; + extent_node_t *node; + + /* Allocate one or more contiguous chunks for this request. */ + + csize = CHUNK_CEILING(size); + if (csize == 0) { + /* size is large enough to cause size_t wrap-around. */ + return (NULL); + } + + /* Allocate an extent node with which to track the chunk. */ + node = base_node_alloc(); + if (node == NULL) + return (NULL); + + ret = chunk_alloc(csize, &zero); + if (ret == NULL) { + base_node_dealloc(node); + return (NULL); + } + + /* Insert node into huge. */ + node->addr = ret; + node->size = csize; + + malloc_mutex_lock(&huge_mtx); + extent_tree_ad_insert(&huge, node); +#ifdef JEMALLOC_STATS + huge_nmalloc++; + huge_allocated += csize; +#endif + malloc_mutex_unlock(&huge_mtx); + +#ifdef JEMALLOC_FILL + if (zero == false) { + if (opt_junk) + memset(ret, 0xa5, csize); + else if (opt_zero) + memset(ret, 0, csize); + } +#endif + + return (ret); +} + +/* Only handles large allocations that require more than chunk alignment. */ +void * +huge_palloc(size_t alignment, size_t size) +{ + void *ret; + size_t alloc_size, chunk_size, offset; + extent_node_t *node; + bool zero; + + /* + * This allocation requires alignment that is even larger than chunk + * alignment. This means that huge_malloc() isn't good enough. + * + * Allocate almost twice as many chunks as are demanded by the size or + * alignment, in order to assure the alignment can be achieved, then + * unmap leading and trailing chunks. + */ + assert(alignment >= chunksize); + + chunk_size = CHUNK_CEILING(size); + + if (size >= alignment) + alloc_size = chunk_size + alignment - chunksize; + else + alloc_size = (alignment << 1) - chunksize; + + /* Allocate an extent node with which to track the chunk. */ + node = base_node_alloc(); + if (node == NULL) + return (NULL); + + zero = false; + ret = chunk_alloc(alloc_size, &zero); + if (ret == NULL) { + base_node_dealloc(node); + return (NULL); + } + + offset = (uintptr_t)ret & (alignment - 1); + assert((offset & chunksize_mask) == 0); + assert(offset < alloc_size); + if (offset == 0) { + /* Trim trailing space. */ + chunk_dealloc((void *)((uintptr_t)ret + chunk_size), alloc_size + - chunk_size); + } else { + size_t trailsize; + + /* Trim leading space. */ + chunk_dealloc(ret, alignment - offset); + + ret = (void *)((uintptr_t)ret + (alignment - offset)); + + trailsize = alloc_size - (alignment - offset) - chunk_size; + if (trailsize != 0) { + /* Trim trailing space. */ + assert(trailsize < alloc_size); + chunk_dealloc((void *)((uintptr_t)ret + chunk_size), + trailsize); + } + } + + /* Insert node into huge. */ + node->addr = ret; + node->size = chunk_size; + + malloc_mutex_lock(&huge_mtx); + extent_tree_ad_insert(&huge, node); +#ifdef JEMALLOC_STATS + huge_nmalloc++; + huge_allocated += chunk_size; +#endif + malloc_mutex_unlock(&huge_mtx); + +#ifdef JEMALLOC_FILL + if (opt_junk) + memset(ret, 0xa5, chunk_size); + else if (opt_zero) + memset(ret, 0, chunk_size); +#endif + + return (ret); +} + +void * +huge_ralloc(void *ptr, size_t size, size_t oldsize) +{ + void *ret; + size_t copysize; + + /* Avoid moving the allocation if the size class would not change. */ + if (oldsize > arena_maxclass && + CHUNK_CEILING(size) == CHUNK_CEILING(oldsize)) { +#ifdef JEMALLOC_FILL + if (opt_junk && size < oldsize) { + memset((void *)((uintptr_t)ptr + size), 0x5a, oldsize + - size); + } else if (opt_zero && size > oldsize) { + memset((void *)((uintptr_t)ptr + oldsize), 0, size + - oldsize); + } +#endif + return (ptr); + } + + /* + * If we get here, then size and oldsize are different enough that we + * need to use a different size class. In that case, fall back to + * allocating new space and copying. + */ + ret = huge_malloc(size, false); + if (ret == NULL) + return (NULL); + + copysize = (size < oldsize) ? size : oldsize; + memcpy(ret, ptr, copysize); + idalloc(ptr); + return (ret); +} + +void +huge_dalloc(void *ptr) +{ + extent_node_t *node, key; + + malloc_mutex_lock(&huge_mtx); + + /* Extract from tree of huge allocations. */ + key.addr = ptr; + node = extent_tree_ad_search(&huge, &key); + assert(node != NULL); + assert(node->addr == ptr); + extent_tree_ad_remove(&huge, node); + +#ifdef JEMALLOC_STATS + huge_ndalloc++; + huge_allocated -= node->size; +#endif + + malloc_mutex_unlock(&huge_mtx); + + /* Unmap chunk. */ +#ifdef JEMALLOC_FILL +#if (defined(JEMALLOC_SWAP) || defined(JEMALLOC_DSS)) + if (opt_junk) + memset(node->addr, 0x5a, node->size); +#endif +#endif + chunk_dealloc(node->addr, node->size); + + base_node_dealloc(node); +} + +size_t +huge_salloc(const void *ptr) +{ + size_t ret; + extent_node_t *node, key; + + malloc_mutex_lock(&huge_mtx); + + /* Extract from tree of huge allocations. */ + key.addr = __DECONST(void *, ptr); + node = extent_tree_ad_search(&huge, &key); + assert(node != NULL); + + ret = node->size; + + malloc_mutex_unlock(&huge_mtx); + + return (ret); +} + +#ifdef JEMALLOC_PROF +prof_thr_cnt_t * +huge_prof_cnt_get(const void *ptr) +{ + prof_thr_cnt_t *ret; + extent_node_t *node, key; + + malloc_mutex_lock(&huge_mtx); + + /* Extract from tree of huge allocations. */ + key.addr = __DECONST(void *, ptr); + node = extent_tree_ad_search(&huge, &key); + assert(node != NULL); + + ret = node->prof_cnt; + + malloc_mutex_unlock(&huge_mtx); + + return (ret); +} + +void +huge_prof_cnt_set(const void *ptr, prof_thr_cnt_t *cnt) +{ + extent_node_t *node, key; + + malloc_mutex_lock(&huge_mtx); + + /* Extract from tree of huge allocations. */ + key.addr = __DECONST(void *, ptr); + node = extent_tree_ad_search(&huge, &key); + assert(node != NULL); + + node->prof_cnt = cnt; + + malloc_mutex_unlock(&huge_mtx); +} +#endif + +bool +huge_boot(void) +{ + + /* Initialize chunks data. */ + if (malloc_mutex_init(&huge_mtx)) + return (true); + extent_tree_ad_new(&huge); + +#ifdef JEMALLOC_STATS + huge_nmalloc = 0; + huge_ndalloc = 0; + huge_allocated = 0; +#endif + + return (false); +} diff --git a/dep/jemalloc/jemalloc.c b/dep/jemalloc/jemalloc.c new file mode 100644 index 00000000000..e01de0d5066 --- /dev/null +++ b/dep/jemalloc/jemalloc.c @@ -0,0 +1,1349 @@ +/*- + * This allocator implementation is designed to provide scalable performance + * for multi-threaded programs on multi-processor systems. The following + * features are included for this purpose: + * + * + Multiple arenas are used if there are multiple CPUs, which reduces lock + * contention and cache sloshing. + * + * + Thread-specific caching is used if there are multiple threads, which + * reduces the amount of locking. + * + * + Cache line sharing between arenas is avoided for internal data + * structures. + * + * + Memory is managed in chunks and runs (chunks can be split into runs), + * rather than as individual pages. This provides a constant-time + * mechanism for associating allocations with particular arenas. + * + * Allocation requests are rounded up to the nearest size class, and no record + * of the original request size is maintained. Allocations are broken into + * categories according to size class. Assuming 1 MiB chunks, 4 KiB pages and + * a 16 byte quantum on a 32-bit system, the size classes in each category are + * as follows: + * + * |========================================| + * | Category | Subcategory | Size | + * |========================================| + * | Small | Tiny | 2 | + * | | | 4 | + * | | | 8 | + * | |------------------+----------| + * | | Quantum-spaced | 16 | + * | | | 32 | + * | | | 48 | + * | | | ... | + * | | | 96 | + * | | | 112 | + * | | | 128 | + * | |------------------+----------| + * | | Cacheline-spaced | 192 | + * | | | 256 | + * | | | 320 | + * | | | 384 | + * | | | 448 | + * | | | 512 | + * | |------------------+----------| + * | | Sub-page | 760 | + * | | | 1024 | + * | | | 1280 | + * | | | ... | + * | | | 3328 | + * | | | 3584 | + * | | | 3840 | + * |========================================| + * | Large | 4 KiB | + * | | 8 KiB | + * | | 12 KiB | + * | | ... | + * | | 1012 KiB | + * | | 1016 KiB | + * | | 1020 KiB | + * |========================================| + * | Huge | 1 MiB | + * | | 2 MiB | + * | | 3 MiB | + * | | ... | + * |========================================| + * + * Different mechanisms are used accoding to category: + * + * Small: Each size class is segregated into its own set of runs. Each run + * maintains a bitmap of which regions are free/allocated. + * + * Large : Each allocation is backed by a dedicated run. Metadata are stored + * in the associated arena chunk header maps. + * + * Huge : Each allocation is backed by a dedicated contiguous set of chunks. + * Metadata are stored in a separate red-black tree. + * + ******************************************************************************* + */ + +#define JEMALLOC_C_ +#include "jemalloc/internal/jemalloc_internal.h" + +/******************************************************************************/ +/* Data. */ + +malloc_mutex_t arenas_lock; +arena_t **arenas; +unsigned narenas; +#ifndef NO_TLS +static unsigned next_arena; +#endif + +#ifndef NO_TLS +__thread arena_t *arenas_map JEMALLOC_ATTR(tls_model("initial-exec")); +#endif + +/* Set to true once the allocator has been initialized. */ +static bool malloc_initialized = false; + +/* Used to let the initializing thread recursively allocate. */ +static pthread_t malloc_initializer = (unsigned long)0; + +/* Used to avoid initialization races. */ +static malloc_mutex_t init_lock = PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP; + +#ifdef DYNAMIC_PAGE_SHIFT +size_t pagesize; +size_t pagesize_mask; +size_t lg_pagesize; +#endif + +unsigned ncpus; + +/* Runtime configuration options. */ +const char *JEMALLOC_P(malloc_options) + JEMALLOC_ATTR(visibility("default")); +#ifdef JEMALLOC_DEBUG +bool opt_abort = true; +# ifdef JEMALLOC_FILL +bool opt_junk = true; +# endif +#else +bool opt_abort = false; +# ifdef JEMALLOC_FILL +bool opt_junk = false; +# endif +#endif +#ifdef JEMALLOC_SYSV +bool opt_sysv = false; +#endif +#ifdef JEMALLOC_XMALLOC +bool opt_xmalloc = false; +#endif +#ifdef JEMALLOC_FILL +bool opt_zero = false; +#endif +static int opt_narenas_lshift = 0; + +/******************************************************************************/ +/* Function prototypes for non-inline static functions. */ + +static void wrtmessage(void *cbopaque, const char *s); +static void stats_print_atexit(void); +static unsigned malloc_ncpus(void); +static bool malloc_init_hard(void); +static void jemalloc_prefork(void); +static void jemalloc_postfork(void); + +/******************************************************************************/ +/* malloc_message() setup. */ + +#ifdef JEMALLOC_HAVE_ATTR +JEMALLOC_ATTR(visibility("hidden")) +#else +static +#endif +void +wrtmessage(void *cbopaque, const char *s) +{ + + write(STDERR_FILENO, s, strlen(s)); +} + +void (*JEMALLOC_P(malloc_message))(void *, const char *s) + JEMALLOC_ATTR(visibility("default")) = wrtmessage; + +/******************************************************************************/ +/* + * Begin miscellaneous support functions. + */ + +/* Create a new arena and insert it into the arenas array at index ind. */ +arena_t * +arenas_extend(unsigned ind) +{ + arena_t *ret; + + /* Allocate enough space for trailing bins. */ + ret = (arena_t *)base_alloc(sizeof(arena_t) + + (sizeof(arena_bin_t) * (nbins - 1))); + if (ret != NULL && arena_new(ret, ind) == false) { + arenas[ind] = ret; + return (ret); + } + /* Only reached if there is an OOM error. */ + + /* + * OOM here is quite inconvenient to propagate, since dealing with it + * would require a check for failure in the fast path. Instead, punt + * by using arenas[0]. In practice, this is an extremely unlikely + * failure. + */ + malloc_write(": Error initializing arena\n"); + if (opt_abort) + abort(); + + return (arenas[0]); +} + +#ifndef NO_TLS +/* + * Choose an arena based on a per-thread value (slow-path code only, called + * only by choose_arena()). + */ +arena_t * +choose_arena_hard(void) +{ + arena_t *ret; + + if (narenas > 1) { + malloc_mutex_lock(&arenas_lock); + if ((ret = arenas[next_arena]) == NULL) + ret = arenas_extend(next_arena); + next_arena = (next_arena + 1) % narenas; + malloc_mutex_unlock(&arenas_lock); + } else + ret = arenas[0]; + + arenas_map = ret; + + return (ret); +} +#endif + +static void +stats_print_atexit(void) +{ + +#if (defined(JEMALLOC_TCACHE) && defined(JEMALLOC_STATS)) + unsigned i; + + /* + * Merge stats from extant threads. This is racy, since individual + * threads do not lock when recording tcache stats events. As a + * consequence, the final stats may be slightly out of date by the time + * they are reported, if other threads continue to allocate. + */ + for (i = 0; i < narenas; i++) { + arena_t *arena = arenas[i]; + if (arena != NULL) { + tcache_t *tcache; + + /* + * tcache_stats_merge() locks bins, so if any code is + * introduced that acquires both arena and bin locks in + * the opposite order, deadlocks may result. + */ + malloc_mutex_lock(&arena->lock); + ql_foreach(tcache, &arena->tcache_ql, link) { + tcache_stats_merge(tcache, arena); + } + malloc_mutex_unlock(&arena->lock); + } + } +#endif + JEMALLOC_P(malloc_stats_print)(NULL, NULL, NULL); +} + +/* + * End miscellaneous support functions. + */ +/******************************************************************************/ +/* + * Begin initialization functions. + */ + +static unsigned +malloc_ncpus(void) +{ + unsigned ret; + long result; + + result = sysconf(_SC_NPROCESSORS_ONLN); + if (result == -1) { + /* Error. */ + ret = 1; + } + ret = (unsigned)result; + + return (ret); +} + +/* + * FreeBSD's pthreads implementation calls malloc(3), so the malloc + * implementation has to take pains to avoid infinite recursion during + * initialization. + */ +static inline bool +malloc_init(void) +{ + + if (malloc_initialized == false) + return (malloc_init_hard()); + + return (false); +} + +static bool +malloc_init_hard(void) +{ + unsigned i; + int linklen; + char buf[PATH_MAX + 1]; + const char *opts; + arena_t *init_arenas[1]; + + malloc_mutex_lock(&init_lock); + if (malloc_initialized || malloc_initializer == pthread_self()) { + /* + * Another thread initialized the allocator before this one + * acquired init_lock, or this thread is the initializing + * thread, and it is recursively allocating. + */ + malloc_mutex_unlock(&init_lock); + return (false); + } + if (malloc_initializer != (unsigned long)0) { + /* Busy-wait until the initializing thread completes. */ + do { + malloc_mutex_unlock(&init_lock); + CPU_SPINWAIT; + malloc_mutex_lock(&init_lock); + } while (malloc_initialized == false); + return (false); + } + +#ifdef DYNAMIC_PAGE_SHIFT + /* Get page size. */ + { + long result; + + result = sysconf(_SC_PAGESIZE); + assert(result != -1); + pagesize = (unsigned)result; + + /* + * We assume that pagesize is a power of 2 when calculating + * pagesize_mask and lg_pagesize. + */ + assert(((result - 1) & result) == 0); + pagesize_mask = result - 1; + lg_pagesize = ffs((int)result) - 1; + } +#endif + + for (i = 0; i < 3; i++) { + unsigned j; + + /* Get runtime configuration. */ + switch (i) { + case 0: + if ((linklen = readlink("/etc/jemalloc.conf", buf, + sizeof(buf) - 1)) != -1) { + /* + * Use the contents of the "/etc/jemalloc.conf" + * symbolic link's name. + */ + buf[linklen] = '\0'; + opts = buf; + } else { + /* No configuration specified. */ + buf[0] = '\0'; + opts = buf; + } + break; + case 1: + if ((opts = getenv("JEMALLOC_OPTIONS")) != NULL) { + /* + * Do nothing; opts is already initialized to + * the value of the JEMALLOC_OPTIONS + * environment variable. + */ + } else { + /* No configuration specified. */ + buf[0] = '\0'; + opts = buf; + } + break; + case 2: + if (JEMALLOC_P(malloc_options) != NULL) { + /* + * Use options that were compiled into the + * program. + */ + opts = JEMALLOC_P(malloc_options); + } else { + /* No configuration specified. */ + buf[0] = '\0'; + opts = buf; + } + break; + default: + /* NOTREACHED */ + assert(false); + buf[0] = '\0'; + opts = buf; + } + + for (j = 0; opts[j] != '\0'; j++) { + unsigned k, nreps; + bool nseen; + + /* Parse repetition count, if any. */ + for (nreps = 0, nseen = false;; j++, nseen = true) { + switch (opts[j]) { + case '0': case '1': case '2': case '3': + case '4': case '5': case '6': case '7': + case '8': case '9': + nreps *= 10; + nreps += opts[j] - '0'; + break; + default: + goto MALLOC_OUT; + } + } +MALLOC_OUT: + if (nseen == false) + nreps = 1; + + for (k = 0; k < nreps; k++) { + switch (opts[j]) { + case 'a': + opt_abort = false; + break; + case 'A': + opt_abort = true; + break; +#ifdef JEMALLOC_PROF + case 'b': + if (opt_lg_prof_bt_max > 0) + opt_lg_prof_bt_max--; + break; + case 'B': + if (opt_lg_prof_bt_max < LG_PROF_BT_MAX) + opt_lg_prof_bt_max++; + break; +#endif + case 'c': + if (opt_lg_cspace_max - 1 > + opt_lg_qspace_max && + opt_lg_cspace_max > + LG_CACHELINE) + opt_lg_cspace_max--; + break; + case 'C': + if (opt_lg_cspace_max < PAGE_SHIFT + - 1) + opt_lg_cspace_max++; + break; + case 'd': + if (opt_lg_dirty_mult + 1 < + (sizeof(size_t) << 3)) + opt_lg_dirty_mult++; + break; + case 'D': + if (opt_lg_dirty_mult >= 0) + opt_lg_dirty_mult--; + break; +#ifdef JEMALLOC_PROF + case 'e': + opt_prof_active = false; + break; + case 'E': + opt_prof_active = true; + break; + case 'f': + opt_prof = false; + break; + case 'F': + opt_prof = true; + break; +#endif +#ifdef JEMALLOC_TCACHE + case 'g': + if (opt_lg_tcache_gc_sweep >= 0) + opt_lg_tcache_gc_sweep--; + break; + case 'G': + if (opt_lg_tcache_gc_sweep + 1 < + (sizeof(size_t) << 3)) + opt_lg_tcache_gc_sweep++; + break; + case 'h': + opt_tcache = false; + break; + case 'H': + opt_tcache = true; + break; +#endif +#ifdef JEMALLOC_PROF + case 'i': + if (opt_lg_prof_interval >= 0) + opt_lg_prof_interval--; + break; + case 'I': + if (opt_lg_prof_interval + 1 < + (sizeof(uint64_t) << 3)) + opt_lg_prof_interval++; + break; +#endif +#ifdef JEMALLOC_FILL + case 'j': + opt_junk = false; + break; + case 'J': + opt_junk = true; + break; +#endif + case 'k': + /* + * Chunks always require at least one + * header page, plus one data page. + */ + if ((1U << (opt_lg_chunk - 1)) >= + (2U << PAGE_SHIFT)) + opt_lg_chunk--; + break; + case 'K': + if (opt_lg_chunk + 1 < + (sizeof(size_t) << 3)) + opt_lg_chunk++; + break; +#ifdef JEMALLOC_PROF + case 'l': + opt_prof_leak = false; + break; + case 'L': + opt_prof_leak = true; + break; +#endif +#ifdef JEMALLOC_TCACHE + case 'm': + if (opt_lg_tcache_maxclass >= 0) + opt_lg_tcache_maxclass--; + break; + case 'M': + if (opt_lg_tcache_maxclass + 1 < + (sizeof(size_t) << 3)) + opt_lg_tcache_maxclass++; + break; +#endif + case 'n': + opt_narenas_lshift--; + break; + case 'N': + opt_narenas_lshift++; + break; +#ifdef JEMALLOC_SWAP + case 'o': + opt_overcommit = false; + break; + case 'O': + opt_overcommit = true; + break; +#endif + case 'p': + opt_stats_print = false; + break; + case 'P': + opt_stats_print = true; + break; + case 'q': + if (opt_lg_qspace_max > LG_QUANTUM) + opt_lg_qspace_max--; + break; + case 'Q': + if (opt_lg_qspace_max + 1 < + opt_lg_cspace_max) + opt_lg_qspace_max++; + break; +#ifdef JEMALLOC_PROF + case 's': + if (opt_lg_prof_sample > 0) + opt_lg_prof_sample--; + break; + case 'S': + if (opt_lg_prof_sample + 1 < + (sizeof(uint64_t) << 3)) + opt_lg_prof_sample++; + break; + case 'u': + opt_prof_udump = false; + break; + case 'U': + opt_prof_udump = true; + break; +#endif +#ifdef JEMALLOC_SYSV + case 'v': + opt_sysv = false; + break; + case 'V': + opt_sysv = true; + break; +#endif +#ifdef JEMALLOC_XMALLOC + case 'x': + opt_xmalloc = false; + break; + case 'X': + opt_xmalloc = true; + break; +#endif +#ifdef JEMALLOC_FILL + case 'z': + opt_zero = false; + break; + case 'Z': + opt_zero = true; + break; +#endif + default: { + char cbuf[2]; + + cbuf[0] = opts[j]; + cbuf[1] = '\0'; + malloc_write( + ": Unsupported character " + "in malloc options: '"); + malloc_write(cbuf); + malloc_write("'\n"); + } + } + } + } + } + + /* Register fork handlers. */ + if (pthread_atfork(jemalloc_prefork, jemalloc_postfork, + jemalloc_postfork) != 0) { + malloc_write(": Error in pthread_atfork()\n"); + if (opt_abort) + abort(); + } + + if (ctl_boot()) { + malloc_mutex_unlock(&init_lock); + return (true); + } + + if (opt_stats_print) { + /* Print statistics at exit. */ + if (atexit(stats_print_atexit) != 0) { + malloc_write(": Error in atexit()\n"); + if (opt_abort) + abort(); + } + } + + if (chunk_boot()) { + malloc_mutex_unlock(&init_lock); + return (true); + } + + if (base_boot()) { + malloc_mutex_unlock(&init_lock); + return (true); + } + +#ifdef JEMALLOC_PROF + prof_boot0(); +#endif + + if (arena_boot()) { + malloc_mutex_unlock(&init_lock); + return (true); + } + +#ifdef JEMALLOC_TCACHE + tcache_boot(); +#endif + + if (huge_boot()) { + malloc_mutex_unlock(&init_lock); + return (true); + } + + /* + * Create enough scaffolding to allow recursive allocation in + * malloc_ncpus(). + */ + narenas = 1; + arenas = init_arenas; + memset(arenas, 0, sizeof(arena_t *) * narenas); + + /* + * Initialize one arena here. The rest are lazily created in + * choose_arena_hard(). + */ + arenas_extend(0); + if (arenas[0] == NULL) { + malloc_mutex_unlock(&init_lock); + return (true); + } + +#ifndef NO_TLS + /* + * Assign the initial arena to the initial thread, in order to avoid + * spurious creation of an extra arena if the application switches to + * threaded mode. + */ + arenas_map = arenas[0]; +#endif + + malloc_mutex_init(&arenas_lock); + +#ifdef JEMALLOC_PROF + if (prof_boot1()) { + malloc_mutex_unlock(&init_lock); + return (true); + } +#endif + + /* Get number of CPUs. */ + malloc_initializer = pthread_self(); + malloc_mutex_unlock(&init_lock); + ncpus = malloc_ncpus(); + malloc_mutex_lock(&init_lock); + + if (ncpus > 1) { + /* + * For SMP systems, create more than one arena per CPU by + * default. + */ + opt_narenas_lshift += 2; + } + + /* Determine how many arenas to use. */ + narenas = ncpus; + if (opt_narenas_lshift > 0) { + if ((narenas << opt_narenas_lshift) > narenas) + narenas <<= opt_narenas_lshift; + /* + * Make sure not to exceed the limits of what base_alloc() can + * handle. + */ + if (narenas * sizeof(arena_t *) > chunksize) + narenas = chunksize / sizeof(arena_t *); + } else if (opt_narenas_lshift < 0) { + if ((narenas >> -opt_narenas_lshift) < narenas) + narenas >>= -opt_narenas_lshift; + /* Make sure there is at least one arena. */ + if (narenas == 0) + narenas = 1; + } + +#ifdef NO_TLS + if (narenas > 1) { + static const unsigned primes[] = {1, 3, 5, 7, 11, 13, 17, 19, + 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, + 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, + 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, + 223, 227, 229, 233, 239, 241, 251, 257, 263}; + unsigned nprimes, parenas; + + /* + * Pick a prime number of hash arenas that is more than narenas + * so that direct hashing of pthread_self() pointers tends to + * spread allocations evenly among the arenas. + */ + assert((narenas & 1) == 0); /* narenas must be even. */ + nprimes = (sizeof(primes) >> LG_SIZEOF_INT); + parenas = primes[nprimes - 1]; /* In case not enough primes. */ + for (i = 1; i < nprimes; i++) { + if (primes[i] > narenas) { + parenas = primes[i]; + break; + } + } + narenas = parenas; + } +#endif + +#ifndef NO_TLS + next_arena = 0; +#endif + + /* Allocate and initialize arenas. */ + arenas = (arena_t **)base_alloc(sizeof(arena_t *) * narenas); + if (arenas == NULL) { + malloc_mutex_unlock(&init_lock); + return (true); + } + /* + * Zero the array. In practice, this should always be pre-zeroed, + * since it was just mmap()ed, but let's be sure. + */ + memset(arenas, 0, sizeof(arena_t *) * narenas); + /* Copy the pointer to the one arena that was already initialized. */ + arenas[0] = init_arenas[0]; + + malloc_initialized = true; + malloc_mutex_unlock(&init_lock); + return (false); +} + +/* + * End initialization functions. + */ +/******************************************************************************/ +/* + * Begin malloc(3)-compatible functions. + */ + +JEMALLOC_ATTR(malloc) +JEMALLOC_ATTR(visibility("default")) +void * +JEMALLOC_P(malloc)(size_t size) +{ + void *ret; +#ifdef JEMALLOC_PROF + prof_thr_cnt_t *cnt; +#endif + + if (malloc_init()) { + ret = NULL; + goto OOM; + } + + if (size == 0) { +#ifdef JEMALLOC_SYSV + if (opt_sysv == false) +#endif + size = 1; +#ifdef JEMALLOC_SYSV + else { +# ifdef JEMALLOC_XMALLOC + if (opt_xmalloc) { + malloc_write(": Error in malloc(): " + "invalid size 0\n"); + abort(); + } +# endif + ret = NULL; + goto RETURN; + } +#endif + } + +#ifdef JEMALLOC_PROF + if (opt_prof) { + if ((cnt = prof_alloc_prep(size)) == NULL) { + ret = NULL; + goto OOM; + } + if (prof_promote && (uintptr_t)cnt != (uintptr_t)1U && size <= + small_maxclass) { + ret = imalloc(small_maxclass+1); + if (ret != NULL) + arena_prof_promoted(ret, size); + } else + ret = imalloc(size); + } else +#endif + ret = imalloc(size); + +OOM: + if (ret == NULL) { +#ifdef JEMALLOC_XMALLOC + if (opt_xmalloc) { + malloc_write(": Error in malloc(): " + "out of memory\n"); + abort(); + } +#endif + errno = ENOMEM; + } + +#ifdef JEMALLOC_SYSV +RETURN: +#endif +#ifdef JEMALLOC_PROF + if (opt_prof && ret != NULL) + prof_malloc(ret, cnt); +#endif + return (ret); +} + +JEMALLOC_ATTR(nonnull(1)) +JEMALLOC_ATTR(visibility("default")) +int +JEMALLOC_P(posix_memalign)(void **memptr, size_t alignment, size_t size) +{ + int ret; + void *result; +#ifdef JEMALLOC_PROF + prof_thr_cnt_t *cnt; +#endif + + if (malloc_init()) + result = NULL; + else { + if (size == 0) { +#ifdef JEMALLOC_SYSV + if (opt_sysv == false) +#endif + size = 1; +#ifdef JEMALLOC_SYSV + else { +# ifdef JEMALLOC_XMALLOC + if (opt_xmalloc) { + malloc_write(": Error in " + "posix_memalign(): invalid size " + "0\n"); + abort(); + } +# endif + result = NULL; + *memptr = NULL; + ret = 0; + goto RETURN; + } +#endif + } + + /* Make sure that alignment is a large enough power of 2. */ + if (((alignment - 1) & alignment) != 0 + || alignment < sizeof(void *)) { +#ifdef JEMALLOC_XMALLOC + if (opt_xmalloc) { + malloc_write(": Error in " + "posix_memalign(): invalid alignment\n"); + abort(); + } +#endif + result = NULL; + ret = EINVAL; + goto RETURN; + } + +#ifdef JEMALLOC_PROF + if (opt_prof) { + if ((cnt = prof_alloc_prep(size)) == NULL) { + result = NULL; + ret = EINVAL; + } else { + if (prof_promote && (uintptr_t)cnt != + (uintptr_t)1U && size <= small_maxclass) { + result = ipalloc(alignment, + small_maxclass+1); + if (result != NULL) { + arena_prof_promoted(result, + size); + } + } else + result = ipalloc(alignment, size); + } + } else +#endif + result = ipalloc(alignment, size); + } + + if (result == NULL) { +#ifdef JEMALLOC_XMALLOC + if (opt_xmalloc) { + malloc_write(": Error in posix_memalign(): " + "out of memory\n"); + abort(); + } +#endif + ret = ENOMEM; + goto RETURN; + } + + *memptr = result; + ret = 0; + +RETURN: +#ifdef JEMALLOC_PROF + if (opt_prof && result != NULL) + prof_malloc(result, cnt); +#endif + return (ret); +} + +JEMALLOC_ATTR(malloc) +JEMALLOC_ATTR(visibility("default")) +void * +JEMALLOC_P(calloc)(size_t num, size_t size) +{ + void *ret; + size_t num_size; +#ifdef JEMALLOC_PROF + prof_thr_cnt_t *cnt; +#endif + + if (malloc_init()) { + num_size = 0; + ret = NULL; + goto RETURN; + } + + num_size = num * size; + if (num_size == 0) { +#ifdef JEMALLOC_SYSV + if ((opt_sysv == false) && ((num == 0) || (size == 0))) +#endif + num_size = 1; +#ifdef JEMALLOC_SYSV + else { + ret = NULL; + goto RETURN; + } +#endif + /* + * Try to avoid division here. We know that it isn't possible to + * overflow during multiplication if neither operand uses any of the + * most significant half of the bits in a size_t. + */ + } else if (((num | size) & (SIZE_T_MAX << (sizeof(size_t) << 2))) + && (num_size / size != num)) { + /* size_t overflow. */ + ret = NULL; + goto RETURN; + } + +#ifdef JEMALLOC_PROF + if (opt_prof) { + if ((cnt = prof_alloc_prep(num_size)) == NULL) { + ret = NULL; + goto RETURN; + } + if (prof_promote && (uintptr_t)cnt != (uintptr_t)1U && num_size + <= small_maxclass) { + ret = icalloc(small_maxclass+1); + if (ret != NULL) + arena_prof_promoted(ret, num_size); + } else + ret = icalloc(num_size); + } else +#endif + ret = icalloc(num_size); + +RETURN: + if (ret == NULL) { +#ifdef JEMALLOC_XMALLOC + if (opt_xmalloc) { + malloc_write(": Error in calloc(): out of " + "memory\n"); + abort(); + } +#endif + errno = ENOMEM; + } + +#ifdef JEMALLOC_PROF + if (opt_prof && ret != NULL) + prof_malloc(ret, cnt); +#endif + return (ret); +} + +JEMALLOC_ATTR(visibility("default")) +void * +JEMALLOC_P(realloc)(void *ptr, size_t size) +{ + void *ret; +#ifdef JEMALLOC_PROF + size_t old_size; + prof_thr_cnt_t *cnt, *old_cnt; +#endif + + if (size == 0) { +#ifdef JEMALLOC_SYSV + if (opt_sysv == false) +#endif + size = 1; +#ifdef JEMALLOC_SYSV + else { + if (ptr != NULL) { +#ifdef JEMALLOC_PROF + if (opt_prof) { + old_size = isalloc(ptr); + old_cnt = prof_cnt_get(ptr); + cnt = NULL; + } +#endif + idalloc(ptr); + } +#ifdef JEMALLOC_PROF + else if (opt_prof) { + old_size = 0; + old_cnt = NULL; + cnt = NULL; + } +#endif + ret = NULL; + goto RETURN; + } +#endif + } + + if (ptr != NULL) { + assert(malloc_initialized || malloc_initializer == + pthread_self()); + +#ifdef JEMALLOC_PROF + if (opt_prof) { + old_size = isalloc(ptr); + old_cnt = prof_cnt_get(ptr); + if ((cnt = prof_alloc_prep(size)) == NULL) { + ret = NULL; + goto OOM; + } + if (prof_promote && (uintptr_t)cnt != (uintptr_t)1U && + size <= small_maxclass) { + ret = iralloc(ptr, small_maxclass+1); + if (ret != NULL) + arena_prof_promoted(ret, size); + } else + ret = iralloc(ptr, size); + } else +#endif + ret = iralloc(ptr, size); + +#ifdef JEMALLOC_PROF +OOM: +#endif + if (ret == NULL) { +#ifdef JEMALLOC_XMALLOC + if (opt_xmalloc) { + malloc_write(": Error in realloc(): " + "out of memory\n"); + abort(); + } +#endif + errno = ENOMEM; + } + } else { +#ifdef JEMALLOC_PROF + if (opt_prof) { + old_size = 0; + old_cnt = NULL; + } +#endif + if (malloc_init()) { +#ifdef JEMALLOC_PROF + if (opt_prof) + cnt = NULL; +#endif + ret = NULL; + } else { +#ifdef JEMALLOC_PROF + if (opt_prof) { + if ((cnt = prof_alloc_prep(size)) == NULL) + ret = NULL; + else { + if (prof_promote && (uintptr_t)cnt != + (uintptr_t)1U && size <= + small_maxclass) { + ret = imalloc(small_maxclass+1); + if (ret != NULL) { + arena_prof_promoted(ret, + size); + } + } else + ret = imalloc(size); + } + } else +#endif + ret = imalloc(size); + } + + if (ret == NULL) { +#ifdef JEMALLOC_XMALLOC + if (opt_xmalloc) { + malloc_write(": Error in realloc(): " + "out of memory\n"); + abort(); + } +#endif + errno = ENOMEM; + } + } + +#ifdef JEMALLOC_SYSV +RETURN: +#endif +#ifdef JEMALLOC_PROF + if (opt_prof) + prof_realloc(ret, cnt, ptr, old_size, old_cnt); +#endif + return (ret); +} + +JEMALLOC_ATTR(visibility("default")) +void +JEMALLOC_P(free)(void *ptr) +{ + + if (ptr != NULL) { + assert(malloc_initialized || malloc_initializer == + pthread_self()); + +#ifdef JEMALLOC_PROF + if (opt_prof) + prof_free(ptr); +#endif + idalloc(ptr); + } +} + +/* + * End malloc(3)-compatible functions. + */ +/******************************************************************************/ +/* + * Begin non-standard functions. + */ + +JEMALLOC_ATTR(visibility("default")) +size_t +JEMALLOC_P(malloc_usable_size)(const void *ptr) +{ + size_t ret; + + assert(ptr != NULL); + ret = isalloc(ptr); + + return (ret); +} + +#ifdef JEMALLOC_SWAP +JEMALLOC_ATTR(visibility("default")) +int +JEMALLOC_P(malloc_swap_enable)(const int *fds, unsigned nfds, int prezeroed) +{ + + /* + * Make sure malloc is initialized, because we need page size, chunk + * size, etc. + */ + if (malloc_init()) + return (-1); + + return (chunk_swap_enable(fds, nfds, (prezeroed != 0)) ? -1 : 0); +} +#endif + +JEMALLOC_ATTR(visibility("default")) +void +JEMALLOC_P(malloc_stats_print)(void (*write_cb)(void *, const char *), + void *cbopaque, const char *opts) +{ + + stats_print(write_cb, cbopaque, opts); +} + +JEMALLOC_ATTR(visibility("default")) +int +JEMALLOC_P(mallctl)(const char *name, void *oldp, size_t *oldlenp, void *newp, + size_t newlen) +{ + + if (malloc_init()) + return (EAGAIN); + + return (ctl_byname(name, oldp, oldlenp, newp, newlen)); +} + +JEMALLOC_ATTR(visibility("default")) +int +JEMALLOC_P(mallctlnametomib)(const char *name, size_t *mibp, size_t *miblenp) +{ + + if (malloc_init()) + return (EAGAIN); + + return (ctl_nametomib(name, mibp, miblenp)); +} + +JEMALLOC_ATTR(visibility("default")) +int +JEMALLOC_P(mallctlbymib)(const size_t *mib, size_t miblen, void *oldp, + size_t *oldlenp, void *newp, size_t newlen) +{ + + if (malloc_init()) + return (EAGAIN); + + return (ctl_bymib(mib, miblen, oldp, oldlenp, newp, newlen)); +} + +/* + * End non-standard functions. + */ +/******************************************************************************/ + +/* + * The following functions are used by threading libraries for protection of + * malloc during fork(). These functions are only called if the program is + * running in threaded mode, so there is no need to check whether the program + * is threaded here. + */ + +static void +jemalloc_prefork(void) +{ + unsigned i; + + /* Acquire all mutexes in a safe order. */ + + malloc_mutex_lock(&arenas_lock); + for (i = 0; i < narenas; i++) { + if (arenas[i] != NULL) + malloc_mutex_lock(&arenas[i]->lock); + } + + malloc_mutex_lock(&base_mtx); + + malloc_mutex_lock(&huge_mtx); + +#ifdef JEMALLOC_DSS + malloc_mutex_lock(&dss_mtx); +#endif + +#ifdef JEMALLOC_SWAP + malloc_mutex_lock(&swap_mtx); +#endif +} + +static void +jemalloc_postfork(void) +{ + unsigned i; + + /* Release all mutexes, now that fork() has completed. */ + +#ifdef JEMALLOC_SWAP + malloc_mutex_unlock(&swap_mtx); +#endif + +#ifdef JEMALLOC_DSS + malloc_mutex_unlock(&dss_mtx); +#endif + + malloc_mutex_unlock(&huge_mtx); + + malloc_mutex_unlock(&base_mtx); + + for (i = 0; i < narenas; i++) { + if (arenas[i] != NULL) + malloc_mutex_unlock(&arenas[i]->lock); + } + malloc_mutex_unlock(&arenas_lock); +} diff --git a/dep/jemalloc/jemalloc/internal/arena.h b/dep/jemalloc/jemalloc/internal/arena.h new file mode 100644 index 00000000000..bb4ce2a54f7 --- /dev/null +++ b/dep/jemalloc/jemalloc/internal/arena.h @@ -0,0 +1,537 @@ +/******************************************************************************/ +#ifdef JEMALLOC_H_TYPES + +/* + * Subpages are an artificially designated partitioning of pages. Their only + * purpose is to support subpage-spaced size classes. + * + * There must be at least 4 subpages per page, due to the way size classes are + * handled. + */ +#define LG_SUBPAGE 8 +#define SUBPAGE ((size_t)(1U << LG_SUBPAGE)) +#define SUBPAGE_MASK (SUBPAGE - 1) + +/* Return the smallest subpage multiple that is >= s. */ +#define SUBPAGE_CEILING(s) \ + (((s) + SUBPAGE_MASK) & ~SUBPAGE_MASK) + +#ifdef JEMALLOC_TINY + /* Smallest size class to support. */ +# define LG_TINY_MIN LG_SIZEOF_PTR +#endif + +/* + * Maximum size class that is a multiple of the quantum, but not (necessarily) + * a power of 2. Above this size, allocations are rounded up to the nearest + * power of 2. + */ +#define LG_QSPACE_MAX_DEFAULT 7 + +/* + * Maximum size class that is a multiple of the cacheline, but not (necessarily) + * a power of 2. Above this size, allocations are rounded up to the nearest + * power of 2. + */ +#define LG_CSPACE_MAX_DEFAULT 9 + +/* + * RUN_MAX_OVRHD indicates maximum desired run header overhead. Runs are sized + * as small as possible such that this setting is still honored, without + * violating other constraints. The goal is to make runs as small as possible + * without exceeding a per run external fragmentation threshold. + * + * We use binary fixed point math for overhead computations, where the binary + * point is implicitly RUN_BFP bits to the left. + * + * Note that it is possible to set RUN_MAX_OVRHD low enough that it cannot be + * honored for some/all object sizes, since there is one bit of header overhead + * per object (plus a constant). This constraint is relaxed (ignored) for runs + * that are so small that the per-region overhead is greater than: + * + * (RUN_MAX_OVRHD / (reg_size << (3+RUN_BFP)) + */ +#define RUN_BFP 12 +/* \/ Implicit binary fixed point. */ +#define RUN_MAX_OVRHD 0x0000003dU +#define RUN_MAX_OVRHD_RELAX 0x00001800U + +/* + * The minimum ratio of active:dirty pages per arena is computed as: + * + * (nactive >> opt_lg_dirty_mult) >= ndirty + * + * So, supposing that opt_lg_dirty_mult is 5, there can be no less than 32 + * times as many active pages as dirty pages. + */ +#define LG_DIRTY_MULT_DEFAULT 5 + +typedef struct arena_chunk_map_s arena_chunk_map_t; +typedef struct arena_chunk_s arena_chunk_t; +typedef struct arena_run_s arena_run_t; +typedef struct arena_bin_s arena_bin_t; +typedef struct arena_s arena_t; + +#endif /* JEMALLOC_H_TYPES */ +/******************************************************************************/ +#ifdef JEMALLOC_H_STRUCTS + +/* Each element of the chunk map corresponds to one page within the chunk. */ +struct arena_chunk_map_s { + union { + /* + * Linkage for run trees. There are two disjoint uses: + * + * 1) arena_t's runs_avail_{clean,dirty} trees. + * 2) arena_run_t conceptually uses this linkage for in-use + * non-full runs, rather than directly embedding linkage. + */ + rb_node(arena_chunk_map_t) rb_link; + /* + * List of runs currently in purgatory. arena_chunk_purge() + * temporarily allocates runs that contain dirty pages while + * purging, so that other threads cannot use the runs while the + * purging thread is operating without the arena lock held. + */ + ql_elm(arena_chunk_map_t) ql_link; + } u; + +#ifdef JEMALLOC_PROF + /* Profile counters, used for large object runs. */ + prof_thr_cnt_t *prof_cnt; +#endif + + /* + * Run address (or size) and various flags are stored together. The bit + * layout looks like (assuming 32-bit system): + * + * ???????? ???????? ????---- ----dzla + * + * ? : Unallocated: Run address for first/last pages, unset for internal + * pages. + * Small: Run page offset. + * Large: Run size for first page, unset for trailing pages. + * - : Unused. + * d : dirty? + * z : zeroed? + * l : large? + * a : allocated? + * + * Following are example bit patterns for the three types of runs. + * + * p : run page offset + * s : run size + * c : size class (used only if prof_promote is true) + * x : don't care + * - : 0 + * + : 1 + * [DZLA] : bit set + * [dzla] : bit unset + * + * Unallocated (clean): + * ssssssss ssssssss ssss---- ----dz-- + * xxxxxxxx xxxxxxxx xxxx---- -----Zxx + * ssssssss ssssssss ssss---- ----dZ-- + * + * Unallocated (dirty): + * ssssssss ssssssss ssss---- ----D--- + * xxxxxxxx xxxxxxxx xxxx---- ----xxxx + * ssssssss ssssssss ssss---- ----D--- + * + * Small: + * pppppppp pppppppp pppp---- ----d--a + * pppppppp pppppppp pppp---- -------a + * pppppppp pppppppp pppp---- ----d--a + * + * Large: + * ssssssss ssssssss ssss++++ ++++D-la + * xxxxxxxx xxxxxxxx xxxx---- ----xxxx + * -------- -------- -------- ----D-la + * + * Large (sampled, size <= PAGE_SIZE): + * ssssssss ssssssss sssscccc ccccD-la + * + * Large (not sampled, size == PAGE_SIZE): + * ssssssss ssssssss ssss++++ ++++D-la + */ + size_t bits; +#ifdef JEMALLOC_PROF +#define CHUNK_MAP_CLASS_SHIFT 4 +#define CHUNK_MAP_CLASS_MASK ((size_t)0xff0U) +#endif +#define CHUNK_MAP_FLAGS_MASK ((size_t)0xfU) +#define CHUNK_MAP_DIRTY ((size_t)0x8U) +#define CHUNK_MAP_ZEROED ((size_t)0x4U) +#define CHUNK_MAP_LARGE ((size_t)0x2U) +#define CHUNK_MAP_ALLOCATED ((size_t)0x1U) +#define CHUNK_MAP_KEY CHUNK_MAP_ALLOCATED +}; +typedef rb_tree(arena_chunk_map_t) arena_avail_tree_t; +typedef rb_tree(arena_chunk_map_t) arena_run_tree_t; + +/* Arena chunk header. */ +struct arena_chunk_s { + /* Arena that owns the chunk. */ + arena_t *arena; + + /* Linkage for the arena's chunks_dirty list. */ + ql_elm(arena_chunk_t) link_dirty; + + /* + * True if the chunk is currently in the chunks_dirty list, due to + * having at some point contained one or more dirty pages. Removal + * from chunks_dirty is lazy, so (dirtied && ndirty == 0) is possible. + */ + bool dirtied; + + /* Number of dirty pages. */ + size_t ndirty; + + /* Map of pages within chunk that keeps track of free/large/small. */ + arena_chunk_map_t map[1]; /* Dynamically sized. */ +}; +typedef rb_tree(arena_chunk_t) arena_chunk_tree_t; + +struct arena_run_s { +#ifdef JEMALLOC_DEBUG + uint32_t magic; +# define ARENA_RUN_MAGIC 0x384adf93 +#endif + + /* Bin this run is associated with. */ + arena_bin_t *bin; + + /* Stack of available freed regions, or NULL. */ + void *avail; + + /* Next region that has never been allocated, or run boundary. */ + void *next; + + /* Number of free regions in run. */ + unsigned nfree; +}; + +struct arena_bin_s { + /* + * All operations on runcur, runs, and stats require that lock be + * locked. Run allocation/deallocation are protected by the arena lock, + * which may be acquired while holding one or more bin locks, but not + * vise versa. + */ + malloc_mutex_t lock; + + /* + * Current run being used to service allocations of this bin's size + * class. + */ + arena_run_t *runcur; + + /* + * Tree of non-full runs. This tree is used when looking for an + * existing run when runcur is no longer usable. We choose the + * non-full run that is lowest in memory; this policy tends to keep + * objects packed well, and it can also help reduce the number of + * almost-empty chunks. + */ + arena_run_tree_t runs; + + /* Size of regions in a run for this bin's size class. */ + size_t reg_size; + + /* Total size of a run for this bin's size class. */ + size_t run_size; + + /* Total number of regions in a run for this bin's size class. */ + uint32_t nregs; + +#ifdef JEMALLOC_PROF + /* + * Offset of first (prof_cnt_t *) in a run header for this bin's size + * class, or 0 if (opt_prof == false). + */ + uint32_t cnt0_offset; +#endif + + /* Offset of first region in a run for this bin's size class. */ + uint32_t reg0_offset; + +#ifdef JEMALLOC_STATS + /* Bin statistics. */ + malloc_bin_stats_t stats; +#endif +}; + +struct arena_s { +#ifdef JEMALLOC_DEBUG + uint32_t magic; +# define ARENA_MAGIC 0x947d3d24 +#endif + + /* This arena's index within the arenas array. */ + unsigned ind; + + /* + * All non-bin-related operations on this arena require that lock be + * locked. + */ + malloc_mutex_t lock; + +#ifdef JEMALLOC_STATS + arena_stats_t stats; +# ifdef JEMALLOC_TCACHE + /* + * List of tcaches for extant threads associated with this arena. + * Stats from these are merged incrementally, and at exit. + */ + ql_head(tcache_t) tcache_ql; +# endif +#endif + +#ifdef JEMALLOC_PROF + uint64_t prof_accumbytes; +#endif + + /* List of dirty-page-containing chunks this arena manages. */ + ql_head(arena_chunk_t) chunks_dirty; + + /* + * In order to avoid rapid chunk allocation/deallocation when an arena + * oscillates right on the cusp of needing a new chunk, cache the most + * recently freed chunk. The spare is left in the arena's chunk trees + * until it is deleted. + * + * There is one spare chunk per arena, rather than one spare total, in + * order to avoid interactions between multiple threads that could make + * a single spare inadequate. + */ + arena_chunk_t *spare; + + /* Number of pages in active runs. */ + size_t nactive; + + /* + * Current count of pages within unused runs that are potentially + * dirty, and for which madvise(... MADV_DONTNEED) has not been called. + * By tracking this, we can institute a limit on how much dirty unused + * memory is mapped for each arena. + */ + size_t ndirty; + + /* + * Approximate number of pages being purged. It is possible for + * multiple threads to purge dirty pages concurrently, and they use + * npurgatory to indicate the total number of pages all threads are + * attempting to purge. + */ + size_t npurgatory; + + /* + * Size/address-ordered trees of this arena's available runs. The trees + * are used for first-best-fit run allocation. The dirty tree contains + * runs with dirty pages (i.e. very likely to have been touched and + * therefore have associated physical pages), whereas the clean tree + * contains runs with pages that either have no associated physical + * pages, or have pages that the kernel may recycle at any time due to + * previous madvise(2) calls. The dirty tree is used in preference to + * the clean tree for allocations, because using dirty pages reduces + * the amount of dirty purging necessary to keep the active:dirty page + * ratio below the purge threshold. + */ + arena_avail_tree_t runs_avail_clean; + arena_avail_tree_t runs_avail_dirty; + + /* + * bins is used to store trees of free regions of the following sizes, + * assuming a 16-byte quantum, 4 KiB page size, and default + * JEMALLOC_OPTIONS. + * + * bins[i] | size | + * --------+--------+ + * 0 | 2 | + * 1 | 4 | + * 2 | 8 | + * --------+--------+ + * 3 | 16 | + * 4 | 32 | + * 5 | 48 | + * : : + * 8 | 96 | + * 9 | 112 | + * 10 | 128 | + * --------+--------+ + * 11 | 192 | + * 12 | 256 | + * 13 | 320 | + * 14 | 384 | + * 15 | 448 | + * 16 | 512 | + * --------+--------+ + * 17 | 768 | + * 18 | 1024 | + * 19 | 1280 | + * : : + * 27 | 3328 | + * 28 | 3584 | + * 29 | 3840 | + * --------+--------+ + * 30 | 4 KiB | + * 31 | 6 KiB | + * 33 | 8 KiB | + * : : + * 43 | 28 KiB | + * 44 | 30 KiB | + * 45 | 32 KiB | + * --------+--------+ + */ + arena_bin_t bins[1]; /* Dynamically sized. */ +}; + +#endif /* JEMALLOC_H_STRUCTS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_EXTERNS + +extern size_t opt_lg_qspace_max; +extern size_t opt_lg_cspace_max; +extern ssize_t opt_lg_dirty_mult; +extern uint8_t const *small_size2bin; + +/* Various bin-related settings. */ +#ifdef JEMALLOC_TINY /* Number of (2^n)-spaced tiny bins. */ +# define ntbins ((unsigned)(LG_QUANTUM - LG_TINY_MIN)) +#else +# define ntbins 0 +#endif +extern unsigned nqbins; /* Number of quantum-spaced bins. */ +extern unsigned ncbins; /* Number of cacheline-spaced bins. */ +extern unsigned nsbins; /* Number of subpage-spaced bins. */ +extern unsigned nbins; +#ifdef JEMALLOC_TINY +# define tspace_max ((size_t)(QUANTUM >> 1)) +#endif +#define qspace_min QUANTUM +extern size_t qspace_max; +extern size_t cspace_min; +extern size_t cspace_max; +extern size_t sspace_min; +extern size_t sspace_max; +#define small_maxclass sspace_max + +#define nlclasses (chunk_npages - arena_chunk_header_npages) + +#ifdef JEMALLOC_TCACHE +void arena_tcache_fill_small(arena_t *arena, tcache_bin_t *tbin, + size_t binind +# ifdef JEMALLOC_PROF + , uint64_t prof_accumbytes +# endif + ); +#endif +#ifdef JEMALLOC_PROF +void arena_prof_accum(arena_t *arena, uint64_t accumbytes); +#endif +void *arena_malloc_small(arena_t *arena, size_t size, bool zero); +void *arena_malloc_large(arena_t *arena, size_t size, bool zero); +void *arena_malloc(size_t size, bool zero); +void *arena_palloc(arena_t *arena, size_t alignment, size_t size, + size_t alloc_size); +size_t arena_salloc(const void *ptr); +#ifdef JEMALLOC_PROF +void arena_prof_promoted(const void *ptr, size_t size); +size_t arena_salloc_demote(const void *ptr); +prof_thr_cnt_t *arena_prof_cnt_get(const void *ptr); +void arena_prof_cnt_set(const void *ptr, prof_thr_cnt_t *cnt); +#endif +void arena_dalloc_bin(arena_t *arena, arena_chunk_t *chunk, void *ptr, + arena_chunk_map_t *mapelm); +void arena_dalloc_large(arena_t *arena, arena_chunk_t *chunk, void *ptr); +#ifdef JEMALLOC_STATS +void arena_stats_merge(arena_t *arena, size_t *nactive, size_t *ndirty, + arena_stats_t *astats, malloc_bin_stats_t *bstats, + malloc_large_stats_t *lstats); +#endif +void *arena_ralloc(void *ptr, size_t size, size_t oldsize); +bool arena_new(arena_t *arena, unsigned ind); +bool arena_boot(void); + +#endif /* JEMALLOC_H_EXTERNS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_INLINES + +#ifndef JEMALLOC_ENABLE_INLINE +void arena_dalloc(arena_t *arena, arena_chunk_t *chunk, void *ptr); +#endif + +#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_ARENA_C_)) +JEMALLOC_INLINE void +arena_dalloc(arena_t *arena, arena_chunk_t *chunk, void *ptr) +{ + size_t pageind; + arena_chunk_map_t *mapelm; + + assert(arena != NULL); + assert(arena->magic == ARENA_MAGIC); + assert(chunk->arena == arena); + assert(ptr != NULL); + assert(CHUNK_ADDR2BASE(ptr) != ptr); + + pageind = (((uintptr_t)ptr - (uintptr_t)chunk) >> PAGE_SHIFT); + mapelm = &chunk->map[pageind]; + assert((mapelm->bits & CHUNK_MAP_ALLOCATED) != 0); + if ((mapelm->bits & CHUNK_MAP_LARGE) == 0) { + /* Small allocation. */ +#ifdef JEMALLOC_TCACHE + tcache_t *tcache; + + if ((tcache = tcache_get()) != NULL) + tcache_dalloc_small(tcache, ptr); + else { +#endif + arena_run_t *run; + arena_bin_t *bin; + + run = (arena_run_t *)((uintptr_t)chunk + + (uintptr_t)((pageind - (mapelm->bits >> + PAGE_SHIFT)) << PAGE_SHIFT)); + assert(run->magic == ARENA_RUN_MAGIC); + assert(((uintptr_t)ptr - ((uintptr_t)run + + (uintptr_t)run->bin->reg0_offset)) % + run->bin->reg_size == 0); + bin = run->bin; + malloc_mutex_lock(&bin->lock); + arena_dalloc_bin(arena, chunk, ptr, mapelm); + malloc_mutex_unlock(&bin->lock); +#ifdef JEMALLOC_TCACHE + } +#endif + } else { +#ifdef JEMALLOC_TCACHE + size_t size = mapelm->bits & ~PAGE_MASK; + + assert(((uintptr_t)ptr & PAGE_MASK) == 0); + if (size <= tcache_maxclass) { + tcache_t *tcache; + + if ((tcache = tcache_get()) != NULL) + tcache_dalloc_large(tcache, ptr, size); + else { + malloc_mutex_lock(&arena->lock); + arena_dalloc_large(arena, chunk, ptr); + malloc_mutex_unlock(&arena->lock); + } + } else { + malloc_mutex_lock(&arena->lock); + arena_dalloc_large(arena, chunk, ptr); + malloc_mutex_unlock(&arena->lock); + } +#else + assert(((uintptr_t)ptr & PAGE_MASK) == 0); + malloc_mutex_lock(&arena->lock); + arena_dalloc_large(arena, chunk, ptr); + malloc_mutex_unlock(&arena->lock); +#endif + } +} +#endif + +#endif /* JEMALLOC_H_INLINES */ +/******************************************************************************/ diff --git a/dep/jemalloc/jemalloc/internal/base.h b/dep/jemalloc/jemalloc/internal/base.h new file mode 100644 index 00000000000..e353f309bd2 --- /dev/null +++ b/dep/jemalloc/jemalloc/internal/base.h @@ -0,0 +1,24 @@ +/******************************************************************************/ +#ifdef JEMALLOC_H_TYPES + +#endif /* JEMALLOC_H_TYPES */ +/******************************************************************************/ +#ifdef JEMALLOC_H_STRUCTS + +#endif /* JEMALLOC_H_STRUCTS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_EXTERNS + +extern malloc_mutex_t base_mtx; + +void *base_alloc(size_t size); +extent_node_t *base_node_alloc(void); +void base_node_dealloc(extent_node_t *node); +bool base_boot(void); + +#endif /* JEMALLOC_H_EXTERNS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_INLINES + +#endif /* JEMALLOC_H_INLINES */ +/******************************************************************************/ diff --git a/dep/jemalloc/jemalloc/internal/chunk.h b/dep/jemalloc/jemalloc/internal/chunk.h new file mode 100644 index 00000000000..1f6abf782f1 --- /dev/null +++ b/dep/jemalloc/jemalloc/internal/chunk.h @@ -0,0 +1,61 @@ +/******************************************************************************/ +#ifdef JEMALLOC_H_TYPES + +/* + * Size and alignment of memory chunks that are allocated by the OS's virtual + * memory system. + */ +#define LG_CHUNK_DEFAULT 22 + +/* Return the chunk address for allocation address a. */ +#define CHUNK_ADDR2BASE(a) \ + ((void *)((uintptr_t)(a) & ~chunksize_mask)) + +/* Return the chunk offset of address a. */ +#define CHUNK_ADDR2OFFSET(a) \ + ((size_t)((uintptr_t)(a) & chunksize_mask)) + +/* Return the smallest chunk multiple that is >= s. */ +#define CHUNK_CEILING(s) \ + (((s) + chunksize_mask) & ~chunksize_mask) + +#endif /* JEMALLOC_H_TYPES */ +/******************************************************************************/ +#ifdef JEMALLOC_H_STRUCTS + +#endif /* JEMALLOC_H_STRUCTS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_EXTERNS + +extern size_t opt_lg_chunk; +#ifdef JEMALLOC_SWAP +extern bool opt_overcommit; +#endif + +#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) +/* Protects stats_chunks; currently not used for any other purpose. */ +extern malloc_mutex_t chunks_mtx; +/* Chunk statistics. */ +extern chunk_stats_t stats_chunks; +#endif + +extern size_t chunksize; +extern size_t chunksize_mask; /* (chunksize - 1). */ +extern size_t chunk_npages; +extern size_t arena_chunk_header_npages; +extern size_t arena_maxclass; /* Max size class for arenas. */ + +void *chunk_alloc(size_t size, bool *zero); +void chunk_dealloc(void *chunk, size_t size); +bool chunk_boot(void); + +#endif /* JEMALLOC_H_EXTERNS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_INLINES + +#endif /* JEMALLOC_H_INLINES */ +/******************************************************************************/ + +#include "jemalloc/internal/chunk_swap.h" +#include "jemalloc/internal/chunk_dss.h" +#include "jemalloc/internal/chunk_mmap.h" diff --git a/dep/jemalloc/jemalloc/internal/chunk_dss.h b/dep/jemalloc/jemalloc/internal/chunk_dss.h new file mode 100644 index 00000000000..6be4ad1f212 --- /dev/null +++ b/dep/jemalloc/jemalloc/internal/chunk_dss.h @@ -0,0 +1,29 @@ +#ifdef JEMALLOC_DSS +/******************************************************************************/ +#ifdef JEMALLOC_H_TYPES + +#endif /* JEMALLOC_H_TYPES */ +/******************************************************************************/ +#ifdef JEMALLOC_H_STRUCTS + +#endif /* JEMALLOC_H_STRUCTS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_EXTERNS + +/* + * Protects sbrk() calls. This avoids malloc races among threads, though it + * does not protect against races with threads that call sbrk() directly. + */ +extern malloc_mutex_t dss_mtx; + +void *chunk_alloc_dss(size_t size, bool *zero); +bool chunk_dealloc_dss(void *chunk, size_t size); +bool chunk_dss_boot(void); + +#endif /* JEMALLOC_H_EXTERNS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_INLINES + +#endif /* JEMALLOC_H_INLINES */ +/******************************************************************************/ +#endif /* JEMALLOC_DSS */ diff --git a/dep/jemalloc/jemalloc/internal/chunk_mmap.h b/dep/jemalloc/jemalloc/internal/chunk_mmap.h new file mode 100644 index 00000000000..8fb90b77c9b --- /dev/null +++ b/dep/jemalloc/jemalloc/internal/chunk_mmap.h @@ -0,0 +1,20 @@ +/******************************************************************************/ +#ifdef JEMALLOC_H_TYPES + +#endif /* JEMALLOC_H_TYPES */ +/******************************************************************************/ +#ifdef JEMALLOC_H_STRUCTS + +#endif /* JEMALLOC_H_STRUCTS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_EXTERNS + +void *chunk_alloc_mmap(size_t size); +void chunk_dealloc_mmap(void *chunk, size_t size); + +#endif /* JEMALLOC_H_EXTERNS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_INLINES + +#endif /* JEMALLOC_H_INLINES */ +/******************************************************************************/ diff --git a/dep/jemalloc/jemalloc/internal/chunk_swap.h b/dep/jemalloc/jemalloc/internal/chunk_swap.h new file mode 100644 index 00000000000..d50cb197449 --- /dev/null +++ b/dep/jemalloc/jemalloc/internal/chunk_swap.h @@ -0,0 +1,33 @@ +#ifdef JEMALLOC_SWAP +/******************************************************************************/ +#ifdef JEMALLOC_H_TYPES + +#endif /* JEMALLOC_H_TYPES */ +/******************************************************************************/ +#ifdef JEMALLOC_H_STRUCTS + +#endif /* JEMALLOC_H_STRUCTS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_EXTERNS + +extern malloc_mutex_t swap_mtx; +extern bool swap_enabled; +extern bool swap_prezeroed; +extern size_t swap_nfds; +extern int *swap_fds; +#ifdef JEMALLOC_STATS +extern size_t swap_avail; +#endif + +void *chunk_alloc_swap(size_t size, bool *zero); +bool chunk_dealloc_swap(void *chunk, size_t size); +bool chunk_swap_enable(const int *fds, unsigned nfds, bool prezeroed); +bool chunk_swap_boot(void); + +#endif /* JEMALLOC_H_EXTERNS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_INLINES + +#endif /* JEMALLOC_H_INLINES */ +/******************************************************************************/ +#endif /* JEMALLOC_SWAP */ diff --git a/dep/jemalloc/jemalloc/internal/ckh.h b/dep/jemalloc/jemalloc/internal/ckh.h new file mode 100644 index 00000000000..c39ea5c75ef --- /dev/null +++ b/dep/jemalloc/jemalloc/internal/ckh.h @@ -0,0 +1,95 @@ +/******************************************************************************/ +#ifdef JEMALLOC_H_TYPES + +typedef struct ckh_s ckh_t; +typedef struct ckhc_s ckhc_t; + +/* Typedefs to allow easy function pointer passing. */ +typedef void ckh_hash_t (const void *, unsigned, size_t *, size_t *); +typedef bool ckh_keycomp_t (const void *, const void *); + +/* Maintain counters used to get an idea of performance. */ +/* #define CKH_COUNT */ +/* Print counter values in ckh_delete() (requires CKH_COUNT). */ +/* #define CKH_VERBOSE */ + +/* + * There are 2^LG_CKH_BUCKET_CELLS cells in each hash table bucket. Try to fit + * one bucket per L1 cache line. + */ +#define LG_CKH_BUCKET_CELLS (LG_CACHELINE - LG_SIZEOF_PTR - 1) + +#endif /* JEMALLOC_H_TYPES */ +/******************************************************************************/ +#ifdef JEMALLOC_H_STRUCTS + +/* Hash table cell. */ +struct ckhc_s { + const void *key; + const void *data; +}; + +struct ckh_s { +#ifdef JEMALLOC_DEBUG +#define CKH_MAGIG 0x3af2489d + uint32_t magic; +#endif + +#ifdef CKH_COUNT + /* Counters used to get an idea of performance. */ + uint64_t ngrows; + uint64_t nshrinks; + uint64_t nshrinkfails; + uint64_t ninserts; + uint64_t nrelocs; +#endif + + /* Used for pseudo-random number generation. */ +#define CKH_A 12345 +#define CKH_C 12347 + uint32_t prn_state; + + /* Total number of items. */ + size_t count; + + /* + * Minimum and current number of hash table buckets. There are + * 2^LG_CKH_BUCKET_CELLS cells per bucket. + */ + unsigned lg_minbuckets; + unsigned lg_curbuckets; + + /* Hash and comparison functions. */ + ckh_hash_t *hash; + ckh_keycomp_t *keycomp; + + /* Hash table with 2^lg_curbuckets buckets. */ + ckhc_t *tab; +}; + +#endif /* JEMALLOC_H_STRUCTS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_EXTERNS + +bool ckh_new(ckh_t *ckh, size_t minitems, ckh_hash_t *hash, + ckh_keycomp_t *keycomp); +void ckh_delete(ckh_t *ckh); +size_t ckh_count(ckh_t *ckh); +bool ckh_iter(ckh_t *ckh, size_t *tabind, void **key, void **data); +bool ckh_insert(ckh_t *ckh, const void *key, const void *data); +bool ckh_remove(ckh_t *ckh, const void *searchkey, void **key, + void **data); +bool ckh_search(ckh_t *ckh, const void *seachkey, void **key, void **data); +void ckh_string_hash(const void *key, unsigned minbits, size_t *hash1, + size_t *hash2); +bool ckh_string_keycomp(const void *k1, const void *k2); +void ckh_pointer_hash(const void *key, unsigned minbits, size_t *hash1, + size_t *hash2); +bool ckh_pointer_keycomp(const void *k1, const void *k2); + +#endif /* JEMALLOC_H_EXTERNS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_INLINES + +#endif /* JEMALLOC_H_INLINES */ +/******************************************************************************/ diff --git a/dep/jemalloc/jemalloc/internal/ctl.h b/dep/jemalloc/jemalloc/internal/ctl.h new file mode 100644 index 00000000000..7bbf21e0e85 --- /dev/null +++ b/dep/jemalloc/jemalloc/internal/ctl.h @@ -0,0 +1,117 @@ +/******************************************************************************/ +#ifdef JEMALLOC_H_TYPES + +typedef struct ctl_node_s ctl_node_t; +typedef struct ctl_arena_stats_s ctl_arena_stats_t; +typedef struct ctl_stats_s ctl_stats_t; + +#endif /* JEMALLOC_H_TYPES */ +/******************************************************************************/ +#ifdef JEMALLOC_H_STRUCTS + +struct ctl_node_s { + bool named; + union { + struct { + const char *name; + /* If (nchildren == 0), this is a terminal node. */ + unsigned nchildren; + const ctl_node_t *children; + } named; + struct { + const ctl_node_t *(*index)(const size_t *, size_t, + size_t); + } indexed; + } u; + int (*ctl)(const size_t *, size_t, void *, size_t *, void *, + size_t); +}; + +struct ctl_arena_stats_s { + bool initialized; + size_t pactive; + size_t pdirty; +#ifdef JEMALLOC_STATS + arena_stats_t astats; + + /* Aggregate stats for small size classes, based on bin stats. */ + size_t allocated_small; + uint64_t nmalloc_small; + uint64_t ndalloc_small; + uint64_t nrequests_small; + + malloc_bin_stats_t *bstats; /* nbins elements. */ + malloc_large_stats_t *lstats; /* nlclasses elements. */ +#endif +}; + +struct ctl_stats_s { +#ifdef JEMALLOC_STATS + size_t allocated; + size_t active; + size_t mapped; + struct { + size_t current; /* stats_chunks.curchunks */ + uint64_t total; /* stats_chunks.nchunks */ + size_t high; /* stats_chunks.highchunks */ + } chunks; + struct { + size_t allocated; /* huge_allocated */ + uint64_t nmalloc; /* huge_nmalloc */ + uint64_t ndalloc; /* huge_ndalloc */ + } huge; +#endif + ctl_arena_stats_t *arenas; /* (narenas + 1) elements. */ +#ifdef JEMALLOC_SWAP + size_t swap_avail; +#endif +}; + +#endif /* JEMALLOC_H_STRUCTS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_EXTERNS + +int ctl_byname(const char *name, void *oldp, size_t *oldlenp, void *newp, + size_t newlen); +int ctl_nametomib(const char *name, size_t *mibp, size_t *miblenp); + +int ctl_bymib(const size_t *mib, size_t miblen, void *oldp, size_t *oldlenp, + void *newp, size_t newlen); +bool ctl_boot(void); + +#define xmallctl(name, oldp, oldlenp, newp, newlen) do { \ + if (JEMALLOC_P(mallctl)(name, oldp, oldlenp, newp, newlen) \ + != 0) { \ + malloc_write(": Invalid xmallctl(\""); \ + malloc_write(name); \ + malloc_write("\", ...) call\n"); \ + abort(); \ + } \ +} while (0) + +#define xmallctlnametomib(name, mibp, miblenp) do { \ + if (JEMALLOC_P(mallctlnametomib)(name, mibp, miblenp) != 0) { \ + malloc_write( \ + ": Invalid xmallctlnametomib(\""); \ + malloc_write(name); \ + malloc_write("\", ...) call\n"); \ + abort(); \ + } \ +} while (0) + +#define xmallctlbymib(mib, miblen, oldp, oldlenp, newp, newlen) do { \ + if (JEMALLOC_P(mallctlbymib)(mib, miblen, oldp, oldlenp, newp, \ + newlen) != 0) { \ + malloc_write( \ + ": Invalid xmallctlbymib() call\n"); \ + abort(); \ + } \ +} while (0) + +#endif /* JEMALLOC_H_EXTERNS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_INLINES + +#endif /* JEMALLOC_H_INLINES */ +/******************************************************************************/ + diff --git a/dep/jemalloc/jemalloc/internal/extent.h b/dep/jemalloc/jemalloc/internal/extent.h new file mode 100644 index 00000000000..33a4e9a3852 --- /dev/null +++ b/dep/jemalloc/jemalloc/internal/extent.h @@ -0,0 +1,49 @@ +/******************************************************************************/ +#ifdef JEMALLOC_H_TYPES + +typedef struct extent_node_s extent_node_t; + +#endif /* JEMALLOC_H_TYPES */ +/******************************************************************************/ +#ifdef JEMALLOC_H_STRUCTS + +/* Tree of extents. */ +struct extent_node_s { +#if (defined(JEMALLOC_SWAP) || defined(JEMALLOC_DSS)) + /* Linkage for the size/address-ordered tree. */ + rb_node(extent_node_t) link_szad; +#endif + + /* Linkage for the address-ordered tree. */ + rb_node(extent_node_t) link_ad; + +#ifdef JEMALLOC_PROF + /* Profile counters, used for huge objects. */ + prof_thr_cnt_t *prof_cnt; +#endif + + /* Pointer to the extent that this tree node is responsible for. */ + void *addr; + + /* Total region size. */ + size_t size; +}; +typedef rb_tree(extent_node_t) extent_tree_t; + +#endif /* JEMALLOC_H_STRUCTS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_EXTERNS + +#if (defined(JEMALLOC_SWAP) || defined(JEMALLOC_DSS)) +rb_proto(, extent_tree_szad_, extent_tree_t, extent_node_t) +#endif + +rb_proto(, extent_tree_ad_, extent_tree_t, extent_node_t) + +#endif /* JEMALLOC_H_EXTERNS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_INLINES + +#endif /* JEMALLOC_H_INLINES */ +/******************************************************************************/ + diff --git a/dep/jemalloc/jemalloc/internal/hash.h b/dep/jemalloc/jemalloc/internal/hash.h new file mode 100644 index 00000000000..d12cdb8359f --- /dev/null +++ b/dep/jemalloc/jemalloc/internal/hash.h @@ -0,0 +1,70 @@ +/******************************************************************************/ +#ifdef JEMALLOC_H_TYPES + +#endif /* JEMALLOC_H_TYPES */ +/******************************************************************************/ +#ifdef JEMALLOC_H_STRUCTS + +#endif /* JEMALLOC_H_STRUCTS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_EXTERNS + +#endif /* JEMALLOC_H_EXTERNS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_INLINES + +#ifndef JEMALLOC_ENABLE_INLINE +uint64_t hash(const void *key, size_t len, uint64_t seed); +#endif + +#if (defined(JEMALLOC_ENABLE_INLINE) || defined(HASH_C_)) +/* + * The following hash function is based on MurmurHash64A(), placed into the + * public domain by Austin Appleby. See http://murmurhash.googlepages.com/ for + * details. + */ +JEMALLOC_INLINE uint64_t +hash(const void *key, size_t len, uint64_t seed) +{ + const uint64_t m = 0xc6a4a7935bd1e995; + const int r = 47; + uint64_t h = seed ^ (len * m); + const uint64_t *data = (const uint64_t *)key; + const uint64_t *end = data + (len/8); + const unsigned char *data2; + + assert(((uintptr_t)key & 0x7) == 0); + + while(data != end) { + uint64_t k = *data++; + + k *= m; + k ^= k >> r; + k *= m; + + h ^= k; + h *= m; + } + + data2 = (const unsigned char *)data; + switch(len & 7) { + case 7: h ^= ((uint64_t)(data2[6])) << 48; + case 6: h ^= ((uint64_t)(data2[5])) << 40; + case 5: h ^= ((uint64_t)(data2[4])) << 32; + case 4: h ^= ((uint64_t)(data2[3])) << 24; + case 3: h ^= ((uint64_t)(data2[2])) << 16; + case 2: h ^= ((uint64_t)(data2[1])) << 8; + case 1: h ^= ((uint64_t)(data2[0])); + h *= m; + } + + h ^= h >> r; + h *= m; + h ^= h >> r; + + return h; +} +#endif + +#endif /* JEMALLOC_H_INLINES */ +/******************************************************************************/ diff --git a/dep/jemalloc/jemalloc/internal/huge.h b/dep/jemalloc/jemalloc/internal/huge.h new file mode 100644 index 00000000000..3cf32f7506d --- /dev/null +++ b/dep/jemalloc/jemalloc/internal/huge.h @@ -0,0 +1,38 @@ +/******************************************************************************/ +#ifdef JEMALLOC_H_TYPES + +#endif /* JEMALLOC_H_TYPES */ +/******************************************************************************/ +#ifdef JEMALLOC_H_STRUCTS + +#endif /* JEMALLOC_H_STRUCTS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_EXTERNS + +#ifdef JEMALLOC_STATS +/* Huge allocation statistics. */ +extern uint64_t huge_nmalloc; +extern uint64_t huge_ndalloc; +extern size_t huge_allocated; +#endif + +/* Protects chunk-related data structures. */ +extern malloc_mutex_t huge_mtx; + +void *huge_malloc(size_t size, bool zero); +void *huge_palloc(size_t alignment, size_t size); +void *huge_ralloc(void *ptr, size_t size, size_t oldsize); +void huge_dalloc(void *ptr); +size_t huge_salloc(const void *ptr); +#ifdef JEMALLOC_PROF +prof_thr_cnt_t *huge_prof_cnt_get(const void *ptr); +void huge_prof_cnt_set(const void *ptr, prof_thr_cnt_t *cnt); +#endif +bool huge_boot(void); + +#endif /* JEMALLOC_H_EXTERNS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_INLINES + +#endif /* JEMALLOC_H_INLINES */ +/******************************************************************************/ diff --git a/dep/jemalloc/jemalloc/internal/jemalloc_internal.h b/dep/jemalloc/jemalloc/internal/jemalloc_internal.h new file mode 100644 index 00000000000..03782dd6690 --- /dev/null +++ b/dep/jemalloc/jemalloc/internal/jemalloc_internal.h @@ -0,0 +1,561 @@ +#include +#include +#include +#include +#include +#include + +#include +#include +#ifndef SIZE_T_MAX +# define SIZE_T_MAX SIZE_MAX +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define JEMALLOC_MANGLE +#include "../jemalloc.h" + +#ifdef JEMALLOC_LAZY_LOCK +#include +#endif + +#define RB_COMPACT +#include "jemalloc/internal/rb.h" +#include "jemalloc/internal/qr.h" +#include "jemalloc/internal/ql.h" + +extern void (*JEMALLOC_P(malloc_message))(void *wcbopaque, const char *s); + +/* + * Define a custom assert() in order to reduce the chances of deadlock during + * assertion failure. + */ +#ifdef JEMALLOC_DEBUG +# define assert(e) do { \ + if (!(e)) { \ + char line_buf[UMAX2S_BUFSIZE]; \ + malloc_write(": "); \ + malloc_write(__FILE__); \ + malloc_write(":"); \ + malloc_write(umax2s(__LINE__, 10, line_buf)); \ + malloc_write(": Failed assertion: "); \ + malloc_write("\""); \ + malloc_write(#e); \ + malloc_write("\"\n"); \ + abort(); \ + } \ +} while (0) +#else +#define assert(e) +#endif + +/* + * jemalloc can conceptually be broken into components (arena, tcache, etc.), + * but there are circular dependencies that cannot be broken without + * substantial performance degradation. In order to reduce the effect on + * visual code flow, read the header files in multiple passes, with one of the + * following cpp variables defined during each pass: + * + * JEMALLOC_H_TYPES : Preprocessor-defined constants and psuedo-opaque data + * types. + * JEMALLOC_H_STRUCTS : Data structures. + * JEMALLOC_H_EXTERNS : Extern data declarations and function prototypes. + * JEMALLOC_H_INLINES : Inline functions. + */ +/******************************************************************************/ +#define JEMALLOC_H_TYPES + +#define ZU(z) ((size_t)z) + +#ifndef __DECONST +# define __DECONST(type, var) ((type)(uintptr_t)(const void *)(var)) +#endif + +#ifdef JEMALLOC_DEBUG + /* Disable inlining to make debugging easier. */ +# define JEMALLOC_INLINE +# define inline +#else +# define JEMALLOC_ENABLE_INLINE +# define JEMALLOC_INLINE static inline +#endif + +/* Size of stack-allocated buffer passed to strerror_r(). */ +#define STRERROR_BUF 64 + +/* Minimum alignment of allocations is 2^LG_QUANTUM bytes. */ +#ifdef __i386__ +# define LG_QUANTUM 4 +#endif +#ifdef __ia64__ +# define LG_QUANTUM 4 +#endif +#ifdef __alpha__ +# define LG_QUANTUM 4 +#endif +#ifdef __sparc64__ +# define LG_QUANTUM 4 +#endif +#if (defined(__amd64__) || defined(__x86_64__)) +# define LG_QUANTUM 4 +#endif +#ifdef __arm__ +# define LG_QUANTUM 3 +#endif +#ifdef __mips__ +# define LG_QUANTUM 3 +#endif +#ifdef __powerpc__ +# define LG_QUANTUM 4 +#endif +#ifdef __s390x__ +# define LG_QUANTUM 4 +#endif + +#define QUANTUM ((size_t)(1U << LG_QUANTUM)) +#define QUANTUM_MASK (QUANTUM - 1) + +/* Return the smallest quantum multiple that is >= a. */ +#define QUANTUM_CEILING(a) \ + (((a) + QUANTUM_MASK) & ~QUANTUM_MASK) + +#define SIZEOF_PTR (1U << LG_SIZEOF_PTR) + +/* We can't use TLS in non-PIC programs, since TLS relies on loader magic. */ +#if (!defined(PIC) && !defined(NO_TLS)) +# define NO_TLS +#endif + +/* + * Maximum size of L1 cache line. This is used to avoid cache line aliasing. + * In addition, this controls the spacing of cacheline-spaced size classes. + */ +#define LG_CACHELINE 6 +#define CACHELINE ((size_t)(1U << LG_CACHELINE)) +#define CACHELINE_MASK (CACHELINE - 1) + +/* Return the smallest cacheline multiple that is >= s. */ +#define CACHELINE_CEILING(s) \ + (((s) + CACHELINE_MASK) & ~CACHELINE_MASK) + +/* + * Page size. STATIC_PAGE_SHIFT is determined by the configure script. If + * DYNAMIC_PAGE_SHIFT is enabled, only use the STATIC_PAGE_* macros where + * compile-time values are required for the purposes of defining data + * structures. + */ +#define STATIC_PAGE_SIZE ((size_t)(1U << STATIC_PAGE_SHIFT)) +#define STATIC_PAGE_MASK ((size_t)(STATIC_PAGE_SIZE - 1)) + +#ifdef DYNAMIC_PAGE_SHIFT +# define PAGE_SHIFT lg_pagesize +# define PAGE_SIZE pagesize +# define PAGE_MASK pagesize_mask +#else +# define PAGE_SHIFT STATIC_PAGE_SHIFT +# define PAGE_SIZE STATIC_PAGE_SIZE +# define PAGE_MASK STATIC_PAGE_MASK +#endif + +/* Return the smallest pagesize multiple that is >= s. */ +#define PAGE_CEILING(s) \ + (((s) + PAGE_MASK) & ~PAGE_MASK) + +#include "jemalloc/internal/totally_not_p_r_n.h" +#include "jemalloc/internal/ckh.h" +#include "jemalloc/internal/stats.h" +#include "jemalloc/internal/ctl.h" +#include "jemalloc/internal/mutex.h" +#include "jemalloc/internal/mb.h" +#include "jemalloc/internal/extent.h" +#include "jemalloc/internal/arena.h" +#include "jemalloc/internal/base.h" +#include "jemalloc/internal/chunk.h" +#include "jemalloc/internal/huge.h" +#include "jemalloc/internal/tcache.h" +#include "jemalloc/internal/hash.h" +#include "jemalloc/internal/prof.h" + +#undef JEMALLOC_H_TYPES +/******************************************************************************/ +#define JEMALLOC_H_STRUCTS + +#include "jemalloc/internal/totally_not_p_r_n.h" +#include "jemalloc/internal/ckh.h" +#include "jemalloc/internal/stats.h" +#include "jemalloc/internal/ctl.h" +#include "jemalloc/internal/mutex.h" +#include "jemalloc/internal/mb.h" +#include "jemalloc/internal/extent.h" +#include "jemalloc/internal/arena.h" +#include "jemalloc/internal/base.h" +#include "jemalloc/internal/chunk.h" +#include "jemalloc/internal/huge.h" +#include "jemalloc/internal/tcache.h" +#include "jemalloc/internal/hash.h" +#include "jemalloc/internal/prof.h" + +#undef JEMALLOC_H_STRUCTS +/******************************************************************************/ +#define JEMALLOC_H_EXTERNS + +extern bool opt_abort; +#ifdef JEMALLOC_FILL +extern bool opt_junk; +#endif +#ifdef JEMALLOC_SYSV +extern bool opt_sysv; +#endif +#ifdef JEMALLOC_XMALLOC +extern bool opt_xmalloc; +#endif +#ifdef JEMALLOC_FILL +extern bool opt_zero; +#endif + +#ifdef DYNAMIC_PAGE_SHIFT +extern size_t pagesize; +extern size_t pagesize_mask; +extern size_t lg_pagesize; +#endif + +/* Number of CPUs. */ +extern unsigned ncpus; + +extern malloc_mutex_t arenas_lock; /* Protects arenas initialization. */ +#ifndef NO_TLS +/* + * Map of pthread_self() --> arenas[???], used for selecting an arena to use + * for allocations. + */ +extern __thread arena_t *arenas_map JEMALLOC_ATTR(tls_model("initial-exec")); +#endif +/* + * Arenas that are used to service external requests. Not all elements of the + * arenas array are necessarily used; arenas are created lazily as needed. + */ +extern arena_t **arenas; +extern unsigned narenas; + +arena_t *arenas_extend(unsigned ind); +#ifndef NO_TLS +arena_t *choose_arena_hard(void); +#endif + +#include "jemalloc/internal/totally_not_p_r_n.h" +#include "jemalloc/internal/ckh.h" +#include "jemalloc/internal/stats.h" +#include "jemalloc/internal/ctl.h" +#include "jemalloc/internal/mutex.h" +#include "jemalloc/internal/mb.h" +#include "jemalloc/internal/extent.h" +#include "jemalloc/internal/arena.h" +#include "jemalloc/internal/base.h" +#include "jemalloc/internal/chunk.h" +#include "jemalloc/internal/huge.h" +#include "jemalloc/internal/tcache.h" +#include "jemalloc/internal/hash.h" +#include "jemalloc/internal/prof.h" + +#undef JEMALLOC_H_EXTERNS +/******************************************************************************/ +#define JEMALLOC_H_INLINES + +#include "jemalloc/internal/totally_not_p_r_n.h" +#include "jemalloc/internal/ckh.h" +#include "jemalloc/internal/stats.h" +#include "jemalloc/internal/ctl.h" +#include "jemalloc/internal/mutex.h" +#include "jemalloc/internal/mb.h" +#include "jemalloc/internal/extent.h" +#include "jemalloc/internal/base.h" +#include "jemalloc/internal/chunk.h" +#include "jemalloc/internal/huge.h" + +#ifndef JEMALLOC_ENABLE_INLINE +void malloc_write(const char *s); +arena_t *choose_arena(void); +#endif + +#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_C_)) +/* + * Wrapper around malloc_message() that avoids the need for + * JEMALLOC_P(malloc_message)(...) throughout the code. + */ +JEMALLOC_INLINE void +malloc_write(const char *s) +{ + + JEMALLOC_P(malloc_message)(NULL, s); +} + +/* + * Choose an arena based on a per-thread value (fast-path code, calls slow-path + * code if necessary). + */ +JEMALLOC_INLINE arena_t * +choose_arena(void) +{ + arena_t *ret; + + /* + * We can only use TLS if this is a PIC library, since for the static + * library version, libc's malloc is used by TLS allocation, which + * introduces a bootstrapping issue. + */ +#ifndef NO_TLS + ret = arenas_map; + if (ret == NULL) { + ret = choose_arena_hard(); + assert(ret != NULL); + } +#else + if (isthreaded && narenas > 1) { + unsigned long ind; + + /* + * Hash pthread_self() to one of the arenas. There is a prime + * number of arenas, so this has a reasonable chance of + * working. Even so, the hashing can be easily thwarted by + * inconvenient pthread_self() values. Without specific + * knowledge of how pthread_self() calculates values, we can't + * easily do much better than this. + */ + ind = (unsigned long) pthread_self() % narenas; + + /* + * Optimistially assume that arenas[ind] has been initialized. + * At worst, we find out that some other thread has already + * done so, after acquiring the lock in preparation. Note that + * this lazy locking also has the effect of lazily forcing + * cache coherency; without the lock acquisition, there's no + * guarantee that modification of arenas[ind] by another thread + * would be seen on this CPU for an arbitrary amount of time. + * + * In general, this approach to modifying a synchronized value + * isn't a good idea, but in this case we only ever modify the + * value once, so things work out well. + */ + ret = arenas[ind]; + if (ret == NULL) { + /* + * Avoid races with another thread that may have already + * initialized arenas[ind]. + */ + malloc_mutex_lock(&arenas_lock); + if (arenas[ind] == NULL) + ret = arenas_extend((unsigned)ind); + else + ret = arenas[ind]; + malloc_mutex_unlock(&arenas_lock); + } + } else + ret = arenas[0]; +#endif + + assert(ret != NULL); + return (ret); +} +#endif + +#include "jemalloc/internal/tcache.h" +#include "jemalloc/internal/arena.h" +#include "jemalloc/internal/hash.h" +#include "jemalloc/internal/prof.h" + +#ifndef JEMALLOC_ENABLE_INLINE +void *imalloc(size_t size); +void *icalloc(size_t size); +void *ipalloc(size_t alignment, size_t size); +size_t isalloc(const void *ptr); +void *iralloc(void *ptr, size_t size); +void idalloc(void *ptr); +#endif + +#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_C_)) +JEMALLOC_INLINE void * +imalloc(size_t size) +{ + + assert(size != 0); + + if (size <= arena_maxclass) + return (arena_malloc(size, false)); + else + return (huge_malloc(size, false)); +} + +JEMALLOC_INLINE void * +icalloc(size_t size) +{ + + if (size <= arena_maxclass) + return (arena_malloc(size, true)); + else + return (huge_malloc(size, true)); +} + +JEMALLOC_INLINE void * +ipalloc(size_t alignment, size_t size) +{ + void *ret; + size_t ceil_size; + + /* + * Round size up to the nearest multiple of alignment. + * + * This done, we can take advantage of the fact that for each small + * size class, every object is aligned at the smallest power of two + * that is non-zero in the base two representation of the size. For + * example: + * + * Size | Base 2 | Minimum alignment + * -----+----------+------------------ + * 96 | 1100000 | 32 + * 144 | 10100000 | 32 + * 192 | 11000000 | 64 + * + * Depending on runtime settings, it is possible that arena_malloc() + * will further round up to a power of two, but that never causes + * correctness issues. + */ + ceil_size = (size + (alignment - 1)) & (-alignment); + /* + * (ceil_size < size) protects against the combination of maximal + * alignment and size greater than maximal alignment. + */ + if (ceil_size < size) { + /* size_t overflow. */ + return (NULL); + } + + if (ceil_size <= PAGE_SIZE || (alignment <= PAGE_SIZE + && ceil_size <= arena_maxclass)) + ret = arena_malloc(ceil_size, false); + else { + size_t run_size; + + /* + * We can't achieve subpage alignment, so round up alignment + * permanently; it makes later calculations simpler. + */ + alignment = PAGE_CEILING(alignment); + ceil_size = PAGE_CEILING(size); + /* + * (ceil_size < size) protects against very large sizes within + * PAGE_SIZE of SIZE_T_MAX. + * + * (ceil_size + alignment < ceil_size) protects against the + * combination of maximal alignment and ceil_size large enough + * to cause overflow. This is similar to the first overflow + * check above, but it needs to be repeated due to the new + * ceil_size value, which may now be *equal* to maximal + * alignment, whereas before we only detected overflow if the + * original size was *greater* than maximal alignment. + */ + if (ceil_size < size || ceil_size + alignment < ceil_size) { + /* size_t overflow. */ + return (NULL); + } + + /* + * Calculate the size of the over-size run that arena_palloc() + * would need to allocate in order to guarantee the alignment. + */ + if (ceil_size >= alignment) + run_size = ceil_size + alignment - PAGE_SIZE; + else { + /* + * It is possible that (alignment << 1) will cause + * overflow, but it doesn't matter because we also + * subtract PAGE_SIZE, which in the case of overflow + * leaves us with a very large run_size. That causes + * the first conditional below to fail, which means + * that the bogus run_size value never gets used for + * anything important. + */ + run_size = (alignment << 1) - PAGE_SIZE; + } + + if (run_size <= arena_maxclass) { + ret = arena_palloc(choose_arena(), alignment, ceil_size, + run_size); + } else if (alignment <= chunksize) + ret = huge_malloc(ceil_size, false); + else + ret = huge_palloc(alignment, ceil_size); + } + + assert(((uintptr_t)ret & (alignment - 1)) == 0); + return (ret); +} + +JEMALLOC_INLINE size_t +isalloc(const void *ptr) +{ + size_t ret; + arena_chunk_t *chunk; + + assert(ptr != NULL); + + chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); + if (chunk != ptr) { + /* Region. */ + assert(chunk->arena->magic == ARENA_MAGIC); + +#ifdef JEMALLOC_PROF + ret = arena_salloc_demote(ptr); +#else + ret = arena_salloc(ptr); +#endif + } else + ret = huge_salloc(ptr); + + return (ret); +} + +JEMALLOC_INLINE void * +iralloc(void *ptr, size_t size) +{ + size_t oldsize; + + assert(ptr != NULL); + assert(size != 0); + + oldsize = isalloc(ptr); + + if (size <= arena_maxclass) + return (arena_ralloc(ptr, size, oldsize)); + else + return (huge_ralloc(ptr, size, oldsize)); +} + +JEMALLOC_INLINE void +idalloc(void *ptr) +{ + arena_chunk_t *chunk; + + assert(ptr != NULL); + + chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); + if (chunk != ptr) + arena_dalloc(chunk->arena, chunk, ptr); + else + huge_dalloc(ptr); +} +#endif + +#undef JEMALLOC_H_INLINES +/******************************************************************************/ diff --git a/dep/jemalloc/jemalloc/internal/jemalloc_internal.h.in b/dep/jemalloc/jemalloc/internal/jemalloc_internal.h.in new file mode 100644 index 00000000000..2c3f32f126d --- /dev/null +++ b/dep/jemalloc/jemalloc/internal/jemalloc_internal.h.in @@ -0,0 +1,561 @@ +#include +#include +#include +#include +#include +#include + +#include +#include +#ifndef SIZE_T_MAX +# define SIZE_T_MAX SIZE_MAX +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define JEMALLOC_MANGLE +#include "../jemalloc@install_suffix@.h" + +#ifdef JEMALLOC_LAZY_LOCK +#include +#endif + +#define RB_COMPACT +#include "jemalloc/internal/rb.h" +#include "jemalloc/internal/qr.h" +#include "jemalloc/internal/ql.h" + +extern void (*JEMALLOC_P(malloc_message))(void *wcbopaque, const char *s); + +/* + * Define a custom assert() in order to reduce the chances of deadlock during + * assertion failure. + */ +#ifdef JEMALLOC_DEBUG +# define assert(e) do { \ + if (!(e)) { \ + char line_buf[UMAX2S_BUFSIZE]; \ + malloc_write(": "); \ + malloc_write(__FILE__); \ + malloc_write(":"); \ + malloc_write(umax2s(__LINE__, 10, line_buf)); \ + malloc_write(": Failed assertion: "); \ + malloc_write("\""); \ + malloc_write(#e); \ + malloc_write("\"\n"); \ + abort(); \ + } \ +} while (0) +#else +#define assert(e) +#endif + +/* + * jemalloc can conceptually be broken into components (arena, tcache, etc.), + * but there are circular dependencies that cannot be broken without + * substantial performance degradation. In order to reduce the effect on + * visual code flow, read the header files in multiple passes, with one of the + * following cpp variables defined during each pass: + * + * JEMALLOC_H_TYPES : Preprocessor-defined constants and psuedo-opaque data + * types. + * JEMALLOC_H_STRUCTS : Data structures. + * JEMALLOC_H_EXTERNS : Extern data declarations and function prototypes. + * JEMALLOC_H_INLINES : Inline functions. + */ +/******************************************************************************/ +#define JEMALLOC_H_TYPES + +#define ZU(z) ((size_t)z) + +#ifndef __DECONST +# define __DECONST(type, var) ((type)(uintptr_t)(const void *)(var)) +#endif + +#ifdef JEMALLOC_DEBUG + /* Disable inlining to make debugging easier. */ +# define JEMALLOC_INLINE +# define inline +#else +# define JEMALLOC_ENABLE_INLINE +# define JEMALLOC_INLINE static inline +#endif + +/* Size of stack-allocated buffer passed to strerror_r(). */ +#define STRERROR_BUF 64 + +/* Minimum alignment of allocations is 2^LG_QUANTUM bytes. */ +#ifdef __i386__ +# define LG_QUANTUM 4 +#endif +#ifdef __ia64__ +# define LG_QUANTUM 4 +#endif +#ifdef __alpha__ +# define LG_QUANTUM 4 +#endif +#ifdef __sparc64__ +# define LG_QUANTUM 4 +#endif +#if (defined(__amd64__) || defined(__x86_64__)) +# define LG_QUANTUM 4 +#endif +#ifdef __arm__ +# define LG_QUANTUM 3 +#endif +#ifdef __mips__ +# define LG_QUANTUM 3 +#endif +#ifdef __powerpc__ +# define LG_QUANTUM 4 +#endif +#ifdef __s390x__ +# define LG_QUANTUM 4 +#endif + +#define QUANTUM ((size_t)(1U << LG_QUANTUM)) +#define QUANTUM_MASK (QUANTUM - 1) + +/* Return the smallest quantum multiple that is >= a. */ +#define QUANTUM_CEILING(a) \ + (((a) + QUANTUM_MASK) & ~QUANTUM_MASK) + +#define SIZEOF_PTR (1U << LG_SIZEOF_PTR) + +/* We can't use TLS in non-PIC programs, since TLS relies on loader magic. */ +#if (!defined(PIC) && !defined(NO_TLS)) +# define NO_TLS +#endif + +/* + * Maximum size of L1 cache line. This is used to avoid cache line aliasing. + * In addition, this controls the spacing of cacheline-spaced size classes. + */ +#define LG_CACHELINE 6 +#define CACHELINE ((size_t)(1U << LG_CACHELINE)) +#define CACHELINE_MASK (CACHELINE - 1) + +/* Return the smallest cacheline multiple that is >= s. */ +#define CACHELINE_CEILING(s) \ + (((s) + CACHELINE_MASK) & ~CACHELINE_MASK) + +/* + * Page size. STATIC_PAGE_SHIFT is determined by the configure script. If + * DYNAMIC_PAGE_SHIFT is enabled, only use the STATIC_PAGE_* macros where + * compile-time values are required for the purposes of defining data + * structures. + */ +#define STATIC_PAGE_SIZE ((size_t)(1U << STATIC_PAGE_SHIFT)) +#define STATIC_PAGE_MASK ((size_t)(STATIC_PAGE_SIZE - 1)) + +#ifdef DYNAMIC_PAGE_SHIFT +# define PAGE_SHIFT lg_pagesize +# define PAGE_SIZE pagesize +# define PAGE_MASK pagesize_mask +#else +# define PAGE_SHIFT STATIC_PAGE_SHIFT +# define PAGE_SIZE STATIC_PAGE_SIZE +# define PAGE_MASK STATIC_PAGE_MASK +#endif + +/* Return the smallest pagesize multiple that is >= s. */ +#define PAGE_CEILING(s) \ + (((s) + PAGE_MASK) & ~PAGE_MASK) + +#include "jemalloc/internal/prn.h" +#include "jemalloc/internal/ckh.h" +#include "jemalloc/internal/stats.h" +#include "jemalloc/internal/ctl.h" +#include "jemalloc/internal/mutex.h" +#include "jemalloc/internal/mb.h" +#include "jemalloc/internal/extent.h" +#include "jemalloc/internal/arena.h" +#include "jemalloc/internal/base.h" +#include "jemalloc/internal/chunk.h" +#include "jemalloc/internal/huge.h" +#include "jemalloc/internal/tcache.h" +#include "jemalloc/internal/hash.h" +#include "jemalloc/internal/prof.h" + +#undef JEMALLOC_H_TYPES +/******************************************************************************/ +#define JEMALLOC_H_STRUCTS + +#include "jemalloc/internal/prn.h" +#include "jemalloc/internal/ckh.h" +#include "jemalloc/internal/stats.h" +#include "jemalloc/internal/ctl.h" +#include "jemalloc/internal/mutex.h" +#include "jemalloc/internal/mb.h" +#include "jemalloc/internal/extent.h" +#include "jemalloc/internal/arena.h" +#include "jemalloc/internal/base.h" +#include "jemalloc/internal/chunk.h" +#include "jemalloc/internal/huge.h" +#include "jemalloc/internal/tcache.h" +#include "jemalloc/internal/hash.h" +#include "jemalloc/internal/prof.h" + +#undef JEMALLOC_H_STRUCTS +/******************************************************************************/ +#define JEMALLOC_H_EXTERNS + +extern bool opt_abort; +#ifdef JEMALLOC_FILL +extern bool opt_junk; +#endif +#ifdef JEMALLOC_SYSV +extern bool opt_sysv; +#endif +#ifdef JEMALLOC_XMALLOC +extern bool opt_xmalloc; +#endif +#ifdef JEMALLOC_FILL +extern bool opt_zero; +#endif + +#ifdef DYNAMIC_PAGE_SHIFT +extern size_t pagesize; +extern size_t pagesize_mask; +extern size_t lg_pagesize; +#endif + +/* Number of CPUs. */ +extern unsigned ncpus; + +extern malloc_mutex_t arenas_lock; /* Protects arenas initialization. */ +#ifndef NO_TLS +/* + * Map of pthread_self() --> arenas[???], used for selecting an arena to use + * for allocations. + */ +extern __thread arena_t *arenas_map JEMALLOC_ATTR(tls_model("initial-exec")); +#endif +/* + * Arenas that are used to service external requests. Not all elements of the + * arenas array are necessarily used; arenas are created lazily as needed. + */ +extern arena_t **arenas; +extern unsigned narenas; + +arena_t *arenas_extend(unsigned ind); +#ifndef NO_TLS +arena_t *choose_arena_hard(void); +#endif + +#include "jemalloc/internal/prn.h" +#include "jemalloc/internal/ckh.h" +#include "jemalloc/internal/stats.h" +#include "jemalloc/internal/ctl.h" +#include "jemalloc/internal/mutex.h" +#include "jemalloc/internal/mb.h" +#include "jemalloc/internal/extent.h" +#include "jemalloc/internal/arena.h" +#include "jemalloc/internal/base.h" +#include "jemalloc/internal/chunk.h" +#include "jemalloc/internal/huge.h" +#include "jemalloc/internal/tcache.h" +#include "jemalloc/internal/hash.h" +#include "jemalloc/internal/prof.h" + +#undef JEMALLOC_H_EXTERNS +/******************************************************************************/ +#define JEMALLOC_H_INLINES + +#include "jemalloc/internal/prn.h" +#include "jemalloc/internal/ckh.h" +#include "jemalloc/internal/stats.h" +#include "jemalloc/internal/ctl.h" +#include "jemalloc/internal/mutex.h" +#include "jemalloc/internal/mb.h" +#include "jemalloc/internal/extent.h" +#include "jemalloc/internal/base.h" +#include "jemalloc/internal/chunk.h" +#include "jemalloc/internal/huge.h" + +#ifndef JEMALLOC_ENABLE_INLINE +void malloc_write(const char *s); +arena_t *choose_arena(void); +#endif + +#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_C_)) +/* + * Wrapper around malloc_message() that avoids the need for + * JEMALLOC_P(malloc_message)(...) throughout the code. + */ +JEMALLOC_INLINE void +malloc_write(const char *s) +{ + + JEMALLOC_P(malloc_message)(NULL, s); +} + +/* + * Choose an arena based on a per-thread value (fast-path code, calls slow-path + * code if necessary). + */ +JEMALLOC_INLINE arena_t * +choose_arena(void) +{ + arena_t *ret; + + /* + * We can only use TLS if this is a PIC library, since for the static + * library version, libc's malloc is used by TLS allocation, which + * introduces a bootstrapping issue. + */ +#ifndef NO_TLS + ret = arenas_map; + if (ret == NULL) { + ret = choose_arena_hard(); + assert(ret != NULL); + } +#else + if (isthreaded && narenas > 1) { + unsigned long ind; + + /* + * Hash pthread_self() to one of the arenas. There is a prime + * number of arenas, so this has a reasonable chance of + * working. Even so, the hashing can be easily thwarted by + * inconvenient pthread_self() values. Without specific + * knowledge of how pthread_self() calculates values, we can't + * easily do much better than this. + */ + ind = (unsigned long) pthread_self() % narenas; + + /* + * Optimistially assume that arenas[ind] has been initialized. + * At worst, we find out that some other thread has already + * done so, after acquiring the lock in preparation. Note that + * this lazy locking also has the effect of lazily forcing + * cache coherency; without the lock acquisition, there's no + * guarantee that modification of arenas[ind] by another thread + * would be seen on this CPU for an arbitrary amount of time. + * + * In general, this approach to modifying a synchronized value + * isn't a good idea, but in this case we only ever modify the + * value once, so things work out well. + */ + ret = arenas[ind]; + if (ret == NULL) { + /* + * Avoid races with another thread that may have already + * initialized arenas[ind]. + */ + malloc_mutex_lock(&arenas_lock); + if (arenas[ind] == NULL) + ret = arenas_extend((unsigned)ind); + else + ret = arenas[ind]; + malloc_mutex_unlock(&arenas_lock); + } + } else + ret = arenas[0]; +#endif + + assert(ret != NULL); + return (ret); +} +#endif + +#include "jemalloc/internal/tcache.h" +#include "jemalloc/internal/arena.h" +#include "jemalloc/internal/hash.h" +#include "jemalloc/internal/prof.h" + +#ifndef JEMALLOC_ENABLE_INLINE +void *imalloc(size_t size); +void *icalloc(size_t size); +void *ipalloc(size_t alignment, size_t size); +size_t isalloc(const void *ptr); +void *iralloc(void *ptr, size_t size); +void idalloc(void *ptr); +#endif + +#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_C_)) +JEMALLOC_INLINE void * +imalloc(size_t size) +{ + + assert(size != 0); + + if (size <= arena_maxclass) + return (arena_malloc(size, false)); + else + return (huge_malloc(size, false)); +} + +JEMALLOC_INLINE void * +icalloc(size_t size) +{ + + if (size <= arena_maxclass) + return (arena_malloc(size, true)); + else + return (huge_malloc(size, true)); +} + +JEMALLOC_INLINE void * +ipalloc(size_t alignment, size_t size) +{ + void *ret; + size_t ceil_size; + + /* + * Round size up to the nearest multiple of alignment. + * + * This done, we can take advantage of the fact that for each small + * size class, every object is aligned at the smallest power of two + * that is non-zero in the base two representation of the size. For + * example: + * + * Size | Base 2 | Minimum alignment + * -----+----------+------------------ + * 96 | 1100000 | 32 + * 144 | 10100000 | 32 + * 192 | 11000000 | 64 + * + * Depending on runtime settings, it is possible that arena_malloc() + * will further round up to a power of two, but that never causes + * correctness issues. + */ + ceil_size = (size + (alignment - 1)) & (-alignment); + /* + * (ceil_size < size) protects against the combination of maximal + * alignment and size greater than maximal alignment. + */ + if (ceil_size < size) { + /* size_t overflow. */ + return (NULL); + } + + if (ceil_size <= PAGE_SIZE || (alignment <= PAGE_SIZE + && ceil_size <= arena_maxclass)) + ret = arena_malloc(ceil_size, false); + else { + size_t run_size; + + /* + * We can't achieve subpage alignment, so round up alignment + * permanently; it makes later calculations simpler. + */ + alignment = PAGE_CEILING(alignment); + ceil_size = PAGE_CEILING(size); + /* + * (ceil_size < size) protects against very large sizes within + * PAGE_SIZE of SIZE_T_MAX. + * + * (ceil_size + alignment < ceil_size) protects against the + * combination of maximal alignment and ceil_size large enough + * to cause overflow. This is similar to the first overflow + * check above, but it needs to be repeated due to the new + * ceil_size value, which may now be *equal* to maximal + * alignment, whereas before we only detected overflow if the + * original size was *greater* than maximal alignment. + */ + if (ceil_size < size || ceil_size + alignment < ceil_size) { + /* size_t overflow. */ + return (NULL); + } + + /* + * Calculate the size of the over-size run that arena_palloc() + * would need to allocate in order to guarantee the alignment. + */ + if (ceil_size >= alignment) + run_size = ceil_size + alignment - PAGE_SIZE; + else { + /* + * It is possible that (alignment << 1) will cause + * overflow, but it doesn't matter because we also + * subtract PAGE_SIZE, which in the case of overflow + * leaves us with a very large run_size. That causes + * the first conditional below to fail, which means + * that the bogus run_size value never gets used for + * anything important. + */ + run_size = (alignment << 1) - PAGE_SIZE; + } + + if (run_size <= arena_maxclass) { + ret = arena_palloc(choose_arena(), alignment, ceil_size, + run_size); + } else if (alignment <= chunksize) + ret = huge_malloc(ceil_size, false); + else + ret = huge_palloc(alignment, ceil_size); + } + + assert(((uintptr_t)ret & (alignment - 1)) == 0); + return (ret); +} + +JEMALLOC_INLINE size_t +isalloc(const void *ptr) +{ + size_t ret; + arena_chunk_t *chunk; + + assert(ptr != NULL); + + chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); + if (chunk != ptr) { + /* Region. */ + assert(chunk->arena->magic == ARENA_MAGIC); + +#ifdef JEMALLOC_PROF + ret = arena_salloc_demote(ptr); +#else + ret = arena_salloc(ptr); +#endif + } else + ret = huge_salloc(ptr); + + return (ret); +} + +JEMALLOC_INLINE void * +iralloc(void *ptr, size_t size) +{ + size_t oldsize; + + assert(ptr != NULL); + assert(size != 0); + + oldsize = isalloc(ptr); + + if (size <= arena_maxclass) + return (arena_ralloc(ptr, size, oldsize)); + else + return (huge_ralloc(ptr, size, oldsize)); +} + +JEMALLOC_INLINE void +idalloc(void *ptr) +{ + arena_chunk_t *chunk; + + assert(ptr != NULL); + + chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); + if (chunk != ptr) + arena_dalloc(chunk->arena, chunk, ptr); + else + huge_dalloc(ptr); +} +#endif + +#undef JEMALLOC_H_INLINES +/******************************************************************************/ diff --git a/dep/jemalloc/jemalloc/internal/mb.h b/dep/jemalloc/jemalloc/internal/mb.h new file mode 100644 index 00000000000..1707aa91d68 --- /dev/null +++ b/dep/jemalloc/jemalloc/internal/mb.h @@ -0,0 +1,108 @@ +/******************************************************************************/ +#ifdef JEMALLOC_H_TYPES + +#endif /* JEMALLOC_H_TYPES */ +/******************************************************************************/ +#ifdef JEMALLOC_H_STRUCTS + +#endif /* JEMALLOC_H_STRUCTS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_EXTERNS + +#endif /* JEMALLOC_H_EXTERNS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_INLINES + +#ifndef JEMALLOC_ENABLE_INLINE +void mb_write(void); +#endif + +#if (defined(JEMALLOC_ENABLE_INLINE) || defined(MB_C_)) +#ifdef __i386__ +/* + * According to the Intel Architecture Software Developer's Manual, current + * processors execute instructions in order from the perspective of other + * processors in a multiprocessor system, but 1) Intel reserves the right to + * change that, and 2) the compiler's optimizer could re-order instructions if + * there weren't some form of barrier. Therefore, even if running on an + * architecture that does not need memory barriers (everything through at least + * i686), an "optimizer barrier" is necessary. + */ +JEMALLOC_INLINE void +mb_write(void) +{ + +# if 0 + /* This is a true memory barrier. */ + asm volatile ("pusha;" + "xor %%eax,%%eax;" + "cpuid;" + "popa;" + : /* Outputs. */ + : /* Inputs. */ + : "memory" /* Clobbers. */ + ); +#else + /* + * This is hopefully enough to keep the compiler from reordering + * instructions around this one. + */ + asm volatile ("nop;" + : /* Outputs. */ + : /* Inputs. */ + : "memory" /* Clobbers. */ + ); +#endif +} +#elif (defined(__amd64_) || defined(__x86_64__)) +JEMALLOC_INLINE void +mb_write(void) +{ + + asm volatile ("sfence" + : /* Outputs. */ + : /* Inputs. */ + : "memory" /* Clobbers. */ + ); +} +#elif defined(__powerpc__) +JEMALLOC_INLINE void +mb_write(void) +{ + + asm volatile ("eieio" + : /* Outputs. */ + : /* Inputs. */ + : "memory" /* Clobbers. */ + ); +} +#elif defined(__sparc64__) +JEMALLOC_INLINE void +mb_write(void) +{ + + asm volatile ("membar #StoreStore" + : /* Outputs. */ + : /* Inputs. */ + : "memory" /* Clobbers. */ + ); +} +#else +/* + * This is much slower than a simple memory barrier, but the semantics of mutex + * unlock make this work. + */ +JEMALLOC_INLINE void +mb_write(void) +{ + malloc_mutex_t mtx; + + malloc_mutex_init(&mtx); + malloc_mutex_lock(&mtx); + malloc_mutex_unlock(&mtx); +} +#endif +#endif + +#endif /* JEMALLOC_H_INLINES */ +/******************************************************************************/ diff --git a/dep/jemalloc/jemalloc/internal/mutex.h b/dep/jemalloc/jemalloc/internal/mutex.h new file mode 100644 index 00000000000..108bfa8abfd --- /dev/null +++ b/dep/jemalloc/jemalloc/internal/mutex.h @@ -0,0 +1,61 @@ +/******************************************************************************/ +#ifdef JEMALLOC_H_TYPES + +typedef pthread_mutex_t malloc_mutex_t; + +#endif /* JEMALLOC_H_TYPES */ +/******************************************************************************/ +#ifdef JEMALLOC_H_STRUCTS + +#endif /* JEMALLOC_H_STRUCTS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_EXTERNS + +#ifdef JEMALLOC_LAZY_LOCK +extern bool isthreaded; +#else +# define isthreaded true +#endif + +bool malloc_mutex_init(malloc_mutex_t *mutex); + +#endif /* JEMALLOC_H_EXTERNS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_INLINES + +#ifndef JEMALLOC_ENABLE_INLINE +void malloc_mutex_lock(malloc_mutex_t *mutex); +bool malloc_mutex_trylock(malloc_mutex_t *mutex); +void malloc_mutex_unlock(malloc_mutex_t *mutex); +#endif + +#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_MUTEX_C_)) +JEMALLOC_INLINE void +malloc_mutex_lock(malloc_mutex_t *mutex) +{ + + if (isthreaded) + pthread_mutex_lock(mutex); +} + +JEMALLOC_INLINE bool +malloc_mutex_trylock(malloc_mutex_t *mutex) +{ + + if (isthreaded) + return (pthread_mutex_trylock(mutex) != 0); + else + return (false); +} + +JEMALLOC_INLINE void +malloc_mutex_unlock(malloc_mutex_t *mutex) +{ + + if (isthreaded) + pthread_mutex_unlock(mutex); +} +#endif + +#endif /* JEMALLOC_H_INLINES */ +/******************************************************************************/ diff --git a/dep/jemalloc/jemalloc/internal/prof.h b/dep/jemalloc/jemalloc/internal/prof.h new file mode 100644 index 00000000000..6e71552d85e --- /dev/null +++ b/dep/jemalloc/jemalloc/internal/prof.h @@ -0,0 +1,171 @@ +#ifdef JEMALLOC_PROF +/******************************************************************************/ +#ifdef JEMALLOC_H_TYPES + +typedef struct prof_bt_s prof_bt_t; +typedef struct prof_cnt_s prof_cnt_t; +typedef struct prof_thr_cnt_s prof_thr_cnt_t; +typedef struct prof_ctx_s prof_ctx_t; +typedef struct prof_s prof_t; + +/* Option defaults. */ +#define LG_PROF_BT_MAX_DEFAULT 2 +#define LG_PROF_SAMPLE_DEFAULT 0 +#define LG_PROF_INTERVAL_DEFAULT 30 + +/* + * Hard limit on stack backtrace depth. Note that the version of + * prof_backtrace() that is based on __builtin_return_address() necessarily has + * a hard-coded number of backtrace frame handlers, so increasing + * LG_PROF_BT_MAX requires changing prof_backtrace(). + */ +#define LG_PROF_BT_MAX 7 /* >= LG_PROF_BT_MAX_DEFAULT */ +#define PROF_BT_MAX (1U << LG_PROF_BT_MAX) + +/* Initial hash table size. */ +#define PROF_CKH_MINITEMS 64 + +/* Size of memory buffer to use when writing dump files. */ +#define PROF_DUMP_BUF_SIZE 65536 + +#endif /* JEMALLOC_H_TYPES */ +/******************************************************************************/ +#ifdef JEMALLOC_H_STRUCTS + +struct prof_bt_s { + /* Backtrace, stored as len program counters. */ + void **vec; + unsigned len; +}; + +#ifdef JEMALLOC_PROF_LIBGCC +/* Data structure passed to libgcc _Unwind_Backtrace() callback functions. */ +typedef struct { + prof_bt_t *bt; + unsigned nignore; + unsigned max; +} prof_unwind_data_t; +#endif + +struct prof_cnt_s { + /* + * Profiling counters. An allocation/deallocation pair can operate on + * different prof_thr_cnt_t objects that are linked into the same + * prof_ctx_t sets_ql, so it is possible for the cur* counters to go + * negative. In principle it is possible for the *bytes counters to + * overflow/underflow, but a general solution would require some form + * of 128-bit counter solution; this implementation doesn't bother to + * solve that problem. + */ + int64_t curobjs; + int64_t curbytes; + uint64_t accumobjs; + uint64_t accumbytes; +}; + +struct prof_thr_cnt_s { + /* Linkage into prof_ctx_t's sets_ql. */ + ql_elm(prof_thr_cnt_t) link; + + /* + * Associated context. If a thread frees an object that it did not + * allocate, it is possible that the context is not cached in the + * thread's hash table, in which case it must be able to look up the + * context, insert a new prof_thr_cnt_t into the thread's hash table, + * and link it into the prof_ctx_t's sets_ql. + */ + prof_ctx_t *ctx; + + /* + * Threads use memory barriers to update the counters. Since there is + * only ever one writer, the only challenge is for the reader to get a + * consistent read of the counters. + * + * The writer uses this series of operations: + * + * 1) Increment epoch to an odd number. + * 2) Update counters. + * 3) Increment epoch to an even number. + * + * The reader must assure 1) that the epoch is even while it reads the + * counters, and 2) that the epoch doesn't change between the time it + * starts and finishes reading the counters. + */ + unsigned epoch; + + /* Profiling counters. */ + prof_cnt_t cnts; +}; + +struct prof_ctx_s { + /* Protects cnt_merged and sets_ql. */ + malloc_mutex_t lock; + + /* Temporary storage for aggregation during dump. */ + prof_cnt_t cnt_dump; + + /* When threads exit, they merge their stats into cnt_merged. */ + prof_cnt_t cnt_merged; + + /* + * List of profile counters, one for each thread that has allocated in + * this context. + */ + ql_head(prof_thr_cnt_t) cnts_ql; +}; + +#endif /* JEMALLOC_H_STRUCTS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_EXTERNS + +extern bool opt_prof; +/* + * Even if opt_prof is true, sampling can be temporarily disabled by setting + * opt_prof_active to false. No locking is used when updating opt_prof_active, + * so there are no guarantees regarding how long it will take for all threads + * to notice state changes. + */ +extern bool opt_prof_active; +extern size_t opt_lg_prof_bt_max; /* Maximum backtrace depth. */ +extern size_t opt_lg_prof_sample; /* Mean bytes between samples. */ +extern ssize_t opt_lg_prof_interval; /* lg(prof_interval). */ +extern bool opt_prof_udump; /* High-water memory dumping. */ +extern bool opt_prof_leak; /* Dump leak summary at exit. */ + +/* + * Profile dump interval, measured in bytes allocated. Each arena triggers a + * profile dump when it reaches this threshold. The effect is that the + * interval between profile dumps averages prof_interval, though the actual + * interval between dumps will tend to be sporadic, and the interval will be a + * maximum of approximately (prof_interval * narenas). + */ +extern uint64_t prof_interval; + +/* + * If true, promote small sampled objects to large objects, since small run + * headers do not have embedded profile context pointers. + */ +extern bool prof_promote; + +bool prof_init(prof_t *prof, bool master); +void prof_destroy(prof_t *prof); + +prof_thr_cnt_t *prof_alloc_prep(size_t size); +prof_thr_cnt_t *prof_cnt_get(const void *ptr); +void prof_malloc(const void *ptr, prof_thr_cnt_t *cnt); +void prof_realloc(const void *ptr, prof_thr_cnt_t *cnt, const void *old_ptr, + size_t old_size, prof_thr_cnt_t *old_cnt); +void prof_free(const void *ptr); +void prof_idump(void); +bool prof_mdump(const char *filename); +void prof_udump(void); +void prof_boot0(void); +bool prof_boot1(void); + +#endif /* JEMALLOC_H_EXTERNS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_INLINES + +#endif /* JEMALLOC_H_INLINES */ +/******************************************************************************/ +#endif /* JEMALLOC_PROF */ diff --git a/dep/jemalloc/jemalloc/internal/ql.h b/dep/jemalloc/jemalloc/internal/ql.h new file mode 100644 index 00000000000..a9ed2393f0c --- /dev/null +++ b/dep/jemalloc/jemalloc/internal/ql.h @@ -0,0 +1,83 @@ +/* + * List definitions. + */ +#define ql_head(a_type) \ +struct { \ + a_type *qlh_first; \ +} + +#define ql_head_initializer(a_head) {NULL} + +#define ql_elm(a_type) qr(a_type) + +/* List functions. */ +#define ql_new(a_head) do { \ + (a_head)->qlh_first = NULL; \ +} while (0) + +#define ql_elm_new(a_elm, a_field) qr_new((a_elm), a_field) + +#define ql_first(a_head) ((a_head)->qlh_first) + +#define ql_last(a_head, a_field) \ + ((ql_first(a_head) != NULL) \ + ? qr_prev(ql_first(a_head), a_field) : NULL) + +#define ql_next(a_head, a_elm, a_field) \ + ((ql_last(a_head, a_field) != (a_elm)) \ + ? qr_next((a_elm), a_field) : NULL) + +#define ql_prev(a_head, a_elm, a_field) \ + ((ql_first(a_head) != (a_elm)) ? qr_prev((a_elm), a_field) \ + : NULL) + +#define ql_before_insert(a_head, a_qlelm, a_elm, a_field) do { \ + qr_before_insert((a_qlelm), (a_elm), a_field); \ + if (ql_first(a_head) == (a_qlelm)) { \ + ql_first(a_head) = (a_elm); \ + } \ +} while (0) + +#define ql_after_insert(a_qlelm, a_elm, a_field) \ + qr_after_insert((a_qlelm), (a_elm), a_field) + +#define ql_head_insert(a_head, a_elm, a_field) do { \ + if (ql_first(a_head) != NULL) { \ + qr_before_insert(ql_first(a_head), (a_elm), a_field); \ + } \ + ql_first(a_head) = (a_elm); \ +} while (0) + +#define ql_tail_insert(a_head, a_elm, a_field) do { \ + if (ql_first(a_head) != NULL) { \ + qr_before_insert(ql_first(a_head), (a_elm), a_field); \ + } \ + ql_first(a_head) = qr_next((a_elm), a_field); \ +} while (0) + +#define ql_remove(a_head, a_elm, a_field) do { \ + if (ql_first(a_head) == (a_elm)) { \ + ql_first(a_head) = qr_next(ql_first(a_head), a_field); \ + } \ + if (ql_first(a_head) != (a_elm)) { \ + qr_remove((a_elm), a_field); \ + } else { \ + ql_first(a_head) = NULL; \ + } \ +} while (0) + +#define ql_head_remove(a_head, a_type, a_field) do { \ + a_type *t = ql_first(a_head); \ + ql_remove((a_head), t, a_field); \ +} while (0) + +#define ql_tail_remove(a_head, a_type, a_field) do { \ + a_type *t = ql_last(a_head, a_field); \ + ql_remove((a_head), t, a_field); \ +} while (0) + +#define ql_foreach(a_var, a_head, a_field) \ + qr_foreach((a_var), ql_first(a_head), a_field) + +#define ql_reverse_foreach(a_var, a_head, a_field) \ + qr_reverse_foreach((a_var), ql_first(a_head), a_field) diff --git a/dep/jemalloc/jemalloc/internal/qr.h b/dep/jemalloc/jemalloc/internal/qr.h new file mode 100644 index 00000000000..fe22352fedd --- /dev/null +++ b/dep/jemalloc/jemalloc/internal/qr.h @@ -0,0 +1,67 @@ +/* Ring definitions. */ +#define qr(a_type) \ +struct { \ + a_type *qre_next; \ + a_type *qre_prev; \ +} + +/* Ring functions. */ +#define qr_new(a_qr, a_field) do { \ + (a_qr)->a_field.qre_next = (a_qr); \ + (a_qr)->a_field.qre_prev = (a_qr); \ +} while (0) + +#define qr_next(a_qr, a_field) ((a_qr)->a_field.qre_next) + +#define qr_prev(a_qr, a_field) ((a_qr)->a_field.qre_prev) + +#define qr_before_insert(a_qrelm, a_qr, a_field) do { \ + (a_qr)->a_field.qre_prev = (a_qrelm)->a_field.qre_prev; \ + (a_qr)->a_field.qre_next = (a_qrelm); \ + (a_qr)->a_field.qre_prev->a_field.qre_next = (a_qr); \ + (a_qrelm)->a_field.qre_prev = (a_qr); \ +} while (0) + +#define qr_after_insert(a_qrelm, a_qr, a_field) \ + do \ + { \ + (a_qr)->a_field.qre_next = (a_qrelm)->a_field.qre_next; \ + (a_qr)->a_field.qre_prev = (a_qrelm); \ + (a_qr)->a_field.qre_next->a_field.qre_prev = (a_qr); \ + (a_qrelm)->a_field.qre_next = (a_qr); \ + } while (0) + +#define qr_meld(a_qr_a, a_qr_b, a_field) do { \ + void *t; \ + (a_qr_a)->a_field.qre_prev->a_field.qre_next = (a_qr_b); \ + (a_qr_b)->a_field.qre_prev->a_field.qre_next = (a_qr_a); \ + t = (a_qr_a)->a_field.qre_prev; \ + (a_qr_a)->a_field.qre_prev = (a_qr_b)->a_field.qre_prev; \ + (a_qr_b)->a_field.qre_prev = t; \ +} while (0) + +/* qr_meld() and qr_split() are functionally equivalent, so there's no need to + * have two copies of the code. */ +#define qr_split(a_qr_a, a_qr_b, a_field) \ + qr_meld((a_qr_a), (a_qr_b), a_field) + +#define qr_remove(a_qr, a_field) do { \ + (a_qr)->a_field.qre_prev->a_field.qre_next \ + = (a_qr)->a_field.qre_next; \ + (a_qr)->a_field.qre_next->a_field.qre_prev \ + = (a_qr)->a_field.qre_prev; \ + (a_qr)->a_field.qre_next = (a_qr); \ + (a_qr)->a_field.qre_prev = (a_qr); \ +} while (0) + +#define qr_foreach(var, a_qr, a_field) \ + for ((var) = (a_qr); \ + (var) != NULL; \ + (var) = (((var)->a_field.qre_next != (a_qr)) \ + ? (var)->a_field.qre_next : NULL)) + +#define qr_reverse_foreach(var, a_qr, a_field) \ + for ((var) = ((a_qr) != NULL) ? qr_prev(a_qr, a_field) : NULL; \ + (var) != NULL; \ + (var) = (((var) != (a_qr)) \ + ? (var)->a_field.qre_prev : NULL)) diff --git a/dep/jemalloc/jemalloc/internal/rb.h b/dep/jemalloc/jemalloc/internal/rb.h new file mode 100644 index 00000000000..ee9b009d235 --- /dev/null +++ b/dep/jemalloc/jemalloc/internal/rb.h @@ -0,0 +1,973 @@ +/*- + ******************************************************************************* + * + * cpp macro implementation of left-leaning 2-3 red-black trees. Parent + * pointers are not used, and color bits are stored in the least significant + * bit of right-child pointers (if RB_COMPACT is defined), thus making node + * linkage as compact as is possible for red-black trees. + * + * Usage: + * + * #include + * #include + * #define NDEBUG // (Optional, see assert(3).) + * #include + * #define RB_COMPACT // (Optional, embed color bits in right-child pointers.) + * #include + * ... + * + ******************************************************************************* + */ + +#ifndef RB_H_ +#define RB_H_ + +#if 0 +__FBSDID("$FreeBSD: head/lib/libc/stdlib/rb.h 204493 2010-02-28 22:57:13Z jasone $"); +#endif + +#ifdef RB_COMPACT +/* Node structure. */ +#define rb_node(a_type) \ +struct { \ + a_type *rbn_left; \ + a_type *rbn_right_red; \ +} +#else +#define rb_node(a_type) \ +struct { \ + a_type *rbn_left; \ + a_type *rbn_right; \ + bool rbn_red; \ +} +#endif + +/* Root structure. */ +#define rb_tree(a_type) \ +struct { \ + a_type *rbt_root; \ + a_type rbt_nil; \ +} + +/* Left accessors. */ +#define rbtn_left_get(a_type, a_field, a_node) \ + ((a_node)->a_field.rbn_left) +#define rbtn_left_set(a_type, a_field, a_node, a_left) do { \ + (a_node)->a_field.rbn_left = a_left; \ +} while (0) + +#ifdef RB_COMPACT +/* Right accessors. */ +#define rbtn_right_get(a_type, a_field, a_node) \ + ((a_type *) (((intptr_t) (a_node)->a_field.rbn_right_red) \ + & ((ssize_t)-2))) +#define rbtn_right_set(a_type, a_field, a_node, a_right) do { \ + (a_node)->a_field.rbn_right_red = (a_type *) (((uintptr_t) a_right) \ + | (((uintptr_t) (a_node)->a_field.rbn_right_red) & ((size_t)1))); \ +} while (0) + +/* Color accessors. */ +#define rbtn_red_get(a_type, a_field, a_node) \ + ((bool) (((uintptr_t) (a_node)->a_field.rbn_right_red) \ + & ((size_t)1))) +#define rbtn_color_set(a_type, a_field, a_node, a_red) do { \ + (a_node)->a_field.rbn_right_red = (a_type *) ((((intptr_t) \ + (a_node)->a_field.rbn_right_red) & ((ssize_t)-2)) \ + | ((ssize_t)a_red)); \ +} while (0) +#define rbtn_red_set(a_type, a_field, a_node) do { \ + (a_node)->a_field.rbn_right_red = (a_type *) (((uintptr_t) \ + (a_node)->a_field.rbn_right_red) | ((size_t)1)); \ +} while (0) +#define rbtn_black_set(a_type, a_field, a_node) do { \ + (a_node)->a_field.rbn_right_red = (a_type *) (((intptr_t) \ + (a_node)->a_field.rbn_right_red) & ((ssize_t)-2)); \ +} while (0) +#else +/* Right accessors. */ +#define rbtn_right_get(a_type, a_field, a_node) \ + ((a_node)->a_field.rbn_right) +#define rbtn_right_set(a_type, a_field, a_node, a_right) do { \ + (a_node)->a_field.rbn_right = a_right; \ +} while (0) + +/* Color accessors. */ +#define rbtn_red_get(a_type, a_field, a_node) \ + ((a_node)->a_field.rbn_red) +#define rbtn_color_set(a_type, a_field, a_node, a_red) do { \ + (a_node)->a_field.rbn_red = (a_red); \ +} while (0) +#define rbtn_red_set(a_type, a_field, a_node) do { \ + (a_node)->a_field.rbn_red = true; \ +} while (0) +#define rbtn_black_set(a_type, a_field, a_node) do { \ + (a_node)->a_field.rbn_red = false; \ +} while (0) +#endif + +/* Node initializer. */ +#define rbt_node_new(a_type, a_field, a_rbt, a_node) do { \ + rbtn_left_set(a_type, a_field, (a_node), &(a_rbt)->rbt_nil); \ + rbtn_right_set(a_type, a_field, (a_node), &(a_rbt)->rbt_nil); \ + rbtn_red_set(a_type, a_field, (a_node)); \ +} while (0) + +/* Tree initializer. */ +#define rb_new(a_type, a_field, a_rbt) do { \ + (a_rbt)->rbt_root = &(a_rbt)->rbt_nil; \ + rbt_node_new(a_type, a_field, a_rbt, &(a_rbt)->rbt_nil); \ + rbtn_black_set(a_type, a_field, &(a_rbt)->rbt_nil); \ +} while (0) + +/* Internal utility macros. */ +#define rbtn_first(a_type, a_field, a_rbt, a_root, r_node) do { \ + (r_node) = (a_root); \ + if ((r_node) != &(a_rbt)->rbt_nil) { \ + for (; \ + rbtn_left_get(a_type, a_field, (r_node)) != &(a_rbt)->rbt_nil;\ + (r_node) = rbtn_left_get(a_type, a_field, (r_node))) { \ + } \ + } \ +} while (0) + +#define rbtn_last(a_type, a_field, a_rbt, a_root, r_node) do { \ + (r_node) = (a_root); \ + if ((r_node) != &(a_rbt)->rbt_nil) { \ + for (; rbtn_right_get(a_type, a_field, (r_node)) != \ + &(a_rbt)->rbt_nil; (r_node) = rbtn_right_get(a_type, a_field, \ + (r_node))) { \ + } \ + } \ +} while (0) + +#define rbtn_rotate_left(a_type, a_field, a_node, r_node) do { \ + (r_node) = rbtn_right_get(a_type, a_field, (a_node)); \ + rbtn_right_set(a_type, a_field, (a_node), \ + rbtn_left_get(a_type, a_field, (r_node))); \ + rbtn_left_set(a_type, a_field, (r_node), (a_node)); \ +} while (0) + +#define rbtn_rotate_right(a_type, a_field, a_node, r_node) do { \ + (r_node) = rbtn_left_get(a_type, a_field, (a_node)); \ + rbtn_left_set(a_type, a_field, (a_node), \ + rbtn_right_get(a_type, a_field, (r_node))); \ + rbtn_right_set(a_type, a_field, (r_node), (a_node)); \ +} while (0) + +/* + * The rb_proto() macro generates function prototypes that correspond to the + * functions generated by an equivalently parameterized call to rb_gen(). + */ + +#define rb_proto(a_attr, a_prefix, a_rbt_type, a_type) \ +a_attr void \ +a_prefix##new(a_rbt_type *rbtree); \ +a_attr a_type * \ +a_prefix##first(a_rbt_type *rbtree); \ +a_attr a_type * \ +a_prefix##last(a_rbt_type *rbtree); \ +a_attr a_type * \ +a_prefix##next(a_rbt_type *rbtree, a_type *node); \ +a_attr a_type * \ +a_prefix##prev(a_rbt_type *rbtree, a_type *node); \ +a_attr a_type * \ +a_prefix##search(a_rbt_type *rbtree, a_type *key); \ +a_attr a_type * \ +a_prefix##nsearch(a_rbt_type *rbtree, a_type *key); \ +a_attr a_type * \ +a_prefix##psearch(a_rbt_type *rbtree, a_type *key); \ +a_attr void \ +a_prefix##insert(a_rbt_type *rbtree, a_type *node); \ +a_attr void \ +a_prefix##remove(a_rbt_type *rbtree, a_type *node); \ +a_attr a_type * \ +a_prefix##iter(a_rbt_type *rbtree, a_type *start, a_type *(*cb)( \ + a_rbt_type *, a_type *, void *), void *arg); \ +a_attr a_type * \ +a_prefix##reverse_iter(a_rbt_type *rbtree, a_type *start, \ + a_type *(*cb)(a_rbt_type *, a_type *, void *), void *arg); + +/* + * The rb_gen() macro generates a type-specific red-black tree implementation, + * based on the above cpp macros. + * + * Arguments: + * + * a_attr : Function attribute for generated functions (ex: static). + * a_prefix : Prefix for generated functions (ex: ex_). + * a_rb_type : Type for red-black tree data structure (ex: ex_t). + * a_type : Type for red-black tree node data structure (ex: ex_node_t). + * a_field : Name of red-black tree node linkage (ex: ex_link). + * a_cmp : Node comparison function name, with the following prototype: + * int (a_cmp *)(a_type *a_node, a_type *a_other); + * ^^^^^^ + * or a_key + * Interpretation of comparision function return values: + * -1 : a_node < a_other + * 0 : a_node == a_other + * 1 : a_node > a_other + * In all cases, the a_node or a_key macro argument is the first + * argument to the comparison function, which makes it possible + * to write comparison functions that treat the first argument + * specially. + * + * Assuming the following setup: + * + * typedef struct ex_node_s ex_node_t; + * struct ex_node_s { + * rb_node(ex_node_t) ex_link; + * }; + * typedef rb_tree(ex_node_t) ex_t; + * rb_gen(static, ex_, ex_t, ex_node_t, ex_link, ex_cmp) + * + * The following API is generated: + * + * static void + * ex_new(ex_t *extree); + * Description: Initialize a red-black tree structure. + * Args: + * extree: Pointer to an uninitialized red-black tree object. + * + * static ex_node_t * + * ex_first(ex_t *extree); + * static ex_node_t * + * ex_last(ex_t *extree); + * Description: Get the first/last node in extree. + * Args: + * extree: Pointer to an initialized red-black tree object. + * Ret: First/last node in extree, or NULL if extree is empty. + * + * static ex_node_t * + * ex_next(ex_t *extree, ex_node_t *node); + * static ex_node_t * + * ex_prev(ex_t *extree, ex_node_t *node); + * Description: Get node's successor/predecessor. + * Args: + * extree: Pointer to an initialized red-black tree object. + * node : A node in extree. + * Ret: node's successor/predecessor in extree, or NULL if node is + * last/first. + * + * static ex_node_t * + * ex_search(ex_t *extree, ex_node_t *key); + * Description: Search for node that matches key. + * Args: + * extree: Pointer to an initialized red-black tree object. + * key : Search key. + * Ret: Node in extree that matches key, or NULL if no match. + * + * static ex_node_t * + * ex_nsearch(ex_t *extree, ex_node_t *key); + * static ex_node_t * + * ex_psearch(ex_t *extree, ex_node_t *key); + * Description: Search for node that matches key. If no match is found, + * return what would be key's successor/predecessor, were + * key in extree. + * Args: + * extree: Pointer to an initialized red-black tree object. + * key : Search key. + * Ret: Node in extree that matches key, or if no match, hypothetical + * node's successor/predecessor (NULL if no successor/predecessor). + * + * static void + * ex_insert(ex_t *extree, ex_node_t *node); + * Description: Insert node into extree. + * Args: + * extree: Pointer to an initialized red-black tree object. + * node : Node to be inserted into extree. + * + * static void + * ex_remove(ex_t *extree, ex_node_t *node); + * Description: Remove node from extree. + * Args: + * extree: Pointer to an initialized red-black tree object. + * node : Node in extree to be removed. + * + * static ex_node_t * + * ex_iter(ex_t *extree, ex_node_t *start, ex_node_t *(*cb)(ex_t *, + * ex_node_t *, void *), void *arg); + * static ex_node_t * + * ex_reverse_iter(ex_t *extree, ex_node_t *start, ex_node *(*cb)(ex_t *, + * ex_node_t *, void *), void *arg); + * Description: Iterate forward/backward over extree, starting at node. + * If extree is modified, iteration must be immediately + * terminated by the callback function that causes the + * modification. + * Args: + * extree: Pointer to an initialized red-black tree object. + * start : Node at which to start iteration, or NULL to start at + * first/last node. + * cb : Callback function, which is called for each node during + * iteration. Under normal circumstances the callback function + * should return NULL, which causes iteration to continue. If a + * callback function returns non-NULL, iteration is immediately + * terminated and the non-NULL return value is returned by the + * iterator. This is useful for re-starting iteration after + * modifying extree. + * arg : Opaque pointer passed to cb(). + * Ret: NULL if iteration completed, or the non-NULL callback return value + * that caused termination of the iteration. + */ +#define rb_gen(a_attr, a_prefix, a_rbt_type, a_type, a_field, a_cmp) \ +a_attr void \ +a_prefix##new(a_rbt_type *rbtree) { \ + rb_new(a_type, a_field, rbtree); \ +} \ +a_attr a_type * \ +a_prefix##first(a_rbt_type *rbtree) { \ + a_type *ret; \ + rbtn_first(a_type, a_field, rbtree, rbtree->rbt_root, ret); \ + if (ret == &rbtree->rbt_nil) { \ + ret = NULL; \ + } \ + return (ret); \ +} \ +a_attr a_type * \ +a_prefix##last(a_rbt_type *rbtree) { \ + a_type *ret; \ + rbtn_last(a_type, a_field, rbtree, rbtree->rbt_root, ret); \ + if (ret == &rbtree->rbt_nil) { \ + ret = NULL; \ + } \ + return (ret); \ +} \ +a_attr a_type * \ +a_prefix##next(a_rbt_type *rbtree, a_type *node) { \ + a_type *ret; \ + if (rbtn_right_get(a_type, a_field, node) != &rbtree->rbt_nil) { \ + rbtn_first(a_type, a_field, rbtree, rbtn_right_get(a_type, \ + a_field, node), ret); \ + } else { \ + a_type *tnode = rbtree->rbt_root; \ + assert(tnode != &rbtree->rbt_nil); \ + ret = &rbtree->rbt_nil; \ + while (true) { \ + int cmp = (a_cmp)(node, tnode); \ + if (cmp < 0) { \ + ret = tnode; \ + tnode = rbtn_left_get(a_type, a_field, tnode); \ + } else if (cmp > 0) { \ + tnode = rbtn_right_get(a_type, a_field, tnode); \ + } else { \ + break; \ + } \ + assert(tnode != &rbtree->rbt_nil); \ + } \ + } \ + if (ret == &rbtree->rbt_nil) { \ + ret = (NULL); \ + } \ + return (ret); \ +} \ +a_attr a_type * \ +a_prefix##prev(a_rbt_type *rbtree, a_type *node) { \ + a_type *ret; \ + if (rbtn_left_get(a_type, a_field, node) != &rbtree->rbt_nil) { \ + rbtn_last(a_type, a_field, rbtree, rbtn_left_get(a_type, \ + a_field, node), ret); \ + } else { \ + a_type *tnode = rbtree->rbt_root; \ + assert(tnode != &rbtree->rbt_nil); \ + ret = &rbtree->rbt_nil; \ + while (true) { \ + int cmp = (a_cmp)(node, tnode); \ + if (cmp < 0) { \ + tnode = rbtn_left_get(a_type, a_field, tnode); \ + } else if (cmp > 0) { \ + ret = tnode; \ + tnode = rbtn_right_get(a_type, a_field, tnode); \ + } else { \ + break; \ + } \ + assert(tnode != &rbtree->rbt_nil); \ + } \ + } \ + if (ret == &rbtree->rbt_nil) { \ + ret = (NULL); \ + } \ + return (ret); \ +} \ +a_attr a_type * \ +a_prefix##search(a_rbt_type *rbtree, a_type *key) { \ + a_type *ret; \ + int cmp; \ + ret = rbtree->rbt_root; \ + while (ret != &rbtree->rbt_nil \ + && (cmp = (a_cmp)(key, ret)) != 0) { \ + if (cmp < 0) { \ + ret = rbtn_left_get(a_type, a_field, ret); \ + } else { \ + ret = rbtn_right_get(a_type, a_field, ret); \ + } \ + } \ + if (ret == &rbtree->rbt_nil) { \ + ret = (NULL); \ + } \ + return (ret); \ +} \ +a_attr a_type * \ +a_prefix##nsearch(a_rbt_type *rbtree, a_type *key) { \ + a_type *ret; \ + a_type *tnode = rbtree->rbt_root; \ + ret = &rbtree->rbt_nil; \ + while (tnode != &rbtree->rbt_nil) { \ + int cmp = (a_cmp)(key, tnode); \ + if (cmp < 0) { \ + ret = tnode; \ + tnode = rbtn_left_get(a_type, a_field, tnode); \ + } else if (cmp > 0) { \ + tnode = rbtn_right_get(a_type, a_field, tnode); \ + } else { \ + ret = tnode; \ + break; \ + } \ + } \ + if (ret == &rbtree->rbt_nil) { \ + ret = (NULL); \ + } \ + return (ret); \ +} \ +a_attr a_type * \ +a_prefix##psearch(a_rbt_type *rbtree, a_type *key) { \ + a_type *ret; \ + a_type *tnode = rbtree->rbt_root; \ + ret = &rbtree->rbt_nil; \ + while (tnode != &rbtree->rbt_nil) { \ + int cmp = (a_cmp)(key, tnode); \ + if (cmp < 0) { \ + tnode = rbtn_left_get(a_type, a_field, tnode); \ + } else if (cmp > 0) { \ + ret = tnode; \ + tnode = rbtn_right_get(a_type, a_field, tnode); \ + } else { \ + ret = tnode; \ + break; \ + } \ + } \ + if (ret == &rbtree->rbt_nil) { \ + ret = (NULL); \ + } \ + return (ret); \ +} \ +a_attr void \ +a_prefix##insert(a_rbt_type *rbtree, a_type *node) { \ + struct { \ + a_type *node; \ + int cmp; \ + } path[sizeof(void *) << 4], *pathp; \ + rbt_node_new(a_type, a_field, rbtree, node); \ + /* Wind. */ \ + path->node = rbtree->rbt_root; \ + for (pathp = path; pathp->node != &rbtree->rbt_nil; pathp++) { \ + int cmp = pathp->cmp = a_cmp(node, pathp->node); \ + assert(cmp != 0); \ + if (cmp < 0) { \ + pathp[1].node = rbtn_left_get(a_type, a_field, \ + pathp->node); \ + } else { \ + pathp[1].node = rbtn_right_get(a_type, a_field, \ + pathp->node); \ + } \ + } \ + pathp->node = node; \ + /* Unwind. */ \ + for (pathp--; (uintptr_t)pathp >= (uintptr_t)path; pathp--) { \ + a_type *cnode = pathp->node; \ + if (pathp->cmp < 0) { \ + a_type *left = pathp[1].node; \ + rbtn_left_set(a_type, a_field, cnode, left); \ + if (rbtn_red_get(a_type, a_field, left)) { \ + a_type *leftleft = rbtn_left_get(a_type, a_field, left);\ + if (rbtn_red_get(a_type, a_field, leftleft)) { \ + /* Fix up 4-node. */ \ + a_type *tnode; \ + rbtn_black_set(a_type, a_field, leftleft); \ + rbtn_rotate_right(a_type, a_field, cnode, tnode); \ + cnode = tnode; \ + } \ + } else { \ + return; \ + } \ + } else { \ + a_type *right = pathp[1].node; \ + rbtn_right_set(a_type, a_field, cnode, right); \ + if (rbtn_red_get(a_type, a_field, right)) { \ + a_type *left = rbtn_left_get(a_type, a_field, cnode); \ + if (rbtn_red_get(a_type, a_field, left)) { \ + /* Split 4-node. */ \ + rbtn_black_set(a_type, a_field, left); \ + rbtn_black_set(a_type, a_field, right); \ + rbtn_red_set(a_type, a_field, cnode); \ + } else { \ + /* Lean left. */ \ + a_type *tnode; \ + bool tred = rbtn_red_get(a_type, a_field, cnode); \ + rbtn_rotate_left(a_type, a_field, cnode, tnode); \ + rbtn_color_set(a_type, a_field, tnode, tred); \ + rbtn_red_set(a_type, a_field, cnode); \ + cnode = tnode; \ + } \ + } else { \ + return; \ + } \ + } \ + pathp->node = cnode; \ + } \ + /* Set root, and make it black. */ \ + rbtree->rbt_root = path->node; \ + rbtn_black_set(a_type, a_field, rbtree->rbt_root); \ +} \ +a_attr void \ +a_prefix##remove(a_rbt_type *rbtree, a_type *node) { \ + struct { \ + a_type *node; \ + int cmp; \ + } *pathp, *nodep, path[sizeof(void *) << 4]; \ + /* Wind. */ \ + nodep = NULL; /* Silence compiler warning. */ \ + path->node = rbtree->rbt_root; \ + for (pathp = path; pathp->node != &rbtree->rbt_nil; pathp++) { \ + int cmp = pathp->cmp = a_cmp(node, pathp->node); \ + if (cmp < 0) { \ + pathp[1].node = rbtn_left_get(a_type, a_field, \ + pathp->node); \ + } else { \ + pathp[1].node = rbtn_right_get(a_type, a_field, \ + pathp->node); \ + if (cmp == 0) { \ + /* Find node's successor, in preparation for swap. */ \ + pathp->cmp = 1; \ + nodep = pathp; \ + for (pathp++; pathp->node != &rbtree->rbt_nil; \ + pathp++) { \ + pathp->cmp = -1; \ + pathp[1].node = rbtn_left_get(a_type, a_field, \ + pathp->node); \ + } \ + break; \ + } \ + } \ + } \ + assert(nodep->node == node); \ + pathp--; \ + if (pathp->node != node) { \ + /* Swap node with its successor. */ \ + bool tred = rbtn_red_get(a_type, a_field, pathp->node); \ + rbtn_color_set(a_type, a_field, pathp->node, \ + rbtn_red_get(a_type, a_field, node)); \ + rbtn_left_set(a_type, a_field, pathp->node, \ + rbtn_left_get(a_type, a_field, node)); \ + /* If node's successor is its right child, the following code */\ + /* will do the wrong thing for the right child pointer. */\ + /* However, it doesn't matter, because the pointer will be */\ + /* properly set when the successor is pruned. */\ + rbtn_right_set(a_type, a_field, pathp->node, \ + rbtn_right_get(a_type, a_field, node)); \ + rbtn_color_set(a_type, a_field, node, tred); \ + /* The pruned leaf node's child pointers are never accessed */\ + /* again, so don't bother setting them to nil. */\ + nodep->node = pathp->node; \ + pathp->node = node; \ + if (nodep == path) { \ + rbtree->rbt_root = nodep->node; \ + } else { \ + if (nodep[-1].cmp < 0) { \ + rbtn_left_set(a_type, a_field, nodep[-1].node, \ + nodep->node); \ + } else { \ + rbtn_right_set(a_type, a_field, nodep[-1].node, \ + nodep->node); \ + } \ + } \ + } else { \ + a_type *left = rbtn_left_get(a_type, a_field, node); \ + if (left != &rbtree->rbt_nil) { \ + /* node has no successor, but it has a left child. */\ + /* Splice node out, without losing the left child. */\ + assert(rbtn_red_get(a_type, a_field, node) == false); \ + assert(rbtn_red_get(a_type, a_field, left)); \ + rbtn_black_set(a_type, a_field, left); \ + if (pathp == path) { \ + rbtree->rbt_root = left; \ + } else { \ + if (pathp[-1].cmp < 0) { \ + rbtn_left_set(a_type, a_field, pathp[-1].node, \ + left); \ + } else { \ + rbtn_right_set(a_type, a_field, pathp[-1].node, \ + left); \ + } \ + } \ + return; \ + } else if (pathp == path) { \ + /* The tree only contained one node. */ \ + rbtree->rbt_root = &rbtree->rbt_nil; \ + return; \ + } \ + } \ + if (rbtn_red_get(a_type, a_field, pathp->node)) { \ + /* Prune red node, which requires no fixup. */ \ + assert(pathp[-1].cmp < 0); \ + rbtn_left_set(a_type, a_field, pathp[-1].node, \ + &rbtree->rbt_nil); \ + return; \ + } \ + /* The node to be pruned is black, so unwind until balance is */\ + /* restored. */\ + pathp->node = &rbtree->rbt_nil; \ + for (pathp--; (uintptr_t)pathp >= (uintptr_t)path; pathp--) { \ + assert(pathp->cmp != 0); \ + if (pathp->cmp < 0) { \ + rbtn_left_set(a_type, a_field, pathp->node, \ + pathp[1].node); \ + assert(rbtn_red_get(a_type, a_field, pathp[1].node) \ + == false); \ + if (rbtn_red_get(a_type, a_field, pathp->node)) { \ + a_type *right = rbtn_right_get(a_type, a_field, \ + pathp->node); \ + a_type *rightleft = rbtn_left_get(a_type, a_field, \ + right); \ + a_type *tnode; \ + if (rbtn_red_get(a_type, a_field, rightleft)) { \ + /* In the following diagrams, ||, //, and \\ */\ + /* indicate the path to the removed node. */\ + /* */\ + /* || */\ + /* pathp(r) */\ + /* // \ */\ + /* (b) (b) */\ + /* / */\ + /* (r) */\ + /* */\ + rbtn_black_set(a_type, a_field, pathp->node); \ + rbtn_rotate_right(a_type, a_field, right, tnode); \ + rbtn_right_set(a_type, a_field, pathp->node, tnode);\ + rbtn_rotate_left(a_type, a_field, pathp->node, \ + tnode); \ + } else { \ + /* || */\ + /* pathp(r) */\ + /* // \ */\ + /* (b) (b) */\ + /* / */\ + /* (b) */\ + /* */\ + rbtn_rotate_left(a_type, a_field, pathp->node, \ + tnode); \ + } \ + /* Balance restored, but rotation modified subtree */\ + /* root. */\ + assert((uintptr_t)pathp > (uintptr_t)path); \ + if (pathp[-1].cmp < 0) { \ + rbtn_left_set(a_type, a_field, pathp[-1].node, \ + tnode); \ + } else { \ + rbtn_right_set(a_type, a_field, pathp[-1].node, \ + tnode); \ + } \ + return; \ + } else { \ + a_type *right = rbtn_right_get(a_type, a_field, \ + pathp->node); \ + a_type *rightleft = rbtn_left_get(a_type, a_field, \ + right); \ + if (rbtn_red_get(a_type, a_field, rightleft)) { \ + /* || */\ + /* pathp(b) */\ + /* // \ */\ + /* (b) (b) */\ + /* / */\ + /* (r) */\ + a_type *tnode; \ + rbtn_black_set(a_type, a_field, rightleft); \ + rbtn_rotate_right(a_type, a_field, right, tnode); \ + rbtn_right_set(a_type, a_field, pathp->node, tnode);\ + rbtn_rotate_left(a_type, a_field, pathp->node, \ + tnode); \ + /* Balance restored, but rotation modified */\ + /* subree root, which may actually be the tree */\ + /* root. */\ + if (pathp == path) { \ + /* Set root. */ \ + rbtree->rbt_root = tnode; \ + } else { \ + if (pathp[-1].cmp < 0) { \ + rbtn_left_set(a_type, a_field, \ + pathp[-1].node, tnode); \ + } else { \ + rbtn_right_set(a_type, a_field, \ + pathp[-1].node, tnode); \ + } \ + } \ + return; \ + } else { \ + /* || */\ + /* pathp(b) */\ + /* // \ */\ + /* (b) (b) */\ + /* / */\ + /* (b) */\ + a_type *tnode; \ + rbtn_red_set(a_type, a_field, pathp->node); \ + rbtn_rotate_left(a_type, a_field, pathp->node, \ + tnode); \ + pathp->node = tnode; \ + } \ + } \ + } else { \ + a_type *left; \ + rbtn_right_set(a_type, a_field, pathp->node, \ + pathp[1].node); \ + left = rbtn_left_get(a_type, a_field, pathp->node); \ + if (rbtn_red_get(a_type, a_field, left)) { \ + a_type *tnode; \ + a_type *leftright = rbtn_right_get(a_type, a_field, \ + left); \ + a_type *leftrightleft = rbtn_left_get(a_type, a_field, \ + leftright); \ + if (rbtn_red_get(a_type, a_field, leftrightleft)) { \ + /* || */\ + /* pathp(b) */\ + /* / \\ */\ + /* (r) (b) */\ + /* \ */\ + /* (b) */\ + /* / */\ + /* (r) */\ + a_type *unode; \ + rbtn_black_set(a_type, a_field, leftrightleft); \ + rbtn_rotate_right(a_type, a_field, pathp->node, \ + unode); \ + rbtn_rotate_right(a_type, a_field, pathp->node, \ + tnode); \ + rbtn_right_set(a_type, a_field, unode, tnode); \ + rbtn_rotate_left(a_type, a_field, unode, tnode); \ + } else { \ + /* || */\ + /* pathp(b) */\ + /* / \\ */\ + /* (r) (b) */\ + /* \ */\ + /* (b) */\ + /* / */\ + /* (b) */\ + assert(leftright != &rbtree->rbt_nil); \ + rbtn_red_set(a_type, a_field, leftright); \ + rbtn_rotate_right(a_type, a_field, pathp->node, \ + tnode); \ + rbtn_black_set(a_type, a_field, tnode); \ + } \ + /* Balance restored, but rotation modified subtree */\ + /* root, which may actually be the tree root. */\ + if (pathp == path) { \ + /* Set root. */ \ + rbtree->rbt_root = tnode; \ + } else { \ + if (pathp[-1].cmp < 0) { \ + rbtn_left_set(a_type, a_field, pathp[-1].node, \ + tnode); \ + } else { \ + rbtn_right_set(a_type, a_field, pathp[-1].node, \ + tnode); \ + } \ + } \ + return; \ + } else if (rbtn_red_get(a_type, a_field, pathp->node)) { \ + a_type *leftleft = rbtn_left_get(a_type, a_field, left);\ + if (rbtn_red_get(a_type, a_field, leftleft)) { \ + /* || */\ + /* pathp(r) */\ + /* / \\ */\ + /* (b) (b) */\ + /* / */\ + /* (r) */\ + a_type *tnode; \ + rbtn_black_set(a_type, a_field, pathp->node); \ + rbtn_red_set(a_type, a_field, left); \ + rbtn_black_set(a_type, a_field, leftleft); \ + rbtn_rotate_right(a_type, a_field, pathp->node, \ + tnode); \ + /* Balance restored, but rotation modified */\ + /* subtree root. */\ + assert((uintptr_t)pathp > (uintptr_t)path); \ + if (pathp[-1].cmp < 0) { \ + rbtn_left_set(a_type, a_field, pathp[-1].node, \ + tnode); \ + } else { \ + rbtn_right_set(a_type, a_field, pathp[-1].node, \ + tnode); \ + } \ + return; \ + } else { \ + /* || */\ + /* pathp(r) */\ + /* / \\ */\ + /* (b) (b) */\ + /* / */\ + /* (b) */\ + rbtn_red_set(a_type, a_field, left); \ + rbtn_black_set(a_type, a_field, pathp->node); \ + /* Balance restored. */ \ + return; \ + } \ + } else { \ + a_type *leftleft = rbtn_left_get(a_type, a_field, left);\ + if (rbtn_red_get(a_type, a_field, leftleft)) { \ + /* || */\ + /* pathp(b) */\ + /* / \\ */\ + /* (b) (b) */\ + /* / */\ + /* (r) */\ + a_type *tnode; \ + rbtn_black_set(a_type, a_field, leftleft); \ + rbtn_rotate_right(a_type, a_field, pathp->node, \ + tnode); \ + /* Balance restored, but rotation modified */\ + /* subtree root, which may actually be the tree */\ + /* root. */\ + if (pathp == path) { \ + /* Set root. */ \ + rbtree->rbt_root = tnode; \ + } else { \ + if (pathp[-1].cmp < 0) { \ + rbtn_left_set(a_type, a_field, \ + pathp[-1].node, tnode); \ + } else { \ + rbtn_right_set(a_type, a_field, \ + pathp[-1].node, tnode); \ + } \ + } \ + return; \ + } else { \ + /* || */\ + /* pathp(b) */\ + /* / \\ */\ + /* (b) (b) */\ + /* / */\ + /* (b) */\ + rbtn_red_set(a_type, a_field, left); \ + } \ + } \ + } \ + } \ + /* Set root. */ \ + rbtree->rbt_root = path->node; \ + assert(rbtn_red_get(a_type, a_field, rbtree->rbt_root) == false); \ +} \ +a_attr a_type * \ +a_prefix##iter_recurse(a_rbt_type *rbtree, a_type *node, \ + a_type *(*cb)(a_rbt_type *, a_type *, void *), void *arg) { \ + if (node == &rbtree->rbt_nil) { \ + return (&rbtree->rbt_nil); \ + } else { \ + a_type *ret; \ + if ((ret = a_prefix##iter_recurse(rbtree, rbtn_left_get(a_type, \ + a_field, node), cb, arg)) != &rbtree->rbt_nil \ + || (ret = cb(rbtree, node, arg)) != NULL) { \ + return (ret); \ + } \ + return (a_prefix##iter_recurse(rbtree, rbtn_right_get(a_type, \ + a_field, node), cb, arg)); \ + } \ +} \ +a_attr a_type * \ +a_prefix##iter_start(a_rbt_type *rbtree, a_type *start, a_type *node, \ + a_type *(*cb)(a_rbt_type *, a_type *, void *), void *arg) { \ + int cmp = a_cmp(start, node); \ + if (cmp < 0) { \ + a_type *ret; \ + if ((ret = a_prefix##iter_start(rbtree, start, \ + rbtn_left_get(a_type, a_field, node), cb, arg)) != \ + &rbtree->rbt_nil || (ret = cb(rbtree, node, arg)) != NULL) { \ + return (ret); \ + } \ + return (a_prefix##iter_recurse(rbtree, rbtn_right_get(a_type, \ + a_field, node), cb, arg)); \ + } else if (cmp > 0) { \ + return (a_prefix##iter_start(rbtree, start, \ + rbtn_right_get(a_type, a_field, node), cb, arg)); \ + } else { \ + a_type *ret; \ + if ((ret = cb(rbtree, node, arg)) != NULL) { \ + return (ret); \ + } \ + return (a_prefix##iter_recurse(rbtree, rbtn_right_get(a_type, \ + a_field, node), cb, arg)); \ + } \ +} \ +a_attr a_type * \ +a_prefix##iter(a_rbt_type *rbtree, a_type *start, a_type *(*cb)( \ + a_rbt_type *, a_type *, void *), void *arg) { \ + a_type *ret; \ + if (start != NULL) { \ + ret = a_prefix##iter_start(rbtree, start, rbtree->rbt_root, \ + cb, arg); \ + } else { \ + ret = a_prefix##iter_recurse(rbtree, rbtree->rbt_root, cb, arg);\ + } \ + if (ret == &rbtree->rbt_nil) { \ + ret = NULL; \ + } \ + return (ret); \ +} \ +a_attr a_type * \ +a_prefix##reverse_iter_recurse(a_rbt_type *rbtree, a_type *node, \ + a_type *(*cb)(a_rbt_type *, a_type *, void *), void *arg) { \ + if (node == &rbtree->rbt_nil) { \ + return (&rbtree->rbt_nil); \ + } else { \ + a_type *ret; \ + if ((ret = a_prefix##reverse_iter_recurse(rbtree, \ + rbtn_right_get(a_type, a_field, node), cb, arg)) != \ + &rbtree->rbt_nil || (ret = cb(rbtree, node, arg)) != NULL) { \ + return (ret); \ + } \ + return (a_prefix##reverse_iter_recurse(rbtree, \ + rbtn_left_get(a_type, a_field, node), cb, arg)); \ + } \ +} \ +a_attr a_type * \ +a_prefix##reverse_iter_start(a_rbt_type *rbtree, a_type *start, \ + a_type *node, a_type *(*cb)(a_rbt_type *, a_type *, void *), \ + void *arg) { \ + int cmp = a_cmp(start, node); \ + if (cmp > 0) { \ + a_type *ret; \ + if ((ret = a_prefix##reverse_iter_start(rbtree, start, \ + rbtn_right_get(a_type, a_field, node), cb, arg)) != \ + &rbtree->rbt_nil || (ret = cb(rbtree, node, arg)) != NULL) { \ + return (ret); \ + } \ + return (a_prefix##reverse_iter_recurse(rbtree, \ + rbtn_left_get(a_type, a_field, node), cb, arg)); \ + } else if (cmp < 0) { \ + return (a_prefix##reverse_iter_start(rbtree, start, \ + rbtn_left_get(a_type, a_field, node), cb, arg)); \ + } else { \ + a_type *ret; \ + if ((ret = cb(rbtree, node, arg)) != NULL) { \ + return (ret); \ + } \ + return (a_prefix##reverse_iter_recurse(rbtree, \ + rbtn_left_get(a_type, a_field, node), cb, arg)); \ + } \ +} \ +a_attr a_type * \ +a_prefix##reverse_iter(a_rbt_type *rbtree, a_type *start, \ + a_type *(*cb)(a_rbt_type *, a_type *, void *), void *arg) { \ + a_type *ret; \ + if (start != NULL) { \ + ret = a_prefix##reverse_iter_start(rbtree, start, \ + rbtree->rbt_root, cb, arg); \ + } else { \ + ret = a_prefix##reverse_iter_recurse(rbtree, rbtree->rbt_root, \ + cb, arg); \ + } \ + if (ret == &rbtree->rbt_nil) { \ + ret = NULL; \ + } \ + return (ret); \ +} + +#endif /* RB_H_ */ diff --git a/dep/jemalloc/jemalloc/internal/stats.h b/dep/jemalloc/jemalloc/internal/stats.h new file mode 100644 index 00000000000..cbf035ff2b9 --- /dev/null +++ b/dep/jemalloc/jemalloc/internal/stats.h @@ -0,0 +1,174 @@ +/******************************************************************************/ +#ifdef JEMALLOC_H_TYPES + +#define UMAX2S_BUFSIZE 65 + +#ifdef JEMALLOC_STATS +typedef struct tcache_bin_stats_s tcache_bin_stats_t; +typedef struct malloc_bin_stats_s malloc_bin_stats_t; +typedef struct malloc_large_stats_s malloc_large_stats_t; +typedef struct arena_stats_s arena_stats_t; +#endif +#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) +typedef struct chunk_stats_s chunk_stats_t; +#endif + +#endif /* JEMALLOC_H_TYPES */ +/******************************************************************************/ +#ifdef JEMALLOC_H_STRUCTS + +#ifdef JEMALLOC_STATS + +#ifdef JEMALLOC_TCACHE +struct tcache_bin_stats_s { + /* + * Number of allocation requests that corresponded to the size of this + * bin. + */ + uint64_t nrequests; +}; +#endif + +struct malloc_bin_stats_s { + /* + * Current number of bytes allocated, including objects currently + * cached by tcache. + */ + size_t allocated; + + /* + * Total number of allocation/deallocation requests served directly by + * the bin. Note that tcache may allocate an object, then recycle it + * many times, resulting many increments to nrequests, but only one + * each to nmalloc and ndalloc. + */ + uint64_t nmalloc; + uint64_t ndalloc; + + /* + * Number of allocation requests that correspond to the size of this + * bin. This includes requests served by tcache, though tcache only + * periodically merges into this counter. + */ + uint64_t nrequests; + +#ifdef JEMALLOC_TCACHE + /* Number of tcache fills from this bin. */ + uint64_t nfills; + + /* Number of tcache flushes to this bin. */ + uint64_t nflushes; +#endif + + /* Total number of runs created for this bin's size class. */ + uint64_t nruns; + + /* + * Total number of runs reused by extracting them from the runs tree for + * this bin's size class. + */ + uint64_t reruns; + + /* High-water mark for this bin. */ + size_t highruns; + + /* Current number of runs in this bin. */ + size_t curruns; +}; + +struct malloc_large_stats_s { + /* + * Total number of allocation/deallocation requests served directly by + * the arena. Note that tcache may allocate an object, then recycle it + * many times, resulting many increments to nrequests, but only one + * each to nmalloc and ndalloc. + */ + uint64_t nmalloc; + uint64_t ndalloc; + + /* + * Number of allocation requests that correspond to this size class. + * This includes requests served by tcache, though tcache only + * periodically merges into this counter. + */ + uint64_t nrequests; + + /* High-water mark for this size class. */ + size_t highruns; + + /* Current number of runs of this size class. */ + size_t curruns; +}; + +struct arena_stats_s { + /* Number of bytes currently mapped. */ + size_t mapped; + + /* + * Total number of purge sweeps, total number of madvise calls made, + * and total pages purged in order to keep dirty unused memory under + * control. + */ + uint64_t npurge; + uint64_t nmadvise; + uint64_t purged; + + /* Per-size-category statistics. */ + size_t allocated_large; + uint64_t nmalloc_large; + uint64_t ndalloc_large; + uint64_t nrequests_large; + + /* + * One element for each possible size class, including sizes that + * overlap with bin size classes. This is necessary because ipalloc() + * sometimes has to use such large objects in order to assure proper + * alignment. + */ + malloc_large_stats_t *lstats; +}; +#endif /* JEMALLOC_STATS */ + +#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) +struct chunk_stats_s { +# ifdef JEMALLOC_STATS + /* Number of chunks that were allocated. */ + uint64_t nchunks; +# endif + + /* High-water mark for number of chunks allocated. */ + size_t highchunks; + + /* + * Current number of chunks allocated. This value isn't maintained for + * any other purpose, so keep track of it in order to be able to set + * highchunks. + */ + size_t curchunks; +}; +#endif /* JEMALLOC_STATS */ + +#endif /* JEMALLOC_H_STRUCTS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_EXTERNS + +extern bool opt_stats_print; + +char *umax2s(uintmax_t x, unsigned base, char *s); +#ifdef JEMALLOC_STATS +void malloc_cprintf(void (*write)(void *, const char *), void *cbopaque, + const char *format, ...) JEMALLOC_ATTR(format(printf, 3, 4)); +void malloc_printf(const char *format, ...) + JEMALLOC_ATTR(format(printf, 1, 2)); +#endif +void stats_print(void (*write)(void *, const char *), void *cbopaque, + const char *opts); + +#endif /* JEMALLOC_H_EXTERNS */ +/******************************************************************************/ +#ifdef JEMALLOC_STATS +#ifdef JEMALLOC_H_INLINES + +#endif /* JEMALLOC_H_INLINES */ +#endif /* JEMALLOC_STATS */ +/******************************************************************************/ diff --git a/dep/jemalloc/jemalloc/internal/tcache.h b/dep/jemalloc/jemalloc/internal/tcache.h new file mode 100644 index 00000000000..c76597fafab --- /dev/null +++ b/dep/jemalloc/jemalloc/internal/tcache.h @@ -0,0 +1,380 @@ +#ifdef JEMALLOC_TCACHE +/******************************************************************************/ +#ifdef JEMALLOC_H_TYPES + +typedef struct tcache_bin_s tcache_bin_t; +typedef struct tcache_s tcache_t; + +/* + * Absolute maximum number of cache slots for each small bin in the thread + * cache. This is an additional constraint beyond that imposed as: twice the + * number of regions per run for this size class. + * + * This constant must be an even number. + */ +#define TCACHE_NSLOTS_SMALL_MAX 200 + +/* Number of cache slots for large size classes. */ +#define TCACHE_NSLOTS_LARGE 20 + +/* (1U << opt_lg_tcache_maxclass) is used to compute tcache_maxclass. */ +#define LG_TCACHE_MAXCLASS_DEFAULT 15 + +/* + * (1U << opt_lg_tcache_gc_sweep) is the approximate number of allocation + * events between full GC sweeps (-1: disabled). Integer rounding may cause + * the actual number to be slightly higher, since GC is performed + * incrementally. + */ +#define LG_TCACHE_GC_SWEEP_DEFAULT 13 + +#endif /* JEMALLOC_H_TYPES */ +/******************************************************************************/ +#ifdef JEMALLOC_H_STRUCTS + +struct tcache_bin_s { +# ifdef JEMALLOC_STATS + tcache_bin_stats_t tstats; +# endif + unsigned low_water; /* Min # cached since last GC. */ + unsigned high_water; /* Max # cached since last GC. */ + unsigned ncached; /* # of cached objects. */ + unsigned ncached_max; /* Upper limit on ncached. */ + void *avail; /* Chain of available objects. */ +}; + +struct tcache_s { +# ifdef JEMALLOC_STATS + ql_elm(tcache_t) link; /* Used for aggregating stats. */ +# endif +# ifdef JEMALLOC_PROF + uint64_t prof_accumbytes;/* Cleared after arena_prof_accum() */ +# endif + arena_t *arena; /* This thread's arena. */ + unsigned ev_cnt; /* Event count since incremental GC. */ + unsigned next_gc_bin; /* Next bin to GC. */ + tcache_bin_t tbins[1]; /* Dynamically sized. */ +}; + +#endif /* JEMALLOC_H_STRUCTS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_EXTERNS + +extern bool opt_tcache; +extern ssize_t opt_lg_tcache_maxclass; +extern ssize_t opt_lg_tcache_gc_sweep; + +/* Map of thread-specific caches. */ +extern __thread tcache_t *tcache_tls + JEMALLOC_ATTR(tls_model("initial-exec")); + +/* + * Number of tcache bins. There are nbins small-object bins, plus 0 or more + * large-object bins. + */ +extern size_t nhbins; + +/* Maximum cached size class. */ +extern size_t tcache_maxclass; + +/* Number of tcache allocation/deallocation events between incremental GCs. */ +extern unsigned tcache_gc_incr; + +void tcache_bin_flush_small(tcache_bin_t *tbin, size_t binind, unsigned rem +#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) + , tcache_t *tcache +#endif + ); +void tcache_bin_flush_large(tcache_bin_t *tbin, size_t binind, unsigned rem +#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) + , tcache_t *tcache +#endif + ); +tcache_t *tcache_create(arena_t *arena); +void *tcache_alloc_small_hard(tcache_t *tcache, tcache_bin_t *tbin, + size_t binind); +void tcache_destroy(tcache_t *tcache); +#ifdef JEMALLOC_STATS +void tcache_stats_merge(tcache_t *tcache, arena_t *arena); +#endif +void tcache_boot(void); + +#endif /* JEMALLOC_H_EXTERNS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_INLINES + +#ifndef JEMALLOC_ENABLE_INLINE +void tcache_event(tcache_t *tcache); +tcache_t *tcache_get(void); +void *tcache_alloc_easy(tcache_bin_t *tbin); +void *tcache_alloc_small(tcache_t *tcache, size_t size, bool zero); +void *tcache_alloc_large(tcache_t *tcache, size_t size, bool zero); +void tcache_dalloc_small(tcache_t *tcache, void *ptr); +void tcache_dalloc_large(tcache_t *tcache, void *ptr, size_t size); +#endif + +#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_TCACHE_C_)) +JEMALLOC_INLINE tcache_t * +tcache_get(void) +{ + tcache_t *tcache; + + if ((isthreaded & opt_tcache) == false) + return (NULL); + + tcache = tcache_tls; + if ((uintptr_t)tcache <= (uintptr_t)1) { + if (tcache == NULL) { + tcache = tcache_create(choose_arena()); + if (tcache == NULL) + return (NULL); + } else + return (NULL); + } + + return (tcache); +} + +JEMALLOC_INLINE void +tcache_event(tcache_t *tcache) +{ + + if (tcache_gc_incr == 0) + return; + + tcache->ev_cnt++; + assert(tcache->ev_cnt <= tcache_gc_incr); + if (tcache->ev_cnt == tcache_gc_incr) { + size_t binind = tcache->next_gc_bin; + tcache_bin_t *tbin = &tcache->tbins[binind]; + + if (tbin->low_water > 0) { + /* + * Flush (ceiling) 3/4 of the objects below the low + * water mark. + */ + if (binind < nbins) { + tcache_bin_flush_small(tbin, binind, + tbin->ncached - tbin->low_water + + (tbin->low_water >> 2) +#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) + , tcache +#endif + ); + } else { + tcache_bin_flush_large(tbin, binind, + tbin->ncached - tbin->low_water + + (tbin->low_water >> 2) +#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) + , tcache +#endif + ); + } + } + tbin->low_water = tbin->ncached; + tbin->high_water = tbin->ncached; + + tcache->next_gc_bin++; + if (tcache->next_gc_bin == nhbins) + tcache->next_gc_bin = 0; + tcache->ev_cnt = 0; + } +} + +JEMALLOC_INLINE void * +tcache_alloc_easy(tcache_bin_t *tbin) +{ + void *ret; + + if (tbin->ncached == 0) + return (NULL); + tbin->ncached--; + if (tbin->ncached < tbin->low_water) + tbin->low_water = tbin->ncached; + ret = tbin->avail; + tbin->avail = *(void **)ret; + return (ret); +} + +JEMALLOC_INLINE void * +tcache_alloc_small(tcache_t *tcache, size_t size, bool zero) +{ + void *ret; + size_t binind; + tcache_bin_t *tbin; + + binind = small_size2bin[size]; + assert(binind < nbins); + tbin = &tcache->tbins[binind]; + ret = tcache_alloc_easy(tbin); + if (ret == NULL) { + ret = tcache_alloc_small_hard(tcache, tbin, binind); + if (ret == NULL) + return (NULL); + } + assert(arena_salloc(ret) == tcache->arena->bins[binind].reg_size); + + if (zero == false) { +#ifdef JEMALLOC_FILL + if (opt_junk) + memset(ret, 0xa5, size); + else if (opt_zero) + memset(ret, 0, size); +#endif + } else + memset(ret, 0, size); + +#ifdef JEMALLOC_STATS + tbin->tstats.nrequests++; +#endif +#ifdef JEMALLOC_PROF + tcache->prof_accumbytes += tcache->arena->bins[binind].reg_size; +#endif + tcache_event(tcache); + return (ret); +} + +JEMALLOC_INLINE void * +tcache_alloc_large(tcache_t *tcache, size_t size, bool zero) +{ + void *ret; + size_t binind; + tcache_bin_t *tbin; + + size = PAGE_CEILING(size); + assert(size <= tcache_maxclass); + binind = nbins + (size >> PAGE_SHIFT) - 1; + assert(binind < nhbins); + tbin = &tcache->tbins[binind]; + ret = tcache_alloc_easy(tbin); + if (ret == NULL) { + /* + * Only allocate one large object at a time, because it's quite + * expensive to create one and not use it. + */ + ret = arena_malloc_large(tcache->arena, size, zero); + if (ret == NULL) + return (NULL); + } else { +#ifdef JEMALLOC_PROF + arena_chunk_t *chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ret); + size_t pageind = (unsigned)(((uintptr_t)ret - (uintptr_t)chunk) + >> PAGE_SHIFT); + chunk->map[pageind].bits |= CHUNK_MAP_CLASS_MASK; +#endif + if (zero == false) { +#ifdef JEMALLOC_FILL + if (opt_junk) + memset(ret, 0xa5, size); + else if (opt_zero) + memset(ret, 0, size); +#endif + } else + memset(ret, 0, size); + +#ifdef JEMALLOC_STATS + tbin->tstats.nrequests++; +#endif +#ifdef JEMALLOC_PROF + tcache->prof_accumbytes += size; +#endif + } + + tcache_event(tcache); + return (ret); +} + +JEMALLOC_INLINE void +tcache_dalloc_small(tcache_t *tcache, void *ptr) +{ + arena_t *arena; + arena_chunk_t *chunk; + arena_run_t *run; + arena_bin_t *bin; + tcache_bin_t *tbin; + size_t pageind, binind; + arena_chunk_map_t *mapelm; + + assert(arena_salloc(ptr) <= small_maxclass); + + chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); + arena = chunk->arena; + pageind = (((uintptr_t)ptr - (uintptr_t)chunk) >> PAGE_SHIFT); + mapelm = &chunk->map[pageind]; + run = (arena_run_t *)((uintptr_t)chunk + (uintptr_t)((pageind - + (mapelm->bits >> PAGE_SHIFT)) << PAGE_SHIFT)); + assert(run->magic == ARENA_RUN_MAGIC); + bin = run->bin; + binind = ((uintptr_t)bin - (uintptr_t)&arena->bins) / + sizeof(arena_bin_t); + assert(binind < nbins); + +#ifdef JEMALLOC_FILL + if (opt_junk) + memset(ptr, 0x5a, bin->reg_size); +#endif + + tbin = &tcache->tbins[binind]; + if (tbin->ncached == tbin->ncached_max) { + tcache_bin_flush_small(tbin, binind, (tbin->ncached_max >> 1) +#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) + , tcache +#endif + ); + } + assert(tbin->ncached < tbin->ncached_max); + *(void **)ptr = tbin->avail; + tbin->avail = ptr; + tbin->ncached++; + if (tbin->ncached > tbin->high_water) + tbin->high_water = tbin->ncached; + + tcache_event(tcache); +} + +JEMALLOC_INLINE void +tcache_dalloc_large(tcache_t *tcache, void *ptr, size_t size) +{ + arena_t *arena; + arena_chunk_t *chunk; + size_t pageind, binind; + tcache_bin_t *tbin; + arena_chunk_map_t *mapelm; + + assert((size & PAGE_MASK) == 0); + assert(arena_salloc(ptr) > small_maxclass); + assert(arena_salloc(ptr) <= tcache_maxclass); + + chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); + arena = chunk->arena; + pageind = (((uintptr_t)ptr - (uintptr_t)chunk) >> PAGE_SHIFT); + mapelm = &chunk->map[pageind]; + binind = nbins + (size >> PAGE_SHIFT) - 1; + +#ifdef JEMALLOC_FILL + if (opt_junk) + memset(ptr, 0x5a, bin->reg_size); +#endif + + tbin = &tcache->tbins[binind]; + if (tbin->ncached == tbin->ncached_max) { + tcache_bin_flush_large(tbin, binind, (tbin->ncached_max >> 1) +#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) + , tcache +#endif + ); + } + assert(tbin->ncached < tbin->ncached_max); + *(void **)ptr = tbin->avail; + tbin->avail = ptr; + tbin->ncached++; + if (tbin->ncached > tbin->high_water) + tbin->high_water = tbin->ncached; + + tcache_event(tcache); +} +#endif + +#endif /* JEMALLOC_H_INLINES */ +/******************************************************************************/ +#endif /* JEMALLOC_TCACHE */ diff --git a/dep/jemalloc/jemalloc/internal/totally_not_p_r_n.h b/dep/jemalloc/jemalloc/internal/totally_not_p_r_n.h new file mode 100644 index 00000000000..0709d708012 --- /dev/null +++ b/dep/jemalloc/jemalloc/internal/totally_not_p_r_n.h @@ -0,0 +1,60 @@ +/******************************************************************************/ +#ifdef JEMALLOC_H_TYPES + +/* + * Simple linear congruential pseudo-random number generator: + * + * prn(y) = (a*x + c) % m + * + * where the following constants ensure maximal period: + * + * a == Odd number (relatively prime to 2^n), and (a-1) is a multiple of 4. + * c == Odd number (relatively prime to 2^n). + * m == 2^32 + * + * See Knuth's TAOCP 3rd Ed., Vol. 2, pg. 17 for details on these constraints. + * + * This choice of m has the disadvantage that the quality of the bits is + * proportional to bit position. For example. the lowest bit has a cycle of 2, + * the next has a cycle of 4, etc. For this reason, we prefer to use the upper + * bits. + * + * Macro parameters: + * uint32_t r : Result. + * unsigned lg_range : (0..32], number of least significant bits to return. + * uint32_t state : Seed value. + * const uint32_t a, c : See above discussion. + */ +#define prn32(r, lg_range, state, a, c) do { \ + assert(lg_range > 0); \ + assert(lg_range <= 32); \ + \ + r = (state * (a)) + (c); \ + state = r; \ + r >>= (32 - lg_range); \ +} while (false) + +/* Same as prn32(), but 64 bits of pseudo-randomness, using uint64_t. */ +#define prn64(r, lg_range, state, a, c) do { \ + assert(lg_range > 0); \ + assert(lg_range <= 64); \ + \ + r = (state * (a)) + (c); \ + state = r; \ + r >>= (64 - lg_range); \ +} while (false) + +#endif /* JEMALLOC_H_TYPES */ +/******************************************************************************/ +#ifdef JEMALLOC_H_STRUCTS + +#endif /* JEMALLOC_H_STRUCTS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_EXTERNS + +#endif /* JEMALLOC_H_EXTERNS */ +/******************************************************************************/ +#ifdef JEMALLOC_H_INLINES + +#endif /* JEMALLOC_H_INLINES */ +/******************************************************************************/ diff --git a/dep/jemalloc/jemalloc/jemalloc.h b/dep/jemalloc/jemalloc/jemalloc.h new file mode 100644 index 00000000000..d9bafbfff55 --- /dev/null +++ b/dep/jemalloc/jemalloc/jemalloc.h @@ -0,0 +1,42 @@ +#ifndef JEMALLOC_H_ +#define JEMALLOC_H_ +#ifdef __cplusplus +extern "C" { +#endif + +#define JEMALLOC_VERSION "1.0.0-0-g5523399" +#define JEMALLOC_VERSION_MAJOR 1 +#define JEMALLOC_VERSION_MINOR 0 +#define JEMALLOC_VERSION_BUGFIX 0 +#define JEMALLOC_VERSION_NREV 0 +#define JEMALLOC_VERSION_GID "5523399" + +#include "jemalloc_defs.h" +#ifndef JEMALLOC_P +# define JEMALLOC_P(s) s +#endif + +extern const char *JEMALLOC_P(malloc_options); +extern void (*JEMALLOC_P(malloc_message))(void *, const char *); + +void *JEMALLOC_P(malloc)(size_t size) JEMALLOC_ATTR(malloc); +void *JEMALLOC_P(calloc)(size_t num, size_t size) JEMALLOC_ATTR(malloc); +int JEMALLOC_P(posix_memalign)(void **memptr, size_t alignment, size_t size) + JEMALLOC_ATTR(nonnull(1)); +void *JEMALLOC_P(realloc)(void *ptr, size_t size); +void JEMALLOC_P(free)(void *ptr); + +size_t JEMALLOC_P(malloc_usable_size)(const void *ptr); +void JEMALLOC_P(malloc_stats_print)(void (*write_cb)(void *, const char *), + void *cbopaque, const char *opts); +int JEMALLOC_P(mallctl)(const char *name, void *oldp, size_t *oldlenp, + void *newp, size_t newlen); +int JEMALLOC_P(mallctlnametomib)(const char *name, size_t *mibp, + size_t *miblenp); +int JEMALLOC_P(mallctlbymib)(const size_t *mib, size_t miblen, void *oldp, + size_t *oldlenp, void *newp, size_t newlen); + +#ifdef __cplusplus +}; +#endif +#endif /* JEMALLOC_H_ */ diff --git a/dep/jemalloc/jemalloc/jemalloc.h.in b/dep/jemalloc/jemalloc/jemalloc.h.in new file mode 100644 index 00000000000..8ef8183686e --- /dev/null +++ b/dep/jemalloc/jemalloc/jemalloc.h.in @@ -0,0 +1,42 @@ +#ifndef JEMALLOC_H_ +#define JEMALLOC_H_ +#ifdef __cplusplus +extern "C" { +#endif + +#define JEMALLOC_VERSION "@jemalloc_version@" +#define JEMALLOC_VERSION_MAJOR @jemalloc_version_major@ +#define JEMALLOC_VERSION_MINOR @jemalloc_version_minor@ +#define JEMALLOC_VERSION_BUGFIX @jemalloc_version_bugfix@ +#define JEMALLOC_VERSION_NREV @jemalloc_version_nrev@ +#define JEMALLOC_VERSION_GID "@jemalloc_version_gid@" + +#include "jemalloc_defs@install_suffix@.h" +#ifndef JEMALLOC_P +# define JEMALLOC_P(s) s +#endif + +extern const char *JEMALLOC_P(malloc_options); +extern void (*JEMALLOC_P(malloc_message))(void *, const char *); + +void *JEMALLOC_P(malloc)(size_t size) JEMALLOC_ATTR(malloc); +void *JEMALLOC_P(calloc)(size_t num, size_t size) JEMALLOC_ATTR(malloc); +int JEMALLOC_P(posix_memalign)(void **memptr, size_t alignment, size_t size) + JEMALLOC_ATTR(nonnull(1)); +void *JEMALLOC_P(realloc)(void *ptr, size_t size); +void JEMALLOC_P(free)(void *ptr); + +size_t JEMALLOC_P(malloc_usable_size)(const void *ptr); +void JEMALLOC_P(malloc_stats_print)(void (*write_cb)(void *, const char *), + void *cbopaque, const char *opts); +int JEMALLOC_P(mallctl)(const char *name, void *oldp, size_t *oldlenp, + void *newp, size_t newlen); +int JEMALLOC_P(mallctlnametomib)(const char *name, size_t *mibp, + size_t *miblenp); +int JEMALLOC_P(mallctlbymib)(const size_t *mib, size_t miblen, void *oldp, + size_t *oldlenp, void *newp, size_t newlen); + +#ifdef __cplusplus +}; +#endif +#endif /* JEMALLOC_H_ */ diff --git a/dep/jemalloc/jemalloc/jemalloc_defs.h b/dep/jemalloc/jemalloc/jemalloc_defs.h new file mode 100644 index 00000000000..e8acaed3abd --- /dev/null +++ b/dep/jemalloc/jemalloc/jemalloc_defs.h @@ -0,0 +1,102 @@ +/* include/jemalloc/jemalloc_defs.h. Generated from jemalloc_defs.h.in by configure. */ +#ifndef JEMALLOC_DEFS_H_ +#define JEMALLOC_DEFS_H_ + +/* + * If JEMALLOC_PREFIX is defined, it will cause all public APIs to be prefixed. + * This makes it possible, with some care, to use multiple allocators + * simultaneously. + * + * In many cases it is more convenient to manually prefix allocator function + * calls than to let macros do it automatically, particularly when using + * multiple allocators simultaneously. Define JEMALLOC_MANGLE before + * #include'ing jemalloc.h in order to cause name mangling that corresponds to + * the API prefixing. + */ +/* #undef JEMALLOC_PREFIX */ +#if (defined(JEMALLOC_PREFIX) && defined(JEMALLOC_MANGLE)) +/* #undef JEMALLOC_P */ +#endif + +/* + * Hyper-threaded CPUs may need a special instruction inside spin loops in + * order to yield to another virtual CPU. + */ +#define CPU_SPINWAIT __asm__ volatile("pause") + +/* Defined if __attribute__((...)) syntax is supported. */ +#define JEMALLOC_HAVE_ATTR +#ifdef JEMALLOC_HAVE_ATTR +# define JEMALLOC_ATTR(s) __attribute__((s)) +#else +# define JEMALLOC_ATTR(s) +#endif + +/* + * JEMALLOC_DEBUG enables assertions and other sanity checks, and disables + * inline functions. + */ +/* #undef JEMALLOC_DEBUG */ + +/* JEMALLOC_STATS enables statistics calculation. */ +/* #undef JEMALLOC_STATS */ + +/* JEMALLOC_PROF enables allocation profiling. */ +/* #undef JEMALLOC_PROF */ + +/* Use libunwind for profile backtracing if defined. */ +/* #undef JEMALLOC_PROF_LIBUNWIND */ + +/* Use libgcc for profile backtracing if defined. */ +/* #undef JEMALLOC_PROF_LIBGCC */ + +/* + * JEMALLOC_TINY enables support for tiny objects, which are smaller than one + * quantum. + */ +#define JEMALLOC_TINY + +/* + * JEMALLOC_TCACHE enables a thread-specific caching layer for small objects. + * This makes it possible to allocate/deallocate objects without any locking + * when the cache is in the steady state. + */ +#define JEMALLOC_TCACHE + +/* + * JEMALLOC_DSS enables use of sbrk(2) to allocate chunks from the data storage + * segment (DSS). + */ +/* #undef JEMALLOC_DSS */ + +/* JEMALLOC_SWAP enables mmap()ed swap file support. */ +/* #undef JEMALLOC_SWAP */ + +/* Support memory filling (junk/zero). */ +/* #undef JEMALLOC_FILL */ + +/* Support optional abort() on OOM. */ +/* #undef JEMALLOC_XMALLOC */ + +/* Support SYSV semantics. */ +/* #undef JEMALLOC_SYSV */ + +/* Support lazy locking (avoid locking unless a second thread is launched). */ +#define JEMALLOC_LAZY_LOCK + +/* Determine page size at run time if defined. */ +/* #undef DYNAMIC_PAGE_SHIFT */ + +/* One page is 2^STATIC_PAGE_SHIFT bytes. */ +#define STATIC_PAGE_SHIFT 12 + +/* TLS is used to map arenas and magazine caches to threads. */ +/* #undef NO_TLS */ + +/* sizeof(void *) == 2^LG_SIZEOF_PTR. */ +#define LG_SIZEOF_PTR 3 + +/* sizeof(int) == 2^LG_SIZEOF_INT. */ +#define LG_SIZEOF_INT 2 + +#endif /* JEMALLOC_DEFS_H_ */ diff --git a/dep/jemalloc/jemalloc/jemalloc_defs.h.in b/dep/jemalloc/jemalloc/jemalloc_defs.h.in new file mode 100644 index 00000000000..8b98d670acc --- /dev/null +++ b/dep/jemalloc/jemalloc/jemalloc_defs.h.in @@ -0,0 +1,101 @@ +#ifndef JEMALLOC_DEFS_H_ +#define JEMALLOC_DEFS_H_ + +/* + * If JEMALLOC_PREFIX is defined, it will cause all public APIs to be prefixed. + * This makes it possible, with some care, to use multiple allocators + * simultaneously. + * + * In many cases it is more convenient to manually prefix allocator function + * calls than to let macros do it automatically, particularly when using + * multiple allocators simultaneously. Define JEMALLOC_MANGLE before + * #include'ing jemalloc.h in order to cause name mangling that corresponds to + * the API prefixing. + */ +#undef JEMALLOC_PREFIX +#if (defined(JEMALLOC_PREFIX) && defined(JEMALLOC_MANGLE)) +#undef JEMALLOC_P +#endif + +/* + * Hyper-threaded CPUs may need a special instruction inside spin loops in + * order to yield to another virtual CPU. + */ +#undef CPU_SPINWAIT + +/* Defined if __attribute__((...)) syntax is supported. */ +#undef JEMALLOC_HAVE_ATTR +#ifdef JEMALLOC_HAVE_ATTR +# define JEMALLOC_ATTR(s) __attribute__((s)) +#else +# define JEMALLOC_ATTR(s) +#endif + +/* + * JEMALLOC_DEBUG enables assertions and other sanity checks, and disables + * inline functions. + */ +#undef JEMALLOC_DEBUG + +/* JEMALLOC_STATS enables statistics calculation. */ +#undef JEMALLOC_STATS + +/* JEMALLOC_PROF enables allocation profiling. */ +#undef JEMALLOC_PROF + +/* Use libunwind for profile backtracing if defined. */ +#undef JEMALLOC_PROF_LIBUNWIND + +/* Use libgcc for profile backtracing if defined. */ +#undef JEMALLOC_PROF_LIBGCC + +/* + * JEMALLOC_TINY enables support for tiny objects, which are smaller than one + * quantum. + */ +#undef JEMALLOC_TINY + +/* + * JEMALLOC_TCACHE enables a thread-specific caching layer for small objects. + * This makes it possible to allocate/deallocate objects without any locking + * when the cache is in the steady state. + */ +#undef JEMALLOC_TCACHE + +/* + * JEMALLOC_DSS enables use of sbrk(2) to allocate chunks from the data storage + * segment (DSS). + */ +#undef JEMALLOC_DSS + +/* JEMALLOC_SWAP enables mmap()ed swap file support. */ +#undef JEMALLOC_SWAP + +/* Support memory filling (junk/zero). */ +#undef JEMALLOC_FILL + +/* Support optional abort() on OOM. */ +#undef JEMALLOC_XMALLOC + +/* Support SYSV semantics. */ +#undef JEMALLOC_SYSV + +/* Support lazy locking (avoid locking unless a second thread is launched). */ +#undef JEMALLOC_LAZY_LOCK + +/* Determine page size at run time if defined. */ +#undef DYNAMIC_PAGE_SHIFT + +/* One page is 2^STATIC_PAGE_SHIFT bytes. */ +#undef STATIC_PAGE_SHIFT + +/* TLS is used to map arenas and magazine caches to threads. */ +#undef NO_TLS + +/* sizeof(void *) == 2^LG_SIZEOF_PTR. */ +#undef LG_SIZEOF_PTR + +/* sizeof(int) == 2^LG_SIZEOF_INT. */ +#undef LG_SIZEOF_INT + +#endif /* JEMALLOC_DEFS_H_ */ diff --git a/dep/jemalloc/mb.c b/dep/jemalloc/mb.c new file mode 100644 index 00000000000..30a1a2e997a --- /dev/null +++ b/dep/jemalloc/mb.c @@ -0,0 +1,2 @@ +#define MB_C_ +#include "jemalloc/internal/jemalloc_internal.h" diff --git a/dep/jemalloc/mutex.c b/dep/jemalloc/mutex.c new file mode 100644 index 00000000000..3b6081a4c4f --- /dev/null +++ b/dep/jemalloc/mutex.c @@ -0,0 +1,70 @@ +#define JEMALLOC_MUTEX_C_ +#include "jemalloc/internal/jemalloc_internal.h" + +/******************************************************************************/ +/* Data. */ + +#ifdef JEMALLOC_LAZY_LOCK +bool isthreaded = false; +#endif + +#ifdef JEMALLOC_LAZY_LOCK +static void pthread_create_once(void); +#endif + +/******************************************************************************/ +/* + * We intercept pthread_create() calls in order to toggle isthreaded if the + * process goes multi-threaded. + */ + +#ifdef JEMALLOC_LAZY_LOCK +static int (*pthread_create_fptr)(pthread_t *__restrict, const pthread_attr_t *, + void *(*)(void *), void *__restrict); + +static void +pthread_create_once(void) +{ + + pthread_create_fptr = dlsym(RTLD_NEXT, "pthread_create"); + if (pthread_create_fptr == NULL) { + malloc_write(": Error in dlsym(RTLD_NEXT, " + "\"pthread_create\")\n"); + abort(); + } + + isthreaded = true; +} + +JEMALLOC_ATTR(visibility("default")) +int +pthread_create(pthread_t *__restrict thread, + const pthread_attr_t *__restrict attr, void *(*start_routine)(void *), + void *__restrict arg) +{ + static pthread_once_t once_control = PTHREAD_ONCE_INIT; + + pthread_once(&once_control, pthread_create_once); + + return (pthread_create_fptr(thread, attr, start_routine, arg)); +} +#endif + +/******************************************************************************/ + +bool +malloc_mutex_init(malloc_mutex_t *mutex) +{ + pthread_mutexattr_t attr; + + if (pthread_mutexattr_init(&attr) != 0) + return (true); + pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ADAPTIVE_NP); + if (pthread_mutex_init(mutex, &attr) != 0) { + pthread_mutexattr_destroy(&attr); + return (true); + } + pthread_mutexattr_destroy(&attr); + + return (false); +} diff --git a/dep/jemalloc/prof.c b/dep/jemalloc/prof.c new file mode 100644 index 00000000000..6326188e50f --- /dev/null +++ b/dep/jemalloc/prof.c @@ -0,0 +1,1328 @@ +#define JEMALLOC_PROF_C_ +#include "jemalloc/internal/jemalloc_internal.h" +#ifdef JEMALLOC_PROF +/******************************************************************************/ + +#ifdef JEMALLOC_PROF_LIBGCC +#include +#endif + +#ifdef JEMALLOC_PROF_LIBUNWIND +#define UNW_LOCAL_ONLY +#include +#endif + +#include + +/******************************************************************************/ +/* Data. */ + +bool opt_prof = false; +bool opt_prof_active = true; +size_t opt_lg_prof_bt_max = LG_PROF_BT_MAX_DEFAULT; +size_t opt_lg_prof_sample = LG_PROF_SAMPLE_DEFAULT; +ssize_t opt_lg_prof_interval = LG_PROF_INTERVAL_DEFAULT; +bool opt_prof_udump = false; +bool opt_prof_leak = false; + +uint64_t prof_interval; +bool prof_promote; + +/* + * Global hash of (prof_bt_t *)-->(prof_ctx_t *). This is the master data + * structure that knows about all backtraces ever captured. + */ +static ckh_t bt2ctx; +static malloc_mutex_t bt2ctx_mtx; + +/* + * Thread-specific hash of (prof_bt_t *)-->(prof_thr_cnt_t *). Each thread + * keeps a cache of backtraces, with associated thread-specific prof_thr_cnt_t + * objects. Other threads may read the prof_thr_cnt_t contents, but no others + * will ever write them. + * + * Upon thread exit, the thread must merge all the prof_thr_cnt_t counter data + * into the associated prof_ctx_t objects, and unlink/free the prof_thr_cnt_t + * objects. + */ +static __thread ckh_t *bt2cnt_tls JEMALLOC_ATTR(tls_model("initial-exec")); + +/* + * Same contents as b2cnt, but initialized such that the TSD destructor is + * called when a thread exits, so that bt2cnt_tls contents can be merged, + * unlinked, and deallocated. + */ +static pthread_key_t bt2cnt_tsd; + +/* (1U << opt_lg_prof_bt_max). */ +static unsigned prof_bt_max; + +static __thread uint64_t prof_sample_prn_state + JEMALLOC_ATTR(tls_model("initial-exec")); +static __thread uint64_t prof_sample_threshold + JEMALLOC_ATTR(tls_model("initial-exec")); +static __thread uint64_t prof_sample_accum + JEMALLOC_ATTR(tls_model("initial-exec")); + +static malloc_mutex_t prof_dump_seq_mtx; +static uint64_t prof_dump_seq; +static uint64_t prof_dump_iseq; +static uint64_t prof_dump_mseq; +static uint64_t prof_dump_useq; + +/* + * This buffer is rather large for stack allocation, so use a single buffer for + * all profile dumps. The buffer is implicitly protected by bt2ctx_mtx, since + * it must be locked anyway during dumping. + */ +static char prof_dump_buf[PROF_DUMP_BUF_SIZE]; +static unsigned prof_dump_buf_end; +static int prof_dump_fd; + +/* Do not dump any profiles until bootstrapping is complete. */ +static bool prof_booted = false; + +static malloc_mutex_t enq_mtx; +static bool enq; +static bool enq_idump; +static bool enq_udump; + +/******************************************************************************/ +/* Function prototypes for non-inline static functions. */ + +static prof_bt_t *bt_dup(prof_bt_t *bt); +static void bt_init(prof_bt_t *bt, void **vec); +#ifdef JEMALLOC_PROF_LIBGCC +static _Unwind_Reason_Code prof_unwind_init_callback( + struct _Unwind_Context *context, void *arg); +static _Unwind_Reason_Code prof_unwind_callback( + struct _Unwind_Context *context, void *arg); +#endif +static void prof_backtrace(prof_bt_t *bt, unsigned nignore, unsigned max); +static prof_thr_cnt_t *prof_lookup(prof_bt_t *bt); +static void prof_cnt_set(const void *ptr, prof_thr_cnt_t *cnt); +static bool prof_flush(bool propagate_err); +static bool prof_write(const char *s, bool propagate_err); +static void prof_ctx_merge(prof_ctx_t *ctx, prof_cnt_t *cnt_all, + size_t *leak_nctx); +static bool prof_dump_ctx(prof_ctx_t *ctx, prof_bt_t *bt, + bool propagate_err); +static bool prof_dump_maps(bool propagate_err); +static bool prof_dump(const char *filename, bool leakcheck, + bool propagate_err); +static void prof_dump_filename(char *filename, char v, int64_t vseq); +static void prof_fdump(void); +static void prof_bt_hash(const void *key, unsigned minbits, size_t *hash1, + size_t *hash2); +static bool prof_bt_keycomp(const void *k1, const void *k2); +static void bt2cnt_thread_cleanup(void *arg); + +/******************************************************************************/ + +static void +bt_init(prof_bt_t *bt, void **vec) +{ + + bt->vec = vec; + bt->len = 0; +} + +static prof_bt_t * +bt_dup(prof_bt_t *bt) +{ + prof_bt_t *ret; + + /* + * Create a single allocation that has space for vec immediately + * following the prof_bt_t structure. The backtraces that get + * stored in the backtrace caches are copied from stack-allocated + * temporary variables, so size is known at creation time. Making this + * a contiguous object improves cache locality. + */ + ret = (prof_bt_t *)imalloc(QUANTUM_CEILING(sizeof(prof_bt_t)) + + (bt->len * sizeof(void *))); + if (ret == NULL) + return (NULL); + ret->vec = (void **)((uintptr_t)ret + + QUANTUM_CEILING(sizeof(prof_bt_t))); + memcpy(ret->vec, bt->vec, bt->len * sizeof(void *)); + ret->len = bt->len; + + return (ret); +} + +static inline void +prof_enter(void) +{ + + malloc_mutex_lock(&enq_mtx); + enq = true; + malloc_mutex_unlock(&enq_mtx); + + malloc_mutex_lock(&bt2ctx_mtx); +} + +static inline void +prof_leave(void) +{ + bool idump, udump; + + malloc_mutex_unlock(&bt2ctx_mtx); + + malloc_mutex_lock(&enq_mtx); + enq = false; + idump = enq_idump; + enq_idump = false; + udump = enq_udump; + enq_udump = false; + malloc_mutex_unlock(&enq_mtx); + + if (idump) + prof_idump(); + if (udump) + prof_udump(); +} + +#ifdef JEMALLOC_PROF_LIBGCC +static _Unwind_Reason_Code +prof_unwind_init_callback(struct _Unwind_Context *context, void *arg) +{ + + return (_URC_NO_REASON); +} + +static _Unwind_Reason_Code +prof_unwind_callback(struct _Unwind_Context *context, void *arg) +{ + prof_unwind_data_t *data = (prof_unwind_data_t *)arg; + + if (data->nignore > 0) + data->nignore--; + else { + data->bt->vec[data->bt->len] = (void *)_Unwind_GetIP(context); + data->bt->len++; + if (data->bt->len == data->max) + return (_URC_END_OF_STACK); + } + + return (_URC_NO_REASON); +} + +static void +prof_backtrace(prof_bt_t *bt, unsigned nignore, unsigned max) +{ + prof_unwind_data_t data = {bt, nignore, max}; + + _Unwind_Backtrace(prof_unwind_callback, &data); +} +#elif defined(JEMALLOC_PROF_LIBUNWIND) +static void +prof_backtrace(prof_bt_t *bt, unsigned nignore, unsigned max) +{ + unw_context_t uc; + unw_cursor_t cursor; + unsigned i; + int err; + + assert(bt->len == 0); + assert(bt->vec != NULL); + assert(max <= (1U << opt_lg_prof_bt_max)); + + unw_getcontext(&uc); + unw_init_local(&cursor, &uc); + + /* Throw away (nignore+1) stack frames, if that many exist. */ + for (i = 0; i < nignore + 1; i++) { + err = unw_step(&cursor); + if (err <= 0) + return; + } + + /* + * Iterate over stack frames until there are no more. Heap-allocate + * and iteratively grow a larger bt if necessary. + */ + for (i = 0; i < max; i++) { + unw_get_reg(&cursor, UNW_REG_IP, (unw_word_t *)&bt->vec[i]); + err = unw_step(&cursor); + if (err <= 0) { + bt->len = i; + break; + } + } +} +#else +static void +prof_backtrace(prof_bt_t *bt, unsigned nignore, unsigned max) +{ +#define NIGNORE 3 +#define BT_FRAME(i) \ + if ((i) < NIGNORE + max) { \ + void *p; \ + if (__builtin_frame_address(i) == 0) \ + return; \ + p = __builtin_return_address(i); \ + if (p == NULL) \ + return; \ + if (i >= NIGNORE) { \ + bt->vec[(i) - NIGNORE] = p; \ + bt->len = (i) - NIGNORE + 1; \ + } \ + } else \ + return; + + assert(max <= (1U << opt_lg_prof_bt_max)); + + /* + * Ignore the first three frames, since they are: + * + * 0: prof_backtrace() + * 1: prof_alloc_prep() + * 2: malloc(), calloc(), etc. + */ +#if 1 + assert(nignore + 1 == NIGNORE); +#else + BT_FRAME(0) + BT_FRAME(1) + BT_FRAME(2) +#endif + BT_FRAME(3) + BT_FRAME(4) + BT_FRAME(5) + BT_FRAME(6) + BT_FRAME(7) + BT_FRAME(8) + BT_FRAME(9) + + BT_FRAME(10) + BT_FRAME(11) + BT_FRAME(12) + BT_FRAME(13) + BT_FRAME(14) + BT_FRAME(15) + BT_FRAME(16) + BT_FRAME(17) + BT_FRAME(18) + BT_FRAME(19) + + BT_FRAME(20) + BT_FRAME(21) + BT_FRAME(22) + BT_FRAME(23) + BT_FRAME(24) + BT_FRAME(25) + BT_FRAME(26) + BT_FRAME(27) + BT_FRAME(28) + BT_FRAME(29) + + BT_FRAME(30) + BT_FRAME(31) + BT_FRAME(32) + BT_FRAME(33) + BT_FRAME(34) + BT_FRAME(35) + BT_FRAME(36) + BT_FRAME(37) + BT_FRAME(38) + BT_FRAME(39) + + BT_FRAME(40) + BT_FRAME(41) + BT_FRAME(42) + BT_FRAME(43) + BT_FRAME(44) + BT_FRAME(45) + BT_FRAME(46) + BT_FRAME(47) + BT_FRAME(48) + BT_FRAME(49) + + BT_FRAME(50) + BT_FRAME(51) + BT_FRAME(52) + BT_FRAME(53) + BT_FRAME(54) + BT_FRAME(55) + BT_FRAME(56) + BT_FRAME(57) + BT_FRAME(58) + BT_FRAME(59) + + BT_FRAME(60) + BT_FRAME(61) + BT_FRAME(62) + BT_FRAME(63) + BT_FRAME(64) + BT_FRAME(65) + BT_FRAME(66) + BT_FRAME(67) + BT_FRAME(68) + BT_FRAME(69) + + BT_FRAME(70) + BT_FRAME(71) + BT_FRAME(72) + BT_FRAME(73) + BT_FRAME(74) + BT_FRAME(75) + BT_FRAME(76) + BT_FRAME(77) + BT_FRAME(78) + BT_FRAME(79) + + BT_FRAME(80) + BT_FRAME(81) + BT_FRAME(82) + BT_FRAME(83) + BT_FRAME(84) + BT_FRAME(85) + BT_FRAME(86) + BT_FRAME(87) + BT_FRAME(88) + BT_FRAME(89) + + BT_FRAME(90) + BT_FRAME(91) + BT_FRAME(92) + BT_FRAME(93) + BT_FRAME(94) + BT_FRAME(95) + BT_FRAME(96) + BT_FRAME(97) + BT_FRAME(98) + BT_FRAME(99) + + BT_FRAME(100) + BT_FRAME(101) + BT_FRAME(102) + BT_FRAME(103) + BT_FRAME(104) + BT_FRAME(105) + BT_FRAME(106) + BT_FRAME(107) + BT_FRAME(108) + BT_FRAME(109) + + BT_FRAME(110) + BT_FRAME(111) + BT_FRAME(112) + BT_FRAME(113) + BT_FRAME(114) + BT_FRAME(115) + BT_FRAME(116) + BT_FRAME(117) + BT_FRAME(118) + BT_FRAME(119) + + BT_FRAME(120) + BT_FRAME(121) + BT_FRAME(122) + BT_FRAME(123) + BT_FRAME(124) + BT_FRAME(125) + BT_FRAME(126) + BT_FRAME(127) + + /* Extras to compensate for NIGNORE. */ + BT_FRAME(128) + BT_FRAME(129) + BT_FRAME(130) +#undef BT_FRAME +} +#endif + +static prof_thr_cnt_t * +prof_lookup(prof_bt_t *bt) +{ + prof_thr_cnt_t *ret; + ckh_t *bt2cnt = bt2cnt_tls; + + if (bt2cnt == NULL) { + /* Initialize an empty cache for this thread. */ + bt2cnt = (ckh_t *)imalloc(sizeof(ckh_t)); + if (bt2cnt == NULL) + return (NULL); + if (ckh_new(bt2cnt, PROF_CKH_MINITEMS, prof_bt_hash, + prof_bt_keycomp)) { + idalloc(bt2cnt); + return (NULL); + } + bt2cnt_tls = bt2cnt; + } + + if (ckh_search(bt2cnt, bt, NULL, (void **)&ret)) { + prof_bt_t *btkey; + prof_ctx_t *ctx; + + /* + * This thread's cache lacks bt. Look for it in the global + * cache. + */ + prof_enter(); + if (ckh_search(&bt2ctx, bt, (void **)&btkey, (void **)&ctx)) { + + /* bt has never been seen before. Insert it. */ + ctx = (prof_ctx_t *)imalloc(sizeof(prof_ctx_t)); + if (ctx == NULL) { + prof_leave(); + return (NULL); + } + btkey = bt_dup(bt); + if (btkey == NULL) { + prof_leave(); + idalloc(ctx); + return (NULL); + } + if (malloc_mutex_init(&ctx->lock)) { + prof_leave(); + idalloc(btkey); + idalloc(ctx); + return (NULL); + } + memset(&ctx->cnt_merged, 0, sizeof(prof_cnt_t)); + ql_new(&ctx->cnts_ql); + if (ckh_insert(&bt2ctx, btkey, ctx)) { + /* OOM. */ + prof_leave(); + idalloc(btkey); + idalloc(ctx); + return (NULL); + } + } + prof_leave(); + + /* Link a prof_thd_cnt_t into ctx for this thread. */ + ret = (prof_thr_cnt_t *)imalloc(sizeof(prof_thr_cnt_t)); + if (ret == NULL) + return (NULL); + ql_elm_new(ret, link); + ret->ctx = ctx; + ret->epoch = 0; + memset(&ret->cnts, 0, sizeof(prof_cnt_t)); + if (ckh_insert(bt2cnt, btkey, ret)) { + idalloc(ret); + return (NULL); + } + malloc_mutex_lock(&ctx->lock); + ql_tail_insert(&ctx->cnts_ql, ret, link); + malloc_mutex_unlock(&ctx->lock); + } + + return (ret); +} + +static inline void +prof_sample_threshold_update(void) +{ + uint64_t r; + double u; + + /* + * Compute prof_sample_threshold as a geometrically distributed random + * variable with mean (2^opt_lg_prof_sample). + */ + prn64(r, 53, prof_sample_prn_state, (uint64_t)1125899906842625LLU, + 1058392653243283975); + u = (double)r * (1.0/9007199254740992.0L); + prof_sample_threshold = (uint64_t)(log(u) / + log(1.0 - (1.0 / (double)((uint64_t)1U << opt_lg_prof_sample)))) + + (uint64_t)1U; +} + +prof_thr_cnt_t * +prof_alloc_prep(size_t size) +{ + prof_thr_cnt_t *ret; + void *vec[prof_bt_max]; + prof_bt_t bt; + + if (opt_prof_active == false) { + /* Sampling is currently inactive, so avoid sampling. */ + ret = (prof_thr_cnt_t *)(uintptr_t)1U; + } else if (opt_lg_prof_sample == 0) { + /* + * Don't bother with sampling logic, since sampling interval is + * 1. + */ + bt_init(&bt, vec); + prof_backtrace(&bt, 2, prof_bt_max); + ret = prof_lookup(&bt); + } else { + if (prof_sample_threshold == 0) { + /* + * Initialize. Seed the prng differently for each + * thread. + */ + prof_sample_prn_state = (uint64_t)(uintptr_t)&size; + prof_sample_threshold_update(); + } + + /* + * Determine whether to capture a backtrace based on whether + * size is enough for prof_accum to reach + * prof_sample_threshold. However, delay updating these + * variables until prof_{m,re}alloc(), because we don't know + * for sure that the allocation will succeed. + * + * Use subtraction rather than addition to avoid potential + * integer overflow. + */ + if (size >= prof_sample_threshold - prof_sample_accum) { + bt_init(&bt, vec); + prof_backtrace(&bt, 2, prof_bt_max); + ret = prof_lookup(&bt); + } else + ret = (prof_thr_cnt_t *)(uintptr_t)1U; + } + + return (ret); +} + +prof_thr_cnt_t * +prof_cnt_get(const void *ptr) +{ + prof_thr_cnt_t *ret; + arena_chunk_t *chunk; + + assert(ptr != NULL); + + chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); + if (chunk != ptr) { + /* Region. */ + assert(chunk->arena->magic == ARENA_MAGIC); + + ret = arena_prof_cnt_get(ptr); + } else + ret = huge_prof_cnt_get(ptr); + + return (ret); +} + +static void +prof_cnt_set(const void *ptr, prof_thr_cnt_t *cnt) +{ + arena_chunk_t *chunk; + + assert(ptr != NULL); + + chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); + if (chunk != ptr) { + /* Region. */ + assert(chunk->arena->magic == ARENA_MAGIC); + + arena_prof_cnt_set(ptr, cnt); + } else + huge_prof_cnt_set(ptr, cnt); +} + +static inline void +prof_sample_accum_update(size_t size) +{ + + if (opt_lg_prof_sample == 0) { + /* + * Don't bother with sampling logic, since sampling interval is + * 1. + */ + return; + } + + /* Take care to avoid integer overflow. */ + if (size >= prof_sample_threshold - prof_sample_accum) { + prof_sample_accum -= (prof_sample_threshold - size); + /* Compute new prof_sample_threshold. */ + prof_sample_threshold_update(); + while (prof_sample_accum >= prof_sample_threshold) { + prof_sample_accum -= prof_sample_threshold; + prof_sample_threshold_update(); + } + } else + prof_sample_accum += size; +} + +void +prof_malloc(const void *ptr, prof_thr_cnt_t *cnt) +{ + size_t size = isalloc(ptr); + + assert(ptr != NULL); + + prof_cnt_set(ptr, cnt); + prof_sample_accum_update(size); + + if ((uintptr_t)cnt > (uintptr_t)1U) { + cnt->epoch++; + /*********/ + mb_write(); + /*********/ + cnt->cnts.curobjs++; + cnt->cnts.curbytes += size; + cnt->cnts.accumobjs++; + cnt->cnts.accumbytes += size; + /*********/ + mb_write(); + /*********/ + cnt->epoch++; + /*********/ + mb_write(); + /*********/ + } +} + +void +prof_realloc(const void *ptr, prof_thr_cnt_t *cnt, const void *old_ptr, + size_t old_size, prof_thr_cnt_t *old_cnt) +{ + size_t size = isalloc(ptr); + + if (ptr != NULL) { + prof_cnt_set(ptr, cnt); + prof_sample_accum_update(size); + } + + if ((uintptr_t)old_cnt > (uintptr_t)1U) + old_cnt->epoch++; + if ((uintptr_t)cnt > (uintptr_t)1U) + cnt->epoch++; + /*********/ + mb_write(); + /*********/ + if ((uintptr_t)old_cnt > (uintptr_t)1U) { + old_cnt->cnts.curobjs--; + old_cnt->cnts.curbytes -= old_size; + } + if ((uintptr_t)cnt > (uintptr_t)1U) { + cnt->cnts.curobjs++; + cnt->cnts.curbytes += size; + cnt->cnts.accumobjs++; + cnt->cnts.accumbytes += size; + } + /*********/ + mb_write(); + /*********/ + if ((uintptr_t)old_cnt > (uintptr_t)1U) + old_cnt->epoch++; + if ((uintptr_t)cnt > (uintptr_t)1U) + cnt->epoch++; + /*********/ + mb_write(); /* Not strictly necessary. */ +} + +void +prof_free(const void *ptr) +{ + prof_thr_cnt_t *cnt = prof_cnt_get(ptr); + + if ((uintptr_t)cnt > (uintptr_t)1) { + size_t size = isalloc(ptr); + + cnt->epoch++; + /*********/ + mb_write(); + /*********/ + cnt->cnts.curobjs--; + cnt->cnts.curbytes -= size; + /*********/ + mb_write(); + /*********/ + cnt->epoch++; + /*********/ + mb_write(); + /*********/ + } +} + +static bool +prof_flush(bool propagate_err) +{ + bool ret = false; + ssize_t err; + + err = write(prof_dump_fd, prof_dump_buf, prof_dump_buf_end); + if (err == -1) { + if (propagate_err == false) { + malloc_write(": write() failed during heap " + "profile flush\n"); + if (opt_abort) + abort(); + } + ret = true; + } + prof_dump_buf_end = 0; + + return (ret); +} + +static bool +prof_write(const char *s, bool propagate_err) +{ + unsigned i, slen, n; + + i = 0; + slen = strlen(s); + while (i < slen) { + /* Flush the buffer if it is full. */ + if (prof_dump_buf_end == PROF_DUMP_BUF_SIZE) + if (prof_flush(propagate_err) && propagate_err) + return (true); + + if (prof_dump_buf_end + slen <= PROF_DUMP_BUF_SIZE) { + /* Finish writing. */ + n = slen - i; + } else { + /* Write as much of s as will fit. */ + n = PROF_DUMP_BUF_SIZE - prof_dump_buf_end; + } + memcpy(&prof_dump_buf[prof_dump_buf_end], &s[i], n); + prof_dump_buf_end += n; + i += n; + } + + return (false); +} + +static void +prof_ctx_merge(prof_ctx_t *ctx, prof_cnt_t *cnt_all, size_t *leak_nctx) +{ + prof_thr_cnt_t *thr_cnt; + prof_cnt_t tcnt; + + malloc_mutex_lock(&ctx->lock); + + memcpy(&ctx->cnt_dump, &ctx->cnt_merged, sizeof(prof_cnt_t)); + ql_foreach(thr_cnt, &ctx->cnts_ql, link) { + volatile unsigned *epoch = &thr_cnt->epoch; + + while (true) { + unsigned epoch0 = *epoch; + + /* Make sure epoch is even. */ + if (epoch0 & 1U) + continue; + + memcpy(&tcnt, &thr_cnt->cnts, sizeof(prof_cnt_t)); + + /* Terminate if epoch didn't change while reading. */ + if (*epoch == epoch0) + break; + } + + ctx->cnt_dump.curobjs += tcnt.curobjs; + ctx->cnt_dump.curbytes += tcnt.curbytes; + ctx->cnt_dump.accumobjs += tcnt.accumobjs; + ctx->cnt_dump.accumbytes += tcnt.accumbytes; + + if (tcnt.curobjs != 0) + (*leak_nctx)++; + } + + /* Merge into cnt_all. */ + cnt_all->curobjs += ctx->cnt_dump.curobjs; + cnt_all->curbytes += ctx->cnt_dump.curbytes; + cnt_all->accumobjs += ctx->cnt_dump.accumobjs; + cnt_all->accumbytes += ctx->cnt_dump.accumbytes; + + malloc_mutex_unlock(&ctx->lock); +} + +static bool +prof_dump_ctx(prof_ctx_t *ctx, prof_bt_t *bt, bool propagate_err) +{ + char buf[UMAX2S_BUFSIZE]; + unsigned i; + + if (prof_write(umax2s(ctx->cnt_dump.curobjs, 10, buf), propagate_err) + || prof_write(": ", propagate_err) + || prof_write(umax2s(ctx->cnt_dump.curbytes, 10, buf), + propagate_err) + || prof_write(" [", propagate_err) + || prof_write(umax2s(ctx->cnt_dump.accumobjs, 10, buf), + propagate_err) + || prof_write(": ", propagate_err) + || prof_write(umax2s(ctx->cnt_dump.accumbytes, 10, buf), + propagate_err) + || prof_write("] @", propagate_err)) + return (true); + + for (i = 0; i < bt->len; i++) { + if (prof_write(" 0x", propagate_err) + || prof_write(umax2s((uintptr_t)bt->vec[i], 16, buf), + propagate_err)) + return (true); + } + + if (prof_write("\n", propagate_err)) + return (true); + + return (false); +} + +static bool +prof_dump_maps(bool propagate_err) +{ + int mfd; + char buf[UMAX2S_BUFSIZE]; + char *s; + unsigned i, slen; + /* /proc//maps\0 */ + char mpath[6 + UMAX2S_BUFSIZE + + 5 + 1]; + + i = 0; + + s = "/proc/"; + slen = strlen(s); + memcpy(&mpath[i], s, slen); + i += slen; + + s = umax2s(getpid(), 10, buf); + slen = strlen(s); + memcpy(&mpath[i], s, slen); + i += slen; + + s = "/maps"; + slen = strlen(s); + memcpy(&mpath[i], s, slen); + i += slen; + + mpath[i] = '\0'; + + mfd = open(mpath, O_RDONLY); + if (mfd != -1) { + ssize_t nread; + + if (prof_write("\nMAPPED_LIBRARIES:\n", propagate_err) && + propagate_err) + return (true); + nread = 0; + do { + prof_dump_buf_end += nread; + if (prof_dump_buf_end == PROF_DUMP_BUF_SIZE) { + /* Make space in prof_dump_buf before read(). */ + if (prof_flush(propagate_err) && propagate_err) + return (true); + } + nread = read(mfd, &prof_dump_buf[prof_dump_buf_end], + PROF_DUMP_BUF_SIZE - prof_dump_buf_end); + } while (nread > 0); + close(mfd); + } else + return (true); + + return (false); +} + +static bool +prof_dump(const char *filename, bool leakcheck, bool propagate_err) +{ + prof_cnt_t cnt_all; + size_t tabind; + prof_bt_t *bt; + prof_ctx_t *ctx; + char buf[UMAX2S_BUFSIZE]; + size_t leak_nctx; + + prof_enter(); + prof_dump_fd = creat(filename, 0644); + if (prof_dump_fd == -1) { + if (propagate_err == false) { + malloc_write(": creat(\""); + malloc_write(filename); + malloc_write("\", 0644) failed\n"); + if (opt_abort) + abort(); + } + goto ERROR; + } + + /* Merge per thread profile stats, and sum them in cnt_all. */ + memset(&cnt_all, 0, sizeof(prof_cnt_t)); + leak_nctx = 0; + for (tabind = 0; ckh_iter(&bt2ctx, &tabind, NULL, (void **)&ctx) + == false;) { + prof_ctx_merge(ctx, &cnt_all, &leak_nctx); + } + + /* Dump profile header. */ + if (prof_write("heap profile: ", propagate_err) + || prof_write(umax2s(cnt_all.curobjs, 10, buf), propagate_err) + || prof_write(": ", propagate_err) + || prof_write(umax2s(cnt_all.curbytes, 10, buf), propagate_err) + || prof_write(" [", propagate_err) + || prof_write(umax2s(cnt_all.accumobjs, 10, buf), propagate_err) + || prof_write(": ", propagate_err) + || prof_write(umax2s(cnt_all.accumbytes, 10, buf), propagate_err)) + goto ERROR; + + if (opt_lg_prof_sample == 0) { + if (prof_write("] @ heapprofile\n", propagate_err)) + goto ERROR; + } else { + if (prof_write("] @ heap_v2/", propagate_err) + || prof_write(umax2s((uint64_t)1U << opt_lg_prof_sample, 10, + buf), propagate_err) + || prof_write("\n", propagate_err)) + goto ERROR; + } + + /* Dump per ctx profile stats. */ + for (tabind = 0; ckh_iter(&bt2ctx, &tabind, (void **)&bt, (void **)&ctx) + == false;) { + if (prof_dump_ctx(ctx, bt, propagate_err)) + goto ERROR; + } + + /* Dump /proc//maps if possible. */ + if (prof_dump_maps(propagate_err)) + goto ERROR; + + if (prof_flush(propagate_err)) + goto ERROR; + close(prof_dump_fd); + prof_leave(); + + if (leakcheck && cnt_all.curbytes != 0) { + malloc_write(": Leak summary: "); + malloc_write(umax2s(cnt_all.curbytes, 10, buf)); + malloc_write((cnt_all.curbytes != 1) ? " bytes, " : " byte, "); + malloc_write(umax2s(cnt_all.curobjs, 10, buf)); + malloc_write((cnt_all.curobjs != 1) ? " objects, " : + " object, "); + malloc_write(umax2s(leak_nctx, 10, buf)); + malloc_write((leak_nctx != 1) ? " contexts\n" : " context\n"); + malloc_write(": Run pprof on \""); + malloc_write(filename); + malloc_write("\" for leak detail\n"); + } + + return (false); +ERROR: + prof_leave(); + return (true); +} + +#define DUMP_FILENAME_BUFSIZE (PATH_MAX+ UMAX2S_BUFSIZE \ + + 1 \ + + UMAX2S_BUFSIZE \ + + 2 \ + + UMAX2S_BUFSIZE \ + + 5 + 1) +static void +prof_dump_filename(char *filename, char v, int64_t vseq) +{ + char buf[UMAX2S_BUFSIZE]; + char *s; + unsigned i, slen; + + /* + * Construct a filename of the form: + * + * ...v.heap\0 + * or + * jeprof...v.heap\0 + */ + + i = 0; + + /* + * Use JEMALLOC_PROF_PREFIX if it's set, and if it is short enough to + * avoid overflowing DUMP_FILENAME_BUFSIZE. The result may exceed + * PATH_MAX, but creat(2) will catch that problem. + */ + if ((s = getenv("JEMALLOC_PROF_PREFIX")) != NULL + && strlen(s) + (DUMP_FILENAME_BUFSIZE - PATH_MAX) <= PATH_MAX) { + slen = strlen(s); + memcpy(&filename[i], s, slen); + i += slen; + + s = "."; + } else + s = "jeprof."; + slen = strlen(s); + memcpy(&filename[i], s, slen); + i += slen; + + s = umax2s(getpid(), 10, buf); + slen = strlen(s); + memcpy(&filename[i], s, slen); + i += slen; + + s = "."; + slen = strlen(s); + memcpy(&filename[i], s, slen); + i += slen; + + s = umax2s(prof_dump_seq, 10, buf); + prof_dump_seq++; + slen = strlen(s); + memcpy(&filename[i], s, slen); + i += slen; + + s = "."; + slen = strlen(s); + memcpy(&filename[i], s, slen); + i += slen; + + filename[i] = v; + i++; + + if (vseq != 0xffffffffffffffffLLU) { + s = umax2s(vseq, 10, buf); + slen = strlen(s); + memcpy(&filename[i], s, slen); + i += slen; + } + + s = ".heap"; + slen = strlen(s); + memcpy(&filename[i], s, slen); + i += slen; + + filename[i] = '\0'; +} + +static void +prof_fdump(void) +{ + char filename[DUMP_FILENAME_BUFSIZE]; + + if (prof_booted == false) + return; + + malloc_mutex_lock(&prof_dump_seq_mtx); + prof_dump_filename(filename, 'f', 0xffffffffffffffffLLU); + malloc_mutex_unlock(&prof_dump_seq_mtx); + prof_dump(filename, opt_prof_leak, false); +} + +void +prof_idump(void) +{ + char filename[DUMP_FILENAME_BUFSIZE]; + + if (prof_booted == false) + return; + malloc_mutex_lock(&enq_mtx); + if (enq) { + enq_idump = true; + malloc_mutex_unlock(&enq_mtx); + return; + } + malloc_mutex_unlock(&enq_mtx); + + malloc_mutex_lock(&prof_dump_seq_mtx); + prof_dump_filename(filename, 'i', prof_dump_iseq); + prof_dump_iseq++; + malloc_mutex_unlock(&prof_dump_seq_mtx); + prof_dump(filename, false, false); +} + +bool +prof_mdump(const char *filename) +{ + char filename_buf[DUMP_FILENAME_BUFSIZE]; + + if (opt_prof == false || prof_booted == false) + return (true); + + if (filename == NULL) { + /* No filename specified, so automatically generate one. */ + malloc_mutex_lock(&prof_dump_seq_mtx); + prof_dump_filename(filename_buf, 'm', prof_dump_mseq); + prof_dump_mseq++; + malloc_mutex_unlock(&prof_dump_seq_mtx); + filename = filename_buf; + } + return (prof_dump(filename, false, true)); +} + +void +prof_udump(void) +{ + char filename[DUMP_FILENAME_BUFSIZE]; + + if (prof_booted == false) + return; + malloc_mutex_lock(&enq_mtx); + if (enq) { + enq_udump = true; + malloc_mutex_unlock(&enq_mtx); + return; + } + malloc_mutex_unlock(&enq_mtx); + + malloc_mutex_lock(&prof_dump_seq_mtx); + prof_dump_filename(filename, 'u', prof_dump_useq); + prof_dump_useq++; + malloc_mutex_unlock(&prof_dump_seq_mtx); + prof_dump(filename, false, false); +} + +static void +prof_bt_hash(const void *key, unsigned minbits, size_t *hash1, size_t *hash2) +{ + size_t ret1, ret2; + uint64_t h; + prof_bt_t *bt = (prof_bt_t *)key; + + assert(minbits <= 32 || (SIZEOF_PTR == 8 && minbits <= 64)); + assert(hash1 != NULL); + assert(hash2 != NULL); + + h = hash(bt->vec, bt->len * sizeof(void *), 0x94122f335b332aeaLLU); + if (minbits <= 32) { + /* + * Avoid doing multiple hashes, since a single hash provides + * enough bits. + */ + ret1 = h & ZU(0xffffffffU); + ret2 = h >> 32; + } else { + ret1 = h; + ret2 = hash(bt->vec, bt->len * sizeof(void *), + 0x8432a476666bbc13U); + } + + *hash1 = ret1; + *hash2 = ret2; +} + +static bool +prof_bt_keycomp(const void *k1, const void *k2) +{ + const prof_bt_t *bt1 = (prof_bt_t *)k1; + const prof_bt_t *bt2 = (prof_bt_t *)k2; + + if (bt1->len != bt2->len) + return (false); + return (memcmp(bt1->vec, bt2->vec, bt1->len * sizeof(void *)) == 0); +} + +static void +bt2cnt_thread_cleanup(void *arg) +{ + ckh_t *bt2cnt; + + bt2cnt = bt2cnt_tls; + if (bt2cnt != NULL) { + ql_head(prof_thr_cnt_t) cnts_ql; + size_t tabind; + prof_thr_cnt_t *cnt; + + /* Iteratively merge cnt's into the global stats. */ + ql_new(&cnts_ql); + tabind = 0; + while (ckh_iter(bt2cnt, &tabind, NULL, (void **)&cnt) == + false) { + prof_ctx_t *ctx = cnt->ctx; + /* Merge stats and detach from ctx. */ + malloc_mutex_lock(&ctx->lock); + ctx->cnt_merged.curobjs += cnt->cnts.curobjs; + ctx->cnt_merged.curbytes += cnt->cnts.curbytes; + ctx->cnt_merged.accumobjs += cnt->cnts.accumobjs; + ctx->cnt_merged.accumbytes += cnt->cnts.accumbytes; + ql_remove(&ctx->cnts_ql, cnt, link); + malloc_mutex_unlock(&ctx->lock); + + /* + * Stash cnt for deletion after finishing with + * ckh_iter(). + */ + ql_tail_insert(&cnts_ql, cnt, link); + } + + /* + * Delete the hash table now that cnts_ql has a list of all + * cnt's. + */ + ckh_delete(bt2cnt); + idalloc(bt2cnt); + bt2cnt_tls = NULL; + + /* Delete cnt's. */ + while ((cnt = ql_last(&cnts_ql, link)) != NULL) { + ql_remove(&cnts_ql, cnt, link); + idalloc(cnt); + } + } +} + +void +prof_boot0(void) +{ + + /* + * opt_prof and prof_promote must be in their final state before any + * arenas are initialized, so this function must be executed early. + */ + + if (opt_prof_leak && opt_prof == false) { + /* + * Enable opt_prof, but in such a way that profiles are never + * automatically dumped. + */ + opt_prof = true; + opt_prof_udump = false; + prof_interval = 0; + } else if (opt_prof) { + if (opt_lg_prof_interval >= 0) { + prof_interval = (((uint64_t)1U) << + opt_lg_prof_interval); + } else + prof_interval = 0; + } + + prof_promote = (opt_prof && opt_lg_prof_sample > PAGE_SHIFT); +} + +bool +prof_boot1(void) +{ + + if (opt_prof) { + if (ckh_new(&bt2ctx, PROF_CKH_MINITEMS, prof_bt_hash, + prof_bt_keycomp)) + return (true); + if (malloc_mutex_init(&bt2ctx_mtx)) + return (true); + if (pthread_key_create(&bt2cnt_tsd, bt2cnt_thread_cleanup) + != 0) { + malloc_write( + ": Error in pthread_key_create()\n"); + abort(); + } + + prof_bt_max = (1U << opt_lg_prof_bt_max); + if (malloc_mutex_init(&prof_dump_seq_mtx)) + return (true); + + if (malloc_mutex_init(&enq_mtx)) + return (true); + enq = false; + enq_idump = false; + enq_udump = false; + + if (atexit(prof_fdump) != 0) { + malloc_write(": Error in atexit()\n"); + if (opt_abort) + abort(); + } + } + +#ifdef JEMALLOC_PROF_LIBGCC + /* + * Cause the backtracing machinery to allocate its internal state + * before enabling profiling. + */ + _Unwind_Backtrace(prof_unwind_init_callback, NULL); +#endif + + prof_booted = true; + + return (false); +} + +/******************************************************************************/ +#endif /* JEMALLOC_PROF */ diff --git a/dep/jemalloc/stats.c b/dep/jemalloc/stats.c new file mode 100644 index 00000000000..9dc75293731 --- /dev/null +++ b/dep/jemalloc/stats.c @@ -0,0 +1,717 @@ +#define JEMALLOC_STATS_C_ +#include "jemalloc/internal/jemalloc_internal.h" + +#define CTL_GET(n, v, t) do { \ + size_t sz = sizeof(t); \ + xmallctl(n, v, &sz, NULL, 0); \ +} while (0) + +#define CTL_I_GET(n, v, t) do { \ + size_t mib[6]; \ + size_t miblen = sizeof(mib) / sizeof(size_t); \ + size_t sz = sizeof(t); \ + xmallctlnametomib(n, mib, &miblen); \ + mib[2] = i; \ + xmallctlbymib(mib, miblen, v, &sz, NULL, 0); \ +} while (0) + +#define CTL_J_GET(n, v, t) do { \ + size_t mib[6]; \ + size_t miblen = sizeof(mib) / sizeof(size_t); \ + size_t sz = sizeof(t); \ + xmallctlnametomib(n, mib, &miblen); \ + mib[2] = j; \ + xmallctlbymib(mib, miblen, v, &sz, NULL, 0); \ +} while (0) + +#define CTL_IJ_GET(n, v, t) do { \ + size_t mib[6]; \ + size_t miblen = sizeof(mib) / sizeof(size_t); \ + size_t sz = sizeof(t); \ + xmallctlnametomib(n, mib, &miblen); \ + mib[2] = i; \ + mib[4] = j; \ + xmallctlbymib(mib, miblen, v, &sz, NULL, 0); \ +} while (0) + +/******************************************************************************/ +/* Data. */ + +bool opt_stats_print = false; + +/******************************************************************************/ +/* Function prototypes for non-inline static functions. */ + +#ifdef JEMALLOC_STATS +static void malloc_vcprintf(void (*write_cb)(void *, const char *), + void *cbopaque, const char *format, va_list ap); +static void stats_arena_bins_print(void (*write_cb)(void *, const char *), + void *cbopaque, unsigned i); +static void stats_arena_lruns_print(void (*write_cb)(void *, const char *), + void *cbopaque, unsigned i); +static void stats_arena_print(void (*write_cb)(void *, const char *), + void *cbopaque, unsigned i); +#endif + +/******************************************************************************/ + +/* + * We don't want to depend on vsnprintf() for production builds, since that can + * cause unnecessary bloat for static binaries. umax2s() provides minimal + * integer printing functionality, so that malloc_printf() use can be limited to + * JEMALLOC_STATS code. + */ +char * +umax2s(uintmax_t x, unsigned base, char *s) +{ + unsigned i; + + i = UMAX2S_BUFSIZE - 1; + s[i] = '\0'; + switch (base) { + case 10: + do { + i--; + s[i] = "0123456789"[x % 10]; + x /= 10; + } while (x > 0); + break; + case 16: + do { + i--; + s[i] = "0123456789abcdef"[x & 0xf]; + x >>= 4; + } while (x > 0); + break; + default: + do { + i--; + s[i] = "0123456789abcdefghijklmnopqrstuvwxyz"[x % base]; + x /= base; + } while (x > 0); + } + + return (&s[i]); +} + +#ifdef JEMALLOC_STATS +static void +malloc_vcprintf(void (*write_cb)(void *, const char *), void *cbopaque, + const char *format, va_list ap) +{ + char buf[4096]; + + if (write_cb == NULL) { + /* + * The caller did not provide an alternate write_cb callback + * function, so use the default one. malloc_write() is an + * inline function, so use malloc_message() directly here. + */ + write_cb = JEMALLOC_P(malloc_message); + cbopaque = NULL; + } + + vsnprintf(buf, sizeof(buf), format, ap); + write_cb(cbopaque, buf); +} + +/* + * Print to a callback function in such a way as to (hopefully) avoid memory + * allocation. + */ +JEMALLOC_ATTR(format(printf, 3, 4)) +void +malloc_cprintf(void (*write_cb)(void *, const char *), void *cbopaque, + const char *format, ...) +{ + va_list ap; + + va_start(ap, format); + malloc_vcprintf(write_cb, cbopaque, format, ap); + va_end(ap); +} + +/* + * Print to stderr in such a way as to (hopefully) avoid memory allocation. + */ +JEMALLOC_ATTR(format(printf, 1, 2)) +void +malloc_printf(const char *format, ...) +{ + va_list ap; + + va_start(ap, format); + malloc_vcprintf(NULL, NULL, format, ap); + va_end(ap); +} +#endif + +#ifdef JEMALLOC_STATS +static void +stats_arena_bins_print(void (*write_cb)(void *, const char *), void *cbopaque, + unsigned i) +{ + size_t pagesize; + bool config_tcache; + unsigned nbins, j, gap_start; + + CTL_GET("arenas.pagesize", &pagesize, size_t); + + CTL_GET("config.tcache", &config_tcache, bool); + if (config_tcache) { + malloc_cprintf(write_cb, cbopaque, + "bins: bin size regs pgs allocated nmalloc" + " ndalloc nrequests nfills nflushes" + " newruns reruns maxruns curruns\n"); + } else { + malloc_cprintf(write_cb, cbopaque, + "bins: bin size regs pgs allocated nmalloc" + " ndalloc newruns reruns maxruns" + " curruns\n"); + } + CTL_GET("arenas.nbins", &nbins, unsigned); + for (j = 0, gap_start = UINT_MAX; j < nbins; j++) { + uint64_t nruns; + + CTL_IJ_GET("stats.arenas.0.bins.0.nruns", &nruns, uint64_t); + if (nruns == 0) { + if (gap_start == UINT_MAX) + gap_start = j; + } else { + unsigned ntbins_, nqbins, ncbins, nsbins; + size_t reg_size, run_size, allocated; + uint32_t nregs; + uint64_t nmalloc, ndalloc, nrequests, nfills, nflushes; + uint64_t reruns; + size_t highruns, curruns; + + if (gap_start != UINT_MAX) { + if (j > gap_start + 1) { + /* Gap of more than one size class. */ + malloc_cprintf(write_cb, cbopaque, + "[%u..%u]\n", gap_start, + j - 1); + } else { + /* Gap of one size class. */ + malloc_cprintf(write_cb, cbopaque, + "[%u]\n", gap_start); + } + gap_start = UINT_MAX; + } + CTL_GET("arenas.ntbins", &ntbins_, unsigned); + CTL_GET("arenas.nqbins", &nqbins, unsigned); + CTL_GET("arenas.ncbins", &ncbins, unsigned); + CTL_GET("arenas.nsbins", &nsbins, unsigned); + CTL_J_GET("arenas.bin.0.size", ®_size, size_t); + CTL_J_GET("arenas.bin.0.nregs", &nregs, uint32_t); + CTL_J_GET("arenas.bin.0.run_size", &run_size, size_t); + CTL_IJ_GET("stats.arenas.0.bins.0.allocated", + &allocated, size_t); + CTL_IJ_GET("stats.arenas.0.bins.0.nmalloc", + &nmalloc, uint64_t); + CTL_IJ_GET("stats.arenas.0.bins.0.ndalloc", + &ndalloc, uint64_t); + if (config_tcache) { + CTL_IJ_GET("stats.arenas.0.bins.0.nrequests", + &nrequests, uint64_t); + CTL_IJ_GET("stats.arenas.0.bins.0.nfills", + &nfills, uint64_t); + CTL_IJ_GET("stats.arenas.0.bins.0.nflushes", + &nflushes, uint64_t); + } + CTL_IJ_GET("stats.arenas.0.bins.0.nreruns", &reruns, + uint64_t); + CTL_IJ_GET("stats.arenas.0.bins.0.highruns", &highruns, + size_t); + CTL_IJ_GET("stats.arenas.0.bins.0.curruns", &curruns, + size_t); + if (config_tcache) { + malloc_cprintf(write_cb, cbopaque, + "%13u %1s %5zu %4u %3zu %12zu %12"PRIu64 + " %12"PRIu64" %12"PRIu64" %12"PRIu64 + " %12"PRIu64" %12"PRIu64" %12"PRIu64 + " %12zu %12zu\n", + j, + j < ntbins_ ? "T" : j < ntbins_ + nqbins ? + "Q" : j < ntbins_ + nqbins + ncbins ? "C" : + "S", + reg_size, nregs, run_size / pagesize, + allocated, nmalloc, ndalloc, nrequests, + nfills, nflushes, nruns, reruns, highruns, + curruns); + } else { + malloc_cprintf(write_cb, cbopaque, + "%13u %1s %5zu %4u %3zu %12zu %12"PRIu64 + " %12"PRIu64" %12"PRIu64" %12"PRIu64 + " %12zu %12zu\n", + j, + j < ntbins_ ? "T" : j < ntbins_ + nqbins ? + "Q" : j < ntbins_ + nqbins + ncbins ? "C" : + "S", + reg_size, nregs, run_size / pagesize, + allocated, nmalloc, ndalloc, nruns, reruns, + highruns, curruns); + } + } + } + if (gap_start != UINT_MAX) { + if (j > gap_start + 1) { + /* Gap of more than one size class. */ + malloc_cprintf(write_cb, cbopaque, "[%u..%u]\n", + gap_start, j - 1); + } else { + /* Gap of one size class. */ + malloc_cprintf(write_cb, cbopaque, "[%u]\n", gap_start); + } + } +} + +static void +stats_arena_lruns_print(void (*write_cb)(void *, const char *), void *cbopaque, + unsigned i) +{ + size_t pagesize, nlruns, j; + ssize_t gap_start; + + CTL_GET("arenas.pagesize", &pagesize, size_t); + + malloc_cprintf(write_cb, cbopaque, + "large: size pages nmalloc ndalloc nrequests" + " maxruns curruns\n"); + CTL_GET("arenas.nlruns", &nlruns, size_t); + for (j = 0, gap_start = -1; j < nlruns; j++) { + uint64_t nmalloc, ndalloc, nrequests; + size_t run_size, highruns, curruns; + + CTL_IJ_GET("stats.arenas.0.lruns.0.nmalloc", &nmalloc, + uint64_t); + CTL_IJ_GET("stats.arenas.0.lruns.0.ndalloc", &ndalloc, + uint64_t); + CTL_IJ_GET("stats.arenas.0.lruns.0.nrequests", &nrequests, + uint64_t); + if (nrequests == 0) { + if (gap_start == -1) + gap_start = j; + } else { + CTL_J_GET("arenas.lrun.0.size", &run_size, size_t); + CTL_IJ_GET("stats.arenas.0.lruns.0.highruns", &highruns, + size_t); + CTL_IJ_GET("stats.arenas.0.lruns.0.curruns", &curruns, + size_t); + if (gap_start != -1) { + malloc_cprintf(write_cb, cbopaque, "[%zu]\n", + j - gap_start); + gap_start = -1; + } + malloc_cprintf(write_cb, cbopaque, + "%13zu %5zu %12"PRIu64" %12"PRIu64" %12"PRIu64 + " %12zu %12zu\n", + run_size, run_size / pagesize, nmalloc, ndalloc, + nrequests, highruns, curruns); + } + } + if (gap_start != -1) + malloc_cprintf(write_cb, cbopaque, "[%zu]\n", j - gap_start); +} + +static void +stats_arena_print(void (*write_cb)(void *, const char *), void *cbopaque, + unsigned i) +{ + size_t pagesize, pactive, pdirty, mapped; + uint64_t npurge, nmadvise, purged; + size_t small_allocated; + uint64_t small_nmalloc, small_ndalloc, small_nrequests; + size_t large_allocated; + uint64_t large_nmalloc, large_ndalloc, large_nrequests; + + CTL_GET("arenas.pagesize", &pagesize, size_t); + + CTL_I_GET("stats.arenas.0.pactive", &pactive, size_t); + CTL_I_GET("stats.arenas.0.pdirty", &pdirty, size_t); + CTL_I_GET("stats.arenas.0.npurge", &npurge, uint64_t); + CTL_I_GET("stats.arenas.0.nmadvise", &nmadvise, uint64_t); + CTL_I_GET("stats.arenas.0.purged", &purged, uint64_t); + malloc_cprintf(write_cb, cbopaque, + "dirty pages: %zu:%zu active:dirty, %"PRIu64" sweep%s," + " %"PRIu64" madvise%s, %"PRIu64" purged\n", + pactive, pdirty, npurge, npurge == 1 ? "" : "s", + nmadvise, nmadvise == 1 ? "" : "s", purged); + + malloc_cprintf(write_cb, cbopaque, + " allocated nmalloc ndalloc nrequests\n"); + CTL_I_GET("stats.arenas.0.small.allocated", &small_allocated, size_t); + CTL_I_GET("stats.arenas.0.small.nmalloc", &small_nmalloc, uint64_t); + CTL_I_GET("stats.arenas.0.small.ndalloc", &small_ndalloc, uint64_t); + CTL_I_GET("stats.arenas.0.small.nrequests", &small_nrequests, uint64_t); + malloc_cprintf(write_cb, cbopaque, + "small: %12zu %12"PRIu64" %12"PRIu64" %12"PRIu64"\n", + small_allocated, small_nmalloc, small_ndalloc, small_nrequests); + CTL_I_GET("stats.arenas.0.large.allocated", &large_allocated, size_t); + CTL_I_GET("stats.arenas.0.large.nmalloc", &large_nmalloc, uint64_t); + CTL_I_GET("stats.arenas.0.large.ndalloc", &large_ndalloc, uint64_t); + CTL_I_GET("stats.arenas.0.large.nrequests", &large_nrequests, uint64_t); + malloc_cprintf(write_cb, cbopaque, + "large: %12zu %12"PRIu64" %12"PRIu64" %12"PRIu64"\n", + large_allocated, large_nmalloc, large_ndalloc, large_nrequests); + malloc_cprintf(write_cb, cbopaque, + "total: %12zu %12"PRIu64" %12"PRIu64" %12"PRIu64"\n", + small_allocated + large_allocated, + small_nmalloc + large_nmalloc, + small_ndalloc + large_ndalloc, + small_nrequests + large_nrequests); + malloc_cprintf(write_cb, cbopaque, "active: %12zu\n", + pactive * pagesize ); + CTL_I_GET("stats.arenas.0.mapped", &mapped, size_t); + malloc_cprintf(write_cb, cbopaque, "mapped: %12zu\n", mapped); + + stats_arena_bins_print(write_cb, cbopaque, i); + stats_arena_lruns_print(write_cb, cbopaque, i); +} +#endif + +void +stats_print(void (*write_cb)(void *, const char *), void *cbopaque, + const char *opts) +{ + uint64_t epoch; + size_t u64sz; + char s[UMAX2S_BUFSIZE]; + bool general = true; + bool merged = true; + bool unmerged = true; + bool bins = true; + bool large = true; + + /* Refresh stats, in case mallctl() was called by the application. */ + epoch = 1; + u64sz = sizeof(uint64_t); + xmallctl("epoch", &epoch, &u64sz, &epoch, sizeof(uint64_t)); + + if (write_cb == NULL) { + /* + * The caller did not provide an alternate write_cb callback + * function, so use the default one. malloc_write() is an + * inline function, so use malloc_message() directly here. + */ + write_cb = JEMALLOC_P(malloc_message); + cbopaque = NULL; + } + + if (opts != NULL) { + unsigned i; + + for (i = 0; opts[i] != '\0'; i++) { + switch (opts[i]) { + case 'g': + general = false; + break; + case 'm': + merged = false; + break; + case 'a': + unmerged = false; + break; + case 'b': + bins = false; + break; + case 'l': + large = false; + break; + default:; + } + } + } + + write_cb(cbopaque, "___ Begin jemalloc statistics ___\n"); + if (general) { + int err; + const char *cpv; + bool bv; + unsigned uv; + ssize_t ssv; + size_t sv, bsz, ssz; + + bsz = sizeof(bool); + ssz = sizeof(size_t); + + CTL_GET("version", &cpv, const char *); + write_cb(cbopaque, "Version: "); + write_cb(cbopaque, cpv); + write_cb(cbopaque, "\n"); + CTL_GET("config.debug", &bv, bool); + write_cb(cbopaque, "Assertions "); + write_cb(cbopaque, bv ? "enabled" : "disabled"); + write_cb(cbopaque, "\n"); + + write_cb(cbopaque, "Boolean JEMALLOC_OPTIONS: "); + if ((err = JEMALLOC_P(mallctl)("opt.abort", &bv, &bsz, NULL, 0)) + == 0) + write_cb(cbopaque, bv ? "A" : "a"); + if ((err = JEMALLOC_P(mallctl)("prof.active", &bv, &bsz, + NULL, 0)) == 0) + write_cb(cbopaque, bv ? "E" : "e"); + if ((err = JEMALLOC_P(mallctl)("opt.prof", &bv, &bsz, NULL, 0)) + == 0) + write_cb(cbopaque, bv ? "F" : "f"); + if ((err = JEMALLOC_P(mallctl)("opt.tcache", &bv, &bsz, NULL, + 0)) == 0) + write_cb(cbopaque, bv ? "H" : "h"); + if ((err = JEMALLOC_P(mallctl)("opt.junk", &bv, &bsz, NULL, 0)) + == 0) + write_cb(cbopaque, bv ? "J" : "j"); + if ((err = JEMALLOC_P(mallctl)("opt.prof_leak", &bv, &bsz, NULL, + 0)) == 0) + write_cb(cbopaque, bv ? "L" : "l"); + if ((err = JEMALLOC_P(mallctl)("opt.overcommit", &bv, &bsz, + NULL, 0)) == 0) + write_cb(cbopaque, bv ? "O" : "o"); + if ((err = JEMALLOC_P(mallctl)("opt.stats_print", &bv, &bsz, + NULL, 0)) == 0) + write_cb(cbopaque, bv ? "P" : "p"); + if ((err = JEMALLOC_P(mallctl)("opt.prof_udump", &bv, &bsz, + NULL, 0)) == 0) + write_cb(cbopaque, bv ? "U" : "u"); + if ((err = JEMALLOC_P(mallctl)("opt.sysv", &bv, &bsz, NULL, 0)) + == 0) + write_cb(cbopaque, bv ? "V" : "v"); + if ((err = JEMALLOC_P(mallctl)("opt.xmalloc", &bv, &bsz, NULL, + 0)) == 0) + write_cb(cbopaque, bv ? "X" : "x"); + if ((err = JEMALLOC_P(mallctl)("opt.zero", &bv, &bsz, NULL, 0)) + == 0) + write_cb(cbopaque, bv ? "Z" : "z"); + write_cb(cbopaque, "\n"); + + write_cb(cbopaque, "CPUs: "); + write_cb(cbopaque, umax2s(ncpus, 10, s)); + write_cb(cbopaque, "\n"); + + CTL_GET("arenas.narenas", &uv, unsigned); + write_cb(cbopaque, "Max arenas: "); + write_cb(cbopaque, umax2s(uv, 10, s)); + write_cb(cbopaque, "\n"); + + write_cb(cbopaque, "Pointer size: "); + write_cb(cbopaque, umax2s(sizeof(void *), 10, s)); + write_cb(cbopaque, "\n"); + + CTL_GET("arenas.quantum", &sv, size_t); + write_cb(cbopaque, "Quantum size: "); + write_cb(cbopaque, umax2s(sv, 10, s)); + write_cb(cbopaque, "\n"); + + CTL_GET("arenas.cacheline", &sv, size_t); + write_cb(cbopaque, "Cacheline size (assumed): "); + write_cb(cbopaque, umax2s(sv, 10, s)); + write_cb(cbopaque, "\n"); + + CTL_GET("arenas.subpage", &sv, size_t); + write_cb(cbopaque, "Subpage spacing: "); + write_cb(cbopaque, umax2s(sv, 10, s)); + write_cb(cbopaque, "\n"); + + if ((err = JEMALLOC_P(mallctl)("arenas.tspace_min", &sv, &ssz, + NULL, 0)) == 0) { + write_cb(cbopaque, "Tiny 2^n-spaced sizes: ["); + write_cb(cbopaque, umax2s(sv, 10, s)); + write_cb(cbopaque, ".."); + + CTL_GET("arenas.tspace_max", &sv, size_t); + write_cb(cbopaque, umax2s(sv, 10, s)); + write_cb(cbopaque, "]\n"); + } + + CTL_GET("arenas.qspace_min", &sv, size_t); + write_cb(cbopaque, "Quantum-spaced sizes: ["); + write_cb(cbopaque, umax2s(sv, 10, s)); + write_cb(cbopaque, ".."); + CTL_GET("arenas.qspace_max", &sv, size_t); + write_cb(cbopaque, umax2s(sv, 10, s)); + write_cb(cbopaque, "]\n"); + + CTL_GET("arenas.cspace_min", &sv, size_t); + write_cb(cbopaque, "Cacheline-spaced sizes: ["); + write_cb(cbopaque, umax2s(sv, 10, s)); + write_cb(cbopaque, ".."); + CTL_GET("arenas.cspace_max", &sv, size_t); + write_cb(cbopaque, umax2s(sv, 10, s)); + write_cb(cbopaque, "]\n"); + + CTL_GET("arenas.sspace_min", &sv, size_t); + write_cb(cbopaque, "Subpage-spaced sizes: ["); + write_cb(cbopaque, umax2s(sv, 10, s)); + write_cb(cbopaque, ".."); + CTL_GET("arenas.sspace_max", &sv, size_t); + write_cb(cbopaque, umax2s(sv, 10, s)); + write_cb(cbopaque, "]\n"); + + CTL_GET("opt.lg_dirty_mult", &ssv, ssize_t); + if (ssv >= 0) { + write_cb(cbopaque, + "Min active:dirty page ratio per arena: "); + write_cb(cbopaque, umax2s((1U << ssv), 10, s)); + write_cb(cbopaque, ":1\n"); + } else { + write_cb(cbopaque, + "Min active:dirty page ratio per arena: N/A\n"); + } + if ((err = JEMALLOC_P(mallctl)("arenas.tcache_max", &sv, + &ssz, NULL, 0)) == 0) { + write_cb(cbopaque, + "Maximum thread-cached size class: "); + write_cb(cbopaque, umax2s(sv, 10, s)); + write_cb(cbopaque, "\n"); + } + if ((err = JEMALLOC_P(mallctl)("opt.lg_tcache_gc_sweep", &ssv, + &ssz, NULL, 0)) == 0) { + size_t tcache_gc_sweep = (1U << ssv); + bool tcache_enabled; + CTL_GET("opt.tcache", &tcache_enabled, bool); + write_cb(cbopaque, "Thread cache GC sweep interval: "); + write_cb(cbopaque, tcache_enabled && ssv >= 0 ? + umax2s(tcache_gc_sweep, 10, s) : "N/A"); + write_cb(cbopaque, "\n"); + } + if ((err = JEMALLOC_P(mallctl)("opt.prof", &bv, &bsz, NULL, 0)) + == 0 && bv) { + CTL_GET("opt.lg_prof_bt_max", &sv, size_t); + write_cb(cbopaque, "Maximum profile backtrace depth: "); + write_cb(cbopaque, umax2s((1U << sv), 10, s)); + write_cb(cbopaque, "\n"); + + CTL_GET("opt.lg_prof_sample", &sv, size_t); + write_cb(cbopaque, "Average profile sample interval: "); + write_cb(cbopaque, umax2s((1U << sv), 10, s)); + write_cb(cbopaque, " (2^"); + write_cb(cbopaque, umax2s(sv, 10, s)); + write_cb(cbopaque, ")\n"); + + CTL_GET("opt.lg_prof_interval", &ssv, ssize_t); + write_cb(cbopaque, "Average profile dump interval: "); + if (ssv >= 0) { + write_cb(cbopaque, umax2s((1U << ssv), 10, s)); + write_cb(cbopaque, " (2^"); + write_cb(cbopaque, umax2s(ssv, 10, s)); + write_cb(cbopaque, ")\n"); + } else + write_cb(cbopaque, "N/A\n"); + } + CTL_GET("arenas.chunksize", &sv, size_t); + write_cb(cbopaque, "Chunk size: "); + write_cb(cbopaque, umax2s(sv, 10, s)); + CTL_GET("opt.lg_chunk", &sv, size_t); + write_cb(cbopaque, " (2^"); + write_cb(cbopaque, umax2s(sv, 10, s)); + write_cb(cbopaque, ")\n"); + } + +#ifdef JEMALLOC_STATS + { + int err; + size_t ssz; + size_t allocated, active, mapped; + size_t chunks_current, chunks_high, swap_avail; + uint64_t chunks_total; + size_t huge_allocated; + uint64_t huge_nmalloc, huge_ndalloc; + + ssz = sizeof(size_t); + + CTL_GET("stats.allocated", &allocated, size_t); + CTL_GET("stats.active", &active, size_t); + CTL_GET("stats.mapped", &mapped, size_t); + malloc_cprintf(write_cb, cbopaque, + "Allocated: %zu, active: %zu, mapped: %zu\n", allocated, + active, mapped); + + /* Print chunk stats. */ + CTL_GET("stats.chunks.total", &chunks_total, uint64_t); + CTL_GET("stats.chunks.high", &chunks_high, size_t); + CTL_GET("stats.chunks.current", &chunks_current, size_t); + if ((err = JEMALLOC_P(mallctl)("swap.avail", &swap_avail, &ssz, + NULL, 0)) == 0) { + size_t lg_chunk; + + malloc_cprintf(write_cb, cbopaque, "chunks: nchunks " + "highchunks curchunks swap_avail\n"); + CTL_GET("opt.lg_chunk", &lg_chunk, size_t); + malloc_cprintf(write_cb, cbopaque, + " %13"PRIu64"%13zu%13zu%13zu\n", + chunks_total, chunks_high, chunks_current, + swap_avail << lg_chunk); + } else { + malloc_cprintf(write_cb, cbopaque, "chunks: nchunks " + "highchunks curchunks\n"); + malloc_cprintf(write_cb, cbopaque, + " %13"PRIu64"%13zu%13zu\n", + chunks_total, chunks_high, chunks_current); + } + + /* Print huge stats. */ + CTL_GET("stats.huge.nmalloc", &huge_nmalloc, uint64_t); + CTL_GET("stats.huge.ndalloc", &huge_ndalloc, uint64_t); + CTL_GET("stats.huge.allocated", &huge_allocated, size_t); + malloc_cprintf(write_cb, cbopaque, + "huge: nmalloc ndalloc allocated\n"); + malloc_cprintf(write_cb, cbopaque, + " %12"PRIu64" %12"PRIu64" %12zu\n", + huge_nmalloc, huge_ndalloc, huge_allocated); + + if (merged) { + unsigned narenas; + + CTL_GET("arenas.narenas", &narenas, unsigned); + { + bool initialized[narenas]; + size_t isz; + unsigned i, ninitialized; + + isz = sizeof(initialized); + xmallctl("arenas.initialized", initialized, + &isz, NULL, 0); + for (i = ninitialized = 0; i < narenas; i++) { + if (initialized[i]) + ninitialized++; + } + + if (ninitialized > 1) { + /* Print merged arena stats. */ + malloc_cprintf(write_cb, cbopaque, + "\nMerged arenas stats:\n"); + stats_arena_print(write_cb, cbopaque, + narenas); + } + } + } + + if (unmerged) { + unsigned narenas; + + /* Print stats for each arena. */ + + CTL_GET("arenas.narenas", &narenas, unsigned); + { + bool initialized[narenas]; + size_t isz; + unsigned i; + + isz = sizeof(initialized); + xmallctl("arenas.initialized", initialized, + &isz, NULL, 0); + + for (i = 0; i < narenas; i++) { + if (initialized[i]) { + malloc_cprintf(write_cb, + cbopaque, + "\narenas[%u]:\n", i); + stats_arena_print(write_cb, + cbopaque, i); + } + } + } + } + } +#endif /* #ifdef JEMALLOC_STATS */ + write_cb(cbopaque, "--- End jemalloc statistics ---\n"); +} diff --git a/dep/jemalloc/tcache.c b/dep/jemalloc/tcache.c new file mode 100644 index 00000000000..ce6ec996159 --- /dev/null +++ b/dep/jemalloc/tcache.c @@ -0,0 +1,403 @@ +#define JEMALLOC_TCACHE_C_ +#include "jemalloc/internal/jemalloc_internal.h" +#ifdef JEMALLOC_TCACHE +/******************************************************************************/ +/* Data. */ + +bool opt_tcache = true; +ssize_t opt_lg_tcache_maxclass = LG_TCACHE_MAXCLASS_DEFAULT; +ssize_t opt_lg_tcache_gc_sweep = LG_TCACHE_GC_SWEEP_DEFAULT; + +/* Map of thread-specific caches. */ +__thread tcache_t *tcache_tls JEMALLOC_ATTR(tls_model("initial-exec")); + +/* + * Same contents as tcache, but initialized such that the TSD destructor is + * called when a thread exits, so that the cache can be cleaned up. + */ +static pthread_key_t tcache_tsd; + +size_t nhbins; +size_t tcache_maxclass; +unsigned tcache_gc_incr; + +/******************************************************************************/ +/* Function prototypes for non-inline static functions. */ + +static void tcache_thread_cleanup(void *arg); + +/******************************************************************************/ + +void * +tcache_alloc_small_hard(tcache_t *tcache, tcache_bin_t *tbin, size_t binind) +{ + void *ret; + + arena_tcache_fill_small(tcache->arena, tbin, binind +#ifdef JEMALLOC_PROF + , tcache->prof_accumbytes +#endif + ); +#ifdef JEMALLOC_PROF + tcache->prof_accumbytes = 0; +#endif + ret = tcache_alloc_easy(tbin); + + return (ret); +} + +void +tcache_bin_flush_small(tcache_bin_t *tbin, size_t binind, unsigned rem +#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) + , tcache_t *tcache +#endif + ) +{ + void *flush, *deferred, *ptr; + unsigned i, nflush, ndeferred; + + assert(binind < nbins); + assert(rem <= tbin->ncached); + + for (flush = tbin->avail, nflush = tbin->ncached - rem; flush != NULL; + flush = deferred, nflush = ndeferred) { + /* Lock the arena bin associated with the first object. */ + arena_chunk_t *chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(flush); + arena_t *arena = chunk->arena; + arena_bin_t *bin = &arena->bins[binind]; + +#ifdef JEMALLOC_PROF + if (arena == tcache->arena) { + malloc_mutex_lock(&arena->lock); + arena_prof_accum(arena, tcache->prof_accumbytes); + malloc_mutex_unlock(&arena->lock); + tcache->prof_accumbytes = 0; + } +#endif + + malloc_mutex_lock(&bin->lock); +#ifdef JEMALLOC_STATS + if (arena == tcache->arena) { + bin->stats.nflushes++; + bin->stats.nrequests += tbin->tstats.nrequests; + tbin->tstats.nrequests = 0; + } +#endif + deferred = NULL; + ndeferred = 0; + for (i = 0; i < nflush; i++) { + ptr = flush; + assert(ptr != NULL); + flush = *(void **)ptr; + chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); + if (chunk->arena == arena) { + size_t pageind = (((uintptr_t)ptr - + (uintptr_t)chunk) >> PAGE_SHIFT); + arena_chunk_map_t *mapelm = + &chunk->map[pageind]; + arena_dalloc_bin(arena, chunk, ptr, mapelm); + } else { + /* + * This object was allocated via a different + * arena bin than the one that is currently + * locked. Stash the object, so that it can be + * handled in a future pass. + */ + *(void **)ptr = deferred; + deferred = ptr; + ndeferred++; + } + } + malloc_mutex_unlock(&bin->lock); + + if (flush != NULL) { + /* + * This was the first pass, and rem cached objects + * remain. + */ + tbin->avail = flush; + } + } + + tbin->ncached = rem; + if (tbin->ncached < tbin->low_water) + tbin->low_water = tbin->ncached; +} + +void +tcache_bin_flush_large(tcache_bin_t *tbin, size_t binind, unsigned rem +#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) + , tcache_t *tcache +#endif + ) +{ + void *flush, *deferred, *ptr; + unsigned i, nflush, ndeferred; + + assert(binind < nhbins); + assert(rem <= tbin->ncached); + + for (flush = tbin->avail, nflush = tbin->ncached - rem; flush != NULL; + flush = deferred, nflush = ndeferred) { + /* Lock the arena associated with the first object. */ + arena_chunk_t *chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(flush); + arena_t *arena = chunk->arena; + + malloc_mutex_lock(&arena->lock); +#if (defined(JEMALLOC_PROF) || defined(JEMALLOC_STATS)) + if (arena == tcache->arena) { +#endif +#ifdef JEMALLOC_PROF + arena_prof_accum(arena, tcache->prof_accumbytes); + tcache->prof_accumbytes = 0; +#endif +#ifdef JEMALLOC_STATS + arena->stats.nrequests_large += tbin->tstats.nrequests; + arena->stats.lstats[binind - nbins].nrequests += + tbin->tstats.nrequests; + tbin->tstats.nrequests = 0; +#endif +#if (defined(JEMALLOC_PROF) || defined(JEMALLOC_STATS)) + } +#endif + deferred = NULL; + ndeferred = 0; + for (i = 0; i < nflush; i++) { + ptr = flush; + assert(ptr != NULL); + flush = *(void **)ptr; + chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); + if (chunk->arena == arena) + arena_dalloc_large(arena, chunk, ptr); + else { + /* + * This object was allocated via a different + * arena than the one that is currently locked. + * Stash the object, so that it can be handled + * in a future pass. + */ + *(void **)ptr = deferred; + deferred = ptr; + ndeferred++; + } + } + malloc_mutex_unlock(&arena->lock); + + if (flush != NULL) { + /* + * This was the first pass, and rem cached objects + * remain. + */ + tbin->avail = flush; + } + } + + tbin->ncached = rem; + if (tbin->ncached < tbin->low_water) + tbin->low_water = tbin->ncached; +} + +tcache_t * +tcache_create(arena_t *arena) +{ + tcache_t *tcache; + size_t size; + unsigned i; + + size = sizeof(tcache_t) + (sizeof(tcache_bin_t) * (nhbins - 1)); + /* + * Round up to the nearest multiple of the cacheline size, in order to + * avoid the possibility of false cacheline sharing. + * + * That this works relies on the same logic as in ipalloc(). + */ + size = (size + CACHELINE_MASK) & (-CACHELINE); + + if (size <= small_maxclass) + tcache = (tcache_t *)arena_malloc_small(arena, size, true); + else + tcache = (tcache_t *)icalloc(size); + + if (tcache == NULL) + return (NULL); + +#ifdef JEMALLOC_STATS + /* Link into list of extant tcaches. */ + malloc_mutex_lock(&arena->lock); + ql_elm_new(tcache, link); + ql_tail_insert(&arena->tcache_ql, tcache, link); + malloc_mutex_unlock(&arena->lock); +#endif + + tcache->arena = arena; + assert((TCACHE_NSLOTS_SMALL_MAX & 1U) == 0); + for (i = 0; i < nbins; i++) { + if ((arena->bins[i].nregs << 1) <= TCACHE_NSLOTS_SMALL_MAX) { + tcache->tbins[i].ncached_max = (arena->bins[i].nregs << + 1); + } else + tcache->tbins[i].ncached_max = TCACHE_NSLOTS_SMALL_MAX; + } + for (; i < nhbins; i++) + tcache->tbins[i].ncached_max = TCACHE_NSLOTS_LARGE; + + tcache_tls = tcache; + pthread_setspecific(tcache_tsd, tcache); + + return (tcache); +} + +void +tcache_destroy(tcache_t *tcache) +{ + unsigned i; + +#ifdef JEMALLOC_STATS + /* Unlink from list of extant tcaches. */ + malloc_mutex_lock(&tcache->arena->lock); + ql_remove(&tcache->arena->tcache_ql, tcache, link); + malloc_mutex_unlock(&tcache->arena->lock); + tcache_stats_merge(tcache, tcache->arena); +#endif + + for (i = 0; i < nbins; i++) { + tcache_bin_t *tbin = &tcache->tbins[i]; + tcache_bin_flush_small(tbin, i, 0 +#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) + , tcache +#endif + ); + +#ifdef JEMALLOC_STATS + if (tbin->tstats.nrequests != 0) { + arena_t *arena = tcache->arena; + arena_bin_t *bin = &arena->bins[i]; + malloc_mutex_lock(&bin->lock); + bin->stats.nrequests += tbin->tstats.nrequests; + malloc_mutex_unlock(&bin->lock); + } +#endif + } + + for (; i < nhbins; i++) { + tcache_bin_t *tbin = &tcache->tbins[i]; + tcache_bin_flush_large(tbin, i, 0 +#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) + , tcache +#endif + ); + +#ifdef JEMALLOC_STATS + if (tbin->tstats.nrequests != 0) { + arena_t *arena = tcache->arena; + malloc_mutex_lock(&arena->lock); + arena->stats.nrequests_large += tbin->tstats.nrequests; + arena->stats.lstats[i - nbins].nrequests += + tbin->tstats.nrequests; + malloc_mutex_unlock(&arena->lock); + } +#endif + } + +#ifdef JEMALLOC_PROF + if (tcache->prof_accumbytes > 0) { + malloc_mutex_lock(&tcache->arena->lock); + arena_prof_accum(tcache->arena, tcache->prof_accumbytes); + malloc_mutex_unlock(&tcache->arena->lock); + } +#endif + + if (arena_salloc(tcache) <= small_maxclass) { + arena_chunk_t *chunk = CHUNK_ADDR2BASE(tcache); + arena_t *arena = chunk->arena; + size_t pageind = (((uintptr_t)tcache - (uintptr_t)chunk) >> + PAGE_SHIFT); + arena_chunk_map_t *mapelm = &chunk->map[pageind]; + arena_run_t *run = (arena_run_t *)((uintptr_t)chunk + + (uintptr_t)((pageind - (mapelm->bits >> PAGE_SHIFT)) << + PAGE_SHIFT)); + arena_bin_t *bin = run->bin; + + malloc_mutex_lock(&bin->lock); + arena_dalloc_bin(arena, chunk, tcache, mapelm); + malloc_mutex_unlock(&bin->lock); + } else + idalloc(tcache); +} + +static void +tcache_thread_cleanup(void *arg) +{ + tcache_t *tcache = (tcache_t *)arg; + + assert(tcache == tcache_tls); + if (tcache != NULL) { + assert(tcache != (void *)(uintptr_t)1); + tcache_destroy(tcache); + tcache_tls = (void *)(uintptr_t)1; + } +} + +#ifdef JEMALLOC_STATS +void +tcache_stats_merge(tcache_t *tcache, arena_t *arena) +{ + unsigned i; + + /* Merge and reset tcache stats. */ + for (i = 0; i < nbins; i++) { + arena_bin_t *bin = &arena->bins[i]; + tcache_bin_t *tbin = &tcache->tbins[i]; + malloc_mutex_lock(&bin->lock); + bin->stats.nrequests += tbin->tstats.nrequests; + malloc_mutex_unlock(&bin->lock); + tbin->tstats.nrequests = 0; + } + + for (; i < nhbins; i++) { + malloc_large_stats_t *lstats = &arena->stats.lstats[i - nbins]; + tcache_bin_t *tbin = &tcache->tbins[i]; + arena->stats.nrequests_large += tbin->tstats.nrequests; + lstats->nrequests += tbin->tstats.nrequests; + tbin->tstats.nrequests = 0; + } +} +#endif + +void +tcache_boot(void) +{ + + if (opt_tcache) { + /* + * If necessary, clamp opt_lg_tcache_maxclass, now that + * small_maxclass and arena_maxclass are known. + */ + if (opt_lg_tcache_maxclass < 0 || (1U << + opt_lg_tcache_maxclass) < small_maxclass) + tcache_maxclass = small_maxclass; + else if ((1U << opt_lg_tcache_maxclass) > arena_maxclass) + tcache_maxclass = arena_maxclass; + else + tcache_maxclass = (1U << opt_lg_tcache_maxclass); + + nhbins = nbins + (tcache_maxclass >> PAGE_SHIFT); + + /* Compute incremental GC event threshold. */ + if (opt_lg_tcache_gc_sweep >= 0) { + tcache_gc_incr = ((1U << opt_lg_tcache_gc_sweep) / + nbins) + (((1U << opt_lg_tcache_gc_sweep) % nbins == + 0) ? 0 : 1); + } else + tcache_gc_incr = 0; + + if (pthread_key_create(&tcache_tsd, tcache_thread_cleanup) != + 0) { + malloc_write( + ": Error in pthread_key_create()\n"); + abort(); + } + } +} +/******************************************************************************/ +#endif /* JEMALLOC_TCACHE */ diff --git a/dep/libmpq/AUTHORS b/dep/libmpq/AUTHORS new file mode 100644 index 00000000000..3d7da7bec9a --- /dev/null +++ b/dep/libmpq/AUTHORS @@ -0,0 +1,10 @@ +Project Initiator: + + * Maik Broemme + +Developers: + + * Maik Broemme + * Tilman Sauerbeck + * Forrest Voight + * Georg Lukas diff --git a/dep/libmpq/CMakeLists.txt b/dep/libmpq/CMakeLists.txt new file mode 100644 index 00000000000..23e8b323398 --- /dev/null +++ b/dep/libmpq/CMakeLists.txt @@ -0,0 +1,34 @@ +# Copyright (C) 2008-2010 Trinity +# +# This file is free software; as a special exception the author gives +# unlimited permission to copy and/or distribute it, with or without +# modifications, as long as this notice is preserved. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the +# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +file(GLOB sources_mpq libmpq/*.c libmpq/*.h) + +set(mpq_STAT_SRCS + ${sources_mpq} +) + +if( UNIX ) + include_directories( + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_SOURCE_DIR}/dep/zlib + ${CMAKE_SOURCE_DIR}/dep/bzip2 + ) +elseif( WIN32 ) + include_directories( + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/win + ${CMAKE_SOURCE_DIR}/dep/zlib + ${CMAKE_SOURCE_DIR}/dep/bzip2 + ) +endif() + +add_library(mpq STATIC ${mpq_STAT_SRCS}) + +set_target_properties(mpq PROPERTIES LINKER_LANGUAGE CXX) diff --git a/dep/libmpq/COPYING b/dep/libmpq/COPYING new file mode 100644 index 00000000000..4189933be9f --- /dev/null +++ b/dep/libmpq/COPYING @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + Appendix: How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) 19yy + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) 19yy name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/dep/libmpq/FAQ b/dep/libmpq/FAQ new file mode 100644 index 00000000000..52ca9f3c705 --- /dev/null +++ b/dep/libmpq/FAQ @@ -0,0 +1,68 @@ +FAQ - Frequently Asked Questions +================================ + +Q: What is libmpq? +A: libmpq is a library for manipulating MoPaQ mpq archives mostly used + used by Blizzard in their games. + +Q: What can i do with libmpq? +A: With libmpq you can write applications which can extract, create + and manipulate mpq archives. + +Q: Is it legal? +A: Yes, i think so. I have no idea why it should not, all informations + about the fileformat are available. + +Q: Is there a description of the functions? +A: Since version 0.4.0 libmpq comes with a API documentation for + developers. The documentation is written as manual pages. + +Q: Can i help? +A: Yes, help is needed, not only with developing, also with testing. + A good point to start is using a recent SVN version of libmpq and + trying to use it with every mpq archive you could get :) + +Q: Can you give a small example to demonstrate the usage? +A: Of course :) The example below takes first parameter as mpq archive + and extracts the first file to a buffer. + + /* + * Compile with: + * + * x86_32: + * + * gcc \ + * -D_FILE_OFFSET_BITS=64 \ + * -D_LARGE_FILES=1 \ + * -D_LARGEFILE_SOURCE=1 \ + * mpq-example.c -o mpq-example -lmpq -lz -lbz2 -I/usr/local/include/libmpq + * + * x86_64: + * + * gcc \ + * -D_LARGE_FILES=1 \ + * mpq-example.c -o mpq-example -lmpq -lz -lbz2 -I/usr/local/include/libmpq + */ + + #include + #include + #include + + int main(int argc, char **argv) { + mpq_archive_s *mpq_archive; + off_t out_size; + char *out_buf; + + /* open the mpq archive given as first parameter. */ + libmpq__archive_open(&mpq_archive, argv[1], -1); + + /* get size of first file (0) and malloc output buffer. */ + libmpq__file_unpacked_size(mpq_archive, 0, &out_size); + out_buf = malloc(out_size); + + /* read, decrypt and unpack file to output buffer. */ + libmpq__file_read(mpq_archive, 0, out_buf, out_size, NULL); + + /* close the mpq archive. */ + libmpq__archive_close(mpq_archive); + } diff --git a/dep/libmpq/INSTALL b/dep/libmpq/INSTALL new file mode 100644 index 00000000000..b42a17ac464 --- /dev/null +++ b/dep/libmpq/INSTALL @@ -0,0 +1,182 @@ +Basic Installation +================== + + These are generic installation instructions. + + 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, a file +`config.cache' that saves the results of its tests to speed up +reconfiguring, and a file `config.log' containing compiler output +(useful mainly for debugging `configure'). + + 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' so they can +be considered for the next release. If at some point `config.cache' +contains results you don't want to keep, you may remove or edit it. + + The file `configure.in' is used to create `configure' by a program +called `autoconf'. You only need `configure.in' 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. If you're + using `csh' on an old version of System V, you might need to type + `sh ./configure' instead to prevent `csh' from trying to execute + `configure' itself. + + Running `configure' takes awhile. 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. + +Compilers and Options +===================== + + Some systems require unusual options for compilation or linking that +the `configure' script does not know about. You can give `configure' +initial values for variables by setting them in the environment. Using +a Bourne-compatible shell, you can do that on the command line like +this: + CC=c89 CFLAGS=-O2 LIBS=-lposix ./configure + +Or on systems that have the `env' program, you can do it like this: + env CPPFLAGS=-I/usr/local/include LDFLAGS=-s ./configure + +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 must use a version of `make' that +supports the `VPATH' variable, such as 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 `..'. + + If you have to use a `make' that does not supports the `VPATH' +variable, you have 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' will install the package's files in +`/usr/local/bin', `/usr/local/man', etc. You can specify an +installation prefix other than `/usr/local' by giving `configure' the +option `--prefix=PATH'. + + You can specify separate installation prefixes for +architecture-specific files and architecture-independent files. If you +give `configure' the option `--exec-prefix=PATH', the package will use +PATH as the prefix for installing programs and libraries. +Documentation and other data files will still use the regular prefix. + + In addition, if you use an unusual directory layout you can give +options like `--bindir=PATH' 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' 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' can not figure out +automatically, but needs to determine by the type of host the package +will run on. Usually `configure' can figure that out, but if it prints +a message saying it can not guess the host type, give it the +`--host=TYPE' option. TYPE can either be a short name for the system +type, such as `sun4', or a canonical name with three fields: + CPU-COMPANY-SYSTEM + +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 host type. + + If you are building compiler tools for cross-compiling, you can also +use the `--target=TYPE' option to select the type of system they will +produce code for and the `--build=TYPE' option to select the type of +system on which you are compiling the package. + +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. + +Operation Controls +================== + + `configure' recognizes the following options to control how it +operates. + +`--cache-file=FILE' + Use and save the results of the tests in FILE instead of + `./config.cache'. Set FILE to `/dev/null' to disable caching, for + debugging `configure'. + +`--help' + Print a summary of the options to `configure', and exit. + +`--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. + +`--version' + Print the version of Autoconf used to generate the `configure' + script, and exit. + +`configure' also accepts some other, not widely useful, options. diff --git a/dep/libmpq/Makefile.am b/dep/libmpq/Makefile.am new file mode 100644 index 00000000000..0a9b54c2526 --- /dev/null +++ b/dep/libmpq/Makefile.am @@ -0,0 +1,26 @@ +# minimum required automake 1.6 +AUTOMAKE_OPTIONS = 1.6 + +# any directories which should be built and installed. +SUBDIRS = libmpq bindings doc + +# the directories which are part of the distribution. +DIST_SUBDIRS = $(SUBDIRS) + +# libmpq runtime configuration script. +bin_SCRIPTS = libmpq-config + +# pkg-config installation directory. +pkgconfigdir = $(libdir)/pkgconfig +pkgconfig_DATA = libmpq.pc + +# extra stuff. +EXTRA_DIST = \ + AUTHORS \ + COPYING \ + FAQ \ + INSTALL \ + NEWS \ + README \ + THANKS \ + TODO diff --git a/dep/libmpq/NEWS b/dep/libmpq/NEWS new file mode 100644 index 00000000000..74850a8a5bb --- /dev/null +++ b/dep/libmpq/NEWS @@ -0,0 +1,76 @@ +Changes version 0.4.2 (2008-05-16) +================================== + + * added full extraction support for protected maps used in + warcraft 3. + + * added full extraction support for all blizzard titles until + world of warcraft - the burning crusade. + + * added support for archives version 2 with extended header and + extended block table. + + * added support for the bzip2 compression algorithm. + + * added support for archives and files inside archive > 2gb. + + * added generic read functions, which will do decryption, + decompression or exploding. + + * the info functions are no longer exported by the library and + were replaced by separate api functions. + + * the file number and block number are count from 0 instead + of 1. + + * added python bindings. + + * linking against libmpq requires from now on the usual largefile + macros -D_FILE_OFFSET_BITS=64 -D_LARGE_FILES=1 -D_LARGEFILE_SOURCE=1 + +Changes version 0.4.1 (2008-04-02) +================================== + + * memory, speed and stability improvements. + + * split sourcecode into library and utility package. + +Changes version 0.4.0 (2008-03-31) +================================== + + * added robust error handling to make the library and extracting + utility more stable. + + * added c++ bindings to public include and moved internal defines + and functions to private include. + + * added support for 64-bit architectures and removed any stupid + pointer to int arithmetics. + + * added much better member names to the structures to make + developers able to understand the code on reading. + + * added full api documentation using manual pages. + + * added full extraction support for all blizzard titles until + warcraft 3 - the frozen throne. + + * added support for single sector and stored files (neither + compressed nor imploded). + + * added support for files which have compressed size greater than + uncompressed size. + + * removed the external listfile database support from 0.3.0 it + was a weird implementation. + +Changes version 0.3.0 (2004-02-12) +================================== + + * added listfile database support from external files. + +Initial version 0.2.1 (2004-01-17) +================================== + + * first version which was able to extract some of the older mopaq + archives. diff --git a/dep/libmpq/README b/dep/libmpq/README new file mode 100644 index 00000000000..3f1bd3a1e9f --- /dev/null +++ b/dep/libmpq/README @@ -0,0 +1,34 @@ +Introduction +============ + +'libmpq' is a library which can be easily used in own applications +to extract, create or manipulate MoPaQ mpq archives. + +MPQ, or MoPaQ, is a proprietary archive format created by +Mike O'Brien, the man hailed as Blizzard's multiplayer engine +genius, back in 1996 as a general purpose archive for use with +Diablo, and named narcissistically for its creator +"Mike O'brien PaCK". The copyrights to it, however, are held by +Havas Interactive, Blizzard's parent company. The archive format +is used by many Blizzard titles like Diablo, Diablo 2, Starcraft, +Warcraft 2: BNE, a newer version in Warcraft 3 and World of +Warcraft (WoW). + +Manual +====== + +Since version 0.4.0 the 'libmpq' package comes with a manpage for +every library function. If you use 'libmpq' first time it is a good +idea to read the `FAQ' file. + +Reporting Bugs +============== + +Bug reports for 'libmpq' can be send to me directly. + + * Maik Broemme + +Enjoy! + +Maik Broemme +http://www.babelize.org/ diff --git a/dep/libmpq/THANKS b/dep/libmpq/THANKS new file mode 100644 index 00000000000..42da1235476 --- /dev/null +++ b/dep/libmpq/THANKS @@ -0,0 +1,21 @@ +'libmpq' was originaly created by Maik Broemme +and i want to thank some people which helped by supplying knowledge, code or +something else. + + * Romy Trompke + - my lovely girlfriend for her patience + + * Ladislav Zezula + - stormlib creator + + * Marko Friedemann + - initial port of stormlib to linux + + * Tom Amigo + - first people who decrypts the MoPaQ archive format + + * ShadowFlare + - creator of the ShadowFlare MPQ API + + * Justin Olbrantz (Quantam) + - creator of the client using ShadowFlare MPQ API diff --git a/dep/libmpq/TODO b/dep/libmpq/TODO new file mode 100644 index 00000000000..0c1951f0b46 --- /dev/null +++ b/dep/libmpq/TODO @@ -0,0 +1,10 @@ +Features and functionality which should be added in the future. + + * Porting for big endian systems. + * Porting for Windows? :) + * Creating mpq archives. + * Brute all unknown filenames, Blizzard uses in their + archives. + +Look at the AUTHORS file if you want help me with 'libmpq', or +if you have other interesting features which should be added. diff --git a/dep/libmpq/autogen.sh b/dep/libmpq/autogen.sh new file mode 100644 index 00000000000..16871edd70d --- /dev/null +++ b/dep/libmpq/autogen.sh @@ -0,0 +1,19 @@ +#!/bin/sh +# +echo "Generating build information using aclocal, autoheader, automake and autoconf" +echo "This may take a while ..." + +# Touch the timestamps on all the files since CVS messes them up +directory=`dirname $0` +touch $directory/configure.ac + +# Regenerate configuration files +libtoolize --copy +aclocal +autoheader +automake --foreign --add-missing --copy +autoconf + +# Run configure for this platform +#./configure $* +echo "Now you are ready to run ./configure" diff --git a/dep/libmpq/bindings/Makefile.am b/dep/libmpq/bindings/Makefile.am new file mode 100644 index 00000000000..b9fefe306ef --- /dev/null +++ b/dep/libmpq/bindings/Makefile.am @@ -0,0 +1,6 @@ +# any directories which should be built and installed. +SUBDIRS = d + +if HAVE_PYTHON +SUBDIRS += python +endif diff --git a/dep/libmpq/bindings/d/Makefile.am b/dep/libmpq/bindings/d/Makefile.am new file mode 100644 index 00000000000..4de7285ae51 --- /dev/null +++ b/dep/libmpq/bindings/d/Makefile.am @@ -0,0 +1,6 @@ +# minimum required automake 1.6 +AUTOMAKE_OPTIONS = 1.6 + +# install D binding to /usr/include/d by default +libmpq_includedir = $(includedir)/d +libmpq_include_HEADERS = mpq.d diff --git a/dep/libmpq/bindings/d/dsss.conf b/dep/libmpq/bindings/d/dsss.conf new file mode 100644 index 00000000000..252482c4933 --- /dev/null +++ b/dep/libmpq/bindings/d/dsss.conf @@ -0,0 +1,2 @@ +[mpq.d] +type=sourcelibrary diff --git a/dep/libmpq/bindings/d/mpq.d b/dep/libmpq/bindings/d/mpq.d new file mode 100644 index 00000000000..d72c2d2a986 --- /dev/null +++ b/dep/libmpq/bindings/d/mpq.d @@ -0,0 +1,318 @@ +/* + * mpq.d -- D programming language module for libmpq + * + * Copyright (c) 2008 Georg Lukas + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This module is written to support Phobos. Patches to allow binding to + * Tango are welcome. + */ + +module mpq; + +/* the following pragma does not work on DMD/Linux, generates a warning on + * GDC/Linux and has not been tested on Windows. Commented out for now. */ +// pragma(lib, "libmpq"); + +import std.string; // for format() and toStringz() +import std.traits; // for ParameterTypeTuple!() + +/* XXX: this assumes that libmpq is compiled with Large File Support on */ +alias long off_t; + +/* libmpq error return values */ +const LIBMPQ_ERROR_OPEN = -1; /* open error on file. */ +const LIBMPQ_ERROR_CLOSE = -2; /* close error on file. */ +const LIBMPQ_ERROR_SEEK = -3; /* lseek error on file. */ +const LIBMPQ_ERROR_READ = -4; /* read error on file. */ +const LIBMPQ_ERROR_WRITE = -5; /* write error on file. */ +const LIBMPQ_ERROR_MALLOC = -6; /* memory allocation error. */ +const LIBMPQ_ERROR_FORMAT = -7; /* format errror. */ +const LIBMPQ_ERROR_NOT_INITIALIZED = -8; /* init() wasn't called. */ +const LIBMPQ_ERROR_SIZE = -9; /* buffer size is to small. */ +const LIBMPQ_ERROR_EXIST = -10; /* file or block does not exist in archive. */ +const LIBMPQ_ERROR_DECRYPT = -11; /* we don't know the decryption seed. */ +const LIBMPQ_ERROR_UNPACK = -12; /* error on unpacking file. */ + +/** libmpq internal meta-data for an archive */ +extern struct mpq_archive_s; + +extern(C) { + +/* libmpq__generic information about library. */ +char *libmpq__version(); + +/* libmpq__generic mpq archive information. */ +int libmpq__archive_open(mpq_archive_s **mpq_archive, char *mpq_filename, off_t archive_offset); +int libmpq__archive_close(mpq_archive_s *mpq_archive); +int libmpq__archive_packed_size(mpq_archive_s *mpq_archive, off_t *packed_size); +int libmpq__archive_unpacked_size(mpq_archive_s *mpq_archive, off_t *unpacked_size); +int libmpq__archive_offset(mpq_archive_s *mpq_archive, off_t *offset); +int libmpq__archive_version(mpq_archive_s *mpq_archive, uint *version_); +int libmpq__archive_files(mpq_archive_s *mpq_archive, uint *files); + +/* libmpq__generic file processing functions. */ +int libmpq__file_packed_size(mpq_archive_s *mpq_archive, uint file_number, off_t *packed_size); +int libmpq__file_unpacked_size(mpq_archive_s *mpq_archive, uint file_number, off_t *unpacked_size); +int libmpq__file_offset(mpq_archive_s *mpq_archive, uint file_number, off_t *offset); +int libmpq__file_blocks(mpq_archive_s *mpq_archive, uint file_number, uint *blocks); +int libmpq__file_encrypted(mpq_archive_s *mpq_archive, uint file_number, uint *encrypted); +int libmpq__file_compressed(mpq_archive_s *mpq_archive, uint file_number, uint *compressed); +int libmpq__file_imploded(mpq_archive_s *mpq_archive, uint file_number, uint *imploded); +int libmpq__file_number(mpq_archive_s *mpq_archive, char *filename, uint *number); +int libmpq__file_read(mpq_archive_s *mpq_archive, uint file_number, ubyte *out_buf, off_t out_size, off_t *transferred); + +/* libmpq__generic block processing functions. */ +int libmpq__block_open_offset(mpq_archive_s *mpq_archive, uint file_number); +int libmpq__block_close_offset(mpq_archive_s *mpq_archive, uint file_number); +int libmpq__block_unpacked_size(mpq_archive_s *mpq_archive, uint file_number, uint block_number, off_t *unpacked_size); +int libmpq__block_read(mpq_archive_s *mpq_archive, uint file_number, uint block_number, ubyte *out_buf, off_t out_size, off_t *transferred); + +} + + +/** exception class for failed libmpq calls */ +class MPQException : Exception { + const string[] Errors = [ + "unknown error", + "open error on file", + "close error on file", + "lseek error on file", + "read error on file", + "write error on file", + "memory allocation error", + "format errror", + "init() wasn't called", + "buffer size is to small", + "file or block does not exist in archive", + "we don't know the decryption seed", + "error on unpacking file"]; + + public int errno; + this(char[] fnname = "unknown_function", int errno = 0) { + + this.errno = errno; + if (-errno >= Errors.length) + errno = 0; + super(std.string.format("Error in %s(): %s (%d)", + fnname, Errors[-errno], errno)); + } +} + + +/** template to wrap function calls and throw exceptions in case of error + * + * thanks for the idea to while(nan) blog, + * http://while-nan.blogspot.com/2007/06/wrapping-functions-for-fun-and-profit.html + * + * use: MPQ_CHECKERR(libmpq__archive_open)(&m, "foo.mpq", -1); + * returns the retval of archive_open on success; + * throws an MPQException on failure. + * + * @param Fn libmpq__function reference + * @param args libmpq__function parameters + * @return return value of libmpq__function on success + * @throw MPQException on error + */ +int MPQ_CHECKERR(alias Fn)(ParameterTypeTuple!(Fn) args) +{ + int result = Fn(args); + if (result < 0) { + /* XXX: relying on non-specified stringof() behaviour */ + throw new MPQException((&Fn).stringof[2..$], result); + } + return result; +} + + +/** mixin alias to wrap library functions into MPQ_CHECKERR. + * + * alias mpq.func_name(...) to MPQ_CHECKERR(libmpq__func_name)(...) + * @param func_name name of the function to be wrapped + */ +template MPQ_FUNC(char[] func_name) { + const char[] MPQ_FUNC = "alias MPQ_CHECKERR!(libmpq__" ~ func_name ~ ") " ~ func_name ~ ";"; +} + +alias libmpq__version libversion; /* must be direct alias because it returns char*, not error int */ +mixin(MPQ_FUNC!("archive_open")); +mixin(MPQ_FUNC!("archive_close")); +mixin(MPQ_FUNC!("archive_packed_size")); +mixin(MPQ_FUNC!("archive_unpacked_size")); +mixin(MPQ_FUNC!("archive_offset")); +mixin(MPQ_FUNC!("archive_version")); +mixin(MPQ_FUNC!("archive_files")); +mixin(MPQ_FUNC!("file_packed_size")); +mixin(MPQ_FUNC!("file_unpacked_size")); +mixin(MPQ_FUNC!("file_offset")); +mixin(MPQ_FUNC!("file_blocks")); +mixin(MPQ_FUNC!("file_encrypted")); +mixin(MPQ_FUNC!("file_compressed")); +mixin(MPQ_FUNC!("file_imploded")); +mixin(MPQ_FUNC!("file_number")); +mixin(MPQ_FUNC!("file_read")); +mixin(MPQ_FUNC!("block_open_offset")); +mixin(MPQ_FUNC!("block_close_offset")); +mixin(MPQ_FUNC!("block_unpacked_size")); +mixin(MPQ_FUNC!("block_read")); + +/** getter function named name for returning archive_* single values: + * + * Archive.() { return libmpq__archive_() } + * + * @param type return type for the original function reference + * @param name name of the original function + * @param name2 name for the prototype (defaults to name, used for "version") + * @return getter function mixin + */ +template MPQ_A_GET(char[] type, char[] name, char[] name2 = name) { + const char[] MPQ_A_GET = type ~ " " ~ name2 ~ "() { " ~ + type ~ " ret; " ~ + "archive_" ~ name ~ "(m, &ret); return ret;" ~ + "}"; +} + +/** wrapper class for an MPQ Archive + * + * syntax: auto a = new mpq.Archive("somefile.mpq"); + */ +class Archive { + mpq_archive_s *m; + File listfile; + char[][] listfiledata; + + this(char[] archivename, off_t offset = -1) { + archive_open(&m, toStringz(archivename), offset); + } + + mixin(MPQ_A_GET!("off_t", "packed_size")); + mixin(MPQ_A_GET!("off_t", "unpacked_size")); + mixin(MPQ_A_GET!("off_t", "offset")); + mixin(MPQ_A_GET!("uint", "version", "version_")); + mixin(MPQ_A_GET!("uint", "files")); + + ~this() { + archive_close(m); + } + + mpq_archive_s* archive() { + return m; + } + + File opIndex(char[] fname) { + return new File(this, fname); + } + File opIndex(int fno) { + return new File(this, fno); + } + + char[][] filelist() { + try { + if (!listfile) { + listfile = this["(listfile)"]; + listfiledata = (cast(char[])listfile.read()).splitlines(); + } + return listfiledata; + } catch (MPQException e) { + return []; + } + } + + /+uint filenumber(char[] filename) { + try { + if (!listfile) { + listfile = this["(listfile)"]; + listfiledata = (cast(char[])listfile.read()).splitlines(); + } + return listfiledata; + } catch (MPQException e) { + return []; + } + }+/ + +} + + +/** getter function named name for returning file_* single values: + * + * File.() { return libmpq__file_() } + * + * @param type return type for the original function reference + * @param name name of the original function + * @param name2 name for the prototype (defaults to name, used for "version") + * @return getter function mixin + */ +template MPQ_F_GET(char[] type, char[] name, char[] name2 = name) { + const char[] MPQ_F_GET = type ~ " " ~ name2 ~ "() { " ~ + type ~ " ret; " ~ + "file_" ~ name ~ "(am, fileno, &ret); " ~ + "return ret;" ~ + "}"; +} + +/** wrapper class for a single file in an MPQ Archive + * + * syntax: + * auto a = new mpq.Archive("somefile.mpq"); + * auto f = a["(listfile)"]; + * auto f2 = a[0]; + * auto f3 = new File(a, "(listfile)"); + */ +class File { + Archive a; + mpq_archive_s* am; + char[] filename; + uint fileno; + + this(Archive a, int fileno) { + this.a = a; + this.am = a.archive(); + if (fileno >= a.files) { + throw new MPQException(format("File(%d)", fileno), + LIBMPQ_ERROR_EXIST); + } + this.filename = format("file%04d.xxx", fileno); + this.fileno = fileno; + } + + this(Archive a, char[] filename) { + this.a = a; + this.am = a.archive(); + this.filename = filename; + /* this line will throw an exception when the file is not there */ + mpq.file_number(am, toStringz(filename), &this.fileno); + } + + mixin(MPQ_F_GET!("off_t", "packed_size")); + mixin(MPQ_F_GET!("off_t", "unpacked_size")); + mixin(MPQ_F_GET!("off_t", "offset")); + mixin(MPQ_F_GET!("uint", "blocks")); + mixin(MPQ_F_GET!("uint", "encrypted")); + mixin(MPQ_F_GET!("uint", "compressed")); + mixin(MPQ_F_GET!("uint", "imploded")); + + uint no() { return fileno; } + char[] name() { return filename; } + + ubyte[] read() { + ubyte[] content; + content.length = this.unpacked_size(); + off_t trans; + mpq.file_read(am, fileno, content.ptr, content.length, &trans); + content.length = trans; + return content; + } +} diff --git a/dep/libmpq/bindings/python/Makefile.am b/dep/libmpq/bindings/python/Makefile.am new file mode 100644 index 00000000000..6971a9b2f6d --- /dev/null +++ b/dep/libmpq/bindings/python/Makefile.am @@ -0,0 +1,5 @@ +# minimum required automake 1.6 +AUTOMAKE_OPTIONS = 1.6 + +# library information and headers which should not be installed. +python_PYTHON = mpq.py diff --git a/dep/libmpq/bindings/python/mpq-info b/dep/libmpq/bindings/python/mpq-info new file mode 100644 index 00000000000..2c67aa1d0cc --- /dev/null +++ b/dep/libmpq/bindings/python/mpq-info @@ -0,0 +1,16 @@ +#!/usr/bin/env python + +from __future__ import division + +import sys + +import mpq + +archive = mpq.Archive(sys.argv[1]) + +print "Name: %s" % sys.argv[1] +print "Version: %s" % archive.filename +print "Offset: %s" % archive.offset +print "Packed size: %s" % archive.packed_size +print "Unpacked size: %s" % archive.unpacked_size +print "Compression ratio: %s" % (archive.packed_size/archive.unpacked_size) diff --git a/dep/libmpq/bindings/python/mpq.py b/dep/libmpq/bindings/python/mpq.py new file mode 100644 index 00000000000..cf6ecaae800 --- /dev/null +++ b/dep/libmpq/bindings/python/mpq.py @@ -0,0 +1,322 @@ +"""wrapper for libmpq""" + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +import ctypes +import ctypes.util +import os + +libmpq = ctypes.CDLL(ctypes.util.find_library("mpq")) + +class Error(Exception): + pass + +errors = { + -1: (IOError, "open"), + -2: (IOError, "close"), + -3: (IOError, "seek"), + -4: (IOError, "read"), + -5: (IOError, "write"), + -6: (MemoryError,), + -7: (Error, "file is not an mpq or is corrupted"), + -8: (AssertionError, "not initialized"), + -9: (AssertionError, "buffer size too small"), + -10: (IndexError, "file not in archive"), + -11: (AssertionError, "decrypt"), + -12: (AssertionError, "unpack"), +} + +def check_error(result, func, arguments, errors=errors): + try: + error = errors[result] + except KeyError: + return result + else: + raise error[0](*error[1:]) + +libmpq.libmpq__version.restype = ctypes.c_char_p + +libmpq.libmpq__archive_open.errcheck = check_error +libmpq.libmpq__archive_close.errcheck = check_error +libmpq.libmpq__archive_packed_size.errcheck = check_error +libmpq.libmpq__archive_unpacked_size.errcheck = check_error +libmpq.libmpq__archive_offset.errcheck = check_error +libmpq.libmpq__archive_version.errcheck = check_error +libmpq.libmpq__archive_files.errcheck = check_error + +libmpq.libmpq__file_packed_size.errcheck = check_error +libmpq.libmpq__file_unpacked_size.errcheck = check_error +libmpq.libmpq__file_offset.errcheck = check_error +libmpq.libmpq__file_blocks.errcheck = check_error +libmpq.libmpq__file_encrypted.errcheck = check_error +libmpq.libmpq__file_compressed.errcheck = check_error +libmpq.libmpq__file_imploded.errcheck = check_error +libmpq.libmpq__file_number.errcheck = check_error +libmpq.libmpq__file_read.errcheck = check_error + +libmpq.libmpq__block_open_offset.errcheck = check_error +libmpq.libmpq__block_close_offset.errcheck = check_error +libmpq.libmpq__block_unpacked_size.errcheck = check_error +libmpq.libmpq__block_read.errcheck = check_error + +__version__ = libmpq.libmpq__version() + + +class Reader(object): + def __init__(self, file, libmpq=libmpq): + self._file = file + self._pos = 0 + self._buf = [] + self._cur_block = 0 + libmpq.libmpq__block_open_offset(self._file._archive._mpq, + self._file.number) + + def __iter__(self): + return self + + def __repr__(self): + return "iter(%r)" % self._file + + def seek(self, offset, whence=os.SEEK_SET, os=os): + if whence == os.SEEK_SET: + pass + elif whence == os.SEEK_CUR: + offset += self._pos + elif whence == os.SEEK_END: + offset += self._file.unpacked_size + else: + raise ValueError, "invalid whence" + + if offset >= self._pos: + self.read(offset - self._pos) + else: + self._pos = 0 + self._buf = [] + self._cur_block = 0 + self.read(offset) + + def tell(self): + return self._pos + + def _read_block(self, ctypes=ctypes, libmpq=libmpq): + block_size = ctypes.c_uint64() + libmpq.libmpq__block_unpacked_size(self._file._archive._mpq, + self._file.number, self._cur_block, ctypes.byref(block_size)) + block_data = ctypes.create_string_buffer(block_size.value) + libmpq.libmpq__block_read(self._file._archive._mpq, + self._file.number, self._cur_block, + block_data, ctypes.c_uint64(len(block_data)), None) + self._buf.append(block_data.raw) + self._cur_block += 1 + + def read(self, size=-1): + while size < 0 or sum(map(len, self._buf)) < size: + if self._cur_block == self._file.blocks: + break + self._read_block() + buf = "".join(self._buf) + if size < 0: + ret = buf + self._buf = [] + else: + ret = buf[:size] + self._buf = [buf[size:]] + self._pos += len(ret) + return ret + + def readline(self, os=os): + line = [] + while True: + char = self.read(1) + if char == "": + break + if char not in '\r\n' and line and line[-1] in '\r\n': + self.seek(-1, os.SEEK_CUR) + break + line.append(char) + return ''.join(line) + + def next(self): + line = self.readline() + if not line: + raise StopIteration + return line + + def readlines(self, sizehint=-1): + res = [] + while sizehint < 0 or sum(map(len, res)) < sizehint: + line = self.readline() + if not line: + break + res.append(line) + return res + + xreadlines = __iter__ + + def __del__(self, libmpq=libmpq): + libmpq.libmpq__block_close_offset(self._file._archive._mpq, + self._file.number) + + +class File(object): + def __init__(self, archive, number, ctypes=ctypes, libmpq=libmpq): + self._archive = archive + self.number = number + + for name, atype in [ + ("packed_size", ctypes.c_uint64), + ("unpacked_size", ctypes.c_uint64), + ("offset", ctypes.c_uint64), + ("blocks", ctypes.c_uint32), + ("encrypted", ctypes.c_uint32), + ("compressed", ctypes.c_uint32), + ("imploded", ctypes.c_uint32), + ]: + data = atype() + func = getattr(libmpq, "libmpq__file_"+name) + func(self._archive._mpq, self.number, ctypes.byref(data)) + setattr(self, name, data.value) + + def __str__(self, ctypes=ctypes, libmpq=libmpq): + data = ctypes.create_string_buffer(self.unpacked_size) + libmpq.libmpq__file_read(self._archive._mpq, self.number, + data, ctypes.c_uint64(len(data)), None) + return data.raw + + def __repr__(self): + return "%r[%i]" % (self._archive, self.number) + + def __iter__(self, Reader=Reader): + return Reader(self) + + +class Archive(object): + def __init__(self, source, ctypes=ctypes, File=File, libmpq=libmpq): + self._source = source + if isinstance(source, File): + assert not source.encrypted + assert not source.compressed + assert not source.imploded + self.filename = source._archive.filename + offset = source._archive.offset + source.offset + else: + self.filename = source + offset = -1 + + self._mpq = ctypes.c_void_p() + libmpq.libmpq__archive_open(ctypes.byref(self._mpq), self.filename, + ctypes.c_uint64(offset)) + self._opened = True + + for field_name, field_type in [ + ("packed_size", ctypes.c_uint64), + ("unpacked_size", ctypes.c_uint64), + ("offset", ctypes.c_uint64), + ("version", ctypes.c_uint32), + ("files", ctypes.c_uint32), + ]: + func = getattr(libmpq, "libmpq__archive_" + field_name) + data = field_type() + func(self._mpq, ctypes.byref(data)) + setattr(self, field_name, data.value) + + def __del__(self, libmpq=libmpq): + if getattr(self, "_opened", False): + libmpq.libmpq__archive_close(self._mpq) + + def __len__(self): + return self.files + + def __contains__(self, item, ctypes=ctypes, libmpq=libmpq): + if isinstance(item, str): + data = ctypes.c_uint32() + try: + libmpq.libmpq__file_number(self._mpq, ctypes.c_char_p(item), + ctypes.byref(data)) + except IndexError: + return False + return True + return 0 <= item < self.files + + def __getitem__(self, item, ctypes=ctypes, File=File, libmpq=libmpq): + if isinstance(item, str): + data = ctypes.c_int() + libmpq.libmpq__file_number(self._mpq, ctypes.c_char_p(item), + ctypes.byref(data)) + item = data.value + else: + if not 0 <= item < self.files: + raise IndexError, "file not in archive" + return File(self, item) + + def __repr__(self): + return "mpq.Archive(%r)" % self._source + +# Remove clutter - everything except Error and Archive. +del os, check_error, ctypes, errors, File, libmpq, Reader + +if __name__ == "__main__": + import sys, random + archive = Archive(sys.argv[1]) + print repr(archive) + for k, v in archive.__dict__.iteritems(): + #if k[0] == '_': continue + print " " * (4 - 1), k, v + assert '(listfile)' in archive + assert 0 in archive + assert len(archive) == archive.files + files = [x.strip() for x in archive['(listfile)']] + files.extend(xrange(archive.files)) + for key in files: #sys.argv[2:] if sys.argv[2:] else xrange(archive.files): + file = archive[key] + print + print " " * (4 - 1), repr(file) + for k, v in file.__dict__.iteritems(): + #if k[0] == '_': continue + print " " * (8 - 1), k, v + + a = str(file) + + b = iter(file).read() + + reader = iter(file) + c = [] + while True: + l = random.randrange(1, 10) + d = reader.read(l) + if not d: break + assert len(d) <= l + c.append(d) + c = "".join(c) + + d = [] + reader.seek(0) + for line in reader: + d.append(line) + d = "".join(d) + + assert a == b == c == d, map(hash, [a,b,c,d]) + assert len(a) == file.unpacked_size + + repr(iter(file)) + + + reader.seek(0) + a = reader.readlines() + + reader.seek(0) + b = list(reader) + + assert a == b diff --git a/dep/libmpq/config.h b/dep/libmpq/config.h new file mode 100644 index 00000000000..c69fb13211b --- /dev/null +++ b/dep/libmpq/config.h @@ -0,0 +1,74 @@ +/* config.h. Generated from config.h.in by configure. */ +/* config.h.in. Generated from configure.ac by autoheader. */ + +/* Define to 1 if you have the header file. */ +#define HAVE_DLFCN_H 1 + +/* Define to 1 if fseeko (and presumably ftello) exists and is declared. */ +#define HAVE_FSEEKO 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_INTTYPES_H 1 + +/* Define to 1 if you have the `bz2' library (-lbz2). */ +#define HAVE_LIBBZ2 1 + +/* Define to 1 if you have the `z' library (-lz). */ +#define HAVE_LIBZ 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_MEMORY_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDINT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDLIB_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRINGS_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRING_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_UNISTD_H 1 + +/* Name of package */ +#define PACKAGE "libmpq" + +/* Define to the address where bug reports for this package should be sent. */ +#define PACKAGE_BUGREPORT "mbroemme@plusserver.de" + +/* Define to the full name of this package. */ +#define PACKAGE_NAME "libmpq" + +/* Define to the full name and version of this package. */ +#define PACKAGE_STRING "libmpq 0.4.2" + +/* Define to the one symbol short name of this package. */ +#define PACKAGE_TARNAME "libmpq" + +/* Define to the version of this package. */ +#define PACKAGE_VERSION "0.4.2" + +/* Define to 1 if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Version number of package */ +#define VERSION "0.4.2" + +/* Number of bits in a file offset, on hosts where this is settable. */ +#define _FILE_OFFSET_BITS 64 + +/* Define to 1 to make fseeko visible on some hosts (e.g. glibc 2.2). */ +/* #undef _LARGEFILE_SOURCE */ + +/* Define for large files, on AIX-style hosts. */ +/* #undef _LARGE_FILES */ diff --git a/dep/libmpq/configure.ac b/dep/libmpq/configure.ac new file mode 100644 index 00000000000..d274eab07c6 --- /dev/null +++ b/dep/libmpq/configure.ac @@ -0,0 +1,84 @@ +# the autoconf initilization. +AC_INIT(libmpq, 0.4.2, [mbroemme@plusserver.de], [libmpq]) + +# detect the canonical host and target build environment. +AC_CANONICAL_SYSTEM + +# initialize autoconf and automake system. +AM_INIT_AUTOMAKE([no-dependencies]) +AC_CONFIG_HEADERS([config.h:config.h.in]) + +# notices. +AC_PREREQ(2.53) +AC_REVISION($Revision: 1.6 $) + +# checking for programs. +AC_PROG_LIBTOOL +AC_PROG_MAKE_SET +AC_PROG_CC +AC_SYS_LARGEFILE +AC_FUNC_FSEEKO + +# check if we need to export some largefile flags. +if test "$enable_largefile" != no; then + if test "$ac_cv_sys_file_offset_bits" != 'no'; then + if test -z "$LFS_CFLAGS" ; then + LFS_CFLAGS="-D_FILE_OFFSET_BITS=$ac_cv_sys_file_offset_bits" + else + LFS_CFLAGS="$LFS_CFLAGS -D_FILE_OFFSET_BITS=$ac_cv_sys_file_offset_bits" + fi + fi + if test "$ac_cv_sys_large_files" != 'no'; then + if test -z "$LFS_CFLAGS" ; then + LFS_CFLAGS="-D_LARGE_FILES=1" + else + LFS_CFLAGS="$LFS_CFLAGS -D_LARGE_FILES=1" + fi + fi + if test "$ac_cv_sys_largefile_source" != 'no'; then + if test -z "$LFS_CFLAGS" ; then + LFS_CFLAGS="-D_LARGEFILE_SOURCE=1" + else + LFS_CFLAGS="$LFS_CFLAGS -D_LARGEFILE_SOURCE=1" + fi + fi +fi + +# export largefile flags. +AC_SUBST(LFS_CFLAGS) + +# check for zlib library. +AC_CHECK_HEADER([zlib.h], [], [AC_MSG_ERROR([*** zlib.h is required, install zlib header files])]) +AC_CHECK_LIB([z], [inflateEnd], [], [AC_MSG_ERROR([*** inflateEnd is required, install zlib library files])]) + +# check for bzlib2 library. +AC_CHECK_HEADER([bzlib.h], [], [AC_MSG_ERROR([*** bzlib.h is required, install bzip2 header files])]) +AC_CHECK_LIB([bz2], [BZ2_bzDecompressInit], [], [AC_MSG_ERROR([*** BZ2_bzDecompressInit is required, install bzip2 library files])]) + +# When we're running gcc 4 or greater, compile with -fvisibility=hidden. +AC_TRY_COMPILE([ +#if !defined(__GNUC__) || (__GNUC__ < 4) +#error not gcc4 +#endif +], [], [CFLAGS="$CFLAGS -fvisibility=hidden"]) + +# find python for binding +AM_PATH_PYTHON([2.4],,[:]) +AM_CONDITIONAL([HAVE_PYTHON], [test "$PYTHON" != :]) + +# configuration files. +AC_CONFIG_FILES([libmpq.pc]) +AC_CONFIG_FILES([libmpq-config],[chmod +x libmpq-config]) + +# creating files. +AC_OUTPUT([ +Makefile +libmpq/Makefile +bindings/Makefile +bindings/d/Makefile +bindings/python/Makefile +doc/Makefile +doc/man1/Makefile +doc/man3/Makefile +tools/Makefile +]) diff --git a/dep/libmpq/debian/changelog b/dep/libmpq/debian/changelog new file mode 100644 index 00000000000..55d2d918755 --- /dev/null +++ b/dep/libmpq/debian/changelog @@ -0,0 +1,35 @@ +libmpq (0.4.2-svn288-1) unstable; urgency=low + + [ babyface ] + * Due to the nature of MPQ archives which can have valid block entries + * removed function libmpq__init() and libmpq__shutdown(), because they + are no longer required and libmpq__file_name(), because it is up to + the application to provide listfile support + * updated documentation to latest API changes + * removed API documentation for removed function prototypes + * removed no longer required files from target + + [ forrestv ] + * mpq.py fix + * spelling - huffmann to huffman + * changed pkware/pkzip to pkzip and used constants instead of numbers + in extract.c + * sanified huffman decoder a bit + * cleanup + update of mpq.py + * Added support for library finding on platforms besides Linux. + * python bindings - sequence methods on Archive, example code + + [ georg ] + * libmpq: file number search now continued over hashtable end + * debian debug package + + -- Georg Lukas Fri, 22 May 2009 22:38:26 +0200 + +libmpq (0.4.2-svn270-1) unstable; urgency=low + + * First debian package + * compatible to new libmpq API (post 0.4.2) + * contains preliminary python-mpq package + + -- Georg Lukas Tue, 07 Oct 2008 14:38:58 +0200 + diff --git a/dep/libmpq/debian/compat b/dep/libmpq/debian/compat new file mode 100644 index 00000000000..7f8f011eb73 --- /dev/null +++ b/dep/libmpq/debian/compat @@ -0,0 +1 @@ +7 diff --git a/dep/libmpq/debian/control b/dep/libmpq/debian/control new file mode 100644 index 00000000000..f35bb060015 --- /dev/null +++ b/dep/libmpq/debian/control @@ -0,0 +1,50 @@ +Source: libmpq +Priority: extra +Maintainer: Georg Lukas +Build-Depends: debhelper (>= 7), autotools-dev, libbz2-dev +Standards-Version: 3.7.3 +Section: libs +Homepage: https://libmpq.org/ + +Package: libmpq-dev +Section: libdevel +Architecture: any +Depends: libmpq0 (= ${binary:Version}) +Description: Headers for libmpq, a library for MoPaQ mpq archives + libmpq is a library for extracting and manipulating MoPaQ mpq archives. + This package provides header files and bindings for applications using + the libmpq library for the following languages: + * C + * Python + * D + +Package: libmpq0 +Section: libs +Architecture: any +Depends: ${shlibs:Depends}, ${misc:Depends} +Description: A library for extracting and manipulating MoPaQ mpq archives + MPQ, or MoPaQ, is a proprietary archive format created by + Mike O'Brien, the man hailed as Blizzard's multiplayer engine + genius, back in 1996 as a general purpose archive for use with + Diablo, and named narcissistically for its creator + "Mike O'brien PaCK". The copyrights to it, however, are held by + Havas Interactive, Blizzard's parent company. The archive format + is used by many Blizzard titles like Diablo, Diablo 2, Starcraft, + Warcraft 2: BNE, a newer version in Warcraft 3 and World of + Warcraft (WoW). + +Package: libmpq0-dbg +Section: libdevel +Architecture: any +Depends: libmpq0 (= ${binary:Version}) +Description: Debug symbols for libmpq0 library package + +Package: python-mpq +Architecture: all +Depends: ${python:Depends} +XB-Python-Version: ${python:Versions} +XS-Python-Version: current +Description: Python bindings for libmpq, a library for MoPaQ mpq archives + libmpq is a library for extracting and manipulating MoPaQ mpq archives. + This package provides the python bindings for libmpq. + diff --git a/dep/libmpq/debian/copyright b/dep/libmpq/debian/copyright new file mode 100644 index 00000000000..f014cf14de7 --- /dev/null +++ b/dep/libmpq/debian/copyright @@ -0,0 +1,23 @@ +This package was debianized by Georg Lukas on +Fri, 04 Jul 2008 18:17:08 +0200. + +It was downloaded from + +Upstream Author: + + Maik Broemme + +Copyright: + + Copyright (C) 2008 Maik Broemme + +License: + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + +The Debian packaging is (C) 2008, Georg Lukas and +is licensed under the GPL, see `/usr/share/common-licenses/GPL'. diff --git a/dep/libmpq/debian/libmpq-dev.dirs b/dep/libmpq/debian/libmpq-dev.dirs new file mode 100644 index 00000000000..7b6c7ee6ec1 --- /dev/null +++ b/dep/libmpq/debian/libmpq-dev.dirs @@ -0,0 +1,6 @@ +usr/bin +usr/lib +usr/lib/pkgconfig +usr/include +usr/share/man/man1 +usr/share/man/man3 diff --git a/dep/libmpq/debian/libmpq-dev.install b/dep/libmpq/debian/libmpq-dev.install new file mode 100644 index 00000000000..4e6ab3278e3 --- /dev/null +++ b/dep/libmpq/debian/libmpq-dev.install @@ -0,0 +1,6 @@ +usr/bin/* +usr/include/* +usr/lib/lib*.a +usr/lib/pkgconfig/* +usr/lib/*.la +usr/share/man/man?/* diff --git a/dep/libmpq/debian/libmpq0.dirs b/dep/libmpq/debian/libmpq0.dirs new file mode 100644 index 00000000000..68457717bd8 --- /dev/null +++ b/dep/libmpq/debian/libmpq0.dirs @@ -0,0 +1 @@ +usr/lib diff --git a/dep/libmpq/debian/libmpq0.docs b/dep/libmpq/debian/libmpq0.docs new file mode 100644 index 00000000000..5ac7060850c --- /dev/null +++ b/dep/libmpq/debian/libmpq0.docs @@ -0,0 +1,6 @@ +FAQ +NEWS +README +TODO +THANKS +AUTHORS diff --git a/dep/libmpq/debian/libmpq0.install b/dep/libmpq/debian/libmpq0.install new file mode 100644 index 00000000000..8aa4466a68e --- /dev/null +++ b/dep/libmpq/debian/libmpq0.install @@ -0,0 +1 @@ +usr/lib/lib*.so* diff --git a/dep/libmpq/debian/python-mpq.install b/dep/libmpq/debian/python-mpq.install new file mode 100644 index 00000000000..a7aba2013b0 --- /dev/null +++ b/dep/libmpq/debian/python-mpq.install @@ -0,0 +1 @@ +usr/lib/python?.? diff --git a/dep/libmpq/debian/rules b/dep/libmpq/debian/rules new file mode 100644 index 00000000000..1e101be5faf --- /dev/null +++ b/dep/libmpq/debian/rules @@ -0,0 +1,112 @@ +#!/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) +ifneq ($(DEB_HOST_GNU_TYPE),$(DEB_BUILD_GNU_TYPE)) +CROSS= --build $(DEB_BUILD_GNU_TYPE) --host $(DEB_HOST_GNU_TYPE) +else +CROSS= --build $(DEB_BUILD_GNU_TYPE) +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. +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 + ./configure $(CROSS) --prefix=/usr --mandir=\$${prefix}/share/man --infodir=\$${prefix}/share/info CFLAGS="$(CFLAGS) -ggdb" LDFLAGS="-Wl,-z,defs" + + +build: build-stamp +build-stamp: config.status + dh_testdir + + # Add here commands to compile the package. + $(MAKE) + + touch $@ + +clean: + dh_testdir + dh_testroot + rm -f build-stamp + + # Add here commands to clean up after the build process. + [ ! -f Makefile ] || $(MAKE) distclean + rm -f config.sub config.guess + + dh_clean + +install: build + dh_testdir + dh_testroot + dh_clean -k + dh_installdirs + + # Add here commands to install the package into debian/tmp + $(MAKE) DESTDIR=$(CURDIR)/debian/tmp install + + +# Build architecture-independent files here. +binary-indep: build install + dh_pysupport usr/lib/python?.?/site-packages + +# Build architecture-dependent files here. +binary-arch: build install + dh_testdir + dh_testroot + dh_installchangelogs + dh_installdocs + dh_installexamples + dh_install +# dh_installmenu +# dh_installdebconf +# dh_installlogrotate +# dh_installemacsen +# dh_installpam +# dh_installmime +# dh_installinit +# dh_installcron +# dh_installinfo + dh_installman + dh_link + dh_strip --dbg-package=libmpq0-dbg + dh_compress + dh_fixperms +# dh_perl + 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/dep/libmpq/doc/Makefile.am b/dep/libmpq/doc/Makefile.am new file mode 100644 index 00000000000..e7ccd5f4518 --- /dev/null +++ b/dep/libmpq/doc/Makefile.am @@ -0,0 +1,5 @@ +# minimum required automake 1.6 +AUTOMAKE_OPTIONS = 1.6 + +# any directories which should be built and installed. +SUBDIRS = man1 man3 diff --git a/dep/libmpq/doc/man1/Makefile.am b/dep/libmpq/doc/man1/Makefile.am new file mode 100644 index 00000000000..055f1aab533 --- /dev/null +++ b/dep/libmpq/doc/man1/Makefile.am @@ -0,0 +1,9 @@ +# minimum required automake 1.6 +AUTOMAKE_OPTIONS = 1.6 + +# manual page directory. +EXTRA_DIST = $(man_MANS) + +# manual pages for the installed binaries. +man_MANS = \ + libmpq-config.1 diff --git a/dep/libmpq/doc/man1/libmpq-config.1 b/dep/libmpq/doc/man1/libmpq-config.1 new file mode 100644 index 00000000000..c025f5ce4f4 --- /dev/null +++ b/dep/libmpq/doc/man1/libmpq-config.1 @@ -0,0 +1,69 @@ +.\" Copyright (c) 2003-2008 Maik Broemme +.\" +.\" This is free documentation; 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. +.\" +.\" The GNU General Public License's references to "object code" +.\" and "executables" are to be interpreted as the output of any +.\" document formatting or typesetting system, including +.\" intermediate and printed output. +.\" +.\" This manual is distributed in the hope that it will be useful, +.\" but WITHOUT ANY WARRANTY; without even the implied warranty of +.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +.\" GNU General Public License for more details. +.\" +.\" You should have received a copy of the GNU General Public +.\" License along with this manual; if not, write to the Free +.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, +.\" USA. +.TH libmpq 1 2008-02-10 "The MoPaQ archive library" +.SH NAME +libmpq-config \- script to get information about the installed version of libmpq. +.SH SYNOPSIS +.B libmpq-config +[\-\-prefix\fI[=DIR]\fP] [\-\-exec\-prefix\fI[=DIR]\fP] [\-\-version] +.br +[\-\-cflags] [\-\-libs] [\-\-static\-libs] +.SH DESCRIPTION +.PP +\fIlibmpq-config\fP is a tool that is used to determine the compiler and linker flags that should be used to compile and link programs that use \fIlibmpq\fP. Finally, it's also used internally by the .m4 macros for GNU autoconf that are included with \fIlibmpq\fP. +.SH OPTIONS +\fIlibmpq-config\fP accepts the following options: +.TP 8 +.B \-\-version +.ti 15 +Print the currently installed version of \fIlibmpq\fP on the standard output. +.TP 8 +.B \-\-libs +.ti 15 +Print the linker flags that are necessary to link \fIlibmpq\fP to a program. +.TP 8 +.B \-\-static\-libs +.ti 15 +Print the linker flags that are necessary to statically link \fIlibmpq\fP to a program. +.TP 8 +.B \-\-cflags +.ti 15 +Print the compiler flags that are necessary to compile a program that use \fIlibmpq\fP. +.TP 8 +.B \-\-prefix=PREFIX +.ti 15 +If specified, use PREFIX instead of the installation prefix that \fIlibmpq\fP was built with when computing the output for the \-\-cflags and \-\-libs options. This option is also used for the exec prefix if \-\-exec\-prefix was not specified. This option must be specified before any \-\-libs or \-\-cflags options. +.TP 8 +.B \-\-exec\-prefix=PREFIX +.ti 15 +If specified, use PREFIX instead of the installation exec prefix that \fIlibmpq\fP was built with when computing the output for the \-\-cflags and \-\-libs options. This option must be specified before any \-\-libs or \-\-cflags options. +.SH NOTE +Instead of using this configuration script you should better use the pkg-config version because this would be more platform independent and makes the usage within GNU autoconf much easier. +.SH SEE ALSO +\fBlibmpq\fR(3) +.SH AUTHOR +Check documentation. +.TP +libmpq is (c) 2003-2008 +.B Maik Broemme +.PP +The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/dep/libmpq/doc/man3/Makefile.am b/dep/libmpq/doc/man3/Makefile.am new file mode 100644 index 00000000000..cad3d865dc1 --- /dev/null +++ b/dep/libmpq/doc/man3/Makefile.am @@ -0,0 +1,31 @@ +# minimum required automake 1.6 +AUTOMAKE_OPTIONS = 1.6 + +# manual page directory. +EXTRA_DIST = $(man_MANS) + +# manual pages for the installed binaries. +man_MANS = \ + libmpq.3 \ + libmpq__archive_close.3 \ + libmpq__archive_files.3 \ + libmpq__archive_offset.3 \ + libmpq__archive_open.3 \ + libmpq__archive_packed_size.3 \ + libmpq__archive_unpacked_size.3 \ + libmpq__archive_version.3 \ + libmpq__block_close_offset.3 \ + libmpq__block_open_offset.3 \ + libmpq__block_read.3 \ + libmpq__block_unpacked_size.3 \ + libmpq__file_blocks.3 \ + libmpq__file_compressed.3 \ + libmpq__file_encrypted.3 \ + libmpq__file_imploded.3 \ + libmpq__file_number.3 \ + libmpq__file_offset.3 \ + libmpq__file_packed_size.3 \ + libmpq__file_read.3 \ + libmpq__file_unpacked_size.3 \ + libmpq__strerror.3 \ + libmpq__version.3 diff --git a/dep/libmpq/doc/man3/libmpq.3 b/dep/libmpq/doc/man3/libmpq.3 new file mode 100644 index 00000000000..768dab0a712 --- /dev/null +++ b/dep/libmpq/doc/man3/libmpq.3 @@ -0,0 +1,207 @@ +.\" Copyright (c) 2003-2008 Maik Broemme +.\" +.\" This is free documentation; 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. +.\" +.\" The GNU General Public License's references to "object code" +.\" and "executables" are to be interpreted as the output of any +.\" document formatting or typesetting system, including +.\" intermediate and printed output. +.\" +.\" This manual is distributed in the hope that it will be useful, +.\" but WITHOUT ANY WARRANTY; without even the implied warranty of +.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +.\" GNU General Public License for more details. +.\" +.\" You should have received a copy of the GNU General Public +.\" License along with this manual; if not, write to the Free +.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, +.\" USA. +.TH libmpq 3 2008-04-29 "The MoPaQ archive library" +.SH NAME +libmpq \- cross-platform C library for manipulating mpq archives. +.SH SYNOPSIS +.nf +.B +#include +.sp +.BI "const char *libmpq__version();" +.sp +.BI "const char *libmpq__strerror(int32_t returncode);" +.sp +.BI "int32_t libmpq__archive_open(" +.BI " mpq_archive_s **" "mpq_archive", +.BI " const char *" "mpq_filename", +.BI " off_t " "archive_offset" +.BI ");" +.sp +.BI "int32_t libmpq__archive_close(" +.BI " mpq_archive_s *" "mpq_archive" +.BI ");" +.sp +.BI "int32_t libmpq__archive_packed_size(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " off_t *" "packed_size" +.BI ");" +.sp +.BI "int32_t libmpq__archive_unpacked_size(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " off_t *" "unpacked_size" +.BI ");" +.sp +.BI "int32_t libmpq__archive_offset(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " off_t *" "offset" +.BI ");" +.sp +.BI "int32_t libmpq__archive_version(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t *" "version" +.BI ");" +.sp +.BI "int32_t libmpq__archive_files(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t *" "files" +.BI ");" +.sp +.BI "int32_t libmpq__file_packed_size(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t " "file_number", +.BI " off_t *" "packed_size" +.BI ");" +.sp +.BI "int32_t libmpq__file_unpacked_size(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t " "file_number", +.BI " off_t *" "unpacked_size" +.BI ");" +.sp +.BI "int32_t libmpq__file_offset(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t " "file_number", +.BI " off_t *" "offset" +.BI ");" +.sp +.BI "int32_t libmpq__file_blocks(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t " "file_number", +.BI " off_t *" "blocks" +.BI ");" +.sp +.BI "int32_t libmpq__file_encrypted(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t " "file_number", +.BI " off_t *" "encrypted" +.BI ");" +.sp +.BI "int32_t libmpq__file_compressed(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t " "file_number", +.BI " off_t *" "compressed" +.BI ");" +.sp +.BI "int32_t libmpq__file_imploded(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t " "file_number", +.BI " off_t *" "imploded" +.BI ");" +.sp +.BI "int32_t libmpq__file_number(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " const char *" "filename", +.BI " uint32_t *" "number" +.BI ");" +.sp +.BI "int32_t libmpq__file_read(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t " "file_number", +.BI " uint8_t *" "out_buf", +.BI " off_t " "out_size", +.BI " off_t *" "transferred" +.BI ");" +.sp +.BI "int32_t libmpq__block_open_offset(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t " "file_number" +.BI ");" +.sp +.BI "int32_t libmpq__block_close_offset(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t " "file_number" +.BI ");" +.sp +.BI "int32_t libmpq__block_packed_size(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t " "file_number", +.BI " uint32_t " "block_number", +.BI " off_t *" "packed_size" +.BI ");" +.sp +.BI "int32_t libmpq__block_unpacked_size(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t " "file_number", +.BI " uint32_t " "block_number", +.BI " off_t *" "unpacked_size" +.BI ");" +.sp +.BI "int32_t libmpq__block_offset(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t " "file_number", +.BI " uint32_t " "block_number", +.BI " off_t *" "offset" +.BI ");" +.sp +.BI "int32_t libmpq__block_seed(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t " "file_number", +.BI " uint32_t " "block_number", +.BI " uint32_t *" "seed" +.BI ");" +.sp +.BI "int32_t libmpq__block_read(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t " "file_number", +.BI " uint32_t " "block_number", +.BI " uint8_t *" "out_buf", +.BI " off_t " "out_size", +.BI " off_t *" "transferred" +.BI ");" +.fi +.SH DESCRIPTION +.PP +The \fIlibmpq\fP library supports decrypting, decompressing, exploding and various manipulations of the MoPaQ archive files. It uses \fIzlib(3)\fP and \fIbzip2(1)\fP compression library. At this moment \fIlibmpq\fP is not able to create MoPaQ archives, this limitation will be removed in a future version. +.SH SEE ALSO +.BR libmpq__version (3), +.BR libmpq__strerror (3), +.BR libmpq__archive_open (3), +.BR libmpq__archive_close (3), +.BR libmpq__archive_packed_size (3), +.BR libmpq__archive_unpacked_size (3), +.BR libmpq__archive_offset (3), +.BR libmpq__archive_version (3), +.BR libmpq__archive_files (3), +.BR libmpq__file_packed_size (3), +.BR libmpq__file_unpacked_size (3), +.BR libmpq__file_offset (3), +.BR libmpq__file_blocks (3), +.BR libmpq__file_encrypted (3), +.BR libmpq__file_compressed (3), +.BR libmpq__file_imploded (3), +.BR libmpq__file_number (3), +.BR libmpq__file_read (3), +.BR libmpq__block_open_offset (3), +.BR libmpq__block_close_offset (3), +.BR libmpq__block_packed_size (3), +.BR libmpq__block_unpacked_size (3), +.BR libmpq__block_offset (3), +.BR libmpq__block_seed (3), +.BR libmpq__block_read (3) +.SH AUTHOR +Check documentation. +.TP +libmpq is (c) 2003-2008 +.B Maik Broemme +.PP +The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/dep/libmpq/doc/man3/libmpq__archive_close.3 b/dep/libmpq/doc/man3/libmpq__archive_close.3 new file mode 100644 index 00000000000..dfc652a6721 --- /dev/null +++ b/dep/libmpq/doc/man3/libmpq__archive_close.3 @@ -0,0 +1,57 @@ +.\" Copyright (c) 2003-2008 Maik Broemme +.\" +.\" This is free documentation; 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. +.\" +.\" The GNU General Public License's references to "object code" +.\" and "executables" are to be interpreted as the output of any +.\" document formatting or typesetting system, including +.\" intermediate and printed output. +.\" +.\" This manual is distributed in the hope that it will be useful, +.\" but WITHOUT ANY WARRANTY; without even the implied warranty of +.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +.\" GNU General Public License for more details. +.\" +.\" You should have received a copy of the GNU General Public +.\" License along with this manual; if not, write to the Free +.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, +.\" USA. +.TH libmpq 3 2008-04-29 "The MoPaQ archive library" +.SH NAME +libmpq \- cross-platform C library for manipulating mpq archives. +.SH SYNOPSIS +.nf +.B +#include +.sp +.BI "int32_t libmpq__archive_close(" +.BI " mpq_archive_s *" "mpq_archive" +.BI ");" +.fi +.SH DESCRIPTION +.PP +Call \fBlibmpq__archive_close\fP() to close a mpq archive which was opened by \fBlibmpq__archive_open\fP(). The function frees the archive structure itself and the contents of it. +.LP +The \fBlibmpq__archive_close\fP() function one takes one argument of the archive structure \fImpq_archive\fP which has to be set by \fBlibmpq__archive_open\fP. +.SH RETURN VALUE +On success, a zero is returned and on error one of the following constants. +.TP +.B LIBMPQ_ERROR_CLOSE +The given file could not be closed. +.SH SEE ALSO +.BR libmpq__archive_open (3), +.BR libmpq__archive_packed_size (3), +.BR libmpq__archive_unpacked_size (3), +.BR libmpq__archive_offset (3), +.BR libmpq__archive_version (3), +.BR libmpq__archive_files (3) +.SH AUTHOR +Check documentation. +.TP +libmpq is (c) 2003-2008 +.B Maik Broemme +.PP +The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/dep/libmpq/doc/man3/libmpq__archive_files.3 b/dep/libmpq/doc/man3/libmpq__archive_files.3 new file mode 100644 index 00000000000..6663b99161a --- /dev/null +++ b/dep/libmpq/doc/man3/libmpq__archive_files.3 @@ -0,0 +1,50 @@ +.\" Copyright (c) 2003-2008 Maik Broemme +.\" +.\" This is free documentation; 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. +.\" +.\" The GNU General Public License's references to "object code" +.\" and "executables" are to be interpreted as the output of any +.\" document formatting or typesetting system, including +.\" intermediate and printed output. +.\" +.\" This manual is distributed in the hope that it will be useful, +.\" but WITHOUT ANY WARRANTY; without even the implied warranty of +.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +.\" GNU General Public License for more details. +.\" +.\" You should have received a copy of the GNU General Public +.\" License along with this manual; if not, write to the Free +.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, +.\" USA. +.TH libmpq 3 2008-05-14 "The MoPaQ archive library" +.SH NAME +libmpq \- cross-platform C library for manipulating mpq archives. +.SH SYNOPSIS +.nf +.B +#include +.sp +.BI "int32_t libmpq__archive_files(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t *" "files" +.BI ");" +.fi +.SH DESCRIPTION +.PP +Call \fBlibmpq__archive_files\fP() to get the number of files inside the archive. It will count only valid files and skip files which have deleted or freed hash entries. +.LP +The \fBlibmpq__archive_files\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument is a reference to the number of \fIfiles\fP in the archive. +.SH RETURN VALUE +On success, a zero is returned. +.SH SEE ALSO +.BR libmpq__file_blocks (3) +.SH AUTHOR +Check documentation. +.TP +libmpq is (c) 2003-2008 +.B Maik Broemme +.PP +The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/dep/libmpq/doc/man3/libmpq__archive_offset.3 b/dep/libmpq/doc/man3/libmpq__archive_offset.3 new file mode 100644 index 00000000000..696ac5e809f --- /dev/null +++ b/dep/libmpq/doc/man3/libmpq__archive_offset.3 @@ -0,0 +1,51 @@ +.\" Copyright (c) 2003-2008 Maik Broemme +.\" +.\" This is free documentation; 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. +.\" +.\" The GNU General Public License's references to "object code" +.\" and "executables" are to be interpreted as the output of any +.\" document formatting or typesetting system, including +.\" intermediate and printed output. +.\" +.\" This manual is distributed in the hope that it will be useful, +.\" but WITHOUT ANY WARRANTY; without even the implied warranty of +.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +.\" GNU General Public License for more details. +.\" +.\" You should have received a copy of the GNU General Public +.\" License along with this manual; if not, write to the Free +.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, +.\" USA. +.TH libmpq 3 2008-05-14 "The MoPaQ archive library" +.SH NAME +libmpq \- cross-platform C library for manipulating mpq archives. +.SH SYNOPSIS +.nf +.B +#include +.sp +.BI "int32_t libmpq__archive_offset(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " off_t *" "offset" +.BI ");" +.fi +.SH DESCRIPTION +.PP +Call \fBlibmpq__archive_offset\fP() to get the offset of the archive, which is the absolute position in the file. It also supports archives within archives. +.LP +The \fBlibmpq__archive_offset\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument is a reference to the archive starting position \fIoffset\fP in file. +.SH RETURN VALUE +On success, a zero is returned. +.SH SEE ALSO +.BR libmpq__file_offset (3), +.BR libmpq__block_offset (3) +.SH AUTHOR +Check documentation. +.TP +libmpq is (c) 2003-2008 +.B Maik Broemme +.PP +The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/dep/libmpq/doc/man3/libmpq__archive_open.3 b/dep/libmpq/doc/man3/libmpq__archive_open.3 new file mode 100644 index 00000000000..02c021f8948 --- /dev/null +++ b/dep/libmpq/doc/man3/libmpq__archive_open.3 @@ -0,0 +1,71 @@ +.\" Copyright (c) 2003-2008 Maik Broemme +.\" +.\" This is free documentation; 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. +.\" +.\" The GNU General Public License's references to "object code" +.\" and "executables" are to be interpreted as the output of any +.\" document formatting or typesetting system, including +.\" intermediate and printed output. +.\" +.\" This manual is distributed in the hope that it will be useful, +.\" but WITHOUT ANY WARRANTY; without even the implied warranty of +.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +.\" GNU General Public License for more details. +.\" +.\" You should have received a copy of the GNU General Public +.\" License along with this manual; if not, write to the Free +.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, +.\" USA. +.TH libmpq 3 2008-04-29 "The MoPaQ archive library" +.SH NAME +libmpq \- cross-platform C library for manipulating mpq archives. +.SH SYNOPSIS +.nf +.B +#include +.sp +.BI "int32_t libmpq__archive_open(" +.BI " mpq_archive_s **" "mpq_archive", +.BI " const char *" "mpq_filename", +.BI " off_t " "archive_offset" +.BI ");" +.fi +.SH DESCRIPTION +.PP +Call \fBlibmpq__archive_open\fP() to open a given mpq archive for later use to extract or manipulate files inside the archive. It will create all required file structures and you have to call \fBlibmpq__archive_close\fP() on success to clean the opened structures. On failure there is no need to call \fBlibmpq__archive_close\fP() because everything will be cleaned up. +.LP +The \fBlibmpq__archive_open\fP() function takes as first argument a reference to the archive structure \fImpq_archive\fP and will open the file \fImpq_filename\fP to the structure pointed to by \fImpq_archive\fP. The last argument, \fIarchive_offset\fP is normally -1, but can be specified when the archive offset is known, or not 512-byte aligned. +.SH RETURN VALUE +On success, *\fImpq_archive\fP is set to a new \fBmpq_archive_s\fP* and zero is returned, and on error one of the following constants is returned. +.TP +.B LIBMPQ_ERROR_OPEN +The given file could not be opened. +.TP +.B LIBMPQ_ERROR_MALLOC +Not enough memory for creating required structures. +.TP +.B LIBMPQ_ERROR_SEEK +Seeking in file failed. +.TP +.B LIBMPQ_ERROR_FORMAT +The given file is no valid mpq archive. +.TP +.B LIBMPQ_ERROR_READ +Reading in archive failed. +.SH SEE ALSO +.BR libmpq__archive_close (3), +.BR libmpq__archive_packed_size (3), +.BR libmpq__archive_unpacked_size (3), +.BR libmpq__archive_offset (3), +.BR libmpq__archive_version (3), +.BR libmpq__archive_files (3) +.SH AUTHOR +Check documentation. +.TP +libmpq is (c) 2003-2008 +.B Maik Broemme +.PP +The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/dep/libmpq/doc/man3/libmpq__archive_packed_size.3 b/dep/libmpq/doc/man3/libmpq__archive_packed_size.3 new file mode 100644 index 00000000000..6c3061f2031 --- /dev/null +++ b/dep/libmpq/doc/man3/libmpq__archive_packed_size.3 @@ -0,0 +1,51 @@ +.\" Copyright (c) 2003-2008 Maik Broemme +.\" +.\" This is free documentation; 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. +.\" +.\" The GNU General Public License's references to "object code" +.\" and "executables" are to be interpreted as the output of any +.\" document formatting or typesetting system, including +.\" intermediate and printed output. +.\" +.\" This manual is distributed in the hope that it will be useful, +.\" but WITHOUT ANY WARRANTY; without even the implied warranty of +.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +.\" GNU General Public License for more details. +.\" +.\" You should have received a copy of the GNU General Public +.\" License along with this manual; if not, write to the Free +.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, +.\" USA. +.TH libmpq 3 2008-04-29 "The MoPaQ archive library" +.SH NAME +libmpq \- cross-platform C library for manipulating mpq archives. +.SH SYNOPSIS +.nf +.B +#include +.sp +.BI "int32_t libmpq__archive_packed_size(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " off_t *" "packed_size" +.BI ");" +.fi +.SH DESCRIPTION +.PP +Call \fBlibmpq__archive_packed_size\fP() to get the packed size of all files in the archive. It will count compressed and imploded files as well as stored only. +.LP +The \fBlibmpq__archive_packed_size\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument is a reference to the compressed, imploded or stored size \fIpacked_size\fP of file. +.SH RETURN VALUE +On success, a zero is returned. +.SH SEE ALSO +.BR libmpq__file_packed_size (3), +.BR libmpq__block_packed_size (3) +.SH AUTHOR +Check documentation. +.TP +libmpq is (c) 2003-2008 +.B Maik Broemme +.PP +The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/dep/libmpq/doc/man3/libmpq__archive_unpacked_size.3 b/dep/libmpq/doc/man3/libmpq__archive_unpacked_size.3 new file mode 100644 index 00000000000..d2ba923c8f0 --- /dev/null +++ b/dep/libmpq/doc/man3/libmpq__archive_unpacked_size.3 @@ -0,0 +1,51 @@ +.\" Copyright (c) 2003-2008 Maik Broemme +.\" +.\" This is free documentation; 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. +.\" +.\" The GNU General Public License's references to "object code" +.\" and "executables" are to be interpreted as the output of any +.\" document formatting or typesetting system, including +.\" intermediate and printed output. +.\" +.\" This manual is distributed in the hope that it will be useful, +.\" but WITHOUT ANY WARRANTY; without even the implied warranty of +.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +.\" GNU General Public License for more details. +.\" +.\" You should have received a copy of the GNU General Public +.\" License along with this manual; if not, write to the Free +.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, +.\" USA. +.TH libmpq 3 2008-04-29 "The MoPaQ archive library" +.SH NAME +libmpq \- cross-platform C library for manipulating mpq archives. +.SH SYNOPSIS +.nf +.B +#include +.sp +.BI "int32_t libmpq__archive_unpacked_size(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " off_t *" "unpacked_size" +.BI ");" +.fi +.SH DESCRIPTION +.PP +Call \fBlibmpq__archive_unpacked_size\fP() to get the unpacked size of all files in the archive. It will count uncompressed and exploded files as well as stored only. +.LP +The \fBlibmpq__archive_unpacked_size\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument is a reference to the uncompressed, exploded or stored size \fIunpacked_size\fP of file. +.SH RETURN VALUE +On success, a zero is returned. +.SH SEE ALSO +.BR libmpq__file_unpacked_size (3), +.BR libmpq__block_unpacked_size (3) +.SH AUTHOR +Check documentation. +.TP +libmpq is (c) 2003-2008 +.B Maik Broemme +.PP +The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/dep/libmpq/doc/man3/libmpq__archive_version.3 b/dep/libmpq/doc/man3/libmpq__archive_version.3 new file mode 100644 index 00000000000..1764046895a --- /dev/null +++ b/dep/libmpq/doc/man3/libmpq__archive_version.3 @@ -0,0 +1,48 @@ +.\" Copyright (c) 2003-2008 Maik Broemme +.\" +.\" This is free documentation; 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. +.\" +.\" The GNU General Public License's references to "object code" +.\" and "executables" are to be interpreted as the output of any +.\" document formatting or typesetting system, including +.\" intermediate and printed output. +.\" +.\" This manual is distributed in the hope that it will be useful, +.\" but WITHOUT ANY WARRANTY; without even the implied warranty of +.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +.\" GNU General Public License for more details. +.\" +.\" You should have received a copy of the GNU General Public +.\" License along with this manual; if not, write to the Free +.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, +.\" USA. +.TH libmpq 3 2008-05-14 "The MoPaQ archive library" +.SH NAME +libmpq \- cross-platform C library for manipulating mpq archives. +.SH SYNOPSIS +.nf +.B +#include +.sp +.BI "int32_t libmpq__archive_version(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t *" "version" +.BI ");" +.fi +.SH DESCRIPTION +.PP +Call \fBlibmpq__archive_version\fP() to get the archive version. Currently there exist two known versions, version 1 which supports archives until 2GB total size and version 2 which supports archives above 2GB total size and both are supported. +.LP +The \fBlibmpq__archive_version\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument is a reference to the \fIversion\fP of archive. +.SH RETURN VALUE +On success, a zero is returned. +.SH AUTHOR +Check documentation. +.TP +libmpq is (c) 2003-2008 +.B Maik Broemme +.PP +The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/dep/libmpq/doc/man3/libmpq__block_close_offset.3 b/dep/libmpq/doc/man3/libmpq__block_close_offset.3 new file mode 100644 index 00000000000..1ec0c06f70d --- /dev/null +++ b/dep/libmpq/doc/man3/libmpq__block_close_offset.3 @@ -0,0 +1,53 @@ +.\" Copyright (c) 2003-2008 Maik Broemme +.\" +.\" This is free documentation; 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. +.\" +.\" The GNU General Public License's references to "object code" +.\" and "executables" are to be interpreted as the output of any +.\" document formatting or typesetting system, including +.\" intermediate and printed output. +.\" +.\" This manual is distributed in the hope that it will be useful, +.\" but WITHOUT ANY WARRANTY; without even the implied warranty of +.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +.\" GNU General Public License for more details. +.\" +.\" You should have received a copy of the GNU General Public +.\" License along with this manual; if not, write to the Free +.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, +.\" USA. +.TH libmpq 3 2008-05-16 "The MoPaQ archive library" +.SH NAME +libmpq \- cross-platform C library for manipulating mpq archives. +.SH SYNOPSIS +.nf +.B +#include +.sp +.BI "int32_t libmpq__block_close_offset(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t " "file_number" +.BI ");" +.fi +.SH DESCRIPTION +.PP +Call \fBlibmpq__block_close_offset\fP() to close the block offset table for the given file. It will close the block offset table regardless of compression (compressed, imploded or stored) type of file. +.LP +The \fBlibmpq__block_close_offset\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument \fIfile_number\fP is the number of file to close. +.SH RETURN VALUE +On success, a zero is returned and on error one of the following constants. +.TP +.B LIBMPQ_ERROR_EXIST +File or block does not exist in archive. +.SH SEE ALSO +.BR libmpq__block_open_offset (3) +.SH AUTHOR +Check documentation. +.TP +libmpq is (c) 2003-2008 +.B Maik Broemme +.PP +The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/dep/libmpq/doc/man3/libmpq__block_open_offset.3 b/dep/libmpq/doc/man3/libmpq__block_open_offset.3 new file mode 100644 index 00000000000..a60b133f406 --- /dev/null +++ b/dep/libmpq/doc/man3/libmpq__block_open_offset.3 @@ -0,0 +1,65 @@ +.\" Copyright (c) 2003-2008 Maik Broemme +.\" +.\" This is free documentation; 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. +.\" +.\" The GNU General Public License's references to "object code" +.\" and "executables" are to be interpreted as the output of any +.\" document formatting or typesetting system, including +.\" intermediate and printed output. +.\" +.\" This manual is distributed in the hope that it will be useful, +.\" but WITHOUT ANY WARRANTY; without even the implied warranty of +.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +.\" GNU General Public License for more details. +.\" +.\" You should have received a copy of the GNU General Public +.\" License along with this manual; if not, write to the Free +.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, +.\" USA. +.TH libmpq 3 2008-05-16 "The MoPaQ archive library" +.SH NAME +libmpq \- cross-platform C library for manipulating mpq archives. +.SH SYNOPSIS +.nf +.B +#include +.sp +.BI "int32_t libmpq__block_open_offset(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t " "file_number" +.BI ");" +.fi +.SH DESCRIPTION +.PP +Call \fBlibmpq__block_open_offset\fP() to open the block offset table for the given file. It will open the block offset table regardless of compression (compressed, imploded or stored) type of file. +.LP +The \fBlibmpq__block_open_offset\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument \fIfile_number\fP is the number of file to open. +.SH RETURN VALUE +On success, a zero is returned and on error one of the following constants. +.TP +.B LIBMPQ_ERROR_EXIST +File or block does not exist in archive. +.TP +.B LIBMPQ_ERROR_SEEK +Seeking in file failed. +.TP +.B LIBMPQ_ERROR_MALLOC +Not enough memory for creating required structures. +.TP +.B LIBMPQ_ERROR_READ +Reading in archive failed. +.TP +.B LIBMPQ_ERROR_DECRYPT +Decrypting block failed. +.SH SEE ALSO +.BR libmpq__block_close_offset (3) +.SH AUTHOR +Check documentation. +.TP +libmpq is (c) 2003-2008 +.B Maik Broemme +.PP +The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/dep/libmpq/doc/man3/libmpq__block_read.3 b/dep/libmpq/doc/man3/libmpq__block_read.3 new file mode 100644 index 00000000000..3272c64c7ed --- /dev/null +++ b/dep/libmpq/doc/man3/libmpq__block_read.3 @@ -0,0 +1,78 @@ +.\" Copyright (c) 2003-2008 Maik Broemme +.\" +.\" This is free documentation; 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. +.\" +.\" The GNU General Public License's references to "object code" +.\" and "executables" are to be interpreted as the output of any +.\" document formatting or typesetting system, including +.\" intermediate and printed output. +.\" +.\" This manual is distributed in the hope that it will be useful, +.\" but WITHOUT ANY WARRANTY; without even the implied warranty of +.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +.\" GNU General Public License for more details. +.\" +.\" You should have received a copy of the GNU General Public +.\" License along with this manual; if not, write to the Free +.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, +.\" USA. +.TH libmpq 3 2008-05-16 "The MoPaQ archive library" +.SH NAME +libmpq \- cross-platform C library for manipulating mpq archives. +.SH SYNOPSIS +.nf +.B +#include +.sp +.BI "int32_t libmpq__block_read(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t " "file_number", +.BI " uint32_t " "block_number, +.BI " uint8_t *" "out_buf", +.BI " off_t " "out_size", +.BI " off_t " "transferred" +.BI ");" +.fi +.SH DESCRIPTION +.PP +Call \fBlibmpq__block_read\fP() to read a given block into memory. If the block is encrypted it will be first decrypted and then if it is packed (compressed or imploded) it will be unpacked. +.LP +The \fBlibmpq__block_read\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument \fIfile_number\fP is the number of file, the third argument \fIblock_number\fP is the number of block. The fourth argument \fIout_buf\fP is the output data buffer which contains the extracted data and the fifth argument \fIout_size\fP is the size of \fIout_buf\fP. The sixth argument is a reference to the \fItransferred\fP bytes of the file. +.SH RETURN VALUE +On success, a zero is returned and on error one of the following constants. +.TP +.B LIBMPQ_ERROR_EXIST +Block does not exist in archive. +.TP +.B LIBMPQ_ERROR_OPEN +Block offset table was not opened by calling \fBlibmpq__block_open_offset\fP(), or it was closed by an \fBlibmpq__block_close_offset\fP() call. +.TP +.B LIBMPQ_ERROR_SIZE +The output buffer is to small. +.TP +.B LIBMPQ_ERROR_SEEK +Seeking in file failed. +.TP +.B LIBMPQ_ERROR_MALLOC +Not enough memory for creating required structures. +.TP +.B LIBMPQ_ERROR_READ +Reading in archive failed. +.TP +.B LIBMPQ_ERROR_DECRYPT +Decrypting block failed. +.TP +.B LIBMPQ_ERROR_UNPACK +Unpacking block failed. +.SH SEE ALSO +.BR libmpq__file_read (3) +.SH AUTHOR +Check documentation. +.TP +libmpq is (c) 2003-2008 +.B Maik Broemme +.PP +The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/dep/libmpq/doc/man3/libmpq__block_unpacked_size.3 b/dep/libmpq/doc/man3/libmpq__block_unpacked_size.3 new file mode 100644 index 00000000000..a21ca48159a --- /dev/null +++ b/dep/libmpq/doc/man3/libmpq__block_unpacked_size.3 @@ -0,0 +1,59 @@ +.\" Copyright (c) 2003-2008 Maik Broemme +.\" +.\" This is free documentation; 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. +.\" +.\" The GNU General Public License's references to "object code" +.\" and "executables" are to be interpreted as the output of any +.\" document formatting or typesetting system, including +.\" intermediate and printed output. +.\" +.\" This manual is distributed in the hope that it will be useful, +.\" but WITHOUT ANY WARRANTY; without even the implied warranty of +.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +.\" GNU General Public License for more details. +.\" +.\" You should have received a copy of the GNU General Public +.\" License along with this manual; if not, write to the Free +.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, +.\" USA. +.TH libmpq 3 2008-05-16 "The MoPaQ archive library" +.SH NAME +libmpq \- cross-platform C library for manipulating mpq archives. +.SH SYNOPSIS +.nf +.B +#include +.sp +.BI "int32_t libmpq__block_unpacked_size(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t " "file_number", +.BI " uint32_t " "block_number", +.BI " off_t *" "unpacked_size" +.BI ");" +.fi +.SH DESCRIPTION +.PP +Call \fBlibmpq__block_unpacked_size\fP() to get the unpacked size of a given block in the file. It will return a valid size for compressed and imploded blocks as well as stored only. +.LP +The \fBlibmpq__block_unpacked_size\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument \fIfile_number\fP is the number of file, the third argument \fIblock_number\fP is the number of block and the fourth argument is a reference to the uncompressed, exploded or stored size \fIunpacked_size\fP of block. +.SH RETURN VALUE +On success, a zero is returned and on error one of the following constants. +.TP +.B LIBMPQ_ERROR_EXIST +File or block does not exist in archive. +.TP +.B LIBMPQ_ERROR_OPEN +Block offset table was not opened by calling \fBlibmpq__block_open_offset\fP(), or it was closed by an \fBlibmpq__block_close_offset\fP() call. +.SH SEE ALSO +.BR libmpq__archive_unpacked_size (3), +.BR libmpq__file_unpacked_size (3) +.SH AUTHOR +Check documentation. +.TP +libmpq is (c) 2003-2008 +.B Maik Broemme +.PP +The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/dep/libmpq/doc/man3/libmpq__file_blocks.3 b/dep/libmpq/doc/man3/libmpq__file_blocks.3 new file mode 100644 index 00000000000..85baeffc603 --- /dev/null +++ b/dep/libmpq/doc/man3/libmpq__file_blocks.3 @@ -0,0 +1,54 @@ +.\" Copyright (c) 2003-2008 Maik Broemme +.\" +.\" This is free documentation; 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. +.\" +.\" The GNU General Public License's references to "object code" +.\" and "executables" are to be interpreted as the output of any +.\" document formatting or typesetting system, including +.\" intermediate and printed output. +.\" +.\" This manual is distributed in the hope that it will be useful, +.\" but WITHOUT ANY WARRANTY; without even the implied warranty of +.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +.\" GNU General Public License for more details. +.\" +.\" You should have received a copy of the GNU General Public +.\" License along with this manual; if not, write to the Free +.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, +.\" USA. +.TH libmpq 3 2008-05-16 "The MoPaQ archive library" +.SH NAME +libmpq \- cross-platform C library for manipulating mpq archives. +.SH SYNOPSIS +.nf +.B +#include +.sp +.BI "int32_t libmpq__file_blocks(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t " "file_number", +.BI " uint32_t *" "blocks" +.BI ");" +.fi +.SH DESCRIPTION +.PP +Call \fBlibmpq__file_blocks\fP() to get the number of blocks for a given file. It will count all blocks for files stored in multiple sectors or count one for files stored in single sector. +.LP +The \fBlibmpq__file_blocks\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument \fIfile_number\fP is the number of file and the third argument is a reference to the number of \fIblocks\fP of the file. +.SH RETURN VALUE +On success, a zero is returned and on error one of the following constants. +.TP +.B LIBMPQ_ERROR_EXIST +File does not exist in archive. +.SH SEE ALSO +.BR libmpq__archive_files (3) +.SH AUTHOR +Check documentation. +.TP +libmpq is (c) 2003-2008 +.B Maik Broemme +.PP +The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/dep/libmpq/doc/man3/libmpq__file_compressed.3 b/dep/libmpq/doc/man3/libmpq__file_compressed.3 new file mode 100644 index 00000000000..24b44f0b666 --- /dev/null +++ b/dep/libmpq/doc/man3/libmpq__file_compressed.3 @@ -0,0 +1,54 @@ +.\" Copyright (c) 2003-2008 Maik Broemme +.\" +.\" This is free documentation; 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. +.\" +.\" The GNU General Public License's references to "object code" +.\" and "executables" are to be interpreted as the output of any +.\" document formatting or typesetting system, including +.\" intermediate and printed output. +.\" +.\" This manual is distributed in the hope that it will be useful, +.\" but WITHOUT ANY WARRANTY; without even the implied warranty of +.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +.\" GNU General Public License for more details. +.\" +.\" You should have received a copy of the GNU General Public +.\" License along with this manual; if not, write to the Free +.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, +.\" USA. +.TH libmpq 3 2008-05-16 "The MoPaQ archive library" +.SH NAME +libmpq \- cross-platform C library for manipulating mpq archives. +.SH SYNOPSIS +.nf +.B +#include +.sp +.BI "int32_t libmpq__file_compressed(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t " "file_number", +.BI " uint32_t *" "compressed" +.BI ");" +.fi +.SH DESCRIPTION +.PP +Call \fBlibmpq__file_compressed\fP() to get the compression status of the given file. It will return true for compressed files and false otherwise. +.LP +The \fBlibmpq__file_compressed\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument \fIfile_number\fP is the number of file and the third argument is a reference to the compression status \fIcompressed\fP of the file. +.SH RETURN VALUE +On success, a zero is returned and on error one of the following constants. +.TP +.B LIBMPQ_ERROR_EXIST +File does not exist in archive. +.SH SEE ALSO +.BR libmpq__archive_files (3) +.SH AUTHOR +Check documentation. +.TP +libmpq is (c) 2003-2008 +.B Maik Broemme +.PP +The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/dep/libmpq/doc/man3/libmpq__file_encrypted.3 b/dep/libmpq/doc/man3/libmpq__file_encrypted.3 new file mode 100644 index 00000000000..798f4019c7a --- /dev/null +++ b/dep/libmpq/doc/man3/libmpq__file_encrypted.3 @@ -0,0 +1,54 @@ +.\" Copyright (c) 2003-2008 Maik Broemme +.\" +.\" This is free documentation; 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. +.\" +.\" The GNU General Public License's references to "object code" +.\" and "executables" are to be interpreted as the output of any +.\" document formatting or typesetting system, including +.\" intermediate and printed output. +.\" +.\" This manual is distributed in the hope that it will be useful, +.\" but WITHOUT ANY WARRANTY; without even the implied warranty of +.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +.\" GNU General Public License for more details. +.\" +.\" You should have received a copy of the GNU General Public +.\" License along with this manual; if not, write to the Free +.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, +.\" USA. +.TH libmpq 3 2008-05-16 "The MoPaQ archive library" +.SH NAME +libmpq \- cross-platform C library for manipulating mpq archives. +.SH SYNOPSIS +.nf +.B +#include +.sp +.BI "int32_t libmpq__file_encrypted(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t " "file_number", +.BI " uint32_t *" "encrypted" +.BI ");" +.fi +.SH DESCRIPTION +.PP +Call \fBlibmpq__file_encrypted\fP() to get the encryption status of the given file. It will return true for encrypted files and false otherwise. +.LP +The \fBlibmpq__file_encrypted\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument \fIfile_number\fP is the number of file and the third argument is a reference to the encryption status \fIencrypted\fP of the file. +.SH RETURN VALUE +On success, a zero is returned and on error one of the following constants. +.TP +.B LIBMPQ_ERROR_EXIST +File does not exist in archive. +.SH SEE ALSO +.BR libmpq__archive_files (3) +.SH AUTHOR +Check documentation. +.TP +libmpq is (c) 2003-2008 +.B Maik Broemme +.PP +The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/dep/libmpq/doc/man3/libmpq__file_imploded.3 b/dep/libmpq/doc/man3/libmpq__file_imploded.3 new file mode 100644 index 00000000000..9adce38cb5f --- /dev/null +++ b/dep/libmpq/doc/man3/libmpq__file_imploded.3 @@ -0,0 +1,54 @@ +.\" Copyright (c) 2003-2008 Maik Broemme +.\" +.\" This is free documentation; 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. +.\" +.\" The GNU General Public License's references to "object code" +.\" and "executables" are to be interpreted as the output of any +.\" document formatting or typesetting system, including +.\" intermediate and printed output. +.\" +.\" This manual is distributed in the hope that it will be useful, +.\" but WITHOUT ANY WARRANTY; without even the implied warranty of +.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +.\" GNU General Public License for more details. +.\" +.\" You should have received a copy of the GNU General Public +.\" License along with this manual; if not, write to the Free +.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, +.\" USA. +.TH libmpq 3 2008-05-16 "The MoPaQ archive library" +.SH NAME +libmpq \- cross-platform C library for manipulating mpq archives. +.SH SYNOPSIS +.nf +.B +#include +.sp +.BI "int32_t libmpq__file_imploded(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t " "file_number", +.BI " uint32_t *" "imploded" +.BI ");" +.fi +.SH DESCRIPTION +.PP +Call \fBlibmpq__file_imploded\fP() to get the implosion status of the given file. It will return true for imploded files and false otherwise. +.LP +The \fBlibmpq__file_imploded\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument \fIfile_number\fP is the number of file and the third argument is a reference to the implosion status \fIimploded\fP of the file. +.SH RETURN VALUE +On success, a zero is returned and on error one of the following constants. +.TP +.B LIBMPQ_ERROR_EXIST +File does not exist in archive. +.SH SEE ALSO +.BR libmpq__archive_files (3) +.SH AUTHOR +Check documentation. +.TP +libmpq is (c) 2003-2008 +.B Maik Broemme +.PP +The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/dep/libmpq/doc/man3/libmpq__file_number.3 b/dep/libmpq/doc/man3/libmpq__file_number.3 new file mode 100644 index 00000000000..8d7a47769ee --- /dev/null +++ b/dep/libmpq/doc/man3/libmpq__file_number.3 @@ -0,0 +1,52 @@ +.\" Copyright (c) 2003-2008 Maik Broemme +.\" +.\" This is free documentation; 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. +.\" +.\" The GNU General Public License's references to "object code" +.\" and "executables" are to be interpreted as the output of any +.\" document formatting or typesetting system, including +.\" intermediate and printed output. +.\" +.\" This manual is distributed in the hope that it will be useful, +.\" but WITHOUT ANY WARRANTY; without even the implied warranty of +.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +.\" GNU General Public License for more details. +.\" +.\" You should have received a copy of the GNU General Public +.\" License along with this manual; if not, write to the Free +.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, +.\" USA. +.TH libmpq 3 2008-05-16 "The MoPaQ archive library" +.SH NAME +libmpq \- cross-platform C library for manipulating mpq archives. +.SH SYNOPSIS +.nf +.B +#include +.sp +.BI "int32_t libmpq__file_number(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " const char *" "filename", +.BI " uint32_t *" "number" +.BI ");" +.fi +.SH DESCRIPTION +.PP +Call \fBlibmpq__file_number\fP() to get the number of a given file in the archive. This function will return a file number regardless of a known or opened listfile. +.LP +The \fBlibmpq__file_number\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument \fIfilename\fP is the name of the file and the third argument is a reference to the \fInumber\fP of the file. +.SH RETURN VALUE +On success, the number of the file is returned and on error one of the following constants. +.TP +.B LIBMPQ_ERROR_EXIST +File does not exist in archive. +.SH AUTHOR +Check documentation. +.TP +libmpq is (c) 2003-2008 +.B Maik Broemme +.PP +The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/dep/libmpq/doc/man3/libmpq__file_offset.3 b/dep/libmpq/doc/man3/libmpq__file_offset.3 new file mode 100644 index 00000000000..392a66d0b04 --- /dev/null +++ b/dep/libmpq/doc/man3/libmpq__file_offset.3 @@ -0,0 +1,55 @@ +.\" Copyright (c) 2003-2008 Maik Broemme +.\" +.\" This is free documentation; 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. +.\" +.\" The GNU General Public License's references to "object code" +.\" and "executables" are to be interpreted as the output of any +.\" document formatting or typesetting system, including +.\" intermediate and printed output. +.\" +.\" This manual is distributed in the hope that it will be useful, +.\" but WITHOUT ANY WARRANTY; without even the implied warranty of +.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +.\" GNU General Public License for more details. +.\" +.\" You should have received a copy of the GNU General Public +.\" License along with this manual; if not, write to the Free +.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, +.\" USA. +.TH libmpq 3 2008-05-15 "The MoPaQ archive library" +.SH NAME +libmpq \- cross-platform C library for manipulating mpq archives. +.SH SYNOPSIS +.nf +.B +#include +.sp +.BI "int32_t libmpq__file_offset(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t " "file_number", +.BI " off_t *" "offset" +.BI ");" +.fi +.SH DESCRIPTION +.PP +Call \fBlibmpq__file_offset\fP() to get the offset of the file, which is the absolute position in the archive. It also supports archives within archives. +.LP +The \fBlibmpq__file_offset\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument \fIfile_number\fP is the number of file and the third argument is a reference to the file starting position \fIoffset\fP in archive. +.SH RETURN VALUE +On success, a zero is returned and on error one of the following constants. +.TP +.B LIBMPQ_ERROR_EXIST +File does not exist in archive. +.SH SEE ALSO +.BR libmpq__archive_offset (3), +.BR libmpq__block_offset (3) +.SH AUTHOR +Check documentation. +.TP +libmpq is (c) 2003-2008 +.B Maik Broemme +.PP +The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/dep/libmpq/doc/man3/libmpq__file_packed_size.3 b/dep/libmpq/doc/man3/libmpq__file_packed_size.3 new file mode 100644 index 00000000000..b584ddf77dd --- /dev/null +++ b/dep/libmpq/doc/man3/libmpq__file_packed_size.3 @@ -0,0 +1,55 @@ +.\" Copyright (c) 2003-2008 Maik Broemme +.\" +.\" This is free documentation; 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. +.\" +.\" The GNU General Public License's references to "object code" +.\" and "executables" are to be interpreted as the output of any +.\" document formatting or typesetting system, including +.\" intermediate and printed output. +.\" +.\" This manual is distributed in the hope that it will be useful, +.\" but WITHOUT ANY WARRANTY; without even the implied warranty of +.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +.\" GNU General Public License for more details. +.\" +.\" You should have received a copy of the GNU General Public +.\" License along with this manual; if not, write to the Free +.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, +.\" USA. +.TH libmpq 3 2008-05-15 "The MoPaQ archive library" +.SH NAME +libmpq \- cross-platform C library for manipulating mpq archives. +.SH SYNOPSIS +.nf +.B +#include +.sp +.BI "int32_t libmpq__file_packed_size(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t " "file_number", +.BI " off_t *" "packed_size" +.BI ");" +.fi +.SH DESCRIPTION +.PP +Call \fBlibmpq__file_packed_size\fP() to get the packed size of a given file in the archive. It will return a valid size for compressed and imploded files as well as stored only. +.LP +The \fBlibmpq__file_packed_size\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument \fIfile_number\fP is the number of file and the third argument is a reference to the compressed, imploded or stored size \fIpacked_size\fP of file. +.SH RETURN VALUE +On success, a zero is returned and on error one of the following constants. +.TP +.B LIBMPQ_ERROR_EXIST +File does not exist in archive. +.SH SEE ALSO +.BR libmpq__archive_packed_size (3), +.BR libmpq__block_packed_size (3) +.SH AUTHOR +Check documentation. +.TP +libmpq is (c) 2003-2008 +.B Maik Broemme +.PP +The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/dep/libmpq/doc/man3/libmpq__file_read.3 b/dep/libmpq/doc/man3/libmpq__file_read.3 new file mode 100644 index 00000000000..cbfafbd0f4f --- /dev/null +++ b/dep/libmpq/doc/man3/libmpq__file_read.3 @@ -0,0 +1,77 @@ +.\" Copyright (c) 2003-2008 Maik Broemme +.\" +.\" This is free documentation; 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. +.\" +.\" The GNU General Public License's references to "object code" +.\" and "executables" are to be interpreted as the output of any +.\" document formatting or typesetting system, including +.\" intermediate and printed output. +.\" +.\" This manual is distributed in the hope that it will be useful, +.\" but WITHOUT ANY WARRANTY; without even the implied warranty of +.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +.\" GNU General Public License for more details. +.\" +.\" You should have received a copy of the GNU General Public +.\" License along with this manual; if not, write to the Free +.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, +.\" USA. +.TH libmpq 3 2008-05-16 "The MoPaQ archive library" +.SH NAME +libmpq \- cross-platform C library for manipulating mpq archives. +.SH SYNOPSIS +.nf +.B +#include +.sp +.BI "int32_t libmpq__file_read(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t " "file_number", +.BI " uint8_t *" "out_buf", +.BI " off_t " "out_size", +.BI " off_t *" "transferred" +.BI ");" +.fi +.SH DESCRIPTION +.PP +Call \fBlibmpq__file_read\fP() to read a given file into memory. If the file is encrypted it will be first decrypted and then if it is packed (compressed or imploded) it will be unpacked. +.LP +The \fBlibmpq__file_read\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument \fIfile_number\fP is the file to extract, the third argument \fIout_buf\fP is the output data buffer which contains the extracted data. The fourth argument \fIout_size\fP is the size of \fIout_buf\fP and the fifth argument is a reference to the \fItransferred\fP bytes of the file. +.SH RETURN VALUE +On success, a zero is returned and on error one of the following constants. +.TP +.B LIBMPQ_ERROR_EXIST +File does not exist in archive. +.TP +.B LIBMPQ_ERROR_OPEN +Block offset table was not opened by calling \fBlibmpq__block_open_offset\fP(), or it was closed by an \fBlibmpq__block_close_offset\fP() call. +.TP +.B LIBMPQ_ERROR_SIZE +The output buffer is to small. +.TP +.B LIBMPQ_ERROR_SEEK +Seeking in file failed. +.TP +.B LIBMPQ_ERROR_MALLOC +Not enough memory for creating required structures. +.TP +.B LIBMPQ_ERROR_READ +Reading in archive failed. +.TP +.B LIBMPQ_ERROR_DECRYPT +Decrypting file failed. +.TP +.B LIBMPQ_ERROR_UNPACK +Unpacking file failed. +.SH SEE ALSO +.BR libmpq__block_read (3) +.SH AUTHOR +Check documentation. +.TP +libmpq is (c) 2003-2008 +.B Maik Broemme +.PP +The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/dep/libmpq/doc/man3/libmpq__file_unpacked_size.3 b/dep/libmpq/doc/man3/libmpq__file_unpacked_size.3 new file mode 100644 index 00000000000..a81cf7a4e76 --- /dev/null +++ b/dep/libmpq/doc/man3/libmpq__file_unpacked_size.3 @@ -0,0 +1,55 @@ +.\" Copyright (c) 2003-2008 Maik Broemme +.\" +.\" This is free documentation; 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. +.\" +.\" The GNU General Public License's references to "object code" +.\" and "executables" are to be interpreted as the output of any +.\" document formatting or typesetting system, including +.\" intermediate and printed output. +.\" +.\" This manual is distributed in the hope that it will be useful, +.\" but WITHOUT ANY WARRANTY; without even the implied warranty of +.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +.\" GNU General Public License for more details. +.\" +.\" You should have received a copy of the GNU General Public +.\" License along with this manual; if not, write to the Free +.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, +.\" USA. +.TH libmpq 3 2008-05-15 "The MoPaQ archive library" +.SH NAME +libmpq \- cross-platform C library for manipulating mpq archives. +.SH SYNOPSIS +.nf +.B +#include +.sp +.BI "int32_t libmpq__file_unpacked_size(" +.BI " mpq_archive_s *" "mpq_archive", +.BI " uint32_t " "file_number", +.BI " off_t *" "unpacked_size" +.BI ");" +.fi +.SH DESCRIPTION +.PP +Call \fBlibmpq__file_unpacked_size\fP() to get the unpacked size of a given file in the archive. It will return a valid size for compressed and imploded files as well as stored only. +.LP +The \fBlibmpq__file_unpacked_size\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument \fIfile_number\fP is the number of file and the third argument is a reference to the uncompressed, exploded or stored size \fIunpacked_size\fP of file. +.SH RETURN VALUE +On success, a zero is returned and on error one of the following constants. +.TP +.B LIBMPQ_ERROR_EXIST +File does not exist in archive. +.SH SEE ALSO +.BR libmpq__archive_unpacked_size (3), +.BR libmpq__block_unpacked_size (3) +.SH AUTHOR +Check documentation. +.TP +libmpq is (c) 2003-2008 +.B Maik Broemme +.PP +The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/dep/libmpq/doc/man3/libmpq__strerror.3 b/dep/libmpq/doc/man3/libmpq__strerror.3 new file mode 100644 index 00000000000..246f422eed0 --- /dev/null +++ b/dep/libmpq/doc/man3/libmpq__strerror.3 @@ -0,0 +1,45 @@ +.\" Copyright (c) 2010 Georg Lukas +.\" +.\" This is free documentation; 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. +.\" +.\" The GNU General Public License's references to "object code" +.\" and "executables" are to be interpreted as the output of any +.\" document formatting or typesetting system, including +.\" intermediate and printed output. +.\" +.\" This manual is distributed in the hope that it will be useful, +.\" but WITHOUT ANY WARRANTY; without even the implied warranty of +.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +.\" GNU General Public License for more details. +.\" +.\" You should have received a copy of the GNU General Public +.\" License along with this manual; if not, write to the Free +.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, +.\" USA. +.TH libmpq 3 2010-07-18 "The MoPaQ archive library" +.SH NAME +libmpq__strerror \- return string describing libmpq error number +.SH SYNOPSIS +.nf +.B +#include +.sp +.BI "const char *libmpq__strerror(int32_t returncode);" +.fi +.SH DESCRIPTION +.PP +Call \fBlibmpq__strerror\fP() to get a string message for the return code of one of the other libmpq functions. +.SH RETURN VALUE +The function returns a string pointer to non-writable memory or NULL if \fBreturncode\fP is not a return code of a libmpq function. +.SH SEE ALSO +.BR libmpq (3), strerror (3) +.SH AUTHOR +Check documentation. +.TP +libmpq is (c) 2003-2008 +.B Maik Broemme +.PP +The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/dep/libmpq/doc/man3/libmpq__version.3 b/dep/libmpq/doc/man3/libmpq__version.3 new file mode 100644 index 00000000000..5500d7314f5 --- /dev/null +++ b/dep/libmpq/doc/man3/libmpq__version.3 @@ -0,0 +1,45 @@ +.\" Copyright (c) 2003-2008 Maik Broemme +.\" +.\" This is free documentation; 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. +.\" +.\" The GNU General Public License's references to "object code" +.\" and "executables" are to be interpreted as the output of any +.\" document formatting or typesetting system, including +.\" intermediate and printed output. +.\" +.\" This manual is distributed in the hope that it will be useful, +.\" but WITHOUT ANY WARRANTY; without even the implied warranty of +.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +.\" GNU General Public License for more details. +.\" +.\" You should have received a copy of the GNU General Public +.\" License along with this manual; if not, write to the Free +.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, +.\" USA. +.TH libmpq 3 2008-03-31 "The MoPaQ archive library" +.SH NAME +libmpq \- cross-platform C library for manipulating mpq archives. +.SH SYNOPSIS +.nf +.B +#include +.sp +.BI "const char *libmpq__version();" +.fi +.SH DESCRIPTION +.PP +Call \fBlibmpq__version\fP() to get information about the version of the library, it is useful to create minimum required version verifications. +.SH RETURN VALUE +The function returns the library version. +.SH SEE ALSO +.BR libmpq (3) +.SH AUTHOR +Check documentation. +.TP +libmpq is (c) 2003-2008 +.B Maik Broemme +.PP +The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/dep/libmpq/libmpq-config.in b/dep/libmpq/libmpq-config.in new file mode 100644 index 00000000000..d345efdbe09 --- /dev/null +++ b/dep/libmpq/libmpq-config.in @@ -0,0 +1,57 @@ +#!/bin/sh + +prefix="@prefix@" +exec_prefix="@exec_prefix@" +exec_prefix_set=no + +usage="\ +Usage: libmpq-config [--prefix[=DIR]] [--exec-prefix[=DIR]] [--version] [--libs] [--cflags]" + +if test "$#" -eq "0"; then + echo "${usage}" 1>&2 + exit 1 +fi + +while test "$#" -gt "0"; do + case "$1" in + -*=*) optarg=`echo "$1" | sed 's/[-_a-zA-Z0-9]*=//'` ;; + *) optarg= ;; + esac + + case "$1" in + --prefix=*) + prefix="$optarg" + if test "$exec_prefix_set" = "no" ; then + exec_prefix="$optarg" + fi + ;; + --prefix) + echo "$prefix" + ;; + --exec-prefix=*) + exec_prefix="$optarg" + exec_prefix_set=yes + ;; + --exec-prefix) + echo "$exec_prefix" + ;; + --version) + echo "@VERSION@" + ;; + --cflags) + largefile="@LFS_CFLAGS@" + includes=-I@includedir@/libmpq + echo "$includes $largefile" + ;; + --libs) + libdirs="-L@libdir@" + echo "$libdirs -lmpq" + ;; + *) + echo "${usage}" 1>&2 + exit 1 + ;; + esac + shift +done + diff --git a/dep/libmpq/libmpq.pc.in b/dep/libmpq/libmpq.pc.in new file mode 100644 index 00000000000..8c53bea35a0 --- /dev/null +++ b/dep/libmpq/libmpq.pc.in @@ -0,0 +1,10 @@ +prefix=@prefix@ +exec_prefix=@exec_prefix@ +libdir=@libdir@ +includedir=@includedir@ + +Name: libmpq +Description: GPL version of the libmpq library +Version: @VERSION@ +Libs: -L${libdir} -lmpq +Cflags: -I${includedir}/libmpq @LFS_CFLAGS@ diff --git a/dep/libmpq/libmpq/Makefile.am b/dep/libmpq/libmpq/Makefile.am new file mode 100644 index 00000000000..409e3dfe02f --- /dev/null +++ b/dep/libmpq/libmpq/Makefile.am @@ -0,0 +1,23 @@ +# minimum required automake 1.6 +AUTOMAKE_OPTIONS = 1.6 + +# library information and headers which should not be installed. +lib_LTLIBRARIES = libmpq.la +noinst_HEADERS = common.h explode.h extract.h huffman.h mpq-internal.h wave.h + +# directory where the include files will be installed. +libmpq_includedir = $(includedir)/libmpq + +# header files to install. +libmpq_include_HEADERS = mpq.h + +libmpq_la_SOURCES = $(GENERAL_SRCS) +libmpq_la_LDFLAGS = -release $(PACKAGE_VERSION) + +GENERAL_SRCS = \ + common.c \ + huffman.c \ + extract.c \ + explode.c \ + mpq.c \ + wave.c diff --git a/dep/libmpq/libmpq/common.c b/dep/libmpq/libmpq/common.c new file mode 100644 index 00000000000..879bd902b58 --- /dev/null +++ b/dep/libmpq/libmpq/common.c @@ -0,0 +1,220 @@ +/* + * common.c -- shared functions used by mpq-tools. + * + * Copyright (c) 2003-2008 Maik Broemme + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +/* generic includes. */ +#include +#include +#include +#include + +/* libmpq main includes. */ +#include "mpq.h" +#include "mpq-internal.h" + +/* libmpq generic includes. */ +#include "extract.h" + +#include "common.h" + +/* the global shared decryption buffer. it's a static array compiled into the + * library, and can be re-created by compiling and running crypt_buf_gen.c + */ +#include "crypt_buf.h" + +/* function to return the hash to a given string. */ +uint32_t libmpq__hash_string(const char *key, uint32_t offset) { + + /* some common variables. */ + uint32_t seed1 = 0x7FED7FED; + uint32_t seed2 = 0xEEEEEEEE; + + /* one key character. */ + uint32_t ch; + + /* prepare seeds. */ + while (*key != 0) { + ch = toupper(*key++); + seed1 = crypt_buf[offset + ch] ^ (seed1 + seed2); + seed2 = ch + seed1 + seed2 + (seed2 << 5) + 3; + } + + return seed1; +} + +/* function to encrypt a block. */ +int32_t libmpq__encrypt_block(uint32_t *in_buf, uint32_t in_size, uint32_t seed) { + + /* some common variables. */ + uint32_t seed2 = 0xEEEEEEEE; + uint32_t ch; + + /* we're processing the data 4 bytes at a time. */ + for (; in_size >= 4; in_size -= 4) { + seed2 += crypt_buf[0x400 + (seed & 0xFF)]; + ch = *in_buf ^ (seed + seed2); + seed = ((~seed << 0x15) + 0x11111111) | (seed >> 0x0B); + seed2 = *in_buf + seed2 + (seed2 << 5) + 3; + *in_buf++ = ch; + } + + /* if no error was found, return decrypted bytes. */ + return LIBMPQ_SUCCESS; +} + + +/* function to decrypt a block. */ +int32_t libmpq__decrypt_block(uint32_t *in_buf, uint32_t in_size, uint32_t seed) { + + /* some common variables. */ + uint32_t seed2 = 0xEEEEEEEE; + uint32_t ch; + + /* we're processing the data 4 bytes at a time. */ + for (; in_size >= 4; in_size -= 4) { + seed2 += crypt_buf[0x400 + (seed & 0xFF)]; + ch = *in_buf ^ (seed + seed2); + seed = ((~seed << 0x15) + 0x11111111) | (seed >> 0x0B); + seed2 = ch + seed2 + (seed2 << 5) + 3; + *in_buf++ = ch; + } + + /* if no error was found, return decrypted bytes. */ + return LIBMPQ_SUCCESS; +} + +/* function to detect decryption key. */ +int32_t libmpq__decrypt_key(uint8_t *in_buf, uint32_t in_size, uint32_t block_size, uint32_t *key) { + + /* some common variables. */ + uint32_t saveseed1; + + /* temp = seed1 + seed2 */ + uint32_t temp; + uint32_t i = 0; + + /* temp = seed1 + buffer[0x400 + (seed1 & 0xFF)] */ + temp = (*(uint32_t *)in_buf ^ in_size) - 0xEEEEEEEE; + + /* try all 255 possibilities. */ + for (i = 0; i < 0x100; i++) { + + /* some common variables. */ + uint32_t seed1; + uint32_t seed2 = 0xEEEEEEEE; + uint32_t ch; + uint32_t ch2; + + /* try the first uint32_t's (we exactly know the value). */ + seed1 = temp - crypt_buf[0x400 + i]; + seed2 += crypt_buf[0x400 + (seed1 & 0xFF)]; + ch = ((uint32_t *)in_buf)[0] ^ (seed1 + seed2); + + if (ch != in_size) { + continue; + } + + /* add one because we are decrypting block positions. */ + saveseed1 = seed1 + 1; + ch2 = ch; + + /* + * if ok, continue and test the second value. we don't know exactly the value, + * but we know that the second one has lower 16 bits set to zero (no compressed + * block is larger than 0xFFFF bytes) + */ + seed1 = ((~seed1 << 0x15) + 0x11111111) | (seed1 >> 0x0B); + seed2 = ch + seed2 + (seed2 << 5) + 3; + seed2 += crypt_buf[0x400 + (seed1 & 0xFF)]; + ch = ((uint32_t *)in_buf)[1] ^ (seed1 + seed2); + + /* check if we found the file seed. */ + if ((ch - ch2) <= block_size) { + + /* file seed found, so return it. */ + *key = saveseed1; + return LIBMPQ_SUCCESS; + } + } + + /* if no file seed was found return with error. */ + return LIBMPQ_ERROR_DECRYPT; +} + +/* function to decompress or explode a block from mpq archive. */ +int32_t libmpq__decompress_block(uint8_t *in_buf, uint32_t in_size, uint8_t *out_buf, uint32_t out_size, uint32_t compression_type) { + + /* some common variables. */ + int32_t tb = 0; + + /* check if buffer is not compressed. */ + if (compression_type == LIBMPQ_FLAG_COMPRESS_NONE) { + + /* no compressed data, so copy input buffer to output buffer. */ + memcpy(out_buf, in_buf, out_size); + + /* store number of bytes copied. */ + tb = out_size; + } + + /* check if one compression mode is used. */ + else if (compression_type == LIBMPQ_FLAG_COMPRESS_PKZIP || + compression_type == LIBMPQ_FLAG_COMPRESS_MULTI) { + + /* check if block is really compressed, some blocks have set the compression flag, but are not compressed. */ + if (in_size < out_size) { + + /* check if we are using pkzip compression algorithm. */ + if (compression_type == LIBMPQ_FLAG_COMPRESS_PKZIP) { + + /* decompress using pkzip. */ + if ((tb = libmpq__decompress_pkzip(in_buf, in_size, out_buf, out_size)) < 0) { + + /* something on decompression failed. */ + return tb; + } + } + + /* check if we are using multiple compression algorithm. */ + else if (compression_type == LIBMPQ_FLAG_COMPRESS_MULTI) { + + /* + * check if it is a file compressed by blizzard's multiple compression, note that storm.dll + * version 1.0.9 distributed with warcraft 3 passes the full path name of the opened archive + * as the new last parameter. + */ + if ((tb = libmpq__decompress_multi(in_buf, in_size, out_buf, out_size)) < 0) { + + /* something on decompression failed. */ + return tb; + } + } + } else { + + /* block has set compression flag, but is not compressed, so copy data to output buffer. */ + memcpy(out_buf, in_buf, out_size); + + /* save the number of transferred bytes. */ + tb = in_size; + } + } + + /* if no error was found, return transferred bytes. */ + return tb; +} diff --git a/dep/libmpq/libmpq/common.h b/dep/libmpq/libmpq/common.h new file mode 100644 index 00000000000..b9e03126434 --- /dev/null +++ b/dep/libmpq/libmpq/common.h @@ -0,0 +1,61 @@ +/* + * common.h -- header functions used by mpq-tools. + * + * Copyright (c) 2003-2008 Maik Broemme + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef _COMMON_H +#define _COMMON_H + +/* function to return the hash to a given string. */ +uint32_t libmpq__hash_string( + const char *key, + uint32_t offset +); + +/* function to encrypt a block. */ +int32_t libmpq__encrypt_block( + uint32_t *in_buf, + uint32_t in_size, + uint32_t seed +); + +/* function to decrypt a block. */ +int32_t libmpq__decrypt_block( + uint32_t *in_buf, + uint32_t in_size, + uint32_t seed +); + +/* function to detect decryption key. */ +int32_t libmpq__decrypt_key( + uint8_t *in_buf, + uint32_t in_size, + uint32_t block_size, + uint32_t *key +); + +/* function to decompress or explode block from archive. */ +int32_t libmpq__decompress_block( + uint8_t *in_buf, + uint32_t in_size, + uint8_t *out_buf, + uint32_t out_size, + uint32_t compression_type +); + +#endif /* _COMMON_H */ diff --git a/dep/libmpq/libmpq/crypt_buf.h b/dep/libmpq/libmpq/crypt_buf.h new file mode 100644 index 00000000000..34184b017fe --- /dev/null +++ b/dep/libmpq/libmpq/crypt_buf.h @@ -0,0 +1,217 @@ +/* DO NOT CHANGE! this file is auto-generated by crypt_buf_gen.c */ +static const uint32_t crypt_buf[0x500] = { + 0x55c636e2, 0x02be0170, 0x584b71d4, 0x2984f00e, 0xb682c809, 0x91cf876b, + 0x775a9c24, 0x597d5ca5, 0x5a1afeb2, 0xd3e9ce0d, 0x32cdcdf8, 0xb18201cd, + 0x3cce05ce, 0xa55d13be, 0xbb0afe71, 0x9376ab33, 0x848f645e, 0x87e45a45, + 0x45b86017, 0x5e656ca8, 0x1b851a95, 0x2542dbd7, 0xab4df9e4, 0x5976ae9b, + 0x6c317e7d, 0xcddd2f94, 0x3c3c13e5, 0x335b1371, 0x31a592ca, 0x51e4fc4c, + 0xf7db5b2f, 0x8abdbe41, 0x8beaa674, 0x20d6b319, 0xde6c9a9d, 0xc5ac84e5, + 0x445a5feb, 0x94958cb0, 0x1e7d3847, 0xf35d29b0, 0xca5cceda, 0xb732c8b5, + 0xfdcc41dd, 0x0edcec16, 0x9d01feae, 0x1165d38e, 0x9ee193c8, 0xbf33b13c, + 0x61bc0dfc, 0xef3e7be9, 0xf8d4d4c5, 0xc79b7694, 0x5a255943, 0x0b3dd20a, + 0x9d1ab5a3, 0xcfa8ba57, 0x5e6d7069, 0xcb89b731, 0x3dc0d15b, 0x0d4d7e7e, + 0x97e37f2b, 0xfefc2bb1, 0xf95b16b5, 0x27a55b93, 0x45f22729, 0x4c986630, + 0x7c666862, 0x5fa40847, 0xa3f16205, 0x791b7764, 0x386b36d6, 0x6e6c3fef, + 0xc75855db, 0x4abc7dc7, 0x4a328f9b, 0xcef20c0f, 0x60b88f07, 0xf7bb4b8f, + 0x830b5192, 0x94f711ec, 0x20250752, 0x399d21a3, 0xe5c0840d, 0xe76cffa5, + 0x624fab29, 0x5df133e6, 0x83e0b9b8, 0xc5796bfb, 0x4a7ab2d0, 0xba59a821, + 0x03a81e4c, 0xcd3adfdb, 0x32b26b8c, 0x8e35c533, 0x9e6300e9, 0x8cf92ac5, + 0x880d18eb, 0x131a53b3, 0x2ed2dc64, 0xb23257c1, 0xa06450c1, 0x1b92cb8e, + 0x72ed730e, 0x19a685f0, 0x82836483, 0x42d94e8a, 0xee9bd6f6, 0x556d0b6a, + 0xba65589a, 0xde24cce4, 0x53329f6c, 0xc754fe8b, 0x503d2dc7, 0x10027ba4, + 0xd3b60a8b, 0x68e68d83, 0x0a9128a9, 0x595fa35f, 0x0b03b5be, 0x150a45c4, + 0xb1629cce, 0xe5f7497b, 0x8a7098a4, 0xb8233e69, 0x8ea0f978, 0x5b579970, + 0xeab14318, 0x4b28b263, 0xb6766cef, 0x06782877, 0x155c6dd0, 0xc711333c, + 0xf819cedf, 0x00eb1d68, 0xd6fffa6e, 0x439e5962, 0xd765d6db, 0xcb0bcee9, + 0x6d3c5647, 0x965466f3, 0x0ca983c9, 0x74ecc1ce, 0xfc0563b6, 0x42b08fee, + 0xc5b38853, 0xfe502ceb, 0x7b432faf, 0xc309e610, 0x2c3997d8, 0x43774654, + 0x15bd9d2c, 0xed6a420d, 0xc7ff520c, 0xb8a97fd1, 0x5e4d60cc, 0xb9738d11, + 0xda2181ff, 0x73ac2597, 0x3a8eec8d, 0xac85e779, 0xf3f975d6, 0xb9fe7b91, + 0x0f155d1e, 0x2860b6dd, 0x835977cb, 0xb0607436, 0x9cab7f6b, 0x8ab91186, + 0xc12b51e9, 0x20084e8b, 0x44ba8ead, 0xa542b130, 0x82bcd5c4, 0xcc747f4e, + 0x0f1909d8, 0xda242e1c, 0x6f7d1aa0, 0xd2626486, 0x88d0781e, 0xab695ccd, + 0xfa569145, 0xb4feb55c, 0xbe47e896, 0xe70a7a88, 0xd56185a2, 0xacf4c871, + 0x09282332, 0x1ddeeaa8, 0x590c7adb, 0xf4a97667, 0xbfd85705, 0x0ea77ccc, + 0xa9f85364, 0x83195869, 0x8bfb041a, 0xdb842f5c, 0xd6f0f315, 0xa7756ea7, + 0x0a51b439, 0xa9edf8a3, 0xd9084e2f, 0x827407f8, 0xd4ac8284, 0x09739d0d, + 0xb3bb6cfc, 0xd539c77d, 0x6bbc9ac0, 0x35c641aa, 0x934c96b0, 0xd17af317, + 0x29c6baef, 0xb275cdac, 0xd72662de, 0x9f5c2544, 0xc1a98f75, 0xd98e8f9a, + 0x47bd5c86, 0x70c610a6, 0xb5482ed4, 0x23b9c68c, 0x3c1bae66, 0x69556e7f, + 0xd902f5e0, 0x653d195b, 0xde6541fb, 0x07bcc6ac, 0xc6ee7788, 0x801534d4, + 0x2c1f35c0, 0xd9de614d, 0xbdccac85, 0xb4d4a0da, 0x242d549b, 0x9d964796, + 0xb9ceb982, 0x59fa99a9, 0xd8986cc1, 0x9e90c1a1, 0x01bbd82f, 0xd7f1c5fd, + 0xdd847eba, 0x883d305d, 0x25f13152, 0x4a92694d, 0x77f1e601, 0x8024e6e7, + 0x02a5f53d, 0x9c3ef4d9, 0xaf403ccc, 0xe2ad03c0, 0x46edf6ec, 0x6f9bd3e6, + 0xcc24ad7a, 0x47afab12, 0x82298df7, 0x708c9eec, 0x76f8c1b1, 0xb39459d2, + 0x3f1e26d9, 0xe1811be7, 0x56ed1c4d, 0xc9d18af8, 0xe828060e, 0x91cada2e, + 0x5ccbf9b7, 0xf1a552d4, 0x3c9d4343, 0xe1008785, 0x2adfeebf, 0xf90240a0, + 0x3d08cce7, 0x426e6fb0, 0x573c984f, 0x13a843ae, 0x406b7439, 0x636085d9, + 0x5000ba9a, 0xad4a47ab, 0xaf001d8d, 0x419907ae, 0x185c8f96, 0xe5e9ed4d, + 0x61764133, 0xd3703d97, 0xac98f0c6, 0xdbc3a37c, 0x85f010c4, 0x90491e32, + 0xf12e18bf, 0xc88c96e1, 0xd3fbd6d9, 0xe3c28b08, 0xd5bf08cc, 0xb1e78859, + 0x2546ddcf, 0xb030b200, 0xaafd2811, 0x55b22d21, 0xd38bf567, 0x469c7a2b, + 0x5ad05792, 0xa1a5981e, 0x7dfb8384, 0x34d1ca0a, 0x7eb0dbe0, 0xd61ce0f6, + 0x398068b7, 0xe6406d1f, 0x95ae6b47, 0xe4281230, 0xb0843061, 0xa70a3a68, + 0xe340f625, 0x72dcbffd, 0x8eb8afcd, 0x18b6661f, 0x17ef5a5c, 0x000c5b22, + 0x6ba13836, 0x6165e383, 0x74481c5b, 0xe56f0711, 0xa26f5024, 0x5ff22e60, + 0x31a5e829, 0xa1094bf0, 0xc680ec6c, 0x8cf327d7, 0xebf1348a, 0x6a227d2f, + 0x74065184, 0x8df65112, 0x2bbd05ee, 0xe4d00ed6, 0x2980ee1a, 0x6ae1da73, + 0xe84614da, 0x6c9906ab, 0xcf8e02db, 0xd3723e97, 0x92f66caf, 0xac8491c7, + 0xaec65696, 0xb98997cf, 0xfa16c762, 0x6d73c65f, 0x205d22a6, 0x4dd3aaa5, + 0x2deb6bc0, 0x9f37686c, 0x71a5282b, 0x376bb9e0, 0x7fff2a1b, 0xde67982f, + 0x9cbf33ce, 0x2e6dab37, 0x6e3424b9, 0x0ee143bc, 0x832a60d9, 0xbb6329e1, + 0x13f6befd, 0x5965fb84, 0xf60b233c, 0x3d695183, 0x433224a1, 0xb5d9cae5, + 0x82459bab, 0x9f21b311, 0xaf6c5247, 0xb447b13a, 0x7b2676c3, 0xc38979cd, + 0x8526ae25, 0xc550ad5b, 0x685099a7, 0x65e9c2bd, 0xe5c6dc36, 0xe10b37a9, + 0x88016878, 0xce81d4e4, 0x24d6fc80, 0x4106152d, 0x6d4f5f90, 0xc4dc74be, + 0xdb48676c, 0x6cb569b7, 0xf3bf598f, 0x042b08d9, 0x02ccb2de, 0xb1056f65, + 0x47994af4, 0xfa141ba4, 0x9376ab2e, 0x07a76737, 0x75e7e6fc, 0x449d80a1, + 0x03b7259d, 0xf6df358a, 0x5a75d5b9, 0x47286923, 0x3b1a30ef, 0xeebe3d6a, + 0x9db1aa00, 0x007a90d9, 0x24667071, 0x019c73cf, 0x69039bcd, 0x95900744, + 0x6518b1eb, 0x6905f202, 0xee3951b2, 0xe141fca9, 0x797fa832, 0x5a95e55b, + 0xd6263b15, 0x5b61f394, 0x897acb1c, 0x005f83a9, 0x22420f71, 0xf495176e, + 0x7e138f3d, 0x1392e384, 0x373bf7aa, 0x8e512816, 0xa960b3ca, 0x0474d74c, + 0xffacd6d7, 0x2ef5ed9e, 0x60992aaa, 0x7e690e99, 0x23c0749d, 0xd8e29105, + 0x555d5909, 0x15631bfe, 0xa69c5a1c, 0x501017ca, 0x99438048, 0x38733ac7, + 0xe682e2c8, 0xd4655fd6, 0x956e4c04, 0x347df643, 0x2f4b177b, 0x93ed3aa4, + 0xa77e1dd5, 0x7ae55702, 0xd2a52fd9, 0xef8ba18c, 0xb7d3c1ee, 0x8078ba8d, + 0xab5aaadb, 0x752be08f, 0x068b31c1, 0x078aae3c, 0xaa5a8343, 0x123d9268, + 0x2ceaee43, 0x8ebdb239, 0x650251f3, 0x04883648, 0x8c62e12e, 0x12b32167, + 0xe5112e9a, 0x10002548, 0x3e7a818d, 0x077e5327, 0xf140cc21, 0x6ce7d75d, + 0x9b99f9a5, 0x3215741c, 0xb6aadbae, 0x738768dc, 0x82a3742f, 0x76517020, + 0xdd872ad8, 0x9d0902b2, 0x7d1a6b04, 0x49381592, 0x63a652a5, 0x0c15e626, + 0xe22f70d6, 0x01e84385, 0xb29de134, 0x20c5000e, 0xe961f443, 0x2d31662e, + 0x3ce6bc28, 0x34f9dd94, 0xfa45de53, 0x497588bd, 0x9468215b, 0x0777fa5c, + 0x6f7114c0, 0xe0e82694, 0xe4371986, 0x57112de2, 0xe0cac289, 0xf2a3cee0, + 0x6a41e1b9, 0xbfcea77d, 0xf927fd52, 0x69747d98, 0xbea76cdb, 0x8dd39557, + 0x04db5ece, 0x2a0885c8, 0x3be4e8ee, 0x21d785dc, 0x09de7c0e, 0x3258ea33, + 0x51922982, 0xee8dd024, 0x3df6965d, 0x30c1237b, 0xf7f6686a, 0x9faca186, + 0x7c400076, 0x85acef8a, 0xf4b6d220, 0xddc3481c, 0x439eaec4, 0x717bbe63, + 0x8259faa7, 0xd682bd68, 0x932a8610, 0x38bf0a7f, 0x6212e2c7, 0x88ee3168, + 0xb3c27047, 0x6133cb1e, 0x15295506, 0x5ae66246, 0x1d208ddd, 0xa91d3dba, + 0xc315968d, 0x6aa2664b, 0x716d0cca, 0x891f4956, 0x80866bff, 0xbd56c847, + 0x9093425a, 0x28dd9e87, 0x84ef3e08, 0x690a49d6, 0x6a7eff82, 0xabcfe400, + 0x3d3be5ca, 0x381b650c, 0x4b7c8622, 0x3e0246f3, 0xa3561654, 0x9488865c, + 0x3aef1bf2, 0x5e5d68a2, 0xd32f1ddc, 0x51972bf0, 0x177a213b, 0x469375c2, + 0x37640bd0, 0xfc3324c8, 0x07091a09, 0x2d63d3fb, 0x2153f023, 0x48223875, + 0x61a55826, 0x8c136538, 0x49f71d98, 0x84c7d51e, 0x85551a73, 0x13d604c5, + 0xd701a626, 0x87b844ca, 0x741eb29d, 0x2a2c977c, 0xc797ca03, 0x6c4085d7, + 0x2dacf79b, 0x734fa2eb, 0xcc290557, 0xfa1e75e4, 0x06b29a27, 0xbece2a7a, + 0x70a4554b, 0xc935942e, 0xa764bbc1, 0x1fe391d6, 0x7807f0c2, 0x40606ed9, + 0xe5153086, 0xe91d7dd2, 0xed5d3ba9, 0xaa14b64a, 0x83b24dd9, 0xec1ff5cd, + 0xba33ead3, 0xe4ef735c, 0xbc062438, 0xd8bfd523, 0x473d1e04, 0x2007f8a7, + 0xb02903ed, 0x86ea8ada, 0x95ab69cf, 0xfd1f9809, 0x9cb3d8bb, 0x51f45958, + 0x9cdd4276, 0xc245865e, 0x8f0c836b, 0x4ee7dc07, 0xf6368d9d, 0xef2c1dc1, + 0xee56b54b, 0xbd62ce2f, 0xf4916aad, 0xc81cb594, 0x41729f49, 0x24bef0a4, + 0xdef487a9, 0x222e05b8, 0x8d3bf5c6, 0x11b55009, 0xad09d2b3, 0x19db9fd1, + 0xd7427085, 0x33dbfc8b, 0x526b9378, 0x790e1bc8, 0xb2998a00, 0xa5641703, + 0x0676d249, 0x6b9185cc, 0x30e4348f, 0x82c52f65, 0x57c7dc24, 0x489c1ecd, + 0x9fcab02a, 0x56d61117, 0xfe869cac, 0x55fc5140, 0x7fbbb382, 0x9e5afc79, + 0x10047c99, 0xfc9f5984, 0x56587e2d, 0xb98193f0, 0x98fe5e8e, 0x29b15b6b, + 0x9561f055, 0xbb0caa25, 0x1e4ecc15, 0x23f5393b, 0x0845b458, 0xceff67ca, + 0xb099900c, 0x00b1564f, 0x39eef3d1, 0xfcc1bf84, 0xac8893b5, 0x6484bf0e, + 0x91c02ab3, 0x8c0c0c70, 0x686fa8c6, 0xe171bed6, 0xdfae37df, 0xd5a1a4e7, + 0xe3eb49a1, 0x5e6014e0, 0x205b21ac, 0xfd58b3da, 0x2e7c07cd, 0xef2cc85a, + 0xd7587b46, 0xf417847d, 0x8a30cec1, 0x70984f6c, 0xf0b63388, 0xc220c98d, + 0xede62936, 0x92c0a7b3, 0x1ef371e8, 0x2005f7af, 0x91a47265, 0xb0cf5504, + 0xd500aba8, 0xcb5c4bd3, 0x9b3bcbc3, 0xcf6644b5, 0xce9488ef, 0x003fc96e, + 0xaa42222f, 0x4844f3d0, 0x4db89d77, 0x08681aae, 0x662f3a28, 0x761552db, + 0x1df7a17a, 0x93feed9a, 0xcc496a4f, 0xa217cfcd, 0x3ba3c930, 0x268f7e77, + 0x0797b4a1, 0x8bebfc51, 0x068930c4, 0x16c874e2, 0xc242da24, 0xfb229f76, + 0xa0795b02, 0x689fc036, 0x17a73732, 0xd21aec00, 0xac00a692, 0x5b217f18, + 0xae421624, 0x2bc05cc0, 0x48c1db7a, 0x4f4e63b4, 0x1667f04e, 0x34020f94, + 0x972b2555, 0x9a07355b, 0x01665970, 0x7db60c6f, 0x3ad7103b, 0x5c3d09c0, + 0xeea3dada, 0x88c21c10, 0x102436d7, 0x6a3b3400, 0xeb523c4c, 0xfb97d896, + 0x964cb86b, 0xdd878038, 0x0529da4d, 0x0b1468a5, 0x18739ac8, 0xf7f26668, + 0xf64f4471, 0x5c14f5c3, 0x44a081fb, 0x39ac7e37, 0x8a17c26b, 0x868f5e67, + 0x3931978d, 0x6edf7817, 0x4951cc67, 0x943407f3, 0xcc5e748f, 0x2b7ee729, + 0xcbb320f0, 0x11fec8e7, 0xfccfc658, 0x03454354, 0x373aa1ec, 0x1d58fe9a, + 0x064710ae, 0xa88aa0ba, 0xd183a23e, 0x40d150a3, 0xf531b8d1, 0xa7d99f85, + 0x11838cd5, 0xb19e64b3, 0x3d67a5e9, 0xb02c5ac6, 0x99b9b9e8, 0x4c202b7a, + 0x15f261d3, 0xa84c2d0d, 0x50f185a6, 0x33ba41d5, 0x39791013, 0x4baff44e, + 0xeeeeaa1c, 0xe0488314, 0x559ccd2b, 0xa104f445, 0x636f37c4, 0x264d5e3b, + 0x75c17f35, 0x75424131, 0xbb115739, 0x74fe755a, 0x7d3a7aa6, 0x2d8be784, + 0x83ed154a, 0xfc2673d8, 0x44dd4a7f, 0x79056cc8, 0x82cc8831, 0x9d3c1b7c, + 0xe9453bfa, 0x24315694, 0x661f3253, 0x75549f5c, 0xbb2b63ed, 0x67e00d96, + 0xf48966c7, 0x0d7bea56, 0xc25f92ef, 0xa947a79d, 0xde4adf6f, 0xac0f0342, + 0xd3eb246b, 0xa4aa118e, 0x3c3e6a46, 0x457f4441, 0xa50a406f, 0x6c508d9f, + 0xe9ac18e7, 0x1ecdb4ba, 0x39ac7e3a, 0x7fb304fa, 0x6f38f8e8, 0x4aecea6d, + 0x61035e73, 0x81708907, 0xebc07205, 0x90fd7614, 0xb52d217f, 0x6c4de195, + 0x1dd49084, 0x64ee482c, 0x94c7a521, 0x540c09d8, 0x75df8dd5, 0x414131f7, + 0x3698fd76, 0xf784db4f, 0xf8c97a03, 0x048f39b9, 0x3bf4f0bd, 0x8cb50992, + 0x9b58d9ee, 0xe5ab79cc, 0x9a5f6052, 0xbd9591b0, 0xfad2232b, 0x5a632254, + 0x0286e618, 0x8ad3c8f7, 0xe4060176, 0x754c4617, 0x5c10490b, 0x6f7d6fff, + 0x2187b42a, 0x5775095b, 0x02f4c663, 0x5a5dca06, 0xfe4ad4c7, 0x53e19f7d, + 0x59ff46b5, 0xbcc42ba5, 0xfd2f4a97, 0xbed6d905, 0x95629b6b, 0x21a1c0db, + 0xaa10b45d, 0xe6ef6d58, 0x2892cf4d, 0x9fed6c10, 0x1e386bf7, 0x9be0c6e8, + 0x2b2f15ef, 0x19f5ac7b, 0x7aff0e72, 0x31da576f, 0x30252cb4, 0x577960ac, + 0x166e9e5a, 0xa9374a61, 0x71369c96, 0x7ff826ae, 0xe8175326, 0xcabbfd33, + 0x0191190e, 0x699d3c3e, 0x36b40b22, 0xb3950513, 0x9b889bfa, 0xa52a5007, + 0xac290fed, 0x3b4e4a4f, 0xb753d8d6, 0x3c531f22, 0x582f6427, 0xa9cd93a9, + 0x546e39ae, 0x242faad2, 0xd2e0f747, 0x09f6325d, 0x59d48719, 0xad7eb66e, + 0xd5512878, 0x56debf9d, 0x5107e5a5, 0xf1c00aa4, 0x814ccca8, 0x600d90f0, + 0x9be97619, 0x915fa5f2, 0x2b5628dd, 0xa33d5f5a, 0x595df7c1, 0x6966215d, + 0x50ec8337, 0xf1d21372, 0x0ee2eefb, 0xad9e70b7, 0xab0d2fe4, 0xcf277b5d, + 0x62585a2c, 0x835a7844, 0x74b1fa6b, 0x49baffd5, 0x2ea9c864, 0x129311a8, + 0xbdfa1867, 0x83ca5997, 0x9d1db719, 0x84bb79e6, 0x9e3f99f2, 0x313f6101, + 0x1b99245b, 0xd15d8fb2, 0xcef90f81, 0x2945268d, 0xdbbcf573, 0xb1021886, + 0x9ee7ec1d, 0x1cf824f7, 0x7eaa2e32, 0x69c0a2b5, 0x7494419c, 0xe253d7d3, + 0x48da3d12, 0x45b8b571, 0xdb4d147a, 0xd82d8dde, 0x265d10a2, 0xb0a6eb9a, + 0x7e1c93a6, 0x36fe2f46, 0xdcad6b00, 0x05439191, 0xb0ce5484, 0x61d1c309, + 0x8da62a03, 0x06d0fe2f, 0xbac6dd3c, 0xca2006f3, 0x8321b1af, 0x0411a6f3, + 0xe8918eac, 0x21a2c152, 0x91c0d54f, 0x6aaa14fa, 0xdd22a440, 0x88cb2075, + 0x7a4eb813, 0x67afa071, 0xd8d98c9c, 0x31f10d47, 0x6ff1a8a8, 0x2faaf0a1, + 0x48a221bb, 0x3be6948b, 0xaa79e79b, 0x0ea7278c, 0x7a3857ef, 0x49b7fe55, + 0xd51cb931, 0x041c018d, 0x00b90501, 0x45ea7881, 0x8fc1dbcf, 0xb80b32a9, + 0xabacd2e9, 0x677bdc40, 0xecace542, 0x6d6514eb, 0x31c09ff7, 0x5e6c1abd, + 0x1c391d0f, 0x0e9d77f1, 0x7119392d, 0x6be9b0ba, 0x6194fa77, 0x45e62148, + 0x42234af2, 0xc3239d66, 0x939cbdbc, 0x56200d9c, 0x6b275208, 0x001a61f3, + 0xccc2a546, 0x4b722be0, 0xee25f2b7, 0x6d86cf9e, 0xaa6be0cd, 0x4dcda7b6, + 0x78d4aa13, 0x36ea7ad9, 0x3f29d700, 0xdeea2d84, 0x6a6af5bd, 0x18afb81c, + 0xd8e4e73c, 0x8aa708ba, 0x658b94d9, 0xa676478c, 0xcfa10c22, 0x25593c74, + 0x8d962235, 0x5f980270, 0x3df6ebc0, 0x8e7d92fa, 0xc3ee55e1, 0xd5f72447, + 0x02b0fa95, 0x52b0b520, 0x70d2c11f, 0x3a6fdd6c, 0x193aa698, 0x5496f7d5, + 0x4208931b, 0x7a4106ec, 0x83e86840, 0xf49b6f8c, 0xba3d9a51, 0x55f54ddd, + 0x2de51372, 0x9afb571b, 0x3ab35406, 0xad64ff1f, 0xc77764fe, 0x7f864466, + 0x416d9cd4, 0xa2489278, 0xe30b86e4, 0x0b5231b6, 0xba67aed6, 0xe5ab2467, + 0x60028b90, 0x1d9e20c6, 0x2a7c692a, 0x6b691cdb, 0x9e51f817, 0x9b763dec, + 0x3d29323f, 0xcfe12b68, 0x754b459b, 0xa2238047, 0xd9c55514, 0x6bdcffc1, + 0x693e6340, 0x82383fe7, 0x1916ea5f, 0xec7bcd59, 0x72de165a, 0xe79a1617, + 0x8ec86234, 0xa8f0d284, 0x20c90226, 0x7bf98884, 0x28a58331, 0x3ec3fa6e, + 0x4ce0895b, 0xc353b4d0, 0x33ef064f, 0x21e5e210, 0xc8bb589d, 0xe85dcab2, + 0xac65829f, 0xa7bf92d0, 0x05a6174d, 0x25a50c2e, 0xe5c78777, 0x3d75021f, + 0x4baa9c98, 0x23bdc884, 0x9653bbd7, 0xbadce7f5, 0xc283a484, 0xc040df2e, + 0x9370a841, 0x2f316022, 0x36eed231, 0xac2cbc0c, 0x13c0a49b, 0xcdd12997, + 0x07fe91b2, 0xcd7eabcd, 0x2c01271d, 0x18432df8, 0x599c6bc7, 0x75e93d5a, + 0xb67a6ee2, 0x8e738e16, 0xff9073fd, 0xaf77026a, 0xf86ea2fc, 0x91509ea3, + 0x33a78dc6, 0x4f79234a, 0x3a7535bc, 0x3539fcb1, 0x3103ee52, 0x4f6f1e69, + 0x6bb3ebbc, 0x4cb77555, 0x8dd1e999, 0x2ade439d, 0x11521fae, 0xb94d2545, + 0x8dde9abd, 0x1909393f, 0xb792a23d, 0x749c455b, 0xb5b60f2c, 0x380459ce, + 0x0dad5820, 0xb130845b, 0x291cbd52, 0xde9a5bb7, 0x51def961, 0x515b6408, + 0xca6e823e, 0x382e6e74, 0xeebe3d71, 0x4c8f0c6a, 0xe676dcea, 0x14e1dc7c, + 0x6f7fc634, 0xcf85a943, 0xd39ea96e, 0x136e7c93, 0x7164b304, 0xf32f1333, + 0x35c34034, 0xde39d721, 0x91a87439, 0xc410111f, 0x29f17aac, 0x1316a6ff, + 0x12f194ee, 0x420b9499, 0xf72db0dc, 0x690b9f93, 0x17d14bb2, 0x8f931ab8, + 0x217500bc, 0x875413f8, 0x98b2e43d, 0xc51f9571, 0x54cebdca, 0x0719cc79, + 0xf3c7080d, 0xe4286771, 0xa3eab3cd, 0x4a6b00e0, 0x11cf0759, 0x7e897379, + 0x5b32876c, 0x5e8cd4f6, 0x0cedfa64, 0x919ac2c7, 0xb214f3b3, 0x0e89c38c, + 0xf0c43a39, 0xeae10522, 0x835bce06, 0x9eec43c2, 0xea26a9d6, 0x69531821, + 0x6725b24a, 0xda81b0e2, 0xd5b4ae33, 0x080f99fb, 0x15a83daf, 0x29dfc720, + 0x91e1900f, 0x28163d58, 0x83d107a2, 0x4eac149a, 0x9f71da18, 0x61d5c4fa, + 0xe3ab2a5f, 0xc7b0d63f, 0xb3cc752a, 0x61ebcfb6, 0x26ffb52a, 0xed789e3f, + 0xaa3bc958, 0x455a8788, 0xc9c082a9, 0x0a1bef0e, 0xc29a5a7e, 0x150d4735, + 0x943809e0, 0x69215510, 0xef0b0da9, 0x3b4e9fb3, 0xd8b5d04c, 0xc7a023a8, + 0xb0d50288, 0x64821375, 0xc260e8cf, 0x8496bd2c, 0xff4f5435, 0x0fb5560c, + 0x7cd74a52, 0x93589c80, 0x88975c47, 0x83bda89d, 0x8bcc4296, 0x01b82c21, + 0xfd821dbf, 0x26520b47, 0x04983e19, 0xd3e1ca27, 0x782c580f, 0x326ff573, + 0xc157bcc7, 0x4f5e6b84, 0x44ebfbfb, 0xda26d9d8, 0x6cd9d08e, 0x1719f1d8, + 0x715c0487, 0x2c2d3c92, 0x53faaba9, 0xbc836146, 0x510c92d6, 0xe089f82a, + 0x4680171f, 0x369f00de, 0x70ec2331, 0x0e253d55, 0xdafb9717, 0xe5dd922d, + 0x95915d21, 0xa0202f96, 0xa161cc47, 0xeacfa6f1, 0xed5e9189, 0xdab87684, + 0xa4b76d4a, 0xfa704897, 0x631f10ba, 0xd39da8f9, 0x5db4c0e4, 0x16fde42a, + 0x2dff7580, 0xb56fec7e, 0xc3ffb370, 0x8e6f36bc, 0x6097d459, 0x514d5d36, + 0xa5a737e2, 0x3977b9b3, 0xfd31a0ca, 0x903368db, 0xe8370d61, 0x98109520, + 0xade23cac, 0x99f82e04, 0x41de7ea3, 0x84a1c295, 0x09191be0, 0x30930d02, + 0x1c9fa44a, 0xc406b6d7, 0xeedca152, 0x6149809c, 0xb0099ef4, 0xc5f653a5, + 0x4c10790d, 0x7303286c +}; diff --git a/dep/libmpq/libmpq/explode.c b/dep/libmpq/libmpq/explode.c new file mode 100644 index 00000000000..2d778d25c39 --- /dev/null +++ b/dep/libmpq/libmpq/explode.c @@ -0,0 +1,602 @@ +/* + * explode.c -- explode function of pkware data compression library. + * + * Copyright (c) 2003-2008 Maik Broemme + * + * This source was adepted from the C++ version of pkware.cpp included + * in stormlib. The C++ version belongs to the following authors: + * + * Ladislav Zezula + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +/* generic includes. */ +#include + +/* libmpq main includes. */ +#include "mpq.h" + +/* libmpq generic includes. */ +#include "explode.h" + +/* tables used for data extraction. */ +static const uint8_t pkzip_dist_bits[] = { + 0x02, 0x04, 0x04, 0x05, 0x05, 0x05, 0x05, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, + 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, + 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08 +}; + +/* tables used for data extraction. */ +static const uint8_t pkzip_dist_code[] = { + 0x03, 0x0D, 0x05, 0x19, 0x09, 0x11, 0x01, 0x3E, 0x1E, 0x2E, 0x0E, 0x36, 0x16, 0x26, 0x06, 0x3A, + 0x1A, 0x2A, 0x0A, 0x32, 0x12, 0x22, 0x42, 0x02, 0x7C, 0x3C, 0x5C, 0x1C, 0x6C, 0x2C, 0x4C, 0x0C, + 0x74, 0x34, 0x54, 0x14, 0x64, 0x24, 0x44, 0x04, 0x78, 0x38, 0x58, 0x18, 0x68, 0x28, 0x48, 0x08, + 0xF0, 0x70, 0xB0, 0x30, 0xD0, 0x50, 0x90, 0x10, 0xE0, 0x60, 0xA0, 0x20, 0xC0, 0x40, 0x80, 0x00 +}; + +/* tables used for data extraction. */ +static const uint8_t pkzip_clen_bits[] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 +}; + +/* tables used for data extraction. */ +static const uint16_t pkzip_len_base[] = { + 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, + 0x0008, 0x000A, 0x000E, 0x0016, 0x0026, 0x0046, 0x0086, 0x0106 +}; + +/* tables used for data extraction. */ +static const uint8_t pkzip_slen_bits[] = { + 0x03, 0x02, 0x03, 0x03, 0x04, 0x04, 0x04, 0x05, 0x05, 0x05, 0x05, 0x06, 0x06, 0x06, 0x07, 0x07 +}; + +/* tables used for data extraction. */ +static const uint8_t pkzip_len_code[] = { + 0x05, 0x03, 0x01, 0x06, 0x0A, 0x02, 0x0C, 0x14, 0x04, 0x18, 0x08, 0x30, 0x10, 0x20, 0x40, 0x00 +}; + +/* tables used for data extraction. */ +static const uint8_t pkzip_bits_asc[] = { + 0x0B, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x08, 0x07, 0x0C, 0x0C, 0x07, 0x0C, 0x0C, + 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0D, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, + 0x04, 0x0A, 0x08, 0x0C, 0x0A, 0x0C, 0x0A, 0x08, 0x07, 0x07, 0x08, 0x09, 0x07, 0x06, 0x07, 0x08, + 0x07, 0x06, 0x07, 0x07, 0x07, 0x07, 0x08, 0x07, 0x07, 0x08, 0x08, 0x0C, 0x0B, 0x07, 0x09, 0x0B, + 0x0C, 0x06, 0x07, 0x06, 0x06, 0x05, 0x07, 0x08, 0x08, 0x06, 0x0B, 0x09, 0x06, 0x07, 0x06, 0x06, + 0x07, 0x0B, 0x06, 0x06, 0x06, 0x07, 0x09, 0x08, 0x09, 0x09, 0x0B, 0x08, 0x0B, 0x09, 0x0C, 0x08, + 0x0C, 0x05, 0x06, 0x06, 0x06, 0x05, 0x06, 0x06, 0x06, 0x05, 0x0B, 0x07, 0x05, 0x06, 0x05, 0x05, + 0x06, 0x0A, 0x05, 0x05, 0x05, 0x05, 0x08, 0x07, 0x08, 0x08, 0x0A, 0x0B, 0x0B, 0x0C, 0x0C, 0x0C, + 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, + 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, + 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, + 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, + 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, + 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, + 0x0D, 0x0C, 0x0D, 0x0D, 0x0D, 0x0C, 0x0D, 0x0D, 0x0D, 0x0C, 0x0D, 0x0D, 0x0D, 0x0D, 0x0C, 0x0D, + 0x0D, 0x0D, 0x0C, 0x0C, 0x0C, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D +}; + +/* tables used for data extraction. */ +static const uint16_t pkzip_code_asc[] = { + 0x0490, 0x0FE0, 0x07E0, 0x0BE0, 0x03E0, 0x0DE0, 0x05E0, 0x09E0, + 0x01E0, 0x00B8, 0x0062, 0x0EE0, 0x06E0, 0x0022, 0x0AE0, 0x02E0, + 0x0CE0, 0x04E0, 0x08E0, 0x00E0, 0x0F60, 0x0760, 0x0B60, 0x0360, + 0x0D60, 0x0560, 0x1240, 0x0960, 0x0160, 0x0E60, 0x0660, 0x0A60, + 0x000F, 0x0250, 0x0038, 0x0260, 0x0050, 0x0C60, 0x0390, 0x00D8, + 0x0042, 0x0002, 0x0058, 0x01B0, 0x007C, 0x0029, 0x003C, 0x0098, + 0x005C, 0x0009, 0x001C, 0x006C, 0x002C, 0x004C, 0x0018, 0x000C, + 0x0074, 0x00E8, 0x0068, 0x0460, 0x0090, 0x0034, 0x00B0, 0x0710, + 0x0860, 0x0031, 0x0054, 0x0011, 0x0021, 0x0017, 0x0014, 0x00A8, + 0x0028, 0x0001, 0x0310, 0x0130, 0x003E, 0x0064, 0x001E, 0x002E, + 0x0024, 0x0510, 0x000E, 0x0036, 0x0016, 0x0044, 0x0030, 0x00C8, + 0x01D0, 0x00D0, 0x0110, 0x0048, 0x0610, 0x0150, 0x0060, 0x0088, + 0x0FA0, 0x0007, 0x0026, 0x0006, 0x003A, 0x001B, 0x001A, 0x002A, + 0x000A, 0x000B, 0x0210, 0x0004, 0x0013, 0x0032, 0x0003, 0x001D, + 0x0012, 0x0190, 0x000D, 0x0015, 0x0005, 0x0019, 0x0008, 0x0078, + 0x00F0, 0x0070, 0x0290, 0x0410, 0x0010, 0x07A0, 0x0BA0, 0x03A0, + 0x0240, 0x1C40, 0x0C40, 0x1440, 0x0440, 0x1840, 0x0840, 0x1040, + 0x0040, 0x1F80, 0x0F80, 0x1780, 0x0780, 0x1B80, 0x0B80, 0x1380, + 0x0380, 0x1D80, 0x0D80, 0x1580, 0x0580, 0x1980, 0x0980, 0x1180, + 0x0180, 0x1E80, 0x0E80, 0x1680, 0x0680, 0x1A80, 0x0A80, 0x1280, + 0x0280, 0x1C80, 0x0C80, 0x1480, 0x0480, 0x1880, 0x0880, 0x1080, + 0x0080, 0x1F00, 0x0F00, 0x1700, 0x0700, 0x1B00, 0x0B00, 0x1300, + 0x0DA0, 0x05A0, 0x09A0, 0x01A0, 0x0EA0, 0x06A0, 0x0AA0, 0x02A0, + 0x0CA0, 0x04A0, 0x08A0, 0x00A0, 0x0F20, 0x0720, 0x0B20, 0x0320, + 0x0D20, 0x0520, 0x0920, 0x0120, 0x0E20, 0x0620, 0x0A20, 0x0220, + 0x0C20, 0x0420, 0x0820, 0x0020, 0x0FC0, 0x07C0, 0x0BC0, 0x03C0, + 0x0DC0, 0x05C0, 0x09C0, 0x01C0, 0x0EC0, 0x06C0, 0x0AC0, 0x02C0, + 0x0CC0, 0x04C0, 0x08C0, 0x00C0, 0x0F40, 0x0740, 0x0B40, 0x0340, + 0x0300, 0x0D40, 0x1D00, 0x0D00, 0x1500, 0x0540, 0x0500, 0x1900, + 0x0900, 0x0940, 0x1100, 0x0100, 0x1E00, 0x0E00, 0x0140, 0x1600, + 0x0600, 0x1A00, 0x0E40, 0x0640, 0x0A40, 0x0A00, 0x1200, 0x0200, + 0x1C00, 0x0C00, 0x1400, 0x0400, 0x1800, 0x0800, 0x1000, 0x0000 +}; + +/* local unused variables. */ +char pkware_copyright[] = "PKWARE Data Compression Library for Win32\r\n" + "Copyright 1989-1995 PKWARE Inc. All Rights Reserved\r\n" + "Patent No. 5,051,745\r\n" + "PKWARE Data Compression Library Reg. U.S. Pat. and Tm. Off.\r\n" + "Version 1.11\r\n"; + +/* skips given number of bits. */ +static int32_t skip_bit(pkzip_cmp_s *mpq_pkzip, uint32_t bits) { + + /* check if number of bits required is less than number of bits in the buffer. */ + if (bits <= mpq_pkzip->extra_bits) { + mpq_pkzip->extra_bits -= bits; + mpq_pkzip->bit_buf >>= bits; + return 0; + } + + /* load input buffer if necessary. */ + mpq_pkzip->bit_buf >>= mpq_pkzip->extra_bits; + if (mpq_pkzip->in_pos == mpq_pkzip->in_bytes) { + mpq_pkzip->in_pos = sizeof(mpq_pkzip->in_buf); + if ((mpq_pkzip->in_bytes = mpq_pkzip->read_buf((char *)mpq_pkzip->in_buf, &mpq_pkzip->in_pos, mpq_pkzip->param)) == 0) { + return 1; + } + mpq_pkzip->in_pos = 0; + } + + /* update bit buffer. */ + mpq_pkzip->bit_buf |= (mpq_pkzip->in_buf[mpq_pkzip->in_pos++] << 8); + mpq_pkzip->bit_buf >>= (bits - mpq_pkzip->extra_bits); + mpq_pkzip->extra_bits = (mpq_pkzip->extra_bits - bits) + 8; + + /* if no error was found, return zero. */ + return 0; +} + +/* this function generate the decode tables used for decryption. */ +static void generate_tables_decode(int32_t count, uint8_t *bits, const uint8_t *code, uint8_t *buf2) { + + /* some common variables. */ + int32_t i; + + /* EBX - count */ + for (i = count-1; i >= 0; i--) { + + /* some common variables. */ + uint32_t idx1 = code[i]; + uint32_t idx2 = 1 << bits[i]; + + /* loop until table is ready. */ + do { + buf2[idx1] = (uint8_t)i; + idx1 += idx2; + } while (idx1 < 0x100); + } +} + +/* this function generate the tables for ascii decompression. */ +static void generate_tables_ascii(pkzip_cmp_s *mpq_pkzip) { + + /* some common variables. */ + const uint16_t *code_asc = &pkzip_code_asc[0xFF]; + uint32_t acc; + uint32_t add; + uint16_t count; + + /* loop through ascii table. */ + for (count = 0x00FF; code_asc >= pkzip_code_asc; code_asc--, count--) { + uint8_t *bits_asc = mpq_pkzip->bits_asc + count; + uint8_t bits_tmp = *bits_asc; + + /* check if byte is finished. */ + if (bits_tmp <= 8) { + add = (1 << bits_tmp); + acc = *code_asc; + do { + mpq_pkzip->offs_2c34[acc] = (uint8_t)count; + acc += add; + } while (acc < 0x100); + } else { + if ((acc = (*code_asc & 0xFF)) != 0) { + mpq_pkzip->offs_2c34[acc] = 0xFF; + if (*code_asc & 0x3F) { + + /* decrease bit by four. */ + bits_tmp -= 4; + *bits_asc = bits_tmp; + add = (1 << bits_tmp); + acc = *code_asc >> 4; + do { + mpq_pkzip->offs_2d34[acc] = (uint8_t)count; + acc += add; + } while (acc < 0x100); + } else { + + /* decrease bit by six. */ + bits_tmp -= 6; + *bits_asc = bits_tmp; + add = (1 << bits_tmp); + acc = *code_asc >> 6; + do { + mpq_pkzip->offs_2e34[acc] = (uint8_t)count; + acc += add; + } while (acc < 0x80); + } + } else { + + /* decrease bit by eight. (one byte) */ + bits_tmp -= 8; + *bits_asc = bits_tmp; + add = (1 << bits_tmp); + acc = *code_asc >> 8; + do { + mpq_pkzip->offs_2eb4[acc] = (uint8_t)count; + acc += add; + } while (acc < 0x100); + } + } + } +} + +/* + * decompress the imploded data using coded literals. + * + * returns: 0x000 - 0x0FF : one byte from compressed file. + * 0x100 - 0x305 : copy previous block. (0x100 = 1 byte) + * 0x306 : out of buffer? + */ +static uint32_t decode_literal(pkzip_cmp_s *mpq_pkzip) { + + /* number of bits to skip. */ + uint32_t bits; + + /* position in buffers. */ + uint32_t value; + + /* check if bit the current buffer is set, if not return the next byte. */ + if (mpq_pkzip->bit_buf & 1) { + + /* skip current bit in the buffer. */ + if (skip_bit(mpq_pkzip, 1)) { + return 0x306; + } + + /* the next bits are position in buffers. */ + value = mpq_pkzip->pos2[(mpq_pkzip->bit_buf & 0xFF)]; + + /* get number of bits to skip. */ + if (skip_bit(mpq_pkzip, mpq_pkzip->slen_bits[value])) { + return 0x306; + } + + /* check bits. */ + if ((bits = mpq_pkzip->clen_bits[value]) != 0) { + + /* some common variables. */ + uint32_t val2 = mpq_pkzip->bit_buf & ((1 << bits) - 1); + + /* check if we should skip one bit. */ + if (skip_bit(mpq_pkzip, bits)) { + + /* check position if we should skip the bit. */ + if ((value + val2) != 0x10E) { + return 0x306; + } + } + + /* fill values. */ + value = mpq_pkzip->len_base[value] + val2; + } + + /* return number of bytes to repeat. */ + return value + 0x100; + } + + /* skip one bit. */ + if (skip_bit(mpq_pkzip, 1)) { + return 0x306; + } + + /* check the binary compression type, read 8 bits and return them as one byte. */ + if (mpq_pkzip->cmp_type == LIBMPQ_PKZIP_CMP_BINARY) { + + /* fill values. */ + value = mpq_pkzip->bit_buf & 0xFF; + + /* check if we should skip one bit. */ + if (skip_bit(mpq_pkzip, 8)) { + return 0x306; + } + + /* return value from bit buffer. */ + return value; + } + + /* check if ascii compression is used. */ + if (mpq_pkzip->bit_buf & 0xFF) { + + /* fill values. */ + value = mpq_pkzip->offs_2c34[mpq_pkzip->bit_buf & 0xFF]; + + /* check value. */ + if (value == 0xFF) { + if (mpq_pkzip->bit_buf & 0x3F) { + + /* check if four bits are in bit buffer for skipping. */ + if (skip_bit(mpq_pkzip, 4)) { + return 0x306; + } + + /* fill values. */ + value = mpq_pkzip->offs_2d34[mpq_pkzip->bit_buf & 0xFF]; + } else { + + /* check if six bits are in bit buffer for skipping. */ + if (skip_bit(mpq_pkzip, 6)) { + return 0x306; + } + + /* fill values. */ + value = mpq_pkzip->offs_2e34[mpq_pkzip->bit_buf & 0x7F]; + } + } + } else { + + /* check if eight bits are in bit buffer for skipping. */ + if (skip_bit(mpq_pkzip, 8)) { + return 0x306; + } + + /* fill values. */ + value = mpq_pkzip->offs_2eb4[mpq_pkzip->bit_buf & 0xFF]; + } + + /* return out of buffer error (0x306) or position in buffer. */ + return skip_bit(mpq_pkzip, mpq_pkzip->bits_asc[value]) ? 0x306 : value; +} + +/* this function retrieves the number of bytes to move back. */ +static uint32_t decode_distance(pkzip_cmp_s *mpq_pkzip, uint32_t length) { + + /* some common variables. */ + uint32_t pos = mpq_pkzip->pos1[(mpq_pkzip->bit_buf & 0xFF)]; + + /* number of bits to skip. */ + uint32_t skip = mpq_pkzip->dist_bits[pos]; + + /* skip the appropriate number of bits. */ + if (skip_bit(mpq_pkzip, skip) == 1) { + return 0; + } + + /* check if length is two. */ + if (length == 2) { + pos = (pos << 2) | (mpq_pkzip->bit_buf & 0x03); + + /* skip the bits. */ + if (skip_bit(mpq_pkzip, 2) == 1) { + return 0; + } + } else { + pos = (pos << mpq_pkzip->dsize_bits) | (mpq_pkzip->bit_buf & mpq_pkzip->dsize_mask); + + /* skip the bits */ + if (skip_bit(mpq_pkzip, mpq_pkzip->dsize_bits) == 1) { + return 0; + } + } + + /* return the bytes to move back. */ + return pos + 1; +} + +/* + * function loads data from the input buffer used by mpq_pkzip + * "implode" and "explode" function as user defined callback and + * returns number of bytes loaded. + * + * char *buf - pointer to a buffer where to store loaded data. + * uint32_t *size - maximum number of bytes to read. + * void *param - custom pointer, parameter of implode/explode. + */ +static uint32_t data_read_input(char *buf, uint32_t *size, void *param) { + + /* some common variables. */ + pkzip_data_s *info = (pkzip_data_s *)param; + uint32_t max_avail = (info->in_bytes - info->in_pos); + uint32_t to_read = *size; + + /* check the case when not enough data available. */ + if (to_read > max_avail) { + to_read = max_avail; + } + + /* load data and increment offsets. */ + memcpy(buf, info->in_buf + info->in_pos, to_read); + info->in_pos += to_read; + + /* return bytes read. */ + return to_read; +} + +/* + * function for store output data used by mpq_pkzip "implode" and + * "explode" as userdefined callback. + * + * char *buf - pointer to data to be written. + * uint32_t *size - number of bytes to write. + * void *param - custom pointer, parameter of implode/explode. + */ +static void data_write_output(char *buf, uint32_t *size, void *param) { + + /* some common variables. */ + pkzip_data_s *info = (pkzip_data_s *)param; + uint32_t max_write = (info->max_out - info->out_pos); + uint32_t to_write = *size; + + /* check the case when not enough space in the output buffer. */ + if (to_write > max_write) { + to_write = max_write; + } + + /* write output data and increments offsets. */ + memcpy(info->out_buf + info->out_pos, buf, to_write); + info->out_pos += to_write; +} + +/* this function extract the data from input stream. */ +static uint32_t expand(pkzip_cmp_s *mpq_pkzip) { + + /* number of bytes to copy. */ + uint32_t copy_bytes; + + /* one byte from compressed file. */ + uint32_t one_byte; + + /* some common variables. */ + uint32_t result; + + /* initialize output buffer position. */ + mpq_pkzip->out_pos = 0x1000; + + /* check if end of data or error, so terminate decompress. */ + while ((result = one_byte = decode_literal(mpq_pkzip)) < 0x305) { + + /* check if one byte is greater than 0x100, which means 'repeat n - 0xFE bytes'. */ + if (one_byte >= 0x100) { + + /* ECX */ + uint8_t *source; + + /* EDX */ + uint8_t *target; + + /* some common variables. */ + uint32_t copy_length = one_byte - 0xFE; + uint32_t move_back; + + /* get length of data to copy. */ + if ((move_back = decode_distance(mpq_pkzip, copy_length)) == 0) { + result = 0x306; + break; + } + + /* target and source pointer. */ + target = &mpq_pkzip->out_buf[mpq_pkzip->out_pos]; + source = target - move_back; + mpq_pkzip->out_pos += copy_length; + + /* copy until nothing left. */ + while (copy_length-- > 0) { + *target++ = *source++; + } + } else { + + /* byte is 0x100 great, so add one byte. */ + mpq_pkzip->out_buf[mpq_pkzip->out_pos++] = (uint8_t)one_byte; + } + + /* check if number of extracted bytes has reached 1/2 of output buffer, so flush output buffer. */ + if (mpq_pkzip->out_pos >= 0x2000) { + + /* copy decompressed data into user buffer. */ + copy_bytes = 0x1000; + mpq_pkzip->write_buf((char *)&mpq_pkzip->out_buf[0x1000], ©_bytes, mpq_pkzip->param); + + /* check if there are some data left, keep them alive. */ + memcpy(mpq_pkzip->out_buf, &mpq_pkzip->out_buf[0x1000], mpq_pkzip->out_pos - 0x1000); + mpq_pkzip->out_pos -= 0x1000; + } + } + + /* copy the rest. */ + copy_bytes = mpq_pkzip->out_pos - 0x1000; + mpq_pkzip->write_buf((char *)&mpq_pkzip->out_buf[0x1000], ©_bytes, mpq_pkzip->param); + + /* return copied bytes. */ + return result; +} + +/* this function explode the data stream. */ +uint32_t libmpq__do_decompress_pkzip(uint8_t *work_buf, void *param) { + + /* some common variables. */ + pkzip_cmp_s *mpq_pkzip = (pkzip_cmp_s *)work_buf; + + /* set the whole work buffer to zeros. */ + memset(mpq_pkzip, 0, sizeof(pkzip_cmp_s)); + + /* initialize work struct and load compressed data. */ + mpq_pkzip->read_buf = data_read_input; + mpq_pkzip->write_buf = data_write_output; + mpq_pkzip->param = param; + mpq_pkzip->in_pos = sizeof(mpq_pkzip->in_buf); + mpq_pkzip->in_bytes = mpq_pkzip->read_buf((char *)mpq_pkzip->in_buf, &mpq_pkzip->in_pos, mpq_pkzip->param); + + /* check if we have pkzip data. */ + if (mpq_pkzip->in_bytes <= 4) { + return LIBMPQ_PKZIP_CMP_BAD_DATA; + } + + /* get the compression type. */ + mpq_pkzip->cmp_type = mpq_pkzip->in_buf[0]; + + /* get the dictionary size. */ + mpq_pkzip->dsize_bits = mpq_pkzip->in_buf[1]; + + /* initialize 16-bit bit buffer. */ + mpq_pkzip->bit_buf = mpq_pkzip->in_buf[2]; + + /* extra (over 8) bits. */ + mpq_pkzip->extra_bits = 0; + + /* position in input buffer. */ + mpq_pkzip->in_pos = 3; + + /* check if valid dictionary size. */ + if (4 > mpq_pkzip->dsize_bits || mpq_pkzip->dsize_bits > 6) { + return LIBMPQ_PKZIP_CMP_INV_DICTSIZE; + } + + /* shifted by 'sar' instruction. */ + mpq_pkzip->dsize_mask = 0xFFFF >> (0x10 - mpq_pkzip->dsize_bits); + + /* check if we are using binary compression. */ + if (mpq_pkzip->cmp_type != LIBMPQ_PKZIP_CMP_BINARY) { + + /* check if we are using ascii compression. */ + if (mpq_pkzip->cmp_type != LIBMPQ_PKZIP_CMP_ASCII) { + return LIBMPQ_PKZIP_CMP_INV_MODE; + } + + /* create ascii buffer. */ + memcpy(mpq_pkzip->bits_asc, pkzip_bits_asc, sizeof(mpq_pkzip->bits_asc)); + generate_tables_ascii(mpq_pkzip); + } + + /* create the tables for decode. */ + memcpy(mpq_pkzip->slen_bits, pkzip_slen_bits, sizeof(mpq_pkzip->slen_bits)); + generate_tables_decode(0x10, mpq_pkzip->slen_bits, pkzip_len_code, mpq_pkzip->pos2); + + /* create the tables for decode. */ + memcpy(mpq_pkzip->clen_bits, pkzip_clen_bits, sizeof(mpq_pkzip->clen_bits)); + memcpy(mpq_pkzip->len_base, pkzip_len_base, sizeof(mpq_pkzip->len_base)); + memcpy(mpq_pkzip->dist_bits, pkzip_dist_bits, sizeof(mpq_pkzip->dist_bits)); + generate_tables_decode(0x40, mpq_pkzip->dist_bits, pkzip_dist_code, mpq_pkzip->pos1); + + /* check if data extraction works. */ + if (expand(mpq_pkzip) != 0x306) { + return LIBMPQ_PKZIP_CMP_NO_ERROR; + } + + /* something failed, so return error. */ + return LIBMPQ_PKZIP_CMP_ABORT; +} diff --git a/dep/libmpq/libmpq/explode.h b/dep/libmpq/libmpq/explode.h new file mode 100644 index 00000000000..1d14dfc0e0a --- /dev/null +++ b/dep/libmpq/libmpq/explode.h @@ -0,0 +1,87 @@ +/* + * explode.h -- header file for pkware data decompression library + * used by mpq-tools. + * + * Copyright (c) 2003-2008 Maik Broemme + * + * This source was adepted from the C++ version of pklib.h included + * in stormlib. The C++ version belongs to the following authors: + * + * Ladislav Zezula + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef _EXPLODE_H +#define _EXPLODE_H + +/* define compression constants and return values. */ +#define LIBMPQ_PKZIP_CMP_BINARY 0 /* binary compression. */ +#define LIBMPQ_PKZIP_CMP_ASCII 1 /* ascii compression. */ +#define LIBMPQ_PKZIP_CMP_NO_ERROR 0 +#define LIBMPQ_PKZIP_CMP_INV_DICTSIZE 1 +#define LIBMPQ_PKZIP_CMP_INV_MODE 2 +#define LIBMPQ_PKZIP_CMP_BAD_DATA 3 +#define LIBMPQ_PKZIP_CMP_ABORT 4 + +#include "pack_begin.h" +/* compression structure. */ +typedef struct { + uint32_t offs0000; /* 0000 - start. */ + uint32_t cmp_type; /* 0004 - compression type (binary or ascii). */ + uint32_t out_pos; /* 0008 - position in output buffer. */ + uint32_t dsize_bits; /* 000C - dict size (4, 5, 6 for 0x400, 0x800, 0x1000). */ + uint32_t dsize_mask; /* 0010 - dict size bitmask (0x0F, 0x1F, 0x3F for 0x400, 0x800, 0x1000). */ + uint32_t bit_buf; /* 0014 - 16-bit buffer for processing input data. */ + uint32_t extra_bits; /* 0018 - number of extra (above 8) bits in bit buffer. */ + uint32_t in_pos; /* 001C - position in in_buf. */ + uint32_t in_bytes; /* 0020 - number of bytes in input buffer. */ + void *param; /* 0024 - custom parameter. */ + uint32_t (*read_buf)(char *buf, uint32_t *size, void *param); /* 0028 offset.*/ + void (*write_buf)(char *buf, uint32_t *size, void *param); /* 002C offset. */ + uint8_t out_buf[0x2000]; /* 0030 - output circle buffer, starting position is 0x1000. */ + uint8_t offs_2030[0x204]; /* 2030 - whats that? */ + uint8_t in_buf[0x800]; /* 2234 - buffer for data to be decompressed. */ + uint8_t pos1[0x100]; /* 2A34 - positions in buffers. */ + uint8_t pos2[0x100]; /* 2B34 - positions in buffers. */ + uint8_t offs_2c34[0x100]; /* 2C34 - buffer. */ + uint8_t offs_2d34[0x100]; /* 2D34 - buffer. */ + uint8_t offs_2e34[0x80]; /* 2EB4 - buffer. */ + uint8_t offs_2eb4[0x100]; /* 2EB4 - buffer. */ + uint8_t bits_asc[0x100]; /* 2FB4 - buffer. */ + uint8_t dist_bits[0x40]; /* 30B4 - numbers of bytes to skip copied block length. */ + uint8_t slen_bits[0x10]; /* 30F4 - numbers of bits for skip copied block length. */ + uint8_t clen_bits[0x10]; /* 3104 - number of valid bits for copied block. */ + uint16_t len_base[0x10]; /* 3114 - buffer. */ +} PACK_STRUCT pkzip_cmp_s; +#include "pack_end.h" + +/* data structure. */ +typedef struct { + uint8_t *in_buf; /* pointer to input data buffer. */ + uint32_t in_pos; /* current offset in input data buffer. */ + int32_t in_bytes; /* number of bytes in the input buffer. */ + uint8_t *out_buf; /* pointer to output data buffer. */ + uint32_t out_pos; /* position in the output buffer. */ + int32_t max_out; /* maximum number of bytes in the output buffer. */ +} pkzip_data_s; + +/* decompress the stream using pkzip compression. */ +uint32_t libmpq__do_decompress_pkzip( + uint8_t *work_buf, + void *param +); + +#endif /* _EXPLODE_H */ diff --git a/dep/libmpq/libmpq/extract.c b/dep/libmpq/libmpq/extract.c new file mode 100644 index 00000000000..11de1071683 --- /dev/null +++ b/dep/libmpq/libmpq/extract.c @@ -0,0 +1,361 @@ +/* + * extract.c -- global extracting function for all known file compressions + * in a mpq archive. + * + * Copyright (c) 2003-2008 Maik Broemme + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +/* generic includes. */ +#include +#include + +/* zlib includes. */ +#include +#include + +/* libmpq main includes. */ +#include "mpq.h" + +/* libmpq generic includes. */ +#include "explode.h" +#include "extract.h" +#include "huffman.h" +#include "wave.h" + +/* table with decompression bits and functions. */ +static decompress_table_s dcmp_table[] = { + {LIBMPQ_COMPRESSION_HUFFMAN, libmpq__decompress_huffman}, /* decompression using huffman trees. */ + {LIBMPQ_COMPRESSION_ZLIB, libmpq__decompress_zlib}, /* decompression with the zlib library. */ + {LIBMPQ_COMPRESSION_PKZIP, libmpq__decompress_pkzip}, /* decompression with pkware data compression library. */ + {LIBMPQ_COMPRESSION_BZIP2, libmpq__decompress_bzip2}, /* decompression with bzip2 library. */ + {LIBMPQ_COMPRESSION_WAVE_MONO, libmpq__decompress_wave_mono}, /* decompression for mono waves. */ + {LIBMPQ_COMPRESSION_WAVE_STEREO, libmpq__decompress_wave_stereo} /* decompression for stereo waves. */ +}; + +/* this function decompress a stream using huffman algorithm. */ +int32_t libmpq__decompress_huffman(uint8_t *in_buf, uint32_t in_size, uint8_t *out_buf, uint32_t out_size) { + + /* TODO: make typdefs of this structs? */ + /* some common variables. */ + int32_t tb = 0; + struct huffman_tree_s *ht; + struct huffman_input_stream_s *is; + + /* allocate memory for the huffman tree. */ + if ((ht = malloc(sizeof(struct huffman_tree_s))) == NULL || + (is = malloc(sizeof(struct huffman_input_stream_s))) == NULL) { + + /* memory allocation problem. */ + return LIBMPQ_ERROR_MALLOC; + } + + /* cleanup structures. */ + memset(ht, 0, sizeof(struct huffman_tree_s)); + memset(is, 0, sizeof(struct huffman_input_stream_s)); + + /* initialize input stream. */ + is->bit_buf = *(uint32_t *)in_buf; + in_buf += sizeof(int32_t); + is->in_buf = (uint8_t *)in_buf; + is->bits = 32; + +// TODO: add all the mallocs to init function and add function libmpq__huffman_tree_free() */ +// if ((result = libmpq__huffman_tree_init(ht, LIBMPQ_HUFF_DECOMPRESS)) < 0) { +// +// /* something on zlib initialization failed. */ +// return LIBMPQ_ERROR_UNPACK; +// } + + /* initialize the huffman tree for decompression. */ + libmpq__huffman_tree_init(ht, LIBMPQ_HUFF_DECOMPRESS); + + /* save the number of copied bytes. */ + tb = libmpq__do_decompress_huffman(ht, is, out_buf, out_size); + + /* free structures. */ + free(is); + free(ht); + + /* return transferred bytes. */ + return tb; +} + +/* this function decompress a stream using zlib algorithm. */ +int32_t libmpq__decompress_zlib(uint8_t *in_buf, uint32_t in_size, uint8_t *out_buf, uint32_t out_size) { + + /* some common variables. */ + int32_t result = 0; + int32_t tb = 0; + z_stream z; + + /* fill the stream structure for zlib. */ + z.next_in = (Bytef *)in_buf; + z.avail_in = (uInt)in_size; + z.total_in = in_size; + z.next_out = (Bytef *)out_buf; + z.avail_out = (uInt)out_size; + z.total_out = 0; + z.zalloc = NULL; + z.zfree = NULL; + + /* initialize the decompression structure, storm.dll uses zlib version 1.1.3. */ + if ((result = inflateInit(&z)) != Z_OK) { + + /* something on zlib initialization failed. */ + return result; + } + + /* call zlib to decompress the data. */ + if ((result = inflate(&z, Z_FINISH)) != Z_STREAM_END) { + + /* something on zlib decompression failed. */ + return result; + } + + /* save transferred bytes. */ + tb = z.total_out; + + /* cleanup zlib. */ + if ((result = inflateEnd(&z)) != Z_OK) { + + /* something on zlib finalization failed. */ + return result; + } + + /* return transferred bytes. */ + return tb; +} + +/* this function decompress a stream using pkzip algorithm. */ +int32_t libmpq__decompress_pkzip(uint8_t *in_buf, uint32_t in_size, uint8_t *out_buf, uint32_t out_size) { + + /* some common variables. */ + int32_t tb = 0; + uint8_t *work_buf; + pkzip_data_s info; + + /* allocate memory for pkzip data structure. */ + if ((work_buf = malloc(sizeof(pkzip_cmp_s))) == NULL) { + + /* memory allocation problem. */ + return LIBMPQ_ERROR_MALLOC; + } + + /* cleanup. */ + memset(work_buf, 0, sizeof(pkzip_cmp_s)); + + /* fill data information structure. */ + info.in_buf = in_buf; + info.in_pos = 0; + info.in_bytes = in_size; + info.out_buf = out_buf; + info.out_pos = 0; + info.max_out = out_size; + + /* do the decompression. */ + if ((tb = libmpq__do_decompress_pkzip(work_buf, &info)) < 0) { + + /* free working buffer. */ + free(work_buf); + + /* something failed on pkzip decompression. */ + return tb; + } + + /* save transferred bytes. */ + tb = info.out_pos; + + /* free working buffer. */ + free(work_buf); + + /* return transferred bytes. */ + return tb; +} + +/* this function decompress a stream using bzip2 library. */ +int32_t libmpq__decompress_bzip2(uint8_t *in_buf, uint32_t in_size, uint8_t *out_buf, uint32_t out_size) { + + /* some common variables. */ + int32_t result = 0; + int32_t tb = 0; + bz_stream strm; + + /* initialize the bzlib decompression. */ + strm.bzalloc = NULL; + strm.bzfree = NULL; + + /* initialize the structure. */ + if ((result = BZ2_bzDecompressInit(&strm, 0, 0)) != BZ_OK) { + + /* something on bzlib initialization failed. */ + return result; + } + + /* fill the stream structure for bzlib. */ + strm.next_in = (char *)in_buf; + strm.avail_in = in_size; + strm.next_out = (char *)out_buf; + strm.avail_out = out_size; + + /* do the decompression. */ + while (BZ2_bzDecompress(&strm) != BZ_STREAM_END); + + /* save transferred bytes. */ + tb = strm.total_out_lo32; + + /* cleanup of bzip stream. */ + BZ2_bzDecompressEnd(&strm); + + /* return transferred bytes. */ + return tb; +} + +/* this function decompress a stream using wave algorithm. (1 channel) */ +int32_t libmpq__decompress_wave_mono(uint8_t *in_buf, uint32_t in_size, uint8_t *out_buf, uint32_t out_size) { + + /* some common variables. */ + int32_t tb = 0; + + /* save the number of copied bytes. */ + if ((tb = libmpq__do_decompress_wave(out_buf, out_size, in_buf, in_size, 1)) < 0) { + + /* something on wave decompression failed. */ + return tb; + } + + /* return transferred bytes. */ + return tb; +} + +/* this function decompress a stream using wave algorithm. (2 channels) */ +int32_t libmpq__decompress_wave_stereo(uint8_t *in_buf, uint32_t in_size, uint8_t *out_buf, uint32_t out_size) { + + /* some common variables. */ + int32_t tb = 0; + + /* save the number of copied bytes. */ + if ((tb = libmpq__do_decompress_wave(out_buf, out_size, in_buf, in_size, 2)) < 0) { + + /* something on wave decompression failed. */ + return tb; + } + + /* return transferred bytes. */ + return tb; +} + +/* this function decompress a stream using a combination of the other compression algorithm. */ +int32_t libmpq__decompress_multi(uint8_t *in_buf, uint32_t in_size, uint8_t *out_buf, uint32_t out_size) { + + /* some common variables. */ + int32_t tb = 0; + uint32_t count = 0; + uint32_t entries = (sizeof(dcmp_table) / sizeof(decompress_table_s)); + uint8_t *temp_buf = NULL; + uint8_t *work_buf = 0; + uint8_t decompress_flag, decompress_unsupp; + uint32_t i; + + /* get applied compression types. */ + decompress_flag = decompress_unsupp = *in_buf++; + + /* decrement data size. */ + in_size--; + + /* search decompression table type and get all types of compression. */ + for (i = 0; i < entries; i++) { + + /* check if have to apply this decompression. */ + if (decompress_flag & dcmp_table[i].mask) { + + /* increase counter for used compression algorithms. */ + count++; + /* this algorithm is supported, remove from unsupp mask */ + decompress_unsupp &= ~dcmp_table[i].mask; + } + } + + /* check if there is some method unhandled. (e.g. compressed by future versions) */ + if (decompress_unsupp) { + + /* compression type is unknown and we need to implement it. :) */ + return LIBMPQ_ERROR_UNPACK; + } + + /* if multiple decompressions should be made, we need temporary buffer for the data. */ + if (count > 1) { + + /* allocate memory for temporary buffer. */ + if ((temp_buf = malloc(out_size)) == NULL) { + + /* memory allocation problem. */ + return LIBMPQ_ERROR_MALLOC; + } + + /* cleanup. */ + memset(temp_buf, 0, out_size); + } + + /* apply all decompressions. */ + for (i = 0, count = 0; i < entries; i++) { + + /* check if not used this kind of compression. */ + if (decompress_flag & dcmp_table[i].mask) { + + /* if multiple decompressions should be made, we need temporary buffer for the data. */ + if (count == 0) { + + /* use output buffer as working buffer. */ + work_buf = out_buf; + } else { + + /* use temporary buffer as working buffer. */ + work_buf = temp_buf; + } + + /* decompress buffer using corresponding function. */ + if ((tb = dcmp_table[i].decompress(in_buf, in_size, work_buf, out_size)) < 0) { + + /* free temporary buffer. */ + free(temp_buf); + + /* something on decompression failed. */ + return tb; + } + + /* move output size to source size for next compression. */ + in_size = out_size; + in_buf = work_buf; + + /* increase counter. */ + count++; + } + } + + /* if output buffer is not the same like target buffer, we have to copy data (this will happen on multiple decompressions). */ + if (work_buf != out_buf) { + + /* copy buffer. */ + memcpy(out_buf, in_buf, out_size); + } + + /* free temporary buffer. */ + free(temp_buf); + + /* return transferred bytes. */ + return tb; +} diff --git a/dep/libmpq/libmpq/extract.h b/dep/libmpq/libmpq/extract.h new file mode 100644 index 00000000000..d6ea794f162 --- /dev/null +++ b/dep/libmpq/libmpq/extract.h @@ -0,0 +1,106 @@ +/* + * extract.h -- header for the extraction functions used by mpq-tools. + * + * Copyright (c) 2003-2008 Maik Broemme + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef _EXTRACT_H +#define _EXTRACT_H + +/* define compression types for multilpe compressions. */ +#define LIBMPQ_COMPRESSION_HUFFMAN 0x01 /* huffman compression. (used on wave files only and introduced in starcraft) */ +#define LIBMPQ_COMPRESSION_ZLIB 0x02 /* zlib compression. (introduced in warcraft 3) */ +#define LIBMPQ_COMPRESSION_PKZIP 0x08 /* pkware dcl compression. (first used compression algorithm) */ +#define LIBMPQ_COMPRESSION_BZIP2 0x10 /* bzip compression. (introduced in warcraft 3 - the frozen throne) */ +#define LIBMPQ_COMPRESSION_WAVE_MONO 0x40 /* adpcm 4:1 compression. (introduced in starcraft) */ +#define LIBMPQ_COMPRESSION_WAVE_STEREO 0x80 /* adpcm 4:1 compression. (introduced in starcraft) */ + +/* + * table for decompression functions, return value for all functions + * is the transferred data size or one of the following error constants: + * + * LIBMPQ_ERROR_MALLOC + * LIBMPQ_ERROR_DECOMPRESS + */ +typedef int32_t (*DECOMPRESS)(uint8_t *, uint32_t, uint8_t *, uint32_t); +typedef struct { + uint32_t mask; /* decompression bit. */ + DECOMPRESS decompress; /* decompression function. */ +} decompress_table_s; + +/* + * huffman decompression routine, the in_size parameter is not used, + * but needs to be specified due to compatibility reasons. + * + * 1500F5F0 + */ +extern int32_t libmpq__decompress_huffman( + uint8_t *in_buf, + uint32_t in_size, + uint8_t *out_buf, + uint32_t out_size +); + +/* decompression using zlib. */ +extern int32_t libmpq__decompress_zlib( + uint8_t *in_buf, + uint32_t in_size, + uint8_t *out_buf, + uint32_t out_size +); + +/* decompression using pkzip. */ +extern int32_t libmpq__decompress_pkzip( + uint8_t *in_buf, + uint32_t in_size, + uint8_t *out_buf, + uint32_t out_size +); + +/* decompression using bzip2. */ +extern int32_t libmpq__decompress_bzip2( + uint8_t *in_buf, + uint32_t in_size, + uint8_t *out_buf, + uint32_t out_size +); + +/* decompression using wave. (1 channel) */ +extern int32_t libmpq__decompress_wave_mono( + uint8_t *in_buf, + uint32_t in_size, + uint8_t *out_buf, + uint32_t out_size +); + +/* decompression using wave. (2 channels) */ +extern int32_t libmpq__decompress_wave_stereo( + uint8_t *in_buf, + uint32_t in_size, + uint8_t *out_buf, + uint32_t out_size +); + +/* decompression using multiple of the above algorithm. */ +extern int32_t libmpq__decompress_multi( + uint8_t *in_buf, + uint32_t in_size, + uint8_t *out_buf, + uint32_t out_size +); + +#endif /* _EXTRACT_H */ diff --git a/dep/libmpq/libmpq/huffman.c b/dep/libmpq/libmpq/huffman.c new file mode 100644 index 00000000000..8fc87be2f60 --- /dev/null +++ b/dep/libmpq/libmpq/huffman.c @@ -0,0 +1,1101 @@ +/* + * huffman.c -- functions do decompress files in mpq files which + * uses a modified huffman version. + * + * Copyright (c) 2003-2008 Maik Broemme + * + * Differences between C++ and C version: + * + * - Removed the object oriented stuff. + * - Replaced the goto things with some better C code. + * + * This source was adepted from the C++ version of huffman.cpp included + * in stormlib. The C++ version belongs to the following authors: + * + * Ladislav Zezula + * ShadowFlare + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +/* generic includes. */ +#include +#include + +/* libmpq main includes. */ +#include "mpq.h" +#include "mpq-internal.h" + +/* libmpq generic includes. */ +#include "huffman.h" + +/* tables for huffman tree. */ +static const uint8_t table_1502A630[] = { + + /* data for compression type 0x00. */ + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, + 0x00, 0x00, + + /* data for compression type 0x01. */ + 0x54, 0x16, 0x16, 0x0D, 0x0C, 0x08, 0x06, 0x05, 0x06, 0x05, 0x06, 0x03, 0x04, 0x04, 0x03, 0x05, + 0x0E, 0x0B, 0x14, 0x13, 0x13, 0x09, 0x0B, 0x06, 0x05, 0x04, 0x03, 0x02, 0x03, 0x02, 0x02, 0x02, + 0x0D, 0x07, 0x09, 0x06, 0x06, 0x04, 0x03, 0x02, 0x04, 0x03, 0x03, 0x03, 0x03, 0x03, 0x02, 0x02, + 0x09, 0x06, 0x04, 0x04, 0x04, 0x04, 0x03, 0x02, 0x03, 0x02, 0x02, 0x02, 0x02, 0x03, 0x02, 0x04, + 0x08, 0x03, 0x04, 0x07, 0x09, 0x05, 0x03, 0x03, 0x03, 0x03, 0x02, 0x02, 0x02, 0x03, 0x02, 0x02, + 0x03, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x01, 0x01, 0x01, 0x02, 0x01, 0x02, 0x02, + 0x06, 0x0A, 0x08, 0x08, 0x06, 0x07, 0x04, 0x03, 0x04, 0x04, 0x02, 0x02, 0x04, 0x02, 0x03, 0x03, + 0x04, 0x03, 0x07, 0x07, 0x09, 0x06, 0x04, 0x03, 0x03, 0x02, 0x01, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x0A, 0x02, 0x02, 0x03, 0x02, 0x02, 0x01, 0x01, 0x02, 0x02, 0x02, 0x06, 0x03, 0x05, 0x02, 0x03, + 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x03, 0x01, 0x01, 0x01, + 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x04, 0x04, 0x04, 0x07, 0x09, 0x08, 0x0C, 0x02, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x03, + 0x04, 0x01, 0x02, 0x04, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, + 0x04, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x01, 0x01, 0x02, 0x02, 0x02, 0x06, 0x4B, + 0x00, 0x00, + + /* data for compression type 0x02. */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x27, 0x00, 0x00, 0x23, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xFF, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x01, 0x01, 0x06, 0x0E, 0x10, 0x04, + 0x06, 0x08, 0x05, 0x04, 0x04, 0x03, 0x03, 0x02, 0x02, 0x03, 0x03, 0x01, 0x01, 0x02, 0x01, 0x01, + 0x01, 0x04, 0x02, 0x04, 0x02, 0x02, 0x02, 0x01, 0x01, 0x04, 0x01, 0x01, 0x02, 0x03, 0x03, 0x02, + 0x03, 0x01, 0x03, 0x06, 0x04, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x02, 0x01, 0x01, + 0x01, 0x29, 0x07, 0x16, 0x12, 0x40, 0x0A, 0x0A, 0x11, 0x25, 0x01, 0x03, 0x17, 0x10, 0x26, 0x2A, + 0x10, 0x01, 0x23, 0x23, 0x2F, 0x10, 0x06, 0x07, 0x02, 0x09, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, + + /* data for compression type 0x03. */ + 0xFF, 0x0B, 0x07, 0x05, 0x0B, 0x02, 0x02, 0x02, 0x06, 0x02, 0x02, 0x01, 0x04, 0x02, 0x01, 0x03, + 0x09, 0x01, 0x01, 0x01, 0x03, 0x04, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, + 0x05, 0x01, 0x01, 0x01, 0x0D, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x02, 0x01, 0x01, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, + 0x0A, 0x04, 0x02, 0x01, 0x06, 0x03, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x03, 0x01, 0x01, 0x01, + 0x05, 0x02, 0x03, 0x04, 0x03, 0x03, 0x03, 0x02, 0x01, 0x01, 0x01, 0x02, 0x01, 0x02, 0x03, 0x03, + 0x01, 0x03, 0x01, 0x01, 0x02, 0x05, 0x01, 0x01, 0x04, 0x03, 0x05, 0x01, 0x03, 0x01, 0x03, 0x03, + 0x02, 0x01, 0x04, 0x03, 0x0A, 0x06, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x02, 0x02, 0x01, 0x0A, 0x02, 0x05, 0x01, 0x01, 0x02, 0x07, 0x02, 0x17, 0x01, 0x05, 0x01, 0x01, + 0x0E, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x06, 0x02, 0x01, 0x04, 0x05, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x07, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, + 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x11, + 0x00, 0x00, + + /* data for compression type 0x04. */ + 0xFF, 0xFB, 0x98, 0x9A, 0x84, 0x85, 0x63, 0x64, 0x3E, 0x3E, 0x22, 0x22, 0x13, 0x13, 0x18, 0x17, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, + + /* data for compression type 0x05. */ + 0xFF, 0xF1, 0x9D, 0x9E, 0x9A, 0x9B, 0x9A, 0x97, 0x93, 0x93, 0x8C, 0x8E, 0x86, 0x88, 0x80, 0x82, + 0x7C, 0x7C, 0x72, 0x73, 0x69, 0x6B, 0x5F, 0x60, 0x55, 0x56, 0x4A, 0x4B, 0x40, 0x41, 0x37, 0x37, + 0x2F, 0x2F, 0x27, 0x27, 0x21, 0x21, 0x1B, 0x1C, 0x17, 0x17, 0x13, 0x13, 0x10, 0x10, 0x0D, 0x0D, + 0x0B, 0x0B, 0x09, 0x09, 0x08, 0x08, 0x07, 0x07, 0x06, 0x05, 0x05, 0x04, 0x04, 0x04, 0x19, 0x18, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, + + /* data for compression type 0x06. */ + 0xC3, 0xCB, 0xF5, 0x41, 0xFF, 0x7B, 0xF7, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xBF, 0xCC, 0xF2, 0x40, 0xFD, 0x7C, 0xF7, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x7A, 0x46, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, + + /* data for compression type 0x07. */ + 0xC3, 0xD9, 0xEF, 0x3D, 0xF9, 0x7C, 0xE9, 0x1E, 0xFD, 0xAB, 0xF1, 0x2C, 0xFC, 0x5B, 0xFE, 0x17, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xBD, 0xD9, 0xEC, 0x3D, 0xF5, 0x7D, 0xE8, 0x1D, 0xFB, 0xAE, 0xF0, 0x2C, 0xFB, 0x5C, 0xFF, 0x18, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x70, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, + + /* data for compression type 0x08. */ + 0xBA, 0xC5, 0xDA, 0x33, 0xE3, 0x6D, 0xD8, 0x18, 0xE5, 0x94, 0xDA, 0x23, 0xDF, 0x4A, 0xD1, 0x10, + 0xEE, 0xAF, 0xE4, 0x2C, 0xEA, 0x5A, 0xDE, 0x15, 0xF4, 0x87, 0xE9, 0x21, 0xF6, 0x43, 0xFC, 0x12, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xB0, 0xC7, 0xD8, 0x33, 0xE3, 0x6B, 0xD6, 0x18, 0xE7, 0x95, 0xD8, 0x23, 0xDB, 0x49, 0xD0, 0x11, + 0xE9, 0xB2, 0xE2, 0x2B, 0xE8, 0x5C, 0xDD, 0x15, 0xF1, 0x87, 0xE7, 0x20, 0xF7, 0x44, 0xFF, 0x13, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x5F, 0x9E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00 +}; + +/* this function insert an item to a huffman tree. */ +void libmpq__huffman_insert_item(struct huffman_tree_item_s **p_item, struct huffman_tree_item_s *item, uint32_t where, struct huffman_tree_item_s *item2) { + + /* EDI - next to the first item. */ + struct huffman_tree_item_s *next = item->next; + + /* ESI - prev to the first item. */ + struct huffman_tree_item_s *prev = item->prev; + + /* pointer to previous item. */ + struct huffman_tree_item_s *prev2; + + /* pointer to next item. */ + long next2; + + /* check the first item already has next one. */ + if (next != 0) { + + /* check if previous item exist. */ + if (PTR_INT(prev) < 0) { + + /* return previous item. */ + prev = PTR_NOT(prev); + } else { + + /* add item. */ + prev += (item - next->prev); + } + + /* 150083C1 - remove the item from the tree. */ + prev->next = next; + next->prev = prev; + + /* invalidate prev and next pointer. */ + item->next = 0; + item->prev = 0; + } + + /* EDX - check if the second item is not entered. */ + if (item2 == NULL) { + + /* take the first tree item. */ + item2 = PTR_PTR(&p_item[1]); + } + + /* check if items should be switched or new one inserted. */ + switch (where) { + case SWITCH_ITEMS: + + /* item2->next (pointer to pointer to first). */ + item->next = item2->next; + item->prev = item2->next->prev; + item2->next->prev = item; + + /* set the first item. */ + item2->next = item; + + /* return from function. */ + return; + case INSERT_ITEM: + + /* set next item (or pointer to pointer to first item) - insert as last item. */ + item->next = item2; + + /* set previous item (or last item in the tree). */ + item->prev = item2->prev; + + /* usually NULL. */ + next2 = PTR_INT(p_item[0]); + + /* previous item to the second (or last tree item). */ + prev2 = item2->prev; + + /* check if previous item is a valid pointer. */ + if (PTR_INT(prev2) < 0) { + + /* set values. */ + prev2 = PTR_NOT(prev); + prev2->next = item; + + /* next after last item. */ + item2->prev = item; + + /* return from function. */ + return; + } + + /* check if next item is empty. */ + if (next2 < 0) { + + /* set next item. */ + next2 = item2 - item2->next->prev; + } + + /* add next item to previous one. */ + prev2 += next2; + prev2->next = item; + + /* set the next and last item. */ + item2->prev = item; + + /* return from function. */ + return; + default: + + /* nothing to do, so return from function. */ + return; + } +} + +/* 1500BC90 - remove item from huffman tree.*/ +void libmpq__huffman_remove_item(struct huffman_tree_item_s *hi) { + + /* EDX - some common variables. */ + struct huffman_tree_item_s *temp; + + /* check if next item is not empty. */ + if (hi->next != NULL) { + + /* fetch previous item. */ + temp = hi->prev; + + /* check if previous item is a pointer. */ + if (PTR_INT(temp) <= 0) { + temp = PTR_NOT(temp); + } else { + temp += (hi - hi->next->prev); + } + + /* reorganize tree. */ + temp->next = hi->next; + hi->next->prev = hi->prev; + hi->next = hi->prev = NULL; + } +} + +/* get previous huffman tree item. */ +struct huffman_tree_item_s *libmpq__huffman_previous_item(struct huffman_tree_item_s *hi, long value) { + + /* check if previous item exist. */ + if (PTR_INT(hi->prev) < 0) { + + /* return previous item. */ + return PTR_NOT(hi->prev); + } + + /* check if something else should returned. */ + if (value < 0) { + + /* fetch previous item of next item. */ + value = hi - hi->next->prev; + } + + /* return previous item with value. */ + return hi->prev + value; +} + +/* get one bit from input stream. */ +uint32_t libmpq__huffman_get_1bit(struct huffman_input_stream_s *is) { + + /* some common variables. */ + uint32_t bit = (is->bit_buf & 1); + + /* shift bit right by one. */ + is->bit_buf >>= 1; + + /* check if we should extract bits. */ + if (--is->bits == 0) { + is->bit_buf = *(uint32_t *)is->in_buf; + is->in_buf += sizeof(int32_t); + is->bits = 32; + } + + /* return the bit. */ + return bit; +} + +/* get 7 bits from the input stream. */ +uint32_t libmpq__huffman_get_7bit(struct huffman_input_stream_s *is) { + + /* check if we should extract bits. */ + if (is->bits <= 7) { + is->bit_buf |= *(uint16_t *)is->in_buf << is->bits; + is->in_buf += sizeof(int16_t); + is->bits += 16; + } + + /* get 7 bits from input stream. */ + return (is->bit_buf & 0x7F); +} + +/* get the whole byte from the input stream. */ +uint32_t libmpq__huffman_get_8bit(struct huffman_input_stream_s *is) { + + /* some common variables. */ + uint32_t one_byte; + + /* check if we should extract bits. */ + if (is->bits <= 8) { + is->bit_buf |= *(uint16_t *)is->in_buf << is->bits; + is->in_buf += sizeof(int16_t); + is->bits += 16; + } + + /* fill values. */ + one_byte = (is->bit_buf & 0xFF); + is->bit_buf >>= 8; + is->bits -= 8; + + /* return the 8 bits. */ + return one_byte; +} + +/* return struct for 1500E740. */ +struct huffman_tree_item_s *libmpq__huffman_call_1500E740(struct huffman_tree_s *ht) { + + /* EDX */ + struct huffman_tree_item_s *p_item1 = ht->item3058; + + /* EAX */ + struct huffman_tree_item_s *p_item2; + + /* some common variables. */ + struct huffman_tree_item_s *p_next; + struct huffman_tree_item_s *p_prev; + struct huffman_tree_item_s **pp_item; + + /* check if item is empty. */ + if (PTR_INT(p_item1) <= 0 || (p_item2 = p_item1) == NULL) { + + /* check if item is not empty. */ + if ((p_item2 = &ht->items0008[ht->items++]) != NULL) { + p_item1 = p_item2; + } else { + p_item1 = ht->first; + } + } else { + p_item1 = p_item2; + } + + /* set next item. */ + p_next = p_item1->next; + + /* check if next item is not empty. */ + if (p_next != NULL) { + + /* set previous item. */ + p_prev = p_item1->prev; + + /* check if previous item is a valid pointer. */ + if (PTR_INT(p_prev) <= 0) { + p_prev = PTR_NOT(p_prev); + } else { + p_prev += (p_item1 - p_item1->next->prev); + } + + /* fill values. */ + p_prev->next = p_next; + p_next->prev = p_prev; + p_item1->next = NULL; + p_item1->prev = NULL; + } + + /* ESI */ + pp_item = &ht->first; + p_item1->next = (struct huffman_tree_item_s *)pp_item; + p_item1->prev = pp_item[1]; + + /* EDI = ht->item305C - ECX */ + p_prev = pp_item[1]; + + /* check if previous pointer is valid. */ + if (p_prev <= 0) { + + /* fill values. */ + p_prev = PTR_NOT(p_prev); + p_prev->next = p_item1; + p_prev->prev = p_item2; + p_item2->parent = NULL; + p_item2->child = NULL; + } else { + + /* check if pointer is valid. */ + if (PTR_INT(ht->item305C) < 0) { + p_prev += (struct huffman_tree_item_s *)pp_item - (*pp_item)->prev; + } else { + p_prev += PTR_INT(ht->item305C); + } + + /* fill values. */ + p_prev->next = p_item1; + pp_item[1] = p_item2; + p_item2->parent = NULL; + p_item2->child = NULL; + } + + /* return item. */ + return p_item2; +} + +/* return struct for 1500E820. */ +void libmpq__huffman_call_1500E820(struct huffman_tree_s *ht, struct huffman_tree_item_s *p_item) { + + /* EDI */ + struct huffman_tree_item_s *p_item1; + + /* EAX */ + struct huffman_tree_item_s *p_item2 = NULL; + + /* EDX */ + struct huffman_tree_item_s *p_item3; + + /* EBX */ + struct huffman_tree_item_s *p_prev; + + /* loop through parent items. */ + for (; p_item != NULL; p_item = p_item->parent) { + + /* increase byte counter. */ + p_item->byte_value++; + + /* loop through previous items. */ + for (p_item1 = p_item; ; p_item1 = p_prev) { + + /* set previous item. */ + p_prev = p_item1->prev; + + /* check if pointer is valid. */ + if (PTR_INT(p_prev) <= 0) { + p_prev = NULL; + break; + } + + /* check if byte value of previous item is higher than actual item. */ + if (p_prev->byte_value >= p_item->byte_value) { + break; + } + } + + /* check if previous item is same like actual item. */ + if (p_item1 == p_item) { + continue; + } + + /* check if next item is not empty, */ + if (p_item1->next != NULL) { + + /* fill values. */ + p_item2 = libmpq__huffman_previous_item(p_item1, -1); + p_item2->next = p_item1->next; + p_item1->next->prev = p_item1->prev; + p_item1->next = NULL; + p_item1->prev = NULL; + } + + /* fill values. */ + p_item2 = p_item->next; + p_item1->next = p_item2; + p_item1->prev = p_item2->prev; + p_item2->prev = p_item1; + p_item->next = p_item1; + + /* check if both items are not empty. */ + if ((p_item2 = p_item1) != NULL) { + + /* fill values. */ + p_item2 = libmpq__huffman_previous_item(p_item, -1); + p_item2->next = p_item->next; + p_item->next->prev = p_item->prev; + p_item->next = NULL; + p_item->prev = NULL; + } + + /* check if previous item is empty. */ + if (p_prev == NULL) { + p_prev = PTR_PTR(&ht->first); + } + + /* fill values. */ + p_item2 = p_prev->next; + p_item->next = p_item2; + p_item->prev = p_item2->prev; + p_item2->prev = p_item; + p_prev->next = p_item; + p_item3 = p_item1->parent->child; + p_item2 = p_item->parent; + + /* check if child item and parent item match. */ + if (p_item2->child == p_item) { + p_item2->child = p_item1; + } + + /* check if items match. */ + if (p_item3 == p_item1) { + p_item1->parent->child = p_item; + } + + /* fill values. */ + p_item2 = p_item->parent; + p_item->parent = p_item1->parent; + p_item1->parent = p_item2; + + /* increase counter. */ + ht->offs0004++; + } +} + +/* this function initialize a huffman tree. */ +void libmpq__huffman_tree_init(struct huffman_tree_s *ht, uint32_t cmp) { + + /* some common variables. */ + uint32_t count; + struct huffman_tree_item_s *hi; + + /* clear links for all the items in the tree. */ + for (hi = ht->items0008, count = 0x203; count != 0; hi++, count--) { + hi->next = hi->prev = NULL; + } + + /* fill values. */ + ht->item3050 = NULL; + ht->item3054 = PTR_PTR(&ht->item3054); + ht->item3058 = PTR_NOT(ht->item3054); + ht->item305C = NULL; + ht->first = PTR_PTR(&ht->first); + ht->last = PTR_NOT(ht->first); + ht->offs0004 = 1; + ht->items = 0; + + /* clear all huffman decompress items, do this only if preparing for decompression. */ + if (cmp == LIBMPQ_HUFF_DECOMPRESS) { + for (count = 0; count < sizeof(ht->qd3474) / sizeof(struct huffman_decompress_s); count++) { + ht->qd3474[count].offs00 = 0; + } + } +} + +/* this function build a huffman tree, called with the first 8 bits loaded from input stream. */ +void libmpq__huffman_tree_build(struct huffman_tree_s *ht, uint32_t cmp_type) { + + /* [ESP+10] - the greatest character found in table. */ + uint32_t max_byte; + + /* [ESP+1C] - pointer to uint8_t in table_1502A630. */ + const uint8_t *byte_array; + + /* thats needed to replace the goto stuff from original source. :) */ + uint32_t found; + + /* [ESP+14] - Pointer to Huffman tree item pointer array. */ + struct huffman_tree_item_s **p_item; + struct huffman_tree_item_s *child1; + + /* some common variables. */ + uint32_t i; + + /* ESI - loop while pointer has a negative value (last entry). */ + while (PTR_INT(ht->last) > 0) { + + /* EAX */ + struct huffman_tree_item_s *temp; + + /* ESI->next */ + if (ht->last->next != NULL) { + libmpq__huffman_remove_item(ht->last); + } + + /* [EDI+4] */ + ht->item3058 = PTR_PTR(&ht->item3054); + + /* EAX */ + ht->last->prev = ht->item3058; + temp = libmpq__huffman_previous_item(PTR_PTR(&ht->item3054), PTR_INT(&ht->item3050)); + temp->next = ht->last; + ht->item3054 = ht->last; + } + + /* clear all pointers in huffman tree item array. */ + memset(ht->items306C, 0, sizeof(ht->items306C)); + + /* greatest character found init to zero. */ + max_byte = 0; + + /* pointer to current entry in huffman tree item pointer array. */ + p_item = (struct huffman_tree_item_s **)&ht->items306C; + + /* ensure we have low 8 bits only. */ + cmp_type &= 0xFF; + + /* EDI also. */ + byte_array = table_1502A630 + cmp_type * 258; + + /* loop to build huffman tree. */ + for (i = 0; i < 0x100; i++, p_item++) { + + /* item to be created. */ + struct huffman_tree_item_s *item = ht->item3058; + struct huffman_tree_item_s *p_item3 = ht->item3058; + uint8_t one_byte = byte_array[i]; + + /* skip all the bytes which are zero. */ + if (byte_array[i] == 0) { + continue; + } + + /* if not valid pointer, take the first available item in the array. */ + if (PTR_INT(item) <= 0) { + item = &ht->items0008[ht->items++]; + } + + /* insert this item as the top of the tree. */ + libmpq__huffman_insert_item(&ht->item305C, item, SWITCH_ITEMS, NULL); + + /* invalidate child and parent. */ + item->parent = NULL; + item->child = NULL; + + /* store pointer into pointer array. */ + *p_item = item; + + /* store counter. */ + item->dcmp_byte = i; + + /* store byte value. */ + item->byte_value = one_byte; + + /* check if byte is to big. */ + if (one_byte >= max_byte) { + + /* set max byte to highest value. */ + max_byte = one_byte; + + /* continue loop. */ + continue; + } + + /* find the first item which has byte value greater than current one byte. */ + found = 0; + + /* EDI - Pointer to the last item. */ + if (PTR_INT((p_item3 = ht->last)) > 0) { + + /* 15006AF7 */ + if (p_item3 != NULL) { + + /* 15006AFB */ + do { + + /* check if we found item. */ + if (p_item3->byte_value >= one_byte) { + found = 1; + break; + } + + /* switch to previous item. */ + p_item3 = p_item3->prev; + } while (PTR_INT(p_item3) > 0); + } + } + + /* check if item was not found. */ + if (found == 0) { + p_item3 = NULL; + } + + /* 15006B09 */ + if (item->next != NULL) { + libmpq__huffman_remove_item(item); + } + + /* 15006B15 */ + if (p_item3 == NULL) { + p_item3 = PTR_PTR(&ht->first); + } + + /* 15006B1F */ + item->next = p_item3->next; + item->prev = p_item3->next->prev; + p_item3->next->prev = item; + p_item3->next = item; + } + + /* 15006B4A */ + for (; i < 0x102; i++) { + + /* EDI */ + struct huffman_tree_item_s **p_item2 = &ht->items306C[i]; + + /* 15006B59 - ESI */ + struct huffman_tree_item_s *item2 = ht->item3058; + + /* check if item is a valid pointer. */ + if (PTR_INT(item2) <= 0) { + item2 = &ht->items0008[ht->items++]; + } + + /* insert the item into tree. */ + libmpq__huffman_insert_item(&ht->item305C, item2, INSERT_ITEM, NULL); + + /* 15006B89 */ + item2->dcmp_byte = i; + item2->byte_value = 1; + item2->parent = NULL; + item2->child = NULL; + *p_item2++ = item2; + } + + /* 15006BAA - EDI - last item (first child to item). */ + if (PTR_INT((child1 = ht->last)) > 0) { + + /* EBP */ + struct huffman_tree_item_s *child2; + + /* ESI */ + struct huffman_tree_item_s *item; + + /* 15006BB8 */ + while (PTR_INT((child2 = child1->prev)) > 0) { + if (PTR_INT((item = ht->item3058)) <= 0) { + item = &ht->items0008[ht->items++]; + } + + /* 15006BE3 */ + libmpq__huffman_insert_item(&ht->item305C, item, SWITCH_ITEMS, NULL); + + /* 15006BF3 */ + item->parent = NULL; + item->child = NULL; + + /* + * EDX = child2->byte_value + child1->byte_value; + * EAX = child1->byte_value; + * ECX = max_byte; (the greatest character (0xFF usually)) + * item->byte_value (0x02 usually) + */ + item->byte_value = child1->byte_value + child2->byte_value; + + /* previous item in the tree. */ + item->child = child1; + child1->parent = item; + child2->parent = item; + + /* EAX = item->byte_value */ + if (item->byte_value >= max_byte) { + max_byte = item->byte_value; + } else { + + /* EDI */ + struct huffman_tree_item_s *p_item2 = child2->prev; + found = 0; + + /* check if item is a valid pointer. */ + if (PTR_INT(p_item2) > 0) { + + /* 15006C2D */ + do { + + /* check if we found item. */ + if (p_item2->byte_value >= item->byte_value) { + found = 1; + break; + } + + /* switch to previous item. */ + p_item2 = p_item2->prev; + } while (PTR_INT(p_item2) > 0); + } + + /* check if item was not found. */ + if (found == 0) { + p_item2 = NULL; + } + + /* check if next item exist. */ + if (item->next != 0) { + + /* some common variables. */ + struct huffman_tree_item_s *temp4 = libmpq__huffman_previous_item(item, -1); + + /* zhe first item changed. */ + temp4->next = item->next; + + /* first->prev changed to negative value. */ + item->next->prev = item->prev; + item->next = NULL; + item->prev = NULL; + } + + /* 15006C62 */ + if (p_item2 == NULL) { + p_item2 = PTR_PTR(&ht->first); + } + + /* set item with 0x100 byte value. */ + item->next = p_item2->next; + + /* set item with 0x17 byte value. */ + item->prev = p_item2->next->prev; + + /* changed prev of item with. */ + p_item2->next->prev = item; + p_item2->next = item; + } + + /* 15006C7B */ + if (PTR_INT((child1 = child2->prev)) <= 0) { + break; + } + } + } + + /* 15006C88 */ + ht->offs0004 = 1; +} + +/* this function did the real decompression. */ +int32_t libmpq__do_decompress_huffman(struct huffman_tree_s *ht, struct huffman_input_stream_s *is, uint8_t *out_buf, uint32_t out_length) { + + /* some common variables. */ + uint32_t dcmp_byte = 0; + uint8_t *out_pos = out_buf; + uint32_t bit_count; + struct huffman_decompress_s *qd; + struct huffman_tree_item_s *p_item1; + struct huffman_tree_item_s *p_item2; + + /* 8 bits loaded from input stream. */ + uint32_t n8bits; + + /* 7 bits loaded from input stream. */ + uint32_t n7bits; + + /* thats needed to replace the goto stuff from original source. :) */ + uint32_t found; + + /* can we use quick decompression */ + uint32_t has_qd; + + /* test the output length, must not be non zero. */ + if (out_length == 0) { + return 0; + } + + /* get the compression type from the input stream. */ + n8bits = libmpq__huffman_get_8bit(is); + + /* build the Huffman tree. */ + libmpq__huffman_tree_build(ht, n8bits); + + /* compression 8 bit or not? */ + ht->cmp0 = (n8bits == 0) ? TRUE : FALSE; + + /* loop until break. */ + for(;;) { + + /* get 7 bits from input stream. */ + n7bits = libmpq__huffman_get_7bit(is); + + /* try to use quick decompression, check huffman decompress struct for corresponding item. */ + qd = &ht->qd3474[n7bits]; + + /* if there is a quick-pass possible (ebx). */ + has_qd = (qd->offs00 >= ht->offs0004) ? TRUE : FALSE; + + /* if we can use quick decompress, use it. */ + if (has_qd) { + found = 0; + if (qd->bits > 7) { + is->bit_buf >>= 7; + is->bits -= 7; + p_item1 = qd->p_item; + found = 1; + } + if (found == 0) { + is->bit_buf >>= qd->bits; + is->bits -= qd->bits; + dcmp_byte = qd->dcmp_byte; + } + } else { + found = 1; + p_item1 = ht->first->next->prev; + if (PTR_INT(p_item1) <= 0) { + p_item1 = NULL; + } + } + + /* check if item was found. */ + if (found == 1) { + bit_count = 0; + p_item2 = NULL; + + /* loop until tree has no deeper level. */ + do { + + /* move down by one level. */ + p_item1 = p_item1->child; + + /* check if current bit is set, move to previous. */ + if (libmpq__huffman_get_1bit(is)) { + p_item1 = p_item1->prev; + } + + /* check if we are at 7th bit, save current huffman tree item. */ + if (++bit_count == 7) { + p_item2 = p_item1; + } + } while (p_item1->child != NULL); + + /* no quick decompression. :( */ + if (has_qd == FALSE) { + + /* check bit counter. */ + if (bit_count > 7) { + qd->offs00 = ht->offs0004; + qd->bits = bit_count; + qd->p_item = p_item2; + } else { + uint32_t index = n7bits & (0xFFFFFFFF >> (32 - bit_count)); + uint32_t add = (1 << bit_count); + + /* loop through compression. */ + for (qd = &ht->qd3474[index]; index <= 0x7F; index += add, qd += add) { + qd->offs00 = ht->offs0004; + qd->bits = bit_count; + qd->dcmp_byte = p_item1->dcmp_byte; + } + } + } + + /* set compression byte. */ + dcmp_byte = p_item1->dcmp_byte; + } + + /* check if huffman tree needs to be modified. */ + if (dcmp_byte == 0x101) { + + /* fill values. */ + n8bits = libmpq__huffman_get_8bit(is); + p_item1 = (ht->last <= 0) ? NULL : ht->last; + p_item2 = libmpq__huffman_call_1500E740(ht); + p_item2->parent = p_item1; + p_item2->dcmp_byte = p_item1->dcmp_byte; + p_item2->byte_value = p_item1->byte_value; + ht->items306C[p_item2->dcmp_byte] = p_item2; + p_item2 = libmpq__huffman_call_1500E740(ht); + p_item2->parent = p_item1; + p_item2->dcmp_byte = n8bits; + p_item2->byte_value = 0; + ht->items306C[p_item2->dcmp_byte] = p_item2; + p_item1->child = p_item2; + + /* call 1500E820. */ + libmpq__huffman_call_1500E820(ht, p_item2); + + /* check if compression is not set. */ + if (ht->cmp0 == 0) { + libmpq__huffman_call_1500E820(ht, ht->items306C[n8bits]); + } + + /* set compression byte. */ + dcmp_byte = n8bits; + } + + /* check for compression. */ + if (dcmp_byte == 0x100) { + break; + } + + /* increase position by compression byte. */ + *out_pos++ = (uint8_t)dcmp_byte; + if (--out_length == 0) { + break; + } + + /* check if compression is not set. */ + if (ht->cmp0) { + libmpq__huffman_call_1500E820(ht, ht->items306C[dcmp_byte]); + } + } + + /* return copied bytes. */ + return (out_pos - out_buf); +} diff --git a/dep/libmpq/libmpq/huffman.h b/dep/libmpq/libmpq/huffman.h new file mode 100644 index 00000000000..6f691088fa0 --- /dev/null +++ b/dep/libmpq/libmpq/huffman.h @@ -0,0 +1,151 @@ +/* + * huffman.h -- structures used for huffman compression. + * + * Copyright (c) 2003-2008 Maik Broemme + * + * This source was adepted from the C++ version of huffman.h included + * in stormlib. The C++ version belongs to the following authors: + * + * Ladislav Zezula + * ShadowFlare + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef _HUFFMAN_H +#define _HUFFMAN_H + +/* define huffman compression and decompression values. */ +#define LIBMPQ_HUFF_DECOMPRESS 0 /* we want to decompress using huffman trees. */ + +/* define pointer conversions. */ +#define PTR_NOT(ptr) (struct huffman_tree_item_s *)(~(unsigned long)(ptr)) +#define PTR_PTR(ptr) ((struct huffman_tree_item_s *)(ptr)) +#define PTR_INT(ptr) (long)(ptr) + +/* define item handling. */ +#define INSERT_ITEM 1 /* insert item into huffman tree. */ +#define SWITCH_ITEMS 2 /* switch items isnide huffman tree. */ + +/* input stream for huffman decompression. */ +struct huffman_input_stream_s { + uint8_t *in_buf; /* 00 - input data. */ + uint32_t bit_buf; /* 04 - input bit buffer. */ + uint32_t bits; /* 08 - number of bits remaining in byte. */ +}; + +/* huffman tree item. */ +struct huffman_tree_item_s { + struct huffman_tree_item_s *next; /* 00 - pointer to next huffman tree item. */ + struct huffman_tree_item_s *prev; /* 04 - pointer to prev huffman tree item (< 0 if none). */ + uint32_t dcmp_byte; /* 08 - index of this item in item pointer array, decompressed byte value. */ + uint32_t byte_value; /* 0C - some byte value. */ + struct huffman_tree_item_s *parent; /* 10 - pointer to parent huffman tree item (NULL if none). */ + struct huffman_tree_item_s *child; /* 14 - pointer to child huffman tree item. */ +}; + +/* structure used for quick decompression. */ +struct huffman_decompress_s { + uint32_t offs00; /* 00 - 1 if resolved. */ + uint32_t bits; /* 04 - bit count. */ + union { + uint32_t dcmp_byte; /* 08 - byte value for decompress (if bitCount <= 7). */ + struct huffman_tree_item_s *p_item; /* 08 - huffman tree item (if number of bits is greater than 7). */ + }; +}; + +/* structure for huffman tree. */ +struct huffman_tree_s { + uint32_t cmp0; /* 0000 - 1 if compression type 0. */ + uint32_t offs0004; /* 0004 - some flag. */ + struct huffman_tree_item_s items0008[0x203]; /* 0008 - huffman tree items. */ + struct huffman_tree_item_s *item3050; /* 3050 - always NULL? */ + struct huffman_tree_item_s *item3054; /* 3054 - pointer to huffman tree item. */ + struct huffman_tree_item_s *item3058; /* 3058 - pointer to huffman tree item (< 0 if invalid). */ + struct huffman_tree_item_s *item305C; /* 305C - usually NULL. */ + struct huffman_tree_item_s *first; /* 3060 - pointer to top (first) huffman tree item. */ + struct huffman_tree_item_s *last; /* 3064 - pointer to bottom (last) huffman tree item (< 0 if invalid). */ + uint32_t items; /* 3068 - number of used huffman tree items. */ + struct huffman_tree_item_s *items306C[0x102]; /* 306C - huffman tree item pointer array. */ + struct huffman_decompress_s qd3474[0x80]; /* 3474 - array for quick decompression. */ + uint8_t table_1502A630[]; /* some table to make struct size flexible. */ +}; + +/* insert a new item into huffman tree. */ +void libmpq__huffman_insert_item( + struct huffman_tree_item_s **p_item, + struct huffman_tree_item_s *item, + uint32_t where, + struct huffman_tree_item_s *item2 +); + +/* remove item from huffman tree. */ +void libmpq__huffman_remove_item( + struct huffman_tree_item_s *hi +); + +/* get previous item from huffman tree. */ +struct huffman_tree_item_s *libmpq__huffman_previous_item( + struct huffman_tree_item_s *hi, + long value +); + +/* get one bit from stream. */ +uint32_t libmpq__huffman_get_1bit( + struct huffman_input_stream_s *is +); + +/* get seven bit from stream. */ +uint32_t libmpq__huffman_get_7bit( + struct huffman_input_stream_s *is +); + +/* get eight bit from stream. */ +uint32_t libmpq__huffman_get_8bit( + struct huffman_input_stream_s *is +); + +/* call 1500E740. */ +struct huffman_tree_item_s *libmpq__huffman_call_1500E740( + struct huffman_tree_s *ht +); + +/* call 1500E820- */ +void libmpq__huffman_call_1500E820( + struct huffman_tree_s *ht, + struct huffman_tree_item_s *p_item +); + +/* initialize the huffman tree. */ +void libmpq__huffman_tree_init( + struct huffman_tree_s *ht, + uint32_t cmp +); + +/* build the huffman tree. */ +void libmpq__huffman_tree_build( + struct huffman_tree_s *ht, + uint32_t cmp_type +); + +/* decompress the stream using huffman compression. */ +int32_t libmpq__do_decompress_huffman( + struct huffman_tree_s *ht, + struct huffman_input_stream_s *is, + uint8_t *out_buf, + uint32_t out_length +); + +#endif /* _HUFFMAN_H */ diff --git a/dep/libmpq/libmpq/mpq-internal.h b/dep/libmpq/libmpq/mpq-internal.h new file mode 100644 index 00000000000..76eabe4190a --- /dev/null +++ b/dep/libmpq/libmpq/mpq-internal.h @@ -0,0 +1,145 @@ +/* + * mpq-internal.h -- some default types and defines, but only required for + * compilation of the library. + * + * Copyright (c) 2003-2008 Maik Broemme + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef _MPQ_INTERNAL_H +#define _MPQ_INTERNAL_H + +/* generic includes. */ +#include +#include + +/* define return value if nothing failed. */ +#define LIBMPQ_SUCCESS 0 /* return value for all functions which success. */ + +/* define generic mpq archive information. */ +#define LIBMPQ_HEADER 0x1A51504D /* mpq archive header ('MPQ\x1A') */ + +/* define the known archive versions. */ +#define LIBMPQ_ARCHIVE_VERSION_ONE 0 /* version one used until world of warcraft. */ +#define LIBMPQ_ARCHIVE_VERSION_TWO 1 /* version two used from world of warcraft - the burning crusade. */ + +/* define values used by blizzard as flags. */ +#define LIBMPQ_FLAG_EXISTS 0x80000000 /* set if file exists, reset when the file was deleted. */ +#define LIBMPQ_FLAG_ENCRYPTED 0x00010000 /* indicates whether file is encrypted. */ +#define LIBMPQ_FLAG_COMPRESSED 0x0000FF00 /* file is compressed. */ +#define LIBMPQ_FLAG_COMPRESS_PKZIP 0x00000100 /* compression made by pkware data compression library. */ +#define LIBMPQ_FLAG_COMPRESS_MULTI 0x00000200 /* multiple compressions. */ +#define LIBMPQ_FLAG_COMPRESS_NONE 0x00000300 /* no compression (no blizzard flag used by myself). */ +#define LIBMPQ_FLAG_SINGLE 0x01000000 /* file is stored in one single sector, first seen in world of warcraft. */ +#define LIBMPQ_FLAG_CRC 0x04000000 /* compressed block offset table has CRC checksum. */ + +/* define generic hash values. */ +#define LIBMPQ_HASH_FREE 0xFFFFFFFF /* hash table entry is empty and has always been empty. */ + +/* define special files. */ +#define LIBMPQ_LISTFILE_NAME "(listfile)" /* internal listfile. */ +#define LIBMPQ_SIGNATURE_NAME "(signature)" /* internal signature file. */ +#define LIBMPQ_ATTRIBUTES_NAME "(attributes)" /* internal attributes file. */ + +/* define true and false, because not all systems have them. */ +#ifndef FALSE +#define FALSE 0 +#endif +#ifndef TRUE +#define TRUE 1 +#endif + +#include "pack_begin.h" +/* mpq archive header. */ +typedef struct { + uint32_t mpq_magic; /* the 0x1A51504D ('MPQ\x1A') signature. */ + uint32_t header_size; /* mpq archive header size. */ + uint32_t archive_size; /* size of mpq archive. */ + uint16_t version; /* 0000 for starcraft and broodwar. */ + uint16_t block_size; /* size of file block is (512 * 2 ^ block size). */ + uint32_t hash_table_offset; /* file position of mpq_hash. */ + uint32_t block_table_offset; /* file position of mpq_block, each entry has 16 bytes. */ + uint32_t hash_table_count; /* number of entries in hash table. */ + uint32_t block_table_count; /* number of entries in the block table. */ +} PACK_STRUCT mpq_header_s; + +/* mpq extended archive header, used since world of warcraft - the burning crusade. */ +typedef struct { + uint64_t extended_offset; /* offset to the beginning of the extended block table, relative to the beginning of the archive. */ + uint16_t hash_table_offset_high; /* upper 16 bits of the hash table offset for large archives. */ + uint16_t block_table_offset_high;/* upper 16 bits of the block table offset for large archives.*/ +} PACK_STRUCT mpq_header_ex_s; + +/* hash entry, all files in the archive are searched by their hashes. */ +typedef struct { + uint32_t hash_a; /* the first two uint32_ts are the encrypted file. */ + uint32_t hash_b; /* the first two uint32_ts are the encrypted file. */ + uint16_t locale; /* locale information. */ + uint16_t platform; /* platform information and zero is default. */ + uint32_t block_table_index; /* index to file description block. */ +} PACK_STRUCT mpq_hash_s; + +/* file description block contains informations about the file. */ +typedef struct { + uint32_t offset; /* block file starting position in the archive. */ + uint32_t packed_size; /* packed file size. */ + uint32_t unpacked_size; /* unpacked file size. */ + uint32_t flags; /* flags. */ +} PACK_STRUCT mpq_block_s; + +/* extended file description block contains information about the offset beyond 2^32 (4GB). */ +typedef struct { + uint16_t offset_high; /* upper 16 bit of the file offset in archive. */ +} PACK_STRUCT mpq_block_ex_s; + +/* file structure used since diablo 1.00 (0x38 bytes). */ +typedef struct { + uint32_t seed; /* seed used for file decrypt. */ + uint32_t *packed_offset; /* position of each file block (only for packed files). */ + uint32_t open_count; /* number of times it has been opened - used for freeing */ +} PACK_STRUCT mpq_file_s; + +/* map structure for valid blocks and hashes (first seen in warcraft 3 archives). */ +typedef struct { + uint32_t block_table_indices; /* real mapping for file number to block entry. */ + uint32_t block_table_diff; /* block table difference between valid blocks and invalid blocks before. */ +} PACK_STRUCT mpq_map_s; +#include "pack_end.h" + +/* archive structure used since diablo 1.00 by blizzard. */ +struct mpq_archive { + + /* generic file information. */ + FILE *fp; /* file handle. */ + + /* generic size information. */ + uint32_t block_size; /* size of the mpq block. */ + off_t archive_offset; /* absolute start position of archive. */ + + /* archive related buffers and tables. */ + mpq_header_s mpq_header; /* mpq file header. */ + mpq_header_ex_s mpq_header_ex; /* mpq extended file header. */ + mpq_hash_s *mpq_hash; /* hash table. */ + mpq_block_s *mpq_block; /* block table. */ + mpq_block_ex_s *mpq_block_ex; /* extended block table. */ + mpq_file_s **mpq_file; /* pointer to the file pointers which are opened. */ + + /* non archive structure related members. */ + mpq_map_s *mpq_map; /* map table between valid blocks and hashes. */ + uint32_t files; /* number of files in archive, which could be extracted. */ +}; + +#endif /* _MPQ_INTERNAL_H */ diff --git a/dep/libmpq/libmpq/mpq.c b/dep/libmpq/libmpq/mpq.c new file mode 100644 index 00000000000..a6ab5db82d9 --- /dev/null +++ b/dep/libmpq/libmpq/mpq.c @@ -0,0 +1,1004 @@ +/* + * mpq.c -- functions for developers using libmpq. + * + * Copyright (c) 2003-2008 Maik Broemme + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +/* mpq-tools configuration includes. */ +#include "config.h" + +/* libmpq main includes. */ +#include "mpq.h" +#include "mpq-internal.h" + +/* libmpq generic includes. */ +#include "common.h" + +/* generic includes. */ +#include +#include +#include +#include + +/* support for platform specific things */ +#include "platform.h" + +/* this function returns the library version information. */ +const char *libmpq__version(void) { + + /* return version information. */ + return VERSION; +} + +static const char *__libmpq_error_strings[] = { + "success", + "open error on file", + "close error on file", + "lseek error on file", + "read error on file", + "write error on file", + "memory allocation error", + "format errror", + "init() wasn't called", + "buffer size is to small", + "file or block does not exist in archive", + "we don't know the decryption seed", + "error on unpacking file" + }; + +/* this function returns a string message for a return code. */ +const char *libmpq__strerror(int32_t returncode) { + /* check for array bounds */ + if (-returncode < 0 || -returncode > sizeof(__libmpq_error_strings)/sizeof(char*)) + return NULL; + + /* return appropriate string */ + return __libmpq_error_strings[-returncode]; +} + +/* this function read a file and verify if it is a valid mpq archive, then it read and decrypt the hash table. */ +int32_t libmpq__archive_open(mpq_archive_s **mpq_archive, const char *mpq_filename, libmpq__off_t archive_offset) { + + /* some common variables. */ + uint32_t rb = 0; + uint32_t i = 0; + uint32_t count = 0; + int32_t result = 0; + uint32_t header_search = FALSE; + + if (archive_offset == -1) { + archive_offset = 0; + header_search = TRUE; + } + + if ((*mpq_archive = calloc(1, sizeof(mpq_archive_s))) == NULL) { + + /* archive struct could not be allocated */ + return LIBMPQ_ERROR_MALLOC; + } + + /* check if file exists and is readable */ + if (((*mpq_archive)->fp = fopen(mpq_filename, "rb")) == NULL) { + + /* file could not be opened. */ + result = LIBMPQ_ERROR_OPEN; + goto error; + } + + /* assign some default values. */ + (*mpq_archive)->mpq_header.mpq_magic = 0; + (*mpq_archive)->files = 0; + + /* loop through file and search for mpq signature. */ + while (TRUE) { + + /* reset header values. */ + (*mpq_archive)->mpq_header.mpq_magic = 0; + + /* seek in file. */ + if (fseeko((*mpq_archive)->fp, archive_offset, SEEK_SET) < 0) { + + /* seek in file failed. */ + result = LIBMPQ_ERROR_SEEK; + goto error; + } + + /* read header from file. */ + if ((rb = fread(&(*mpq_archive)->mpq_header, 1, sizeof(mpq_header_s), (*mpq_archive)->fp)) != sizeof(mpq_header_s)) { + + /* no valid mpq archive. */ + result = LIBMPQ_ERROR_FORMAT; + goto error; + } + + /* check if we found a valid mpq header. */ + if ((*mpq_archive)->mpq_header.mpq_magic == LIBMPQ_HEADER) { + + /* check if we process old mpq archive version. */ + if ((*mpq_archive)->mpq_header.version == LIBMPQ_ARCHIVE_VERSION_ONE) { + + /* check if the archive is protected. */ + if ((*mpq_archive)->mpq_header.header_size != sizeof(mpq_header_s)) { + + /* correct header size. */ + (*mpq_archive)->mpq_header.header_size = sizeof(mpq_header_s); + } + } + + /* check if we process new mpq archive version. */ + if ((*mpq_archive)->mpq_header.version == LIBMPQ_ARCHIVE_VERSION_TWO) { + + /* check if the archive is protected. */ + if ((*mpq_archive)->mpq_header.header_size != sizeof(mpq_header_s) + sizeof(mpq_header_ex_s)) { + + /* correct header size. */ + (*mpq_archive)->mpq_header.header_size = sizeof(mpq_header_s) + sizeof(mpq_header_ex_s); + } + } + + /* break the loop, because header was found. */ + break; + } + + /* move to the next possible offset. */ + if (!header_search) { + + /* no valid mpq archive. */ + result = LIBMPQ_ERROR_FORMAT; + goto error; + } + archive_offset += 512; + } + + /* store block size for later use. */ + (*mpq_archive)->block_size = 512 << (*mpq_archive)->mpq_header.block_size; + + /* store archive offset and size for later use. */ + (*mpq_archive)->archive_offset = archive_offset; + + /* check if we process new mpq archive version. */ + if ((*mpq_archive)->mpq_header.version == LIBMPQ_ARCHIVE_VERSION_TWO) { + + /* seek in file. */ + if (fseeko((*mpq_archive)->fp, sizeof(mpq_header_s) + archive_offset, SEEK_SET) < 0) { + + /* seek in file failed. */ + result = LIBMPQ_ERROR_SEEK; + goto error; + } + + /* read header from file. */ + if ((rb = fread(&(*mpq_archive)->mpq_header_ex, 1, sizeof(mpq_header_ex_s), (*mpq_archive)->fp)) != sizeof(mpq_header_ex_s)) { + + /* no valid mpq archive. */ + result = LIBMPQ_ERROR_FORMAT; + goto error; + } + } + + /* allocate memory for the block table, hash table, file and block table to file mapping. */ + if (((*mpq_archive)->mpq_block = calloc((*mpq_archive)->mpq_header.block_table_count, sizeof(mpq_block_s))) == NULL || + ((*mpq_archive)->mpq_block_ex = calloc((*mpq_archive)->mpq_header.block_table_count, sizeof(mpq_block_ex_s))) == NULL || + ((*mpq_archive)->mpq_hash = calloc((*mpq_archive)->mpq_header.hash_table_count, sizeof(mpq_hash_s))) == NULL || + ((*mpq_archive)->mpq_file = calloc((*mpq_archive)->mpq_header.block_table_count, sizeof(mpq_file_s))) == NULL || + ((*mpq_archive)->mpq_map = calloc((*mpq_archive)->mpq_header.block_table_count, sizeof(mpq_map_s))) == NULL) { + + /* memory allocation problem. */ + result = LIBMPQ_ERROR_MALLOC; + goto error; + } + + /* seek in file. */ + if (fseeko((*mpq_archive)->fp, (*mpq_archive)->mpq_header.hash_table_offset + (((long long)((*mpq_archive)->mpq_header_ex.hash_table_offset_high)) << 32) + (*mpq_archive)->archive_offset, SEEK_SET) < 0) { + + /* seek in file failed. */ + result = LIBMPQ_ERROR_SEEK; + goto error; + } + + /* read the hash table into the buffer. */ + if ((rb = fread((*mpq_archive)->mpq_hash, 1, (*mpq_archive)->mpq_header.hash_table_count * sizeof(mpq_hash_s), (*mpq_archive)->fp)) < 0) { + + /* something on read failed. */ + result = LIBMPQ_ERROR_READ; + goto error; + } + + /* decrypt the hashtable. */ + libmpq__decrypt_block((uint32_t *)((*mpq_archive)->mpq_hash), (*mpq_archive)->mpq_header.hash_table_count * sizeof(mpq_hash_s), libmpq__hash_string("(hash table)", 0x300)); + + /* seek in file. */ + if (fseeko((*mpq_archive)->fp, (*mpq_archive)->mpq_header.block_table_offset + (((long long)((*mpq_archive)->mpq_header_ex.block_table_offset_high)) << 32) + (*mpq_archive)->archive_offset, SEEK_SET) < 0) { + + /* seek in file failed. */ + result = LIBMPQ_ERROR_SEEK; + goto error; + } + + /* read the block table into the buffer. */ + if ((rb = fread((*mpq_archive)->mpq_block, 1, (*mpq_archive)->mpq_header.block_table_count * sizeof(mpq_block_s), (*mpq_archive)->fp)) < 0) { + + /* something on read failed. */ + result = LIBMPQ_ERROR_READ; + goto error; + } + + /* decrypt block table. */ + libmpq__decrypt_block((uint32_t *)((*mpq_archive)->mpq_block), (*mpq_archive)->mpq_header.block_table_count * sizeof(mpq_block_s), libmpq__hash_string("(block table)", 0x300)); + + /* check if extended block table is present, regardless of version 2 it is only present in archives > 4GB. */ + if ((*mpq_archive)->mpq_header_ex.extended_offset > 0) { + + /* seek in file. */ + if (fseeko((*mpq_archive)->fp, (*mpq_archive)->mpq_header_ex.extended_offset + archive_offset, SEEK_SET) < 0) { + + /* seek in file failed. */ + result = LIBMPQ_ERROR_SEEK; + goto error; + } + + /* read header from file. */ + if ((rb = fread((*mpq_archive)->mpq_block_ex, 1, (*mpq_archive)->mpq_header.block_table_count * sizeof(mpq_block_ex_s), (*mpq_archive)->fp)) < 0) { + + /* no valid mpq archive. */ + result = LIBMPQ_ERROR_FORMAT; + goto error; + } + } + + /* loop through all files in mpq archive and check if they are valid. */ + for (i = 0; i < (*mpq_archive)->mpq_header.block_table_count; i++) { + + /* save block difference between valid and invalid blocks. */ + (*mpq_archive)->mpq_map[i].block_table_diff = i - count; + + /* check if file exists, sizes and offsets are correct. */ + if (((*mpq_archive)->mpq_block[i].flags & LIBMPQ_FLAG_EXISTS) == 0) { + + /* file does not exist, so nothing to do with that block. */ + continue; + } + + /* create final indices tables. */ + (*mpq_archive)->mpq_map[count].block_table_indices = i; + + /* increase file counter. */ + count++; + } + + /* save the number of files. */ + (*mpq_archive)->files = count; + + /* if no error was found, return zero. */ + return LIBMPQ_SUCCESS; + +error: + if ((*mpq_archive)->fp) + fclose((*mpq_archive)->fp); + + free((*mpq_archive)->mpq_map); + free((*mpq_archive)->mpq_file); + free((*mpq_archive)->mpq_hash); + free((*mpq_archive)->mpq_block); + free((*mpq_archive)->mpq_block_ex); + free(*mpq_archive); + + *mpq_archive = NULL; + + return result; +} + +/* this function close the file descriptor, free the decryption buffer and the file list. */ +int32_t libmpq__archive_close(mpq_archive_s *mpq_archive) { + + /* try to close the file */ + if ((fclose(mpq_archive->fp)) < 0) { + + /* don't free anything here, so the caller can try calling us + * again. + */ + return LIBMPQ_ERROR_CLOSE; + } + + /* free header, tables and list. */ + free(mpq_archive->mpq_map); + free(mpq_archive->mpq_file); + free(mpq_archive->mpq_hash); + free(mpq_archive->mpq_block); + free(mpq_archive->mpq_block_ex); + free(mpq_archive); + + /* if no error was found, return zero. */ + return LIBMPQ_SUCCESS; +} + +/* this function return the packed size of all files in the archive. */ +int32_t libmpq__archive_packed_size(mpq_archive_s *mpq_archive, libmpq__off_t *packed_size) { + + /* some common variables. */ + uint32_t i; + + /* loop through all files in archive and count packed size. */ + for (i = 0; i < mpq_archive->files; i++) { + *packed_size += mpq_archive->mpq_block[mpq_archive->mpq_map[i].block_table_indices].packed_size; + } + + /* if no error was found, return zero. */ + return LIBMPQ_SUCCESS; +} + +/* this function return the unpacked size of all files in the archive. */ +int32_t libmpq__archive_unpacked_size(mpq_archive_s *mpq_archive, libmpq__off_t *unpacked_size) { + + /* some common variables. */ + uint32_t i; + + /* loop through all files in archive and count unpacked size. */ + for (i = 0; i < mpq_archive->files; i++) { + *unpacked_size += mpq_archive->mpq_block[mpq_archive->mpq_map[i].block_table_indices].unpacked_size; + } + + /* if no error was found, return zero. */ + return LIBMPQ_SUCCESS; +} + +/* this function return the archive offset (beginning of archive in file). */ +int32_t libmpq__archive_offset(mpq_archive_s *mpq_archive, libmpq__off_t *offset) { + + /* return archive offset. */ + *offset = mpq_archive->archive_offset; + + /* if no error was found, return zero. */ + return LIBMPQ_SUCCESS; +} + +/* this function return the archive offset. */ +int32_t libmpq__archive_version(mpq_archive_s *mpq_archive, uint32_t *version) { + + /* return archive version. */ + *version = mpq_archive->mpq_header.version + 1; + + /* if no error was found, return zero. */ + return LIBMPQ_SUCCESS; +} + +/* this function return the number of valid files in archive. */ +int32_t libmpq__archive_files(mpq_archive_s *mpq_archive, uint32_t *files) { + + /* return archive version. */ + *files = mpq_archive->files; + + /* if no error was found, return zero. */ + return LIBMPQ_SUCCESS; +} + +#define CHECK_FILE_NUM(file_number, mpq_archive) \ + if (file_number < 0 || file_number > mpq_archive->files - 1) { \ + return LIBMPQ_ERROR_EXIST; \ + } + +#define CHECK_BLOCK_NUM(block_number, mpq_archive) \ + if (block_number < 0 || block_number >= ((mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].flags & LIBMPQ_FLAG_SINGLE) != 0 ? 1 : (mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].unpacked_size + mpq_archive->block_size - 1) / mpq_archive->block_size)) { \ + return LIBMPQ_ERROR_EXIST; \ + } + +/* this function return the packed size of the given files in the archive. */ +int32_t libmpq__file_packed_size(mpq_archive_s *mpq_archive, uint32_t file_number, libmpq__off_t *packed_size) { + + /* check if given file number is not out of range. */ + CHECK_FILE_NUM(file_number, mpq_archive) + + /* get the packed size of file. */ + *packed_size = mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].packed_size; + + /* if no error was found, return zero. */ + return LIBMPQ_SUCCESS; +} + +/* this function return the unpacked size of the given file in the archive. */ +int32_t libmpq__file_unpacked_size(mpq_archive_s *mpq_archive, uint32_t file_number, libmpq__off_t *unpacked_size) { + + /* check if given file number is not out of range. */ + CHECK_FILE_NUM(file_number, mpq_archive) + + /* get the unpacked size of file. */ + *unpacked_size = mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].unpacked_size; + + /* if no error was found, return zero. */ + return LIBMPQ_SUCCESS; +} + +/* this function return the file offset (beginning of file in archive). */ +int32_t libmpq__file_offset(mpq_archive_s *mpq_archive, uint32_t file_number, libmpq__off_t *offset) { + + /* check if given file number is not out of range. */ + CHECK_FILE_NUM(file_number, mpq_archive) + + /* return file offset relative to archive start. */ + *offset = mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].offset + (((long long)mpq_archive->mpq_block_ex[mpq_archive->mpq_map[file_number].block_table_indices].offset_high) << 32); + + /* if no error was found, return zero. */ + return LIBMPQ_SUCCESS; +} + +/* this function return the number of blocks for the given file in the archive. */ +int32_t libmpq__file_blocks(mpq_archive_s *mpq_archive, uint32_t file_number, uint32_t *blocks) { + + /* check if given file number is not out of range. */ + CHECK_FILE_NUM(file_number, mpq_archive) + + /* return the number of blocks for the given file. */ + *blocks = (mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].flags & LIBMPQ_FLAG_SINGLE) != 0 ? 1 : (mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].unpacked_size + mpq_archive->block_size - 1) / mpq_archive->block_size; + + /* if no error was found, return zero. */ + return LIBMPQ_SUCCESS; +} + +/* this function return if the file is encrypted or not. */ +int32_t libmpq__file_encrypted(mpq_archive_s *mpq_archive, uint32_t file_number, uint32_t *encrypted) { + + /* check if given file number is not out of range. */ + CHECK_FILE_NUM(file_number, mpq_archive) + + /* return the encryption status of file. */ + *encrypted = (mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].flags & LIBMPQ_FLAG_ENCRYPTED) != 0 ? TRUE : FALSE; + + /* if no error was found, return zero. */ + return LIBMPQ_SUCCESS; +} + +/* this function return if the file is compressed or not. */ +int32_t libmpq__file_compressed(mpq_archive_s *mpq_archive, uint32_t file_number, uint32_t *compressed) { + + /* check if given file number is not out of range. */ + CHECK_FILE_NUM(file_number, mpq_archive) + + /* return the compression status of file. */ + *compressed = (mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].flags & LIBMPQ_FLAG_COMPRESS_MULTI) != 0 ? TRUE : FALSE; + + /* if no error was found, return zero. */ + return LIBMPQ_SUCCESS; +} + +/* this function return if the file is imploded or not. */ +int32_t libmpq__file_imploded(mpq_archive_s *mpq_archive, uint32_t file_number, uint32_t *imploded) { + + /* check if given file number is not out of range. */ + CHECK_FILE_NUM(file_number, mpq_archive) + + /* return the implosion status of file. */ + *imploded = (mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].flags & LIBMPQ_FLAG_COMPRESS_PKZIP) != 0 ? TRUE : FALSE; + + /* if no error was found, return zero. */ + return LIBMPQ_SUCCESS; +} + +/* this function return filenumber by the given name. */ +int32_t libmpq__file_number(mpq_archive_s *mpq_archive, const char *filename, uint32_t *number) { + + /* some common variables. */ + uint32_t i, hash1, hash2, hash3, ht_count; + + /* if the list of file names doesn't include this one, we'll have + * to figure out the file number the "hard" way. + */ + ht_count = mpq_archive->mpq_header.hash_table_count; + + hash1 = libmpq__hash_string (filename, 0x0) & (ht_count - 1); + hash2 = libmpq__hash_string (filename, 0x100); + hash3 = libmpq__hash_string (filename, 0x200); + + /* loop through all files in mpq archive. + * hash1 gives us a clue about the starting position of this + * search. + */ + for (i = hash1; mpq_archive->mpq_hash[i].block_table_index != LIBMPQ_HASH_FREE; i = (i + 1) & (ht_count - 1)) { + + /* if the other two hashes match, we found our file number. */ + if (mpq_archive->mpq_hash[i].hash_a == hash2 && + mpq_archive->mpq_hash[i].hash_b == hash3) { + + /* return the file number. */ + *number = mpq_archive->mpq_hash[i].block_table_index - mpq_archive->mpq_map[mpq_archive->mpq_hash[i].block_table_index].block_table_diff; + + /* we found our file, return zero. */ + return LIBMPQ_SUCCESS; + } + + /* check if we have cycled through the whole hash table */ + if (((i + 1) & (ht_count - 1)) == hash1) { + break; + } + } + + /* if no matching entry found, so return error. */ + return LIBMPQ_ERROR_EXIST; +} + +/* this function read the given file from archive into a buffer. */ +int32_t libmpq__file_read(mpq_archive_s *mpq_archive, uint32_t file_number, uint8_t *out_buf, libmpq__off_t out_size, libmpq__off_t *transferred) { + + /* some common variables. */ + uint32_t i; + uint32_t blocks = 0; + int32_t result = 0; + libmpq__off_t file_offset = 0; + libmpq__off_t unpacked_size = 0; + libmpq__off_t transferred_block = 0; + libmpq__off_t transferred_total = 0; + + /* check if given file number is not out of range. */ + CHECK_FILE_NUM(file_number, mpq_archive) + + /* get target size of block. */ + libmpq__file_unpacked_size(mpq_archive, file_number, &unpacked_size); + + /* check if target buffer is to small. */ + if (unpacked_size > out_size) { + + /* output buffer size is to small or block size is unknown. */ + return LIBMPQ_ERROR_SIZE; + } + + /* fetch file offset. */ + libmpq__file_offset(mpq_archive, file_number, &file_offset); + + /* get block count for file. */ + libmpq__file_blocks(mpq_archive, file_number, &blocks); + + /* open the packed block offset table. */ + if ((result = libmpq__block_open_offset(mpq_archive, file_number)) < 0) { + + /* something on opening packed block offset table failed. */ + return result; + } + + /* loop through all blocks. */ + for (i = 0; i < blocks; i++) { + + /* cleanup size variable. */ + unpacked_size = 0; + + /* get unpacked block size. */ + libmpq__block_unpacked_size(mpq_archive, file_number, i, &unpacked_size); + + /* read block. */ + if ((result = libmpq__block_read(mpq_archive, file_number, i, out_buf + transferred_total, unpacked_size, &transferred_block)) < 0) { + + /* close the packed block offset table. */ + libmpq__block_close_offset(mpq_archive, file_number); + + /* something on reading block failed. */ + return result; + } + + transferred_total += transferred_block; + + } + + /* close the packed block offset table. */ + libmpq__block_close_offset(mpq_archive, file_number); + + /* check for null pointer. */ + if (transferred != NULL) { + + /* store transferred bytes. */ + *transferred = transferred_total; + } + + /* if no error was found, return zero. */ + return LIBMPQ_SUCCESS; +} + +/* this function open a file in the given archive and caches the block offset information. */ +int32_t libmpq__block_open_offset(mpq_archive_s *mpq_archive, uint32_t file_number) { + + /* some common variables. */ + uint32_t i; + uint32_t packed_size; + int32_t rb = 0; + int32_t result = 0; + + /* check if given file number is not out of range. */ + CHECK_FILE_NUM(file_number, mpq_archive) + + if (mpq_archive->mpq_file[file_number]) { + + /* file already opened, so increment counter */ + mpq_archive->mpq_file[file_number]->open_count++; + return LIBMPQ_SUCCESS; + } + + /* check if file is not stored in a single sector. */ + if ((mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].flags & LIBMPQ_FLAG_SINGLE) == 0) { + + /* get packed size based on block size and block count. */ + packed_size = sizeof(uint32_t) * (((mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].unpacked_size + mpq_archive->block_size - 1) / mpq_archive->block_size) + 1); + } else { + + /* file is stored in single sector and we need only two entries for the packed block offset table. */ + packed_size = sizeof(uint32_t) * 2; + } + + /* check if data has one extra entry. */ + if ((mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].flags & LIBMPQ_FLAG_CRC) != 0) { + + /* add one uint32_t. */ + packed_size += sizeof(uint32_t); + } + + /* allocate memory for the file. */ + if ((mpq_archive->mpq_file[file_number] = calloc(1, sizeof(mpq_file_s))) == NULL) { + + /* memory allocation problem. */ + result = LIBMPQ_ERROR_MALLOC; + goto error; + } + + /* allocate memory for the packed block offset table. */ + if ((mpq_archive->mpq_file[file_number]->packed_offset = calloc(1, packed_size)) == NULL) { + + /* memory allocation problem. */ + result = LIBMPQ_ERROR_MALLOC; + goto error; + } + + /* initialize counter to one opening */ + mpq_archive->mpq_file[file_number]->open_count = 1; + + /* check if we need to load the packed block offset table, we will maintain this table for unpacked files too. */ + if ((mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].flags & LIBMPQ_FLAG_COMPRESSED) != 0 && + (mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].flags & LIBMPQ_FLAG_SINGLE) == 0) { + + /* seek to block position. */ + if (fseeko(mpq_archive->fp, mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].offset + (((long long)mpq_archive->mpq_block_ex[mpq_archive->mpq_map[file_number].block_table_indices].offset_high) << 32) + mpq_archive->archive_offset, SEEK_SET) < 0) { + + /* seek in file failed. */ + result = LIBMPQ_ERROR_SEEK; + goto error; + } + + /* read block positions from begin of file. */ + if ((rb = fread(mpq_archive->mpq_file[file_number]->packed_offset, 1, packed_size, mpq_archive->fp)) < 0) { + + /* something on read from archive failed. */ + result = LIBMPQ_ERROR_READ; + goto error; + } + + /* check if the archive is protected some way, sometimes the file appears not to be encrypted, but it is. + * a special case are files with an additional sector but LIBMPQ_FLAG_CRC not set. we don't want to handle + * them as encrypted. */ + if (mpq_archive->mpq_file[file_number]->packed_offset[0] != rb && + mpq_archive->mpq_file[file_number]->packed_offset[0] != rb + 4) { + + /* file is encrypted. */ + mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].flags |= LIBMPQ_FLAG_ENCRYPTED; + } + + /* check if packed offset block is encrypted, we have to decrypt it. */ + if (mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].flags & LIBMPQ_FLAG_ENCRYPTED) { + + /* check if we don't know the file seed, try to find it. */ + if (libmpq__decrypt_key((uint8_t *)mpq_archive->mpq_file[file_number]->packed_offset, packed_size, mpq_archive->block_size, &mpq_archive->mpq_file[file_number]->seed) < 0) { + + /* sorry without seed, we cannot extract file. */ + result = LIBMPQ_ERROR_DECRYPT; + goto error; + } + + /* decrypt block in input buffer. */ + if (libmpq__decrypt_block(mpq_archive->mpq_file[file_number]->packed_offset, packed_size, mpq_archive->mpq_file[file_number]->seed - 1) < 0 ) { + + /* something on decrypt failed. */ + result = LIBMPQ_ERROR_DECRYPT; + goto error; + } + + /* check if the block positions are correctly decrypted. */ + if (mpq_archive->mpq_file[file_number]->packed_offset[0] != packed_size) { + + /* sorry without seed, we cannot extract file. */ + result = LIBMPQ_ERROR_DECRYPT; + goto error; + } + } + } else { + + /* check if file is not stored in a single sector. */ + if ((mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].flags & LIBMPQ_FLAG_SINGLE) == 0) { + + /* loop through all blocks and create packed block offset table based on block size. */ + for (i = 0; i < ((mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].unpacked_size + mpq_archive->block_size - 1) / mpq_archive->block_size + 1); i++) { + + /* check if we process the last block. */ + if (i == ((mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].unpacked_size + mpq_archive->block_size - 1) / mpq_archive->block_size)) { + + /* store size of last block. */ + mpq_archive->mpq_file[file_number]->packed_offset[i] = mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].unpacked_size; + } else { + + /* store default block size. */ + mpq_archive->mpq_file[file_number]->packed_offset[i] = i * mpq_archive->block_size; + } + } + } else { + + /* store offsets. */ + mpq_archive->mpq_file[file_number]->packed_offset[0] = 0; + mpq_archive->mpq_file[file_number]->packed_offset[1] = mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].packed_size; + } + } + + /* if no error was found, return zero. */ + return LIBMPQ_SUCCESS; + +error: + + /* free packed block offset table and file pointer. */ + free(mpq_archive->mpq_file[file_number]->packed_offset); + free(mpq_archive->mpq_file[file_number]); + + /* return error constant. */ + return result; +} + +/* this function free the file pointer to the opened file in archive. */ +int32_t libmpq__block_close_offset(mpq_archive_s *mpq_archive, uint32_t file_number) { + + /* check if given file number is not out of range. */ + CHECK_FILE_NUM(file_number, mpq_archive) + + if (mpq_archive->mpq_file[file_number] == NULL) { + + /* packed block offset table is not opened. */ + return LIBMPQ_ERROR_OPEN; + } + + mpq_archive->mpq_file[file_number]->open_count--; + + if (mpq_archive->mpq_file[file_number]->open_count != 0) { + + /* still in use */ + return LIBMPQ_SUCCESS; + } + + /* free packed block offset table and file pointer. */ + free(mpq_archive->mpq_file[file_number]->packed_offset); + free(mpq_archive->mpq_file[file_number]); + + /* mark it as unopened - libmpq__block_open_offset checks for this to decide whether to increment the counter */ + mpq_archive->mpq_file[file_number] = NULL; + + /* if no error was found, return zero. */ + return LIBMPQ_SUCCESS; +} + +/* this function return the unpacked size of the given file and block in the archive. */ +int32_t libmpq__block_unpacked_size(mpq_archive_s *mpq_archive, uint32_t file_number, uint32_t block_number, libmpq__off_t *unpacked_size) { + + /* check if given file number is not out of range. */ + CHECK_FILE_NUM(file_number, mpq_archive) + + /* check if given block number is not out of range. */ + CHECK_BLOCK_NUM(block_number, mpq_archive) + + /* check if packed block offset table is opened. */ + if (mpq_archive->mpq_file[file_number] == NULL || + mpq_archive->mpq_file[file_number]->packed_offset == NULL) { + + /* packed block offset table is not opened. */ + return LIBMPQ_ERROR_OPEN; + } + + /* check if block is stored as single sector. */ + if ((mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].flags & LIBMPQ_FLAG_SINGLE) != 0) { + + /* return the unpacked size of the block in the mpq archive. */ + *unpacked_size = mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].unpacked_size; + } + + /* check if block is not stored as single sector. */ + if ((mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].flags & LIBMPQ_FLAG_SINGLE) == 0) { + + /* check if we not process the last block. */ + if (block_number < ((mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].unpacked_size + mpq_archive->block_size - 1) / mpq_archive->block_size) - 1) { + + /* return the block size as unpacked size. */ + *unpacked_size = mpq_archive->block_size; + } else { + + /* return the unpacked size of the last block in the mpq archive. */ + *unpacked_size = mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].unpacked_size - mpq_archive->block_size * block_number; + } + } + + /* if no error was found, return zero. */ + return LIBMPQ_SUCCESS; +} + +/* this function return the decryption seed for the given file and block. */ +int32_t libmpq__block_seed(mpq_archive_s *mpq_archive, uint32_t file_number, uint32_t block_number, uint32_t *seed) { + + /* check if given file number is not out of range. */ + CHECK_FILE_NUM(file_number, mpq_archive) + + /* check if given block number is not out of range. */ + CHECK_BLOCK_NUM(block_number, mpq_archive) + + /* check if packed block offset table is opened. */ + if (mpq_archive->mpq_file[file_number] == NULL || + mpq_archive->mpq_file[file_number]->packed_offset == NULL) { + + /* packed block offset table is not opened. */ + return LIBMPQ_ERROR_OPEN; + } + + /* return the decryption key. */ + *seed = mpq_archive->mpq_file[file_number]->seed + block_number; + + /* if no error was found, return zero. */ + return LIBMPQ_SUCCESS; +} + +/* this function read the given block from archive into a buffer. */ +int32_t libmpq__block_read(mpq_archive_s *mpq_archive, uint32_t file_number, uint32_t block_number, uint8_t *out_buf, libmpq__off_t out_size, libmpq__off_t *transferred) { + + /* some common variables. */ + uint8_t *in_buf; + uint32_t seed = 0; + uint32_t encrypted = 0; + uint32_t compressed = 0; + uint32_t imploded = 0; + int32_t tb = 0; + libmpq__off_t block_offset = 0; + off_t in_size = 0; + libmpq__off_t unpacked_size = 0; + + /* check if given file number is not out of range. */ + CHECK_FILE_NUM(file_number, mpq_archive) + + /* check if given block number is not out of range. */ + CHECK_BLOCK_NUM(block_number, mpq_archive) + + /* check if packed block offset table is opened. */ + if (mpq_archive->mpq_file[file_number] == NULL || + mpq_archive->mpq_file[file_number]->packed_offset == NULL) { + + /* packed block offset table is not opened. */ + return LIBMPQ_ERROR_OPEN; + } + + /* get target size of block. */ + libmpq__block_unpacked_size(mpq_archive, file_number, block_number, &unpacked_size); + + /* check if target buffer is to small. */ + if (unpacked_size > out_size) { + + /* output buffer size is to small or block size is unknown. */ + return LIBMPQ_ERROR_SIZE; + } + + /* fetch some required values like input buffer size and block offset. */ + block_offset = mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].offset + (((long long)mpq_archive->mpq_block_ex[mpq_archive->mpq_map[file_number].block_table_indices].offset_high) << 32) + mpq_archive->mpq_file[file_number]->packed_offset[block_number]; + in_size = mpq_archive->mpq_file[file_number]->packed_offset[block_number + 1] - mpq_archive->mpq_file[file_number]->packed_offset[block_number]; + + /* seek in file. */ + if (fseeko(mpq_archive->fp, block_offset + mpq_archive->archive_offset, SEEK_SET) < 0) { + + /* something with seek in file failed. */ + return LIBMPQ_ERROR_SEEK; + } + + /* allocate memory for the read buffer. */ + if ((in_buf = calloc(1, in_size)) == NULL) { + + /* memory allocation problem. */ + return LIBMPQ_ERROR_MALLOC; + } + + /* read block from file. */ + if (fread(in_buf, 1, in_size, mpq_archive->fp) < 0) { + + /* free buffers. */ + free(in_buf); + + /* something on reading block failed. */ + return LIBMPQ_ERROR_READ; + } + + /* get encryption status. */ + libmpq__file_encrypted(mpq_archive, file_number, &encrypted); + + /* check if file is encrypted. */ + if (encrypted == 1) { + + /* get decryption key. */ + libmpq__block_seed(mpq_archive, file_number, block_number, &seed); + + /* decrypt block. */ + if (libmpq__decrypt_block((uint32_t *)in_buf, in_size, seed) < 0) { + + /* free buffers. */ + free(in_buf); + + /* something on decrypting block failed. */ + return LIBMPQ_ERROR_DECRYPT; + } + } + + /* get compression status. */ + libmpq__file_compressed(mpq_archive, file_number, &compressed); + + /* check if file is compressed. */ + if (compressed == 1) { + + /* decompress block. */ + if ((tb = libmpq__decompress_block(in_buf, in_size, out_buf, out_size, LIBMPQ_FLAG_COMPRESS_MULTI)) < 0) { + + /* free temporary buffer. */ + free(in_buf); + + /* something on decompressing block failed. */ + return LIBMPQ_ERROR_UNPACK; + } + } + + /* get implosion status. */ + libmpq__file_imploded(mpq_archive, file_number, &imploded); + + /* check if file is imploded. */ + if (imploded == 1) { + + /* explode block. */ + if ((tb = libmpq__decompress_block(in_buf, in_size, out_buf, out_size, LIBMPQ_FLAG_COMPRESS_PKZIP)) < 0) { + + /* free temporary buffer. */ + free(in_buf); + + /* something on decompressing block failed. */ + return LIBMPQ_ERROR_UNPACK; + } + } + + /* check if file is neither compressed nor imploded. */ + if (compressed == 0 && imploded == 0) { + + /* copy block. */ + if ((tb = libmpq__decompress_block(in_buf, in_size, out_buf, out_size, LIBMPQ_FLAG_COMPRESS_NONE)) < 0) { + + /* free temporary buffer. */ + free(in_buf); + + /* something on decompressing block failed. */ + return LIBMPQ_ERROR_UNPACK; + } + } + + /* free read buffer. */ + free(in_buf); + + /* check for null pointer. */ + if (transferred != NULL) { + + /* store transferred bytes. */ + *transferred = tb; + } + + /* if no error was found, return zero. */ + return LIBMPQ_SUCCESS; +} diff --git a/dep/libmpq/libmpq/mpq.h b/dep/libmpq/libmpq/mpq.h new file mode 100644 index 00000000000..abd4862c334 --- /dev/null +++ b/dep/libmpq/libmpq/mpq.h @@ -0,0 +1,101 @@ +/* + * mpq.h -- some default types and defines. + * + * Copyright (c) 2003-2008 Maik Broemme + * + * Some parts (the encryption and decryption stuff) were adapted from + * the C++ version of StormLib.h and StormPort.h included in stormlib. + * The C++ version belongs to the following authors: + * + * Ladislav Zezula + * Marko Friedemann + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef _MPQ_H +#define _MPQ_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* generic includes. */ +#include +#include + +#if defined(__GNUC__) && (__GNUC__ >= 4) +# define LIBMPQ_API __attribute__((visibility("default"))) +#else +# define LIBMPQ_API +#endif + +/* define errors. */ +#define LIBMPQ_ERROR_OPEN -1 /* open error on file. */ +#define LIBMPQ_ERROR_CLOSE -2 /* close error on file. */ +#define LIBMPQ_ERROR_SEEK -3 /* lseek error on file. */ +#define LIBMPQ_ERROR_READ -4 /* read error on file. */ +#define LIBMPQ_ERROR_WRITE -5 /* write error on file. */ +#define LIBMPQ_ERROR_MALLOC -6 /* memory allocation error. */ +#define LIBMPQ_ERROR_FORMAT -7 /* format errror. */ +#define LIBMPQ_ERROR_NOT_INITIALIZED -8 /* libmpq__init() wasn't called. */ +#define LIBMPQ_ERROR_SIZE -9 /* buffer size is to small. */ +#define LIBMPQ_ERROR_EXIST -10 /* file or block does not exist in archive. */ +#define LIBMPQ_ERROR_DECRYPT -11 /* we don't know the decryption seed. */ +#define LIBMPQ_ERROR_UNPACK -12 /* error on unpacking file. */ + +/* internal data structure. */ +typedef struct mpq_archive mpq_archive_s; + +/* file offset data type for API*/ +typedef int64_t libmpq__off_t; + +/* generic information about library. */ +extern LIBMPQ_API const char *libmpq__version(void); + +/* string error message for a libmpq return code. */ +extern LIBMPQ_API const char *libmpq__strerror(int32_t returncode); + +/* generic mpq archive information. */ +extern LIBMPQ_API int32_t libmpq__archive_open(mpq_archive_s **mpq_archive, const char *mpq_filename, libmpq__off_t archive_offset); +extern LIBMPQ_API int32_t libmpq__archive_close(mpq_archive_s *mpq_archive); +extern LIBMPQ_API int32_t libmpq__archive_packed_size(mpq_archive_s *mpq_archive, libmpq__off_t *packed_size); +extern LIBMPQ_API int32_t libmpq__archive_unpacked_size(mpq_archive_s *mpq_archive, libmpq__off_t *unpacked_size); +extern LIBMPQ_API int32_t libmpq__archive_offset(mpq_archive_s *mpq_archive, libmpq__off_t *offset); +extern LIBMPQ_API int32_t libmpq__archive_version(mpq_archive_s *mpq_archive, uint32_t *version); +extern LIBMPQ_API int32_t libmpq__archive_files(mpq_archive_s *mpq_archive, uint32_t *files); + +/* generic file processing functions. */ +extern LIBMPQ_API int32_t libmpq__file_packed_size(mpq_archive_s *mpq_archive, uint32_t file_number, libmpq__off_t *packed_size); +extern LIBMPQ_API int32_t libmpq__file_unpacked_size(mpq_archive_s *mpq_archive, uint32_t file_number, libmpq__off_t *unpacked_size); +extern LIBMPQ_API int32_t libmpq__file_offset(mpq_archive_s *mpq_archive, uint32_t file_number, libmpq__off_t *offset); +extern LIBMPQ_API int32_t libmpq__file_blocks(mpq_archive_s *mpq_archive, uint32_t file_number, uint32_t *blocks); +extern LIBMPQ_API int32_t libmpq__file_encrypted(mpq_archive_s *mpq_archive, uint32_t file_number, uint32_t *encrypted); +extern LIBMPQ_API int32_t libmpq__file_compressed(mpq_archive_s *mpq_archive, uint32_t file_number, uint32_t *compressed); +extern LIBMPQ_API int32_t libmpq__file_imploded(mpq_archive_s *mpq_archive, uint32_t file_number, uint32_t *imploded); +extern LIBMPQ_API int32_t libmpq__file_number(mpq_archive_s *mpq_archive, const char *filename, uint32_t *number); +extern LIBMPQ_API int32_t libmpq__file_read(mpq_archive_s *mpq_archive, uint32_t file_number, uint8_t *out_buf, libmpq__off_t out_size, libmpq__off_t *transferred); + +/* generic block processing functions. */ +extern LIBMPQ_API int32_t libmpq__block_open_offset(mpq_archive_s *mpq_archive, uint32_t file_number); +extern LIBMPQ_API int32_t libmpq__block_close_offset(mpq_archive_s *mpq_archive, uint32_t file_number); +extern LIBMPQ_API int32_t libmpq__block_unpacked_size(mpq_archive_s *mpq_archive, uint32_t file_number, uint32_t block_number, libmpq__off_t *unpacked_size); +extern LIBMPQ_API int32_t libmpq__block_read(mpq_archive_s *mpq_archive, uint32_t file_number, uint32_t block_number, uint8_t *out_buf, libmpq__off_t out_size, libmpq__off_t *transferred); + +#ifdef __cplusplus +} +#endif + +#endif /* _MPQ_H */ diff --git a/dep/libmpq/libmpq/pack_begin.h b/dep/libmpq/libmpq/pack_begin.h new file mode 100644 index 00000000000..eb4a6ddebbb --- /dev/null +++ b/dep/libmpq/libmpq/pack_begin.h @@ -0,0 +1,34 @@ +/* + * pack_begin.h -- header file for struct packing used by libmpq. + * + * Copyright (c) 2010 Georg Lukas + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef _PACK_BEGIN +#define _PACK_BEGIN +#else +#error "pack_begin.h may not be included twice!" +#endif + +#ifdef _MSC_VER + #pragma pack(push,1) + #define PACK_STRUCT +#else + /* we assume GNU here */ + #define PACK_STRUCT __attribute__((packed)) +#endif + diff --git a/dep/libmpq/libmpq/pack_end.h b/dep/libmpq/libmpq/pack_end.h new file mode 100644 index 00000000000..a8a35113bfb --- /dev/null +++ b/dep/libmpq/libmpq/pack_end.h @@ -0,0 +1,31 @@ +/* + * pack_end.h -- header file for struct packing used by libmpq. + * + * Copyright (c) 2010 Georg Lukas + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifdef _PACK_BEGIN +#undef _PACK_BEGIN +#else +#error "pack_begin.h must be includede before pack_end.h" +#endif + +#ifdef _MSC_VER + #pragma pack(pop) +#endif + +#undef PACK_STRUCT diff --git a/dep/libmpq/libmpq/platform.h b/dep/libmpq/libmpq/platform.h new file mode 100644 index 00000000000..68fdfdc5ded --- /dev/null +++ b/dep/libmpq/libmpq/platform.h @@ -0,0 +1,28 @@ +/* + * platform.h -- header file for platform specific parts. + * + * Copyright (c) 2010 Georg Lukas + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef _PLATFORM_H +#define _PLATFORM_H + +#ifdef _MSC_VER + #define fseeko _fseeki64 +#endif + +#endif /* _PLATFORM_H */ diff --git a/dep/libmpq/libmpq/wave.c b/dep/libmpq/libmpq/wave.c new file mode 100644 index 00000000000..628593fce83 --- /dev/null +++ b/dep/libmpq/libmpq/wave.c @@ -0,0 +1,250 @@ +/* + * wave.c -- this file contains decompression methods used by mpq-tools + * to decompress wave files. + * + * Copyright (c) 2003-2007 Maik Broemme + * + * This source was adepted from the C++ version of wave.cpp included + * in stormlib. The C++ version belongs to the following authors: + * + * Ladislav Zezula + * Tom Amigo + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +/* generic includes. */ +#include + +/* libmpq generic includes. */ +#include "wave.h" + +/* table necessary dor decompression. */ +static const uint32_t wave_table_1503f120[] = { + 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF, 0x00000004, 0xFFFFFFFF, 0x00000002, 0xFFFFFFFF, 0x00000006, + 0xFFFFFFFF, 0x00000001, 0xFFFFFFFF, 0x00000005, 0xFFFFFFFF, 0x00000003, 0xFFFFFFFF, 0x00000007, + 0xFFFFFFFF, 0x00000001, 0xFFFFFFFF, 0x00000005, 0xFFFFFFFF, 0x00000003, 0xFFFFFFFF, 0x00000007, + 0xFFFFFFFF, 0x00000002, 0xFFFFFFFF, 0x00000004, 0xFFFFFFFF, 0x00000006, 0xFFFFFFFF, 0x00000008 +}; + +/* table necessary dor decompression. */ +static const uint32_t wave_table_1503f1a0[] = { + 0x00000007, 0x00000008, 0x00000009, 0x0000000A, 0x0000000B, 0x0000000C, 0x0000000D, 0x0000000E, + 0x00000010, 0x00000011, 0x00000013, 0x00000015, 0x00000017, 0x00000019, 0x0000001C, 0x0000001F, + 0x00000022, 0x00000025, 0x00000029, 0x0000002D, 0x00000032, 0x00000037, 0x0000003C, 0x00000042, + 0x00000049, 0x00000050, 0x00000058, 0x00000061, 0x0000006B, 0x00000076, 0x00000082, 0x0000008F, + 0x0000009D, 0x000000AD, 0x000000BE, 0x000000D1, 0x000000E6, 0x000000FD, 0x00000117, 0x00000133, + 0x00000151, 0x00000173, 0x00000198, 0x000001C1, 0x000001EE, 0x00000220, 0x00000256, 0x00000292, + 0x000002D4, 0x0000031C, 0x0000036C, 0x000003C3, 0x00000424, 0x0000048E, 0x00000502, 0x00000583, + 0x00000610, 0x000006AB, 0x00000756, 0x00000812, 0x000008E0, 0x000009C3, 0x00000ABD, 0x00000BD0, + 0x00000CFF, 0x00000E4C, 0x00000FBA, 0x0000114C, 0x00001307, 0x000014EE, 0x00001706, 0x00001954, + 0x00001BDC, 0x00001EA5, 0x000021B6, 0x00002515, 0x000028CA, 0x00002CDF, 0x0000315B, 0x0000364B, + 0x00003BB9, 0x000041B2, 0x00004844, 0x00004F7E, 0x00005771, 0x0000602F, 0x000069CE, 0x00007462, + 0x00007FFF +}; + +/* this function decompress a wave file, mono or stereo, 1500F230 offset. */ +int32_t libmpq__do_decompress_wave(uint8_t *out_buf, int32_t out_length, uint8_t *in_buf, int32_t in_length, int32_t channels) { + + /* some common variables. */ + byte_and_int16_t out; + byte_and_int16_t in; + uint32_t index; + int32_t nr_array1[2]; + int32_t nr_array2[2]; + int32_t count = 0; + + /* end on input buffer. */ + uint8_t *in_end = in_buf + in_length; + + /* assign default values. */ + out.pb = out_buf; + in.pb = in_buf; + nr_array1[0] = 0x2C; + nr_array1[1] = 0x2C; + + /* increase. */ + in.pw++; + + /* 15007AD7 */ + for (count = 0; count < channels; count++) { + + /* some common variables. */ + int32_t temp; + + /* save pointer. */ + temp = *(int16_t *)in.pw++; + nr_array2[count] = temp; + + /* check if should break. */ + if (out_length < 2) { + return out.pb - out_buf; + } + + /* return values. */ + *out.pw++ = (uint16_t)temp; + out_length -= 2; + } + + /* decrease channels. */ + index = channels - 1; + + /* loop through input buffer until end reached. */ + while (in.pb < in_end) { + + /* save the byte. */ + uint8_t one_byte = *in.pb++; + + /* check how many channels and set index. */ + if (channels == 2) { + index = (index == 0) ? 1 : 0; + } + + /* 15007B25 - get one byte from input buffer. */ + if (one_byte & 0x80) { + + /* 15007B32 */ + switch (one_byte & 0x7F) { + case 0: + + /* 15007B8E */ + if (nr_array1[index] != 0) { + nr_array1[index]--; + } + + /* check if should break. */ + if (out_length < 2) { + break; + } + + /* return values. */ + *out.pw++ = (uint16_t)nr_array2[index]; + out_length -= 2; + + /* continue loop. */ + continue; + case 1: + /* 15007B72 and EBX. */ + nr_array1[index] += 8; + + /* check index. */ + if (nr_array1[index] > 0x58) { + nr_array1[index] = 0x58; + } + + /* check how many channels and set index. */ + if (channels == 2) { + index = (index == 0) ? 1 : 0; + } + + /* continue loop. */ + continue; + case 2: + + /* nothing todo, so continue. */ + continue; + default: + + /* decrease index. */ + nr_array1[index] -= 8; + + /* check index. */ + if (nr_array1[index] < 0) { + nr_array1[index] = 0; + } + + /* check if two channels left. */ + if (channels != 2) { + continue; + } + index = (index == 0) ? 1 : 0; + + /* continue loop. */ + continue; + } + } else { + + /* EDI */ + uint32_t temp1 = wave_table_1503f1a0[nr_array1[index]]; + + /* ESI */ + uint32_t temp2 = temp1 >> in_buf[1]; + + /* ECX */ + int32_t temp3 = nr_array2[index]; + + /* EBX = one byte. */ + if (one_byte & 0x01) { + temp2 += (temp1 >> 0); + } + if (one_byte & 0x02) { + temp2 += (temp1 >> 1); + } + if (one_byte & 0x04) { + temp2 += (temp1 >> 2); + } + if (one_byte & 0x08) { + temp2 += (temp1 >> 3); + } + if (one_byte & 0x10) { + temp2 += (temp1 >> 4); + } + if (one_byte & 0x20) { + temp2 += (temp1 >> 5); + } + if (one_byte & 0x40) { + temp3 -= temp2; + if (temp3 <= (int32_t)0xFFFF8000) { + temp3 = (int32_t)0xFFFF8000; + } + } else { + temp3 += temp2; + if (temp3 >= 0x7FFF) { + temp3 = 0x7FFF; + } + } + + /* restore index. */ + nr_array2[index] = temp3; + + /* check if should break. */ + if (out_length < 2) { + break; + } + + /* assign values. */ + temp2 = nr_array1[index]; + one_byte &= 0x1F; + *out.pw++ = (uint16_t)temp3; + out_length -= 2; + temp2 += wave_table_1503f120[one_byte]; + nr_array1[index] = temp2; + + /* check index. */ + if (nr_array1[index] < 0) { + nr_array1[index] = 0; + } else { + + /* check index. */ + if (nr_array1[index] > 0x58) { + nr_array1[index] = 0x58; + } + } + } + } + + /* return copied bytes. */ + return (out.pb - out_buf); +} diff --git a/dep/libmpq/libmpq/wave.h b/dep/libmpq/libmpq/wave.h new file mode 100644 index 00000000000..1b9491bd70a --- /dev/null +++ b/dep/libmpq/libmpq/wave.h @@ -0,0 +1,45 @@ +/* + * wave.h -- header file for wav unplode functions used by mpq-tools. + * + * Copyright (c) 2003-2007 Maik Broemme + * + * This source was adepted from the C++ version of wave.h included + * in stormlib. The C++ version belongs to the following authors: + * + * Ladislav Zezula + * Tom Amigo + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef _WAVE_H +#define _WAVE_H + +/* buffer. */ +typedef union { + uint16_t *pw; + uint8_t *pb; +} byte_and_int16_t; + +/* decompress a wave file, mono or stereo, 1500F230 offset. */ +int32_t libmpq__do_decompress_wave( + uint8_t *out_buf, + int32_t out_length, + uint8_t *in_buf, + int32_t in_length, + int32_t channels +); + +#endif /* _WAVE_H */ diff --git a/dep/libmpq/tools/Makefile.am b/dep/libmpq/tools/Makefile.am new file mode 100644 index 00000000000..607205379a4 --- /dev/null +++ b/dep/libmpq/tools/Makefile.am @@ -0,0 +1,8 @@ +# minimum required automake 1.6 +AUTOMAKE_OPTIONS = 1.6 + +# the main programs. +bin_PROGRAMS = crypt_buf_gen + +# sources for crypt_buf_gen program. +crypt_buf_gen_SOURCES = crypt_buf_gen.c diff --git a/dep/libmpq/tools/crypt_buf_gen.c b/dep/libmpq/tools/crypt_buf_gen.c new file mode 100644 index 00000000000..3d150fc661f --- /dev/null +++ b/dep/libmpq/tools/crypt_buf_gen.c @@ -0,0 +1,85 @@ +/* + * crypt_buf_gen.c -- tool to re-create the static decryption buffer. + * + * Copyright (c) 2003-2008 Maik Broemme + * Copyright (c) 2008 Georg Lukas + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * + * Usage: + * $ make crypt_buf_gen + * $ ./crypt_buf_gen > crypt_buf.h + * + */ +#include +#include +#include + +static uint32_t *buffer; + +int32_t libmpq__buffer_init() { + buffer = malloc(sizeof(uint32_t) * 0x500); + + if (!buffer) + return -1; + + /* some common variables. */ + uint32_t seed = 0x00100001; + uint32_t index1 = 0; + uint32_t index2 = 0; + uint32_t i; + + /* initialize the decryption buffer. */ + for (index1 = 0; index1 < 0x100; index1++) { + for(index2 = index1, i = 0; i < 5; i++, index2 += 0x100) { + + /* some common variables. */ + uint32_t temp1, temp2; + + /* temporary copy. */ + seed = (seed * 125 + 3) % 0x2AAAAB; + temp1 = (seed & 0xFFFF) << 0x10; + + /* temporary copy. */ + seed = (seed * 125 + 3) % 0x2AAAAB; + temp2 = (seed & 0xFFFF); + + /* assign buffer. */ + buffer[index2] = (temp1 | temp2); + } + } + + /* if no error was found, return zero. */ + return 0; +} + +int main() { + if (libmpq__buffer_init() != 0) + perror("libmpq__buffer_init()"); + int x; + printf("/* DO NOT CHANGE! this file is auto-generated by crypt_buf_gen.c */\n"); + printf("static const uint32_t crypt_buf[0x500] = {\n\t"); + for (x = 0; x < 0x500; x++) { + printf("0x%08x", buffer[x]); + if (x < 0x500 - 1) { + if (x % 6 == 5) + printf(",\n\t"); + else + printf(", "); + } + } + printf("\n};\n"); +} diff --git a/dep/libmpq/win/config.h b/dep/libmpq/win/config.h new file mode 100644 index 00000000000..6833494624d --- /dev/null +++ b/dep/libmpq/win/config.h @@ -0,0 +1,81 @@ +/* config.h. Generated from config.h.in by configure. */ +/* config.h.in. Generated from configure.ac by autoheader. */ + +/* Define to 1 if you have the header file. */ +#define HAVE_DLFCN_H 1 + +/* Define to 1 if fseeko (and presumably ftello) exists and is declared. */ +#define HAVE_FSEEKO 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_INTTYPES_H 1 + +/* Define to 1 if you have the `bz2' library (-lbz2). */ +#define HAVE_LIBBZ2 1 + +/* Define to 1 if you have the `z' library (-lz). */ +#define HAVE_LIBZ 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_MEMORY_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDINT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDLIB_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRINGS_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRING_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_UNISTD_H 0 + +/* Define to the sub-directory in which libtool stores uninstalled libraries. + */ +#define LT_OBJDIR ".libs/" + +/* Name of package */ +#define PACKAGE "libmpq" + +/* Define to the address where bug reports for this package should be sent. */ +#define PACKAGE_BUGREPORT "mbroemme@plusserver.de" + +/* Define to the full name of this package. */ +#define PACKAGE_NAME "libmpq" + +/* Define to the full name and version of this package. */ +#define PACKAGE_STRING "libmpq 0.4.2" + +/* Define to the one symbol short name of this package. */ +#define PACKAGE_TARNAME "libmpq" + +/* Define to the home page for this package. */ +#define PACKAGE_URL "" + +/* Define to the version of this package. */ +#define PACKAGE_VERSION "0.4.2" + +/* Define to 1 if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Version number of package */ +#define VERSION "0.4.2" + +/* Number of bits in a file offset, on hosts where this is settable. */ +/* #undef _FILE_OFFSET_BITS */ + +/* Define to 1 to make fseeko visible on some hosts (e.g. glibc 2.2). */ +/* #undef _LARGEFILE_SOURCE */ + +/* Define for large files, on AIX-style hosts. */ +/* #undef _LARGE_FILES */ diff --git a/dep/libmpq/win/dirent.h b/dep/libmpq/win/dirent.h new file mode 100644 index 00000000000..6425174092d --- /dev/null +++ b/dep/libmpq/win/dirent.h @@ -0,0 +1,230 @@ +/***************************************************************************** + * dirent.h - dirent API for Microsoft Visual Studio + * + * Copyright (C) 2006 Toni Ronkko + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * ``Software''), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL TONI RONKKO BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + * Dec 15, 2009, John Cunningham + * Added rewinddir member function + * + * Jan 18, 2008, Toni Ronkko + * Using FindFirstFileA and WIN32_FIND_DATAA to avoid converting string + * between multi-byte and unicode representations. This makes the + * code simpler and also allows the code to be compiled under MingW. Thanks + * to Azriel Fasten for the suggestion. + * + * Mar 4, 2007, Toni Ronkko + * Bug fix: due to the strncpy_s() function this file only compiled in + * Visual Studio 2005. Using the new string functions only when the + * compiler version allows. + * + * Nov 2, 2006, Toni Ronkko + * Major update: removed support for Watcom C, MS-DOS and Turbo C to + * simplify the file, updated the code to compile cleanly on Visual + * Studio 2005 with both unicode and multi-byte character strings, + * removed rewinddir() as it had a bug. + * + * Aug 20, 2006, Toni Ronkko + * Removed all remarks about MSVC 1.0, which is antiqued now. Simplified + * comments by removing SGML tags. + * + * May 14 2002, Toni Ronkko + * Embedded the function definitions directly to the header so that no + * source modules need to be included in the Visual Studio project. Removed + * all the dependencies to other projects so that this very header can be + * used independently. + * + * May 28 1998, Toni Ronkko + * First version. + *****************************************************************************/ +#ifndef DIRENT_H +#define DIRENT_H + +#include +#include +#include + + +typedef struct dirent +{ + char d_name[MAX_PATH + 1]; /* current dir entry (multi-byte char string) */ + WIN32_FIND_DATAA data; /* file attributes */ +} dirent; + + +typedef struct DIR +{ + dirent current; /* Current directory entry */ + int cached; /* Indicates un-processed entry in memory */ + HANDLE search_handle; /* File search handle */ + char patt[MAX_PATH + 3]; /* search pattern (3 = pattern + "\\*\0") */ +} DIR; + + +/* Forward declarations */ +static DIR *opendir (const char *dirname); +static struct dirent *readdir (DIR *dirp); +static int closedir (DIR *dirp); +static void rewinddir(DIR* dirp); + + +/* Use the new safe string functions introduced in Visual Studio 2005 */ +#if defined(_MSC_VER) && _MSC_VER >= 1400 +# define STRNCPY(dest,src,size) strncpy_s((dest),(size),(src),_TRUNCATE) +#else +# define STRNCPY(dest,src,size) strncpy((dest),(src),(size)) +#endif + + +/***************************************************************************** + * Open directory stream DIRNAME for read and return a pointer to the + * internal working area that is used to retrieve individual directory + * entries. + */ +static DIR *opendir(const char *dirname) +{ + DIR *dirp; + assert (dirname != NULL); + assert (strlen (dirname) < MAX_PATH); + + /* construct new DIR structure */ + dirp = (DIR*) malloc (sizeof (struct DIR)); + if (dirp != NULL) { + char *p; + + /* take directory name... */ + STRNCPY (dirp->patt, dirname, sizeof(dirp->patt)); + dirp->patt[MAX_PATH] = '\0'; + + /* ... and append search pattern to it */ + p = strchr (dirp->patt, '\0'); + if (dirp->patt < p && *(p-1) != '\\' && *(p-1) != ':') { + *p++ = '\\'; + } + *p++ = '*'; + *p = '\0'; + + /* open stream and retrieve first file */ + dirp->search_handle = FindFirstFileA (dirp->patt, &dirp->current.data); + if (dirp->search_handle == INVALID_HANDLE_VALUE) { + /* invalid search pattern? */ + free (dirp); + return NULL; + } + + /* there is an un-processed directory entry in memory now */ + dirp->cached = 1; + } + + return dirp; +} + + +/***************************************************************************** + * Read a directory entry, and return a pointer to a dirent structure + * containing the name of the entry in d_name field. Individual directory + * entries returned by this very function include regular files, + * sub-directories, pseudo-directories "." and "..", but also volume labels, + * hidden files and system files may be returned. + */ +static struct dirent *readdir(DIR *dirp) +{ + assert (dirp != NULL); + + if (dirp->search_handle == INVALID_HANDLE_VALUE) { + /* directory stream was opened/rewound incorrectly or ended normally */ + return NULL; + } + + /* get next directory entry */ + if (dirp->cached != 0) { + /* a valid directory entry already in memory */ + dirp->cached = 0; + } else { + /* read next directory entry from disk */ + if (FindNextFileA (dirp->search_handle, &dirp->current.data) == FALSE) { + /* the very last file has been processed or an error occured */ + FindClose (dirp->search_handle); + dirp->search_handle = INVALID_HANDLE_VALUE; + return NULL; + } + } + + /* copy as a multibyte character string */ + STRNCPY ( dirp->current.d_name, + dirp->current.data.cFileName, + sizeof(dirp->current.d_name) ); + dirp->current.d_name[MAX_PATH] = '\0'; + + return &dirp->current; +} + + +/***************************************************************************** + * Close directory stream opened by opendir() function. Close of the + * directory stream invalidates the DIR structure as well as any previously + * read directory entry. + */ +static int closedir(DIR *dirp) +{ + assert (dirp != NULL); + + /* release search handle */ + if (dirp->search_handle != INVALID_HANDLE_VALUE) { + FindClose (dirp->search_handle); + dirp->search_handle = INVALID_HANDLE_VALUE; + } + + /* release directory handle */ + free (dirp); + return 0; +} + + +/***************************************************************************** + * Resets the position of the directory stream to which dirp refers to the + * beginning of the directory. It also causes the directory stream to refer + * to the current state of the corresponding directory, as a call to opendir() + * would have done. If dirp does not refer to a directory stream, the effect + * is undefined. + */ +static void rewinddir(DIR* dirp) +{ + /* release search handle */ + if (dirp->search_handle != INVALID_HANDLE_VALUE) { + FindClose (dirp->search_handle); + dirp->search_handle = INVALID_HANDLE_VALUE; + } + + /* open new search handle and retrieve first file */ + dirp->search_handle = FindFirstFileA (dirp->patt, &dirp->current.data); + if (dirp->search_handle == INVALID_HANDLE_VALUE) { + /* invalid search pattern? */ + free (dirp); + return; + } + + /* there is an un-processed directory entry in memory now */ + dirp->cached = 1; +} + + +#endif /*DIRENT_H*/ diff --git a/dep/libmpq/win/stdint.h b/dep/libmpq/win/stdint.h new file mode 100644 index 00000000000..d02608a5972 --- /dev/null +++ b/dep/libmpq/win/stdint.h @@ -0,0 +1,247 @@ +// ISO C9x compliant stdint.h for Microsoft Visual Studio +// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 +// +// Copyright (c) 2006-2008 Alexander Chemeris +// +// 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. The name of the author may be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 _MSC_VER // [ +#error "Use this header only with Microsoft Visual C++ compilers!" +#endif // _MSC_VER ] + +#ifndef _MSC_STDINT_H_ // [ +#define _MSC_STDINT_H_ + +#if _MSC_VER > 1000 +#pragma once +#endif + +#include + +// For Visual Studio 6 in C++ mode and for many Visual Studio versions when +// compiling for ARM we should wrap include with 'extern "C++" {}' +// or compiler give many errors like this: +// error C2733: second C linkage of overloaded function 'wmemchr' not allowed +#ifdef __cplusplus +extern "C" { +#endif +# include +#ifdef __cplusplus +} +#endif + +// Define _W64 macros to mark types changing their size, like intptr_t. +#ifndef _W64 +# if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300 +# define _W64 __w64 +# else +# define _W64 +# endif +#endif + + +// 7.18.1 Integer types + +// 7.18.1.1 Exact-width integer types + +// Visual Studio 6 and Embedded Visual C++ 4 doesn't +// realize that, e.g. char has the same size as __int8 +// so we give up on __intX for them. +#if (_MSC_VER < 1300) + typedef signed char int8_t; + typedef signed short int16_t; + typedef signed int int32_t; + typedef unsigned char uint8_t; + typedef unsigned short uint16_t; + typedef unsigned int uint32_t; +#else + typedef signed __int8 int8_t; + typedef signed __int16 int16_t; + typedef signed __int32 int32_t; + typedef unsigned __int8 uint8_t; + typedef unsigned __int16 uint16_t; + typedef unsigned __int32 uint32_t; +#endif +typedef signed __int64 int64_t; +typedef unsigned __int64 uint64_t; + + +// 7.18.1.2 Minimum-width integer types +typedef int8_t int_least8_t; +typedef int16_t int_least16_t; +typedef int32_t int_least32_t; +typedef int64_t int_least64_t; +typedef uint8_t uint_least8_t; +typedef uint16_t uint_least16_t; +typedef uint32_t uint_least32_t; +typedef uint64_t uint_least64_t; + +// 7.18.1.3 Fastest minimum-width integer types +typedef int8_t int_fast8_t; +typedef int16_t int_fast16_t; +typedef int32_t int_fast32_t; +typedef int64_t int_fast64_t; +typedef uint8_t uint_fast8_t; +typedef uint16_t uint_fast16_t; +typedef uint32_t uint_fast32_t; +typedef uint64_t uint_fast64_t; + +// 7.18.1.4 Integer types capable of holding object pointers +#ifdef _WIN64 // [ + typedef signed __int64 intptr_t; + typedef unsigned __int64 uintptr_t; +#else // _WIN64 ][ + typedef _W64 signed int intptr_t; + typedef _W64 unsigned int uintptr_t; +#endif // _WIN64 ] + +// 7.18.1.5 Greatest-width integer types +typedef int64_t intmax_t; +typedef uint64_t uintmax_t; + + +// 7.18.2 Limits of specified-width integer types + +#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259 + +// 7.18.2.1 Limits of exact-width integer types +#define INT8_MIN ((int8_t)_I8_MIN) +#define INT8_MAX _I8_MAX +#define INT16_MIN ((int16_t)_I16_MIN) +#define INT16_MAX _I16_MAX +#define INT32_MIN ((int32_t)_I32_MIN) +#define INT32_MAX _I32_MAX +#define INT64_MIN ((int64_t)_I64_MIN) +#define INT64_MAX _I64_MAX +#define UINT8_MAX _UI8_MAX +#define UINT16_MAX _UI16_MAX +#define UINT32_MAX _UI32_MAX +#define UINT64_MAX _UI64_MAX + +// 7.18.2.2 Limits of minimum-width integer types +#define INT_LEAST8_MIN INT8_MIN +#define INT_LEAST8_MAX INT8_MAX +#define INT_LEAST16_MIN INT16_MIN +#define INT_LEAST16_MAX INT16_MAX +#define INT_LEAST32_MIN INT32_MIN +#define INT_LEAST32_MAX INT32_MAX +#define INT_LEAST64_MIN INT64_MIN +#define INT_LEAST64_MAX INT64_MAX +#define UINT_LEAST8_MAX UINT8_MAX +#define UINT_LEAST16_MAX UINT16_MAX +#define UINT_LEAST32_MAX UINT32_MAX +#define UINT_LEAST64_MAX UINT64_MAX + +// 7.18.2.3 Limits of fastest minimum-width integer types +#define INT_FAST8_MIN INT8_MIN +#define INT_FAST8_MAX INT8_MAX +#define INT_FAST16_MIN INT16_MIN +#define INT_FAST16_MAX INT16_MAX +#define INT_FAST32_MIN INT32_MIN +#define INT_FAST32_MAX INT32_MAX +#define INT_FAST64_MIN INT64_MIN +#define INT_FAST64_MAX INT64_MAX +#define UINT_FAST8_MAX UINT8_MAX +#define UINT_FAST16_MAX UINT16_MAX +#define UINT_FAST32_MAX UINT32_MAX +#define UINT_FAST64_MAX UINT64_MAX + +// 7.18.2.4 Limits of integer types capable of holding object pointers +#ifdef _WIN64 // [ +# define INTPTR_MIN INT64_MIN +# define INTPTR_MAX INT64_MAX +# define UINTPTR_MAX UINT64_MAX +#else // _WIN64 ][ +# define INTPTR_MIN INT32_MIN +# define INTPTR_MAX INT32_MAX +# define UINTPTR_MAX UINT32_MAX +#endif // _WIN64 ] + +// 7.18.2.5 Limits of greatest-width integer types +#define INTMAX_MIN INT64_MIN +#define INTMAX_MAX INT64_MAX +#define UINTMAX_MAX UINT64_MAX + +// 7.18.3 Limits of other integer types + +#ifdef _WIN64 // [ +# define PTRDIFF_MIN _I64_MIN +# define PTRDIFF_MAX _I64_MAX +#else // _WIN64 ][ +# define PTRDIFF_MIN _I32_MIN +# define PTRDIFF_MAX _I32_MAX +#endif // _WIN64 ] + +#define SIG_ATOMIC_MIN INT_MIN +#define SIG_ATOMIC_MAX INT_MAX + +#ifndef SIZE_MAX // [ +# ifdef _WIN64 // [ +# define SIZE_MAX _UI64_MAX +# else // _WIN64 ][ +# define SIZE_MAX _UI32_MAX +# endif // _WIN64 ] +#endif // SIZE_MAX ] + +// WCHAR_MIN and WCHAR_MAX are also defined in +#ifndef WCHAR_MIN // [ +# define WCHAR_MIN 0 +#endif // WCHAR_MIN ] +#ifndef WCHAR_MAX // [ +# define WCHAR_MAX _UI16_MAX +#endif // WCHAR_MAX ] + +#define WINT_MIN 0 +#define WINT_MAX _UI16_MAX + +#endif // __STDC_LIMIT_MACROS ] + + +// 7.18.4 Limits of other integer types + +#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 + +// 7.18.4.1 Macros for minimum-width integer constants + +#define INT8_C(val) val##i8 +#define INT16_C(val) val##i16 +#define INT32_C(val) val##i32 +#define INT64_C(val) val##i64 + +#define UINT8_C(val) val##ui8 +#define UINT16_C(val) val##ui16 +#define UINT32_C(val) val##ui32 +#define UINT64_C(val) val##ui64 + +// 7.18.4.2 Macros for greatest-width integer constants +#define INTMAX_C INT64_C +#define UINTMAX_C UINT64_C + +#endif // __STDC_CONSTANT_MACROS ] + + +#endif // _MSC_STDINT_H_ ] diff --git a/dep/mersennetwister/MersenneTwister.h b/dep/mersennetwister/MersenneTwister.h new file mode 100644 index 00000000000..1cff879643f --- /dev/null +++ b/dep/mersennetwister/MersenneTwister.h @@ -0,0 +1,405 @@ +// MersenneTwister.h +// Mersenne Twister random number generator -- a C++ class MTRand +// Based on code by Makoto Matsumoto, Takuji Nishimura, and Shawn Cokus +// Richard J. Wagner v1.0 15 May 2003 rjwagner@writeme.com + +// The Mersenne Twister is an algorithm for generating random numbers. It +// was designed with consideration of the flaws in various other generators. +// The period, 2^19937-1, and the order of equidistribution, 623 dimensions, +// are far greater. The generator is also fast; it avoids multiplication and +// division, and it benefits from caches and pipelines. For more information +// see the inventors' web page at http://www.math.keio.ac.jp/~matumoto/emt.html + +// Reference +// M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-Dimensionally +// Equidistributed Uniform Pseudo-Random Number Generator", ACM Transactions on +// Modeling and Computer Simulation, Vol. 8, No. 1, January 1998, pp 3-30. + +// Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, +// Copyright (C) 2000 - 2003, Richard J. Wagner +// 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. The names of its contributors may not 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. + +// The original code included the following notice: +// +// When you use this, send an email to: matumoto@math.keio.ac.jp +// with an appropriate reference to your work. +// +// It would be nice to CC: rjwagner@writeme.com and Cokus@math.washington.edu +// when you write. + +#ifndef MERSENNETWISTER_H +#define MERSENNETWISTER_H + +// Not thread safe (unless auto-initialization is avoided and each thread has +// its own MTRand object) + +#include"Define.h" + +#include +#include +#include + +class MTRand { +// Data +public: + typedef ::uint32 uint32; + enum { N = 624 }; // length of state vector + enum { SAVE = N + 1 }; // length of array for save() + +protected: + enum { M = 397 }; // period parameter + + uint32 state[N]; // internal state + uint32 *pNext; // next value to get from state + int left; // number of values left before reload needed + +//Methods +public: + MTRand( const uint32& oneSeed ); // initialize with a simple uint32 + MTRand( uint32 *const bigSeed, uint32 const seedLength = N ); // or an array + MTRand(); // auto-initialize with /dev/urandom or time() and clock() + MTRand(const MTRand&); // prevent copy constructor + MTRand& operator=(const MTRand&); // no-op operator= + + // Do NOT use for CRYPTOGRAPHY without securely hashing several returned + // values together, otherwise the generator state can be learned after + // reading 624 consecutive values. + + // Access to 32-bit random numbers + double rand(); // real number in [0,1] + double rand( const double& n ); // real number in [0,n] + double randExc(); // real number in [0,1) + double randExc( const double& n ); // real number in [0,n) + double randDblExc(); // real number in (0,1) + double randDblExc( const double& n ); // real number in (0,n) + uint32 randInt(); // integer in [0,2^32-1] + uint32 randInt( const uint32& n ); // integer in [0,n] for n < 2^32 + double operator()() { return rand(); } // same as rand() + + // Access to 53-bit random numbers (capacity of IEEE double precision) + double rand53(); // real number in [0,1) + + // Access to nonuniform random number distributions + double randNorm( const double& mean = 0.0, const double& variance = 0.0 ); + + // Re-seeding functions with same behavior as initializers + void seed( const uint32 oneSeed ); + void seed( uint32 *const bigSeed, const uint32 seedLength = N ); + void seed(); + + // Saving and loading generator state + void save( uint32* saveArray ) const; // to array of size SAVE + void load( uint32 *const loadArray ); // from such array + /* Trinity not use streams for random values output + friend std::ostream& operator<<( std::ostream& os, const MTRand& mtrand ); + friend std::istream& operator>>( std::istream& is, MTRand& mtrand ); + */ +protected: + void initialize( const uint32 oneSeed ); + void reload(); + uint32 hiBit( const uint32& u ) const { return u & 0x80000000UL; } + uint32 loBit( const uint32& u ) const { return u & 0x00000001UL; } + uint32 loBits( const uint32& u ) const { return u & 0x7fffffffUL; } + uint32 mixBits( const uint32& u, const uint32& v ) const + { return hiBit(u) | loBits(v); } + uint32 twist( const uint32& m, const uint32& s0, const uint32& s1 ) const + { return m ^ (mixBits(s0,s1)>>1) ^ uint32(-(int32)(loBit(s1) & 0x9908b0dfUL)); } + static uint32 hash( time_t t, clock_t c ); +}; + +inline MTRand::MTRand(const MTRand&) + { seed(); } + +inline MTRand& MTRand::operator=(const MTRand&) + { return *this; } + +inline MTRand::MTRand( const uint32& oneSeed ) + { seed(oneSeed); } + +inline MTRand::MTRand( uint32 *const bigSeed, const uint32 seedLength ) + { seed(bigSeed,seedLength); } + +inline MTRand::MTRand() + { seed(); } + +inline double MTRand::rand() + { return double(randInt()) * (1.0/4294967295.0); } + +inline double MTRand::rand( const double& n ) + { return rand() * n; } + +inline double MTRand::randExc() + { return double(randInt()) * (1.0/4294967296.0); } + +inline double MTRand::randExc( const double& n ) + { return randExc() * n; } + +inline double MTRand::randDblExc() + { return ( double(randInt()) + 0.5 ) * (1.0/4294967296.0); } + +inline double MTRand::randDblExc( const double& n ) + { return randDblExc() * n; } + +inline double MTRand::rand53() +{ + uint32 a = randInt() >> 5, b = randInt() >> 6; + return ( a * 67108864.0 + b ) * (1.0/9007199254740992.0); // by Isaku Wada +} + +inline double MTRand::randNorm( const double& mean, const double& variance ) +{ + // Return a real number from a normal (Gaussian) distribution with given + // mean and variance by Box-Muller method + double r = sqrt( -2.0 * log( 1.0-randDblExc()) ) * variance; + double phi = 2.0 * 3.14159265358979323846264338328 * randExc(); + return mean + r * cos(phi); +} + +inline MTRand::uint32 MTRand::randInt() +{ + // Pull a 32-bit integer from the generator state + // Every other access function simply transforms the numbers extracted here + + if( left == 0 ) reload(); + --left; + + register uint32 s1; + s1 = *pNext++; + s1 ^= (s1 >> 11); + s1 ^= (s1 << 7) & 0x9d2c5680UL; + s1 ^= (s1 << 15) & 0xefc60000UL; + return ( s1 ^ (s1 >> 18) ); +} + +inline MTRand::uint32 MTRand::randInt( const uint32& n ) +{ + // Find which bits are used in n + // Optimized by Magnus Jonsson (magnus@smartelectronix.com) + uint32 used = n; + used |= used >> 1; + used |= used >> 2; + used |= used >> 4; + used |= used >> 8; + used |= used >> 16; + + // Draw numbers until one is found in [0,n] + uint32 i; + do + i = randInt() & used; // toss unused bits to shorten search + while( i > n ); + return i; +} + +inline void MTRand::seed( const uint32 oneSeed ) +{ + // Seed the generator with a simple uint32 + initialize(oneSeed); + reload(); +} + +inline void MTRand::seed( uint32 *const bigSeed, const uint32 seedLength ) +{ + // Seed the generator with an array of uint32's + // There are 2^19937-1 possible initial states. This function allows + // all of those to be accessed by providing at least 19937 bits (with a + // default seed length of N = 624 uint32's). Any bits above the lower 32 + // in each element are discarded. + // Just call seed() if you want to get array from /dev/urandom + initialize(19650218UL); + register int i = 1; + register uint32 j = 0; + register int k = ( N > int(seedLength) ? N : int(seedLength) ); + for (; k; --k ) + { + state[i] = + state[i] ^ ( (state[i-1] ^ (state[i-1] >> 30)) * 1664525UL ); + state[i] += ( bigSeed[j] & 0xffffffffUL ) + j; + state[i] &= 0xffffffffUL; + ++i; ++j; + if( i >= N ) { state[0] = state[N-1]; i = 1; } + if( j >= seedLength ) j = 0; + } + for (k = N - 1; k; --k ) + { + state[i] = + state[i] ^ ( (state[i-1] ^ (state[i-1] >> 30)) * 1566083941UL ); + state[i] -= i; + state[i] &= 0xffffffffUL; + ++i; + if( i >= N ) { state[0] = state[N-1]; i = 1; } + } + state[0] = 0x80000000UL; // MSB is 1, assuring non-zero initial array + reload(); +} + +inline void MTRand::seed() +{ + // Seed the generator with hash of time() and clock() values + seed( hash( time(NULL), clock() ) ); +} + +inline void MTRand::initialize( const uint32 seed ) +{ + // Initialize generator state with seed + // See Knuth TAOCP Vol 2, 3rd Ed, p.106 for multiplier. + // In previous versions, most significant bits (MSBs) of the seed affect + // only MSBs of the state array. Modified 9 Jan 2002 by Makoto Matsumoto. + register uint32 *s = state; + register uint32 *r = state; + register int i = 1; + *s++ = seed & 0xffffffffUL; + for (; i < N; ++i ) + { + *s++ = ( 1812433253UL * ( *r ^ (*r >> 30) ) + i ) & 0xffffffffUL; + r++; + } +} + +inline void MTRand::reload() +{ + // Generate N new values in state + // Made clearer and faster by Matthew Bellew (matthew.bellew@home.com) + register uint32 *p = state; + register int i; + for (i = N - M; i--; ++p ) + *p = twist( p[M], p[0], p[1] ); + for (i = M; --i; ++p ) + *p = twist( p[M-N], p[0], p[1] ); + *p = twist( p[M-N], p[0], state[0] ); + + left = N, pNext = state; +} + +inline MTRand::uint32 MTRand::hash( time_t t, clock_t c ) +{ + // Get a uint32 from t and c + // Better than uint32(x) in case x is floating point in [0,1] + // Based on code by Lawrence Kirby (fred@genesis.demon.co.uk) + + static uint32 differ = 0; // guarantee time-based seeds will change + + uint32 h1 = 0; + unsigned char *p = (unsigned char *) &t; + for (size_t i = 0; i < sizeof(t); ++i ) + { + h1 *= UCHAR_MAX + 2U; + h1 += p[i]; + } + uint32 h2 = 0; + p = (unsigned char *) &c; + for (size_t j = 0; j < sizeof(c); ++j ) + { + h2 *= UCHAR_MAX + 2U; + h2 += p[j]; + } + return ( h1 + differ++ ) ^ h2; +} + +inline void MTRand::save( uint32* saveArray ) const +{ + register uint32 *sa = saveArray; + register const uint32 *s = state; + register int i = N; + for (; i--; *sa++ = *s++ ) {} + *sa = left; +} + +inline void MTRand::load( uint32 *const loadArray ) +{ + register uint32 *s = state; + register uint32 *la = loadArray; + register int i = N; + for (; i--; *s++ = *la++ ) {} + left = *la; + pNext = &state[N-left]; +} + +/* Trinity not use streams for random values output +inline std::ostream& operator<<( std::ostream& os, const MTRand& mtrand ) +{ + register const MTRand::uint32 *s = mtrand.state; + register int i = mtrand.N; + for (; i--; os << *s++ << "\t" ) {} + return os << mtrand.left; +} + +inline std::istream& operator>>( std::istream& is, MTRand& mtrand ) +{ + register MTRand::uint32 *s = mtrand.state; + register int i = mtrand.N; + for (; i--; is >> *s++ ) {} + is >> mtrand.left; + mtrand.pNext = &mtrand.state[mtrand.N-mtrand.left]; + return is; +} +*/ + +#endif // MERSENNETWISTER_H + +// Change log: +// +// v0.1 - First release on 15 May 2000 +// - Based on code by Makoto Matsumoto, Takuji Nishimura, and Shawn Cokus +// - Translated from C to C++ +// - Made completely ANSI compliant +// - Designed convenient interface for initialization, seeding, and +// obtaining numbers in default or user-defined ranges +// - Added automatic seeding from /dev/urandom or time() and clock() +// - Provided functions for saving and loading generator state +// +// v0.2 - Fixed bug which reloaded generator one step too late +// +// v0.3 - Switched to clearer, faster reload() code from Matthew Bellew +// +// v0.4 - Removed trailing newline in saved generator format to be consistent +// with output format of built-in types +// +// v0.5 - Improved portability by replacing static const int's with enum's and +// clarifying return values in seed(); suggested by Eric Heimburg +// - Removed MAXINT constant; use 0xffffffffUL instead +// +// v0.6 - Eliminated seed overflow when uint32 is larger than 32 bits +// - Changed integer [0,n] generator to give better uniformity +// +// v0.7 - Fixed operator precedence ambiguity in reload() +// - Added access for real numbers in (0,1) and (0,n) +// +// v0.8 - Included time.h header to properly support time_t and clock_t +// +// v1.0 - Revised seeding to match 26 Jan 2002 update of Nishimura and Matsumoto +// - Allowed for seeding with arrays of any length +// - Added access for real numbers in [0,1) with 53-bit resolution +// - Added access for real numbers from normal (Gaussian) distributions +// - Increased overall speed by optimizing twist() +// - Doubled speed of integer [0,n] generation +// - Fixed out-of-range number generation on 64-bit machines +// - Improved portability by substituting literal constants for long enum's +// - Changed license from GNU LGPL to BSD + diff --git a/dep/sockets/Base64.cpp b/dep/sockets/Base64.cpp new file mode 100644 index 00000000000..f7f12f5edff --- /dev/null +++ b/dep/sockets/Base64.cpp @@ -0,0 +1,262 @@ +/** \file Base64.cpp + ** \date 2004-02-13 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2004-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#include "Base64.h" + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +const char *Base64::bstr = + "ABCDEFGHIJKLMNOPQ" + "RSTUVWXYZabcdefgh" + "ijklmnopqrstuvwxy" + "z0123456789+/"; + +const char Base64::rstr[] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 63, + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0, + 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0, + 0, 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, 0, 0, 0, 0, 0}; + +Base64::Base64() +{ +} + +void Base64::encode(FILE *fil, std::string& output, bool add_crlf) +{ + size_t remain; + size_t i = 0; + size_t o = 0; + char input[4]; + + output = ""; + remain = fread(input,1,3,fil); + while (remain > 0) + { + if (add_crlf && o && o % 76 == 0) + output += "\n"; + switch (remain) + { + case 1: + output += bstr[ ((input[i] >> 2) & 0x3f) ]; + output += bstr[ ((input[i] << 4) & 0x30) ]; + output += "=="; + break; + case 2: + output += bstr[ ((input[i] >> 2) & 0x3f) ]; + output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ]; + output += bstr[ ((input[i + 1] << 2) & 0x3c) ]; + output += "="; + break; + default: + output += bstr[ ((input[i] >> 2) & 0x3f) ]; + output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ]; + output += bstr[ ((input[i + 1] << 2) & 0x3c) + ((input[i + 2] >> 6) & 0x03) ]; + output += bstr[ (input[i + 2] & 0x3f) ]; + } + o += 4; + // + remain = fread(input,1,3,fil); + } +} + +void Base64::encode(const std::string& str_in, std::string& str_out, bool add_crlf) +{ + encode(str_in.c_str(), str_in.size(), str_out, add_crlf); +} + +void Base64::encode(const char* input,size_t l,std::string& output, bool add_crlf) +{ + size_t i = 0; + size_t o = 0; + + output = ""; + while (i < l) + { + size_t remain = l - i; + if (add_crlf && o && o % 76 == 0) + output += "\n"; + switch (remain) + { + case 1: + output += bstr[ ((input[i] >> 2) & 0x3f) ]; + output += bstr[ ((input[i] << 4) & 0x30) ]; + output += "=="; + break; + case 2: + output += bstr[ ((input[i] >> 2) & 0x3f) ]; + output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ]; + output += bstr[ ((input[i + 1] << 2) & 0x3c) ]; + output += "="; + break; + default: + output += bstr[ ((input[i] >> 2) & 0x3f) ]; + output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ]; + output += bstr[ ((input[i + 1] << 2) & 0x3c) + ((input[i + 2] >> 6) & 0x03) ]; + output += bstr[ (input[i + 2] & 0x3f) ]; + } + o += 4; + i += 3; + } +} + +void Base64::encode(const unsigned char* input,size_t l,std::string& output,bool add_crlf) +{ + size_t i = 0; + size_t o = 0; + + output = ""; + while (i < l) + { + size_t remain = l - i; + if (add_crlf && o && o % 76 == 0) + output += "\n"; + switch (remain) + { + case 1: + output += bstr[ ((input[i] >> 2) & 0x3f) ]; + output += bstr[ ((input[i] << 4) & 0x30) ]; + output += "=="; + break; + case 2: + output += bstr[ ((input[i] >> 2) & 0x3f) ]; + output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ]; + output += bstr[ ((input[i + 1] << 2) & 0x3c) ]; + output += "="; + break; + default: + output += bstr[ ((input[i] >> 2) & 0x3f) ]; + output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ]; + output += bstr[ ((input[i + 1] << 2) & 0x3c) + ((input[i + 2] >> 6) & 0x03) ]; + output += bstr[ (input[i + 2] & 0x3f) ]; + } + o += 4; + i += 3; + } +} + +void Base64::decode(const std::string& input,std::string& output) +{ + size_t i = 0; + size_t l = input.size(); + + output = ""; + while (i < l) + { + while (i < l && (input[i] == 13 || input[i] == 10)) + i++; + if (i < l) + { + char b1 = (char)((rstr[(int)input[i]] << 2 & 0xfc) + + (rstr[(int)input[i + 1]] >> 4 & 0x03)); + output += b1; + if (input[i + 2] != '=') + { + char b2 = (char)((rstr[(int)input[i + 1]] << 4 & 0xf0) + + (rstr[(int)input[i + 2]] >> 2 & 0x0f)); + output += b2; + } + if (input[i + 3] != '=') + { + char b3 = (char)((rstr[(int)input[i + 2]] << 6 & 0xc0) + + rstr[(int)input[i + 3]]); + output += b3; + } + i += 4; + } + } +} + +void Base64::decode(const std::string& input, unsigned char *output, size_t& sz) +{ + size_t i = 0; + size_t l = input.size(); + size_t j = 0; + + while (i < l) + { + while (i < l && (input[i] == 13 || input[i] == 10)) + i++; + if (i < l) + { + unsigned char b1 = (unsigned char)((rstr[(int)input[i]] << 2 & 0xfc) + + (rstr[(int)input[i + 1]] >> 4 & 0x03)); + if (output) + { + output[j] = b1; + } + j++; + if (input[i + 2] != '=') + { + unsigned char b2 = (unsigned char)((rstr[(int)input[i + 1]] << 4 & 0xf0) + + (rstr[(int)input[i + 2]] >> 2 & 0x0f)); + if (output) + { + output[j] = b2; + } + j++; + } + if (input[i + 3] != '=') + { + unsigned char b3 = (unsigned char)((rstr[(int)input[i + 2]] << 6 & 0xc0) + + rstr[(int)input[i + 3]]); + if (output) + { + output[j] = b3; + } + j++; + } + i += 4; + } + } + sz = j; +} + +size_t Base64::decode_length(const std::string& str64) +{ + if (str64.empty() || str64.size() % 4) + return 0; + size_t l = 3 * (str64.size() / 4 - 1) + 1; + if (str64[str64.size() - 2] != '=') + l++; + if (str64[str64.size() - 1] != '=') + l++; + return l; +} + +#ifdef SOCKETS_NAMESPACE +} +#endif + + diff --git a/dep/sockets/CMakeLists.txt b/dep/sockets/CMakeLists.txt new file mode 100644 index 00000000000..a1756773c08 --- /dev/null +++ b/dep/sockets/CMakeLists.txt @@ -0,0 +1,21 @@ +# Copyright (C) 2008-2010 Trinity +# +# This file is free software; as a special exception the author gives +# unlimited permission to copy and/or distribute it, with or without +# modifications, as long as this notice is preserved. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the +# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +file(GLOB sources *.cpp) + +set(trinitysockets_STAT_SRCS + ${sources} +) + +include_directories( + ${CMAKE_CURRENT_SOURCE_DIR}/include +) + +add_library(trinitysockets STATIC ${trinitysockets_STAT_SRCS}) diff --git a/dep/sockets/Exception.cpp b/dep/sockets/Exception.cpp new file mode 100644 index 00000000000..4d79aeef813 --- /dev/null +++ b/dep/sockets/Exception.cpp @@ -0,0 +1,45 @@ +/** + ** \file Exception.cpp + ** \date 2007-09-28 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2007 Anders Hedstrom + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifdef _MSC_VER +#pragma warning(disable:4786) +#endif +#include "Exception.h" + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +Exception::Exception(const std::string& description) : m_description(description) +{ +} + +const std::string Exception::ToString() const +{ + return m_description; +} + +#ifdef SOCKETS_NAMESPACE +} // namespace SOCKETS_NAMESPACE { +#endif + + diff --git a/dep/sockets/Ipv4Address.cpp b/dep/sockets/Ipv4Address.cpp new file mode 100644 index 00000000000..03935038951 --- /dev/null +++ b/dep/sockets/Ipv4Address.cpp @@ -0,0 +1,192 @@ +/** + ** \file Ipv4Address.cpp + ** \date 2006-09-21 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2007 Anders Hedstrom + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#include "Ipv4Address.h" +#include "Utility.h" +#include "Parse.h" +#ifndef _WIN32 +#include +#endif + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +Ipv4Address::Ipv4Address(port_t port) : m_valid(true) +{ + memset(&m_addr, 0, sizeof(m_addr)); + m_addr.sin_family = AF_INET; + m_addr.sin_port = htons( port ); +} + +Ipv4Address::Ipv4Address(ipaddr_t a,port_t port) : m_valid(true) +{ + memset(&m_addr, 0, sizeof(m_addr)); + m_addr.sin_family = AF_INET; + m_addr.sin_port = htons( port ); + memcpy(&m_addr.sin_addr, &a, sizeof(struct in_addr)); +} + +Ipv4Address::Ipv4Address(struct in_addr& a,port_t port) : m_valid(true) +{ + memset(&m_addr, 0, sizeof(m_addr)); + m_addr.sin_family = AF_INET; + m_addr.sin_port = htons( port ); + m_addr.sin_addr = a; +} + +Ipv4Address::Ipv4Address(const std::string& host,port_t port) : m_valid(false) +{ + memset(&m_addr, 0, sizeof(m_addr)); + m_addr.sin_family = AF_INET; + m_addr.sin_port = htons( port ); + { + ipaddr_t a; + if (Utility::u2ip(host, a)) + { + memcpy(&m_addr.sin_addr, &a, sizeof(struct in_addr)); + m_valid = true; + } + } +} + +Ipv4Address::Ipv4Address(struct sockaddr_in& sa) +{ + m_addr = sa; + m_valid = sa.sin_family == AF_INET; +} + +Ipv4Address::~Ipv4Address() +{ +} + +Ipv4Address::operator struct sockaddr *() +{ + return (struct sockaddr *)&m_addr; +} + +Ipv4Address::operator socklen_t() +{ + return sizeof(struct sockaddr_in); +} + +void Ipv4Address::SetPort(port_t port) +{ + m_addr.sin_port = htons( port ); +} + +port_t Ipv4Address::GetPort() +{ + return ntohs( m_addr.sin_port ); +} + +bool Ipv4Address::Resolve(const std::string& hostname,struct in_addr& a) +{ + struct sockaddr_in sa; + memset(&a, 0, sizeof(a)); + if (Utility::isipv4(hostname)) + { + if (!Utility::u2ip(hostname, sa, AI_NUMERICHOST)) + return false; + a = sa.sin_addr; + return true; + } + if (!Utility::u2ip(hostname, sa)) + return false; + a = sa.sin_addr; + return true; +} + +bool Ipv4Address::Reverse(struct in_addr& a,std::string& name) +{ + struct sockaddr_in sa; + memset(&sa, 0, sizeof(sa)); + sa.sin_family = AF_INET; + sa.sin_addr = a; + return Utility::reverse((struct sockaddr *)&sa, sizeof(sa), name); +} + +std::string Ipv4Address::Convert(bool include_port) +{ + if (include_port) + return Convert(m_addr.sin_addr) + ":" + Utility::l2string(GetPort()); + return Convert(m_addr.sin_addr); +} + +std::string Ipv4Address::Convert(struct in_addr& a) +{ + struct sockaddr_in sa; + memset(&sa, 0, sizeof(sa)); + sa.sin_family = AF_INET; + sa.sin_addr = a; + std::string name; + Utility::reverse((struct sockaddr *)&sa, sizeof(sa), name, NI_NUMERICHOST); + return name; +} + +void Ipv4Address::SetAddress(struct sockaddr *sa) +{ + memcpy(&m_addr, sa, sizeof(struct sockaddr_in)); +} + +int Ipv4Address::GetFamily() +{ + return m_addr.sin_family; +} + +bool Ipv4Address::IsValid() +{ + return m_valid; +} + +bool Ipv4Address::operator==(SocketAddress& a) +{ + if (a.GetFamily() != GetFamily()) + return false; + if ((socklen_t)a != sizeof(m_addr)) + return false; + struct sockaddr *sa = a; + struct sockaddr_in *p = (struct sockaddr_in *)sa; + if (p -> sin_port != m_addr.sin_port) + return false; + if (memcmp(&p -> sin_addr, &m_addr.sin_addr, 4)) + return false; + return true; +} + +std::auto_ptr Ipv4Address::GetCopy() +{ + return std::auto_ptr(new Ipv4Address(m_addr)); +} + +std::string Ipv4Address::Reverse() +{ + std::string tmp; + Reverse(m_addr.sin_addr, tmp); + return tmp; +} + +#ifdef SOCKETS_NAMESPACE +} // namespace SOCKETS_NAMESPACE { +#endif + + diff --git a/dep/sockets/Ipv6Address.cpp b/dep/sockets/Ipv6Address.cpp new file mode 100644 index 00000000000..3208b5098fa --- /dev/null +++ b/dep/sockets/Ipv6Address.cpp @@ -0,0 +1,247 @@ +/** + ** \file Ipv6Address.cpp + ** \date 2006-09-21 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2007 Anders Hedstrom + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#include "Ipv6Address.h" +#ifdef ENABLE_IPV6 + +#include "Utility.h" +#include "Parse.h" +#ifndef _WIN32 +#include +#endif +#ifdef IPPROTO_IPV6 + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +Ipv6Address::Ipv6Address(port_t port) : m_valid(true) +{ + memset(&m_addr, 0, sizeof(m_addr)); + m_addr.sin6_family = AF_INET6; + m_addr.sin6_port = htons( port ); +} + +Ipv6Address::Ipv6Address(struct in6_addr& a,port_t port) : m_valid(true) +{ + memset(&m_addr, 0, sizeof(m_addr)); + m_addr.sin6_family = AF_INET6; + m_addr.sin6_port = htons( port ); + m_addr.sin6_addr = a; +} + +Ipv6Address::Ipv6Address(const std::string& host,port_t port) : m_valid(false) +{ + memset(&m_addr, 0, sizeof(m_addr)); + m_addr.sin6_family = AF_INET6; + m_addr.sin6_port = htons( port ); + { + struct in6_addr a; + if (Utility::u2ip(host, a)) + { + m_addr.sin6_addr = a; + m_valid = true; + } + } +} + +Ipv6Address::Ipv6Address(struct sockaddr_in6& sa) +{ + m_addr = sa; + m_valid = sa.sin6_family == AF_INET6; +} + +Ipv6Address::~Ipv6Address() +{ +} + +Ipv6Address::operator struct sockaddr *() +{ + return (struct sockaddr *)&m_addr; +} + +Ipv6Address::operator socklen_t() +{ + return sizeof(struct sockaddr_in6); +} + +void Ipv6Address::SetPort(port_t port) +{ + m_addr.sin6_port = htons( port ); +} + +port_t Ipv6Address::GetPort() +{ + return ntohs( m_addr.sin6_port ); +} + +bool Ipv6Address::Resolve(const std::string& hostname,struct in6_addr& a) +{ + struct sockaddr_in6 sa; + memset(&a, 0, sizeof(a)); + if (Utility::isipv6(hostname)) + { + if (!Utility::u2ip(hostname, sa, AI_NUMERICHOST)) + return false; + a = sa.sin6_addr; + return true; + } + if (!Utility::u2ip(hostname, sa)) + return false; + a = sa.sin6_addr; + return true; +} + +bool Ipv6Address::Reverse(struct in6_addr& a,std::string& name) +{ + struct sockaddr_in6 sa; + memset(&sa, 0, sizeof(sa)); + sa.sin6_family = AF_INET6; + sa.sin6_addr = a; + return Utility::reverse((struct sockaddr *)&sa, sizeof(sa), name); +} + +std::string Ipv6Address::Convert(bool include_port) +{ + if (include_port) + return Convert(m_addr.sin6_addr) + ":" + Utility::l2string(GetPort()); + return Convert(m_addr.sin6_addr); +} + +std::string Ipv6Address::Convert(struct in6_addr& a,bool mixed) +{ + char slask[100]; // l2ip temporary + *slask = 0; + unsigned int prev = 0; + bool skipped = false; + bool ok_to_skip = true; + if (mixed) + { + unsigned short x; + unsigned short addr16[8]; + memcpy(addr16, &a, sizeof(addr16)); + for (size_t i = 0; i < 6; i++) + { + x = ntohs(addr16[i]); + if (*slask && (x || !ok_to_skip || prev)) + strcat(slask,":"); + if (x || !ok_to_skip) + { + sprintf(slask + strlen(slask),"%x", x); + if (x && skipped) + ok_to_skip = false; + } + else + { + skipped = true; + } + prev = x; + } + x = ntohs(addr16[6]); + sprintf(slask + strlen(slask),":%u.%u",x / 256,x & 255); + x = ntohs(addr16[7]); + sprintf(slask + strlen(slask),".%u.%u",x / 256,x & 255); + } + else + { + struct sockaddr_in6 sa; + memset(&sa, 0, sizeof(sa)); + sa.sin6_family = AF_INET6; + sa.sin6_addr = a; + std::string name; + Utility::reverse((struct sockaddr *)&sa, sizeof(sa), name, NI_NUMERICHOST); + return name; + } + return slask; +} + +void Ipv6Address::SetAddress(struct sockaddr *sa) +{ + memcpy(&m_addr, sa, sizeof(struct sockaddr_in6)); +} + +int Ipv6Address::GetFamily() +{ + return m_addr.sin6_family; +} + +void Ipv6Address::SetFlowinfo(uint32_t x) +{ + m_addr.sin6_flowinfo = x; +} + +uint32_t Ipv6Address::GetFlowinfo() +{ + return m_addr.sin6_flowinfo; +} + +#ifndef _WIN32 +void Ipv6Address::SetScopeId(uint32_t x) +{ + m_addr.sin6_scope_id = x; +} + +uint32_t Ipv6Address::GetScopeId() +{ + return m_addr.sin6_scope_id; +} +#endif + +bool Ipv6Address::IsValid() +{ + return m_valid; +} + +bool Ipv6Address::operator==(SocketAddress& a) +{ + if (a.GetFamily() != GetFamily()) + return false; + if ((socklen_t)a != sizeof(m_addr)) + return false; + struct sockaddr *sa = a; + struct sockaddr_in6 *p = (struct sockaddr_in6 *)sa; + if (p -> sin6_port != m_addr.sin6_port) + return false; + if (memcmp(&p -> sin6_addr, &m_addr.sin6_addr, sizeof(struct in6_addr))) + return false; + return true; +} + +std::auto_ptr Ipv6Address::GetCopy() +{ + return std::auto_ptr(new Ipv6Address(m_addr)); +} + +std::string Ipv6Address::Reverse() +{ + std::string tmp; + Reverse(m_addr.sin6_addr, tmp); + return tmp; +} + +#ifdef SOCKETS_NAMESPACE +} // namespace SOCKETS_NAMESPACE { +#endif +#endif // IPPROTO_IPV6 +#endif // ENABLE_IPV6 + + diff --git a/dep/sockets/Lock.cpp b/dep/sockets/Lock.cpp new file mode 100644 index 00000000000..b75664cfbdc --- /dev/null +++ b/dep/sockets/Lock.cpp @@ -0,0 +1,52 @@ +/** \file Lock.cpp + ** \date 2005-08-22 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2005,2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#include "Mutex.h" +#include "Lock.h" + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +Lock::Lock(Mutex& m) : m_mutex(m) +{ + m_mutex.Lock(); +} + +Lock::~Lock() +{ + m_mutex.Unlock(); +} + + +#ifdef SOCKETS_NAMESPACE +} +#endif + + diff --git a/dep/sockets/Makefile b/dep/sockets/Makefile new file mode 100644 index 00000000000..88b6199788c --- /dev/null +++ b/dep/sockets/Makefile @@ -0,0 +1,136 @@ +# CMAKE generated file: DO NOT EDIT! +# Generated by "Unix Makefiles" Generator, CMake Version 2.6 + +# Default target executed when no arguments are given to make. +default_target: all +.PHONY : default_target + +#============================================================================= +# Special targets provided by cmake. + +# Disable implicit rules so canoncical targets will work. +.SUFFIXES: + +# Remove some rules from gmake that .SUFFIXES does not remove. +SUFFIXES = + +.SUFFIXES: .hpux_make_needs_suffix_list + +# Suppress display of executed commands. +$(VERBOSE).SILENT: + +# A target that is always out of date. +cmake_force: +.PHONY : cmake_force + +#============================================================================= +# Set environment variables for the build. + +# The shell in which to execute make rules. +SHELL = /bin/sh + +# The CMake executable. +CMAKE_COMMAND = /usr/bin/cmake + +# The command to remove a file. +RM = /usr/bin/cmake -E remove -f + +# The program to use to edit the cache. +CMAKE_EDIT_COMMAND = /usr/bin/ccmake + +# The top-level source directory on which CMake was run. +CMAKE_SOURCE_DIR = /home/trinity/dev/trinitycore/dep/sockets + +# The top-level build directory on which CMake was run. +CMAKE_BINARY_DIR = /home/trinity/dev/trinitycore/dep/sockets + +#============================================================================= +# Targets provided globally by CMake. + +# Special rule for the target edit_cache +edit_cache: + @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake cache editor..." + /usr/bin/ccmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) +.PHONY : edit_cache + +# Special rule for the target edit_cache +edit_cache/fast: edit_cache +.PHONY : edit_cache/fast + +# Special rule for the target rebuild_cache +rebuild_cache: + @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..." + /usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) +.PHONY : rebuild_cache + +# Special rule for the target rebuild_cache +rebuild_cache/fast: rebuild_cache +.PHONY : rebuild_cache/fast + +# The main all target +all: cmake_check_build_system + $(CMAKE_COMMAND) -E cmake_progress_start /home/trinity/dev/trinitycore/dep/sockets/CMakeFiles /home/trinity/dev/trinitycore/dep/sockets/CMakeFiles/progress.make + $(MAKE) -f CMakeFiles/Makefile2 all + $(CMAKE_COMMAND) -E cmake_progress_start /home/trinity/dev/trinitycore/dep/sockets/CMakeFiles 0 +.PHONY : all + +# The main clean target +clean: + $(MAKE) -f CMakeFiles/Makefile2 clean +.PHONY : clean + +# The main clean target +clean/fast: clean +.PHONY : clean/fast + +# Prepare targets for installation. +preinstall: all + $(MAKE) -f CMakeFiles/Makefile2 preinstall +.PHONY : preinstall + +# Prepare targets for installation. +preinstall/fast: + $(MAKE) -f CMakeFiles/Makefile2 preinstall +.PHONY : preinstall/fast + +# clear depends +depend: + $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1 +.PHONY : depend + +#============================================================================= +# Target rules for targets named trinitysockets + +# Build rule for target. +trinitysockets: cmake_check_build_system + $(MAKE) -f CMakeFiles/Makefile2 trinitysockets +.PHONY : trinitysockets + +# fast build rule for target. +trinitysockets/fast: + $(MAKE) -f CMakeFiles/trinitysockets.dir/build.make CMakeFiles/trinitysockets.dir/build +.PHONY : trinitysockets/fast + +# Help Target +help: + @echo "The following are some of the valid targets for this Makefile:" + @echo "... all (the default if no target is provided)" + @echo "... clean" + @echo "... depend" + @echo "... edit_cache" + @echo "... rebuild_cache" + @echo "... trinitysockets" +.PHONY : help + + + +#============================================================================= +# Special targets to cleanup operation of make. + +# Special rule to run CMake to check the build system integrity. +# No rule that depends on this can have commands that come from listfiles +# because they might be regenerated. +cmake_check_build_system: + $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0 +.PHONY : cmake_check_build_system + diff --git a/dep/sockets/Mutex.cpp b/dep/sockets/Mutex.cpp new file mode 100644 index 00000000000..681e85cee5b --- /dev/null +++ b/dep/sockets/Mutex.cpp @@ -0,0 +1,77 @@ +/** \file Mutex.cpp + ** \date 2004-10-30 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2004-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#include "Mutex.h" + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +Mutex::Mutex() +{ +#ifdef _WIN32 + m_mutex = ::CreateMutex(NULL, FALSE, NULL); +#else + pthread_mutex_init(&m_mutex, NULL); +#endif +} + +Mutex::~Mutex() +{ +#ifdef _WIN32 + ::CloseHandle(m_mutex); +#else + pthread_mutex_destroy(&m_mutex); +#endif +} + +void Mutex::Lock() +{ +#ifdef _WIN32 + /*DWORD d =*/ WaitForSingleObject(m_mutex, INFINITE); + /// \todo check 'd' for result +#else + pthread_mutex_lock(&m_mutex); +#endif +} + +void Mutex::Unlock() +{ +#ifdef _WIN32 + ::ReleaseMutex(m_mutex); +#else + pthread_mutex_unlock(&m_mutex); +#endif +} + +#ifdef SOCKETS_NAMESPACE +} +#endif + + diff --git a/dep/sockets/Parse.cpp b/dep/sockets/Parse.cpp new file mode 100644 index 00000000000..2967859f23d --- /dev/null +++ b/dep/sockets/Parse.cpp @@ -0,0 +1,318 @@ +/** \file Parse.cpp - parse a string + ** + ** Written: 1999-Feb-10 grymse@alhem.net + **/ + +/* +Copyright (C) 1999-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#include +#include + +#include "Parse.h" + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +/* implementation of class Parse */ + +Parse::Parse() +:pa_the_str("") +,pa_splits("") +,pa_ord("") +,pa_the_ptr(0) +,pa_breakchar(0) +,pa_enable(0) +,pa_disable(0) +,pa_nospace(0) +,pa_quote(false) +{ +} + +Parse::Parse(const std::string&s) +:pa_the_str(s) +,pa_splits("") +,pa_ord("") +,pa_the_ptr(0) +,pa_breakchar(0) +,pa_enable(0) +,pa_disable(0) +,pa_nospace(0) +,pa_quote(false) +{ +} + +Parse::Parse(const std::string&s,const std::string&sp) +:pa_the_str(s) +,pa_splits(sp) +,pa_ord("") +,pa_the_ptr(0) +,pa_breakchar(0) +,pa_enable(0) +,pa_disable(0) +,pa_nospace(0) +,pa_quote(false) +{ +} + +Parse::Parse(const std::string&s,const std::string&sp,short /*nospace*/) +:pa_the_str(s) +,pa_splits(sp) +,pa_ord("") +,pa_the_ptr(0) +,pa_breakchar(0) +,pa_enable(0) +,pa_disable(0) +,pa_nospace(1) +,pa_quote(false) +{ +} + +Parse::~Parse() +{ +} + +#define C ((pa_the_ptr l(h); + + if (l.Bind("127.0.0.1", m_port)) + { + return; + } + h.Add(&l); + + m_ready = true; + while (!m_quit && IsRunning() ) + { + h.Select(0, 500000); + } + SetRunning(false); +} + +void ResolvServer::Quit() +{ + m_quit = true; +} + +bool ResolvServer::Ready() +{ + return m_ready; +} + +#ifdef SOCKETS_NAMESPACE +} +#endif + +#endif // ENABLE_RESOLVER + + diff --git a/dep/sockets/ResolvSocket.cpp b/dep/sockets/ResolvSocket.cpp new file mode 100644 index 00000000000..636de276426 --- /dev/null +++ b/dep/sockets/ResolvSocket.cpp @@ -0,0 +1,426 @@ +/** \file ResolvSocket.cpp + ** \date 2005-03-24 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2004-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifdef _WIN32 +#ifdef _MSC_VER +#pragma warning(disable:4786) +#pragma warning(disable:4503) +#endif +#else +#include +#endif +#include "ResolvSocket.h" +#ifdef ENABLE_RESOLVER +#include "Utility.h" +#include "Parse.h" +#include "ISocketHandler.h" +#include "Lock.h" +#include "Mutex.h" + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +//#ifdef _DEBUG +//#define DEB(x) x +//#else +#define DEB(x) +//#endif + +// static +ResolvSocket::cache_t ResolvSocket::m_cache; +ResolvSocket::timeout_t ResolvSocket::m_cache_to; +Mutex ResolvSocket::m_cache_mutex; + +ResolvSocket::ResolvSocket(ISocketHandler& h) +:TcpSocket(h) +,m_bServer(false) +,m_parent(NULL) +#ifdef ENABLE_IPV6 +,m_resolve_ipv6(false) +#endif +,m_cached(false) +{ + SetLineProtocol(); +} + +ResolvSocket::ResolvSocket(ISocketHandler& h, Socket *parent, const std::string& host, port_t port, bool ipv6) +:TcpSocket(h) +,m_bServer(false) +,m_parent(parent) +,m_resolv_host(host) +,m_resolv_port(port) +#ifdef ENABLE_IPV6 +,m_resolve_ipv6(ipv6) +#endif +,m_cached(false) +{ + SetLineProtocol(); +} + +ResolvSocket::ResolvSocket(ISocketHandler& h, Socket *parent, ipaddr_t a) +:TcpSocket(h) +,m_bServer(false) +,m_parent(parent) +,m_resolv_port(0) +,m_resolv_address(a) +#ifdef ENABLE_IPV6 +,m_resolve_ipv6(false) +#endif +,m_cached(false) +{ + SetLineProtocol(); +} + +#ifdef ENABLE_IPV6 +ResolvSocket::ResolvSocket(ISocketHandler& h, Socket *parent, in6_addr& a) +:TcpSocket(h) +,m_bServer(false) +,m_parent(parent) +,m_resolv_port(0) +,m_resolve_ipv6(true) +,m_resolv_address6(a) +,m_cached(false) +{ + SetLineProtocol(); +} +#endif + +ResolvSocket::~ResolvSocket() +{ +} + +void ResolvSocket::OnLine(const std::string& line) +{ + Parse pa(line, ":"); + if (m_bServer) + { + m_query = pa.getword(); + m_data = pa.getrest(); +DEB( fprintf(stderr, " *** ResolvSocket server; query=%s, data=%s\n", m_query.c_str(), m_data.c_str());) + // %! check cache + { + Lock lock(m_cache_mutex); + if (m_cache[m_query].find(m_data) != m_cache[m_query].end()) + { + if (time(NULL) - m_cache_to[m_query][m_data] < 3600) // ttl + { + std::string result = m_cache[m_query][m_data]; +DEB(fprintf(stderr, " *** Returning cache for [%s][%s] = '%s'\n", m_query.c_str(), m_data.c_str(), result.c_str());) + Send("Cached\n"); + if (!result.size()) /* failed */ + { + Send("Failed\n\n"); + SetCloseAndDelete(); + return; + } + else + if (m_query == "gethostbyname") + { + Send("A: " + result + "\n\n"); + SetCloseAndDelete(); + return; + } + else +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + if (m_query == "gethostbyname2") + { + Send("AAAA: " + result + "\n\n"); + SetCloseAndDelete(); + return; + } + else +#endif +#endif + if (m_query == "gethostbyaddr") + { + Send("Name: " + result + "\n\n"); + SetCloseAndDelete(); + return; + } + } + } + } + if (!Detach()) // detach failed? + { + SetCloseAndDelete(); + } + return; + } + std::string key = pa.getword(); + std::string value = pa.getrest(); +DEB( fprintf(stderr, " *** ResolvSocket response; %s: %s\n", key.c_str(), value.c_str());) + + if (key == "Cached") + { + m_cached = true; + } + else + if (key == "Failed" && m_parent) + { +DEB( fprintf(stderr, " ************ Resolve failed\n");) + if (Handler().Resolving(m_parent) || Handler().Valid(m_parent)) + { + m_parent -> OnResolveFailed(m_resolv_id); + } + // update cache + if (!m_cached) + { + Lock lock(m_cache_mutex); +DEB(fprintf(stderr, " *** Update cache for [%s][%s] = '%s'\n", m_query.c_str(), m_data.c_str(), value.c_str());) + m_cache[m_query][m_data] = value; + m_cache_to[m_query][m_data] = time(NULL); + } + m_parent = NULL; + } + else + if (key == "Name" && !m_resolv_host.size() && m_parent) + { + if (Handler().Resolving(m_parent) || Handler().Valid(m_parent)) + { + m_parent -> OnReverseResolved(m_resolv_id, value); + } + // update cache + if (!m_cached) + { + Lock lock(m_cache_mutex); +DEB(fprintf(stderr, " *** Update cache for [%s][%s] = '%s'\n", m_query.c_str(), m_data.c_str(), value.c_str());) + m_cache[m_query][m_data] = value; + m_cache_to[m_query][m_data] = time(NULL); + } + m_parent = NULL; + } + else + if (key == "A" && m_parent) + { + if (Handler().Resolving(m_parent) || Handler().Valid(m_parent)) + { + ipaddr_t l; + Utility::u2ip(value, l); // ip2ipaddr_t + m_parent -> OnResolved(m_resolv_id, l, m_resolv_port); + } + // update cache + if (!m_cached) + { + Lock lock(m_cache_mutex); +DEB(fprintf(stderr, " *** Update cache for [%s][%s] = '%s'\n", m_query.c_str(), m_data.c_str(), value.c_str());) + m_cache[m_query][m_data] = value; + m_cache_to[m_query][m_data] = time(NULL); + } + m_parent = NULL; // always use first ip in case there are several + } +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + else + if (key == "AAAA" && m_parent) + { + if (Handler().Resolving(m_parent) || Handler().Valid(m_parent)) + { + in6_addr a; + Utility::u2ip(value, a); + m_parent -> OnResolved(m_resolv_id, a, m_resolv_port); + } + // update cache + if (!m_cached) + { + Lock lock(m_cache_mutex); +DEB(fprintf(stderr, " *** Update cache for [%s][%s] = '%s'\n", m_query.c_str(), m_data.c_str(), value.c_str());) + m_cache[m_query][m_data] = value; + m_cache_to[m_query][m_data] = time(NULL); + } + m_parent = NULL; + } +#endif +#endif +} + +void ResolvSocket::OnDetached() +{ +DEB( fprintf(stderr, " *** ResolvSocket::OnDetached(); query=%s, data=%s\n", m_query.c_str(), m_data.c_str());) + if (m_query == "gethostbyname") + { + struct sockaddr_in sa; + if (Utility::u2ip(m_data, sa)) + { + std::string ip; + Utility::l2ip(sa.sin_addr, ip); + Send("A: " + ip + "\n"); + } + else + { + Send("Failed\n"); + } + Send("\n"); + } + else +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + if (m_query == "gethostbyname2") + { + struct sockaddr_in6 sa; + if (Utility::u2ip(m_data, sa)) + { + std::string ip; + Utility::l2ip(sa.sin6_addr, ip); + Send("AAAA: " + ip + "\n"); + } + else + { + Send("Failed\n"); + } + Send("\n"); + } + else +#endif +#endif + if (m_query == "gethostbyaddr") + { + if (Utility::isipv4( m_data )) + { + struct sockaddr_in sa; + if (!Utility::u2ip(m_data, sa, AI_NUMERICHOST)) + { + Send("Failed: convert to sockaddr_in failed\n"); + } + else + { + std::string name; + if (!Utility::reverse( (struct sockaddr *)&sa, sizeof(sa), name)) + { + Send("Failed: ipv4 reverse lookup of " + m_data + "\n"); + } + else + { + Send("Name: " + name + "\n"); + } + } + } + else +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + if (Utility::isipv6( m_data )) + { + struct sockaddr_in6 sa; + if (!Utility::u2ip(m_data, sa, AI_NUMERICHOST)) + { + Send("Failed: convert to sockaddr_in6 failed\n"); + } + else + { + std::string name; + if (!Utility::reverse( (struct sockaddr *)&sa, sizeof(sa), name)) + { + Send("Failed: ipv6 reverse lookup of " + m_data + "\n"); + } + else + { + Send("Name: " + name + "\n"); + } + } + } + else +#endif +#endif + { + Send("Failed: malformed address\n"); + } + Send("\n"); + } + else + { + std::string msg = "Unknown query type: " + m_query; + Handler().LogError(this, "OnDetached", 0, msg); + Send("Unknown\n\n"); + } + SetCloseAndDelete(); +} + +void ResolvSocket::OnConnect() +{ + if (!m_resolv_host.empty()) + { +#ifdef ENABLE_IPV6 + std::string msg = (m_resolve_ipv6 ? "gethostbyname2 " : "gethostbyname ") + m_resolv_host + "\n"; + m_query = m_resolve_ipv6 ? "gethostbyname2" : "gethostbyname"; +#else + std::string msg = "gethostbyname " + m_resolv_host + "\n"; + m_query = "gethostbyname"; +#endif + m_data = m_resolv_host; + Send( msg ); + return; + } +#ifdef ENABLE_IPV6 + if (m_resolve_ipv6) + { + std::string tmp; + Utility::l2ip(m_resolv_address6, tmp); + m_query = "gethostbyaddr"; + m_data = tmp; + std::string msg = "gethostbyaddr " + tmp + "\n"; + Send( msg ); + } +#endif + std::string tmp; + Utility::l2ip(m_resolv_address, tmp); + m_query = "gethostbyaddr"; + m_data = tmp; + std::string msg = "gethostbyaddr " + tmp + "\n"; + Send( msg ); +} + +void ResolvSocket::OnDelete() +{ + if (m_parent) + { + if (Handler().Resolving(m_parent) || Handler().Valid(m_parent)) + { + m_parent -> OnResolveFailed(m_resolv_id); + } + // update cache + if (!m_cached) + { + Lock lock(m_cache_mutex); + std::string value; +DEB(fprintf(stderr, " *** Update cache for [%s][%s] = '%s'\n", m_query.c_str(), m_data.c_str(), value.c_str());) + m_cache[m_query][m_data] = value; + m_cache_to[m_query][m_data] = time(NULL); + } + m_parent = NULL; + } +} + +#ifdef SOCKETS_NAMESPACE +} +#endif + +#endif // ENABLE_RESOLVER + + diff --git a/dep/sockets/Socket.cpp b/dep/sockets/Socket.cpp new file mode 100644 index 00000000000..f53cd27621e --- /dev/null +++ b/dep/sockets/Socket.cpp @@ -0,0 +1,1726 @@ +/** \file Socket.cpp + ** \date 2004-02-13 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2004-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#include "Socket.h" +#ifdef _WIN32 +#ifdef _MSC_VER +#pragma warning(disable:4786) +#endif +#include +#else +#include +#include +#endif +#include +#include + +#include "ISocketHandler.h" +#include "Utility.h" + +#include "SocketAddress.h" +#include "SocketHandler.h" +#ifdef ENABLE_EXCEPTIONS +#include "Exception.h" +#endif +#include "Ipv4Address.h" + +//#ifdef _DEBUG +//#define DEB(x) x; fflush(stderr); +//#else +#define DEB(x) +//#endif + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +// statics +#ifdef _WIN32 +WSAInitializer Socket::m_winsock_init; +#endif + +Socket::Socket(ISocketHandler& h) +//:m_flags(0) +:m_handler(h) +,m_socket( INVALID_SOCKET ) +,m_bDel(false) +,m_bClose(false) +,m_tCreate(time(NULL)) +,m_parent(NULL) +,m_b_disable_read(false) +,m_connected(false) +,m_b_erased_by_handler(false) +,m_tClose(0) +,m_client_remote_address(NULL) +,m_remote_address(NULL) +,m_traffic_monitor(NULL) +,m_bLost(false) +#ifdef HAVE_OPENSSL +,m_b_enable_ssl(false) +,m_b_ssl(false) +,m_b_ssl_server(false) +#endif +#ifdef ENABLE_IPV6 +,m_ipv6(false) +#endif +#ifdef ENABLE_POOL +,m_socket_type(0) +,m_bClient(false) +,m_bRetain(false) +#endif +#ifdef ENABLE_SOCKS4 +,m_bSocks4(false) +,m_socks4_host(h.GetSocks4Host()) +,m_socks4_port(h.GetSocks4Port()) +,m_socks4_userid(h.GetSocks4Userid()) +#endif +#ifdef ENABLE_DETACH +,m_detach(false) +,m_detached(false) +,m_pThread(NULL) +,m_slave_handler(NULL) +#endif +{ +} + +Socket::~Socket() +{ + Handler().Remove(this); + if (m_socket != INVALID_SOCKET +#ifdef ENABLE_POOL + && !m_bRetain +#endif + ) + { + Close(); + } +} + +void Socket::Init() +{ +} + +void Socket::OnRead() +{ +} + +void Socket::OnWrite() +{ +} + +void Socket::OnException() +{ + // %! exception doesn't always mean something bad happened, this code should be reworked + // errno valid here? + int err = SoError(); + Handler().LogError(this, "exception on select", err, StrError(err), LOG_LEVEL_FATAL); + SetCloseAndDelete(); +} + +void Socket::OnDelete() +{ +} + +void Socket::OnConnect() +{ +} + +void Socket::OnAccept() +{ +} + +int Socket::Close() +{ + if (m_socket == INVALID_SOCKET) // this could happen + { + Handler().LogError(this, "Socket::Close", 0, "file descriptor invalid", LOG_LEVEL_WARNING); + return 0; + } + int n; + if ((n = closesocket(m_socket)) == -1) + { + // failed... + Handler().LogError(this, "close", Errno, StrError(Errno), LOG_LEVEL_ERROR); + } + Handler().Set(m_socket, false, false, false); // remove from fd_set's + Handler().AddList(m_socket, LIST_CALLONCONNECT, false); +#ifdef ENABLE_DETACH + Handler().AddList(m_socket, LIST_DETACH, false); +#endif + Handler().AddList(m_socket, LIST_TIMEOUT, false); + Handler().AddList(m_socket, LIST_RETRY, false); + Handler().AddList(m_socket, LIST_CLOSE, false); + m_socket = INVALID_SOCKET; + return n; +} + +SOCKET Socket::CreateSocket(int af,int type, const std::string& protocol) +{ + struct protoent *p = NULL; + SOCKET s; + +#ifdef ENABLE_POOL + m_socket_type = type; + m_socket_protocol = protocol; +#endif + if (!protocol.empty()) + { + p = getprotobyname( protocol.c_str() ); + if (!p) + { + Handler().LogError(this, "getprotobyname", Errno, StrError(Errno), LOG_LEVEL_FATAL); + SetCloseAndDelete(); +#ifdef ENABLE_EXCEPTIONS + throw Exception(std::string("getprotobyname() failed: ") + StrError(Errno)); +#endif + return INVALID_SOCKET; + } + } + int protno = p ? p -> p_proto : 0; + + s = socket(af, type, protno); + if (s == INVALID_SOCKET) + { + Handler().LogError(this, "socket", Errno, StrError(Errno), LOG_LEVEL_FATAL); + SetCloseAndDelete(); +#ifdef ENABLE_EXCEPTIONS + throw Exception(std::string("socket() failed: ") + StrError(Errno)); +#endif + return INVALID_SOCKET; + } + Attach(s); + OnOptions(af, type, protno, s); + Attach(INVALID_SOCKET); + return s; +} + +void Socket::Attach(SOCKET s) +{ + m_socket = s; +} + +SOCKET Socket::GetSocket() +{ + return m_socket; +} + +void Socket::SetDeleteByHandler(bool x) +{ + m_bDel = x; +} + +bool Socket::DeleteByHandler() +{ + return m_bDel; +} + +void Socket::SetCloseAndDelete(bool x) +{ + if (x != m_bClose) + { + Handler().AddList(m_socket, LIST_CLOSE, x); + m_bClose = x; + if (x) + { + m_tClose = time(NULL); + } + } +} + +bool Socket::CloseAndDelete() +{ + return m_bClose; +} + +void Socket::SetRemoteAddress(SocketAddress& ad) //struct sockaddr* sa, socklen_t l) +{ + m_remote_address = ad.GetCopy(); +} + +std::auto_ptr Socket::GetRemoteSocketAddress() +{ + return m_remote_address -> GetCopy(); +} + +ISocketHandler& Socket::Handler() const +{ +#ifdef ENABLE_DETACH + if (IsDetached()) + return *m_slave_handler; +#endif + return m_handler; +} + +ISocketHandler& Socket::MasterHandler() const +{ + return m_handler; +} + +ipaddr_t Socket::GetRemoteIP4() +{ + ipaddr_t l = 0; +#ifdef ENABLE_IPV6 + if (m_ipv6) + { + Handler().LogError(this, "GetRemoteIP4", 0, "get ipv4 address for ipv6 socket", LOG_LEVEL_WARNING); + } +#endif + if (m_remote_address.get() != NULL) + { + struct sockaddr *p = *m_remote_address; + struct sockaddr_in *sa = (struct sockaddr_in *)p; + memcpy(&l, &sa -> sin_addr, sizeof(struct in_addr)); + } + return l; +} + +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 +struct in6_addr Socket::GetRemoteIP6() +{ + if (!m_ipv6) + { + Handler().LogError(this, "GetRemoteIP6", 0, "get ipv6 address for ipv4 socket", LOG_LEVEL_WARNING); + } + struct sockaddr_in6 fail; + if (m_remote_address.get() != NULL) + { + struct sockaddr *p = *m_remote_address; + memcpy(&fail, p, sizeof(struct sockaddr_in6)); + } + else + { + memset(&fail, 0, sizeof(struct sockaddr_in6)); + } + return fail.sin6_addr; +} +#endif +#endif + +port_t Socket::GetRemotePort() +{ + if (!m_remote_address.get()) + { + return 0; + } + return m_remote_address -> GetPort(); +} + +std::string Socket::GetRemoteAddress() +{ + if (!m_remote_address.get()) + { + return ""; + } + return m_remote_address -> Convert(false); +} + +std::string Socket::GetRemoteHostname() +{ + if (!m_remote_address.get()) + { + return ""; + } + return m_remote_address -> Reverse(); +} + +bool Socket::SetNonblocking(bool bNb) +{ +#ifdef _WIN32 + unsigned long l = bNb ? 1 : 0; + int n = ioctlsocket(m_socket, FIONBIO, &l); + if (n != 0) + { + Handler().LogError(this, "ioctlsocket(FIONBIO)", Errno, ""); + return false; + } + return true; +#else + if (bNb) + { + if (fcntl(m_socket, F_SETFL, O_NONBLOCK) == -1) + { + Handler().LogError(this, "fcntl(F_SETFL, O_NONBLOCK)", Errno, StrError(Errno), LOG_LEVEL_ERROR); + return false; + } + } + else + { + if (fcntl(m_socket, F_SETFL, 0) == -1) + { + Handler().LogError(this, "fcntl(F_SETFL, 0)", Errno, StrError(Errno), LOG_LEVEL_ERROR); + return false; + } + } + return true; +#endif +} + +bool Socket::SetNonblocking(bool bNb, SOCKET s) +{ +#ifdef _WIN32 + unsigned long l = bNb ? 1 : 0; + int n = ioctlsocket(s, FIONBIO, &l); + if (n != 0) + { + Handler().LogError(this, "ioctlsocket(FIONBIO)", Errno, ""); + return false; + } + return true; +#else + if (bNb) + { + if (fcntl(s, F_SETFL, O_NONBLOCK) == -1) + { + Handler().LogError(this, "fcntl(F_SETFL, O_NONBLOCK)", Errno, StrError(Errno), LOG_LEVEL_ERROR); + return false; + } + } + else + { + if (fcntl(s, F_SETFL, 0) == -1) + { + Handler().LogError(this, "fcntl(F_SETFL, 0)", Errno, StrError(Errno), LOG_LEVEL_ERROR); + return false; + } + } + return true; +#endif +} + +void Socket::Set(bool bRead, bool bWrite, bool bException) +{ + Handler().Set(m_socket, bRead, bWrite, bException); +} + +bool Socket::Ready() +{ + if (m_socket != INVALID_SOCKET && !CloseAndDelete()) + return true; + return false; +} + +void Socket::OnLine(const std::string& ) +{ +} + +void Socket::OnConnectFailed() +{ +} + +Socket *Socket::GetParent() +{ + return m_parent; +} + +void Socket::SetParent(Socket *x) +{ + m_parent = x; +} + +port_t Socket::GetPort() +{ + Handler().LogError(this, "GetPort", 0, "GetPort only implemented for ListenSocket", LOG_LEVEL_WARNING); + return 0; +} + +bool Socket::OnConnectRetry() +{ + return true; +} + +#ifdef ENABLE_RECONNECT +void Socket::OnReconnect() +{ +} +#endif + +time_t Socket::Uptime() +{ + return time(NULL) - m_tCreate; +} + +#ifdef ENABLE_IPV6 +void Socket::SetIpv6(bool x) +{ + m_ipv6 = x; +} + +bool Socket::IsIpv6() +{ + return m_ipv6; +} +#endif + +void Socket::DisableRead(bool x) +{ + m_b_disable_read = x; +} + +bool Socket::IsDisableRead() +{ + return m_b_disable_read; +} + +void Socket::SendBuf(const char *,size_t,int) +{ +} + +void Socket::Send(const std::string&,int) +{ +} + +void Socket::SetConnected(bool x) +{ + m_connected = x; +} + +bool Socket::IsConnected() +{ + return m_connected; +} + +void Socket::OnDisconnect() +{ +} + +void Socket::SetLost() +{ + m_bLost = true; +} + +bool Socket::Lost() +{ + return m_bLost; +} + +void Socket::SetErasedByHandler(bool x) +{ + m_b_erased_by_handler = x; +} + +bool Socket::ErasedByHandler() +{ + return m_b_erased_by_handler; +} + +time_t Socket::TimeSinceClose() +{ + return time(NULL) - m_tClose; +} + +void Socket::SetClientRemoteAddress(SocketAddress& ad) +{ + if (!ad.IsValid()) + { + Handler().LogError(this, "SetClientRemoteAddress", 0, "remote address not valid", LOG_LEVEL_ERROR); + } + m_client_remote_address = ad.GetCopy(); +} + +std::auto_ptr Socket::GetClientRemoteAddress() +{ + if (!m_client_remote_address.get()) + { + Handler().LogError(this, "GetClientRemoteAddress", 0, "remote address not yet set", LOG_LEVEL_ERROR); + } + return m_client_remote_address -> GetCopy(); +} + +uint64_t Socket::GetBytesSent(bool) +{ + return 0; +} + +uint64_t Socket::GetBytesReceived(bool) +{ + return 0; +} + +#ifdef HAVE_OPENSSL +void Socket::OnSSLConnect() +{ +} + +void Socket::OnSSLAccept() +{ +} + +bool Socket::SSLNegotiate() +{ + return false; +} + +bool Socket::IsSSL() +{ + return m_b_enable_ssl; +} + +void Socket::EnableSSL(bool x) +{ + m_b_enable_ssl = x; +} + +bool Socket::IsSSLNegotiate() +{ + return m_b_ssl; +} + +void Socket::SetSSLNegotiate(bool x) +{ + m_b_ssl = x; +} + +bool Socket::IsSSLServer() +{ + return m_b_ssl_server; +} + +void Socket::SetSSLServer(bool x) +{ + m_b_ssl_server = x; +} + +void Socket::OnSSLConnectFailed() +{ +} + +void Socket::OnSSLAcceptFailed() +{ +} +#endif // HAVE_OPENSSL + +#ifdef ENABLE_POOL +void Socket::CopyConnection(Socket *sock) +{ + Attach( sock -> GetSocket() ); +#ifdef ENABLE_IPV6 + SetIpv6( sock -> IsIpv6() ); +#endif + SetSocketType( sock -> GetSocketType() ); + SetSocketProtocol( sock -> GetSocketProtocol() ); + + SetClientRemoteAddress( *sock -> GetClientRemoteAddress() ); + SetRemoteAddress( *sock -> GetRemoteSocketAddress() ); +} + +void Socket::SetIsClient() +{ + m_bClient = true; +} + +void Socket::SetSocketType(int x) +{ + m_socket_type = x; +} + +int Socket::GetSocketType() +{ + return m_socket_type; +} + +void Socket::SetSocketProtocol(const std::string& x) +{ + m_socket_protocol = x; +} + +const std::string& Socket::GetSocketProtocol() +{ + return m_socket_protocol; +} + +void Socket::SetRetain() +{ + if (m_bClient) m_bRetain = true; +} + +bool Socket::Retain() +{ + return m_bRetain; +} + +#endif // ENABLE_POOL + +#ifdef ENABLE_SOCKS4 +void Socket::OnSocks4Connect() +{ + Handler().LogError(this, "OnSocks4Connect", 0, "Use with TcpSocket only"); +} + +void Socket::OnSocks4ConnectFailed() +{ + Handler().LogError(this, "OnSocks4ConnectFailed", 0, "Use with TcpSocket only"); +} + +bool Socket::OnSocks4Read() +{ + Handler().LogError(this, "OnSocks4Read", 0, "Use with TcpSocket only"); + return true; +} + +void Socket::SetSocks4Host(const std::string& host) +{ + Utility::u2ip(host, m_socks4_host); +} + +bool Socket::Socks4() +{ + return m_bSocks4; +} + +void Socket::SetSocks4(bool x) +{ + m_bSocks4 = x; +} + +void Socket::SetSocks4Host(ipaddr_t a) +{ + m_socks4_host = a; +} + +void Socket::SetSocks4Port(port_t p) +{ + m_socks4_port = p; +} + +void Socket::SetSocks4Userid(const std::string& x) +{ + m_socks4_userid = x; +} + +ipaddr_t Socket::GetSocks4Host() +{ + return m_socks4_host; +} + +port_t Socket::GetSocks4Port() +{ + return m_socks4_port; +} + +const std::string& Socket::GetSocks4Userid() +{ + return m_socks4_userid; +} +#endif // ENABLE_SOCKS4 + +#ifdef ENABLE_DETACH +bool Socket::Detach() +{ + if (!DeleteByHandler()) + return false; + if (m_pThread) + return false; + if (m_detached) + return false; + SetDetach(); + return true; +} + +void Socket::DetachSocket() +{ + SetDetached(); + m_pThread = new SocketThread(this); + m_pThread -> SetRelease(true); +} + +void Socket::OnDetached() +{ +} + +void Socket::SetDetach(bool x) +{ + Handler().AddList(m_socket, LIST_DETACH, x); + m_detach = x; +} + +bool Socket::IsDetach() +{ + return m_detach; +} + +void Socket::SetDetached(bool x) +{ + m_detached = x; +} + +const bool Socket::IsDetached() const +{ + return m_detached; +} + +void Socket::SetSlaveHandler(ISocketHandler *p) +{ + m_slave_handler = p; +} + +Socket::SocketThread::SocketThread(Socket *p) +:Thread(false) +,m_socket(p) +{ + // Creator will release +} + +Socket::SocketThread::~SocketThread() +{ + if (IsRunning()) + { + SetRelease(true); + SetRunning(false); +#ifdef _WIN32 + Sleep(1000); +#else + sleep(1); +#endif + } +} + +void Socket::SocketThread::Run() +{ + SocketHandler h; + h.SetSlave(); + h.Add(m_socket); + m_socket -> SetSlaveHandler(&h); + m_socket -> OnDetached(); + while (h.GetCount() && IsRunning()) + { + h.Select(0, 500000); + } + // m_socket now deleted oops + // yeah oops m_socket delete its socket thread, that means this + // so Socket will no longer delete its socket thread, instead we do this: + SetDeleteOnExit(); +} +#endif // ENABLE_DETACH + +#ifdef ENABLE_RESOLVER +int Socket::Resolve(const std::string& host,port_t port) +{ + return Handler().Resolve(this, host, port); +} + +#ifdef ENABLE_IPV6 +int Socket::Resolve6(const std::string& host,port_t port) +{ + return Handler().Resolve6(this, host, port); +} +#endif + +int Socket::Resolve(ipaddr_t a) +{ + return Handler().Resolve(this, a); +} + +#ifdef ENABLE_IPV6 +int Socket::Resolve(in6_addr& a) +{ + return Handler().Resolve(this, a); +} +#endif + +void Socket::OnResolved(int,ipaddr_t,port_t) +{ +} + +#ifdef ENABLE_IPV6 +void Socket::OnResolved(int,in6_addr&,port_t) +{ +} +#endif + +void Socket::OnReverseResolved(int,const std::string&) +{ +} + +void Socket::OnResolveFailed(int) +{ +} +#endif // ENABLE_RESOLVER + +/* IP options */ + +bool Socket::SetIpOptions(const void *p, socklen_t len) +{ +#ifdef IP_OPTIONS + if (setsockopt(GetSocket(), IPPROTO_IP, IP_OPTIONS, (char *)p, len) == -1) + { + Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_OPTIONS)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +#else + Handler().LogError(this, "ip option not available", 0, "IP_OPTIONS", LOG_LEVEL_INFO); + return false; +#endif +} + +#ifdef IP_PKTINFO +bool Socket::SetIpPktinfo(bool x) +{ + int optval = x ? 1 : 0; + if (setsockopt(GetSocket(), IPPROTO_IP, IP_PKTINFO, (char *)&optval, sizeof(optval)) == -1) + { + Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_PKTINFO)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +} +#endif + +#ifdef IP_RECVTOS +bool Socket::SetIpRecvTOS(bool x) +{ + int optval = x ? 1 : 0; + if (setsockopt(GetSocket(), IPPROTO_IP, IP_RECVTOS, (char *)&optval, sizeof(optval)) == -1) + { + Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_RECVTOS)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +} +#endif + +#ifdef IP_RECVTTL +bool Socket::SetIpRecvTTL(bool x) +{ + int optval = x ? 1 : 0; + if (setsockopt(GetSocket(), IPPROTO_IP, IP_RECVTTL, (char *)&optval, sizeof(optval)) == -1) + { + Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_RECVTTL)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +} +#endif + +#ifdef IP_RECVOPTS +bool Socket::SetIpRecvopts(bool x) +{ + int optval = x ? 1 : 0; + if (setsockopt(GetSocket(), IPPROTO_IP, IP_RECVOPTS, (char *)&optval, sizeof(optval)) == -1) + { + Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_RECVOPTS)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +} +#endif + +#ifdef IP_RETOPTS +bool Socket::SetIpRetopts(bool x) +{ + int optval = x ? 1 : 0; + if (setsockopt(GetSocket(), IPPROTO_IP, IP_RETOPTS, (char *)&optval, sizeof(optval)) == -1) + { + Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_RETOPTS)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +} +#endif + +bool Socket::SetIpTOS(unsigned char tos) +{ +#ifdef IP_TOS + if (setsockopt(GetSocket(), IPPROTO_IP, IP_TOS, (char *)&tos, sizeof(tos)) == -1) + { + Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_TOS)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +#else + Handler().LogError(this, "ip option not available", 0, "IP_TOS", LOG_LEVEL_INFO); + return false; +#endif +} + +unsigned char Socket::IpTOS() +{ + unsigned char tos = 0; +#ifdef IP_TOS + socklen_t len = sizeof(tos); + if (getsockopt(GetSocket(), IPPROTO_IP, IP_TOS, (char *)&tos, &len) == -1) + { + Handler().LogError(this, "getsockopt(IPPROTO_IP, IP_TOS)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + } +#else + Handler().LogError(this, "ip option not available", 0, "IP_TOS", LOG_LEVEL_INFO); +#endif + return tos; +} + +bool Socket::SetIpTTL(int ttl) +{ +#ifdef IP_TTL + if (setsockopt(GetSocket(), IPPROTO_IP, IP_TTL, (char *)&ttl, sizeof(ttl)) == -1) + { + Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_TTL)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +#else + Handler().LogError(this, "ip option not available", 0, "IP_TTL", LOG_LEVEL_INFO); + return false; +#endif +} + +int Socket::IpTTL() +{ + int ttl = 0; +#ifdef IP_TTL + socklen_t len = sizeof(ttl); + if (getsockopt(GetSocket(), IPPROTO_IP, IP_TTL, (char *)&ttl, &len) == -1) + { + Handler().LogError(this, "getsockopt(IPPROTO_IP, IP_TTL)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + } +#else + Handler().LogError(this, "ip option not available", 0, "IP_TTL", LOG_LEVEL_INFO); +#endif + return ttl; +} + +bool Socket::SetIpHdrincl(bool x) +{ +#ifdef IP_HDRINCL + int optval = x ? 1 : 0; + if (setsockopt(GetSocket(), IPPROTO_IP, IP_HDRINCL, (char *)&optval, sizeof(optval)) == -1) + { + Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_HDRINCL)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +#else + Handler().LogError(this, "ip option not available", 0, "IP_HDRINCL", LOG_LEVEL_INFO); + return false; +#endif +} + +#ifdef IP_RECVERR +bool Socket::SetIpRecverr(bool x) +{ + int optval = x ? 1 : 0; + if (setsockopt(GetSocket(), IPPROTO_IP, IP_RECVERR, (char *)&optval, sizeof(optval)) == -1) + { + Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_RECVERR)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +} +#endif + +#ifdef IP_MTU_DISCOVER +bool Socket::SetIpMtudiscover(bool x) +{ + int optval = x ? 1 : 0; + if (setsockopt(GetSocket(), IPPROTO_IP, IP_MTU_DISCOVER, (char *)&optval, sizeof(optval)) == -1) + { + Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_MTU_DISCOVER)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +} +#endif + +#ifdef IP_MTU +int Socket::IpMtu() +{ + int mtu = 0; + socklen_t len = sizeof(mtu); + if (getsockopt(GetSocket(), IPPROTO_IP, IP_MTU, (char *)&mtu, &len) == -1) + { + Handler().LogError(this, "getsockopt(IPPROTO_IP, IP_MTU)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + } + return mtu; +} +#endif + +#ifdef IP_ROUTER_ALERT +bool Socket::SetIpRouterAlert(bool x) +{ + int optval = x ? 1 : 0; + if (setsockopt(GetSocket(), IPPROTO_IP, IP_ROUTER_ALERT, (char *)&optval, sizeof(optval)) == -1) + { + Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_ROUTER_ALERT)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +} +#endif + +bool Socket::SetIpMulticastTTL(int ttl) +{ +#ifdef IP_MULTICAST_TTL + if (setsockopt(GetSocket(), IPPROTO_IP, IP_MULTICAST_TTL, (char *)&ttl, sizeof(ttl)) == -1) + { + Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_MULTICAST_TTL)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +#else + Handler().LogError(this, "ip option not available", 0, "IP_MULTICAST_TTL", LOG_LEVEL_INFO); + return false; +#endif +} + +int Socket::IpMulticastTTL() +{ + int ttl = 0; +#ifdef IP_MULTICAST_TTL + socklen_t len = sizeof(ttl); + if (getsockopt(GetSocket(), IPPROTO_IP, IP_MULTICAST_TTL, (char *)&ttl, &len) == -1) + { + Handler().LogError(this, "getsockopt(IPPROTO_IP, IP_MULTICAST_TTL)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + } +#else + Handler().LogError(this, "ip option not available", 0, "IP_MULTICAST_TTL", LOG_LEVEL_INFO); +#endif + return ttl; +} + +bool Socket::SetMulticastLoop(bool x) +{ +#ifdef IP_MULTICAST_LOOP + int optval = x ? 1 : 0; + if (setsockopt(GetSocket(), IPPROTO_IP, IP_MULTICAST_LOOP, (char *)&optval, sizeof(optval)) == -1) + { + Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_MULTICAST_LOOP)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +#else + Handler().LogError(this, "ip option not available", 0, "IP_MULTICAST_LOOP", LOG_LEVEL_INFO); + return false; +#endif +} + +#ifdef LINUX +bool Socket::IpAddMembership(struct ip_mreqn& ref) +{ +#ifdef IP_ADD_MEMBERSHIP + if (setsockopt(GetSocket(), IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&ref, sizeof(struct ip_mreqn)) == -1) + { + Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +#else + Handler().LogError(this, "ip option not available", 0, "IP_ADD_MEMBERSHIP", LOG_LEVEL_INFO); + return false; +#endif +} +#endif + +bool Socket::IpAddMembership(struct ip_mreq& ref) +{ +#ifdef IP_ADD_MEMBERSHIP + if (setsockopt(GetSocket(), IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&ref, sizeof(struct ip_mreq)) == -1) + { + Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +#else + Handler().LogError(this, "ip option not available", 0, "IP_ADD_MEMBERSHIP", LOG_LEVEL_INFO); + return false; +#endif +} + +#ifdef LINUX +bool Socket::IpDropMembership(struct ip_mreqn& ref) +{ +#ifdef IP_DROP_MEMBERSHIP + if (setsockopt(GetSocket(), IPPROTO_IP, IP_DROP_MEMBERSHIP, (char *)&ref, sizeof(struct ip_mreqn)) == -1) + { + Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_DROP_MEMBERSHIP)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +#else + Handler().LogError(this, "ip option not available", 0, "IP_DROP_MEMBERSHIP", LOG_LEVEL_INFO); + return false; +#endif +} +#endif + +bool Socket::IpDropMembership(struct ip_mreq& ref) +{ +#ifdef IP_DROP_MEMBERSHIP + if (setsockopt(GetSocket(), IPPROTO_IP, IP_DROP_MEMBERSHIP, (char *)&ref, sizeof(struct ip_mreq)) == -1) + { + Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_DROP_MEMBERSHIP)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +#else + Handler().LogError(this, "ip option not available", 0, "IP_DROP_MEMBERSHIP", LOG_LEVEL_INFO); + return false; +#endif +} + +/* SOCKET options */ + +bool Socket::SetSoReuseaddr(bool x) +{ +#ifdef SO_REUSEADDR + int optval = x ? 1 : 0; + if (setsockopt(GetSocket(), SOL_SOCKET, SO_REUSEADDR, (char *)&optval, sizeof(optval)) == -1) + { + Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_REUSEADDR)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +#else + Handler().LogError(this, "socket option not available", 0, "SO_REUSEADDR", LOG_LEVEL_INFO); + return false; +#endif +} + +bool Socket::SetSoKeepalive(bool x) +{ +#ifdef SO_KEEPALIVE + int optval = x ? 1 : 0; + if (setsockopt(GetSocket(), SOL_SOCKET, SO_KEEPALIVE, (char *)&optval, sizeof(optval)) == -1) + { + Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_KEEPALIVE)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +#else + Handler().LogError(this, "socket option not available", 0, "SO_KEEPALIVE", LOG_LEVEL_INFO); + return false; +#endif +} + +#ifdef SO_NOSIGPIPE +bool Socket::SetSoNosigpipe(bool x) +{ + int optval = x ? 1 : 0; + if (setsockopt(GetSocket(), SOL_SOCKET, SO_NOSIGPIPE, (char *)&optval, sizeof(optval)) == -1) + { + Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_NOSIGPIPE)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +} +#endif + +bool Socket::SoAcceptconn() +{ + int value = 0; +#ifdef SO_ACCEPTCONN + socklen_t len = sizeof(value); + if (getsockopt(GetSocket(), SOL_SOCKET, SO_ACCEPTCONN, (char *)&value, &len) == -1) + { + Handler().LogError(this, "getsockopt(SOL_SOCKET, SO_ACCEPTCONN)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + } +#else + Handler().LogError(this, "socket option not available", 0, "SO_ACCEPTCONN", LOG_LEVEL_INFO); +#endif + return value ? true : false; +} + +#ifdef SO_BSDCOMPAT +bool Socket::SetSoBsdcompat(bool x) +{ + int optval = x ? 1 : 0; + if (setsockopt(GetSocket(), SOL_SOCKET, SO_BSDCOMPAT, (char *)&optval, sizeof(optval)) == -1) + { + Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_BSDCOMPAT)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +} +#endif + +#ifdef SO_BINDTODEVICE +bool Socket::SetSoBindtodevice(const std::string& intf) +{ + if (setsockopt(GetSocket(), SOL_SOCKET, SO_BINDTODEVICE, (char *)intf.c_str(), intf.size()) == -1) + { + Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_BINDTODEVICE)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +} +#endif + +bool Socket::SetSoBroadcast(bool x) +{ +#ifdef SO_BROADCAST + int optval = x ? 1 : 0; + if (setsockopt(GetSocket(), SOL_SOCKET, SO_BROADCAST, (char *)&optval, sizeof(optval)) == -1) + { + Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_BROADCAST)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +#else + Handler().LogError(this, "socket option not available", 0, "SO_BROADCAST", LOG_LEVEL_INFO); + return false; +#endif +} + +bool Socket::SetSoDebug(bool x) +{ +#ifdef SO_DEBUG + int optval = x ? 1 : 0; + if (setsockopt(GetSocket(), SOL_SOCKET, SO_DEBUG, (char *)&optval, sizeof(optval)) == -1) + { + Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_DEBUG)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +#else + Handler().LogError(this, "socket option not available", 0, "SO_DEBUG", LOG_LEVEL_INFO); + return false; +#endif +} + +int Socket::SoError() +{ + int value = 0; +#ifdef SO_ERROR + socklen_t len = sizeof(value); + if (getsockopt(GetSocket(), SOL_SOCKET, SO_ERROR, (char *)&value, &len) == -1) + { + Handler().LogError(this, "getsockopt(SOL_SOCKET, SO_ERROR)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + } +#else + Handler().LogError(this, "socket option not available", 0, "SO_ERROR", LOG_LEVEL_INFO); +#endif + return value; +} + +bool Socket::SetSoDontroute(bool x) +{ +#ifdef SO_DONTROUTE + int optval = x ? 1 : 0; + if (setsockopt(GetSocket(), SOL_SOCKET, SO_DONTROUTE, (char *)&optval, sizeof(optval)) == -1) + { + Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_DONTROUTE)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +#else + Handler().LogError(this, "socket option not available", 0, "SO_DONTROUTE", LOG_LEVEL_INFO); + return false; +#endif +} + +bool Socket::SetSoLinger(int onoff, int linger) +{ +#ifdef SO_LINGER + struct linger stl; + stl.l_onoff = onoff; + stl.l_linger = linger; + if (setsockopt(GetSocket(), SOL_SOCKET, SO_LINGER, (char *)&stl, sizeof(stl)) == -1) + { + Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_LINGER)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +#else + Handler().LogError(this, "socket option not available", 0, "SO_LINGER", LOG_LEVEL_INFO); + return false; +#endif +} + +bool Socket::SetSoOobinline(bool x) +{ +#ifdef SO_OOBINLINE + int optval = x ? 1 : 0; + if (setsockopt(GetSocket(), SOL_SOCKET, SO_OOBINLINE, (char *)&optval, sizeof(optval)) == -1) + { + Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_OOBINLINE)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +#else + Handler().LogError(this, "socket option not available", 0, "SO_OOBINLINE", LOG_LEVEL_INFO); + return false; +#endif +} + +#ifdef SO_PASSCRED +bool Socket::SetSoPasscred(bool x) +{ + int optval = x ? 1 : 0; + if (setsockopt(GetSocket(), SOL_SOCKET, SO_PASSCRED, (char *)&optval, sizeof(optval)) == -1) + { + Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_PASSCRED)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +} +#endif + +#ifdef SO_PEERCRED +bool Socket::SoPeercred(struct ucred& ucr) +{ + if (setsockopt(GetSocket(), SOL_SOCKET, SO_PEERCRED, (char *)&ucr, sizeof(ucr)) == -1) + { + Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_PEERCRED)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +} +#endif + +#ifdef SO_PRIORITY +bool Socket::SetSoPriority(int x) +{ + if (setsockopt(GetSocket(), SOL_SOCKET, SO_PRIORITY, (char *)&x, sizeof(x)) == -1) + { + Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_PRIORITY)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +} +#endif + +bool Socket::SetSoRcvlowat(int x) +{ +#ifdef SO_RCVLOWAT + if (setsockopt(GetSocket(), SOL_SOCKET, SO_RCVLOWAT, (char *)&x, sizeof(x)) == -1) + { + Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_RCVLOWAT)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +#else + Handler().LogError(this, "socket option not available", 0, "SO_RCVLOWAT", LOG_LEVEL_INFO); + return false; +#endif +} + +bool Socket::SetSoSndlowat(int x) +{ +#ifdef SO_SNDLOWAT + if (setsockopt(GetSocket(), SOL_SOCKET, SO_SNDLOWAT, (char *)&x, sizeof(x)) == -1) + { + Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_SNDLOWAT)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +#else + Handler().LogError(this, "socket option not available", 0, "SO_SNDLOWAT", LOG_LEVEL_INFO); + return false; +#endif +} + +bool Socket::SetSoRcvtimeo(struct timeval& tv) +{ +#ifdef SO_RCVTIMEO + if (setsockopt(GetSocket(), SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv)) == -1) + { + Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_RCVTIMEO)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +#else + Handler().LogError(this, "socket option not available", 0, "SO_RCVTIMEO", LOG_LEVEL_INFO); + return false; +#endif +} + +bool Socket::SetSoSndtimeo(struct timeval& tv) +{ +#ifdef SO_SNDTIMEO + if (setsockopt(GetSocket(), SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv)) == -1) + { + Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_SNDTIMEO)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +#else + Handler().LogError(this, "socket option not available", 0, "SO_SNDTIMEO", LOG_LEVEL_INFO); + return false; +#endif +} + +bool Socket::SetSoRcvbuf(int x) +{ +#ifdef SO_RCVBUF + if (setsockopt(GetSocket(), SOL_SOCKET, SO_RCVBUF, (char *)&x, sizeof(x)) == -1) + { + Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_RCVBUF)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +#else + Handler().LogError(this, "socket option not available", 0, "SO_RCVBUF", LOG_LEVEL_INFO); + return false; +#endif +} + +int Socket::SoRcvbuf() +{ + int value = 0; +#ifdef SO_RCVBUF + socklen_t len = sizeof(value); + if (getsockopt(GetSocket(), SOL_SOCKET, SO_RCVBUF, (char *)&value, &len) == -1) + { + Handler().LogError(this, "getsockopt(SOL_SOCKET, SO_RCVBUF)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + } +#else + Handler().LogError(this, "socket option not available", 0, "SO_RCVBUF", LOG_LEVEL_INFO); +#endif + return value; +} + +#ifdef SO_RCVBUFFORCE +bool Socket::SetSoRcvbufforce(int x) +{ + if (setsockopt(GetSocket(), SOL_SOCKET, SO_RCVBUFFORCE, (char *)&x, sizeof(x)) == -1) + { + Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_RCVBUFFORCE)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +} +#endif + +bool Socket::SetSoSndbuf(int x) +{ +#ifdef SO_SNDBUF + if (setsockopt(GetSocket(), SOL_SOCKET, SO_SNDBUF, (char *)&x, sizeof(x)) == -1) + { + Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_SNDBUF)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +#else + Handler().LogError(this, "socket option not available", 0, "SO_SNDBUF", LOG_LEVEL_INFO); + return false; +#endif +} + +int Socket::SoSndbuf() +{ + int value = 0; +#ifdef SO_SNDBUF + socklen_t len = sizeof(value); + if (getsockopt(GetSocket(), SOL_SOCKET, SO_SNDBUF, (char *)&value, &len) == -1) + { + Handler().LogError(this, "getsockopt(SOL_SOCKET, SO_SNDBUF)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + } +#else + Handler().LogError(this, "socket option not available", 0, "SO_SNDBUF", LOG_LEVEL_INFO); +#endif + return value; +} + +#ifdef SO_SNDBUFFORCE +bool Socket::SetSoSndbufforce(int x) +{ + if (setsockopt(GetSocket(), SOL_SOCKET, SO_SNDBUFFORCE, (char *)&x, sizeof(x)) == -1) + { + Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_SNDBUFFORCE)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +} +#endif + +#ifdef SO_TIMESTAMP +bool Socket::SetSoTimestamp(bool x) +{ + int optval = x ? 1 : 0; + if (setsockopt(GetSocket(), SOL_SOCKET, SO_TIMESTAMP, (char *)&optval, sizeof(optval)) == -1) + { + Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_TIMESTAMP)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +} +#endif + +int Socket::SoType() +{ + int value = 0; +#ifdef SO_TYPE + socklen_t len = sizeof(value); + if (getsockopt(GetSocket(), SOL_SOCKET, SO_TYPE, (char *)&value, &len) == -1) + { + Handler().LogError(this, "getsockopt(SOL_SOCKET, SO_TYPE)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + } +#else + Handler().LogError(this, "socket option not available", 0, "SO_TYPE", LOG_LEVEL_INFO); +#endif + return value; +} + +#ifdef ENABLE_TRIGGERS +void Socket::Subscribe(int id) +{ + Handler().Subscribe(id, this); +} + +void Socket::Unsubscribe(int id) +{ + Handler().Unsubscribe(id, this); +} + +void Socket::OnTrigger(int, const TriggerData&) +{ +} + +void Socket::OnCancelled(int) +{ +} +#endif + +void Socket::SetTimeout(time_t secs) +{ + if (!secs) + { + Handler().AddList(m_socket, LIST_TIMEOUT, false); + return; + } + Handler().AddList(m_socket, LIST_TIMEOUT, true); + m_timeout_start = time(NULL); + m_timeout_limit = secs; +} + +void Socket::OnTimeout() +{ +} + +void Socket::OnConnectTimeout() +{ +} + +bool Socket::Timeout(time_t tnow) +{ + if (tnow - m_timeout_start > m_timeout_limit) + return true; + return false; +} + +/** Returns local port number for bound socket file descriptor. */ +port_t Socket::GetSockPort() +{ +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + if (IsIpv6()) + { + struct sockaddr_in6 sa; + socklen_t sockaddr_length = sizeof(struct sockaddr_in6); + if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1) + memset(&sa, 0, sizeof(sa)); + return ntohs(sa.sin6_port); + } +#endif +#endif + struct sockaddr_in sa; + socklen_t sockaddr_length = sizeof(struct sockaddr_in); + if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1) + memset(&sa, 0, sizeof(sa)); + return ntohs(sa.sin_port); +} + +/** Returns local ipv4 address for bound socket file descriptor. */ +ipaddr_t Socket::GetSockIP4() +{ +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + if (IsIpv6()) + { + return 0; + } +#endif +#endif + struct sockaddr_in sa; + socklen_t sockaddr_length = sizeof(struct sockaddr_in); + if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1) + memset(&sa, 0, sizeof(sa)); + ipaddr_t a; + memcpy(&a, &sa.sin_addr, 4); + return a; +} + +/** Returns local ipv4 address as text for bound socket file descriptor. */ +std::string Socket::GetSockAddress() +{ +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + if (IsIpv6()) + { + return ""; + } +#endif +#endif + struct sockaddr_in sa; + socklen_t sockaddr_length = sizeof(struct sockaddr_in); + if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1) + memset(&sa, 0, sizeof(sa)); + Ipv4Address addr( sa ); + return addr.Convert(); +} + +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 +/** Returns local ipv6 address for bound socket file descriptor. */ +struct in6_addr Socket::GetSockIP6() +{ + if (IsIpv6()) + { + struct sockaddr_in6 sa; + socklen_t sockaddr_length = sizeof(struct sockaddr_in6); + if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1) + memset(&sa, 0, sizeof(sa)); + return sa.sin6_addr; + } + struct in6_addr a; + memset(&a, 0, sizeof(a)); + return a; +} + +/** Returns local ipv6 address as text for bound socket file descriptor. */ +std::string Socket::GetSockAddress6() +{ + if (IsIpv6()) + { + struct sockaddr_in6 sa; + socklen_t sockaddr_length = sizeof(struct sockaddr_in6); + if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1) + memset(&sa, 0, sizeof(sa)); + Ipv6Address addr( sa ); + return addr.Convert(); + } + return ""; +} +#endif +#endif + +#ifdef SOCKETS_NAMESPACE +} +#endif + + diff --git a/dep/sockets/SocketHandler.cpp b/dep/sockets/SocketHandler.cpp new file mode 100644 index 00000000000..acf71fb2efa --- /dev/null +++ b/dep/sockets/SocketHandler.cpp @@ -0,0 +1,1377 @@ +/** \file SocketHandler.cpp + ** \date 2004-02-13 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2004-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifdef _WIN32 +#ifdef _MSC_VER +#pragma warning(disable:4786) +#endif +#endif +#include +#include +#include +#include + +#include "SocketHandler.h" +#include "UdpSocket.h" +#include "ResolvSocket.h" +#include "ResolvServer.h" +#include "TcpSocket.h" +#include "Mutex.h" +#include "Utility.h" +#include "SocketAddress.h" + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +//#ifdef _DEBUG +//#define DEB(x) x; fflush(stderr); +//#else +#define DEB(x) +//#endif + +SocketHandler::SocketHandler(StdLog *p) +:m_stdlog(p) +,m_mutex(m_mutex) +,m_b_use_mutex(false) +,m_maxsock(0) +,m_preverror(-1) +,m_errcnt(0) +,m_tlast(0) +#ifdef ENABLE_SOCKS4 +,m_socks4_host(0) +,m_socks4_port(0) +,m_bTryDirect(false) +#endif +#ifdef ENABLE_RESOLVER +,m_resolv_id(0) +,m_resolver(NULL) +#endif +#ifdef ENABLE_POOL +,m_b_enable_pool(false) +#endif +#ifdef ENABLE_TRIGGERS +,m_next_trigger_id(0) +#endif +#ifdef ENABLE_DETACH +,m_slave(false) +#endif +{ + FD_ZERO(&m_rfds); + FD_ZERO(&m_wfds); + FD_ZERO(&m_efds); +} + +SocketHandler::SocketHandler(Mutex& mutex,StdLog *p) +:m_stdlog(p) +,m_mutex(mutex) +,m_b_use_mutex(true) +,m_maxsock(0) +,m_preverror(-1) +,m_errcnt(0) +,m_tlast(0) +#ifdef ENABLE_SOCKS4 +,m_socks4_host(0) +,m_socks4_port(0) +,m_bTryDirect(false) +#endif +#ifdef ENABLE_RESOLVER +,m_resolv_id(0) +,m_resolver(NULL) +#endif +#ifdef ENABLE_POOL +,m_b_enable_pool(false) +#endif +#ifdef ENABLE_TRIGGERS +,m_next_trigger_id(0) +#endif +#ifdef ENABLE_DETACH +,m_slave(false) +#endif +{ + m_mutex.Lock(); + FD_ZERO(&m_rfds); + FD_ZERO(&m_wfds); + FD_ZERO(&m_efds); +} + +SocketHandler::~SocketHandler() +{ +#ifdef ENABLE_RESOLVER + if (m_resolver) + { + m_resolver -> Quit(); + } +#endif + { + while (m_sockets.size()) + { +DEB( fprintf(stderr, "Emptying sockets list in SocketHandler destructor, %d instances\n", (int)m_sockets.size());) + socket_m::iterator it = m_sockets.begin(); + Socket *p = it -> second; + if (p) + { +DEB( fprintf(stderr, " fd %d\n", p -> GetSocket());) + p -> Close(); +DEB( fprintf(stderr, " fd closed %d\n", p -> GetSocket());) +// p -> OnDelete(); // hey, I turn this back on. what's the worst that could happen??!! + // MinionSocket breaks, calling MinderHandler methods in OnDelete - + // MinderHandler is already gone when that happens... + + // only delete socket when controlled + // ie master sockethandler can delete non-detached sockets + // and a slave sockethandler can only delete a detach socket + if (p -> DeleteByHandler() +#ifdef ENABLE_DETACH + && !(m_slave ^ p -> IsDetached()) +#endif + ) + { + p -> SetErasedByHandler(); + delete p; + } + m_sockets.erase(it); + } + else + { + m_sockets.erase(it); + } +DEB( fprintf(stderr, "next\n");) + } +DEB( fprintf(stderr, "/Emptying sockets list in SocketHandler destructor, %d instances\n", (int)m_sockets.size());) + } +#ifdef ENABLE_RESOLVER + if (m_resolver) + { + delete m_resolver; + } +#endif + if (m_b_use_mutex) + { + m_mutex.Unlock(); + } +} + +Mutex& SocketHandler::GetMutex() const +{ + return m_mutex; +} + +#ifdef ENABLE_DETACH +void SocketHandler::SetSlave(bool x) +{ + m_slave = x; +} + +bool SocketHandler::IsSlave() +{ + return m_slave; +} +#endif + +void SocketHandler::RegStdLog(StdLog *log) +{ + m_stdlog = log; +} + +void SocketHandler::LogError(Socket *p,const std::string& user_text,int err,const std::string& sys_err,loglevel_t t) +{ + if (m_stdlog) + { + m_stdlog -> error(this, p, user_text, err, sys_err, t); + } +} + +void SocketHandler::Add(Socket *p) +{ + if (p -> GetSocket() == INVALID_SOCKET) + { + LogError(p, "Add", -1, "Invalid socket", LOG_LEVEL_WARNING); + if (p -> CloseAndDelete()) + { + m_delete.push_back(p); + } + return; + } + if (m_add.find(p -> GetSocket()) != m_add.end()) + { + LogError(p, "Add", (int)p -> GetSocket(), "Attempt to add socket already in add queue", LOG_LEVEL_FATAL); + m_delete.push_back(p); + return; + } + m_add[p -> GetSocket()] = p; +} + +void SocketHandler::Get(SOCKET s,bool& r,bool& w,bool& e) +{ + if (s >= 0) + { + r = FD_ISSET(s, &m_rfds) ? true : false; + w = FD_ISSET(s, &m_wfds) ? true : false; + e = FD_ISSET(s, &m_efds) ? true : false; + } +} + +void SocketHandler::Set(SOCKET s,bool bRead,bool bWrite,bool bException) +{ +DEB( fprintf(stderr, "Set(%d, %s, %s, %s)\n", s, bRead ? "true" : "false", bWrite ? "true" : "false", bException ? "true" : "false");) + if (s >= 0) + { + if (bRead) + { + if (!FD_ISSET(s, &m_rfds)) + { + FD_SET(s, &m_rfds); + } + } + else + { + FD_CLR(s, &m_rfds); + } + if (bWrite) + { + if (!FD_ISSET(s, &m_wfds)) + { + FD_SET(s, &m_wfds); + } + } + else + { + FD_CLR(s, &m_wfds); + } + if (bException) + { + if (!FD_ISSET(s, &m_efds)) + { + FD_SET(s, &m_efds); + } + } + else + { + FD_CLR(s, &m_efds); + } + } +} + +int SocketHandler::Select(long sec,long usec) +{ + struct timeval tv; + tv.tv_sec = sec; + tv.tv_usec = usec; + return Select(&tv); +} + +int SocketHandler::Select() +{ + if (!m_fds_callonconnect.empty() || +#ifdef ENABLE_DETACH + (!m_slave && !m_fds_detach.empty()) || +#endif + !m_fds_timeout.empty() || + !m_fds_retry.empty() || + !m_fds_close.empty() || + !m_fds_erase.empty()) + { + return Select(0, 200000); + } + return Select(NULL); +} + +int SocketHandler::Select(struct timeval *tsel) +{ + size_t ignore = 0; + while (m_add.size() > ignore) + { + if (m_sockets.size() >= FD_SETSIZE) + { + LogError(NULL, "Select", (int)m_sockets.size(), "FD_SETSIZE reached", LOG_LEVEL_WARNING); + break; + } + socket_m::iterator it = m_add.begin(); + SOCKET s = it -> first; + Socket *p = it -> second; +DEB( fprintf(stderr, "Trying to add fd %d, m_add.size() %d, ignore %d\n", (int)s, (int)m_add.size(), (int)ignore);) + // + if (m_sockets.find(p -> GetSocket()) != m_sockets.end()) + { + LogError(p, "Add", (int)p -> GetSocket(), "Attempt to add socket already in controlled queue", LOG_LEVEL_FATAL); + // %! it's a dup, don't add to delete queue, just ignore it + m_delete.push_back(p); + m_add.erase(it); +// ignore++; + continue; + } + if (!p -> CloseAndDelete()) + { + StreamSocket *scp = dynamic_cast(p); + if (scp && scp -> Connecting()) // 'Open' called before adding socket + { + Set(s,false,true); + } + else + { + TcpSocket *tcp = dynamic_cast(p); + bool bWrite = tcp ? tcp -> GetOutputLength() != 0 : false; + if (p -> IsDisableRead()) + { + Set(s, false, bWrite); + } + else + { + Set(s, true, bWrite); + } + } + m_maxsock = (s > m_maxsock) ? s : m_maxsock; + } + else + { + LogError(p, "Add", (int)p -> GetSocket(), "Trying to add socket with SetCloseAndDelete() true", LOG_LEVEL_WARNING); + } + // only add to m_fds (process fd_set events) if + // slave handler and detached/detaching socket + // master handler and non-detached socket +#ifdef ENABLE_DETACH + if (!(m_slave ^ p -> IsDetach())) +#endif + { + m_fds.push_back(s); + } + m_sockets[s] = p; + // + m_add.erase(it); + } +#ifdef MACOSX + fd_set rfds; + fd_set wfds; + fd_set efds; + FD_COPY(&m_rfds, &rfds); + FD_COPY(&m_wfds, &wfds); + FD_COPY(&m_efds, &efds); +#else + fd_set rfds = m_rfds; + fd_set wfds = m_wfds; + fd_set efds = m_efds; +#endif + int n; + if (m_b_use_mutex) + { + m_mutex.Unlock(); + n = select( (int)(m_maxsock + 1),&rfds,&wfds,&efds,tsel); + m_mutex.Lock(); + } + else + { + n = select( (int)(m_maxsock + 1),&rfds,&wfds,&efds,tsel); + } + if (n == -1) + { + /* + EBADF An invalid file descriptor was given in one of the sets. + EINTR A non blocked signal was caught. + EINVAL n is negative. Or struct timeval contains bad time values (<0). + ENOMEM select was unable to allocate memory for internal tables. + */ + if (Errno != m_preverror || m_errcnt++ % 10000 == 0) + { + LogError(NULL, "select", Errno, StrError(Errno)); +DEB( fprintf(stderr, "m_maxsock: %d\n", m_maxsock); + fprintf(stderr, "%s\n", Errno == EINVAL ? "EINVAL" : + Errno == EINTR ? "EINTR" : + Errno == EBADF ? "EBADF" : + Errno == ENOMEM ? "ENOMEM" : ""); + // test bad fd + for (SOCKET i = 0; i <= m_maxsock; i++) + { + bool t = false; + FD_ZERO(&rfds); + FD_ZERO(&wfds); + FD_ZERO(&efds); + if (FD_ISSET(i, &m_rfds)) + { + FD_SET(i, &rfds); + t = true; + } + if (FD_ISSET(i, &m_wfds)) + { + FD_SET(i, &wfds); + t = true; + } + if (FD_ISSET(i, &m_efds)) + { + FD_SET(i, &efds); + t = true; + } + if (t && m_sockets.find(i) == m_sockets.end()) + { + fprintf(stderr, "Bad fd in fd_set: %d\n", i); + } + } +) // DEB + m_preverror = Errno; + } + /// \todo rebuild fd_set's from active sockets list (m_sockets) here + } + else + if (!n) + { + m_preverror = -1; + } + else + if (n > 0) + { + for (socket_v::iterator it2 = m_fds.begin(); it2 != m_fds.end() && n; it2++) + { + SOCKET i = *it2; + if (FD_ISSET(i, &rfds)) + { + socket_m::iterator itmp = m_sockets.find(i); + if (itmp != m_sockets.end()) // found + { + Socket *p = itmp -> second; + // new SSL negotiate method +#ifdef HAVE_OPENSSL + if (p -> IsSSLNegotiate()) + { + p -> SSLNegotiate(); + } + else +#endif + { + p -> OnRead(); + } + } + else + { + LogError(NULL, "GetSocket/handler/1", (int)i, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING); + } + n--; + } + if (FD_ISSET(i, &wfds)) + { + socket_m::iterator itmp = m_sockets.find(i); + if (itmp != m_sockets.end()) // found + { + Socket *p = itmp -> second; + // new SSL negotiate method +#ifdef HAVE_OPENSSL + if (p -> IsSSLNegotiate()) + { + p -> SSLNegotiate(); + } + else +#endif + { + p -> OnWrite(); + } + } + else + { + LogError(NULL, "GetSocket/handler/2", (int)i, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING); + } + n--; + } + if (FD_ISSET(i, &efds)) + { + socket_m::iterator itmp = m_sockets.find(i); + if (itmp != m_sockets.end()) // found + { + Socket *p = itmp -> second; + p -> OnException(); + } + else + { + LogError(NULL, "GetSocket/handler/3", (int)i, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING); + } + n--; + } + } // m_fds loop + m_preverror = -1; + } // if (n > 0) + + // check CallOnConnect - EVENT + if (!m_fds_callonconnect.empty()) + { + socket_v tmp = m_fds_callonconnect; + for (socket_v::iterator it = tmp.begin(); it != tmp.end(); it++) + { + Socket *p = NULL; + { + socket_m::iterator itmp = m_sockets.find(*it); + if (itmp != m_sockets.end()) // found + { + p = itmp -> second; + } + else + { + LogError(NULL, "GetSocket/handler/4", (int)*it, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING); + } + } + if (p) + { +// if (p -> CallOnConnect() && p -> Ready() ) + { + p -> SetConnected(); // moved here from inside if (tcp) check below +#ifdef HAVE_OPENSSL + if (p -> IsSSL()) // SSL Enabled socket + p -> OnSSLConnect(); + else +#endif +#ifdef ENABLE_SOCKS4 + if (p -> Socks4()) + p -> OnSocks4Connect(); + else +#endif + { + TcpSocket *tcp = dynamic_cast(p); + if (tcp) + { + if (tcp -> GetOutputLength()) + { + p -> OnWrite(); + } + } +#ifdef ENABLE_RECONNECT + if (tcp && tcp -> IsReconnect()) + p -> OnReconnect(); + else +#endif + { +// LogError(p, "Calling OnConnect", 0, "Because CallOnConnect", LOG_LEVEL_INFO); + p -> OnConnect(); + } + } +// p -> SetCallOnConnect( false ); + AddList(p -> GetSocket(), LIST_CALLONCONNECT, false); + } + } + } + } +#ifdef ENABLE_DETACH + // check detach of socket if master handler - EVENT + if (!m_slave && !m_fds_detach.empty()) + { + // %! why not using tmp list here??!? + for (socket_v::iterator it = m_fds_detach.begin(); it != m_fds_detach.end(); it++) + { + Socket *p = NULL; + { + socket_m::iterator itmp = m_sockets.find(*it); + if (itmp != m_sockets.end()) // found + { + p = itmp -> second; + } + else + { + LogError(NULL, "GetSocket/handler/5", (int)*it, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING); + } + } + if (p) + { +// if (p -> IsDetach()) + { + Set(p -> GetSocket(), false, false, false); + // After DetachSocket(), all calls to Handler() will return a reference + // to the new slave SocketHandler running in the new thread. + p -> DetachSocket(); + // Adding the file descriptor to m_fds_erase will now also remove the + // socket from the detach queue - tnx knightmad + m_fds_erase.push_back(p -> GetSocket()); + } + } + } + } +#endif + // check Connecting - connection timeout - conditional event + if (m_fds_timeout.size()) + { + time_t tnow = time(NULL); + if (tnow != m_tlast) + { + socket_v tmp = m_fds_timeout; +DEB( fprintf(stderr, "Checking %d socket(s) for timeout\n", tmp.size());) + for (socket_v::iterator it = tmp.begin(); it != tmp.end(); it++) + { + Socket *p = NULL; + { + socket_m::iterator itmp = m_sockets.find(*it); + if (itmp != m_sockets.end()) // found + { + p = itmp -> second; + } + else + { + itmp = m_add.find(*it); + if (itmp != m_add.end()) + { + p = itmp -> second; + } + else + { + LogError(NULL, "GetSocket/handler/6", (int)*it, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING); + } + } + } + if (p) + { + if (p -> Timeout(tnow)) + { + StreamSocket *scp = dynamic_cast(p); + if (scp && scp -> Connecting()) + p -> OnConnectTimeout(); + else + p -> OnTimeout(); + p -> SetTimeout(0); + } + } + } + m_tlast = tnow; + } // tnow != tlast + } + // check retry client connect - EVENT + if (!m_fds_retry.empty()) + { + socket_v tmp = m_fds_retry; + for (socket_v::iterator it = tmp.begin(); it != tmp.end(); it++) + { + Socket *p = NULL; + { + socket_m::iterator itmp = m_sockets.find(*it); + if (itmp != m_sockets.end()) // found + { + p = itmp -> second; + } + else + { + LogError(NULL, "GetSocket/handler/7", (int)*it, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING); + } + } + if (p) + { +// if (p -> RetryClientConnect()) + { + TcpSocket *tcp = dynamic_cast(p); + SOCKET nn = *it; //(*it3).first; + tcp -> SetRetryClientConnect(false); +DEB( fprintf(stderr, "Close() before retry client connect\n");) + p -> Close(); // removes from m_fds_retry + std::auto_ptr ad = p -> GetClientRemoteAddress(); + if (ad.get()) + { + tcp -> Open(*ad); + } + else + { + LogError(p, "RetryClientConnect", 0, "no address", LOG_LEVEL_ERROR); + } + Add(p); + m_fds_erase.push_back(nn); + } + } + } + } + // check close and delete - conditional event + if (!m_fds_close.empty()) + { + socket_v tmp = m_fds_close; +DEB( fprintf(stderr, "m_fds_close.size() == %d\n", (int)m_fds_close.size());) + for (socket_v::iterator it = tmp.begin(); it != tmp.end(); it++) + { + Socket *p = NULL; + { + socket_m::iterator itmp = m_sockets.find(*it); + if (itmp != m_sockets.end()) // found + { + p = itmp -> second; + } + else + { + itmp = m_add.find(*it); + if (itmp != m_add.end()) + { + p = itmp -> second; + } + else + { + LogError(NULL, "GetSocket/handler/8", (int)*it, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING); + } + } + } + if (p) + { +// if (p -> CloseAndDelete() ) + { + TcpSocket *tcp = dynamic_cast(p); + // new graceful tcp - flush and close timeout 5s + if (tcp && p -> IsConnected() && tcp -> GetFlushBeforeClose() && +#ifdef HAVE_OPENSSL + !tcp -> IsSSL() && +#endif + p -> TimeSinceClose() < 5) + { +DEB( fprintf(stderr, " close(1)\n");) + if (tcp -> GetOutputLength()) + { + LogError(p, "Closing", (int)tcp -> GetOutputLength(), "Sending all data before closing", LOG_LEVEL_INFO); + } + else // shutdown write when output buffer is empty + if (!(tcp -> GetShutdown() & SHUT_WR)) + { + SOCKET nn = *it; + if (nn != INVALID_SOCKET && shutdown(nn, SHUT_WR) == -1) + { + LogError(p, "graceful shutdown", Errno, StrError(Errno), LOG_LEVEL_ERROR); + } + tcp -> SetShutdown(SHUT_WR); + } + } + else +#ifdef ENABLE_RECONNECT + if (tcp && p -> IsConnected() && tcp -> Reconnect()) + { + SOCKET nn = *it; //(*it3).first; +DEB( fprintf(stderr, " close(2) fd %d\n", nn);) + p -> SetCloseAndDelete(false); + tcp -> SetIsReconnect(); + p -> SetConnected(false); +DEB( fprintf(stderr, "Close() before reconnect\n");) + p -> Close(); // dispose of old file descriptor (Open creates a new) + p -> OnDisconnect(); + std::auto_ptr ad = p -> GetClientRemoteAddress(); + if (ad.get()) + { + tcp -> Open(*ad); + } + else + { + LogError(p, "Reconnect", 0, "no address", LOG_LEVEL_ERROR); + } + tcp -> ResetConnectionRetries(); + Add(p); + m_fds_erase.push_back(nn); + } + else +#endif + { + SOCKET nn = *it; //(*it3).first; +DEB( fprintf(stderr, " close(3) fd %d GetSocket() %d\n", nn, p -> GetSocket());) + if (tcp && p -> IsConnected() && tcp -> GetOutputLength()) + { + LogError(p, "Closing", (int)tcp -> GetOutputLength(), "Closing socket while data still left to send", LOG_LEVEL_WARNING); + } +#ifdef ENABLE_POOL + if (p -> Retain() && !p -> Lost()) + { + PoolSocket *p2 = new PoolSocket(*this, p); + p2 -> SetDeleteByHandler(); + Add(p2); + // + p -> SetCloseAndDelete(false); // added - remove from m_fds_close + } + else +#endif // ENABLE_POOL + { + Set(p -> GetSocket(),false,false,false); +DEB( fprintf(stderr, "Close() before OnDelete\n");) + p -> Close(); + } + p -> OnDelete(); + if (p -> DeleteByHandler()) + { + p -> SetErasedByHandler(); + } + m_fds_erase.push_back(nn); + } + } + } + } + } + + // check erased sockets + bool check_max_fd = false; + while (!m_fds_erase.empty()) + { + socket_v::iterator it = m_fds_erase.begin(); + SOCKET nn = *it; +#ifdef ENABLE_DETACH + { + for (socket_v::iterator it = m_fds_detach.begin(); it != m_fds_detach.end(); it++) + { + if (*it == nn) + { + m_fds_detach.erase(it); + break; + } + } + } +#endif + { + for (socket_v::iterator it = m_fds.begin(); it != m_fds.end(); it++) + { + if (*it == nn) + { + m_fds.erase(it); + break; + } + } + } + { + socket_m::iterator it = m_sockets.find(nn); + if (it != m_sockets.end()) + { + Socket *p = it -> second; + /* Sometimes a SocketThread class can finish its run before the master + sockethandler gets here. In that case, the SocketThread has set the + 'ErasedByHandler' flag on the socket which will make us end up with a + double delete on the socket instance. + The fix is to make sure that the master sockethandler only can delete + non-detached sockets, and a slave sockethandler only can delete + detach sockets. */ + if (p -> ErasedByHandler() +#ifdef ENABLE_DETACH + && !(m_slave ^ p -> IsDetached()) +#endif + ) + { +#ifdef ENABLE_TRIGGERS + bool again = false; + do + { + again = false; + for (std::map::iterator it = m_trigger_src.begin(); it != m_trigger_src.end(); it++) + { + int id = it -> first; + Socket *src = it -> second; + if (src == p) + { + for (std::map::iterator it = m_trigger_dst[id].begin(); it != m_trigger_dst[id].end(); it++) + { + Socket *dst = it -> first; + if (Valid(dst)) + { + dst -> OnCancelled(id); + } + } + m_trigger_src.erase(m_trigger_src.find(id)); + m_trigger_dst.erase(m_trigger_dst.find(id)); + again = true; + break; + } + } + } while (again); +#endif + delete p; + } + m_sockets.erase(it); + } + } + m_fds_erase.erase(it); + check_max_fd = true; + } + // calculate max file descriptor for select() call + if (check_max_fd) + { + m_maxsock = 0; + for (socket_v::iterator it = m_fds.begin(); it != m_fds.end(); it++) + { + SOCKET s = *it; + m_maxsock = s > m_maxsock ? s : m_maxsock; + } + } + // remove Add's that fizzed + while (!m_delete.empty()) + { + std::list::iterator it = m_delete.begin(); + Socket *p = *it; + p -> OnDelete(); + m_delete.erase(it); + if (p -> DeleteByHandler() +#ifdef ENABLE_DETACH + && !(m_slave ^ p -> IsDetached()) +#endif + ) + { + p -> SetErasedByHandler(); +#ifdef ENABLE_TRIGGERS + bool again = false; + do + { + again = false; + for (std::map::iterator it = m_trigger_src.begin(); it != m_trigger_src.end(); it++) + { + int id = it -> first; + Socket *src = it -> second; + if (src == p) + { + for (std::map::iterator it = m_trigger_dst[id].begin(); it != m_trigger_dst[id].end(); it++) + { + Socket *dst = it -> first; + if (Valid(dst)) + { + dst -> OnCancelled(id); + } + } + m_trigger_src.erase(m_trigger_src.find(id)); + m_trigger_dst.erase(m_trigger_dst.find(id)); + again = true; + break; + } + } + } while (again); +#endif + delete p; + } + } + return n; +} + +#ifdef ENABLE_RESOLVER +bool SocketHandler::Resolving(Socket *p0) +{ + std::map::iterator it = m_resolve_q.find(p0); + return it != m_resolve_q.end(); +} +#endif + +bool SocketHandler::Valid(Socket *p0) +{ + for (socket_m::iterator it = m_sockets.begin(); it != m_sockets.end(); it++) + { + Socket *p = it -> second; + if (p0 == p) + return true; + } + return false; +} + +bool SocketHandler::OkToAccept(Socket *) +{ + return true; +} + +size_t SocketHandler::GetCount() +{ +/* +printf(" m_sockets : %d\n", m_sockets.size()); +printf(" m_add : %d\n", m_add.size()); +printf(" m_delete : %d\n", m_delete.size()); +*/ + return m_sockets.size() + m_add.size() + m_delete.size(); +} + +#ifdef ENABLE_SOCKS4 +void SocketHandler::SetSocks4Host(ipaddr_t a) +{ + m_socks4_host = a; +} + +void SocketHandler::SetSocks4Host(const std::string& host) +{ + Utility::u2ip(host, m_socks4_host); +} + +void SocketHandler::SetSocks4Port(port_t port) +{ + m_socks4_port = port; +} + +void SocketHandler::SetSocks4Userid(const std::string& id) +{ + m_socks4_userid = id; +} +#endif + +#ifdef ENABLE_RESOLVER +int SocketHandler::Resolve(Socket *p,const std::string& host,port_t port) +{ + // check cache + ResolvSocket *resolv = new ResolvSocket(*this, p, host, port); + resolv -> SetId(++m_resolv_id); + resolv -> SetDeleteByHandler(); + ipaddr_t local; + Utility::u2ip("127.0.0.1", local); + if (!resolv -> Open(local, m_resolver_port)) + { + LogError(resolv, "Resolve", -1, "Can't connect to local resolve server", LOG_LEVEL_FATAL); + } + Add(resolv); + m_resolve_q[p] = true; +DEB( fprintf(stderr, " *** Resolve '%s:%d' id#%d m_resolve_q size: %d p: %p\n", host.c_str(), port, resolv -> GetId(), m_resolve_q.size(), p);) + return resolv -> GetId(); +} + +#ifdef ENABLE_IPV6 +int SocketHandler::Resolve6(Socket *p,const std::string& host,port_t port) +{ + // check cache + ResolvSocket *resolv = new ResolvSocket(*this, p, host, port, true); + resolv -> SetId(++m_resolv_id); + resolv -> SetDeleteByHandler(); + ipaddr_t local; + Utility::u2ip("127.0.0.1", local); + if (!resolv -> Open(local, m_resolver_port)) + { + LogError(resolv, "Resolve", -1, "Can't connect to local resolve server", LOG_LEVEL_FATAL); + } + Add(resolv); + m_resolve_q[p] = true; + return resolv -> GetId(); +} +#endif + +int SocketHandler::Resolve(Socket *p,ipaddr_t a) +{ + // check cache + ResolvSocket *resolv = new ResolvSocket(*this, p, a); + resolv -> SetId(++m_resolv_id); + resolv -> SetDeleteByHandler(); + ipaddr_t local; + Utility::u2ip("127.0.0.1", local); + if (!resolv -> Open(local, m_resolver_port)) + { + LogError(resolv, "Resolve", -1, "Can't connect to local resolve server", LOG_LEVEL_FATAL); + } + Add(resolv); + m_resolve_q[p] = true; + return resolv -> GetId(); +} + +#ifdef ENABLE_IPV6 +int SocketHandler::Resolve(Socket *p,in6_addr& a) +{ + // check cache + ResolvSocket *resolv = new ResolvSocket(*this, p, a); + resolv -> SetId(++m_resolv_id); + resolv -> SetDeleteByHandler(); + ipaddr_t local; + Utility::u2ip("127.0.0.1", local); + if (!resolv -> Open(local, m_resolver_port)) + { + LogError(resolv, "Resolve", -1, "Can't connect to local resolve server", LOG_LEVEL_FATAL); + } + Add(resolv); + m_resolve_q[p] = true; + return resolv -> GetId(); +} +#endif + +void SocketHandler::EnableResolver(port_t port) +{ + if (!m_resolver) + { + m_resolver_port = port; + m_resolver = new ResolvServer(port); + } +} + +bool SocketHandler::ResolverReady() +{ + return m_resolver ? m_resolver -> Ready() : false; +} +#endif // ENABLE_RESOLVER + +#ifdef ENABLE_SOCKS4 +void SocketHandler::SetSocks4TryDirect(bool x) +{ + m_bTryDirect = x; +} + +ipaddr_t SocketHandler::GetSocks4Host() +{ + return m_socks4_host; +} + +port_t SocketHandler::GetSocks4Port() +{ + return m_socks4_port; +} + +const std::string& SocketHandler::GetSocks4Userid() +{ + return m_socks4_userid; +} + +bool SocketHandler::Socks4TryDirect() +{ + return m_bTryDirect; +} +#endif + +#ifdef ENABLE_RESOLVER +bool SocketHandler::ResolverEnabled() +{ + return m_resolver ? true : false; +} + +port_t SocketHandler::GetResolverPort() +{ + return m_resolver_port; +} +#endif // ENABLE_RESOLVER + +#ifdef ENABLE_POOL +ISocketHandler::PoolSocket *SocketHandler::FindConnection(int type,const std::string& protocol,SocketAddress& ad) +{ + for (socket_m::iterator it = m_sockets.begin(); it != m_sockets.end() && !m_sockets.empty(); it++) + { + PoolSocket *pools = dynamic_cast(it -> second); + if (pools) + { + if (pools -> GetSocketType() == type && + pools -> GetSocketProtocol() == protocol && +// %! pools -> GetClientRemoteAddress() && + *pools -> GetClientRemoteAddress() == ad) + { + m_sockets.erase(it); + pools -> SetRetain(); // avoid Close in Socket destructor + return pools; // Caller is responsible that this socket is deleted + } + } + } + return NULL; +} + +void SocketHandler::EnablePool(bool x) +{ + m_b_enable_pool = x; +} + +bool SocketHandler::PoolEnabled() +{ + return m_b_enable_pool; +} +#endif + +void SocketHandler::Remove(Socket *p) +{ +#ifdef ENABLE_RESOLVER + std::map::iterator it4 = m_resolve_q.find(p); + if (it4 != m_resolve_q.end()) + m_resolve_q.erase(it4); +#endif + if (p -> ErasedByHandler()) + { + return; + } + for (socket_m::iterator it = m_sockets.begin(); it != m_sockets.end(); it++) + { + if (it -> second == p) + { + LogError(p, "Remove", -1, "Socket destructor called while still in use", LOG_LEVEL_WARNING); + m_sockets.erase(it); + return; + } + } + for (socket_m::iterator it2 = m_add.begin(); it2 != m_add.end(); it2++) + { + if ((*it2).second == p) + { + LogError(p, "Remove", -2, "Socket destructor called while still in use", LOG_LEVEL_WARNING); + m_add.erase(it2); + return; + } + } + for (std::list::iterator it3 = m_delete.begin(); it3 != m_delete.end(); it3++) + { + if (*it3 == p) + { + LogError(p, "Remove", -3, "Socket destructor called while still in use", LOG_LEVEL_WARNING); + m_delete.erase(it3); + return; + } + } +} + +void SocketHandler::CheckSanity() +{ + CheckList(m_fds, "active sockets"); // active sockets + CheckList(m_fds_erase, "sockets to be erased"); // should always be empty anyway + CheckList(m_fds_callonconnect, "checklist CallOnConnect"); +#ifdef ENABLE_DETACH + CheckList(m_fds_detach, "checklist Detach"); +#endif + CheckList(m_fds_timeout, "checklist Timeout"); + CheckList(m_fds_retry, "checklist retry client connect"); + CheckList(m_fds_close, "checklist close and delete"); +} + +void SocketHandler::CheckList(socket_v& ref,const std::string& listname) +{ + for (socket_v::iterator it = ref.begin(); it != ref.end(); it++) + { + SOCKET s = *it; + if (m_sockets.find(s) != m_sockets.end()) + continue; + if (m_add.find(s) != m_add.end()) + continue; + bool found = false; + for (std::list::iterator it = m_delete.begin(); it != m_delete.end(); it++) + { + Socket *p = *it; + if (p -> GetSocket() == s) + { + found = true; + break; + } + } + if (!found) + { + fprintf(stderr, "CheckList failed for \"%s\": fd %d\n", listname.c_str(), s); + } + } +} + +void SocketHandler::AddList(SOCKET s,list_t which_one,bool add) +{ + if (s == INVALID_SOCKET) + { +DEB( fprintf(stderr, "AddList: invalid_socket\n");) + return; + } + socket_v& ref = + (which_one == LIST_CALLONCONNECT) ? m_fds_callonconnect : +#ifdef ENABLE_DETACH + (which_one == LIST_DETACH) ? m_fds_detach : +#endif + (which_one == LIST_TIMEOUT) ? m_fds_timeout : + (which_one == LIST_RETRY) ? m_fds_retry : + (which_one == LIST_CLOSE) ? m_fds_close : m_fds_close; + if (add) + { +#ifdef ENABLE_DETACH +DEB( fprintf(stderr, "AddList; %5d: %s: %s\n", s, (which_one == LIST_CALLONCONNECT) ? "CallOnConnect" : + (which_one == LIST_DETACH) ? "Detach" : + (which_one == LIST_TIMEOUT) ? "Timeout" : + (which_one == LIST_RETRY) ? "Retry" : + (which_one == LIST_CLOSE) ? "Close" : "", + add ? "Add" : "Remove");) +#else +DEB( fprintf(stderr, "AddList; %5d: %s: %s\n", s, (which_one == LIST_CALLONCONNECT) ? "CallOnConnect" : + (which_one == LIST_TIMEOUT) ? "Timeout" : + (which_one == LIST_RETRY) ? "Retry" : + (which_one == LIST_CLOSE) ? "Close" : "", + add ? "Add" : "Remove");) +#endif + } + if (add) + { + for (socket_v::iterator it = ref.begin(); it != ref.end(); it++) + { + if (*it == s) // already there + { + return; + } + } + ref.push_back(s); + return; + } + // remove + for (socket_v::iterator it = ref.begin(); it != ref.end(); it++) + { + if (*it == s) + { + ref.erase(it); + break; + } + } +//DEB( fprintf(stderr, "/AddList\n");) +} + +#ifdef ENABLE_TRIGGERS +int SocketHandler::TriggerID(Socket *src) +{ + int id = m_next_trigger_id++; + m_trigger_src[id] = src; + return id; +} + +bool SocketHandler::Subscribe(int id, Socket *dst) +{ + if (m_trigger_src.find(id) != m_trigger_src.end()) + { + std::map::iterator it = m_trigger_dst[id].find(dst); + if (it != m_trigger_dst[id].end()) + { + m_trigger_dst[id][dst] = true; + return true; + } + LogError(dst, "Subscribe", id, "Already subscribed", LOG_LEVEL_INFO); + return false; + } + LogError(dst, "Subscribe", id, "Trigger id not found", LOG_LEVEL_INFO); + return false; +} + +bool SocketHandler::Unsubscribe(int id, Socket *dst) +{ + if (m_trigger_src.find(id) != m_trigger_src.end()) + { + std::map::iterator it = m_trigger_dst[id].find(dst); + if (it != m_trigger_dst[id].end()) + { + m_trigger_dst[id].erase(it); + return true; + } + LogError(dst, "Unsubscribe", id, "Not subscribed", LOG_LEVEL_INFO); + return false; + } + LogError(dst, "Unsubscribe", id, "Trigger id not found", LOG_LEVEL_INFO); + return false; +} + +void SocketHandler::Trigger(int id, Socket::TriggerData& data, bool erase) +{ + if (m_trigger_src.find(id) != m_trigger_src.end()) + { + data.SetSource( m_trigger_src[id] ); + for (std::map::iterator it = m_trigger_dst[id].begin(); it != m_trigger_dst[id].end(); it++) + { + Socket *dst = it -> first; + if (Valid(dst)) + { + dst -> OnTrigger(id, data); + } + } + if (erase) + { + m_trigger_src.erase(m_trigger_src.find(id)); + m_trigger_dst.erase(m_trigger_dst.find(id)); + } + } + else + { + LogError(NULL, "Trigger", id, "Trigger id not found", LOG_LEVEL_INFO); + } +} +#endif // ENABLE_TRIGGERS + +#ifdef SOCKETS_NAMESPACE +} +#endif + + diff --git a/dep/sockets/StdoutLog.cpp b/dep/sockets/StdoutLog.cpp new file mode 100644 index 00000000000..e745a6d3358 --- /dev/null +++ b/dep/sockets/StdoutLog.cpp @@ -0,0 +1,98 @@ +/** \file StdoutLog.cpp + ** \date 2004-06-01 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2004-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#include + +#ifdef _MSC_VER +#pragma warning(disable:4786) +#endif + +#include + +#include "ISocketHandler.h" +#include "Socket.h" +#include "StdoutLog.h" + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + + +void StdoutLog::error(ISocketHandler *,Socket *sock,const std::string& call,int err,const std::string& sys_err,loglevel_t lvl) +{ + time_t t = time(NULL); + struct tm tp; +#ifdef _WIN32 + memcpy(&tp, localtime(&t), sizeof(tp)); +#else + localtime_r(&t, &tp); +#endif + std::string level; + + switch (lvl) + { + case LOG_LEVEL_WARNING: + level = "Warning"; + break; + case LOG_LEVEL_ERROR: + level = "Error"; + break; + case LOG_LEVEL_FATAL: + level = "Fatal"; + break; + case LOG_LEVEL_INFO: + level = "Info"; + break; + } + if (sock) + { + printf("%d-%02d-%02d %02d:%02d:%02d :: fd %d :: %s: %d %s (%s)\n", + tp.tm_year + 1900, + tp.tm_mon + 1, + tp.tm_mday, + tp.tm_hour,tp.tm_min,tp.tm_sec, + sock -> GetSocket(), + call.c_str(),err,sys_err.c_str(),level.c_str()); + } + else + { + printf("%d-%02d-%02d %02d:%02d:%02d :: %s: %d %s (%s)\n", + tp.tm_year + 1900, + tp.tm_mon + 1, + tp.tm_mday, + tp.tm_hour,tp.tm_min,tp.tm_sec, + call.c_str(),err,sys_err.c_str(),level.c_str()); + } +} + +#ifdef SOCKETS_NAMESPACE +} +#endif + + diff --git a/dep/sockets/StreamSocket.cpp b/dep/sockets/StreamSocket.cpp new file mode 100644 index 00000000000..009abadad8f --- /dev/null +++ b/dep/sockets/StreamSocket.cpp @@ -0,0 +1,145 @@ +#include "StreamSocket.h" +#include "ISocketHandler.h" + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +StreamSocket::StreamSocket(ISocketHandler& h) : Socket(h) +,m_bConnecting(false) +,m_connect_timeout(5) +,m_flush_before_close(true) +,m_connection_retry(0) +,m_retries(0) +,m_call_on_connect(false) +,m_b_retry_connect(false) +,m_line_protocol(false) +,m_shutdown(0) +{ +} + +StreamSocket::~StreamSocket() +{ +} + +void StreamSocket::SetConnecting(bool x) +{ + if (x != m_bConnecting) + { + m_bConnecting = x; + if (x) + { + SetTimeout( GetConnectTimeout() ); + } + else + { + SetTimeout( 0 ); + } + } +} + +bool StreamSocket::Connecting() +{ + return m_bConnecting; +} + +bool StreamSocket::Ready() +{ + if (GetSocket() != INVALID_SOCKET && !Connecting() && !CloseAndDelete()) + return true; + return false; +} + +void StreamSocket::SetConnectTimeout(int x) +{ + m_connect_timeout = x; +} + +int StreamSocket::GetConnectTimeout() +{ + return m_connect_timeout; +} + +void StreamSocket::SetFlushBeforeClose(bool x) +{ + m_flush_before_close = x; +} + +bool StreamSocket::GetFlushBeforeClose() +{ + return m_flush_before_close; +} + +int StreamSocket::GetConnectionRetry() +{ + return m_connection_retry; +} + +void StreamSocket::SetConnectionRetry(int x) +{ + m_connection_retry = x; +} + +int StreamSocket::GetConnectionRetries() +{ + return m_retries; +} + +void StreamSocket::IncreaseConnectionRetries() +{ + m_retries++; +} + +void StreamSocket::ResetConnectionRetries() +{ + m_retries = 0; +} + +void StreamSocket::SetCallOnConnect(bool x) +{ + Handler().AddList(GetSocket(), LIST_CALLONCONNECT, x); + m_call_on_connect = x; +} + +bool StreamSocket::CallOnConnect() +{ + return m_call_on_connect; +} + +void StreamSocket::SetRetryClientConnect(bool x) +{ + Handler().AddList(GetSocket(), LIST_RETRY, x); + m_b_retry_connect = x; +} + +bool StreamSocket::RetryClientConnect() +{ + return m_b_retry_connect; +} + +void StreamSocket::SetLineProtocol(bool x) +{ + m_line_protocol = x; +} + +bool StreamSocket::LineProtocol() +{ + return m_line_protocol; +} + +void StreamSocket::SetShutdown(int x) +{ + m_shutdown = x; +} + +int StreamSocket::GetShutdown() +{ + return m_shutdown; +} + + +#ifdef SOCKETS_NAMESPACE +} // namespace SOCKETS_NAMESPACE { +#endif + + diff --git a/dep/sockets/TcpSocket.cpp b/dep/sockets/TcpSocket.cpp new file mode 100644 index 00000000000..5f067b53124 --- /dev/null +++ b/dep/sockets/TcpSocket.cpp @@ -0,0 +1,1681 @@ +/** \file TcpSocket.cpp + ** \date 2004-02-13 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2004-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifdef _WIN32 +#ifdef _MSC_VER +#pragma warning(disable:4786) +#endif +#include +#else +#include +#endif +#include "ISocketHandler.h" +#include +#include +#include +#include +#ifdef HAVE_OPENSSL +#include +#include +#endif +#include +#include + +#include "TcpSocket.h" +#include "Utility.h" +#include "Ipv4Address.h" +#include "Ipv6Address.h" +#include "Mutex.h" +#include "IFile.h" + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +//#ifdef _DEBUG +//#define DEB(x) x +//#else +#define DEB(x) +//#endif + +// statics +#ifdef HAVE_OPENSSL +SSLInitializer TcpSocket::m_ssl_init; +#endif + +// thanks, q +#ifdef _MSC_VER +#pragma warning(disable:4355) +#endif +TcpSocket::TcpSocket(ISocketHandler& h) : StreamSocket(h) +,ibuf(TCP_BUFSIZE_READ) +,m_b_input_buffer_disabled(false) +,m_bytes_sent(0) +,m_bytes_received(0) +,m_skip_c(false) +#ifdef SOCKETS_DYNAMIC_TEMP +,m_buf(new char[TCP_BUFSIZE_READ + 1]) +#endif +,m_obuf_top(NULL) +,m_transfer_limit(0) +,m_output_length(0) +#ifdef HAVE_OPENSSL +,m_ssl_ctx(NULL) +,m_ssl(NULL) +,m_sbio(NULL) +#endif +#ifdef ENABLE_SOCKS4 +,m_socks4_state(0) +#endif +#ifdef ENABLE_RESOLVER +,m_resolver_id(0) +#endif +#ifdef ENABLE_RECONNECT +,m_b_reconnect(false) +,m_b_is_reconnect(false) +#endif +{ +} +#ifdef _MSC_VER +#pragma warning(default:4355) +#endif + +#ifdef _MSC_VER +#pragma warning(disable:4355) +#endif +TcpSocket::TcpSocket(ISocketHandler& h,size_t isize,size_t osize) : StreamSocket(h) +,ibuf(isize) +,m_b_input_buffer_disabled(false) +,m_bytes_sent(0) +,m_bytes_received(0) +,m_skip_c(false) +#ifdef SOCKETS_DYNAMIC_TEMP +,m_buf(new char[TCP_BUFSIZE_READ + 1]) +#endif +,m_obuf_top(NULL) +,m_transfer_limit(0) +,m_output_length(0) +#ifdef HAVE_OPENSSL +,m_ssl_ctx(NULL) +,m_ssl(NULL) +,m_sbio(NULL) +#endif +#ifdef ENABLE_SOCKS4 +,m_socks4_state(0) +#endif +#ifdef ENABLE_RESOLVER +,m_resolver_id(0) +#endif +#ifdef ENABLE_RECONNECT +,m_b_reconnect(false) +,m_b_is_reconnect(false) +#endif +{ +} +#ifdef _MSC_VER +#pragma warning(default:4355) +#endif + +TcpSocket::~TcpSocket() +{ +#ifdef SOCKETS_DYNAMIC_TEMP + delete[] m_buf; +#endif + // %! empty m_obuf + while (m_obuf.size()) + { + output_l::iterator it = m_obuf.begin(); + OUTPUT *p = *it; + delete p; + m_obuf.erase(it); + } +#ifdef HAVE_OPENSSL + if (m_ssl) + { + SSL_free(m_ssl); + } +#endif +} + +bool TcpSocket::Open(ipaddr_t ip,port_t port,bool skip_socks) +{ + Ipv4Address ad(ip, port); + Ipv4Address local; + return Open(ad, local, skip_socks); +} + +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 +bool TcpSocket::Open(in6_addr ip,port_t port,bool skip_socks) +{ + Ipv6Address ad(ip, port); + return Open(ad, skip_socks); +} +#endif +#endif + +bool TcpSocket::Open(SocketAddress& ad,bool skip_socks) +{ + Ipv4Address bind_ad("0.0.0.0", 0); + return Open(ad, bind_ad, skip_socks); +} + +bool TcpSocket::Open(SocketAddress& ad,SocketAddress& bind_ad,bool skip_socks) +{ + if (!ad.IsValid()) + { + Handler().LogError(this, "Open", 0, "Invalid SocketAddress", LOG_LEVEL_FATAL); + SetCloseAndDelete(); + return false; + } + if (Handler().GetCount() >= FD_SETSIZE) + { + Handler().LogError(this, "Open", 0, "no space left in fd_set", LOG_LEVEL_FATAL); + SetCloseAndDelete(); + return false; + } + SetConnecting(false); +#ifdef ENABLE_SOCKS4 + SetSocks4(false); +#endif + // check for pooling +#ifdef ENABLE_POOL + if (Handler().PoolEnabled()) + { + ISocketHandler::PoolSocket *pools = Handler().FindConnection(SOCK_STREAM, "tcp", ad); + if (pools) + { + CopyConnection( pools ); + delete pools; + + SetIsClient(); + SetCallOnConnect(); // ISocketHandler must call OnConnect + Handler().LogError(this, "SetCallOnConnect", 0, "Found pooled connection", LOG_LEVEL_INFO); + return true; + } + } +#endif + // if not, create new connection + SOCKET s = CreateSocket(ad.GetFamily(), SOCK_STREAM, "tcp"); + if (s == INVALID_SOCKET) + { + return false; + } + // socket must be nonblocking for async connect + if (!SetNonblocking(true, s)) + { + SetCloseAndDelete(); + closesocket(s); + return false; + } +#ifdef ENABLE_POOL + SetIsClient(); // client because we connect +#endif + SetClientRemoteAddress(ad); + int n = 0; + if (bind_ad.GetPort() != 0) + { + bind(s, bind_ad, bind_ad); + } +#ifdef ENABLE_SOCKS4 + if (!skip_socks && GetSocks4Host() && GetSocks4Port()) + { + Ipv4Address sa(GetSocks4Host(), GetSocks4Port()); + { + std::string sockshost; + Utility::l2ip(GetSocks4Host(), sockshost); + Handler().LogError(this, "Open", 0, "Connecting to socks4 server @ " + sockshost + ":" + + Utility::l2string(GetSocks4Port()), LOG_LEVEL_INFO); + } + SetSocks4(); + n = connect(s, sa, sa); + SetRemoteAddress(sa); + } + else +#endif + { + n = connect(s, ad, ad); + SetRemoteAddress(ad); + } + if (n == -1) + { + // check error code that means a connect is in progress +#ifdef _WIN32 + if (Errno == WSAEWOULDBLOCK) +#else + if (Errno == EINPROGRESS) +#endif + { + Attach(s); + SetConnecting( true ); // this flag will control fd_set's + } + else +#ifdef ENABLE_SOCKS4 + if (Socks4() && Handler().Socks4TryDirect() ) // retry + { + closesocket(s); + return Open(ad, true); + } + else +#endif +#ifdef ENABLE_RECONNECT + if (Reconnect()) + { + Handler().LogError(this, "connect: failed, reconnect pending", Errno, StrError(Errno), LOG_LEVEL_INFO); + Attach(s); + SetConnecting( true ); // this flag will control fd_set's + } + else +#endif + { + Handler().LogError(this, "connect: failed", Errno, StrError(Errno), LOG_LEVEL_FATAL); + SetCloseAndDelete(); + closesocket(s); + return false; + } + } + else + { + Attach(s); + SetCallOnConnect(); // ISocketHandler must call OnConnect + } + + // 'true' means connected or connecting(not yet connected) + // 'false' means something failed + return true; //!Connecting(); +} + +bool TcpSocket::Open(const std::string &host,port_t port) +{ +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + if (IsIpv6()) + { +#ifdef ENABLE_RESOLVER + if (!Handler().ResolverEnabled() || Utility::isipv6(host) ) + { +#endif + in6_addr a; + if (!Utility::u2ip(host, a)) + { + SetCloseAndDelete(); + return false; + } + Ipv6Address ad(a, port); + Ipv6Address local; + return Open(ad, local); +#ifdef ENABLE_RESOLVER + } + m_resolver_id = Resolve6(host, port); + return true; +#endif + } +#endif +#endif +#ifdef ENABLE_RESOLVER + if (!Handler().ResolverEnabled() || Utility::isipv4(host) ) + { +#endif + ipaddr_t l; + if (!Utility::u2ip(host,l)) + { + SetCloseAndDelete(); + return false; + } + Ipv4Address ad(l, port); + Ipv4Address local; + return Open(ad, local); +#ifdef ENABLE_RESOLVER + } + // resolve using async resolver thread + m_resolver_id = Resolve(host, port); + return true; +#endif +} + +#ifdef ENABLE_RESOLVER +void TcpSocket::OnResolved(int id,ipaddr_t a,port_t port) +{ +DEB( fprintf(stderr, "TcpSocket::OnResolved id %d addr %x port %d\n", id, a, port);) + if (id == m_resolver_id) + { + if (a && port) + { + Ipv4Address ad(a, port); + Ipv4Address local; + if (Open(ad, local)) + { + if (!Handler().Valid(this)) + { + Handler().Add(this); + } + } + } + else + { + Handler().LogError(this, "OnResolved", 0, "Resolver failed", LOG_LEVEL_FATAL); + SetCloseAndDelete(); + } + } + else + { + Handler().LogError(this, "OnResolved", id, "Resolver returned wrong job id", LOG_LEVEL_FATAL); + SetCloseAndDelete(); + } +} + +#ifdef ENABLE_IPV6 +void TcpSocket::OnResolved(int id,in6_addr& a,port_t port) +{ + if (id == m_resolver_id) + { + Ipv6Address ad(a, port); + if (ad.IsValid()) + { + Ipv6Address local; + if (Open(ad, local)) + { + if (!Handler().Valid(this)) + { + Handler().Add(this); + } + } + } + } + else + { + Handler().LogError(this, "OnResolved", id, "Resolver returned wrong job id", LOG_LEVEL_FATAL); + SetCloseAndDelete(); + } +} +#endif +#endif + +void TcpSocket::OnRead() +{ + int n = 0; +#ifdef SOCKETS_DYNAMIC_TEMP + char *buf = m_buf; +#else + char buf[TCP_BUFSIZE_READ]; +#endif +#ifdef HAVE_OPENSSL + if (IsSSL()) + { + if (!Ready()) + return; + n = SSL_read(m_ssl, buf, TCP_BUFSIZE_READ); + if (n == -1) + { + n = SSL_get_error(m_ssl, n); + switch (n) + { + case SSL_ERROR_NONE: + case SSL_ERROR_WANT_READ: + case SSL_ERROR_WANT_WRITE: + break; + case SSL_ERROR_ZERO_RETURN: +DEB( fprintf(stderr, "SSL_read() returns zero - closing socket\n");) + OnDisconnect(); + SetCloseAndDelete(true); + SetFlushBeforeClose(false); + SetLost(); + break; + default: +DEB( fprintf(stderr, "SSL read problem, errcode = %d\n",n);) + OnDisconnect(); + SetCloseAndDelete(true); + SetFlushBeforeClose(false); + SetLost(); + } + return; + } + else + if (!n) + { + OnDisconnect(); + SetCloseAndDelete(true); + SetFlushBeforeClose(false); + SetLost(); + SetShutdown(SHUT_WR); + return; + } + else + if (n > 0 && n <= TCP_BUFSIZE_READ) + { + m_bytes_received += n; + if (GetTrafficMonitor()) + { + GetTrafficMonitor() -> fwrite(buf, 1, n); + } + if (!m_b_input_buffer_disabled && !ibuf.Write(buf,n)) + { + Handler().LogError(this, "OnRead(ssl)", 0, "ibuf overflow", LOG_LEVEL_WARNING); + } + } + else + { + Handler().LogError(this, "OnRead(ssl)", n, "abnormal value from SSL_read", LOG_LEVEL_ERROR); + } + } + else +#endif // HAVE_OPENSSL + { + n = recv(GetSocket(), buf, TCP_BUFSIZE_READ, MSG_NOSIGNAL); + if (n == -1) + { + Handler().LogError(this, "read", Errno, StrError(Errno), LOG_LEVEL_FATAL); + OnDisconnect(); + SetCloseAndDelete(true); + SetFlushBeforeClose(false); + SetLost(); + return; + } + else + if (!n) + { + OnDisconnect(); + SetCloseAndDelete(true); + SetFlushBeforeClose(false); + SetLost(); + SetShutdown(SHUT_WR); + return; + } + else + if (n > 0 && n <= TCP_BUFSIZE_READ) + { + m_bytes_received += n; + if (GetTrafficMonitor()) + { + GetTrafficMonitor() -> fwrite(buf, 1, n); + } + if (!m_b_input_buffer_disabled && !ibuf.Write(buf,n)) + { + Handler().LogError(this, "OnRead", 0, "ibuf overflow", LOG_LEVEL_WARNING); + } + } + else + { + Handler().LogError(this, "OnRead", n, "abnormal value from recv", LOG_LEVEL_ERROR); + } + } + // + OnRead( buf, n ); +} + +void TcpSocket::OnRead( char *buf, size_t n ) +{ + // unbuffered + if (n > 0 && n <= TCP_BUFSIZE_READ) + { + if (LineProtocol()) + { + buf[n] = 0; + size_t i = 0; + if (m_skip_c && (buf[i] == 13 || buf[i] == 10) && buf[i] != m_c) + { + m_skip_c = false; + i++; + } + size_t x = i; + for (; i < n && LineProtocol(); i++) + { + while ((buf[i] == 13 || buf[i] == 10) && LineProtocol()) + { + char c = buf[i]; + buf[i] = 0; + if (buf[x]) + { + m_line += (buf + x); + } + OnLine( m_line ); + i++; + m_skip_c = true; + m_c = c; + if (i < n && (buf[i] == 13 || buf[i] == 10) && buf[i] != c) + { + m_skip_c = false; + i++; + } + x = i; + m_line = ""; + } + if (!LineProtocol()) + { + break; + } + } + if (!LineProtocol()) + { + if (i < n) + { + OnRawData(buf + i, n - i); + } + } + else + if (buf[x]) + { + m_line += (buf + x); + } + } + else + { + OnRawData(buf, n); + } + } + if (m_b_input_buffer_disabled) + { + return; + } + // further processing: socks4 +#ifdef ENABLE_SOCKS4 + if (Socks4()) + { + bool need_more = false; + while (GetInputLength() && !need_more && !CloseAndDelete()) + { + need_more = OnSocks4Read(); + } + } +#endif +} + +void TcpSocket::OnWriteComplete() +{ +} + +void TcpSocket::OnWrite() +{ + if (Connecting()) + { + int err = SoError(); + + // don't reset connecting flag on error here, we want the OnConnectFailed timeout later on + if (!err) // ok + { + Set(!IsDisableRead(), false); + SetConnecting(false); + SetCallOnConnect(); + return; + } + Handler().LogError(this, "tcp: connect failed", err, StrError(err), LOG_LEVEL_FATAL); + Set(false, false); // no more monitoring because connection failed + + // failed +#ifdef ENABLE_SOCKS4 + if (Socks4()) + { + // %! leave 'Connecting' flag set? + OnSocks4ConnectFailed(); + return; + } +#endif + if (GetConnectionRetry() == -1 || + (GetConnectionRetry() && GetConnectionRetries() < GetConnectionRetry()) ) + { + // even though the connection failed at once, only retry after + // the connection timeout. + // should we even try to connect again, when CheckConnect returns + // false it's because of a connection error - not a timeout... + return; + } + SetConnecting(false); + SetCloseAndDelete( true ); + /// \todo state reason why connect failed + OnConnectFailed(); + return; + } + // try send next block in buffer + // if full block is sent, repeat + // if all blocks are sent, reset m_wfds + + bool repeat = false; + size_t sz = m_transfer_limit ? GetOutputLength() : 0; + do + { + output_l::iterator it = m_obuf.begin(); + OUTPUT *p = *it; + repeat = false; + int n = TryWrite(p -> Buf(), p -> Len()); + if (n > 0) + { + size_t left = p -> Remove(n); + m_output_length -= n; + if (!left) + { + delete p; + m_obuf.erase(it); + if (!m_obuf.size()) + { + m_obuf_top = NULL; + OnWriteComplete(); + } + else + { + repeat = true; + } + } + } + } while (repeat); + + if (m_transfer_limit && sz > m_transfer_limit && GetOutputLength() < m_transfer_limit) + { + OnTransferLimit(); + } + + // check output buffer set, set/reset m_wfds accordingly + { + bool br; + bool bw; + bool bx; + Handler().Get(GetSocket(), br, bw, bx); + if (m_obuf.size()) + Set(br, true); + else + Set(br, false); + } +} + +int TcpSocket::TryWrite(const char *buf, size_t len) +{ + int n = 0; +#ifdef HAVE_OPENSSL + if (IsSSL()) + { + n = SSL_write(m_ssl, buf, (int)len); + if (n == -1) + { + int errnr = SSL_get_error(m_ssl, n); + if ( errnr != SSL_ERROR_WANT_READ && errnr != SSL_ERROR_WANT_WRITE ) + { + OnDisconnect(); + SetCloseAndDelete(true); + SetFlushBeforeClose(false); + SetLost(); + const char *errbuf = ERR_error_string(errnr, NULL); + Handler().LogError(this, "OnWrite/SSL_write", errnr, errbuf, LOG_LEVEL_FATAL); + } + return 0; + } + else + if (!n) + { + OnDisconnect(); + SetCloseAndDelete(true); + SetFlushBeforeClose(false); + SetLost(); +DEB( int errnr = SSL_get_error(m_ssl, n); + const char *errbuf = ERR_error_string(errnr, NULL); + fprintf(stderr, "SSL_write() returns 0: %d : %s\n",errnr, errbuf);) + } + } + else +#endif // HAVE_OPENSSL + { + n = send(GetSocket(), buf, (int)len, MSG_NOSIGNAL); + if (n == -1) + { + // normal error codes: + // WSAEWOULDBLOCK + // EAGAIN or EWOULDBLOCK +#ifdef _WIN32 + if (Errno != WSAEWOULDBLOCK) +#else + if (Errno != EWOULDBLOCK) +#endif + { + Handler().LogError(this, "send", Errno, StrError(Errno), LOG_LEVEL_FATAL); + OnDisconnect(); + SetCloseAndDelete(true); + SetFlushBeforeClose(false); + SetLost(); + } + return 0; + } + } + if (n > 0) + { + m_bytes_sent += n; + if (GetTrafficMonitor()) + { + GetTrafficMonitor() -> fwrite(buf, 1, n); + } + } + return n; +} + +void TcpSocket::Buffer(const char *buf, size_t len) +{ + size_t ptr = 0; + m_output_length += len; + while (ptr < len) + { + // buf/len => pbuf/sz + size_t space = 0; + if (m_obuf_top && (space = m_obuf_top -> Space()) > 0) + { + const char *pbuf = buf + ptr; + size_t sz = len - ptr; + if (space >= sz) + { + m_obuf_top -> Add(pbuf, sz); + ptr += sz; + } + else + { + m_obuf_top -> Add(pbuf, space); + ptr += space; + } + } + else + { + m_obuf_top = new OUTPUT; + m_obuf.push_back( m_obuf_top ); + } + } +} + +void TcpSocket::Send(const std::string &str,int i) +{ + SendBuf(str.c_str(),str.size(),i); +} + +void TcpSocket::SendBuf(const char *buf,size_t len,int) +{ + if (!Ready() && !Connecting()) + { + Handler().LogError(this, "SendBuf", -1, "Attempt to write to a non-ready socket" ); // warning + if (GetSocket() == INVALID_SOCKET) + Handler().LogError(this, "SendBuf", 0, " * GetSocket() == INVALID_SOCKET", LOG_LEVEL_INFO); + if (Connecting()) + Handler().LogError(this, "SendBuf", 0, " * Connecting()", LOG_LEVEL_INFO); + if (CloseAndDelete()) + Handler().LogError(this, "SendBuf", 0, " * CloseAndDelete()", LOG_LEVEL_INFO); + return; + } + if (!IsConnected()) + { + Handler().LogError(this, "SendBuf", -1, "Attempt to write to a non-connected socket, will be sent on connect" ); // warning + Buffer(buf, len); + return; + } + if (m_obuf_top) + { + Buffer(buf, len); + return; + } + int n = TryWrite(buf, len); + if (n >= 0 && n < (int)len) + { + Buffer(buf + n, len - n); + } + // if ( data in buffer || !IsConnected ) + // { + // add to buffer + // } + // else + // try_send + // if any data is unsent, buffer it and set m_wfds + + // check output buffer set, set/reset m_wfds accordingly + { + bool br; + bool bw; + bool bx; + Handler().Get(GetSocket(), br, bw, bx); + if (m_obuf.size()) + Set(br, true); + else + Set(br, false); + } +} + +void TcpSocket::OnLine(const std::string& ) +{ +} + +#ifdef _MSC_VER +#pragma warning(disable:4355) +#endif +TcpSocket::TcpSocket(const TcpSocket& s) +:StreamSocket(s) +,ibuf(0) +{ +} +#ifdef _MSC_VER +#pragma warning(default:4355) +#endif + +#ifdef ENABLE_SOCKS4 +void TcpSocket::OnSocks4Connect() +{ + char request[1000]; + memset(request, 0, sizeof(request)); + request[0] = 4; // socks v4 + request[1] = 1; // command code: CONNECT + { + std::auto_ptr ad = GetClientRemoteAddress(); + if (ad.get()) + { + struct sockaddr *p0 = (struct sockaddr *)*ad; + struct sockaddr_in *p = (struct sockaddr_in *)p0; + if (p -> sin_family == AF_INET) + { + memcpy(request + 2, &p -> sin_port, 2); // nwbo is ok here + memcpy(request + 4, &p -> sin_addr, sizeof(struct in_addr)); + } + else + { + /// \todo warn + } + } + else + { + /// \todo warn + } + } + strcpy(request + 8, GetSocks4Userid().c_str()); + size_t length = GetSocks4Userid().size() + 8 + 1; + SendBuf(request, length); + m_socks4_state = 0; +} + +void TcpSocket::OnSocks4ConnectFailed() +{ + Handler().LogError(this,"OnSocks4ConnectFailed",0,"connection to socks4 server failed, trying direct connection",LOG_LEVEL_WARNING); + if (!Handler().Socks4TryDirect()) + { + SetConnecting(false); + SetCloseAndDelete(); + OnConnectFailed(); // just in case + } + else + { + SetRetryClientConnect(); + } +} + +bool TcpSocket::OnSocks4Read() +{ + switch (m_socks4_state) + { + case 0: + ibuf.Read(&m_socks4_vn, 1); + m_socks4_state = 1; + break; + case 1: + ibuf.Read(&m_socks4_cd, 1); + m_socks4_state = 2; + break; + case 2: + if (GetInputLength() > 1) + { + ibuf.Read( (char *)&m_socks4_dstport, 2); + m_socks4_state = 3; + } + else + { + return true; + } + break; + case 3: + if (GetInputLength() > 3) + { + ibuf.Read( (char *)&m_socks4_dstip, 4); + SetSocks4(false); + + switch (m_socks4_cd) + { + case 90: + OnConnect(); + Handler().LogError(this, "OnSocks4Read", 0, "Connection established", LOG_LEVEL_INFO); + break; + case 91: + case 92: + case 93: + Handler().LogError(this,"OnSocks4Read",m_socks4_cd,"socks4 server reports connect failed",LOG_LEVEL_FATAL); + SetConnecting(false); + SetCloseAndDelete(); + OnConnectFailed(); + break; + default: + Handler().LogError(this,"OnSocks4Read",m_socks4_cd,"socks4 server unrecognized response",LOG_LEVEL_FATAL); + SetCloseAndDelete(); + break; + } + } + else + { + return true; + } + break; + } + return false; +} +#endif + +void TcpSocket::Sendf(const char *format, ...) +{ + va_list ap; + va_start(ap, format); + char slask[5000]; // vsprintf / vsnprintf temporary +#ifdef _WIN32 + vsprintf(slask, format, ap); +#else + vsnprintf(slask, 5000, format, ap); +#endif + va_end(ap); + Send( slask ); +} + +#ifdef HAVE_OPENSSL +void TcpSocket::OnSSLConnect() +{ + SetNonblocking(true); + { + if (m_ssl_ctx) + { +DEB( fprintf(stderr, "SSL Context already initialized - closing socket\n");) + SetCloseAndDelete(true); + return; + } + InitSSLClient(); + } + if (m_ssl_ctx) + { + /* Connect the SSL socket */ + m_ssl = SSL_new(m_ssl_ctx); + if (!m_ssl) + { +DEB( fprintf(stderr, " m_ssl is NULL\n");) + SetCloseAndDelete(true); + return; + } + SSL_set_mode(m_ssl, SSL_MODE_AUTO_RETRY); + m_sbio = BIO_new_socket((int)GetSocket(), BIO_NOCLOSE); + if (!m_sbio) + { +DEB( fprintf(stderr, " m_sbio is NULL\n");) + SetCloseAndDelete(true); + return; + } + SSL_set_bio(m_ssl, m_sbio, m_sbio); + if (!SSLNegotiate()) + { + SetSSLNegotiate(); + } + } + else + { + SetCloseAndDelete(); + } +} + +void TcpSocket::OnSSLAccept() +{ + SetNonblocking(true); + { + if (m_ssl_ctx) + { +DEB( fprintf(stderr, "SSL Context already initialized - closing socket\n");) + SetCloseAndDelete(true); + return; + } + InitSSLServer(); + SetSSLServer(); + } + if (m_ssl_ctx) + { + m_ssl = SSL_new(m_ssl_ctx); + if (!m_ssl) + { +DEB( fprintf(stderr, " m_ssl is NULL\n");) + SetCloseAndDelete(true); + return; + } + SSL_set_mode(m_ssl, SSL_MODE_AUTO_RETRY); + m_sbio = BIO_new_socket((int)GetSocket(), BIO_NOCLOSE); + if (!m_sbio) + { +DEB( fprintf(stderr, " m_sbio is NULL\n");) + SetCloseAndDelete(true); + return; + } + SSL_set_bio(m_ssl, m_sbio, m_sbio); +// if (!SSLNegotiate()) + { + SetSSLNegotiate(); + } + } +} + +bool TcpSocket::SSLNegotiate() +{ + if (!IsSSLServer()) // client + { + int r = SSL_connect(m_ssl); + if (r > 0) + { + SetSSLNegotiate(false); + /// \todo: resurrect certificate check... client +// CheckCertificateChain( "");//ServerHOST); + SetNonblocking(false); + // + { + SetConnected(); + if (GetOutputLength()) + { + OnWrite(); + } + } +#ifdef ENABLE_RECONNECT + if (IsReconnect()) + OnReconnect(); + else +#endif + { + OnConnect(); + } + Handler().LogError(this, "SSLNegotiate/SSL_connect", 0, "Connection established", LOG_LEVEL_INFO); + return true; + } + else + if (!r) + { + Handler().LogError(this, "SSLNegotiate/SSL_connect", 0, "Connection failed", LOG_LEVEL_INFO); + SetSSLNegotiate(false); + SetCloseAndDelete(); + OnSSLConnectFailed(); + } + else + { + r = SSL_get_error(m_ssl, r); + if (r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE) + { + Handler().LogError(this, "SSLNegotiate/SSL_connect", -1, "Connection failed", LOG_LEVEL_INFO); +DEB( fprintf(stderr, "SSL_connect() failed - closing socket, return code: %d\n",r);) + SetSSLNegotiate(false); + SetCloseAndDelete(true); + OnSSLConnectFailed(); + } + } + } + else // server + { + int r = SSL_accept(m_ssl); + if (r > 0) + { + SetSSLNegotiate(false); + /// \todo: resurrect certificate check... server +// CheckCertificateChain( "");//ClientHOST); + SetNonblocking(false); + // + { + SetConnected(); + if (GetOutputLength()) + { + OnWrite(); + } + } + OnAccept(); + Handler().LogError(this, "SSLNegotiate/SSL_accept", 0, "Connection established", LOG_LEVEL_INFO); + return true; + } + else + if (!r) + { + Handler().LogError(this, "SSLNegotiate/SSL_accept", 0, "Connection failed", LOG_LEVEL_INFO); + SetSSLNegotiate(false); + SetCloseAndDelete(); + OnSSLAcceptFailed(); + } + else + { + r = SSL_get_error(m_ssl, r); + if (r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE) + { + Handler().LogError(this, "SSLNegotiate/SSL_accept", -1, "Connection failed", LOG_LEVEL_INFO); +DEB( fprintf(stderr, "SSL_accept() failed - closing socket, return code: %d\n",r);) + SetSSLNegotiate(false); + SetCloseAndDelete(true); + OnSSLAcceptFailed(); + } + } + } + return false; +} + +void TcpSocket::InitSSLClient() +{ + InitializeContext("", SSLv23_method()); +} + +void TcpSocket::InitSSLServer() +{ + Handler().LogError(this, "InitSSLServer", 0, "You MUST implement your own InitSSLServer method", LOG_LEVEL_FATAL); + SetCloseAndDelete(); +} + +void TcpSocket::InitializeContext(const std::string& context, SSL_METHOD *meth_in) +{ + /* Create our context*/ + static std::map client_contexts; + if (client_contexts.find(context) == client_contexts.end()) + { + SSL_METHOD *meth = meth_in ? meth_in : SSLv3_method(); + m_ssl_ctx = client_contexts[context] = SSL_CTX_new(meth); + SSL_CTX_set_mode(m_ssl_ctx, SSL_MODE_AUTO_RETRY); + } + else + { + m_ssl_ctx = client_contexts[context]; + } +} + +void TcpSocket::InitializeContext(const std::string& context,const std::string& keyfile,const std::string& password,SSL_METHOD *meth_in) +{ + /* Create our context*/ + static std::map server_contexts; + if (server_contexts.find(context) == server_contexts.end()) + { + SSL_METHOD *meth = meth_in ? meth_in : SSLv3_method(); + m_ssl_ctx = server_contexts[context] = SSL_CTX_new(meth); + SSL_CTX_set_mode(m_ssl_ctx, SSL_MODE_AUTO_RETRY); + // session id + if (!context.empty()) + SSL_CTX_set_session_id_context(m_ssl_ctx, (const unsigned char *)context.c_str(), (unsigned int)context.size()); + else + SSL_CTX_set_session_id_context(m_ssl_ctx, (const unsigned char *)"--empty--", 9); + } + else + { + m_ssl_ctx = server_contexts[context]; + } + + /* Load our keys and certificates*/ + if (!(SSL_CTX_use_certificate_file(m_ssl_ctx, keyfile.c_str(), SSL_FILETYPE_PEM))) + { + Handler().LogError(this, "TcpSocket InitializeContext", 0, "Couldn't read certificate file " + keyfile, LOG_LEVEL_FATAL); + } + + m_password = password; + SSL_CTX_set_default_passwd_cb(m_ssl_ctx, SSL_password_cb); + SSL_CTX_set_default_passwd_cb_userdata(m_ssl_ctx, this); + if (!(SSL_CTX_use_PrivateKey_file(m_ssl_ctx, keyfile.c_str(), SSL_FILETYPE_PEM))) + { + Handler().LogError(this, "TcpSocket InitializeContext", 0, "Couldn't read private key file " + keyfile, LOG_LEVEL_FATAL); + } +} + +void TcpSocket::InitializeContext(const std::string& context,const std::string& certfile,const std::string& keyfile,const std::string& password,SSL_METHOD *meth_in) +{ + /* Create our context*/ + static std::map server_contexts; + if (server_contexts.find(context) == server_contexts.end()) + { + SSL_METHOD *meth = meth_in ? meth_in : SSLv3_method(); + m_ssl_ctx = server_contexts[context] = SSL_CTX_new(meth); + SSL_CTX_set_mode(m_ssl_ctx, SSL_MODE_AUTO_RETRY); + // session id + if (context.size()) + SSL_CTX_set_session_id_context(m_ssl_ctx, (const unsigned char *)context.c_str(), (unsigned int)context.size()); + else + SSL_CTX_set_session_id_context(m_ssl_ctx, (const unsigned char *)"--empty--", 9); + } + else + { + m_ssl_ctx = server_contexts[context]; + } + + /* Load our keys and certificates*/ + if (!(SSL_CTX_use_certificate_file(m_ssl_ctx, certfile.c_str(), SSL_FILETYPE_PEM))) + { + Handler().LogError(this, "TcpSocket InitializeContext", 0, "Couldn't read certificate file " + keyfile, LOG_LEVEL_FATAL); + } + + m_password = password; + SSL_CTX_set_default_passwd_cb(m_ssl_ctx, SSL_password_cb); + SSL_CTX_set_default_passwd_cb_userdata(m_ssl_ctx, this); + if (!(SSL_CTX_use_PrivateKey_file(m_ssl_ctx, keyfile.c_str(), SSL_FILETYPE_PEM))) + { + Handler().LogError(this, "TcpSocket InitializeContext", 0, "Couldn't read private key file " + keyfile, LOG_LEVEL_FATAL); + } +} + +int TcpSocket::SSL_password_cb(char *buf,int num,int rwflag,void *userdata) +{ + Socket *p0 = static_cast(userdata); + TcpSocket *p = dynamic_cast(p0); + std::string pw = p ? p -> GetPassword() : ""; + if ( (size_t)num < pw.size() + 1) + { + return 0; + } + strcpy(buf,pw.c_str()); + return (int)pw.size(); +} +#endif // HAVE_OPENSSL + +int TcpSocket::Close() +{ + if (GetSocket() == INVALID_SOCKET) // this could happen + { + Handler().LogError(this, "Socket::Close", 0, "file descriptor invalid", LOG_LEVEL_WARNING); + return 0; + } + int n; + SetNonblocking(true); + if (!Lost() && IsConnected() && !(GetShutdown() & SHUT_WR)) + { + if (shutdown(GetSocket(), SHUT_WR) == -1) + { + // failed... + Handler().LogError(this, "shutdown", Errno, StrError(Errno), LOG_LEVEL_ERROR); + } + } + // + char tmp[1000]; + if (!Lost() && (n = recv(GetSocket(),tmp,1000,0)) >= 0) + { + if (n) + { + Handler().LogError(this, "read() after shutdown", n, "bytes read", LOG_LEVEL_WARNING); + } + } +#ifdef HAVE_OPENSSL + if (IsSSL() && m_ssl) + SSL_shutdown(m_ssl); + if (m_ssl) + { + SSL_free(m_ssl); + m_ssl = NULL; + } +#endif + return Socket::Close(); +} + +#ifdef HAVE_OPENSSL +SSL_CTX *TcpSocket::GetSslContext() +{ + if (!m_ssl_ctx) + Handler().LogError(this, "GetSslContext", 0, "SSL Context is NULL; check InitSSLServer/InitSSLClient", LOG_LEVEL_WARNING); + return m_ssl_ctx; +} + +SSL *TcpSocket::GetSsl() +{ + if (!m_ssl) + Handler().LogError(this, "GetSsl", 0, "SSL is NULL; check InitSSLServer/InitSSLClient", LOG_LEVEL_WARNING); + return m_ssl; +} +#endif + +#ifdef ENABLE_RECONNECT +void TcpSocket::SetReconnect(bool x) +{ + m_b_reconnect = x; +} +#endif + +void TcpSocket::OnRawData(const char *buf_in,size_t len) +{ +} + +size_t TcpSocket::GetInputLength() +{ + return ibuf.GetLength(); +} + +size_t TcpSocket::GetOutputLength() +{ + return m_output_length; +} + +uint64_t TcpSocket::GetBytesReceived(bool clear) +{ + uint64_t z = m_bytes_received; + if (clear) + m_bytes_received = 0; + return z; +} + +uint64_t TcpSocket::GetBytesSent(bool clear) +{ + uint64_t z = m_bytes_sent; + if (clear) + m_bytes_sent = 0; + return z; +} + +#ifdef ENABLE_RECONNECT +bool TcpSocket::Reconnect() +{ + return m_b_reconnect; +} + +void TcpSocket::SetIsReconnect(bool x) +{ + m_b_is_reconnect = x; +} + +bool TcpSocket::IsReconnect() +{ + return m_b_is_reconnect; +} +#endif + +#ifdef HAVE_OPENSSL +const std::string& TcpSocket::GetPassword() +{ + return m_password; +} +#endif + +void TcpSocket::DisableInputBuffer(bool x) +{ + m_b_input_buffer_disabled = x; +} + +void TcpSocket::OnOptions(int family,int type,int protocol,SOCKET s) +{ +DEB( fprintf(stderr, "Socket::OnOptions()\n");) +#ifdef SO_NOSIGPIPE + SetSoNosigpipe(true); +#endif + SetSoReuseaddr(true); + SetSoKeepalive(true); +} + +void TcpSocket::SetLineProtocol(bool x) +{ + StreamSocket::SetLineProtocol(x); + DisableInputBuffer(x); +} + +bool TcpSocket::SetTcpNodelay(bool x) +{ +#ifdef TCP_NODELAY + int optval = x ? 1 : 0; + if (setsockopt(GetSocket(), IPPROTO_TCP, TCP_NODELAY, (char *)&optval, sizeof(optval)) == -1) + { + Handler().LogError(this, "setsockopt(IPPROTO_TCP, TCP_NODELAY)", Errno, StrError(Errno), LOG_LEVEL_FATAL); + return false; + } + return true; +#else + Handler().LogError(this, "socket option not available", 0, "TCP_NODELAY", LOG_LEVEL_INFO); + return false; +#endif +} + +TcpSocket::CircularBuffer::CircularBuffer(size_t size) +:buf(new char[2 * size]) +,m_max(size) +,m_q(0) +,m_b(0) +,m_t(0) +,m_count(0) +{ +} + +TcpSocket::CircularBuffer::~CircularBuffer() +{ + delete[] buf; +} + +bool TcpSocket::CircularBuffer::Write(const char *s,size_t l) +{ + if (m_q + l > m_max) + { + return false; // overflow + } + m_count += (unsigned long)l; + if (m_t + l > m_max) // block crosses circular border + { + size_t l1 = m_max - m_t; // size left until circular border crossing + // always copy full block to buffer(buf) + top pointer(m_t) + // because we have doubled the buffer size for performance reasons + memcpy(buf + m_t, s, l); + memcpy(buf, s + l1, l - l1); + m_t = l - l1; + m_q += l; + } + else + { + memcpy(buf + m_t, s, l); + memcpy(buf + m_max + m_t, s, l); + m_t += l; + if (m_t >= m_max) + m_t -= m_max; + m_q += l; + } + return true; +} + +bool TcpSocket::CircularBuffer::Read(char *s,size_t l) +{ + if (l > m_q) + { + return false; // not enough chars + } + if (m_b + l > m_max) // block crosses circular border + { + size_t l1 = m_max - m_b; + if (s) + { + memcpy(s, buf + m_b, l1); + memcpy(s + l1, buf, l - l1); + } + m_b = l - l1; + m_q -= l; + } + else + { + if (s) + { + memcpy(s, buf + m_b, l); + } + m_b += l; + if (m_b >= m_max) + m_b -= m_max; + m_q -= l; + } + if (!m_q) + { + m_b = m_t = 0; + } + return true; +} + +bool TcpSocket::CircularBuffer::SoftRead(char *s, size_t l) +{ + if (l > m_q) + { + return false; + } + if (m_b + l > m_max) // block crosses circular border + { + size_t l1 = m_max - m_b; + if (s) + { + memcpy(s, buf + m_b, l1); + memcpy(s + l1, buf, l - l1); + } + } + else + { + if (s) + { + memcpy(s, buf + m_b, l); + } + } + return true; +} + +bool TcpSocket::CircularBuffer::Remove(size_t l) +{ + return Read(NULL, l); +} + +size_t TcpSocket::CircularBuffer::GetLength() +{ + return m_q; +} + +const char *TcpSocket::CircularBuffer::GetStart() +{ + return buf + m_b; +} + +size_t TcpSocket::CircularBuffer::GetL() +{ + return (m_b + m_q > m_max) ? m_max - m_b : m_q; +} + +size_t TcpSocket::CircularBuffer::Space() +{ + return m_max - m_q; +} + +unsigned long TcpSocket::CircularBuffer::ByteCounter(bool clear) +{ + if (clear) + { + unsigned long x = m_count; + m_count = 0; + return x; + } + return m_count; +} + +std::string TcpSocket::CircularBuffer::ReadString(size_t l) +{ + char *sz = new char[l + 1]; + if (!Read(sz, l)) // failed, debug printout in Read() method + { + delete[] sz; + return ""; + } + sz[l] = 0; + std::string tmp = sz; + delete[] sz; + return tmp; +} + +void TcpSocket::OnConnectTimeout() +{ + Handler().LogError(this, "connect", -1, "connect timeout", LOG_LEVEL_FATAL); +#ifdef ENABLE_SOCKS4 + if (Socks4()) + { + OnSocks4ConnectFailed(); + // retry direct connection + } + else +#endif + if (GetConnectionRetry() == -1 || + (GetConnectionRetry() && GetConnectionRetries() < GetConnectionRetry()) ) + { + IncreaseConnectionRetries(); + // ask socket via OnConnectRetry callback if we should continue trying + if (OnConnectRetry()) + { + SetRetryClientConnect(); + } + else + { + SetCloseAndDelete( true ); + /// \todo state reason why connect failed + OnConnectFailed(); + } + } + else + { + SetCloseAndDelete(true); + /// \todo state reason why connect failed + OnConnectFailed(); + } + // + SetConnecting(false); +} + +#ifdef _WIN32 +void TcpSocket::OnException() +{ + if (Connecting()) + { +#ifdef ENABLE_SOCKS4 + if (Socks4()) + OnSocks4ConnectFailed(); + else +#endif + if (GetConnectionRetry() == -1 || + (GetConnectionRetry() && + GetConnectionRetries() < GetConnectionRetry() )) + { + // even though the connection failed at once, only retry after + // the connection timeout + // should we even try to connect again, when CheckConnect returns + // false it's because of a connection error - not a timeout... + } + else + { + SetConnecting(false); // tnx snibbe + SetCloseAndDelete(); + OnConnectFailed(); + } + return; + } + // %! exception doesn't always mean something bad happened, this code should be reworked + // errno valid here? + int err = SoError(); + Handler().LogError(this, "exception on select", err, StrError(err), LOG_LEVEL_FATAL); + SetCloseAndDelete(); +} +#endif // _WIN32 + +int TcpSocket::Protocol() +{ + return IPPROTO_TCP; +} + +void TcpSocket::SetTransferLimit(size_t sz) +{ + m_transfer_limit = sz; +} + +void TcpSocket::OnTransferLimit() +{ +} + +#ifdef SOCKETS_NAMESPACE +} +#endif + + diff --git a/dep/sockets/Thread.cpp b/dep/sockets/Thread.cpp new file mode 100644 index 00000000000..773e9f214fa --- /dev/null +++ b/dep/sockets/Thread.cpp @@ -0,0 +1,154 @@ +/** \file Thread.cpp + ** \date 2004-10-30 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2004-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#include +#ifdef _WIN32 +#include +#include "socket_include.h" +#else +#include +#endif + +#include "Thread.h" + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +Thread::Thread(bool release) +:m_thread(0) +,m_running(true) +,m_release(false) +,m_b_delete_on_exit(false) +,m_b_destructor(false) +{ +#ifdef _WIN32 +// m_thread = ::CreateThread(NULL, 0, StartThread, this, 0, &m_dwThreadId); + m_thread = (HANDLE)_beginthreadex(NULL, 0, &StartThread, this, 0, &m_dwThreadId); +#else + pthread_attr_t attr; + + pthread_attr_init(&attr); + pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); + if (pthread_create(&m_thread,&attr, StartThread,this) == -1) + { + perror("Thread: create failed"); + SetRunning(false); + } +// pthread_attr_destroy(&attr); +#endif + m_release = release; +} + +Thread::~Thread() +{ + m_b_destructor = true; + if (m_running) + { + SetRelease(true); + SetRunning(false); +#ifdef _WIN32 + Sleep(1000); +#else + sleep(1); +#endif + } +#ifdef _WIN32 + if (m_thread) + ::CloseHandle(m_thread); +#endif +} + +threadfunc_t STDPREFIX Thread::StartThread(threadparam_t zz) +{ + Thread *p = (Thread *)zz; + + while (p -> m_running && !p -> m_release) + { +#ifdef _WIN32 + Sleep(1000); +#else + sleep(1); +#endif + } + if (p -> m_running) + { + p -> Run(); + } + p -> SetRunning(false); // if return + if (p -> DeleteOnExit() && !p -> IsDestructor()) + { + delete p; + } +#ifdef _WIN32 + _endthreadex(0); +#endif + return (threadfunc_t)NULL; +} + +bool Thread::IsRunning() +{ + return m_running; +} + +void Thread::SetRunning(bool x) +{ + m_running = x; +} + +bool Thread::IsReleased() +{ + return m_release; +} + +void Thread::SetRelease(bool x) +{ + m_release = x; +} + +bool Thread::DeleteOnExit() +{ + return m_b_delete_on_exit; +} + +void Thread::SetDeleteOnExit(bool x) +{ + m_b_delete_on_exit = x; +} + +bool Thread::IsDestructor() +{ + return m_b_destructor; +} + +#ifdef SOCKETS_NAMESPACE +} +#endif + + diff --git a/dep/sockets/UdpSocket.cpp b/dep/sockets/UdpSocket.cpp new file mode 100644 index 00000000000..a3d393c00e2 --- /dev/null +++ b/dep/sockets/UdpSocket.cpp @@ -0,0 +1,810 @@ +/** \file UdpSocket.cpp + ** \date 2004-02-13 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2004-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifdef _WIN32 +#ifdef _MSC_VER +#pragma warning(disable:4786) +#endif +#include +#else +#include +#endif + +#include "ISocketHandler.h" +#include "UdpSocket.h" +#include "Utility.h" +#include "Ipv4Address.h" +#include "Ipv6Address.h" +#ifdef ENABLE_EXCEPTIONS +#include "Exception.h" +#endif +// include this to see strange sights +//#include + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +UdpSocket::UdpSocket(ISocketHandler& h, int ibufsz, bool ipv6, int retries) : Socket(h) +, m_ibuf(new char[ibufsz]) +, m_ibufsz(ibufsz) +, m_bind_ok(false) +, m_port(0) +, m_last_size_written(-1) +, m_retries(retries) +, m_b_read_ts(false) +{ +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + SetIpv6(ipv6); +#endif +#endif +} + +UdpSocket::~UdpSocket() +{ + Close(); + delete[] m_ibuf; +} + +int UdpSocket::Bind(port_t &port, int range) +{ +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + if (IsIpv6()) + { + Ipv6Address ad(port); + return Bind(ad, range); + } +#endif +#endif + Ipv4Address ad(port); + return Bind(ad, range); +} + +int UdpSocket::Bind(const std::string& intf, port_t &port, int range) +{ +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + if (IsIpv6()) + { + Ipv6Address ad(intf, port); + if (ad.IsValid()) + { + return Bind(ad, range); + } + SetCloseAndDelete(); + return -1; + } +#endif +#endif + Ipv4Address ad(intf, port); + if (ad.IsValid()) + { + return Bind(ad, range); + } + SetCloseAndDelete(); + return -1; +} + +int UdpSocket::Bind(ipaddr_t a, port_t &port, int range) +{ + Ipv4Address ad(a, port); + return Bind(ad, range); +} + +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 +int UdpSocket::Bind(in6_addr a, port_t &port, int range) +{ + Ipv6Address ad(a, port); + return Bind(ad, range); +} +#endif +#endif + +int UdpSocket::Bind(SocketAddress& ad, int range) +{ + if (GetSocket() == INVALID_SOCKET) + { + Attach(CreateSocket(ad.GetFamily(), SOCK_DGRAM, "udp")); + } + if (GetSocket() != INVALID_SOCKET) + { + SetNonblocking(true); + int n = bind(GetSocket(), ad, ad); + int tries = range; + while (n == -1 && tries--) + { + ad.SetPort(ad.GetPort() + 1); + n = bind(GetSocket(), ad, ad); + } + if (n == -1) + { + Handler().LogError(this, "bind", Errno, StrError(Errno), LOG_LEVEL_FATAL); + SetCloseAndDelete(); +#ifdef ENABLE_EXCEPTIONS + throw Exception("bind() failed for UdpSocket, port:range: " + Utility::l2string(ad.GetPort()) + ":" + Utility::l2string(range)); +#endif + return -1; + } + m_bind_ok = true; + m_port = ad.GetPort(); + return 0; + } + return -1; +} + +/** if you wish to use Send, first Open a connection */ +bool UdpSocket::Open(ipaddr_t l, port_t port) +{ + Ipv4Address ad(l, port); + return Open(ad); +} + +bool UdpSocket::Open(const std::string& host, port_t port) +{ +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + if (IsIpv6()) + { + Ipv6Address ad(host, port); + if (ad.IsValid()) + { + return Open(ad); + } + return false; + } +#endif +#endif + Ipv4Address ad(host, port); + if (ad.IsValid()) + { + return Open(ad); + } + return false; +} + +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 +bool UdpSocket::Open(struct in6_addr& a, port_t port) +{ + Ipv6Address ad(a, port); + return Open(ad); +} +#endif +#endif + +bool UdpSocket::Open(SocketAddress& ad) +{ + if (GetSocket() == INVALID_SOCKET) + { + Attach(CreateSocket(ad.GetFamily(), SOCK_DGRAM, "udp")); + } + if (GetSocket() != INVALID_SOCKET) + { + SetNonblocking(true); + if (connect(GetSocket(), ad, ad) == -1) + { + Handler().LogError(this, "connect", Errno, StrError(Errno), LOG_LEVEL_FATAL); + SetCloseAndDelete(); + return false; + } + SetConnected(); + return true; + } + return false; +} + +void UdpSocket::CreateConnection() +{ +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + if (IsIpv6()) + { + if (GetSocket() == INVALID_SOCKET) + { + SOCKET s = CreateSocket(AF_INET6, SOCK_DGRAM, "udp"); + if (s == INVALID_SOCKET) + { + return; + } + SetNonblocking(true, s); + Attach(s); + } + return; + } +#endif +#endif + if (GetSocket() == INVALID_SOCKET) + { + SOCKET s = CreateSocket(AF_INET, SOCK_DGRAM, "udp"); + if (s == INVALID_SOCKET) + { + return; + } + SetNonblocking(true, s); + Attach(s); + } +} + +/** send to specified address */ +void UdpSocket::SendToBuf(const std::string& h, port_t p, const char *data, int len, int flags) +{ +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + if (IsIpv6()) + { + Ipv6Address ad(h, p); + if (ad.IsValid()) + { + SendToBuf(ad, data, len, flags); + } + return; + } +#endif +#endif + Ipv4Address ad(h, p); + if (ad.IsValid()) + { + SendToBuf(ad, data, len, flags); + } +} + +/** send to specified address */ +void UdpSocket::SendToBuf(ipaddr_t a, port_t p, const char *data, int len, int flags) +{ + Ipv4Address ad(a, p); + SendToBuf(ad, data, len, flags); +} + +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 +void UdpSocket::SendToBuf(in6_addr a, port_t p, const char *data, int len, int flags) +{ + Ipv6Address ad(a, p); + SendToBuf(ad, data, len, flags); +} +#endif +#endif + +void UdpSocket::SendToBuf(SocketAddress& ad, const char *data, int len, int flags) +{ + if (GetSocket() == INVALID_SOCKET) + { + Attach(CreateSocket(ad.GetFamily(), SOCK_DGRAM, "udp")); + } + if (GetSocket() != INVALID_SOCKET) + { + SetNonblocking(true); + if ((m_last_size_written = sendto(GetSocket(), data, len, flags, ad, ad)) == -1) + { + Handler().LogError(this, "sendto", Errno, StrError(Errno), LOG_LEVEL_ERROR); + } + } +} + +void UdpSocket::SendTo(const std::string& a, port_t p, const std::string& str, int flags) +{ + SendToBuf(a, p, str.c_str(), (int)str.size(), flags); +} + +void UdpSocket::SendTo(ipaddr_t a, port_t p, const std::string& str, int flags) +{ + SendToBuf(a, p, str.c_str(), (int)str.size(), flags); +} + +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 +void UdpSocket::SendTo(in6_addr a, port_t p, const std::string& str, int flags) +{ + SendToBuf(a, p, str.c_str(), (int)str.size(), flags); +} +#endif +#endif + +void UdpSocket::SendTo(SocketAddress& ad, const std::string& str, int flags) +{ + SendToBuf(ad, str.c_str(), (int)str.size(), flags); +} + +/** send to connected address */ +void UdpSocket::SendBuf(const char *data, size_t len, int flags) +{ + if (!IsConnected()) + { + Handler().LogError(this, "SendBuf", 0, "not connected", LOG_LEVEL_ERROR); + return; + } + if ((m_last_size_written = send(GetSocket(), data, (int)len, flags)) == -1) + { + Handler().LogError(this, "send", Errno, StrError(Errno), LOG_LEVEL_ERROR); + } +} + +void UdpSocket::Send(const std::string& str, int flags) +{ + SendBuf(str.c_str(), (int)str.size(), flags); +} + +#if defined(LINUX) || defined(MACOSX) +int UdpSocket::ReadTS(char *ioBuf, int inBufSize, struct sockaddr *from, socklen_t fromlen, struct timeval *ts) +{ + struct msghdr msg; + struct iovec vec[1]; + union { + struct cmsghdr cm; +#ifdef MACOSX +#ifdef __DARWIN_UNIX03 +#define ALIGNBYTES __DARWIN_ALIGNBYTES +#endif +#define myALIGN(p) (((unsigned int)(p) + ALIGNBYTES) &~ ALIGNBYTES) +#define myCMSG_SPACE(l) (myALIGN(sizeof(struct cmsghdr)) + myALIGN(l)) + char data[ myCMSG_SPACE(sizeof(struct timeval)) ]; +#else + char data[ CMSG_SPACE(sizeof(struct timeval)) ]; +#endif + } cmsg_un; + struct cmsghdr *cmsg; + struct timeval *tv; + + vec[0].iov_base = ioBuf; + vec[0].iov_len = inBufSize; + + memset(&msg, 0, sizeof(msg)); + memset(from, 0, fromlen); + memset(ioBuf, 0, inBufSize); + memset(&cmsg_un, 0, sizeof(cmsg_un)); + + msg.msg_name = (caddr_t)from; + msg.msg_namelen = fromlen; + msg.msg_iov = vec; + msg.msg_iovlen = 1; + msg.msg_control = cmsg_un.data; + msg.msg_controllen = sizeof(cmsg_un.data); + msg.msg_flags = 0; + + // Original version - for reference only + //int n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len); + + int n = recvmsg(GetSocket(), &msg, MSG_DONTWAIT); + + // now ioBuf will contain the data, as if we used recvfrom + + // Now get the time + if(n != -1 && msg.msg_controllen >= sizeof(struct cmsghdr) && !(msg.msg_flags & MSG_CTRUNC)) + { + tv = 0; + for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg)) + { + if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_TIMESTAMP) + { + tv = (struct timeval *)CMSG_DATA(cmsg); + } + } + if (tv) + { + memcpy(ts, tv, sizeof(struct timeval)); + } + } + // The address is in network order, but that's OK right now + return n; +} +#endif + +void UdpSocket::OnRead() +{ +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + if (IsIpv6()) + { + struct sockaddr_in6 sa; + socklen_t sa_len = sizeof(sa); + if (m_b_read_ts) + { + struct timeval ts; + Utility::GetTime(&ts); +#if !defined(LINUX) && !defined(MACOSX) + int n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len); +#else + int n = ReadTS(m_ibuf, m_ibufsz, (struct sockaddr *)&sa, sa_len, &ts); +#endif + if (n > 0) + { + this -> OnRawData(m_ibuf, n, (struct sockaddr *)&sa, sa_len, &ts); + } + else + if (n == -1) + { +#ifdef _WIN32 + if (Errno != WSAEWOULDBLOCK) +#else + if (Errno != EWOULDBLOCK) +#endif + Handler().LogError(this, "recvfrom", Errno, StrError(Errno), LOG_LEVEL_ERROR); + } + return; + } + int n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len); + int q = m_retries; // receive max 10 at one cycle + while (n > 0) + { + if (sa_len != sizeof(sa)) + { + Handler().LogError(this, "recvfrom", 0, "unexpected address struct size", LOG_LEVEL_WARNING); + } + this -> OnRawData(m_ibuf, n, (struct sockaddr *)&sa, sa_len); + if (!q--) + break; + // + n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len); + } + if (n == -1) + { +#ifdef _WIN32 + if (Errno != WSAEWOULDBLOCK) +#else + if (Errno != EWOULDBLOCK) +#endif + Handler().LogError(this, "recvfrom", Errno, StrError(Errno), LOG_LEVEL_ERROR); + } + return; + } +#endif +#endif + struct sockaddr_in sa; + socklen_t sa_len = sizeof(sa); + if (m_b_read_ts) + { + struct timeval ts; + Utility::GetTime(&ts); +#if !defined(LINUX) && !defined(MACOSX) + int n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len); +#else + int n = ReadTS(m_ibuf, m_ibufsz, (struct sockaddr *)&sa, sa_len, &ts); +#endif + if (n > 0) + { + this -> OnRawData(m_ibuf, n, (struct sockaddr *)&sa, sa_len, &ts); + } + else + if (n == -1) + { +#ifdef _WIN32 + if (Errno != WSAEWOULDBLOCK) +#else + if (Errno != EWOULDBLOCK) +#endif + Handler().LogError(this, "recvfrom", Errno, StrError(Errno), LOG_LEVEL_ERROR); + } + return; + } + int n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len); + int q = m_retries; + while (n > 0) + { + if (sa_len != sizeof(sa)) + { + Handler().LogError(this, "recvfrom", 0, "unexpected address struct size", LOG_LEVEL_WARNING); + } + this -> OnRawData(m_ibuf, n, (struct sockaddr *)&sa, sa_len); + if (!q--) + break; + // + n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len); + } + if (n == -1) + { +#ifdef _WIN32 + if (Errno != WSAEWOULDBLOCK) +#else + if (Errno != EWOULDBLOCK) +#endif + Handler().LogError(this, "recvfrom", Errno, StrError(Errno), LOG_LEVEL_ERROR); + } +} + +void UdpSocket::SetBroadcast(bool b) +{ + int one = 1; + int zero = 0; + + if (GetSocket() == INVALID_SOCKET) + { + CreateConnection(); + } + if (b) + { + if (setsockopt(GetSocket(), SOL_SOCKET, SO_BROADCAST, (char *) &one, sizeof(one)) == -1) + { + Handler().LogError(this, "SetBroadcast", Errno, StrError(Errno), LOG_LEVEL_WARNING); + } + } + else + { + if (setsockopt(GetSocket(), SOL_SOCKET, SO_BROADCAST, (char *) &zero, sizeof(zero)) == -1) + { + Handler().LogError(this, "SetBroadcast", Errno, StrError(Errno), LOG_LEVEL_WARNING); + } + } +} + +bool UdpSocket::IsBroadcast() +{ + int is_broadcast = 0; + socklen_t size; + + if (GetSocket() == INVALID_SOCKET) + { + CreateConnection(); + } + if (getsockopt(GetSocket(), SOL_SOCKET, SO_BROADCAST, (char *)&is_broadcast, &size) == -1) + { + Handler().LogError(this, "IsBroadcast", Errno, StrError(Errno), LOG_LEVEL_WARNING); + } + return is_broadcast != 0; +} + +void UdpSocket::SetMulticastTTL(int ttl) +{ + if (GetSocket() == INVALID_SOCKET) + { + CreateConnection(); + } + if (setsockopt(GetSocket(), SOL_IP, IP_MULTICAST_TTL, (char *)&ttl, sizeof(int)) == -1) + { + Handler().LogError(this, "SetMulticastTTL", Errno, StrError(Errno), LOG_LEVEL_WARNING); + } +} + +int UdpSocket::GetMulticastTTL() +{ + int ttl = 0; + socklen_t size = sizeof(int); + + if (GetSocket() == INVALID_SOCKET) + { + CreateConnection(); + } + if (getsockopt(GetSocket(), SOL_IP, IP_MULTICAST_TTL, (char *)&ttl, &size) == -1) + { + Handler().LogError(this, "GetMulticastTTL", Errno, StrError(Errno), LOG_LEVEL_WARNING); + } + return ttl; +} + +void UdpSocket::SetMulticastLoop(bool x) +{ + if (GetSocket() == INVALID_SOCKET) + { + CreateConnection(); + } +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + if (IsIpv6()) + { + int val = x ? 1 : 0; + if (setsockopt(GetSocket(), IPPROTO_IPV6, IPV6_MULTICAST_LOOP, (char *)&val, sizeof(int)) == -1) + { + Handler().LogError(this, "SetMulticastLoop", Errno, StrError(Errno), LOG_LEVEL_WARNING); + } + return; + } +#endif +#endif + int val = x ? 1 : 0; + if (setsockopt(GetSocket(), SOL_IP, IP_MULTICAST_LOOP, (char *)&val, sizeof(int)) == -1) + { + Handler().LogError(this, "SetMulticastLoop", Errno, StrError(Errno), LOG_LEVEL_WARNING); + } +} + +bool UdpSocket::IsMulticastLoop() +{ + if (GetSocket() == INVALID_SOCKET) + { + CreateConnection(); + } +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + if (IsIpv6()) + { + int is_loop = 0; + socklen_t size = sizeof(int); + if (getsockopt(GetSocket(), IPPROTO_IPV6, IPV6_MULTICAST_LOOP, (char *)&is_loop, &size) == -1) + { + Handler().LogError(this, "IsMulticastLoop", Errno, StrError(Errno), LOG_LEVEL_WARNING); + } + return is_loop ? true : false; + } +#endif +#endif + int is_loop = 0; + socklen_t size = sizeof(int); + if (getsockopt(GetSocket(), SOL_IP, IP_MULTICAST_LOOP, (char *)&is_loop, &size) == -1) + { + Handler().LogError(this, "IsMulticastLoop", Errno, StrError(Errno), LOG_LEVEL_WARNING); + } + return is_loop ? true : false; +} + +void UdpSocket::AddMulticastMembership(const std::string& group, const std::string& local_if, int if_index) +{ + if (GetSocket() == INVALID_SOCKET) + { + CreateConnection(); + } +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + if (IsIpv6()) + { + struct ipv6_mreq x; + struct in6_addr addr; + if (Utility::u2ip( group, addr )) + { + x.ipv6mr_multiaddr = addr; + x.ipv6mr_interface = if_index; + if (setsockopt(GetSocket(), IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, (char *)&x, sizeof(struct ipv6_mreq)) == -1) + { + Handler().LogError(this, "AddMulticastMembership", Errno, StrError(Errno), LOG_LEVEL_WARNING); + } + } + return; + } +#endif +#endif + struct ip_mreq x; // ip_mreqn + ipaddr_t addr; + if (Utility::u2ip( group, addr )) + { + memcpy(&x.imr_multiaddr.s_addr, &addr, sizeof(addr)); + Utility::u2ip( local_if, addr); + memcpy(&x.imr_interface.s_addr, &addr, sizeof(addr)); +// x.imr_ifindex = if_index; + if (setsockopt(GetSocket(), SOL_IP, IP_ADD_MEMBERSHIP, (char *)&x, sizeof(struct ip_mreq)) == -1) + { + Handler().LogError(this, "AddMulticastMembership", Errno, StrError(Errno), LOG_LEVEL_WARNING); + } + } +} + +void UdpSocket::DropMulticastMembership(const std::string& group, const std::string& local_if, int if_index) +{ + if (GetSocket() == INVALID_SOCKET) + { + CreateConnection(); + } +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + if (IsIpv6()) + { + struct ipv6_mreq x; + struct in6_addr addr; + if (Utility::u2ip( group, addr )) + { + x.ipv6mr_multiaddr = addr; + x.ipv6mr_interface = if_index; + if (setsockopt(GetSocket(), IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, (char *)&x, sizeof(struct ipv6_mreq)) == -1) + { + Handler().LogError(this, "DropMulticastMembership", Errno, StrError(Errno), LOG_LEVEL_WARNING); + } + } + return; + } +#endif +#endif + struct ip_mreq x; // ip_mreqn + ipaddr_t addr; + if (Utility::u2ip( group, addr )) + { + memcpy(&x.imr_multiaddr.s_addr, &addr, sizeof(addr)); + Utility::u2ip( local_if, addr); + memcpy(&x.imr_interface.s_addr, &addr, sizeof(addr)); +// x.imr_ifindex = if_index; + if (setsockopt(GetSocket(), SOL_IP, IP_DROP_MEMBERSHIP, (char *)&x, sizeof(struct ip_mreq)) == -1) + { + Handler().LogError(this, "DropMulticastMembership", Errno, StrError(Errno), LOG_LEVEL_WARNING); + } + } +} + +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 +void UdpSocket::SetMulticastHops(int hops) +{ + if (GetSocket() == INVALID_SOCKET) + { + CreateConnection(); + } + if (!IsIpv6()) + { + Handler().LogError(this, "SetMulticastHops", 0, "Ipv6 only", LOG_LEVEL_ERROR); + return; + } + if (setsockopt(GetSocket(), IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (char *)&hops, sizeof(int)) == -1) + { + Handler().LogError(this, "SetMulticastHops", Errno, StrError(Errno), LOG_LEVEL_WARNING); + } +} + +int UdpSocket::GetMulticastHops() +{ + if (GetSocket() == INVALID_SOCKET) + { + CreateConnection(); + } + if (!IsIpv6()) + { + Handler().LogError(this, "SetMulticastHops", 0, "Ipv6 only", LOG_LEVEL_ERROR); + return -1; + } + int hops = 0; + socklen_t size = sizeof(int); + if (getsockopt(GetSocket(), IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (char *)&hops, &size) == -1) + { + Handler().LogError(this, "GetMulticastHops", Errno, StrError(Errno), LOG_LEVEL_WARNING); + } + return hops; +} +#endif // IPPROTO_IPV6 +#endif + +bool UdpSocket::IsBound() +{ + return m_bind_ok; +} + +void UdpSocket::OnRawData(const char *buf, size_t len, struct sockaddr *sa, socklen_t sa_len) +{ +} + +void UdpSocket::OnRawData(const char *buf, size_t len, struct sockaddr *sa, socklen_t sa_len, struct timeval *ts) +{ +} + +port_t UdpSocket::GetPort() +{ + return m_port; +} + +int UdpSocket::GetLastSizeWritten() +{ + return m_last_size_written; +} + +void UdpSocket::SetTimestamp(bool x) +{ + m_b_read_ts = x; +} + +#ifdef SOCKETS_NAMESPACE +} +#endif + + diff --git a/dep/sockets/Utility.cpp b/dep/sockets/Utility.cpp new file mode 100644 index 00000000000..7c093fc0832 --- /dev/null +++ b/dep/sockets/Utility.cpp @@ -0,0 +1,960 @@ +/** \file Utility.cpp + ** \date 2004-02-13 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2004-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#include "Utility.h" +#include "Parse.h" +#include "Ipv4Address.h" +#include "Ipv6Address.h" +#include "Base64.h" +#include +#ifdef _WIN32 +#include +#else +#include +#include +#endif +#include + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +// defines for the random number generator +#define TWIST_IA 397 +#define TWIST_IB (TWIST_LEN - TWIST_IA) +#define UMASK 0x80000000 +#define LMASK 0x7FFFFFFF +#define MATRIX_A 0x9908B0DF +#define TWIST(b,i,j) ((b)[i] & UMASK) | ((b)[j] & LMASK) +#define MAGIC_TWIST(s) (((s) & 1) * MATRIX_A) + +// statics +std::string Utility::m_host; +bool Utility::m_local_resolved = false; +ipaddr_t Utility::m_ip = 0; +std::string Utility::m_addr; +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 +struct in6_addr Utility::m_local_ip6; +std::string Utility::m_local_addr6; +#endif +#endif + +std::string Utility::base64(const std::string& str_in) +{ + std::string str; + Base64 m_b; + m_b.encode(str_in, str, false); // , false == do not add cr/lf + return str; +} + +std::string Utility::base64d(const std::string& str_in) +{ + std::string str; + Base64 m_b; + m_b.decode(str_in, str); + return str; +} + +std::string Utility::l2string(long l) +{ + std::string str; + char tmp[100]; + sprintf(tmp,"%ld",l); + str = tmp; + return str; +} + +std::string Utility::bigint2string(uint64_t l) +{ + std::string str; + uint64_t tmp = l; + while (tmp) + { + uint64_t a = tmp % 10; + str = (char)(a + 48) + str; + tmp /= 10; + } + if (str.empty()) + { + str = "0"; + } + return str; +} + +uint64_t Utility::atoi64(const std::string& str) +{ + uint64_t l = 0; + for (size_t i = 0; i < str.size(); i++) + { + l = l * 10 + str[i] - 48; + } + return l; +} + +unsigned int Utility::hex2unsigned(const std::string& str) +{ + unsigned int r = 0; + for (size_t i = 0; i < str.size(); i++) + { + r = r * 16 + str[i] - 48 - ((str[i] >= 'A') ? 7 : 0) - ((str[i] >= 'a') ? 32 : 0); + } + return r; +} + +/* +* Encode string per RFC1738 URL encoding rules +* tnx rstaveley +*/ +std::string Utility::rfc1738_encode(const std::string& src) +{ +static char hex[] = "0123456789ABCDEF"; + std::string dst; + for (size_t i = 0; i < src.size(); i++) + { + if (isalnum(src[i])) + { + dst += src[i]; + } + else + if (src[i] == ' ') + { + dst += '+'; + } + else + { + unsigned char c = static_cast(src[i]); + dst += '%'; + dst += hex[c / 16]; + dst += hex[c % 16]; + } + } + return dst; +} // rfc1738_encode + +/* +* Decode string per RFC1738 URL encoding rules +* tnx rstaveley +*/ +std::string Utility::rfc1738_decode(const std::string& src) +{ + std::string dst; + for (size_t i = 0; i < src.size(); i++) + { + if (src[i] == '%' && isxdigit(src[i + 1]) && isxdigit(src[i + 2])) + { + char c1 = src[++i]; + char c2 = src[++i]; + c1 = c1 - 48 - ((c1 >= 'A') ? 7 : 0) - ((c1 >= 'a') ? 32 : 0); + c2 = c2 - 48 - ((c2 >= 'A') ? 7 : 0) - ((c2 >= 'a') ? 32 : 0); + dst += (char)(c1 * 16 + c2); + } + else + if (src[i] == '+') + { + dst += ' '; + } + else + { + dst += src[i]; + } + } + return dst; +} // rfc1738_decode + +bool Utility::isipv4(const std::string& str) +{ + int dots = 0; + // %! ignore :port? + for (size_t i = 0; i < str.size(); i++) + { + if (str[i] == '.') + dots++; + else + if (!isdigit(str[i])) + return false; + } + if (dots != 3) + return false; + return true; +} + +bool Utility::isipv6(const std::string& str) +{ + size_t qc = 0; + size_t qd = 0; + for (size_t i = 0; i < str.size(); i++) + { + qc += (str[i] == ':') ? 1 : 0; + qd += (str[i] == '.') ? 1 : 0; + } + if (qc > 7) + { + return false; + } + if (qd && qd != 3) + { + return false; + } + Parse pa(str,":."); + std::string tmp = pa.getword(); + while (!tmp.empty()) + { + if (tmp.size() > 4) + { + return false; + } + for (size_t i = 0; i < tmp.size(); i++) + { + if (tmp[i] < '0' || (tmp[i] > '9' && tmp[i] < 'A') || + (tmp[i] > 'F' && tmp[i] < 'a') || tmp[i] > 'f') + { + return false; + } + } + // + tmp = pa.getword(); + } + return true; +} + +bool Utility::u2ip(const std::string& str, ipaddr_t& l) +{ + struct sockaddr_in sa; + bool r = Utility::u2ip(str, sa); + memcpy(&l, &sa.sin_addr, sizeof(l)); + return r; +} + +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 +bool Utility::u2ip(const std::string& str, struct in6_addr& l) +{ + struct sockaddr_in6 sa; + bool r = Utility::u2ip(str, sa); + l = sa.sin6_addr; + return r; +} +#endif +#endif + +void Utility::l2ip(const ipaddr_t ip, std::string& str) +{ + struct sockaddr_in sa; + memset(&sa, 0, sizeof(sa)); + sa.sin_family = AF_INET; + memcpy(&sa.sin_addr, &ip, sizeof(sa.sin_addr)); + Utility::reverse( (struct sockaddr *)&sa, sizeof(sa), str, NI_NUMERICHOST); +} + +void Utility::l2ip(const in_addr& ip, std::string& str) +{ + struct sockaddr_in sa; + memset(&sa, 0, sizeof(sa)); + sa.sin_family = AF_INET; + sa.sin_addr = ip; + Utility::reverse( (struct sockaddr *)&sa, sizeof(sa), str, NI_NUMERICHOST); +} + +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 +void Utility::l2ip(const struct in6_addr& ip, std::string& str,bool mixed) +{ + char slask[100]; // l2ip temporary + *slask = 0; + unsigned int prev = 0; + bool skipped = false; + bool ok_to_skip = true; + if (mixed) + { + unsigned short x; + unsigned short addr16[8]; + memcpy(addr16, &ip, sizeof(addr16)); + for (size_t i = 0; i < 6; i++) + { + x = ntohs(addr16[i]); + if (*slask && (x || !ok_to_skip || prev)) + strcat(slask,":"); + if (x || !ok_to_skip) + { + sprintf(slask + strlen(slask),"%x", x); + if (x && skipped) + ok_to_skip = false; + } + else + { + skipped = true; + } + prev = x; + } + x = ntohs(addr16[6]); + sprintf(slask + strlen(slask),":%u.%u",x / 256,x & 255); + x = ntohs(addr16[7]); + sprintf(slask + strlen(slask),".%u.%u",x / 256,x & 255); + } + else + { + struct sockaddr_in6 sa; + memset(&sa, 0, sizeof(sa)); + sa.sin6_family = AF_INET6; + sa.sin6_addr = ip; + Utility::reverse( (struct sockaddr *)&sa, sizeof(sa), str, NI_NUMERICHOST); + return; + } + str = slask; +} + +int Utility::in6_addr_compare(in6_addr a,in6_addr b) +{ + for (size_t i = 0; i < 16; i++) + { + if (a.s6_addr[i] < b.s6_addr[i]) + return -1; + if (a.s6_addr[i] > b.s6_addr[i]) + return 1; + } + return 0; +} +#endif +#endif + +void Utility::ResolveLocal() +{ + char h[256]; + + // get local hostname and translate into ip-address + *h = 0; + gethostname(h,255); + { + if (Utility::u2ip(h, m_ip)) + { + Utility::l2ip(m_ip, m_addr); + } + } +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + memset(&m_local_ip6, 0, sizeof(m_local_ip6)); + { + if (Utility::u2ip(h, m_local_ip6)) + { + Utility::l2ip(m_local_ip6, m_local_addr6); + } + } +#endif +#endif + m_host = h; + m_local_resolved = true; +} + +const std::string& Utility::GetLocalHostname() +{ + if (!m_local_resolved) + { + ResolveLocal(); + } + return m_host; +} + +ipaddr_t Utility::GetLocalIP() +{ + if (!m_local_resolved) + { + ResolveLocal(); + } + return m_ip; +} + +const std::string& Utility::GetLocalAddress() +{ + if (!m_local_resolved) + { + ResolveLocal(); + } + return m_addr; +} + +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 +const struct in6_addr& Utility::GetLocalIP6() +{ + if (!m_local_resolved) + { + ResolveLocal(); + } + return m_local_ip6; +} + +const std::string& Utility::GetLocalAddress6() +{ + if (!m_local_resolved) + { + ResolveLocal(); + } + return m_local_addr6; +} +#endif +#endif + +void Utility::SetEnv(const std::string& var,const std::string& value) +{ +#if (defined(SOLARIS8) || defined(SOLARIS)) + { + static std::map vmap; + if (vmap.find(var) != vmap.end()) + { + delete[] vmap[var]; + } + vmap[var] = new char[var.size() + 1 + value.size() + 1]; + sprintf(vmap[var], "%s=%s", var.c_str(), value.c_str()); + putenv( vmap[var] ); + } +#elif defined _WIN32 + { + std::string slask = var + "=" + value; + _putenv( (char *)slask.c_str()); + } +#else + setenv(var.c_str(), value.c_str(), 1); +#endif +} + +std::string Utility::Sa2String(struct sockaddr *sa) +{ +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + if (sa -> sa_family == AF_INET6) + { + struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)sa; + std::string tmp; + Utility::l2ip(sa6 -> sin6_addr, tmp); + return tmp + ":" + Utility::l2string(ntohs(sa6 -> sin6_port)); + } +#endif +#endif + if (sa -> sa_family == AF_INET) + { + struct sockaddr_in *sa4 = (struct sockaddr_in *)sa; + ipaddr_t a; + memcpy(&a, &sa4 -> sin_addr, 4); + std::string tmp; + Utility::l2ip(a, tmp); + return tmp + ":" + Utility::l2string(ntohs(sa4 -> sin_port)); + } + return ""; +} + +void Utility::GetTime(struct timeval *p) +{ +#ifdef _WIN32 + FILETIME ft; // Contains a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC). + GetSystemTimeAsFileTime(&ft); + uint64_t tt; + memcpy(&tt, &ft, sizeof(tt)); + tt /= 10; // make it usecs + p->tv_sec = (long)tt / 1000000; + p->tv_usec = (long)tt % 1000000; +#else + gettimeofday(p, NULL); +#endif +} + +std::auto_ptr Utility::CreateAddress(struct sockaddr *sa,socklen_t sa_len) +{ + switch (sa -> sa_family) + { + case AF_INET: + if (sa_len == sizeof(struct sockaddr_in)) + { + struct sockaddr_in *p = (struct sockaddr_in *)sa; + return std::auto_ptr(new Ipv4Address(*p)); + } + break; +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + case AF_INET6: + if (sa_len == sizeof(struct sockaddr_in6)) + { + struct sockaddr_in6 *p = (struct sockaddr_in6 *)sa; + return std::auto_ptr(new Ipv6Address(*p)); + } + break; +#endif +#endif + } + return std::auto_ptr(NULL); +} + +bool Utility::u2ip(const std::string& host, struct sockaddr_in& sa, int ai_flags) +{ + memset(&sa, 0, sizeof(sa)); + sa.sin_family = AF_INET; +#ifdef NO_GETADDRINFO + if ((ai_flags & AI_NUMERICHOST) != 0 || isipv4(host)) + { + Parse pa((char *)host.c_str(), "."); + union { + struct { + unsigned char b1; + unsigned char b2; + unsigned char b3; + unsigned char b4; + } a; + ipaddr_t l; + } u; + u.a.b1 = static_cast(pa.getvalue()); + u.a.b2 = static_cast(pa.getvalue()); + u.a.b3 = static_cast(pa.getvalue()); + u.a.b4 = static_cast(pa.getvalue()); + memcpy(&sa.sin_addr, &u.l, sizeof(sa.sin_addr)); + return true; + } +#ifndef LINUX + struct hostent *he = gethostbyname( host.c_str() ); + if (!he) + { + return false; + } + memcpy(&sa.sin_addr, he -> h_addr, sizeof(sa.sin_addr)); +#else + struct hostent he; + struct hostent *result = NULL; + int myerrno = 0; + char buf[2000]; + int n = gethostbyname_r(host.c_str(), &he, buf, sizeof(buf), &result, &myerrno); + if (n || !result) + { + return false; + } + if (he.h_addr_list && he.h_addr_list[0]) + memcpy(&sa.sin_addr, he.h_addr, 4); + else + return false; +#endif + return true; +#else + struct addrinfo hints; + memset(&hints, 0, sizeof(hints)); + // AI_NUMERICHOST + // AI_CANONNAME + // AI_PASSIVE - server + // AI_ADDRCONFIG + // AI_V4MAPPED + // AI_ALL + // AI_NUMERICSERV + hints.ai_flags = ai_flags; + hints.ai_family = AF_INET; + hints.ai_socktype = 0; + hints.ai_protocol = 0; + struct addrinfo *res; + if (Utility::isipv4(host)) + hints.ai_flags |= AI_NUMERICHOST; + int n = getaddrinfo(host.c_str(), NULL, &hints, &res); + if (!n) + { + std::vector vec; + struct addrinfo *ai = res; + while (ai) + { + if (ai -> ai_addrlen == sizeof(sa)) + vec.push_back( ai ); + ai = ai -> ai_next; + } + if (vec.empty()) + return false; + ai = vec[Utility::Rnd() % vec.size()]; + { + memcpy(&sa, ai -> ai_addr, ai -> ai_addrlen); + } + freeaddrinfo(res); + return true; + } + std::string error = "Error: "; +#ifndef __CYGWIN__ + error += gai_strerror(n); +#endif + return false; +#endif // NO_GETADDRINFO +} + +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 +bool Utility::u2ip(const std::string& host, struct sockaddr_in6& sa, int ai_flags) +{ + memset(&sa, 0, sizeof(sa)); + sa.sin6_family = AF_INET6; +#ifdef NO_GETADDRINFO + if ((ai_flags & AI_NUMERICHOST) != 0 || isipv6(host)) + { + std::list vec; + size_t x = 0; + for (size_t i = 0; i <= host.size(); i++) + { + if (i == host.size() || host[i] == ':') + { + std::string s = host.substr(x, i - x); + // + if (strstr(s.c_str(),".")) // x.x.x.x + { + Parse pa(s,"."); + char slask[100]; // u2ip temporary hex2string conversion + unsigned long b0 = static_cast(pa.getvalue()); + unsigned long b1 = static_cast(pa.getvalue()); + unsigned long b2 = static_cast(pa.getvalue()); + unsigned long b3 = static_cast(pa.getvalue()); + sprintf(slask,"%lx",b0 * 256 + b1); + vec.push_back(slask); + sprintf(slask,"%lx",b2 * 256 + b3); + vec.push_back(slask); + } + else + { + vec.push_back(s); + } + // + x = i + 1; + } + } + size_t sz = vec.size(); // number of byte pairs + size_t i = 0; // index in in6_addr.in6_u.u6_addr16[] ( 0 .. 7 ) + unsigned short addr16[8]; + for (std::list::iterator it = vec.begin(); it != vec.end(); it++) + { + std::string bytepair = *it; + if (!bytepair.empty()) + { + addr16[i++] = htons(Utility::hex2unsigned(bytepair)); + } + else + { + addr16[i++] = 0; + while (sz++ < 8) + { + addr16[i++] = 0; + } + } + } + memcpy(&sa.sin6_addr, addr16, sizeof(addr16)); + return true; + } +#ifdef SOLARIS + int errnum = 0; + struct hostent *he = getipnodebyname( host.c_str(), AF_INET6, 0, &errnum ); +#else + struct hostent *he = gethostbyname2( host.c_str(), AF_INET6 ); +#endif + if (!he) + { + return false; + } + memcpy(&sa.sin6_addr,he -> h_addr_list[0],he -> h_length); +#ifdef SOLARIS + free(he); +#endif + return true; +#else + struct addrinfo hints; + memset(&hints, 0, sizeof(hints)); + hints.ai_flags = ai_flags; + hints.ai_family = AF_INET6; + hints.ai_socktype = 0; + hints.ai_protocol = 0; + struct addrinfo *res; + if (Utility::isipv6(host)) + hints.ai_flags |= AI_NUMERICHOST; + int n = getaddrinfo(host.c_str(), NULL, &hints, &res); + if (!n) + { + std::vector vec; + struct addrinfo *ai = res; + while (ai) + { + if (ai -> ai_addrlen == sizeof(sa)) + vec.push_back( ai ); + ai = ai -> ai_next; + } + if (vec.empty()) + return false; + ai = vec[Utility::Rnd() % vec.size()]; + { + memcpy(&sa, ai -> ai_addr, ai -> ai_addrlen); + } + freeaddrinfo(res); + return true; + } + std::string error = "Error: "; +#ifndef __CYGWIN__ + error += gai_strerror(n); +#endif + return false; +#endif // NO_GETADDRINFO +} +#endif // IPPROTO_IPV6 +#endif // ENABLE_IPV6 + +bool Utility::reverse(struct sockaddr *sa, socklen_t sa_len, std::string& hostname, int flags) +{ + std::string service; + return Utility::reverse(sa, sa_len, hostname, service, flags); +} + +bool Utility::reverse(struct sockaddr *sa, socklen_t sa_len, std::string& hostname, std::string& service, int flags) +{ + hostname = ""; + service = ""; +#ifdef NO_GETADDRINFO + switch (sa -> sa_family) + { + case AF_INET: + if (flags & NI_NUMERICHOST) + { + union { + struct { + unsigned char b1; + unsigned char b2; + unsigned char b3; + unsigned char b4; + } a; + ipaddr_t l; + } u; + struct sockaddr_in *sa_in = (struct sockaddr_in *)sa; + memcpy(&u.l, &sa_in -> sin_addr, sizeof(u.l)); + char tmp[100]; + sprintf(tmp, "%u.%u.%u.%u", u.a.b1, u.a.b2, u.a.b3, u.a.b4); + hostname = tmp; + return true; + } + else + { + struct sockaddr_in *sa_in = (struct sockaddr_in *)sa; + struct hostent *h = gethostbyaddr( (const char *)&sa_in -> sin_addr, sizeof(sa_in -> sin_addr), AF_INET); + if (h) + { + hostname = h -> h_name; + return true; + } + } + break; +#ifdef ENABLE_IPV6 + case AF_INET6: + if (flags & NI_NUMERICHOST) + { + char slask[100]; // l2ip temporary + *slask = 0; + unsigned int prev = 0; + bool skipped = false; + bool ok_to_skip = true; + { + unsigned short addr16[8]; + struct sockaddr_in6 *sa_in6 = (struct sockaddr_in6 *)sa; + memcpy(addr16, &sa_in6 -> sin6_addr, sizeof(addr16)); + for (size_t i = 0; i < 8; i++) + { + unsigned short x = ntohs(addr16[i]); + if (*slask && (x || !ok_to_skip || prev)) + strcat(slask,":"); + if (x || !ok_to_skip) + { + sprintf(slask + strlen(slask),"%x", x); + if (x && skipped) + ok_to_skip = false; + } + else + { + skipped = true; + } + prev = x; + } + } + if (!*slask) + strcpy(slask, "::"); + hostname = slask; + return true; + } + else + { + // %! TODO: ipv6 reverse lookup + struct sockaddr_in6 *sa_in = (struct sockaddr_in6 *)sa; + struct hostent *h = gethostbyaddr( (const char *)&sa_in -> sin6_addr, sizeof(sa_in -> sin6_addr), AF_INET6); + if (h) + { + hostname = h -> h_name; + return true; + } + } + break; +#endif + } + return false; +#else + char host[NI_MAXHOST]; + char serv[NI_MAXSERV]; + // NI_NOFQDN + // NI_NUMERICHOST + // NI_NAMEREQD + // NI_NUMERICSERV + // NI_DGRAM + int n = getnameinfo(sa, sa_len, host, sizeof(host), serv, sizeof(serv), flags); + if (n) + { + // EAI_AGAIN + // EAI_BADFLAGS + // EAI_FAIL + // EAI_FAMILY + // EAI_MEMORY + // EAI_NONAME + // EAI_OVERFLOW + // EAI_SYSTEM + return false; + } + hostname = host; + service = serv; + return true; +#endif // NO_GETADDRINFO +} + +bool Utility::u2service(const std::string& name, int& service, int ai_flags) +{ +#ifdef NO_GETADDRINFO + // %! + return false; +#else + struct addrinfo hints; + service = 0; + memset(&hints, 0, sizeof(hints)); + // AI_NUMERICHOST + // AI_CANONNAME + // AI_PASSIVE - server + // AI_ADDRCONFIG + // AI_V4MAPPED + // AI_ALL + // AI_NUMERICSERV + hints.ai_flags = ai_flags; + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = 0; + hints.ai_protocol = 0; + struct addrinfo *res; + int n = getaddrinfo(NULL, name.c_str(), &hints, &res); + if (!n) + { + service = res -> ai_protocol; + freeaddrinfo(res); + return true; + } + return false; +#endif // NO_GETADDRINFO +} + +unsigned long Utility::ThreadID() +{ +#ifdef _WIN32 + return GetCurrentThreadId(); +#else + return (unsigned long)pthread_self(); +#endif +} + +std::string Utility::ToLower(const std::string& str) +{ + std::string r; + for (size_t i = 0; i < str.size(); i++) + { + if (str[i] >= 'A' && str[i] <= 'Z') + r += str[i] | 32; + else + r += str[i]; + } + return r; +} + +std::string Utility::ToUpper(const std::string& str) +{ + std::string r; + for (size_t i = 0; i < str.size(); i++) + { + if (str[i] >= 'a' && str[i] <= 'z') + r += (char)(str[i] - 32); + else + r += str[i]; + } + return r; +} + +std::string Utility::ToString(double d) +{ + char tmp[100]; + sprintf(tmp, "%f", d); + return tmp; +} + +unsigned long Utility::Rnd() +{ +static Utility::Rng generator( (unsigned long)time(NULL) ); + return generator.Get(); +} + +Utility::Rng::Rng(unsigned long seed) : m_value( 0 ) +{ + m_tmp[0]= seed & 0xffffffffUL; + for (int i = 1; i < TWIST_LEN; i++) + { + m_tmp[i] = (1812433253UL * (m_tmp[i - 1] ^ (m_tmp[i - 1] >> 30)) + i); + } +} + +unsigned long Utility::Rng::Get() +{ + unsigned long val = m_tmp[m_value]; + ++m_value; + if (m_value == TWIST_LEN) + { + for (int i = 0; i < TWIST_IB; ++i) + { + unsigned long s = TWIST(m_tmp, i, i + 1); + m_tmp[i] = m_tmp[i + TWIST_IA] ^ (s >> 1) ^ MAGIC_TWIST(s); + } + { + for (int i = 0; i < TWIST_LEN - 1; ++i) + { + unsigned long s = TWIST(m_tmp, i, i + 1); + m_tmp[i] = m_tmp[i - TWIST_IB] ^ (s >> 1) ^ MAGIC_TWIST(s); + } + } + unsigned long s = TWIST(m_tmp, TWIST_LEN - 1, 0); + m_tmp[TWIST_LEN - 1] = m_tmp[TWIST_IA - 1] ^ (s >> 1) ^ MAGIC_TWIST(s); + + m_value = 0; + } + return val; +} + +#ifdef SOCKETS_NAMESPACE +} +#endif + + diff --git a/dep/sockets/include/Base64.h b/dep/sockets/include/Base64.h new file mode 100644 index 00000000000..d4323aaa019 --- /dev/null +++ b/dep/sockets/include/Base64.h @@ -0,0 +1,77 @@ +/** \file Base64.h + ** \date 2004-02-13 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2004-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifndef _SOCKETS_Base64_H +#define _SOCKETS_Base64_H + +#include "sockets-config.h" +#ifdef _MSC_VER +#pragma warning(disable:4514) +#endif + +#include +#include + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +/** \defgroup util Utilities */ + +/** Base64 encode/decode. + \ingroup util */ +class Base64 +{ +public: + Base64(); + + void encode(FILE *, std::string& , bool add_crlf = true); + void encode(const std::string&, std::string& , bool add_crlf = true); + void encode(const char *, size_t, std::string& , bool add_crlf = true); + void encode(const unsigned char *, size_t, std::string& , bool add_crlf = true); + + void decode(const std::string&, std::string& ); + void decode(const std::string&, unsigned char *, size_t&); + + size_t decode_length(const std::string& ); + +private: + Base64(const Base64& ) {} + Base64& operator=(const Base64& ) { return *this; } +static const char *bstr; +static const char rstr[128]; +}; + +#ifdef SOCKETS_NAMESPACE +} +#endif + +#endif // _SOCKETS_Base64_H + + diff --git a/dep/sockets/include/Exception.h b/dep/sockets/include/Exception.h new file mode 100644 index 00000000000..bb881b2d74f --- /dev/null +++ b/dep/sockets/include/Exception.h @@ -0,0 +1,55 @@ +/** + ** \file Exception.h + ** \date 2007-09-28 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2007 Anders Hedstrom + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifndef _Sockets_Exception_H +#define _Sockets_Exception_H + +#include + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +class Exception +{ +public: + Exception(const std::string& description); + virtual ~Exception() {} + + virtual const std::string ToString() const; + + Exception(const Exception& ) {} // copy constructor + + Exception& operator=(const Exception& ) { return *this; } // assignment operator + +private: + std::string m_description; + +}; + +#ifdef SOCKETS_NAMESPACE +} // namespace SOCKETS_NAMESPACE { +#endif + +#endif // _Sockets_Exception_H + + diff --git a/dep/sockets/include/File.h b/dep/sockets/include/File.h new file mode 100644 index 00000000000..ed322efa2d8 --- /dev/null +++ b/dep/sockets/include/File.h @@ -0,0 +1,82 @@ +/** \file File.h + ** \date 2005-04-25 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2004-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifndef _SOCKETS_File_H +#define _SOCKETS_File_H + +#include "sockets-config.h" +#include "IFile.h" +#include + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +/** IFile implementation of a disk file. + \ingroup file */ +class File : public IFile +{ +public: + File(); + ~File(); + + bool fopen(const std::string&, const std::string&); + void fclose(); + + size_t fread(char *, size_t, size_t) const; + size_t fwrite(const char *, size_t, size_t); + + char *fgets(char *, int) const; + void fprintf(const char *format, ...); + + off_t size() const; + bool eof() const; + + void reset_read() const; + void reset_write(); + +private: + File(const File& ) {} // copy constructor + File& operator=(const File& ) { return *this; } // assignment operator + + std::string m_path; + std::string m_mode; + FILE *m_fil; + mutable long m_rptr; + long m_wptr; +}; + + +#ifdef SOCKETS_NAMESPACE +} +#endif + +#endif // _SOCKETS_File_H + + diff --git a/dep/sockets/include/IFile.h b/dep/sockets/include/IFile.h new file mode 100644 index 00000000000..657c8a4b1d9 --- /dev/null +++ b/dep/sockets/include/IFile.h @@ -0,0 +1,71 @@ +/** \file IFile.h + ** \date 2005-04-25 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2004-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifndef _SOCKETS_IFile_H +#define _SOCKETS_IFile_H + +#include "sockets-config.h" +#include + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +/** \defgroup file File handling */ +/** Pure virtual file I/O interface. + \ingroup file */ +class IFile +{ +public: + virtual ~IFile() {} + + virtual bool fopen(const std::string&, const std::string&) = 0; + virtual void fclose() = 0; + + virtual size_t fread(char *, size_t, size_t) const = 0; + virtual size_t fwrite(const char *, size_t, size_t) = 0; + + virtual char *fgets(char *, int) const = 0; + virtual void fprintf(const char *format, ...) = 0; + + virtual off_t size() const = 0; + virtual bool eof() const = 0; + + virtual void reset_read() const = 0; + virtual void reset_write() = 0; + +}; + +#ifdef SOCKETS_NAMESPACE +} +#endif + +#endif // _SOCKETS_IFile_H + + diff --git a/dep/sockets/include/ISocketHandler.h b/dep/sockets/include/ISocketHandler.h new file mode 100644 index 00000000000..940783c104b --- /dev/null +++ b/dep/sockets/include/ISocketHandler.h @@ -0,0 +1,231 @@ +/** \file ISocketHandler.h + ** \date 2004-02-13 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2004-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifndef _SOCKETS_ISocketHandler_H +#define _SOCKETS_ISocketHandler_H +#include "sockets-config.h" + +#include + +#include "socket_include.h" +#include "Socket.h" +#include "StdLog.h" + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +typedef enum { + LIST_CALLONCONNECT = 0, +#ifdef ENABLE_DETACH + LIST_DETACH, +#endif + LIST_TIMEOUT, + LIST_RETRY, + LIST_CLOSE +} list_t; + +class SocketAddress; +class Mutex; + +/** Socket container class, event generator. + \ingroup basic */ +class ISocketHandler +{ + friend class Socket; + +public: + /** Connection pool class for internal use by the ISocketHandler. + \ingroup internal */ +#ifdef ENABLE_POOL + class PoolSocket : public Socket + { + public: + PoolSocket(ISocketHandler& h,Socket *src) : Socket(h) { + CopyConnection( src ); + SetIsClient(); + } + + void OnRead() { + Handler().LogError(this, "OnRead", 0, "data on hibernating socket", LOG_LEVEL_FATAL); + SetCloseAndDelete(); + } + void OnOptions(int,int,int,SOCKET) {} + + }; +#endif + +public: + virtual ~ISocketHandler() {} + + /** Get mutex reference for threadsafe operations. */ + virtual Mutex& GetMutex() const = 0; + + /** Register StdLog object for error callback. + \param log Pointer to log class */ + virtual void RegStdLog(StdLog *log) = 0; + + /** Log error to log class for print out / storage. */ + virtual void LogError(Socket *p,const std::string& user_text,int err,const std::string& sys_err,loglevel_t t = LOG_LEVEL_WARNING) = 0; + + // ------------------------------------------------------------------------- + // Socket stuff + // ------------------------------------------------------------------------- + /** Add socket instance to socket map. Removal is always automatic. */ + virtual void Add(Socket *) = 0; +private: + /** Remove socket from socket map, used by Socket class. */ + virtual void Remove(Socket *) = 0; +public: + /** Get status of read/write/exception file descriptor set for a socket. */ + virtual void Get(SOCKET s,bool& r,bool& w,bool& e) = 0; + /** Set read/write/exception file descriptor sets (fd_set). */ + virtual void Set(SOCKET s,bool bRead,bool bWrite,bool bException = true) = 0; + + /** Wait for events, generate callbacks. */ + virtual int Select(long sec,long usec) = 0; + /** This method will not return until an event has been detected. */ + virtual int Select() = 0; + /** Wait for events, generate callbacks. */ + virtual int Select(struct timeval *tsel) = 0; + + /** Check that a socket really is handled by this socket handler. */ + virtual bool Valid(Socket *) = 0; + /** Return number of sockets handled by this handler. */ + virtual size_t GetCount() = 0; + + /** Override and return false to deny all incoming connections. + \param p ListenSocket class pointer (use GetPort to identify which one) */ + virtual bool OkToAccept(Socket *p) = 0; + + /** Called by Socket when a socket changes state. */ + virtual void AddList(SOCKET s,list_t which_one,bool add) = 0; + + // ------------------------------------------------------------------------- + // Connection pool + // ------------------------------------------------------------------------- +#ifdef ENABLE_POOL + /** Find available open connection (used by connection pool). */ + virtual ISocketHandler::PoolSocket *FindConnection(int type,const std::string& protocol,SocketAddress&) = 0; + /** Enable connection pool (by default disabled). */ + virtual void EnablePool(bool = true) = 0; + /** Check pool status. + \return true if connection pool is enabled */ + virtual bool PoolEnabled() = 0; +#endif // ENABLE_POOL + + // ------------------------------------------------------------------------- + // Socks4 + // ------------------------------------------------------------------------- +#ifdef ENABLE_SOCKS4 + /** Set socks4 server ip that all new tcp sockets should use. */ + virtual void SetSocks4Host(ipaddr_t) = 0; + /** Set socks4 server hostname that all new tcp sockets should use. */ + virtual void SetSocks4Host(const std::string& ) = 0; + /** Set socks4 server port number that all new tcp sockets should use. */ + virtual void SetSocks4Port(port_t) = 0; + /** Set optional socks4 userid. */ + virtual void SetSocks4Userid(const std::string& ) = 0; + /** If connection to socks4 server fails, immediately try direct connection to final host. */ + virtual void SetSocks4TryDirect(bool = true) = 0; + /** Get socks4 server ip. + \return socks4 server ip */ + virtual ipaddr_t GetSocks4Host() = 0; + /** Get socks4 port number. + \return socks4 port number */ + virtual port_t GetSocks4Port() = 0; + /** Get socks4 userid (optional). + \return socks4 userid */ + virtual const std::string& GetSocks4Userid() = 0; + /** Check status of socks4 try direct flag. + \return true if direct connection should be tried if connection to socks4 server fails */ + virtual bool Socks4TryDirect() = 0; +#endif // ENABLE_SOCKS4 + + // ------------------------------------------------------------------------- + // DNS resolve server + // ------------------------------------------------------------------------- +#ifdef ENABLE_RESOLVER + /** Enable asynchronous DNS. + \param port Listen port of asynchronous dns server */ + virtual void EnableResolver(port_t = 16667) = 0; + /** Check resolver status. + \return true if resolver is enabled */ + virtual bool ResolverEnabled() = 0; + /** Queue a dns request. + \param host Hostname to be resolved + \param port Port number will be echoed in Socket::OnResolved callback */ + virtual int Resolve(Socket *,const std::string& host,port_t port) = 0; +#ifdef ENABLE_IPV6 + virtual int Resolve6(Socket *,const std::string& host,port_t port) = 0; +#endif + /** Do a reverse dns lookup. */ + virtual int Resolve(Socket *,ipaddr_t a) = 0; +#ifdef ENABLE_IPV6 + virtual int Resolve(Socket *,in6_addr& a) = 0; +#endif + /** Get listen port of asynchronous dns server. */ + virtual port_t GetResolverPort() = 0; + /** Resolver thread ready for queries. */ + virtual bool ResolverReady() = 0; + /** Returns true if socket waiting for a resolve event. */ + virtual bool Resolving(Socket *) = 0; +#endif // ENABLE_RESOLVER + +#ifdef ENABLE_TRIGGERS + /** Fetch unique trigger id. */ + virtual int TriggerID(Socket *src) = 0; + /** Subscribe socket to trigger id. */ + virtual bool Subscribe(int id, Socket *dst) = 0; + /** Unsubscribe socket from trigger id. */ + virtual bool Unsubscribe(int id, Socket *dst) = 0; + /** Execute OnTrigger for subscribed sockets. + \param id Trigger ID + \param data Data passed from source to destination + \param erase Empty trigger id source and destination maps if 'true', + Leave them in place if 'false' - if a trigger should be called many times */ + virtual void Trigger(int id, Socket::TriggerData& data, bool erase = true) = 0; +#endif // ENABLE_TRIGGERS + +#ifdef ENABLE_DETACH + /** Indicates that the handler runs under SocketThread. */ + virtual void SetSlave(bool x = true) = 0; + /** Indicates that the handler runs under SocketThread. */ + virtual bool IsSlave() = 0; +#endif // ENABLE_DETACH + +}; + +#ifdef SOCKETS_NAMESPACE +} +#endif + +#endif // _SOCKETS_ISocketHandler_H + + diff --git a/dep/sockets/include/Ipv4Address.h b/dep/sockets/include/Ipv4Address.h new file mode 100644 index 00000000000..71d925254e9 --- /dev/null +++ b/dep/sockets/include/Ipv4Address.h @@ -0,0 +1,95 @@ +/** + ** \file Ipv4Address.h + ** \date 2006-09-21 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2007 Anders Hedstrom + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifndef _SOCKETS_Ipv4Address_H +#define _SOCKETS_Ipv4Address_H + +#include "sockets-config.h" +#include "SocketAddress.h" + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +/* Ipv4 address implementation. + \ingroup basic */ +class Ipv4Address : public SocketAddress +{ +public: + /** Create empty Ipv4 address structure. + \param port Port number */ + Ipv4Address(port_t port = 0); + /** Create Ipv4 address structure. + \param a Socket address in network byte order (as returned by Utility::u2ip) + \param port Port number in host byte order */ + Ipv4Address(ipaddr_t a,port_t port); + /** Create Ipv4 address structure. + \param a Socket address in network byte order + \param port Port number in host byte order */ + Ipv4Address(struct in_addr& a,port_t port); + /** Create Ipv4 address structure. + \param host Hostname to be resolved + \param port Port number in host byte order */ + Ipv4Address(const std::string& host,port_t port); + Ipv4Address(struct sockaddr_in&); + ~Ipv4Address(); + + // SocketAddress implementation + + operator struct sockaddr *(); + operator socklen_t(); + bool operator==(SocketAddress&); + + void SetPort(port_t port); + port_t GetPort(); + + void SetAddress(struct sockaddr *sa); + int GetFamily(); + + bool IsValid(); + std::auto_ptr GetCopy(); + + /** Convert address struct to text. */ + std::string Convert(bool include_port = false); + std::string Reverse(); + + /** Resolve hostname. */ +static bool Resolve(const std::string& hostname,struct in_addr& a); + /** Reverse resolve (IP to hostname). */ +static bool Reverse(struct in_addr& a,std::string& name); + /** Convert address struct to text. */ +static std::string Convert(struct in_addr& a); + +private: + Ipv4Address(const Ipv4Address& ) {} // copy constructor + Ipv4Address& operator=(const Ipv4Address& ) { return *this; } // assignment operator + struct sockaddr_in m_addr; + bool m_valid; +}; + + +#ifdef SOCKETS_NAMESPACE +} // namespace SOCKETS_NAMESPACE { +#endif +#endif // _SOCKETS_Ipv4Address_H + + diff --git a/dep/sockets/include/Ipv6Address.h b/dep/sockets/include/Ipv6Address.h new file mode 100644 index 00000000000..20c68d8c92d --- /dev/null +++ b/dep/sockets/include/Ipv6Address.h @@ -0,0 +1,105 @@ +/** + ** \file Ipv6Address.h + ** \date 2006-09-21 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2007 Anders Hedstrom + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifndef _SOCKETS_Ipv6Address_H +#define _SOCKETS_Ipv6Address_H +#include "sockets-config.h" +#ifdef ENABLE_IPV6 + +#include "SocketAddress.h" +#ifdef IPPROTO_IPV6 +#if defined( _WIN32) && !defined(__CYGWIN__) +typedef unsigned __int32 uint32_t; +#endif + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +/** Ipv6 address implementation. + \ingroup basic */ +class Ipv6Address : public SocketAddress +{ +public: + /** Create empty Ipv6 address structure. + \param port Port number */ + Ipv6Address(port_t port = 0); + /** Create Ipv6 address structure. + \param a Socket address in network byte order + \param port Port number in host byte order */ + Ipv6Address(struct in6_addr& a,port_t port); + /** Create Ipv6 address structure. + \param host Hostname to be resolved + \param port Port number in host byte order */ + Ipv6Address(const std::string& host,port_t port); + Ipv6Address(struct sockaddr_in6&); + ~Ipv6Address(); + + // SocketAddress implementation + + operator struct sockaddr *(); + operator socklen_t(); + bool operator==(SocketAddress&); + + void SetPort(port_t port); + port_t GetPort(); + + void SetAddress(struct sockaddr *sa); + int GetFamily(); + + bool IsValid(); + std::auto_ptr GetCopy(); + + /** Convert address struct to text. */ + std::string Convert(bool include_port = false); + std::string Reverse(); + + /** Resolve hostname. */ +static bool Resolve(const std::string& hostname,struct in6_addr& a); + /** Reverse resolve (IP to hostname). */ +static bool Reverse(struct in6_addr& a,std::string& name); + /** Convert address struct to text. */ +static std::string Convert(struct in6_addr& a,bool mixed = false); + + void SetFlowinfo(uint32_t); + uint32_t GetFlowinfo(); +#ifndef _WIN32 + void SetScopeId(uint32_t); + uint32_t GetScopeId(); +#endif + +private: + Ipv6Address(const Ipv6Address& ) {} // copy constructor + Ipv6Address& operator=(const Ipv6Address& ) { return *this; } // assignment operator + struct sockaddr_in6 m_addr; + bool m_valid; +}; + + +#ifdef SOCKETS_NAMESPACE +} // namespace SOCKETS_NAMESPACE { +#endif +#endif // IPPROTO_IPV6 +#endif // ENABLE_IPV6 +#endif // _SOCKETS_Ipv6Address_H + + diff --git a/dep/sockets/include/ListenSocket.h b/dep/sockets/include/ListenSocket.h new file mode 100644 index 00000000000..8934a809d0e --- /dev/null +++ b/dep/sockets/include/ListenSocket.h @@ -0,0 +1,418 @@ +/** \file ListenSocket.h + ** \date 2004-02-13 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2004-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifndef _SOCKETS_ListenSocket_H +#define _SOCKETS_ListenSocket_H +#include "sockets-config.h" + +#ifdef _WIN32 +#include +#else +#include +#endif + +#include "ISocketHandler.h" +#include "Socket.h" +#include "Utility.h" +#include "SctpSocket.h" +#include "Ipv4Address.h" +#include "Ipv6Address.h" +#ifdef ENABLE_EXCEPTIONS +#include "Exception.h" +#endif + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +/** Binds incoming port number to new Socket class X. + \ingroup basic */ +template +class ListenSocket : public Socket +{ +public: + /** Constructor. + \param h ISocketHandler reference + \param use_creator Optional use of creator (default true) */ + ListenSocket(ISocketHandler& h,bool use_creator = true) : Socket(h), m_depth(0), m_creator(NULL) + ,m_bHasCreate(false) + { + if (use_creator) + { + m_creator = new X(h); + Socket *tmp = m_creator -> Create(); + if (tmp && dynamic_cast(tmp)) + { + m_bHasCreate = true; + } + if (tmp) + { + delete tmp; + } + } + } + ~ListenSocket() { + if (m_creator) + { + delete m_creator; + } + } + + /** Close file descriptor. */ + int Close() { + if (GetSocket() != INVALID_SOCKET) + { + closesocket(GetSocket()); + } + return 0; + } + + /** Bind and listen to any interface. + \param port Port (0 is random) + \param depth Listen queue depth */ + int Bind(port_t port,int depth = 20) { +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + if (IsIpv6()) + { + Ipv6Address ad(port); + return Bind(ad, depth); + } + else +#endif +#endif + { + Ipv4Address ad(port); + return Bind(ad, depth); + } + } + + int Bind(SocketAddress& ad,int depth) { +#ifdef USE_SCTP + if (dynamic_cast(m_creator)) + { + return Bind(ad, "sctp", depth); + } +#endif + return Bind(ad, "tcp", depth); + } + + /** Bind and listen to any interface, with optional protocol. + \param port Port (0 is random) + \param protocol Network protocol + \param depth Listen queue depth */ + int Bind(port_t port,const std::string& protocol,int depth = 20) { +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + if (IsIpv6()) + { + Ipv6Address ad(port); + return Bind(ad, protocol, depth); + } + else +#endif +#endif + { + Ipv4Address ad(port); + return Bind(ad, protocol, depth); + } + } + + /** Bind and listen to specific interface. + \param intf Interface hostname + \param port Port (0 is random) + \param depth Listen queue depth */ + int Bind(const std::string& intf,port_t port,int depth = 20) { +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + if (IsIpv6()) + { + Ipv6Address ad(intf, port); + if (ad.IsValid()) + { + return Bind(ad, depth); + } + Handler().LogError(this, "Bind", 0, "name resolution of interface name failed", LOG_LEVEL_FATAL); + return -1; + } + else +#endif +#endif + { + Ipv4Address ad(intf, port); + if (ad.IsValid()) + { + return Bind(ad, depth); + } + Handler().LogError(this, "Bind", 0, "name resolution of interface name failed", LOG_LEVEL_FATAL); + return -1; + } + } + + /** Bind and listen to specific interface. + \param intf Interface hostname + \param port Port (0 is random) + \param protocol Network protocol + \param depth Listen queue depth */ + int Bind(const std::string& intf,port_t port,const std::string& protocol,int depth = 20) { +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + if (IsIpv6()) + { + Ipv6Address ad(intf, port); + if (ad.IsValid()) + { + return Bind(ad, protocol, depth); + } + Handler().LogError(this, "Bind", 0, "name resolution of interface name failed", LOG_LEVEL_FATAL); + return -1; + } + else +#endif +#endif + { + Ipv4Address ad(intf, port); + if (ad.IsValid()) + { + return Bind(ad, protocol, depth); + } + Handler().LogError(this, "Bind", 0, "name resolution of interface name failed", LOG_LEVEL_FATAL); + return -1; + } + } + + /** Bind and listen to ipv4 interface. + \param a Ipv4 interface address + \param port Port (0 is random) + \param depth Listen queue depth */ + int Bind(ipaddr_t a,port_t port,int depth = 20) { + Ipv4Address ad(a, port); +#ifdef USE_SCTP + if (dynamic_cast(m_creator)) + { + return Bind(ad, "sctp", depth); + } +#endif + return Bind(ad, "tcp", depth); + } + /** Bind and listen to ipv4 interface. + \param a Ipv4 interface address + \param port Port (0 is random) + \param protocol Network protocol + \param depth Listen queue depth */ + int Bind(ipaddr_t a,port_t port,const std::string& protocol,int depth) { + Ipv4Address ad(a, port); + return Bind(ad, protocol, depth); + } + +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + /** Bind and listen to ipv6 interface. + \param a Ipv6 interface address + \param port Port (0 is random) + \param depth Listen queue depth */ + int Bind(in6_addr a,port_t port,int depth = 20) { + Ipv6Address ad(a, port); +#ifdef USE_SCTP + if (dynamic_cast(m_creator)) + { + return Bind(ad, "sctp", depth); + } +#endif + return Bind(ad, "tcp", depth); + } + /** Bind and listen to ipv6 interface. + \param a Ipv6 interface address + \param port Port (0 is random) + \param protocol Network protocol + \param depth Listen queue depth */ + int Bind(in6_addr a,port_t port,const std::string& protocol,int depth) { + Ipv6Address ad(a, port); + return Bind(ad, protocol, depth); + } +#endif +#endif + + /** Bind and listen to network interface. + \param ad Interface address + \param protocol Network protocol + \param depth Listen queue depth */ + int Bind(SocketAddress& ad,const std::string& protocol,int depth) { + SOCKET s; + if ( (s = CreateSocket(ad.GetFamily(), SOCK_STREAM, protocol)) == INVALID_SOCKET) + { + return -1; + } + if (bind(s, ad, ad) == -1) + { + Handler().LogError(this, "bind", Errno, StrError(Errno), LOG_LEVEL_FATAL); + closesocket(s); +#ifdef ENABLE_EXCEPTIONS + throw Exception("bind() failed for port " + Utility::l2string(ad.GetPort()) + ": " + StrError(Errno)); +#endif + return -1; + } + if (listen(s, depth) == -1) + { + Handler().LogError(this, "listen", Errno, StrError(Errno), LOG_LEVEL_FATAL); + closesocket(s); +#ifdef ENABLE_EXCEPTIONS + throw Exception("listen() failed for port " + Utility::l2string(ad.GetPort()) + ": " + StrError(Errno)); +#endif + return -1; + } + m_depth = depth; + Attach(s); + return 0; + } + + /** Return assigned port number. */ + port_t GetPort() + { + return GetSockPort(); + } + + /** Return listen queue depth. */ + int GetDepth() + { + return m_depth; + } + + /** OnRead on a ListenSocket receives an incoming connection. */ + void OnRead() + { + struct sockaddr sa; + socklen_t sa_len = sizeof(struct sockaddr); + SOCKET a_s = accept(GetSocket(), &sa, &sa_len); + + if (a_s == INVALID_SOCKET) + { + Handler().LogError(this, "accept", Errno, StrError(Errno), LOG_LEVEL_ERROR); + return; + } + if (!Handler().OkToAccept(this)) + { + Handler().LogError(this, "accept", -1, "Not OK to accept", LOG_LEVEL_WARNING); + closesocket(a_s); + return; + } + if (Handler().GetCount() >= FD_SETSIZE) + { + Handler().LogError(this, "accept", (int)Handler().GetCount(), "ISocketHandler fd_set limit reached", LOG_LEVEL_FATAL); + closesocket(a_s); + return; + } + Socket *tmp = m_bHasCreate ? m_creator -> Create() : new X(Handler()); +#ifdef ENABLE_IPV6 + tmp -> SetIpv6( IsIpv6() ); +#endif + tmp -> SetParent(this); + tmp -> Attach(a_s); + tmp -> SetNonblocking(true); + { +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + if (sa_len == sizeof(struct sockaddr_in6)) + { + struct sockaddr_in6 *p = (struct sockaddr_in6 *)&sa; + if (p -> sin6_family == AF_INET6) + { + Ipv6Address ad(p -> sin6_addr,ntohs(p -> sin6_port)); + ad.SetFlowinfo(p -> sin6_flowinfo); +#ifndef _WIN32 + ad.SetScopeId(p -> sin6_scope_id); +#endif + tmp -> SetRemoteAddress(ad); + } + } +#endif +#endif + if (sa_len == sizeof(struct sockaddr_in)) + { + struct sockaddr_in *p = (struct sockaddr_in *)&sa; + if (p -> sin_family == AF_INET) + { + Ipv4Address ad(p -> sin_addr,ntohs(p -> sin_port)); + tmp -> SetRemoteAddress(ad); + } + } + } + tmp -> SetConnected(true); + tmp -> Init(); + tmp -> SetDeleteByHandler(true); + Handler().Add(tmp); +#ifdef HAVE_OPENSSL + if (tmp -> IsSSL()) // SSL Enabled socket + { + // %! OnSSLAccept calls SSLNegotiate that can finish in this one call. + // %! If that happens and negotiation fails, the 'tmp' instance is + // %! still added to the list of active sockets in the sockethandler. + // %! See bugfix for this in SocketHandler::Select - don't Set rwx + // %! flags if CloseAndDelete() flag is true. + // %! An even better fugbix (see TcpSocket::OnSSLAccept) now avoids + // %! the Add problem altogether, so ignore the above. + // %! (OnSSLAccept does no longer call SSLNegotiate().) + tmp -> OnSSLAccept(); + } + else +#endif + { + tmp -> OnAccept(); + } + } + + /** Please don't use this method. + "accept()" is handled automatically in the OnRead() method. */ + virtual SOCKET Accept(SOCKET socket, struct sockaddr *saptr, socklen_t *lenptr) + { + return accept(socket, saptr, lenptr); + } + + bool HasCreator() { return m_bHasCreate; } + + void OnOptions(int,int,int,SOCKET) { + SetSoReuseaddr(true); + } + +protected: + ListenSocket(const ListenSocket& s) : Socket(s) {} +private: + ListenSocket& operator=(const ListenSocket& ) { return *this; } + int m_depth; + X *m_creator; + bool m_bHasCreate; +}; + +#ifdef SOCKETS_NAMESPACE +} +#endif + +#endif // _SOCKETS_ListenSocket_H + + diff --git a/dep/sockets/include/Lock.h b/dep/sockets/include/Lock.h new file mode 100644 index 00000000000..f3bb9273920 --- /dev/null +++ b/dep/sockets/include/Lock.h @@ -0,0 +1,58 @@ +/** \file Lock.h + ** \date 2005-08-22 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2005,2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifndef _SOCKETS_Lock_H +#define _SOCKETS_Lock_H + +#include "sockets-config.h" +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +class Mutex; + +/** Mutex encapsulation class. + \ingroup threading */ +class Lock +{ +public: + Lock(Mutex&); + ~Lock(); + +private: + Mutex& m_mutex; +}; + + +#ifdef SOCKETS_NAMESPACE +} +#endif +#endif // _SOCKETS_Lock_H + + diff --git a/dep/sockets/include/Mutex.h b/dep/sockets/include/Mutex.h new file mode 100644 index 00000000000..e42a57c3262 --- /dev/null +++ b/dep/sockets/include/Mutex.h @@ -0,0 +1,68 @@ +/** \file Mutex.h + ** \date 2004-10-30 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2004-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifndef _SOCKETS_Mutex_H +#define _SOCKETS_Mutex_H + +#include "sockets-config.h" +#ifndef _WIN32 +#include +#else +#include +#endif + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +/** Mutex container class, used by Lock. + \ingroup threading */ +class Mutex +{ + friend class Lock; +public: + Mutex(); + ~Mutex(); + + void Lock(); + void Unlock(); +private: +#ifdef _WIN32 + HANDLE m_mutex; +#else + pthread_mutex_t m_mutex; +#endif +}; + +#ifdef SOCKETS_NAMESPACE +} +#endif +#endif // _SOCKETS_Mutex_H + + diff --git a/dep/sockets/include/Parse.h b/dep/sockets/include/Parse.h new file mode 100644 index 00000000000..52bd9327e28 --- /dev/null +++ b/dep/sockets/include/Parse.h @@ -0,0 +1,100 @@ +/** \file Parse.h - parse a string + ** + ** Written: 1999-Feb-10 grymse@alhem.net + **/ + +/* +Copyright (C) 1999-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ + +#ifndef _SOCKETS_Parse_H +#define _SOCKETS_Parse_H + +#include "sockets-config.h" +#ifdef _MSC_VER +#pragma warning(disable:4514) +#endif + +#include + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +/***************************************************/ +/* interface of class Parse */ + +/** Splits a string whatever way you want. + \ingroup util */ +class Parse +{ +public: + Parse(); + Parse(const std::string&); + Parse(const std::string&,const std::string&); + Parse(const std::string&,const std::string&,short); + ~Parse(); + short issplit(const char); + void getsplit(); + void getsplit(std::string&); + std::string getword(); + void getword(std::string&); + void getword(std::string&,std::string&,int); + std::string getrest(); + void getrest(std::string&); + long getvalue(); + void setbreak(const char); + int getwordlen(); + int getrestlen(); + void enablebreak(const char c) { + pa_enable = c; + } + void disablebreak(const char c) { + pa_disable = c; + } + void getline(); + void getline(std::string&); + size_t getptr() { return pa_the_ptr; } + void EnableQuote(bool b) { pa_quote = b; } + +private: + std::string pa_the_str; + std::string pa_splits; + std::string pa_ord; + size_t pa_the_ptr; + char pa_breakchar; + char pa_enable; + char pa_disable; + short pa_nospace; + bool pa_quote; +}; + +#ifdef SOCKETS_NAMESPACE +} +#endif + +#endif // _SOCKETS_Parse_H + + diff --git a/dep/sockets/include/ResolvServer.h b/dep/sockets/include/ResolvServer.h new file mode 100644 index 00000000000..409c9b7a619 --- /dev/null +++ b/dep/sockets/include/ResolvServer.h @@ -0,0 +1,72 @@ +/** \file ResolvServer.h + ** \date 2005-03-24 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2004-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifndef _SOCKETS_ResolvServer_H +#define _SOCKETS_ResolvServer_H +#include "sockets-config.h" +#ifdef ENABLE_RESOLVER +#include "socket_include.h" +#include "Thread.h" + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +/** \defgroup async Asynchronous DNS */ +/** Async DNS resolver thread. + \ingroup async */ +class ResolvServer : public Thread +{ +public: + ResolvServer(port_t); + ~ResolvServer(); + + void Run(); + void Quit(); + + bool Ready(); + +private: + ResolvServer(const ResolvServer& ) {} // copy constructor + ResolvServer& operator=(const ResolvServer& ) { return *this; } // assignment operator + + bool m_quit; + port_t m_port; + bool m_ready; +}; + + +#ifdef SOCKETS_NAMESPACE +} +#endif + +#endif // ENABLE_RESOLVER +#endif // _SOCKETS_ResolvServer_H + + diff --git a/dep/sockets/include/ResolvSocket.h b/dep/sockets/include/ResolvSocket.h new file mode 100644 index 00000000000..60743736e08 --- /dev/null +++ b/dep/sockets/include/ResolvSocket.h @@ -0,0 +1,105 @@ +/** \file ResolvSocket.h + ** \date 2005-03-24 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2004-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifndef _SOCKETS_ResolvSocket_H +#define _SOCKETS_ResolvSocket_H +#include "sockets-config.h" +#ifdef ENABLE_RESOLVER +#include "TcpSocket.h" +#include + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +class Mutex; + +/** Async DNS resolver socket. + \ingroup async */ +class ResolvSocket : public TcpSocket +{ + typedef std::map > cache_t; /* host, result */ + typedef std::map > timeout_t; /* host, time */ + +public: + ResolvSocket(ISocketHandler&); + ResolvSocket(ISocketHandler&, Socket *parent, const std::string& host, port_t port, bool ipv6 = false); + ResolvSocket(ISocketHandler&, Socket *parent, ipaddr_t); +#ifdef ENABLE_IPV6 + ResolvSocket(ISocketHandler&, Socket *parent, in6_addr&); +#endif + ~ResolvSocket(); + + void OnAccept() { m_bServer = true; } + void OnLine(const std::string& line); + void OnDetached(); + void OnDelete(); + + void SetId(int x) { m_resolv_id = x; } + int GetId() { return m_resolv_id; } + + void OnConnect(); + +#ifdef ENABLE_IPV6 + void SetResolveIpv6(bool x = true) { m_resolve_ipv6 = x; } +#endif + +private: + ResolvSocket(const ResolvSocket& s) : TcpSocket(s) {} // copy constructor + ResolvSocket& operator=(const ResolvSocket& ) { return *this; } // assignment operator + + std::string m_query; + std::string m_data; + bool m_bServer; + Socket *m_parent; + int m_resolv_id; + std::string m_resolv_host; + port_t m_resolv_port; + ipaddr_t m_resolv_address; +#ifdef ENABLE_IPV6 + bool m_resolve_ipv6; + in6_addr m_resolv_address6; +#endif + static cache_t m_cache; + static timeout_t m_cache_to; + static Mutex m_cache_mutex; + bool m_cached; +}; + + +#ifdef SOCKETS_NAMESPACE +} +#endif + +#endif // ENABLE_RESOLVER +#endif // _SOCKETS_ResolvSocket_H + + diff --git a/dep/sockets/include/SctpSocket.h b/dep/sockets/include/SctpSocket.h new file mode 100644 index 00000000000..ed507fb1880 --- /dev/null +++ b/dep/sockets/include/SctpSocket.h @@ -0,0 +1,108 @@ +/** + ** \file SctpSocket.h + ** \date 2006-09-04 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2007 Anders Hedstrom + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifndef _SOCKETS_SctpSocket_H +#define _SOCKETS_SctpSocket_H +#include "sockets-config.h" + +#include "StreamSocket.h" +#ifdef USE_SCTP +#include + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +#define SCTP_BUFSIZE_READ 16400 + +class SocketAddress; + +class SctpSocket : public StreamSocket +{ +public: + /** SctpSocket constructor. + \param h Owner + \param type SCTP_STREAM or SCTP_SEQPACKET */ + SctpSocket(ISocketHandler& h,int type); + ~SctpSocket(); + + /** bind() */ + int Bind(const std::string&,port_t); + int Bind(SocketAddress&); + /** sctp_bindx() */ + int AddAddress(const std::string&,port_t); + int AddAddress(SocketAddress&); + /** sctp_bindx() */ + int RemoveAddress(const std::string&,port_t); + int RemoveAddress(SocketAddress&); + + /** connect() */ + int Open(const std::string&,port_t); + int Open(SocketAddress&); + + /** Connect timeout callback. */ + void OnConnectTimeout(); +#ifdef _WIN32 + /** Connection failed reported as exception on win32 */ + void OnException(); +#endif + +#ifndef SOLARIS + /** sctp_connectx() */ + int AddConnection(const std::string&,port_t); + int AddConnection(SocketAddress&); +#endif + + /** Get peer addresses of an association. */ + int getpaddrs(sctp_assoc_t id,std::list&); + /** Get all bound addresses of an association. */ + int getladdrs(sctp_assoc_t id,std::list&); + + /** sctp_peeloff */ + int PeelOff(sctp_assoc_t id); + + /** recvmsg callback */ + virtual void OnReceiveMessage(const char *buf,size_t sz,struct sockaddr *sa,socklen_t sa_len,struct sctp_sndrcvinfo *sinfo,int msg_flags) = 0; + + void OnOptions(int,int,int,SOCKET) {} + + virtual int Protocol(); + +protected: + SctpSocket(const SctpSocket& s) : StreamSocket(s) {} + void OnRead(); + void OnWrite(); + +private: + SctpSocket& operator=(const SctpSocket& s) { return *this; } + int m_type; ///< SCTP_STREAM or SCTP_SEQPACKET + char *m_buf; ///< Temporary receive buffer +}; + +#ifdef SOCKETS_NAMESPACE +} // namespace SOCKETS_NAMESPACE +#endif + +#endif // USE_SCTP +#endif // _SOCKETS_SctpSocket_H + + diff --git a/dep/sockets/include/Socket.h b/dep/sockets/include/Socket.h new file mode 100644 index 00000000000..23a806b5ea1 --- /dev/null +++ b/dep/sockets/include/Socket.h @@ -0,0 +1,735 @@ +/** \file Socket.h + ** \date 2004-02-13 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2004-2007 Anders Hedstrom + +This software is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifndef _SOCKETS_Socket_H +#define _SOCKETS_Socket_H +#include "sockets-config.h" + +#include +#include +#include +#ifdef HAVE_OPENSSL +#include +#endif + +#include "socket_include.h" +#include +#include "SocketAddress.h" +#include "Thread.h" + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +class ISocketHandler; +class SocketAddress; +class IFile; + +/** \defgroup basic Basic sockets */ +/** Socket base class. + \ingroup basic */ +class Socket +{ + friend class ISocketHandler; +#ifdef ENABLE_DETACH + /** Detached socket run thread. + \ingroup internal */ + class SocketThread : public Thread + { + public: + SocketThread(Socket *p); + ~SocketThread(); + + void Run(); + + private: + Socket *GetSocket() const { return m_socket; } + SocketThread(const SocketThread& s) : m_socket(s.GetSocket()) {} + SocketThread& operator=(const SocketThread& ) { return *this; } + Socket *m_socket; + }; +#endif // ENABLE_DETACH + +#ifdef ENABLE_TRIGGERS +public: + /** Data pass class from source to destination. */ + class TriggerData + { + public: + TriggerData() : m_src(NULL) {} + virtual ~TriggerData() {} + + Socket *GetSource() const { return m_src; } + void SetSource(Socket *x) { m_src = x; } + + private: + Socket *m_src; + }; +#endif // ENABLE_TRIGGERS + + /** Socket mode flags. */ +/* + enum { + // Socket + SOCK_DEL = 0x01, ///< Delete by handler flag + SOCK_CLOSE = 0x02, ///< Close and delete flag + SOCK_DISABLE_READ = 0x04, ///< Disable checking for read events + SOCK_CONNECTED = 0x08, ///< Socket is connected (tcp/udp) + + SOCK_ERASED_BY_HANDLER = 0x10, ///< Set by handler before delete + // HAVE_OPENSSL + SOCK_ENABLE_SSL = 0x20, ///< Enable SSL for this TcpSocket + SOCK_SSL = 0x40, ///< ssl negotiation mode (TcpSocket) + SOCK_SSL_SERVER = 0x80, ///< True if this is an incoming ssl TcpSocket connection + + // ENABLE_IPV6 + SOCK_IPV6 = 0x0100, ///< This is an ipv6 socket if this one is true + // ENABLE_POOL + SOCK_CLIENT = 0x0200, ///< only client connections are pooled + SOCK_RETAIN = 0x0400, ///< keep connection on close + SOCK_LOST = 0x0800, ///< connection lost + + // ENABLE_SOCKS4 + SOCK_SOCKS4 = 0x1000, ///< socks4 negotiation mode (TcpSocket) + // ENABLE_DETACH + SOCK_DETACH = 0x2000, ///< Socket ordered to detach flag + SOCK_DETACHED = 0x4000, ///< Socket has been detached + // StreamSocket + STREAMSOCK_CONNECTING = 0x8000, ///< Flag indicating connection in progress + + STREAMSOCK_FLUSH_BEFORE_CLOSE = 0x010000L, ///< Send all data before closing (default true) + STREAMSOCK_CALL_ON_CONNECT = 0x020000L, ///< OnConnect will be called next ISocketHandler cycle if true + STREAMSOCK_RETRY_CONNECT = 0x040000L, ///< Try another connection attempt next ISocketHandler cycle + STREAMSOCK_LINE_PROTOCOL = 0x080000L, ///< Line protocol mode flag + + }; +*/ + +public: + /** "Default" constructor */ + Socket(ISocketHandler&); + + virtual ~Socket(); + + /** Socket class instantiation method. Used when a "non-standard" constructor + * needs to be used for the socket class. Note: the socket class still needs + * the "default" constructor with one ISocketHandler& as input parameter. + */ + virtual Socket *Create() { return NULL; } + + /** Returns reference to sockethandler that owns the socket. + If the socket is detached, this is a reference to the slave sockethandler. + */ + ISocketHandler& Handler() const; + + /** Returns reference to sockethandler that owns the socket. + This one always returns the reference to the original sockethandler, + even if the socket is detached. + */ + ISocketHandler& MasterHandler() const; + + /** Called by ListenSocket after accept but before socket is added to handler. + * CTcpSocket uses this to create its ICrypt member variable. + * The ICrypt member variable is created by a virtual method, therefore + * it can't be called directly from the CTcpSocket constructor. + * Also used to determine if incoming HTTP connection is normal (port 80) + * or ssl (port 443). + */ + virtual void Init(); + + /** Create a socket file descriptor. + \param af Address family AF_INET / AF_INET6 / ... + \param type SOCK_STREAM / SOCK_DGRAM / ... + \param protocol "tcp" / "udp" / ... */ + SOCKET CreateSocket(int af,int type,const std::string& protocol = ""); + + /** Assign this socket a file descriptor created + by a call to socket() or otherwise. */ + void Attach(SOCKET s); + + /** Return file descriptor assigned to this socket. */ + SOCKET GetSocket(); + + /** Close connection immediately - internal use. + \sa SetCloseAndDelete */ + virtual int Close(); + + /** Add file descriptor to sockethandler fd_set's. */ + void Set(bool bRead,bool bWrite,bool bException = true); + + /** Returns true when socket file descriptor is valid + and socket is not about to be closed. */ + virtual bool Ready(); + + /** Returns pointer to ListenSocket that created this instance + * on an incoming connection. */ + Socket *GetParent(); + + /** Used by ListenSocket to set parent pointer of newly created + * socket instance. */ + void SetParent(Socket *); + + /** Get listening port from ListenSocket<>. */ + virtual port_t GetPort(); + + /** Set socket non-block operation. */ + bool SetNonblocking(bool); + + /** Set socket non-block operation. */ + bool SetNonblocking(bool, SOCKET); + + /** Total lifetime of instance. */ + time_t Uptime(); + + /** Set address/port of last connect() call. */ + void SetClientRemoteAddress(SocketAddress&); + + /** Get address/port of last connect() call. */ + std::auto_ptr GetClientRemoteAddress(); + + /** Common interface for SendBuf used by Tcp and Udp sockets. */ + virtual void SendBuf(const char *,size_t,int = 0); + + /** Common interface for Send used by Tcp and Udp sockets. */ + virtual void Send(const std::string&,int = 0); + + /** Outgoing traffic counter. */ + virtual uint64_t GetBytesSent(bool clear = false); + + /** Incoming traffic counter. */ + virtual uint64_t GetBytesReceived(bool clear = false); + + // LIST_TIMEOUT + + /** Enable timeout control. 0=disable timeout check. */ + void SetTimeout(time_t secs); + + /** Check timeout. \return true if time limit reached */ + bool Timeout(time_t tnow); + + /** Used by ListenSocket. ipv4 and ipv6 */ + void SetRemoteAddress(SocketAddress&); + + /** \name Event callbacks */ + //@{ + + /** Called when there is something to be read from the file descriptor. */ + virtual void OnRead(); + /** Called when there is room for another write on the file descriptor. */ + virtual void OnWrite(); + /** Called on socket exception. */ + virtual void OnException(); + /** Called before a socket class is deleted by the ISocketHandler. */ + virtual void OnDelete(); + /** Called when a connection has completed. */ + virtual void OnConnect(); + /** Called when an incoming connection has been completed. */ + virtual void OnAccept(); + /** Called when a complete line has been read and the socket is in + * line protocol mode. */ + virtual void OnLine(const std::string& ); + /** Called on connect timeout (5s). */ + virtual void OnConnectFailed(); + /** Called when a client socket is created, to set socket options. + \param family AF_INET, AF_INET6, etc + \param type SOCK_STREAM, SOCK_DGRAM, etc + \param protocol Protocol number (tcp, udp, sctp, etc) + \param s Socket file descriptor + */ + virtual void OnOptions(int family,int type,int protocol,SOCKET s) = 0; + /** Connection retry callback - return false to abort connection attempts */ + virtual bool OnConnectRetry(); +#ifdef ENABLE_RECONNECT + /** a reconnect has been made */ + virtual void OnReconnect(); +#endif + /** TcpSocket: When a disconnect has been detected (recv/SSL_read returns 0 bytes). */ + virtual void OnDisconnect(); + /** Timeout callback. */ + virtual void OnTimeout(); + /** Connection timeout. */ + virtual void OnConnectTimeout(); + //@} + + /** \name Socket mode flags, set/reset */ + //@{ + /** Set delete by handler true when you want the sockethandler to + delete the socket instance after use. */ + void SetDeleteByHandler(bool = true); + /** Check delete by handler flag. + \return true if this instance should be deleted by the sockethandler */ + bool DeleteByHandler(); + + // LIST_CLOSE - conditional event queue + + /** Set close and delete to terminate the connection. */ + void SetCloseAndDelete(bool = true); + /** Check close and delete flag. + \return true if this socket should be closed and the instance removed */ + bool CloseAndDelete(); + + /** Return number of seconds since socket was ordered to close. \sa SetCloseAndDelete */ + time_t TimeSinceClose(); + + /** Ignore read events for an output only socket. */ + void DisableRead(bool x = true); + /** Check ignore read events flag. + \return true if read events should be ignored */ + bool IsDisableRead(); + + /** Set connected status. */ + void SetConnected(bool = true); + /** Check connected status. + \return true if connected */ + bool IsConnected(); + + /** Connection lost - error while reading/writing from a socket - TcpSocket only. */ + void SetLost(); + /** Check connection lost status flag, used by TcpSocket only. + \return true if there was an error while r/w causing the socket to close */ + bool Lost(); + + /** Set flag indicating the socket is being actively deleted by the sockethandler. */ + void SetErasedByHandler(bool x = true); + /** Get value of flag indicating socket is deleted by sockethandler. */ + bool ErasedByHandler(); + + //@} + + /** \name Information about remote connection */ + //@{ + /** Returns address of remote end. */ + std::auto_ptr GetRemoteSocketAddress(); + /** Returns address of remote end: ipv4. */ + ipaddr_t GetRemoteIP4(); +#ifdef ENABLE_IPV6 + /** Returns address of remote end: ipv6. */ +#ifdef IPPROTO_IPV6 + struct in6_addr GetRemoteIP6(); +#endif +#endif + /** Returns remote port number: ipv4 and ipv6. */ + port_t GetRemotePort(); + /** Returns remote ip as string? ipv4 and ipv6. */ + std::string GetRemoteAddress(); + /** ipv4 and ipv6(not implemented) */ + std::string GetRemoteHostname(); + //@} + + /** Returns local port number for bound socket file descriptor. */ + port_t GetSockPort(); + /** Returns local ipv4 address for bound socket file descriptor. */ + ipaddr_t GetSockIP4(); + /** Returns local ipv4 address as text for bound socket file descriptor. */ + std::string GetSockAddress(); +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + /** Returns local ipv6 address for bound socket file descriptor. */ + struct in6_addr GetSockIP6(); + /** Returns local ipv6 address as text for bound socket file descriptor. */ + std::string GetSockAddress6(); +#endif +#endif + // -------------------------------------------------------------------------- + /** @name IP options + When an ip or socket option is available on all of the operating systems + I'm testing on (linux 2.4.x, _win32, macosx, solaris9 intel) they are not + checked with an #ifdef below. + This might cause a compile error on other operating systems. */ + // -------------------------------------------------------------------------- + + // IP options + //@{ + + bool SetIpOptions(const void *p, socklen_t len); + bool SetIpTOS(unsigned char tos); + unsigned char IpTOS(); + bool SetIpTTL(int ttl); + int IpTTL(); + bool SetIpHdrincl(bool x = true); + bool SetIpMulticastTTL(int); + int IpMulticastTTL(); + bool SetMulticastLoop(bool x = true); + bool IpAddMembership(struct ip_mreq&); + bool IpDropMembership(struct ip_mreq&); + +#ifdef IP_PKTINFO + bool SetIpPktinfo(bool x = true); +#endif +#ifdef IP_RECVTOS + bool SetIpRecvTOS(bool x = true); +#endif +#ifdef IP_RECVTTL + bool SetIpRecvTTL(bool x = true); +#endif +#ifdef IP_RECVOPTS + bool SetIpRecvopts(bool x = true); +#endif +#ifdef IP_RETOPTS + bool SetIpRetopts(bool x = true); +#endif +#ifdef IP_RECVERR + bool SetIpRecverr(bool x = true); +#endif +#ifdef IP_MTU_DISCOVER + bool SetIpMtudiscover(bool x = true); +#endif +#ifdef IP_MTU + int IpMtu(); +#endif +#ifdef IP_ROUTER_ALERT + bool SetIpRouterAlert(bool x = true); +#endif +#ifdef LINUX + bool IpAddMembership(struct ip_mreqn&); +#endif +#ifdef LINUX + bool IpDropMembership(struct ip_mreqn&); +#endif + //@} + + // SOCKET options + /** @name Socket Options */ + //@{ + + bool SoAcceptconn(); + bool SetSoBroadcast(bool x = true); + bool SetSoDebug(bool x = true); + int SoError(); + bool SetSoDontroute(bool x = true); + bool SetSoLinger(int onoff, int linger); + bool SetSoOobinline(bool x = true); + bool SetSoRcvlowat(int); + bool SetSoSndlowat(int); + bool SetSoRcvtimeo(struct timeval&); + bool SetSoSndtimeo(struct timeval&); + bool SetSoRcvbuf(int); + int SoRcvbuf(); + bool SetSoSndbuf(int); + int SoSndbuf(); + int SoType(); + bool SetSoReuseaddr(bool x = true); + bool SetSoKeepalive(bool x = true); + +#ifdef SO_BSDCOMPAT + bool SetSoBsdcompat(bool x = true); +#endif +#ifdef SO_BINDTODEVICE + bool SetSoBindtodevice(const std::string& intf); +#endif +#ifdef SO_PASSCRED + bool SetSoPasscred(bool x = true); +#endif +#ifdef SO_PEERCRED + bool SoPeercred(struct ucred& ); +#endif +#ifdef SO_PRIORITY + bool SetSoPriority(int); +#endif +#ifdef SO_RCVBUFFORCE + bool SetSoRcvbufforce(int); +#endif +#ifdef SO_SNDBUFFORCE + bool SetSoSndbufforce(int); +#endif +#ifdef SO_TIMESTAMP + bool SetSoTimestamp(bool x = true); +#endif +#ifdef SO_NOSIGPIPE + bool SetSoNosigpipe(bool x = true); +#endif + //@} + + // TCP options in TcpSocket.h/TcpSocket.cpp + +#ifdef HAVE_OPENSSL + /** @name SSL Support */ + //@{ + /** SSL client/server support - internal use. \sa TcpSocket */ + virtual void OnSSLConnect(); + /** SSL client/server support - internal use. \sa TcpSocket */ + virtual void OnSSLAccept(); + /** SSL negotiation failed for client connect. */ + virtual void OnSSLConnectFailed(); + /** SSL negotiation failed for server accept. */ + virtual void OnSSLAcceptFailed(); + /** new SSL support */ + virtual bool SSLNegotiate(); + /** Check if SSL is Enabled for this TcpSocket. + \return true if this is a TcpSocket with SSL enabled */ + bool IsSSL(); + /** Enable SSL operation for a TcpSocket. */ + void EnableSSL(bool x = true); + /** Still negotiating ssl connection. + \return true if ssl negotiating is still in progress */ + bool IsSSLNegotiate(); + /** Set flag indicating ssl handshaking still in progress. */ + void SetSSLNegotiate(bool x = true); + /** OnAccept called with SSL Enabled. + \return true if this is a TcpSocket with an incoming SSL connection */ + bool IsSSLServer(); + /** Set flag indicating that this is a TcpSocket with incoming SSL connection. */ + void SetSSLServer(bool x = true); + /** SSL; Get pointer to ssl context structure. */ + virtual SSL_CTX *GetSslContext() { return NULL; } + /** SSL; Get pointer to ssl structure. */ + virtual SSL *GetSsl() { return NULL; } + //@} +#endif // HAVE_OPENSSL + +#ifdef ENABLE_IPV6 + /** Enable ipv6 for this socket. */ + void SetIpv6(bool x = true); + /** Check ipv6 socket. + \return true if this is an ipv6 socket */ + bool IsIpv6(); +#endif + +#ifdef ENABLE_POOL + /** @name Connection Pool */ + //@{ + /** Client = connecting TcpSocket. */ + void SetIsClient(); + /** Socket type from socket() call. */ + void SetSocketType(int x); + /** Socket type from socket() call. */ + int GetSocketType(); + /** Protocol type from socket() call. */ + void SetSocketProtocol(const std::string& x); + /** Protocol type from socket() call. */ + const std::string& GetSocketProtocol(); + /** Instruct a client socket to stay open in the connection pool after use. + If you have connected to a server using tcp, you can call SetRetain + to leave the connection open after your socket instance has been deleted. + The next connection you make to the same server will reuse the already + opened connection, if it is still available. + */ + void SetRetain(); + /** Check retain flag. + \return true if the socket should be moved to connection pool after use */ + bool Retain(); + /** Copy connection parameters from sock. */ + void CopyConnection(Socket *sock); + //@} +#endif // ENABLE_POOL + +#ifdef ENABLE_SOCKS4 + /** \name Socks4 support */ + //@{ + /** Socks4 client support internal use. \sa TcpSocket */ + virtual void OnSocks4Connect(); + /** Socks4 client support internal use. \sa TcpSocket */ + virtual void OnSocks4ConnectFailed(); + /** Socks4 client support internal use. \sa TcpSocket */ + virtual bool OnSocks4Read(); + /** Called when the last write caused the tcp output buffer to + * become empty. */ + /** socket still in socks4 negotiation mode */ + bool Socks4(); + /** Set flag indicating Socks4 handshaking in progress */ + void SetSocks4(bool x = true); + + /** Set socks4 server host address to use */ + void SetSocks4Host(ipaddr_t a); + /** Set socks4 server hostname to use. */ + void SetSocks4Host(const std::string& ); + /** Socks4 server port to use. */ + void SetSocks4Port(port_t p); + /** Provide a socks4 userid if required by the socks4 server. */ + void SetSocks4Userid(const std::string& x); + /** Get the ip address of socks4 server to use. + \return socks4 server host address */ + ipaddr_t GetSocks4Host(); + /** Get the socks4 server port to use. + \return socks4 server port */ + port_t GetSocks4Port(); + /** Get socks4 userid. + \return Socks4 userid */ + const std::string& GetSocks4Userid(); + //@} +#endif // ENABLE_SOCKS4 + +#ifdef ENABLE_RESOLVER + /** \name Asynchronous Resolver */ + //@{ + /** Request an asynchronous dns resolution. + \param host hostname to be resolved + \param port port number passed along for the ride + \return Resolve ID */ + int Resolve(const std::string& host,port_t port = 0); +#ifdef ENABLE_IPV6 + int Resolve6(const std::string& host, port_t port = 0); +#endif + /** Callback returning a resolved address. + \param id Resolve ID from Resolve call + \param a resolved ip address + \param port port number passed to Resolve */ + virtual void OnResolved(int id,ipaddr_t a,port_t port); +#ifdef ENABLE_IPV6 + virtual void OnResolved(int id,in6_addr& a,port_t port); +#endif + /** Request asynchronous reverse dns lookup. + \param a in_addr to be translated */ + int Resolve(ipaddr_t a); +#ifdef ENABLE_IPV6 + int Resolve(in6_addr& a); +#endif + /** Callback returning reverse resolve results. + \param id Resolve ID + \param name Resolved hostname */ + virtual void OnReverseResolved(int id,const std::string& name); + /** Callback indicating failed dns lookup. + \param id Resolve ID */ + virtual void OnResolveFailed(int id); + //@} +#endif // ENABLE_RESOLVER + +#ifdef ENABLE_DETACH + /** \name Thread Support */ + //@{ + /** Callback fires when a new socket thread has started and this + socket is ready for operation again. + \sa ResolvSocket */ + virtual void OnDetached(); + + // LIST_DETACH + + /** Internal use. */ + void SetDetach(bool x = true); + /** Check detach flag. + \return true if the socket should detach to its own thread */ + bool IsDetach(); + + /** Internal use. */ + void SetDetached(bool x = true); + /** Check detached flag. + \return true if the socket runs in its own thread. */ + const bool IsDetached() const; + /** Order this socket to start its own thread and call OnDetached + when ready for operation. */ + bool Detach(); + /** Store the slave sockethandler pointer. */ + void SetSlaveHandler(ISocketHandler *); + /** Create new thread for this socket to run detached in. */ + void DetachSocket(); + //@} +#endif // ENABLE_DETACH + + /** Write traffic to an IFile. Socket will not delete this object. */ + void SetTrafficMonitor(IFile *p) { m_traffic_monitor = p; } + +#ifdef ENABLE_TRIGGERS + /** \name Triggers */ + //@{ + /** Subscribe to trigger id. */ + void Subscribe(int id); + /** Unsubscribe from trigger id. */ + void Unsubscribe(int id); + /** Trigger callback, with data passed from source to destination. */ + virtual void OnTrigger(int id, const TriggerData& data); + /** Trigger cancelled because source has been deleted (as in delete). */ + virtual void OnCancelled(int id); + //@} +#endif + +protected: + /** default constructor not available */ + Socket() : m_handler(m_handler) {} + /** copy constructor not available */ + Socket(const Socket& s) : m_handler(s.m_handler) {} + + /** assignment operator not available. */ + Socket& operator=(const Socket& ) { return *this; } + + /** All traffic will be written to this IFile, if set. */ + IFile *GetTrafficMonitor() { return m_traffic_monitor; } + +// unsigned long m_flags; ///< boolean flags, replacing old 'bool' members + +private: + ISocketHandler& m_handler; ///< Reference of ISocketHandler in control of this socket + SOCKET m_socket; ///< File descriptor + bool m_bDel; ///< Delete by handler flag + bool m_bClose; ///< Close and delete flag + time_t m_tCreate; ///< Time in seconds when this socket was created + Socket *m_parent; ///< Pointer to ListenSocket class, valid for incoming sockets + bool m_b_disable_read; ///< Disable checking for read events + bool m_connected; ///< Socket is connected (tcp/udp) + bool m_b_erased_by_handler; ///< Set by handler before delete + time_t m_tClose; ///< Time in seconds when ordered to close + std::auto_ptr m_client_remote_address; ///< Address of last connect() + std::auto_ptr m_remote_address; ///< Remote end address + IFile *m_traffic_monitor; + time_t m_timeout_start; ///< Set by SetTimeout + time_t m_timeout_limit; ///< Defined by SetTimeout + bool m_bLost; ///< connection lost + +#ifdef _WIN32 +static WSAInitializer m_winsock_init; ///< Winsock initialization singleton class +#endif + +#ifdef HAVE_OPENSSL + bool m_b_enable_ssl; ///< Enable SSL for this TcpSocket + bool m_b_ssl; ///< ssl negotiation mode (TcpSocket) + bool m_b_ssl_server; ///< True if this is an incoming ssl TcpSocket connection +#endif + +#ifdef ENABLE_IPV6 + bool m_ipv6; ///< This is an ipv6 socket if this one is true +#endif + +#ifdef ENABLE_POOL + int m_socket_type; ///< Type of socket, from socket() call + std::string m_socket_protocol; ///< Protocol, from socket() call + bool m_bClient; ///< only client connections are pooled + bool m_bRetain; ///< keep connection on close +#endif + +#ifdef ENABLE_SOCKS4 + bool m_bSocks4; ///< socks4 negotiation mode (TcpSocket) + ipaddr_t m_socks4_host; ///< socks4 server address + port_t m_socks4_port; ///< socks4 server port number + std::string m_socks4_userid; ///< socks4 server usedid +#endif + +#ifdef ENABLE_DETACH + bool m_detach; ///< Socket ordered to detach flag + bool m_detached; ///< Socket has been detached + SocketThread *m_pThread; ///< Detach socket thread class pointer + ISocketHandler *m_slave_handler; ///< Actual sockethandler while detached +#endif +}; + +#ifdef SOCKETS_NAMESPACE +} +#endif + +#endif // _SOCKETS_Socket_H + + diff --git a/dep/sockets/include/SocketAddress.h b/dep/sockets/include/SocketAddress.h new file mode 100644 index 00000000000..abdbbfd2cf6 --- /dev/null +++ b/dep/sockets/include/SocketAddress.h @@ -0,0 +1,93 @@ +/** + ** \file SocketAddress.h + ** \date 2006-09-21 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2007 Anders Hedstrom + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifndef _SOCKETS_SocketAddress_H +#define _SOCKETS_SocketAddress_H + +#include "sockets-config.h" +#include +#include +#include "socket_include.h" + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +/** + This class and its subclasses is intended to be used as replacement + for the internal data type 'ipaddr_t' and various implementations of + IPv6 addressing found throughout the library. + 'ipaddr_t' is an IPv4 address in network byte order. + 'port_t' is the portnumber in host byte order. + 'struct in6_addr' is an IPv6 address. + 'struct in_addr' is an IPv4 address. + \ingroup basic +*/ +class SocketAddress +{ +public: + virtual ~SocketAddress() {} + + /** Get a pointer to the address struct. */ + virtual operator struct sockaddr *() = 0; + + /** Get length of address struct. */ + virtual operator socklen_t() = 0; + + /** Compare two addresses. */ + virtual bool operator==(SocketAddress&) = 0; + + /** Set port number. + \param port Port number in host byte order */ + virtual void SetPort(port_t port) = 0; + + /** Get port number. + \return Port number in host byte order. */ + virtual port_t GetPort() = 0; + + /** Set socket address. + \param sa Pointer to either 'struct sockaddr_in' or 'struct sockaddr_in6'. */ + virtual void SetAddress(struct sockaddr *sa) = 0; + + /** Convert address to text. */ + virtual std::string Convert(bool include_port) = 0; + + /** Reverse lookup of address. */ + virtual std::string Reverse() = 0; + + /** Get address family. */ + virtual int GetFamily() = 0; + + /** Address structure is valid. */ + virtual bool IsValid() = 0; + + /** Get a copy of this SocketAddress object. */ + virtual std::auto_ptr GetCopy() = 0; +}; + + +#ifdef SOCKETS_NAMESPACE +} // namespace SOCKETS_NAMESPACE { +#endif +#endif // _SOCKETS_SocketAddress_H + + diff --git a/dep/sockets/include/SocketHandler.h b/dep/sockets/include/SocketHandler.h new file mode 100644 index 00000000000..5598ec4249b --- /dev/null +++ b/dep/sockets/include/SocketHandler.h @@ -0,0 +1,265 @@ +/** \file SocketHandler.h + ** \date 2004-02-13 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2004-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifndef _SOCKETS_SocketHandler_H +#define _SOCKETS_SocketHandler_H + +#include "sockets-config.h" +#include +#include + +#include "socket_include.h" +#include "ISocketHandler.h" + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +class Socket; +#ifdef ENABLE_RESOLVER +class ResolvServer; +#endif +class Mutex; + +/** Socket container class, event generator. + \ingroup basic */ +class SocketHandler : public ISocketHandler +{ +protected: + /** Map type for holding file descriptors/socket object pointers. */ + typedef std::map socket_m; + +public: + /** SocketHandler constructor. + \param log Optional log class pointer */ + SocketHandler(StdLog *log = NULL); + + /** SocketHandler threadsafe constructor. + \param mutex Externally declared mutex variable + \param log Optional log class pointer */ + SocketHandler(Mutex& mutex,StdLog *log = NULL); + + ~SocketHandler(); + + /** Get mutex reference for threadsafe operations. */ + Mutex& GetMutex() const; + + /** Register StdLog object for error callback. + \param log Pointer to log class */ + void RegStdLog(StdLog *log); + + /** Log error to log class for print out / storage. */ + void LogError(Socket *p,const std::string& user_text,int err,const std::string& sys_err,loglevel_t t = LOG_LEVEL_WARNING); + + /** Add socket instance to socket map. Removal is always automatic. */ + void Add(Socket *); + + /** Get status of read/write/exception file descriptor set for a socket. */ + void Get(SOCKET s,bool& r,bool& w,bool& e); + + /** Set read/write/exception file descriptor sets (fd_set). */ + void Set(SOCKET s,bool bRead,bool bWrite,bool bException = true); + + /** Wait for events, generate callbacks. */ + int Select(long sec,long usec); + + /** This method will not return until an event has been detected. */ + int Select(); + + /** Wait for events, generate callbacks. */ + int Select(struct timeval *tsel); + + /** Check that a socket really is handled by this socket handler. */ + bool Valid(Socket *); + + /** Return number of sockets handled by this handler. */ + size_t GetCount(); + + /** Override and return false to deny all incoming connections. + \param p ListenSocket class pointer (use GetPort to identify which one) */ + bool OkToAccept(Socket *p); + + /** Called by Socket when a socket changes state. */ + void AddList(SOCKET s,list_t which_one,bool add); + + // Connection pool +#ifdef ENABLE_POOL + /** Find available open connection (used by connection pool). */ + ISocketHandler::PoolSocket *FindConnection(int type,const std::string& protocol,SocketAddress&); + /** Enable connection pool (by default disabled). */ + void EnablePool(bool x = true); + /** Check pool status. + \return true if connection pool is enabled */ + bool PoolEnabled(); +#endif // ENABLE_POOL + + // Socks4 +#ifdef ENABLE_SOCKS4 + /** Set socks4 server ip that all new tcp sockets should use. */ + void SetSocks4Host(ipaddr_t); + /** Set socks4 server hostname that all new tcp sockets should use. */ + void SetSocks4Host(const std::string& ); + /** Set socks4 server port number that all new tcp sockets should use. */ + void SetSocks4Port(port_t); + /** Set optional socks4 userid. */ + void SetSocks4Userid(const std::string& ); + /** If connection to socks4 server fails, immediately try direct connection to final host. */ + void SetSocks4TryDirect(bool x = true); + /** Get socks4 server ip. + \return socks4 server ip */ + ipaddr_t GetSocks4Host(); + /** Get socks4 port number. + \return socks4 port number */ + port_t GetSocks4Port(); + /** Get socks4 userid (optional). + \return socks4 userid */ + const std::string& GetSocks4Userid(); + /** Check status of socks4 try direct flag. + \return true if direct connection should be tried if connection to socks4 server fails */ + bool Socks4TryDirect(); +#endif // ENABLE_SOCKS4 + + // DNS resolve server +#ifdef ENABLE_RESOLVER + /** Enable asynchronous DNS. + \param port Listen port of asynchronous dns server */ + void EnableResolver(port_t port = 16667); + /** Check resolver status. + \return true if resolver is enabled */ + bool ResolverEnabled(); + /** Queue a dns request. + \param host Hostname to be resolved + \param port Port number will be echoed in Socket::OnResolved callback */ + int Resolve(Socket *,const std::string& host,port_t port); +#ifdef ENABLE_IPV6 + int Resolve6(Socket *,const std::string& host,port_t port); +#endif + /** Do a reverse dns lookup. */ + int Resolve(Socket *,ipaddr_t a); +#ifdef ENABLE_IPV6 + int Resolve(Socket *,in6_addr& a); +#endif + /** Get listen port of asynchronous dns server. */ + port_t GetResolverPort(); + /** Resolver thread ready for queries. */ + bool ResolverReady(); + /** Returns true if the socket is waiting for a resolve event. */ + bool Resolving(Socket *); +#endif // ENABLE_RESOLVER + +#ifdef ENABLE_TRIGGERS + /** Fetch unique trigger id. */ + int TriggerID(Socket *src); + /** Subscribe socket to trigger id. */ + bool Subscribe(int id, Socket *dst); + /** Unsubscribe socket from trigger id. */ + bool Unsubscribe(int id, Socket *dst); + /** Execute OnTrigger for subscribed sockets. + \param id Trigger ID + \param data Data passed from source to destination + \param erase Empty trigger id source and destination maps if 'true', + Leave them in place if 'false' - if a trigger should be called many times */ + void Trigger(int id, Socket::TriggerData& data, bool erase = true); +#endif // ENABLE_TRIGGERS + +#ifdef ENABLE_DETACH + /** Indicates that the handler runs under SocketThread. */ + void SetSlave(bool x = true); + /** Indicates that the handler runs under SocketThread. */ + bool IsSlave(); +#endif + + /** Sanity check of those accursed lists. */ + void CheckSanity(); + +protected: + socket_m m_sockets; ///< Active sockets map + socket_m m_add; ///< Sockets to be added to sockets map + std::list m_delete; ///< Sockets to be deleted (failed when Add) + +protected: + StdLog *m_stdlog; ///< Registered log class, or NULL + Mutex& m_mutex; ///< Thread safety mutex + bool m_b_use_mutex; ///< Mutex correctly initialized + +private: + void CheckList(socket_v&,const std::string&); ///< Used by CheckSanity + /** Remove socket from socket map, used by Socket class. */ + void Remove(Socket *); + SOCKET m_maxsock; ///< Highest file descriptor + 1 in active sockets list + fd_set m_rfds; ///< file descriptor set monitored for read events + fd_set m_wfds; ///< file descriptor set monitored for write events + fd_set m_efds; ///< file descriptor set monitored for exceptions + int m_preverror; ///< debug select() error + int m_errcnt; ///< debug select() error + time_t m_tlast; ///< timeout control + + // state lists + socket_v m_fds; ///< Active file descriptor list + socket_v m_fds_erase; ///< File descriptors that are to be erased from m_sockets + socket_v m_fds_callonconnect; ///< checklist CallOnConnect +#ifdef ENABLE_DETACH + socket_v m_fds_detach; ///< checklist Detach +#endif + socket_v m_fds_timeout; ///< checklist timeout + socket_v m_fds_retry; ///< checklist retry client connect + socket_v m_fds_close; ///< checklist close and delete + +#ifdef ENABLE_SOCKS4 + ipaddr_t m_socks4_host; ///< Socks4 server host ip + port_t m_socks4_port; ///< Socks4 server port number + std::string m_socks4_userid; ///< Socks4 userid + bool m_bTryDirect; ///< Try direct connection if socks4 server fails +#endif +#ifdef ENABLE_RESOLVER + int m_resolv_id; ///< Resolver id counter + ResolvServer *m_resolver; ///< Resolver thread pointer + port_t m_resolver_port; ///< Resolver listen port + std::map m_resolve_q; ///< resolve queue +#endif +#ifdef ENABLE_POOL + bool m_b_enable_pool; ///< Connection pool enabled if true +#endif +#ifdef ENABLE_TRIGGERS + int m_next_trigger_id; ///< Unique trigger id counter + std::map m_trigger_src; ///< mapping trigger id to source socket + std::map > m_trigger_dst; ///< mapping trigger id to destination sockets +#endif +#ifdef ENABLE_DETACH + bool m_slave; ///< Indicates that this is a ISocketHandler run in SocketThread +#endif +}; + +#ifdef SOCKETS_NAMESPACE +} +#endif + +#endif // _SOCKETS_SocketHandler_H + + diff --git a/dep/sockets/include/StdLog.h b/dep/sockets/include/StdLog.h new file mode 100644 index 00000000000..3ff68d6e9ea --- /dev/null +++ b/dep/sockets/include/StdLog.h @@ -0,0 +1,73 @@ +/** \file StdLog.h + ** \date 2004-06-01 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2004-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifndef _SOCKETS_StdLog_H +#define _SOCKETS_StdLog_H + +#include "sockets-config.h" +#include + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +/** error level enum. */ +typedef enum +{ + LOG_LEVEL_WARNING = 0, + LOG_LEVEL_ERROR, + LOG_LEVEL_FATAL, + LOG_LEVEL_INFO +} loglevel_t; + +class ISocketHandler; +class Socket; + +/** \defgroup logging Log help classes */ +/** Log class interface. + \ingroup logging */ +class StdLog +{ +public: + virtual ~StdLog() {} + + virtual void error(ISocketHandler *,Socket *, + const std::string& user_text, + int err, + const std::string& sys_err, + loglevel_t = LOG_LEVEL_WARNING) = 0; +}; + +#ifdef SOCKETS_NAMESPACE +} +#endif + +#endif // _SOCKETS_StdLog_H + + diff --git a/dep/sockets/include/StdoutLog.h b/dep/sockets/include/StdoutLog.h new file mode 100644 index 00000000000..aeb25b3e6e6 --- /dev/null +++ b/dep/sockets/include/StdoutLog.h @@ -0,0 +1,55 @@ +/** \file StdoutLog.h + ** \date 2004-06-01 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2004-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifndef _SOCKETS_StdoutLog_H +#define _SOCKETS_StdoutLog_H + +#include "sockets-config.h" +#include "StdLog.h" + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +/** StdLog implementation, logs to stdout. + \ingroup logging */ +class StdoutLog : public StdLog +{ +public: + void error(ISocketHandler *,Socket *,const std::string& call,int err,const std::string& sys_err,loglevel_t); +}; + + +#ifdef SOCKETS_NAMESPACE +} +#endif + +#endif // _SOCKETS_StdoutLog_H + + diff --git a/dep/sockets/include/StreamSocket.h b/dep/sockets/include/StreamSocket.h new file mode 100644 index 00000000000..bcce10ffbc5 --- /dev/null +++ b/dep/sockets/include/StreamSocket.h @@ -0,0 +1,124 @@ +#ifndef _StreamSocket_H +#define _StreamSocket_H + +#include "Socket.h" + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +/** SOCK_STREAM Socket base class. + \ingroup basic */ +class StreamSocket : public Socket +{ +public: + StreamSocket(ISocketHandler& ); + ~StreamSocket(); + + /** Socket should Check Connect on next write event from select(). */ + void SetConnecting(bool = true); + + /** Check connecting flag. + \return true if the socket is still trying to connect */ + bool Connecting(); + + /** Returns true when socket file descriptor is valid, + socket connection is established, and socket is not about to + be closed. */ + bool Ready(); + + /** Set timeout to use for connection attempt. + \param x Timeout in seconds */ + void SetConnectTimeout(int x); + + /** Return number of seconds to wait for a connection. + \return Connection timeout (seconds) */ + int GetConnectTimeout(); + + /** Set flush before close to make a tcp socket completely empty its + output buffer before closing the connection. */ + void SetFlushBeforeClose(bool = true); + + /** Check flush before status. + \return true if the socket should send all data before closing */ + bool GetFlushBeforeClose(); + + /** Define number of connection retries (tcp only). + n = 0 - no retry + n > 0 - number of retries + n = -1 - unlimited retries */ + void SetConnectionRetry(int n); + + /** Get number of maximum connection retries (tcp only). */ + int GetConnectionRetry(); + + /** Increase number of actual connection retries (tcp only). */ + void IncreaseConnectionRetries(); + + /** Get number of actual connection retries (tcp only). */ + int GetConnectionRetries(); + + /** Reset actual connection retries (tcp only). */ + void ResetConnectionRetries(); + + // LIST_CALLONCONNECT + + /** Instruct socket to call OnConnect callback next sockethandler cycle. */ + void SetCallOnConnect(bool x = true); + + /** Check call on connect flag. + \return true if OnConnect() should be called a.s.a.p */ + bool CallOnConnect(); + + // LIST_RETRY + + /** Set flag to initiate a connection attempt after a connection timeout. */ + void SetRetryClientConnect(bool x = true); + + /** Check if a connection attempt should be made. + \return true when another attempt should be made */ + bool RetryClientConnect(); + + /** Called after OnRead if socket is in line protocol mode. + \sa SetLineProtocol */ + /** Enable the OnLine callback. Do not create your own OnRead + * callback when using this. */ + virtual void SetLineProtocol(bool = true); + + /** Check line protocol mode. + \return true if socket is in line protocol mode */ + bool LineProtocol(); + + /** Set shutdown status. */ + void SetShutdown(int); + + /** Get shutdown status. */ + int GetShutdown(); + + /** Returns IPPROTO_TCP or IPPROTO_SCTP */ + virtual int Protocol() = 0; + +protected: + StreamSocket(const StreamSocket& ) {} // copy constructor + +private: + StreamSocket& operator=(const StreamSocket& ) { return *this; } // assignment operator + + bool m_bConnecting; ///< Flag indicating connection in progress + int m_connect_timeout; ///< Connection timeout (seconds) + bool m_flush_before_close; ///< Send all data before closing (default true) + int m_connection_retry; ///< Maximum connection retries (tcp) + int m_retries; ///< Actual number of connection retries (tcp) + bool m_call_on_connect; ///< OnConnect will be called next ISocketHandler cycle if true + bool m_b_retry_connect; ///< Try another connection attempt next ISocketHandler cycle + bool m_line_protocol; ///< Line protocol mode flag + int m_shutdown; ///< Shutdown status +}; + +#ifdef SOCKETS_NAMESPACE +} // namespace SOCKETS_NAMESPACE { +#endif + +#endif // _StreamSocket_H + + diff --git a/dep/sockets/include/TcpSocket.h b/dep/sockets/include/TcpSocket.h new file mode 100644 index 00000000000..de1be8bd8b9 --- /dev/null +++ b/dep/sockets/include/TcpSocket.h @@ -0,0 +1,356 @@ +/** \file TcpSocket.h + ** \date 2004-02-13 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2004-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifndef _SOCKETS_TcpSocket_H +#define _SOCKETS_TcpSocket_H +#include "sockets-config.h" +#include "StreamSocket.h" +#ifdef HAVE_OPENSSL +#include +#include "SSLInitializer.h" +#endif + +#include + +#define TCP_BUFSIZE_READ 16400 +#define TCP_OUTPUT_CAPACITY 1024000 + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +class SocketAddress; + +/** Socket implementation for TCP. + \ingroup basic */ +class TcpSocket : public StreamSocket +{ + /** \defgroup internal Internal utility */ +protected: + /** Buffer class containing one read/write circular buffer. + \ingroup internal */ + class CircularBuffer + { + public: + CircularBuffer(size_t size); + ~CircularBuffer(); + + /** append l bytes from p to buffer */ + bool Write(const char *p,size_t l); + /** copy l bytes from buffer to dest */ + bool Read(char *dest,size_t l); + /** copy l bytes from buffer to dest, dont touch buffer pointers */ + bool SoftRead(char *dest, size_t l); + /** skip l bytes from buffer */ + bool Remove(size_t l); + /** read l bytes from buffer, returns as string. */ + std::string ReadString(size_t l); + + /** total buffer length */ + size_t GetLength(); + /** pointer to circular buffer beginning */ + const char *GetStart(); + /** return number of bytes from circular buffer beginning to buffer physical end */ + size_t GetL(); + /** return free space in buffer, number of bytes until buffer overrun */ + size_t Space(); + + /** return total number of bytes written to this buffer, ever */ + unsigned long ByteCounter(bool clear = false); + + private: + CircularBuffer(const CircularBuffer& /*s*/) {} + CircularBuffer& operator=(const CircularBuffer& ) { return *this; } + char *buf; + size_t m_max; + size_t m_q; + size_t m_b; + size_t m_t; + unsigned long m_count; + }; + /** Output buffer struct. + \ingroup internal */ + struct OUTPUT { + OUTPUT() : _b(0), _t(0), _q(0) {} + OUTPUT(const char *buf, size_t len) : _b(0), _t(len), _q(len) { + memcpy(_buf, buf, len); + } + size_t Space() { + return TCP_OUTPUT_CAPACITY - _t; + } + void Add(const char *buf, size_t len) { + memcpy(_buf + _t, buf, len); + _t += len; + _q += len; + } + size_t Remove(size_t len) { + _b += len; + _q -= len; + return _q; + } + const char *Buf() { + return _buf + _b; + } + size_t Len() { + return _q; + } + size_t _b; + size_t _t; + size_t _q; + char _buf[TCP_OUTPUT_CAPACITY]; + }; + typedef std::list output_l; + +public: + /** Constructor with standard values on input/output buffers. */ + TcpSocket(ISocketHandler& ); + /** Constructor with custom values for i/o buffer. + \param h ISocketHandler reference + \param isize Input buffer size + \param osize Output buffer size */ + TcpSocket(ISocketHandler& h,size_t isize,size_t osize); + ~TcpSocket(); + + /** Open a connection to a remote server. + If you want your socket to connect to a server, + always call Open before Add'ing a socket to the sockethandler. + If not, the connection attempt will not be monitored by the + socket handler... + \param ip IP address + \param port Port number + \param skip_socks Do not use socks4 even if configured */ + bool Open(ipaddr_t ip,port_t port,bool skip_socks = false); +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + /** Open connection. + \param ip Ipv6 address + \param port Port number + \param skip_socks Do not use socks4 even if configured */ + bool Open(in6_addr ip,port_t port,bool skip_socks = false); +#endif +#endif + bool Open(SocketAddress&,bool skip_socks = false); + bool Open(SocketAddress&,SocketAddress& bind_address,bool skip_socks = false); + /** Open connection. + \param host Hostname + \param port Port number */ + bool Open(const std::string &host,port_t port); + + /** Connect timeout callback. */ + void OnConnectTimeout(); +#ifdef _WIN32 + /** Connection failed reported as exception on win32 */ + void OnException(); +#endif + + /** Close file descriptor - internal use only. + \sa SetCloseAndDelete */ + int Close(); + + /** Send a string. + \param s String to send + \param f Dummy flags -- not used */ + void Send(const std::string &s,int f = 0); + /** Send string using printf formatting. */ + void Sendf(const char *format, ...); + /** Send buffer of bytes. + \param buf Buffer pointer + \param len Length of data + \param f Dummy flags -- not used */ + void SendBuf(const char *buf,size_t len,int f = 0); + /** This callback is executed after a successful read from the socket. + \param buf Pointer to the data + \param len Length of the data */ + virtual void OnRawData(const char *buf,size_t len); + + /** Called when output buffer has been sent. + Note: Will only be called IF the output buffer has been used. + Send's that was successful without needing the output buffer + will not generate a call to this method. */ + virtual void OnWriteComplete(); + /** Number of bytes in input buffer. */ + size_t GetInputLength(); + /** Number of bytes in output buffer. */ + size_t GetOutputLength(); + + /** Callback fires when a socket in line protocol has read one full line. + \param line Line read */ + void OnLine(const std::string& line); + /** Get counter of number of bytes received. */ + uint64_t GetBytesReceived(bool clear = false); + /** Get counter of number of bytes sent. */ + uint64_t GetBytesSent(bool clear = false); + + /** Socks4 specific callback. */ + void OnSocks4Connect(); + /** Socks4 specific callback. */ + void OnSocks4ConnectFailed(); + /** Socks4 specific callback. + \return 'need_more' */ + bool OnSocks4Read(); + +#ifdef ENABLE_RESOLVER + /** Callback executed when resolver thread has finished a resolve request. */ + void OnResolved(int id,ipaddr_t a,port_t port); +#ifdef ENABLE_IPV6 + void OnResolved(int id,in6_addr& a,port_t port); +#endif +#endif +#ifdef HAVE_OPENSSL + /** Callback for 'New' ssl support - replaces SSLSocket. Internal use. */ + void OnSSLConnect(); + /** Callback for 'New' ssl support - replaces SSLSocket. Internal use. */ + void OnSSLAccept(); + /** This method must be implemented to initialize + the ssl context for an outgoing connection. */ + virtual void InitSSLClient(); + /** This method must be implemented to initialize + the ssl context for an incoming connection. */ + virtual void InitSSLServer(); +#endif + +#ifdef ENABLE_RECONNECT + /** Flag that says a broken connection will try to reconnect. */ + void SetReconnect(bool = true); + /** Check reconnect on lost connection flag status. */ + bool Reconnect(); + /** Flag to determine if a reconnect is in progress. */ + void SetIsReconnect(bool x = true); + /** Socket is reconnecting. */ + bool IsReconnect(); +#endif + + void DisableInputBuffer(bool = true); + + void OnOptions(int,int,int,SOCKET); + + void SetLineProtocol(bool = true); + + // TCP options + bool SetTcpNodelay(bool = true); + + virtual int Protocol(); + + /** Trigger limit for callback OnTransferLimit. */ + void SetTransferLimit(size_t sz); + /** This callback fires when the output buffer drops below the value + set by SetTransferLimit. Default: 0 (disabled). */ + virtual void OnTransferLimit(); + +protected: + TcpSocket(const TcpSocket& ); + void OnRead(); + void OnRead( char *buf, size_t n ); + void OnWrite(); +#ifdef HAVE_OPENSSL + /** SSL; Initialize ssl context for a client socket. + \param meth_in SSL method */ + void InitializeContext(const std::string& context, SSL_METHOD *meth_in = NULL); + /** SSL; Initialize ssl context for a server socket. + \param keyfile Combined private key/certificate file + \param password Password for private key + \param meth_in SSL method */ + void InitializeContext(const std::string& context, const std::string& keyfile, const std::string& password, SSL_METHOD *meth_in = NULL); + /** SSL; Initialize ssl context for a server socket. + \param certfile Separate certificate file + \param keyfile Combined private key/certificate file + \param password Password for private key + \param meth_in SSL method */ + void InitializeContext(const std::string& context, const std::string& certfile, const std::string& keyfile, const std::string& password, SSL_METHOD *meth_in = NULL); + /** SSL; Password callback method. */ +static int SSL_password_cb(char *buf,int num,int rwflag,void *userdata); + /** SSL; Get pointer to ssl context structure. */ + virtual SSL_CTX *GetSslContext(); + /** SSL; Get pointer to ssl structure. */ + virtual SSL *GetSsl(); + /** ssl; still negotiating connection. */ + bool SSLNegotiate(); + /** SSL; Get ssl password. */ + const std::string& GetPassword(); +#endif + + CircularBuffer ibuf; ///< Circular input buffer + +private: + TcpSocket& operator=(const TcpSocket& ) { return *this; } + + /** the actual send() */ + int TryWrite(const char *buf, size_t len); + /** add data to output buffer top */ + void Buffer(const char *buf, size_t len); + + // + bool m_b_input_buffer_disabled; + uint64_t m_bytes_sent; + uint64_t m_bytes_received; + bool m_skip_c; ///< Skip second char of CRLF or LFCR sequence in OnRead + char m_c; ///< First char in CRLF or LFCR sequence + std::string m_line; ///< Current line in line protocol mode +#ifdef SOCKETS_DYNAMIC_TEMP + char *m_buf; ///< temporary read buffer +#endif + output_l m_obuf; ///< output buffer + OUTPUT *m_obuf_top; ///< output buffer on top + size_t m_transfer_limit; + size_t m_output_length; + +#ifdef HAVE_OPENSSL +static SSLInitializer m_ssl_init; + SSL_CTX *m_ssl_ctx; ///< ssl context + SSL *m_ssl; ///< ssl 'socket' + BIO *m_sbio; ///< ssl bio + std::string m_password; ///< ssl password +#endif + +#ifdef ENABLE_SOCKS4 + int m_socks4_state; ///< socks4 support + char m_socks4_vn; ///< socks4 support, temporary variable + char m_socks4_cd; ///< socks4 support, temporary variable + unsigned short m_socks4_dstport; ///< socks4 support + unsigned long m_socks4_dstip; ///< socks4 support +#endif + +#ifdef ENABLE_RESOLVER + int m_resolver_id; ///< Resolver id (if any) for current Open call +#endif + +#ifdef ENABLE_RECONNECT + bool m_b_reconnect; ///< Reconnect on lost connection flag + bool m_b_is_reconnect; ///< Trying to reconnect +#endif + +}; + +#ifdef SOCKETS_NAMESPACE +} +#endif + +#endif // _SOCKETS_TcpSocket_H + + diff --git a/dep/sockets/include/Thread.h b/dep/sockets/include/Thread.h new file mode 100644 index 00000000000..efb766e9ee6 --- /dev/null +++ b/dep/sockets/include/Thread.h @@ -0,0 +1,100 @@ +/** \file Thread.h + ** \date 2004-10-30 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2004-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifndef _SOCKETS_Thread_H +#define _SOCKETS_Thread_H + +#include "sockets-config.h" +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +#ifdef _WIN32 +// to be +//typedef DWORD threadfunc_t; +//typedef LPVOID threadparam_t; +//#define STDPREFIX WINAPI +typedef unsigned threadfunc_t; +typedef void * threadparam_t; +#define STDPREFIX __stdcall +#else +#include + +typedef void * threadfunc_t; +typedef void * threadparam_t; +#define STDPREFIX +#endif + +/** \defgroup threading Threading */ +/** Thread base class. +The Thread class is used by the resolver (ResolvServer) and running a detached socket (SocketThread). +When you know some processing will take a long time and will freeze up a socket, there is always the +possibility to call Detach() on that socket before starting the processing. +When the OnDetached() callback is later called the processing can continue, now in its own thread. + \ingroup threading */ +class Thread +{ +public: + Thread(bool release = true); + virtual ~Thread(); + + static threadfunc_t STDPREFIX StartThread(threadparam_t); + + virtual void Run() = 0; + + bool IsRunning(); + void SetRunning(bool x); + bool IsReleased(); + void SetRelease(bool x); + bool DeleteOnExit(); + void SetDeleteOnExit(bool x = true); + bool IsDestructor(); + +private: + Thread(const Thread& ) {} + Thread& operator=(const Thread& ) { return *this; } +#ifdef _WIN32 + HANDLE m_thread; + unsigned m_dwThreadId; +#else + pthread_t m_thread; +#endif + bool m_running; + bool m_release; + bool m_b_delete_on_exit; + bool m_b_destructor; +}; + +#ifdef SOCKETS_NAMESPACE +} +#endif + +#endif // _SOCKETS_Thread_H + + diff --git a/dep/sockets/include/UdpSocket.h b/dep/sockets/include/UdpSocket.h new file mode 100644 index 00000000000..3b06c6955bd --- /dev/null +++ b/dep/sockets/include/UdpSocket.h @@ -0,0 +1,215 @@ +/** \file UdpSocket.h + ** \date 2004-02-13 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2004-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifndef _SOCKETS_UdpSocket_H +#define _SOCKETS_UdpSocket_H + +#include "sockets-config.h" +#include "Socket.h" + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +/** Socket implementation for UDP. + \ingroup basic */ +class UdpSocket : public Socket +{ +public: + /** Constructor. + \param h ISocketHandler reference + \param ibufsz Maximum size of receive message (extra bytes will be truncated) + \param ipv6 'true' if this is an ipv6 socket */ + UdpSocket(ISocketHandler& h,int ibufsz = 16384,bool ipv6 = false, int retries = 0); + ~UdpSocket(); + + /** Called when incoming data has been received. + \param buf Pointer to data + \param len Length of data + \param sa Pointer to sockaddr struct of sender + \param sa_len Length of sockaddr struct */ + virtual void OnRawData(const char *buf,size_t len,struct sockaddr *sa,socklen_t sa_len); + + /** Called when incoming data has been received and read timestamp is enabled. + \param buf Pointer to data + \param len Length of data + \param sa Pointer to sockaddr struct of sender + \param sa_len Length of sockaddr struct + \param ts Timestamp from message */ + virtual void OnRawData(const char *buf,size_t len,struct sockaddr *sa,socklen_t sa_len,struct timeval *ts); + + /** To receive incoming data, call Bind to setup an incoming port. + \param port Incoming port number + \param range Port range to try if ports already in use + \return 0 if bind succeeded */ + int Bind(port_t& port,int range = 1); + /** To receive data on a specific interface:port, use this. + \param intf Interface ip/hostname + \param port Port number + \param range Port range + \return 0 if bind succeeded */ + int Bind(const std::string& intf,port_t& port,int range = 1); + /** To receive data on a specific interface:port, use this. + \param a Ip address + \param port Port number + \param range Port range + \return 0 if bind succeeded */ + int Bind(ipaddr_t a,port_t& port,int range = 1); +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + /** To receive data on a specific interface:port, use this. + \param a Ipv6 address + \param port Port number + \param range Port range + \return 0 if bind succeeded */ + int Bind(in6_addr a,port_t& port,int range = 1); +#endif +#endif + /** To receive data on a specific interface:port, use this. + \param ad Socket address + \param range Port range + \return 0 if bind succeeded */ + int Bind(SocketAddress& ad,int range = 1); + + /** Define remote host. + \param l Address of remote host + \param port Port of remote host + \return true if successful */ + bool Open(ipaddr_t l,port_t port); + /** Define remote host. + \param host Hostname + \param port Port number + \return true if successful */ + bool Open(const std::string& host,port_t port); +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + /** Define remote host. + \param a Address of remote host, ipv6 + \param port Port of remote host + \return true if successful */ + bool Open(struct in6_addr& a,port_t port); +#endif +#endif + /** Define remote host. + \param ad Socket address + \return true if successful */ + bool Open(SocketAddress& ad); + + /** Send to specified host */ + void SendToBuf(const std::string& ,port_t,const char *data,int len,int flags = 0); + /** Send to specified address */ + void SendToBuf(ipaddr_t,port_t,const char *data,int len,int flags = 0); +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + /** Send to specified ipv6 address */ + void SendToBuf(in6_addr,port_t,const char *data,int len,int flags = 0); +#endif +#endif + /** Send to specified socket address */ + void SendToBuf(SocketAddress& ad,const char *data,int len,int flags = 0); + + /** Send string to specified host */ + void SendTo(const std::string&,port_t,const std::string&,int flags = 0); + /** Send string to specified address */ + void SendTo(ipaddr_t,port_t,const std::string&,int flags = 0); +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + /** Send string to specified ipv6 address */ + void SendTo(in6_addr,port_t,const std::string&,int flags = 0); +#endif +#endif + /** Send string to specified socket address */ + void SendTo(SocketAddress& ad,const std::string&,int flags = 0); + + /** Send to connected address */ + void SendBuf(const char *data,size_t,int flags = 0); + /** Send string to connected address. */ + void Send(const std::string& ,int flags = 0); + + /** Set broadcast */ + void SetBroadcast(bool b = true); + /** Check broadcast flag. + \return true broadcast is enabled. */ + bool IsBroadcast(); + + /** multicast */ + void SetMulticastTTL(int ttl = 1); + int GetMulticastTTL(); + void SetMulticastLoop(bool = true); + bool IsMulticastLoop(); + void AddMulticastMembership(const std::string& group,const std::string& intf = "0.0.0.0",int if_index = 0); + void DropMulticastMembership(const std::string& group,const std::string& intf = "0.0.0.0",int if_index = 0); +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + /** multicast, ipv6 only */ + void SetMulticastHops(int = -1); + /** multicast, ipv6 only */ + int GetMulticastHops(); +#endif +#endif + /** Returns true if Bind succeeded. */ + bool IsBound(); + /** Return Bind port number */ + port_t GetPort(); + + void OnOptions(int,int,int,SOCKET) {} + + int GetLastSizeWritten(); + + /** Also read timestamp information from incoming message */ + void SetTimestamp(bool = true); + +protected: + UdpSocket(const UdpSocket& s) : Socket(s) {} + void OnRead(); +#if defined(LINUX) || defined(MACOSX) + /** This method emulates socket recvfrom, but uses messages so we can get the timestamp */ + int ReadTS(char *ioBuf, int inBufSize, struct sockaddr *from, socklen_t fromlen, struct timeval *ts); +#endif + +private: + UdpSocket& operator=(const UdpSocket& ) { return *this; } + /** create before using sendto methods */ + void CreateConnection(); + char *m_ibuf; ///< Input buffer + int m_ibufsz; ///< Size of input buffer + bool m_bind_ok; ///< Bind completed successfully + port_t m_port; ///< Bind port number + int m_last_size_written; + int m_retries; + bool m_b_read_ts; +}; + +#ifdef SOCKETS_NAMESPACE +} +#endif + +#endif // _SOCKETS_UdpSocket_H + + diff --git a/dep/sockets/include/Utility.h b/dep/sockets/include/Utility.h new file mode 100644 index 00000000000..724a94e4b32 --- /dev/null +++ b/dep/sockets/include/Utility.h @@ -0,0 +1,186 @@ +/** \file Utility.h + ** \date 2004-02-13 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2004-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifndef _SOCKETS_Utility_H +#define _SOCKETS_Utility_H + +#include "sockets-config.h" +#include +#include +#include +#include "socket_include.h" +#include +#include + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +#define TWIST_LEN 624 + +class SocketAddress; + +/** Conversion utilities. + \ingroup util */ +class Utility +{ + /** + The Mersenne Twister + http://www.math.keio.ac.jp/~matumoto/emt.html + */ + class Rng { + public: + Rng(unsigned long seed); + + unsigned long Get(); + + private: + int m_value; + unsigned long m_tmp[TWIST_LEN]; + }; + class ncmap_compare { + public: + bool operator()(const std::string& x, const std::string& y) const { + return strcasecmp(x.c_str(), y.c_str()) < 0; + } + }; +public: + template class ncmap : public std::map { + public: + ncmap() {} + }; +public: + static std::string base64(const std::string& str_in); + static std::string base64d(const std::string& str_in); + static std::string l2string(long l); + static std::string bigint2string(uint64_t l); + static uint64_t atoi64(const std::string& str); + static unsigned int hex2unsigned(const std::string& str); + static std::string rfc1738_encode(const std::string& src); + static std::string rfc1738_decode(const std::string& src); + + /** Checks whether a string is a valid ipv4/ipv6 ip number. */ + static bool isipv4(const std::string&); + /** Checks whether a string is a valid ipv4/ipv6 ip number. */ + static bool isipv6(const std::string&); + + /** Hostname to ip resolution ipv4, not asynchronous. */ + static bool u2ip(const std::string&, ipaddr_t&); + static bool u2ip(const std::string&, struct sockaddr_in& sa, int ai_flags = 0); + +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + /** Hostname to ip resolution ipv6, not asynchronous. */ + static bool u2ip(const std::string&, struct in6_addr&); + static bool u2ip(const std::string&, struct sockaddr_in6& sa, int ai_flags = 0); +#endif +#endif + + /** Reverse lookup of address to hostname */ + static bool reverse(struct sockaddr *sa, socklen_t sa_len, std::string&, int flags = 0); + static bool reverse(struct sockaddr *sa, socklen_t sa_len, std::string& hostname, std::string& service, int flags = 0); + + static bool u2service(const std::string& name, int& service, int ai_flags = 0); + + /** Convert binary ip address to string: ipv4. */ + static void l2ip(const ipaddr_t,std::string& ); + static void l2ip(const in_addr&,std::string& ); +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + /** Convert binary ip address to string: ipv6. */ + static void l2ip(const struct in6_addr&,std::string& ,bool mixed = false); + + /** ipv6 address compare. */ + static int in6_addr_compare(in6_addr,in6_addr); +#endif +#endif + /** ResolveLocal (hostname) - call once before calling any GetLocal method. */ + static void ResolveLocal(); + /** Returns local hostname, ResolveLocal must be called once before using. + \sa ResolveLocal */ + static const std::string& GetLocalHostname(); + /** Returns local ip, ResolveLocal must be called once before using. + \sa ResolveLocal */ + static ipaddr_t GetLocalIP(); + /** Returns local ip number as string. + \sa ResolveLocal */ + static const std::string& GetLocalAddress(); +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + /** Returns local ipv6 ip. + \sa ResolveLocal */ + static const struct in6_addr& GetLocalIP6(); + /** Returns local ipv6 address. + \sa ResolveLocal */ + static const std::string& GetLocalAddress6(); +#endif +#endif + /** Set environment variable. + \param var Name of variable to set + \param value Value */ + static void SetEnv(const std::string& var,const std::string& value); + /** Convert sockaddr struct to human readable string. + \param sa Ptr to sockaddr struct */ + static std::string Sa2String(struct sockaddr *sa); + + /** Get current time in sec/microseconds. */ + static void GetTime(struct timeval *); + + static std::auto_ptr CreateAddress(struct sockaddr *,socklen_t); + + static unsigned long ThreadID(); + + static std::string ToLower(const std::string& str); + static std::string ToUpper(const std::string& str); + + static std::string ToString(double d); + + /** Returns a random 32-bit integer */ + static unsigned long Rnd(); + +private: + static std::string m_host; ///< local hostname + static ipaddr_t m_ip; ///< local ip address + static std::string m_addr; ///< local ip address in string format +#ifdef ENABLE_IPV6 +#ifdef IPPROTO_IPV6 + static struct in6_addr m_local_ip6; ///< local ipv6 address +#endif + static std::string m_local_addr6; ///< local ipv6 address in string format +#endif + static bool m_local_resolved; ///< ResolveLocal has been called if true +}; + +#ifdef SOCKETS_NAMESPACE +} +#endif + +#endif // _SOCKETS_Utility_H + + diff --git a/dep/sockets/include/socket_include.h b/dep/sockets/include/socket_include.h new file mode 100644 index 00000000000..89855a54108 --- /dev/null +++ b/dep/sockets/include/socket_include.h @@ -0,0 +1,290 @@ +/** \file socket_include.h + ** \date 2005-04-12 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2004-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifndef _SOCKETS_socket_include_H +#define _SOCKETS_socket_include_H +#include "sockets-config.h" + +#ifdef _MSC_VER +#pragma warning(disable:4514) +#endif + +// common defines affecting library and applications using library + +/* Define SOCKETS_DYNAMIC_TEMP to use dynamically allocated buffers + in read operations - helps on ECOS */ +#define SOCKETS_DYNAMIC_TEMP + +// platform specific stuff +#if (defined(__unix__) || defined(unix)) && !defined(USG) +#include +#endif +#include + +// int64 +#ifdef _WIN32 +typedef unsigned __int64 uint64_t; +#else +#include +#ifdef SOLARIS +# include +#else +# include +#endif +#endif + +#ifndef _WIN32 +// ---------------------------------------- +// common unix includes / defines +#include +#include +#include +#include +#include +#include +//#include + +// all typedefs in this file will be declared outside the sockets namespace, +// because some os's will already have one or more of the type defined. +typedef int SOCKET; +#define Errno errno +#define StrError strerror + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +// WIN32 adapt +#define closesocket close +#define INVALID_SOCKET -1 +#define SOCKET_ERROR -1 + +#ifndef INADDR_NONE +#define INADDR_NONE ((unsigned long) -1) +#endif // INADDR_NONE + +#ifdef SOCKETS_NAMESPACE +} +#endif + +#endif // !_WIN32 + +// ---------------------------------------- +// Generic +#ifndef SOL_IP +#define SOL_IP IPPROTO_IP +#endif + +// ---------------------------------------- +// OS specific adaptions + +#ifdef SOLARIS +// ---------------------------------------- +// Solaris +typedef unsigned short port_t; +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif +// no defs + +#ifdef SOCKETS_NAMESPACE +} +#endif + +#define s6_addr16 _S6_un._S6_u8 +#define MSG_NOSIGNAL 0 + +#elif defined __FreeBSD__ +// ---------------------------------------- +// FreeBSD +# if __FreeBSD_version >= 400014 +# define s6_addr16 __u6_addr.__u6_addr16 +# if !defined(MSG_NOSIGNAL) +# define MSG_NOSIGNAL 0 +# endif +# include +typedef in_addr_t ipaddr_t; +typedef in_port_t port_t; +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif +// no defs + +#ifdef SOCKETS_NAMESPACE +} +#endif + +# define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP +# define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP +# else +# error FreeBSD versions prior to 400014 does not support ipv6 +# endif + +#elif defined (__NetBSD__) || defined (__OpenBSD__) +# if !defined(MSG_NOSIGNAL) +# define MSG_NOSIGNAL 0 +# endif +# include +typedef in_addr_t ipaddr_t; +typedef in_port_t port_t; +#elif defined MACOSX +// ---------------------------------------- +// Mac OS X +#include +#ifdef __DARWIN_UNIX03 +typedef unsigned short port_t; +#else +#include +#endif // __DARWIN_UNIX03 +typedef unsigned long ipaddr_t; +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif +// no defs + +#ifdef SOCKETS_NAMESPACE +} +#endif + +#define s6_addr16 __u6_addr.__u6_addr16 +#define MSG_NOSIGNAL 0 // oops - thanks Derek +#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP +#define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP + +#elif defined _WIN32 +// ---------------------------------------- +// Win32 +#ifdef _MSC_VER +#pragma comment(lib, "wsock32.lib") +#endif +#define strcasecmp _stricmp + +typedef unsigned long ipaddr_t; +typedef unsigned short port_t; +typedef int socklen_t; +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif +// no defs + +#ifdef SOCKETS_NAMESPACE +} +#endif + +// 1.8.6: define FD_SETSIZE to something bigger than 64 if there are a lot of +// simultaneous connections (must be done before including winsock.h) +#define FD_SETSIZE 1024 + +// windows 2000 with ipv6 preview installed: +// http://msdn.microsoft.com/downloads/sdks/platform/tpipv6.asp +// see the FAQ on how to install +#define WIN32_LEAN_AND_MEAN +#include +#include +#if _MSC_VER < 1200 +#ifndef __CYGWIN__ +#ifdef ENABLE_IPV6 +#include // For IPv6 Tech Preview. +#endif +#endif +#endif // _MSC_VER < 1200 + +#define MSG_NOSIGNAL 0 +//#define SHUT_RDWR 2 +#define SHUT_WR 1 + +#define Errno WSAGetLastError() +const char *StrError(int x); + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + +// class WSAInitializer is a part of the Socket class (on win32) +// as a static instance - so whenever an application uses a Socket, +// winsock is initialized +class WSAInitializer // Winsock Initializer +{ +public: + WSAInitializer() { + if (WSAStartup(0x101,&m_wsadata)) + { + exit(-1); + } + } + ~WSAInitializer() { + WSACleanup(); + } +private: + WSADATA m_wsadata; +}; + +#ifdef SOCKETS_NAMESPACE +} +#endif + +#else +// ---------------------------------------- +// LINUX +typedef unsigned long ipaddr_t; +typedef unsigned short port_t; +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif +// no defs + +#ifdef SOCKETS_NAMESPACE +} +#endif + +#endif + +#ifdef SOCKETS_NAMESPACE +namespace SOCKETS_NAMESPACE { +#endif + /** List type containing file descriptors. */ + typedef std::list socket_v; + +#ifdef SOCKETS_NAMESPACE +} +#endif + +// getaddrinfo / getnameinfo replacements +#ifdef NO_GETADDRINFO +#ifndef AI_NUMERICHOST +#define AI_NUMERICHOST 1 +#endif +#ifndef NI_NUMERICHOST +#define NI_NUMERICHOST 1 +#endif +#endif + +#endif // _SOCKETS_socket_include_H + + diff --git a/dep/sockets/include/sockets-config.h b/dep/sockets/include/sockets-config.h new file mode 100644 index 00000000000..1c8dc439092 --- /dev/null +++ b/dep/sockets/include/sockets-config.h @@ -0,0 +1,90 @@ +/** + ** \file sockets-config.h + ** \date 2007-04-14 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2007 Anders Hedstrom + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#ifndef _SOCKETS_CONFIG_H +#define _SOCKETS_CONFIG_H + +#ifndef _RUN_DP +/* First undefine symbols if already defined. */ +#undef HAVE_OPENSSL +#undef ENABLE_IPV6 +#undef USE_SCTP +#undef NO_GETADDRINFO +#undef ENABLE_POOL +#undef ENABLE_SOCKS4 +#undef ENABLE_RESOLVER +#undef ENABLE_RECONNECT +#undef ENABLE_DETACH +#undef ENABLE_TRIGGERS +#undef ENABLE_EXCEPTIONS +#endif // _RUN_DP + +// define MACOSX for internal socket library checks +#if defined(__APPLE__) && defined(__MACH__) && !defined(MACOSX) +#define MACOSX +#endif + +/* OpenSSL support. */ +//#define HAVE_OPENSSL + +/* Ipv6 support. */ +//#define ENABLE_IPV6 + +/* SCTP support. */ +//#define USE_SCTP + +/* Define NO_GETADDRINFO if your operating system does not support + the "getaddrinfo" and "getnameinfo" function calls. */ +#define NO_GETADDRINFO + +/* Connection pool support. */ +#define ENABLE_POOL + +/* Socks4 client support. */ +//#define ENABLE_SOCKS4 + +/* Asynchronous resolver. */ +#define ENABLE_RESOLVER + +/* Enable TCP reconnect on lost connection. + Socket::OnReconnect + Socket::OnDisconnect +*/ +#define ENABLE_RECONNECT + +/* Enable socket thread detach functionality. */ +#define ENABLE_DETACH + +/* Enable socket to socket triggers. Not yet in use. */ +//#define ENABLE_TRIGGERS + +/* Enabled exceptions. */ +//#define ENABLE_EXCEPTIONS + +/* Resolver uses the detach function so either enable both or disable both. */ +#ifndef ENABLE_DETACH +#undef ENABLE_RESOLVER +#endif + +#endif // _SOCKETS_CONFIG_H + + diff --git a/dep/sockets/network_kist.txt b/dep/sockets/network_kist.txt new file mode 100644 index 00000000000..f6597bf9c77 --- /dev/null +++ b/dep/sockets/network_kist.txt @@ -0,0 +1,20 @@ +The following are the only .cpp files used from the new network library (v2.2.8) This file is just for future reference. + +Base64.cpp +Exception.cpp +Ipv4Address.cpp +Ipv6Address.cpp +Lock.cpp +Mutex.cpp +Parse.cpp +ResolvServer.cpp +ResolvSocket.cpp +Socket.cpp +SocketHandler.cpp +socket_include.cpp +StdoutLog.cpp +StreamSocket.cpp +TcpSocket.cpp +Thread.cpp +UdpSocket.cpp +Utility.cpp diff --git a/dep/sockets/socket_include.cpp b/dep/sockets/socket_include.cpp new file mode 100644 index 00000000000..290602c1b52 --- /dev/null +++ b/dep/sockets/socket_include.cpp @@ -0,0 +1,89 @@ +/** \file socket_include.cpp + ** \date 2004-11-28 + ** \author grymse@alhem.net +**/ +/* +Copyright (C) 2004-2007 Anders Hedstrom + +This library is made available under the terms of the GNU GPL. + +If you would like to use this library in a closed-source application, +a separate license agreement is available. For information about +the closed-source license agreement for the C++ sockets library, +please visit http://www.alhem.net/Sockets/license.html and/or +email license@alhem.net. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +#include + +// only to be included in win32 projects +const char *StrError(int x) +{ +static char tmp[100]; + switch (x) + { + case 10004: return "Interrupted function call."; + case 10013: return "Permission denied."; + case 10014: return "Bad address."; + case 10022: return "Invalid argument."; + case 10024: return "Too many open files."; + case 10035: return "Resource temporarily unavailable."; + case 10036: return "Operation now in progress."; + case 10037: return "Operation already in progress."; + case 10038: return "Socket operation on nonsocket."; + case 10039: return "Destination address required."; + case 10040: return "Message too long."; + case 10041: return "Protocol wrong type for socket."; + case 10042: return "Bad protocol option."; + case 10043: return "Protocol not supported."; + case 10044: return "Socket type not supported."; + case 10045: return "Operation not supported."; + case 10046: return "Protocol family not supported."; + case 10047: return "Address family not supported by protocol family."; + case 10048: return "Address already in use."; + case 10049: return "Cannot assign requested address."; + case 10050: return "Network is down."; + case 10051: return "Network is unreachable."; + case 10052: return "Network dropped connection on reset."; + case 10053: return "Software caused connection abort."; + case 10054: return "Connection reset by peer."; + case 10055: return "No buffer space available."; + case 10056: return "Socket is already connected."; + case 10057: return "Socket is not connected."; + case 10058: return "Cannot send after socket shutdown."; + case 10060: return "Connection timed out."; + case 10061: return "Connection refused."; + case 10064: return "Host is down."; + case 10065: return "No route to host."; + case 10067: return "Too many processes."; + case 10091: return "Network subsystem is unavailable."; + case 10092: return "Winsock.dll version out of range."; + case 10093: return "Successful WSAStartup not yet performed."; + case 10101: return "Graceful shutdown in progress."; + case 10109: return "Class type not found."; + case 11001: return "Host not found."; + case 11002: return "Nonauthoritative host not found."; + case 11003: return "This is a nonrecoverable error."; + case 11004: return "Valid name, no data record of requested type."; + + default: + break; + } + sprintf(tmp, "Winsock error code: %d", x); + return tmp; +} + + diff --git a/dep/utf8cpp/utf8.h b/dep/utf8cpp/utf8.h new file mode 100644 index 00000000000..82b13f59f98 --- /dev/null +++ b/dep/utf8cpp/utf8.h @@ -0,0 +1,34 @@ +// Copyright 2006 Nemanja Trifunovic + +/* +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +*/ + + +#ifndef UTF8_FOR_CPP_2675DCD0_9480_4c0c_B92A_CC14C027B731 +#define UTF8_FOR_CPP_2675DCD0_9480_4c0c_B92A_CC14C027B731 + +#include "utf8/checked.h" +#include "utf8/unchecked.h" + +#endif // header guard diff --git a/dep/utf8cpp/utf8/checked.h b/dep/utf8cpp/utf8/checked.h new file mode 100644 index 00000000000..a1d2035364d --- /dev/null +++ b/dep/utf8cpp/utf8/checked.h @@ -0,0 +1,323 @@ +// Copyright 2006 Nemanja Trifunovic + +/* +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +*/ + + +#ifndef UTF8_FOR_CPP_CHECKED_H_2675DCD0_9480_4c0c_B92A_CC14C027B731 +#define UTF8_FOR_CPP_CHECKED_H_2675DCD0_9480_4c0c_B92A_CC14C027B731 + +#include "core.h" +#include + +namespace utf8 +{ + // Base for the exceptions that may be thrown from the library + class exception : public std::exception { + }; + + // Exceptions that may be thrown from the library functions. + class invalid_code_point : public exception { + uint32_t cp; + public: + invalid_code_point(uint32_t cp) : cp(cp) {} + virtual const char* what() const throw() { return "Invalid code point"; } + uint32_t code_point() const {return cp;} + }; + + class invalid_utf8 : public exception { + uint8_t u8; + public: + invalid_utf8 (uint8_t u) : u8(u) {} + virtual const char* what() const throw() { return "Invalid UTF-8"; } + uint8_t utf8_octet() const {return u8;} + }; + + class invalid_utf16 : public exception { + uint16_t u16; + public: + invalid_utf16 (uint16_t u) : u16(u) {} + virtual const char* what() const throw() { return "Invalid UTF-16"; } + uint16_t utf16_word() const {return u16;} + }; + + class not_enough_room : public exception { + public: + virtual const char* what() const throw() { return "Not enough space"; } + }; + + /// The library API - functions intended to be called by the users + + template + output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out, uint32_t replacement) + { + while (start != end) { + octet_iterator sequence_start = start; + internal::utf_error err_code = internal::validate_next(start, end); + switch (err_code) { + case internal::UTF8_OK : + for (octet_iterator it = sequence_start; it != start; ++it) + *out++ = *it; + break; + case internal::NOT_ENOUGH_ROOM: + throw not_enough_room(); + case internal::INVALID_LEAD: + append (replacement, out); + ++start; + break; + case internal::INCOMPLETE_SEQUENCE: + case internal::OVERLONG_SEQUENCE: + case internal::INVALID_CODE_POINT: + append (replacement, out); + ++start; + // just one replacement mark for the sequence + while (internal::is_trail(*start) && start != end) + ++start; + break; + } + } + return out; + } + + template + inline output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out) + { + static const uint32_t replacement_marker = internal::mask16(0xfffd); + return replace_invalid(start, end, out, replacement_marker); + } + + template + octet_iterator append(uint32_t cp, octet_iterator result) + { + if (!internal::is_code_point_valid(cp)) + throw invalid_code_point(cp); + + if (cp < 0x80) // one octet + *(result++) = static_cast(cp); + else if (cp < 0x800) { // two octets + *(result++) = static_cast((cp >> 6) | 0xc0); + *(result++) = static_cast((cp & 0x3f) | 0x80); + } + else if (cp < 0x10000) { // three octets + *(result++) = static_cast((cp >> 12) | 0xe0); + *(result++) = static_cast(((cp >> 6) & 0x3f) | 0x80); + *(result++) = static_cast((cp & 0x3f) | 0x80); + } + else { // four octets + *(result++) = static_cast((cp >> 18) | 0xf0); + *(result++) = static_cast(((cp >> 12) & 0x3f) | 0x80); + *(result++) = static_cast(((cp >> 6) & 0x3f) | 0x80); + *(result++) = static_cast((cp & 0x3f) | 0x80); + } + return result; + } + + template + uint32_t next(octet_iterator& it, octet_iterator end) + { + uint32_t cp = 0; + internal::utf_error err_code = internal::validate_next(it, end, &cp); + switch (err_code) { + case internal::UTF8_OK : + break; + case internal::NOT_ENOUGH_ROOM : + throw not_enough_room(); + case internal::INVALID_LEAD : + case internal::INCOMPLETE_SEQUENCE : + case internal::OVERLONG_SEQUENCE : + throw invalid_utf8(*it); + case internal::INVALID_CODE_POINT : + throw invalid_code_point(cp); + } + return cp; + } + + template + uint32_t peek_next(octet_iterator it, octet_iterator end) + { + return next(it, end); + } + + template + uint32_t prior(octet_iterator& it, octet_iterator start) + { + octet_iterator end = it; + while (internal::is_trail(*(--it))) + if (it < start) + throw invalid_utf8(*it); // error - no lead byte in the sequence + octet_iterator temp = it; + return next(temp, end); + } + + /// Deprecated in versions that include "prior" + template + uint32_t previous(octet_iterator& it, octet_iterator pass_start) + { + octet_iterator end = it; + while (internal::is_trail(*(--it))) + if (it == pass_start) + throw invalid_utf8(*it); // error - no lead byte in the sequence + octet_iterator temp = it; + return next(temp, end); + } + + template + void advance (octet_iterator& it, distance_type n, octet_iterator end) + { + for (distance_type i = 0; i < n; ++i) + next(it, end); + } + + template + typename std::iterator_traits::difference_type + distance (octet_iterator first, octet_iterator last) + { + typename std::iterator_traits::difference_type dist; + for (dist = 0; first < last; ++dist) + next(first, last); + return dist; + } + + template + octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result) + { + while (start != end) { + uint32_t cp = internal::mask16(*start++); + // Take care of surrogate pairs first + if (internal::is_lead_surrogate(cp)) { + if (start != end) { + uint32_t trail_surrogate = internal::mask16(*start++); + if (internal::is_trail_surrogate(trail_surrogate)) + cp = (cp << 10) + trail_surrogate + internal::SURROGATE_OFFSET; + else + throw invalid_utf16(static_cast(trail_surrogate)); + } + else + throw invalid_utf16(static_cast(cp)); + + } + // Lone trail surrogate + else if (internal::is_trail_surrogate(cp)) + throw invalid_utf16(static_cast(cp)); + + result = append(cp, result); + } + return result; + } + + template + u16bit_iterator utf8to16 (octet_iterator start, octet_iterator end, u16bit_iterator result) + { + while (start != end) { + uint32_t cp = next(start, end); + if (cp > 0xffff) { //make a surrogate pair + *result++ = static_cast((cp >> 10) + internal::LEAD_OFFSET); + *result++ = static_cast((cp & 0x3ff) + internal::TRAIL_SURROGATE_MIN); + } + else + *result++ = static_cast(cp); + } + return result; + } + + template + octet_iterator utf32to8 (u32bit_iterator start, u32bit_iterator end, octet_iterator result) + { + while (start != end) + result = append(*(start++), result); + + return result; + } + + template + u32bit_iterator utf8to32 (octet_iterator start, octet_iterator end, u32bit_iterator result) + { + while (start != end) + (*result++) = next(start, end); + + return result; + } + + // The iterator class + template + class iterator : public std::iterator { + octet_iterator it; + octet_iterator range_start; + octet_iterator range_end; + public: + iterator () {}; + explicit iterator (const octet_iterator& octet_it, + const octet_iterator& range_start, + const octet_iterator& range_end) : + it(octet_it), range_start(range_start), range_end(range_end) + { + if (it < range_start || it > range_end) + throw std::out_of_range("Invalid utf-8 iterator position"); + } + // the default "big three" are OK + octet_iterator base () const { return it; } + uint32_t operator * () const + { + octet_iterator temp = it; + return next(temp, range_end); + } + bool operator == (const iterator& rhs) const + { + if (range_start != rhs.range_start || range_end != rhs.range_end) + throw std::logic_error("Comparing utf-8 iterators defined with different ranges"); + return (it == rhs.it); + } + bool operator != (const iterator& rhs) const + { + return !(operator == (rhs)); + } + iterator& operator ++ () + { + next(it, range_end); + return *this; + } + iterator operator ++ (int) + { + iterator temp = *this; + next(it, range_end); + return temp; + } + iterator& operator -- () + { + prior(it, range_start); + return *this; + } + iterator operator -- (int) + { + iterator temp = *this; + prior(it, range_start); + return temp; + } + }; // class iterator + +} // namespace utf8 + +#endif //header guard + + diff --git a/dep/utf8cpp/utf8/core.h b/dep/utf8cpp/utf8/core.h new file mode 100644 index 00000000000..ec709f12006 --- /dev/null +++ b/dep/utf8cpp/utf8/core.h @@ -0,0 +1,358 @@ +// Copyright 2006 Nemanja Trifunovic + +/* +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +*/ + + +#ifndef UTF8_FOR_CPP_CORE_H_2675DCD0_9480_4c0c_B92A_CC14C027B731 +#define UTF8_FOR_CPP_CORE_H_2675DCD0_9480_4c0c_B92A_CC14C027B731 + +#include + +namespace utf8 +{ + // The typedefs for 8-bit, 16-bit and 32-bit unsigned integers + // You may need to change them to match your system. + // These typedefs have the same names as ones from cstdint, or boost/cstdint + typedef unsigned char uint8_t; + typedef unsigned short uint16_t; + typedef unsigned int uint32_t; + +// Helper code - not intended to be directly called by the library users. May be changed at any time +namespace internal +{ + // Unicode constants + // Leading (high) surrogates: 0xd800 - 0xdbff + // Trailing (low) surrogates: 0xdc00 - 0xdfff + const uint16_t LEAD_SURROGATE_MIN = 0xd800u; + const uint16_t LEAD_SURROGATE_MAX = 0xdbffu; + const uint16_t TRAIL_SURROGATE_MIN = 0xdc00u; + const uint16_t TRAIL_SURROGATE_MAX = 0xdfffu; + const uint16_t LEAD_OFFSET = LEAD_SURROGATE_MIN - (0x10000 >> 10); + const uint32_t SURROGATE_OFFSET = 0x10000u - (LEAD_SURROGATE_MIN << 10) - TRAIL_SURROGATE_MIN; + + // Maximum valid value for a Unicode code point + const uint32_t CODE_POINT_MAX = 0x0010ffffu; + + template + inline uint8_t mask8(octet_type oc) + { + return static_cast(0xff & oc); + } + template + inline uint16_t mask16(u16_type oc) + { + return static_cast(0xffff & oc); + } + template + inline bool is_trail(octet_type oc) + { + return ((mask8(oc) >> 6) == 0x2); + } + + template + inline bool is_lead_surrogate(u16 cp) + { + return (cp >= LEAD_SURROGATE_MIN && cp <= LEAD_SURROGATE_MAX); + } + + template + inline bool is_trail_surrogate(u16 cp) + { + return (cp >= TRAIL_SURROGATE_MIN && cp <= TRAIL_SURROGATE_MAX); + } + + template + inline bool is_surrogate(u16 cp) + { + return (cp >= LEAD_SURROGATE_MIN && cp <= TRAIL_SURROGATE_MAX); + } + + template + inline bool is_code_point_valid(u32 cp) + { + return (cp <= CODE_POINT_MAX && !is_surrogate(cp) && cp != 0xfffe && cp != 0xffff); + } + + template + inline typename std::iterator_traits::difference_type + sequence_length(octet_iterator lead_it) + { + uint8_t lead = mask8(*lead_it); + if (lead < 0x80) + return 1; + else if ((lead >> 5) == 0x6) + return 2; + else if ((lead >> 4) == 0xe) + return 3; + else if ((lead >> 3) == 0x1e) + return 4; + else + return 0; + } + + template + inline bool is_overlong_sequence(uint32_t cp, octet_difference_type length) + { + if (cp < 0x80) { + if (length != 1) + return true; + } + else if (cp < 0x800) { + if (length != 2) + return true; + } + else if (cp < 0x10000) { + if (length != 3) + return true; + } + + return false; + } + + enum utf_error {UTF8_OK, NOT_ENOUGH_ROOM, INVALID_LEAD, INCOMPLETE_SEQUENCE, OVERLONG_SEQUENCE, INVALID_CODE_POINT}; + + /// get_sequence_x functions decode utf-8 sequences of the length x + + template + utf_error get_sequence_1(octet_iterator& it, octet_iterator end, uint32_t* code_point) + { + if (it != end) { + if (code_point) + *code_point = mask8(*it); + return UTF8_OK; + } + return NOT_ENOUGH_ROOM; + } + + template + utf_error get_sequence_2(octet_iterator& it, octet_iterator end, uint32_t* code_point) + { + utf_error ret_code = NOT_ENOUGH_ROOM; + + if (it != end) { + uint32_t cp = mask8(*it); + if (++it != end) { + if (is_trail(*it)) { + cp = ((cp << 6) & 0x7ff) + ((*it) & 0x3f); + + if (code_point) + *code_point = cp; + ret_code = UTF8_OK; + } + else + ret_code = INCOMPLETE_SEQUENCE; + } + else + ret_code = NOT_ENOUGH_ROOM; + } + + return ret_code; + } + + template + utf_error get_sequence_3(octet_iterator& it, octet_iterator end, uint32_t* code_point) + { + utf_error ret_code = NOT_ENOUGH_ROOM; + + if (it != end) { + uint32_t cp = mask8(*it); + if (++it != end) { + if (is_trail(*it)) { + cp = ((cp << 12) & 0xffff) + ((mask8(*it) << 6) & 0xfff); + if (++it != end) { + if (is_trail(*it)) { + cp += (*it) & 0x3f; + + if (code_point) + *code_point = cp; + ret_code = UTF8_OK; + } + else + ret_code = INCOMPLETE_SEQUENCE; + } + else + ret_code = NOT_ENOUGH_ROOM; + } + else + ret_code = INCOMPLETE_SEQUENCE; + } + else + ret_code = NOT_ENOUGH_ROOM; + } + + return ret_code; + } + + template + utf_error get_sequence_4(octet_iterator& it, octet_iterator end, uint32_t* code_point) + { + utf_error ret_code = NOT_ENOUGH_ROOM; + + if (it != end) { + uint32_t cp = mask8(*it); + if (++it != end) { + if (is_trail(*it)) { + cp = ((cp << 18) & 0x1fffff) + ((mask8(*it) << 12) & 0x3ffff); + if (++it != end) { + if (is_trail(*it)) { + cp += (mask8(*it) << 6) & 0xfff; + if (++it != end) { + if (is_trail(*it)) { + cp += (*it) & 0x3f; + + if (code_point) + *code_point = cp; + ret_code = UTF8_OK; + } + else + ret_code = INCOMPLETE_SEQUENCE; + } + else + ret_code = NOT_ENOUGH_ROOM; + } + else + ret_code = INCOMPLETE_SEQUENCE; + } + else + ret_code = NOT_ENOUGH_ROOM; + } + else + ret_code = INCOMPLETE_SEQUENCE; + } + else + ret_code = NOT_ENOUGH_ROOM; + } + + return ret_code; + } + + template + utf_error validate_next(octet_iterator& it, octet_iterator end, uint32_t* code_point) + { + // Save the original value of it so we can go back in case of failure + // Of course, it does not make much sense with i.e. stream iterators + octet_iterator original_it = it; + + uint32_t cp = 0; + // Determine the sequence length based on the lead octet + typedef typename std::iterator_traits::difference_type octet_difference_type; + octet_difference_type length = sequence_length(it); + if (length == 0) + return INVALID_LEAD; + + // Now that we have a valid sequence length, get trail octets and calculate the code point + utf_error err = UTF8_OK; + switch (length) { + case 1: + err = get_sequence_1(it, end, &cp); + break; + case 2: + err = get_sequence_2(it, end, &cp); + break; + case 3: + err = get_sequence_3(it, end, &cp); + break; + case 4: + err = get_sequence_4(it, end, &cp); + break; + } + + if (err == UTF8_OK) { + // Decoding succeeded. Now, security checks... + if (is_code_point_valid(cp)) { + if (!is_overlong_sequence(cp, length)){ + // Passed! Return here. + if (code_point) + *code_point = cp; + ++it; + return UTF8_OK; + } + else + err = OVERLONG_SEQUENCE; + } + else + err = INVALID_CODE_POINT; + } + + // Failure branch - restore the original value of the iterator + it = original_it; + return err; + } + + template + inline utf_error validate_next(octet_iterator& it, octet_iterator end) { + return validate_next(it, end, 0); + } + +} // namespace internal + + /// The library API - functions intended to be called by the users + + // Byte order mark + const uint8_t bom[] = {0xef, 0xbb, 0xbf}; + + template + octet_iterator find_invalid(octet_iterator start, octet_iterator end) + { + octet_iterator result = start; + while (result != end) { + internal::utf_error err_code = internal::validate_next(result, end); + if (err_code != internal::UTF8_OK) + return result; + } + return result; + } + + template + inline bool is_valid(octet_iterator start, octet_iterator end) + { + return (find_invalid(start, end) == end); + } + + template + inline bool starts_with_bom (octet_iterator it, octet_iterator end) + { + return ( + ((it != end) && (internal::mask8(*it++)) == bom[0]) && + ((it != end) && (internal::mask8(*it++)) == bom[1]) && + ((it != end) && (internal::mask8(*it)) == bom[2]) + ); + } + + //Deprecated in release 2.3 + template + inline bool is_bom (octet_iterator it) + { + return ( + (internal::mask8(*it++)) == bom[0] && + (internal::mask8(*it++)) == bom[1] && + (internal::mask8(*it)) == bom[2] + ); + } +} // namespace utf8 + +#endif // header guard + + diff --git a/dep/utf8cpp/utf8/unchecked.h b/dep/utf8cpp/utf8/unchecked.h new file mode 100644 index 00000000000..2f3eb4d1d02 --- /dev/null +++ b/dep/utf8cpp/utf8/unchecked.h @@ -0,0 +1,228 @@ +// Copyright 2006 Nemanja Trifunovic + +/* +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +*/ + + +#ifndef UTF8_FOR_CPP_UNCHECKED_H_2675DCD0_9480_4c0c_B92A_CC14C027B731 +#define UTF8_FOR_CPP_UNCHECKED_H_2675DCD0_9480_4c0c_B92A_CC14C027B731 + +#include "core.h" + +namespace utf8 +{ + namespace unchecked + { + template + octet_iterator append(uint32_t cp, octet_iterator result) + { + if (cp < 0x80) // one octet + *(result++) = static_cast(cp); + else if (cp < 0x800) { // two octets + *(result++) = static_cast((cp >> 6) | 0xc0); + *(result++) = static_cast((cp & 0x3f) | 0x80); + } + else if (cp < 0x10000) { // three octets + *(result++) = static_cast((cp >> 12) | 0xe0); + *(result++) = static_cast(((cp >> 6) & 0x3f) | 0x80); + *(result++) = static_cast((cp & 0x3f) | 0x80); + } + else { // four octets + *(result++) = static_cast((cp >> 18) | 0xf0); + *(result++) = static_cast(((cp >> 12) & 0x3f)| 0x80); + *(result++) = static_cast(((cp >> 6) & 0x3f) | 0x80); + *(result++) = static_cast((cp & 0x3f) | 0x80); + } + return result; + } + + template + uint32_t next(octet_iterator& it) + { + uint32_t cp = internal::mask8(*it); + typename std::iterator_traits::difference_type length = utf8::internal::sequence_length(it); + switch (length) { + case 1: + break; + case 2: + it++; + cp = ((cp << 6) & 0x7ff) + ((*it) & 0x3f); + break; + case 3: + ++it; + cp = ((cp << 12) & 0xffff) + ((internal::mask8(*it) << 6) & 0xfff); + ++it; + cp += (*it) & 0x3f; + break; + case 4: + ++it; + cp = ((cp << 18) & 0x1fffff) + ((internal::mask8(*it) << 12) & 0x3ffff); + ++it; + cp += (internal::mask8(*it) << 6) & 0xfff; + ++it; + cp += (*it) & 0x3f; + break; + } + ++it; + return cp; + } + + template + uint32_t peek_next(octet_iterator it) + { + return next(it); + } + + template + uint32_t prior(octet_iterator& it) + { + while (internal::is_trail(*(--it))) ; + octet_iterator temp = it; + return next(temp); + } + + // Deprecated in versions that include prior, but only for the sake of consistency (see utf8::previous) + template + inline uint32_t previous(octet_iterator& it) + { + return prior(it); + } + + template + void advance (octet_iterator& it, distance_type n) + { + for (distance_type i = 0; i < n; ++i) + next(it); + } + + template + typename std::iterator_traits::difference_type + distance (octet_iterator first, octet_iterator last) + { + typename std::iterator_traits::difference_type dist; + for (dist = 0; first < last; ++dist) + next(first); + return dist; + } + + template + octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result) + { + while (start != end) { + uint32_t cp = internal::mask16(*start++); + // Take care of surrogate pairs first + if (internal::is_lead_surrogate(cp)) { + uint32_t trail_surrogate = internal::mask16(*start++); + cp = (cp << 10) + trail_surrogate + internal::SURROGATE_OFFSET; + } + result = append(cp, result); + } + return result; + } + + template + u16bit_iterator utf8to16 (octet_iterator start, octet_iterator end, u16bit_iterator result) + { + while (start < end) { + uint32_t cp = next(start); + if (cp > 0xffff) { //make a surrogate pair + *result++ = static_cast((cp >> 10) + internal::LEAD_OFFSET); + *result++ = static_cast((cp & 0x3ff) + internal::TRAIL_SURROGATE_MIN); + } + else + *result++ = static_cast(cp); + } + return result; + } + + template + octet_iterator utf32to8 (u32bit_iterator start, u32bit_iterator end, octet_iterator result) + { + while (start != end) + result = append(*(start++), result); + + return result; + } + + template + u32bit_iterator utf8to32 (octet_iterator start, octet_iterator end, u32bit_iterator result) + { + while (start < end) + (*result++) = next(start); + + return result; + } + + // The iterator class + template + class iterator : public std::iterator { + octet_iterator it; + public: + iterator () {}; + explicit iterator (const octet_iterator& octet_it): it(octet_it) {} + // the default "big three" are OK + octet_iterator base () const { return it; } + uint32_t operator * () const + { + octet_iterator temp = it; + return next(temp); + } + bool operator == (const iterator& rhs) const + { + return (it == rhs.it); + } + bool operator != (const iterator& rhs) const + { + return !(operator == (rhs)); + } + iterator& operator ++ () + { + std::advance(it, internal::sequence_length(it)); + return *this; + } + iterator operator ++ (int) + { + iterator temp = *this; + std::advance(it, internal::sequence_length(it)); + return temp; + } + iterator& operator -- () + { + prior(it); + return *this; + } + iterator operator -- (int) + { + iterator temp = *this; + prior(it); + return temp; + } + }; // class iterator + + } // namespace utf8::unchecked +} // namespace utf8 + + +#endif // header guard + diff --git a/dep/zlib/CMakeLists.txt b/dep/zlib/CMakeLists.txt new file mode 100644 index 00000000000..98be26ae497 --- /dev/null +++ b/dep/zlib/CMakeLists.txt @@ -0,0 +1,30 @@ +# Copyright (C) 2008-2010 Trinity +# +# This file is free software; as a special exception the author gives +# unlimited permission to copy and/or distribute it, with or without +# modifications, as long as this notice is preserved. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the +# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +SET(zlib_STAT_SRCS + adler32.c + compress.c + crc32.c + deflate.c + example.c + infback.c + inffast.c + inflate.c + inftrees.c + trees.c + uncompr.c + zutil.c +) + +include_directories( + ${CMAKE_CURRENT_SOURCE_DIR} +) + +add_library(zlib STATIC ${zlib_STAT_SRCS}) diff --git a/dep/zlib/adler32.c b/dep/zlib/adler32.c new file mode 100644 index 00000000000..65ad6a5adc4 --- /dev/null +++ b/dep/zlib/adler32.c @@ -0,0 +1,169 @@ +/* adler32.c -- compute the Adler-32 checksum of a data stream + * Copyright (C) 1995-2007 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#include "zutil.h" + +#define local static + +local uLong adler32_combine_(uLong adler1, uLong adler2, z_off64_t len2); + +#define BASE 65521UL /* largest prime smaller than 65536 */ +#define NMAX 5552 +/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ + +#define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;} +#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); +#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); +#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); +#define DO16(buf) DO8(buf,0); DO8(buf,8); + +/* use NO_DIVIDE if your processor does not do division in hardware */ +#ifdef NO_DIVIDE +# define MOD(a) \ + do { \ + if (a >= (BASE << 16)) a -= (BASE << 16); \ + if (a >= (BASE << 15)) a -= (BASE << 15); \ + if (a >= (BASE << 14)) a -= (BASE << 14); \ + if (a >= (BASE << 13)) a -= (BASE << 13); \ + if (a >= (BASE << 12)) a -= (BASE << 12); \ + if (a >= (BASE << 11)) a -= (BASE << 11); \ + if (a >= (BASE << 10)) a -= (BASE << 10); \ + if (a >= (BASE << 9)) a -= (BASE << 9); \ + if (a >= (BASE << 8)) a -= (BASE << 8); \ + if (a >= (BASE << 7)) a -= (BASE << 7); \ + if (a >= (BASE << 6)) a -= (BASE << 6); \ + if (a >= (BASE << 5)) a -= (BASE << 5); \ + if (a >= (BASE << 4)) a -= (BASE << 4); \ + if (a >= (BASE << 3)) a -= (BASE << 3); \ + if (a >= (BASE << 2)) a -= (BASE << 2); \ + if (a >= (BASE << 1)) a -= (BASE << 1); \ + if (a >= BASE) a -= BASE; \ + } while (0) +# define MOD4(a) \ + do { \ + if (a >= (BASE << 4)) a -= (BASE << 4); \ + if (a >= (BASE << 3)) a -= (BASE << 3); \ + if (a >= (BASE << 2)) a -= (BASE << 2); \ + if (a >= (BASE << 1)) a -= (BASE << 1); \ + if (a >= BASE) a -= BASE; \ + } while (0) +#else +# define MOD(a) a %= BASE +# define MOD4(a) a %= BASE +#endif + +/* ========================================================================= */ +uLong ZEXPORT adler32(adler, buf, len) + uLong adler; + const Bytef *buf; + uInt len; +{ + unsigned long sum2; + unsigned n; + + /* split Adler-32 into component sums */ + sum2 = (adler >> 16) & 0xffff; + adler &= 0xffff; + + /* in case user likes doing a byte at a time, keep it fast */ + if (len == 1) { + adler += buf[0]; + if (adler >= BASE) + adler -= BASE; + sum2 += adler; + if (sum2 >= BASE) + sum2 -= BASE; + return adler | (sum2 << 16); + } + + /* initial Adler-32 value (deferred check for len == 1 speed) */ + if (buf == Z_NULL) + return 1L; + + /* in case short lengths are provided, keep it somewhat fast */ + if (len < 16) { + while (len--) { + adler += *buf++; + sum2 += adler; + } + if (adler >= BASE) + adler -= BASE; + MOD4(sum2); /* only added so many BASE's */ + return adler | (sum2 << 16); + } + + /* do length NMAX blocks -- requires just one modulo operation */ + while (len >= NMAX) { + len -= NMAX; + n = NMAX / 16; /* NMAX is divisible by 16 */ + do { + DO16(buf); /* 16 sums unrolled */ + buf += 16; + } while (--n); + MOD(adler); + MOD(sum2); + } + + /* do remaining bytes (less than NMAX, still just one modulo) */ + if (len) { /* avoid modulos if none remaining */ + while (len >= 16) { + len -= 16; + DO16(buf); + buf += 16; + } + while (len--) { + adler += *buf++; + sum2 += adler; + } + MOD(adler); + MOD(sum2); + } + + /* return recombined sums */ + return adler | (sum2 << 16); +} + +/* ========================================================================= */ +local uLong adler32_combine_(adler1, adler2, len2) + uLong adler1; + uLong adler2; + z_off64_t len2; +{ + unsigned long sum1; + unsigned long sum2; + unsigned rem; + + /* the derivation of this formula is left as an exercise for the reader */ + rem = (unsigned)(len2 % BASE); + sum1 = adler1 & 0xffff; + sum2 = rem * sum1; + MOD(sum2); + sum1 += (adler2 & 0xffff) + BASE - 1; + sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem; + if (sum1 >= BASE) sum1 -= BASE; + if (sum1 >= BASE) sum1 -= BASE; + if (sum2 >= (BASE << 1)) sum2 -= (BASE << 1); + if (sum2 >= BASE) sum2 -= BASE; + return sum1 | (sum2 << 16); +} + +/* ========================================================================= */ +uLong ZEXPORT adler32_combine(adler1, adler2, len2) + uLong adler1; + uLong adler2; + z_off_t len2; +{ + return adler32_combine_(adler1, adler2, len2); +} + +uLong ZEXPORT adler32_combine64(adler1, adler2, len2) + uLong adler1; + uLong adler2; + z_off64_t len2; +{ + return adler32_combine_(adler1, adler2, len2); +} diff --git a/dep/zlib/compress.c b/dep/zlib/compress.c new file mode 100644 index 00000000000..ea4dfbe9d7b --- /dev/null +++ b/dep/zlib/compress.c @@ -0,0 +1,80 @@ +/* compress.c -- compress a memory buffer + * Copyright (C) 1995-2005 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#define ZLIB_INTERNAL +#include "zlib.h" + +/* =========================================================================== + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least 0.1% larger than sourceLen plus + 12 bytes. Upon exit, destLen is the actual size of the compressed buffer. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ +int ZEXPORT compress2 (dest, destLen, source, sourceLen, level) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; + int level; +{ + z_stream stream; + int err; + + stream.next_in = (Bytef*)source; + stream.avail_in = (uInt)sourceLen; +#ifdef MAXSEG_64K + /* Check for source > 64K on 16-bit machine: */ + if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; +#endif + stream.next_out = dest; + stream.avail_out = (uInt)*destLen; + if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; + + stream.zalloc = (alloc_func)0; + stream.zfree = (free_func)0; + stream.opaque = (voidpf)0; + + err = deflateInit(&stream, level); + if (err != Z_OK) return err; + + err = deflate(&stream, Z_FINISH); + if (err != Z_STREAM_END) { + deflateEnd(&stream); + return err == Z_OK ? Z_BUF_ERROR : err; + } + *destLen = stream.total_out; + + err = deflateEnd(&stream); + return err; +} + +/* =========================================================================== + */ +int ZEXPORT compress (dest, destLen, source, sourceLen) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; +{ + return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION); +} + +/* =========================================================================== + If the default memLevel or windowBits for deflateInit() is changed, then + this function needs to be updated. + */ +uLong ZEXPORT compressBound (sourceLen) + uLong sourceLen; +{ + return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + + (sourceLen >> 25) + 13; +} diff --git a/dep/zlib/crc32.c b/dep/zlib/crc32.c new file mode 100644 index 00000000000..91be372d224 --- /dev/null +++ b/dep/zlib/crc32.c @@ -0,0 +1,442 @@ +/* crc32.c -- compute the CRC-32 of a data stream + * Copyright (C) 1995-2006, 2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + * + * Thanks to Rodney Brown for his contribution of faster + * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing + * tables for updating the shift register in one step with three exclusive-ors + * instead of four steps with four exclusive-ors. This results in about a + * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3. + */ + +/* @(#) $Id$ */ + +/* + Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore + protection on the static variables used to control the first-use generation + of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should + first call get_crc_table() to initialize the tables before allowing more than + one thread to use crc32(). + */ + +#ifdef MAKECRCH +# include +# ifndef DYNAMIC_CRC_TABLE +# define DYNAMIC_CRC_TABLE +# endif /* !DYNAMIC_CRC_TABLE */ +#endif /* MAKECRCH */ + +#include "zutil.h" /* for STDC and FAR definitions */ + +#define local static + +/* Find a four-byte integer type for crc32_little() and crc32_big(). */ +#ifndef NOBYFOUR +# ifdef STDC /* need ANSI C limits.h to determine sizes */ +# include +# define BYFOUR +# if (UINT_MAX == 0xffffffffUL) + typedef unsigned int u4; +# else +# if (ULONG_MAX == 0xffffffffUL) + typedef unsigned long u4; +# else +# if (USHRT_MAX == 0xffffffffUL) + typedef unsigned short u4; +# else +# undef BYFOUR /* can't find a four-byte integer type! */ +# endif +# endif +# endif +# endif /* STDC */ +#endif /* !NOBYFOUR */ + +/* Definitions for doing the crc four data bytes at a time. */ +#ifdef BYFOUR +# define REV(w) ((((w)>>24)&0xff)+(((w)>>8)&0xff00)+ \ + (((w)&0xff00)<<8)+(((w)&0xff)<<24)) + local unsigned long crc32_little OF((unsigned long, + const unsigned char FAR *, unsigned)); + local unsigned long crc32_big OF((unsigned long, + const unsigned char FAR *, unsigned)); +# define TBLS 8 +#else +# define TBLS 1 +#endif /* BYFOUR */ + +/* Local functions for crc concatenation */ +local unsigned long gf2_matrix_times OF((unsigned long *mat, + unsigned long vec)); +local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat)); +local uLong crc32_combine_(uLong crc1, uLong crc2, z_off64_t len2); + + +#ifdef DYNAMIC_CRC_TABLE + +local volatile int crc_table_empty = 1; +local unsigned long FAR crc_table[TBLS][256]; +local void make_crc_table OF((void)); +#ifdef MAKECRCH + local void write_table OF((FILE *, const unsigned long FAR *)); +#endif /* MAKECRCH */ +/* + Generate tables for a byte-wise 32-bit CRC calculation on the polynomial: + x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. + + Polynomials over GF(2) are represented in binary, one bit per coefficient, + with the lowest powers in the most significant bit. Then adding polynomials + is just exclusive-or, and multiplying a polynomial by x is a right shift by + one. If we call the above polynomial p, and represent a byte as the + polynomial q, also with the lowest power in the most significant bit (so the + byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, + where a mod b means the remainder after dividing a by b. + + This calculation is done using the shift-register method of multiplying and + taking the remainder. The register is initialized to zero, and for each + incoming bit, x^32 is added mod p to the register if the bit is a one (where + x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by + x (which is shifting right by one and adding x^32 mod p if the bit shifted + out is a one). We start with the highest power (least significant bit) of + q and repeat for all eight bits of q. + + The first table is simply the CRC of all possible eight bit values. This is + all the information needed to generate CRCs on data a byte at a time for all + combinations of CRC register values and incoming bytes. The remaining tables + allow for word-at-a-time CRC calculation for both big-endian and little- + endian machines, where a word is four bytes. +*/ +local void make_crc_table() +{ + unsigned long c; + int n, k; + unsigned long poly; /* polynomial exclusive-or pattern */ + /* terms of polynomial defining this crc (except x^32): */ + static volatile int first = 1; /* flag to limit concurrent making */ + static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; + + /* See if another task is already doing this (not thread-safe, but better + than nothing -- significantly reduces duration of vulnerability in + case the advice about DYNAMIC_CRC_TABLE is ignored) */ + if (first) { + first = 0; + + /* make exclusive-or pattern from polynomial (0xedb88320UL) */ + poly = 0UL; + for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++) + poly |= 1UL << (31 - p[n]); + + /* generate a crc for every 8-bit value */ + for (n = 0; n < 256; n++) { + c = (unsigned long)n; + for (k = 0; k < 8; k++) + c = c & 1 ? poly ^ (c >> 1) : c >> 1; + crc_table[0][n] = c; + } + +#ifdef BYFOUR + /* generate crc for each value followed by one, two, and three zeros, + and then the byte reversal of those as well as the first table */ + for (n = 0; n < 256; n++) { + c = crc_table[0][n]; + crc_table[4][n] = REV(c); + for (k = 1; k < 4; k++) { + c = crc_table[0][c & 0xff] ^ (c >> 8); + crc_table[k][n] = c; + crc_table[k + 4][n] = REV(c); + } + } +#endif /* BYFOUR */ + + crc_table_empty = 0; + } + else { /* not first */ + /* wait for the other guy to finish (not efficient, but rare) */ + while (crc_table_empty) + ; + } + +#ifdef MAKECRCH + /* write out CRC tables to crc32.h */ + { + FILE *out; + + out = fopen("crc32.h", "w"); + if (out == NULL) return; + fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n"); + fprintf(out, " * Generated automatically by crc32.c\n */\n\n"); + fprintf(out, "local const unsigned long FAR "); + fprintf(out, "crc_table[TBLS][256] =\n{\n {\n"); + write_table(out, crc_table[0]); +# ifdef BYFOUR + fprintf(out, "#ifdef BYFOUR\n"); + for (k = 1; k < 8; k++) { + fprintf(out, " },\n {\n"); + write_table(out, crc_table[k]); + } + fprintf(out, "#endif\n"); +# endif /* BYFOUR */ + fprintf(out, " }\n};\n"); + fclose(out); + } +#endif /* MAKECRCH */ +} + +#ifdef MAKECRCH +local void write_table(out, table) + FILE *out; + const unsigned long FAR *table; +{ + int n; + + for (n = 0; n < 256; n++) + fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n], + n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", ")); +} +#endif /* MAKECRCH */ + +#else /* !DYNAMIC_CRC_TABLE */ +/* ======================================================================== + * Tables of CRC-32s of all single-byte values, made by make_crc_table(). + */ +#include "crc32.h" +#endif /* DYNAMIC_CRC_TABLE */ + +/* ========================================================================= + * This function can be used by asm versions of crc32() + */ +const unsigned long FAR * ZEXPORT get_crc_table() +{ +#ifdef DYNAMIC_CRC_TABLE + if (crc_table_empty) + make_crc_table(); +#endif /* DYNAMIC_CRC_TABLE */ + return (const unsigned long FAR *)crc_table; +} + +/* ========================================================================= */ +#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8) +#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1 + +/* ========================================================================= */ +unsigned long ZEXPORT crc32(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + uInt len; +{ + if (buf == Z_NULL) return 0UL; + +#ifdef DYNAMIC_CRC_TABLE + if (crc_table_empty) + make_crc_table(); +#endif /* DYNAMIC_CRC_TABLE */ + +#ifdef BYFOUR + if (sizeof(void *) == sizeof(ptrdiff_t)) { + u4 endian; + + endian = 1; + if (*((unsigned char *)(&endian))) + return crc32_little(crc, buf, len); + else + return crc32_big(crc, buf, len); + } +#endif /* BYFOUR */ + crc = crc ^ 0xffffffffUL; + while (len >= 8) { + DO8; + len -= 8; + } + if (len) do { + DO1; + } while (--len); + return crc ^ 0xffffffffUL; +} + +#ifdef BYFOUR + +/* ========================================================================= */ +#define DOLIT4 c ^= *buf4++; \ + c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \ + crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24] +#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4 + +/* ========================================================================= */ +local unsigned long crc32_little(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + unsigned len; +{ + register u4 c; + register const u4 FAR *buf4; + + c = (u4)crc; + c = ~c; + while (len && ((ptrdiff_t)buf & 3)) { + c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); + len--; + } + + buf4 = (const u4 FAR *)(const void FAR *)buf; + while (len >= 32) { + DOLIT32; + len -= 32; + } + while (len >= 4) { + DOLIT4; + len -= 4; + } + buf = (const unsigned char FAR *)buf4; + + if (len) do { + c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); + } while (--len); + c = ~c; + return (unsigned long)c; +} + +/* ========================================================================= */ +#define DOBIG4 c ^= *++buf4; \ + c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \ + crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24] +#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4 + +/* ========================================================================= */ +local unsigned long crc32_big(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + unsigned len; +{ + register u4 c; + register const u4 FAR *buf4; + + c = REV((u4)crc); + c = ~c; + while (len && ((ptrdiff_t)buf & 3)) { + c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); + len--; + } + + buf4 = (const u4 FAR *)(const void FAR *)buf; + buf4--; + while (len >= 32) { + DOBIG32; + len -= 32; + } + while (len >= 4) { + DOBIG4; + len -= 4; + } + buf4++; + buf = (const unsigned char FAR *)buf4; + + if (len) do { + c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); + } while (--len); + c = ~c; + return (unsigned long)(REV(c)); +} + +#endif /* BYFOUR */ + +#define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */ + +/* ========================================================================= */ +local unsigned long gf2_matrix_times(mat, vec) + unsigned long *mat; + unsigned long vec; +{ + unsigned long sum; + + sum = 0; + while (vec) { + if (vec & 1) + sum ^= *mat; + vec >>= 1; + mat++; + } + return sum; +} + +/* ========================================================================= */ +local void gf2_matrix_square(square, mat) + unsigned long *square; + unsigned long *mat; +{ + int n; + + for (n = 0; n < GF2_DIM; n++) + square[n] = gf2_matrix_times(mat, mat[n]); +} + +/* ========================================================================= */ +local uLong crc32_combine_(crc1, crc2, len2) + uLong crc1; + uLong crc2; + z_off64_t len2; +{ + int n; + unsigned long row; + unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */ + unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */ + + /* degenerate case (also disallow negative lengths) */ + if (len2 <= 0) + return crc1; + + /* put operator for one zero bit in odd */ + odd[0] = 0xedb88320UL; /* CRC-32 polynomial */ + row = 1; + for (n = 1; n < GF2_DIM; n++) { + odd[n] = row; + row <<= 1; + } + + /* put operator for two zero bits in even */ + gf2_matrix_square(even, odd); + + /* put operator for four zero bits in odd */ + gf2_matrix_square(odd, even); + + /* apply len2 zeros to crc1 (first square will put the operator for one + zero byte, eight zero bits, in even) */ + do { + /* apply zeros operator for this bit of len2 */ + gf2_matrix_square(even, odd); + if (len2 & 1) + crc1 = gf2_matrix_times(even, crc1); + len2 >>= 1; + + /* if no more bits set, then done */ + if (len2 == 0) + break; + + /* another iteration of the loop with odd and even swapped */ + gf2_matrix_square(odd, even); + if (len2 & 1) + crc1 = gf2_matrix_times(odd, crc1); + len2 >>= 1; + + /* if no more bits set, then done */ + } while (len2 != 0); + + /* return combined crc */ + crc1 ^= crc2; + return crc1; +} + +/* ========================================================================= */ +uLong ZEXPORT crc32_combine(crc1, crc2, len2) + uLong crc1; + uLong crc2; + z_off_t len2; +{ + return crc32_combine_(crc1, crc2, len2); +} + +uLong ZEXPORT crc32_combine64(crc1, crc2, len2) + uLong crc1; + uLong crc2; + z_off64_t len2; +{ + return crc32_combine_(crc1, crc2, len2); +} diff --git a/dep/zlib/crc32.h b/dep/zlib/crc32.h new file mode 100644 index 00000000000..8053b6117c0 --- /dev/null +++ b/dep/zlib/crc32.h @@ -0,0 +1,441 @@ +/* crc32.h -- tables for rapid CRC calculation + * Generated automatically by crc32.c + */ + +local const unsigned long FAR crc_table[TBLS][256] = +{ + { + 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL, + 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL, + 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL, + 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL, + 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL, + 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL, + 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL, + 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL, + 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL, + 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL, + 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL, + 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL, + 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL, + 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL, + 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL, + 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL, + 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL, + 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL, + 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL, + 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL, + 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL, + 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL, + 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL, + 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL, + 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL, + 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL, + 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL, + 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL, + 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL, + 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL, + 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL, + 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL, + 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL, + 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL, + 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL, + 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL, + 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL, + 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL, + 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL, + 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL, + 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL, + 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL, + 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL, + 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL, + 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL, + 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL, + 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL, + 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL, + 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL, + 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL, + 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL, + 0x2d02ef8dUL +#ifdef BYFOUR + }, + { + 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL, + 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL, + 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL, + 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL, + 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL, + 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL, + 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL, + 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL, + 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL, + 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL, + 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL, + 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL, + 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL, + 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL, + 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL, + 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL, + 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL, + 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL, + 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL, + 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL, + 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL, + 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL, + 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL, + 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL, + 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL, + 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL, + 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL, + 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL, + 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL, + 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL, + 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL, + 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL, + 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL, + 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL, + 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL, + 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL, + 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL, + 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL, + 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL, + 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL, + 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL, + 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL, + 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL, + 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL, + 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL, + 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL, + 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL, + 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL, + 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL, + 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL, + 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL, + 0x9324fd72UL + }, + { + 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL, + 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL, + 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL, + 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL, + 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL, + 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL, + 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL, + 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL, + 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL, + 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL, + 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL, + 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL, + 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL, + 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL, + 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL, + 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL, + 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL, + 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL, + 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL, + 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL, + 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL, + 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL, + 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL, + 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL, + 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL, + 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL, + 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL, + 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL, + 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL, + 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL, + 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL, + 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL, + 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL, + 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL, + 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL, + 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL, + 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL, + 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL, + 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL, + 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL, + 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL, + 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL, + 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL, + 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL, + 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL, + 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL, + 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL, + 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL, + 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL, + 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL, + 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL, + 0xbe9834edUL + }, + { + 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL, + 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL, + 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL, + 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL, + 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL, + 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL, + 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL, + 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL, + 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL, + 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL, + 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL, + 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL, + 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL, + 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL, + 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL, + 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL, + 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL, + 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL, + 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL, + 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL, + 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL, + 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL, + 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL, + 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL, + 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL, + 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL, + 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL, + 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL, + 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL, + 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL, + 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL, + 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL, + 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL, + 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL, + 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL, + 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL, + 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL, + 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL, + 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL, + 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL, + 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL, + 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL, + 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL, + 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL, + 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL, + 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL, + 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL, + 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL, + 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL, + 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL, + 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL, + 0xde0506f1UL + }, + { + 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL, + 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL, + 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL, + 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL, + 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL, + 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL, + 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL, + 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL, + 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL, + 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL, + 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL, + 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL, + 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL, + 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL, + 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL, + 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL, + 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL, + 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL, + 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL, + 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL, + 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL, + 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL, + 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL, + 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL, + 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL, + 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL, + 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL, + 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL, + 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL, + 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL, + 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL, + 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL, + 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL, + 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL, + 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL, + 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL, + 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL, + 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL, + 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL, + 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL, + 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL, + 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL, + 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL, + 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL, + 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL, + 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL, + 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL, + 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL, + 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL, + 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL, + 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL, + 0x8def022dUL + }, + { + 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL, + 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL, + 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL, + 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL, + 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL, + 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL, + 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL, + 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL, + 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL, + 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL, + 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL, + 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL, + 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL, + 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL, + 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL, + 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL, + 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL, + 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL, + 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL, + 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL, + 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL, + 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL, + 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL, + 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL, + 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL, + 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL, + 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL, + 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL, + 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL, + 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL, + 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL, + 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL, + 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL, + 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL, + 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL, + 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL, + 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL, + 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL, + 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL, + 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL, + 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL, + 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL, + 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL, + 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL, + 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL, + 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL, + 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL, + 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL, + 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL, + 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL, + 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL, + 0x72fd2493UL + }, + { + 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL, + 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL, + 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL, + 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL, + 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL, + 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL, + 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL, + 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL, + 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL, + 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL, + 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL, + 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL, + 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL, + 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL, + 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL, + 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL, + 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL, + 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL, + 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL, + 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL, + 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL, + 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL, + 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL, + 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL, + 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL, + 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL, + 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL, + 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL, + 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL, + 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL, + 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL, + 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL, + 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL, + 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL, + 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL, + 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL, + 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL, + 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL, + 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL, + 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL, + 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL, + 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL, + 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL, + 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL, + 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL, + 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL, + 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL, + 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL, + 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL, + 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL, + 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL, + 0xed3498beUL + }, + { + 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL, + 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL, + 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL, + 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL, + 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL, + 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL, + 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL, + 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL, + 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL, + 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL, + 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL, + 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL, + 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL, + 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL, + 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL, + 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL, + 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL, + 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL, + 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL, + 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL, + 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL, + 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL, + 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL, + 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL, + 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL, + 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL, + 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL, + 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL, + 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL, + 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL, + 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL, + 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL, + 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL, + 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL, + 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL, + 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL, + 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL, + 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL, + 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL, + 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL, + 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL, + 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL, + 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL, + 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL, + 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL, + 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL, + 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL, + 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL, + 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL, + 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL, + 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL, + 0xf10605deUL +#endif + } +}; diff --git a/dep/zlib/deflate.c b/dep/zlib/deflate.c new file mode 100644 index 00000000000..5c4022f3d47 --- /dev/null +++ b/dep/zlib/deflate.c @@ -0,0 +1,1834 @@ +/* deflate.c -- compress data using the deflation algorithm + * Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * ALGORITHM + * + * The "deflation" process depends on being able to identify portions + * of the input text which are identical to earlier input (within a + * sliding window trailing behind the input currently being processed). + * + * The most straightforward technique turns out to be the fastest for + * most input files: try all possible matches and select the longest. + * The key feature of this algorithm is that insertions into the string + * dictionary are very simple and thus fast, and deletions are avoided + * completely. Insertions are performed at each input character, whereas + * string matches are performed only when the previous match ends. So it + * is preferable to spend more time in matches to allow very fast string + * insertions and avoid deletions. The matching algorithm for small + * strings is inspired from that of Rabin & Karp. A brute force approach + * is used to find longer strings when a small match has been found. + * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze + * (by Leonid Broukhis). + * A previous version of this file used a more sophisticated algorithm + * (by Fiala and Greene) which is guaranteed to run in linear amortized + * time, but has a larger average cost, uses more memory and is patented. + * However the F&G algorithm may be faster for some highly redundant + * files if the parameter max_chain_length (described below) is too large. + * + * ACKNOWLEDGEMENTS + * + * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and + * I found it in 'freeze' written by Leonid Broukhis. + * Thanks to many people for bug reports and testing. + * + * REFERENCES + * + * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification". + * Available in http://www.ietf.org/rfc/rfc1951.txt + * + * A description of the Rabin and Karp algorithm is given in the book + * "Algorithms" by R. Sedgewick, Addison-Wesley, p252. + * + * Fiala,E.R., and Greene,D.H. + * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595 + * + */ + +/* @(#) $Id$ */ + +#include "deflate.h" + +const char deflate_copyright[] = + " deflate 1.2.5 Copyright 1995-2010 Jean-loup Gailly and Mark Adler "; +/* + If you use the zlib library in a product, an acknowledgment is welcome + in the documentation of your product. If for some reason you cannot + include such an acknowledgment, I would appreciate that you keep this + copyright string in the executable of your product. + */ + +/* =========================================================================== + * Function prototypes. + */ +typedef enum { + need_more, /* block not completed, need more input or more output */ + block_done, /* block flush performed */ + finish_started, /* finish started, need only more output at next deflate */ + finish_done /* finish done, accept no more input or output */ +} block_state; + +typedef block_state (*compress_func) OF((deflate_state *s, int flush)); +/* Compression function. Returns the block state after the call. */ + +local void fill_window OF((deflate_state *s)); +local block_state deflate_stored OF((deflate_state *s, int flush)); +local block_state deflate_fast OF((deflate_state *s, int flush)); +#ifndef FASTEST +local block_state deflate_slow OF((deflate_state *s, int flush)); +#endif +local block_state deflate_rle OF((deflate_state *s, int flush)); +local block_state deflate_huff OF((deflate_state *s, int flush)); +local void lm_init OF((deflate_state *s)); +local void putShortMSB OF((deflate_state *s, uInt b)); +local void flush_pending OF((z_streamp strm)); +local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); +#ifdef ASMV + void match_init OF((void)); /* asm code initialization */ + uInt longest_match OF((deflate_state *s, IPos cur_match)); +#else +local uInt longest_match OF((deflate_state *s, IPos cur_match)); +#endif + +#ifdef DEBUG +local void check_match OF((deflate_state *s, IPos start, IPos match, + int length)); +#endif + +/* =========================================================================== + * Local data + */ + +#define NIL 0 +/* Tail of hash chains */ + +#ifndef TOO_FAR +# define TOO_FAR 4096 +#endif +/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */ + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +typedef struct config_s { + ush good_length; /* reduce lazy search above this match length */ + ush max_lazy; /* do not perform lazy search above this match length */ + ush nice_length; /* quit search above this match length */ + ush max_chain; + compress_func func; +} config; + +#ifdef FASTEST +local const config configuration_table[2] = { +/* good lazy nice chain */ +/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ +/* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */ +#else +local const config configuration_table[10] = { +/* good lazy nice chain */ +/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ +/* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */ +/* 2 */ {4, 5, 16, 8, deflate_fast}, +/* 3 */ {4, 6, 32, 32, deflate_fast}, + +/* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */ +/* 5 */ {8, 16, 32, 32, deflate_slow}, +/* 6 */ {8, 16, 128, 128, deflate_slow}, +/* 7 */ {8, 32, 128, 256, deflate_slow}, +/* 8 */ {32, 128, 258, 1024, deflate_slow}, +/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */ +#endif + +/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 + * For deflate_fast() (levels <= 3) good is ignored and lazy has a different + * meaning. + */ + +#define EQUAL 0 +/* result of memcmp for equal strings */ + +#ifndef NO_DUMMY_DECL +struct static_tree_desc_s {int dummy;}; /* for buggy compilers */ +#endif + +/* =========================================================================== + * Update a hash value with the given input byte + * IN assertion: all calls to to UPDATE_HASH are made with consecutive + * input characters, so that a running hash key can be computed from the + * previous key instead of complete recalculation each time. + */ +#define UPDATE_HASH(s,h,c) (h = (((h)<hash_shift) ^ (c)) & s->hash_mask) + + +/* =========================================================================== + * Insert string str in the dictionary and set match_head to the previous head + * of the hash chain (the most recent string with same hash key). Return + * the previous length of the hash chain. + * If this file is compiled with -DFASTEST, the compression level is forced + * to 1, and no hash chains are maintained. + * IN assertion: all calls to to INSERT_STRING are made with consecutive + * input characters and the first MIN_MATCH bytes of str are valid + * (except for the last MIN_MATCH-1 bytes of the input file). + */ +#ifdef FASTEST +#define INSERT_STRING(s, str, match_head) \ + (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ + match_head = s->head[s->ins_h], \ + s->head[s->ins_h] = (Pos)(str)) +#else +#define INSERT_STRING(s, str, match_head) \ + (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ + match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \ + s->head[s->ins_h] = (Pos)(str)) +#endif + +/* =========================================================================== + * Initialize the hash table (avoiding 64K overflow for 16 bit systems). + * prev[] will be initialized on the fly. + */ +#define CLEAR_HASH(s) \ + s->head[s->hash_size-1] = NIL; \ + zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head)); + +/* ========================================================================= */ +int ZEXPORT deflateInit_(strm, level, version, stream_size) + z_streamp strm; + int level; + const char *version; + int stream_size; +{ + return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, + Z_DEFAULT_STRATEGY, version, stream_size); + /* To do: ignore strm->next_in if we use it as window */ +} + +/* ========================================================================= */ +int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, + version, stream_size) + z_streamp strm; + int level; + int method; + int windowBits; + int memLevel; + int strategy; + const char *version; + int stream_size; +{ + deflate_state *s; + int wrap = 1; + static const char my_version[] = ZLIB_VERSION; + + ushf *overlay; + /* We overlay pending_buf and d_buf+l_buf. This works since the average + * output size for (length,distance) codes is <= 24 bits. + */ + + if (version == Z_NULL || version[0] != my_version[0] || + stream_size != sizeof(z_stream)) { + return Z_VERSION_ERROR; + } + if (strm == Z_NULL) return Z_STREAM_ERROR; + + strm->msg = Z_NULL; + if (strm->zalloc == (alloc_func)0) { + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; + } + if (strm->zfree == (free_func)0) strm->zfree = zcfree; + +#ifdef FASTEST + if (level != 0) level = 1; +#else + if (level == Z_DEFAULT_COMPRESSION) level = 6; +#endif + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } +#ifdef GZIP + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } +#endif + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED) { + return Z_STREAM_ERROR; + } + if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */ + s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state)); + if (s == Z_NULL) return Z_MEM_ERROR; + strm->state = (struct internal_state FAR *)s; + s->strm = strm; + + s->wrap = wrap; + s->gzhead = Z_NULL; + s->w_bits = windowBits; + s->w_size = 1 << s->w_bits; + s->w_mask = s->w_size - 1; + + s->hash_bits = memLevel + 7; + s->hash_size = 1 << s->hash_bits; + s->hash_mask = s->hash_size - 1; + s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); + + s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); + s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); + s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos)); + + s->high_water = 0; /* nothing written to s->window yet */ + + s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + s->pending_buf = (uchf *) overlay; + s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L); + + if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || + s->pending_buf == Z_NULL) { + s->status = FINISH_STATE; + strm->msg = (char*)ERR_MSG(Z_MEM_ERROR); + deflateEnd (strm); + return Z_MEM_ERROR; + } + s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + + s->level = level; + s->strategy = strategy; + s->method = (Byte)method; + + return deflateReset(strm); +} + +/* ========================================================================= */ +int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) + z_streamp strm; + const Bytef *dictionary; + uInt dictLength; +{ + deflate_state *s; + uInt length = dictLength; + uInt n; + IPos hash_head = 0; + + if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL || + strm->state->wrap == 2 || + (strm->state->wrap == 1 && strm->state->status != INIT_STATE)) + return Z_STREAM_ERROR; + + s = strm->state; + if (s->wrap) + strm->adler = adler32(strm->adler, dictionary, dictLength); + + if (length < MIN_MATCH) return Z_OK; + if (length > s->w_size) { + length = s->w_size; + dictionary += dictLength - length; /* use the tail of the dictionary */ + } + zmemcpy(s->window, dictionary, length); + s->strstart = length; + s->block_start = (long)length; + + /* Insert all strings in the hash table (except for the last two bytes). + * s->lookahead stays null, so s->ins_h will be recomputed at the next + * call of fill_window. + */ + s->ins_h = s->window[0]; + UPDATE_HASH(s, s->ins_h, s->window[1]); + for (n = 0; n <= length - MIN_MATCH; n++) { + INSERT_STRING(s, n, hash_head); + } + if (hash_head) hash_head = 0; /* to make compiler happy */ + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateReset (strm) + z_streamp strm; +{ + deflate_state *s; + + if (strm == Z_NULL || strm->state == Z_NULL || + strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) { + return Z_STREAM_ERROR; + } + + strm->total_in = strm->total_out = 0; + strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */ + strm->data_type = Z_UNKNOWN; + + s = (deflate_state *)strm->state; + s->pending = 0; + s->pending_out = s->pending_buf; + + if (s->wrap < 0) { + s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */ + } + s->status = s->wrap ? INIT_STATE : BUSY_STATE; + strm->adler = +#ifdef GZIP + s->wrap == 2 ? crc32(0L, Z_NULL, 0) : +#endif + adler32(0L, Z_NULL, 0); + s->last_flush = Z_NO_FLUSH; + + _tr_init(s); + lm_init(s); + + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateSetHeader (strm, head) + z_streamp strm; + gz_headerp head; +{ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + if (strm->state->wrap != 2) return Z_STREAM_ERROR; + strm->state->gzhead = head; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflatePrime (strm, bits, value) + z_streamp strm; + int bits; + int value; +{ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + strm->state->bi_valid = bits; + strm->state->bi_buf = (ush)(value & ((1 << bits) - 1)); + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateParams(strm, level, strategy) + z_streamp strm; + int level; + int strategy; +{ + deflate_state *s; + compress_func func; + int err = Z_OK; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + s = strm->state; + +#ifdef FASTEST + if (level != 0) level = 1; +#else + if (level == Z_DEFAULT_COMPRESSION) level = 6; +#endif + if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { + return Z_STREAM_ERROR; + } + func = configuration_table[s->level].func; + + if ((strategy != s->strategy || func != configuration_table[level].func) && + strm->total_in != 0) { + /* Flush the last buffer: */ + err = deflate(strm, Z_BLOCK); + } + if (s->level != level) { + s->level = level; + s->max_lazy_match = configuration_table[level].max_lazy; + s->good_match = configuration_table[level].good_length; + s->nice_match = configuration_table[level].nice_length; + s->max_chain_length = configuration_table[level].max_chain; + } + s->strategy = strategy; + return err; +} + +/* ========================================================================= */ +int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain) + z_streamp strm; + int good_length; + int max_lazy; + int nice_length; + int max_chain; +{ + deflate_state *s; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + s = strm->state; + s->good_match = good_length; + s->max_lazy_match = max_lazy; + s->nice_match = nice_length; + s->max_chain_length = max_chain; + return Z_OK; +} + +/* ========================================================================= + * For the default windowBits of 15 and memLevel of 8, this function returns + * a close to exact, as well as small, upper bound on the compressed size. + * They are coded as constants here for a reason--if the #define's are + * changed, then this function needs to be changed as well. The return + * value for 15 and 8 only works for those exact settings. + * + * For any setting other than those defaults for windowBits and memLevel, + * the value returned is a conservative worst case for the maximum expansion + * resulting from using fixed blocks instead of stored blocks, which deflate + * can emit on compressed data for some combinations of the parameters. + * + * This function could be more sophisticated to provide closer upper bounds for + * every combination of windowBits and memLevel. But even the conservative + * upper bound of about 14% expansion does not seem onerous for output buffer + * allocation. + */ +uLong ZEXPORT deflateBound(strm, sourceLen) + z_streamp strm; + uLong sourceLen; +{ + deflate_state *s; + uLong complen, wraplen; + Bytef *str; + + /* conservative upper bound for compressed data */ + complen = sourceLen + + ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5; + + /* if can't get parameters, return conservative bound plus zlib wrapper */ + if (strm == Z_NULL || strm->state == Z_NULL) + return complen + 6; + + /* compute wrapper length */ + s = strm->state; + switch (s->wrap) { + case 0: /* raw deflate */ + wraplen = 0; + break; + case 1: /* zlib wrapper */ + wraplen = 6 + (s->strstart ? 4 : 0); + break; + case 2: /* gzip wrapper */ + wraplen = 18; + if (s->gzhead != Z_NULL) { /* user-supplied gzip header */ + if (s->gzhead->extra != Z_NULL) + wraplen += 2 + s->gzhead->extra_len; + str = s->gzhead->name; + if (str != Z_NULL) + do { + wraplen++; + } while (*str++); + str = s->gzhead->comment; + if (str != Z_NULL) + do { + wraplen++; + } while (*str++); + if (s->gzhead->hcrc) + wraplen += 2; + } + break; + default: /* for compiler happiness */ + wraplen = 6; + } + + /* if not default parameters, return conservative bound */ + if (s->w_bits != 15 || s->hash_bits != 8 + 7) + return complen + wraplen; + + /* default settings: return tight bound for that case */ + return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + + (sourceLen >> 25) + 13 - 6 + wraplen; +} + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +local void putShortMSB (s, b) + deflate_state *s; + uInt b; +{ + put_byte(s, (Byte)(b >> 8)); + put_byte(s, (Byte)(b & 0xff)); +} + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->next_out buffer and copying into it. + * (See also read_buf()). + */ +local void flush_pending(strm) + z_streamp strm; +{ + unsigned len = strm->state->pending; + + if (len > strm->avail_out) len = strm->avail_out; + if (len == 0) return; + + zmemcpy(strm->next_out, strm->state->pending_out, len); + strm->next_out += len; + strm->state->pending_out += len; + strm->total_out += len; + strm->avail_out -= len; + strm->state->pending -= len; + if (strm->state->pending == 0) { + strm->state->pending_out = strm->state->pending_buf; + } +} + +/* ========================================================================= */ +int ZEXPORT deflate (strm, flush) + z_streamp strm; + int flush; +{ + int old_flush; /* value of flush param for previous deflate call */ + deflate_state *s; + + if (strm == Z_NULL || strm->state == Z_NULL || + flush > Z_BLOCK || flush < 0) { + return Z_STREAM_ERROR; + } + s = strm->state; + + if (strm->next_out == Z_NULL || + (strm->next_in == Z_NULL && strm->avail_in != 0) || + (s->status == FINISH_STATE && flush != Z_FINISH)) { + ERR_RETURN(strm, Z_STREAM_ERROR); + } + if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR); + + s->strm = strm; /* just in case */ + old_flush = s->last_flush; + s->last_flush = flush; + + /* Write the header */ + if (s->status == INIT_STATE) { +#ifdef GZIP + if (s->wrap == 2) { + strm->adler = crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (s->gzhead == Z_NULL) { + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s->level == 9 ? 2 : + (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s->status = BUSY_STATE; + } + else { + put_byte(s, (s->gzhead->text ? 1 : 0) + + (s->gzhead->hcrc ? 2 : 0) + + (s->gzhead->extra == Z_NULL ? 0 : 4) + + (s->gzhead->name == Z_NULL ? 0 : 8) + + (s->gzhead->comment == Z_NULL ? 0 : 16) + ); + put_byte(s, (Byte)(s->gzhead->time & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff)); + put_byte(s, s->level == 9 ? 2 : + (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? + 4 : 0)); + put_byte(s, s->gzhead->os & 0xff); + if (s->gzhead->extra != Z_NULL) { + put_byte(s, s->gzhead->extra_len & 0xff); + put_byte(s, (s->gzhead->extra_len >> 8) & 0xff); + } + if (s->gzhead->hcrc) + strm->adler = crc32(strm->adler, s->pending_buf, + s->pending); + s->gzindex = 0; + s->status = EXTRA_STATE; + } + } + else +#endif + { + uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; + uInt level_flags; + + if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2) + level_flags = 0; + else if (s->level < 6) + level_flags = 1; + else if (s->level == 6) + level_flags = 2; + else + level_flags = 3; + header |= (level_flags << 6); + if (s->strstart != 0) header |= PRESET_DICT; + header += 31 - (header % 31); + + s->status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s->strstart != 0) { + putShortMSB(s, (uInt)(strm->adler >> 16)); + putShortMSB(s, (uInt)(strm->adler & 0xffff)); + } + strm->adler = adler32(0L, Z_NULL, 0); + } + } +#ifdef GZIP + if (s->status == EXTRA_STATE) { + if (s->gzhead->extra != Z_NULL) { + uInt beg = s->pending; /* start of bytes to update crc */ + + while (s->gzindex < (s->gzhead->extra_len & 0xffff)) { + if (s->pending == s->pending_buf_size) { + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + flush_pending(strm); + beg = s->pending; + if (s->pending == s->pending_buf_size) + break; + } + put_byte(s, s->gzhead->extra[s->gzindex]); + s->gzindex++; + } + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + if (s->gzindex == s->gzhead->extra_len) { + s->gzindex = 0; + s->status = NAME_STATE; + } + } + else + s->status = NAME_STATE; + } + if (s->status == NAME_STATE) { + if (s->gzhead->name != Z_NULL) { + uInt beg = s->pending; /* start of bytes to update crc */ + int val; + + do { + if (s->pending == s->pending_buf_size) { + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + flush_pending(strm); + beg = s->pending; + if (s->pending == s->pending_buf_size) { + val = 1; + break; + } + } + val = s->gzhead->name[s->gzindex++]; + put_byte(s, val); + } while (val != 0); + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + if (val == 0) { + s->gzindex = 0; + s->status = COMMENT_STATE; + } + } + else + s->status = COMMENT_STATE; + } + if (s->status == COMMENT_STATE) { + if (s->gzhead->comment != Z_NULL) { + uInt beg = s->pending; /* start of bytes to update crc */ + int val; + + do { + if (s->pending == s->pending_buf_size) { + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + flush_pending(strm); + beg = s->pending; + if (s->pending == s->pending_buf_size) { + val = 1; + break; + } + } + val = s->gzhead->comment[s->gzindex++]; + put_byte(s, val); + } while (val != 0); + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + if (val == 0) + s->status = HCRC_STATE; + } + else + s->status = HCRC_STATE; + } + if (s->status == HCRC_STATE) { + if (s->gzhead->hcrc) { + if (s->pending + 2 > s->pending_buf_size) + flush_pending(strm); + if (s->pending + 2 <= s->pending_buf_size) { + put_byte(s, (Byte)(strm->adler & 0xff)); + put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); + strm->adler = crc32(0L, Z_NULL, 0); + s->status = BUSY_STATE; + } + } + else + s->status = BUSY_STATE; + } +#endif + + /* Flush as much pending output as possible */ + if (s->pending != 0) { + flush_pending(strm); + if (strm->avail_out == 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s->last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm->avail_in == 0 && flush <= old_flush && + flush != Z_FINISH) { + ERR_RETURN(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s->status == FINISH_STATE && strm->avail_in != 0) { + ERR_RETURN(strm, Z_BUF_ERROR); + } + + /* Start a new block or continue the current one. + */ + if (strm->avail_in != 0 || s->lookahead != 0 || + (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { + block_state bstate; + + bstate = s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) : + (s->strategy == Z_RLE ? deflate_rle(s, flush) : + (*(configuration_table[s->level].func))(s, flush)); + + if (bstate == finish_started || bstate == finish_done) { + s->status = FINISH_STATE; + } + if (bstate == need_more || bstate == finish_started) { + if (strm->avail_out == 0) { + s->last_flush = -1; /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate == block_done) { + if (flush == Z_PARTIAL_FLUSH) { + _tr_align(s); + } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ + _tr_stored_block(s, (char*)0, 0L, 0); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush == Z_FULL_FLUSH) { + CLEAR_HASH(s); /* forget history */ + if (s->lookahead == 0) { + s->strstart = 0; + s->block_start = 0L; + } + } + } + flush_pending(strm); + if (strm->avail_out == 0) { + s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + Assert(strm->avail_out > 0, "bug2"); + + if (flush != Z_FINISH) return Z_OK; + if (s->wrap <= 0) return Z_STREAM_END; + + /* Write the trailer */ +#ifdef GZIP + if (s->wrap == 2) { + put_byte(s, (Byte)(strm->adler & 0xff)); + put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); + put_byte(s, (Byte)((strm->adler >> 16) & 0xff)); + put_byte(s, (Byte)((strm->adler >> 24) & 0xff)); + put_byte(s, (Byte)(strm->total_in & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 8) & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 16) & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 24) & 0xff)); + } + else +#endif + { + putShortMSB(s, (uInt)(strm->adler >> 16)); + putShortMSB(s, (uInt)(strm->adler & 0xffff)); + } + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */ + return s->pending != 0 ? Z_OK : Z_STREAM_END; +} + +/* ========================================================================= */ +int ZEXPORT deflateEnd (strm) + z_streamp strm; +{ + int status; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + + status = strm->state->status; + if (status != INIT_STATE && + status != EXTRA_STATE && + status != NAME_STATE && + status != COMMENT_STATE && + status != HCRC_STATE && + status != BUSY_STATE && + status != FINISH_STATE) { + return Z_STREAM_ERROR; + } + + /* Deallocate in reverse order of allocations: */ + TRY_FREE(strm, strm->state->pending_buf); + TRY_FREE(strm, strm->state->head); + TRY_FREE(strm, strm->state->prev); + TRY_FREE(strm, strm->state->window); + + ZFREE(strm, strm->state); + strm->state = Z_NULL; + + return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK; +} + +/* ========================================================================= + * Copy the source state to the destination state. + * To simplify the source, this is not supported for 16-bit MSDOS (which + * doesn't have enough memory anyway to duplicate compression states). + */ +int ZEXPORT deflateCopy (dest, source) + z_streamp dest; + z_streamp source; +{ +#ifdef MAXSEG_64K + return Z_STREAM_ERROR; +#else + deflate_state *ds; + deflate_state *ss; + ushf *overlay; + + + if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) { + return Z_STREAM_ERROR; + } + + ss = source->state; + + zmemcpy(dest, source, sizeof(z_stream)); + + ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state)); + if (ds == Z_NULL) return Z_MEM_ERROR; + dest->state = (struct internal_state FAR *) ds; + zmemcpy(ds, ss, sizeof(deflate_state)); + ds->strm = dest; + + ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); + ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos)); + ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos)); + overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2); + ds->pending_buf = (uchf *) overlay; + + if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || + ds->pending_buf == Z_NULL) { + deflateEnd (dest); + return Z_MEM_ERROR; + } + /* following zmemcpy do not work for 16-bit MSDOS */ + zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte)); + zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos)); + zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos)); + zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); + + ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); + ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush); + ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize; + + ds->l_desc.dyn_tree = ds->dyn_ltree; + ds->d_desc.dyn_tree = ds->dyn_dtree; + ds->bl_desc.dyn_tree = ds->bl_tree; + + return Z_OK; +#endif /* MAXSEG_64K */ +} + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->next_in buffer and copying from it. + * (See also flush_pending()). + */ +local int read_buf(strm, buf, size) + z_streamp strm; + Bytef *buf; + unsigned size; +{ + unsigned len = strm->avail_in; + + if (len > size) len = size; + if (len == 0) return 0; + + strm->avail_in -= len; + + if (strm->state->wrap == 1) { + strm->adler = adler32(strm->adler, strm->next_in, len); + } +#ifdef GZIP + else if (strm->state->wrap == 2) { + strm->adler = crc32(strm->adler, strm->next_in, len); + } +#endif + zmemcpy(buf, strm->next_in, len); + strm->next_in += len; + strm->total_in += len; + + return (int)len; +} + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +local void lm_init (s) + deflate_state *s; +{ + s->window_size = (ulg)2L*s->w_size; + + CLEAR_HASH(s); + + /* Set the default configuration parameters: + */ + s->max_lazy_match = configuration_table[s->level].max_lazy; + s->good_match = configuration_table[s->level].good_length; + s->nice_match = configuration_table[s->level].nice_length; + s->max_chain_length = configuration_table[s->level].max_chain; + + s->strstart = 0; + s->block_start = 0L; + s->lookahead = 0; + s->match_length = s->prev_length = MIN_MATCH-1; + s->match_available = 0; + s->ins_h = 0; +#ifndef FASTEST +#ifdef ASMV + match_init(); /* initialize the asm code */ +#endif +#endif +} + +#ifndef FASTEST +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +#ifndef ASMV +/* For 80x86 and 680x0, an optimized version will be provided in match.asm or + * match.S. The code will be functionally equivalent. + */ +local uInt longest_match(s, cur_match) + deflate_state *s; + IPos cur_match; /* current match */ +{ + unsigned chain_length = s->max_chain_length;/* max hash chain length */ + register Bytef *scan = s->window + s->strstart; /* current string */ + register Bytef *match; /* matched string */ + register int len; /* length of current match */ + int best_len = s->prev_length; /* best match length so far */ + int nice_match = s->nice_match; /* stop if match long enough */ + IPos limit = s->strstart > (IPos)MAX_DIST(s) ? + s->strstart - (IPos)MAX_DIST(s) : NIL; + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + Posf *prev = s->prev; + uInt wmask = s->w_mask; + +#ifdef UNALIGNED_OK + /* Compare two bytes at a time. Note: this is not always beneficial. + * Try with and without -DUNALIGNED_OK to check. + */ + register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1; + register ush scan_start = *(ushf*)scan; + register ush scan_end = *(ushf*)(scan+best_len-1); +#else + register Bytef *strend = s->window + s->strstart + MAX_MATCH; + register Byte scan_end1 = scan[best_len-1]; + register Byte scan_end = scan[best_len]; +#endif + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s->prev_length >= s->good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; + + Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + Assert(cur_match < s->strstart, "no future"); + match = s->window + cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ +#if (defined(UNALIGNED_OK) && MAX_MATCH == 258) + /* This code assumes sizeof(unsigned short) == 2. Do not use + * UNALIGNED_OK if your compiler uses a different size. + */ + if (*(ushf*)(match+best_len-1) != scan_end || + *(ushf*)match != scan_start) continue; + + /* It is not necessary to compare scan[2] and match[2] since they are + * always equal when the other bytes match, given that the hash keys + * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at + * strstart+3, +5, ... up to strstart+257. We check for insufficient + * lookahead only every 4th comparison; the 128th check will be made + * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is + * necessary to put more guard bytes at the end of the window, or + * to check more often for insufficient lookahead. + */ + Assert(scan[2] == match[2], "scan[2]?"); + scan++, match++; + do { + } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + scan < strend); + /* The funny "do {}" generates better code on most compilers */ + + /* Here, scan <= window+strstart+257 */ + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + if (*scan == *match) scan++; + + len = (MAX_MATCH - 1) - (int)(strend-scan); + scan = strend - (MAX_MATCH-1); + +#else /* UNALIGNED_OK */ + + if (match[best_len] != scan_end || + match[best_len-1] != scan_end1 || + *match != *scan || + *++match != scan[1]) continue; + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2, match++; + Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + scan < strend); + + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + scan = strend - MAX_MATCH; + +#endif /* UNALIGNED_OK */ + + if (len > best_len) { + s->match_start = cur_match; + best_len = len; + if (len >= nice_match) break; +#ifdef UNALIGNED_OK + scan_end = *(ushf*)(scan+best_len-1); +#else + scan_end1 = scan[best_len-1]; + scan_end = scan[best_len]; +#endif + } + } while ((cur_match = prev[cur_match & wmask]) > limit + && --chain_length != 0); + + if ((uInt)best_len <= s->lookahead) return (uInt)best_len; + return s->lookahead; +} +#endif /* ASMV */ + +#else /* FASTEST */ + +/* --------------------------------------------------------------------------- + * Optimized version for FASTEST only + */ +local uInt longest_match(s, cur_match) + deflate_state *s; + IPos cur_match; /* current match */ +{ + register Bytef *scan = s->window + s->strstart; /* current string */ + register Bytef *match; /* matched string */ + register int len; /* length of current match */ + register Bytef *strend = s->window + s->strstart + MAX_MATCH; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + Assert(cur_match < s->strstart, "no future"); + + match = s->window + cur_match; + + /* Return failure if the match length is less than 2: + */ + if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1; + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2, match += 2; + Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + scan < strend); + + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + + if (len < MIN_MATCH) return MIN_MATCH - 1; + + s->match_start = cur_match; + return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead; +} + +#endif /* FASTEST */ + +#ifdef DEBUG +/* =========================================================================== + * Check that the match at match_start is indeed a match. + */ +local void check_match(s, start, match, length) + deflate_state *s; + IPos start, match; + int length; +{ + /* check that the match is indeed a match */ + if (zmemcmp(s->window + match, + s->window + start, length) != EQUAL) { + fprintf(stderr, " start %u, match %u, length %d\n", + start, match, length); + do { + fprintf(stderr, "%c%c", s->window[match++], s->window[start++]); + } while (--length != 0); + z_error("invalid match"); + } + if (z_verbose > 1) { + fprintf(stderr,"\\[%d,%d]", start-match, length); + do { putc(s->window[start++], stderr); } while (--length != 0); + } +} +#else +# define check_match(s, start, match, length) +#endif /* DEBUG */ + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +local void fill_window(s) + deflate_state *s; +{ + register unsigned n, m; + register Posf *p; + unsigned more; /* Amount of free space at the end of the window. */ + uInt wsize = s->w_size; + + do { + more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); + + /* Deal with !@#$% 64K limit: */ + if (sizeof(int) <= 2) { + if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + more = wsize; + + } else if (more == (unsigned)(-1)) { + /* Very unlikely, but possible on 16 bit machine if + * strstart == 0 && lookahead == 1 (input done a byte at time) + */ + more--; + } + } + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s->strstart >= wsize+MAX_DIST(s)) { + + zmemcpy(s->window, s->window+wsize, (unsigned)wsize); + s->match_start -= wsize; + s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ + s->block_start -= (long) wsize; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + n = s->hash_size; + p = &s->head[n]; + do { + m = *--p; + *p = (Pos)(m >= wsize ? m-wsize : NIL); + } while (--n); + + n = wsize; +#ifndef FASTEST + p = &s->prev[n]; + do { + m = *--p; + *p = (Pos)(m >= wsize ? m-wsize : NIL); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); +#endif + more += wsize; + } + if (s->strm->avail_in == 0) return; + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + Assert(more >= 2, "more < 2"); + + n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); + s->lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s->lookahead >= MIN_MATCH) { + s->ins_h = s->window[s->strstart]; + UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); +#if MIN_MATCH != 3 + Call UPDATE_HASH() MIN_MATCH-3 more times +#endif + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ + if (s->high_water < s->window_size) { + ulg curr = s->strstart + (ulg)(s->lookahead); + ulg init; + + if (s->high_water < curr) { + /* Previous high water mark below current data -- zero WIN_INIT + * bytes or up to end of window, whichever is less. + */ + init = s->window_size - curr; + if (init > WIN_INIT) + init = WIN_INIT; + zmemzero(s->window + curr, (unsigned)init); + s->high_water = curr + init; + } + else if (s->high_water < (ulg)curr + WIN_INIT) { + /* High water mark at or above current data, but below current data + * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up + * to end of window, whichever is less. + */ + init = (ulg)curr + WIN_INIT - s->high_water; + if (init > s->window_size - s->high_water) + init = s->window_size - s->high_water; + zmemzero(s->window + s->high_water, (unsigned)init); + s->high_water += init; + } + } +} + +/* =========================================================================== + * Flush the current block, with given end-of-file flag. + * IN assertion: strstart is set to the end of the current match. + */ +#define FLUSH_BLOCK_ONLY(s, last) { \ + _tr_flush_block(s, (s->block_start >= 0L ? \ + (charf *)&s->window[(unsigned)s->block_start] : \ + (charf *)Z_NULL), \ + (ulg)((long)s->strstart - s->block_start), \ + (last)); \ + s->block_start = s->strstart; \ + flush_pending(s->strm); \ + Tracev((stderr,"[FLUSH]")); \ +} + +/* Same but force premature exit if necessary. */ +#define FLUSH_BLOCK(s, last) { \ + FLUSH_BLOCK_ONLY(s, last); \ + if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \ +} + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ +local block_state deflate_stored(s, flush) + deflate_state *s; + int flush; +{ + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + ulg max_block_size = 0xffff; + ulg max_start; + + if (max_block_size > s->pending_buf_size - 5) { + max_block_size = s->pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s->lookahead <= 1) { + + Assert(s->strstart < s->w_size+MAX_DIST(s) || + s->block_start >= (long)s->w_size, "slide too late"); + + fill_window(s); + if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more; + + if (s->lookahead == 0) break; /* flush the current block */ + } + Assert(s->block_start >= 0L, "block gone"); + + s->strstart += s->lookahead; + s->lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + max_start = s->block_start + max_block_size; + if (s->strstart == 0 || (ulg)s->strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s->lookahead = (uInt)(s->strstart - max_start); + s->strstart = (uInt)max_start; + FLUSH_BLOCK(s, 0); + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) { + FLUSH_BLOCK(s, 0); + } + } + FLUSH_BLOCK(s, flush == Z_FINISH); + return flush == Z_FINISH ? finish_done : block_done; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +local block_state deflate_fast(s, flush) + deflate_state *s; + int flush; +{ + IPos hash_head; /* head of the hash chain */ + int bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s->lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = NIL; + if (s->lookahead >= MIN_MATCH) { + INSERT_STRING(s, s->strstart, hash_head); + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s->match_length = longest_match (s, hash_head); + /* longest_match() sets match_start */ + } + if (s->match_length >= MIN_MATCH) { + check_match(s, s->strstart, s->match_start, s->match_length); + + _tr_tally_dist(s, s->strstart - s->match_start, + s->match_length - MIN_MATCH, bflush); + + s->lookahead -= s->match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ +#ifndef FASTEST + if (s->match_length <= s->max_insert_length && + s->lookahead >= MIN_MATCH) { + s->match_length--; /* string at strstart already in table */ + do { + s->strstart++; + INSERT_STRING(s, s->strstart, hash_head); + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s->match_length != 0); + s->strstart++; + } else +#endif + { + s->strstart += s->match_length; + s->match_length = 0; + s->ins_h = s->window[s->strstart]; + UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); +#if MIN_MATCH != 3 + Call UPDATE_HASH() MIN_MATCH-3 more times +#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + } + if (bflush) FLUSH_BLOCK(s, 0); + } + FLUSH_BLOCK(s, flush == Z_FINISH); + return flush == Z_FINISH ? finish_done : block_done; +} + +#ifndef FASTEST +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +local block_state deflate_slow(s, flush) + deflate_state *s; + int flush; +{ + IPos hash_head; /* head of hash chain */ + int bflush; /* set if current block must be flushed */ + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s->lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = NIL; + if (s->lookahead >= MIN_MATCH) { + INSERT_STRING(s, s->strstart, hash_head); + } + + /* Find the longest match, discarding those <= prev_length. + */ + s->prev_length = s->match_length, s->prev_match = s->match_start; + s->match_length = MIN_MATCH-1; + + if (hash_head != NIL && s->prev_length < s->max_lazy_match && + s->strstart - hash_head <= MAX_DIST(s)) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s->match_length = longest_match (s, hash_head); + /* longest_match() sets match_start */ + + if (s->match_length <= 5 && (s->strategy == Z_FILTERED +#if TOO_FAR <= 32767 + || (s->match_length == MIN_MATCH && + s->strstart - s->match_start > TOO_FAR) +#endif + )) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s->match_length = MIN_MATCH-1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) { + uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + check_match(s, s->strstart-1, s->prev_match, s->prev_length); + + _tr_tally_dist(s, s->strstart -1 - s->prev_match, + s->prev_length - MIN_MATCH, bflush); + + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s->lookahead -= s->prev_length-1; + s->prev_length -= 2; + do { + if (++s->strstart <= max_insert) { + INSERT_STRING(s, s->strstart, hash_head); + } + } while (--s->prev_length != 0); + s->match_available = 0; + s->match_length = MIN_MATCH-1; + s->strstart++; + + if (bflush) FLUSH_BLOCK(s, 0); + + } else if (s->match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + Tracevv((stderr,"%c", s->window[s->strstart-1])); + _tr_tally_lit(s, s->window[s->strstart-1], bflush); + if (bflush) { + FLUSH_BLOCK_ONLY(s, 0); + } + s->strstart++; + s->lookahead--; + if (s->strm->avail_out == 0) return need_more; + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s->match_available = 1; + s->strstart++; + s->lookahead--; + } + } + Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s->match_available) { + Tracevv((stderr,"%c", s->window[s->strstart-1])); + _tr_tally_lit(s, s->window[s->strstart-1], bflush); + s->match_available = 0; + } + FLUSH_BLOCK(s, flush == Z_FINISH); + return flush == Z_FINISH ? finish_done : block_done; +} +#endif /* FASTEST */ + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +local block_state deflate_rle(s, flush) + deflate_state *s; + int flush; +{ + int bflush; /* set if current block must be flushed */ + uInt prev; /* byte at distance one to match */ + Bytef *scan, *strend; /* scan goes up to strend for length of run */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest encodable run. + */ + if (s->lookahead < MAX_MATCH) { + fill_window(s); + if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s->match_length = 0; + if (s->lookahead >= MIN_MATCH && s->strstart > 0) { + scan = s->window + s->strstart - 1; + prev = *scan; + if (prev == *++scan && prev == *++scan && prev == *++scan) { + strend = s->window + s->strstart + MAX_MATCH; + do { + } while (prev == *++scan && prev == *++scan && + prev == *++scan && prev == *++scan && + prev == *++scan && prev == *++scan && + prev == *++scan && prev == *++scan && + scan < strend); + s->match_length = MAX_MATCH - (int)(strend - scan); + if (s->match_length > s->lookahead) + s->match_length = s->lookahead; + } + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s->match_length >= MIN_MATCH) { + check_match(s, s->strstart, s->strstart - 1, s->match_length); + + _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush); + + s->lookahead -= s->match_length; + s->strstart += s->match_length; + s->match_length = 0; + } else { + /* No match, output a literal byte */ + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + } + if (bflush) FLUSH_BLOCK(s, 0); + } + FLUSH_BLOCK(s, flush == Z_FINISH); + return flush == Z_FINISH ? finish_done : block_done; +} + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +local block_state deflate_huff(s, flush) + deflate_state *s; + int flush; +{ + int bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s->lookahead == 0) { + fill_window(s); + if (s->lookahead == 0) { + if (flush == Z_NO_FLUSH) + return need_more; + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s->match_length = 0; + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + if (bflush) FLUSH_BLOCK(s, 0); + } + FLUSH_BLOCK(s, flush == Z_FINISH); + return flush == Z_FINISH ? finish_done : block_done; +} diff --git a/dep/zlib/deflate.h b/dep/zlib/deflate.h new file mode 100644 index 00000000000..cbf0d1ea5d9 --- /dev/null +++ b/dep/zlib/deflate.h @@ -0,0 +1,342 @@ +/* deflate.h -- internal compression state + * Copyright (C) 1995-2010 Jean-loup Gailly + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* @(#) $Id$ */ + +#ifndef DEFLATE_H +#define DEFLATE_H + +#include "zutil.h" + +/* define NO_GZIP when compiling if you want to disable gzip header and + trailer creation by deflate(). NO_GZIP would be used to avoid linking in + the crc code when it is not needed. For shared libraries, gzip encoding + should be left enabled. */ +#ifndef NO_GZIP +# define GZIP +#endif + +/* =========================================================================== + * Internal compression state. + */ + +#define LENGTH_CODES 29 +/* number of length codes, not counting the special END_BLOCK code */ + +#define LITERALS 256 +/* number of literal bytes 0..255 */ + +#define L_CODES (LITERALS+1+LENGTH_CODES) +/* number of Literal or Length codes, including the END_BLOCK code */ + +#define D_CODES 30 +/* number of distance codes */ + +#define BL_CODES 19 +/* number of codes used to transfer the bit lengths */ + +#define HEAP_SIZE (2*L_CODES+1) +/* maximum heap size */ + +#define MAX_BITS 15 +/* All codes must not exceed MAX_BITS bits */ + +#define INIT_STATE 42 +#define EXTRA_STATE 69 +#define NAME_STATE 73 +#define COMMENT_STATE 91 +#define HCRC_STATE 103 +#define BUSY_STATE 113 +#define FINISH_STATE 666 +/* Stream status */ + + +/* Data structure describing a single value and its code string. */ +typedef struct ct_data_s { + union { + ush freq; /* frequency count */ + ush code; /* bit string */ + } fc; + union { + ush dad; /* father node in Huffman tree */ + ush len; /* length of bit string */ + } dl; +} FAR ct_data; + +#define Freq fc.freq +#define Code fc.code +#define Dad dl.dad +#define Len dl.len + +typedef struct static_tree_desc_s static_tree_desc; + +typedef struct tree_desc_s { + ct_data *dyn_tree; /* the dynamic tree */ + int max_code; /* largest code with non zero frequency */ + static_tree_desc *stat_desc; /* the corresponding static tree */ +} FAR tree_desc; + +typedef ush Pos; +typedef Pos FAR Posf; +typedef unsigned IPos; + +/* A Pos is an index in the character window. We use short instead of int to + * save space in the various tables. IPos is used only for parameter passing. + */ + +typedef struct internal_state { + z_streamp strm; /* pointer back to this zlib stream */ + int status; /* as the name implies */ + Bytef *pending_buf; /* output still pending */ + ulg pending_buf_size; /* size of pending_buf */ + Bytef *pending_out; /* next pending byte to output to the stream */ + uInt pending; /* nb of bytes in the pending buffer */ + int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ + gz_headerp gzhead; /* gzip header information to write */ + uInt gzindex; /* where in extra, name, or comment */ + Byte method; /* STORED (for zip only) or DEFLATED */ + int last_flush; /* value of flush param for previous deflate call */ + + /* used by deflate.c: */ + + uInt w_size; /* LZ77 window size (32K by default) */ + uInt w_bits; /* log2(w_size) (8..16) */ + uInt w_mask; /* w_size - 1 */ + + Bytef *window; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. Also, it limits + * the window size to 64K, which is quite useful on MSDOS. + * To do: use the user input buffer as sliding window. + */ + + ulg window_size; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + Posf *prev; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + Posf *head; /* Heads of the hash chains or NIL. */ + + uInt ins_h; /* hash index of string to be inserted */ + uInt hash_size; /* number of elements in hash table */ + uInt hash_bits; /* log2(hash_size) */ + uInt hash_mask; /* hash_size-1 */ + + uInt hash_shift; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + long block_start; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + uInt match_length; /* length of best match */ + IPos prev_match; /* previous match */ + int match_available; /* set if previous match exists */ + uInt strstart; /* start of string to insert */ + uInt match_start; /* start of matching string */ + uInt lookahead; /* number of valid bytes ahead in window */ + + uInt prev_length; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + uInt max_chain_length; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + uInt max_lazy_match; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ +# define max_insert_length max_lazy_match + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + int level; /* compression level (1..9) */ + int strategy; /* favor or force Huffman coding*/ + + uInt good_match; + /* Use a faster search when the previous match is longer than this */ + + int nice_match; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + /* Didn't use ct_data typedef below to supress compiler warning */ + struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + struct tree_desc_s l_desc; /* desc. for literal tree */ + struct tree_desc_s d_desc; /* desc. for distance tree */ + struct tree_desc_s bl_desc; /* desc. for bit length tree */ + + ush bl_count[MAX_BITS+1]; + /* number of codes at each bit length for an optimal tree */ + + int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + int heap_len; /* number of elements in the heap */ + int heap_max; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + uch depth[2*L_CODES+1]; + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + uchf *l_buf; /* buffer for literals or lengths */ + + uInt lit_bufsize; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + uInt last_lit; /* running index in l_buf */ + + ushf *d_buf; + /* Buffer for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + ulg opt_len; /* bit length of current block with optimal trees */ + ulg static_len; /* bit length of current block with static trees */ + uInt matches; /* number of string matches in current block */ + int last_eob_len; /* bit length of EOB code for last block */ + +#ifdef DEBUG + ulg compressed_len; /* total bit length of compressed file mod 2^32 */ + ulg bits_sent; /* bit length of compressed data sent mod 2^32 */ +#endif + + ush bi_buf; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + int bi_valid; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + ulg high_water; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ + +} FAR deflate_state; + +/* Output a byte on the stream. + * IN assertion: there is enough room in pending_buf. + */ +#define put_byte(s, c) {s->pending_buf[s->pending++] = (c);} + + +#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) +/* Minimum amount of lookahead, except at the end of the input file. + * See deflate.c for comments about the MIN_MATCH+1. + */ + +#define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD) +/* In order to simplify the code, particularly on 16 bit machines, match + * distances are limited to MAX_DIST instead of WSIZE. + */ + +#define WIN_INIT MAX_MATCH +/* Number of bytes after end of data in window to initialize in order to avoid + memory checker errors from longest match routines */ + + /* in trees.c */ +void ZLIB_INTERNAL _tr_init OF((deflate_state *s)); +int ZLIB_INTERNAL _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); +void ZLIB_INTERNAL _tr_flush_block OF((deflate_state *s, charf *buf, + ulg stored_len, int last)); +void ZLIB_INTERNAL _tr_align OF((deflate_state *s)); +void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf, + ulg stored_len, int last)); + +#define d_code(dist) \ + ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]) +/* Mapping from a distance to a distance code. dist is the distance - 1 and + * must not have side effects. _dist_code[256] and _dist_code[257] are never + * used. + */ + +#ifndef DEBUG +/* Inline versions of _tr_tally for speed: */ + +#if defined(GEN_TREES_H) || !defined(STDC) + extern uch ZLIB_INTERNAL _length_code[]; + extern uch ZLIB_INTERNAL _dist_code[]; +#else + extern const uch ZLIB_INTERNAL _length_code[]; + extern const uch ZLIB_INTERNAL _dist_code[]; +#endif + +# define _tr_tally_lit(s, c, flush) \ + { uch cc = (c); \ + s->d_buf[s->last_lit] = 0; \ + s->l_buf[s->last_lit++] = cc; \ + s->dyn_ltree[cc].Freq++; \ + flush = (s->last_lit == s->lit_bufsize-1); \ + } +# define _tr_tally_dist(s, distance, length, flush) \ + { uch len = (length); \ + ush dist = (distance); \ + s->d_buf[s->last_lit] = dist; \ + s->l_buf[s->last_lit++] = len; \ + dist--; \ + s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ + s->dyn_dtree[d_code(dist)].Freq++; \ + flush = (s->last_lit == s->lit_bufsize-1); \ + } +#else +# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c) +# define _tr_tally_dist(s, distance, length, flush) \ + flush = _tr_tally(s, distance, length) +#endif + +#endif /* DEFLATE_H */ diff --git a/dep/zlib/example.c b/dep/zlib/example.c new file mode 100644 index 00000000000..604736f15f6 --- /dev/null +++ b/dep/zlib/example.c @@ -0,0 +1,565 @@ +/* example.c -- usage example of the zlib compression library + * Copyright (C) 1995-2006 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#include "zlib.h" +#include + +#ifdef STDC +# include +# include +#endif + +#if defined(VMS) || defined(RISCOS) +# define TESTFILE "foo-gz" +#else +# define TESTFILE "foo.gz" +#endif + +#define CHECK_ERR(err, msg) { \ + if (err != Z_OK) { \ + fprintf(stderr, "%s error: %d\n", msg, err); \ + exit(1); \ + } \ +} + +const char hello[] = "hello, hello!"; +/* "hello world" would be more standard, but the repeated "hello" + * stresses the compression code better, sorry... + */ + +const char dictionary[] = "hello"; +uLong dictId; /* Adler32 value of the dictionary */ + +void test_compress OF((Byte *compr, uLong comprLen, + Byte *uncompr, uLong uncomprLen)); +void test_gzio OF((const char *fname, + Byte *uncompr, uLong uncomprLen)); +void test_deflate OF((Byte *compr, uLong comprLen)); +void test_inflate OF((Byte *compr, uLong comprLen, + Byte *uncompr, uLong uncomprLen)); +void test_large_deflate OF((Byte *compr, uLong comprLen, + Byte *uncompr, uLong uncomprLen)); +void test_large_inflate OF((Byte *compr, uLong comprLen, + Byte *uncompr, uLong uncomprLen)); +void test_flush OF((Byte *compr, uLong *comprLen)); +void test_sync OF((Byte *compr, uLong comprLen, + Byte *uncompr, uLong uncomprLen)); +void test_dict_deflate OF((Byte *compr, uLong comprLen)); +void test_dict_inflate OF((Byte *compr, uLong comprLen, + Byte *uncompr, uLong uncomprLen)); +int main OF((int argc, char *argv[])); + +/* =========================================================================== + * Test compress() and uncompress() + */ +void test_compress(compr, comprLen, uncompr, uncomprLen) + Byte *compr, *uncompr; + uLong comprLen, uncomprLen; +{ + int err; + uLong len = (uLong)strlen(hello)+1; + + err = compress(compr, &comprLen, (const Bytef*)hello, len); + CHECK_ERR(err, "compress"); + + strcpy((char*)uncompr, "garbage"); + + err = uncompress(uncompr, &uncomprLen, compr, comprLen); + CHECK_ERR(err, "uncompress"); + + if (strcmp((char*)uncompr, hello)) { + fprintf(stderr, "bad uncompress\n"); + exit(1); + } else { + printf("uncompress(): %s\n", (char *)uncompr); + } +} + +/* =========================================================================== + * Test read/write of .gz files + */ +void test_gzio(fname, uncompr, uncomprLen) + const char *fname; /* compressed file name */ + Byte *uncompr; + uLong uncomprLen; +{ +#ifdef NO_GZCOMPRESS + fprintf(stderr, "NO_GZCOMPRESS -- gz* functions cannot compress\n"); +#else + int err; + int len = (int)strlen(hello)+1; + gzFile file; + z_off_t pos; + + file = gzopen(fname, "wb"); + if (file == NULL) { + fprintf(stderr, "gzopen error\n"); + exit(1); + } + gzputc(file, 'h'); + if (gzputs(file, "ello") != 4) { + fprintf(stderr, "gzputs err: %s\n", gzerror(file, &err)); + exit(1); + } + if (gzprintf(file, ", %s!", "hello") != 8) { + fprintf(stderr, "gzprintf err: %s\n", gzerror(file, &err)); + exit(1); + } + gzseek(file, 1L, SEEK_CUR); /* add one zero byte */ + gzclose(file); + + file = gzopen(fname, "rb"); + if (file == NULL) { + fprintf(stderr, "gzopen error\n"); + exit(1); + } + strcpy((char*)uncompr, "garbage"); + + if (gzread(file, uncompr, (unsigned)uncomprLen) != len) { + fprintf(stderr, "gzread err: %s\n", gzerror(file, &err)); + exit(1); + } + if (strcmp((char*)uncompr, hello)) { + fprintf(stderr, "bad gzread: %s\n", (char*)uncompr); + exit(1); + } else { + printf("gzread(): %s\n", (char*)uncompr); + } + + pos = gzseek(file, -8L, SEEK_CUR); + if (pos != 6 || gztell(file) != pos) { + fprintf(stderr, "gzseek error, pos=%ld, gztell=%ld\n", + (long)pos, (long)gztell(file)); + exit(1); + } + + if (gzgetc(file) != ' ') { + fprintf(stderr, "gzgetc error\n"); + exit(1); + } + + if (gzungetc(' ', file) != ' ') { + fprintf(stderr, "gzungetc error\n"); + exit(1); + } + + gzgets(file, (char*)uncompr, (int)uncomprLen); + if (strlen((char*)uncompr) != 7) { /* " hello!" */ + fprintf(stderr, "gzgets err after gzseek: %s\n", gzerror(file, &err)); + exit(1); + } + if (strcmp((char*)uncompr, hello + 6)) { + fprintf(stderr, "bad gzgets after gzseek\n"); + exit(1); + } else { + printf("gzgets() after gzseek: %s\n", (char*)uncompr); + } + + gzclose(file); +#endif +} + +/* =========================================================================== + * Test deflate() with small buffers + */ +void test_deflate(compr, comprLen) + Byte *compr; + uLong comprLen; +{ + z_stream c_stream; /* compression stream */ + int err; + uLong len = (uLong)strlen(hello)+1; + + c_stream.zalloc = (alloc_func)0; + c_stream.zfree = (free_func)0; + c_stream.opaque = (voidpf)0; + + err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION); + CHECK_ERR(err, "deflateInit"); + + c_stream.next_in = (Bytef*)hello; + c_stream.next_out = compr; + + while (c_stream.total_in != len && c_stream.total_out < comprLen) { + c_stream.avail_in = c_stream.avail_out = 1; /* force small buffers */ + err = deflate(&c_stream, Z_NO_FLUSH); + CHECK_ERR(err, "deflate"); + } + /* Finish the stream, still forcing small buffers: */ + for (;;) { + c_stream.avail_out = 1; + err = deflate(&c_stream, Z_FINISH); + if (err == Z_STREAM_END) break; + CHECK_ERR(err, "deflate"); + } + + err = deflateEnd(&c_stream); + CHECK_ERR(err, "deflateEnd"); +} + +/* =========================================================================== + * Test inflate() with small buffers + */ +void test_inflate(compr, comprLen, uncompr, uncomprLen) + Byte *compr, *uncompr; + uLong comprLen, uncomprLen; +{ + int err; + z_stream d_stream; /* decompression stream */ + + strcpy((char*)uncompr, "garbage"); + + d_stream.zalloc = (alloc_func)0; + d_stream.zfree = (free_func)0; + d_stream.opaque = (voidpf)0; + + d_stream.next_in = compr; + d_stream.avail_in = 0; + d_stream.next_out = uncompr; + + err = inflateInit(&d_stream); + CHECK_ERR(err, "inflateInit"); + + while (d_stream.total_out < uncomprLen && d_stream.total_in < comprLen) { + d_stream.avail_in = d_stream.avail_out = 1; /* force small buffers */ + err = inflate(&d_stream, Z_NO_FLUSH); + if (err == Z_STREAM_END) break; + CHECK_ERR(err, "inflate"); + } + + err = inflateEnd(&d_stream); + CHECK_ERR(err, "inflateEnd"); + + if (strcmp((char*)uncompr, hello)) { + fprintf(stderr, "bad inflate\n"); + exit(1); + } else { + printf("inflate(): %s\n", (char *)uncompr); + } +} + +/* =========================================================================== + * Test deflate() with large buffers and dynamic change of compression level + */ +void test_large_deflate(compr, comprLen, uncompr, uncomprLen) + Byte *compr, *uncompr; + uLong comprLen, uncomprLen; +{ + z_stream c_stream; /* compression stream */ + int err; + + c_stream.zalloc = (alloc_func)0; + c_stream.zfree = (free_func)0; + c_stream.opaque = (voidpf)0; + + err = deflateInit(&c_stream, Z_BEST_SPEED); + CHECK_ERR(err, "deflateInit"); + + c_stream.next_out = compr; + c_stream.avail_out = (uInt)comprLen; + + /* At this point, uncompr is still mostly zeroes, so it should compress + * very well: + */ + c_stream.next_in = uncompr; + c_stream.avail_in = (uInt)uncomprLen; + err = deflate(&c_stream, Z_NO_FLUSH); + CHECK_ERR(err, "deflate"); + if (c_stream.avail_in != 0) { + fprintf(stderr, "deflate not greedy\n"); + exit(1); + } + + /* Feed in already compressed data and switch to no compression: */ + deflateParams(&c_stream, Z_NO_COMPRESSION, Z_DEFAULT_STRATEGY); + c_stream.next_in = compr; + c_stream.avail_in = (uInt)comprLen/2; + err = deflate(&c_stream, Z_NO_FLUSH); + CHECK_ERR(err, "deflate"); + + /* Switch back to compressing mode: */ + deflateParams(&c_stream, Z_BEST_COMPRESSION, Z_FILTERED); + c_stream.next_in = uncompr; + c_stream.avail_in = (uInt)uncomprLen; + err = deflate(&c_stream, Z_NO_FLUSH); + CHECK_ERR(err, "deflate"); + + err = deflate(&c_stream, Z_FINISH); + if (err != Z_STREAM_END) { + fprintf(stderr, "deflate should report Z_STREAM_END\n"); + exit(1); + } + err = deflateEnd(&c_stream); + CHECK_ERR(err, "deflateEnd"); +} + +/* =========================================================================== + * Test inflate() with large buffers + */ +void test_large_inflate(compr, comprLen, uncompr, uncomprLen) + Byte *compr, *uncompr; + uLong comprLen, uncomprLen; +{ + int err; + z_stream d_stream; /* decompression stream */ + + strcpy((char*)uncompr, "garbage"); + + d_stream.zalloc = (alloc_func)0; + d_stream.zfree = (free_func)0; + d_stream.opaque = (voidpf)0; + + d_stream.next_in = compr; + d_stream.avail_in = (uInt)comprLen; + + err = inflateInit(&d_stream); + CHECK_ERR(err, "inflateInit"); + + for (;;) { + d_stream.next_out = uncompr; /* discard the output */ + d_stream.avail_out = (uInt)uncomprLen; + err = inflate(&d_stream, Z_NO_FLUSH); + if (err == Z_STREAM_END) break; + CHECK_ERR(err, "large inflate"); + } + + err = inflateEnd(&d_stream); + CHECK_ERR(err, "inflateEnd"); + + if (d_stream.total_out != 2*uncomprLen + comprLen/2) { + fprintf(stderr, "bad large inflate: %ld\n", d_stream.total_out); + exit(1); + } else { + printf("large_inflate(): OK\n"); + } +} + +/* =========================================================================== + * Test deflate() with full flush + */ +void test_flush(compr, comprLen) + Byte *compr; + uLong *comprLen; +{ + z_stream c_stream; /* compression stream */ + int err; + uInt len = (uInt)strlen(hello)+1; + + c_stream.zalloc = (alloc_func)0; + c_stream.zfree = (free_func)0; + c_stream.opaque = (voidpf)0; + + err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION); + CHECK_ERR(err, "deflateInit"); + + c_stream.next_in = (Bytef*)hello; + c_stream.next_out = compr; + c_stream.avail_in = 3; + c_stream.avail_out = (uInt)*comprLen; + err = deflate(&c_stream, Z_FULL_FLUSH); + CHECK_ERR(err, "deflate"); + + compr[3]++; /* force an error in first compressed block */ + c_stream.avail_in = len - 3; + + err = deflate(&c_stream, Z_FINISH); + if (err != Z_STREAM_END) { + CHECK_ERR(err, "deflate"); + } + err = deflateEnd(&c_stream); + CHECK_ERR(err, "deflateEnd"); + + *comprLen = c_stream.total_out; +} + +/* =========================================================================== + * Test inflateSync() + */ +void test_sync(compr, comprLen, uncompr, uncomprLen) + Byte *compr, *uncompr; + uLong comprLen, uncomprLen; +{ + int err; + z_stream d_stream; /* decompression stream */ + + strcpy((char*)uncompr, "garbage"); + + d_stream.zalloc = (alloc_func)0; + d_stream.zfree = (free_func)0; + d_stream.opaque = (voidpf)0; + + d_stream.next_in = compr; + d_stream.avail_in = 2; /* just read the zlib header */ + + err = inflateInit(&d_stream); + CHECK_ERR(err, "inflateInit"); + + d_stream.next_out = uncompr; + d_stream.avail_out = (uInt)uncomprLen; + + inflate(&d_stream, Z_NO_FLUSH); + CHECK_ERR(err, "inflate"); + + d_stream.avail_in = (uInt)comprLen-2; /* read all compressed data */ + err = inflateSync(&d_stream); /* but skip the damaged part */ + CHECK_ERR(err, "inflateSync"); + + err = inflate(&d_stream, Z_FINISH); + if (err != Z_DATA_ERROR) { + fprintf(stderr, "inflate should report DATA_ERROR\n"); + /* Because of incorrect adler32 */ + exit(1); + } + err = inflateEnd(&d_stream); + CHECK_ERR(err, "inflateEnd"); + + printf("after inflateSync(): hel%s\n", (char *)uncompr); +} + +/* =========================================================================== + * Test deflate() with preset dictionary + */ +void test_dict_deflate(compr, comprLen) + Byte *compr; + uLong comprLen; +{ + z_stream c_stream; /* compression stream */ + int err; + + c_stream.zalloc = (alloc_func)0; + c_stream.zfree = (free_func)0; + c_stream.opaque = (voidpf)0; + + err = deflateInit(&c_stream, Z_BEST_COMPRESSION); + CHECK_ERR(err, "deflateInit"); + + err = deflateSetDictionary(&c_stream, + (const Bytef*)dictionary, sizeof(dictionary)); + CHECK_ERR(err, "deflateSetDictionary"); + + dictId = c_stream.adler; + c_stream.next_out = compr; + c_stream.avail_out = (uInt)comprLen; + + c_stream.next_in = (Bytef*)hello; + c_stream.avail_in = (uInt)strlen(hello)+1; + + err = deflate(&c_stream, Z_FINISH); + if (err != Z_STREAM_END) { + fprintf(stderr, "deflate should report Z_STREAM_END\n"); + exit(1); + } + err = deflateEnd(&c_stream); + CHECK_ERR(err, "deflateEnd"); +} + +/* =========================================================================== + * Test inflate() with a preset dictionary + */ +void test_dict_inflate(compr, comprLen, uncompr, uncomprLen) + Byte *compr, *uncompr; + uLong comprLen, uncomprLen; +{ + int err; + z_stream d_stream; /* decompression stream */ + + strcpy((char*)uncompr, "garbage"); + + d_stream.zalloc = (alloc_func)0; + d_stream.zfree = (free_func)0; + d_stream.opaque = (voidpf)0; + + d_stream.next_in = compr; + d_stream.avail_in = (uInt)comprLen; + + err = inflateInit(&d_stream); + CHECK_ERR(err, "inflateInit"); + + d_stream.next_out = uncompr; + d_stream.avail_out = (uInt)uncomprLen; + + for (;;) { + err = inflate(&d_stream, Z_NO_FLUSH); + if (err == Z_STREAM_END) break; + if (err == Z_NEED_DICT) { + if (d_stream.adler != dictId) { + fprintf(stderr, "unexpected dictionary"); + exit(1); + } + err = inflateSetDictionary(&d_stream, (const Bytef*)dictionary, + sizeof(dictionary)); + } + CHECK_ERR(err, "inflate with dict"); + } + + err = inflateEnd(&d_stream); + CHECK_ERR(err, "inflateEnd"); + + if (strcmp((char*)uncompr, hello)) { + fprintf(stderr, "bad inflate with dict\n"); + exit(1); + } else { + printf("inflate with dictionary: %s\n", (char *)uncompr); + } +} + +/* =========================================================================== + * Usage: example [output.gz [input.gz]] + */ + +int main(argc, argv) + int argc; + char *argv[]; +{ + Byte *compr, *uncompr; + uLong comprLen = 10000*sizeof(int); /* don't overflow on MSDOS */ + uLong uncomprLen = comprLen; + static const char* myVersion = ZLIB_VERSION; + + if (zlibVersion()[0] != myVersion[0]) { + fprintf(stderr, "incompatible zlib version\n"); + exit(1); + + } else if (strcmp(zlibVersion(), ZLIB_VERSION) != 0) { + fprintf(stderr, "warning: different zlib version\n"); + } + + printf("zlib version %s = 0x%04x, compile flags = 0x%lx\n", + ZLIB_VERSION, ZLIB_VERNUM, zlibCompileFlags()); + + compr = (Byte*)calloc((uInt)comprLen, 1); + uncompr = (Byte*)calloc((uInt)uncomprLen, 1); + /* compr and uncompr are cleared to avoid reading uninitialized + * data and to ensure that uncompr compresses well. + */ + if (compr == Z_NULL || uncompr == Z_NULL) { + printf("out of memory\n"); + exit(1); + } + test_compress(compr, comprLen, uncompr, uncomprLen); + + test_gzio((argc > 1 ? argv[1] : TESTFILE), + uncompr, uncomprLen); + + test_deflate(compr, comprLen); + test_inflate(compr, comprLen, uncompr, uncomprLen); + + test_large_deflate(compr, comprLen, uncompr, uncomprLen); + test_large_inflate(compr, comprLen, uncompr, uncomprLen); + + test_flush(compr, &comprLen); + test_sync(compr, comprLen, uncompr, uncomprLen); + comprLen = uncomprLen; + + test_dict_deflate(compr, comprLen); + test_dict_inflate(compr, comprLen, uncompr, uncomprLen); + + free(compr); + free(uncompr); + + return 0; +} diff --git a/dep/zlib/gzclose.c b/dep/zlib/gzclose.c new file mode 100644 index 00000000000..caeb99a3177 --- /dev/null +++ b/dep/zlib/gzclose.c @@ -0,0 +1,25 @@ +/* gzclose.c -- zlib gzclose() function + * Copyright (C) 2004, 2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "gzguts.h" + +/* gzclose() is in a separate file so that it is linked in only if it is used. + That way the other gzclose functions can be used instead to avoid linking in + unneeded compression or decompression routines. */ +int ZEXPORT gzclose(file) + gzFile file; +{ +#ifndef NO_GZCOMPRESS + gz_statep state; + + if (file == NULL) + return Z_STREAM_ERROR; + state = (gz_statep)file; + + return state->mode == GZ_READ ? gzclose_r(file) : gzclose_w(file); +#else + return gzclose_r(file); +#endif +} diff --git a/dep/zlib/gzguts.h b/dep/zlib/gzguts.h new file mode 100644 index 00000000000..0f8fb79f87d --- /dev/null +++ b/dep/zlib/gzguts.h @@ -0,0 +1,132 @@ +/* gzguts.h -- zlib internal header definitions for gz* operations + * Copyright (C) 2004, 2005, 2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#ifdef _LARGEFILE64_SOURCE +# ifndef _LARGEFILE_SOURCE +# define _LARGEFILE_SOURCE 1 +# endif +# ifdef _FILE_OFFSET_BITS +# undef _FILE_OFFSET_BITS +# endif +#endif + +#if ((__GNUC__-0) * 10 + __GNUC_MINOR__-0 >= 33) && !defined(NO_VIZ) +# define ZLIB_INTERNAL __attribute__((visibility ("hidden"))) +#else +# define ZLIB_INTERNAL +#endif + +#include +#include "zlib.h" +#ifdef STDC +# include +# include +# include +#endif +#include + +#ifdef NO_DEFLATE /* for compatibility with old definition */ +# define NO_GZCOMPRESS +#endif + +#ifdef _MSC_VER +# include +# define vsnprintf _vsnprintf +#endif + +#ifndef local +# define local static +#endif +/* compile with -Dlocal if your debugger can't find static symbols */ + +/* gz* functions always use library allocation functions */ +#ifndef STDC + extern voidp malloc OF((uInt size)); + extern void free OF((voidpf ptr)); +#endif + +/* get errno and strerror definition */ +#if defined UNDER_CE +# include +# define zstrerror() gz_strwinerror((DWORD)GetLastError()) +#else +# ifdef STDC +# include +# define zstrerror() strerror(errno) +# else +# define zstrerror() "stdio error (consult errno)" +# endif +#endif + +/* provide prototypes for these when building zlib without LFS */ +#if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); + ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); +#endif + +/* default i/o buffer size -- double this for output when reading */ +#define GZBUFSIZE 8192 + +/* gzip modes, also provide a little integrity check on the passed structure */ +#define GZ_NONE 0 +#define GZ_READ 7247 +#define GZ_WRITE 31153 +#define GZ_APPEND 1 /* mode set to GZ_WRITE after the file is opened */ + +/* values for gz_state how */ +#define LOOK 0 /* look for a gzip header */ +#define COPY 1 /* copy input directly */ +#define GZIP 2 /* decompress a gzip stream */ + +/* internal gzip file state data structure */ +typedef struct { + /* used for both reading and writing */ + int mode; /* see gzip modes above */ + int fd; /* file descriptor */ + char *path; /* path or fd for error messages */ + z_off64_t pos; /* current position in uncompressed data */ + unsigned size; /* buffer size, zero if not allocated yet */ + unsigned want; /* requested buffer size, default is GZBUFSIZE */ + unsigned char *in; /* input buffer */ + unsigned char *out; /* output buffer (double-sized when reading) */ + unsigned char *next; /* next output data to deliver or write */ + /* just for reading */ + unsigned have; /* amount of output data unused at next */ + int eof; /* true if end of input file reached */ + z_off64_t start; /* where the gzip data started, for rewinding */ + z_off64_t raw; /* where the raw data started, for seeking */ + int how; /* 0: get header, 1: copy, 2: decompress */ + int direct; /* true if last read direct, false if gzip */ + /* just for writing */ + int level; /* compression level */ + int strategy; /* compression strategy */ + /* seek request */ + z_off64_t skip; /* amount to skip (already rewound if backwards) */ + int seek; /* true if seek request pending */ + /* error information */ + int err; /* error code */ + char *msg; /* error message */ + /* zlib inflate or deflate stream */ + z_stream strm; /* stream structure in-place (not a pointer) */ +} gz_state; +typedef gz_state FAR *gz_statep; + +/* shared functions */ +void ZLIB_INTERNAL gz_error OF((gz_statep, int, const char *)); +#if defined UNDER_CE +char ZLIB_INTERNAL *gz_strwinerror OF((DWORD error)); +#endif + +/* GT_OFF(x), where x is an unsigned value, is true if x > maximum z_off64_t + value -- needed when comparing unsigned to z_off64_t, which is signed + (possible z_off64_t types off_t, off64_t, and long are all signed) */ +#ifdef INT_MAX +# define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > INT_MAX) +#else +unsigned ZLIB_INTERNAL gz_intmax OF((void)); +# define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > gz_intmax()) +#endif diff --git a/dep/zlib/gzlib.c b/dep/zlib/gzlib.c new file mode 100644 index 00000000000..603e60ed544 --- /dev/null +++ b/dep/zlib/gzlib.c @@ -0,0 +1,537 @@ +/* gzlib.c -- zlib functions common to reading and writing gzip files + * Copyright (C) 2004, 2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "gzguts.h" + +#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 +# define LSEEK lseek64 +#else +# define LSEEK lseek +#endif + +/* Local functions */ +local void gz_reset OF((gz_statep)); +local gzFile gz_open OF((const char *, int, const char *)); + +#if defined UNDER_CE + +/* Map the Windows error number in ERROR to a locale-dependent error message + string and return a pointer to it. Typically, the values for ERROR come + from GetLastError. + + The string pointed to shall not be modified by the application, but may be + overwritten by a subsequent call to gz_strwinerror + + The gz_strwinerror function does not change the current setting of + GetLastError. */ +char ZLIB_INTERNAL *gz_strwinerror (error) + DWORD error; +{ + static char buf[1024]; + + wchar_t *msgbuf; + DWORD lasterr = GetLastError(); + DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM + | FORMAT_MESSAGE_ALLOCATE_BUFFER, + NULL, + error, + 0, /* Default language */ + (LPVOID)&msgbuf, + 0, + NULL); + if (chars != 0) { + /* If there is an \r\n appended, zap it. */ + if (chars >= 2 + && msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') { + chars -= 2; + msgbuf[chars] = 0; + } + + if (chars > sizeof (buf) - 1) { + chars = sizeof (buf) - 1; + msgbuf[chars] = 0; + } + + wcstombs(buf, msgbuf, chars + 1); + LocalFree(msgbuf); + } + else { + sprintf(buf, "unknown win32 error (%ld)", error); + } + + SetLastError(lasterr); + return buf; +} + +#endif /* UNDER_CE */ + +/* Reset gzip file state */ +local void gz_reset(state) + gz_statep state; +{ + if (state->mode == GZ_READ) { /* for reading ... */ + state->have = 0; /* no output data available */ + state->eof = 0; /* not at end of file */ + state->how = LOOK; /* look for gzip header */ + state->direct = 1; /* default for empty file */ + } + state->seek = 0; /* no seek request pending */ + gz_error(state, Z_OK, NULL); /* clear error */ + state->pos = 0; /* no uncompressed data yet */ + state->strm.avail_in = 0; /* no input data yet */ +} + +/* Open a gzip file either by name or file descriptor. */ +local gzFile gz_open(path, fd, mode) + const char *path; + int fd; + const char *mode; +{ + gz_statep state; + + /* allocate gzFile structure to return */ + state = malloc(sizeof(gz_state)); + if (state == NULL) + return NULL; + state->size = 0; /* no buffers allocated yet */ + state->want = GZBUFSIZE; /* requested buffer size */ + state->msg = NULL; /* no error message yet */ + + /* interpret mode */ + state->mode = GZ_NONE; + state->level = Z_DEFAULT_COMPRESSION; + state->strategy = Z_DEFAULT_STRATEGY; + while (*mode) { + if (*mode >= '0' && *mode <= '9') + state->level = *mode - '0'; + else + switch (*mode) { + case 'r': + state->mode = GZ_READ; + break; +#ifndef NO_GZCOMPRESS + case 'w': + state->mode = GZ_WRITE; + break; + case 'a': + state->mode = GZ_APPEND; + break; +#endif + case '+': /* can't read and write at the same time */ + free(state); + return NULL; + case 'b': /* ignore -- will request binary anyway */ + break; + case 'f': + state->strategy = Z_FILTERED; + break; + case 'h': + state->strategy = Z_HUFFMAN_ONLY; + break; + case 'R': + state->strategy = Z_RLE; + break; + case 'F': + state->strategy = Z_FIXED; + default: /* could consider as an error, but just ignore */ + ; + } + mode++; + } + + /* must provide an "r", "w", or "a" */ + if (state->mode == GZ_NONE) { + free(state); + return NULL; + } + + /* save the path name for error messages */ + state->path = malloc(strlen(path) + 1); + if (state->path == NULL) { + free(state); + return NULL; + } + strcpy(state->path, path); + + /* open the file with the appropriate mode (or just use fd) */ + state->fd = fd != -1 ? fd : + open(path, +#ifdef O_LARGEFILE + O_LARGEFILE | +#endif +#ifdef O_BINARY + O_BINARY | +#endif + (state->mode == GZ_READ ? + O_RDONLY : + (O_WRONLY | O_CREAT | ( + state->mode == GZ_WRITE ? + O_TRUNC : + O_APPEND))), + 0666); + if (state->fd == -1) { + free(state->path); + free(state); + return NULL; + } + if (state->mode == GZ_APPEND) + state->mode = GZ_WRITE; /* simplify later checks */ + + /* save the current position for rewinding (only if reading) */ + if (state->mode == GZ_READ) { + state->start = LSEEK(state->fd, 0, SEEK_CUR); + if (state->start == -1) state->start = 0; + } + + /* initialize stream */ + gz_reset(state); + + /* return stream */ + return (gzFile)state; +} + +/* -- see zlib.h -- */ +gzFile ZEXPORT gzopen(path, mode) + const char *path; + const char *mode; +{ + return gz_open(path, -1, mode); +} + +/* -- see zlib.h -- */ +gzFile ZEXPORT gzopen64(path, mode) + const char *path; + const char *mode; +{ + return gz_open(path, -1, mode); +} + +/* -- see zlib.h -- */ +gzFile ZEXPORT gzdopen(fd, mode) + int fd; + const char *mode; +{ + char *path; /* identifier for error messages */ + gzFile gz; + + if (fd == -1 || (path = malloc(7 + 3 * sizeof(int))) == NULL) + return NULL; + sprintf(path, "", fd); /* for debugging */ + gz = gz_open(path, fd, mode); + free(path); + return gz; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzbuffer(file, size) + gzFile file; + unsigned size; +{ + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return -1; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return -1; + + /* make sure we haven't already allocated memory */ + if (state->size != 0) + return -1; + + /* check and set requested size */ + if (size == 0) + return -1; + state->want = size; + return 0; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzrewind(file) + gzFile file; +{ + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + + /* check that we're reading and that there's no error */ + if (state->mode != GZ_READ || state->err != Z_OK) + return -1; + + /* back up and start over */ + if (LSEEK(state->fd, state->start, SEEK_SET) == -1) + return -1; + gz_reset(state); + return 0; +} + +/* -- see zlib.h -- */ +z_off64_t ZEXPORT gzseek64(file, offset, whence) + gzFile file; + z_off64_t offset; + int whence; +{ + unsigned n; + z_off64_t ret; + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return -1; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return -1; + + /* check that there's no error */ + if (state->err != Z_OK) + return -1; + + /* can only seek from start or relative to current position */ + if (whence != SEEK_SET && whence != SEEK_CUR) + return -1; + + /* normalize offset to a SEEK_CUR specification */ + if (whence == SEEK_SET) + offset -= state->pos; + else if (state->seek) + offset += state->skip; + state->seek = 0; + + /* if within raw area while reading, just go there */ + if (state->mode == GZ_READ && state->how == COPY && + state->pos + offset >= state->raw) { + ret = LSEEK(state->fd, offset - state->have, SEEK_CUR); + if (ret == -1) + return -1; + state->have = 0; + state->eof = 0; + state->seek = 0; + gz_error(state, Z_OK, NULL); + state->strm.avail_in = 0; + state->pos += offset; + return state->pos; + } + + /* calculate skip amount, rewinding if needed for back seek when reading */ + if (offset < 0) { + if (state->mode != GZ_READ) /* writing -- can't go backwards */ + return -1; + offset += state->pos; + if (offset < 0) /* before start of file! */ + return -1; + if (gzrewind(file) == -1) /* rewind, then skip to offset */ + return -1; + } + + /* if reading, skip what's in output buffer (one less gzgetc() check) */ + if (state->mode == GZ_READ) { + n = GT_OFF(state->have) || (z_off64_t)state->have > offset ? + (unsigned)offset : state->have; + state->have -= n; + state->next += n; + state->pos += n; + offset -= n; + } + + /* request skip (if not zero) */ + if (offset) { + state->seek = 1; + state->skip = offset; + } + return state->pos + offset; +} + +/* -- see zlib.h -- */ +z_off_t ZEXPORT gzseek(file, offset, whence) + gzFile file; + z_off_t offset; + int whence; +{ + z_off64_t ret; + + ret = gzseek64(file, (z_off64_t)offset, whence); + return ret == (z_off_t)ret ? (z_off_t)ret : -1; +} + +/* -- see zlib.h -- */ +z_off64_t ZEXPORT gztell64(file) + gzFile file; +{ + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return -1; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return -1; + + /* return position */ + return state->pos + (state->seek ? state->skip : 0); +} + +/* -- see zlib.h -- */ +z_off_t ZEXPORT gztell(file) + gzFile file; +{ + z_off64_t ret; + + ret = gztell64(file); + return ret == (z_off_t)ret ? (z_off_t)ret : -1; +} + +/* -- see zlib.h -- */ +z_off64_t ZEXPORT gzoffset64(file) + gzFile file; +{ + z_off64_t offset; + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return -1; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return -1; + + /* compute and return effective offset in file */ + offset = LSEEK(state->fd, 0, SEEK_CUR); + if (offset == -1) + return -1; + if (state->mode == GZ_READ) /* reading */ + offset -= state->strm.avail_in; /* don't count buffered input */ + return offset; +} + +/* -- see zlib.h -- */ +z_off_t ZEXPORT gzoffset(file) + gzFile file; +{ + z_off64_t ret; + + ret = gzoffset64(file); + return ret == (z_off_t)ret ? (z_off_t)ret : -1; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzeof(file) + gzFile file; +{ + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return 0; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return 0; + + /* return end-of-file state */ + return state->mode == GZ_READ ? + (state->eof && state->strm.avail_in == 0 && state->have == 0) : 0; +} + +/* -- see zlib.h -- */ +const char * ZEXPORT gzerror(file, errnum) + gzFile file; + int *errnum; +{ + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return NULL; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return NULL; + + /* return error information */ + if (errnum != NULL) + *errnum = state->err; + return state->msg == NULL ? "" : state->msg; +} + +/* -- see zlib.h -- */ +void ZEXPORT gzclearerr(file) + gzFile file; +{ + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return; + + /* clear error and end-of-file */ + if (state->mode == GZ_READ) + state->eof = 0; + gz_error(state, Z_OK, NULL); +} + +/* Create an error message in allocated memory and set state->err and + state->msg accordingly. Free any previous error message already there. Do + not try to free or allocate space if the error is Z_MEM_ERROR (out of + memory). Simply save the error message as a static string. If there is an + allocation failure constructing the error message, then convert the error to + out of memory. */ +void ZLIB_INTERNAL gz_error(state, err, msg) + gz_statep state; + int err; + const char *msg; +{ + /* free previously allocated message and clear */ + if (state->msg != NULL) { + if (state->err != Z_MEM_ERROR) + free(state->msg); + state->msg = NULL; + } + + /* set error code, and if no message, then done */ + state->err = err; + if (msg == NULL) + return; + + /* for an out of memory error, save as static string */ + if (err == Z_MEM_ERROR) { + state->msg = (char *)msg; + return; + } + + /* construct error message with path */ + if ((state->msg = malloc(strlen(state->path) + strlen(msg) + 3)) == NULL) { + state->err = Z_MEM_ERROR; + state->msg = (char *)"out of memory"; + return; + } + strcpy(state->msg, state->path); + strcat(state->msg, ": "); + strcat(state->msg, msg); + return; +} + +#ifndef INT_MAX +/* portably return maximum value for an int (when limits.h presumed not + available) -- we need to do this to cover cases where 2's complement not + used, since C standard permits 1's complement and sign-bit representations, + otherwise we could just use ((unsigned)-1) >> 1 */ +unsigned ZLIB_INTERNAL gz_intmax() +{ + unsigned p, q; + + p = 1; + do { + q = p; + p <<= 1; + p++; + } while (p > q); + return q >> 1; +} +#endif diff --git a/dep/zlib/gzread.c b/dep/zlib/gzread.c new file mode 100644 index 00000000000..548201ab009 --- /dev/null +++ b/dep/zlib/gzread.c @@ -0,0 +1,653 @@ +/* gzread.c -- zlib functions for reading gzip files + * Copyright (C) 2004, 2005, 2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "gzguts.h" + +/* Local functions */ +local int gz_load OF((gz_statep, unsigned char *, unsigned, unsigned *)); +local int gz_avail OF((gz_statep)); +local int gz_next4 OF((gz_statep, unsigned long *)); +local int gz_head OF((gz_statep)); +local int gz_decomp OF((gz_statep)); +local int gz_make OF((gz_statep)); +local int gz_skip OF((gz_statep, z_off64_t)); + +/* Use read() to load a buffer -- return -1 on error, otherwise 0. Read from + state->fd, and update state->eof, state->err, and state->msg as appropriate. + This function needs to loop on read(), since read() is not guaranteed to + read the number of bytes requested, depending on the type of descriptor. */ +local int gz_load(state, buf, len, have) + gz_statep state; + unsigned char *buf; + unsigned len; + unsigned *have; +{ + int ret; + + *have = 0; + do { + ret = read(state->fd, buf + *have, len - *have); + if (ret <= 0) + break; + *have += ret; + } while (*have < len); + if (ret < 0) { + gz_error(state, Z_ERRNO, zstrerror()); + return -1; + } + if (ret == 0) + state->eof = 1; + return 0; +} + +/* Load up input buffer and set eof flag if last data loaded -- return -1 on + error, 0 otherwise. Note that the eof flag is set when the end of the input + file is reached, even though there may be unused data in the buffer. Once + that data has been used, no more attempts will be made to read the file. + gz_avail() assumes that strm->avail_in == 0. */ +local int gz_avail(state) + gz_statep state; +{ + z_streamp strm = &(state->strm); + + if (state->err != Z_OK) + return -1; + if (state->eof == 0) { + if (gz_load(state, state->in, state->size, + (unsigned *)&(strm->avail_in)) == -1) + return -1; + strm->next_in = state->in; + } + return 0; +} + +/* Get next byte from input, or -1 if end or error. */ +#define NEXT() ((strm->avail_in == 0 && gz_avail(state) == -1) ? -1 : \ + (strm->avail_in == 0 ? -1 : \ + (strm->avail_in--, *(strm->next_in)++))) + +/* Get a four-byte little-endian integer and return 0 on success and the value + in *ret. Otherwise -1 is returned and *ret is not modified. */ +local int gz_next4(state, ret) + gz_statep state; + unsigned long *ret; +{ + int ch; + unsigned long val; + z_streamp strm = &(state->strm); + + val = NEXT(); + val += (unsigned)NEXT() << 8; + val += (unsigned long)NEXT() << 16; + ch = NEXT(); + if (ch == -1) + return -1; + val += (unsigned long)ch << 24; + *ret = val; + return 0; +} + +/* Look for gzip header, set up for inflate or copy. state->have must be zero. + If this is the first time in, allocate required memory. state->how will be + left unchanged if there is no more input data available, will be set to COPY + if there is no gzip header and direct copying will be performed, or it will + be set to GZIP for decompression, and the gzip header will be skipped so + that the next available input data is the raw deflate stream. If direct + copying, then leftover input data from the input buffer will be copied to + the output buffer. In that case, all further file reads will be directly to + either the output buffer or a user buffer. If decompressing, the inflate + state and the check value will be initialized. gz_head() will return 0 on + success or -1 on failure. Failures may include read errors or gzip header + errors. */ +local int gz_head(state) + gz_statep state; +{ + z_streamp strm = &(state->strm); + int flags; + unsigned len; + + /* allocate read buffers and inflate memory */ + if (state->size == 0) { + /* allocate buffers */ + state->in = malloc(state->want); + state->out = malloc(state->want << 1); + if (state->in == NULL || state->out == NULL) { + if (state->out != NULL) + free(state->out); + if (state->in != NULL) + free(state->in); + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + state->size = state->want; + + /* allocate inflate memory */ + state->strm.zalloc = Z_NULL; + state->strm.zfree = Z_NULL; + state->strm.opaque = Z_NULL; + state->strm.avail_in = 0; + state->strm.next_in = Z_NULL; + if (inflateInit2(&(state->strm), -15) != Z_OK) { /* raw inflate */ + free(state->out); + free(state->in); + state->size = 0; + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + } + + /* get some data in the input buffer */ + if (strm->avail_in == 0) { + if (gz_avail(state) == -1) + return -1; + if (strm->avail_in == 0) + return 0; + } + + /* look for the gzip magic header bytes 31 and 139 */ + if (strm->next_in[0] == 31) { + strm->avail_in--; + strm->next_in++; + if (strm->avail_in == 0 && gz_avail(state) == -1) + return -1; + if (strm->avail_in && strm->next_in[0] == 139) { + /* we have a gzip header, woo hoo! */ + strm->avail_in--; + strm->next_in++; + + /* skip rest of header */ + if (NEXT() != 8) { /* compression method */ + gz_error(state, Z_DATA_ERROR, "unknown compression method"); + return -1; + } + flags = NEXT(); + if (flags & 0xe0) { /* reserved flag bits */ + gz_error(state, Z_DATA_ERROR, "unknown header flags set"); + return -1; + } + NEXT(); /* modification time */ + NEXT(); + NEXT(); + NEXT(); + NEXT(); /* extra flags */ + NEXT(); /* operating system */ + if (flags & 4) { /* extra field */ + len = (unsigned)NEXT(); + len += (unsigned)NEXT() << 8; + while (len--) + if (NEXT() < 0) + break; + } + if (flags & 8) /* file name */ + while (NEXT() > 0) + ; + if (flags & 16) /* comment */ + while (NEXT() > 0) + ; + if (flags & 2) { /* header crc */ + NEXT(); + NEXT(); + } + /* an unexpected end of file is not checked for here -- it will be + noticed on the first request for uncompressed data */ + + /* set up for decompression */ + inflateReset(strm); + strm->adler = crc32(0L, Z_NULL, 0); + state->how = GZIP; + state->direct = 0; + return 0; + } + else { + /* not a gzip file -- save first byte (31) and fall to raw i/o */ + state->out[0] = 31; + state->have = 1; + } + } + + /* doing raw i/o, save start of raw data for seeking, copy any leftover + input to output -- this assumes that the output buffer is larger than + the input buffer, which also assures space for gzungetc() */ + state->raw = state->pos; + state->next = state->out; + if (strm->avail_in) { + memcpy(state->next + state->have, strm->next_in, strm->avail_in); + state->have += strm->avail_in; + strm->avail_in = 0; + } + state->how = COPY; + state->direct = 1; + return 0; +} + +/* Decompress from input to the provided next_out and avail_out in the state. + If the end of the compressed data is reached, then verify the gzip trailer + check value and length (modulo 2^32). state->have and state->next are set + to point to the just decompressed data, and the crc is updated. If the + trailer is verified, state->how is reset to LOOK to look for the next gzip + stream or raw data, once state->have is depleted. Returns 0 on success, -1 + on failure. Failures may include invalid compressed data or a failed gzip + trailer verification. */ +local int gz_decomp(state) + gz_statep state; +{ + int ret; + unsigned had; + unsigned long crc, len; + z_streamp strm = &(state->strm); + + /* fill output buffer up to end of deflate stream */ + had = strm->avail_out; + do { + /* get more input for inflate() */ + if (strm->avail_in == 0 && gz_avail(state) == -1) + return -1; + if (strm->avail_in == 0) { + gz_error(state, Z_DATA_ERROR, "unexpected end of file"); + return -1; + } + + /* decompress and handle errors */ + ret = inflate(strm, Z_NO_FLUSH); + if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT) { + gz_error(state, Z_STREAM_ERROR, + "internal error: inflate stream corrupt"); + return -1; + } + if (ret == Z_MEM_ERROR) { + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + if (ret == Z_DATA_ERROR) { /* deflate stream invalid */ + gz_error(state, Z_DATA_ERROR, + strm->msg == NULL ? "compressed data error" : strm->msg); + return -1; + } + } while (strm->avail_out && ret != Z_STREAM_END); + + /* update available output and crc check value */ + state->have = had - strm->avail_out; + state->next = strm->next_out - state->have; + strm->adler = crc32(strm->adler, state->next, state->have); + + /* check gzip trailer if at end of deflate stream */ + if (ret == Z_STREAM_END) { + if (gz_next4(state, &crc) == -1 || gz_next4(state, &len) == -1) { + gz_error(state, Z_DATA_ERROR, "unexpected end of file"); + return -1; + } + if (crc != strm->adler) { + gz_error(state, Z_DATA_ERROR, "incorrect data check"); + return -1; + } + if (len != (strm->total_out & 0xffffffffL)) { + gz_error(state, Z_DATA_ERROR, "incorrect length check"); + return -1; + } + state->how = LOOK; /* ready for next stream, once have is 0 (leave + state->direct unchanged to remember how) */ + } + + /* good decompression */ + return 0; +} + +/* Make data and put in the output buffer. Assumes that state->have == 0. + Data is either copied from the input file or decompressed from the input + file depending on state->how. If state->how is LOOK, then a gzip header is + looked for (and skipped if found) to determine wither to copy or decompress. + Returns -1 on error, otherwise 0. gz_make() will leave state->have as COPY + or GZIP unless the end of the input file has been reached and all data has + been processed. */ +local int gz_make(state) + gz_statep state; +{ + z_streamp strm = &(state->strm); + + if (state->how == LOOK) { /* look for gzip header */ + if (gz_head(state) == -1) + return -1; + if (state->have) /* got some data from gz_head() */ + return 0; + } + if (state->how == COPY) { /* straight copy */ + if (gz_load(state, state->out, state->size << 1, &(state->have)) == -1) + return -1; + state->next = state->out; + } + else if (state->how == GZIP) { /* decompress */ + strm->avail_out = state->size << 1; + strm->next_out = state->out; + if (gz_decomp(state) == -1) + return -1; + } + return 0; +} + +/* Skip len uncompressed bytes of output. Return -1 on error, 0 on success. */ +local int gz_skip(state, len) + gz_statep state; + z_off64_t len; +{ + unsigned n; + + /* skip over len bytes or reach end-of-file, whichever comes first */ + while (len) + /* skip over whatever is in output buffer */ + if (state->have) { + n = GT_OFF(state->have) || (z_off64_t)state->have > len ? + (unsigned)len : state->have; + state->have -= n; + state->next += n; + state->pos += n; + len -= n; + } + + /* output buffer empty -- return if we're at the end of the input */ + else if (state->eof && state->strm.avail_in == 0) + break; + + /* need more data to skip -- load up output buffer */ + else { + /* get more output, looking for header if required */ + if (gz_make(state) == -1) + return -1; + } + return 0; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzread(file, buf, len) + gzFile file; + voidp buf; + unsigned len; +{ + unsigned got, n; + gz_statep state; + z_streamp strm; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + strm = &(state->strm); + + /* check that we're reading and that there's no error */ + if (state->mode != GZ_READ || state->err != Z_OK) + return -1; + + /* since an int is returned, make sure len fits in one, otherwise return + with an error (this avoids the flaw in the interface) */ + if ((int)len < 0) { + gz_error(state, Z_BUF_ERROR, "requested length does not fit in int"); + return -1; + } + + /* if len is zero, avoid unnecessary operations */ + if (len == 0) + return 0; + + /* process a skip request */ + if (state->seek) { + state->seek = 0; + if (gz_skip(state, state->skip) == -1) + return -1; + } + + /* get len bytes to buf, or less than len if at the end */ + got = 0; + do { + /* first just try copying data from the output buffer */ + if (state->have) { + n = state->have > len ? len : state->have; + memcpy(buf, state->next, n); + state->next += n; + state->have -= n; + } + + /* output buffer empty -- return if we're at the end of the input */ + else if (state->eof && strm->avail_in == 0) + break; + + /* need output data -- for small len or new stream load up our output + buffer */ + else if (state->how == LOOK || len < (state->size << 1)) { + /* get more output, looking for header if required */ + if (gz_make(state) == -1) + return -1; + continue; /* no progress yet -- go back to memcpy() above */ + /* the copy above assures that we will leave with space in the + output buffer, allowing at least one gzungetc() to succeed */ + } + + /* large len -- read directly into user buffer */ + else if (state->how == COPY) { /* read directly */ + if (gz_load(state, buf, len, &n) == -1) + return -1; + } + + /* large len -- decompress directly into user buffer */ + else { /* state->how == GZIP */ + strm->avail_out = len; + strm->next_out = buf; + if (gz_decomp(state) == -1) + return -1; + n = state->have; + state->have = 0; + } + + /* update progress */ + len -= n; + buf = (char *)buf + n; + got += n; + state->pos += n; + } while (len); + + /* return number of bytes read into user buffer (will fit in int) */ + return (int)got; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzgetc(file) + gzFile file; +{ + int ret; + unsigned char buf[1]; + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + + /* check that we're reading and that there's no error */ + if (state->mode != GZ_READ || state->err != Z_OK) + return -1; + + /* try output buffer (no need to check for skip request) */ + if (state->have) { + state->have--; + state->pos++; + return *(state->next)++; + } + + /* nothing there -- try gzread() */ + ret = gzread(file, buf, 1); + return ret < 1 ? -1 : buf[0]; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzungetc(c, file) + int c; + gzFile file; +{ + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + + /* check that we're reading and that there's no error */ + if (state->mode != GZ_READ || state->err != Z_OK) + return -1; + + /* process a skip request */ + if (state->seek) { + state->seek = 0; + if (gz_skip(state, state->skip) == -1) + return -1; + } + + /* can't push EOF */ + if (c < 0) + return -1; + + /* if output buffer empty, put byte at end (allows more pushing) */ + if (state->have == 0) { + state->have = 1; + state->next = state->out + (state->size << 1) - 1; + state->next[0] = c; + state->pos--; + return c; + } + + /* if no room, give up (must have already done a gzungetc()) */ + if (state->have == (state->size << 1)) { + gz_error(state, Z_BUF_ERROR, "out of room to push characters"); + return -1; + } + + /* slide output data if needed and insert byte before existing data */ + if (state->next == state->out) { + unsigned char *src = state->out + state->have; + unsigned char *dest = state->out + (state->size << 1); + while (src > state->out) + *--dest = *--src; + state->next = dest; + } + state->have++; + state->next--; + state->next[0] = c; + state->pos--; + return c; +} + +/* -- see zlib.h -- */ +char * ZEXPORT gzgets(file, buf, len) + gzFile file; + char *buf; + int len; +{ + unsigned left, n; + char *str; + unsigned char *eol; + gz_statep state; + + /* check parameters and get internal structure */ + if (file == NULL || buf == NULL || len < 1) + return NULL; + state = (gz_statep)file; + + /* check that we're reading and that there's no error */ + if (state->mode != GZ_READ || state->err != Z_OK) + return NULL; + + /* process a skip request */ + if (state->seek) { + state->seek = 0; + if (gz_skip(state, state->skip) == -1) + return NULL; + } + + /* copy output bytes up to new line or len - 1, whichever comes first -- + append a terminating zero to the string (we don't check for a zero in + the contents, let the user worry about that) */ + str = buf; + left = (unsigned)len - 1; + if (left) do { + /* assure that something is in the output buffer */ + if (state->have == 0) { + if (gz_make(state) == -1) + return NULL; /* error */ + if (state->have == 0) { /* end of file */ + if (buf == str) /* got bupkus */ + return NULL; + break; /* got something -- return it */ + } + } + + /* look for end-of-line in current output buffer */ + n = state->have > left ? left : state->have; + eol = memchr(state->next, '\n', n); + if (eol != NULL) + n = (unsigned)(eol - state->next) + 1; + + /* copy through end-of-line, or remainder if not found */ + memcpy(buf, state->next, n); + state->have -= n; + state->next += n; + state->pos += n; + left -= n; + buf += n; + } while (left && eol == NULL); + + /* found end-of-line or out of space -- terminate string and return it */ + buf[0] = 0; + return str; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzdirect(file) + gzFile file; +{ + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return 0; + state = (gz_statep)file; + + /* check that we're reading */ + if (state->mode != GZ_READ) + return 0; + + /* if the state is not known, but we can find out, then do so (this is + mainly for right after a gzopen() or gzdopen()) */ + if (state->how == LOOK && state->have == 0) + (void)gz_head(state); + + /* return 1 if reading direct, 0 if decompressing a gzip stream */ + return state->direct; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzclose_r(file) + gzFile file; +{ + int ret; + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return Z_STREAM_ERROR; + state = (gz_statep)file; + + /* check that we're reading */ + if (state->mode != GZ_READ) + return Z_STREAM_ERROR; + + /* free memory and close file */ + if (state->size) { + inflateEnd(&(state->strm)); + free(state->out); + free(state->in); + } + gz_error(state, Z_OK, NULL); + free(state->path); + ret = close(state->fd); + free(state); + return ret ? Z_ERRNO : Z_OK; +} diff --git a/dep/zlib/gzwrite.c b/dep/zlib/gzwrite.c new file mode 100644 index 00000000000..e8defc6887a --- /dev/null +++ b/dep/zlib/gzwrite.c @@ -0,0 +1,531 @@ +/* gzwrite.c -- zlib functions for writing gzip files + * Copyright (C) 2004, 2005, 2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "gzguts.h" + +/* Local functions */ +local int gz_init OF((gz_statep)); +local int gz_comp OF((gz_statep, int)); +local int gz_zero OF((gz_statep, z_off64_t)); + +/* Initialize state for writing a gzip file. Mark initialization by setting + state->size to non-zero. Return -1 on failure or 0 on success. */ +local int gz_init(state) + gz_statep state; +{ + int ret; + z_streamp strm = &(state->strm); + + /* allocate input and output buffers */ + state->in = malloc(state->want); + state->out = malloc(state->want); + if (state->in == NULL || state->out == NULL) { + if (state->out != NULL) + free(state->out); + if (state->in != NULL) + free(state->in); + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + + /* allocate deflate memory, set up for gzip compression */ + strm->zalloc = Z_NULL; + strm->zfree = Z_NULL; + strm->opaque = Z_NULL; + ret = deflateInit2(strm, state->level, Z_DEFLATED, + 15 + 16, 8, state->strategy); + if (ret != Z_OK) { + free(state->in); + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + + /* mark state as initialized */ + state->size = state->want; + + /* initialize write buffer */ + strm->avail_out = state->size; + strm->next_out = state->out; + state->next = strm->next_out; + return 0; +} + +/* Compress whatever is at avail_in and next_in and write to the output file. + Return -1 if there is an error writing to the output file, otherwise 0. + flush is assumed to be a valid deflate() flush value. If flush is Z_FINISH, + then the deflate() state is reset to start a new gzip stream. */ +local int gz_comp(state, flush) + gz_statep state; + int flush; +{ + int ret, got; + unsigned have; + z_streamp strm = &(state->strm); + + /* allocate memory if this is the first time through */ + if (state->size == 0 && gz_init(state) == -1) + return -1; + + /* run deflate() on provided input until it produces no more output */ + ret = Z_OK; + do { + /* write out current buffer contents if full, or if flushing, but if + doing Z_FINISH then don't write until we get to Z_STREAM_END */ + if (strm->avail_out == 0 || (flush != Z_NO_FLUSH && + (flush != Z_FINISH || ret == Z_STREAM_END))) { + have = (unsigned)(strm->next_out - state->next); + if (have && ((got = write(state->fd, state->next, have)) < 0 || + (unsigned)got != have)) { + gz_error(state, Z_ERRNO, zstrerror()); + return -1; + } + if (strm->avail_out == 0) { + strm->avail_out = state->size; + strm->next_out = state->out; + } + state->next = strm->next_out; + } + + /* compress */ + have = strm->avail_out; + ret = deflate(strm, flush); + if (ret == Z_STREAM_ERROR) { + gz_error(state, Z_STREAM_ERROR, + "internal error: deflate stream corrupt"); + return -1; + } + have -= strm->avail_out; + } while (have); + + /* if that completed a deflate stream, allow another to start */ + if (flush == Z_FINISH) + deflateReset(strm); + + /* all done, no errors */ + return 0; +} + +/* Compress len zeros to output. Return -1 on error, 0 on success. */ +local int gz_zero(state, len) + gz_statep state; + z_off64_t len; +{ + int first; + unsigned n; + z_streamp strm = &(state->strm); + + /* consume whatever's left in the input buffer */ + if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1) + return -1; + + /* compress len zeros (len guaranteed > 0) */ + first = 1; + while (len) { + n = GT_OFF(state->size) || (z_off64_t)state->size > len ? + (unsigned)len : state->size; + if (first) { + memset(state->in, 0, n); + first = 0; + } + strm->avail_in = n; + strm->next_in = state->in; + state->pos += n; + if (gz_comp(state, Z_NO_FLUSH) == -1) + return -1; + len -= n; + } + return 0; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzwrite(file, buf, len) + gzFile file; + voidpc buf; + unsigned len; +{ + unsigned put = len; + unsigned n; + gz_statep state; + z_streamp strm; + + /* get internal structure */ + if (file == NULL) + return 0; + state = (gz_statep)file; + strm = &(state->strm); + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return 0; + + /* since an int is returned, make sure len fits in one, otherwise return + with an error (this avoids the flaw in the interface) */ + if ((int)len < 0) { + gz_error(state, Z_BUF_ERROR, "requested length does not fit in int"); + return 0; + } + + /* if len is zero, avoid unnecessary operations */ + if (len == 0) + return 0; + + /* allocate memory if this is the first time through */ + if (state->size == 0 && gz_init(state) == -1) + return 0; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return 0; + } + + /* for small len, copy to input buffer, otherwise compress directly */ + if (len < state->size) { + /* copy to input buffer, compress when full */ + do { + if (strm->avail_in == 0) + strm->next_in = state->in; + n = state->size - strm->avail_in; + if (n > len) + n = len; + memcpy(strm->next_in + strm->avail_in, buf, n); + strm->avail_in += n; + state->pos += n; + buf = (char *)buf + n; + len -= n; + if (len && gz_comp(state, Z_NO_FLUSH) == -1) + return 0; + } while (len); + } + else { + /* consume whatever's left in the input buffer */ + if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1) + return 0; + + /* directly compress user buffer to file */ + strm->avail_in = len; + strm->next_in = (voidp)buf; + state->pos += len; + if (gz_comp(state, Z_NO_FLUSH) == -1) + return 0; + } + + /* input was all buffered or compressed (put will fit in int) */ + return (int)put; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzputc(file, c) + gzFile file; + int c; +{ + unsigned char buf[1]; + gz_statep state; + z_streamp strm; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + strm = &(state->strm); + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return -1; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return -1; + } + + /* try writing to input buffer for speed (state->size == 0 if buffer not + initialized) */ + if (strm->avail_in < state->size) { + if (strm->avail_in == 0) + strm->next_in = state->in; + strm->next_in[strm->avail_in++] = c; + state->pos++; + return c; + } + + /* no room in buffer or not initialized, use gz_write() */ + buf[0] = c; + if (gzwrite(file, buf, 1) != 1) + return -1; + return c; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzputs(file, str) + gzFile file; + const char *str; +{ + int ret; + unsigned len; + + /* write string */ + len = (unsigned)strlen(str); + ret = gzwrite(file, str, len); + return ret == 0 && len != 0 ? -1 : ret; +} + +#ifdef STDC +#include + +/* -- see zlib.h -- */ +int ZEXPORTVA gzprintf (gzFile file, const char *format, ...) +{ + int size, len; + gz_statep state; + z_streamp strm; + va_list va; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + strm = &(state->strm); + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return 0; + + /* make sure we have some buffer space */ + if (state->size == 0 && gz_init(state) == -1) + return 0; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return 0; + } + + /* consume whatever's left in the input buffer */ + if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1) + return 0; + + /* do the printf() into the input buffer, put length in len */ + size = (int)(state->size); + state->in[size - 1] = 0; + va_start(va, format); +#ifdef NO_vsnprintf +# ifdef HAS_vsprintf_void + (void)vsprintf(state->in, format, va); + va_end(va); + for (len = 0; len < size; len++) + if (state->in[len] == 0) break; +# else + len = vsprintf(state->in, format, va); + va_end(va); +# endif +#else +# ifdef HAS_vsnprintf_void + (void)vsnprintf(state->in, size, format, va); + va_end(va); + len = strlen(state->in); +# else + len = vsnprintf((char *)(state->in), size, format, va); + va_end(va); +# endif +#endif + + /* check that printf() results fit in buffer */ + if (len <= 0 || len >= (int)size || state->in[size - 1] != 0) + return 0; + + /* update buffer and position, defer compression until needed */ + strm->avail_in = (unsigned)len; + strm->next_in = state->in; + state->pos += len; + return len; +} + +#else /* !STDC */ + +/* -- see zlib.h -- */ +int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, + a11, a12, a13, a14, a15, a16, a17, a18, a19, a20) + gzFile file; + const char *format; + int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, + a11, a12, a13, a14, a15, a16, a17, a18, a19, a20; +{ + int size, len; + gz_statep state; + z_streamp strm; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + strm = &(state->strm); + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return 0; + + /* make sure we have some buffer space */ + if (state->size == 0 && gz_init(state) == -1) + return 0; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return 0; + } + + /* consume whatever's left in the input buffer */ + if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1) + return 0; + + /* do the printf() into the input buffer, put length in len */ + size = (int)(state->size); + state->in[size - 1] = 0; +#ifdef NO_snprintf +# ifdef HAS_sprintf_void + sprintf(state->in, format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); + for (len = 0; len < size; len++) + if (state->in[len] == 0) break; +# else + len = sprintf(state->in, format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); +# endif +#else +# ifdef HAS_snprintf_void + snprintf(state->in, size, format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); + len = strlen(state->in); +# else + len = snprintf(state->in, size, format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); +# endif +#endif + + /* check that printf() results fit in buffer */ + if (len <= 0 || len >= (int)size || state->in[size - 1] != 0) + return 0; + + /* update buffer and position, defer compression until needed */ + strm->avail_in = (unsigned)len; + strm->next_in = state->in; + state->pos += len; + return len; +} + +#endif + +/* -- see zlib.h -- */ +int ZEXPORT gzflush(file, flush) + gzFile file; + int flush; +{ + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return Z_STREAM_ERROR; + + /* check flush parameter */ + if (flush < 0 || flush > Z_FINISH) + return Z_STREAM_ERROR; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return -1; + } + + /* compress remaining data with requested flush */ + gz_comp(state, flush); + return state->err; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzsetparams(file, level, strategy) + gzFile file; + int level; + int strategy; +{ + gz_statep state; + z_streamp strm; + + /* get internal structure */ + if (file == NULL) + return Z_STREAM_ERROR; + state = (gz_statep)file; + strm = &(state->strm); + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return Z_STREAM_ERROR; + + /* if no change is requested, then do nothing */ + if (level == state->level && strategy == state->strategy) + return Z_OK; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return -1; + } + + /* change compression parameters for subsequent input */ + if (state->size) { + /* flush previous input with previous parameters before changing */ + if (strm->avail_in && gz_comp(state, Z_PARTIAL_FLUSH) == -1) + return state->err; + deflateParams(strm, level, strategy); + } + state->level = level; + state->strategy = strategy; + return Z_OK; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzclose_w(file) + gzFile file; +{ + int ret = 0; + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return Z_STREAM_ERROR; + state = (gz_statep)file; + + /* check that we're writing */ + if (state->mode != GZ_WRITE) + return Z_STREAM_ERROR; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + ret += gz_zero(state, state->skip); + } + + /* flush, free memory, and close file */ + ret += gz_comp(state, Z_FINISH); + (void)deflateEnd(&(state->strm)); + free(state->out); + free(state->in); + gz_error(state, Z_OK, NULL); + free(state->path); + ret += close(state->fd); + free(state); + return ret ? Z_ERRNO : Z_OK; +} diff --git a/dep/zlib/infback.c b/dep/zlib/infback.c new file mode 100644 index 00000000000..af3a8c965d5 --- /dev/null +++ b/dep/zlib/infback.c @@ -0,0 +1,632 @@ +/* infback.c -- inflate using a call-back interface + * Copyright (C) 1995-2009 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + This code is largely copied from inflate.c. Normally either infback.o or + inflate.o would be linked into an application--not both. The interface + with inffast.c is retained so that optimized assembler-coded versions of + inflate_fast() can be used with either inflate.c or infback.c. + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "inffast.h" + +/* function prototypes */ +local void fixedtables OF((struct inflate_state FAR *state)); + +/* + strm provides memory allocation functions in zalloc and zfree, or + Z_NULL to use the library memory allocation functions. + + windowBits is in the range 8..15, and window is a user-supplied + window and output buffer that is 2**windowBits bytes. + */ +int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size) +z_streamp strm; +int windowBits; +unsigned char FAR *window; +const char *version; +int stream_size; +{ + struct inflate_state FAR *state; + + if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || + stream_size != (int)(sizeof(z_stream))) + return Z_VERSION_ERROR; + if (strm == Z_NULL || window == Z_NULL || + windowBits < 8 || windowBits > 15) + return Z_STREAM_ERROR; + strm->msg = Z_NULL; /* in case we return an error */ + if (strm->zalloc == (alloc_func)0) { + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; + } + if (strm->zfree == (free_func)0) strm->zfree = zcfree; + state = (struct inflate_state FAR *)ZALLOC(strm, 1, + sizeof(struct inflate_state)); + if (state == Z_NULL) return Z_MEM_ERROR; + Tracev((stderr, "inflate: allocated\n")); + strm->state = (struct internal_state FAR *)state; + state->dmax = 32768U; + state->wbits = windowBits; + state->wsize = 1U << windowBits; + state->window = window; + state->wnext = 0; + state->whave = 0; + return Z_OK; +} + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +local void fixedtables(state) +struct inflate_state FAR *state; +{ +#ifdef BUILDFIXED + static int virgin = 1; + static code *lenfix, *distfix; + static code fixed[544]; + + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + unsigned sym, bits; + static code *next; + + /* literal/length table */ + sym = 0; + while (sym < 144) state->lens[sym++] = 8; + while (sym < 256) state->lens[sym++] = 9; + while (sym < 280) state->lens[sym++] = 7; + while (sym < 288) state->lens[sym++] = 8; + next = fixed; + lenfix = next; + bits = 9; + inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); + + /* distance table */ + sym = 0; + while (sym < 32) state->lens[sym++] = 5; + distfix = next; + bits = 5; + inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); + + /* do this just once */ + virgin = 0; + } +#else /* !BUILDFIXED */ +# include "inffixed.h" +#endif /* BUILDFIXED */ + state->lencode = lenfix; + state->lenbits = 9; + state->distcode = distfix; + state->distbits = 5; +} + +/* Macros for inflateBack(): */ + +/* Load returned state from inflate_fast() */ +#define LOAD() \ + do { \ + put = strm->next_out; \ + left = strm->avail_out; \ + next = strm->next_in; \ + have = strm->avail_in; \ + hold = state->hold; \ + bits = state->bits; \ + } while (0) + +/* Set state from registers for inflate_fast() */ +#define RESTORE() \ + do { \ + strm->next_out = put; \ + strm->avail_out = left; \ + strm->next_in = next; \ + strm->avail_in = have; \ + state->hold = hold; \ + state->bits = bits; \ + } while (0) + +/* Clear the input bit accumulator */ +#define INITBITS() \ + do { \ + hold = 0; \ + bits = 0; \ + } while (0) + +/* Assure that some input is available. If input is requested, but denied, + then return a Z_BUF_ERROR from inflateBack(). */ +#define PULL() \ + do { \ + if (have == 0) { \ + have = in(in_desc, &next); \ + if (have == 0) { \ + next = Z_NULL; \ + ret = Z_BUF_ERROR; \ + goto inf_leave; \ + } \ + } \ + } while (0) + +/* Get a byte of input into the bit accumulator, or return from inflateBack() + with an error if there is no input available. */ +#define PULLBYTE() \ + do { \ + PULL(); \ + have--; \ + hold += (unsigned long)(*next++) << bits; \ + bits += 8; \ + } while (0) + +/* Assure that there are at least n bits in the bit accumulator. If there is + not enough available input to do that, then return from inflateBack() with + an error. */ +#define NEEDBITS(n) \ + do { \ + while (bits < (unsigned)(n)) \ + PULLBYTE(); \ + } while (0) + +/* Return the low n bits of the bit accumulator (n < 16) */ +#define BITS(n) \ + ((unsigned)hold & ((1U << (n)) - 1)) + +/* Remove n bits from the bit accumulator */ +#define DROPBITS(n) \ + do { \ + hold >>= (n); \ + bits -= (unsigned)(n); \ + } while (0) + +/* Remove zero to seven bits as needed to go to a byte boundary */ +#define BYTEBITS() \ + do { \ + hold >>= bits & 7; \ + bits -= bits & 7; \ + } while (0) + +/* Assure that some output space is available, by writing out the window + if it's full. If the write fails, return from inflateBack() with a + Z_BUF_ERROR. */ +#define ROOM() \ + do { \ + if (left == 0) { \ + put = state->window; \ + left = state->wsize; \ + state->whave = left; \ + if (out(out_desc, put, left)) { \ + ret = Z_BUF_ERROR; \ + goto inf_leave; \ + } \ + } \ + } while (0) + +/* + strm provides the memory allocation functions and window buffer on input, + and provides information on the unused input on return. For Z_DATA_ERROR + returns, strm will also provide an error message. + + in() and out() are the call-back input and output functions. When + inflateBack() needs more input, it calls in(). When inflateBack() has + filled the window with output, or when it completes with data in the + window, it calls out() to write out the data. The application must not + change the provided input until in() is called again or inflateBack() + returns. The application must not change the window/output buffer until + inflateBack() returns. + + in() and out() are called with a descriptor parameter provided in the + inflateBack() call. This parameter can be a structure that provides the + information required to do the read or write, as well as accumulated + information on the input and output such as totals and check values. + + in() should return zero on failure. out() should return non-zero on + failure. If either in() or out() fails, than inflateBack() returns a + Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it + was in() or out() that caused in the error. Otherwise, inflateBack() + returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format + error, or Z_MEM_ERROR if it could not allocate memory for the state. + inflateBack() can also return Z_STREAM_ERROR if the input parameters + are not correct, i.e. strm is Z_NULL or the state was not initialized. + */ +int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc) +z_streamp strm; +in_func in; +void FAR *in_desc; +out_func out; +void FAR *out_desc; +{ + struct inflate_state FAR *state; + unsigned char FAR *next; /* next input */ + unsigned char FAR *put; /* next output */ + unsigned have, left; /* available input and output */ + unsigned long hold; /* bit buffer */ + unsigned bits; /* bits in bit buffer */ + unsigned copy; /* number of stored or match bytes to copy */ + unsigned char FAR *from; /* where to copy match bytes from */ + code here; /* current decoding table entry */ + code last; /* parent table entry */ + unsigned len; /* length to copy for repeats, bits to drop */ + int ret; /* return code */ + static const unsigned short order[19] = /* permutation of code lengths */ + {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + + /* Check that the strm exists and that the state was initialized */ + if (strm == Z_NULL || strm->state == Z_NULL) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + + /* Reset the state */ + strm->msg = Z_NULL; + state->mode = TYPE; + state->last = 0; + state->whave = 0; + next = strm->next_in; + have = next != Z_NULL ? strm->avail_in : 0; + hold = 0; + bits = 0; + put = state->window; + left = state->wsize; + + /* Inflate until end of block marked as last */ + for (;;) + switch (state->mode) { + case TYPE: + /* determine and dispatch block type */ + if (state->last) { + BYTEBITS(); + state->mode = DONE; + break; + } + NEEDBITS(3); + state->last = BITS(1); + DROPBITS(1); + switch (BITS(2)) { + case 0: /* stored block */ + Tracev((stderr, "inflate: stored block%s\n", + state->last ? " (last)" : "")); + state->mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + Tracev((stderr, "inflate: fixed codes block%s\n", + state->last ? " (last)" : "")); + state->mode = LEN; /* decode codes */ + break; + case 2: /* dynamic block */ + Tracev((stderr, "inflate: dynamic codes block%s\n", + state->last ? " (last)" : "")); + state->mode = TABLE; + break; + case 3: + strm->msg = (char *)"invalid block type"; + state->mode = BAD; + } + DROPBITS(2); + break; + + case STORED: + /* get and verify stored block length */ + BYTEBITS(); /* go to byte boundary */ + NEEDBITS(32); + if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { + strm->msg = (char *)"invalid stored block lengths"; + state->mode = BAD; + break; + } + state->length = (unsigned)hold & 0xffff; + Tracev((stderr, "inflate: stored length %u\n", + state->length)); + INITBITS(); + + /* copy stored block from input to output */ + while (state->length != 0) { + copy = state->length; + PULL(); + ROOM(); + if (copy > have) copy = have; + if (copy > left) copy = left; + zmemcpy(put, next, copy); + have -= copy; + next += copy; + left -= copy; + put += copy; + state->length -= copy; + } + Tracev((stderr, "inflate: stored end\n")); + state->mode = TYPE; + break; + + case TABLE: + /* get dynamic table entries descriptor */ + NEEDBITS(14); + state->nlen = BITS(5) + 257; + DROPBITS(5); + state->ndist = BITS(5) + 1; + DROPBITS(5); + state->ncode = BITS(4) + 4; + DROPBITS(4); +#ifndef PKZIP_BUG_WORKAROUND + if (state->nlen > 286 || state->ndist > 30) { + strm->msg = (char *)"too many length or distance symbols"; + state->mode = BAD; + break; + } +#endif + Tracev((stderr, "inflate: table sizes ok\n")); + + /* get code length code lengths (not a typo) */ + state->have = 0; + while (state->have < state->ncode) { + NEEDBITS(3); + state->lens[order[state->have++]] = (unsigned short)BITS(3); + DROPBITS(3); + } + while (state->have < 19) + state->lens[order[state->have++]] = 0; + state->next = state->codes; + state->lencode = (code const FAR *)(state->next); + state->lenbits = 7; + ret = inflate_table(CODES, state->lens, 19, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid code lengths set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: code lengths ok\n")); + + /* get length and distance code code lengths */ + state->have = 0; + while (state->have < state->nlen + state->ndist) { + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.val < 16) { + NEEDBITS(here.bits); + DROPBITS(here.bits); + state->lens[state->have++] = here.val; + } + else { + if (here.val == 16) { + NEEDBITS(here.bits + 2); + DROPBITS(here.bits); + if (state->have == 0) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + len = (unsigned)(state->lens[state->have - 1]); + copy = 3 + BITS(2); + DROPBITS(2); + } + else if (here.val == 17) { + NEEDBITS(here.bits + 3); + DROPBITS(here.bits); + len = 0; + copy = 3 + BITS(3); + DROPBITS(3); + } + else { + NEEDBITS(here.bits + 7); + DROPBITS(here.bits); + len = 0; + copy = 11 + BITS(7); + DROPBITS(7); + } + if (state->have + copy > state->nlen + state->ndist) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + while (copy--) + state->lens[state->have++] = (unsigned short)len; + } + } + + /* handle error breaks in while */ + if (state->mode == BAD) break; + + /* check for end-of-block code (better have one) */ + if (state->lens[256] == 0) { + strm->msg = (char *)"invalid code -- missing end-of-block"; + state->mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state->next = state->codes; + state->lencode = (code const FAR *)(state->next); + state->lenbits = 9; + ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid literal/lengths set"; + state->mode = BAD; + break; + } + state->distcode = (code const FAR *)(state->next); + state->distbits = 6; + ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, + &(state->next), &(state->distbits), state->work); + if (ret) { + strm->msg = (char *)"invalid distances set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: codes ok\n")); + state->mode = LEN; + + case LEN: + /* use inflate_fast() if we have enough input and output */ + if (have >= 6 && left >= 258) { + RESTORE(); + if (state->whave < state->wsize) + state->whave = state->wsize - left; + inflate_fast(strm, state->wsize); + LOAD(); + break; + } + + /* get a literal, length, or end-of-block code */ + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.op && (here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->lencode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(here.bits); + state->length = (unsigned)here.val; + + /* process literal */ + if (here.op == 0) { + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", here.val)); + ROOM(); + *put++ = (unsigned char)(state->length); + left--; + state->mode = LEN; + break; + } + + /* process end of block */ + if (here.op & 32) { + Tracevv((stderr, "inflate: end of block\n")); + state->mode = TYPE; + break; + } + + /* invalid code */ + if (here.op & 64) { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + + /* length code -- get extra bits, if any */ + state->extra = (unsigned)(here.op) & 15; + if (state->extra != 0) { + NEEDBITS(state->extra); + state->length += BITS(state->extra); + DROPBITS(state->extra); + } + Tracevv((stderr, "inflate: length %u\n", state->length)); + + /* get distance code */ + for (;;) { + here = state->distcode[BITS(state->distbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if ((here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->distcode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(here.bits); + if (here.op & 64) { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + state->offset = (unsigned)here.val; + + /* get distance extra bits, if any */ + state->extra = (unsigned)(here.op) & 15; + if (state->extra != 0) { + NEEDBITS(state->extra); + state->offset += BITS(state->extra); + DROPBITS(state->extra); + } + if (state->offset > state->wsize - (state->whave < state->wsize ? + left : 0)) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } + Tracevv((stderr, "inflate: distance %u\n", state->offset)); + + /* copy match from window to output */ + do { + ROOM(); + copy = state->wsize - state->offset; + if (copy < left) { + from = put + copy; + copy = left - copy; + } + else { + from = put - state->offset; + copy = left; + } + if (copy > state->length) copy = state->length; + state->length -= copy; + left -= copy; + do { + *put++ = *from++; + } while (--copy); + } while (state->length != 0); + break; + + case DONE: + /* inflate stream terminated properly -- write leftover output */ + ret = Z_STREAM_END; + if (left < state->wsize) { + if (out(out_desc, state->window, state->wsize - left)) + ret = Z_BUF_ERROR; + } + goto inf_leave; + + case BAD: + ret = Z_DATA_ERROR; + goto inf_leave; + + default: /* can't happen, but makes compilers happy */ + ret = Z_STREAM_ERROR; + goto inf_leave; + } + + /* Return unused input */ + inf_leave: + strm->next_in = next; + strm->avail_in = have; + return ret; +} + +int ZEXPORT inflateBackEnd(strm) +z_streamp strm; +{ + if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) + return Z_STREAM_ERROR; + ZFREE(strm, strm->state); + strm->state = Z_NULL; + Tracev((stderr, "inflate: end\n")); + return Z_OK; +} diff --git a/dep/zlib/inffast.c b/dep/zlib/inffast.c new file mode 100644 index 00000000000..2f1d60b43b8 --- /dev/null +++ b/dep/zlib/inffast.c @@ -0,0 +1,340 @@ +/* inffast.c -- fast decoding + * Copyright (C) 1995-2008, 2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "inffast.h" + +#ifndef ASMINF + +/* Allow machine dependent optimization for post-increment or pre-increment. + Based on testing to date, + Pre-increment preferred for: + - PowerPC G3 (Adler) + - MIPS R5000 (Randers-Pehrson) + Post-increment preferred for: + - none + No measurable difference: + - Pentium III (Anderson) + - M68060 (Nikl) + */ +#ifdef POSTINC +# define OFF 0 +# define PUP(a) *(a)++ +#else +# define OFF 1 +# define PUP(a) *++(a) +#endif + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state->mode == LEN + strm->avail_in >= 6 + strm->avail_out >= 258 + start >= strm->avail_out + state->bits < 8 + + On return, state->mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm->avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm->avail_out >= 258 for each loop to avoid checking for + output space. + */ +void ZLIB_INTERNAL inflate_fast(strm, start) +z_streamp strm; +unsigned start; /* inflate()'s starting value for strm->avail_out */ +{ + struct inflate_state FAR *state; + unsigned char FAR *in; /* local strm->next_in */ + unsigned char FAR *last; /* while in < last, enough input available */ + unsigned char FAR *out; /* local strm->next_out */ + unsigned char FAR *beg; /* inflate()'s initial strm->next_out */ + unsigned char FAR *end; /* while out < end, enough space available */ +#ifdef INFLATE_STRICT + unsigned dmax; /* maximum distance from zlib header */ +#endif + unsigned wsize; /* window size or zero if not using window */ + unsigned whave; /* valid bytes in the window */ + unsigned wnext; /* window write index */ + unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */ + unsigned long hold; /* local strm->hold */ + unsigned bits; /* local strm->bits */ + code const FAR *lcode; /* local strm->lencode */ + code const FAR *dcode; /* local strm->distcode */ + unsigned lmask; /* mask for first level of length codes */ + unsigned dmask; /* mask for first level of distance codes */ + code here; /* retrieved table entry */ + unsigned op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + unsigned len; /* match length, unused bytes */ + unsigned dist; /* match distance */ + unsigned char FAR *from; /* where to copy match from */ + + /* copy state to local variables */ + state = (struct inflate_state FAR *)strm->state; + in = strm->next_in - OFF; + last = in + (strm->avail_in - 5); + out = strm->next_out - OFF; + beg = out - (start - strm->avail_out); + end = out + (strm->avail_out - 257); +#ifdef INFLATE_STRICT + dmax = state->dmax; +#endif + wsize = state->wsize; + whave = state->whave; + wnext = state->wnext; + window = state->window; + hold = state->hold; + bits = state->bits; + lcode = state->lencode; + dcode = state->distcode; + lmask = (1U << state->lenbits) - 1; + dmask = (1U << state->distbits) - 1; + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + do { + if (bits < 15) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + here = lcode[hold & lmask]; + dolen: + op = (unsigned)(here.bits); + hold >>= op; + bits -= op; + op = (unsigned)(here.op); + if (op == 0) { /* literal */ + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", here.val)); + PUP(out) = (unsigned char)(here.val); + } + else if (op & 16) { /* length base */ + len = (unsigned)(here.val); + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + len += (unsigned)hold & ((1U << op) - 1); + hold >>= op; + bits -= op; + } + Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + here = dcode[hold & dmask]; + dodist: + op = (unsigned)(here.bits); + hold >>= op; + bits -= op; + op = (unsigned)(here.op); + if (op & 16) { /* distance base */ + dist = (unsigned)(here.val); + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + if (bits < op) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + } + dist += (unsigned)hold & ((1U << op) - 1); +#ifdef INFLATE_STRICT + if (dist > dmax) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#endif + hold >>= op; + bits -= op; + Tracevv((stderr, "inflate: distance %u\n", dist)); + op = (unsigned)(out - beg); /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state->sane) { + strm->msg = + (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + if (len <= op - whave) { + do { + PUP(out) = 0; + } while (--len); + continue; + } + len -= op - whave; + do { + PUP(out) = 0; + } while (--op > whave); + if (op == 0) { + from = out - dist; + do { + PUP(out) = PUP(from); + } while (--len); + continue; + } +#endif + } + from = window - OFF; + if (wnext == 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = out - dist; /* rest from output */ + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = window - OFF; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = out - dist; /* rest from output */ + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = out - dist; /* rest from output */ + } + } + while (len > 2) { + PUP(out) = PUP(from); + PUP(out) = PUP(from); + PUP(out) = PUP(from); + len -= 3; + } + if (len) { + PUP(out) = PUP(from); + if (len > 1) + PUP(out) = PUP(from); + } + } + else { + from = out - dist; /* copy direct from output */ + do { /* minimum length is three */ + PUP(out) = PUP(from); + PUP(out) = PUP(from); + PUP(out) = PUP(from); + len -= 3; + } while (len > 2); + if (len) { + PUP(out) = PUP(from); + if (len > 1) + PUP(out) = PUP(from); + } + } + } + else if ((op & 64) == 0) { /* 2nd level distance code */ + here = dcode[here.val + (hold & ((1U << op) - 1))]; + goto dodist; + } + else { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + } + else if ((op & 64) == 0) { /* 2nd level length code */ + here = lcode[here.val + (hold & ((1U << op) - 1))]; + goto dolen; + } + else if (op & 32) { /* end-of-block */ + Tracevv((stderr, "inflate: end of block\n")); + state->mode = TYPE; + break; + } + else { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + } while (in < last && out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + in -= len; + bits -= len << 3; + hold &= (1U << bits) - 1; + + /* update state and return */ + strm->next_in = in + OFF; + strm->next_out = out + OFF; + strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last)); + strm->avail_out = (unsigned)(out < end ? + 257 + (end - out) : 257 - (out - end)); + state->hold = hold; + state->bits = bits; + return; +} + +/* + inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe): + - Using bit fields for code structure + - Different op definition to avoid & for extra bits (do & for table bits) + - Three separate decoding do-loops for direct, window, and wnext == 0 + - Special case for distance > 1 copies to do overlapped load and store copy + - Explicit branch predictions (based on measured branch probabilities) + - Deferring match copy and interspersed it with decoding subsequent codes + - Swapping literal/length else + - Swapping window/direct else + - Larger unrolled copy loops (three is about right) + - Moving len -= 3 statement into middle of loop + */ + +#endif /* !ASMINF */ diff --git a/dep/zlib/inffast.h b/dep/zlib/inffast.h new file mode 100644 index 00000000000..e5c1aa4ca8c --- /dev/null +++ b/dep/zlib/inffast.h @@ -0,0 +1,11 @@ +/* inffast.h -- header to use inffast.c + * Copyright (C) 1995-2003, 2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +void ZLIB_INTERNAL inflate_fast OF((z_streamp strm, unsigned start)); diff --git a/dep/zlib/inffixed.h b/dep/zlib/inffixed.h new file mode 100644 index 00000000000..75ed4b5978d --- /dev/null +++ b/dep/zlib/inffixed.h @@ -0,0 +1,94 @@ + /* inffixed.h -- table for decoding fixed codes + * Generated automatically by makefixed(). + */ + + /* WARNING: this file should *not* be used by applications. It + is part of the implementation of the compression library and + is subject to change. Applications should only use zlib.h. + */ + + static const code lenfix[512] = { + {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48}, + {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128}, + {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59}, + {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176}, + {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20}, + {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100}, + {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8}, + {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216}, + {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76}, + {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114}, + {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2}, + {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148}, + {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42}, + {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86}, + {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15}, + {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236}, + {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62}, + {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142}, + {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31}, + {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162}, + {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25}, + {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105}, + {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4}, + {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202}, + {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69}, + {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125}, + {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13}, + {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195}, + {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35}, + {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91}, + {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19}, + {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246}, + {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55}, + {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135}, + {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99}, + {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190}, + {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16}, + {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96}, + {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6}, + {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209}, + {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72}, + {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116}, + {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4}, + {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153}, + {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44}, + {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82}, + {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11}, + {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229}, + {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58}, + {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138}, + {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51}, + {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173}, + {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30}, + {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110}, + {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0}, + {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195}, + {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65}, + {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121}, + {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9}, + {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258}, + {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37}, + {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93}, + {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23}, + {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251}, + {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51}, + {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131}, + {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67}, + {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183}, + {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23}, + {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103}, + {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9}, + {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223}, + {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79}, + {0,9,255} + }; + + static const code distfix[32] = { + {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025}, + {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193}, + {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385}, + {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577}, + {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073}, + {22,5,193},{64,5,0} + }; diff --git a/dep/zlib/inflate.c b/dep/zlib/inflate.c new file mode 100644 index 00000000000..a8431abeacf --- /dev/null +++ b/dep/zlib/inflate.c @@ -0,0 +1,1480 @@ +/* inflate.c -- zlib decompression + * Copyright (C) 1995-2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * Change history: + * + * 1.2.beta0 24 Nov 2002 + * - First version -- complete rewrite of inflate to simplify code, avoid + * creation of window when not needed, minimize use of window when it is + * needed, make inffast.c even faster, implement gzip decoding, and to + * improve code readability and style over the previous zlib inflate code + * + * 1.2.beta1 25 Nov 2002 + * - Use pointers for available input and output checking in inffast.c + * - Remove input and output counters in inffast.c + * - Change inffast.c entry and loop from avail_in >= 7 to >= 6 + * - Remove unnecessary second byte pull from length extra in inffast.c + * - Unroll direct copy to three copies per loop in inffast.c + * + * 1.2.beta2 4 Dec 2002 + * - Change external routine names to reduce potential conflicts + * - Correct filename to inffixed.h for fixed tables in inflate.c + * - Make hbuf[] unsigned char to match parameter type in inflate.c + * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset) + * to avoid negation problem on Alphas (64 bit) in inflate.c + * + * 1.2.beta3 22 Dec 2002 + * - Add comments on state->bits assertion in inffast.c + * - Add comments on op field in inftrees.h + * - Fix bug in reuse of allocated window after inflateReset() + * - Remove bit fields--back to byte structure for speed + * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths + * - Change post-increments to pre-increments in inflate_fast(), PPC biased? + * - Add compile time option, POSTINC, to use post-increments instead (Intel?) + * - Make MATCH copy in inflate() much faster for when inflate_fast() not used + * - Use local copies of stream next and avail values, as well as local bit + * buffer and bit count in inflate()--for speed when inflate_fast() not used + * + * 1.2.beta4 1 Jan 2003 + * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings + * - Move a comment on output buffer sizes from inffast.c to inflate.c + * - Add comments in inffast.c to introduce the inflate_fast() routine + * - Rearrange window copies in inflate_fast() for speed and simplification + * - Unroll last copy for window match in inflate_fast() + * - Use local copies of window variables in inflate_fast() for speed + * - Pull out common wnext == 0 case for speed in inflate_fast() + * - Make op and len in inflate_fast() unsigned for consistency + * - Add FAR to lcode and dcode declarations in inflate_fast() + * - Simplified bad distance check in inflate_fast() + * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new + * source file infback.c to provide a call-back interface to inflate for + * programs like gzip and unzip -- uses window as output buffer to avoid + * window copying + * + * 1.2.beta5 1 Jan 2003 + * - Improved inflateBack() interface to allow the caller to provide initial + * input in strm. + * - Fixed stored blocks bug in inflateBack() + * + * 1.2.beta6 4 Jan 2003 + * - Added comments in inffast.c on effectiveness of POSTINC + * - Typecasting all around to reduce compiler warnings + * - Changed loops from while (1) or do {} while (1) to for (;;), again to + * make compilers happy + * - Changed type of window in inflateBackInit() to unsigned char * + * + * 1.2.beta7 27 Jan 2003 + * - Changed many types to unsigned or unsigned short to avoid warnings + * - Added inflateCopy() function + * + * 1.2.0 9 Mar 2003 + * - Changed inflateBack() interface to provide separate opaque descriptors + * for the in() and out() functions + * - Changed inflateBack() argument and in_func typedef to swap the length + * and buffer address return values for the input function + * - Check next_in and next_out for Z_NULL on entry to inflate() + * + * The history for versions after 1.2.0 are in ChangeLog in zlib distribution. + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "inffast.h" + +#ifdef MAKEFIXED +# ifndef BUILDFIXED +# define BUILDFIXED +# endif +#endif + +/* function prototypes */ +local void fixedtables OF((struct inflate_state FAR *state)); +local int updatewindow OF((z_streamp strm, unsigned out)); +#ifdef BUILDFIXED + void makefixed OF((void)); +#endif +local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf, + unsigned len)); + +int ZEXPORT inflateReset(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + strm->total_in = strm->total_out = state->total = 0; + strm->msg = Z_NULL; + strm->adler = 1; /* to support ill-conceived Java test suite */ + state->mode = HEAD; + state->last = 0; + state->havedict = 0; + state->dmax = 32768U; + state->head = Z_NULL; + state->wsize = 0; + state->whave = 0; + state->wnext = 0; + state->hold = 0; + state->bits = 0; + state->lencode = state->distcode = state->next = state->codes; + state->sane = 1; + state->back = -1; + Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +int ZEXPORT inflateReset2(strm, windowBits) +z_streamp strm; +int windowBits; +{ + int wrap; + struct inflate_state FAR *state; + + /* get the state */ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 1; +#ifdef GUNZIP + if (windowBits < 48) + windowBits &= 15; +#endif + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) + return Z_STREAM_ERROR; + if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) { + ZFREE(strm, state->window); + state->window = Z_NULL; + } + + /* update state and reset the rest of it */ + state->wrap = wrap; + state->wbits = (unsigned)windowBits; + return inflateReset(strm); +} + +int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size) +z_streamp strm; +int windowBits; +const char *version; +int stream_size; +{ + int ret; + struct inflate_state FAR *state; + + if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || + stream_size != (int)(sizeof(z_stream))) + return Z_VERSION_ERROR; + if (strm == Z_NULL) return Z_STREAM_ERROR; + strm->msg = Z_NULL; /* in case we return an error */ + if (strm->zalloc == (alloc_func)0) { + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; + } + if (strm->zfree == (free_func)0) strm->zfree = zcfree; + state = (struct inflate_state FAR *) + ZALLOC(strm, 1, sizeof(struct inflate_state)); + if (state == Z_NULL) return Z_MEM_ERROR; + Tracev((stderr, "inflate: allocated\n")); + strm->state = (struct internal_state FAR *)state; + state->window = Z_NULL; + ret = inflateReset2(strm, windowBits); + if (ret != Z_OK) { + ZFREE(strm, state); + strm->state = Z_NULL; + } + return ret; +} + +int ZEXPORT inflateInit_(strm, version, stream_size) +z_streamp strm; +const char *version; +int stream_size; +{ + return inflateInit2_(strm, DEF_WBITS, version, stream_size); +} + +int ZEXPORT inflatePrime(strm, bits, value) +z_streamp strm; +int bits; +int value; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (bits < 0) { + state->hold = 0; + state->bits = 0; + return Z_OK; + } + if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR; + value &= (1L << bits) - 1; + state->hold += value << state->bits; + state->bits += bits; + return Z_OK; +} + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +local void fixedtables(state) +struct inflate_state FAR *state; +{ +#ifdef BUILDFIXED + static int virgin = 1; + static code *lenfix, *distfix; + static code fixed[544]; + + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + unsigned sym, bits; + static code *next; + + /* literal/length table */ + sym = 0; + while (sym < 144) state->lens[sym++] = 8; + while (sym < 256) state->lens[sym++] = 9; + while (sym < 280) state->lens[sym++] = 7; + while (sym < 288) state->lens[sym++] = 8; + next = fixed; + lenfix = next; + bits = 9; + inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); + + /* distance table */ + sym = 0; + while (sym < 32) state->lens[sym++] = 5; + distfix = next; + bits = 5; + inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); + + /* do this just once */ + virgin = 0; + } +#else /* !BUILDFIXED */ +# include "inffixed.h" +#endif /* BUILDFIXED */ + state->lencode = lenfix; + state->lenbits = 9; + state->distcode = distfix; + state->distbits = 5; +} + +#ifdef MAKEFIXED +#include + +/* + Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also + defines BUILDFIXED, so the tables are built on the fly. makefixed() writes + those tables to stdout, which would be piped to inffixed.h. A small program + can simply call makefixed to do this: + + void makefixed(void); + + int main(void) + { + makefixed(); + return 0; + } + + Then that can be linked with zlib built with MAKEFIXED defined and run: + + a.out > inffixed.h + */ +void makefixed() +{ + unsigned low, size; + struct inflate_state state; + + fixedtables(&state); + puts(" /* inffixed.h -- table for decoding fixed codes"); + puts(" * Generated automatically by makefixed()."); + puts(" */"); + puts(""); + puts(" /* WARNING: this file should *not* be used by applications."); + puts(" It is part of the implementation of this library and is"); + puts(" subject to change. Applications should only use zlib.h."); + puts(" */"); + puts(""); + size = 1U << 9; + printf(" static const code lenfix[%u] = {", size); + low = 0; + for (;;) { + if ((low % 7) == 0) printf("\n "); + printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits, + state.lencode[low].val); + if (++low == size) break; + putchar(','); + } + puts("\n };"); + size = 1U << 5; + printf("\n static const code distfix[%u] = {", size); + low = 0; + for (;;) { + if ((low % 6) == 0) printf("\n "); + printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits, + state.distcode[low].val); + if (++low == size) break; + putchar(','); + } + puts("\n };"); +} +#endif /* MAKEFIXED */ + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +local int updatewindow(strm, out) +z_streamp strm; +unsigned out; +{ + struct inflate_state FAR *state; + unsigned copy, dist; + + state = (struct inflate_state FAR *)strm->state; + + /* if it hasn't been done already, allocate space for the window */ + if (state->window == Z_NULL) { + state->window = (unsigned char FAR *) + ZALLOC(strm, 1U << state->wbits, + sizeof(unsigned char)); + if (state->window == Z_NULL) return 1; + } + + /* if window not in use yet, initialize */ + if (state->wsize == 0) { + state->wsize = 1U << state->wbits; + state->wnext = 0; + state->whave = 0; + } + + /* copy state->wsize or less output bytes into the circular window */ + copy = out - strm->avail_out; + if (copy >= state->wsize) { + zmemcpy(state->window, strm->next_out - state->wsize, state->wsize); + state->wnext = 0; + state->whave = state->wsize; + } + else { + dist = state->wsize - state->wnext; + if (dist > copy) dist = copy; + zmemcpy(state->window + state->wnext, strm->next_out - copy, dist); + copy -= dist; + if (copy) { + zmemcpy(state->window, strm->next_out - copy, copy); + state->wnext = copy; + state->whave = state->wsize; + } + else { + state->wnext += dist; + if (state->wnext == state->wsize) state->wnext = 0; + if (state->whave < state->wsize) state->whave += dist; + } + } + return 0; +} + +/* Macros for inflate(): */ + +/* check function to use adler32() for zlib or crc32() for gzip */ +#ifdef GUNZIP +# define UPDATE(check, buf, len) \ + (state->flags ? crc32(check, buf, len) : adler32(check, buf, len)) +#else +# define UPDATE(check, buf, len) adler32(check, buf, len) +#endif + +/* check macros for header crc */ +#ifdef GUNZIP +# define CRC2(check, word) \ + do { \ + hbuf[0] = (unsigned char)(word); \ + hbuf[1] = (unsigned char)((word) >> 8); \ + check = crc32(check, hbuf, 2); \ + } while (0) + +# define CRC4(check, word) \ + do { \ + hbuf[0] = (unsigned char)(word); \ + hbuf[1] = (unsigned char)((word) >> 8); \ + hbuf[2] = (unsigned char)((word) >> 16); \ + hbuf[3] = (unsigned char)((word) >> 24); \ + check = crc32(check, hbuf, 4); \ + } while (0) +#endif + +/* Load registers with state in inflate() for speed */ +#define LOAD() \ + do { \ + put = strm->next_out; \ + left = strm->avail_out; \ + next = strm->next_in; \ + have = strm->avail_in; \ + hold = state->hold; \ + bits = state->bits; \ + } while (0) + +/* Restore state from registers in inflate() */ +#define RESTORE() \ + do { \ + strm->next_out = put; \ + strm->avail_out = left; \ + strm->next_in = next; \ + strm->avail_in = have; \ + state->hold = hold; \ + state->bits = bits; \ + } while (0) + +/* Clear the input bit accumulator */ +#define INITBITS() \ + do { \ + hold = 0; \ + bits = 0; \ + } while (0) + +/* Get a byte of input into the bit accumulator, or return from inflate() + if there is no input available. */ +#define PULLBYTE() \ + do { \ + if (have == 0) goto inf_leave; \ + have--; \ + hold += (unsigned long)(*next++) << bits; \ + bits += 8; \ + } while (0) + +/* Assure that there are at least n bits in the bit accumulator. If there is + not enough available input to do that, then return from inflate(). */ +#define NEEDBITS(n) \ + do { \ + while (bits < (unsigned)(n)) \ + PULLBYTE(); \ + } while (0) + +/* Return the low n bits of the bit accumulator (n < 16) */ +#define BITS(n) \ + ((unsigned)hold & ((1U << (n)) - 1)) + +/* Remove n bits from the bit accumulator */ +#define DROPBITS(n) \ + do { \ + hold >>= (n); \ + bits -= (unsigned)(n); \ + } while (0) + +/* Remove zero to seven bits as needed to go to a byte boundary */ +#define BYTEBITS() \ + do { \ + hold >>= bits & 7; \ + bits -= bits & 7; \ + } while (0) + +/* Reverse the bytes in a 32-bit value */ +#define REVERSE(q) \ + ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ + (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) + +/* + inflate() uses a state machine to process as much input data and generate as + much output data as possible before returning. The state machine is + structured roughly as follows: + + for (;;) switch (state) { + ... + case STATEn: + if (not enough input data or output space to make progress) + return; + ... make progress ... + state = STATEm; + break; + ... + } + + so when inflate() is called again, the same case is attempted again, and + if the appropriate resources are provided, the machine proceeds to the + next state. The NEEDBITS() macro is usually the way the state evaluates + whether it can proceed or should return. NEEDBITS() does the return if + the requested bits are not available. The typical use of the BITS macros + is: + + NEEDBITS(n); + ... do something with BITS(n) ... + DROPBITS(n); + + where NEEDBITS(n) either returns from inflate() if there isn't enough + input left to load n bits into the accumulator, or it continues. BITS(n) + gives the low n bits in the accumulator. When done, DROPBITS(n) drops + the low n bits off the accumulator. INITBITS() clears the accumulator + and sets the number of available bits to zero. BYTEBITS() discards just + enough bits to put the accumulator on a byte boundary. After BYTEBITS() + and a NEEDBITS(8), then BITS(8) would return the next byte in the stream. + + NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return + if there is no input available. The decoding of variable length codes uses + PULLBYTE() directly in order to pull just enough bytes to decode the next + code, and no more. + + Some states loop until they get enough input, making sure that enough + state information is maintained to continue the loop where it left off + if NEEDBITS() returns in the loop. For example, want, need, and keep + would all have to actually be part of the saved state in case NEEDBITS() + returns: + + case STATEw: + while (want < need) { + NEEDBITS(n); + keep[want++] = BITS(n); + DROPBITS(n); + } + state = STATEx; + case STATEx: + + As shown above, if the next state is also the next case, then the break + is omitted. + + A state may also return if there is not enough output space available to + complete that state. Those states are copying stored data, writing a + literal byte, and copying a matching string. + + When returning, a "goto inf_leave" is used to update the total counters, + update the check value, and determine whether any progress has been made + during that inflate() call in order to return the proper return code. + Progress is defined as a change in either strm->avail_in or strm->avail_out. + When there is a window, goto inf_leave will update the window with the last + output written. If a goto inf_leave occurs in the middle of decompression + and there is no window currently, goto inf_leave will create one and copy + output to the window for the next call of inflate(). + + In this implementation, the flush parameter of inflate() only affects the + return code (per zlib.h). inflate() always writes as much as possible to + strm->next_out, given the space available and the provided input--the effect + documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers + the allocation of and copying into a sliding window until necessary, which + provides the effect documented in zlib.h for Z_FINISH when the entire input + stream available. So the only thing the flush parameter actually does is: + when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it + will return Z_BUF_ERROR if it has not reached the end of the stream. + */ + +int ZEXPORT inflate(strm, flush) +z_streamp strm; +int flush; +{ + struct inflate_state FAR *state; + unsigned char FAR *next; /* next input */ + unsigned char FAR *put; /* next output */ + unsigned have, left; /* available input and output */ + unsigned long hold; /* bit buffer */ + unsigned bits; /* bits in bit buffer */ + unsigned in, out; /* save starting available input and output */ + unsigned copy; /* number of stored or match bytes to copy */ + unsigned char FAR *from; /* where to copy match bytes from */ + code here; /* current decoding table entry */ + code last; /* parent table entry */ + unsigned len; /* length to copy for repeats, bits to drop */ + int ret; /* return code */ +#ifdef GUNZIP + unsigned char hbuf[4]; /* buffer for gzip header crc calculation */ +#endif + static const unsigned short order[19] = /* permutation of code lengths */ + {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + + if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL || + (strm->next_in == Z_NULL && strm->avail_in != 0)) + return Z_STREAM_ERROR; + + state = (struct inflate_state FAR *)strm->state; + if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */ + LOAD(); + in = have; + out = left; + ret = Z_OK; + for (;;) + switch (state->mode) { + case HEAD: + if (state->wrap == 0) { + state->mode = TYPEDO; + break; + } + NEEDBITS(16); +#ifdef GUNZIP + if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */ + state->check = crc32(0L, Z_NULL, 0); + CRC2(state->check, hold); + INITBITS(); + state->mode = FLAGS; + break; + } + state->flags = 0; /* expect zlib header */ + if (state->head != Z_NULL) + state->head->done = -1; + if (!(state->wrap & 1) || /* check if zlib header allowed */ +#else + if ( +#endif + ((BITS(8) << 8) + (hold >> 8)) % 31) { + strm->msg = (char *)"incorrect header check"; + state->mode = BAD; + break; + } + if (BITS(4) != Z_DEFLATED) { + strm->msg = (char *)"unknown compression method"; + state->mode = BAD; + break; + } + DROPBITS(4); + len = BITS(4) + 8; + if (state->wbits == 0) + state->wbits = len; + else if (len > state->wbits) { + strm->msg = (char *)"invalid window size"; + state->mode = BAD; + break; + } + state->dmax = 1U << len; + Tracev((stderr, "inflate: zlib header ok\n")); + strm->adler = state->check = adler32(0L, Z_NULL, 0); + state->mode = hold & 0x200 ? DICTID : TYPE; + INITBITS(); + break; +#ifdef GUNZIP + case FLAGS: + NEEDBITS(16); + state->flags = (int)(hold); + if ((state->flags & 0xff) != Z_DEFLATED) { + strm->msg = (char *)"unknown compression method"; + state->mode = BAD; + break; + } + if (state->flags & 0xe000) { + strm->msg = (char *)"unknown header flags set"; + state->mode = BAD; + break; + } + if (state->head != Z_NULL) + state->head->text = (int)((hold >> 8) & 1); + if (state->flags & 0x0200) CRC2(state->check, hold); + INITBITS(); + state->mode = TIME; + case TIME: + NEEDBITS(32); + if (state->head != Z_NULL) + state->head->time = hold; + if (state->flags & 0x0200) CRC4(state->check, hold); + INITBITS(); + state->mode = OS; + case OS: + NEEDBITS(16); + if (state->head != Z_NULL) { + state->head->xflags = (int)(hold & 0xff); + state->head->os = (int)(hold >> 8); + } + if (state->flags & 0x0200) CRC2(state->check, hold); + INITBITS(); + state->mode = EXLEN; + case EXLEN: + if (state->flags & 0x0400) { + NEEDBITS(16); + state->length = (unsigned)(hold); + if (state->head != Z_NULL) + state->head->extra_len = (unsigned)hold; + if (state->flags & 0x0200) CRC2(state->check, hold); + INITBITS(); + } + else if (state->head != Z_NULL) + state->head->extra = Z_NULL; + state->mode = EXTRA; + case EXTRA: + if (state->flags & 0x0400) { + copy = state->length; + if (copy > have) copy = have; + if (copy) { + if (state->head != Z_NULL && + state->head->extra != Z_NULL) { + len = state->head->extra_len - state->length; + zmemcpy(state->head->extra + len, next, + len + copy > state->head->extra_max ? + state->head->extra_max - len : copy); + } + if (state->flags & 0x0200) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + state->length -= copy; + } + if (state->length) goto inf_leave; + } + state->length = 0; + state->mode = NAME; + case NAME: + if (state->flags & 0x0800) { + if (have == 0) goto inf_leave; + copy = 0; + do { + len = (unsigned)(next[copy++]); + if (state->head != Z_NULL && + state->head->name != Z_NULL && + state->length < state->head->name_max) + state->head->name[state->length++] = len; + } while (len && copy < have); + if (state->flags & 0x0200) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + if (len) goto inf_leave; + } + else if (state->head != Z_NULL) + state->head->name = Z_NULL; + state->length = 0; + state->mode = COMMENT; + case COMMENT: + if (state->flags & 0x1000) { + if (have == 0) goto inf_leave; + copy = 0; + do { + len = (unsigned)(next[copy++]); + if (state->head != Z_NULL && + state->head->comment != Z_NULL && + state->length < state->head->comm_max) + state->head->comment[state->length++] = len; + } while (len && copy < have); + if (state->flags & 0x0200) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + if (len) goto inf_leave; + } + else if (state->head != Z_NULL) + state->head->comment = Z_NULL; + state->mode = HCRC; + case HCRC: + if (state->flags & 0x0200) { + NEEDBITS(16); + if (hold != (state->check & 0xffff)) { + strm->msg = (char *)"header crc mismatch"; + state->mode = BAD; + break; + } + INITBITS(); + } + if (state->head != Z_NULL) { + state->head->hcrc = (int)((state->flags >> 9) & 1); + state->head->done = 1; + } + strm->adler = state->check = crc32(0L, Z_NULL, 0); + state->mode = TYPE; + break; +#endif + case DICTID: + NEEDBITS(32); + strm->adler = state->check = REVERSE(hold); + INITBITS(); + state->mode = DICT; + case DICT: + if (state->havedict == 0) { + RESTORE(); + return Z_NEED_DICT; + } + strm->adler = state->check = adler32(0L, Z_NULL, 0); + state->mode = TYPE; + case TYPE: + if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave; + case TYPEDO: + if (state->last) { + BYTEBITS(); + state->mode = CHECK; + break; + } + NEEDBITS(3); + state->last = BITS(1); + DROPBITS(1); + switch (BITS(2)) { + case 0: /* stored block */ + Tracev((stderr, "inflate: stored block%s\n", + state->last ? " (last)" : "")); + state->mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + Tracev((stderr, "inflate: fixed codes block%s\n", + state->last ? " (last)" : "")); + state->mode = LEN_; /* decode codes */ + if (flush == Z_TREES) { + DROPBITS(2); + goto inf_leave; + } + break; + case 2: /* dynamic block */ + Tracev((stderr, "inflate: dynamic codes block%s\n", + state->last ? " (last)" : "")); + state->mode = TABLE; + break; + case 3: + strm->msg = (char *)"invalid block type"; + state->mode = BAD; + } + DROPBITS(2); + break; + case STORED: + BYTEBITS(); /* go to byte boundary */ + NEEDBITS(32); + if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { + strm->msg = (char *)"invalid stored block lengths"; + state->mode = BAD; + break; + } + state->length = (unsigned)hold & 0xffff; + Tracev((stderr, "inflate: stored length %u\n", + state->length)); + INITBITS(); + state->mode = COPY_; + if (flush == Z_TREES) goto inf_leave; + case COPY_: + state->mode = COPY; + case COPY: + copy = state->length; + if (copy) { + if (copy > have) copy = have; + if (copy > left) copy = left; + if (copy == 0) goto inf_leave; + zmemcpy(put, next, copy); + have -= copy; + next += copy; + left -= copy; + put += copy; + state->length -= copy; + break; + } + Tracev((stderr, "inflate: stored end\n")); + state->mode = TYPE; + break; + case TABLE: + NEEDBITS(14); + state->nlen = BITS(5) + 257; + DROPBITS(5); + state->ndist = BITS(5) + 1; + DROPBITS(5); + state->ncode = BITS(4) + 4; + DROPBITS(4); +#ifndef PKZIP_BUG_WORKAROUND + if (state->nlen > 286 || state->ndist > 30) { + strm->msg = (char *)"too many length or distance symbols"; + state->mode = BAD; + break; + } +#endif + Tracev((stderr, "inflate: table sizes ok\n")); + state->have = 0; + state->mode = LENLENS; + case LENLENS: + while (state->have < state->ncode) { + NEEDBITS(3); + state->lens[order[state->have++]] = (unsigned short)BITS(3); + DROPBITS(3); + } + while (state->have < 19) + state->lens[order[state->have++]] = 0; + state->next = state->codes; + state->lencode = (code const FAR *)(state->next); + state->lenbits = 7; + ret = inflate_table(CODES, state->lens, 19, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid code lengths set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: code lengths ok\n")); + state->have = 0; + state->mode = CODELENS; + case CODELENS: + while (state->have < state->nlen + state->ndist) { + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.val < 16) { + NEEDBITS(here.bits); + DROPBITS(here.bits); + state->lens[state->have++] = here.val; + } + else { + if (here.val == 16) { + NEEDBITS(here.bits + 2); + DROPBITS(here.bits); + if (state->have == 0) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + len = state->lens[state->have - 1]; + copy = 3 + BITS(2); + DROPBITS(2); + } + else if (here.val == 17) { + NEEDBITS(here.bits + 3); + DROPBITS(here.bits); + len = 0; + copy = 3 + BITS(3); + DROPBITS(3); + } + else { + NEEDBITS(here.bits + 7); + DROPBITS(here.bits); + len = 0; + copy = 11 + BITS(7); + DROPBITS(7); + } + if (state->have + copy > state->nlen + state->ndist) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + while (copy--) + state->lens[state->have++] = (unsigned short)len; + } + } + + /* handle error breaks in while */ + if (state->mode == BAD) break; + + /* check for end-of-block code (better have one) */ + if (state->lens[256] == 0) { + strm->msg = (char *)"invalid code -- missing end-of-block"; + state->mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state->next = state->codes; + state->lencode = (code const FAR *)(state->next); + state->lenbits = 9; + ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid literal/lengths set"; + state->mode = BAD; + break; + } + state->distcode = (code const FAR *)(state->next); + state->distbits = 6; + ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, + &(state->next), &(state->distbits), state->work); + if (ret) { + strm->msg = (char *)"invalid distances set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: codes ok\n")); + state->mode = LEN_; + if (flush == Z_TREES) goto inf_leave; + case LEN_: + state->mode = LEN; + case LEN: + if (have >= 6 && left >= 258) { + RESTORE(); + inflate_fast(strm, out); + LOAD(); + if (state->mode == TYPE) + state->back = -1; + break; + } + state->back = 0; + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.op && (here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->lencode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + state->back += last.bits; + } + DROPBITS(here.bits); + state->back += here.bits; + state->length = (unsigned)here.val; + if ((int)(here.op) == 0) { + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", here.val)); + state->mode = LIT; + break; + } + if (here.op & 32) { + Tracevv((stderr, "inflate: end of block\n")); + state->back = -1; + state->mode = TYPE; + break; + } + if (here.op & 64) { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + state->extra = (unsigned)(here.op) & 15; + state->mode = LENEXT; + case LENEXT: + if (state->extra) { + NEEDBITS(state->extra); + state->length += BITS(state->extra); + DROPBITS(state->extra); + state->back += state->extra; + } + Tracevv((stderr, "inflate: length %u\n", state->length)); + state->was = state->length; + state->mode = DIST; + case DIST: + for (;;) { + here = state->distcode[BITS(state->distbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if ((here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->distcode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + state->back += last.bits; + } + DROPBITS(here.bits); + state->back += here.bits; + if (here.op & 64) { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + state->offset = (unsigned)here.val; + state->extra = (unsigned)(here.op) & 15; + state->mode = DISTEXT; + case DISTEXT: + if (state->extra) { + NEEDBITS(state->extra); + state->offset += BITS(state->extra); + DROPBITS(state->extra); + state->back += state->extra; + } +#ifdef INFLATE_STRICT + if (state->offset > state->dmax) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#endif + Tracevv((stderr, "inflate: distance %u\n", state->offset)); + state->mode = MATCH; + case MATCH: + if (left == 0) goto inf_leave; + copy = out - left; + if (state->offset > copy) { /* copy from window */ + copy = state->offset - copy; + if (copy > state->whave) { + if (state->sane) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + Trace((stderr, "inflate.c too far\n")); + copy -= state->whave; + if (copy > state->length) copy = state->length; + if (copy > left) copy = left; + left -= copy; + state->length -= copy; + do { + *put++ = 0; + } while (--copy); + if (state->length == 0) state->mode = LEN; + break; +#endif + } + if (copy > state->wnext) { + copy -= state->wnext; + from = state->window + (state->wsize - copy); + } + else + from = state->window + (state->wnext - copy); + if (copy > state->length) copy = state->length; + } + else { /* copy from output */ + from = put - state->offset; + copy = state->length; + } + if (copy > left) copy = left; + left -= copy; + state->length -= copy; + do { + *put++ = *from++; + } while (--copy); + if (state->length == 0) state->mode = LEN; + break; + case LIT: + if (left == 0) goto inf_leave; + *put++ = (unsigned char)(state->length); + left--; + state->mode = LEN; + break; + case CHECK: + if (state->wrap) { + NEEDBITS(32); + out -= left; + strm->total_out += out; + state->total += out; + if (out) + strm->adler = state->check = + UPDATE(state->check, put - out, out); + out = left; + if (( +#ifdef GUNZIP + state->flags ? hold : +#endif + REVERSE(hold)) != state->check) { + strm->msg = (char *)"incorrect data check"; + state->mode = BAD; + break; + } + INITBITS(); + Tracev((stderr, "inflate: check matches trailer\n")); + } +#ifdef GUNZIP + state->mode = LENGTH; + case LENGTH: + if (state->wrap && state->flags) { + NEEDBITS(32); + if (hold != (state->total & 0xffffffffUL)) { + strm->msg = (char *)"incorrect length check"; + state->mode = BAD; + break; + } + INITBITS(); + Tracev((stderr, "inflate: length matches trailer\n")); + } +#endif + state->mode = DONE; + case DONE: + ret = Z_STREAM_END; + goto inf_leave; + case BAD: + ret = Z_DATA_ERROR; + goto inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + default: + return Z_STREAM_ERROR; + } + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + inf_leave: + RESTORE(); + if (state->wsize || (state->mode < CHECK && out != strm->avail_out)) + if (updatewindow(strm, out)) { + state->mode = MEM; + return Z_MEM_ERROR; + } + in -= strm->avail_in; + out -= strm->avail_out; + strm->total_in += in; + strm->total_out += out; + state->total += out; + if (state->wrap && out) + strm->adler = state->check = + UPDATE(state->check, strm->next_out - out, out); + strm->data_type = state->bits + (state->last ? 64 : 0) + + (state->mode == TYPE ? 128 : 0) + + (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0); + if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK) + ret = Z_BUF_ERROR; + return ret; +} + +int ZEXPORT inflateEnd(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (state->window != Z_NULL) ZFREE(strm, state->window); + ZFREE(strm, strm->state); + strm->state = Z_NULL; + Tracev((stderr, "inflate: end\n")); + return Z_OK; +} + +int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength) +z_streamp strm; +const Bytef *dictionary; +uInt dictLength; +{ + struct inflate_state FAR *state; + unsigned long id; + + /* check state */ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (state->wrap != 0 && state->mode != DICT) + return Z_STREAM_ERROR; + + /* check for correct dictionary id */ + if (state->mode == DICT) { + id = adler32(0L, Z_NULL, 0); + id = adler32(id, dictionary, dictLength); + if (id != state->check) + return Z_DATA_ERROR; + } + + /* copy dictionary to window */ + if (updatewindow(strm, strm->avail_out)) { + state->mode = MEM; + return Z_MEM_ERROR; + } + if (dictLength > state->wsize) { + zmemcpy(state->window, dictionary + dictLength - state->wsize, + state->wsize); + state->whave = state->wsize; + } + else { + zmemcpy(state->window + state->wsize - dictLength, dictionary, + dictLength); + state->whave = dictLength; + } + state->havedict = 1; + Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK; +} + +int ZEXPORT inflateGetHeader(strm, head) +z_streamp strm; +gz_headerp head; +{ + struct inflate_state FAR *state; + + /* check state */ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if ((state->wrap & 2) == 0) return Z_STREAM_ERROR; + + /* save header structure */ + state->head = head; + head->done = 0; + return Z_OK; +} + +/* + Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found + or when out of input. When called, *have is the number of pattern bytes + found in order so far, in 0..3. On return *have is updated to the new + state. If on return *have equals four, then the pattern was found and the + return value is how many bytes were read including the last byte of the + pattern. If *have is less than four, then the pattern has not been found + yet and the return value is len. In the latter case, syncsearch() can be + called again with more data and the *have state. *have is initialized to + zero for the first call. + */ +local unsigned syncsearch(have, buf, len) +unsigned FAR *have; +unsigned char FAR *buf; +unsigned len; +{ + unsigned got; + unsigned next; + + got = *have; + next = 0; + while (next < len && got < 4) { + if ((int)(buf[next]) == (got < 2 ? 0 : 0xff)) + got++; + else if (buf[next]) + got = 0; + else + got = 4 - got; + next++; + } + *have = got; + return next; +} + +int ZEXPORT inflateSync(strm) +z_streamp strm; +{ + unsigned len; /* number of bytes to look at or looked at */ + unsigned long in, out; /* temporary to save total_in and total_out */ + unsigned char buf[4]; /* to restore bit buffer to byte string */ + struct inflate_state FAR *state; + + /* check parameters */ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR; + + /* if first time, start search in bit buffer */ + if (state->mode != SYNC) { + state->mode = SYNC; + state->hold <<= state->bits & 7; + state->bits -= state->bits & 7; + len = 0; + while (state->bits >= 8) { + buf[len++] = (unsigned char)(state->hold); + state->hold >>= 8; + state->bits -= 8; + } + state->have = 0; + syncsearch(&(state->have), buf, len); + } + + /* search available input */ + len = syncsearch(&(state->have), strm->next_in, strm->avail_in); + strm->avail_in -= len; + strm->next_in += len; + strm->total_in += len; + + /* return no joy or set up to restart inflate() on a new block */ + if (state->have != 4) return Z_DATA_ERROR; + in = strm->total_in; out = strm->total_out; + inflateReset(strm); + strm->total_in = in; strm->total_out = out; + state->mode = TYPE; + return Z_OK; +} + +/* + Returns true if inflate is currently at the end of a block generated by + Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP + implementation to provide an additional safety check. PPP uses + Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored + block. When decompressing, PPP checks that at the end of input packet, + inflate is waiting for these length bytes. + */ +int ZEXPORT inflateSyncPoint(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + return state->mode == STORED && state->bits == 0; +} + +int ZEXPORT inflateCopy(dest, source) +z_streamp dest; +z_streamp source; +{ + struct inflate_state FAR *state; + struct inflate_state FAR *copy; + unsigned char FAR *window; + unsigned wsize; + + /* check input */ + if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL || + source->zalloc == (alloc_func)0 || source->zfree == (free_func)0) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)source->state; + + /* allocate space */ + copy = (struct inflate_state FAR *) + ZALLOC(source, 1, sizeof(struct inflate_state)); + if (copy == Z_NULL) return Z_MEM_ERROR; + window = Z_NULL; + if (state->window != Z_NULL) { + window = (unsigned char FAR *) + ZALLOC(source, 1U << state->wbits, sizeof(unsigned char)); + if (window == Z_NULL) { + ZFREE(source, copy); + return Z_MEM_ERROR; + } + } + + /* copy state */ + zmemcpy(dest, source, sizeof(z_stream)); + zmemcpy(copy, state, sizeof(struct inflate_state)); + if (state->lencode >= state->codes && + state->lencode <= state->codes + ENOUGH - 1) { + copy->lencode = copy->codes + (state->lencode - state->codes); + copy->distcode = copy->codes + (state->distcode - state->codes); + } + copy->next = copy->codes + (state->next - state->codes); + if (window != Z_NULL) { + wsize = 1U << state->wbits; + zmemcpy(window, state->window, wsize); + } + copy->window = window; + dest->state = (struct internal_state FAR *)copy; + return Z_OK; +} + +int ZEXPORT inflateUndermine(strm, subvert) +z_streamp strm; +int subvert; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + state->sane = !subvert; +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + return Z_OK; +#else + state->sane = 1; + return Z_DATA_ERROR; +#endif +} + +long ZEXPORT inflateMark(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return -1L << 16; + state = (struct inflate_state FAR *)strm->state; + return ((long)(state->back) << 16) + + (state->mode == COPY ? state->length : + (state->mode == MATCH ? state->was - state->length : 0)); +} diff --git a/dep/zlib/inflate.h b/dep/zlib/inflate.h new file mode 100644 index 00000000000..95f4986d400 --- /dev/null +++ b/dep/zlib/inflate.h @@ -0,0 +1,122 @@ +/* inflate.h -- internal inflate state definition + * Copyright (C) 1995-2009 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* define NO_GZIP when compiling if you want to disable gzip header and + trailer decoding by inflate(). NO_GZIP would be used to avoid linking in + the crc code when it is not needed. For shared libraries, gzip decoding + should be left enabled. */ +#ifndef NO_GZIP +# define GUNZIP +#endif + +/* Possible inflate modes between inflate() calls */ +typedef enum { + HEAD, /* i: waiting for magic header */ + FLAGS, /* i: waiting for method and flags (gzip) */ + TIME, /* i: waiting for modification time (gzip) */ + OS, /* i: waiting for extra flags and operating system (gzip) */ + EXLEN, /* i: waiting for extra length (gzip) */ + EXTRA, /* i: waiting for extra bytes (gzip) */ + NAME, /* i: waiting for end of file name (gzip) */ + COMMENT, /* i: waiting for end of comment (gzip) */ + HCRC, /* i: waiting for header crc (gzip) */ + DICTID, /* i: waiting for dictionary check value */ + DICT, /* waiting for inflateSetDictionary() call */ + TYPE, /* i: waiting for type bits, including last-flag bit */ + TYPEDO, /* i: same, but skip check to exit inflate on new block */ + STORED, /* i: waiting for stored size (length and complement) */ + COPY_, /* i/o: same as COPY below, but only first time in */ + COPY, /* i/o: waiting for input or output to copy stored block */ + TABLE, /* i: waiting for dynamic block table lengths */ + LENLENS, /* i: waiting for code length code lengths */ + CODELENS, /* i: waiting for length/lit and distance code lengths */ + LEN_, /* i: same as LEN below, but only first time in */ + LEN, /* i: waiting for length/lit/eob code */ + LENEXT, /* i: waiting for length extra bits */ + DIST, /* i: waiting for distance code */ + DISTEXT, /* i: waiting for distance extra bits */ + MATCH, /* o: waiting for output space to copy string */ + LIT, /* o: waiting for output space to write literal */ + CHECK, /* i: waiting for 32-bit check value */ + LENGTH, /* i: waiting for 32-bit length (gzip) */ + DONE, /* finished check, done -- remain here until reset */ + BAD, /* got a data error -- remain here until reset */ + MEM, /* got an inflate() memory error -- remain here until reset */ + SYNC /* looking for synchronization bytes to restart inflate() */ +} inflate_mode; + +/* + State transitions between above modes - + + (most modes can go to BAD or MEM on error -- not shown for clarity) + + Process header: + HEAD -> (gzip) or (zlib) or (raw) + (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME -> COMMENT -> + HCRC -> TYPE + (zlib) -> DICTID or TYPE + DICTID -> DICT -> TYPE + (raw) -> TYPEDO + Read deflate blocks: + TYPE -> TYPEDO -> STORED or TABLE or LEN_ or CHECK + STORED -> COPY_ -> COPY -> TYPE + TABLE -> LENLENS -> CODELENS -> LEN_ + LEN_ -> LEN + Read deflate codes in fixed or dynamic block: + LEN -> LENEXT or LIT or TYPE + LENEXT -> DIST -> DISTEXT -> MATCH -> LEN + LIT -> LEN + Process trailer: + CHECK -> LENGTH -> DONE + */ + +/* state maintained between inflate() calls. Approximately 10K bytes. */ +struct inflate_state { + inflate_mode mode; /* current inflate mode */ + int last; /* true if processing last block */ + int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ + int havedict; /* true if dictionary provided */ + int flags; /* gzip header method and flags (0 if zlib) */ + unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */ + unsigned long check; /* protected copy of check value */ + unsigned long total; /* protected copy of output count */ + gz_headerp head; /* where to save gzip header information */ + /* sliding window */ + unsigned wbits; /* log base 2 of requested window size */ + unsigned wsize; /* window size or zero if not using window */ + unsigned whave; /* valid bytes in the window */ + unsigned wnext; /* window write index */ + unsigned char FAR *window; /* allocated sliding window, if needed */ + /* bit accumulator */ + unsigned long hold; /* input bit accumulator */ + unsigned bits; /* number of bits in "in" */ + /* for string and stored block copying */ + unsigned length; /* literal or length of data to copy */ + unsigned offset; /* distance back to copy string from */ + /* for table and code decoding */ + unsigned extra; /* extra bits needed */ + /* fixed and dynamic code tables */ + code const FAR *lencode; /* starting table for length/literal codes */ + code const FAR *distcode; /* starting table for distance codes */ + unsigned lenbits; /* index bits for lencode */ + unsigned distbits; /* index bits for distcode */ + /* dynamic table building */ + unsigned ncode; /* number of code length code lengths */ + unsigned nlen; /* number of length code lengths */ + unsigned ndist; /* number of distance code lengths */ + unsigned have; /* number of code lengths in lens[] */ + code FAR *next; /* next available space in codes[] */ + unsigned short lens[320]; /* temporary storage for code lengths */ + unsigned short work[288]; /* work area for code table building */ + code codes[ENOUGH]; /* space for code tables */ + int sane; /* if false, allow invalid distance too far */ + int back; /* bits back of last unprocessed length/lit */ + unsigned was; /* initial length of match */ +}; diff --git a/dep/zlib/inftrees.c b/dep/zlib/inftrees.c new file mode 100644 index 00000000000..11e9c52accb --- /dev/null +++ b/dep/zlib/inftrees.c @@ -0,0 +1,330 @@ +/* inftrees.c -- generate Huffman trees for efficient decoding + * Copyright (C) 1995-2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "inftrees.h" + +#define MAXBITS 15 + +const char inflate_copyright[] = + " inflate 1.2.5 Copyright 1995-2010 Mark Adler "; +/* + If you use the zlib library in a product, an acknowledgment is welcome + in the documentation of your product. If for some reason you cannot + include such an acknowledgment, I would appreciate that you keep this + copyright string in the executable of your product. + */ + +/* + Build a set of tables to decode the provided canonical Huffman code. + The code lengths are lens[0..codes-1]. The result starts at *table, + whose indices are 0..2^bits-1. work is a writable array of at least + lens shorts, which is used as a work area. type is the type of code + to be generated, CODES, LENS, or DISTS. On return, zero is success, + -1 is an invalid code, and +1 means that ENOUGH isn't enough. table + on return points to the next available entry's address. bits is the + requested root table index bits, and on return it is the actual root + table index bits. It will differ if the request is greater than the + longest code or if it is less than the shortest code. + */ +int ZLIB_INTERNAL inflate_table(type, lens, codes, table, bits, work) +codetype type; +unsigned short FAR *lens; +unsigned codes; +code FAR * FAR *table; +unsigned FAR *bits; +unsigned short FAR *work; +{ + unsigned len; /* a code's length in bits */ + unsigned sym; /* index of code symbols */ + unsigned min, max; /* minimum and maximum code lengths */ + unsigned root; /* number of index bits for root table */ + unsigned curr; /* number of index bits for current table */ + unsigned drop; /* code bits to drop for sub-table */ + int left; /* number of prefix codes available */ + unsigned used; /* code entries in table used */ + unsigned huff; /* Huffman code */ + unsigned incr; /* for incrementing code, index */ + unsigned fill; /* index for replicating entries */ + unsigned low; /* low bits for current root entry */ + unsigned mask; /* mask for low root bits */ + code here; /* table entry for duplication */ + code FAR *next; /* next available space in table */ + const unsigned short FAR *base; /* base value table to use */ + const unsigned short FAR *extra; /* extra bits table to use */ + int end; /* use base and extra for symbol > end */ + unsigned short count[MAXBITS+1]; /* number of codes of each length */ + unsigned short offs[MAXBITS+1]; /* offsets in table for each length */ + static const unsigned short lbase[31] = { /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; + static const unsigned short lext[31] = { /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 73, 195}; + static const unsigned short dbase[32] = { /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0}; + static const unsigned short dext[32] = { /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64}; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) + count[len] = 0; + for (sym = 0; sym < codes; sym++) + count[lens[sym]]++; + + /* bound code lengths, force root to be within code lengths */ + root = *bits; + for (max = MAXBITS; max >= 1; max--) + if (count[max] != 0) break; + if (root > max) root = max; + if (max == 0) { /* no symbols to code at all */ + here.op = (unsigned char)64; /* invalid code marker */ + here.bits = (unsigned char)1; + here.val = (unsigned short)0; + *(*table)++ = here; /* make a table to force an error */ + *(*table)++ = here; + *bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) + if (count[min] != 0) break; + if (root < min) root = min; + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) return -1; /* over-subscribed */ + } + if (left > 0 && (type == CODES || max != 1)) + return -1; /* incomplete set */ + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) + offs[len + 1] = offs[len] + count[len]; + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) + if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym; + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + switch (type) { + case CODES: + base = extra = work; /* dummy value--not used */ + end = 19; + break; + case LENS: + base = lbase; + base -= 257; + extra = lext; + extra -= 257; + end = 256; + break; + default: /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } + + /* initialize state for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = *table; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = (unsigned)(-1); /* trigger new sub-table when len > root */ + used = 1U << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type == LENS && used >= ENOUGH_LENS) || + (type == DISTS && used >= ENOUGH_DISTS)) + return 1; + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + here.bits = (unsigned char)(len - drop); + if ((int)(work[sym]) < end) { + here.op = (unsigned char)0; + here.val = work[sym]; + } + else if ((int)(work[sym]) > end) { + here.op = (unsigned char)(extra[work[sym]]); + here.val = base[work[sym]]; + } + else { + here.op = (unsigned char)(32 + 64); /* end of block */ + here.val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1U << (len - drop); + fill = 1U << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + next[(huff >> drop) + fill] = here; + } while (fill != 0); + + /* backwards increment the len-bit code huff */ + incr = 1U << (len - 1); + while (huff & incr) + incr >>= 1; + if (incr != 0) { + huff &= incr - 1; + huff += incr; + } + else + huff = 0; + + /* go to next symbol, update count, len */ + sym++; + if (--(count[len]) == 0) { + if (len == max) break; + len = lens[work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) != low) { + /* if first time, transition to sub-tables */ + if (drop == 0) + drop = root; + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = (int)(1 << curr); + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) break; + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1U << curr; + if ((type == LENS && used >= ENOUGH_LENS) || + (type == DISTS && used >= ENOUGH_DISTS)) + return 1; + + /* point entry in root table to sub-table */ + low = huff & mask; + (*table)[low].op = (unsigned char)curr; + (*table)[low].bits = (unsigned char)root; + (*table)[low].val = (unsigned short)(next - *table); + } + } + + /* + Fill in rest of table for incomplete codes. This loop is similar to the + loop above in incrementing huff for table indices. It is assumed that + len is equal to curr + drop, so there is no loop needed to increment + through high index bits. When the current sub-table is filled, the loop + drops back to the root table to fill in any remaining entries there. + */ + here.op = (unsigned char)64; /* invalid code marker */ + here.bits = (unsigned char)(len - drop); + here.val = (unsigned short)0; + while (huff != 0) { + /* when done with sub-table, drop back to root table */ + if (drop != 0 && (huff & mask) != low) { + drop = 0; + len = root; + next = *table; + here.bits = (unsigned char)len; + } + + /* put invalid code marker in table */ + next[huff >> drop] = here; + + /* backwards increment the len-bit code huff */ + incr = 1U << (len - 1); + while (huff & incr) + incr >>= 1; + if (incr != 0) { + huff &= incr - 1; + huff += incr; + } + else + huff = 0; + } + + /* set return parameters */ + *table += used; + *bits = root; + return 0; +} diff --git a/dep/zlib/inftrees.h b/dep/zlib/inftrees.h new file mode 100644 index 00000000000..baa53a0b1a1 --- /dev/null +++ b/dep/zlib/inftrees.h @@ -0,0 +1,62 @@ +/* inftrees.h -- header to use inftrees.c + * Copyright (C) 1995-2005, 2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* Structure for decoding tables. Each entry provides either the + information needed to do the operation requested by the code that + indexed that table entry, or it provides a pointer to another + table that indexes more bits of the code. op indicates whether + the entry is a pointer to another table, a literal, a length or + distance, an end-of-block, or an invalid code. For a table + pointer, the low four bits of op is the number of index bits of + that table. For a length or distance, the low four bits of op + is the number of extra bits to get after the code. bits is + the number of bits in this code or part of the code to drop off + of the bit buffer. val is the actual byte to output in the case + of a literal, the base length or distance, or the offset from + the current table to the next table. Each entry is four bytes. */ +typedef struct { + unsigned char op; /* operation, extra bits, table bits */ + unsigned char bits; /* bits in this part of the code */ + unsigned short val; /* offset in table or code value */ +} code; + +/* op values as set by inflate_table(): + 00000000 - literal + 0000tttt - table link, tttt != 0 is the number of table index bits + 0001eeee - length or distance, eeee is the number of extra bits + 01100000 - end of block + 01000000 - invalid code + */ + +/* Maximum size of the dynamic table. The maximum number of code structures is + 1444, which is the sum of 852 for literal/length codes and 592 for distance + codes. These values were found by exhaustive searches using the program + examples/enough.c found in the zlib distribtution. The arguments to that + program are the number of symbols, the initial root table size, and the + maximum bit length of a code. "enough 286 9 15" for literal/length codes + returns returns 852, and "enough 30 6 15" for distance codes returns 592. + The initial root table size (9 or 6) is found in the fifth argument of the + inflate_table() calls in inflate.c and infback.c. If the root table size is + changed, then these maximum sizes would be need to be recalculated and + updated. */ +#define ENOUGH_LENS 852 +#define ENOUGH_DISTS 592 +#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS) + +/* Type of code to build for inflate_table() */ +typedef enum { + CODES, + LENS, + DISTS +} codetype; + +int ZLIB_INTERNAL inflate_table OF((codetype type, unsigned short FAR *lens, + unsigned codes, code FAR * FAR *table, + unsigned FAR *bits, unsigned short FAR *work)); diff --git a/dep/zlib/minigzip.c b/dep/zlib/minigzip.c new file mode 100644 index 00000000000..9825ccc3a71 --- /dev/null +++ b/dep/zlib/minigzip.c @@ -0,0 +1,440 @@ +/* minigzip.c -- simulate gzip using the zlib compression library + * Copyright (C) 1995-2006, 2010 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * minigzip is a minimal implementation of the gzip utility. This is + * only an example of using zlib and isn't meant to replace the + * full-featured gzip. No attempt is made to deal with file systems + * limiting names to 14 or 8+3 characters, etc... Error checking is + * very limited. So use minigzip only for testing; use gzip for the + * real thing. On MSDOS, use only on file names without extension + * or in pipe mode. + */ + +/* @(#) $Id$ */ + +#include "zlib.h" +#include + +#ifdef STDC +# include +# include +#endif + +#ifdef USE_MMAP +# include +# include +# include +#endif + +#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__) +# include +# include +# ifdef UNDER_CE +# include +# endif +# define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY) +#else +# define SET_BINARY_MODE(file) +#endif + +#ifdef VMS +# define unlink delete +# define GZ_SUFFIX "-gz" +#endif +#ifdef RISCOS +# define unlink remove +# define GZ_SUFFIX "-gz" +# define fileno(file) file->__file +#endif +#if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os +# include /* for fileno */ +#endif + +#if !defined(Z_HAVE_UNISTD_H) && !defined(_LARGEFILE64_SOURCE) +#ifndef WIN32 /* unlink already in stdio.h for WIN32 */ + extern int unlink OF((const char *)); +#endif +#endif + +#if defined(UNDER_CE) +# include +# define perror(s) pwinerror(s) + +/* Map the Windows error number in ERROR to a locale-dependent error + message string and return a pointer to it. Typically, the values + for ERROR come from GetLastError. + + The string pointed to shall not be modified by the application, + but may be overwritten by a subsequent call to strwinerror + + The strwinerror function does not change the current setting + of GetLastError. */ + +static char *strwinerror (error) + DWORD error; +{ + static char buf[1024]; + + wchar_t *msgbuf; + DWORD lasterr = GetLastError(); + DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM + | FORMAT_MESSAGE_ALLOCATE_BUFFER, + NULL, + error, + 0, /* Default language */ + (LPVOID)&msgbuf, + 0, + NULL); + if (chars != 0) { + /* If there is an \r\n appended, zap it. */ + if (chars >= 2 + && msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') { + chars -= 2; + msgbuf[chars] = 0; + } + + if (chars > sizeof (buf) - 1) { + chars = sizeof (buf) - 1; + msgbuf[chars] = 0; + } + + wcstombs(buf, msgbuf, chars + 1); + LocalFree(msgbuf); + } + else { + sprintf(buf, "unknown win32 error (%ld)", error); + } + + SetLastError(lasterr); + return buf; +} + +static void pwinerror (s) + const char *s; +{ + if (s && *s) + fprintf(stderr, "%s: %s\n", s, strwinerror(GetLastError ())); + else + fprintf(stderr, "%s\n", strwinerror(GetLastError ())); +} + +#endif /* UNDER_CE */ + +#ifndef GZ_SUFFIX +# define GZ_SUFFIX ".gz" +#endif +#define SUFFIX_LEN (sizeof(GZ_SUFFIX)-1) + +#define BUFLEN 16384 +#define MAX_NAME_LEN 1024 + +#ifdef MAXSEG_64K +# define local static + /* Needed for systems with limitation on stack size. */ +#else +# define local +#endif + +char *prog; + +void error OF((const char *msg)); +void gz_compress OF((FILE *in, gzFile out)); +#ifdef USE_MMAP +int gz_compress_mmap OF((FILE *in, gzFile out)); +#endif +void gz_uncompress OF((gzFile in, FILE *out)); +void file_compress OF((char *file, char *mode)); +void file_uncompress OF((char *file)); +int main OF((int argc, char *argv[])); + +/* =========================================================================== + * Display error message and exit + */ +void error(msg) + const char *msg; +{ + fprintf(stderr, "%s: %s\n", prog, msg); + exit(1); +} + +/* =========================================================================== + * Compress input to output then close both files. + */ + +void gz_compress(in, out) + FILE *in; + gzFile out; +{ + local char buf[BUFLEN]; + int len; + int err; + +#ifdef USE_MMAP + /* Try first compressing with mmap. If mmap fails (minigzip used in a + * pipe), use the normal fread loop. + */ + if (gz_compress_mmap(in, out) == Z_OK) return; +#endif + for (;;) { + len = (int)fread(buf, 1, sizeof(buf), in); + if (ferror(in)) { + perror("fread"); + exit(1); + } + if (len == 0) break; + + if (gzwrite(out, buf, (unsigned)len) != len) error(gzerror(out, &err)); + } + fclose(in); + if (gzclose(out) != Z_OK) error("failed gzclose"); +} + +#ifdef USE_MMAP /* MMAP version, Miguel Albrecht */ + +/* Try compressing the input file at once using mmap. Return Z_OK if + * if success, Z_ERRNO otherwise. + */ +int gz_compress_mmap(in, out) + FILE *in; + gzFile out; +{ + int len; + int err; + int ifd = fileno(in); + caddr_t buf; /* mmap'ed buffer for the entire input file */ + off_t buf_len; /* length of the input file */ + struct stat sb; + + /* Determine the size of the file, needed for mmap: */ + if (fstat(ifd, &sb) < 0) return Z_ERRNO; + buf_len = sb.st_size; + if (buf_len <= 0) return Z_ERRNO; + + /* Now do the actual mmap: */ + buf = mmap((caddr_t) 0, buf_len, PROT_READ, MAP_SHARED, ifd, (off_t)0); + if (buf == (caddr_t)(-1)) return Z_ERRNO; + + /* Compress the whole file at once: */ + len = gzwrite(out, (char *)buf, (unsigned)buf_len); + + if (len != (int)buf_len) error(gzerror(out, &err)); + + munmap(buf, buf_len); + fclose(in); + if (gzclose(out) != Z_OK) error("failed gzclose"); + return Z_OK; +} +#endif /* USE_MMAP */ + +/* =========================================================================== + * Uncompress input to output then close both files. + */ +void gz_uncompress(in, out) + gzFile in; + FILE *out; +{ + local char buf[BUFLEN]; + int len; + int err; + + for (;;) { + len = gzread(in, buf, sizeof(buf)); + if (len < 0) error (gzerror(in, &err)); + if (len == 0) break; + + if ((int)fwrite(buf, 1, (unsigned)len, out) != len) { + error("failed fwrite"); + } + } + if (fclose(out)) error("failed fclose"); + + if (gzclose(in) != Z_OK) error("failed gzclose"); +} + + +/* =========================================================================== + * Compress the given file: create a corresponding .gz file and remove the + * original. + */ +void file_compress(file, mode) + char *file; + char *mode; +{ + local char outfile[MAX_NAME_LEN]; + FILE *in; + gzFile out; + + if (strlen(file) + strlen(GZ_SUFFIX) >= sizeof(outfile)) { + fprintf(stderr, "%s: filename too long\n", prog); + exit(1); + } + + strcpy(outfile, file); + strcat(outfile, GZ_SUFFIX); + + in = fopen(file, "rb"); + if (in == NULL) { + perror(file); + exit(1); + } + out = gzopen(outfile, mode); + if (out == NULL) { + fprintf(stderr, "%s: can't gzopen %s\n", prog, outfile); + exit(1); + } + gz_compress(in, out); + + unlink(file); +} + + +/* =========================================================================== + * Uncompress the given file and remove the original. + */ +void file_uncompress(file) + char *file; +{ + local char buf[MAX_NAME_LEN]; + char *infile, *outfile; + FILE *out; + gzFile in; + size_t len = strlen(file); + + if (len + strlen(GZ_SUFFIX) >= sizeof(buf)) { + fprintf(stderr, "%s: filename too long\n", prog); + exit(1); + } + + strcpy(buf, file); + + if (len > SUFFIX_LEN && strcmp(file+len-SUFFIX_LEN, GZ_SUFFIX) == 0) { + infile = file; + outfile = buf; + outfile[len-3] = '\0'; + } else { + outfile = file; + infile = buf; + strcat(infile, GZ_SUFFIX); + } + in = gzopen(infile, "rb"); + if (in == NULL) { + fprintf(stderr, "%s: can't gzopen %s\n", prog, infile); + exit(1); + } + out = fopen(outfile, "wb"); + if (out == NULL) { + perror(file); + exit(1); + } + + gz_uncompress(in, out); + + unlink(infile); +} + + +/* =========================================================================== + * Usage: minigzip [-c] [-d] [-f] [-h] [-r] [-1 to -9] [files...] + * -c : write to standard output + * -d : decompress + * -f : compress with Z_FILTERED + * -h : compress with Z_HUFFMAN_ONLY + * -r : compress with Z_RLE + * -1 to -9 : compression level + */ + +int main(argc, argv) + int argc; + char *argv[]; +{ + int copyout = 0; + int uncompr = 0; + gzFile file; + char *bname, outmode[20]; + + strcpy(outmode, "wb6 "); + + prog = argv[0]; + bname = strrchr(argv[0], '/'); + if (bname) + bname++; + else + bname = argv[0]; + argc--, argv++; + + if (!strcmp(bname, "gunzip")) + uncompr = 1; + else if (!strcmp(bname, "zcat")) + copyout = uncompr = 1; + + while (argc > 0) { + if (strcmp(*argv, "-c") == 0) + copyout = 1; + else if (strcmp(*argv, "-d") == 0) + uncompr = 1; + else if (strcmp(*argv, "-f") == 0) + outmode[3] = 'f'; + else if (strcmp(*argv, "-h") == 0) + outmode[3] = 'h'; + else if (strcmp(*argv, "-r") == 0) + outmode[3] = 'R'; + else if ((*argv)[0] == '-' && (*argv)[1] >= '1' && (*argv)[1] <= '9' && + (*argv)[2] == 0) + outmode[2] = (*argv)[1]; + else + break; + argc--, argv++; + } + if (outmode[3] == ' ') + outmode[3] = 0; + if (argc == 0) { + SET_BINARY_MODE(stdin); + SET_BINARY_MODE(stdout); + if (uncompr) { + file = gzdopen(fileno(stdin), "rb"); + if (file == NULL) error("can't gzdopen stdin"); + gz_uncompress(file, stdout); + } else { + file = gzdopen(fileno(stdout), outmode); + if (file == NULL) error("can't gzdopen stdout"); + gz_compress(stdin, file); + } + } else { + if (copyout) { + SET_BINARY_MODE(stdout); + } + do { + if (uncompr) { + if (copyout) { + file = gzopen(*argv, "rb"); + if (file == NULL) + fprintf(stderr, "%s: can't gzopen %s\n", prog, *argv); + else + gz_uncompress(file, stdout); + } else { + file_uncompress(*argv); + } + } else { + if (copyout) { + FILE * in = fopen(*argv, "rb"); + + if (in == NULL) { + perror(*argv); + } else { + file = gzdopen(fileno(stdout), outmode); + if (file == NULL) error("can't gzdopen stdout"); + + gz_compress(in, file); + } + + } else { + file_compress(*argv, outmode); + } + } + } while (argv++, --argc); + } + return 0; +} diff --git a/dep/zlib/trees.c b/dep/zlib/trees.c new file mode 100644 index 00000000000..56e9bb1c115 --- /dev/null +++ b/dep/zlib/trees.c @@ -0,0 +1,1244 @@ +/* trees.c -- output deflated data using Huffman coding + * Copyright (C) 1995-2010 Jean-loup Gailly + * detect_data_type() function provided freely by Cosmin Truta, 2006 + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * ALGORITHM + * + * The "deflation" process uses several Huffman trees. The more + * common source values are represented by shorter bit sequences. + * + * Each code tree is stored in a compressed form which is itself + * a Huffman encoding of the lengths of all the code strings (in + * ascending order by source values). The actual code strings are + * reconstructed from the lengths in the inflate process, as described + * in the deflate specification. + * + * REFERENCES + * + * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification". + * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc + * + * Storer, James A. + * Data Compression: Methods and Theory, pp. 49-50. + * Computer Science Press, 1988. ISBN 0-7167-8156-5. + * + * Sedgewick, R. + * Algorithms, p290. + * Addison-Wesley, 1983. ISBN 0-201-06672-6. + */ + +/* @(#) $Id$ */ + +/* #define GEN_TREES_H */ + +#include "deflate.h" + +#ifdef DEBUG +# include +#endif + +/* =========================================================================== + * Constants + */ + +#define MAX_BL_BITS 7 +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +#define END_BLOCK 256 +/* end of block literal code */ + +#define REP_3_6 16 +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +#define REPZ_3_10 17 +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +#define REPZ_11_138 18 +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */ + = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; + +local const int extra_dbits[D_CODES] /* extra bits for each distance code */ + = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; + +local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */ + = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; + +local const uch bl_order[BL_CODES] + = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +#define Buf_size (8 * 2*sizeof(char)) +/* Number of bits used within bi_buf. (bi_buf might be implemented on + * more than 16 bits on some systems.) + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +#define DIST_CODE_LEN 512 /* see definition of array dist_code below */ + +#if defined(GEN_TREES_H) || !defined(STDC) +/* non ANSI compilers may not accept trees.h */ + +local ct_data static_ltree[L_CODES+2]; +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +local ct_data static_dtree[D_CODES]; +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +uch _dist_code[DIST_CODE_LEN]; +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +uch _length_code[MAX_MATCH-MIN_MATCH+1]; +/* length code for each normalized match length (0 == MIN_MATCH) */ + +local int base_length[LENGTH_CODES]; +/* First normalized length for each code (0 = MIN_MATCH) */ + +local int base_dist[D_CODES]; +/* First normalized distance for each code (0 = distance of 1) */ + +#else +# include "trees.h" +#endif /* GEN_TREES_H */ + +struct static_tree_desc_s { + const ct_data *static_tree; /* static tree or NULL */ + const intf *extra_bits; /* extra bits for each code or NULL */ + int extra_base; /* base index for extra_bits */ + int elems; /* max number of elements in the tree */ + int max_length; /* max bit length for the codes */ +}; + +local static_tree_desc static_l_desc = +{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; + +local static_tree_desc static_d_desc = +{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; + +local static_tree_desc static_bl_desc = +{(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; + +/* =========================================================================== + * Local (static) routines in this file. + */ + +local void tr_static_init OF((void)); +local void init_block OF((deflate_state *s)); +local void pqdownheap OF((deflate_state *s, ct_data *tree, int k)); +local void gen_bitlen OF((deflate_state *s, tree_desc *desc)); +local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count)); +local void build_tree OF((deflate_state *s, tree_desc *desc)); +local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code)); +local void send_tree OF((deflate_state *s, ct_data *tree, int max_code)); +local int build_bl_tree OF((deflate_state *s)); +local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes, + int blcodes)); +local void compress_block OF((deflate_state *s, ct_data *ltree, + ct_data *dtree)); +local int detect_data_type OF((deflate_state *s)); +local unsigned bi_reverse OF((unsigned value, int length)); +local void bi_windup OF((deflate_state *s)); +local void bi_flush OF((deflate_state *s)); +local void copy_block OF((deflate_state *s, charf *buf, unsigned len, + int header)); + +#ifdef GEN_TREES_H +local void gen_trees_header OF((void)); +#endif + +#ifndef DEBUG +# define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len) + /* Send a code of the given tree. c and tree must not have side effects */ + +#else /* DEBUG */ +# define send_code(s, c, tree) \ + { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \ + send_bits(s, tree[c].Code, tree[c].Len); } +#endif + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +#define put_short(s, w) { \ + put_byte(s, (uch)((w) & 0xff)); \ + put_byte(s, (uch)((ush)(w) >> 8)); \ +} + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +#ifdef DEBUG +local void send_bits OF((deflate_state *s, int value, int length)); + +local void send_bits(s, value, length) + deflate_state *s; + int value; /* value to send */ + int length; /* number of bits */ +{ + Tracevv((stderr," l %2d v %4x ", length, value)); + Assert(length > 0 && length <= 15, "invalid length"); + s->bits_sent += (ulg)length; + + /* If not enough room in bi_buf, use (valid) bits from bi_buf and + * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid)) + * unused bits in value. + */ + if (s->bi_valid > (int)Buf_size - length) { + s->bi_buf |= (ush)value << s->bi_valid; + put_short(s, s->bi_buf); + s->bi_buf = (ush)value >> (Buf_size - s->bi_valid); + s->bi_valid += length - Buf_size; + } else { + s->bi_buf |= (ush)value << s->bi_valid; + s->bi_valid += length; + } +} +#else /* !DEBUG */ + +#define send_bits(s, value, length) \ +{ int len = length;\ + if (s->bi_valid > (int)Buf_size - len) {\ + int val = value;\ + s->bi_buf |= (ush)val << s->bi_valid;\ + put_short(s, s->bi_buf);\ + s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\ + s->bi_valid += len - Buf_size;\ + } else {\ + s->bi_buf |= (ush)(value) << s->bi_valid;\ + s->bi_valid += len;\ + }\ +} +#endif /* DEBUG */ + + +/* the arguments must not have side effects */ + +/* =========================================================================== + * Initialize the various 'constant' tables. + */ +local void tr_static_init() +{ +#if defined(GEN_TREES_H) || !defined(STDC) + static int static_init_done = 0; + int n; /* iterates over tree elements */ + int bits; /* bit counter */ + int length; /* length value */ + int code; /* code value */ + int dist; /* distance index */ + ush bl_count[MAX_BITS+1]; + /* number of codes at each bit length for an optimal tree */ + + if (static_init_done) return; + + /* For some embedded targets, global variables are not initialized: */ +#ifdef NO_INIT_GLOBAL_POINTERS + static_l_desc.static_tree = static_ltree; + static_l_desc.extra_bits = extra_lbits; + static_d_desc.static_tree = static_dtree; + static_d_desc.extra_bits = extra_dbits; + static_bl_desc.extra_bits = extra_blbits; +#endif + + /* Initialize the mapping length (0..255) -> length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES-1; code++) { + base_length[code] = length; + for (n = 0; n < (1< dist code (0..29) */ + dist = 0; + for (code = 0 ; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1<>= 7; /* from now on, all distances are divided by 128 */ + for ( ; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { + _dist_code[256 + dist++] = (uch)code; + } + } + Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; + n = 0; + while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; + while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; + while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; + while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n].Len = 5; + static_dtree[n].Code = bi_reverse((unsigned)n, 5); + } + static_init_done = 1; + +# ifdef GEN_TREES_H + gen_trees_header(); +# endif +#endif /* defined(GEN_TREES_H) || !defined(STDC) */ +} + +/* =========================================================================== + * Genererate the file trees.h describing the static trees. + */ +#ifdef GEN_TREES_H +# ifndef DEBUG +# include +# endif + +# define SEPARATOR(i, last, width) \ + ((i) == (last)? "\n};\n\n" : \ + ((i) % (width) == (width)-1 ? ",\n" : ", ")) + +void gen_trees_header() +{ + FILE *header = fopen("trees.h", "w"); + int i; + + Assert (header != NULL, "Can't open trees.h"); + fprintf(header, + "/* header created automatically with -DGEN_TREES_H */\n\n"); + + fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n"); + for (i = 0; i < L_CODES+2; i++) { + fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code, + static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5)); + } + + fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n"); + for (i = 0; i < D_CODES; i++) { + fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code, + static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5)); + } + + fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n"); + for (i = 0; i < DIST_CODE_LEN; i++) { + fprintf(header, "%2u%s", _dist_code[i], + SEPARATOR(i, DIST_CODE_LEN-1, 20)); + } + + fprintf(header, + "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); + for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) { + fprintf(header, "%2u%s", _length_code[i], + SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20)); + } + + fprintf(header, "local const int base_length[LENGTH_CODES] = {\n"); + for (i = 0; i < LENGTH_CODES; i++) { + fprintf(header, "%1u%s", base_length[i], + SEPARATOR(i, LENGTH_CODES-1, 20)); + } + + fprintf(header, "local const int base_dist[D_CODES] = {\n"); + for (i = 0; i < D_CODES; i++) { + fprintf(header, "%5u%s", base_dist[i], + SEPARATOR(i, D_CODES-1, 10)); + } + + fclose(header); +} +#endif /* GEN_TREES_H */ + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +void ZLIB_INTERNAL _tr_init(s) + deflate_state *s; +{ + tr_static_init(); + + s->l_desc.dyn_tree = s->dyn_ltree; + s->l_desc.stat_desc = &static_l_desc; + + s->d_desc.dyn_tree = s->dyn_dtree; + s->d_desc.stat_desc = &static_d_desc; + + s->bl_desc.dyn_tree = s->bl_tree; + s->bl_desc.stat_desc = &static_bl_desc; + + s->bi_buf = 0; + s->bi_valid = 0; + s->last_eob_len = 8; /* enough lookahead for inflate */ +#ifdef DEBUG + s->compressed_len = 0L; + s->bits_sent = 0L; +#endif + + /* Initialize the first block of the first file: */ + init_block(s); +} + +/* =========================================================================== + * Initialize a new block. + */ +local void init_block(s) + deflate_state *s; +{ + int n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; + for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; + for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; + + s->dyn_ltree[END_BLOCK].Freq = 1; + s->opt_len = s->static_len = 0L; + s->last_lit = s->matches = 0; +} + +#define SMALLEST 1 +/* Index within the heap array of least frequent node in the Huffman tree */ + + +/* =========================================================================== + * Remove the smallest element from the heap and recreate the heap with + * one less element. Updates heap and heap_len. + */ +#define pqremove(s, tree, top) \ +{\ + top = s->heap[SMALLEST]; \ + s->heap[SMALLEST] = s->heap[s->heap_len--]; \ + pqdownheap(s, tree, SMALLEST); \ +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +#define smaller(tree, n, m, depth) \ + (tree[n].Freq < tree[m].Freq || \ + (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +local void pqdownheap(s, tree, k) + deflate_state *s; + ct_data *tree; /* the tree to restore */ + int k; /* node to move down */ +{ + int v = s->heap[k]; + int j = k << 1; /* left son of k */ + while (j <= s->heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s->heap_len && + smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s->heap[j], s->depth)) break; + + /* Exchange v with the smallest son */ + s->heap[k] = s->heap[j]; k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s->heap[k] = v; +} + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +local void gen_bitlen(s, desc) + deflate_state *s; + tree_desc *desc; /* the tree descriptor */ +{ + ct_data *tree = desc->dyn_tree; + int max_code = desc->max_code; + const ct_data *stree = desc->stat_desc->static_tree; + const intf *extra = desc->stat_desc->extra_bits; + int base = desc->stat_desc->extra_base; + int max_length = desc->stat_desc->max_length; + int h; /* heap index */ + int n, m; /* iterate over the tree elements */ + int bits; /* bit length */ + int xbits; /* extra bits */ + ush f; /* frequency */ + int overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ + + for (h = s->heap_max+1; h < HEAP_SIZE; h++) { + n = s->heap[h]; + bits = tree[tree[n].Dad].Len + 1; + if (bits > max_length) bits = max_length, overflow++; + tree[n].Len = (ush)bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) continue; /* not a leaf node */ + + s->bl_count[bits]++; + xbits = 0; + if (n >= base) xbits = extra[n-base]; + f = tree[n].Freq; + s->opt_len += (ulg)f * (bits + xbits); + if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits); + } + if (overflow == 0) return; + + Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length-1; + while (s->bl_count[bits] == 0) bits--; + s->bl_count[bits]--; /* move one leaf down the tree */ + s->bl_count[bits+1] += 2; /* move one overflow item as its brother */ + s->bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits != 0; bits--) { + n = s->bl_count[bits]; + while (n != 0) { + m = s->heap[--h]; + if (m > max_code) continue; + if ((unsigned) tree[m].Len != (unsigned) bits) { + Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s->opt_len += ((long)bits - (long)tree[m].Len) + *(long)tree[m].Freq; + tree[m].Len = (ush)bits; + } + n--; + } + } +} + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +local void gen_codes (tree, max_code, bl_count) + ct_data *tree; /* the tree to decorate */ + int max_code; /* largest code with non zero frequency */ + ushf *bl_count; /* number of codes at each bit length */ +{ + ush next_code[MAX_BITS+1]; /* next code value for each bit length */ + ush code = 0; /* running code value */ + int bits; /* bit index */ + int n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (code + bl_count[bits-1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + Assert (code + bl_count[MAX_BITS]-1 == (1<dyn_tree; + const ct_data *stree = desc->stat_desc->static_tree; + int elems = desc->stat_desc->elems; + int n, m; /* iterate over heap elements */ + int max_code = -1; /* largest code with non zero frequency */ + int node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s->heap_len = 0, s->heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n].Freq != 0) { + s->heap[++(s->heap_len)] = max_code = n; + s->depth[n] = 0; + } else { + tree[n].Len = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s->heap_len < 2) { + node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0); + tree[node].Freq = 1; + s->depth[node] = 0; + s->opt_len--; if (stree) s->static_len -= stree[node].Len; + /* node is 0 or 1 so it does not have extra bits */ + } + desc->max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + pqremove(s, tree, n); /* n = node of least frequency */ + m = s->heap[SMALLEST]; /* m = node of next least frequency */ + + s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */ + s->heap[--(s->heap_max)] = m; + + /* Create a new node father of n and m */ + tree[node].Freq = tree[n].Freq + tree[m].Freq; + s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ? + s->depth[n] : s->depth[m]) + 1); + tree[n].Dad = tree[m].Dad = (ush)node; +#ifdef DUMP_BL_TREE + if (tree == s->bl_tree) { + fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)", + node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); + } +#endif + /* and insert the new node in the heap */ + s->heap[SMALLEST] = node++; + pqdownheap(s, tree, SMALLEST); + + } while (s->heap_len >= 2); + + s->heap[--(s->heap_max)] = s->heap[SMALLEST]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, (tree_desc *)desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes ((ct_data *)tree, max_code, s->bl_count); +} + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +local void scan_tree (s, tree, max_code) + deflate_state *s; + ct_data *tree; /* the tree to be scanned */ + int max_code; /* and its largest code of non zero frequency */ +{ + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].Len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + if (nextlen == 0) max_count = 138, min_count = 3; + tree[max_code+1].Len = (ush)0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n+1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + s->bl_tree[curlen].Freq += count; + } else if (curlen != 0) { + if (curlen != prevlen) s->bl_tree[curlen].Freq++; + s->bl_tree[REP_3_6].Freq++; + } else if (count <= 10) { + s->bl_tree[REPZ_3_10].Freq++; + } else { + s->bl_tree[REPZ_11_138].Freq++; + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } +} + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +local void send_tree (s, tree, max_code) + deflate_state *s; + ct_data *tree; /* the tree to be scanned */ + int max_code; /* and its largest code of non zero frequency */ +{ + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].Len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen == 0) max_count = 138, min_count = 3; + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n+1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + do { send_code(s, curlen, s->bl_tree); } while (--count != 0); + + } else if (curlen != 0) { + if (curlen != prevlen) { + send_code(s, curlen, s->bl_tree); count--; + } + Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3); + + } else { + send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7); + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } +} + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +local int build_bl_tree(s) + deflate_state *s; +{ + int max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); + scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, (tree_desc *)(&(s->bl_desc))); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { + if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; + } + /* Update opt_len to include the bit length tree and counts */ + s->opt_len += 3*(max_blindex+1) + 5+5+4; + Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + s->opt_len, s->static_len)); + + return max_blindex; +} + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +local void send_all_trees(s, lcodes, dcodes, blcodes) + deflate_state *s; + int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + int rank; /* index in bl_order */ + + Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + "too many codes"); + Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes-1, 5); + send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); + } + Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */ + Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */ + Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + +/* =========================================================================== + * Send a stored block + */ +void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last) + deflate_state *s; + charf *buf; /* input block */ + ulg stored_len; /* length of input block */ + int last; /* one if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK<<1)+last, 3); /* send block type */ +#ifdef DEBUG + s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; + s->compressed_len += (stored_len + 4) << 3; +#endif + copy_block(s, buf, (unsigned)stored_len, 1); /* with header */ +} + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + * The current inflate code requires 9 bits of lookahead. If the + * last two codes for the previous block (real code plus EOB) were coded + * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode + * the last real code. In this case we send two empty static blocks instead + * of one. (There are no problems if the previous block is stored or fixed.) + * To simplify the code, we assume the worst case of last real code encoded + * on one bit only. + */ +void ZLIB_INTERNAL _tr_align(s) + deflate_state *s; +{ + send_bits(s, STATIC_TREES<<1, 3); + send_code(s, END_BLOCK, static_ltree); +#ifdef DEBUG + s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ +#endif + bi_flush(s); + /* Of the 10 bits for the empty block, we have already sent + * (10 - bi_valid) bits. The lookahead for the last real code (before + * the EOB of the previous block) was thus at least one plus the length + * of the EOB plus what we have just sent of the empty static block. + */ + if (1 + s->last_eob_len + 10 - s->bi_valid < 9) { + send_bits(s, STATIC_TREES<<1, 3); + send_code(s, END_BLOCK, static_ltree); +#ifdef DEBUG + s->compressed_len += 10L; +#endif + bi_flush(s); + } + s->last_eob_len = 7; +} + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ +void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) + deflate_state *s; + charf *buf; /* input block, or NULL if too old */ + ulg stored_len; /* length of input block */ + int last; /* one if this is the last block for a file */ +{ + ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + int max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s->level > 0) { + + /* Check if the file is binary or text */ + if (s->strm->data_type == Z_UNKNOWN) + s->strm->data_type = detect_data_type(s); + + /* Construct the literal and distance trees */ + build_tree(s, (tree_desc *)(&(s->l_desc))); + Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + s->static_len)); + + build_tree(s, (tree_desc *)(&(s->d_desc))); + Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s->opt_len+3+7)>>3; + static_lenb = (s->static_len+3+7)>>3; + + Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + s->last_lit)); + + if (static_lenb <= opt_lenb) opt_lenb = static_lenb; + + } else { + Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + +#ifdef FORCE_STORED + if (buf != (char*)0) { /* force stored block */ +#else + if (stored_len+4 <= opt_lenb && buf != (char*)0) { + /* 4: two words for the lengths */ +#endif + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + +#ifdef FORCE_STATIC + } else if (static_lenb >= 0) { /* force static trees */ +#else + } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) { +#endif + send_bits(s, (STATIC_TREES<<1)+last, 3); + compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree); +#ifdef DEBUG + s->compressed_len += 3 + s->static_len; +#endif + } else { + send_bits(s, (DYN_TREES<<1)+last, 3); + send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, + max_blindex+1); + compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree); +#ifdef DEBUG + s->compressed_len += 3 + s->opt_len; +#endif + } + Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); +#ifdef DEBUG + s->compressed_len += 7; /* align on byte boundary */ +#endif + } + Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + s->compressed_len-7*last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +int ZLIB_INTERNAL _tr_tally (s, dist, lc) + deflate_state *s; + unsigned dist; /* distance of matched string */ + unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + s->d_buf[s->last_lit] = (ush)dist; + s->l_buf[s->last_lit++] = (uch)lc; + if (dist == 0) { + /* lc is the unmatched char */ + s->dyn_ltree[lc].Freq++; + } else { + s->matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + Assert((ush)dist < (ush)MAX_DIST(s) && + (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++; + s->dyn_dtree[d_code(dist)].Freq++; + } + +#ifdef TRUNCATE_BLOCK + /* Try to guess if it is profitable to stop the current block here */ + if ((s->last_lit & 0x1fff) == 0 && s->level > 2) { + /* Compute an upper bound for the compressed length */ + ulg out_length = (ulg)s->last_lit*8L; + ulg in_length = (ulg)((long)s->strstart - s->block_start); + int dcode; + for (dcode = 0; dcode < D_CODES; dcode++) { + out_length += (ulg)s->dyn_dtree[dcode].Freq * + (5L+extra_dbits[dcode]); + } + out_length >>= 3; + Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", + s->last_lit, in_length, out_length, + 100L - out_length*100L/in_length)); + if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1; + } +#endif + return (s->last_lit == s->lit_bufsize-1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +local void compress_block(s, ltree, dtree) + deflate_state *s; + ct_data *ltree; /* literal tree */ + ct_data *dtree; /* distance tree */ +{ + unsigned dist; /* distance of matched string */ + int lc; /* match length or unmatched char (if dist == 0) */ + unsigned lx = 0; /* running index in l_buf */ + unsigned code; /* the code to send */ + int extra; /* number of extra bits to send */ + + if (s->last_lit != 0) do { + dist = s->d_buf[lx]; + lc = s->l_buf[lx++]; + if (dist == 0) { + send_code(s, lc, ltree); /* send a literal byte */ + Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code+LITERALS+1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra != 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra != 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + "pendingBuf overflow"); + + } while (lx < s->last_lit); + + send_code(s, END_BLOCK, ltree); + s->last_eob_len = ltree[END_BLOCK].Len; +} + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +local int detect_data_type(s) + deflate_state *s; +{ + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + unsigned long black_mask = 0xf3ffc07fUL; + int n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>= 1) + if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0)) + return Z_BINARY; + + /* Check for textual ("white-listed") bytes. */ + if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0 + || s->dyn_ltree[13].Freq != 0) + return Z_TEXT; + for (n = 32; n < LITERALS; n++) + if (s->dyn_ltree[n].Freq != 0) + return Z_TEXT; + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; +} + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +local unsigned bi_reverse(code, len) + unsigned code; /* the value to invert */ + int len; /* its bit length */ +{ + register unsigned res = 0; + do { + res |= code & 1; + code >>= 1, res <<= 1; + } while (--len > 0); + return res >> 1; +} + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +local void bi_flush(s) + deflate_state *s; +{ + if (s->bi_valid == 16) { + put_short(s, s->bi_buf); + s->bi_buf = 0; + s->bi_valid = 0; + } else if (s->bi_valid >= 8) { + put_byte(s, (Byte)s->bi_buf); + s->bi_buf >>= 8; + s->bi_valid -= 8; + } +} + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +local void bi_windup(s) + deflate_state *s; +{ + if (s->bi_valid > 8) { + put_short(s, s->bi_buf); + } else if (s->bi_valid > 0) { + put_byte(s, (Byte)s->bi_buf); + } + s->bi_buf = 0; + s->bi_valid = 0; +#ifdef DEBUG + s->bits_sent = (s->bits_sent+7) & ~7; +#endif +} + +/* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ +local void copy_block(s, buf, len, header) + deflate_state *s; + charf *buf; /* the input data */ + unsigned len; /* its length */ + int header; /* true if block header must be written */ +{ + bi_windup(s); /* align on byte boundary */ + s->last_eob_len = 8; /* enough lookahead for inflate */ + + if (header) { + put_short(s, (ush)len); + put_short(s, (ush)~len); +#ifdef DEBUG + s->bits_sent += 2*16; +#endif + } +#ifdef DEBUG + s->bits_sent += (ulg)len<<3; +#endif + while (len--) { + put_byte(s, *buf++); + } +} diff --git a/dep/zlib/trees.h b/dep/zlib/trees.h new file mode 100644 index 00000000000..d35639d82a2 --- /dev/null +++ b/dep/zlib/trees.h @@ -0,0 +1,128 @@ +/* header created automatically with -DGEN_TREES_H */ + +local const ct_data static_ltree[L_CODES+2] = { +{{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}}, +{{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}}, +{{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}}, +{{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}}, +{{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}}, +{{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}}, +{{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}}, +{{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}}, +{{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}}, +{{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}}, +{{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}}, +{{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}}, +{{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}}, +{{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}}, +{{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}}, +{{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}}, +{{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}}, +{{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}}, +{{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}}, +{{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}}, +{{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}}, +{{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}}, +{{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}}, +{{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}}, +{{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}}, +{{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}}, +{{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}}, +{{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}}, +{{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}}, +{{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}}, +{{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}}, +{{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}}, +{{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}}, +{{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}}, +{{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}}, +{{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}}, +{{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}}, +{{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}}, +{{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}}, +{{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}}, +{{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}}, +{{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}}, +{{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}}, +{{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}}, +{{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}}, +{{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}}, +{{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}}, +{{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}}, +{{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}}, +{{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}}, +{{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}}, +{{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}}, +{{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}}, +{{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}}, +{{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}}, +{{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}}, +{{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}}, +{{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}} +}; + +local const ct_data static_dtree[D_CODES] = { +{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}}, +{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}}, +{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}}, +{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}}, +{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}}, +{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}} +}; + +const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = { + 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, + 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, +10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, +11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, +12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, +13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, +13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, +18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, +23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 +}; + +const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, +13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, +17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, +19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, +21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, +22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, +23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, +25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 +}; + +local const int base_length[LENGTH_CODES] = { +0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, +64, 80, 96, 112, 128, 160, 192, 224, 0 +}; + +local const int base_dist[D_CODES] = { + 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, + 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, + 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 +}; + diff --git a/dep/zlib/uncompr.c b/dep/zlib/uncompr.c new file mode 100644 index 00000000000..ad98be3a5d8 --- /dev/null +++ b/dep/zlib/uncompr.c @@ -0,0 +1,59 @@ +/* uncompr.c -- decompress a memory buffer + * Copyright (C) 1995-2003, 2010 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#define ZLIB_INTERNAL +#include "zlib.h" + +/* =========================================================================== + Decompresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total + size of the destination buffer, which must be large enough to hold the + entire uncompressed data. (The size of the uncompressed data must have + been saved previously by the compressor and transmitted to the decompressor + by some mechanism outside the scope of this compression library.) + Upon exit, destLen is the actual size of the compressed buffer. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer, or Z_DATA_ERROR if the input data was corrupted. +*/ +int ZEXPORT uncompress (dest, destLen, source, sourceLen) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; +{ + z_stream stream; + int err; + + stream.next_in = (Bytef*)source; + stream.avail_in = (uInt)sourceLen; + /* Check for source > 64K on 16-bit machine: */ + if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; + + stream.next_out = dest; + stream.avail_out = (uInt)*destLen; + if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; + + stream.zalloc = (alloc_func)0; + stream.zfree = (free_func)0; + + err = inflateInit(&stream); + if (err != Z_OK) return err; + + err = inflate(&stream, Z_FINISH); + if (err != Z_STREAM_END) { + inflateEnd(&stream); + if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0)) + return Z_DATA_ERROR; + return err; + } + *destLen = stream.total_out; + + err = inflateEnd(&stream); + return err; +} diff --git a/dep/zlib/zconf.h b/dep/zlib/zconf.h new file mode 100644 index 00000000000..02ce56c4313 --- /dev/null +++ b/dep/zlib/zconf.h @@ -0,0 +1,428 @@ +/* zconf.h -- configuration of the zlib compression library + * Copyright (C) 1995-2010 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#ifndef ZCONF_H +#define ZCONF_H + +/* + * If you *really* need a unique prefix for all types and library functions, + * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. + * Even better than compiling with -DZ_PREFIX would be to use configure to set + * this permanently in zconf.h using "./configure --zprefix". + */ +#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ + +/* all linked symbols */ +# define _dist_code z__dist_code +# define _length_code z__length_code +# define _tr_align z__tr_align +# define _tr_flush_block z__tr_flush_block +# define _tr_init z__tr_init +# define _tr_stored_block z__tr_stored_block +# define _tr_tally z__tr_tally +# define adler32 z_adler32 +# define adler32_combine z_adler32_combine +# define adler32_combine64 z_adler32_combine64 +# define compress z_compress +# define compress2 z_compress2 +# define compressBound z_compressBound +# define crc32 z_crc32 +# define crc32_combine z_crc32_combine +# define crc32_combine64 z_crc32_combine64 +# define deflate z_deflate +# define deflateBound z_deflateBound +# define deflateCopy z_deflateCopy +# define deflateEnd z_deflateEnd +# define deflateInit2_ z_deflateInit2_ +# define deflateInit_ z_deflateInit_ +# define deflateParams z_deflateParams +# define deflatePrime z_deflatePrime +# define deflateReset z_deflateReset +# define deflateSetDictionary z_deflateSetDictionary +# define deflateSetHeader z_deflateSetHeader +# define deflateTune z_deflateTune +# define deflate_copyright z_deflate_copyright +# define get_crc_table z_get_crc_table +# define gz_error z_gz_error +# define gz_intmax z_gz_intmax +# define gz_strwinerror z_gz_strwinerror +# define gzbuffer z_gzbuffer +# define gzclearerr z_gzclearerr +# define gzclose z_gzclose +# define gzclose_r z_gzclose_r +# define gzclose_w z_gzclose_w +# define gzdirect z_gzdirect +# define gzdopen z_gzdopen +# define gzeof z_gzeof +# define gzerror z_gzerror +# define gzflush z_gzflush +# define gzgetc z_gzgetc +# define gzgets z_gzgets +# define gzoffset z_gzoffset +# define gzoffset64 z_gzoffset64 +# define gzopen z_gzopen +# define gzopen64 z_gzopen64 +# define gzprintf z_gzprintf +# define gzputc z_gzputc +# define gzputs z_gzputs +# define gzread z_gzread +# define gzrewind z_gzrewind +# define gzseek z_gzseek +# define gzseek64 z_gzseek64 +# define gzsetparams z_gzsetparams +# define gztell z_gztell +# define gztell64 z_gztell64 +# define gzungetc z_gzungetc +# define gzwrite z_gzwrite +# define inflate z_inflate +# define inflateBack z_inflateBack +# define inflateBackEnd z_inflateBackEnd +# define inflateBackInit_ z_inflateBackInit_ +# define inflateCopy z_inflateCopy +# define inflateEnd z_inflateEnd +# define inflateGetHeader z_inflateGetHeader +# define inflateInit2_ z_inflateInit2_ +# define inflateInit_ z_inflateInit_ +# define inflateMark z_inflateMark +# define inflatePrime z_inflatePrime +# define inflateReset z_inflateReset +# define inflateReset2 z_inflateReset2 +# define inflateSetDictionary z_inflateSetDictionary +# define inflateSync z_inflateSync +# define inflateSyncPoint z_inflateSyncPoint +# define inflateUndermine z_inflateUndermine +# define inflate_copyright z_inflate_copyright +# define inflate_fast z_inflate_fast +# define inflate_table z_inflate_table +# define uncompress z_uncompress +# define zError z_zError +# define zcalloc z_zcalloc +# define zcfree z_zcfree +# define zlibCompileFlags z_zlibCompileFlags +# define zlibVersion z_zlibVersion + +/* all zlib typedefs in zlib.h and zconf.h */ +# define Byte z_Byte +# define Bytef z_Bytef +# define alloc_func z_alloc_func +# define charf z_charf +# define free_func z_free_func +# define gzFile z_gzFile +# define gz_header z_gz_header +# define gz_headerp z_gz_headerp +# define in_func z_in_func +# define intf z_intf +# define out_func z_out_func +# define uInt z_uInt +# define uIntf z_uIntf +# define uLong z_uLong +# define uLongf z_uLongf +# define voidp z_voidp +# define voidpc z_voidpc +# define voidpf z_voidpf + +/* all zlib structs in zlib.h and zconf.h */ +# define gz_header_s z_gz_header_s +# define internal_state z_internal_state + +#endif + +#if defined(__MSDOS__) && !defined(MSDOS) +# define MSDOS +#endif +#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) +# define OS2 +#endif +#if defined(_WINDOWS) && !defined(WINDOWS) +# define WINDOWS +#endif +#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) +# ifndef WIN32 +# define WIN32 +# endif +#endif +#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) +# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) +# ifndef SYS16BIT +# define SYS16BIT +# endif +# endif +#endif + +/* + * Compile with -DMAXSEG_64K if the alloc function cannot allocate more + * than 64k bytes at a time (needed on systems with 16-bit int). + */ +#ifdef SYS16BIT +# define MAXSEG_64K +#endif +#ifdef MSDOS +# define UNALIGNED_OK +#endif + +#ifdef __STDC_VERSION__ +# ifndef STDC +# define STDC +# endif +# if __STDC_VERSION__ >= 199901L +# ifndef STDC99 +# define STDC99 +# endif +# endif +#endif +#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) +# define STDC +#endif +#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) +# define STDC +#endif +#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) +# define STDC +#endif +#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) +# define STDC +#endif + +#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ +# define STDC +#endif + +#ifndef STDC +# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ +# define const /* note: need a more gentle solution here */ +# endif +#endif + +/* Some Mac compilers merge all .h files incorrectly: */ +#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) +# define NO_DUMMY_DECL +#endif + +/* Maximum value for memLevel in deflateInit2 */ +#ifndef MAX_MEM_LEVEL +# ifdef MAXSEG_64K +# define MAX_MEM_LEVEL 8 +# else +# define MAX_MEM_LEVEL 9 +# endif +#endif + +/* Maximum value for windowBits in deflateInit2 and inflateInit2. + * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files + * created by gzip. (Files created by minigzip can still be extracted by + * gzip.) + */ +#ifndef MAX_WBITS +# define MAX_WBITS 15 /* 32K LZ77 window */ +#endif + +/* The memory requirements for deflate are (in bytes): + (1 << (windowBits+2)) + (1 << (memLevel+9)) + that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) + plus a few kilobytes for small objects. For example, if you want to reduce + the default memory requirements from 256K to 128K, compile with + make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" + Of course this will generally degrade compression (there's no free lunch). + + The memory requirements for inflate are (in bytes) 1 << windowBits + that is, 32K for windowBits=15 (default value) plus a few kilobytes + for small objects. +*/ + + /* Type declarations */ + +#ifndef OF /* function prototypes */ +# ifdef STDC +# define OF(args) args +# else +# define OF(args) () +# endif +#endif + +/* The following definitions for FAR are needed only for MSDOS mixed + * model programming (small or medium model with some far allocations). + * This was tested only with MSC; for other MSDOS compilers you may have + * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, + * just define FAR to be empty. + */ +#ifdef SYS16BIT +# if defined(M_I86SM) || defined(M_I86MM) + /* MSC small or medium model */ +# define SMALL_MEDIUM +# ifdef _MSC_VER +# define FAR _far +# else +# define FAR far +# endif +# endif +# if (defined(__SMALL__) || defined(__MEDIUM__)) + /* Turbo C small or medium model */ +# define SMALL_MEDIUM +# ifdef __BORLANDC__ +# define FAR _far +# else +# define FAR far +# endif +# endif +#endif + +#if defined(WINDOWS) || defined(WIN32) + /* If building or using zlib as a DLL, define ZLIB_DLL. + * This is not mandatory, but it offers a little performance increase. + */ +# ifdef ZLIB_DLL +# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) +# ifdef ZLIB_INTERNAL +# define ZEXTERN extern __declspec(dllexport) +# else +# define ZEXTERN extern __declspec(dllimport) +# endif +# endif +# endif /* ZLIB_DLL */ + /* If building or using zlib with the WINAPI/WINAPIV calling convention, + * define ZLIB_WINAPI. + * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. + */ +# ifdef ZLIB_WINAPI +# ifdef FAR +# undef FAR +# endif +# include + /* No need for _export, use ZLIB.DEF instead. */ + /* For complete Windows compatibility, use WINAPI, not __stdcall. */ +# define ZEXPORT WINAPI +# ifdef WIN32 +# define ZEXPORTVA WINAPIV +# else +# define ZEXPORTVA FAR CDECL +# endif +# endif +#endif + +#if defined (__BEOS__) +# ifdef ZLIB_DLL +# ifdef ZLIB_INTERNAL +# define ZEXPORT __declspec(dllexport) +# define ZEXPORTVA __declspec(dllexport) +# else +# define ZEXPORT __declspec(dllimport) +# define ZEXPORTVA __declspec(dllimport) +# endif +# endif +#endif + +#ifndef ZEXTERN +# define ZEXTERN extern +#endif +#ifndef ZEXPORT +# define ZEXPORT +#endif +#ifndef ZEXPORTVA +# define ZEXPORTVA +#endif + +#ifndef FAR +# define FAR +#endif + +#if !defined(__MACTYPES__) +typedef unsigned char Byte; /* 8 bits */ +#endif +typedef unsigned int uInt; /* 16 bits or more */ +typedef unsigned long uLong; /* 32 bits or more */ + +#ifdef SMALL_MEDIUM + /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ +# define Bytef Byte FAR +#else + typedef Byte FAR Bytef; +#endif +typedef char FAR charf; +typedef int FAR intf; +typedef uInt FAR uIntf; +typedef uLong FAR uLongf; + +#ifdef STDC + typedef void const *voidpc; + typedef void FAR *voidpf; + typedef void *voidp; +#else + typedef Byte const *voidpc; + typedef Byte FAR *voidpf; + typedef Byte *voidp; +#endif + +#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ +# define Z_HAVE_UNISTD_H +#endif + +#ifdef STDC +# include /* for off_t */ +#endif + +/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and + * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even + * though the former does not conform to the LFS document), but considering + * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as + * equivalently requesting no 64-bit operations + */ +#if -_LARGEFILE64_SOURCE - -1 == 1 +# undef _LARGEFILE64_SOURCE +#endif + +#if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) +# include /* for SEEK_* and off_t */ +# ifdef VMS +# include /* for off_t */ +# endif +# ifndef z_off_t +# define z_off_t off_t +# endif +#endif + +#ifndef SEEK_SET +# define SEEK_SET 0 /* Seek from beginning of file. */ +# define SEEK_CUR 1 /* Seek from current position. */ +# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ +#endif + +#ifndef z_off_t +# define z_off_t long +#endif + +#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 +# define z_off64_t off64_t +#else +# define z_off64_t z_off_t +#endif + +#if defined(__OS400__) +# define NO_vsnprintf +#endif + +#if defined(__MVS__) +# define NO_vsnprintf +#endif + +/* MVS linker does not support external names larger than 8 bytes */ +#if defined(__MVS__) + #pragma map(deflateInit_,"DEIN") + #pragma map(deflateInit2_,"DEIN2") + #pragma map(deflateEnd,"DEEND") + #pragma map(deflateBound,"DEBND") + #pragma map(inflateInit_,"ININ") + #pragma map(inflateInit2_,"ININ2") + #pragma map(inflateEnd,"INEND") + #pragma map(inflateSync,"INSY") + #pragma map(inflateSetDictionary,"INSEDI") + #pragma map(compressBound,"CMBND") + #pragma map(inflate_table,"INTABL") + #pragma map(inflate_fast,"INFA") + #pragma map(inflate_copyright,"INCOPY") +#endif + +#endif /* ZCONF_H */ diff --git a/dep/zlib/zlib.h b/dep/zlib/zlib.h new file mode 100644 index 00000000000..bfbba83e8ee --- /dev/null +++ b/dep/zlib/zlib.h @@ -0,0 +1,1613 @@ +/* zlib.h -- interface of the 'zlib' general purpose compression library + version 1.2.5, April 19th, 2010 + + Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + + + The data format used by the zlib library is described by RFCs (Request for + Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt + (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). +*/ + +#ifndef ZLIB_H +#define ZLIB_H + +#include "zconf.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ZLIB_VERSION "1.2.5" +#define ZLIB_VERNUM 0x1250 +#define ZLIB_VER_MAJOR 1 +#define ZLIB_VER_MINOR 2 +#define ZLIB_VER_REVISION 5 +#define ZLIB_VER_SUBREVISION 0 + +/* + The 'zlib' compression library provides in-memory compression and + decompression functions, including integrity checks of the uncompressed data. + This version of the library supports only one compression method (deflation) + but other algorithms will be added later and will have the same stream + interface. + + Compression can be done in a single step if the buffers are large enough, + or can be done by repeated calls of the compression function. In the latter + case, the application must provide more input and/or consume the output + (providing more output space) before each call. + + The compressed data format used by default by the in-memory functions is + the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped + around a deflate stream, which is itself documented in RFC 1951. + + The library also supports reading and writing files in gzip (.gz) format + with an interface similar to that of stdio using the functions that start + with "gz". The gzip format is different from the zlib format. gzip is a + gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. + + This library can optionally read and write gzip streams in memory as well. + + The zlib format was designed to be compact and fast for use in memory + and on communications channels. The gzip format was designed for single- + file compression on file systems, has a larger header than zlib to maintain + directory information, and uses a different, slower check method than zlib. + + The library does not install any signal handler. The decoder checks + the consistency of the compressed data, so the library should never crash + even in case of corrupted input. +*/ + +typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); +typedef void (*free_func) OF((voidpf opaque, voidpf address)); + +struct internal_state; + +typedef struct z_stream_s { + Bytef *next_in; /* next input byte */ + uInt avail_in; /* number of bytes available at next_in */ + uLong total_in; /* total nb of input bytes read so far */ + + Bytef *next_out; /* next output byte should be put there */ + uInt avail_out; /* remaining free space at next_out */ + uLong total_out; /* total nb of bytes output so far */ + + char *msg; /* last error message, NULL if no error */ + struct internal_state FAR *state; /* not visible by applications */ + + alloc_func zalloc; /* used to allocate the internal state */ + free_func zfree; /* used to free the internal state */ + voidpf opaque; /* private data object passed to zalloc and zfree */ + + int data_type; /* best guess about the data type: binary or text */ + uLong adler; /* adler32 value of the uncompressed data */ + uLong reserved; /* reserved for future use */ +} z_stream; + +typedef z_stream FAR *z_streamp; + +/* + gzip header information passed to and from zlib routines. See RFC 1952 + for more details on the meanings of these fields. +*/ +typedef struct gz_header_s { + int text; /* true if compressed data believed to be text */ + uLong time; /* modification time */ + int xflags; /* extra flags (not used when writing a gzip file) */ + int os; /* operating system */ + Bytef *extra; /* pointer to extra field or Z_NULL if none */ + uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ + uInt extra_max; /* space at extra (only when reading header) */ + Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ + uInt name_max; /* space at name (only when reading header) */ + Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ + uInt comm_max; /* space at comment (only when reading header) */ + int hcrc; /* true if there was or will be a header crc */ + int done; /* true when done reading gzip header (not used + when writing a gzip file) */ +} gz_header; + +typedef gz_header FAR *gz_headerp; + +/* + The application must update next_in and avail_in when avail_in has dropped + to zero. It must update next_out and avail_out when avail_out has dropped + to zero. The application must initialize zalloc, zfree and opaque before + calling the init function. All other fields are set by the compression + library and must not be updated by the application. + + The opaque value provided by the application will be passed as the first + parameter for calls of zalloc and zfree. This can be useful for custom + memory management. The compression library attaches no meaning to the + opaque value. + + zalloc must return Z_NULL if there is not enough memory for the object. + If zlib is used in a multi-threaded application, zalloc and zfree must be + thread safe. + + On 16-bit systems, the functions zalloc and zfree must be able to allocate + exactly 65536 bytes, but will not be required to allocate more than this if + the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers + returned by zalloc for objects of exactly 65536 bytes *must* have their + offset normalized to zero. The default allocation function provided by this + library ensures this (see zutil.c). To reduce memory requirements and avoid + any allocation of 64K objects, at the expense of compression ratio, compile + the library with -DMAX_WBITS=14 (see zconf.h). + + The fields total_in and total_out can be used for statistics or progress + reports. After compression, total_in holds the total size of the + uncompressed data and may be saved for use in the decompressor (particularly + if the decompressor wants to decompress everything in a single step). +*/ + + /* constants */ + +#define Z_NO_FLUSH 0 +#define Z_PARTIAL_FLUSH 1 +#define Z_SYNC_FLUSH 2 +#define Z_FULL_FLUSH 3 +#define Z_FINISH 4 +#define Z_BLOCK 5 +#define Z_TREES 6 +/* Allowed flush values; see deflate() and inflate() below for details */ + +#define Z_OK 0 +#define Z_STREAM_END 1 +#define Z_NEED_DICT 2 +#define Z_ERRNO (-1) +#define Z_STREAM_ERROR (-2) +#define Z_DATA_ERROR (-3) +#define Z_MEM_ERROR (-4) +#define Z_BUF_ERROR (-5) +#define Z_VERSION_ERROR (-6) +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + +#define Z_NO_COMPRESSION 0 +#define Z_BEST_SPEED 1 +#define Z_BEST_COMPRESSION 9 +#define Z_DEFAULT_COMPRESSION (-1) +/* compression levels */ + +#define Z_FILTERED 1 +#define Z_HUFFMAN_ONLY 2 +#define Z_RLE 3 +#define Z_FIXED 4 +#define Z_DEFAULT_STRATEGY 0 +/* compression strategy; see deflateInit2() below for details */ + +#define Z_BINARY 0 +#define Z_TEXT 1 +#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ +#define Z_UNKNOWN 2 +/* Possible values of the data_type field (though see inflate()) */ + +#define Z_DEFLATED 8 +/* The deflate compression method (the only one supported in this version) */ + +#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ + +#define zlib_version zlibVersion() +/* for compatibility with versions < 1.0.2 */ + + + /* basic functions */ + +ZEXTERN const char * ZEXPORT zlibVersion OF((void)); +/* The application can compare zlibVersion and ZLIB_VERSION for consistency. + If the first character differs, the library code actually used is not + compatible with the zlib.h header file used by the application. This check + is automatically made by deflateInit and inflateInit. + */ + +/* +ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); + + Initializes the internal stream state for compression. The fields + zalloc, zfree and opaque must be initialized before by the caller. If + zalloc and zfree are set to Z_NULL, deflateInit updates them to use default + allocation functions. + + The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: + 1 gives best speed, 9 gives best compression, 0 gives no compression at all + (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION + requests a default compromise between speed and compression (currently + equivalent to level 6). + + deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if level is not a valid compression level, or + Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible + with the version assumed by the caller (ZLIB_VERSION). msg is set to null + if there is no error message. deflateInit does not perform any compression: + this will be done by deflate(). +*/ + + +ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); +/* + deflate compresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. deflate performs one or both of the + following actions: + + - Compress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in and avail_in are updated and + processing will resume at this point for the next call of deflate(). + + - Provide more output starting at next_out and update next_out and avail_out + accordingly. This action is forced if the parameter flush is non zero. + Forcing flush frequently degrades the compression ratio, so this parameter + should be set only when necessary (in interactive applications). Some + output may be provided even if flush is not set. + + Before the call of deflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming more + output, and updating avail_in or avail_out accordingly; avail_out should + never be zero before the call. The application can consume the compressed + output when it wants, for example when the output buffer is full (avail_out + == 0), or after each call of deflate(). If deflate returns Z_OK and with + zero avail_out, it must be called again after making room in the output + buffer because there might be more output pending. + + Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to + decide how much data to accumulate before producing output, in order to + maximize compression. + + If the parameter flush is set to Z_SYNC_FLUSH, all pending output is + flushed to the output buffer and the output is aligned on a byte boundary, so + that the decompressor can get all input data available so far. (In + particular avail_in is zero after the call if enough output space has been + provided before the call.) Flushing may degrade compression for some + compression algorithms and so it should be used only when necessary. This + completes the current deflate block and follows it with an empty stored block + that is three bits plus filler bits to the next byte, followed by four bytes + (00 00 ff ff). + + If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the + output buffer, but the output is not aligned to a byte boundary. All of the + input data so far will be available to the decompressor, as for Z_SYNC_FLUSH. + This completes the current deflate block and follows it with an empty fixed + codes block that is 10 bits long. This assures that enough bytes are output + in order for the decompressor to finish the block before the empty fixed code + block. + + If flush is set to Z_BLOCK, a deflate block is completed and emitted, as + for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to + seven bits of the current block are held to be written as the next byte after + the next deflate block is completed. In this case, the decompressor may not + be provided enough bits at this point in order to complete decompression of + the data provided so far to the compressor. It may need to wait for the next + block to be emitted. This is for advanced applications that need to control + the emission of deflate blocks. + + If flush is set to Z_FULL_FLUSH, all output is flushed as with + Z_SYNC_FLUSH, and the compression state is reset so that decompression can + restart from this point if previous compressed data has been damaged or if + random access is desired. Using Z_FULL_FLUSH too often can seriously degrade + compression. + + If deflate returns with avail_out == 0, this function must be called again + with the same value of the flush parameter and more output space (updated + avail_out), until the flush is complete (deflate returns with non-zero + avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that + avail_out is greater than six to avoid repeated flush markers due to + avail_out == 0 on return. + + If the parameter flush is set to Z_FINISH, pending input is processed, + pending output is flushed and deflate returns with Z_STREAM_END if there was + enough output space; if deflate returns with Z_OK, this function must be + called again with Z_FINISH and more output space (updated avail_out) but no + more input data, until it returns with Z_STREAM_END or an error. After + deflate has returned Z_STREAM_END, the only possible operations on the stream + are deflateReset or deflateEnd. + + Z_FINISH can be used immediately after deflateInit if all the compression + is to be done in a single step. In this case, avail_out must be at least the + value returned by deflateBound (see below). If deflate does not return + Z_STREAM_END, then it must be called again as described above. + + deflate() sets strm->adler to the adler32 checksum of all input read + so far (that is, total_in bytes). + + deflate() may update strm->data_type if it can make a good guess about + the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered + binary. This field is only for information purposes and does not affect the + compression algorithm in any manner. + + deflate() returns Z_OK if some progress has been made (more input + processed or more output produced), Z_STREAM_END if all input has been + consumed and all output has been produced (only when flush is set to + Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example + if next_in or next_out was Z_NULL), Z_BUF_ERROR if no progress is possible + (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not + fatal, and deflate() can be called again with more input and more output + space to continue compressing. +*/ + + +ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending + output. + + deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the + stream state was inconsistent, Z_DATA_ERROR if the stream was freed + prematurely (some input or output was discarded). In the error case, msg + may be set but then points to a static string (which must not be + deallocated). +*/ + + +/* +ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); + + Initializes the internal stream state for decompression. The fields + next_in, avail_in, zalloc, zfree and opaque must be initialized before by + the caller. If next_in is not Z_NULL and avail_in is large enough (the + exact value depends on the compression method), inflateInit determines the + compression method from the zlib header and allocates all data structures + accordingly; otherwise the allocation will be deferred to the first call of + inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to + use default allocation functions. + + inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller, or Z_STREAM_ERROR if the parameters are + invalid, such as a null pointer to the structure. msg is set to null if + there is no error message. inflateInit does not perform any decompression + apart from possibly reading the zlib header if present: actual decompression + will be done by inflate(). (So next_in and avail_in may be modified, but + next_out and avail_out are unused and unchanged.) The current implementation + of inflateInit() does not process any header information -- that is deferred + until inflate() is called. +*/ + + +ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); +/* + inflate decompresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. inflate performs one or both of the + following actions: + + - Decompress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in is updated and processing will + resume at this point for the next call of inflate(). + + - Provide more output starting at next_out and update next_out and avail_out + accordingly. inflate() provides as much output as possible, until there is + no more input data or no more space in the output buffer (see below about + the flush parameter). + + Before the call of inflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming more + output, and updating the next_* and avail_* values accordingly. The + application can consume the uncompressed output when it wants, for example + when the output buffer is full (avail_out == 0), or after each call of + inflate(). If inflate returns Z_OK and with zero avail_out, it must be + called again after making room in the output buffer because there might be + more output pending. + + The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH, + Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much + output as possible to the output buffer. Z_BLOCK requests that inflate() + stop if and when it gets to the next deflate block boundary. When decoding + the zlib or gzip format, this will cause inflate() to return immediately + after the header and before the first block. When doing a raw inflate, + inflate() will go ahead and process the first block, and will return when it + gets to the end of that block, or when it runs out of data. + + The Z_BLOCK option assists in appending to or combining deflate streams. + Also to assist in this, on return inflate() will set strm->data_type to the + number of unused bits in the last byte taken from strm->next_in, plus 64 if + inflate() is currently decoding the last block in the deflate stream, plus + 128 if inflate() returned immediately after decoding an end-of-block code or + decoding the complete header up to just before the first byte of the deflate + stream. The end-of-block will not be indicated until all of the uncompressed + data from that block has been written to strm->next_out. The number of + unused bits may in general be greater than seven, except when bit 7 of + data_type is set, in which case the number of unused bits will be less than + eight. data_type is set as noted here every time inflate() returns for all + flush options, and so can be used to determine the amount of currently + consumed input in bits. + + The Z_TREES option behaves as Z_BLOCK does, but it also returns when the + end of each deflate block header is reached, before any actual data in that + block is decoded. This allows the caller to determine the length of the + deflate block header for later use in random access within a deflate block. + 256 is added to the value of strm->data_type when inflate() returns + immediately after reaching the end of the deflate block header. + + inflate() should normally be called until it returns Z_STREAM_END or an + error. However if all decompression is to be performed in a single step (a + single call of inflate), the parameter flush should be set to Z_FINISH. In + this case all pending input is processed and all pending output is flushed; + avail_out must be large enough to hold all the uncompressed data. (The size + of the uncompressed data may have been saved by the compressor for this + purpose.) The next operation on this stream must be inflateEnd to deallocate + the decompression state. The use of Z_FINISH is never required, but can be + used to inform inflate that a faster approach may be used for the single + inflate() call. + + In this implementation, inflate() always flushes as much output as + possible to the output buffer, and always uses the faster approach on the + first call. So the only effect of the flush parameter in this implementation + is on the return value of inflate(), as noted below, or when it returns early + because Z_BLOCK or Z_TREES is used. + + If a preset dictionary is needed after this call (see inflateSetDictionary + below), inflate sets strm->adler to the adler32 checksum of the dictionary + chosen by the compressor and returns Z_NEED_DICT; otherwise it sets + strm->adler to the adler32 checksum of all output produced so far (that is, + total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described + below. At the end of the stream, inflate() checks that its computed adler32 + checksum is equal to that saved by the compressor and returns Z_STREAM_END + only if the checksum is correct. + + inflate() can decompress and check either zlib-wrapped or gzip-wrapped + deflate data. The header type is detected automatically, if requested when + initializing with inflateInit2(). Any information contained in the gzip + header is not retained, so applications that need that information should + instead use raw inflate, see inflateInit2() below, or inflateBack() and + perform their own processing of the gzip header and trailer. + + inflate() returns Z_OK if some progress has been made (more input processed + or more output produced), Z_STREAM_END if the end of the compressed data has + been reached and all uncompressed output has been produced, Z_NEED_DICT if a + preset dictionary is needed at this point, Z_DATA_ERROR if the input data was + corrupted (input stream not conforming to the zlib format or incorrect check + value), Z_STREAM_ERROR if the stream structure was inconsistent (for example + next_in or next_out was Z_NULL), Z_MEM_ERROR if there was not enough memory, + Z_BUF_ERROR if no progress is possible or if there was not enough room in the + output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and + inflate() can be called again with more input and more output space to + continue decompressing. If Z_DATA_ERROR is returned, the application may + then call inflateSync() to look for a good compression block if a partial + recovery of the data is desired. +*/ + + +ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending + output. + + inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state + was inconsistent. In the error case, msg may be set but then points to a + static string (which must not be deallocated). +*/ + + + /* Advanced functions */ + +/* + The following functions are needed only in some special applications. +*/ + +/* +ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, + int level, + int method, + int windowBits, + int memLevel, + int strategy)); + + This is another version of deflateInit with more compression options. The + fields next_in, zalloc, zfree and opaque must be initialized before by the + caller. + + The method parameter is the compression method. It must be Z_DEFLATED in + this version of the library. + + The windowBits parameter is the base two logarithm of the window size + (the size of the history buffer). It should be in the range 8..15 for this + version of the library. Larger values of this parameter result in better + compression at the expense of memory usage. The default value is 15 if + deflateInit is used instead. + + windowBits can also be -8..-15 for raw deflate. In this case, -windowBits + determines the window size. deflate() will then generate raw deflate data + with no zlib header or trailer, and will not compute an adler32 check value. + + windowBits can also be greater than 15 for optional gzip encoding. Add + 16 to windowBits to write a simple gzip header and trailer around the + compressed data instead of a zlib wrapper. The gzip header will have no + file name, no extra data, no comment, no modification time (set to zero), no + header crc, and the operating system will be set to 255 (unknown). If a + gzip stream is being written, strm->adler is a crc32 instead of an adler32. + + The memLevel parameter specifies how much memory should be allocated + for the internal compression state. memLevel=1 uses minimum memory but is + slow and reduces compression ratio; memLevel=9 uses maximum memory for + optimal speed. The default value is 8. See zconf.h for total memory usage + as a function of windowBits and memLevel. + + The strategy parameter is used to tune the compression algorithm. Use the + value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a + filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no + string match), or Z_RLE to limit match distances to one (run-length + encoding). Filtered data consists mostly of small values with a somewhat + random distribution. In this case, the compression algorithm is tuned to + compress them better. The effect of Z_FILTERED is to force more Huffman + coding and less string matching; it is somewhat intermediate between + Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as + fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The + strategy parameter only affects the compression ratio but not the + correctness of the compressed output even if it is not set appropriately. + Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler + decoder for special applications. + + deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid + method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is + incompatible with the version assumed by the caller (ZLIB_VERSION). msg is + set to null if there is no error message. deflateInit2 does not perform any + compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the compression dictionary from the given byte sequence + without producing any compressed output. This function must be called + immediately after deflateInit, deflateInit2 or deflateReset, before any call + of deflate. The compressor and decompressor must use exactly the same + dictionary (see inflateSetDictionary). + + The dictionary should consist of strings (byte sequences) that are likely + to be encountered later in the data to be compressed, with the most commonly + used strings preferably put towards the end of the dictionary. Using a + dictionary is most useful when the data to be compressed is short and can be + predicted with good accuracy; the data can then be compressed better than + with the default empty dictionary. + + Depending on the size of the compression data structures selected by + deflateInit or deflateInit2, a part of the dictionary may in effect be + discarded, for example if the dictionary is larger than the window size + provided in deflateInit or deflateInit2. Thus the strings most likely to be + useful should be put at the end of the dictionary, not at the front. In + addition, the current implementation of deflate will use at most the window + size minus 262 bytes of the provided dictionary. + + Upon return of this function, strm->adler is set to the adler32 value + of the dictionary; the decompressor may later use this value to determine + which dictionary has been used by the compressor. (The adler32 value + applies to the whole dictionary even if only a subset of the dictionary is + actually used by the compressor.) If a raw deflate was requested, then the + adler32 value is not computed and strm->adler is not set. + + deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a + parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is + inconsistent (for example if deflate has already been called for this stream + or if the compression method is bsort). deflateSetDictionary does not + perform any compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when several compression strategies will be + tried, for example when there are several ways of pre-processing the input + data with a filter. The streams that will be discarded should then be freed + by calling deflateEnd. Note that deflateCopy duplicates the internal + compression state which can be quite large, so this strategy is slow and can + consume lots of memory. + + deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being Z_NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); +/* + This function is equivalent to deflateEnd followed by deflateInit, + but does not free and reallocate all the internal compression state. The + stream will keep the same compression level and any other attributes that + may have been set by deflateInit2. + + deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). +*/ + +ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, + int level, + int strategy)); +/* + Dynamically update the compression level and compression strategy. The + interpretation of level and strategy is as in deflateInit2. This can be + used to switch between compression and straight copy of the input data, or + to switch to a different kind of input data requiring a different strategy. + If the compression level is changed, the input available so far is + compressed with the old level (and may be flushed); the new level will take + effect only at the next call of deflate(). + + Before the call of deflateParams, the stream state must be set as for + a call of deflate(), since the currently available input may have to be + compressed and flushed. In particular, strm->avail_out must be non-zero. + + deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source + stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR if + strm->avail_out was zero. +*/ + +ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, + int good_length, + int max_lazy, + int nice_length, + int max_chain)); +/* + Fine tune deflate's internal compression parameters. This should only be + used by someone who understands the algorithm used by zlib's deflate for + searching for the best matching string, and even then only by the most + fanatic optimizer trying to squeeze out the last compressed bit for their + specific input data. Read the deflate.c source code for the meaning of the + max_lazy, good_length, nice_length, and max_chain parameters. + + deflateTune() can be called after deflateInit() or deflateInit2(), and + returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. + */ + +ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, + uLong sourceLen)); +/* + deflateBound() returns an upper bound on the compressed size after + deflation of sourceLen bytes. It must be called after deflateInit() or + deflateInit2(), and after deflateSetHeader(), if used. This would be used + to allocate an output buffer for deflation in a single pass, and so would be + called before deflate(). +*/ + +ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + deflatePrime() inserts bits in the deflate output stream. The intent + is that this function is used to start off the deflate output with the bits + leftover from a previous deflate stream when appending to it. As such, this + function can only be used for raw deflate, and must be used before the first + deflate() call after a deflateInit2() or deflateReset(). bits must be less + than or equal to 16, and that many of the least significant bits of value + will be inserted in the output. + + deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, + gz_headerp head)); +/* + deflateSetHeader() provides gzip header information for when a gzip + stream is requested by deflateInit2(). deflateSetHeader() may be called + after deflateInit2() or deflateReset() and before the first call of + deflate(). The text, time, os, extra field, name, and comment information + in the provided gz_header structure are written to the gzip header (xflag is + ignored -- the extra flags are set according to the compression level). The + caller must assure that, if not Z_NULL, name and comment are terminated with + a zero byte, and that if extra is not Z_NULL, that extra_len bytes are + available there. If hcrc is true, a gzip header crc is included. Note that + the current versions of the command-line version of gzip (up through version + 1.3.x) do not support header crc's, and will report that it is a "multi-part + gzip file" and give up. + + If deflateSetHeader is not used, the default gzip header has text false, + the time set to zero, and os set to 255, with no extra, name, or comment + fields. The gzip header is returned to the default state by deflateReset(). + + deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, + int windowBits)); + + This is another version of inflateInit with an extra parameter. The + fields next_in, avail_in, zalloc, zfree and opaque must be initialized + before by the caller. + + The windowBits parameter is the base two logarithm of the maximum window + size (the size of the history buffer). It should be in the range 8..15 for + this version of the library. The default value is 15 if inflateInit is used + instead. windowBits must be greater than or equal to the windowBits value + provided to deflateInit2() while compressing, or it must be equal to 15 if + deflateInit2() was not used. If a compressed stream with a larger window + size is given as input, inflate() will return with the error code + Z_DATA_ERROR instead of trying to allocate a larger window. + + windowBits can also be zero to request that inflate use the window size in + the zlib header of the compressed stream. + + windowBits can also be -8..-15 for raw inflate. In this case, -windowBits + determines the window size. inflate() will then process raw deflate data, + not looking for a zlib or gzip header, not generating a check value, and not + looking for any check values for comparison at the end of the stream. This + is for use with other formats that use the deflate compressed data format + such as zip. Those formats provide their own check values. If a custom + format is developed using the raw deflate format for compressed data, it is + recommended that a check value such as an adler32 or a crc32 be applied to + the uncompressed data as is done in the zlib, gzip, and zip formats. For + most applications, the zlib format should be used as is. Note that comments + above on the use in deflateInit2() applies to the magnitude of windowBits. + + windowBits can also be greater than 15 for optional gzip decoding. Add + 32 to windowBits to enable zlib and gzip decoding with automatic header + detection, or add 16 to decode only the gzip format (the zlib format will + return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a + crc32 instead of an adler32. + + inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller, or Z_STREAM_ERROR if the parameters are + invalid, such as a null pointer to the structure. msg is set to null if + there is no error message. inflateInit2 does not perform any decompression + apart from possibly reading the zlib header if present: actual decompression + will be done by inflate(). (So next_in and avail_in may be modified, but + next_out and avail_out are unused and unchanged.) The current implementation + of inflateInit2() does not process any header information -- that is + deferred until inflate() is called. +*/ + +ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the decompression dictionary from the given uncompressed byte + sequence. This function must be called immediately after a call of inflate, + if that call returned Z_NEED_DICT. The dictionary chosen by the compressor + can be determined from the adler32 value returned by that call of inflate. + The compressor and decompressor must use exactly the same dictionary (see + deflateSetDictionary). For raw inflate, this function can be called + immediately after inflateInit2() or inflateReset() and before any call of + inflate() to set the dictionary. The application must insure that the + dictionary that was used for compression is provided. + + inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a + parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is + inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the + expected one (incorrect adler32 value). inflateSetDictionary does not + perform any decompression: this will be done by subsequent calls of + inflate(). +*/ + +ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); +/* + Skips invalid compressed data until a full flush point (see above the + description of deflate with Z_FULL_FLUSH) can be found, or until all + available input is skipped. No output is provided. + + inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR + if no more input was provided, Z_DATA_ERROR if no flush point has been + found, or Z_STREAM_ERROR if the stream structure was inconsistent. In the + success case, the application may save the current current value of total_in + which indicates where valid compressed data was found. In the error case, + the application may repeatedly call inflateSync, providing more input each + time, until success or end of the input data. +*/ + +ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when randomly accessing a large stream. The + first pass through the stream can periodically record the inflate state, + allowing restarting inflate at those points when randomly accessing the + stream. + + inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being Z_NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); +/* + This function is equivalent to inflateEnd followed by inflateInit, + but does not free and reallocate all the internal decompression state. The + stream will keep attributes that may have been set by inflateInit2. + + inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). +*/ + +ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm, + int windowBits)); +/* + This function is the same as inflateReset, but it also permits changing + the wrap and window size requests. The windowBits parameter is interpreted + the same as it is for inflateInit2. + + inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL), or if + the windowBits parameter is invalid. +*/ + +ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + This function inserts bits in the inflate input stream. The intent is + that this function is used to start inflating at a bit position in the + middle of a byte. The provided bits will be used before any bytes are used + from next_in. This function should only be used with raw inflate, and + should be used before the first inflate() call after inflateInit2() or + inflateReset(). bits must be less than or equal to 16, and that many of the + least significant bits of value will be inserted in the input. + + If bits is negative, then the input stream bit buffer is emptied. Then + inflatePrime() can be called again to put bits in the buffer. This is used + to clear out bits leftover after feeding inflate a block description prior + to feeding inflate codes. + + inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm)); +/* + This function returns two values, one in the lower 16 bits of the return + value, and the other in the remaining upper bits, obtained by shifting the + return value down 16 bits. If the upper value is -1 and the lower value is + zero, then inflate() is currently decoding information outside of a block. + If the upper value is -1 and the lower value is non-zero, then inflate is in + the middle of a stored block, with the lower value equaling the number of + bytes from the input remaining to copy. If the upper value is not -1, then + it is the number of bits back from the current bit position in the input of + the code (literal or length/distance pair) currently being processed. In + that case the lower value is the number of bytes already emitted for that + code. + + A code is being processed if inflate is waiting for more input to complete + decoding of the code, or if it has completed decoding but is waiting for + more output space to write the literal or match data. + + inflateMark() is used to mark locations in the input data for random + access, which may be at bit positions, and to note those cases where the + output of a code may span boundaries of random access blocks. The current + location in the input stream can be determined from avail_in and data_type + as noted in the description for the Z_BLOCK flush parameter for inflate. + + inflateMark returns the value noted above or -1 << 16 if the provided + source stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, + gz_headerp head)); +/* + inflateGetHeader() requests that gzip header information be stored in the + provided gz_header structure. inflateGetHeader() may be called after + inflateInit2() or inflateReset(), and before the first call of inflate(). + As inflate() processes the gzip stream, head->done is zero until the header + is completed, at which time head->done is set to one. If a zlib stream is + being decoded, then head->done is set to -1 to indicate that there will be + no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be + used to force inflate() to return immediately after header processing is + complete and before any actual data is decompressed. + + The text, time, xflags, and os fields are filled in with the gzip header + contents. hcrc is set to true if there is a header CRC. (The header CRC + was valid if done is set to one.) If extra is not Z_NULL, then extra_max + contains the maximum number of bytes to write to extra. Once done is true, + extra_len contains the actual extra field length, and extra contains the + extra field, or that field truncated if extra_max is less than extra_len. + If name is not Z_NULL, then up to name_max characters are written there, + terminated with a zero unless the length is greater than name_max. If + comment is not Z_NULL, then up to comm_max characters are written there, + terminated with a zero unless the length is greater than comm_max. When any + of extra, name, or comment are not Z_NULL and the respective field is not + present in the header, then that field is set to Z_NULL to signal its + absence. This allows the use of deflateSetHeader() with the returned + structure to duplicate the header. However if those fields are set to + allocated memory, then the application will need to save those pointers + elsewhere so that they can be eventually freed. + + If inflateGetHeader is not used, then the header information is simply + discarded. The header is always checked for validity, including the header + CRC if present. inflateReset() will reset the process to discard the header + information. The application would need to call inflateGetHeader() again to + retrieve the header from the next gzip stream. + + inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, + unsigned char FAR *window)); + + Initialize the internal stream state for decompression using inflateBack() + calls. The fields zalloc, zfree and opaque in strm must be initialized + before the call. If zalloc and zfree are Z_NULL, then the default library- + derived memory allocation routines are used. windowBits is the base two + logarithm of the window size, in the range 8..15. window is a caller + supplied buffer of that size. Except for special applications where it is + assured that deflate was used with small window sizes, windowBits must be 15 + and a 32K byte window must be supplied to be able to decompress general + deflate streams. + + See inflateBack() for the usage of these routines. + + inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of + the paramaters are invalid, Z_MEM_ERROR if the internal state could not be + allocated, or Z_VERSION_ERROR if the version of the library does not match + the version of the header file. +*/ + +typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *)); +typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); + +ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, + in_func in, void FAR *in_desc, + out_func out, void FAR *out_desc)); +/* + inflateBack() does a raw inflate with a single call using a call-back + interface for input and output. This is more efficient than inflate() for + file i/o applications in that it avoids copying between the output and the + sliding window by simply making the window itself the output buffer. This + function trusts the application to not change the output buffer passed by + the output function, at least until inflateBack() returns. + + inflateBackInit() must be called first to allocate the internal state + and to initialize the state with the user-provided window buffer. + inflateBack() may then be used multiple times to inflate a complete, raw + deflate stream with each call. inflateBackEnd() is then called to free the + allocated state. + + A raw deflate stream is one with no zlib or gzip header or trailer. + This routine would normally be used in a utility that reads zip or gzip + files and writes out uncompressed files. The utility would decode the + header and process the trailer on its own, hence this routine expects only + the raw deflate stream to decompress. This is different from the normal + behavior of inflate(), which expects either a zlib or gzip header and + trailer around the deflate stream. + + inflateBack() uses two subroutines supplied by the caller that are then + called by inflateBack() for input and output. inflateBack() calls those + routines until it reads a complete deflate stream and writes out all of the + uncompressed data, or until it encounters an error. The function's + parameters and return types are defined above in the in_func and out_func + typedefs. inflateBack() will call in(in_desc, &buf) which should return the + number of bytes of provided input, and a pointer to that input in buf. If + there is no input available, in() must return zero--buf is ignored in that + case--and inflateBack() will return a buffer error. inflateBack() will call + out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() + should return zero on success, or non-zero on failure. If out() returns + non-zero, inflateBack() will return with an error. Neither in() nor out() + are permitted to change the contents of the window provided to + inflateBackInit(), which is also the buffer that out() uses to write from. + The length written by out() will be at most the window size. Any non-zero + amount of input may be provided by in(). + + For convenience, inflateBack() can be provided input on the first call by + setting strm->next_in and strm->avail_in. If that input is exhausted, then + in() will be called. Therefore strm->next_in must be initialized before + calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called + immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in + must also be initialized, and then if strm->avail_in is not zero, input will + initially be taken from strm->next_in[0 .. strm->avail_in - 1]. + + The in_desc and out_desc parameters of inflateBack() is passed as the + first parameter of in() and out() respectively when they are called. These + descriptors can be optionally used to pass any information that the caller- + supplied in() and out() functions need to do their job. + + On return, inflateBack() will set strm->next_in and strm->avail_in to + pass back any unused input that was provided by the last in() call. The + return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR + if in() or out() returned an error, Z_DATA_ERROR if there was a format error + in the deflate stream (in which case strm->msg is set to indicate the nature + of the error), or Z_STREAM_ERROR if the stream was not properly initialized. + In the case of Z_BUF_ERROR, an input or output error can be distinguished + using strm->next_in which will be Z_NULL only if in() returned an error. If + strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning + non-zero. (in() will always be called before out(), so strm->next_in is + assured to be defined if out() returns non-zero.) Note that inflateBack() + cannot return Z_OK. +*/ + +ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); +/* + All memory allocated by inflateBackInit() is freed. + + inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream + state was inconsistent. +*/ + +ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); +/* Return flags indicating compile-time options. + + Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: + 1.0: size of uInt + 3.2: size of uLong + 5.4: size of voidpf (pointer) + 7.6: size of z_off_t + + Compiler, assembler, and debug options: + 8: DEBUG + 9: ASMV or ASMINF -- use ASM code + 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention + 11: 0 (reserved) + + One-time table building (smaller code, but not thread-safe if true): + 12: BUILDFIXED -- build static block decoding tables when needed + 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed + 14,15: 0 (reserved) + + Library content (indicates missing functionality): + 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking + deflate code when not needed) + 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect + and decode gzip streams (to avoid linking crc code) + 18-19: 0 (reserved) + + Operation variations (changes in library functionality): + 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate + 21: FASTEST -- deflate algorithm with only one, lowest compression level + 22,23: 0 (reserved) + + The sprintf variant used by gzprintf (zero is best): + 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format + 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! + 26: 0 = returns value, 1 = void -- 1 means inferred string length returned + + Remainder: + 27-31: 0 (reserved) + */ + + + /* utility functions */ + +/* + The following utility functions are implemented on top of the basic + stream-oriented functions. To simplify the interface, some default options + are assumed (compression level and memory usage, standard memory allocation + functions). The source code of these utility functions can be modified if + you need special options. +*/ + +ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Compresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size + of the destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed buffer. + + compress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer. +*/ + +ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen, + int level)); +/* + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed buffer. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ + +ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); +/* + compressBound() returns an upper bound on the compressed size after + compress() or compress2() on sourceLen bytes. It would be used before a + compress() or compress2() call to allocate the destination buffer. +*/ + +ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Decompresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size + of the destination buffer, which must be large enough to hold the entire + uncompressed data. (The size of the uncompressed data must have been saved + previously by the compressor and transmitted to the decompressor by some + mechanism outside the scope of this compression library.) Upon exit, destLen + is the actual size of the uncompressed buffer. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. +*/ + + + /* gzip file access functions */ + +/* + This library supports reading and writing files in gzip (.gz) format with + an interface similar to that of stdio, using the functions that start with + "gz". The gzip format is different from the zlib format. gzip is a gzip + wrapper, documented in RFC 1952, wrapped around a deflate stream. +*/ + +typedef voidp gzFile; /* opaque gzip file descriptor */ + +/* +ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); + + Opens a gzip (.gz) file for reading or writing. The mode parameter is as + in fopen ("rb" or "wb") but can also include a compression level ("wb9") or + a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only + compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F' + for fixed code compression as in "wb9F". (See the description of + deflateInit2 for more information about the strategy parameter.) Also "a" + can be used instead of "w" to request that the gzip stream that will be + written be appended to the file. "+" will result in an error, since reading + and writing to the same gzip file is not supported. + + gzopen can be used to read a file which is not in gzip format; in this + case gzread will directly read from the file without decompression. + + gzopen returns NULL if the file could not be opened, if there was + insufficient memory to allocate the gzFile state, or if an invalid mode was + specified (an 'r', 'w', or 'a' was not provided, or '+' was provided). + errno can be checked to determine if the reason gzopen failed was that the + file could not be opened. +*/ + +ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); +/* + gzdopen associates a gzFile with the file descriptor fd. File descriptors + are obtained from calls like open, dup, creat, pipe or fileno (if the file + has been previously opened with fopen). The mode parameter is as in gzopen. + + The next call of gzclose on the returned gzFile will also close the file + descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor + fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, + mode);. The duplicated descriptor should be saved to avoid a leak, since + gzdopen does not close fd if it fails. + + gzdopen returns NULL if there was insufficient memory to allocate the + gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not + provided, or '+' was provided), or if fd is -1. The file descriptor is not + used until the next gz* read, write, seek, or close operation, so gzdopen + will not detect if fd is invalid (unless fd is -1). +*/ + +ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size)); +/* + Set the internal buffer size used by this library's functions. The + default buffer size is 8192 bytes. This function must be called after + gzopen() or gzdopen(), and before any other calls that read or write the + file. The buffer memory allocation is always deferred to the first read or + write. Two buffers are allocated, either both of the specified size when + writing, or one of the specified size and the other twice that size when + reading. A larger buffer size of, for example, 64K or 128K bytes will + noticeably increase the speed of decompression (reading). + + The new buffer size also affects the maximum length for gzprintf(). + + gzbuffer() returns 0 on success, or -1 on failure, such as being called + too late. +*/ + +ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); +/* + Dynamically update the compression level or strategy. See the description + of deflateInit2 for the meaning of these parameters. + + gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not + opened for writing. +*/ + +ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); +/* + Reads the given number of uncompressed bytes from the compressed file. If + the input file was not in gzip format, gzread copies the given number of + bytes into the buffer. + + After reaching the end of a gzip stream in the input, gzread will continue + to read, looking for another gzip stream, or failing that, reading the rest + of the input file directly without decompression. The entire input file + will be read if gzread is called until it returns less than the requested + len. + + gzread returns the number of uncompressed bytes actually read, less than + len for end of file, or -1 for error. +*/ + +ZEXTERN int ZEXPORT gzwrite OF((gzFile file, + voidpc buf, unsigned len)); +/* + Writes the given number of uncompressed bytes into the compressed file. + gzwrite returns the number of uncompressed bytes written or 0 in case of + error. +*/ + +ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...)); +/* + Converts, formats, and writes the arguments to the compressed file under + control of the format string, as in fprintf. gzprintf returns the number of + uncompressed bytes actually written, or 0 in case of error. The number of + uncompressed bytes written is limited to 8191, or one less than the buffer + size given to gzbuffer(). The caller should assure that this limit is not + exceeded. If it is exceeded, then gzprintf() will return an error (0) with + nothing written. In this case, there may also be a buffer overflow with + unpredictable consequences, which is possible only if zlib was compiled with + the insecure functions sprintf() or vsprintf() because the secure snprintf() + or vsnprintf() functions were not available. This can be determined using + zlibCompileFlags(). +*/ + +ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); +/* + Writes the given null-terminated string to the compressed file, excluding + the terminating null character. + + gzputs returns the number of characters written, or -1 in case of error. +*/ + +ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); +/* + Reads bytes from the compressed file until len-1 characters are read, or a + newline character is read and transferred to buf, or an end-of-file + condition is encountered. If any characters are read or if len == 1, the + string is terminated with a null character. If no characters are read due + to an end-of-file or len < 1, then the buffer is left untouched. + + gzgets returns buf which is a null-terminated string, or it returns NULL + for end-of-file or in case of error. If there was an error, the contents at + buf are indeterminate. +*/ + +ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); +/* + Writes c, converted to an unsigned char, into the compressed file. gzputc + returns the value that was written, or -1 in case of error. +*/ + +ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); +/* + Reads one byte from the compressed file. gzgetc returns this byte or -1 + in case of end of file or error. +*/ + +ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); +/* + Push one character back onto the stream to be read as the first character + on the next read. At least one character of push-back is allowed. + gzungetc() returns the character pushed, or -1 on failure. gzungetc() will + fail if c is -1, and may fail if a character has been pushed but not read + yet. If gzungetc is used immediately after gzopen or gzdopen, at least the + output buffer size of pushed characters is allowed. (See gzbuffer above.) + The pushed character will be discarded if the stream is repositioned with + gzseek() or gzrewind(). +*/ + +ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); +/* + Flushes all pending output into the compressed file. The parameter flush + is as in the deflate() function. The return value is the zlib error number + (see function gzerror below). gzflush is only permitted when writing. + + If the flush parameter is Z_FINISH, the remaining data is written and the + gzip stream is completed in the output. If gzwrite() is called again, a new + gzip stream will be started in the output. gzread() is able to read such + concatented gzip streams. + + gzflush should be called only when strictly necessary because it will + degrade compression if called too often. +*/ + +/* +ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, + z_off_t offset, int whence)); + + Sets the starting position for the next gzread or gzwrite on the given + compressed file. The offset represents a number of bytes in the + uncompressed data stream. The whence parameter is defined as in lseek(2); + the value SEEK_END is not supported. + + If the file is opened for reading, this function is emulated but can be + extremely slow. If the file is opened for writing, only forward seeks are + supported; gzseek then compresses a sequence of zeroes up to the new + starting position. + + gzseek returns the resulting offset location as measured in bytes from + the beginning of the uncompressed stream, or -1 in case of error, in + particular if the file is opened for writing and the new starting position + would be before the current position. +*/ + +ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); +/* + Rewinds the given file. This function is supported only for reading. + + gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) +*/ + +/* +ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); + + Returns the starting position for the next gzread or gzwrite on the given + compressed file. This position represents a number of bytes in the + uncompressed data stream, and is zero when starting, even if appending or + reading a gzip stream from the middle of a file using gzdopen(). + + gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) +*/ + +/* +ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file)); + + Returns the current offset in the file being read or written. This offset + includes the count of bytes that precede the gzip stream, for example when + appending or when using gzdopen() for reading. When reading, the offset + does not include as yet unused buffered input. This information can be used + for a progress indicator. On error, gzoffset() returns -1. +*/ + +ZEXTERN int ZEXPORT gzeof OF((gzFile file)); +/* + Returns true (1) if the end-of-file indicator has been set while reading, + false (0) otherwise. Note that the end-of-file indicator is set only if the + read tried to go past the end of the input, but came up short. Therefore, + just like feof(), gzeof() may return false even if there is no more data to + read, in the event that the last read request was for the exact number of + bytes remaining in the input file. This will happen if the input file size + is an exact multiple of the buffer size. + + If gzeof() returns true, then the read functions will return no more data, + unless the end-of-file indicator is reset by gzclearerr() and the input file + has grown since the previous end of file was detected. +*/ + +ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); +/* + Returns true (1) if file is being copied directly while reading, or false + (0) if file is a gzip stream being decompressed. This state can change from + false to true while reading the input file if the end of a gzip stream is + reached, but is followed by data that is not another gzip stream. + + If the input file is empty, gzdirect() will return true, since the input + does not contain a gzip stream. + + If gzdirect() is used immediately after gzopen() or gzdopen() it will + cause buffers to be allocated to allow reading the file to determine if it + is a gzip file. Therefore if gzbuffer() is used, it should be called before + gzdirect(). +*/ + +ZEXTERN int ZEXPORT gzclose OF((gzFile file)); +/* + Flushes all pending output if necessary, closes the compressed file and + deallocates the (de)compression state. Note that once file is closed, you + cannot call gzerror with file, since its structures have been deallocated. + gzclose must not be called more than once on the same file, just as free + must not be called more than once on the same allocation. + + gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a + file operation error, or Z_OK on success. +*/ + +ZEXTERN int ZEXPORT gzclose_r OF((gzFile file)); +ZEXTERN int ZEXPORT gzclose_w OF((gzFile file)); +/* + Same as gzclose(), but gzclose_r() is only for use when reading, and + gzclose_w() is only for use when writing or appending. The advantage to + using these instead of gzclose() is that they avoid linking in zlib + compression or decompression code that is not used when only reading or only + writing respectively. If gzclose() is used, then both compression and + decompression code will be included the application when linking to a static + zlib library. +*/ + +ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); +/* + Returns the error message for the last error which occurred on the given + compressed file. errnum is set to zlib error number. If an error occurred + in the file system and not in the compression library, errnum is set to + Z_ERRNO and the application may consult errno to get the exact error code. + + The application must not modify the returned string. Future calls to + this function may invalidate the previously returned string. If file is + closed, then the string previously returned by gzerror will no longer be + available. + + gzerror() should be used to distinguish errors from end-of-file for those + functions above that do not distinguish those cases in their return values. +*/ + +ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); +/* + Clears the error and end-of-file flags for file. This is analogous to the + clearerr() function in stdio. This is useful for continuing to read a gzip + file that is being written concurrently. +*/ + + + /* checksum functions */ + +/* + These functions are not related to compression but are exported + anyway because they might be useful in applications using the compression + library. +*/ + +ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); +/* + Update a running Adler-32 checksum with the bytes buf[0..len-1] and + return the updated checksum. If buf is Z_NULL, this function returns the + required initial value for the checksum. + + An Adler-32 checksum is almost as reliable as a CRC32 but can be computed + much faster. + + Usage example: + + uLong adler = adler32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + adler = adler32(adler, buffer, length); + } + if (adler != original_adler) error(); +*/ + +/* +ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, + z_off_t len2)); + + Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 + and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for + each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of + seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. +*/ + +ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); +/* + Update a running CRC-32 with the bytes buf[0..len-1] and return the + updated CRC-32. If buf is Z_NULL, this function returns the required + initial value for the for the crc. Pre- and post-conditioning (one's + complement) is performed within this function so it shouldn't be done by the + application. + + Usage example: + + uLong crc = crc32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + crc = crc32(crc, buffer, length); + } + if (crc != original_crc) error(); +*/ + +/* +ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); + + Combine two CRC-32 check values into one. For two sequences of bytes, + seq1 and seq2 with lengths len1 and len2, CRC-32 check values were + calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 + check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and + len2. +*/ + + + /* various hacks, don't look :) */ + +/* deflateInit and inflateInit are macros to allow checking the zlib version + * and the compiler's view of z_stream: + */ +ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, + int windowBits, int memLevel, + int strategy, const char *version, + int stream_size)); +ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, + unsigned char FAR *window, + const char *version, + int stream_size)); +#define deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream)) +#define inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream)) +#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ + (strategy), ZLIB_VERSION, sizeof(z_stream)) +#define inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream)) +#define inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, sizeof(z_stream)) + +/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or + * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if + * both are true, the application gets the *64 functions, and the regular + * functions are changed to 64 bits) -- in case these are set on systems + * without large file support, _LFS64_LARGEFILE must also be true + */ +#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); + ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t)); +#endif + +#if !defined(ZLIB_INTERNAL) && _FILE_OFFSET_BITS-0 == 64 && _LFS64_LARGEFILE-0 +# define gzopen gzopen64 +# define gzseek gzseek64 +# define gztell gztell64 +# define gzoffset gzoffset64 +# define adler32_combine adler32_combine64 +# define crc32_combine crc32_combine64 +# ifdef _LARGEFILE64_SOURCE + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int)); + ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); +# endif +#else + ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *)); + ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int)); + ZEXTERN z_off_t ZEXPORT gztell OF((gzFile)); + ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); +#endif + +/* hack for buggy compilers */ +#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL) + struct internal_state {int dummy;}; +#endif + +/* undocumented functions */ +ZEXTERN const char * ZEXPORT zError OF((int)); +ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp)); +ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void)); +ZEXTERN int ZEXPORT inflateUndermine OF((z_streamp, int)); + +#ifdef __cplusplus +} +#endif + +#endif /* ZLIB_H */ diff --git a/dep/zlib/zutil.c b/dep/zlib/zutil.c new file mode 100644 index 00000000000..898ed345b0e --- /dev/null +++ b/dep/zlib/zutil.c @@ -0,0 +1,318 @@ +/* zutil.c -- target dependent utility functions for the compression library + * Copyright (C) 1995-2005, 2010 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#include "zutil.h" + +#ifndef NO_DUMMY_DECL +struct internal_state {int dummy;}; /* for buggy compilers */ +#endif + +const char * const z_errmsg[10] = { +"need dictionary", /* Z_NEED_DICT 2 */ +"stream end", /* Z_STREAM_END 1 */ +"", /* Z_OK 0 */ +"file error", /* Z_ERRNO (-1) */ +"stream error", /* Z_STREAM_ERROR (-2) */ +"data error", /* Z_DATA_ERROR (-3) */ +"insufficient memory", /* Z_MEM_ERROR (-4) */ +"buffer error", /* Z_BUF_ERROR (-5) */ +"incompatible version",/* Z_VERSION_ERROR (-6) */ +""}; + + +const char * ZEXPORT zlibVersion() +{ + return ZLIB_VERSION; +} + +uLong ZEXPORT zlibCompileFlags() +{ + uLong flags; + + flags = 0; + switch ((int)(sizeof(uInt))) { + case 2: break; + case 4: flags += 1; break; + case 8: flags += 2; break; + default: flags += 3; + } + switch ((int)(sizeof(uLong))) { + case 2: break; + case 4: flags += 1 << 2; break; + case 8: flags += 2 << 2; break; + default: flags += 3 << 2; + } + switch ((int)(sizeof(voidpf))) { + case 2: break; + case 4: flags += 1 << 4; break; + case 8: flags += 2 << 4; break; + default: flags += 3 << 4; + } + switch ((int)(sizeof(z_off_t))) { + case 2: break; + case 4: flags += 1 << 6; break; + case 8: flags += 2 << 6; break; + default: flags += 3 << 6; + } +#ifdef DEBUG + flags += 1 << 8; +#endif +#if defined(ASMV) || defined(ASMINF) + flags += 1 << 9; +#endif +#ifdef ZLIB_WINAPI + flags += 1 << 10; +#endif +#ifdef BUILDFIXED + flags += 1 << 12; +#endif +#ifdef DYNAMIC_CRC_TABLE + flags += 1 << 13; +#endif +#ifdef NO_GZCOMPRESS + flags += 1L << 16; +#endif +#ifdef NO_GZIP + flags += 1L << 17; +#endif +#ifdef PKZIP_BUG_WORKAROUND + flags += 1L << 20; +#endif +#ifdef FASTEST + flags += 1L << 21; +#endif +#ifdef STDC +# ifdef NO_vsnprintf + flags += 1L << 25; +# ifdef HAS_vsprintf_void + flags += 1L << 26; +# endif +# else +# ifdef HAS_vsnprintf_void + flags += 1L << 26; +# endif +# endif +#else + flags += 1L << 24; +# ifdef NO_snprintf + flags += 1L << 25; +# ifdef HAS_sprintf_void + flags += 1L << 26; +# endif +# else +# ifdef HAS_snprintf_void + flags += 1L << 26; +# endif +# endif +#endif + return flags; +} + +#ifdef DEBUG + +# ifndef verbose +# define verbose 0 +# endif +int ZLIB_INTERNAL z_verbose = verbose; + +void ZLIB_INTERNAL z_error (m) + char *m; +{ + fprintf(stderr, "%s\n", m); + exit(1); +} +#endif + +/* exported to allow conversion of error code to string for compress() and + * uncompress() + */ +const char * ZEXPORT zError(err) + int err; +{ + return ERR_MSG(err); +} + +#if defined(_WIN32_WCE) + /* The Microsoft C Run-Time Library for Windows CE doesn't have + * errno. We define it as a global variable to simplify porting. + * Its value is always 0 and should not be used. + */ + int errno = 0; +#endif + +#ifndef HAVE_MEMCPY + +void ZLIB_INTERNAL zmemcpy(dest, source, len) + Bytef* dest; + const Bytef* source; + uInt len; +{ + if (len == 0) return; + do { + *dest++ = *source++; /* ??? to be unrolled */ + } while (--len != 0); +} + +int ZLIB_INTERNAL zmemcmp(s1, s2, len) + const Bytef* s1; + const Bytef* s2; + uInt len; +{ + uInt j; + + for (j = 0; j < len; j++) { + if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1; + } + return 0; +} + +void ZLIB_INTERNAL zmemzero(dest, len) + Bytef* dest; + uInt len; +{ + if (len == 0) return; + do { + *dest++ = 0; /* ??? to be unrolled */ + } while (--len != 0); +} +#endif + + +#ifdef SYS16BIT + +#ifdef __TURBOC__ +/* Turbo C in 16-bit mode */ + +# define MY_ZCALLOC + +/* Turbo C malloc() does not allow dynamic allocation of 64K bytes + * and farmalloc(64K) returns a pointer with an offset of 8, so we + * must fix the pointer. Warning: the pointer must be put back to its + * original form in order to free it, use zcfree(). + */ + +#define MAX_PTR 10 +/* 10*64K = 640K */ + +local int next_ptr = 0; + +typedef struct ptr_table_s { + voidpf org_ptr; + voidpf new_ptr; +} ptr_table; + +local ptr_table table[MAX_PTR]; +/* This table is used to remember the original form of pointers + * to large buffers (64K). Such pointers are normalized with a zero offset. + * Since MSDOS is not a preemptive multitasking OS, this table is not + * protected from concurrent access. This hack doesn't work anyway on + * a protected system like OS/2. Use Microsoft C instead. + */ + +voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, unsigned size) +{ + voidpf buf = opaque; /* just to make some compilers happy */ + ulg bsize = (ulg)items*size; + + /* If we allocate less than 65520 bytes, we assume that farmalloc + * will return a usable pointer which doesn't have to be normalized. + */ + if (bsize < 65520L) { + buf = farmalloc(bsize); + if (*(ush*)&buf != 0) return buf; + } else { + buf = farmalloc(bsize + 16L); + } + if (buf == NULL || next_ptr >= MAX_PTR) return NULL; + table[next_ptr].org_ptr = buf; + + /* Normalize the pointer to seg:0 */ + *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4; + *(ush*)&buf = 0; + table[next_ptr++].new_ptr = buf; + return buf; +} + +void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) +{ + int n; + if (*(ush*)&ptr != 0) { /* object < 64K */ + farfree(ptr); + return; + } + /* Find the original pointer */ + for (n = 0; n < next_ptr; n++) { + if (ptr != table[n].new_ptr) continue; + + farfree(table[n].org_ptr); + while (++n < next_ptr) { + table[n-1] = table[n]; + } + next_ptr--; + return; + } + ptr = opaque; /* just to make some compilers happy */ + Assert(0, "zcfree: ptr not found"); +} + +#endif /* __TURBOC__ */ + + +#ifdef M_I86 +/* Microsoft C in 16-bit mode */ + +# define MY_ZCALLOC + +#if (!defined(_MSC_VER) || (_MSC_VER <= 600)) +# define _halloc halloc +# define _hfree hfree +#endif + +voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, uInt items, uInt size) +{ + if (opaque) opaque = 0; /* to make compiler happy */ + return _halloc((long)items, size); +} + +void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) +{ + if (opaque) opaque = 0; /* to make compiler happy */ + _hfree(ptr); +} + +#endif /* M_I86 */ + +#endif /* SYS16BIT */ + + +#ifndef MY_ZCALLOC /* Any system without a special alloc function */ + +#ifndef STDC +extern voidp malloc OF((uInt size)); +extern voidp calloc OF((uInt items, uInt size)); +extern void free OF((voidpf ptr)); +#endif + +voidpf ZLIB_INTERNAL zcalloc (opaque, items, size) + voidpf opaque; + unsigned items; + unsigned size; +{ + if (opaque) items += size - size; /* make compiler happy */ + return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) : + (voidpf)calloc(items, size); +} + +void ZLIB_INTERNAL zcfree (opaque, ptr) + voidpf opaque; + voidpf ptr; +{ + free(ptr); + if (opaque) return; /* make compiler happy */ +} + +#endif /* MY_ZCALLOC */ diff --git a/dep/zlib/zutil.h b/dep/zlib/zutil.h new file mode 100644 index 00000000000..258fa88799a --- /dev/null +++ b/dep/zlib/zutil.h @@ -0,0 +1,274 @@ +/* zutil.h -- internal interface and configuration of the compression library + * Copyright (C) 1995-2010 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* @(#) $Id$ */ + +#ifndef ZUTIL_H +#define ZUTIL_H + +#if ((__GNUC__-0) * 10 + __GNUC_MINOR__-0 >= 33) && !defined(NO_VIZ) +# define ZLIB_INTERNAL __attribute__((visibility ("hidden"))) +#else +# define ZLIB_INTERNAL +#endif + +#include "zlib.h" + +#ifdef STDC +# if !(defined(_WIN32_WCE) && defined(_MSC_VER)) +# include +# endif +# include +# include +#endif + +#ifndef local +# define local static +#endif +/* compile with -Dlocal if your debugger can't find static symbols */ + +typedef unsigned char uch; +typedef uch FAR uchf; +typedef unsigned short ush; +typedef ush FAR ushf; +typedef unsigned long ulg; + +extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ +/* (size given to avoid silly warnings with Visual C++) */ + +#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] + +#define ERR_RETURN(strm,err) \ + return (strm->msg = (char*)ERR_MSG(err), (err)) +/* To be used only when the state is known to be valid */ + + /* common constants */ + +#ifndef DEF_WBITS +# define DEF_WBITS MAX_WBITS +#endif +/* default windowBits for decompression. MAX_WBITS is for compression only */ + +#if MAX_MEM_LEVEL >= 8 +# define DEF_MEM_LEVEL 8 +#else +# define DEF_MEM_LEVEL MAX_MEM_LEVEL +#endif +/* default memLevel */ + +#define STORED_BLOCK 0 +#define STATIC_TREES 1 +#define DYN_TREES 2 +/* The three kinds of block type */ + +#define MIN_MATCH 3 +#define MAX_MATCH 258 +/* The minimum and maximum match lengths */ + +#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ + + /* target dependencies */ + +#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32)) +# define OS_CODE 0x00 +# if defined(__TURBOC__) || defined(__BORLANDC__) +# if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) + /* Allow compilation with ANSI keywords only enabled */ + void _Cdecl farfree( void *block ); + void *_Cdecl farmalloc( unsigned long nbytes ); +# else +# include +# endif +# else /* MSC or DJGPP */ +# include +# endif +#endif + +#ifdef AMIGA +# define OS_CODE 0x01 +#endif + +#if defined(VAXC) || defined(VMS) +# define OS_CODE 0x02 +# define F_OPEN(name, mode) \ + fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512") +#endif + +#if defined(ATARI) || defined(atarist) +# define OS_CODE 0x05 +#endif + +#ifdef OS2 +# define OS_CODE 0x06 +# ifdef M_I86 +# include +# endif +#endif + +#if defined(MACOS) || defined(TARGET_OS_MAC) +# define OS_CODE 0x07 +# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os +# include /* for fdopen */ +# else +# ifndef fdopen +# define fdopen(fd,mode) NULL /* No fdopen() */ +# endif +# endif +#endif + +#ifdef TOPS20 +# define OS_CODE 0x0a +#endif + +#ifdef WIN32 +# ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */ +# define OS_CODE 0x0b +# endif +#endif + +#ifdef __50SERIES /* Prime/PRIMOS */ +# define OS_CODE 0x0f +#endif + +#if defined(_BEOS_) || defined(RISCOS) +# define fdopen(fd,mode) NULL /* No fdopen() */ +#endif + +#if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX +# if defined(_WIN32_WCE) +# define fdopen(fd,mode) NULL /* No fdopen() */ +# ifndef _PTRDIFF_T_DEFINED + typedef int ptrdiff_t; +# define _PTRDIFF_T_DEFINED +# endif +# else +# define fdopen(fd,type) _fdopen(fd,type) +# endif +#endif + +#if defined(__BORLANDC__) + #pragma warn -8004 + #pragma warn -8008 + #pragma warn -8066 +#endif + +/* provide prototypes for these when building zlib without LFS */ +#if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0 + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); +#endif + + /* common defaults */ + +#ifndef OS_CODE +# define OS_CODE 0x03 /* assume Unix */ +#endif + +#ifndef F_OPEN +# define F_OPEN(name, mode) fopen((name), (mode)) +#endif + + /* functions */ + +#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif +#if defined(__CYGWIN__) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif +#ifndef HAVE_VSNPRINTF +# ifdef MSDOS + /* vsnprintf may exist on some MS-DOS compilers (DJGPP?), + but for now we just assume it doesn't. */ +# define NO_vsnprintf +# endif +# ifdef __TURBOC__ +# define NO_vsnprintf +# endif +# ifdef WIN32 + /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */ +# if !defined(vsnprintf) && !defined(NO_vsnprintf) +# if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 ) +# define vsnprintf _vsnprintf +# endif +# endif +# endif +# ifdef __SASC +# define NO_vsnprintf +# endif +#endif +#ifdef VMS +# define NO_vsnprintf +#endif + +#if defined(pyr) +# define NO_MEMCPY +#endif +#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__) + /* Use our own functions for small and medium model with MSC <= 5.0. + * You may have to use the same strategy for Borland C (untested). + * The __SC__ check is for Symantec. + */ +# define NO_MEMCPY +#endif +#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY) +# define HAVE_MEMCPY +#endif +#ifdef HAVE_MEMCPY +# ifdef SMALL_MEDIUM /* MSDOS small or medium model */ +# define zmemcpy _fmemcpy +# define zmemcmp _fmemcmp +# define zmemzero(dest, len) _fmemset(dest, 0, len) +# else +# define zmemcpy memcpy +# define zmemcmp memcmp +# define zmemzero(dest, len) memset(dest, 0, len) +# endif +#else + void ZLIB_INTERNAL zmemcpy OF((Bytef* dest, const Bytef* source, uInt len)); + int ZLIB_INTERNAL zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len)); + void ZLIB_INTERNAL zmemzero OF((Bytef* dest, uInt len)); +#endif + +/* Diagnostic functions */ +#ifdef DEBUG +# include + extern int ZLIB_INTERNAL z_verbose; + extern void ZLIB_INTERNAL z_error OF((char *m)); +# define Assert(cond,msg) {if(!(cond)) z_error(msg);} +# define Trace(x) {if (z_verbose>=0) fprintf x ;} +# define Tracev(x) {if (z_verbose>0) fprintf x ;} +# define Tracevv(x) {if (z_verbose>1) fprintf x ;} +# define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;} +# define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;} +#else +# define Assert(cond,msg) +# define Trace(x) +# define Tracev(x) +# define Tracevv(x) +# define Tracec(c,x) +# define Tracecv(c,x) +#endif + + +voidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items, + unsigned size)); +void ZLIB_INTERNAL zcfree OF((voidpf opaque, voidpf ptr)); + +#define ZALLOC(strm, items, size) \ + (*((strm)->zalloc))((strm)->opaque, (items), (size)) +#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) +#define TRY_FREE(s, p) {if (p) ZFREE(s, p);} + +#endif /* ZUTIL_H */ diff --git a/doc/AuctionHouseBot.txt b/doc/AuctionHouseBot.txt new file mode 100644 index 00000000000..cc15a084c9a --- /dev/null +++ b/doc/AuctionHouseBot.txt @@ -0,0 +1,236 @@ +Populates the auction houses with items. It can make the game feel a bit more +like official on small servers. Items and prices are chosen randomly based on +the parameters you define. If an auction expires, auctions are deleted quietly. +AHBot will not buy it's own items, and will not receive mail from the AH +or get returned mail. + +=============================================================================== +~~HOW TO CONFIGURE~~ +=============================================================================== +Step 1.) Create a character that you are going to use as the auction house bot + character. This character will be the auction's owner for all the + items created by the bot. +Step 2.) Go into the realm database and note the account number for the + character. +Step 3.) Go into the characters database and note the character's GUID. +Step 4.) Log in at least once with this character. + (Do not change the configuration before this) +Step 5.) Tune the configuration options in the configuration file and the + Database. + +#These are the settings in the configuration file: +AuctionHouseBot.DEBUG = 0 +AuctionHouseBot.EnableSeller = 0 +AuctionHouseBot.EnableBuyer = 0 +AuctionHouseBot.UseBuyPriceForSeller = 0 +AuctionHouseBot.UseBuyPriceForBuyer = 0 +AuctionHouseBot.Account = 0 +AuctionHouseBot.GUID = 0 +AuctionHouseBot.ItemsPerCycle = 200 + +AuctionHouseBot.DEBUG enables (1) or disables (0) Debug output +AuctionHouseBot.EnableSeller enables (1) or disables (0) the Seller +AuctionHouseBot.EnableBuyer enables (1) or disables (0) the Buyer +AuctionHouseBot.UseBuyPriceForSeller Use SellPrice (0) or BuyPrice (1) for determining prices +AuctionHouseBot.UseBuyPriceForBuyer Use SellPrice (0) or BuyPrice (1) for determining prices +AuctionHouseBot.Account is the account number (in realmd->account table) of the player you want to run as the auction bot. Note: a value of 0 will disable the bot. +AuctionHouseBot.GUID is the GUID (in characters->characters table) of the player you want to run as the auction bot. Note: a value of 0 will disable the bot. +AuctionHouseBot.ItemsPerCycle determines how many items are added each time AHBot is run (once per minute, by default) + +#These are the Filters For filtering certain items/trade goods from the AH +AuctionHouseBot.VendorItems = 0 +AuctionHouseBot.VendorTradeGoods = 0 +AuctionHouseBot.LootItems = 1 +AuctionHouseBot.LootTradeGoods = 1 +AuctionHouseBot.OtherItems = 0 +AuctionHouseBot.OtherTradeGoods = 0 +AuctionHouseBot.No_Bind = 1 +AuctionHouseBot.Bind_When_Picked_Up = 0 +AuctionHouseBot.Bind_When_Equipped = 1 +AuctionHouseBot.Bind_When_Use = 1 +AuctionHouseBot.Bind_Quest_Item = 0 +AuctionHouseBot.DisableBeta_PTR_Unused = 0 +AuctionHouseBot.DisablePermEnchant = 0 +AuctionHouseBot.DisableConjured = 0 +AuctionHouseBot.DisableGems = 0 +AuctionHouseBot.DisableMoney = 0 +AuctionHouseBot.DisableMoneyLoot = 0 +AuctionHouseBot.DisableLootable = 0 +AuctionHouseBot.DisableKeys = 0 +AuctionHouseBot.DisableDuration = 0 +AuctionHouseBot.DisableBOP_Or_Quest_NoReqLevel = 0 + +AuctionHouseBot.VendorItems is a boolean value (0 or 1) that indicates whether to include Vendor only items +AuctionHouseBot.VendorTradeGoods is a boolean value (0 or 1) that indicates whether to include Vendor only Trade Goods +AuctionHouseBot.LootItems is a boolean value (0 or 1) that indicates whether to include Loot/Fish/Skin/etc. only items +AuctionHouseBot.LootTradeGoods is a boolean value (0 or 1) that indicates whether to include Loot/Fish/Skin/etc. only Trade Goods +AuctionHouseBot.OtherItems is a boolean value (0 or 1) that indicates whether to include Other items not covered by the first 2 +AuctionHouseBot.OtherTradeGoods is a boolean value (0 or 1) that indicates whether to include Other Trade Goods not covered by the first 2 +AuctionHouseBot.No_Bind is a boolean value (0 or 1) that indicates whether to include items with a bonding of 0 +AuctionHouseBot.Bind_When_Picked_Up = is a boolean value (0 or 1) that indicates whether to include items with a bonding of 1 +AuctionHouseBot.Bind_When_Equipped = is a boolean value (0 or 1) that indicates whether to include items with a bonding of 2 +AuctionHouseBot.Bind_When_Use = is a boolean value (0 or 1) that indicates whether to include items with a bonding of 3 +AuctionHouseBot.Bind_Quest_Item = is a boolean value (0 or 1) that indicates whether to include items with a bonding of 4 +AuctionHouseBot.DisableBeta_PTR_Unused is a boolean value (0 or 1) that will Disable certain items that are usually unavailable to Players +AuctionHouseBot.DisablePermEnchant is a boolean value (0 or 1) that will Disable Items with a Permanent Enchantment +AuctionHouseBot.DisableConjured is a boolean value (0 or 1) that will Disable Conjured Items +AuctionHouseBot.DisableGems is a boolean value (0 or 1) that will Disable Gems +AuctionHouseBot.DisableMoney is a boolean value (0 or 1) that will Disable Items that are used as money +AuctionHouseBot.DisableMoneyLoot is a boolean value (0 or 1) that will Disable Items that have Money as a loot +AuctionHouseBot.DisableLootable is a boolean value (0 or 1) that will Disable Items that have other items as loot +AuctionHouseBot.DisableKeys is a boolean value (0 or 1) that will Disable Items that are keys +AuctionHouseBot.DisableDuration is a boolean value (0 or 1) that will Disable Items with a duration +AuctionHouseBot.DisableBOP_Or_Quest_NoReqLevel is a boolean value (0 or 1) that will Disable items that are BOP or Quest Item with a Required level that is less than the Item Level + +#These Filters are boolean (0 or 1) and will disable items that are +#specifically meant for the Class named. +#(UnusedClass is Class 10, which was skipped for some reason) +AuctionHouseBot.DisableWarriorItems = 0 +AuctionHouseBot.DisablePaladinItems = 0 +AuctionHouseBot.DisableHunterItems = 0 +AuctionHouseBot.DisableRogueItems = 0 +AuctionHouseBot.DisablePriestItems = 0 +AuctionHouseBot.DisableDKItems = 0 +AuctionHouseBot.DisableShamanItems = 0 +AuctionHouseBot.DisableMageItems = 0 +AuctionHouseBot.DisableWarlockItems = 0 +AuctionHouseBot.DisableUnusedClassItems = 0 +AuctionHouseBot.DisableDruidItems = 0 + +#These are the Filters For filtering certain items/trade goods from the AH +AuctionHouseBot.DisableItemsBelowLevel = 0 +AuctionHouseBot.DisableItemsAboveLevel = 0 +AuctionHouseBot.DisableTGsBelowLevel = 0 +AuctionHouseBot.DisableTGsAboveLevel = 0 +AuctionHouseBot.DisableItemsBelowGUID = 0 +AuctionHouseBot.DisableItemsAboveGUID = 0 +AuctionHouseBot.DisableTGsBelowGUID = 0 +AuctionHouseBot.DisableTGsAboveGUID = 0 +AuctionHouseBot.DisableItemsBelowReqLevel = 0 +AuctionHouseBot.DisableItemsAboveReqLevel = 0 +AuctionHouseBot.DisableTGsBelowReqLevel = 0 +AuctionHouseBot.DisableTGsAboveReqLevel = 0 +AuctionHouseBot.DisableItemsBelowReqSkillRank = 0 +AuctionHouseBot.DisableItemsAboveReqSkillRank = 0 +AuctionHouseBot.DisableTGsBelowReqSkillRank = 0 +AuctionHouseBot.DisableTGsAboveReqSkillRank = 0 + +#These are the settings in the Database: +#Each Auctionhouse has it's own set of these + +MinItems = 0 +#The Minimum number of items you want to keep in the auction houses. +#(default 0 - minimum will be the same as maximum). +#If it is higher than the value of the corresponding maxItems setting, +#it will be set down to match the maxItems setting. + +MaxItems = 0 +#The Maximum number of items you want to keep in the auction houses. + +#These must add up to 100 each one is the percentage +#of the auction items that should be trade goods of +#that quality. A value of 0 will disable. + +PercentGreyTradeGoods = 0 +PercentWhiteTradeGoods = 27 +PercentGreenTradeGoods = 12 +PercentBlueTradeGoods = 10 +PercentPurpleTradeGoods = 1 +PercentOrangeTradeGoods = 0 +PercentYellowTradeGoods = 0 + +PercentGreyItems = 0 +PercentWhiteItems = 10 +PercentGreenItems = 30 +PercentBlueItems = 8 +PercentPurpleItems = 2 +PercentOrangeItems = 0 +PercentYellowItems = 0 + +#MinPrice(Color) is the minimum price adjustment for items. For example the default is 150, which means 150%. So if an item vendors for 1g it would go to auction for a minimum of 1.5g. +#MaxPrice(Color) is the maximum price adjustment for items. +#MinBidPrice(Color) these two control the starting bid as a percent of the buyout price. For example, if MinBidPrice is 30 and MaxBidPrice is 80 the starting bid for the auction will randomly be between 30-80% of the randomly chosen buyout price. +#MaxBidPrice(Color) these two control the starting bid as a percent of the buyout price. For example, if MinBidPrice is 30 and MaxBidPrice is 80 the starting bid for the auction will randomly be between 30-80% of the randomly chosen buyout price. +#MaxStack(Color) is maximum stack size to create for this quality type. A value of zero will disable the maximum stack size for this quality allowing the bot to create stacks (of random size) of items as big as the item type allows. + +MinPriceGrey = 100 +MaxPriceGrey = 150 +MinBidPriceGrey = 70 +MaxBidPriceGrey = 100 +MaxStackGrey = 0 +MinPriceWhite = 150 +MaxPriceWhite = 250 +MinBidPriceWhite = 70 +MaxBidPriceWhite = 100 +MaxStackWhite = 0 +MinPriceGreen = 800 +MaxPriceGreen = 1400 +MinBidPriceGreen = 80 +MaxBidPriceGreen = 100 +MaxStackGreen = 0 +MinPriceBlue = 1250 +MaxPriceBlue = 1750 +MinBidPriceBlue = 75 +MaxBidPriceBlue = 100 +MaxStackBlue = 0 +MinPricePurple = 2250 +MaxPricePurple = 4550 +MinBidPricePurple = 80 +MaxBidPricePurple = 100 +MaxStackPurple = 0 +MinPriceOrange = 4250 +MaxPriceOrange = 5550 +MinBidPriceOrange = 80 +MaxBidPriceOrange = 100 +MaxStackOrange = 0 +MinPriceYellow = 5250 +MaxPriceYellow = 6550 +MinBidPriceYellow = 80 +MaxBidPriceYellow = 100 +MaxStackYellow = 0 + +#These are the multipliers that are applied to the vendor price for an item, that determines if AHBot will buy it or not. +#1 means AHBot will pay the same as (or less than) a vendor would pay, 2 means up to twice as much, etc. + +BuyerPriceGrey = 1 +BuyerPriceWhite = 3 +BuyerPriceGreen = 5 +BuyerPriceBlue = 12 +BuyerPricePurple = 15 +BuyerPriceOrange = 20 +BuyerPriceYellow = 22 + +#BuyerBiddingInterval is the time (in minutes) between bids. +#BuyerBidsPerInterval is the number of bids the buyer will make in a cycle + +BuyerBiddingInterval = 1 +BuyerBidsPerInterval = 1 + + + +How to use ahcommands from the console (CLI) or in game with GM level 3 players: +ahbotoptions - will display usage instructions +ahbotoptions help - will display the list of commands + +ahexpire - will expire all the auctions in the requested auction house that were created by AHBot. +minitems - will set the minimum number of items in the AH before it starts being filled again. +maxitems - will set the maximum number of items in the AH. +percentages - will set the percentage of each quality in the AH +minprice - will set the minimum price multiplier for auctions. +maxprice - will set the maximum price multiplier for auctions. +minbidprice - will set the minimum starting bid as a percent of the buyout price for auctions. +maxbidprice - will set the maximum starting bid as a percent of the buyout price for auctions. +maxstack - will set the maximum number of items in stacks for auctions. 0 will set the maximum to the maximum for that item type. +buyerprice - will set the bid price multiplier for auctions. +biddinginterval - will set the number of minutes between bids on auctions. +bidsperinterval - will set the number of bids to enter per cycle. + +The auction house IDs are: +2 - Alliance +6 - Horde +7 - Neutral + + +AHBot Originally made by Chris K. Currently maintained by Paradox +Much thanks to Chris K, grether and Dolomit6! +AHBot Now includes AHBuyer created by Kerbe as a derivative of AHBot, and later modified by Paradox diff --git a/doc/EventAI.txt b/doc/EventAI.txt new file mode 100644 index 00000000000..7d0294da05f --- /dev/null +++ b/doc/EventAI.txt @@ -0,0 +1,868 @@ +============================================= +EventAI documentation: (updated May 19, 2009) +============================================= + +EventAI allows users to create new creature scripts entierly within the database. + +For the AI to be used, you must first make sure to set AIname for each creature that should use this AI. +UPDATE creature_template SET AIName = 'EventAI' WHERE entry IN (...); + + +========================================= +Basic structure of EventAI +========================================= + +EventAI follows a basic if (Event) then do (Action) format. +Below is the list of current fields of the creature_ai_scripts table. + +(Field_Name) (Description) +id This value is merely an incrementing counter of the current Event number. Required for sql queries. +creature_id Creature id which should trigger this event. + +event_type The type of event (see "Event types" below) +event_inverse_phase_mask Mask with phases this event should NOT trigger in* +event_chance Percentage chance of triggering the event (1 - 100) +event_flags Event flags (repeatable, ... (see below)) +event_param1 Variables for the event (depends on event_type) +event_param2 +event_param3 +event_param4 + +action1_type An action to take when the event occurs (see "Action types" below) +action1_param1 Variables used by Action1 (depends on action_type) +action1_param2 +action1_param3 + +action2_type +action2_param1 +action2_param2 +action2_param3 + +action3_type +action3_param1 +action3_param2 +action3_param3 + +All params are signed 32-bit values (+/- 2147483647). Time values are always in milliseconds. +In case of a percentage value, use value/100 (ie. param = 500 then that means 500%, -50 = -50%) + +[*] Phase mask is a bitmask of phases which shouldn't trigger this event. (ie. Phase mask of value 12 (binary 1100) results in triggering this event in phases 0, 1 and all others with exception for phases 2 and 3 (counting from 0). + + +========================================= +Event types +========================================= + +A list of event types EventAI is able to handle. +Each event type has its own specific interpretation of the params that accompany it. +Params are always read in the ascending order (from Param1 to Param3). +Events will not repeat until the creature exits combat or unless EFLAG_REPEATABLE is set. +Some events such as EVENT_T_AGGRO, EVENT_T_DEATH, EVENT_T_SPAWNED, and EVENT_T_EVADE cannot repeat. + +# Internal name Param usage Description +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +0 EVENT_T_TIMER InitialMin, InitialMax, RepeatMin, RepeatMax Expires at first between (Param1) and (Param2) and then between every (Param3) and (Param4), but only in combat. +1 EVENT_T_TIMER_OOC InitialMin, InitialMax, RepeatMin, RepeatMax Expires at first between (Param1) and (Param2) and then between every (Param3) and (Param4), but only out of combat. +2 EVENT_T_HP HPMax%, HPMin%, RepeatMin, RepeatMax Expires when HP is between (Param1) and (Param2). Will repeat every (Param3) and (Param4). +3 EVENT_T_MANA ManaMax%,ManaMin% RepeatMin, RepeatMax Expires once Mana% is between (Param1) and (Param2). Will repeat every (Param3) and (Param4). +4 EVENT_T_AGGRO NONE Expires upon initial aggro (does not repeat). +5 EVENT_T_KILL RepeatMin, RepeatMax Expires upon killing a player. Will repeat between (Param1) and (Param2). +6 EVENT_T_DEATH NONE Expires upon creature death. +7 EVENT_T_EVADE NONE Expires upon creature EnterEvadeMode(). +8 EVENT_T_SPELLHIT SpellID, Schoolmask, RepeatMin, RepeatMax Expires upon a spell hit. When (param1) is set, it will be used as a trigger. With (param2) specified, the expiration is limited to specific spell schools (-1 for all). Will repeat every (Param3) and (Param4). +9 EVENT_T_RANGE MinDist, MaxDist, RepeatMin, RepeatMax Expires when the highest threat target distance is greater than (Param1) and less than (Param2). Will repeat every (Param3) and (Param4). +10 EVENT_T_OOC_LOS Hostile-or-Not, MaxAllowedRange, RepeatMin, RepeatMax Expires when a unit moves within distance (MaxAllowedRange) of a creature. If (Param1) is zero it will expire only when unit is hostile, friendly otherwise (Param1 = 1), depends generally on faction. Will repeat every (Param3) and (Param4). Does not expire when the creature is in combat. +11 EVENT_T_SPAWNED NONE Expires on initial spawn and on creature respawn (useful for setting ranged movement type). +12 EVENT_T_TARGET_HP HPMax%, HPMin%, RepeatMin, RepeatMax Expires when current target's HP is between (Param1) and (Param2). Will repeat every (Param3) and (Param4). +13 EVENT_T_TARGET_CASTING RepeatMin, RepeatatMax Expires when the current target is casting a spell. Will repeat every (Param1) and (Param2). +14 EVENT_T_FRIENDLY_HP HPDeficit, Radius, RepeatMin, RepeatMax Expires when a friendly unit in radius has at least (Param1) HP missing. Will repeat every (Param3) and (Param4). +15 EVENT_T_FRIENDLY_IS_CC DispelType, Radius, RepeatMin, RepeatMax Expires when a friendly unit is crowd controlled within the given radius (Param2). Will repeat every (Param3) and (Param4). +16 EVENT_T_MISSING_BUFF SpellId, Radius, RepeatMin, RepeatMax Expires when a friendly unit is missing aura(s) given by a spell (Param1) within radius (Param2). Will repeat every (Param3) and (Param4). +17 EVENT_T_SUMMONED_UNIT CreatureId, RepeatMin, RepeatMax Expires after creature with entry = (Param1) is spawned (Param1 = 0 means all spawns). Will repeat every (Param2) and (Param3). +18 EVENT_T_TARGET_MANA ManaMax%, ManaMin%, RepeatMin, RepeatMax +21 EVENT_T_REACHED_HOME NONE Expires when a creature reach it's home(spawn) location after evade. +22 EVENT_T_RECEIVE_EMOTE EmoteId, Condition, CondValue1, CondValue2 Expires when a creature receives an emote with emote text id (enum TextEmotes) in (Param1). Conditions can be defined (Param2) with optional values (Param3,Param4), see enum ConditionType. +23 EVENT_T_BUFFED SpellID, AmmountInStack, RepeatMin, RepeatMax Expires when a creature has spell (Param1) auras applied in a stack greater or equal to value provided in (Param2). Will repeat every (Param3) and (Param4). +24 EVENT_T_TARGET_BUFFED SpellID, AmmountInStack, RepeatMin, RepeatMax Expires when a target unit has spell (Param1) auras applied in a stack greater or equal to value provided in (Param2). Will repeat every (Param3) and (Param4). +35 EVENT_T_RESET NONE Expires when creature leaves combat, spawns or respawns. + +========================================= +Action Types +========================================= + +A list of action types that EventAI can handle. +Each event type has its own specific interpretation of it's params, like every event type. + +# Internal name Param usage Description +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +0 ACTION_T_NONE No Action Does nothing. +1 ACTION_T_TEXT -TextId1, -TextId2, -TextId3 Simply displays the specified -TextId. When -TextId2 and -TextId3 are specified, the selection will be randomized. Text types are defined, along with other options for the text, in a table below. All values needs to be negative. +2 ACTION_T_SET_FACTION FactionId Changes faction for a creature. When param1 is zero, creature will revert to it's default faction. +3 ACTION_T_MORPH_TO_ENTRY_OR_MODEL CreatureEntry, ModelId Set either model from creature_template.entry (Param1) OR explicit modelId (Param2). If (Param1) AND (Param2) are both 0, demorph and revert to the default model. +4 ACTION_T_SOUND SoundId Plays a sound +5 ACTION_T_EMOTE EmoteId Does an emote +6 ACTION_T_RANDOM_SAY UNUSED +7 ACTION_T_RANDOM_YELL UNUSED +8 ACTION_T_RANDOM_TEXTEMOTE UNUSED +9 ACTION_T_RANDOM_SOUND SoundId1, SoundId2, SoundId3 Plays a random sound * +10 ACTION_T_RANDOM_EMOTE EmoteId1, EmoteId2, EmoteId3 Emotes a random emote +11 ACTION_T_CAST SpellId, Target, CastFlags Casts spell (Param1) on a target (Param2) using cast flags (specified below). +12 ACTION_T_SUMMON CreatureID, Target, Duration Summons a creature (Param1) for (Param3) duration and orders it to attach (Param2) target. Spawns on top of current creature. +13 ACTION_T_THREAT_SINGLE_PCT Threat%, Target Modifies a threat by (Param1) percent on a target (Param2). +14 ACTION_T_THREAT_ALL_PCT Threat% Modifies a threat by (Param1) on all targets in the threat list (using -100% here will result in full aggro dump). +15 ACTION_T_QUEST_EVENT QuestID, Target Calls AreaExploredOrEventHappens with (Param1) for a target in (Param2). +16 ACTION_T_QUEST_CASTCREATUREGO CreatureID, SpellId, Target Sends CastCreatureOrGo for a creature specified by CreatureId (Param1) with provided spell id (Param2) for a target in (Param3). +17 ACTION_T_SET_UNIT_FIELD Field_Number, Value, Target Sets a unit field (Param1) to provided value (Param2) on a target in (Param3). +18 ACTION_T_SET_UNIT_FLAG Flags, Target Sets flag (flags can be used together to modify multiple flags at once) on a target (Param2). +19 ACTION_T_REMOVE_UNIT_FLAG Flags, Target Removes flag on a target (Param2). +20 ACTION_T_AUTO_ATTACK AllowAutoAttack Stop melee attack when (Param1) is zero, otherwise continue attacking / allow melee attack. +21 ACTION_T_COMBAT_MOVEMENT AllowCombatMovement Stop combat based movement when (Param1) is zero, otherwise continue/allow combat based movement (targeted movement generator). +22 ACTION_T_SET_PHASE Phase Sets the current phase to (Param1). +23 ACTION_T_INC_PHASE Value Increments the phase by (Param1). May be negative to decrement, but should not be zero. +24 ACTION_T_EVADE No Params Forces the creature to evade, wiping all threat and dropping combat. +25 ACTION_T_FLEE_FOR_ASSIST No Params Causes the creature to flee for assistence (often at low health). +26 ACTION_T_QUEST_EVENT_ALL QuestId Calls GroupEventHappens with (Param1). Only used if it's _expected_ event should call quest completion for all players in a current party. +27 ACTION_T_CASTCREATUREGO_ALL QuestId, SpellId Calls CastedCreatureOrGo for all players on the threat list with quest id specified in (Param1) and spell id in (Param2). +28 ACTION_T_REMOVEAURASFROMSPELL Target, Spellid Removes all auras on a target (Param1) caused by a spell (Param2). +29 ACTION_T_RANGED_MOVEMENT Distance, Angle Changes the movement generator to a ranged type. (note: default melee type can still be set by using 0 as angle and 0 as distance). +30 ACTION_T_RANDOM_PHASE PhaseId1, PhaseId2, PhaseId3 Sets a phase to a specified id(s)* +31 ACTION_T_RANDOM_PHASE_RANGE PhaseMin, PhaseMax Sets a phase to a random id (Phase = PhaseMin + rnd % PhaseMin-PhaseMax). PhaseMax must be greater than PhaseMin. +32 ACTION_T_SUMMON CreatureID, Target, SummonID Summons a creature (Param1) to attack target (Param2) at location specified by EventAI_Summons (Param3). +33 ACTION_T_KILLED_MONSTER CreatureID, Target Calls KilledMonster (Param1) for a target (Param2). +34 ACTION_T_SET_INST_DATA Field, Data Calls ScriptedInstance::SetData with field (Param1) and data (Param2). +35 ACTION_T_SET_INST_DATA64 Field, Target Calls ScriptedInstance::SetData64 with field (Param1) and target's GUID (Param2). +36 ACTION_T_UPDATE_TEMPLATE TemplateId, Team Changes a creature's template to (Param1) with team = Alliance or Horde when (Param2) is either false or true respectively. +37 ACTION_T_DIE No Params Kills the creature +38 ACTION_T_ZONE_COMBAT_PULSE No Params Puts all players within an instance into combat with the creature. Only works when a creature is already in combat. Doesn't work outside instances. +39 ACTION_T_CALL_FOR_HELP Radius Call any friendly out-of-combat creatures in a radius (Param1) to attack current creature's target. +40 ACTION_T_SET_SHEATH Sheath Sets sheath state for a creature (0 = no weapon, 1 = melee weapon, 2 = ranged weapon). +41 ACTION_T_FORCE_DESPAWN No Params Despawns the creature +42 ACTION_T_SET_INVINCIBILITY_HP_LEVEL hp_level, is_percent Set min. health level for creature that can be set at damage as flat value or percent from max health + +* = Use -1 where the param is expected to do nothing. Random constant is generated for each event, so if you have a random yell and a random sound, they will be linked up with each other (ie. param2 with param2). + + +========================================= +Event Types +========================================= +Note: +COMBAT ONLY - Means that this event will only trigger durring combat. +OUT OF COMBAT ONLY - Means that this event will only trigger while out of combat. +BOTH - This event can trigger both in and out of combat. + +Events that do not have lables on them are events that are directly involved with the in and out of combat state. + +------------------ +0 = EVENT_T_TIMER: +------------------ +Parameter 1: InitialMin - Minumum Time used to calculate Random Initial Expire +Parameter 2: InitialMax - Maximum Time used to calculate Random Initial Expire +Parameter 3: RepeatMin - Minimum Time used to calculate Random Repeat Expire +Parameter 4: RepeatMax - Maximum Time used to calculate Random Repeat Expire + +COMBAT ONLY! - Expires first between (Param1) and (Param2) and then between every (Param3) and (Param4) from then on. +This is commonly used for spells that repeat cast during combat (Simulate Spell Cooldown). + +---------------------- +1 = EVENT_T_TIMER_OOC: +---------------------- +Parameter 1: InitialMin - Minumum Time used to calculate Random Initial Expire +Parameter 2: InitialMax - Maximum Time used to calculate Random Initial Expire +Parameter 3: RepeatMin - Minimum Time used to calculate Random Repeat Expire +Parameter 4: RepeatMax - Maximum Time used to calculate Random Repeat Expire + +OUT OF COMBAT ONLY! - Expires first between (Param1) and (Param2) and then between every (Param3) and (Param4) from then on. +This is commonly used for events that occur and repeat outside of combat. + +--------------- +2 = EVENT_T_HP: +--------------- +Parameter 1: HPMax% - Maximum HP% That this Event will Expire +Parameter 2: HPMin% - Minimum HP% That this Event will Expire +Parameter 3: RepeatMin - Minimum Time used to calculate Random Repeat Expire +Parameter 4: RepeatMax - Maximum Time used to calculate Random Repeat Expire + +BOTH - Expires when HP is between (Param1) and (Param2). Will repeat every (Param3) and (Param4). +This is commonly used for events that trigger at a specific HP% (Such as Heal/Enrage Spells or NPC's that Flee). + +----------------- +3 = EVENT_T_MANA: +----------------- +Parameter 1: ManaMax% - Maximum Mana% That this Event will Expire +Parameter 2: ManaMin% - Minimum Mana% That this Event will Expire +Parameter 3: RepeatMin - Minimum Time used to calculate Random Repeat Expire +Parameter 4: RepeatMax - Maximum Time used to calculate Random Repeat Expire + +BOTH - Expires once Mana% is between (Param1) and (Param2). Will repeat every (Param3) and (Param4). +This is commonly used for events where an NPC low on Mana will do something (Such as stop casting spells and switch to melee). + +------------------ +4 = EVENT_T_AGGRO: +------------------ +This Event Expires upon initial aggro (does not repeat). + +----------------- +5 = EVENT_T_KILL: +----------------- +Parameter 1: RepeatMin - Minimum Time used to calculate Random Repeat Expire +Parameter 2: RepeatMax - Maximum Time used to calculate Random Repeat Expire + +COMBAT ONLY! - Expires upon killing a player. Will repeat every (Param1) and (Param2). +This Event Expires upon killing a player. It is commonly used for NPC's who yell or do something after killing a player. + +------------------ +6 = EVENT_T_DEATH: +------------------ +This Event Expires upon Death of the Scripted NPC. +This is commonly used for NPC's who have a yell on death or cast some kind if summon spell when they die. + +------------------ +7 = EVENT_T_EVADE: +------------------ +This Event Expires upon the creature EnterEvadeMode(). +This is commonly used for NPC's who use phases, allows you to reset their phase to 0 upon evade to prevent possible strange behavior. + +--------------------- +8 = EVENT_T_SPELLHIT: +--------------------- +Parameter 1: SpellID - The Spell ID that will trigger the event to occur (NOTE: If you use Spell School as the trigger set this value to 0) +Parameter 2: School - Spell School to trigger the event (NOTE: If you use a SpellID then set this value to -1) - *See Below for Spell School Bitmask Values* +Parameter 3: RepeatMin - Minimum Time used to calculate Random Repeat Expire +Parameter 4: RepeatMax - Maximum Time used to calculate Random Repeat Expire + +BOTH - Expires upon Spell hit. If (param1) is set will only expire on that spell OR If (param2) is set it will only expire on spells of that school. Will repeat every (Param3) and (Param4). +This Event is commonly used for NPC's who can do special things when you cast a spell (Or specific spell) on them. + +(name, school, schoolmask) +SPELL_SCHOOL_NORMAL = 0, ==> 1 +SPELL_SCHOOL_HOLY = 1, ==> 2 +SPELL_SCHOOL_FIRE = 2, ==> 4 +SPELL_SCHOOL_NATURE = 3, ==> 8 +SPELL_SCHOOL_FROST = 4, ==> 16 +SPELL_SCHOOL_SHADOW = 5, ==> 32 +SPELL_SCHOOL_ARCANE = 6, ==> 64 +Use These Values For Schoolmask (Param2) or Any Combinations Of These Schoolmasks for Multiple Schools. + +------------------ +9 = EVENT_T_RANGE: +------------------ +Parameter 1: MinDist - This Distance is the Minimum Distance between the NPC and it's target to allow this Event to Expire +Parameter 2: MaxDist - This Distance is the Maximum Distance between the NPC and it's target to allow this Event to Expire +Parameter 3: RepeatMin - Minimum Time used to calculate Random Repeat Expire +Parameter 4: RepeatMax - Maximum Time used to calculate Random Repeat Expire + +COMBAT ONLY! - Expires when the highest threat target distance is greater than (Param1) and less than (Param2). Will repeat every (Param3) and (Param4). +This Event is commonly used for NPC's who have Ranged Combat and will Throw/Shoot between a certian distance. + +--------------------- +10 = EVENT_T_OOC_LOS: +--------------------- +Parameter 1: Hostile-or-Not - This will expire if Unit are hostile. If Param1=1 it will only expire if Unit are not Hostile(generally determined by faction) +Parameter 2: MaxAllowedRange - Expires when a Unit moves within this distance to creature +Parameter 3: RepeatMin - Minimum Time used to calculate Random Repeat Expire +Parameter 4: RepeatMax - Maximum Time used to calculate Random Repeat Expire + +OUT OF COMBAT! +This Event is commonly used for NPC's who do something or say something to you when you walk past them Out of Combat. + +--------------------- +11 = EVENT_T_SPAWNED: +--------------------- +Expires at initial spawn and at creature respawn. +This Event is commonly used for setting ranged movement type or Summoning a Pet on Spawn +Parameter 1: 0: works always, 1: works on map in Parameter 2, 2: works on zone/subzone in Parameter 2 +Parameter 2: depends on Parameter 1: for 1 it is map ID, for 2 it is area ID to check + +----------------------- +12 = EVENT_T_TARGET_HP: +----------------------- +Parameter 1: HPMax% - Maximum HP% That this Event will Expire +Parameter 2: HPMin% - Minimum HP% That this Event will Expire +Parameter 3: RepeatMin - Minimum Time used to calculate Random Repeat Expire +Parameter 4: RepeatMax - Maximum Time used to calculate Random Repeat Expire + +COMBAT ONLY! - Expires when Current NPC's Target's HP is between (Param1) and (Param2). Will repeat every (Param3) and (Param4). +This Event is commonly used for NPC's who have a special ability (Like Execute) that only casts when a Player HP is low. + +---------------------------- +13 = EVENT_T_TARGET_CASTING: +---------------------------- +Parameter 1: RepeatMin - Minimum Time used to calculate Random Repeat Expire +Parameter 2: RepeatMax - Maximum Time used to calculate Random Repeat Expire + +COMBAT ONLY! - Expires when the current target is casting a spell. Will repeat every (Param1) and (Param2). +This event is commonly used for NPC's who will cast a counter spell when their target starts to cast a spell. + +------------------------- +14 = EVENT_T_FRIENDLY_HP: +------------------------- +Parameter 1: HPDeficit - This is the Amount of HP Missing from Full HP to trigger this event (You would need to calculate the amount of HP the event happens and subtract that from Full HP Value to get this number) +Parameter 2: Radius - This is the Range in Yards the NPC will scan for nearby Friendlies (Faction is Friendly To) for the missing amount of HP in Param1. +Parameter 3: RepeatMin - Minimum Time used to calculate Random Repeat Expire +Parameter 4: RepeatMax - Maximum Time used to calculate Random Repeat Expire + +COMBAT ONLY! - Expires when a friendly unit in radius(param2) has at least (param1) hp missing. Will repeat every (Param3) and (Param4). +This is commonly used when an NPC in Combat will heal a nearby Friendly NPC in Combat with a Heal/Renew Spell. + +---------------------------- +15 = EVENT_T_FRIENDLY_IS_CC: +---------------------------- +Parameter 1: DispelType - Dispel Type to trigger the event - *See Below for Dispel Bitmask Values* +Parameter 2: Radius - This is the Range in Yards the NPC will scan for nearby Friendlies being Crowd Controlled +Parameter 3: RepeatMin - Minimum Time used to calculate Random Repeat Expire +Parameter 4: RepeatMax - Maximum Time used to calculate Random Repeat Expire + +COMBAT ONLY! - Expires when a friendly unit is Crowd controlled within the given radius (param2). Will repeat every (Param3) and (Param4). +This is commonly used for NPC's who can come to the resule of other Friendly NPC's if being Crowd Controlled + +-------------------------- +16 = EVENT_T_MISSING_BUFF: +-------------------------- +Parameter 1: SpellId - This is the SpellID That the Aura Check will look for (If it is missing this Aura) +Parameter 2: Radius - This is the Range in Yards the NPC will scan for nearby Friendlies (Faction is Friendly To) for the missing Aura. +Parameter 3: RepeatMin - Minimum Time used to calculate Random Repeat Expire +Parameter 4: RepeatMax - Maximum Time used to calculate Random Repeat Expire + +BOTH - Expires when a friendly unit is missing aura's given by spell (param1) within radius (param2). Will repeat every (Param3) and (Param4). +This is commonly used for NPC's who watch friendly units for a debuff to end so they can recast it on them again. + +--------------------------- +17 = EVENT_T_SUMMONED_UNIT: +--------------------------- +Parameter 1: CreatureId - The CreatureID that the NPC is watching to spawn to trigger this event +Parameter 2: RepeatMin - Minimum Time used to calculate Random Repeat Expire +Parameter 3: RepeatMax - Maximum Time used to calculate Random Repeat Expire + +BOTH - Expires after creature with entry(Param1) is spawned or for all spawns if param1 = 0. Will repeat every (Param2) and (Param3) . +This is commonly used for NPC's who will do something special once another NPC is summoned. Usually used is Complex Scripts or Special Events. + +--------------------------- +21 = EVENT_T_REACHED_HOME: +--------------------------- +Expires only when creature has returned to it's home location after Evade. Out of combat event. +Most commonly used to cast spells that can not be casted in EVENT_T_EVADE and other effects that does not fit in while still running back to spawn/home location. + +--------------------------- +22 = EVENT_T_RECEIVE_EMOTE: +--------------------------- +Expires only when creature receive emote from player. Valid text emote id's are in Mangos source (enum TextEmotes) +Event does not require any conditions to process, however many are ecpected to have condition. + +--------------------------- +23 = EVENT_T_BUFFED : +--------------------------- +Parameter 1: SpellId - This is the SpellID That the Aura Check will look for +Parameter 2: Amount - This is the amount of SpellID's auras at creature required for event expire. +Parameter 3: RepeatMin - Minimum Time used to calculate Random Repeat Expire +Parameter 4: RepeatMax - Maximum Time used to calculate Random Repeat Expire + +--------------------------- +24 = EVENT_T_TARGET_BUFFED: +--------------------------- +Parameter 1: SpellId - This is the SpellID That the Aura Check will look for +Parameter 2: Amount - This is the amount of SpellID's auras at target unit required for event expire. +Parameter 3: RepeatMin - Minimum Time used to calculate Random Repeat Expire +Parameter 4: RepeatMax - Maximum Time used to calculate Random Repeat Expire + +EventAI use conditions from available in Mangos (enum ConditionType) +Current implemented conditions: +CONDITION_NONE (0) 0 0 +CONDITION_AURA (1) spell_id effindex +CONDITION_ITEM (2) item_id count +CONDITION_ITEM_EQUIPPED (3) item_id count +CONDITION_ZONEID (4) zone_id 0 +CONDITION_REPUTATION_RANK (5) faction_id min_rank +CONDITION_TEAM (6) player_team 0 (469-Alliance / 67-Horde) +CONDITION_SKILL (7) skill_id min_skill_value +CONDITION_QUESTREWARDED (8) quest_id 0, if quest are rewarded +CONDITION_QUESTTAKEN (9) quest_id 0, while quest active(incomplete) +CONDITION_ACTIVE_EVENT (12) event_id 0, note this is id from dbc, also defined in Mangos source(enum HolidayIds) NOT id of game_event in database + +========================================= +Action Types +========================================= + +----------------- +1 = ACTION_T_TEXT: +----------------- +Parameter 1: The entry of the text that the NPC should use from eventai_texts table. Optionally a entry from other tables can be used (such as custom_texts). + Entry are required to be negative and exist in a *_texts-table. The type text to be displayed are defined in the texts-table itself (Say, Yell, Whisper, Emote Text, Boss Whisper, Boss Emote) + Other options are also to be defined in the texts-table, such as a sound to be heard with the text and the language used in output (common, dwarvish, etc). + In case this entry has a localized version of the text, the localized text will be displayed in client that support this locale. + +Parameter 2: Optional. TextId can be defined in addition. The same apply to this as explained above, however eventAI will randomize between the two. +Parameter 3: Optional, if Parameter 2 exist. In this case, eventAI will randomize between three. + +Read at bottom for documentation of creature_ai_texts-table. + +------------------ +2 = ACTION_T_SET_FACTION: +------------------ +Parameter 1: FactionId from Faction.dbc OR 0. Changes faction for creature. If 0, creature will revert to it's default faction if previously changed. + +----------------------- +3 = ACTION_T_MORPH_TO_ENTRY_OR_MODEL: +----------------------- +Parameter 1: Creature entry from creature_template. Action will then change to the model this creature are using. +Parameter 2: If parameter 1 is 0, then this modelId will be used (in case parameter 1 exist, parameter 2 will not be used) + +If both parameter 1 and 2 is 0, the creature will DeMorph, and use it's default model. + +------------------- +4 = ACTION_T_SOUND: +------------------- +Parameter 1: The Sound ID to be played. (Sound IDs are contained in the DBC files.) + +The creature will play the specified sound. +This is commonly used for Bosses who Yell and then also have a Voice for the same thing. + +------------------- +5 = ACTION_T_EMOTE: +------------------- +Parameter 1: The Emote ID that the creature should perform. (Emote IDs are also contained in the DBC but they can be found in the mangos source as well). + +The creature will perform a visual emote. Unlike a text emote, a visual emote is one where the creature will actually move or perform a gesture. +This is commonly used for NPC's who may perform a special action (Salute, Roar, ect...). Not all player emotes work for creature models. + +------------------------ +6 = ACTION_T_RANDOM_SAY: +------------------------ +UNUSED Can be reused to create new action type + +------------------------- +7 = ACTION_T_RANDOM_YELL: +------------------------- +UNUSED Can be reused to create new action type + +------------------------------ +8 = ACTION_T_RANDOM_TEXTEMOTE: +------------------------------ +UNUSED Can be reused to create new action type + +-------------------------- +9 = ACTION_T_RANDOM_SOUND: +-------------------------- +Parameter 1: The Sound ID to be played as Random Choice #1. +Parameter 2: The Sound ID to be played as Random Choice #2. +Parameter 3: The Sound ID to be played as Random Choice #3. + +Similar to the ACTION_T_SOUND action, it will choose at random a sound to play. + +--------------------------- +10 = ACTION_T_RANDOM_EMOTE: +--------------------------- +Parameter 1: The Emote ID to be played as Random Choice #1. +Parameter 2: The Emote ID to be played as Random Choice #2. +Parameter 3: The Emote ID to be played as Random Choice #3. + +Similar to the ACTION_T_EMOTE action, it will choose at random an Emote to Visually Perform. + +------------------- +11 = ACTION_T_CAST: +------------------- +Parameter 1: SpellId - The Spell ID to use for the NPC to cast. The value used in this field needs to be a valid Spell ID. +Parameter 2: Target - The Target Type defining who the creature should cast the spell at. The value in this field needs to be a valid Target Type as specified in the reference tables below. +Parameter 3: CastFlags - See Table Below for Cast Flag Bitmask Values. If you are unsure what to set this value at leave it at 0. + +The creature will cast a spell specified by a spell ID on a target specified by the target type. +This is commonly used for NPC's who cast spells. + +--------------------- +12 = ACTION_T_SUMMON: +--------------------- +Parameter 1: CreatureID - The Creature Template ID to be Summoned. The value here needs to be a valid Creature Template ID. +Parameter 2: Target - The Target Type defining who the Summoned creature will attack once spawned. The value in this field needs to be a valid Target Type as specified in the reference tables below. +Parameter 3: Duration - The duration until the summoned creature should be unsummoned AFTER Combat ends. The value in this field is in milliseconds or 0. + +The NPC will Summon another creature at the same spot as itself that will attack the specified target. +NOTE: Almost all Creature Summons have proper Summon Spells that should be used when possible. This Action is a powerful last resort option only to be used if nothing else works. +NOTE: Using Target Type 0 will cause the Summoned creature to not attack anyone. +NOTE: If Duration is set at 0, then the summoned creature will not despawn until it has died. +This is used as a manual way to force an NPC to Summon. +-------------------------------- +13 = ACTION_T_THREAT_SINGLE_PCT: +-------------------------------- +Parameter 1: Threat% - Threat percent that should be modified. The value in this field can range from -100 to +100. If it is negative, threat will be taken away and if positive, threat will be added. +Parameter 2: Target - The Target Type defining on whom the threat change should occur. The value in this field needs to be a valid target type as specified in the reference tables below. + +This action will modify the threat of a target in the creature's threat list by the specified percent. +This is commonly used to allow an NPC to adjust the Threat to a single player. + +----------------------------- +14 = ACTION_T_THREAT_ALL_PCT: +----------------------------- +Parameter 1: Threat% - The percent that should be used in modifying everyone's threat in the creature's threat list. The value here can range from -100 to +100. + +This action will modify the threat for everyone in the creature's threat list by the specified percent. +NOTE: Using -100 will cause the creature to reset everyone's threat to 0 so that everyone has the same amount of threat. It will NOT remove anyone from the threat list. +This is commonly used to allow an NPC to drop threat for all players to zero. + +-------------------------- +15 = ACTION_T_QUEST_EVENT: +-------------------------- +Parameter 1: QuestID - The Quest Template ID. The value here must be a valid quest template ID. Furthermore, the quest should have SpecialFlags | 2 as it would need to be completed by an external event which is the activation of this action. +Parameter 2: Target - The Target Type defining whom the quest should be completed for. The value in this field needs to be a valid target type as specified in the reference tables below. + +This action will satisfy the external completion requirement for the quest for the specified target defined by the target type. +NOTE: This action can only be used with player targets so it must be ensured that the target type will point to a player. +This is commonly used for Quests where only ONE player will gain credit for the quest. + +----------------------------- +16 = ACTION_T_CASTCREATUREGO: +----------------------------- +Parameter 1: CreatureID - The Creature Template ID to be Summoned. The value here needs to be a valid Creature Template ID. +Parameter 2: SpellId - The Spell ID to use to simulate the cast. The value used in this field needs to be a valid Spell ID. +Parameter 3: Target - The Target Type defining whom the quest credit should be given to. The value in this field needs to be a valid target type as specified in the reference tables below. + +This action will call CastedCreatureOrGO() function for the player. It can be used to give quest credit for casting a spell on the creature. +This is commonly used for NPC's who have a special requirement to have a Spell cast on them to complete a quest. + +----------------------------- +17 = ACTION_T_SET_UNIT_FIELD: +----------------------------- +Parameter 1: Field_Number - The index of the Field Number to be changed. Use (http://wiki.udbforums.org/index.php/Character_data) for a list of indeces and what they control. Creatures only contain the OBJECT_FIELD_* and UNIT_FIELD_* fields. They do not contain the PLAYER_FIELD_* fields. +Parameter 2: Value - The new value to be put in the field. +Parameter 3: Target - The Target Type defining for whom the unit field should be changed. The value in this field needs to be a valid target type as specified in the reference tables below. + +When activated, this action can change the target's unit field values. More information on the field value indeces can be found at (http://wiki.udbforums.org/index.php/Character_data) + +---------------------------- +18 = ACTION_T_SET_UNIT_FLAG: +---------------------------- +Parameter 1: Flags - The flag(s) to be set. Multiple flags can be set by using bitwise-OR on them (adding them together). +Parameter 2: Target - The Target Type defining for whom the flags should be changed. The value in this field needs to be a valid Target Type as specified in the reference tables below. + +When activated, this action changes the target's flags by adding (turning on) more flags. For example, this action can make the creature unattackable/unselectable if the right flags are used. + +------------------------------- +19 = ACTION_T_REMOVE_UNIT_FLAG: +------------------------------- +Parameter 1: Flags - The flag(s) to be removed. Multiple flags can be set by using bitwise-OR on them (adding them together). +Parameter 2: Target - The target type defining for whom the flags should be changed. The value in this field needs to be a valid Target Type as specified in the reference tables below. + +When activated, this action changes the target's flags by removing (turning off) flags. For example, this action can make the creature normal after it was unattackable/unselectable if the right flags are used. + +-------------------------- +20 = ACTION_T_AUTO_ATTACK: +-------------------------- +Parameter 1: AllowAutoAttack - If zero, then the creature will stop its melee attacks. If non-zero, then the creature will either continue its melee attacks (the action would then have no effect) or it will start its melee attacks on the target with the top threat if its melee attacks were previously stopped. + +This action controls whether or not the creature should stop or start the auto melee attack. +NOTE: The ACID Dev Team has conformed to using either 0 or 1 for the Param values (0 = Stop Melee, 1 = Start Melee). +This is commonly used in combination with EVENT_T_RANGE and ACTION_T_COMBAT_MOVEMENT for Ranged Combat for Mages and Spell Casters. + +------------------------------ +21 = ACTION_T_COMBAT_MOVEMENT: +------------------------------ +Parameter 1: If zero, then the creature will stop moving towards its victim (if its victim gets out of melee range) and will be stationary. If non-zero, then the creature will either continue to follow its victim (the action would have no effect) or it will start to follow the target with the top threat if its movement was disabled before. +Parameter 2: If non-zero, then stop melee combat state (if param1=0) or start melee combat state (if param1!=0) and creature in combat with selected target. + +This action controls whether or not the creature will always move towards its target. +NOTE: The ACID Dev Team has conformed to using either 0 or 1 for the Param values. (0 = Stop Movement, 1 = Start Movement) +This is commonly used with EVENT_T_RANGE and ACTION_T_AUTO_ATTACK for NPC's who engage in Ranged Comabt (Either Spells or Ranged Attacks) +Parameter 2 specialy used for ranged combat proper client side visual show ranged weapon in proper state. + +------------------------ +22 = ACTION_T_SET_PHASE: +------------------------ +Parameter 1: The new phase to set the creature in. This number must be an integer between 0 and 31. Numbers outside of that range will result in an error. + +When activated, this action sets the creature's event to the specified value. +NOTE: The creature's current Phase is NOT reset at creature evade. You must manually set the phase back to 0 at EVENT_T_RESET. +NOTE: The value used for the Param is the actual Phase Number (Not The Event_Inverse_Phase_Mask) +This is commonly used for complex scripts with several phases and you need to switch to a different phase. + +------------------------ +23 = ACTION_T_INC_PHASE: +------------------------ +Parameter 1: Value - The number of phases to increase or decrease. Use negative values to decrease the current phase. + +When activated, this action will increase (or decrease) the current creature's phase. +NOTE: After increasing or decreasing the phase by this action, the current phase must NOT be lower than 0 or exceed 31. +This can be used instead of ACTION_T_SET_PHASE to change phases in scripts. Just a user friendly option for changing phases. + +-------------------- +24 = ACTION_T_EVADE: +-------------------- +When activated, the creature will immediately exit out of combat, clear its threat list, and move back to its spawn point. Basically, this action will reset the whole encounter. +NOTE: All Param Values Are 0 for this Action. + +------------------- +25 = ACTION_T_FLEE: +------------------- +When activated, the creature will try to flee from combat. Currently this is done by it casting a fear-like spell on itself called "Run Away". +A Better Flee system is in Development. +NOTE: All Param Values Are 0 for this Action. + +------------------------------ +26 = ACTION_T_QUEST_EVENT_ALL: +------------------------------ +Parameter 1: QuestId - The quest ID to finish for everyone. + +This action does the same thing as the ACTION_T_QUEST_EVENT does but it does it for all players in the creature's threat list. +NOTE: If a player is not in the NPC's threat list for whatever reason, he/she won't get the quest completed. + +--------------------------------- +27 = ACTION_T_CASTCREATUREGO_ALL: +--------------------------------- +Parameter 1: QuestId - The quest template ID. +Parameter 2: SpellId - The spell ID used to simulate the cast. + +This action does the same thing as the ACTION_T_CASTCREATUREGO does but it does it for all players in the creature's threat list. +NOTE: If a player is not in its threat list for whatever reason, he/she won't receive the cast emulation. + +----------------------------------- +28 = ACTION_T_REMOVEAURASFROMSPELL: +----------------------------------- +Parameter 1: Target - The target type defining for whom the unit field should be changed. The value in this field needs to be a valid target type as specified in the reference tables below. +Parameter 2: SpellId - The spell ID whose auras will be removed. + +This action will remove all auras from a specific spell from the target. +This is commonly used for NPC's who have an OOC Aura that is removed at combat start or a similar idea (Like Stealth or Shape Shift) + +------------------------------ +29 = ACTION_T_RANGED_MOVEMENT: +------------------------------ +Parameter 1: Distance - The distance the mob should keep between it and its target. +Parameter 2: Angle - The angle the mob should use. + +This action changes the movement type generator to ranged type using the specified values for angle and distance. +NOTE: Specifying zero angle and distance will make it just melee instead. +This is commonly used for NPC's who always attack at range and you can specify the distance they will maintain from the target. + +--------------------------- +30 = ACTION_T_RANDOM_PHASE: +--------------------------- +Parameter 1: PhaseId1 - A possible random phase choice. +Parameter 2: PhaseId2 - A possible random phase choice. +Parameter 3: PhaseId3 - A possible random phase choice. + +Randomly sets the phase to one from the three parameter choices. +NOTE: Use -1 to specify that if this param is picked to do nothing. Random is constant between actions within an event. So if you have a random Yell and a random Sound they will match up (ex: param2 with param2) +NOTE 2: PLEASE NOTE THAT EACH OF THE PARAM VALUES ARE ACTUAL PHASE NUMBERS NOT THE INVERSE PHASE MASK VALUE. +This is commonly used for Spellcasting NPC's who on Aggro may select at random a school of spells to use for the fight. Use this if you have up to 3 phases used, otherwise use Action 31 for more then 3 phases. + +--------------------------------- +31 = ACTION_T_RANDOM_PHASE_RANGE: +--------------------------------- +Parameter 1: PhaseMin - The minimum of the phase range. +Parameter 2: PhaseMax - The maximum of the phase range. The number here must be greater than PhaseMin. + +Randomly sets the phase between a range of phases controlled by the parameters. Sets the phase to a random id (Phase = PhaseMin + rnd % PhaseMin-PhaseMax). +NOTE: PhaseMax must be greater than PhaseMin. +NOTE 2: PLEASE NOTE THAT EACH OF THE PARAM VALUES ARE ACTUAL PHASE NUMBERS NOT THE INVERSE PHASE MASK VALUE. +This is commonly used for Spellcasting NPC's who on Aggro may select at random a school of spells to use for the fight. Use this if you have MORE then 3 phases used, otherwise use Action 30. + +--------------------- +32 = ACTION_T_SUMMON: +--------------------- +Parameter 1: CreatureID - The creature template ID to be summoned. The value here needs to be a valid creature template ID. +Parameter 2: Target - The target type defining who the summoned creature will attack. The value in this field needs to be a valid target type as specified in the reference tables below. NOTE: Using target type 0 will cause the summoned creature to not attack anyone. +Parameter 3: SummonID - The summon ID from the creature_ai_summons table controlling the position (and spawntime) where the summoned mob should be spawned at. + +Summons creature (param1) to attack target (param2) at location specified by creature_ai_summons (param3). +NOTE: Param3 Value is the ID Value used for the entry used in creature_ai_summons for this action. You MUST have an creature_ai_summons entry to use this action. +This is commonly used for NPC's who need to Summon a creature at a specific location. (Normally used for complex events) + +----------------------------- +33 = ACTION_T_KILLED_MONSTER: +----------------------------- +Parameter 1: CreatureID - The creature template ID. The value here must be a valid creature template ID. +Parameter 2: Target - The target type defining whom the quest kill count should be given to. The value in this field needs to be a valid target type as specified in the reference tables below. + +When activated, this action will call KilledMonster() function for the player. It can be used to give creature credit for killing a creature. In general if the quest is set to be accompished on different creatures (e.g. "Credit" templates). +NOTE: It can be ANY creature including certain quest specific triggers +This is commonly used for giving the player Quest Credits for NPC kills (Many NPC's may use the same CreatureID for the Kill Credit) + +---------------------------- +34 = ACTION_T_SET_INST_DATA: +---------------------------- +Parameter 1: Field - The field to change in the instance script. Again, this field needs to be a valid field that has been already defined in the instance's script. +Parameter 2: Data - The value to put at that field index. + +Sets data for the instance. Note that this will only work when the creature is inside an instantiable zone that has a valid script (ScriptedInstance) assigned. +This is commonly used to link an EventAI script with a existing Script Library C++ Script. You make make things happen like opening doors on specific events that happen. + +------------------------------ +35 = ACTION_T_SET_INST_DATA64: +------------------------------ +Parameter 1: Field - The field to change in the instance script. Again, this field needs to be a valid field that has been already defined in the instance's script. +Parameter 2: Target - The target type to use to get the GUID that will be stored at the field index. The value in this field needs to be a valid target type as specified in the reference tables below. + +Sets GUID (64 bits) data for the instance based on the target. Note that this will only work when the creature is inside an instantiable zone that has a valid script (ScriptedInstance) assigned. +Calls ScriptedInstance::SetData64 with field (param1) and data (param2) target's GUID. + +------------------------------ +36 = ACTION_T_UPDATE_TEMPLATE: +------------------------------ +Parameter 1: TemplateId - The creature template ID. The value here must be a valid creature template ID. +Parameter 2: Team - Use model_id from team : Alliance(0) or Horde (1). + +This function temporarily changes creature entry to new entry, display is changed, loot is changed, but AI is not changed. At respawn creature will be reverted to original entry. +Changes the creature to a new creature template of (param1) with team = Alliance if (param2) = false or Horde if (param2) = true + +------------------ +37 = ACTION_T_DIE: +------------------ +Kills the creature +This is commonly used if you need to Instakill the creature for one reason or another. + +-------------------------------- +38 = ACTION_T_ZONE_COMBAT_PULSE: +-------------------------------- +Places all players within the instance into combat with the creature. Only works in combat and only works inside of instances. + +---------------------------- +39 = ACTION_T_CALL_FOR_HELP: +---------------------------- +Parameter 1: Radius - All friendly (not only same faction) creatures will go to help + +Call any friendly creatures (if its not in combat/etc) in radius attack creature target. +Mostly used when call to help more wide that normal aggro radius or auto-used call for assistance, and need apply at some event. + +------------------------- +40 ACTION_T_SET_SHEATH: +------------------------- +Parameter 1: Sheath state +0 SHEATH_STATE_UNARMED not prepared weapon show (not used mostly by creatures) +1 SHEATH_STATE_MELEE melee weapon prepared show +2 SHEATH_STATE_RANGED ranged weapon prepared show + +Let set sheath state for creature. +Note: SHEATH_STATE_RANGED case work in combat state only if combat not start as melee commands. +This possible setup by set ar event AI start (single used EVENT_T_TIMER_OOC set ACTION_T_COMBAT_MOVEMENT 0 for creature that prefered ranged attack) + +------------------------- +41 ACTION_T_FORCE_DESPAWN +------------------------- +Despawns the creature (in or out of combat) +No parameters + +------------------------- +42 ACTION_T_SET_INVINCIBILITY_HP_LEVEL +------------------------- +Parameter 1: min. health level for creature that can be set at damage, 0 used as absent min. health value for apply damage. +Parameter 2: format of paramater 1 value +0 paramater 1 used as flat value +1 paramater 1 used as percent (0..100) from creature max health + +========================================= +Target Types +========================================= +Below is the list of current Target types that EventAI can handle. +Target types are used by certain actions and may effect actions differently + +(# Internal Name Discription) +0 TARGET_T_SELF Self cast +1 TARGET_T_HOSTILE Our current target (ie: highest aggro) +2 TARGET_T_HOSTILE_SECOND_AGGRO Second highest aggro (generaly used for cleaves and some special attacks) +3 TARGET_T_HOSTILE_LAST_AGGRO Dead last on aggro (no idea what this could be used for) +4 TARGET_T_HOSTILE_RANDOM Just any random target on our threat list +5 TARGET_T_HOSTILE_RANDOM_NOT_TOP Any random target except top threat +6 TARGET_T_ACTION_INVOKER Unit who caused this Event to occur (only works for EVENT_T_AGGRO, EVENT_T_KILL, EVENT_T_DEATH, EVENT_T_SPELLHIT, EVENT_T_OOC_LOS, EVENT_T_FRIENDLY_HP) + +========================================= +Cast Flags +========================================= +Below is the list of current Cast Flags that EventAI's spell casting can handle. +Cast flags are handled bitwise. Bit 0 is Interrupt Previous, bit 1 is triggered, etc. +So for example the number "3" (11 in Binary, selecting first 2 options) would mean that this cast has both CAST_INTURRUPT_PREVIOUS and CAST_TRIGGERED. +Another example: the number "5" (101 in Binary, selecting first and third options) would mean that this cast has CAST_INTURRUPT_PREVIOUS and CAST_FORCE_CAST. + +(bit# Decimal Internal Name Discription) +0 1 CAST_INTURRUPT_PREVIOUS Interrupts any previous spell casting (basicaly makes sure that this spell goes off) +1 2 CAST_TRIGGERED Forces the spell to be instant cast and require no mana/reagents. +2 4 CAST_FORCE_CAST Forces spell to cast even if the target is possibly out of range or the creature is possibly out of mana +3 8 CAST_NO_MELEE_IF_OOM Prevents creature from entering melee if out of mana or out of range +4 16 CAST_FORCE_TARGET_SELF Forces the target to cast this spell on itself +5 32 CAST_AURA_NOT_PRESENT Only casts the spell on the target if the target does not have the aura from that spell on itself already. + +NOTE: You can add the numbers in the decimal column to combine flags. + For example if you wanted to use CAST_NO_MELEE_IF_OOM(8) and CAST_TRIGGERED(2) you would simply use 10 in the cast flags field (8 + 2 = 10). + +========================================= +Event Flags +========================================= +Below is the list of current Event Flags that EventAI can handle. Event flags are handled bitwise. + +(bit# Decimal Internal Name Discription) +0 1 EFLAG_REPEATABLE Event repeats (Does not repeat if this flag is not set) +1 2 EFLAG_NORMAL Event occurs in Normal instance difficulty (will not occur in Normal if not set) +2 4 EFLAG_HEROIC Event occurs in Heroic instance difficulty (will not occur in Heroic if not set) +3 8 +4 16 +5 32 +6 64 +7 128 EFLAG_DEBUG_ONLY Prevents events from occuring on Release builds. Useful for testing new features. + +NOTE: You can add the numbers in the decimal column to combine flags. + + +========================================= +Basic Structure of creature_ai_texts +========================================= +Below is a the list of current fields within the texts tables. + +Field_Name Description +----------------------------------------------------------- +entry This value is mearly an NEGATIVE identifier of the current text number. Required for sql queries. Valid range are -1 to -999999 +content_default This is the actual text presented in the default language (English). + +content_loc1 This is the actual text presented in the Localization #1 Clients (Korean) +content_loc2 This is the actual text presented in the Localization #2 Clients (French) +content_loc3 This is the actual text presented in the Localization #3 Clients (German) +content_loc4 This is the actual text presented in the Localization #4 Clients (Chinese) +content_loc5 This is the actual text presented in the Localization #5 Clients (Taiwanese) +content_loc6 This is the actual text presented in the Localization #6 Clients (Spanish) +content_loc7 This is the actual text presented in the Localization #7 Clients (Spanish Mexico) +content_loc8 This is the actual text presented in the Localization #8 Clients (Russian) + +sound This value is the Sound ID that corresponds to the actual text used. +type Variables used to define type of text (Say/Yell/Textemote/Whisper). +language This value is the Language that the text is native in. +emote Value from enum Emote. Only source of text will play this emote (not target, if target are defined in DoScriptText) +comment This is a comment regarding the text entry + +Note: Fields `content_loc1` to `content_loc8` are NULL values by default and are normally handled by seperate localization projects. + +========================================= +Text Types (type) +========================================= +Below is the list of current Text types that texts tables can handle. These were previously seperate Actions in ACID. + +# Internal Name Description +----------------------------------------------------------- +0 CHAT_TYPE_SAY This type sets the text to be displayed as a Say (Speech Bubble). +1 CHAT_TYPE_YELL This type sets the text to be displayed as a Yell (Red Speech Bubble) and usually has a matching Sound ID. +2 CHAT_TYPE_TEXT_EMOTE This type sets the text to be displayed as a text emote in orange in the chat log. +3 CHAT_TYPE_BOSS_EMOTE This type sets the text to be displayed as a text emote in orange in the chat log (Used only for specific Bosses). +4 CHAT_TYPE_WHISPER This type sets the text to be displayed as a whisper to the player in the chat log. +5 CHAT_TYPE_BOSS_WHISPER This type sets the text to be displayed as a whisper to the player in the chat log (Used only for specific Bosses). +6 CHAT_TYPE_ZONE_YELL Same as CHAT_TYPE_YELL but will display to all players in current zone. + +========================================= +Language Types (language) +========================================= +Below is the list of current Language types that are allowed. +This is the Race Language that the text is native to (So it will display properly) + +# Internal Name Description +----------------------------------------------------------- +0 UNIVERSAL Text in this language is understood by ALL Races. +1 ORCISH Text in this language is understood ONLY by Horde Races. +2 DARNASSIAN Text in this language is understood ONLY by the Night Elf Race. +3 TAURAHE Text in this language is understood ONLY by the Tauren Race. +6 DWARVISH Text in this language is understood ONLY by the Dwarf Race. +7 COMMON Text in this language is understood ONLY by Alliance Races. +8 DEMONIC Text in this language is understood ONLY by the Demon Race (Not Implimented). +9 TITAN This language was used by Sargeras to speak with other Titians (Not Implemented). +10 THALASSIAN Text in this language is understood ONLY by the Blood Elf Race. +11 DRACONIC Text in this language is understood ONLY by the Dragon Race. +12 KALIMAG Text will display as Kalimag (not readable by players, language of all elementals) +13 GNOMISH Text in this language is understood ONLY by the Gnome Race. +14 TROLL Text in this language is understood ONLY by the Troll Race. +33 GUTTERSPEAK Text in this language is understood ONLY by the Undead Race. +35 DRAENEI Text in this language is understood ONLY by the Draenai Race. +36 ZOMBIE (not currently used?) +37 GNOMISH BINARY Binary language used by Alliance when drinking Binary Brew +38 GOBLIN BINARY Binary language used by Horce when drinking Binary Brew diff --git a/doc/HowToScript.txt b/doc/HowToScript.txt new file mode 100644 index 00000000000..73968a08b19 --- /dev/null +++ b/doc/HowToScript.txt @@ -0,0 +1,27 @@ + +** HOW TO SCRIPT IN C++ ** + +1 - create a file myscript.cpp in scripts folder. +2 - copy the content of script_default.cpp, it as the structure on how the scripting fuctions are organized. + dont forget to change the name of fuctions, like GossipHello_default to GossipHello_myscript. + +3 - in fuction AddSC_default change to AddSC_myscript. +4 - newscript->Name="default"; change the string to "myscript" this name is the one to be called from the db +5 - dont forget to change the name in here to newscript->pGossipHello = &GossipHello_default; this is where the scripted fuctions are stored. +6 - and last thing is in ScriptMgr.cpp + +add your AddSC_myscript in here + +// -- Scripts to be added -- +extern void AddSC_default(); +// ------------------- + +and here + +// -- Inicialize the Scripts to be Added -- + AddSC_default(); +// ---------------------------------------- + +now start using the player fuctions to script ;) + +hope it helps, any question use our forum. \ No newline at end of file diff --git a/doc/TextTables.txt b/doc/TextTables.txt new file mode 100644 index 00000000000..eac63384785 --- /dev/null +++ b/doc/TextTables.txt @@ -0,0 +1,87 @@ +========================================= +Texts Documentation +========================================= + +Scriptdev2 Revision 695 introduces a new format for using texts in EventAI and SD2 Scripts. +This information relates to the *_texts tables located in the ScriptDev Database. + +Any script can at any time access and use text from any of the three text tables, as long as the entry does in fact exist. +Custom scripters are adviced to store their text data in custom_texts. + +The different tables has ranges of entries allowed for that table. +Reserved EventAI in Mangos entry -1 -> -999999 +script_texts: entry -1000000 -> -1999999 +custom_texts: entry -2000000 -> -2999999 +Any entry out of range for that table will display a startup error. + + +========================================= +Basic Structure of script_texts and custom_texts +========================================= +Below is a the list of current fields within the texts tables. + +Field_Name Description +----------------------------------------------------------- +entry This value is mearly an NEGATIVE identifier of the current text number. Required for sql queries. +content_default This is the actual text presented in the default language (English). + +content_loc1 This is the actual text presented in the Localization #1 Clients (Korean) +content_loc2 This is the actual text presented in the Localization #2 Clients (French) +content_loc3 This is the actual text presented in the Localization #3 Clients (German) +content_loc4 This is the actual text presented in the Localization #4 Clients (Chinese) +content_loc5 This is the actual text presented in the Localization #5 Clients (Taiwanese) +content_loc6 This is the actual text presented in the Localization #6 Clients (Spanish) +content_loc7 This is the actual text presented in the Localization #7 Clients (Spanish Mexico) +content_loc8 This is the actual text presented in the Localization #8 Clients (Russian) + +sound This value is the Sound ID that corresponds to the actual text used (Defined in SoundEntries.dbc). +type Variables used to define type of text (Say/Yell/Textemote/Whisper). +language This value is the Language that the text is native in (Defined in Languages.dbc). +emote Value from enum Emote (defined in Emotes.dbc). Only source of text will play this emote (not target, if target are defined in DoScriptText) +comment This is a comment regarding the text entry (For ACID, accepted format is to use Creature ID of NPC using it). + +Note: Fields `content_loc1` to `content_loc8` are NULL values by default and are handled by seperate localization projects. + + +========================================= +Text Types (type) +========================================= +Below is the list of current Text types that texts tables can handle. These were previously seperate Actions in ACID. + +# Internal Name Description +----------------------------------------------------------- +0 CHAT_TYPE_SAY This type sets the text to be displayed as a Say (Speech Bubble). +1 CHAT_TYPE_YELL This type sets the text to be displayed as a Yell (Red Speech Bubble) and usually has a matching Sound ID. +2 CHAT_TYPE_TEXT_EMOTE This type sets the text to be displayed as a text emote in orange in the chat log. +3 CHAT_TYPE_BOSS_EMOTE This type sets the text to be displayed as a text emote in orange in the chat log (Used only for specific Bosses). +4 CHAT_TYPE_WHISPER This type sets the text to be displayed as a whisper to the player in the chat log. +5 CHAT_TYPE_BOSS_WHISPER This type sets the text to be displayed as a whisper to the player in the chat log (Used only for specific Bosses). +6 CHAT_TYPE_ZONE_YELL Same as CHAT_TYPE_YELL but will display to all players in current zone. + + +========================================= +Language Types (language) +========================================= +Below is the list of current Language types that are allowed. +This is the Race Language that the text is native to (So it will display properly) + +# Internal Name Description +----------------------------------------------------------- +0 UNIVERSAL Text in this language is understood by ALL Races. +1 ORCISH Text in this language is understood ONLY by Horde Races. +2 DARNASSIAN Text in this language is understood ONLY by the Night Elf Race. +3 TAURAHE Text in this language is understood ONLY by the Tauren Race. +6 DWARVISH Text in this language is understood ONLY by the Dwarf Race. +7 COMMON Text in this language is understood ONLY by Alliance Races. +8 DEMONIC Text in this language is understood ONLY by the Demon Race (Not Implimented). +9 TITAN This language was used by Sargeras to speak with other Titians (Not Implemented). +10 THALASSIAN Text in this language is understood ONLY by the Blood Elf Race. +11 DRACONIC Text in this language is understood ONLY by the Dragon Race. +12 KALIMAG Text will display as Kalimag (not readable by players, language of all elementals) +13 GNOMISH Text in this language is understood ONLY by the Gnome Race. +14 TROLL Text in this language is understood ONLY by the Troll Race. +33 GUTTERSPEAK Text in this language is understood ONLY by the Undead Race. +35 DRAENEI Text in this language is understood ONLY by the Draenai Race. +36 ZOMBIE (not currently used?) +37 GNOMISH BINARY Binary language used by Alliance when drinking Binary Brew +38 GOBLIN BINARY Binary language used by Horce when drinking Binary Brew \ No newline at end of file diff --git a/doc/UnixInstall.txt b/doc/UnixInstall.txt new file mode 100644 index 00000000000..45431f679e4 --- /dev/null +++ b/doc/UnixInstall.txt @@ -0,0 +1,60 @@ += TrinityCore -- Linux installation = +Copyright (C) 2008-2010 TrinityCore (http://www.trinitycore.org) + +CHECK http://www.trinitycore.info/w/Linux_Build_HOWTO FOR FURTHER HELP + +Installing TrinityCore is fairly simple on a Linux machine, assuming you +have all required applications + +The most important ones are: + + g++ + gcc + make + cmake version 2.6.x or greater + libmysql++-dev + subversion (for checking out Trinity Database) + mercurial (for checking out the core) + openssl + libssl-dev + zlib1g-dev + libtool + libmysqlclient15-dev + patch + build-essential + mysql-client + +Most of these are included on common Linux distros, others you may have +to install by your self. Please check your distro's repos. + +Make a directory to build in, you can call it anything you want like +build or bin etc, then go into the directory and cmake and make. E.G. +you created a dir named build ad want to have your finalcompiled product +installed in /home/trinity/server, an example sequence of commands can +be : + + cmake ../ -DPREFIX=/home/trinity/server + make + make install + +Thats just about all thats needed. You can however tweak more settings +than where to install using flags built into our cmake files. Just open +up CMakeLists.txt in the main folder and take a look at some of the +flags like + + SCRIPTS --enable or disable trinity script (enabled or disabled by a 1 or 0, enabled by default) + DEBUG --enable debugging (enabled or disabled by a 1 or 0) + CLI --enable command line support (enabled or disabled by a 1 or 0, enabled by default) + PREFIX --prefix directory for install (see example for use) + CONF_DIR --location for your trinity config files + CMAKE_C_FLAGS --advanced users only + CMAKE_CXX_FLAGS --advanced users only + + +Of course, replace the paths in prefix, conf_dir with the directories +you wish to install TrinityCore to. The datadir is where maps, DBCs, and +SQLs are stored. The sysconfdir is where configuration files are stored. + +Once TrinityCore is installed you will need to apply database updates +where necessary. Furthermore, you must configure your installation by +editing the config files in the sysconfdir. diff --git a/doc/gpl-2.0.txt b/doc/gpl-2.0.txt new file mode 100644 index 00000000000..d159169d105 --- /dev/null +++ b/doc/gpl-2.0.txt @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/docs/AuctionHouseBot.txt b/docs/AuctionHouseBot.txt deleted file mode 100644 index cc15a084c9a..00000000000 --- a/docs/AuctionHouseBot.txt +++ /dev/null @@ -1,236 +0,0 @@ -Populates the auction houses with items. It can make the game feel a bit more -like official on small servers. Items and prices are chosen randomly based on -the parameters you define. If an auction expires, auctions are deleted quietly. -AHBot will not buy it's own items, and will not receive mail from the AH -or get returned mail. - -=============================================================================== -~~HOW TO CONFIGURE~~ -=============================================================================== -Step 1.) Create a character that you are going to use as the auction house bot - character. This character will be the auction's owner for all the - items created by the bot. -Step 2.) Go into the realm database and note the account number for the - character. -Step 3.) Go into the characters database and note the character's GUID. -Step 4.) Log in at least once with this character. - (Do not change the configuration before this) -Step 5.) Tune the configuration options in the configuration file and the - Database. - -#These are the settings in the configuration file: -AuctionHouseBot.DEBUG = 0 -AuctionHouseBot.EnableSeller = 0 -AuctionHouseBot.EnableBuyer = 0 -AuctionHouseBot.UseBuyPriceForSeller = 0 -AuctionHouseBot.UseBuyPriceForBuyer = 0 -AuctionHouseBot.Account = 0 -AuctionHouseBot.GUID = 0 -AuctionHouseBot.ItemsPerCycle = 200 - -AuctionHouseBot.DEBUG enables (1) or disables (0) Debug output -AuctionHouseBot.EnableSeller enables (1) or disables (0) the Seller -AuctionHouseBot.EnableBuyer enables (1) or disables (0) the Buyer -AuctionHouseBot.UseBuyPriceForSeller Use SellPrice (0) or BuyPrice (1) for determining prices -AuctionHouseBot.UseBuyPriceForBuyer Use SellPrice (0) or BuyPrice (1) for determining prices -AuctionHouseBot.Account is the account number (in realmd->account table) of the player you want to run as the auction bot. Note: a value of 0 will disable the bot. -AuctionHouseBot.GUID is the GUID (in characters->characters table) of the player you want to run as the auction bot. Note: a value of 0 will disable the bot. -AuctionHouseBot.ItemsPerCycle determines how many items are added each time AHBot is run (once per minute, by default) - -#These are the Filters For filtering certain items/trade goods from the AH -AuctionHouseBot.VendorItems = 0 -AuctionHouseBot.VendorTradeGoods = 0 -AuctionHouseBot.LootItems = 1 -AuctionHouseBot.LootTradeGoods = 1 -AuctionHouseBot.OtherItems = 0 -AuctionHouseBot.OtherTradeGoods = 0 -AuctionHouseBot.No_Bind = 1 -AuctionHouseBot.Bind_When_Picked_Up = 0 -AuctionHouseBot.Bind_When_Equipped = 1 -AuctionHouseBot.Bind_When_Use = 1 -AuctionHouseBot.Bind_Quest_Item = 0 -AuctionHouseBot.DisableBeta_PTR_Unused = 0 -AuctionHouseBot.DisablePermEnchant = 0 -AuctionHouseBot.DisableConjured = 0 -AuctionHouseBot.DisableGems = 0 -AuctionHouseBot.DisableMoney = 0 -AuctionHouseBot.DisableMoneyLoot = 0 -AuctionHouseBot.DisableLootable = 0 -AuctionHouseBot.DisableKeys = 0 -AuctionHouseBot.DisableDuration = 0 -AuctionHouseBot.DisableBOP_Or_Quest_NoReqLevel = 0 - -AuctionHouseBot.VendorItems is a boolean value (0 or 1) that indicates whether to include Vendor only items -AuctionHouseBot.VendorTradeGoods is a boolean value (0 or 1) that indicates whether to include Vendor only Trade Goods -AuctionHouseBot.LootItems is a boolean value (0 or 1) that indicates whether to include Loot/Fish/Skin/etc. only items -AuctionHouseBot.LootTradeGoods is a boolean value (0 or 1) that indicates whether to include Loot/Fish/Skin/etc. only Trade Goods -AuctionHouseBot.OtherItems is a boolean value (0 or 1) that indicates whether to include Other items not covered by the first 2 -AuctionHouseBot.OtherTradeGoods is a boolean value (0 or 1) that indicates whether to include Other Trade Goods not covered by the first 2 -AuctionHouseBot.No_Bind is a boolean value (0 or 1) that indicates whether to include items with a bonding of 0 -AuctionHouseBot.Bind_When_Picked_Up = is a boolean value (0 or 1) that indicates whether to include items with a bonding of 1 -AuctionHouseBot.Bind_When_Equipped = is a boolean value (0 or 1) that indicates whether to include items with a bonding of 2 -AuctionHouseBot.Bind_When_Use = is a boolean value (0 or 1) that indicates whether to include items with a bonding of 3 -AuctionHouseBot.Bind_Quest_Item = is a boolean value (0 or 1) that indicates whether to include items with a bonding of 4 -AuctionHouseBot.DisableBeta_PTR_Unused is a boolean value (0 or 1) that will Disable certain items that are usually unavailable to Players -AuctionHouseBot.DisablePermEnchant is a boolean value (0 or 1) that will Disable Items with a Permanent Enchantment -AuctionHouseBot.DisableConjured is a boolean value (0 or 1) that will Disable Conjured Items -AuctionHouseBot.DisableGems is a boolean value (0 or 1) that will Disable Gems -AuctionHouseBot.DisableMoney is a boolean value (0 or 1) that will Disable Items that are used as money -AuctionHouseBot.DisableMoneyLoot is a boolean value (0 or 1) that will Disable Items that have Money as a loot -AuctionHouseBot.DisableLootable is a boolean value (0 or 1) that will Disable Items that have other items as loot -AuctionHouseBot.DisableKeys is a boolean value (0 or 1) that will Disable Items that are keys -AuctionHouseBot.DisableDuration is a boolean value (0 or 1) that will Disable Items with a duration -AuctionHouseBot.DisableBOP_Or_Quest_NoReqLevel is a boolean value (0 or 1) that will Disable items that are BOP or Quest Item with a Required level that is less than the Item Level - -#These Filters are boolean (0 or 1) and will disable items that are -#specifically meant for the Class named. -#(UnusedClass is Class 10, which was skipped for some reason) -AuctionHouseBot.DisableWarriorItems = 0 -AuctionHouseBot.DisablePaladinItems = 0 -AuctionHouseBot.DisableHunterItems = 0 -AuctionHouseBot.DisableRogueItems = 0 -AuctionHouseBot.DisablePriestItems = 0 -AuctionHouseBot.DisableDKItems = 0 -AuctionHouseBot.DisableShamanItems = 0 -AuctionHouseBot.DisableMageItems = 0 -AuctionHouseBot.DisableWarlockItems = 0 -AuctionHouseBot.DisableUnusedClassItems = 0 -AuctionHouseBot.DisableDruidItems = 0 - -#These are the Filters For filtering certain items/trade goods from the AH -AuctionHouseBot.DisableItemsBelowLevel = 0 -AuctionHouseBot.DisableItemsAboveLevel = 0 -AuctionHouseBot.DisableTGsBelowLevel = 0 -AuctionHouseBot.DisableTGsAboveLevel = 0 -AuctionHouseBot.DisableItemsBelowGUID = 0 -AuctionHouseBot.DisableItemsAboveGUID = 0 -AuctionHouseBot.DisableTGsBelowGUID = 0 -AuctionHouseBot.DisableTGsAboveGUID = 0 -AuctionHouseBot.DisableItemsBelowReqLevel = 0 -AuctionHouseBot.DisableItemsAboveReqLevel = 0 -AuctionHouseBot.DisableTGsBelowReqLevel = 0 -AuctionHouseBot.DisableTGsAboveReqLevel = 0 -AuctionHouseBot.DisableItemsBelowReqSkillRank = 0 -AuctionHouseBot.DisableItemsAboveReqSkillRank = 0 -AuctionHouseBot.DisableTGsBelowReqSkillRank = 0 -AuctionHouseBot.DisableTGsAboveReqSkillRank = 0 - -#These are the settings in the Database: -#Each Auctionhouse has it's own set of these - -MinItems = 0 -#The Minimum number of items you want to keep in the auction houses. -#(default 0 - minimum will be the same as maximum). -#If it is higher than the value of the corresponding maxItems setting, -#it will be set down to match the maxItems setting. - -MaxItems = 0 -#The Maximum number of items you want to keep in the auction houses. - -#These must add up to 100 each one is the percentage -#of the auction items that should be trade goods of -#that quality. A value of 0 will disable. - -PercentGreyTradeGoods = 0 -PercentWhiteTradeGoods = 27 -PercentGreenTradeGoods = 12 -PercentBlueTradeGoods = 10 -PercentPurpleTradeGoods = 1 -PercentOrangeTradeGoods = 0 -PercentYellowTradeGoods = 0 - -PercentGreyItems = 0 -PercentWhiteItems = 10 -PercentGreenItems = 30 -PercentBlueItems = 8 -PercentPurpleItems = 2 -PercentOrangeItems = 0 -PercentYellowItems = 0 - -#MinPrice(Color) is the minimum price adjustment for items. For example the default is 150, which means 150%. So if an item vendors for 1g it would go to auction for a minimum of 1.5g. -#MaxPrice(Color) is the maximum price adjustment for items. -#MinBidPrice(Color) these two control the starting bid as a percent of the buyout price. For example, if MinBidPrice is 30 and MaxBidPrice is 80 the starting bid for the auction will randomly be between 30-80% of the randomly chosen buyout price. -#MaxBidPrice(Color) these two control the starting bid as a percent of the buyout price. For example, if MinBidPrice is 30 and MaxBidPrice is 80 the starting bid for the auction will randomly be between 30-80% of the randomly chosen buyout price. -#MaxStack(Color) is maximum stack size to create for this quality type. A value of zero will disable the maximum stack size for this quality allowing the bot to create stacks (of random size) of items as big as the item type allows. - -MinPriceGrey = 100 -MaxPriceGrey = 150 -MinBidPriceGrey = 70 -MaxBidPriceGrey = 100 -MaxStackGrey = 0 -MinPriceWhite = 150 -MaxPriceWhite = 250 -MinBidPriceWhite = 70 -MaxBidPriceWhite = 100 -MaxStackWhite = 0 -MinPriceGreen = 800 -MaxPriceGreen = 1400 -MinBidPriceGreen = 80 -MaxBidPriceGreen = 100 -MaxStackGreen = 0 -MinPriceBlue = 1250 -MaxPriceBlue = 1750 -MinBidPriceBlue = 75 -MaxBidPriceBlue = 100 -MaxStackBlue = 0 -MinPricePurple = 2250 -MaxPricePurple = 4550 -MinBidPricePurple = 80 -MaxBidPricePurple = 100 -MaxStackPurple = 0 -MinPriceOrange = 4250 -MaxPriceOrange = 5550 -MinBidPriceOrange = 80 -MaxBidPriceOrange = 100 -MaxStackOrange = 0 -MinPriceYellow = 5250 -MaxPriceYellow = 6550 -MinBidPriceYellow = 80 -MaxBidPriceYellow = 100 -MaxStackYellow = 0 - -#These are the multipliers that are applied to the vendor price for an item, that determines if AHBot will buy it or not. -#1 means AHBot will pay the same as (or less than) a vendor would pay, 2 means up to twice as much, etc. - -BuyerPriceGrey = 1 -BuyerPriceWhite = 3 -BuyerPriceGreen = 5 -BuyerPriceBlue = 12 -BuyerPricePurple = 15 -BuyerPriceOrange = 20 -BuyerPriceYellow = 22 - -#BuyerBiddingInterval is the time (in minutes) between bids. -#BuyerBidsPerInterval is the number of bids the buyer will make in a cycle - -BuyerBiddingInterval = 1 -BuyerBidsPerInterval = 1 - - - -How to use ahcommands from the console (CLI) or in game with GM level 3 players: -ahbotoptions - will display usage instructions -ahbotoptions help - will display the list of commands - -ahexpire - will expire all the auctions in the requested auction house that were created by AHBot. -minitems - will set the minimum number of items in the AH before it starts being filled again. -maxitems - will set the maximum number of items in the AH. -percentages - will set the percentage of each quality in the AH -minprice - will set the minimum price multiplier for auctions. -maxprice - will set the maximum price multiplier for auctions. -minbidprice - will set the minimum starting bid as a percent of the buyout price for auctions. -maxbidprice - will set the maximum starting bid as a percent of the buyout price for auctions. -maxstack - will set the maximum number of items in stacks for auctions. 0 will set the maximum to the maximum for that item type. -buyerprice - will set the bid price multiplier for auctions. -biddinginterval - will set the number of minutes between bids on auctions. -bidsperinterval - will set the number of bids to enter per cycle. - -The auction house IDs are: -2 - Alliance -6 - Horde -7 - Neutral - - -AHBot Originally made by Chris K. Currently maintained by Paradox -Much thanks to Chris K, grether and Dolomit6! -AHBot Now includes AHBuyer created by Kerbe as a derivative of AHBot, and later modified by Paradox diff --git a/docs/EventAI.txt b/docs/EventAI.txt deleted file mode 100644 index 7d0294da05f..00000000000 --- a/docs/EventAI.txt +++ /dev/null @@ -1,868 +0,0 @@ -============================================= -EventAI documentation: (updated May 19, 2009) -============================================= - -EventAI allows users to create new creature scripts entierly within the database. - -For the AI to be used, you must first make sure to set AIname for each creature that should use this AI. -UPDATE creature_template SET AIName = 'EventAI' WHERE entry IN (...); - - -========================================= -Basic structure of EventAI -========================================= - -EventAI follows a basic if (Event) then do (Action) format. -Below is the list of current fields of the creature_ai_scripts table. - -(Field_Name) (Description) -id This value is merely an incrementing counter of the current Event number. Required for sql queries. -creature_id Creature id which should trigger this event. - -event_type The type of event (see "Event types" below) -event_inverse_phase_mask Mask with phases this event should NOT trigger in* -event_chance Percentage chance of triggering the event (1 - 100) -event_flags Event flags (repeatable, ... (see below)) -event_param1 Variables for the event (depends on event_type) -event_param2 -event_param3 -event_param4 - -action1_type An action to take when the event occurs (see "Action types" below) -action1_param1 Variables used by Action1 (depends on action_type) -action1_param2 -action1_param3 - -action2_type -action2_param1 -action2_param2 -action2_param3 - -action3_type -action3_param1 -action3_param2 -action3_param3 - -All params are signed 32-bit values (+/- 2147483647). Time values are always in milliseconds. -In case of a percentage value, use value/100 (ie. param = 500 then that means 500%, -50 = -50%) - -[*] Phase mask is a bitmask of phases which shouldn't trigger this event. (ie. Phase mask of value 12 (binary 1100) results in triggering this event in phases 0, 1 and all others with exception for phases 2 and 3 (counting from 0). - - -========================================= -Event types -========================================= - -A list of event types EventAI is able to handle. -Each event type has its own specific interpretation of the params that accompany it. -Params are always read in the ascending order (from Param1 to Param3). -Events will not repeat until the creature exits combat or unless EFLAG_REPEATABLE is set. -Some events such as EVENT_T_AGGRO, EVENT_T_DEATH, EVENT_T_SPAWNED, and EVENT_T_EVADE cannot repeat. - -# Internal name Param usage Description -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -0 EVENT_T_TIMER InitialMin, InitialMax, RepeatMin, RepeatMax Expires at first between (Param1) and (Param2) and then between every (Param3) and (Param4), but only in combat. -1 EVENT_T_TIMER_OOC InitialMin, InitialMax, RepeatMin, RepeatMax Expires at first between (Param1) and (Param2) and then between every (Param3) and (Param4), but only out of combat. -2 EVENT_T_HP HPMax%, HPMin%, RepeatMin, RepeatMax Expires when HP is between (Param1) and (Param2). Will repeat every (Param3) and (Param4). -3 EVENT_T_MANA ManaMax%,ManaMin% RepeatMin, RepeatMax Expires once Mana% is between (Param1) and (Param2). Will repeat every (Param3) and (Param4). -4 EVENT_T_AGGRO NONE Expires upon initial aggro (does not repeat). -5 EVENT_T_KILL RepeatMin, RepeatMax Expires upon killing a player. Will repeat between (Param1) and (Param2). -6 EVENT_T_DEATH NONE Expires upon creature death. -7 EVENT_T_EVADE NONE Expires upon creature EnterEvadeMode(). -8 EVENT_T_SPELLHIT SpellID, Schoolmask, RepeatMin, RepeatMax Expires upon a spell hit. When (param1) is set, it will be used as a trigger. With (param2) specified, the expiration is limited to specific spell schools (-1 for all). Will repeat every (Param3) and (Param4). -9 EVENT_T_RANGE MinDist, MaxDist, RepeatMin, RepeatMax Expires when the highest threat target distance is greater than (Param1) and less than (Param2). Will repeat every (Param3) and (Param4). -10 EVENT_T_OOC_LOS Hostile-or-Not, MaxAllowedRange, RepeatMin, RepeatMax Expires when a unit moves within distance (MaxAllowedRange) of a creature. If (Param1) is zero it will expire only when unit is hostile, friendly otherwise (Param1 = 1), depends generally on faction. Will repeat every (Param3) and (Param4). Does not expire when the creature is in combat. -11 EVENT_T_SPAWNED NONE Expires on initial spawn and on creature respawn (useful for setting ranged movement type). -12 EVENT_T_TARGET_HP HPMax%, HPMin%, RepeatMin, RepeatMax Expires when current target's HP is between (Param1) and (Param2). Will repeat every (Param3) and (Param4). -13 EVENT_T_TARGET_CASTING RepeatMin, RepeatatMax Expires when the current target is casting a spell. Will repeat every (Param1) and (Param2). -14 EVENT_T_FRIENDLY_HP HPDeficit, Radius, RepeatMin, RepeatMax Expires when a friendly unit in radius has at least (Param1) HP missing. Will repeat every (Param3) and (Param4). -15 EVENT_T_FRIENDLY_IS_CC DispelType, Radius, RepeatMin, RepeatMax Expires when a friendly unit is crowd controlled within the given radius (Param2). Will repeat every (Param3) and (Param4). -16 EVENT_T_MISSING_BUFF SpellId, Radius, RepeatMin, RepeatMax Expires when a friendly unit is missing aura(s) given by a spell (Param1) within radius (Param2). Will repeat every (Param3) and (Param4). -17 EVENT_T_SUMMONED_UNIT CreatureId, RepeatMin, RepeatMax Expires after creature with entry = (Param1) is spawned (Param1 = 0 means all spawns). Will repeat every (Param2) and (Param3). -18 EVENT_T_TARGET_MANA ManaMax%, ManaMin%, RepeatMin, RepeatMax -21 EVENT_T_REACHED_HOME NONE Expires when a creature reach it's home(spawn) location after evade. -22 EVENT_T_RECEIVE_EMOTE EmoteId, Condition, CondValue1, CondValue2 Expires when a creature receives an emote with emote text id (enum TextEmotes) in (Param1). Conditions can be defined (Param2) with optional values (Param3,Param4), see enum ConditionType. -23 EVENT_T_BUFFED SpellID, AmmountInStack, RepeatMin, RepeatMax Expires when a creature has spell (Param1) auras applied in a stack greater or equal to value provided in (Param2). Will repeat every (Param3) and (Param4). -24 EVENT_T_TARGET_BUFFED SpellID, AmmountInStack, RepeatMin, RepeatMax Expires when a target unit has spell (Param1) auras applied in a stack greater or equal to value provided in (Param2). Will repeat every (Param3) and (Param4). -35 EVENT_T_RESET NONE Expires when creature leaves combat, spawns or respawns. - -========================================= -Action Types -========================================= - -A list of action types that EventAI can handle. -Each event type has its own specific interpretation of it's params, like every event type. - -# Internal name Param usage Description -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -0 ACTION_T_NONE No Action Does nothing. -1 ACTION_T_TEXT -TextId1, -TextId2, -TextId3 Simply displays the specified -TextId. When -TextId2 and -TextId3 are specified, the selection will be randomized. Text types are defined, along with other options for the text, in a table below. All values needs to be negative. -2 ACTION_T_SET_FACTION FactionId Changes faction for a creature. When param1 is zero, creature will revert to it's default faction. -3 ACTION_T_MORPH_TO_ENTRY_OR_MODEL CreatureEntry, ModelId Set either model from creature_template.entry (Param1) OR explicit modelId (Param2). If (Param1) AND (Param2) are both 0, demorph and revert to the default model. -4 ACTION_T_SOUND SoundId Plays a sound -5 ACTION_T_EMOTE EmoteId Does an emote -6 ACTION_T_RANDOM_SAY UNUSED -7 ACTION_T_RANDOM_YELL UNUSED -8 ACTION_T_RANDOM_TEXTEMOTE UNUSED -9 ACTION_T_RANDOM_SOUND SoundId1, SoundId2, SoundId3 Plays a random sound * -10 ACTION_T_RANDOM_EMOTE EmoteId1, EmoteId2, EmoteId3 Emotes a random emote -11 ACTION_T_CAST SpellId, Target, CastFlags Casts spell (Param1) on a target (Param2) using cast flags (specified below). -12 ACTION_T_SUMMON CreatureID, Target, Duration Summons a creature (Param1) for (Param3) duration and orders it to attach (Param2) target. Spawns on top of current creature. -13 ACTION_T_THREAT_SINGLE_PCT Threat%, Target Modifies a threat by (Param1) percent on a target (Param2). -14 ACTION_T_THREAT_ALL_PCT Threat% Modifies a threat by (Param1) on all targets in the threat list (using -100% here will result in full aggro dump). -15 ACTION_T_QUEST_EVENT QuestID, Target Calls AreaExploredOrEventHappens with (Param1) for a target in (Param2). -16 ACTION_T_QUEST_CASTCREATUREGO CreatureID, SpellId, Target Sends CastCreatureOrGo for a creature specified by CreatureId (Param1) with provided spell id (Param2) for a target in (Param3). -17 ACTION_T_SET_UNIT_FIELD Field_Number, Value, Target Sets a unit field (Param1) to provided value (Param2) on a target in (Param3). -18 ACTION_T_SET_UNIT_FLAG Flags, Target Sets flag (flags can be used together to modify multiple flags at once) on a target (Param2). -19 ACTION_T_REMOVE_UNIT_FLAG Flags, Target Removes flag on a target (Param2). -20 ACTION_T_AUTO_ATTACK AllowAutoAttack Stop melee attack when (Param1) is zero, otherwise continue attacking / allow melee attack. -21 ACTION_T_COMBAT_MOVEMENT AllowCombatMovement Stop combat based movement when (Param1) is zero, otherwise continue/allow combat based movement (targeted movement generator). -22 ACTION_T_SET_PHASE Phase Sets the current phase to (Param1). -23 ACTION_T_INC_PHASE Value Increments the phase by (Param1). May be negative to decrement, but should not be zero. -24 ACTION_T_EVADE No Params Forces the creature to evade, wiping all threat and dropping combat. -25 ACTION_T_FLEE_FOR_ASSIST No Params Causes the creature to flee for assistence (often at low health). -26 ACTION_T_QUEST_EVENT_ALL QuestId Calls GroupEventHappens with (Param1). Only used if it's _expected_ event should call quest completion for all players in a current party. -27 ACTION_T_CASTCREATUREGO_ALL QuestId, SpellId Calls CastedCreatureOrGo for all players on the threat list with quest id specified in (Param1) and spell id in (Param2). -28 ACTION_T_REMOVEAURASFROMSPELL Target, Spellid Removes all auras on a target (Param1) caused by a spell (Param2). -29 ACTION_T_RANGED_MOVEMENT Distance, Angle Changes the movement generator to a ranged type. (note: default melee type can still be set by using 0 as angle and 0 as distance). -30 ACTION_T_RANDOM_PHASE PhaseId1, PhaseId2, PhaseId3 Sets a phase to a specified id(s)* -31 ACTION_T_RANDOM_PHASE_RANGE PhaseMin, PhaseMax Sets a phase to a random id (Phase = PhaseMin + rnd % PhaseMin-PhaseMax). PhaseMax must be greater than PhaseMin. -32 ACTION_T_SUMMON CreatureID, Target, SummonID Summons a creature (Param1) to attack target (Param2) at location specified by EventAI_Summons (Param3). -33 ACTION_T_KILLED_MONSTER CreatureID, Target Calls KilledMonster (Param1) for a target (Param2). -34 ACTION_T_SET_INST_DATA Field, Data Calls ScriptedInstance::SetData with field (Param1) and data (Param2). -35 ACTION_T_SET_INST_DATA64 Field, Target Calls ScriptedInstance::SetData64 with field (Param1) and target's GUID (Param2). -36 ACTION_T_UPDATE_TEMPLATE TemplateId, Team Changes a creature's template to (Param1) with team = Alliance or Horde when (Param2) is either false or true respectively. -37 ACTION_T_DIE No Params Kills the creature -38 ACTION_T_ZONE_COMBAT_PULSE No Params Puts all players within an instance into combat with the creature. Only works when a creature is already in combat. Doesn't work outside instances. -39 ACTION_T_CALL_FOR_HELP Radius Call any friendly out-of-combat creatures in a radius (Param1) to attack current creature's target. -40 ACTION_T_SET_SHEATH Sheath Sets sheath state for a creature (0 = no weapon, 1 = melee weapon, 2 = ranged weapon). -41 ACTION_T_FORCE_DESPAWN No Params Despawns the creature -42 ACTION_T_SET_INVINCIBILITY_HP_LEVEL hp_level, is_percent Set min. health level for creature that can be set at damage as flat value or percent from max health - -* = Use -1 where the param is expected to do nothing. Random constant is generated for each event, so if you have a random yell and a random sound, they will be linked up with each other (ie. param2 with param2). - - -========================================= -Event Types -========================================= -Note: -COMBAT ONLY - Means that this event will only trigger durring combat. -OUT OF COMBAT ONLY - Means that this event will only trigger while out of combat. -BOTH - This event can trigger both in and out of combat. - -Events that do not have lables on them are events that are directly involved with the in and out of combat state. - ------------------- -0 = EVENT_T_TIMER: ------------------- -Parameter 1: InitialMin - Minumum Time used to calculate Random Initial Expire -Parameter 2: InitialMax - Maximum Time used to calculate Random Initial Expire -Parameter 3: RepeatMin - Minimum Time used to calculate Random Repeat Expire -Parameter 4: RepeatMax - Maximum Time used to calculate Random Repeat Expire - -COMBAT ONLY! - Expires first between (Param1) and (Param2) and then between every (Param3) and (Param4) from then on. -This is commonly used for spells that repeat cast during combat (Simulate Spell Cooldown). - ----------------------- -1 = EVENT_T_TIMER_OOC: ----------------------- -Parameter 1: InitialMin - Minumum Time used to calculate Random Initial Expire -Parameter 2: InitialMax - Maximum Time used to calculate Random Initial Expire -Parameter 3: RepeatMin - Minimum Time used to calculate Random Repeat Expire -Parameter 4: RepeatMax - Maximum Time used to calculate Random Repeat Expire - -OUT OF COMBAT ONLY! - Expires first between (Param1) and (Param2) and then between every (Param3) and (Param4) from then on. -This is commonly used for events that occur and repeat outside of combat. - ---------------- -2 = EVENT_T_HP: ---------------- -Parameter 1: HPMax% - Maximum HP% That this Event will Expire -Parameter 2: HPMin% - Minimum HP% That this Event will Expire -Parameter 3: RepeatMin - Minimum Time used to calculate Random Repeat Expire -Parameter 4: RepeatMax - Maximum Time used to calculate Random Repeat Expire - -BOTH - Expires when HP is between (Param1) and (Param2). Will repeat every (Param3) and (Param4). -This is commonly used for events that trigger at a specific HP% (Such as Heal/Enrage Spells or NPC's that Flee). - ------------------ -3 = EVENT_T_MANA: ------------------ -Parameter 1: ManaMax% - Maximum Mana% That this Event will Expire -Parameter 2: ManaMin% - Minimum Mana% That this Event will Expire -Parameter 3: RepeatMin - Minimum Time used to calculate Random Repeat Expire -Parameter 4: RepeatMax - Maximum Time used to calculate Random Repeat Expire - -BOTH - Expires once Mana% is between (Param1) and (Param2). Will repeat every (Param3) and (Param4). -This is commonly used for events where an NPC low on Mana will do something (Such as stop casting spells and switch to melee). - ------------------- -4 = EVENT_T_AGGRO: ------------------- -This Event Expires upon initial aggro (does not repeat). - ------------------ -5 = EVENT_T_KILL: ------------------ -Parameter 1: RepeatMin - Minimum Time used to calculate Random Repeat Expire -Parameter 2: RepeatMax - Maximum Time used to calculate Random Repeat Expire - -COMBAT ONLY! - Expires upon killing a player. Will repeat every (Param1) and (Param2). -This Event Expires upon killing a player. It is commonly used for NPC's who yell or do something after killing a player. - ------------------- -6 = EVENT_T_DEATH: ------------------- -This Event Expires upon Death of the Scripted NPC. -This is commonly used for NPC's who have a yell on death or cast some kind if summon spell when they die. - ------------------- -7 = EVENT_T_EVADE: ------------------- -This Event Expires upon the creature EnterEvadeMode(). -This is commonly used for NPC's who use phases, allows you to reset their phase to 0 upon evade to prevent possible strange behavior. - ---------------------- -8 = EVENT_T_SPELLHIT: ---------------------- -Parameter 1: SpellID - The Spell ID that will trigger the event to occur (NOTE: If you use Spell School as the trigger set this value to 0) -Parameter 2: School - Spell School to trigger the event (NOTE: If you use a SpellID then set this value to -1) - *See Below for Spell School Bitmask Values* -Parameter 3: RepeatMin - Minimum Time used to calculate Random Repeat Expire -Parameter 4: RepeatMax - Maximum Time used to calculate Random Repeat Expire - -BOTH - Expires upon Spell hit. If (param1) is set will only expire on that spell OR If (param2) is set it will only expire on spells of that school. Will repeat every (Param3) and (Param4). -This Event is commonly used for NPC's who can do special things when you cast a spell (Or specific spell) on them. - -(name, school, schoolmask) -SPELL_SCHOOL_NORMAL = 0, ==> 1 -SPELL_SCHOOL_HOLY = 1, ==> 2 -SPELL_SCHOOL_FIRE = 2, ==> 4 -SPELL_SCHOOL_NATURE = 3, ==> 8 -SPELL_SCHOOL_FROST = 4, ==> 16 -SPELL_SCHOOL_SHADOW = 5, ==> 32 -SPELL_SCHOOL_ARCANE = 6, ==> 64 -Use These Values For Schoolmask (Param2) or Any Combinations Of These Schoolmasks for Multiple Schools. - ------------------- -9 = EVENT_T_RANGE: ------------------- -Parameter 1: MinDist - This Distance is the Minimum Distance between the NPC and it's target to allow this Event to Expire -Parameter 2: MaxDist - This Distance is the Maximum Distance between the NPC and it's target to allow this Event to Expire -Parameter 3: RepeatMin - Minimum Time used to calculate Random Repeat Expire -Parameter 4: RepeatMax - Maximum Time used to calculate Random Repeat Expire - -COMBAT ONLY! - Expires when the highest threat target distance is greater than (Param1) and less than (Param2). Will repeat every (Param3) and (Param4). -This Event is commonly used for NPC's who have Ranged Combat and will Throw/Shoot between a certian distance. - ---------------------- -10 = EVENT_T_OOC_LOS: ---------------------- -Parameter 1: Hostile-or-Not - This will expire if Unit are hostile. If Param1=1 it will only expire if Unit are not Hostile(generally determined by faction) -Parameter 2: MaxAllowedRange - Expires when a Unit moves within this distance to creature -Parameter 3: RepeatMin - Minimum Time used to calculate Random Repeat Expire -Parameter 4: RepeatMax - Maximum Time used to calculate Random Repeat Expire - -OUT OF COMBAT! -This Event is commonly used for NPC's who do something or say something to you when you walk past them Out of Combat. - ---------------------- -11 = EVENT_T_SPAWNED: ---------------------- -Expires at initial spawn and at creature respawn. -This Event is commonly used for setting ranged movement type or Summoning a Pet on Spawn -Parameter 1: 0: works always, 1: works on map in Parameter 2, 2: works on zone/subzone in Parameter 2 -Parameter 2: depends on Parameter 1: for 1 it is map ID, for 2 it is area ID to check - ------------------------ -12 = EVENT_T_TARGET_HP: ------------------------ -Parameter 1: HPMax% - Maximum HP% That this Event will Expire -Parameter 2: HPMin% - Minimum HP% That this Event will Expire -Parameter 3: RepeatMin - Minimum Time used to calculate Random Repeat Expire -Parameter 4: RepeatMax - Maximum Time used to calculate Random Repeat Expire - -COMBAT ONLY! - Expires when Current NPC's Target's HP is between (Param1) and (Param2). Will repeat every (Param3) and (Param4). -This Event is commonly used for NPC's who have a special ability (Like Execute) that only casts when a Player HP is low. - ----------------------------- -13 = EVENT_T_TARGET_CASTING: ----------------------------- -Parameter 1: RepeatMin - Minimum Time used to calculate Random Repeat Expire -Parameter 2: RepeatMax - Maximum Time used to calculate Random Repeat Expire - -COMBAT ONLY! - Expires when the current target is casting a spell. Will repeat every (Param1) and (Param2). -This event is commonly used for NPC's who will cast a counter spell when their target starts to cast a spell. - -------------------------- -14 = EVENT_T_FRIENDLY_HP: -------------------------- -Parameter 1: HPDeficit - This is the Amount of HP Missing from Full HP to trigger this event (You would need to calculate the amount of HP the event happens and subtract that from Full HP Value to get this number) -Parameter 2: Radius - This is the Range in Yards the NPC will scan for nearby Friendlies (Faction is Friendly To) for the missing amount of HP in Param1. -Parameter 3: RepeatMin - Minimum Time used to calculate Random Repeat Expire -Parameter 4: RepeatMax - Maximum Time used to calculate Random Repeat Expire - -COMBAT ONLY! - Expires when a friendly unit in radius(param2) has at least (param1) hp missing. Will repeat every (Param3) and (Param4). -This is commonly used when an NPC in Combat will heal a nearby Friendly NPC in Combat with a Heal/Renew Spell. - ----------------------------- -15 = EVENT_T_FRIENDLY_IS_CC: ----------------------------- -Parameter 1: DispelType - Dispel Type to trigger the event - *See Below for Dispel Bitmask Values* -Parameter 2: Radius - This is the Range in Yards the NPC will scan for nearby Friendlies being Crowd Controlled -Parameter 3: RepeatMin - Minimum Time used to calculate Random Repeat Expire -Parameter 4: RepeatMax - Maximum Time used to calculate Random Repeat Expire - -COMBAT ONLY! - Expires when a friendly unit is Crowd controlled within the given radius (param2). Will repeat every (Param3) and (Param4). -This is commonly used for NPC's who can come to the resule of other Friendly NPC's if being Crowd Controlled - --------------------------- -16 = EVENT_T_MISSING_BUFF: --------------------------- -Parameter 1: SpellId - This is the SpellID That the Aura Check will look for (If it is missing this Aura) -Parameter 2: Radius - This is the Range in Yards the NPC will scan for nearby Friendlies (Faction is Friendly To) for the missing Aura. -Parameter 3: RepeatMin - Minimum Time used to calculate Random Repeat Expire -Parameter 4: RepeatMax - Maximum Time used to calculate Random Repeat Expire - -BOTH - Expires when a friendly unit is missing aura's given by spell (param1) within radius (param2). Will repeat every (Param3) and (Param4). -This is commonly used for NPC's who watch friendly units for a debuff to end so they can recast it on them again. - ---------------------------- -17 = EVENT_T_SUMMONED_UNIT: ---------------------------- -Parameter 1: CreatureId - The CreatureID that the NPC is watching to spawn to trigger this event -Parameter 2: RepeatMin - Minimum Time used to calculate Random Repeat Expire -Parameter 3: RepeatMax - Maximum Time used to calculate Random Repeat Expire - -BOTH - Expires after creature with entry(Param1) is spawned or for all spawns if param1 = 0. Will repeat every (Param2) and (Param3) . -This is commonly used for NPC's who will do something special once another NPC is summoned. Usually used is Complex Scripts or Special Events. - ---------------------------- -21 = EVENT_T_REACHED_HOME: ---------------------------- -Expires only when creature has returned to it's home location after Evade. Out of combat event. -Most commonly used to cast spells that can not be casted in EVENT_T_EVADE and other effects that does not fit in while still running back to spawn/home location. - ---------------------------- -22 = EVENT_T_RECEIVE_EMOTE: ---------------------------- -Expires only when creature receive emote from player. Valid text emote id's are in Mangos source (enum TextEmotes) -Event does not require any conditions to process, however many are ecpected to have condition. - ---------------------------- -23 = EVENT_T_BUFFED : ---------------------------- -Parameter 1: SpellId - This is the SpellID That the Aura Check will look for -Parameter 2: Amount - This is the amount of SpellID's auras at creature required for event expire. -Parameter 3: RepeatMin - Minimum Time used to calculate Random Repeat Expire -Parameter 4: RepeatMax - Maximum Time used to calculate Random Repeat Expire - ---------------------------- -24 = EVENT_T_TARGET_BUFFED: ---------------------------- -Parameter 1: SpellId - This is the SpellID That the Aura Check will look for -Parameter 2: Amount - This is the amount of SpellID's auras at target unit required for event expire. -Parameter 3: RepeatMin - Minimum Time used to calculate Random Repeat Expire -Parameter 4: RepeatMax - Maximum Time used to calculate Random Repeat Expire - -EventAI use conditions from available in Mangos (enum ConditionType) -Current implemented conditions: -CONDITION_NONE (0) 0 0 -CONDITION_AURA (1) spell_id effindex -CONDITION_ITEM (2) item_id count -CONDITION_ITEM_EQUIPPED (3) item_id count -CONDITION_ZONEID (4) zone_id 0 -CONDITION_REPUTATION_RANK (5) faction_id min_rank -CONDITION_TEAM (6) player_team 0 (469-Alliance / 67-Horde) -CONDITION_SKILL (7) skill_id min_skill_value -CONDITION_QUESTREWARDED (8) quest_id 0, if quest are rewarded -CONDITION_QUESTTAKEN (9) quest_id 0, while quest active(incomplete) -CONDITION_ACTIVE_EVENT (12) event_id 0, note this is id from dbc, also defined in Mangos source(enum HolidayIds) NOT id of game_event in database - -========================================= -Action Types -========================================= - ------------------ -1 = ACTION_T_TEXT: ------------------ -Parameter 1: The entry of the text that the NPC should use from eventai_texts table. Optionally a entry from other tables can be used (such as custom_texts). - Entry are required to be negative and exist in a *_texts-table. The type text to be displayed are defined in the texts-table itself (Say, Yell, Whisper, Emote Text, Boss Whisper, Boss Emote) - Other options are also to be defined in the texts-table, such as a sound to be heard with the text and the language used in output (common, dwarvish, etc). - In case this entry has a localized version of the text, the localized text will be displayed in client that support this locale. - -Parameter 2: Optional. TextId can be defined in addition. The same apply to this as explained above, however eventAI will randomize between the two. -Parameter 3: Optional, if Parameter 2 exist. In this case, eventAI will randomize between three. - -Read at bottom for documentation of creature_ai_texts-table. - ------------------- -2 = ACTION_T_SET_FACTION: ------------------- -Parameter 1: FactionId from Faction.dbc OR 0. Changes faction for creature. If 0, creature will revert to it's default faction if previously changed. - ------------------------ -3 = ACTION_T_MORPH_TO_ENTRY_OR_MODEL: ------------------------ -Parameter 1: Creature entry from creature_template. Action will then change to the model this creature are using. -Parameter 2: If parameter 1 is 0, then this modelId will be used (in case parameter 1 exist, parameter 2 will not be used) - -If both parameter 1 and 2 is 0, the creature will DeMorph, and use it's default model. - -------------------- -4 = ACTION_T_SOUND: -------------------- -Parameter 1: The Sound ID to be played. (Sound IDs are contained in the DBC files.) - -The creature will play the specified sound. -This is commonly used for Bosses who Yell and then also have a Voice for the same thing. - -------------------- -5 = ACTION_T_EMOTE: -------------------- -Parameter 1: The Emote ID that the creature should perform. (Emote IDs are also contained in the DBC but they can be found in the mangos source as well). - -The creature will perform a visual emote. Unlike a text emote, a visual emote is one where the creature will actually move or perform a gesture. -This is commonly used for NPC's who may perform a special action (Salute, Roar, ect...). Not all player emotes work for creature models. - ------------------------- -6 = ACTION_T_RANDOM_SAY: ------------------------- -UNUSED Can be reused to create new action type - -------------------------- -7 = ACTION_T_RANDOM_YELL: -------------------------- -UNUSED Can be reused to create new action type - ------------------------------- -8 = ACTION_T_RANDOM_TEXTEMOTE: ------------------------------- -UNUSED Can be reused to create new action type - --------------------------- -9 = ACTION_T_RANDOM_SOUND: --------------------------- -Parameter 1: The Sound ID to be played as Random Choice #1. -Parameter 2: The Sound ID to be played as Random Choice #2. -Parameter 3: The Sound ID to be played as Random Choice #3. - -Similar to the ACTION_T_SOUND action, it will choose at random a sound to play. - ---------------------------- -10 = ACTION_T_RANDOM_EMOTE: ---------------------------- -Parameter 1: The Emote ID to be played as Random Choice #1. -Parameter 2: The Emote ID to be played as Random Choice #2. -Parameter 3: The Emote ID to be played as Random Choice #3. - -Similar to the ACTION_T_EMOTE action, it will choose at random an Emote to Visually Perform. - -------------------- -11 = ACTION_T_CAST: -------------------- -Parameter 1: SpellId - The Spell ID to use for the NPC to cast. The value used in this field needs to be a valid Spell ID. -Parameter 2: Target - The Target Type defining who the creature should cast the spell at. The value in this field needs to be a valid Target Type as specified in the reference tables below. -Parameter 3: CastFlags - See Table Below for Cast Flag Bitmask Values. If you are unsure what to set this value at leave it at 0. - -The creature will cast a spell specified by a spell ID on a target specified by the target type. -This is commonly used for NPC's who cast spells. - ---------------------- -12 = ACTION_T_SUMMON: ---------------------- -Parameter 1: CreatureID - The Creature Template ID to be Summoned. The value here needs to be a valid Creature Template ID. -Parameter 2: Target - The Target Type defining who the Summoned creature will attack once spawned. The value in this field needs to be a valid Target Type as specified in the reference tables below. -Parameter 3: Duration - The duration until the summoned creature should be unsummoned AFTER Combat ends. The value in this field is in milliseconds or 0. - -The NPC will Summon another creature at the same spot as itself that will attack the specified target. -NOTE: Almost all Creature Summons have proper Summon Spells that should be used when possible. This Action is a powerful last resort option only to be used if nothing else works. -NOTE: Using Target Type 0 will cause the Summoned creature to not attack anyone. -NOTE: If Duration is set at 0, then the summoned creature will not despawn until it has died. -This is used as a manual way to force an NPC to Summon. --------------------------------- -13 = ACTION_T_THREAT_SINGLE_PCT: --------------------------------- -Parameter 1: Threat% - Threat percent that should be modified. The value in this field can range from -100 to +100. If it is negative, threat will be taken away and if positive, threat will be added. -Parameter 2: Target - The Target Type defining on whom the threat change should occur. The value in this field needs to be a valid target type as specified in the reference tables below. - -This action will modify the threat of a target in the creature's threat list by the specified percent. -This is commonly used to allow an NPC to adjust the Threat to a single player. - ------------------------------ -14 = ACTION_T_THREAT_ALL_PCT: ------------------------------ -Parameter 1: Threat% - The percent that should be used in modifying everyone's threat in the creature's threat list. The value here can range from -100 to +100. - -This action will modify the threat for everyone in the creature's threat list by the specified percent. -NOTE: Using -100 will cause the creature to reset everyone's threat to 0 so that everyone has the same amount of threat. It will NOT remove anyone from the threat list. -This is commonly used to allow an NPC to drop threat for all players to zero. - --------------------------- -15 = ACTION_T_QUEST_EVENT: --------------------------- -Parameter 1: QuestID - The Quest Template ID. The value here must be a valid quest template ID. Furthermore, the quest should have SpecialFlags | 2 as it would need to be completed by an external event which is the activation of this action. -Parameter 2: Target - The Target Type defining whom the quest should be completed for. The value in this field needs to be a valid target type as specified in the reference tables below. - -This action will satisfy the external completion requirement for the quest for the specified target defined by the target type. -NOTE: This action can only be used with player targets so it must be ensured that the target type will point to a player. -This is commonly used for Quests where only ONE player will gain credit for the quest. - ------------------------------ -16 = ACTION_T_CASTCREATUREGO: ------------------------------ -Parameter 1: CreatureID - The Creature Template ID to be Summoned. The value here needs to be a valid Creature Template ID. -Parameter 2: SpellId - The Spell ID to use to simulate the cast. The value used in this field needs to be a valid Spell ID. -Parameter 3: Target - The Target Type defining whom the quest credit should be given to. The value in this field needs to be a valid target type as specified in the reference tables below. - -This action will call CastedCreatureOrGO() function for the player. It can be used to give quest credit for casting a spell on the creature. -This is commonly used for NPC's who have a special requirement to have a Spell cast on them to complete a quest. - ------------------------------ -17 = ACTION_T_SET_UNIT_FIELD: ------------------------------ -Parameter 1: Field_Number - The index of the Field Number to be changed. Use (http://wiki.udbforums.org/index.php/Character_data) for a list of indeces and what they control. Creatures only contain the OBJECT_FIELD_* and UNIT_FIELD_* fields. They do not contain the PLAYER_FIELD_* fields. -Parameter 2: Value - The new value to be put in the field. -Parameter 3: Target - The Target Type defining for whom the unit field should be changed. The value in this field needs to be a valid target type as specified in the reference tables below. - -When activated, this action can change the target's unit field values. More information on the field value indeces can be found at (http://wiki.udbforums.org/index.php/Character_data) - ----------------------------- -18 = ACTION_T_SET_UNIT_FLAG: ----------------------------- -Parameter 1: Flags - The flag(s) to be set. Multiple flags can be set by using bitwise-OR on them (adding them together). -Parameter 2: Target - The Target Type defining for whom the flags should be changed. The value in this field needs to be a valid Target Type as specified in the reference tables below. - -When activated, this action changes the target's flags by adding (turning on) more flags. For example, this action can make the creature unattackable/unselectable if the right flags are used. - -------------------------------- -19 = ACTION_T_REMOVE_UNIT_FLAG: -------------------------------- -Parameter 1: Flags - The flag(s) to be removed. Multiple flags can be set by using bitwise-OR on them (adding them together). -Parameter 2: Target - The target type defining for whom the flags should be changed. The value in this field needs to be a valid Target Type as specified in the reference tables below. - -When activated, this action changes the target's flags by removing (turning off) flags. For example, this action can make the creature normal after it was unattackable/unselectable if the right flags are used. - --------------------------- -20 = ACTION_T_AUTO_ATTACK: --------------------------- -Parameter 1: AllowAutoAttack - If zero, then the creature will stop its melee attacks. If non-zero, then the creature will either continue its melee attacks (the action would then have no effect) or it will start its melee attacks on the target with the top threat if its melee attacks were previously stopped. - -This action controls whether or not the creature should stop or start the auto melee attack. -NOTE: The ACID Dev Team has conformed to using either 0 or 1 for the Param values (0 = Stop Melee, 1 = Start Melee). -This is commonly used in combination with EVENT_T_RANGE and ACTION_T_COMBAT_MOVEMENT for Ranged Combat for Mages and Spell Casters. - ------------------------------- -21 = ACTION_T_COMBAT_MOVEMENT: ------------------------------- -Parameter 1: If zero, then the creature will stop moving towards its victim (if its victim gets out of melee range) and will be stationary. If non-zero, then the creature will either continue to follow its victim (the action would have no effect) or it will start to follow the target with the top threat if its movement was disabled before. -Parameter 2: If non-zero, then stop melee combat state (if param1=0) or start melee combat state (if param1!=0) and creature in combat with selected target. - -This action controls whether or not the creature will always move towards its target. -NOTE: The ACID Dev Team has conformed to using either 0 or 1 for the Param values. (0 = Stop Movement, 1 = Start Movement) -This is commonly used with EVENT_T_RANGE and ACTION_T_AUTO_ATTACK for NPC's who engage in Ranged Comabt (Either Spells or Ranged Attacks) -Parameter 2 specialy used for ranged combat proper client side visual show ranged weapon in proper state. - ------------------------- -22 = ACTION_T_SET_PHASE: ------------------------- -Parameter 1: The new phase to set the creature in. This number must be an integer between 0 and 31. Numbers outside of that range will result in an error. - -When activated, this action sets the creature's event to the specified value. -NOTE: The creature's current Phase is NOT reset at creature evade. You must manually set the phase back to 0 at EVENT_T_RESET. -NOTE: The value used for the Param is the actual Phase Number (Not The Event_Inverse_Phase_Mask) -This is commonly used for complex scripts with several phases and you need to switch to a different phase. - ------------------------- -23 = ACTION_T_INC_PHASE: ------------------------- -Parameter 1: Value - The number of phases to increase or decrease. Use negative values to decrease the current phase. - -When activated, this action will increase (or decrease) the current creature's phase. -NOTE: After increasing or decreasing the phase by this action, the current phase must NOT be lower than 0 or exceed 31. -This can be used instead of ACTION_T_SET_PHASE to change phases in scripts. Just a user friendly option for changing phases. - --------------------- -24 = ACTION_T_EVADE: --------------------- -When activated, the creature will immediately exit out of combat, clear its threat list, and move back to its spawn point. Basically, this action will reset the whole encounter. -NOTE: All Param Values Are 0 for this Action. - -------------------- -25 = ACTION_T_FLEE: -------------------- -When activated, the creature will try to flee from combat. Currently this is done by it casting a fear-like spell on itself called "Run Away". -A Better Flee system is in Development. -NOTE: All Param Values Are 0 for this Action. - ------------------------------- -26 = ACTION_T_QUEST_EVENT_ALL: ------------------------------- -Parameter 1: QuestId - The quest ID to finish for everyone. - -This action does the same thing as the ACTION_T_QUEST_EVENT does but it does it for all players in the creature's threat list. -NOTE: If a player is not in the NPC's threat list for whatever reason, he/she won't get the quest completed. - ---------------------------------- -27 = ACTION_T_CASTCREATUREGO_ALL: ---------------------------------- -Parameter 1: QuestId - The quest template ID. -Parameter 2: SpellId - The spell ID used to simulate the cast. - -This action does the same thing as the ACTION_T_CASTCREATUREGO does but it does it for all players in the creature's threat list. -NOTE: If a player is not in its threat list for whatever reason, he/she won't receive the cast emulation. - ------------------------------------ -28 = ACTION_T_REMOVEAURASFROMSPELL: ------------------------------------ -Parameter 1: Target - The target type defining for whom the unit field should be changed. The value in this field needs to be a valid target type as specified in the reference tables below. -Parameter 2: SpellId - The spell ID whose auras will be removed. - -This action will remove all auras from a specific spell from the target. -This is commonly used for NPC's who have an OOC Aura that is removed at combat start or a similar idea (Like Stealth or Shape Shift) - ------------------------------- -29 = ACTION_T_RANGED_MOVEMENT: ------------------------------- -Parameter 1: Distance - The distance the mob should keep between it and its target. -Parameter 2: Angle - The angle the mob should use. - -This action changes the movement type generator to ranged type using the specified values for angle and distance. -NOTE: Specifying zero angle and distance will make it just melee instead. -This is commonly used for NPC's who always attack at range and you can specify the distance they will maintain from the target. - ---------------------------- -30 = ACTION_T_RANDOM_PHASE: ---------------------------- -Parameter 1: PhaseId1 - A possible random phase choice. -Parameter 2: PhaseId2 - A possible random phase choice. -Parameter 3: PhaseId3 - A possible random phase choice. - -Randomly sets the phase to one from the three parameter choices. -NOTE: Use -1 to specify that if this param is picked to do nothing. Random is constant between actions within an event. So if you have a random Yell and a random Sound they will match up (ex: param2 with param2) -NOTE 2: PLEASE NOTE THAT EACH OF THE PARAM VALUES ARE ACTUAL PHASE NUMBERS NOT THE INVERSE PHASE MASK VALUE. -This is commonly used for Spellcasting NPC's who on Aggro may select at random a school of spells to use for the fight. Use this if you have up to 3 phases used, otherwise use Action 31 for more then 3 phases. - ---------------------------------- -31 = ACTION_T_RANDOM_PHASE_RANGE: ---------------------------------- -Parameter 1: PhaseMin - The minimum of the phase range. -Parameter 2: PhaseMax - The maximum of the phase range. The number here must be greater than PhaseMin. - -Randomly sets the phase between a range of phases controlled by the parameters. Sets the phase to a random id (Phase = PhaseMin + rnd % PhaseMin-PhaseMax). -NOTE: PhaseMax must be greater than PhaseMin. -NOTE 2: PLEASE NOTE THAT EACH OF THE PARAM VALUES ARE ACTUAL PHASE NUMBERS NOT THE INVERSE PHASE MASK VALUE. -This is commonly used for Spellcasting NPC's who on Aggro may select at random a school of spells to use for the fight. Use this if you have MORE then 3 phases used, otherwise use Action 30. - ---------------------- -32 = ACTION_T_SUMMON: ---------------------- -Parameter 1: CreatureID - The creature template ID to be summoned. The value here needs to be a valid creature template ID. -Parameter 2: Target - The target type defining who the summoned creature will attack. The value in this field needs to be a valid target type as specified in the reference tables below. NOTE: Using target type 0 will cause the summoned creature to not attack anyone. -Parameter 3: SummonID - The summon ID from the creature_ai_summons table controlling the position (and spawntime) where the summoned mob should be spawned at. - -Summons creature (param1) to attack target (param2) at location specified by creature_ai_summons (param3). -NOTE: Param3 Value is the ID Value used for the entry used in creature_ai_summons for this action. You MUST have an creature_ai_summons entry to use this action. -This is commonly used for NPC's who need to Summon a creature at a specific location. (Normally used for complex events) - ------------------------------ -33 = ACTION_T_KILLED_MONSTER: ------------------------------ -Parameter 1: CreatureID - The creature template ID. The value here must be a valid creature template ID. -Parameter 2: Target - The target type defining whom the quest kill count should be given to. The value in this field needs to be a valid target type as specified in the reference tables below. - -When activated, this action will call KilledMonster() function for the player. It can be used to give creature credit for killing a creature. In general if the quest is set to be accompished on different creatures (e.g. "Credit" templates). -NOTE: It can be ANY creature including certain quest specific triggers -This is commonly used for giving the player Quest Credits for NPC kills (Many NPC's may use the same CreatureID for the Kill Credit) - ----------------------------- -34 = ACTION_T_SET_INST_DATA: ----------------------------- -Parameter 1: Field - The field to change in the instance script. Again, this field needs to be a valid field that has been already defined in the instance's script. -Parameter 2: Data - The value to put at that field index. - -Sets data for the instance. Note that this will only work when the creature is inside an instantiable zone that has a valid script (ScriptedInstance) assigned. -This is commonly used to link an EventAI script with a existing Script Library C++ Script. You make make things happen like opening doors on specific events that happen. - ------------------------------- -35 = ACTION_T_SET_INST_DATA64: ------------------------------- -Parameter 1: Field - The field to change in the instance script. Again, this field needs to be a valid field that has been already defined in the instance's script. -Parameter 2: Target - The target type to use to get the GUID that will be stored at the field index. The value in this field needs to be a valid target type as specified in the reference tables below. - -Sets GUID (64 bits) data for the instance based on the target. Note that this will only work when the creature is inside an instantiable zone that has a valid script (ScriptedInstance) assigned. -Calls ScriptedInstance::SetData64 with field (param1) and data (param2) target's GUID. - ------------------------------- -36 = ACTION_T_UPDATE_TEMPLATE: ------------------------------- -Parameter 1: TemplateId - The creature template ID. The value here must be a valid creature template ID. -Parameter 2: Team - Use model_id from team : Alliance(0) or Horde (1). - -This function temporarily changes creature entry to new entry, display is changed, loot is changed, but AI is not changed. At respawn creature will be reverted to original entry. -Changes the creature to a new creature template of (param1) with team = Alliance if (param2) = false or Horde if (param2) = true - ------------------- -37 = ACTION_T_DIE: ------------------- -Kills the creature -This is commonly used if you need to Instakill the creature for one reason or another. - --------------------------------- -38 = ACTION_T_ZONE_COMBAT_PULSE: --------------------------------- -Places all players within the instance into combat with the creature. Only works in combat and only works inside of instances. - ----------------------------- -39 = ACTION_T_CALL_FOR_HELP: ----------------------------- -Parameter 1: Radius - All friendly (not only same faction) creatures will go to help - -Call any friendly creatures (if its not in combat/etc) in radius attack creature target. -Mostly used when call to help more wide that normal aggro radius or auto-used call for assistance, and need apply at some event. - -------------------------- -40 ACTION_T_SET_SHEATH: -------------------------- -Parameter 1: Sheath state -0 SHEATH_STATE_UNARMED not prepared weapon show (not used mostly by creatures) -1 SHEATH_STATE_MELEE melee weapon prepared show -2 SHEATH_STATE_RANGED ranged weapon prepared show - -Let set sheath state for creature. -Note: SHEATH_STATE_RANGED case work in combat state only if combat not start as melee commands. -This possible setup by set ar event AI start (single used EVENT_T_TIMER_OOC set ACTION_T_COMBAT_MOVEMENT 0 for creature that prefered ranged attack) - -------------------------- -41 ACTION_T_FORCE_DESPAWN -------------------------- -Despawns the creature (in or out of combat) -No parameters - -------------------------- -42 ACTION_T_SET_INVINCIBILITY_HP_LEVEL -------------------------- -Parameter 1: min. health level for creature that can be set at damage, 0 used as absent min. health value for apply damage. -Parameter 2: format of paramater 1 value -0 paramater 1 used as flat value -1 paramater 1 used as percent (0..100) from creature max health - -========================================= -Target Types -========================================= -Below is the list of current Target types that EventAI can handle. -Target types are used by certain actions and may effect actions differently - -(# Internal Name Discription) -0 TARGET_T_SELF Self cast -1 TARGET_T_HOSTILE Our current target (ie: highest aggro) -2 TARGET_T_HOSTILE_SECOND_AGGRO Second highest aggro (generaly used for cleaves and some special attacks) -3 TARGET_T_HOSTILE_LAST_AGGRO Dead last on aggro (no idea what this could be used for) -4 TARGET_T_HOSTILE_RANDOM Just any random target on our threat list -5 TARGET_T_HOSTILE_RANDOM_NOT_TOP Any random target except top threat -6 TARGET_T_ACTION_INVOKER Unit who caused this Event to occur (only works for EVENT_T_AGGRO, EVENT_T_KILL, EVENT_T_DEATH, EVENT_T_SPELLHIT, EVENT_T_OOC_LOS, EVENT_T_FRIENDLY_HP) - -========================================= -Cast Flags -========================================= -Below is the list of current Cast Flags that EventAI's spell casting can handle. -Cast flags are handled bitwise. Bit 0 is Interrupt Previous, bit 1 is triggered, etc. -So for example the number "3" (11 in Binary, selecting first 2 options) would mean that this cast has both CAST_INTURRUPT_PREVIOUS and CAST_TRIGGERED. -Another example: the number "5" (101 in Binary, selecting first and third options) would mean that this cast has CAST_INTURRUPT_PREVIOUS and CAST_FORCE_CAST. - -(bit# Decimal Internal Name Discription) -0 1 CAST_INTURRUPT_PREVIOUS Interrupts any previous spell casting (basicaly makes sure that this spell goes off) -1 2 CAST_TRIGGERED Forces the spell to be instant cast and require no mana/reagents. -2 4 CAST_FORCE_CAST Forces spell to cast even if the target is possibly out of range or the creature is possibly out of mana -3 8 CAST_NO_MELEE_IF_OOM Prevents creature from entering melee if out of mana or out of range -4 16 CAST_FORCE_TARGET_SELF Forces the target to cast this spell on itself -5 32 CAST_AURA_NOT_PRESENT Only casts the spell on the target if the target does not have the aura from that spell on itself already. - -NOTE: You can add the numbers in the decimal column to combine flags. - For example if you wanted to use CAST_NO_MELEE_IF_OOM(8) and CAST_TRIGGERED(2) you would simply use 10 in the cast flags field (8 + 2 = 10). - -========================================= -Event Flags -========================================= -Below is the list of current Event Flags that EventAI can handle. Event flags are handled bitwise. - -(bit# Decimal Internal Name Discription) -0 1 EFLAG_REPEATABLE Event repeats (Does not repeat if this flag is not set) -1 2 EFLAG_NORMAL Event occurs in Normal instance difficulty (will not occur in Normal if not set) -2 4 EFLAG_HEROIC Event occurs in Heroic instance difficulty (will not occur in Heroic if not set) -3 8 -4 16 -5 32 -6 64 -7 128 EFLAG_DEBUG_ONLY Prevents events from occuring on Release builds. Useful for testing new features. - -NOTE: You can add the numbers in the decimal column to combine flags. - - -========================================= -Basic Structure of creature_ai_texts -========================================= -Below is a the list of current fields within the texts tables. - -Field_Name Description ------------------------------------------------------------ -entry This value is mearly an NEGATIVE identifier of the current text number. Required for sql queries. Valid range are -1 to -999999 -content_default This is the actual text presented in the default language (English). - -content_loc1 This is the actual text presented in the Localization #1 Clients (Korean) -content_loc2 This is the actual text presented in the Localization #2 Clients (French) -content_loc3 This is the actual text presented in the Localization #3 Clients (German) -content_loc4 This is the actual text presented in the Localization #4 Clients (Chinese) -content_loc5 This is the actual text presented in the Localization #5 Clients (Taiwanese) -content_loc6 This is the actual text presented in the Localization #6 Clients (Spanish) -content_loc7 This is the actual text presented in the Localization #7 Clients (Spanish Mexico) -content_loc8 This is the actual text presented in the Localization #8 Clients (Russian) - -sound This value is the Sound ID that corresponds to the actual text used. -type Variables used to define type of text (Say/Yell/Textemote/Whisper). -language This value is the Language that the text is native in. -emote Value from enum Emote. Only source of text will play this emote (not target, if target are defined in DoScriptText) -comment This is a comment regarding the text entry - -Note: Fields `content_loc1` to `content_loc8` are NULL values by default and are normally handled by seperate localization projects. - -========================================= -Text Types (type) -========================================= -Below is the list of current Text types that texts tables can handle. These were previously seperate Actions in ACID. - -# Internal Name Description ------------------------------------------------------------ -0 CHAT_TYPE_SAY This type sets the text to be displayed as a Say (Speech Bubble). -1 CHAT_TYPE_YELL This type sets the text to be displayed as a Yell (Red Speech Bubble) and usually has a matching Sound ID. -2 CHAT_TYPE_TEXT_EMOTE This type sets the text to be displayed as a text emote in orange in the chat log. -3 CHAT_TYPE_BOSS_EMOTE This type sets the text to be displayed as a text emote in orange in the chat log (Used only for specific Bosses). -4 CHAT_TYPE_WHISPER This type sets the text to be displayed as a whisper to the player in the chat log. -5 CHAT_TYPE_BOSS_WHISPER This type sets the text to be displayed as a whisper to the player in the chat log (Used only for specific Bosses). -6 CHAT_TYPE_ZONE_YELL Same as CHAT_TYPE_YELL but will display to all players in current zone. - -========================================= -Language Types (language) -========================================= -Below is the list of current Language types that are allowed. -This is the Race Language that the text is native to (So it will display properly) - -# Internal Name Description ------------------------------------------------------------ -0 UNIVERSAL Text in this language is understood by ALL Races. -1 ORCISH Text in this language is understood ONLY by Horde Races. -2 DARNASSIAN Text in this language is understood ONLY by the Night Elf Race. -3 TAURAHE Text in this language is understood ONLY by the Tauren Race. -6 DWARVISH Text in this language is understood ONLY by the Dwarf Race. -7 COMMON Text in this language is understood ONLY by Alliance Races. -8 DEMONIC Text in this language is understood ONLY by the Demon Race (Not Implimented). -9 TITAN This language was used by Sargeras to speak with other Titians (Not Implemented). -10 THALASSIAN Text in this language is understood ONLY by the Blood Elf Race. -11 DRACONIC Text in this language is understood ONLY by the Dragon Race. -12 KALIMAG Text will display as Kalimag (not readable by players, language of all elementals) -13 GNOMISH Text in this language is understood ONLY by the Gnome Race. -14 TROLL Text in this language is understood ONLY by the Troll Race. -33 GUTTERSPEAK Text in this language is understood ONLY by the Undead Race. -35 DRAENEI Text in this language is understood ONLY by the Draenai Race. -36 ZOMBIE (not currently used?) -37 GNOMISH BINARY Binary language used by Alliance when drinking Binary Brew -38 GOBLIN BINARY Binary language used by Horce when drinking Binary Brew diff --git a/docs/HowToScript.txt b/docs/HowToScript.txt deleted file mode 100644 index 73968a08b19..00000000000 --- a/docs/HowToScript.txt +++ /dev/null @@ -1,27 +0,0 @@ - -** HOW TO SCRIPT IN C++ ** - -1 - create a file myscript.cpp in scripts folder. -2 - copy the content of script_default.cpp, it as the structure on how the scripting fuctions are organized. - dont forget to change the name of fuctions, like GossipHello_default to GossipHello_myscript. - -3 - in fuction AddSC_default change to AddSC_myscript. -4 - newscript->Name="default"; change the string to "myscript" this name is the one to be called from the db -5 - dont forget to change the name in here to newscript->pGossipHello = &GossipHello_default; this is where the scripted fuctions are stored. -6 - and last thing is in ScriptMgr.cpp - -add your AddSC_myscript in here - -// -- Scripts to be added -- -extern void AddSC_default(); -// ------------------- - -and here - -// -- Inicialize the Scripts to be Added -- - AddSC_default(); -// ---------------------------------------- - -now start using the player fuctions to script ;) - -hope it helps, any question use our forum. \ No newline at end of file diff --git a/docs/TextTables.txt b/docs/TextTables.txt deleted file mode 100644 index eac63384785..00000000000 --- a/docs/TextTables.txt +++ /dev/null @@ -1,87 +0,0 @@ -========================================= -Texts Documentation -========================================= - -Scriptdev2 Revision 695 introduces a new format for using texts in EventAI and SD2 Scripts. -This information relates to the *_texts tables located in the ScriptDev Database. - -Any script can at any time access and use text from any of the three text tables, as long as the entry does in fact exist. -Custom scripters are adviced to store their text data in custom_texts. - -The different tables has ranges of entries allowed for that table. -Reserved EventAI in Mangos entry -1 -> -999999 -script_texts: entry -1000000 -> -1999999 -custom_texts: entry -2000000 -> -2999999 -Any entry out of range for that table will display a startup error. - - -========================================= -Basic Structure of script_texts and custom_texts -========================================= -Below is a the list of current fields within the texts tables. - -Field_Name Description ------------------------------------------------------------ -entry This value is mearly an NEGATIVE identifier of the current text number. Required for sql queries. -content_default This is the actual text presented in the default language (English). - -content_loc1 This is the actual text presented in the Localization #1 Clients (Korean) -content_loc2 This is the actual text presented in the Localization #2 Clients (French) -content_loc3 This is the actual text presented in the Localization #3 Clients (German) -content_loc4 This is the actual text presented in the Localization #4 Clients (Chinese) -content_loc5 This is the actual text presented in the Localization #5 Clients (Taiwanese) -content_loc6 This is the actual text presented in the Localization #6 Clients (Spanish) -content_loc7 This is the actual text presented in the Localization #7 Clients (Spanish Mexico) -content_loc8 This is the actual text presented in the Localization #8 Clients (Russian) - -sound This value is the Sound ID that corresponds to the actual text used (Defined in SoundEntries.dbc). -type Variables used to define type of text (Say/Yell/Textemote/Whisper). -language This value is the Language that the text is native in (Defined in Languages.dbc). -emote Value from enum Emote (defined in Emotes.dbc). Only source of text will play this emote (not target, if target are defined in DoScriptText) -comment This is a comment regarding the text entry (For ACID, accepted format is to use Creature ID of NPC using it). - -Note: Fields `content_loc1` to `content_loc8` are NULL values by default and are handled by seperate localization projects. - - -========================================= -Text Types (type) -========================================= -Below is the list of current Text types that texts tables can handle. These were previously seperate Actions in ACID. - -# Internal Name Description ------------------------------------------------------------ -0 CHAT_TYPE_SAY This type sets the text to be displayed as a Say (Speech Bubble). -1 CHAT_TYPE_YELL This type sets the text to be displayed as a Yell (Red Speech Bubble) and usually has a matching Sound ID. -2 CHAT_TYPE_TEXT_EMOTE This type sets the text to be displayed as a text emote in orange in the chat log. -3 CHAT_TYPE_BOSS_EMOTE This type sets the text to be displayed as a text emote in orange in the chat log (Used only for specific Bosses). -4 CHAT_TYPE_WHISPER This type sets the text to be displayed as a whisper to the player in the chat log. -5 CHAT_TYPE_BOSS_WHISPER This type sets the text to be displayed as a whisper to the player in the chat log (Used only for specific Bosses). -6 CHAT_TYPE_ZONE_YELL Same as CHAT_TYPE_YELL but will display to all players in current zone. - - -========================================= -Language Types (language) -========================================= -Below is the list of current Language types that are allowed. -This is the Race Language that the text is native to (So it will display properly) - -# Internal Name Description ------------------------------------------------------------ -0 UNIVERSAL Text in this language is understood by ALL Races. -1 ORCISH Text in this language is understood ONLY by Horde Races. -2 DARNASSIAN Text in this language is understood ONLY by the Night Elf Race. -3 TAURAHE Text in this language is understood ONLY by the Tauren Race. -6 DWARVISH Text in this language is understood ONLY by the Dwarf Race. -7 COMMON Text in this language is understood ONLY by Alliance Races. -8 DEMONIC Text in this language is understood ONLY by the Demon Race (Not Implimented). -9 TITAN This language was used by Sargeras to speak with other Titians (Not Implemented). -10 THALASSIAN Text in this language is understood ONLY by the Blood Elf Race. -11 DRACONIC Text in this language is understood ONLY by the Dragon Race. -12 KALIMAG Text will display as Kalimag (not readable by players, language of all elementals) -13 GNOMISH Text in this language is understood ONLY by the Gnome Race. -14 TROLL Text in this language is understood ONLY by the Troll Race. -33 GUTTERSPEAK Text in this language is understood ONLY by the Undead Race. -35 DRAENEI Text in this language is understood ONLY by the Draenai Race. -36 ZOMBIE (not currently used?) -37 GNOMISH BINARY Binary language used by Alliance when drinking Binary Brew -38 GOBLIN BINARY Binary language used by Horce when drinking Binary Brew \ No newline at end of file diff --git a/docs/UnixInstall.txt b/docs/UnixInstall.txt deleted file mode 100644 index 45431f679e4..00000000000 --- a/docs/UnixInstall.txt +++ /dev/null @@ -1,60 +0,0 @@ -= TrinityCore -- Linux installation = -Copyright (C) 2008-2010 TrinityCore (http://www.trinitycore.org) - -CHECK http://www.trinitycore.info/w/Linux_Build_HOWTO FOR FURTHER HELP - -Installing TrinityCore is fairly simple on a Linux machine, assuming you -have all required applications - -The most important ones are: - - g++ - gcc - make - cmake version 2.6.x or greater - libmysql++-dev - subversion (for checking out Trinity Database) - mercurial (for checking out the core) - openssl - libssl-dev - zlib1g-dev - libtool - libmysqlclient15-dev - patch - build-essential - mysql-client - -Most of these are included on common Linux distros, others you may have -to install by your self. Please check your distro's repos. - -Make a directory to build in, you can call it anything you want like -build or bin etc, then go into the directory and cmake and make. E.G. -you created a dir named build ad want to have your finalcompiled product -installed in /home/trinity/server, an example sequence of commands can -be : - - cmake ../ -DPREFIX=/home/trinity/server - make - make install - -Thats just about all thats needed. You can however tweak more settings -than where to install using flags built into our cmake files. Just open -up CMakeLists.txt in the main folder and take a look at some of the -flags like - - SCRIPTS --enable or disable trinity script (enabled or disabled by a 1 or 0, enabled by default) - DEBUG --enable debugging (enabled or disabled by a 1 or 0) - CLI --enable command line support (enabled or disabled by a 1 or 0, enabled by default) - PREFIX --prefix directory for install (see example for use) - CONF_DIR --location for your trinity config files - CMAKE_C_FLAGS --advanced users only - CMAKE_CXX_FLAGS --advanced users only - - -Of course, replace the paths in prefix, conf_dir with the directories -you wish to install TrinityCore to. The datadir is where maps, DBCs, and -SQLs are stored. The sysconfdir is where configuration files are stored. - -Once TrinityCore is installed you will need to apply database updates -where necessary. Furthermore, you must configure your installation by -editing the config files in the sysconfdir. diff --git a/docs/gpl-2.0.txt b/docs/gpl-2.0.txt deleted file mode 100644 index d159169d105..00000000000 --- a/docs/gpl-2.0.txt +++ /dev/null @@ -1,339 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. diff --git a/externals/CMakeLists.txt b/externals/CMakeLists.txt deleted file mode 100644 index 12b5e44de51..00000000000 --- a/externals/CMakeLists.txt +++ /dev/null @@ -1,28 +0,0 @@ -# Copyright (C) 2008-2010 Trinity -# -# This file is free software; as a special exception the author gives -# unlimited permission to copy and/or distribute it, with or without -# modifications, as long as this notice is preserved. -# -# This program is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the -# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -if(CMAKE_SYSTEM_NAME MATCHES "Linux") - add_subdirectory(jemalloc) - set(JEMALLOC_LIB "jemalloc") -endif() - -if(CMAKE_SYSTEM_NAME MATCHES "Windows") - add_subdirectory(ace) - add_subdirectory(zlib) - add_subdirectory(bzip2) -endif() - -add_subdirectory(g3dlite) -add_subdirectory(sockets) -add_subdirectory(gsoap) - -if(TOOLS) - add_subdirectory(libmpq) -endif() diff --git a/externals/PackageList.txt b/externals/PackageList.txt deleted file mode 100644 index bf14636223d..00000000000 --- a/externals/PackageList.txt +++ /dev/null @@ -1,45 +0,0 @@ -TrinityCore uses (parts of or in whole) the following opensource software : - -ACE (ADAPTIVE Communication Environment) - http://www.cs.wustl.edu/~schmidt/ACE.html - Version: 5.8.1 - -bzip2 (a freely available, patent free, high-quality data compressor) - http://www.bzip.org/ - Version: 1.0.5 - -G3D (a commercial-grade C++ 3D engine available as Open Source (BSD License) - http://g3d.sourceforge.net/ - Version: 6.09 - -jemalloc (a general-purpose scalable concurrent malloc-implementation) - http://www.canonware.com/jemalloc/ - Version: 1.0.0 - -libMPQ (a library for reading MPQ files) - https://libmpq.org/ - Version: 1.0.4 - -MersenneTwister (a very fast random number generator) - http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html - Version: 0.4.2 - -SFMT (SIMD-oriented Fast Mersenne Twister) - http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/index.html - Version: 1.3.3 - -sockets (a GPL licensed C++ class library wrapping the berkeley sockets C API) - http://www.alhem.net/Sockets/ - Version: UNKNOWN - -utf8-cpp (UTF-8 with C++ in a Portable Way) - http://utfcpp.sourceforge.net/ - Version: 2.3 - -vld (a free open-source memory leak detection system for Visual C++) - http://sites.google.com/site/dmoulding/vld - Version: 1.0 - -zlib (A Massively Spiffy Yet Delicately Unobtrusive Compression Library) - http://www.zlib.net/ - Version: 1.2.5 diff --git a/externals/SFMT/SFMT-alti.h b/externals/SFMT/SFMT-alti.h deleted file mode 100644 index df3186cbbd7..00000000000 --- a/externals/SFMT/SFMT-alti.h +++ /dev/null @@ -1,156 +0,0 @@ -/** - * @file SFMT-alti.h - * - * @brief SIMD oriented Fast Mersenne Twister(SFMT) - * pseudorandom number generator - * - * @author Mutsuo Saito (Hiroshima University) - * @author Makoto Matsumoto (Hiroshima University) - * - * Copyright (C) 2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima - * University. All rights reserved. - * - * The new BSD License is applied to this software. - * see LICENSE.txt - */ - -#ifndef SFMT_ALTI_H -#define SFMT_ALTI_H - -inline static vector unsigned int vec_recursion(vector unsigned int a, - vector unsigned int b, - vector unsigned int c, - vector unsigned int d) - ALWAYSINLINE; - -/** - * This function represents the recursion formula in AltiVec and BIG ENDIAN. - * @param a a 128-bit part of the interal state array - * @param b a 128-bit part of the interal state array - * @param c a 128-bit part of the interal state array - * @param d a 128-bit part of the interal state array - * @return output - */ -inline static vector unsigned int vec_recursion(vector unsigned int a, - vector unsigned int b, - vector unsigned int c, - vector unsigned int d) { - - const vector unsigned int sl1 = ALTI_SL1; - const vector unsigned int sr1 = ALTI_SR1; -#ifdef ONLY64 - const vector unsigned int mask = ALTI_MSK64; - const vector unsigned char perm_sl = ALTI_SL2_PERM64; - const vector unsigned char perm_sr = ALTI_SR2_PERM64; -#else - const vector unsigned int mask = ALTI_MSK; - const vector unsigned char perm_sl = ALTI_SL2_PERM; - const vector unsigned char perm_sr = ALTI_SR2_PERM; -#endif - vector unsigned int v, w, x, y, z; - x = vec_perm(a, (vector unsigned int)perm_sl, perm_sl); - v = a; - y = vec_sr(b, sr1); - z = vec_perm(c, (vector unsigned int)perm_sr, perm_sr); - w = vec_sl(d, sl1); - z = vec_xor(z, w); - y = vec_and(y, mask); - v = vec_xor(v, x); - z = vec_xor(z, y); - z = vec_xor(z, v); - return z; -} - -/** - * This function fills the internal state array with pseudorandom - * integers. - */ -inline static void gen_rand_all(void) { - int i; - vector unsigned int r, r1, r2; - - r1 = sfmt[N - 2].s; - r2 = sfmt[N - 1].s; - for (i = 0; i < N - POS1; i++) { - r = vec_recursion(sfmt[i].s, sfmt[i + POS1].s, r1, r2); - sfmt[i].s = r; - r1 = r2; - r2 = r; - } - for (; i < N; i++) { - r = vec_recursion(sfmt[i].s, sfmt[i + POS1 - N].s, r1, r2); - sfmt[i].s = r; - r1 = r2; - r2 = r; - } -} - -/** - * This function fills the user-specified array with pseudorandom - * integers. - * - * @param array an 128-bit array to be filled by pseudorandom numbers. - * @param size number of 128-bit pesudorandom numbers to be generated. - */ -inline static void gen_rand_array(w128_t *array, int size) { - int i, j; - vector unsigned int r, r1, r2; - - r1 = sfmt[N - 2].s; - r2 = sfmt[N - 1].s; - for (i = 0; i < N - POS1; i++) { - r = vec_recursion(sfmt[i].s, sfmt[i + POS1].s, r1, r2); - array[i].s = r; - r1 = r2; - r2 = r; - } - for (; i < N; i++) { - r = vec_recursion(sfmt[i].s, array[i + POS1 - N].s, r1, r2); - array[i].s = r; - r1 = r2; - r2 = r; - } - /* main loop */ - for (; i < size - N; i++) { - r = vec_recursion(array[i - N].s, array[i + POS1 - N].s, r1, r2); - array[i].s = r; - r1 = r2; - r2 = r; - } - for (j = 0; j < 2 * N - size; j++) { - sfmt[j].s = array[j + size - N].s; - } - for (; i < size; i++) { - r = vec_recursion(array[i - N].s, array[i + POS1 - N].s, r1, r2); - array[i].s = r; - sfmt[j++].s = r; - r1 = r2; - r2 = r; - } -} - -#ifndef ONLY64 -#if defined(__APPLE__) -#define ALTI_SWAP (vector unsigned char) \ - (4, 5, 6, 7, 0, 1, 2, 3, 12, 13, 14, 15, 8, 9, 10, 11) -#else -#define ALTI_SWAP {4, 5, 6, 7, 0, 1, 2, 3, 12, 13, 14, 15, 8, 9, 10, 11} -#endif -/** - * This function swaps high and low 32-bit of 64-bit integers in user - * specified array. - * - * @param array an 128-bit array to be swaped. - * @param size size of 128-bit array. - */ -inline static void swap(w128_t *array, int size) { - int i; - const vector unsigned char perm = ALTI_SWAP; - - for (i = 0; i < size; i++) { - array[i].s = vec_perm(array[i].s, (vector unsigned int)perm, perm); - } -} -#endif - -#endif diff --git a/externals/SFMT/SFMT-params.h b/externals/SFMT/SFMT-params.h deleted file mode 100644 index 661bbf26a28..00000000000 --- a/externals/SFMT/SFMT-params.h +++ /dev/null @@ -1,97 +0,0 @@ -#ifndef SFMT_PARAMS_H -#define SFMT_PARAMS_H - -#if !defined(MEXP) -#ifdef __GNUC__ - #warning "MEXP is not defined. I assume MEXP is 19937." -#endif - #define MEXP 19937 -#endif -/*----------------- - BASIC DEFINITIONS - -----------------*/ -/** Mersenne Exponent. The period of the sequence - * is a multiple of 2^MEXP-1. - * #define MEXP 19937 */ -/** SFMT generator has an internal state array of 128-bit integers, - * and N is its size. */ -#define N (MEXP / 128 + 1) -/** N32 is the size of internal state array when regarded as an array - * of 32-bit integers.*/ -#define N32 (N * 4) -/** N64 is the size of internal state array when regarded as an array - * of 64-bit integers.*/ -#define N64 (N * 2) - -/*---------------------- - the parameters of SFMT - following definitions are in paramsXXXX.h file. - ----------------------*/ -/** the pick up position of the array. -#define POS1 122 -*/ - -/** the parameter of shift left as four 32-bit registers. -#define SL1 18 - */ - -/** the parameter of shift left as one 128-bit register. - * The 128-bit integer is shifted by (SL2 * 8) bits. -#define SL2 1 -*/ - -/** the parameter of shift right as four 32-bit registers. -#define SR1 11 -*/ - -/** the parameter of shift right as one 128-bit register. - * The 128-bit integer is shifted by (SL2 * 8) bits. -#define SR2 1 -*/ - -/** A bitmask, used in the recursion. These parameters are introduced - * to break symmetry of SIMD. -#define MSK1 0xdfffffefU -#define MSK2 0xddfecb7fU -#define MSK3 0xbffaffffU -#define MSK4 0xbffffff6U -*/ - -/** These definitions are part of a 128-bit period certification vector. -#define PARITY1 0x00000001U -#define PARITY2 0x00000000U -#define PARITY3 0x00000000U -#define PARITY4 0xc98e126aU -*/ - -#if MEXP == 607 - #include "SFMT-params607.h" -#elif MEXP == 1279 - #include "SFMT-params1279.h" -#elif MEXP == 2281 - #include "SFMT-params2281.h" -#elif MEXP == 4253 - #include "SFMT-params4253.h" -#elif MEXP == 11213 - #include "SFMT-params11213.h" -#elif MEXP == 19937 - #include "SFMT-params19937.h" -#elif MEXP == 44497 - #include "SFMT-params44497.h" -#elif MEXP == 86243 - #include "SFMT-params86243.h" -#elif MEXP == 132049 - #include "SFMT-params132049.h" -#elif MEXP == 216091 - #include "SFMT-params216091.h" -#else -#ifdef __GNUC__ - #error "MEXP is not valid." - #undef MEXP -#else - #undef MEXP -#endif - -#endif - -#endif /* SFMT_PARAMS_H */ diff --git a/externals/SFMT/SFMT-sse2.h b/externals/SFMT/SFMT-sse2.h deleted file mode 100644 index 4e91d9c6121..00000000000 --- a/externals/SFMT/SFMT-sse2.h +++ /dev/null @@ -1,121 +0,0 @@ -/** - * @file SFMT-sse2.h - * @brief SIMD oriented Fast Mersenne Twister(SFMT) for Intel SSE2 - * - * @author Mutsuo Saito (Hiroshima University) - * @author Makoto Matsumoto (Hiroshima University) - * - * @note We assume LITTLE ENDIAN in this file - * - * Copyright (C) 2006, 2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima - * University. All rights reserved. - * - * The new BSD License is applied to this software, see LICENSE.txt - */ - -#ifndef SFMT_SSE2_H -#define SFMT_SSE2_H - -PRE_ALWAYS static __m128i mm_recursion(__m128i *a, __m128i *b, __m128i c, - __m128i d, __m128i mask) ALWAYSINLINE; - -/** - * This function represents the recursion formula. - * @param a a 128-bit part of the interal state array - * @param b a 128-bit part of the interal state array - * @param c a 128-bit part of the interal state array - * @param d a 128-bit part of the interal state array - * @param mask 128-bit mask - * @return output - */ -PRE_ALWAYS static __m128i mm_recursion(__m128i *a, __m128i *b, - __m128i c, __m128i d, __m128i mask) { - __m128i v, x, y, z; - - x = _mm_load_si128(a); - y = _mm_srli_epi32(*b, SR1); - z = _mm_srli_si128(c, SR2); - v = _mm_slli_epi32(d, SL1); - z = _mm_xor_si128(z, x); - z = _mm_xor_si128(z, v); - x = _mm_slli_si128(x, SL2); - y = _mm_and_si128(y, mask); - z = _mm_xor_si128(z, x); - z = _mm_xor_si128(z, y); - return z; -} - -/** - * This function fills the internal state array with pseudorandom - * integers. - */ -inline static void gen_rand_all(void) { - int i; - __m128i r, r1, r2, mask; - mask = _mm_set_epi32(MSK4, MSK3, MSK2, MSK1); - - r1 = _mm_load_si128(&sfmt[N - 2].si); - r2 = _mm_load_si128(&sfmt[N - 1].si); - for (i = 0; i < N - POS1; i++) { - r = mm_recursion(&sfmt[i].si, &sfmt[i + POS1].si, r1, r2, mask); - _mm_store_si128(&sfmt[i].si, r); - r1 = r2; - r2 = r; - } - for (; i < N; i++) { - r = mm_recursion(&sfmt[i].si, &sfmt[i + POS1 - N].si, r1, r2, mask); - _mm_store_si128(&sfmt[i].si, r); - r1 = r2; - r2 = r; - } -} - -/** - * This function fills the user-specified array with pseudorandom - * integers. - * - * @param array an 128-bit array to be filled by pseudorandom numbers. - * @param size number of 128-bit pesudorandom numbers to be generated. - */ -inline static void gen_rand_array(w128_t *array, int size) { - int i, j; - __m128i r, r1, r2, mask; - mask = _mm_set_epi32(MSK4, MSK3, MSK2, MSK1); - - r1 = _mm_load_si128(&sfmt[N - 2].si); - r2 = _mm_load_si128(&sfmt[N - 1].si); - for (i = 0; i < N - POS1; i++) { - r = mm_recursion(&sfmt[i].si, &sfmt[i + POS1].si, r1, r2, mask); - _mm_store_si128(&array[i].si, r); - r1 = r2; - r2 = r; - } - for (; i < N; i++) { - r = mm_recursion(&sfmt[i].si, &array[i + POS1 - N].si, r1, r2, mask); - _mm_store_si128(&array[i].si, r); - r1 = r2; - r2 = r; - } - /* main loop */ - for (; i < size - N; i++) { - r = mm_recursion(&array[i - N].si, &array[i + POS1 - N].si, r1, r2, - mask); - _mm_store_si128(&array[i].si, r); - r1 = r2; - r2 = r; - } - for (j = 0; j < 2 * N - size; j++) { - r = _mm_load_si128(&array[j + size - N].si); - _mm_store_si128(&sfmt[j].si, r); - } - for (; i < size; i++) { - r = mm_recursion(&array[i - N].si, &array[i + POS1 - N].si, r1, r2, - mask); - _mm_store_si128(&array[i].si, r); - _mm_store_si128(&sfmt[j++].si, r); - r1 = r2; - r2 = r; - } -} - -#endif diff --git a/externals/SFMT/SFMT.c b/externals/SFMT/SFMT.c deleted file mode 100644 index d36465d9e14..00000000000 --- a/externals/SFMT/SFMT.c +++ /dev/null @@ -1,620 +0,0 @@ -/** - * @file SFMT.c - * @brief SIMD oriented Fast Mersenne Twister(SFMT) - * - * @author Mutsuo Saito (Hiroshima University) - * @author Makoto Matsumoto (Hiroshima University) - * - * Copyright (C) 2006,2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima - * University. All rights reserved. - * - * The new BSD License is applied to this software, see LICENSE.txt - */ -#include -#include -#include "SFMT.h" -#include "SFMT-params.h" - -#if defined(__BIG_ENDIAN__) && !defined(__amd64) && !defined(BIG_ENDIAN64) -#define BIG_ENDIAN64 1 -#endif -#if defined(HAVE_ALTIVEC) && !defined(BIG_ENDIAN64) -#define BIG_ENDIAN64 1 -#endif -#if defined(ONLY64) && !defined(BIG_ENDIAN64) - #if defined(__GNUC__) - #error "-DONLY64 must be specified with -DBIG_ENDIAN64" - #endif -#undef ONLY64 -#endif -/*------------------------------------------------------ - 128-bit SIMD data type for Altivec, SSE2 or standard C - ------------------------------------------------------*/ -#if defined(HAVE_ALTIVEC) - #if !defined(__APPLE__) - #include - #endif -/** 128-bit data structure */ -union W128_T { - vector unsigned int s; - uint32_t u[4]; -}; -/** 128-bit data type */ -typedef union W128_T w128_t; - -#elif defined(HAVE_SSE2) - #include - -/** 128-bit data structure */ -union W128_T { - __m128i si; - uint32_t u[4]; -}; -/** 128-bit data type */ -typedef union W128_T w128_t; - -#else - -/** 128-bit data structure */ -struct W128_T { - uint32_t u[4]; -}; -/** 128-bit data type */ -typedef struct W128_T w128_t; - -#endif - -/*-------------------------------------- - FILE GLOBAL VARIABLES - internal state, index counter and flag - --------------------------------------*/ -/** the 128-bit internal state array */ -static w128_t sfmt[N]; -/** the 32bit integer pointer to the 128-bit internal state array */ -static uint32_t *psfmt32 = &sfmt[0].u[0]; -#if !defined(BIG_ENDIAN64) || defined(ONLY64) -/** the 64bit integer pointer to the 128-bit internal state array */ -static uint64_t *psfmt64 = (uint64_t *)&sfmt[0].u[0]; -#endif -/** index counter to the 32-bit internal state array */ -static int idx; -/** a flag: it is 0 if and only if the internal state is not yet - * initialized. */ -static int initialized = 0; -/** a parity check vector which certificate the period of 2^{MEXP} */ -static uint32_t parity[4] = {PARITY1, PARITY2, PARITY3, PARITY4}; - -/*---------------- - STATIC FUNCTIONS - ----------------*/ -inline static int idxof(int i); -inline static void rshift128(w128_t *out, w128_t const *in, int shift); -inline static void lshift128(w128_t *out, w128_t const *in, int shift); -inline static void gen_rand_all(void); -inline static void gen_rand_array(w128_t *array, int size); -inline static uint32_t func1(uint32_t x); -inline static uint32_t func2(uint32_t x); -static void period_certification(void); -#if defined(BIG_ENDIAN64) && !defined(ONLY64) -inline static void swap(w128_t *array, int size); -#endif - -#if defined(HAVE_ALTIVEC) - #include "SFMT-alti.h" -#elif defined(HAVE_SSE2) - #include "SFMT-sse2.h" -#endif - -/** - * This function simulate a 64-bit index of LITTLE ENDIAN - * in BIG ENDIAN machine. - */ -#ifdef ONLY64 -inline static int idxof(int i) { - return i ^ 1; -} -#else -inline static int idxof(int i) { - return i; -} -#endif -/** - * This function simulates SIMD 128-bit right shift by the standard C. - * The 128-bit integer given in in is shifted by (shift * 8) bits. - * This function simulates the LITTLE ENDIAN SIMD. - * @param out the output of this function - * @param in the 128-bit data to be shifted - * @param shift the shift value - */ -#ifdef ONLY64 -inline static void rshift128(w128_t *out, w128_t const *in, int shift) { - uint64_t th, tl, oh, ol; - - th = ((uint64_t)in->u[2] << 32) | ((uint64_t)in->u[3]); - tl = ((uint64_t)in->u[0] << 32) | ((uint64_t)in->u[1]); - - oh = th >> (shift * 8); - ol = tl >> (shift * 8); - ol |= th << (64 - shift * 8); - out->u[0] = (uint32_t)(ol >> 32); - out->u[1] = (uint32_t)ol; - out->u[2] = (uint32_t)(oh >> 32); - out->u[3] = (uint32_t)oh; -} -#else -inline static void rshift128(w128_t *out, w128_t const *in, int shift) { - uint64_t th, tl, oh, ol; - - th = ((uint64_t)in->u[3] << 32) | ((uint64_t)in->u[2]); - tl = ((uint64_t)in->u[1] << 32) | ((uint64_t)in->u[0]); - - oh = th >> (shift * 8); - ol = tl >> (shift * 8); - ol |= th << (64 - shift * 8); - out->u[1] = (uint32_t)(ol >> 32); - out->u[0] = (uint32_t)ol; - out->u[3] = (uint32_t)(oh >> 32); - out->u[2] = (uint32_t)oh; -} -#endif -/** - * This function simulates SIMD 128-bit left shift by the standard C. - * The 128-bit integer given in in is shifted by (shift * 8) bits. - * This function simulates the LITTLE ENDIAN SIMD. - * @param out the output of this function - * @param in the 128-bit data to be shifted - * @param shift the shift value - */ -#ifdef ONLY64 -inline static void lshift128(w128_t *out, w128_t const *in, int shift) { - uint64_t th, tl, oh, ol; - - th = ((uint64_t)in->u[2] << 32) | ((uint64_t)in->u[3]); - tl = ((uint64_t)in->u[0] << 32) | ((uint64_t)in->u[1]); - - oh = th << (shift * 8); - ol = tl << (shift * 8); - oh |= tl >> (64 - shift * 8); - out->u[0] = (uint32_t)(ol >> 32); - out->u[1] = (uint32_t)ol; - out->u[2] = (uint32_t)(oh >> 32); - out->u[3] = (uint32_t)oh; -} -#else -inline static void lshift128(w128_t *out, w128_t const *in, int shift) { - uint64_t th, tl, oh, ol; - - th = ((uint64_t)in->u[3] << 32) | ((uint64_t)in->u[2]); - tl = ((uint64_t)in->u[1] << 32) | ((uint64_t)in->u[0]); - - oh = th << (shift * 8); - ol = tl << (shift * 8); - oh |= tl >> (64 - shift * 8); - out->u[1] = (uint32_t)(ol >> 32); - out->u[0] = (uint32_t)ol; - out->u[3] = (uint32_t)(oh >> 32); - out->u[2] = (uint32_t)oh; -} -#endif - -/** - * This function represents the recursion formula. - * @param r output - * @param a a 128-bit part of the internal state array - * @param b a 128-bit part of the internal state array - * @param c a 128-bit part of the internal state array - * @param d a 128-bit part of the internal state array - */ -#if (!defined(HAVE_ALTIVEC)) && (!defined(HAVE_SSE2)) -#ifdef ONLY64 -inline static void do_recursion(w128_t *r, w128_t *a, w128_t *b, w128_t *c, - w128_t *d) { - w128_t x; - w128_t y; - - lshift128(&x, a, SL2); - rshift128(&y, c, SR2); - r->u[0] = a->u[0] ^ x.u[0] ^ ((b->u[0] >> SR1) & MSK2) ^ y.u[0] - ^ (d->u[0] << SL1); - r->u[1] = a->u[1] ^ x.u[1] ^ ((b->u[1] >> SR1) & MSK1) ^ y.u[1] - ^ (d->u[1] << SL1); - r->u[2] = a->u[2] ^ x.u[2] ^ ((b->u[2] >> SR1) & MSK4) ^ y.u[2] - ^ (d->u[2] << SL1); - r->u[3] = a->u[3] ^ x.u[3] ^ ((b->u[3] >> SR1) & MSK3) ^ y.u[3] - ^ (d->u[3] << SL1); -} -#else -inline static void do_recursion(w128_t *r, w128_t *a, w128_t *b, w128_t *c, - w128_t *d) { - w128_t x; - w128_t y; - - lshift128(&x, a, SL2); - rshift128(&y, c, SR2); - r->u[0] = a->u[0] ^ x.u[0] ^ ((b->u[0] >> SR1) & MSK1) ^ y.u[0] - ^ (d->u[0] << SL1); - r->u[1] = a->u[1] ^ x.u[1] ^ ((b->u[1] >> SR1) & MSK2) ^ y.u[1] - ^ (d->u[1] << SL1); - r->u[2] = a->u[2] ^ x.u[2] ^ ((b->u[2] >> SR1) & MSK3) ^ y.u[2] - ^ (d->u[2] << SL1); - r->u[3] = a->u[3] ^ x.u[3] ^ ((b->u[3] >> SR1) & MSK4) ^ y.u[3] - ^ (d->u[3] << SL1); -} -#endif -#endif - -#if (!defined(HAVE_ALTIVEC)) && (!defined(HAVE_SSE2)) -/** - * This function fills the internal state array with pseudorandom - * integers. - */ -inline static void gen_rand_all(void) { - int i; - w128_t *r1, *r2; - - r1 = &sfmt[N - 2]; - r2 = &sfmt[N - 1]; - for (i = 0; i < N - POS1; i++) { - do_recursion(&sfmt[i], &sfmt[i], &sfmt[i + POS1], r1, r2); - r1 = r2; - r2 = &sfmt[i]; - } - for (; i < N; i++) { - do_recursion(&sfmt[i], &sfmt[i], &sfmt[i + POS1 - N], r1, r2); - r1 = r2; - r2 = &sfmt[i]; - } -} - -/** - * This function fills the user-specified array with pseudorandom - * integers. - * - * @param array an 128-bit array to be filled by pseudorandom numbers. - * @param size number of 128-bit pseudorandom numbers to be generated. - */ -inline static void gen_rand_array(w128_t *array, int size) { - int i, j; - w128_t *r1, *r2; - - r1 = &sfmt[N - 2]; - r2 = &sfmt[N - 1]; - for (i = 0; i < N - POS1; i++) { - do_recursion(&array[i], &sfmt[i], &sfmt[i + POS1], r1, r2); - r1 = r2; - r2 = &array[i]; - } - for (; i < N; i++) { - do_recursion(&array[i], &sfmt[i], &array[i + POS1 - N], r1, r2); - r1 = r2; - r2 = &array[i]; - } - for (; i < size - N; i++) { - do_recursion(&array[i], &array[i - N], &array[i + POS1 - N], r1, r2); - r1 = r2; - r2 = &array[i]; - } - for (j = 0; j < 2 * N - size; j++) { - sfmt[j] = array[j + size - N]; - } - for (; i < size; i++, j++) { - do_recursion(&array[i], &array[i - N], &array[i + POS1 - N], r1, r2); - r1 = r2; - r2 = &array[i]; - sfmt[j] = array[i]; - } -} -#endif - -#if defined(BIG_ENDIAN64) && !defined(ONLY64) && !defined(HAVE_ALTIVEC) -inline static void swap(w128_t *array, int size) { - int i; - uint32_t x, y; - - for (i = 0; i < size; i++) { - x = array[i].u[0]; - y = array[i].u[2]; - array[i].u[0] = array[i].u[1]; - array[i].u[2] = array[i].u[3]; - array[i].u[1] = x; - array[i].u[3] = y; - } -} -#endif -/** - * This function represents a function used in the initialization - * by init_by_array - * @param x 32-bit integer - * @return 32-bit integer - */ -static uint32_t func1(uint32_t x) { - return (x ^ (x >> 27)) * (uint32_t)1664525UL; -} - -/** - * This function represents a function used in the initialization - * by init_by_array - * @param x 32-bit integer - * @return 32-bit integer - */ -static uint32_t func2(uint32_t x) { - return (x ^ (x >> 27)) * (uint32_t)1566083941UL; -} - -/** - * This function certificate the period of 2^{MEXP} - */ -static void period_certification(void) { - int inner = 0; - int i, j; - uint32_t work; - - for (i = 0; i < 4; i++) - inner ^= psfmt32[idxof(i)] & parity[i]; - for (i = 16; i > 0; i >>= 1) - inner ^= inner >> i; - inner &= 1; - /* check OK */ - if (inner == 1) { - return; - } - /* check NG, and modification */ - for (i = 0; i < 4; i++) { - work = 1; - for (j = 0; j < 32; j++) { - if ((work & parity[i]) != 0) { - psfmt32[idxof(i)] ^= work; - return; - } - work = work << 1; - } - } -} - -/*---------------- - PUBLIC FUNCTIONS - ----------------*/ -/** - * This function returns the identification string. - * The string shows the word size, the Mersenne exponent, - * and all parameters of this generator. - */ -const char *get_idstring(void) { - return IDSTR; -} - -/** - * This function returns the minimum size of array used for \b - * fill_array32() function. - * @return minimum size of array used for fill_array32() function. - */ -int get_min_array_size32(void) { - return N32; -} - -/** - * This function returns the minimum size of array used for \b - * fill_array64() function. - * @return minimum size of array used for fill_array64() function. - */ -int get_min_array_size64(void) { - return N64; -} - -#ifndef ONLY64 -/** - * This function generates and returns 32-bit pseudorandom number. - * init_gen_rand or init_by_array must be called before this function. - * @return 32-bit pseudorandom number - */ -uint32_t gen_rand32(void) { - uint32_t r; - - assert(initialized); - if (idx >= N32) { - gen_rand_all(); - idx = 0; - } - r = psfmt32[idx++]; - return r; -} -#endif -/** - * This function generates and returns 64-bit pseudorandom number. - * init_gen_rand or init_by_array must be called before this function. - * The function gen_rand64 should not be called after gen_rand32, - * unless an initialization is again executed. - * @return 64-bit pseudorandom number - */ -uint64_t gen_rand64(void) { -#if defined(BIG_ENDIAN64) && !defined(ONLY64) - uint32_t r1, r2; -#else - uint64_t r; -#endif - - assert(initialized); - assert(idx % 2 == 0); - - if (idx >= N32) { - gen_rand_all(); - idx = 0; - } -#if defined(BIG_ENDIAN64) && !defined(ONLY64) - r1 = psfmt32[idx]; - r2 = psfmt32[idx + 1]; - idx += 2; - return ((uint64_t)r2 << 32) | r1; -#else - r = psfmt64[idx / 2]; - idx += 2; - return r; -#endif -} - -#ifndef ONLY64 -/** - * This function generates pseudorandom 32-bit integers in the - * specified array[] by one call. The number of pseudorandom integers - * is specified by the argument size, which must be at least 624 and a - * multiple of four. The generation by this function is much faster - * than the following gen_rand function. - * - * For initialization, init_gen_rand or init_by_array must be called - * before the first call of this function. This function can not be - * used after calling gen_rand function, without initialization. - * - * @param array an array where pseudorandom 32-bit integers are filled - * by this function. The pointer to the array must be \b "aligned" - * (namely, must be a multiple of 16) in the SIMD version, since it - * refers to the address of a 128-bit integer. In the standard C - * version, the pointer is arbitrary. - * - * @param size the number of 32-bit pseudorandom integers to be - * generated. size must be a multiple of 4, and greater than or equal - * to (MEXP / 128 + 1) * 4. - * - * @note \b memalign or \b posix_memalign is available to get aligned - * memory. Mac OSX doesn't have these functions, but \b malloc of OSX - * returns the pointer to the aligned memory block. - */ -void fill_array32(uint32_t *array, int size) { - assert(initialized); - assert(idx == N32); - assert(size % 4 == 0); - assert(size >= N32); - - gen_rand_array((w128_t *)array, size / 4); - idx = N32; -} -#endif - -/** - * This function generates pseudorandom 64-bit integers in the - * specified array[] by one call. The number of pseudorandom integers - * is specified by the argument size, which must be at least 312 and a - * multiple of two. The generation by this function is much faster - * than the following gen_rand function. - * - * For initialization, init_gen_rand or init_by_array must be called - * before the first call of this function. This function can not be - * used after calling gen_rand function, without initialization. - * - * @param array an array where pseudorandom 64-bit integers are filled - * by this function. The pointer to the array must be "aligned" - * (namely, must be a multiple of 16) in the SIMD version, since it - * refers to the address of a 128-bit integer. In the standard C - * version, the pointer is arbitrary. - * - * @param size the number of 64-bit pseudorandom integers to be - * generated. size must be a multiple of 2, and greater than or equal - * to (MEXP / 128 + 1) * 2 - * - * @note \b memalign or \b posix_memalign is available to get aligned - * memory. Mac OSX doesn't have these functions, but \b malloc of OSX - * returns the pointer to the aligned memory block. - */ -void fill_array64(uint64_t *array, int size) { - assert(initialized); - assert(idx == N32); - assert(size % 2 == 0); - assert(size >= N64); - - gen_rand_array((w128_t *)array, size / 2); - idx = N32; - -#if defined(BIG_ENDIAN64) && !defined(ONLY64) - swap((w128_t *)array, size /2); -#endif -} - -/** - * This function initializes the internal state array with a 32-bit - * integer seed. - * - * @param seed a 32-bit integer used as the seed. - */ -void init_gen_rand(uint32_t seed) { - int i; - - psfmt32[idxof(0)] = seed; - for (i = 1; i < N32; i++) { - psfmt32[idxof(i)] = 1812433253UL * (psfmt32[idxof(i - 1)] - ^ (psfmt32[idxof(i - 1)] >> 30)) - + i; - } - idx = N32; - period_certification(); - initialized = 1; -} - -/** - * This function initializes the internal state array, - * with an array of 32-bit integers used as the seeds - * @param init_key the array of 32-bit integers, used as a seed. - * @param key_length the length of init_key. - */ -void init_by_array(uint32_t *init_key, int key_length) { - int i, j, count; - uint32_t r; - int lag; - int mid; - int size = N * 4; - - if (size >= 623) { - lag = 11; - } else if (size >= 68) { - lag = 7; - } else if (size >= 39) { - lag = 5; - } else { - lag = 3; - } - mid = (size - lag) / 2; - - memset(sfmt, 0x8b, sizeof(sfmt)); - if (key_length + 1 > N32) { - count = key_length + 1; - } else { - count = N32; - } - r = func1(psfmt32[idxof(0)] ^ psfmt32[idxof(mid)] - ^ psfmt32[idxof(N32 - 1)]); - psfmt32[idxof(mid)] += r; - r += key_length; - psfmt32[idxof(mid + lag)] += r; - psfmt32[idxof(0)] = r; - - count--; - for (i = 1, j = 0; (j < count) && (j < key_length); j++) { - r = func1(psfmt32[idxof(i)] ^ psfmt32[idxof((i + mid) % N32)] - ^ psfmt32[idxof((i + N32 - 1) % N32)]); - psfmt32[idxof((i + mid) % N32)] += r; - r += init_key[j] + i; - psfmt32[idxof((i + mid + lag) % N32)] += r; - psfmt32[idxof(i)] = r; - i = (i + 1) % N32; - } - for (; j < count; j++) { - r = func1(psfmt32[idxof(i)] ^ psfmt32[idxof((i + mid) % N32)] - ^ psfmt32[idxof((i + N32 - 1) % N32)]); - psfmt32[idxof((i + mid) % N32)] += r; - r += i; - psfmt32[idxof((i + mid + lag) % N32)] += r; - psfmt32[idxof(i)] = r; - i = (i + 1) % N32; - } - for (j = 0; j < N32; j++) { - r = func2(psfmt32[idxof(i)] + psfmt32[idxof((i + mid) % N32)] - + psfmt32[idxof((i + N32 - 1) % N32)]); - psfmt32[idxof((i + mid) % N32)] ^= r; - r -= i; - psfmt32[idxof((i + mid + lag) % N32)] ^= r; - psfmt32[idxof(i)] = r; - i = (i + 1) % N32; - } - - idx = N32; - period_certification(); - initialized = 1; -} diff --git a/externals/SFMT/SFMT.h b/externals/SFMT/SFMT.h deleted file mode 100644 index 7c8b35e9e95..00000000000 --- a/externals/SFMT/SFMT.h +++ /dev/null @@ -1,157 +0,0 @@ -/** - * @file SFMT.h - * - * @brief SIMD oriented Fast Mersenne Twister(SFMT) pseudorandom - * number generator - * - * @author Mutsuo Saito (Hiroshima University) - * @author Makoto Matsumoto (Hiroshima University) - * - * Copyright (C) 2006, 2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima - * University. All rights reserved. - * - * The new BSD License is applied to this software. - * see LICENSE.txt - * - * @note We assume that your system has inttypes.h. If your system - * doesn't have inttypes.h, you have to typedef uint32_t and uint64_t, - * and you have to define PRIu64 and PRIx64 in this file as follows: - * @verbatim - typedef unsigned int uint32_t - typedef unsigned long long uint64_t - #define PRIu64 "llu" - #define PRIx64 "llx" -@endverbatim - * uint32_t must be exactly 32-bit unsigned integer type (no more, no - * less), and uint64_t must be exactly 64-bit unsigned integer type. - * PRIu64 and PRIx64 are used for printf function to print 64-bit - * unsigned int and 64-bit unsigned int in hexadecimal format. - */ - -#ifndef SFMT_H -#define SFMT_H - -#include - -#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) - #include -#elif defined(_MSC_VER) || defined(__BORLANDC__) - typedef unsigned int uint32_t; - typedef unsigned __int64 uint64_t; - #define inline __inline -#else - #include - #if defined(__GNUC__) - #define inline __inline__ - #endif -#endif - -#ifndef PRIu64 - #if defined(_MSC_VER) || defined(__BORLANDC__) - #define PRIu64 "I64u" - #define PRIx64 "I64x" - #else - #define PRIu64 "llu" - #define PRIx64 "llx" - #endif -#endif - -#if defined(__GNUC__) -#define ALWAYSINLINE __attribute__((always_inline)) -#else -#define ALWAYSINLINE -#endif - -#if defined(_MSC_VER) - #if _MSC_VER >= 1200 - #define PRE_ALWAYS __forceinline - #else - #define PRE_ALWAYS inline - #endif -#else - #define PRE_ALWAYS inline -#endif - -uint32_t gen_rand32(void); -uint64_t gen_rand64(void); -void fill_array32(uint32_t *array, int size); -void fill_array64(uint64_t *array, int size); -void init_gen_rand(uint32_t seed); -void init_by_array(uint32_t *init_key, int key_length); -const char *get_idstring(void); -int get_min_array_size32(void); -int get_min_array_size64(void); - -/* These real versions are due to Isaku Wada */ -/** generates a random number on [0,1]-real-interval */ -inline static double to_real1(uint32_t v) -{ - return v * (1.0/4294967295.0); - /* divided by 2^32-1 */ -} - -/** generates a random number on [0,1]-real-interval */ -inline static double genrand_real1(void) -{ - return to_real1(gen_rand32()); -} - -/** generates a random number on [0,1)-real-interval */ -inline static double to_real2(uint32_t v) -{ - return v * (1.0/4294967296.0); - /* divided by 2^32 */ -} - -/** generates a random number on [0,1)-real-interval */ -inline static double genrand_real2(void) -{ - return to_real2(gen_rand32()); -} - -/** generates a random number on (0,1)-real-interval */ -inline static double to_real3(uint32_t v) -{ - return (((double)v) + 0.5)*(1.0/4294967296.0); - /* divided by 2^32 */ -} - -/** generates a random number on (0,1)-real-interval */ -inline static double genrand_real3(void) -{ - return to_real3(gen_rand32()); -} -/** These real versions are due to Isaku Wada */ - -/** generates a random number on [0,1) with 53-bit resolution*/ -inline static double to_res53(uint64_t v) -{ - return v * (1.0/18446744073709551616.0L); -} - -/** generates a random number on [0,1) with 53-bit resolution from two - * 32 bit integers */ -inline static double to_res53_mix(uint32_t x, uint32_t y) -{ - return to_res53(x | ((uint64_t)y << 32)); -} - -/** generates a random number on [0,1) with 53-bit resolution - */ -inline static double genrand_res53(void) -{ - return to_res53(gen_rand64()); -} - -/** generates a random number on [0,1) with 53-bit resolution - using 32bit integer. - */ -inline static double genrand_res53_mix(void) -{ - uint32_t x, y; - - x = gen_rand32(); - y = gen_rand32(); - return to_res53_mix(x, y); -} -#endif diff --git a/externals/ace/ACE.cpp b/externals/ace/ACE.cpp deleted file mode 100644 index 3dd5e2e6f9b..00000000000 --- a/externals/ace/ACE.cpp +++ /dev/null @@ -1,3517 +0,0 @@ -// $Id: ACE.cpp 91066 2010-07-12 11:05:04Z johnnyw $ - -#include "ace/ACE.h" - -#include "ace/Basic_Types.h" -#include "ace/Handle_Set.h" -#include "ace/Auto_Ptr.h" -#include "ace/SString.h" -#include "ace/Version.h" -#include "ace/Message_Block.h" -#include "ace/Log_Msg.h" -#include "ace/OS_NS_sys_select.h" -#include "ace/OS_NS_string.h" -#include "ace/OS_NS_strings.h" -#include "ace/OS_NS_signal.h" -#include "ace/OS_NS_stdio.h" -#include "ace/OS_NS_sys_resource.h" -#include "ace/OS_NS_sys_wait.h" -#include "ace/OS_NS_sys_time.h" -#include "ace/OS_NS_time.h" -#include "ace/OS_NS_sys_uio.h" -#include "ace/OS_NS_sys_stat.h" -#include "ace/OS_NS_ctype.h" -#include "ace/OS_NS_fcntl.h" -#include "ace/OS_TLI.h" -#include "ace/Truncate.h" - -#if defined (ACE_VXWORKS) && (ACE_VXWORKS < 0x620) -extern "C" int maxFiles; -#endif /* ACE_VXWORKS */ - -#if !defined (__ACE_INLINE__) -#include "ace/ACE.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_HAS_POLL) && defined (ACE_HAS_LIMITED_SELECT) -# include "ace/OS_NS_poll.h" -#endif /* ACE_HAS_POLL && ACE_HAS_LIMITED_SELECT */ - - -ACE_RCSID (ace, - ACE, - "$Id: ACE.cpp 91066 2010-07-12 11:05:04Z johnnyw $") - - -// Open versioned namespace, if enabled by the user. - ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -namespace ACE -{ - // private: - // Used internally so not exported. - - // Size of allocation granularity. - size_t allocation_granularity_ = 0; - - // Size of a VM page. - size_t pagesize_ = 0; - - // Are we debugging ACE? - // Keeps track of whether we're in some global debug mode. - char debug_; -} - - -int -ACE::out_of_handles (int error) -{ - // EMFILE is common to all platforms. - if (error == EMFILE || -#if defined (ACE_WIN32) - // On Win32, we need to check for ENOBUFS also. - error == ENOBUFS || -#elif defined (HPUX) - // On HPUX, we need to check for EADDRNOTAVAIL also. - error == EADDRNOTAVAIL || -#elif defined (linux) - // On linux, we need to check for ENOENT also. - error == ENOENT || - // For RedHat5.2, need to check for EINVAL too. - error == EINVAL || - // Without threads check for EOPNOTSUPP - error == EOPNOTSUPP || -#elif defined (sun) - // On sun, we need to check for ENOSR also. - error == ENOSR || - // Without threads check for ENOTSUP - error == ENOTSUP || -#elif defined (__FreeBSD__) - // On FreeBSD we need to check for EOPNOTSUPP (LinuxThreads) or - // ENOSYS (libc_r threads) also. - error == EOPNOTSUPP || - error == ENOSYS || -#elif defined (__OpenBSD__) - // OpenBSD appears to return EBADF. - error == EBADF || -#elif defined (__sgi) // irix - error == ENOTSUP || -#elif defined (DIGITAL_UNIX) // osf1 - error == ENOTSUP || -#endif /* ACE_WIN32 */ - error == ENFILE) - return 1; - else - return 0; -} - -u_int -ACE::major_version (void) -{ - return ACE_MAJOR_VERSION; -} - -u_int -ACE::minor_version (void) -{ - return ACE_MINOR_VERSION; -} - -u_int -ACE::beta_version (void) -{ - return ACE_BETA_VERSION; -} - -const ACE_TCHAR * -ACE::compiler_name (void) -{ -#ifdef ACE_CC_NAME - return ACE_CC_NAME; -#else - return ACE_TEXT (""); -#endif -} - -u_int -ACE::compiler_major_version (void) -{ -#ifdef ACE_CC_MAJOR_VERSION - return ACE_CC_MAJOR_VERSION; -#else - return 0; -#endif -} - -u_int -ACE::compiler_minor_version (void) -{ -#ifdef ACE_CC_MINOR_VERSION - return ACE_CC_MINOR_VERSION; -#else - return 0; -#endif -} - -u_int -ACE::compiler_beta_version (void) -{ -#ifdef ACE_CC_BETA_VERSION - return ACE_CC_BETA_VERSION; -#else - return 0; -#endif -} - -ACE_TCHAR -ACE::nibble2hex (u_int n) -{ - // Yes, this works for UNICODE - return ACE_TEXT ("0123456789abcdef")[n & 0x0f]; -} - -bool -ACE::debug (void) -{ - static const char* debug = ACE_OS::getenv ("ACE_DEBUG"); - return (ACE::debug_ != 0) ? ACE::debug_ : (debug != 0 ? (*debug != '0') : false); -} - -void -ACE::debug (bool onoff) -{ - ACE::debug_ = onoff; -} - -int -ACE::select (int width, - ACE_Handle_Set *readfds, - ACE_Handle_Set *writefds, - ACE_Handle_Set *exceptfds, - const ACE_Time_Value *timeout) -{ - int result = ACE_OS::select (width, - readfds ? readfds->fdset () : 0, - writefds ? writefds->fdset () : 0, - exceptfds ? exceptfds->fdset () : 0, - timeout); - if (result > 0) - { -# if !defined (ACE_WIN32) - // This isn't needed for Windows... it's a no-op anyway. - if (readfds) - readfds->sync ((ACE_HANDLE) width); - if (writefds) - writefds->sync ((ACE_HANDLE) width); - if (exceptfds) - exceptfds->sync ((ACE_HANDLE) width); -#endif /* ACE_WIN32 */ - } - return result; -} - -int -ACE::select (int width, - ACE_Handle_Set &readfds, - const ACE_Time_Value *timeout) -{ - int result = ACE_OS::select (width, - readfds.fdset (), - 0, - 0, - timeout); - -#if !defined (ACE_WIN32) - if (result > 0) - readfds.sync ((ACE_HANDLE) width); -#endif /* ACE_WIN32 */ - return result; -} - -int -ACE::terminate_process (pid_t pid) -{ -#if defined (ACE_HAS_PHARLAP) - ACE_UNUSED_ARG (pid); - ACE_NOTSUP_RETURN (-1); -#elif defined (ACE_WIN32) - // Create a handle for the given process id. - ACE_HANDLE process_handle = - ::OpenProcess (PROCESS_TERMINATE, - FALSE, // New handle is not inheritable. - pid); - - if (process_handle == ACE_INVALID_HANDLE - || process_handle == 0) - return -1; - else - { - // Kill the process associated with process_handle. - BOOL terminate_result = - ::TerminateProcess (process_handle, 0); - // Free up the kernel resources. - ACE_OS::close (process_handle); - return terminate_result ? 0 : -1; - } -#else - return ACE_OS::kill (pid, 9); -#endif /* ACE_HAS_PHARLAP */ -} - -int -ACE::process_active (pid_t pid) -{ -#if !defined(ACE_WIN32) - if (ACE_OS::kill (pid, 0) == 0) - return 1; - else if (errno == ESRCH) - return 0; - else - return -1; -#else - // Create a handle for the given process id. - ACE_HANDLE process_handle = - ::OpenProcess (PROCESS_QUERY_INFORMATION, FALSE, pid); - if (process_handle == ACE_INVALID_HANDLE || process_handle == 0) - return 0; - else - { - DWORD status; - int result = 1; - if (::GetExitCodeProcess (process_handle, - &status) == 0 - || status != STILL_ACTIVE) - result = 0; - - ::CloseHandle (process_handle); - return result; - } -#endif /* !ACE_WIN32 */ -} - -const ACE_TCHAR * -ACE::execname (const ACE_TCHAR *old_name) -{ -#if defined (ACE_WIN32) - const ACE_TCHAR *suffix = ACE_OS::strrchr (old_name, ACE_TEXT ('.')); - if (suffix == 0 || ACE_OS::strcasecmp (suffix, ACE_TEXT (".exe")) != 0) - { - ACE_TCHAR *new_name = 0; - - size_t size = - ACE_OS::strlen (old_name) - + ACE_OS::strlen (ACE_TEXT (".exe")) - + 1; - - ACE_NEW_RETURN (new_name, - ACE_TCHAR[size], - 0); - ACE_TCHAR *end = new_name; - - end = ACE_OS::strecpy (new_name, old_name); - - // Concatenate the .exe suffix onto the end of the executable. - // end points _after_ the terminating nul. - ACE_OS::strcpy (end - 1, ACE_TEXT (".exe")); - - return new_name; - } -#endif /* ACE_WIN32 */ - return old_name; -} - -u_long -ACE::hash_pjw (const char *str, size_t len) -{ - u_long hash = 0; - - for (size_t i = 0; i < len; i++) - { - const char temp = str[i]; - hash = (hash << 4) + (temp * 13); - - u_long g = hash & 0xf0000000; - - if (g) - { - hash ^= (g >> 24); - hash ^= g; - } - } - - return hash; -} - -u_long -ACE::hash_pjw (const char *str) -{ - return ACE::hash_pjw (str, ACE_OS::strlen (str)); -} - -#if defined (ACE_HAS_WCHAR) -u_long -ACE::hash_pjw (const wchar_t *str, size_t len) -{ - u_long hash = 0; - - for (size_t i = 0; i < len; i++) - { - // @@ UNICODE: Does this function do the correct thing with wchar's? - - const wchar_t temp = str[i]; - hash = (hash << 4) + (temp * 13); - - u_long g = hash & 0xf0000000; - - if (g) - { - hash ^= (g >> 24); - hash ^= g; - } - } - - return hash; -} - -u_long -ACE::hash_pjw (const wchar_t *str) -{ - return ACE::hash_pjw (str, ACE_OS::strlen (str)); -} -#endif /* ACE_HAS_WCHAR */ - -ACE_TCHAR * -ACE::strenvdup (const ACE_TCHAR *str) -{ - ACE_TRACE ("ACE::strenvdup"); - - return ACE_OS::strenvdup (str); -} - -/* - -Examples: - -Source NT UNIX -================================================================== -netsvc netsvc.dll libnetsvc.so -(PATH will be (LD_LIBRARY_PATH -evaluated) evaluated) - -libnetsvc.dll libnetsvc.dll libnetsvc.dll + warning -netsvc.so netsvc.so + warning libnetsvc.so - -..\../libs/netsvc ..\..\libs\netsvc.dll ../../libs/netsvc.so -(absolute path used) (absolute path used) - -*/ - -const ACE_TCHAR * -ACE::basename (const ACE_TCHAR *pathname, ACE_TCHAR delim) -{ - ACE_TRACE ("ACE::basename"); - const ACE_TCHAR *temp = ACE_OS::strrchr (pathname, delim); - - if (temp == 0) - return pathname; - else - return temp + 1; -} - -const ACE_TCHAR * -ACE::dirname (const ACE_TCHAR *pathname, ACE_TCHAR delim) -{ - ACE_TRACE ("ACE::dirname"); - static ACE_TCHAR return_dirname[MAXPATHLEN + 1]; - - const ACE_TCHAR *temp = ACE_OS::strrchr (pathname, delim); - - if (temp == 0) - { - return_dirname[0] = '.'; - return_dirname[1] = '\0'; - - return return_dirname; - } - else - { - // When the len is truncated, there are problems! This should - // not happen in normal circomstances - size_t len = temp - pathname + 1; - if (len > (sizeof return_dirname / sizeof (ACE_TCHAR))) - len = sizeof return_dirname / sizeof (ACE_TCHAR); - - ACE_OS::strsncpy (return_dirname, - pathname, - len); - return return_dirname; - } -} - -ssize_t -ACE::recv (ACE_HANDLE handle, - void *buf, - size_t len, - int flags, - const ACE_Time_Value *timeout) -{ - if (timeout == 0) - return ACE_OS::recv (handle, (char *) buf, len, flags); - else - { - int val = 0; - if (ACE::enter_recv_timedwait (handle, timeout, val) ==-1) - return -1; - else - { - ssize_t bytes_transferred = - ACE_OS::recv (handle, (char *) buf, len, flags); - ACE::restore_non_blocking_mode (handle, val); - return bytes_transferred; - } - } -} - -#if defined (ACE_HAS_TLI) - -ssize_t -ACE::t_rcv (ACE_HANDLE handle, - void *buf, - size_t len, - int *flags, - const ACE_Time_Value *timeout) -{ - if (timeout == 0) - return ACE_OS::t_rcv (handle, (char *) buf, len, flags); - else - { - int val = 0; - if (ACE::enter_recv_timedwait (handle, timeout, val) ==-1) - return -1; - else - { - ssize_t bytes_transferred = - ACE_OS::t_rcv (handle, (char *) buf, len, flags); - ACE::restore_non_blocking_mode (handle, val); - return bytes_transferred; - } - } -} - -#endif /* ACE_HAS_TLI */ - -ssize_t -ACE::recv (ACE_HANDLE handle, - void *buf, - size_t n, - const ACE_Time_Value *timeout) -{ - if (timeout == 0) - return ACE::recv_i (handle, buf, n); - else - { - int val = 0; - if (ACE::enter_recv_timedwait (handle, timeout, val) == -1) - return -1; - else - { - ssize_t bytes_transferred = ACE::recv_i (handle, buf, n); - ACE::restore_non_blocking_mode (handle, val); - return bytes_transferred; - } - } -} - -ssize_t -ACE::recvmsg (ACE_HANDLE handle, - struct msghdr *msg, - int flags, - const ACE_Time_Value *timeout) -{ - if (timeout == 0) - return ACE_OS::recvmsg (handle, msg, flags); - else - { - int val = 0; - if (ACE::enter_recv_timedwait (handle, timeout, val) == -1) - return -1; - else - { - ssize_t bytes_transferred = ACE_OS::recvmsg (handle, msg, flags); - ACE::restore_non_blocking_mode (handle, val); - return bytes_transferred; - } - } -} - -ssize_t -ACE::recvfrom (ACE_HANDLE handle, - char *buf, - int len, - int flags, - struct sockaddr *addr, - int *addrlen, - const ACE_Time_Value *timeout) -{ - if (timeout == 0) - return ACE_OS::recvfrom (handle, buf, len, flags, addr, addrlen); - else - { - int val = 0; - if (ACE::enter_recv_timedwait (handle, timeout, val) == -1) - return -1; - else - { - ssize_t bytes_transferred = - ACE_OS::recvfrom (handle, buf, len, flags, addr, addrlen); - ACE::restore_non_blocking_mode (handle, val); - return bytes_transferred; - } - } -} - -ssize_t -ACE::recv_n_i (ACE_HANDLE handle, - void *buf, - size_t len, - int flags, - size_t *bt) -{ - size_t temp; - size_t &bytes_transferred = bt == 0 ? temp : *bt; - ssize_t n; - - for (bytes_transferred = 0; - bytes_transferred < len; - bytes_transferred += n) - { - // Try to transfer as much of the remaining data as possible. - n = ACE_OS::recv (handle, - static_cast (buf) + bytes_transferred, - len - bytes_transferred, - flags); - // Check EOF. - if (n == 0) - return 0; - - // Check for other errors. - if (n == -1) - { - // Check for possible blocking. - if (errno == EWOULDBLOCK) - { - // Wait for the blocking to subside. - int const result = ACE::handle_read_ready (handle, 0); - - // Did select() succeed? - if (result != -1) - { - // Blocking subsided. Continue data transfer. - n = 0; - continue; - } - } - - // Other data transfer or select() failures. - return -1; - } - } - - return static_cast (bytes_transferred); -} - -ssize_t -ACE::recv_n_i (ACE_HANDLE handle, - void *buf, - size_t len, - int flags, - const ACE_Time_Value *timeout, - size_t *bt) -{ - size_t temp; - size_t &bytes_transferred = bt == 0 ? temp : *bt; - ssize_t n; - ssize_t result = 0; - int error = 0; - - int val = 0; - ACE::record_and_set_non_blocking_mode (handle, val); - - for (bytes_transferred = 0; - bytes_transferred < len; - bytes_transferred += n) - { - // Try to transfer as much of the remaining data as possible. - // Since the socket is in non-blocking mode, this call will not - // block. - n = ACE_OS::recv (handle, - static_cast (buf) + bytes_transferred, - len - bytes_transferred, - flags); - - // Check for errors. - if (n == 0 || - n == -1) - { - // Check for possible blocking. - if (n == -1 && - errno == EWOULDBLOCK) - { - // Wait upto for the blocking to subside. - int const rtn = ACE::handle_read_ready (handle, timeout); - - // Did select() succeed? - if (rtn != -1) - { - // Blocking subsided in period. Continue - // data transfer. - n = 0; - continue; - } - } - - // Wait in select() timed out or other data transfer or - // select() failures. - error = 1; - result = n; - break; - } - } - - ACE::restore_non_blocking_mode (handle, val); - - if (error) - return result; - else - return static_cast (bytes_transferred); -} - -#if defined (ACE_HAS_TLI) - -ssize_t -ACE::t_rcv_n_i (ACE_HANDLE handle, - void *buf, - size_t len, - int *flags, - size_t *bt) -{ - size_t temp; - size_t &bytes_transferred = bt == 0 ? temp : *bt; - ssize_t n; - - for (bytes_transferred = 0; - bytes_transferred < len; - bytes_transferred += n) - { - // Try to transfer as much of the remaining data as possible. - n = ACE_OS::t_rcv (handle, - (char *) buf + bytes_transferred, - len - bytes_transferred, - flags); - // Check EOF. - if (n == 0) - return 0; - - // Check for other errors. - if (n == -1) - { - // Check for possible blocking. - if (errno == EWOULDBLOCK) - { - // Wait for the blocking to subside. - int const result = ACE::handle_read_ready (handle, 0); - - // Did select() succeed? - if (result != -1) - { - // Blocking subsided. Continue data transfer. - n = 0; - continue; - } - } - - // Other data transfer or select() failures. - return -1; - } - } - - return bytes_transferred; -} - -ssize_t -ACE::t_rcv_n_i (ACE_HANDLE handle, - void *buf, - size_t len, - int *flags, - const ACE_Time_Value *timeout, - size_t *bt) -{ - size_t temp; - size_t &bytes_transferred = bt == 0 ? temp : *bt; - ssize_t n; - ssize_t result = 0; - int error = 0; - - int val = 0; - ACE::record_and_set_non_blocking_mode (handle, val); - - for (bytes_transferred = 0; - bytes_transferred < len; - bytes_transferred += n) - { - // Try to transfer as much of the remaining data as possible. - // Since the socket is in non-blocking mode, this call will not - // block. - n = ACE_OS::t_rcv (handle, - (char *) buf + bytes_transferred, - len - bytes_transferred, - flags); - - // Check for errors. - if (n == 0 || - n == -1) - { - // Check for possible blocking. - if (n == -1 && - errno == EWOULDBLOCK) - { - // Wait upto for the blocking to subside. - int const rtn = ACE::handle_read_ready (handle, timeout); - - // Did select() succeed? - if (rtn != -1) - { - // Blocking subsided in period. Continue - // data transfer. - n = 0; - continue; - } - } - - // Wait in select() timed out or other data transfer or - // select() failures. - error = 1; - result = n; - break; - } - } - - ACE::restore_non_blocking_mode (handle, val); - - if (error) - return result; - else - return bytes_transferred; -} - -#endif /* ACE_HAS_TLI */ - -ssize_t -ACE::recv_n_i (ACE_HANDLE handle, - void *buf, - size_t len, - size_t *bt) -{ - size_t temp; - size_t &bytes_transferred = bt == 0 ? temp : *bt; - ssize_t n; - - for (bytes_transferred = 0; - bytes_transferred < len; - bytes_transferred += n) - { - // Try to transfer as much of the remaining data as possible. - n = ACE::recv_i (handle, - static_cast (buf) + bytes_transferred, - len - bytes_transferred); - // Check EOF. - if (n == 0) - { - return 0; - } - // Check for other errors. - if (n == -1) - { - // Check for possible blocking. - if (errno == EWOULDBLOCK) - { - // Wait for the blocking to subside. - int const result = ACE::handle_read_ready (handle, 0); - - // Did select() succeed? - if (result != -1) - { - // Blocking subsided. Continue data transfer. - n = 0; - continue; - } - } - - // Other data transfer or select() failures. - return -1; - } - } - - return static_cast (bytes_transferred); -} - -ssize_t -ACE::recv_n_i (ACE_HANDLE handle, - void *buf, - size_t len, - const ACE_Time_Value *timeout, - size_t *bt) -{ - size_t temp; - size_t &bytes_transferred = bt == 0 ? temp : *bt; - ssize_t n; - ssize_t result = 0; - int error = 0; - - int val = 0; - ACE::record_and_set_non_blocking_mode (handle, val); - - for (bytes_transferred = 0; - bytes_transferred < len; - bytes_transferred += n) - { - // Try to transfer as much of the remaining data as possible. - // Since the socket is in non-blocking mode, this call will not - // block. - n = ACE::recv_i (handle, - static_cast (buf) + bytes_transferred, - len - bytes_transferred); - - // Check for errors. - if (n == 0 || - n == -1) - { - // Check for possible blocking. - if (n == -1 && - errno == EWOULDBLOCK) - { - // Wait upto for the blocking to subside. - int const rtn = ACE::handle_read_ready (handle, timeout); - - // Did select() succeed? - if (rtn != -1) - { - // Blocking subsided in period. Continue - // data transfer. - n = 0; - continue; - } - } - - // Wait in select() timed out or other data transfer or - // select() failures. - error = 1; - result = n; - break; - } - } - - ACE::restore_non_blocking_mode (handle, val); - - if (error) - return result; - else - return static_cast (bytes_transferred); -} - -// This is basically an interface to ACE_OS::readv, that doesn't use -// the struct iovec explicitly. The ... can be passed as an arbitrary -// number of (char *ptr, int len) tuples. However, the count N is the -// *total* number of trailing arguments, *not* a couple of the number -// of tuple pairs! - -ssize_t -ACE::recv (ACE_HANDLE handle, size_t n, ...) -{ - va_list argp; - int const total_tuples = static_cast (n / 2); - iovec *iovp = 0; -#if defined (ACE_HAS_ALLOCA) - iovp = (iovec *) alloca (total_tuples * sizeof (iovec)); -#else - ACE_NEW_RETURN (iovp, - iovec[total_tuples], - -1); -#endif /* !defined (ACE_HAS_ALLOCA) */ - - va_start (argp, n); - - for (int i = 0; i < total_tuples; i++) - { - iovp[i].iov_base = va_arg (argp, char *); - iovp[i].iov_len = va_arg (argp, int); - } - - ssize_t const result = ACE_OS::recvv (handle, iovp, total_tuples); -#if !defined (ACE_HAS_ALLOCA) - delete [] iovp; -#endif /* !defined (ACE_HAS_ALLOCA) */ - va_end (argp); - return result; -} - -ssize_t -ACE::recvv (ACE_HANDLE handle, - iovec *iov, - int iovcnt, - const ACE_Time_Value *timeout) -{ - if (timeout == 0) - return ACE_OS::recvv (handle, iov, iovcnt); - else - { - int val = 0; - if (ACE::enter_recv_timedwait (handle, timeout, val) == -1) - return -1; - else - { - ssize_t bytes_transferred = ACE_OS::recvv (handle, iov, iovcnt); - ACE::restore_non_blocking_mode (handle, val); - return bytes_transferred; - } - } -} - -ssize_t -ACE::recvv_n_i (ACE_HANDLE handle, - iovec *iov, - int iovcnt, - size_t *bt) -{ - size_t temp; - size_t &bytes_transferred = bt == 0 ? temp : *bt; - bytes_transferred = 0; - - for (int s = 0; s < iovcnt; ) - { - // Try to transfer as much of the remaining data as possible. - ssize_t n = ACE_OS::recvv (handle, iov + s, iovcnt - s); - // Check EOF. - if (n == 0) - return 0; - - // Check for other errors. - if (n == -1) - { - // Check for possible blocking. - if (errno == EWOULDBLOCK) - { - // Wait for the blocking to subside. - int const result = ACE::handle_read_ready (handle, 0); - - // Did select() succeed? - if (result != -1) - { - // Blocking subsided. Continue data transfer. - n = 0; - continue; - } - } - - // Other data transfer or select() failures. - return -1; - } - - for (bytes_transferred += n; - s < iovcnt - && n >= static_cast (iov[s].iov_len); - s++) - n -= iov[s].iov_len; - - if (n != 0) - { - char *base = static_cast (iov[s].iov_base); - iov[s].iov_base = base + n; - iov[s].iov_len = iov[s].iov_len - n; - } - } - - return ACE_Utils::truncate_cast (bytes_transferred); -} - -ssize_t -ACE::recvv_n_i (ACE_HANDLE handle, - iovec *iov, - int iovcnt, - const ACE_Time_Value *timeout, - size_t *bt) -{ - size_t temp; - size_t &bytes_transferred = bt == 0 ? temp : *bt; - bytes_transferred = 0; - ssize_t result = 0; - int error = 0; - - int val = 0; - ACE::record_and_set_non_blocking_mode (handle, val); - - for (int s = 0; s < iovcnt; ) - { - // Try to transfer as much of the remaining data as possible. - // Since the socket is in non-blocking mode, this call will not - // block. - ssize_t n = ACE_OS::recvv (handle, iov + s, iovcnt - s); - - // Check for errors. - if (n == 0 || n == -1) - { - // Check for possible blocking. - if (n == -1 && errno == EWOULDBLOCK) - { - // Wait upto for the blocking to subside. - int const rtn = ACE::handle_read_ready (handle, timeout); - - // Did select() succeed? - if (rtn != -1) - { - // Blocking subsided in period. Continue - // data transfer. - n = 0; - continue; - } - } - - // Wait in select() timed out or other data transfer or - // select() failures. - error = 1; - result = n; - break; - } - - for (bytes_transferred += n; - s < iovcnt - && n >= static_cast (iov[s].iov_len); - s++) - n -= iov[s].iov_len; - - if (n != 0) - { - char *base = reinterpret_cast (iov[s].iov_base); - iov[s].iov_base = base + n; - iov[s].iov_len = iov[s].iov_len - n; - } - } - - ACE::restore_non_blocking_mode (handle, val); - - if (error) - { - return result; - } - else - { - return ACE_Utils::truncate_cast (bytes_transferred); - } -} - -ssize_t -ACE::recv_n (ACE_HANDLE handle, - ACE_Message_Block *message_block, - const ACE_Time_Value *timeout, - size_t *bt) -{ - size_t temp; - size_t &bytes_transferred = bt == 0 ? temp : *bt; - bytes_transferred = 0; - - iovec iov[ACE_IOV_MAX]; - int iovcnt = 0; - - while (message_block != 0) - { - // Our current message block chain. - const ACE_Message_Block *current_message_block = message_block; - - while (current_message_block != 0) - { - size_t current_message_block_length = - current_message_block->length (); - char *this_rd_ptr = current_message_block->rd_ptr (); - - // Check if this block has any space for incoming data. - while (current_message_block_length > 0) - { - u_long const this_chunk_length = - ACE_Utils::truncate_cast ( - current_message_block_length); - - // Collect the data in the iovec. - iov[iovcnt].iov_base = this_rd_ptr; - iov[iovcnt].iov_len = this_chunk_length; - current_message_block_length -= this_chunk_length; - this_rd_ptr += this_chunk_length; - - // Increment iovec counter. - ++iovcnt; - - // The buffer is full make a OS call. @@ TODO find a way to - // find ACE_IOV_MAX for platforms that do not define it rather - // than simply setting ACE_IOV_MAX to some arbitrary value such - // as 16. - if (iovcnt == ACE_IOV_MAX) - { - size_t current_transfer = 0; - - ssize_t const result = ACE::recvv_n (handle, - iov, - iovcnt, - timeout, - ¤t_transfer); - - // Add to total bytes transferred. - bytes_transferred += current_transfer; - - // Errors. - if (result == -1 || result == 0) - return result; - - // Reset iovec counter. - iovcnt = 0; - } - } - - // Select the next message block in the chain. - current_message_block = current_message_block->cont (); - } - - // Selection of the next message block chain. - message_block = message_block->next (); - } - - // Check for remaining buffers to be sent. This will happen when - // ACE_IOV_MAX is not a multiple of the number of message blocks. - if (iovcnt != 0) - { - size_t current_transfer = 0; - - ssize_t const result = ACE::recvv_n (handle, - iov, - iovcnt, - timeout, - ¤t_transfer); - - // Add to total bytes transferred. - bytes_transferred += current_transfer; - - // Errors. - if (result == -1 || result == 0) - { - return result; - } - } - - // Return total bytes transferred. - return ACE_Utils::truncate_cast (bytes_transferred); -} - -ssize_t -ACE::send (ACE_HANDLE handle, - const void *buf, - size_t n, - int flags, - const ACE_Time_Value *timeout) -{ - if (timeout == 0) - return ACE_OS::send (handle, (const char *) buf, n, flags); - else - { - int val = 0; - if (ACE::enter_send_timedwait (handle, timeout, val) == -1) - return -1; - else - { - ssize_t const bytes_transferred = - ACE_OS::send (handle, (const char *) buf, n, flags); - ACE::restore_non_blocking_mode (handle, val); - return bytes_transferred; - } - } -} - -#if defined (ACE_HAS_TLI) - -ssize_t -ACE::t_snd (ACE_HANDLE handle, - const void *buf, - size_t n, - int flags, - const ACE_Time_Value *timeout) -{ - if (timeout == 0) - return ACE_OS::t_snd (handle, (const char *) buf, n, flags); - else - { - int val = 0; - if (ACE::enter_send_timedwait (handle, timeout, val) == -1) - return -1; - else - { - ssize_t const bytes_transferred = - ACE_OS::t_snd (handle, (const char *) buf, n, flags); - ACE::restore_non_blocking_mode (handle, val); - return bytes_transferred; - } - } -} - -#endif /* ACE_HAS_TLI */ - -ssize_t -ACE::send (ACE_HANDLE handle, - const void *buf, - size_t n, - const ACE_Time_Value *timeout) -{ - if (timeout == 0) - return ACE::send_i (handle, buf, n); - else - { - int val = 0; - if (ACE::enter_send_timedwait (handle, timeout, val) == -1) - return -1; - else - { - ssize_t const bytes_transferred = ACE::send_i (handle, buf, n); - ACE::restore_non_blocking_mode (handle, val); - return bytes_transferred; - } - } -} - -ssize_t -ACE::sendmsg (ACE_HANDLE handle, - const struct msghdr *msg, - int flags, - const ACE_Time_Value *timeout) -{ - if (timeout == 0) - return ACE_OS::sendmsg (handle, msg, flags); - else - { - int val = 0; - if (ACE::enter_send_timedwait (handle, timeout, val) == -1) - return -1; - else - { - ssize_t const bytes_transferred = - ACE_OS::sendmsg (handle, msg, flags); - ACE::restore_non_blocking_mode (handle, val); - return bytes_transferred; - } - } -} - -ssize_t -ACE::sendto (ACE_HANDLE handle, - const char *buf, - int len, - int flags, - const struct sockaddr *addr, - int addrlen, - const ACE_Time_Value *timeout) -{ - if (timeout == 0) - return ACE_OS::sendto (handle, buf, len, flags, addr, addrlen); - else - { - int val = 0; - if (ACE::enter_send_timedwait (handle, timeout, val) == -1) - return -1; - else - { - ssize_t const bytes_transferred = - ACE_OS::sendto (handle, buf, len, flags, addr, addrlen); - ACE::restore_non_blocking_mode (handle, val); - return bytes_transferred; - } - } -} - -ssize_t -ACE::send_n_i (ACE_HANDLE handle, - const void *buf, - size_t len, - int flags, - size_t *bt) -{ - size_t temp; - size_t &bytes_transferred = bt == 0 ? temp : *bt; - ssize_t n; - - for (bytes_transferred = 0; - bytes_transferred < len; - bytes_transferred += n) - { - // Try to transfer as much of the remaining data as possible. - n = ACE_OS::send (handle, - (char *) buf + bytes_transferred, - len - bytes_transferred, - flags); - // Check EOF. - if (n == 0) - return 0; - - // Check for other errors. - if (n == -1) - { - // Check for possible blocking. -#if defined (ACE_WIN32) - if (errno == EWOULDBLOCK) // If enobufs no need to loop -#else - if (errno == EWOULDBLOCK || errno == ENOBUFS) -#endif /* ACE_WIN32 */ - { - // Wait for the blocking to subside. - int const result = ACE::handle_write_ready (handle, 0); - - // Did select() succeed? - if (result != -1) - { - // Blocking subsided. Continue data transfer. - n = 0; - continue; - } - } - - // Other data transfer or select() failures. - return -1; - } - } - - return ACE_Utils::truncate_cast (bytes_transferred); -} - -ssize_t -ACE::send_n_i (ACE_HANDLE handle, - const void *buf, - size_t len, - int flags, - const ACE_Time_Value *timeout, - size_t *bt) -{ - size_t temp; - size_t &bytes_transferred = bt == 0 ? temp : *bt; - ssize_t n; - ssize_t result = 0; - int error = 0; - - int val = 0; - ACE::record_and_set_non_blocking_mode (handle, val); - - for (bytes_transferred = 0; - bytes_transferred < len; - bytes_transferred += n) - { - // Try to transfer as much of the remaining data as possible. - // Since the socket is in non-blocking mode, this call will not - // block. - n = ACE_OS::send (handle, - (char *) buf + bytes_transferred, - len - bytes_transferred, - flags); - - // Check for errors. - if (n == 0 || - n == -1) - { - // Check for possible blocking. - if (n == -1 && (errno == EWOULDBLOCK || errno == ENOBUFS)) - { - // Wait upto for the blocking to subside. - int const rtn = ACE::handle_write_ready (handle, timeout); - - // Did select() succeed? - if (rtn != -1) - { - // Blocking subsided in period. Continue - // data transfer. - n = 0; - continue; - } - } - - // Wait in select() timed out or other data transfer or - // select() failures. - error = 1; - result = n; - break; - } - } - - ACE::restore_non_blocking_mode (handle, val); - - if (error) - { - return result; - } - else - { - return ACE_Utils::truncate_cast (bytes_transferred); - } -} - -#if defined (ACE_HAS_TLI) - -ssize_t -ACE::t_snd_n_i (ACE_HANDLE handle, - const void *buf, - size_t len, - int flags, - size_t *bt) -{ - size_t temp; - size_t &bytes_transferred = bt == 0 ? temp : *bt; - ssize_t n; - - for (bytes_transferred = 0; - bytes_transferred < len; - bytes_transferred += n) - { - // Try to transfer as much of the remaining data as possible. - n = ACE_OS::t_snd (handle, - (char *) buf + bytes_transferred, - len - bytes_transferred, - flags); - // Check EOF. - if (n == 0) - return 0; - - // Check for other errors. - if (n == -1) - { - // Check for possible blocking. - if (errno == EWOULDBLOCK || errno == ENOBUFS) - { - // Wait for the blocking to subside. - int const result = ACE::handle_write_ready (handle, 0); - - // Did select() succeed? - if (result != -1) - { - // Blocking subsided. Continue data transfer. - n = 0; - continue; - } - } - - // Other data transfer or select() failures. - return -1; - } - } - - return bytes_transferred; -} - -ssize_t -ACE::t_snd_n_i (ACE_HANDLE handle, - const void *buf, - size_t len, - int flags, - const ACE_Time_Value *timeout, - size_t *bt) -{ - size_t temp; - size_t &bytes_transferred = bt == 0 ? temp : *bt; - ssize_t n; - ssize_t result = 0; - int error = 0; - - int val = 0; - ACE::record_and_set_non_blocking_mode (handle, val); - - for (bytes_transferred = 0; - bytes_transferred < len; - bytes_transferred += n) - { - // Try to transfer as much of the remaining data as possible. - // Since the socket is in non-blocking mode, this call will not - // block. - n = ACE_OS::t_snd (handle, - (char *) buf + bytes_transferred, - len - bytes_transferred, - flags); - - // Check for errors. - if (n == 0 || - n == -1) - { - // Check for possible blocking. - if (n == -1 && - errno == EWOULDBLOCK || errno == ENOBUFS) - { - // Wait upto for the blocking to subside. - int const rtn = ACE::handle_write_ready (handle, timeout); - - // Did select() succeed? - if (rtn != -1) - { - // Blocking subsided in period. Continue - // data transfer. - n = 0; - continue; - } - } - - // Wait in select() timed out or other data transfer or - // select() failures. - error = 1; - result = n; - break; - } - } - - ACE::restore_non_blocking_mode (handle, val); - - if (error) - return result; - else - return bytes_transferred; -} - -#endif /* ACE_HAS_TLI */ - -ssize_t -ACE::send_n_i (ACE_HANDLE handle, - const void *buf, - size_t len, - size_t *bt) -{ - size_t temp; - size_t &bytes_transferred = bt == 0 ? temp : *bt; - ssize_t n; - - for (bytes_transferred = 0; - bytes_transferred < len; - bytes_transferred += n) - { - // Try to transfer as much of the remaining data as possible. - n = ACE::send_i (handle, - (char *) buf + bytes_transferred, - len - bytes_transferred); - // Check EOF. - if (n == 0) - { - return 0; - } - - // Check for other errors. - if (n == -1) - { - // Check for possible blocking. - if (errno == EWOULDBLOCK || errno == ENOBUFS) - { - // Wait for the blocking to subside. - int const result = ACE::handle_write_ready (handle, 0); - - // Did select() succeed? - if (result != -1) - { - // Blocking subsided. Continue data transfer. - n = 0; - continue; - } - } - - // Other data transfer or select() failures. - return -1; - } - } - - return ACE_Utils::truncate_cast (bytes_transferred); -} - -ssize_t -ACE::send_n_i (ACE_HANDLE handle, - const void *buf, - size_t len, - const ACE_Time_Value *timeout, - size_t *bt) -{ - size_t temp; - size_t &bytes_transferred = bt == 0 ? temp : *bt; - ssize_t n; - ssize_t result = 0; - int error = 0; - - int val = 0; - ACE::record_and_set_non_blocking_mode (handle, val); - - for (bytes_transferred = 0; - bytes_transferred < len; - bytes_transferred += n) - { - // Try to transfer as much of the remaining data as possible. - // Since the socket is in non-blocking mode, this call will not - // block. - n = ACE::send_i (handle, - (char *) buf + bytes_transferred, - len - bytes_transferred); - - // Check for errors. - if (n == 0 || - n == -1) - { - // Check for possible blocking. - if (n == -1 && - (errno == EWOULDBLOCK || errno == ENOBUFS)) - { - // Wait upto for the blocking to subside. - int const rtn = ACE::handle_write_ready (handle, timeout); - - // Did select() succeed? - if (rtn != -1) - { - // Blocking subsided in period. Continue - // data transfer. - n = 0; - continue; - } - } - - // Wait in select() timed out or other data transfer or - // select() failures. - error = 1; - result = n; - break; - } - } - - ACE::restore_non_blocking_mode (handle, val); - - if (error) - { - return result; - } - else - { - return ACE_Utils::truncate_cast (bytes_transferred); - } -} - -// Send N char *ptrs and int lengths. Note that the char *'s precede -// the ints (basically, an varargs version of writev). The count N is -// the *total* number of trailing arguments, *not* a couple of the -// number of tuple pairs! - -ssize_t -ACE::send (ACE_HANDLE handle, size_t n, ...) -{ - va_list argp; - int total_tuples = static_cast (n / 2); - iovec *iovp; -#if defined (ACE_HAS_ALLOCA) - iovp = (iovec *) alloca (total_tuples * sizeof (iovec)); -#else - ACE_NEW_RETURN (iovp, - iovec[total_tuples], - -1); -#endif /* !defined (ACE_HAS_ALLOCA) */ - - va_start (argp, n); - - for (int i = 0; i < total_tuples; i++) - { - iovp[i].iov_base = va_arg (argp, char *); - iovp[i].iov_len = va_arg (argp, int); - } - - ssize_t result = ACE_OS::sendv (handle, iovp, total_tuples); -#if !defined (ACE_HAS_ALLOCA) - delete [] iovp; -#endif /* !defined (ACE_HAS_ALLOCA) */ - va_end (argp); - return result; -} - -ssize_t -ACE::sendv (ACE_HANDLE handle, - const iovec *iov, - int iovcnt, - const ACE_Time_Value *timeout) -{ - if (timeout == 0) - return ACE_OS::sendv (handle, iov, iovcnt); - else - { - int val = 0; - if (ACE::enter_send_timedwait (handle, timeout, val) == -1) - return -1; - else - { - ssize_t bytes_transferred = ACE_OS::sendv (handle, iov, iovcnt); - ACE::restore_non_blocking_mode (handle, val); - return bytes_transferred; - } - } -} - -ssize_t -ACE::sendv_n_i (ACE_HANDLE handle, - const iovec *i, - int iovcnt, - size_t *bt) -{ - size_t temp; - size_t &bytes_transferred = bt == 0 ? temp : *bt; - bytes_transferred = 0; - - iovec *iov = const_cast (i); - - for (int s = 0; - s < iovcnt; - ) - { - // Try to transfer as much of the remaining data as possible. - ssize_t n = ACE_OS::sendv (handle, iov + s, iovcnt - s); - - // Check EOF. - if (n == 0) - return 0; - - // Check for other errors. - if (n == -1) - { - // Check for possible blocking. - if (errno == EWOULDBLOCK || errno == ENOBUFS) - { - // Wait for the blocking to subside. - int const result = ACE::handle_write_ready (handle, 0); - - // Did select() succeed? - if (result != -1) - { - // Blocking subsided. Continue data transfer. - n = 0; - continue; - } - } - - // Other data transfer or select() failures. - return -1; - } - - for (bytes_transferred += n; - s < iovcnt - && n >= static_cast (iov[s].iov_len); - s++) - n -= iov[s].iov_len; - - if (n != 0) - { - char *base = reinterpret_cast (iov[s].iov_base); - iov[s].iov_base = base + n; - iov[s].iov_len = iov[s].iov_len - n; - } - } - - return ACE_Utils::truncate_cast (bytes_transferred); -} - -ssize_t -ACE::sendv_n_i (ACE_HANDLE handle, - const iovec *i, - int iovcnt, - const ACE_Time_Value *timeout, - size_t *bt) -{ - size_t temp; - size_t &bytes_transferred = bt == 0 ? temp : *bt; - bytes_transferred = 0; - ssize_t result = 0; - int error = 0; - - int val = 0; - ACE::record_and_set_non_blocking_mode (handle, val); - - iovec *iov = const_cast (i); - - for (int s = 0; - s < iovcnt; - ) - { - // Try to transfer as much of the remaining data as possible. - // Since the socket is in non-blocking mode, this call will not - // block. - ssize_t n = ACE_OS::sendv (handle, iov + s, iovcnt - s); - - // Check for errors. - if (n == 0 || - n == -1) - { - // Check for possible blocking. - if (n == -1 && - (errno == EWOULDBLOCK || errno == ENOBUFS)) - { - // Wait upto for the blocking to subside. - int const rtn = ACE::handle_write_ready (handle, timeout); - - // Did select() succeed? - if (rtn != -1) - { - // Blocking subsided in period. Continue - // data transfer. - n = 0; - continue; - } - } - - // Wait in select() timed out or other data transfer or - // select() failures. - error = 1; - result = n; - break; - } - - for (bytes_transferred += n; - s < iovcnt - && n >= static_cast (iov[s].iov_len); - s++) - n -= iov[s].iov_len; - - if (n != 0) - { - char *base = reinterpret_cast (iov[s].iov_base); - iov[s].iov_base = base + n; - iov[s].iov_len = iov[s].iov_len - n; - } - } - - ACE::restore_non_blocking_mode (handle, val); - - if (error) - { - return result; - } - else - { - return ACE_Utils::truncate_cast (bytes_transferred); - } -} - -ssize_t -ACE::write_n (ACE_HANDLE handle, - const ACE_Message_Block *message_block, - size_t *bt) -{ - size_t temp; - size_t &bytes_transferred = bt == 0 ? temp : *bt; - bytes_transferred = 0; - - iovec iov[ACE_IOV_MAX]; - int iovcnt = 0; - - while (message_block != 0) - { - // Our current message block chain. - const ACE_Message_Block *current_message_block = message_block; - - while (current_message_block != 0) - { - size_t current_message_block_length = - current_message_block->length (); - char *this_block_ptr = current_message_block->rd_ptr (); - - // Check if this block has any data to be sent. - while (current_message_block_length > 0) - { - u_long const this_chunk_length = - ACE_Utils::truncate_cast ( - current_message_block_length); - - // Collect the data in the iovec. - iov[iovcnt].iov_base = this_block_ptr; - iov[iovcnt].iov_len = this_chunk_length; - current_message_block_length -= this_chunk_length; - this_block_ptr += this_chunk_length; - - // Increment iovec counter. - ++iovcnt; - - // The buffer is full make a OS call. @@ TODO find a way to - // find ACE_IOV_MAX for platforms that do not define it rather - // than simply setting ACE_IOV_MAX to some arbitrary value such - // as 16. - if (iovcnt == ACE_IOV_MAX) - { - size_t current_transfer = 0; - - ssize_t const result = ACE::writev_n (handle, - iov, - iovcnt, - ¤t_transfer); - - // Add to total bytes transferred. - bytes_transferred += current_transfer; - - // Errors. - if (result == -1 || result == 0) - return result; - - // Reset iovec counter. - iovcnt = 0; - } - } - - // Select the next message block in the chain. - current_message_block = current_message_block->cont (); - } - - // Selection of the next message block chain. - message_block = message_block->next (); - } - - // Check for remaining buffers to be sent. This will happen when - // ACE_IOV_MAX is not a multiple of the number of message blocks. - if (iovcnt != 0) - { - size_t current_transfer = 0; - - ssize_t const result = ACE::writev_n (handle, - iov, - iovcnt, - ¤t_transfer); - - // Add to total bytes transferred. - bytes_transferred += current_transfer; - - // Errors. - if (result == -1 || result == 0) - return result; - } - - // Return total bytes transferred. - return ACE_Utils::truncate_cast (bytes_transferred); -} - -ssize_t -ACE::send_n (ACE_HANDLE handle, - const ACE_Message_Block *message_block, - const ACE_Time_Value *timeout, - size_t *bt) -{ - size_t temp; - size_t &bytes_transferred = bt == 0 ? temp : *bt; - bytes_transferred = 0; - - iovec iov[ACE_IOV_MAX]; - int iovcnt = 0; - - while (message_block != 0) - { - // Our current message block chain. - const ACE_Message_Block *current_message_block = message_block; - - while (current_message_block != 0) - { - char *this_block_ptr = current_message_block->rd_ptr (); - size_t current_message_block_length = - current_message_block->length (); - - // Check if this block has any data to be sent. - while (current_message_block_length > 0) - { - u_long const this_chunk_length = - ACE_Utils::truncate_cast ( - current_message_block_length); - - // Collect the data in the iovec. - iov[iovcnt].iov_base = this_block_ptr; - iov[iovcnt].iov_len = this_chunk_length; - current_message_block_length -= this_chunk_length; - this_block_ptr += this_chunk_length; - - // Increment iovec counter. - ++iovcnt; - - // The buffer is full make a OS call. @@ TODO find a way to - // find ACE_IOV_MAX for platforms that do not define it rather - // than simply setting ACE_IOV_MAX to some arbitrary value such - // as 16. - if (iovcnt == ACE_IOV_MAX) - { - size_t current_transfer = 0; - - ssize_t const result = ACE::sendv_n (handle, - iov, - iovcnt, - timeout, - ¤t_transfer); - - // Add to total bytes transferred. - bytes_transferred += current_transfer; - - // Errors. - if (result == -1 || result == 0) - return result; - - // Reset iovec counter. - iovcnt = 0; - } - } - - // Select the next message block in the chain. - current_message_block = current_message_block->cont (); - } - - // Selection of the next message block chain. - message_block = message_block->next (); - } - - // Check for remaining buffers to be sent. This will happen when - // ACE_IOV_MAX is not a multiple of the number of message blocks. - if (iovcnt != 0) - { - size_t current_transfer = 0; - - ssize_t const result = ACE::sendv_n (handle, - iov, - iovcnt, - timeout, - ¤t_transfer); - - // Add to total bytes transferred. - bytes_transferred += current_transfer; - - // Errors. - if (result == -1 || result == 0) - { - return result; - } - } - - // Return total bytes transferred. - return ACE_Utils::truncate_cast (bytes_transferred); -} - -ssize_t -ACE::readv_n (ACE_HANDLE handle, - iovec *iov, - int iovcnt, - size_t *bt) -{ - size_t temp; - size_t &bytes_transferred = bt == 0 ? temp : *bt; - bytes_transferred = 0; - - for (int s = 0; - s < iovcnt; - ) - { - ssize_t n = ACE_OS::readv (handle, - iov + s, - iovcnt - s); - - if (n == -1 || n == 0) - return n; - - for (bytes_transferred += n; - s < iovcnt - && n >= static_cast (iov[s].iov_len); - s++) - n -= iov[s].iov_len; - - if (n != 0) - { - char *base = reinterpret_cast (iov[s].iov_base); - iov[s].iov_base = base + n; - iov[s].iov_len = iov[s].iov_len - n; - } - } - - return ACE_Utils::truncate_cast (bytes_transferred); -} - -ssize_t -ACE::writev_n (ACE_HANDLE handle, - const iovec *i, - int iovcnt, - size_t *bt) -{ - size_t temp; - size_t &bytes_transferred = bt == 0 ? temp : *bt; - bytes_transferred = 0; - - iovec *iov = const_cast (i); - - for (int s = 0; - s < iovcnt; - ) - { - ssize_t n = ACE_OS::writev (handle, - iov + s, - iovcnt - s); - - if (n == -1 || n == 0) - { - return n; - } - - for (bytes_transferred += n; - s < iovcnt - && n >= static_cast (iov[s].iov_len); - s++) - n -= iov[s].iov_len; - - if (n != 0) - { - char *base = reinterpret_cast (iov[s].iov_base); - iov[s].iov_base = base + n; - iov[s].iov_len = iov[s].iov_len - n; - } - } - - return ACE_Utils::truncate_cast (bytes_transferred); -} - -int -ACE::handle_ready (ACE_HANDLE handle, - const ACE_Time_Value *timeout, - int read_ready, - int write_ready, - int exception_ready) -{ -#if defined (ACE_HAS_POLL) && defined (ACE_HAS_LIMITED_SELECT) - ACE_UNUSED_ARG (write_ready); - ACE_UNUSED_ARG (exception_ready); - - struct pollfd fds; - - fds.fd = handle; - fds.events = read_ready ? POLLIN : POLLOUT; - fds.revents = 0; - - int result = ACE_OS::poll (&fds, 1, timeout); -#else - ACE_Handle_Set handle_set; - handle_set.set_bit (handle); - - // Wait for data or for the timeout to elapse. - int select_width; -# if defined (ACE_WIN32) - // This arg is ignored on Windows and causes pointer truncation - // warnings on 64-bit compiles. - select_width = 0; -# else - select_width = int (handle) + 1; -# endif /* ACE_WIN64 */ - int result = ACE_OS::select (select_width, - read_ready ? handle_set.fdset () : 0, // read_fds. - write_ready ? handle_set.fdset () : 0, // write_fds. - exception_ready ? handle_set.fdset () : 0, // exception_fds. - timeout); - -#endif /* ACE_HAS_POLL && ACE_HAS_LIMITED_SELECT */ - - switch (result) - { - case 0: // Timer expired. - errno = ETIME; - /* FALLTHRU */ - case -1: // we got here directly - select() returned -1. - return -1; - case 1: // Handle has data. - /* FALLTHRU */ - default: // default is case result > 0; return a - // ACE_ASSERT (result == 1); - return result; - } -} - -int -ACE::enter_recv_timedwait (ACE_HANDLE handle, - const ACE_Time_Value *timeout, - int &val) -{ - int result = ACE::handle_read_ready (handle, - timeout); - - if (result == -1) - return -1; - - ACE::record_and_set_non_blocking_mode (handle, - val); - - return result; -} - -int -ACE::enter_send_timedwait (ACE_HANDLE handle, - const ACE_Time_Value *timeout, - int &val) -{ - int result = ACE::handle_write_ready (handle, - timeout); - - if (result == -1) - return -1; - - ACE::record_and_set_non_blocking_mode (handle, - val); - - return result; -} - -void -ACE::record_and_set_non_blocking_mode (ACE_HANDLE handle, - int &val) -{ - // We need to record whether we are already *in* nonblocking mode, - // so that we can correctly reset the state when we're done. - val = ACE::get_flags (handle); - - if (ACE_BIT_DISABLED (val, ACE_NONBLOCK)) - // Set the handle into non-blocking mode if it's not already in - // it. - ACE::set_flags (handle, ACE_NONBLOCK); -} - -void -ACE::restore_non_blocking_mode (ACE_HANDLE handle, - int val) -{ - if (ACE_BIT_DISABLED (val, - ACE_NONBLOCK)) - { - // Save/restore errno. - ACE_Errno_Guard error (errno); - // Only disable ACE_NONBLOCK if we weren't in non-blocking mode - // originally. - ACE::clr_flags (handle, ACE_NONBLOCK); - } -} - - -// Format buffer into printable format. This is useful for debugging. -// Portions taken from mdump by J.P. Knight (J.P.Knight@lut.ac.uk) -// Modifications by Todd Montgomery. - -size_t -ACE::format_hexdump (const char *buffer, - size_t size, - ACE_TCHAR *obuf, - size_t obuf_sz) -{ - ACE_TRACE ("ACE::format_hexdump"); - - u_char c; - ACE_TCHAR textver[16 + 1]; - - // We can fit 16 bytes output in text mode per line, 4 chars per byte. - size_t maxlen = (obuf_sz / 68) * 16; - - if (size > maxlen) - size = maxlen; - - size_t i; - - size_t const lines = size / 16; - for (i = 0; i < lines; i++) - { - size_t j; - - for (j = 0 ; j < 16; j++) - { - c = (u_char) buffer[(i << 4) + j]; // or, buffer[i*16+j] - ACE_OS::sprintf (obuf, - ACE_TEXT ("%02x "), - c); - obuf += 3; - if (j == 7) - { - ACE_OS::sprintf (obuf, - ACE_TEXT (" ")); - ++obuf; - } - textver[j] = ACE_OS::ace_isprint (c) ? c : '.'; - } - - textver[j] = 0; - - ACE_OS::sprintf (obuf, -#if !defined (ACE_WIN32) && defined (ACE_USES_WCHAR) - ACE_TEXT (" %ls\n"), -#else - ACE_TEXT (" %s\n"), -#endif - textver); - - while (*obuf != '\0') - ++obuf; - } - - if (size % 16) - { - for (i = 0 ; i < size % 16; i++) - { - c = (u_char) buffer[size - size % 16 + i]; - ACE_OS::sprintf (obuf, - ACE_TEXT ("%02x "), - c); - obuf += 3; - if (i == 7) - { - ACE_OS::sprintf (obuf, - ACE_TEXT (" ")); - ++obuf; - } - textver[i] = ACE_OS::ace_isprint (c) ? c : '.'; - } - - for (i = size % 16; i < 16; i++) - { - ACE_OS::sprintf (obuf, - ACE_TEXT (" ")); - obuf += 3; - if (i == 7) - { - ACE_OS::sprintf (obuf, - ACE_TEXT (" ")); - ++obuf; - } - textver[i] = ' '; - } - - textver[i] = 0; - ACE_OS::sprintf (obuf, -#if !defined (ACE_WIN32) && defined (ACE_USES_WCHAR) - ACE_TEXT (" %ls\n"), -#else - ACE_TEXT (" %s\n"), -#endif - textver); - } - return size; -} - -// Returns the current timestamp in the form -// "hour:minute:second:microsecond." The month, day, and year are -// also stored in the beginning of the date_and_time array. - -ACE_TCHAR * -ACE::timestamp (ACE_TCHAR date_and_time[], - size_t date_and_timelen, - bool return_pointer_to_first_digit) -{ - return ACE::timestamp (ACE_Time_Value::zero, - date_and_time, - date_and_timelen, - return_pointer_to_first_digit); -} - -// Returns the given timestamp in the form -// "hour:minute:second:microsecond." The month, day, and year are -// also stored in the beginning of the date_and_time array. - -ACE_TCHAR * -ACE::timestamp (const ACE_Time_Value& time_value, - ACE_TCHAR date_and_time[], - size_t date_and_timelen, - bool return_pointer_to_first_digit) -{ - //ACE_TRACE ("ACE::timestamp"); - - if (date_and_timelen < 35) - { - errno = EINVAL; - return 0; - } - -#if defined (WIN32) - if (time_value == ACE_Time_Value::zero) - { - // Emulate Unix. Win32 does NOT support all the UNIX versions - // below, so DO we need this ifdef. - static const ACE_TCHAR *day_of_week_name[] = - { - ACE_TEXT ("Sun"), - ACE_TEXT ("Mon"), - ACE_TEXT ("Tue"), - ACE_TEXT ("Wed"), - ACE_TEXT ("Thu"), - ACE_TEXT ("Fri"), - ACE_TEXT ("Sat") - }; - - static const ACE_TCHAR *month_name[] = - { - ACE_TEXT ("Jan"), - ACE_TEXT ("Feb"), - ACE_TEXT ("Mar"), - ACE_TEXT ("Apr"), - ACE_TEXT ("May"), - ACE_TEXT ("Jun"), - ACE_TEXT ("Jul"), - ACE_TEXT ("Aug"), - ACE_TEXT ("Sep"), - ACE_TEXT ("Oct"), - ACE_TEXT ("Nov"), - ACE_TEXT ("Dec") - }; - - SYSTEMTIME local; - ::GetLocalTime (&local); - - ACE_OS::sprintf (date_and_time, - ACE_TEXT ("%3s %3s %2d %04d %02d:%02d:%02d.%06d"), - day_of_week_name[local.wDayOfWeek], - month_name[local.wMonth - 1], - (int) local.wDay, - (int) local.wYear, - (int) local.wHour, - (int) local.wMinute, - (int) local.wSecond, - (int) (local.wMilliseconds * 1000)); - return &date_and_time[15 + (return_pointer_to_first_digit != 0)]; - } -#endif /* WIN32 */ - ACE_TCHAR timebuf[26]; // This magic number is based on the ctime(3c) man page. - ACE_Time_Value cur_time = - (time_value == ACE_Time_Value::zero) ? - ACE_Time_Value (ACE_OS::gettimeofday ()) : time_value; - time_t secs = cur_time.sec (); - - ACE_OS::ctime_r (&secs, - timebuf, - sizeof timebuf / sizeof (ACE_TCHAR)); - // date_and_timelen > sizeof timebuf! - ACE_OS::strsncpy (date_and_time, - timebuf, - date_and_timelen); - ACE_TCHAR yeartmp[5]; - ACE_OS::strsncpy (yeartmp, - &date_and_time[20], - 5); - ACE_TCHAR timetmp[9]; - ACE_OS::strsncpy (timetmp, - &date_and_time[11], - 9); - ACE_OS::sprintf (&date_and_time[11], -# if defined (ACE_USES_WCHAR) - ACE_TEXT ("%ls %ls.%06ld"), -# else - ACE_TEXT ("%s %s.%06ld"), -# endif /* ACE_USES_WCHAR */ - yeartmp, - timetmp, - cur_time.usec ()); - date_and_time[33] = '\0'; - return &date_and_time[15 + (return_pointer_to_first_digit != 0)]; -} - -// This function rounds the request to a multiple of the page size. - -size_t -ACE::round_to_pagesize (size_t len) -{ - ACE_TRACE ("ACE::round_to_pagesize"); - - if (ACE::pagesize_ == 0) - ACE::pagesize_ = ACE_OS::getpagesize (); - - return (len + (ACE::pagesize_ - 1)) & ~(ACE::pagesize_ - 1); -} - -size_t -ACE::round_to_allocation_granularity (size_t len) -{ - ACE_TRACE ("ACE::round_to_allocation_granularity"); - - if (ACE::allocation_granularity_ == 0) - ACE::allocation_granularity_ = ACE_OS::allocation_granularity (); - - return (len + (ACE::allocation_granularity_ - 1)) & ~(ACE::allocation_granularity_ - 1); -} - -ACE_HANDLE -ACE::handle_timed_complete (ACE_HANDLE h, - const ACE_Time_Value *timeout, - int is_tli) -{ - ACE_TRACE ("ACE::handle_timed_complete"); - -#if !defined (ACE_WIN32) && defined (ACE_HAS_POLL) && defined (ACE_HAS_LIMITED_SELECT) - - struct pollfd fds; - - fds.fd = h; - fds.events = POLLIN | POLLOUT; - fds.revents = 0; - -#else - ACE_Handle_Set rd_handles; - ACE_Handle_Set wr_handles; - rd_handles.set_bit (h); - wr_handles.set_bit (h); -#endif /* !ACE_WIN32 && ACE_HAS_POLL && ACE_HAS_LIMITED_SELECT */ - -#if defined (ACE_WIN32) - // Winsock is different - it sets the exception bit for failed connect, - // unlike other platforms, where the write bit is set for both success - // and fail. - ACE_Handle_Set ex_handles; - ex_handles.set_bit (h); -#endif /* ACE_WIN32 */ - - bool need_to_check = false; - bool known_failure = false; - -#if defined (ACE_WIN32) - int n = ACE_OS::select (0, // Ignored on Windows: int (h) + 1, - 0, - wr_handles, - ex_handles, - timeout); -#else -# if defined (ACE_HAS_POLL) && defined (ACE_HAS_LIMITED_SELECT) - - int n = ACE_OS::poll (&fds, 1, timeout); - -# else - int n = 0; - if (is_tli) - n = ACE_OS::select (int (h) + 1, - rd_handles, - wr_handles, - 0, - timeout); - else - n = ACE_OS::select (int (h) + 1, - 0, - wr_handles, - 0, - timeout); -# endif /* ACE_HAS_POLL && ACE_HAS_LIMITED_SELECT */ -#endif /* ACE_WIN32 */ - - // If we failed to connect within the time period allocated by the - // caller, then we fail (e.g., the remote host might have been too - // busy to accept our call). - if (n <= 0) - { - if (n == 0 && timeout != 0) - errno = ETIME; - return ACE_INVALID_HANDLE; - } - - // On Windows, a ready-for-write handle is successfully connected, and - // ready-for-exception is a failure. On fails, we need to grab the error - // code via getsockopt. - // On BSD sockets using select(), the handle becomes writable on - // completion either success or fail, so if the select() does not time - // out, we need to check for success/fail. - // It is believed that TLI sockets use the readable=fail, writeable=success - // but that hasn't been as well tested. -#if defined (ACE_WIN32) - ACE_UNUSED_ARG (is_tli); - - // On Win32, ex_handle set indicates a failure. We'll do the check - // to try and get an errno value, but the connect failed regardless of - // what getsockopt says about the error. - if (ex_handles.is_set (h)) - { - need_to_check = true; - known_failure = true; - } -#else - if (is_tli) -# if defined (ACE_HAS_POLL) && defined (ACE_HAS_LIMITED_SELECT) - need_to_check = (fds.revents & POLLIN) && !(fds.revents & POLLOUT); -# else - need_to_check = rd_handles.is_set (h) && !wr_handles.is_set (h); -# endif /* ACE_HAS_POLL && ACE_HAS_LIMITED_SELECT */ - - else -# if defined (ACE_HAS_POLL) && defined (ACE_HAS_LIMITED_SELECT) - need_to_check = (fds.revents & POLLIN); -# else - need_to_check = true; -# endif /* ACE_HAS_POLL && ACE_HAS_LIMITED_SELECT */ -#endif /* ACE_WIN32 */ - - if (need_to_check) - { -#if defined (SOL_SOCKET) && defined (SO_ERROR) - int sock_err = 0; - int sock_err_len = sizeof (sock_err); - int sockopt_ret = ACE_OS::getsockopt (h, SOL_SOCKET, SO_ERROR, - (char *)&sock_err, &sock_err_len); - if (sockopt_ret < 0) - { - h = ACE_INVALID_HANDLE; - } - - if (sock_err != 0 || known_failure) - { - h = ACE_INVALID_HANDLE; - errno = sock_err; - } -#else - char dummy; - - // The following recv() won't block provided that the - // ACE_NONBLOCK flag has not been turned off . - n = ACE::recv (h, &dummy, 1, MSG_PEEK); - - // If no data was read/peeked at, check to see if it's because - // of a non-connected socket (and therefore an error) or there's - // just no data yet. - if (n <= 0) - { - if (n == 0) - { - errno = ECONNREFUSED; - h = ACE_INVALID_HANDLE; - } - else if (errno != EWOULDBLOCK && errno != EAGAIN) - h = ACE_INVALID_HANDLE; - } -#endif - } - - // 1. The HANDLE is ready for writing and doesn't need to be checked or - // 2. recv() returned an indication of the state of the socket - if there is - // either data present, or a recv is legit but there's no data yet, - // the connection was successfully established. - return h; -} - -// Wait up to amount of time to accept a connection. - -int -ACE::handle_timed_accept (ACE_HANDLE listener, - ACE_Time_Value *timeout, - bool restart) -{ - ACE_TRACE ("ACE::handle_timed_accept"); - // Make sure we don't bomb out on erroneous values. - if (listener == ACE_INVALID_HANDLE) - return -1; - -#if defined (ACE_HAS_POLL) && defined (ACE_HAS_LIMITED_SELECT) - - struct pollfd fds; - - fds.fd = listener; - fds.events = POLLIN; - fds.revents = 0; - -#else - // Use the select() implementation rather than poll(). - ACE_Handle_Set rd_handle; - rd_handle.set_bit (listener); -#endif /* ACE_HAS_POLL && ACE_HAS_LIMITED_SELECT */ - - // We need a loop here if is enabled. - - for (;;) - { -#if defined (ACE_HAS_POLL) && defined (ACE_HAS_LIMITED_SELECT) - - int n = ACE_OS::poll (&fds, 1, timeout); - -#else - int select_width; -# if defined (ACE_WIN32) - // This arg is ignored on Windows and causes pointer truncation - // warnings on 64-bit compiles. - select_width = 0; -# else - select_width = int (listener) + 1; -# endif /* ACE_WIN32 */ - int n = ACE_OS::select (select_width, - rd_handle, 0, 0, - timeout); -#endif /* ACE_HAS_POLL && ACE_HAS_LIMITED_SELECT */ - - switch (n) - { - case -1: - if (errno == EINTR && restart) - continue; - else - return -1; - /* NOTREACHED */ - case 0: - if (timeout != 0 && *timeout == ACE_Time_Value::zero) - errno = EWOULDBLOCK; - else - errno = ETIMEDOUT; - return -1; - /* NOTREACHED */ - case 1: - return 0; - /* NOTREACHED */ - default: - errno = EINVAL; - return -1; - /* NOTREACHED */ - } - } -} - -// Make the current process a UNIX daemon. This is based on Stevens -// code from APUE. - -int -ACE::daemonize (const ACE_TCHAR pathname[], - bool close_all_handles, - const ACE_TCHAR program_name[]) -{ - ACE_TRACE ("ACE::daemonize"); -#if !defined (ACE_LACKS_FORK) - pid_t pid = ACE_OS::fork (); - - if (pid == -1) - return -1; - else if (pid != 0) - ACE_OS::exit (0); // Parent exits. - - // 1st child continues. - ACE_OS::setsid (); // Become session leader. - - ACE_OS::signal (SIGHUP, SIG_IGN); - - pid = ACE_OS::fork (program_name); - - if (pid != 0) - ACE_OS::exit (0); // First child terminates. - - // Second child continues. - - if (pathname != 0) - // change working directory. - ACE_OS::chdir (pathname); - - ACE_OS::umask (0); // clear our file mode creation mask. - - // Close down the I/O handles. - if (close_all_handles) - { - for (int i = ACE::max_handles () - 1; i >= 0; i--) - ACE_OS::close (i); - - int fd = ACE_OS::open ("/dev/null", O_RDWR, 0); - if (fd != -1) - { - ACE_OS::dup2 (fd, ACE_STDIN); - ACE_OS::dup2 (fd, ACE_STDOUT); - ACE_OS::dup2 (fd, ACE_STDERR); - - if (fd > ACE_STDERR) - ACE_OS::close (fd); - } - } - - return 0; -#else - ACE_UNUSED_ARG (pathname); - ACE_UNUSED_ARG (close_all_handles); - ACE_UNUSED_ARG (program_name); - - ACE_NOTSUP_RETURN (-1); -#endif /* ACE_LACKS_FORK */ -} - -pid_t -ACE::fork (const ACE_TCHAR *program_name, - int avoid_zombies) -{ - if (avoid_zombies == 0) - return ACE_OS::fork (program_name); - else - { - // This algorithm is adapted from an example in the Stevens book - // "Advanced Programming in the Unix Environment" and an item in - // Andrew Gierth's Unix Programming FAQ. It creates an orphan - // process that's inherited by the init process; init cleans up - // when the orphan process terminates. - // - // Another way to avoid zombies is to ignore or catch the - // SIGCHLD signal; we don't use that approach here. - - pid_t pid = ACE_OS::fork (); - if (pid == 0) - { - // The child process forks again to create a grandchild. - switch (ACE_OS::fork (program_name)) - { - case 0: // grandchild returns 0. - return 0; - case -1: // assumes all errnos are < 256 - ACE_OS::_exit (errno); - default: // child terminates, orphaning grandchild - ACE_OS::_exit (0); - } - } - - // Parent process waits for child to terminate. - ACE_exitcode status; - if (pid < 0 || ACE_OS::waitpid (pid, &status, 0) < 0) - return -1; - - // child terminated by calling exit()? - if (WIFEXITED ((status))) - { - // child terminated normally? - if (WEXITSTATUS ((status)) == 0) - return 1; - else - errno = WEXITSTATUS ((status)); - } - else - // child didn't call exit(); perhaps it received a signal? - errno = EINTR; - - return -1; - } -} - -int -ACE::max_handles (void) -{ - ACE_TRACE ("ACE::max_handles"); -#if defined (RLIMIT_NOFILE) && !defined (ACE_LACKS_RLIMIT) - rlimit rl; - int const r = ACE_OS::getrlimit (RLIMIT_NOFILE, &rl); -# if !defined (RLIM_INFINITY) - if (r == 0) - return rl.rlim_cur; -# else - if (r == 0 && rl.rlim_cur != RLIM_INFINITY) - return rl.rlim_cur; - // If == RLIM_INFINITY, fall through to the ACE_LACKS_RLIMIT sections -# endif /* RLIM_INFINITY */ -#endif /* RLIMIT_NOFILE && !ACE_LACKS_RLIMIT */ - -#if defined (_SC_OPEN_MAX) - return ACE_OS::sysconf (_SC_OPEN_MAX); -#elif defined (ACE_VXWORKS) && (ACE_VXWORKS < 0x620) - return maxFiles; -#elif defined (FD_SETSIZE) - return FD_SETSIZE; -#else - ACE_NOTSUP_RETURN (-1); -#endif /* _SC_OPEN_MAX */ -} - -// Set the number of currently open handles in the process. -// -// If NEW_LIMIT == -1 set the limit to the maximum allowable. -// Otherwise, set it to be the value of NEW_LIMIT. - -int -ACE::set_handle_limit (int new_limit, - int increase_limit_only) -{ - ACE_TRACE ("ACE::set_handle_limit"); - int cur_limit = ACE::max_handles (); - int max_limit = cur_limit; - - if (cur_limit == -1) - return -1; - -#if !defined (ACE_LACKS_RLIMIT) && defined (RLIMIT_NOFILE) - struct rlimit rl; - - ACE_OS::memset ((void *) &rl, 0, sizeof rl); - int r = ACE_OS::getrlimit (RLIMIT_NOFILE, &rl); - if (r == 0) - max_limit = rl.rlim_max; -#endif /* ACE_LACKS_RLIMIT */ - - if (new_limit == -1) - new_limit = max_limit; - - if (new_limit < 0) - { - errno = EINVAL; - return -1; - } - else if (new_limit > cur_limit) - { - // Increase the limit. -#if !defined (ACE_LACKS_RLIMIT) && defined (RLIMIT_NOFILE) - rl.rlim_cur = new_limit; - return ACE_OS::setrlimit (RLIMIT_NOFILE, &rl); -#elif defined (ACE_LACKS_RLIMIT_NOFILE) - return 0; -#else - // Must return EINVAL errno. - ACE_NOTSUP_RETURN (-1); -#endif /* ACE_LACKS_RLIMIT */ - } - else if (increase_limit_only == 0) - { - // Decrease the limit. -#if !defined (ACE_LACKS_RLIMIT) && defined (RLIMIT_NOFILE) - rl.rlim_cur = new_limit; - return ACE_OS::setrlimit (RLIMIT_NOFILE, &rl); -#else - // We give a chance to platforms without RLIMIT to work. - // Instead of ACE_NOTSUP_RETURN (0), just return 0 because - // new_limit is <= cur_limit, so it's a no-op. - return 0; -#endif /* ACE_LACKS_RLIMIT */ - } - - return 0; -} - -// Euclid's greatest common divisor algorithm. -u_long -ACE::gcd (u_long x, u_long y) -{ - while (y != 0) - { - u_long r = x % y; - x = y; - y = r; - } - - return x; -} - - -// Calculates the minimum enclosing frame size for the given values. -u_long -ACE::minimum_frame_size (u_long period1, u_long period2) -{ - // if one of the periods is zero, treat it as though it as - // uninitialized and return the other period as the frame size - if (0 == period1) - { - return period2; - } - if (0 == period2) - { - return period1; - } - - // if neither is zero, find the greatest common divisor of the two periods - u_long greatest_common_divisor = ACE::gcd (period1, period2); - - // explicitly consider cases to reduce risk of possible overflow errors - if (greatest_common_divisor == 1) - { - // periods are relative primes: just multiply them together - return period1 * period2; - } - else if (greatest_common_divisor == period1) - { - // the first period divides the second: return the second - return period2; - } - else if (greatest_common_divisor == period2) - { - // the second period divides the first: return the first - return period1; - } - else - { - // the current frame size and the entry's effective period - // have a non-trivial greatest common divisor: return the - // product of factors divided by those in their gcd. - return (period1 * period2) / greatest_common_divisor; - } -} - - -u_long -ACE::is_prime (const u_long n, - const u_long min_factor, - const u_long max_factor) -{ - if (n > 3) - for (u_long factor = min_factor; - factor <= max_factor; - ++factor) - if (n / factor * factor == n) - return factor; - - return 0; -} - -const ACE_TCHAR * -ACE::sock_error (int error) -{ -#if defined (ACE_WIN32) - static ACE_TCHAR unknown_msg[64]; - - switch (error) - { - case WSAVERNOTSUPPORTED: - return ACE_TEXT ("version of WinSock not supported"); - /* NOTREACHED */ - case WSASYSNOTREADY: - return ACE_TEXT ("WinSock not present or not responding"); - /* NOTREACHED */ - case WSAEINVAL: - return ACE_TEXT ("app version not supported by DLL"); - /* NOTREACHED */ - case WSAHOST_NOT_FOUND: - return ACE_TEXT ("Authoritive: Host not found"); - /* NOTREACHED */ - case WSATRY_AGAIN: - return ACE_TEXT ("Non-authoritive: host not found or server failure"); - /* NOTREACHED */ - case WSANO_RECOVERY: - return ACE_TEXT ("Non-recoverable: refused or not implemented"); - /* NOTREACHED */ - case WSANO_DATA: - return ACE_TEXT ("Valid name, no data record for type"); - /* NOTREACHED */ - /* - case WSANO_ADDRESS: - return "Valid name, no MX record"; - */ - case WSANOTINITIALISED: - return ACE_TEXT ("WSA Startup not initialized"); - /* NOTREACHED */ - case WSAENETDOWN: - return ACE_TEXT ("Network subsystem failed"); - /* NOTREACHED */ - case WSAEINPROGRESS: - return ACE_TEXT ("Blocking operation in progress"); - /* NOTREACHED */ - case WSAEINTR: - return ACE_TEXT ("Blocking call cancelled"); - /* NOTREACHED */ - case WSAEAFNOSUPPORT: - return ACE_TEXT ("address family not supported"); - /* NOTREACHED */ - case WSAEMFILE: - return ACE_TEXT ("no file handles available"); - /* NOTREACHED */ - case WSAENOBUFS: - return ACE_TEXT ("no buffer space available"); - /* NOTREACHED */ - case WSAEPROTONOSUPPORT: - return ACE_TEXT ("specified protocol not supported"); - /* NOTREACHED */ - case WSAEPROTOTYPE: - return ACE_TEXT ("protocol wrong type for this socket"); - /* NOTREACHED */ - case WSAESOCKTNOSUPPORT: - return ACE_TEXT ("socket type not supported for address family"); - /* NOTREACHED */ - case WSAENOTSOCK: - return ACE_TEXT ("handle is not a socket"); - /* NOTREACHED */ - case WSAEWOULDBLOCK: - return ACE_TEXT ("resource temporarily unavailable"); - /* NOTREACHED */ - case WSAEADDRINUSE: - return ACE_TEXT ("address already in use"); - /* NOTREACHED */ - case WSAECONNABORTED: - return ACE_TEXT ("connection aborted"); - /* NOTREACHED */ - case WSAECONNRESET: - return ACE_TEXT ("connection reset"); - /* NOTREACHED */ - case WSAENOTCONN: - return ACE_TEXT ("not connected"); - /* NOTREACHED */ - case WSAETIMEDOUT: - return ACE_TEXT ("connection timed out"); - /* NOTREACHED */ - case WSAECONNREFUSED: - return ACE_TEXT ("connection refused"); - /* NOTREACHED */ - case WSAEHOSTDOWN: - return ACE_TEXT ("host down"); - /* NOTREACHED */ - case WSAEHOSTUNREACH: - return ACE_TEXT ("host unreachable"); - /* NOTREACHED */ - case WSAEADDRNOTAVAIL: - return ACE_TEXT ("address not available"); - /* NOTREACHED */ - case WSAEISCONN: - return ACE_TEXT ("socket is already connected"); - /* NOTREACHED */ - case WSAENETRESET: - return ACE_TEXT ("network dropped connection on reset"); - /* NOTREACHED */ - case WSAEMSGSIZE: - return ACE_TEXT ("message too long"); - /* NOTREACHED */ - case WSAENETUNREACH: - return ACE_TEXT ("network is unreachable"); - /* NOTREACHED */ - case WSAEFAULT: - return ACE_TEXT ("bad address"); - /* NOTREACHED */ - case WSAEDISCON: - return ACE_TEXT ("graceful shutdown in progress"); - /* NOTREACHED */ - case WSAEACCES: - return ACE_TEXT ("permission denied"); - /* NOTREACHED */ - case WSAESHUTDOWN: - return ACE_TEXT ("cannot send after socket shutdown"); - /* NOTREACHED */ - case WSAEPROCLIM: - return ACE_TEXT ("too many processes"); - /* NOTREACHED */ - case WSAEALREADY: - return ACE_TEXT ("operation already in progress"); - /* NOTREACHED */ - case WSAEPFNOSUPPORT: - return ACE_TEXT ("protocol family not supported"); - /* NOTREACHED */ - case WSAENOPROTOOPT: - return ACE_TEXT ("bad protocol option"); - /* NOTREACHED */ - case WSATYPE_NOT_FOUND: - return ACE_TEXT ("class type not found"); - /* NOTREACHED */ - case WSAEOPNOTSUPP: - return ACE_TEXT ("operation not supported"); - /* NOTREACHED */ - case WSAEDESTADDRREQ: - return ACE_TEXT ("destination address required"); - /* NOTREACHED */ - default: - ACE_OS::sprintf (unknown_msg, ACE_TEXT ("unknown error: %d"), error); - return unknown_msg; - /* NOTREACHED */ - } -#else - ACE_UNUSED_ARG (error); - ACE_NOTSUP_RETURN (0); -#endif /* ACE_WIN32 */ -} - -bool -ACE::is_sock_error (int error) -{ -#if defined (ACE_WIN32) - switch (error) - { - case WSAVERNOTSUPPORTED: - case WSASYSNOTREADY: - case WSAEINVAL: - case WSAHOST_NOT_FOUND: - case WSATRY_AGAIN: - case WSANO_RECOVERY: - case WSANO_DATA: - /* - case WSANO_ADDRESS: - */ - case WSANOTINITIALISED: - case WSAENETDOWN: - case WSAEINPROGRESS: - case WSAEINTR: - case WSAEAFNOSUPPORT: - case WSAEMFILE: - case WSAENOBUFS: - case WSAEPROTONOSUPPORT: - case WSAEPROTOTYPE: - case WSAESOCKTNOSUPPORT: - case WSAENOTSOCK: - case WSAEWOULDBLOCK: - case WSAEADDRINUSE: - case WSAECONNABORTED: - case WSAECONNRESET: - case WSAENOTCONN: - case WSAETIMEDOUT: - case WSAECONNREFUSED: - case WSAEHOSTDOWN: - case WSAEHOSTUNREACH: - case WSAEADDRNOTAVAIL: - case WSAEISCONN: - case WSAENETRESET: - case WSAEMSGSIZE: - case WSAENETUNREACH: - case WSAEFAULT: - case WSAEDISCON: - case WSAEACCES: - case WSAESHUTDOWN: - case WSAEPROCLIM: - case WSAEALREADY: - case WSAEPFNOSUPPORT: - case WSAENOPROTOOPT: - case WSATYPE_NOT_FOUND: - case WSAEOPNOTSUPP: - return true; - } -#else - ACE_UNUSED_ARG (error); -#endif /* ACE_WIN32 */ - return false; -} - -char * -ACE::strndup (const char *str, size_t n) -{ - const char *t = str; - size_t len; - - // Figure out how long this string is (remember, it might not be - // NUL-terminated). - - for (len = 0; - len < n && *t++ != '\0'; - len++) - continue; - - char *s; - ACE_ALLOCATOR_RETURN (s, - (char *) ACE_OS::malloc (len + 1), - 0); - return ACE_OS::strsncpy (s, str, len + 1); -} - -#if defined (ACE_HAS_WCHAR) -wchar_t * -ACE::strndup (const wchar_t *str, size_t n) -{ - const wchar_t *t = str; - size_t len; - - // Figure out how long this string is (remember, it might not be - // NUL-terminated). - - for (len = 0; - len < n && *t++ != '\0'; - len++) - continue; - - wchar_t *s; - ACE_ALLOCATOR_RETURN (s, - static_cast ( - ACE_OS::malloc ((len + 1) * sizeof (wchar_t))), - 0); - return ACE_OS::strsncpy (s, str, len + 1); -} -#endif /* ACE_HAS_WCHAR */ - -char * -ACE::strnnew (const char *str, size_t n) -{ - const char *t = str; - size_t len; - - // Figure out how long this string is (remember, it might not be - // NUL-terminated). - - for (len = 0; - len < n && *t++ != L'\0'; - len++) - continue; - - char *s; - ACE_NEW_RETURN (s, - char[len + 1], - 0); - return ACE_OS::strsncpy (s, str, len + 1); -} - -#if defined (ACE_HAS_WCHAR) -wchar_t * -ACE::strnnew (const wchar_t *str, size_t n) -{ - const wchar_t *t = str; - size_t len; - - // Figure out how long this string is (remember, it might not be - // NUL-terminated). - - for (len = 0; - len < n && *t++ != ACE_TEXT_WIDE ('\0'); - len++) - continue; - - wchar_t *s; - ACE_NEW_RETURN (s, - wchar_t[len + 1], - 0); - return ACE_OS::strsncpy (s, str, len + 1); -} -#endif /* ACE_HAS_WCHAR */ - -const char * -ACE::strend (const char *s) -{ - while (*s++ != '\0') - continue; - - return s; -} - -#if defined ACE_HAS_WCHAR -const wchar_t * -ACE::strend (const wchar_t *s) -{ - while (*s++ != ACE_TEXT_WIDE ('\0')) - continue; - - return s; -} -#endif - -char * -ACE::strnew (const char *s) -{ - if (s == 0) - return 0; - char *t = 0; - ACE_NEW_RETURN (t, - char [ACE_OS::strlen (s) + 1], - 0); - if (t == 0) - return 0; - else - return ACE_OS::strcpy (t, s); -} - -#if defined (ACE_HAS_WCHAR) -wchar_t * -ACE::strnew (const wchar_t *s) -{ - if (s == 0) - return 0; - wchar_t *t = 0; - ACE_NEW_RETURN (t, - wchar_t[ACE_OS::strlen (s) + 1], - 0); - if (t == 0) - return 0; - else - return ACE_OS::strcpy (t, s); -} -#endif /* ACE_HAS_WCHAR */ - -// helper functions for ACE::wild_match() -namespace -{ - - inline bool equal_char (char a, char b, bool case_sensitive) - { - if (case_sensitive) - return a == b; - return ACE_OS::ace_tolower (a) == ACE_OS::ace_tolower (b); - } - - // precond: *p == '[' start of char class - // postcond: *p == ']' end of the char class - inline bool equal_class (char s, const char *&p, bool case_sensitive) - { - ++p; - bool negate = false; - if (*p == '!') - { - negate = true; - ++p; - } - // ] and - are regular in 1st position - for (bool first = true; *p && (first || *p != ']'); ++p) - { - if (!first && *p == '-' && p[1] != ']') - { - if (!p[1] || p[1] <= p[-1]) // invalid range - { - continue; - } - // Since we are in the POSIX locale, only the basic ASCII - // characters are allowed as the range endpoints. These characters - // are the same values in both signed and unsigned chars so we - // don't have to account for any "pathological cases." - for (char range = p[-1] + 1; range <= p[1]; ++range) - { - if (equal_char (s, range, case_sensitive)) - { - while (*++p != ']') {} - return !negate; - } - } - ++p; // consume the character 1 past the - - } - else if (equal_char (s, *p, case_sensitive)) - { - while (*++p != ']') {} - return !negate; - } - first = false; - } - return negate; - } -} - -bool -ACE::wild_match(const char *str, const char *pat, bool case_sensitive, - bool character_classes) -{ - if (str == pat) - return true; - if (pat == 0 || str == 0) - return false; - - bool star = false, escape = false; - const char *s = str; - const char *p = pat; - while (*s != '\0') - { - if (!escape && *p == '\\') - { - ++p; - escape = true; - } - else if (!escape && *p == '*') - { - star = true; - pat = p; - while (*++pat == '*') {} - - if (*pat == '\0') - return true; - p = pat; - } - else if (!escape && *p == '?') - { - ++s; - ++p; - } - else if (!escape && character_classes && *p == '[') - { - if (equal_class (*s, p, case_sensitive)) - { - ++p; - } - else - { - if (!star) - return false; - p = pat; - } - ++s; - } - else if (!equal_char (*s, *p, case_sensitive)) - { - if (!star) - return false; - ++s; - p = pat; - escape = false; - } - else - { - ++s; - ++p; - escape = false; - } - } - if (*p == '*') - while (*++p == '*') {} - - return *p == '\0'; -} - -// Close versioned namespace, if enabled by the user. -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/ACE.h b/externals/ace/ACE.h deleted file mode 100644 index 56ce13cfd75..00000000000 --- a/externals/ace/ACE.h +++ /dev/null @@ -1,849 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file ACE.h - * - * $Id: ACE.h 88193 2009-12-16 09:14:06Z mcorino $ - * - * This file contains value added ACE functions that extend the - * behavior of the UNIX and Win32 OS calls. - * - * All these ACE static functions are consolidated in a single place - * in order to manage the namespace better. These functions are put - * here rather than in @c ACE_OS in order to separate concerns. - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_ACE_H -#define ACE_ACE_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/OS_NS_math.h" -#include "ace/Flag_Manip.h" -#include "ace/Handle_Ops.h" -#include "ace/Lib_Find.h" -#include "ace/Init_ACE.h" -#include "ace/Sock_Connect.h" -#include "ace/Default_Constants.h" - -#if defined (ACE_EXPORT_MACRO) -# undef ACE_EXPORT_MACRO -#endif -#define ACE_EXPORT_MACRO ACE_Export - -// Open versioned namespace, if enabled by the user. -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Forward declarations. -class ACE_Time_Value; -class ACE_Message_Block; -class ACE_Handle_Set; - -/** - * @namespace ACE - * - * @brief The namespace containing the ACE framework itself. - * - * The ACE namespace contains all types (classes, structures, - * typedefs, etc), and global functions and variables in the ACE - * framework. - */ -namespace ACE -{ - // = ACE version information. - /// e.g., the "5" in ACE 5.1.12. - extern ACE_Export u_int major_version (void); - - /// e.g., the "1" in ACE 5.1.12. - extern ACE_Export u_int minor_version (void); - - /// e.g., the "12" in ACE 5.1.12. - /// Returns 0 for "stable" (non-beta) releases. - extern ACE_Export u_int beta_version (void); - - // = C++ compiler version information. - /// E.g., the "SunPro C++" in SunPro C++ 4.32.0 - extern ACE_Export const ACE_TCHAR * compiler_name (void); - - /// E.g., the "4" in SunPro C++ 4.32.0 - extern ACE_Export u_int compiler_major_version (void); - - /// E.g., the "32" in SunPro C++ 4.32.0 - extern ACE_Export u_int compiler_minor_version (void); - - /// E.g., the "0" in SunPro C++ 4.32.0 - extern ACE_Export u_int compiler_beta_version (void); - - /// Check if error indicates the process being out of handles (file - /// descriptors). - extern ACE_Export int out_of_handles (int error); - - /// Simple wildcard matching function supporting '*' and '?' - /// return true if string s matches pattern. - /// If character_classes is true, '[' is treated as a wildcard character - /// as described in the fnmatch() POSIX API. The following POSIX "bracket - /// expression" features are not implemented: collating symbols, equivalence - /// class expressions, and character class expressions. The POSIX locale is - /// assumed. - extern ACE_Export bool wild_match(const char* s, const char* pattern, - bool case_sensitive = true, bool character_classes = false); - - /** - * @name I/O operations - * - * Notes on common parameters: - * - * @a handle is the connected endpoint that will be used for I/O. - * - * @a buf is the buffer to write from or receive into. - * - * @a len is the number of bytes to transfer. - * - * The @a timeout parameter in the following methods indicates how - * long to blocking trying to transfer data. If @a timeout == 0, - * then the call behaves as a normal send/recv call, i.e., for - * blocking sockets, the call will block until action is possible; - * for non-blocking sockets, @c EWOULDBLOCK will be returned if no - * action is immediately possible. - * - * If @a timeout != 0, the call will wait until the relative time - * specified in @a *timeout elapses. - * - * The "_n()" I/O methods keep looping until all the data has been - * transferred. These methods also work for sockets in non-blocking - * mode i.e., they keep looping on @c EWOULDBLOCK. @a timeout is - * used to make sure we keep making progress, i.e., the same timeout - * value is used for every I/O operation in the loop and the timeout - * is not counted down. - * - * The return values for the "*_n()" methods match the return values - * from the non "_n()" methods and are specified as follows: - * - * - On complete transfer, the number of bytes transferred is returned. - * - On timeout, -1 is returned, @c errno == @c ETIME. - * - On error, -1 is returned, @c errno is set to appropriate error. - * - On @c EOF, 0 is returned, @c errno is irrelevant. - * - * On partial transfers, i.e., if any data is transferred before - * timeout / error / @c EOF, @a bytes_transferred> will contain the - * number of bytes transferred. - * - * Methods with @a iovec parameter are I/O vector variants of the - * I/O operations. - * - * Methods with the extra @a flags argument will always result in - * @c send getting called. Methods without the extra @a flags - * argument will result in @c send getting called on Win32 - * platforms, and @c write getting called on non-Win32 platforms. - */ - //@{ - extern ACE_Export ssize_t recv (ACE_HANDLE handle, - void *buf, - size_t len, - int flags, - const ACE_Time_Value *timeout = 0); - -#if defined (ACE_HAS_TLI) - - extern ACE_Export ssize_t t_rcv (ACE_HANDLE handle, - void *buf, - size_t len, - int *flags, - const ACE_Time_Value *timeout = 0); - -#endif /* ACE_HAS_TLI */ - - extern ACE_Export ssize_t recv (ACE_HANDLE handle, - void *buf, - size_t len, - const ACE_Time_Value *timeout = 0); - - extern ACE_Export ssize_t recvmsg (ACE_HANDLE handle, - struct msghdr *msg, - int flags, - const ACE_Time_Value *timeout = 0); - - extern ACE_Export ssize_t recvfrom (ACE_HANDLE handle, - char *buf, - int len, - int flags, - struct sockaddr *addr, - int *addrlen, - const ACE_Time_Value *timeout = 0); - - ACE_NAMESPACE_INLINE_FUNCTION - ssize_t recv_n (ACE_HANDLE handle, - void *buf, - size_t len, - int flags, - const ACE_Time_Value *timeout = 0, - size_t *bytes_transferred = 0); - -#if defined (ACE_HAS_TLI) - - ACE_NAMESPACE_INLINE_FUNCTION - ssize_t t_rcv_n (ACE_HANDLE handle, - void *buf, - size_t len, - int *flags, - const ACE_Time_Value *timeout = 0, - size_t *bytes_transferred = 0); - -#endif /* ACE_HAS_TLI */ - - ACE_NAMESPACE_INLINE_FUNCTION - ssize_t recv_n (ACE_HANDLE handle, - void *buf, - size_t len, - const ACE_Time_Value *timeout = 0, - size_t *bytes_transferred = 0); - - /// Receive into a variable number of pieces. - /** - * Accepts a variable, caller-specified, number of pointer/length - * pairs. Arguments following @a n are char *, size_t pairs. - * - * @param handle The I/O handle to receive on - * @param n The total number of char *, size_t pairs following @a n. - * - * @return -1 on error, else total number of bytes received. - */ - extern ACE_Export ssize_t recv (ACE_HANDLE handle, size_t n, ...); - - extern ACE_Export ssize_t recvv (ACE_HANDLE handle, - iovec *iov, - int iovcnt, - const ACE_Time_Value *timeout = 0); - - ACE_NAMESPACE_INLINE_FUNCTION - ssize_t recvv_n (ACE_HANDLE handle, - iovec *iov, - int iovcnt, - const ACE_Time_Value *timeout = 0, - size_t *bytes_transferred = 0); - - extern ACE_Export ssize_t recv_n (ACE_HANDLE handle, - ACE_Message_Block *message_block, - const ACE_Time_Value *timeout = 0, - size_t *bytes_transferred = 0); - - extern ACE_Export ssize_t send (ACE_HANDLE handle, - const void *buf, - size_t len, - int flags, - const ACE_Time_Value *timeout = 0); - -#if defined (ACE_HAS_TLI) - - extern ACE_Export ssize_t t_snd (ACE_HANDLE handle, - const void *buf, - size_t len, - int flags, - const ACE_Time_Value *timeout = 0); - -#endif /* ACE_HAS_TLI */ - - extern ACE_Export ssize_t send (ACE_HANDLE handle, - const void *buf, - size_t len, - const ACE_Time_Value *timeout = 0); - - extern ACE_Export ssize_t sendmsg (ACE_HANDLE handle, - const struct msghdr *msg, - int flags, - const ACE_Time_Value *timeout = 0); - - extern ACE_Export ssize_t sendto (ACE_HANDLE handle, - const char *buf, - int len, - int flags, - const struct sockaddr *addr, - int addrlen, - const ACE_Time_Value *timeout = 0); - - ACE_NAMESPACE_INLINE_FUNCTION - ssize_t send_n (ACE_HANDLE handle, - const void *buf, - size_t len, - int flags, - const ACE_Time_Value *timeout = 0, - size_t *bytes_transferred = 0); - -#if defined (ACE_HAS_TLI) - - ACE_NAMESPACE_INLINE_FUNCTION - ssize_t t_snd_n (ACE_HANDLE handle, - const void *buf, - size_t len, - int flags, - const ACE_Time_Value *timeout = 0, - size_t *bytes_transferred = 0); - -#endif /* ACE_HAS_TLI */ - - ACE_NAMESPACE_INLINE_FUNCTION - ssize_t send_n (ACE_HANDLE handle, - const void *buf, - size_t len, - const ACE_Time_Value *timeout = 0, - size_t *bytes_transferred = 0); - - /// Varargs variant. - extern ACE_Export ssize_t send (ACE_HANDLE handle, size_t n, ...); - - extern ACE_Export ssize_t sendv (ACE_HANDLE handle, - const iovec *iov, - int iovcnt, - const ACE_Time_Value *timeout = 0); - - ACE_NAMESPACE_INLINE_FUNCTION - ssize_t sendv_n (ACE_HANDLE handle, - const iovec *iov, - int iovcnt, - const ACE_Time_Value *timeout = 0, - size_t *bytes_transferred = 0); - - /// Send all the @a message_blocks chained through their @c next and - /// @c cont pointers. This call uses the underlying OS gather-write - /// operation to reduce the domain-crossing penalty. - extern ACE_Export ssize_t send_n (ACE_HANDLE handle, - const ACE_Message_Block *message_block, - const ACE_Time_Value *timeout = 0, - size_t *bytes_transferred = 0); - - // = File system I/O functions (these don't support timeouts). - - ACE_NAMESPACE_INLINE_FUNCTION - ssize_t read_n (ACE_HANDLE handle, - void *buf, - size_t len, - size_t *bytes_transferred = 0); - - ACE_NAMESPACE_INLINE_FUNCTION - ssize_t write_n (ACE_HANDLE handle, - const void *buf, - size_t len, - size_t *bytes_transferred = 0); - - /// Write all the @a message_blocks chained through their @c next - /// and @c cont pointers. This call uses the underlying OS - /// gather-write operation to reduce the domain-crossing penalty. - extern ACE_Export ssize_t write_n (ACE_HANDLE handle, - const ACE_Message_Block *message_block, - size_t *bytes_transferred = 0); - - extern ACE_Export ssize_t readv_n (ACE_HANDLE handle, - iovec *iov, - int iovcnt, - size_t *bytes_transferred = 0); - - extern ACE_Export ssize_t writev_n (ACE_HANDLE handle, - const iovec *iov, - int iovcnt, - size_t *bytes_transferred = 0); - //@} - - /** - * Wait up to @a timeout amount of time to passively establish a - * connection. This method doesn't perform the @c accept, it just - * does the timed wait. - */ - extern ACE_Export int handle_timed_accept (ACE_HANDLE listener, - ACE_Time_Value *timeout, - bool restart); - - /** - * Wait up to @a timeout amount of time to complete an actively - * established non-blocking connection. If @a is_tli is non-0 then - * we are being called by a TLI wrapper (which behaves slightly - * differently from a socket wrapper). - */ - extern ACE_Export ACE_HANDLE handle_timed_complete ( - ACE_HANDLE listener, - const ACE_Time_Value *timeout, - int is_tli = 0); - - /** - * Reset the limit on the number of open handles. If @a new_limit - * == -1 set the limit to the maximum allowable. Otherwise, set - * the limit value to @a new_limit. If @a increase_limit_only is - * non-0 then only allow increases to the limit. - */ - extern ACE_Export int set_handle_limit (int new_limit = -1, - int increase_limit_only = 0); - - /** - * Returns the maximum number of open handles currently permitted in - * this process. This maximum may be extended using - * @c ACE::set_handle_limit. - */ - extern ACE_Export int max_handles (void); - - // = String functions - /** - * Return a dynamically allocated duplicate of @a str, substituting - * the environment variable if @c str[0] @c == @c '$'. Note that - * the pointer is allocated with @c ACE_OS::malloc and must be freed - * by @c ACE_OS::free. - */ - extern ACE_Export ACE_TCHAR *strenvdup (const ACE_TCHAR *str); - - /// Returns a pointer to the "end" of the string, i.e., the character - /// past the '\0'. - extern ACE_Export const char *strend (const char *s); - - /// This method is just like @c strdup, except that it uses - /// @c operator @c new rather than @c malloc. If @a s is NULL - /// returns NULL rather than segfaulting. - extern ACE_Export char *strnew (const char *s); - - /// Delete the memory allocated by @c strnew. - ACE_NAMESPACE_INLINE_FUNCTION void strdelete (char *s); - - /// Create a fresh new copy of @a str, up to @a n chars long. Uses - /// @c ACE_OS::malloc to allocate the new string. - extern ACE_Export char *strndup (const char *str, size_t n); - - /// Create a fresh new copy of @a str, up to @a n chars long. Uses - /// @c ACE_OS::malloc to allocate the new string. - extern ACE_Export char *strnnew (const char *str, size_t n); - - /// Determine if a specified pathname is "dot dir" (ie. "." or ".."). - ACE_NAMESPACE_INLINE_FUNCTION bool isdotdir (const char *s); - -#if defined (ACE_HAS_WCHAR) - extern ACE_Export const wchar_t *strend (const wchar_t *s); - - extern ACE_Export wchar_t *strnew (const wchar_t *s); - - ACE_NAMESPACE_INLINE_FUNCTION void strdelete (wchar_t *s); - - extern ACE_Export wchar_t *strndup (const wchar_t *str, size_t n); - - extern ACE_Export wchar_t *strnnew (const wchar_t *str, size_t n); - - ACE_NAMESPACE_INLINE_FUNCTION bool isdotdir (const wchar_t *s); - -#endif /* ACE_HAS_WCHAR */ - - /** - * On Windows, determines if a specified pathname ends with ".exe" - * (not case sensitive). If on Windows and there is no ".exe" suffix, - * a new ACE_TCHAR array is allocated and a copy of @c pathname with - * the ".exe" suffix is copied into it. In this case, the caller is - * responsible for calling delete [] on the returned pointer. - * - * @param pathname The name to check for a proper suffix. - * - * @retval @c pathname if there is a proper suffix for Windows. This is - * always the return value for non-Windows platforms. - * @retval If a suffix needs to be added, returns a pointer to new[] - * allocated memory containing the original @c pathname plus - * a ".exe" suffix. The caller is responsible for freeing the - * memory using delete []. - */ - extern ACE_Export const ACE_TCHAR *execname (const ACE_TCHAR *pathname); - - /** - * Returns the "basename" of a @a pathname separated by @a delim. - * For instance, the basename of "/tmp/foo.cpp" is "foo.cpp" when - * @a delim is @a '/'. - */ - extern ACE_Export const ACE_TCHAR *basename (const ACE_TCHAR *pathname, - ACE_TCHAR delim = - ACE_DIRECTORY_SEPARATOR_CHAR); - - /** - * Returns the "dirname" of a @a pathname. For instance, the - * dirname of "/tmp/foo.cpp" is "/tmp" when @a delim is @a '/'. If - * @a pathname has no @a delim ".\0" is returned. This method does - * not modify @a pathname and is not reentrant. - */ - extern ACE_Export const ACE_TCHAR *dirname (const ACE_TCHAR *pathname, - ACE_TCHAR delim = - ACE_DIRECTORY_SEPARATOR_CHAR); - - /** - * Returns the given timestamp in the form - * "hour:minute:second:microsecond." The month, day, and year are - * also stored in the beginning of the @a date_and_time array, which - * is a user-supplied array of size @a time_len> @c ACE_TCHARs. - * Returns 0 if unsuccessful, else returns pointer to beginning of the - * "time" portion of @a date_and_time. If @a - * return_pointer_to_first_digit is 0 then return a pointer to the - * space before the time, else return a pointer to the beginning of - * the time portion. - */ - extern ACE_Export ACE_TCHAR *timestamp (const ACE_Time_Value& time_value, - ACE_TCHAR date_and_time[], - size_t time_len, - bool return_pointer_to_first_digit = false); - - /** - * Returns the current timestamp in the form - * "hour:minute:second:microsecond." The month, day, and year are - * also stored in the beginning of the @a date_and_time array, which - * is a user-supplied array of size @a time_len> @c ACE_TCHARs. - * Returns 0 if unsuccessful, else returns pointer to beginning of the - * "time" portion of @a date_and_time. If @a - * return_pointer_to_first_digit is 0 then return a pointer to the - * space before the time, else return a pointer to the beginning of - * the time portion. - */ - extern ACE_Export ACE_TCHAR *timestamp (ACE_TCHAR date_and_time[], - size_t time_len, - bool return_pointer_to_first_digit = false); - - /** - * if @a avoid_zombies == 0 call @c ACE_OS::fork directly, else - * create an orphan process that's inherited by the init process; - * init cleans up when the orphan process terminates so we don't - * create zombies. Returns -1 on failure and either the child PID - * on success if @a avoid_zombies == 0 or 1 on success if @a - * avoid_zombies != 0 (this latter behavior is a known bug that - * needs to be fixed). - */ - extern ACE_Export pid_t fork ( - const ACE_TCHAR *program_name = ACE_TEXT (""), - int avoid_zombies = 0); - - /** - * Become a daemon process using the algorithm in Richard Stevens - * "Advanced Programming in the UNIX Environment." If - * @a close_all_handles is non-zero then all open file handles are - * closed. - */ - extern ACE_Export int daemonize ( - const ACE_TCHAR pathname[] = ACE_TEXT ("/"), - bool close_all_handles = ACE_DEFAULT_CLOSE_ALL_HANDLES, - const ACE_TCHAR program_name[] = ACE_TEXT ("")); - - // = Miscellaneous functions. - /// Rounds the request to a multiple of the page size. - extern ACE_Export size_t round_to_pagesize (size_t len); - - /// Rounds the request to a multiple of the allocation granularity. - extern ACE_Export size_t round_to_allocation_granularity (size_t len); - - // @@ UNICODE what about buffer? - /// Format buffer into printable format. This is useful for - /// debugging. - extern ACE_Export size_t format_hexdump (const char *buffer, size_t size, - ACE_TCHAR *obuf, size_t obuf_sz); - - /// Computes the hash value of {str} using the "Hash PJW" routine. - extern ACE_Export u_long hash_pjw (const char *str); - - /// Computes the hash value of {str} using the "Hash PJW" routine. - extern ACE_Export u_long hash_pjw (const char *str, size_t len); - -#if defined (ACE_HAS_WCHAR) - /// Computes the hash value of {str} using the "Hash PJW" routine. - extern ACE_Export u_long hash_pjw (const wchar_t *str); - - /// Computes the hash value of {str} using the "Hash PJW" routine. - extern ACE_Export u_long hash_pjw (const wchar_t *str, size_t len); -#endif /* ACE_HAS_WCHAR */ - - /// Computes CRC-CCITT for the string. - extern ACE_Export ACE_UINT16 crc_ccitt(const char *str); - - /// Computes CRC-CCITT for the buffer. - extern ACE_Export ACE_UINT16 crc_ccitt(const void *buf, size_t len, - ACE_UINT16 crc = 0); - - /// Computes CRC-CCITT for the @ len iovec buffers. - extern ACE_Export ACE_UINT16 crc_ccitt(const iovec *iov, int len, - ACE_UINT16 crc = 0); - - /// Computes the ISO 8802-3 standard 32 bits CRC for the string. - extern ACE_Export ACE_UINT32 crc32 (const char *str); - - /// Computes the ISO 8802-3 standard 32 bits CRC for the buffer. - extern ACE_Export ACE_UINT32 crc32 (const void *buf, size_t len, - ACE_UINT32 crc = 0); - - /// Computes the ISO 8802-3 standard 32 bits CRC for the - /// @ len iovec buffers. - extern ACE_Export ACE_UINT32 crc32 (const iovec *iov, int len, - ACE_UINT32 crc = 0); - - /// Euclid's greatest common divisor algorithm. - extern ACE_Export u_long gcd (u_long x, u_long y); - - /// Calculates the minimum enclosing frame size for the given values. - extern ACE_Export u_long minimum_frame_size (u_long period1, u_long period2); - - /** - * Function that can burn up noticeable CPU time: brute-force - * determination of whether number @a n is prime. Returns 0 if - * it is prime, or the smallest factor if it is not prime. - * @a min_factor and @a max_factor can be used to partition the work - * among threads. For just one thread, typical values are 2 and - * n/2. - */ - extern ACE_Export u_long is_prime (const u_long n, - const u_long min_factor, - const u_long max_factor); - - /// Map troublesome win32 errno values to values that standard C - /// strerr function understands. Thank you Microsoft. - extern ACE_Export int map_errno (int error); - - /// Returns a string containing the error message corresponding to a - /// WinSock error. This works around an omission in the Win32 API. - /// @internal - extern ACE_Export const ACE_TCHAR * sock_error (int error); - - /// Determins whether the given error code corresponds to to a - /// WinSock error. If so returns true, false otherwise. - /// @internal - extern ACE_Export bool is_sock_error (int error); - - /** - * Checks if process with {pid} is still alive. Returns 1 if it is - * still alive, 0 if it isn't alive, and -1 if something weird - * happened. - */ - extern ACE_Export int process_active (pid_t pid); - - /** - * Terminate the process abruptly with id @a pid. On Win32 platforms - * this uses {TerminateProcess} and on POSIX platforms is uses - * {kill} with the -9 (SIGKILL) signal, which cannot be caught or - * ignored. Note that this call is potentially dangerous to use - * since the process being terminated may not have a chance to - * cleanup before it shuts down. - */ - extern ACE_Export int terminate_process (pid_t pid); - - /** - * This method uses process id and object pointer to come up with a - * machine wide unique name. The process ID will provide uniqueness - * between processes on the same machine. The "this" pointer of the - * {object} will provide uniqueness between other "live" objects in - * the same process. The uniqueness of this name is therefore only - * valid for the life of {object}. - */ - ACE_NAMESPACE_INLINE_FUNCTION void unique_name (const void *object, - ACE_TCHAR *name, - size_t length); - - /// Computes the base 2 logarithm of {num}. - ACE_NAMESPACE_INLINE_FUNCTION u_long log2 (u_long num); - - /// Hex conversion utility. - extern ACE_Export ACE_TCHAR nibble2hex (u_int n); - - /// Convert a hex character to its byte representation. - ACE_NAMESPACE_INLINE_FUNCTION u_char hex2byte (ACE_TCHAR c); - - // = Set/get the debug level. - extern ACE_Export bool debug (void); - extern ACE_Export void debug (bool onoff); - - /// Wrapper facade for @c select that uses @c ACE_Handle_Sets. - extern ACE_Export int select (int width, - ACE_Handle_Set *readfds, - ACE_Handle_Set *writefds = 0, - ACE_Handle_Set *exceptfds = 0, - const ACE_Time_Value *timeout = 0); - - /// Wrapper facade for the most common use of @c select that uses - /// @c ACE_Handle_Sets. - extern ACE_Export int select (int width, - ACE_Handle_Set &readfds, - const ACE_Time_Value *timeout = 0); - - /// Timed wait for handle to get read ready. - ACE_NAMESPACE_INLINE_FUNCTION - int handle_read_ready (ACE_HANDLE handle, - const ACE_Time_Value *timeout); - - /// Timed wait for handle to get write ready. - ACE_NAMESPACE_INLINE_FUNCTION - int handle_write_ready (ACE_HANDLE handle, - const ACE_Time_Value *timeout); - - /// Timed wait for handle to get exception ready. - ACE_NAMESPACE_INLINE_FUNCTION - int handle_exception_ready (ACE_HANDLE handle, - const ACE_Time_Value *timeout); - - /// Timed wait for handle to get read, write, or exception ready. - extern ACE_Export int handle_ready (ACE_HANDLE handle, - const ACE_Time_Value *timeout, - int read_ready, - int write_ready, - int exception_ready); - - /// Wait for @a timeout before proceeding to a @c recv operation. - /// @a val keeps track of whether we're in non-blocking mode or - /// not. - extern ACE_Export int enter_recv_timedwait (ACE_HANDLE handle, - const ACE_Time_Value *timeout, - int &val); - - /// Wait for @a timeout before proceeding to a @c send operation. - /// @a val keeps track of whether we're in non-blocking mode or - /// not. - extern ACE_Export int enter_send_timedwait (ACE_HANDLE handle, - const ACE_Time_Value* timeout, - int &val); - - /// This makes sure that @a handle is set into non-blocking mode. - /// @a val keeps track of whether were in non-blocking mode or not. - extern ACE_Export void record_and_set_non_blocking_mode (ACE_HANDLE handle, - int &val); - - /// Cleanup after a timed operation, restore the appropriate - /// non-blocking status of @a handle. - extern ACE_Export void restore_non_blocking_mode (ACE_HANDLE handle, - int val); - - // private: - // These functions aren't meant to be used internally, so they are - // not exported. - - // - // = Recv_n helpers - // - - ACE_NAMESPACE_INLINE_FUNCTION ssize_t recv_i (ACE_HANDLE handle, - void *buf, - size_t len); - - extern ACE_Export ssize_t recv_n_i (ACE_HANDLE handle, - void *buf, - size_t len, - int flags, - size_t *bytes_transferred); - - extern ACE_Export ssize_t recv_n_i (ACE_HANDLE handle, - void *buf, - size_t len, - int flags, - const ACE_Time_Value *timeout, - size_t *bytes_transferred); - -#if defined (ACE_HAS_TLI) - - extern ACE_Export ssize_t t_rcv_n_i (ACE_HANDLE handle, - void *buf, - size_t len, - int *flags, - size_t *bytes_transferred); - - extern ACE_Export ssize_t t_rcv_n_i (ACE_HANDLE handle, - void *buf, - size_t len, - int *flags, - const ACE_Time_Value *timeout, - size_t *bytes_transferred); - -#endif /* ACE_HAS_TLI */ - - extern ACE_Export ssize_t recv_n_i (ACE_HANDLE handle, - void *buf, - size_t len, - size_t *bytes_transferred); - - extern ACE_Export ssize_t recv_n_i (ACE_HANDLE handle, - void *buf, - size_t len, - const ACE_Time_Value *timeout, - size_t *bytes_transferred); - - extern ACE_Export ssize_t recvv_n_i (ACE_HANDLE handle, - iovec *iov, - int iovcnt, - size_t *bytes_transferred); - - extern ACE_Export ssize_t recvv_n_i (ACE_HANDLE handle, - iovec *iov, - int iovcnt, - const ACE_Time_Value *timeout, - size_t *bytes_transferred); - - // - // = Send_n helpers - // - - ACE_NAMESPACE_INLINE_FUNCTION ssize_t send_i (ACE_HANDLE handle, - const void *buf, - size_t len); - - extern ACE_Export ssize_t send_n_i (ACE_HANDLE handle, - const void *buf, - size_t len, - int flags, - size_t *bytes_transferred); - - extern ACE_Export ssize_t send_n_i (ACE_HANDLE handle, - const void *buf, - size_t len, - int flags, - const ACE_Time_Value *timeout, - size_t *bytes_transferred); - -#if defined (ACE_HAS_TLI) - - extern ACE_Export ssize_t t_snd_n_i (ACE_HANDLE handle, - const void *buf, - size_t len, - int flags, - size_t *bytes_transferred); - - extern ACE_Export ssize_t t_snd_n_i (ACE_HANDLE handle, - const void *buf, - size_t len, - int flags, - const ACE_Time_Value *timeout, - size_t *bytes_transferred); - -#endif /* ACE_HAS_TLI */ - - extern ACE_Export ssize_t send_n_i (ACE_HANDLE handle, - const void *buf, - size_t len, - size_t *bytes_transferred); - - extern ACE_Export ssize_t send_n_i (ACE_HANDLE handle, - const void *buf, - size_t len, - const ACE_Time_Value *timeout, - size_t *bytes_transferred); - - extern ACE_Export ssize_t sendv_n_i (ACE_HANDLE handle, - const iovec *iov, - int iovcnt, - size_t *bytes_transferred); - - extern ACE_Export ssize_t sendv_n_i (ACE_HANDLE handle, - const iovec *iov, - int iovcnt, - const ACE_Time_Value *timeout, - size_t *bytes_transferred); - -} - -// Close versioned namespace, if enabled by the user. -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/ACE.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" - -#endif /* ACE_ACE_H */ diff --git a/externals/ace/ACE.inl b/externals/ace/ACE.inl deleted file mode 100644 index 4be80bfb64c..00000000000 --- a/externals/ace/ACE.inl +++ /dev/null @@ -1,348 +0,0 @@ -// -*- C++ -*- -// -// $Id: ACE.inl 87366 2009-11-05 20:16:30Z olli $ - -#include "ace/OS_NS_unistd.h" -#include "ace/OS_NS_Thread.h" -#include "ace/OS_NS_ctype.h" -#include "ace/OS_NS_sys_socket.h" - -// Open versioned namespace, if enabled by the user. -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - - -// Wrappers for methods that have been moved to ACE_OS. - -ACE_INLINE ssize_t -ACE::read_n (ACE_HANDLE handle, - void *buf, - size_t len, - size_t *bytes_transferred) -{ - return ACE_OS::read_n (handle, - buf, - len, - bytes_transferred); -} - -ACE_INLINE ssize_t -ACE::write_n (ACE_HANDLE handle, - const void *buf, - size_t len, - size_t *bytes_transferred) -{ - return ACE_OS::write_n (handle, - buf, - len, - bytes_transferred); -} - -ACE_INLINE ssize_t -ACE::recv_n (ACE_HANDLE handle, - void *buf, - size_t len, - int flags, - const ACE_Time_Value *timeout, - size_t *bytes_transferred) -{ - if (timeout == 0) - return ACE::recv_n_i (handle, - buf, - len, - flags, - bytes_transferred); - else - return ACE::recv_n_i (handle, - buf, - len, - flags, - timeout, - bytes_transferred); -} - -#if defined (ACE_HAS_TLI) - -ACE_INLINE ssize_t -ACE::t_rcv_n (ACE_HANDLE handle, - void *buf, - size_t len, - int *flags, - const ACE_Time_Value *timeout, - size_t *bytes_transferred) -{ - if (timeout == 0) - return ACE::t_rcv_n_i (handle, - buf, - len, - flags, - bytes_transferred); - else - return ACE::t_rcv_n_i (handle, - buf, - len, - flags, - timeout, - bytes_transferred); -} - -#endif /* ACE_HAS_TLI */ - -ACE_INLINE ssize_t -ACE::recv_n (ACE_HANDLE handle, - void *buf, - size_t len, - const ACE_Time_Value *timeout, - size_t *bytes_transferred) -{ - if (timeout == 0) - return ACE::recv_n_i (handle, - buf, - len, - bytes_transferred); - else - return ACE::recv_n_i (handle, - buf, - len, - timeout, - bytes_transferred); -} - -ACE_INLINE ssize_t -ACE::recvv_n (ACE_HANDLE handle, - iovec *iov, - int iovcnt, - const ACE_Time_Value *timeout, - size_t *bytes_transferred) -{ - if (timeout == 0) - return ACE::recvv_n_i (handle, - iov, - iovcnt, - bytes_transferred); - else - return ACE::recvv_n_i (handle, - iov, - iovcnt, - timeout, - bytes_transferred); -} - -ACE_INLINE ssize_t -ACE::send_n (ACE_HANDLE handle, - const void *buf, - size_t len, - int flags, - const ACE_Time_Value *timeout, - size_t *bytes_transferred) -{ - if (timeout == 0) - return ACE::send_n_i (handle, - buf, - len, - flags, - bytes_transferred); - else - return ACE::send_n_i (handle, - buf, - len, - flags, - timeout, - bytes_transferred); -} - -#if defined (ACE_HAS_TLI) - -ACE_INLINE ssize_t -ACE::t_snd_n (ACE_HANDLE handle, - const void *buf, - size_t len, - int flags, - const ACE_Time_Value *timeout, - size_t *bytes_transferred) -{ - if (timeout == 0) - return ACE::t_snd_n_i (handle, - buf, - len, - flags, - bytes_transferred); - else - return ACE::t_snd_n_i (handle, - buf, - len, - flags, - timeout, - bytes_transferred); -} - -#endif /* ACE_HAS_TLI */ - -ACE_INLINE ssize_t -ACE::send_n (ACE_HANDLE handle, - const void *buf, - size_t len, - const ACE_Time_Value *timeout, - size_t *bytes_transferred) -{ - if (timeout == 0) - return ACE::send_n_i (handle, - buf, - len, - bytes_transferred); - else - return ACE::send_n_i (handle, - buf, - len, - timeout, - bytes_transferred); -} - -ACE_INLINE ssize_t -ACE::sendv_n (ACE_HANDLE handle, - const iovec *iov, - int iovcnt, - const ACE_Time_Value *timeout, - size_t *bytes_transferred) -{ - if (timeout == 0) - return ACE::sendv_n_i (handle, - iov, - iovcnt, - bytes_transferred); - else - return ACE::sendv_n_i (handle, - iov, - iovcnt, - timeout, - bytes_transferred); -} - -ACE_INLINE ssize_t -ACE::send_i (ACE_HANDLE handle, const void *buf, size_t len) -{ -#if defined (ACE_WIN32) || defined (HPUX) - return ACE_OS::send (handle, (const char *) buf, len); -#else - return ACE_OS::write (handle, (const char *) buf, len); -#endif /* ACE_WIN32 */ -} - -ACE_INLINE ssize_t -ACE::recv_i (ACE_HANDLE handle, void *buf, size_t len) -{ -#if defined (ACE_WIN32) || defined (ACE_OPENVMS) || defined (ACE_TANDEM_T1248_PTHREADS) - return ACE_OS::recv (handle, (char *) buf, len); -#else - return ACE_OS::read (handle, (char *) buf, len); -#endif /* ACE_WIN32 */ -} - -ACE_INLINE int -ACE::handle_read_ready (ACE_HANDLE handle, - const ACE_Time_Value *timeout) -{ - return ACE::handle_ready (handle, - timeout, - 1, - 0, - 0); -} - -ACE_INLINE int -ACE::handle_write_ready (ACE_HANDLE handle, - const ACE_Time_Value *timeout) -{ - return ACE::handle_ready (handle, - timeout, - 0, - 1, - 0); -} - -ACE_INLINE int -ACE::handle_exception_ready (ACE_HANDLE handle, - const ACE_Time_Value *timeout) -{ - return ACE::handle_ready (handle, - timeout, - 0, - 0, - 1); -} - -ACE_INLINE void -ACE::strdelete (char *s) -{ - delete [] s; -} - -#if defined (ACE_HAS_WCHAR) -ACE_INLINE void -ACE::strdelete (wchar_t *s) -{ - delete [] s; -} -#endif /* ACE_HAS_WCHAR */ - -ACE_INLINE bool -ACE::isdotdir (const char *s) -{ - return (s[0] == '.' && - ((s[1] == 0) || (s[1] == '.' && s[2] == 0))); -} - -#if defined (ACE_HAS_WCHAR) -ACE_INLINE bool -ACE::isdotdir (const wchar_t *s) -{ - return (s[0] == ACE_TEXT ('.') && - ((s[1] == 0) || (s[1] == ACE_TEXT ('.') && s[2] == 0))); -} -#endif /* ACE_HAS_WCHAR */ - -ACE_INLINE void -ACE::unique_name (const void *object, - ACE_TCHAR *name, - size_t length) -{ - ACE_OS::unique_name (object, name, length); -} - -ACE_INLINE u_long -ACE::log2 (u_long num) -{ - u_long log = 0; - - for (; num > 1; ++log) - num >>= 1; - - return log; -} - -ACE_INLINE int -ACE::map_errno (int error) -{ -#if defined (ACE_WIN32) - switch (error) - { - case WSAEWOULDBLOCK: - return EAGAIN; // Same as UNIX errno EWOULDBLOCK. - } -#endif /* ACE_WIN32 */ - - return error; -} - -ACE_INLINE u_char -ACE::hex2byte (ACE_TCHAR c) -{ - if (ACE_OS::ace_isdigit (c)) - return (u_char) (c - ACE_TEXT ('0')); - else if (ACE_OS::ace_islower (c)) - return (u_char) (10 + c - ACE_TEXT ('a')); - else - return (u_char) (10 + c - ACE_TEXT ('A')); -} - -// Close versioned namespace, if enabled by the user. -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/ACE.pc.in b/externals/ace/ACE.pc.in deleted file mode 100644 index 90b2a9eebd7..00000000000 --- a/externals/ace/ACE.pc.in +++ /dev/null @@ -1,10 +0,0 @@ -prefix=@prefix@ -exec_prefix=@exec_prefix@ -libdir=@libdir@ -includedir=@includedir@ - -Name: ACE -Description: ADAPTIVE Communication Environment -Version: @VERSION@ -Libs: -L${libdir} -lACE @LIBS@ -Cflags: -I${includedir} diff --git a/externals/ace/ACE_crc32.cpp b/externals/ace/ACE_crc32.cpp deleted file mode 100644 index 70d93e6b598..00000000000 --- a/externals/ace/ACE_crc32.cpp +++ /dev/null @@ -1,161 +0,0 @@ -// $Id: ACE_crc32.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/ACE.h" - -ACE_RCSID (ace, - ACE_crc32, - "$Id: ACE_crc32.cpp 80826 2008-03-04 14:51:23Z wotte $") - - -namespace -{ - /*****************************************************************/ - /* */ - /* CRC LOOKUP TABLE */ - /* ================ */ - /* The following CRC lookup table was generated automagically */ - /* by the Rocksoft^tm Model CRC Algorithm Table Generation */ - /* Program V1.0 using the following model parameters: */ - /* */ - /* Width : 4 bytes. */ - /* Poly : 0x04C11DB7L */ - /* Reverse : TRUE. */ - /* */ - /* For more information on the Rocksoft^tm Model CRC Algorithm, */ - /* see the document titled "A Painless Guide to CRC Error */ - /* Detection Algorithms" by Ross Williams */ - /* (ross@guest.adelaide.edu.au.). This document is likely to be */ - /* in the FTP archive "ftp.adelaide.edu.au/pub/rocksoft". */ - /* */ - /*****************************************************************/ - - const ACE_UINT32 crc_table[] = - { - 0x00000000L, 0x77073096L, 0xEE0E612CL, 0x990951BAL, - 0x076DC419L, 0x706AF48FL, 0xE963A535L, 0x9E6495A3L, - 0x0EDB8832L, 0x79DCB8A4L, 0xE0D5E91EL, 0x97D2D988L, - 0x09B64C2BL, 0x7EB17CBDL, 0xE7B82D07L, 0x90BF1D91L, - 0x1DB71064L, 0x6AB020F2L, 0xF3B97148L, 0x84BE41DEL, - 0x1ADAD47DL, 0x6DDDE4EBL, 0xF4D4B551L, 0x83D385C7L, - 0x136C9856L, 0x646BA8C0L, 0xFD62F97AL, 0x8A65C9ECL, - 0x14015C4FL, 0x63066CD9L, 0xFA0F3D63L, 0x8D080DF5L, - 0x3B6E20C8L, 0x4C69105EL, 0xD56041E4L, 0xA2677172L, - 0x3C03E4D1L, 0x4B04D447L, 0xD20D85FDL, 0xA50AB56BL, - 0x35B5A8FAL, 0x42B2986CL, 0xDBBBC9D6L, 0xACBCF940L, - 0x32D86CE3L, 0x45DF5C75L, 0xDCD60DCFL, 0xABD13D59L, - 0x26D930ACL, 0x51DE003AL, 0xC8D75180L, 0xBFD06116L, - 0x21B4F4B5L, 0x56B3C423L, 0xCFBA9599L, 0xB8BDA50FL, - 0x2802B89EL, 0x5F058808L, 0xC60CD9B2L, 0xB10BE924L, - 0x2F6F7C87L, 0x58684C11L, 0xC1611DABL, 0xB6662D3DL, - 0x76DC4190L, 0x01DB7106L, 0x98D220BCL, 0xEFD5102AL, - 0x71B18589L, 0x06B6B51FL, 0x9FBFE4A5L, 0xE8B8D433L, - 0x7807C9A2L, 0x0F00F934L, 0x9609A88EL, 0xE10E9818L, - 0x7F6A0DBBL, 0x086D3D2DL, 0x91646C97L, 0xE6635C01L, - 0x6B6B51F4L, 0x1C6C6162L, 0x856530D8L, 0xF262004EL, - 0x6C0695EDL, 0x1B01A57BL, 0x8208F4C1L, 0xF50FC457L, - 0x65B0D9C6L, 0x12B7E950L, 0x8BBEB8EAL, 0xFCB9887CL, - 0x62DD1DDFL, 0x15DA2D49L, 0x8CD37CF3L, 0xFBD44C65L, - 0x4DB26158L, 0x3AB551CEL, 0xA3BC0074L, 0xD4BB30E2L, - 0x4ADFA541L, 0x3DD895D7L, 0xA4D1C46DL, 0xD3D6F4FBL, - 0x4369E96AL, 0x346ED9FCL, 0xAD678846L, 0xDA60B8D0L, - 0x44042D73L, 0x33031DE5L, 0xAA0A4C5FL, 0xDD0D7CC9L, - 0x5005713CL, 0x270241AAL, 0xBE0B1010L, 0xC90C2086L, - 0x5768B525L, 0x206F85B3L, 0xB966D409L, 0xCE61E49FL, - 0x5EDEF90EL, 0x29D9C998L, 0xB0D09822L, 0xC7D7A8B4L, - 0x59B33D17L, 0x2EB40D81L, 0xB7BD5C3BL, 0xC0BA6CADL, - 0xEDB88320L, 0x9ABFB3B6L, 0x03B6E20CL, 0x74B1D29AL, - 0xEAD54739L, 0x9DD277AFL, 0x04DB2615L, 0x73DC1683L, - 0xE3630B12L, 0x94643B84L, 0x0D6D6A3EL, 0x7A6A5AA8L, - 0xE40ECF0BL, 0x9309FF9DL, 0x0A00AE27L, 0x7D079EB1L, - 0xF00F9344L, 0x8708A3D2L, 0x1E01F268L, 0x6906C2FEL, - 0xF762575DL, 0x806567CBL, 0x196C3671L, 0x6E6B06E7L, - 0xFED41B76L, 0x89D32BE0L, 0x10DA7A5AL, 0x67DD4ACCL, - 0xF9B9DF6FL, 0x8EBEEFF9L, 0x17B7BE43L, 0x60B08ED5L, - 0xD6D6A3E8L, 0xA1D1937EL, 0x38D8C2C4L, 0x4FDFF252L, - 0xD1BB67F1L, 0xA6BC5767L, 0x3FB506DDL, 0x48B2364BL, - 0xD80D2BDAL, 0xAF0A1B4CL, 0x36034AF6L, 0x41047A60L, - 0xDF60EFC3L, 0xA867DF55L, 0x316E8EEFL, 0x4669BE79L, - 0xCB61B38CL, 0xBC66831AL, 0x256FD2A0L, 0x5268E236L, - 0xCC0C7795L, 0xBB0B4703L, 0x220216B9L, 0x5505262FL, - 0xC5BA3BBEL, 0xB2BD0B28L, 0x2BB45A92L, 0x5CB36A04L, - 0xC2D7FFA7L, 0xB5D0CF31L, 0x2CD99E8BL, 0x5BDEAE1DL, - 0x9B64C2B0L, 0xEC63F226L, 0x756AA39CL, 0x026D930AL, - 0x9C0906A9L, 0xEB0E363FL, 0x72076785L, 0x05005713L, - 0x95BF4A82L, 0xE2B87A14L, 0x7BB12BAEL, 0x0CB61B38L, - 0x92D28E9BL, 0xE5D5BE0DL, 0x7CDCEFB7L, 0x0BDBDF21L, - 0x86D3D2D4L, 0xF1D4E242L, 0x68DDB3F8L, 0x1FDA836EL, - 0x81BE16CDL, 0xF6B9265BL, 0x6FB077E1L, 0x18B74777L, - 0x88085AE6L, 0xFF0F6A70L, 0x66063BCAL, 0x11010B5CL, - 0x8F659EFFL, 0xF862AE69L, 0x616BFFD3L, 0x166CCF45L, - 0xA00AE278L, 0xD70DD2EEL, 0x4E048354L, 0x3903B3C2L, - 0xA7672661L, 0xD06016F7L, 0x4969474DL, 0x3E6E77DBL, - 0xAED16A4AL, 0xD9D65ADCL, 0x40DF0B66L, 0x37D83BF0L, - 0xA9BCAE53L, 0xDEBB9EC5L, 0x47B2CF7FL, 0x30B5FFE9L, - 0xBDBDF21CL, 0xCABAC28AL, 0x53B39330L, 0x24B4A3A6L, - 0xBAD03605L, 0xCDD70693L, 0x54DE5729L, 0x23D967BFL, - 0xB3667A2EL, 0xC4614AB8L, 0x5D681B02L, 0x2A6F2B94L, - 0xB40BBE37L, 0xC30C8EA1L, 0x5A05DF1BL, 0x2D02EF8DL - }; - - /*****************************************************************/ - /* End of CRC Lookup Table */ - /*****************************************************************/ -} - -#define COMPUTE(var, ch) (var) = (crc_table[(var ^ ch) & 0xFF] ^ (var >> 8)) - -// Open versioned namespace, if enabled by the user. -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_UINT32 -ACE::crc32 (const char *string) -{ - ACE_UINT32 crc = 0xFFFFFFFF; - - for (const char *p = string; - *p != 0; - ++p) - { - COMPUTE (crc, *p); - } - - return ~crc; -} - -ACE_UINT32 -ACE::crc32 (const void *buffer, size_t len, ACE_UINT32 crc) -{ - crc = ~crc; - - for (const char *p = (const char *) buffer, - *e = (const char *) buffer + len; - p != e; - ++p) - { - COMPUTE (crc, *p); - } - - return ~crc; -} - -ACE_UINT32 -ACE::crc32 (const iovec *iov, int len, ACE_UINT32 crc) -{ - crc = ~crc; - - for (int i = 0; i < len; ++i) - { - for (const char *p = (const char *) iov[i].iov_base, - *e = (const char *) iov[i].iov_base + iov[i].iov_len; - p != e; - ++p) - COMPUTE (crc, *p); - } - - return ~crc; -} - -// Close versioned namespace, if enabled by the user. -ACE_END_VERSIONED_NAMESPACE_DECL - -#undef COMPUTE diff --git a/externals/ace/ACE_crc_ccitt.cpp b/externals/ace/ACE_crc_ccitt.cpp deleted file mode 100644 index ef7f5d65bd1..00000000000 --- a/externals/ace/ACE_crc_ccitt.cpp +++ /dev/null @@ -1,128 +0,0 @@ -// $Id: ACE_crc_ccitt.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/ACE.h" - -ACE_RCSID (ace, - ACE_crc_ccitt, - "$Id: ACE_crc_ccitt.cpp 80826 2008-03-04 14:51:23Z wotte $") - -namespace -{ - /*****************************************************************/ - /* */ - /* CRC LOOKUP TABLE */ - /* ================ */ - /* The following CRC lookup table was generated automagically */ - /* by the Rocksoft^tm Model CRC Algorithm Table Generation */ - /* Program V1.0 using the following model parameters: */ - /* */ - /* Width : 2 bytes. */ - /* Poly : 0x1021 */ - /* Reverse : TRUE. */ - /* */ - /* For more information on the Rocksoft^tm Model CRC Algorithm, */ - /* see the document titled "A Painless Guide to CRC Error */ - /* Detection Algorithms" by Ross Williams */ - /* (ross@guest.adelaide.edu.au.). This document is likely to be */ - /* in the FTP archive "ftp.adelaide.edu.au/pub/rocksoft". */ - /* */ - /*****************************************************************/ - - const ACE_UINT16 crc_table[] = - { - 0x0000, 0x1189, 0x2312, 0x329B, 0x4624, 0x57AD, 0x6536, 0x74BF, - 0x8C48, 0x9DC1, 0xAF5A, 0xBED3, 0xCA6C, 0xDBE5, 0xE97E, 0xF8F7, - 0x1081, 0x0108, 0x3393, 0x221A, 0x56A5, 0x472C, 0x75B7, 0x643E, - 0x9CC9, 0x8D40, 0xBFDB, 0xAE52, 0xDAED, 0xCB64, 0xF9FF, 0xE876, - 0x2102, 0x308B, 0x0210, 0x1399, 0x6726, 0x76AF, 0x4434, 0x55BD, - 0xAD4A, 0xBCC3, 0x8E58, 0x9FD1, 0xEB6E, 0xFAE7, 0xC87C, 0xD9F5, - 0x3183, 0x200A, 0x1291, 0x0318, 0x77A7, 0x662E, 0x54B5, 0x453C, - 0xBDCB, 0xAC42, 0x9ED9, 0x8F50, 0xFBEF, 0xEA66, 0xD8FD, 0xC974, - 0x4204, 0x538D, 0x6116, 0x709F, 0x0420, 0x15A9, 0x2732, 0x36BB, - 0xCE4C, 0xDFC5, 0xED5E, 0xFCD7, 0x8868, 0x99E1, 0xAB7A, 0xBAF3, - 0x5285, 0x430C, 0x7197, 0x601E, 0x14A1, 0x0528, 0x37B3, 0x263A, - 0xDECD, 0xCF44, 0xFDDF, 0xEC56, 0x98E9, 0x8960, 0xBBFB, 0xAA72, - 0x6306, 0x728F, 0x4014, 0x519D, 0x2522, 0x34AB, 0x0630, 0x17B9, - 0xEF4E, 0xFEC7, 0xCC5C, 0xDDD5, 0xA96A, 0xB8E3, 0x8A78, 0x9BF1, - 0x7387, 0x620E, 0x5095, 0x411C, 0x35A3, 0x242A, 0x16B1, 0x0738, - 0xFFCF, 0xEE46, 0xDCDD, 0xCD54, 0xB9EB, 0xA862, 0x9AF9, 0x8B70, - 0x8408, 0x9581, 0xA71A, 0xB693, 0xC22C, 0xD3A5, 0xE13E, 0xF0B7, - 0x0840, 0x19C9, 0x2B52, 0x3ADB, 0x4E64, 0x5FED, 0x6D76, 0x7CFF, - 0x9489, 0x8500, 0xB79B, 0xA612, 0xD2AD, 0xC324, 0xF1BF, 0xE036, - 0x18C1, 0x0948, 0x3BD3, 0x2A5A, 0x5EE5, 0x4F6C, 0x7DF7, 0x6C7E, - 0xA50A, 0xB483, 0x8618, 0x9791, 0xE32E, 0xF2A7, 0xC03C, 0xD1B5, - 0x2942, 0x38CB, 0x0A50, 0x1BD9, 0x6F66, 0x7EEF, 0x4C74, 0x5DFD, - 0xB58B, 0xA402, 0x9699, 0x8710, 0xF3AF, 0xE226, 0xD0BD, 0xC134, - 0x39C3, 0x284A, 0x1AD1, 0x0B58, 0x7FE7, 0x6E6E, 0x5CF5, 0x4D7C, - 0xC60C, 0xD785, 0xE51E, 0xF497, 0x8028, 0x91A1, 0xA33A, 0xB2B3, - 0x4A44, 0x5BCD, 0x6956, 0x78DF, 0x0C60, 0x1DE9, 0x2F72, 0x3EFB, - 0xD68D, 0xC704, 0xF59F, 0xE416, 0x90A9, 0x8120, 0xB3BB, 0xA232, - 0x5AC5, 0x4B4C, 0x79D7, 0x685E, 0x1CE1, 0x0D68, 0x3FF3, 0x2E7A, - 0xE70E, 0xF687, 0xC41C, 0xD595, 0xA12A, 0xB0A3, 0x8238, 0x93B1, - 0x6B46, 0x7ACF, 0x4854, 0x59DD, 0x2D62, 0x3CEB, 0x0E70, 0x1FF9, - 0xF78F, 0xE606, 0xD49D, 0xC514, 0xB1AB, 0xA022, 0x92B9, 0x8330, - 0x7BC7, 0x6A4E, 0x58D5, 0x495C, 0x3DE3, 0x2C6A, 0x1EF1, 0x0F78 - }; - - /*****************************************************************/ - /* End of CRC Lookup Table */ - /*****************************************************************/ -} - -#define COMPUTE(var, ch) (var) = (crc_table[(var ^ ch) & 0xFF] ^ (var >> 8)) - -// Open versioned namespace, if enabled by the user. -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_UINT16 -ACE::crc_ccitt (const char *string) -{ - ACE_UINT16 crc = 0xFFFF; - - for (const char *p = string; - *p != 0; - ++p) - { - COMPUTE (crc, *p); - } - - return ~crc; -} - -ACE_UINT16 -ACE::crc_ccitt (const void *buffer, size_t len, ACE_UINT16 crc) -{ - crc = ~crc; - - for (const char *p = (const char *) buffer, - *e = (const char *) buffer + len; - p != e; - ++p) - { - COMPUTE (crc, *p); - } - - return ~crc; -} - -ACE_UINT16 -ACE::crc_ccitt (const iovec *iov, int len, ACE_UINT16 crc) -{ - crc = ~crc; - - for (int i = 0; i < len; ++i) - { - for (const char *p = (const char *) iov[i].iov_base, - *e = (const char *) iov[i].iov_base + iov[i].iov_len; - p != e; - ++p) - COMPUTE (crc, *p); - } - - return ~crc; -} - -// Close versioned namespace, if enabled by the user. -ACE_END_VERSIONED_NAMESPACE_DECL - -#undef COMPUTE diff --git a/externals/ace/ACE_export.h b/externals/ace/ACE_export.h deleted file mode 100644 index 8ad2a33ebaf..00000000000 --- a/externals/ace/ACE_export.h +++ /dev/null @@ -1,76 +0,0 @@ -// -*- C++ -*- -// $Id: ACE_export.h 80826 2008-03-04 14:51:23Z wotte $ -// Definition for Win32 Export directives. -// This file is generated automatically by -// generate_export_file.pl -// ------------------------------ - -#ifndef ACE_EXPORT_H -#define ACE_EXPORT_H - -#include "ace/config-lite.h" - -#if defined (ACE_AS_STATIC_LIBS) - -# if !defined (ACE_HAS_DLL) -# define ACE_HAS_DLL 0 -# endif /* ! ACE_HAS_DLL */ -#else -# if !defined (ACE_HAS_DLL) -# define ACE_HAS_DLL 1 -# endif /* ! ACE_HAS_DLL */ -#endif /* ACE_AS_STATIC_LIB */ - -#if defined (ACE_HAS_DLL) -# if (ACE_HAS_DLL == 1) -# if defined (ACE_BUILD_DLL) -# define ACE_Export ACE_Proper_Export_Flag -# define ACE_SINGLETON_DECLARATION(T) ACE_EXPORT_SINGLETON_DECLARATION (T) -# define ACE_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) -# else -# define ACE_Export ACE_Proper_Import_Flag -# define ACE_SINGLETON_DECLARATION(T) ACE_IMPORT_SINGLETON_DECLARATION (T) -# define ACE_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) -# endif /* ACE_BUILD_DLL */ -# else -# define ACE_Export -# define ACE_SINGLETON_DECLARATION(T) -# define ACE_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) -# endif /* ! ACE_HAS_DLL == 1 */ -#else -# define ACE_Export -# define ACE_SINGLETON_DECLARATION(T) -# define ACE_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) -#endif /* ACE_HAS_DLL */ - -// Added by hand to help with ACE_OS namespace -#if defined (__TANDEM) && defined (USE_EXPLICIT_EXPORT) -#define ACE_NAMESPACE_STORAGE_CLASS ACE_EXPORT_MACRO extern -#else -#define ACE_NAMESPACE_STORAGE_CLASS extern ACE_EXPORT_MACRO -#endif - -#if defined (__ACE_INLINE__) -# if defined (_MSC_VER) || defined (__MINGW32__) || defined (CYGWIN32) || \ - (defined (__SUNPRO_CC) && __SUNPRO_CC >= 0x560) || \ - (defined (__HP_aCC) && (__HP_aCC >= 60500)) || \ - (defined (__sgi) && \ - defined (_COMPILER_VERSION) && _COMPILER_VERSION <= 730) -# define ACE_NAMESPACE_INLINE_FUNCTION inline -# else -# define ACE_NAMESPACE_INLINE_FUNCTION ACE_NAMESPACE_STORAGE_CLASS inline -# endif -# define ACE_INLINE_TEMPLATE_FUNCTION inline -#else -# define ACE_NAMESPACE_INLINE_FUNCTION ACE_NAMESPACE_STORAGE_CLASS -// Microsoft Visual C++ will accept 'extern'; others refuse. -# if defined (_MSC_VER) || defined (__BORLANDC__) -# define ACE_INLINE_TEMPLATE_FUNCTION ACE_Export -# else -# define ACE_INLINE_TEMPLATE_FUNCTION -# endif -#endif - -#endif /* ACE_EXPORT_H */ - -// End of auto generated file. diff --git a/externals/ace/ARGV.cpp b/externals/ace/ARGV.cpp deleted file mode 100644 index edfd4efa790..00000000000 --- a/externals/ace/ARGV.cpp +++ /dev/null @@ -1,383 +0,0 @@ -// $Id: ARGV.cpp 81374 2008-04-16 13:07:47Z iliyan $ - -#ifndef ACE_ARGV_CPP -#define ACE_ARGV_CPP - -#include "ace/Log_Msg.h" -#include "ace/OS_NS_unistd.h" -#include "ace/OS_NS_string.h" -#include "ace/OS_Memory.h" - -#if !defined (__ACE_INLINE__) -#include "ace/ARGV.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID(ace, ARGV, "$Id: ARGV.cpp 81374 2008-04-16 13:07:47Z iliyan $") - -// Open versioned namespace, if enabled by the user. -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE (ACE_ARGV_Queue_Entry) -ACE_ALLOC_HOOK_DEFINE (ACE_ARGV) - -template -void -ACE_ARGV_Queue_Entry_T::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_ARGV_Queue_Entry_T::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("arg_ = %s"), this->arg_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("quote_arg_ = %d"), (int)this->quote_arg_)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -template -void -ACE_ARGV_T::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_ARGV_T::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("argc_ = %d"), this->argc_)); - - ACE_ARGV *this_obj = const_cast (this); - - for (int i = 0; i < this->argc_; i++) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("\nargv_[%i] = %s"), - i, - this_obj->argv ()[i])); - - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nbuf = %s\n"), this->buf_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n"))); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -// Creates this->argv_ out of this->buf_. New memory is allocated for -// each element of the array. This is used by the array-to-string -// style constructor and for creating this->argv_ when in iterative -// mode. - -template -int -ACE_ARGV_T::string_to_argv (void) -{ - ACE_TRACE ("ACE_ARGV_T::string_to_argv"); - - return ACE_OS::string_to_argv (this->buf_, - this->argc_, - this->argv_, - this->substitute_env_args_); -} - -template -ACE_ARGV_T::ACE_ARGV_T (const CHAR_TYPE buf[], - bool substitute_env_args) - : substitute_env_args_ (substitute_env_args), - iterative_ (false), - argc_ (0), - argv_ (0), - buf_ (0), - length_ (0), - queue_ () -{ - ACE_TRACE ("ACE_ARGV_T::ACE_ARGV_T CHAR_TYPE[] to CHAR_TYPE *[]"); - - if (buf == 0 || buf[0] == 0) - return; - - // Make an internal copy of the string. - ACE_NEW (this->buf_, - CHAR_TYPE[ACE_OS::strlen (buf) + 1]); - ACE_OS::strcpy (this->buf_, buf); - - // Create this->argv_. - if (this->string_to_argv () == -1) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("string_to_argv"))); -} - -template -ACE_ARGV_T::ACE_ARGV_T (CHAR_TYPE *argv[], - bool substitute_env_args, - bool quote_arg) - : substitute_env_args_ (substitute_env_args), - iterative_ (false), - argc_ (0), - argv_ (0), - buf_ (0), - length_ (0), - queue_ () -{ - ACE_TRACE ("ACE_ARGV_T::ACE_ARGV_T CHAR_TYPE*[] to CHAR_TYPE[]"); - - if (argv == 0 || argv[0] == 0) - return; - - this->argc_ = ACE_OS::argv_to_string (argv, - this->buf_, - substitute_env_args, - quote_arg); -} - -template -ACE_ARGV_T::ACE_ARGV_T (int argc, - CHAR_TYPE *argv[], - bool substitute_env_args, - bool quote_arg) - : substitute_env_args_ (substitute_env_args), - iterative_ (false), - argc_ (0), - argv_ (0), - buf_ (0), - length_ (0), - queue_ () -{ - ACE_TRACE ("ACE_ARGV_T::ACE_ARGV_T int,CHAR_TYPE*[] to CHAR_TYPE[]"); - - this->argc_ = ACE_OS::argv_to_string (argc, - argv, - this->buf_, - substitute_env_args, - quote_arg); -} - - -template -ACE_ARGV_T::ACE_ARGV_T (CHAR_TYPE *first_argv[], - CHAR_TYPE *second_argv[], - bool substitute_env_args, - bool quote_args) - : substitute_env_args_ (substitute_env_args), - iterative_ (false), - argc_ (0), - argv_ (0), - buf_ (0), - length_ (0), - queue_ () -{ - ACE_TRACE ("ACE_ARGV_T::ACE_ARGV_T CHAR_TYPE*[] + CHAR_TYPE *[] to CHAR_TYPE[]"); - - int first_argc = 0; - int second_argc = 0; - - CHAR_TYPE *first_buf = 0; - CHAR_TYPE *second_buf = 0; - - // convert the first argv to a string - if (first_argv != 0 && first_argv[0] != 0) - { - first_argc = ACE_OS::argv_to_string (first_argv, - first_buf, - substitute_env_args, - quote_args); - } - - // convert the second argv to a string - if (second_argv != 0 && second_argv[0] != 0) - { - second_argc = ACE_OS::argv_to_string (second_argv, - second_buf, - substitute_env_args, - quote_args); - } - - // Add the number of arguments in both the argvs. - this->argc_ = first_argc + second_argc; - - size_t buf_len = - ACE_OS::strlen (first_buf) + ACE_OS::strlen (second_buf) + 1; - - // Allocate memory to the lenght of the combined argv string. - ACE_NEW (this->buf_, - CHAR_TYPE[buf_len + 1]); - - // copy the first argv string to the buffer - ACE_OS::strcpy (this->buf_, first_buf); - - // concatenate the second argv string to the buffer - ACE_OS::strcat (this->buf_, second_buf); - - // Delete the first and second buffers - delete [] first_buf; - delete [] second_buf; -} - -template -ACE_ARGV_T::ACE_ARGV_T (bool substitute_env_args) - : substitute_env_args_ (substitute_env_args), - iterative_ (true), - argc_ (0), - argv_ (0), - buf_ (0), - length_ (0), - queue_ () -{ - ACE_TRACE ("ACE_ARGV_T::ACE_ARGV_T Iterative"); - - // Nothing to do yet -- the user puts in arguments via add () -} - -template -int -ACE_ARGV_T::add (const CHAR_TYPE *next_arg, bool quote_arg) -{ - // Only allow this to work in the "iterative" verion -- the - // ACE_ARGVs created with the one argument constructor. - if (!this->iterative_) - { - errno = EINVAL; - return -1; - } - - this->length_ += ACE_OS::strlen (next_arg); - if (quote_arg && ACE_OS::strchr (next_arg, ' ') != 0) - { - this->length_ += 2; - if (ACE_OS::strchr (next_arg, '"') != 0) - for (const CHAR_TYPE * p = next_arg; *p != '\0'; ++p) - if (*p == '"') ++this->length_; - } - else - { - quote_arg = false; - } - - // Put the new argument at the end of the queue. - if (this->queue_.enqueue_tail (ACE_ARGV_Queue_Entry_T (next_arg, quote_arg)) == -1) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("Can't add more to ARGV queue")), - -1); - - ++this->argc_; - - // Wipe argv_ and buf_ away so that they will be recreated if the - // user calls argv () or buf (). - if (this->argv_ != 0) - { - for (int i = 0; this->argv_[i] != 0; i++) - ACE_OS::free ((void *) this->argv_[i]); - - delete [] this->argv_; - this->argv_ = 0; - } - - delete [] this->buf_; - this->buf_ = 0; - - return 0; -} - -template -int -ACE_ARGV_T::add (CHAR_TYPE *argv[], bool quote_args) -{ - for (int i = 0; argv[i] != 0; i++) - if (this->add (argv[i], quote_args) == -1) - return -1; - - return 0; -} - -// Free up argv_ and buf_ - -template -ACE_ARGV_T::~ACE_ARGV_T (void) -{ - ACE_TRACE ("ACE_ARGV_T::~ACE_ARGV_T"); - - if (this->argv_ != 0) - for (int i = 0; this->argv_[i] != 0; i++) - ACE_OS::free ((void *) this->argv_[i]); - - delete [] this->argv_; - delete [] this->buf_; -} - -// Create buf_ out of the queue_. This is only used in the -// "iterative" mode. - -template -int -ACE_ARGV_T::create_buf_from_queue (void) -{ - ACE_TRACE ("ACE_ARGV_T::create_buf_from_queue"); - - // If the are no arguments, don't do anything - if (this->argc_ <= 0) - return -1; - - delete [] this->buf_; - - ACE_NEW_RETURN (this->buf_, - CHAR_TYPE[this->length_ + this->argc_], - -1); - - // Get an iterator over the queue - ACE_Unbounded_Queue_Iterator > iter (this->queue_); - - ACE_ARGV_Queue_Entry_T *arg = 0; - CHAR_TYPE *ptr = this->buf_; - size_t len; - - while (!iter.done ()) - { - // Get next argument from the queue. - iter.next (arg); - iter.advance (); - - if (arg->quote_arg_) - { - *ptr++ = '"'; - if (ACE_OS::strchr (arg->arg_, '"') != 0) - { - CHAR_TYPE prev = 0; - for (const CHAR_TYPE * p = arg->arg_; *p != '\0'; ++p) - { - if (*p == '"' && prev != '\\') *ptr++ = '\\'; - prev = *ptr++ = *p; - } - } - else - { - len = ACE_OS::strlen (arg->arg_); - // Copy the argument into buf_ - ACE_OS::memcpy ((void *) ptr, - (const void *) (arg->arg_), - len * sizeof (CHAR_TYPE)); - // Move the pointer down. - ptr += len; - } - *ptr++ = '"'; - } - else - { - len = ACE_OS::strlen (arg->arg_); - // Copy the argument into buf_ - ACE_OS::memcpy ((void *) ptr, - (const void *) (arg->arg_), - len * sizeof (CHAR_TYPE)); - // Move the pointer down. - ptr += len; - } - - // Put in an argument separating space. - *ptr++ = ' '; - } - - // Put in the NUL terminator - ptr[-1] = '\0'; - - return 0; -} - -// Close versioned namespace, if enabled by the user. -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_ARGV_CPP */ diff --git a/externals/ace/ARGV.h b/externals/ace/ARGV.h deleted file mode 100644 index 66e71810a95..00000000000 --- a/externals/ace/ARGV.h +++ /dev/null @@ -1,333 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file ARGV.h - * - * $Id: ARGV.h 81156 2008-03-30 20:56:47Z iliyan $ - * - * @author Doug Schmidt - * @author Everett Anderson - */ -//========================================================================== - -#ifndef ACE_ARGUMENT_VECTOR_H -#define ACE_ARGUMENT_VECTOR_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Global_Macros.h" -#include "ace/Unbounded_Queue.h" - -// Open versioned namespace, if enabled by the user. -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_ARGV_Queue_Entry_T - * - * @brief An entry in the queue which keeps user supplied arguments. - */ -template -class ACE_ARGV_Queue_Entry_T -{ -public: - // = Initialization and termination. - /// Initialize a ACE_ARGV_Queue_Entry_T. - ACE_ARGV_Queue_Entry_T (void); - - /** - * Initialize a ACE_ARGV_Queue_Entry_T. - * - * @param arg Pointer to an argument - * - * @param quote_arg The argument @a arg need to be quoted - * while adding to the vector. - */ - ACE_ARGV_Queue_Entry_T (const CHAR_TYPE *arg, - bool quote_arg); - - /** - * Initialize a ACE_ARGV_Queue_Entry_T. - * - * @param entry Pointer to a queue entry - */ - ACE_ARGV_Queue_Entry_T (const ACE_ARGV_Queue_Entry_T &entry); - - /// We need this destructor to keep some compilers from complaining. - /// It's just a no-op, however. - ~ACE_ARGV_Queue_Entry_T (void); - - /// Dump the state of this object. - void dump (void) const; - - // Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - - /// Pointer to the argument. - const CHAR_TYPE * arg_; - - /// The argument need to be quoted while adding to the vector. - bool quote_arg_; -}; - -/** - * @class ACE_ARGV_T - * - * @brief Builds a counted argument vector (ala argc/argv) from either - * a string or a set of separate tokens. This class preserves whitespace - * within tokens only if the whitespace-containing token is enclosed in - * either single (') or double (") quotes. This is consistent with the - * expected behavior if an argument vector obtained using this class is - * passed to, for example, ACE_Get_Opt. - * - * This class can substitute environment variable values for tokens that - * are environment variable references (e.g., @c $VAR). This only works - * if the token is an environment variable reference and nothing else; it - * doesn't substitute environment variable references within a token. - * For example, @c $HOME/file will not substitute the value of the HOME - * environment variable. - */ -template -class ACE_ARGV_T -{ -public: - // = Initialization and termination. - /** - * Splits the specified string into an argument vector. Arguments in the - * string are delimited by whitespace. Whitespace-containing arguments - * must be enclosed in quotes, either single (') or double ("). - * - * @param buf A nul-terminated CHAR_TYPE array to split into arguments - * for the vector. - * - * @param substitute_env_args If non-zero, any token that is an - * environment variable reference (e.g., @c $VAR) will have - * its environment variable value in the resultant vector - * in place of the environment variable name. - */ - explicit ACE_ARGV_T (const CHAR_TYPE buf[], - bool substitute_env_args = true); - - /** - * Initializes the argument vector from a set of arguments. Any environment - * variable references are translated (if applicable) during execution of - * this method. In contrast with ACE_ARGV_T(CHAR_TYPE *[], bool, bool), this - * ctor does not require argv to be 0-terminated as the number of arguments - * is provided explicitely. - * - * @param argc The number of arguments in the argv array. - * - * @param argv An array of tokens to initialize the object with. All needed - * data is copied from @a argv during this call; the pointers - * in @a argv are not needed after this call, and the memory - * referred to by @a argv is not referenced by this object. - * - * @param substitute_env_args If non-zero, any element of @a argv that is - * an environment variable reference (e.g., @c $VAR) will have - * its environment variable value in the resultant vector - * in place of the environment variable name. - * - * @param quote_args If non-zero each argument @a argv[i] needs to - * be enclosed in double quotes ('"'). - */ - explicit ACE_ARGV_T (int argc, - CHAR_TYPE *argv[], - bool substitute_env_args = true, - bool quote_args = false); - - /** - * Initializes the argument vector from a set of arguments. Any environment - * variable references are translated (if applicable) during execution of - * this method. - * - * @param argv An array of tokens to initialize the object with. The - * array must be terminated with a 0 pointer. All needed - * data is copied from @a argv during this call; the pointers - * in @a argv are not needed after this call, and the memory - * referred to by @a argv is not referenced by this object. - * - * @param substitute_env_args If non-zero, any element of @a argv that is - * an environment variable reference (e.g., @c $VAR) will have - * its environment variable value in the resultant vector - * in place of the environment variable name. - * - * @param quote_args If non-zero each argument @a argv[i] needs to - * be enclosed in double quotes ('"'). - */ - explicit ACE_ARGV_T (CHAR_TYPE *argv[], - bool substitute_env_args = true, - bool quote_args = false); - - /** - * Initializes the argument vector from two combined argument vectors. - * - * @param first_argv An array of tokens to initialize the object with. - * The array must be terminated with a 0 pointer. - * @param second_argv An array of tokens that is concatenated with the - * the tokens in @a first_argv. The array must be - * terminated with a 0 pointer. - * @param substitute_env_args If non-zero, any element of @a first_argv - * or @a second_argv that is an environment variable - * reference (e.g., @c $VAR) will have its environment - * variable value in the resultant vector in place - * of the environment variable name. - * - * @param quote_args If non-zero each arguments @a first_argv[i] and - * @a second_argv[i] needs to be enclosed - * in double quotes ('"'). - */ - ACE_ARGV_T (CHAR_TYPE *first_argv[], - CHAR_TYPE *second_argv[], - bool substitute_env_args = true, - bool quote_args = false); - - /** - * Initialize this object so arguments can be added later using one - * of the add methods. This is referred to as the @i iterative method - * of adding arguments to this object. - */ - explicit ACE_ARGV_T (bool substitute_env_args = true); - - /// Destructor. - ~ACE_ARGV_T (void); - - /** @name Accessor methods - * - * These methods access the argument vector contained in this object. - */ - //@{ - /** - * Returns the specified element of the current argument vector. - * - * @param index Index to the desired element. - * - * @retval Pointer to the indexed string. - * @retval 0 if @a index is out of bounds. - */ - const CHAR_TYPE *operator[] (size_t index); - - /** - * Returns the current argument vector. The returned pointers are to data - * maintained internally to this class. Do not change or delete either the - * pointers or the memory to which they refer. - */ - CHAR_TYPE **argv (void); - - /// Returns the current number of arguments. - int argc (void) const; - - /** - * Returns a single string form of the current arguments. The returned - * pointer refers to memory maintained internally to this class. Do not - * change or delete it. - */ - const CHAR_TYPE *buf (void); - - //@} - - /// Dump the state of this object. - void dump (void) const; - - // Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - - /** - * Add another argument. This only works in the iterative mode. - * - * @note This method copies the specified pointer, but not the data - * contained in the referenced memory. Thus, if the content of - * the memory referred to by @a next_arg are changed after this - * method returns, the results are undefined. - * - * @param next_arg Pointer to the next argument to add to the vector. - * - * @param quote_arg The argument @a next_arg need to be quoted while - * adding to the vector. - * - * @retval 0 on success; -1 on failure. Most likely @c errno values are: - * - EINVAL: This object is not in iterative mode. - * - ENOMEM: Not enough memory available to save @a next_arg. - */ - int add (const CHAR_TYPE *next_arg, bool quote_arg = false); - - /** - * Add an array of arguments. This only works in the iterative mode. - * - * @note This method copies the specified pointers, but not the data - * contained in the referenced memory. Thus, if the content of - * the memory referred to by any of the @a argv elements is - * changed after this method returns, the results are undefined. - * - * @param argv Pointers to the arguments to add to the vector. - * @a argv must be terminated by a 0 pointer. - * - * @param quote_args If non-zero each argument @a argv[i] needs to - * be enclosed in double quotes ('"'). - * - * @retval 0 on success; -1 on failure. Most likely @c errno values are: - * - EINVAL: This object is not in iterative mode. - * - ENOMEM: Not enough memory available to save @a next_arg. - */ - int add (CHAR_TYPE *argv[], bool quote_args = false); - -private: - /// Copy constructor not implemented. - ACE_UNIMPLEMENTED_FUNC (ACE_ARGV_T (const ACE_ARGV_T&)) - - /// Assignment operator not implemented. - ACE_UNIMPLEMENTED_FUNC (ACE_ARGV_T operator= (const ACE_ARGV_T&)) - - /// Creates buf_ from the queue of added args, deletes previous buf_. - int create_buf_from_queue (void); - - /// Converts buf_ into the CHAR_TYPE *argv[] format. - int string_to_argv (void); - - /// Replace args with environment variable values? - bool substitute_env_args_; - - bool iterative_; - - /// Number of arguments in the ARGV array. - int argc_; - - /// The array of string arguments. - CHAR_TYPE **argv_; - - /// Buffer containing the contents. - CHAR_TYPE *buf_; - - /// Total length of the arguments in the queue, not counting - /// separating spaces - size_t length_; - - /// Queue which keeps user supplied arguments. This is only - /// active in the "iterative" mode. - ACE_Unbounded_Queue > queue_; -}; - -typedef ACE_ARGV_Queue_Entry_T ACE_ARGV_Queue_Entry; -typedef ACE_ARGV_T ACE_ARGV; - -// Close versioned namespace, if enabled by the user. -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/ARGV.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/ARGV.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("ARGV.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" -#endif /* ACE_ARGUMENT_VECTOR_H */ diff --git a/externals/ace/ARGV.inl b/externals/ace/ARGV.inl deleted file mode 100644 index fdc5b13d7c3..00000000000 --- a/externals/ace/ARGV.inl +++ /dev/null @@ -1,104 +0,0 @@ -/* -*- C++ -*- */ -// $Id: ARGV.inl 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Global_Macros.h" - -// Open versioned namespace, if enabled by the user. -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template ACE_INLINE -ACE_ARGV_Queue_Entry_T::ACE_ARGV_Queue_Entry_T (void) - : arg_(0), - quote_arg_(false) -{ - // No-op -} - -template ACE_INLINE -ACE_ARGV_Queue_Entry_T::ACE_ARGV_Queue_Entry_T (const CHAR_TYPE *arg, - bool quote_arg) - : arg_(arg), - quote_arg_(quote_arg) -{ - // No-op -} - -template ACE_INLINE -ACE_ARGV_Queue_Entry_T::ACE_ARGV_Queue_Entry_T (const ACE_ARGV_Queue_Entry_T &entry) - : arg_(entry.arg_), - quote_arg_(entry.quote_arg_) -{ - // No-op -} - -template ACE_INLINE -ACE_ARGV_Queue_Entry_T::~ACE_ARGV_Queue_Entry_T (void) -{ - // No-op just to keep some compilers happy... -} - -// Return the number of args -template -ACE_INLINE int -ACE_ARGV_T::argc (void) const -{ - ACE_TRACE ("ACE_ARGV_T::argc"); - // Try to create the argv_ if it isn't there - ACE_ARGV_T *nonconst_this = - const_cast *> (this); - (void) nonconst_this->argv (); - return this->argc_; -} - -// Return the arguments in a space-separated string -template -ACE_INLINE const CHAR_TYPE * -ACE_ARGV_T::buf (void) -{ - ACE_TRACE ("ACE_ARGV_T::buf"); - - if (this->buf_ == 0 && this->iterative_) - this->create_buf_from_queue (); - - return (const CHAR_TYPE *) this->buf_; -} - -// Return the arguments in an entry-per-argument array - -template -ACE_INLINE CHAR_TYPE ** -ACE_ARGV_T::argv (void) -{ - ACE_TRACE ("ACE_ARGV_T::argv"); - - // Try to create the argv_ if it isn't there - if (this->argv_ == 0) - { - if (this->iterative_ && this->buf_ == 0) - this->create_buf_from_queue (); - - // Convert buf_ to argv_ - if (this->string_to_argv () == -1) - return (CHAR_TYPE **) 0; - } - - return (CHAR_TYPE **) this->argv_; -} - -// Subscript operator. - -template -ACE_INLINE const CHAR_TYPE * -ACE_ARGV_T::operator[] (size_t i) -{ - ACE_TRACE ("ACE_ARGV_T::operator[]"); - - // Don't go out of bounds. - if (i >= static_cast (this->argc_)) - return 0; - - return (const CHAR_TYPE *) this->argv ()[i]; -} - -// Close versioned namespace, if enabled by the user. -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/ATM_Acceptor.cpp b/externals/ace/ATM_Acceptor.cpp deleted file mode 100644 index 7e835658f01..00000000000 --- a/externals/ace/ATM_Acceptor.cpp +++ /dev/null @@ -1,309 +0,0 @@ -// $Id: ATM_Acceptor.cpp 84262 2009-01-29 10:34:33Z johnnyw $ - -#include "ace/ATM_Acceptor.h" - -ACE_RCSID(ace, ATM_Acceptor, "$Id: ATM_Acceptor.cpp 84262 2009-01-29 10:34:33Z johnnyw $") - -#if defined (ACE_HAS_ATM) - -#if defined (ACE_HAS_LINUX_ATM) -#include /**/ "linux/atmdev.h" -#endif /* ACE_HAS_LINUX_ATM */ - -#if !defined (__ACE_INLINE__) -#include "ace/ATM_Acceptor.inl" -#endif /* __ACE_INLINE__ */ - - -// Open versioned namespace, if enabled by the user. -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Put the actual definitions of the ACE_ATM_Request and -// ACE_ATM_Request_Queue classes here to hide them from clients... - -ACE_ALLOC_HOOK_DEFINE(ACE_ATM_Acceptor) - -ACE_ATM_Acceptor::ACE_ATM_Acceptor (void) -{ - ACE_TRACE ("ACE_ATM_Acceptor::ACE_ATM_Acceptor"); -} - -ACE_ATM_Acceptor::~ACE_ATM_Acceptor (void) -{ - ACE_TRACE ("ACE_ATM_Acceptor::~ACE_ATM_Acceptor"); -} - -int -ACE_ATM_Acceptor::get_local_addr (ACE_ATM_Addr &local_addr) -{ - ACE_TRACE ("ACE_ATM_Acceptor::get_local_addr"); - -#if defined (ACE_HAS_FORE_ATM_WS2) - unsigned long ret = 0; - DWORD deviceID = 0; - ATM_ADDRESS addr; - struct sockaddr_atm *laddr; - - if (::WSAIoctl ((int) ((ACE_SOCK_Acceptor *)this) -> get_handle (), - SIO_GET_ATM_ADDRESS, - (LPVOID) &deviceID, - sizeof (DWORD), - (LPVOID)&addr, - sizeof (ATM_ADDRESS), - &ret, - 0, - 0) == SOCKET_ERROR) { - ACE_OS::printf ("ATM_Acceptor (get_local_addr): WSIoctl: %d\n", - ::WSAGetLastError ()); - return -1; - } - - laddr = (struct sockaddr_atm *)local_addr.get_addr (); - ACE_OS::memcpy ((void *)& (laddr -> satm_number), - (void *)&addr, - ATM_ADDR_SIZE - 1); - - return 0; -#elif defined (ACE_HAS_FORE_ATM_XTI) - ACE_UNUSED_ARG (local_addr); - - return 0; -#elif defined (ACE_HAS_LINUX_ATM) - ATM_Addr *myaddr = (ATM_Addr *)local_addr.get_addr (); - int addrlen = sizeof (myaddr->sockaddratmsvc); - - if (ACE_OS::getsockname (acceptor_.get_handle (), - (struct sockaddr *) & (myaddr->sockaddratmsvc), - &addrlen) < 0) { - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ATM_Acceptor (get_local_addr): ioctl: %d\n"), - errno)); - return -1; - } - - return 0; -#else - ACE_UNUSED_ARG (local_addr); - - return 0; -#endif /* ACE_HAS_FORE_ATM_WS2 && ACE_HAS_FORE_ATM_XTI */ -} - -ACE_HANDLE -ACE_ATM_Acceptor::open (const ACE_Addr &remote_sap, - int backlog, - ACE_ATM_Params params) -{ - ACE_TRACE ("ACE_ATM_Acceptor::open"); -#if defined (ACE_HAS_FORE_ATM_XTI) - ACE_HANDLE handle = acceptor_.open (remote_sap, - params.get_reuse_addr (), - params.get_oflag (), - params.get_info (), - backlog, - params.get_device ()); - return (handle == ACE_INVALID_HANDLE ? -1 : 0); -#elif defined (ACE_HAS_FORE_ATM_WS2) - struct sockaddr_atm local_atm_addr; - ACE_HANDLE ret; - DWORD flags = 0; - - /* Create a local endpoint of communication */ - - // Only leaves can listen. - flags = ACE_FLAG_MULTIPOINT_C_LEAF | ACE_FLAG_MULTIPOINT_D_LEAF; - - if ((ret = ACE_OS::socket (AF_ATM, - SOCK_RAW, - ATMPROTO_AAL5, - 0, - 0, - flags)) - == ACE_INVALID_HANDLE) { - ACE_OS::printf ("Acceptor (open): socket %d\n", - ::WSAGetLastError ()); - return (ret); - } - - ((ACE_SOCK_Acceptor *)this) -> set_handle (ret); - - /* Set up the address information to become a server */ - ACE_OS::memset ((void *) &local_atm_addr, 0, sizeof local_atm_addr); - local_atm_addr.satm_family = AF_ATM; - local_atm_addr.satm_number.AddressType = SAP_FIELD_ANY_AESA_REST; - local_atm_addr.satm_number.Addr[ ATM_ADDR_SIZE - 1 ] - = ((ACE_ATM_Addr *)&remote_sap) -> get_selector (); - local_atm_addr.satm_blli.Layer2Protocol = SAP_FIELD_ANY; - local_atm_addr.satm_blli.Layer3Protocol = SAP_FIELD_ABSENT; - local_atm_addr.satm_bhli.HighLayerInfoType = SAP_FIELD_ABSENT; - - /* Associate address with endpoint */ - if (ACE_OS::bind (((ACE_SOCK_Acceptor *)this) -> get_handle (), - reinterpret_cast (&local_atm_addr), - sizeof local_atm_addr) == -1) { - ACE_OS::printf ("Acceptor (open): bind %d\n", ::WSAGetLastError ()); - return (ACE_INVALID_HANDLE); - } - - /* Make endpoint listen for service requests */ - if (ACE_OS::listen (( (ACE_SOCK_Acceptor *)this) -> get_handle (), - backlog) - == -1) { - ACE_OS::printf ("Acceptor (open): listen %d\n", ::WSAGetLastError ()); - return (ACE_INVALID_HANDLE); - } - - return 0; -#elif defined (ACE_HAS_LINUX_ATM) - //we need to set the qos before binding to the socket - //use remote_sap as local_sap - - ACE_ATM_Addr local_sap; - ATM_Addr *local_sap_addr = (ATM_Addr*)local_sap.get_addr (); - ACE_ATM_QoS def_qos; - ATM_QoS qos = def_qos.get_qos (); - - ACE_HANDLE handle; - if ((handle = ACE_OS::socket (params.get_protocol_family (), - params.get_type (), - params.get_protocol (), - params.get_protocol_info (), - params.get_sock_group (), - params.get_flags () - )) - == ACE_INVALID_HANDLE) { - ACE_DEBUG (LM_DEBUG, - ACE_TEXT ("Acceptor (socket): socket %d\n"), - errno); - return (ACE_INVALID_HANDLE); - } - - ((ACE_SOCK_Acceptor *)this) -> set_handle (handle); - if (ACE_OS::setsockopt (handle, - SOL_ATM, - SO_ATMQOS, - reinterpret_cast (&qos), - sizeof (qos)) < 0) { - ACE_OS::printf ("Acceptor (setsockopt): setsockopt:%d\n", - errno); - } - - struct atmif_sioc req; - struct sockaddr_atmsvc aux_addr[1024]; - - req.number = 0; - req.arg = aux_addr; - req.length = sizeof (aux_addr); - if (ACE_OS::ioctl (handle, - ATM_GETADDR, - &req) < 0) { - ACE_OS::perror ("Acceptor (setsockopt): ioctl:"); - } - else { - local_sap_addr->sockaddratmsvc = aux_addr[0]; - } - local_sap.set_selector (( (ACE_ATM_Addr*)&remote_sap)->get_selector ()); - - if (ACE_OS::bind (handle, - reinterpret_cast ( - &(local_sap_addr->sockaddratmsvc)), - sizeof (local_sap_addr->sockaddratmsvc) - ) == -1) { - ACE_DEBUG (LM_DEBUG, - ACE_TEXT ("Acceptor (open): bind %d\n"), - errno); - return -1; - } - // Make endpoint listen for service requests - if (ACE_OS::listen (handle, - backlog) - == -1) { - ACE_DEBUG (LM_DEBUG, - ACE_TEXT ("Acceptor (listen): listen %d\n"), - errno); - return -1; - } - - return 0; -#else - ACE_UNUSED_ARG (remote_sap); - ACE_UNUSED_ARG (backlog); - ACE_UNUSED_ARG (params); -#endif /* ACE_HAS_FORE_ATM_XTI/ACE_HAS_FORE_ATM_WS2/ACE_HAS_LINUX_ATM */ -} - -int -ACE_ATM_Acceptor::accept (ACE_ATM_Stream &new_sap, - ACE_Addr *remote_addr, - ACE_Time_Value *timeout, - bool restart, - bool reset_new_handle, - ACE_ATM_Params params, - ACE_ATM_QoS qos) -{ - ACE_TRACE ("ACE_ATM_Acceptor::accept"); -#if defined (ACE_HAS_FORE_ATM_XTI) - ATM_QoS optbuf = qos.get_qos (); - - return (acceptor_.accept (new_sap.get_stream (), - remote_addr, - timeout, - restart, - reset_new_handle, - params.get_rw_flag (), - params.get_user_data (), - &optbuf)); -#elif defined (ACE_HAS_FORE_ATM_WS2) - ACE_HANDLE n_handle; - ACE_HANDLE s_handle = ((ACE_SOCK_Acceptor *) this) -> get_handle (); - struct sockaddr_atm *cli_addr - = (struct sockaddr_atm *)remote_addr -> get_addr (); - int caddr_len = sizeof (struct sockaddr_atm); - - do { - n_handle = ACE_OS::accept (s_handle, - reinterpret_cast (cli_addr), - &caddr_len); - } while (n_handle == ACE_INVALID_HANDLE && errno == EINTR); - - ((ACE_ATM_Addr *)remote_addr) -> set (cli_addr, - ((ACE_ATM_Addr *)remote_addr) -> get_selector ()); - ((ACE_IPC_SAP *)&new_sap) -> set_handle (n_handle); - - return 0; -#elif defined (ACE_HAS_LINUX_ATM) - ACE_UNUSED_ARG (params); - - ACE_HANDLE s_handle = ((ACE_SOCK_Acceptor *) this) -> get_handle (); - struct atm_qos accept_qos = qos.get_qos (); - - if (ACE_OS::setsockopt (s_handle, - SOL_ATM, - SO_ATMQOS, - reinterpret_cast (&accept_qos), - sizeof (accept_qos)) < 0) { - ACE_OS::printf ("Acceptor (accept): error setting Qos"); - } - - return (acceptor_.accept (new_sap.get_stream (), - remote_addr, - timeout, - restart, - reset_new_handle)); -#else - ACE_UNUSED_ARG (new_sap); - ACE_UNUSED_ARG (remote_addr); - ACE_UNUSED_ARG (timeout); - ACE_UNUSED_ARG (restart); - ACE_UNUSED_ARG (reset_new_handle); - ACE_UNUSED_ARG (params); - ACE_UNUSED_ARG (qos); - return 0; -#endif /* ACE_HAS_FORE_ATM_XTI */ -} - -// Close versioned namespace, if enabled by the user. -ACE_END_VERSIONED_NAMESPACE_DECL - - -#endif /* ACE_HAS_ATM */ diff --git a/externals/ace/ATM_Acceptor.h b/externals/ace/ATM_Acceptor.h deleted file mode 100644 index 1241a228caa..00000000000 --- a/externals/ace/ATM_Acceptor.h +++ /dev/null @@ -1,123 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file ATM_Acceptor.h - * - * $Id: ATM_Acceptor.h 82723 2008-09-16 09:35:44Z johnnyw $ - * - * @author Joe Hoffert - */ -//============================================================================= - - -#ifndef ACE_ATM_ACCEPTOR_H -#define ACE_ATM_ACCEPTOR_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_ATM) - -#include "ace/ATM_Stream.h" -#include "ace/ATM_Params.h" -#include "ace/ATM_QoS.h" - -#if defined (ACE_HAS_LINUX_ATM) -#include /**/ "atm.h" -#endif /* ACE_HAS_LINUX_ATM */ - -#if defined (ACE_HAS_FORE_ATM_WS2) || defined (ACE_HAS_LINUX_ATM) -#include "ace/SOCK_Acceptor.h" -ACE_BEGIN_VERSIONED_NAMESPACE_DECL -typedef ACE_SOCK_Acceptor ATM_Acceptor; -ACE_END_VERSIONED_NAMESPACE_DECL -#elif defined (ACE_HAS_FORE_ATM_XTI) -#include "ace/TLI_Acceptor.h" -ACE_BEGIN_VERSIONED_NAMESPACE_DECL -typedef ACE_TLI_Acceptor ATM_Acceptor; -ACE_END_VERSIONED_NAMESPACE_DECL -#endif // ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM - -// Open versioned namespace, if enabled by the user. -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Forward declarations. -class ACE_Time_Value; - -/** - * @class ACE_ATM_Acceptor - * - * @brief Defines the member functions for ACE_ATM_Acceptor abstraction. - * - * This class wraps up the ACE_SOCK_Acceptor and ACE_TLI_Acceptor - * to make the mechanism for the ATM protocol transparent. - */ -class ACE_Export ACE_ATM_Acceptor -{ - -public: - // = Initialization and termination methods. - /// Default constructor. - ACE_ATM_Acceptor (void); - - ~ACE_ATM_Acceptor (); - - /// Initiate a passive mode connection. - ACE_ATM_Acceptor (const ACE_Addr &remote_sap, - int backlog = ACE_DEFAULT_BACKLOG, - ACE_ATM_Params params = ACE_ATM_Params()); - - /// Initiate a passive mode socket. - ACE_HANDLE open (const ACE_Addr &remote_sap, - int backlog = ACE_DEFAULT_BACKLOG, - ACE_ATM_Params params = ACE_ATM_Params()); - - /// Close down the acceptor and release resources. - int close (void); - - // = Passive connection acceptance method. - - /// Accept a new data transfer connection. A @a timeout of 0 means - /// block forever, a @a timeout of {0, 0} means poll. @a restart == 1 - /// means "restart if interrupted." - int accept (ACE_ATM_Stream &new_sap, - ACE_Addr *remote_addr = 0, - ACE_Time_Value *timeout = 0, - bool restart = true, - bool reset_new_handle = false, - ACE_ATM_Params params = ACE_ATM_Params(), - ACE_ATM_QoS qos = ACE_ATM_QoS()); - - /// Get the local address currently listening on - int get_local_addr( ACE_ATM_Addr &local_addr ); - - // = Meta-type info - typedef ACE_ATM_Addr PEER_ADDR; - typedef ACE_ATM_Stream PEER_STREAM; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - ATM_Acceptor acceptor_; -}; - -// Close versioned namespace, if enabled by the user. -ACE_END_VERSIONED_NAMESPACE_DECL - - -#if defined (__ACE_INLINE__) -#include "ace/ATM_Acceptor.inl" -#endif /* __ACE_INLINE__ */ - -#endif /* ACE_HAS_ATM */ -#include /**/ "ace/post.h" -#endif /* ACE_ATM_ACCEPTOR_H */ diff --git a/externals/ace/ATM_Acceptor.inl b/externals/ace/ATM_Acceptor.inl deleted file mode 100644 index fa60c4ad89a..00000000000 --- a/externals/ace/ATM_Acceptor.inl +++ /dev/null @@ -1,43 +0,0 @@ -// -*- C++ -*- -// -// $Id: ATM_Acceptor.inl 80826 2008-03-04 14:51:23Z wotte $ - -// Open versioned namespace, if enabled by the user. -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE void -ACE_ATM_Acceptor::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_ATM_Acceptor::dump"); -#endif /* ACE_HAS_DUMP */ -} - -ACE_INLINE -ACE_ATM_Acceptor::ACE_ATM_Acceptor (const ACE_Addr &remote_sap, - int backlog, - ACE_ATM_Params params) -{ - ACE_TRACE ("ACE_ATM_Acceptor::ACE_ATM_Acceptor"); - - //FUZZ: disable check_for_lack_ACE_OS - if (open (remote_sap, backlog, params) < 0) - //FUZZ: enable check_for_lack_ACE_OS - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_ATM_Acceptor::ACE_ATM_Acceptor"))); -} - -ACE_INLINE -int -ACE_ATM_Acceptor::close (void) -{ -#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2) || defined (ACE_HAS_LINUX_ATM) - return (acceptor_.close()); -#else - return 0; -#endif // ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM -} - -// Close versioned namespace, if enabled by the user. -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/ATM_Addr.cpp b/externals/ace/ATM_Addr.cpp deleted file mode 100644 index 991498d6668..00000000000 --- a/externals/ace/ATM_Addr.cpp +++ /dev/null @@ -1,522 +0,0 @@ -// $Id: ATM_Addr.cpp 84565 2009-02-23 08:20:39Z johnnyw $ - -// Defines the Internet domain address family address format. - -#include "ace/ATM_Addr.h" -#if defined (ACE_HAS_ATM) - -#include "ace/Log_Msg.h" - -#if defined (ACE_HAS_FORE_ATM_WS2) -#include /**/ "forews2.h" -#endif /* ACE_HAS_FORE_ATM_WS2 */ - -#if !defined (__ACE_INLINE__) -#include "ace/ATM_Addr.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID(ace, ATM_Addr, "$Id: ATM_Addr.cpp 84565 2009-02-23 08:20:39Z johnnyw $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_ATM_Addr) - -#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2) -#define BHLI_MAGIC "FORE_ATM" -// This is line rate in cells/s for an OC-3 MM interface. -const long ACE_ATM_Addr::LINE_RATE = 353207; -const int ACE_ATM_Addr::OPT_FLAGS_CPID = 0x1; -const int ACE_ATM_Addr::OPT_FLAGS_PMP = 0x2; -const int ACE_ATM_Addr::DEFAULT_SELECTOR = 0x99; -#elif defined (ACE_HAS_LINUX_ATM) -//pbrandao:for Linux: -//pbrandao:for now stick with current definitions -//pbrandao:see if later need to change -const long ACE_ATM_Addr::LINE_RATE = 353207; -const int ACE_ATM_Addr::OPT_FLAGS_CPID = 0; -const int ACE_ATM_Addr::OPT_FLAGS_PMP = 0; -const int ACE_ATM_Addr::DEFAULT_SELECTOR = 0x99; -#else -const long ACE_ATM_Addr::LINE_RATE = 0L; -const int ACE_ATM_Addr::OPT_FLAGS_CPID = 0; -const int ACE_ATM_Addr::OPT_FLAGS_PMP = 0; -const int ACE_ATM_Addr::DEFAULT_SELECTOR = 0x0; -#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ - -// Default constructor - -ACE_ATM_Addr::ACE_ATM_Addr (u_char selector) -#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2) - : ACE_Addr (AF_ATM, -#elif defined (ACE_HAS_LINUX_ATM) - : ACE_Addr (PF_ATMSVC, -#else - : ACE_Addr (AF_UNSPEC, -#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ - sizeof this->atm_addr_) -{ - // ACE_TRACE ("ACE_ATM_Addr::ACE_ATM_Addr"); - (void) ACE_OS::memset ((void *) &this->atm_addr_, - 0, - sizeof this->atm_addr_); - this->init (selector); -} - -// Copy constructor. - -ACE_ATM_Addr::ACE_ATM_Addr (const ACE_ATM_Addr &sap, - u_char selector) -#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2) - : ACE_Addr (AF_ATM, -#elif defined (ACE_HAS_LINUX_ATM) - : ACE_Addr (PF_ATMSVC, -#else - : ACE_Addr (AF_UNSPEC, -#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ - sizeof this->atm_addr_) -{ - ACE_TRACE ("ACE_ATM_Addr::ACE_ATM_Addr"); - this->set (sap, selector); -#if defined (ACE_HAS_LINUX_ATM) - this->atm_addr_.sockaddratmsvc.sas_family = PF_ATMSVC; - this->atm_addr_.atmsap.blli[0].l3_proto = ATM_L3_NONE; - this->atm_addr_.atmsap.blli[0].l2_proto = ATM_L2_NONE; - this->atm_addr_.atmsap.bhli.hl_type = ATM_HL_NONE; -#endif /* ACE_HAS_LINUX_ATM */ -} - -ACE_ATM_Addr::ACE_ATM_Addr (const ATM_Addr *sap, - u_char selector) -#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2) - : ACE_Addr (AF_ATM, -#elif defined (ACE_HAS_LINUX_ATM) - : ACE_Addr (PF_ATMSVC, -#else - : ACE_Addr (AF_UNSPEC, -#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ - sizeof this->atm_addr_) -{ - ACE_TRACE ("ACE_ATM_Addr::ACE_ATM_Addr"); - this->set (sap, selector); -} - - -ACE_ATM_Addr::ACE_ATM_Addr (const ACE_TCHAR sap[], - u_char selector) -#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2) - : ACE_Addr (AF_ATM, -#elif defined (ACE_HAS_LINUX_ATM) - : ACE_Addr (PF_ATMSVC, -#else - : ACE_Addr (AF_UNSPEC, -#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ - sizeof this->atm_addr_) -{ - ACE_TRACE ("ACE_ATM_Addr::ACE_ATM_Addr"); - this->set (sap, selector); -} - -ACE_ATM_Addr::~ACE_ATM_Addr (void) -{ -} - -// Return the address. - -void * -ACE_ATM_Addr::get_addr (void) const -{ - ACE_TRACE ("ACE_ATM_Addr::get_addr"); - return (void *) &this->atm_addr_; -} - -void -ACE_ATM_Addr::init (u_char selector) -{ -#if defined (ACE_HAS_FORE_ATM_XTI) - // Note: this approach may be FORE implementation-specific. When we - // bind with tag_addr ABSENT and tag_selector PRESENT, only the - // selector (i.e. address[19]) is used by the TP. The rest of the - // local address is filled in by the TP and can be obtained via the - // 'ret' parameter or with t_getname ()/t_getprotaddr (). - - atm_addr_.addressType = (u_int16_t) AF_ATM; - - atm_addr_.sap.t_atm_sap_addr.SVE_tag_addr = (int8_t) T_ATM_ABSENT; - atm_addr_.sap.t_atm_sap_addr.SVE_tag_selector = (int8_t) T_ATM_PRESENT; - - atm_addr_.sap.t_atm_sap_addr.address_format = (u_int8_t) T_ATM_ENDSYS_ADDR; - atm_addr_.sap.t_atm_sap_addr.address_length = ATMNSAP_ADDR_LEN; - atm_addr_.sap.t_atm_sap_addr.address[ATMNSAP_ADDR_LEN - 1] = selector; - - atm_addr_.sap.t_atm_sap_layer2.SVE_tag = (int8_t) T_ATM_ABSENT; - atm_addr_.sap.t_atm_sap_layer3.SVE_tag = (int8_t) T_ATM_ABSENT; - - atm_addr_.sap.t_atm_sap_appl.SVE_tag = (int8_t) T_ATM_PRESENT; - atm_addr_.sap.t_atm_sap_appl.ID_type = (u_int8_t) T_ATM_USER_APP_ID; - - ACE_OS::memcpy (atm_addr_.sap.t_atm_sap_appl.ID.user_defined_ID, - BHLI_MAGIC, - sizeof atm_addr_.sap.t_atm_sap_appl.ID); -#elif defined (ACE_HAS_FORE_ATM_WS2) - ACE_OS::memset ((void *)&atm_addr_, 0, sizeof atm_addr_); - atm_addr_.satm_number.Addr[ ATM_ADDR_SIZE - 1 ] = (char)selector; - atm_addr_.satm_family = AF_ATM; - atm_addr_.satm_number.AddressType = ATM_NSAP; - atm_addr_.satm_number.NumofDigits = ATM_ADDR_SIZE; - atm_addr_.satm_blli.Layer2Protocol = SAP_FIELD_ABSENT; - atm_addr_.satm_blli.Layer3Protocol = SAP_FIELD_ABSENT; - atm_addr_.satm_bhli.HighLayerInfoType = SAP_FIELD_ABSENT; - - // Need to know the correspondence. - //atm_addr_.sap.t_atm_sap_appl.SVE_tag = (int8_t) T_ATM_PRESENT; - //atm_addr_.sap.t_atm_sap_appl.ID_type = (u_int8_t) T_ATM_USER_APP_ID; - //ACE_OS::memcpy (atm_addr_.sap.t_atm_sap_appl.ID.user_defined_ID, - // BHLI_MAGIC, - // sizeof atm_addr_.sap.t_atm_sap_appl.ID); -#elif defined (ACE_HAS_LINUX_ATM) - atm_addr_.sockaddratmsvc.sas_family = AF_ATMSVC; - atm_addr_.sockaddratmsvc.sas_addr.prv[ATM_ESA_LEN - 1] = (char)selector; - atm_addr_.atmsap.blli[0].l3_proto = ATM_L3_NONE; - atm_addr_.atmsap.blli[0].l2_proto = ATM_L2_NONE; - atm_addr_.atmsap.bhli.hl_type = ATM_HL_NONE; -#else - ACE_UNUSED_ARG (selector); -#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ -} - -int -ACE_ATM_Addr::set (const ACE_ATM_Addr &sap, - u_char selector) -{ - ACE_TRACE ("ACE_ATM_Addr::set"); - - this->init (selector); - - this->ACE_Addr::base_set (sap.get_type (), - sap.get_size ()); - -#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2) - ACE_ASSERT (sap.get_type () == AF_ATM); -#elif defined (ACE_HAS_LINUX_ATM) - ACE_ASSERT (sap.get_type () == PF_ATMSVC); -#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 */ - - (void) ACE_OS::memcpy ((void *) &this->atm_addr_, - (void *) &sap.atm_addr_, - sizeof this->atm_addr_); - return 0; -} - -int -ACE_ATM_Addr::set (const ATM_Addr *sap, - u_char selector) -{ - ACE_TRACE ("ACE_ATM_Addr::set"); - - this->init (selector); - -#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2) - this->ACE_Addr::base_set (AF_ATM, -#elif defined (ACE_HAS_LINUX_ATM) - this->ACE_Addr::base_set (PF_ATMSVC, -#else - this->ACE_Addr::base_set (AF_UNSPEC, -#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 */ - sizeof (*sap)); - - (void) ACE_OS::memcpy ((void *) &this->atm_addr_, - (void *) sap, - sizeof this->atm_addr_); - return 0; -} - -int -ACE_ATM_Addr::set (const ACE_TCHAR address[], - u_char selector) -{ - ACE_TRACE ("ACE_ATM_Addr::set"); - int ret; - - this->init (selector); - -#if defined (ACE_HAS_FORE_ATM_XTI) - atm_addr_.sap.t_atm_sap_addr.SVE_tag_addr = - (int8_t) T_ATM_PRESENT; -#endif /* ACE_HAS_FORE_ATM_XTI */ - - ret = this -> string_to_addr (address); - this -> set_selector (selector); - return ret; -} - -// Transform the string into the current addressing format. - -int -ACE_ATM_Addr::string_to_addr (const ACE_TCHAR sap[]) -{ - ACE_TRACE ("ACE_ATM_Addr::string_to_addr"); - -#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2) - this->ACE_Addr::base_set (AF_ATM, -#elif defined (ACE_HAS_LINUX_ATM) - this->ACE_Addr::base_set (PF_ATMSVC, -#else - this->ACE_Addr::base_set (AF_UNSPEC, -#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ - sizeof this->atm_addr_); -#if defined (ACE_HAS_FORE_ATM_XTI) - struct hostent *entry; - struct atmnsap_addr *nsap; - - // Yow, someone gave us a NULL ATM address! - if (sap == 0) - { - errno = EINVAL; - return -1; - } - else if ((entry = gethostbyname_atmnsap ((ACE_TCHAR *)sap)) != 0) - { - ACE_OS::memcpy (atm_addr_.sap.t_atm_sap_addr.address, - entry->h_addr_list[0], - ATMNSAP_ADDR_LEN - 1); - } - else if ((nsap = atmnsap_addr (sap)) != 0) - { - ACE_OS::memcpy (atm_addr_.sap.t_atm_sap_addr.address, - nsap->atmnsap, - ATMNSAP_ADDR_LEN); - } - else { - errno = EINVAL; - return -1; - } -#elif defined (ACE_HAS_FORE_ATM_WS2) - DWORD dwValue; - HANDLE hLookup; - WSAQUERYSETW qsRestrictions; - CSADDR_INFO csaBuffer; - WCHAR tmpWStr[100]; - - MultiByteToWideChar (CP_ACP, MB_PRECOMPOSED, sap, -1, tmpWStr, 100); - - csaBuffer.LocalAddr.iSockaddrLength = sizeof (struct sockaddr_atm); - csaBuffer.LocalAddr.lpSockaddr = (struct sockaddr *)&atm_addr_; - csaBuffer.RemoteAddr.iSockaddrLength = sizeof (struct sockaddr_atm); - csaBuffer.RemoteAddr.lpSockaddr = (struct sockaddr *)&atm_addr_; - - qsRestrictions.dwSize = sizeof (WSAQUERYSETW); - qsRestrictions.lpszServiceInstanceName = 0; - qsRestrictions.lpServiceClassId = &FORE_NAME_CLASS; - qsRestrictions.lpVersion = 0; - qsRestrictions.lpszComment = 0; - qsRestrictions.dwNameSpace = FORE_NAME_SPACE; - qsRestrictions.lpNSProviderId = 0; - qsRestrictions.lpszContext = L""; - qsRestrictions.dwNumberOfProtocols = 0; - qsRestrictions.lpafpProtocols = 0; - qsRestrictions.lpszQueryString = tmpWStr; - qsRestrictions.dwNumberOfCsAddrs = 1; - qsRestrictions.lpcsaBuffer = &csaBuffer; - qsRestrictions.lpBlob = 0; //&blob; - - if (::WSALookupServiceBeginW (&qsRestrictions, LUP_RETURN_ALL, &hLookup) - == SOCKET_ERROR) { - ACE_OS::printf ("Error: WSALookupServiceBeginW failed! %d\n", - ::WSAGetLastError ()); - return -1; - } - - dwValue = sizeof (WSAQUERYSETW); - - if (::WSALookupServiceNextW (hLookup, 0, &dwValue, &qsRestrictions) - == SOCKET_ERROR) { - if (WSAGetLastError () != WSA_E_NO_MORE) { - ACE_OS::printf ("Error: WSALookupServiceNextW failed! %d\n", - ::WSAGetLastError ()); - return -1; - } - } - - if (WSALookupServiceEnd (hLookup) == SOCKET_ERROR) { - ACE_OS::printf ("Error : WSALookupServiceEnd failed! %d\n", - ::WSAGetLastError ()); - errno = EINVAL; - return -1; - } -#elif defined (ACE_HAS_LINUX_ATM) - if (sap == 0 || !ACE_OS::strcmp (sap,"")) { - errno = EINVAL; - return -1; - } - - if (text2atm ((ACE_TCHAR *)sap, - (struct sockaddr *)& (atm_addr_.sockaddratmsvc), - sizeof (atm_addr_.sockaddratmsvc), - T2A_SVC | T2A_NAME) < 0) { - ACE_DEBUG (LM_DEBUG, - "Error : text2atm failed!\n"); - errno = EINVAL; - return -1; - } -#else - ACE_UNUSED_ARG (sap); - - return 0; -#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ - -#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2) || defined (ACE_HAS_LINUX_ATM) - return 0; -#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 */ -} - -// Transform the current address into string format. - -int -ACE_ATM_Addr::addr_to_string (ACE_TCHAR addr[], - size_t addrlen) const -{ - ACE_TRACE ("ACE_ATM_Addr::addr_to_string"); - -#if defined (ACE_HAS_FORE_ATM_XTI) - ACE_TCHAR buffer[MAXNAMELEN + 1]; - struct atmnsap_addr nsap; - ACE_OS::memcpy (nsap.atmnsap, - atm_addr_.sap.t_atm_sap_addr.address, - ATMNSAP_ADDR_LEN); - ACE_OS::sprintf (buffer, - ACE_TEXT ("%s"), - atmnsap_ntoa (nsap)); - - size_t total_len = ACE_OS::strlen (buffer) + sizeof ('\0'); - - if (addrlen < total_len) - return -1; - else - ACE_OS::strcpy (addr, buffer); - - return 0; -#elif defined (ACE_HAS_FORE_ATM_WS2) - ACE_TCHAR buffer[MAXNAMELEN + 1]; - int i; - - if (addrlen < ATM_ADDR_SIZE + 1) - return -1; - - for (i = 0; i < ATM_ADDR_SIZE; i++) { - buffer[ i * 3 ] = '\0'; - ACE_OS::sprintf (buffer, ACE_TEXT ("%s%02x."), - buffer, - atm_addr_.satm_number.Addr[ i ]); - } - - buffer[ ATM_ADDR_SIZE * 3 - 1 ] = '\0'; - ACE_OS::strcpy (addr, buffer); - - return 0; -#elif defined (ACE_HAS_LINUX_ATM) - ACE_TCHAR buffer[MAX_ATM_ADDR_LEN + 1]; - int total_len; - if ((total_len = atm2text (buffer, - sizeof buffer, - (struct sockaddr *)& (atm_addr_.sockaddratmsvc), - A2T_PRETTY)) < 0) { - ACE_DEBUG ((LM_DEBUG,"ACE_ATM_Addr (addr_to_string): atm2text failed\n")); - return -1; - } - if (addrlen < (size_t)total_len) - return -1; - else - ACE_OS::strcpy (addr, - buffer); - - return 0; -#else - ACE_UNUSED_ARG (addr); - ACE_UNUSED_ARG (addrlen); - return -1; -#endif /* ACE_HAS_FORE_ATM_XTI && ACE_HAS_FORE_ATM_WS2 */ -} - -const ACE_TCHAR * -ACE_ATM_Addr::addr_to_string (void) const -{ - ACE_TRACE ("ACE_ATM_Addr::addr_to_string"); - - static ACE_TCHAR addr[MAXHOSTNAMELEN + 1]; - if (this->addr_to_string (addr, - MAXHOSTNAMELEN + 1) < 0) - return 0; - - return addr; -} - -// Set a pointer to the address. -void -ACE_ATM_Addr::set_addr (void *addr, int len) -{ - ACE_TRACE ("ACE_ATM_Addr::set_addr"); - -#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2) - this->ACE_Addr::base_set (AF_ATM, -#elif defined (ACE_HAS_LINUX_ATM) - this->ACE_Addr::base_set (PF_ATMSVC, -#else - this->ACE_Addr::base_set (AF_UNSPEC, -#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_WS2 */ - len); - ACE_OS::memcpy ((void *) &this->atm_addr_, - (void *) addr, len); -} - -// Compare two addresses for inequality. - -bool -ACE_ATM_Addr::operator != (const ACE_ATM_Addr &sap) const -{ - ACE_TRACE ("ACE_ATM_Addr::operator !="); - return ! ((*this) == sap); -} - -// Compare two addresses for equality. - -bool -ACE_ATM_Addr::operator == (const ACE_ATM_Addr &sap) const -{ - ACE_TRACE ("ACE_ATM_Addr::operator =="); - -#if defined (ACE_HAS_LINUX_ATM) - return (atm_equal ((const struct sockaddr *)& (this->atm_addr_.sockaddratmsvc), - (const struct sockaddr *)& (sap.atm_addr_.sockaddratmsvc), - 0, - 0) - && - sap_equal (& (this->atm_addr_.atmsap), - & (sap.atm_addr_.atmsap), - 0)); -#else - return ACE_OS::memcmp (&atm_addr_, - &sap.atm_addr_, - sizeof (ATM_Addr)) == 0; -#endif /* ACE_HAS_LINUX_ATM */ -} - -void -ACE_ATM_Addr::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_ATM_Addr::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - - ACE_TCHAR s[ACE_MAX_FULLY_QUALIFIED_NAME_LEN + 16]; - ACE_OS::sprintf (s, - ACE_TEXT ("%s"), - this->addr_to_string ()); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("%s"), s)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_ATM */ diff --git a/externals/ace/ATM_Addr.h b/externals/ace/ATM_Addr.h deleted file mode 100644 index 7fa93f1492c..00000000000 --- a/externals/ace/ATM_Addr.h +++ /dev/null @@ -1,197 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file ATM_Addr.h - * - * $Id: ATM_Addr.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Joe Hoffert - */ -//========================================================================== - -#ifndef ACE_ATM_ADDR_H -#define ACE_ATM_ADDR_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_ATM) - -#include /**/ "ace/ACE_export.h" -#include "ace/Addr.h" - -#if defined (ACE_HAS_FORE_ATM_XTI) -ACE_BEGIN_VERSIONED_NAMESPACE_DECL -typedef ATMSAPAddress ATM_Addr; -ACE_END_VERSIONED_NAMESPACE_DECL -#elif defined (ACE_HAS_FORE_ATM_WS2) -#define FORE_NAME_SPACE NS_ALL -ACE_BEGIN_VERSIONED_NAMESPACE_DECL -typedef struct sockaddr_atm ATM_Addr; -ACE_END_VERSIONED_NAMESPACE_DECL -#elif defined (ACE_HAS_LINUX_ATM) - -#include /**/ "atm.h" - -// Open versioned namespace, if enabled by the user. -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -//pbrandao:as Linux has this 2 structs separeted we "link it" here -typedef struct _linux_atm_addr -{ - struct sockaddr_atmsvc sockaddratmsvc; - struct atm_sap atmsap; -} ATM_Addr; -#else -typedef int ATM_Addr; -#endif /* ACE_HAS_FORE_ATM_XTI/ACE_HAS_FORE_ATM_WS2/ACE_HAS_LINUX_ATM */ - -/** - * @class ACE_ATM_Addr - * - * @brief Defines the ATM domain address family address format. - */ -class ACE_Export ACE_ATM_Addr : public ACE_Addr -{ -public: - // Constants used for ATM options - static const long LINE_RATE; - static const int OPT_FLAGS_CPID; - static const int OPT_FLAGS_PMP; - static const int DEFAULT_SELECTOR; - - // = Initialization methods. - /// Default constructor. - ACE_ATM_Addr (u_char selector = DEFAULT_SELECTOR); - - /// Copy constructor. - ACE_ATM_Addr (const ACE_ATM_Addr &, - u_char selector = DEFAULT_SELECTOR); - - /** - * Creates an ACE_ATM_Addr from an ATMSAPAddress structure. This - * is vendor specific (FORE systems). May need to change when other - * vendors are supported. - */ - ACE_ATM_Addr (const ATM_Addr *, - u_char selector = DEFAULT_SELECTOR); - - /** - * Initializes an ACE_ATM_Addr from the which can be - * "atm-address" (e.g., - * "47.0005.80.ffe100.0000.f20f.2200.0020480694f9.00") or "hostname" - * (e.g., "frisbee.cs.wustl.edu"). - */ - ACE_ATM_Addr (const ACE_TCHAR sap[], - u_char selector = DEFAULT_SELECTOR); - - /// Default dtor. - ~ACE_ATM_Addr (void); - - // = Initialization methods (useful after object construction). - /// Default initialization for non-address values (e.g., - /// t_atm_sap_addr.SVE_tag_addr, t_atm_sap_addr.SVE_tag_selector) - void init (u_char selector = DEFAULT_SELECTOR); - - /// Initializes from another ACE_ATM_Addr. - int set (const ACE_ATM_Addr &, - u_char selector = DEFAULT_SELECTOR); - - /** - * Initializes an ACE_ATM_Addr from an ATMSAPAddress/sockaddr_atm - * structure. This is vendor specific (FORE systems). May need to - * change when other vendors are supported. - */ - int set (const ATM_Addr *, - u_char selector = DEFAULT_SELECTOR); - - /** - * Initializes an ACE_ATM_Addr from the which can be - * "atm-address" (e.g., - * "47.0005.80.ffe100.0000.f20f.2200.0020480694f9.00") or "hostname" - * (e.g., "frisbee.cs.wustl.edu"). - */ - int set (const ACE_TCHAR sap[], - u_char selector = DEFAULT_SELECTOR); - - /** - * Initializes an ACE_ATM_Addr from the which can be - * "atm-address" (e.g., - * "47.0005.80.ffe100.0000.f20f.2200.0020480694f9.00") or "hostname" - * (e.g., "frisbee.cs.wustl.edu"). - */ - virtual int string_to_addr (const ACE_TCHAR sap[]); - - /** - * Return the character representation of the ATM address (e.g., - * "47.0005.80.ffe100.0000.f20f.2200.0020480694f9.00") storing it in - * the @a addr (which is assumed to be bytes long). This - * version is reentrant. Returns -1 if the of the @a addr - * is too small, else 0. - */ - virtual int addr_to_string (ACE_TCHAR addr[], - size_t addrlen) const; - - /** - * Return the character representation of the ATM address (e.g., - * "47.0005.80.ffe100.0000.f20f.2200.0020480694f9.00"). Returns -1 - * if the of the is too small, else 0.(This version - * is non-reentrant since it returns a pointer to a static data - * area.) - */ - const ACE_TCHAR *addr_to_string (void) const; - - /// Return a pointer to the underlying network address. - virtual void *get_addr (void) const; - - /// Set a pointer to the address. - virtual void set_addr (void *, int); - - /// Return the selector for network address. - u_char get_selector (void) const; - - /// Set the selector for the network address. - void set_selector (u_char selector); - - /** - * Compare two addresses for equality. The addresses are considered - * equal if they contain the same ATM address. Q: Is there any - * other check for equality needed for ATM? - */ - bool operator == (const ACE_ATM_Addr &SAP) const; - - /// Compare two addresses for inequality. - bool operator != (const ACE_ATM_Addr &SAP) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -// char *construct_options (ACE_HANDLE fd, -// int qos_kb, -// int flags, -// long *optsize); -// // Construct options for ATM connections - -private: - ATM_Addr atm_addr_; -}; - -// Close versioned namespace, if enabled by the user. -ACE_END_VERSIONED_NAMESPACE_DECL - - -#if defined (__ACE_INLINE__) -#include "ace/ATM_Addr.inl" -#endif /* __ACE_INLINE__ */ - -#endif /* ACE_HAS_ATM */ -#include /**/ "ace/post.h" -#endif /* ACE_ATM_ADDR_H */ diff --git a/externals/ace/ATM_Addr.inl b/externals/ace/ATM_Addr.inl deleted file mode 100644 index 55f43d6613a..00000000000 --- a/externals/ace/ATM_Addr.inl +++ /dev/null @@ -1,37 +0,0 @@ -// -*- C++ -*- -// -// $Id: ATM_Addr.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE u_char -ACE_ATM_Addr::get_selector (void) const -{ - ACE_TRACE ("ACE_ATM_Addr::get_selector"); -#if defined (ACE_HAS_FORE_ATM_XTI) - return atm_addr_.sap.t_atm_sap_addr.address[ATMNSAP_ADDR_LEN - 1]; -#elif defined (ACE_HAS_FORE_ATM_WS2) - return atm_addr_.satm_number.Addr[ ATM_ADDR_SIZE - 1 ]; -#elif defined (ACE_HAS_LINUX_ATM) - return atm_addr_.sockaddratmsvc.sas_addr.prv[ATM_ESA_LEN - 1]; -#else - return 0; -#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ -} - -ACE_INLINE void -ACE_ATM_Addr::set_selector (u_char selector) -{ - ACE_TRACE ("ACE_ATM_Addr::set_selector"); -#if defined (ACE_HAS_FORE_ATM_XTI) - atm_addr_.sap.t_atm_sap_addr.address[ATMNSAP_ADDR_LEN - 1] = selector; -#elif defined (ACE_HAS_FORE_ATM_WS2) - atm_addr_.satm_number.Addr[ ATM_ADDR_SIZE - 1 ] = selector; -#elif defined (ACE_HAS_LINUX_ATM) - atm_addr_.sockaddratmsvc.sas_addr.prv[ATM_ESA_LEN - 1] = selector; -#else - ACE_UNUSED_ARG (selector); -#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/ATM_Connector.cpp b/externals/ace/ATM_Connector.cpp deleted file mode 100644 index c1ce226adce..00000000000 --- a/externals/ace/ATM_Connector.cpp +++ /dev/null @@ -1,138 +0,0 @@ -// ATM_Connector.cpp -// $Id: ATM_Connector.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/ATM_Connector.h" -#if defined (ACE_HAS_ATM) - -#include "ace/Handle_Set.h" - -ACE_RCSID(ace, ATM_Connector, "$Id: ATM_Connector.cpp 80826 2008-03-04 14:51:23Z wotte $") - -#if !defined (__ACE_INLINE__) -#include "ace/ATM_Connector.inl" -#endif /* __ACE_INLINE__ */ - -// Open versioned namespace, if enabled by the user. -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_ATM_Connector) - -ACE_ATM_Connector::ACE_ATM_Connector (void) -{ - ACE_TRACE ("ACE_ATM_Connector::ACE_ATM_Connector"); -} - -// Actively connect and produce a new ACE_ATM_Stream if things go well... -// Connect the to the , waiting up to -// amount of time if necessary. - -int -ACE_ATM_Connector::connect (ACE_ATM_Stream &new_stream, - const ACE_ATM_Addr &remote_sap, - ACE_ATM_Params params, - ACE_ATM_QoS options, - ACE_Time_Value *timeout, - const ACE_ATM_Addr &local_sap, - int reuse_addr, - int flags, - int perms) -{ - ACE_TRACE ("ACE_ATM_Connector::connect"); -#if defined (ACE_HAS_FORE_ATM_XTI) - return connector_.connect(new_stream.get_stream(), - remote_sap, - timeout, - local_sap, - reuse_addr, - flags, - perms, - params.get_device(), - params.get_info(), - params.get_rw_flag(), - params.get_user_data(), - &options.get_qos()); -#elif defined (ACE_HAS_FORE_ATM_WS2) - ACE_DEBUG(LM_DEBUG, - ACE_TEXT ("ATM_Connector(connect): set QoS parameters\n" )); - - ACE_HANDLE s = new_stream.get_handle(); - struct sockaddr_atm *saddr = ( struct sockaddr_atm *)remote_sap.get_addr(); - ACE_QoS cqos = options.get_qos(); - - ACE_QoS_Params qos_params = ACE_QoS_Params(0, - 0, - &cqos, - 0, - 0); - - ACE_DEBUG(LM_DEBUG, - ACE_TEXT ("ATM_Connector(connect): connecting...\n")); - - int result = ACE_OS::connect( s, - ( struct sockaddr *)saddr, - sizeof( struct sockaddr_atm ), - qos_params ); - - if ( result != 0 ) - ACE_OS::printf( "ATM_Connector(connect): connection failed, %d\n", - ::WSAGetLastError()); - - return result; -#elif defined (ACE_HAS_LINUX_ATM) - ACE_UNUSED_ARG (params); - ACE_UNUSED_ARG (timeout); - ACE_UNUSED_ARG (reuse_addr); - ACE_UNUSED_ARG (perms); - ACE_UNUSED_ARG (flags); - - ACE_HANDLE handle = new_stream.get_handle(); - ATM_QoS qos =options.get_qos(); - ATM_Addr *local_addr=(ATM_Addr*)local_sap.get_addr(), - *remote_addr=(ATM_Addr*)remote_sap.get_addr(); - - if (ACE_OS::setsockopt(handle, - SOL_ATM, - SO_ATMSAP, - reinterpret_cast (&(local_addr->atmsap)), - sizeof(local_addr->atmsap)) < 0) { - ACE_OS::printf( "ATM_Connector(connect): unable to set atmsap %d\nContinuing...", - errno); - } - if (ACE_OS::setsockopt(handle, - SOL_ATM, - SO_ATMQOS, - reinterpret_cast (&qos), - sizeof(qos)) < 0) { - ACE_DEBUG((LM_DEBUG,ACE_TEXT ("ATM_Connector(connect): unable to set qos %d\n"), - errno)); - return -1; - } - - int result = ACE_OS::connect(handle, - (struct sockaddr *)&(remote_addr->sockaddratmsvc), - sizeof( remote_addr->sockaddratmsvc)); - - if ( result != 0 ) - ACE_DEBUG(LM_DEBUG, - ACE_TEXT ("ATM_Connector(connect): connection failed, %d\n"), - errno); - - return result; -#else - ACE_UNUSED_ARG (new_stream); - ACE_UNUSED_ARG (remote_sap); - ACE_UNUSED_ARG (params); - ACE_UNUSED_ARG (options); - ACE_UNUSED_ARG (timeout); - ACE_UNUSED_ARG (local_sap); - ACE_UNUSED_ARG (reuse_addr); - ACE_UNUSED_ARG (flags); - ACE_UNUSED_ARG (perms); - return 0; -#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ -} - -// Close versioned namespace, if enabled by the user. -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_ATM */ diff --git a/externals/ace/ATM_Connector.h b/externals/ace/ATM_Connector.h deleted file mode 100644 index 940fc5a307f..00000000000 --- a/externals/ace/ATM_Connector.h +++ /dev/null @@ -1,164 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file ATM_Connector.h - * - * $Id: ATM_Connector.h 82723 2008-09-16 09:35:44Z johnnyw $ - * - * @author Joe Hoffert - */ -//============================================================================= - -#ifndef ACE_ATM_CONNECTOR_H -#define ACE_ATM_CONNECTOR_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_ATM) - -#include "ace/ATM_Stream.h" -#include "ace/ATM_Params.h" -#include "ace/ATM_QoS.h" - -#if defined (ACE_WIN32) || defined (ACE_HAS_LINUX_ATM) -#include "ace/SOCK_Connector.h" -ACE_BEGIN_VERSIONED_NAMESPACE_DECL -typedef ACE_SOCK_Connector ATM_Connector; -ACE_END_VERSIONED_NAMESPACE_DECL -#else -#include "ace/XTI_ATM_Mcast.h" -ACE_BEGIN_VERSIONED_NAMESPACE_DECL -typedef ACE_XTI_ATM_Mcast ATM_Connector; -// Open versioned namespace, if enabled by the user. -ACE_END_VERSIONED_NAMESPACE_DECL -#endif - -// Open versioned namespace, if enabled by the user. -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_ATM_Connector - * - * @brief Defines an active connection factory for the ACE_ATM C++ - * wrappers. - */ -class ACE_Export ACE_ATM_Connector -{ -public: - // = Initialization methods. - /// Default constructor. - ACE_ATM_Connector (void); - - /** - * Actively connect and produce a @a new_stream if things go well. - * The @a remote_sap is the address that we are trying to connect - * with. The are the parameters needed for either socket - * or XTI/ATM connections. The @a timeout is the amount of time to - * wait to connect. If it's 0 then we block indefinitely. If - * *timeout == {0, 0} then the connection is done using non-blocking - * mode. In this case, if the connection can't be made immediately - * the value of -1 is returned with @c errno == EWOULDBLOCK. If - * *timeout > {0, 0} then this is the maximum amount of time to wait before - * timing out. If the time expires before the connection is made - * @c errno == ETIME. The @a local_sap is the value of local address - * to bind to. If it's the default value of then - * the user is letting the OS do the binding. If @a reuse_addr == 1 - * then the is reused, even if it hasn't been cleanedup yet. - */ - ACE_ATM_Connector (ACE_ATM_Stream &new_stream, - const ACE_ATM_Addr &remote_sap, - ACE_ATM_Params params = ACE_ATM_Params(), - ACE_ATM_QoS options = ACE_ATM_QoS(), - ACE_Time_Value *timeout = 0, - const ACE_ATM_Addr &local_sap = ACE_ATM_Addr( "", 0 ), - int reuse_addr = 0, -#if defined (ACE_WIN32) - int flags = 0, -#else - int flags = O_RDWR, -#endif /* ACE_WIN32 */ - int perms = 0); - - /** - * Actively connect and produce a @a new_stream if things go well. - * The @a remote_sap is the address that we are trying to connect - * with. The are the parameters needed for either socket - * or XTI/ATM connections. The @a timeout is the amount of time to - * wait to connect. If it's 0 then we block indefinitely. If - * *timeout == {0, 0} then the connection is done using non-blocking - * mode. In this case, if the connection can't be made immediately - * the value of -1 is returned with @c errno == EWOULDBLOCK. If - * *timeout > {0, 0} then this is the maximum amount of time to wait before - * timing out. If the time expires before the connection is made - * @c errno == ETIME. The @a local_sap is the value of local address - * to bind to. If it's the default value of then - * the user is letting the OS do the binding. If @a reuse_addr == 1 - * then the is reused, even if it hasn't been cleanedup yet. - */ - int connect (ACE_ATM_Stream &new_stream, - const ACE_ATM_Addr &remote_sap, - ACE_ATM_Params params = ACE_ATM_Params(), - ACE_ATM_QoS options = ACE_ATM_QoS(), - ACE_Time_Value *timeout = 0, - const ACE_ATM_Addr &local_sap = ACE_ATM_Addr( "", - 0 ), - int reuse_addr = 0, -#if defined (ACE_WIN32) - int flags = 0, -#else - int flags = O_RDWR, -#endif /* ACE_WIN32 */ - int perms = 0); - - /** - * Try to complete a non-blocking connection. - * If connection completion is successful then @a new_stream contains - * the connected ACE_SOCK_Stream. If @a remote_sap is non-NULL then it - * will contain the address of the connected peer. - */ - int complete (ACE_ATM_Stream &new_stream, - ACE_ATM_Addr *remote_sap, - ACE_Time_Value *tv); - - /** - * Actively add a leaf to the root (i.e., point-to-multipoint). The - * @a remote_sap is the address of the leaf that we - * are trying to add. - */ - int add_leaf (ACE_ATM_Stream ¤t_stream, - const ACE_Addr &remote_sap, - ACE_ATM_QoS &qos); - - /// Resets any event associations on this handle - bool reset_new_handle (ACE_HANDLE handle); - - // = Meta-type info - typedef ACE_ATM_Addr PEER_ADDR; - typedef ACE_ATM_Stream PEER_STREAM; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - ATM_Connector connector_; -}; - -// Open versioned namespace, if enabled by the user. -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/ATM_Connector.inl" -#endif /* __ACE_INLINE__ */ - -#endif /* ACE_HAS_ATM */ -#include /**/ "ace/post.h" -#endif /* ACE_ATM_CONNECTOR_H */ diff --git a/externals/ace/ATM_Connector.inl b/externals/ace/ATM_Connector.inl deleted file mode 100644 index 10d1623f6c3..00000000000 --- a/externals/ace/ATM_Connector.inl +++ /dev/null @@ -1,132 +0,0 @@ -// -*- C++ -*- -// -// $Id: ATM_Connector.inl 84565 2009-02-23 08:20:39Z johnnyw $ - -// Open versioned namespace, if enabled by the user. -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE void -ACE_ATM_Connector::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_ATM_Connector::dump"); -#endif /* ACE_HAS_DUMP */ -} - -ACE_INLINE -ACE_ATM_Connector::ACE_ATM_Connector (ACE_ATM_Stream &new_stream, - const ACE_ATM_Addr &remote_sap, - ACE_ATM_Params params, - ACE_ATM_QoS options, - ACE_Time_Value *timeout, - const ACE_ATM_Addr &local_sap, - int reuse_addr, - int flags, - int perms) -{ - ACE_TRACE ("ACE_ATM_Connector::ACE_ATM_Connector"); - if ((ACE_HANDLE)this->connect (new_stream, - remote_sap, - params, - options, - timeout, - local_sap, - reuse_addr, - flags, - perms) == ACE_INVALID_HANDLE - && timeout != 0 && !(errno == EWOULDBLOCK || errno == ETIME)) - ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_ATM_Stream::ACE_ATM_Stream"))); -} - -// Try to complete a non-blocking connection. - -ACE_INLINE -int -ACE_ATM_Connector::complete (ACE_ATM_Stream &new_stream, - ACE_ATM_Addr *remote_sap, - ACE_Time_Value *tv) -{ - ACE_TRACE ("ACE_ATM_Connector::complete"); -#if defined (ACE_HAS_ATM) - return connector_.complete(new_stream.get_stream(), - remote_sap, - tv); -#else - ACE_UNUSED_ARG(new_stream); - ACE_UNUSED_ARG(remote_sap); - ACE_UNUSED_ARG(tv); - return 0; -#endif -} - -ACE_INLINE -int -ACE_ATM_Connector::add_leaf (ACE_ATM_Stream ¤t_stream, - const ACE_Addr &remote_sap, - ACE_ATM_QoS &qos) -{ - ACE_TRACE ("ACE_ATM_Connector::add_leaf"); -#if defined (ACE_HAS_FORE_ATM_XTI) - return connector_.add_leaf(current_stream.get_stream(), - remote_sap, - leaf_id, - timeout); -#elif defined (ACE_HAS_FORE_ATM_WS2) - struct sockaddr_atm *saddr = (struct sockaddr_atm *)remote_sap.get_addr(); - ACE_QoS cqos = qos.get_qos(); - int addr_len = sizeof( struct sockaddr_atm ); - - ACE_QoS_Params qos_params(0, - 0, - &cqos, - 0, - (JL_SENDER_ONLY)); - - ACE_OS::printf( "ATM_Connector::add_leaf: connecting...\n" ); - - ACE_HANDLE result = ACE_OS::join_leaf(current_stream.get_handle(), - (struct sockaddr *)saddr, - addr_len, - qos_params); - - if ( result == ACE_INVALID_HANDLE ) - ACE_OS::printf( "ATM_Connector(add_leaf): connection failed, %d\n", - ::WSAGetLastError()); - - return (result != ACE_INVALID_HANDLE); -#elif defined (ACE_HAS_LINUX_ATM) - ACE_OS::printf("ATM_Connector(add_leaf): not yet implemented in Linux\n"); - - ACE_UNUSED_ARG(current_stream); - ACE_UNUSED_ARG(remote_sap); - ACE_UNUSED_ARG(leaf_id); - ACE_UNUSED_ARG(timeout); - - return 0; -#else - ACE_UNUSED_ARG(current_stream); - ACE_UNUSED_ARG(remote_sap); - ACE_UNUSED_ARG(leaf_id); - ACE_UNUSED_ARG(timeout); - return 0; -#endif -} - -ACE_INLINE -bool -ACE_ATM_Connector::reset_new_handle (ACE_HANDLE handle) -{ -#if defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0) - // Reset the event association - return ::WSAEventSelect ((SOCKET) handle, - 0, - 0); -#else /* !defined ACE_HAS_WINSOCK2 */ - ACE_UNUSED_ARG (handle); - return false; -#endif /* ACE_WIN32 */ -} - -// Close versioned namespace, if enabled by the user. -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/ATM_Params.cpp b/externals/ace/ATM_Params.cpp deleted file mode 100644 index 70a05f1d71b..00000000000 --- a/externals/ace/ATM_Params.cpp +++ /dev/null @@ -1,20 +0,0 @@ -// $Id: ATM_Params.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/ATM_Params.h" - -#if defined (ACE_HAS_ATM) - -ACE_RCSID(ace, ATM_Params, "$Id: ATM_Params.cpp 80826 2008-03-04 14:51:23Z wotte $") - -#if !defined (__ACE_INLINE__) -#include "ace/ATM_Params.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_ATM_Params) - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_ATM */ - diff --git a/externals/ace/ATM_Params.h b/externals/ace/ATM_Params.h deleted file mode 100644 index d1e8c923118..00000000000 --- a/externals/ace/ATM_Params.h +++ /dev/null @@ -1,214 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file ATM_Params.h - * - * $Id: ATM_Params.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Joe Hoffert - */ -//========================================================================== - - -#ifndef ACE_ATM_PARAMS_H -#define ACE_ATM_PARAMS_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_ATM) - -#include /**/ "ace/ACE_export.h" - -#if defined (ACE_HAS_FORE_ATM_XTI) -#include "ace/TLI.h" -#define ATM_PROTOCOL_DEFAULT 0 -typedef struct t_info Param_Info; -typedef struct netbuf Param_Udata; -#elif defined (ACE_HAS_FORE_ATM_WS2) -#include "ace/SOCK.h" -#define ATM_PROTOCOL_DEFAULT ATMPROTO_AAL5 -#define ACE_XTI_ATM_DEVICE "" -typedef int Param_Info; -typedef int Param_Udata; -#elif defined (ACE_HAS_LINUX_ATM) -#include /**/ "atm.h" -#define AF_ATM PF_ATMSVC -#define ACE_XTI_ATM_DEVICE "" -#define ATM_PROTOCOL_DEFAULT ATM_AAL5 -typedef int Param_Info; -typedef int Param_Udata; -#else -#define ACE_XTI_ATM_DEVICE "" -typedef int Param_Info; -typedef int Param_Udata; -#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_ATM_Params - * - * @brief Wrapper class that simplifies the information passed to the ATM - * enabled ACE_ATM_Connector class. - */ -class ACE_Export ACE_ATM_Params -{ -public: - /** - * Initialize the data members. This class combines options from - * ACE_SOCK_Connector (@a protocol_family, @a protocol, , - * @a protocol_info, , and @a flags) and - * ACE_TLI_Connector (, , , , and ) - * so that either mechanism can be used transparently for ATM. - */ - ACE_ATM_Params (int rw_flag = 1, - const char device[] = ACE_XTI_ATM_DEVICE, - Param_Info *info = 0, - Param_Udata *udata = 0, - int oflag = O_RDWR, - int protocol_family = AF_ATM, - int protocol = ATM_PROTOCOL_DEFAULT, - int type = -#if defined (ACE_HAS_LINUX_ATM) - SOCK_DGRAM, -#else - SOCK_RAW, -#endif /* ACE_HAS_LINUX_ATM */ - ACE_Protocol_Info *protocol_info = 0, - ACE_SOCK_GROUP g = 0, - u_long flags - = ACE_FLAG_MULTIPOINT_C_ROOT - | ACE_FLAG_MULTIPOINT_D_ROOT, // connector by default - int reuse_addr = 0); - - /// Destructor. - ~ACE_ATM_Params (); - - /// Get protocol family. - int get_protocol_family (void) const; - - /// Set protocol family. - void set_protocol_family (int); - - /// Get protocol. - int get_protocol (void) const; - - /// Set protocol. - void set_protocol (int); - - /// Get type. - int get_type (void) const; - - /// Set type. - void set_type (int); - - /// Get protocol info. - ACE_Protocol_Info *get_protocol_info( void ); - - /// Set protocol info. - void set_protocol_info( ACE_Protocol_Info *); - - /// Get socket group. - ACE_SOCK_GROUP get_sock_group( void ); - - /// Set socket group. - void set_sock_group( ACE_SOCK_GROUP ); - - /// Get socket flags. - u_long get_flags( void ); - - /// Set socket flags. - void set_flags( u_long ); - - /// Get reuse_addr flag. - int get_reuse_addr (void) const; - - /// Set reuse_addr flag. - void set_reuse_addr (int); - - /// Get device. - const char* get_device (void) const; - - /// Get info. - Param_Info* get_info (void) const; - - /// Set info. - void set_info (Param_Info *); - - /// Get r/w flag. - int get_rw_flag (void) const; - - /// Set r/w flag. - void set_rw_flag (int); - - /// Get user data. - Param_Udata* get_user_data (void) const; - - /// Set user data. - void set_user_data (Param_Udata*); - - /// Get open flag. - int get_oflag (void) const; - - /// Set open flag. - void set_oflag (int); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - /// Protocol family for sockets connections. - int protocol_family_; - - /// Protocol for sockets connections. - int protocol_; - - /// Type for opening sockets. - int type_; - - /// Information about the protocol. - ACE_Protocol_Info *protocol_info_; - - /// Socket group used (for sockets only). - ACE_SOCK_GROUP group_; - - /// Flags for sockets (for sockets only). - u_long flags_; - - /// Flag for reusing address for opening sockets. - int reuse_addr_; - - /// Device name for XTI/ATM connections. - const char *device_; - - /// Info for XTI/ATM connections. - Param_Info *info_; - - /// R/W flag for XTI/ATM connections. - int rw_flag_; - - /// User data for XTI/ATM connections. - Param_Udata *udata_; - - /// Open flag for XTI/ATM connections. - int oflag_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/ATM_Params.inl" -#endif /* __ACE_INLINE__ */ - -#endif /* ACE_HAS_ATM */ -#include /**/ "ace/post.h" -#endif /* ACE_ATM_PARAMS_H */ diff --git a/externals/ace/ATM_Params.inl b/externals/ace/ATM_Params.inl deleted file mode 100644 index de2a4d45127..00000000000 --- a/externals/ace/ATM_Params.inl +++ /dev/null @@ -1,235 +0,0 @@ -// -*- C++ -*- -// -// $Id: ATM_Params.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE void -ACE_ATM_Params::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_ATM_Params::dump"); -#endif /* ACE_HAS_DUMP */ -} - -ACE_INLINE -ACE_ATM_Params::ACE_ATM_Params (int rw_flag, - const char device[], - Param_Info *info, - Param_Udata *udata, - int oflag, - int protocol_family, - int protocol, - int type, - ACE_Protocol_Info *protocol_info, - ACE_SOCK_GROUP g, - u_long flags, - int reuse_addr) - : protocol_family_(protocol_family), - protocol_(protocol), - type_(type), - protocol_info_(protocol_info), - group_(g), - flags_(flags), - reuse_addr_(reuse_addr), - device_(device), - info_(info), - rw_flag_(rw_flag), - udata_(udata), - oflag_(oflag) -{ - ACE_TRACE ("ACE_ATM_Params::ACE_ATM_Params"); -} - -// Default dtor. -ACE_INLINE -ACE_ATM_Params::~ACE_ATM_Params (void) -{ - ACE_TRACE ("ACE_ATM_Params::~ACE_ATM_Params"); -} - -ACE_INLINE -int -ACE_ATM_Params::get_protocol_family (void) const -{ - ACE_TRACE ("ACE_ATM_Params::get_protocol_family"); - return protocol_family_; -} - -ACE_INLINE -void -ACE_ATM_Params::set_protocol_family (int family) -{ - ACE_TRACE ("ACE_ATM_Params::set_protocol_family"); - protocol_family_ = family; -} - -ACE_INLINE -int -ACE_ATM_Params::get_protocol (void) const -{ - ACE_TRACE ("ACE_ATM_Params::get_protocol"); - return protocol_; -} - -ACE_INLINE -void -ACE_ATM_Params::set_protocol (int protocol) -{ - ACE_TRACE ("ACE_ATM_Params::set_protocol"); - protocol_ = protocol; -} - -ACE_INLINE -int -ACE_ATM_Params::get_type (void) const -{ - ACE_TRACE ("ACE_ATM_Params::get_type"); - return type_; -} - -ACE_INLINE -void -ACE_ATM_Params::set_type (int type) -{ - ACE_TRACE ("ACE_ATM_Params::set_type"); - type_ = type; -} - -ACE_INLINE -ACE_Protocol_Info* -ACE_ATM_Params::get_protocol_info( void ) -{ - ACE_TRACE ("ACE_ATM_Params::get_protocol_info"); - return protocol_info_; -} - -ACE_INLINE -void -ACE_ATM_Params::set_protocol_info( ACE_Protocol_Info *protocol_info ) -{ - ACE_TRACE ("ACE_ATM_Params::set_protocol_info"); - protocol_info_ = protocol_info; -} - -ACE_INLINE -ACE_SOCK_GROUP -ACE_ATM_Params::get_sock_group( void ) -{ - ACE_TRACE ("ACE_ATM_Params::get_sock_group"); - return group_; -} - -ACE_INLINE -void -ACE_ATM_Params::set_sock_group( ACE_SOCK_GROUP g ) -{ - ACE_TRACE ("ACE_ATM_Params::set_sock_group"); - group_ = g; -} - -ACE_INLINE -u_long -ACE_ATM_Params::get_flags( void ) -{ - ACE_TRACE ("ACE_ATM_Params::get_flags"); - return flags_; -} - -ACE_INLINE -void -ACE_ATM_Params::set_flags( u_long flags) -{ - ACE_TRACE ("ACE_ATM_Params::set_flags"); - flags_ = flags; -} - -ACE_INLINE -int -ACE_ATM_Params::get_reuse_addr (void) const -{ - ACE_TRACE ("ACE_ATM_Params::get_reuse_addr"); - return reuse_addr_; -} - -ACE_INLINE -void -ACE_ATM_Params::set_reuse_addr (int reuse_addr) -{ - ACE_TRACE ("ACE_ATM_Params::set_reuse_addr"); - reuse_addr_ = reuse_addr; -} - -ACE_INLINE -const char* -ACE_ATM_Params::get_device (void) const -{ - ACE_TRACE ("ACE_ATM_Params::get_device"); - return device_; -} - -ACE_INLINE -Param_Info* -ACE_ATM_Params::get_info (void) const -{ - ACE_TRACE ("ACE_ATM_Params::get_info"); - return info_; -} - -ACE_INLINE -void -ACE_ATM_Params::set_info (Param_Info* info) -{ - ACE_TRACE ("ACE_ATM_Params::set_info"); - info_ = info; -} - -ACE_INLINE -int -ACE_ATM_Params::get_rw_flag (void) const -{ - ACE_TRACE ("ACE_ATM_Params::get_rw_flag"); - return rw_flag_; -} - -ACE_INLINE -void -ACE_ATM_Params::set_rw_flag (int rw_flag) -{ - ACE_TRACE ("ACE_ATM_Params::set_rw_flag"); - rw_flag_ = rw_flag; -} - -ACE_INLINE -Param_Udata* -ACE_ATM_Params::get_user_data (void) const -{ - ACE_TRACE ("ACE_ATM_Params::get_user_data"); - return udata_; -} - -ACE_INLINE -void -ACE_ATM_Params::set_user_data (Param_Udata *udata) -{ - ACE_TRACE ("ACE_ATM_Params::set_user_data"); - udata_ = udata; -} - -ACE_INLINE -int -ACE_ATM_Params::get_oflag (void) const -{ - ACE_TRACE ("ACE_ATM_Params::get_oflag"); - return oflag_; -} - -ACE_INLINE -void -ACE_ATM_Params::set_oflag (int oflag) -{ - ACE_TRACE ("ACE_ATM_Params::set_oflag"); - oflag_ = oflag; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/ATM_QoS.cpp b/externals/ace/ATM_QoS.cpp deleted file mode 100644 index 5f83d3a14d2..00000000000 --- a/externals/ace/ATM_QoS.cpp +++ /dev/null @@ -1,631 +0,0 @@ -// $Id: ATM_QoS.cpp 84262 2009-01-29 10:34:33Z johnnyw $ - -#include "ace/ATM_QoS.h" - -ACE_RCSID(ace, ATM_QoS, "$Id: ATM_QoS.cpp 84262 2009-01-29 10:34:33Z johnnyw $") - -#if defined (ACE_HAS_ATM) - -#if !defined (__ACE_INLINE__) -#include "ace/ATM_QoS.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2) -#define BHLI_MAGIC "FORE_ATM" -// This is line rate in cells/s for an OC-3 MM interface. -const long ACE_ATM_QoS::LINE_RATE = 353207; -const int ACE_ATM_QoS::OPT_FLAGS_CPID = 0x1; -const int ACE_ATM_QoS::OPT_FLAGS_PMP = 0x2; -const int ACE_ATM_QoS::DEFAULT_SELECTOR = 0x99; -const int ACE_ATM_QoS::DEFAULT_PKT_SIZE = 8192; -#elif defined (ACE_HAS_LINUX_ATM) -//pbrandao:for Linux: -//pbrandao:for now stick with current definitions -//pbrandao:see if later need to change -const long ACE_ATM_QoS::LINE_RATE = 353207; -const int ACE_ATM_QoS::OPT_FLAGS_CPID = 0x1; -const int ACE_ATM_QoS::OPT_FLAGS_PMP = 0x2; -const int ACE_ATM_QoS::DEFAULT_SELECTOR = 0x99; -const int ACE_ATM_QoS::DEFAULT_PKT_SIZE = 8192; -#else -const long ACE_ATM_QoS::LINE_RATE = 0L; -const int ACE_ATM_QoS::OPT_FLAGS_CPID = 0; -const int ACE_ATM_QoS::OPT_FLAGS_PMP = 0; -const int ACE_ATM_QoS::DEFAULT_SELECTOR = 0x0; -const int ACE_ATM_QoS::DEFAULT_PKT_SIZE = 0; -#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ - -ACE_ALLOC_HOOK_DEFINE(ACE_ATM_QoS) - -ACE_ATM_QoS::ACE_ATM_QoS (int pktSize) -{ - ACE_TRACE ("ACE_ATM_QoS::ACE_ATM_QoS"); -#if defined (ACE_HAS_LINUX_ATM) - ACE_OS::memset(&qos_, 0, sizeof(qos_)); - qos_.aal = ATM_PROTOCOL_DEFAULT; - qos_.rxtp.traffic_class = ATM_ANYCLASS; - qos_.rxtp.max_sdu = pktSize; - qos_.txtp.traffic_class = ATM_ANYCLASS; - qos_.txtp.max_sdu = pktSize; -#else - ACE_UNUSED_ARG (pktSize); -#endif /* ACE_HAS_LINUX_ATM */ -} - -ACE_ATM_QoS::ACE_ATM_QoS(int rate, - int pktSize) -{ - ACE_TRACE( "ACE_ATM_QoS::ACE_ATM_QoS" ); -#if defined (ACE_HAS_FORE_ATM_WS2) - AAL_PARAMETERS_IE ie_aalparams; - ATM_TRAFFIC_DESCRIPTOR_IE ie_td; - ATM_BROADBAND_BEARER_CAPABILITY_IE ie_bbc; - ATM_QOS_CLASS_IE ie_qos; - Q2931_IE *ie_ptr; - int size; - - // Setting up cbr parameters ... - ie_aalparams.AALType = AALTYPE_5; - ie_aalparams.AALSpecificParameters.AAL5Parameters.ForwardMaxCPCSSDUSize - = pktSize; // was 1516; - ie_aalparams.AALSpecificParameters.AAL5Parameters.BackwardMaxCPCSSDUSize - = pktSize; // was 1516; - ie_aalparams.AALSpecificParameters.AAL5Parameters.Mode = AAL5_MODE_MESSAGE; - ie_aalparams.AALSpecificParameters.AAL5Parameters.SSCSType = AAL5_SSCS_NULL; - - size = sizeof(Q2931_IE_TYPE) + sizeof(ULONG) + sizeof(AAL_PARAMETERS_IE); - - ie_td.Forward.PeakCellRate_CLP0 = SAP_FIELD_ABSENT; - ie_td.Forward.PeakCellRate_CLP01 = rate; - ie_td.Forward.SustainableCellRate_CLP0 = SAP_FIELD_ABSENT; - ie_td.Forward.SustainableCellRate_CLP01 = SAP_FIELD_ABSENT; - ie_td.Forward.MaxBurstSize_CLP0 = SAP_FIELD_ABSENT; - ie_td.Forward.MaxBurstSize_CLP01 = SAP_FIELD_ABSENT; - ie_td.Forward.Tagging = SAP_FIELD_ABSENT; - - ie_td.Backward.PeakCellRate_CLP0 = SAP_FIELD_ABSENT; - ie_td.Backward.PeakCellRate_CLP01 = rate; - ie_td.Backward.SustainableCellRate_CLP0 = SAP_FIELD_ABSENT; - ie_td.Backward.SustainableCellRate_CLP01 = SAP_FIELD_ABSENT; - ie_td.Backward.MaxBurstSize_CLP0 = SAP_FIELD_ABSENT; - ie_td.Backward.MaxBurstSize_CLP01 = SAP_FIELD_ABSENT; - ie_td.Backward.Tagging = SAP_FIELD_ABSENT; - - ie_td.BestEffort = 0; // Note: this must be set to zero for CBR. - - size += sizeof( Q2931_IE_TYPE ) - + sizeof( ULONG ) - + sizeof( ATM_TRAFFIC_DESCRIPTOR_IE ); - - ie_bbc.BearerClass = BCOB_X; - ie_bbc.TrafficType = TT_CBR; - ie_bbc.TimingRequirements = TR_END_TO_END; - ie_bbc.ClippingSusceptability = CLIP_NOT; - ie_bbc.UserPlaneConnectionConfig = UP_P2P; - - size += sizeof( Q2931_IE_TYPE ) - + sizeof( ULONG ) - + sizeof( ATM_BROADBAND_BEARER_CAPABILITY_IE ); - - ie_qos.QOSClassForward = QOS_CLASS1; - ie_qos.QOSClassBackward = QOS_CLASS1; // This may not be really used - // since we do only simplex data xfer. - - size += sizeof(Q2931_IE_TYPE) + sizeof(ULONG) + sizeof(ATM_QOS_CLASS_IE); - - qos_.ProviderSpecific.buf = (char *) ACE_OS::malloc(size); - if (qos_.ProviderSpecific.buf == 0) { - ACE_ERROR((LM_ERROR, - ACE_TEXT ("ACE_ATM_QoS::ACE_ATM_QoS: Unable to allocate %d bytes for qos_.ProviderSpecific.buf\n"), - size)); - return; - } - qos_.ProviderSpecific.len = size; - ACE_OS::memset(qos_.ProviderSpecific.buf, 0, size); - - ie_ptr = (Q2931_IE *) qos_.ProviderSpecific.buf; - ie_ptr->IEType = IE_AALParameters; - ie_ptr->IELength = sizeof( Q2931_IE_TYPE ) - + sizeof( ULONG ) - + sizeof( AAL_PARAMETERS_IE ); - ACE_OS::memcpy(ie_ptr->IE, &ie_aalparams, sizeof(AAL_PARAMETERS_IE)); - - ie_ptr = (Q2931_IE *) ((char *)ie_ptr + ie_ptr->IELength); - ie_ptr->IEType = IE_TrafficDescriptor; - ie_ptr->IELength = sizeof( Q2931_IE_TYPE ) - + sizeof( ULONG ) - + sizeof( ATM_TRAFFIC_DESCRIPTOR_IE ); - ACE_OS::memcpy(ie_ptr->IE, &ie_td, sizeof(ATM_TRAFFIC_DESCRIPTOR_IE)); - - ie_ptr = (Q2931_IE *) ((char *)ie_ptr + ie_ptr->IELength); - ie_ptr->IEType = IE_BroadbandBearerCapability; - ie_ptr->IELength = sizeof( Q2931_IE_TYPE ) - + sizeof( ULONG ) - + sizeof( ATM_BROADBAND_BEARER_CAPABILITY_IE ); - ACE_OS::memcpy(ie_ptr->IE, - &ie_bbc, - sizeof(ATM_BROADBAND_BEARER_CAPABILITY_IE)); - - ie_ptr = (Q2931_IE *) ((char *)ie_ptr + ie_ptr->IELength); - ie_ptr->IEType = IE_QOSClass; - ie_ptr->IELength = sizeof( Q2931_IE_TYPE ) - + sizeof( ULONG ) - + sizeof( ATM_QOS_CLASS_IE ); - ACE_OS::memcpy(ie_ptr->IE, &ie_qos, sizeof(ATM_QOS_CLASS_IE)); - - // qos_.SendingFlowspec.TokenRate = 0xffffffff; - // qos_.SendingFlowspec.TokenBucketSize = 0xffffffff; - // qos_.SendingFlowspec.PeakBandwidth = 0xffffffff; - // qos_.SendingFlowspec.Latency = 0xffffffff; - // qos_.SendingFlowspec.DelayVariation = 0xffffffff; - // qos_.SendingFlowspec.ServiceType = SERVICETYPE_BESTEFFORT; - // This will most probably be ignored by the service provider. - // qos_.SendingFlowspec.MaxSduSize = 0xffffffff; - // qos_.SendingFlowspec.MinimumPolicedSize = 0xffffffff; - - // qos_.ReceivingFlowspec.TokenRate = 0xffffffff; - // qos_.ReceivingFlowspec.TokenBucketSize = 0xffffffff; - // qos_.ReceivingFlowspec.PeakBandwidth = 0xffffffff; - // qos_.ReceivingFlowspec.Latency = 0xffffffff; - // qos_.ReceivingFlowspec.DelayVariation = 0xffffffff; - // qos_.ReceivingFlowspec.ServiceType = SERVICETYPE_BESTEFFORT; - // This will most probably be ignored by the service provider. - // qos_.ReceivingFlowspec.MaxSduSize = 0xffffffff; - // qos_.ReceivingFlowspec.MinimumPolicedSize = 0; - - ACE_Flow_Spec send_fspec( 0xffffffff, - 0xffffffff, - 0xffffffff, - 0xffffffff, - 0xffffffff, - SERVICETYPE_BESTEFFORT, - // This will most probably ignored by SP. - 0xffffffff, - 0xffffffff, - 15, - ACE_DEFAULT_THREAD_PRIORITY ), - recv_fspec( 0xffffffff, - 0xffffffff, - 0xffffffff, - 0xffffffff, - 0xffffffff, - SERVICETYPE_BESTEFFORT, - // This will most probably ignored by SP. - 0xffffffff, - 0, - 15, - ACE_DEFAULT_THREAD_PRIORITY ); - - qos_.sending_flowspec (send_fspec); - qos_.receiving_flowspec (recv_fspec); -#elif defined (ACE_HAS_FORE_ATM_XTI) - ACE_UNUSED_ARG (rate); - ACE_UNUSED_ARG (pktSize); -#elif defined (ACE_HAS_LINUX_ATM) - ACE_OS::memset(&qos_, - 0, - sizeof(qos_)); - qos_.aal = ATM_PROTOCOL_DEFAULT; - qos_.rxtp.max_sdu = pktSize; - - if (rate > 0) { - qos_.rxtp.pcr = rate; - qos_.rxtp.traffic_class = ATM_CBR; - qos_.txtp.traffic_class = ATM_CBR; - qos_.txtp.pcr = rate; - } - else { - qos_.rxtp.traffic_class = ATM_UBR; - qos_.txtp.traffic_class = ATM_UBR; - } - - qos_.txtp.max_sdu = pktSize; -#else - ACE_UNUSED_ARG (rate); -#endif /* ACE_HAS_FORE_ATM_WS2 || ACE_HAS_FORE_ATM_XTI || ACE_HAS_LINUX_ATM */ -} - -void -ACE_ATM_QoS::set_cbr_rate (int rate, - int pktSize) -{ - ACE_TRACE ("ACE_ATM_QoS::set_cbr_rate"); -#if defined (ACE_HAS_FORE_ATM_WS2) - /* - AAL_PARAMETERS_IE ie_aalparams; - ATM_TRAFFIC_DESCRIPTOR_IE ie_td; - ATM_BROADBAND_BEARER_CAPABILITY_IE ie_bbc; - ATM_QOS_CLASS_IE ie_qos; - Q2931_IE *ie_ptr; - int size; - */ - - ACE_OS::printf( "ATM_QoS(set_cbr_rate): set rate to %d c/s\n", rate ); - - // Setting up cbr parameters ... - /* - FORE has changed this - we no longer specify QoS this way - ie_aalparams.AALType = AALTYPE_5; - ie_aalparams.AALSpecificParameters.AAL5Parameters.ForwardMaxCPCSSDUSize - = pktSize; // was 1516; - ie_aalparams.AALSpecificParameters.AAL5Parameters.BackwardMaxCPCSSDUSize - = pktSize; // was 1516; - ie_aalparams.AALSpecificParameters.AAL5Parameters.Mode = AAL5_MODE_MESSAGE; - ie_aalparams.AALSpecificParameters.AAL5Parameters.SSCSType = AAL5_SSCS_NULL; - - size = sizeof(Q2931_IE_TYPE) + sizeof(ULONG) + sizeof(AAL_PARAMETERS_IE); - - ie_td.Forward.PeakCellRate_CLP0 = SAP_FIELD_ABSENT; - ie_td.Forward.PeakCellRate_CLP01 = rate; - ie_td.Forward.SustainableCellRate_CLP0 = SAP_FIELD_ABSENT; - ie_td.Forward.SustainableCellRate_CLP01 = SAP_FIELD_ABSENT; - ie_td.Forward.MaxBurstSize_CLP0 = SAP_FIELD_ABSENT; - ie_td.Forward.MaxBurstSize_CLP01 = SAP_FIELD_ABSENT; - ie_td.Forward.Tagging = SAP_FIELD_ABSENT; - - ie_td.Backward.PeakCellRate_CLP0 = SAP_FIELD_ABSENT; - ie_td.Backward.PeakCellRate_CLP01 = rate; - ie_td.Backward.SustainableCellRate_CLP0 = SAP_FIELD_ABSENT; - ie_td.Backward.SustainableCellRate_CLP01 = SAP_FIELD_ABSENT; - ie_td.Backward.MaxBurstSize_CLP0 = SAP_FIELD_ABSENT; - ie_td.Backward.MaxBurstSize_CLP01 = SAP_FIELD_ABSENT; - ie_td.Backward.Tagging = SAP_FIELD_ABSENT; - - ie_td.BestEffort = 0; // Note: this must be set to zero for CBR. - - size += sizeof( Q2931_IE_TYPE ) + - sizeof( ULONG ) + - sizeof( ATM_TRAFFIC_DESCRIPTOR_IE ); - - ie_bbc.BearerClass = BCOB_X; - ie_bbc.TrafficType = TT_CBR; - ie_bbc.TimingRequirements = TR_END_TO_END; - ie_bbc.ClippingSusceptability = CLIP_NOT; - ie_bbc.UserPlaneConnectionConfig = UP_P2P; - - size += sizeof(Q2931_IE_TYPE) + - sizeof(ULONG) + - sizeof(ATM_BROADBAND_BEARER_CAPABILITY_IE); - - ie_qos.QOSClassForward = QOS_CLASS1; - ie_qos.QOSClassBackward = QOS_CLASS1; // This may not be really used - // since we only simplex data xfer. - - size += sizeof(Q2931_IE_TYPE) + sizeof(ULONG) + sizeof(ATM_QOS_CLASS_IE); - - qos_.ProviderSpecific.buf = (char *) ACE_OS::malloc(size); - if (qos_.ProviderSpecific.buf == 0) { - ACE_ERROR((LM_ERROR, - ACE_TEXT ("ACE_ATM_QoS::ACE_ATM_QoS: Unable to allocate %d bytes for qos_.ProviderSpecific.buf\n"), - size)); - return; - } - qos_.ProviderSpecific.len = size; - ACE_OS::memset(qos_.ProviderSpecific.buf, 0, size); - - ie_ptr = (Q2931_IE *) qos_.ProviderSpecific.buf; - ie_ptr->IEType = IE_AALParameters; - ie_ptr->IELength = sizeof( Q2931_IE_TYPE ) + - sizeof( ULONG ) + - sizeof( AAL_PARAMETERS_IE ); - ACE_OS::memcpy(ie_ptr->IE, &ie_aalparams, sizeof(AAL_PARAMETERS_IE)); - - ie_ptr = (Q2931_IE *) ((char *)ie_ptr + ie_ptr->IELength); - ie_ptr->IEType = IE_TrafficDescriptor; - ie_ptr->IELength = sizeof( Q2931_IE_TYPE ) + - sizeof( ULONG ) + - sizeof( ATM_TRAFFIC_DESCRIPTOR_IE ); - ACE_OS::memcpy(ie_ptr->IE, &ie_td, sizeof(ATM_TRAFFIC_DESCRIPTOR_IE)); - - ie_ptr = (Q2931_IE *) ((char *)ie_ptr + ie_ptr->IELength); - ie_ptr->IEType = IE_BroadbandBearerCapability; - ie_ptr->IELength = sizeof( Q2931_IE_TYPE ) + - sizeof( ULONG ) + - sizeof( ATM_BROADBAND_BEARER_CAPABILITY_IE ); - ACE_OS::memcpy( ie_ptr->IE, - &ie_bbc, - sizeof( ATM_BROADBAND_BEARER_CAPABILITY_IE )); - - ie_ptr = (Q2931_IE *) ((char *)ie_ptr + ie_ptr->IELength); - ie_ptr->IEType = IE_QOSClass; - ie_ptr->IELength = sizeof(Q2931_IE_TYPE) + sizeof(ULONG) + - sizeof(ATM_QOS_CLASS_IE); - ACE_OS::memcpy(ie_ptr->IE, &ie_qos, sizeof(ATM_QOS_CLASS_IE)); - */ - - const int BYTES_PER_ATM_CELL = 53; - ACE_OS::memset(&qos_, 0, sizeof(ATM_QoS)); - // Setting the token rate sets the minimum rate. 3 Mbits/sec seems too high. - // Certainly for Vaudeville audio, we only need about 1000 c/s which is - // 424000 bits/sec which is 53000 bytes/sec. - //qos_.SendingFlowspec.TokenRate = 3*(1024*128); // 3Mbits/sec - qos_.SendingFlowspec.TokenRate = 53000; // 1000 cells/sec - qos_.SendingFlowspec.TokenBucketSize = 32*1024; // our block size - //ourQos.SendingFlowspec.PeakBandwidth = ourQos.SendingFlowspec.TokenRate; - qos_.SendingFlowspec.ServiceType = SERVICETYPE_GUARANTEED; - // Peak bandwidth is in bytes/sec. The rate is specified in cells/sec so - // we need to convert from cells/sec to bytes/sec (i.e., multiply by 53). - qos_.SendingFlowspec.PeakBandwidth = rate * BYTES_PER_ATM_CELL; - qos_.SendingFlowspec.Latency = -1; // we don't care too much - qos_.SendingFlowspec.DelayVariation = -1; // we don't care too much - // no provider-specific data allowed on ATM - qos_.ProviderSpecific.buf=0; - qos_.ProviderSpecific.len=0; - // unidirectional P2MP; we don't need to setup the Receiving flowspec - - //qos_.SendingFlowspec.TokenRate = 0xffffffff; - //qos_.SendingFlowspec.TokenBucketSize = 0xffffffff; - //qos_.SendingFlowspec.PeakBandwidth = 0xffffffff; - //qos_.SendingFlowspec.Latency = 0xffffffff; - //qos_.SendingFlowspec.DelayVariation = 0xffffffff; - //qos_.SendingFlowspec.ServiceType = SERVICETYPE_BESTEFFORT; - // This will most probably be ignored by the service provider. - //qos_.SendingFlowspec.MaxSduSize = 0xffffffff; - //qos_.SendingFlowspec.MinimumPolicedSize = 0xffffffff; - - //qos_.ReceivingFlowspec.TokenRate = 0xffffffff; - //qos_.ReceivingFlowspec.TokenBucketSize = 0xffffffff; - //qos_.ReceivingFlowspec.PeakBandwidth = 0xffffffff; - //qos_.ReceivingFlowspec.Latency = 0xffffffff; - //qos_.ReceivingFlowspec.DelayVariation = 0xffffffff; - //qos_.ReceivingFlowspec.ServiceType = SERVICETYPE_BESTEFFORT; - // This will most probably be ignored by the service provider. - //qos_.ReceivingFlowspec.MaxSduSize = 0xffffffff; - //qos_.ReceivingFlowspec.MinimumPolicedSize = 0; - - /* - ACE_Flow_Spec send_fspec( 0xffffffff, - 0xffffffff, - 0xffffffff, - 0xffffffff, - 0xffffffff, - SERVICETYPE_BESTEFFORT, - // This will most probably ignored by SP. - 0xffffffff, - 0xffffffff, - 15, - ACE_DEFAULT_THREAD_PRIORITY ), - recv_fspec( 0xffffffff, - 0xffffffff, - 0xffffffff, - 0xffffffff, - 0xffffffff, - SERVICETYPE_BESTEFFORT, - // This will most probably ignored by SP. - 0xffffffff, - 0, - 15, - ACE_DEFAULT_THREAD_PRIORITY ); - - qos_.sending_flowspec( send_fspec ); - qos_.receiving_flowspec( recv_fspec ); - */ -#elif defined (ACE_HAS_FORE_ATM_XTI) - ACE_UNUSED_ARG (rate); - ACE_UNUSED_ARG (pktSize); -#elif defined (ACE_HAS_LINUX_ATM) - ACE_UNUSED_ARG (pktSize); - - qos_.rxtp.traffic_class = ATM_CBR; - qos_.rxtp.pcr = rate; - qos_.txtp.traffic_class = ATM_CBR; - qos_.txtp.pcr = rate; -#else - ACE_UNUSED_ARG (rate); -#endif /* ACE_HAS_FORE_ATM_WS2 || ACE_HAS_FORE_ATM_XTI || ACE_HAS_LINUX_ATM */ -} - -void -ACE_ATM_QoS::set_rate (ACE_HANDLE fd, - int rate, - int flags) -{ - ACE_TRACE ("ACE_ATM_QoS::set_rate"); -#if defined (ACE_HAS_FORE_ATM_WS2) || defined (ACE_HAS_LINUX_ATM) - set_cbr_rate( rate ); - - ACE_UNUSED_ARG( fd ); - ACE_UNUSED_ARG( flags ); -#elif defined (ACE_HAS_FORE_ATM_XTI) - long optlen = 0; - qos_.buf = construct_options(fd, - rate, - flags, - &optlen); - qos_.len = optlen; -#else - ACE_UNUSED_ARG (rate); -#endif /* ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM || ACE_HAS_FORE_ATM_XTI */ -} - -char* -ACE_ATM_QoS::construct_options (ACE_HANDLE fd, - int rate, - int flags, - long *len) -{ -#if defined (ACE_HAS_FORE_ATM_WS2) || defined (ACE_HAS_LINUX_ATM) - ACE_UNUSED_ARG (fd); - ACE_UNUSED_ARG (rate); - ACE_UNUSED_ARG (flags); - ACE_UNUSED_ARG (len); - return 0; -#elif defined (ACE_HAS_FORE_ATM_XTI) - struct t_opthdr *popt; - char *buf; - int qos_cells; - struct t_info info; - - if (ACE_OS::t_getinfo (fd, &info) == -1) - { - ACE_OS::t_error ("t_getinfo"); - return 0; - } - - buf = (char *) ACE_OS::malloc (info.options); - - if (buf == 0) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("Unable to allocate %d bytes for options\n"), - info.options), - 0); - - popt = (struct t_opthdr *) buf; - - if (flags & OPT_FLAGS_CPID) - { - // This constructs the T_ATM_ORIG_ADDR option, which is used to - // signal the UNI 3.1 Calling Party ID Information Element. - t_atm_addr *source_addr; - - popt->len = sizeof (struct t_opthdr) + sizeof (t_atm_addr); - popt->level = T_ATM_SIGNALING; - popt->name = T_ATM_ORIG_ADDR; - popt->status = 0; - - source_addr = - (t_atm_addr *)((char *) popt + sizeof (struct t_opthdr)); - - source_addr->address_format = T_ATM_ENDSYS_ADDR; - source_addr->address_length = ATMNSAP_ADDR_LEN; - - ATMSAPAddress local_addr; - struct t_bind boundaddr; - - boundaddr.addr.maxlen = sizeof(local_addr); - boundaddr.addr.buf = (char *) &local_addr; - - //if (ACE_OS::t_getprotaddr(fd, &boundaddr, 0) < 0) { - if (ACE_OS::t_getname(fd, - &boundaddr.addr, - LOCALNAME) < 0) - { - ACE_OS::t_error("t_getname (local_address)"); - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("Can't get local address!\n"))); - ACE_OS::free (buf); - return 0; - } - - ACE_OS::memcpy(source_addr->address, - local_addr.sap.t_atm_sap_addr.address, - ATMNSAP_ADDR_LEN); - - popt = T_OPT_NEXTHDR (buf, info.options , popt); - } - - // This constructs all options necessary (bearer cap., QoS, and - // Traffic Descriptor) to signal for a CBR connection with the - // specified QoS in kbit/sec., and/or specify a PMP connection. - - // For FORE 200e cards, the adapter shapes traffic to CBR with rate - // equal to PCR CLP=0+1 (traffic.forward.PCR_all_traffic) - - qos_cells = (rate * 1000) / (48*8); - - if ((qos_cells > 0 && qos_cells < LINE_RATE) - || (ACE_BIT_ENABLED (flags, OPT_FLAGS_PMP))) - { - struct t_atm_bearer *bearer; - struct t_atm_traffic *traffic; - - // T_ATM_BEARER_CAP: Broadband bearer capability - popt->len = sizeof (struct t_opthdr) + sizeof (struct t_atm_bearer); - popt->level = T_ATM_SIGNALING; - popt->name = T_ATM_BEARER_CAP; - popt->status = 0; - - bearer = (struct t_atm_bearer *)((char *) popt + - sizeof (struct t_opthdr)); - bearer->bearer_class = T_ATM_CLASS_X; - - if (qos_cells) - { - bearer->traffic_type = T_ATM_CBR; - bearer->timing_requirements = T_ATM_END_TO_END; - } - else - { - bearer->traffic_type = 0; // UBR - bearer->timing_requirements = 0; - } - bearer->clipping_susceptibility = T_ATM_NULL; - - if (ACE_BIT_ENABLED (flags, OPT_FLAGS_PMP)) - bearer->connection_configuration = T_ATM_1_TO_MANY; - else - bearer->connection_configuration = T_ATM_1_TO_1; - - popt = T_OPT_NEXTHDR (buf, info.options, popt); - - // T_ATM_TRAFFIC: traffic descriptor - popt->len = sizeof (struct t_opthdr) + sizeof (struct t_atm_traffic); - popt->level = T_ATM_SIGNALING; - popt->name = T_ATM_TRAFFIC; - popt->status = 0; - - traffic = (struct t_atm_traffic *)((char *) popt + - sizeof (struct t_opthdr)); - - traffic->forward.PCR_high_priority = T_ATM_ABSENT; - traffic->forward.PCR_all_traffic = qos_cells ? qos_cells : LINE_RATE; - traffic->forward.SCR_high_priority = T_ATM_ABSENT; - traffic->forward.SCR_all_traffic = T_ATM_ABSENT; - traffic->forward.MBS_high_priority = T_ATM_ABSENT; - traffic->forward.MBS_all_traffic = T_ATM_ABSENT; - traffic->forward.tagging = T_NO; - - traffic->backward.PCR_high_priority = T_ATM_ABSENT; - traffic->backward.PCR_all_traffic = - (ACE_BIT_ENABLED (flags, OPT_FLAGS_PMP)) - ? 0 : qos_cells ? qos_cells : LINE_RATE; - traffic->backward.SCR_high_priority = T_ATM_ABSENT; - traffic->backward.SCR_all_traffic = T_ATM_ABSENT; - traffic->backward.MBS_high_priority = T_ATM_ABSENT; - traffic->backward.MBS_all_traffic = T_ATM_ABSENT; - traffic->backward.tagging = T_NO; - - traffic->best_effort = qos_cells ? T_NO : T_YES; - - popt = T_OPT_NEXTHDR (buf, - info.options, - popt); - } - - if (qos_cells > 0 && qos_cells < LINE_RATE) - { - struct t_atm_qos *qos; - - // T_ATM_QOS: Quality of Service - popt->len = sizeof (struct t_opthdr) + sizeof (struct t_atm_qos); - popt->level = T_ATM_SIGNALING; - popt->name = T_ATM_QOS; - popt->status = 0; - - qos = (struct t_atm_qos *)((char *) popt + sizeof (struct t_opthdr)); - qos->coding_standard = T_ATM_ITU_CODING; - qos->forward.qos_class = T_ATM_QOS_CLASS_1; - qos->backward.qos_class = T_ATM_QOS_CLASS_1; - - popt = T_OPT_NEXTHDR (buf, info.options, popt); - } - - // Return actual size of options and option buffer to user. - *len = (char *) popt - buf; - - return buf; -#else - ACE_UNUSED_ARG (fd); - ACE_UNUSED_ARG (rate); - ACE_UNUSED_ARG (flag); - ACE_UNUSED_ARG (len); - return 0; -#endif /* ACE_HAS_FORE_ATM_WS2 */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_ATM */ - diff --git a/externals/ace/ATM_QoS.h b/externals/ace/ATM_QoS.h deleted file mode 100644 index 4e35f3fddb4..00000000000 --- a/externals/ace/ATM_QoS.h +++ /dev/null @@ -1,115 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file ATM_QoS.h - * - * $Id: ATM_QoS.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Joe Hoffert - */ -//========================================================================== - - -#ifndef ACE_ATM_QoS_H -#define ACE_ATM_QoS_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined(ACE_LACKS_PRAGMA_ONCE) -#pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_ATM) - -#if defined (ACE_HAS_FORE_ATM_WS2) -ACE_BEGIN_VERSIONED_NAMESPACE_DECL -// just map to WS2 GQOS struct -typedef ACE_QoS ATM_QoS; -ACE_END_VERSIONED_NAMESPACE_DECL -#elif defined (ACE_HAS_FORE_ATM_XTI) -ACE_BEGIN_VERSIONED_NAMESPACE_DECL -typedef struct netbuf ATM_QoS; -ACE_END_VERSIONED_NAMESPACE_DECL -#elif defined (ACE_HAS_LINUX_ATM) -#include /**/ "atm.h" -#include "ace/ATM_Params.h" -ACE_BEGIN_VERSIONED_NAMESPACE_DECL -typedef struct atm_qos ATM_QoS; -ACE_END_VERSIONED_NAMESPACE_DECL -#else -ACE_BEGIN_VERSIONED_NAMESPACE_DECL -typedef int ATM_QoS; -ACE_END_VERSIONED_NAMESPACE_DECL -#endif /* ACE_HAS_FORE_ATM_WS2 || ACE_HAS_FORE_ATM_XTI || ACE_HAS_LINUX_ATM */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_ATM_QoS - * - * @brief Define the QoS parameters for ATM - * - * This class wraps up QoS parameters for both ATM/XTI and - * ATM/WinSock2 to make the mechanism for the ATM protocol - * transparent. - */ -class ACE_Export ACE_ATM_QoS -{ -public: - // Constants used for ATM options - static const long LINE_RATE; - static const int OPT_FLAGS_CPID; - static const int OPT_FLAGS_PMP; - static const int DEFAULT_SELECTOR; - static const int DEFAULT_PKT_SIZE; - - // = Initializattion and termination methods. - /// Default constructor. - ACE_ATM_QoS(int = DEFAULT_PKT_SIZE); - - /// Constructor with a CBR rate. - ACE_ATM_QoS(int, - int = DEFAULT_PKT_SIZE); - - ~ACE_ATM_QoS (); - - /// Set the rate. - void set_rate (ACE_HANDLE, - int, - int); - - /// Set CBR rate in cells per second. - void set_cbr_rate (int, - int = DEFAULT_PKT_SIZE); - - /// Get ATM_QoS struct. - ATM_QoS get_qos (void); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - /// Construct QoS options. - char* construct_options(ACE_HANDLE, - int, - int, - long*); - -private: - ATM_QoS qos_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/ATM_QoS.inl" -#endif /* __ACE_INLINE__ */ - -#endif /* ACE_HAS_ATM */ -#include /**/ "ace/post.h" -#endif /* ACE_ATM_QoS_H */ diff --git a/externals/ace/ATM_QoS.inl b/externals/ace/ATM_QoS.inl deleted file mode 100644 index 52b5211190d..00000000000 --- a/externals/ace/ATM_QoS.inl +++ /dev/null @@ -1,29 +0,0 @@ -// -*- C++ -*- -// -// $Id: ATM_QoS.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE void -ACE_ATM_QoS::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_ATM_QoS::dump"); -#endif /* ACE_HAS_DUMP */ -} - -ACE_INLINE -ACE_ATM_QoS::~ACE_ATM_QoS () -{ - ACE_TRACE ("ACE_ATM_QoS::~ACE_ATM_QoS"); -} - -ACE_INLINE -ATM_QoS -ACE_ATM_QoS::get_qos (void) -{ - ACE_TRACE ("ACE_ATM_QoS::get_qos"); - return qos_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/ATM_Stream.cpp b/externals/ace/ATM_Stream.cpp deleted file mode 100644 index a9dc0461fa2..00000000000 --- a/externals/ace/ATM_Stream.cpp +++ /dev/null @@ -1,290 +0,0 @@ -// $Id: ATM_Stream.cpp 84262 2009-01-29 10:34:33Z johnnyw $ - -#include "ace/ATM_Stream.h" - -ACE_RCSID (ace, ATM_Stream, "$Id: ATM_Stream.cpp 84262 2009-01-29 10:34:33Z johnnyw $") - -#if defined (ACE_HAS_ATM) - -#if !defined (__ACE_INLINE__) -#include "ace/ATM_Stream.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE (ACE_ATM_Stream) - -char* -ACE_ATM_Stream::get_peer_name (void) const -{ - ACE_TRACE ("ACE_ATM_Stream::get_peer_name"); -#if defined (ACE_HAS_FORE_ATM_XTI) - // // Use t_getprotaddr for XTI/ATM - // struct t_bind *localaddr - // = (struct t_bind *) ACE_OS::t_alloc (get_handle (), - // T_BIND, - // T_ADDR); - // struct t_bind *peeraddr - // = (struct t_bind *) ACE_OS::t_alloc (get_handle (), - // T_BIND, - // T_ADDR); - // ::t_getprotaddr (get_handle (), - // localaddr, - // peeraddr); - - // char* connected_name = (char*) ACE_OS::malloc (peeraddr->addr.len + 1); - // ACE_OS::strcpy (connected_name, - // peeraddr->addr.buf); - // ACE_OS::t_free ((char *) localaddr, - // T_BIND); - // ACE_OS::t_free ((char *) peeraddr, - // T_BIND); - // return (connected_name); - -#error "This doesn't seem to work. May need to jimmy-rig something with the" -#error "/etc/xti_hosts file - Ugh!" - - ACE_ATM_Addr sa; - struct netbuf name; - name.maxlen = sa.get_size (); - name.buf = (char *) sa.get_addr (); - ACE_OS::t_getname (this->get_handle (), &name, REMOTENAME); - // ACE_OS::ioctl (this->get_handle (), - // TI_GETPEERNAME, - // &name); - return (name.buf); - -#elif defined (ACE_HAS_FORE_ATM_WS2) - // Use getpeername for WinSock2. - struct sockaddr_atm name; - ACE_OS::memset (&name, 0, sizeof (name)); - int nameSize = sizeof (name); - - if (ACE_OS::getpeername (this->get_handle (), - (struct sockaddr *) &name, - &nameSize) != 0) { - return 0; - } - - char buffer[256]; - for (unsigned int index = 0; index < ATM_ADDR_SIZE - 1; index++) { - buffer[ index * 3 ] = '\0'; - ACE_OS::sprintf (buffer, "%s%02x.", buffer, name.satm_number.Addr[ index ]); - } - buffer[ (ATM_ADDR_SIZE - 1) * 3 ] = '\0'; - ACE_OS::sprintf (buffer, "%s%02x.", buffer, 0); - buffer[ ATM_ADDR_SIZE * 3 - 1 ] = '\0'; - for (index = 0; index < ACE_OS::strlen (buffer); ++index) - buffer[index] = ACE_OS::ace_tolower (buffer[index]); - - ifstream atm_hosts ("C:/WINNT/atmhosts"); - assert (atm_hosts.is_open ()); - - // Find the host address in the ATM hosts file and return the - // host name - char line[256]; - char *host_ptr, *host_name = 0; - ACE_NEW_RETURN (host_name, char[256], 0); - while (!atm_hosts.eof ()) { - atm_hosts.getline (line, 256); - // Convert the line to lower case to ease comparison - for (index = 0; index < ACE_OS::strlen (line); ++index) - line[index] = ACE_OS::ace_tolower (line[index]); - if (ACE_OS::strstr (line, buffer) != 0) - { - char *strtok_p; - // Grab the second token which is the host name - ACE_OS::strtok_r (line, " \t", &strtok_p); - host_ptr = ACE_OS::strtok (0, " \t", &strtok_p); - ACE_OS::strcpy (host_name, host_ptr); - break; - } - } - - return host_name; -#elif defined (ACE_HAS_LINUX_ATM) - ATM_Addr name; - int nameSize = sizeof (name.sockaddratmsvc); - - if (ACE_OS::getpeername (this->get_handle (), - (struct sockaddr *) & (name.sockaddratmsvc), - &nameSize) < 0) { - ACE_OS::perror ("ACE_ATM_Stream (get_peer_name) : "); - return 0; - } - - static ACE_TCHAR buffer[MAX_ATM_ADDR_LEN + 1]; - int total_len; - if ((total_len = atm2text (buffer,sizeof buffer, - (struct sockaddr *) & (name.sockaddratmsvc), - A2T_PRETTY|A2T_NAME)) < 0) { - ACE_DEBUG ((LM_DEBUG,ACE_TEXT ("ACE_ATM_Stream (get_peer_name) :%d"),errno)); - return 0; - } - - return (char*) buffer; -#else - return 0; -#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ -} - -ACE_HANDLE -ACE_ATM_Stream::get_handle (void) const -{ - ACE_TRACE ("ACE_ATM_Stream::get_handle"); -#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2) || defined (ACE_HAS_LINUX_ATM) - return stream_.get_handle (); -#else - return 0; -#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ -} - -int -ACE_ATM_Stream::get_vpi_vci (ACE_UINT16 &vpi, - ACE_UINT16 &vci) const -{ - ACE_TRACE ("ACE_ATM_Stream::get_vpi_vci"); -#if defined (ACE_HAS_FORE_ATM_XTI) - struct t_atm_conn_prop conn_prop; - char* connect_opts = (char *) &conn_prop; - int opt_size = sizeof (t_atm_conn_prop); - struct t_info info; - struct t_optmgmt opt_req, opt_ret; - - if (ACE_OS::t_getinfo (stream_.get_handle (), - &info) < 0) - { - ACE_OS::t_error ("t_getinfo"); - return -1; - } - - char *buf_req = (char *) ACE_OS::malloc (info.options); - if (buf_req == 0) - { - ACE_OS::fprintf (stderr, - "Unable to allocate %ld bytes for options\n", - info.options); - return -1; - } - - char *buf_ret = (char *) ACE_OS::malloc (info.options); - if (buf_ret == 0) - { - ACE_OS::fprintf (stderr, - "Unable to allocate %ld bytes for options\n", - info.options); - return -1; - } - - ACE_OS::memset (&opt_req, 0, sizeof (opt_req)); - ACE_OS::memset (&opt_ret, 0, sizeof (opt_ret)); - - struct t_opthdr *popt = (struct t_opthdr *) buf_req; - struct t_opthdr *popt_ret = (struct t_opthdr *) buf_ret; - - popt->len= sizeof (struct t_opthdr) + opt_size; - - // We are only concerned with SVCs so no other check or values are needed - // here. - popt->level = T_ATM_SIGNALING; - popt->name = T_ATM_CONN_PROP; - popt->status = 0; - - opt_req.opt.len = popt->len; - opt_req.opt.buf = (char *) popt; - opt_req.flags = T_CURRENT; - - popt = T_OPT_NEXTHDR (buf_req, - info.options, - popt); - opt_ret.opt.maxlen = info.options; - opt_ret.opt.buf = (char *) popt_ret; - - if (ACE_OS::t_optmgmt (stream_.get_handle (), - &opt_req, - &opt_ret) < 0) { - ACE_OS::t_error ("t_optmgmt"); - return -1; - } - - ACE_OS::memcpy (connect_opts, - (char *) popt_ret + sizeof (struct t_opthdr), - opt_size); - - ACE_OS::free (buf_ret); - ACE_OS::free (buf_req); - - vpi = conn_prop.vpi; - vci = conn_prop.vci; - return 0; -#elif defined (ACE_HAS_FORE_ATM_WS2) - ATM_CONNECTION_ID connID; - DWORD bytes = 0; - - if (::WSAIoctl ((int) this -> get_handle (), - SIO_GET_ATM_CONNECTION_ID, - 0, - 0, - (LPVOID) &connID, - sizeof (ATM_CONNECTION_ID), - &bytes, - 0, - 0) - == SOCKET_ERROR) { - ACE_OS::printf ("Error: WSAIoctl %d\n", WSAGetLastError ()); - } - - vpi = (ACE_UINT16) connID.VPI; - vci = (ACE_UINT16) connID.VCI; - - return 0; -#elif defined (ACE_HAS_LINUX_ATM) -#if defined (SO_ATMPVC) /* atm version>=0.62 */ - struct sockaddr_atmpvc mypvcaddr; - int addrpvclen = sizeof (mypvcaddr); - if (ACE_OS::getsockopt (stream_.get_handle (), - SOL_ATM, - SO_ATMPVC, - reinterpret_cast (&mypvcaddr), - &addrpvclen) < 0) { - ACE_DEBUG (LM_DEBUG, - ACE_TEXT ("ACE_ATM_Stream::get_vpi_vci: getsockopt %d\n"), - errno); - return -1; - } - vpi = (ACE_UINT16) mypvcaddr.sap_addr.vpi; - vci = (ACE_UINT16) mypvcaddr.sap_addr.vci; - - return 0; -#elif defined (SO_VCID) /* patch for atm version 0.59 */ - struct atm_vcid mypvcid; - int pvcidlen = sizeof (mypvcid); - if (ACE_OS::getsockopt (stream_.get_handle (), - SOL_ATM,SO_VCID, - reinterpret_cast (&mypvcid), - &pvcidlen) < 0) { - ACE_DEBUG (LM_DEBUG, - ACE_TEXT ("ACE_ATM_Stream::get_vpi_vci: getsockopt %d\n"), - errno); - return -1; - } - vpi = (ACE_UINT16) mypvcid.vpi; - vci = (ACE_UINT16) mypvcid.vci; - - return 0; -#else - ACE_DEBUG (LM_DEBUG, - ACE_TEXT ("ACE_ATM_Stream::get_vpi_vci: Not implemented in this ATM version. Update to >= 0.62\n Or patch 0.59")); - ACE_UNUSED_ARG (vci); - ACE_UNUSED_ARG (vpi); - - return -1; -#endif /* SO_ATMPVC || SO_VCID */ -#else - return -1; -#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 || ACE_HAS_LINUX_ATM */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_ATM */ diff --git a/externals/ace/ATM_Stream.h b/externals/ace/ATM_Stream.h deleted file mode 100644 index 41ffb0da32e..00000000000 --- a/externals/ace/ATM_Stream.h +++ /dev/null @@ -1,107 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file ATM_Stream.h - * - * $Id: ATM_Stream.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Joe Hoffert - */ -//============================================================================= - - -#ifndef ACE_ATM_STREAM_H -#define ACE_ATM_STREAM_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_ATM) - -#include "ace/ATM_Addr.h" -#include "ace/ATM_Params.h" - -#if defined (ACE_WIN32) -#include "ace/SOCK_Stream.h" -ACE_BEGIN_VERSIONED_NAMESPACE_DECL -typedef ACE_SOCK_Stream ATM_Stream; -ACE_END_VERSIONED_NAMESPACE_DECL -#else -#include "ace/TLI_Stream.h" -ACE_BEGIN_VERSIONED_NAMESPACE_DECL -typedef ACE_TLI_Stream ATM_Stream; -ACE_END_VERSIONED_NAMESPACE_DECL -#endif - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_ATM_Stream - * - * @brief Defines the member functions for ACE_ATM_Stream abstraction. - */ -class ACE_Export ACE_ATM_Stream -{ -public: - // = Initialization and termination methods. - /// Default constructor. - ACE_ATM_Stream (void); - - // = ATM-specific open and shutdown operations. - /// open the stream. - int open (ACE_ATM_Params params = ACE_ATM_Params()); - - /// Close down and release resources. - int close (void); - - /// Get the underlying handle. - ACE_HANDLE get_handle (void) const; - - /// Get the underlying stream. - ATM_Stream& get_stream (void); - - /// Get the name of the connected host. - char* get_peer_name (void) const; - - /// Get the VPI and VCI of the stream. - int get_vpi_vci (ACE_UINT16 &vpi, - ACE_UINT16 &vci) const; - - /// Recv an n byte buffer from the connected transport mechanism. - ssize_t recv (void *buf, - size_t n, - int *flags = 0) const; - - /// Send exactly n bytes to the connected transport mechanism. - ssize_t send_n (const void *buf, - size_t n, - int flags) const; - - // = Meta-type info - typedef ACE_ATM_Addr PEER_ADDR; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - /// Typedef'd to the appropriate stream mechanism above. - ATM_Stream stream_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/ATM_Stream.inl" -#endif /* __ACE_INLINE__ */ - -#endif /* ACE_HAS_ATM */ -#include /**/ "ace/post.h" -#endif /* ACE_ATM_STREAM_H */ diff --git a/externals/ace/ATM_Stream.inl b/externals/ace/ATM_Stream.inl deleted file mode 100644 index 007e25832a5..00000000000 --- a/externals/ace/ATM_Stream.inl +++ /dev/null @@ -1,133 +0,0 @@ -// -*- C++ -*- -// -// $Id: ATM_Stream.inl 84262 2009-01-29 10:34:33Z johnnyw $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE void -ACE_ATM_Stream::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_ATM_Stream::dump"); -#endif /* ACE_HAS_DUMP */ -} - -ACE_INLINE -ACE_ATM_Stream::ACE_ATM_Stream (void) -{ - ACE_TRACE ("ACE_ATM_Stream::ACE_ATM_Stream"); -} - -ACE_INLINE -int -ACE_ATM_Stream::open (ACE_ATM_Params params) -{ - ACE_TRACE ("ACE_ATM_Stream::open"); -#if defined (ACE_HAS_FORE_ATM_XTI) - ACE_HANDLE handle = stream_.open (params.get_device(), - params.get_oflag(), - params.get_info()); - return (handle == ACE_INVALID_HANDLE ? -1 : 0); -#elif defined (ACE_HAS_FORE_ATM_WS2) - params.set_flags( ACE_FLAG_MULTIPOINT_C_ROOT | ACE_FLAG_MULTIPOINT_D_ROOT ); - - int retval = stream_.open (params.get_type(), - params.get_protocol_family(), - params.get_protocol(), - params.get_protocol_info(), - params.get_sock_group(), - params.get_flags(), - params.get_reuse_addr()); - if (retval == -1) - return -1; - - struct sockaddr_atm sock_addr; - - ACE_OS::memset(&sock_addr, 0, sizeof(struct sockaddr_atm)); - sock_addr.satm_family = AF_ATM; - sock_addr.satm_number.AddressType=ADDR_ANY; - sock_addr.satm_number.NumofDigits = ATM_ADDR_SIZE; - sock_addr.satm_blli.Layer2Protocol = SAP_FIELD_ABSENT; - sock_addr.satm_blli.Layer3Protocol = SAP_FIELD_ABSENT; - sock_addr.satm_bhli.HighLayerInfoType = SAP_FIELD_ABSENT; - if (ACE_OS::bind(get_handle(), - (struct sockaddr FAR *)&sock_addr, - sizeof(struct sockaddr_atm)) < 0) - { - ACE_OS::printf("Error binding local address: %d",WSAGetLastError()); - return -1; - } - - return 0; -#else - ACE_UNUSED_ARG(params); - return 0; -#endif /* ACE_HAS_FORE_ATM_XTI */ -} - -ACE_INLINE -int -ACE_ATM_Stream::close (void) -{ - ACE_TRACE ("ACE_ATM_Stream::close"); -#if defined (ACE_HAS_FORE_ATM_XTI) || defined (ACE_HAS_FORE_ATM_WS2) - return stream_.close (); -#else - return 0; -#endif /* ACE_HAS_FORE_ATM_XTI || ACE_HAS_FORE_ATM_WS2 */ -} - -ACE_INLINE -ATM_Stream& -ACE_ATM_Stream::get_stream (void) -{ - ACE_TRACE ("ACE_ATM_Stream::get_stream"); - return stream_; -} - -ACE_INLINE -ssize_t -ACE_ATM_Stream::recv (void *buf, - size_t n, - int *flags) const -{ - ACE_TRACE ("ACE_ATM_Stream::recv"); -#if defined (ACE_HAS_FORE_ATM_XTI) - return stream_.recv (buf, - n, - flags); -#elif defined (ACE_HAS_FORE_ATM_WS2) - return stream_.recv (buf, - n); -#else - ACE_UNUSED_ARG(buf); - ACE_UNUSED_ARG(n); - ACE_UNUSED_ARG(flags); - return 0; -#endif /* ACE_HAS_FORE_ATM_XTI */ -} - -ACE_INLINE -ssize_t -ACE_ATM_Stream::send_n (const void *buf, - size_t n, - int flags) const -{ - ACE_TRACE ("ACE_ATM_Stream::send_n"); -#if defined (ACE_HAS_FORE_ATM_XTI) - return stream_.send_n (buf, - n, - flags); -#elif defined (ACE_HAS_FORE_ATM_WS2) - return stream_.send_n (buf, - n, - flags); -#else - ACE_UNUSED_ARG(buf); - ACE_UNUSED_ARG(n); - ACE_UNUSED_ARG(flags); - return 0; -#endif /* ACE_HAS_FORE_ATM_XTI */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Acceptor.cpp b/externals/ace/Acceptor.cpp deleted file mode 100644 index e2e1ad7b8e7..00000000000 --- a/externals/ace/Acceptor.cpp +++ /dev/null @@ -1,1246 +0,0 @@ -#ifndef ACE_ACCEPTOR_CPP -#define ACE_ACCEPTOR_CPP - -#include "ace/ACE.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Acceptor.h" -#include "ace/Handle_Set.h" -#include "ace/Svc_Handler.h" -#include "ace/WFMO_Reactor.h" -#include "ace/OS_NS_stdio.h" -#include "ace/OS_NS_string.h" -#include "ace/OS_NS_sys_select.h" - -ACE_RCSID (ace, - Acceptor, - "$Id: Acceptor.cpp 84935 2009-03-22 19:21:58Z schmidt $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Acceptor) - -template void -ACE_Acceptor::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Acceptor::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - this->peer_acceptor_.dump (); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -template -ACE_Acceptor::operator ACE_PEER_ACCEPTOR & () const -{ - ACE_TRACE ("ACE_Acceptor::operator ACE_PEER_ACCEPTOR &"); - return (ACE_PEER_ACCEPTOR &) this->peer_acceptor_; -} - -template ACE_PEER_ACCEPTOR & -ACE_Acceptor::acceptor (void) const -{ - ACE_TRACE ("ACE_Acceptor::acceptor"); - return const_cast (this->peer_acceptor_); -} - -// Returns ACE_HANDLE of the underlying Acceptor_Strategy. - -template ACE_HANDLE -ACE_Acceptor::get_handle (void) const -{ - ACE_TRACE ("ACE_Acceptor::get_handle"); - return this->peer_acceptor_.get_handle (); -} - -// Initialize the appropriate strategies for creation, passive -// connection acceptance, and concurrency, and then register -// with the Reactor and listen for connection requests at the -// designated . - -template int -ACE_Acceptor::open - (const ACE_PEER_ACCEPTOR_ADDR &local_addr, - ACE_Reactor *reactor, - int flags, - int use_select, - int reuse_addr) -{ - ACE_TRACE ("ACE_Acceptor::open"); - this->flags_ = flags; - this->use_select_ = use_select; - this->reuse_addr_ = reuse_addr; - this->peer_acceptor_addr_ = local_addr; - - // Must supply a valid Reactor to Acceptor::open()... - - if (reactor == 0) - { - errno = EINVAL; - return -1; - } - - if (this->peer_acceptor_.open (local_addr, reuse_addr) == -1) - return -1; - - // Set the peer acceptor's handle into non-blocking mode. This is a - // safe-guard against the race condition that can otherwise occur - // between the time when indicates that a passive-mode - // socket handle is "ready" and when we call . During this - // interval, the client can shutdown the connection, in which case, - // the call can hang! - if (this->accept_strategy_->acceptor ().enable (ACE_NONBLOCK) != 0) - return -1; - - // Initialize the concurrency strategy. - - if (con_s == 0) - { - ACE_NEW_RETURN (con_s, - CONCURRENCY_STRATEGY, - -1); - this->delete_concurrency_strategy_ = true; - } - this->concurrency_strategy_ = con_s; - - // Initialize the scheduling strategy. - - if (sch_s == 0) - { - ACE_NEW_RETURN (sch_s, - SCHEDULING_STRATEGY, - -1); - this->delete_scheduling_strategy_ = true; - } - this->scheduling_strategy_ = sch_s; - - this->use_select_ = use_select; - - return this->reactor ()->register_handler - (this, - ACE_Event_Handler::ACCEPT_MASK); -} - -// Simple constructor. - -template -ACE_Strategy_Acceptor::ACE_Strategy_Acceptor - (const ACE_TCHAR service_name[], - const ACE_TCHAR service_description[], - int use_select, - int reuse_addr) - : creation_strategy_ (0), - delete_creation_strategy_ (false), - accept_strategy_ (0), - delete_accept_strategy_ (false), - concurrency_strategy_ (0), - delete_concurrency_strategy_ (false), - scheduling_strategy_ (0), - delete_scheduling_strategy_ (false), - service_name_ (0), - service_description_ (0) -{ - ACE_TRACE ("ACE_Strategy_Acceptor::ACE_Strategy_Acceptor"); - - if (service_name != 0) - ACE_ALLOCATOR (this->service_name_, - ACE_OS::strdup (service_name)); - if (service_description != 0) - ACE_ALLOCATOR (this->service_description_, - ACE_OS::strdup (service_description)); - this->use_select_ = use_select; - this->reuse_addr_ = reuse_addr; -} - -template -ACE_Strategy_Acceptor::ACE_Strategy_Acceptor - (const ACE_PEER_ACCEPTOR_ADDR &addr, - ACE_Reactor *reactor, - ACE_Creation_Strategy *cre_s, - ACE_Accept_Strategy *acc_s, - ACE_Concurrency_Strategy *con_s, - ACE_Scheduling_Strategy *sch_s, - const ACE_TCHAR service_name[], - const ACE_TCHAR service_description[], - int use_select, - int reuse_addr) - : creation_strategy_ (0), - delete_creation_strategy_ (false), - accept_strategy_ (0), - delete_accept_strategy_ (false), - concurrency_strategy_ (0), - delete_concurrency_strategy_ (false), - scheduling_strategy_ (0), - delete_scheduling_strategy_ (false), - service_name_ (0), - service_description_ (0) -{ - ACE_TRACE ("ACE_Strategy_Acceptor::ACE_Strategy_Acceptor"); - - if (this->open (addr, - reactor, - cre_s, - acc_s, - con_s, - sch_s, - service_name, - service_description, - use_select, - reuse_addr) == -1) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_Strategy_Acceptor::ACE_Strategy_Acceptor"))); -} - -// Perform termination activities when is removed from the -// . - -template int -ACE_Strategy_Acceptor::handle_close (ACE_HANDLE, - ACE_Reactor_Mask) -{ - ACE_TRACE ("ACE_Strategy_Acceptor::handle_close"); - // Guard against multiple closes. - if (this->reactor () != 0) - { - ACE_HANDLE handle = this->get_handle (); - - if (this->delete_creation_strategy_) - delete this->creation_strategy_; - this->delete_creation_strategy_ = false; - this->creation_strategy_ = 0; - - if (this->delete_accept_strategy_) - delete this->accept_strategy_; - this->delete_accept_strategy_ = false; - this->accept_strategy_ = 0; - - if (this->delete_concurrency_strategy_) - delete this->concurrency_strategy_; - this->delete_concurrency_strategy_ = false; - this->concurrency_strategy_ = 0; - - if (this->delete_scheduling_strategy_) - delete this->scheduling_strategy_; - this->delete_scheduling_strategy_ = false; - this->scheduling_strategy_ = 0; - - // We must use the obtained *before* we deleted the - // accept_strategy_... - - this->reactor ()->remove_handler - (handle, - ACE_Event_Handler::ACCEPT_MASK | ACE_Event_Handler::DONT_CALL); - - // Set the Reactor to 0 so that we don't try to close down - // again. - this->reactor (0); - } - return 0; -} - -// Bridge method for creating a . The strategy for -// creating a are configured into the Acceptor via it's -// . The default is to create a new -// . However, subclasses can override this strategy to -// perform creation in any way that they like (such as -// creating subclass instances of , using a singleton, -// dynamically linking the handler, etc.). - -template int -ACE_Strategy_Acceptor::make_svc_handler (SVC_HANDLER *&sh) -{ - ACE_TRACE ("ACE_Strategy_Acceptor::make_svc_handler"); - return this->creation_strategy_->make_svc_handler (sh); -} - -// Bridge method for accepting the new connection into the -// . The default behavior delegates to the -// in the Acceptor_Strategy. - -template int -ACE_Strategy_Acceptor::accept_svc_handler - (SVC_HANDLER *svc_handler) -{ - ACE_TRACE ("ACE_Strategy_Acceptor::accept_svc_handler"); - return this->accept_strategy_->accept_svc_handler (svc_handler); -} - -// Bridge method for activating a with the appropriate -// concurrency strategy. The default behavior of this method is to -// activate the SVC_HANDLER by calling its open() method (which allows -// the SVC_HANDLER to define its own concurrency strategy). However, -// subclasses can override this strategy to do more sophisticated -// concurrency activations (such as creating the SVC_HANDLER as an -// "active object" via multi-threading or multi-processing). - -template int -ACE_Strategy_Acceptor::activate_svc_handler - (SVC_HANDLER *svc_handler) -{ - ACE_TRACE ("ACE_Strategy_Acceptor::activate_svc_handler"); - return this->concurrency_strategy_->activate_svc_handler - (svc_handler, - (void *) this); -} - -template -ACE_Strategy_Acceptor::~ACE_Strategy_Acceptor (void) -{ - ACE_TRACE ("ACE_Strategy_Acceptor::~ACE_Strategy_Acceptor"); - ACE_OS::free ((void *) this->service_name_); - ACE_OS::free ((void *) this->service_description_); - this->handle_close (); -} - -// Signal the server to shutdown gracefully. - -template int -ACE_Strategy_Acceptor::handle_signal (int, siginfo_t *, ucontext_t *) -{ - ACE_Reactor::instance()->end_reactor_event_loop (); - return 0; -} - -template int -ACE_Strategy_Acceptor::info (ACE_TCHAR **strp, - size_t length) const -{ - ACE_TRACE ("ACE_Strategy_Acceptor::info"); - - ACE_TCHAR buf[BUFSIZ]; - ACE_TCHAR service_addr_str[BUFSIZ]; - ACE_PEER_ACCEPTOR_ADDR addr; - - if (this->acceptor ().get_local_addr (addr) == -1) - return -1; - else if (addr.addr_to_string (service_addr_str, - sizeof service_addr_str) == -1) - return -1; - - // @@ Should add the protocol in... - ACE_OS::sprintf (buf, - ACE_TEXT ("%s\t %s #%s\n"), - this->service_name_ == 0 - ? ACE_TEXT ("") - : this->service_name_, - service_addr_str, - this->service_description_ == 0 - ? ACE_TEXT ("") - : this->service_description_); - - if (*strp == 0 && (*strp = ACE_OS::strdup (buf)) == 0) - return -1; - else - ACE_OS::strsncpy (*strp, buf, length); - return static_cast (ACE_OS::strlen (buf)); -} - -template int -ACE_Strategy_Acceptor::fini (void) -{ - ACE_TRACE ("ACE_Strategy_Acceptor::fini"); - return this->ACE_Strategy_Acceptor::handle_close (); -} - -ACE_ALLOC_HOOK_DEFINE(ACE_Oneshot_Acceptor) - -template void -ACE_Oneshot_Acceptor::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Oneshot_Acceptor::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nsvc_handler_ = %x"), this->svc_handler_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nrestart_ = %d"), this->restart_)); - this->peer_acceptor_.dump (); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("delete_concurrency_strategy_ = %d"), - delete_concurrency_strategy_)); - this->concurrency_strategy_->dump (); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -template int -ACE_Oneshot_Acceptor::open - (const ACE_PEER_ACCEPTOR_ADDR &local_addr, - ACE_Reactor *reactor, - ACE_Concurrency_Strategy *con_s) -{ - ACE_TRACE ("ACE_Oneshot_Acceptor::open"); - this->reactor (reactor); - - // Initialize the concurrency strategy. - - if (con_s == 0) - { - ACE_NEW_RETURN (con_s, - ACE_Concurrency_Strategy, - -1); - this->delete_concurrency_strategy_ = true; - } - this->concurrency_strategy_ = con_s; - - // Reuse the addr, even if it is already in use...! - return this->peer_acceptor_.open (local_addr, 1); -} - -template -ACE_Oneshot_Acceptor::ACE_Oneshot_Acceptor (void) - : delete_concurrency_strategy_ (false) -{ - ACE_TRACE ("ACE_Oneshot_Acceptor::ACE_Oneshot_Acceptor"); - this->reactor (0); -} - -template -ACE_Oneshot_Acceptor::ACE_Oneshot_Acceptor - (const ACE_PEER_ACCEPTOR_ADDR &local_addr, - ACE_Reactor *reactor, - ACE_Concurrency_Strategy *cs) - : delete_concurrency_strategy_ (false) -{ - ACE_TRACE ("ACE_Oneshot_Acceptor::ACE_Oneshot_Acceptor"); - if (this->open (local_addr, reactor, cs) == -1) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_Oneshot_Acceptor::ACE_Oneshot_Acceptor"))); -} - -template -ACE_Oneshot_Acceptor::~ACE_Oneshot_Acceptor (void) -{ - ACE_TRACE ("ACE_Oneshot_Acceptor::~ACE_Oneshot_Acceptor"); - this->handle_close (); -} - -template int -ACE_Oneshot_Acceptor::close (void) -{ - ACE_TRACE ("ACE_Oneshot_Acceptor::close"); - return this->handle_close (); -} - -template int -ACE_Oneshot_Acceptor::handle_close (ACE_HANDLE, - ACE_Reactor_Mask) -{ - ACE_TRACE ("ACE_Oneshot_Acceptor::handle_close"); - - // Guard against multiple closes. - if (this->delete_concurrency_strategy_) - { - delete this->concurrency_strategy_; - this->delete_concurrency_strategy_ = false; - this->concurrency_strategy_ = 0; - } - // Note that if we aren't actually registered with the - // ACE_Reactor then it's ok for this call to fail... - - if (this->reactor ()) - this->reactor ()->remove_handler - (this, - ACE_Event_Handler::ACCEPT_MASK | ACE_Event_Handler::DONT_CALL); - - if (this->peer_acceptor_.close () == -1) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("close\n"))); - return 0; -} - -template int -ACE_Oneshot_Acceptor::handle_timeout - (const ACE_Time_Value &tv, - const void *arg) -{ - ACE_TRACE ("ACE_Oneshot_Acceptor::handle_timeout"); - errno = ETIME; - - if (this->svc_handler_->handle_timeout (tv, arg) == -1) - this->svc_handler_->handle_close (this->svc_handler_->get_handle (), - ACE_Event_Handler::TIMER_MASK); - - // Since we aren't necessarily registered with the Reactor, don't - // bother to check the return value here... - if (this->reactor ()) - this->reactor ()->remove_handler (this, - ACE_Event_Handler::ACCEPT_MASK); - return 0; -} - -template int -ACE_Oneshot_Acceptor::cancel (void) -{ - ACE_TRACE ("ACE_Oneshot_Acceptor::cancel"); - return this->reactor () && this->reactor ()->cancel_timer (this); -} - -template int -ACE_Oneshot_Acceptor::register_handler - (SVC_HANDLER *svc_handler, - const ACE_Synch_Options &synch_options, - bool restart) -{ - ACE_TRACE ("ACE_Oneshot_Acceptor::register_handler"); - // Can't do this if we don't have a Reactor. - if (this->reactor () == 0) - { - errno = EINVAL; - return -1; - } - else - { - this->svc_handler_ = svc_handler; - this->restart_ = restart; - ACE_Time_Value *tv = (ACE_Time_Value *) synch_options.time_value (); - - if (tv != 0 - && this->reactor ()->schedule_timer (this, - synch_options.arg (), - *tv) == 0) - return -1; - else - return this->reactor ()->register_handler - (this, - ACE_Event_Handler::ACCEPT_MASK); - } -} - -// Bridge method for activating a with the appropriate -// concurrency strategy. The default behavior of this method is to -// activate the SVC_HANDLER by calling its open() method (which allows -// the SVC_HANDLER to define its own concurrency strategy). However, -// subclasses can override this strategy to do more sophisticated -// concurrency activations (such as creating the SVC_HANDLER as an -// "active object" via multi-threading or multi-processing). - -template int -ACE_Oneshot_Acceptor::activate_svc_handler - (SVC_HANDLER *svc_handler) -{ - ACE_TRACE ("ACE_Oneshot_Acceptor::activate_svc_handler"); - return this->concurrency_strategy_->activate_svc_handler - (svc_handler, - (void *) this); -} - -// Factors out the code shared between the and -// methods. - -template int -ACE_Oneshot_Acceptor::shared_accept - (SVC_HANDLER *svc_handler, - ACE_PEER_ACCEPTOR_ADDR *remote_addr, - ACE_Time_Value *timeout, - bool restart, - bool reset_new_handle) -{ - ACE_TRACE ("ACE_Oneshot_Acceptor::shared_accept"); - if (svc_handler == 0) - return -1; - - // Accept connection into the Svc_Handler. - else if (this->peer_acceptor_.accept (svc_handler->peer (), // stream - remote_addr, // remote address - timeout, // timeout - restart, // restart - reset_new_handle // reset new handle - ) == -1) - { - // Check whether we just timed out or whether we failed... - if (!(errno == EWOULDBLOCK || errno == ETIME)) - // Close down handler to avoid memory leaks. - svc_handler->close (CLOSE_DURING_NEW_CONNECTION); - return -1; - } - // Activate the using the designated concurrency - // strategy (note that this method becomes responsible for handling - // errors and freeing up the memory if things go awry...) - else - return this->activate_svc_handler (svc_handler); -} - -// Make a SVC_HANDLER, accept the connection into the SVC_HANDLER, and -// then activate the SVC_HANDLER. Note that SVC_HANDLER::open() -// decides what type of concurrency strategy to use. - -template int -ACE_Oneshot_Acceptor::accept - (SVC_HANDLER *svc_handler, - ACE_PEER_ACCEPTOR_ADDR *remote_addr, - const ACE_Synch_Options &synch_options, - bool restart, - bool reset_new_handle) -{ - ACE_TRACE ("ACE_Oneshot_Acceptor::accept"); - // Note that if timeout == ACE_Time_Value (x, y) where (x > 0 || y > - // 0) then this->connector_.connect() will block synchronously. If - // is set then we don't want this to happen (since we - // want the ACE_Reactor to do the timeout asynchronously). - // Therefore, we'll force this->connector_ to use ACE_Time_Value (0, - // 0) in this case... - - ACE_Time_Value *timeout; - int use_reactor = synch_options[ACE_Synch_Options::USE_REACTOR]; - - if (use_reactor) - timeout = (ACE_Time_Value *) &ACE_Time_Value::zero; - else - timeout = (ACE_Time_Value *) synch_options.time_value (); - - if (this->shared_accept (svc_handler, // stream - remote_addr, // remote address - timeout, // timeout - restart, // restart - reset_new_handle // reset new handler - ) == -1) - { - if (use_reactor && errno == EWOULDBLOCK) - // We couldn't accept right away, so let's wait in the - // . - this->register_handler (svc_handler, - synch_options, - restart); - return -1; - } - return 0; -} - -// Accepts one pending connection from a client (since we're the -// "oneshot" Acceptor). - -template int -ACE_Oneshot_Acceptor::handle_input (ACE_HANDLE) -{ - ACE_TRACE ("ACE_Oneshot_Acceptor::handle_input"); - int result = 0; - - // Cancel any timer that might be pending. - this->cancel (); - - // Try to find out if the implementation of the reactor that we are - // using requires us to reset the event association for the newly - // created handle. This is because the newly created handle will - // inherit the properties of the listen handle, including its event - // associations. - bool const reset_new_handle = this->reactor ()->uses_event_associations (); - - // There is a use-case whereby this object will be gone upon return - // from shared_accept - if the Svc_Handler deletes this Oneshot_Acceptor - // during the shared_accept/activation steps. So, do whatever we need - // to do with this object before calling shared_accept. - if (this->reactor ()) - this->reactor ()->remove_handler - (this, - ACE_Event_Handler::ACCEPT_MASK | ACE_Event_Handler::DONT_CALL); - - if (this->shared_accept (this->svc_handler_, // stream - 0, // remote address - 0, // timeout - this->restart_, // restart - reset_new_handle // reset new handle - ) == -1) - result = -1; - - return result; -} - -// Hook called by the explicit dynamic linking facility. - -template int -ACE_Oneshot_Acceptor::init (int, ACE_TCHAR *[]) -{ - ACE_TRACE ("ACE_Oneshot_Acceptor::init"); - return -1; -} - -template int -ACE_Oneshot_Acceptor::fini (void) -{ - ACE_TRACE ("ACE_Oneshot_Acceptor::fini"); - return this->handle_close (); -} - -template int -ACE_Oneshot_Acceptor::info (ACE_TCHAR **strp, - size_t length) const -{ - ACE_TRACE ("ACE_Oneshot_Acceptor::info"); - ACE_TCHAR buf[BUFSIZ]; - ACE_TCHAR addr_str[BUFSIZ]; - ACE_PEER_ACCEPTOR_ADDR addr; - - if (this->peer_acceptor_.get_local_addr (addr) == -1) - return -1; - else if (addr.addr_to_string (addr_str, sizeof addr_str) == -1) - return -1; - - ACE_OS::sprintf (buf, - ACE_TEXT ("%s\t %s %s"), - ACE_TEXT ("ACE_Oneshot_Acceptor"), - addr_str, - ACE_TEXT ("#oneshot acceptor factory\n")); - - if (*strp == 0 && (*strp = ACE_OS::strdup (buf)) == 0) - return -1; - else - ACE_OS::strsncpy (*strp, buf, length); - return static_cast (ACE_OS::strlen (buf)); -} - -template int -ACE_Oneshot_Acceptor::suspend (void) -{ - ACE_TRACE ("ACE_Oneshot_Acceptor::suspend"); - return this->reactor () && this->reactor ()->suspend_handler (this); -} - -template int -ACE_Oneshot_Acceptor::resume (void) -{ - ACE_TRACE ("ACE_Oneshot_Acceptor::resume"); - return this->reactor () && this->reactor ()->resume_handler (this); -} - -// Returns ACE_HANDLE of the underlying peer_acceptor. - -template ACE_HANDLE -ACE_Oneshot_Acceptor::get_handle (void) const -{ - ACE_TRACE ("ACE_Oneshot_Acceptor::get_handle"); - return this->peer_acceptor_.get_handle (); -} - -template ACE_PEER_ACCEPTOR & -ACE_Oneshot_Acceptor::acceptor (void) const -{ - ACE_TRACE ("ACE_Oneshot_Acceptor::acceptor"); - return (ACE_PEER_ACCEPTOR &) this->peer_acceptor_; -} - -template -ACE_Oneshot_Acceptor::operator ACE_PEER_ACCEPTOR & () const -{ - ACE_TRACE ("ACE_Oneshot_Acceptor::operator ACE_PEER_ACCEPTOR &"); - return (ACE_PEER_ACCEPTOR &) this->peer_acceptor_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_ACCEPTOR_CPP */ diff --git a/externals/ace/Acceptor.h b/externals/ace/Acceptor.h deleted file mode 100644 index 64cf488b9d4..00000000000 --- a/externals/ace/Acceptor.h +++ /dev/null @@ -1,695 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Acceptor.h - * - * $Id: Acceptor.h 88800 2010-02-01 23:18:34Z shuston $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_ACCEPTOR_H -#define ACE_ACCEPTOR_H - -#include /**/ "ace/pre.h" - -#include "ace/Service_Object.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Strategies_T.h" -#include "ace/Synch_Options.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Acceptor - * - * @brief Abstract factory for creating a service handler - * (SVC_HANDLER), accepting into the SVC_HANDLER, and - * activating the SVC_HANDLER. - * - * Implements the basic strategy for passively establishing - * connections with clients. An ACE_Acceptor is parameterized - * by concrete types that conform to the interfaces of - * PEER_ACCEPTOR and SVC_HANDLER. The PEER_ACCEPTOR is - * instantiated with a transport mechanism that passively - * establishes connections. The SVC_HANDLER is instantiated - * with a concrete type that performs the application-specific - * service. An ACE_Acceptor inherits from ACE_Service_Object, - * which in turn inherits from ACE_Event_Handler. This enables - * the ACE_Reactor to dispatch the ACE_Acceptor's handle_input - * method when connection events occur. The handle_input method - * performs the ACE_Acceptor's default creation, connection - * establishment, and service activation strategies. These - * strategies can be overridden by subclasses individually or as - * a group. - */ -template -class ACE_Acceptor : public ACE_Service_Object -{ -public: - - // Useful STL-style traits. - typedef ACE_PEER_ACCEPTOR_ADDR addr_type; - typedef ACE_PEER_ACCEPTOR acceptor_type; - typedef SVC_HANDLER handler_type; - typedef typename SVC_HANDLER::stream_type stream_type; - - /// "Do-nothing" constructor. - ACE_Acceptor (ACE_Reactor * = 0, - int use_select = 1); - - /** - * Open the contained @c PEER_ACCEPTOR object to begin listening, and - * register with the specified reactor for accept events. An - * acceptor can only listen to one port at a time, so make sure to - * @c close() the acceptor before calling @c open() again. - * - * The @c PEER_ACCEPTOR handle is put into non-blocking mode as a - * safeguard against the race condition that can otherwise occur - * between the time when the passive-mode socket handle is "ready" - * and when the actual @c accept() call is made. During this - * interval, the client can shutdown the connection, in which case, - * the @c accept() call can hang. - * - * @param local_addr The address to listen at. - * @param reactor Pointer to the ACE_Reactor instance to register - * this object with. The default is the singleton. - * @param flags Flags to control what mode an accepted socket - * will be put into after it is accepted. The only - * legal value for this argument is @c ACE_NONBLOCK, - * which enables non-blocking mode on the accepted - * peer stream object in @c SVC_HANDLER. The default - * is 0. - * @param use_select Affects behavior when called back by the reactor - * when a connection can be accepted. If non-zero, - * this object will accept all pending connections, - * instead of just the one that triggered the reactor - * callback. Uses ACE_OS::select() internally to - * detect any remaining acceptable connections. - * The default is 1. - * @param reuse_addr Passed to the @c PEER_ACCEPTOR::open() method with - * @p local_addr. Generally used to request that the - * OS allow reuse of the listen port. The default is 1. - */ - ACE_Acceptor (const ACE_PEER_ACCEPTOR_ADDR &local_addr, - ACE_Reactor *reactor = ACE_Reactor::instance (), - int flags = 0, - int use_select = 1, - int reuse_addr = 1); - - /** - * Open the contained @c PEER_ACCEPTOR object to begin listening, and - * register with the specified reactor for accept events. An - * acceptor can only listen to one port at a time, so make sure to - * @c close() the acceptor before calling @c open() again. - * - * The @c PEER_ACCEPTOR handle is put into non-blocking mode as a - * safeguard against the race condition that can otherwise occur - * between the time when the passive-mode socket handle is "ready" - * and when the actual @c accept() call is made. During this - * interval, the client can shutdown the connection, in which case, - * the @c accept() call can hang. - * - * @param local_addr The address to listen at. - * @param reactor Pointer to the ACE_Reactor instance to register - * this object with. The default is the singleton. - * @param flags Flags to control what mode an accepted socket - * will be put into after it is accepted. The only - * legal value for this argument is @c ACE_NONBLOCK, - * which enables non-blocking mode on the accepted - * peer stream object in @c SVC_HANDLER. The default - * is 0. - * @param use_select Affects behavior when called back by the reactor - * when a connection can be accepted. If non-zero, - * this object will accept all pending connections, - * instead of just the one that triggered the reactor - * callback. Uses ACE_OS::select() internally to - * detect any remaining acceptable connections. - * The default is 1. - * @param reuse_addr Passed to the @c PEER_ACCEPTOR::open() method with - * @p local_addr. Generally used to request that the - * OS allow reuse of the listen port. The default is 1. - * - * @retval 0 Success - * @retval -1 Failure, @c errno contains an error code. - */ - virtual int open (const ACE_PEER_ACCEPTOR_ADDR &local_addr, - ACE_Reactor *reactor = ACE_Reactor::instance (), - int flags = 0, - int use_select = 1, - int reuse_addr = 1); - - /// Close down the Acceptor's resources. - virtual ~ACE_Acceptor (void); - - /// Return the underlying PEER_ACCEPTOR object. - virtual operator ACE_PEER_ACCEPTOR &() const; - - /// Return the underlying PEER_ACCEPTOR object. - virtual ACE_PEER_ACCEPTOR &acceptor (void) const; - - /// Returns the listening acceptor's {ACE_HANDLE}. - virtual ACE_HANDLE get_handle (void) const; - - /// Close down the Acceptor - virtual int close (void); - - /// In the event that an accept fails, this method will be called and - /// the return value will be returned from handle_input(). - virtual int handle_accept_error (void); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - // = The following three methods define the Acceptor's strategies - // for creating, accepting, and activating SVC_HANDLER's, - // respectively. - - /** - * Bridge method for creating a SVC_HANDLER. The default is to - * create a new {SVC_HANDLER} if {sh} == 0, else {sh} is unchanged. - * However, subclasses can override this policy to perform - * SVC_HANDLER creation in any way that they like (such as creating - * subclass instances of SVC_HANDLER, using a singleton, dynamically - * linking the handler, etc.). Returns -1 on failure, else 0. - */ - virtual int make_svc_handler (SVC_HANDLER *&sh); - - /** - * Bridge method for accepting the new connection into the - * @a svc_handler. The default behavior delegates to the - * PEER_ACCEPTOR::accept. - */ - virtual int accept_svc_handler (SVC_HANDLER *svc_handler); - - /** - * Bridge method for activating a {svc_handler} with the appropriate - * concurrency strategy. The default behavior of this method is to - * activate the SVC_HANDLER by calling its {open} method (which - * allows the SVC_HANDLER to define its own concurrency strategy). - * However, subclasses can override this strategy to do more - * sophisticated concurrency activations (such as making the - * SVC_HANDLER as an "active object" via multi-threading or - * multi-processing). - */ - virtual int activate_svc_handler (SVC_HANDLER *svc_handler); - - // = Demultiplexing hooks. - /// Perform termination activities when {this} is removed from the - /// {reactor}. - virtual int handle_close (ACE_HANDLE = ACE_INVALID_HANDLE, - ACE_Reactor_Mask = ACE_Event_Handler::ALL_EVENTS_MASK); - - /// Accepts all pending connections from clients, and creates and - /// activates SVC_HANDLERs. - virtual int handle_input (ACE_HANDLE); - - // = Dynamic linking hooks. - /// Default version does no work and returns -1. Must be overloaded - /// by application developer to do anything meaningful. - virtual int init (int argc, ACE_TCHAR *argv[]); - - /// Calls {handle_close}. - virtual int fini (void); - - /// Default version returns address info in {buf}. - virtual int info (ACE_TCHAR **buf, size_t) const; - -public: - // = Service management hooks. - /// This method calls {Reactor::suspend}. - virtual int suspend (void); - - /// This method calls {Reactor::resume}. - virtual int resume (void); - -protected: - /// Concrete factory for accepting connections from clients... - ACE_PEER_ACCEPTOR peer_acceptor_; - - /// Needed to reopen the socket if {accept} fails. - ACE_PEER_ACCEPTOR_ADDR peer_acceptor_addr_; - - /** - * Flags that indicate how {SVC_HANDLER}'s should be initialized - * prior to being activated. Right now, the only flag that is - * processed is {ACE_NONBLOCK}, which enabled non-blocking I/O on - * the {SVC_HANDLER} when it is opened. - */ - int flags_; - - /// Flag that indicates whether it shall use {select} in the - /// {accept}-loop. - int use_select_; - - /// Needed to reopen the socket if {accept} fails. - int reuse_addr_; -}; - -/** - * @class ACE_Strategy_Acceptor - * - * @brief Abstract factory for creating a service handler - * (SVC_HANDLER), accepting into the SVC_HANDLER, and activating - * the SVC_HANDLER. - * - * Implements a flexible and extensible set of strategies for - * passively establishing connections with clients. There are - * three main strategies: (1) creating a SVC_HANDLER, (2) - * passively accepting a new connection from a client into the - * SVC_HANDLER, and (3) activating the SVC_HANDLER with a - * particular concurrency mechanism. - */ -template -class ACE_Strategy_Acceptor - : public ACE_Acceptor -{ -public: - - // Useful STL-style traits. - typedef ACE_Creation_Strategy - creation_strategy_type; - typedef ACE_Accept_Strategy - accept_strategy_type; - typedef ACE_Concurrency_Strategy - concurrency_strategy_type; - typedef ACE_Scheduling_Strategy scheduling_strategy_type; - typedef ACE_Acceptor - base_type; - - // = Define some useful (old style) traits. - typedef ACE_Creation_Strategy CREATION_STRATEGY; - typedef ACE_Accept_Strategy ACCEPT_STRATEGY; - typedef ACE_Concurrency_Strategy CONCURRENCY_STRATEGY; - typedef ACE_Scheduling_Strategy SCHEDULING_STRATEGY; - - /// Default constructor. - ACE_Strategy_Acceptor (const ACE_TCHAR service_name[] = 0, - const ACE_TCHAR service_description[] = 0, - int use_select = 1, - int reuse_addr = 1); - - /** - * Initialize the appropriate strategies for creation, passive - * connection acceptance, and concurrency, and then register {this} - * with the Reactor and listen for connection requests at the - * designated {local_addr}. - */ - ACE_Strategy_Acceptor (const ACE_PEER_ACCEPTOR_ADDR &local_addr, - ACE_Reactor * = ACE_Reactor::instance (), - ACE_Creation_Strategy * = 0, - ACE_Accept_Strategy * = 0, - ACE_Concurrency_Strategy * = 0, - ACE_Scheduling_Strategy * = 0, - const ACE_TCHAR service_name[] = 0, - const ACE_TCHAR service_description[] = 0, - int use_select = 1, - int reuse_addr = 1); - - /** - * Open the contained @c PEER_ACCEPTOR object to begin listening, and - * register with the specified reactor for accept events. - * - * The @c PEER_ACCEPTOR handle is put into non-blocking mode as a - * safeguard against the race condition that can otherwise occur - * between the time when the passive-mode socket handle is "ready" - * and when the actual @c accept call is made. During this - * interval, the client can shutdown the connection, in which case, - * the {accept} call can hang. - * - * @param local_addr The address to listen at. - * @param reactor Pointer to the ACE_Reactor instance to register - * this object with. The default is the singleton. - * @param flags Flags to control what mode an accepted socket - * will be put into after it is accepted. The only - * legal value for this argument is @c ACE_NONBLOCK, - * which enables non-blocking mode on the accepted - * peer stream object in @c SVC_HANDLER. The default - * is 0. - * @param use_select Affects behavior when called back by the reactor - * when a connection can be accepted. If non-zero, - * this object will accept all pending connections, - * instead of just the one that triggered the reactor - * callback. Uses ACE_OS::select() internally to - * detect any remaining acceptable connections. - * The default is 1. - * @param reuse_addr Passed to the @c PEER_ACCEPTOR::open() method with - * @p local_addr. Generally used to request that the - * OS allow reuse of the listen port. The default is 1. - * - * @retval 0 Success - * @retval -1 Failure, @c errno contains an error code. - */ - virtual int open (const ACE_PEER_ACCEPTOR_ADDR &local_addr, - ACE_Reactor *reactor, - int flags = 0, - int use_select = 1, - int reuse_addr = 1); - - /** - * Initialize the appropriate strategies for creation, passive - * connection acceptance, and concurrency, and then register {this} - * with the Reactor and listen for connection requests at the - * designated {local_addr}. - */ - virtual int open (const ACE_PEER_ACCEPTOR_ADDR &, - ACE_Reactor * = ACE_Reactor::instance (), - ACE_Creation_Strategy * = 0, - ACE_Accept_Strategy * =0, - ACE_Concurrency_Strategy * = 0, - ACE_Scheduling_Strategy * = 0, - const ACE_TCHAR *service_name = 0, - const ACE_TCHAR *service_description = 0, - int use_select = 1, - int reuse_addr = 1); - - /// Close down the Strategy_Acceptor's resources. - virtual ~ACE_Strategy_Acceptor (void); - - /// Return the underlying PEER_ACCEPTOR object. - virtual operator ACE_PEER_ACCEPTOR &() const; - - /// Return the underlying PEER_ACCEPTOR object. - virtual ACE_PEER_ACCEPTOR &acceptor (void) const; - - /// Returns the listening acceptor's {ACE_HANDLE}. - virtual ACE_HANDLE get_handle (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - - // = Service management hooks. - - /// This method delegates to the {Scheduling_Strategy}'s {suspend} - /// method. - virtual int suspend (void); - - /// This method delegates to the {Scheduling_Strategy}'s {resume} - /// method. - virtual int resume (void); - -protected: - - /// Calls {handle_close} when dynamically unlinked. - virtual int fini (void); - - /// Default version returns address info in {buf}. - virtual int info (ACE_TCHAR **buf, size_t) const; - - // = The following three methods define the {Acceptor}'s strategies - // for creating, accepting, and activating {SVC_HANDLER}'s, - // respectively. - - /** - * Bridge method for creating a {SVC_HANDLER}. The strategy for - * creating a {SVC_HANDLER} are configured into the Acceptor via - * it's {creation_strategy_}. The default is to create a new - * {SVC_HANDLER} if {sh} == 0, else {sh} is unchanged. However, - * subclasses can override this policy to perform {SVC_HANDLER} - * creation in any way that they like (such as creating subclass - * instances of {SVC_HANDLER}, using a singleton, dynamically - * linking the handler, etc.). Returns -1 on failure, else 0. - */ - virtual int make_svc_handler (SVC_HANDLER *&); - - /** - * Bridge method for accepting the new connection into the - * {SVC_HANDLER}. The default behavior delegates to the - * {PEER_ACCEPTOR::accept} in the {Acceptor_Strategy}. - */ - virtual int accept_svc_handler (SVC_HANDLER *svc_handler); - - /** - * Bridge method for activating a {SVC_HANDLER} with the appropriate - * concurrency strategy. The default behavior of this method is to - * activate the {SVC_HANDLER} by calling its {open} method (which - * allows the {SVC_HANDLER} to define its own concurrency strategy). - * However, subclasses can override this strategy to do more - * sophisticated concurrency activations (such as creating the - * {SVC_HANDLER} as an "active object" via multi-threading or - * multi-processing). - */ - virtual int activate_svc_handler (SVC_HANDLER *svc_handler); - - // = Demultiplexing hooks. - /// Perform termination activities when {this} is removed from the - /// {Reactor}. - virtual int handle_close (ACE_HANDLE = ACE_INVALID_HANDLE, - ACE_Reactor_Mask = ACE_Event_Handler::ALL_EVENTS_MASK); - - /// Handle SIGINT. - virtual int handle_signal (int signum, siginfo_t *, ucontext_t *); - - // = These data members are "logically private" but are put in the - // protected part in case subclasses want to access them. - - // = Strategy objects. - - /// Creation strategy for an Acceptor. - CREATION_STRATEGY *creation_strategy_; - - /// true if {Acceptor} created the creation strategy and thus should - /// delete it, else false. - bool delete_creation_strategy_; - - /// Accept strategy for an {Acceptor}. - ACCEPT_STRATEGY *accept_strategy_; - - /// true if {Acceptor} created the accept strategy and thus should delete - /// it, else false. - bool delete_accept_strategy_; - - /// Concurrency strategy for an {Acceptor}. - CONCURRENCY_STRATEGY *concurrency_strategy_; - - /// true if {Acceptor} created the concurrency strategy and thus should - /// delete it, else false. - bool delete_concurrency_strategy_; - - /// Scheduling strategy for an {Acceptor}. - SCHEDULING_STRATEGY *scheduling_strategy_; - - /// true if {Acceptor} created the scheduling strategy and thus should - /// delete it, else false. - bool delete_scheduling_strategy_; - - // = Service information objects. - - /// Name of the service. - ACE_TCHAR *service_name_; - - /// Description of the service. - ACE_TCHAR *service_description_; - - /// Address that the {Strategy_Acceptor} uses to listen for - /// connections. - ACE_PEER_ACCEPTOR_ADDR service_addr_; -}; - -/** - * @class ACE_Oneshot_Acceptor - * - * @brief Generic factory for passively connecting clients and creating - * exactly one service handler of the type SVC_HANDLER specified in the - * template. - * - * This class works similarly to the regular ACE_Acceptor, but - * with the following differences: - * -# ACE_Oneshot_Acceptor doesn't automatically register itself with the - * ACE_Reactor; the caller is expected to call the accept() method - * directly. Since a later call to accept() may require a reactor, - * the constructor and open() methods both accept an ACE_Reactor pointer - * which is saved in case it's needed in accept(). - * -# ACE_Oneshot_Acceptor doesn't need an ACE_Creation_Strategy (because - * the user supplies the SVC_HANDLER) or an ACE_Accept_Strategy (because - * this class only accepts one connection and then removes all traces of - * itself from the ACE_Reactor if it was registered for asynchronous - * accepts). - * - * The usage model for ACE_Oneshot_Acceptor is: - * - Instantiate an object and establish its local address to listen at. - * This can be accomplished using either the address-accepting constructor - * (but there's no error indication) or the default constructor followed - * by a call to open(). - * - Call the accept() method. This will attempt to accept a connection - * immediately. If there is no immediately available connection to accept, - * behavior is governed by the ACE_Synch_Options argument passed to open(). - */ -template -class ACE_Oneshot_Acceptor : public ACE_Service_Object -{ -public: - - // Useful STL-style traits. - typedef ACE_PEER_ACCEPTOR_ADDR addr_type; - typedef ACE_PEER_ACCEPTOR acceptor_type; - typedef SVC_HANDLER handler_type; - typedef typename SVC_HANDLER::stream_type stream_type; - - /// Constructor. - ACE_Oneshot_Acceptor (void); - - /** - * Initialize the appropriate strategies for concurrency and then - * open the acceptor at the designated @a local_addr. Note - * that unlike ACE_Acceptor and ACE_Strategy_Acceptor, this - * method does NOT register this acceptor with the @a reactor at - * this point -- the @a reactor parameter is saved in case it's - * needed later. - */ - ACE_Oneshot_Acceptor (const ACE_PEER_ACCEPTOR_ADDR &local_addr, - ACE_Reactor *reactor = ACE_Reactor::instance (), - ACE_Concurrency_Strategy * = 0); - - /** - * Initialize the appropriate strategies for concurrency and then - * open the acceptor at the designated @a local_addr. Note - * that unlike ACE_Acceptor and ACE_Strategy_Acceptor, this - * method does NOT register this acceptor with the @a reactor at - * this point -- the @a reactor parameter is saved in case it's - * needed later. - */ - int open (const ACE_PEER_ACCEPTOR_ADDR &, - ACE_Reactor *reactor = ACE_Reactor::instance (), - ACE_Concurrency_Strategy * = 0); - - /// Close down the {Oneshot_Acceptor}. - virtual ~ACE_Oneshot_Acceptor (void); - - // = Explicit factory operation. - /// Create a {SVC_HANDLER}, accept the connection into the - /// {SVC_HANDLER}, and activate the {SVC_HANDLER}. - virtual int accept (SVC_HANDLER * = 0, - ACE_PEER_ACCEPTOR_ADDR *remote_addr = 0, - const ACE_Synch_Options &synch_options = ACE_Synch_Options::defaults, - bool restart = true, - bool reset_new_handle = false); - - /// Cancel a oneshot acceptor that was started asynchronously. - virtual int cancel (void); - - /// Return the underlying {PEER_ACCEPTOR} object. - virtual operator ACE_PEER_ACCEPTOR &() const; - - /// Return the underlying {PEER_ACCEPTOR} object. - virtual ACE_PEER_ACCEPTOR &acceptor (void) const; - - /// Close down the {Oneshot_Acceptor}. - virtual int close (void); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - /** - * Bridge method for activating a {svc_handler} with the appropriate - * concurrency strategy. Default behavior is to activate the - * {SVC_HANDLER} as a "passive object." However, subclasses can - * override this strategy to do more sophisticated concurrency - * activations (such as creating the {SVC_HANDLER} as an "active - * object" via multi-threading or multi-processing). - */ - virtual int activate_svc_handler (SVC_HANDLER *svc_handler); - - /// Factors out the code shared between the {accept} and - /// {handle_input} methods. - int shared_accept (SVC_HANDLER *svc_handler, - ACE_PEER_ACCEPTOR_ADDR *remote_addr, - ACE_Time_Value *timeout, - bool restart, - bool reset_new_handle); - - // = Demultiplexing hooks. - /// Returns the listening acceptor's {ACE_HANDLE}. - virtual ACE_HANDLE get_handle (void) const; - - /// Perform termination activities when {this} is removed from the - /// {reactor}. - virtual int handle_close (ACE_HANDLE = ACE_INVALID_HANDLE, - ACE_Reactor_Mask = ACE_Event_Handler::ALL_EVENTS_MASK); - - /// Accept one connection from a client and activates the - /// SVC_HANDLER. - virtual int handle_input (ACE_HANDLE); - - /// Called when an acceptor times out... - virtual int handle_timeout (const ACE_Time_Value &tv, - const void *arg); - - // = Dynamic linking hooks. - /// Default version does no work and returns -1. Must be overloaded - /// by application developer to do anything meaningful. - virtual int init (int argc, ACE_TCHAR *argv[]); - - /// Default version does no work and returns -1. Must be overloaded - /// by application developer to do anything meaningful. - virtual int fini (void); - - /// Default version returns address info in {buf}. - virtual int info (ACE_TCHAR **, size_t) const; - - // = Service management hooks. - /// Default version does no work and returns -1. Must be overloaded - /// by application developer to do anything meaningful. - virtual int suspend (void); - - /// Default version does no work and returns -1. Must be overloaded - /// by application developer to do anything meaningful. - virtual int resume (void); - -private: - /** - * Insert ourselves into the {ACE_Reactor} so that we can continue - * accepting this connection asynchronously. This method should NOT - * be called by developers directly. - */ - int register_handler (SVC_HANDLER *svc_handler, - const ACE_Synch_Options &options, - bool restart); - - /// Hold the svc_handler_ across asynchrony boundaries. - SVC_HANDLER *svc_handler_; - - /// Hold the restart flag across asynchrony boundaries. - bool restart_; - - /// Factory that establishes connections passively. - ACE_PEER_ACCEPTOR peer_acceptor_; - - /// Concurrency strategy for an Acceptor. - ACE_Concurrency_Strategy *concurrency_strategy_; - - /// true if Acceptor created the concurrency strategy and thus should - /// delete it, else false. - bool delete_concurrency_strategy_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Acceptor.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Acceptor.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" - -#endif /* ACE_ACCEPTOR_H */ diff --git a/externals/ace/Activation_Queue.cpp b/externals/ace/Activation_Queue.cpp deleted file mode 100644 index 37be7a46a7a..00000000000 --- a/externals/ace/Activation_Queue.cpp +++ /dev/null @@ -1,138 +0,0 @@ -#include "ace/Activation_Queue.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Activation_Queue.inl" -#endif /* __ACE_INLINE__ */ - -#include "ace/Log_Msg.h" -#include "ace/Method_Request.h" -#include "ace/Malloc_Base.h" -#include "ace/Time_Value.h" - -ACE_RCSID (ace, - Activation_Queue, - "$Id: Activation_Queue.cpp 84565 2009-02-23 08:20:39Z johnnyw $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -void -ACE_Activation_Queue::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("delete_queue_ = %d\n"), - this->delete_queue_)); - ACE_DEBUG ((LM_INFO, ACE_TEXT ("queue_:\n"))); - if (this->queue_) - this->queue_->dump(); - else - //FUZZ: disable check_for_NULL - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(NULL)\n"))); - //FUZZ: enable check_for_NULL - - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -ACE_Activation_Queue::ACE_Activation_Queue (ACE_Message_Queue *new_queue, - ACE_Allocator *alloc, - ACE_Allocator *db_alloc) - : delete_queue_ (false) - , allocator_(alloc) - , data_block_allocator_(db_alloc) -{ - if (this->allocator_ == 0) - this->allocator_ = ACE_Allocator::instance (); - - if (new_queue) - this->queue_ = new_queue; - else - { - ACE_NEW (this->queue_, - ACE_Message_Queue); - this->delete_queue_ = true; - } -} - -void -ACE_Activation_Queue::queue (ACE_Message_Queue *q) -{ - // Destroy the internal queue if one exist. - if (this->delete_queue_) - { - // Destroy the current queue. - delete this->queue_; - - // Set the flag to false. NOTE that the delete_queue_ flag is a - // flag used to only indicate whether or not if an internal - // ACE_Message_Queue has been created, therefore, it will not - // affect the user if the user decided to replace the queue with - // their own queue no matter how many time they call on this - // function. - this->delete_queue_ = false; - } - - queue_ = q; -} - -ACE_Activation_Queue::~ACE_Activation_Queue (void) -{ - if (this->delete_queue_) - delete this->queue_; -} - -ACE_Method_Request * -ACE_Activation_Queue::dequeue (ACE_Time_Value *tv) -{ - ACE_Message_Block *mb = 0; - - // Dequeue the message. - if (this->queue_->dequeue_head (mb, tv) != -1) - { - // Get the next . - ACE_Method_Request *mr = - reinterpret_cast (mb->base ()); - // Delete the message block. - mb->release (); - return mr; - } - else - return 0; -} - -int -ACE_Activation_Queue::enqueue (ACE_Method_Request *mr, - ACE_Time_Value *tv) -{ - ACE_Message_Block *mb = 0; - - // We pass sizeof (*mr) here so that flow control will work - // correctly. Since we also pass note that no unnecessary - // memory is actually allocated -- just the size field is set. - ACE_NEW_MALLOC_RETURN (mb, - static_cast (this->allocator_->malloc (sizeof (ACE_Message_Block))), - ACE_Message_Block (sizeof (*mr), // size - ACE_Message_Block::MB_DATA, // type - 0, // cont - (char *) mr, // data - 0, // allocator - 0, // locking strategy - mr->priority (), // priority - ACE_Time_Value::zero, // execution time - ACE_Time_Value::max_time, // absolute time of deadline - this->data_block_allocator_, // data_block allocator - this->allocator_), // message_block allocator - -1); - - // Enqueue in priority order. - int const result = this->queue_->enqueue_prio (mb, tv); - - // Free ACE_Message_Block if enqueue_prio failed. - if (result == -1) - ACE_DES_FREE (mb, this->allocator_->free, ACE_Message_Block); - - return result; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Activation_Queue.h b/externals/ace/Activation_Queue.h deleted file mode 100644 index ab58eedb586..00000000000 --- a/externals/ace/Activation_Queue.h +++ /dev/null @@ -1,168 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Activation_Queue.h - * - * $Id: Activation_Queue.h 91066 2010-07-12 11:05:04Z johnnyw $ - * - * @author Andres Kruse - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_ACTIVATION_QUEUE_H -#define ACE_ACTIVATION_QUEUE_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Message_Queue.h" -#include "ace/Copy_Disabled.h" -#include "ace/Condition_Thread_Mutex.h" - -/// Define to be compatible with the terminology in the POSA2 book! -#define ACE_Activation_List ACE_Activation_Queue - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -class ACE_Method_Request; - -/** - * @class ACE_Activation_Queue - * - * @brief - * Reifies a method into a request. Subclasses typically - * represent necessary state and behavior. - * - * Maintains a priority-ordered queue of ACE_Method_Request objects. - * A scheduler class (often derived from ACE_Task) subsequently removes - * each method request and invokes its @c call() method. - * - * This class is discussed in depth in the Active Object chapter - * of POSA2. In that book, it is referred to as an Activation List. - * - * @sa ACE_Method_Request - */ -class ACE_Export ACE_Activation_Queue : private ACE_Copy_Disabled -{ -public: - /// Constructor. - /** - * Initializes a new activation queue. - * - * @param new_queue The activation queue uses an ACE_Message_Queue to - * queue and order the method requests. If this argument - * is 0, a new ACE_Message_Queue is created for this - * object's use and will be deleted when this object is - * destroyed. If a non-zero pointer is supplied, the - * passed object will be used and will not be deleted when - * this object is destroyed. If an ACE_Task is being created - * to act as the scheduler, for instance, its - * ACE_Message_Queue pointer can be passed to this object. - * @param alloc Optional, the allocator to use when allocating - * ACE_Message_Block instances that wrap the method requests - * queued to this activation queue. Defaults to - * ACE_Allocator::instance(). - * @param db_alloc Optional, the allocator to use when allocating - * data blocks for the ACE_Message_Block instances that - * wrap the method requests queued to this activation queue. - * Defaults to ACE_Allocator::instance(). - */ - ACE_Activation_Queue (ACE_Message_Queue *new_queue = 0, - ACE_Allocator *alloc = 0, - ACE_Allocator *db_alloc = 0); - - /// Destructor. - virtual ~ACE_Activation_Queue (void); - - // = Activate Queue operations. - - /// Dequeue the next available ACE_Method_Request. - /** - * @param tv If 0, the method will block until a method request is - * available, else will wait until the absolute time specified - * in the referenced ACE_Time_Value. This method will return, - * earlier, however, if queue is closed, deactivated, or when - * a signal occurs. - * - * @retval Pointer to the dequeued ACE_Method_Request object. - * @retval 0 an error occurs; errno contains further information. If - * the specified timeout elapses, errno will be @c EWOULDBLOCK. - */ - ACE_Method_Request *dequeue (ACE_Time_Value *tv = 0); - - /// Enqueue the ACE_Method_Request in priority order. - /** - * The priority of the method request is obtained via the @c priority() - * method of the queued method request. Priority ordering is determined - * by the ACE_Message_Queue class; 0 is the lowest priority. - * - * @param new_method_request Pointer to the ACE_Method_Request object to - * queue. This object's @c priority() method is called to obtain - * the priority. - * @param tv If 0, the method will block until the method request can - * be queued, else will wait until the absolute time specified - * in the referenced ACE_Time_Value. This method will return, - * earlier, however, if queue is closed, deactivated, or when - * a signal occurs. - * - * @retval >0 The number of method requests on the queue after adding - * the specified request. - * @retval -1 if an error occurs; errno contains further information. If - * the specified timeout elapses, errno will be @c EWOULDBLOCK. - */ - int enqueue (ACE_Method_Request *new_method_request, ACE_Time_Value *tv = 0); - - /// Get the current number of method objects in the queue. - size_t method_count (void) const; - - /// Returns 1 if the queue is empty, 0 otherwise. - int is_empty (void) const; - - /// Returns 1 if the queue is full, 0 otherwise. - int is_full (void) const; - - /// Dump the state of an request. - void dump (void) const; - - /// Get a pointer to the underlying queue. - ACE_Message_Queue *queue (void) const; - - /// Set the pointer to the underlying queue. - void queue (ACE_Message_Queue *q); - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - - /// Stores the Method_Requests. - ACE_Message_Queue *queue_; - - /// Keeps track of whether we need to delete the queue. - bool delete_queue_; - -private: - - /// Allocation strategy of the queue. - ACE_Allocator *allocator_; - - /// Allocation strategy of the message blocks. - ACE_Allocator *data_block_allocator_; - -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Activation_Queue.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_ACTIVATION_QUEUE_H */ diff --git a/externals/ace/Activation_Queue.inl b/externals/ace/Activation_Queue.inl deleted file mode 100644 index 4c0ffc049d3..00000000000 --- a/externals/ace/Activation_Queue.inl +++ /dev/null @@ -1,31 +0,0 @@ -// -*- C++ -*- -// -// $Id: Activation_Queue.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE size_t -ACE_Activation_Queue::method_count (void) const -{ - return queue_->message_count (); -} - -ACE_INLINE int -ACE_Activation_Queue::is_full (void) const -{ - return queue_->is_full (); -} - -ACE_INLINE int -ACE_Activation_Queue::is_empty (void) const -{ - return queue_->is_empty (); -} - -ACE_INLINE ACE_Message_Queue * -ACE_Activation_Queue::queue (void) const -{ - return queue_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Active_Map_Manager.cpp b/externals/ace/Active_Map_Manager.cpp deleted file mode 100644 index 6ec891b5d10..00000000000 --- a/externals/ace/Active_Map_Manager.cpp +++ /dev/null @@ -1,9 +0,0 @@ -// $Id: Active_Map_Manager.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Active_Map_Manager.h" - -ACE_RCSID(ace, Active_Map_Manager, "$Id: Active_Map_Manager.cpp 80826 2008-03-04 14:51:23Z wotte $") - -#if !defined (__ACE_INLINE__) -#include "ace/Active_Map_Manager.inl" -#endif /* __ACE_INLINE__ */ diff --git a/externals/ace/Active_Map_Manager.h b/externals/ace/Active_Map_Manager.h deleted file mode 100644 index a6c167e5f88..00000000000 --- a/externals/ace/Active_Map_Manager.h +++ /dev/null @@ -1,116 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file Active_Map_Manager.h - * - * $Id: Active_Map_Manager.h 91066 2010-07-12 11:05:04Z johnnyw $ - * - * @author Irfan Pyarali - */ -//============================================================================= - - -#ifndef ACE_ACTIVE_MAP_MANAGER_H -#define ACE_ACTIVE_MAP_MANAGER_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Basic_Types.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Active_Map_Manager_Key - * - * @brief Key used in the Active Object Map. - * - * This key keeps information of the index and the generation - * count of the slot it represents. Since the index information - * is part of the key, lookups are super fast and predictable, - */ -class ACE_Export ACE_Active_Map_Manager_Key -{ -public: - /// Default constructor. - ACE_Active_Map_Manager_Key (void); - - /** - * Constructor given the @a slot_index and @a slot_generation number. - * This is useful once the user has somehow recovered the - * @a slot_index and @a slot_generation number from the client. - */ - ACE_Active_Map_Manager_Key (ACE_UINT32 slot_index, - ACE_UINT32 slot_generation); - - /// Get the slot_index. - ACE_UINT32 slot_index (void) const; - - /// Set the slot_index. - void slot_index (ACE_UINT32 i); - - /// Get the slot_generation number. - ACE_UINT32 slot_generation (void) const; - - /// Set the slot_generation number. - void slot_generation (ACE_UINT32 g); - - /// Size required to store information about active key. - static size_t size (void); - - /// Recover state of active key from @a data. User must make sure - /// that @a data encoded using the encode() method. - void decode (const void *data); - - /// Encode state of the active key into @a data. @a data must be as - /// big as the value returned from . - void encode (void *data) const; - - /// Compare keys. - bool operator== (const ACE_Active_Map_Manager_Key &rhs) const; - bool operator!= (const ACE_Active_Map_Manager_Key &rhs) const; - - // = This really should be protected but because of template - // friends, they are not. - - /// Increment the slot_generation number. - void increment_slot_generation_count (void); - -private: - - /** - * @brief Data for the Active Object Map Key. - * - * This separate structure makes it easier to manage copying - * the index and the generation to and from the user buffer. - * - */ - struct key_data - { - /// Slot index in the active map. - ACE_UINT32 slot_index_; - - /// Slot generation number of @c slot_index_ slot in the active map. - ACE_UINT32 slot_generation_; - }; - - /// Data for the Active Object Map Key. - key_data key_data_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Active_Map_Manager.inl" -#endif /* __ACE_INLINE__ */ - -// Include the templates here. -#include "ace/Active_Map_Manager_T.h" - -#include /**/ "ace/post.h" -#endif /* ACE_ACTIVE_MAP_MANAGER_H */ diff --git a/externals/ace/Active_Map_Manager.inl b/externals/ace/Active_Map_Manager.inl deleted file mode 100644 index df90ada6a00..00000000000 --- a/externals/ace/Active_Map_Manager.inl +++ /dev/null @@ -1,95 +0,0 @@ -// -*- C++ -*- -// -// $Id: Active_Map_Manager.inl 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/OS_NS_string.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE -ACE_Active_Map_Manager_Key::ACE_Active_Map_Manager_Key (void) -{ - // If you change ~0, please change ACE_Map_Manager::free_list_id() - // accordingly. - this->key_data_.slot_index_ = (ACE_UINT32) ~0; - this->key_data_.slot_generation_ = 0; -} - -ACE_INLINE -ACE_Active_Map_Manager_Key::ACE_Active_Map_Manager_Key (ACE_UINT32 slot_index, - ACE_UINT32 slot_generation) -{ - this->key_data_.slot_index_ = slot_index; - this->key_data_.slot_generation_ = slot_generation; -} - -ACE_INLINE ACE_UINT32 -ACE_Active_Map_Manager_Key::slot_index (void) const -{ - return this->key_data_.slot_index_; -} - -ACE_INLINE ACE_UINT32 -ACE_Active_Map_Manager_Key::slot_generation (void) const -{ - return this->key_data_.slot_generation_; -} - -ACE_INLINE bool -ACE_Active_Map_Manager_Key::operator== (const ACE_Active_Map_Manager_Key &rhs) const -{ - return - this->key_data_.slot_index_ == rhs.key_data_.slot_index_ && - this->key_data_.slot_generation_ == rhs.key_data_.slot_generation_; -} - -ACE_INLINE bool -ACE_Active_Map_Manager_Key::operator!= (const ACE_Active_Map_Manager_Key &rhs) const -{ - return !this->operator== (rhs); -} - -ACE_INLINE void -ACE_Active_Map_Manager_Key::slot_index (ACE_UINT32 i) -{ - this->key_data_.slot_index_ = i; -} - -ACE_INLINE void -ACE_Active_Map_Manager_Key::slot_generation (ACE_UINT32 g) -{ - this->key_data_.slot_generation_ = g; -} - -ACE_INLINE void -ACE_Active_Map_Manager_Key::increment_slot_generation_count (void) -{ - ++this->key_data_.slot_generation_; -} - -/* static */ -ACE_INLINE size_t -ACE_Active_Map_Manager_Key::size (void) -{ - return sizeof (ACE_UINT32) + sizeof (ACE_UINT32); -} - -ACE_INLINE void -ACE_Active_Map_Manager_Key::decode (const void *data) -{ - // Copy the information from the user buffer into the key. - ACE_OS::memcpy (&this->key_data_, - data, - sizeof this->key_data_); -} - -ACE_INLINE void -ACE_Active_Map_Manager_Key::encode (void *data) const -{ - // Copy the key data to the user buffer. - ACE_OS::memcpy (data, - &this->key_data_, - sizeof this->key_data_); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Active_Map_Manager_T.cpp b/externals/ace/Active_Map_Manager_T.cpp deleted file mode 100644 index 732cc295117..00000000000 --- a/externals/ace/Active_Map_Manager_T.cpp +++ /dev/null @@ -1,22 +0,0 @@ -// $Id: Active_Map_Manager_T.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#ifndef ACE_ACTIVE_MAP_MANAGER_T_CPP -#define ACE_ACTIVE_MAP_MANAGER_T_CPP - -#include "ace/Active_Map_Manager_T.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (__ACE_INLINE__) -#include "ace/Active_Map_Manager_T.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Active_Map_Manager) - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_ACTIVE_MAP_MANAGER_T_CPP */ diff --git a/externals/ace/Active_Map_Manager_T.h b/externals/ace/Active_Map_Manager_T.h deleted file mode 100644 index 80eaada26a1..00000000000 --- a/externals/ace/Active_Map_Manager_T.h +++ /dev/null @@ -1,211 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file Active_Map_Manager_T.h - * - * $Id: Active_Map_Manager_T.h 84316 2009-02-03 19:46:05Z johnnyw $ - * - * @author Irfan Pyarali - */ -//============================================================================= - - -#ifndef ACE_ACTIVE_MAP_MANAGER_T_H -#define ACE_ACTIVE_MAP_MANAGER_T_H -#include /**/ "ace/pre.h" - -#include "ace/Map_Manager.h" -#include "ace/Active_Map_Manager.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Null_Mutex.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Active_Map_Manager - * - * @brief Define a map abstraction that associates system generated - * keys with user specified values. - * - * Since the key is system generated, searches are very fast and - * take a constant amount of time. - */ -template -class ACE_Active_Map_Manager : public ACE_Map_Manager -{ -public: - - // = Traits. - typedef ACE_Active_Map_Manager_Key key_type; - typedef T mapped_type; - - typedef ACE_Map_Entry ENTRY; - typedef ACE_Map_Iterator ITERATOR; - typedef ACE_Map_Reverse_Iterator REVERSE_ITERATOR; - - typedef ENTRY entry; - typedef ITERATOR iterator; - typedef REVERSE_ITERATOR reverse_iterator; - - // = Initialization and termination methods. - /// Initialize a Active_Map_Manager with the ACE_DEFAULT_MAP_SIZE. - ACE_Active_Map_Manager (ACE_Allocator *alloc = 0); - - /// Initialize a Active_Map_Manager with @a size entries. - ACE_Active_Map_Manager (size_t size, - ACE_Allocator *alloc = 0); - - /// Close down a Active_Map_Manager and release dynamically - /// allocated resources. - ~ACE_Active_Map_Manager (void); - - /// Initialize a Active_Map_Manager with size @a length. - int open (size_t length = ACE_DEFAULT_MAP_SIZE, - ACE_Allocator *alloc = 0); - - /// Close down a Active_Map_Manager and release dynamically - /// allocated resources. - int close (void); - - /// Add @a value to the map, and the corresponding key produced by the - /// Active_Map_Manager is returned through @a key. - int bind (const T &value, - ACE_Active_Map_Manager_Key &key); - - /// Add @a value to the map. The user does not care about the - /// corresponding key produced by the Active_Map_Manager. - int bind (const T &value); - - /** - * Reserves a slot in the internal structure and returns the key and - * a pointer to the value. User should place their @a value into - * @a internal_value. This method is useful in reducing the number - * of copies required in some cases. Note that @a internal_value is - * only a temporary pointer and will change when the map resizes. - * Therefore, the user should use the pointer immediately and not - * hold on to it. - */ - int bind (ACE_Active_Map_Manager_Key &key, - T *&internal_value); - - /// Reassociate @a key with @a value. The function fails if @a key is - /// not in the map. - int rebind (const ACE_Active_Map_Manager_Key &key, - const T &value); - - /** - * Reassociate @a key with @a value, storing the old value into the - * "out" parameter @a old_value. The function fails if @a key is not - * in the map. - */ - int rebind (const ACE_Active_Map_Manager_Key &key, - const T &value, - T &old_value); - - /** - * Reassociate @a key with @a value, storing the old key and value - * into the "out" parameter @a old_key and @a old_value. The function - * fails if @a key is not in the map. - */ - int rebind (const ACE_Active_Map_Manager_Key &key, - const T &value, - ACE_Active_Map_Manager_Key &old_key, - T &old_value); - - /// Locate @a value associated with @a key. - int find (const ACE_Active_Map_Manager_Key &key, - T &value) const; - - /// Is @a key in the map? - int find (const ACE_Active_Map_Manager_Key &key) const; - - /** - * Locate @a value associated with @a key. The value is returned via - * @a internal_value and hence a copy is saved. Note that - * @a internal_value is only a temporary pointer and will change when - * the map resizes. Therefore, the user should use the pointer - * immediately and not hold on to it. - */ - int find (const ACE_Active_Map_Manager_Key &key, - T *&internal_value) const; - - // Creates a key. User should place their @a value into - // <*internal_value>. This method is useful in reducing the number - // of copies required in some cases. - - /// Remove @a key from the map. - int unbind (const ACE_Active_Map_Manager_Key &key); - - /// Remove @a key from the map, and return the @a value associated with - /// @a key. - int unbind (const ACE_Active_Map_Manager_Key &key, - T &value); - - /** - * Locate @a value associated with @a key. The value is returned via - * @a internal_value and hence a copy is saved. Note that - * @a internal_value is only a temporary pointer and will change when - * the map resizes or when this slot is reused. Therefore, the user - * should use the pointer immediately and not hold on to it. - */ - int unbind (const ACE_Active_Map_Manager_Key &key, - T *&internal_value); - - /// Return the current size of the map. - size_t current_size (void) const; - - /// Return the total size of the map. - size_t total_size (void) const; - - /// Returns a key that cannot be found in the map. - static const ACE_Active_Map_Manager_Key npos (void); - - /// Dump the state of an object. - void dump (void) const; - - // = STL styled iterator factory functions. - - /// Return forward iterator. - ACE_Map_Iterator begin (void); - ACE_Map_Iterator end (void); - - /// Return reverse iterator. - ACE_Map_Reverse_Iterator rbegin (void); - ACE_Map_Reverse_Iterator rend (void); - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - - /// Private base class - typedef ACE_Map_Manager ACE_AMM_BASE; - -private: - - // = Disallow these operations. - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Active_Map_Manager &)) - ACE_UNIMPLEMENTED_FUNC (ACE_Active_Map_Manager (const ACE_Active_Map_Manager &)) -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Active_Map_Manager_T.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Active_Map_Manager_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Active_Map_Manager_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" -#endif /* ACE_ACTIVE_MAP_MANAGER_T_H */ diff --git a/externals/ace/Active_Map_Manager_T.inl b/externals/ace/Active_Map_Manager_T.inl deleted file mode 100644 index 647b55ebd56..00000000000 --- a/externals/ace/Active_Map_Manager_T.inl +++ /dev/null @@ -1,311 +0,0 @@ -// -*- C++ -*- -// -// $Id: Active_Map_Manager_T.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template ACE_INLINE int -ACE_Active_Map_Manager::bind (ACE_Active_Map_Manager_Key &key, - T *&internal_value) -{ - ACE_UINT32 slot_index; - int result = this->next_free (slot_index); - - if (result == 0) - { - // Move from free list to occupied list - this->move_from_free_list_to_occupied_list (slot_index); - - // Reset the key. - this->search_structure_[slot_index].ext_id_.increment_slot_generation_count (); - this->search_structure_[slot_index].ext_id_.slot_index (slot_index); - - // Copy the key for the user. - key = this->search_structure_[slot_index].ext_id_; - - // This is where the user should place the value. - internal_value = &this->search_structure_[slot_index].int_id_; - - // Update the current size. - ++this->cur_size_; - } - - return result; -} - -template ACE_INLINE int -ACE_Active_Map_Manager::bind (const T &value, - ACE_Active_Map_Manager_Key &key) -{ - T *internal_value = 0; - int result = this->bind (key, - internal_value); - - if (result == 0) - { - // Store new value. - *internal_value = value; - } - - return result; -} - -template ACE_INLINE int -ACE_Active_Map_Manager::bind (const T &value) -{ - ACE_Active_Map_Manager_Key key; - return this->bind (value, key); -} - -template ACE_INLINE int -ACE_Active_Map_Manager::find (const ACE_Active_Map_Manager_Key &key, - T *&internal_value) const -{ - ACE_UINT32 slot_index = key.slot_index (); - ACE_UINT32 slot_generation = key.slot_generation (); - - if (slot_index > this->total_size_ || -#if defined (ACE_HAS_LAZY_MAP_MANAGER) - this->search_structure_[slot_index].free_ || -#endif /* ACE_HAS_LAZY_MAP_MANAGER */ - this->search_structure_[slot_index].ext_id_.slot_generation () != slot_generation || - this->search_structure_[slot_index].ext_id_.slot_index () == - (ACE_UINT32)this->free_list_id ()) - { - return -1; - } - else - { - // This is where the user value is. - internal_value = &this->search_structure_[slot_index].int_id_; - } - - return 0; -} - -template ACE_INLINE int -ACE_Active_Map_Manager::find (const ACE_Active_Map_Manager_Key &key) const -{ - T *internal_value = 0; - return this->find (key, - internal_value); -} - -template ACE_INLINE int -ACE_Active_Map_Manager::find (const ACE_Active_Map_Manager_Key &key, - T &value) const -{ - T *internal_value = 0; - int result = this->find (key, - internal_value); - - if (result == 0) - value = *internal_value; - - return result; -} - -template ACE_INLINE int -ACE_Active_Map_Manager::rebind (const ACE_Active_Map_Manager_Key &key, - const T &value) -{ - int result = this->find (key); - - if (result == 0) - { - // Store new value. - this->search_structure_[key.slot_index ()].int_id_ = value; - } - - return result; -} - -template ACE_INLINE int -ACE_Active_Map_Manager::rebind (const ACE_Active_Map_Manager_Key &key, - const T &value, - T &old_value) -{ - int result = this->find (key); - - if (result == 0) - { - // Copy old value. - old_value = this->search_structure_[key.slot_index ()].int_id_; - - // Store new value. - this->search_structure_[key.slot_index ()].int_id_ = value; - } - - return result; -} - -template ACE_INLINE int -ACE_Active_Map_Manager::rebind (const ACE_Active_Map_Manager_Key &key, - const T &value, - ACE_Active_Map_Manager_Key &old_key, - T &old_value) -{ - int result = this->find (key); - - if (result == 0) - { - // Copy old key. - old_key = this->search_structure_[key.slot_index ()].ext_id_; - - // Copy old value. - old_value = this->search_structure_[key.slot_index ()].int_id_; - - // Store new value. - this->search_structure_[key.slot_index ()].int_id_ = value; - } - - return result; -} - -template ACE_INLINE int -ACE_Active_Map_Manager::unbind (const ACE_Active_Map_Manager_Key &key, - T *&internal_value) -{ - int result = this->find (key, - internal_value); - - if (result == 0) - { - ACE_UINT32 slot_index = key.slot_index (); - -#if defined (ACE_HAS_LAZY_MAP_MANAGER) - - // - // In the case of lazy map managers, the movement of free slots - // from the occupied list to the free list is delayed until we - // run out of free slots in the free list. - // - - this->search_structure_[slot_index].free_ = 1; - -#else - - // Move from occupied list to free list. - this->move_from_occupied_list_to_free_list (slot_index); - -#endif /* ACE_HAS_LAZY_MAP_MANAGER */ - - // Reset the slot_index. This will tell us that this entry is free. - this->search_structure_[slot_index].ext_id_.slot_index (this->free_list_id ()); - - // Update the current size. - --this->cur_size_; - } - - return result; -} - -template ACE_INLINE int -ACE_Active_Map_Manager::unbind (const ACE_Active_Map_Manager_Key &key, - T &value) -{ - T *internal_value; - int result = this->unbind (key, - internal_value); - - if (result == 0) - { - // Copy old value. - value = *internal_value; - } - - return result; -} - -template ACE_INLINE int -ACE_Active_Map_Manager::unbind (const ACE_Active_Map_Manager_Key &key) -{ - T *internal_value; - return this->unbind (key, - internal_value); -} - -template ACE_INLINE -ACE_Active_Map_Manager::ACE_Active_Map_Manager (ACE_Allocator *alloc) - : ACE_AMM_BASE (alloc) -{ -} - -template ACE_INLINE -ACE_Active_Map_Manager::ACE_Active_Map_Manager (size_t size, - ACE_Allocator *alloc) - : ACE_AMM_BASE (size, - alloc) -{ -} - -template ACE_INLINE -ACE_Active_Map_Manager::~ACE_Active_Map_Manager (void) -{ -} - -template ACE_INLINE int -ACE_Active_Map_Manager::open (size_t length, - ACE_Allocator *alloc) -{ - return ACE_AMM_BASE::open (length, alloc); -} - -template ACE_INLINE int -ACE_Active_Map_Manager::close (void) -{ - return ACE_AMM_BASE::close (); -} - -template ACE_INLINE size_t -ACE_Active_Map_Manager::current_size (void) const -{ - return ACE_AMM_BASE::current_size (); -} - -template ACE_INLINE size_t -ACE_Active_Map_Manager::total_size (void) const -{ - return ACE_AMM_BASE::total_size (); -} - -/* static */ -template ACE_INLINE const ACE_Active_Map_Manager_Key -ACE_Active_Map_Manager::npos (void) -{ - return ACE_Active_Map_Manager_Key (~0, ~0); -} - -template ACE_INLINE void -ACE_Active_Map_Manager::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_AMM_BASE::dump (); -#endif /* ACE_HAS_DUMP */ -} - -template ACE_Map_Iterator -ACE_Active_Map_Manager::begin (void) -{ - return ACE_AMM_BASE::begin (); -} - -template ACE_INLINE ACE_Map_Iterator -ACE_Active_Map_Manager::end (void) -{ - return ACE_AMM_BASE::end (); -} - -template ACE_INLINE ACE_Map_Reverse_Iterator -ACE_Active_Map_Manager::rbegin (void) -{ - return ACE_AMM_BASE::rbegin (); -} - -template ACE_INLINE ACE_Map_Reverse_Iterator -ACE_Active_Map_Manager::rend (void) -{ - return ACE_AMM_BASE::rend (); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Addr.cpp b/externals/ace/Addr.cpp deleted file mode 100644 index af78d91b9ca..00000000000 --- a/externals/ace/Addr.cpp +++ /dev/null @@ -1,71 +0,0 @@ -// $Id: Addr.cpp 84619 2009-02-26 12:26:16Z johnnyw $ - -#include "ace/Addr.h" - -ACE_RCSID (ace, - Addr, - "$Id: Addr.cpp 84619 2009-02-26 12:26:16Z johnnyw $") - -#if !defined (__ACE_INLINE__) -#include "ace/Addr.inl" -#endif /* __ACE_INLINE__ */ - -#include "ace/Log_Msg.h" -#include "ace/os_include/sys/os_socket.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Note: this object requires static construction and destruction. -/* static */ -const ACE_Addr ACE_Addr::sap_any (AF_ANY, -1); - -ACE_ALLOC_HOOK_DEFINE(ACE_Addr) - - -// Initializes instance variables. Note that 0 is an unspecified -// protocol family type... - -ACE_Addr::ACE_Addr (int type, int size) : - addr_type_ (type), - addr_size_ (size) -{ -} - -ACE_Addr::~ACE_Addr (void) -{ -} - -void * -ACE_Addr::get_addr (void) const -{ - return 0; -} - -void -ACE_Addr::set_addr (void *, int) -{ -} - -// Initializes instance variables. - -void -ACE_Addr::base_set (int type, int size) -{ - this->addr_type_ = type; - this->addr_size_ = size; -} - -void -ACE_Addr::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Addr::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("addr_type_ = %d"), this->addr_type_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\naddr_size_ = %d"), this->addr_size_)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Addr.h b/externals/ace/Addr.h deleted file mode 100644 index e58ffe2c0f5..00000000000 --- a/externals/ace/Addr.h +++ /dev/null @@ -1,103 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Addr.h - * - * $Id: Addr.h 81030 2008-03-20 12:43:29Z johnnyw $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_ADDR_H -#define ACE_ADDR_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Addr - * - * @brief Defines the base class for the "address family independent" - * address format. - */ -class ACE_Export ACE_Addr -{ -public: - // = Initialization and termination methods. - /// Initializes instance variables. - ACE_Addr (int type = -1, int size = -1); - - /// Destructor. - virtual ~ACE_Addr (void); - - // = Get/set the size of the address. - - /// Return the size of the address. - int get_size (void) const; - - /// Sets the size of the address. - void set_size (int size); - - // = Get/set the type of the address. - - /// Get the type of the address. - int get_type (void) const; - - /// Set the type of the address. - void set_type (int type); - - /// Return a pointer to the address. - virtual void *get_addr (void) const; - - /// Set a pointer to the address. - virtual void set_addr (void *, int len); - - // = Equality/inequality tests - /// Check for address equality. - bool operator == (const ACE_Addr &sap) const; - - /// Check for address inequality. - bool operator != (const ACE_Addr &sap) const; - - /// Initializes instance variables. - void base_set (int type, int size); - - /// Wild-card address. - static const ACE_Addr sap_any; - - /// Returns a hash value. This should be overwritten by a subclass - /// that can produce a better hash value. - virtual unsigned long hash (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - /// e.g., AF_UNIX, AF_INET, AF_SPIPE, etc. - int addr_type_; - - /// Number of bytes in the address. - int addr_size_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Addr.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" - -#endif /* ACE_ADDR_H */ diff --git a/externals/ace/Addr.inl b/externals/ace/Addr.inl deleted file mode 100644 index 0ff355eaeb7..00000000000 --- a/externals/ace/Addr.inl +++ /dev/null @@ -1,57 +0,0 @@ -// -*- C++ -*- -// -// $Id: Addr.inl 87295 2009-11-02 14:45:59Z johnnyw $ - -// Return the address of the address. - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE bool -ACE_Addr::operator == (const ACE_Addr &sap) const -{ - return (sap.addr_type_ == this->addr_type_ && - sap.addr_size_ == this->addr_size_ ); -} - -ACE_INLINE bool -ACE_Addr::operator != (const ACE_Addr &sap) const -{ - return (sap.addr_type_ != this->addr_type_ || - sap.addr_size_ != this->addr_size_ ); -} - -/// Return the size of the address. -ACE_INLINE int -ACE_Addr::get_size (void) const -{ - return this->addr_size_; -} - -/// Sets the size of the address. -ACE_INLINE void -ACE_Addr::set_size (int size) -{ - this->addr_size_ = size; -} - -/// Return the type of the address. -ACE_INLINE int -ACE_Addr::get_type (void) const -{ - return this->addr_type_; -} - -/// Set the type of the address. -ACE_INLINE void -ACE_Addr::set_type (int type) -{ - this->addr_type_ = type; -} - -ACE_INLINE unsigned long -ACE_Addr::hash (void) const -{ - return 0; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Arg_Shifter.cpp b/externals/ace/Arg_Shifter.cpp deleted file mode 100644 index 5a7182c3423..00000000000 --- a/externals/ace/Arg_Shifter.cpp +++ /dev/null @@ -1,229 +0,0 @@ -#ifndef ACE_ARG_SHIFTER_T_CPP -#define ACE_ARG_SHIFTER_T_CPP - -#include "ace/Arg_Shifter.h" -#include "ace/OS_NS_string.h" -#include "ace/OS_NS_strings.h" -#include "ace/OS_Errno.h" -#include "ace/OS_Memory.h" - -ACE_RCSID (ace, - Arg_Shifter, - "$Id: Arg_Shifter.cpp 83749 2008-11-14 18:39:10Z johnnyw $") - - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template -ACE_Arg_Shifter_T::ACE_Arg_Shifter_T (int& argc, - const CHAR_TYPE** argv, - const CHAR_TYPE** temp) - : argc_ (argc), - total_size_ (argc), - temp_ (temp), - argv_ (argv), - current_index_ (0), - back_ (argc - 1), - front_ (0) -{ - this->init (); -} - -template -ACE_Arg_Shifter_T::ACE_Arg_Shifter_T (int& argc, - CHAR_TYPE** argv, - CHAR_TYPE** temp) - : argc_ (argc), - total_size_ (argc), - temp_ ((const CHAR_TYPE **) temp), - argv_ ((const CHAR_TYPE **) argv), - current_index_ (0), - back_ (argc - 1), - front_ (0) -{ - this->init (); -} - -template -void -ACE_Arg_Shifter_T::init (void) -{ - // If not provided with one, allocate a temporary array. - if (this->temp_ == 0) - ACE_NEW (this->temp_, - const CHAR_TYPE *[this->total_size_]); - - if (this->temp_ != 0) - { - // Fill the temporary array. - this->argc_ = 0; - for (int i = 0; i < this->total_size_; i++) - { - this->temp_[i] = this->argv_[i]; - this->argv_[i] = 0; - } - } - else - { - // Allocation failed, prohibit iteration. - this->current_index_ = this->argc_; - this->front_ = this->argc_; - } -} - -template -ACE_Arg_Shifter_T::~ACE_Arg_Shifter_T (void) -{ - // Delete the temporary vector. - delete [] temp_; -} - -template -const CHAR_TYPE * -ACE_Arg_Shifter_T::get_current (void) const -{ - const CHAR_TYPE * retval = 0; - - if (this->is_anything_left ()) - retval = this->temp_[current_index_]; - - return retval; -} - -template -const CHAR_TYPE * -ACE_Arg_Shifter_T::get_the_parameter (const CHAR_TYPE *flag) -{ - // the return 0's abound because this method - // would otherwise be a deep if { } else { } - - // check to see if any arguments still exist - if (!this->is_anything_left()) - return 0; - - // check to see if the flag is the argument - int const offset = this->cur_arg_strncasecmp (flag); - if (offset == -1) - return 0; - - if (offset == 0) - { - this->consume_arg (); - - if (!this->is_parameter_next()) - { - return 0; - } - } - // the parameter is in the middle somewhere... - return this->temp_[current_index_] + offset; -} - -template -int -ACE_Arg_Shifter_T::cur_arg_strncasecmp (const CHAR_TYPE *flag) -{ - // Check for a current argument - if (this->is_anything_left()) - { - size_t const flag_length = ACE_OS::strlen (flag); - - // Check for presence of the flag - if (ACE_OS::strncasecmp(this->temp_[current_index_], - flag, - flag_length) == 0) - { - if (ACE_OS::strlen(temp_[current_index_]) == flag_length) - { - // match and lengths are equal - return 0; - } - else - { - // matches, with more info to boot! - size_t const remaining = ACE_OS::strspn - (this->temp_[current_index_] + flag_length, - ACE_TEXT (" ")) + flag_length; - return static_cast (remaining); - } - } - } - // failure - return -1; -} - -template -int -ACE_Arg_Shifter_T::consume_arg (int number) -{ - int retval = 0; - - // Stick knowns at the end of the vector (consumed). - if (this->is_anything_left() >= number) - { - for (int i = 0, j = this->back_ - (number - 1); - i < number; - ++i, ++j, ++this->current_index_) - this->argv_[j] = this->temp_[this->current_index_]; - - this->back_ -= number; - retval = 1; - } - - return retval; -} - -template -int -ACE_Arg_Shifter_T::ignore_arg (int number) -{ - int retval = 0; - - // Keep unknowns at the head of the vector. - if (this->is_anything_left () >= number) - { - for (int i = 0; - i < number; - i++, this->current_index_++, this->front_++) - this->argv_[this->front_] = this->temp_[this->current_index_]; - - retval = 1; - this->argc_ += number; - } - - return retval; -} - -template -int -ACE_Arg_Shifter_T::is_anything_left (void) const -{ - return this->total_size_ - this->current_index_; -} - -template -int -ACE_Arg_Shifter_T::is_option_next (void) const -{ - return this->is_anything_left () && - this->temp_[this->current_index_][0] == '-'; -} - -template -int -ACE_Arg_Shifter_T::is_parameter_next (void) const -{ - return this->is_anything_left () - && this->temp_[this->current_index_][0] != '-'; -} - -template -int -ACE_Arg_Shifter_T::num_ignored_args (void) const -{ - return this->front_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_ATOMIC_OP_T_CPP */ diff --git a/externals/ace/Arg_Shifter.h b/externals/ace/Arg_Shifter.h deleted file mode 100644 index 2e5f0b0f5e7..00000000000 --- a/externals/ace/Arg_Shifter.h +++ /dev/null @@ -1,221 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Arg_Shifter.h - * - * $Id: Arg_Shifter.h 83891 2008-11-28 11:01:50Z johnnyw $ - * - * @author Seth Widoff - */ -//============================================================================= - -#ifndef ACE_ARG_SHIFTER_H -#define ACE_ARG_SHIFTER_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Global_Macros.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Arg_Shifter_T - * - * @brief This ADT operates on a specified set of arguments (@a argv). - * As known arguments are scanned, they are shifted to the back of the - * @a argv vector, so deeper levels of argument parsing can locate the yet - * unprocessed arguments at the beginning of the vector. - * - * The @c ACE_Arg_Shifter copies the pointers of the @a argv vector - * into a temporary array. As the @c ACE_Arg_Shifter iterates over - * the copied vector, it places known arguments in the rear of the - * vector, leaving the unknown ones in the beginning. So, after having - * visited all the arguments in the temporary vector, @c ACE_Arg_Shifter - * has placed all the unknown arguments in their original order at - * the front of original @a argv. - */ -template -class ACE_Arg_Shifter_T -{ -public: - // = Initialization and termination methods. - /** - * Initialize the ACE_Arg_Shifter to the vector over which to - * iterate. Optionally, also provide the temporary array for - * use in shifting the arguments. If ACE_Arg_Shifter must allocate - * the temporary vector internally and dynamic allocation fails, the - * ACE_Arg_Shifter will set all indicators to end of the vector, - * forbidding iteration. Following iteration over @a argv, the - * @a argc value will be updated to contain the number of - * unconsumed arguments. - * @param argc The number of strings in @a argv. @a argc will be - * updated to reflect the number of unconsumed arguments. - * @param argv The argument vector to shift. The string pointers in - * the vector will be reordered to place the @a argc unconsumed - * arguments at the front of the vector. - * @param temp A vector of @c CHAR_TYPE pointers at least @a argc - * elements long. The vector will be used for argument shifting as - * the specified @a argv vector is consumed. The vector must not - * be modified while this object exists. If this argument is 0 - * (the default) the object will allocate and free the temporary - * vector transparently. - */ - ACE_Arg_Shifter_T (int& argc, - const CHAR_TYPE **argv, - const CHAR_TYPE **temp = 0); - - /// Same behavior as the preceding constructor, but without the - /// "const" qualifier. - ACE_Arg_Shifter_T (int& argc, - CHAR_TYPE **argv, - CHAR_TYPE **temp = 0); - - /// Destructor. - ~ACE_Arg_Shifter_T (void); - - /// Get the current head of the vector. - const CHAR_TYPE *get_current (void) const; - - /** - * If the @a flag matches the current_arg of arg shifter - * this method will attempt to return the associated - * parameter value - * - * Safe to call without checking that a current arg exists - * - * In the following examples, a pointer to the char* "value" is ret - * - * eg: main -foobar value, main -FooBar value - * main -FOOBARvalue - * - * all of the above will all match the @a flag == -FooBar - * and will return a char* to "value" - * - * main -foobar 4 would succeed and return a char* to "4" - * main -foobar -4 does not succeed (-4 is not a parameter) - * but instead, would return 0 - * - * 0 is returned: - * If the current argument does not match flag - * If there is no parameter found after a 'matched' flag - * - * If the flag is matched and the flag and parameter DO NOT RUN - * together, the flag is consumed, the parameter is returned, - * and the new current argument is the parameter value. - * ie '-foobarflag VALUE' leaves the new cur arg == "VALUE" - * - * If the flag is matched and the flag and parameter RUN - * together '-foobarflagVALUE', the flag is NOT consumed - * and the cur arg is left pointing to the entire flag/value pair - */ - const CHAR_TYPE *get_the_parameter (const CHAR_TYPE* flag); - - /** - * Check if the current argument matches (case insensitive) @a flag - * - * ------------------------------------------------------------ - * - * Case A: Perfect Match (case insensitive) - * 0 is returned. - * - * ie: when current_arg = "-foobar" or "-FOOBAR" or "-fooBAR" - * this->cur_arg_strncasecmp ("-FooBar); - * will return 0 - * - * ------------------------------------------------------------ - * - * Case B: Perfect Match (case insensitive) but the current_arg - * is longer than the flag. Returns a number equal to the index - * in the char* indicating the start of the extra characters - * - * ie: when current_arg = "-foobar98023" - * this->cur_arg_strncasecmp ("-FooBar); - * will return 7 - * - * Notice: this number will always be > 0 - * - * ------------------------------------------------------------ - * - * Case C: If neither of Case A or B is met (no match) - * then -1 is returned - */ - int cur_arg_strncasecmp (const CHAR_TYPE *flag); - - /// Consume @a number argument(s) by sticking them/it on the end of - /// the vector. - int consume_arg (int number = 1); - - /// Place @a number arguments in the same relative order ahead of the - /// known arguments in the vector. - int ignore_arg (int number = 1); - - /// Returns the number of args left to see in the vector. - int is_anything_left (void) const; - - /// Returns 1 if there's a next item in the vector and it begins with - /// '-'. - int is_option_next (void) const; - - /// Returns 1 if there's a next item in the vector and it doesn't - /// begin with '-'. - int is_parameter_next (void) const; - - /// Returns the number of irrelevant args seen. - int num_ignored_args (void) const; - -private: - /// Copy Constructor should not be used. - ACE_UNIMPLEMENTED_FUNC (ACE_Arg_Shifter_T (const ACE_Arg_Shifter_T&)) - - /// Assignment '=' operator should not be used. - ACE_UNIMPLEMENTED_FUNC (ACE_Arg_Shifter_T operator= (const ACE_Arg_Shifter_T&)) - - /// Refactor the constructor logic. - void init (void); - - /// The size of the argument vector. - int& argc_; - - /// The size of argv_. - int total_size_; - - /// The temporary array over which we traverse. - const CHAR_TYPE **temp_; - - /// The array in which the arguments are reordered. - const CHAR_TYPE **argv_; - - /// The element in we're currently examining. - int current_index_; - - /// The index of in which we'll stick the next unknown - /// argument. - int back_; - - /// The index of in which we'll stick the next known - /// argument. - int front_; -}; - -typedef ACE_Arg_Shifter_T ACE_Arg_Shifter; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Arg_Shifter.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Arg_Shifter.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" - -#endif /* ACE_ARG_SHIFTER_H */ diff --git a/externals/ace/Argv_Type_Converter.cpp b/externals/ace/Argv_Type_Converter.cpp deleted file mode 100644 index 1ebeeb4cc30..00000000000 --- a/externals/ace/Argv_Type_Converter.cpp +++ /dev/null @@ -1,196 +0,0 @@ -// $Id: Argv_Type_Converter.cpp 85772 2009-06-23 20:14:18Z mitza $ - -#include "ace/Argv_Type_Converter.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Argv_Type_Converter.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID (ace, - Argv_Type_Converter, - "$Id: Argv_Type_Converter.cpp 85772 2009-06-23 20:14:18Z mitza $") - -#include "ace/OS_NS_string.h" -#include "ace/OS_Errno.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -#if defined (ACE_USES_WCHAR) -ACE_Argv_Type_Converter::ACE_Argv_Type_Converter (int &argc, wchar_t** argv) - : saved_argc_ (argc), - char_argv_ (0), - wchar_argv_ (argv), - before_pass_argc_ (argc), - original_type_ (true), - wchar_passed_ (false), - char_passed_ (false) -{ - this->initialize (); - - for (int i = 0; i < argc; ++i) - this->char_argv_[i] = ACE_OS::strdup (ACE_TEXT_ALWAYS_CHAR (argv[i])); -} -#endif // ACE_USES_WCHAR - - -ACE_Argv_Type_Converter::ACE_Argv_Type_Converter (int &argc, char **argv) - : saved_argc_(argc), - char_argv_(argv) -#if defined (ACE_USES_WCHAR) - , wchar_argv_(0), - before_pass_argc_(argc), - original_type_(false), - wchar_passed_(false), - char_passed_(false) -{ - this->initialize(); - - for (int i = 0; i < argc; ++i) - this->wchar_argv_[i] = ACE_OS::strdup (ACE_TEXT_ANTI_TO_TCHAR (argv[i])); -} -#else -{ -} -#endif // ACE_USES_WCHAR - -ACE_Argv_Type_Converter::~ACE_Argv_Type_Converter (void) -{ -#if defined (ACE_USES_WCHAR) - // selectively delete the 'copy' of argv - if (this->original_type_) - { - // if original type is wchar_t - if (this->char_passed_) - this->align_wchar_with_char (); - - for (int i = 0; i < this->before_pass_argc_; ++i) - ACE_OS::free (this->char_argv_[i]); - - delete [] this->char_argv_; - } - else - { - // if original type is char - if (this->wchar_passed_) - this->align_char_with_wchar (); - - for (int i = 0; i < this->before_pass_argc_; ++i) - ACE_OS::free (this->wchar_argv_[i]); - - delete [] this->wchar_argv_; - } -#endif // ACE_USES_WCHAR -} - -#if defined (ACE_USES_WCHAR) -void -ACE_Argv_Type_Converter::initialize (void) -{ - if (this->original_type_) - { - // Make a copy of argv in 'char'. type Create one more argv entry - // than original argc for the NULL. - ACE_NEW (char_argv_, - char *[this->saved_argc_ + 1]); - this->char_argv_[saved_argc_] = 0; // last entry of argv is - // always a NULL - } - else - { - // make a copy of argv in 'wchar_t' type - ACE_NEW (this->wchar_argv_, - wchar_t*[this->saved_argc_ + 1]); - this->wchar_argv_[saved_argc_] = 0; - } -} - - -void -ACE_Argv_Type_Converter::align_char_with_wchar (void) -{ - for (int wchar_argv_index = 0; wchar_argv_index < this->saved_argc_; - ++wchar_argv_index) - { - wchar_t *match_argv = this->wchar_argv_[wchar_argv_index]; - // if n'th entries of both argv lists are different - if (ACE_OS::strcmp (this->char_argv_[wchar_argv_index], - ACE_TEXT_ALWAYS_CHAR (match_argv)) != 0) - { - // loop through the wchar argv list entries that are after - // wchar_argv_index - for (int i = wchar_argv_index + 1; i < before_pass_argc_; ++i) - { - if (ACE_OS::strcmp (this->char_argv_[i], - ACE_TEXT_ALWAYS_CHAR (match_argv)) == 0) - { - // swap the pointers in the char argv list - char *temp = this->char_argv_[wchar_argv_index]; - this->char_argv_[wchar_argv_index] = this->char_argv_[i]; - this->char_argv_[i] = temp; - break; - } - } - } - } - - this->cleanup (); -} - -void -ACE_Argv_Type_Converter::align_wchar_with_char (void) -{ - for (int char_argv_index = 0; char_argv_index < saved_argc_; - ++char_argv_index) - { - char* match_argv = this->char_argv_[char_argv_index]; - // if n'th entries of both argv lists are different - if (ACE_OS::strcmp ( - ACE_TEXT_ALWAYS_CHAR (this->wchar_argv_[char_argv_index]), - match_argv) != 0) - { - // loop through the wchar argv list entries that are after - // wchar_argv_index - for (int i = char_argv_index + 1; i < this->before_pass_argc_; ++i) - { - if (ACE_OS::strcmp ( - ACE_TEXT_ALWAYS_CHAR(this->wchar_argv_[i]), - match_argv) == 0) { - // swap the pointers in the char argv list - wchar_t* temp = this->wchar_argv_[char_argv_index]; - this->wchar_argv_[char_argv_index] = this->wchar_argv_[i]; - this->wchar_argv_[i] = temp; - break; - } - } - } - } - - this->cleanup(); -} - -void -ACE_Argv_Type_Converter::cleanup (void) -{ - for (int i = this->saved_argc_; i < this->before_pass_argc_; ++i) - { - // Check whether it's ours to delete. - if (original_type_) - { - ACE_OS::free (this->char_argv_[i]); - this->char_argv_[i] = 0; - } - else - { - ACE_OS::free (this->wchar_argv_[i]); - this->wchar_argv_[i] = 0; - } - } - - this->before_pass_argc_ = this->saved_argc_; - - this->wchar_passed_ = false; - this->char_passed_ = false; -} -#endif // ACE_USES_WCHAR - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Argv_Type_Converter.h b/externals/ace/Argv_Type_Converter.h deleted file mode 100644 index d41d839b671..00000000000 --- a/externals/ace/Argv_Type_Converter.h +++ /dev/null @@ -1,119 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Argv_Type_Converter.h - * - * $Id: Argv_Type_Converter.h 83891 2008-11-28 11:01:50Z johnnyw $ - * - * @author Si Mong Park - */ -//============================================================================= - -#ifndef ACE_ARGV_TYPE_CONVERTER_H -#define ACE_ARGV_TYPE_CONVERTER_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" -#include "ace/OS_Memory.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Argv_Type_Converter - * - * @brief To convert 'char' input/command line parameter to 'wchar_t'. - * - * This class is to convert 'char' type command line parameter to - * wide-character (wchar_t) format and stores the copy of it. - * This is useful for all classes that use 'char**' argv but cannot - * be converted into 'ACE_TCHAR**' version. - * Note that the converted data will be lost upon destruction, so - * classes should use this class as their data member. - */ -class ACE_Export ACE_Argv_Type_Converter -{ -public: - - ACE_Argv_Type_Converter (int &argc, char** argv); - -#if defined (ACE_USES_WCHAR) - ACE_Argv_Type_Converter (int &argc, wchar_t** argv); -#endif // ACE_USES_WCHAR - - ~ACE_Argv_Type_Converter (void); - - /// Returns the pointer of converted command line. - ACE_TCHAR** get_TCHAR_argv (void); - - /// Returns the pointer of ASCII (char) command line. - char** get_ASCII_argv (void); - - /// Returns the number of sub parameters (argc). - int& get_argc (void); - -private: - - /// Copy Constructor should not be used. - ACE_Argv_Type_Converter (const ACE_Argv_Type_Converter&); - - /// Assignment '=' operator should not be used. - ACE_Argv_Type_Converter operator= (const ACE_Argv_Type_Converter&); - -#if defined (ACE_USES_WCHAR) - - /// Perform common initialization for two Ctor's. - void initialize (void); - - /// Align all entries in the char type argv list with wchar_t type - /// argv list. - void align_char_with_wchar (void); - - /// Align all entries in the wchar_t type argv list with char type - /// argv list. - void align_wchar_with_char (void); - - /// Clean up removed (comsumed) argv entries and reset the pass flags. - void cleanup (void); -#endif // ACE_USES_WCHAR - -private: - /// Original number of input parameter, same as 'argc'. - int &saved_argc_; - - /// Data member pointer that contains converted argv in ACE_ANTI_TCHAR. - char** char_argv_; - -#if defined (ACE_USES_WCHAR) - /// Data member pointer that contains converted argv in ACE_TCHAR. - wchar_t** wchar_argv_; - - /// argc value before any argv has been passed. - int before_pass_argc_; - - /// false represents original argv passed in is char, and true - /// represents wchar_t. - bool const original_type_; - - /// true indicates wchar_t type argv has been passed. - bool wchar_passed_; - - /// true indicates char type argv has been passed. - bool char_passed_; -#endif /* ACE_USES_WCHAR */ -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Argv_Type_Converter.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" - -#endif /* ACE_ARGV_TYPE_CONVERTER_H */ diff --git a/externals/ace/Argv_Type_Converter.inl b/externals/ace/Argv_Type_Converter.inl deleted file mode 100644 index e4b0ed5a059..00000000000 --- a/externals/ace/Argv_Type_Converter.inl +++ /dev/null @@ -1,44 +0,0 @@ -// -*- C++ -*- -// -// $Id: Argv_Type_Converter.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE ACE_TCHAR** -ACE_Argv_Type_Converter::get_TCHAR_argv (void) -{ -#if defined (ACE_USES_WCHAR) - if (this->char_passed_) - { - this->align_wchar_with_char (); - } - - this->wchar_passed_ = true; - return this->wchar_argv_; -#else - return this->char_argv_; -#endif // ACE_USES_WCHAR -} - -ACE_INLINE char** -ACE_Argv_Type_Converter::get_ASCII_argv (void) -{ -#if defined (ACE_USES_WCHAR) - if (this->wchar_passed_) - { - this->align_char_with_wchar (); - } - - this->char_passed_ = true; -#endif // ACE_USES_WCHAR - - return this->char_argv_; -} - -ACE_INLINE int& -ACE_Argv_Type_Converter::get_argc (void) -{ - return this->saved_argc_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Array.h b/externals/ace/Array.h deleted file mode 100644 index 3caaa7b719b..00000000000 --- a/externals/ace/Array.h +++ /dev/null @@ -1,29 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file Array.h - * - * $Id: Array.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @deprecated - * - * @note This file has been deprecated and will soon go away. You - * should directly include "Containers_T.h" instead. - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_ARRAY_H -#define ACE_ARRAY_H -#include /**/ "ace/pre.h" - -#include "ace/Containers_T.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include /**/ "ace/post.h" -#endif /* ACE_ARRAY_H */ diff --git a/externals/ace/Array_Base.cpp b/externals/ace/Array_Base.cpp deleted file mode 100644 index 49e42e1ad98..00000000000 --- a/externals/ace/Array_Base.cpp +++ /dev/null @@ -1,235 +0,0 @@ -// $Id: Array_Base.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#ifndef ACE_ARRAY_BASE_CPP -#define ACE_ARRAY_BASE_CPP - -#include "ace/Array_Base.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (__ACE_INLINE__) -#include "ace/Array_Base.inl" -#endif /* __ACE_INLINE__ */ - -#include "ace/Malloc_Base.h" -#include "ace/os_include/os_errno.h" - -#include - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Dynamically initialize an array. -template -ACE_Array_Base::ACE_Array_Base (typename ACE_Array_Base::size_type size, - ACE_Allocator *alloc) - : max_size_ (size), - cur_size_ (size), - allocator_ (alloc) -{ - if (this->allocator_ == 0) - this->allocator_ = ACE_Allocator::instance (); - - if (size != 0) - { - ACE_ALLOCATOR (this->array_, - (T *) this->allocator_->malloc (size * sizeof (T))); - for (size_type i = 0; i < size; ++i) - new (&array_[i]) T; - } - else - this->array_ = 0; -} - -template -ACE_Array_Base::ACE_Array_Base (typename ACE_Array_Base::size_type size, - const T &default_value, - ACE_Allocator *alloc) - : max_size_ (size), - cur_size_ (size), - allocator_ (alloc) -{ - if (this->allocator_ == 0) - this->allocator_ = ACE_Allocator::instance (); - - if (size != 0) - { - ACE_ALLOCATOR (this->array_, - (T *) this->allocator_->malloc (size * sizeof (T))); - for (size_type i = 0; i < size; ++i) - new (&array_[i]) T (default_value); - } - else - this->array_ = 0; -} - -// The copy constructor (performs initialization). - -template -ACE_Array_Base::ACE_Array_Base (const ACE_Array_Base &s) - : max_size_ (s.size ()), - cur_size_ (s.size ()), - allocator_ (s.allocator_) -{ - if (this->allocator_ == 0) - this->allocator_ = ACE_Allocator::instance (); - - ACE_ALLOCATOR (this->array_, - (T *) this->allocator_->malloc (s.size () * sizeof (T))); - for (size_type i = 0; i < this->size (); ++i) - new (&this->array_[i]) T (s.array_[i]); -} - -// Assignment operator (performs assignment). - -template void -ACE_Array_Base::operator= (const ACE_Array_Base &s) -{ - // Check for "self-assignment". - - if (this != &s) - { - if (this->max_size_ < s.size ()) - { - // Need to reallocate memory. - - // Strongly exception-safe assignment. - // - // Note that we're swapping the allocators here, too. - // Should we? Probably. "*this" should be a duplicate of - // the "right hand side". - ACE_Array_Base tmp (s); - this->swap (tmp); - } - else - { - // Underlying array is large enough. No need to reallocate - // memory. - // - // "*this" still owns the memory for the underlying array. - // Do not swap out the allocator. - // - // @@ Why don't we just drop the explicit destructor and - // placement operator new() calls with a straight - // element-by-element assignment? Is the existing - // approach more efficient? - // -Ossama - - ACE_DES_ARRAY_NOFREE (this->array_, - s.size (), - T); - - this->cur_size_ = s.size (); - - for (size_type i = 0; i < this->size (); ++i) - new (&this->array_[i]) T (s.array_[i]); - } - } -} - -// Set an item in the array at location slot. - -template int -ACE_Array_Base::set (const T &new_item, - typename ACE_Array_Base::size_type slot) -{ - if (this->in_range (slot)) - { - this->array_[slot] = new_item; - return 0; - } - else - return -1; -} - -// Get an item in the array at location slot. - -template int -ACE_Array_Base::get (T &item, - typename ACE_Array_Base::size_type slot) const -{ - if (this->in_range (slot)) - { - // Copies the item. If you don't want to copy, use operator [] - // instead (but then you'll be responsible for range checking). - item = this->array_[slot]; - return 0; - } - else - return -1; -} - -template int -ACE_Array_Base::max_size (typename ACE_Array_Base::size_type new_size) -{ - if (new_size > this->max_size_) - { - T *tmp = 0; - - ACE_ALLOCATOR_RETURN (tmp, - (T *) this->allocator_->malloc (new_size * sizeof (T)), - -1); - for (size_type i = 0; i < this->cur_size_; ++i) - new (&tmp[i]) T (this->array_[i]); - - // Initialize the new portion of the array that exceeds the - // previously allocated section. - for (size_type j = this->cur_size_; j < new_size; ++j) - new (&tmp[j]) T; - - ACE_DES_ARRAY_FREE (this->array_, - this->max_size_, - this->allocator_->free, - T); - this->array_ = tmp; - this->max_size_ = new_size; - this->cur_size_ = new_size; - } - - return 0; -} - -template int -ACE_Array_Base::size (typename ACE_Array_Base::size_type new_size) -{ - int const r = this->max_size (new_size); - - if (r == 0) - this->cur_size_ = new_size; - - return r; -} - -template -void -ACE_Array_Base::swap (ACE_Array_Base & rhs) -{ - std::swap (this->max_size_ , rhs.max_size_); - std::swap (this->cur_size_ , rhs.cur_size_); - std::swap (this->array_ , rhs.array_); - std::swap (this->allocator_, rhs.allocator_); -} - -// **************************************************************** - -template int -ACE_Array_Iterator::next (T *&item) -{ - // ACE_TRACE ("ACE_Array_Iterator::next"); - - if (this->done ()) - { - item = 0; - return 0; - } - else - { - item = &array_[current_]; - return 1; - } -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_ARRAY_BASE_CPP */ diff --git a/externals/ace/Array_Base.h b/externals/ace/Array_Base.h deleted file mode 100644 index 0d6620a6ca6..00000000000 --- a/externals/ace/Array_Base.h +++ /dev/null @@ -1,256 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Array_Base.h - * - * $Id: Array_Base.h 84477 2009-02-16 13:30:38Z johnnyw $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_ARRAY_BASE_H -#define ACE_ARRAY_BASE_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Global_Macros.h" -#include "ace/Malloc_Base.h" -#include /* For reverse_iterator adapters */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Forward declaration. -template class ACE_Array_Iterator; - -/** - * @class ACE_Array_Base - * - * @brief Implement a simple dynamic array - * - * This parametric class implements a simple dynamic array; - * resizing must be controlled by the user. No comparison or find - * operations are implemented. - */ -template -class ACE_Array_Base -{ -public: - - // Old/ACE-style traits. - typedef T TYPE; - typedef ACE_Array_Iterator ITERATOR; - - // STL-style typedefs/traits. - typedef T value_type; - typedef value_type * iterator; - typedef value_type const * const_iterator; - typedef value_type & reference; - typedef value_type const & const_reference; - typedef value_type * pointer; - typedef value_type const * const_pointer; - typedef ptrdiff_t difference_type; - typedef ACE_Allocator::size_type size_type; - - ACE_DECLARE_STL_REVERSE_ITERATORS - - // = Initialization and termination methods. - - /// Dynamically create an uninitialized array. - ACE_Array_Base (size_type size = 0, - ACE_Allocator * the_allocator = 0); - - /// Dynamically initialize the entire array to the . - ACE_Array_Base (size_type size, - T const & default_value, - ACE_Allocator * the_allocator = 0); - - /** - * The copy constructor performs initialization by making an exact - * copy of the contents of parameter , i.e., *this == s will - * return true. - */ - ACE_Array_Base (ACE_Array_Base const & s); - - /** - * Assignment operator performs an assignment by making an exact - * copy of the contents of parameter , i.e., *this == s will - * return true. Note that if the of is >= than - * we can copy it without reallocating. However, if - * is < we must delete the , - * reallocate a new , and then copy the contents of . - */ - void operator= (ACE_Array_Base const & s); - - /// Clean up the array (e.g., delete dynamically allocated memory). - ~ACE_Array_Base (void); - - // = Set/get methods. - - /// Set item in the array at location @a slot. Doesn't - /// perform range checking. - T & operator[] (size_type slot); - - /// Get item in the array at location @a slot. Doesn't - /// perform range checking. - T const & operator[] (size_type slot) const; - - /// Set an item in the array at location @a slot. Returns - /// -1 if @a slot is not in range, else returns 0. - int set (T const & new_item, size_type slot); - - /** - * Get an item in the array at location @a slot. Returns -1 if - * @a slot is not in range, else returns 0. Note that this function - * copies the item. If you want to avoid the copy, you can use - * the const operator [], but then you'll be responsible for range checking. - */ - int get (T & item, size_type slot) const; - - /// Returns the of the array. - size_type size (void) const; - - /** - * Changes the size of the array to match @a new_size. - * It copies the old contents into the new array. - * Return -1 on failure. - */ - int size (size_type new_size); - - /// Returns the of the array. - size_type max_size (void) const; - - /** - * Changes the size of the array to match @a new_size. - * It copies the old contents into the new array. - * Return -1 on failure. - * It does not affect new_size - */ - int max_size (size_type new_size); - - /** - * @name Forward Iterator Accessors - * - * Forward iterator accessors. - */ - //@{ - iterator begin (void); - iterator end (void); - const_iterator begin (void) const; - const_iterator end (void) const; - //@} - - /** - * @name Reverse Iterator Accessors - * - * Reverse iterator accessors. - */ - //@{ - reverse_iterator rbegin (void); - reverse_iterator rend (void); - const_reverse_iterator rbegin (void) const; - const_reverse_iterator rend (void) const; - //@} - - /// Swap the contents of this array with the given @a array in - /// an exception-safe manner. - void swap (ACE_Array_Base & array); - -protected: - - /// Returns 1 if @a slot is within range, i.e., 0 >= @a slot < - /// @c cur_size_, else returns 0. - bool in_range (size_type slot) const; - - /// Maximum size of the array, i.e., the total number of @c T elements - /// in @c array_. - size_type max_size_; - - /** - * Current size of the array. This starts out being == to - * . However, if we are assigned a smaller array, then - * will become less than . The purpose of - * keeping track of both sizes is to avoid reallocating memory if we - * don't have to. - */ - size_type cur_size_; - - /// Pointer to the array's storage buffer. - value_type * array_; - - /// Allocation strategy of the ACE_Array_Base. - ACE_Allocator * allocator_; - - friend class ACE_Array_Iterator; -}; - -// **************************************************************** - -/** - * @class ACE_Array_Iterator - * - * @brief Implement an iterator over an ACE_Array. - * - * This iterator is safe in the face of array element deletions. - * But it is NOT safe if the array is resized (via the ACE_Array - * assignment operator) during iteration. That would be very - * odd, and dangerous. - */ -template -class ACE_Array_Iterator -{ -public: - // = Initialization method. - ACE_Array_Iterator (ACE_Array_Base &); - - // = Iteration methods. - - /// Pass back the @a next_item that hasn't been seen in the Array. - /// Returns 0 when all items have been seen, else 1. - int next (T *&next_item); - - /// Move forward by one element in the Array. Returns 0 when all the - /// items in the Array have been seen, else 1. - int advance (void); - - /// Returns 1 when all items have been seen, else 0. - int done (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - /// Pointer to the current item in the iteration. - size_t current_; - - /// Pointer to the Array we're iterating over. - ACE_Array_Base &array_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Array_Base.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Array_Base.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Array_Base.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" - -#endif /* ACE_ARRAY_BASE_H */ diff --git a/externals/ace/Array_Base.inl b/externals/ace/Array_Base.inl deleted file mode 100644 index 046c1bffc89..00000000000 --- a/externals/ace/Array_Base.inl +++ /dev/null @@ -1,146 +0,0 @@ -// -*- C++ -*- -// -// $Id: Array_Base.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Clean up the array (e.g., delete dynamically allocated memory). -template ACE_INLINE -ACE_Array_Base::~ACE_Array_Base (void) -{ - ACE_DES_ARRAY_FREE (this->array_, - this->max_size_, - this->allocator_->free, - T); -} - -template -ACE_INLINE typename ACE_Array_Base::iterator -ACE_Array_Base::begin (void) -{ - return this->array_; -} - -template -ACE_INLINE typename ACE_Array_Base::iterator -ACE_Array_Base::end (void) -{ - return this->array_ + this->cur_size_; -} - -template -ACE_INLINE typename ACE_Array_Base::const_iterator -ACE_Array_Base::begin (void) const -{ - return this->array_; -} - -template -ACE_INLINE typename ACE_Array_Base::const_iterator -ACE_Array_Base::end (void) const -{ - return this->array_ + this->cur_size_; -} - -template -ACE_INLINE typename ACE_Array_Base::reverse_iterator -ACE_Array_Base::rbegin (void) -{ - return reverse_iterator (this->end ()); -} - -template -ACE_INLINE typename ACE_Array_Base::reverse_iterator -ACE_Array_Base::rend (void) -{ - return reverse_iterator (this->begin ()); -} - -template -ACE_INLINE typename ACE_Array_Base::const_reverse_iterator -ACE_Array_Base::rbegin (void) const -{ - return const_reverse_iterator (this->end ()); -} - -template -ACE_INLINE typename ACE_Array_Base::const_reverse_iterator -ACE_Array_Base::rend (void) const -{ - return const_reverse_iterator (this->begin ()); -} - -template ACE_INLINE typename ACE_Array_Base::size_type -ACE_Array_Base::size (void) const -{ - return this->cur_size_; -} - -template ACE_INLINE typename ACE_Array_Base::size_type -ACE_Array_Base::max_size (void) const -{ - return this->max_size_; -} - -template ACE_INLINE bool -ACE_Array_Base::in_range (typename ACE_Array_Base::size_type index) const -{ - return index < this->cur_size_; -} - -template ACE_INLINE T & -ACE_Array_Base::operator[] (typename ACE_Array_Base::size_type index) -{ - return this->array_[index]; -} - -template ACE_INLINE const T & -ACE_Array_Base::operator[] (typename ACE_Array_Base::size_type index) const -{ - return this->array_[index]; -} - -// **************************************************************** - -template ACE_INLINE void -ACE_Array_Iterator::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - // ACE_TRACE ("ACE_Array_Iterator::dump"); -#endif /* ACE_HAS_DUMP */ -} - -template ACE_INLINE -ACE_Array_Iterator::ACE_Array_Iterator (ACE_Array_Base &a) - : current_ (0), - array_ (a) -{ - // ACE_TRACE ("ACE_Array_Iterator::ACE_Array_Iterator"); -} - -template ACE_INLINE int -ACE_Array_Iterator::advance (void) -{ - // ACE_TRACE ("ACE_Array_Iterator::advance"); - - if (this->current_ < array_.size ()) - { - ++this->current_; - return 1; - } - else - { - // Already finished iterating. - return 0; - } -} - -template ACE_INLINE int -ACE_Array_Iterator::done (void) const -{ - ACE_TRACE ("ACE_Array_Iterator::done"); - - return this->current_ >= array_.size (); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Array_Map.cpp b/externals/ace/Array_Map.cpp deleted file mode 100644 index 5530a8b54b6..00000000000 --- a/externals/ace/Array_Map.cpp +++ /dev/null @@ -1,299 +0,0 @@ -// $Id: Array_Map.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#ifndef ACE_ARRAY_MAP_CPP -#define ACE_ARRAY_MAP_CPP - -#include "ace/Array_Map.h" - -#ifndef __ACE_INLINE__ -# include "ace/Array_Map.inl" -#endif /* !__ACE_INLINE__ */ - -#include "ace/checked_iterator.h" - -#include - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -#ifndef ACE_LACKS_MEMBER_TEMPLATES -template -template -ACE_Array_Map::ACE_Array_Map (InputIterator f, - InputIterator l) - : size_ (l - f) - , capacity_ (size_) - , nodes_ (size_ == 0 ? 0 : new value_type[size_]) -{ - (void) std::copy (f, - l, - ACE_make_checked_array_iterator (this->begin (), - this->size_)); - -// iterator n = this->begin (); - -// for (InputIterator i = f; i != l; ++i, ++n) -// *n = *i; -} -#else -template -ACE_Array_Map::ACE_Array_Map ( - typename ACE_Array_Map::const_iterator f, - typename ACE_Array_Map::const_iterator l) - : size_ (l - f) - , capacity_ (size_) - , nodes_ (size_ == 0 ? 0 : new value_type[size_]) -{ - (void) std::copy (f, - l, - ACE_make_checked_array_iterator (this->begin (), - this->size_)); - -// iterator n = this->begin (); - -// for (const_iterator i = f; i != l; ++i, ++n) -// *n = *i; -} -#endif /* !ACE_LACKS_MEMBER_TEMPLATES */ - -template -ACE_Array_Map::ACE_Array_Map ( - ACE_Array_Map const & map) - : size_ (map.size_) - , capacity_ (map.size_) - , nodes_ (size_ == 0 ? 0 : new value_type[size_]) -{ - std::copy (map.begin (), - map.end (), - ACE_make_checked_array_iterator (this->begin (), - this->size_)); - -// iterator f = map.begin (); -// iterator l = map.end (); -// iterator n = this->begin (); - -// for (iterator i = f; i != l; ++i, ++n) -// *n = *i; -} - -template -ACE_Array_Map::~ACE_Array_Map (void) -{ - delete[] this->nodes_; -} - -template -void -ACE_Array_Map::swap ( - ACE_Array_Map & map) -{ - std::swap (this->size_, map.size_); - std::swap (this->capacity_, map.capacity_); - std::swap (this->nodes_, map.nodes_); -} - -template -std::pair::iterator, bool> -ACE_Array_Map::insert ( - typename ACE_Array_Map::value_type const & x) -{ - // Linear insertion due to linear duplicate key search. - - bool inserted = false; - iterator i = this->find (x.first); - - if (i == this->end ()) - { - // Add the element to the array. - - size_type const old_size = this->size (); - this->grow (1); // Increase size by at least one. - - i = this->begin () + old_size; - *i = x; - - ++this->size_; - - inserted = true; - } - - return std::make_pair (i, inserted); -} - -#ifndef ACE_LACKS_MEMBER_TEMPLATES -template -template -void -ACE_Array_Map::insert (InputIterator f, InputIterator l) -{ - this->grow (l - f); // Preallocate storage. - - for (InputIterator i = f; i != l; ++i) - { - (void) this->insert (*i); - } -} -#else -template -void -ACE_Array_Map::insert ( - typename ACE_Array_Map::const_iterator f, - typename ACE_Array_Map::const_iterator l) -{ - this->grow (l - f); // Preallocate storage. - - for (const_iterator i = f; i != l; ++i) - { - (void) this->insert (*i); - } -} -#endif /* ACE_LACKS_MEMBER_TEMPLATES */ - -template -void -ACE_Array_Map::erase ( - typename ACE_Array_Map::iterator pos) -{ - iterator const first = this->begin (); - iterator const last = this->end (); - - if (pos >= first && pos < last) - { - if (pos != last - 1) - { - // Relocate the tail element to the location of the erased - // element to prevent introduction of "holes" in the - // underlying array. - *pos = *(last - 1); - } - - // Explicitly destroy the tail element by assigning a default - // constructed instance to it. Note that this also works for - // the case of a map of size 1. - *(last - 1) = value_type (); - - --this->size_; - } -} - -template -typename ACE_Array_Map::size_type -ACE_Array_Map::erase ( - typename ACE_Array_Map::key_type const & k) -{ - iterator pos = this->find (k); - - size_type const old_size = this->size_; - - this->erase (pos); - - return old_size - this->size_; -} - -template -void -ACE_Array_Map::erase ( - typename ACE_Array_Map::iterator first, - typename ACE_Array_Map::iterator last) -{ - if (this->begin () <= first && first < last && last < this->end ()) - for (iterator i = first; i != last; ++i) - this->erase (i); -} - -template -void -ACE_Array_Map::clear (void) -{ - this->size_ = 0; // No need to deallocate array nor destroy elements. -} - -template -typename ACE_Array_Map::iterator -ACE_Array_Map::find ( - typename ACE_Array_Map::key_type const & k) -{ - iterator const the_end = this->end (); - - EqualTo eq; - - for (iterator i = this->begin (); i != the_end; ++i) - if (eq (k, i->first)) - return i; - - return this->end (); -} - -template -typename ACE_Array_Map::const_iterator -ACE_Array_Map::find ( - typename ACE_Array_Map::key_type const & k) const -{ - const_iterator const the_end = this->end (); - - EqualTo eq; - - for (const_iterator i = this->begin (); i != the_end; ++i) - if (eq (k, i->first)) - return i; - - return this->end (); -} - -template -void -ACE_Array_Map::grow ( - typename ACE_Array_Map::size_type s) -{ - if (this->size () + s > this->capacity_) - { - // This implementation focuses more on static footprint than - // speed. - - // Strongly exception safe. - - ACE_Array_Map temp (this->size () + s); - - std::copy (this->begin (), - this->end (), - ACE_make_checked_array_iterator (temp.begin (), - temp.capacity_)); - - size_type const n = this->size (); // Do not swap out the size - // since we bypassed the - // temporary map's element - // counting code. - this->swap (temp); - - this->size_ = n; - } -} - -// --------------------------------------------------------------- - -template -bool -operator== (ACE_Array_Map const & lhs, - ACE_Array_Map const & rhs) -{ - // Do not include Array_Map capacity in comparison. It isn't useful - // in this case. - - return (lhs.size () == rhs.size () - && std::equal (lhs.begin (), - lhs.end (), - ACE_make_checked_array_iterator (rhs.begin (), - rhs.size ()))); -} - -template -bool -operator< (ACE_Array_Map const & lhs, - ACE_Array_Map const & rhs) -{ - return std::lexicographical_compare (lhs.begin (), lhs.end (), - rhs.begin (), rhs.end ()); -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_ARRAY_MAP_CPP */ diff --git a/externals/ace/Array_Map.h b/externals/ace/Array_Map.h deleted file mode 100644 index 1515ea45529..00000000000 --- a/externals/ace/Array_Map.h +++ /dev/null @@ -1,300 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Array_Map.h - * - * $Id: Array_Map.h 84136 2009-01-12 11:01:17Z johnnyw $ - * - * Light weight array-based map with fast iteration but linear - * (i.e. O(n)) search times. STL-style interface is exposed. - * - * @note This class requires the STL generic algorithms and - * reverse_iterator adapter. - * - * @author Ossama Othman - */ -//============================================================================= - - -#ifndef ACE_ARRAY_MAP_H -#define ACE_ARRAY_MAP_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include -#include -#include - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Array_Map - * - * @brief Light weight array-based map with fast iteration, but linear - * (i.e. O(n)) search times. - * - * Map implementation that focuses on small footprint and fast - * iteration. Search times are, however, linear (O(n)) meaning that - * this map isn't suitable for large data sets that will be searched - * in performance critical areas of code. Iteration over large data - * sets, however, is faster than linked list-based maps, for example, - * since spatial locality is maximized through the use of contiguous - * arrays as the underlying storage. - * @par - * An @c ACE_Array_Map is a unique associative container, meaning that - * duplicate values may not be added to the map. It is also pair - * associative (value_type is a std::pair<>). It is not a sorted - * container. - * @par - * An STL @c std::map -like interface is exposed by this class - * portability. Furthermore, this map's iterators are compatible with - * STL algorithms. - * @par - * Requirements and Performance Characteristics - * - Internal Structure - * Array - * - Duplicates allowed? - * No - * - Random access allowed? - * Yes - * - Search speed - * O(n) - * - Insert/replace speed - * O(n), can be longer if the map has to resize - * - Iterator still valid after change to container? - * No - * - Frees memory for removed elements? - * Yes - * - Items inserted by - * Value - * - Requirements for key type - * -# Default constructor - * -# Copy constructor - * -# operator= - * -# operator== - * - Requirements for object type - * -# Default constructor - * -# Copy constructor - * -# operator= - */ -template > -class ACE_Array_Map -{ -public: - - // STL-style typedefs/traits. - typedef Key key_type; - typedef Value data_type; - typedef std::pair value_type; - typedef value_type * iterator; - typedef value_type const * const_iterator; - typedef value_type & reference; - typedef value_type const & const_reference; - typedef value_type * pointer; - typedef value_type const * const_pointer; - typedef ptrdiff_t difference_type; - typedef size_t size_type; - - ACE_DECLARE_STL_REVERSE_ITERATORS - - /// Default Constructor. - /** - * Create an empty map with a preallocated buffer of size @a s. - */ - ACE_Array_Map (size_type s = 0); - -#ifndef ACE_LACKS_MEMBER_TEMPLATES - template - ACE_Array_Map (InputIterator f, InputIterator l); -#else - ACE_Array_Map (const_iterator f, const_iterator l); -#endif /* !ACE_LACKS_MEMBER_TEMPLATES */ - - ACE_Array_Map (ACE_Array_Map const & map); - ACE_Array_Map & operator= (ACE_Array_Map const & map); - - /// Destructor. - ~ACE_Array_Map (void); - - /** - * @name Forward Iterator Accessors - * - * Forward iterator accessors. - */ - //@{ - iterator begin (void); - iterator end (void); - const_iterator begin (void) const; - const_iterator end (void) const; - //@} - - /** - * @name Reverse Iterator Accessors - * - * Reverse iterator accessors. - */ - //@{ - reverse_iterator rbegin (void); - reverse_iterator rend (void); - const_reverse_iterator rbegin (void) const; - const_reverse_iterator rend (void) const; - //@} - - /// Return current size of map. - /** - * @return The number of elements in the map. - */ - size_type size (void) const; - - /// Maximum number of elements the map can hold. - size_type max_size (void) const; - - /// Return @c true if the map is empty, else @c false. - bool is_empty (void) const; // ACE style - - /** - * Return @c true if the map is empty, else @c false. We recommend - * using @c is_empty() instead since it's more consistent with the - * ACE container naming conventions. - */ - bool empty (void) const; // STL style - - /// Swap the contents of this map with the given @a map in an - /// exception-safe manner. - void swap (ACE_Array_Map & map); - - /// Insert the value @a x into the map. - /** - * STL-style map insertion method. - * - * @param x @c std::pair containing key and datum. - * - * @return @c std::pair::second will be @c false if the map already - * contains a value with the same key as @a x. - */ - std::pair insert (value_type const & x); - -#ifndef ACE_LACKS_MEMBER_TEMPLATES - /// Insert range of elements into map. - template - void insert (InputIterator f, InputIterator l); -#else - /// Insert range of elements into map. - void insert (const_iterator f, const_iterator l); -#endif /* ACE_LACKS_MEMBER_TEMPLATES */ - - /// Remove element at position @a pos from the map. - void erase (iterator pos); - - /// Remove element corresponding to key @a k from the map. - /** - * @return Number of elements that were erased. - */ - size_type erase (key_type const & k); - - /// Remove range of elements [@a first, @a last) from the map. - /** - * @note [@a first, @a last) must be valid range within the map. - */ - void erase (iterator first, iterator last); - - /// Clear contents of map. - /** - * @note This a constant time (O(1)) operation. - */ - void clear (void); - - /** - * @name Search Operations - * - * Search the map for data corresponding to key @a k. - */ - //@{ - /** - * @return @c end() if data corresponding to key @a k is not in the - * map. - */ - iterator find (key_type const & k); - - /** - * @return @c end() if data corresponding to key @a k is not in the - * map. - */ - const_iterator find (key_type const & k) const; - //@} - - /// Count the number of elements corresponding to key @a k. - /** - * @return In the case of this map, the count will always be one if - * such exists in the map. - */ - size_type count (key_type const & k); - - /// Convenience array index operator. - /** - * Array index operator that allows insertion and retrieval of - * elements using an array index syntax, such as: - * @par - * map["Foo"] = 12; - */ - data_type & operator[] (key_type const & k); - -private: - - /// Increase size of underlying buffer by @a s. - void grow (size_type s); - -private: - - /// Number of elements in the map. - size_type size_; - - /// Current size of underlying array. - /** - * @note @c capacity_ is always greater than or equal to @c size_; - */ - size_type capacity_; - - /// Underlying array containing keys and data. - value_type * nodes_; - -}; - -// -------------------------------------------------------------- - -/// @c ACE_Array_Map equality operator. -template -bool operator== (ACE_Array_Map const & lhs, - ACE_Array_Map const & rhs); - -/// @c ACE_Array_Map lexicographical comparison operator. -template -bool operator< (ACE_Array_Map const & lhs, - ACE_Array_Map const & rhs); - -// -------------------------------------------------------------- - -ACE_END_VERSIONED_NAMESPACE_DECL - -#ifdef __ACE_INLINE__ -# include "ace/Array_Map.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -# include "ace/Array_Map.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Array_Map.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" - -#endif /* ACE_ARRAY_MAP_H */ diff --git a/externals/ace/Array_Map.inl b/externals/ace/Array_Map.inl deleted file mode 100644 index b053dc0a441..00000000000 --- a/externals/ace/Array_Map.inl +++ /dev/null @@ -1,133 +0,0 @@ -// -*- C++ -*- -// -// $Id: Array_Map.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template -ACE_INLINE -ACE_Array_Map::ACE_Array_Map ( - typename ACE_Array_Map::size_type s) - : size_ (0) - , capacity_ (s) - , nodes_ (s == 0 ? 0 : new value_type[s]) -{ -} - -template -ACE_INLINE ACE_Array_Map & -ACE_Array_Map::operator= ( - ACE_Array_Map const & map) -{ - // Strongly exception-safe assignment. - - ACE_Array_Map temp (map); - this->swap (temp); - return *this; -} - -template -ACE_INLINE typename ACE_Array_Map::iterator -ACE_Array_Map::begin (void) -{ - return this->nodes_; -} - -template -ACE_INLINE typename ACE_Array_Map::iterator -ACE_Array_Map::end (void) -{ - return this->nodes_ + this->size_; -} - -template -ACE_INLINE typename ACE_Array_Map::const_iterator -ACE_Array_Map::begin (void) const -{ - return this->nodes_; -} - -template -ACE_INLINE typename ACE_Array_Map::const_iterator -ACE_Array_Map::end (void) const -{ - return this->nodes_ + this->size_; -} - -template -ACE_INLINE typename ACE_Array_Map::reverse_iterator -ACE_Array_Map::rbegin (void) -{ - return reverse_iterator (this->end ()); -} - -template -ACE_INLINE typename ACE_Array_Map::reverse_iterator -ACE_Array_Map::rend (void) -{ - return reverse_iterator (this->begin ()); -} - -template -ACE_INLINE typename ACE_Array_Map::const_reverse_iterator -ACE_Array_Map::rbegin (void) const -{ - return const_reverse_iterator (this->end ()); -} - -template -ACE_INLINE typename ACE_Array_Map::const_reverse_iterator -ACE_Array_Map::rend (void) const -{ - return const_reverse_iterator (this->begin ()); -} - -template -ACE_INLINE typename ACE_Array_Map::size_type -ACE_Array_Map::size (void) const -{ - return this->size_; -} - -template -ACE_INLINE typename ACE_Array_Map::size_type -ACE_Array_Map::max_size (void) const -{ - return size_type (-1) / sizeof (value_type); -} - -template -ACE_INLINE bool -ACE_Array_Map::is_empty (void) const -{ - return this->size_ == 0; -} - -// The following method is deprecated. - -template -ACE_INLINE bool -ACE_Array_Map::empty (void) const -{ - return this->is_empty (); -} - -template -ACE_INLINE typename ACE_Array_Map::size_type -ACE_Array_Map::count ( - typename ACE_Array_Map::key_type const & k) -{ - return - (this->find (k) == this->end () ? 0 : 1); // Only one datum per key. -} - -template -ACE_INLINE typename ACE_Array_Map::data_type & -ACE_Array_Map::operator[] ( - typename ACE_Array_Map::key_type const & k) -{ - iterator i = (this->insert (value_type (k, data_type ()))).first; - return (*i).second; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Assert.cpp b/externals/ace/Assert.cpp deleted file mode 100644 index 4a71c9e5a9d..00000000000 --- a/externals/ace/Assert.cpp +++ /dev/null @@ -1,24 +0,0 @@ -// $Id: Assert.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Assert.h" -#include "ace/Log_Msg.h" - -ACE_RCSID(ace, Assert, "$Id: Assert.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// The following ASSERT macro is courtesy of Alexandre Karev -// . -void -__ace_assert(const char *file, int line, const ACE_TCHAR *expression) -{ - int error = ACE_Log_Msg::last_error_adapter (); - ACE_Log_Msg *log = ACE_Log_Msg::instance (); - - log->set (file, line, -1, error, log->restart (), - log->msg_ostream (), log->msg_callback ()); - - log->log (LM_ERROR, ACE_TEXT ("ACE_ASSERT: file %N, line %l assertion failed for '%s'.%a\n"), expression, -1); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Assert.h b/externals/ace/Assert.h deleted file mode 100644 index 89363d4c69a..00000000000 --- a/externals/ace/Assert.h +++ /dev/null @@ -1,40 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Assert.h - * - * $Id: Assert.h 82808 2008-09-23 11:27:27Z smcqueen $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_ASSERT_H -#define ACE_ASSERT_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#include /**/ "ace/config-all.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL -ACE_Export void __ace_assert(const char *file, int line, const ACE_TCHAR *expression); -ACE_END_VERSIONED_NAMESPACE_DECL - -#define ACE_TEST_ASSERT(X) \ - ((X) \ - ? static_cast(0) \ - : ACE_VERSIONED_NAMESPACE_NAME::__ace_assert(__FILE__, __LINE__, ACE_TEXT_CHAR_TO_TCHAR (#X))) - -#if defined (ACE_NDEBUG) -#define ACE_ASSERT(x) \ - (static_cast(0)) -#else -#define ACE_ASSERT(X) ACE_TEST_ASSERT(X) -#endif /* ACE_NDEBUG */ - -#include /**/ "ace/post.h" - -#endif /* ACE_ASSERT */ diff --git a/externals/ace/Asynch_Acceptor.cpp b/externals/ace/Asynch_Acceptor.cpp deleted file mode 100644 index 3afb27c7b7d..00000000000 --- a/externals/ace/Asynch_Acceptor.cpp +++ /dev/null @@ -1,514 +0,0 @@ -/* -*- C++ -*- */ -// $Id: Asynch_Acceptor.cpp 85213 2009-04-29 16:34:20Z shuston $ - -#ifndef ACE_ASYNCH_ACCEPTOR_C -#define ACE_ASYNCH_ACCEPTOR_C - -#include "ace/Asynch_Acceptor.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_RCSID(ace, Asynch_Acceptor, "$Id: Asynch_Acceptor.cpp 85213 2009-04-29 16:34:20Z shuston $") - -#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) || defined (ACE_HAS_AIO_CALLS) -// This only works on platforms that support async i/o. - -#include "ace/OS_Errno.h" -#include "ace/OS_Memory.h" -#include "ace/OS_NS_sys_socket.h" -#include "ace/Log_Msg.h" -#include "ace/Message_Block.h" -#include "ace/INET_Addr.h" -#include "ace/SOCK_Stream.h" -#include "ace/Sock_Connect.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template -ACE_Asynch_Acceptor::ACE_Asynch_Acceptor (void) - : listen_handle_ (ACE_INVALID_HANDLE), - pass_addresses_ (false), - validate_new_connection_ (false), - reissue_accept_ (1), - bytes_to_read_ (0) -{ -} - -template -ACE_Asynch_Acceptor::~ACE_Asynch_Acceptor (void) -{ - // Close down the listen socket - if (this->listen_handle_ != ACE_INVALID_HANDLE) - { - ACE_OS::closesocket (this->listen_handle_); - this->listen_handle_ = ACE_INVALID_HANDLE; - } -} - -template int -ACE_Asynch_Acceptor::open (const ACE_INET_Addr &address, - size_t bytes_to_read, - bool pass_addresses, - int backlog, - int reuse_addr, - ACE_Proactor *proactor, - bool validate_new_connection, - int reissue_accept, - int number_of_initial_accepts) -{ - ACE_TRACE ("ACE_Asynch_Acceptor<>::open"); - - this->proactor (proactor); - this->pass_addresses_ = pass_addresses; - this->bytes_to_read_ = bytes_to_read; - this->validate_new_connection_ = validate_new_connection; - this->reissue_accept_ = reissue_accept; - this->addr_family_ = address.get_type (); - - // Create the listener socket - this->listen_handle_ = ACE_OS::socket (address.get_type (), SOCK_STREAM, 0); - if (this->listen_handle_ == ACE_INVALID_HANDLE) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_OS::socket")), - -1); - // Initialize the ACE_Asynch_Accept - if (this->asynch_accept_.open (*this, - this->listen_handle_, - 0, - this->proactor ()) == -1) - { - ACE_Errno_Guard g (errno); - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_Asynch_Accept::open"))); - ACE_OS::closesocket (this->listen_handle_); - this->listen_handle_ = ACE_INVALID_HANDLE; - return -1; - } - - if (reuse_addr) - { - // Reuse the address - int one = 1; - if (ACE_OS::setsockopt (this->listen_handle_, - SOL_SOCKET, - SO_REUSEADDR, - (const char*) &one, - sizeof one) == -1) - { - ACE_Errno_Guard g (errno); - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_OS::setsockopt"))); - ACE_OS::closesocket (this->listen_handle_); - this->listen_handle_ = ACE_INVALID_HANDLE; - return -1; - } - } - - // If port is not specified, bind to any port. - static ACE_INET_Addr sa (ACE_sap_any_cast (const ACE_INET_Addr &)); - - if (address == sa && - ACE::bind_port (this->listen_handle_, - INADDR_ANY, - address.get_type()) == -1) - { - ACE_Errno_Guard g (errno); - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE::bind_port"))); - ACE_OS::closesocket (this->listen_handle_); - this->listen_handle_ = ACE_INVALID_HANDLE; - return -1; - } - - // Bind to the specified port. - if (ACE_OS::bind (this->listen_handle_, - reinterpret_cast (address.get_addr ()), - address.get_size ()) == -1) - { - ACE_Errno_Guard g (errno); - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_OS::bind"))); - ACE_OS::closesocket (this->listen_handle_); - this->listen_handle_ = ACE_INVALID_HANDLE; - return -1; - } - - // Start listening. - if (ACE_OS::listen (this->listen_handle_, backlog) == -1) - { - ACE_Errno_Guard g (errno); - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_OS::listen"))); - ACE_OS::closesocket (this->listen_handle_); - this->listen_handle_ = ACE_INVALID_HANDLE; - return -1; - } - - // For the number of . - if (number_of_initial_accepts == -1) - number_of_initial_accepts = backlog; - - for (int i = 0; i < number_of_initial_accepts; i++) - { - // Initiate accepts. - if (this->accept (bytes_to_read) == -1) - { - ACE_Errno_Guard g (errno); - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_Asynch_Acceptor::accept"))); - ACE_OS::closesocket (this->listen_handle_); - this->listen_handle_ = ACE_INVALID_HANDLE; - return -1; - } - } - - return 0; -} - -template int -ACE_Asynch_Acceptor::set_handle (ACE_HANDLE listen_handle) -{ - ACE_TRACE ("ACE_Asynch_Acceptor<>::set_handle"); - - // Take ownership of the - this->listen_handle_ = listen_handle; - - // Reinitialize the ACE_Asynch_Accept - if (this->asynch_accept_.open (*this, - this->listen_handle_, - 0, - this->proactor ()) == -1) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_Asynch_Accept::open")), - -1); - return 0; -} - -template ACE_HANDLE -ACE_Asynch_Acceptor::get_handle (void) const -{ - return this->listen_handle_; -} - -template int -ACE_Asynch_Acceptor::accept (size_t bytes_to_read, const void *act) -{ - ACE_TRACE ("ACE_Asynch_Acceptor<>::accept"); - - ACE_Message_Block *message_block = 0; - // The space_needed calculation is drive by needs of Windows. POSIX doesn't - // need to extra 16 bytes, but it doesn't hurt. - size_t space_needed = sizeof (sockaddr_in) + 16; -#if defined (ACE_HAS_IPV6) - if (PF_INET6 == this->addr_family_) - space_needed = sizeof (sockaddr_in6) + 16; -#endif /* ACE_HAS_IPV6 */ - space_needed = (2 * space_needed) + bytes_to_read; - - // Create a new message block big enough for the addresses and data - ACE_NEW_RETURN (message_block, - ACE_Message_Block (space_needed), - -1); - - // Initiate asynchronous accepts - if (this->asynch_accept_.accept (*message_block, - bytes_to_read, - ACE_INVALID_HANDLE, - act, - 0, - ACE_SIGRTMIN, - this->addr_family_) == -1) - { - // Cleanup on error - message_block->release (); - return -1; - } - return 0; -} - -template void -ACE_Asynch_Acceptor::handle_accept (const ACE_Asynch_Accept::Result &result) -{ - ACE_TRACE ("ACE_Asynch_Acceptor<>::handle_accept"); - - // Variable for error tracking - int error = 0; - - // If the asynchronous accept fails. - if (!result.success () || result.accept_handle () == ACE_INVALID_HANDLE) - { - error = 1; - } - -#if defined (ACE_WIN32) - // In order to use accept handle with other Window Sockets 1.1 - // functions, we call the setsockopt function with the - // SO_UPDATE_ACCEPT_CONTEXT option. This option initializes the - // socket so that other Windows Sockets routines to access the - // socket correctly. - if (!error && - ACE_OS::setsockopt (result.accept_handle (), - SOL_SOCKET, - SO_UPDATE_ACCEPT_CONTEXT, - (char *) &this->listen_handle_, - sizeof (this->listen_handle_)) == -1) - { - error = 1; - } -#endif /* ACE_WIN32 */ - - // Parse address. - ACE_INET_Addr local_address; - ACE_INET_Addr remote_address; - if (!error && - (this->validate_new_connection_ || this->pass_addresses_)) - // Parse the addresses. - this->parse_address (result, - remote_address, - local_address); - - // Validate remote address - if (!error && - this->validate_new_connection_ && - (this->validate_connection (result, remote_address, local_address) == -1)) - { - error = 1; - } - - HANDLER *new_handler = 0; - if (!error) - { - // The Template method - new_handler = this->make_handler (); - if (new_handler == 0) - { - error = 1; - } - } - - // If no errors - if (!error) - { - // Update the Proactor. - new_handler->proactor (this->proactor ()); - - // Pass the addresses - if (this->pass_addresses_) - new_handler->addresses (remote_address, - local_address); - - // Pass the ACT - if (result.act () != 0) - new_handler->act (result.act ()); - - // Set up the handler's new handle value - new_handler->handle (result.accept_handle ()); - - // Initiate the handler - new_handler->open (result.accept_handle (), - result.message_block ()); - } - - // On failure, no choice but to close the socket - if (error && - result.accept_handle() != ACE_INVALID_HANDLE ) - ACE_OS::closesocket (result.accept_handle ()); - - // Delete the dynamically allocated message_block - result.message_block ().release (); - - // Start off another asynchronous accept to keep the backlog going, - // unless we closed the listen socket already (from the destructor), - // or this callback is the result of a canceled/aborted accept. - if (this->should_reissue_accept () && - this->listen_handle_ != ACE_INVALID_HANDLE -#if defined (ACE_WIN32) - && result.error () != ERROR_OPERATION_ABORTED -#else - && result.error () != ECANCELED -#endif - ) - this->accept (this->bytes_to_read_, result.act ()); -} - -template int -ACE_Asynch_Acceptor::validate_connection - (const ACE_Asynch_Accept::Result& /* result */, - const ACE_INET_Addr& /* remote */, - const ACE_INET_Addr& /* local */) -{ - // Default implementation always validates the remote address. - return 0; -} - -template int -ACE_Asynch_Acceptor::cancel (void) -{ - ACE_TRACE ("ACE_Asynch_Acceptor<>::cancel"); - - // All I/O operations that are canceled will complete with the error - // ERROR_OPERATION_ABORTED. All completion notifications for the I/O - // operations will occur normally. -#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) - return (int) ::CancelIo (this->listen_handle_); -#else - // Supported now - return this->asynch_accept_.cancel(); -#endif /* defined (ACE_HAS_WIN32_OVERLAPPED_IO) */ -} - -template void -ACE_Asynch_Acceptor::parse_address (const - ACE_Asynch_Accept::Result &result, - ACE_INET_Addr &remote_address, - ACE_INET_Addr &local_address) -{ - ACE_TRACE ("ACE_Asynch_Acceptor<>::parse_address"); - -#if defined (ACE_HAS_AIO_CALLS) - - // Use an ACE_SOCK to get the addresses - it knows how to deal with - // ACE_INET_Addr objects and get IPv4/v6 addresses. - ACE_SOCK_Stream str (result.accept_handle ()); - str.get_local_addr (local_address); - str.get_remote_addr (remote_address); - -#elif defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0) - - ACE_Message_Block &message_block = result.message_block (); - - sockaddr *local_addr = 0; - sockaddr *remote_addr = 0; - int local_size = 0; - int remote_size = 0; - // This matches setup in accept(). - size_t addr_size = sizeof (sockaddr_in) + 16; -#if defined (ACE_HAS_IPV6) - if (this->addr_family_ == PF_INET6) - addr_size = sizeof (sockaddr_in6) + 16; -#endif /* ACE_HAS_IPV6 */ - - ::GetAcceptExSockaddrs (message_block.rd_ptr (), - static_cast (this->bytes_to_read_), - static_cast (addr_size), - static_cast (addr_size), - &local_addr, - &local_size, - &remote_addr, - &remote_size); - - local_address.set (reinterpret_cast (local_addr), - local_size); - remote_address.set (reinterpret_cast (remote_addr), - remote_size); -#else - // just in case - errno = ENOTSUP; -#endif /* defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0) */ - return; -} - -template ACE_HANDLE -ACE_Asynch_Acceptor::handle (void) const -{ - return this->listen_handle_; -} - -template void -ACE_Asynch_Acceptor::handle (ACE_HANDLE h) -{ - ACE_Handler::handle (h); -} - -template ACE_Asynch_Accept & -ACE_Asynch_Acceptor::asynch_accept (void) -{ - return this->asynch_accept_; -} - -template HANDLER * -ACE_Asynch_Acceptor::make_handler (void) -{ - // Default behavior - HANDLER *handler = 0; - ACE_NEW_RETURN (handler, - HANDLER, - 0); - return handler; -} - -/* static */ -template size_t -ACE_Asynch_Acceptor::address_size (void) -{ - return sizeof (sockaddr) + sizeof (sockaddr_in); -} - -template bool -ACE_Asynch_Acceptor::pass_addresses (void) const -{ - return this->pass_addresses_; -} - -template void -ACE_Asynch_Acceptor::pass_addresses (bool new_value) -{ - this->pass_addresses_ = new_value; -} - -template bool -ACE_Asynch_Acceptor::validate_new_connection (void) const -{ - return this->validate_new_connection_; -} - -template void -ACE_Asynch_Acceptor::validate_new_connection (bool new_value) -{ - this->validate_new_connection_ = new_value; -} - -template int -ACE_Asynch_Acceptor::reissue_accept (void) const -{ - return this->reissue_accept_; -} - -template void -ACE_Asynch_Acceptor::reissue_accept (int new_value) -{ - this->reissue_accept_ = new_value; -} - -template size_t -ACE_Asynch_Acceptor::bytes_to_read (void) const -{ - return this->bytes_to_read_; -} - -template void -ACE_Asynch_Acceptor::bytes_to_read (size_t new_value) -{ - this->bytes_to_read_ = new_value; -} - -template int -ACE_Asynch_Acceptor::should_reissue_accept (void) -{ - return this->reissue_accept_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_WIN32 || ACE_HAS_AIO_CALLS */ -#endif /* ACE_ASYNCH_ACCEPTOR_C */ diff --git a/externals/ace/Asynch_Acceptor.h b/externals/ace/Asynch_Acceptor.h deleted file mode 100644 index 29872d59482..00000000000 --- a/externals/ace/Asynch_Acceptor.h +++ /dev/null @@ -1,281 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file Asynch_Acceptor.h - * - * $Id: Asynch_Acceptor.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Irfan Pyarali (irfan@cs.wustl.edu) - */ -//============================================================================= - -#ifndef ACE_ASYNCH_ACCEPTOR_H -#define ACE_ASYNCH_ACCEPTOR_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) || defined (ACE_HAS_AIO_CALLS) -// This only works on platforms that support async i/o. - -#include "ace/Default_Constants.h" -#include "ace/Asynch_IO.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Forward declarations -class ACE_Message_Block; -class ACE_INET_Addr; - -/** - * @class ACE_Asynch_Acceptor - * - * @brief This class is an example of the Acceptor Pattern. This class - * will accept new connections and create new HANDLER to handle - * the new connections. - * - * Unlike the ACE_Acceptor, however, this class is designed to - * be used asynchronously. - */ -template -class ACE_Asynch_Acceptor : public ACE_Handler -{ -public: - /// A do nothing constructor. - ACE_Asynch_Acceptor (void); - - /// Virtual destruction - virtual ~ACE_Asynch_Acceptor (void); - - /** - * @c open starts one or more asynchronous accept requests on a - * @a address. Each accept operation may optionally read an - * initial buffer from the new connection when accepted. - * - * @param address The address to listen/accept connections on. - * If the address does not specify a port, a random - * port is selected and bound. - * @param bytes_to_read Optional, specifies the maximum number of bytes - * to read with the accept. The buffer for the initial - * data is allocated internally and passed to the - * @c ACE_Service_Handler::open() hook method. It is - * legitimate only during the @c open() method and must - * be copied if required after @c open() returns. - * This pre-read function works only on Windows. - * @param pass_addresses Optional, a non-zero value indicates that - * the local and peer addresses should be passed to the - * associated @c ACE_Service_Handler::addresses() method - * after any call to @c validate_new_connection() and prior - * to the @c open() hook method call. - * @param backlog Optional, defaulting to @c ACE_DEFAULT_ASYNCH_BACKLOG (which - * can be adjusted in your platform's @c config.h file). - * Specifies the listening backlog for the listening socket. - * @param reuse_addr Optional, indicates whether the @c SO_REUSEADDR - * option is set on the listening socket or not. - * @param proactor Optional, pointer to the @c ACE_Proactor to use for - * demultiplexing asynchronous accepts. If 0, the - * process's singleton @c ACE_Proactor is used. - * @param validate_new_connection Optional, if true, this object's - * @c validate_connection() method is called after - * the accept completes, but before the service handler's - * @c open() hook method is called. If @c - * validate_connection() returns -1, the newly-accepted - * socket is immediately closed, and the @c addresses() - * method is not called. - * @param reissue_accept Optional, if non-zero (the default), a new - * asynchronous accept operation is started after each - * completion, whether the completion is for success or - * failure, and whether or not a successfully-accepted - * connection is subsequently refused. - * @param number_of_initial_accepts Optional, the number of asynchronous - * accepts that are started immediately. If -1 (the - * default), the value of @a backlog is used. - * - * @note On Windows, the peer address is only available at the time - * the connection is accepted. Therefore, if you require the peer - * address on Windows, do not rely on the - * @c ACE_SOCK::get_remote_addr() method - it won't work. You must - * supply a non-zero value for @a pass_addresses and obtain the - * peer address in the @c ACE_Service_Handler::addresses() method. - * - * @see ACE_INET_Addr - * @see ACE_Service_Handler - */ - virtual int open (const ACE_INET_Addr &address, - size_t bytes_to_read = 0, - bool pass_addresses = false, - int backlog = ACE_DEFAULT_ASYNCH_BACKLOG, - int reuse_addr = 1, - ACE_Proactor *proactor = 0, - bool validate_new_connection = false, - int reissue_accept = 1, - int number_of_initial_accepts = -1); - - /// Get the underlying handle. - virtual ACE_HANDLE get_handle (void) const; - - /** - * Set the underlying listen handle. It is the user's responsibility - * to make sure that the old listen handle has been appropriately - * closed and the all outstanding asynchronous operations have - * either completed or have been canceled on the old listen handle. - */ - virtual int set_handle (ACE_HANDLE handle); - - /// This initiates a new asynchronous accept operation. - /** - * You need only call this method if the @a reissue_accept argument - * passed to @c open() was 0. - */ - virtual int accept (size_t bytes_to_read = 0, const void *act = 0); - - /** - * Cancels all pending accepts operations issued by this object. - * - * @note On Windows, only accept operations initiated by the calling thread - * are canceled. - */ - virtual int cancel (void); - - /** - * Template method to validate peer before service is opened. - * This method is called after a new connection is accepted if the - * @a validate_connection argument to @c open() was non-zero or - * the @c validate_new_connection() method is called to turn this - * feature on. The default implementation returns 0. Users can - * reimplement this method to perform validation of the peer - * using it's address, running an authentication procedure (such as - * SSL) or anything else necessary or desireable. The return value - * from this method determines whether or not ACE will continue - * opening the service or abort the connection. - * - * @param result Result of the connection acceptance. - * @param remote Peer's address. - * @param local Local address connection was accepted at. - * - * @retval -1 ACE_Asynch_Acceptor will close the connection, and - * the service will not be opened. - * @retval 0 Service opening will proceeed. - */ - virtual int validate_connection (const ACE_Asynch_Accept::Result& result, - const ACE_INET_Addr &remote, - const ACE_INET_Addr& local); - - /** - * Template method for deciding whether to reissue accept. - * - * This hook method is called after each accept completes to decide if - * another accept should be initiated. If the method returns a non-zero - * value, another accept is initiated. - * - * The default implemenation always returns the value passed as the - * @c open() method's @a reissue_accept argument. That value can also - * be changed using the @c reissue_accept() method. - */ - virtual int should_reissue_accept (void); - - // - // These are low level tweaking methods - // - - /// Get flag that indicates if parsing and passing of addresses to - /// the service_handler is necessary. - virtual bool pass_addresses (void) const; - - /// Set flag that indicates if parsing and passing of addresses to - /// the service_handler is necessary. - virtual void pass_addresses (bool new_value); - - /// Get flag that indicates if address validation is required. - virtual bool validate_new_connection (void) const; - - /// Set flag that indicates if address validation is required. - virtual void validate_new_connection (bool new_value); - - /// Get flag that indicates if a new accept should be reissued when a accept - /// completes. - virtual int reissue_accept (void) const; - - /// Set flag that indicates if a new accept should be reissued when a accept - /// completes. - virtual void reissue_accept (int new_value); - - /// Get bytes to be read with the call. - virtual size_t bytes_to_read (void) const; - - /// Set bytes to be read with the call. - virtual void bytes_to_read (size_t new_value); - - /// @deprecated address_size() assumes IPv4 use, so is not always valid. - /// This method will be removed after ACE 5.5. Internal uses have been - /// changes to base needed sizes on the addr_family_ member. - static size_t address_size (void); - -protected: - - /// This is called when an outstanding accept completes. - virtual void handle_accept (const ACE_Asynch_Accept::Result &result); - - /// Return the listen handle. - ACE_HANDLE handle (void) const; - /// Set the listen handle. - void handle (ACE_HANDLE h); - - /// This parses the address from read buffer. - void parse_address (const ACE_Asynch_Accept::Result &result, - ACE_INET_Addr &remote_address, - ACE_INET_Addr &local_address); - - /// Return the asynch accept object. - ACE_Asynch_Accept &asynch_accept (void); - - /** - * This is the template method used to create new handler. - * Subclasses must overwrite this method if a new handler creation - * strategy is required. - */ - virtual HANDLER *make_handler (void); - -private: - /// Handle used to listen for new connections. - ACE_HANDLE listen_handle_; - - /// Asynch_Accept used to make life easier :-) - ACE_Asynch_Accept asynch_accept_; - - /// Flag that indicates if parsing of addresses is necessary. - bool pass_addresses_; - - /// Flag that indicates if address validation is required. - bool validate_new_connection_; - - /// Flag that indicates if a new accept should be reissued when a - /// accept completes. - int reissue_accept_; - - /// Bytes to be read with the call. - size_t bytes_to_read_; - - /// Address family used to open this object. Obtained from @a address passed - /// to @c open(). - int addr_family_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Asynch_Acceptor.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Asynch_Acceptor.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#endif /* ACE_HAS_WIN32_OVERLAPPED_IO || ACE_HAS_AIO_CALLS */ -#include /**/ "ace/post.h" -#endif /* ACE_ASYNCH_ACCEPTOR_H */ diff --git a/externals/ace/Asynch_Connector.cpp b/externals/ace/Asynch_Connector.cpp deleted file mode 100644 index 3d493069f00..00000000000 --- a/externals/ace/Asynch_Connector.cpp +++ /dev/null @@ -1,296 +0,0 @@ -// $Id: Asynch_Connector.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#ifndef ACE_ASYNCH_CONNECTOR_CPP -#define ACE_ASYNCH_CONNECTOR_CPP - -#include "ace/Asynch_Connector.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if (defined (ACE_WIN32) || defined (ACE_HAS_AIO_CALLS)) && !defined(ACE_HAS_WINCE) -// This only works on platforms that support async I/O. - -#include "ace/OS_NS_sys_socket.h" -#include "ace/OS_Memory.h" -#include "ace/Flag_Manip.h" -#include "ace/Log_Msg.h" -#include "ace/Message_Block.h" -#include "ace/INET_Addr.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template -ACE_Asynch_Connector::ACE_Asynch_Connector (void) - : pass_addresses_ (false), - validate_new_connection_ (false) -{ -} - -template -ACE_Asynch_Connector::~ACE_Asynch_Connector (void) -{ - //this->asynch_connect_.close (); -} - -template int -ACE_Asynch_Connector::open (bool pass_addresses, - ACE_Proactor *proactor, - bool validate_new_connection) -{ - this->proactor (proactor); - this->pass_addresses_ = pass_addresses; - this->validate_new_connection_ = validate_new_connection; - - // Initialize the ACE_Asynch_Connect - if (this->asynch_connect_.open (*this, - ACE_INVALID_HANDLE, - 0, - this->proactor ()) == -1) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_Asynch_Connect::open")), - -1); - return 0; -} - -template int -ACE_Asynch_Connector::connect (const ACE_INET_Addr & remote_sap, - const ACE_INET_Addr & local_sap, - int reuse_addr, - const void *act) -{ - // Initiate asynchronous connect - if (this->asynch_connect_.connect (ACE_INVALID_HANDLE, - remote_sap, - local_sap, - reuse_addr, - act) == -1) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_Asynch_Connect::connect")), - -1); - return 0; -} - -template void -ACE_Asynch_Connector::handle_connect (const ACE_Asynch_Connect::Result &result) -{ - // Variable for error tracking - int error = 0; - - // If the asynchronous connect fails. - if (!result.success () || - result.connect_handle () == ACE_INVALID_HANDLE) - { - error = 1; - } - - if (result.error () != 0) - { - error = 1; - } - - // set blocking mode - if (!error && - ACE::clr_flags - (result.connect_handle (), ACE_NONBLOCK) != 0) - { - error = 1; - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_Asynch_Connector::handle_connect : Set blocking mode"))); - } - - // Parse the addresses. - ACE_INET_Addr local_address; - ACE_INET_Addr remote_address; - if (!error && - (this->validate_new_connection_ || this->pass_addresses_)) - this->parse_address (result, - remote_address, - local_address); - - // Call validate_connection even if there was an error - it's the only - // way the application can learn the connect disposition. - if (this->validate_new_connection_ && - this->validate_connection (result, remote_address, local_address) == -1) - { - error = 1; - } - - HANDLER *new_handler = 0; - if (!error) - { - // The Template method - new_handler = this->make_handler (); - if (new_handler == 0) - { - error = 1; - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_Asynch_Connector::handle_connect : Making of new handler failed"))); - } - } - - // If no errors - if (!error) - { - // Update the Proactor. - new_handler->proactor (this->proactor ()); - - // Pass the addresses - if (this->pass_addresses_) - new_handler->addresses (remote_address, - local_address); - - // Pass the ACT - if (result.act () != 0) - new_handler->act (result.act ()); - - // Set up the handler's new handle value - new_handler->handle (result.connect_handle ()); - - ACE_Message_Block mb; - - // Initiate the handler with empty message block; - new_handler->open (result.connect_handle (), mb); - } - - // On failure, no choice but to close the socket - if (error && - result.connect_handle() != ACE_INVALID_HANDLE) - ACE_OS::closesocket (result.connect_handle ()); -} - -template int -ACE_Asynch_Connector::validate_connection - (const ACE_Asynch_Connect::Result &, - const ACE_INET_Addr & /* remote_address */, - const ACE_INET_Addr & /* local_address */) -{ - // Default implementation always validates the remote address. - return 0; -} - -template int -ACE_Asynch_Connector::cancel (void) -{ - return this->asynch_connect_.cancel (); -} - -template void -ACE_Asynch_Connector::parse_address (const ACE_Asynch_Connect::Result &result, - ACE_INET_Addr &remote_address, - ACE_INET_Addr &local_address) -{ -#if defined (ACE_HAS_IPV6) - // Getting the addresses. - sockaddr_in6 local_addr; - sockaddr_in6 remote_addr; -#else - // Getting the addresses. - sockaddr_in local_addr; - sockaddr_in remote_addr; -#endif /* ACE_HAS_IPV6 */ - - // Get the length. - int local_size = sizeof (local_addr); - int remote_size = sizeof (remote_addr); - - // Get the local address. - if (ACE_OS::getsockname (result.connect_handle (), - reinterpret_cast (&local_addr), - &local_size) < 0) - ACE_ERROR ((LM_ERROR, - ACE_TEXT("%p\n"), - ACE_TEXT("ACE_Asynch_Connector:: failed"))); - - // Get the remote address. - if (ACE_OS::getpeername (result.connect_handle (), - reinterpret_cast (&remote_addr), - &remote_size) < 0) - ACE_ERROR ((LM_ERROR, - ACE_TEXT("%p\n"), - ACE_TEXT("ACE_Asynch_Connector:: failed"))); - - // Set the addresses. - local_address.set (reinterpret_cast (&local_addr), - local_size); - remote_address.set (reinterpret_cast (&remote_addr), - remote_size); - -#if 0 - // @@ Just debugging. - char local_address_buf [BUFSIZ]; - char remote_address_buf [BUFSIZ]; - - if (local_address.addr_to_string (local_address_buf, - sizeof local_address_buf) == -1) - ACE_ERROR ((LM_ERROR, - "Error:%m:can't obtain local_address's address string")); - - ACE_DEBUG ((LM_DEBUG, - "ACE_Asynch_Connector::parse_address : " - "Local address %s\n", - local_address_buf)); - - if (remote_address.addr_to_string (remote_address_buf, - sizeof remote_address_buf) == -1) - ACE_ERROR ((LM_ERROR, - "Error:%m:can't obtain remote_address's address string")); - - ACE_DEBUG ((LM_DEBUG, - "ACE_Asynch_Connector::parse_address : " - "Remote address %s\n", - remote_address_buf)); -#endif /* 0 */ - - return; -} - - -template ACE_Asynch_Connect & -ACE_Asynch_Connector::asynch_connect (void) -{ - return this->asynch_connect_; -} - -template HANDLER * -ACE_Asynch_Connector::make_handler (void) -{ - // Default behavior - HANDLER *handler = 0; - ACE_NEW_RETURN (handler, HANDLER, 0); - return handler; -} - -template bool -ACE_Asynch_Connector::pass_addresses (void) const -{ - return this->pass_addresses_; -} - -template void -ACE_Asynch_Connector::pass_addresses (bool new_value) -{ - this->pass_addresses_ = new_value; -} - -template bool -ACE_Asynch_Connector::validate_new_connection (void) const -{ - return this->validate_new_connection_; -} - -template void -ACE_Asynch_Connector::validate_new_connection (bool new_value) -{ - this->validate_new_connection_ = new_value; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_WIN32 || ACE_HAS_AIO_CALLS */ -#endif /* ACE_ASYNCH_CONNECTOR_CPP */ diff --git a/externals/ace/Asynch_Connector.h b/externals/ace/Asynch_Connector.h deleted file mode 100644 index 7c7969cc20d..00000000000 --- a/externals/ace/Asynch_Connector.h +++ /dev/null @@ -1,171 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file Asynch_Connector.h - * - * $Id: Asynch_Connector.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Alexander Libman - */ -//============================================================================= - -#ifndef ACE_ASYNCH_CONNECTOR_H -#define ACE_ASYNCH_CONNECTOR_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if (defined (ACE_WIN32) || defined (ACE_HAS_AIO_CALLS)) && !defined(ACE_HAS_WINCE) -// This only works on platforms that support async i/o. - -#include "ace/Asynch_IO.h" -#include "ace/INET_Addr.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Forward declarations -class ACE_Message_Block; - -/** - * @class ACE_Asynch_Connector - * - * @brief This class is an example of the Connector pattern. This class - * will establish new connections and create new HANDLER objects to handle - * the new connections. - * - * Unlike the ACE_Connector, however, this class is designed to - * be used asynchronously with the ACE Proactor framework. - */ - -template -class ACE_Asynch_Connector : public ACE_Handler -{ -public: - /// A do nothing constructor. - ACE_Asynch_Connector (void); - - /// Virtual destruction - virtual ~ACE_Asynch_Connector (void); - - /** - * This opens asynch connector - */ - virtual int open (bool pass_addresses = false, - ACE_Proactor *proactor = 0, - bool validate_new_connection = true); - - /// This initiates a new asynchronous connect - virtual int connect (const ACE_INET_Addr &remote_sap, - const ACE_INET_Addr &local_sap = - (const ACE_INET_Addr &)ACE_Addr::sap_any, - int reuse_addr = 1, - const void *act = 0); - - /** - * This cancels all pending accepts operations that were issued by - * the calling thread. - * - * @note On Windows, this method does not cancel connect operations - * issued by other threads. - * - * @note On POSIX, delegates cancelation to ACE_POSIX_Asynch_Connect. - */ - virtual int cancel (void); - - - /** - * Template method to validate peer before service is opened. - * This method is called when the connection attempt completes, - * whether it succeeded or failed, if the @a validate_connection - * argument to @c open() was non-zero or the @c validate_new_connection() - * method is called to turn this feature on. The default implementation - * returns 0. Users can (and probably should) reimplement this method - * to learn about the success or failure of the connection attempt. - * If the connection completed successfully, this method can be used to - * perform validation of the peer using it's address, running an - * authentication procedure (such as SSL) or anything else necessary or - * desireable. The return value from this method determines whether or - * not ACE will continue opening the service or abort the connection. - * - * @param result Result of the connection acceptance. Use - * result.success() to determine success or failure of - * the connection attempt. - * @param remote Peer's address. If the connection failed, this object - * is undefined. - * @param local Local address connection was completed from. If the - * connection failed, this object is undefined. - * - * @retval -1 ACE_Asynch_Connector will close the connection, and - * the service will not be opened. - * @retval 0 Service opening will proceeed. - * @return Return value is ignored if the connection attempt failed. - */ - virtual int validate_connection (const ACE_Asynch_Connect::Result& result, - const ACE_INET_Addr &remote, - const ACE_INET_Addr& local); - - // - // These are low level tweaking methods - // - - /// Set and get flag that indicates if parsing and passing of - /// addresses to the service_handler is necessary. - virtual bool pass_addresses (void) const; - virtual void pass_addresses (bool new_value); - - /// Set and get flag that indicates if address validation is - /// required. - virtual bool validate_new_connection (void) const; - virtual void validate_new_connection (bool new_value); - -protected: - - /// This is called when an outstanding accept completes. - virtual void handle_connect (const ACE_Asynch_Connect::Result &result); - - - /// This parses the address from read buffer. - void parse_address (const ACE_Asynch_Connect::Result &result, - ACE_INET_Addr &remote_address, - ACE_INET_Addr &local_address); - - /// Return the asynch Connect object. - ACE_Asynch_Connect & asynch_connect (void); - - /** - * This is the template method used to create new handler. - * Subclasses must overwrite this method if a new handler creation - * strategy is required. - */ - virtual HANDLER *make_handler (void); - -private: - - /// Asynch_Connect used to make life easier :-) - ACE_Asynch_Connect asynch_connect_; - - /// Flag that indicates if parsing of addresses is necessary. - bool pass_addresses_; - - /// Flag that indicates if address validation is required. - bool validate_new_connection_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Asynch_Connector.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Asynch_Connector.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#endif /* ACE_WIN32 || ACE_HAS_AIO_CALLS */ -#include /**/ "ace/post.h" -#endif /* ACE_ASYNCH_CONNECTOR_H */ diff --git a/externals/ace/Asynch_IO.cpp b/externals/ace/Asynch_IO.cpp deleted file mode 100644 index 26bba31a3a9..00000000000 --- a/externals/ace/Asynch_IO.cpp +++ /dev/null @@ -1,1414 +0,0 @@ -// $Id: Asynch_IO.cpp 82559 2008-08-07 20:23:07Z parsons $ - -#include "ace/Asynch_IO.h" - -ACE_RCSID(ace, Asynch_IO, "$Id: Asynch_IO.cpp 82559 2008-08-07 20:23:07Z parsons $") - -#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) || defined (ACE_HAS_AIO_CALLS) -// This only works on platforms with Asynchronous IO - -#include "ace/Proactor.h" -#include "ace/Message_Block.h" -#include "ace/INET_Addr.h" -#include "ace/Asynch_IO_Impl.h" -#include "ace/os_include/os_errno.h" -#include "ace/Truncate.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -size_t -ACE_Asynch_Result::bytes_transferred (void) const -{ - return this->implementation ()->bytes_transferred (); -} - -const void * -ACE_Asynch_Result::act (void) const -{ - return this->implementation ()->act (); -} - -int -ACE_Asynch_Result::success (void) const -{ - return this->implementation ()->success (); -} - -const void * -ACE_Asynch_Result::completion_key (void) const -{ - return this->implementation ()->completion_key (); -} - -unsigned long -ACE_Asynch_Result::error (void) const -{ - return this->implementation ()->error (); -} - -ACE_HANDLE -ACE_Asynch_Result::event (void) const -{ - return this->implementation ()->event (); -} - -unsigned long -ACE_Asynch_Result::offset (void) const -{ - return this->implementation ()->offset (); -} - -unsigned long -ACE_Asynch_Result::offset_high (void) const -{ - return this->implementation ()->offset_high (); -} - -int -ACE_Asynch_Result::priority (void) const -{ - return this->implementation ()->priority (); -} - -int -ACE_Asynch_Result::signal_number (void) const -{ - return this->implementation ()->signal_number (); -} - -ACE_Asynch_Result::ACE_Asynch_Result (ACE_Asynch_Result_Impl *implementation) - : implementation_ (implementation) -{ -} - -ACE_Asynch_Result::~ACE_Asynch_Result (void) -{ - // Proactor deletes the implementation when the finishes. -} - -ACE_Asynch_Result_Impl * -ACE_Asynch_Result::implementation (void) const -{ - return this->implementation_; -} - -// ********************************************************************* - -int -ACE_Asynch_Operation::open (ACE_Handler &handler, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor) -{ - return this->implementation ()->open (handler.proxy (), - handle, - completion_key, - proactor); -} - -int -ACE_Asynch_Operation::cancel (void) -{ - if (0 == this->implementation ()) - { - errno = EFAULT; - return -1; - } - return this->implementation ()->cancel (); -} - -ACE_Proactor * -ACE_Asynch_Operation::proactor (void) const -{ - if (0 == this->implementation ()) - { - errno = EFAULT; - return 0; - } - return this->implementation ()->proactor (); -} - -ACE_Asynch_Operation::ACE_Asynch_Operation (void) -{ -} - -ACE_Asynch_Operation::~ACE_Asynch_Operation (void) -{ -} - -ACE_Proactor * -ACE_Asynch_Operation::get_proactor (ACE_Proactor *user_proactor, - ACE_Handler &handler) const -{ - if (user_proactor == 0) - { - // Grab the singleton proactor if proactor> is zero - user_proactor = handler.proactor (); - if (user_proactor == 0) - user_proactor = ACE_Proactor::instance (); - } - - return user_proactor; -} - -// ************************************************************ - -ACE_Asynch_Read_Stream::ACE_Asynch_Read_Stream (void) - : implementation_ (0) -{ -} - -ACE_Asynch_Read_Stream::~ACE_Asynch_Read_Stream (void) -{ - // Delete the implementation. - delete this->implementation_; - this->implementation_ = 0; -} - -int -ACE_Asynch_Read_Stream::open (ACE_Handler &handler, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor) -{ - // Get a proactor for/from the user. - proactor = this->get_proactor (proactor, handler); - - // Now let us get the implementation initialized. - if ((this->implementation_ = proactor->create_asynch_read_stream ()) == 0) - return -1; - - // Call the method of the base class. - return ACE_Asynch_Operation::open (handler, - handle, - completion_key, - proactor); -} - -int -ACE_Asynch_Read_Stream::read (ACE_Message_Block &message_block, - size_t bytes_to_read, - const void *act, - int priority, - int signal_number) -{ - if (0 == this->implementation_) - { - errno = EFAULT; - return -1; - } - return this->implementation_->read (message_block, - bytes_to_read, - act, - priority, - signal_number); -} - -#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) -int -ACE_Asynch_Read_Stream::readv (ACE_Message_Block &message_block, - size_t bytes_to_read, - const void *act, - int priority, - int signal_number) -{ - if (0 == this->implementation_) - { - errno = EFAULT; - return -1; - } - return this->implementation_->readv (message_block, - bytes_to_read, - act, - priority, - signal_number); -} -#endif /* ACE_HAS_WIN32_OVERLAPPED_IO */ - -ACE_Asynch_Operation_Impl * -ACE_Asynch_Read_Stream::implementation (void) const -{ - return this->implementation_; -} - -// ************************************************************ - -size_t -ACE_Asynch_Read_Stream::Result::bytes_to_read (void) const -{ - return this->implementation ()->bytes_to_read (); -} - -ACE_Message_Block & -ACE_Asynch_Read_Stream::Result::message_block (void) const -{ - return this->implementation ()->message_block (); -} - -ACE_HANDLE -ACE_Asynch_Read_Stream::Result::handle (void) const -{ - return this->implementation ()->handle (); -} - -ACE_Asynch_Read_Stream::Result::Result (ACE_Asynch_Read_Stream_Result_Impl *implementation) - : ACE_Asynch_Result (implementation), - implementation_ (implementation) -{ -} - -ACE_Asynch_Read_Stream::Result::~Result (void) -{ - // Proactor will delete the implementation after is - // finished. -} - -ACE_Asynch_Read_Stream_Result_Impl * -ACE_Asynch_Read_Stream::Result::implementation (void) const -{ - return this->implementation_; -} - -// *************************************************** - -ACE_Asynch_Write_Stream::ACE_Asynch_Write_Stream (void) - : implementation_ (0) -{ -} - -ACE_Asynch_Write_Stream::~ACE_Asynch_Write_Stream (void) -{ - // Delete the implementation. - delete this->implementation_; - this->implementation_ = 0; -} - -int -ACE_Asynch_Write_Stream::open (ACE_Handler &handler, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor) -{ - // Get a proactor for/from the user. - proactor = this->get_proactor (proactor, handler); - - // Now let us get the implementation initialized. - if ((this->implementation_ = proactor->create_asynch_write_stream ()) == 0) - return -1; - - // Call the method of the base class. - return ACE_Asynch_Operation::open (handler, - handle, - completion_key, - proactor); -} - -int -ACE_Asynch_Write_Stream::write (ACE_Message_Block &message_block, - size_t bytes_to_write, - const void *act, - int priority, - int signal_number) -{ - if (0 == this->implementation_) - { - errno = EFAULT; - return -1; - } - return this->implementation_->write (message_block, - bytes_to_write, - act, - priority, - signal_number); -} - -#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) -int -ACE_Asynch_Write_Stream::writev (ACE_Message_Block &message_block, - size_t bytes_to_write, - const void *act, - int priority, - int signal_number) -{ - if (0 == this->implementation_) - { - errno = EFAULT; - return -1; - } - return this->implementation_->writev (message_block, - bytes_to_write, - act, - priority, - signal_number); -} -#endif /* ACE_HAS_WIN32_OVERLAPPED_IO */ - -ACE_Asynch_Operation_Impl * -ACE_Asynch_Write_Stream::implementation (void) const -{ - return this->implementation_; -} - -// ************************************************************ - -size_t -ACE_Asynch_Write_Stream::Result::bytes_to_write (void) const -{ - return this->implementation ()->bytes_to_write (); -} - -ACE_Message_Block & -ACE_Asynch_Write_Stream::Result::message_block (void) const -{ - return this->implementation ()->message_block (); -} - -ACE_HANDLE -ACE_Asynch_Write_Stream::Result::handle (void) const -{ - return this->implementation ()->handle (); -} - -ACE_Asynch_Write_Stream::Result::Result (ACE_Asynch_Write_Stream_Result_Impl *implementation) - : ACE_Asynch_Result (implementation), - implementation_ (implementation) -{ -} - -ACE_Asynch_Write_Stream::Result::~Result (void) -{ - // Proactor will delte the implementation when the call - // finishes. -} - -ACE_Asynch_Write_Stream_Result_Impl * -ACE_Asynch_Write_Stream::Result::implementation (void) const -{ - return this->implementation_; -} - -// ************************************************************ - -ACE_Asynch_Read_File::ACE_Asynch_Read_File (void) - : implementation_ (0) -{ -} - -ACE_Asynch_Read_File::~ACE_Asynch_Read_File (void) -{ - // Delete the implementation. - delete this->implementation_; - this->implementation_ = 0; -} - -int -ACE_Asynch_Read_File::open (ACE_Handler &handler, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor) -{ - // Get a proactor for/from the user. - proactor = this->get_proactor (proactor, handler); - - // Now let us get the implementation initialized. - if ((this->implementation_ = proactor->create_asynch_read_file ()) == 0) - return -1; - - // Call the method of the base class. - return ACE_Asynch_Operation::open (handler, - handle, - completion_key, - proactor); -} - -int -ACE_Asynch_Read_File::read (ACE_Message_Block &message_block, - size_t bytes_to_read, - unsigned long offset, - unsigned long offset_high, - const void *act, - int priority, - int signal_number) -{ - if (0 == this->implementation_) - { - errno = EFAULT; - return -1; - } - return this->implementation_->read (message_block, - bytes_to_read, - offset, - offset_high, - act, - priority, - signal_number); -} - -#if (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) -int -ACE_Asynch_Read_File::readv (ACE_Message_Block &message_block, - size_t bytes_to_read, - unsigned long offset, - unsigned long offset_high, - const void *act, - int priority, - int signal_number) -{ - if (0 == this->implementation_) - { - errno = EFAULT; - return -1; - } - return this->implementation_->readv (message_block, - bytes_to_read, - offset, - offset_high, - act, - priority, - signal_number); -} -#endif /* (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) */ - -ACE_Asynch_Operation_Impl * -ACE_Asynch_Read_File::implementation (void) const -{ - return this->implementation_; -} - -// ************************************************************ - -ACE_Asynch_Read_File::Result::Result (ACE_Asynch_Read_File_Result_Impl *implementation) - : ACE_Asynch_Read_Stream::Result (implementation), - implementation_ (implementation) -{ -} - -ACE_Asynch_Read_File::Result::~Result (void) -{ - // Proactor will delete the implementation when call - // completes. -} - -ACE_Asynch_Read_File_Result_Impl * -ACE_Asynch_Read_File::Result::implementation (void) const -{ - return this->implementation_; -} - -// ************************************************************ - -ACE_Asynch_Write_File::ACE_Asynch_Write_File (void) - : implementation_ (0) -{ -} - -ACE_Asynch_Write_File::~ACE_Asynch_Write_File (void) -{ - // Delete the implementation. - delete this->implementation_; - this->implementation_ = 0; -} - -int -ACE_Asynch_Write_File::open (ACE_Handler &handler, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor) -{ - // Get a proactor for/from the user. - proactor = this->get_proactor (proactor, handler); - - // Now let us get the implementation initialized. - if ((this->implementation_ = proactor->create_asynch_write_file ()) == 0) - return -1; - - // Call the method of the base class. - return ACE_Asynch_Operation::open (handler, - handle, - completion_key, - proactor); -} - -int -ACE_Asynch_Write_File::write (ACE_Message_Block &message_block, - size_t bytes_to_write, - unsigned long offset, - unsigned long offset_high, - const void *act, - int priority, - int signal_number) -{ - if (0 == this->implementation_) - { - errno = EFAULT; - return -1; - } - return this->implementation_->write (message_block, - bytes_to_write, - offset, - offset_high, - act, - priority, - signal_number); -} - -#if (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) -int -ACE_Asynch_Write_File::writev (ACE_Message_Block &message_block, - size_t bytes_to_write, - unsigned long offset, - unsigned long offset_high, - const void *act, - int priority, - int signal_number) -{ - if (0 == this->implementation_) - { - errno = EFAULT; - return -1; - } - return this->implementation_->writev (message_block, - bytes_to_write, - offset, - offset_high, - act, - priority, - signal_number); -} -#endif /* (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) */ - -ACE_Asynch_Operation_Impl * -ACE_Asynch_Write_File::implementation (void) const -{ - return this->implementation_; -} - -// ************************************************************ - -ACE_Asynch_Write_File::Result::Result (ACE_Asynch_Write_File_Result_Impl *implementation) - : ACE_Asynch_Write_Stream::Result (implementation), - implementation_ (implementation) -{ -} - -ACE_Asynch_Write_File::Result::~Result (void) -{ - // Proactor will delete the implementation when the call - // completes. -} - -ACE_Asynch_Write_File_Result_Impl * -ACE_Asynch_Write_File::Result::implementation (void) const -{ - return this->implementation_; -} - -// ********************************************************************* - -ACE_Asynch_Accept::ACE_Asynch_Accept (void) - : implementation_ (0) -{ -} - -ACE_Asynch_Accept::~ACE_Asynch_Accept (void) -{ - // Delete the implementation. - delete this->implementation_; - this->implementation_ = 0; -} - -int -ACE_Asynch_Accept::open (ACE_Handler &handler, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor) -{ - // Get a proactor for/from the user. - proactor = this->get_proactor (proactor, handler); - - // Now let us get the implementation initialized. - if ((this->implementation_ = proactor->create_asynch_accept ()) == 0) - return -1; - - // Call the method of the base class. - return ACE_Asynch_Operation::open (handler, - handle, - completion_key, - proactor); -} - -int -ACE_Asynch_Accept::accept (ACE_Message_Block &message_block, - size_t bytes_to_read, - ACE_HANDLE accept_handle, - const void *act, - int priority, - int signal_number, - int addr_family) -{ - if (0 == this->implementation_) - { - errno = EFAULT; - return -1; - } - return this->implementation_->accept (message_block, - bytes_to_read, - accept_handle, - act, - priority, - signal_number, - addr_family); -} - -ACE_Asynch_Operation_Impl * -ACE_Asynch_Accept::implementation (void) const -{ - return this->implementation_; -} - -// ************************************************************ - -size_t -ACE_Asynch_Accept::Result::bytes_to_read (void) const -{ - return this->implementation ()->bytes_to_read (); -} - -ACE_Message_Block & -ACE_Asynch_Accept::Result::message_block (void) const -{ - return this->implementation ()->message_block (); -} - -ACE_HANDLE -ACE_Asynch_Accept::Result::listen_handle (void) const -{ - return this->implementation ()->listen_handle (); -} - -ACE_HANDLE -ACE_Asynch_Accept::Result::accept_handle (void) const -{ - return this->implementation ()->accept_handle (); -} - -ACE_Asynch_Accept::Result::Result (ACE_Asynch_Accept_Result_Impl *implementation) - : ACE_Asynch_Result (implementation), - implementation_ (implementation) -{ -} - -ACE_Asynch_Accept::Result::~Result (void) -{ - // Proactor will delete the implementation when the call - // completes. -} - -ACE_Asynch_Accept_Result_Impl * -ACE_Asynch_Accept::Result::implementation (void) const -{ - return this->implementation_; -} - - - -// ********************************************************************* - -ACE_Asynch_Connect::ACE_Asynch_Connect (void) - : implementation_ (0) -{ -} - -ACE_Asynch_Connect::~ACE_Asynch_Connect (void) -{ - // Delete the implementation. - delete this->implementation_; - this->implementation_ = 0; -} - -int -ACE_Asynch_Connect::open (ACE_Handler &handler, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor) -{ - // Get a proactor for/from the user. - proactor = this->get_proactor (proactor, handler); - - // Now let us get the implementation initialized. - if ((this->implementation_ = proactor->create_asynch_connect ()) == 0) - return -1; - - // Call the method of the base class. - return ACE_Asynch_Operation::open (handler, - handle, - completion_key, - proactor); -} - -int -ACE_Asynch_Connect::connect (ACE_HANDLE connect_handle, - const ACE_Addr & remote_sap, - const ACE_Addr & local_sap, - int reuse_addr, - const void *act, - int priority, - int signal_number) -{ - if (0 == this->implementation_) - { - errno = EFAULT; - return -1; - } - return this->implementation_->connect (connect_handle, - remote_sap, - local_sap, - reuse_addr, - act, - priority, - signal_number); -} - -ACE_Asynch_Operation_Impl * -ACE_Asynch_Connect::implementation (void) const -{ - return this->implementation_; -} - -// ************************************************************ - -ACE_Asynch_Connect::Result::Result (ACE_Asynch_Connect_Result_Impl *implementation) - : ACE_Asynch_Result (implementation), - implementation_ (implementation) -{ -} - -ACE_Asynch_Connect::Result::~Result (void) -{ - // Proactor will delete the implementation when the call - // completes. -} - -ACE_HANDLE -ACE_Asynch_Connect::Result::connect_handle (void) const -{ - return this->implementation ()->connect_handle (); -} - - -ACE_Asynch_Connect_Result_Impl * -ACE_Asynch_Connect::Result::implementation (void) const -{ - return this->implementation_; -} - -// ************************************************************ - -ACE_Asynch_Transmit_File::ACE_Asynch_Transmit_File (void) - : implementation_ (0) -{ -} - -ACE_Asynch_Transmit_File::~ACE_Asynch_Transmit_File (void) -{ - // Delete the implementation. - delete this->implementation_; - this->implementation_ = 0; -} - -int -ACE_Asynch_Transmit_File::open (ACE_Handler &handler, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor) -{ - // Get a proactor for/from the user. - proactor = this->get_proactor (proactor, handler); - - // Now let us get the implementation initialized. - if ((this->implementation_ = proactor->create_asynch_transmit_file ()) == 0) - return -1; - - // Call the method of the base class. - return ACE_Asynch_Operation::open (handler, - handle, - completion_key, - proactor); -} - -int -ACE_Asynch_Transmit_File::transmit_file (ACE_HANDLE file, - Header_And_Trailer *header_and_trailer, - size_t bytes_to_write, - unsigned long offset, - unsigned long offset_high, - size_t bytes_per_send, - unsigned long flags, - const void *act, - int priority, - int signal_number) -{ - if (0 == this->implementation_) - { - errno = EFAULT; - return -1; - } - return this->implementation_->transmit_file (file, - header_and_trailer, - bytes_to_write, - offset, - offset_high, - bytes_per_send, - flags, - act, - priority, - signal_number); -} - -ACE_Asynch_Operation_Impl * -ACE_Asynch_Transmit_File::implementation (void) const -{ - return this->implementation_; -} - -// **************************************************************************** - -ACE_HANDLE -ACE_Asynch_Transmit_File::Result::socket (void) const -{ - return this->implementation ()->socket (); -} - -ACE_HANDLE -ACE_Asynch_Transmit_File::Result::file (void) const -{ - return this->implementation ()->file (); -} - -ACE_Asynch_Transmit_File::Header_And_Trailer * -ACE_Asynch_Transmit_File::Result::header_and_trailer (void) const -{ - return this->implementation ()->header_and_trailer (); -} - -size_t -ACE_Asynch_Transmit_File::Result::bytes_to_write (void) const -{ - return this->implementation ()->bytes_to_write (); -} - -size_t -ACE_Asynch_Transmit_File::Result::bytes_per_send (void) const -{ - return this->implementation ()->bytes_per_send (); -} - -unsigned long -ACE_Asynch_Transmit_File::Result::flags (void) const -{ - return this->implementation ()->flags (); -} - -ACE_Asynch_Transmit_File::Result::Result (ACE_Asynch_Transmit_File_Result_Impl *implementation) - : ACE_Asynch_Result (implementation), - implementation_ (implementation) -{ -} - -ACE_Asynch_Transmit_File::Result::~Result (void) -{ -} - -ACE_Asynch_Transmit_File_Result_Impl * -ACE_Asynch_Transmit_File::Result::implementation (void) const -{ - return this->implementation_; -} - -// ************************************************************ - -ACE_Asynch_Transmit_File::Header_And_Trailer::Header_And_Trailer (ACE_Message_Block *header, - size_t header_bytes, - ACE_Message_Block *trailer, - size_t trailer_bytes) - : header_ (header), - header_bytes_ (header_bytes), - trailer_ (trailer), - trailer_bytes_ (trailer_bytes) -{ -} - -ACE_Asynch_Transmit_File::Header_And_Trailer::~Header_And_Trailer (void) -{ -} - -void -ACE_Asynch_Transmit_File::Header_And_Trailer::header_and_trailer (ACE_Message_Block *header, - size_t header_bytes, - ACE_Message_Block *trailer, - size_t trailer_bytes) -{ - this->header (header); - this->header_bytes (header_bytes); - this->trailer (trailer); - this->trailer_bytes (trailer_bytes); -} - -ACE_Message_Block * -ACE_Asynch_Transmit_File::Header_And_Trailer::header (void) const -{ - return this->header_; -} - -void -ACE_Asynch_Transmit_File::Header_And_Trailer::header (ACE_Message_Block *message_block) -{ - this->header_ = message_block; -} - -size_t -ACE_Asynch_Transmit_File::Header_And_Trailer::header_bytes (void) const -{ - return this->header_bytes_; -} - -void -ACE_Asynch_Transmit_File::Header_And_Trailer::header_bytes (size_t bytes) -{ - this->header_bytes_ = bytes; -} - -ACE_Message_Block * -ACE_Asynch_Transmit_File::Header_And_Trailer::trailer (void) const -{ - return this->trailer_; -} - -void -ACE_Asynch_Transmit_File::Header_And_Trailer::trailer (ACE_Message_Block *message_block) -{ - this->trailer_ = message_block; -} - -size_t -ACE_Asynch_Transmit_File::Header_And_Trailer::trailer_bytes (void) const -{ - return this->trailer_bytes_; -} - -void -ACE_Asynch_Transmit_File::Header_And_Trailer::trailer_bytes (size_t bytes) -{ - this->trailer_bytes_ = bytes; -} - -ACE_LPTRANSMIT_FILE_BUFFERS -ACE_Asynch_Transmit_File::Header_And_Trailer::transmit_buffers (void) -{ - // If both are zero, return zero - if (this->header_ == 0 && this->trailer_ == 0) - { - return 0; - } - else - { - // Something is valid - - // If header is valid, set the fields - if (this->header_ != 0) - { - this->transmit_buffers_.Head = this->header_->rd_ptr (); -#if defined (ACE_WIN64) || defined (ACE_WIN32) - this->transmit_buffers_.HeadLength = - ACE_Utils::truncate_cast (this->header_bytes_); -#else - this->transmit_buffers_.HeadLength = this->header_bytes_; -#endif /* ACE_WIN64 || ACE_WIN32 */ - } - else - { - this->transmit_buffers_.Head = 0; - this->transmit_buffers_.HeadLength = 0; - } - - // If trailer is valid, set the fields - if (this->trailer_ != 0) - { - this->transmit_buffers_.Tail = this->trailer_->rd_ptr (); -#if defined(ACE_WIN64) || defined (ACE_WIN32) - this->transmit_buffers_.TailLength = - ACE_Utils::truncate_cast (this->trailer_bytes_); -#else - this->transmit_buffers_.TailLength = this->trailer_bytes_; -#endif /* ACE_WIN64 || ACE_WIN32 */ - } - else - { - this->transmit_buffers_.Tail = 0; - this->transmit_buffers_.TailLength = 0; - } - - // Return the transmit buffers - return &this->transmit_buffers_; - } -} - -// ********************************************************************* - -ACE_Handler::ACE_Handler (void) - : proactor_ (0), handle_ (ACE_INVALID_HANDLE) -{ - ACE_Handler::Proxy *p; - ACE_NEW (p, ACE_Handler::Proxy (this)); - this->proxy_.reset (p); -} - -ACE_Handler::ACE_Handler (ACE_Proactor *d) - : proactor_ (d), handle_ (ACE_INVALID_HANDLE) -{ - ACE_Handler::Proxy *p; - ACE_NEW (p, ACE_Handler::Proxy (this)); - this->proxy_.reset (p); -} - -ACE_Handler::~ACE_Handler (void) -{ - ACE_Handler::Proxy *p = this->proxy_.get (); - if (p) - p->reset (); -} - -void -ACE_Handler::handle_read_stream (const ACE_Asynch_Read_Stream::Result & /* result */) -{ -} - -void -ACE_Handler::handle_write_stream (const ACE_Asynch_Write_Stream::Result & /* result */) -{ -} - -void -ACE_Handler::handle_write_dgram (const ACE_Asynch_Write_Dgram::Result & /* result */) -{ -} - -void -ACE_Handler::handle_read_dgram (const ACE_Asynch_Read_Dgram::Result & /* result */) -{ -} - -void -ACE_Handler::handle_accept (const ACE_Asynch_Accept::Result & /* result */) -{ -} - -void -ACE_Handler::handle_connect (const ACE_Asynch_Connect::Result & /* result */) -{ -} - -void -ACE_Handler::handle_transmit_file (const ACE_Asynch_Transmit_File::Result & /* result */) -{ -} - -void -ACE_Handler::handle_read_file (const ACE_Asynch_Read_File::Result & /* result */) -{ -} - -void -ACE_Handler::handle_write_file (const ACE_Asynch_Write_File::Result & /* result */) -{ -} - -void -ACE_Handler::handle_time_out (const ACE_Time_Value & /* tv */, - const void * /* act */) -{ -} - -void -ACE_Handler::handle_wakeup (void) -{ -} - -ACE_Proactor * -ACE_Handler::proactor (void) -{ - return this->proactor_; -} - -void -ACE_Handler::proactor (ACE_Proactor *p) -{ - this->proactor_ = p; -} - -ACE_HANDLE -ACE_Handler::handle (void) const -{ - return this->handle_; -} - -void -ACE_Handler::handle (ACE_HANDLE h) -{ - this->handle_ = h; -} - -ACE_Refcounted_Auto_Ptr & -ACE_Handler::proxy (void) -{ - return this->proxy_; -} - -// ************************************************************ - -ACE_Service_Handler::ACE_Service_Handler (void) -{ -} - -ACE_Service_Handler::~ACE_Service_Handler (void) -{ -} - -void -ACE_Service_Handler::addresses (const ACE_INET_Addr & /* remote_address */, - const ACE_INET_Addr & /* local_address */ ) -{ -} - -void -ACE_Service_Handler::act (const void *) -{ -} - -void -ACE_Service_Handler::open (ACE_HANDLE, - ACE_Message_Block &) -{ -} - - -// ************************************************************ - -ACE_Asynch_Read_Dgram::ACE_Asynch_Read_Dgram (void) - : implementation_ (0) -{ -} - -ACE_Asynch_Read_Dgram::~ACE_Asynch_Read_Dgram (void) -{ - // Delete the implementation. - delete this->implementation_; - this->implementation_ = 0; -} - -int -ACE_Asynch_Read_Dgram::open (ACE_Handler &handler, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor) -{ - // Get a proactor for/from the user. - proactor = this->get_proactor (proactor, handler); - - // Now let us get the implementation initialized. - if ((this->implementation_ = proactor->create_asynch_read_dgram ()) == 0) - return -1; - - // Call the method of the base class. - return ACE_Asynch_Operation::open (handler, - handle, - completion_key, - proactor); -} - -ssize_t -ACE_Asynch_Read_Dgram::recv (ACE_Message_Block *message_block, - size_t &number_of_bytes_recvd, - int flags, - int protocol_family, - const void *act, - int priority, - int signal_number) -{ - if (0 == this->implementation_) - { - errno = EFAULT; - return -1; - } - return this->implementation_->recv (message_block, - number_of_bytes_recvd, - flags, - protocol_family, - act, - priority, - signal_number); -} - -ACE_Asynch_Operation_Impl * -ACE_Asynch_Read_Dgram::implementation (void) const -{ - return this->implementation_; -} - -// ************************************************************ - -int -ACE_Asynch_Read_Dgram::Result::remote_address (ACE_Addr& addr) const -{ - return this->implementation ()->remote_address (addr); -} - -ACE_Message_Block* -ACE_Asynch_Read_Dgram::Result::message_block (void) const -{ - return this->implementation ()->message_block (); -} - -int -ACE_Asynch_Read_Dgram::Result::flags (void) const -{ - return this->implementation ()->flags (); -} - -size_t -ACE_Asynch_Read_Dgram::Result::bytes_to_read (void) const -{ - return this->implementation ()->bytes_to_read (); -} - -ACE_HANDLE -ACE_Asynch_Read_Dgram::Result::handle (void) const -{ - return this->implementation ()->handle(); -} - -ACE_Asynch_Read_Dgram::Result::Result (ACE_Asynch_Read_Dgram_Result_Impl *implementation) -: ACE_Asynch_Result (implementation), - implementation_ (implementation) -{ -} - -ACE_Asynch_Read_Dgram::Result::~Result (void) -{ -} - -ACE_Asynch_Read_Dgram_Result_Impl * -ACE_Asynch_Read_Dgram::Result::implementation (void) const -{ - return this->implementation_; -} - -// ************************************************************ - - -ACE_Asynch_Write_Dgram::ACE_Asynch_Write_Dgram (void) - : implementation_ (0) -{ -} - -ACE_Asynch_Write_Dgram::~ACE_Asynch_Write_Dgram (void) -{ - // Delete the implementation. - delete this->implementation_; - this->implementation_ = 0; -} - -int -ACE_Asynch_Write_Dgram::open (ACE_Handler &handler, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor) -{ - // Get a proactor for/from the user. - proactor = this->get_proactor (proactor, handler); - - // Now let us get the implementation initialized. - if ((this->implementation_ = proactor->create_asynch_write_dgram ()) == 0) - return -1; - - // Call the method of the base class. - return ACE_Asynch_Operation::open (handler, - handle, - completion_key, - proactor); -} - -ssize_t -ACE_Asynch_Write_Dgram::send (ACE_Message_Block *message_block, - size_t &number_of_bytes_sent, - int flags, - const ACE_Addr& remote_addr, - const void *act, - int priority, - int signal_number) -{ - if (0 == this->implementation_) - { - errno = EFAULT; - return -1; - } - return this->implementation_->send (message_block, - number_of_bytes_sent, - flags, - remote_addr, - act, - priority, - signal_number); -} - -ACE_Asynch_Operation_Impl * -ACE_Asynch_Write_Dgram::implementation (void) const -{ - return this->implementation_; -} - -// ************************************************************ - -size_t -ACE_Asynch_Write_Dgram::Result::bytes_to_write (void) const -{ - return this->implementation ()->bytes_to_write (); -} - -ACE_Message_Block* -ACE_Asynch_Write_Dgram::Result::message_block () const -{ - return this->implementation ()->message_block (); -} - -int -ACE_Asynch_Write_Dgram::Result::flags (void) const -{ - return this->implementation ()->flags (); -} - -ACE_HANDLE -ACE_Asynch_Write_Dgram::Result::handle (void) const -{ - return this->implementation ()->handle (); -} - -ACE_Asynch_Write_Dgram_Result_Impl * -ACE_Asynch_Write_Dgram::Result::implementation (void) const -{ - return this->implementation_; -} - -ACE_Asynch_Write_Dgram::Result::Result (ACE_Asynch_Write_Dgram_Result_Impl *implementation) -: ACE_Asynch_Result (implementation), - implementation_ (implementation) -{ -} - -ACE_Asynch_Write_Dgram::Result::~Result (void) -{ -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_WIN32_OVERLAPPED_IO || ACE_HAS_AIO_CALLS */ diff --git a/externals/ace/Asynch_IO.h b/externals/ace/Asynch_IO.h deleted file mode 100644 index 641e22a8de4..00000000000 --- a/externals/ace/Asynch_IO.h +++ /dev/null @@ -1,1761 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file Asynch_IO.h - * - * $Id: Asynch_IO.h 84837 2009-03-16 13:01:15Z johnnyw $ - * - * This works on Win32 (defined (ACE_WIN32) && !defined - * (ACE_HAS_WINCE)) platforms and on POSIX4 platforms with {aio_*} - * routines (defined (ACE_HAS_AIO_CALLS)) - * - * On Win32 platforms, the implementation of - * {ACE_Asynch_Transmit_File} and {ACE_Asynch_Accept} are only - * supported if ACE_HAS_WINSOCK2 is defined or you are on WinNT 4.0 - * or higher. - * - * @author Irfan Pyarali - * @author Tim Harrison - * @author Alexander Babu Arulanthu - * @author Roger Tragin - * @author Alexander Libman - */ -//============================================================================= - -#ifndef ACE_ASYNCH_IO_H -#define ACE_ASYNCH_IO_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -#pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) || defined (ACE_HAS_AIO_CALLS) - -#include "ace/Synch_Traits.h" -#if defined (ACE_HAS_THREADS) -# include "ace/Thread_Mutex.h" -#else -# include "ace/Null_Mutex.h" -#endif /* ACE_HAS_THREADS */ -#include "ace/Refcounted_Auto_Ptr.h" - -#include "ace/os_include/os_signal.h" -#include "ace/os_include/sys/os_socket.h" -#include "ace/os_include/sys/os_types.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -# if defined (ACE_HAS_WIN32_OVERLAPPED_IO) -typedef TRANSMIT_FILE_BUFFERS ACE_TRANSMIT_FILE_BUFFERS; -typedef LPTRANSMIT_FILE_BUFFERS ACE_LPTRANSMIT_FILE_BUFFERS; -typedef PTRANSMIT_FILE_BUFFERS ACE_PTRANSMIT_FILE_BUFFERS; - -# define ACE_INFINITE INFINITE -# define ACE_STATUS_TIMEOUT STATUS_TIMEOUT -# define ACE_WAIT_FAILED WAIT_FAILED -# define ACE_WAIT_TIMEOUT WAIT_TIMEOUT -# else /* ACE_HAS_WIN32_OVERLAPPED_IO */ -struct ACE_TRANSMIT_FILE_BUFFERS -{ - void *Head; - size_t HeadLength; - void *Tail; - size_t TailLength; -}; -typedef ACE_TRANSMIT_FILE_BUFFERS* ACE_PTRANSMIT_FILE_BUFFERS; -typedef ACE_TRANSMIT_FILE_BUFFERS* ACE_LPTRANSMIT_FILE_BUFFERS; - -# if !defined (ACE_INFINITE) -# define ACE_INFINITE LONG_MAX -# endif /* ACE_INFINITE */ -# define ACE_STATUS_TIMEOUT LONG_MAX -# define ACE_WAIT_FAILED LONG_MAX -# define ACE_WAIT_TIMEOUT LONG_MAX -# endif /* ACE_HAS_WIN32_OVERLAPPED_IO */ - -// Forward declarations -class ACE_Proactor; -class ACE_Handler; -class ACE_Message_Block; -class ACE_INET_Addr; -class ACE_Addr; - -// Forward declarations -class ACE_Asynch_Result_Impl; -class ACE_Time_Value; - -/** - * @class ACE_Asynch_Result - * - * @brief An interface base class which allows users access to common - * information related to an asynchronous operation. - * - * An interface base class from which you can obtain some basic - * information like the number of bytes transferred, the ACT - * associated with the asynchronous operation, indication of - * success or failure, etc. Subclasses may want to store more - * information that is particular to the asynchronous operation - * it represents. - */ -class ACE_Export ACE_Asynch_Result -{ - -public: - /// Number of bytes transferred by the operation. - size_t bytes_transferred (void) const; - - /// ACT associated with the operation. - const void *act (void) const; - - /// Did the operation succeed? - int success (void) const; - - /** - * This is the ACT associated with the handle on which the - * Asynch_Operation takes place. - * - * On WIN32, this returns the ACT associated with the handle when it - * was registered with the I/O completion port. - * - * @@ This is not implemented for POSIX4 platforms. Returns 0. - */ - const void *completion_key (void) const; - - /// Error value if the operation fails. - unsigned long error (void) const; - - /** - * On WIN32, this returns the event associated with the OVERLAPPED - * structure. - * - * This returns ACE_INVALID_HANDLE on POSIX4-Unix platforms. - */ - ACE_HANDLE event (void) const; - - /** - * This really makes sense only when doing file I/O. - * - * On WIN32, these are represented in the OVERLAPPED datastructure. - * - * @@ On POSIX4-Unix, offset_high should be supported using - * aiocb64. - */ - unsigned long offset (void) const; - unsigned long offset_high (void) const; - - /** - * Priority of the operation. - * - * On POSIX4-Unix, this is supported. Priority works like {nice} in - * Unix. Negative values are not allowed. 0 means priority of the - * operation same as the process priority. 1 means priority of the - * operation is one less than process. And so forth. - * - * On Win32, this is a no-op. - */ - int priority (void) const; - - /** - * POSIX4 real-time signal number to be used for the - * operation. {signal_number} ranges from ACE_SIGRTMIN to ACE_SIGRTMAX. By - * default, ACE_SIGRTMIN is used to issue {aio_} calls. This is a no-op - * on non-POSIX4 systems and returns 0. - */ - int signal_number (void) const; - - - /// Destructor. - virtual ~ACE_Asynch_Result (void); - -protected: - /// Constructor. This implementation will not be deleted. The - /// implementation will be deleted by the Proactor. - ACE_Asynch_Result (ACE_Asynch_Result_Impl *implementation); - - /// Get the implementation class. - ACE_Asynch_Result_Impl *implementation (void) const; - - /// Implementation class. - ACE_Asynch_Result_Impl *implementation_; -}; - -// Forward declarations -class ACE_Asynch_Operation_Impl; - -/** - * @class ACE_Asynch_Operation - * - * @brief This is an interface base class for all asynch - * operations. The resposiblility of this class is to forward - * all methods to its delegation/implementation class, e.g., - * ACE_WIN32_Asynch_Operation or ACE_POSIX_Asynch_Operation. - * - * There are some attributes and functionality which is common - * to all asychronous operations. The delegation classes of this - * class will factor out this code. - */ -class ACE_Export ACE_Asynch_Operation -{ - -public: - /** - * Initializes the factory with information which will be used with - * each asynchronous call. If ({handle} == ACE_INVALID_HANDLE), - * {ACE_Handler::handle} will be called on the {handler} to get the - * correct handle. - */ - int open (ACE_Handler &handler, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor); - - /** - * (Attempts to) cancel the asynchronous operation pending against - * the {handle} registered with this Operation. - * - * All completion notifications for the I/O operations will occur - * normally. - * - * = Return Values: - * - * -1 : Operation failed. (can get only in POSIX). - * 0 : All the operations were cancelled. - * 1 : All the operations were already finished in this - * handle. Unable to cancel them. - * 2 : Atleast one of the requested operations cannot be - * cancelled. - * - * There is slight difference in the semantics between NT and POSIX - * platforms which is given below. - * - * = Win32 : - * - * cancels all pending accepts operations that were issued by the - * calling thread. The function does not cancel asynchronous - * operations issued by other threads. - * All I/O operations that are canceled will complete with the - * error ERROR_OPERATION_ABORTED. - * - * = POSIX: - * - * Attempts to cancel one or more asynchronous I/O requests - * currently outstanding against the {handle} registered in this - * operation. - * For requested operations that are successfully canceled, the - * associated error status is set to ECANCELED. - */ - int cancel (void); - - - // = Access methods. - - /// Return the underlying proactor. - ACE_Proactor* proactor (void) const; - - /// Destructor. - virtual ~ACE_Asynch_Operation (void); - -protected: - /// Constructor. - ACE_Asynch_Operation (void); - - /// Return the underlying implementation class. - virtual ACE_Asynch_Operation_Impl *implementation (void) const = 0; - - /// Get a proactor for/from the user - ACE_Proactor *get_proactor (ACE_Proactor *user_proactor, - ACE_Handler &handler) const; -}; - -// Forward declarations -class ACE_Asynch_Read_Stream_Result_Impl; -class ACE_Asynch_Read_Stream_Impl; - -/** - * @class ACE_Asynch_Read_Stream - * - * @brief This class is a factory for starting off asynchronous reads - * on a stream. This class forwards all methods to its - * implementation class. - * - * Once {open} is called, multiple asynchronous {read}s can - * started using this class. An ACE_Asynch_Read_Stream::Result - * will be passed back to the {handler} when the asynchronous - * reads completes through the {ACE_Handler::handle_read_stream} - * callback. - */ -class ACE_Export ACE_Asynch_Read_Stream : public ACE_Asynch_Operation -{ - -public: - /// A do nothing constructor. - ACE_Asynch_Read_Stream (void); - - /// Destructor - virtual ~ACE_Asynch_Read_Stream (void); - - /** - * Initializes the factory with information which will be used with - * each asynchronous call. - * - * @param handler The ACE_Handler that will be called to handle completions - * for operations initiated using this factory. - * @param handle The handle that future read operations will use. - * If handle == @c ACE_INVALID_HANDLE, - * ACE_Handler::handle() will be called on @ handler - * to get the correct handle. - * - * @retval 0 for success. - * @retval -1 for failure; consult @c errno for further information. - */ - int open (ACE_Handler &handler, - ACE_HANDLE handle = ACE_INVALID_HANDLE, - const void *completion_key = 0, - ACE_Proactor *proactor = 0); - - /** - * Initiate an asynchronous read operation. - * - * @param message_block The ACE_Message_Block to receive the data. - * Received bytes will be placed in the block - * beginning at its current write pointer. - * If data is read, the message block's write - * pointer will be advanced by the number of - * bytes read. - * @param num_bytes_to_read The maximum number of bytes to read. - * @param act Asynchronous Completion Token; passed through to - * the completion handler in the Result object. - * @param priority Priority of the operation. On POSIX4-Unix, - * this is supported. Works like @c nice in Unix. - * Negative values are not allowed. 0 means - * priority of the operation same as the process - * priority. 1 means priority of the operation is - * one less than process priority, etc. - * Ignored on Windows. - * @param signal_number The POSIX4 real-time signal number to be used - * to signal completion of the operation. Values - * range from ACE_SIGRTMIN to ACE_SIGRTMAX. - * This argument is ignored on non-POSIX4 systems. - */ - int read (ACE_Message_Block &message_block, - size_t num_bytes_to_read, - const void *act = 0, - int priority = 0, - int signal_number = ACE_SIGRTMIN); - -#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) - /** - * Same as above but with scatter support, through chaining of composite - * message blocks using the continuation field. - */ - int readv (ACE_Message_Block &message_block, - size_t num_bytes_to_read, - const void *act = 0, - int priority = 0, - int signal_number = ACE_SIGRTMIN); -#endif /* defined (ACE_HAS_WIN32_OVERLAPPED_IO) */ - - /// Return the underlying implementation class. - // (this should be protected...) - virtual ACE_Asynch_Operation_Impl *implementation (void) const; - -protected: - /// Implementation class that all methods will be forwarded to. - ACE_Asynch_Read_Stream_Impl *implementation_; - -public: -/** - * @class Result - * - * @brief This is the class which will be passed back to the - * ACE_Handler::handle_read_stream when the asynchronous read completes. - * This class forwards all the methods to the implementation classes. - * - * This class has all the information necessary for the - * handler to uniquiely identify the completion of the - * asynchronous read. - */ - class ACE_Export Result : public ACE_Asynch_Result - { - - /// The concrete implementation result classes only construct this - /// class. - friend class ACE_POSIX_Asynch_Read_Stream_Result; - friend class ACE_WIN32_Asynch_Read_Stream_Result; - - public: - /// The number of bytes which were requested at the start of the - /// asynchronous read. - size_t bytes_to_read (void) const; - - /// Message block which contains the read data. - ACE_Message_Block &message_block (void) const; - - /// I/O handle used for reading. - ACE_HANDLE handle (void) const; - - /// Get the implementation class. - ACE_Asynch_Read_Stream_Result_Impl *implementation (void) const; - - protected: - /// Constructor. - Result (ACE_Asynch_Read_Stream_Result_Impl *implementation); - - /// Destructor. - virtual ~Result (void); - - /// The implementation class. - ACE_Asynch_Read_Stream_Result_Impl *implementation_; - }; -private: - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Asynch_Read_Stream &)) - ACE_UNIMPLEMENTED_FUNC (ACE_Asynch_Read_Stream (const ACE_Asynch_Read_Stream &)) -}; - -// Forward declarations -class ACE_Asynch_Write_Stream_Impl; -class ACE_Asynch_Write_Stream_Result_Impl; - -/** - * @class ACE_Asynch_Write_Stream - * - * @brief This class is a factory for initiating asynchronous writes - * on a connected TCP/IP stream. This class forwards all methods to its - * implementation class. - * - * Once open() is called, multiple asynchronous writes can be - * started using this class. An ACE_Asynch_Write_Stream::Result - * will be passed to the ACE_Handler::handle_write_stream() method on the - * opened ACE_Handler object when the asynchronous write completes. - */ -class ACE_Export ACE_Asynch_Write_Stream : public ACE_Asynch_Operation -{ - -public: - /// A do nothing constructor. - ACE_Asynch_Write_Stream (void); - - /// Destructor. - virtual ~ACE_Asynch_Write_Stream (void); - - /** - * Initializes the factory with information which will be used with - * each asynchronous operation. - * - * @param handler ACE_Handler to be notified when operations initiated - * via this factory complete. The handle_write_stream() - * method will be called on this object. - * @param handle The socket handle to initiate write operations on. - * If handle is @c ACE_INVALID_HANDLE, - * ACE_Handler::handle() will be called on handler to - * get the handle value. - * @param completion_key A token that is passed to the completion handler. - * @param proactor The ACE_Proactor object which will control operation - * completion and dispatching the results to handler. - * If this is 0, the process's singleton ACE_Proactor - * will be used. - * - * @retval 0 for success. - * @retval -1 for failure; consult @c errno for further information. - */ - int open (ACE_Handler &handler, - ACE_HANDLE handle = ACE_INVALID_HANDLE, - const void *completion_key = 0, - ACE_Proactor *proactor = 0); - - /** - * Initiates an asynchronous write on a socket. If the operation completes - * the ACE_Handler object registered in open() will receive a completion - * callback via its handle_write_stream() method. - * - * @param bytes_to_write The number of bytes to write. - * @param message_block The ACE_Message_Block containing data to write. - * Data is written to the socket beginning at the - * block's rd_ptr. Upon successful completion - * of the write operation, the message_block rd_ptr - * is updated to reflect the data that was written. - * @param act Token that is passed through to the completion - * handler. - * @param priority Priority of the operation. This argument only has - * an affect on POSIX4-Unix. Works like @c nice in - * Unix; negative values are not allowed. 0 means - * priority of the operation same as the process - * priority. 1 means priority of the operation is one - * less than the process, and so forth. - * @param signal_number The POSIX4 real-time signal number to be used - * for the operation. signal_number ranges from - * ACE_SIGRTMIN to ACE_SIGRTMAX. This argument is - * not used on other platforms. - * - * @retval 0 for success, and the handle_write_stream associated - * with the opened ACE_Handler will be called. An - * instance of ACE_Asynch_Write_Stream::Result will be - * passed to the completion handler. - * @retval -1 for failure; consult @c errno for further information. - */ - int write (ACE_Message_Block &message_block, - size_t bytes_to_write, - const void *act = 0, - int priority = 0, - int signal_number = ACE_SIGRTMIN); - -#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) - /** - * Same as above but with gather support, through chaining of composite - * message blocks using the continuation field. - */ - int writev (ACE_Message_Block &message_block, - size_t bytes_to_write, - const void *act = 0, - int priority = 0, - int signal_number = ACE_SIGRTMIN); -#endif /* defined (ACE_HAS_WIN32_OVERLAPPED_IO) */ - - /// Return the underlying implementation class. - /// @todo (this should be protected...) - virtual ACE_Asynch_Operation_Impl *implementation (void) const; - -protected: - /// Implementation class that all methods will be forwarded to. - ACE_Asynch_Write_Stream_Impl *implementation_; - -public: -/** - * @class Result - * - * @brief This is that class which will be passed back to the - * ACE_Handler when the asynchronous write completes. This class - * forwards all the methods to the implementation class. - * - * This class has all the information necessary for the - * handler to uniquiely identify the completion of the - * asynchronous write. - */ - class ACE_Export Result : public ACE_Asynch_Result - { - - /// The concrete implementation result classes only construct this - /// class. - friend class ACE_POSIX_Asynch_Write_Stream_Result; - friend class ACE_WIN32_Asynch_Write_Stream_Result; - - public: - /// The number of bytes which were requested at the start of the - /// asynchronous write. - size_t bytes_to_write (void) const; - - /// Message block that contains the data to be written. - ACE_Message_Block &message_block (void) const; - - /// I/O handle used for writing. - ACE_HANDLE handle (void) const; - - /// Get the implementation class. - ACE_Asynch_Write_Stream_Result_Impl *implementation (void) const; - - protected: - /// Constructor. - Result (ACE_Asynch_Write_Stream_Result_Impl *implementation); - - /// Destructor. - virtual ~Result (void); - - /// Implementation class. - ACE_Asynch_Write_Stream_Result_Impl *implementation_; - }; -private: - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Asynch_Write_Stream &)) - ACE_UNIMPLEMENTED_FUNC (ACE_Asynch_Write_Stream (const ACE_Asynch_Write_Stream &)) -}; - -// Forward declarations -class ACE_Asynch_Read_File_Impl; -class ACE_Asynch_Read_File_Result_Impl; - -/** - * @class ACE_Asynch_Read_File - * - * @brief This class is a factory for starting off asynchronous reads - * on a file. This class forwards all methods to its - * implementation class. - * - * Once open() is called, multiple asynchronous reads can - * started using this class. An ACE_Asynch_Read_File::Result - * will be passed back to the completion handler's - * ACE_Handler::handle_read_file() method when each asynchronous - * read completes. - * This class differs slightly from ACE_Asynch_Read_Stream as it - * allows the user to specify an offset for the read. - */ -class ACE_Export ACE_Asynch_Read_File : public ACE_Asynch_Read_Stream -{ - -public: - /// A do nothing constructor. - ACE_Asynch_Read_File (void); - - /// Destructor. - virtual ~ACE_Asynch_Read_File (void); - - /** - * Initializes the factory with information which will be used with - * each asynchronous operation. - * - * @param handler ACE_Handler to be notified when operations initiated - * via this factory complete. The - * ACE_Handler::handle_read_file() method will be - * called on this object. - * @param handle The file handle to initiate read operations on. - * If handle is @c ACE_INVALID_HANDLE, - * ACE_Handler::handle() will be called on handler to - * get the handle value. - * @param completion_key A token that is passed to the completion handler. - * @param proactor The ACE_Proactor object which will control operation - * completion and dispatching the results to handler. - * If this is 0, the process's singleton ACE_Proactor - * will be used. - * - * @retval 0 for success. - * @retval -1 for failure; consult @c errno for further information. - */ - int open (ACE_Handler &handler, - ACE_HANDLE handle = ACE_INVALID_HANDLE, - const void *completion_key = 0, - ACE_Proactor *proactor = 0); - - /** - * This starts off an asynchronous read. Upto {bytes_to_read} will - * be read and stored in the {message_block}. The read will start - * at {offset} from the beginning of the file. Priority of the - * operation is specified by {priority}. On POSIX4-Unix, this is - * supported. Works like {nice} in Unix. Negative values are not - * allowed. 0 means priority of the operation same as the process - * priority. 1 means priority of the operation is one less than - * process. And so forth. On Win32, this argument is a no-op. - * {signal_number} is the POSIX4 real-time signal number to be used - * for the operation. {signal_number} ranges from ACE_SIGRTMIN to - * ACE_SIGRTMAX. This argument is a no-op on non-POSIX4 systems. - */ - int read (ACE_Message_Block &message_block, - size_t bytes_to_read, - unsigned long offset = 0, - unsigned long offset_high = 0, - const void *act = 0, - int priority = 0, - int signal_number = ACE_SIGRTMIN); - -#if (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) - /** - * Same as above but with scatter support, through chaining of composite - * message blocks using the continuation field. - * @note In win32 Each data block payload must be at least the size of a system - * memory page and must be aligned on a system memory page size boundary - */ - int readv (ACE_Message_Block &message_block, - size_t bytes_to_read, - unsigned long offset = 0, - unsigned long offset_high = 0, - const void *act = 0, - int priority = 0, - int signal_number = ACE_SIGRTMIN); -#endif /* (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) */ - - /// Return the underlying implementation class. - // (this should be protected...) - virtual ACE_Asynch_Operation_Impl *implementation (void) const; - -protected: - /// Delegation/implementation class that all methods will be - /// forwarded to. - ACE_Asynch_Read_File_Impl *implementation_; - -public: -/** - * @class Result - * - * @brief This is that class which will be passed back to the - * {handler} when the asynchronous read completes. This class - * forwards all the methods to the implementation class. - * - * This class has all the information necessary for the - * {handler} to uniquiely identify the completion of the - * asynchronous read. - * This class differs slightly from - * ACE_Asynch_Read_Stream::Result as it calls back - * {ACE_Handler::handle_read_file} on the {handler} instead of - * {ACE_Handler::handle_read_stream}. No additional state is - * required by this class as ACE_Asynch_Result can store the - * {offset}. - */ - class ACE_Export Result : public ACE_Asynch_Read_Stream::Result - { - - /// The concrete implementation result classes only construct this - /// class. - friend class ACE_POSIX_Asynch_Read_File_Result; - friend class ACE_WIN32_Asynch_Read_File_Result; - - public: - /// Get the implementation class. - ACE_Asynch_Read_File_Result_Impl *implementation (void) const; - - protected: - /// Constructor. This implementation will not be deleted. - Result (ACE_Asynch_Read_File_Result_Impl *implementation); - - /// Destructor. - virtual ~Result (void); - - /// The implementation class. - ACE_Asynch_Read_File_Result_Impl *implementation_; - - private: - /// Here just to provide an dummpy implementation, since the - /// one auto generated by MSVC is flagged as infinitely recursive - void operator= (Result &) {} - }; -private: - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Asynch_Read_File &)) - ACE_UNIMPLEMENTED_FUNC (ACE_Asynch_Read_File (const ACE_Asynch_Read_File &)) -}; - -// Forward declarations -class ACE_Asynch_Write_File_Impl; -class ACE_Asynch_Write_File_Result_Impl; - -/** - * @class ACE_Asynch_Write_File - * - * @brief This class is a factory for starting off asynchronous writes - * on a file. This class forwards all methods to its - * implementation class. - * - * Once {open} is called, multiple asynchronous {write}s can be - * started using this class. A ACE_Asynch_Write_File::Result - * will be passed back to the {handler} when the asynchronous - * writes completes through the {ACE_Handler::handle_write_file} - * callback. - * This class differs slightly from ACE_Asynch_Write_Stream as - * it allows the user to specify an offset for the write. - */ -class ACE_Export ACE_Asynch_Write_File : public ACE_Asynch_Write_Stream -{ - -public: - /// A do nothing constructor. - ACE_Asynch_Write_File (void); - - /// Destructor. - virtual ~ACE_Asynch_Write_File (void); - - /** - * Initializes the factory with information which will be used with - * each asynchronous call. If ({handle} == ACE_INVALID_HANDLE), - * {ACE_Handler::handle} will be called on the {handler} to get the - * correct handle. - */ - int open (ACE_Handler &handler, - ACE_HANDLE handle = ACE_INVALID_HANDLE, - const void *completion_key = 0, - ACE_Proactor *proactor = 0); - - /** - * This starts off an asynchronous write. Upto {bytes_to_write} - * will be written from the {message_block}, starting at the - * block's {rd_ptr}. The write will go to the file, starting - * {offset} bytes from the beginning of the file. Priority of the - * operation is specified by {priority}. On POSIX4-Unix, this is - * supported. Works like {nice} in Unix. Negative values are not - * allowed. 0 means priority of the operation same as the process - * priority. 1 means priority of the operation is one less than - * process. And so forth. On Win32, this is a no-op. - * {signal_number} is the POSIX4 real-time signal number to be used - * for the operation. {signal_number} ranges from ACE_SIGRTMIN to - * ACE_SIGRTMAX. This argument is a no-op on non-POSIX4 systems. - */ - int write (ACE_Message_Block &message_block, - size_t bytes_to_write, - unsigned long offset = 0, - unsigned long offset_high = 0, - const void *act = 0, - int priority = 0, - int signal_number = ACE_SIGRTMIN); - -#if (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) - /** - * Same as above but with gather support, through chaining of composite - * message blocks using the continuation field. - * @note In win32 Each data block payload must be at least the size of a system - * memory page and must be aligned on a system memory page size boundary - */ - int writev (ACE_Message_Block &message_block, - size_t bytes_to_write, - unsigned long offset = 0, - unsigned long offset_high = 0, - const void *act = 0, - int priority = 0, - int signal_number = ACE_SIGRTMIN); -#endif /* (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) */ - - /// Return the underlying implementation class. - // (this should be protected...) - virtual ACE_Asynch_Operation_Impl *implementation (void) const; - -protected: - /// Implementation object. - ACE_Asynch_Write_File_Impl *implementation_; - -public: -/** - * @class Result - * - * @brief This is that class which will be passed back to the - * {handler} when the asynchronous write completes. This class - * forwards all the methods to the implementation class. - * - * This class has all the information necessary for the - * {handler} to uniquiely identify the completion of the - * asynchronous write. - * This class differs slightly from - * ACE_Asynch_Write_Stream::Result as it calls back - * {ACE_Handler::handle_write_file} on the {handler} instead - * of {ACE_Handler::handle_write_stream}. No additional state - * is required by this class as ACE_Asynch_Result can store - * the {offset}. - */ - class ACE_Export Result : public ACE_Asynch_Write_Stream::Result - { - - /// The concrete implementation result classes only construct this - /// class. - friend class ACE_POSIX_Asynch_Write_File_Result; - friend class ACE_WIN32_Asynch_Write_File_Result; - - public: - /// Get the implementation class. - ACE_Asynch_Write_File_Result_Impl *implementation (void) const; - - protected: - /// Constructor. This implementation will not be deleted. - Result (ACE_Asynch_Write_File_Result_Impl *implementation); - - /// Destructor. - virtual ~Result (void); - - /// The implementation class. - ACE_Asynch_Write_File_Result_Impl *implementation_; - - private: - /// Here just to provide an dummpy implementation, since the - /// one auto generated by MSVC is flagged as infinitely recursive - void operator= (Result &) {}; - }; -private: - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Asynch_Write_File &)) - ACE_UNIMPLEMENTED_FUNC (ACE_Asynch_Write_File (const ACE_Asynch_Write_File &)) -}; - -// Forward declarations -class ACE_Asynch_Accept_Result_Impl; -class ACE_Asynch_Accept_Impl; - -/** - * @class ACE_Asynch_Accept - * - * @brief This class is a factory for starting off asynchronous accepts - * on a listen handle. This class forwards all methods to its - * implementation class. - * - * Once {open} is called, multiple asynchronous {accept}s can - * started using this class. A ACE_Asynch_Accept::Result will - * be passed back to the {handler} when the asynchronous accept - * completes through the {ACE_Handler::handle_accept} - * callback. - */ -class ACE_Export ACE_Asynch_Accept : public ACE_Asynch_Operation -{ - -public: - /// A do nothing constructor. - ACE_Asynch_Accept (void); - - /// Destructor. - virtual ~ACE_Asynch_Accept (void); - - /** - * Initializes the factory with information which will be used with - * each asynchronous call. If ({handle} == ACE_INVALID_HANDLE), - * {ACE_Handler::handle} will be called on the {handler} to get the - * correct handle. - */ - int open (ACE_Handler &handler, - ACE_HANDLE handle = ACE_INVALID_HANDLE, - const void *completion_key = 0, - ACE_Proactor *proactor = 0); - - /** - * This starts off an asynchronous accept. The asynchronous accept - * call also allows any initial data to be returned to the - * handler specified to @c open(). - * @param message_block A message block to receive initial data, as well - * as the local and remote addresses when the - * connection is made. Since the block receives - * the addresses regardless of whether or not - * initial data is available or requested, the - * message block size must be at least - * @a bytes_to_read plus two times the size of - * the addresses used (IPv4 or IPv6). - * @param bytes_to_read The maximum number of bytes of initial data - * to read into @a message_block. - * @param accept_handle The handle that the new connection will be - * accepted on. If @c INVALID_HANDLE, a new - * handle will be created using @a addr_family. - * @param act Value to be passed in result when operation - * completes. - * @param priority Priority of the operation. On POSIX4-Unix, this - * is supported. Works like @c nice in Unix. - * Negative values are not allowed. 0 means - * priority of the operation same as the process - * priority. 1 means priority of the operation is - * one less than process. And so forth. - * On Win32, this argument is ignored. - * @param signal_number The POSIX4 real-time signal number to be used - * for the operation. Value range is from - * @c ACE_SIGRTMIN to @c ACE_SIGRTMAX. - * This argument is ignored on non-POSIX4 systems. - * @param addr_family The address family to use if @a accept_handle - * is @c ACE_INVALID_HANDLE and a new handle must - * be opened. Values are @c AF_INET and @c PF_INET6. - */ - int accept (ACE_Message_Block &message_block, - size_t bytes_to_read, - ACE_HANDLE accept_handle = ACE_INVALID_HANDLE, - const void *act = 0, - int priority = 0, - int signal_number = ACE_SIGRTMIN, - int addr_family = AF_INET); - - /// Return the underlying implementation class. - // (this should be protected...) - virtual ACE_Asynch_Operation_Impl *implementation (void) const; - -protected: - /// Delegation/implementation class that all methods will be - /// forwarded to. - ACE_Asynch_Accept_Impl *implementation_; - -public: -/** - * @class Result - * - * @brief This is that class which will be passed back to the - * {handler} when the asynchronous accept completes. - * - * This class has all the information necessary for the - * {handler} to uniquiely identify the completion of the - * asynchronous accept. - */ - class ACE_Export Result : public ACE_Asynch_Result - { - - /// The concrete implementation result classes only construct this - /// class. - friend class ACE_POSIX_Asynch_Accept_Result; - friend class ACE_WIN32_Asynch_Accept_Result; - - public: - /// The number of bytes which were requested at the start of the - /// asynchronous accept. - size_t bytes_to_read (void) const; - - /// Message block which contains the read data. - ACE_Message_Block &message_block (void) const; - - /// I/O handle used for accepting new connections. - ACE_HANDLE listen_handle (void) const; - - /// I/O handle for the new connection. - ACE_HANDLE accept_handle (void) const; - - /// Get the implementation. - ACE_Asynch_Accept_Result_Impl *implementation (void) const; - - protected: - /// Contructor. Implementation will not be deleted. - Result (ACE_Asynch_Accept_Result_Impl *implementation); - - /// Destructor. - virtual ~Result (void); - - /// Impelmentation class. - ACE_Asynch_Accept_Result_Impl *implementation_; - }; -private: - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Asynch_Accept &)) - ACE_UNIMPLEMENTED_FUNC (ACE_Asynch_Accept (const ACE_Asynch_Accept &)) -}; -// Forward declarations -class ACE_Asynch_Connect_Result_Impl; -class ACE_Asynch_Connect_Impl; - -/** - * @class ACE_Asynch_Connect - * - * @brief This class is a factory for starting off asynchronous connects - * This class forwards all methods to its implementation class. - * - * Once @c open is called, multiple asynchronous connect operationss can - * started using this class. A ACE_Asynch_Connect::Result will - * be passed back to the associated ACE_Handler when the asynchronous connect - * completes through the ACE_Handler::handle_connect() callback. - */ -class ACE_Export ACE_Asynch_Connect : public ACE_Asynch_Operation -{ - -public: - /// A do nothing constructor. - ACE_Asynch_Connect (void); - - /// Destructor. - virtual ~ACE_Asynch_Connect (void); - - /** - * Initializes the factory with information which will be used with - * each asynchronous call. - * - * @note @arg handle is ignored and should be @c ACE_INVALID_HANDLE. - */ - int open (ACE_Handler &handler, - ACE_HANDLE handle = ACE_INVALID_HANDLE, - const void *completion_key = 0, - ACE_Proactor *proactor = 0); - - /** - * This starts off an asynchronous Connect. - */ - int connect (ACE_HANDLE connect_handle, - const ACE_Addr & remote_sap, - const ACE_Addr & local_sap, - int reuse_addr, - const void *act=0, - int priority = 0, - int signal_number = ACE_SIGRTMIN); - - /// Return the underlying implementation class. - // (this should be protected...) - virtual ACE_Asynch_Operation_Impl *implementation (void) const; - -protected: - /// Delegation/implementation class that all methods will be - /// forwarded to. - ACE_Asynch_Connect_Impl *implementation_; - -public: -/** - * @class Result - * - * @brief This is that class which will be passed back to the - * handler when the asynchronous connect completes. - * - * This class has all the information necessary for the - * handler to uniquely identify the completion of the - * asynchronous connect. - */ - class ACE_Export Result : public ACE_Asynch_Result - { - - /// The concrete implementation result classes only construct this - /// class. - friend class ACE_POSIX_Asynch_Connect_Result; - friend class ACE_WIN32_Asynch_Connect_Result; - - public: - - /// I/O handle for the connection. - ACE_HANDLE connect_handle (void) const; - - /// Get the implementation. - ACE_Asynch_Connect_Result_Impl *implementation (void) const; - - protected: - /// Contructor. Implementation will not be deleted. - Result (ACE_Asynch_Connect_Result_Impl *implementation); - - /// Destructor. - virtual ~Result (void); - - /// Impelmentation class. - ACE_Asynch_Connect_Result_Impl *implementation_; - }; -private: - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Asynch_Connect &)) - ACE_UNIMPLEMENTED_FUNC (ACE_Asynch_Connect (const ACE_Asynch_Connect &)) -}; - -// Forward declarations -class ACE_Asynch_Transmit_File_Result_Impl; -class ACE_Asynch_Transmit_File_Impl; - -/** - * @class ACE_Asynch_Transmit_File - * - * @brief This class is a factory for starting off asynchronous - * transmit files on a stream. - * - * Once {open} is called, multiple asynchronous {transmit_file}s - * can started using this class. A - * ACE_Asynch_Transmit_File::Result will be passed back to the - * {handler} when the asynchronous transmit file completes - * through the {ACE_Handler::handle_transmit_file} callback. - * The transmit_file function transmits file data over a - * connected network connection. The function uses the operating - * system's cache manager to retrieve the file data. This - * function provides high-performance file data transfer over - * network connections. This function would be of great use in - * a Web Server, Image Server, etc. - */ -class ACE_Export ACE_Asynch_Transmit_File : public ACE_Asynch_Operation -{ - -public: - // Forward declarations - class Header_And_Trailer; - - /// A do nothing constructor. - ACE_Asynch_Transmit_File (void); - - /// Destructor. - virtual ~ACE_Asynch_Transmit_File (void); - - /** - * Initializes the factory with information which will be used with - * each asynchronous call. If ({handle} == ACE_INVALID_HANDLE), - * {ACE_Handler::handle} will be called on the {handler} to get the - * correct handle. - */ - int open (ACE_Handler &handler, - ACE_HANDLE handle = ACE_INVALID_HANDLE, - const void *completion_key = 0, - ACE_Proactor *proactor = 0); - - /** - * This starts off an asynchronous transmit file. The {file} is a - * handle to an open file. {header_and_trailer} is a pointer to a - * data structure that contains pointers to data to send before and - * after the file data is sent. Set this parameter to 0 if you only - * want to transmit the file data. Upto {bytes_to_write} will be - * written to the {socket}. If you want to send the entire file, - * let {bytes_to_write} = 0. {bytes_per_send} is the size of each - * block of data sent per send operation. Please read the Win32 - * documentation on what the flags should be. Priority of the - * operation is specified by {priority}. On POSIX4-Unix, this is - * supported. Works like {nice} in Unix. Negative values are not - * allowed. 0 means priority of the operation same as the process - * priority. 1 means priority of the operation is one less than - * process. And so forth. On Win32, this is a no-op. - * {signal_number} is the POSIX4 real-time signal number to be used - * for the operation. {signal_number} ranges from ACE_SIGRTMIN to - * ACE_SIGRTMAX. This argument is a no-op on non-POSIX4 systems. - */ - int transmit_file (ACE_HANDLE file, - Header_And_Trailer *header_and_trailer = 0, - size_t bytes_to_write = 0, - unsigned long offset = 0, - unsigned long offset_high = 0, - size_t bytes_per_send = 0, - unsigned long flags = 0, - const void *act = 0, - int priority = 0, - int signal_number = ACE_SIGRTMIN); - - /// Return the underlying implementation class. - // (this should be protected...) - virtual ACE_Asynch_Operation_Impl *implementation (void) const; - -protected: - /// The implementation class. - ACE_Asynch_Transmit_File_Impl *implementation_; - -public: -/** - * @class Result - * - * @brief This is that class which will be passed back to the - * {handler} when the asynchronous transmit file completes. - * - * This class has all the information necessary for the - * {handler} to uniquiely identify the completion of the - * asynchronous transmit file. - */ - class ACE_Export Result : public ACE_Asynch_Result - { - - /// The concrete implementation result classes only construct this - /// class. - friend class ACE_POSIX_Asynch_Transmit_File_Result; - friend class ACE_WIN32_Asynch_Transmit_File_Result; - - public: - /// Socket used for transmitting the file. - ACE_HANDLE socket (void) const; - - /// File from which the data is read. - ACE_HANDLE file (void) const; - - /// Header and trailer data associated with this transmit file. - Header_And_Trailer *header_and_trailer (void) const; - - /// The number of bytes which were requested at the start of the - /// asynchronous transmit file. - size_t bytes_to_write (void) const; - - /// Number of bytes per send requested at the start of the transmit - /// file. - size_t bytes_per_send (void) const; - - /// Flags which were passed into transmit file. - unsigned long flags (void) const; - - /// Get the implementation class. - ACE_Asynch_Transmit_File_Result_Impl *implementation (void) const; - - protected: - /// Constructor. - Result (ACE_Asynch_Transmit_File_Result_Impl *implementation); - - /// Destructor. - virtual ~Result (void); - - /// The implementation class. - ACE_Asynch_Transmit_File_Result_Impl *implementation_; - }; - -/** - * @class Header_And_Trailer - * - * @brief The class defines a data structure that contains pointers - * to data to send before and after the file data is sent. - * - * This class provides a wrapper over TRANSMIT_FILE_BUFFERS - * and provided a consistent use of ACE_Message_Blocks. - */ - class ACE_Export Header_And_Trailer - { - - public: - /// Constructor. - Header_And_Trailer (ACE_Message_Block *header = 0, - size_t header_bytes = 0, - ACE_Message_Block *trailer = 0, - size_t trailer_bytes = 0); - - /// Destructor - virtual ~Header_And_Trailer (void); - - /// This method allows all the member to be set in one fell swoop. - void header_and_trailer (ACE_Message_Block *header = 0, - size_t header_bytes = 0, - ACE_Message_Block *trailer = 0, - size_t trailer_bytes = 0); - - /// Get header which goes before the file data. - ACE_Message_Block *header (void) const; - - /// Set header which goes before the file data. - void header (ACE_Message_Block *message_block); - - /// Get size of the header data. - size_t header_bytes (void) const; - - /// Set size of the header data. - void header_bytes (size_t bytes); - - /// Get trailer which goes after the file data. - ACE_Message_Block *trailer (void) const; - - /// Set trailer which goes after the file data. - void trailer (ACE_Message_Block *message_block); - - /// Get size of the trailer data. - size_t trailer_bytes (void) const; - - /// Set size of the trailer data. - void trailer_bytes (size_t bytes); - - /// Conversion routine. - ACE_LPTRANSMIT_FILE_BUFFERS transmit_buffers (void); - - protected: - /// Header data. - ACE_Message_Block *header_; - - /// Size of header data. - size_t header_bytes_; - - /// Trailer data. - ACE_Message_Block *trailer_; - - /// Size of trailer data. - size_t trailer_bytes_; - - /// Target data structure. - ACE_TRANSMIT_FILE_BUFFERS transmit_buffers_; - }; -private: - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Asynch_Transmit_File &)) - ACE_UNIMPLEMENTED_FUNC (ACE_Asynch_Transmit_File (const ACE_Asynch_Transmit_File &)) -}; - - -// Forward declarations -class ACE_Asynch_Read_Dgram_Result_Impl; -class ACE_Asynch_Read_Dgram_Impl; -class ACE_Addr; - -/** - * @class ACE_Asynch_Read_Dgram - * - * @brief This class is a factory for starting off asynchronous reads - * on a UDP socket. This class forwards all methods to its - * implementation class. - * - * Once {open} is called, multiple asynchronous {read}s can be - * started using this class. An ACE_Asynch_Read_Dgram::Result - * will be passed back to the {handler} when the asynchronous - * reads completes through the {ACE_Handler::handle_read_dgram} - * callback. - */ -class ACE_Export ACE_Asynch_Read_Dgram : public ACE_Asynch_Operation -{ - -public: - /// A do nothing constructor. - ACE_Asynch_Read_Dgram (void); - - /// Destructor - virtual ~ACE_Asynch_Read_Dgram (void); - - /** - * Initializes the factory with information which will be used with - * each asynchronous call. If ({handle} == ACE_INVALID_HANDLE), - * {ACE_Handler::handle} will be called on the {handler} to get the - * correct handle. - */ - int open (ACE_Handler &handler, - ACE_HANDLE handle = ACE_INVALID_HANDLE, - const void *completion_key = 0, - ACE_Proactor *proactor = 0); - - /** This starts off an asynchronous read. Upto - * {message_block->total_size()} will be read and stored in the - * {message_block}. {message_block}'s {wr_ptr} will be updated to reflect - * the added bytes if the read operation is successfully completed. - * Return code of 1 means immediate success and {number_of_bytes_recvd} - * will contain number of bytes read. The {ACE_Handler::handle_read_dgram} - * method will still be called. Return code of 0 means the IO will - * complete proactively. Return code of -1 means there was an error, use - * errno to get the error code. - * - * Scatter/gather is supported on WIN32 by using the {message_block->cont()} - * method. Up to ACE_IOV_MAX {message_block}'s are supported. Upto - * {message_block->size()} bytes will be read into each {message block} for - * a total of {message_block->total_size()} bytes. All {message_block}'s - * {wr_ptr}'s will be updated to reflect the added bytes for each - * {message_block} - * - * Priority of the operation is specified by {priority}. On POSIX4-Unix, - * this is supported. Works like {nice} in Unix. Negative values are not - * allowed. 0 means priority of the operation same as the process - * priority. 1 means priority of the operation is one less than - * process. And so forth. On Win32, {priority} is a no-op. - * {signal_number} is the POSIX4 real-time signal number to be used - * for the operation. {signal_number} ranges from ACE_SIGRTMIN to - * ACE_SIGRTMAX. This argument is a no-op on non-POSIX4 systems. - */ - ssize_t recv (ACE_Message_Block *message_block, - size_t &number_of_bytes_recvd, - int flags, - int protocol_family = PF_INET, - const void *act = 0, - int priority = 0, - int signal_number = ACE_SIGRTMIN); - - /// Return the underlying implementation class. - // (this should be protected...) - virtual ACE_Asynch_Operation_Impl *implementation (void) const; - -protected: - /// Implementation class that all methods will be forwarded to. - ACE_Asynch_Read_Dgram_Impl *implementation_; - -public: -/** - * @class Result - * - * @brief This is the class which will be passed back to the - * {handler} when the asynchronous read completes. This class - * forwards all the methods to the implementation classes. - * - * This class has all the information necessary for the - * {handler} to uniquiely identify the completion of the - * asynchronous read. - */ - class ACE_Export Result : public ACE_Asynch_Result - { - - /// The concrete implementation result classes only construct this - /// class. - friend class ACE_POSIX_Asynch_Read_Dgram_Result; - friend class ACE_WIN32_Asynch_Read_Dgram_Result; - - public: - - /// The number of bytes which were requested at the start of the - /// asynchronous read. - size_t bytes_to_read (void) const; - - /// Message block which contains the read data - ACE_Message_Block *message_block (void) const; - - /// The flags used in the read - int flags (void) const; - - /// The address of where the packet came from - int remote_address (ACE_Addr& addr) const; - - /// I/O handle used for reading. - ACE_HANDLE handle (void) const; - - /// Get the implementation class. - ACE_Asynch_Read_Dgram_Result_Impl *implementation (void) const; - - protected: - /// Constructor. - Result (ACE_Asynch_Read_Dgram_Result_Impl *implementation); - - /// Destructor. - virtual ~Result (void); - - /// The implementation class. - ACE_Asynch_Read_Dgram_Result_Impl *implementation_; - }; -private: - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Asynch_Read_Dgram &)) - ACE_UNIMPLEMENTED_FUNC (ACE_Asynch_Read_Dgram (const ACE_Asynch_Read_Dgram &)) -}; - -// Forward declarations -class ACE_Asynch_Write_Dgram_Impl; -class ACE_Asynch_Write_Dgram_Result_Impl; - -/** - * @class ACE_Asynch_Write_Dgram - * - * @brief This class is a factory for starting off asynchronous writes - * on a UDP socket. This class forwards all methods to its - * implementation class. - * - * Once {open} is called, multiple asynchronous {writes}s can - * started using this class. An ACE_Asynch_Write_Dgram::Result - * will be passed back to the {handler} when the asynchronous - * write completes through the - * {ACE_Handler::handle_write_dgram} callback. - */ -class ACE_Export ACE_Asynch_Write_Dgram : public ACE_Asynch_Operation -{ - -public: - /// A do nothing constructor. - ACE_Asynch_Write_Dgram (void); - - /// Destructor. - virtual ~ACE_Asynch_Write_Dgram (void); - - /** - * Initializes the factory with information which will be used with - * each asynchronous call. If ({handle} == ACE_INVALID_HANDLE), - * {ACE_Handler::handle} will be called on the {handler} to get the - * correct handle. - */ - int open (ACE_Handler &handler, - ACE_HANDLE handle = ACE_INVALID_HANDLE, - const void *completion_key = 0, - ACE_Proactor *proactor = 0); - - /** This starts off an asynchronous send. Upto - * {message_block->total_length()} will be sent. {message_block}'s - * {rd_ptr} will be updated to reflect the sent bytes if the send operation - * is successfully completed. - * Return code of 1 means immediate success and {number_of_bytes_sent} - * is updated to number of bytes sent. The {ACE_Handler::handle_write_dgram} - * method will still be called. Return code of 0 means the IO will - * complete proactively. Return code of -1 means there was an error, use - * errno to get the error code. - * - * Scatter/gather is supported on WIN32 by using the {message_block->cont()} - * method. Up to ACE_IOV_MAX {message_block}'s are supported. Upto - * {message_block->length()} bytes will be sent from each {message block} - * for a total of {message_block->total_length()} bytes. All - * {message_block}'s {rd_ptr}'s will be updated to reflect the bytes sent - * from each {message_block}. - * - * Priority of the operation is specified by {priority}. On POSIX4-Unix, - * this is supported. Works like {nice} in Unix. Negative values are not - * allowed. 0 means priority of the operation same as the process - * priority. 1 means priority of the operation is one less than - * process. And so forth. On Win32, this argument is a no-op. - * {signal_number} is the POSIX4 real-time signal number to be used - * for the operation. {signal_number} ranges from ACE_SIGRTMIN to - * ACE_SIGRTMAX. This argument is a no-op on non-POSIX4 systems. - */ - ssize_t send (ACE_Message_Block *message_block, - size_t &number_of_bytes_sent, - int flags, - const ACE_Addr& remote_addr, - const void *act = 0, - int priority = 0, - int signal_number = ACE_SIGRTMIN); - - /// Return the underlying implementation class. - // (this should be protected...) - virtual ACE_Asynch_Operation_Impl *implementation (void) const; - -protected: - /// Implementation class that all methods will be forwarded to. - ACE_Asynch_Write_Dgram_Impl *implementation_; - -public: -/** - * @class Result - * - * @brief This is that class which will be passed back to the - * {handler} when the asynchronous write completes. This class - * forwards all the methods to the implementation class. - * - * This class has all the information necessary for the - * {handler} to uniquiely identify the completion of the - * asynchronous write. - */ - class ACE_Export Result : public ACE_Asynch_Result - { - - /// The concrete implementation result classes only construct this - /// class. - friend class ACE_POSIX_Asynch_Write_Dgram_Result; - friend class ACE_WIN32_Asynch_Write_Dgram_Result; - - public: - - /// The number of bytes which were requested at the start of the - /// asynchronous write. - size_t bytes_to_write (void) const; - - /// Message block which contains the sent data - ACE_Message_Block *message_block (void) const; - - /// The flags using in the write - int flags (void) const; - - /// I/O handle used for writing. - ACE_HANDLE handle (void) const; - - /// Get the implementation class. - ACE_Asynch_Write_Dgram_Result_Impl *implementation (void) const; - - protected: - /// Constructor. - Result (ACE_Asynch_Write_Dgram_Result_Impl *implementation); - - /// Destructor. - virtual ~Result (void); - - /// Implementation class. - ACE_Asynch_Write_Dgram_Result_Impl *implementation_; - }; -private: - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Asynch_Write_Dgram &)) - ACE_UNIMPLEMENTED_FUNC (ACE_Asynch_Write_Dgram (const ACE_Asynch_Write_Dgram &)) -}; - - -/** - * @class ACE_Handler - * - * @brief This base class defines the interface for receiving the - * results of asynchronous operations. - * - * Subclasses of this class will fill in appropriate methods. - */ -class ACE_Export ACE_Handler -{ -public: - /// A do nothing constructor. - ACE_Handler (void); - - /// A do nothing constructor which allows proactor to be set to \. - ACE_Handler (ACE_Proactor *p); - - /// Virtual destruction. - virtual ~ACE_Handler (void); - - /// This method will be called when an asynchronous read completes on - /// a stream. - virtual void handle_read_stream (const ACE_Asynch_Read_Stream::Result &result); - - /// This method will be called when an asynchronous write completes - /// on a UDP socket. - virtual void handle_write_dgram (const ACE_Asynch_Write_Dgram::Result &result); - - /// This method will be called when an asynchronous read completes on - /// a UDP socket. - virtual void handle_read_dgram (const ACE_Asynch_Read_Dgram::Result &result); - - /// This method will be called when an asynchronous write completes - /// on a stream. - virtual void handle_write_stream (const ACE_Asynch_Write_Stream::Result &result); - - /// This method will be called when an asynchronous read completes on - /// a file. - virtual void handle_read_file (const ACE_Asynch_Read_File::Result &result); - - /// This method will be called when an asynchronous write completes - /// on a file. - virtual void handle_write_file (const ACE_Asynch_Write_File::Result &result); - - /// This method will be called when an asynchronous accept completes. - virtual void handle_accept (const ACE_Asynch_Accept::Result &result); - - /// This method will be called when an asynchronous connect completes. - virtual void handle_connect (const ACE_Asynch_Connect::Result &result); - - /// This method will be called when an asynchronous transmit file - /// completes. - virtual void handle_transmit_file (const ACE_Asynch_Transmit_File::Result &result); - - /// Called when timer expires. {tv} was the requested time value and - /// {act} is the ACT passed when scheduling the timer. - virtual void handle_time_out (const ACE_Time_Value &tv, - const void *act = 0); - - /** - * This is method works with the {run_event_loop} of the - * ACE_Proactor. A special {Wake_Up_Completion} is used to wake up - * all the threads that are blocking for completions. - */ - virtual void handle_wakeup (void); - - /// Get the proactor associated with this handler. - ACE_Proactor *proactor (void); - - /// Set the proactor. - void proactor (ACE_Proactor *p); - - /** - * Get the I/O handle used by this {handler}. This method will be - * called by the ACE_Asynch_* classes when an ACE_INVALID_HANDLE is - * passed to {open}. - */ - virtual ACE_HANDLE handle (void) const; - - /// Set the ACE_HANDLE value for this Handler. - virtual void handle (ACE_HANDLE); - - /** - * @class Proxy - * - * @brief The Proxy class acts as a proxy for dispatch of completions - * to operations issued for the associated handler. It allows the handler - * to be deleted while operations are outstanding. The proxy must be used - * to get the ACE_Handler pointer for dispatching, and if it's 0, the - * handler is no longer valid and the result should not be dispatched. - */ - class ACE_Export Proxy - { - public: - Proxy (ACE_Handler *handler) : handler_ (handler) {}; - void reset (void) { this->handler_ = 0; }; - ACE_Handler *handler (void) { return this->handler_; }; - private: - ACE_Handler *handler_; - }; - typedef ACE_Refcounted_Auto_Ptr - Proxy_Ptr; - - Proxy_Ptr &proxy (void); - -protected: - /// The proactor associated with this handler. - ACE_Proactor *proactor_; - - /// The ACE_HANDLE in use with this handler. - ACE_HANDLE handle_; - - /// Refers to proxy for this handler. - ACE_Refcounted_Auto_Ptr proxy_; - - ACE_UNIMPLEMENTED_FUNC (ACE_Handler (const ACE_Handler &)) - ACE_UNIMPLEMENTED_FUNC (ACE_Handler operator= (const ACE_Handler &)) -}; - -// Forward declarations -class ACE_INET_Addr; - -// Forward declarations -template -class ACE_Asynch_Acceptor; - -/** - * @class ACE_Service_Handler - * - * @brief This base class defines the interface for the - * ACE_Asynch_Acceptor to call into when new connection are - * accepted. - * - * Subclasses of this class will fill in appropriate methods to - * define application specific behavior. - */ -class ACE_Export ACE_Service_Handler : public ACE_Handler -{ - - /// The Acceptor is the factory and therefore should have special - /// privileges. - friend class ACE_Asynch_Acceptor; - -public: - /// A do nothing constructor. - ACE_Service_Handler (void); - - /// Virtual destruction. - virtual ~ACE_Service_Handler (void); - - /** - * {open} is called by ACE_Asynch_Acceptor to initialize a new - * instance of ACE_Service_Handler that has been created after the - * new connection is accepted. The handle for the new connection is - * passed along with the initial data that may have shown up. - */ - virtual void open (ACE_HANDLE new_handle, - ACE_Message_Block &message_block); - - // protected: - // This should be corrected after the correct semantics of the - // friend has been figured out. - - /// Called by ACE_Asynch_Acceptor to pass the addresses of the new - /// connections. - virtual void addresses (const ACE_INET_Addr &remote_address, - const ACE_INET_Addr &local_address); - - /// Called by ACE_Asynch_Acceptor to pass the act. - virtual void act (const void *); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_WIN32 || ACE_HAS_AIO_CALLS*/ -#include /**/ "ace/post.h" -#endif /* ACE_ASYNCH_IO_H */ diff --git a/externals/ace/Asynch_IO_Impl.cpp b/externals/ace/Asynch_IO_Impl.cpp deleted file mode 100644 index b4b47eda55c..00000000000 --- a/externals/ace/Asynch_IO_Impl.cpp +++ /dev/null @@ -1,117 +0,0 @@ -// $Id: Asynch_IO_Impl.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Asynch_IO_Impl.h" - -#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) || defined (ACE_HAS_AIO_CALLS) -// This only works on Win32 platforms and on Unix platforms supporting -// aio calls. - -#if !defined (__ACE_INLINE__) -#include "ace/Asynch_IO_Impl.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_Asynch_Result_Impl::~ACE_Asynch_Result_Impl (void) -{ -} - -ACE_Asynch_Operation_Impl::~ACE_Asynch_Operation_Impl (void) -{ -} - -ACE_Asynch_Read_Stream_Impl::~ACE_Asynch_Read_Stream_Impl (void) -{ -} - -ACE_Asynch_Read_Stream_Result_Impl::~ACE_Asynch_Read_Stream_Result_Impl (void) -{ -} - -ACE_Asynch_Write_Stream_Impl::~ACE_Asynch_Write_Stream_Impl (void) -{ -} - -ACE_Asynch_Write_Stream_Result_Impl::~ACE_Asynch_Write_Stream_Result_Impl (void) -{ -} - -ACE_Asynch_Read_File_Impl::~ACE_Asynch_Read_File_Impl (void) -{ -} - -ACE_Asynch_Write_File_Impl::~ACE_Asynch_Write_File_Impl (void) -{ -} - -ACE_Asynch_Read_File_Result_Impl::~ACE_Asynch_Read_File_Result_Impl (void) -{ -} - -ACE_Asynch_Write_File_Result_Impl::~ACE_Asynch_Write_File_Result_Impl (void) -{ -} - -ACE_Asynch_Accept_Result_Impl::~ACE_Asynch_Accept_Result_Impl (void) -{ -} - -ACE_Asynch_Connect_Result_Impl::~ACE_Asynch_Connect_Result_Impl (void) -{ -} - -ACE_Asynch_Accept_Impl::~ACE_Asynch_Accept_Impl (void) -{ -} - -ACE_Asynch_Connect_Impl::~ACE_Asynch_Connect_Impl (void) -{ -} - -ACE_Asynch_Transmit_File_Impl::~ACE_Asynch_Transmit_File_Impl (void) -{ -} - -ACE_Asynch_Transmit_File_Result_Impl::~ACE_Asynch_Transmit_File_Result_Impl (void) -{ -} - -ACE_Asynch_Read_Dgram_Impl::~ACE_Asynch_Read_Dgram_Impl (void) -{ -} - -ACE_Asynch_Read_Dgram_Impl::ACE_Asynch_Read_Dgram_Impl (void) -{ -} - -ACE_Asynch_Write_Dgram_Impl::~ACE_Asynch_Write_Dgram_Impl (void) -{ -} - -ACE_Asynch_Write_Dgram_Impl::ACE_Asynch_Write_Dgram_Impl (void) -{ -} - -//*********************************************** - -ACE_Asynch_Read_Dgram_Result_Impl::~ACE_Asynch_Read_Dgram_Result_Impl (void) -{ -} - -ACE_Asynch_Read_Dgram_Result_Impl::ACE_Asynch_Read_Dgram_Result_Impl (void) -{ -} - -//*********************************************** - -ACE_Asynch_Write_Dgram_Result_Impl::~ACE_Asynch_Write_Dgram_Result_Impl (void) -{ -} - -ACE_Asynch_Write_Dgram_Result_Impl::ACE_Asynch_Write_Dgram_Result_Impl (void) -{ -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_WIN32_OVERLAPPED_IO || ACE_HAS_AIO_CALLS */ diff --git a/externals/ace/Asynch_IO_Impl.h b/externals/ace/Asynch_IO_Impl.h deleted file mode 100644 index 06eb5c10a87..00000000000 --- a/externals/ace/Asynch_IO_Impl.h +++ /dev/null @@ -1,816 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file Asynch_IO_Impl.h - * - * $Id: Asynch_IO_Impl.h 80826 2008-03-04 14:51:23Z wotte $ - * - * - * This class contains asbtract base classes for all the concrete - * implementation classes for the various asynchronous operations - * that are used with the Praoctor. - * - * - * @author Irfan Pyarali (irfan@cs.wustl.edu) - * @author Tim Harrison (harrison@cs.wustl.edu) - * @author Alexander Babu Arulanthu - * @author Roger Tragin - * @author Alexander Libman - */ -//============================================================================= - -#ifndef ACE_ASYNCH_IO_IMPL_H -#define ACE_ASYNCH_IO_IMPL_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -#pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) || defined (ACE_HAS_AIO_CALLS) -// This only works on Win32 platforms and on Unix platforms supporting -// aio calls. - -#include "ace/Asynch_IO.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Forward declaration. -class ACE_Proactor_Impl; - -/** - * @class ACE_Asynch_Result_Impl - * - * @brief Abstract base class for the all the classes that provide - * concrete implementations for ACE_Asynch_Result. - * - */ -class ACE_Export ACE_Asynch_Result_Impl -{ -public: - virtual ~ACE_Asynch_Result_Impl (void); - - /// Number of bytes transferred by the operation. - virtual size_t bytes_transferred (void) const = 0; - - /// ACT associated with the operation. - virtual const void *act (void) const = 0; - - /// Did the operation succeed? - virtual int success (void) const = 0; - - /// This ACT is not the same as the ACT associated with the - /// asynchronous operation. - virtual const void *completion_key (void) const = 0; - - /// Error value if the operation fail. - virtual u_long error (void) const = 0; - - /// Event associated with the OVERLAPPED structure. - virtual ACE_HANDLE event (void) const = 0; - - /// This really make sense only when doing file I/O. - virtual u_long offset (void) const = 0; - virtual u_long offset_high (void) const = 0; - - /// Priority of the operation. - virtual int priority (void) const = 0; - - /** - * POSIX4 real-time signal number to be used for the - * operation. ranges from SIGRTMIN to SIGRTMAX. By - * default, SIGRTMIN is used to issue calls. This is a no-op - * on non-POSIX4 systems and returns 0. - */ - virtual int signal_number (void) const = 0; - - // protected: - // - // These two should really be protected. But sometimes it - // simplifies code to be able to "fake" a result. Use carefully. - /// This is called when the asynchronous operation completes. - virtual void complete (size_t bytes_transferred, - int success, - const void *completion_key, - u_long error = 0) = 0; - - /// Post @c this to the Proactor's completion port. - virtual int post_completion (ACE_Proactor_Impl *proactor) = 0; - -protected: - /// Do-nothing constructor. - ACE_Asynch_Result_Impl (void); -}; - -/** - * @class ACE_Asynch_Operation_Impl - * - * @brief Abstract base class for all the concrete implementation - * classes that provide different implementations for the - * ACE_Asynch_Operation. - */ -class ACE_Export ACE_Asynch_Operation_Impl -{ -public: - virtual ~ACE_Asynch_Operation_Impl (void); - - /** - * Initializes the factory with information which will be used with - * each asynchronous call. If @a handle == ACE_INVALID_HANDLE, - * ACE_Handler::handle() will be called on the proxied handler to get the - * correct handle. - */ - virtual int open (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor) = 0; - - /** - * This cancels all pending accepts operations that were issued by - * the calling thread. The function does not cancel asynchronous - * operations issued by other threads. - */ - virtual int cancel (void) = 0; - - // = Access methods. - - /// Return the underlying proactor. - virtual ACE_Proactor* proactor (void) const = 0; - -protected: - /// Do-nothing constructor. - ACE_Asynch_Operation_Impl (void); -}; - -/** - * @class ACE_Asynch_Read_Stream_Impl - * - * @brief Abstract base class for all the concrete implementation - * classes that provide different implementations for the - * ACE_Asynch_Read_Stream - * - */ -class ACE_Export ACE_Asynch_Read_Stream_Impl : public virtual ACE_Asynch_Operation_Impl -{ -public: - virtual ~ACE_Asynch_Read_Stream_Impl (void); - - /// This starts off an asynchronous read. Upto @a bytes_to_read will - /// be read and stored in the @a message_block. - virtual int read (ACE_Message_Block &message_block, - size_t bytes_to_read, - const void *act, - int priority, - int signal_number) = 0; - -#if (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) - /** - * Same as above but with scatter support, through chaining of composite - * message blocks using the continuation field. - */ - virtual int readv (ACE_Message_Block &message_block, - size_t bytes_to_read, - const void *act, - int priority, - int signal_number) = 0; -#endif /* (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) */ - -protected: - /// Do-nothing constructor. - ACE_Asynch_Read_Stream_Impl (void); -}; - -/** - * @class ACE_Asynch_Read_Stream_Result_Impl - * - * @brief Abstract base class for all the concrete implementation - * classes that provide different implementations for the - * ACE_Asynch_Read_Stream::Result class. - * - */ -class ACE_Export ACE_Asynch_Read_Stream_Result_Impl : public virtual ACE_Asynch_Result_Impl -{ -public: - virtual ~ACE_Asynch_Read_Stream_Result_Impl (void); - - /// The number of bytes which were requested at the start of the - /// asynchronous read. - virtual size_t bytes_to_read (void) const = 0; - - /// Message block which contains the read data. - virtual ACE_Message_Block &message_block (void) const = 0; - - /// I/O handle used for reading. - virtual ACE_HANDLE handle (void) const = 0; - -protected: - /// Do-nothing constructor. - ACE_Asynch_Read_Stream_Result_Impl (void); -}; - -/** - * @class ACE_Asynch_Write_Stream_Impl - * - * @brief Abstract base class for all the concrete implementation - * classes that provide different implementations for the - * ACE_Asynch_Write_Stream class. - * - */ -class ACE_Export ACE_Asynch_Write_Stream_Impl : public virtual ACE_Asynch_Operation_Impl -{ -public: - virtual ~ACE_Asynch_Write_Stream_Impl (void); - - /// This starts off an asynchronous write. Upto @a bytes_to_write - /// will be written from the @a message_block. - virtual int write (ACE_Message_Block &message_block, - size_t bytes_to_write, - const void *act, - int priority, - int signal_number) = 0; - -#if (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) - /** - * Same as above but with gather support, through chaining of composite - * message blocks using the continuation field. - */ - virtual int writev (ACE_Message_Block &message_block, - size_t bytes_to_write, - const void *act, - int priority, - int signal_number) = 0; -#endif /* (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) */ - -protected: - /// Do-nothing constructor. - ACE_Asynch_Write_Stream_Impl (void); -}; - -/** - * @class ACE_Asynch_Write_Stream_Result_Impl - * - * @brief Abstract base class for all the concrete implementation - * classes that provide different implementations for the - * ACE_Asynch_Write_Stream::Result. - * - */ -class ACE_Export ACE_Asynch_Write_Stream_Result_Impl : public virtual ACE_Asynch_Result_Impl -{ -public: - virtual ~ACE_Asynch_Write_Stream_Result_Impl (void); - - /// The number of bytes which were requested at the start of the - /// asynchronous write. - virtual size_t bytes_to_write (void) const = 0; - - /// Message block that contains the data to be written. - virtual ACE_Message_Block &message_block (void) const = 0; - - /// I/O handle used for writing. - virtual ACE_HANDLE handle (void) const = 0; - -protected: - /// Do-nothing constructor. - ACE_Asynch_Write_Stream_Result_Impl (void); -}; - -/** - * @class ACE_Asynch_Read_File_Impl - * - * @brief Abstract base class for all the concrete implementation - * classes that provide different implementations for the - * ACE_Asynch_Read_File::Result. - * - */ -class ACE_Export ACE_Asynch_Read_File_Impl : public virtual ACE_Asynch_Read_Stream_Impl -{ -public: - virtual ~ACE_Asynch_Read_File_Impl (void); - - /** - * This starts off an asynchronous read. Upto @a bytes_to_read will - * be read and stored in the @a message_block. The read will start - * at @a offset from the beginning of the file. - */ - virtual int read (ACE_Message_Block &message_block, - size_t bytes_to_read, - u_long offset, - u_long offset_high, - const void *act, - int priority, - int signal_number) = 0; - -#if (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) - /** - * Same as above but with scatter support, through chaining of composite - * message blocks using the continuation field. - * @note In win32 Each data block payload must be at least the size of a system - * memory page and must be aligned on a system memory page size boundary - */ - virtual int readv (ACE_Message_Block &message_block, - size_t bytes_to_read, - u_long offset, - u_long offset_high, - const void *act, - int priority, - int signal_number) = 0; -#endif /* (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) */ - - /// This starts off an asynchronous read. Upto @a bytes_to_read will - /// be read and stored in the @a message_block. - virtual int read (ACE_Message_Block &message_block, - size_t bytes_to_read, - const void *act, - int priority, - int signal_number) = 0; - -#if (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) - /** - * Same as above but with scatter support, through chaining of composite - * message blocks using the continuation field. - */ - virtual int readv (ACE_Message_Block &message_block, - size_t bytes_to_read, - const void *act, - int priority, - int signal_number) = 0; -#endif /* (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) */ - -protected: - /// Do-nothing constructor. - ACE_Asynch_Read_File_Impl (void); -}; - -/** - * @class ACE_Asynch_Read_File_Result_Impl - * - * @brief This is the abstract base class for all the concrete - * implementation classes for ACE_Asynch_Read_File::Result. - * - */ -class ACE_Export ACE_Asynch_Read_File_Result_Impl : public virtual ACE_Asynch_Read_Stream_Result_Impl -{ -public: - /// Destructor. - virtual ~ACE_Asynch_Read_File_Result_Impl (void); - -protected: - /// Do-nothing constructor. - ACE_Asynch_Read_File_Result_Impl (void); -}; - -/** - * @class ACE_Asynch_Write_File_Impl - * - * @brief Abstract base class for all the concrete implementation - * classes that provide different implementations for the - * ACE_Asynch_Write_File. - * - */ -class ACE_Export ACE_Asynch_Write_File_Impl : public virtual ACE_Asynch_Write_Stream_Impl -{ -public: - virtual ~ACE_Asynch_Write_File_Impl (void); - - /** - * This starts off an asynchronous write. Upto @a bytes_to_write - * will be write and stored in the @a message_block. The write will - * start at @a offset from the beginning of the file. - */ - virtual int write (ACE_Message_Block &message_block, - size_t bytes_to_write, - u_long offset, - u_long offset_high, - const void *act, - int priority, - int signal_number) = 0; - -#if (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) - /** - * Same as above but with gather support, through chaining of composite - * message blocks using the continuation field. - * @note In win32 Each data block payload must be at least the size of a system - * memory page and must be aligned on a system memory page size boundary - */ - virtual int writev (ACE_Message_Block &message_block, - size_t bytes_to_write, - u_long offset, - u_long offset_high, - const void *act, - int priority, - int signal_number) = 0; -#endif /* (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) */ - - /// This starts off an asynchronous write. Upto @a bytes_to_write - /// will be written from the @a message_block. - virtual int write (ACE_Message_Block &message_block, - size_t bytes_to_write, - const void *act, - int priority, - int signal_number) = 0; - -#if (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) - /** - * Same as above but with gather support, through chaining of composite - * message blocks using the continuation field. - */ - virtual int writev (ACE_Message_Block &message_block, - size_t bytes_to_write, - const void *act, - int priority, - int signal_number) = 0; -#endif /* (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) */ - -protected: - /// Do-nothing constructor. - ACE_Asynch_Write_File_Impl (void); -}; - -/** - * @class ACE_Asynch_Write_File_Result_Impl - * - * @brief This is the abstract base class for all the concrete - * implementation classes that provide different implementations - * for the ACE_Asynch_Write_File::Result. - * - */ -class ACE_Export ACE_Asynch_Write_File_Result_Impl : public virtual ACE_Asynch_Write_Stream_Result_Impl -{ -public: - virtual ~ACE_Asynch_Write_File_Result_Impl (void); - -protected: - /// Do-nothing constructor. - ACE_Asynch_Write_File_Result_Impl (void); -}; - -/** - * @class ACE_Asynch_Accept_Impl - * - * @brief Abstract base class for all the concrete implementation - * classes that provide different implementations for the - * ACE_Asynch_Accept. - * - */ -class ACE_Export ACE_Asynch_Accept_Impl : public virtual ACE_Asynch_Operation_Impl -{ -public: - virtual ~ACE_Asynch_Accept_Impl (void); - - /** - * This starts off an asynchronous accept. The asynchronous accept - * call also allows any initial data to be returned to the - * . Upto @a bytes_to_read will be read and stored in the - * @a message_block. The @a accept_handle will be used for the - * call. If (@a accept_handle == INVALID_HANDLE), a new - * handle will be created. - * - * @a message_block must be specified. This is because the address of - * the new connection is placed at the end of this buffer. - */ - virtual int accept (ACE_Message_Block &message_block, - size_t bytes_to_read, - ACE_HANDLE accept_handle, - const void *act, - int priority, - int signal_number, - int addr_family) = 0; - -protected: - /// Do-nothing constructor. - ACE_Asynch_Accept_Impl (void); -}; - -/** - * @class ACE_Asynch_Accept_Result_Impl - * - * @brief Abstract base class for all the concrete implementation - * classes that provide different implementations for the - * ACE_Asynch_Accept. - * - */ -class ACE_Export ACE_Asynch_Accept_Result_Impl : public virtual ACE_Asynch_Result_Impl -{ -public: - virtual ~ACE_Asynch_Accept_Result_Impl (void); - - /// The number of bytes which were requested at the start of the - /// asynchronous accept. - virtual size_t bytes_to_read (void) const = 0; - - /// Message block which contains the read data. - virtual ACE_Message_Block &message_block (void) const = 0; - - /// I/O handle used for accepting new connections. - virtual ACE_HANDLE listen_handle (void) const = 0; - - /// I/O handle for the new connection. - virtual ACE_HANDLE accept_handle (void) const = 0; - -protected: - /// Do-nothing constructor. - ACE_Asynch_Accept_Result_Impl (void); -}; - - -/** - * @class ACE_Asynch_Connect_Impl - * - * @brief Abstract base class for all the concrete implementation - * classes that provide different implementations for the - * ACE_Asynch_Connect. - * - */ -class ACE_Export ACE_Asynch_Connect_Impl : public virtual ACE_Asynch_Operation_Impl -{ -public: - virtual ~ACE_Asynch_Connect_Impl (void); - - /** - * This starts off an asynchronous connect - */ - virtual int connect (ACE_HANDLE connect_handle, - const ACE_Addr & remote_sap, - const ACE_Addr & local_sap, - int reuse_addr, - const void *act, - int priority, - int signal_number) = 0; - -protected: - /// Do-nothing constructor. - ACE_Asynch_Connect_Impl (void); -}; - -/** - * @class ACE_Asynch_Connect_Result_Impl - * - * @brief Abstract base class for all the concrete implementation - * classes that provide different implementations for the - * ACE_Asynch_Connect. - * - */ -class ACE_Export ACE_Asynch_Connect_Result_Impl : public virtual ACE_Asynch_Result_Impl -{ -public: - virtual ~ACE_Asynch_Connect_Result_Impl (void); - - /// I/O handle for the connection. - virtual ACE_HANDLE connect_handle (void) const = 0; - -protected: - /// Do-nothing constructor. - ACE_Asynch_Connect_Result_Impl (void); -}; - - -/** - * @class ACE_Asynch_Transmit_File_Impl - * - * @brief Abstract base class for all the concrete implementation - * classes that provide different implementations for the - * ACE_Asynch_Transmit_File. - * - */ -class ACE_Asynch_Transmit_File_Impl : public virtual ACE_Asynch_Operation_Impl -{ -public: - virtual ~ACE_Asynch_Transmit_File_Impl (void); - - /// This starts off an asynchronous transmit file. - virtual int transmit_file (ACE_HANDLE file, - ACE_Asynch_Transmit_File::Header_And_Trailer *header_and_trailer, - size_t bytes_to_write, - u_long offset, - u_long offset_high, - size_t bytes_per_send, - u_long flags, - const void *act, - int priority, - int signal_number) = 0; - -protected: - /// Do-nothing constructor. - ACE_Asynch_Transmit_File_Impl (void); -}; - -/** - * @class ACE_Asynch_Transmit_File_Result_Impl - * - * @brief Abstract base class for all the concrete implementation - * classes that provide different implementations for the - * ACE_Asynch_Transmit_File::Result. - * - */ -class ACE_Export ACE_Asynch_Transmit_File_Result_Impl : public virtual ACE_Asynch_Result_Impl -{ -public: - virtual ~ACE_Asynch_Transmit_File_Result_Impl (void); - - /// Socket used for transmitting the file. - virtual ACE_HANDLE socket (void) const = 0; - - /// File from which the data is read. - virtual ACE_HANDLE file (void) const = 0; - - /// Header and trailer data associated with this transmit file. - virtual ACE_Asynch_Transmit_File::Header_And_Trailer *header_and_trailer (void) const = 0; - - /// The number of bytes which were requested at the start of the - /// asynchronous transmit file. - virtual size_t bytes_to_write (void) const = 0; - - /// Number of bytes per send requested at the start of the transmit - /// file. - virtual size_t bytes_per_send (void) const = 0; - - /// Flags which were passed into transmit file. - virtual u_long flags (void) const = 0; - -protected: - /// Do-nothing constructor. - ACE_Asynch_Transmit_File_Result_Impl (void); -}; - - -/** - * @class ACE_Asynch_Read_Dgram_Impl - * - * @brief Abstract base class for all the concrete implementation - * classes that provide different implementations for the - * ACE_Asynch_Read_Dgram - * - */ -class ACE_Export ACE_Asynch_Read_Dgram_Impl : public virtual ACE_Asynch_Operation_Impl -{ -public: - virtual ~ACE_Asynch_Read_Dgram_Impl (void); - - /** This starts off an asynchronous read. Upto - * total_size()> will be read and stored in the - * @a message_block. @a message_block's will be updated to reflect - * the added bytes if the read operation is successful completed. - * Return code of 1 means immediate success and - * will contain number of bytes read. The - * method will still be called. Return code of 0 means the IO will - * complete proactively. Return code of -1 means there was an error, use - * errno to get the error code. - * - * Scatter/gather is supported on WIN32 by using the cont()> - * method. Up to ACE_IOV_MAX @a message_block's are supported. Upto - * size()> bytes will be read into each for - * a total of total_size()> bytes. All @a message_block's - * 's will be updated to reflect the added bytes for each - * @a message_block - * - * Priority of the operation is specified by @a priority. On POSIX4-Unix, - * this is supported. Works like in Unix. Negative values are not - * allowed. 0 means priority of the operation same as the process - * priority. 1 means priority of the operation is one less than - * process. And so forth. On Win32, @a priority is a no-op. - * @a signal_number is the POSIX4 real-time signal number to be used - * for the operation. @a signal_number ranges from ACE_SIGRTMIN to - * ACE_SIGRTMAX. This argument is a no-op on non-POSIX4 systems. - */ - virtual ssize_t recv (ACE_Message_Block *message_block, - size_t &number_of_bytes_recvd, - int flags, - int protocol_family, - const void *act, - int priority, - int signal_number) = 0; - -protected: - /// Do-nothing constructor. - ACE_Asynch_Read_Dgram_Impl (void); -}; - -/** - * @class ACE_Asynch_Read_Dgram_Result_Impl - * - * @brief Abstract base class for all the concrete implementation - * classes that provide different implementations for the - * ACE_Asynch_Read_Dgram::Result class. - * - */ -class ACE_Export ACE_Asynch_Read_Dgram_Result_Impl : public virtual ACE_Asynch_Result_Impl -{ -public: - virtual ~ACE_Asynch_Read_Dgram_Result_Impl (void); - - /// Message block which contains the read data - virtual ACE_Message_Block *message_block (void) const = 0; - - /// The number of bytes which were requested at the start of the - /// asynchronous read. - virtual size_t bytes_to_read (void) const = 0; - - /// The address of where the packet came from - virtual int remote_address (ACE_Addr& addr) const = 0; - - /// The flags used in the read - virtual int flags (void) const = 0; - - /// I/O handle used for reading. - virtual ACE_HANDLE handle (void) const = 0; - -protected: - /// Do-nothing constructor. - ACE_Asynch_Read_Dgram_Result_Impl (void); -}; - -/** - * @class ACE_Asynch_Write_Dgram_Impl - * - * @brief Abstract base class for all the concrete implementation - * classes that provide different implementations for the - * ACE_Asynch_Write_Dgram class. - * - */ -class ACE_Export ACE_Asynch_Write_Dgram_Impl : public virtual ACE_Asynch_Operation_Impl -{ -public: - virtual ~ACE_Asynch_Write_Dgram_Impl (void); - - /** This starts off an asynchronous send. Upto - * total_length()> will be sent. @a message_block's - * will be updated to reflect the sent bytes if the send operation - * is successful completed. - * Return code of 1 means immediate success and - * is updated to number of bytes sent. The - * method will still be called. Return code of 0 means the IO will - * complete proactively. Return code of -1 means there was an error, use - * errno to get the error code. - * - * Scatter/gather is supported on WIN32 by using the cont()> - * method. Up to ACE_IOV_MAX @a message_block's are supported. Upto - * length()> bytes will be sent from each - * for a total of total_length()> bytes. All - * @a message_block's 's will be updated to reflect the bytes sent - * from each @a message_block. - * - * Priority of the operation is specified by @a priority. On POSIX4-Unix, - * this is supported. Works like in Unix. Negative values are not - * allowed. 0 means priority of the operation same as the process - * priority. 1 means priority of the operation is one less than - * process. And so forth. On Win32, this argument is a no-op. - * @a signal_number is the POSIX4 real-time signal number to be used - * for the operation. @a signal_number ranges from ACE_SIGRTMIN to - * ACE_SIGRTMAX. This argument is a no-op on non-POSIX4 systems. - */ - virtual ssize_t send (ACE_Message_Block *message_block, - size_t &number_of_bytes_sent, - int flags, - const ACE_Addr &addr, - const void *act, - int priority, - int signal_number) = 0; - -protected: - /// Do-nothing constructor. - ACE_Asynch_Write_Dgram_Impl (void); -}; - -/** - * @class ACE_Asynch_Write_Dgram_Result_Impl - * - * @brief Abstract base class for all the concrete implementation - * classes that provide different implementations for the - * ACE_Asynch_Write_Dgram::Result class. - * - */ -class ACE_Export ACE_Asynch_Write_Dgram_Result_Impl : public virtual ACE_Asynch_Result_Impl -{ -public: - virtual ~ACE_Asynch_Write_Dgram_Result_Impl (void); - - /// The number of bytes which were requested at the start of the - /// asynchronous write. - virtual size_t bytes_to_write (void) const = 0; - - /// Message block which contains the sent data - virtual ACE_Message_Block *message_block (void) const = 0; - - /// The flags using in the write - virtual int flags (void) const = 0; - - /// I/O handle used for writing. - virtual ACE_HANDLE handle (void) const = 0; - -protected: - /// Do-nothing constructor. - ACE_Asynch_Write_Dgram_Result_Impl (void); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Asynch_IO_Impl.inl" -#endif /* __ACE_INLINE__ */ - -#endif /* ACE_HAS_WIN32_OVERLAPPED_IO || ACE_HAS_AIO_CALLS */ -#include /**/ "ace/post.h" -#endif /* ACE_ASYNCH_IO_IMPL_H */ diff --git a/externals/ace/Asynch_IO_Impl.inl b/externals/ace/Asynch_IO_Impl.inl deleted file mode 100644 index 60dc69dfb31..00000000000 --- a/externals/ace/Asynch_IO_Impl.inl +++ /dev/null @@ -1,106 +0,0 @@ -// -*- C++ -*- -// -// $Id: Asynch_IO_Impl.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE -ACE_Asynch_Result_Impl::ACE_Asynch_Result_Impl (void) -{ -} - -ACE_INLINE -ACE_Asynch_Operation_Impl::ACE_Asynch_Operation_Impl (void) -{ -} - -ACE_INLINE -ACE_Asynch_Read_Stream_Impl::ACE_Asynch_Read_Stream_Impl (void) - : ACE_Asynch_Operation_Impl () -{ -} - -ACE_INLINE -ACE_Asynch_Read_Stream_Result_Impl::ACE_Asynch_Read_Stream_Result_Impl (void) - : ACE_Asynch_Result_Impl () -{ -} - -ACE_INLINE -ACE_Asynch_Write_Stream_Impl::ACE_Asynch_Write_Stream_Impl (void) - : ACE_Asynch_Operation_Impl () -{ -} - -ACE_INLINE -ACE_Asynch_Write_Stream_Result_Impl::ACE_Asynch_Write_Stream_Result_Impl (void) - : ACE_Asynch_Result_Impl () -{ -} - -ACE_INLINE -ACE_Asynch_Read_File_Impl::ACE_Asynch_Read_File_Impl (void) - : ACE_Asynch_Operation_Impl (), - ACE_Asynch_Read_Stream_Impl () -{ -} - -ACE_INLINE -ACE_Asynch_Read_File_Result_Impl::ACE_Asynch_Read_File_Result_Impl (void) - : ACE_Asynch_Result_Impl (), - ACE_Asynch_Read_Stream_Result_Impl () -{ -} - -ACE_INLINE -ACE_Asynch_Write_File_Impl::ACE_Asynch_Write_File_Impl (void) - : ACE_Asynch_Operation_Impl (), - ACE_Asynch_Write_Stream_Impl () -{ -} - -ACE_INLINE -ACE_Asynch_Write_File_Result_Impl::ACE_Asynch_Write_File_Result_Impl (void) - : ACE_Asynch_Result_Impl (), - ACE_Asynch_Write_Stream_Result_Impl () -{ -} - -ACE_INLINE -ACE_Asynch_Accept_Impl::ACE_Asynch_Accept_Impl (void) - : ACE_Asynch_Operation_Impl () -{ -} - -ACE_INLINE -ACE_Asynch_Accept_Result_Impl::ACE_Asynch_Accept_Result_Impl (void) - : ACE_Asynch_Result_Impl () -{ -} - -ACE_INLINE -ACE_Asynch_Connect_Impl::ACE_Asynch_Connect_Impl (void) - : ACE_Asynch_Operation_Impl () -{ -} - -ACE_INLINE -ACE_Asynch_Connect_Result_Impl::ACE_Asynch_Connect_Result_Impl (void) - : ACE_Asynch_Result_Impl () -{ -} - - -ACE_INLINE -ACE_Asynch_Transmit_File_Impl::ACE_Asynch_Transmit_File_Impl (void) - : ACE_Asynch_Operation_Impl () -{ -} - -ACE_INLINE -ACE_Asynch_Transmit_File_Result_Impl::ACE_Asynch_Transmit_File_Result_Impl (void) - : ACE_Asynch_Result_Impl () -{ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Asynch_Pseudo_Task.cpp b/externals/ace/Asynch_Pseudo_Task.cpp deleted file mode 100644 index 94f0d6980ed..00000000000 --- a/externals/ace/Asynch_Pseudo_Task.cpp +++ /dev/null @@ -1,130 +0,0 @@ -// $Id: Asynch_Pseudo_Task.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Asynch_Pseudo_Task.h" - -#include "ace/OS_NS_errno.h" -#include "ace/OS_NS_signal.h" - -ACE_RCSID(ace, Asynch_Pseudo_Task, "$Id: Asynch_Pseudo_Task.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_Asynch_Pseudo_Task::ACE_Asynch_Pseudo_Task () - : select_reactor_ (), // should be initialized before reactor_ - reactor_ (&select_reactor_, 0) // don't delete implementation -{ -} - -ACE_Asynch_Pseudo_Task::~ACE_Asynch_Pseudo_Task () -{ - this->stop (); -} - -int -ACE_Asynch_Pseudo_Task::start (void) -{ - if (this->reactor_.initialized () == 0) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("%N:%l:%p\n"), - ACE_TEXT ("start reactor is not initialized")), - -1); - - return this->activate () == -1 ? -1 : 0; // If started, return 0 -} - -int -ACE_Asynch_Pseudo_Task::stop (void) -{ - if (this->thr_count () == 0) // already stopped - return 0; - - if (this->reactor_.end_reactor_event_loop () == -1) - return -1; - - this->wait (); - this->reactor_.close (); - return 0; -} - -int -ACE_Asynch_Pseudo_Task::svc (void) -{ -#if !defined (ACE_WIN32) - - sigset_t RT_signals; - - sigemptyset (&RT_signals); - for (int si = ACE_SIGRTMIN; si <= ACE_SIGRTMAX; si++) - sigaddset (&RT_signals, si); - - if (ACE_OS::pthread_sigmask (SIG_BLOCK, &RT_signals, 0) != 0) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("Error:(%P | %t):%p\n"), - ACE_TEXT ("pthread_sigmask"))); -#endif - - reactor_.owner (ACE_Thread::self ()); - reactor_.run_reactor_event_loop (); - - return 0; -} - - - -int -ACE_Asynch_Pseudo_Task::register_io_handler (ACE_HANDLE handle, - ACE_Event_Handler *handler, - ACE_Reactor_Mask mask, - int flg_suspend) -{ - // Register the handler with the reactor. - if (-1 == this->reactor_.register_handler (handle, handler, mask)) - return -1; - - if (flg_suspend == 0) - return 0; - - // Suspend the handle now. Enable only when the accept is issued - // by the application. - if (this->reactor_.suspend_handler (handle) == -1) - { - ACE_ERROR - ((LM_ERROR, - ACE_TEXT ("%N:%l:%p\n"), - ACE_TEXT ("register_io_handler (suspended)"))); - this->reactor_.remove_handler (handle, ACE_Event_Handler::ALL_EVENTS_MASK - | ACE_Event_Handler::DONT_CALL); - return -1; - } - - return 0; -} - -int -ACE_Asynch_Pseudo_Task::remove_io_handler (ACE_HANDLE handle) -{ - return this->reactor_.remove_handler (handle, - ACE_Event_Handler::ALL_EVENTS_MASK - | ACE_Event_Handler::DONT_CALL); -} - -int -ACE_Asynch_Pseudo_Task::remove_io_handler (ACE_Handle_Set &set) -{ - return this->reactor_.remove_handler (set, ACE_Event_Handler::ALL_EVENTS_MASK - | ACE_Event_Handler::DONT_CALL); -} - -int -ACE_Asynch_Pseudo_Task::suspend_io_handler (ACE_HANDLE handle) -{ - return this->reactor_.suspend_handler (handle); -} - -int -ACE_Asynch_Pseudo_Task::resume_io_handler (ACE_HANDLE handle) -{ - return this->reactor_.resume_handler (handle); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Asynch_Pseudo_Task.h b/externals/ace/Asynch_Pseudo_Task.h deleted file mode 100644 index 6e2c3a1d427..00000000000 --- a/externals/ace/Asynch_Pseudo_Task.h +++ /dev/null @@ -1,73 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Asynch_Pseudo_Task.h - * - * $Id: Asynch_Pseudo_Task.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Alexander Libman - */ -//============================================================================= - -#ifndef ACE_ASYNCH_PSEUDO_TASK_H -#define ACE_ASYNCH_PSEUDO_TASK_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -#pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Reactor.h" -#include "ace/Select_Reactor.h" -#include "ace/Task.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/* - * Specialization hook to replace the Reactor with the - * concrete Reactor implementation, e.g., select_st, - * select_mt etc. - */ -//@@ REACTOR_SPL_INCLUDE_FORWARD_DECL_ADD_HOOK - -/** - * @class ACE_Asynch_Pseudo_Task - * - */ -class ACE_Export ACE_Asynch_Pseudo_Task : public ACE_Task -{ -public: - ACE_Asynch_Pseudo_Task(); - virtual ~ACE_Asynch_Pseudo_Task(); - - int start (void); - int stop (void); - - int register_io_handler (ACE_HANDLE handle, - ACE_Event_Handler *handler, - ACE_Reactor_Mask mask, - int flg_suspend); - - int remove_io_handler (ACE_HANDLE handle); - int remove_io_handler (ACE_Handle_Set &set); - int resume_io_handler (ACE_HANDLE handle); - int suspend_io_handler (ACE_HANDLE handle); - -protected: - virtual int svc (void); - - /// Should be initialized before reactor_ - ACE_Select_Reactor select_reactor_; - - ACE_Reactor reactor_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" - -#endif /* ACE_ASYNCH_PSEUDO_TASK_H */ diff --git a/externals/ace/Atomic_Op.cpp b/externals/ace/Atomic_Op.cpp deleted file mode 100644 index 10731e3c396..00000000000 --- a/externals/ace/Atomic_Op.cpp +++ /dev/null @@ -1,310 +0,0 @@ -// $Id: Atomic_Op.cpp 89905 2010-04-16 13:04:47Z johnnyw $ - -#include "ace/Atomic_Op.h" -#include "ace/OS_NS_unistd.h" - -ACE_RCSID (ace, - Atomic_Op, - "$Id: Atomic_Op.cpp 89905 2010-04-16 13:04:47Z johnnyw $") - -#if !defined (__ACE_INLINE__) -#include "ace/Atomic_Op.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_HAS_BUILTIN_ATOMIC_OP) - -#if defined (ACE_INCLUDE_ATOMIC_OP_SPARC) -# include "ace/Atomic_Op_Sparc.h" -#endif /* ACE_INCLUDE_ATOMIC_OP_SPARC */ - -namespace { - -#if defined (_MSC_VER) -// Disable "no return value" warning, as we will be putting -// the return values directly into the EAX register. -#pragma warning (push) -#pragma warning (disable: 4035) -#endif /* _MSC_VER */ - -long -single_cpu_increment (volatile long *value) -{ -#if defined (ACE_HAS_INTEL_ASSEMBLY) - long tmp = 1; - unsigned long addr = reinterpret_cast (value); - asm( "xadd %0, (%1)" : "+r"(tmp) : "r"(addr) ); - return tmp + 1; -#elif !defined (ACE_HAS_SOLARIS_ATOMIC_LIB) && (defined (sun) || \ - (defined (__SUNPRO_CC) && (defined (__i386) || defined (__x86_64)))) - return ace_atomic_add_long ( - reinterpret_cast (value), 1); -#elif defined(__GNUC__) && defined(PPC) - long tmp; - asm("lwz %0,%1" : "=r" (tmp) : "m" (*value) ); - asm("addi %0,%0,1" : "+r" (tmp) ); - asm("stw %0,%1" : "+r" (tmp), "=m" (*value) ); - return tmp; -#else /* ACE_HAS_INTEL_ASSEMBLY*/ - ACE_UNUSED_ARG (value); - ACE_NOTSUP_RETURN (-1); -#endif /* ACE_HAS_INTEL_ASSEMBLY*/ -} - -long -single_cpu_decrement (volatile long *value) -{ -#if defined (ACE_HAS_INTEL_ASSEMBLY) - long tmp = -1; - unsigned long addr = reinterpret_cast (value); - asm( "xadd %0, (%1)" : "+r"(tmp) : "r"(addr) ); - return tmp - 1; -#elif !defined (ACE_HAS_SOLARIS_ATOMIC_LIB) && (defined (sun) || \ - (defined (__SUNPRO_CC) && (defined (__i386) || defined (__x86_64)))) - return ace_atomic_add_long ( - reinterpret_cast (value), -1); -#elif defined(__GNUC__) && defined(PPC) - long tmp; - asm("lwz %0,%1" : "=r" (tmp) : "m" (*value) ); - asm("addi %0,%0,-1" : "+r" (tmp) ); - asm("stw %0,%1" : "+r" (tmp), "=m" (*value) ); - return tmp; -#else /* ACE_HAS_INTEL_ASSEMBLY*/ - ACE_UNUSED_ARG (value); - ACE_NOTSUP_RETURN (-1); -#endif /* ACE_HAS_INTEL_ASSEMBLY*/ -} - -long -single_cpu_exchange (volatile long *value, long rhs) -{ -#if defined (ACE_HAS_INTEL_ASSEMBLY) - unsigned long addr = reinterpret_cast (value); - asm( "xchg %0, (%1)" : "+r"(rhs) : "r"(addr) ); - return rhs; -#elif !defined (ACE_HAS_SOLARIS_ATOMIC_LIB) && (defined (sun) || \ - (defined (__SUNPRO_CC) && (defined (__i386) || defined (__x86_64)))) - return ace_atomic_swap_long ( - reinterpret_cast (value), rhs); -#elif defined(__GNUC__) && defined(PPC) - long tmp; - asm("lwz %0,%1" : "=r" (tmp) : "m" (rhs) ); - asm("stw %0,%1" : "+r" (tmp), "=m" (*value) ); - return tmp; -#else /* ACE_HAS_INTEL_ASSEMBLY*/ - ACE_UNUSED_ARG (value); - ACE_UNUSED_ARG (rhs); - ACE_NOTSUP_RETURN (-1); -#endif /* ACE_HAS_INTEL_ASSEMBLY*/ -} - -long -single_cpu_exchange_add (volatile long *value, long rhs) -{ -#if defined (ACE_HAS_INTEL_ASSEMBLY) - unsigned long addr = reinterpret_cast (value); - asm( "xadd %0, (%1)" : "+r"(rhs) : "r"(addr) ); - return rhs; -#elif !defined (ACE_HAS_SOLARIS_ATOMIC_LIB) && (defined (sun) || \ - (defined (__SUNPRO_CC) && (defined (__i386) || defined (__x86_64)))) - return ace_atomic_swap_add_long ( - reinterpret_cast (value), rhs); -#elif defined(__GNUC__) && defined(PPC) - long tmp; - asm("add %0,%1,%2" : "=r" (tmp) : "r" (*value), "r" (rhs) ); - asm("stw %0,%1" : "+r" (tmp), "=m" (*value) ); - return tmp; -#elif defined (WIN32) && !defined (ACE_HAS_INTERLOCKED_EXCHANGEADD) -# if defined (_MSC_VER) - __asm - { - mov eax, rhs - mov edx, value - xadd [edx], eax - } - // Return value is already in EAX register. -# elif defined (__BORLANDC__) - _EAX = rhs; - _EDX = reinterpret_cast (value); - __emit__(0x0F, 0xC1, 0x02); // xadd [edx], eax - // Return value is already in EAX register. -# else /* _MSC_VER */ - ACE_UNUSED_ARG (value); - ACE_UNUSED_ARG (rhs); - ACE_NOTSUP_RETURN (-1); -# endif /* _MSC_VER */ -#else /* ACE_HAS_INTEL_ASSEMBLY*/ - ACE_UNUSED_ARG (value); - ACE_UNUSED_ARG (rhs); - ACE_NOTSUP_RETURN (-1); -#endif /* ACE_HAS_INTEL_ASSEMBLY*/ -} - -long -multi_cpu_increment (volatile long *value) -{ -#if defined (ACE_HAS_INTEL_ASSEMBLY) - long tmp = 1; - unsigned long addr = reinterpret_cast (value); - asm( "lock ; xadd %0, (%1)" : "+r"(tmp) : "r"(addr) ); - return tmp + 1; -#elif !defined (ACE_HAS_SOLARIS_ATOMIC_LIB) && (defined (sun) || \ - (defined (__SUNPRO_CC) && (defined (__i386) || defined (__x86_64)))) - return ace_atomic_add_long ( - reinterpret_cast (value), 1); -#else /* ACE_HAS_INTEL_ASSEMBLY*/ - ACE_UNUSED_ARG (value); - ACE_NOTSUP_RETURN (-1); -#endif /* ACE_HAS_INTEL_ASSEMBLY*/ -} - -long -multi_cpu_decrement (volatile long *value) -{ -#if defined (ACE_HAS_INTEL_ASSEMBLY) - long tmp = -1; - unsigned long addr = reinterpret_cast (value); - asm( "lock ; xadd %0, (%1)" : "+r"(tmp) : "r"(addr) ); - return tmp - 1; -#elif !defined (ACE_HAS_SOLARIS_ATOMIC_LIB) && (defined (sun) || \ - (defined (__SUNPRO_CC) && (defined (__i386) || defined (__x86_64)))) - return ace_atomic_add_long ( - reinterpret_cast (value), -1); -#else /* ACE_HAS_INTEL_ASSEMBLY*/ - ACE_UNUSED_ARG (value); - ACE_NOTSUP_RETURN (-1); -#endif /* ACE_HAS_INTEL_ASSEMBLY*/ -} - -long -multi_cpu_exchange (volatile long *value, long rhs) -{ -#if defined (ACE_HAS_INTEL_ASSEMBLY) - unsigned long addr = reinterpret_cast (value); - // The XCHG instruction automatically follows LOCK semantics - asm( "xchg %0, (%1)" : "+r"(rhs) : "r"(addr) ); - return rhs; -#elif !defined (ACE_HAS_SOLARIS_ATOMIC_LIB) && (defined (sun) || \ - (defined (__SUNPRO_CC) && (defined (__i386) || defined (__x86_64)))) - return ace_atomic_swap_long ( - reinterpret_cast (value), rhs); -#else /* ACE_HAS_INTEL_ASSEMBLY*/ - ACE_UNUSED_ARG (value); - ACE_UNUSED_ARG (rhs); - ACE_NOTSUP_RETURN (-1); -#endif /* ACE_HAS_INTEL_ASSEMBLY*/ -} - -long -multi_cpu_exchange_add (volatile long *value, long rhs) -{ -#if defined (ACE_HAS_INTEL_ASSEMBLY) - unsigned long addr = reinterpret_cast (value); - asm( "lock ; xadd %0, (%1)" : "+r"(rhs) : "r"(addr) ); - return rhs; -#elif !defined (ACE_HAS_SOLARIS_ATOMIC_LIB) && (defined (sun) || \ - (defined (__SUNPRO_CC) && (defined (__i386) || defined (__x86_64)))) - return ace_atomic_swap_add_long ( - reinterpret_cast (value), rhs); -#elif defined (WIN32) && !defined (ACE_HAS_INTERLOCKED_EXCHANGEADD) -# if defined (_MSC_VER) - __asm - { - mov eax, rhs - mov edx, value - lock xadd [edx], eax - } - // Return value is already in EAX register. -# elif defined (__BORLANDC__) - _EAX = rhs; - _EDX = reinterpret_cast (value); - __emit__(0xF0, 0x0F, 0xC1, 0x02); // lock xadd [edx], eax - // Return value is already in EAX register. -# else /* _MSC_VER */ - ACE_UNUSED_ARG (value); - ACE_UNUSED_ARG (rhs); - ACE_NOTSUP_RETURN (-1); -# endif /* _MSC_VER */ -#else /* ACE_HAS_INTEL_ASSEMBLY*/ - ACE_UNUSED_ARG (value); - ACE_UNUSED_ARG (rhs); - ACE_NOTSUP_RETURN (-1); -#endif /* ACE_HAS_INTEL_ASSEMBLY*/ -} - -#if defined (_MSC_VER) -#pragma warning (pop) -#endif /* _MSC_VER */ - -} // end namespace - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -long (*ACE_Atomic_Op::increment_fn_) (volatile long *) = multi_cpu_increment; -long (*ACE_Atomic_Op::decrement_fn_) (volatile long *) = multi_cpu_decrement; -long (*ACE_Atomic_Op::exchange_fn_) (volatile long *, long) = multi_cpu_exchange; -long (*ACE_Atomic_Op::exchange_add_fn_) (volatile long *, long) = multi_cpu_exchange_add; - -void -ACE_Atomic_Op::init_functions (void) -{ - if (ACE_OS::num_processors () == 1) - { - increment_fn_ = single_cpu_increment; - decrement_fn_ = single_cpu_decrement; - exchange_fn_ = single_cpu_exchange; - exchange_add_fn_ = single_cpu_exchange_add; - } - else - { - increment_fn_ = multi_cpu_increment; - decrement_fn_ = multi_cpu_decrement; - exchange_fn_ = multi_cpu_exchange; - exchange_add_fn_ = multi_cpu_exchange_add; - } -} - -void -ACE_Atomic_Op::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -long (*ACE_Atomic_Op::increment_fn_) (volatile long *) = multi_cpu_increment; -long (*ACE_Atomic_Op::decrement_fn_) (volatile long *) = multi_cpu_decrement; -long (*ACE_Atomic_Op::exchange_fn_) (volatile long *, long) = multi_cpu_exchange; -long (*ACE_Atomic_Op::exchange_add_fn_) (volatile long *, long) = multi_cpu_exchange_add; - -void -ACE_Atomic_Op::init_functions (void) -{ - if (ACE_OS::num_processors () == 1) - { - increment_fn_ = single_cpu_increment; - decrement_fn_ = single_cpu_decrement; - exchange_fn_ = single_cpu_exchange; - exchange_add_fn_ = single_cpu_exchange_add; - } - else - { - increment_fn_ = multi_cpu_increment; - decrement_fn_ = multi_cpu_decrement; - exchange_fn_ = multi_cpu_exchange; - exchange_add_fn_ = multi_cpu_exchange_add; - } -} - -void -ACE_Atomic_Op::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_BUILTIN_ATOMIC_OP */ diff --git a/externals/ace/Atomic_Op.h b/externals/ace/Atomic_Op.h deleted file mode 100644 index 8ebc6c6d8b9..00000000000 --- a/externals/ace/Atomic_Op.h +++ /dev/null @@ -1,355 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Atomic_Op.h - * - * $Id: Atomic_Op.h 89936 2010-04-20 13:04:53Z johnnyw $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_ATOMIC_OP_H -#define ACE_ATOMIC_OP_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Thread_Mutex.h" - -// Include the templates here. -#include "ace/Atomic_Op_T.h" - -// Determine whether builtin atomic op support is -// available on this platform. -#if defined (ACE_HAS_THREADS) -# if defined (WIN32) -# if defined (ACE_HAS_INTRINSIC_INTERLOCKED) -# define ACE_HAS_BUILTIN_ATOMIC_OP -# endif /* ACE_HAS_INTRINSIC_INTERLOCKED */ -# if defined (ACE_HAS_INTERLOCKED_EXCHANGEADD) -# define ACE_HAS_BUILTIN_ATOMIC_OP -# else /* ACE_HAS_INTERLOCKED_EXCHANGEADD */ - // Inline assembly emulation of InterlockedExchangeAdd - // is currently only implemented for MSVC (x86 only) and Borland. -# if (defined (_MSC_VER) && defined (_M_IX86)) || defined (__BORLANDC__) -# define ACE_HAS_BUILTIN_ATOMIC_OP -# endif /* _MSC_VER || __BORLANDC__ */ -# endif /* ACE_HAS_INTERLOCKED_EXCHANGEADD */ -# elif defined (ACE_HAS_INTEL_ASSEMBLY) -# define ACE_HAS_BUILTIN_ATOMIC_OP -# elif defined (ACE_HAS_VXATOMICLIB) -# define ACE_HAS_BUILTIN_ATOMIC_OP -# elif defined (ACE_HAS_SOLARIS_ATOMIC_LIB) && !defined (ACE_HAS_BUILTIN_ATOMIC_OP) -# define ACE_HAS_BUILTIN_ATOMIC_OP -# endif /* WIN32 */ -#endif /* ACE_HAS_THREADS */ - -// If we have the GCC Atomic builtin support, use it -#if defined (ACE_HAS_GCC_ATOMIC_BUILTINS) && (ACE_HAS_GCC_ATOMIC_BUILTINS == 1) -# undef ACE_HAS_BUILTIN_ATOMIC_OP -#endif - -// Include the templates here. -#include "ace/Atomic_Op_GCC_T.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -#if defined (ACE_HAS_BUILTIN_ATOMIC_OP) - -/** - * @brief Specialization of ACE_Atomic_Op for platforms that - * support atomic integer operations. - * - * Specialization of ACE_Atomic_Op for platforms that support atomic - * integer operations. - */ -template<> -class ACE_Export ACE_Atomic_Op -{ -public: - /// Initialize @c value_ to 0. - ACE_Atomic_Op (void); - - /// Initialize @c value_ to c. - ACE_Atomic_Op (long c); - - /// Manage copying... - ACE_Atomic_Op (const ACE_Atomic_Op &c); - - /// Atomically pre-increment @c value_. - long operator++ (void); - - /// Atomically post-increment @c value_. - long operator++ (int); - - /// Atomically increment @c value_ by rhs. - long operator+= (long rhs); - - /// Atomically pre-decrement @c value_. - long operator-- (void); - - /// Atomically post-decrement @c value_. - long operator-- (int); - - /// Atomically decrement @c value_ by rhs. - long operator-= (long rhs); - - /// Atomically compare @c value_ with rhs. - bool operator== (long rhs) const; - - /// Atomically compare @c value_ with rhs. - bool operator!= (long rhs) const; - - /// Atomically check if @c value_ greater than or equal to rhs. - bool operator>= (long rhs) const; - - /// Atomically check if @c value_ greater than rhs. - bool operator> (long rhs) const; - - /// Atomically check if @c value_ less than or equal to rhs. - bool operator<= (long rhs) const; - - /// Atomically check if @c value_ less than rhs. - bool operator< (long rhs) const; - - /// Atomically assign rhs to @c value_. - ACE_Atomic_Op &operator= (long rhs); - - /// Atomically assign to @c value_. - ACE_Atomic_Op &operator= (const ACE_Atomic_Op &rhs); - - /// Explicitly return @c value_. - long value (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Explicitly return @c value_ (by reference). - volatile long &value_i (void); - - // ACE_ALLOC_HOOK_DECLARE; - // Declare the dynamic allocation hooks. - - /// Used during ACE object manager initialization to optimize the fast - /// atomic op implementation according to the number of CPUs. - static void init_functions (void); - -private: - - // This function cannot be supported by this template specialization. - // If you need access to an underlying lock, use the ACE_Atomic_Op_Ex - // template instead. - ACE_Thread_Mutex &mutex (void); - -private: - - /// Current object decorated by the atomic op. - volatile long value_; - - // Pointers to selected atomic op implementations. - static long (*increment_fn_) (volatile long *); - static long (*decrement_fn_) (volatile long *); - static long (*exchange_fn_) (volatile long *, long); - static long (*exchange_add_fn_) (volatile long *, long); -}; - -/** - * @brief Specialization of ACE_Atomic_Op for platforms that - * support atomic integer operations. - * - * Specialization of ACE_Atomic_Op for platforms that support atomic - * integer operations. - */ -template<> -class ACE_Export ACE_Atomic_Op -{ -public: - /// Initialize @c value_ to 0. - ACE_Atomic_Op (void); - - /// Initialize @c value_ to c. - ACE_Atomic_Op (unsigned long c); - - /// Manage copying... - ACE_Atomic_Op (const ACE_Atomic_Op &c); - - /// Atomically pre-increment @c value_. - unsigned long operator++ (void); - - /// Atomically post-increment @c value_. - unsigned long operator++ (int); - - /// Atomically increment @c value_ by rhs. - unsigned long operator+= (unsigned long rhs); - - /// Atomically pre-decrement @c value_. - unsigned long operator-- (void); - - /// Atomically post-decrement @c value_. - unsigned long operator-- (int); - - /// Atomically decrement @c value_ by rhs. - unsigned long operator-= (unsigned long rhs); - - /// Atomically compare @c value_ with rhs. - bool operator== (unsigned long rhs) const; - - /// Atomically compare @c value_ with rhs. - bool operator!= (unsigned long rhs) const; - - /// Atomically check if @c value_ greater than or equal to rhs. - bool operator>= (unsigned long rhs) const; - - /// Atomically check if @c value_ greater than rhs. - bool operator> (unsigned long rhs) const; - - /// Atomically check if @c value_ less than or equal to rhs. - bool operator<= (unsigned long rhs) const; - - /// Atomically check if @c value_ less than rhs. - bool operator< (unsigned long rhs) const; - - /// Atomically assign rhs to @c value_. - ACE_Atomic_Op &operator= (unsigned long rhs); - - /// Atomically assign to @c value_. - ACE_Atomic_Op &operator= (const ACE_Atomic_Op &rhs); - - /// Explicitly return @c value_. - unsigned long value (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Explicitly return @c value_ (by reference). - volatile unsigned long &value_i (void); - - // ACE_ALLOC_HOOK_DECLARE; - // Declare the dynamic allocation hooks. - - /// Used during ACE object manager initialization to optimize the fast - /// atomic op implementation according to the number of CPUs. - static void init_functions (void); - -private: - - /// This function cannot be supported by this template specialization. - /// If you need access to an underlying lock, use the ACE_Atomic_Op_Ex - /// template instead. - ACE_Thread_Mutex &mutex (void); - -private: - - /// Current object decorated by the atomic op. - volatile unsigned long value_; - - // Pointers to selected atomic op implementations. - static long (*increment_fn_) (volatile long *); - static long (*decrement_fn_) (volatile long *); - static long (*exchange_fn_) (volatile long *, long); - static long (*exchange_add_fn_) (volatile long *, long); -}; - -#endif /* !ACE_HAS_BUILTIN_ATOMIC_OP */ - -#if defined (ACE_HAS_GCC_ATOMIC_BUILTINS) && (ACE_HAS_GCC_ATOMIC_BUILTINS == 1) - -template<> -class ACE_Export ACE_Atomic_Op -: public ACE_Atomic_Op_GCC -{ -public: - ACE_Atomic_Op (void); - ACE_Atomic_Op (int c); - ACE_Atomic_Op (const ACE_Atomic_Op &c); - ACE_Atomic_Op &operator= (int rhs); -}; - -template<> -class ACE_Export ACE_Atomic_Op -: public ACE_Atomic_Op_GCC -{ -public: - ACE_Atomic_Op (void); - ACE_Atomic_Op (unsigned int c); - ACE_Atomic_Op (const ACE_Atomic_Op &c); - ACE_Atomic_Op &operator= (unsigned int rhs); -}; - -// If we have built in atomic op, use that, the assignment operator -// is faster for a long/unsinged long -template<> -class ACE_Export ACE_Atomic_Op -: public ACE_Atomic_Op_GCC -{ -public: - ACE_Atomic_Op (void); - ACE_Atomic_Op (long c); - ACE_Atomic_Op (const ACE_Atomic_Op &c); - ACE_Atomic_Op &operator= (long rhs); -}; - -template<> -class ACE_Export ACE_Atomic_Op -: public ACE_Atomic_Op_GCC -{ -public: - ACE_Atomic_Op (void); - ACE_Atomic_Op (unsigned long c); - ACE_Atomic_Op (const ACE_Atomic_Op &c); - ACE_Atomic_Op &operator= (unsigned long rhs); -}; - -#if !defined (ACE_LACKS_GCC_ATOMIC_BUILTINS_2) -template<> -class ACE_Export ACE_Atomic_Op -: public ACE_Atomic_Op_GCC -{ -public: - ACE_Atomic_Op (void); - ACE_Atomic_Op (short c); - ACE_Atomic_Op (const ACE_Atomic_Op &c); - ACE_Atomic_Op &operator= (short rhs); -}; - -template<> -class ACE_Export ACE_Atomic_Op -: public ACE_Atomic_Op_GCC -{ -public: - ACE_Atomic_Op (void); - ACE_Atomic_Op (unsigned short c); - ACE_Atomic_Op (const ACE_Atomic_Op &c); - ACE_Atomic_Op &operator= (unsigned short rhs); -}; -#endif - -#if !defined (ACE_LACKS_GCC_ATOMIC_BUILTINS_1) -template<> -class ACE_Export ACE_Atomic_Op -: public ACE_Atomic_Op_GCC -{ -public: - ACE_Atomic_Op (void); - ACE_Atomic_Op (bool c); - ACE_Atomic_Op (const ACE_Atomic_Op &c); - ACE_Atomic_Op &operator= (bool rhs); -}; -#endif - -#endif /* ACE_HAS_BUILTIN_ATOMIC_OP */ - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Atomic_Op.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /*ACE_ATOMIC_OP_H*/ diff --git a/externals/ace/Atomic_Op.inl b/externals/ace/Atomic_Op.inl deleted file mode 100644 index 6dcade6c04d..00000000000 --- a/externals/ace/Atomic_Op.inl +++ /dev/null @@ -1,582 +0,0 @@ -// -*- C++ -*- -// -// $Id: Atomic_Op.inl 89905 2010-04-16 13:04:47Z johnnyw $ - -#if defined (ACE_HAS_INTRINSIC_INTERLOCKED) -# include "ace/os_include/os_intrin.h" -# pragma intrinsic (_InterlockedExchange, _InterlockedExchangeAdd, _InterlockedIncrement, _InterlockedDecrement) -#endif /* ACE_HAS_INTRINSIC_INTERLOCKED */ - -#if defined (ACE_HAS_VXATOMICLIB) -# include -#endif - -#if defined (ACE_HAS_SOLARIS_ATOMIC_LIB) -# include -#endif - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -#if defined (ACE_HAS_BUILTIN_ATOMIC_OP) - -ACE_INLINE -ACE_Atomic_Op::ACE_Atomic_Op (void) - : value_ (0) -{ -} - -ACE_INLINE -ACE_Atomic_Op::ACE_Atomic_Op (long c) - : value_ (c) -{ -} - -ACE_INLINE -ACE_Atomic_Op::ACE_Atomic_Op ( - const ACE_Atomic_Op &rhs) - : value_ (rhs.value_) -{ -} - -ACE_INLINE long -ACE_Atomic_Op::operator++ (void) -{ -#if defined (ACE_HAS_INTRINSIC_INTERLOCKED) - return ::_InterlockedIncrement (const_cast (&this->value_)); -#elif defined (WIN32) - return ::InterlockedIncrement (const_cast (&this->value_)); -#elif defined (ACE_HAS_VXATOMICLIB) - return ::vxAtomicInc (reinterpret_cast (const_cast (&this->value_))) + 1; -#elif defined (ACE_HAS_SOLARIS_ATOMIC_LIB) - return ::atomic_inc_ulong_nv (reinterpret_cast(&this->value_)); -#else /* WIN32 */ - return (*increment_fn_) (&this->value_); -#endif /* WIN32 */ -} - -ACE_INLINE long -ACE_Atomic_Op::operator++ (int) -{ - return ++*this - 1; -} - -ACE_INLINE long -ACE_Atomic_Op::operator-- (void) -{ -#if defined (ACE_HAS_INTRINSIC_INTERLOCKED) - return ::_InterlockedDecrement (const_cast (&this->value_)); -#elif defined (WIN32) - return ::InterlockedDecrement (const_cast (&this->value_)); -#elif defined (ACE_HAS_VXATOMICLIB) - return ::vxAtomicDec (reinterpret_cast (const_cast (&this->value_))) - 1; -#elif defined (ACE_HAS_SOLARIS_ATOMIC_LIB) - return ::atomic_dec_ulong_nv (reinterpret_cast(&this->value_)); -#else /* WIN32 */ - return (*decrement_fn_) (&this->value_); -#endif /* WIN32 */ -} - -ACE_INLINE long -ACE_Atomic_Op::operator-- (int) -{ - return --*this + 1; -} - -ACE_INLINE long -ACE_Atomic_Op::operator+= (long rhs) -{ -#if defined (ACE_HAS_INTRINSIC_INTERLOCKED) - return ::_InterlockedExchangeAdd (const_cast (&this->value_), - rhs) + rhs; -#elif defined (WIN32) && defined (ACE_HAS_INTERLOCKED_EXCHANGEADD) - return ::InterlockedExchangeAdd (const_cast (&this->value_), - rhs) + rhs; -#elif defined (ACE_HAS_VXATOMICLIB) - return ::vxAtomicAdd (reinterpret_cast (const_cast (&this->value_)), rhs) + rhs; -#elif defined (ACE_HAS_SOLARIS_ATOMIC_LIB) - return ::atomic_add_long_nv (reinterpret_cast(&this->value_), rhs); -#else /* WIN32 && ACE_HAS_INTERLOCKED_EXCHANGEADD */ - return (*exchange_add_fn_) (&this->value_, rhs) + rhs; -#endif /* WIN32 && ACE_HAS_INTERLOCKED_EXCHANGEADD */ -} - -ACE_INLINE long -ACE_Atomic_Op::operator-= (long rhs) -{ -#if defined (ACE_HAS_INTRINSIC_INTERLOCKED) - return ::_InterlockedExchangeAdd (const_cast (&this->value_), - -rhs) - rhs; -#elif defined (WIN32) && defined (ACE_HAS_INTERLOCKED_EXCHANGEADD) - return ::InterlockedExchangeAdd (const_cast (&this->value_), - -rhs) - rhs; -#elif defined (ACE_HAS_VXATOMICLIB) - return ::vxAtomicSub (reinterpret_cast (const_cast (&this->value_)), rhs) - rhs; -#elif defined (ACE_HAS_SOLARIS_ATOMIC_LIB) - return ::atomic_add_long_nv (reinterpret_cast(&this->value_), -rhs); -#else /* WIN32 && ACE_HAS_INTERLOCKED_EXCHANGEADD */ - return (*exchange_add_fn_) (&this->value_, -rhs) - rhs; -#endif /* WIN32 && ACE_HAS_INTERLOCKED_EXCHANGEADD */ -} - -ACE_INLINE bool -ACE_Atomic_Op::operator== (long rhs) const -{ - return (this->value_ == rhs); -} - -ACE_INLINE bool -ACE_Atomic_Op::operator!= (long rhs) const -{ - return (this->value_ != rhs); -} - -ACE_INLINE bool -ACE_Atomic_Op::operator>= (long rhs) const -{ - return (this->value_ >= rhs); -} - -ACE_INLINE bool -ACE_Atomic_Op::operator> (long rhs) const -{ - return (this->value_ > rhs); -} - -ACE_INLINE bool -ACE_Atomic_Op::operator<= (long rhs) const -{ - return (this->value_ <= rhs); -} - -ACE_INLINE bool -ACE_Atomic_Op::operator< (long rhs) const -{ - return (this->value_ < rhs); -} - -ACE_INLINE ACE_Atomic_Op & -ACE_Atomic_Op::operator= (long rhs) -{ -#if defined (ACE_HAS_INTRINSIC_INTERLOCKED) - ::_InterlockedExchange (const_cast (&this->value_), rhs); -#elif defined (WIN32) - ::InterlockedExchange (const_cast (&this->value_), rhs); -#elif defined (ACE_HAS_VXATOMICLIB) - ::vxAtomicSet (reinterpret_cast (const_cast (&this->value_)), rhs); -#elif defined (ACE_HAS_SOLARIS_ATOMIC_LIB) - ::atomic_swap_ulong (reinterpret_cast(&this->value_), rhs); -#else /* WIN32 */ - (*exchange_fn_) (&this->value_, rhs); -#endif /* WIN32 */ - return *this; -} - -ACE_INLINE ACE_Atomic_Op & -ACE_Atomic_Op::operator= ( - const ACE_Atomic_Op &rhs) -{ -#if defined (ACE_HAS_INTRINSIC_INTERLOCKED) - ::_InterlockedExchange (const_cast (&this->value_), rhs.value_); -#elif defined (WIN32) - ::InterlockedExchange (const_cast (&this->value_), rhs.value_); -#elif defined (ACE_HAS_VXATOMICLIB) - ::vxAtomicSet (reinterpret_cast (const_cast (&this->value_)), rhs.value_); -#elif defined (ACE_HAS_SOLARIS_ATOMIC_LIB) - ::atomic_swap_ulong (reinterpret_cast(&this->value_), rhs.value_); -#else /* WIN32 */ - (*exchange_fn_) (&this->value_, rhs.value_); -#endif /* WIN32 */ - return *this; -} - -ACE_INLINE long -ACE_Atomic_Op::value (void) const -{ - return this->value_; -} - -ACE_INLINE volatile long & -ACE_Atomic_Op::value_i (void) -{ - return this->value_; -} - - -ACE_INLINE -ACE_Atomic_Op::ACE_Atomic_Op (void) - : value_ (0) -{ -} - -ACE_INLINE -ACE_Atomic_Op::ACE_Atomic_Op (unsigned long c) - : value_ (c) -{ -} - -ACE_INLINE -ACE_Atomic_Op::ACE_Atomic_Op ( - const ACE_Atomic_Op &rhs) - : value_ (rhs.value_) -{ -} - -ACE_INLINE unsigned long -ACE_Atomic_Op::operator++ (void) -{ -#if defined (ACE_HAS_INTRINSIC_INTERLOCKED) - return static_cast (::_InterlockedIncrement (const_cast (reinterpret_cast(&this->value_)))); -#elif defined (WIN32) - return static_cast (::InterlockedIncrement (const_cast (reinterpret_cast(&this->value_)))); -#elif defined (ACE_HAS_VXATOMICLIB) - return static_cast (::vxAtomicInc (reinterpret_cast (const_cast (reinterpret_cast(&this->value_))))) + 1; -#elif defined (ACE_HAS_SOLARIS_ATOMIC_LIB) - return ::atomic_inc_ulong_nv (&this->value_); -#else /* WIN32 */ - return static_cast ((*increment_fn_) (reinterpret_cast (&this->value_))); -#endif /* WIN32 */ -} - -ACE_INLINE unsigned long -ACE_Atomic_Op::operator++ (int) -{ - return ++*this - 1; -} - -ACE_INLINE unsigned long -ACE_Atomic_Op::operator-- (void) -{ -#if defined (ACE_HAS_INTRINSIC_INTERLOCKED) - return static_cast (::_InterlockedDecrement (const_cast (reinterpret_cast(&this->value_)))); -#elif defined (WIN32) - return static_cast (::InterlockedDecrement (const_cast (reinterpret_cast(&this->value_)))); -#elif defined (ACE_HAS_VXATOMICLIB) - return static_cast (::vxAtomicDec (reinterpret_cast (const_cast (reinterpret_cast(&this->value_))))) - 1; -#elif defined (ACE_HAS_SOLARIS_ATOMIC_LIB) - return ::atomic_dec_ulong_nv (&this->value_); -#else /* WIN32 */ - return static_cast ((*decrement_fn_) (reinterpret_cast (&this->value_))); -#endif /* WIN32 */ -} - -ACE_INLINE unsigned long -ACE_Atomic_Op::operator-- (int) -{ - return --*this + 1; -} - -ACE_INLINE unsigned long -ACE_Atomic_Op::operator+= (unsigned long rhs) -{ -#if defined (ACE_HAS_INTRINSIC_INTERLOCKED) - return static_cast (::_InterlockedExchangeAdd (const_cast (reinterpret_cast (&this->value_)), - rhs)) + rhs; -#elif defined (WIN32) && defined (ACE_HAS_INTERLOCKED_EXCHANGEADD) - return static_cast (::InterlockedExchangeAdd (const_cast (reinterpret_cast (&this->value_)), - rhs)) + rhs; -#elif defined (ACE_HAS_VXATOMICLIB) - return static_cast (::vxAtomicAdd (reinterpret_cast (const_cast (reinterpret_cast(&this->value_))), rhs)) + rhs; -#elif defined (ACE_HAS_SOLARIS_ATOMIC_LIB) - return ::atomic_add_long_nv (&this->value_, rhs); -#else /* WIN32 && ACE_HAS_INTERLOCKED_EXCHANGEADD */ - return static_cast ((*exchange_add_fn_) (reinterpret_cast (&this->value_), rhs)) + rhs; -#endif /* WIN32 && ACE_HAS_INTERLOCKED_EXCHANGEADD */ -} - -ACE_INLINE unsigned long -ACE_Atomic_Op::operator-= (unsigned long rhs) -{ -#if defined (ACE_HAS_INTRINSIC_INTERLOCKED) - return static_cast (::_InterlockedExchangeAdd (const_cast (reinterpret_cast(&this->value_)), - -static_cast(rhs))) - rhs; -#elif defined (WIN32) && defined (ACE_HAS_INTERLOCKED_EXCHANGEADD) - return static_cast (::InterlockedExchangeAdd (const_cast (reinterpret_cast(&this->value_)), - -static_cast(rhs))) - rhs; -#elif defined (ACE_HAS_VXATOMICLIB) - return static_cast (::vxAtomicSub (reinterpret_cast (const_cast (reinterpret_cast(&this->value_))), rhs)) - rhs; -#elif defined (ACE_HAS_SOLARIS_ATOMIC_LIB) - return ::atomic_add_long_nv (&this->value_, -rhs); -#else /* WIN32 && ACE_HAS_INTERLOCKED_EXCHANGEADD */ - long l_rhs = static_cast (rhs); - return static_cast ((*exchange_add_fn_) (reinterpret_cast (&this->value_), -l_rhs)) - rhs; -#endif /* WIN32 && ACE_HAS_INTERLOCKED_EXCHANGEADD */ -} - -ACE_INLINE bool -ACE_Atomic_Op::operator== (unsigned long rhs) const -{ - return (this->value_ == rhs); -} - -ACE_INLINE bool -ACE_Atomic_Op::operator!= (unsigned long rhs) const -{ - return (this->value_ != rhs); -} - -ACE_INLINE bool -ACE_Atomic_Op::operator>= (unsigned long rhs) const -{ - return (this->value_ >= rhs); -} - -ACE_INLINE bool -ACE_Atomic_Op::operator> (unsigned long rhs) const -{ - return (this->value_ > rhs); -} - -ACE_INLINE bool -ACE_Atomic_Op::operator<= (unsigned long rhs) const -{ - return (this->value_ <= rhs); -} - -ACE_INLINE bool -ACE_Atomic_Op::operator< (unsigned long rhs) const -{ - return (this->value_ < rhs); -} - -ACE_INLINE ACE_Atomic_Op & -ACE_Atomic_Op::operator= (unsigned long rhs) -{ -#if defined (ACE_HAS_INTRINSIC_INTERLOCKED) - ::_InterlockedExchange (const_cast (reinterpret_cast (&this->value_)), rhs); -#elif defined (WIN32) - ::InterlockedExchange (const_cast (reinterpret_cast (&this->value_)), rhs); -#elif defined (ACE_HAS_VXATOMICLIB) - ::vxAtomicSet (reinterpret_cast (const_cast (reinterpret_cast (&this->value_))), rhs); -#elif defined (ACE_HAS_SOLARIS_ATOMIC_LIB) - ::atomic_swap_ulong (&this->value_, rhs); -#else /* WIN32 */ - (*exchange_fn_) (reinterpret_cast (&this->value_), rhs); -#endif /* WIN32 */ - return *this; -} - -ACE_INLINE ACE_Atomic_Op & -ACE_Atomic_Op::operator= ( - const ACE_Atomic_Op &rhs) -{ -#if defined (ACE_HAS_INTRINSIC_INTERLOCKED) - ::_InterlockedExchange (const_cast (reinterpret_cast (&this->value_)), rhs.value_); -#elif defined (WIN32) - ::InterlockedExchange (const_cast (reinterpret_cast (&this->value_)), rhs.value_); -#elif defined (ACE_HAS_VXATOMICLIB) - ::vxAtomicSet (reinterpret_cast (const_cast (reinterpret_cast (&this->value_))), rhs.value_); -#elif defined (ACE_HAS_SOLARIS_ATOMIC_LIB) - ::atomic_swap_ulong (&this->value_, rhs.value_); -#else /* WIN32 */ - (*exchange_fn_) (reinterpret_cast (&this->value_), rhs.value_); -#endif /* WIN32 */ - return *this; -} - -ACE_INLINE unsigned long -ACE_Atomic_Op::value (void) const -{ - return this->value_; -} - -ACE_INLINE volatile unsigned long & -ACE_Atomic_Op::value_i (void) -{ - return this->value_; -} - -#endif /* ACE_HAS_BUILTIN_ATOMIC_OP */ - -#if defined (ACE_HAS_GCC_ATOMIC_BUILTINS) && (ACE_HAS_GCC_ATOMIC_BUILTINS == 1) - -ACE_INLINE -ACE_Atomic_Op::ACE_Atomic_Op (void) : - ACE_Atomic_Op_GCC () -{ -} - -ACE_INLINE -ACE_Atomic_Op::ACE_Atomic_Op (int c) : - ACE_Atomic_Op_GCC(c) -{ -} - -ACE_INLINE -ACE_Atomic_Op::ACE_Atomic_Op (const ACE_Atomic_Op &c) : - ACE_Atomic_Op_GCC(c) -{ -} - -ACE_INLINE -ACE_Atomic_Op& -ACE_Atomic_Op::operator= (int rhs) -{ - ACE_Atomic_Op_GCC::operator= (rhs); - return *this; -} - - -ACE_INLINE -ACE_Atomic_Op::ACE_Atomic_Op (void) : - ACE_Atomic_Op_GCC() -{ -} - -ACE_INLINE -ACE_Atomic_Op::ACE_Atomic_Op (const ACE_Atomic_Op &c) : - ACE_Atomic_Op_GCC(c) -{ -} - -ACE_INLINE -ACE_Atomic_Op::ACE_Atomic_Op (unsigned int c) : - ACE_Atomic_Op_GCC(c) -{ -} - -ACE_INLINE -ACE_Atomic_Op& -ACE_Atomic_Op::operator= (unsigned int rhs) -{ - ACE_Atomic_Op_GCC::operator= (rhs); - return *this; -} - -ACE_INLINE -ACE_Atomic_Op::ACE_Atomic_Op (void) : - ACE_Atomic_Op_GCC() -{ -} - -ACE_INLINE -ACE_Atomic_Op::ACE_Atomic_Op (long c) : - ACE_Atomic_Op_GCC(c) -{ -} - -ACE_INLINE -ACE_Atomic_Op::ACE_Atomic_Op (const ACE_Atomic_Op &c) : - ACE_Atomic_Op_GCC(c) -{ -} - -ACE_INLINE -ACE_Atomic_Op& -ACE_Atomic_Op::operator= (long rhs) -{ - ACE_Atomic_Op_GCC::operator= (rhs); - return *this; -} - -ACE_INLINE -ACE_Atomic_Op::ACE_Atomic_Op (void) : - ACE_Atomic_Op_GCC () -{ -} - -ACE_INLINE -ACE_Atomic_Op::ACE_Atomic_Op (unsigned long c) : - ACE_Atomic_Op_GCC(c) -{ -} - -ACE_INLINE -ACE_Atomic_Op::ACE_Atomic_Op (const ACE_Atomic_Op &c) : - ACE_Atomic_Op_GCC(c) -{ -} - -ACE_INLINE -ACE_Atomic_Op& -ACE_Atomic_Op::operator= (unsigned long rhs) -{ - ACE_Atomic_Op_GCC::operator= (rhs); - return *this; -} - -#if !defined (ACE_LACKS_GCC_ATOMIC_BUILTINS_2) -ACE_INLINE -ACE_Atomic_Op::ACE_Atomic_Op (void) : - ACE_Atomic_Op_GCC() -{ -} - -ACE_INLINE -ACE_Atomic_Op::ACE_Atomic_Op (short c) : - ACE_Atomic_Op_GCC(c) -{ -} - -ACE_INLINE -ACE_Atomic_Op::ACE_Atomic_Op (const ACE_Atomic_Op &c) : - ACE_Atomic_Op_GCC(c) -{ -} - -ACE_INLINE -ACE_Atomic_Op& -ACE_Atomic_Op::operator= (short rhs) -{ - ACE_Atomic_Op_GCC::operator= (rhs); - return *this; -} - -ACE_INLINE -ACE_Atomic_Op::ACE_Atomic_Op (void) : - ACE_Atomic_Op_GCC () -{ -} - -ACE_INLINE -ACE_Atomic_Op::ACE_Atomic_Op (unsigned short c) : - ACE_Atomic_Op_GCC(c) -{ -} - -ACE_INLINE -ACE_Atomic_Op::ACE_Atomic_Op (const ACE_Atomic_Op &c) : - ACE_Atomic_Op_GCC(c) -{ -} - -ACE_INLINE -ACE_Atomic_Op& -ACE_Atomic_Op::operator= (unsigned short rhs) -{ - ACE_Atomic_Op_GCC::operator= (rhs); - return *this; -} -#endif - -#if !defined (ACE_LACKS_GCC_ATOMIC_BUILTINS_1) -ACE_INLINE -ACE_Atomic_Op::ACE_Atomic_Op (void) : - ACE_Atomic_Op_GCC () -{ -} - -ACE_INLINE -ACE_Atomic_Op::ACE_Atomic_Op (bool c) : - ACE_Atomic_Op_GCC(c) -{ -} - -ACE_INLINE -ACE_Atomic_Op::ACE_Atomic_Op (const ACE_Atomic_Op &c) : - ACE_Atomic_Op_GCC(c) -{ -} - -ACE_INLINE -ACE_Atomic_Op& -ACE_Atomic_Op::operator= (bool rhs) -{ - ACE_Atomic_Op_GCC::operator= (rhs); - return *this; -} -#endif - -#endif /* ACE_HAS_GCC_ATOMIC_BUILTINS==1 */ - -ACE_END_VERSIONED_NAMESPACE_DECL - diff --git a/externals/ace/Atomic_Op_GCC_T.cpp b/externals/ace/Atomic_Op_GCC_T.cpp deleted file mode 100644 index bbe6ec676ec..00000000000 --- a/externals/ace/Atomic_Op_GCC_T.cpp +++ /dev/null @@ -1,29 +0,0 @@ -// $Id: Atomic_Op_GCC_T.cpp 89345 2010-03-05 13:04:51Z johnnyw $ - -#include "ace/OS_NS_unistd.h" - -ACE_RCSID (ace, - Atomic_Op_GCC, - "$Id: Atomic_Op_GCC_T.cpp 89345 2010-03-05 13:04:51Z johnnyw $") - -#if defined (ACE_HAS_GCC_ATOMIC_BUILTINS) && (ACE_HAS_GCC_ATOMIC_BUILTINS == 1) - -#if !defined (__ACE_INLINE__) -#include "ace/Atomic_Op_GCC_T.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template -void -ACE_Atomic_Op_GCC::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_GCC_ATOMIC_BUILTINS */ diff --git a/externals/ace/Atomic_Op_GCC_T.h b/externals/ace/Atomic_Op_GCC_T.h deleted file mode 100644 index 92bc771dda6..00000000000 --- a/externals/ace/Atomic_Op_GCC_T.h +++ /dev/null @@ -1,136 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Atomic_Op_GCC_T.h - * - * $Id: Atomic_Op_GCC_T.h 89339 2010-03-05 12:20:47Z johnnyw $ - * - * @author Johnny Willemsen -class ACE_Export ACE_Atomic_Op_GCC -{ -public: - /// Atomically pre-increment @c value_. - T operator++ (void); - - /// Atomically post-increment @c value_. - T operator++ (int); - - /// Atomically increment @c value_ by rhs. - T operator+= (T rhs); - - /// Atomically pre-decrement @c value_. - T operator-- (void); - - /// Atomically post-decrement @c value_. - T operator-- (int); - - /// Atomically decrement @c value_ by rhs. - T operator-= (T rhs); - - /// Atomically compare @c value_ with rhs. - bool operator== (T rhs) const; - - /// Atomically compare @c value_ with rhs. - bool operator!= (T rhs) const; - - /// Atomically check if @c value_ greater than or equal to rhs. - bool operator>= (T rhs) const; - - /// Atomically check if @c value_ greater than rhs. - bool operator> (T rhs) const; - - /// Atomically check if @c value_ less than or equal to rhs. - bool operator<= (T rhs) const; - - /// Atomically check if @c value_ less than rhs. - bool operator< (T rhs) const; - - /// Explicitly return @c value_. - T value (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Explicitly return @c value_ (by reference). - volatile T &value_i (void); - - // ACE_ALLOC_HOOK_DECLARE; - // Declare the dynamic allocation hooks. - -protected: - /// Atomically assign rhs to @c value_. - ACE_Atomic_Op_GCC &operator= (T rhs); - - /// Atomically assign to @c value_. - ACE_Atomic_Op_GCC &operator= (const ACE_Atomic_Op_GCC &rhs); - - /// Initialize @c value_ to 0. - ACE_Atomic_Op_GCC (void); - - /// Initialize @c value_ to c. - ACE_Atomic_Op_GCC (T c); - - /// Manage copying... - ACE_Atomic_Op_GCC (const ACE_Atomic_Op_GCC &c); - -private: - - // This function cannot be supported by this template specialization. - // If you need access to an underlying lock, use the ACE_Atomic_Op_Ex - // template instead. - ACE_Thread_Mutex &mutex (void); - -private: - - /// Current object decorated by the atomic op. - volatile T value_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Atomic_Op_GCC_T.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Atomic_Op_GCC_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Atomic_Op_GCC_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - - -#endif /* ACE_HAS_GCC_ATOMIC_BUILTINS */ - -#include /**/ "ace/post.h" -#endif /*ACE_ATOMIC_OP_GCC_T_H*/ diff --git a/externals/ace/Atomic_Op_GCC_T.inl b/externals/ace/Atomic_Op_GCC_T.inl deleted file mode 100644 index c6fe027022b..00000000000 --- a/externals/ace/Atomic_Op_GCC_T.inl +++ /dev/null @@ -1,148 +0,0 @@ -// -*- C++ -*- -// -// $Id: Atomic_Op_GCC_T.inl 89391 2010-03-08 13:53:30Z johnnyw $ - -#if defined (ACE_HAS_GCC_ATOMIC_BUILTINS) && (ACE_HAS_GCC_ATOMIC_BUILTINS == 1) - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template -ACE_INLINE -ACE_Atomic_Op_GCC::ACE_Atomic_Op_GCC (void) - : value_ (0) -{ -} - -template -ACE_INLINE -ACE_Atomic_Op_GCC::ACE_Atomic_Op_GCC (T c) - : value_ (c) -{ -} - -template -ACE_INLINE -ACE_Atomic_Op_GCC::ACE_Atomic_Op_GCC ( - const ACE_Atomic_Op_GCC &rhs) - : value_ (rhs.value_) -{ -} - -template -ACE_INLINE T -ACE_Atomic_Op_GCC::operator++ (void) -{ - return __sync_add_and_fetch (&this->value_, 1); -} - -template -ACE_INLINE T -ACE_Atomic_Op_GCC::operator++ (int) -{ - return __sync_fetch_and_add (&this->value_, 1); -} - -template -ACE_INLINE T -ACE_Atomic_Op_GCC::operator-- (void) -{ - return __sync_sub_and_fetch (&this->value_, 1); -} - -template -ACE_INLINE T -ACE_Atomic_Op_GCC::operator-- (int) -{ - return __sync_fetch_and_sub (&this->value_, 1); -} - -template -ACE_INLINE T -ACE_Atomic_Op_GCC::operator+= (T rhs) -{ - return __sync_add_and_fetch (&this->value_, rhs); -} - -template -ACE_INLINE T -ACE_Atomic_Op_GCC::operator-= (T rhs) -{ - return __sync_sub_and_fetch (&this->value_, rhs); -} - -template -ACE_INLINE bool -ACE_Atomic_Op_GCC::operator== (T rhs) const -{ - return (this->value_ == rhs); -} - -template -ACE_INLINE bool -ACE_Atomic_Op_GCC::operator!= (T rhs) const -{ - return (this->value_ != rhs); -} - -template -ACE_INLINE bool -ACE_Atomic_Op_GCC::operator>= (T rhs) const -{ - return (this->value_ >= rhs); -} - -template -ACE_INLINE bool -ACE_Atomic_Op_GCC::operator> (T rhs) const -{ - return (this->value_ > rhs); -} - -template -ACE_INLINE bool -ACE_Atomic_Op_GCC::operator<= (T rhs) const -{ - return (this->value_ <= rhs); -} - -template -ACE_INLINE bool -ACE_Atomic_Op_GCC::operator< (T rhs) const -{ - return (this->value_ < rhs); -} - -template -ACE_INLINE ACE_Atomic_Op_GCC & -ACE_Atomic_Op_GCC::operator= (T rhs) -{ - (void) __sync_lock_test_and_set (&this->value_, rhs); - return *this; -} - -template -ACE_INLINE ACE_Atomic_Op_GCC & -ACE_Atomic_Op_GCC::operator= ( - const ACE_Atomic_Op_GCC &rhs) -{ - (void) __sync_lock_test_and_set (&this->value_, rhs.value_); - return *this; -} - -template -ACE_INLINE T -ACE_Atomic_Op_GCC::value (void) const -{ - return this->value_; -} - -template -ACE_INLINE volatile T & -ACE_Atomic_Op_GCC::value_i (void) -{ - return this->value_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_GCC_ATOMIC_BUILTINS */ diff --git a/externals/ace/Atomic_Op_Sparc.c b/externals/ace/Atomic_Op_Sparc.c deleted file mode 100644 index 842673e58cc..00000000000 --- a/externals/ace/Atomic_Op_Sparc.c +++ /dev/null @@ -1,187 +0,0 @@ -/* $Id: Atomic_Op_Sparc.c 80826 2008-03-04 14:51:23Z wotte $ - * - * This is a C file for a reason. The Sun C++ compiler does not accept - * inline assembler. - * - * Portions of this code are based on atomic operations found in the - * linux kernel source code. - */ - -#if defined (ACE_INCLUDE_ATOMIC_OP_SPARC) - -#if defined(__i386) && defined(__SUNPRO_C) -static void -__sunpro_asm_code() { - __asm("\n\ - .globl ace_atomic_add_long \n\ - .type ace_atomic_add_long,@function \n\ - .align 4 \n\ -ace_atomic_add_long: \n\ - movl 0x00000004(%esp), %edx \n\ - movl 0x00000008(%esp), %eax \n\ - lock; xadd %eax, (%edx) \n\ - addl 0x00000008(%esp), %eax \n\ - ret \n\ - "); - - __asm("\n\ - .globl ace_atomic_swap_long \n\ - .type ace_atomic_swap_long,@function \n\ - .align 4 \n\ -ace_atomic_swap_long: \n\ - movl 0x00000004(%esp), %edx \n\ - movl 0x00000008(%esp), %eax \n\ - xchg %eax, (%edx) \n\ - ret \n\ - "); - - __asm("\n\ - .globl ace_atomic_swap_add_long \n\ - .type ace_atomic_swap_add_long,@function \n\ - .align 4 \n\ -ace_atomic_swap_add_long: \n\ - movl 0x00000004(%esp), %edx \n\ - movl 0x00000008(%esp), %eax \n\ - lock; xadd %eax, (%edx) \n\ - ret \n\ - "); -} - -#elif defined(__x86_64) && defined(__SUNPRO_C) - -static void -__sunpro_asm_code() { - __asm("\n\ - .globl ace_atomic_add_long \n\ - .type ace_atomic_add_long,@function \n\ - .align 16 \n\ -ace_atomic_add_long: \n\ - movq %rsi, %rax \n\ - lock; xaddq %rax, (%rdi) \n\ - addq %rsi, %rax \n\ - ret \n\ - "); - - __asm("\n\ - .globl ace_atomic_swap_long \n\ - .type ace_atomic_swap_long,@function \n\ - .align 16 \n\ -ace_atomic_swap_long: \n\ - xchgq %rsi, (%rdi) \n\ - movq %rsi, %rax \n\ - ret \n\ - "); - - __asm("\n\ - .globl ace_atomic_swap_add_long \n\ - .type ace_atomic_swap_add_long,@function \n\ - .align 16 \n\ -ace_atomic_swap_add_long: \n\ - lock; xaddq %rsi, (%rdi) \n\ - movq %rsi, %rax \n\ - ret \n\ - "); -} - -#elif defined (__sparcv9) - -unsigned long -ace_atomic_add_long (volatile unsigned long *dest, long rhs) -{ - __asm ("restore\n" - "ldx [%o0], %o2\n" - ".again_add:\n" - "add %o2, %o1, %o3\n" - "casx [%o0], %o2, %o3\n" - "cmp %o2, %o3\n" - "bne,pn %xcc, .again_add\n" - "mov %o3, %o2\n" - "retl\n" - "add %o2, %o1, %o0\n"); -} - -unsigned long -ace_atomic_swap_long (volatile unsigned long *dest, unsigned long rhs) -{ - __asm ("restore\n" - "ldx [%o0], %o2\n" - ".again_swap:\n" - "mov %o1, %o3\n" - "casx [%o0], %o2, %o3\n" - "cmp %o2, %o3\n" - "bne,pn %xcc, .again_swap\n" - "mov %o3, %o2\n" - "retl\n" - "mov %o3, %o0\n"); -} - -unsigned long -ace_atomic_swap_add_long (volatile unsigned long *dest, long rhs) -{ - __asm ("restore\n" - "ldx [%o0], %o2\n" - ".again_swap_add:\n" - "mov %o2, %o4\n" - "add %o2, %o1, %o3\n" - "casx [%o0], %o2, %o3\n" - "cmp %o2, %o3\n" - "bne,pn %xcc, .again_swap_add\n" - "mov %o3, %o2\n" - "retl\n" - "mov %o4, %o0\n"); -} - -#else - -unsigned long -ace_atomic_add_long (volatile unsigned long *dest, long rhs) -{ - __asm ("restore\n" - "ld [%o0], %o2\n" - ".again_add:\n" - "add %o2, %o1, %o3\n" - "cas [%o0], %o2, %o3\n" - "cmp %o2, %o3\n" - "bne,pn %icc, .again_add\n" - "mov %o3, %o2\n" - "retl\n" - "add %o2, %o1, %o0\n"); -} - -unsigned long -ace_atomic_swap_long (volatile unsigned long *dest, unsigned long rhs) -{ - __asm ("restore\n" - "ld [%o0], %o2\n" - ".again_swap:\n" - "mov %o1, %o3\n" - "cas [%o0], %o2, %o3\n" - "cmp %o2, %o3\n" - "bne,pn %icc, .again_swap\n" - "mov %o3, %o2\n" - "retl\n" - "mov %o3, %o0\n"); -} - -unsigned long -ace_atomic_swap_add_long (volatile unsigned long *dest, long rhs) -{ - __asm ("restore\n" - "ld [%o0], %o2\n" - ".again_swap_add:\n" - "mov %o2, %o4\n" - "add %o2, %o1, %o3\n" - "cas [%o0], %o2, %o3\n" - "cmp %o2, %o3\n" - "bne,pn %icc, .again_swap_add\n" - "mov %o3, %o2\n" - "retl\n" - "mov %o4, %o0\n"); -} - -# endif /* __sparcv9 */ - -#elif !defined (__GNUC__) && !defined (__INTEL_COMPILER) -/* Make compilers stop complaining about an empty translation unit */ -static int shut_up_compiler = 0; -#endif /* ACE_INCLUDE_ATOMIC_OP_SPARC */ diff --git a/externals/ace/Atomic_Op_Sparc.h b/externals/ace/Atomic_Op_Sparc.h deleted file mode 100644 index 75b9ad6eaa2..00000000000 --- a/externals/ace/Atomic_Op_Sparc.h +++ /dev/null @@ -1,14 +0,0 @@ -/* -*- C++ -*- */ -// $Id: Atomic_Op_Sparc.h 80826 2008-03-04 14:51:23Z wotte $ - -#ifndef ACE_ATOMIC_OP_SPARC_H -#define ACE_ATOMIC_OP_SPARC_H - -extern "C" -{ - unsigned long ace_atomic_add_long (volatile unsigned long *dest, long rhs); - unsigned long ace_atomic_swap_long (volatile unsigned long *dest, unsigned long rhs); - unsigned long ace_atomic_swap_add_long (volatile unsigned long *dest, long rhs); -} - -#endif /* ACE_ATOMIC_OP_SPARC_H */ diff --git a/externals/ace/Atomic_Op_T.cpp b/externals/ace/Atomic_Op_T.cpp deleted file mode 100644 index fcaa529b8e6..00000000000 --- a/externals/ace/Atomic_Op_T.cpp +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef ACE_ATOMIC_OP_T_CPP -#define ACE_ATOMIC_OP_T_CPP - -#include "ace/Atomic_Op_T.h" - -#ifdef ACE_HAS_DUMP -# include "ace/Log_Msg.h" -#endif /* ACE_HAS_DUMP */ - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (__ACE_INLINE__) -#include "ace/Atomic_Op_T.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Atomic_Op_Ex) -ACE_ALLOC_HOOK_DEFINE(ACE_Atomic_Op) - -ACE_RCSID(ace, Atomic_Op_T, "$Id: Atomic_Op_T.cpp 85141 2009-04-22 08:48:30Z johnnyw $") - -// ************************************************* -template ACE_LOCK & -ACE_Atomic_Op_Ex::mutex (void) -{ - // ACE_TRACE ("ACE_Atomic_Op_Ex::mutex"); - return this->mutex_; -} - -template -void -ACE_Atomic_Op_Ex::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - // ACE_TRACE ("ACE_Atomic_Op_Ex::dump"); - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - this->mutex_.dump (); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP, this)); -#endif /* ACE_HAS_DUMP */ -} - -template -ACE_Atomic_Op_Ex::ACE_Atomic_Op_Ex (ACE_LOCK & mtx) - : mutex_ (mtx) - , value_ (0) -{ - // ACE_TRACE ("ACE_Atomic_Op_Ex::ACE_Atomic_Op_Ex"); -} - -template -ACE_Atomic_Op_Ex::ACE_Atomic_Op_Ex ( - ACE_LOCK & mtx, - typename ACE_Atomic_Op_Ex::arg_type c) - : mutex_ (mtx) - , value_ (c) -{ - // ACE_TRACE ("ACE_Atomic_Op_Ex::ACE_Atomic_Op_Ex"); -} - -// **************************************************************** - -template -ACE_Atomic_Op::ACE_Atomic_Op (void) - : impl_ (this->own_mutex_) -{ - // ACE_TRACE ("ACE_Atomic_Op::ACE_Atomic_Op"); -} - -template -ACE_Atomic_Op::ACE_Atomic_Op ( - typename ACE_Atomic_Op::arg_type c) - : impl_ (own_mutex_, c) -{ - // ACE_TRACE ("ACE_Atomic_Op::ACE_Atomic_Op"); -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_ATOMIC_OP_T_CPP */ diff --git a/externals/ace/Atomic_Op_T.h b/externals/ace/Atomic_Op_T.h deleted file mode 100644 index 13bd7dbbf88..00000000000 --- a/externals/ace/Atomic_Op_T.h +++ /dev/null @@ -1,369 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Atomic_Op_T.h - * - * $Id: Atomic_Op_T.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_ATOMIC_OP_T_H -#define ACE_ATOMIC_OP_T_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template -struct ACE_Type_Traits -{ - typedef TYPE const & parameter_type; -}; - -template<> -struct ACE_Type_Traits -{ - typedef bool parameter_type; -}; - -template<> -struct ACE_Type_Traits -{ - typedef char parameter_type; -}; - -template<> -struct ACE_Type_Traits -{ - typedef signed char parameter_type; -}; - -template<> -struct ACE_Type_Traits -{ - typedef unsigned char parameter_type; -}; - -template<> -struct ACE_Type_Traits -{ - typedef short parameter_type; -}; - -template<> -struct ACE_Type_Traits -{ - typedef unsigned short parameter_type; -}; - -template<> -struct ACE_Type_Traits -{ - typedef int parameter_type; -}; - -template<> -struct ACE_Type_Traits -{ - typedef unsigned int parameter_type; -}; - -template<> -struct ACE_Type_Traits -{ - typedef long parameter_type; -}; - -template<> -struct ACE_Type_Traits -{ - typedef unsigned long parameter_type; -}; - -#ifndef ACE_LACKS_LONGLONG_T -template<> -struct ACE_Type_Traits -{ - typedef long long parameter_type; -}; -#endif /* !ACE_LACKS_LONGLONG_T */ - -#if !defined (ACE_LACKS_LONGLONG_T) \ - && !defined (ACE_LACKS_UNSIGNEDLONGLONG_T) -template<> -struct ACE_Type_Traits -{ - typedef unsigned long long parameter_type; -}; -#endif /* !ACE_LACKS_LONGLONG_T && !ACE_LACKS_UNSIGNEDLONGLONG_T */ - -template<> -struct ACE_Type_Traits -{ - typedef float parameter_type; -}; - -template<> -struct ACE_Type_Traits -{ - typedef double parameter_type; -}; - -template<> -struct ACE_Type_Traits -{ - typedef long double parameter_type; -}; - -template -struct ACE_Type_Traits -{ - typedef TYPE* parameter_type; -}; - -/** - * @class ACE_Atomic_Op_Ex - * - * @brief Transparently parameterizes synchronization into basic - * arithmetic operations. - * - * This class is described in an article in the July/August 1994 - * issue of the C++ Report magazine. It implements a - * templatized version of the Decorator pattern from the GoF book. - * - * ACE_Atomic_Op_Ex objects must be constructed with a reference - * to an existing lock. A single lock can be shared between - * multiple ACE_Atomic_Op_Ex objects. If you do not require this - * ability consider using the ACE_Atomic_Op class instead, which - * may be able to take advantage of platform-specific - * optimisations to provide atomic operations without requiring a - * lock. - */ -template -class ACE_Atomic_Op_Ex -{ -public: - - typedef typename ACE_Type_Traits::parameter_type arg_type; - - // = Initialization methods. - - /// Initialize @c value_ to 0. - ACE_Atomic_Op_Ex (ACE_LOCK & mtx); - - /// Initialize @c value_ to c. - ACE_Atomic_Op_Ex (ACE_LOCK & mtx, arg_type c); - - // = Accessors. - - /// Atomically pre-increment @c value_. - TYPE operator++ (void); - - /// Atomically post-increment @c value_. - TYPE operator++ (int); - - /// Atomically increment @c value_ by rhs. - TYPE operator+= (arg_type rhs); - - /// Atomically pre-decrement @c value_. - TYPE operator-- (void); - - /// Atomically post-decrement @c value_. - TYPE operator-- (int); - - /// Atomically decrement @c value_ by rhs. - TYPE operator-= (arg_type rhs); - - /// Atomically compare @c value_ with rhs. - bool operator== (arg_type rhs) const; - - /// Atomically compare @c value_ with rhs. - bool operator!= (arg_type rhs) const; - - /// Atomically check if @c value_ greater than or equal to rhs. - bool operator>= (arg_type rhs) const; - - /// Atomically check if @c value_ greater than rhs. - bool operator> (arg_type rhs) const; - - /// Atomically check if @c value_ less than or equal to rhs. - bool operator<= (arg_type rhs) const; - - /// Atomically check if @c value_ less than rhs. - bool operator< (arg_type rhs) const; - - /// Atomically assign rhs to @c value_. - ACE_Atomic_Op_Ex &operator= (arg_type rhs); - - /// Atomically assign to @c value_. - ACE_Atomic_Op_Ex &operator= ( - ACE_Atomic_Op_Ex const & rhs); - - /// Explicitly return @c value_. - TYPE value (void) const; - - /// Dump the state of an object. - void dump (void) const; - - // ACE_ALLOC_HOOK_DECLARE; - // Declare the dynamic allocation hooks. - - /// Manage copying... - ACE_Atomic_Op_Ex (ACE_Atomic_Op_Ex const &); - - /** - * Returns a reference to the underlying . This makes it - * possible to acquire the lock explicitly, which can be useful in - * some cases if you instantiate the with an - * ACE_Recursive_Mutex or ACE_Process_Mutex. @note the right - * name would be lock_, but HP/C++ will choke on that! - */ - ACE_LOCK & mutex (void); - - /** - * Explicitly return @c value_ (by reference). This gives the user - * full, unrestricted access to the underlying value. This method - * will usually be used in conjunction with explicit access to the - * lock. Use with care ;-) - */ - TYPE & value_i (void); - -private: - /// Type of synchronization mechanism. - ACE_LOCK & mutex_; - - /// Current object decorated by the atomic op. - TYPE value_; -}; - -/** - * @class ACE_Atomic_Op - * - * @brief Transparently parameterizes synchronization into basic - * arithmetic operations. - * - * This class is described in an article in the July/August 1994 - * issue of the C++ Report magazine. It implements a - * templatized version of the Decorator pattern from the GoF book. - * - * Certain platforms may provide a template specialization for - * ACE_Atomic_Op that provides optimized - * atomic integer operations without actually requiring a mutex. - */ -template -class ACE_Atomic_Op -{ -public: - - typedef typename ACE_Type_Traits::parameter_type arg_type; - - /// Initialize @c value_ to 0. - ACE_Atomic_Op (void); - - /// Initialize @c value_ to c. - ACE_Atomic_Op (arg_type c); - - /// Manage copying... - ACE_Atomic_Op (ACE_Atomic_Op const & c); - - /// Atomically assign rhs to @c value_. - ACE_Atomic_Op & operator= (arg_type rhs); - - /// Atomically assign to @c value_. - ACE_Atomic_Op & operator= ( - ACE_Atomic_Op const & rhs); - - /// Atomically pre-increment @c value_. - TYPE operator++ (void); - - /// Atomically post-increment @c value_. - TYPE operator++ (int); - - /// Atomically increment @c value_ by rhs. - TYPE operator+= (arg_type rhs); - - /// Atomically pre-decrement @c value_. - TYPE operator-- (void); - - /// Atomically post-decrement @c value_. - TYPE operator-- (int); - - /// Atomically decrement @c value_ by rhs. - TYPE operator-= (arg_type rhs); - - /// Atomically compare @c value_ with rhs. - bool operator== (arg_type rhs) const; - - /// Atomically compare @c value_ with rhs. - bool operator!= (arg_type rhs) const; - - /// Atomically check if @c value_ greater than or equal to rhs. - bool operator>= (arg_type rhs) const; - - /// Atomically check if @c value_ greater than rhs. - bool operator> (arg_type rhs) const; - - /// Atomically check if @c value_ less than or equal to rhs. - bool operator<= (arg_type rhs) const; - - /// Atomically check if @c value_ less than rhs. - bool operator< (arg_type rhs) const; - - /// Explicitly return @c value_. - TYPE value (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /** - * Returns a reference to the underlying . This makes it - * possible to acquire the lock explicitly, which can be useful in - * some cases if you instantiate the ACE_Atomic_Op with an - * ACE_Recursive_Mutex or ACE_Process_Mutex. - * - * @deprecated This member function is deprecated and so may go away in - * the future. If you need access to the underlying mutex, consider - * using the ACE_Atomic_Op_Ex template instead. - */ - ACE_LOCK & mutex (void); - - /** - * Explicitly return @c value_ (by reference). This gives the user - * full, unrestricted access to the underlying value. This method - * will usually be used in conjunction with explicit access to the - * lock. Use with care ;-) - */ - TYPE & value_i (void); - -private: - /// Type of synchronization mechanism. - ACE_LOCK own_mutex_; - - /// Underlying atomic op implementation. - ACE_Atomic_Op_Ex impl_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Atomic_Op_T.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Atomic_Op_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Atomic_Op_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" -#endif /*ACE_ATOMIC_OP_T_H*/ diff --git a/externals/ace/Atomic_Op_T.inl b/externals/ace/Atomic_Op_T.inl deleted file mode 100644 index ff051b0cbce..00000000000 --- a/externals/ace/Atomic_Op_T.inl +++ /dev/null @@ -1,340 +0,0 @@ -// -*- C++ -*- -// -// $Id: Atomic_Op_T.inl 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Guard_T.h" - -#include - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// -// ACE_Atomic_Op_Ex inline functions -// - -template -ACE_INLINE TYPE -ACE_Atomic_Op_Ex::operator++ (void) -{ - // ACE_TRACE ("ACE_Atomic_Op_Ex::operator++"); - ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, this->value_); - return ++this->value_; -} - -template -ACE_INLINE TYPE -ACE_Atomic_Op_Ex::operator+= ( - typename ACE_Atomic_Op_Ex::arg_type rhs) -{ - // ACE_TRACE ("ACE_Atomic_Op_Ex::operator+="); - ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, this->value_); - return this->value_ += rhs; -} - -template -ACE_INLINE TYPE -ACE_Atomic_Op_Ex::operator-- (void) -{ - // ACE_TRACE ("ACE_Atomic_Op_Ex::operator--"); - ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, this->value_); - return --this->value_; -} - -template -ACE_INLINE TYPE -ACE_Atomic_Op_Ex::operator-= ( - typename ACE_Atomic_Op_Ex::arg_type rhs) -{ - // ACE_TRACE ("ACE_Atomic_Op_Ex::operator-="); - ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, this->value_); - return this->value_ -= rhs; -} - -template -ACE_INLINE -ACE_Atomic_Op_Ex::ACE_Atomic_Op_Ex ( - ACE_Atomic_Op_Ex const & rhs) - : mutex_ (rhs.mutex_) - , value_ (rhs.value ()) // rhs.value() returns atomically -{ - // ACE_TRACE ("ACE_Atomic_Op_Ex::ACE_Atomic_Op_Ex"); -} - -template -ACE_INLINE TYPE -ACE_Atomic_Op_Ex::operator++ (int) -{ - // ACE_TRACE ("ACE_Atomic_Op_Ex::operator++"); - ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, this->value_); - return this->value_++; -} - -template -ACE_INLINE TYPE -ACE_Atomic_Op_Ex::operator-- (int) -{ - // ACE_TRACE ("ACE_Atomic_Op_Ex::operator--"); - ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, this->value_); - return this->value_--; -} - -template -ACE_INLINE bool -ACE_Atomic_Op_Ex::operator== ( - typename ACE_Atomic_Op_Ex::arg_type rhs) const -{ - // ACE_TRACE ("ACE_Atomic_Op_Ex::operator=="); - ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, false); - return this->value_ == rhs; -} - -template -ACE_INLINE bool -ACE_Atomic_Op_Ex::operator!= ( - typename ACE_Atomic_Op_Ex::arg_type rhs) const -{ - // ACE_TRACE ("ACE_Atomic_Op_Ex::operator!="); - return !(*this == rhs); -} - -template -ACE_INLINE bool -ACE_Atomic_Op_Ex::operator>= ( - typename ACE_Atomic_Op_Ex::arg_type rhs) const -{ - // ACE_TRACE ("ACE_Atomic_Op_Ex::operator>="); - ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, false); - return this->value_ >= rhs; -} - -template -ACE_INLINE bool -ACE_Atomic_Op_Ex::operator> ( - typename ACE_Atomic_Op_Ex::arg_type rhs) const -{ - // ACE_TRACE ("ACE_Atomic_Op_Ex::operator>"); - ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, false); - return this->value_ > rhs; -} - -template -ACE_INLINE bool -ACE_Atomic_Op_Ex::operator<= ( - typename ACE_Atomic_Op_Ex::arg_type rhs) const -{ - // ACE_TRACE ("ACE_Atomic_Op_Ex::operator<="); - ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, false); - return this->value_ <= rhs; -} - -template -ACE_INLINE bool -ACE_Atomic_Op_Ex::operator< ( - typename ACE_Atomic_Op_Ex::arg_type rhs) const -{ - // ACE_TRACE ("ACE_Atomic_Op_Ex::operator<"); - ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, false); - return this->value_ < rhs; -} - -template -ACE_INLINE ACE_Atomic_Op_Ex & -ACE_Atomic_Op_Ex::operator= ( - ACE_Atomic_Op_Ex const & rhs) -{ - // ACE_TRACE ("ACE_Atomic_Op_Ex::operator="); - - ACE_Atomic_Op_Ex tmp (rhs); - - ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, *this); - std::swap (this->value_, tmp.value_); - - return *this; -} - -template -ACE_INLINE TYPE -ACE_Atomic_Op_Ex::value (void) const -{ - // ACE_TRACE ("ACE_Atomic_Op_Ex::value"); - ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, this->value_); - return this->value_; -} - -template -ACE_INLINE TYPE & -ACE_Atomic_Op_Ex::value_i (void) -{ - // Explicitly return (by reference). This gives the user - // full, unrestricted access to the underlying value. This method - // will usually be used in conjunction with explicit access to the - // lock. Use with care ;-) - return this->value_; -} - -template -ACE_INLINE ACE_Atomic_Op_Ex & -ACE_Atomic_Op_Ex::operator= ( - typename ACE_Atomic_Op_Ex::arg_type rhs) -{ - // ACE_TRACE ("ACE_Atomic_Op_Ex::operator="); - ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, *this); - this->value_ = rhs; - return *this; -} - -// -// ACE_Atomic_Op inline functions -// - -template ACE_INLINE -ACE_Atomic_Op::ACE_Atomic_Op ( - ACE_Atomic_Op const & rhs) - : impl_ (own_mutex_, rhs.value ()) -{ - // ACE_TRACE ("ACE_Atomic_Op::ACE_Atomic_Op"); -} - - -template -ACE_INLINE ACE_Atomic_Op & -ACE_Atomic_Op::operator= ( - typename ACE_Atomic_Op::arg_type i) -{ - this->impl_ = i; - return *this; -} - -template -ACE_INLINE ACE_Atomic_Op & -ACE_Atomic_Op::operator= ( - ACE_Atomic_Op const & rhs) -{ - this->impl_ = rhs.impl_; - return *this; -} - -template -ACE_INLINE TYPE -ACE_Atomic_Op::operator++ (void) -{ - return ++this->impl_; -} - -template -ACE_INLINE TYPE -ACE_Atomic_Op::operator++ (int) -{ - return this->impl_++; -} - -template -ACE_INLINE TYPE -ACE_Atomic_Op::operator+= ( - typename ACE_Atomic_Op::arg_type rhs) -{ - return this->impl_ += rhs; -} - -template -ACE_INLINE TYPE -ACE_Atomic_Op::operator-- (void) -{ - return --this->impl_; -} - -template -ACE_INLINE TYPE -ACE_Atomic_Op::operator-- (int) -{ - return this->impl_--; -} - -template -ACE_INLINE TYPE -ACE_Atomic_Op::operator-= ( - typename ACE_Atomic_Op::arg_type rhs) -{ - return this->impl_ -= rhs; -} - -template -ACE_INLINE bool -ACE_Atomic_Op::operator== ( - typename ACE_Atomic_Op::arg_type rhs) const -{ - return this->impl_ == rhs; -} - -template -ACE_INLINE bool -ACE_Atomic_Op::operator!= ( - typename ACE_Atomic_Op::arg_type rhs) const -{ - return this->impl_ != rhs; -} - -template -ACE_INLINE bool -ACE_Atomic_Op::operator>= ( - typename ACE_Atomic_Op::arg_type rhs) const -{ - return this->impl_ >= rhs; -} - -template -ACE_INLINE bool -ACE_Atomic_Op::operator> ( - typename ACE_Atomic_Op::arg_type rhs) const -{ - return this->impl_ > rhs; -} - -template -ACE_INLINE bool -ACE_Atomic_Op::operator<= ( - typename ACE_Atomic_Op::arg_type rhs) const -{ - return this->impl_ <= rhs; -} - -template -ACE_INLINE bool -ACE_Atomic_Op::operator< ( - typename ACE_Atomic_Op::arg_type rhs) const -{ - return this->impl_ < rhs; -} - -template -ACE_INLINE TYPE -ACE_Atomic_Op::value (void) const -{ - return this->impl_.value (); -} - -template -ACE_INLINE void -ACE_Atomic_Op::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - this->impl_.dump (); -#endif /* ACE_HAS_DUMP */ - return; -} - -template -ACE_INLINE ACE_LOCK & -ACE_Atomic_Op::mutex (void) -{ - return this->own_mutex_; -} - -template -ACE_INLINE TYPE & -ACE_Atomic_Op::value_i (void) -{ - return this->impl_.value_i (); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Auto_Event.cpp b/externals/ace/Auto_Event.cpp deleted file mode 100644 index 51efcf7605b..00000000000 --- a/externals/ace/Auto_Event.cpp +++ /dev/null @@ -1,49 +0,0 @@ -// $Id: Auto_Event.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Auto_Event.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Auto_Event.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID (ace, - Auto_Event, - "$Id: Auto_Event.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_Auto_Event::ACE_Auto_Event (int initial_state, - int type, - const char *name, - void *arg) - : ACE_Event (0, - initial_state, - type, - ACE_TEXT_CHAR_TO_TCHAR (name), - arg) -{ -} - -#if defined (ACE_HAS_WCHAR) -ACE_Auto_Event::ACE_Auto_Event (int initial_state, - int type, - const wchar_t *name, - void *arg) - : ACE_Event (0, - initial_state, - type, - ACE_TEXT_WCHAR_TO_TCHAR (name), - arg) -{ -} -#endif /* ACE_HAS_WCHAR */ - -void -ACE_Auto_Event::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_Event::dump (); -#endif /* ACE_HAS_DUMP */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Auto_Event.h b/externals/ace/Auto_Event.h deleted file mode 100644 index 042f82ed2ff..00000000000 --- a/externals/ace/Auto_Event.h +++ /dev/null @@ -1,73 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file Auto_Event.h - * - * $Id: Auto_Event.h 80826 2008-03-04 14:51:23Z wotte $ - * - * Moved from Synch.h. - * - * @author Douglas C. Schmidt - */ -//========================================================================== - -#ifndef ACE_AUTO_EVENT_H -#define ACE_AUTO_EVENT_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Event.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Auto_Event - * - * @brief Auto Events. - * - * Specialization of Event mechanism which wakes up one waiting - * thread on . All platforms support process-scope locking - * support. However, only Win32 platforms support global naming and - * system-scope locking support. - */ -class ACE_Export ACE_Auto_Event : public ACE_Event -{ -public: - /// Constructor which will create auto event - ACE_Auto_Event (int initial_state = 0, - int type = USYNC_THREAD, - const char *name = 0, - void *arg = 0); - -#if defined (ACE_HAS_WCHAR) - /// Constructor which will create auto event (wchar_t version) - ACE_Auto_Event (int initial_state, - int type, - const wchar_t *name, - void *arg = 0); -#endif /* ACE_HAS_WCHAR */ - - /// Default dtor. - ~ACE_Auto_Event (void); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks - ACE_ALLOC_HOOK_DECLARE; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Auto_Event.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_AUTO_EVENT_H */ diff --git a/externals/ace/Auto_Event.inl b/externals/ace/Auto_Event.inl deleted file mode 100644 index b614e0b0d77..00000000000 --- a/externals/ace/Auto_Event.inl +++ /dev/null @@ -1,12 +0,0 @@ -// -*- C++ -*- -// -// $Id: Auto_Event.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE -ACE_Auto_Event::~ACE_Auto_Event (void) -{ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Auto_Functor.cpp b/externals/ace/Auto_Functor.cpp deleted file mode 100644 index 9d0dc79aa52..00000000000 --- a/externals/ace/Auto_Functor.cpp +++ /dev/null @@ -1,39 +0,0 @@ -// $Id: Auto_Functor.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#ifndef ACE_AUTO_FUNCTOR_CPP -#define ACE_AUTO_FUNCTOR_CPP - -#include "ace/Auto_Functor.h" - -#if !defined(__ACE_INLINE__) -# include "ace/Auto_Functor.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template -ACE_Utils::Auto_Functor::~Auto_Functor() -{ - reset(0); -} - -template void -ACE_Utils::Auto_Functor::reset(X * p) -{ - if(p_ != 0) - { - f_(p_); - } - p_ = p; -} - -templatevoid -ACE_Utils::Auto_Functor::reset(X * p, Functor f) -{ - reset(p); - f_ = f; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /*ACE_AUTO_FUNCTOR_CPP*/ diff --git a/externals/ace/Auto_Functor.h b/externals/ace/Auto_Functor.h deleted file mode 100644 index 2c2b81eb265..00000000000 --- a/externals/ace/Auto_Functor.h +++ /dev/null @@ -1,127 +0,0 @@ -// -*- C++ -*- -//============================================================================= -/** - * @file Auto_Functor.h - * - * $Id: Auto_Functor.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Carlos O'Ryan - */ -//============================================================================= -#ifndef ACE_AUTO_FUNCTOR_H -#define ACE_AUTO_FUNCTOR_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Global_Macros.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -namespace ACE_Utils -{ -/** - * @class Auto_Functor_Ref - * - * @brief Helper class to implement assignment and copy-construction - * as expected - */ -template -struct Auto_Functor_Ref -{ - X * p_; - Functor f_; - - Auto_Functor_Ref(X * p, Functor f); -}; - -/** - * @class Auto_Functor - * - * @brief Helper template to implement auto_ptr<>-like classes, but - * executing a functor in the destructor, instead of always - * deleting things. - * - * The functor is called in the destructor, and it must implement: - * - * Functor() throw();
- * Functor(Functor const &) throw();
- * Functor & operator=(Functor const &) throw();
- * void operator()(X * p) throw();
- * - */ -template -class Auto_Functor -{ -public: - typedef X element_type; - typedef Functor functor_type; - - /// Constructor - explicit Auto_Functor (X * p = 0, - Functor functor = Functor()); // throw() - - Auto_Functor (Auto_Functor & rhs); // throw() - - Auto_Functor& operator= (Auto_Functor & rhs); // throw() - -#if !defined(ACE_LACKS_MEMBER_TEMPLATES) - template - Auto_Functor(Auto_Functor& rhs); // throw() - - template - Auto_Functor& operator= (Auto_Functor& rhs); // throw() -#endif /* ACE_LACKS_MEMBER_TEMPLATES */ - - ~Auto_Functor(); // throw() - - X & operator*() const; // throw() - - X * operator->() const; // throw() - - X * get(); // throw() - - X * release(); // throw() - - void reset (X * p = 0); // throw() - - void reset (X * p, Functor f); // throw() - - Functor const & functor() const; // throw() - - Auto_Functor(Auto_Functor_Ref rhs); // throw() - - Auto_Functor & operator=(Auto_Functor_Ref rhs); // throw() - -#if !defined(ACE_LACKS_MEMBER_TEMPLATES) - template operator Auto_Functor_Ref(); // throw() - - template operator Auto_Functor(); // throw() -#else - operator Auto_Functor_Ref(); // throw() -#endif /* ACE_LACKS_MEMBER_TEMPLATES */ - -private: - X * p_; - - Functor f_; -}; - -} // namespace ACE_Utils - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined(__ACE_INLINE__) -# include "ace/Auto_Functor.inl" -#endif /* __ACE_INLINE__ */ - -#if defined(ACE_TEMPLATES_REQUIRE_SOURCE) -# include "ace/Auto_Functor.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#include /**/ "ace/post.h" -#endif /* ACE_AUTO_FUNCTOR_H*/ diff --git a/externals/ace/Auto_Functor.inl b/externals/ace/Auto_Functor.inl deleted file mode 100644 index d4cb2cc0473..00000000000 --- a/externals/ace/Auto_Functor.inl +++ /dev/null @@ -1,134 +0,0 @@ -// -*- C++ -*- -// -// $Id: Auto_Functor.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template ACE_INLINE -ACE_Utils::Auto_Functor_Ref:: -Auto_Functor_Ref(X * p, Functor f) - : p_(p) - , f_(f) -{ -} - -template ACE_INLINE -ACE_Utils::Auto_Functor::Auto_Functor(X * p, Functor f) - : p_(p) - , f_(f) -{ -} - -template ACE_INLINE -ACE_Utils::Auto_Functor::Auto_Functor(Auto_Functor & rhs) - : p_(rhs.release()) - , f_(rhs.f_) -{ -} - -template -ACE_INLINE ACE_Utils::Auto_Functor& -ACE_Utils::Auto_Functor:: operator=(Auto_Functor & rhs) -{ - reset(rhs.release()); - f_ = rhs.f_; - return *this; -} - -#if !defined(ACE_LACKS_MEMBER_TEMPLATES) -template template ACE_INLINE -ACE_Utils::Auto_Functor::Auto_Functor(Auto_Functor& rhs) - : p_(rhs.release()) - , f_(rhs.f_) -{ -} - -template template -ACE_INLINE ACE_Utils::Auto_Functor& -ACE_Utils::Auto_Functor::operator=(Auto_Functor& rhs) -{ - reset(rhs.release()); - return *this; -} -#endif /* ACE_LACKS_MEMBER_TEMPLATES */ - -template ACE_INLINE X & -ACE_Utils::Auto_Functor::operator*() const -{ - return *p_; -} - -template -ACE_INLINE X * -ACE_Utils::Auto_Functor::operator->() const -{ - return p_; -} - -template -ACE_INLINE X * -ACE_Utils::Auto_Functor::get() -{ - return p_; -} - -template -ACE_INLINE X * -ACE_Utils::Auto_Functor::release() -{ - X * tmp = p_; - p_ = 0; - return tmp; -} - -template -ACE_INLINE Functor const & -ACE_Utils::Auto_Functor::functor() const -{ - return f_; -} - -template ACE_INLINE -ACE_Utils::Auto_Functor::Auto_Functor(Auto_Functor_Ref rhs) - : p_(rhs.p_) - , f_(rhs.f_) -{ -} - -template -ACE_INLINE ACE_Utils::Auto_Functor & -ACE_Utils::Auto_Functor::operator=(Auto_Functor_Ref rhs) -{ - if(rhs.p_ != p_) - { - reset(rhs.p_); - f_ = rhs.f_; - } - return *this; -} - -#if !defined(ACE_LACKS_MEMBER_TEMPLATES) - -template template ACE_INLINE -ACE_Utils::Auto_Functor::operator ACE_Utils::Auto_Functor_Ref() -{ - return ACE_Utils::Auto_Functor_Ref(release(), f_); -} - -template template ACE_INLINE -ACE_Utils::Auto_Functor::operator ACE_Utils::Auto_Functor() -{ - return ACE_Utils::Auto_Functor(release(), f_); -} - -#else - -templateACE_INLINE -ACE_Utils::Auto_Functor::operator ACE_Utils::Auto_Functor_Ref() -{ - return ACE_Utils::Auto_Functor_Ref(release(), f_); -} - -#endif /* ACE_LACKS_MEMBER_TEMPLATES */ - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Auto_IncDec_T.cpp b/externals/ace/Auto_IncDec_T.cpp deleted file mode 100644 index ccef122edcf..00000000000 --- a/externals/ace/Auto_IncDec_T.cpp +++ /dev/null @@ -1,34 +0,0 @@ -// $Id: Auto_IncDec_T.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#ifndef ACE_AUTO_INCDEC_T_CPP -#define ACE_AUTO_INCDEC_T_CPP - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Auto_IncDec_T.h" -#include "ace/Log_Msg.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Auto_IncDec_T.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Auto_IncDec) - -template void -ACE_Auto_IncDec::dump (void) const -{ -#if defined (ACE_HAS_DUMP) -// ACE_TRACE ("ACE_Auto_IncDec::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_AUTO_INCDEC_T_CPP */ diff --git a/externals/ace/Auto_IncDec_T.h b/externals/ace/Auto_IncDec_T.h deleted file mode 100644 index 8fcdb0bcd76..00000000000 --- a/externals/ace/Auto_IncDec_T.h +++ /dev/null @@ -1,91 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Auto_IncDec_T.h - * - * $Id: Auto_IncDec_T.h 84675 2009-03-02 11:44:35Z johnnyw $ - * - * @author Edan Ayal - */ -//============================================================================= - - -#ifndef ACE_AUTO_INCDEC_T_H -#define ACE_AUTO_INCDEC_T_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Global_Macros.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Auto_IncDec - * - * @brief This class automatically increments and decrements a - * parameterized counter. - * - * This data structure is meant to be used within a method, - * function, or scope. The actual parameter given for the - * template parameter - * must provide at least operators ++ and --. - */ -template -class ACE_Auto_IncDec -{ -public: - - /// Implicitly increment the counter. - ACE_Auto_IncDec (ACE_SAFELY_INCREMENTABLE_DECREMENTABLE &counter); - - /// Implicitly decrement the counter. - ~ACE_Auto_IncDec (void); - - /// Dump the state of an object. - void dump (void) const; - -protected: - /// Reference to the counter - /// we're incrementing/decrementing. - ACE_SAFELY_INCREMENTABLE_DECREMENTABLE &counter_; - -private: - // = Prevent assignment and initialization. - ACE_UNIMPLEMENTED_FUNC (void operator= (const - ACE_Auto_IncDec &)) - ACE_UNIMPLEMENTED_FUNC (ACE_Auto_IncDec (const - ACE_Auto_IncDec &)) -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Auto_IncDec_T.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Auto_IncDec_T.cpp" -// On Win32 platforms, this code will be included as template source -// code and will not be inlined. Therefore, we first turn off -// ACE_INLINE, set it to be nothing, include the code, and then turn -// ACE_INLINE back to its original setting. All this nonsense is -// necessary, since the generic template code that needs to be -// specialized cannot be inlined, else the compiler will ignore the -// specialization code. Also, the specialization code *must* be -// inlined or the compiler will ignore the specializations. -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Auto_IncDec_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" - -#endif /* ACE_AUTO_INCDEC_T_H */ diff --git a/externals/ace/Auto_IncDec_T.inl b/externals/ace/Auto_IncDec_T.inl deleted file mode 100644 index e61980e7192..00000000000 --- a/externals/ace/Auto_IncDec_T.inl +++ /dev/null @@ -1,25 +0,0 @@ -// -*- C++ -*- -// -// $Id: Auto_IncDec_T.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Implicitly and automatically increment the counter. - -template ACE_INLINE -ACE_Auto_IncDec::ACE_Auto_IncDec - (ACE_SAFELY_INCREMENTABLE_DECREMENTABLE &counter) - : counter_ (counter) -{ - ++this->counter_; -} - -// Implicitly and automatically decrement the counter. - -template ACE_INLINE -ACE_Auto_IncDec::~ACE_Auto_IncDec (void) -{ - --this->counter_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Auto_Ptr.cpp b/externals/ace/Auto_Ptr.cpp deleted file mode 100644 index 791bd482a23..00000000000 --- a/externals/ace/Auto_Ptr.cpp +++ /dev/null @@ -1,21 +0,0 @@ -// $Id: Auto_Ptr.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#ifndef ACE_AUTO_PTR_CPP -#define ACE_AUTO_PTR_CPP - -#include "ace/Auto_Ptr.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Auto_Ptr.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID(ace, Auto_Ptr, "$Id: Auto_Ptr.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Auto_Basic_Ptr) -ACE_ALLOC_HOOK_DEFINE(ACE_Auto_Basic_Array_Ptr) - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_AUTO_PTR_CPP */ diff --git a/externals/ace/Auto_Ptr.h b/externals/ace/Auto_Ptr.h deleted file mode 100644 index 3183019aceb..00000000000 --- a/externals/ace/Auto_Ptr.h +++ /dev/null @@ -1,242 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file Auto_Ptr.h - * - * $Id: Auto_Ptr.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Doug Schmidt - * @author Irfan Pyarali - * @author Jack Reeves - * @author Dr. Harald M. Mueller - */ -//============================================================================= - -#ifndef ACE_AUTO_PTR_H -#define ACE_AUTO_PTR_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (_MSC_VER) -// Suppress warning e.g. "return type for -// 'ACE_Auto_Array_Pointer::operator ->' is 'type *' (i.e., not a UDT -// or reference to a UDT. Will produce errors if applied using infix -// notation)" -# pragma warning(push) -# pragma warning(disable: 4284) -#endif /* _MSC_VER */ - - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Auto_Basic_Ptr - * - * @brief Implements the draft C++ standard auto_ptr abstraction. - * This class allows one to work on non-object (basic) types - */ -template -class ACE_Auto_Basic_Ptr -{ -public: - typedef X element_type; - - // = Initialization and termination methods - explicit ACE_Auto_Basic_Ptr (X * p = 0) : p_ (p) {} - - ACE_Auto_Basic_Ptr (ACE_Auto_Basic_Ptr & ap); - ACE_Auto_Basic_Ptr &operator= (ACE_Auto_Basic_Ptr & rhs); - ~ACE_Auto_Basic_Ptr (void); - - // = Accessor methods. - X &operator *() const; - X *get (void) const; - X *release (void); - void reset (X * p = 0); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - X *p_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if !defined (ACE_LACKS_AUTO_PTR) && \ - defined (ACE_HAS_STANDARD_CPP_LIBRARY) && \ - (ACE_HAS_STANDARD_CPP_LIBRARY != 0) -#include -#if defined (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB) && \ - (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB != 0) -using std::auto_ptr; -#endif /* ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB */ -#else /* ACE_HAS_STANDARD_CPP_LIBRARY */ - -/** - * @class auto_ptr - * - * @brief Implements the draft C++ standard auto_ptr abstraction. - */ -template -class auto_ptr : public ACE_Auto_Basic_Ptr -{ -public: - typedef X element_type; - - // = Initialization and termination methods - explicit auto_ptr (X * p = 0) : ACE_Auto_Basic_Ptr (p) {} - auto_ptr (auto_ptr & ap) : ACE_Auto_Basic_Ptr (ap.release ()) {} - - X *operator-> () const; -}; - -#endif /* ACE_HAS_STANDARD_CPP_LIBRARY */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @brief Implements the draft C++ standard auto_ptr abstraction. - * This version can be used instead of auto_ptr, and obviates - * the need for the ACE_AUTO_PTR_RESET macro on platforms like - * VC6 where the auto_ptr is broken. - */ -template -class ACE_Auto_Ptr : public ACE_Auto_Basic_Ptr -{ -public: - typedef X element_type; - - // = Initialization and termination methods - explicit ACE_Auto_Ptr (X * p = 0) : ACE_Auto_Basic_Ptr (p) {} - - X *operator-> () const; -}; - -/** - * @class ACE_Auto_Basic_Array_Ptr - * - * @brief Implements an extension to the draft C++ standard auto_ptr - * abstraction. This class allows one to work on non-object - * (basic) types that must be treated as an array, e.g., - * deallocated via "delete [] foo". - */ -template -class ACE_Auto_Basic_Array_Ptr -{ -public: - typedef X element_type; - - // = Initialization and termination methods. - explicit ACE_Auto_Basic_Array_Ptr (X * p = 0) : p_ (p) {} - - ACE_Auto_Basic_Array_Ptr (ACE_Auto_Basic_Array_Ptr & ap); - ACE_Auto_Basic_Array_Ptr &operator= (ACE_Auto_Basic_Array_Ptr & rhs); - ~ACE_Auto_Basic_Array_Ptr (void); - - // = Accessor methods. - X & operator* () const; - X & operator[] (int i) const; - X * get (void) const; - X * release (void); - void reset (X * p = 0); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - X * p_; -}; - -/** - * @class ACE_Auto_Array_Ptr - * - * @brief Implements an extension to the draft C++ standard auto_ptr - * abstraction. - */ -template -class ACE_Auto_Array_Ptr : public ACE_Auto_Basic_Array_Ptr -{ -public: - typedef X element_type; - - // = Initialization and termination methods. - explicit ACE_Auto_Array_Ptr (X *p = 0) - : ACE_Auto_Basic_Array_Ptr (p) {} - - X *operator-> () const; -}; - - -/** - * @brief Reset given @c auto_ptr element to new element. - * - * Some platforms have an older version of auto_ptr support, which - * lacks reset, and cannot be disabled easily. Portability to these - * platforms requires use of this function template. This function - * template also works for the @c ACE_Auto_{Basic_}Array_Ptr class - * template, as well. - */ -template -inline void -ACE_auto_ptr_reset (AUTO_PTR_TYPE & ap, - PTR_TYPE * p) -{ -#if defined (ACE_AUTO_PTR_LACKS_RESET) - // Allow compiler to adjust pointer to potential base class pointer - // of element type found in auto_ptr. - typename AUTO_PTR_TYPE::element_type * const tp = p; - if (tp != ap.get ()) - { - ap = AUTO_PTR_TYPE (tp); - } -#else - ap.reset (p); -#endif /* ACE_AUTO_PTR_LACKS_RESET */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -// Some platforms have an older version of auto_ptr -// support, which lacks reset, and cannot be disabled -// easily. Portability to these platforms requires -// use of the following ACE_AUTO_PTR_RESET macro. -// -// The TYPE macro parameter is no longer necessary but we leave it -// around for backward compatibility. This is also the reason why the -// ACE_auto_ptr_reset function template is not called -// ACE_AUTO_PTR_RESET. -# define ACE_AUTO_PTR_RESET(AUTOPTR,NEWPTR,TYPE) \ - ACE_auto_ptr_reset (AUTOPTR, NEWPTR); - -#if defined (__ACE_INLINE__) -#include "ace/Auto_Ptr.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Auto_Ptr.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Auto_Ptr.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#if defined (_MSC_VER) -// Restore the warning state to what it was before entry. -# pragma warning(pop) -#endif /* _MSC_VER */ - -#include /**/ "ace/post.h" -#endif /* ACE_AUTO_PTR_H */ diff --git a/externals/ace/Auto_Ptr.inl b/externals/ace/Auto_Ptr.inl deleted file mode 100644 index 9ea47c3f208..00000000000 --- a/externals/ace/Auto_Ptr.inl +++ /dev/null @@ -1,171 +0,0 @@ -// -*- C++ -*- -// -// $Id: Auto_Ptr.inl 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Global_Macros.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template ACE_INLINE void -ACE_Auto_Basic_Ptr::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Auto_Basic_Ptr::dump"); -#endif /* ACE_HAS_DUMP */ -} - -template ACE_INLINE void -ACE_Auto_Basic_Array_Ptr::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Auto_Basic_Array_Ptr::dump"); -#endif /* ACE_HAS_DUMP */ -} - -template ACE_INLINE -ACE_Auto_Basic_Ptr::ACE_Auto_Basic_Ptr (ACE_Auto_Basic_Ptr &rhs) - : p_ (rhs.release ()) -{ - ACE_TRACE ("ACE_Auto_Basic_Ptr::ACE_Auto_Basic_Ptr"); -} - -template ACE_INLINE X * -ACE_Auto_Basic_Ptr::get (void) const -{ - ACE_TRACE ("ACE_Auto_Basic_Ptr::get"); - return this->p_; -} - -template ACE_INLINE X * -ACE_Auto_Basic_Ptr::release (void) -{ - ACE_TRACE ("ACE_Auto_Basic_Ptr::release"); - X *old = this->p_; - this->p_ = 0; - return old; -} - -template ACE_INLINE void -ACE_Auto_Basic_Ptr::reset (X *p) -{ - ACE_TRACE ("ACE_Auto_Basic_Ptr::reset"); - if (this->get () != p) - delete this->get (); - this->p_ = p; -} - -template ACE_INLINE ACE_Auto_Basic_Ptr & -ACE_Auto_Basic_Ptr::operator= (ACE_Auto_Basic_Ptr &rhs) -{ - ACE_TRACE ("ACE_Auto_Basic_Ptr::operator="); - if (this != &rhs) - { - this->reset (rhs.release ()); - } - return *this; -} - -template ACE_INLINE -ACE_Auto_Basic_Ptr::~ACE_Auto_Basic_Ptr (void) -{ - ACE_TRACE ("ACE_Auto_Basic_Ptr::~ACE_Auto_Basic_Ptr"); - delete this->get (); -} - -template ACE_INLINE X & -ACE_Auto_Basic_Ptr::operator *() const -{ - ACE_TRACE ("ACE_Auto_Basic_Ptr::operator *()"); - return *this->get (); -} - -#if defined (ACE_LACKS_AUTO_PTR) || \ - !defined (ACE_HAS_STANDARD_CPP_LIBRARY) || \ - (ACE_HAS_STANDARD_CPP_LIBRARY == 0) - -template ACE_INLINE X * -auto_ptr::operator-> () const -{ - ACE_TRACE ("auto_ptr::operator->"); - return this->get (); -} - -#endif /* ACE_HAS_STANDARD_CPP_LIBRARY */ - -template ACE_INLINE X * -ACE_Auto_Ptr::operator-> () const -{ - ACE_TRACE ("ACE_Auto_Ptr::operator->"); - return this->get (); -} - -template ACE_INLINE X * -ACE_Auto_Basic_Array_Ptr::get (void) const -{ - ACE_TRACE ("ACE_Auto_Basic_Array_Ptr::get"); - return this->p_; -} - -template ACE_INLINE X * -ACE_Auto_Basic_Array_Ptr::release (void) -{ - ACE_TRACE ("ACE_Auto_Basic_Array_Ptr::release"); - X *old = this->p_; - this->p_ = 0; - return old; -} - -template ACE_INLINE void -ACE_Auto_Basic_Array_Ptr::reset (X *p) -{ - ACE_TRACE ("ACE_Auto_Basic_Array_Ptr::reset"); - if (this->get () != p) - delete [] this->get (); - this->p_ = p; -} - -template ACE_INLINE -ACE_Auto_Basic_Array_Ptr::ACE_Auto_Basic_Array_Ptr (ACE_Auto_Basic_Array_Ptr &rhs) - : p_ (rhs.release ()) -{ - ACE_TRACE ("ACE_Auto_Basic_Array_Ptr::ACE_Auto_Basic_Array_Ptr"); -} - -template ACE_INLINE ACE_Auto_Basic_Array_Ptr & -ACE_Auto_Basic_Array_Ptr::operator= (ACE_Auto_Basic_Array_Ptr &rhs) -{ - ACE_TRACE ("ACE_Auto_Basic_Array_Ptr::operator="); - if (this != &rhs) - { - this->reset (rhs.release ()); - } - return *this; -} - -template ACE_INLINE -ACE_Auto_Basic_Array_Ptr::~ACE_Auto_Basic_Array_Ptr (void) -{ - ACE_TRACE ("ACE_Auto_Basic_Array_Ptr::~ACE_Auto_Basic_Array_Ptr"); - delete [] this->get (); -} - -template ACE_INLINE X & -ACE_Auto_Basic_Array_Ptr::operator *() const -{ - return *this->get (); -} - -template ACE_INLINE X & -ACE_Auto_Basic_Array_Ptr::operator[](int i) const -{ - X *array = this->get (); - return array[i]; -} - -template ACE_INLINE X * -ACE_Auto_Array_Ptr::operator->() const -{ - return this->get (); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Barrier.cpp b/externals/ace/Barrier.cpp deleted file mode 100644 index 29e7422600c..00000000000 --- a/externals/ace/Barrier.cpp +++ /dev/null @@ -1,196 +0,0 @@ -// $Id: Barrier.cpp 84282 2009-01-30 15:04:29Z msmit $ - -#include "ace/Barrier.h" - -#if defined (ACE_HAS_THREADS) - -#if !defined (__ACE_INLINE__) -#include "ace/Barrier.inl" -#endif /* __ACE_INLINE__ */ - -#include "ace/Guard_T.h" -#include "ace/OS_NS_errno.h" - -#if defined (ACE_HAS_DUMP) -# include "ace/Log_Msg.h" -#endif /* ACE_HAS_DUMP */ - -ACE_RCSID (ace, - Barrier, - "$Id: Barrier.cpp 84282 2009-01-30 15:04:29Z msmit $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Sub_Barrier) - -void -ACE_Sub_Barrier::dump (void) const -{ -#if defined (ACE_HAS_DUMP) -// ACE_TRACE ("ACE_Sub_Barrier::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - this->barrier_finished_.dump (); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("running_threads_ = %d\n"), this->running_threads_)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -ACE_Sub_Barrier::ACE_Sub_Barrier (unsigned int count, - ACE_Thread_Mutex &lock, - const ACE_TCHAR *name, - void *arg) - : barrier_finished_ (lock, name, arg), - running_threads_ (count) -{ -// ACE_TRACE ("ACE_Sub_Barrier::ACE_Sub_Barrier"); -} - -ACE_ALLOC_HOOK_DEFINE(ACE_Barrier) - -void -ACE_Barrier::dump (void) const -{ -#if defined (ACE_HAS_DUMP) -// ACE_TRACE ("ACE_Barrier::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - this->lock_.dump (); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("current_generation_ = %d"), this->current_generation_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ncount_ = %d"), this->count_)); - this->sub_barrier_1_.dump (); - this->sub_barrier_2_.dump (); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -ACE_Barrier::ACE_Barrier (unsigned int count, - const ACE_TCHAR *name, - void *arg) - : lock_ (name, (ACE_mutexattr_t *) arg), - current_generation_ (0), - count_ (count), - sub_barrier_1_ (count, lock_, name, arg), - sub_barrier_2_ (count, lock_, name, arg) -{ - ACE_TRACE ("ACE_Barrier::ACE_Barrier"); - this->sub_barrier_[0] = &this->sub_barrier_1_; - this->sub_barrier_[1] = &this->sub_barrier_2_; -} - -int -ACE_Barrier::wait (void) -{ - ACE_TRACE ("ACE_Barrier::wait"); - ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1); - - ACE_Sub_Barrier *sbp = - this->sub_barrier_[this->current_generation_]; - - // Check for shutdown... - if (sbp == 0) - { - errno = ESHUTDOWN; - return -1; - } - - int retval = 0; - - if (sbp->running_threads_ == 1) - { - // We're the last running thread, so swap generations and tell - // all the threads waiting on the barrier to continue on their - // way. - sbp->running_threads_ = this->count_; - // Swap generations. - this->current_generation_ = 1 - this->current_generation_; - sbp->barrier_finished_.broadcast (); - } - else - { - --sbp->running_threads_; - - // Block until all the other threads wait(). - while (sbp->running_threads_ != this->count_) - sbp->barrier_finished_.wait (); - - // We're awake and the count has completed. See if it completed - // because all threads hit the barrier, or because the barrier - // was shut down. - if (this->sub_barrier_[this->current_generation_] == 0) - { - errno = ESHUTDOWN; - retval = -1; - } - } - - return retval; -} - -int -ACE_Barrier::shutdown (void) -{ - ACE_TRACE ("ACE_Barrier::shutdown"); - ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1); - - ACE_Sub_Barrier *sbp = - this->sub_barrier_[this->current_generation_]; - - // Check for shutdown... - if (sbp == 0) - { - errno = ESHUTDOWN; - return -1; - } - - // Flag the shutdown - this->sub_barrier_[0] = 0; - this->sub_barrier_[1] = 0; - // Tell all the threads waiting on the barrier to continue on their way. - sbp->running_threads_ = this->count_; - sbp->barrier_finished_.broadcast (); - - return 0; -} - -ACE_ALLOC_HOOK_DEFINE(ACE_Thread_Barrier) - -ACE_Thread_Barrier::ACE_Thread_Barrier (unsigned int count, - const ACE_TCHAR *name) - : ACE_Barrier (count, name) -{ -// ACE_TRACE ("ACE_Thread_Barrier::ACE_Thread_Barrier"); -} - -void -ACE_Thread_Barrier::dump (void) const -{ -#if defined (ACE_HAS_DUMP) -// ACE_TRACE ("ACE_Thread_Barrier::dump"); - ACE_Barrier::dump (); -#endif /* ACE_HAS_DUMP */ -} - -#if 0 -ACE_ALLOC_HOOK_DEFINE(ACE_Process_Barrier) - -ACE_Process_Barrier::ACE_Process_Barrier (u_int count, - const ACE_TCHAR *name) - : ACE_Barrier (count, USYNC_PROCESS, name) -{ -// ACE_TRACE ("ACE_Process_Barrier::ACE_Process_Barrier"); -} - -void -ACE_Process_Barrier::dump (void) const -{ -#if defined (ACE_HAS_DUMP) -// ACE_TRACE ("ACE_Process_Barrier::dump"); - ACE_Barrier::dump (); -#endif /* ACE_HAS_DUMP */ -} -#endif /* 0 */ - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_THREADS */ diff --git a/externals/ace/Barrier.h b/externals/ace/Barrier.h deleted file mode 100644 index 189ff07e4cc..00000000000 --- a/externals/ace/Barrier.h +++ /dev/null @@ -1,215 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file Barrier.h - * - * $Id: Barrier.h 80826 2008-03-04 14:51:23Z wotte $ - * - * Moved from Synch.h. - * - * @author Douglas C. Schmidt - */ -//========================================================================== - -#ifndef ACE_BARRIER_H -#define ACE_BARRIER_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include /**/ "ace/config-all.h" - -// ACE platform supports some form of threading. -#if !defined (ACE_HAS_THREADS) - -#include "ace/OS_NS_errno.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Barrier - * - * @brief This is a no-op to make ACE "syntactically consistent." - */ -class ACE_Export ACE_Barrier -{ -public: - ACE_Barrier (unsigned int, const ACE_TCHAR * = 0, void * = 0) {} - ~ACE_Barrier (void) {} - int wait (void) { ACE_NOTSUP_RETURN (-1); } - void dump (void) const {} -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#else /* ACE_HAS_THREADS */ - -#include "ace/Condition_Thread_Mutex.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -struct ACE_Export ACE_Sub_Barrier -{ - // = Initialization. - ACE_Sub_Barrier (unsigned int count, - ACE_Thread_Mutex &lock, - const ACE_TCHAR *name = 0, - void *arg = 0); - - ~ACE_Sub_Barrier (void); - - /// True if this generation of the barrier is done. - ACE_Condition_Thread_Mutex barrier_finished_; - - /// Number of threads that are still running. - int running_threads_; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; -}; - -/** - * @class ACE_Barrier - * - * @brief Implements "barrier synchronization". - * - * This class allows number of threads to synchronize - * their completion of (one round of) a task, which is known as - * "barrier synchronization". After all the threads call - * on the barrier they are all atomically released and can begin a new - * round. - * - * This implementation uses a "sub-barrier generation numbering" - * scheme to avoid overhead and to ensure that all threads wait to - * leave the barrier correct. This code is based on an article from - * SunOpsis Vol. 4, No. 1 by Richard Marejka - * (Richard.Marejka@canada.sun.com). - */ -class ACE_Export ACE_Barrier -{ -public: - /// Initialize the barrier to synchronize @a count threads. - ACE_Barrier (unsigned int count, - const ACE_TCHAR *name = 0, - void *arg = 0); - - /// Default dtor. - ~ACE_Barrier (void); - - /// Block the caller until all @c count threads have called @c wait and - /// then allow all the caller threads to continue in parallel. - /// - /// @retval 0 after successfully waiting for all threads to wait. - /// @retval -1 if an error occurs or the barrier is shut - /// down (@sa shutdown ()). - int wait (void); - - /// Shut the barrier down, aborting the wait of all waiting threads. - /// Any threads waiting on the barrier when it is shut down will return with - /// value -1, errno ESHUTDOWN. - /// - /// @retval 0 for success, -1 if already shut down. - /// - /// @since ACE beta 5.4.9. - int shutdown (void); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - /// Serialize access to the barrier state. - ACE_Thread_Mutex lock_; - - /// Either 0 or 1, depending on whether we are the first generation - /// of waiters or the next generation of waiters. - int current_generation_; - - /// Total number of threads that can be waiting at any one time. - int count_; - - /** - * We keep two @c sub_barriers, one for the first "generation" of - * waiters, and one for the next "generation" of waiters. This - * efficiently solves the problem of what to do if all the first - * generation waiters don't leave the barrier before one of the - * threads calls wait() again (i.e., starts up the next generation - * barrier). - */ - ACE_Sub_Barrier sub_barrier_1_; - ACE_Sub_Barrier sub_barrier_2_; - ACE_Sub_Barrier *sub_barrier_[2]; - -private: - // = Prevent assignment and initialization. - void operator= (const ACE_Barrier &); - ACE_Barrier (const ACE_Barrier &); -}; - -#if 0 -/** - * @class ACE_Process_Barrier - * - * @brief Implements "barrier synchronization" using ACE_Process_Mutexes! - * - * This class is just a simple wrapper for ACE_Barrier that - * selects the USYNC_PROCESS variant for the locks. - */ -class ACE_Export ACE_Process_Barrier : public ACE_Barrier -{ -public: - /// Create a Process_Barrier, passing in the optional @a name. - ACE_Process_Barrier (unsigned int count, const ACE_TCHAR *name = 0); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; -}; -#endif /* 0 */ - -/** - * @class ACE_Thread_Barrier - * - * @brief Implements "barrier synchronization" using ACE_Thread_Mutexes! - * - * This class is just a simple wrapper for ACE_Barrier that - * selects the USYNC_THREAD variant for the locks. - */ -class ACE_Export ACE_Thread_Barrier : public ACE_Barrier -{ -public: - /// Create a Thread_Barrier, passing in the optional @a name. - ACE_Thread_Barrier (unsigned int count, const ACE_TCHAR *name = 0); - - /// Default dtor. - ~ACE_Thread_Barrier (void); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Barrier.inl" -#endif /* __ACE_INLINE__ */ - -#endif /* !ACE_HAS_THREADS */ - -#include /**/ "ace/post.h" -#endif /* ACE_BARRIER_H */ diff --git a/externals/ace/Barrier.inl b/externals/ace/Barrier.inl deleted file mode 100644 index 10430d917a3..00000000000 --- a/externals/ace/Barrier.inl +++ /dev/null @@ -1,22 +0,0 @@ -// -*- C++ -*- -// -// $Id: Barrier.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE -ACE_Sub_Barrier::~ACE_Sub_Barrier (void) -{ -} - -ACE_INLINE -ACE_Barrier::~ACE_Barrier (void) -{ -} - -ACE_INLINE -ACE_Thread_Barrier::~ACE_Thread_Barrier (void) -{ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Base_Thread_Adapter.cpp b/externals/ace/Base_Thread_Adapter.cpp deleted file mode 100644 index eac2c14903c..00000000000 --- a/externals/ace/Base_Thread_Adapter.cpp +++ /dev/null @@ -1,128 +0,0 @@ -// $Id: Base_Thread_Adapter.cpp 84340 2009-02-05 22:28:08Z stallions $ - -#include "ace/Base_Thread_Adapter.h" - -ACE_RCSID (ace, - Base_Thread_Adapter, - "$Id: Base_Thread_Adapter.cpp 84340 2009-02-05 22:28:08Z stallions $") - -#if !defined (ACE_HAS_INLINED_OSCALLS) -# include "ace/Base_Thread_Adapter.inl" -#endif /* ACE_HAS_INLINED_OSCALLS */ - -#if defined (ACE_HAS_TSS_EMULATION) -# include "ace/OS_NS_Thread.h" -#endif /* ACE_HAS_TSS_EMULATION */ - -#include "ace/Service_Config.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INIT_LOG_MSG_HOOK ACE_Base_Thread_Adapter::init_log_msg_hook_ = 0; -ACE_INHERIT_LOG_MSG_HOOK ACE_Base_Thread_Adapter::inherit_log_msg_hook_ = 0; -ACE_CLOSE_LOG_MSG_HOOK ACE_Base_Thread_Adapter::close_log_msg_hook_ = 0; -ACE_SYNC_LOG_MSG_HOOK ACE_Base_Thread_Adapter::sync_log_msg_hook_ = 0; -ACE_THR_DESC_LOG_MSG_HOOK ACE_Base_Thread_Adapter::thr_desc_log_msg_hook_ = 0; - -ACE_Base_Thread_Adapter::ACE_Base_Thread_Adapter ( - ACE_THR_FUNC user_func, - void *arg, - ACE_THR_C_FUNC entry_point, - ACE_OS_Thread_Descriptor *td -#if defined (ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS) - , ACE_SEH_EXCEPT_HANDLER selector - , ACE_SEH_EXCEPT_HANDLER handler -#endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */ - ) - : user_func_ (user_func) - , arg_ (arg) - , entry_point_ (entry_point) - , thr_desc_ (td) - , ctx_ (ACE_Service_Config::current()) -{ - ACE_OS_TRACE ("ACE_Base_Thread_Adapter::ACE_Base_Thread_Adapter"); - - if (ACE_Base_Thread_Adapter::init_log_msg_hook_ != 0) - (*ACE_Base_Thread_Adapter::init_log_msg_hook_) ( - this->log_msg_attributes_ -# if defined (ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS) - , selector - , handler -# endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */ - ); -#ifdef ACE_USES_GPROF - getitimer (ITIMER_PROF, &itimer_); -#endif // ACE_USES_GPROF -} - -ACE_Base_Thread_Adapter::~ACE_Base_Thread_Adapter (void) -{ -} - -void -ACE_Base_Thread_Adapter::inherit_log_msg (void) -{ - if (ACE_Base_Thread_Adapter::inherit_log_msg_hook_ != 0) - (*ACE_Base_Thread_Adapter::inherit_log_msg_hook_)( - this->thr_desc_, - this->log_msg_attributes_); - - // Initialize the proper configuration context for the new thread - // Placed here since inherit_log_msg() gets called from any of our - // descendants (before self-destructing) - ACE_Service_Config::current (this->ctx_); -} - -void -ACE_Base_Thread_Adapter::close_log_msg (void) -{ - if (ACE_Base_Thread_Adapter::close_log_msg_hook_ != 0) - (*ACE_Base_Thread_Adapter::close_log_msg_hook_) (); -} - -void -ACE_Base_Thread_Adapter::sync_log_msg (const ACE_TCHAR *prg) -{ - if (ACE_Base_Thread_Adapter::sync_log_msg_hook_ != 0) - (*ACE_Base_Thread_Adapter::sync_log_msg_hook_) (prg); -} - -ACE_OS_Thread_Descriptor * -ACE_Base_Thread_Adapter::thr_desc_log_msg (void) -{ - if (ACE_Base_Thread_Adapter::thr_desc_log_msg_hook_ != 0) - return (*ACE_Base_Thread_Adapter::thr_desc_log_msg_hook_) (); - return 0; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -// Run the thread entry point for the . This must -// be an extern "C" to make certain compilers happy... - -extern "C" ACE_THR_FUNC_RETURN -ACE_THREAD_ADAPTER_NAME (void *args) -{ - ACE_OS_TRACE ("ACE_THREAD_ADAPTER_NAME"); - -#if defined (ACE_HAS_TSS_EMULATION) - // As early as we can in the execution of the new thread, allocate - // its local TS storage. Allocate it on the stack, to save dynamic - // allocation/dealloction. - void *ts_storage[ACE_TSS_Emulation::ACE_TSS_THREAD_KEYS_MAX]; - ACE_TSS_Emulation::tss_open (ts_storage); -#endif /* ACE_HAS_TSS_EMULATION */ - - ACE_Base_Thread_Adapter * const thread_args = - static_cast (args); - -#ifdef ACE_USES_GPROF - setitimer (ITIMER_PROF, thread_args->timerval (), 0); -#endif // ACE_USES_GPROF - - // Invoke the user-supplied function with the args. - ACE_THR_FUNC_RETURN status = thread_args->invoke (); - - return status; -} - diff --git a/externals/ace/Base_Thread_Adapter.h b/externals/ace/Base_Thread_Adapter.h deleted file mode 100644 index b36d18e4f13..00000000000 --- a/externals/ace/Base_Thread_Adapter.h +++ /dev/null @@ -1,195 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Base_Thread_Adapter.h - * - * $Id: Base_Thread_Adapter.h 81239 2008-04-04 22:28:48Z iliyan $ - * - * @author Nanbor Wang - */ -//============================================================================= - -#ifndef ACE_BASE_THREAD_ADAPTER_H -#define ACE_BASE_THREAD_ADAPTER_H -#include /**/ "ace/pre.h" - -#include "ace/OS_Log_Msg_Attributes.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include /**/ "ace/ACE_export.h" -#include "ace/OS_Log_Msg_Attributes.h" - -#ifdef ACE_USES_GPROF -#include "os_include/sys/os_time.h" -#endif // ACE_USES_GPROF - -#if (defined (ACE_HAS_VERSIONED_NAMESPACE) && ACE_HAS_VERSIONED_NAMESPACE == 1) -# define ACE_THREAD_ADAPTER_NAME ACE_PREPROC_CONCATENATE(ACE_VERSIONED_NAMESPACE_NAME, _ace_thread_adapter) -#else -# define ACE_THREAD_ADAPTER_NAME ace_thread_adapter -#endif /* ACE_HAS_VERSIONED_NAMESPACE == 1 */ - -// Run the thread entry point for the ACE_Thread_Adapter. This must -// be an extern "C" to make certain compilers happy... - -extern "C" ACE_Export ACE_THR_FUNC_RETURN ACE_THREAD_ADAPTER_NAME (void *args); - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_OS_Thread_Descriptor - * - * @brief Parent class of all ACE_Thread_Descriptor classes. - * = - * Container for ACE_Thread_Descriptor members that are - * used in ACE_OS. - */ -class ACE_Export ACE_OS_Thread_Descriptor -{ -public: - /// Get the thread creation flags. - long flags (void) const; - -protected: - /// For use by ACE_Thread_Descriptor. - ACE_OS_Thread_Descriptor (long flags = 0); - - /** - * Keeps track of whether this thread was created "detached" or not. - * If a thread is *not* created detached then if someone calls - * , we need to join with that thread (and - * close down the handle). - */ - long flags_; -}; - - - -class ACE_Service_Gestalt; - - -/** - * @class ACE_Base_Thread_Adapter - * - * @brief Base class for all the Thread_Adapters. - * - * Converts a C++ function into a function that can be - * called from a thread creation routine - * (e.g., pthread_create() or _beginthreadex()) that expects an - * extern "C" entry point. This class also makes it possible to - * transparently provide hooks to register a thread with an - * ACE_Thread_Manager. - * This class is used in ACE_OS::thr_create(). In general, the - * thread that creates an object of this class is different from - * the thread that calls @c invoke() on this object. Therefore, - * the @c invoke() method is responsible for deleting itself. - */ -class ACE_Export ACE_Base_Thread_Adapter -{ -public: - - virtual ~ACE_Base_Thread_Adapter (void); - - /// Virtual method invoked by the thread entry point. - virtual ACE_THR_FUNC_RETURN invoke (void) = 0; - - /// Accessor for the C entry point function to the OS thread creation - /// routine. - ACE_THR_C_FUNC entry_point (void); - -#ifdef ACE_USES_GPROF - /// Accessor to the itimer_ - /// followed http://sam.zoy.org/writings/programming/gprof.html - struct itimerval* timerval (void); -#endif // ACE_USES_PROF - - /// Invoke the close_log_msg_hook, if it is present - static void close_log_msg (void); - - /// Invoke the sync_log_msg_hook, if it is present - static void sync_log_msg (const ACE_TCHAR *prog_name); - - /// Invoke the thr_desc_log_msg_hook, if it is present - static ACE_OS_Thread_Descriptor *thr_desc_log_msg (void); - -protected: - /// Constructor. - ACE_Base_Thread_Adapter (ACE_THR_FUNC user_func, - void *arg, - ACE_THR_C_FUNC entry_point = (ACE_THR_C_FUNC) ACE_THREAD_ADAPTER_NAME, - ACE_OS_Thread_Descriptor *td = 0 -# if defined (ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS) - , ACE_SEH_EXCEPT_HANDLER selector = 0 - , ACE_SEH_EXCEPT_HANDLER handler = 0 -# endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */ - ); - /// Inherit the logging features if the parent thread has an - /// ACE_Log_Msg. - void inherit_log_msg (void); - -private: - /// The hooks to inherit and cleanup the Log_Msg attributes - static ACE_INIT_LOG_MSG_HOOK init_log_msg_hook_; - static ACE_INHERIT_LOG_MSG_HOOK inherit_log_msg_hook_; - static ACE_CLOSE_LOG_MSG_HOOK close_log_msg_hook_; - static ACE_SYNC_LOG_MSG_HOOK sync_log_msg_hook_; - static ACE_THR_DESC_LOG_MSG_HOOK thr_desc_log_msg_hook_; - - /// Set the Log_Msg hooks - static void set_log_msg_hooks (ACE_INIT_LOG_MSG_HOOK init_hook, - ACE_INHERIT_LOG_MSG_HOOK inherit_hook, - ACE_CLOSE_LOG_MSG_HOOK close_hook, - ACE_SYNC_LOG_MSG_HOOK sync_hook, - ACE_THR_DESC_LOG_MSG_HOOK thr_desc); - - /// Allow the ACE_Log_Msg class to set its hooks. - friend class ACE_Log_Msg; - -protected: - /// Thread startup function passed in by the user (C++ linkage). - ACE_THR_FUNC user_func_; - - /// Argument to thread startup function. - void *arg_; - - /// Entry point to the underlying OS thread creation call (C - /// linkage). - ACE_THR_C_FUNC entry_point_; - - /** - * Optional thread descriptor. Passing this pointer in will force - * the spawned thread to cache this location in and wait - * until fills in all information in thread - * descriptor. - */ - ACE_OS_Thread_Descriptor *thr_desc_; - - /// The ACE_Log_Msg attributes. - ACE_OS_Log_Msg_Attributes log_msg_attributes_; - - /// That is usefull for gprof, define itimerval -#ifdef ACE_USES_GPROF - struct itimerval itimer_; -#endif // ACE_USES_GPROF - - /// Keep a reference to the configuration context that spawns the - /// thread so the child can inherit it. - ACE_Service_Gestalt * const ctx_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -# if defined (ACE_HAS_INLINED_OSCALLS) -# if defined (ACE_INLINE) -# undef ACE_INLINE -# endif /* ACE_INLINE */ -# define ACE_INLINE inline -# include "ace/Base_Thread_Adapter.inl" -# endif /* ACE_HAS_INLINED_OSCALLS */ - -#include /**/ "ace/post.h" -#endif /* ACE_BASE_THREAD_ADAPTER_H */ diff --git a/externals/ace/Base_Thread_Adapter.inl b/externals/ace/Base_Thread_Adapter.inl deleted file mode 100644 index 3bac80246dd..00000000000 --- a/externals/ace/Base_Thread_Adapter.inl +++ /dev/null @@ -1,48 +0,0 @@ -// -*- C++ -*- -// -// $Id: Base_Thread_Adapter.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE long -ACE_OS_Thread_Descriptor::flags (void) const -{ - return flags_; -} - -ACE_INLINE -ACE_OS_Thread_Descriptor::ACE_OS_Thread_Descriptor (long flags) - : flags_ (flags) -{ -} - -ACE_INLINE void -ACE_Base_Thread_Adapter::set_log_msg_hooks ( - ACE_INIT_LOG_MSG_HOOK init_hook, - ACE_INHERIT_LOG_MSG_HOOK inherit_hook, - ACE_CLOSE_LOG_MSG_HOOK close_hook, - ACE_SYNC_LOG_MSG_HOOK sync_hook, - ACE_THR_DESC_LOG_MSG_HOOK thr_desc_hook) -{ - ACE_Base_Thread_Adapter::init_log_msg_hook_ = init_hook; - ACE_Base_Thread_Adapter::inherit_log_msg_hook_ = inherit_hook; - ACE_Base_Thread_Adapter::close_log_msg_hook_ = close_hook; - ACE_Base_Thread_Adapter::sync_log_msg_hook_ = sync_hook; - ACE_Base_Thread_Adapter::thr_desc_log_msg_hook_ = thr_desc_hook; -} - -ACE_INLINE ACE_THR_C_FUNC -ACE_Base_Thread_Adapter::entry_point (void) -{ - return this->entry_point_; -} - -#ifdef ACE_USES_GPROF -ACE_INLINE itimerval* -ACE_Base_Thread_Adapter::timerval (void) -{ - return &(this->itimer_); -} -#endif // ACE_USES_GPROF - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Based_Pointer_Repository.cpp b/externals/ace/Based_Pointer_Repository.cpp deleted file mode 100644 index 4ebe8b82c7a..00000000000 --- a/externals/ace/Based_Pointer_Repository.cpp +++ /dev/null @@ -1,119 +0,0 @@ -// $Id: Based_Pointer_Repository.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Map_Manager.h" -#include "ace/Based_Pointer_Repository.h" -#include "ace/Guard_T.h" -#include "ace/Null_Mutex.h" -#include "ace/Synch_Traits.h" -#include "ace/RW_Thread_Mutex.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Based_Pointer_Repository_Rep - * - * @brief Implementation for the ACE_Based_Pointer_Repository. - * - * Every memory pool in ACE binds it's mapping base address and - * the mapped size to this repository every time it maps/remaps a - * new chunk of memory successfully. - */ -class ACE_Based_Pointer_Repository_Rep -{ -public: - // Useful typedefs. - typedef ACE_Map_Manager MAP_MANAGER; - typedef ACE_Map_Iterator MAP_ITERATOR; - typedef ACE_Map_Entry MAP_ENTRY; - - /// Keeps track of the mapping between addresses and their associated - /// values. - MAP_MANAGER addr_map_; - - /// Synchronize concurrent access to the map. - ACE_SYNCH_MUTEX lock_; -}; - -ACE_Based_Pointer_Repository::ACE_Based_Pointer_Repository (void) -{ - ACE_TRACE ("ACE_Based_Pointer_Repository::ACE_Based_Pointer_Repository"); - ACE_NEW (this->rep_, - ACE_Based_Pointer_Repository_Rep); -} - -ACE_Based_Pointer_Repository::~ACE_Based_Pointer_Repository (void) -{ - ACE_TRACE ("ACE_Based_Pointer_Repository::~ACE_Based_Pointer_Repository"); - delete this->rep_; -} - -// Search for appropriate base address in repository - -int -ACE_Based_Pointer_Repository::find (void *addr, void *&base_addr) -{ - ACE_TRACE ("ACE_Based_Pointer_Repository::find"); - ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, mon, this->rep_->lock_, -1); - ACE_Based_Pointer_Repository_Rep::MAP_ENTRY *ce = 0; - - for (ACE_Based_Pointer_Repository_Rep::MAP_ITERATOR iter (this->rep_->addr_map_); - iter.next (ce) != 0; - iter.advance ()) - // Check to see if is within any of the regions. - if (addr >= ce->ext_id_ - && addr < ((char *)ce->ext_id_ + ce->int_id_)) - { - // Assign the base address. - base_addr = ce->ext_id_; - return 1; - } - - // Assume base address 0 (e.g., if new'ed). - base_addr = 0; - return 0; -} - -// Bind a new entry to the repository or update the size of an -// existing entry. - -int -ACE_Based_Pointer_Repository::bind (void *addr, size_t size) -{ - ACE_TRACE ("ACE_Based_Pointer_Repository::bind"); - ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, mon, this->rep_->lock_, -1); - - return this->rep_->addr_map_.rebind (addr, size); -} - -// Unbind a base from the repository. - -int -ACE_Based_Pointer_Repository::unbind (void *addr) -{ - ACE_TRACE ("ACE_Based_Pointer_Repository::unbind"); - ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, mon, this->rep_->lock_, -1); - ACE_Based_Pointer_Repository_Rep::MAP_ENTRY *ce = 0; - - // Search for service handlers that requested notification. - - for (ACE_Based_Pointer_Repository_Rep::MAP_ITERATOR iter (this->rep_->addr_map_); - iter.next (ce) != 0; - iter.advance ()) - { - // Check to see if is within any of the regions and if - // so, unbind the key from the map. - if (addr >= ce->ext_id_ - && addr < ((char *)ce->ext_id_ + ce->int_id_)) - // Unbind base address. - return this->rep_->addr_map_.unbind (ce->ext_id_); - } - - return 0; -} - -#if defined (ACE_HAS_EXPLICIT_STATIC_TEMPLATE_MEMBER_INSTANTIATION) -template ACE_Singleton * - ACE_Singleton::singleton_; -#endif /* ACE_HAS_EXPLICIT_STATIC_TEMPLATE_MEMBER_INSTANTIATION */ - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Based_Pointer_Repository.h b/externals/ace/Based_Pointer_Repository.h deleted file mode 100644 index d549ce15326..00000000000 --- a/externals/ace/Based_Pointer_Repository.h +++ /dev/null @@ -1,94 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Based_Pointer_Repository.h - * - * $Id: Based_Pointer_Repository.h 84837 2009-03-16 13:01:15Z johnnyw $ - * - * @author Dietrich Quehl - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_BASED_POINTER_REPOSITORY_H -#define ACE_BASED_POINTER_REPOSITORY_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Singleton.h" -#include "ace/Synch_Traits.h" -#include "ace/os_include/os_stddef.h" - - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Forward decl., using the "Cheshire Cat" technique. -class ACE_Based_Pointer_Repository_Rep; - -/** - * @class ACE_Based_Pointer_Repository - * - * @brief Maps pointers to the base address of the region to which each - * pointer belongs. - */ -class ACE_Export ACE_Based_Pointer_Repository -{ -public: - // = Use ACE_Null_Mutex to allow locking while iterating. - - // = Initialization and termination methods. - ACE_Based_Pointer_Repository (void); - ~ACE_Based_Pointer_Repository (void); - - // = Search structure methods. - /** - * Return the appropriate @a base_addr region that contains @a addr. - * Returns 1 on success and 0 if the @a addr isn't contained in any - * @a base_addr region. - */ - int find (void *addr, - void *&base_addr); - - /// Bind a new entry to the repository or update the size of an - /// existing entry. Returns 0 on success and -1 on failure. - int bind (void *addr, - size_t size); - - /// Unbind from the repository the that @a addr is - /// contained within. - int unbind (void *addr); - -private: - - /// Use the "Cheshire-Cat" technique to hide the implementation in - /// order to avoid circular #include dependencies. - ACE_Based_Pointer_Repository_Rep *rep_; - -private: - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Based_Pointer_Repository &)) - ACE_UNIMPLEMENTED_FUNC (ACE_Based_Pointer_Repository (const ACE_Based_Pointer_Repository &)) -}; - -// ---------------------------------- - -/// Declare a process wide singleton -ACE_SINGLETON_DECLARE (ACE_Singleton, - ACE_Based_Pointer_Repository, - ACE_SYNCH_RW_MUTEX) - -/// Provide a Singleton access point to the based pointer repository. -typedef ACE_Singleton - ACE_BASED_POINTER_REPOSITORY; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" - -#endif /* ACE_BASED_POINTER_REPOSITORY_H */ diff --git a/externals/ace/Based_Pointer_T.cpp b/externals/ace/Based_Pointer_T.cpp deleted file mode 100644 index b85774db48d..00000000000 --- a/externals/ace/Based_Pointer_T.cpp +++ /dev/null @@ -1,121 +0,0 @@ -// $Id: Based_Pointer_T.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#ifndef ACE_BASED_POINTER_T_CPP -#define ACE_BASED_POINTER_T_CPP - -#include "ace/Based_Pointer_T.h" -#include "ace/Based_Pointer_Repository.h" -#include "ace/Log_Msg.h" - -# define ACE_TRACEX(X) ACE_Trace ____ (ACE_TEXT (X), __LINE__, ACE_TEXT (__FILE__)) - -#if !defined (__ACE_INLINE__) -#include "ace/Based_Pointer_T.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template -ACE_Based_Pointer::ACE_Based_Pointer (void) -{ - ACE_TRACE ("ACE_Based_Pointer::ACE_Based_Pointer"); -} - -template void -ACE_Based_Pointer_Basic::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Based_Pointer_Basic::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ntarget_ = %d\n"), this->target_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("base_offset_ = %d\n"), this->base_offset_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("computed pointer = %x\n"), - (CONCRETE *)(ACE_COMPUTE_BASED_POINTER (this)))); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -template -ACE_Based_Pointer::ACE_Based_Pointer (CONCRETE *initial) - : ACE_Based_Pointer_Basic (initial) -{ - ACE_TRACE ("ACE_Based_Pointer_Basic::ACE_Based_Pointer_Basic"); -} - -template -ACE_Based_Pointer::ACE_Based_Pointer (const void* base_addr, int) - : ACE_Based_Pointer_Basic (base_addr, 0) -{ - ACE_TRACE ("ACE_Based_Pointer_Basic::ACE_Based_Pointer_Basic"); -} - -template -ACE_Based_Pointer_Basic::ACE_Based_Pointer_Basic (void) - : target_ (0), - base_offset_ (0) -{ - ACE_TRACE ("ACE_Based_Pointer_Basic::ACE_Based_Pointer_Basic"); - void *base_addr = 0; - - // Find the base address associated with our pointer. Note - // that it's ok for to return 0, which simply indicates that - // the address is not in memory-mapped virtual address space. - ACE_BASED_POINTER_REPOSITORY::instance ()->find (this, - base_addr); - this->base_offset_ = (char *) this - (char *) base_addr; -} - -template -ACE_Based_Pointer_Basic::ACE_Based_Pointer_Basic (const void *base_addr, int) - : target_ (0), - base_offset_ (0) -{ - ACE_TRACE ("ACE_Based_Pointer_Basic::ACE_Based_Pointer_Basic"); - this->base_offset_ = (char *) this - (char *) base_addr; -} - -template -ACE_Based_Pointer_Basic::ACE_Based_Pointer_Basic (CONCRETE *rhs) - : target_ (0), - base_offset_ (0) -{ - ACE_TRACE ("ACE_Based_Pointer_Basic::ACE_Based_Pointer_Basic"); - - if (rhs == 0) - // Store a value of that indicate "NULL" pointer. - this->target_ = -1; - else - { - void *base_addr = 0; - - // Find the base address associated with the pointer. - // Note that it's ok for to return 0, which simply - // indicates that the address is not in memory-mapped virtual - // address space. - ACE_BASED_POINTER_REPOSITORY::instance ()->find (this, - base_addr); - this->base_offset_ = (char *) this - (char *) base_addr; - this->target_ = ((char *) rhs - (char *) base_addr); - } -} - -template -ACE_Based_Pointer_Basic::ACE_Based_Pointer_Basic (const ACE_Based_Pointer_Basic &) -{ - ACE_TRACE ("ACE_Based_Pointer_Basic::ACE_Based_Pointer_Basic"); - - ACE_ASSERT (0); // not implemented. -} - -template -ACE_Based_Pointer::ACE_Based_Pointer (const ACE_Based_Pointer &rhs) - : ACE_Based_Pointer_Basic (rhs) -{ - ACE_TRACE ("ACE_Based_Pointer::ACE_Based_Pointer"); - ACE_ASSERT (0); // not implemented. -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_BASED_POINTER_T_CPP */ diff --git a/externals/ace/Based_Pointer_T.h b/externals/ace/Based_Pointer_T.h deleted file mode 100644 index 802e73ca0d3..00000000000 --- a/externals/ace/Based_Pointer_T.h +++ /dev/null @@ -1,205 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Based_Pointer_T.h - * - * $Id: Based_Pointer_T.h 81705 2008-05-15 14:02:02Z johnnyw $ - * - * @author Dietrich Quehl - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_BASED_POINTER_T_H -#define ACE_BASED_POINTER_T_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" -#include "ace/Basic_Types.h" - -#if defined (_MSC_VER) -// Suppress warning e.g. "return type for -// 'ACE_Based_Pointer::operator ->' is 'long *' (i.e., not a UDT -// or reference to a UDT. Will produce errors if applied using infix -// notation)" -#pragma warning(disable: 4284) -#endif /* _MSC_VER */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Based_Pointer_Basic - * - * @brief A proxy that keeps track of the relative offset of a "pointer" - * from its base address. - * This class makes it possible to transparently use "pointers" in - * shared memory as easily as programming with pointers to local - * memory. In particular, we don't need to ensure that the base - * addresses of all the pointers are mapped into separate - * processes at the same absolute memory base address. - */ -template -class ACE_Based_Pointer_Basic -{ -public: - /** - * This constructor initializes the by asking the - * Singleton for the base address of - * the memory region within which it is instantiated. Two results - * are possible: - * - * 1. An has stored a base address/size pair and the - * new based-pointer instance is located between the base address and - * the base address + size - 1. In this case, the repository - * returns the base address. - * - * 2. No suitable address/size pair was found. The repository - * assumes an address in the regular (not mapped) virtual address - * space of the process and returns 0. In this case, the - * based-pointer uses its address as an offset to it's base - * address 0. - */ - ACE_Based_Pointer_Basic (void); - - /** - * Initialize this object using the @a initial pointer. This - * constructor initializes the by asking the - * Singleton for the base address of - * the memory region within which it is instantiated. Three results - * are possible: - * - * 1. An has stored a base address/size pair and the - * new based-pointer instance is located between the base address and - * the base address + size - 1. In this case, the repository - * returns the base address. - * - * 2. No suitable address/size pair was found. The repository - * assumes an address in the regular (not mapped) virtual address - * space of the process and returns 0. In this case, the - * based-pointer uses its address as an offset to its base - * address 0. - * - * 3. If @a initial is 0 then set the value of to -1, which - * indicates a "NULL" pointer. - */ - ACE_Based_Pointer_Basic (CONCRETE *initial); - - /// Copy constructor. - ACE_Based_Pointer_Basic (const ACE_Based_Pointer_Basic &); - - /// Constructor for know base address. @a o is only used to - /// resolve overload ambiguity. - ACE_Based_Pointer_Basic (const void *base_addr, int o); - - /// Pseudo-assignment operator. - void operator = (CONCRETE *from); - - /// Pseudo-assignment operator. - void operator = (const ACE_Based_Pointer_Basic &); - - /// Dereference operator. - CONCRETE operator * (void) const; - - /// Less than operator. - bool operator < (const ACE_Based_Pointer_Basic &) const; - - /// Less than or equal operator. - bool operator <= (const ACE_Based_Pointer_Basic &) const; - - /// Greater than operator. - bool operator > (const ACE_Based_Pointer_Basic &) const; - - /// Greater than or equal operator. - bool operator >= (const ACE_Based_Pointer_Basic &) const; - - /// Equality operator. - bool operator == (const ACE_Based_Pointer_Basic &) const; - - /// Inequality operator. - bool operator != (const ACE_Based_Pointer_Basic &) const; - - /// Subscript operator. - CONCRETE operator [](int index) const; - - /// Increment operator. - void operator+= (int index); - - /// Returns the underlying memory address of the smart pointer. - operator CONCRETE *() const; - - /// Returns the underlying memory address of the smart pointer. - CONCRETE *addr (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - - /// Dump the state of the object. - void dump (void) const; - -protected: - ptrdiff_t target_; - - /// Keep track of our offset from the base pointer. - ptrdiff_t base_offset_; -}; - -/** - * @class ACE_Based_Pointer - * - * @brief A smart proxy that keeps track of the relative offset of a - * "pointer" from its base address. - * - * This class makes it possible to transparently use "pointers" in - * shared memory as easily as programming with pointers to local - * memory by overloading the C++ delegation operator ->(). - */ -template -class ACE_Based_Pointer : public ACE_Based_Pointer_Basic -{ -public: - // = Initialization method. - /// Constructor. See constructor for ACE_Based_Pointer_Basic for - /// details. - ACE_Based_Pointer (void); - - /// Initialize this object using the pointer. See - /// constructor for ACE_Based_Pointer_Basic for details. - ACE_Based_Pointer (CONCRETE *initial); - - /// Initialize this object with known @a base_addr. @a dummy is - /// a dummy value used to resolve overload ambiguity and it - /// otherwise ignored. - ACE_Based_Pointer (const void *base_addr, int dummy); - - /// Copy constructor (not implemented yet). - ACE_Based_Pointer (const ACE_Based_Pointer &); - - /// Assignment operator. - void operator = (const ACE_Based_Pointer &); - - /// Pseudo-assignment operator. - void operator = (CONCRETE *from); - - /// The C++ "delegation operator". - CONCRETE *operator-> (void); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Based_Pointer_T.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Based_Pointer_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Based_Pointer_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" - -#endif /* ACE_BASED_POINTER_T_H */ diff --git a/externals/ace/Based_Pointer_T.inl b/externals/ace/Based_Pointer_T.inl deleted file mode 100644 index ba6a5aa511b..00000000000 --- a/externals/ace/Based_Pointer_T.inl +++ /dev/null @@ -1,139 +0,0 @@ -// -*- C++ -*- -// -// $Id: Based_Pointer_T.inl 81705 2008-05-15 14:02:02Z johnnyw $ - -#define ACE_COMPUTE_BASED_POINTER(P) (((char *) (P) - (P)->base_offset_) + (P)->target_) -#include "ace/Global_Macros.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template ACE_INLINE CONCRETE * -ACE_Based_Pointer::operator->(void) -{ - ACE_TRACE ("ACE_Based_Pointer::operator->"); - return reinterpret_cast (ACE_COMPUTE_BASED_POINTER (this)); -} - -template ACE_INLINE void -ACE_Based_Pointer_Basic::operator = (CONCRETE *rhs) -{ - ACE_TRACE ("ACE_Based_Pointer_Basic::operator ="); - if (rhs == 0) - // Store a value of that indicate "NULL" pointer. - this->target_ = -1; - else - this->target_ = ((char *) rhs - - ((char *) this - this->base_offset_)); -} - -template ACE_INLINE void -ACE_Based_Pointer::operator = (CONCRETE *rhs) -{ - ACE_TRACE ("ACE_Based_Pointer::operator ="); - if (rhs == 0) - // Store a value of that indicate "NULL" pointer. - this->target_ = -1; - else - this->target_ = ((char *) rhs - - ((char *) this - this->base_offset_)); -} - -template ACE_INLINE CONCRETE -ACE_Based_Pointer_Basic::operator *(void) const -{ - ACE_TRACE ("ACE_Based_Pointer_Basic::operator *"); - return *reinterpret_cast (ACE_COMPUTE_BASED_POINTER (this)); -} - -template ACE_INLINE CONCRETE * -ACE_Based_Pointer_Basic::addr (void) const -{ - ACE_TRACE ("ACE_Based_Pointer_Basic::addr"); - - if (this->target_ == -1) - return 0; - else - return reinterpret_cast (ACE_COMPUTE_BASED_POINTER (this)); -} - -template ACE_INLINE -ACE_Based_Pointer_Basic::operator CONCRETE *() const -{ - ACE_TRACE ("ACE_Based_Pointer_Basic::operator CONCRETE *()"); - - return this->addr (); -} - -template ACE_INLINE CONCRETE -ACE_Based_Pointer_Basic::operator [] (int index) const -{ - ACE_TRACE ("ACE_Based_Pointer_Basic::operator []"); - CONCRETE *c = - reinterpret_cast (ACE_COMPUTE_BASED_POINTER (this)); - return c[index]; -} - -template ACE_INLINE void -ACE_Based_Pointer_Basic::operator += (int index) -{ - ACE_TRACE ("ACE_Based_Pointer_Basic::operator +="); - this->base_offset_ += (index * sizeof (CONCRETE)); -} - -template ACE_INLINE bool -ACE_Based_Pointer_Basic::operator == (const ACE_Based_Pointer_Basic &rhs) const -{ - ACE_TRACE ("ACE_Based_Pointer_Basic::operator =="); - return ACE_COMPUTE_BASED_POINTER (this) == ACE_COMPUTE_BASED_POINTER (&rhs); -} - -template ACE_INLINE bool -ACE_Based_Pointer_Basic::operator != (const ACE_Based_Pointer_Basic &rhs) const -{ - ACE_TRACE ("ACE_Based_Pointer_Basic::operator !="); - return !(*this == rhs); -} - -template ACE_INLINE bool -ACE_Based_Pointer_Basic::operator < (const ACE_Based_Pointer_Basic &rhs) const -{ - ACE_TRACE ("ACE_Based_Pointer_Basic::operator <"); - return ACE_COMPUTE_BASED_POINTER (this) < ACE_COMPUTE_BASED_POINTER (&rhs); -} - -template ACE_INLINE bool -ACE_Based_Pointer_Basic::operator <= (const ACE_Based_Pointer_Basic &rhs) const -{ - ACE_TRACE ("ACE_Based_Pointer_Basic::operator <="); - return ACE_COMPUTE_BASED_POINTER (this) <= ACE_COMPUTE_BASED_POINTER (&rhs); -} - -template ACE_INLINE bool -ACE_Based_Pointer_Basic::operator > (const ACE_Based_Pointer_Basic &rhs) const -{ - ACE_TRACE ("ACE_Based_Pointer_Basic::operator >"); - return ACE_COMPUTE_BASED_POINTER (this) > ACE_COMPUTE_BASED_POINTER (&rhs); -} - -template ACE_INLINE bool -ACE_Based_Pointer_Basic::operator >= (const ACE_Based_Pointer_Basic &rhs) const -{ - ACE_TRACE ("ACE_Based_Pointer_Basic::operator >="); - return ACE_COMPUTE_BASED_POINTER (this) >= ACE_COMPUTE_BASED_POINTER (&rhs); -} - -template ACE_INLINE void -ACE_Based_Pointer_Basic::operator= (const ACE_Based_Pointer_Basic &rhs) -{ - ACE_TRACE ("ACE_Based_Pointer_Basic::operator="); - *this = rhs.addr (); -} - -template ACE_INLINE void -ACE_Based_Pointer::operator= (const ACE_Based_Pointer &rhs) -{ - ACE_TRACE ("ACE_Based_Pointer::operator="); - *this = rhs.addr (); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Basic_Stats.cpp b/externals/ace/Basic_Stats.cpp deleted file mode 100644 index fe678333d89..00000000000 --- a/externals/ace/Basic_Stats.cpp +++ /dev/null @@ -1,78 +0,0 @@ -// $Id: Basic_Stats.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Basic_Stats.h" -#include "ace/Log_Msg.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Basic_Stats.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID(ace, - Basic_Stats, - "$Id: Basic_Stats.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -void -ACE_Basic_Stats::accumulate (const ACE_Basic_Stats &rhs) -{ - if (rhs.samples_count_ == 0) - return; - - if (this->samples_count_ == 0) - { - this->min_ = rhs.min_; - this->min_at_ = rhs.min_at_; - - this->max_ = rhs.max_; - this->max_at_ = rhs.max_at_; - } - else - { - if (this->min_ > rhs.min_) - { - this->min_ = rhs.min_; - this->min_at_ = rhs.min_at_; - } - if (this->max_ < rhs.max_) - { - this->max_ = rhs.max_; - this->max_at_ = rhs.max_at_; - } - } - - this->samples_count_ += rhs.samples_count_; - this->sum_ += rhs.sum_; -} - -void -ACE_Basic_Stats::dump_results (const ACE_TCHAR *msg, ACE_UINT32 sf) const -{ -#ifndef ACE_NLOGGING - if (this->samples_count () == 0u) - { - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("%s : no data collected\n"), msg)); - return; - } - - ACE_UINT64 avg = this->sum_ / this->samples_count_; - - ACE_UINT64 l_min = this->min_ / sf; - ACE_UINT64 l_max = this->max_ / sf; - ACE_UINT64 l_avg = avg / sf; - - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("%s latency : %Q[%d]/%Q/%Q[%d] (min/avg/max)\n"), - msg, - l_min, this->min_at_, - l_avg, - l_max, this->max_at_)); - -#else - ACE_UNUSED_ARG (msg); - ACE_UNUSED_ARG (sf); -#endif /* ACE_NLOGGING */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Basic_Stats.h b/externals/ace/Basic_Stats.h deleted file mode 100644 index bff1ff29f65..00000000000 --- a/externals/ace/Basic_Stats.h +++ /dev/null @@ -1,87 +0,0 @@ - -//============================================================================= -/** - * @file Basic_Stats.h - * - * $Id: Basic_Stats.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Carlos O'Ryan - */ -//============================================================================= - - -#ifndef ACE_BASIC_STATS_H -#define ACE_BASIC_STATS_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" -#include "ace/Basic_Types.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/// Collect basic stats about a series of samples -/** - * Compute the average and standard deviation (aka jitter) for an - * arbitrary number of samples, using constant space. - * Normally used for latency statistics. - */ -class ACE_Export ACE_Basic_Stats -{ -public: - /// Constructor - /** - * The number of samples is pre-allocated, and cannot changes once - * the class is initialized. - */ - ACE_Basic_Stats (void); - - /// The number of samples received so far - ACE_UINT32 samples_count (void) const; - - /// Record one sample. - void sample (ACE_UINT64 value); - - /// Update the values to reflect the stats in @a rhs. - void accumulate (const ACE_Basic_Stats &rhs); - - /// Dump all the samples - /** - * Prints out the results, using @a msg as a prefix for each message and - * scaling all the numbers by @a scale_factor. The latter is useful because - * high resolution timer samples are acquired in clock ticks, but often - * presented in microseconds. - */ - void dump_results (const ACE_TCHAR *msg, - ACE_UINT32 scale_factor) const; - - /// The number of samples - ACE_UINT32 samples_count_; - - /// The minimum value - ACE_UINT64 min_; - - /// The number of the sample that had the minimum value - ACE_UINT32 min_at_; - - /// The maximum value - ACE_UINT64 max_; - - /// The number of the sample that had the maximum value - ACE_UINT32 max_at_; - - /// The sum of all the values - ACE_UINT64 sum_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Basic_Stats.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_BASIC_STATS_H */ diff --git a/externals/ace/Basic_Stats.inl b/externals/ace/Basic_Stats.inl deleted file mode 100644 index e2f153884e3..00000000000 --- a/externals/ace/Basic_Stats.inl +++ /dev/null @@ -1,53 +0,0 @@ -// -*- C++ -*- -// -// $Id: Basic_Stats.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE -ACE_Basic_Stats::ACE_Basic_Stats (void) - : samples_count_ (0) - , min_ (0) - , min_at_ (0) - , max_ (0) - , max_at_ (0) - , sum_ (0) -{ -} - -ACE_INLINE ACE_UINT32 -ACE_Basic_Stats::samples_count (void) const -{ - return this->samples_count_; -} - -ACE_INLINE void -ACE_Basic_Stats::sample (ACE_UINT64 value) -{ - ++this->samples_count_; - - if (this->samples_count_ == 1u) - { - this->min_ = value; - this->min_at_ = this->samples_count_; - this->max_ = value; - this->max_at_ = this->samples_count_; - } - else - { - if (this->min_ > value) - { - this->min_ = value; - this->min_at_ = this->samples_count_; - } - if (this->max_ < value) - { - this->max_ = value; - this->max_at_ = this->samples_count_; - } - } - - this->sum_ += value; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Basic_Types.cpp b/externals/ace/Basic_Types.cpp deleted file mode 100644 index 42ae83c0b2a..00000000000 --- a/externals/ace/Basic_Types.cpp +++ /dev/null @@ -1,139 +0,0 @@ -#include "ace/Basic_Types.h" - -#if !defined (__ACE_INLINE__) -# include "ace/Basic_Types.inl" -#endif /* ! __ACE_INLINE__ */ - - -ACE_RCSID (ace, - Basic_Types, - "$Id: Basic_Types.cpp 80826 2008-03-04 14:51:23Z wotte $") - - -#if defined (ACE_LACKS_LONGLONG_T) && !defined (ACE_LACKS_UNSIGNEDLONGLONG_T) -# include "ace/Log_Msg.h" -# include "ace/OS_NS_stdio.h" -# include "ace/OS_NS_string.h" -# if !defined (ACE_LACKS_IOSTREAM_TOTALLY) -// FUZZ: disable check_for_streams_include -# include "ace/streams.h" -# endif /* ! ACE_LACKS_IOSTREAM_TOTALLY */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -void -ACE_U_LongLong::output (FILE *file) const -{ - if (h_ () > 0) - ACE_OS::fprintf (file, "0x%lx%0*lx", h_ (), 2 * sizeof l_ (), l_ ()); - else - ACE_OS::fprintf (file, "0x%lx", l_ ()); -} - - -ACE_TCHAR * -ACE_U_LongLong::as_string (ACE_TCHAR *output, - unsigned int base, - unsigned int uppercase) const -{ - if (*this == 0) - { - ACE_OS::strcpy(output, "0"); - } - else - { - switch(base) - { - case 8: - { - unsigned int index = 0; - int bshift = 31; - while(bshift >= 1) - { - unsigned int sval = (this->h_ () >> bshift) & 7; - if (sval > 0 || index != 0) - { - output[index] = sval + '0'; - ++index; - } - bshift -= 3; - } - bshift = 30; - while(bshift >= 0) - { - unsigned int sval = (this->l_ () >> bshift) & 7; - // Combine the last bit of hi with the first 3-bit digit - if (bshift == 30) - { - sval |= (this->h_ () & 1) << 2; - } - if (sval > 0 || index != 0) - { - output[index] = sval + '0'; - ++index; - } - bshift -= 3; - } - output[index] = '\0'; - break; - } - case 10: - { - ACE_OS::sprintf(output, "%.0f", *this / 1.0); - break; - } - case 16: - { - if (this->h_ () != 0) - { - ACE_OS::sprintf(output, - (uppercase ? "%lX%0*lX" : "%lx%0*lx"), - this->h_ (), 2 * sizeof this->l_ (), - this->l_ ()); - } - else - { - ACE_OS::sprintf(output, - (uppercase ? "%lX" : "%lx"), this->l_ ()); - - } - break; - } - default: - { - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("Unsupported base = %u\n"), base)); - output[0] = '\0'; - } - } - } - - return output; -} - - -# if !defined (ACE_LACKS_IOSTREAM_TOTALLY) -ostream& -operator<< (ostream& os, const ACE_U_LongLong& ll) -{ -#ifdef __TANDEM && (__CPLUSPLUS_VERSION >= 3) - unsigned long flags = os.flags(); -#else - unsigned long flags = os.setf(0); -#endif - char buffer[32]; - - if ((flags & ios::oct) != 0) - os << ll.as_string (buffer, 8); - else if ((flags & ios::hex) != 0) - os << ll.as_string (buffer, 16, (flags & ios::uppercase)); - else - os << ll.as_string (buffer); - return os; -} -# endif - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_LACKS_LONGLONG_T */ - diff --git a/externals/ace/Basic_Types.h b/externals/ace/Basic_Types.h deleted file mode 100644 index bc467fafb5c..00000000000 --- a/externals/ace/Basic_Types.h +++ /dev/null @@ -1,962 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Basic_Types.h - * - * $Id: Basic_Types.h 91161 2010-07-21 18:25:12Z schmidt $ - * - * @author David L. Levine - * - * #defines the list of preprocessor macros below. The config.h file can - * pre-define any of these to short-cut the definitions. This is usually - * only necessary if the preprocessor does all of its math using integers. - * - * Sizes of built-in types: - * - ACE_SIZEOF_CHAR - * - ACE_SIZEOF_WCHAR - * - ACE_SIZEOF_SHORT - * - ACE_SIZEOF_INT - * - ACE_SIZEOF_LONG - * - ACE_SIZEOF_LONG_LONG - * - ACE_SIZEOF_VOID_P - * - ACE_SIZEOF_FLOAT - * - ACE_SIZEOF_DOUBLE - * - ACE_SIZEOF_LONG_DOUBLE - * - * Wrappers for built-in types of specific sizes: - * - ACE_USHORT16 (For backward compatibility. Use ACE_UINT16 instead.) - * - ACE_INT8 - * - ACE_UINT8 - * - ACE_INT16 - * - ACE_UINT16 - * - ACE_INT32 - * - ACE_UINT32 - * - ACE_UINT64 - * (@note ACE_INT64 is partly defined, there is no ACE_LongLong for - * platforms that don't have a native 8-byte integer type.) - * - * Byte-order (endian-ness) determination: - * ACE_BYTE_ORDER, to either ACE_BIG_ENDIAN or ACE_LITTLE_ENDIAN - * - * - */ -//============================================================================= - -#include "ace/config-lite.h" - -#ifndef ACE_BASIC_TYPES_H -# define ACE_BASIC_TYPES_H - -# include /**/ "ace/pre.h" - -# if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -# endif /* ACE_LACKS_PRAGMA_ONCE */ - -// Pull in definitions -# include "ace/os_include/os_limits.h" // Integer limits -# include "ace/os_include/os_float.h" // Floating point limits -# include "ace/os_include/os_stdlib.h" // Other types -# include "ace/os_include/os_stddef.h" // Get ptrdiff_t - see further comments below - -# if defined(ACE_LACKS_LONGLONG_T) -# include "ace/os_include/os_stdio.h" // For long long emulation -# endif /* ACE_LACKS_LONGLONG_T */ - -# include "ace/os_include/sys/os_types.h" - -# if !defined (ACE_LACKS_SYS_PARAM_H) -# include /**/ -# endif /* ACE_LACKS_SYS_PARAM_H */ - -# include "ace/ACE_export.h" - -# if !defined (ACE_LACKS_STDINT_H) -# include -# endif -# if !defined (ACE_LACKS_INTTYPES_H) -# include -# endif - -#ifdef ACE_LACKS_INTPTR_T -# include "ace/If_Then_Else.h" - -// This intptr_t typedef is here instead of -// since it depends on the template -// metaprogramming in . - -// We could compare ACE_SIZEOF_VOID_P against ACE_SIZEOF_LONG, etc. -// However, that depends on the ACE preprocessor symbol definitions in -// the platform-specific configuration header being correct. -// The template meta-programming approach we take below, -// i.e. determining the type at compile-time rather than at -// preprocessing-time, will work for all platforms, and does not -// depend on ACE developer-defined configuration parameters. - -typedef ACE::If_Then_Else< - (sizeof (void*) == sizeof (signed int)), - signed int, - ACE::If_Then_Else< - (sizeof (void*) == sizeof (signed long)), - signed long, -#ifdef ACE_LACKS_LONGLONG_T - void /* Unknown. Force an invalid type */ -#else - ACE::If_Then_Else< - (sizeof (void*) == sizeof (signed long long)), - signed long long, - void /* Unknown. Force an invalid type */ - >::result_type -#endif /* ACE_LACKS_LONGLONG_T */ - >::result_type - >::result_type intptr_t; - -typedef ACE::If_Then_Else< - (sizeof (void*) == sizeof (unsigned int)), - unsigned int, - ACE::If_Then_Else< - (sizeof (void*) == sizeof (unsigned long)), - unsigned long, -#ifdef ACE_LACKS_UNSIGNEDLONGLONG_T - void /* Unknown. Force an invalid type */ -#else - ACE::If_Then_Else< - (sizeof (void*) == sizeof (unsigned long long)), - unsigned long long, - void /* Unknown. Force an invalid type */ - >::result_type -#endif /* ACE_LACKS_UNSIGNEDLONGLONG_T */ - >::result_type - >::result_type uintptr_t; - -#endif /* ACE_LACKS_INTPTR_T */ - -// A char always has 1 byte, by definition. -# define ACE_SIZEOF_CHAR 1 - -// Unfortunately, there isn't a portable way to determine the size of a wchar. -// So we just define them on a platform basis. If the platform doesn't -// define it and it's an XPG4 system, assume wchar_t is 4 bytes. Some code -// uses ACE_SIZEOF_WCHAR in preprocessor statements, so sizeof() isn't valid. -// If the platform config doesn't set this, and this guess is wrong, -// Basic_Types_Test should catch the inconsistency. -# if defined (ACE_HAS_WCHAR) -# if !defined (ACE_SIZEOF_WCHAR) -# if defined (ACE_HAS_XPG4_MULTIBYTE_CHAR) -# define ACE_SIZEOF_WCHAR 4 -# else -// 0 so the Basic_Types test will catch this. -# define ACE_SIZEOF_WCHAR 0 -# endif /* ACE_HAS_XPG4_MULTIBYTE_CHAR */ -# endif /* !ACE_SIZEOF_WCHAR */ -# endif /* ACE_HAS_WCHAR */ - -// The number of bytes in a short. -# if !defined (ACE_SIZEOF_SHORT) -# if (USHRT_MAX) == 255U -# define ACE_SIZEOF_SHORT 1 -# elif (USHRT_MAX) == 65535U -# define ACE_SIZEOF_SHORT 2 -# elif (USHRT_MAX) == 4294967295U -# define ACE_SIZEOF_SHORT 4 -# elif (USHRT_MAX) == 18446744073709551615U -# define ACE_SIZEOF_SHORT 8 -# else -# error: unsupported short size, must be updated for this platform! -# endif /* USHRT_MAX */ -# endif /* !defined (ACE_SIZEOF_SHORT) */ - -// The number of bytes in an int. -# if !defined (ACE_SIZEOF_INT) -# if (UINT_MAX) == 65535U -# define ACE_SIZEOF_INT 2 -# elif (UINT_MAX) == 4294967295U -# define ACE_SIZEOF_INT 4 -# elif (UINT_MAX) == 18446744073709551615U -# define ACE_SIZEOF_INT 8 -# else -# error: unsupported int size, must be updated for this platform! -# endif /* UINT_MAX */ -# endif /* !defined (ACE_SIZEOF_INT) */ - -// The number of bytes in a long. -# if !defined (ACE_SIZEOF_LONG) -# if (ULONG_MAX) == 65535UL -# define ACE_SIZEOF_LONG 2 -# elif ((ULONG_MAX) == 4294967295UL) -# define ACE_SIZEOF_LONG 4 -# elif ((ULONG_MAX) == 18446744073709551615UL) -# define ACE_SIZEOF_LONG 8 -# else -# error: unsupported long size, must be updated for this platform! -# endif /* ULONG_MAX */ -# endif /* !defined (ACE_SIZEOF_LONG) */ - -// The number of bytes in a long long. -# if !defined (ACE_SIZEOF_LONG_LONG) -# if defined (ACE_LACKS_LONGLONG_T) -# define ACE_SIZEOF_LONG_LONG 8 -# elif defined (ULLONG_MAX) -# if ((ULLONG_MAX) == 4294967295ULL) -# define ACE_SIZEOF_LONG_LONG 4 -# elif ((ULLONG_MAX) == 18446744073709551615ULL) -# define ACE_SIZEOF_LONG_LONG 8 -# endif -# elif defined (ULONGLONG_MAX) -# if ((ULONGLONG_MAX) == 4294967295ULL) -# define ACE_SIZEOF_LONG_LONG 4 -# elif ((ULONGLONG_MAX) == 18446744073709551615ULL) -# define ACE_SIZEOF_LONG_LONG 8 -# endif -# endif -# // If we can't determine the size of long long, assume it is 8 -# // instead of erroring out. (Either ULLONG_MAX and ULONGLONG_MAX -# // may not be supported; or an extended C/C++ dialect may need to -# // be selected. If this assumption is wrong, it can be addressed -# // in the platform-specific config header. -# if !defined (ACE_SIZEOF_LONG_LONG) -# define ACE_SIZEOF_LONG_LONG 8 -# endif -# endif /* !defined (ACE_SIZEOF_LONG_LONG) */ - - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// The sizes of the commonly implemented types are now known. Set up -// typedefs for whatever we can. Some of these are needed for certain -// cases of ACE_UINT64, so do them before the 64-bit stuff. - -#if defined (ACE_INT8_TYPE) - typedef ACE_INT8_TYPE ACE_INT8; -#elif defined (ACE_HAS_INT8_T) - typedef int8_t ACE_INT8; -#elif !defined (ACE_LACKS_SIGNED_CHAR) - typedef signed char ACE_INT8; -#else - typedef char ACE_INT8; -#endif /* defined (ACE_INT8_TYPE) */ - -#if defined (ACE_UINT8_TYPE) - typedef ACE_UINT8_TYPE ACE_UINT8; -#elif defined (ACE_HAS_UINT8_T) - typedef uint8_t ACE_UINT8; -#else - typedef unsigned char ACE_UINT8; -#endif /* defined (ACE_UINT8_TYPE) */ - -#if defined (ACE_INT16_TYPE) - typedef ACE_INT16_TYPE ACE_INT16; -#elif defined (ACE_HAS_INT16_T) - typedef int16_t ACE_INT16; -#elif ACE_SIZEOF_SHORT == 2 - typedef short ACE_INT16; -#elif ACE_SIZEOF_INT == 2 - typedef int ACE_INT16; -#else -# error Have to add to the ACE_INT16 type setting -#endif /* defined (ACE_INT16_TYPE) */ - -#if defined (ACE_UINT16_TYPE) - typedef ACE_UINT16_TYPE ACE_UINT16; -#elif defined (ACE_HAS_UINT16_T) - typedef uint16_t ACE_UINT16; -#elif ACE_SIZEOF_SHORT == 2 - typedef unsigned short ACE_UINT16; -#elif ACE_SIZEOF_INT == 2 - typedef unsigned int ACE_UINT16; -#else -# error Have to add to the ACE_UINT16 type setting -#endif /* defined (ACE_UINT16_TYPE) */ - -#if defined (ACE_INT32_TYPE) - typedef ACE_INT32_TYPE ACE_INT32; -#elif defined (ACE_HAS_INT32_T) - typedef int32_t ACE_INT32; -#elif ACE_SIZEOF_INT == 4 - typedef int ACE_INT32; -#elif ACE_SIZEOF_LONG == 4 - typedef long ACE_INT32; -#else -# error Have to add to the ACE_INT32 type setting -#endif /* defined (ACE_INT32_TYPE) */ - -#if defined (ACE_UINT32_TYPE) - typedef ACE_UINT32_TYPE ACE_UINT32; -#elif defined (ACE_HAS_UINT32_T) - typedef uint32_t ACE_UINT32; -#elif ACE_SIZEOF_INT == 4 - typedef unsigned int ACE_UINT32; -#elif ACE_SIZEOF_LONG == 4 - typedef unsigned long ACE_UINT32; -#else -# error Have to add to the ACE_UINT32 type setting -#endif /* defined (ACE_UINT32_TYPE) */ - -#if defined (ACE_INT64_TYPE) - typedef ACE_INT64_TYPE ACE_INT64; -#elif defined (ACE_HAS_INT64_T) - typedef int64_t ACE_INT64; -#elif ACE_SIZEOF_LONG == 8 - typedef long ACE_INT64; -#elif !defined (ACE_LACKS_LONGLONG_T) && ACE_SIZEOF_LONG_LONG == 8 -# ifdef __GNUC__ - // Silence g++ "-pedantic" warnings regarding use of "long long" - // type. - __extension__ -# endif /* __GNUC__ */ - typedef long long ACE_INT64; -#endif /* defined (ACE_INT64_TYPE) */ - -#if !(defined (ACE_LACKS_LONGLONG_T) || defined (ACE_LACKS_UNSIGNEDLONGLONG_T)) -/* See matching #if around ACE_U_LongLong class declaration below */ - -# if defined (ACE_UINT64_TYPE) - typedef ACE_UINT64_TYPE ACE_UINT64; -# elif defined (ACE_HAS_UINT64_T) - typedef uint64_t ACE_UINT64; -# elif ACE_SIZEOF_LONG == 8 - typedef unsigned long ACE_UINT64; -# elif ACE_SIZEOF_LONG_LONG == 8 -# ifdef __GNUC__ - // Silence g++ "-pedantic" warnings regarding use of "long long" - // type. - __extension__ -# endif /* __GNUC__ */ - typedef unsigned long long ACE_UINT64; -# endif /* defined (ACE_UINT64_TYPE) */ -#endif /* !(ACE_LACKS_LONGLONG_T || ACE_LACKS_UNSIGNEDLONGLONG_T) */ - - -typedef ACE_UINT16 ACE_USHORT16; // @@ Backward compatibility. - -// Define a generic byte for use in codecs -typedef unsigned char ACE_Byte; - -// Define a pseudo wide character type when wchar is not supported so we -// can support basic wide character string operations. - -# if defined (ACE_HAS_WCHAR) || defined (ACE_HAS_XPG4_MULTIBYTE_CHAR) -# define ACE_WINT_T wint_t -# define ACE_WCHAR_T wchar_t -# else -# define ACE_WINT_T ACE_UINT16 -# define ACE_WCHAR_T ACE_UINT16 -# endif /* ACE_HAS_WCHAR */ - -// The number of bytes in a void *. -# ifndef ACE_SIZEOF_VOID_P -# define ACE_SIZEOF_VOID_P ACE_SIZEOF_LONG -# endif /* ACE_SIZEOF_VOID_P */ - -ACE_END_VERSIONED_NAMESPACE_DECL - -// Byte-order (endian-ness) determination. -# if defined (BYTE_ORDER) -# if (BYTE_ORDER == LITTLE_ENDIAN) -# define ACE_LITTLE_ENDIAN 0x0123 -# define ACE_BYTE_ORDER ACE_LITTLE_ENDIAN -# elif (BYTE_ORDER == BIG_ENDIAN) -# define ACE_BIG_ENDIAN 0x3210 -# define ACE_BYTE_ORDER ACE_BIG_ENDIAN -# else -# error: unknown BYTE_ORDER! -# endif /* BYTE_ORDER */ -# elif defined (_BYTE_ORDER) -# if (_BYTE_ORDER == _LITTLE_ENDIAN) -# define ACE_LITTLE_ENDIAN 0x0123 -# define ACE_BYTE_ORDER ACE_LITTLE_ENDIAN -# elif (_BYTE_ORDER == _BIG_ENDIAN) -# define ACE_BIG_ENDIAN 0x3210 -# define ACE_BYTE_ORDER ACE_BIG_ENDIAN -# else -# error: unknown _BYTE_ORDER! -# endif /* _BYTE_ORDER */ -# elif defined (__BYTE_ORDER) -# if (__BYTE_ORDER == __LITTLE_ENDIAN) -# define ACE_LITTLE_ENDIAN 0x0123 -# define ACE_BYTE_ORDER ACE_LITTLE_ENDIAN -# elif (__BYTE_ORDER == __BIG_ENDIAN) -# define ACE_BIG_ENDIAN 0x3210 -# define ACE_BYTE_ORDER ACE_BIG_ENDIAN -# else -# error: unknown __BYTE_ORDER! -# endif /* __BYTE_ORDER */ -# else /* ! BYTE_ORDER && ! __BYTE_ORDER */ - // We weren't explicitly told, so we have to figure it out . . . - // Note that Itanium hardware (IA64) can run in either byte order. It's - // selected by the OS when loading; Windows runs little, HP-UX runs big. -# if defined (i386) || defined (__i386__) || defined (_M_IX86) || \ - defined (vax) || defined (__alpha) || defined (__LITTLE_ENDIAN__) || \ - defined (ARM) || defined (_M_IA64) || defined (_M_AMD64) || \ - defined (__amd64) || \ - ((defined (__ia64__) || defined (__ia64)) && !defined (__hpux)) - // We know these are little endian. -# define ACE_LITTLE_ENDIAN 0x0123 -# define ACE_BYTE_ORDER ACE_LITTLE_ENDIAN -# else - // Otherwise, we assume big endian. -# define ACE_BIG_ENDIAN 0x3210 -# define ACE_BYTE_ORDER ACE_BIG_ENDIAN -# endif -# endif /* ! BYTE_ORDER && ! __BYTE_ORDER */ - -// Byte swapping macros to deal with differences between little endian -// and big endian machines. Note that "long" here refers to 32 bit -// quantities. -# define ACE_SWAP_LONG(L) ((ACE_SWAP_WORD ((L) & 0xFFFF) << 16) \ - | ACE_SWAP_WORD(((L) >> 16) & 0xFFFF)) -# define ACE_SWAP_WORD(L) ((((L) & 0x00FF) << 8) | (((L) & 0xFF00) >> 8)) - -# if defined (ACE_LITTLE_ENDIAN) -# define ACE_HTONL(X) ACE_SWAP_LONG (X) -# define ACE_NTOHL(X) ACE_SWAP_LONG (X) -# define ACE_IDL_NCTOHL(X) (X) -# define ACE_IDL_NSTOHL(X) (X) -# else -# define ACE_HTONL(X) X -# define ACE_NTOHL(X) X -# define ACE_IDL_NCTOHL(X) (X << 24) -# define ACE_IDL_NSTOHL(X) ((X) << 16) -# endif /* ACE_LITTLE_ENDIAN */ - -# if defined (ACE_LITTLE_ENDIAN) -# define ACE_HTONS(x) ACE_SWAP_WORD(x) -# define ACE_NTOHS(x) ACE_SWAP_WORD(x) -# else -# define ACE_HTONS(x) x -# define ACE_NTOHS(x) x -# endif /* ACE_LITTLE_ENDIAN */ - -#if defined (ACE_LACKS_LONGLONG_T) - // This throws away the high 32 bits. It's very unlikely that a - // pointer will be more than 32 bits wide if the platform does not - // support 64-bit integers. -# define ACE_LONGLONG_TO_PTR(PTR_TYPE, L) \ - reinterpret_cast (L.lo ()) -#elif defined (ACE_OPENVMS) && (!defined (__INITIAL_POINTER_SIZE) || (__INITIAL_POINTER_SIZE < 64)) -# define ACE_LONGLONG_TO_PTR(PTR_TYPE, L) \ - reinterpret_cast (static_cast (L)) -#else /* ! ACE_LACKS_LONGLONG_T */ -# define ACE_LONGLONG_TO_PTR(PTR_TYPE, L) \ - reinterpret_cast (static_cast (L)) -#endif /* ! ACE_LACKS_LONGLONG_T */ - -// If the platform lacks an unsigned long long, define one. -#if defined (ACE_LACKS_LONGLONG_T) || defined (ACE_LACKS_UNSIGNEDLONGLONG_T) -// Forward declaration for streams -# include "ace/iosfwd.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_U_LongLong - * - * @brief Unsigned long long for platforms that don't have one. - * - * Provide our own unsigned long long. This is intended to be - * use with ACE_High_Res_Timer, so the division operator assumes - * that the quotient fits into a u_long. - * Please note that the constructor takes (optionally) two values. - * The high one contributes 0x100000000 times its value. So, - * for example, (0, 2) is _not_ 20000000000, but instead - * 0x200000000. To emphasize this, the default values are expressed - * in hex, and output () dumps the value in hex. - */ - class ACE_Export ACE_U_LongLong - { - public: - // = Initialization and termination methods. -#if defined (ACE_LACKS_UNSIGNEDLONGLONG_T) - ACE_U_LongLong (const long long value = 0x0); -#else - ACE_U_LongLong (const ACE_UINT32 lo = 0x0, const ACE_UINT32 hi = 0x0); -#endif - ACE_U_LongLong (const ACE_U_LongLong &); - ACE_U_LongLong &operator= (const ACE_U_LongLong &); - ACE_U_LongLong &operator= (const ACE_INT32 &); - ACE_U_LongLong &operator= (const ACE_UINT32 &); - ~ACE_U_LongLong (void); - - // = Overloaded relation operators. - bool operator== (const ACE_U_LongLong &) const; - bool operator== (const ACE_UINT32) const; - bool operator!= (const ACE_U_LongLong &) const; - bool operator!= (const ACE_UINT32) const; - bool operator< (const ACE_U_LongLong &) const; - bool operator< (const ACE_UINT32) const; - bool operator<= (const ACE_U_LongLong &) const; - bool operator<= (const ACE_UINT32) const; - bool operator> (const ACE_U_LongLong &) const; - bool operator> (const ACE_UINT32) const; - bool operator>= (const ACE_U_LongLong &) const; - bool operator>= (const ACE_UINT32) const; - - ACE_U_LongLong operator+ (const ACE_U_LongLong &) const; - ACE_U_LongLong operator+ (const ACE_UINT32) const; - ACE_U_LongLong operator- (const ACE_U_LongLong &) const; - ACE_U_LongLong operator- (const ACE_UINT32) const; - ACE_U_LongLong operator* (const ACE_UINT32) const; - ACE_U_LongLong &operator*= (const ACE_UINT32); - - ACE_U_LongLong operator<< (const unsigned int) const; - ACE_U_LongLong &operator<<= (const unsigned int); - ACE_U_LongLong operator>> (const unsigned int) const; - ACE_U_LongLong &operator>>= (const unsigned int); - - double operator/ (const double) const; - - ACE_U_LongLong &operator+= (const ACE_U_LongLong &); - ACE_U_LongLong &operator+= (const ACE_UINT32); - ACE_U_LongLong &operator-= (const ACE_U_LongLong &); - ACE_U_LongLong &operator-= (const ACE_UINT32); - ACE_U_LongLong &operator++ (); - ACE_U_LongLong &operator-- (); - const ACE_U_LongLong operator++ (int); - const ACE_U_LongLong operator-- (int); - ACE_U_LongLong &operator|= (const ACE_U_LongLong); - ACE_U_LongLong &operator|= (const ACE_UINT32); - ACE_U_LongLong &operator&= (const ACE_U_LongLong); - ACE_U_LongLong &operator&= (const ACE_UINT32); - - // Note that the following take ACE_UINT32 arguments. These are - // typical use cases, and easy to implement. But, they limit the - // return values to 32 bits as well. There are no checks for - // overflow. - ACE_UINT32 operator/ (const ACE_UINT32) const; - ACE_UINT32 operator% (const ACE_UINT32) const; - - // The following only operate on the lower 32 bits (they take only - // 32 bit arguments). - ACE_UINT32 operator| (const ACE_INT32) const; - ACE_UINT32 operator& (const ACE_INT32) const; - - // The following operators convert their arguments to - // ACE_UINT32. So, there may be information loss if they are - // used. - ACE_U_LongLong operator* (const ACE_INT32) const; - ACE_U_LongLong &operator*= (const ACE_INT32); - ACE_UINT32 operator/ (const ACE_INT32) const; -# if ACE_SIZEOF_INT == 4 - ACE_UINT32 operator/ (const unsigned long) const; - ACE_UINT32 operator/ (const long) const; -# else /* ACE_SIZEOF_INT != 4 */ - ACE_UINT32 operator/ (const unsigned int) const; - ACE_UINT32 operator/ (const int) const; -# endif /* ACE_SIZEOF_INT != 4 */ - - // = Helper methods. - /// Outputs the value to the FILE, in hex. - void output (FILE * = stdout) const; - - ACE_TCHAR *as_string (ACE_TCHAR *string, - unsigned int base = 10, - unsigned int uppercase = 0) const; - - ACE_UINT32 hi (void) const; - ACE_UINT32 lo (void) const; - - void hi (const ACE_UINT32 hi); - void lo (const ACE_UINT32 lo); - -#if defined (ACE_LACKS_UNSIGNEDLONGLONG_T) - long long to_int64 (void) const; -# endif - - private: - -#if defined (ACE_LACKS_UNSIGNEDLONGLONG_T) - long long data_; -#else - public: - struct ace_hi_lo_correct_endian - { -# if defined (ACE_BIG_ENDIAN) - /// High 32 bits. - ACE_UINT32 hi_; - /// Low 32 bits. - ACE_UINT32 lo_; - -# else - - /// Low 32 bits. - ACE_UINT32 lo_; - /// High 32 bits. - ACE_UINT32 hi_; -# endif /* ! ACE_BIG_ENDIAN */ - }; - private: - union - { - struct ace_hi_lo_correct_endian data_; - - /// To ensure alignment on 8-byte boundary. - double for_alignment_; - }; - - // @note the following four accessors are inlined here in - // order to minimize the extent of the data_ struct. It's - // only used here; the .i and .cpp files use the accessors. - - /// Internal utility function to hide access through struct. - const ACE_UINT32 &h_ () const { return data_.hi_; } - - /// Internal utility function to hide access through struct. - ACE_UINT32 &h_ () { return data_.hi_; } - - /// Internal utility function to hide access through struct. - const ACE_UINT32 &l_ () const { return data_.lo_; } - - /// Internal utility function to hide access through struct. - ACE_UINT32 &l_ () { return data_.lo_; } - - // @note the above four accessors are inlined here in - // order to minimize the extent of the data_ struct. It's - // only used here; the .inl and .cpp files use the accessors. - - /// These functions are used to implement multiplication. - ACE_UINT32 ul_shift (ACE_UINT32 a, - ACE_UINT32 c_in, - ACE_UINT32 *c_out) const; - ACE_U_LongLong ull_shift (ACE_U_LongLong a, - ACE_UINT32 c_in, - ACE_UINT32 *c_out) const; - ACE_U_LongLong ull_add (ACE_U_LongLong a, - ACE_U_LongLong b, - ACE_UINT32 *carry) const; - ACE_U_LongLong ull_mult (ACE_U_LongLong a, - ACE_UINT32 b, - ACE_UINT32 *carry) const; -#endif // ACE_LACKS_UNSIGNEDLONGLONG_T - }; - - typedef ACE_U_LongLong ACE_UINT64; - -#if !defined (ACE_LACKS_IOSTREAM_TOTALLY) - ostream &operator<< (ostream &, const ACE_U_LongLong &); -#endif /* ! ACE_LACKS_IOSTREAM_TOTALLY */ - -ACE_END_VERSIONED_NAMESPACE_DECL - -# endif /* ACE_LACKS_LONGLONG_T */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Conversions from ACE_UINT64 to ACE_UINT32. ACE_CU64_TO_CU32 should -// be used on const ACE_UINT64's. -# if defined (ACE_LACKS_LONGLONG_T) || defined (ACE_LACKS_UNSIGNEDLONGLONG_T) -inline ACE_UINT32 -ACE_U64_TO_U32 (ACE_U_LongLong const & n) -{ - /** - * @note We could add a cast operator to ACE_U_LongLong but that may - * cause more problems than it solves. Force users to perform - * an explicit cast via ACE_{C}U64_TO_{C}U32. - */ - return n.lo (); -} - -inline ACE_UINT32 -ACE_CU64_TO_CU32 (ACE_U_LongLong const & n) -{ - return ACE_U64_TO_U32 (n); -} -# else /* ! ACE_LACKS_LONGLONG_T */ -inline ACE_UINT32 -ACE_U64_TO_U32 (ACE_UINT64 n) -{ - return static_cast (n); -} - -inline ACE_UINT32 -ACE_CU64_TO_CU32 (ACE_UINT64 n) -{ - return static_cast (n); -} -# endif /* ! ACE_LACKS_LONGLONG_T */ - -ACE_END_VERSIONED_NAMESPACE_DECL - -// 64-bit literals require special marking on some platforms. -# if defined (ACE_LACKS_LONGLONG_T) - // Can only specify 32-bit arguments. -# define ACE_UINT64_LITERAL(n) n ## UL - // This one won't really work, but it'll keep - // some compilers happy until we have better support -# define ACE_INT64_LITERAL(n) n ## L -# elif defined (ACE_WIN32) -# if defined (__MINGW32__) -# define ACE_UINT64_LITERAL(n) n ## ull -# define ACE_INT64_LITERAL(n) n ## ll -# else -# define ACE_UINT64_LITERAL(n) n ## ui64 -# define ACE_INT64_LITERAL(n) n ## i64 -# endif /* defined (__MINGW32__) */ -# elif defined (__TANDEM) -# define ACE_UINT64_LITERAL(n) n ## LL -# define ACE_INT64_LITERAL(n) n ## LL -# else /* ! ACE_WIN32 && ! ACE_LACKS_LONGLONG_T */ -# define ACE_UINT64_LITERAL(n) n ## ull -# define ACE_INT64_LITERAL(n) n ## ll -# endif /* ! ACE_WIN32 && ! ACE_LACKS_LONGLONG_T */ - -#if !defined (ACE_INT8_FORMAT_SPECIFIER_ASCII) -# if defined (PRId8) -# define ACE_INT8_FORMAT_SPECIFIER_ASCII "%" PRId8 -# else -# define ACE_INT8_FORMAT_SPECIFIER_ASCII "%d" -# endif /* defined (PRId8) */ -#endif /* ACE_INT8_FORMAT_SPECIFIER_ASCII */ - -#if !defined (ACE_INT8_FORMAT_SPECIFIER) -# if defined (PRId8) -# define ACE_INT8_FORMAT_SPECIFIER ACE_TEXT ("%") ACE_TEXT (PRId8) -# else -# define ACE_INT8_FORMAT_SPECIFIER ACE_TEXT (ACE_INT8_FORMAT_SPECIFIER_ASCII) -# endif /* defined (PRId8) */ -#endif /* ACE_INT8_FORMAT_SPECIFIER */ - -#if !defined (ACE_UINT8_FORMAT_SPECIFIER_ASCII) -# if defined (PRIu8) -# define ACE_UINT8_FORMAT_SPECIFIER_ASCII "%" PRIu8 -# else -# define ACE_UINT8_FORMAT_SPECIFIER_ASCII "%u" -# endif /* defined (PRIu8) */ -#endif /* ACE_UINT8_FORMAT_SPECIFIER */ - -#if !defined (ACE_UINT8_FORMAT_SPECIFIER) -# if defined (PRIu8) -# define ACE_UINT8_FORMAT_SPECIFIER ACE_TEXT ("%") ACE_TEXT (PRIu8) -# else -# define ACE_UINT8_FORMAT_SPECIFIER ACE_TEXT (ACE_UINT8_FORMAT_SPECIFIER_ASCII) -# endif /* defined (PRIu8) */ -#endif /* ACE_UINT8_FORMAT_SPECIFIER */ - -#if !defined (ACE_INT16_FORMAT_SPECIFIER_ASCII) -# if defined (PRId16) -# define ACE_INT16_FORMAT_SPECIFIER_ASCII "%" PRId16 -# else -# define ACE_INT16_FORMAT_SPECIFIER_ASCII "%d" -# endif /* defined (PRId16) */ -#endif /* ACE_INT16_FORMAT_SPECIFIER */ - -#if !defined (ACE_INT16_FORMAT_SPECIFIER) -# if defined (PRId16) -# define ACE_INT16_FORMAT_SPECIFIER ACE_TEXT ("%") ACE_TEXT (PRId16) -# else -# define ACE_INT16_FORMAT_SPECIFIER ACE_TEXT (ACE_INT16_FORMAT_SPECIFIER_ASCII) -# endif /* defined (PRId16) */ -#endif /* ACE_INT16_FORMAT_SPECIFIER */ - -#if !defined (ACE_UINT16_FORMAT_SPECIFIER_ASCII) -# if defined (PRIu16) -# define ACE_UINT16_FORMAT_SPECIFIER_ASCII "%" PRIu16 -# else -# define ACE_UINT16_FORMAT_SPECIFIER_ASCII "%u" -# endif /* defined (PRIu16) */ -#endif /* ACE_UINT16_FORMAT_SPECIFIER */ - -#if !defined (ACE_UINT16_FORMAT_SPECIFIER) -# if defined (PRIu16) -# define ACE_UINT16_FORMAT_SPECIFIER ACE_TEXT ("%") ACE_TEXT (PRIu16) -# else -# define ACE_UINT16_FORMAT_SPECIFIER ACE_TEXT (ACE_UINT16_FORMAT_SPECIFIER_ASCII) -# endif /* defined (PRIu16) */ -#endif /* ACE_UINT16_FORMAT_SPECIFIER */ - -#if !defined (ACE_INT32_FORMAT_SPECIFIER_ASCII) -# if defined (PRId32) -# define ACE_INT32_FORMAT_SPECIFIER_ASCII "%" PRId32 -# elif ACE_SIZEOF_INT == 4 -# define ACE_INT32_FORMAT_SPECIFIER_ASCII "%d" -# else -# define ACE_INT32_FORMAT_SPECIFIER_ASCII "%ld" -# endif /* defined (PRId32) */ -#endif /* ACE_INT32_FORMAT_SPECIFIER */ - -#if !defined (ACE_INT32_FORMAT_SPECIFIER) -# if defined (PRId32) -# define ACE_INT32_FORMAT_SPECIFIER ACE_TEXT ("%") ACE_TEXT (PRId32) -# else -# define ACE_INT32_FORMAT_SPECIFIER ACE_TEXT (ACE_INT32_FORMAT_SPECIFIER_ASCII) -# endif /* defined (PRId32) */ -#endif /* ACE_INT32_FORMAT_SPECIFIER */ - -#if !defined (ACE_UINT32_FORMAT_SPECIFIER_ASCII) -# if defined (PRIu32) -# define ACE_UINT32_FORMAT_SPECIFIER_ASCII "%" PRIu32 -# elif ACE_SIZEOF_INT == 4 -# define ACE_UINT32_FORMAT_SPECIFIER_ASCII "%u" -# else -# define ACE_UINT32_FORMAT_SPECIFIER_ASCII "%lu" -# endif /* defined (PRIu32) */ -#endif /* ACE_UINT32_FORMAT_SPECIFIER */ - -#if !defined (ACE_UINT32_FORMAT_SPECIFIER) -# if defined (PRIu32) -# define ACE_UINT32_FORMAT_SPECIFIER ACE_TEXT ("%") ACE_TEXT (PRIu32) -# else -# define ACE_UINT32_FORMAT_SPECIFIER ACE_TEXT (ACE_UINT32_FORMAT_SPECIFIER_ASCII) -# endif /* defined (PRIu32) */ -#endif /* ACE_UINT32_FORMAT_SPECIFIER */ - -#if !defined (ACE_INT64_FORMAT_SPECIFIER_ASCII) -# if defined (PRId64) -# define ACE_INT64_FORMAT_SPECIFIER_ASCII "%" PRId64 -# elif ACE_SIZEOF_LONG == 8 -# define ACE_INT64_FORMAT_SPECIFIER_ASCII "%ld" -# else -# define ACE_INT64_FORMAT_SPECIFIER_ASCII "%lld" -# endif /* defined (PRId64) */ -#endif /* ACE_INT64_FORMAT_SPECIFIER */ - -#if !defined (ACE_INT64_FORMAT_SPECIFIER) -# if defined (PRId64) -# define ACE_INT64_FORMAT_SPECIFIER ACE_TEXT ("%") ACE_TEXT (PRId64) -# else -# define ACE_INT64_FORMAT_SPECIFIER ACE_TEXT (ACE_INT64_FORMAT_SPECIFIER_ASCII) -# endif /* defined (PRId64) */ -#endif /* ACE_INT64_FORMAT_SPECIFIER */ - -#if !defined (ACE_UINT64_FORMAT_SPECIFIER_ASCII) -# if defined (PRIu64) -# define ACE_UINT64_FORMAT_SPECIFIER_ASCII "%" PRIu64 -# elif ACE_SIZEOF_LONG == 8 -# define ACE_UINT64_FORMAT_SPECIFIER_ASCII "%lu" -# else -# define ACE_UINT64_FORMAT_SPECIFIER_ASCII "%llu" -# endif /* defined (PRIu64) */ -#endif /* ACE_UINT64_FORMAT_SPECIFIER_ASCII */ - -#if !defined (ACE_UINT64_FORMAT_SPECIFIER) -# if defined (PRIu64) -# define ACE_UINT64_FORMAT_SPECIFIER ACE_TEXT ("%") ACE_TEXT (PRIu64) -# else -# define ACE_UINT64_FORMAT_SPECIFIER ACE_TEXT (ACE_UINT64_FORMAT_SPECIFIER_ASCII) -# endif /* defined (PRIu64) */ -#endif /* ACE_UINT64_FORMAT_SPECIFIER */ - -#if !defined (ACE_SSIZE_T_FORMAT_SPECIFIER_ASCII) -# if defined (ACE_WIN64) -# define ACE_SSIZE_T_FORMAT_SPECIFIER_ASCII "%I64d" -# else -# define ACE_SSIZE_T_FORMAT_SPECIFIER_ASCII "%d" -# endif /* ACE_WIN64 */ -#endif /* ACE_SSIZE_T_FORMAT_SPECIFIER */ - -#if !defined (ACE_SSIZE_T_FORMAT_SPECIFIER) -#define ACE_SSIZE_T_FORMAT_SPECIFIER ACE_TEXT (ACE_SSIZE_T_FORMAT_SPECIFIER_ASCII) -#endif /* ACE_SSIZE_T_FORMAT_SPECIFIER */ - -#if !defined (ACE_SIZE_T_FORMAT_SPECIFIER_ASCII) -# if defined (ACE_WIN64) -# define ACE_SIZE_T_FORMAT_SPECIFIER_ASCII "%I64u" -# else -# define ACE_SIZE_T_FORMAT_SPECIFIER_ASCII "%u" -# endif /* ACE_WIN64 */ -#endif /* ACE_SIZE_T_FORMAT_SPECIFIER */ - -#if !defined (ACE_SIZE_T_FORMAT_SPECIFIER) -#define ACE_SIZE_T_FORMAT_SPECIFIER ACE_TEXT (ACE_SIZE_T_FORMAT_SPECIFIER_ASCII) -#endif /* ACE_SIZE_T_FORMAT_SPECIFIER */ - -// Cast from UINT64 to a double requires an intermediate cast to INT64 -// on some platforms. -# if defined (ACE_LACKS_LONGLONG_T) - // Only use the low 32 bits. -# define ACE_UINT64_DBLCAST_ADAPTER(n) ACE_U64_TO_U32 (n) -# elif defined (ACE_LACKS_UNSIGNEDLONGLONG_T) -# define ACE_UINT64_DBLCAST_ADAPTER(n) ((n).to_int64 ()) -# elif defined (ACE_WIN32) -# define ACE_UINT64_DBLCAST_ADAPTER(n) static_cast<__int64> (n) -# else /* ! ACE_WIN32 && ! ACE_LACKS_LONGLONG_T */ -# define ACE_UINT64_DBLCAST_ADAPTER(n) (n) -# endif /* ! ACE_WIN32 && ! ACE_LACKS_LONGLONG_T */ - - -// The number of bytes in a float. -# ifndef ACE_SIZEOF_FLOAT -# if FLT_MAX_EXP == 128 -# define ACE_SIZEOF_FLOAT 4 -# elif FLT_MAX_EXP == 1024 -# define ACE_SIZEOF_FLOAT 8 -# else -# error: unsupported float size, must be updated for this platform! -# endif /* FLT_MAX_EXP */ -# endif /* ACE_SIZEOF_FLOAT */ - -// The number of bytes in a double. -# ifndef ACE_SIZEOF_DOUBLE -# if DBL_MAX_EXP == 128 -# define ACE_SIZEOF_DOUBLE 4 -# elif DBL_MAX_EXP == 1024 -# define ACE_SIZEOF_DOUBLE 8 -# else -# error: unsupported double size, must be updated for this platform! -# endif /* DBL_MAX_EXP */ -# endif /* ACE_SIZEOF_DOUBLE */ - -// The number of bytes in a long double. -# ifndef ACE_SIZEOF_LONG_DOUBLE -# if LDBL_MAX_EXP == 128 -# define ACE_SIZEOF_LONG_DOUBLE 4 -# elif LDBL_MAX_EXP == 1024 -# if defined (__powerpc64__) -# define ACE_SIZEOF_LONG_DOUBLE 16 -# else -# define ACE_SIZEOF_LONG_DOUBLE 8 -# endif -# elif LDBL_MAX_EXP == 16384 -# if defined (LDBL_DIG) && LDBL_DIG == 18 -# if defined (__ia64) || defined (__x86_64) -# define ACE_SIZEOF_LONG_DOUBLE 16 -# else /* ! __ia64 || __x86_64 */ -# define ACE_SIZEOF_LONG_DOUBLE 12 -# endif /* __ia64 */ -# else /* ! LDBL_DIG || LDBL_DIG != 18 */ -# define ACE_SIZEOF_LONG_DOUBLE 16 -# endif /* ! LDBL_DIG || LDBL_DIG != 18 */ -# else -# error: unsupported double size, must be updated for this platform! -# endif /* LDBL_MAX_EXP */ -# endif /* ACE_SIZEOF_LONG_DOUBLE */ - -// Max and min sizes for the ACE integer types. -#define ACE_CHAR_MAX 0x7F -#define ACE_CHAR_MIN -(ACE_CHAR_MAX)-1 -#define ACE_OCTET_MAX 0xFF -#define ACE_INT16_MAX 0x7FFF -#define ACE_INT16_MIN -(ACE_INT16_MAX)-1 -#define ACE_UINT16_MAX 0xFFFF -#define ACE_WCHAR_MAX ACE_UINT16_MAX -#define ACE_INT32_MAX 0x7FFFFFFF -#define ACE_INT32_MIN -(ACE_INT32_MAX)-1 -#define ACE_UINT32_MAX 0xFFFFFFFF -#define ACE_INT64_MAX ACE_INT64_LITERAL(0x7FFFFFFFFFFFFFFF) -#define ACE_INT64_MIN -(ACE_INT64_MAX)-1 - -#if defined (ACE_LACKS_UNSIGNEDLONGLONG_T) -// ACE_U_LongLong's constructor accepts a "long long" in this -// case. Set it to ACE_U_LongLong (-1) since the bit pattern for long -// long (-1) is the same as the maximum unsigned long long value. -# define ACE_UINT64_MAX ACE_U_LongLong (ACE_INT64_LITERAL (0xFFFFFFFFFFFFFFFF)) -#elif defined (ACE_LACKS_LONGLONG_T) -// ACE_U_LongLong's constructor accepts an ACE_UINT32 low and high -// pair of parameters. -# define ACE_UINT64_MAX ACE_U_LongLong (0xFFFFFFFFu, 0xFFFFFFFFu) -#else -# define ACE_UINT64_MAX ACE_UINT64_LITERAL (0xFFFFFFFFFFFFFFFF) -#endif /* ACE_LACKS_UNSIGNEDLONGLONG_T */ - -// These use ANSI/IEEE format. -#define ACE_FLT_MAX 3.402823466e+38F -#define ACE_FLT_MIN 1.175494351e-38F -#define ACE_DBL_MAX 1.7976931348623158e+308 -#define ACE_DBL_MIN 2.2250738585072014e-308 - -# if defined (__ACE_INLINE__) -# include "ace/Basic_Types.inl" -# endif /* __ACE_INLINE__ */ - -# include /**/ "ace/post.h" -#endif /* ACE_BASIC_TYPES_H */ diff --git a/externals/ace/Basic_Types.inl b/externals/ace/Basic_Types.inl deleted file mode 100644 index c6f0013d45e..00000000000 --- a/externals/ace/Basic_Types.inl +++ /dev/null @@ -1,954 +0,0 @@ -// -*- C++ -*- -// -// $Id: Basic_Types.inl 80826 2008-03-04 14:51:23Z wotte $ - -# if !defined (ACE_LACKS_LONGLONG_T) && defined (ACE_LACKS_UNSIGNEDLONGLONG_T) - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Implementation for ACE_U_LongLong when we have signed long long -// but no unsigned long long. - -ACE_INLINE -ACE_U_LongLong::ACE_U_LongLong (const long long value) - : data_ (value) -{ -} - -ACE_INLINE ACE_UINT32 -ACE_U_LongLong::hi (void) const -{ - return (data_ >> 32) & 0xFFFFFFFF; -} - -ACE_INLINE ACE_UINT32 -ACE_U_LongLong::lo (void) const -{ - return data_ & 0xFFFFFFFF; -} - -ACE_INLINE void -ACE_U_LongLong::hi (const ACE_UINT32 hi) -{ - data_ = hi; - data_ <<= 32; -} - -ACE_INLINE void -ACE_U_LongLong::lo (const ACE_UINT32 lo) -{ - data_ = lo; -} - -ACE_INLINE long long -ACE_U_LongLong::to_int64 (void) const -{ - return data_; -} - -ACE_INLINE -ACE_U_LongLong::~ACE_U_LongLong (void) -{ -} - -ACE_INLINE bool -ACE_U_LongLong::operator== (const ACE_U_LongLong &n) const -{ - return data_ == n.data_; -} - -ACE_INLINE bool -ACE_U_LongLong::operator== (const ACE_UINT32 n) const -{ - return data_ == n; -} - -ACE_INLINE bool -ACE_U_LongLong::operator!= (const ACE_U_LongLong &n) const -{ - return ! (*this == n); -} - -ACE_INLINE bool -ACE_U_LongLong::operator!= (const ACE_UINT32 n) const -{ - return ! (*this == n); -} - -ACE_INLINE bool -ACE_U_LongLong::operator< (const ACE_U_LongLong &n) const -{ - if (data_ > 0) - if (n.data_ > 0) - return data_ < n.data_; - else - return true; - else - if (n.data_ > 0) - return false; - else - return data_ < n.data_; -} - -ACE_INLINE bool -ACE_U_LongLong::operator< (const ACE_UINT32 n) const -{ - return operator< (static_cast (n)); -} - -ACE_INLINE bool -ACE_U_LongLong::operator<= (const ACE_U_LongLong &n) const -{ - if (data_ == n.data_) return true; - - return data_ < n.data_; -} - -ACE_INLINE bool -ACE_U_LongLong::operator<= (const ACE_UINT32 n) const -{ - return operator<= (static_cast (n)); -} - -ACE_INLINE bool -ACE_U_LongLong::operator> (const ACE_U_LongLong &n) const -{ - if (data_ > 0) - if (n.data_ > 0) - return data_ > n.data_; - else - return false; - else - if (n.data_ > 0) - return true; - else - return data_ > n.data_; -} - -ACE_INLINE bool -ACE_U_LongLong::operator> (const ACE_UINT32 n) const -{ - return operator> (static_cast (n)); -} - -ACE_INLINE bool -ACE_U_LongLong::operator>= (const ACE_U_LongLong &n) const -{ - if (data_ == n.data_) return true; - - return data_ > n.data_; -} - -ACE_INLINE bool -ACE_U_LongLong::operator>= (const ACE_UINT32 n) const -{ - return operator>= (static_cast (n)); -} - -ACE_INLINE -ACE_U_LongLong::ACE_U_LongLong (const ACE_U_LongLong &n) - : data_ (n.data_) -{ -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator= (const ACE_U_LongLong &n) -{ - data_ = n.data_; - - return *this; -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator= (const ACE_INT32 &rhs) -{ - if (rhs >= 0) - { - data_ = rhs; - data_ &= 0xFFFFFFFF; - } - else - { - // We do not handle the case where a negative 32 bit integer is - // assigned to this representation of a 64 bit unsigned integer. - // The "undefined behavior" behavior performed by this - // implementation is to simply set all bits to zero. - data_ = 0; - } - - return *this; -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator= (const ACE_UINT32 &rhs) -{ - data_ = rhs; - - return *this; -} - - -ACE_INLINE ACE_U_LongLong -ACE_U_LongLong::operator+ (const ACE_U_LongLong &n) const -{ - return data_ + n.data_; -} - -ACE_INLINE ACE_U_LongLong -ACE_U_LongLong::operator+ (const ACE_UINT32 n) const -{ - return operator+ (static_cast (n)); -} - -ACE_INLINE ACE_U_LongLong -ACE_U_LongLong::operator- (const ACE_U_LongLong &n) const -{ - return data_ - n.data_; -} - -ACE_INLINE ACE_U_LongLong -ACE_U_LongLong::operator- (const ACE_UINT32 n) const -{ - return operator- (static_cast (n)); -} - -ACE_INLINE ACE_U_LongLong -ACE_U_LongLong::operator<< (const u_int n) const -{ - return data_ << n; -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator<<= (const u_int n) -{ - data_ <<= n; - - return *this; -} - -ACE_INLINE ACE_U_LongLong -ACE_U_LongLong::operator>> (const u_int n) const -{ - return data_ >> n; -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator>>= (const u_int n) -{ - data_ >>= n; - - return *this; -} - -ACE_INLINE double -ACE_U_LongLong::operator/ (const double n) const -{ - return data_ / n; -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator+= (const ACE_U_LongLong &n) -{ - data_ += n.data_; - - return *this; -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator+= (const ACE_UINT32 n) -{ - return operator+= (static_cast (n)); -} - -ACE_INLINE ACE_U_LongLong -ACE_U_LongLong::operator* (const ACE_UINT32 n) const -{ - return data_ * n; -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator*= (const ACE_UINT32 n) -{ - data_ *= n; - - return *this; -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator-= (const ACE_U_LongLong &n) -{ - data_ -= n.data_; - - return *this; -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator-= (const ACE_UINT32 n) -{ - return operator-= (static_cast (n)); -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator++ () -{ - ++data_; - - return *this; -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator-- () -{ - --data_; - - return *this; -} - -ACE_INLINE const ACE_U_LongLong -ACE_U_LongLong::operator++ (int) -{ - // Post-increment operator should always be implemented in terms of - // the pre-increment operator to enforce consistent semantics. - ACE_U_LongLong temp (*this); - ++*this; - return temp; -} - -ACE_INLINE const ACE_U_LongLong -ACE_U_LongLong::operator-- (int) -{ - // Post-decrement operator should always be implemented in terms of - // the pre-decrement operator to enforce consistent semantics. - ACE_U_LongLong temp (*this); - --*this; - return temp; -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator|= (const ACE_U_LongLong n) -{ - data_ |= n.data_; - - return *this; -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator|= (const ACE_UINT32 n) -{ - return operator|= (static_cast (n)); -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator&= (const ACE_U_LongLong n) -{ - data_ &= n.data_; - - return *this; -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator&= (const ACE_UINT32 n) -{ - return operator&= (static_cast (n)); -} - -ACE_INLINE ACE_UINT32 -ACE_U_LongLong::operator/ (const ACE_UINT32 n) const -{ - return data_ / n; -} - -ACE_INLINE ACE_UINT32 -ACE_U_LongLong::operator% (const ACE_UINT32 n) const -{ - return data_ % n; -} - -ACE_INLINE ACE_UINT32 -ACE_U_LongLong::operator| (const ACE_INT32 n) const -{ - return data_ | n; -} - -ACE_INLINE ACE_UINT32 -ACE_U_LongLong::operator& (const ACE_INT32 n) const -{ - return data_ & n; -} - -ACE_INLINE ACE_U_LongLong -ACE_U_LongLong::operator* (const ACE_INT32 n) const -{ - return operator* ((ACE_UINT32) n); -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator*= (const ACE_INT32 n) -{ - return operator*= ((ACE_UINT32) n); -} - -ACE_INLINE ACE_UINT32 -ACE_U_LongLong::operator/ (const ACE_INT32 n) const -{ - return operator/ ((ACE_UINT32) n); -} - -#if ACE_SIZEOF_INT == 4 -ACE_INLINE ACE_UINT32 -ACE_U_LongLong::operator/ (const u_long n) const -{ - return operator/ ((ACE_UINT32) n); -} - -ACE_INLINE ACE_UINT32 -ACE_U_LongLong::operator/ (const long n) const -{ - return operator/ ((ACE_UINT32) n); -} - -#else /* ACE_SIZEOF_INT != 4 */ -ACE_INLINE ACE_UINT32 -ACE_U_LongLong::operator/ (const u_int n) const -{ - return operator/ ((ACE_UINT32) n); -} - -ACE_INLINE ACE_UINT32 -ACE_U_LongLong::operator/ (const int n) const -{ - return operator/ ((ACE_UINT32) n); -} -#endif - -ACE_END_VERSIONED_NAMESPACE_DECL - -#elif defined (ACE_LACKS_LONGLONG_T) - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE -ACE_U_LongLong::ACE_U_LongLong (const ACE_UINT32 lo, const ACE_UINT32 hi) -{ - h_ () = hi; - l_ () = lo; -} - -ACE_INLINE ACE_UINT32 -ACE_U_LongLong::hi (void) const -{ - return h_ (); -} - -ACE_INLINE ACE_UINT32 -ACE_U_LongLong::lo (void) const -{ - return l_ (); -} - -ACE_INLINE void -ACE_U_LongLong::hi (const ACE_UINT32 hi) -{ - h_ () = hi; -} - -ACE_INLINE void -ACE_U_LongLong::lo (const ACE_UINT32 lo) -{ - l_ () = lo; -} - -ACE_INLINE -ACE_U_LongLong::~ACE_U_LongLong (void) -{ -} - -ACE_INLINE bool -ACE_U_LongLong::operator== (const ACE_U_LongLong &n) const -{ - return h_ () == n.h_ () && l_ () == n.l_ (); -} - -ACE_INLINE bool -ACE_U_LongLong::operator== (const ACE_UINT32 n) const -{ - return h_ () == 0 && l_ () == n; -} - -ACE_INLINE bool -ACE_U_LongLong::operator!= (const ACE_U_LongLong &n) const -{ - return ! (*this == n); -} - -ACE_INLINE bool -ACE_U_LongLong::operator!= (const ACE_UINT32 n) const -{ - return ! (*this == n); -} - -ACE_INLINE bool -ACE_U_LongLong::operator< (const ACE_U_LongLong &n) const -{ - return h_ () < n.h_ () ? 1 - : h_ () > n.h_ () ? 0 - : l_ () < n.l_ (); -} - -ACE_INLINE bool -ACE_U_LongLong::operator< (const ACE_UINT32 n) const -{ - return operator< (static_cast (n)); -} - -ACE_INLINE bool -ACE_U_LongLong::operator<= (const ACE_U_LongLong &n) const -{ - return h_ () < n.h_ () ? 1 - : h_ () > n.h_ () ? 0 - : l_ () <= n.l_ (); -} - -ACE_INLINE bool -ACE_U_LongLong::operator<= (const ACE_UINT32 n) const -{ - return operator<= (static_cast (n)); -} - -ACE_INLINE bool -ACE_U_LongLong::operator> (const ACE_U_LongLong &n) const -{ - return h_ () > n.h_ () ? 1 - : h_ () < n.h_ () ? 0 - : l_ () > n.l_ (); -} - -ACE_INLINE bool -ACE_U_LongLong::operator> (const ACE_UINT32 n) const -{ - return operator> (static_cast (n)); -} - -ACE_INLINE bool -ACE_U_LongLong::operator>= (const ACE_U_LongLong &n) const -{ - return h_ () > n.h_ () ? 1 - : h_ () < n.h_ () ? 0 - : l_ () >= n.l_ (); -} - -ACE_INLINE bool -ACE_U_LongLong::operator>= (const ACE_UINT32 n) const -{ - return operator>= (static_cast (n)); -} - -ACE_INLINE -ACE_U_LongLong::ACE_U_LongLong (const ACE_U_LongLong &n) -{ - h_ () = n.h_ (); - l_ () = n.l_ (); -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator= (const ACE_U_LongLong &n) -{ - h_ () = n.h_ (); - l_ () = n.l_ (); - - return *this; -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator= (const ACE_INT32 &rhs) -{ - if (rhs >= 0) - { - l_ () = static_cast (rhs); - h_ () = 0; - } - else - { - // We do not handle the case where a negative 32 bit integer is - // assigned to this representation of a 64 bit unsigned integer. - // The "undefined behavior" behavior performed by this - // implementation is to simply set all bits to zero. - l_ () = 0; - h_ () = 0; - } - - return *this; -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator= (const ACE_UINT32 &rhs) -{ - l_ () = rhs; - h_ () = 0; - - return *this; -} - - -ACE_INLINE ACE_U_LongLong -ACE_U_LongLong::operator+ (const ACE_U_LongLong &n) const -{ - ACE_U_LongLong ret (l_ () + n.l_ (), h_ () + n.h_ ()); - if (ret.l_ () < n.l_ ()) /* carry */ ++ret.h_ (); - - return ret; -} - -ACE_INLINE ACE_U_LongLong -ACE_U_LongLong::operator+ (const ACE_UINT32 n) const -{ - return operator+ (static_cast (n)); -} - -ACE_INLINE ACE_U_LongLong -ACE_U_LongLong::operator- (const ACE_U_LongLong &n) const -{ - ACE_U_LongLong ret (l_ () - n.l_ (), h_ () - n.h_ ()); - if (l_ () < n.l_ ()) /* borrow */ --ret.h_ (); - - return ret; -} - -ACE_INLINE ACE_U_LongLong -ACE_U_LongLong::operator- (const ACE_UINT32 n) const -{ - return operator- (static_cast (n)); -} - -ACE_INLINE ACE_U_LongLong -ACE_U_LongLong::operator<< (const u_int n) const -{ - const ACE_UINT32 carry_mask = l_ () >> (32 - n); - ACE_U_LongLong ret (n < 32 ? l_ () << n : 0, - n < 32 ? (h_ () << n) | carry_mask : carry_mask); - - return ret; -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator<<= (const u_int n) -{ - const ACE_UINT32 carry_mask = l_ () >> (32 - n); - h_ () = n < 32 ? (h_ () << n) | carry_mask : carry_mask; - - // g++ 2.7.2.3/Solaris 2.5.1 doesn't modify l_ () if shifted by 32. - l_ () = n < 32 ? l_ () << n : 0; - - return *this; -} - -ACE_INLINE ACE_U_LongLong -ACE_U_LongLong::operator>> (const u_int n) const -{ - const ACE_UINT32 carry_mask = h_ () << (32 - n); - ACE_U_LongLong ret (n < 32 ? (l_ () >> n) | carry_mask : 0, - n < 32 ? h_ () >> n : 0); - - return ret; -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator>>= (const u_int n) -{ - const ACE_UINT32 carry_mask = h_ () << (32 - n); - l_ () = n < 32 ? (l_ () >> n) | carry_mask : carry_mask; - h_ () = n < 32 ? h_ () >> n : 0; - - return *this; -} - -ACE_INLINE double -ACE_U_LongLong::operator/ (const double n) const -{ - // See the derivation above in operator/ (const ACE_UINT32). - - return ((double) 0xffffffffu - n + 1.0) / n * h_ () + - (double) h_ () + (double) l_ () / n; -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator+= (const ACE_U_LongLong &n) -{ - h_ () += n.h_ (); - l_ () += n.l_ (); - if (l_ () < n.l_ ()) /* carry */ ++h_ (); - - return *this; -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator+= (const ACE_UINT32 n) -{ - return operator+= (static_cast (n)); -} - -#define ACE_HIGHBIT (~(~0UL >> 1)) - -ACE_INLINE ACE_UINT32 -ACE_U_LongLong::ul_shift (ACE_UINT32 a, ACE_UINT32 c_in, ACE_UINT32 *c_out) const -{ - const ACE_UINT32 b = (a << 1) | c_in; - *c_out = (*c_out << 1) + ((a & ACE_HIGHBIT) > 0); - - return b; -} - -ACE_INLINE ACE_U_LongLong -ACE_U_LongLong::ull_shift (ACE_U_LongLong a, - ACE_UINT32 c_in, - ACE_UINT32 *c_out) const -{ - ACE_U_LongLong b; - - b.l_ () = (a.l_ () << 1) | c_in; - c_in = ((a.l_ () & ACE_HIGHBIT) > 0); - b.h_ () = (a.h_ () << 1) | c_in; - *c_out = (*c_out << 1) + ((a.h_ () & ACE_HIGHBIT) > 0); - - return b; -} - -ACE_INLINE ACE_U_LongLong -ACE_U_LongLong::ull_add (ACE_U_LongLong a, ACE_U_LongLong b, ACE_UINT32 *carry) const -{ - ACE_U_LongLong r (0, 0); - ACE_UINT32 c1, c2, c3, c4; - - c1 = a.l_ () % 2; - c2 = b.l_ () % 2; - c3 = 0; - - r.l_ () = a.l_ ()/2 + b.l_ ()/2 + (c1+c2)/2; - r.l_ () = ul_shift (r.l_ (), (c1+c2)%2, &c3); - - c1 = a.h_ () % 2; - c2 = b.h_ () % 2; - c4 = 0; - - r.h_ () = a.h_ ()/2 + b.h_ ()/2 + (c1+c2+c3)/2; - r.h_ () = ul_shift (r.h_ (), (c1+c2+c3)%2, &c4); - - *carry = c4; - - return r; -} - -ACE_INLINE ACE_U_LongLong -ACE_U_LongLong::ull_mult (ACE_U_LongLong a, ACE_UINT32 b, ACE_UINT32 *carry) const -{ - register ACE_UINT32 mask = ACE_HIGHBIT; - const ACE_U_LongLong zero (0, 0); - ACE_U_LongLong accum (0, 0); - ACE_UINT32 c; - - *carry = 0; - if (b > 0) - do - { - accum = ull_shift (accum, 0U, carry); - if (b & mask) - accum = ull_add (accum, a, &c); - else - accum = ull_add (accum, zero, &c); - *carry += c; - mask >>= 1; - } - while (mask > 0); - - return accum; -} - -ACE_INLINE ACE_U_LongLong -ACE_U_LongLong::operator* (const ACE_UINT32 n) const -{ - ACE_UINT32 carry; // will throw the carry away - - return ull_mult (*this, n, &carry); -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator*= (const ACE_UINT32 n) -{ - ACE_UINT32 carry; // will throw the carry away - - return *this = ull_mult (*this, n, &carry); -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator-= (const ACE_U_LongLong &n) -{ - h_ () -= n.h_ (); - if (l_ () < n.l_ ()) /* borrow */ --h_ (); - l_ () -= n.l_ (); - - return *this; -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator-= (const ACE_UINT32 n) -{ - return operator-= (static_cast (n)); -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator++ () -{ - ++l_ (); - if (l_ () == 0) /* carry */ ++h_ (); - - return *this; -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator-- () -{ - if (l_ () == 0) /* borrow */ --h_ (); - --l_ (); - - return *this; -} - -ACE_INLINE const ACE_U_LongLong -ACE_U_LongLong::operator++ (int) -{ - // Post-increment operator should always be implemented in terms of - // the pre-increment operator to enforce consistent semantics. - ACE_U_LongLong temp (*this); - ++*this; - return temp; -} - -ACE_INLINE const ACE_U_LongLong -ACE_U_LongLong::operator-- (int) -{ - // Post-decrement operator should always be implemented in terms of - // the pre-decrement operator to enforce consistent semantics. - ACE_U_LongLong temp (*this); - --*this; - return temp; -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator|= (const ACE_U_LongLong n) -{ - l_ () |= n.l_ (); - h_ () |= n.h_ (); - - return *this; -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator|= (const ACE_UINT32 n) -{ - return operator|= (static_cast (n)); -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator&= (const ACE_U_LongLong n) -{ - l_ () &= n.l_ (); - h_ () &= n.h_ (); - - return *this; -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator&= (const ACE_UINT32 n) -{ - return operator&= (static_cast (n)); -} - -ACE_INLINE ACE_UINT32 -ACE_U_LongLong::operator/ (const ACE_UINT32 n) const -{ - // This takes advantage of the fact that the return type has only 32 - // bits. Replace 0x100000000 with 0xffffffff + 1 because the former - // has 33 bits. - // Quotient = (0x100000000u * hi_ + lo_) / n - // = ((0x100000000u - n + n) * hi_ + lo_) / n - // = ((0x100000000u - n) / n * hi_ + hi_ * n / n + lo_ / n - // = (0x100000000u - n) / n * hi_ + hi_ + lo_ / n - // = (0xffffffffu - n + 1) / n * hi_ + hi_ + lo_ / n - - return (0xffffffffu - n + 1) / n * h_ () + h_ () + l_ () / n; -} - -ACE_INLINE ACE_UINT32 -ACE_U_LongLong::operator% (const ACE_UINT32 n) const -{ - // Because the argument is an ACE_UINT32, the result can never be - // bigger than 32 bits. Replace 0x100000000 with 0xffffffff + 1 - // because the former has 33 bits. - // Mod = (0x100000000u * hi_ + lo_) % n - // = (0x100000000u % n * hi_ + lo_ % n) % n - // = ((0x100000000u - n) % n * hi_ + lo_ % n) % n - // = ((0xffffffffu - n + 1) % n * hi_ + lo_ % n) % n - - return ((0xffffffff - n + 1) % n * h_ () + l_ () % n) % n; -} - -ACE_INLINE ACE_UINT32 -ACE_U_LongLong::operator| (const ACE_INT32 n) const -{ - return l_ () | n; -} - -ACE_INLINE ACE_UINT32 -ACE_U_LongLong::operator& (const ACE_INT32 n) const -{ - return l_ () & n; -} - -ACE_INLINE ACE_U_LongLong -ACE_U_LongLong::operator* (const ACE_INT32 n) const -{ - return operator* ((ACE_UINT32) n); -} - -ACE_INLINE ACE_U_LongLong & -ACE_U_LongLong::operator*= (const ACE_INT32 n) -{ - return operator*= ((ACE_UINT32) n); -} - -ACE_INLINE ACE_UINT32 -ACE_U_LongLong::operator/ (const ACE_INT32 n) const -{ - return operator/ ((ACE_UINT32) n); -} - -#if ACE_SIZEOF_INT == 4 -ACE_INLINE ACE_UINT32 -ACE_U_LongLong::operator/ (const u_long n) const -{ - return operator/ ((ACE_UINT32) n); -} - -ACE_INLINE ACE_UINT32 -ACE_U_LongLong::operator/ (const long n) const -{ - return operator/ ((ACE_UINT32) n); -} - -#else /* ACE_SIZEOF_INT != 4 */ -ACE_INLINE ACE_UINT32 -ACE_U_LongLong::operator/ (const u_int n) const -{ - return operator/ ((ACE_UINT32) n); -} - -ACE_INLINE ACE_UINT32 -ACE_U_LongLong::operator/ (const int n) const -{ - return operator/ ((ACE_UINT32) n); -} -#endif /* ACE_SIZEOF_INT != 4 */ - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_LACKS_LONGLONG_T || ACE_LACKS_UNSIGNEDLONGLONG_T */ diff --git a/externals/ace/Bound_Ptr.h b/externals/ace/Bound_Ptr.h deleted file mode 100644 index 5176ff9514a..00000000000 --- a/externals/ace/Bound_Ptr.h +++ /dev/null @@ -1,388 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Bound_Ptr.h - * - * $Id: Bound_Ptr.h 82723 2008-09-16 09:35:44Z johnnyw $ - * - * @author Christopher Kohlhoff - * @author Boris Kolpackov - */ -//============================================================================= - -#ifndef ACE_BOUND_PTR_H -#define ACE_BOUND_PTR_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Auto_Ptr.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Bound_Ptr_Counter - * - * @brief An ACE_Bound_Ptr_Counter object encapsulates an - * object reference count. - * - * Do not use this class directly, use ACE_Strong_Bound_Ptr or - * ACE_Weak_Bound_Ptr instead. - */ -template -class ACE_Bound_Ptr_Counter -{ -public: - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - - ACE_Bound_Ptr_Counter (long init_obj_ref_count = 0); - ~ACE_Bound_Ptr_Counter (void); - - /// Create a ACE_Bound_Ptr_Counter and initialize the - /// reference count to indicate ownership by a strong pointer. - static ACE_Bound_Ptr_Counter *create_strong (void); - - /// Increase both the object and counter reference counts and return - /// the new object reference count. A return value of -1 indicates - /// that the object has already been destroyed. - static long attach_strong (ACE_Bound_Ptr_Counter *counter); - - /// Decreases both the object and counter reference counts and - /// deletes whichever has no more references. Returns the new object - /// reference count. - static long detach_strong (ACE_Bound_Ptr_Counter *counter); - - /// Create a ACE_Bound_Ptr_Counter and initialize the - /// reference count to indicate no ownership. - static ACE_Bound_Ptr_Counter *create_weak (void); - - /// Increase the counter reference count and return argument. - static void attach_weak (ACE_Bound_Ptr_Counter *counter); - - /// Decreases the counter reference count and deletes the counter if - /// it has no more references. - static void detach_weak (ACE_Bound_Ptr_Counter *counter); - - /// Determine whether the object has been deleted. - static bool object_was_deleted (ACE_Bound_Ptr_Counter *counter); - -private: - - /// Allocate a new ACE_Bound_Ptr_Counter instance, - /// returning NULL if it cannot be created. - static ACE_Bound_Ptr_Counter *internal_create (long init_obj_ref_count); - -private: - - /// Reference count of underlying object. Is set to -1 once the - /// object has been destroyed to indicate to all weak pointers that - /// it is no longer valid. - long obj_ref_count_; - - /// Reference count of this counter. - long self_ref_count_; - - /// Mutex variable to synchronize access to the reference counts. - ACE_LOCK lock_; -}; - -// Forward decl. -template class ACE_Weak_Bound_Ptr; - -/** - * @class ACE_Strong_Bound_Ptr - * - * @brief This class implements support for a reference counted - * pointer. - * - * Assigning or copying instances of an ACE_Strong_Bound_Ptr will - * automatically increment the reference count of the underlying object. - * When the last instance of an ACE_Strong_Bound_Ptr that references a - * particular object is destroyed or overwritten, it will invoke delete - * on its underlying pointer. - */ -template -class ACE_Strong_Bound_Ptr -{ -public: - /// Constructor that initializes an ACE_Strong_Bound_Ptr to point to the - /// object \ immediately. - explicit ACE_Strong_Bound_Ptr (X *p = 0); - - /// Constructor that initializes an ACE_Strong_Bound_Ptr by stealing - /// ownership of an object from an auto_ptr. - explicit ACE_Strong_Bound_Ptr (auto_ptr p); - - /// Copy constructor binds @c this and @a r to the same object. - ACE_Strong_Bound_Ptr (const ACE_Strong_Bound_Ptr &r); - - /// Constructor binds @c this and @a r to the same object. - ACE_Strong_Bound_Ptr (const ACE_Weak_Bound_Ptr &r); - - /// Copy constructor binds @c this and @a r to the same object if - /// Y* can be implicitly converted to X*. - template - ACE_Strong_Bound_Ptr (const ACE_Strong_Bound_Ptr &r) - : counter_ (r.counter_), - ptr_ (dynamic_cast(r.ptr_)) - { - // This ctor is temporarily defined here to increase our chances - // of being accepted by broken compilers. - // - COUNTER::attach_strong (this->counter_); - } - - /// Destructor. - ~ACE_Strong_Bound_Ptr (void); - - /// Assignment operator that binds @c this and @a r to the same object. - void operator = (const ACE_Strong_Bound_Ptr &r); - - /// Assignment operator that binds @c this and @a r to the same object. - void operator = (const ACE_Weak_Bound_Ptr &r); - - /// Assignment operator that binds @c this and @a r to the same object - /// if Y* can be implicitly converted to X*. - template - ACE_Weak_Bound_Ptr& - operator= (const ACE_Strong_Bound_Ptr &r) - { - // This operator is temporarily defined here to increase our chances - // of being accepted by broken compilers. - // - - // This will work if &r == this, by first increasing the ref count - - COUNTER *new_counter = r.counter_; - X* new_ptr = dynamic_cast (r.ptr_); - COUNTER::attach_strong (new_counter); - if (COUNTER::detach_strong (this->counter_) == 0) - delete this->ptr_; - this->counter_ = new_counter; - this->ptr_ = new_ptr; - - return *this; - } - - /// Equality operator that returns @c true if both - /// ACE_Strong_Bound_Ptr instances point to the same underlying - /// object. - /** - * @note It also returns @c true if both objects have just been - * instantiated and not used yet. - */ - bool operator == (const ACE_Strong_Bound_Ptr &r) const; - - /// Equality operator that returns true if the ACE_Strong_Bound_Ptr - /// and ACE_Weak_Bound_Ptr objects point to the same underlying - /// object. - /** - * @note It also returns @c true if both objects have just been - * instantiated and not used yet. - */ - bool operator == (const ACE_Weak_Bound_Ptr &r) const; - - /// Equality operator that returns @c true if the - /// ACE_Strong_Bound_Ptr and the raw pointer point to the same - /// underlying object. - bool operator == (X *p) const; - - /// Inequality operator, which is the opposite of equality. - bool operator != (const ACE_Strong_Bound_Ptr &r) const; - - /// Inequality operator, which is the opposite of equality. - bool operator != (const ACE_Weak_Bound_Ptr &r) const; - - /// Inequality operator, which is the opposite of equality. - bool operator != (X *p) const; - - /// Redirection operator - X *operator-> (void) const; - - /// Dereference operator - X &operator * (void) const; - - /// Get the pointer value. - X *get (void) const; - - /// Resets the ACE_Strong_Bound_Ptr to refer to a different - /// underlying object. - void reset (X *p = 0); - - /// Resets the ACE_Strong_Bound_Ptr to refer to a different - /// underlying object, ownership of which is stolen from the - /// auto_ptr. - void reset (auto_ptr p); - - /// Allows us to check for NULL on all ACE_Strong_Bound_Ptr - /// objects. - bool null (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - typedef X X_t; // This indirection is for Borland C++. - - friend class ACE_Weak_Bound_Ptr; - - template - friend class ACE_Strong_Bound_Ptr; - - /// The ACE_Bound_Ptr_Counter type. - typedef ACE_Bound_Ptr_Counter COUNTER; - - /// The reference counter. - COUNTER *counter_; - - /// The underlying object. - X *ptr_; -}; - -/** - * @class ACE_Weak_Bound_Ptr - * - * @brief This class implements support for a weak pointer that complements - * ACE_Strong_Bound_Ptr. - * - * Unlike ACE_Strong_Bound_Ptr, assigning or copying instances of an - * ACE_Weak_Bound_Ptr will not automatically increment the reference - * count of the underlying object. What ACE_Weak_Bound_Ptr does is - * preserve the knowledge that the object is in fact reference - * counted, and thus provides an alternative to raw pointers where - * non-ownership associations must be maintained. When the last - * instance of an ACE_Strong_Bound_Ptr that references a particular - * object is destroyed or overwritten, the corresponding - * ACE_Weak_Bound_Ptr instances are set to NULL. - */ -template -class ACE_Weak_Bound_Ptr -{ -public: - /// Constructor that initializes an ACE_Weak_Bound_Ptr to point to - /// the object \ immediately. - explicit ACE_Weak_Bound_Ptr (X *p = 0); - - /// Copy constructor binds @c this and @a r to the same object. - ACE_Weak_Bound_Ptr (const ACE_Weak_Bound_Ptr &r); - - /// Constructor binds @c this and @a r to the same object. - ACE_Weak_Bound_Ptr (const ACE_Strong_Bound_Ptr &r); - - /// Destructor. - ~ACE_Weak_Bound_Ptr (void); - - /// Assignment operator that binds @c this and @a r to the same object. - void operator = (const ACE_Weak_Bound_Ptr &r); - - /// Assignment operator that binds @c this and @a r to the same object. - void operator = (const ACE_Strong_Bound_Ptr &r); - - /// Equality operator that returns @c true if both - /// ACE_Weak_Bound_Ptr objects point to the same underlying object. - /** - * @note It also returns @c true if both objects have just been - * instantiated and not used yet. - */ - bool operator == (const ACE_Weak_Bound_Ptr &r) const; - - /// Equality operator that returns @c true if the ACE_Weak_Bound_Ptr - /// and ACE_Strong_Bound_Ptr objects point to the same underlying - /// object. - /** - * @note It also returns @c true if both objects have just been - * instantiated and not used yet. - */ - bool operator == (const ACE_Strong_Bound_Ptr &r) const; - - /// Equality operator that returns @c true if the ACE_Weak_Bound_Ptr - /// and the raw pointer point to the same underlying object. - bool operator == (X *p) const; - - /// Inequality operator, which is the opposite of equality. - bool operator != (const ACE_Weak_Bound_Ptr &r) const; - - /// Inequality operator, which is the opposite of equality. - bool operator != (const ACE_Strong_Bound_Ptr &r) const; - - /// Inequality operator, which is the opposite of equality. - bool operator != (X *p) const; - - /// Redirection operator. - /** - * It returns a temporary strong pointer and makes use of the - * chaining properties of operator-> to ensure that the underlying - * object does not disappear while you are using it. If you are - * certain of the lifetimes of the object, and do not want to incur - * the locking overhead, then use the unsafe_get method instead. - */ - ACE_Strong_Bound_Ptr operator-> (void) const; - - /// Obtain a strong pointer corresponding to this weak pointer. This - /// function is useful to create a temporary strong pointer for - /// conversion to a reference. - ACE_Strong_Bound_Ptr strong (void) const; - - /// Get the pointer value. Warning: this does not affect the - /// reference count of the underlying object, so it may disappear on - /// you while you are using it if you are not careful. - X *unsafe_get (void) const; - - /// Resets the ACE_Weak_Bound_Ptr to refer to a different underlying - /// object. - void reset (X *p = 0); - - /// Increment the reference count on the underlying object. - /** - * Returns the new reference count on the object. This function may - * be used to integrate the bound pointers into an external - * reference counting mechanism such as those used by COM or CORBA - * servants. - */ - long add_ref (void); - - /// Decrement the reference count on the underlying object, which is deleted - /// if the count has reached zero. - /** - * Returns the new reference count on the object. This function may - * be used to integrate the bound pointers into an external - * reference counting mechanism such as those used by COM or CORBA - * servants. - */ - long remove_ref (void); - - /// Allows us to check for NULL on all ACE_Weak_Bound_Ptr objects. - bool null (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - typedef X X_t; // This indirection is for Borland C++. - - friend class ACE_Strong_Bound_Ptr; - - /// The ACE_Bound_Ptr_Counter type. - typedef ACE_Bound_Ptr_Counter COUNTER; - - /// The reference counter. - COUNTER *counter_; - - /// The underlying object. - X *ptr_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include "ace/Bound_Ptr.inl" - -#include /**/ "ace/post.h" - -#endif /* ACE_BOUND_PTR_H */ diff --git a/externals/ace/Bound_Ptr.inl b/externals/ace/Bound_Ptr.inl deleted file mode 100644 index 399a7bc9b23..00000000000 --- a/externals/ace/Bound_Ptr.inl +++ /dev/null @@ -1,494 +0,0 @@ -/* -*- C++ -*- */ -// $Id: Bound_Ptr.inl 82723 2008-09-16 09:35:44Z johnnyw $ - -// Bound_Ptr.i - -#include "ace/Guard_T.h" -#if !defined (ACE_NEW_THROWS_EXCEPTIONS) -# include "ace/Log_Msg.h" -#endif /* ACE_NEW_THROWS_EXCEPTIONS */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template inline ACE_Bound_Ptr_Counter * -ACE_Bound_Ptr_Counter::internal_create (long init_obj_ref_count) -{ - ACE_Bound_Ptr_Counter *temp = 0; - ACE_NEW_RETURN (temp, - ACE_Bound_Ptr_Counter (init_obj_ref_count), - 0); - return temp; -} - -template inline ACE_Bound_Ptr_Counter * -ACE_Bound_Ptr_Counter::create_strong (void) -{ - // Set initial object reference count to 1. - ACE_Bound_Ptr_Counter *temp = internal_create (1); -#if defined (ACE_NEW_THROWS_EXCEPTIONS) - if (temp == 0) - ACE_throw_bad_alloc; -#else - ACE_ASSERT (temp != 0); -#endif /* ACE_NEW_THROWS_EXCEPTIONS */ - return temp; -} - - - -template inline long -ACE_Bound_Ptr_Counter::attach_strong (ACE_Bound_Ptr_Counter* counter) -{ - ACE_GUARD_RETURN (ACE_LOCK, guard, counter->lock_, -1); - - // Can't attach a strong pointer to an object that has already been deleted. - if (counter->obj_ref_count_ == -1) - return -1; - - long new_obj_ref_count = ++counter->obj_ref_count_; - ++counter->self_ref_count_; - - return new_obj_ref_count; -} - -template inline long -ACE_Bound_Ptr_Counter::detach_strong (ACE_Bound_Ptr_Counter* counter) -{ - ACE_Bound_Ptr_Counter *counter_del = 0; - long new_obj_ref_count; - - { - ACE_GUARD_RETURN (ACE_LOCK, guard, counter->lock_, -1); - - if ((new_obj_ref_count = --counter->obj_ref_count_) == 0) - // Change the object reference count to -1 to indicate that the - // object has been deleted, as opposed to a weak pointer that - // simply hasn't had any strong pointers created from it yet. - counter->obj_ref_count_ = -1; - - if (--counter->self_ref_count_ == 0) - // Since counter contains the lock held by the ACE_Guard, the - // guard needs to be released before freeing the memory holding - // the lock. So save the pointer to free, then release, then - // free. - counter_del = counter; - - } // Release the lock - - delete counter_del; - - return new_obj_ref_count; -} - -template inline ACE_Bound_Ptr_Counter * -ACE_Bound_Ptr_Counter::create_weak (void) -{ - // Set initial object reference count to 0. - - ACE_Bound_Ptr_Counter *temp = internal_create (0); -#if defined (ACE_NEW_THROWS_EXCEPTIONS) - if (temp == 0) - ACE_throw_bad_alloc; -#else - ACE_ASSERT (temp != 0); -#endif /* ACE_NEW_THROWS_EXCEPTIONS */ - return temp; -} - -template inline void -ACE_Bound_Ptr_Counter::attach_weak (ACE_Bound_Ptr_Counter* counter) -{ - ACE_GUARD (ACE_LOCK, guard, counter->lock_); - - ++counter->self_ref_count_; -} - -template inline void -ACE_Bound_Ptr_Counter::detach_weak (ACE_Bound_Ptr_Counter* counter) -{ - ACE_Bound_Ptr_Counter *counter_del = 0; - - { - ACE_GUARD (ACE_LOCK, guard, counter->lock_); - - if (--counter->self_ref_count_ == 0) - // Since counter contains the lock held by the ACE_Guard, the - // guard needs to be released before freeing the memory holding - // the lock. So save the pointer to free, then release, then - // free. - counter_del = counter; - - } // Release the lock - - delete counter_del; -} - -template inline bool -ACE_Bound_Ptr_Counter::object_was_deleted (ACE_Bound_Ptr_Counter *counter) -{ - ACE_GUARD_RETURN (ACE_LOCK, guard, counter->lock_, 0); - - return counter->obj_ref_count_ == -1; -} - -template inline -ACE_Bound_Ptr_Counter::ACE_Bound_Ptr_Counter (long init_obj_ref_count) - : obj_ref_count_ (init_obj_ref_count), - self_ref_count_ (1) -{ -} - -template inline -ACE_Bound_Ptr_Counter::~ACE_Bound_Ptr_Counter (void) -{ -} - -template inline -ACE_Strong_Bound_Ptr::ACE_Strong_Bound_Ptr (X *p) - : counter_ (COUNTER::create_strong ()), - ptr_ (p) -{ -} - -template inline -ACE_Strong_Bound_Ptr::ACE_Strong_Bound_Ptr (auto_ptr p) - : counter_ (COUNTER::create_strong ()), - ptr_ (p.release()) -{ -} - -template inline -ACE_Strong_Bound_Ptr::ACE_Strong_Bound_Ptr (const ACE_Strong_Bound_Ptr &r) - : counter_ (r.counter_), - ptr_ (r.ptr_) -{ - COUNTER::attach_strong (this->counter_); -} - -template inline -ACE_Strong_Bound_Ptr::ACE_Strong_Bound_Ptr (const ACE_Weak_Bound_Ptr &r) - : counter_ (r.counter_), - ptr_ (r.ptr_) -{ - // When creating a strong pointer from a weak one we can't assume that the - // underlying object still exists. Therefore we must check for a return value - // of -1, which indicates that the object has been destroyed. - if (COUNTER::attach_strong (this->counter_) == -1) - { - // Underlying object has already been deleted, so set this pointer to null. - this->counter_ = COUNTER::create_strong (); - this->ptr_ = 0; - } -} - -template inline -ACE_Strong_Bound_Ptr::~ACE_Strong_Bound_Ptr (void) -{ - if (COUNTER::detach_strong (this->counter_) == 0) - delete this->ptr_; -} - -template inline void -ACE_Strong_Bound_Ptr::operator = (const ACE_Strong_Bound_Ptr &rhs) -{ - // This will work if &r == this, by first increasing the ref count, but - // why go through all that? - if (&rhs == this) - return; - - COUNTER *new_counter = rhs.counter_; - X_t *new_ptr = rhs.ptr_; - COUNTER::attach_strong (new_counter); - if (COUNTER::detach_strong (this->counter_) == 0) - delete this->ptr_; - this->counter_ = new_counter; - this->ptr_ = new_ptr; -} - -template inline void -ACE_Strong_Bound_Ptr::operator = (const ACE_Weak_Bound_Ptr &rhs) -{ - // This will work if &r == this, by first increasing the ref count, but - // why go through all that? - if (&rhs == this) - return; - - COUNTER *new_counter = rhs.counter_; - X_t *new_ptr = rhs.ptr_; - - // When creating a strong pointer from a weak one we can't assume that the - // underlying object still exists. Therefore we must check for a return value - // of -1, which indicates that the object has been destroyed. - if (COUNTER::attach_strong (new_counter) == -1) - { - // Underlying object has already been deleted, so set this pointer to null. - new_counter = COUNTER::create_strong (); - new_ptr = 0; - } - - if (COUNTER::detach_strong (this->counter_) == 0) - delete this->ptr_; - this->counter_ = new_counter; - this->ptr_ = new_ptr; -} - -template inline bool -ACE_Strong_Bound_Ptr::operator== (const ACE_Strong_Bound_Ptr &r) const -{ - return this->ptr_ == r.ptr_; -} - -template inline bool -ACE_Strong_Bound_Ptr::operator== (const ACE_Weak_Bound_Ptr &r) const -{ - // Use the weak pointer's operator== since it will check for null. - return r == *this; -} - -template inline bool -ACE_Strong_Bound_Ptr::operator== (X *p) const -{ - return this->ptr_ == p; -} - -template inline bool -ACE_Strong_Bound_Ptr::operator!= (const ACE_Strong_Bound_Ptr &r) const -{ - return this->ptr_ != r.ptr_; -} - -template inline bool -ACE_Strong_Bound_Ptr::operator!= (const ACE_Weak_Bound_Ptr &r) const -{ - // Use the weak pointer's operator!= since it will check for null. - return r != *this; -} - -template inline bool -ACE_Strong_Bound_Ptr::operator!= (X *p) const -{ - return this->ptr_ != p; -} - -template inline X * -ACE_Strong_Bound_Ptr::operator-> (void) const -{ - return this->ptr_; -} - -template inline X & -ACE_Strong_Bound_Ptr::operator *() const -{ - return *this->ptr_; -} - -template inline X* -ACE_Strong_Bound_Ptr::get (void) const -{ - return this->ptr_; -} - -template inline bool -ACE_Strong_Bound_Ptr::null (void) const -{ - return this->ptr_ == 0; -} - -template inline void -ACE_Strong_Bound_Ptr::reset (X *p) -{ - COUNTER *old_counter = this->counter_; - X_t *old_ptr = this->ptr_; - this->counter_ = COUNTER::create_strong (); - this->ptr_ = p; - if (COUNTER::detach_strong (old_counter) == 0) - delete old_ptr; -} - -template inline void -ACE_Strong_Bound_Ptr::reset (auto_ptr p) -{ - COUNTER *old_counter = this->counter_; - X_t *old_ptr = this->ptr_; - this->counter_ = COUNTER::create_strong (); - this->ptr_ = p.release (); - if (COUNTER::detach_strong (old_counter) == 0) - delete old_ptr; -} - -template inline -ACE_Weak_Bound_Ptr::ACE_Weak_Bound_Ptr (X *p) - : counter_ (COUNTER::create_weak ()), - ptr_ (p) -{ -} - -template inline -ACE_Weak_Bound_Ptr::ACE_Weak_Bound_Ptr (const ACE_Weak_Bound_Ptr &r) - : counter_ (r.counter_), - ptr_ (r.ptr_) -{ - COUNTER::attach_weak (this->counter_); -} - -template inline -ACE_Weak_Bound_Ptr::ACE_Weak_Bound_Ptr (const ACE_Strong_Bound_Ptr &r) - : counter_ (r.counter_), - ptr_ (r.ptr_) -{ - COUNTER::attach_weak (this->counter_); -} - -template inline -ACE_Weak_Bound_Ptr::~ACE_Weak_Bound_Ptr (void) -{ - COUNTER::detach_weak (this->counter_); -} - -template inline void -ACE_Weak_Bound_Ptr::operator = (const ACE_Weak_Bound_Ptr &rhs) -{ - // This will work if &rhs == this, by first increasing the ref count - COUNTER *new_counter = rhs.counter_; - COUNTER::attach_weak (new_counter); - COUNTER::detach_weak (this->counter_); - this->counter_ = new_counter; - this->ptr_ = rhs.ptr_; -} - -template inline void -ACE_Weak_Bound_Ptr::operator = (const ACE_Strong_Bound_Ptr &rhs) -{ - // This will work if &rhs == this, by first increasing the ref count - COUNTER *new_counter = rhs.counter_; - COUNTER::attach_weak (new_counter); - COUNTER::detach_weak (this->counter_); - this->counter_ = new_counter; - this->ptr_ = rhs.ptr_; -} - -template inline bool -ACE_Weak_Bound_Ptr::operator== (const ACE_Weak_Bound_Ptr &r) const -{ - // A weak pointer must behave as though it is automatically set to null - // if the underlying object has been deleted. - if (COUNTER::object_was_deleted (this->counter_)) - return r.ptr_ == 0; - - return this->ptr_ == r.ptr_; -} - -template inline bool -ACE_Weak_Bound_Ptr::operator== (const ACE_Strong_Bound_Ptr &r) const -{ - // A weak pointer must behave as though it is automatically set to null - // if the underlying object has been deleted. - if (COUNTER::object_was_deleted (this->counter_)) - return r.ptr_ == 0; - - return this->ptr_ == r.ptr_; -} - -template inline bool -ACE_Weak_Bound_Ptr::operator== (X *p) const -{ - // A weak pointer must behave as though it is automatically set to null - // if the underlying object has been deleted. - if (COUNTER::object_was_deleted (this->counter_)) - return p == 0; - - return this->ptr_ == p; -} - -template inline bool -ACE_Weak_Bound_Ptr::operator!= (const ACE_Weak_Bound_Ptr &r) const -{ - // A weak pointer must behave as though it is automatically set to null - // if the underlying object has been deleted. - if (COUNTER::object_was_deleted (this->counter_)) - return r.ptr_ != 0; - - return this->ptr_ != r.ptr_; -} - -template inline bool -ACE_Weak_Bound_Ptr::operator!= (const ACE_Strong_Bound_Ptr &r) const -{ - // A weak pointer must behave as though it is automatically set to null - // if the underlying object has been deleted. - if (COUNTER::object_was_deleted (this->counter_)) - return r.ptr_ != 0; - - return this->ptr_ != r.ptr_; -} - -template inline bool -ACE_Weak_Bound_Ptr::operator!= (X *p) const -{ - // A weak pointer must behave as though it is automatically set to null - // if the underlying object has been deleted. - if (COUNTER::object_was_deleted (this->counter_)) - return p != 0; - - return this->ptr_ != p; -} - -template inline ACE_Strong_Bound_Ptr -ACE_Weak_Bound_Ptr::operator-> (void) const -{ - return ACE_Strong_Bound_Ptr (*this); -} - -template inline ACE_Strong_Bound_Ptr -ACE_Weak_Bound_Ptr::strong (void) const -{ - return ACE_Strong_Bound_Ptr (*this); -} - -template inline X* -ACE_Weak_Bound_Ptr::unsafe_get (void) const -{ - // We do not check if the object has been deleted, since this operation - // is defined to be unsafe! - return this->ptr_; -} - -template inline bool -ACE_Weak_Bound_Ptr::null (void) const -{ - // A weak pointer must behave as though it is automatically set to null - // if the underlying object has been deleted. - if (COUNTER::object_was_deleted (this->counter_)) - return true; - - return this->ptr_ == 0; -} - -template inline void -ACE_Weak_Bound_Ptr::reset (X *p) -{ - COUNTER *old_counter = this->counter_; - this->counter_ = COUNTER::create_weak (); - this->ptr_ = p; - COUNTER::detach_weak (old_counter); -} - -template inline long -ACE_Weak_Bound_Ptr::add_ref () -{ - return COUNTER::attach_strong (counter_); -} - -template inline long -ACE_Weak_Bound_Ptr::remove_ref () -{ - long new_obj_ref_count = COUNTER::detach_strong (counter_); - if (new_obj_ref_count == 0) - { - delete this->ptr_; - this->ptr_ = 0; - } - return new_obj_ref_count; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/CDR_Base.cpp b/externals/ace/CDR_Base.cpp deleted file mode 100644 index 35393c3f577..00000000000 --- a/externals/ace/CDR_Base.cpp +++ /dev/null @@ -1,802 +0,0 @@ -#include "ace/CDR_Base.h" - -#if !defined (__ACE_INLINE__) -# include "ace/CDR_Base.inl" -#endif /* ! __ACE_INLINE__ */ - -#include "ace/Message_Block.h" -#include "ace/OS_Memory.h" -#include "ace/OS_NS_string.h" - -ACE_RCSID (ace, - CDR_Base, - "$Id: CDR_Base.cpp 86825 2009-09-28 17:45:23Z johnnyw $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -#if defined (NONNATIVE_LONGDOUBLE) -static const ACE_INT16 max_eleven_bit = 0x3ff; -static const ACE_INT16 max_fifteen_bit = 0x3fff; -#endif /* NONNATIVE_LONGDOUBLE */ - -// -// See comments in CDR_Base.inl about optimization cases for swap_XX_array. -// - -void -ACE_CDR::swap_2_array (char const * orig, char* target, size_t n) -{ - // ACE_ASSERT(n > 0); The caller checks that n > 0 - - // We pretend that AMD64/GNU G++ systems have a Pentium CPU to - // take advantage of the inline assembly implementation. - - // Later, we try to read in 32 or 64 bit chunks, - // so make sure we don't do that for unaligned addresses. -#if ACE_SIZEOF_LONG == 8 && \ - !((defined(__amd64__) || defined (__x86_64__)) && defined(__GNUG__)) - char const * const o8 = ACE_ptr_align_binary (orig, 8); - while (orig < o8 && n > 0) - { - ACE_CDR::swap_2 (orig, target); - orig += 2; - target += 2; - --n; - } -#else - char const * const o4 = ACE_ptr_align_binary (orig, 4); - // this is an _if_, not a _while_. The mistmatch can only be by 2. - if (orig != o4) - { - ACE_CDR::swap_2 (orig, target); - orig += 2; - target += 2; - --n; - } -#endif - if (n == 0) - return; - - // - // Loop unrolling. Here be dragons. - // - - // (n & (~3)) is the greatest multiple of 4 not bigger than n. - // In the while loop ahead, orig will move over the array by 8 byte - // increments (4 elements of 2 bytes). - // end marks our barrier for not falling outside. - char const * const end = orig + 2 * (n & (~3)); - - // See if we're aligned for writting in 64 or 32 bit chunks... -#if ACE_SIZEOF_LONG == 8 && \ - !((defined(__amd64__) || defined (__x86_64__)) && defined(__GNUG__)) - if (target == ACE_ptr_align_binary (target, 8)) -#else - if (target == ACE_ptr_align_binary (target, 4)) -#endif - { - while (orig < end) - { -#if defined (ACE_HAS_INTEL_ASSEMBLY) - unsigned int a = - * reinterpret_cast (orig); - unsigned int b = - * reinterpret_cast (orig + 4); - asm ( "bswap %1" : "=r" (a) : "0" (a) ); - asm ( "bswap %1" : "=r" (b) : "0" (b) ); - asm ( "rol $16, %1" : "=r" (a) : "0" (a) ); - asm ( "rol $16, %1" : "=r" (b) : "0" (b) ); - * reinterpret_cast (target) = a; - * reinterpret_cast (target + 4) = b; -#elif defined(ACE_HAS_PENTIUM) \ - && (defined(_MSC_VER) || defined(__BORLANDC__)) \ - && !defined(ACE_LACKS_INLINE_ASSEMBLY) - __asm mov ecx, orig; - __asm mov edx, target; - __asm mov eax, [ecx]; - __asm mov ebx, 4[ecx]; - __asm bswap eax; - __asm bswap ebx; - __asm rol eax, 16; - __asm rol ebx, 16; - __asm mov [edx], eax; - __asm mov 4[edx], ebx; -#elif ACE_SIZEOF_LONG == 8 - // 64 bit architecture. - register unsigned long a = - * reinterpret_cast (orig); - - register unsigned long a1 = (a & 0x00ff00ff00ff00ffUL) << 8; - register unsigned long a2 = (a & 0xff00ff00ff00ff00UL) >> 8; - - a = (a1 | a2); - - * reinterpret_cast (target) = a; -#else - register ACE_UINT32 a = - * reinterpret_cast (orig); - register ACE_UINT32 b = - * reinterpret_cast (orig + 4); - - register ACE_UINT32 a1 = (a & 0x00ff00ffU) << 8; - register ACE_UINT32 b1 = (b & 0x00ff00ffU) << 8; - register ACE_UINT32 a2 = (a & 0xff00ff00U) >> 8; - register ACE_UINT32 b2 = (b & 0xff00ff00U) >> 8; - - a = (a1 | a2); - b = (b1 | b2); - - * reinterpret_cast (target) = a; - * reinterpret_cast (target + 4) = b; -#endif - orig += 8; - target += 8; - } - } - else - { - // We're out of luck. We have to write in 2 byte chunks. - while (orig < end) - { -#if defined (ACE_HAS_INTEL_ASSEMBLY) - unsigned int a = - * reinterpret_cast (orig); - unsigned int b = - * reinterpret_cast (orig + 4); - asm ( "bswap %1" : "=r" (a) : "0" (a) ); - asm ( "bswap %1" : "=r" (b) : "0" (b) ); - // We're little endian. - * reinterpret_cast (target + 2) - = (unsigned short) (a & 0xffff); - * reinterpret_cast (target + 6) - = (unsigned short) (b & 0xffff); - asm ( "shrl $16, %1" : "=r" (a) : "0" (a) ); - asm ( "shrl $16, %1" : "=r" (b) : "0" (b) ); - * reinterpret_cast (target + 0) - = (unsigned short) (a & 0xffff); - * reinterpret_cast (target + 4) - = (unsigned short) (b & 0xffff); -#elif defined (ACE_HAS_PENTIUM) \ - && (defined (_MSC_VER) || defined (__BORLANDC__)) \ - && !defined (ACE_LACKS_INLINE_ASSEMBLY) - __asm mov ecx, orig; - __asm mov edx, target; - __asm mov eax, [ecx]; - __asm mov ebx, 4[ecx]; - __asm bswap eax; - __asm bswap ebx; - // We're little endian. - __asm mov 2[edx], ax; - __asm mov 6[edx], bx; - __asm shr eax, 16; - __asm shr ebx, 16; - __asm mov 0[edx], ax; - __asm mov 4[edx], bx; -#elif ACE_SIZEOF_LONG == 8 - // 64 bit architecture. - register unsigned long a = - * reinterpret_cast (orig); - - register unsigned long a1 = (a & 0x00ff00ff00ff00ffUL) << 8; - register unsigned long a2 = (a & 0xff00ff00ff00ff00UL) >> 8; - - a = (a1 | a2); - - ACE_UINT16 b1 = static_cast (a >> 48); - ACE_UINT16 b2 = static_cast ((a >> 32) & 0xffff); - ACE_UINT16 b3 = static_cast ((a >> 16) & 0xffff); - ACE_UINT16 b4 = static_cast (a & 0xffff); - -#if defined(ACE_LITTLE_ENDIAN) - * reinterpret_cast (target) = b4; - * reinterpret_cast (target + 2) = b3; - * reinterpret_cast (target + 4) = b2; - * reinterpret_cast (target + 6) = b1; -#else - * reinterpret_cast (target) = b1; - * reinterpret_cast (target + 2) = b2; - * reinterpret_cast (target + 4) = b3; - * reinterpret_cast (target + 6) = b4; -#endif -#else - register ACE_UINT32 a = - * reinterpret_cast (orig); - register ACE_UINT32 b = - * reinterpret_cast (orig + 4); - - register ACE_UINT32 a1 = (a & 0x00ff00ff) << 8; - register ACE_UINT32 b1 = (b & 0x00ff00ff) << 8; - register ACE_UINT32 a2 = (a & 0xff00ff00) >> 8; - register ACE_UINT32 b2 = (b & 0xff00ff00) >> 8; - - a = (a1 | a2); - b = (b1 | b2); - - ACE_UINT32 c1 = static_cast (a >> 16); - ACE_UINT32 c2 = static_cast (a & 0xffff); - ACE_UINT32 c3 = static_cast (b >> 16); - ACE_UINT32 c4 = static_cast (b & 0xffff); - -#if defined(ACE_LITTLE_ENDIAN) - * reinterpret_cast (target) = c2; - * reinterpret_cast (target + 2) = c1; - * reinterpret_cast (target + 4) = c4; - * reinterpret_cast (target + 6) = c3; -#else - * reinterpret_cast (target) = c1; - * reinterpret_cast (target + 2) = c2; - * reinterpret_cast (target + 4) = c3; - * reinterpret_cast (target + 6) = c4; -#endif -#endif - - orig += 8; - target += 8; - } - } - - // (n & 3) == (n % 4). - switch (n&3) { - case 3: - ACE_CDR::swap_2 (orig, target); - orig += 2; - target += 2; - case 2: - ACE_CDR::swap_2 (orig, target); - orig += 2; - target += 2; - case 1: - ACE_CDR::swap_2 (orig, target); - } -} - -void -ACE_CDR::swap_4_array (char const * orig, char* target, size_t n) -{ - // ACE_ASSERT (n > 0); The caller checks that n > 0 - -#if ACE_SIZEOF_LONG == 8 - // Later, we read from *orig in 64 bit chunks, - // so make sure we don't generate unaligned readings. - char const * const o8 = ACE_ptr_align_binary (orig, 8); - // The mismatch can only be by 4. - if (orig != o8) - { - ACE_CDR::swap_4 (orig, target); - orig += 4; - target += 4; - --n; - } -#endif /* ACE_SIZEOF_LONG == 8 */ - - if (n == 0) - return; - - // - // Loop unrolling. Here be dragons. - // - - // (n & (~3)) is the greatest multiple of 4 not bigger than n. - // In the while loop, orig will move over the array by 16 byte - // increments (4 elements of 4 bytes). - // ends marks our barrier for not falling outside. - char const * const end = orig + 4 * (n & (~3)); - -#if ACE_SIZEOF_LONG == 8 - // 64 bits architecture. - // See if we can write in 8 byte chunks. - if (target == ACE_ptr_align_binary (target, 8)) - { - while (orig < end) - { - register unsigned long a = - * reinterpret_cast (orig); - register unsigned long b = - * reinterpret_cast (orig + 8); - -#if defined(ACE_HAS_INTEL_ASSEMBLY) - asm ("bswapq %1" : "=r" (a) : "0" (a)); - asm ("bswapq %1" : "=r" (b) : "0" (b)); - asm ("rol $32, %1" : "=r" (a) : "0" (a)); - asm ("rol $32, %1" : "=r" (b) : "0" (b)); -#else - register unsigned long a84 = (a & 0x000000ff000000ffL) << 24; - register unsigned long b84 = (b & 0x000000ff000000ffL) << 24; - register unsigned long a73 = (a & 0x0000ff000000ff00L) << 8; - register unsigned long b73 = (b & 0x0000ff000000ff00L) << 8; - register unsigned long a62 = (a & 0x00ff000000ff0000L) >> 8; - register unsigned long b62 = (b & 0x00ff000000ff0000L) >> 8; - register unsigned long a51 = (a & 0xff000000ff000000L) >> 24; - register unsigned long b51 = (b & 0xff000000ff000000L) >> 24; - - a = (a84 | a73 | a62 | a51); - b = (b84 | b73 | b62 | b51); -#endif - - * reinterpret_cast (target) = a; - * reinterpret_cast (target + 8) = b; - - orig += 16; - target += 16; - } - } - else - { - // We are out of luck, we have to write in 4 byte chunks. - while (orig < end) - { - register unsigned long a = - * reinterpret_cast (orig); - register unsigned long b = - * reinterpret_cast (orig + 8); - -#if defined(ACE_HAS_INTEL_ASSEMBLY) - asm ("bswapq %1" : "=r" (a) : "0" (a)); - asm ("bswapq %1" : "=r" (b) : "0" (b)); - asm ("rol $32, %1" : "=r" (a) : "0" (a)); - asm ("rol $32, %1" : "=r" (b) : "0" (b)); -#else - register unsigned long a84 = (a & 0x000000ff000000ffL) << 24; - register unsigned long b84 = (b & 0x000000ff000000ffL) << 24; - register unsigned long a73 = (a & 0x0000ff000000ff00L) << 8; - register unsigned long b73 = (b & 0x0000ff000000ff00L) << 8; - register unsigned long a62 = (a & 0x00ff000000ff0000L) >> 8; - register unsigned long b62 = (b & 0x00ff000000ff0000L) >> 8; - register unsigned long a51 = (a & 0xff000000ff000000L) >> 24; - register unsigned long b51 = (b & 0xff000000ff000000L) >> 24; - - a = (a84 | a73 | a62 | a51); - b = (b84 | b73 | b62 | b51); -#endif - - ACE_UINT32 c1 = static_cast (a >> 32); - ACE_UINT32 c2 = static_cast (a & 0xffffffff); - ACE_UINT32 c3 = static_cast (b >> 32); - ACE_UINT32 c4 = static_cast (b & 0xffffffff); - -#if defined (ACE_LITTLE_ENDIAN) - * reinterpret_cast (target + 0) = c2; - * reinterpret_cast (target + 4) = c1; - * reinterpret_cast (target + 8) = c4; - * reinterpret_cast (target + 12) = c3; -#else - * reinterpret_cast (target + 0) = c1; - * reinterpret_cast (target + 4) = c2; - * reinterpret_cast (target + 8) = c3; - * reinterpret_cast (target + 12) = c4; -#endif - orig += 16; - target += 16; - } - } - -#else /* ACE_SIZEOF_LONG != 8 */ - - while (orig < end) - { -#if defined (ACE_HAS_PENTIUM) && defined (__GNUG__) - register unsigned int a = - *reinterpret_cast (orig); - register unsigned int b = - *reinterpret_cast (orig + 4); - register unsigned int c = - *reinterpret_cast (orig + 8); - register unsigned int d = - *reinterpret_cast (orig + 12); - - asm ("bswap %1" : "=r" (a) : "0" (a)); - asm ("bswap %1" : "=r" (b) : "0" (b)); - asm ("bswap %1" : "=r" (c) : "0" (c)); - asm ("bswap %1" : "=r" (d) : "0" (d)); - - *reinterpret_cast (target) = a; - *reinterpret_cast (target + 4) = b; - *reinterpret_cast (target + 8) = c; - *reinterpret_cast (target + 12) = d; -#elif defined (ACE_HAS_PENTIUM) \ - && (defined (_MSC_VER) || defined (__BORLANDC__)) \ - && !defined (ACE_LACKS_INLINE_ASSEMBLY) - __asm mov eax, orig - __asm mov esi, target - __asm mov edx, [eax] - __asm mov ecx, 4[eax] - __asm mov ebx, 8[eax] - __asm mov eax, 12[eax] - __asm bswap edx - __asm bswap ecx - __asm bswap ebx - __asm bswap eax - __asm mov [esi], edx - __asm mov 4[esi], ecx - __asm mov 8[esi], ebx - __asm mov 12[esi], eax -#else - register ACE_UINT32 a = - * reinterpret_cast (orig); - register ACE_UINT32 b = - * reinterpret_cast (orig + 4); - register ACE_UINT32 c = - * reinterpret_cast (orig + 8); - register ACE_UINT32 d = - * reinterpret_cast (orig + 12); - - // Expect the optimizer reordering this A LOT. - // We leave it this way for clarity. - a = (a << 24) | ((a & 0xff00) << 8) | ((a & 0xff0000) >> 8) | (a >> 24); - b = (b << 24) | ((b & 0xff00) << 8) | ((b & 0xff0000) >> 8) | (b >> 24); - c = (c << 24) | ((c & 0xff00) << 8) | ((c & 0xff0000) >> 8) | (c >> 24); - d = (d << 24) | ((d & 0xff00) << 8) | ((d & 0xff0000) >> 8) | (d >> 24); - - * reinterpret_cast (target) = a; - * reinterpret_cast (target + 4) = b; - * reinterpret_cast (target + 8) = c; - * reinterpret_cast (target + 12) = d; -#endif - - orig += 16; - target += 16; - } - -#endif /* ACE_SIZEOF_LONG == 8 */ - - // (n & 3) == (n % 4). - switch (n & 3) { - case 3: - ACE_CDR::swap_4 (orig, target); - orig += 4; - target += 4; - case 2: - ACE_CDR::swap_4 (orig, target); - orig += 4; - target += 4; - case 1: - ACE_CDR::swap_4 (orig, target); - } -} - -// -// We don't benefit from unrolling in swap_8_array and swap_16_array -// (swap_8 and swap_16 are big enough). -// -void -ACE_CDR::swap_8_array (char const * orig, char* target, size_t n) -{ - // ACE_ASSERT(n > 0); The caller checks that n > 0 - - char const * const end = orig + 8*n; - while (orig < end) - { - swap_8 (orig, target); - orig += 8; - target += 8; - } -} - -void -ACE_CDR::swap_16_array (char const * orig, char* target, size_t n) -{ - // ACE_ASSERT(n > 0); The caller checks that n > 0 - - char const * const end = orig + 16*n; - while (orig < end) - { - swap_16 (orig, target); - orig += 16; - target += 16; - } -} - -void -ACE_CDR::mb_align (ACE_Message_Block *mb) -{ -#if !defined (ACE_CDR_IGNORE_ALIGNMENT) - char * const start = ACE_ptr_align_binary (mb->base (), - ACE_CDR::MAX_ALIGNMENT); -#else - char * const start = mb->base (); -#endif /* ACE_CDR_IGNORE_ALIGNMENT */ - mb->rd_ptr (start); - mb->wr_ptr (start); -} - -int -ACE_CDR::grow (ACE_Message_Block *mb, size_t minsize) -{ - size_t newsize = - ACE_CDR::first_size (minsize + ACE_CDR::MAX_ALIGNMENT); - - if (newsize <= mb->size ()) - return 0; - - ACE_Data_Block *db = - mb->data_block ()->clone_nocopy (0, newsize); - - if (db == 0) - return -1; - - // Do the equivalent of ACE_CDR::mb_align() here to avoid having - // to allocate an ACE_Message_Block on the stack thereby avoiding - // the manipulation of the data blocks reference count - size_t mb_len = mb->length (); - char *start = ACE_ptr_align_binary (db->base (), - ACE_CDR::MAX_ALIGNMENT); - - ACE_OS::memcpy (start, mb->rd_ptr (), mb_len); - mb->data_block (db); - - // Setting the data block on the mb resets the read and write - // pointers back to the beginning. We must set the rd_ptr to the - // aligned start and adjust the write pointer to the end - mb->rd_ptr (start); - mb->wr_ptr (start + mb_len); - - // Remove the DONT_DELETE flags from mb - mb->clr_self_flags (ACE_Message_Block::DONT_DELETE); - - return 0; -} - -size_t -ACE_CDR::total_length (const ACE_Message_Block* begin, - const ACE_Message_Block* end) -{ - size_t l = 0; - // Compute the total size. - for (const ACE_Message_Block *i = begin; - i != end; - i = i->cont ()) - l += i->length (); - return l; -} - -int -ACE_CDR::consolidate (ACE_Message_Block *dst, - const ACE_Message_Block *src) -{ - if (src == 0) - return 0; - - size_t const newsize = - ACE_CDR::first_size (ACE_CDR::total_length (src, 0) - + ACE_CDR::MAX_ALIGNMENT); - - if (dst->size (newsize) == -1) - return -1; - -#if !defined (ACE_CDR_IGNORE_ALIGNMENT) - // We must copy the contents of src into the new buffer, but - // respecting the alignment. - ptrdiff_t srcalign = - ptrdiff_t(src->rd_ptr ()) % ACE_CDR::MAX_ALIGNMENT; - ptrdiff_t dstalign = - ptrdiff_t(dst->rd_ptr ()) % ACE_CDR::MAX_ALIGNMENT; - ptrdiff_t offset = srcalign - dstalign; - if (offset < 0) - offset += ACE_CDR::MAX_ALIGNMENT; - dst->rd_ptr (static_cast (offset)); - dst->wr_ptr (dst->rd_ptr ()); -#endif /* ACE_CDR_IGNORE_ALIGNMENT */ - - for (const ACE_Message_Block* i = src; - i != 0; - i = i->cont ()) - { - // If the destination and source are the same, do not - // attempt to copy the data. Just update the write pointer. - if (dst->wr_ptr () != i->rd_ptr ()) - dst->copy (i->rd_ptr (), i->length ()); - else - dst->wr_ptr (i->length ()); - } - return 0; -} - -#if defined (NONNATIVE_LONGLONG) -bool -ACE_CDR::LongLong::operator== (const ACE_CDR::LongLong &rhs) const -{ - return this->h == rhs.h && this->l == rhs.l; -} - -bool -ACE_CDR::LongLong::operator!= (const ACE_CDR::LongLong &rhs) const -{ - return this->l != rhs.l || this->h != rhs.h; -} - -#endif /* NONNATIVE_LONGLONG */ - -#if defined (NONNATIVE_LONGDOUBLE) -ACE_CDR::LongDouble& -ACE_CDR::LongDouble::assign (const ACE_CDR::LongDouble::NativeImpl& rhs) -{ - ACE_OS::memset (this->ld, 0, sizeof (this->ld)); - - if (sizeof (rhs) == 8) - { -#if defined (ACE_LITTLE_ENDIAN) - static const size_t byte_zero = 1; - static const size_t byte_one = 0; - char rhs_ptr[16]; - ACE_CDR::swap_8 (reinterpret_cast (&rhs), rhs_ptr); -#else - static const size_t byte_zero = 0; - static const size_t byte_one = 1; - const char* rhs_ptr = reinterpret_cast (&rhs); -#endif - ACE_INT16 sign = static_cast ( - static_cast (rhs_ptr[0])) & 0x8000; - ACE_INT16 exponent = ((rhs_ptr[0] & 0x7f) << 4) | - ((rhs_ptr[1] >> 4) & 0xf); - const char* exp_ptr = reinterpret_cast (&exponent); - - // Infinity and NaN have an exponent of 0x7ff in 64-bit IEEE - if (exponent == 0x7ff) - { - exponent = 0x7fff; - } - else - { - exponent = (exponent - max_eleven_bit) + max_fifteen_bit; - } - exponent |= sign; - - // Store the sign bit and exponent - this->ld[0] = exp_ptr[byte_zero]; - this->ld[1] = exp_ptr[byte_one]; - - // Store the mantissa. In an 8 byte double, it is split by - // 4 bits (because of the 12 bits for sign and exponent), so - // we have to shift and or the rhs to get the right bytes. - size_t li = 2; - bool direction = true; - for (size_t ri = 1; ri < sizeof (rhs);) - { - if (direction) - { - this->ld[li] |= ((rhs_ptr[ri] << 4) & 0xf0); - direction = false; - ++ri; - } - else - { - this->ld[li] |= ((rhs_ptr[ri] >> 4) & 0xf); - direction = true; - ++li; - } - } -#if defined (ACE_LITTLE_ENDIAN) - ACE_OS::memcpy (rhs_ptr, this->ld, sizeof (this->ld)); - ACE_CDR::swap_16 (rhs_ptr, this->ld); -#endif - } - else - { - ACE_OS::memcpy(this->ld, - reinterpret_cast (&rhs), sizeof (rhs)); - } - return *this; -} - -ACE_CDR::LongDouble& -ACE_CDR::LongDouble::assign (const ACE_CDR::LongDouble& rhs) -{ - if (this != &rhs) - *this = rhs; - return *this; -} - -bool -ACE_CDR::LongDouble::operator== (const ACE_CDR::LongDouble &rhs) const -{ - return ACE_OS::memcmp (this->ld, rhs.ld, 16) == 0; -} - -bool -ACE_CDR::LongDouble::operator!= (const ACE_CDR::LongDouble &rhs) const -{ - return ACE_OS::memcmp (this->ld, rhs.ld, 16) != 0; -} - -ACE_CDR::LongDouble::operator ACE_CDR::LongDouble::NativeImpl () const -{ - ACE_CDR::LongDouble::NativeImpl ret = 0.0; - char* lhs_ptr = reinterpret_cast (&ret); - - if (sizeof (ret) == 8) - { -#if defined (ACE_LITTLE_ENDIAN) - static const size_t byte_zero = 1; - static const size_t byte_one = 0; - char copy[16]; - ACE_CDR::swap_16 (this->ld, copy); -#else - static const size_t byte_zero = 0; - static const size_t byte_one = 1; - const char* copy = this->ld; -#endif - ACE_INT16 exponent = 0; - char* exp_ptr = reinterpret_cast (&exponent); - exp_ptr[byte_zero] = copy[0]; - exp_ptr[byte_one] = copy[1]; - - ACE_INT16 sign = (exponent & 0x8000); - exponent &= 0x7fff; - - // Infinity and NaN have an exponent of 0x7fff in 128-bit IEEE - if (exponent == 0x7fff) - { - exponent = 0x7ff; - } - else - { - exponent = (exponent - max_fifteen_bit) + max_eleven_bit; - } - exponent = (exponent << 4) | sign; - - // Store the sign and exponent - lhs_ptr[0] = exp_ptr[byte_zero]; - lhs_ptr[1] = exp_ptr[byte_one]; - - // Store the mantissa. In an 8 byte double, it is split by - // 4 bits (because of the 12 bits for sign and exponent), so - // we have to shift and or the rhs to get the right bytes. - size_t li = 1; - bool direction = true; - for (size_t ri = 2; li < sizeof (ret);) { - if (direction) - { - lhs_ptr[li] |= ((copy[ri] >> 4) & 0xf); - direction = false; - ++li; - } - else - { - lhs_ptr[li] |= ((copy[ri] & 0xf) << 4); - direction = true; - ++ri; - } - } - -#if defined (ACE_LITTLE_ENDIAN) - ACE_CDR::swap_8 (lhs_ptr, lhs_ptr); -#endif - } - else - { - ACE_OS::memcpy(lhs_ptr, this->ld, sizeof (ret)); - } - - // This bit of code is unnecessary. However, this code is - // necessary to work around a bug in the gcc 4.1.1 optimizer. - ACE_CDR::LongDouble tmp; - tmp.assign (ret); - - return ret; -} -#endif /* NONNATIVE_LONGDOUBLE */ - -#if defined(_UNICOS) && !defined(_CRAYMPP) -// placeholders to get things compiling -ACE_CDR::Float::Float (void) -{ -} - -ACE_CDR::Float::Float (const float & /* init */) -{ -} - -ACE_CDR::Float & -ACE_CDR::Float::operator= (const float & /* rhs */) -{ - return *this; -} - -bool -ACE_CDR::Float::operator!= (const ACE_CDR::Float & /* rhs */) const -{ - return false; -} -#endif /* _UNICOS */ - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/CDR_Base.h b/externals/ace/CDR_Base.h deleted file mode 100644 index 12b4a4953fd..00000000000 --- a/externals/ace/CDR_Base.h +++ /dev/null @@ -1,382 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file CDR_Base.h - * - * $Id: CDR_Base.h 88488 2010-01-12 14:20:13Z olli $ - * - * ACE Common Data Representation (CDR) basic types. - * - * The current implementation assumes that the host has 1-byte, - * 2-byte and 4-byte integral types, and that it has single - * precision and double precision IEEE floats. - * Those assumptions are pretty good these days, with Crays being - * the only known exception. - * - * - * @author TAO version by - * @author Aniruddha Gokhale - * @author Carlos O'Ryan - * @author ACE version by - * @author Jeff Parsons - * @author Istvan Buki - */ -//============================================================================= - - -#ifndef ACE_CDR_BASE_H -#define ACE_CDR_BASE_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Basic_Types.h" -#include "ace/Default_Constants.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Stuff used by the ACE CDR classes. Watch these values... they're also used -// in the ACE_CDR Byte_Order enum below. -#if defined ACE_LITTLE_ENDIAN -# define ACE_CDR_BYTE_ORDER 1 -// little endian encapsulation byte order has value = 1 -#else /* ! ACE_LITTLE_ENDIAN */ -# define ACE_CDR_BYTE_ORDER 0 -// big endian encapsulation byte order has value = 0 -#endif /* ! ACE_LITTLE_ENDIAN */ - -class ACE_Message_Block; - -/** - * @class ACE_CDR - * - * @brief Keep constants and some routines common to both Output and - * Input CDR streams. - */ -class ACE_Export ACE_CDR -{ -public: - // = Constants defined by the CDR protocol. - // By defining as many of these constants as possible as enums we - // ensure they get inlined and avoid pointless static memory - // allocations. - - enum - { - // Note that some of these get reused as part of the standard - // binary format: unsigned is the same size as its signed cousin, - // float is LONG_SIZE, and double is LONGLONG_SIZE. - - OCTET_SIZE = 1, - SHORT_SIZE = 2, - LONG_SIZE = 4, - LONGLONG_SIZE = 8, - LONGDOUBLE_SIZE = 16, - - OCTET_ALIGN = 1, - SHORT_ALIGN = 2, - LONG_ALIGN = 4, - LONGLONG_ALIGN = 8, - /// @note the CORBA LongDouble alignment requirements do not - /// match its size... - LONGDOUBLE_ALIGN = 8, - - /// Maximal CDR 1.1 alignment: "quad precision" FP (i.e. "CDR::Long - /// double", size as above). - MAX_ALIGNMENT = 8, - - /// The default buffer size. - /** - * @todo We want to add options to control this - * default value, so this constant should be read as the default - * default value ;-) - */ - DEFAULT_BUFSIZE = ACE_DEFAULT_CDR_BUFSIZE, - - /// The buffer size grows exponentially until it reaches this size; - /// afterwards it grows linearly using the next constant - EXP_GROWTH_MAX = ACE_DEFAULT_CDR_EXP_GROWTH_MAX, - - /// Once exponential growth is ruled out the buffer size increases - /// in chunks of this size, note that this constants have the same - /// value right now, but it does not need to be so. - LINEAR_GROWTH_CHUNK = ACE_DEFAULT_CDR_LINEAR_GROWTH_CHUNK - }; - - /** - * @enum Byte_Order - * - * Defines values for the byte_order argument to ACE_OutputCDR and - * ACE_InputCDR. - */ - enum Byte_Order - { - /// Use big-endian order (also known as network byte order). - BYTE_ORDER_BIG_ENDIAN = 0, - /// Use little-endian order. - BYTE_ORDER_LITTLE_ENDIAN = 1, - /// Use whichever byte order is native to this machine. - BYTE_ORDER_NATIVE = ACE_CDR_BYTE_ORDER - }; - - /** - * Do byte swapping for each basic IDL type size. There exist only - * routines to put byte, halfword (2 bytes), word (4 bytes), - * doubleword (8 bytes) and quadword (16 byte); because those are - * the IDL basic type sizes. - */ - static void swap_2 (char const *orig, char *target); - static void swap_4 (char const *orig, char *target); - static void swap_8 (char const *orig, char *target); - static void swap_16 (char const *orig, char *target); - static void swap_2_array (char const *orig, - char *target, - size_t length); - static void swap_4_array (char const *orig, - char *target, - size_t length); - static void swap_8_array (char const *orig, - char *target, - size_t length); - static void swap_16_array (char const *orig, - char *target, - size_t length); - - /// Align the message block to ACE_CDR::MAX_ALIGNMENT, - /// set by the CORBA spec at 8 bytes. - static void mb_align (ACE_Message_Block *mb); - - /** - * Compute the size of the smallest buffer that can contain at least - * @a minsize bytes. - * To understand how a "best fit" is computed look at the - * algorithm in the code. - * Basically the buffers grow exponentially, up to a certain point, - * then the buffer size grows linearly. - * The advantage of this algorithm is that is rapidly grows to a - * large value, but does not explode at the end. - */ - static size_t first_size (size_t minsize); - - /// Compute not the smallest, but the second smallest buffer that - /// will fir @a minsize bytes. - static size_t next_size (size_t minsize); - - /** - * Increase the capacity of mb to contain at least @a minsize bytes. - * If @a minsize is zero the size is increased by an amount at least - * large enough to contain any of the basic IDL types. - * @retval -1 Failure - * @retval 0 Success. - */ - static int grow (ACE_Message_Block *mb, size_t minsize); - - /** - * Copy a message block chain into a single message block, - * preserving the alignment of the first message block of the - * original stream, not the following message blocks. - * @retval -1 Failure - * @retval 0 Success. - */ - static int consolidate (ACE_Message_Block *dst, - const ACE_Message_Block *src); - - static size_t total_length (const ACE_Message_Block *begin, - const ACE_Message_Block *end); - - /** - * @name Basic OMG IDL Types - * - * These types are for use in the CDR classes. The cleanest way to - * avoid complaints from all compilers is to define them all. - */ - //@{ - typedef bool Boolean; - typedef unsigned char Octet; - typedef char Char; - typedef ACE_WCHAR_T WChar; - typedef ACE_INT16 Short; - typedef ACE_UINT16 UShort; - typedef ACE_INT32 Long; - typedef ACE_UINT32 ULong; - typedef ACE_UINT64 ULongLong; - -# if (defined (_MSC_VER)) || (defined (__BORLANDC__)) - typedef __int64 LongLong; -# elif ACE_SIZEOF_LONG == 8 && !defined(_CRAYMPP) - typedef long LongLong; -# elif defined(__TANDEM) - typedef long long LongLong; -# elif ACE_SIZEOF_LONG_LONG == 8 && !defined (ACE_LACKS_LONGLONG_T) -# if defined (sun) && !defined (ACE_LACKS_U_LONGLONG_T) - // sun #defines u_longlong_t, maybe other platforms do also. - // Use it, at least with g++, so that its -pedantic doesn't - // complain about no ANSI C++ long long. - typedef longlong_t LongLong; -# else - typedef long long LongLong; -# endif /* sun */ -# else /* no native 64 bit integer type */ -# define NONNATIVE_LONGLONG - struct ACE_Export LongLong - { -# if defined (ACE_BIG_ENDIAN) - ACE_CDR::Long h; - ACE_CDR::Long l; -# else - ACE_CDR::Long l; - ACE_CDR::Long h; -# endif /* ! ACE_BIG_ENDIAN */ - - /** - * @name Overloaded Relation Operators. - * - * The canonical comparison operators. - */ - //@{ - bool operator== (const LongLong &rhs) const; - bool operator!= (const LongLong &rhs) const; - //@} - }; -# endif /* no native 64 bit integer type */ - -# if defined (NONNATIVE_LONGLONG) -# define ACE_CDR_LONGLONG_INITIALIZER {0,0} -# else -# define ACE_CDR_LONGLONG_INITIALIZER 0 -# endif /* NONNATIVE_LONGLONG */ - -# if ACE_SIZEOF_FLOAT == 4 - typedef float Float; -# else /* ACE_SIZEOF_FLOAT != 4 */ - struct Float - { -# if ACE_SIZEOF_INT == 4 - // Use unsigned int to get word alignment. - unsigned int f; -# else /* ACE_SIZEOF_INT != 4 */ - // Applications will probably have trouble with this. - char f[4]; -# if defined(_UNICOS) && !defined(_CRAYMPP) - Float (void); - Float (const float &init); - Float & operator= (const float &rhs); - bool operator!= (const Float &rhs) const; -# endif /* _UNICOS */ -# endif /* ACE_SIZEOF_INT != 4 */ - }; -# endif /* ACE_SIZEOF_FLOAT != 4 */ - -# if ACE_SIZEOF_DOUBLE == 8 - typedef double Double; -# else /* ACE_SIZEOF_DOUBLE != 8 */ - struct Double - { -# if ACE_SIZEOF_LONG == 8 - // Use u long to get word alignment. - unsigned long f; -# else /* ACE_SIZEOF_INT != 8 */ - // Applications will probably have trouble with this. - char f[8]; -# endif /* ACE_SIZEOF_INT != 8 */ - }; -# endif /* ACE_SIZEOF_DOUBLE != 8 */ - - // 94-9-32 Appendix A defines a 128 bit floating point "long - // double" data type, with greatly extended precision and four - // more bits of exponent (compared to "double"). This is an IDL - // extension, not yet standard. - -# if ACE_SIZEOF_LONG_DOUBLE == 16 - typedef long double LongDouble; -# define ACE_CDR_LONG_DOUBLE_INITIALIZER 0 -# define ACE_CDR_LONG_DOUBLE_ASSIGNMENT(LHS, RHS) LHS = RHS -# else -# define NONNATIVE_LONGDOUBLE -# define ACE_CDR_LONG_DOUBLE_INITIALIZER {{0}} -# define ACE_CDR_LONG_DOUBLE_ASSIGNMENT(LHS, RHS) LHS.assign (RHS) - struct ACE_Export LongDouble - { - // VxWorks' compiler (gcc 2.96) gets confused by the operator long - // double, so we avoid using long double as the NativeImpl. - // Linux's x86 long double format (12 or 16 bytes) is incompatible - // with Windows, Solaris, AIX, MacOS X and HP-UX (and probably others) - // long double format (8 or 16 bytes). If you need 32-bit Linux to - // inter-operate with 64-bit Linux you will want to define this - // macro to 0 so that "long double" is used. Otherwise, do not define - // this macro. -# if defined (ACE_CDR_IMPLEMENT_WITH_NATIVE_DOUBLE) && \ - (ACE_CDR_IMPLEMENT_WITH_NATIVE_DOUBLE == 1) - typedef double NativeImpl; -# else - typedef long double NativeImpl; -# endif /* ACE_CDR_IMPLEMENT_WITH_NATIVE_DOUBLE==1 */ - - char ld[16]; - - LongDouble& assign (const NativeImpl& rhs); - LongDouble& assign (const LongDouble& rhs); - - bool operator== (const LongDouble &rhs) const; - bool operator!= (const LongDouble &rhs) const; - - LongDouble& operator*= (const NativeImpl rhs) { - return this->assign (static_cast (*this) * rhs); - } - LongDouble& operator/= (const NativeImpl rhs) { - return this->assign (static_cast (*this) / rhs); - } - LongDouble& operator+= (const NativeImpl rhs) { - return this->assign (static_cast (*this) + rhs); - } - LongDouble& operator-= (const NativeImpl rhs) { - return this->assign (static_cast (*this) - rhs); - } - LongDouble& operator++ () { - return this->assign (static_cast (*this) + 1); - } - LongDouble& operator-- () { - return this->assign (static_cast (*this) - 1); - } - LongDouble operator++ (int) { - LongDouble ldv = *this; - this->assign (static_cast (*this) + 1); - return ldv; - } - LongDouble operator-- (int) { - LongDouble ldv = *this; - this->assign (static_cast (*this) - 1); - return ldv; - } - - operator NativeImpl () const; - }; -# endif /* ACE_SIZEOF_LONG_DOUBLE != 16 */ - - //@} - -#if !defined (ACE_CDR_GIOP_MAJOR_VERSION) -# define ACE_CDR_GIOP_MAJOR_VERSION 1 -#endif /*ACE_CDR_GIOP_MAJOR_VERSION */ - -#if !defined (ACE_CDR_GIOP_MINOR_VERSION) -# define ACE_CDR_GIOP_MINOR_VERSION 2 -#endif /* ACE_CDR_GIOP_MINOR_VERSION */ -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -# include "ace/CDR_Base.inl" -#endif /* __ACE_INLINE__ */ - - -#include /**/ "ace/post.h" - -#endif /* ACE_CDR_BASE_H */ diff --git a/externals/ace/CDR_Base.inl b/externals/ace/CDR_Base.inl deleted file mode 100644 index 85373170af7..00000000000 --- a/externals/ace/CDR_Base.inl +++ /dev/null @@ -1,255 +0,0 @@ -// -*- C++ -*- -// -// $Id: CDR_Base.inl 80826 2008-03-04 14:51:23Z wotte $ - -#if defined (ACE_HAS_INTRINSIC_BYTESWAP) -// Take advantage of MSVC++ byte swapping compiler intrinsics (found -// in ). -# pragma intrinsic (_byteswap_ushort, _byteswap_ulong, _byteswap_uint64) -#endif /* ACE_HAS_INTRINSIC_BYTESWAP */ - -#if defined (ACE_HAS_BSWAP_16) || defined (ACE_HAS_BSWAP_32) || defined (ACE_HAS_BSWAP_64) -# include "ace/os_include/os_byteswap.h" -#endif - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// -// The ACE_CDR::swap_X and ACE_CDR::swap_X_array routines are broken -// in 5 cases for optimization: -// -// * MSVC++ 7.1 or better -// => Compiler intrinsics -// -// * AMD64 CPU + gnu g++ -// => gcc amd64 inline assembly. -// -// * x86 Pentium CPU + gnu g++ -// (ACE_HAS_PENTIUM && __GNUG__) -// => gcc x86 inline assembly. -// -// * x86 Pentium CPU and (_MSC_VER) or BORLAND C++) -// (ACE_HAS_PENTIUM && ( _MSC_VER || __BORLANDC__ ) -// => MSC x86 inline assembly. -// -// * 64 bit architecture -// (ACE_SIZEOF_LONG == 8) -// => shift/masks using 64bit words. -// -// * default -// (none of the above) -// => shift/masks using 32bit words. -// -// -// Some things you could find useful to know if you intend to mess -// with this optimizations for swaps: -// -// * MSVC++ don't assume register values are conserved between -// statements. So you can clobber any register you want, -// whenever you want (well not *anyone* really, see manual). -// The MSVC++ optimizer will try to pick different registers -// for the C++ statements sorrounding your asm block, and if -// it's not possible will use the stack. -// -// * If you clobber registers with asm statements in gcc, you -// better do it in an asm-only function, or save/restore them -// before/after in the stack. If not, sorrounding C statements -// could end using the same registers and big-badda-bum (been -// there, done that...). The big-badda-bum could happen *even -// if you specify the clobbered register in your asm's*. -// Even better, use gcc asm syntax for detecting the register -// asigned to a certain variable so you don't have to clobber any -// register directly. -// - -ACE_INLINE void -ACE_CDR::swap_2 (const char *orig, char* target) -{ -#if defined (ACE_HAS_INTRINSIC_BYTESWAP) - // Take advantage of MSVC++ compiler intrinsic byte swapping - // function. - *reinterpret_cast (target) = - _byteswap_ushort (*reinterpret_cast (orig)); -#elif defined (ACE_HAS_BSWAP16) - *reinterpret_cast (target) = - bswap16 (*reinterpret_cast (orig)); -#elif defined (ACE_HAS_BSWAP_16) - *reinterpret_cast (target) = - bswap_16 (*reinterpret_cast (orig)); -#elif defined(ACE_HAS_INTEL_ASSEMBLY) - unsigned short a = - *reinterpret_cast (orig); - asm( "rolw $8, %0" : "=r" (a) : "0" (a) ); - *reinterpret_cast (target) = a; -#elif defined (ACE_HAS_PENTIUM) \ - && (defined(_MSC_VER) || defined(__BORLANDC__)) \ - && !defined(ACE_LACKS_INLINE_ASSEMBLY) - __asm mov ebx, orig; - __asm mov ecx, target; - __asm mov ax, [ebx]; - __asm rol ax, 8; - __asm mov [ecx], ax; -#else - register ACE_UINT16 usrc = * reinterpret_cast (orig); - register ACE_UINT16* udst = reinterpret_cast (target); - *udst = (usrc << 8) | (usrc >> 8); -#endif /* ACE_HAS_PENTIUM */ -} - -ACE_INLINE void -ACE_CDR::swap_4 (const char* orig, char* target) -{ -#if defined (ACE_HAS_INTRINSIC_BYTESWAP) - // Take advantage of MSVC++ compiler intrinsic byte swapping - // function. - *reinterpret_cast (target) = - _byteswap_ulong (*reinterpret_cast (orig)); -#elif defined (ACE_HAS_BSWAP32) - *reinterpret_cast (target) = - bswap32 (*reinterpret_cast (orig)); -#elif defined (ACE_HAS_BSWAP_32) - *reinterpret_cast (target) = - bswap_32 (*reinterpret_cast (orig)); -#elif defined(ACE_HAS_INTEL_ASSEMBLY) - // We have ACE_HAS_PENTIUM, so we know the sizeof's. - register unsigned int j = - *reinterpret_cast (orig); - asm ("bswap %1" : "=r" (j) : "0" (j)); - *reinterpret_cast (target) = j; -#elif defined(ACE_HAS_PENTIUM) \ - && (defined(_MSC_VER) || defined(__BORLANDC__)) \ - && !defined(ACE_LACKS_INLINE_ASSEMBLY) - __asm mov ebx, orig; - __asm mov ecx, target; - __asm mov eax, [ebx]; - __asm bswap eax; - __asm mov [ecx], eax; -#else - register ACE_UINT32 x = * reinterpret_cast (orig); - x = (x << 24) | ((x & 0xff00) << 8) | ((x & 0xff0000) >> 8) | (x >> 24); - * reinterpret_cast (target) = x; -#endif /* ACE_HAS_INTRINSIC_BYTESWAP */ -} - -ACE_INLINE void -ACE_CDR::swap_8 (const char* orig, char* target) -{ -#if defined (ACE_HAS_INTRINSIC_BYTESWAP) - // Take advantage of MSVC++ compiler intrinsic byte swapping - // function. - *reinterpret_cast (target) = - _byteswap_uint64 (*reinterpret_cast (orig)); -#elif defined (ACE_HAS_BSWAP64) - *reinterpret_cast (target) = - bswap64 (*reinterpret_cast (orig)); -#elif defined (ACE_HAS_BSWAP_64) - *reinterpret_cast (target) = - bswap_64 (*reinterpret_cast (orig)); -#elif (defined (__amd64__) || defined (__x86_64__)) && defined(__GNUG__) - register unsigned long x = - * reinterpret_cast (orig); - asm ("bswapq %1" : "=r" (x) : "0" (x)); - *reinterpret_cast (target) = x; -#elif defined(ACE_HAS_PENTIUM) && defined(__GNUG__) - register unsigned int i = - *reinterpret_cast (orig); - register unsigned int j = - *reinterpret_cast (orig + 4); - asm ("bswap %1" : "=r" (i) : "0" (i)); - asm ("bswap %1" : "=r" (j) : "0" (j)); - *reinterpret_cast (target + 4) = i; - *reinterpret_cast (target) = j; -#elif defined(ACE_HAS_PENTIUM) \ - && (defined(_MSC_VER) || defined(__BORLANDC__)) \ - && !defined(ACE_LACKS_INLINE_ASSEMBLY) - __asm mov ecx, orig; - __asm mov edx, target; - __asm mov eax, [ecx]; - __asm mov ebx, 4[ecx]; - __asm bswap eax; - __asm bswap ebx; - __asm mov 4[edx], eax; - __asm mov [edx], ebx; -#elif ACE_SIZEOF_LONG == 8 - // 64 bit architecture. - register unsigned long x = - * reinterpret_cast (orig); - register unsigned long x84 = (x & 0x000000ff000000ffUL) << 24; - register unsigned long x73 = (x & 0x0000ff000000ff00UL) << 8; - register unsigned long x62 = (x & 0x00ff000000ff0000UL) >> 8; - register unsigned long x51 = (x & 0xff000000ff000000UL) >> 24; - x = (x84 | x73 | x62 | x51); - x = (x << 32) | (x >> 32); - *reinterpret_cast (target) = x; -#else - register ACE_UINT32 x = - * reinterpret_cast (orig); - register ACE_UINT32 y = - * reinterpret_cast (orig + 4); - x = (x << 24) | ((x & 0xff00) << 8) | ((x & 0xff0000) >> 8) | (x >> 24); - y = (y << 24) | ((y & 0xff00) << 8) | ((y & 0xff0000) >> 8) | (y >> 24); - * reinterpret_cast (target) = y; - * reinterpret_cast (target + 4) = x; -#endif /* ACE_HAS_INTRINSIC_BYTESWAP */ -} - -ACE_INLINE void -ACE_CDR::swap_16 (const char* orig, char* target) -{ - swap_8 (orig + 8, target); - swap_8 (orig, target + 8); -} - -ACE_INLINE size_t -ACE_CDR::first_size (size_t minsize) -{ - if (minsize == 0) - return ACE_CDR::DEFAULT_BUFSIZE; - - size_t newsize = ACE_CDR::DEFAULT_BUFSIZE; - while (newsize < minsize) - { - if (newsize < ACE_CDR::EXP_GROWTH_MAX) - { - // We grow exponentially at the beginning, this is fast and - // reduces the number of allocations. - - // Quickly multiply by two using a bit shift. This is - // guaranteed to work since the variable is an unsigned - // integer. - newsize <<= 1; - } - else - { - // but continuing with exponential growth can result in over - // allocations and easily yield an allocation failure. - // So we grow linearly when the buffer is too big. - newsize += ACE_CDR::LINEAR_GROWTH_CHUNK; - } - } - return newsize; -} - -ACE_INLINE size_t -ACE_CDR::next_size (size_t minsize) -{ - size_t newsize = ACE_CDR::first_size (minsize); - - if (newsize == minsize) - { - // If necessary increment the size - if (newsize < ACE_CDR::EXP_GROWTH_MAX) - // Quickly multiply by two using a bit shift. This is - // guaranteed to work since the variable is an unsigned - // integer. - newsize <<= 1; - else - newsize += ACE_CDR::LINEAR_GROWTH_CHUNK; - } - - return newsize; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -// **************************************************************** diff --git a/externals/ace/CDR_Size.cpp b/externals/ace/CDR_Size.cpp deleted file mode 100644 index 96970927037..00000000000 --- a/externals/ace/CDR_Size.cpp +++ /dev/null @@ -1,262 +0,0 @@ -#include "ace/CDR_Size.h" -#include "ace/SString.h" -#include "ace/OS_Memory.h" -#include "ace/Truncate.h" - -#if !defined (__ACE_INLINE__) -# include "ace/CDR_Size.inl" -#endif /* ! __ACE_INLINE__ */ - -ACE_RCSID (ace, - CDR_Size, - "$Id: CDR_Size.cpp 82559 2008-08-07 20:23:07Z parsons $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_CDR::Boolean -ACE_SizeCDR::write_wchar (ACE_CDR::WChar x) -{ - // Note: translator framework is not supported. - // - if (ACE_OutputCDR::wchar_maxbytes () == 0) - { - errno = EACCES; - return (this->good_bit_ = false); - } - - if (static_cast (major_version_) == 1 - && static_cast (minor_version_) == 2) - { - ACE_CDR::Octet len = - static_cast (ACE_OutputCDR::wchar_maxbytes ()); - - if (this->write_1 (&len)) - { - if (ACE_OutputCDR::wchar_maxbytes () == sizeof(ACE_CDR::WChar)) - { - return - this->write_octet_array ( - reinterpret_cast (&x), - static_cast (len)); - } - else - { - if (ACE_OutputCDR::wchar_maxbytes () == 2) - { - ACE_CDR::Short sx = static_cast (x); - return - this->write_octet_array ( - reinterpret_cast (&sx), - static_cast (len)); - } - else - { - ACE_CDR::Octet ox = static_cast (x); - return - this->write_octet_array ( - reinterpret_cast (&ox), - static_cast (len)); - } - } - } - } - else if (static_cast (minor_version_) == 0) - { // wchar is not allowed with GIOP 1.0. - errno = EINVAL; - return (this->good_bit_ = false); - } - - if (ACE_OutputCDR::wchar_maxbytes () == sizeof (ACE_CDR::WChar)) - { - const void *temp = &x; - return this->write_4 (reinterpret_cast (temp)); - } - else if (ACE_OutputCDR::wchar_maxbytes () == 2) - { - ACE_CDR::Short sx = static_cast (x); - return this->write_2 (reinterpret_cast (&sx)); - } - - ACE_CDR::Octet ox = static_cast (x); - return this->write_1 (reinterpret_cast (&ox)); -} - -ACE_CDR::Boolean -ACE_SizeCDR::write_string (ACE_CDR::ULong len, - const ACE_CDR::Char *x) -{ - // Note: translator framework is not supported. - // - if (len != 0) - { - if (this->write_ulong (len + 1)) - return this->write_char_array (x, len + 1); - } - else - { - // Be nice to programmers: treat nulls as empty strings not - // errors. (OMG-IDL supports languages that don't use the C/C++ - // notion of null v. empty strings; nulls aren't part of the OMG-IDL - // string model.) - if (this->write_ulong (1)) - return this->write_char (0); - } - - return (this->good_bit_ = false); -} - -ACE_CDR::Boolean -ACE_SizeCDR::write_string (const ACE_CString &x) -{ - // @@ Leave this method in here, not the `.i' file so that we don't - // have to unnecessarily pull in the `ace/SString.h' header. - return this->write_string (static_cast (x.length ()), - x.c_str()); -} - -ACE_CDR::Boolean -ACE_SizeCDR::write_wstring (ACE_CDR::ULong len, - const ACE_CDR::WChar *x) -{ - // Note: translator framework is not supported. - // - if (ACE_OutputCDR::wchar_maxbytes () == 0) - { - errno = EACCES; - return (this->good_bit_ = false); - } - - if (static_cast (this->major_version_) == 1 - && static_cast (this->minor_version_) == 2) - { - if (x != 0) - { - //In GIOP 1.2 the length field contains the number of bytes - //the wstring occupies rather than number of wchars - //Taking sizeof might not be a good way! This is a temporary fix. - ACE_CDR::Boolean good_ulong = - this->write_ulong ( - ACE_Utils::truncate_cast ( - ACE_OutputCDR::wchar_maxbytes () * len)); - - if (good_ulong) - { - return this->write_wchar_array (x, len); - } - } - else - { - //In GIOP 1.2 zero length wstrings are legal - return this->write_ulong (0); - } - } - - else - if (x != 0) - { - if (this->write_ulong (len + 1)) - return this->write_wchar_array (x, len + 1); - } - else if (this->write_ulong (1)) - return this->write_wchar (0); - return (this->good_bit_ = false); -} - -ACE_CDR::Boolean -ACE_SizeCDR::write_1 (const ACE_CDR::Octet *) -{ - this->adjust (1); - return true; -} - -ACE_CDR::Boolean -ACE_SizeCDR::write_2 (const ACE_CDR::UShort *) -{ - this->adjust (ACE_CDR::SHORT_SIZE); - return true; -} - -ACE_CDR::Boolean -ACE_SizeCDR::write_4 (const ACE_CDR::ULong *) -{ - this->adjust (ACE_CDR::LONG_SIZE); - return true; -} - -ACE_CDR::Boolean -ACE_SizeCDR::write_8 (const ACE_CDR::ULongLong *) -{ - this->adjust (ACE_CDR::LONGLONG_SIZE); - return true; -} - -ACE_CDR::Boolean -ACE_SizeCDR::write_16 (const ACE_CDR::LongDouble *) -{ - this->adjust (ACE_CDR::LONGDOUBLE_SIZE, - ACE_CDR::LONGDOUBLE_ALIGN); - return true; -} - -ACE_CDR::Boolean -ACE_SizeCDR::write_wchar_array_i (const ACE_CDR::WChar *, - ACE_CDR::ULong length) -{ - if (length == 0) - return true; - - size_t const align = (ACE_OutputCDR::wchar_maxbytes () == 2) ? - ACE_CDR::SHORT_ALIGN : - ACE_CDR::OCTET_ALIGN; - - this->adjust (ACE_OutputCDR::wchar_maxbytes () * length, align); - return true; -} - - -ACE_CDR::Boolean -ACE_SizeCDR::write_array (const void *, - size_t size, - size_t align, - ACE_CDR::ULong length) -{ - if (length == 0) - return true; - - this->adjust (size * length, align); - return true; -} - -ACE_CDR::Boolean -ACE_SizeCDR::write_boolean_array (const ACE_CDR::Boolean*, - ACE_CDR::ULong length) -{ - this->adjust (length, 1); - return true; -} - -void -ACE_SizeCDR::adjust (size_t size) -{ - adjust (size, size); -} - -void -ACE_SizeCDR::adjust (size_t size, - size_t align) -{ -#if !defined (ACE_LACKS_CDR_ALIGNMENT) - const size_t offset = ACE_align_binary (size_, align) - size_; - size_ += offset; -#endif /* ACE_LACKS_CDR_ALIGNMENT */ - size_ += size; -} - -ACE_CDR::Boolean -operator<< (ACE_SizeCDR &ss, const ACE_CString &x) -{ - ss.write_string (x); - return ss.good_bit (); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/CDR_Size.h b/externals/ace/CDR_Size.h deleted file mode 100644 index a0b3c462ca8..00000000000 --- a/externals/ace/CDR_Size.h +++ /dev/null @@ -1,241 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file CDR_Size.h - * - * $Id: CDR_Size.h 80826 2008-03-04 14:51:23Z wotte $ - * - * - * ACE Common Data Representation (CDR) size-calculating stream. - * - * - * The current implementation assumes that the host has 1-byte, - * 2-byte and 4-byte integral types, and that it has single - * precision and double precision IEEE floats. - * Those assumptions are pretty good these days, with Crays beign - * the only known exception. - * - * - * @author Boris Kolpackov - * - */ -//============================================================================= - -#ifndef ACE_CDR_SIZE_H -#define ACE_CDR_SIZE_H - -#include /**/ "ace/pre.h" - -#include "ace/CDR_Base.h" -#include "ace/CDR_Stream.h" // for ACE_OutputCDR::from_* - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/SStringfwd.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_SizeCDR - * - * @brief A CDR stream for calculating size of the representation. - * - */ -class ACE_Export ACE_SizeCDR -{ -public: - /// Default constructor. - ACE_SizeCDR (ACE_CDR::Octet major_version = ACE_CDR_GIOP_MAJOR_VERSION, - ACE_CDR::Octet minor_version = ACE_CDR_GIOP_MINOR_VERSION); - - /// Returns @c false if an error has ocurred. - bool good_bit (void) const; - - - /// Reset current size. - void reset (void); - - - /// Return current size. - size_t total_length (void) const; - - - // Return 0 on failure and 1 on success. - //@{ @name Size-calculating pseudo-write operations - ACE_CDR::Boolean write_boolean (ACE_CDR::Boolean x); - ACE_CDR::Boolean write_char (ACE_CDR::Char x); - ACE_CDR::Boolean write_wchar (ACE_CDR::WChar x); - ACE_CDR::Boolean write_octet (ACE_CDR::Octet x); - ACE_CDR::Boolean write_short (ACE_CDR::Short x); - ACE_CDR::Boolean write_ushort (ACE_CDR::UShort x); - ACE_CDR::Boolean write_long (ACE_CDR::Long x); - ACE_CDR::Boolean write_ulong (ACE_CDR::ULong x); - ACE_CDR::Boolean write_longlong (const ACE_CDR::LongLong &x); - ACE_CDR::Boolean write_ulonglong (const ACE_CDR::ULongLong &x); - ACE_CDR::Boolean write_float (ACE_CDR::Float x); - ACE_CDR::Boolean write_double (const ACE_CDR::Double &x); - ACE_CDR::Boolean write_longdouble (const ACE_CDR::LongDouble &x); - - /// For string we offer methods that accept a precomputed length. - ACE_CDR::Boolean write_string (const ACE_CDR::Char *x); - ACE_CDR::Boolean write_string (ACE_CDR::ULong len, - const ACE_CDR::Char *x); - ACE_CDR::Boolean write_string (const ACE_CString &x); - ACE_CDR::Boolean write_wstring (const ACE_CDR::WChar *x); - ACE_CDR::Boolean write_wstring (ACE_CDR::ULong length, - const ACE_CDR::WChar *x); - //@} - - /// @note the portion written starts at and ends - /// at . - /// The length is *NOT* stored into the CDR stream. - //@{ @name Array write operations - ACE_CDR::Boolean write_boolean_array (const ACE_CDR::Boolean *x, - ACE_CDR::ULong length); - ACE_CDR::Boolean write_char_array (const ACE_CDR::Char *x, - ACE_CDR::ULong length); - ACE_CDR::Boolean write_wchar_array (const ACE_CDR::WChar* x, - ACE_CDR::ULong length); - ACE_CDR::Boolean write_octet_array (const ACE_CDR::Octet* x, - ACE_CDR::ULong length); - ACE_CDR::Boolean write_short_array (const ACE_CDR::Short *x, - ACE_CDR::ULong length); - ACE_CDR::Boolean write_ushort_array (const ACE_CDR::UShort *x, - ACE_CDR::ULong length); - ACE_CDR::Boolean write_long_array (const ACE_CDR::Long *x, - ACE_CDR::ULong length); - ACE_CDR::Boolean write_ulong_array (const ACE_CDR::ULong *x, - ACE_CDR::ULong length); - ACE_CDR::Boolean write_longlong_array (const ACE_CDR::LongLong* x, - ACE_CDR::ULong length); - ACE_CDR::Boolean write_ulonglong_array (const ACE_CDR::ULongLong *x, - ACE_CDR::ULong length); - ACE_CDR::Boolean write_float_array (const ACE_CDR::Float *x, - ACE_CDR::ULong length); - ACE_CDR::Boolean write_double_array (const ACE_CDR::Double *x, - ACE_CDR::ULong length); - ACE_CDR::Boolean write_longdouble_array (const ACE_CDR::LongDouble* x, - ACE_CDR::ULong length); - - /// - /// Adjust to @a size and count octets. - void adjust (size_t size); - - /// As above, but now the size and alignment requirements may be - /// different. - void adjust (size_t size, - size_t align); - -private: - /// disallow copying... - ACE_SizeCDR (const ACE_SizeCDR& rhs); - ACE_SizeCDR& operator= (const ACE_SizeCDR& rhs); - - ACE_CDR::Boolean write_1 (const ACE_CDR::Octet *x); - ACE_CDR::Boolean write_2 (const ACE_CDR::UShort *x); - ACE_CDR::Boolean write_4 (const ACE_CDR::ULong *x); - ACE_CDR::Boolean write_8 (const ACE_CDR::ULongLong *x); - ACE_CDR::Boolean write_16 (const ACE_CDR::LongDouble *x); - - /** - * write an array of @a length elements, each of @a size bytes and the - * start aligned at a multiple of . The elements are assumed - * to be packed with the right alignment restrictions. It is mostly - * designed for buffers of the basic types. - * - * This operation uses ; as explained above it is expected - * that using assignment is faster that for one element, - * but for several elements should be more efficient, it - * could be interesting to find the break even point and optimize - * for that case, but that would be too platform dependent. - */ - ACE_CDR::Boolean write_array (const void *x, - size_t size, - size_t align, - ACE_CDR::ULong length); - - - ACE_CDR::Boolean write_wchar_array_i (const ACE_CDR::WChar* x, - ACE_CDR::ULong length); - -private: - /// Set to false when an error ocurrs. - bool good_bit_; - - /// Current size. - size_t size_; - -protected: - /// GIOP version information - ACE_CDR::Octet major_version_; - ACE_CDR::Octet minor_version_; -}; - -// @@ This operator should not be inlined since they force SString.h -// to be included in this header. -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, - const ACE_CString &x); - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -# include "ace/CDR_Size.inl" -#else /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Not used by CORBA or TAO -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, - ACE_CDR::Char x); - -// CDR size-calculating output operators for primitive types - -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, - ACE_CDR::Short x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, - ACE_CDR::UShort x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, - ACE_CDR::Long x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, - ACE_CDR::ULong x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, - ACE_CDR::LongLong x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, - ACE_CDR::ULongLong x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR& ss, - ACE_CDR::LongDouble x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, - ACE_CDR::Float x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, - ACE_CDR::Double x); - -// CDR size-calculating output operator from helper classes - -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, - ACE_OutputCDR::from_boolean x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, - ACE_OutputCDR::from_char x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, - ACE_OutputCDR::from_wchar x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, - ACE_OutputCDR::from_octet x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, - ACE_OutputCDR::from_string x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, - ACE_OutputCDR::from_wstring x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, - const ACE_CDR::Char* x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_SizeCDR &ss, - const ACE_CDR::WChar* x); - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* __ACE_INLINE__ */ - - -#include /**/ "ace/post.h" - -#endif /* ACE_CDR_SIZE_H */ diff --git a/externals/ace/CDR_Size.inl b/externals/ace/CDR_Size.inl deleted file mode 100644 index 4ea81523faf..00000000000 --- a/externals/ace/CDR_Size.inl +++ /dev/null @@ -1,424 +0,0 @@ -// -*- C++ -*- -// -// $Id: CDR_Size.inl 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/OS_NS_string.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE -ACE_SizeCDR::ACE_SizeCDR (ACE_CDR::Octet major_version, - ACE_CDR::Octet minor_version) - : good_bit_ (true), - size_ (0), - major_version_ (major_version), - minor_version_ (minor_version) -{ -} - -ACE_INLINE bool -ACE_SizeCDR::good_bit (void) const -{ - return this->good_bit_; -} - -ACE_INLINE void -ACE_SizeCDR::reset (void) -{ - this->size_ = 0; -} - -ACE_INLINE size_t -ACE_SizeCDR::total_length (void) const -{ - return this->size_; -} - - -// Encode the CDR stream. - -ACE_INLINE ACE_CDR::Boolean -ACE_SizeCDR::write_octet (ACE_CDR::Octet x) -{ - return this->write_1 (reinterpret_cast (&x)); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_SizeCDR::write_boolean (ACE_CDR::Boolean x) -{ - return (ACE_CDR::Boolean) this->write_octet (x ? (ACE_CDR::Octet) 1 : (ACE_CDR::Octet) 0); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_SizeCDR::write_char (ACE_CDR::Char x) -{ - // Note: translator framework is not supported. - // - return this->write_1 (reinterpret_cast (&x)); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_SizeCDR::write_short (ACE_CDR::Short x) -{ - return this->write_2 (reinterpret_cast (&x)); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_SizeCDR::write_ushort (ACE_CDR::UShort x) -{ - return this->write_2 (reinterpret_cast (&x)); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_SizeCDR::write_long (ACE_CDR::Long x) -{ - return this->write_4 (reinterpret_cast (&x)); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_SizeCDR::write_ulong (ACE_CDR::ULong x) -{ - return this->write_4 (reinterpret_cast (&x)); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_SizeCDR::write_longlong (const ACE_CDR::LongLong &x) -{ - return this->write_8 (reinterpret_cast (&x)); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_SizeCDR::write_ulonglong (const ACE_CDR::ULongLong &x) -{ - const void *temp = &x; - return this->write_8 (reinterpret_cast (temp)); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_SizeCDR::write_float (ACE_CDR::Float x) -{ - const void *temp = &x; - return this->write_4 (reinterpret_cast (temp)); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_SizeCDR::write_double (const ACE_CDR::Double &x) -{ - const void *temp = &x; - return this->write_8 (reinterpret_cast (temp)); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_SizeCDR::write_longdouble (const ACE_CDR::LongDouble &x) -{ - const void *temp = &x; - return this->write_16 (reinterpret_cast (temp)); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_SizeCDR::write_string (const ACE_CDR::Char *x) -{ - if (x != 0) - { - const ACE_CDR::ULong len = - static_cast (ACE_OS::strlen (x)); - return this->write_string (len, x); - } - return this->write_string (0, 0); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_SizeCDR::write_wstring (const ACE_CDR::WChar *x) -{ - if (x != 0) - { - ACE_CDR::ULong len = - static_cast (ACE_OS::strlen (x)); - return this->write_wstring (len, x); - } - return this->write_wstring (0, 0); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_SizeCDR::write_char_array (const ACE_CDR::Char *x, - ACE_CDR::ULong length) -{ - // Note: translator framework is not supported. - // - return this->write_array (x, - ACE_CDR::OCTET_SIZE, - ACE_CDR::OCTET_ALIGN, - length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_SizeCDR::write_wchar_array (const ACE_CDR::WChar* x, - ACE_CDR::ULong length) -{ - // Note: translator framework is not supported. - // - if (ACE_OutputCDR::wchar_maxbytes () == 0) - { - errno = EACCES; - return (ACE_CDR::Boolean) (this->good_bit_ = false); - } - if (ACE_OutputCDR::wchar_maxbytes () == sizeof (ACE_CDR::WChar)) - return this->write_array (x, - sizeof (ACE_CDR::WChar), - sizeof (ACE_CDR::WChar) == 2 - ? ACE_CDR::SHORT_ALIGN - : ACE_CDR::LONG_ALIGN, - length); - return this->write_wchar_array_i (x,length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_SizeCDR::write_octet_array (const ACE_CDR::Octet* x, - ACE_CDR::ULong length) -{ - return this->write_array (x, - ACE_CDR::OCTET_SIZE, - ACE_CDR::OCTET_ALIGN, - length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_SizeCDR::write_short_array (const ACE_CDR::Short *x, - ACE_CDR::ULong length) -{ - return this->write_array (x, - ACE_CDR::SHORT_SIZE, - ACE_CDR::SHORT_ALIGN, - length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_SizeCDR::write_ushort_array (const ACE_CDR::UShort *x, - ACE_CDR::ULong length) -{ - return this->write_array (x, - ACE_CDR::SHORT_SIZE, - ACE_CDR::SHORT_ALIGN, - length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_SizeCDR::write_long_array (const ACE_CDR::Long *x, - ACE_CDR::ULong length) -{ - return this->write_array (x, - ACE_CDR::LONG_SIZE, - ACE_CDR::LONG_ALIGN, - length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_SizeCDR::write_ulong_array (const ACE_CDR::ULong *x, - ACE_CDR::ULong length) -{ - return this->write_array (x, - ACE_CDR::LONG_SIZE, - ACE_CDR::LONG_ALIGN, - length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_SizeCDR::write_longlong_array (const ACE_CDR::LongLong *x, - ACE_CDR::ULong length) -{ - return this->write_array (x, - ACE_CDR::LONGLONG_SIZE, - ACE_CDR::LONGLONG_ALIGN, - length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_SizeCDR::write_ulonglong_array (const ACE_CDR::ULongLong *x, - ACE_CDR::ULong length) -{ - return this->write_array (x, - ACE_CDR::LONGLONG_SIZE, - ACE_CDR::LONGLONG_ALIGN, - length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_SizeCDR::write_float_array (const ACE_CDR::Float *x, - ACE_CDR::ULong length) -{ - return this->write_array (x, - ACE_CDR::LONG_SIZE, - ACE_CDR::LONG_ALIGN, - length); -} - - -ACE_INLINE ACE_CDR::Boolean -ACE_SizeCDR::write_double_array (const ACE_CDR::Double *x, - ACE_CDR::ULong length) -{ - return this->write_array (x, - ACE_CDR::LONGLONG_SIZE, - ACE_CDR::LONGLONG_ALIGN, - length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_SizeCDR::write_longdouble_array (const ACE_CDR::LongDouble* x, - ACE_CDR::ULong length) -{ - return this->write_array (x, - ACE_CDR::LONGDOUBLE_SIZE, - ACE_CDR::LONGDOUBLE_ALIGN, - length); -} - - -// **************************************************************** - - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_SizeCDR &ss, ACE_CDR::Char x) -{ - ss.write_char (x); - return (ACE_CDR::Boolean) ss.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_SizeCDR &ss, ACE_CDR::Short x) -{ - ss.write_short (x); - return (ACE_CDR::Boolean) ss.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_SizeCDR &ss, ACE_CDR::UShort x) -{ - ss.write_ushort (x); - return (ACE_CDR::Boolean) ss.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_SizeCDR &ss, ACE_CDR::Long x) -{ - ss.write_long (x); - return (ACE_CDR::Boolean) ss.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_SizeCDR &ss, ACE_CDR::ULong x) -{ - ss.write_ulong (x); - return (ACE_CDR::Boolean) ss.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_SizeCDR &ss, ACE_CDR::LongLong x) -{ - ss.write_longlong (x); - return (ACE_CDR::Boolean) ss.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_SizeCDR &ss, ACE_CDR::ULongLong x) -{ - ss.write_ulonglong (x); - return (ACE_CDR::Boolean) ss.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_SizeCDR &ss, ACE_CDR::LongDouble x) -{ - ss.write_longdouble (x); - return (ACE_CDR::Boolean) ss.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_SizeCDR &ss, ACE_CDR::Float x) -{ - ss.write_float (x); - return (ACE_CDR::Boolean) ss.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_SizeCDR &ss, ACE_CDR::Double x) -{ - ss.write_double (x); - return (ACE_CDR::Boolean) ss.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_SizeCDR &ss, const ACE_CDR::Char *x) -{ - ss.write_string (x); - return (ACE_CDR::Boolean) ss.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_SizeCDR &ss, const ACE_CDR::WChar *x) -{ - ss.write_wstring (x); - return (ACE_CDR::Boolean) ss.good_bit (); -} - -// The following use the helper classes -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_SizeCDR &ss, ACE_OutputCDR::from_boolean x) -{ - ss.write_boolean (x.val_); - return (ACE_CDR::Boolean) ss.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_SizeCDR &ss, ACE_OutputCDR::from_char x) -{ - ss.write_char (x.val_); - return (ACE_CDR::Boolean) ss.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_SizeCDR &ss, ACE_OutputCDR::from_wchar x) -{ - ss.write_wchar (x.val_); - return (ACE_CDR::Boolean) ss.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_SizeCDR &ss, ACE_OutputCDR::from_octet x) -{ - ss.write_octet (x.val_); - return (ACE_CDR::Boolean) ss.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_SizeCDR &ss, ACE_OutputCDR::from_string x) -{ - ACE_CDR::ULong len = 0; - - if (x.val_ != 0) - { - len = static_cast (ACE_OS::strlen (x.val_)); - } - - ss.write_string (len, x.val_); - return - (ACE_CDR::Boolean) (ss.good_bit () && (!x.bound_ || len <= x.bound_)); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_SizeCDR &ss, ACE_OutputCDR::from_wstring x) -{ - ACE_CDR::ULong len = 0; - - if (x.val_ != 0) - { - len = static_cast (ACE_OS::strlen (x.val_)); - } - - ss.write_wstring (len, x.val_); - return - (ACE_CDR::Boolean) (ss.good_bit () && (!x.bound_ || len <= x.bound_)); -} - - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/CDR_Stream.cpp b/externals/ace/CDR_Stream.cpp deleted file mode 100644 index 74d33be5876..00000000000 --- a/externals/ace/CDR_Stream.cpp +++ /dev/null @@ -1,2063 +0,0 @@ -#include "ace/CDR_Stream.h" -#include "ace/SString.h" -#include "ace/Auto_Ptr.h" -#include "ace/Truncate.h" - -#if !defined (__ACE_INLINE__) -# include "ace/CDR_Stream.inl" -#endif /* ! __ACE_INLINE__ */ - -ACE_RCSID (ace, - CDR_Stream, - "$Id: CDR_Stream.cpp 88653 2010-01-21 23:19:50Z sowayaa $") - -// **************************************************************** - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -size_t ACE_OutputCDR::wchar_maxbytes_ = sizeof (ACE_CDR::WChar); - -ACE_OutputCDR::ACE_OutputCDR (size_t size, - int byte_order, - ACE_Allocator *buffer_allocator, - ACE_Allocator *data_block_allocator, - ACE_Allocator *message_block_allocator, - size_t memcpy_tradeoff, - ACE_CDR::Octet major_version, - ACE_CDR::Octet minor_version) - : start_ ((size ? size : (size_t) ACE_CDR::DEFAULT_BUFSIZE) + ACE_CDR::MAX_ALIGNMENT, - ACE_Message_Block::MB_DATA, - 0, - 0, - buffer_allocator, - 0, - 0, - ACE_Time_Value::zero, - ACE_Time_Value::max_time, - data_block_allocator, - message_block_allocator), -#if !defined (ACE_LACKS_CDR_ALIGNMENT) - current_alignment_ (0), -#endif /* ACE_LACKS_CDR_ALIGNMENT */ - current_is_writable_ (true), - do_byte_swap_ (byte_order != ACE_CDR_BYTE_ORDER), - good_bit_ (true), - memcpy_tradeoff_ (memcpy_tradeoff), - major_version_ (major_version), - minor_version_ (minor_version), - char_translator_ (0), - wchar_translator_ (0) - -{ - ACE_CDR::mb_align (&this->start_); - this->current_ = &this->start_; - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - ACE_NEW (this->monitor_, - ACE::Monitor_Control::Size_Monitor); - this->monitor_->receive (this->total_length ()); -#endif /* ACE_HAS_MONITOR_POINTS==1 */ -} - -ACE_OutputCDR::ACE_OutputCDR (char *data, - size_t size, - int byte_order, - ACE_Allocator *buffer_allocator, - ACE_Allocator *data_block_allocator, - ACE_Allocator *message_block_allocator, - size_t memcpy_tradeoff, - ACE_CDR::Octet major_version, - ACE_CDR::Octet minor_version) - : start_ (size, - ACE_Message_Block::MB_DATA, - 0, - data, - buffer_allocator, - 0, - 0, - ACE_Time_Value::zero, - ACE_Time_Value::max_time, - data_block_allocator, - message_block_allocator), -#if !defined (ACE_LACKS_CDR_ALIGNMENT) - current_alignment_ (0), -#endif /* ACE_LACKS_CDR_ALIGNMENT */ - current_is_writable_ (true), - do_byte_swap_ (byte_order != ACE_CDR_BYTE_ORDER), - good_bit_ (true), - memcpy_tradeoff_ (memcpy_tradeoff), - major_version_ (major_version), - minor_version_ (minor_version), - char_translator_ (0), - wchar_translator_ (0) -{ - // We cannot trust the buffer to be properly aligned - ACE_CDR::mb_align (&this->start_); - this->current_ = &this->start_; - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - ACE_NEW (this->monitor_, - ACE::Monitor_Control::Size_Monitor); - this->monitor_->receive (this->total_length ()); -#endif /* ACE_HAS_MONITOR_POINTS==1 */ -} - -ACE_OutputCDR::ACE_OutputCDR (ACE_Data_Block *data_block, - int byte_order, - ACE_Allocator *message_block_allocator, - size_t memcpy_tradeoff, - ACE_CDR::Octet major_version, - ACE_CDR::Octet minor_version) - : start_ (data_block, - ACE_Message_Block::DONT_DELETE, - message_block_allocator), -#if !defined (ACE_LACKS_CDR_ALIGNMENT) - current_alignment_ (0), -#endif /* ACE_LACKS_CDR_ALIGNMENT */ - current_is_writable_ (true), - do_byte_swap_ (byte_order != ACE_CDR_BYTE_ORDER), - good_bit_ (true), - memcpy_tradeoff_ (memcpy_tradeoff), - major_version_ (major_version), - minor_version_ (minor_version), - char_translator_ (0), - wchar_translator_ (0) -{ - // We cannot trust the buffer to be properly aligned - ACE_CDR::mb_align (&this->start_); - this->current_ = &this->start_; - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - ACE_NEW (this->monitor_, - ACE::Monitor_Control::Size_Monitor); - this->monitor_->receive (this->total_length ()); -#endif /* ACE_HAS_MONITOR_POINTS==1 */ -} - -ACE_OutputCDR::ACE_OutputCDR (ACE_Message_Block *data, - int byte_order, - size_t memcpy_tradeoff, - ACE_CDR::Octet major_version, - ACE_CDR::Octet minor_version) - : start_ (data->data_block ()->duplicate ()), -#if !defined (ACE_LACKS_CDR_ALIGNMENT) - current_alignment_ (0), -#endif /* ACE_LACKS_CDR_ALIGNMENT */ - current_is_writable_ (true), - do_byte_swap_ (byte_order != ACE_CDR_BYTE_ORDER), - good_bit_ (true), - memcpy_tradeoff_ (memcpy_tradeoff), - major_version_ (major_version), - minor_version_ (minor_version), - char_translator_ (0), - wchar_translator_ (0) -{ - // We cannot trust the buffer to be properly aligned - ACE_CDR::mb_align (&this->start_); - this->current_ = &this->start_; - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - ACE_NEW (this->monitor_, - ACE::Monitor_Control::Size_Monitor); - this->monitor_->receive (this->total_length ()); -#endif /* ACE_HAS_MONITOR_POINTS==1 */ -} - -/*static*/ void -ACE_OutputCDR::wchar_maxbytes (size_t maxbytes) -{ - ACE_OutputCDR::wchar_maxbytes_ = maxbytes; -} - -/*static*/ size_t -ACE_OutputCDR::wchar_maxbytes () -{ - return ACE_OutputCDR::wchar_maxbytes_; -} - -int -ACE_OutputCDR::grow_and_adjust (size_t size, - size_t align, - char*& buf) -{ - if (!this->current_is_writable_ - || this->current_->cont () == 0 - || this->current_->cont ()->size () < size + ACE_CDR::MAX_ALIGNMENT) - { - // Calculate the new buffer's length; if growing for encode, we - // don't grow in "small" chunks because of the cost. - size_t cursize = this->current_->size (); - if (this->current_->cont () != 0) - cursize = this->current_->cont ()->size (); - size_t minsize = size; - -#if !defined (ACE_LACKS_CDR_ALIGNMENT) - minsize += ACE_CDR::MAX_ALIGNMENT; -#endif /* ACE_LACKS_CDR_ALIGNMENT */ - - // Make sure that there is enough room for bytes, but - // also make it bigger than whatever our current size is. - if (minsize < cursize) - minsize = cursize; - - size_t const newsize = ACE_CDR::next_size (minsize); - - this->good_bit_ = false; - ACE_Message_Block* tmp = 0; - ACE_NEW_RETURN (tmp, - ACE_Message_Block (newsize, - ACE_Message_Block::MB_DATA, - 0, - 0, - this->current_->data_block ()->allocator_strategy (), - 0, - 0, - ACE_Time_Value::zero, - ACE_Time_Value::max_time, - this->current_->data_block ()->data_block_allocator ()), - -1); - - // Message block initialization may fail while the construction - // succeds. Since as a matter of policy, ACE may throw no - // exceptions, we have to do a separate check like this. - if (tmp != 0 && tmp->size () < newsize) - { - delete tmp; - errno = ENOMEM; - return -1; - } - - this->good_bit_ = true; - -#if !defined (ACE_LACKS_CDR_ALIGNMENT) - // The new block must start with the same alignment as the - // previous block finished. - ptrdiff_t const tmpalign = - reinterpret_cast (tmp->rd_ptr ()) % ACE_CDR::MAX_ALIGNMENT; - ptrdiff_t const curalign = - static_cast (this->current_alignment_) % ACE_CDR::MAX_ALIGNMENT; - ptrdiff_t offset = curalign - tmpalign; - if (offset < 0) - offset += ACE_CDR::MAX_ALIGNMENT; - tmp->rd_ptr (static_cast (offset)); - tmp->wr_ptr (tmp->rd_ptr ()); -#endif /* ACE_LACKS_CDR_ALIGNMENT */ - - // grow the chain and set the current block. - tmp->cont (this->current_->cont ()); - this->current_->cont (tmp); - } - this->current_ = this->current_->cont (); - this->current_is_writable_ = true; - - return this->adjust (size, align, buf); -} - -ACE_CDR::Boolean -ACE_OutputCDR::write_wchar (ACE_CDR::WChar x) -{ - if (this->wchar_translator_ != 0) - return (this->good_bit_ = this->wchar_translator_->write_wchar (*this, x)); - if (ACE_OutputCDR::wchar_maxbytes_ == 0) - { - errno = EACCES; - return (this->good_bit_ = false); - } - if (static_cast (major_version_) == 1 - && static_cast (minor_version_) == 2) - { - ACE_CDR::Octet len = - static_cast (ACE_OutputCDR::wchar_maxbytes_); - if (this->write_1 (&len)) - { - if (ACE_OutputCDR::wchar_maxbytes_ == sizeof(ACE_CDR::WChar)) - return - this->write_octet_array ( - reinterpret_cast (&x), - static_cast (len)); - else - if (ACE_OutputCDR::wchar_maxbytes_ == 2) - { - ACE_CDR::Short sx = static_cast (x); - return - this->write_octet_array ( - reinterpret_cast (&sx), - static_cast (len)); - } - else - { - ACE_CDR::Octet ox = static_cast (x); - return - this->write_octet_array ( - reinterpret_cast (&ox), - static_cast (len)); - } - } - } - else if (static_cast (minor_version_) == 0) - { // wchar is not allowed with GIOP 1.0. - errno = EINVAL; - return (this->good_bit_ = false); - } - if (ACE_OutputCDR::wchar_maxbytes_ == sizeof (ACE_CDR::WChar)) - { - void const * const temp = &x; - return - this->write_4 (reinterpret_cast (temp)); - } - else if (ACE_OutputCDR::wchar_maxbytes_ == 2) - { - ACE_CDR::Short sx = static_cast (x); - return this->write_2 (reinterpret_cast (&sx)); - } - ACE_CDR::Octet ox = static_cast (x); - return this->write_1 (reinterpret_cast (&ox)); -} - -ACE_CDR::Boolean -ACE_OutputCDR::write_string (ACE_CDR::ULong len, - const ACE_CDR::Char *x) -{ - // @@ This is a slight violation of "Optimize for the common case", - // i.e. normally the translator will be 0, but OTOH the code is - // smaller and should be better for the cache ;-) ;-) - if (this->char_translator_ != 0) - return this->char_translator_->write_string (*this, len, x); - - if (len != 0) - { - if (this->write_ulong (len + 1)) - return this->write_char_array (x, len + 1); - } - else - { - // Be nice to programmers: treat nulls as empty strings not - // errors. (OMG-IDL supports languages that don't use the C/C++ - // notion of null v. empty strings; nulls aren't part of the OMG-IDL - // string model.) - if (this->write_ulong (1)) - return this->write_char (0); - } - - return (this->good_bit_ = false); -} - -ACE_CDR::Boolean -ACE_OutputCDR::write_string (const ACE_CString &x) -{ - // @@ Leave this method in here, not the `.i' file so that we don't - // have to unnecessarily pull in the `ace/SString.h' header. - return this->write_string (static_cast (x.length ()), - x.c_str()); -} - -ACE_CDR::Boolean -ACE_OutputCDR::write_wstring (ACE_CDR::ULong len, - const ACE_CDR::WChar *x) -{ - // @@ This is a slight violation of "Optimize for the common case", - // i.e. normally the translator will be 0, but OTOH the code is - // smaller and should be better for the cache ;-) ;-) - // What do we do for GIOP 1.2??? - if (this->wchar_translator_ != 0) - return this->wchar_translator_->write_wstring (*this, len, x); - if (ACE_OutputCDR::wchar_maxbytes_ == 0) - { - errno = EACCES; - return (this->good_bit_ = false); - } - - if (static_cast (this->major_version_) == 1 - && static_cast (this->minor_version_) == 2) - { - if (x != 0) - { - //In GIOP 1.2 the length field contains the number of bytes - //the wstring occupies rather than number of wchars - //Taking sizeof might not be a good way! This is a temporary fix. - ACE_CDR::Boolean good_ulong = - this->write_ulong ( - ACE_Utils::truncate_cast ( - ACE_OutputCDR::wchar_maxbytes_ * len)); - - if (good_ulong) - { - return this->write_wchar_array (x, len); - } - } - else - { - //In GIOP 1.2 zero length wstrings are legal - return this->write_ulong (0); - } - } - - else - if (x != 0) - { - if (this->write_ulong (len + 1)) - return this->write_wchar_array (x, len + 1); - } - else if (this->write_ulong (1)) - return this->write_wchar (0); - return (this->good_bit_ = false); -} - -ACE_CDR::Boolean -ACE_OutputCDR::write_octet_array_mb (const ACE_Message_Block* mb) -{ - // If the buffer is small and it fits in the current message - // block it is be cheaper just to copy the buffer. - for (const ACE_Message_Block* i = mb; - i != 0; - i = i->cont ()) - { - size_t const length = i->length (); - - // If the mb does not own its data we are forced to make a copy. - if (ACE_BIT_ENABLED (i->flags (), - ACE_Message_Block::DONT_DELETE)) - { - if (! this->write_array (i->rd_ptr (), - ACE_CDR::OCTET_SIZE, - ACE_CDR::OCTET_ALIGN, - static_cast (length))) - return (this->good_bit_ = false); - continue; - } - - if (length < this->memcpy_tradeoff_ - && this->current_->wr_ptr () + length < this->current_->end ()) - { - if (! this->write_array (i->rd_ptr (), - ACE_CDR::OCTET_SIZE, - ACE_CDR::OCTET_ALIGN, - static_cast (length))) - return (this->good_bit_ = false); - continue; - } - - ACE_Message_Block* cont = 0; - this->good_bit_ = false; - ACE_NEW_RETURN (cont, - ACE_Message_Block (i->data_block ()->duplicate ()), - false); - this->good_bit_ = true; - - if (this->current_->cont () != 0) - ACE_Message_Block::release (this->current_->cont ()); - cont->rd_ptr (i->rd_ptr ()); - cont->wr_ptr (i->wr_ptr ()); - - this->current_->cont (cont); - this->current_ = cont; - this->current_is_writable_ = false; -#if !defined (ACE_LACKS_CDR_ALIGNMENT) - this->current_alignment_ = - (this->current_alignment_ + cont->length ()) % ACE_CDR::MAX_ALIGNMENT; -#endif /* ACE_LACKS_CDR_ALIGNMENT */ - } - - return true; -} - -ACE_CDR::Boolean -ACE_OutputCDR::write_1 (const ACE_CDR::Octet *x) -{ - char *buf = 0; - if (this->adjust (1, buf) == 0) - { - *reinterpret_cast (buf) = *x; - return true; - } - - return false; -} - -ACE_CDR::Boolean -ACE_OutputCDR::write_2 (const ACE_CDR::UShort *x) -{ - char *buf = 0; - if (this->adjust (ACE_CDR::SHORT_SIZE, buf) == 0) - { -#if !defined (ACE_ENABLE_SWAP_ON_WRITE) - *reinterpret_cast (buf) = *x; - return true; -#else - if (!this->do_byte_swap_) - { - *reinterpret_cast (buf) = *x; - return true; - } - else - { - ACE_CDR::swap_2 (reinterpret_cast (x), buf); - return true; - } -#endif /* ACE_ENABLE_SWAP_ON_WRITE */ - } - - return false; -} - -ACE_CDR::Boolean -ACE_OutputCDR::write_4 (const ACE_CDR::ULong *x) -{ - char *buf = 0; - if (this->adjust (ACE_CDR::LONG_SIZE, buf) == 0) - { -#if !defined (ACE_ENABLE_SWAP_ON_WRITE) - *reinterpret_cast (buf) = *x; - return true; -#else - if (!this->do_byte_swap_) - { - *reinterpret_cast (buf) = *x; - return true; - } - else - { - ACE_CDR::swap_4 (reinterpret_cast (x), buf); - return true; - } -#endif /* ACE_ENABLE_SWAP_ON_WRITE */ - } - - return false; -} - -ACE_CDR::Boolean -ACE_OutputCDR::write_8 (const ACE_CDR::ULongLong *x) -{ - char *buf = 0; - - if (this->adjust (ACE_CDR::LONGLONG_SIZE, buf) == 0) - { -#if defined (__arm__) && !defined (ACE_HAS_IPHONE) - // Convert to Intel format (12345678 => 56781234) - const char *orig = reinterpret_cast (x); - char *target = buf; - register ACE_UINT32 x = - *reinterpret_cast (orig); - register ACE_UINT32 y = - *reinterpret_cast (orig + 4); - *reinterpret_cast (target) = y; - *reinterpret_cast (target + 4) = x; - return true; -#else -# if !defined (ACE_ENABLE_SWAP_ON_WRITE) - *reinterpret_cast (buf) = *x; - return true; -# else - if (!this->do_byte_swap_) - { - *reinterpret_cast (buf) = *x; - return true; - } - else - { - ACE_CDR::swap_8 (reinterpret_cast (x), buf); - return true; - } -# endif /* ACE_ENABLE_SWAP_ON_WRITE */ -#endif /* !__arm__ */ - } - - return false; -} - -ACE_CDR::Boolean -ACE_OutputCDR::write_16 (const ACE_CDR::LongDouble *x) -{ - char* buf = 0; - if (this->adjust (ACE_CDR::LONGDOUBLE_SIZE, - ACE_CDR::LONGDOUBLE_ALIGN, - buf) == 0) - { -#if !defined (ACE_ENABLE_SWAP_ON_WRITE) - *reinterpret_cast (buf) = *x; - return 1; -#else - if (!this->do_byte_swap_) - { - *reinterpret_cast (buf) = *x; - return true; - } - else - { - ACE_CDR::swap_16 (reinterpret_cast (x), buf); - return true; - } -#endif /* ACE_ENABLE_SWAP_ON_WRITE */ - } - - return false; -} - -ACE_CDR::Boolean -ACE_OutputCDR::write_wchar_array_i (const ACE_CDR::WChar *x, - ACE_CDR::ULong length) -{ - if (length == 0) - return true; - char* buf = 0; - size_t const align = (ACE_OutputCDR::wchar_maxbytes_ == 2) ? - ACE_CDR::SHORT_ALIGN : - ACE_CDR::OCTET_ALIGN; - - if (this->adjust (ACE_OutputCDR::wchar_maxbytes_ * length, align, buf) == 0) - { - if (ACE_OutputCDR::wchar_maxbytes_ == 2) - { - ACE_CDR::UShort *sb = reinterpret_cast (buf); - for (size_t i = 0; i < length; ++i) -#if !defined (ACE_ENABLE_SWAP_ON_WRITE) - sb[i] = static_cast (x[i]); -#else - if (!this->do_byte_swap_) - sb[i] = static_cast (x[i]); - else - { - ACE_CDR::UShort sx = static_cast (x[i]); - ACE_CDR::swap_2 (reinterpret_cast (&sx), &buf[i * 2]); - } -#endif /* ACE_ENABLE_SWAP_ON_WRITE */ - } - else - { - for (size_t i = 0; i < length; ++i) - buf[i] = static_cast (x[i]); - } - return this->good_bit_; - } - return false; -} - - -ACE_CDR::Boolean -ACE_OutputCDR::write_array (const void *x, - size_t size, - size_t align, - ACE_CDR::ULong length) -{ - if (length == 0) - return true; - char *buf = 0; - if (this->adjust (size * length, align, buf) == 0) - { -#if !defined (ACE_ENABLE_SWAP_ON_WRITE) - ACE_OS::memcpy (buf, x, size*length); - return true; -#else - if (!this->do_byte_swap_ || size == 1) - { - ACE_OS::memcpy (buf, x, size*length); - return true; - } - else - { - const char *source = reinterpret_cast (x); - switch (size) - { - case 2: - ACE_CDR::swap_2_array (source, buf, length); - return true; - case 4: - ACE_CDR::swap_4_array (source, buf, length); - return true; - case 8: - ACE_CDR::swap_8_array (source, buf, length); - return true; - case 16: - ACE_CDR::swap_16_array (source, buf, length); - return true; - default: - // TODO: print something? - this->good_bit_ = false; - return false; - } - } -#endif /* ACE_ENABLE_SWAP_ON_WRITE */ - } - this->good_bit_ = false; - return false; -} - - -ACE_CDR::Boolean -ACE_OutputCDR::write_boolean_array (const ACE_CDR::Boolean* x, - ACE_CDR::ULong length) -{ - // It is hard to optimize this, the spec requires that on the wire - // booleans be represented as a byte with value 0 or 1, but in - // memory it is possible (though very unlikely) that a boolean has - // a non-zero value (different from 1). - // We resort to a simple loop. - ACE_CDR::Boolean const * const end = x + length; - - for (ACE_CDR::Boolean const * i = x; - i != end && this->good_bit (); - ++i) - (void) this->write_boolean (*i); - - return this->good_bit (); -} - -char * -ACE_OutputCDR::write_long_placeholder (void) -{ - char *buf = 0; - if (this->adjust (ACE_CDR::LONG_SIZE, buf) == 0) - *reinterpret_cast (buf) = 0; - else - buf = 0; - return buf; -} - -char * -ACE_OutputCDR::write_short_placeholder (void) -{ - char *buf = 0; - if (this->adjust (ACE_CDR::SHORT_SIZE, buf) == 0) - *reinterpret_cast (buf) = 0; - else - buf = 0; - return buf; -} - -ACE_CDR::Boolean -ACE_OutputCDR::replace (ACE_CDR::Long x, char* loc) -{ - if (this->find (loc) == 0) - return false; - -#if !defined (ACE_ENABLE_SWAP_ON_WRITE) - *reinterpret_cast (loc) = x; -#else - if (!this->do_byte_swap_) - { - *reinterpret_cast (loc) = x; - } - else - { - ACE_CDR::swap_4 (reinterpret_cast (&x), loc); - } -#endif /* ACE_ENABLE_SWAP_ON_WRITE */ - - return true; -} - - -ACE_CDR::Boolean -ACE_OutputCDR::replace (ACE_CDR::Short x, char* loc) -{ - if (this->find (loc) == 0) - return false; - -#if !defined (ACE_ENABLE_SWAP_ON_WRITE) - *reinterpret_cast (loc) = x; -#else - if (!this->do_byte_swap_) - { - *reinterpret_cast (loc) = x; - } - else - { - ACE_CDR::swap_2 (reinterpret_cast (&x), loc); - } -#endif /* ACE_ENABLE_SWAP_ON_WRITE */ - - return true; -} - - -int -ACE_OutputCDR::consolidate (void) -{ - // Optimize by only doing something if we need to - if (this->current_ != &this->start_) - { - // Set the number of bytes in the top-level block, reallocating - // if necessary. The rd_ptr and wr_ptr remain at the original offsets - // into the buffer, even if it is reallocated. - // Return an error if the allocation failed. - size_t const newsize = - ACE_CDR::first_size (this->total_length () - + ACE_CDR::MAX_ALIGNMENT); - if (this->start_.size (newsize) < 0) - { - return -1; - } - - // Consolidate the chain into the first block. NOTE that - // ACE_CDR::consolidate can not be used since we don't want to - // overwrite what is already in the first block. We just append it since - // the read and write pointers weren't affected by the resizing above. - // We also don't have to worry about alignment since the start block is - // already aligned. - // NOTE also we know there is a continuation since we checked for it - // above. There is therefore no reason to check for a 0 continuation - // field here. - ACE_Message_Block *cont = this->start_.cont (); - for (const ACE_Message_Block* i = cont; i != 0; i = i->cont ()) - { - this->start_.copy (i->rd_ptr (), i->length ()); - } - - // Release the old blocks that were consolidated and reset the - // current_ and current_is_writable_ to reflect the single used block. - ACE_Message_Block::release (cont); - this->start_.cont (0); - this->current_ = &this->start_; - this->current_is_writable_ = true; - } - - return 0; -} - - -ACE_Message_Block* -ACE_OutputCDR::find (char* loc) -{ - ACE_Message_Block* mb = 0; - for (mb = &this->start_; mb != 0; mb = mb->cont ()) - { - if (loc <= mb->wr_ptr () && loc >= mb->rd_ptr ()) - { - break; - } - } - - return mb; -} - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - -void -ACE_OutputCDR::register_monitor (const char *id) -{ - this->monitor_->name (id); - this->monitor_->add_to_registry (); -} - -void -ACE_OutputCDR::unregister_monitor (void) -{ - this->monitor_->remove_from_registry (); -} - -#endif /* ACE_HAS_MONITOR_POINTS==1 */ - -// **************************************************************** - -ACE_InputCDR::ACE_InputCDR (const char *buf, - size_t bufsiz, - int byte_order, - ACE_CDR::Octet major_version, - ACE_CDR::Octet minor_version) - : start_ (buf, bufsiz), - do_byte_swap_ (byte_order != ACE_CDR_BYTE_ORDER), - good_bit_ (true), - major_version_ (major_version), - minor_version_ (minor_version), - char_translator_ (0), - wchar_translator_ (0) -{ - this->start_.wr_ptr (bufsiz); - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - ACE_NEW (this->monitor_, - ACE::Monitor_Control::Size_Monitor); - this->monitor_->receive (bufsiz); -#endif /* ACE_HAS_MONITOR_POINTS==1 */ -} - -ACE_InputCDR::ACE_InputCDR (size_t bufsiz, - int byte_order, - ACE_CDR::Octet major_version, - ACE_CDR::Octet minor_version) - : start_ (bufsiz), - do_byte_swap_ (byte_order != ACE_CDR_BYTE_ORDER), - good_bit_ (true), - major_version_ (major_version), - minor_version_ (minor_version), - char_translator_ (0), - wchar_translator_ (0) -{ -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - ACE_NEW (this->monitor_, - ACE::Monitor_Control::Size_Monitor); - this->monitor_->receive (bufsiz); -#endif /* ACE_HAS_MONITOR_POINTS==1 */ -} - -ACE_InputCDR::ACE_InputCDR (const ACE_Message_Block *data, - int byte_order, - ACE_CDR::Octet major_version, - ACE_CDR::Octet minor_version, - ACE_Lock* lock) - : start_ (0, ACE_Message_Block::MB_DATA, 0, 0, 0, lock), - good_bit_ (true), - major_version_ (major_version), - minor_version_ (minor_version), - char_translator_ (0), - wchar_translator_ (0) -{ -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - ACE_NEW (this->monitor_, - ACE::Monitor_Control::Size_Monitor); - this->monitor_->receive (this->start_.total_size ()); -#endif /* ACE_HAS_MONITOR_POINTS==1 */ - - this->reset (data, byte_order); -} - -ACE_InputCDR::ACE_InputCDR (ACE_Data_Block *data, - ACE_Message_Block::Message_Flags flag, - int byte_order, - ACE_CDR::Octet major_version, - ACE_CDR::Octet minor_version) - : start_ (data, flag), - do_byte_swap_ (byte_order != ACE_CDR_BYTE_ORDER), - good_bit_ (true), - major_version_ (major_version), - minor_version_ (minor_version), - char_translator_ (0), - wchar_translator_ (0) -{ -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - ACE_NEW (this->monitor_, - ACE::Monitor_Control::Size_Monitor); - this->monitor_->receive (data->size ()); -#endif /* ACE_HAS_MONITOR_POINTS==1 */ -} - -ACE_InputCDR::ACE_InputCDR (ACE_Data_Block *data, - ACE_Message_Block::Message_Flags flag, - size_t rd_pos, - size_t wr_pos, - int byte_order, - ACE_CDR::Octet major_version, - ACE_CDR::Octet minor_version) - : start_ (data, flag), - do_byte_swap_ (byte_order != ACE_CDR_BYTE_ORDER), - good_bit_ (true), - major_version_ (major_version), - minor_version_ (minor_version), - char_translator_ (0), - wchar_translator_ (0) -{ - // Set the read pointer - this->start_.rd_ptr (rd_pos); - - // Set the write pointer after doing a sanity check. - char* wrpos = this->start_.base () + wr_pos; - - if (this->start_.end () >= wrpos) - { - this->start_.wr_ptr (wr_pos); - } - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - ACE_NEW (this->monitor_, - ACE::Monitor_Control::Size_Monitor); - this->monitor_->receive (data->size ()); -#endif /* ACE_HAS_MONITOR_POINTS==1 */ -} - -ACE_InputCDR::ACE_InputCDR (const ACE_InputCDR& rhs, - size_t size, - ACE_CDR::Long offset) - : start_ (rhs.start_, - ACE_CDR::MAX_ALIGNMENT), - do_byte_swap_ (rhs.do_byte_swap_), - good_bit_ (true), - major_version_ (rhs.major_version_), - minor_version_ (rhs.minor_version_), - char_translator_ (rhs.char_translator_), - wchar_translator_ (rhs.wchar_translator_) -{ -#if !defined (ACE_LACKS_CDR_ALIGNMENT) - // Align the base pointer assuming that the incoming stream is also - // aligned the way we are aligned - char *incoming_start = ACE_ptr_align_binary (rhs.start_.base (), - ACE_CDR::MAX_ALIGNMENT); -#else - char *incoming_start = rhs.start_.base (); -#endif /* ACE_LACKS_CDR_ALIGNMENT */ - - const size_t newpos = - (rhs.start_.rd_ptr() - incoming_start) + offset; - - if (newpos <= this->start_.space () - && newpos + size <= this->start_.space ()) - { - this->start_.rd_ptr (newpos); - this->start_.wr_ptr (newpos + size); - } - else - { - this->good_bit_ = false; - } - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - ACE_NEW (this->monitor_, - ACE::Monitor_Control::Size_Monitor); - this->monitor_->receive (this->start_.total_size ()); -#endif /* ACE_HAS_MONITOR_POINTS==1 */ -} - -ACE_InputCDR::ACE_InputCDR (const ACE_InputCDR& rhs, - size_t size) - : start_ (rhs.start_, - ACE_CDR::MAX_ALIGNMENT), - do_byte_swap_ (rhs.do_byte_swap_), - good_bit_ (true), - major_version_ (rhs.major_version_), - minor_version_ (rhs.minor_version_), - char_translator_ (rhs.char_translator_), - wchar_translator_ (rhs.wchar_translator_) -{ -#if !defined (ACE_LACKS_CDR_ALIGNMENT) - // Align the base pointer assuming that the incoming stream is also - // aligned the way we are aligned - char *incoming_start = ACE_ptr_align_binary (rhs.start_.base (), - ACE_CDR::MAX_ALIGNMENT); -#else - char *incoming_start = rhs.start_.base (); -#endif /* ACE_LACKS_CDR_ALIGNMENT */ - - const size_t newpos = - rhs.start_.rd_ptr() - incoming_start; - - if (newpos <= this->start_.space () - && newpos + size <= this->start_.space ()) - { - // Notice that ACE_Message_Block::duplicate may leave the - // wr_ptr() with a higher value than what we actually want. - this->start_.rd_ptr (newpos); - this->start_.wr_ptr (newpos + size); - - ACE_CDR::Octet byte_order = 0; - (void) this->read_octet (byte_order); - this->do_byte_swap_ = (byte_order != ACE_CDR_BYTE_ORDER); - } - else - { - this->good_bit_ = false; - } - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - ACE_NEW (this->monitor_, - ACE::Monitor_Control::Size_Monitor); - this->monitor_->receive (this->start_.total_size ()); -#endif /* ACE_HAS_MONITOR_POINTS==1 */ -} - -ACE_InputCDR::ACE_InputCDR (const ACE_InputCDR& rhs) - : start_ (rhs.start_, - ACE_CDR::MAX_ALIGNMENT), - do_byte_swap_ (rhs.do_byte_swap_), - good_bit_ (true), - major_version_ (rhs.major_version_), - minor_version_ (rhs.minor_version_), - char_translator_ (rhs.char_translator_), - wchar_translator_ (rhs.wchar_translator_) -{ -#if !defined (ACE_LACKS_CDR_ALIGNMENT) - char *buf = ACE_ptr_align_binary (rhs.start_.base (), - ACE_CDR::MAX_ALIGNMENT); -#else - char *buf = rhs.start_.base (); -#endif /* ACE_LACKS_CDR_ALIGNMENT */ - - size_t rd_offset = rhs.start_.rd_ptr () - buf; - size_t wr_offset = rhs.start_.wr_ptr () - buf; - this->start_.rd_ptr (rd_offset); - this->start_.wr_ptr (wr_offset); - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - ACE_NEW (this->monitor_, - ACE::Monitor_Control::Size_Monitor); - this->monitor_->receive (this->start_.total_size ()); -#endif /* ACE_HAS_MONITOR_POINTS==1 */ -} - -ACE_InputCDR::ACE_InputCDR (ACE_InputCDR::Transfer_Contents x) - : start_ (x.rhs_.start_.data_block ()), - do_byte_swap_ (x.rhs_.do_byte_swap_), - good_bit_ (true), - major_version_ (x.rhs_.major_version_), - minor_version_ (x.rhs_.minor_version_), - char_translator_ (x.rhs_.char_translator_), - wchar_translator_ (x.rhs_.wchar_translator_) -{ - this->start_.rd_ptr (x.rhs_.start_.rd_ptr ()); - this->start_.wr_ptr (x.rhs_.start_.wr_ptr ()); - - ACE_Data_Block* db = this->start_.data_block ()->clone_nocopy (); - (void) x.rhs_.start_.replace_data_block (db); - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - ACE_NEW (this->monitor_, - ACE::Monitor_Control::Size_Monitor); - this->monitor_->receive (this->start_.total_size ()); -#endif /* ACE_HAS_MONITOR_POINTS==1 */ -} - -ACE_InputCDR& -ACE_InputCDR::operator= (const ACE_InputCDR& rhs) -{ - if (this != &rhs) - { - this->start_.data_block (rhs.start_.data_block ()->duplicate ()); - this->start_.rd_ptr (rhs.start_.rd_ptr ()); - this->start_.wr_ptr (rhs.start_.wr_ptr ()); - this->do_byte_swap_ = rhs.do_byte_swap_; - this->good_bit_ = true; - this->char_translator_ = rhs.char_translator_; - this->major_version_ = rhs.major_version_; - this->minor_version_ = rhs.minor_version_; - } - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - this->monitor_->receive (this->start_.total_size ()); -#endif /* ACE_HAS_MONITOR_POINTS==1 */ - - return *this; -} - -ACE_InputCDR::ACE_InputCDR (const ACE_OutputCDR& rhs, - ACE_Allocator* buffer_allocator, - ACE_Allocator* data_block_allocator, - ACE_Allocator* message_block_allocator) - : start_ (rhs.total_length () + ACE_CDR::MAX_ALIGNMENT, - ACE_Message_Block::MB_DATA, - 0, - 0, - buffer_allocator, - 0, - 0, - ACE_Time_Value::zero, - ACE_Time_Value::max_time, - data_block_allocator, - message_block_allocator), - do_byte_swap_ (rhs.do_byte_swap_), - good_bit_ (true), - major_version_ (rhs.major_version_), - minor_version_ (rhs.minor_version_), - char_translator_ (rhs.char_translator_), - wchar_translator_ (rhs.wchar_translator_) -{ - ACE_CDR::mb_align (&this->start_); - for (const ACE_Message_Block *i = rhs.begin (); - i != rhs.end (); - i = i->cont ()) - { - this->start_.copy (i->rd_ptr (), i->length ()); - } - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - ACE_NEW (this->monitor_, - ACE::Monitor_Control::Size_Monitor); - this->monitor_->receive (this->start_.total_size ()); -#endif /* ACE_HAS_MONITOR_POINTS==1 */ -} - -ACE_CDR::Boolean -ACE_InputCDR::skip_wchar (void) -{ - if (static_cast (major_version_) == 1 - && static_cast (minor_version_) == 2) - { - ACE_CDR::Octet len; - if (this->read_1 (&len)) - return this->skip_bytes (static_cast (len)); - } - else - { - ACE_CDR::WChar x; - void * const temp = &x; - if (ACE_OutputCDR::wchar_maxbytes_ == 2) - return this->read_2 (reinterpret_cast (temp)); - else - return this->read_4 (reinterpret_cast (temp)); - } - - return (this->good_bit_ = false); -} - -ACE_CDR::Boolean -ACE_InputCDR::read_wchar (ACE_CDR::WChar& x) -{ - if (this->wchar_translator_ != 0) - { - this->good_bit_ = this->wchar_translator_->read_wchar (*this,x); - return this->good_bit_; - } - if (ACE_OutputCDR::wchar_maxbytes_ == 0) - { - errno = EACCES; - return (this->good_bit_ = false); - } - - if (ACE_OutputCDR::wchar_maxbytes_ == sizeof (ACE_CDR::WChar)) - { - if (static_cast (major_version_) == 1 - && static_cast (minor_version_) == 2) - { - ACE_CDR::Octet len; - - if (this->read_1 (&len)) - return this->read_array - (reinterpret_cast (&x), - static_cast (len), - ACE_CDR::OCTET_ALIGN, - 1); - - else - return (this->good_bit_ = false); - } - - void * const temp = &x; - if (sizeof (ACE_CDR::WChar) == 2) - return this->read_2 (reinterpret_cast (temp)); - else - return this->read_4 (reinterpret_cast (temp)); - } - - if (static_cast (major_version_) == 1 - && static_cast (minor_version_) == 2) - { - ACE_CDR::Octet len; - - if (this->read_1 (&len)) - { - if (len == 2) - { - ACE_CDR::Short sx; - if (this->read_array - (reinterpret_cast (&sx), - static_cast (len), - ACE_CDR::OCTET_ALIGN, - 1)) - { - x = static_cast (sx); - return true; - } - } - else - { - ACE_CDR::Octet ox; - if (this->read_array - (reinterpret_cast (&ox), - static_cast (len), - ACE_CDR::OCTET_ALIGN, - 1)) - { - x = static_cast (ox); - return true; - } - } - } - } - else - { - if (ACE_OutputCDR::wchar_maxbytes_ == 2) - { - ACE_CDR::UShort sx; - if (this->read_2 (reinterpret_cast (&sx))) - { - x = static_cast (sx); - return true; - } - } - else - { - ACE_CDR::Octet ox; - if (this->read_1 (&ox)) - { - x = static_cast (ox); - return true; - } - - } - } - return (this->good_bit_ = false); -} - -ACE_CDR::Boolean -ACE_InputCDR::read_string (ACE_CDR::Char *&x) -{ - // @@ This is a slight violation of "Optimize for the common case", - // i.e. normally the translator will be 0, but OTOH the code is - // smaller and should be better for the cache ;-) ;-) - if (this->char_translator_ != 0) - { - this->good_bit_ = this->char_translator_->read_string (*this, x); - return this->good_bit_; - } - - ACE_CDR::ULong len = 0; - - if (!this->read_ulong (len)) - return false; - - // A check for the length being too great is done later in the - // call to read_char_array but we want to have it done before - // the memory is allocated. - if (len > 0 && len <= this->length()) - { - ACE_NEW_RETURN (x, - ACE_CDR::Char[len], - 0); - - ACE_Auto_Basic_Array_Ptr safe_data (x); - - if (this->read_char_array (x, len)) - { - (void) safe_data.release (); - return true; - } - } - else if (len == 0) - { - // Convert any null strings to empty strings since empty - // strings can cause crashes. (See bug 58.) - ACE_NEW_RETURN (x, - ACE_CDR::Char[1], - 0); - ACE_OS::strcpy (const_cast (x), ""); - return true; - } - - x = 0; - return (this->good_bit_ = false); -} - -ACE_CDR::Boolean -ACE_InputCDR::read_string (ACE_CString &x) -{ - ACE_CDR::Char * data = 0; - if (this->read_string (data)) - { - ACE_Auto_Basic_Array_Ptr safe_data (data); - x = data; - return true; - } - - x = ""; - return (this->good_bit_ = false); -} - -ACE_CDR::Boolean -ACE_InputCDR::read_wstring (ACE_CDR::WChar*& x) -{ - // @@ This is a slight violation of "Optimize for the common case", - // i.e. normally the translator will be 0, but OTOH the code is - // smaller and should be better for the cache ;-) ;-) - if (this->wchar_translator_ != 0) - { - this->good_bit_ = this->wchar_translator_->read_wstring (*this, x); - return this->good_bit_; - } - if (ACE_OutputCDR::wchar_maxbytes_ == 0) - { - errno = EACCES; - return (this->good_bit_ = false); - } - - ACE_CDR::ULong len = 0; - - if (!this->read_ulong (len)) - { - return false; - } - - // A check for the length being too great is done later in the - // call to read_char_array but we want to have it done before - // the memory is allocated. - if (len > 0 && len <= this->length ()) - { - ACE_Auto_Basic_Array_Ptr safe_data; - - if (static_cast (this->major_version_) == 1 - && static_cast (this->minor_version_) == 2) - { - len /= - ACE_Utils::truncate_cast ( - ACE_OutputCDR::wchar_maxbytes_); - - //allocating one extra for the null character needed by applications - ACE_NEW_RETURN (x, - ACE_CDR::WChar [len + 1], - false); - - ACE_auto_ptr_reset (safe_data, x); - - if (this->read_wchar_array (x, len)) - { - - //Null character used by applications to find the end of - //the wstring - //Is this okay with the GIOP 1.2 spec?? - x[len] = '\x00'; - - (void) safe_data.release (); - - return true; - } - } - else - { - ACE_NEW_RETURN (x, - ACE_CDR::WChar [len], - false); - - ACE_auto_ptr_reset (safe_data, x); - - if (this->read_wchar_array (x, len)) - { - (void) safe_data.release (); - - return true; - } - } - } - else if (len == 0) - { - // Convert any null strings to empty strings since empty - // strings can cause crashes. (See bug 58.) - ACE_NEW_RETURN (x, - ACE_CDR::WChar[1], - false); - x[0] = '\x00'; - return true; - } - - this->good_bit_ = false; - x = 0; - return false; -} - -ACE_CDR::Boolean -ACE_InputCDR::read_array (void* x, - size_t size, - size_t align, - ACE_CDR::ULong length) -{ - if (length == 0) - return true; - char* buf = 0; - - if (this->adjust (size * length, align, buf) == 0) - { -#if defined (ACE_DISABLE_SWAP_ON_READ) - ACE_OS::memcpy (x, buf, size*length); -#else - if (!this->do_byte_swap_ || size == 1) - ACE_OS::memcpy (x, buf, size*length); - else - { - char *target = reinterpret_cast (x); - switch (size) - { - case 2: - ACE_CDR::swap_2_array (buf, target, length); - break; - case 4: - ACE_CDR::swap_4_array (buf, target, length); - break; - case 8: - ACE_CDR::swap_8_array (buf, target, length); - break; - case 16: - ACE_CDR::swap_16_array (buf, target, length); - break; - default: - // TODO: print something? - this->good_bit_ = false; - return false; - } - } -#endif /* ACE_DISABLE_SWAP_ON_READ */ - return this->good_bit_; - } - return false; -} - -ACE_CDR::Boolean -ACE_InputCDR::read_wchar_array_i (ACE_CDR::WChar* x, - ACE_CDR::ULong length) -{ - if (length == 0) - return true; - char* buf = 0; - size_t const align = (ACE_OutputCDR::wchar_maxbytes_ == 2) ? - ACE_CDR::SHORT_ALIGN : - ACE_CDR::OCTET_ALIGN; - - if (this->adjust (ACE_OutputCDR::wchar_maxbytes_ * length, align, buf) == 0) - { - if (ACE_OutputCDR::wchar_maxbytes_ == 2) - { - ACE_CDR::UShort *sb = reinterpret_cast (buf); - for (size_t i = 0; i < length; ++i) -#if defined (ACE_DISABLE_SWAP_ON_READ) - x[i] = static_cast (sb[i]); -#else - if (!this->do_byte_swap_) - x[i] = static_cast (sb[i]); - else - { - ACE_CDR::UShort sx; - ACE_CDR::swap_2 (&buf[i * 2], reinterpret_cast (&sx)); - x[i] = static_cast (sx); - } -#endif /* ACE_DISABLE_SWAP_ON_READ */ - } - else - { - for (size_t i = 0; i < length; ++i) - x[i] = static_cast (buf[i]); - } - return this->good_bit_; - } - return false; -} - - -ACE_CDR::Boolean -ACE_InputCDR::read_boolean_array (ACE_CDR::Boolean *x, - ACE_CDR::ULong length) -{ - // Make sure the length of the array isn't greater than the length of - // the stream. - if (length > this->length ()) - { - this->good_bit_ = false; - return false; - } - - // It is hard to optimize this, the spec requires that on the wire - // booleans be represented as a byte with value 0 or 1, but in - // memory it is possible (though very unlikely) that a boolean has - // a non-zero value (different from 1). - // We resort to a simple loop. - for (ACE_CDR::ULong i = 0; i != length && this->good_bit_; ++i) - (void) this->read_boolean (x[i]); - - return this->good_bit_; -} - -ACE_CDR::Boolean -ACE_InputCDR::read_1 (ACE_CDR::Octet *x) -{ - if (this->rd_ptr () < this->wr_ptr ()) - { - *x = *reinterpret_cast (this->rd_ptr ()); - this->start_.rd_ptr (1); - return true; - } - - this->good_bit_ = false; - return false; -} - -ACE_CDR::Boolean -ACE_InputCDR::read_2 (ACE_CDR::UShort *x) -{ - char *buf = 0; - if (this->adjust (ACE_CDR::SHORT_SIZE, buf) == 0) - { -#if !defined (ACE_DISABLE_SWAP_ON_READ) - if (!this->do_byte_swap_) - *x = *reinterpret_cast (buf); - else - ACE_CDR::swap_2 (buf, reinterpret_cast (x)); -#else - *x = *reinterpret_cast (buf); -#endif /* ACE_DISABLE_SWAP_ON_READ */ - return true; - } - this->good_bit_ = false; - return false; -} - -ACE_CDR::Boolean -ACE_InputCDR::read_4 (ACE_CDR::ULong *x) -{ - char *buf = 0; - if (this->adjust (ACE_CDR::LONG_SIZE, buf) == 0) - { -#if !defined (ACE_DISABLE_SWAP_ON_READ) - if (!this->do_byte_swap_) - *x = *reinterpret_cast (buf); - else - ACE_CDR::swap_4 (buf, reinterpret_cast (x)); -#else - *x = *reinterpret_cast (buf); -#endif /* ACE_DISABLE_SWAP_ON_READ */ - return true; - } - this->good_bit_ = false; - return false; -} - -ACE_CDR::Boolean -ACE_InputCDR::read_8 (ACE_CDR::ULongLong *x) -{ - char *buf = 0; - - if (this->adjust (ACE_CDR::LONGLONG_SIZE, buf) == 0) - { -#if !defined (ACE_DISABLE_SWAP_ON_READ) -# if defined (__arm__) && !defined (ACE_HAS_IPHONE) - if (!this->do_byte_swap_) - { - // Convert from Intel format (12345678 => 56781234) - const char *orig = buf; - char *target = reinterpret_cast (x); - register ACE_UINT32 x = - *reinterpret_cast (orig); - register ACE_UINT32 y = - *reinterpret_cast (orig + 4); - *reinterpret_cast (target) = y; - *reinterpret_cast (target + 4) = x; - } - else - { - // Convert from Sparc format (12345678 => 43218765) - const char *orig = buf; - char *target = reinterpret_cast (x); - register ACE_UINT32 x = - *reinterpret_cast (orig); - register ACE_UINT32 y = - *reinterpret_cast (orig + 4); - x = (x << 24) | ((x & 0xff00) << 8) | ((x & 0xff0000) >> 8) | (x >> 24); - y = (y << 24) | ((y & 0xff00) << 8) | ((y & 0xff0000) >> 8) | (y >> 24); - *reinterpret_cast (target) = x; - *reinterpret_cast (target + 4) = y; - } -# else - if (!this->do_byte_swap_) - *x = *reinterpret_cast (buf); - else - ACE_CDR::swap_8 (buf, reinterpret_cast (x)); -# endif /* !__arm__ */ -#else - *x = *reinterpret_cast (buf); -#endif /* ACE_DISABLE_SWAP_ON_READ */ - return true; - } - - this->good_bit_ = false; - return false; -} - -ACE_CDR::Boolean -ACE_InputCDR::read_16 (ACE_CDR::LongDouble *x) -{ - char *buf = 0; - if (this->adjust (ACE_CDR::LONGDOUBLE_SIZE, - ACE_CDR::LONGDOUBLE_ALIGN, - buf) == 0) - { -#if !defined (ACE_DISABLE_SWAP_ON_READ) - if (!this->do_byte_swap_) - *x = *reinterpret_cast (buf); - else - ACE_CDR::swap_16 (buf, reinterpret_cast (x)); -#else - *x = *reinterpret_cast (buf); -#endif /* ACE_DISABLE_SWAP_ON_READ */ - return true; - } - - this->good_bit_ = false; - return false; -} - -ACE_CDR::Boolean -ACE_InputCDR::skip_string (void) -{ - ACE_CDR::ULong len = 0; - if (this->read_ulong (len)) - { - if (this->rd_ptr () + len <= this->wr_ptr ()) - { - this->rd_ptr (len); - return true; - } - this->good_bit_ = false; - } - return false; -} - -ACE_CDR::Boolean -ACE_InputCDR::skip_wstring (void) -{ - ACE_CDR::ULong len = 0; - ACE_CDR::Boolean continue_skipping = read_ulong (len); - - if (continue_skipping && len != 0) - { - if (static_cast (this->major_version_) == 1 - && static_cast (this->minor_version_) == 2) - continue_skipping = this->skip_bytes ((size_t)len); - else - while (continue_skipping && len--) - continue_skipping = this->skip_wchar (); - } - return continue_skipping; -} - -ACE_CDR::Boolean -ACE_InputCDR::skip_bytes (size_t len) -{ - if (this->rd_ptr () + len <= this->wr_ptr ()) - { - this->rd_ptr (len); - return true; - } - this->good_bit_ = false; - return false; -} - -int -ACE_InputCDR::grow (size_t newsize) -{ - if (ACE_CDR::grow (&this->start_, newsize) == -1) - return -1; - - ACE_CDR::mb_align (&this->start_); - this->start_.wr_ptr (newsize); - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - if (newsize > this->start_.total_size ()) - { - this->monitor_->receive (newsize); - } -#endif /* ACE_HAS_MONITOR_POINTS==1 */ - - return 0; -} - -void -ACE_InputCDR::reset (const ACE_Message_Block* data, - int byte_order) -{ - this->reset_byte_order (byte_order); - ACE_CDR::consolidate (&this->start_, data); - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - this->monitor_->receive (this->start_.total_size ()); -#endif /* ACE_HAS_MONITOR_POINTS==1 */ -} - -void -ACE_InputCDR::steal_from (ACE_InputCDR &cdr) -{ - this->do_byte_swap_ = cdr.do_byte_swap_; - this->start_.data_block (cdr.start_.data_block ()->duplicate ()); - - // If the message block had a DONT_DELETE flags, just clear it off.. - this->start_.clr_self_flags (ACE_Message_Block::DONT_DELETE); - this->start_.rd_ptr (cdr.start_.rd_ptr ()); - - this->start_.wr_ptr (cdr.start_.wr_ptr ()); - this->major_version_ = cdr.major_version_; - this->minor_version_ = cdr.minor_version_; - cdr.reset_contents (); - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - this->monitor_->receive (this->start_.total_size ()); -#endif /* ACE_HAS_MONITOR_POINTS==1 */ -} - -void -ACE_InputCDR::exchange_data_blocks (ACE_InputCDR &cdr) -{ - // Exchange byte orders - int const byte_order = cdr.do_byte_swap_; - cdr.do_byte_swap_ = this->do_byte_swap_; - this->do_byte_swap_ = byte_order; - - // Get the destination read and write pointers - size_t const drd_pos = - cdr.start_.rd_ptr () - cdr.start_.base (); - size_t const dwr_pos = - cdr.start_.wr_ptr () - cdr.start_.base (); - - // Get the source read & write pointers - size_t const srd_pos = - this->start_.rd_ptr () - this->start_.base (); - size_t const swr_pos = - this->start_.wr_ptr () - this->start_.base (); - - // Exchange data_blocks. Dont release any of the data blocks. - ACE_Data_Block *dnb = - this->start_.replace_data_block (cdr.start_.data_block ()); - cdr.start_.replace_data_block (dnb); - - // Exchange the flags information.. - ACE_Message_Block::Message_Flags df = cdr.start_.self_flags (); - ACE_Message_Block::Message_Flags sf = this->start_.self_flags (); - - cdr.start_.clr_self_flags (df); - this->start_.clr_self_flags (sf); - - cdr.start_.set_self_flags (sf); - this->start_.set_self_flags (df); - - // Reset the pointers to zero before it is set again. - cdr.start_.reset (); - this->start_.reset (); - - // Set the read and write pointers. - if (cdr.start_.size () >= srd_pos) - { - cdr.start_.rd_ptr (srd_pos); - } - - if (cdr.start_.size () >= swr_pos) - { - cdr.start_.wr_ptr (swr_pos); - } - - if (this->start_.size () >= drd_pos) - { - this->start_.rd_ptr (drd_pos); - } - - if (this->start_.size () >= dwr_pos) - { - this->start_.wr_ptr (dwr_pos); - } - - ACE_CDR::Octet const dmajor = cdr.major_version_; - ACE_CDR::Octet const dminor = cdr.minor_version_; - - // Exchange the GIOP version info - cdr.major_version_ = this->major_version_; - cdr.minor_version_ = this->minor_version_; - - this->major_version_ = dmajor; - this->minor_version_ = dminor; - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - this->monitor_->receive (this->start_.total_size ()); -#endif /* ACE_HAS_MONITOR_POINTS==1 */ -} - -ACE_Data_Block * -ACE_InputCDR::clone_from (ACE_InputCDR &cdr) -{ - this->do_byte_swap_ = cdr.do_byte_swap_; - - // Get the read & write pointer positions in the incoming CDR - // streams - char *rd_ptr = cdr.start_.rd_ptr (); - char *wr_ptr = cdr.start_.wr_ptr (); - - // Now reset the incoming CDR stream - cdr.start_.reset (); - - // As we have reset the stream, try to align the underlying message - // block in the incoming stream - ACE_CDR::mb_align (&cdr.start_); - - // Get the read & write pointer positions again - char *nrd_ptr = cdr.start_.rd_ptr (); - char *nwr_ptr = cdr.start_.wr_ptr (); - - // Actual length of the stream is.. - // @todo: This will look idiotic, but we dont seem to have much of a - // choice. How do we calculate the length of the incoming stream? - // Calling the method before calling reset () would give us the - // wrong length of the stream that needs copying. So we do the - // calulation like this - // (1) We get the and positions of the incoming - // stream. - // (2) Then we reset the stream and then align it. - // (3) We get the and positions again. (Points #1 - // thru #3 has been done already) - // (4) The difference in the and positions gives - // us the following, the actual bytes traversed by the and - // . - // (5) The bytes traversed by the is the actual length of - // the stream. - - // Actual bytes traversed - size_t rd_bytes = rd_ptr - nrd_ptr; - size_t wr_bytes = wr_ptr - nwr_ptr; - - ACE_CDR::mb_align (&this->start_); - - ACE_Data_Block *db = this->start_.data_block (); - - // If the size of the data that needs to be copied are higher than - // what is available, then do a reallocation. - if (wr_bytes > (this->start_.size () - ACE_CDR::MAX_ALIGNMENT)) - { - // @@NOTE: We need to probably add another method to the message - // block interface to simplify this - db = cdr.start_.data_block ()->clone_nocopy (); - - if (db == 0 || db->size ((wr_bytes) + - ACE_CDR::MAX_ALIGNMENT) == -1) - return 0; - - // Replace our data block by using the incoming CDR stream. - db = this->start_.replace_data_block (db); - - // Align the start_ message block. - ACE_CDR::mb_align (&this->start_); - - // Clear the DONT_DELETE flag if it has been set - this->start_.clr_self_flags (ACE_Message_Block::DONT_DELETE); - } - - // Now do the copy - (void) ACE_OS::memcpy (this->start_.wr_ptr (), - cdr.start_.rd_ptr (), - wr_bytes); - - // Set the read pointer position to the same point as that was in - // cdr. - this->start_.rd_ptr (rd_bytes); - this->start_.wr_ptr (wr_bytes); - - // We have changed the read & write pointers for the incoming - // stream. Set them back to the positions that they were before.. - cdr.start_.rd_ptr (rd_bytes); - cdr.start_.wr_ptr (wr_bytes); - - this->major_version_ = cdr.major_version_; - this->minor_version_ = cdr.minor_version_; - - // Copy the char/wchar translators - this->char_translator_ = cdr.char_translator_; - this->wchar_translator_ = cdr.wchar_translator_; - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - this->monitor_->receive (this->start_.total_size ()); -#endif /* ACE_HAS_MONITOR_POINTS==1 */ - - return db; -} - -ACE_Message_Block* -ACE_InputCDR::steal_contents (void) -{ - ACE_Message_Block* block = this->start_.clone (); - this->start_.data_block (block->data_block ()->clone ()); - - // If at all our message had a DONT_DELETE flag set, just clear it - // off. - this->start_.clr_self_flags (ACE_Message_Block::DONT_DELETE); - - ACE_CDR::mb_align (&this->start_); - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - this->monitor_->receive (this->start_.total_size ()); -#endif /* ACE_HAS_MONITOR_POINTS==1 */ - - return block; -} - -void -ACE_InputCDR::reset_contents (void) -{ - this->start_.data_block (this->start_.data_block ()->clone_nocopy ()); - - // Reset the flags... - this->start_.clr_self_flags (ACE_Message_Block::DONT_DELETE); - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - this->monitor_->receive (this->start_.total_size ()); -#endif /* ACE_HAS_MONITOR_POINTS==1 */ -} - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - -void -ACE_InputCDR::register_monitor (const char *id) -{ - this->monitor_->name (id); - this->monitor_->add_to_registry (); -} - -void -ACE_InputCDR::unregister_monitor (void) -{ - this->monitor_->remove_from_registry (); -} - -#endif /* ACE_HAS_MONITOR_POINTS==1 */ - -// -------------------------------------------------------------- - -ACE_Char_Codeset_Translator::~ACE_Char_Codeset_Translator (void) -{ -} - -// -------------------------------------------------------------- - -ACE_WChar_Codeset_Translator::~ACE_WChar_Codeset_Translator (void) -{ -} - -// -------------------------------------------------------------- - -ACE_CDR::Boolean -operator<< (ACE_OutputCDR &os, const ACE_CString &x) -{ - os.write_string (x); - return os.good_bit (); -} - -ACE_CDR::Boolean -operator>> (ACE_InputCDR &is, ACE_CString &x) -{ - is.read_string (x); - return is.good_bit (); -} - -#if defined (GEN_OSTREAM_OPS) - -std::ostream& -operator<< (std::ostream &os, ACE_OutputCDR::from_boolean x) -{ - return (x.val_ ? os << "true" : os << "false"); -} - -std::ostream& -operator<< (std::ostream &os, ACE_OutputCDR::from_char x) -{ - return os << '\'' << x.val_ << '\''; -} - -std::ostream& -operator<< (std::ostream &os, ACE_OutputCDR::from_wchar x) -{ - os.setf (ios_base::showbase); - os.setf (ios_base::hex, ios_base::basefield); - os << x.val_; - os.unsetf (ios_base::showbase); - os.setf (ios_base::dec, ios_base::basefield); - return os; -} - -std::ostream& -operator<< (std::ostream &os, ACE_OutputCDR::from_octet x) -{ - // Same format (hex) and no risk of overflow. - ACE_CDR::WChar w = static_cast (x.val_); - ACE_OutputCDR::from_wchar tmp (w); - return os << tmp; -} - -#endif /* GEN_OSTREAM_OPS */ - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/CDR_Stream.h b/externals/ace/CDR_Stream.h deleted file mode 100644 index 0a200dc56dd..00000000000 --- a/externals/ace/CDR_Stream.h +++ /dev/null @@ -1,1402 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file CDR_Stream.h - * - * $Id: CDR_Stream.h 84527 2009-02-19 14:01:42Z johnnyw $ - * - * ACE Common Data Representation (CDR) marshaling and demarshaling - * classes. - * - * This implementation was inspired in the CDR class in SunSoft's - * IIOP engine, but has a completely different implementation and a - * different interface too. - * - * The current implementation assumes that the host has 1-byte, - * 2-byte and 4-byte integral types, and that it has single - * precision and double precision IEEE floats. - * Those assumptions are pretty good these days, with Crays being - * the only known exception. - * - * Optimizations - * ------------- - * ACE_LACKS_CDR_ALIGNMENT - * @author Arvind S. Krishna - * - * CDR stream ignores alignment when marshaling data. Use this option - * only when ACE_DISABLE_SWAP_ON_READ can be enabled. This option requires - * ACE CDR engine to do both marshaling and demarshaling. - * - * - * @author TAO version by Aniruddha Gokhale - * @author Carlos O'Ryan - * @author ACE version by Jeff Parsons - * @author Istvan Buki - * @author Codeset translation by Jim Rogers - */ -//============================================================================= - -#ifndef ACE_CDR_STREAM_H -#define ACE_CDR_STREAM_H - -#include /**/ "ace/pre.h" - -#include "ace/CDR_Base.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/SStringfwd.h" -#include "ace/Message_Block.h" - -#if defined (GEN_OSTREAM_OPS) -#include "ace/streams.h" -#endif /* GEN_OSTREAM_OPS */ - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) -#include "Monitor_Size.h" -#endif /* ACE_HAS_MONITOR_POINTS==1 */ - - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -class ACE_Char_Codeset_Translator; -class ACE_WChar_Codeset_Translator; - -class ACE_InputCDR; - -/** - * @class ACE_OutputCDR - * - * @brief A CDR stream for marshalling data, most often for transmission to - * another system which may or may not have the same byte order. - * - * This class is based on the the CORBA spec for Java (98-02-29), - * java class omg.org.CORBA.portable.OutputStream. It diverts in - * a few ways: - * @li Operations taking arrays don't have offsets, because in C++ - * it is easier to describe an array starting from x+offset. - * @li Operations return an error status, because exceptions are - * not widely available in C++ (yet). - */ -class ACE_Export ACE_OutputCDR -{ -public: - /** - * The Codeset translators need access to some private members to - * efficiently marshal arrays - * For reading from an output CDR stream. - */ - friend class ACE_Char_Codeset_Translator; - friend class ACE_WChar_Codeset_Translator; - friend class ACE_InputCDR; - - /** - * Default constructor; allows one to set byte ordering, allocators, and - * tuning information. - * - * @param size Causes constructor to preallocate @a size bytes; if - * @a size is 0 it allocates the default size. - * - * @param byte_order The byte order that data will have within this - * object. Unless otherwise specified, the byte order - * will be the order native to the hardware this is - * executed on. To force the marshalled data to have - * a specific order, specify one of the values defined - * in ACE_CDR::Byte_Order. - * @note The @c ACE_ENABLE_SWAP_ON_WRITE config macro - * must be set for any local byte swapping to occur - * as data is inserted into an ACE_OutputCDR object. - */ - ACE_OutputCDR (size_t size = 0, - int byte_order = ACE_CDR::BYTE_ORDER_NATIVE, - ACE_Allocator* buffer_allocator = 0, - ACE_Allocator* data_block_allocator = 0, - ACE_Allocator* message_block_allocator = 0, - size_t memcpy_tradeoff = ACE_DEFAULT_CDR_MEMCPY_TRADEOFF, - ACE_CDR::Octet major_version = ACE_CDR_GIOP_MAJOR_VERSION, - ACE_CDR::Octet minor_version = ACE_CDR_GIOP_MINOR_VERSION); - - /// Build a CDR stream with an initial buffer, it will *not* remove - /// @a data, since it did not allocated it. It's important to be careful - /// with the alignment of @a data. - /** - * Create an output stream from an arbitrary buffer, care must be - * exercised with alignment, because this contructor will align if - * needed. In this case @a data will not point to the start of the - * output stream. @c begin()->rd_ptr() points to the start of the - * output stream. See @c ACE_ptr_align_binary() to properly align a - * pointer and use ACE_CDR::MAX_ALIGNMENT for the correct alignment. - */ - ACE_OutputCDR (char *data, - size_t size, - int byte_order = ACE_CDR::BYTE_ORDER_NATIVE, - ACE_Allocator* buffer_allocator = 0, - ACE_Allocator* data_block_allocator = 0, - ACE_Allocator* message_block_allocator = 0, - size_t memcpy_tradeoff = ACE_DEFAULT_CDR_MEMCPY_TRADEOFF, - ACE_CDR::Octet giop_major_version = ACE_CDR_GIOP_MAJOR_VERSION, - ACE_CDR::Octet giop_minor_version = ACE_CDR_GIOP_MINOR_VERSION); - - /// Build a CDR stream with an initial data block, it will *not* remove - /// , since it did not allocated it. It's important to be - // careful with the alignment of . - /** - * Create an output stream from an arbitrary data block, care must be - * exercised with alignment, because this contructor will align if - * needed. In this case @a data_block will not point to the - * start of the output stream. begin()->rd_ptr() points to the start - * off the output stream. See ACE_ptr_align_binary() to properly align a - * pointer and use ACE_CDR::MAX_ALIGNMENT for the correct alignment. - */ - ACE_OutputCDR (ACE_Data_Block *data_block, - int byte_order = ACE_CDR::BYTE_ORDER_NATIVE, - ACE_Allocator* message_block_allocator = 0, - size_t memcpy_tradeoff = ACE_DEFAULT_CDR_MEMCPY_TRADEOFF, - ACE_CDR::Octet giop_major_version = ACE_CDR_GIOP_MAJOR_VERSION, - ACE_CDR::Octet giop_minor_version = ACE_CDR_GIOP_MINOR_VERSION); - - /// Build a CDR stream with an initial Message_Block chain, it will - /// *not* remove @a data, since it did not allocate it. - ACE_OutputCDR (ACE_Message_Block *data, - int byte_order = ACE_CDR::BYTE_ORDER_NATIVE, - size_t memcpy_tradeoff = ACE_DEFAULT_CDR_MEMCPY_TRADEOFF, - ACE_CDR::Octet giop_major_version = ACE_CDR_GIOP_MAJOR_VERSION, - ACE_CDR::Octet giop_minor_version = ACE_CDR_GIOP_MINOR_VERSION); - - /// destructor - ~ACE_OutputCDR (void); - - /** - * Disambiguate overload when inserting booleans, octets, chars, and - * bounded strings. - */ - //@{ @name Helper classes - - struct ACE_Export from_boolean - { - explicit from_boolean (ACE_CDR::Boolean b); - ACE_CDR::Boolean val_; - }; - - struct ACE_Export from_octet - { - explicit from_octet (ACE_CDR::Octet o); - ACE_CDR::Octet val_; - }; - - struct ACE_Export from_char - { - explicit from_char (ACE_CDR::Char c); - ACE_CDR::Char val_; - }; - - struct ACE_Export from_wchar - { - explicit from_wchar (ACE_CDR::WChar wc); - ACE_CDR::WChar val_; - }; - - struct ACE_Export from_string - { - from_string (ACE_CDR::Char* s, - ACE_CDR::ULong b, - ACE_CDR::Boolean nocopy = 0); - from_string (const ACE_CDR::Char* s, - ACE_CDR::ULong b, - ACE_CDR::Boolean nocopy = 0); - ACE_CDR::Char *val_; - ACE_CDR::ULong bound_; - ACE_CDR::Boolean nocopy_; - }; - - struct ACE_Export from_wstring - { - from_wstring (ACE_CDR::WChar* ws, - ACE_CDR::ULong b, - ACE_CDR::Boolean nocopy = 0); - from_wstring (const ACE_CDR::WChar* ws, - ACE_CDR::ULong b, - ACE_CDR::Boolean nocopy = 0); - ACE_CDR::WChar *val_; - ACE_CDR::ULong bound_; - ACE_CDR::Boolean nocopy_; - }; - //@} - - /** - * @{ @name Write operations - * Return 0 on failure and 1 on success. - */ - ACE_CDR::Boolean write_boolean (ACE_CDR::Boolean x); - ACE_CDR::Boolean write_char (ACE_CDR::Char x); - ACE_CDR::Boolean write_wchar (ACE_CDR::WChar x); - ACE_CDR::Boolean write_octet (ACE_CDR::Octet x); - ACE_CDR::Boolean write_short (ACE_CDR::Short x); - ACE_CDR::Boolean write_ushort (ACE_CDR::UShort x); - ACE_CDR::Boolean write_long (ACE_CDR::Long x); - ACE_CDR::Boolean write_ulong (ACE_CDR::ULong x); - ACE_CDR::Boolean write_longlong (const ACE_CDR::LongLong &x); - ACE_CDR::Boolean write_ulonglong (const ACE_CDR::ULongLong &x); - ACE_CDR::Boolean write_float (ACE_CDR::Float x); - ACE_CDR::Boolean write_double (const ACE_CDR::Double &x); - ACE_CDR::Boolean write_longdouble (const ACE_CDR::LongDouble &x); - - /// For string we offer methods that accept a precomputed length. - ACE_CDR::Boolean write_string (const ACE_CDR::Char *x); - ACE_CDR::Boolean write_string (ACE_CDR::ULong len, - const ACE_CDR::Char *x); - ACE_CDR::Boolean write_string (const ACE_CString &x); - ACE_CDR::Boolean write_wstring (const ACE_CDR::WChar *x); - ACE_CDR::Boolean write_wstring (ACE_CDR::ULong length, - const ACE_CDR::WChar *x); - //@} - - /// @note the portion written starts at @a x and ends - /// at @a x + @a length. - /// The length is *NOT* stored into the CDR stream. - //@{ @name Array write operations - ACE_CDR::Boolean write_boolean_array (const ACE_CDR::Boolean *x, - ACE_CDR::ULong length); - ACE_CDR::Boolean write_char_array (const ACE_CDR::Char *x, - ACE_CDR::ULong length); - ACE_CDR::Boolean write_wchar_array (const ACE_CDR::WChar* x, - ACE_CDR::ULong length); - ACE_CDR::Boolean write_octet_array (const ACE_CDR::Octet* x, - ACE_CDR::ULong length); - ACE_CDR::Boolean write_short_array (const ACE_CDR::Short *x, - ACE_CDR::ULong length); - ACE_CDR::Boolean write_ushort_array (const ACE_CDR::UShort *x, - ACE_CDR::ULong length); - ACE_CDR::Boolean write_long_array (const ACE_CDR::Long *x, - ACE_CDR::ULong length); - ACE_CDR::Boolean write_ulong_array (const ACE_CDR::ULong *x, - ACE_CDR::ULong length); - ACE_CDR::Boolean write_longlong_array (const ACE_CDR::LongLong* x, - ACE_CDR::ULong length); - ACE_CDR::Boolean write_ulonglong_array (const ACE_CDR::ULongLong *x, - ACE_CDR::ULong length); - ACE_CDR::Boolean write_float_array (const ACE_CDR::Float *x, - ACE_CDR::ULong length); - ACE_CDR::Boolean write_double_array (const ACE_CDR::Double *x, - ACE_CDR::ULong length); - ACE_CDR::Boolean write_longdouble_array (const ACE_CDR::LongDouble* x, - ACE_CDR::ULong length); - - /// Write an octet array contained inside a MB, this can be optimized - /// to minimize copies. - ACE_CDR::Boolean write_octet_array_mb (const ACE_Message_Block* mb); - //@} - - /** - * @{ @name Placeholder/replace operations - * Facilitates writing a placeholder into a CDR stream to be replaced - * later with a different value. - * - * @note An example use for this facility is: - * @code - ACE_OutputCDR strm; - ... // insert values... - char *pos = strm.write_long_placeholder (); - ... // insert more values - ACE_CDR::Long real_val; // Somehow assign the "correct" value - strm.replace (real_val, pos); // Replace earlier placeholder - @endcode - */ - - /** - * Write a placeholder into the stream. The placeholder's pointer - * is returned so it may later be passed as the @a loc argument to - * replace (). - * These methods align the stream's write pointer properly prior to - * writing the placeholder. - * - * @retval Pointer to the placeholder; 0 if there is not enough space - * in the stream and memory could not be allocated. - */ - char* write_long_placeholder (void); - char* write_short_placeholder (void); - - /** - * Writes a new value into a specific location. This is commonly - * used to update a prior "placeholder" location in the stream. - * The specified location is assumed to have proper CDR alignment for the - * type to insert. This requirement is satisfied by using one of the - * placeholder-writing methods to align the stream for the anticipated - * value and obtain the correct location. - * Treatment of @a x with repect to byte swapping is the same as for when - * any value is inserted. - * - * @param x The value to insert into the specified location. - * @param loc The location at which to insert @a x. @a loc must be a valid - * position within the stream's current set of message blocks. - * - * @sa write_long_placeholder(), write_short_placeholder () - */ - ACE_CDR::Boolean replace (ACE_CDR::Long x, char* loc); - ACE_CDR::Boolean replace (ACE_CDR::Short x, char* loc); - //@} - - /** - * Return 0 on failure and 1 on success. - */ - //@{ @name Append contents of own CDR stream to another - ACE_CDR::Boolean append_boolean (ACE_InputCDR &); - ACE_CDR::Boolean append_char (ACE_InputCDR &); - ACE_CDR::Boolean append_wchar (ACE_InputCDR &); - ACE_CDR::Boolean append_octet (ACE_InputCDR &); - ACE_CDR::Boolean append_short (ACE_InputCDR &); - ACE_CDR::Boolean append_ushort (ACE_InputCDR &); - ACE_CDR::Boolean append_long (ACE_InputCDR &); - ACE_CDR::Boolean append_ulong (ACE_InputCDR &); - ACE_CDR::Boolean append_longlong (ACE_InputCDR &); - ACE_CDR::Boolean append_ulonglong (ACE_InputCDR &); - ACE_CDR::Boolean append_float (ACE_InputCDR &); - ACE_CDR::Boolean append_double (ACE_InputCDR &); - ACE_CDR::Boolean append_longdouble (ACE_InputCDR &); - - ACE_CDR::Boolean append_wstring (ACE_InputCDR &); - ACE_CDR::Boolean append_string (ACE_InputCDR &); - //@} - - /// Returns @c false if an error has ocurred. - /** - * @note The only expected error is to run out of memory. - */ - bool good_bit (void) const; - - /// Reuse the CDR stream to write on the old buffer. - void reset (void); - - /// Add the length of each message block in the chain. - size_t total_length (void) const; - - /** - * Return the start of the message block chain for this CDR stream. - * @note The complete CDR stream is represented by a chain of - * message blocks. - */ - const ACE_Message_Block *begin (void) const; - - /// Return the last message in the chain that is is use. - const ACE_Message_Block *end (void) const; - - /// Return the message block in chain. - const ACE_Message_Block *current (void) const; - - /// Replace the message block chain with a single message block. - /** - * Upon successful completion, there will be a single message block - * containing the data from the complete message block chain. - * - * @note The only expected error is to run out of memory. - */ - int consolidate (void); - - /** - * Access the underlying buffer (read only). @note This - * method only returns a pointer to the first block in the - * chain. - */ - const char *buffer (void) const; - - /** - * Return the size of first message block in the block chain. @note This - * method only returns information about the first block in the - * chain. - */ - size_t length (void) const; - - /** - * Utility function to allow the user more flexibility. - * Pads the stream up to the nearest -byte boundary. - * Argument MUST be a power of 2. - * Returns 0 on success and -1 on failure. - */ - int align_write_ptr (size_t alignment); - - /// Access the codeset translators. They can be null! - ACE_Char_Codeset_Translator *char_translator (void) const; - ACE_WChar_Codeset_Translator *wchar_translator (void) const; - - /// Set the char codeset translator. - void char_translator (ACE_Char_Codeset_Translator *); - /// Set the wchar codeset translator. - void wchar_translator (ACE_WChar_Codeset_Translator *); - - /// set the global size of serialized wchars. This may be different - /// than the size of a wchar_t. - static void wchar_maxbytes (size_t max_bytes); - - /// access the serialized size of wchars. - static size_t wchar_maxbytes (void); - - /** - * Return alignment of the wr_ptr(), with respect to the start of - * the CDR stream. This is not the same as the alignment of - * current->wr_ptr()! - */ - size_t current_alignment (void) const; - - void current_alignment (size_t current_alignment); - - /** - * Returns (in @a buf) the next position in the buffer aligned to - * @a size, it advances the Message_Block wr_ptr past the data - * (i.e., @a buf + @a size). If necessary it grows the Message_Block - * buffer. Sets the good_bit to false and returns a -1 on failure. - */ - int adjust (size_t size, - char *&buf); - - /// As above, but now the size and alignment requirements may be - /// different. - int adjust (size_t size, - size_t align, - char *&buf); - - /// Returns true if this stream is writing in non-native byte order - /// and false otherwise. For example, it would be true if either - /// ACE_ENABLE_SWAP_ON_WRITE is defined or a specific byte order was - /// specified for this stream. - bool do_byte_swap (void) const; - - /// Returns the byte order this stream is marshaling data in. Will be one - /// of the values in ACE_CDR::Byte_Order. - int byte_order (void) const; - - /// For use by a gateway, which creates the output stream for the - /// reply to the client in its native byte order, but which must - /// send the reply in the byte order of the target's reply to the - /// gateway. - void reset_byte_order (int byte_order); - - /// set GIOP version info - void set_version (ACE_CDR::Octet major, ACE_CDR::Octet minor); - - /// Set the underlying GIOP version.. - void get_version (ACE_CDR::Octet &major, ACE_CDR::Octet &minor); - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - /// Register and unregister our buffer size monitor. - void register_monitor (const char* id); - void unregister_monitor (void); -#endif /* ACE_HAS_MONITOR_POINTS==1 */ - -private: - - // Find the message block in the chain of message blocks - // that the provide location locates. - ACE_Message_Block* find (char* loc); - - /// disallow copying... - ACE_OutputCDR (const ACE_OutputCDR& rhs); - ACE_OutputCDR& operator= (const ACE_OutputCDR& rhs); - - ACE_CDR::Boolean write_1 (const ACE_CDR::Octet *x); - ACE_CDR::Boolean write_2 (const ACE_CDR::UShort *x); - ACE_CDR::Boolean write_4 (const ACE_CDR::ULong *x); - ACE_CDR::Boolean write_8 (const ACE_CDR::ULongLong *x); - ACE_CDR::Boolean write_16 (const ACE_CDR::LongDouble *x); - - /** - * write an array of @a length elements, each of @a size bytes and the - * start aligned at a multiple of . The elements are assumed - * to be packed with the right alignment restrictions. It is mostly - * designed for buffers of the basic types. - * - * This operation uses ; as explained above it is expected - * that using assignment is faster that for one element, - * but for several elements should be more efficient, it - * could be interesting to find the break even point and optimize - * for that case, but that would be too platform dependent. - */ - ACE_CDR::Boolean write_array (const void *x, - size_t size, - size_t align, - ACE_CDR::ULong length); - - - ACE_CDR::Boolean write_wchar_array_i (const ACE_CDR::WChar* x, - ACE_CDR::ULong length); - - - /** - * Grow the CDR stream. When it returns @a buf contains a pointer to - * memory in the CDR stream, with at least @a size bytes ahead of it - * and aligned to an boundary. It moved the to . - */ - int grow_and_adjust (size_t size, - size_t align, - char *&buf); - -private: - /// The start of the chain of message blocks. - ACE_Message_Block start_; - - /// The current block in the chain where we are writing. - ACE_Message_Block *current_; - -#if !defined (ACE_LACKS_CDR_ALIGNMENT) - /** - * The current alignment as measured from the start of the buffer. - * Usually this coincides with the alignment of the buffer in - * memory, but, when we chain another buffer this "quasi invariant" - * is broken. - * The current_alignment is used to readjust the buffer following - * the stolen message block. - */ - size_t current_alignment_; -#endif /* ACE_LACKS_CDR_ALIGNMENT */ - - /** - * Is the current block writable. When we steal a buffer from the - * user and just chain it into the message block we are not supposed - * to write on it, even if it is past the start and end of the - * buffer. - */ - bool current_is_writable_; - - /** - * If not zero swap bytes at writing so the created CDR stream byte - * order does *not* match the machine byte order. The motivation - * for such a beast is that in some setting a few (fast) machines - * can be serving hundreds of slow machines with the opposite byte - * order, so it makes sense (as a load balancing device) to put the - * responsibility in the writers. THIS IS NOT A STANDARD IN CORBA, - * USE AT YOUR OWN RISK - */ - bool do_byte_swap_; - - /// Set to false when an error ocurrs. - bool good_bit_; - - /// Break-even point for copying. - size_t const memcpy_tradeoff_; - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - ACE::Monitor_Control::Size_Monitor *monitor_; -#endif /* ACE_HAS_MONITOR_POINTS==1 */ - -protected: - /// GIOP version information - ACE_CDR::Octet major_version_; - ACE_CDR::Octet minor_version_; - - /// If not nil, invoke for translation of character and string data. - ACE_Char_Codeset_Translator *char_translator_; - ACE_WChar_Codeset_Translator *wchar_translator_; - - /** - * Some wide char codesets may be defined with a maximum number - * of bytes that is smaller than the size of a wchar_t. This means - * that the CDR cannot simply memcpy a block of wchars to and from - * the stream, but must instead realign the bytes appropriately. - * In cases when wchar i/o is not allowed, such as with GIOP 1.0, - * or not having a native wchar codeset defined, the maxbytes is - * set to zero, indicating no wchar data is allowed. - */ - static size_t wchar_maxbytes_; -}; - - -// **************************************************************** - -/** - * @class ACE_InputCDR - * - * @brief A CDR stream for demarshalling CDR-encoded data. - * - * This class is based on the the CORBA spec for Java (98-02-29), - * java class omg.org.CORBA.portable.InputStream. It diverts in a - * few ways: - * @li Operations to retrieve basic types take parameters by - * reference. - * @li Operations taking arrays don't have offsets, because in C++ - * it is easier to describe an array starting from x+offset. - * @li Operations return an error status, because exceptions are - * not widely available in C++ (yet). - */ -class ACE_Export ACE_InputCDR -{ -public: - // The translators need privileged access to efficiently demarshal - // arrays and such. - friend class ACE_Char_Codeset_Translator; - friend class ACE_WChar_Codeset_Translator; - - /** - * Create an input stream from an arbitrary buffer. The buffer must - * be properly aligned because this contructor will *not* work if - * the buffer is aligned unproperly.See ACE_ptr_align_binary() for - * instructions on how to align a pointer properly and use - * ACE_CDR::MAX_ALIGNMENT for the correct alignment. - */ - ACE_InputCDR (const char *buf, - size_t bufsiz, - int byte_order = ACE_CDR::BYTE_ORDER_NATIVE, - ACE_CDR::Octet major_version = ACE_CDR_GIOP_MAJOR_VERSION, - ACE_CDR::Octet minor_version = ACE_CDR_GIOP_MINOR_VERSION); - - /// Create an empty input stream. The caller is responsible for - /// putting the right data and providing the right alignment. - ACE_InputCDR (size_t bufsiz, - int byte_order = ACE_CDR::BYTE_ORDER_NATIVE, - ACE_CDR::Octet major_version = ACE_CDR_GIOP_MAJOR_VERSION, - ACE_CDR::Octet minor_version = ACE_CDR_GIOP_MINOR_VERSION); - - /// Create an input stream from an ACE_Message_Block - /** - * The alignment of the @a data block is carried into the new - * ACE_InputCDR object. This constructor either increments the - * @a data reference count, or copies the data (if it's a compound - * message block) so the caller can release the block immediately - * upon return. - */ - ACE_InputCDR (const ACE_Message_Block *data, - int byte_order = ACE_CDR::BYTE_ORDER_NATIVE, - ACE_CDR::Octet major_version = ACE_CDR_GIOP_MAJOR_VERSION, - ACE_CDR::Octet minor_version = ACE_CDR_GIOP_MINOR_VERSION, - ACE_Lock* lock = 0); - - /// Create an input stream from an ACE_Data_Block. The - /// indicates whether the @a data can be deleted by the CDR stream - /// or not - ACE_InputCDR (ACE_Data_Block *data, - ACE_Message_Block::Message_Flags flag = 0, - int byte_order = ACE_CDR::BYTE_ORDER_NATIVE, - ACE_CDR::Octet major_version = ACE_CDR_GIOP_MAJOR_VERSION, - ACE_CDR::Octet minor_version = ACE_CDR_GIOP_MINOR_VERSION); - - /// Create an input stream from an ACE_Data_Block. It also sets the - /// read and write pointers at the desired positions. This would be - /// helpful if the applications desires to create a new CDR stream - /// from a semi-processed datablock. - ACE_InputCDR (ACE_Data_Block *data, - ACE_Message_Block::Message_Flags flag, - size_t read_pointer_position, - size_t write_pointer_position, - int byte_order = ACE_CDR::BYTE_ORDER_NATIVE, - ACE_CDR::Octet major_version = ACE_CDR_GIOP_MAJOR_VERSION, - ACE_CDR::Octet minor_version = ACE_CDR_GIOP_MINOR_VERSION); - - /** - * These make a copy of the current stream state, but do not copy - * the internal buffer, so the same stream can be read multiple - * times efficiently. - */ - ACE_InputCDR (const ACE_InputCDR& rhs); - - ACE_InputCDR& operator= (const ACE_InputCDR& rhs); - - /// When interpreting indirected TypeCodes it is useful to make a - /// "copy" of the stream starting in the new position. - ACE_InputCDR (const ACE_InputCDR& rhs, - size_t size, - ACE_CDR::Long offset); - - /// This creates an encapsulated stream, the first byte must be (per - /// the spec) the byte order of the encapsulation. - ACE_InputCDR (const ACE_InputCDR& rhs, - size_t size); - - /// Create an input CDR from an output CDR. - ACE_InputCDR (const ACE_OutputCDR& rhs, - ACE_Allocator* buffer_allocator = 0, - ACE_Allocator* data_block_allocator = 0, - ACE_Allocator* message_block_allocator = 0); - - /// Helper class to transfer the contents from one input CDR to - /// another without requiring any extra memory allocations, data - /// copies or too many temporaries. - struct ACE_Export Transfer_Contents - { - Transfer_Contents (ACE_InputCDR &rhs); - - ACE_InputCDR &rhs_; - }; - /// Transfer the contents from to a new CDR - ACE_InputCDR (Transfer_Contents rhs); - - /// Destructor - ~ACE_InputCDR (void); - - /// Disambiguate overloading when extracting octets, chars, - /// booleans, and bounded strings - //@{ @name Helper classes - - struct ACE_Export to_boolean - { - explicit to_boolean (ACE_CDR::Boolean &b); - ACE_CDR::Boolean &ref_; - }; - - struct ACE_Export to_char - { - explicit to_char (ACE_CDR::Char &c); - ACE_CDR::Char &ref_; - }; - - struct ACE_Export to_wchar - { - explicit to_wchar (ACE_CDR::WChar &wc); - ACE_CDR::WChar &ref_; - }; - - struct ACE_Export to_octet - { - explicit to_octet (ACE_CDR::Octet &o); - ACE_CDR::Octet &ref_; - }; - - struct ACE_Export to_string - { - /** - * @deprecated The constructor taking a non-const string is now - * deprecated (C++ mapping 00-01-02), but we keep it - * around for backward compatibility. - */ - to_string (ACE_CDR::Char *&s, - ACE_CDR::ULong b); - to_string (const ACE_CDR::Char *&s, - ACE_CDR::ULong b); - const ACE_CDR::Char *&val_; - ACE_CDR::ULong bound_; - }; - - struct ACE_Export to_wstring - { - /// The constructor taking a non-const wstring is - /// now deprecated (C++ mapping 00-01-02), but we - /// keep it around for backward compatibility. - to_wstring (ACE_CDR::WChar *&ws, - ACE_CDR::ULong b); - to_wstring (const ACE_CDR::WChar *&ws, - ACE_CDR::ULong b); - const ACE_CDR::WChar *&val_; - ACE_CDR::ULong bound_; - }; - //@} - - /** - * Return @c false on failure and @c true on success. - */ - //@{ @name Read basic IDL types - ACE_CDR::Boolean read_boolean (ACE_CDR::Boolean& x); - ACE_CDR::Boolean read_char (ACE_CDR::Char &x); - ACE_CDR::Boolean read_wchar (ACE_CDR::WChar& x); - ACE_CDR::Boolean read_octet (ACE_CDR::Octet& x); - ACE_CDR::Boolean read_short (ACE_CDR::Short &x); - ACE_CDR::Boolean read_ushort (ACE_CDR::UShort &x); - ACE_CDR::Boolean read_long (ACE_CDR::Long &x); - ACE_CDR::Boolean read_ulong (ACE_CDR::ULong &x); - ACE_CDR::Boolean read_longlong (ACE_CDR::LongLong& x); - ACE_CDR::Boolean read_ulonglong (ACE_CDR::ULongLong& x); - ACE_CDR::Boolean read_float (ACE_CDR::Float &x); - ACE_CDR::Boolean read_double (ACE_CDR::Double &x); - ACE_CDR::Boolean read_longdouble (ACE_CDR::LongDouble &x); - - ACE_CDR::Boolean read_string (ACE_CDR::Char *&x); - ACE_CDR::Boolean read_string (ACE_CString &x); - ACE_CDR::Boolean read_wstring (ACE_CDR::WChar*& x); - //@} - - /** - * The buffer @a x must be large enough to contain @a length - * elements. - * Return @c false on failure and @c true on success. - */ - //@{ @name Read basic IDL types arrays - ACE_CDR::Boolean read_boolean_array (ACE_CDR::Boolean* x, - ACE_CDR::ULong length); - ACE_CDR::Boolean read_char_array (ACE_CDR::Char *x, - ACE_CDR::ULong length); - ACE_CDR::Boolean read_wchar_array (ACE_CDR::WChar* x, - ACE_CDR::ULong length); - ACE_CDR::Boolean read_octet_array (ACE_CDR::Octet* x, - ACE_CDR::ULong length); - ACE_CDR::Boolean read_short_array (ACE_CDR::Short *x, - ACE_CDR::ULong length); - ACE_CDR::Boolean read_ushort_array (ACE_CDR::UShort *x, - ACE_CDR::ULong length); - ACE_CDR::Boolean read_long_array (ACE_CDR::Long *x, - ACE_CDR::ULong length); - ACE_CDR::Boolean read_ulong_array (ACE_CDR::ULong *x, - ACE_CDR::ULong length); - ACE_CDR::Boolean read_longlong_array (ACE_CDR::LongLong* x, - ACE_CDR::ULong length); - ACE_CDR::Boolean read_ulonglong_array (ACE_CDR::ULongLong* x, - ACE_CDR::ULong length); - ACE_CDR::Boolean read_float_array (ACE_CDR::Float *x, - ACE_CDR::ULong length); - ACE_CDR::Boolean read_double_array (ACE_CDR::Double *x, - ACE_CDR::ULong length); - ACE_CDR::Boolean read_longdouble_array (ACE_CDR::LongDouble* x, - ACE_CDR::ULong length); - //@} - - /** - * Return @c false on failure and @c true on success. - */ - //@{ @name Skip elements - ACE_CDR::Boolean skip_boolean (void); - ACE_CDR::Boolean skip_char (void); - ACE_CDR::Boolean skip_wchar (void); - ACE_CDR::Boolean skip_octet (void); - ACE_CDR::Boolean skip_short (void); - ACE_CDR::Boolean skip_ushort (void); - ACE_CDR::Boolean skip_long (void); - ACE_CDR::Boolean skip_ulong (void); - ACE_CDR::Boolean skip_longlong (void); - ACE_CDR::Boolean skip_ulonglong (void); - ACE_CDR::Boolean skip_float (void); - ACE_CDR::Boolean skip_double (void); - ACE_CDR::Boolean skip_longdouble (void); - //@} - - /** - * The next field must be a string, this method skips it. It is - * useful in parsing a TypeCode. - * @return @c false on failure and @c true on success. - */ - ACE_CDR::Boolean skip_wstring (void); - ACE_CDR::Boolean skip_string (void); - - /// Skip @a n bytes in the CDR stream. - /** - * @return @c false on failure and @c true on success. - */ - ACE_CDR::Boolean skip_bytes (size_t n); - - /// returns @c false if a problem has been detected. - bool good_bit (void) const; - - /** - * @return The start of the message block chain for this CDR - * stream. - * - * @note In the current implementation the chain has length 1, but - * we are planning to change that. - */ - const ACE_Message_Block* start (void) const; - - // = The following functions are useful to read the contents of the - // CDR stream from a socket or file. - - /** - * Grow the internal buffer, reset @c rd_ptr to the first byte in - * the new buffer that is properly aligned, and set @c wr_ptr to @c - * rd_ptr @c + @c newsize - */ - int grow (size_t newsize); - - /** - * After reading and partially parsing the contents the user can - * detect a change in the byte order, this method will let him/her - * change it. - */ - void reset_byte_order (int byte_order); - - /// Re-initialize the CDR stream, copying the contents of the chain - /// of message_blocks starting from @a data. - void reset (const ACE_Message_Block *data, - int byte_order); - - /// Steal the contents from the current CDR. - ACE_Message_Block *steal_contents (void); - - /// Steal the contents of @a cdr and make a shallow copy into this - /// stream. - void steal_from (ACE_InputCDR &cdr); - - /// Exchange data blocks with the caller of this method. The read - /// and write pointers are also exchanged. - /** - * @note We now do only with the start_ message block. - */ - void exchange_data_blocks (ACE_InputCDR &cdr); - - /// Copy the data portion from the @a cdr to this cdr and return the - /// data content (ie. the ACE_Data_Block) from this CDR to the - /// caller. - /** - * @note The caller is responsible for managing the memory of the - * returned ACE_Data_Block. - */ - ACE_Data_Block* clone_from (ACE_InputCDR &cdr); - - /// Re-initialize the CDR stream, forgetting about the old contents - /// of the stream and allocating a new buffer (from the allocators). - void reset_contents (void); - - /// Returns the current position for the @c rd_ptr. - char* rd_ptr (void); - - /// Returns the current position for the @c wr_ptr. - char* wr_ptr (void); - - /// Return how many bytes are left in the stream. - size_t length (void) const; - - /** - * Utility function to allow the user more flexibility. - * Skips up to the nearest @a alignment-byte boundary. - * Argument MUST be a power of 2. - * - * @return 0 on success and -1 on failure. - */ - int align_read_ptr (size_t alignment); - - /// If @c true then this stream is writing in non-native byte order. - /// This is only meaningful if ACE_ENABLE_SWAP_ON_WRITE is defined. - bool do_byte_swap (void) const; - - /// If @c do_byte_swap() returns @c false, this returns - /// ACE_CDR_BYTE_ORDER else it returns !ACE_CDR_BYTE_ORDER. - int byte_order (void) const; - - /// Access the codeset translators. They can be nil! - ACE_Char_Codeset_Translator *char_translator (void) const; - ACE_WChar_Codeset_Translator *wchar_translator (void) const; - - /// Set the codeset translators. - void char_translator (ACE_Char_Codeset_Translator *); - void wchar_translator (ACE_WChar_Codeset_Translator *); - - /** - * Returns (in @a buf) the next position in the buffer aligned to - * @a size. It advances the Message_Block @c rd_ptr past the data - * (i.e., @c buf @c + @c size). Sets the good_bit to @c false and - * returns a -1 on failure. - */ - int adjust (size_t size, - char *&buf); - - /// As above, but now the size and alignment requirements may be - /// different. - int adjust (size_t size, - size_t align, - char *&buf); - - /// Set the underlying GIOP version.. - void set_version (ACE_CDR::Octet major, ACE_CDR::Octet minor); - - /// Set the underlying GIOP version.. - void get_version (ACE_CDR::Octet &major, ACE_CDR::Octet &minor); - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - /// Register and unregister our buffer size monitor. - void register_monitor (const char* id); - void unregister_monitor (void); -#endif /* ACE_HAS_MONITOR_POINTS==1 */ - -protected: - - /// The start of the chain of message blocks, even though in the - /// current version the chain always has length 1. - ACE_Message_Block start_; - - /// The CDR stream byte order does not match the one on the machine, - /// swapping is needed while reading. - bool do_byte_swap_; - - /// set to @c false when an error occurs. - bool good_bit_; - - /// The GIOP versions for this stream - ACE_CDR::Octet major_version_; - ACE_CDR::Octet minor_version_; - - /// If not nil, invoke for translation of character and string data. - ACE_Char_Codeset_Translator *char_translator_; - ACE_WChar_Codeset_Translator *wchar_translator_; - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - ACE::Monitor_Control::Size_Monitor *monitor_; -#endif /* ACE_HAS_MONITOR_POINTS==1 */ - -private: - - ACE_CDR::Boolean read_1 (ACE_CDR::Octet *x); - ACE_CDR::Boolean read_2 (ACE_CDR::UShort *x); - ACE_CDR::Boolean read_4 (ACE_CDR::ULong *x); - ACE_CDR::Boolean read_8 (ACE_CDR::ULongLong *x); - ACE_CDR::Boolean read_16 (ACE_CDR::LongDouble *x); - - // Several types can be read using the same routines, since TAO - // tries to use native types with known size for each CORBA type. - // We could use void* or char* to make the interface more - // consistent, but using native types let us exploit the strict - // alignment requirements of CDR streams and implement the - // operations using asignment. - - /** - * Read an array of @a length elements, each of @a size bytes and the - * start aligned at a multiple of . The elements are assumed - * to be packed with the right alignment restrictions. It is mostly - * designed for buffers of the basic types. - * - * This operation uses ; as explained above it is expected - * that using assignment is faster that for one element, - * but for several elements should be more efficient, it - * could be interesting to find the break even point and optimize - * for that case, but that would be too platform dependent. - */ - ACE_CDR::Boolean read_array (void* x, - size_t size, - size_t align, - ACE_CDR::ULong length); - - /** - * On those occasions when the native codeset for wchar is smaller than - * the size of a wchar_t, such as using UTF-16 with a 4-byte wchar_t, a - * special form of reading the array is needed. Actually, this should be - * a default translator. - */ - ACE_CDR::Boolean read_wchar_array_i (ACE_CDR::WChar * x, - ACE_CDR::ULong length); - - /// Move the rd_ptr ahead by @a offset bytes. - void rd_ptr (size_t offset); - - /// Points to the continuation field of the current message block. - char* end (void); -}; - -// **************************************************************** - -/** - * @class ACE_Char_Codeset_Translator - * - * @brief Codeset translation routines common to both Output and Input - * CDR streams. - * - * This class is a base class for defining codeset translation - * routines to handle the character set translations required by - * both CDR Input streams and CDR Output streams. - * - * Translators are reference counted. This allows for stateful as well - * as stateless translators. Stateless translators will be allocated - * once whereas CDR Streams own their own copy of a stateful translator. - */ -class ACE_Export ACE_Char_Codeset_Translator -{ -public: - virtual ~ACE_Char_Codeset_Translator (); - - /// Read a single character from the stream, converting from the - /// stream codeset to the native codeset - virtual ACE_CDR::Boolean read_char (ACE_InputCDR&, - ACE_CDR::Char&) = 0; - - /// Read a string from the stream, including the length, converting - /// the characters from the stream codeset to the native codeset - virtual ACE_CDR::Boolean read_string (ACE_InputCDR&, - ACE_CDR::Char *&) = 0; - - /// Read an array of characters from the stream, converting the - /// characters from the stream codeset to the native codeset. - virtual ACE_CDR::Boolean read_char_array (ACE_InputCDR&, - ACE_CDR::Char*, - ACE_CDR::ULong) = 0; - - /// Write a single character to the stream, converting from the - /// native codeset to the stream codeset - virtual ACE_CDR::Boolean write_char (ACE_OutputCDR&, - ACE_CDR::Char) = 0; - - /// Write a string to the stream, including the length, converting - /// from the native codeset to the stream codeset - virtual ACE_CDR::Boolean write_string (ACE_OutputCDR&, - ACE_CDR::ULong, - const ACE_CDR::Char*) = 0; - - /// Write an array of characters to the stream, converting from the - /// native codeset to the stream codeset - virtual ACE_CDR::Boolean write_char_array (ACE_OutputCDR&, - const ACE_CDR::Char*, - ACE_CDR::ULong) = 0; - - virtual ACE_CDR::ULong ncs () = 0; - virtual ACE_CDR::ULong tcs () = 0; -protected: - /// Children have access to low-level routines because they cannot - /// use read_char or something similar (it would recurse). - ACE_CDR::Boolean read_1 (ACE_InputCDR& input, - ACE_CDR::Octet *x); - ACE_CDR::Boolean write_1 (ACE_OutputCDR& output, - const ACE_CDR::Octet *x); - - /// Efficiently read @a length elements of size @a size each from - /// into ; the data must be aligned to . - ACE_CDR::Boolean read_array (ACE_InputCDR& input, - void* x, - size_t size, - size_t align, - ACE_CDR::ULong length); - - /** - * Efficiently write @a length elements of size @a size from into - * . Before inserting the elements enough padding is added - * to ensure that the elements will be aligned to in the - * stream. - */ - ACE_CDR::Boolean write_array (ACE_OutputCDR& output, - const void *x, - size_t size, - size_t align, - ACE_CDR::ULong length); - - /** - * Exposes the stream implementation of , this is useful in - * many cases to minimize memory allocations during marshaling. - * On success @a buf will contain a contiguous area in the CDR stream - * that can hold @a size bytes aligned to . - * Results - */ - int adjust (ACE_OutputCDR& out, - size_t size, - size_t align, - char *&buf); - - /// Used by derived classes to set errors in the CDR stream. - void good_bit (ACE_OutputCDR& out, bool bit); - - /// Obtain the CDR Stream's major & minor version values. - ACE_CDR::Octet major_version (ACE_InputCDR& input); - ACE_CDR::Octet minor_version (ACE_InputCDR& input); - ACE_CDR::Octet major_version (ACE_OutputCDR& output); - ACE_CDR::Octet minor_version (ACE_OutputCDR& output); -}; - -// **************************************************************** - -/** - * @class ACE_WChar_Codeset_Translator - * - * @brief Codeset translation routines common to both Output and Input - * CDR streams. - * - * This class is a base class for defining codeset translation - * routines to handle the character set translations required by - * both CDR Input streams and CDR Output streams. - */ -class ACE_Export ACE_WChar_Codeset_Translator -{ -public: - virtual ~ACE_WChar_Codeset_Translator (); - - virtual ACE_CDR::Boolean read_wchar (ACE_InputCDR&, - ACE_CDR::WChar&) = 0; - virtual ACE_CDR::Boolean read_wstring (ACE_InputCDR&, - ACE_CDR::WChar *&) = 0; - virtual ACE_CDR::Boolean read_wchar_array (ACE_InputCDR&, - ACE_CDR::WChar*, - ACE_CDR::ULong) = 0; - virtual ACE_CDR::Boolean write_wchar (ACE_OutputCDR&, - ACE_CDR::WChar) = 0; - virtual ACE_CDR::Boolean write_wstring (ACE_OutputCDR&, - ACE_CDR::ULong, - const ACE_CDR::WChar*) = 0; - virtual ACE_CDR::Boolean write_wchar_array (ACE_OutputCDR&, - const ACE_CDR::WChar*, - ACE_CDR::ULong) = 0; - - virtual ACE_CDR::ULong ncs () = 0; - virtual ACE_CDR::ULong tcs () = 0; -protected: - /// Children have access to low-level routines because they cannot - /// use read_char or something similar (it would recurse). - ACE_CDR::Boolean read_1 (ACE_InputCDR& input, - ACE_CDR::Octet *x); - ACE_CDR::Boolean read_2 (ACE_InputCDR& input, - ACE_CDR::UShort *x); - ACE_CDR::Boolean read_4 (ACE_InputCDR& input, - ACE_CDR::ULong *x); - ACE_CDR::Boolean write_1 (ACE_OutputCDR& output, - const ACE_CDR::Octet *x); - ACE_CDR::Boolean write_2 (ACE_OutputCDR& output, - const ACE_CDR::UShort *x); - ACE_CDR::Boolean write_4 (ACE_OutputCDR& output, - const ACE_CDR::ULong *x); - - /// Efficiently read @a length elements of size @a size each from - /// into ; the data must be aligned to . - ACE_CDR::Boolean read_array (ACE_InputCDR& input, - void* x, - size_t size, - size_t align, - ACE_CDR::ULong length); - - /** - * Efficiently write @a length elements of size @a size from into - * . Before inserting the elements enough padding is added - * to ensure that the elements will be aligned to in the - * stream. - */ - ACE_CDR::Boolean write_array (ACE_OutputCDR& output, - const void *x, - size_t size, - size_t align, - ACE_CDR::ULong length); - - /** - * Exposes the stream implementation of , this is useful in - * many cases to minimize memory allocations during marshaling. - * On success @a buf will contain a contiguous area in the CDR stream - * that can hold @a size bytes aligned to . - * Results - */ - int adjust (ACE_OutputCDR& out, - size_t size, - size_t align, - char *&buf); - - /// Used by derived classes to set errors in the CDR stream. - void good_bit (ACE_OutputCDR& out, bool bit); - - /// Obtain the CDR Stream's major & minor version values. - ACE_CDR::Octet major_version (ACE_InputCDR& input); - ACE_CDR::Octet minor_version (ACE_InputCDR& input); - ACE_CDR::Octet major_version (ACE_OutputCDR& output); - ACE_CDR::Octet minor_version (ACE_OutputCDR& output); - -}; - -// @@ These operators should not be inlined since they force SString.h -// to be included in this header. -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, - const ACE_CString &x); - -extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, - ACE_CString &x); - - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -# include "ace/CDR_Stream.inl" -#else /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Not used by CORBA or TAO -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, - ACE_CDR::Char x); -// CDR output operators for primitive types - -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, - ACE_CDR::Short x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, - ACE_CDR::UShort x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, - ACE_CDR::Long x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, - ACE_CDR::ULong x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, - ACE_CDR::LongLong x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, - ACE_CDR::ULongLong x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR& os, - ACE_CDR::LongDouble x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, - ACE_CDR::Float x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, - ACE_CDR::Double x); - -// CDR output operator from helper classes - -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, - ACE_OutputCDR::from_boolean x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, - ACE_OutputCDR::from_char x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, - ACE_OutputCDR::from_wchar x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, - ACE_OutputCDR::from_octet x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, - ACE_OutputCDR::from_string x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, - ACE_OutputCDR::from_wstring x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, - const ACE_CDR::Char* x); -extern ACE_Export ACE_CDR::Boolean operator<< (ACE_OutputCDR &os, - const ACE_CDR::WChar* x); - -// Not used by CORBA or TAO -extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, - ACE_CDR::Char &x); -// CDR input operators for primitive types - -extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, - ACE_CDR::Short &x); -extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, - ACE_CDR::UShort &x); -extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, - ACE_CDR::Long &x); -extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, - ACE_CDR::ULong &x); -extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, - ACE_CDR::LongLong &x); -extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, - ACE_CDR::ULongLong &x); -extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, - ACE_CDR::LongDouble &x); -extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, - ACE_CDR::Float &x); -extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, - ACE_CDR::Double &x); - -// CDR input operator from helper classes - -extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, - ACE_InputCDR::to_boolean x); -extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, - ACE_InputCDR::to_char x); -extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, - ACE_InputCDR::to_wchar x); -extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, - ACE_InputCDR::to_octet x); -extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, - ACE_InputCDR::to_string x); -extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, - ACE_InputCDR::to_wstring x); -extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, - ACE_CDR::Char*& x); -extern ACE_Export ACE_CDR::Boolean operator>> (ACE_InputCDR &is, - ACE_CDR::WChar*& x); - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* __ACE_INLINE__ */ - -#if defined (GEN_OSTREAM_OPS) - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// ostream insertion operators for debugging code generated from IDL. All -// but these below are either in generated code itself or are unambiguous -// primitive types. - -ACE_Export std::ostream& operator<< (std::ostream &os, - ACE_OutputCDR::from_boolean x); - -ACE_Export std::ostream& operator<< (std::ostream &os, - ACE_OutputCDR::from_char x); - -ACE_Export std::ostream& operator<< (std::ostream &os, - ACE_OutputCDR::from_wchar x); - -ACE_Export std::ostream& operator<< (std::ostream &os, - ACE_OutputCDR::from_octet x); - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* GEN_OSTREAM_OPS */ - -#include /**/ "ace/post.h" - -#endif /* ACE_CDR_STREAM_H */ diff --git a/externals/ace/CDR_Stream.inl b/externals/ace/CDR_Stream.inl deleted file mode 100644 index 2be60c154dd..00000000000 --- a/externals/ace/CDR_Stream.inl +++ /dev/null @@ -1,1727 +0,0 @@ -// -*- C++ -*- -// -// $Id: CDR_Stream.inl 84206 2009-01-21 02:49:26Z schmidt $ - -#include "ace/OS_NS_string.h" -#include "ace/OS_Memory.h" - -// **************************************************************** - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// implementing the special types -ACE_INLINE -ACE_OutputCDR::from_boolean::from_boolean (ACE_CDR::Boolean b) - : val_ (b) -{ -} - -ACE_INLINE -ACE_InputCDR::to_boolean::to_boolean (ACE_CDR::Boolean &b) - : ref_ (b) -{ -} - -ACE_INLINE -ACE_OutputCDR::from_octet::from_octet (ACE_CDR::Octet o) - : val_ (o) -{ -} - -ACE_INLINE -ACE_InputCDR::to_octet::to_octet (ACE_CDR::Octet &o) - : ref_ (o) -{ -} - -ACE_INLINE -ACE_OutputCDR::from_char::from_char (ACE_CDR::Char c) - : val_ (c) -{ -} - -ACE_INLINE -ACE_InputCDR::to_char::to_char (ACE_CDR::Char &c) - : ref_ (c) -{ -} - -ACE_INLINE -ACE_OutputCDR::from_wchar::from_wchar (ACE_CDR::WChar wc) - : val_ (wc) -{ -} - -ACE_INLINE -ACE_InputCDR::to_wchar::to_wchar (ACE_CDR::WChar &wc) - : ref_ (wc) -{ -} - -ACE_INLINE -ACE_OutputCDR::from_string::from_string (ACE_CDR::Char *s, - ACE_CDR::ULong b, - ACE_CDR::Boolean nocopy) - : val_ (s), - bound_ (b), - nocopy_ (nocopy) -{ -} - -ACE_INLINE -ACE_OutputCDR::from_string::from_string (const ACE_CDR::Char *s, - ACE_CDR::ULong b, - ACE_CDR::Boolean nocopy) - : val_ (const_cast (s)), - bound_ (b), - nocopy_ (nocopy) -{ -} - -ACE_INLINE -ACE_InputCDR::to_string::to_string (ACE_CDR::Char *&s, - ACE_CDR::ULong b) - : val_ (const_cast (s)), - bound_ (b) -{ -} - -ACE_INLINE -ACE_InputCDR::to_string::to_string (const ACE_CDR::Char *&s, - ACE_CDR::ULong b) - : val_ (s), - bound_ (b) -{ -} - -ACE_INLINE -ACE_OutputCDR::from_wstring::from_wstring (ACE_CDR::WChar *ws, - ACE_CDR::ULong b, - ACE_CDR::Boolean nocopy) - : val_ (ws), - bound_ (b), - nocopy_ (nocopy) -{ -} - -ACE_INLINE -ACE_OutputCDR::from_wstring::from_wstring (const ACE_CDR::WChar *ws, - ACE_CDR::ULong b, - ACE_CDR::Boolean nocopy) - : val_ (const_cast (ws)), - bound_ (b), - nocopy_ (nocopy) -{ -} - -ACE_INLINE -ACE_InputCDR::to_wstring::to_wstring (ACE_CDR::WChar *&ws, - ACE_CDR::ULong b) - : val_ (const_cast (ws)), - bound_ (b) -{ -} - -ACE_INLINE -ACE_InputCDR::to_wstring::to_wstring (const ACE_CDR::WChar *&ws, - ACE_CDR::ULong b) - : val_ (ws), - bound_ (b) -{ -} - -ACE_INLINE -ACE_InputCDR::Transfer_Contents::Transfer_Contents (ACE_InputCDR &rhs) - : rhs_ (rhs) -{ -} - -// **************************************************************** - -ACE_INLINE -ACE_OutputCDR::~ACE_OutputCDR (void) -{ - if (this->start_.cont () != 0) - { - ACE_Message_Block::release (this->start_.cont ()); - this->start_.cont (0); - } - - this->current_ = 0; - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - this->monitor_->remove_ref (); -#endif /* ACE_HAS_MONITOR_POINTS==1 */ -} - -ACE_INLINE void -ACE_OutputCDR::reset (void) -{ - this->current_ = &this->start_; - this->current_is_writable_ = true; - ACE_CDR::mb_align (&this->start_); - -#if !defined (ACE_LACKS_CDR_ALIGNMENT) - this->current_alignment_ = 0; -#endif /* ACE_LACKS_CDR_ALIGNMENT */ - - // It is tempting not to remove the memory, but we need to do so to - // release any potential user buffers chained in the continuation - // field. - - ACE_Message_Block * const cont = this->start_.cont (); - if (cont) - { - ACE_Message_Block::release (cont); - this->start_.cont (0); - } - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - this->monitor_->receive (this->start_.total_size ()); -#endif /* ACE_HAS_MONITOR_POINTS==1 */ -} - -// Encode the CDR stream. - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::write_octet (ACE_CDR::Octet x) -{ - return this->write_1 (&x); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::write_boolean (ACE_CDR::Boolean x) -{ - return - static_cast ( - this->write_octet ( - x - ? static_cast (1) - : static_cast (0))); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::write_char (ACE_CDR::Char x) -{ - if (this->char_translator_ == 0) - { - ACE_CDR::Octet temp = static_cast (x); - return this->write_1 (&temp); - } - return this->char_translator_->write_char (*this, x); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::write_short (ACE_CDR::Short x) -{ - ACE_CDR::UShort temp = static_cast (x); - return this->write_2 (&temp); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::write_ushort (ACE_CDR::UShort x) -{ - return this->write_2 (&x); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::write_long (ACE_CDR::Long x) -{ - ACE_CDR::ULong temp = static_cast (x); - return this->write_4 (&temp); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::write_ulong (ACE_CDR::ULong x) -{ - return this->write_4 (&x); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::write_longlong (const ACE_CDR::LongLong &x) -{ - void const * const temp = &x; - return this->write_8 (reinterpret_cast (temp)); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::write_ulonglong (const ACE_CDR::ULongLong &x) -{ - return this->write_8 (&x); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::write_float (ACE_CDR::Float x) -{ - void const * const temp = &x; - return this->write_4 (reinterpret_cast (temp)); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::write_double (const ACE_CDR::Double &x) -{ - void const * const temp = &x; - return this->write_8 (reinterpret_cast (temp)); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::write_longdouble (const ACE_CDR::LongDouble &x) -{ - return this->write_16 (&x); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::write_string (const ACE_CDR::Char *x) -{ - if (x) - { - ACE_CDR::ULong const len = - static_cast (ACE_OS::strlen (x)); - return this->write_string (len, x); - } - - return this->write_string (0, 0); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::write_wstring (const ACE_CDR::WChar *x) -{ - if (x) - { - ACE_CDR::ULong const len = - static_cast (ACE_OS::strlen (x)); - return this->write_wstring (len, x); - } - - return this->write_wstring (0, 0); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::write_char_array (const ACE_CDR::Char *x, - ACE_CDR::ULong length) -{ - if (this->char_translator_ == 0) - return this->write_array (x, - ACE_CDR::OCTET_SIZE, - ACE_CDR::OCTET_ALIGN, - length); - return this->char_translator_->write_char_array (*this, x, length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::write_wchar_array (const ACE_CDR::WChar* x, - ACE_CDR::ULong length) -{ - if (this->wchar_translator_) - return this->wchar_translator_->write_wchar_array (*this, x, length); - - if (ACE_OutputCDR::wchar_maxbytes_ == 0) - { - errno = EACCES; - return (ACE_CDR::Boolean) (this->good_bit_ = false); - } - - if (ACE_OutputCDR::wchar_maxbytes_ == sizeof (ACE_CDR::WChar)) - return this->write_array (x, - sizeof (ACE_CDR::WChar), - sizeof (ACE_CDR::WChar) == 2 - ? ACE_CDR::SHORT_ALIGN - : ACE_CDR::LONG_ALIGN, - length); - return this->write_wchar_array_i (x,length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::write_octet_array (const ACE_CDR::Octet* x, - ACE_CDR::ULong length) -{ - return this->write_array (x, - ACE_CDR::OCTET_SIZE, - ACE_CDR::OCTET_ALIGN, - length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::write_short_array (const ACE_CDR::Short *x, - ACE_CDR::ULong length) -{ - return this->write_array (x, - ACE_CDR::SHORT_SIZE, - ACE_CDR::SHORT_ALIGN, - length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::write_ushort_array (const ACE_CDR::UShort *x, - ACE_CDR::ULong length) -{ - return this->write_array (x, - ACE_CDR::SHORT_SIZE, - ACE_CDR::SHORT_ALIGN, - length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::write_long_array (const ACE_CDR::Long *x, - ACE_CDR::ULong length) -{ - return this->write_array (x, - ACE_CDR::LONG_SIZE, - ACE_CDR::LONG_ALIGN, - length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::write_ulong_array (const ACE_CDR::ULong *x, - ACE_CDR::ULong length) -{ - return this->write_array (x, - ACE_CDR::LONG_SIZE, - ACE_CDR::LONG_ALIGN, - length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::write_longlong_array (const ACE_CDR::LongLong *x, - ACE_CDR::ULong length) -{ - return this->write_array (x, - ACE_CDR::LONGLONG_SIZE, - ACE_CDR::LONGLONG_ALIGN, - length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::write_ulonglong_array (const ACE_CDR::ULongLong *x, - ACE_CDR::ULong length) -{ - return this->write_array (x, - ACE_CDR::LONGLONG_SIZE, - ACE_CDR::LONGLONG_ALIGN, - length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::write_float_array (const ACE_CDR::Float *x, - ACE_CDR::ULong length) -{ - return this->write_array (x, - ACE_CDR::LONG_SIZE, - ACE_CDR::LONG_ALIGN, - length); -} - - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::write_double_array (const ACE_CDR::Double *x, - ACE_CDR::ULong length) -{ - return this->write_array (x, - ACE_CDR::LONGLONG_SIZE, - ACE_CDR::LONGLONG_ALIGN, - length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::write_longdouble_array (const ACE_CDR::LongDouble* x, - ACE_CDR::ULong length) -{ - return this->write_array (x, - ACE_CDR::LONGDOUBLE_SIZE, - ACE_CDR::LONGDOUBLE_ALIGN, - length); -} - -ACE_INLINE bool -ACE_OutputCDR::good_bit (void) const -{ - return this->good_bit_; -} - -ACE_INLINE int -ACE_OutputCDR::adjust (size_t size, - size_t align, - char*& buf) -{ - if (!this->current_is_writable_) - return this->grow_and_adjust (size, align, buf); - -#if !defined (ACE_LACKS_CDR_ALIGNMENT) - size_t const offset = - ACE_align_binary (this->current_alignment_, align) - - this->current_alignment_; - - buf = this->current_->wr_ptr () + offset; -#else - buf = this->current_->wr_ptr (); -#endif /* ACE_LACKS_CDR_ALIGNMENT */ - - char * const end = buf + size; - - if (end <= this->current_->end () && - end >= buf) - { -#if !defined (ACE_LACKS_CDR_ALIGNMENT) - this->current_alignment_ += offset + size; -#endif /* ACE_LACKS_CDR_ALIGNMENT */ - this->current_->wr_ptr (end); - -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - this->monitor_->receive (this->total_length ()); -#endif /* ACE_HAS_MONITOR_POINTS==1 */ - - return 0; - } - - return this->grow_and_adjust (size, align, buf); -} - -ACE_INLINE int -ACE_OutputCDR::adjust (size_t size, char*& buf) -{ - return this->adjust (size, size, buf); -} - -ACE_INLINE void -ACE_OutputCDR::set_version (ACE_CDR::Octet major, ACE_CDR::Octet minor) -{ - this->major_version_ = major; - this->minor_version_ = minor; -} - -ACE_INLINE void -ACE_OutputCDR::get_version (ACE_CDR::Octet &major, ACE_CDR::Octet &minor) -{ - major = this->major_version_; - minor = this->minor_version_; -} - - -ACE_INLINE const ACE_Message_Block* -ACE_OutputCDR::begin (void) const -{ - return &this->start_; -} - -ACE_INLINE const ACE_Message_Block* -ACE_OutputCDR::end (void) const -{ - return this->current_->cont (); -} - -ACE_INLINE const ACE_Message_Block* -ACE_OutputCDR::current (void) const -{ - return this->current_; -} - -ACE_INLINE size_t -ACE_OutputCDR::total_length (void) const -{ - return ACE_CDR::total_length (this->begin (), this->end ()); -} - -ACE_INLINE const char* -ACE_OutputCDR::buffer (void) const -{ - return this->start_.rd_ptr (); -} - -ACE_INLINE size_t -ACE_OutputCDR::length (void) const -{ - return this->start_.length (); -} - -ACE_INLINE bool -ACE_OutputCDR::do_byte_swap (void) const -{ - return this->do_byte_swap_; -} - -ACE_INLINE int -ACE_OutputCDR::byte_order (void) const -{ - if (this->do_byte_swap ()) - return !ACE_CDR_BYTE_ORDER; - else - return ACE_CDR_BYTE_ORDER; -} - -ACE_INLINE void -ACE_OutputCDR::reset_byte_order (int byte_order) -{ - this->do_byte_swap_ = (byte_order != ACE_CDR_BYTE_ORDER); -} - -ACE_INLINE size_t -ACE_OutputCDR::current_alignment (void) const -{ -#if !defined (ACE_LACKS_CDR_ALIGNMENT) - return this->current_alignment_; -#else - // Default value set to 0 - return 0; -#endif /* ACE_LACKS_CDR_ALIGNMENT */ -} - -ACE_INLINE void -ACE_OutputCDR::current_alignment (size_t current_alignment) -{ -#if !defined (ACE_LACKS_CDR_ALIGNMENT) - this->current_alignment_ = current_alignment; -#else - ACE_UNUSED_ARG (current_alignment); -#endif /* ACE_LACKS_CDR_ALIGNMENT */ -} - -ACE_INLINE int -ACE_OutputCDR::align_write_ptr (size_t alignment) -{ -#if !defined (ACE_LACKS_CDR_ALIGNMENT) - char *dummy; - return this->adjust (0, alignment, dummy); -#else - ACE_UNUSED_ARG (alignment); - // A return value of -1 from this function is used - // to indicate failure, returning 0 - return 0; -#endif /* ACE_LACKS_CDR_ALIGNMENT */ -} - -ACE_INLINE ACE_Char_Codeset_Translator * -ACE_OutputCDR::char_translator (void) const -{ - return this->char_translator_; -} - -ACE_INLINE ACE_WChar_Codeset_Translator * -ACE_OutputCDR::wchar_translator (void) const -{ - return this->wchar_translator_; -} - -ACE_INLINE void -ACE_OutputCDR::char_translator (ACE_Char_Codeset_Translator * ctran) -{ - this->char_translator_ = ctran; -} - -ACE_INLINE void -ACE_OutputCDR::wchar_translator (ACE_WChar_Codeset_Translator * wctran) -{ - this->wchar_translator_ = wctran; -} - -// **************************************************************** - -ACE_INLINE -ACE_InputCDR::~ACE_InputCDR (void) -{ -#if defined (ACE_HAS_MONITOR_POINTS) && (ACE_HAS_MONITOR_POINTS == 1) - this->monitor_->remove_ref (); -#endif /* ACE_HAS_MONITOR_POINTS==1 */ -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::read_octet (ACE_CDR::Octet& x) -{ - return this->read_1 (&x); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::read_boolean (ACE_CDR::Boolean& x) -{ - ACE_CDR::Octet tmp = 0; - (void) this->read_octet (tmp); - x = tmp ? true : false; - return (ACE_CDR::Boolean) this->good_bit_; -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::read_char (ACE_CDR::Char &x) -{ - if (this->char_translator_ == 0) - { - void *temp = &x; - return this->read_1 (reinterpret_cast (temp)); - } - return this->char_translator_->read_char (*this, x); -} - - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::read_short (ACE_CDR::Short &x) -{ - void *temp = &x; - return this->read_2 (reinterpret_cast (temp)); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::read_ushort (ACE_CDR::UShort &x) -{ - return this->read_2 (&x); -} - - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::read_long (ACE_CDR::Long &x) -{ - void *temp = &x; - return this->read_4 (reinterpret_cast (temp)); -} - - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::read_ulong (ACE_CDR::ULong &x) -{ - return this->read_4 (&x); -} - - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::read_longlong (ACE_CDR::LongLong &x) -{ - void *temp = &x; - return this->read_8 (reinterpret_cast (temp)); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::read_ulonglong (ACE_CDR::ULongLong &x) -{ - return this->read_8 (&x); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::read_float (ACE_CDR::Float &x) -{ - void *temp = &x; - return this->read_4 (reinterpret_cast (temp)); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::read_double (ACE_CDR::Double &x) -{ - void *temp = &x; - return this->read_8 (reinterpret_cast (temp)); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::read_longdouble (ACE_CDR::LongDouble &x) -{ - return this->read_16 (&x); -} - -ACE_INLINE size_t -ACE_InputCDR::length (void) const -{ - return this->start_.length (); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::read_char_array (ACE_CDR::Char* x, - ACE_CDR::ULong length) -{ - // Make sure the length of the array isn't greater than the length of - // the stream. - if (length > this->length ()) - { - this->good_bit_ = false; - return false; - } - - if (this->char_translator_ == 0) - return this->read_array (x, - ACE_CDR::OCTET_SIZE, - ACE_CDR::OCTET_ALIGN, - length); - return this->char_translator_->read_char_array (*this, x, length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::read_wchar_array (ACE_CDR::WChar* x, - ACE_CDR::ULong length) -{ - // Make sure the length of the array isn't greater than the length of - // the stream. - if (length * ACE_OutputCDR::wchar_maxbytes_ > this->length ()) - { - this->good_bit_ = false; - return false; - } - - if (this->wchar_translator_ != 0) - return this->wchar_translator_->read_wchar_array (*this, x, length); - if (ACE_OutputCDR::wchar_maxbytes_ != sizeof (ACE_CDR::WChar)) - return this->read_wchar_array_i (x, length); - return this->read_array (x, - sizeof (ACE_CDR::WChar), - sizeof (ACE_CDR::WChar) == 2 - ? ACE_CDR::SHORT_ALIGN - : ACE_CDR::LONG_ALIGN, - length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::read_octet_array (ACE_CDR::Octet* x, - ACE_CDR::ULong length) -{ - // Make sure the length of the array isn't greater than the length of - // the stream. - if (length * ACE_CDR::OCTET_SIZE > this->length ()) - { - this->good_bit_ = false; - return false; - } - - return this->read_array (x, - ACE_CDR::OCTET_SIZE, - ACE_CDR::OCTET_ALIGN, - length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::read_short_array (ACE_CDR::Short *x, - ACE_CDR::ULong length) -{ - // Make sure the length of the array isn't greater than the length of - // the stream. - if (length * ACE_CDR::SHORT_SIZE > this->length ()) - { - this->good_bit_ = false; - return false; - } - - return this->read_array (x, - ACE_CDR::SHORT_SIZE, - ACE_CDR::SHORT_ALIGN, - length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::read_ushort_array (ACE_CDR::UShort *x, - ACE_CDR::ULong length) -{ - // Make sure the length of the array isn't greater than the length of - // the stream. - if (length * ACE_CDR::SHORT_SIZE > this->length ()) - { - this->good_bit_ = false; - return false; - } - - return this->read_array (x, - ACE_CDR::SHORT_SIZE, - ACE_CDR::SHORT_ALIGN, - length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::read_long_array (ACE_CDR::Long *x, - ACE_CDR::ULong length) -{ - // Make sure the length of the array isn't greater than the length of - // the stream. - if (length * ACE_CDR::LONG_SIZE > this->length ()) - { - this->good_bit_ = false; - return false; - } - - return this->read_array (x, - ACE_CDR::LONG_SIZE, - ACE_CDR::LONG_ALIGN, - length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::read_ulong_array (ACE_CDR::ULong *x, - ACE_CDR::ULong length) -{ - // Make sure the length of the array isn't greater than the length of - // the stream. - if (length * ACE_CDR::LONG_SIZE > this->length ()) - { - this->good_bit_ = false; - return false; - } - - return this->read_array (x, - ACE_CDR::LONG_SIZE, - ACE_CDR::LONG_ALIGN, - length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::read_longlong_array (ACE_CDR::LongLong *x, - ACE_CDR::ULong length) -{ - // Make sure the length of the array isn't greater than the length of - // the stream. - if (length * ACE_CDR::LONGLONG_SIZE > this->length ()) - { - this->good_bit_ = false; - return false; - } - - return this->read_array (x, - ACE_CDR::LONGLONG_SIZE, - ACE_CDR::LONGLONG_ALIGN, - length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::read_ulonglong_array (ACE_CDR::ULongLong *x, - ACE_CDR::ULong length) -{ - // Make sure the length of the array isn't greater than the length of - // the stream. - if (length * ACE_CDR::LONGLONG_SIZE > this->length ()) - { - this->good_bit_ = false; - return false; - } - - return this->read_array (x, - ACE_CDR::LONGLONG_SIZE, - ACE_CDR::LONGLONG_ALIGN, - length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::read_float_array (ACE_CDR::Float *x, - ACE_CDR::ULong length) -{ - // Make sure the length of the array isn't greater than the length of - // the stream. - if (length * ACE_CDR::LONG_SIZE > this->length ()) - { - this->good_bit_ = false; - return false; - } - - return this->read_array (x, - ACE_CDR::LONG_SIZE, - ACE_CDR::LONG_ALIGN, - length); -} - - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::read_double_array (ACE_CDR::Double *x, - ACE_CDR::ULong length) -{ - // Make sure the length of the array isn't greater than the length of - // the stream. - if (length * ACE_CDR::LONGLONG_SIZE > this->length ()) - { - this->good_bit_ = false; - return false; - } - - return this->read_array (x, - ACE_CDR::LONGLONG_SIZE, - ACE_CDR::LONGLONG_ALIGN, - length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::read_longdouble_array (ACE_CDR::LongDouble* x, - ACE_CDR::ULong length) -{ - // Make sure the length of the array isn't greater than the length of - // the stream. - if (length * ACE_CDR::LONGDOUBLE_SIZE > this->length ()) - { - this->good_bit_ = false; - return false; - } - return this->read_array (x, - ACE_CDR::LONGDOUBLE_SIZE, - ACE_CDR::LONGDOUBLE_ALIGN, - length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::skip_octet (void) -{ - ACE_CDR::Octet x; - return this->read_1 (&x); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::skip_char (void) -{ - return this->skip_octet (); // sizeof (Char) == sizeof (Octet) -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::skip_boolean (void) -{ - return this->skip_octet () && this->good_bit_; -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::skip_ushort (void) -{ - ACE_CDR::UShort x; - return this->read_2 (&x); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::skip_short (void) -{ - return this->skip_ushort (); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::skip_ulong (void) -{ - ACE_CDR::ULong x; - return this->read_4 (&x); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::skip_long (void) -{ - return this->skip_ulong (); // sizeof (Long) == sizeof (ULong) -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::skip_ulonglong (void) -{ - ACE_CDR::ULongLong x; - return this->read_8 (&x); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::skip_longlong (void) -{ - return this->skip_ulonglong (); // sizeof (LongLong) == sizeof (ULongLong) -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::skip_float (void) -{ - return this->skip_ulong (); // sizeof(Float) == sizeof (ULong) -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::skip_double (void) -{ - return this->skip_ulonglong (); // sizeof(Double) == sizeof (ULongLong) -} - -ACE_INLINE ACE_CDR::Boolean -ACE_InputCDR::skip_longdouble (void) -{ - ACE_CDR::LongDouble x; - return this->read_16 (&x); -} - -ACE_INLINE char* -ACE_InputCDR::end (void) -{ - return this->start_.end (); -} - -ACE_INLINE void -ACE_InputCDR::rd_ptr (size_t offset) -{ - this->start_.rd_ptr (offset); -} - -ACE_INLINE char* -ACE_InputCDR::rd_ptr (void) -{ - return this->start_.rd_ptr (); -} - -ACE_INLINE char* -ACE_InputCDR::wr_ptr (void) -{ - return this->start_.wr_ptr (); -} - -ACE_INLINE int -ACE_InputCDR::adjust (size_t size, - size_t align, - char*& buf) -{ -#if !defined (ACE_LACKS_CDR_ALIGNMENT) - buf = ACE_ptr_align_binary (this->rd_ptr (), align); -#else - buf = this->rd_ptr (); -#endif /* ACE_LACKS_CDR_ALIGNMENT */ - - char * const end = buf + size; - if (end <= this->wr_ptr ()) - { - this->start_.rd_ptr (end); - return 0; - } - - this->good_bit_ = false; - return -1; -#if defined (ACE_LACKS_CDR_ALIGNMENT) - ACE_UNUSED_ARG (align); -#endif /* ACE_LACKS_CDR_ALIGNMENT */ -} - -ACE_INLINE int -ACE_InputCDR::adjust (size_t size, - char*& buf) -{ - return this->adjust (size, size, buf); -} - -ACE_INLINE const ACE_Message_Block* -ACE_InputCDR::start (void) const -{ - return &this->start_; -} - -ACE_INLINE bool -ACE_InputCDR::good_bit (void) const -{ - return this->good_bit_; -} - -// **************************************************************** - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_OutputCDR &os, ACE_CDR::Char x) -{ - os.write_char (x); - return (ACE_CDR::Boolean) os.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_OutputCDR &os, ACE_CDR::Short x) -{ - os.write_short (x); - return (ACE_CDR::Boolean) os.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_OutputCDR &os, ACE_CDR::UShort x) -{ - os.write_ushort (x); - return (ACE_CDR::Boolean) os.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_OutputCDR &os, ACE_CDR::Long x) -{ - os.write_long (x); - return (ACE_CDR::Boolean) os.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_OutputCDR &os, ACE_CDR::ULong x) -{ - os.write_ulong (x); - return (ACE_CDR::Boolean) os.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_OutputCDR &os, ACE_CDR::LongLong x) -{ - os.write_longlong (x); - return (ACE_CDR::Boolean) os.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_OutputCDR &os, ACE_CDR::ULongLong x) -{ - os.write_ulonglong (x); - return (ACE_CDR::Boolean) os.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_OutputCDR &os, ACE_CDR::LongDouble x) -{ - os.write_longdouble (x); - return (ACE_CDR::Boolean) os.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_OutputCDR &os, ACE_CDR::Float x) -{ - os.write_float (x); - return (ACE_CDR::Boolean) os.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_OutputCDR &os, ACE_CDR::Double x) -{ - os.write_double (x); - return (ACE_CDR::Boolean) os.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_OutputCDR &os, const ACE_CDR::Char *x) -{ - os.write_string (x); - return (ACE_CDR::Boolean) os.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_OutputCDR &os, const ACE_CDR::WChar *x) -{ - os.write_wstring (x); - return (ACE_CDR::Boolean) os.good_bit (); -} - -// The following use the helper classes -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_OutputCDR &os, ACE_OutputCDR::from_boolean x) -{ - (void) os.write_boolean (x.val_); - return (ACE_CDR::Boolean) os.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_OutputCDR &os, ACE_OutputCDR::from_char x) -{ - os.write_char (x.val_); - return (ACE_CDR::Boolean) os.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_OutputCDR &os, ACE_OutputCDR::from_wchar x) -{ - os.write_wchar (x.val_); - return (ACE_CDR::Boolean) os.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_OutputCDR &os, ACE_OutputCDR::from_octet x) -{ - os.write_octet (x.val_); - return (ACE_CDR::Boolean) os.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_OutputCDR &os, ACE_OutputCDR::from_string x) -{ - ACE_CDR::ULong len = 0; - - if (x.val_ != 0) - { - len = static_cast (ACE_OS::strlen (x.val_)); - } - - os.write_string (len, x.val_); - return - (ACE_CDR::Boolean) (os.good_bit () && (!x.bound_ || len <= x.bound_)); -} - -ACE_INLINE ACE_CDR::Boolean -operator<< (ACE_OutputCDR &os, ACE_OutputCDR::from_wstring x) -{ - ACE_CDR::ULong len = 0; - - if (x.val_ != 0) - { - len = static_cast (ACE_OS::strlen (x.val_)); - } - - os.write_wstring (len, x.val_); - return - (ACE_CDR::Boolean) (os.good_bit () && (!x.bound_ || len <= x.bound_)); -} - -// **************************************************************** - -ACE_INLINE ACE_CDR::Boolean -operator>> (ACE_InputCDR &is, ACE_CDR::Char &x) -{ - return is.read_char (x) && is.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator>> (ACE_InputCDR &is, ACE_CDR::Short &x) -{ - return is.read_short (x) && is.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator>> (ACE_InputCDR &is, ACE_CDR::UShort &x) -{ - return is.read_ushort (x) && is.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator>>(ACE_InputCDR &is, ACE_CDR::Long &x) -{ - return is.read_long (x) && is.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator>> (ACE_InputCDR &is, ACE_CDR::ULong &x) -{ - return is.read_ulong (x) && is.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator>> (ACE_InputCDR& is, ACE_CDR::LongLong &x) -{ - return is.read_longlong (x) && is.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator>> (ACE_InputCDR& is, ACE_CDR::ULongLong &x) -{ - return is.read_ulonglong (x) && is.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator>> (ACE_InputCDR& is, ACE_CDR::LongDouble &x) -{ - return is.read_longdouble (x) && is.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator>> (ACE_InputCDR &is, ACE_CDR::Float &x) -{ - return is.read_float (x) && is.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator>> (ACE_InputCDR &is, ACE_CDR::Double &x) -{ - return is.read_double (x) && is.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator>> (ACE_InputCDR &is, ACE_CDR::Char *&x) -{ - return is.read_string (x) && is.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator>> (ACE_InputCDR &is, ACE_CDR::WChar *&x) -{ - return is.read_wstring (x) && is.good_bit (); -} - -// The following use the helper classes -ACE_INLINE ACE_CDR::Boolean -operator>> (ACE_InputCDR &is, ACE_InputCDR::to_boolean x) -{ - return is.read_boolean (x.ref_); -} - -ACE_INLINE ACE_CDR::Boolean -operator>> (ACE_InputCDR &is, ACE_InputCDR::to_char x) -{ - return is.read_char (x.ref_) && is.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator>> (ACE_InputCDR &is, ACE_InputCDR::to_wchar x) -{ - return is.read_wchar (x.ref_) && is.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator>> (ACE_InputCDR &is, ACE_InputCDR::to_octet x) -{ - return is.read_octet (x.ref_) && is.good_bit (); -} - -ACE_INLINE ACE_CDR::Boolean -operator>> (ACE_InputCDR &is, ACE_InputCDR::to_string x) -{ - // check if the bounds are satisfied - return - (is.read_string (const_cast (x.val_)) - && is.good_bit () - && (!x.bound_ - || ACE_OS::strlen (x.val_) <= x.bound_)); -} - -ACE_INLINE ACE_CDR::Boolean -operator>> (ACE_InputCDR &is, ACE_InputCDR::to_wstring x) -{ - // check if the bounds are satisfied - return - (is.read_wstring (const_cast (x.val_)) - && is.good_bit () - && (!x.bound_ - || ACE_OS::strlen (x.val_) <= x.bound_)); -} - -// *************************************************************************** -// We must define these methods here because they use the "read_*" inlined -// methods of the ACE_InputCDR class -// *************************************************************************** - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::append_boolean (ACE_InputCDR &stream) -{ - ACE_CDR::Boolean x; - return stream.read_boolean (x) ? this->write_boolean (x) : false; -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::append_char (ACE_InputCDR &stream) -{ - ACE_CDR::Char x; - return stream.read_char (x) ? this->write_char (x) : false; -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::append_wchar (ACE_InputCDR &stream) -{ - ACE_CDR::WChar x; - return stream.read_wchar (x) ? this->write_wchar (x) : false; -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::append_octet (ACE_InputCDR &stream) -{ - ACE_CDR::Octet x; - return stream.read_octet (x) ? this->write_octet (x) : false; -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::append_short (ACE_InputCDR &stream) -{ - ACE_CDR::Short x; - return stream.read_short (x) ? this->write_short (x) : false; -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::append_ushort (ACE_InputCDR &stream) -{ - ACE_CDR::UShort x; - return stream.read_ushort (x) ? this->write_ushort (x) : false; -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::append_long (ACE_InputCDR &stream) -{ - ACE_CDR::Long x; - return stream.read_long (x) ? this->write_long (x) : false; -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::append_ulong (ACE_InputCDR &stream) -{ - ACE_CDR::ULong x; - return stream.read_ulong (x) ? this->write_ulong (x) : false; -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::append_longlong (ACE_InputCDR &stream) -{ - ACE_CDR::LongLong x; - return stream.read_longlong (x) ? this->write_longlong (x) : false; -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::append_ulonglong (ACE_InputCDR &stream) -{ - ACE_CDR::ULongLong x; - return stream.read_ulonglong (x) ? this->write_ulonglong (x) : false; -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::append_float (ACE_InputCDR &stream) -{ - ACE_CDR::Float x; - return stream.read_float (x) ? this->write_float (x) : false; -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::append_double (ACE_InputCDR &stream) -{ - ACE_CDR::Double x; - return stream.read_double (x) ? this->write_double (x) : false; -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::append_longdouble (ACE_InputCDR &stream) -{ - ACE_CDR::LongDouble x; - return stream.read_longdouble (x) ? this->write_longdouble (x) : false; -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::append_string (ACE_InputCDR &stream) -{ - ACE_CDR::Char *x = 0; - ACE_CDR::Boolean const flag = - (stream.read_string (x) ? this->write_string (x) : false); - delete [] x; - return flag; -} - -ACE_INLINE ACE_CDR::Boolean -ACE_OutputCDR::append_wstring (ACE_InputCDR &stream) -{ - ACE_CDR::WChar *x = 0; - ACE_CDR::Boolean const flag = - (stream.read_wstring (x) ? this->write_wstring (x) : false); - delete [] x; - return flag; -} - -ACE_INLINE void -ACE_InputCDR::reset_byte_order (int byte_order) -{ - this->do_byte_swap_ = (byte_order != ACE_CDR_BYTE_ORDER); -} - -ACE_INLINE bool -ACE_InputCDR::do_byte_swap (void) const -{ - return this->do_byte_swap_; -} - -ACE_INLINE int -ACE_InputCDR::byte_order (void) const -{ - return this->do_byte_swap () ? !ACE_CDR_BYTE_ORDER : ACE_CDR_BYTE_ORDER; -} - -ACE_INLINE int -ACE_InputCDR::align_read_ptr (size_t alignment) -{ -#if !defined (ACE_LACKS_CDR_ALIGNMENT) - char *buf = ACE_ptr_align_binary (this->rd_ptr (), - alignment); -#else - char *buf = this->rd_ptr (); -#endif /* ACE_LACKS_CDR_ALIGNMENT */ - - if (buf <= this->wr_ptr ()) - { - this->start_.rd_ptr (buf); - return 0; - } - - this->good_bit_ = false; - return -1; -} - -ACE_INLINE void -ACE_InputCDR::set_version (ACE_CDR::Octet major, ACE_CDR::Octet minor) -{ - this->major_version_ = major; - this->minor_version_ = minor; -} - -ACE_INLINE void -ACE_InputCDR::get_version (ACE_CDR::Octet &major, ACE_CDR::Octet &minor) -{ - major = this->major_version_; - minor = this->minor_version_; -} - -ACE_INLINE ACE_Char_Codeset_Translator * -ACE_InputCDR::char_translator (void) const -{ - return this->char_translator_; -} - -ACE_INLINE ACE_WChar_Codeset_Translator * -ACE_InputCDR::wchar_translator (void) const -{ - return this->wchar_translator_; -} - - -ACE_INLINE void -ACE_InputCDR::char_translator (ACE_Char_Codeset_Translator * ctran) -{ - this->char_translator_ = ctran; -} - -ACE_INLINE void -ACE_InputCDR::wchar_translator (ACE_WChar_Codeset_Translator * wctran) -{ - this->wchar_translator_ = wctran; -} - -// **************************************************************** - -ACE_INLINE ACE_CDR::Boolean -ACE_Char_Codeset_Translator::read_1 (ACE_InputCDR& input, - ACE_CDR::Octet *x) -{ - return input.read_1 (x); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_Char_Codeset_Translator::write_1 (ACE_OutputCDR& output, - const ACE_CDR::Octet *x) -{ - return output.write_1 (x); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_Char_Codeset_Translator::read_array (ACE_InputCDR& in, - void* x, - size_t size, - size_t align, - ACE_CDR::ULong length) -{ - return in.read_array (x, size, align, length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_Char_Codeset_Translator::write_array (ACE_OutputCDR& out, - const void *x, - size_t size, - size_t align, - ACE_CDR::ULong length) -{ - return out.write_array(x, size, align, length); -} - -ACE_INLINE int -ACE_Char_Codeset_Translator::adjust (ACE_OutputCDR& out, - size_t size, - size_t align, - char *&buf) -{ - return out.adjust(size, align, buf); -} - -ACE_INLINE void -ACE_Char_Codeset_Translator::good_bit (ACE_OutputCDR& out, bool bit) -{ - out.good_bit_ = bit; -} - -ACE_INLINE ACE_CDR::Octet -ACE_Char_Codeset_Translator::major_version (ACE_InputCDR& input) -{ - return input.major_version_; -} - -ACE_INLINE ACE_CDR::Octet -ACE_Char_Codeset_Translator::minor_version (ACE_InputCDR& input) -{ - return input.minor_version_; -} - -ACE_INLINE ACE_CDR::Octet -ACE_Char_Codeset_Translator::major_version (ACE_OutputCDR& output) -{ - return output.major_version_; -} - -ACE_INLINE ACE_CDR::Octet -ACE_Char_Codeset_Translator::minor_version (ACE_OutputCDR& output) -{ - return output.minor_version_; -} - -// **************************************************************** - -ACE_INLINE ACE_CDR::Boolean -ACE_WChar_Codeset_Translator::read_1 (ACE_InputCDR& input, - ACE_CDR::Octet *x) -{ - return input.read_1 (x); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_WChar_Codeset_Translator::read_2 (ACE_InputCDR& input, - ACE_CDR::UShort *x) -{ - return input.read_2 (x); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_WChar_Codeset_Translator::read_4 (ACE_InputCDR& input, - ACE_CDR::ULong *x) -{ - return input.read_4 (x); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_WChar_Codeset_Translator::write_1 (ACE_OutputCDR& output, - const ACE_CDR::Octet *x) -{ - return output.write_1 (x); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_WChar_Codeset_Translator::write_2 (ACE_OutputCDR& output, - const ACE_CDR::UShort *x) -{ - return output.write_2 (x); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_WChar_Codeset_Translator::write_4 (ACE_OutputCDR& output, - const ACE_CDR::ULong *x) -{ - return output.write_4 (x); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_WChar_Codeset_Translator::read_array (ACE_InputCDR& in, - void* x, - size_t size, - size_t align, - ACE_CDR::ULong length) -{ - return in.read_array (x, size, align, length); -} - -ACE_INLINE ACE_CDR::Boolean -ACE_WChar_Codeset_Translator::write_array (ACE_OutputCDR& out, - const void *x, - size_t size, - size_t align, - ACE_CDR::ULong length) -{ - return out.write_array(x, size, align, length); -} - -ACE_INLINE int -ACE_WChar_Codeset_Translator::adjust (ACE_OutputCDR& out, - size_t size, - size_t align, - char *&buf) -{ - return out.adjust(size, align, buf); -} - -ACE_INLINE void -ACE_WChar_Codeset_Translator::good_bit (ACE_OutputCDR& out, bool bit) -{ - out.good_bit_ = bit; -} - -ACE_INLINE ACE_CDR::Octet -ACE_WChar_Codeset_Translator::major_version (ACE_InputCDR& input) -{ - return input.major_version_; -} - -ACE_INLINE ACE_CDR::Octet -ACE_WChar_Codeset_Translator::minor_version (ACE_InputCDR& input) -{ - return input.minor_version_; -} - -ACE_INLINE ACE_CDR::Octet -ACE_WChar_Codeset_Translator::major_version (ACE_OutputCDR& output) -{ - return output.major_version_; -} - -ACE_INLINE ACE_CDR::Octet -ACE_WChar_Codeset_Translator::minor_version (ACE_OutputCDR& output) -{ - return output.minor_version_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/CE_Screen_Output.cpp b/externals/ace/CE_Screen_Output.cpp deleted file mode 100644 index dfd3d717a1f..00000000000 --- a/externals/ace/CE_Screen_Output.cpp +++ /dev/null @@ -1,158 +0,0 @@ -// $Id: CE_Screen_Output.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/CE_Screen_Output.h" -#if defined (ACE_HAS_WINCE) - -#include "ace/Log_Msg.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_CE_Screen_Output::ACE_CE_Screen_Output(HWND hEdit) -: handler_(hEdit) -, pFile_(0) -{ -} - -ACE_CE_Screen_Output::ACE_CE_Screen_Output() -: handler_(0) -, pFile_(0) -{ -} - -ACE_CE_Screen_Output::~ACE_CE_Screen_Output() -{ - if (pFile_ != 0) { - fclose(pFile_); - } -} - -void ACE_CE_Screen_Output::log(ACE_Log_Record &log_record) -{ - ACE_TCHAR verbose_msg[ACE_Log_Record::MAXVERBOSELOGMSGLEN]; - int result = log_record.format_msg (ACE_TEXT("WindozeCE"), // host name - 0, // verbose flag - verbose_msg); - - if (result == 0) - { - verbose_msg[ ACE_OS::strlen(verbose_msg) - 1 ] = 0; // CE does not like '\n' by itself. - *this << verbose_msg << endl; - } -} - -void ACE_CE_Screen_Output::SetOutputWindow(HWND hEdit) -{ - handler_ = hEdit; -} - -void ACE_CE_Screen_Output::clear() -{ - SetWindowText(handler_, 0); -} - -ACE_CE_Screen_Output& ACE_CE_Screen_Output::operator << (ACE_TCHAR* output) -{ - int length = GetWindowTextLength(handler_); - SendMessage(handler_, EM_SETSEL, length, length); - SendMessage(handler_, EM_REPLACESEL, 0, (LPARAM)output); - - if (pFile_ != 0) - { - fwprintf(pFile_, L"%s", output); - } - - return *this; -} - -ACE_CE_Screen_Output& ACE_CE_Screen_Output::operator << (const ACE_TCHAR* output) -{ - ACE_TCHAR* buffer = ACE_OS::strdup(output); - if (buffer != 0) - { - *this << buffer; - delete buffer; - } - return *this; -} - -ACE_CE_Screen_Output& ACE_CE_Screen_Output::operator << (ACE_ANTI_TCHAR* output) -{ - *this << ACE_TEXT_CHAR_TO_TCHAR(output); - return *this; -} - -ACE_CE_Screen_Output& ACE_CE_Screen_Output::operator << (const ACE_ANTI_TCHAR* output) -{ - *this << ACE_TEXT_CHAR_TO_TCHAR(output); - return *this; -} - -ACE_CE_Screen_Output& ACE_CE_Screen_Output::operator << (char output) -{ - *this << (int)output; - return *this; -} - -ACE_CE_Screen_Output& ACE_CE_Screen_Output::operator << (unsigned char output) -{ - *this << (int)output; - return *this; -} - -ACE_CE_Screen_Output& ACE_CE_Screen_Output::operator << (unsigned short output) -{ - ACE_TCHAR buffer[20]; - wsprintf(buffer, ACE_TEXT("%u"), output); - *this << buffer; - return *this; -} - -ACE_CE_Screen_Output& ACE_CE_Screen_Output::operator << (int output) -{ - ACE_TCHAR buffer[20]; - wsprintf(buffer, ACE_TEXT("%d"), output); - *this << buffer; - return *this; -} - -ACE_CE_Screen_Output& ACE_CE_Screen_Output::operator << (unsigned int output) -{ - ACE_TCHAR buffer[20]; - wsprintf(buffer, ACE_TEXT("%du"), output); - *this << buffer; - return *this; -} - -ACE_CE_Screen_Output& ACE_CE_Screen_Output::operator << (float output) -{ - ACE_TCHAR buffer[20]; - swprintf(buffer, ACE_TEXT("%f"), output); - *this << buffer; - return *this; -} - -ACE_CE_Screen_Output& ACE_CE_Screen_Output::operator << (long output) -{ - ACE_TCHAR buffer[20]; - wsprintf(buffer, ACE_TEXT("%l"), output); - *this << buffer; - return *this; -} - -ACE_CE_Screen_Output& ACE_CE_Screen_Output::operator << (unsigned long output) -{ - ACE_TCHAR buffer[20]; - wsprintf(buffer, ACE_TEXT("%lu"), output); - *this << buffer; - return *this; -} - -ACE_CE_Screen_Output& ACE_CE_Screen_Output::operator << (FILE* pFile) -{ - pFile_ = pFile; - return *this; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif // ACE_HAS_WINCE diff --git a/externals/ace/CE_Screen_Output.h b/externals/ace/CE_Screen_Output.h deleted file mode 100644 index ba2bc7c02b5..00000000000 --- a/externals/ace/CE_Screen_Output.h +++ /dev/null @@ -1,109 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file CE_Screen_Output.h - * - * $Id: CE_Screen_Output.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Si Mong Park - */ -//============================================================================= - -#ifndef ACE_CE_SCREEN_OUTPUT_H -#define ACE_CE_SCREEN_OUTPUT_H - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -#pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_WINCE) - -#include "ace/Log_Msg_Callback.h" -#include "ace/Log_Record.h" - -namespace -{ - const ACE_TCHAR endl[] = ACE_TEXT("\r\n"); - const ACE_TCHAR tab[] = ACE_TEXT("\t"); -} - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_CE_Screen_Output - * - * @brief Replacement of text output for Windows CE. - * - * This class allows standard text output to be displayed on - * text window for Windows CE. Generally, all ACE output will - * go through under CE if and only if user uses WindozeCE - * implementation by using main_ce instead of main. - * Also, for the easier debugging purpose, object pointer of - * this class can be gotten from ACE_Log_Msg::msg_callback() - * and then can be used directly by user just like cout stream. - */ -class ACE_Export ACE_CE_Screen_Output : public ACE_Log_Msg_Callback -{ -public: - - ACE_CE_Screen_Output (HWND hEdit); - - ACE_CE_Screen_Output (void); - - virtual ~ACE_CE_Screen_Output(); - - /// Implementation of pure virtual function from ACE_Log_Msg_Callback. - virtual void log (ACE_Log_Record &log_record); - - /// Interface to specify active window handle. - void SetOutputWindow (HWND hWnd); - - void clear (void); - - /// Stream insertion operator that performs actual print out. - /** - * @note This is the only one operator that performs output. All - * other perators convert the type and use this operator - * underneath. - */ - ACE_CE_Screen_Output& operator << (ACE_TCHAR*); - ACE_CE_Screen_Output& operator << (const ACE_TCHAR*); - - ACE_CE_Screen_Output& operator << (ACE_ANTI_TCHAR* output); - ACE_CE_Screen_Output& operator << (const ACE_ANTI_TCHAR* output); - - ACE_CE_Screen_Output& operator << (char output); - ACE_CE_Screen_Output& operator << (unsigned char output); - - ACE_CE_Screen_Output& operator << (unsigned short output); - - ACE_CE_Screen_Output& operator << (int output); - ACE_CE_Screen_Output& operator << (unsigned int output); - - ACE_CE_Screen_Output& operator << (float output); - - ACE_CE_Screen_Output& operator << (long output); - ACE_CE_Screen_Output& operator << (unsigned long output); - - ACE_CE_Screen_Output& operator << (FILE* pFile); - -private: - - ACE_CE_Screen_Output (ACE_CE_Screen_Output&); - -private: - - HWND handler_; - - /// FILE pointer that used to save output to file. This class does - /// not own the file handler pointer. - FILE* pFile_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif // ACE_HAS_WINCE -#endif // ACE_CE_SCREEN_OUTPUT_H diff --git a/externals/ace/CMakeLists.txt b/externals/ace/CMakeLists.txt deleted file mode 100644 index 2b5a487ef03..00000000000 --- a/externals/ace/CMakeLists.txt +++ /dev/null @@ -1,337 +0,0 @@ -# Copyright (C) 2008-2010 Trinity -# -# This file is free software; as a special exception the author gives -# unlimited permission to copy and/or distribute it, with or without -# modifications, as long as this notice is preserved. -# -# This program is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the -# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -# NOTE: Do not use glob here, it would include files we don't want -set(ace_STAT_SRCS - PrecompiledHeaders/WinAcePCH.cpp - ACE.cpp - ACE_crc32.cpp - ACE_crc_ccitt.cpp - ace_wchar.cpp - Activation_Queue.cpp - Active_Map_Manager.cpp - Addr.cpp - Argv_Type_Converter.cpp - Assert.cpp - Asynch_IO.cpp - Asynch_IO_Impl.cpp - Asynch_Pseudo_Task.cpp - ATM_Acceptor.cpp - ATM_Addr.cpp - ATM_Connector.cpp - ATM_Params.cpp - ATM_QoS.cpp - ATM_Stream.cpp - Atomic_Op.cpp - Atomic_Op_Sparc.c - Auto_Event.cpp - Barrier.cpp - Base_Thread_Adapter.cpp - Based_Pointer_Repository.cpp - Basic_Stats.cpp - Basic_Types.cpp - Capabilities.cpp - CDR_Base.cpp - CDR_Size.cpp - CDR_Stream.cpp - Cleanup.cpp - Codecs.cpp - Codeset_IBM1047.cpp - Codeset_Registry.cpp - Codeset_Registry_db.cpp - Condition_Recursive_Thread_Mutex.cpp - Condition_Thread_Mutex.cpp - Configuration.cpp - Configuration_Import_Export.cpp - Connection_Recycling_Strategy.cpp - Containers.cpp - Copy_Disabled.cpp - Countdown_Time.cpp - Date_Time.cpp - DEV.cpp - DEV_Addr.cpp - DEV_Connector.cpp - DEV_IO.cpp - Dev_Poll_Reactor.cpp - Dirent.cpp - Dirent_Selector.cpp - DLL.cpp - DLL_Manager.cpp - Dump.cpp - Dynamic.cpp - Dynamic_Message_Strategy.cpp - Dynamic_Service_Base.cpp - Dynamic_Service_Dependency.cpp - Encoding_Converter.cpp - Encoding_Converter_Factory.cpp - Event.cpp - Event_Handler.cpp - FIFO.cpp - FIFO_Recv.cpp - FIFO_Recv_Msg.cpp - FIFO_Send.cpp - FIFO_Send_Msg.cpp - FILE.cpp - FILE_Addr.cpp - FILE_Connector.cpp - FILE_IO.cpp - File_Lock.cpp - Filecache.cpp - Flag_Manip.cpp - Framework_Component.cpp - Functor.cpp - Functor_String.cpp - Get_Opt.cpp - gethrtime.cpp - Handle_Ops.cpp - Handle_Set.cpp - Hashable.cpp - High_Res_Timer.cpp - ICMP_Socket.cpp - INET_Addr.cpp - Init_ACE.cpp - IO_Cntl_Msg.cpp - IO_SAP.cpp - IOStream.cpp - IPC_SAP.cpp - Lib_Find.cpp - Local_Memory_Pool.cpp - Local_Name_Space.cpp - Local_Tokens.cpp - Lock.cpp - Log_Msg.cpp - Log_Msg_Backend.cpp - Log_Msg_Callback.cpp - Log_Msg_IPC.cpp - Log_Msg_NT_Event_Log.cpp - Log_Msg_UNIX_Syslog.cpp - Log_Record.cpp - Logging_Strategy.cpp - LSOCK.cpp - LSOCK_Acceptor.cpp - LSOCK_CODgram.cpp - LSOCK_Connector.cpp - LSOCK_Dgram.cpp - LSOCK_Stream.cpp - Malloc.cpp - Malloc_Allocator.cpp - Manual_Event.cpp - MEM_Acceptor.cpp - MEM_Addr.cpp - MEM_Connector.cpp - MEM_IO.cpp - Mem_Map.cpp - MEM_SAP.cpp - MEM_Stream.cpp - Message_Block.cpp - Message_Queue.cpp - Message_Queue_NT.cpp - Message_Queue_Vx.cpp - Method_Request.cpp - MMAP_Memory_Pool.cpp - Monitor_Admin.cpp - Monitor_Admin_Manager.cpp - Monitor_Base.cpp - Monitor_Control_Action.cpp - Monitor_Control_Types.cpp - Monitor_Point_Registry.cpp - Monitor_Size.cpp - Msg_WFMO_Reactor.cpp - Multihomed_INET_Addr.cpp - Mutex.cpp - Name_Proxy.cpp - Name_Request_Reply.cpp - Name_Space.cpp - Naming_Context.cpp - Netlink_Addr.cpp - Notification_Queue.cpp - Notification_Strategy.cpp - NT_Service.cpp - Obchunk.cpp - Object_Manager.cpp - Object_Manager_Base.cpp - OS_Errno.cpp - OS_Log_Msg_Attributes.cpp - OS_main.cpp - OS_NS_arpa_inet.cpp - OS_NS_ctype.cpp - OS_NS_dirent.cpp - OS_NS_dlfcn.cpp - OS_NS_errno.cpp - OS_NS_fcntl.cpp - OS_NS_math.cpp - OS_NS_netdb.cpp - OS_NS_poll.cpp - OS_NS_pwd.cpp - OS_NS_regex.cpp - OS_NS_signal.cpp - OS_NS_stdio.cpp - OS_NS_stdlib.cpp - OS_NS_string.cpp - OS_NS_strings.cpp - OS_NS_stropts.cpp - OS_NS_sys_mman.cpp - OS_NS_sys_msg.cpp - OS_NS_sys_resource.cpp - OS_NS_sys_select.cpp - OS_NS_sys_sendfile.cpp - OS_NS_sys_shm.cpp - OS_NS_sys_socket.cpp - OS_NS_sys_stat.cpp - OS_NS_sys_time.cpp - OS_NS_sys_uio.cpp - OS_NS_sys_utsname.cpp - OS_NS_sys_wait.cpp - OS_NS_Thread.cpp - OS_NS_time.cpp - OS_NS_unistd.cpp - OS_NS_wchar.cpp - OS_QoS.cpp - OS_Thread_Adapter.cpp - OS_TLI.cpp - Pagefile_Memory_Pool.cpp - Parse_Node.cpp - PI_Malloc.cpp - Ping_Socket.cpp - Pipe.cpp - POSIX_Asynch_IO.cpp - POSIX_CB_Proactor.cpp - POSIX_Proactor.cpp - Priority_Reactor.cpp - Proactor.cpp - Proactor_Impl.cpp - Process.cpp - Process_Manager.cpp - Process_Mutex.cpp - Process_Semaphore.cpp - Profile_Timer.cpp - Reactor.cpp - Reactor_Impl.cpp - Reactor_Notification_Strategy.cpp - Reactor_Timer_Interface.cpp - Read_Buffer.cpp - Recursive_Thread_Mutex.cpp - Recyclable.cpp - Registry.cpp - Registry_Name_Space.cpp - Remote_Name_Space.cpp - Remote_Tokens.cpp - Rtems_init.c - RW_Mutex.cpp - RW_Process_Mutex.cpp - RW_Thread_Mutex.cpp - Sample_History.cpp - Sbrk_Memory_Pool.cpp - Sched_Params.cpp - Select_Reactor_Base.cpp - Semaphore.cpp - Service_Config.cpp - Service_Gestalt.cpp - Service_Manager.cpp - Service_Object.cpp - Service_Repository.cpp - Service_Types.cpp - Shared_Memory.cpp - Shared_Memory_MM.cpp - Shared_Memory_Pool.cpp - Shared_Memory_SV.cpp - Shared_Object.cpp - Sig_Adapter.cpp - Sig_Handler.cpp - Signal.cpp - SOCK.cpp - SOCK_Acceptor.cpp - SOCK_CODgram.cpp - Sock_Connect.cpp - SOCK_Connector.cpp - SOCK_Dgram.cpp - SOCK_Dgram_Bcast.cpp - SOCK_Dgram_Mcast.cpp - SOCK_IO.cpp - SOCK_Netlink.cpp - SOCK_SEQPACK_Acceptor.cpp - SOCK_SEQPACK_Association.cpp - SOCK_SEQPACK_Connector.cpp - SOCK_Stream.cpp - SPIPE.cpp - SPIPE_Acceptor.cpp - SPIPE_Addr.cpp - SPIPE_Connector.cpp - SPIPE_Stream.cpp - SString.cpp - Stack_Trace.cpp - Stats.cpp - String_Base_Const.cpp - SUN_Proactor.cpp - SV_Message.cpp - SV_Message_Queue.cpp - SV_Semaphore_Complex.cpp - SV_Semaphore_Simple.cpp - SV_Shared_Memory.cpp - Svc_Conf_Lexer.cpp - Svc_Conf_y.cpp - Synch_Options.cpp - System_Time.cpp - Task.cpp - Thread.cpp - Thread_Adapter.cpp - Thread_Control.cpp - Thread_Exit.cpp - Thread_Hook.cpp - Thread_Manager.cpp - Thread_Mutex.cpp - Thread_Semaphore.cpp - Throughput_Stats.cpp - Time_Value.cpp - Timeprobe.cpp - TLI.cpp - TLI_Acceptor.cpp - TLI_Connector.cpp - TLI_Stream.cpp - Token.cpp - Token_Collection.cpp - Token_Invariants.cpp - Token_Manager.cpp - Token_Request_Reply.cpp - TP_Reactor.cpp - Trace.cpp - TSS_Adapter.cpp - TTY_IO.cpp - UNIX_Addr.cpp - UPIPE_Acceptor.cpp - UPIPE_Connector.cpp - UPIPE_Stream.cpp - UTF16_Encoding_Converter.cpp - UTF32_Encoding_Converter.cpp - UTF8_Encoding_Converter.cpp - UUID.cpp - WFMO_Reactor.cpp - WIN32_Asynch_IO.cpp - WIN32_Proactor.cpp - XML_Svc_Conf.cpp - XTI_ATM_Mcast.cpp -) - -include_directories( - ${CMAKE_SOURCE_DIR}/externals - ${CMAKE_SOURCE_DIR}/externals/ace/PrecompiledHeaders - ${CMAKE_SOURCE_DIR}/externals/zlib -) - -# Needed for PCH support -set_source_files_properties(Atomic_Op_Sparc.c Rtems_init.c PROPERTIES LANGUAGE CXX) - -add_definitions(-DACE_BUILD_DLL) - -add_library(ace SHARED ${ace_STAT_SRCS}) - -add_native_precompiled_header(ace ${CMAKE_SOURCE_DIR}/externals/ace/PrecompiledHeaders/WinAcePCH) - -install(TARGETS ace RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}") diff --git a/externals/ace/CORBA_macros.h b/externals/ace/CORBA_macros.h deleted file mode 100644 index beab26b7f04..00000000000 --- a/externals/ace/CORBA_macros.h +++ /dev/null @@ -1,575 +0,0 @@ -// -*- C++ -*- - -// ============================================================================ -/** - * @file CORBA_macros.h - * - * $Id: CORBA_macros.h 80826 2008-03-04 14:51:23Z wotte $ - * - * Writing code that is portable between platforms with or without - * native C++ exceptions is hard. The following macros offer some - * help on this task, mostly oriented to making the ORB code and the - * IDL generated code portable. - * - * @author Nanbor Wang - * @author Aniruddha Gokhale - * @author Carlos O'Ryan , et al. - */ -// ============================================================================ - -// Macros for handling CORBA exceptions. - -#ifndef ACE_CORBA_MACROS_H -#define ACE_CORBA_MACROS_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -# if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -# endif /* ACE_LACKS_PRAGMA_ONCE */ - -#define ACE_ENV_POLLUTE_NAMES - -#include "ace/Exception_Macros.h" - -// The Windows MFC exception mechanism requires that a caught CException -// (including the CMemoryException in use here) be freed using its Delete() -// method. Thus, when MFC is in use and we're catching exceptions as a result -// of new(), the exception's Delete() method has to be called. No other -// platform imposes this sort of restriction/requirement. The Windows -// config stuff (at least for MSVC/MFC) defines a ACE_del_bad_alloc macro -// that works with its ACE_bad_alloc macro to implement this cleanup -// requirement. Since no other platform requires this, define it as -// empty here. -#if !defined (ACE_del_bad_alloc) -# define ACE_del_bad_alloc -#endif - -#if !defined (ACE_LACKS_DEPRECATED_MACROS) - -// If you wish to you use these macros for emulating exceptions on -// platforms which lack native exception support, you need to do the -// following: -// 1. Define a class Exception. You can name it as you please. This class -// should be at the root of the inheritance hierarchy of all the -// exceptions used in your application. It should define at a minimum -// the following pure virtual methods: -// a) _downcast () - Which allows narrowing of the base exception type to a -// derived type. -// b) _raise() - Which throws an exception of type Exception. -// -// Classes which derive from these should implement these operations. -// -// 2. Define a class Environment. You can name it as you please. This class -// is an exception holder. This class is always on the stack. It should -// support at a minimum the following methods: -// a) exception() - Which returns the Exception held in the current -// Environment. -// b) exception (Exception* foo) - Which replaces/sets the Exception -// held in the current Environment with foo. -// b) clear() - Which resets a particular instance of Environment. -// c) A copy constructor and an assignment operator. -// -// Note that the above description assumes that you use the following -// macros only within a particular domain. For example, if your -// application has to interoperate across domains, then you need to define -// an exception adapter to translate exceptions from one domain to -// exceptions in the other. Please refer to Stroustrup's book on how to do -// this. If your use case is this complex, you would be better off with -// going with native exceptions rather than emulated exceptions, though -// the macros should still work if you defined your adapter class as -// ACE_EXCEPTION_TYPE. - - -// The following macros assume that an environment variable is passed -// in/out of each function that can throw an exception. The type of the -// environment variable is defined by ACE_ENV_TYPE. - -#if !defined (ACE_ENV_TYPE) -# define ACE_ENV_TYPE CORBA::Environment -#endif /* ACE_ENV_TYPE */ - -// The name of the variable is defined by ACE_TRY_ENV. Below is the name -// that we use by default. If you wish to change it you can redefine -// ACE_TRY_ENV to change the default name. Also ACE_ADOPT_ENV allows the -// use of non-standard name within a scope. - -#if !defined (ACE_TRY_ENV) -# define ACE_TRY_ENV _ACE_CORBA_Environment_variable -#endif /* ACE_TRY_ENV */ - -// The base type of Exception from which all the other exception types are -// derived. You can set this to any type as you please. By default, it is -// set to CORBA::Exception. - -#if !defined (ACE_EXCEPTION_TYPE) -# define ACE_EXCEPTION_TYPE CORBA::Exception -#endif /* ACE_EXCEPTION_TYPE */ - -// This method is used to get the default value of the Environment -// variable. In the case of TAO, this variable is part of the TSS ORB -// resources and the method TAO_default_environment() returns the -// Environment variable. - -#if !defined (ACE_DEFAULT_GET_ENV_METHOD) -# define ACE_DEFAULT_GET_ENV_METHOD TAO_default_environment -#endif /* ACE_DEFAULT_GET_ENV_METHOD */ - -// This is the exception caught by ACE_CATCHANY. -#if !defined (ACE_ANY_EXCEPTION) -# define ACE_ANY_EXCEPTION ex -#endif /* ACE_ANY_EXCEPTION */ - -// Declare a new environment variable on the stack. The type of the -// environment variable is determined by ACE_ENV_TYPE. -#if defined (ACE_USES_NATIVE_EXCEPTIONS) -// Don't instantiate an emulated exception environment at all when -// using native C++ exception support. It won't be used. -# define ACE_DECLARE_NEW_ENV -#else -# define ACE_DECLARE_NEW_ENV \ - ACE_ENV_TYPE ACE_TRY_ENV -#endif /* ACE_USES_NATIVE_EXCEPTIONS */ - -// Provided for backward compatibility purposes. Don't use it in new code. -// Use the definition above along with defining ACE_ENV_TYPE. - -#if defined (ACE_ENV_POLLUTE_NAMES) -# define ACE_DECLARE_NEW_CORBA_ENV ACE_DECLARE_NEW_ENV -#endif /* ACE_ENV_POLLUTE_NAMES */ - -#if defined (ACE_USES_NATIVE_EXCEPTIONS) -// ----------------------------------------------------------------- - -// Provided for backward compatibility purposes. Don't use it in new code. -#if defined (ACE_ENV_POLLUTE_NAMES) -# define ACE_ADOPT_CORBA_ENV(ENV) -#endif /* ACE_ENV_POLLUTE_NAMES */ - -#define ACE_ADOPT_ENV (ENV) - -// No need to check. Native exceptions handle the control flow -// automatically when an exception occurs. -# define ACE_CHECK - -// Used when the function requires a return value. -# define ACE_CHECK_RETURN(RETV) - -// ACE_THROW_INT should not be used by the user. -# define ACE_THROW_INT(EXCEPTION) \ - throw EXCEPTION - -// Throwing an exception is easy. These two macros should _NOT_ be -// used within try blocks. -# define ACE_THROW(EXCEPTION) \ - throw EXCEPTION - -// Throwing an exception when the function requires a return value. -# define ACE_THROW_RETURN(EXCEPTION,RETV) \ - throw EXCEPTION - -// For compilers with native exceptions, we can simply use try to try. ;-) -// do {} while (0) is required to avoid compilation warnings. -# define ACE_TRY \ - do \ - { \ - try \ - { -# define ACE_TRY_NEW_ENV \ - do \ - { \ - try \ - { -# define ACE_TRY_EX(LABEL) \ - do \ - { \ - try \ - { - -// No need to check for exceptions within try block for compilers with -// native exceptions. -# define ACE_TRY_CHECK -# define ACE_TRY_CHECK_EX(LABEL) - -// Likewise, throwing exceptions within try blocks is easy. -# define ACE_TRY_THROW(EXCEPTION) throw EXCEPTION -# define ACE_TRY_THROW_EX(EXCEPTION,LABEL) throw EXCEPTION - -// Same thing for catch. -# define ACE_CATCH(EXCEPTION,VAR) \ - } \ - catch (EXCEPTION & VAR) \ - { \ - ACE_UNUSED_ARG (VAR); - -# define ACE_CATCHANY \ - ACE_CATCH(ACE_EXCEPTION_TYPE, ACE_ANY_EXCEPTION) - -# define ACE_CATCHALL \ - } \ - catch (...) \ - { - -# if defined (ACE_HAS_DEPRECATED_ACE_RETHROW) -# define ACE_RETHROW throw -# endif /* ACE_HAS_DEPRECATED_ACE_RETHROW */ - -// Rethrowing the exception from catch blocks. -# define ACE_RE_THROW throw -# define ACE_RE_THROW_EX(LABEL) throw - -// Close the catch block. -# define ACE_ENDTRY \ - } \ - } while (0) - -#else /* ! ACE_USES_NATIVE_EXCEPTIONS */ -// ----------------------------------------------------------------- - -// When handling compilers without native exceptions, things get a bit -// hairy. Exceptions are simulated using ACE_ENV_TYPE. The trick here is to -// make sure the flow-of-control can simulate the case when native -// exceptions occur... - -#if defined (ACE_ENV_POLLUTE_NAMES) -# define ACE_ADOPT_CORBA_ENV(ENV) ACE_ENV_TYPE &ACE_TRY_ENV = ENV -#endif /* ACE_ENV_POLLUTE_NAMES */ - -# define ACE_ADOPT_ENV(ENV) ACE_ENV_TYPE &ACE_TRY_ENV = ENV - -// Follow every statement that could throw exceptions with ACE_CHECK or -// ACE_CHECK_RETURN. These two macros should _NOT_ be used within try -// blocks. Use ACE_TRY_CHECK or ACE_TRY_CHECK_EX instead. -# define ACE_CHECK \ - if (ACE_TRY_ENV . exception () != 0) \ - return -// When function requires a return value -# define ACE_CHECK_RETURN(RETV) \ - if (ACE_TRY_ENV . exception () != 0) \ - return RETV - -// ACE_THROW_INT should not be used by the user. -# define ACE_THROW_INT(EXCEPTION) ACE_TRY_ENV.exception (new EXCEPTION) - -// Throwing exceptions will inevitably cause a return from the current -// function. These two macros should _NOT_ be used within try blocks. Use -// ACE_TRY_THROW or ACE_TRY_THROW_EX instead. -# define ACE_THROW(EXCEPTION) \ - do \ - { \ - ACE_TRY_ENV.exception (new EXCEPTION); \ - return; \ - } while (0) - -# define ACE_THROW_RETURN(EXCEPTION,RETV) \ - do \ - { \ - ACE_TRY_ENV.exception (new EXCEPTION); \ - return RETV; \ - } while (0) - -// ACE_TRY sets up flags to control program flow. ACE_TRY_FLAG acts like a -// one-shot flip-flop. When an exception occurs (detected using -// ACE_TRY_CHECK,) ACE_TRY_FLAG will be reset and the control goes back -// into ACE_TRY_LABEL. Since ACE_TRY_FLAG is reset, the try block won't get -// executed again and the control proceeds to the following catch blocks. -// ACE_EXCEPTION_NOT_CAUGHT flag is used to prevent catching an exception -// twice. This macro assumes there's already an ACE_ENV_TYPE variable -// ACE_TRY_ENV defined (which should be the case normally) -# define ACE_TRY \ - do { \ - int ACE_TRY_FLAG = 1; \ - int ACE_EXCEPTION_NOT_CAUGHT = 1; \ - ACE_TRY_LABEL: \ - if (ACE_TRY_FLAG) \ - do { - -// ACE_TRY_NEW_ENV functions like the macro ACE_TRY but defines a new -// ACE_ENV_TYPE variable ACE_TRY_ENV. It is most often used in the outer -// most function where no ACE_TRY_ENV is available. -# define ACE_TRY_NEW_ENV \ - do { \ - ACE_DECLARE_NEW_ENV;\ - int ACE_TRY_FLAG = 1; \ - int ACE_EXCEPTION_NOT_CAUGHT = 1; \ - ACE_TRY_LABEL: \ - if (ACE_TRY_FLAG) \ - do { - -// ACE_TRY_EX works exactly like ACE_TRY macro except the label used in the -// try block is customizable to avoid name clashing. It should be used when -// nested try blocks or multiple try blocks are required, in the same -// function. -# define ACE_TRY_EX(LABEL) \ - do { \ - int ACE_TRY_FLAG = 1; \ - int ACE_EXCEPTION_NOT_CAUGHT = 1; \ - ACE_TRY_LABEL ## LABEL: \ - if (ACE_TRY_FLAG) \ - do { - -// Check for exceptions within try blocks. -# define ACE_TRY_CHECK \ - { \ - if (ACE_TRY_ENV.exception () != 0) \ - { \ - ACE_TRY_FLAG = 0; \ - goto ACE_TRY_LABEL; \ - } \ - } - -// Checking exception within EX try blocks. -# define ACE_TRY_CHECK_EX(LABEL) \ - { \ - if (ACE_TRY_ENV.exception () != 0) \ - { \ - ACE_TRY_FLAG = 0; \ - goto ACE_TRY_LABEL ## LABEL; \ - } \ - } - -// Throwing exception within TRY blocks. -# define ACE_TRY_THROW(EXCEPTION) \ - { \ - ACE_TRY_ENV.exception (new EXCEPTION); \ - ACE_TRY_FLAG = 0; \ - goto ACE_TRY_LABEL; \ - } - -# define ACE_TRY_THROW_EX(EXCEPTION,LABEL) \ - { \ - ACE_TRY_ENV.exception (new EXCEPTION); \ - ACE_TRY_FLAG = 0; \ - goto ACE_TRY_LABEL ## LABEL; \ - } - -// When exceptions occur or try block finishes execution without exception, -// control will continue in the catch block. This macro first checks if -// there's any uncaught exception left. If all the conditions are met, we -// have caught an exception. It then resets ACE_EXCEPTION_NOT_CAUGHT to -// prevent subsequent catch blocks from catching the same exception again, -// and extracts out the underlying exception in ACE_TRY_ENV. We also make a -// copy of ACE_TRY_ENV in ACE_CAUGHT_ENV, in case we want to rethrow the -// exception. ACE_TRY_ENV is cleared out after the exception is caught so -// you should not use ACE_TRY_ENV within the catch block(You should use the -// exception directly). -# define ACE_CATCH(TYPE,VAR) \ - } while (0); \ - do \ - if (ACE_TRY_ENV.exception () != 0 && ACE_EXCEPTION_NOT_CAUGHT && \ - TYPE::_downcast(ACE_TRY_ENV.exception ()) != 0) \ - { \ - ACE_ENV_TYPE ACE_CAUGHT_ENV = ACE_TRY_ENV;\ - ACE_EXCEPTION_NOT_CAUGHT = 0; \ - TYPE &VAR = *TYPE::_downcast (ACE_CAUGHT_ENV.exception ()); \ - ACE_UNUSED_ARG (VAR); \ - ACE_TRY_ENV.clear (); - -// ACE_CATCHANY uses ACE_CATCH to catch all exceptions derived from -// ACE_EXCEPTION_TYPE -# define ACE_CATCHANY ACE_CATCH (ACE_EXCEPTION_TYPE, ACE_ANY_EXCEPTION) - -// Since there's no other exception for compilers without exception -// support, we simply catch all ACE_EXCEPTION_TYPE exceptions for -// ACE_CATCHALL. -# define ACE_CATCHALL ACE_CATCHANY - -# if defined (ACE_HAS_DEPRECATED_ACE_RETHROW) -# define ACE_RETHROW \ - do \ - ACE_TRY_ENV = ACE_CAUGHT_ENV; \ - while (0) -# endif /* ACE_HAS_DEPRECATED_ACE_RETHROW */ - -// Rethrowing exception within catch blocks. Notice that we depend on the -// ACE_CHECK/ACE_CHECK_RETURN following the ACE_ENDTRY, or ACE_TRY_CHECK/ -// ACE_TRY_CHECK_EX following the ACE_ENDTRY when the catch block is within -// another try block, to do the "Right Thing[TM]." -# define ACE_RE_THROW \ - do {\ - ACE_TRY_ENV = ACE_CAUGHT_ENV; \ - goto ACE_TRY_LABEL; \ - } while (0) -# define ACE_RE_THROW_EX(LABEL) \ - do {\ - ACE_TRY_ENV = ACE_CAUGHT_ENV; \ - goto ACE_TRY_LABEL ## LABEL; \ - } while (0) - -// Close the try block. Since exceptions may not get caught, and exceptions -// can also be rethrown from the catch block, it's always a good idea to -// follow ACE_ENDTRY with ACE_CHECK or ACE_TRY_CHECK (depending on the -// context.) -# define ACE_ENDTRY \ - } while (0); \ - } while (0) - -#endif /* ! ACE_USES_NATIVE_EXCEPTIONS */ - -#endif /* !ACE_LACKS_DEPRECATED_MACROS */ - -// ACE_HAS_EXCEPTIONS is not the same as ACE_NEW_THROWS_EXCEPTIONS. -#if defined(ACE_NEW_THROWS_EXCEPTIONS) - -# if defined (ACE_HAS_NEW_NOTHROW) - -# define ACE_NEW_THROW_EX(POINTER,CONSTRUCTOR,EXCEPTION) \ - do { POINTER = new (ACE_nothrow) CONSTRUCTOR; \ - if (POINTER == 0) { throw EXCEPTION; } \ - } while (0) - -# else - -# define ACE_NEW_THROW_EX(POINTER,CONSTRUCTOR,EXCEPTION) \ - do { try { POINTER = new CONSTRUCTOR; } \ - catch (ACE_bad_alloc) { ACE_del_bad_alloc throw EXCEPTION; } \ - } while (0) - -# endif /* ACE_HAS_NEW_NOTHROW */ - -#else /* ! ACE_NEW_THROWS_EXCEPTIONS */ - -# define ACE_NEW_THROW_EX(POINTER,CONSTRUCTOR,EXCEPTION) \ - do { POINTER = new CONSTRUCTOR; \ - if (POINTER == 0) { throw EXCEPTION; } \ - } while (0) - -#endif /* ACE_NEW_THROWS_EXCEPTIONS */ - -# define ACE_GUARD_THROW_EX(MUTEX,OBJ,LOCK,EXCEPTION) \ - ACE_Guard< MUTEX > OBJ (LOCK); \ - if (OBJ.locked () == 0) throw EXCEPTION; - -# define ACE_READ_GUARD_THROW_EX(MUTEX,OBJ,LOCK,EXCEPTION) \ - ACE_Read_Guard< MUTEX > OBJ (LOCK); \ - if (OBJ.locked () == 0) throw EXCEPTION; - -# define ACE_WRITE_GUARD_THROW_EX(MUTEX,OBJ,LOCK,EXCEPTION) \ - ACE_Write_Guard< MUTEX > OBJ (LOCK); \ - if (OBJ.locked () == 0) throw EXCEPTION; - -#if !defined (ACE_LACKS_DEPRECATED_MACROS) - -//@{ -/** - * @name Native C++ exceptions portability macros. - * - * The following macros are used to write code portable between platforms - * with and without native C++ exception support. Their main goal is to - * hide the presence of the ACE_ENV_TYPE argument, but they collaborate - * with the ACE_TRY_* macros to emulate the try/catch blocks. - */ - -/// Define a macro to emit code only when ACE_ENV_TYPE is used -#if !defined (ACE_USES_NATIVE_EXCEPTIONS) || defined (ACE_ENV_BKWD_COMPAT) -# define ACE_ENV_EMIT_CODE(X) X -#else -# define ACE_ENV_EMIT_CODE(X) -#endif /* ACE_USES_NATIVE_EXCEPTIONS && ! ACE_ENV_BKWD_COMPAT */ - -/// Another macro to emit code only when ACE_ENV_TYPE is used -#if !defined (ACE_USES_NATIVE_EXCEPTIONS) || defined (ACE_ENV_BKWD_COMPAT) -# define ACE_ENV_EMIT_CODE2(X,Y) X,Y -#else -# define ACE_ENV_EMIT_CODE2(X,Y) -#endif /* ACE_USES_NATIVE_EXCEPTIONS && ! ACE_ENV_BKWD_COMPAT */ - -/// Helper macro -#define ACE_ENV_EMIT_DUMMY - -/// Declare a ACE_ENV_TYPE argument as the last argument of a -/// function -/** - * Normally this macro is used as follows: - * - * void my_funct (int x, int y ACE_ENV_ARG_DECL); - * - * Its purpose is to provide developers (and users) with a mechanism to - * write code that is portable to platforms with and without native C++ - * exceptions. - */ -#define ACE_ENV_ARG_DECL \ - ACE_ENV_EMIT_CODE2(ACE_ENV_EMIT_DUMMY, \ - ACE_ENV_TYPE &ACE_TRY_ENV) - -/// Declare a ACE_ENV_TYPE argument with the default value obtained from -/// the ORB/application. -/** - * It is similar to ACE_ENV_ARG_DECL. The name of the default environment - * getter method needs to be changed when switching ORBs or when used with - * another application. - */ -#define ACE_ENV_ARG_DECL_WITH_DEFAULTS \ - ACE_ENV_EMIT_CODE2(ACE_ENV_EMIT_DUMMY, \ - ACE_ENV_TYPE &ACE_TRY_ENV = \ - ACE_DEFAULT_GET_ENV_METHOD ()) - -/// Declare a ACE_ENV_TYPE argument that is not used by the -/// function definition. -/** - * Similar to ACE_ENV_ARG_DECL, but the formal parameter name is dropped to - * avoid warnings about unused parameters - */ -#define ACE_ENV_ARG_DECL_NOT_USED \ - ACE_ENV_EMIT_CODE2(ACE_ENV_EMIT_DUMMY, \ - ACE_ENV_TYPE &) - -/// Declare a ACE_ENV_TYPE argument for methods that do not take any other -/// parameters -#define ACE_ENV_SINGLE_ARG_DECL \ - ACE_ENV_EMIT_CODE(ACE_ENV_TYPE &ACE_TRY_ENV) - -/// Declare a ACE_ENV_TYPE argument with a default value for methods that -/// do not take any other parameters. The name of the default environment -/// getter method needs to be changed when switching ORBs or when used in -/// another application. -#define ACE_ENV_SINGLE_ARG_DECL_WITH_DEFAULTS \ - ACE_ENV_EMIT_CODE(ACE_ENV_TYPE &ACE_TRY_ENV = \ - ACE_DEFAULT_GET_ENV_METHOD ()) - -/// Declare a ACE_ENV_TYPE argument for methods which don't use it. -#define ACE_ENV_SINGLE_ARG_DECL_NOT_USED \ - ACE_ENV_EMIT_CODE(ACE_ENV_TYPE &) - -/// Use the ACE_ENV_TYPE argument in a nested call -#define ACE_ENV_ARG_PARAMETER \ - ACE_ENV_EMIT_CODE2(ACE_ENV_EMIT_DUMMY, \ - ACE_TRY_ENV) - -/// Use the ACE_ENV_TYPE argument in a nested call, assuming that the -/// called function takes only the ACE_TRY_ENV argument. -#define ACE_ENV_SINGLE_ARG_PARAMETER \ - ACE_ENV_EMIT_CODE(ACE_TRY_ENV) - -/// Eliminate unused argument warnings about ACE_TRY_ENV -#define ACE_ENV_ARG_NOT_USED \ - ACE_ENV_EMIT_CODE(ACE_UNUSED_ARG(ACE_TRY_ENV)) -//@} - -#if !defined (ACE_USES_NATIVE_EXCEPTIONS) -// This thing can be moved above when we drop ACE_ENV_BKWD_COMPAT. -# define ACE_ENV_RAISE(ex) ACE_TRY_ENV.exception (ex) -#else -# define ACE_ENV_RAISE(ex) (ex)->_raise () -#endif /* ACE_USES_NATIVE_EXCEPTIONS */ - -// ============================================================ - -// Print out a TAO exception. This is not CORBA compliant. -# define ACE_PRINT_TAO_EXCEPTION(EX,INFO) \ - EX._tao_print_exception (INFO) - -// Print out a CORBA exception. There is not portable way to -// dump a CORBA exception. If you are using other ORB implementation, -// redefine the macro to get what you want. -# if !defined ACE_PRINT_EXCEPTION -# define ACE_PRINT_EXCEPTION(EX,INFO) ACE_PRINT_TAO_EXCEPTION(EX,INFO) -# endif /* ACE_PRINT_EXCEPTION */ - -#endif /* !ACE_LACKS_DEPRECATED_MACROS */ - -#include /**/ "ace/post.h" - -#endif /* ACE_CORBA_MACROS_H */ diff --git a/externals/ace/Cache_Map_Manager_T.cpp b/externals/ace/Cache_Map_Manager_T.cpp deleted file mode 100644 index f87031eb0d7..00000000000 --- a/externals/ace/Cache_Map_Manager_T.cpp +++ /dev/null @@ -1,420 +0,0 @@ -// $Id: Cache_Map_Manager_T.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#ifndef ACE_CACHE_MAP_MANAGER_T_CPP -#define ACE_CACHE_MAP_MANAGER_T_CPP - -#include "ace/Cache_Map_Manager_T.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -#pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Log_Msg.h" -#include "ace/Malloc_Base.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Cache_Map_Manager_T.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Cache_Map_Manager) - -ACE_ALLOC_HOOK_DEFINE(ACE_Cache_Map_Iterator) - -ACE_ALLOC_HOOK_DEFINE(ACE_Cache_Map_Reverse_Iterator) - -#define ACE_T1 class KEY, class VALUE, class CMAP_TYPE, class ITERATOR_IMPL, class REVERSE_ITERATOR_IMPL, class CACHING_STRATEGY, class ATTRIBUTES -#define ACE_T2 KEY, VALUE, CMAP_TYPE, ITERATOR_IMPL, REVERSE_ITERATOR_IMPL, CACHING_STRATEGY, ATTRIBUTES - -template -ACE_Cache_Map_Manager::ACE_Cache_Map_Manager (CACHING_STRATEGY &caching_s, - size_t size, - ACE_Allocator *alloc) - : caching_strategy_ (caching_s) -{ - if (this->open (size, alloc) == -1) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_Cache_Map_Manager::ACE_Cache_Map_Manager"))); - -} - -template -ACE_Cache_Map_Manager::~ACE_Cache_Map_Manager (void) -{ - this->close (); -} - -template int -ACE_Cache_Map_Manager::open (size_t length, - ACE_Allocator *alloc) -{ - return this->map_.open (length, - alloc); -} - -template int -ACE_Cache_Map_Manager::close (void) -{ - return this->map_.close (); -} - -template int -ACE_Cache_Map_Manager::bind (const KEY &key, - const VALUE &value) -{ - // Insert an entry which has the and the which - // is the combination of the and the attributes of the - // caching strategy. - CACHE_VALUE cache_value (value, - this->caching_strategy_.attributes ()); - - int bind_result = this->map_.bind (key, - cache_value); - - if (bind_result != -1) - { - - int result = this->caching_strategy_.notify_bind (bind_result, - cache_value.second ()); - - if (result == -1) - { - - this->map_.unbind (key); - - // Unless the notification goes thru the bind operation is - // not complete. - bind_result = -1; - - } - - } - - return bind_result; -} - - -template int -ACE_Cache_Map_Manager::rebind (const KEY &key, - const VALUE &value) -{ - CACHE_VALUE cache_value (value, - this->caching_strategy_.attributes ()); - - int rebind_result = this->map_.rebind (key, - cache_value); - - if (rebind_result != -1) - { - - int result = this->caching_strategy_.notify_rebind (rebind_result, - cache_value.second ()); - - if (result == -1) - { - - // Make sure the unbind operation is done only when the - // notification fails after a bind which is denoted by - // rebind_result = 0 - if (rebind_result == 0) - this->map_.unbind (key); - - // Unless the notification goes thru the rebind operation is - // not complete. - rebind_result = -1; - - } - - } - - return rebind_result; -} - - -template int -ACE_Cache_Map_Manager::rebind (const KEY &key, - const VALUE &value, - VALUE &old_value) -{ - CACHE_VALUE cache_value (value, - this->caching_strategy_.attributes ()); - - CACHE_VALUE old_cache_value (old_value, - this->caching_strategy_.attributes ()); - - int rebind_result = this->map_.rebind (key, - cache_value, - old_cache_value); - - if (rebind_result != -1) - { - - int result = this->caching_strategy_.notify_rebind (rebind_result, - cache_value.second ()); - - if (result == -1) - { - - // Make sure the unbind operation is done only when the - // notification fails after a bind which is denoted by - // rebind_result = 0 - if (rebind_result == 0) - this->map_.unbind (key); - - // Unless the notification goes thru the rebind operation is - // not complete. - rebind_result = -1; - - } - else - { - - old_value = old_cache_value.first (); - - } - - } - - return rebind_result; -} - -template int -ACE_Cache_Map_Manager::rebind (const KEY &key, - const VALUE &value, - KEY &old_key, - VALUE &old_value) -{ - CACHE_VALUE cache_value (value, - this->caching_strategy_.attributes ()); - - CACHE_VALUE old_cache_value (old_value, - this->caching_strategy_.attributes ()); - - int rebind_result = this->map_.rebind (key, - cache_value, - old_key, - old_cache_value); - - if (rebind_result != -1) - { - - int result = this->caching_strategy_.notify_rebind (rebind_result, - cache_value.second ()); - - if (result == -1) - { - - // Make sure the unbind operation is done only when the - // notification fails after a bind which is denoted by - // rebind_result = 0 - if (rebind_result == 0) - this->map_.unbind (key); - - // Unless the notification goes thru the rebind operation is - // not complete. - rebind_result = -1; - - } - else - { - - old_value = old_cache_value.first (); - - } - - } - - return rebind_result; -} - -template int -ACE_Cache_Map_Manager::trybind (const KEY &key, - VALUE &value) -{ - CACHE_VALUE cache_value (value, - this->caching_strategy_.attributes ()); - - int trybind_result = this->map_.trybind (key, - cache_value); - - if (trybind_result != -1) - { - - int result = this->caching_strategy_.notify_trybind (trybind_result, - cache_value.second ()); - - if (result == -1) - { - - // If the entry has got inserted into the map, it is removed - // due to failure. - if (trybind_result == 0) - this->map_.unbind (key); - - trybind_result = -1; - - } - else - { - - // If an attempt is made to bind an existing entry the value - // is overwritten with the value from the map. - if (trybind_result == 1) - value = cache_value.first (); - - } - - } - - return trybind_result; -} - -template int -ACE_Cache_Map_Manager::find (const KEY &key, - VALUE &value) -{ - // Lookup the key and populate the . - CACHE_VALUE cache_value; - - int find_result = this->map_.find (key, - cache_value); - - if (find_result != -1) - { - - int result = this->caching_strategy_.notify_find (find_result, - cache_value.second ()); - - // Unless the find and notification operations go thru, this - // method is not successful. - if (result == -1) - find_result = -1; - else - { - - // Since the has now changed after the - // notification, we need to bind to the map again. - int rebind_result = this->map_.rebind (key, - cache_value); - if (rebind_result == -1) - find_result = -1; - else - value = cache_value.first (); - - } - - } - - return find_result; -} - -template int -ACE_Cache_Map_Manager::find (const KEY &key) -{ - // Lookup the key and populate the . - CACHE_VALUE cache_value; - - int find_result = this->map_.find (key, - cache_value); - - if (find_result != -1) - { - - int result = this->caching_strategy_.notify_find (find_result, - cache_value.second ()); - - // Unless the find and notification operations go thru, this - // method is not successful. - if (result == -1) - find_result = -1; - else - { - - // Since the has now changed after the - // notification, we need to bind to the map again. - int rebind_result = this->map_.rebind (key, - cache_value); - - if (rebind_result == -1) - find_result = -1; - - } - - } - - return find_result; -} - - -template int -ACE_Cache_Map_Manager::unbind (const KEY &key) -{ - // Remove the entry from the cache. - CACHE_VALUE cache_value; - - int unbind_result = this->map_.unbind (key, - cache_value); - - if (unbind_result != -1) - { - - int result = this->caching_strategy_.notify_unbind (unbind_result, - cache_value.second ()); - - if (result == -1) - unbind_result = -1; - - } - - return unbind_result; -} - -template int -ACE_Cache_Map_Manager::unbind (const KEY &key, - VALUE &value) -{ - // Remove the entry from the cache. - CACHE_VALUE cache_value; - - int unbind_result = this->map_.unbind (key, - cache_value); - - if (unbind_result != -1) - { - - int result = this->caching_strategy_.notify_unbind (unbind_result, - cache_value.second ()); - - if (result == -1) - unbind_result = -1; - else - value = cache_value.first (); - - } - - return unbind_result; -} - -template void -ACE_Cache_Map_Manager::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - this->map_.dump (); - - this->caching_strategy_.dump (); -#endif /* ACE_HAS_DUMP */ -} - -#undef ACE_T1 -#undef ACE_T2 - -template -ACE_Cache_Map_Iterator::~ACE_Cache_Map_Iterator (void) -{ -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_CACHE_MAP_MANAGER_T_CPP */ diff --git a/externals/ace/Cache_Map_Manager_T.h b/externals/ace/Cache_Map_Manager_T.h deleted file mode 100644 index 060a8b38aac..00000000000 --- a/externals/ace/Cache_Map_Manager_T.h +++ /dev/null @@ -1,405 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Cache_Map_Manager_T.h - * - * $Id: Cache_Map_Manager_T.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Kirthika Parameswaran - */ -//============================================================================= - -#ifndef ACE_CACHE_MAP_MANAGER_T_H -#define ACE_CACHE_MAP_MANAGER_T_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Default_Constants.h" -#include "ace/Global_Macros.h" -#include "ace/Pair_T.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Forward declaration. -class ACE_Allocator; - -#define ACE_Cache_Map_Iterator ACMI -#define ACE_Cache_Map_Reverse_Iterator ACMRI - -template -class ACE_Cache_Map_Iterator; - -template -class ACE_Cache_Map_Reverse_Iterator; - -// For linkers that cant grok long names. -#define ACE_Cache_Map_Manager ACMM - -/** - * @class ACE_Cache_Map_Manager - * - * @brief Defines a abstraction that will purge entries from a map. - * - * The will manage the map it contains - * and provide purging on demand from the map. The strategy for - * caching is decided by the user and provided to the Cache - * Manager. The Cache Manager acts as a agent and communicates - * between the Map and the Strategy for purging entries from the - * map. - * No locking mechanism provided since locking at this level - * isn't efficient. Locking has to be provided by the - * application. - */ -template -class ACE_Cache_Map_Manager -{ -public: - - // = Traits. - typedef KEY key_type; - typedef VALUE mapped_type; - typedef CMAP_TYPE map_type; - typedef CACHING_STRATEGY caching_strategy_type; - - typedef ITERATOR_IMPL ITERATOR_IMPLEMENTATION; - typedef REVERSE_ITERATOR_IMPL REVERSE_ITERATOR_IMPLEMENTATION; - - friend class ACE_Cache_Map_Iterator; - friend class ACE_Cache_Map_Reverse_Iterator; - - // = ACE-style iterator typedefs. - typedef ACE_Cache_Map_Iterator - ITERATOR; - typedef ACE_Cache_Map_Reverse_Iterator - REVERSE_ITERATOR; - - // = STL-style iterator typedefs. - typedef ITERATOR - iterator; - typedef REVERSE_ITERATOR - reverse_iterator; - - /** - * The actual value mapped to the key in the map. The - * are used by the strategy and is transparent to the user of this - * class. - */ - typedef ACE_Pair CACHE_VALUE; - - // = Initialization and termination methods. - - /// Initialize a with and - /// @a size entries. - ACE_Cache_Map_Manager (CACHING_STRATEGY &caching_strategy, - size_t size = ACE_DEFAULT_MAP_SIZE, - ACE_Allocator *alloc = 0); - - /// Close down a and release dynamically allocated - /// resources. - virtual ~ACE_Cache_Map_Manager (void); - - /// Initialize a cache with size @a length. - int open (size_t length = ACE_DEFAULT_MAP_SIZE, - ACE_Allocator *alloc = 0); - - /// Close down a cache and release dynamically allocated resources. - int close (void); - - /** - * Associate @a key with @a value. If @a key is already in the CMAP_TYPE - * then the ENTRY is not changed. Returns 0 if a new entry is bound - * successfully, returns 1 if an attempt is made to bind an existing - * entry, and returns -1 if failures occur. - */ - int bind (const KEY &key, - const VALUE &value); - - /** - * Lookup entry in the cache. If it is not found, returns -1. - * If the @a key is located in the CMAP_TYPE object, the CACHING_STRATEGY is - * notified of it via notify_find (int result, ATTRIBUTES &attribute). - * If notify_find also returns 0 (success), then this function returns - * 0 (success) and sets the cached value in @a value. - */ - int find (const KEY &key, - VALUE &value); - - /** - * Lookup entry in the cache. If it is not found, returns -1. - * If the @a key is located in the CMAP_TYPE object, the CACHING_STRATEGY is - * notified of it via notify_find (int result, ATTRIBUTES &attribute). - * If notify_find also returns 0 (success), then this function returns - * 0 (success). - */ - int find (const KEY &key); - - /** - * Reassociate the @a key with @a value. If the @a key already exists - * in the cache then returns 1, on a new bind returns 0 and returns - * -1 in case of any failures. - */ - int rebind (const KEY &key, - const VALUE &value); - - /** - * Reassociate @a key with @a value, storing the old value into the - * "out" parameter @a old_value. The function fails if @a key is not - * in the cache for caches that do not allow user specified keys. - * However, for caches that allow user specified keys, if the key is - * not in the cache, a new @a key / @a value association is created. - */ - int rebind (const KEY &key, - const VALUE &value, - VALUE &old_value); - - /** - * Reassociate @a key with @a value, storing the old key and value - * into the "out" parameters @a old_key and @a old_value. The - * function fails if @a key is not in the cache for caches that do - * not allow user specified keys. However, for caches that allow - * user specified keys, if the key is not in the cache, a new - * @a key / @a value association is created. - */ - int rebind (const KEY &key, - const VALUE &value, - KEY &old_key, - VALUE &old_value); - - /** - * Associate @a key with @a value if and only if @a key is not in the - * cache. If @a key is already in the cache, then the @a value - * parameter is overwritten with the existing value in the - * cache. Returns 0 if a new @a key / @a value association is created. - * Returns 1 if an attempt is made to bind an existing entry. This - * function fails for maps that do not allow user specified keys. - */ - int trybind (const KEY &key, - VALUE &value); - - /// Remove @a key from the cache. - int unbind (const KEY &key); - - /// Remove @a key from the cache, and return the @a value associated with - /// @a key. - int unbind (const KEY &key, - VALUE &value); - - /// Remove entries from the cache depending upon the strategy. - int purge (void); - - /// Return the current size of the cache. - size_t current_size (void) const; - - /// Return the total size of the cache. - size_t total_size (void) const; - - /// Dumps the state of the object. - void dump (void) const; - - // = STL styled iterator factory functions. - - /// Return forward iterator. - ITERATOR begin (void); - ITERATOR end (void); - - /// Return reverse iterator. - REVERSE_ITERATOR rbegin (void); - REVERSE_ITERATOR rend (void); - - /// The map managed by the Cache_Map_Manager. - CMAP_TYPE &map (void); - - /// The caching strategy used on the cache. - CACHING_STRATEGY &caching_strategy (void); - -protected: - - /// The underlying map which needs to be cached. - CMAP_TYPE map_; - - /// The strategy to be followed for caching entries in the map. - CACHING_STRATEGY &caching_strategy_; - -private: - - // = Disallow these operations. - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Cache_Map_Manager &)) - ACE_UNIMPLEMENTED_FUNC (ACE_Cache_Map_Manager (const ACE_Cache_Map_Manager &)) - -}; - -/** - * @class ACE_Cache_Map_Iterator - * - * @brief Defines a iterator for the Cache_Map_Manager. - * - * Implementation to be provided by the iterator of the map - * managed by the ACE_Cache_Map_Manager. - */ -template -class ACE_Cache_Map_Iterator -{ - -public: - - // = Traits. - /// The actual value mapped to the key in the cache. The - /// are used by the strategy and is transperant to the cache user. - typedef ACE_Reference_Pair - value_type; - typedef ACE_Pair - CACHE_VALUE; - - // = Initialisation and termination methods. - - ACE_Cache_Map_Iterator (const IMPLEMENTATION &iterator_impl); - - /// Copy constructor. - ACE_Cache_Map_Iterator (const ACE_Cache_Map_Iterator &rhs); - - virtual ~ACE_Cache_Map_Iterator (void); - - // = Iteration methods. - - /// assignment operator. - ACE_Cache_Map_Iterator &operator= - (const ACE_Cache_Map_Iterator &rhs); - - /// Comparision operators. - bool operator== (const ACE_Cache_Map_Iterator &rhs) const; - bool operator!= (const ACE_Cache_Map_Iterator &rhs) const; - - /// Returns a reference to the internal element @c this is pointing - /// to. - ACE_Reference_Pair operator* (void) const; - - // = STL styled iteration, compare, and reference functions. - - /// Prefix advance - ACE_Cache_Map_Iterator &operator++ (void); - - /// Postfix advance. - ACE_Cache_Map_Iterator operator++ (int); - - /// Prefix reverse. - ACE_Cache_Map_Iterator &operator-- (void); - - /// Postfix reverse. - ACE_Cache_Map_Iterator operator-- (int); - - /// Returns the iterator of the internal map in the custody of the - /// Cache_Map_Manager. - IMPLEMENTATION &iterator_implementation (void); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - /// The actual iterator which iterates internally on the map - /// belonging to the Cache_Map_Manager. - IMPLEMENTATION iterator_implementation_; -}; - -/** - * @class ACE_Cache_Map_Reverse_Iterator - * - * @brief Defines a reverse iterator for the Cache_Map_Manager. - * - * Implementation to be provided by the reverse iterator of the map - * managed by thr Cache_Map_manager. - */ -template -class ACE_Cache_Map_Reverse_Iterator -{ -public: - - // = Traits. - /// The actual value mapped to the key in the cache. The - /// are used by the strategy and is transperant to the cache user. - typedef ACE_Reference_Pair value_type; - typedef ACE_Pair CACHE_VALUE; - - // = Initialisation and termination methods. - - ACE_Cache_Map_Reverse_Iterator (const REVERSE_IMPLEMENTATION &iterator_impl); - - /// Copy constructor. - ACE_Cache_Map_Reverse_Iterator (const ACE_Cache_Map_Reverse_Iterator &rhs); - - ~ACE_Cache_Map_Reverse_Iterator (void); - - // = Iteration methods. - - /// Assignment operator. - ACE_Cache_Map_Reverse_Iterator &operator= - (const ACE_Cache_Map_Reverse_Iterator &rhs); - - /// Comparision operators. - bool operator== (const ACE_Cache_Map_Reverse_Iterator &rhs) const; - bool operator!= (const ACE_Cache_Map_Reverse_Iterator &rhs) const; - - /// Returns a reference to the internal element @c this is pointing - /// to. - ACE_Reference_Pair operator* (void) const; - - // = STL styled iteration, compare, and reference functions. - - /// Prefix advance - ACE_Cache_Map_Reverse_Iterator &operator++ (void); - - /// Postfix advance. - ACE_Cache_Map_Reverse_Iterator operator++ (int); - - /// Prefix reverse. - ACE_Cache_Map_Reverse_Iterator &operator-- (void); - - /// Postfix reverse. - ACE_Cache_Map_Reverse_Iterator operator-- (int); - - /// Returns the iterator of the internal map in the custody of the - /// Cache_Map_Manager. - REVERSE_IMPLEMENTATION &iterator_implementation (void); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - /// The actual iterator which iterates internally on the map - /// belonging to the Cache_Map_Manager. - REVERSE_IMPLEMENTATION reverse_iterator_implementation_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Cache_Map_Manager_T.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Cache_Map_Manager_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Cache_Map_Manager_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" - -#endif /* ACE_CACHE_MAP_MANAGER_T_H */ diff --git a/externals/ace/Cache_Map_Manager_T.inl b/externals/ace/Cache_Map_Manager_T.inl deleted file mode 100644 index bcd48bd33e9..00000000000 --- a/externals/ace/Cache_Map_Manager_T.inl +++ /dev/null @@ -1,245 +0,0 @@ -// -*- C++ -*- -// -//$Id: Cache_Map_Manager_T.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template ACE_INLINE int -ACE_Cache_Map_Manager::purge (void) -{ - return this->caching_strategy ().caching_utility ().clear_cache (this->map_, - this->caching_strategy ().purge_percent ()); -} - -template ACE_INLINE size_t -ACE_Cache_Map_Manager::current_size (void) const -{ - return this->map_.current_size (); -} - -template ACE_INLINE size_t -ACE_Cache_Map_Manager::total_size (void) const -{ - return this->map_.total_size (); -} - -template ACE_INLINE CMAP_TYPE & -ACE_Cache_Map_Manager::map (void) -{ - return this->map_; -} - -template ACE_INLINE CACHING_STRATEGY & -ACE_Cache_Map_Manager::caching_strategy (void) -{ - return this->caching_strategy_; -} - -template ACE_INLINE ACE_Cache_Map_Iterator -ACE_Cache_Map_Manager::begin (void) -{ - return ITERATOR (this->map_.begin ()); -} - -template ACE_INLINE ACE_Cache_Map_Iterator -ACE_Cache_Map_Manager::end (void) -{ - return ITERATOR (this->map_.end ()); -} - -template ACE_INLINE ACE_Cache_Map_Reverse_Iterator -ACE_Cache_Map_Manager::rbegin (void) -{ - return REVERSE_ITERATOR (this->map_.rbegin ()); -} -template ACE_INLINE ACE_Cache_Map_Reverse_Iterator -ACE_Cache_Map_Manager::rend (void) -{ - return REVERSE_ITERATOR (this->map_.rend ()); -} - -//////////////////////////////////////////////////////////////////////////////// - -template ACE_INLINE -ACE_Cache_Map_Iterator::ACE_Cache_Map_Iterator (const ACE_Cache_Map_Iterator &rhs) - : iterator_implementation_ (rhs.iterator_implementation_) -{ -} - -template ACE_INLINE ACE_Cache_Map_Iterator & -ACE_Cache_Map_Iterator::operator= (const ACE_Cache_Map_Iterator &rhs) -{ - this->iterator_implementation_ = rhs.iterator_implementation_; - return *this; -} - -template ACE_INLINE bool -ACE_Cache_Map_Iterator::operator== (const ACE_Cache_Map_Iterator &rhs) const -{ - return this->iterator_implementation_ == rhs.iterator_implementation_; -} - -template ACE_INLINE bool -ACE_Cache_Map_Iterator::operator!= (const ACE_Cache_Map_Iterator &rhs) const -{ - return this->iterator_implementation_ != rhs.iterator_implementation_; -} - -template ACE_INLINE ACE_Reference_Pair -ACE_Cache_Map_Iterator::operator* (void) const -{ - value_type retn ((*this->iterator_implementation_).ext_id_, - (*this->iterator_implementation_).int_id_.first ()); - return retn; -} - -template ACE_INLINE -ACE_Cache_Map_Iterator & -ACE_Cache_Map_Iterator::operator++ (void) -{ - ++this->iterator_implementation_; - return *this; -} - -template ACE_INLINE -ACE_Cache_Map_Iterator -ACE_Cache_Map_Iterator::operator++ (int) -{ - ACE_Cache_Map_Iterator retn = *this; - ++this->iterator_implementation_; - return retn; -} - -template ACE_INLINE -ACE_Cache_Map_Iterator & -ACE_Cache_Map_Iterator::operator-- (void) -{ - --this->iterator_implementation_; - return *this; -} - -template ACE_INLINE -ACE_Cache_Map_Iterator -ACE_Cache_Map_Iterator::operator-- (int) -{ - ACE_Cache_Map_Iterator retn = *this; - --this->iterator_implementation_; - return retn; -} - -template ACE_INLINE void -ACE_Cache_Map_Iterator::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - this->iterator_implementation_.dump (); -#endif /* ACE_HAS_DUMP */ -} - -template ACE_INLINE -ACE_Cache_Map_Iterator::ACE_Cache_Map_Iterator (const IMPLEMENTATION &iterator_impl) - : iterator_implementation_ (iterator_impl) -{ -} - -template ACE_INLINE IMPLEMENTATION & -ACE_Cache_Map_Iterator::iterator_implementation (void) -{ - return this->iterator_implementation_; -} - -//////////////////////////////////////////////////////////////////////////////// - -template ACE_INLINE -ACE_Cache_Map_Reverse_Iterator::ACE_Cache_Map_Reverse_Iterator (const ACE_Cache_Map_Reverse_Iterator &rhs) - : reverse_iterator_implementation_ (rhs.reverse_iterator_implementation_) -{ -} - -template ACE_INLINE -ACE_Cache_Map_Reverse_Iterator::~ACE_Cache_Map_Reverse_Iterator (void) -{ -} - -template ACE_INLINE ACE_Cache_Map_Reverse_Iterator & -ACE_Cache_Map_Reverse_Iterator::operator= (const ACE_Cache_Map_Reverse_Iterator &rhs) -{ - this->reverse_iterator_implementation_ = rhs.reverse_iterator_implementation_; - return *this; -} - -template ACE_INLINE bool -ACE_Cache_Map_Reverse_Iterator::operator== (const ACE_Cache_Map_Reverse_Iterator &rhs) const -{ - return this->reverse_iterator_implementation_ == rhs.reverse_iterator_implementation_; -} - -template ACE_INLINE bool -ACE_Cache_Map_Reverse_Iterator::operator!= (const ACE_Cache_Map_Reverse_Iterator &rhs) const -{ - return this->reverse_iterator_implementation_ != rhs.reverse_iterator_implementation_; -} - -template ACE_INLINE ACE_Reference_Pair -ACE_Cache_Map_Reverse_Iterator::operator* (void) const -{ - value_type retv ((*this->reverse_iterator_implementation_).ext_id_, - (*this->reverse_iterator_implementation_).int_id_.first ()); - return retv; -} - -template ACE_INLINE -ACE_Cache_Map_Reverse_Iterator & -ACE_Cache_Map_Reverse_Iterator::operator++ (void) -{ - ++this->reverse_iterator_implementation_; - return *this; -} - -template ACE_INLINE -ACE_Cache_Map_Reverse_Iterator -ACE_Cache_Map_Reverse_Iterator::operator++ (int) -{ - ACE_Cache_Map_Reverse_Iterator retn = *this; - ++this->reverse_iterator_implementation_; - return retn; -} - -template ACE_INLINE -ACE_Cache_Map_Reverse_Iterator & -ACE_Cache_Map_Reverse_Iterator::operator-- (void) -{ - --this->reverse_iterator_implementation_; - return *this; -} - -template ACE_INLINE -ACE_Cache_Map_Reverse_Iterator -ACE_Cache_Map_Reverse_Iterator::operator-- (int) -{ - ACE_Cache_Map_Reverse_Iterator retn = *this; - --this->reverse_iterator_implementation_; - return retn; -} - - -template ACE_INLINE void -ACE_Cache_Map_Reverse_Iterator::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - this->reverse_iterator_implementation_.dump (); -#endif /* ACE_HAS_DUMP */ -} - -template ACE_INLINE -ACE_Cache_Map_Reverse_Iterator::ACE_Cache_Map_Reverse_Iterator (const REVERSE_IMPLEMENTATION &iterator_impl) - : reverse_iterator_implementation_(iterator_impl) -{ -} - -template ACE_INLINE REVERSE_IMPLEMENTATION & -ACE_Cache_Map_Reverse_Iterator::iterator_implementation (void) -{ - return this->reverse_iterator_implementation_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Cached_Connect_Strategy_T.cpp b/externals/ace/Cached_Connect_Strategy_T.cpp deleted file mode 100644 index 077c6d6a9ae..00000000000 --- a/externals/ace/Cached_Connect_Strategy_T.cpp +++ /dev/null @@ -1,734 +0,0 @@ -//$Id: Cached_Connect_Strategy_T.cpp 82771 2008-09-17 18:47:48Z johnnyw $ - -#ifndef ACE_CACHED_CONNECT_STRATEGY_T_CPP -#define ACE_CACHED_CONNECT_STRATEGY_T_CPP - -#include "ace/Cached_Connect_Strategy_T.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -#pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/ACE.h" -#include "ace/Service_Repository.h" -#include "ace/Service_Types.h" -#include "ace/Thread_Manager.h" -#include "ace/WFMO_Reactor.h" -#include "ace/Pair_T.h" - -#define ACE_T1 class SVC_HANDLER, ACE_PEER_CONNECTOR_1, class CACHING_STRATEGY, class ATTRIBUTES, class MUTEX -#define ACE_T2 SVC_HANDLER, ACE_PEER_CONNECTOR_2, CACHING_STRATEGY, ATTRIBUTES, MUTEX - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template -ACE_Cached_Connect_Strategy_Ex::ACE_Cached_Connect_Strategy_Ex -(CACHING_STRATEGY &caching_s, - ACE_Creation_Strategy *cre_s, - ACE_Concurrency_Strategy *con_s, - ACE_Recycling_Strategy *rec_s, - MUTEX *lock, - int delete_lock) - : CCSBASE (cre_s, con_s, rec_s, lock, delete_lock), - connection_cache_ (caching_s) -{ - if (this->open (cre_s, con_s, rec_s) == -1) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_Cached_Connect_Strategy_Ex\n"))); -} - -template -ACE_Cached_Connect_Strategy_Ex::~ACE_Cached_Connect_Strategy_Ex (void) -{ - cleanup (); -} - - -template int -ACE_Cached_Connect_Strategy_Ex::check_hint_i -(SVC_HANDLER *&sh, - const ACE_PEER_CONNECTOR_ADDR &remote_addr, - ACE_Time_Value *timeout, - const ACE_PEER_CONNECTOR_ADDR &local_addr, - bool reuse_addr, - int flags, - int perms, - ACE_Hash_Map_Entry, ACE_Pair > *&entry, - int &found) -{ - ACE_UNUSED_ARG (remote_addr); - ACE_UNUSED_ARG (timeout); - ACE_UNUSED_ARG (local_addr); - ACE_UNUSED_ARG (reuse_addr); - ACE_UNUSED_ARG (flags); - ACE_UNUSED_ARG (perms); - - found = 0; - - // Get the recycling act for the svc_handler - CONNECTION_CACHE_ENTRY *possible_entry = - (CONNECTION_CACHE_ENTRY *) sh->recycling_act (); - - // Check to see if the hint svc_handler has been closed down - if (possible_entry->ext_id_.recycle_state () == ACE_RECYCLABLE_CLOSED) - { - // If close, decrement refcount - if (possible_entry->ext_id_.decrement () == 0) - { - // If refcount goes to zero, close down the svc_handler - possible_entry->int_id_.first ()->recycler (0, 0); - possible_entry->int_id_.first ()->close (); - this->purge_i (possible_entry); - } - - // Hint not successful - found = 0; - - // Reset hint - sh = 0; - } - - // If hint is not closed, see if it is connected to the correct - // address and is recyclable - else if ((possible_entry->ext_id_.recycle_state () == ACE_RECYCLABLE_IDLE_AND_PURGABLE || - possible_entry->ext_id_.recycle_state () == ACE_RECYCLABLE_IDLE_BUT_NOT_PURGABLE) && - possible_entry->ext_id_.subject () == remote_addr) - { - // Hint successful - found = 1; - - // Tell the that it should prepare itself for - // being recycled. - this->prepare_for_recycling (sh); - - // - // Update the caching attributes directly since we don't do a - // find() on the cache map. - // - - // Indicates successful find. - int find_result = 0; - - int result = this->caching_strategy ().notify_find (find_result, - possible_entry->int_id_.second ()); - - if (result == -1) - return result; - } - else - { - // This hint will not be used. - possible_entry->ext_id_.decrement (); - - // Hint not successful - found = 0; - - // If is not connected to the correct address or is busy, - // we will not use it. - sh = 0; - } - - if (found) - entry = possible_entry; - - return 0; -} - -template int -ACE_Cached_Connect_Strategy_Ex::find_or_create_svc_handler_i -(SVC_HANDLER *&sh, - const ACE_PEER_CONNECTOR_ADDR &remote_addr, - ACE_Time_Value *timeout, - const ACE_PEER_CONNECTOR_ADDR &local_addr, - bool reuse_addr, - int flags, - int perms, - ACE_Hash_Map_Entry, ACE_Pair > *&entry, - int &found) -{ - REFCOUNTED_HASH_RECYCLABLE_ADDRESS search_addr (remote_addr); - - // Try to find the address in the cache. Only if we don't find it - // do we create a new and connect it with the server. - while (this->find (search_addr, entry) != -1) - { - // We found a cached svc_handler. - // Get the cached - sh = entry->int_id_.first (); - - // Is the connection clean? - int state_result = - ACE::handle_ready (sh->peer ().get_handle (), - &ACE_Time_Value::zero, - 1, // read ready - 0, // write ready - 1);// exception ready - - if (state_result == 1) - { - - if (sh->close () == -1) - return -1; - - sh = 0; - - // Cycle it once again.. - } - else if ((state_result == -1) && (errno == ETIME)) - { - // Found!!! - // Set the flag - found = 1; - - // Tell the that it should prepare itself for - // being recycled. - if (this->prepare_for_recycling (sh) == -1) - return -1; - - return 0; - } - else - { - return -1; - } - } - - // Not found... - - // Set the flag - found = 0; - - // We need to use a temporary variable here since we are not - // allowed to change because other threads may use this - // when we let go of the lock during the OS level connect. - // - // Note that making a new svc_handler, connecting remotely, - // binding to the map, and assigning of the hint and recycler - // should be atomic to the outside world. - SVC_HANDLER *potential_handler = 0; - - // Create a new svc_handler - if (this->make_svc_handler (potential_handler) == -1) - return -1; - - // Connect using the svc_handler. - if (this->cached_connect (potential_handler, - remote_addr, - timeout, - local_addr, - reuse_addr, - flags, - perms) == -1) - { - // Close the svc handler. - potential_handler->close (0); - - return -1; - } - else - { - // Insert the new SVC_HANDLER instance into the cache. - if (this->connection_cache_.bind (search_addr, - potential_handler, - entry) == -1) - { - // Close the svc handler and reset . - potential_handler->close (0); - - return -1; - } - - // Everything succeeded as planned. Assign to - // . - sh = potential_handler; - - // Set the recycler and the recycling act - - this->assign_recycler (sh, this, entry); - } - - return 0; -} - -template int -ACE_Cached_Connect_Strategy_Ex::cached_connect (SVC_HANDLER *&sh, - const ACE_PEER_CONNECTOR_ADDR &remote_addr, - ACE_Time_Value *timeout, - const ACE_PEER_CONNECTOR_ADDR &local_addr, - bool reuse_addr, - int flags, - int perms) -{ - // Actively establish the connection. This is a timed blocking - // connect. - if (this->new_connection (sh, - remote_addr, - timeout, - local_addr, - reuse_addr, - flags, - perms) == -1) - { - // If connect() failed because of timeouts, we have to reject - // the connection entirely. This is necessary since currently - // there is no way for the non-blocking connects to complete and - // for the to notify the cache of the completion of - // connect(). - - if (errno == EWOULDBLOCK || errno == ETIMEDOUT) - errno = ENOTSUP; - else if (ACE::out_of_handles (errno) || errno == EADDRINUSE) - { - // If the connect failed due to the process running out of - // file descriptors then, auto_purging of some connections - // are done from the CONNECTION_CACHE. This frees the - // descriptors which get used in the connect process and - // hence the same method is called again! - if (this->purge_connections () == -1) - return -1; - - // Try connecting again. - if (this->new_connection (sh, - remote_addr, - timeout, - local_addr, - reuse_addr, - flags, - perms) == -1) - { - if (errno == EWOULDBLOCK || errno == ETIMEDOUT) - errno = ENOTSUP; - return -1; - } - } - else - { - return -1; - } - } - - return 0; - -} - - -template int -ACE_Cached_Connect_Strategy_Ex::connect_svc_handler_i -(SVC_HANDLER *&sh, - const ACE_PEER_CONNECTOR_ADDR &remote_addr, - ACE_Time_Value *timeout, - const ACE_PEER_CONNECTOR_ADDR &local_addr, - bool reuse_addr, - int flags, - int perms, - int& found) -{ - CONNECTION_CACHE_ENTRY *entry = 0; - - // Check if the user passed a hint svc_handler - if (sh != 0) - { - int result = this->check_hint_i (sh, - remote_addr, - timeout, - local_addr, - reuse_addr, - flags, - perms, - entry, - found); - if (result != 0) - return result; - } - - // If not found - if (!found) - { - int result = this->find_or_create_svc_handler_i (sh, - remote_addr, - timeout, - local_addr, - reuse_addr, - flags, - perms, - entry, - found); - - if (result != 0) - return result; - - // Increment the refcount - entry->ext_id_.increment (); - } - - // For all successful cases: mark the in the cache - // as being . Therefore recyclable is BUSY. - entry->ext_id_.recycle_state (ACE_RECYCLABLE_BUSY); - - return 0; -} - - -template int -ACE_Cached_Connect_Strategy_Ex::cache_i (const void *recycling_act) -{ - // The wonders and perils of ACT - CONNECTION_CACHE_ENTRY *entry = (CONNECTION_CACHE_ENTRY *) recycling_act; - - // Mark the in the cache as not being . - // Therefore recyclable is IDLE. - entry->ext_id_.recycle_state (ACE_RECYCLABLE_IDLE_AND_PURGABLE); - - return 0; -} - -template int -ACE_Cached_Connect_Strategy_Ex::recycle_state_i (const void *recycling_act, - ACE_Recyclable_State new_state) -{ - // The wonders and perils of ACT - CONNECTION_CACHE_ENTRY *entry = (CONNECTION_CACHE_ENTRY *) recycling_act; - - // Mark the in the cache as not being . - // Therefore recyclable is IDLE. - entry->ext_id_.recycle_state (new_state); - - return 0; -} - -template ACE_Recyclable_State -ACE_Cached_Connect_Strategy_Ex::recycle_state_i (const void *recycling_act) const -{ - // The wonders and perils of ACT - CONNECTION_CACHE_ENTRY *entry = (CONNECTION_CACHE_ENTRY *) recycling_act; - - // Mark the in the cache as not being . - // Therefore recyclable is IDLE. - return entry->ext_id_.recycle_state (); -} - -template int -ACE_Cached_Connect_Strategy_Ex::purge_i (const void *recycling_act) -{ - // The wonders and perils of ACT - CONNECTION_CACHE_ENTRY *entry = (CONNECTION_CACHE_ENTRY *) recycling_act; - - return this->connection_cache_.unbind (entry); -} - - -template int -ACE_Cached_Connect_Strategy_Ex::mark_as_closed_i (const void *recycling_act) -{ - // The wonders and perils of ACT - CONNECTION_CACHE_ENTRY *entry = (CONNECTION_CACHE_ENTRY *) recycling_act; - - // Mark the in the cache as CLOSED. - entry->ext_id_.recycle_state (ACE_RECYCLABLE_CLOSED); - - return 0; -} - -template int -ACE_Cached_Connect_Strategy_Ex::cleanup_hint_i (const void *recycling_act, - void **act_holder) -{ - // Reset the <*act_holder> in the confines and protection of the - // lock. - if (act_holder) - *act_holder = 0; - - // The wonders and perils of ACT - CONNECTION_CACHE_ENTRY *entry = (CONNECTION_CACHE_ENTRY *) recycling_act; - - // Decrement the refcount on the . - int refcount = entry->ext_id_.decrement (); - - // If the svc_handler state is closed and the refcount == 0, call - // close() on svc_handler. - if (entry->ext_id_.recycle_state () == ACE_RECYCLABLE_CLOSED && - refcount == 0) - { - entry->int_id_.first ()->recycler (0, 0); - entry->int_id_.first ()->close (); - this->purge_i (entry); - } - - return 0; -} - -template int -ACE_Cached_Connect_Strategy_Ex::purge_connections (void) -{ - return this->connection_cache_.purge (); -} - -template CACHING_STRATEGY & -ACE_Cached_Connect_Strategy_Ex::caching_strategy (void) -{ - return this->connection_cache_.caching_strategy (); -} - -template int -ACE_Cached_Connect_Strategy_Ex::find (ACE_Refcounted_Hash_Recyclable &search_addr, - ACE_Hash_Map_Entry, ACE_Pair > *&entry) -{ - typedef ACE_Hash_Map_Bucket_Iterator, - ACE_Hash, - ACE_Equal_To, - ACE_Null_Mutex> - CONNECTION_CACHE_BUCKET_ITERATOR; - - CONNECTION_CACHE_BUCKET_ITERATOR iterator (this->connection_cache_.map (), - search_addr); - - CONNECTION_CACHE_BUCKET_ITERATOR end (this->connection_cache_.map (), - search_addr, - 1); - - for (; - iterator != end; - ++iterator) - { - REFCOUNTED_HASH_RECYCLABLE_ADDRESS &addr = (*iterator).ext_id_; - - if (addr.recycle_state () != ACE_RECYCLABLE_IDLE_AND_PURGABLE && - addr.recycle_state () != ACE_RECYCLABLE_IDLE_BUT_NOT_PURGABLE) - continue; - - if (addr.subject () != search_addr.subject ()) - continue; - - entry = &(*iterator); - - // - // Update the caching attributes directly since we don't do a - // find() on the cache map. - // - - // Indicates successful find. - int find_result = 0; - - int result = this->caching_strategy ().notify_find (find_result, - entry->int_id_.second ()); - - if (result == -1) - return result; - - return 0; - } - - return -1; -} - -template void -ACE_Cached_Connect_Strategy_Ex::cleanup (void) -{ - // Excluded other threads from changing the cache while we cleanup - ACE_GUARD (MUTEX, ace_mon, *this->lock_); - - // Close down all cached service handlers. - typename CONNECTION_CACHE::ITERATOR iter = this->connection_cache_.begin (); - while (iter != this->connection_cache_.end ()) - { - if ((*iter).second () != 0) - { - // save entry for future use - CONNECTION_CACHE_ENTRY *entry = (CONNECTION_CACHE_ENTRY *) - (*iter).second ()->recycling_act (); - - // close handler - (*iter).second ()->recycler (0, 0); - (*iter).second ()->close (); - - // remember next iter - typename CONNECTION_CACHE::ITERATOR next_iter = iter; - ++next_iter; - - // purge the item from the hash - this->purge_i (entry); - - // assign next iter - iter = next_iter; - } - else - ++iter; - } -} - -ACE_ALLOC_HOOK_DEFINE(ACE_Cached_Connect_Strategy_Ex) -///////////////////////////////////////////////////////////////////////// - -template -ACE_Bounded_Cached_Connect_Strategy::ACE_Bounded_Cached_Connect_Strategy -(size_t max_size, - CACHING_STRATEGY &caching_s, - ACE_Creation_Strategy *cre_s, - ACE_Concurrency_Strategy *con_s, - ACE_Recycling_Strategy *rec_s, - MUTEX *lock, - int delete_lock) - : CCSEBASE (caching_s, cre_s, con_s, rec_s, lock, delete_lock), - max_size_ (max_size) -{ -} - -template -ACE_Bounded_Cached_Connect_Strategy::~ACE_Bounded_Cached_Connect_Strategy(void) -{ -} - -template -int -ACE_Bounded_Cached_Connect_Strategy::find_or_create_svc_handler_i -(SVC_HANDLER *&sh, - const ACE_PEER_CONNECTOR_ADDR &remote_addr, - ACE_Time_Value *timeout, - const ACE_PEER_CONNECTOR_ADDR &local_addr, - bool reuse_addr, - int flags, - int perms, - ACE_Hash_Map_Entry, - ACE_Pair > *&entry, - int &found) -{ - - REFCOUNTED_HASH_RECYCLABLE_ADDRESS search_addr (remote_addr); - - // Try to find the address in the cache. Only if we don't find it - // do we create a new and connect it with the server. - while (this->find (search_addr, entry) != -1) - { - // We found a cached svc_handler. - // Get the cached - sh = entry->int_id_.first (); - - // Is the connection clean? - int state_result= ACE::handle_ready (sh->peer ().get_handle (), - &ACE_Time_Value::zero, - 1, // read ready - 0, // write ready - 1);// exception ready - - if (state_result == 1) - { - // The connection was disconnected during idle. - // close the svc_handler down. - if (sh->close () == -1) - { - ACE_ASSERT (0); - return -1; - } - sh = 0; - // and rotate once more... - } - else if ((state_result == -1) && (errno == ETIME)) - { - // Found!!! - // Set the flag - found = 1; - - // Tell the that it should prepare itself for - // being recycled. - if (this->prepare_for_recycling (sh) == -1) - { - ACE_ASSERT (0); - return -1; - } - - return 0; - } - else // some other return value or error... - { - ACE_ASSERT (0); // just to see it coming - - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("(%t)ACE_Bounded_Cached_Connect_Strategy<>::") - ACE_TEXT ("find_or_create_svc_handler_i - ") - ACE_TEXT ("error polling server socket state.\n"))); - - return -1; - } - } - - // Not found... - - // Set the flag - found = 0; - - // Check the limit of handlers... - if ((this->max_size_ > 0) && - (this->connection_cache_.current_size () >= this->max_size_)) - { - // Try to purge idle connections - if (this->purge_connections () == -1) - return -1; - - // Check limit again. - if (this->connection_cache_.current_size () >= this->max_size_) - // still too much! - return -1; - - // OK, we have room now... - } - - // We need to use a temporary variable here since we are not - // allowed to change because other threads may use this - // when we let go of the lock during the OS level connect. - // - // Note that making a new svc_handler, connecting remotely, - // binding to the map, and assigning of the hint and recycler - // should be atomic to the outside world. - SVC_HANDLER *potential_handler = 0; - - // Create a new svc_handler - if (this->make_svc_handler (potential_handler) == -1) - return -1; - - // Connect using the svc_handler. - if (this->cached_connect (potential_handler, - remote_addr, - timeout, - local_addr, - reuse_addr, - flags, - perms) == -1) - { - // Close the svc handler. - potential_handler->close (0); - return -1; - } - else - { - // Insert the new SVC_HANDLER instance into the cache. - if (this->connection_cache_.bind (search_addr, - potential_handler, - entry) == -1) - { - // Close the svc handler and reset . - potential_handler->close (0); - - return -1; - } - - // Everything succeeded as planned. Assign to - // . - sh = potential_handler; - - // Set the recycler and the recycling act - this->assign_recycler (sh, this, entry); - } - - return 0; -} - -ACE_ALLOC_HOOK_DEFINE(ACE_Bounded_Cached_Connect_Strategy) - -ACE_END_VERSIONED_NAMESPACE_DECL - -#undef ACE_T1 -#undef ACE_T2 - -#endif /* ACE_CACHED_CONNECT_STRATEGY_T_CPP */ diff --git a/externals/ace/Cached_Connect_Strategy_T.h b/externals/ace/Cached_Connect_Strategy_T.h deleted file mode 100644 index e95218f60fc..00000000000 --- a/externals/ace/Cached_Connect_Strategy_T.h +++ /dev/null @@ -1,263 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Cached_Connect_Strategy_T.h - * - * $Id: Cached_Connect_Strategy_T.h 91077 2010-07-13 14:33:08Z johnnyw $ - * - * @author Kirthika Parameswaran - */ -//============================================================================= - -#ifndef CACHED_CONNECT_STRATEGY_T_H -#define CACHED_CONNECT_STRATEGY_T_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Strategies_T.h" -#include "ace/Hash_Cache_Map_Manager_T.h" -#include "ace/Caching_Strategies_T.h" -#include "ace/Functor_T.h" -#include "ace/Pair_T.h" - -// For linkers which cant grok long names... -#define ACE_Cached_Connect_Strategy_Ex ACCSE - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Cached_Connect_Strategy_Ex - * - * @brief A connection strategy which caches connections to peers - * (represented by SVC_HANDLER instances), thereby allowing - * subsequent re-use of unused, but available, connections. - * - * is intended to be used as a - * plug-in connection strategy for ACE_Strategy_Connector. - * It's added value is re-use of established connections and - * tweaking the role of the cache as per the caching strategy. - */ -template -class ACE_Cached_Connect_Strategy_Ex - : public ACE_Cached_Connect_Strategy -{ -public: - /// Constructor - ACE_Cached_Connect_Strategy_Ex ( - CACHING_STRATEGY &caching_s, - ACE_Creation_Strategy *cre_s = 0, - ACE_Concurrency_Strategy *con_s = 0, - ACE_Recycling_Strategy *rec_s = 0, - MUTEX *lock = 0, - int delete_lock = 0); - - /// Destructor - virtual ~ACE_Cached_Connect_Strategy_Ex (void); - - /// Explicit purging of connection entries from the connection cache. - virtual int purge_connections (void); - - /// Mark as closed (non-locking version). This is used during the cleanup of the - /// connections purged. - virtual int mark_as_closed_i (const void *recycling_act); - - /** - * Since g++ version < 2.8 arent happy with templates, this special - * method had to be devised to avoid memory leaks and perform - * cleanup of the . - */ - void cleanup (void); - - // = Typedefs for managing the map - typedef ACE_Refcounted_Hash_Recyclable - REFCOUNTED_HASH_RECYCLABLE_ADDRESS; - typedef ACE_Hash_Cache_Map_Manager, - ACE_Equal_To, - CACHING_STRATEGY, - ATTRIBUTES> - CONNECTION_CACHE; - typedef typename CONNECTION_CACHE::CACHE_ENTRY CONNECTION_CACHE_ENTRY; - typedef typename CONNECTION_CACHE::key_type KEY; - typedef typename CONNECTION_CACHE::mapped_type VALUE; - - typedef ACE_Recyclable_Handler_Cleanup_Strategy, - ACE_Hash_Map_Manager_Ex, - ACE_Hash, - ACE_Equal_To, - MUTEX> > - CLEANUP_STRATEGY; - - typedef ACE_Cached_Connect_Strategy - CCSBASE; - - // = Accessor. - CACHING_STRATEGY &caching_strategy (void); - -protected: - - /// Find an idle handle. - int find (ACE_Refcounted_Hash_Recyclable &search_addr, - ACE_Hash_Map_Entry, ACE_Pair > *&entry); - - /// Remove from cache (non-locking version). - virtual int purge_i (const void *recycling_act); - - /// Add to cache (non-locking version). - virtual int cache_i (const void *recycling_act); - - /// Get/Set recycle_state (non-locking version). - virtual int recycle_state_i (const void *recycling_act, - ACE_Recyclable_State new_state); - virtual ACE_Recyclable_State recycle_state_i (const void *recycling_act) const; - - /// Cleanup hint and reset @c *act_holder to zero if @a act_holder != 0. - virtual int cleanup_hint_i (const void *recycling_act, - void **act_holder); - - // = Helpers - int check_hint_i (SVC_HANDLER *&sh, - const ACE_PEER_CONNECTOR_ADDR &remote_addr, - ACE_Time_Value *timeout, - const ACE_PEER_CONNECTOR_ADDR &local_addr, - bool reuse_addr, - int flags, - int perms, - ACE_Hash_Map_Entry, ACE_Pair > *&entry, - int &found); - - virtual int find_or_create_svc_handler_i (SVC_HANDLER *&sh, - const ACE_PEER_CONNECTOR_ADDR &remote_addr, - ACE_Time_Value *timeout, - const ACE_PEER_CONNECTOR_ADDR &local_addr, - bool reuse_addr, - int flags, - int perms, - ACE_Hash_Map_Entry, ACE_Pair > *&entry, - int &found); - - virtual int connect_svc_handler_i (SVC_HANDLER *&sh, - const ACE_PEER_CONNECTOR_ADDR &remote_addr, - ACE_Time_Value *timeout, - const ACE_PEER_CONNECTOR_ADDR &local_addr, - bool reuse_addr, - int flags, - int perms, - int &found); - - /** - * Connection of the svc_handler with the remote host. This method - * also encapsulates the connection done with auto_purging under the - * hood. If the connect failed due to the process running out of - * file descriptors then, auto_purging of some connections are done - * from the CONNECTION_CACHE. This frees the descriptors which get - * used in the connect process and hence the connect operation can - * succeed. - */ - virtual int cached_connect (SVC_HANDLER *&sh, - const ACE_PEER_CONNECTOR_ADDR &remote_addr, - ACE_Time_Value *timeout, - const ACE_PEER_CONNECTOR_ADDR &local_addr, - bool reuse_addr, - int flags, - int perms); - - /// Table that maintains the cache of connected SVC_HANDLERs. - CONNECTION_CACHE connection_cache_; -}; - -///////////////////////////////////////////////////////////////////////////// - -// For linkers which cant grok long names... -#define ACE_Bounded_Cached_Connect_Strategy ABCCS - -/** - * @class ACE_Bounded_Cached_Connect_Strategy - * - * @brief - * A connection strategy which caches connections to peers - * (represented by SVC_HANDLER instances), thereby allowing - * subsequent re-use of unused, but available, connections. - * This strategy should be used when the cache is bounded by - * maximum size. - * - * Bounded_Cached_Connect_Strategy is intended to be used as a - * plug-in connection strategy for ACE_Strategy_Connector. - * It's added value is re-use of established connections and - * tweaking the role of the cache as per the caching strategy. - * Thanks to Edan Ayal for contributing this - * class and Susan Liebeskind for - * brainstorming about it. - */ -template -class ACE_Bounded_Cached_Connect_Strategy - : public ACE_Cached_Connect_Strategy_Ex -{ - - typedef ACE_Cached_Connect_Strategy_Ex - CCSEBASE; - - // = Typedefs for managing the map - typedef ACE_Refcounted_Hash_Recyclable - REFCOUNTED_HASH_RECYCLABLE_ADDRESS; - -public: - - /// Constructor - ACE_Bounded_Cached_Connect_Strategy (size_t max_size, - CACHING_STRATEGY &caching_s, - ACE_Creation_Strategy *cre_s = 0, - ACE_Concurrency_Strategy *con_s = 0, - ACE_Recycling_Strategy *rec_s = 0, - MUTEX *lock = 0, - int delete_lock = 0); - - /// Destructor - virtual ~ACE_Bounded_Cached_Connect_Strategy (void); - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - - virtual int find_or_create_svc_handler_i (SVC_HANDLER *&sh, - const ACE_PEER_CONNECTOR_ADDR &remote_addr, - ACE_Time_Value *timeout, - const ACE_PEER_CONNECTOR_ADDR &local_addr, - bool reuse_addr, - int flags, - int perms, - ACE_Hash_Map_Entry, - ACE_Pair > *&entry, - int &found); - -protected: - - /// Max items in the cache, used as a bound for the creation of svc_handlers. - size_t max_size_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Cached_Connect_Strategy_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Cached_Connect_Strategy_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" -#endif /* CACHED_CONNECT_STRATEGY_T_H */ diff --git a/externals/ace/Caching_Strategies_T.cpp b/externals/ace/Caching_Strategies_T.cpp deleted file mode 100644 index 2b0fd4e764a..00000000000 --- a/externals/ace/Caching_Strategies_T.cpp +++ /dev/null @@ -1,59 +0,0 @@ -//$Id: Caching_Strategies_T.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#ifndef ACE_CACHING_STRATEGIES_T_CPP -#define ACECACHING_STRATEGIES_T_CPP - -#include "ace/Caching_Strategies_T.h" -#include "ace/Log_Msg.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Caching_Strategies_T.inl" -#endif /* __ACE_INLINE__ */ - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -#pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template -ACE_Caching_Strategy::~ACE_Caching_Strategy (void) -{ -} - -////////////////////////////////////////////////////////////////////////////////// - -template -ACE_LRU_Caching_Strategy::ACE_LRU_Caching_Strategy (void) - : timer_ (0), - purge_percent_ (10) -{ -} - -//////////////////////////////////////////////////////////////////////////////////////////////// - -template -ACE_LFU_Caching_Strategy::ACE_LFU_Caching_Strategy (void) - : purge_percent_ (10) -{ -} - -//////////////////////////////////////////////////////////////////////////////////////////////// - -template -ACE_FIFO_Caching_Strategy::ACE_FIFO_Caching_Strategy (void) - : order_ (0), - purge_percent_ (10) -{ -} - -//////////////////////////////////////////////////////////////////////////////////////////////// - -ACE_ALLOC_HOOK_DEFINE(ACE_LRU_Caching_Strategy) -ACE_ALLOC_HOOK_DEFINE(ACE_LFU_Caching_Strategy) -ACE_ALLOC_HOOK_DEFINE(ACE_FIFO_Caching_Strategy) -ACE_ALLOC_HOOK_DEFINE(ACE_Null_Caching_Strategy) - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_CACHING_STRATEGIES_T_CPP */ diff --git a/externals/ace/Caching_Strategies_T.h b/externals/ace/Caching_Strategies_T.h deleted file mode 100644 index e4b0817aa26..00000000000 --- a/externals/ace/Caching_Strategies_T.h +++ /dev/null @@ -1,552 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Caching_Strategies_T.h - * - * $Id: Caching_Strategies_T.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Kirthika Parameswaran - */ -//============================================================================= - -#ifndef ACE_CACHING_STRATEGIES_H -#define ACE_CACHING_STRATEGIES_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" -#include "ace/Caching_Utility_T.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined(_MSC_VER) -#pragma warning(disable:4503) -#endif /* _MSC_VER */ - -// For linkers that cant grok long names. -#define ACE_Caching_Strategy ACS - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Caching_Strategy - * - * @brief This class is an abstract base class for a caching strategy. - * - * This class consists of all the interfaces a caching strategy should - * have and is used in association with the - * ACE_Caching_Strategy_Adaptor. - */ -template -class ACE_Caching_Strategy -{ -public: - /// Destructor. - virtual ~ACE_Caching_Strategy (void); - - /// Accessor method for the timer attributes. - virtual ATTRIBUTES attributes (void) = 0; - - /// Get the percentage of entries to purge. - virtual double purge_percent (void) = 0; - - /// Set the percentage of entries to purge. - virtual void purge_percent (double percentage) = 0; - - // = Strategy related Operations - - /// This method acts as a notification about the CONTAINERs bind - /// method call. - virtual int notify_bind (int result, - const ATTRIBUTES &attr) = 0; - - /// This method acts as a notification about the CONTAINERs find - /// method call - virtual int notify_find (int result, - ATTRIBUTES &attr) = 0; - - /// This method acts as a notification about the CONTAINERs unbind - /// method call - virtual int notify_unbind (int result, - const ATTRIBUTES &attr) = 0; - - /// This method acts as a notification about the CONTAINERs trybind - /// method call - virtual int notify_trybind (int result, - ATTRIBUTES &attr) = 0; - - /// This method acts as a notification about the CONTAINERs rebind - /// method call - virtual int notify_rebind (int result, - const ATTRIBUTES &attr) = 0; - - /// Purge the cache. - virtual CACHING_UTILITY &caching_utility (void) = 0; - - /// Dumps the state of the object. - virtual void dump (void) const = 0; -}; - -////////////////////////////////////////////////////////////////////////// - -#define ACE_Caching_Strategy_Adapter ACSA - -/** - * @class ACE_Caching_Strategy_Adapter - * - * @brief This class follows the Adaptor pattern and is used to provide - * External Polymorphism by deriving from ACE_Caching_Strategy. - * - * This class simply delegates all requests to the - * IMPLEMNETATION object within. This class should be passed in - * place of the the abstract base ACE_Caching_Strategy class as - * part of the External Polymorphism pattern. - */ -template -class ACE_Caching_Strategy_Adapter - : public ACE_Caching_Strategy -{ - -public: - - /// Constructor. - ACE_Caching_Strategy_Adapter (IMPLEMENTATION *implementation = 0, - bool delete_implementation = false); - - /// Destructor. - ~ACE_Caching_Strategy_Adapter (void); - - /// Accessor method for the timer attributes. - ATTRIBUTES attributes (void); - - /// Get the percentage of entries to purge. - double purge_percent (void); - - /// Set the percentage of entries to purge. - void purge_percent (double percentage); - - // = Strategy related Operations - - /// This method acts as a notification about the CONTAINERs bind - /// method call. - int notify_bind (int result, - const ATTRIBUTES &attr); - - /// This method acts as a notification about the CONTAINERs find - /// method call - int notify_find (int result, - ATTRIBUTES &attr); - - /// This method acts as a notification about the CONTAINERs unbind - /// method call - int notify_unbind (int result, - const ATTRIBUTES &attr); - - /// This method acts as a notification about the CONTAINERs trybind - /// method call - int notify_trybind (int result, - ATTRIBUTES &attr); - - /// This method acts as a notification about the CONTAINERs rebind - /// method call - int notify_rebind (int result, - const ATTRIBUTES &attr); - - /// Accessor to the implementation. - IMPLEMENTATION &implementation (void); - - /// Purge the cache. - CACHING_UTILITY &caching_utility (void); - - /// Dumps the state of the object. - void dump (void) const; - -private: - - /// Implementation class. - IMPLEMENTATION *implementation_; - - /// Do we need to delete the implementation? - bool delete_implementation_; -}; - -////////////////////////////////////////////////////////////////////////// -#define ACE_LRU_Caching_Strategy ALRU - -/** - * @class ACE_LRU_Caching_Strategy - * - * @brief Defines a Least Recently Used strategy which will decide on - * the item to be removed from the cache. - * - * This is a strategy which makes use of a virtual timer which - * is updated whenever an item is inserted or looked up in the - * container. When the need of purging entries arises, the items - * with the lowest timer values are removed. - * Explanation of the template parameter list: - * CONTAINER is any map with entries of type . - * The ATTRIBUTES are the deciding factor for purging of entries - * and should logically be included with the VALUE. Some ways of - * doing this are: As being a member of the VALUE or VALUE being - * ACE_Pair. The CACHING_UTILITY is the - * class which can be plugged in and which decides the entries - * to purge. - */ -template -class ACE_LRU_Caching_Strategy -{ -public: - - // Traits. - typedef ATTRIBUTES CACHING_ATTRIBUTES; - - // = Initialisation and termination. - - /** - * The is the map in which the entries reside. The - * timer attribute is initialed to zero in this constructor. And - * the field denotes the percentage of the entries - * in the cache which can be purged automagically and by default is - * set to 10%. - */ - ACE_LRU_Caching_Strategy (void); - - // = Operations of the strategy. - - /// Accessor method for the timer attributes. - ATTRIBUTES attributes (void); - - /// Get the percentage of entries to purge. - double purge_percent (void); - - /// Set the percentage of entries to purge. - void purge_percent (double percentage); - - // = Strategy related Operations - - /// This method acts as a notification about the CONTAINERs bind - /// method call. - int notify_bind (int result, - const ATTRIBUTES &attr); - - /// This method acts as a notification about the CONTAINERs find - /// method call - int notify_find (int result, - ATTRIBUTES &attr); - - /// This method acts as a notification about the CONTAINERs unbind - /// method call - int notify_unbind (int result, - const ATTRIBUTES &attr); - - - /// This method acts as a notification about the CONTAINERs trybind - /// method call - int notify_trybind (int result, - ATTRIBUTES &attr); - - /// This method acts as a notification about the CONTAINERs rebind - /// method call - int notify_rebind (int result, - const ATTRIBUTES &attr); - - /// Purge the cache. - CACHING_UTILITY &caching_utility (void); - - /// Dumps the state of the object. - void dump (void) const; - -private: - - /// This element is the one which is the deciding factor for purging - /// of an ITEM. - ATTRIBUTES timer_; - - /// The level about which the purging will happen automagically. - double purge_percent_; - - /// This is the helper class which will decide and expunge entries - /// from the cache. - CACHING_UTILITY caching_utility_; -}; - -////////////////////////////////////////////////////////////////////////// -#define ACE_LFU_Caching_Strategy ALFU - -/** - * @class ACE_LFU_Caching_Strategy - * - * @brief Defines a Least Frequently Used strategy for which will decide on - * the item to be removed from the cache. - * - * A attribute is tagged to each item which increments whenever - * the item is bound or looked up in the cache. Thus it denotes - * the frequency of use. According to the value of the attribute - * the item is removed from the CONTAINER i.e cache. - * Explanation of the template parameter list: - * CONTAINER is any map with entries of type . - * The ATTRIBUTES are the deciding factor for purging of entries - * and should logically be included with the VALUE. Some ways of - * doing this are: As being a member of the VALUE or VALUE being - * ACE_Pair. The CACHING_UTILITY is the - * class which can be plugged in and which decides the entries - * to purge. - */ -template -class ACE_LFU_Caching_Strategy -{ - -public: - - // Traits. - typedef ATTRIBUTES CACHING_ATTRIBUTES; - - // = Initialisation and termination methods. - - /** - * The is the map in which the entries reside. The - * timer attribute is initialed to zero in this constructor. And - * the field denotes the percentage of the entries - * in the cache which can be purged automagically and by default is - * set to 10%. - */ - ACE_LFU_Caching_Strategy (void); - - // = Strategy methods. - - /// Access the attributes. - ATTRIBUTES attributes (void); - - /// Get the percentage of entries to purge. - double purge_percent (void); - - /// Set the percentage of entries to purge. - void purge_percent (double percentage); - - // = Strategy related Operations - - /// This method acts as a notification about the CONTAINERs bind - /// method call. - int notify_bind (int result, - const ATTRIBUTES &attr); - - /// Lookup notification. - int notify_find (int result, - ATTRIBUTES &attr); - - /// This method acts as a notification about the CONTAINERs unbind - /// method call - int notify_unbind (int result, - const ATTRIBUTES &attr); - - /// This method acts as a notification about the CONTAINERs trybind - /// method call - int notify_trybind (int result, - ATTRIBUTES &attr); - - /// This method acts as a notification about the CONTAINERs rebind - /// method call - int notify_rebind (int result, - const ATTRIBUTES &attr); - - /// Purge the cache. - CACHING_UTILITY &caching_utility (void); - - /// Dumps the state of the object. - void dump (void) const; - -private: - - /// The level about which the purging will happen automagically. - double purge_percent_; - - /// This is the helper class which will decide and expunge entries - /// from the cache. - CACHING_UTILITY caching_utility_; -}; - -///////////////////////////////////////////////////////////// -#define ACE_FIFO_Caching_Strategy AFIFO - -/** - * @class ACE_FIFO_Caching_Strategy - * - * @brief The First In First Out strategy is implemented wherein each - * item is ordered. - * - * The order tag of each item is used to decide the item to be - * removed from the cache. The items with least order are removed. - * Explanation of the template parameter list: - * CONTAINER is any map with entries of type . - * The ATTRIBUTES are the deciding factor for purging of entries - * and should logically be included with the VALUE. Some ways of - * doing this are: As being a member of the VALUE or VALUE being - * ACE_Pair. The CACHING_UTILITY is the - * class which can be plugged in and which decides the entries - * to purge. - */ -template -class ACE_FIFO_Caching_Strategy -{ - -public: - - typedef ATTRIBUTES CACHING_ATTRIBUTES; - - // = Initialisation and termination. - - /** - * The is the map in which the entries reside. The - * timer attribute is initialed to zero in this constructor. And - * the field denotes the percentage of the entries - * in the cache which can be purged automagically and by default is - * set to 10%. - */ - ACE_FIFO_Caching_Strategy (void); - - // = Strategy methods. - - /// Accessor method. - ATTRIBUTES attributes (void); - - /// Get the percentage of entries to purge. - double purge_percent (void); - - /// Set the percentage of entries to purge. - void purge_percent (double percentage); - - // = Strategy related Operations - - /// Notification for an item getting bound into the cache. - int notify_bind (int result, - const ATTRIBUTES &attr); - - /// This method acts as a notification about the CONTAINERs find - /// method call - int notify_find (int result, - ATTRIBUTES &attr); - - /// This method acts as a notification about the CONTAINERs unbind - /// method call - int notify_unbind (int result, - const ATTRIBUTES &attr); - - /// This method acts as a notification about the CONTAINERs trybind - /// method call - int notify_trybind (int result, - ATTRIBUTES &attr); - - /// Notification for an item getting bound again into the cache. - int notify_rebind (int result, - const ATTRIBUTES &attr); - - /// Purge the cache. - CACHING_UTILITY &caching_utility (void); - - /// Dumps the state of the object. - void dump (void) const; - -private: - - /// The order is the deciding factor for the item to be removed from - /// the cache. - ATTRIBUTES order_; - - /// The level about which the purging will happen automagically. - double purge_percent_; - - /// This is the helper class which will decide and expunge entries - /// from the cache. - CACHING_UTILITY caching_utility_; -}; - -////////////////////////////////////////////////////////////////////// -#define ACE_Null_Caching_Strategy ANULL - -/** - * @class ACE_Null_Caching_Strategy - * - * @brief The is a special caching strategy which doesnt have the purging - * feature. - * - * No purging provided. To be used when purging might be too expensive - * an operation. - */ -template -class ACE_Null_Caching_Strategy -{ - -public: - - // = Traits. - typedef ATTRIBUTES CACHING_ATTRIBUTES; - - // = Strategy methods. All are NO_OP methods!!! - - /// Accessor method. - ATTRIBUTES attributes (void); - - /// Get the percentage of entries to purge. - double purge_percent (void); - - /// Set the percentage of entries to purge. - void purge_percent (double percentage); - - // = Strategy related Operations - - /// Notification for an item getting bound into the cache. - int notify_bind (int result, - const ATTRIBUTES &attr); - - /// This method acts as a notification about the CONTAINERs find - /// method call - int notify_find (int result, - ATTRIBUTES &attr); - - /// This method acts as a notification about the CONTAINERs unbind - /// method call - int notify_unbind (int result, - const ATTRIBUTES &attr); - - /// This method acts as a notification about the CONTAINERs trybind - /// method call - int notify_trybind (int result, - ATTRIBUTES &attr); - - /// Notification for an item getting bound again into the cache. - int notify_rebind (int result, - const ATTRIBUTES &attr); - - /// Purge the cache. - CACHING_UTILITY &caching_utility (void); - - /// Dumps the state of the object. - void dump (void) const; - -private: - - /// This is the helper class which will decide and expunge entries - /// from the cache. - CACHING_UTILITY caching_utility_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Caching_Strategies_T.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Caching_Strategies_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Caching_Strategies_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" - -#endif /* ACE_CACHING_STRATEGIES_H */ diff --git a/externals/ace/Caching_Strategies_T.inl b/externals/ace/Caching_Strategies_T.inl deleted file mode 100644 index 41fa2d30301..00000000000 --- a/externals/ace/Caching_Strategies_T.inl +++ /dev/null @@ -1,456 +0,0 @@ -// -*-C++-*- -// -//$Id: Caching_Strategies_T.inl 80826 2008-03-04 14:51:23Z wotte $ - -////////////////////////////////////////////////////////////////////////////////// - -#include "ace/OS_Memory.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template ACE_INLINE -ACE_Caching_Strategy_Adapter::ACE_Caching_Strategy_Adapter (IMPLEMENTATION *implementation, - bool delete_implementation) - : implementation_ (implementation), - delete_implementation_ (delete_implementation) -{ - if (this->implementation_ == 0) - { - ACE_NEW (this->implementation_, - IMPLEMENTATION); - this->delete_implementation_ = true; - } -} - -template ACE_INLINE -ACE_Caching_Strategy_Adapter::~ACE_Caching_Strategy_Adapter (void) -{ - if (this->delete_implementation_) - { - delete this->implementation_; - this->delete_implementation_ = false; - this->implementation_ = 0; - } -} - -template ACE_INLINE ATTRIBUTES -ACE_Caching_Strategy_Adapter::attributes (void) -{ - return this->implementation_->attributes (); -} - -template ACE_INLINE double -ACE_Caching_Strategy_Adapter::purge_percent (void) -{ - return this->implementation_->purge_percent (); -} - -template ACE_INLINE void -ACE_Caching_Strategy_Adapter::purge_percent (double percentage) -{ - this->implementation_->purge_percent (percentage); -} - -template ACE_INLINE int -ACE_Caching_Strategy_Adapter::notify_bind (int result, - const ATTRIBUTES &attr) -{ - return this->implementation_->notify_bind (result, - attr); -} - -template ACE_INLINE int -ACE_Caching_Strategy_Adapter::notify_find (int result, - ATTRIBUTES &attr) -{ - return this->implementation_->notify_find (result, - attr); -} - -template ACE_INLINE int -ACE_Caching_Strategy_Adapter::notify_unbind (int result, - const ATTRIBUTES &attr) -{ - return this->implementation_->notify_unbind (result, - attr); -} - -template ACE_INLINE int -ACE_Caching_Strategy_Adapter::notify_trybind (int result, - ATTRIBUTES &attr) -{ - return this->implementation_->notify_trybind (result, - attr); -} - -template ACE_INLINE int -ACE_Caching_Strategy_Adapter::notify_rebind (int result, - const ATTRIBUTES &attr) -{ - return this->implementation_->notify_rebind (result, - attr); -} - -template ACE_INLINE IMPLEMENTATION & -ACE_Caching_Strategy_Adapter::implementation (void) -{ - return *this->implementation_; -} - -template ACE_INLINE CACHING_UTILITY & -ACE_Caching_Strategy_Adapter::caching_utility (void) -{ - return this->implementation_->caching_utility (); -} - -template ACE_INLINE void -ACE_Caching_Strategy_Adapter::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Caching_Strategy_Adapter::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -////////////////////////////////////////////////////////////////////////////////// - -template ACE_INLINE ATTRIBUTES -ACE_LRU_Caching_Strategy::attributes (void) -{ - return this->timer_; -} - -template ACE_INLINE double -ACE_LRU_Caching_Strategy::purge_percent (void) -{ - return this->purge_percent_; -} - -template ACE_INLINE void -ACE_LRU_Caching_Strategy::purge_percent (double percentage) -{ - this->purge_percent_ = percentage; -} - -template ACE_INLINE int -ACE_LRU_Caching_Strategy::notify_bind ( - int result, - const ATTRIBUTES & /* attr */) -{ - if (result == 0) - ++this->timer_; - - return result; -} - -template ACE_INLINE int -ACE_LRU_Caching_Strategy::notify_find ( - int result, - ATTRIBUTES &attr) -{ - if (result == 0) - { - attr = this->timer_; - ++this->timer_; - } - - return result; -} - -template ACE_INLINE int -ACE_LRU_Caching_Strategy::notify_unbind ( - int result, - const ATTRIBUTES & /* attr */) -{ - return result; -} - -template ACE_INLINE int -ACE_LRU_Caching_Strategy::notify_trybind ( - int result, - ATTRIBUTES & /* attr */) -{ - return result; -} - -template ACE_INLINE int -ACE_LRU_Caching_Strategy::notify_rebind ( - int result, - const ATTRIBUTES & /* attr */) -{ - if (result == 0) - ++this->timer_; - - return result; -} - -template ACE_INLINE CACHING_UTILITY & -ACE_LRU_Caching_Strategy::caching_utility (void) -{ - return this->caching_utility_; -} - -template ACE_INLINE void -ACE_LRU_Caching_Strategy::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_LRU_Caching_Strategy::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("timer_ = %d "), this->timer_)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -////////////////////////////////////////////////////////////////////////////////// - -template ACE_INLINE ATTRIBUTES -ACE_LFU_Caching_Strategy::attributes (void) -{ - return 0; -} - -template ACE_INLINE double -ACE_LFU_Caching_Strategy::purge_percent (void) -{ - return this->purge_percent_; -} - -template ACE_INLINE void -ACE_LFU_Caching_Strategy::purge_percent (double percentage) -{ - this->purge_percent_ = percentage; -} - -template ACE_INLINE int -ACE_LFU_Caching_Strategy::notify_bind (int result, - const ATTRIBUTES & /* attr */) -{ - - return result; -} - -template ACE_INLINE int -ACE_LFU_Caching_Strategy::notify_find (int result, - ATTRIBUTES &attr) -{ - if (result == 0) - ++attr; - - return result; -} - -template ACE_INLINE int -ACE_LFU_Caching_Strategy::notify_trybind (int result, - ATTRIBUTES & /* attr */) -{ - return result; -} - -template ACE_INLINE int -ACE_LFU_Caching_Strategy::notify_rebind (int result, - const ATTRIBUTES & /* attr */) -{ - return result; -} - -template ACE_INLINE int -ACE_LFU_Caching_Strategy::notify_unbind (int result, - const ATTRIBUTES & /* attr */) -{ - return result; -} - -template ACE_INLINE CACHING_UTILITY & -ACE_LFU_Caching_Strategy::caching_utility (void) -{ - return this->caching_utility_; -} - -template ACE_INLINE void -ACE_LFU_Caching_Strategy::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_LFU_Caching_Strategy::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -////////////////////////////////////////////////////////////////////////////////////// - -template ACE_INLINE ATTRIBUTES -ACE_FIFO_Caching_Strategy::attributes (void) -{ - return this->order_; -} - -template ACE_INLINE double -ACE_FIFO_Caching_Strategy::purge_percent (void) -{ - return this->purge_percent_; -} - -template ACE_INLINE void -ACE_FIFO_Caching_Strategy::purge_percent (double percentage) -{ - this->purge_percent_ = percentage; -} - -template ACE_INLINE int -ACE_FIFO_Caching_Strategy::notify_bind (int result, - const ATTRIBUTES &attr) -{ - ACE_UNUSED_ARG (attr); - - if (result == 0) - ++this->order_; - - return result; -} - -template ACE_INLINE int -ACE_FIFO_Caching_Strategy::notify_find (int result, - ATTRIBUTES &attr) -{ - ACE_UNUSED_ARG (attr); - - return result; -} - -template ACE_INLINE int -ACE_FIFO_Caching_Strategy::notify_unbind (int result, - const ATTRIBUTES &attr) -{ - ACE_UNUSED_ARG (attr); - - return result; -} - -template ACE_INLINE int -ACE_FIFO_Caching_Strategy::notify_trybind (int result, - ATTRIBUTES &attr) -{ - ACE_UNUSED_ARG (attr); - - return result; -} - -template ACE_INLINE int -ACE_FIFO_Caching_Strategy::notify_rebind (int result, - const ATTRIBUTES &attr) -{ - ACE_UNUSED_ARG (attr); - - if (result == 0) - ++this->order_; - - return result; -} - -template ACE_INLINE CACHING_UTILITY & -ACE_FIFO_Caching_Strategy::caching_utility (void) -{ - return this->caching_utility_; -} - -template ACE_INLINE void -ACE_FIFO_Caching_Strategy::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_FIFO_Caching_Strategy::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("order_ = %d "), this->order_)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -////////////////////////////////////////////////////////////////////////////////// - -template ACE_INLINE ATTRIBUTES -ACE_Null_Caching_Strategy::attributes (void) -{ - return 0; -} - -template ACE_INLINE double -ACE_Null_Caching_Strategy::purge_percent (void) -{ - return 0; -} - -template ACE_INLINE void -ACE_Null_Caching_Strategy::purge_percent (double percentage) -{ - ACE_UNUSED_ARG (percentage); -} - -template ACE_INLINE int -ACE_Null_Caching_Strategy::notify_bind (int result, - const ATTRIBUTES &attr) -{ - ACE_UNUSED_ARG (attr); - - return result; -} - -template ACE_INLINE int -ACE_Null_Caching_Strategy::notify_find (int result, - ATTRIBUTES &attr) -{ - ACE_UNUSED_ARG (attr); - - return result; -} - -template ACE_INLINE int -ACE_Null_Caching_Strategy::notify_unbind (int result, - const ATTRIBUTES &attr) -{ - ACE_UNUSED_ARG (attr); - - return result; -} - -template ACE_INLINE int -ACE_Null_Caching_Strategy::notify_trybind (int result, - ATTRIBUTES &attr) -{ - ACE_UNUSED_ARG (attr); - - return result; -} - -template ACE_INLINE int -ACE_Null_Caching_Strategy::notify_rebind (int result, - const ATTRIBUTES &attr) -{ - ACE_UNUSED_ARG (attr); - - return result; -} - -template ACE_INLINE CACHING_UTILITY & -ACE_Null_Caching_Strategy::caching_utility (void) -{ - return this->caching_utility_; -} - -template ACE_INLINE void -ACE_Null_Caching_Strategy::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Null_Caching_Strategy::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -////////////////////////////////////////////////////////////////////////////////// diff --git a/externals/ace/Caching_Utility_T.cpp b/externals/ace/Caching_Utility_T.cpp deleted file mode 100644 index a03a4575891..00000000000 --- a/externals/ace/Caching_Utility_T.cpp +++ /dev/null @@ -1,499 +0,0 @@ -// $Id: Caching_Utility_T.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#ifndef ACE_CACHING_UTILITY_T_CPP -#define ACE_CACHING_UTILITY_T_CPP - -#include "ace/Caching_Utility_T.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -#pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Min_Max.h" -#include "ace/OS_Memory.h" -#include "ace/Recyclable.h" - -////////////////////////////////////////////////////////////////////////////// - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template -ACE_Pair_Caching_Utility::ACE_Pair_Caching_Utility (ACE_Cleanup_Strategy *cleanup_strategy, - int delete_cleanup_strategy) - : cleanup_strategy_ (cleanup_strategy), - delete_cleanup_strategy_ (delete_cleanup_strategy) -{ - if (cleanup_strategy == 0) - { - ACE_NEW (this->cleanup_strategy_, - CLEANUP_STRATEGY); - this->delete_cleanup_strategy_ = 1; - } -} - -template -ACE_Pair_Caching_Utility::~ACE_Pair_Caching_Utility (void) -{ - if (this->delete_cleanup_strategy_) - delete this->cleanup_strategy_; -} - -template int -ACE_Pair_Caching_Utility::clear_cache (CONTAINER &container, - double purge_percent) -{ - // Check that the purge_percent is non-zero. - if (purge_percent == 0) - return 0; - - // Get the number of entries in the container. - size_t current_map_size = container.current_size (); - - // Also whether the number of entries in the cache! - // Oops! then there is no way out but exiting. So return an error. - if (current_map_size == 0) - return 0; - - // Calculate the no of entries to remove from the cache depending - // upon the . - size_t const entries_to_remove - = ACE_MAX (static_cast (1), - static_cast (static_cast (purge_percent) - / 100 * current_map_size)); - KEY *key_to_remove = 0; - VALUE *value_to_remove = 0; - - for (size_t i = 0; i < entries_to_remove ; ++i) - { - this->minimum (container, - key_to_remove, - value_to_remove); - - // Simply verifying that the key is non-zero. - // This is important for strategies where the minimum - // entry cant be found due to constraints on the type of entry - // to remove. - if (key_to_remove == 0) - return 0; - - if (this->cleanup_strategy_->cleanup (container, - key_to_remove, - value_to_remove) == -1) - return -1; - - } - - return 0; -} - -template void -ACE_Pair_Caching_Utility::minimum (CONTAINER &container, - KEY *&key_to_remove, - VALUE *&value_to_remove) -{ - // Starting values. - ITERATOR iter = container.begin (); - ITERATOR end = container.end (); - ATTRIBUTES min = (*iter).int_id_.second (); - key_to_remove = &(*iter).ext_id_; - value_to_remove = &(*iter).int_id_; - - // The iterator moves thru the container searching for the entry - // with the lowest ATTRIBUTES. - for (++iter; - iter != end; - ++iter) - { - if (min > (*iter).int_id_.second ()) - { - // Ah! an item with lower ATTTRIBUTES... - min = (*iter).int_id_.second (); - key_to_remove = &(*iter).ext_id_; - value_to_remove = &(*iter).int_id_; - } - } -} - -//////////////////////////////////////////////////////////////////////////////////////////////////////// - -template -ACE_Recyclable_Handler_Caching_Utility::ACE_Recyclable_Handler_Caching_Utility (ACE_Cleanup_Strategy *cleanup_strategy, - int delete_cleanup_strategy) - : cleanup_strategy_ (cleanup_strategy), - delete_cleanup_strategy_ (delete_cleanup_strategy) -{ - if (cleanup_strategy == 0) - { - ACE_NEW (this->cleanup_strategy_, - CLEANUP_STRATEGY); - this->delete_cleanup_strategy_ = 1; - } -} - -template -ACE_Recyclable_Handler_Caching_Utility::~ACE_Recyclable_Handler_Caching_Utility (void) -{ - if (this->delete_cleanup_strategy_) - delete this->cleanup_strategy_; -} - -template int -ACE_Recyclable_Handler_Caching_Utility::clear_cache (CONTAINER &container, - double purge_percent) -{ - // Check that the purge_percent is non-zero. - if (purge_percent == 0) - return 0; - - // Get the number of entries in the container. - size_t current_map_size = container.current_size (); - - // Also whether the number of entries in the cache is just one! - // Oops! then there is no way out but exiting. So return an error. - // if (current_map_size <= 1) - if (current_map_size == 0) - return 0; - - // Calculate the no of entries to remove from the cache depending - // upon the . - size_t const entries_to_remove - = ACE_MAX (static_cast (1), - static_cast (static_cast (purge_percent) - / 100 * current_map_size)); - - KEY *key_to_remove = 0; - VALUE *value_to_remove = 0; - - for (size_t i = 0; i < entries_to_remove ; ++i) - { - this->minimum (container, - key_to_remove, - value_to_remove); - - // Simply verifying that the key is non-zero. - // This is important for strategies where the minimum - // entry cant be found due to constraints on the type of entry - // to remove. - if (key_to_remove == 0) - return 0; - - if (this->cleanup_strategy_->cleanup (container, - key_to_remove, - value_to_remove) == -1) - return -1; - } - - return 0; -} - -template void -ACE_Recyclable_Handler_Caching_Utility::minimum (CONTAINER &container, - KEY *&key_to_remove, - VALUE *&value_to_remove) -{ - // Starting values. - ITERATOR end = container.end (); - ITERATOR iter = container.begin (); - ATTRIBUTES min = (*iter).int_id_.second (); - key_to_remove = 0; - value_to_remove = 0; - // Found the minimum entry to be purged? - int found = 0; - - // The iterator moves thru the container searching for the entry - // with the lowest ATTRIBUTES. - for (; - iter != end; - ++iter) - { - // If the entry isnt IDLE_AND_PURGABLE continue until you reach - // the first entry which can be purged. This is the minimum with - // which you will compare the rest of the purgable entries. - if ((*iter).ext_id_.recycle_state () == ACE_RECYCLABLE_IDLE_AND_PURGABLE || - (*iter).ext_id_.recycle_state () == ACE_RECYCLABLE_PURGABLE_BUT_NOT_IDLE) - { - if (found == 0) - { - min = (*iter).int_id_.second (); - key_to_remove = &(*iter).ext_id_; - value_to_remove = &(*iter).int_id_; - found = 1; - } - else - { - // Ah! an entry with lower ATTTRIBUTES... - if (min > (*iter).int_id_.second ()) - { - min = (*iter).int_id_.second (); - key_to_remove = &(*iter).ext_id_; - value_to_remove = &(*iter).int_id_; - } - } - } - } -} - -//////////////////////////////////////////////////////////////////////////////// - -template -ACE_Refcounted_Recyclable_Handler_Caching_Utility::ACE_Refcounted_Recyclable_Handler_Caching_Utility (ACE_Cleanup_Strategy *cleanup_strategy, - int delete_cleanup_strategy) - : cleanup_strategy_ (cleanup_strategy), - delete_cleanup_strategy_ (delete_cleanup_strategy), - marked_as_closed_entries_ (0) -{ - if (cleanup_strategy == 0) - { - ACE_NEW (this->cleanup_strategy_, - CLEANUP_STRATEGY); - this->delete_cleanup_strategy_ = 1; - } -} - -template -ACE_Refcounted_Recyclable_Handler_Caching_Utility::~ACE_Refcounted_Recyclable_Handler_Caching_Utility (void) -{ - if (this->delete_cleanup_strategy_) - delete this->cleanup_strategy_; -} - -template int -ACE_Refcounted_Recyclable_Handler_Caching_Utility::clear_cache (CONTAINER &container, - double purge_percent) -{ - // Check that the purge_percent is non-zero. - if (purge_percent == 0) - return 0; - - // Get the number of entries in the container which can be considered for purging. - size_t const available_entries = - container.current_size () - this->marked_as_closed_entries_; - - // Also whether the number of entries in the cache zero. - // Oops! then there is no way out but exiting. - if (available_entries <= 0) - return 0; - - // Calculate the no of entries to remove from the cache depending - // upon the . - size_t entries_to_remove - = ACE_MAX (static_cast (1), - static_cast (static_cast (purge_percent) - / 100 * available_entries)); - - if (entries_to_remove >= available_entries || entries_to_remove == 0) - entries_to_remove = available_entries - 1; - - KEY *key_to_remove = 0; - VALUE *value_to_remove = 0; - - for (size_t i = 0; i < entries_to_remove ; ++i) - { - this->minimum (container, - key_to_remove, - value_to_remove); - - // Simply verifying that the key is non-zero. - // This is important for strategies where the minimum - // entry cant be found due to constraints on the type of entry - // to remove. - if (key_to_remove == 0) - return 0; - - if (this->cleanup_strategy_->cleanup (container, - key_to_remove, - value_to_remove) == -1) - return -1; - - ++this->marked_as_closed_entries_; - } - - return 0; -} - -template void -ACE_Refcounted_Recyclable_Handler_Caching_Utility::minimum (CONTAINER &container, - KEY *&key_to_remove, - VALUE *&value_to_remove) -{ - // Starting values. - ITERATOR end = container.end (); - ITERATOR iter = container.begin (); - ATTRIBUTES min = (*iter).int_id_.second (); - key_to_remove = 0; - value_to_remove = 0; - // Found the minimum entry to be purged? - int found = 0; - - // The iterator moves thru the container searching for the entry - // with the lowest ATTRIBUTES. - for (; - iter != end; - ++iter) - { - // If the entry isnt IDLE_AND_PURGABLE continue until you reach - // the first entry which can be purged. This is the minimum with - // which you will compare the rest of the purgable entries. - if ((*iter).ext_id_.recycle_state () == ACE_RECYCLABLE_IDLE_AND_PURGABLE || - (*iter).ext_id_.recycle_state () == ACE_RECYCLABLE_PURGABLE_BUT_NOT_IDLE) - { - if (found == 0) - { - min = (*iter).int_id_.second (); - key_to_remove = &(*iter).ext_id_; - value_to_remove = &(*iter).int_id_; - found = 1; - } - else - { - // Ah! an entry with lower ATTTRIBUTES... - if (min > (*iter).int_id_.second ()) - { - min = (*iter).int_id_.second (); - key_to_remove = &(*iter).ext_id_; - value_to_remove = &(*iter).int_id_; - } - } - } - } -} - -//////////////////////////////////////////////////////////////////////////////// - -template -ACE_Handler_Caching_Utility::ACE_Handler_Caching_Utility (ACE_Cleanup_Strategy *cleanup_strategy, - int delete_cleanup_strategy) - : cleanup_strategy_ (cleanup_strategy), - delete_cleanup_strategy_ (delete_cleanup_strategy) -{ - if (cleanup_strategy == 0) - { - ACE_NEW (this->cleanup_strategy_, - CLEANUP_STRATEGY); - this->delete_cleanup_strategy_ = 1; - } -} - -template -ACE_Handler_Caching_Utility::~ACE_Handler_Caching_Utility (void) -{ - if (this->delete_cleanup_strategy_) - delete this->cleanup_strategy_; -} - -template int -ACE_Handler_Caching_Utility::clear_cache (CONTAINER &container, - double purge_percent) -{ - // Check that the purge_percent is non-zero. - if (purge_percent == 0) - return 0; - - // Get the number of entries in the container. - size_t current_map_size = container.current_size (); - - // Also whether the number of entries in the cache is just one! - // Oops! then there is no way out but exiting. So return an error. - if (current_map_size == 0) - return 0; - - // Calculate the no of entries to remove from the cache depending - // upon the . - size_t entries_to_remove - = ACE_MAX (static_cast (1), - static_cast (static_cast (purge_percent) - / 100 * current_map_size)); - - KEY *key_to_remove = 0; - VALUE *value_to_remove = 0; - - for (size_t i = 0; i < entries_to_remove ; ++i) - { - this->minimum (container, - key_to_remove, - value_to_remove); - - if (this->cleanup_strategy_->cleanup (container, - key_to_remove, - value_to_remove) == -1) - return -1; - } - - return 0; -} - -template void -ACE_Handler_Caching_Utility::minimum (CONTAINER &container, - KEY *&key_to_remove, - VALUE *&value_to_remove) -{ - // Starting values. - ITERATOR iter = container.begin (); - ITERATOR end = container.end (); - ATTRIBUTES min = (*iter).int_id_->caching_attributes (); - key_to_remove = &(*iter).ext_id_; - value_to_remove = &(*iter).int_id_; - - // The iterator moves thru the container searching for the entry - // with the lowest ATTRIBUTES. - for (++iter; - iter != end; - ++iter) - { - if (min > (*iter).int_id_->caching_attributes () && - (*iter).int_id_->active () != 1) - { - // Ah! an item with lower ATTTRIBUTES... - min = (*iter).int_id_->caching_attributes (); - key_to_remove = &(*iter).ext_id_; - value_to_remove = &(*iter).int_id_; - } - } -} - -//////////////////////////////////////////////////////////////////////////////////////////////////////// - -template -ACE_Null_Caching_Utility::ACE_Null_Caching_Utility (ACE_Cleanup_Strategy *cleanup_strategy, - int delete_cleanup_strategy) - : cleanup_strategy_ (cleanup_strategy), - delete_cleanup_strategy_ (delete_cleanup_strategy) -{ - if (cleanup_strategy == 0) - { - ACE_NEW (this->cleanup_strategy_, - CLEANUP_STRATEGY); - this->delete_cleanup_strategy_ = 1; - } -} - -template -ACE_Null_Caching_Utility::~ACE_Null_Caching_Utility (void) -{ - if (this->delete_cleanup_strategy_) - delete this->cleanup_strategy_; -} - -template int -ACE_Null_Caching_Utility::clear_cache (CONTAINER &container, - double purge_percent) -{ - ACE_UNUSED_ARG (container); - ACE_UNUSED_ARG (purge_percent); - - return 0; -} - -template void -ACE_Null_Caching_Utility::minimum (CONTAINER &container, - KEY *&key_to_remove, - VALUE *&value_to_remove) -{ - ACE_UNUSED_ARG (container); - ACE_UNUSED_ARG (key_to_remove); - ACE_UNUSED_ARG (value_to_remove); -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_CACHING_UTILITY_T_CPP */ diff --git a/externals/ace/Caching_Utility_T.h b/externals/ace/Caching_Utility_T.h deleted file mode 100644 index 5428682d099..00000000000 --- a/externals/ace/Caching_Utility_T.h +++ /dev/null @@ -1,347 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Caching_Utility_T.h - * - * $Id: Caching_Utility_T.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Kirthika Parameswaran - */ -//============================================================================= - -#ifndef ACE_CACHING_UTILITY_H -#define ACE_CACHING_UTILITY_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Global_Macros.h" -#include "ace/Cleanup_Strategies_T.h" - -// For linkers that cant grok long names. -#define ACE_Pair_Caching_Utility APUTIL - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Pair_Caching_Utility - * - * @brief Defines a helper class for the Caching Strategies. - * - * This class defines the methods commonly used by the different - * caching strategies. For instance: method which - * decides and purges the entry from the container. @note This - * class helps in the caching_strategies using a container - * containing entries of > - * kind. The attributes helps in deciding the entries to be - * purged. The Cleanup_Strategy is the callback class to which the - * entries to be cleaned up will be delegated. - */ -template -class ACE_Pair_Caching_Utility -{ -public: - - typedef ACE_Cleanup_Strategy CLEANUP_STRATEGY; - - /// Constructor. - ACE_Pair_Caching_Utility (ACE_Cleanup_Strategy *cleanup_strategy = 0, - int delete_cleanup_strategy = 0); - - /// Destructor. - ~ACE_Pair_Caching_Utility (void); - - /** - * Purge entries from the @a container. The Cleanup_Strategy will do the - * actual job of cleanup once the entries to be cleaned up are decided. - */ - int clear_cache (CONTAINER &container, - double purge_percent); - -protected: - - /// Find the entry with minimum caching attributes. - void minimum (CONTAINER &container, - KEY *&key_to_remove, - VALUE *&value_to_remove); - - /// The cleanup strategy which can be used to destroy the entries of - /// the container. - CLEANUP_STRATEGY *cleanup_strategy_; - - /// Whether the cleanup_strategy should be destroyed or not. - int delete_cleanup_strategy_; - - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Pair_Caching_Utility &)) - ACE_UNIMPLEMENTED_FUNC (ACE_Pair_Caching_Utility (const ACE_Pair_Caching_Utility &)) -}; - -//////////////////////////////////////////////////////////////////////////////// -#define ACE_Recyclable_Handler_Caching_Utility ARHUTIL - -/** - * @class ACE_Recyclable_Handler_Caching_Utility - * - * @brief Defines a helper class for the Caching Strategies. - * - * This class defines the methods commonly used by the different - * caching strategies. For instance: method which - * decides and purges the entry from the container. @note This - * class helps in the caching_strategies using a container - * containing entries of kind. The attributes - * helps in deciding the entries to be purged. The - * Cleanup_Strategy is the callback class to which the entries to - * be cleaned up will be delegated. - */ -template -class ACE_Recyclable_Handler_Caching_Utility -{ - -public: - - typedef ACE_Recyclable_Handler_Cleanup_Strategy CLEANUP_STRATEGY; - typedef ACE_Cleanup_Strategy CLEANUP_STRATEGY_BASE; - - /// Constructor. - ACE_Recyclable_Handler_Caching_Utility (ACE_Cleanup_Strategy *cleanup_strategy = 0, - int delete_cleanup_strategy = 0); - - /// Destructor. - ~ACE_Recyclable_Handler_Caching_Utility (void); - - /** - * Purge entries from the . The Cleanup_Strategy will do - * the actual job of cleanup once the entries to be cleaned up are - * decided. - */ - int clear_cache (CONTAINER &container, - double purge_percent); - -protected: - - /// Find the entry with minimum caching attributes. - void minimum (CONTAINER &container, - KEY *&key_to_remove, - VALUE *&value_to_remove); - - /// This is the default Cleanup Strategy for this utility. - CLEANUP_STRATEGY_BASE *cleanup_strategy_; - - /// Whether the cleanup_strategy should be destroyed or not. - int delete_cleanup_strategy_; - -private: - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Recyclable_Handler_Caching_Utility &)) - ACE_UNIMPLEMENTED_FUNC (ACE_Recyclable_Handler_Caching_Utility (const ACE_Recyclable_Handler_Caching_Utility &)) -}; - -/////////////////////////////////////////////////////////////////////////// -#define ACE_Refcounted_Recyclable_Handler_Caching_Utility ARRHUTIL - -/** - * @class ACE_Refcounted_Recyclable_Handler_Caching_Utility - * - * @brief Defines a helper class for the Caching Strategies. - * - * This class defines the methods commonly used by the different - * caching strategies. For instance: clear_cache () method which - * decides and purges the entry from the container. @note This - * class helps in the caching_strategies using a container - * containing entries of kind. The attributes helps in - * deciding the entries to be purged. The Cleanup_Strategy is the - * callback class to which the entries to be cleaned up will be - * delegated. - */ -template -class ACE_Refcounted_Recyclable_Handler_Caching_Utility -{ - -public: - - typedef ACE_Refcounted_Recyclable_Handler_Cleanup_Strategy CLEANUP_STRATEGY; - typedef ACE_Cleanup_Strategy CLEANUP_STRATEGY_BASE; - - /// Constructor. - ACE_Refcounted_Recyclable_Handler_Caching_Utility (ACE_Cleanup_Strategy *cleanup_strategy = 0, - int delete_cleanup_strategy = 0); - - /// Destructor. - ~ACE_Refcounted_Recyclable_Handler_Caching_Utility (void); - - /** - * Purge entries from the . The Cleanup_Strategy will do - * the actual job of cleanup once the entries to be cleaned up are - * decided. - */ - int clear_cache (CONTAINER &container, - double purge_percent); - -protected: - - /// Find the entry with minimum caching attributes. - void minimum (CONTAINER &container, - KEY *&key_to_remove, - VALUE *&value_to_remove); - - /// This is the default Cleanup Strategy for this utility. - CLEANUP_STRATEGY_BASE *cleanup_strategy_; - - /// Whether the cleanup_strategy should be destroyed or not. - int delete_cleanup_strategy_; - - /** - * This figure denotes the number of entries are there in the - * container which have been marked as closed already but might - * not have been unbound from the container. - */ - size_t marked_as_closed_entries_; - -private: - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Refcounted_Recyclable_Handler_Caching_Utility &)) - ACE_UNIMPLEMENTED_FUNC (ACE_Refcounted_Recyclable_Handler_Caching_Utility (const ACE_Refcounted_Recyclable_Handler_Caching_Utility &)) -}; - -//////////////////////////////////////////////////////////////////////////////////////// - -/** - * @class ACE_Handler_Caching_Utility - * - * @brief Defines a helper class for the Caching Strategies. - * - * This class defines the methods commonly used by the different - * caching strategies. For instance: method which - * decides and purges the entry from the container. @note This - * class helps in the caching_strategies using a container - * containing entries of kind where the HANDLER - * contains the caching attributes which help in deciding the - * entries to be purged. The Cleanup_Strategy is the callback - * class to which the entries to be cleaned up will be delegated. - */ -template -class ACE_Handler_Caching_Utility -{ -public: - - typedef ACE_Handler_Cleanup_Strategy CLEANUP_STRATEGY; - typedef ACE_Cleanup_Strategy CLEANUP_STRATEGY_BASE; - - /// Constructor. - ACE_Handler_Caching_Utility (ACE_Cleanup_Strategy *cleanup_strategy = 0, - int delete_cleanup_strategy = 0); - - /// Destructor. - ~ACE_Handler_Caching_Utility (void); - - /** - * Purge entries from the . The Cleanup_Strategy will do - * the actual job of cleanup once the entries to be cleaned up are - * decided. - */ - int clear_cache (CONTAINER &container, - double purge_percent); - -protected: - - /** - * Find the entry with minimum caching attributes. This is handler - * specific since this utility is to be used very specifically for - * handler who have caching_attributes for server side acched - * connection management. - */ - void minimum (CONTAINER &container, - KEY *&key_to_remove, - VALUE *&value_to_remove); - - /// The cleanup strategy which can be used to destroy the entries of - /// the container. - CLEANUP_STRATEGY_BASE *cleanup_strategy_; - - /// Whether the cleanup_strategy should be destroyed or not. - int delete_cleanup_strategy_; - -private: - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Handler_Caching_Utility &)) - ACE_UNIMPLEMENTED_FUNC (ACE_Handler_Caching_Utility (const ACE_Handler_Caching_Utility &)) -}; - -/////////////////////////////////////////////////////////////////////////// -#define ACE_Null_Caching_Utility ANUTIL -/** - * @class ACE_Null_Caching_Utility - * - * @brief Defines a dummy helper class for the Caching Strategies. - * - * This class defines the methods commonly used by the different - * caching strategies. For instance: method which - * decides and purges the entry from the container. @note This - * class is be used with the Null_Caching_Strategy. The - * Cleanup_Strategy is the callback class to which the entries to - * be cleaned up will be delegated. - */ -template -class ACE_Null_Caching_Utility -{ -public: - - typedef ACE_Null_Cleanup_Strategy CLEANUP_STRATEGY; - typedef ACE_Cleanup_Strategy CLEANUP_STRATEGY_BASE; - - /// Constructor. - ACE_Null_Caching_Utility (ACE_Cleanup_Strategy *cleanup_strategy = 0, - int delete_cleanup_strategy = 0); - - /// Destructor. - ~ACE_Null_Caching_Utility (void); - - /** - * Purge entries from the . The Cleanup_Strategy will do - * the actual job of cleanup once the entries to be cleaned up are - * decided. @note Here it is a no-op. - */ - int clear_cache (CONTAINER &container, - double purge_percent); - -protected: - - /** - * Find the entry with minimum caching attributes. This is handler - * specific since this utility is to be used very specifically for - * handler who have caching_attributes for server side acched - * connection management.@note Here it is a no-op. - */ - void minimum (CONTAINER &container, - KEY *&key_to_remove, - VALUE *&value_to_remove); - - /// The cleanup strategy which can be used to destroy the entries of - /// the container. - CLEANUP_STRATEGY_BASE *cleanup_strategy_; - - /// Whether the cleanup_strategy should be destroyed or not. - int delete_cleanup_strategy_; - -private: - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Null_Caching_Utility &)) - ACE_UNIMPLEMENTED_FUNC (ACE_Null_Caching_Utility (const ACE_Null_Caching_Utility &)) -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Caching_Utility_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Caching_Utility_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" - -#endif /* ACE_CACHING_UTILITY_H */ diff --git a/externals/ace/Capabilities.cpp b/externals/ace/Capabilities.cpp deleted file mode 100644 index 5d46e75472a..00000000000 --- a/externals/ace/Capabilities.cpp +++ /dev/null @@ -1,355 +0,0 @@ -#include "ace/Capabilities.h" -#include "ace/OS_NS_ctype.h" -#include "ace/OS_Memory.h" -#include "ace/OS_NS_string.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Capabilities.inl" -#endif /* !__ACE_INLINE__ */ - -#include "ace/OS_NS_stdio.h" - -ACE_RCSID (ace, - Capabilities, - "$Id: Capabilities.cpp 80826 2008-03-04 14:51:23Z wotte $") - - -#define ACE_ESC ((ACE_TCHAR)0x1b) - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_CapEntry::~ACE_CapEntry (void) -{ -} - -ACE_Capabilities::ACE_Capabilities (void) - : caps_ () -{ -} - -ACE_Capabilities::~ACE_Capabilities (void) -{ - this->resetcaps (); -} - -const ACE_TCHAR * -ACE_Capabilities::parse (const ACE_TCHAR *buf, ACE_TString &cap) -{ - while (*buf != ACE_TEXT ('\0') && *buf != ACE_TEXT (',')) - { - if (*buf == ACE_TEXT ('\\')) - { - ++buf; - if (*buf == ACE_TEXT ('E') || *buf == ACE_TEXT ('e')) - { - cap += ACE_ESC; - ++buf; - continue; - } - else if (*buf == ACE_TEXT ('r')) - { - cap += ACE_TEXT ('\r'); - ++buf; - continue; - } - else if (*buf == ACE_TEXT ('n')) - { - cap += ACE_TEXT ('\n'); - ++buf; - continue; - } - else if (*buf == ACE_TEXT ('t')) - { - cap += ACE_TEXT ('\t'); - ++buf; - continue; - } - else if (*buf == ACE_TEXT ('\\')) - { - cap += *buf++; - continue; - } - if (ACE_OS::ace_isdigit(*buf)) - { - // @@ UNICODE Does this work with unicode? - int oc = 0; - for (int i = 0; - i < 3 && *buf && ACE_OS::ace_isdigit (*buf); - i++) - oc = oc * 8 + (*buf++ - ACE_TEXT ('0')); - - cap += (ACE_TCHAR) oc; - continue; - } - } - cap += *buf++; - } - return buf; -} - -const ACE_TCHAR * -ACE_Capabilities::parse (const ACE_TCHAR *buf, int &cap) -{ - int n = 0; - - while (*buf && ACE_OS::ace_isdigit (*buf)) - n = n * 10 + (*buf++ - ACE_TEXT ('0')); - - cap = n; - - return buf; -} - -void -ACE_Capabilities::resetcaps (void) -{ - for (CAPABILITIES_MAP::ITERATOR iter (this->caps_); - !iter.done (); - iter.advance ()) - { - CAPABILITIES_MAP::ENTRY *entry = 0; - iter.next (entry); - delete entry->int_id_; - } - - this->caps_.close (); - this->caps_.open (); -} - -int -ACE_Capabilities::fillent (const ACE_TCHAR *buf) -{ - this->resetcaps (); - while (*buf) - { - ACE_TString s; - int n; - ACE_TString name; - ACE_CapEntry *ce; - - // Skip blanks - while (*buf && ACE_OS::ace_isspace(*buf)) buf++; - // If we get end of line return - - if (*buf == ACE_TEXT ('\0')) - break; - - if (*buf == ACE_TEXT ('#')) - { - while (*buf && *buf != ACE_TEXT ('\n')) - buf++; - if (*buf == ACE_TEXT ('\n')) - buf++; - continue; - } - while(*buf && *buf != ACE_TEXT ('=') - && *buf!= ACE_TEXT ('#') - && *buf != ACE_TEXT (',')) - name += *buf++; - - // If name is null. - switch (*buf) - { - case ACE_TEXT ('='): - // String property - buf = this->parse (buf + 1, s); - ACE_NEW_RETURN (ce, - ACE_StringCapEntry (s), - -1); - if (this->caps_.bind (name, ce) == -1) - { - delete ce; - return -1; - } - break; - case ACE_TEXT ('#'): - // Integer property - buf = this->parse (buf + 1, n); - ACE_NEW_RETURN (ce, - ACE_IntCapEntry (n), - -1); - if (this->caps_.bind (name, ce) == -1) - { - delete ce; - return -1; - } - break; - case ACE_TEXT (','): - // Boolean - ACE_NEW_RETURN (ce, - ACE_BoolCapEntry (1), - -1); - if (this->caps_.bind (name, ce) == -1) - { - delete ce; - return -1; - } - break; - default: - return 0; - } - - if (*buf++ != ACE_TEXT (',')) - return -1; - } - - return 0; -} - -int -ACE_Capabilities::is_entry (const ACE_TCHAR *name, const ACE_TCHAR *line) -{ - for (;;) - { - // Skip blanks or irrelevant characters - while (*line && ACE_OS::ace_isspace(*line)) - ++line; - - // End of line reached - if (*line == ACE_TEXT ('\0')) - break; - - // Build the entry name - ACE_TString nextname; - while (*line && *line != ACE_TEXT ('|') && *line != ACE_TEXT (',')) - nextname += *line++; - - // We have found the required entry? - if (ACE_OS::strcmp (nextname.c_str (), name) == 0) - return 1; - - // Skip puntuaction char if neccesary. - if (*line == ACE_TEXT ('|') || *line == ACE_TEXT (',')) - ++line; - else - { - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("Invalid entry\n"))); - break; - } - } - return 0; -} - -int -ACE_Capabilities::getline (FILE *fp, ACE_TString &line) -{ - int ch; - - line.set (0, 0); - - while ((ch = ACE_OS::fgetc (fp)) != EOF && ch != ACE_TEXT ('\n')) - line += (ACE_TCHAR) ch; - - if (ch == EOF && line.length () == 0) - return -1; - else - return 0; -} - -int -ACE_Capabilities::getval (const ACE_TCHAR *keyname, ACE_TString &val) -{ - ACE_CapEntry* cap = 0; - if (this->caps_.find (keyname, cap) == -1) - return -1; - - ACE_StringCapEntry *scap = - dynamic_cast (cap); - if (scap == 0) - return -1; - - val = scap->getval (); - return 0; -} - -int -ACE_Capabilities::getval (const ACE_TCHAR *keyname, int &val) -{ - ACE_CapEntry *cap = 0; - if (this->caps_.find (keyname, cap) == -1) - return -1; - - ACE_IntCapEntry *icap = - dynamic_cast (cap); - if (icap != 0) - { - val = icap->getval (); - return 0; - } - - ACE_BoolCapEntry *bcap = - dynamic_cast (cap); - - if (bcap == 0) - return -1; - - val = bcap->getval (); - return 0; -} - -#if !defined (ACE_IS_SPLITTING) -static int -is_empty (const ACE_TCHAR *line) -{ - while (*line && ACE_OS::ace_isspace (*line)) - ++line; - - return *line == ACE_TEXT ('\0') || *line == ACE_TEXT ('#'); -} - -static int -is_line (const ACE_TCHAR *line) -{ - while (*line && ACE_OS::ace_isspace (*line)) - ++line; - - return *line != ACE_TEXT ('\0'); -} -#endif /* !ACE_IS_SPLITTING */ - -int -ACE_Capabilities::getent (const ACE_TCHAR *fname, const ACE_TCHAR *name) -{ - FILE *fp = ACE_OS::fopen (fname, ACE_TEXT ("r")); - - if (fp == 0) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("Can't open %s file\n"), - fname), - -1); - - int done; - ACE_TString line; - - while (0 == (done = (this->getline (fp, line) == -1)) - && is_empty (line.c_str ())) - continue; - - while (!done) - { - ACE_TString newline; - ACE_TString description; - - while (0 == (done = (this->getline (fp, newline) == -1))) - if (is_line (newline.c_str ())) - description += newline; - else - break; - - if (this->is_entry (name, line.c_str())) - { - ACE_OS::fclose (fp); - return this->fillent (description.c_str ()); - } - - line = newline; - while (!done && is_empty (line.c_str ())) - done = this->getline (fp, line) == -1; - } - - ACE_OS::fclose (fp); - return -1; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Capabilities.h b/externals/ace/Capabilities.h deleted file mode 100644 index f4c8b5cc6fb..00000000000 --- a/externals/ace/Capabilities.h +++ /dev/null @@ -1,221 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file Capabilities.h - * - * $Id: Capabilities.h 91077 2010-07-13 14:33:08Z johnnyw $ - * - * @author Arturo Montes - */ -//============================================================================= - - -#ifndef ACE_CAPABILITIES_H -#define ACE_CAPABILITIES_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Null_Mutex.h" -#include "ace/Hash_Map_Manager_T.h" -#include "ace/Containers.h" -#include "ace/SString.h" -#include "ace/Functor_String.h" - -#if defined (ACE_IS_SPLITTING) -# include "ace/OS_NS_ctype.h" -#endif /* ACE_IS_SPLITTING */ - - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_CapEntry - * - * @brief This class is the base class for all ACE Capabilities entry - * subclasses. - * - * This class is not instantiable and does not provide accessors - * or methods. If you want to add a new kind of attribute subclass - * this class and dynamic_cast to proper subclass. - */ -class ACE_Export ACE_CapEntry -{ -public: - - virtual ~ACE_CapEntry (void); - -protected: - - enum - { - ACE_INTCAP = 0, - ACE_STRINGCAP = 1, - ACE_BOOLCAP = 2 - }; - - ACE_CapEntry (int captype); - -protected: - - int captype_; - -}; - -/** - * @class ACE_IntCapEntry - * - * @brief This class implement the ACE Integer Capability subclass. - * - * This is a container class for ACE Capabilities integer container - * values. - */ -class ACE_Export ACE_IntCapEntry : public ACE_CapEntry -{ -public: - ACE_IntCapEntry (int val); - int getval (void) const; - -protected: - int val_; -}; - -/** - * @class ACE_StringCapEntry - * - * @brief This class implement the ACE String Capability subclass. - * - * This is a container class for ACE Capabilities String container - * values. - */ -class ACE_Export ACE_StringCapEntry : public ACE_CapEntry -{ -public: - ACE_StringCapEntry (const ACE_TString &val); - ACE_TString getval (void) const; - -protected: - ACE_TString val_; -}; - -/** - * @class ACE_BoolCapEntry - * - * @brief This class implement the ACE Bool Capability subclass. - * - * This is a container class for ACE Capabilities bool container - * values. - */ -class ACE_Export ACE_BoolCapEntry : public ACE_CapEntry -{ -public: - ACE_BoolCapEntry (int val); - int getval (void) const; - -protected: - int val_; -}; - -/** - * @class ACE_Capabilities - * - * @brief - * This class implement the ACE Capabilities. - * - * This is a container class for ACE Capabilities - * values. Currently exist three different capability values: - * ACE_IntCapEntry (integer), ACE_BoolCapEntry (bool) and - * ACE_StringCapEntry (String). An ACE_Capabilities is a - * unordered set of pair = (String, ACE_CapEntry *). Where - * the first component is the name of capability and the second - * component is a pointer to the capability value container. A - * FILE is a container for ACE_Capabilities, the - * ACE_Capabilities has a name in the file, as a termcap file. - */ -class ACE_Export ACE_Capabilities -{ -public: - - typedef ACE_Hash_Map_Manager_Ex, ACE_Equal_To, ACE_Null_Mutex> CAPABILITIES_MAP; - - /// The Constructor - ACE_Capabilities (void); - - /// The Destructor - ~ACE_Capabilities(void); - -public: - - /// Get a string entry. - int getval (const ACE_TCHAR *ent, ACE_TString &val); - - /// Get an integer entry. - int getval (const ACE_TCHAR *ent, int &val); - - /// Get the ACE_Capabilities name from FILE fname and load the - /// associated capabitily entries in map. - int getent (const ACE_TCHAR *fname, const ACE_TCHAR *name); - -protected: - - /// Parse an integer property - const ACE_TCHAR *parse (const ACE_TCHAR *buf, int &cap); - - /// Parse a string property - const ACE_TCHAR *parse (const ACE_TCHAR *buf, ACE_TString &cap); - - /// Fill the ACE_Capabilities with description in ent. - int fillent(const ACE_TCHAR *ent); - - /// Parse a cap entry - int parseent (const ACE_TCHAR *name, ACE_TCHAR *line); - - /// Get a line from FILE input stream - int getline (FILE* fp, - ACE_TString &line); - - /// Is a valid entry - int is_entry (const ACE_TCHAR *name, const ACE_TCHAR *line); - - /// Reset the set of capabilities - void resetcaps (void); - -private: - - /// This is the set of ACE_CapEntry. - CAPABILITIES_MAP caps_; -}; - -#if defined (ACE_IS_SPLITTING) -int -is_empty (const ACE_TCHAR *line) -{ - while (*line && ACE_OS::ace_isspace (*line)) - ++line; - - return *line == ACE_TEXT ('\0') || *line == ACE_TEXT ('#'); -} - -int -is_line (const ACE_TCHAR *line) -{ - while (*line && ACE_OS::ace_isspace (*line)) - ++line; - - return *line != ACE_TEXT ('\0'); -} -#endif /* ACE_IS_SPLITTING */ - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Capabilities.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* __ACE_CAPABILITIES_H__ */ diff --git a/externals/ace/Capabilities.inl b/externals/ace/Capabilities.inl deleted file mode 100644 index 37284b28696..00000000000 --- a/externals/ace/Capabilities.inl +++ /dev/null @@ -1,52 +0,0 @@ -// -*- C++ -*- -// -// $Id: Capabilities.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE -ACE_CapEntry::ACE_CapEntry (int captype) - : captype_ (captype) -{ -} - -ACE_INLINE -ACE_IntCapEntry::ACE_IntCapEntry (int val) - : ACE_CapEntry (ACE_INTCAP), - val_ (val) -{ -} - -ACE_INLINE int -ACE_IntCapEntry::getval (void) const -{ - return val_; -} - -ACE_INLINE -ACE_StringCapEntry::ACE_StringCapEntry (const ACE_TString &val) - : ACE_CapEntry (ACE_STRINGCAP), - val_ (val) -{ -} - -ACE_INLINE ACE_TString -ACE_StringCapEntry::getval (void) const -{ - return val_; -} - -ACE_INLINE -ACE_BoolCapEntry::ACE_BoolCapEntry (int val) - : ACE_CapEntry (ACE_BOOLCAP), - val_(val) -{ -} - -ACE_INLINE int -ACE_BoolCapEntry::getval (void) const -{ - return val_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Cleanup.cpp b/externals/ace/Cleanup.cpp deleted file mode 100644 index 5c7317ed4da..00000000000 --- a/externals/ace/Cleanup.cpp +++ /dev/null @@ -1,181 +0,0 @@ -// $Id: Cleanup.cpp 84201 2009-01-20 06:26:02Z johnnyw $ - -#include "ace/Cleanup.h" - -ACE_RCSID (ace, - Cleanup, - "$Id: Cleanup.cpp 84201 2009-01-20 06:26:02Z johnnyw $") - -#if !defined (ACE_HAS_INLINED_OSCALLS) -# include "ace/Cleanup.inl" -#endif /* ACE_HAS_INLINED_OSCALLS */ - -#include "ace/OS_Memory.h" -#include "ace/OS_NS_string.h" -#include "ace/os_include/os_typeinfo.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -void -ACE_Cleanup::cleanup (void *) -{ - delete this; -} - -ACE_Cleanup::~ACE_Cleanup (void) -{ -} - -/*****************************************************************************/ - -extern "C" void -ACE_CLEANUP_DESTROYER_NAME (ACE_Cleanup *object, void *param) -{ - object->cleanup (param); -} - -/*****************************************************************************/ - -ACE_Cleanup_Info_Node::ACE_Cleanup_Info_Node (void) - : object_ (0), - cleanup_hook_ (0), - param_ (0), - name_ (0) -{ -} - -ACE_Cleanup_Info_Node::ACE_Cleanup_Info_Node (void *object, - ACE_CLEANUP_FUNC cleanup_hook, - void *param, - const char *name) - : object_ (object), - cleanup_hook_ (cleanup_hook), - param_ (param), - name_ (name ? ACE_OS::strdup (name) : 0) -{ -} - -ACE_Cleanup_Info_Node::~ACE_Cleanup_Info_Node (void) -{ - if (this->name_) - ACE_OS::free ((void *) name_); -} - -bool -ACE_Cleanup_Info_Node::operator== (const ACE_Cleanup_Info_Node &o) const -{ - return o.object_ == this->object_ - && o.cleanup_hook_ == this->cleanup_hook_ - && o.param_ == this->param_; -} - -bool -ACE_Cleanup_Info_Node::operator!= (const ACE_Cleanup_Info_Node &o) const -{ - return !(*this == o); -} - - -/*****************************************************************************/ - -ACE_OS_Exit_Info::ACE_OS_Exit_Info (void) -{ -} - -ACE_OS_Exit_Info::~ACE_OS_Exit_Info (void) -{ -} - -int -ACE_OS_Exit_Info::at_exit_i (void *object, - ACE_CLEANUP_FUNC cleanup_hook, - void *param, - const char* name) -{ - // Return -1 and sets errno if unable to allocate storage. Enqueue - // at the head and dequeue from the head to get LIFO ordering. - ACE_Cleanup_Info_Node *new_node = 0; - - ACE_NEW_RETURN (new_node, - ACE_Cleanup_Info_Node (object, cleanup_hook, param, name), - -1); - - registered_objects_.push_front (new_node); - - return 0; -} - -bool -ACE_OS_Exit_Info::find (void *object) -{ - for (ACE_Cleanup_Info_Node *iter = registered_objects_.head (); - iter != 0; - iter = iter->next ()) - { - if (iter->object () == object) - { - // The object has already been registered. - return true; - } - } - - return false; -} - -bool -ACE_OS_Exit_Info::remove (void *object) -{ - ACE_Cleanup_Info_Node *node = 0; - for (ACE_Cleanup_Info_Node *iter = registered_objects_.head (); - iter != 0; - iter = iter->next ()) - { - if (iter->object () == object) - { - node = iter; - break; - } - } - - if (node) - { - registered_objects_.remove (node); - delete node; - return true; - } - - return false; -} - - -void -ACE_OS_Exit_Info::call_hooks (void) -{ - // Call all registered cleanup hooks, in reverse order of - // registration. - for (ACE_Cleanup_Info_Node *iter = registered_objects_.pop_front (); - iter != 0; - iter = registered_objects_.pop_front ()) - { - if (iter->cleanup_hook () == reinterpret_cast ( - ACE_CLEANUP_DESTROYER_NAME)) - { - // The object is an ACE_Cleanup. - ACE_CLEANUP_DESTROYER_NAME ( - reinterpret_cast (iter->object ()), - iter->param ()); - } - else if (iter->object () == &ace_exit_hook_marker) - { - // The hook is an ACE_EXIT_HOOK. - (* reinterpret_cast (iter->cleanup_hook ())) (); - } - else - { - (*iter->cleanup_hook ()) (iter->object (), iter->param ()); - } - delete iter; - } -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Cleanup.h b/externals/ace/Cleanup.h deleted file mode 100644 index bd750724fb3..00000000000 --- a/externals/ace/Cleanup.h +++ /dev/null @@ -1,160 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Cleanup.h - * - * $Id: Cleanup.h 84163 2009-01-15 07:57:27Z johnnyw $ - * - * @author Douglas C. Schmidt - * @author Jesper S. M|ller - * @author and a cast of thousands... - * - * Originally in OS.h. - */ -//============================================================================= - -#ifndef ACE_CLEANUP_H -# define ACE_CLEANUP_H - -# include /**/ "ace/pre.h" - -# include "ace/config-lite.h" - -# if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -# endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include /**/ "ace/ACE_export.h" - -# include "ace/Intrusive_List.h" -# include "ace/Intrusive_List_Node.h" - -#if (defined (ACE_HAS_VERSIONED_NAMESPACE) && ACE_HAS_VERSIONED_NAMESPACE == 1) -# include "ace/Global_Macros.h" -# define ACE_CLEANUP_DESTROYER_NAME ACE_PREPROC_CONCATENATE(ACE_VERSIONED_NAMESPACE_NAME, _ace_cleanup_destroyer) -#else -# define ACE_CLEANUP_DESTROYER_NAME ace_cleanup_destroyer -#endif /* ACE_HAS_VERSIONED_NAMESPACE == 1 */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Cleanup - * - * @brief Base class for objects that are cleaned by ACE_Object_Manager. - */ -class ACE_Export ACE_Cleanup -{ -public: - /// No-op constructor. - ACE_Cleanup (void); - - /// Destructor. - virtual ~ACE_Cleanup (void); - - /// Cleanup method that, by default, simply deletes itself. - virtual void cleanup (void *param = 0); -}; - -/// Adapter for cleanup, used by ACE_Object_Manager. -extern "C" ACE_Export -void ACE_CLEANUP_DESTROYER_NAME (ACE_Cleanup *, void *param = 0); - -/** - * @class ACE_Cleanup_Info_Node - * - * @brief For maintaining a list of ACE_Cleanup_Info items. - * - * For internal use by ACE_Object_Manager. - */ -class ACE_Cleanup_Info_Node : public ACE_Intrusive_List_Node -{ -public: - ACE_Cleanup_Info_Node (void); - ACE_Cleanup_Info_Node (void *object, - ACE_CLEANUP_FUNC cleanup_hook, - void *param, - const char *name); - ~ACE_Cleanup_Info_Node (void); - - /// Equality operator. - bool operator== (const ACE_Cleanup_Info_Node &o) const; - - /// Inequality operator. - bool operator!= (const ACE_Cleanup_Info_Node &o) const; - - void* object(void); - - ACE_CLEANUP_FUNC cleanup_hook (void); - - void *param (void); -private: - /// Point to object that gets passed into the . - void *object_; - - /// Cleanup hook that gets called back. - ACE_CLEANUP_FUNC cleanup_hook_; - - /// Parameter passed to the . - void *param_; - - /// Name of the cleanup object - const char *name_; -}; - -typedef ACE_Intrusive_List ACE_Cleanup_Info_Node_List; - -/** - * @class ACE_OS_Exit_Info - * - * @brief Hold Object Manager cleanup (exit) information. - * - * @internal - * - * For internal use by the ACE library, only. - */ -class ACE_Export ACE_OS_Exit_Info -{ -public: - /// Default constructor. - ACE_OS_Exit_Info (void); - - /// Destructor. - ~ACE_OS_Exit_Info (void); - - /// Use to register a cleanup hook. - int at_exit_i (void *object, ACE_CLEANUP_FUNC cleanup_hook, void *param, const char* name = 0); - - /// Look for a registered cleanup hook object. Returns true if already - /// registered, false if not. - bool find (void *object); - - /// Remove a registered cleanup hook object. Returns true if removed - /// false if not. - bool remove (void *object); - - /// Call all registered cleanup hooks, in reverse order of - /// registration. - void call_hooks (); - -private: - /** - * Keeps track of all registered objects. - */ - ACE_Cleanup_Info_Node_List registered_objects_; -}; - - -ACE_END_VERSIONED_NAMESPACE_DECL - -# if defined (ACE_HAS_INLINED_OSCALLS) -# if defined (ACE_INLINE) -# undef ACE_INLINE -# endif /* ACE_INLINE */ -# define ACE_INLINE inline -# include "ace/Cleanup.inl" -# endif /* ACE_HAS_INLINED_OSCALLS */ - -# include /**/ "ace/post.h" -#endif /* ACE_CLEANUP_H */ diff --git a/externals/ace/Cleanup.inl b/externals/ace/Cleanup.inl deleted file mode 100644 index 196a9f4788f..00000000000 --- a/externals/ace/Cleanup.inl +++ /dev/null @@ -1,30 +0,0 @@ -// -*- C++ -*- -// -// $Id: Cleanup.inl 83956 2008-12-03 07:57:38Z johnnyw $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE -ACE_Cleanup::ACE_Cleanup (void) -{ -} - -ACE_INLINE void* -ACE_Cleanup_Info_Node::object(void) -{ - return this->object_; -} - -ACE_INLINE ACE_CLEANUP_FUNC -ACE_Cleanup_Info_Node::cleanup_hook (void) -{ - return this->cleanup_hook_; -} - -ACE_INLINE void * -ACE_Cleanup_Info_Node::param (void) -{ - return this->param_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Cleanup_Strategies_T.cpp b/externals/ace/Cleanup_Strategies_T.cpp deleted file mode 100644 index 32965993774..00000000000 --- a/externals/ace/Cleanup_Strategies_T.cpp +++ /dev/null @@ -1,95 +0,0 @@ -//$Id: Cleanup_Strategies_T.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#ifndef ACE_CLEANUP_STRATEGIES_T_CPP -#define ACE_CLEANUP_STRATEGIES_T_CPP - -#include "ace/Cleanup_Strategies_T.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -#pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -//////////////////////////////////////////////////////////////////////////// - -template -ACE_Cleanup_Strategy::~ACE_Cleanup_Strategy (void) -{ -} - -template int -ACE_Cleanup_Strategy::cleanup (CONTAINER &container, - KEY *key, - VALUE *) -{ - return container.unbind (*key); -} - -//////////////////////////////////////////////////////////////////////////// - -template int -ACE_Recyclable_Handler_Cleanup_Strategy::cleanup ( - CONTAINER &container, - KEY *key, - VALUE *) -{ - VALUE value; - - if (container.unbind (*key, value) == -1) - return -1; - - value.first ()->recycler (0, 0); - - value.first ()->close (); - - return 0; -} - -///////////////////////////////////////////////////////////////////////////// - -template int -ACE_Refcounted_Recyclable_Handler_Cleanup_Strategy::cleanup ( - CONTAINER &, - KEY *, - VALUE *value) -{ - return value->first ()->handle_close_i (); -} - -//////////////////////////////////////////////////////////////////////////// - -template int -ACE_Handler_Cleanup_Strategy::cleanup ( - CONTAINER &container, - KEY *key, - VALUE *value) -{ - // Remove the item from cache only if the handler isnt in use. - if ((*value)->active () == 0) - { - (*value)->close (); - - if (container.unbind (*key) == -1) - return -1; - - } - - return 0; -} - -//////////////////////////////////////////////////////////////////////////// - -template int -ACE_Null_Cleanup_Strategy::cleanup (CONTAINER &, - KEY *, - VALUE *) -{ - return 0; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_CLEANUP_STRATEGIES_T_CPP */ diff --git a/externals/ace/Cleanup_Strategies_T.h b/externals/ace/Cleanup_Strategies_T.h deleted file mode 100644 index ca51b47b10f..00000000000 --- a/externals/ace/Cleanup_Strategies_T.h +++ /dev/null @@ -1,149 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Cleanup_Strategies_T.h - * - * $Id: Cleanup_Strategies_T.h 81388 2008-04-23 14:02:05Z johnnyw $ - * - * @author Kirthika Parameswaran - */ -//============================================================================= - - -#ifndef CLEANUP_STRATEGIES_H -#define CLEANUP_STRATEGIES_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -// For linkers that cant grok long names. -#define ACE_Cleanup_Strategy ACLE - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Cleanup_Strategy - * - * @brief Defines a default strategy to be followed for cleaning up - * entries from a map which is the container. - * - * By default the entry to be cleaned up is removed from the - * container. - */ -template -class ACE_Cleanup_Strategy -{ - -public: - - /// Destructor. - virtual ~ACE_Cleanup_Strategy (void); - - /// The method which will do the cleanup of the entry in the container. - virtual int cleanup (CONTAINER &container, KEY *key, VALUE *value); -}; - -////////////////////////////////////////////////////////////////////// -#define ACE_Recyclable_Handler_Cleanup_Strategy ARHCLE - -/** - * @class ACE_Recyclable_Handler_Cleanup_Strategy - * - * @brief Defines a strategy to be followed for cleaning up - * entries which are svc_handlers from a container. - * - * The entry to be cleaned up is removed from the container. - * Here, since we are dealing with svc_handlers specifically, we - * perform a couple of extra operations. @note To be used when - * the handler is recyclable. - */ -template -class ACE_Recyclable_Handler_Cleanup_Strategy : public ACE_Cleanup_Strategy -{ - -public: - - /// The method which will do the cleanup of the entry in the container. - virtual int cleanup (CONTAINER &container, KEY *key, VALUE *value); -}; - -////////////////////////////////////////////////////////////////////// -#define ACE_Refcounted_Recyclable_Handler_Cleanup_Strategy ARRHCLE - -/** - * @class ACE_Refcounted_Recyclable_Handler_Cleanup_Strategy - * - * @brief Defines a strategy to be followed for cleaning up - * entries which are svc_handlers from a container. - * - * The entry to be cleaned up is removed from the container. - * Here, since we are dealing with recyclable svc_handlers with - * addresses which are refcountable specifically, we perform a - * couple of extra operations and do so without any locking. - */ -template -class ACE_Refcounted_Recyclable_Handler_Cleanup_Strategy : public ACE_Cleanup_Strategy -{ -public: - /// The method which will do the cleanup of the entry in the container. - virtual int cleanup (CONTAINER &container, KEY *key, VALUE *value); -}; - -////////////////////////////////////////////////////////////////////// - -/** - * @class ACE_Handler_Cleanup_Strategy - * - * @brief Defines a strategy to be followed for cleaning up - * entries which are svc_handlers from a container. - * - * The entry to be cleaned up is removed from the container. - * Here, since we are dealing with svc_handlers specifically, we - * perform a couple of extra operations. @note This cleanup strategy - * should be used in the case when the handler has the caching - * attributes. - */ -template -class ACE_Handler_Cleanup_Strategy : public ACE_Cleanup_Strategy -{ -public: - /// The method which will do the cleanup of the entry in the container. - virtual int cleanup (CONTAINER &container, KEY *key, VALUE *value); -}; - -////////////////////////////////////////////////////////////////////// -#define ACE_Null_Cleanup_Strategy ANCLE - -/** - * @class ACE_Null_Cleanup_Strategy - * - * @brief Defines a do-nothing implementation of the cleanup strategy. - * - * This class simply does nothing at all! Can be used to nullify - * the effect of the Cleanup Strategy. - */ -template -class ACE_Null_Cleanup_Strategy : public ACE_Cleanup_Strategy -{ -public: - /// The dummy cleanup method. - virtual int cleanup (CONTAINER &container, KEY *key, VALUE *value); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Cleanup_Strategies_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Cleanup_Strategies_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" -#endif /* CLEANUP_STRATEGIES_H */ diff --git a/externals/ace/Codecs.cpp b/externals/ace/Codecs.cpp deleted file mode 100644 index 71491fe1c44..00000000000 --- a/externals/ace/Codecs.cpp +++ /dev/null @@ -1,234 +0,0 @@ -#include "ace/Codecs.h" -#include "ace/Log_Msg.h" -#include "ace/OS_Memory.h" -#include "ace/OS_NS_ctype.h" - -ACE_RCSID (ace, - Codecs, - "$Id: Codecs.cpp 80826 2008-03-04 14:51:23Z wotte $") - -namespace -{ - // Just in case ... -#undef alphabet -#undef pad -#undef max_columns - - // Symbols which form the Base64 alphabet (Defined as per RFC 2045) - ACE_Byte const alphabet[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - - // The padding character used in the encoding - ACE_Byte const pad = '='; - - // Number of columns per line of encoded output (Can have a maximum - // value of 76). - int const max_columns = 72; -} - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -bool ACE_Base64::init_ = false; - -ACE_Byte ACE_Base64::decoder_[256]; - -ACE_Byte ACE_Base64::member_[256]; - -ACE_Byte* -ACE_Base64::encode (const ACE_Byte* input, - const size_t input_len, - size_t* output_len, - bool is_chunked) -{ - if (!ACE_Base64::init_) - ACE_Base64::init(); - - if (!input) - return 0; - - ACE_Byte* result = 0; - - size_t length = ((input_len + 2) / 3) * 4; - size_t num_lines = length / max_columns + 1; - length += num_lines + 1; - ACE_NEW_RETURN (result, ACE_Byte[length], 0); - - int char_count = 0; - int bits = 0; - size_t pos = 0; - int cols = 0; - - for (size_t i = 0; i < input_len; ++i) - { - bits += input[i]; - ++char_count; - - if (char_count == 3) - { - result[pos++] = alphabet[bits >> 18]; - result[pos++] = alphabet[(bits >> 12) & 0x3f]; - result[pos++] = alphabet[(bits >> 6) & 0x3f]; - result[pos++] = alphabet[bits & 0x3f]; - cols += 4; - if (cols == max_columns) { - if (is_chunked) - result[pos++] = '\n'; - cols = 0; - } - bits = 0; - char_count = 0; - } - else - { - bits <<= 8; - } - } - - if (char_count != 0) - { - bits <<= (16 - (8 * char_count)); - result[pos++] = alphabet[bits >> 18]; - result[pos++] = alphabet[(bits >> 12) & 0x3f]; - cols += 2; - if (char_count == 1) - { - result[pos++] = pad; - result[pos++] = pad; - cols += 2; - } - else - { - result[pos++] = alphabet[(bits >> 6) & 0x3f]; - result[pos++] = pad; - cols += 2; - } - } - - if (cols > 0 && is_chunked) - result[pos++] = '\n'; - - result[pos] = 0; - *output_len = pos; - return result; -} - -size_t -ACE_Base64::length (const ACE_Byte* input) -{ - if (!ACE_Base64::init_) - ACE_Base64::init(); - - ACE_Byte* ptr = const_cast (input); - while (*ptr != 0 && - (member_[*(ptr)] == 1 || *ptr == pad - || ACE_OS::ace_isspace (*ptr))) - ++ptr; - size_t len = ptr - input; - len = ((len + 3) / 4) * 3 + 1 ; - return len; -} - -ACE_Byte* -ACE_Base64::decode (const ACE_Byte* input, size_t* output_len) -{ - if (!ACE_Base64::init_) - ACE_Base64::init(); - - if (!input) - return 0; - - size_t result_len = ACE_Base64::length (input); - ACE_Byte* result = 0; - ACE_NEW_RETURN (result, ACE_Byte[result_len], 0); - - ACE_Byte* ptr = const_cast (input); - while (*ptr != 0 && - (member_[*(ptr)] == 1 || *ptr == pad - || ACE_OS::ace_isspace (*ptr))) - ++ptr; - size_t input_len = ptr - input; - - int char_count = 0; - int bits = 0; - size_t pos = 0; - - size_t i = 0; - for (; i < input_len; ++i) - { - if (input[i] == pad) - break; - if (!ACE_Base64::member_[input[i]]) - continue; - bits += decoder_[input[i]]; - ++char_count; - - if (char_count == 4) - { - result[pos++] = static_cast (bits >> 16); - result[pos++] = static_cast ((bits >> 8) & 0xff); - result[pos++] = static_cast (bits & 0xff); - bits = 0; - char_count = 0; - } - else - { - bits <<= 6; - } - } - - int errors = 0; - if ( i == input_len) - { - if (char_count) - { - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("Decoding incomplete: atleast %d bits truncated\n"), - (4 - char_count) * 6)); - ++errors; - } - } - else - { - switch (char_count) - { - case 1: - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("Decoding incomplete: atleast 2 bits missing\n"))); - ++errors; - break; - case 2: - result[pos++] = static_cast (bits >> 10); - break; - case 3: - result[pos++] = static_cast (bits >> 16); - result[pos++] = static_cast ((bits >> 8) & 0xff); - break; - } - } - - if (errors) - { - delete[] result; - return 0; - } - result[pos] = 0; - *output_len = pos; - return result; -} - -void -ACE_Base64::init () -{ - if (!ACE_Base64::init_) - { - for (ACE_Byte i = 0; i < sizeof (alphabet); ++i) - { - ACE_Base64::decoder_[alphabet[i]] = i; - ACE_Base64::member_ [alphabet[i]] = 1; - } - ACE_Base64::init_ = true; - } - return; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Codecs.h b/externals/ace/Codecs.h deleted file mode 100644 index 2c4227dd0ad..00000000000 --- a/externals/ace/Codecs.h +++ /dev/null @@ -1,121 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Codecs.h - * - * $Id: Codecs.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Krishnakumar B - * - * Codecs is a generic wrapper for various encoding and decoding - * mechanisms. Currently it includes Base64 content transfer-encoding as - * specified by RFC 2045, Multipurpose Internet Mail Extensions (MIME) Part - * One: Format of Internet Message Bodies. - * - */ -//============================================================================= - -#ifndef ACE_CODECS_H -#define ACE_CODECS_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Basic_Types.h" -#include "ace/Global_Macros.h" - - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Base64 - * - * @brief Encode/Decode a stream of bytes according to Base64 encoding. - * - * This class provides methods to encode or decode a stream of bytes - * to/from Base64 encoding. It doesn't convert the input stream to a - * canonical form before encoding. - * - */ -class ACE_Export ACE_Base64 -{ -public: - - //@{ - - /** - * Encodes a stream of bytes to Base64 data - * - * @param input Binary data in byte stream. - * @param input_len Length of the byte stream. - * @param output_len Length of the encoded Base64 byte stream. - * @param is_chunked If true, terminate 72 character blocks with newline - * @return Encoded Base64 data in byte stream or NULL if input data cannot - * be encoded. - */ - - static ACE_Byte* encode (const ACE_Byte* input, - const size_t input_len, - size_t* output_len, - bool is_chunked = true); - /** - * Decodes a stream of Base64 to bytes data - * - * @param input Encoded Base64 data in byte stream. - * @param output_len Length of the binary byte stream. - * @return Binary data in byte stream or NULL if input data cannot - * be encoded. - */ - static ACE_Byte* decode (const ACE_Byte* input, - size_t* output_len); - - /** - * Return the length of the encoded input data - * - * @param input Encoded Base64 data in byte stream. - * @return Length of the encoded Base64 data. - * - */ - static size_t length (const ACE_Byte* input); - - //@} - -protected: - - // Prevent default construction. - ACE_Base64 (void) {} - -private: - - // Preventing copying and assignment. - ACE_Base64 (ACE_Base64 const &); - ACE_Base64 & operator= (ACE_Base64 const &); - - /// Initialize the tables for encoding/decoding. - static void init (void); - -private: - - /// Alphabet used for decoding i.e decoder_[alphabet_[i = 0..63]] = i - static ACE_Byte decoder_[]; - - /// Alphabet used to check valid range of encoded input i.e - /// member_[alphabet_[0..63]] = 1 - static ACE_Byte member_[]; - - /// Boolean to denote whether initialization is complete - static bool init_; - -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" - -#endif /* ACE_CODECS_H */ diff --git a/externals/ace/Codeset_IBM1047.cpp b/externals/ace/Codeset_IBM1047.cpp deleted file mode 100644 index 91582cf4ef3..00000000000 --- a/externals/ace/Codeset_IBM1047.cpp +++ /dev/null @@ -1,309 +0,0 @@ - -//============================================================================= -/** - * @file Codeset_IBM1047.cpp - * - * $Id: Codeset_IBM1047.cpp 81661 2008-05-09 12:05:34Z johnnyw $ - * - * Defines the arrays required to convert between ISO8859 (aka - * Latin/1) and IBM1047 (aka EBCDIC). - * - * - * @author Jim Rogers (jrogers@viasoft.com) - */ -//============================================================================= - - -#include "ace/Codeset_IBM1047.h" - -#if defined (ACE_HAS_EBCDIC) - -ACE_RCSID (ace, - Codeset_IBM1047, - "$Id: Codeset_IBM1047.cpp 81661 2008-05-09 12:05:34Z johnnyw $") - -#include "ace/OS_Memory.h" -#include "ace/OS_NS_string.h" - -namespace -{ - char const to_IBM1047[] = - { - "\x00\x01\x02\x03\x37\x2D\x2E\x2F\x16\x05\x25\x0B\x0C\x0D\x0E\x0F" // 00-0F - "\x10\x11\x12\x13\x3C\x3D\x32\x26\x18\x19\x3F\x27\x22\x1D\x35\x1F" // 10-1F - "\x40\x5A\x7F\x7B\x5B\x6C\x50\x7D\x4D\x5D\x5C\x4E\x6B\x60\x4B\x61" // 20-2F - "\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\x7A\x5E\x4C\x7E\x6E\x6F" // 30-3F - "\x7C\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xD1\xD2\xD3\xD4\xD5\xD6" // 40-4F - "\xD7\xD8\xD9\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xAD\xE0\xBD\x5F\x6D" // 50-5F - "\x79\x81\x82\x83\x84\x85\x86\x87\x88\x89\x91\x92\x93\x94\x95\x96" // 60-6F - "\x97\x98\x99\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xC0\x4F\xD0\xA1\x07" // 70-7F - "\x43\x20\x21\x1C\x23\xEB\x24\x9B\x71\x28\x38\x49\x90\xBA\xEC\xDF" // 80-8F - "\x45\x29\x2A\x9D\x72\x2B\x8A\x9A\x67\x56\x64\x4A\x53\x68\x59\x46" // 90-9F - "\xEA\xDA\x2C\xDE\x8B\x55\x41\xFE\x58\x51\x52\x48\x69\xDB\x8E\x8D" // A0-AF - "\x73\x74\x75\xFA\x15\xB0\xB1\xB3\xB4\xB5\x6A\xB7\xB8\xB9\xCC\xBC" // B0-BF - "\xAB\x3E\x3B\x0A\xBF\x8F\x3A\x14\xA0\x17\xCB\xCA\x1A\x1B\x9C\x04" // C0-CF - "\x34\xEF\x1E\x06\x08\x09\x77\x70\xBE\xBB\xAC\x54\x63\x65\x66\x62" // D0-DF - "\x30\x42\x47\x57\xEE\x33\xB6\xE1\xCD\xED\x36\x44\xCE\xCF\x31\xAA" // E0-EF - "\xFC\x9E\xAE\x8C\xDD\xDC\x39\xFB\x80\xAF\xFD\x78\x76\xB2\x9F\xFF" // F0-FF -}; - - char const from_IBM1047[] = - { - "\x00\x01\x02\x03\xCF\x09\xD3\x7F\xD4\xD5\xC3\x0B\x0C\x0D\x0E\x0F" // 00-0F - "\x10\x11\x12\x13\xC7\xB4\x08\xC9\x18\x19\xCC\xCD\x83\x1D\xD2\x1F" // 10-1F - "\x81\x82\x1C\x84\x86\x0A\x17\x1B\x89\x91\x92\x95\xA2\x05\x06\x07" // 20-2F - "\x20\xEE\x16\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\xC1\x1A" // 30-3F - "\x20\xA6\xE1\x80\xEB\x90\x9F\xE2\xAB\x8B\x9B\x2E\x3C\x28\x2B\x7C" // 40-4F - "\x26\xA9\xAA\x9C\xDB\xA5\x99\xE3\xA8\x9E\x21\x24\x2A\x29\x3B\x5E" // 50-5F - "\x2D\x2F\xDF\xDC\x9A\xDD\xDE\x98\x9D\xAC\xBA\x2C\x25\x5F\x3E\x3F" // 60-6F - "\xD7\x88\x94\xB0\xB1\xB2\xFC\xD6\xFB\x60\x3A\x23\x40\x27\x3D\x22" // 70-7F - "\xF8\x61\x62\x63\x64\x65\x66\x67\x68\x69\x96\xA4\xF3\xAF\xAE\xC5" // 80-8F - "\x8C\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x97\x87\xCE\x93\xF1\xFE" // 90-9F - "\xC8\x7E\x73\x74\x75\x76\x77\x78\x79\x7A\xEF\xC0\xDA\x5B\xF2\xF9" // A0-AF - "\xB5\xB6\xFD\xB7\xB8\xB9\xE6\xBB\xBC\xBD\x8D\xD9\xBF\x5D\xD8\xC4" // B0-BF - "\x7B\x41\x42\x43\x44\x45\x46\x47\x48\x49\xCB\xCA\xBE\xE8\xEC\xED" // C0-CF - "\x7D\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\xA1\xAD\xF5\xF4\xA3\x8F" // D0-DF - "\x5C\xE7\x53\x54\x55\x56\x57\x58\x59\x5A\xA0\x85\x8E\xE9\xE4\xD1" // E0-EF - "\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\xB3\xF7\xF0\xFA\xA7\xFF" // F0-FF - }; -} - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_IBM1047_ISO8859::ACE_IBM1047_ISO8859 (void) -{ -} - -ACE_IBM1047_ISO8859::~ACE_IBM1047_ISO8859 (void) -{ -} - -ACE_CDR::ULong -ACE_IBM1047_ISO8859::ncs () -{ - return 0x10020417; -} - -ACE_CDR::ULong -ACE_IBM1047_ISO8859::tcs () -{ - return 0x00010001; -} - -ACE_CDR::Boolean -ACE_IBM1047_ISO8859::read_char (ACE_InputCDR &in, - ACE_CDR::Char &x) -{ - if (this->read_1 (in, reinterpret_cast (&x))) - { - x = to_IBM1047[x]; - return 1; - } - return 0; -} - -ACE_CDR::Boolean -ACE_IBM1047_ISO8859::read_string (ACE_InputCDR& in, - ACE_CDR::Char *& x) -{ - ACE_CDR::ULong len; - - in.read_ulong (len); - - if (len > 0) - { - ACE_NEW_RETURN (x, - ACE_CDR::Char[len], - 0); - - if (this->read_char_array (in, x, len)) - return 1; - - delete [] x; - } - - x = 0; - return 0; -} - -ACE_CDR::Boolean -ACE_IBM1047_ISO8859::read_char_array (ACE_InputCDR& in, - ACE_CDR::Char* x, - ACE_CDR::ULong len) -{ - if (this->read_array (in, - x, - ACE_CDR::OCTET_SIZE, - ACE_CDR::OCTET_ALIGN, - len)) - { - for (ACE_CDR::ULong i = 0; i != len; ++i) - x[i] = to_IBM1047[x[i]]; - - return 1; - } - - return 0; -} - -ACE_CDR::Boolean -ACE_IBM1047_ISO8859::write_char (ACE_OutputCDR& out, - ACE_CDR::Char x) -{ - return - this->write_1 (out, - reinterpret_cast (&from_IBM1047[x])); -} - -ACE_CDR::Boolean -ACE_IBM1047_ISO8859::write_string (ACE_OutputCDR& out, - ACE_CDR::ULong len, - const ACE_CDR::Char* x) -{ - if (out.write_ulong (len + 1)) - return this->write_char_array (out, x, len + 1); - return 0; -} - -ACE_CDR::Boolean -ACE_IBM1047_ISO8859::write_char_array (ACE_OutputCDR& out, - const ACE_CDR::Char* x, - ACE_CDR::ULong len) -{ - char *buf = 0; - if (this->adjust (out, len, 1, buf) == 0) - { - ACE_OS::memcpy (buf, x, len); - - for (ACE_CDR::ULong i = 0; i != len; ++i) - buf[i] = from_IBM1047[buf[i]]; - - return 1; - } - - this->good_bit(out, 0); - return 0; -} - -// **************************************************************** - -ACE_ISO8859_IBM1047::ACE_ISO8859_IBM1047 (void) -{ -} - -ACE_ISO8859_IBM1047::~ACE_ISO8859_IBM1047 (void) -{ -} - -ACE_CDR::ULong -ACE_ISO8859_IBM1047::ncs () -{ - return 0x00010001; -} - -ACE_CDR::ULong -ACE_ISO8859_IBM1047::tcs () -{ - return 0x10020417; -} - -ACE_CDR::Boolean -ACE_ISO8859_IBM1047::read_char (ACE_InputCDR& in, - ACE_CDR::Char& x) -{ - if (this->read_1 (in, reinterpret_cast (&x))) - { - x = from_IBM1047[x]; - return 1; - } - return 0; -} - -ACE_CDR::Boolean -ACE_ISO8859_IBM1047::read_string (ACE_InputCDR &in, - ACE_CDR::Char *&x) -{ - ACE_CDR::ULong len; - - in.read_ulong (len); - - if (len > 0) - { - ACE_NEW_RETURN (x, - ACE_CDR::Char[len], - 0); - - if (this->read_char_array (in, x, len)) - return 1; - - delete [] x; - } - - x = 0; - return 0; -} - -ACE_CDR::Boolean -ACE_ISO8859_IBM1047::read_char_array (ACE_InputCDR &in, - ACE_CDR::Char *x, - ACE_CDR::ULong len) -{ - if (this->read_array (in, - x, - ACE_CDR::OCTET_SIZE, - ACE_CDR::OCTET_ALIGN, - len)) - { - for (ACE_CDR::ULong i = 0; i != len; ++i) - x[i] = from_IBM1047[x[i]]; - - return 1; - } - - return 0; -} - -ACE_CDR::Boolean -ACE_ISO8859_IBM1047::write_char (ACE_OutputCDR &out, - ACE_CDR::Char x) -{ - return - this->write_1 (out, - reinterpret_cast (&to_IBM1047[x])); -} - -ACE_CDR::Boolean -ACE_ISO8859_IBM1047::write_string (ACE_OutputCDR& out, - ACE_CDR::ULong len, - const ACE_CDR::Char* x) -{ - if (out.write_ulong (len + 1)) - return this->write_char_array (out, x, len + 1); - else - return 0; -} - -ACE_CDR::Boolean -ACE_ISO8859_IBM1047::write_char_array (ACE_OutputCDR &out, - const ACE_CDR::Char *x, - ACE_CDR::ULong len) -{ - char *buf = 0; - - if (this->adjust (out, len, 1, buf) == 0) - { - ACE_OS::memcpy (buf, x, len); - - for (ACE_CDR::ULong i = 0; i != len; ++i) - buf[i] = to_IBM1047[buf[i]]; - - return 1; - } - - this->good_bit (out, 0); - return 0; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_EBCDIC */ diff --git a/externals/ace/Codeset_IBM1047.h b/externals/ace/Codeset_IBM1047.h deleted file mode 100644 index 3caa8881fbf..00000000000 --- a/externals/ace/Codeset_IBM1047.h +++ /dev/null @@ -1,127 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Codeset_IBM1047.h - * - * $Id: Codeset_IBM1047.h 81388 2008-04-23 14:02:05Z johnnyw $ - * - * Declares the arrays required to convert between ISO8859 (aka - * Latin/1) and IBM1047 (aka EBCDIC). - * - * @author Jim Rogers (jrogers@viasoft.com) - */ -//============================================================================= - - -#ifndef ACE_CODESET_IMB1047_H -#define ACE_CODESET_IMB1047_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_EBCDIC) - -#include "ace/CDR_Stream.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// **************************************************************** - -/** - * @class ACE_IBM1047_ISO8859 - * - * @brief Codeset translation specialization. - * - * This class performs the codeset translation: - * - Native: IBM_1047 (i.e. EBCDIC) - * - Stream: ISO-8859 (i.e. Latin/1) - */ -class ACE_Export ACE_IBM1047_ISO8859 : public ACE_Char_Codeset_Translator -{ -public: - /// A do nothing constructor. - ACE_IBM1047_ISO8859 (void); - - /// Virtual destruction - virtual ~ACE_IBM1047_ISO8859 (void); - - // = Documented in $ACE_ROOT/ace/CDR_Stream.h - virtual ACE_CDR::Boolean read_char (ACE_InputCDR &, - ACE_CDR::Char &); - virtual ACE_CDR::Boolean read_string (ACE_InputCDR &, - ACE_CDR::Char *&); - virtual ACE_CDR::Boolean read_char_array (ACE_InputCDR &, - ACE_CDR::Char *, - ACE_CDR::ULong); - virtual ACE_CDR::Boolean write_char (ACE_OutputCDR &, - ACE_CDR::Char); - virtual ACE_CDR::Boolean write_string (ACE_OutputCDR &, - ACE_CDR::ULong, - const ACE_CDR::Char *); - virtual ACE_CDR::Boolean write_char_array (ACE_OutputCDR &, - const ACE_CDR::Char *, - ACE_CDR::ULong); - - /// Return the native codeset ID as defined in the OSF code and character - /// set registry, 0x10020417 - virtual ACE_CDR::ULong ncs (); - /// Return the translated codeset ID as defined in the OSF code and character - /// set registry, 0x00010001 - virtual ACE_CDR::ULong tcs (); -}; - -/** - * @class ACE_ISO8859_IBM1047 - * - * @brief Codeset translation specialization. - * - * This class performs the codeset translation: - * - Native: ISO-8859 (i.e. Latin/1) - * - Stream: IBM-1047 (i.e. EBCDIC) - */ -class ACE_Export ACE_ISO8859_IBM1047 : public ACE_Char_Codeset_Translator -{ -public: - /// A do nothing constructor. - ACE_ISO8859_IBM1047 (void); - - /// Virtual destruction - virtual ~ACE_ISO8859_IBM1047 (void); - - // = Documented in $ACE_ROOT/ace/CDR_Stream.h - virtual ACE_CDR::Boolean read_char (ACE_InputCDR &, - ACE_CDR::Char &); - virtual ACE_CDR::Boolean read_string (ACE_InputCDR &, - ACE_CDR::Char *&); - virtual ACE_CDR::Boolean read_char_array (ACE_InputCDR &, - ACE_CDR::Char *, - ACE_CDR::ULong); - virtual ACE_CDR::Boolean write_char (ACE_OutputCDR &, - ACE_CDR::Char); - virtual ACE_CDR::Boolean write_string (ACE_OutputCDR &, - ACE_CDR::ULong, - const ACE_CDR::Char *); - virtual ACE_CDR::Boolean write_char_array (ACE_OutputCDR &, - const ACE_CDR::Char *, - ACE_CDR::ULong); - - /// Return the native codeset ID as defined in the OSF code and character - /// set registry, 0x00010001 - virtual ACE_CDR::ULong ncs (); - /// Return the translated codeset ID as defined in the OSF code and character - /// set registry, 0x10020417 - virtual ACE_CDR::ULong tcs (); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_EBCDIC */ - -#include /**/ "ace/post.h" - -#endif /* ACE_CODESET_IMB1047_H */ diff --git a/externals/ace/Codeset_Registry.cpp b/externals/ace/Codeset_Registry.cpp deleted file mode 100644 index c23ef37231a..00000000000 --- a/externals/ace/Codeset_Registry.cpp +++ /dev/null @@ -1,111 +0,0 @@ -//============================================================================= -/** - * @file Codeset_Registry.cpp - * - * $Id: Codeset_Registry.cpp 80826 2008-03-04 14:51:23Z wotte $ - * - * emulated codset regstry functions - * - * - * @author Phil Mesnier - */ -//============================================================================= - -#include "ace/Codeset_Registry.h" -#include "ace/OS_Memory.h" -#include "ace/OS_NS_string.h" - -// $Id: Codeset_Registry.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#if !defined (__ACE_INLINE__) -#include "ace/Codeset_Registry.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID (ace, - Codeset_Registry, - "$Id: Codeset_Registry.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -int -ACE_Codeset_Registry::locale_to_registry_i (const ACE_CString &locale, - ACE_CDR::ULong &codeset_id, - ACE_CDR::UShort *num_sets, - ACE_CDR::UShort **char_sets) -{ - registry_entry const *element = 0; - for (size_t i = 0; element == 0 && i < num_registry_entries_; i++) - if (ACE_OS::strcmp (registry_db_[i].loc_name_, locale.c_str ()) == 0) - element = ®istry_db_[i]; - if (element == 0) - return 0; - codeset_id = element->codeset_id_; - if (num_sets != 0) - *num_sets = element->num_sets_; - if (char_sets != 0) - { - ACE_NEW_RETURN (*char_sets,ACE_CDR::UShort[element->num_sets_],0); - ACE_OS::memcpy (*char_sets, element->char_sets_, - element->num_sets_ * sizeof (ACE_CDR::UShort)); - } - return 1; -} - -int -ACE_Codeset_Registry::registry_to_locale_i (ACE_CDR::ULong codeset_id, - ACE_CString &locale, - ACE_CDR::UShort *num_sets, - ACE_CDR::UShort **char_sets) -{ - registry_entry const *element = 0; - for (size_t i = 0; element == 0 && i < num_registry_entries_; i++) - if (codeset_id == registry_db_[i].codeset_id_) - element = ®istry_db_[i]; - if (element == 0) - return 0; - locale.set (element->loc_name_); - if (num_sets != 0) - *num_sets = element->num_sets_; - if (char_sets != 0) - { - ACE_NEW_RETURN (*char_sets,ACE_CDR::UShort[element->num_sets_],0); - ACE_OS::memcpy (*char_sets, element->char_sets_, - element->num_sets_ * sizeof (ACE_CDR::UShort)); - } - return 1; -} - -int -ACE_Codeset_Registry::is_compatible_i (ACE_CDR::ULong codeset_id, - ACE_CDR::ULong other) -{ - registry_entry const *lhs = 0; - registry_entry const *rhs = 0; - for (size_t i = 0; (lhs == 0 || rhs == 0) && i < num_registry_entries_; i++) - { - if (codeset_id == registry_db_[i].codeset_id_) - lhs = ®istry_db_[i]; - if (other == registry_db_[i].codeset_id_) - rhs = ®istry_db_[i]; - } - - if (lhs == 0 || rhs == 0) - return 0; - - for (ACE_CDR::UShort l = 0; l < lhs->num_sets_; l++) - for (ACE_CDR::UShort r = 0; r < rhs->num_sets_; r++) - if (rhs->char_sets_[r] == lhs->char_sets_[l]) - return 1; - return 0; -} - -ACE_CDR::Short -ACE_Codeset_Registry::get_max_bytes_i (ACE_CDR::ULong codeset_id) -{ - for (size_t i = 0; i < num_registry_entries_; i++) - if (codeset_id == registry_db_[i].codeset_id_) - return registry_db_[i].max_bytes_; - return 0; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Codeset_Registry.h b/externals/ace/Codeset_Registry.h deleted file mode 100644 index e72c435f82b..00000000000 --- a/externals/ace/Codeset_Registry.h +++ /dev/null @@ -1,104 +0,0 @@ -// -*- C++ -*- -//============================================================================= -/** - * @file Codeset_Registry.h - * - * $Id: Codeset_Registry.h 81348 2008-04-14 09:00:32Z johnnyw $ - * - * ACE wrapper around access functions for the OSF's DCE codeset registry - * access functions - * - * For environments that intrinsicly support the DCE defined access functions, - * the methods in this class are simply wrappers. On other platforms, emulation - * is provided. The motivation for this class is to support interoperability - * via translators and the CDR streams, primarily in TAO, but this capability - * is not restricted to CORBA. - * - * The emulated functionality supports Open Group RFC #40, currently RFC 40.2, - * www.opengroup.org/tech/rfc/rfc40.2.html - * - * @author Phil Mesnier - */ -//============================================================================= - -#ifndef ACE_CODESET_REGISTRY_H -#define ACE_CODESET_REGISTRY_H - -#include /**/ "ace/pre.h" -#include "ace/SString.h" -#include "ace/CDR_Base.h" -#include "ace/Codeset_Symbols.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_DCE_CODESET_REGISTRY) -#include /**/ -#endif /* ACE_HAS_DCE_CODESET_REGISTRY */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -class ACE_Export ACE_Codeset_Registry -{ -public: - - /// Based on a locale string, find the registry value and optional codeset - /// collection. This wraps the dce_cs_loc_to_rgy function, or emulates it. - static int locale_to_registry (const ACE_CString &locale, - ACE_CDR::ULong &codeset_id, - ACE_CDR::UShort * = 0, - ACE_CDR::UShort ** = 0); - - /// Based on a registry value, find the locale string and optional codeset - /// collection. This wraps the dce_cs_rgy_to_loc function, or emulates it. - static int registry_to_locale (ACE_CDR::ULong codeset_id, - ACE_CString &locale, - ACE_CDR::UShort * = 0, - ACE_CDR::UShort ** = 0); - - /// Tell if two codesets are compatible. This wraps the - /// rpc_cs_char_set_compat_check function. - static int is_compatible (ACE_CDR::ULong codeset_id, - ACE_CDR::ULong other); - - /// Return the max number of bytes required to represent a single character. - /// This wraps the rpc_rgy_get_max_bytes function. - static ACE_CDR::Short get_max_bytes (ACE_CDR::ULong codeset_id); - - enum {max_charsets_ = 5}; -protected: - typedef struct { - const char * desc_; - const char * loc_name_; - ACE_CDR::ULong codeset_id_; - ACE_CDR::UShort num_sets_; - ACE_CDR::UShort char_sets_[max_charsets_]; - ACE_CDR::UShort max_bytes_; - } registry_entry; - -private: - static size_t const num_registry_entries_; - static registry_entry const registry_db_[]; - - static int locale_to_registry_i (const ACE_CString &locale, - ACE_CDR::ULong &codeset_id, - ACE_CDR::UShort * = 0, - ACE_CDR::UShort ** = 0); - static int registry_to_locale_i (ACE_CDR::ULong codeset_id, - ACE_CString &locale, - ACE_CDR::UShort * = 0, - ACE_CDR::UShort ** = 0); - static int is_compatible_i (ACE_CDR::ULong codeset_id, - ACE_CDR::ULong other); - static ACE_CDR::Short get_max_bytes_i (ACE_CDR::ULong codeset_id); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Codeset_Registry.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_CODESET_REGISTRY_H */ diff --git a/externals/ace/Codeset_Registry.inl b/externals/ace/Codeset_Registry.inl deleted file mode 100644 index 4419cf5e7fc..00000000000 --- a/externals/ace/Codeset_Registry.inl +++ /dev/null @@ -1,102 +0,0 @@ -// -*- C++ -*- -//============================================================================= -/** - * @file Codeset_Registry.inl - * - * $Id: Codeset_Registry.inl 80826 2008-03-04 14:51:23Z wotte $ - * - * ACE wrapper around access functions for the OSF's DCE codeset registry - * access functions - the inline functions either call the system supplied - * DCE based codeset regsitry function, or calls the emulation - * - * - * @author Phil Mesnier - */ -//============================================================================= - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE -int -ACE_Codeset_Registry::locale_to_registry(const ACE_CString &locale, - ACE_CDR::ULong &codeset_id, - ACE_CDR::UShort *num_sets, - ACE_CDR::UShort **char_sets) -{ -#if defined (ACE_HAS_DCE_CODESET_REGISTRY) - error_status_t result; - dce_cs_loc_to_rgy (locale.c_str(), - &codeset_id, - num_sets, - char_sets, - &result); - return (result == dce_cs_c_ok) ? 1 : 0; -#else - return ACE_Codeset_Registry::locale_to_registry_i (locale, - codeset_id, - num_sets, - char_sets); -#endif /* ACE_HAS_DCE_CODESET_REGISTRY */ -} - -// based on a registry value, find the locale string and optional codeset -// collection. This wraps the dce_cs_rgy_to_loc function, or emulates it. -ACE_INLINE -int -ACE_Codeset_Registry::registry_to_locale(ACE_CDR::ULong codeset_id, - ACE_CString &locale, - ACE_CDR::UShort *num_sets, - ACE_CDR::UShort **char_sets) -{ -#if defined (ACE_HAS_DCE_CODESET_REGISTRY) - error_status_t result; - char *buffer; - dce_cs_rgy_to_loc (codeset_id, - &buffer, - num_sets, - char_sets, - &result); - locale.set(buffer); // does a copy :-( - free (buffer); - return (result == dce_cs_c_ok) ? 1 : 0; -#else - return ACE_Codeset_Registry::registry_to_locale_i (codeset_id, - locale, - num_sets, - char_sets); -#endif /* ACE_HAS_DCE_CODESET_REGISTRY */ -} - -// Tell if two codesets are compatible. This wraps the -// rpc_cs_char_set_compat_check function. -ACE_INLINE -int -ACE_Codeset_Registry::is_compatible (ACE_CDR::ULong codeset_id, - ACE_CDR::ULong other) -{ -#if defined (ACE_HAS_DCE_CODESET_REGISTRY) - error_status_t result; - rpc_cs_char_set_compat_check(codeset_id,other,&result); - return (result == rpc_s_ok) ? 1 : 0; -#else - return ACE_Codeset_Registry::is_compatible_i (codeset_id,other); -#endif /* ACE_HAS_DCE_CODESET_REGISTRY */ -} - -// Return the max number of bytes required to represent a single character. -// This wraps the rpc_rgy_get_max_bytes function. -ACE_INLINE -ACE_CDR::Short -ACE_Codeset_Registry::get_max_bytes (ACE_CDR::ULong codeset_id) -{ -#if defined (ACE_HAS_DCE_CODESET_REGISTRY) - error_status_t result; - short max_bytes; - rpc_rgy_get_max_bytes(codeset_id,&max_bytes,&result); - return (result == rpc_s_ok) ? (short)max_bytes : 0; -#else - return ACE_Codeset_Registry::get_max_bytes_i (codeset_id); -#endif /* ACE_HAS_DCE_CODESET_REGISTRY */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Codeset_Registry_db.cpp b/externals/ace/Codeset_Registry_db.cpp deleted file mode 100644 index 32b38631c6f..00000000000 --- a/externals/ace/Codeset_Registry_db.cpp +++ /dev/null @@ -1,33 +0,0 @@ -/* $Id: Codeset_Registry_db.cpp 81756 2008-05-22 09:47:33Z johnnyw $ - * Codeset registry DB, generated Fri Feb 28 21:01:30 2003 - * source: code_set_registry1.2g.txt - * - * To populate the registry_db, construct a codeset registry text file based - * on the OSF's Character and Code Set Registry. See DCE RFC 40.1 for details - * on obtaining the full text for the current registry. Once you have composed - * a text file containing all the desired codeset information, build and run - * mkcsregdb. The source is in $ACE_ROOT/apps/mkcsregdb. It will generate a new - * copy of this file, with the registry_db_ array properly initialized. - */ - -#include "ace/Codeset_Registry.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_Codeset_Registry::registry_entry const -ACE_Codeset_Registry::registry_db_[] = -{ - {"ISO/IEC 10646-1:1993; UCS-2, Level 1","UCS-2",0x00010100,1,{0x1000},2}, - {"ISO 8859-1:1987; Latin Alphabet No. 1","ISO8859_1",0x00010001,1,{0x0011},1}, - {"IBM-1047 (CCSID 01047); Latin-1 Open System","EBCDIC",0x10020417,1,{0x0011},1}, - {"ISO/IEC 10646-1:1993; UCS-4, Level 1","UCS-4",0x00010104,1,{0x1000},4}, - {"ISO/IEC 10646-1:1993; UTF-16, UCS Transformation Format 16-bit form","UTF-16",0x00010109,1,{0x1000},2}, - {"X/Open UTF-8; UCS Transformation Format 8 (UTF-8)","UTF-8",0x05010001,1,{0x1000},6}, - {"ISO/IEC 8859-5:1988; Latin-Cyrillic Alphabet","ISO-8859-5",0x00010005,1,{0x0015},1}, - {"IBM-1251 (CCSID 01251); MS Windows Cyrillic","CP1251",0x100204e3,1,{0x0015},1}, - {"IBM-855 (CCSID 04951); Cyrillic Personal Computer","CP855",0x10021357,1,{0x0015},1} -}; - -size_t const ACE_Codeset_Registry::num_registry_entries_ = 9; - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Codeset_Symbols.h b/externals/ace/Codeset_Symbols.h deleted file mode 100644 index 6ffe198c1a9..00000000000 --- a/externals/ace/Codeset_Symbols.h +++ /dev/null @@ -1,220 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Codeset_Symbols.h - * - * $Id: Codeset_Symbols.h 80826 2008-03-04 14:51:23Z wotte $ - * - * Symbolic names for codeset ids. - * - * @author Dale Wilson (wilson_d@ociweb.com) - */ -//============================================================================= -#ifndef CODESET_SYMBOLS_H -#define CODESET_SYMBOLS_H - -// These numbers are assigned by the OpenGroup, a database is -// available at -// -// ftp://ftp.opengroup.org/pub/code_set_registry/ -// -// Alas, the database is in a semi-regular text file -- difficult to use. -// The following C/C++-friendly version of the codeset ids was captured -// from Version 1.2g of the registry. -// -#define ACE_CODESET_ID_ISO_8859_1 0x00010001U -#define ACE_CODESET_ID_ISO_8859_2 0x00010002U -#define ACE_CODESET_ID_ISO_8859_3 0x00010003U -#define ACE_CODESET_ID_ISO_8859_4 0x00010004U -#define ACE_CODESET_ID_ISO_8859_5 0x00010005U -#define ACE_CODESET_ID_ISO_8859_6 0x00010006U -#define ACE_CODESET_ID_ISO_8859_7 0x00010007U -#define ACE_CODESET_ID_ISO_8859_8 0x00010008U -#define ACE_CODESET_ID_ISO_8859_9 0x00010009U -#define ACE_CODESET_ID_ISO_8859_10 0x0001000AU -#define ACE_CODESET_ID_ISO_8859_15 0x0001000FU -#define ACE_CODESET_ID_ISO_646 0x00010020U -#define ACE_CODESET_ID_ISO_UCS_2_LEVEL_1 0x00010100U -#define ACE_CODESET_ID_ISO_UCS_2_LEVEL_2 0x00010101U -#define ACE_CODESET_ID_ISO_UCS_2_LEVEL_3 0x00010102U -#define ACE_CODESET_ID_ISO_UCS_4_LEVEL_1 0x00010104U -#define ACE_CODESET_ID_ISO_UCS_4_LEVEL_2 0x00010105U -#define ACE_CODESET_ID_ISO_UCS_4_LEVEL_3 0x00010106U -#define ACE_CODESET_ID_ISO_UTF_8 0x00010108U -#define ACE_CODESET_ID_ISO_UTF_16 0x00010109U -#define ACE_CODESET_ID_JIS_X0201 0x00030001U -#define ACE_CODESET_ID_JIS_X0208_1978 0x00030004U -#define ACE_CODESET_ID_JIS_X0208_1983 0x00030005U -#define ACE_CODESET_ID_JIS_X0208_1990 0x00030006U -#define ACE_CODESET_ID_JIS_X0212 0x0003000AU -#define ACE_CODESET_ID_JIS_EUCJP 0x00030010U -#define ACE_CODESET_ID_KS_C5601 0x00040001U -#define ACE_CODESET_ID_KS_C5657 0x00040002U -#define ACE_CODESET_ID_KS_EUCKR 0x0004000AU -#define ACE_CODESET_ID_CNS_11643_1986 0x00050001U -#define ACE_CODESET_ID_CNS_11643_1992 0x00050002U -#define ACE_CODESET_ID_CNS_EUCTW_1991 0x0005000AU -#define ACE_CODESET_ID_CNS_EUCTW_1993 0x00050010U -#define ACE_CODESET_ID_TIS_620_25290X000B0001U -#define ACE_CODESET_ID_TTB_CCDC 0x000D0001U -#define ACE_CODESET_ID_OSF_JAPANESE_UJIS 0x05000010U -#define ACE_CODESET_ID_OSF_JAPANESE_SJIS_1 0x05000011U -#define ACE_CODESET_ID_OSF_JAPANESE_SJIS_2 0x05000012U -#define ACE_CODESET_ID_XOPEN_UTF_8 0x05010001U -#define ACE_CODESET_ID_JVC_EUCJP 0x05020001U -#define ACE_CODESET_ID_JVC_SJIS 0x05020002U -#define ACE_CODESET_ID_DEC_KANJI 0x10000001U -#define ACE_CODESET_ID_SUPER_DEC_KANJI 0x10000002U -#define ACE_CODESET_ID_DEC_SHIFT_JIS 0x10000003U -#define ACE_CODESET_ID_HP_ROMAN8 0x10010001U -#define ACE_CODESET_ID_HP_KANA8 0x10010002U -#define ACE_CODESET_ID_HP_ARABIC8 0x10010003U -#define ACE_CODESET_ID_HP_GREEK8 0x10010004U -#define ACE_CODESET_ID_HP_HEBREW8 0x10010005U -#define ACE_CODESET_ID_HP_TURKISH8 0x10010006U -#define ACE_CODESET_ID_HP15CN 0x10010007U -#define ACE_CODESET_ID_HP_BIG5 0x10010008U -#define ACE_CODESET_ID_HP_JAPANESE15__SJIS_ 0x10010009U -#define ACE_CODESET_ID_HP_SJISHI 0x1001000AU -#define ACE_CODESET_ID_HP_SJISPC 0x1001000BU -#define ACE_CODESET_ID_HP_UJIS 0x1001000CU -#define ACE_CODESET_ID_IBM_037 0x10020025U -#define ACE_CODESET_ID_IBM_273 0x10020111U -#define ACE_CODESET_ID_IBM_277 0x10020115U -#define ACE_CODESET_ID_IBM_278 0x10020116U -#define ACE_CODESET_ID_IBM_280 0x10020118U -#define ACE_CODESET_ID_IBM_282 0x1002011AU -#define ACE_CODESET_ID_IBM_284 0x1002011CU -#define ACE_CODESET_ID_IBM_285 0x1002011DU -#define ACE_CODESET_ID_IBM_290 0x10020122U -#define ACE_CODESET_ID_IBM_297 0x10020129U -#define ACE_CODESET_ID_IBM_300 0x1002012CU -#define ACE_CODESET_ID_IBM_301 0x1002012DU -#define ACE_CODESET_ID_IBM_420 0x100201A4U -#define ACE_CODESET_ID_IBM_424 0x100201A8U -#define ACE_CODESET_ID_IBM_437 0x100201B5U -#define ACE_CODESET_ID_IBM_500 0x100201F4U -#define ACE_CODESET_ID_IBM_833 0x10020341U -#define ACE_CODESET_ID_IBM_834 0x10020342U -#define ACE_CODESET_ID_IBM_835 0x10020343U -#define ACE_CODESET_ID_IBM_836 0x10020344U -#define ACE_CODESET_ID_IBM_837 0x10020345U -#define ACE_CODESET_ID_IBM_838 0x10020346U -#define ACE_CODESET_ID_IBM_839 0x10020347U -#define ACE_CODESET_ID_IBM_850 0x10020352U -#define ACE_CODESET_ID_IBM_852 0x10020354U -#define ACE_CODESET_ID_IBM_855 0x10020357U -#define ACE_CODESET_ID_IBM_856 0x10020358U -#define ACE_CODESET_ID_IBM_857 0x10020359U -#define ACE_CODESET_ID_IBM_861 0x1002035DU -#define ACE_CODESET_ID_IBM_862 0x1002035EU -#define ACE_CODESET_ID_IBM_863 0x1002035FU -#define ACE_CODESET_ID_IBM_864 0x10020360U -#define ACE_CODESET_ID_IBM_866 0x10020362U -#define ACE_CODESET_ID_IBM_868 0x10020364U -#define ACE_CODESET_ID_IBM_869 0x10020365U -#define ACE_CODESET_ID_IBM_870 0x10020366U -#define ACE_CODESET_ID_IBM_871 0x10020367U -#define ACE_CODESET_ID_IBM_874 0x1002036AU -#define ACE_CODESET_ID_IBM_875 0x1002036BU -#define ACE_CODESET_ID_IBM_880 0x10020370U -#define ACE_CODESET_ID_IBM_891 0x1002037BU -#define ACE_CODESET_ID_IBM_896 0x10020380U -#define ACE_CODESET_ID_IBM_897 0x10020381U -#define ACE_CODESET_ID_IBM_903 0x10020387U -#define ACE_CODESET_ID_IBM_904 0x10020388U -#define ACE_CODESET_ID_IBM_918 0x10020396U -#define ACE_CODESET_ID_IBM_921 0x10020399U -#define ACE_CODESET_ID_IBM_922 0x1002039AU -#define ACE_CODESET_ID_IBM_926 0x1002039EU -#define ACE_CODESET_ID_IBM_927 0x1002039FU -#define ACE_CODESET_ID_IBM_928 0x100203A0U -#define ACE_CODESET_ID_IBM_929 0x100203A1U -#define ACE_CODESET_ID_IBM_930 0x100203A2U -#define ACE_CODESET_ID_IBM_932 0x100203A4U -#define ACE_CODESET_ID_IBM_933 0x100203A5U -#define ACE_CODESET_ID_IBM_934 0x100203A6U -#define ACE_CODESET_ID_IBM_935 0x100203A7U -#define ACE_CODESET_ID_IBM_936 0x100203A8U -#define ACE_CODESET_ID_IBM_937 0x100203A9U -#define ACE_CODESET_ID_IBM_938 0x100203AAU -#define ACE_CODESET_ID_IBM_939 0x100203ABU -#define ACE_CODESET_ID_IBM_941 0x100203ADU -#define ACE_CODESET_ID_IBM_942 0x100203AEU -#define ACE_CODESET_ID_IBM_943 0x100203AFU -#define ACE_CODESET_ID_IBM_946 0x100203B2U -#define ACE_CODESET_ID_IBM_947 0x100203B3U -#define ACE_CODESET_ID_IBM_948 0x100203B4U -#define ACE_CODESET_ID_IBM_949 0x100203B5U -#define ACE_CODESET_ID_IBM_950 0x100203B6U -#define ACE_CODESET_ID_IBM_951 0x100203B7U -#define ACE_CODESET_ID_IBM_955 0x100203BBU -#define ACE_CODESET_ID_IBM_964 0x100203C4U -#define ACE_CODESET_ID_IBM_970 0x100203CAU -#define ACE_CODESET_ID_IBM_1006 0x100203EEU -#define ACE_CODESET_ID_IBM_1025 0x10020401U -#define ACE_CODESET_ID_IBM_1026 0x10020402U -#define ACE_CODESET_ID_IBM_1027 0x10020403U -#define ACE_CODESET_ID_IBM_1040 0x10020410U -#define ACE_CODESET_ID_IBM_1041 0x10020411U -#define ACE_CODESET_ID_IBM_1043 0x10020413U -#define ACE_CODESET_ID_IBM_1046 0x10020416U -#define ACE_CODESET_ID_IBM_1047 0x10020417U -#define ACE_CODESET_ID_IBM_1088 0x10020440U -#define ACE_CODESET_ID_IBM_1097 0x10020449U -#define ACE_CODESET_ID_IBM_1098 0x1002044AU -#define ACE_CODESET_ID_IBM_1112 0x10020458U -#define ACE_CODESET_ID_IBM_1114 0x1002045AU -#define ACE_CODESET_ID_IBM_1115 0x1002045BU -#define ACE_CODESET_ID_IBM_1122 0x10020462U -#define ACE_CODESET_ID_IBM_1250 0x100204E2U -#define ACE_CODESET_ID_IBM_1251 0x100204E3U -#define ACE_CODESET_ID_IBM_1252 0x100204E4U -#define ACE_CODESET_ID_IBM_1253 0x100204E5U -#define ACE_CODESET_ID_IBM_1254 0x100204E6U -#define ACE_CODESET_ID_IBM_1255 0x100204E7U -#define ACE_CODESET_ID_IBM_1256 0x100204E8U -#define ACE_CODESET_ID_IBM_1257 0x100204E9U -#define ACE_CODESET_ID_IBM_1380 0x10020564U -#define ACE_CODESET_ID_IBM_1381 0x10020565U -#define ACE_CODESET_ID_IBM_1383 0x10020567U -#define ACE_CODESET_ID_IBM_4396 0x1002112CU -#define ACE_CODESET_ID_IBM_4946 0x10021352U -#define ACE_CODESET_ID_IBM_4948 0x10021354U -#define ACE_CODESET_ID_IBM_4951 0x10021357U -#define ACE_CODESET_ID_IBM_4952 0x10021358U -#define ACE_CODESET_ID_IBM_4953 0x10021359U -#define ACE_CODESET_ID_IBM_4960 0x10021360U -#define ACE_CODESET_ID_IBM_4964 0x10021364U -#define ACE_CODESET_ID_IBM_4965 0x10021365U -#define ACE_CODESET_ID_IBM_5026 0x100213A2U -#define ACE_CODESET_ID_IBM_5031 0x100213A7U -#define ACE_CODESET_ID_IBM_5035 0x100213ABU -#define ACE_CODESET_ID_IBM_5048 0x100213B8U -#define ACE_CODESET_ID_IBM_5049 0x100213B9U -#define ACE_CODESET_ID_IBM_5067 0x100213CBU -#define ACE_CODESET_ID_IBM_8612 0x100221A4U -#define ACE_CODESET_ID_IBM_9025 0x10022341U -#define ACE_CODESET_ID_IBM_9026 0x10022342U -#define ACE_CODESET_ID_IBM_9030 0x10022346U -#define ACE_CODESET_ID_IBM_9056 0x10022360U -#define ACE_CODESET_ID_IBM_9066 0x1002236AU -#define ACE_CODESET_ID_IBM_9125 0x100223A5U -#define ACE_CODESET_ID_IBM_25426 0x10026352U -#define ACE_CODESET_ID_IBM_25432 0x10026358U -#define ACE_CODESET_ID_IBM_1042 0x10026412U -#define ACE_CODESET_ID_IBM_28709 0x10027025U -#define ACE_CODESET_ID_IBM_33624 0x10028358U -#define ACE_CODESET_ID_IBM_33722 0x100283BAU -#define ACE_CODESET_ID_HTCSJIS 0x10030001U -#define ACE_CODESET_ID_HTCUJIS 0x10030002U -#define ACE_CODESET_ID_FUJITSU_U90 0x10040001U -#define ACE_CODESET_ID_FUJITSU_S90 0x10040002U -#define ACE_CODESET_ID_FUJITSU_R90 0x10040003U -#define ACE_CODESET_ID_EBCDIC_ASCII_AND_JEF 0x10040004U -#define ACE_CODESET_ID_EBCDIC_KATAKANA_AND_JEF 0x10040005U -#define ACE_CODESET_ID_EBCDIC_JAPANESE_ENGLISH_AND_JEF 0x10040006U - -#define ACE_CODESET_ID_TAO_BACKWARD_COMPATIBLE 0xf54414F0U -#endif // CODESET_SYMBOLS_H diff --git a/externals/ace/Condition_Recursive_Thread_Mutex.cpp b/externals/ace/Condition_Recursive_Thread_Mutex.cpp deleted file mode 100644 index 1f357589f55..00000000000 --- a/externals/ace/Condition_Recursive_Thread_Mutex.cpp +++ /dev/null @@ -1,129 +0,0 @@ -// -*- C++ -*- - -/** - * @file Condition_Recursive_Thread_Mutex.cpp - * - * $Id: Condition_Recursive_Thread_Mutex.cpp 89127 2010-02-22 19:58:18Z schmidt $ - * - * Originally in Synch.cpp - * - * @author Douglas C. Schmidt - */ - -#include "ace/Condition_Recursive_Thread_Mutex.h" - -#if defined (ACE_HAS_THREADS) - -#if defined (ACE_HAS_DUMP) -# include "ace/Log_Msg.h" -#endif /* ACE_HAS_DUMP */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -int -ACE_Condition::remove (void) -{ - return ACE_OS::cond_destroy (&this->cond_); -} - -void -ACE_Condition::dump (void) const -{ -#if defined (ACE_HAS_DUMP) -// ACE_TRACE ("ACE_Condition::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - // No dump method for ACE_cond_t even in emulated mode. - // cond_.dump (); - this->mutex_.dump (); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n"))); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -ACE_Condition::~ACE_Condition (void) -{ - this->remove (); -} - -ACE_Condition::ACE_Condition (ACE_Recursive_Thread_Mutex &m) - : mutex_ (m) -{ - ACE_OS::cond_init (&this->cond_); -} - -int -ACE_Condition::wait (const ACE_Time_Value *abstime) -{ - return this->wait (this->mutex_, abstime); -} - -int -ACE_Condition::wait (ACE_Recursive_Thread_Mutex &mutex, - const ACE_Time_Value *abstime) -{ - ACE_recursive_mutex_state mutex_state_holder; - ACE_recursive_thread_mutex_t &recursive_mutex = mutex.lock (); - - if (ACE_OS::recursive_mutex_cond_unlock (&recursive_mutex, - mutex_state_holder) == -1) - return -1; - - // We wait on the condition, specifying the nesting mutex. For platforms - // with ACE_HAS_RECURSIVE_MUTEXES, this is the recursive mutex itself, - // and is the same as recursive_mutex, above. The caller should have been - // holding the lock on entry to this method, and it is still held. - // For other platforms, this is the nesting mutex that guards the - // ACE_recursive_mutex_t internals, and recursive_mutex_cond_unlock() - // returned with the lock held, but waiters primed and waiting to be - // released. At cond_wait below, the mutex will be released. - // On return, it will be reacquired. - int const result = abstime == 0 - ? ACE_OS::cond_wait (&this->cond_, - &mutex.get_nesting_mutex ()) - : ACE_OS::cond_timedwait (&this->cond_, - &mutex.get_nesting_mutex (), - const_cast (abstime)); - // We are holding the mutex, whether the wait succeeded or failed. - // Stash errno (in case it failed) and then we need to reset the - // recursive mutex state to what it was on entry to this method. - // Resetting it may require a wait for another thread to release - // the ACE_recursive_thread_mutex_t if this is a platform without - // ACE_HAS_RECURSIVE_MUTEXES, and recursive_mutex_cond_relock() takes - // care of that. - { - ACE_Errno_Guard error (errno); - ACE_OS::recursive_mutex_cond_relock (&recursive_mutex, - mutex_state_holder); - } - - return result; -} - -int -ACE_Condition::signal (void) -{ - return ACE_OS::cond_signal (&this->cond_); -} - -int -ACE_Condition::broadcast (void) -{ - return ACE_OS::cond_broadcast (&this->cond_); -} - -ACE_Recursive_Thread_Mutex & -ACE_Condition::mutex (void) -{ - return this->mutex_; -} - -ACE_Condition_Recursive_Thread_Mutex::ACE_Condition_Recursive_Thread_Mutex ( - ACE_Recursive_Thread_Mutex &m) : - ACE_Condition (m) -{ -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_THREADS */ diff --git a/externals/ace/Condition_Recursive_Thread_Mutex.h b/externals/ace/Condition_Recursive_Thread_Mutex.h deleted file mode 100644 index ac3177da8c8..00000000000 --- a/externals/ace/Condition_Recursive_Thread_Mutex.h +++ /dev/null @@ -1,116 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file Condition_Recursive_Thread_Mutex.h - * - * $Id: Condition_Recursive_Thread_Mutex.h 86731 2009-09-17 12:23:48Z johnnyw $ - * - * Moved from Synch.h. - * - * @author Douglas C. Schmidt - */ -//========================================================================== - -#ifndef ACE_CONDITION_RECURSIVE_THREAD_MUTEX_H -#define ACE_CONDITION_RECURSIVE_THREAD_MUTEX_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_HAS_THREADS) -# include "ace/Null_Condition.h" -#else /* ACE_HAS_THREADS */ -#include "ace/Recursive_Thread_Mutex.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template class ACE_Condition; - -/** - * @brief ACE_Condition template specialization written using - * @a ACE_Recursive_Thread_Mutex. This allows threads to block until - * shared data changes state using recursive mutexes. - */ -template<> -class ACE_Export ACE_Condition -{ -public: - /// Initialize the condition variable with a recursive mutex. - ACE_Condition (ACE_Recursive_Thread_Mutex &m); - - /// Implicitly destroy the condition variable. - ~ACE_Condition (void); - - /** - * Explicitly destroy the condition variable. Note that only one - * thread should call this method since it doesn't protect against - * race conditions. - */ - int remove (void); - - /** - * Block on condition, or until absolute time-of-day has passed. If - * abstime == 0 use "blocking" semantics. Else, if @a abstime - * != 0 and the call times out before the condition is signaled - * returns -1 and sets errno to ETIME. - */ - int wait (const ACE_Time_Value *abstime = 0); - - /** - * Block on condition or until absolute time-of-day has passed. If - * abstime == 0 use "blocking" wait() semantics on the recursive @a mutex - * passed as a parameter (this is useful if you need to store the - * in shared memory). Else, if != 0 and the - * call times out before the condition is signaled returns -1 - * and sets errno to ETIME. - */ - int wait (ACE_Recursive_Thread_Mutex &mutex, - const ACE_Time_Value *abstime = 0); - - /// Signal one waiting thread. - int signal (void); - - /// Signal *all* waiting threads. - int broadcast (void); - - /// Returns a reference to the underlying mutex; - ACE_Recursive_Thread_Mutex &mutex (void); - - /// Dump the state of an object. - void dump (void) const; - -private: - - // = Prevent assignment and copying. - void operator= (const ACE_Condition &); - ACE_Condition (const ACE_Condition &); - -private: - - /// A normal (i.e., non-recursive) condition variable. - ACE_cond_t cond_; - - /// Reference to the recursive mutex. - ACE_Recursive_Thread_Mutex &mutex_; - -}; - -class ACE_Export ACE_Condition_Recursive_Thread_Mutex - : public ACE_Condition -{ -public: - /// Initialize the condition variable with a recursive mutex. - ACE_Condition_Recursive_Thread_Mutex (ACE_Recursive_Thread_Mutex &m); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* !ACE_HAS_THREADS */ - -#include /**/ "ace/post.h" -#endif /* ACE_CONDITION_RECURSIVE_THREAD_MUTEX_H */ diff --git a/externals/ace/Condition_T.cpp b/externals/ace/Condition_T.cpp deleted file mode 100644 index ae75d9ff359..00000000000 --- a/externals/ace/Condition_T.cpp +++ /dev/null @@ -1,127 +0,0 @@ -// $Id: Condition_T.cpp 89127 2010-02-22 19:58:18Z schmidt $ - -#ifndef ACE_CONDITION_T_CPP -#define ACE_CONDITION_T_CPP - -#include "ace/Condition_T.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_THREADS) - -#include "ace/Log_Msg.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Condition_T.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Condition) - -template void -ACE_Condition::dump (void) const -{ -#if defined (ACE_HAS_DUMP) -// ACE_TRACE ("ACE_Condition::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n"))); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -template -ACE_Thread_Condition::ACE_Thread_Condition (MUTEX &m, - const ACE_TCHAR *name, - void *arg) - : ACE_Condition (m, USYNC_THREAD, name, arg) -{ -// ACE_TRACE ("ACE_Thread_Condition::ACE_Thread_Condition"); -} - -template void -ACE_Thread_Condition::dump (void) const -{ -#if defined (ACE_HAS_DUMP) -// ACE_TRACE ("ACE_Thread_Condition::dump"); - - ACE_Condition::dump (); -#endif /* ACE_HAS_DUMP */ -} - -template -ACE_Condition::ACE_Condition (MUTEX &m, - int type, - const ACE_TCHAR *name, - void *arg) - : - mutex_ (m) -{ - // ACE_TRACE ("ACE_Condition::ACE_Condition"); - - if (ACE_OS::cond_init (&this->cond_, - (short) type, - name, - arg) != 0) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_Condition::ACE_Condition"))); -} - -template -ACE_Condition::~ACE_Condition (void) -{ - // ACE_TRACE ("ACE_Condition::~ACE_Condition"); - - if (this->remove () == -1) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_Condition::~ACE_Condition"))); -} - -template int -ACE_Condition::wait (void) -{ - // ACE_TRACE ("ACE_Condition::wait"); - return ACE_OS::cond_wait (&this->cond_, - &this->mutex_.lock ()); -} - -template int -ACE_Condition::wait (MUTEX &mutex, - const ACE_Time_Value *abstime) -{ -// ACE_TRACE ("ACE_Condition::wait"); - if (abstime == 0) - { - return ACE_OS::cond_wait (&this->cond_, - &mutex.lock ()); - } - else - { - ACE_Time_Value tv = *abstime; - return ACE_OS::cond_timedwait (&this->cond_, - &mutex.lock (), - &tv); - } -} - -// Peform an "alertable" timed wait. If the argument ABSTIME == 0 -// then we do a regular cond_wait(), else we do a timed wait for up to -// ABSTIME using the Solaris cond_timedwait() function. - -template int -ACE_Condition::wait (const ACE_Time_Value *abstime) -{ -// ACE_TRACE ("ACE_Condition::wait"); - return this->wait (this->mutex_, abstime); -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_THREADS */ - -#endif /* ACE_CONDITION_T_CPP */ diff --git a/externals/ace/Condition_T.h b/externals/ace/Condition_T.h deleted file mode 100644 index 936ce821777..00000000000 --- a/externals/ace/Condition_T.h +++ /dev/null @@ -1,167 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file Condition_T.h - * - * $Id: Condition_T.h 81462 2008-04-28 11:39:40Z johnnyw $ - * - * Moved from Synch.h. - * - * @author Douglas C. Schmidt - */ -//========================================================================== - -#ifndef ACE_CONDITION_T_H -#define ACE_CONDITION_T_H - -#include /**/ "ace/pre.h" - -#include "ace/OS_NS_Thread.h" -#include "ace/Lock.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_THREADS) /* ACE platform supports some form of threading. */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -class ACE_Time_Value; - -/** - * @class ACE_Condition - * - * @brief ACE_Condition variable wrapper, which allows threads to block - * until shared data changes state. - * - * A condition variable enables threads to atomically block and - * test the condition under the protection of a mutual exclu- - * sion lock (mutex) until the condition is satisfied. That is, - * the mutex must have been held by the thread before calling - * wait or signal on the condition. If the condition is false, - * a thread blocks on a condition variable and atomically - * releases the mutex that is waiting for the condition to - * change. If another thread changes the condition, it may wake - * up waiting threads by signaling the associated condition - * variable. The waiting threads, upon awakening, reacquire the - * mutex and re-evaluate the condition. - * Note, you can only parameterize with - * @a ACE_Thread_Mutex, @a ACE_Recursive_Thread_Mutex, or @a ACE_Null_Mutex. - */ -template -class ACE_Condition -{ -public: - // = Initialiation and termination methods. - /// Initialize the condition variable. - ACE_Condition (MUTEX &m, int type = USYNC_THREAD, - const ACE_TCHAR *name = 0, void *arg = 0); - - /// Implicitly destroy the condition variable. - ~ACE_Condition (void); - - // = Lock accessors. - /** - * Block on condition, or until absolute time-of-day has passed. If - * @a abstime == 0 use "blocking" semantics. Else, if @a abstime - * != 0 and the call times out before the condition is signaled - * returns -1 and sets errno to ETIME. - */ - int wait (const ACE_Time_Value *abstime); - - /// Block on condition. - int wait (void); - - /** - * Block on condition or until absolute time-of-day has passed. If - * abstime == 0 use "blocking" wait() semantics on the - * passed as a parameter (this is useful if you need to store the - * in shared memory). Else, if != 0 and the - * call times out before the condition is signaled returns -1 - * and sets errno to ETIME. - */ - int wait (MUTEX &mutex, const ACE_Time_Value *abstime = 0); - - /// Signal one waiting thread. - int signal (void); - - /// Signal *all* waiting threads. - int broadcast (void); - - // = Utility methods. - /// Explicitly destroy the condition variable. - int remove (void); - - /// Returns a reference to the underlying mutex_; - MUTEX &mutex (void); - - /// Dump the state of an object. - void dump (void) const; - - // ACE_ALLOC_HOOK_DECLARE; - // Declare the dynamic allocation hooks. - -protected: - /// Condition variable. - ACE_cond_t cond_; - - /// Reference to mutex lock. - MUTEX &mutex_; - -private: - // = Prevent assignment and initialization. - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Condition &)) - ACE_UNIMPLEMENTED_FUNC (ACE_Condition (const ACE_Condition &)) -}; - -/** - * @class ACE_Thread_Condition - * - * @brief ACE_Condition variable wrapper that works within processes. - * - * A condition variable enables threads to atomically block and - * test the condition under the protection of a mutual exclu- - * sion lock (mutex) until the condition is satisfied. That is, - * the mutex must have been held by the thread before calling - * wait or signal on the condition. If the condition is false, - * a thread blocks on a condition variable and atomically - * releases the mutex that is waiting for the condition to - * change. If another thread changes the condition, it may wake - * up waiting threads by signaling the associated condition - * variable. The waiting threads, upon awakening, reacquire the - * mutex and re-evaluate the condition. - */ -template -class ACE_Thread_Condition : public ACE_Condition -{ -public: - // = Initialization method. - ACE_Thread_Condition (MUTEX &m, const ACE_TCHAR *name = 0, void *arg = 0); - - /// Dump the state of an object. - void dump (void) const; - - // ACE_ALLOC_HOOK_DECLARE; - // Declare the dynamic allocation hooks. -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Condition_T.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Condition_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Condition_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#endif /* ACE_HAS_THREADS */ - -#include /**/ "ace/post.h" -#endif /* ACE_CONDITION_T_H */ diff --git a/externals/ace/Condition_T.inl b/externals/ace/Condition_T.inl deleted file mode 100644 index e3b452734a2..00000000000 --- a/externals/ace/Condition_T.inl +++ /dev/null @@ -1,51 +0,0 @@ -// -*- C++ -*- -// -// $Id: Condition_T.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template ACE_INLINE int -ACE_Condition::remove (void) -{ - // ACE_TRACE ("ACE_Condition::remove"); - - // cond_destroy() is called in a loop if the condition variable is - // BUSY. This avoids a condition where a condition is signaled and - // because of some timing problem, the thread that is to be signaled - // has called the cond_wait routine after the signal call. Since - // the condition signal is not queued in any way, deadlock occurs. - - int result = 0; - - while ((result = ACE_OS::cond_destroy (&this->cond_)) == -1 - && errno == EBUSY) - { - ACE_OS::cond_broadcast (&this->cond_); - ACE_OS::thr_yield (); - } - - return result; -} - -template ACE_INLINE MUTEX & -ACE_Condition::mutex (void) -{ - // ACE_TRACE ("ACE_Condition::mutex"); - return this->mutex_; -} - -template ACE_INLINE int -ACE_Condition::signal (void) -{ -// ACE_TRACE ("ACE_Condition::signal"); - return ACE_OS::cond_signal (&this->cond_); -} - -template ACE_INLINE int -ACE_Condition::broadcast (void) -{ -// ACE_TRACE ("ACE_Condition::broadcast"); - return ACE_OS::cond_broadcast (&this->cond_); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Condition_Thread_Mutex.cpp b/externals/ace/Condition_Thread_Mutex.cpp deleted file mode 100644 index c9f2620e432..00000000000 --- a/externals/ace/Condition_Thread_Mutex.cpp +++ /dev/null @@ -1,126 +0,0 @@ -/* -*- C++ -*- */ -/** - * @file Condition_Thread_Mutex.cpp - * - * $Id: Condition_Thread_Mutex.cpp 80826 2008-03-04 14:51:23Z wotte $ - * - * Originally in Synch.cpp - * - * @author Douglas C. Schmidt - */ - -#include "ace/Condition_Thread_Mutex.h" - -#if defined (ACE_HAS_THREADS) - -#if !defined (__ACE_INLINE__) -#include "ace/Condition_Thread_Mutex.inl" -#endif /* __ACE_INLINE__ */ - -#include "ace/Log_Msg.h" - -ACE_RCSID(ace, Condition_Thread_Mutex, "$Id: Condition_Thread_Mutex.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Condition_Thread_Mutex) - -void -ACE_Condition_Thread_Mutex::dump (void) const -{ -#if defined (ACE_HAS_DUMP) -// ACE_TRACE ("ACE_Condition_Thread_Mutex::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n"))); -#if defined (ACE_WIN32) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("waiters = %d\n"), - this->cond_.waiters ())); -#endif /* ACE_WIN32 */ - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -ACE_Condition_Thread_Mutex::ACE_Condition_Thread_Mutex (ACE_Thread_Mutex &m, - const ACE_TCHAR *name, - void *arg) - : mutex_ (m), - removed_ (false) -{ -// ACE_TRACE ("ACE_Condition_Thread_Mutex::ACE_Condition_Thread_Mutex"); - if (ACE_OS::cond_init (&this->cond_, - (short) USYNC_THREAD, - name, - arg) != 0) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_Condition_Thread_Mutex::ACE_Condition_Thread_Mutex"))); -} - -ACE_Condition_Thread_Mutex:: -ACE_Condition_Thread_Mutex (ACE_Thread_Mutex &m, - ACE_Condition_Attributes &attributes, - const ACE_TCHAR *name, - void *arg) - : mutex_ (m), - removed_ (false) -{ -// ACE_TRACE ("ACE_Condition_Thread_Mutex::ACE_Condition_Thread_Mutex"); - if (ACE_OS::cond_init (&this->cond_, attributes.attributes_, - name, arg) != 0) - ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_Condition_Thread_Mutex::ACE_Condition_Thread_Mutex"))); -} - -ACE_Condition_Thread_Mutex::~ACE_Condition_Thread_Mutex (void) -{ -// ACE_TRACE ("ACE_Condition_Thread_Mutex::~ACE_Condition_Thread_Mutex"); - this->remove (); -} - -// Peform an "alertable" timed wait. If the argument == 0 -// then we do a regular , else we do a timed wait for up to -// using the function. - -int -ACE_Condition_Thread_Mutex::wait (void) -{ -// ACE_TRACE ("ACE_Condition_Thread_Mutex::wait"); - return ACE_OS::cond_wait (&this->cond_, &this->mutex_.lock_); -} - -int -ACE_Condition_Thread_Mutex::wait (ACE_Thread_Mutex &mutex, - const ACE_Time_Value *abstime) -{ -// ACE_TRACE ("ACE_Condition_Thread_Mutex::wait"); - return ACE_OS::cond_timedwait (&this->cond_, - &mutex.lock_, - const_cast (abstime)); -} - -int -ACE_Condition_Thread_Mutex::wait (const ACE_Time_Value *abstime) -{ -// ACE_TRACE ("ACE_Condition_Thread_Mutex::wait"); - return this->wait (this->mutex_, abstime); -} - -int -ACE_Condition_Thread_Mutex::signal (void) -{ -// ACE_TRACE ("ACE_Condition_Thread_Mutex::signal"); - return ACE_OS::cond_signal (&this->cond_); -} - -int -ACE_Condition_Thread_Mutex::broadcast (void) -{ -// ACE_TRACE ("ACE_Condition_Thread_Mutex::broadcast"); - return ACE_OS::cond_broadcast (&this->cond_); -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_THREADS */ diff --git a/externals/ace/Condition_Thread_Mutex.h b/externals/ace/Condition_Thread_Mutex.h deleted file mode 100644 index 693ff0820aa..00000000000 --- a/externals/ace/Condition_Thread_Mutex.h +++ /dev/null @@ -1,190 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file Condition_Thread_Mutex.h - * - * $Id: Condition_Thread_Mutex.h 80826 2008-03-04 14:51:23Z wotte $ - * - * Moved from Synch.h. - * - * @author Douglas C. Schmidt - */ -//========================================================================== - -#ifndef ACE_CONDITION_THREAD_MUTEX_H -#define ACE_CONDITION_THREAD_MUTEX_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_HAS_THREADS) -# include "ace/Null_Condition.h" -#else /* ACE_HAS_THREADS */ -// ACE platform supports some form of threading. - -#include "ace/Thread_Mutex.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -class ACE_Time_Value; - -class ACE_Export ACE_Condition_Attributes -{ -public: - /// Constructor - ACE_Condition_Attributes (int type = ACE_DEFAULT_SYNCH_TYPE); - - /// Destructor - ~ACE_Condition_Attributes (void); - -private: - friend class ACE_Condition_Thread_Mutex; - - /// The attributes - ACE_condattr_t attributes_; - -private: - // = Prevent assignment and initialization. - void operator= (const ACE_Condition_Attributes &); - ACE_Condition_Attributes (const ACE_Condition_Attributes &); -}; - -/** - * @class ACE_Condition_Thread_Mutex - * - * @brief ACE_Condition variable wrapper written using ACE_Mutexes This - * allows threads to block until shared data changes state. - * A condition variable enables threads to atomically block and - * test the condition under the protection of a mutual exclu- - * sion lock (mutex) until the condition is satisfied. That is, - * the mutex must have been held by the thread before calling - * wait or signal on the condition. If the condition is false, - * a thread blocks on a condition variable and atomically - * releases the mutex that is waiting for the condition to - * change. If another thread changes the condition, it may wake - * up waiting threads by signaling the associated condition - * variable. The waiting threads, upon awakening, reacquire the - * mutex and re-evaluate the condition. - * - * This should be an instantiation of ACE_Condition but problems - * with compilers precludes this... - */ -class ACE_Export ACE_Condition_Thread_Mutex -{ -public: - /// Initialize the condition variable. - ACE_Condition_Thread_Mutex (ACE_Thread_Mutex &m, - const ACE_TCHAR *name = 0, - void *arg = 0); - - /// Initialize the condition variable. - ACE_Condition_Thread_Mutex (ACE_Thread_Mutex &m, - ACE_Condition_Attributes &attributes, - const ACE_TCHAR *name = 0, - void *arg = 0); - - /// Implicitly destroy the condition variable. - ~ACE_Condition_Thread_Mutex (void); - - /** - * Explicitly destroy the condition variable. Note that only one - * thread should call this method since it doesn't protect against - * race conditions. - */ - int remove (void); - - /** - * Block on condition, or until absolute time-of-day has passed. If - * abstime == 0 use "blocking" semantics. Else, if @a abstime - * != 0 and the call times out before the condition is signaled - * returns -1 and sets errno to ETIME. - */ - int wait (const ACE_Time_Value *abstime); - - /// Block on condition. - int wait (void); - - /** - * Block on condition or until absolute time-of-day has passed. If - * abstime == 0 use "blocking" wait() semantics on the - * passed as a parameter (this is useful if you need to store the - * in shared memory). Else, if @a abstime != 0 and the - * call times out before the condition is signaled returns -1 - * and sets errno to ETIME. - */ - int wait (ACE_Thread_Mutex &mutex, const ACE_Time_Value *abstime = 0); - - /// Signal one waiting thread. - int signal (void); - - /// Signal *all* waiting threads. - int broadcast (void); - - /// Returns a reference to the underlying mutex; - ACE_Thread_Mutex &mutex (void); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - /// Condition variable. - ACE_cond_t cond_; - - /// Reference to mutex lock. - ACE_Thread_Mutex &mutex_; - - /// Keeps track of whether has been called yet to avoid - /// multiple calls, e.g., explicitly and implicitly in the - /// destructor. This flag isn't protected by a lock, so make sure - /// that you don't have multiple threads simultaneously calling - /// on the same object, which is a bad idea anyway... - bool removed_; - -private: - // = Prevent assignment and initialization. - void operator= (const ACE_Condition_Thread_Mutex &); - ACE_Condition_Thread_Mutex (const ACE_Condition_Thread_Mutex &); -}; - -#if 0 -// The following class is commented out since there doesn't -// appear to be a portable and robust means of implementing this -// functionality across platforms. If you know of a portable and -// robust way to implement this functionality please let us know. - -/** - * @class ACE_Process_Condition - * - * @brief ACE_Condition variable wrapper that works across processes. - */ -class ACE_Export ACE_Process_Condition -{ -public: - ACE_Process_Condition (MUTEX &m, const ACE_TCHAR *name = 0, void *arg = 0); - - /// Dump the state of an object. - void dump (void) const; - - // ACE_ALLOC_HOOK_DECLARE; - // Declare the dynamic allocation hooks. -}; -#endif /* 0 */ - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Condition_Thread_Mutex.inl" -#endif /* __ACE_INLINE__ */ - -#endif /* !ACE_HAS_THREADS */ - -#include /**/ "ace/post.h" -#endif /* ACE_CONDITION_THREAD_MUTEX_H */ diff --git a/externals/ace/Condition_Thread_Mutex.inl b/externals/ace/Condition_Thread_Mutex.inl deleted file mode 100644 index 851269e4af6..00000000000 --- a/externals/ace/Condition_Thread_Mutex.inl +++ /dev/null @@ -1,74 +0,0 @@ -// -*- C++ -*- -// -// $Id: Condition_Thread_Mutex.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE -ACE_Condition_Attributes::ACE_Condition_Attributes (int type) -{ - (void) ACE_OS::condattr_init (this->attributes_, type); -} - -ACE_INLINE -ACE_Condition_Attributes::~ACE_Condition_Attributes (void) -{ - ACE_OS::condattr_destroy (this->attributes_); -} - -ACE_INLINE int -ACE_Condition_Thread_Mutex::remove (void) -{ -// ACE_TRACE ("ACE_Condition_Thread_Mutex::remove"); - - // is called in a loop if the condition variable is - // BUSY. This avoids a condition where a condition is signaled and - // because of some timing problem, the thread that is to be signaled - // has called the cond_wait routine after the signal call. Since - // the condition signal is not queued in any way, deadlock occurs. - - int result = 0; - - if (!this->removed_) - { - this->removed_ = true; - - while ((result = ACE_OS::cond_destroy (&this->cond_)) == -1 - && errno == EBUSY) - { - ACE_OS::cond_broadcast (&this->cond_); - ACE_OS::thr_yield (); - } - } - return result; -} - -ACE_INLINE ACE_Thread_Mutex & -ACE_Condition_Thread_Mutex::mutex (void) -{ -// ACE_TRACE ("ACE_Condition_Thread_Mutex::mutex"); - return this->mutex_; -} - -#if 0 -template void -ACE_Process_Condition::dump (void) const -{ -#if defined (ACE_HAS_DUMP) -// ACE_TRACE ("ACE_Process_Condition::dump"); - - ACE_Condition::dump (); -#endif /* ACE_HAS_DUMP */ -} - -template -ACE_Process_Condition::ACE_Process_Condition (MUTEX &m, - const ACE_TCHAR *name, - void *arg) - : ACE_Condition (m, USYNC_PROCESS, name, arg) -{ -// ACE_TRACE ("ACE_Process_Condition::ACE_Process_Condition"); -} -#endif /* 0 */ - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Configuration.cpp b/externals/ace/Configuration.cpp deleted file mode 100644 index 1914f2dc651..00000000000 --- a/externals/ace/Configuration.cpp +++ /dev/null @@ -1,2152 +0,0 @@ -// $Id: Configuration.cpp 86348 2009-08-04 14:45:29Z shuston $ -#include "ace/Configuration.h" -#include "ace/Auto_Ptr.h" -#include "ace/SString.h" -#include "ace/OS_NS_string.h" -#include "ace/OS_NS_strings.h" -#include "ace/Tokenizer_T.h" - -// Can remove this when import_config and export_config are removed from -// ACE_Configuration. They're deprecated at ACE 5.2. -#include "ace/Configuration_Import_Export.h" - -#if !defined (ACE_LACKS_ACCESS) -# include "ace/OS_NS_unistd.h" -#endif /* ACE_LACKS_ACCESS */ - -#if !defined (__ACE_INLINE__) -#include "ace/Configuration.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_Section_Key_Internal::ACE_Section_Key_Internal (void) - : ref_count_ (0) -{ -} - -ACE_Section_Key_Internal::~ACE_Section_Key_Internal (void) -{ -} - -int -ACE_Section_Key_Internal::add_ref (void) -{ - ++ref_count_; - return 0; -} - -int -ACE_Section_Key_Internal::dec_ref (void) -{ - if (!--ref_count_) - delete this; - return 0; -} - -ACE_Configuration_Section_Key::ACE_Configuration_Section_Key (void) - : key_ (0) -{ -} - -ACE_Configuration_Section_Key::~ACE_Configuration_Section_Key (void) -{ - if (key_) - key_->dec_ref (); -} - -ACE_Configuration_Section_Key::ACE_Configuration_Section_Key (ACE_Section_Key_Internal* key) - : key_ (key) -{ - if (key_) - key_->add_ref (); -} - -ACE_Configuration_Section_Key::ACE_Configuration_Section_Key (const ACE_Configuration_Section_Key& rhs) - : key_ (rhs.key_) -{ - if (key_) - key_->add_ref (); -} - -ACE_Configuration_Section_Key& -ACE_Configuration_Section_Key::operator= (const ACE_Configuration_Section_Key& rhs) -{ - if (this != &rhs) - { - if (key_) - key_->dec_ref (); - - key_ = rhs.key_; - - if (key_) - key_->add_ref (); - } - return *this; -} - -////////////////////////////////////////////////////////////////////////////// - -ACE_TCHAR ACE_Configuration::NULL_String_ = '\0'; - -ACE_Configuration::ACE_Configuration (void) - : root_ () -{ -} - -ACE_Configuration::~ACE_Configuration (void) -{ -} - -ACE_Section_Key_Internal* -ACE_Configuration::get_internal_key (const ACE_Configuration_Section_Key& key) -{ - return key.key_; -} - -int -ACE_Configuration::expand_path (const ACE_Configuration_Section_Key& key, - const ACE_TString& path_in, - ACE_Configuration_Section_Key& key_out, - int create) -{ - // Make a copy of key - ACE_Configuration_Section_Key current_section = key; - ACE_Auto_Basic_Array_Ptr pData (path_in.rep ()); - ACE_Tokenizer parser (pData.get ()); - parser.delimiter_replace ('\\', '\0'); - parser.delimiter_replace ('/', '\0'); - - for (ACE_TCHAR *temp = parser.next (); - temp != 0; - temp = parser.next ()) - { - // Open the section - if (open_section (current_section, - temp, - create, - key_out)) - return -1; - - current_section = key_out; - } - - return 0; - -} - -// import_config and export_config are here for backward compatibility, -// and have been deprecated. -int -ACE_Configuration::export_config (const ACE_TCHAR* filename) -{ - ACE_Registry_ImpExp exporter (*this); - return exporter.export_config (filename); -} - -int -ACE_Configuration::import_config (const ACE_TCHAR* filename) -{ - ACE_Registry_ImpExp importer (*this); - return importer.import_config (filename); -} - -int -ACE_Configuration::validate_name (const ACE_TCHAR* name, int allow_path) -{ - // Invalid character set - const ACE_TCHAR* reject = - allow_path ? ACE_TEXT ("][") : ACE_TEXT ("\\]["); - - // Position of the first invalid character or terminating null. - size_t const pos = ACE_OS::strcspn (name, reject); - - // Check if it is an invalid character. - if (name[pos] != ACE_TEXT ('\0')) - { - errno = EINVAL; - return -1; - } - - // The first character can never be a path separator. - if (name[0] == ACE_TEXT ('\\')) - { - errno = EINVAL; - return -1; - } - - // Validate length. - if (pos == 0 || pos > 255) - { - errno = ENAMETOOLONG; - return -1; - } - - return 0; -} - -int -ACE_Configuration::validate_value_name (const ACE_TCHAR* name) -{ - if (name == 0 || *name == this->NULL_String_) - return 0; - - return this->validate_name (name); -} - -const ACE_Configuration_Section_Key& -ACE_Configuration::root_section (void) const -{ - return root_; -} - -/** - * Determine if the contents of this object is the same as the - * contents of the object on the right hand side. - * Returns 1 (True) if they are equal and 0 (False) if they are not equal - */ -bool -ACE_Configuration::operator== (const ACE_Configuration& rhs) const -{ - bool rc = true; - int sectionIndex = 0; - ACE_TString sectionName; - ACE_Configuration *nonconst_this = const_cast (this); - ACE_Configuration &nonconst_rhs = const_cast (rhs); - - const ACE_Configuration_Section_Key& rhsRoot = rhs.root_section (); - ACE_Configuration_Section_Key rhsSection; - ACE_Configuration_Section_Key thisSection; - - // loop through each section in this object - while ((rc) && (nonconst_this->enumerate_sections (this->root_, - sectionIndex, - sectionName) == 0)) - { - // find that section in the rhs object - if (nonconst_rhs.open_section (rhsRoot, - sectionName.c_str (), - 0, - rhsSection) != 0) - { - // If the rhs object does not contain the section then we are - // not equal. - rc = false; - } - else if (nonconst_this->open_section (this->root_, - sectionName.c_str (), - 0, - thisSection) != 0) - { - // if there is some error opening the section in this object - rc = false; - } - else - { - // Well the sections match - int valueIndex = 0; - ACE_TString valueName; - VALUETYPE valueType; - VALUETYPE rhsType; - - // Enumerate each value in this section - while ((rc) && nonconst_this->enumerate_values (thisSection, - valueIndex, - valueName, - valueType) == 0) - { - // look for the same value in the rhs section - if (nonconst_rhs.find_value (rhsSection, - valueName.c_str (), - rhsType) != 0) - { - // We're not equal if the same value cannot - // be found in the rhs object. - rc = false; - } - else if (valueType != rhsType) - { - // we're not equal if the types do not match. - rc = false; - } - else - { - // finally compare values. - if (valueType == STRING) - { - ACE_TString thisString, rhsString; - if (nonconst_this->get_string_value (thisSection, - valueName.c_str (), - thisString) != 0) - { - // we're not equal if we cannot get this string - rc = false; - } - else if (nonconst_rhs.get_string_value ( - rhsSection, - valueName.c_str (), - rhsString) != 0) - { - // we're not equal if we cannot get rhs string - rc = false; - } - rc = (thisString == rhsString); - } - else if (valueType == INTEGER) - { - u_int thisInt = 0; - u_int rhsInt = 0; - if (nonconst_this->get_integer_value ( - thisSection, - valueName.c_str (), - thisInt) != 0) - { - // we're not equal if we cannot get this int - rc = false; - } - else if (nonconst_rhs.get_integer_value ( - rhsSection, - valueName.c_str (), - rhsInt) != 0) - { - // we're not equal if we cannot get rhs int - rc = false; - } - rc = (thisInt == rhsInt); - } - else if (valueType == BINARY) - { - void* thisData = 0; - void* rhsData = 0; - size_t thisLength = 0; - size_t rhsLength = 0; - if (nonconst_this->get_binary_value (thisSection, - valueName.c_str (), - thisData, - thisLength) != 0) - { - // we're not equal if we cannot get this data - rc = false; - } - else if (nonconst_rhs.get_binary_value ( - rhsSection, - valueName.c_str (), - rhsData, - rhsLength) != 0) - { - // we're not equal if we cannot get this data - rc = false; - } - - rc = (thisLength == rhsLength); - // are the length's the same? - - if (rc) - { - unsigned char* thisCharData = - (unsigned char*)thisData; - unsigned char* rhsCharData = (unsigned char*)rhsData; - // yes, then check each element - for (size_t count = 0; - (rc) && (count < thisLength); - count++) - { - rc = (* (thisCharData + count) == * (rhsCharData + count)); - } - - delete [] thisCharData; - delete [] rhsCharData; - }// end if the length's match - } - // We should never have valueTypes of INVALID, therefore - // we're not comparing them. How would we since we have - // no get operation for invalid types. - // So, if we have them, we guess they are equal. - - }// end else if values match. - - ++valueIndex; - - }// end value while loop - - // look in the rhs for values not in this - valueIndex = 0; - while ((rc) && (nonconst_rhs.enumerate_values (rhsSection, - valueIndex, - valueName, - rhsType) == 0)) - { - // look for the same value in this section - if (nonconst_this->find_value (thisSection, - valueName.c_str (), - valueType) != 0) - { - // We're not equal if the same value cannot - // be found in the rhs object. - rc = false; - } - ++valueIndex; - }// end while for rhs values not in this. - - }// end else if sections match. - - ++sectionIndex; - - }// end section while loop - - // Finally, make sure that there are no sections in rhs that do not - // exist in this - sectionIndex = 0; - while ((rc) - && (nonconst_rhs.enumerate_sections (rhsRoot, - sectionIndex, - sectionName) == 0)) - { - // find the section in this - if (nonconst_this->open_section (this->root_, - sectionName.c_str (), - 0, - thisSection) != 0) - { - // if there is some error opening the section in this object - rc = false; - } - else if (nonconst_rhs.open_section (rhsRoot, - sectionName.c_str (), - 0, - rhsSection) != 0) - { - // If the rhs object does not contain the section then we - // are not equal. - rc = false; - } - ++sectionIndex; - } - return rc; -} - -bool -ACE_Configuration::operator!= (const ACE_Configuration& rhs) const -{ - return !(*this == rhs); -} - -////////////////////////////////////////////////////////////////////////////// - -#if defined (ACE_WIN32) && !defined (ACE_LACKS_WIN32_REGISTRY) - -static const int ACE_DEFAULT_BUFSIZE = 256; - -static const ACE_TCHAR *temp_name (const ACE_TCHAR *name) -{ - if (name && *name == ACE_Configuration::NULL_String_) - return 0; - return name; -} - -ACE_Section_Key_Win32::ACE_Section_Key_Win32 (HKEY hKey) - : hKey_ (hKey) -{ -} - -ACE_Section_Key_Win32::~ACE_Section_Key_Win32 (void) -{ - ::RegCloseKey (hKey_); -} - -////////////////////////////////////////////////////////////////////////////// - -bool -ACE_Configuration_Win32Registry::operator== (const ACE_Configuration_Win32Registry &rhs) const -{ - ACE_UNUSED_ARG (rhs); - return true; -} - -bool -ACE_Configuration_Win32Registry::operator!= (const ACE_Configuration_Win32Registry &rhs) const -{ - ACE_UNUSED_ARG (rhs); - return true; -} - -ACE_Configuration_Win32Registry::ACE_Configuration_Win32Registry (HKEY hKey) -{ - ACE_Section_Key_Win32 *temp = 0; - - ACE_NEW (temp, ACE_Section_Key_Win32 (hKey)); - - root_ = ACE_Configuration_Section_Key (temp); -} - - -ACE_Configuration_Win32Registry::~ACE_Configuration_Win32Registry (void) -{ -} - -int -ACE_Configuration_Win32Registry::open_section (const ACE_Configuration_Section_Key& base, - const ACE_TCHAR* sub_section, - int create, - ACE_Configuration_Section_Key& result) -{ - if (validate_name (sub_section, 1)) - return -1; - - HKEY base_key; - if (load_key (base, base_key)) - return -1; - - int errnum; - HKEY result_key; - if ((errnum = ACE_TEXT_RegOpenKeyEx (base_key, - sub_section, - 0, - KEY_ALL_ACCESS, - &result_key)) != ERROR_SUCCESS) - { - if (!create) - { - errno = errnum; - return -1; - } - - if ((errnum = ACE_TEXT_RegCreateKeyEx (base_key, - sub_section, - 0, - 0, - REG_OPTION_NON_VOLATILE, - KEY_ALL_ACCESS, - 0, - &result_key, - (PDWORD) 0 - )) != ERROR_SUCCESS) - { - errno = errnum; - return -1; - } - } - - ACE_Section_Key_Win32 *temp; - - ACE_NEW_RETURN (temp, ACE_Section_Key_Win32 (result_key), -1); - result = ACE_Configuration_Section_Key (temp); - return 0; -} - -int -ACE_Configuration_Win32Registry::remove_section (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* sub_section, - bool recursive) -{ - if (validate_name (sub_section)) - return -1; - - HKEY base_key; - if (load_key (key, base_key)) - return -1; - - if (recursive) - { - ACE_Configuration_Section_Key section; - if (open_section (key, sub_section, 0, section)) - return -1; - - HKEY sub_key; - if (load_key (section, sub_key)) - return -1; - - ACE_TCHAR name_buffer[ACE_DEFAULT_BUFSIZE]; - DWORD buffer_size = ACE_DEFAULT_BUFSIZE; - // Note we don't increment the index because the - // enumeration becomes invalid if we change the - // subkey, which we do when we delete it. By leaving - // it 0, we always delete the top entry - while (ACE_TEXT_RegEnumKeyEx (sub_key, - 0, - name_buffer, - &buffer_size, - 0, - 0, - 0, - 0) == ERROR_SUCCESS) - { - remove_section (section, name_buffer, true); - buffer_size = ACE_DEFAULT_BUFSIZE; - } - } - - int const errnum = ACE_TEXT_RegDeleteKey (base_key, sub_section); - if (errnum != ERROR_SUCCESS) - { - errno = errnum; - return -1; - } - - return 0; -} - -int -ACE_Configuration_Win32Registry::enumerate_values (const ACE_Configuration_Section_Key& key, - int index, - ACE_TString& name, - VALUETYPE& type) -{ - HKEY base_key; - if (load_key (key, base_key)) - return -1; - - ACE_TCHAR name_buffer[ACE_DEFAULT_BUFSIZE]; - DWORD buffer_size = ACE_DEFAULT_BUFSIZE; - DWORD value_type; - - int rc = ACE_TEXT_RegEnumValue (base_key, - index, - name_buffer, - &buffer_size, - 0, - &value_type, - 0, - 0); - if (rc == ERROR_NO_MORE_ITEMS) - return 1; - else if (rc != ERROR_SUCCESS) - { - errno = rc; - return -1; - } - - name = name_buffer; - - switch (value_type) - { - case REG_BINARY: - type = BINARY; - break; - case REG_SZ: - type = STRING; - break; - case REG_DWORD: - type = INTEGER; - break; - default: - type = INVALID; - } - - return 0; -} - -int -ACE_Configuration_Win32Registry::enumerate_sections (const ACE_Configuration_Section_Key& key, - int index, - ACE_TString& name) -{ - HKEY base_key; - if (load_key (key, base_key)) - return -1; - - ACE_TCHAR name_buffer[ACE_DEFAULT_BUFSIZE]; - DWORD buffer_size = ACE_DEFAULT_BUFSIZE; - int rc = ACE_TEXT_RegEnumKeyEx (base_key, - index, - name_buffer, - &buffer_size, - 0, - 0, - 0, - 0); - if (rc == ERROR_NO_MORE_ITEMS) - return 1; - else if (rc != ERROR_MORE_DATA && rc != ERROR_SUCCESS) - { - errno = rc; - return -1; - } - - name = name_buffer; - - return 0; -} - -int -ACE_Configuration_Win32Registry::set_string_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - const ACE_TString& value) -{ - const ACE_TCHAR *t_name = temp_name (name); - if (validate_value_name (t_name)) - return -1; - - HKEY base_key; - if (load_key (key, base_key)) - return -1; - - int errnum; - DWORD len = static_cast (value.length () + 1); - len *= sizeof (ACE_TCHAR); - if ((errnum = ACE_TEXT_RegSetValueEx (base_key, - t_name, - 0, - REG_SZ, - (BYTE *) value.fast_rep (), - len)) - != ERROR_SUCCESS) - { - errno = errnum; - return -1; - } - - return 0; -} - -int -ACE_Configuration_Win32Registry::set_integer_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - u_int value) -{ - const ACE_TCHAR *t_name = temp_name (name); - if (validate_value_name (t_name)) - return -1; - - HKEY base_key; - if (load_key (key, base_key)) - return -1; - - int errnum; - if ((errnum = ACE_TEXT_RegSetValueEx (base_key, - t_name, - 0, - REG_DWORD, - (BYTE *) &value, - sizeof (value))) != ERROR_SUCCESS) - { - errno = errnum; - return -1; - } - - return 0; -} - -int -ACE_Configuration_Win32Registry::set_binary_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - const void* data, - size_t length) -{ - const ACE_TCHAR *t_name = temp_name (name); - if (validate_value_name (t_name)) - return -1; - - HKEY base_key; - if (load_key (key, base_key)) - return -1; - - int errnum; - if ((errnum = ACE_TEXT_RegSetValueEx (base_key, - t_name, - 0, - REG_BINARY, - (BYTE *) data, - static_cast (length))) - != ERROR_SUCCESS) - { - errno = errnum; - return -1; - } - - return 0; -} - -int -ACE_Configuration_Win32Registry::get_string_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - ACE_TString& value) -{ - const ACE_TCHAR *t_name = temp_name (name); - if (validate_value_name (t_name)) - return -1; - - HKEY base_key; - if (load_key (key, base_key)) - return -1; - - // Get the size of the binary data from windows - int errnum; - DWORD buffer_length = 0; - DWORD type; - if ((errnum = ACE_TEXT_RegQueryValueEx (base_key, - t_name, - 0, - &type, - (BYTE *) 0, - &buffer_length)) != ERROR_SUCCESS) - { - errno = errnum; - return -1; - } - - if (type != REG_SZ) - { - errno = ERROR_INVALID_DATATYPE; - return -1; - } - - ACE_TCHAR *temp = 0; - ACE_NEW_RETURN (temp, - ACE_TCHAR[buffer_length], - -1); - - ACE_Auto_Basic_Array_Ptr buffer (temp); - - if ((errnum = ACE_TEXT_RegQueryValueEx (base_key, - t_name, - 0, - &type, - (BYTE *) buffer.get (), - &buffer_length)) != ERROR_SUCCESS) - { - errno = errnum; - return -1; - } - - value = buffer.get (); - return 0; -} - -int -ACE_Configuration_Win32Registry::get_integer_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - u_int& value) -{ - const ACE_TCHAR *t_name = temp_name (name); - if (validate_value_name (t_name)) - return -1; - - HKEY base_key; - if (load_key (key, base_key)) - return -1; - - int errnum; - DWORD length = sizeof (value); - DWORD type; - if ((errnum = ACE_TEXT_RegQueryValueEx (base_key, - t_name, - 0, - &type, - (BYTE *) &value, - &length)) != ERROR_SUCCESS) - { - errno = errnum; - return -1; - } - - if (type != REG_DWORD) - { - errno = ERROR_INVALID_DATATYPE; - return -1; - } - - return 0; -} - -int -ACE_Configuration_Win32Registry::get_binary_value ( - const ACE_Configuration_Section_Key &key, - const ACE_TCHAR *name, - void *&data, - size_t &length) -{ - const ACE_TCHAR *t_name = temp_name (name); - if (validate_value_name (t_name)) - return -1; - - HKEY base_key; - if (load_key (key, base_key)) - return -1; - - // Get the size of the binary data from windows - int errnum; - DWORD buffer_length = 0; - DWORD type; - if ((errnum = ACE_TEXT_RegQueryValueEx (base_key, - t_name, - 0, - &type, - (BYTE *) 0, - &buffer_length)) != ERROR_SUCCESS) - { - errno = errnum; - return -1; - } - - if (type != REG_BINARY) - { - errno = ERROR_INVALID_DATATYPE; - return -1; - } - - length = buffer_length; - - BYTE * the_data = 0; - ACE_NEW_RETURN (the_data, BYTE[length], -1); - ACE_Auto_Basic_Array_Ptr safe_data (the_data); - - if ((errnum = ACE_TEXT_RegQueryValueEx (base_key, - t_name, - 0, - &type, - the_data, - &buffer_length)) != ERROR_SUCCESS) - { - data = 0; - errno = errnum; - return -1; - } - - data = safe_data.release (); - - return 0; -} - -int -ACE_Configuration_Win32Registry::find_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - VALUETYPE& type_out) -{ - const ACE_TCHAR *t_name = temp_name (name); - if (validate_value_name (t_name)) - return -1; - - HKEY base_key; - if (load_key (key, base_key)) - return -1; - - DWORD buffer_length=0; - DWORD type; - int result=ACE_TEXT_RegQueryValueEx (base_key, - t_name, - 0, - &type, - 0, - &buffer_length); - if (result != ERROR_SUCCESS) - { - errno = result; - return -1; - } - - switch (type) - { - case REG_SZ: - type_out = STRING; - break; - case REG_DWORD: - type_out = INTEGER; - break; - case REG_BINARY: - type_out = BINARY; - break; - default: - return -1; // unknown type - } - - return 0; -} - -int -ACE_Configuration_Win32Registry::remove_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name) -{ - const ACE_TCHAR *t_name = temp_name (name); - if (validate_value_name (t_name)) - return -1; - - HKEY base_key; - if (load_key (key, base_key)) - return -1; - - int errnum; - if ((errnum = ACE_TEXT_RegDeleteValue (base_key, t_name)) != ERROR_SUCCESS) - { - errno = errnum; - return -1; - } - - return 0; -} - - -int -ACE_Configuration_Win32Registry::load_key (const ACE_Configuration_Section_Key& key, - HKEY& hKey) -{ - ACE_Section_Key_Win32* pKey = dynamic_cast (get_internal_key (key)); - if (!pKey) - return -1; - - hKey = pKey->hKey_; - return 0; -} - -HKEY -ACE_Configuration_Win32Registry::resolve_key (HKEY hKey, - const ACE_TCHAR* path, - int create) -{ - HKEY result = 0; - // Make a copy of hKey - int errnum; -#if defined (ACE_HAS_WINCE) - if ((errnum = RegOpenKeyEx (hKey, 0, 0, 0, &result)) != ERROR_SUCCESS) -#else - if ((errnum = RegOpenKey (hKey, 0, &result)) != ERROR_SUCCESS) -#endif // ACE_HAS_WINCE - { - errno = errnum; - return 0; - } - - // recurse through the path - ACE_TCHAR *temp_path = 0; - ACE_NEW_RETURN (temp_path, - ACE_TCHAR[ACE_OS::strlen (path) + 1], - 0); - ACE_Auto_Basic_Array_Ptr pData (temp_path); - ACE_OS::strcpy (pData.get (), path); - ACE_Tokenizer parser (pData.get ()); - parser.delimiter_replace ('\\', '\0'); - parser.delimiter_replace ('/', '\0'); - - for (ACE_TCHAR *temp = parser.next (); - temp != 0; - temp = parser.next ()) - { - // Open the key - HKEY subkey; - -#if defined (ACE_HAS_WINCE) - if ((errnum = ACE_TEXT_RegOpenKeyEx (result, - temp, - 0, - 0, - &subkey)) != ERROR_SUCCESS) -#else - if ((errnum = ACE_TEXT_RegOpenKey (result, - temp, - &subkey)) != ERROR_SUCCESS) -#endif // ACE_HAS_WINCE - { - // try creating it - if (!create || (errnum = ACE_TEXT_RegCreateKeyEx (result, - temp, - 0, - 0, - 0, - KEY_ALL_ACCESS, - 0, - &subkey, - (PDWORD) 0 - )) !=ERROR_SUCCESS) - { - errno = errnum; - // error - ::RegCloseKey (result); - return 0; - } - } - // release our open key handle - ::RegCloseKey (result); - result = subkey; - } - - return result; -} - -#endif /* ACE_WIN32 && !ACE_LACKS_WIN32_REGISTRY */ - -/////////////////////////////////////////////////////////////// - -ACE_Configuration_Value_IntId::ACE_Configuration_Value_IntId (void) - : type_ (ACE_Configuration::INVALID), - length_ (0) -{ - this->data_.ptr_ = 0; -} - -ACE_Configuration_Value_IntId::ACE_Configuration_Value_IntId (ACE_TCHAR* string) - : type_ (ACE_Configuration::STRING), - length_ (0) -{ - this->data_.ptr_ = string; -} - -ACE_Configuration_Value_IntId::ACE_Configuration_Value_IntId (u_int integer) - : type_ (ACE_Configuration::INTEGER), - length_ (0) -{ - this->data_.int_ = integer; -} - -ACE_Configuration_Value_IntId::ACE_Configuration_Value_IntId (void* data, size_t length) - : type_ (ACE_Configuration::BINARY), - length_ (length) -{ - this->data_.ptr_ = data; -} - -ACE_Configuration_Value_IntId::ACE_Configuration_Value_IntId (const ACE_Configuration_Value_IntId& rhs) - : type_ (rhs.type_), - data_ (rhs.data_), - length_ (rhs.length_) -{ -} - -ACE_Configuration_Value_IntId::~ACE_Configuration_Value_IntId (void) -{ -} - -ACE_Configuration_Value_IntId& ACE_Configuration_Value_IntId::operator= (const ACE_Configuration_Value_IntId& rhs) -{ - if (this != &rhs) - { - type_ = rhs.type_; - data_ = rhs.data_; - length_ = rhs.length_; - } - return *this; -} - -void -ACE_Configuration_Value_IntId::free (ACE_Allocator *alloc) -{ - if (this->type_ == ACE_Configuration::STRING - || this->type_ == ACE_Configuration::BINARY) - alloc->free (data_.ptr_); - // Do nothing in other cases... -} - -ACE_Configuration_ExtId::ACE_Configuration_ExtId (void) - : name_ (0) -{ -} - -ACE_Configuration_ExtId::ACE_Configuration_ExtId (const ACE_TCHAR* name) - : name_ (name) -{ -} - -ACE_Configuration_ExtId::ACE_Configuration_ExtId (const ACE_Configuration_ExtId& rhs) - : name_ (rhs.name_) -{ -} - -ACE_Configuration_ExtId::~ACE_Configuration_ExtId (void) -{ -} - -ACE_Configuration_ExtId& ACE_Configuration_ExtId::operator= (const ACE_Configuration_ExtId& rhs) -{ - if (this != &rhs) - name_ = rhs.name_; - - return *this; -} - -bool -ACE_Configuration_ExtId::operator== (const ACE_Configuration_ExtId& rhs) const -{ - return (ACE_OS::strcasecmp (name_, rhs.name_) == 0); -} - -bool -ACE_Configuration_ExtId::operator!= (const ACE_Configuration_ExtId& rhs) const -{ - return !this->operator== (rhs); -} - -u_long -ACE_Configuration_ExtId::hash (void) const -{ - ACE_TString temp (name_, 0, false); - return temp.hash (); -} - -void -ACE_Configuration_ExtId::free (ACE_Allocator *alloc) -{ - alloc->free ((void *) (name_)); -} - -/////////////////////////////////////////////////////////////////////// - -ACE_Configuration_Section_IntId::ACE_Configuration_Section_IntId (void) - : value_hash_map_ (0), - section_hash_map_ (0) -{ -} - -ACE_Configuration_Section_IntId::ACE_Configuration_Section_IntId (VALUE_MAP* value_hash_map, SUBSECTION_MAP* section_hash_map) - : value_hash_map_ (value_hash_map), - section_hash_map_ (section_hash_map) -{ -} - -ACE_Configuration_Section_IntId::ACE_Configuration_Section_IntId (const ACE_Configuration_Section_IntId& rhs) - : value_hash_map_ (rhs.value_hash_map_), - section_hash_map_ (rhs.section_hash_map_) -{ - -} - -ACE_Configuration_Section_IntId::~ACE_Configuration_Section_IntId () -{ -} - -ACE_Configuration_Section_IntId& -ACE_Configuration_Section_IntId::operator= (const ACE_Configuration_Section_IntId& rhs) -{ - if (this != &rhs) - { - value_hash_map_ = rhs.value_hash_map_; - section_hash_map_ = rhs.section_hash_map_; - } - return *this; -} - -void -ACE_Configuration_Section_IntId::free (ACE_Allocator *alloc) -{ - alloc->free ((void *) (value_hash_map_)); - alloc->free ((void *) (section_hash_map_)); -} - -ACE_Configuration_Section_Key_Heap::ACE_Configuration_Section_Key_Heap (const ACE_TCHAR* path) - : path_ (0), - value_iter_ (0), - section_iter_ (0) -{ - path_ = ACE_OS::strdup (path); -} - -ACE_Configuration_Section_Key_Heap::~ACE_Configuration_Section_Key_Heap () -{ - delete value_iter_; - delete section_iter_; - ACE_OS::free (path_); -} - -////////////////////////////////////////////////////////////////////////////// - -ACE_Configuration_Heap::ACE_Configuration_Heap (void) - : allocator_ (0), - index_ (0), - default_map_size_ (0) -{ - ACE_Configuration_Section_Key_Heap *temp = 0; - - ACE_NEW (temp, ACE_Configuration_Section_Key_Heap (ACE_TEXT (""))); - root_ = ACE_Configuration_Section_Key (temp); -} - -ACE_Configuration_Heap::~ACE_Configuration_Heap (void) -{ - if (allocator_) - allocator_->sync (); - - delete allocator_; -} - -int -ACE_Configuration_Heap::open (size_t default_map_size) -{ - if (this->allocator_ != 0) - { - errno = EBUSY; - return -1; - } - - default_map_size_ = default_map_size; - // Create the allocator with the appropriate options. - // The name used for the lock is the same as one used - // for the file. - ACE_NEW_RETURN (this->allocator_, - HEAP_ALLOCATOR (), - -1); - return create_index (); -} - - -int -ACE_Configuration_Heap::open (const ACE_TCHAR* file_name, - void* base_address, - size_t default_map_size) -{ - if (this->allocator_ != 0) - { - errno = EBUSY; - return -1; - } - - default_map_size_ = default_map_size; - - // Make sure that the file name is of the legal length. - if (ACE_OS::strlen (file_name) >= MAXNAMELEN + MAXPATHLEN) - { - errno = ENAMETOOLONG; - return -1; - } - - ACE_MMAP_Memory_Pool::OPTIONS options (base_address); - - // Create the allocator with the appropriate options. The name used - // for the lock is the same as one used for the file. - ACE_NEW_RETURN (this->allocator_, - PERSISTENT_ALLOCATOR (file_name, - file_name, - &options), - -1); - -#if !defined (ACE_LACKS_ACCESS) - // Now check if the backing store has been created successfully. - if (ACE_OS::access (file_name, F_OK) != 0) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("create_index\n")), - -1); -#endif /* ACE_LACKS_ACCESS */ - - return create_index (); -} - -int -ACE_Configuration_Heap::create_index (void) -{ - void *section_index = 0; - - // This is the easy case since if we find hash table in the - // memory-mapped file we know it's already initialized. - if (this->allocator_->find (ACE_CONFIG_SECTION_INDEX, section_index) == 0) - this->index_ = (SECTION_MAP *) section_index; - - // Create a new (because we've just created a new - // memory-mapped file). - else - { - size_t index_size = sizeof (SECTION_MAP); - section_index = this->allocator_->malloc (index_size); - - if (section_index == 0 - || create_index_helper (section_index) == -1 - || this->allocator_->bind (ACE_CONFIG_SECTION_INDEX, - section_index) == -1) - { - // Attempt to clean up. - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("create_index failed\n"))); - this->allocator_->remove (); - return -1; - } - // Add the root section - return new_section (ACE_TEXT (""), root_); - } - return 0; -} - -int -ACE_Configuration_Heap::create_index_helper (void *buffer) -{ - ACE_ASSERT (this->allocator_); - this->index_ = new (buffer) SECTION_MAP (this->allocator_); - return 0; -} - -int -ACE_Configuration_Heap::load_key (const ACE_Configuration_Section_Key& key, - ACE_TString& name) -{ - ACE_ASSERT (this->allocator_); - ACE_Configuration_Section_Key_Heap* pKey = - dynamic_cast (get_internal_key (key)); - - if (!pKey) - { - return -1; - } - - ACE_TString temp (pKey->path_, 0, false); - name.assign_nocopy (temp); - return 0; -} - - -int -ACE_Configuration_Heap::add_section (const ACE_Configuration_Section_Key& base, - const ACE_TCHAR* sub_section, - ACE_Configuration_Section_Key& result) -{ - ACE_ASSERT (this->allocator_); - ACE_TString section; - if (load_key (base, section)) - return -1; - - // Find the base section - ACE_Configuration_ExtId ExtId (section.fast_rep ()); - ACE_Configuration_Section_IntId IntId; - if (index_->find (ExtId, IntId, allocator_)) - return -1; - - // See if this section already exists - ACE_Configuration_ExtId SubSectionExtId (sub_section); - int ignored = 0; - - if (!IntId.section_hash_map_->find (SubSectionExtId, ignored, allocator_)) - { - // already exists! - errno = EEXIST; - return -1; - } - - // Create the new section name - // only prepend a separater if were not at the root - if (section.length ()) - section += ACE_TEXT ("\\"); - - section += sub_section; - - // Add it to the base section - ACE_TCHAR* pers_name = (ACE_TCHAR *) allocator_->malloc ((ACE_OS::strlen (sub_section) + 1) * sizeof (ACE_TCHAR)); - ACE_OS::strcpy (pers_name, sub_section); - ACE_Configuration_ExtId SSExtId (pers_name); - if (IntId.section_hash_map_->bind (SSExtId, ignored, allocator_)) - { - allocator_->free (pers_name); - return -1; - } - return (new_section (section, result)); -} - -int -ACE_Configuration_Heap::new_section (const ACE_TString& section, - ACE_Configuration_Section_Key& result) -{ - ACE_ASSERT (this->allocator_); - // Create a new section and add it to the global list - - // Allocate memory for items to be stored in the table. - size_t section_len = section.length () + 1; - ACE_TCHAR *ptr = (ACE_TCHAR*) this->allocator_->malloc (section_len * sizeof (ACE_TCHAR)); - - int return_value = -1; - - if (ptr == 0) - return -1; - else - { - // Populate memory with data. - ACE_OS::strcpy (ptr, section.fast_rep ()); - - void *value_hash_map = 0; - size_t map_size = sizeof (VALUE_MAP); - value_hash_map = this->allocator_->malloc (map_size); - - // If allocation failed ... - if (value_hash_map == 0) - return -1; - - // Initialize allocated hash map through placement new. - if (value_open_helper (default_map_size_, value_hash_map ) == -1) - { - this->allocator_->free (value_hash_map ); - return -1; - } - - // create the section map - void* section_hash_map = 0; - map_size = sizeof (SUBSECTION_MAP); - section_hash_map = this->allocator_->malloc (map_size); - - // If allocation failed - if (section_hash_map == 0) - return -1; - - // initialize allocated hash map through placement new - if (section_open_helper (default_map_size_, section_hash_map) == -1) - { - this->allocator_->free (value_hash_map ); - this->allocator_->free (section_hash_map); - return -1; - } - - ACE_Configuration_ExtId name (ptr); - ACE_Configuration_Section_IntId entry ((VALUE_MAP*) value_hash_map, - (SUBSECTION_MAP*) section_hash_map); - - // Do a normal bind. This will fail if there's already an - // entry with the same name. - return_value = this->index_->bind (name, entry, this->allocator_); - - if (return_value == 1 /* Entry already existed so bind failed. */ - || return_value == -1 /* Unable to bind for other reasons. */) - { - // Free our dynamically allocated memory. - this->allocator_->free (static_cast (ptr)); - return return_value; - } - - // If bind () succeed, it will automatically sync - // up the map manager entry. However, we must sync up our - // name/value memory. - this->allocator_->sync (ptr, section_len); - } - - // set the result - ACE_Configuration_Section_Key_Heap *temp; - ACE_NEW_RETURN (temp, - ACE_Configuration_Section_Key_Heap (ptr), - -1); - result = ACE_Configuration_Section_Key (temp); - return return_value; -} - -int -ACE_Configuration_Heap::value_open_helper (size_t hash_table_size, - void *buffer) -{ - ACE_ASSERT (this->allocator_); - new (buffer) VALUE_MAP (hash_table_size, this->allocator_); - return 0; -} - -int -ACE_Configuration_Heap::section_open_helper (size_t hash_table_size, - void *buffer) -{ - ACE_ASSERT (this->allocator_); - new (buffer) SUBSECTION_MAP (hash_table_size, this->allocator_); - return 0; -} - -int -ACE_Configuration_Heap::open_section (const ACE_Configuration_Section_Key& base, - const ACE_TCHAR* sub_section, - int create, - ACE_Configuration_Section_Key& result) -{ - ACE_ASSERT (this->allocator_); - if (validate_name (sub_section, 1)) // 1 == allow_path - return -1; - - result = base; - - for (const ACE_TCHAR* separator; - (separator = ACE_OS::strchr (sub_section, ACE_TEXT ('\\'))) != 0; - ) - { - ACE_TString simple_section (sub_section, separator - sub_section); - int ret_val = - open_simple_section (result, simple_section.c_str (), create, result); - if (ret_val) - return ret_val; - sub_section = separator + 1; - } - - return open_simple_section (result, sub_section, create, result); -} - -int -ACE_Configuration_Heap::open_simple_section (const ACE_Configuration_Section_Key& base, - const ACE_TCHAR* sub_section, - int create, - ACE_Configuration_Section_Key& result) -{ - ACE_TString section (0, 0, false); - - if (load_key (base, section)) - { - return -1; - } - - // Only add the \\ if were not at the root - if (section.length ()) - { - section += ACE_TEXT ("\\"); - } - - section += sub_section; - - // resolve the section - ACE_Configuration_ExtId ExtId (section.fast_rep ()); - ACE_Configuration_Section_IntId IntId; - - if (index_->find (ExtId, IntId, allocator_)) - { - if (!create) - { - errno = ENOENT; - return -1; - } - - return add_section (base, sub_section, result); - } - - ACE_Configuration_Section_Key_Heap *temp; - ACE_NEW_RETURN (temp, - ACE_Configuration_Section_Key_Heap (section.fast_rep ()), - -1); - result = ACE_Configuration_Section_Key (temp); - return 0; -} - -int -ACE_Configuration_Heap::remove_section (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* sub_section, - bool recursive) -{ - ACE_ASSERT (this->allocator_); - if (validate_name (sub_section)) - return -1; - - ACE_TString section; - if (load_key (key, section)) - return -1; - - // Find this key - ACE_Configuration_ExtId ParentExtId (section.fast_rep ()); - ACE_Configuration_Section_IntId ParentIntId; - if (index_->find (ParentExtId, ParentIntId, allocator_)) - return -1;// no parent key - - // Find this subkey - if (section.length ()) - section += ACE_TEXT ("\\"); - - section += sub_section; - ACE_Configuration_ExtId SectionExtId (section.fast_rep ()); - SECTION_HASH::ENTRY* section_entry = 0; - SECTION_HASH* hashmap = index_; - if (hashmap->find (SectionExtId, section_entry)) - return -1; - - if (recursive) - { - ACE_Configuration_Section_Key section; - if (open_section (key, sub_section, 0, section)) - return -1; - - int index = 0; - ACE_TString name; - while (!enumerate_sections (section, index, name)) - { - if (remove_section (section, name.fast_rep (), true)) - return -1; - - ++index; - } - } - - // Now make sure we dont have any subkeys - if (section_entry->int_id_.section_hash_map_->current_size ()) - { - errno = ENOTEMPTY; - return -1; - } - - // Now remove subkey from parent key - ACE_Configuration_ExtId SubSExtId (sub_section); - SUBSECTION_HASH::ENTRY* subsection_entry; - if (((SUBSECTION_HASH*)ParentIntId.section_hash_map_)-> - find (SubSExtId, subsection_entry)) - return -1; - - if (ParentIntId.section_hash_map_->unbind (SubSExtId, allocator_)) - return -1; - - subsection_entry->ext_id_.free (allocator_); - - // Remember the pointers so we can free them after we unbind - ACE_Configuration_ExtId ExtIdToFree (section_entry->ext_id_); - ACE_Configuration_Section_IntId IntIdToFree (section_entry->int_id_); - - // iterate over all values and free memory - VALUE_HASH* value_hash_map = section_entry->int_id_.value_hash_map_; - VALUE_HASH::ITERATOR value_iter = value_hash_map->begin (); - while (!value_iter.done ()) - { - VALUE_HASH::ENTRY* value_entry = 0; - if (!value_iter.next (value_entry)) - return 1; - - value_entry->ext_id_.free (allocator_); - value_entry->int_id_.free (allocator_); - - value_iter.advance (); - } - - // remove it - if (index_->unbind (SectionExtId, allocator_)) - return -1; - - value_hash_map->close (); - section_entry->int_id_.section_hash_map_->close (allocator_); - - // Free the memory - ExtIdToFree.free (allocator_); - IntIdToFree.free (allocator_); - - return 0; -} - -int -ACE_Configuration_Heap::enumerate_values (const ACE_Configuration_Section_Key& key, - int index, - ACE_TString& name, - VALUETYPE& type) -{ - ACE_ASSERT (this->allocator_); - ACE_Configuration_Section_Key_Heap* pKey = - dynamic_cast (get_internal_key (key)); - if (!pKey) - return -1; - - name = pKey->path_; - - // resolve the section - ACE_Configuration_ExtId ExtId (pKey->path_); - ACE_Configuration_Section_IntId IntId; - if (index_->find (ExtId, IntId, allocator_)) - return -1; - - // Handle iterator resets - if (index == 0) - { - ACE_Hash_Map_Manager_Ex, - ACE_Equal_To, - ACE_Null_Mutex>* hash_map = IntId.value_hash_map_; - delete pKey->value_iter_; - - ACE_NEW_RETURN (pKey->value_iter_, - VALUE_HASH::ITERATOR (hash_map->begin ()), - -1); - } - - // Get the next entry - ACE_Hash_Map_Entry* entry = 0; - - if (!pKey->value_iter_->next (entry)) - return 1; - - // Return the value of the iterator and advance it - name = entry->ext_id_.name_; - type = entry->int_id_.type_; - pKey->value_iter_->advance (); - - return 0; -} - -int -ACE_Configuration_Heap::enumerate_sections (const ACE_Configuration_Section_Key& key, - int index, - ACE_TString& name) -{ - ACE_ASSERT (this->allocator_); - // cast to a heap section key - ACE_Configuration_Section_Key_Heap* pKey = - dynamic_cast (get_internal_key (key)); - if (!pKey) - return -1; // not a heap key! - - // resolve the section - ACE_Configuration_ExtId ExtId (pKey->path_); - ACE_Configuration_Section_IntId IntId; - if (index_->find (ExtId, IntId, allocator_)) - return -1; // unknown section - - // Handle iterator resets - if (index == 0) - { - if (pKey->section_iter_) - delete pKey->section_iter_; - - ACE_NEW_RETURN (pKey->section_iter_, - SUBSECTION_HASH::ITERATOR (IntId.section_hash_map_->begin ()), - -1); - } - - // Get the next entry - ACE_Hash_Map_Entry* entry = 0; - if (!pKey->section_iter_->next (entry)) - return 1; - - // Return the value of the iterator and advance it - pKey->section_iter_->advance (); - name = entry->ext_id_.name_; - - return 0; -} - -int -ACE_Configuration_Heap::set_string_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - const ACE_TString& value) -{ - ACE_ASSERT (this->allocator_); - const ACE_TCHAR *t_name = name ? name : &this->NULL_String_; - if (validate_value_name (t_name)) - return -1; - - ACE_TString section; - if (load_key (key, section)) - return -1; - - ACE_Configuration_ExtId section_ext (section.fast_rep ()); - ACE_Configuration_Section_IntId section_int; - if (index_->find (section_ext, section_int, allocator_)) - return -1; - - // Get the entry for this item (if it exists) - VALUE_HASH::ENTRY* entry = 0; - ACE_Configuration_ExtId item_name (t_name); - if (section_int.value_hash_map_->VALUE_HASH::find (item_name, entry) == 0) - { - // found item, replace it - // Free the old value - entry->int_id_.free (allocator_); - // Allocate the new value in this heap - ACE_TCHAR* pers_value = - (ACE_TCHAR *) allocator_->malloc ((value.length () + 1) * sizeof (ACE_TCHAR)); - ACE_OS::strcpy (pers_value, value.fast_rep ()); - ACE_Configuration_Value_IntId new_value_int (pers_value); - entry->int_id_ = new_value_int; - } - else - { - // it doesn't exist, bind it - ACE_TCHAR* pers_name = - (ACE_TCHAR *) allocator_->malloc ((ACE_OS::strlen (t_name) + 1) * sizeof (ACE_TCHAR)); - ACE_OS::strcpy (pers_name, t_name); - ACE_TCHAR* pers_value = - (ACE_TCHAR *) allocator_->malloc ((value.length () + 1) * sizeof (ACE_TCHAR)); - ACE_OS::strcpy (pers_value, value.fast_rep ()); - ACE_Configuration_ExtId item_name (pers_name); - ACE_Configuration_Value_IntId item_value (pers_value); - if (section_int.value_hash_map_->bind (item_name, item_value, allocator_)) - { - allocator_->free (pers_value); - allocator_->free (pers_name); - return -1; - } - return 0; - } - - return 0; -} - -int -ACE_Configuration_Heap::set_integer_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - u_int value) -{ - ACE_ASSERT (this->allocator_); - const ACE_TCHAR *t_name = name ? name : &this->NULL_String_; - if (validate_value_name (t_name)) - return -1; - - // Get the section name from the key - ACE_TString section; - if (load_key (key, section)) - return -1; - - // Find this section - ACE_Configuration_ExtId section_ext (section.fast_rep ()); - ACE_Configuration_Section_IntId section_int; - if (index_->find (section_ext, section_int, allocator_)) - return -1; // section does not exist - - // Get the entry for this item (if it exists) - VALUE_HASH::ENTRY* entry = 0; - ACE_Configuration_ExtId item_name (t_name); - if (section_int.value_hash_map_->VALUE_HASH::find (item_name, entry) == 0) - { - // found item, replace it - ACE_Configuration_Value_IntId new_value_int (value); - entry->int_id_ = new_value_int; - } - else - { - // it doesn't exist, bind it - ACE_TCHAR* pers_name = - (ACE_TCHAR *) allocator_->malloc ((ACE_OS::strlen (t_name) + 1) * sizeof (ACE_TCHAR)); - ACE_OS::strcpy (pers_name, t_name); - ACE_Configuration_ExtId item_name (pers_name); - ACE_Configuration_Value_IntId item_value (value); - if (section_int.value_hash_map_->bind (item_name, item_value, allocator_)) - { - allocator_->free (pers_name); - return -1; - } - return 0; - } - - return 0; -} - -int -ACE_Configuration_Heap::set_binary_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - const void* data, - size_t length) -{ - ACE_ASSERT (this->allocator_); - const ACE_TCHAR *t_name = name ? name : &this->NULL_String_; - if (validate_value_name (t_name)) - return -1; - - // Get the section name from the key - ACE_TString section; - if (load_key (key, section)) - return -1; - - // Find this section - ACE_Configuration_ExtId section_ext (section.fast_rep ()); - ACE_Configuration_Section_IntId section_int; - if (index_->find (section_ext, section_int, allocator_)) - return -1; // section does not exist - - // Get the entry for this item (if it exists) - VALUE_HASH::ENTRY* entry = 0; - ACE_Configuration_ExtId item_name (t_name); - if (section_int.value_hash_map_->VALUE_HASH::find (item_name, entry) == 0) - { - // found item, replace it - // Free the old value - entry->int_id_.free (allocator_); - // Allocate the new value in this heap - ACE_TCHAR* pers_value = (ACE_TCHAR *) allocator_->malloc (length); - ACE_OS::memcpy (pers_value, data, length); - ACE_Configuration_Value_IntId new_value_int (pers_value, length); - entry->int_id_ = new_value_int; - } - else - { - // it doesn't exist, bind it - ACE_TCHAR* pers_name = - (ACE_TCHAR *) allocator_->malloc ((ACE_OS::strlen (t_name) + 1) * sizeof (ACE_TCHAR)); - ACE_OS::strcpy (pers_name, t_name); - ACE_TCHAR* pers_value = (ACE_TCHAR *) allocator_->malloc (length); - ACE_OS::memcpy (pers_value, data, length); - ACE_Configuration_ExtId item_name (pers_name); - ACE_Configuration_Value_IntId item_value (pers_value, length); - if (section_int.value_hash_map_->bind (item_name, item_value, allocator_)) - { - allocator_->free (pers_value); - allocator_->free (pers_name); - return -1; - } - return 0; - } - - return 0; -} - -int -ACE_Configuration_Heap::get_string_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - ACE_TString& value) -{ - ACE_ASSERT (this->allocator_); - const ACE_TCHAR *t_name = name ? name : &this->NULL_String_; - if (validate_value_name (t_name)) - return -1; - - // Get the section name from the key - ACE_TString section; - if (load_key (key, section)) - return -1; - - // Find this section - ACE_Configuration_ExtId ExtId (section.fast_rep ()); - ACE_Configuration_Section_IntId IntId; - if (index_->find (ExtId, IntId, allocator_)) - return -1; // section does not exist - - // See if it exists first - ACE_Configuration_ExtId VExtId (t_name); - ACE_Configuration_Value_IntId VIntId; - if (IntId.value_hash_map_->find (VExtId, VIntId, allocator_)) - return -1; // unknown value - - // Check type - if (VIntId.type_ != ACE_Configuration::STRING) - { - errno = ENOENT; - return -1; - } - - // everythings ok, return the data - value = static_cast (VIntId.data_.ptr_); - return 0; -} - -int -ACE_Configuration_Heap::get_integer_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - u_int& value) -{ - ACE_ASSERT (this->allocator_); - - const ACE_TCHAR *t_name = name ? name : &this->NULL_String_; - if (validate_value_name (t_name)) - return -1; - - // Get the section name from the key - ACE_TString section (0, 0, false); - - if (this->load_key (key, section) != 0) - { - return -1; - } - - // Find this section - ACE_Configuration_ExtId ExtId (section.fast_rep ()); - ACE_Configuration_Section_IntId IntId; - - if (index_->find (ExtId, IntId, allocator_) != 0) - { - return -1; // section does not exist - } - - - // See if it exists first - ACE_Configuration_ExtId VExtId (t_name); - ACE_Configuration_Value_IntId VIntId; - - if (IntId.value_hash_map_->find (VExtId, VIntId, allocator_) != 0) - { - return -1; // unknown value - } - - // Check type - if (VIntId.type_ != ACE_Configuration::INTEGER) - { - errno = ENOENT; - return -1; - } - - // Everythings ok, return the data - value = VIntId.data_.int_; - return 0; -} - -int -ACE_Configuration_Heap::get_binary_value ( - const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - void*& data, - size_t& length) -{ - ACE_ASSERT (this->allocator_); - const ACE_TCHAR *t_name = name ? name : &this->NULL_String_; - if (validate_value_name (t_name)) - return -1; - - // Get the section name from the key - ACE_TString section; - if (load_key (key, section)) - return -1; - - // Find this section - ACE_Configuration_ExtId ExtId (section.fast_rep ()); - ACE_Configuration_Section_IntId IntId; - if (index_->find (ExtId, IntId, allocator_)) - return -1; // section does not exist - - ACE_Configuration_ExtId VExtId (t_name); - ACE_Configuration_Value_IntId VIntId; - // See if it exists first - if (IntId.value_hash_map_->find (VExtId, VIntId, allocator_)) - return -1; // unknown value - - // Check type - if (VIntId.type_ != ACE_Configuration::BINARY) - { - errno = ENOENT; - return -1; - } - - // Make a copy - ACE_NEW_RETURN (data, char[VIntId.length_], -1); - ACE_OS::memcpy (data, VIntId.data_.ptr_, VIntId.length_); - length = VIntId.length_; - return 0; -} - -int -ACE_Configuration_Heap::find_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - VALUETYPE& type_out) -{ - ACE_ASSERT (this->allocator_); - const ACE_TCHAR *t_name = name ? name : &this->NULL_String_; - if (validate_value_name (t_name)) - return -1; - - // Get the section name from the key - ACE_TString section; - if (load_key (key, section)) - return -1; - - // Find this section - ACE_Configuration_ExtId ExtId (section.fast_rep ()); - ACE_Configuration_Section_IntId IntId; - if (index_->find (ExtId, IntId, allocator_)) - return -1; // section does not exist - - // Find it - ACE_Configuration_ExtId ValueExtId (t_name); - VALUE_HASH::ENTRY* value_entry = 0; - if (((VALUE_HASH *) IntId.value_hash_map_)->find (ValueExtId, value_entry)) - return -1; // value does not exist - - type_out = value_entry->int_id_.type_; - return 0; -} - -int -ACE_Configuration_Heap::remove_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name) -{ - ACE_ASSERT (this->allocator_); - const ACE_TCHAR *t_name = name ? name : &this->NULL_String_; - if (validate_value_name (t_name)) - return -1; - - // Get the section name from the key - ACE_TString section; - if (load_key (key, section)) - return -1; - - // Find this section - ACE_Configuration_ExtId ExtId (section.fast_rep ()); - ACE_Configuration_Section_IntId IntId; - if (index_->find (ExtId, IntId, allocator_)) - return -1; // section does not exist - - // Find it - ACE_Configuration_ExtId ValueExtId (t_name); - VALUE_HASH::ENTRY* value_entry = 0; - if (((VALUE_HASH *) IntId.value_hash_map_)->find (ValueExtId, value_entry)) - return -1; - - // free it - value_entry->ext_id_.free (allocator_); - value_entry->int_id_.free (allocator_); - - // Unbind it - if (IntId.value_hash_map_->unbind (ValueExtId, allocator_)) - return -1; - - return 0; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Configuration.h b/externals/ace/Configuration.h deleted file mode 100644 index 3543619017e..00000000000 --- a/externals/ace/Configuration.h +++ /dev/null @@ -1,919 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file Configuration.h - * - * $Id: Configuration.h 86348 2009-08-04 14:45:29Z shuston $ - * - * @author Chris Hafey - * - * The ACE configuration API provides a portable abstraction for - * program configuration similar to the Microsoft Windows registry. - * The API supports a tree based hierarchy of configuration sections. Each - * section contains other sections or values. Values may contain string, - * unsigned integer and binary data. - * - * @note These classes are not thread safe, if multiple threads use these - * classes, you are responsible for serializing access. - * - * For examples of using this class, see: - * -# The test code in ACE_wrappers/test - * -# wxConfigViewer, a Windows like Registry Editor for ACE_Configuration - * -# TAO's IFR, it makes extensive use of ACE_Configuration - * - * @todo Templatize this class with an ACE_LOCK to provide thread safety - */ -//============================================================================= - -#ifndef ACE_CONFIGURATION_H -#define ACE_CONFIGURATION_H -#include /**/ "ace/pre.h" - -#include "ace/SStringfwd.h" -#include "ace/Hash_Map_With_Allocator_T.h" -#include "ace/Malloc_T.h" -#include "ace/MMAP_Memory_Pool.h" -#include "ace/Local_Memory_Pool.h" -#include "ace/Synch_Traits.h" - - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -// configurable parameters - -#if !defined (ACE_CONFIG_SECTION_INDEX) -# define ACE_CONFIG_SECTION_INDEX "Config_Section_Index" -#endif /* ! ACE_CONFIG_SECTION_INDEX */ - -#if !defined (ACE_DEFAULT_CONFIG_SECTION_SIZE) -#define ACE_DEFAULT_CONFIG_SECTION_SIZE 16 -#endif /* ACE_DEFAULT_CONFIG_SECTION_SIZE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Section_Key_Internal - * - * @internal - * - * @brief A base class for internal handles to section keys for - * configuration implementations - * - * Implementations subclass this base class to represent a - * section key. - */ -class ACE_Export ACE_Section_Key_Internal -{ -public: - /// Virtual destructor, make sure descendants are virtual! - virtual ~ACE_Section_Key_Internal (void); - - /// Increment reference count - virtual int add_ref (void); - - /// Decrement reference count. Will delete this if count gets to 0 - virtual int dec_ref (void); -protected: - ACE_Section_Key_Internal (void); - ACE_Section_Key_Internal (const ACE_Section_Key_Internal& rhs); - ACE_Section_Key_Internal& operator= (ACE_Section_Key_Internal& rhs); - - u_int ref_count_; -}; - -/** - * @class ACE_Configuration_Section_Key - * - * @brief Reference counted wrapper for ACE_Section_Key_Internal. - * - * Reference counted wrapper class for the abstract internal - * section key. A user gets one of these to represent a section - * in the configuration database. - */ -class ACE_Export ACE_Configuration_Section_Key -{ - friend class ACE_Configuration; -public: - /// Default constructor. - ACE_Configuration_Section_Key (void); - - /// Constructor that initializes to a pointer to a concrete internal key. - /** - * @param key The section key to reference. Calls add_ref() with @a key. - */ - explicit ACE_Configuration_Section_Key (ACE_Section_Key_Internal *key); - - /// Copy constructor, increments the reference count on the key. - ACE_Configuration_Section_Key (const ACE_Configuration_Section_Key &rhs); - - /// Destructor, decrements reference count on the referenced key. - ~ACE_Configuration_Section_Key (void); - - /// Assignment operator, increments reference count for this object - /// and decrements it on @a rhs. - ACE_Configuration_Section_Key & - operator= (const ACE_Configuration_Section_Key &rhs); -private: - ACE_Section_Key_Internal *key_; -}; - -/** - * @class ACE_Configuration - * - * @internal - * - * @brief Base class for configuration databases - * - * This class provides an interface for configuration databases. A concrete - * class is required that implements the interface. - * - * @sa ACE_Configuration_Heap - * @sa ACE_Configuration_Win32Registry - */ -class ACE_Export ACE_Configuration -{ -public: - /// Enumeration for the various types of values we can store. - enum VALUETYPE - { - STRING, - INTEGER, - BINARY, - INVALID - }; - - /// Destructor - virtual ~ACE_Configuration (void); - - /// Obtain a reference to the root section of this configuration. - /* - * @return Reference to the configuration's root section. Note that - * it is a const reference. - */ - virtual const ACE_Configuration_Section_Key& root_section (void) const; - - /** - * Opens a named section in an existing section. - * - * @param base Existing section in which to open the named section. - * @param sub_section Name of the section to open. - * @param create If zero, the named section must exist. If non-zero, - * the named section will be created if it does not exist. - * @param result Reference; receives the section key for the new - * section. - * - * @retval 0 for success. - * @retval -1 for error; ACE_OS::last_error() retrieves error code. - */ - virtual int open_section (const ACE_Configuration_Section_Key &base, - const ACE_TCHAR *sub_section, - int create, - ACE_Configuration_Section_Key& result) = 0; - - /// Removes a named section. - /** - * @param key Section key to remove the named section from. - * @param sub_section Name of the section to remove. - * @param recursive If true, any subkeys below @a sub_section are - * removed as well. - * - * @retval 0 for success. - * @retval -1 for error; ACE_OS::last_error() retrieves error code. - */ - virtual int remove_section (const ACE_Configuration_Section_Key &key, - const ACE_TCHAR *sub_section, - bool recursive) = 0; - - /** - * Enumerates through the values in a section. - * - * @param key Section key to iterate through. - * @param index Iteration position. Must be zero on the first call to - * iterate through @a key. Increment @a index by one on each - * successive call to this method. - * @param name Receives the value's name. - * @param type Receives the value's data type. - * - * @note You may not delete or add values while enumerating. If the - * section is modified during enumeration, results are undefined; - * you must restart the enumeration from index 0. - * - * @retval 0 for success, @a name and @a type are valid. - * @retval 1 there are no more values in the section. - * @retval -1 for error; ACE_OS::last_error() retrieves error code. - */ - virtual int enumerate_values (const ACE_Configuration_Section_Key& key, - int index, - ACE_TString& name, - VALUETYPE& type) = 0; - - /** - * Enumerates through the subsections in a section. - * - * @param key Section key to iterate through. - * @param index Iteration position. Must be zero on the first call to - * iterate through @a key. Increment @a index by one on each - * successive call to this method. - * @param name Receives the subsection's name. - * - * @note You may not modify the @a key section while enumerating. If the - * section is modified during enumeration, results are undefined; - * you must restart the enumeration from index 0. - * - * @retval 0 for success, @a name has a valid name. - * @retval 1 there are no more subsections in the section. - * @retval -1 for error; ACE_OS::last_error() retrieves error code. - */ - virtual int enumerate_sections (const ACE_Configuration_Section_Key& key, - int index, ACE_TString& name) = 0; - - /// Sets a string-typed value. - /** - * @param key Configuration section to set the value in. - * @param name Name of the configuration value to set. If a value with - * the specified name exists, it is replaced. - * @param value The string to set the configuration value to. - * - * @retval 0 for success. - * @retval -1 for error; ACE_OS::last_error() retrieves error code. - */ - virtual int set_string_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - const ACE_TString& value) = 0; - - /// Sets a integer-typed value. - /** - * @param key Configuration section to set the value in. - * @param name Name of the configuration value to set. If a value with - * the specified name exists, it is replaced. - * @param value The integer to set the configuration value to. - * - * @retval 0 for success. - * @retval -1 for error; ACE_OS::last_error() retrieves error code. - */ - virtual int set_integer_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - u_int value) = 0; - - /// Sets a binary-typed value. - /** - * @param key Configuration section to set the value in. - * @param name Name of the configuration value to set. If a value with - * the specified name exists, it is replaced. - * @param data Pointer to the binary data for the value. - * @param length Number of bytes for the new value. - * - * @retval 0 for success. - * @retval -1 for error; ACE_OS::last_error() retrieves error code. - */ - virtual int set_binary_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - const void* data, - size_t length) = 0; - - /// Gets a string-typed value. - /** - * @param key Configuration section to get the value from. - * @param name Name of the configuration value to get. - * @param value Receives the configuration value if it exists and - * has type STRING. - * - * @retval 0 for success. - * @retval -1 for error; ACE_OS::last_error() retrieves error code. - */ - virtual int get_string_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - ACE_TString& value) = 0; - - /// Gets an integer-typed value. - /** - * @param key Configuration section to get the value from. - * @param name Name of the configuration value to get. - * @param value Receives the configuration value if it exists and - * has type INTEGER. - * - * @retval 0 for success. - * @retval -1 for error; ACE_OS::last_error() retrieves error code. - */ - virtual int get_integer_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - u_int& value) = 0; - - /// Gets a binary-typed value. - /** - * @param key Configuration section to get the value from. - * @param name Name of the configuration value to get. - * @param data Receives a pointer to memory holding the binary data - * for the value. This method allocates the memory pointed - * to using operator new[]. The caller is responsible for - * freeing the memory using operator delete[]. - * @param length Receives the number of bytes in the value. - * - * @retval 0 for success; caller is responsible for freeing the - * returned memory. - * @retval -1 for error; ACE_OS::last_error() retrieves error code. - */ - virtual int get_binary_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - void*& data, - size_t& length) = 0; - - /** - * Retrieves the type of a named configuration value. - * - * @param key Configuration section to look up the name in. - * @param name Name of the configuration value to get the type of. - * @param type Receives the data type of the named value, if it exists. - * - * @retval 0 for success. - * @retval -1 for error; ACE_OS::last_error() retrieves error code. - */ - virtual int find_value(const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - VALUETYPE& type) = 0; - - /// Removes a named value. - /** - * @param key Configuration section to remove the named value from. - * @param name Name of the configuration value to remove. - * - * @retval 0 for success. - * @retval -1 for error; ACE_OS::last_error() retrieves error code. - */ - virtual int remove_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name) = 0; - - /** - * Expands @a path_in to @a key_out from @a key. If create is true, - * the subsections are created. Returns 0 on success, non zero on - * error The path consists of sections separated by the backslash - * '\' or forward slash '/'. - * Returns 0 on success, -1 if - virtual ~ACE_Section_Key_Win32 (void); - - // Not used - ACE_Section_Key_Win32 (const ACE_Section_Key_Win32& rhs); - ACE_Section_Key_Win32& operator= (const ACE_Section_Key_Win32& rhs); -}; - -/** - * @class ACE_Configuration_Win32Registry - * - * @brief The win32 registry implementation of a configuration database - * - * The win32 implementation basically makes calls through to the - * registry functions. The API is very similar so very little - * work must be done - */ -class ACE_Export ACE_Configuration_Win32Registry : public ACE_Configuration -{ -public: - - /** - * Constructor for registry configuration database. hKey is the - * base registry key to attach to. This class takes ownership of - * hKey, it will invoke on it upon destruction. - */ - explicit ACE_Configuration_Win32Registry (HKEY hKey); - - /// Destructor - virtual ~ACE_Configuration_Win32Registry (void); - - virtual int open_section (const ACE_Configuration_Section_Key& base, - const ACE_TCHAR* sub_section, - int create, - ACE_Configuration_Section_Key& result); - - virtual int remove_section (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* sub_section, - bool recursive); - - virtual int enumerate_values (const ACE_Configuration_Section_Key& key, - int index, - ACE_TString& name, - VALUETYPE& type); - - virtual int enumerate_sections (const ACE_Configuration_Section_Key& key, - int index, - ACE_TString& name); - - virtual int set_string_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - const ACE_TString& value); - - virtual int set_integer_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - u_int value); - - virtual int set_binary_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - const void* data, - size_t length); - - virtual int get_string_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - ACE_TString& value); - - virtual int get_integer_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - u_int& value); - - virtual int get_binary_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - void*& data, - size_t& length); - - virtual int find_value(const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - VALUETYPE& type); - - /// Removes the the value @a name from @a key. returns non zero on error - virtual int remove_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name); - - /** - * This method traverses through . It is useful when - * you want the HKEY for a specific registry key, especially when - * initializing this implementation. Caller is responsible for - * closeing this key when it is no longer used. If create is 1 - * (default) the keys are create if they don't already exist. - * Returns 0 on error - */ - static HKEY resolve_key (HKEY hKey, - const ACE_TCHAR* path, - int create = 1); - virtual bool operator== (const ACE_Configuration_Win32Registry &rhs) const; - virtual bool operator!= (const ACE_Configuration_Win32Registry &rhs) const; - -protected: - - /// Gets the HKEY for a configuration section - int load_key (const ACE_Configuration_Section_Key& key, HKEY& hKey); - - // Not used - ACE_Configuration_Win32Registry (void); - ACE_Configuration_Win32Registry (const ACE_Configuration_Win32Registry& rhs); - ACE_Configuration_Win32Registry& operator= (const ACE_Configuration_Win32Registry& rhs); -}; -#endif /* ACE_WIN32 && !ACE_LACKS_WIN32_REGISTRY */ - -// ACE_Allocator version - -typedef ACE_Allocator_Adapter > - PERSISTENT_ALLOCATOR; -typedef ACE_Allocator_Adapter > - HEAP_ALLOCATOR; - -/** - * @class ACE_Configuration_ExtId - * - * @brief External ID for the section and value hash - * - * Contains a pointer to the section or value name. - */ -class ACE_Export ACE_Configuration_ExtId -{ -public: - /// Defeault ctor - ACE_Configuration_ExtId (void); - - /// Named constructor - explicit ACE_Configuration_ExtId (const ACE_TCHAR* name); - - /// Copy ctor - ACE_Configuration_ExtId (const ACE_Configuration_ExtId& rhs); - - /// destructor - ~ACE_Configuration_ExtId (void); - - /// Assignment operator - ACE_Configuration_ExtId& operator= (const ACE_Configuration_ExtId& rhs); - - /// Equality comparison operator (must match name_). - bool operator== (const ACE_Configuration_ExtId &rhs) const; - - /// Inequality comparison operator. - bool operator!= (const ACE_Configuration_ExtId &rhs) const; - - /// Frees the name of the value. needed since we don't know the - /// allocator name_ was created in - void free (ACE_Allocator *alloc); - - /// hash function is required in order for this class to be usable by - /// ACE_Hash_Map_Manager. - u_long hash (void) const; - - // = Data members. - - const ACE_TCHAR * name_; - - // Accessors - const ACE_TCHAR *name (void); -}; - -typedef ACE_Hash_Map_With_Allocator - SUBSECTION_MAP; -typedef ACE_Hash_Map_Manager_Ex, - ACE_Equal_To, - ACE_Null_Mutex> - SUBSECTION_HASH; - -/// @deprecated Deprecated typedef. Use the SUBSECTION_HASH::ENTRY trait instead. -typedef SUBSECTION_HASH::ENTRY SUBSECTION_ENTRY; - -/** - * @class ACE_Configuration_Value_IntId - * - * @brief The section hash table internal value class - * - * This class is present as the internal portion of a section's - * value hash table It may store string, integer or binary data. - */ -class ACE_Export ACE_Configuration_Value_IntId -{ -public: - /// Default constructor - ACE_Configuration_Value_IntId (void); - - /// String constructor, takes ownership of string - explicit ACE_Configuration_Value_IntId (ACE_TCHAR* string); - - /// Integer constructor - explicit ACE_Configuration_Value_IntId (u_int integer); - - /// Binary constructor, takes ownership of data - ACE_Configuration_Value_IntId (void* data, size_t length); - - /// Copy ctor - ACE_Configuration_Value_IntId (const ACE_Configuration_Value_IntId& rhs); - - /// Destructor - ~ACE_Configuration_Value_IntId (void); - - /// Assignment operator - ACE_Configuration_Value_IntId& operator= ( - const ACE_Configuration_Value_IntId& rhs); - - void free (ACE_Allocator *alloc); - - // = Data members. - - /** - * Points to the string value or binary data or IS the integer - * Length is only used when type_ == BINARY - */ - ACE_Configuration::VALUETYPE type_; - union { - void * ptr_; - u_int int_; - } data_; - size_t length_; -}; - -typedef ACE_Hash_Map_With_Allocator - VALUE_MAP; -typedef ACE_Hash_Map_Manager_Ex, - ACE_Equal_To, - ACE_Null_Mutex> - VALUE_HASH; - -// Deprecated typedef. Use the VALUE_HASH::ENTRY trait instead. -typedef VALUE_HASH::ENTRY VALUE_ENTRY; - -/** - * @class ACE_Configuration_Section_IntId - * - * @brief The internal ID for a section hash table - * - * Contains a hash table containing value name/values - */ -class ACE_Export ACE_Configuration_Section_IntId -{ -public: - /// Default ctor - ACE_Configuration_Section_IntId (void); - - /// Named ctor - ACE_Configuration_Section_IntId (VALUE_MAP* value_hash_map, - SUBSECTION_MAP* section_hash_map); - - /// Copy ctor - ACE_Configuration_Section_IntId (const ACE_Configuration_Section_IntId& rhs); - - /// Destructor - ~ACE_Configuration_Section_IntId (void); - - /// Assignment operator - ACE_Configuration_Section_IntId& operator= ( - const ACE_Configuration_Section_IntId& rhs); - - /// Frees the hash table and all its values - void free (ACE_Allocator *alloc); - - // = Data Members. - VALUE_MAP* value_hash_map_; - - SUBSECTION_MAP* section_hash_map_; -}; - -typedef ACE_Hash_Map_With_Allocator - SECTION_MAP; -typedef ACE_Hash_Map_Manager_Ex, - ACE_Equal_To, - ACE_Null_Mutex> - SECTION_HASH; - -// Deprecated typedef. Use the SECTION_HASH::ENTRY trait instead. -typedef SECTION_HASH::ENTRY SECTION_ENTRY; - -/** - * @class ACE_Configuration_Section_Key_Heap - * - * @brief Internal section key class for heap based configuration - * database. - * - * Contains a value iterator and full path name of section. - */ -class ACE_Export ACE_Configuration_Section_Key_Heap - : public ACE_Section_Key_Internal -{ -public: - /// Constructor based on the full path of the section - ACE_Configuration_Section_Key_Heap (const ACE_TCHAR* path); - - /// The path itself - ACE_TCHAR* path_; - - /// The value iterator - VALUE_HASH::ITERATOR* value_iter_; - - /// The sub section iterator - SUBSECTION_HASH::ITERATOR* section_iter_; -protected: - /// Destructor - will delete the iterators - virtual ~ACE_Configuration_Section_Key_Heap (void); - - // Not used - ACE_Configuration_Section_Key_Heap (const ACE_Configuration_Section_Key_Heap& rhs); - ACE_Configuration_Section_Key_Heap& operator= (const ACE_Configuration_Section_Key_Heap& rhs); -}; - -/** - * @class ACE_Configuration_Heap - * - * @brief The concrete implementation of a allocator based - * configuration database - * - * This class uses ACE's Allocators to manage a memory - * representation of a configuration database. A persistent heap - * may be used to store configurations persistently - * - * @note Before using this class you must call one of the open methods. - * - * @todo - * - Need to investigate what happens if memory mapped file gets mapped to - * a location different than it was created with. - */ -class ACE_Export ACE_Configuration_Heap : public ACE_Configuration -{ -public: - - /// Default ctor - ACE_Configuration_Heap (void); - - /// Destructor - virtual ~ACE_Configuration_Heap (void); - - /** - * Opens a configuration that allocates its memory from a memory-mapped file. - * This makes it possible to persist a configuration to permanent storage. - * This is not the same as exporting the configuration to a file; the - * memory-mapped file is not likely to be very readable by humans. - * - * @param file_name Name of the file to map into memory. - * - * @param base_address Address to map the base of @a file_name to. - * - * @param default_map_size Starting size for the internal hash tables that - * contain configuration information. - * - * @retval 0 for success. - * @retval -1 for error, with errno set to indicate the cause. If open() - * is called multiple times, errno will be @c EBUSY. - */ - int open (const ACE_TCHAR* file_name, - void* base_address = ACE_DEFAULT_BASE_ADDR, - size_t default_map_size = ACE_DEFAULT_CONFIG_SECTION_SIZE); - - /** - * Opens a configuration that allocates memory from the heap. - * - * @param default_map_size Starting size for the internal hash tables that - * contain configuration information. - * - * @retval 0 for success. - * @retval -1 for error, with errno set to indicate the cause. If open() - * is called multiple times, errno will be @c EBUSY. - */ - int open (size_t default_map_size = ACE_DEFAULT_CONFIG_SECTION_SIZE); - - virtual int open_section (const ACE_Configuration_Section_Key& base, - const ACE_TCHAR* sub_section, - int create, ACE_Configuration_Section_Key& result); - - virtual int remove_section (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* sub_section, - bool recursive); - - virtual int enumerate_values (const ACE_Configuration_Section_Key& key, - int index, - ACE_TString& name, - VALUETYPE& type); - - virtual int enumerate_sections (const ACE_Configuration_Section_Key& key, - int index, - ACE_TString& name); - - virtual int set_string_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - const ACE_TString& value); - - virtual int set_integer_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - u_int value); - - virtual int set_binary_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - const void* data, - size_t length); - - virtual int get_string_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - ACE_TString& value); - - virtual int get_integer_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - u_int& value); - - virtual int get_binary_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - void* &data, - size_t &length); - - virtual int find_value(const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name, - VALUETYPE& type); - - /// Removes the the value @a name from @a key. returns non zero on error - virtual int remove_value (const ACE_Configuration_Section_Key& key, - const ACE_TCHAR* name); - -private: - /// @a sub_section may not contain path separators - int open_simple_section (const ACE_Configuration_Section_Key &base, - const ACE_TCHAR *sub_section, - int create, ACE_Configuration_Section_Key &result); - /// Adds a new section - int add_section (const ACE_Configuration_Section_Key &base, - const ACE_TCHAR *sub_section, - ACE_Configuration_Section_Key &result); - - /// Helper for the method. - int create_index (void); - - /// Helper for create_index() method: places hash table into an - /// allocated space. - int create_index_helper (void *buffer); - - int value_open_helper (size_t hash_table_size, void *buffer); - - int section_open_helper (size_t hash_table_size, void *buffer); - - int load_key (const ACE_Configuration_Section_Key& key, ACE_TString& name); - - int new_section (const ACE_TString& section, - ACE_Configuration_Section_Key& result); - - ACE_Configuration_Heap (const ACE_Configuration_Heap& rhs); - ACE_Configuration_Heap& operator= (const ACE_Configuration_Heap& rhs); - - ACE_Allocator *allocator_; - SECTION_MAP *index_; - size_t default_map_size_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Configuration.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIGURATION_H */ diff --git a/externals/ace/Configuration.inl b/externals/ace/Configuration.inl deleted file mode 100644 index 19c2c591bf4..00000000000 --- a/externals/ace/Configuration.inl +++ /dev/null @@ -1,13 +0,0 @@ -// -*- C++ -*- -// -// $Id: Configuration.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE const ACE_TCHAR* -ACE_Configuration_ExtId::name (void) -{ - return name_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Configuration_Import_Export.cpp b/externals/ace/Configuration_Import_Export.cpp deleted file mode 100644 index ae489f05dfa..00000000000 --- a/externals/ace/Configuration_Import_Export.cpp +++ /dev/null @@ -1,670 +0,0 @@ -// $Id: Configuration_Import_Export.cpp 84565 2009-02-23 08:20:39Z johnnyw $ - -#include "ace/Configuration_Import_Export.h" -#include "ace/OS_Errno.h" -#include "ace/OS_NS_stdio.h" -#include "ace/OS_NS_ctype.h" -#include "ace/OS_NS_string.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_Config_ImpExp_Base::ACE_Config_ImpExp_Base (ACE_Configuration& config) - : config_ (config) -{ -} - -ACE_Config_ImpExp_Base::~ACE_Config_ImpExp_Base (void) -{ -} - -ACE_Registry_ImpExp::ACE_Registry_ImpExp (ACE_Configuration& config) - : ACE_Config_ImpExp_Base (config) -{ -} - -ACE_Registry_ImpExp::~ACE_Registry_ImpExp (void) -{ -} - -// Imports the configuration database from filename. -// No existing data is removed. -int -ACE_Registry_ImpExp::import_config (const ACE_TCHAR* filename) -{ - if (0 == filename) - { - errno = EINVAL; - return -1; - } - FILE* in = ACE_OS::fopen (filename, ACE_TEXT ("r")); - if (!in) - return -1; - - u_int buffer_size = 4096; - u_int read_pos = 0; - ACE_TCHAR *buffer = 0; - ACE_NEW_NORETURN (buffer, ACE_TCHAR[buffer_size]); - if (!buffer) - { - ACE_Errno_Guard guard (errno); - (void) ACE_OS::fclose (in); - return -1; - } - ACE_Configuration_Section_Key section; - ACE_TCHAR *end = 0; - - while (ACE_OS::fgets (buffer+read_pos, buffer_size - read_pos, in)) - { - // Check if we got all the line. - end = ACE_OS::strrchr (buffer + read_pos, - ACE_TEXT ('\n')); // look for end of line - if (!end) // we havn't reach the end of the line yet - { - // allocate a new buffer - double size the previous one - ACE_TCHAR *temp_buffer; - ACE_NEW_NORETURN (temp_buffer, ACE_TCHAR[buffer_size * 2]); - if (!temp_buffer) - { - ACE_Errno_Guard guard (errno); - delete [] buffer; - (void) ACE_OS::fclose (in); - return -1; - } - - // copy the beginnning of the line - ACE_OS::memcpy (temp_buffer, buffer, buffer_size); - read_pos = buffer_size - 1; - buffer_size *= 2; - delete [] buffer; - buffer = temp_buffer; - continue; - } - read_pos = 0; - - // Check for a comment - if (buffer[0] == ACE_TEXT (';') || buffer[0] == ACE_TEXT ('#')) - continue; - - if (buffer[0] == ACE_TEXT ('[')) - { - // We have a new section here, strip out the section name - end = ACE_OS::strrchr (buffer, ACE_TEXT (']')); - if (!end) - { - ACE_OS::fclose (in); - delete [] buffer; - return -3; - } - *end = 0; - - if (config_.expand_path (config_.root_section (), buffer + 1, section, 1)) - { - ACE_OS::fclose (in); - delete [] buffer; - return -3; - } - continue; - } // end if firs char is a [ - - if (buffer[0] == ACE_TEXT ('"')) - { - // we have a value - end = ACE_OS::strchr (buffer+1, '"'); - if (!end) // no closing quote, not a value so just skip it - continue; - - // null terminate the name - *end = 0; - ACE_TCHAR* name = buffer + 1; - end+=2; - // determine the type - if (*end == '\"') - { - // string type - // truncate trailing " - ++end; - ACE_TCHAR* trailing = ACE_OS::strrchr (end, '"'); - if (trailing) - *trailing = 0; - if (config_.set_string_value (section, name, end)) - { - ACE_OS::fclose (in); - delete [] buffer; - return -4; - } - } - else if (ACE_OS::strncmp (end, ACE_TEXT ("dword:"), 6) == 0) - { - // number type - ACE_TCHAR* endptr = 0; - unsigned long value = ACE_OS::strtoul (end + 6, &endptr, 16); - if (config_.set_integer_value (section, name, value)) - { - ACE_OS::fclose (in); - delete [] buffer; - return -4; - } - } - else if (ACE_OS::strncmp (end, ACE_TEXT ("hex:"), 4) == 0) - { - // binary type - size_t string_length = ACE_OS::strlen (end + 4); - // divide by 3 to get the actual buffer length - size_t length = string_length / 3; - size_t remaining = length; - u_char* data = 0; - ACE_NEW_RETURN (data, - u_char[length], - -1); - u_char* out = data; - ACE_TCHAR* inb = end + 4; - ACE_TCHAR* endptr = 0; - while (remaining) - { - u_char charin = (u_char) ACE_OS::strtoul (inb, &endptr, 16); - *out = charin; - ++out; - --remaining; - inb += 3; - } - if (config_.set_binary_value (section, name, data, length)) - { - ACE_OS::fclose (in); - delete [] data; - delete [] buffer; - return -4; - } - else - delete [] data; - } - else - { - // invalid type, ignore - continue; - } - }// end if first char is a " - else - { - // if the first character is not a ", [, ;, or # we may be - // processing a file in the old format. - // Try and process the line as such and if it fails, - // return an error - int rc = process_previous_line_format (buffer, section); - if (rc != 0) - { - ACE_OS::fclose (in); - delete [] buffer; - return rc; - } - } // end if maybe old format - } // end while fgets - - if (ferror (in)) - { - ACE_OS::fclose (in); - delete [] buffer; - return -1; - } - - ACE_OS::fclose (in); - delete [] buffer; - return 0; -} - -// This method exports the entire configuration database to . -// Once the file is opened this method calls 'export_section' passing -// the root section. -int -ACE_Registry_ImpExp::export_config (const ACE_TCHAR* filename) -{ - if (0 == filename) - { - errno = EINVAL; - return -1; - } - int result = -1; - - FILE* out = ACE_OS::fopen (filename, ACE_TEXT ("w")); - if (out) - { - result = this->export_section (config_.root_section (), - ACE_TEXT (""), - out); - // The data may have been buffered and will be flush on close, - // so we need to check that the close succeeds. - if (ACE_OS::fclose (out) < 0) - result = -7; - } - return result; -} - -// Method provided by derived classes in order to write one section -// to the file specified. Called by export_config when exporting -// the entire configuration object. - -int -ACE_Registry_ImpExp::export_section (const ACE_Configuration_Section_Key& section, - const ACE_TString& path, - FILE* out) -{ - // don't export the root - if (path.length ()) - { - // Write out the section header - ACE_TString header = ACE_TEXT ("["); - header += path; - header += ACE_TEXT ("]"); - header += ACE_TEXT ("\n"); - if (ACE_OS::fputs (header.fast_rep (), out) < 0) - return -1; - // Write out each value - int index = 0; - ACE_TString name; - ACE_Configuration::VALUETYPE type; - ACE_TString line; - ACE_TCHAR int_value[32]; - ACE_TCHAR bin_value[3]; - void* binary_data; - size_t binary_length; - ACE_TString string_value; - while (!config_.enumerate_values (section, index, name, type)) - { - line = ACE_TEXT ("\"") + name + ACE_TEXT ("\"="); - switch (type) - { - case ACE_Configuration::INTEGER: - { - u_int value; - if (config_.get_integer_value (section, name.fast_rep (), value)) - return -2; - ACE_OS::sprintf (int_value, ACE_TEXT ("%08x"), value); - line += ACE_TEXT ("dword:"); - line += int_value; - break; - } - case ACE_Configuration::STRING: - { - if (config_.get_string_value (section, - name.fast_rep (), - string_value)) - return -2; - line += ACE_TEXT ("\""); - line += string_value + ACE_TEXT ("\""); - break; - } -#ifdef _WIN32 - case ACE_Configuration::INVALID: - break; // JDO added break. Otherwise INVALID is processed - // like BINARY. If that's correct, please remove the - // break and these comments -#endif - case ACE_Configuration::BINARY: - { - // not supported yet - maybe use BASE64 codeing? - if (config_.get_binary_value (section, - name.fast_rep (), - binary_data, - binary_length)) - return -2; - line += ACE_TEXT ("hex:"); - unsigned char* ptr = (unsigned char*)binary_data; - while (binary_length) - { - if (ptr != binary_data) - { - line += ACE_TEXT (","); - } - ACE_OS::sprintf (bin_value, ACE_TEXT ("%02x"), *ptr); - line += bin_value; - --binary_length; - ++ptr; - } - delete [] (char*) binary_data; - break; - } - default: - return -3; - } - line += ACE_TEXT ("\n"); - if (ACE_OS::fputs (line.fast_rep (), out) < 0) - return -4; - ++index; - } - } - // Export all sub sections - int index = 0; - ACE_TString name; - ACE_Configuration_Section_Key sub_key; - ACE_TString sub_section; - while (!config_.enumerate_sections (section, index, name)) - { - ACE_TString sub_section (path); - if (path.length ()) - sub_section += ACE_TEXT ("\\"); - sub_section += name; - if (config_.open_section (section, name.fast_rep (), 0, sub_key)) - return -5; - if (export_section (sub_key, sub_section.fast_rep (), out)) - return -6; - ++index; - } - return 0; -} - -// -// This method read the line format origionally used in ACE 5.1 -// -int -ACE_Registry_ImpExp::process_previous_line_format (ACE_TCHAR* buffer, - ACE_Configuration_Section_Key& section) -{ - // Chop any cr/lf at the end of the line. - ACE_TCHAR *endp = ACE_OS::strpbrk (buffer, ACE_TEXT ("\r\n")); - if (endp != 0) - *endp = '\0'; - - // assume this is a value, read in the value name - ACE_TCHAR* end = ACE_OS::strchr (buffer, '='); - if (end) // no =, not a value so just skip it - { - // null terminate the name - *end = 0; - ++end; - // determine the type - if (*end == '\"') - { - // string type - if(config_.set_string_value (section, buffer, end + 1)) - return -4; - } - else if (*end == '#') - { - // number type - u_int value = ACE_OS::atoi (end + 1); - if (config_.set_integer_value (section, buffer, value)) - return -4; - } - } - return 0; -} // end read_previous_line_format - - -ACE_Ini_ImpExp::ACE_Ini_ImpExp (ACE_Configuration& config) - : ACE_Config_ImpExp_Base (config) -{ -} - -ACE_Ini_ImpExp::~ACE_Ini_ImpExp (void) -{ -} - -// Method to read file and populate object. -int -ACE_Ini_ImpExp::import_config (const ACE_TCHAR* filename) -{ - if (0 == filename) - { - errno = EINVAL; - return -1; - } - FILE* in = ACE_OS::fopen (filename, ACE_TEXT ("r")); - if (!in) - return -1; - - // @@ Make this a dynamic size! - ACE_TCHAR buffer[4096]; - ACE_Configuration_Section_Key section; - while (ACE_OS::fgets (buffer, sizeof buffer, in)) - { - ACE_TCHAR *line = this->squish (buffer); - // Check for a comment and blank line - if (line[0] == ACE_TEXT (';') || - line[0] == ACE_TEXT ('#') || - line[0] == '\0') - continue; - - if (line[0] == ACE_TEXT ('[')) - { - // We have a new section here, strip out the section name - ACE_TCHAR* end = ACE_OS::strrchr (line, ACE_TEXT (']')); - if (!end) - { - ACE_OS::fclose (in); - return -3; - } - *end = 0; - - if (config_.expand_path (config_.root_section (), - line + 1, - section, - 1)) - { - ACE_OS::fclose (in); - return -3; - } - - continue; - } - - // We have a line; name ends at equal sign. - ACE_TCHAR *end = ACE_OS::strchr (line, ACE_TEXT ('=')); - if (end == 0) // No '=' - { - ACE_OS::fclose (in); - return -3; - } - *end++ = '\0'; - ACE_TCHAR *name = this->squish (line); -#if 0 - if (ACE_OS::strlen (name) == 0) // No name; just an '=' - { - ACE_OS::fclose (in); - return -3; - } -#endif - // Now find the start of the value - ACE_TCHAR *value = this->squish (end); - size_t value_len = ACE_OS::strlen (value); - if (value_len > 0) - { - // ACE 5.2 (and maybe earlier) exported strings may be enclosed - // in quotes. If string is quote-delimited, strip the quotes. - // Newer exported files don't have quote delimiters. - if (value[0] == ACE_TEXT ('"') && - value[value_len - 1] == ACE_TEXT ('"')) - { - // Strip quotes off both ends. - value[value_len - 1] = '\0'; - ++value; - } - } - - if (config_.set_string_value (section, name, value)) - { - ACE_OS::fclose (in); - return -4; - } - } // end while fgets - - if (ferror (in)) - { - ACE_OS::fclose (in); - return -1; - } - - ACE_OS::fclose (in); - return 0; -} - -// This method exports the entire configuration database to . -// Once the file is opened this method calls 'export_section' passing -// the root section. -int -ACE_Ini_ImpExp::export_config (const ACE_TCHAR* filename) -{ - if (0 == filename) - { - errno = EINVAL; - return -1; - } - int result = -1; - - FILE* out = ACE_OS::fopen (filename, ACE_TEXT ("w")); - if (out) - { - result = this->export_section (config_.root_section (), - ACE_TEXT (""), - out); - // The data may have been buffered and will be flush on close, - // so we need to check that the close succeeds. - if (ACE_OS::fclose (out) < 0) - result = -7; - } - return result; -} - -// Method provided by derived classes in order to write one section to the -// file specified. Called by export_config when exporting the entire -// configuration objet - -int -ACE_Ini_ImpExp::export_section (const ACE_Configuration_Section_Key& section, - const ACE_TString& path, - FILE* out) -{ - // don't export the root - if (path.length ()) - { - // Write out the section header - ACE_TString header = ACE_TEXT ("["); - header += path; - header += ACE_TEXT ("]\n"); - if (ACE_OS::fputs (header.fast_rep (), out) < 0) - return -1; - // Write out each value - int index = 0; - ACE_TString name; - ACE_Configuration::VALUETYPE type; - ACE_TString line; - ACE_TCHAR int_value[32]; - ACE_TCHAR bin_value[3]; - void* binary_data; - size_t binary_length; - ACE_TString string_value; - while (!config_.enumerate_values (section, index, name, type)) - { - line = name + ACE_TEXT ("="); - switch (type) - { - case ACE_Configuration::INTEGER: - { - u_int value; - if (config_.get_integer_value (section, name.fast_rep (), value)) - return -2; - ACE_OS::sprintf (int_value, ACE_TEXT ("%08x"), value); - line += int_value; - break; - } - case ACE_Configuration::STRING: - { - if (config_.get_string_value (section, - name.fast_rep (), - string_value)) - return -2; - line += string_value; - break; - } -#ifdef _WIN32 - case ACE_Configuration::INVALID: - break; // JDO added break. Otherwise INVALID is processed - // like BINARY. If that's correct, please remove the - // break and these comments -#endif - case ACE_Configuration::BINARY: - { - // not supported yet - maybe use BASE64 codeing? - if (config_.get_binary_value (section, - name.fast_rep (), - binary_data, - binary_length)) - return -2; - line += ACE_TEXT ("\""); - unsigned char* ptr = (unsigned char*)binary_data; - while (binary_length) - { - if (ptr != binary_data) - { - line += ACE_TEXT (","); - } - ACE_OS::sprintf (bin_value, ACE_TEXT ("%02x"), *ptr); - line += bin_value; - --binary_length; - ++ptr; - } - line += ACE_TEXT ("\""); - delete [] (char *) binary_data; - break; - } - default: - return -3; - - }// end switch on type - - line += ACE_TEXT ("\n"); - if (ACE_OS::fputs (line.fast_rep (), out) < 0) - return -4; - ++index; - }// end while enumerating values - } - // Export all sub sections - int index = 0; - ACE_TString name; - ACE_Configuration_Section_Key sub_key; - ACE_TString sub_section; - while (!config_.enumerate_sections (section, index, name)) - { - ACE_TString sub_section (path); - if (path.length ()) - sub_section += ACE_TEXT ("\\"); - sub_section += name; - if (config_.open_section (section, name.fast_rep (), 0, sub_key)) - return -5; - if (export_section (sub_key, sub_section.fast_rep (), out)) - return -6; - ++index; - } - return 0; - -} - -// Method to squish leading and trailing whitespaces from a string. -// Whitespace is defined as: spaces (' '), tabs ('\t') or end-of-line -// (cr/lf). The terminating nul is moved up to expunge trailing -// whitespace and the returned pointer points at the first -// non-whitespace character in the string, which may be the nul -// terminator if the string is all whitespace. - -ACE_TCHAR * -ACE_Ini_ImpExp::squish (ACE_TCHAR *src) -{ - ACE_TCHAR *cp = 0; - - if (src == 0) - return 0; - - // Start at the end and work backwards over all whitespace. - for (cp = src + ACE_OS::strlen (src) - 1; - cp != src; - --cp) - if (!ACE_OS::ace_isspace (*cp)) - break; - cp[1] = '\0'; // Chop trailing whitespace - - // Now start at the beginning and move over all whitespace. - for (cp = src; ACE_OS::ace_isspace (*cp); ++cp) - continue; - - return cp; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Configuration_Import_Export.h b/externals/ace/Configuration_Import_Export.h deleted file mode 100644 index e93544bee29..00000000000 --- a/externals/ace/Configuration_Import_Export.h +++ /dev/null @@ -1,215 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file Configuration_Import_Export.h - * - * $Id: Configuration_Import_Export.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Jerry D. Odenwelder Jr. - * Chris Hafey - * - * Classes defined in this file provide the ability to import and export - * ACE Configuration objects to/from disk files. The base class - * ACE_Config_ImpExp_Base provides the common functionality and the derived - * classes implement the import/export functionality for the specific format. - * - * @todo - * - Add locking for thread safety. - * - Provide ability to read file in one format and write in another. - * - See todo's in each class - */ -//============================================================================= - -#ifndef ACE_CONFIGURATION_IMPORT_EXPORT_H -#define ACE_CONFIGURATION_IMPORT_EXPORT_H -#include /**/ "ace/pre.h" - -#include "ace/Configuration.h" -#include "ace/SString.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Config_ImpExp_Base - * - * @brief Base class for file import/export configuration. - * - * This class provides base functionality for configuration objects - * that are persisted in files. It takes an ACE_Configuration - * object that it populates with the data read. - * - */ -class ACE_Export ACE_Config_ImpExp_Base -{ -public: - /// Constructor taking the ACE_Configuration to import/export to - ACE_Config_ImpExp_Base (ACE_Configuration& config); - - /** - * Destructor - */ - virtual ~ACE_Config_ImpExp_Base (void); - - /** - * Imports the configuration database from @a filename. - * No existing data is removed. - */ - virtual int import_config (const ACE_TCHAR* filename) = 0; - - /** - * This method exports the entire configuration database to @a filename. - * Once the file is opened this method calls 'export_section' passing - * the root section. - */ - virtual int export_config (const ACE_TCHAR* filename) = 0; - -protected: - ACE_Configuration &config_; - -private: - ACE_Config_ImpExp_Base (const ACE_Config_ImpExp_Base&); - ACE_Config_ImpExp_Base& operator= (const ACE_Config_ImpExp_Base&); -}; - -/** - * @class ACE_Registry_ImpExp - * - * @brief Configuration object that imports/exports data to a file formatted - * using the Win32 Registry file export format. This format looks like - * [Section] - * "key"="String Data" - * "key"=dword: numeric data in hexidecimal format - * "key"=hex: binary data - * - * @todo - * - Add dynamic buffer when importing. currently it will not allow - * importing of values greater than a fixed ammount (4096 bytes) - * - */ -class ACE_Export ACE_Registry_ImpExp : public ACE_Config_ImpExp_Base -{ -public: - /// Construction - ACE_Registry_ImpExp (ACE_Configuration&); - - /// Destruction. - virtual ~ACE_Registry_ImpExp (void); - - /** - * Imports the configuration database from filename. - * No existing data is removed. - */ - virtual int import_config (const ACE_TCHAR* filename); - - /** - * This method exports the entire configuration database to @a filename. - * Once the file is opened this method calls export_section() passing - * the root section. - */ - virtual int export_config (const ACE_TCHAR* filename); - -private: - int export_section (const ACE_Configuration_Section_Key& section, - const ACE_TString& path, - FILE* out); - - int process_previous_line_format (ACE_TCHAR* buffer, - ACE_Configuration_Section_Key& section); - - ACE_Registry_ImpExp ( const ACE_Registry_ImpExp&); - ACE_Registry_ImpExp& operator= ( const ACE_Registry_ImpExp&); -}; - -/** - * @class ACE_Ini_ImpExp - * - * @brief Imports the configuration database from filename as strings. - * Allows non-typed values. (no #, dword: hex:, etc. prefixes) and - * skips whitespace (tabs and spaces) as in standard .ini and .conf - * files. Values (to right of equal sign) can be double quote - * delimited to embed tabs and spaces in the string. - * Caller must convert string to type. - * - * This method allows for lines in the .ini or .conf file like this: - * - * TimeToLive = 100 - * Delay = FALSE - * Flags = FF34 - * Heading = "ACE - Adaptive Communication Environment" - * - * (note leading whitespace (tabs) in examples below) - * - * SeekIndex = 14 - * TraceLevel = 6 # Can comment lines like this - * Justification = left_justified - * - * The caller can then retrieve the string with the regular - * function and convert the string to the - * desired data type. - * - * @todo - * - Strings with embedded newlines cause the import to fail - * - Strings with embedded quotes " cause the import to fail - * - Importing/exporting for values in the root section does not work - * - Add dynamic buffer when importing. currently it will not allow - * importing of values greater than a fixed ammount (4096 bytes) -*/ -class ACE_Export ACE_Ini_ImpExp : public ACE_Config_ImpExp_Base -{ -public: - /** - * Construction - */ - ACE_Ini_ImpExp (ACE_Configuration&); - - /** - * Destructor - */ - virtual ~ACE_Ini_ImpExp (void); - - /** - * Imports the configuration database from filename. - * No existing data is removed. - */ - virtual int import_config (const ACE_TCHAR* filename); - - /** - * This method exports the entire configuration database to @a filename. - * Once the file is opened this method calls export_section() passing - * the root section. - */ - virtual int export_config (const ACE_TCHAR* filename); - -private: - /** - * Method provided by derived classes in order to write one section - * to the file specified. Called by export_config() when exporting - * the entire configuration object. - */ - int export_section (const ACE_Configuration_Section_Key& section, - const ACE_TString& path, - FILE* out); - - /** - * Method to squish leading and trailing whitespaces in a string. - * Whitespace is defined as: spaces (' '), tabs ('\\t') or cr/lf. - * Returns a pointer to the first non-whitespace character in the - * buffer provided, or a pointer to the terminating null if the string - * is all whitespace. The terminating null is moved forward to the - * first character past the last non-whitespace. - */ - ACE_TCHAR *squish (ACE_TCHAR *src); - - ACE_Ini_ImpExp (const ACE_Ini_ImpExp&); - ACE_Ini_ImpExp& operator= (const ACE_Ini_ImpExp&); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIGURATION_IMPORT_EXPORT_H */ diff --git a/externals/ace/Connection_Recycling_Strategy.cpp b/externals/ace/Connection_Recycling_Strategy.cpp deleted file mode 100644 index 78b08884340..00000000000 --- a/externals/ace/Connection_Recycling_Strategy.cpp +++ /dev/null @@ -1,13 +0,0 @@ -#include "ace/Connection_Recycling_Strategy.h" - - -ACE_RCSID(ace, Connection_Recycling_Strategy, "$Id: Connection_Recycling_Strategy.cpp 80826 2008-03-04 14:51:23Z wotte $") - - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_Connection_Recycling_Strategy::~ACE_Connection_Recycling_Strategy (void) -{ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Connection_Recycling_Strategy.h b/externals/ace/Connection_Recycling_Strategy.h deleted file mode 100644 index 75169638dcf..00000000000 --- a/externals/ace/Connection_Recycling_Strategy.h +++ /dev/null @@ -1,63 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file Connection_Recycling_Strategy.h - * - * $Id: Connection_Recycling_Strategy.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Doug Schmidt - */ -//============================================================================= -#ifndef ACE_CONNECTION_RECYCLING_STRATEGY_H -#define ACE_CONNECTION_RECYCLING_STRATEGY_H -#include /**/ "ace/pre.h" - -#include "ace/Recyclable.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Connection_Recycling_Strategy - * - * @brief Defines the interface for a connection recycler. - */ -class ACE_Export ACE_Connection_Recycling_Strategy -{ -public: - /// Virtual Destructor - virtual ~ACE_Connection_Recycling_Strategy (void); - - /// Remove from cache. - virtual int purge (const void *recycling_act) = 0; - - /// Add to cache. - virtual int cache (const void *recycling_act) = 0; - - virtual int recycle_state (const void *recycling_act, - ACE_Recyclable_State new_state) = 0; - - /// Get/Set recycle_state. - virtual ACE_Recyclable_State recycle_state (const void *recycling_act) const = 0; - - /// Mark as closed. - virtual int mark_as_closed (const void *recycling_act) = 0; - - /// Mark as closed.(non-locking version) - virtual int mark_as_closed_i (const void *recycling_act) = 0; - - /// Cleanup hint and reset @a act_holder to zero if @a act_holder != 0. - virtual int cleanup_hint (const void *recycling_act, - void **act_holder = 0) = 0; - -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" - -#endif /*ACE_CONNECTION_RECYCLING_STRATEGY*/ diff --git a/externals/ace/Connector.cpp b/externals/ace/Connector.cpp deleted file mode 100644 index 820ca875c16..00000000000 --- a/externals/ace/Connector.cpp +++ /dev/null @@ -1,991 +0,0 @@ -// $Id: Connector.cpp 89510 2010-03-17 12:21:14Z vzykov $ - -#ifndef ACE_CONNECTOR_CPP -#define ACE_CONNECTOR_CPP - -#include "ace/Connector.h" -#include "ace/ACE.h" -#include "ace/OS_NS_stdio.h" -#include "ace/OS_NS_string.h" -#include "ace/os_include/os_fcntl.h" /* Has ACE_NONBLOCK */ - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Connector) - -template -ACE_NonBlocking_Connect_Handler::ACE_NonBlocking_Connect_Handler -(ACE_Connector_Base &connector, - SVC_HANDLER *sh, - long id) - : connector_ (connector) - , svc_handler_ (sh) - , cleanup_svc_handler_ (0) - , timer_id_ (id) -{ - ACE_TRACE ("ACE_NonBlocking_Connect_Handler::ACE_NonBlocking_Connect_Handler"); - - this->reference_counting_policy ().value - (ACE_Event_Handler::Reference_Counting_Policy::ENABLED); - - if (this->svc_handler_ != 0 && - this->svc_handler_->reference_counting_policy ().value () == - ACE_Event_Handler::Reference_Counting_Policy::ENABLED) - { - // If SVC_HANDLER is reference counted then NBCH holds a reference - // in cleanup_svc_handle_ which is both a pointer to SVC_HANDLER - // and a flag that triggers remove_reference in NBCH destructor. - this->cleanup_svc_handler_ = sh; - this->cleanup_svc_handler_->add_reference (); - } -} - -template -ACE_NonBlocking_Connect_Handler::~ACE_NonBlocking_Connect_Handler (void) -{ - if (this->cleanup_svc_handler_) - { - this->cleanup_svc_handler_->remove_reference (); - } -} - -template SVC_HANDLER * -ACE_NonBlocking_Connect_Handler::svc_handler (void) -{ - ACE_TRACE ("ACE_NonBlocking_Connect_Handler::svc_handler"); - return this->svc_handler_; -} - -template long -ACE_NonBlocking_Connect_Handler::timer_id (void) -{ - ACE_TRACE ("ACE_NonBlocking_Connect_Handler::timer_id"); - return this->timer_id_; -} - -template void -ACE_NonBlocking_Connect_Handler::timer_id (long id) -{ - ACE_TRACE ("ACE_NonBlocking_Connect_Handler::timer_id"); - this->timer_id_ = id; -} - -template void -ACE_NonBlocking_Connect_Handler::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_NonBlocking_Connect_Handler::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("svc_handler_ = %x"), this->svc_handler_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ntimer_id_ = %d"), this->timer_id_)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -template bool -ACE_NonBlocking_Connect_Handler::close (SVC_HANDLER *&sh) -{ - // Make sure that we haven't already initialized the Svc_Handler. - if (!this->svc_handler_) - return false; - - { - // Exclusive access to the Reactor. - ACE_GUARD_RETURN (ACE_Lock, - ace_mon, - this->reactor ()->lock (), - 0); - - // Double check. - if (!this->svc_handler_) - return false; - - // Remember the Svc_Handler. - sh = this->svc_handler_; - ACE_HANDLE h = sh->get_handle (); - this->svc_handler_ = 0; - - // Remove this handle from the set of non-blocking handles - // in the Connector. - this->connector_.non_blocking_handles ().remove (h); - - // Cancel timer. - if (this->reactor ()->cancel_timer (this->timer_id (), - 0, - 0) == -1) - return false; - - // Remove from Reactor. - if (this->reactor ()->remove_handler ( - h, - ACE_Event_Handler::ALL_EVENTS_MASK) == -1) - return false; - } - - return true; -} - - -template int -ACE_NonBlocking_Connect_Handler::handle_timeout -(const ACE_Time_Value &tv, - const void *arg) -{ - // This method is called if a connection times out before completing. - ACE_TRACE ("ACE_NonBlocking_Connect_Handler::handle_timeout"); - - SVC_HANDLER *svc_handler = 0; - int const retval = this->close (svc_handler) ? 0 : -1; - - // Forward to the SVC_HANDLER the that was passed in as a - // magic cookie during ACE_Connector::connect(). This gives the - // SVC_HANDLER an opportunity to take corrective action (e.g., wait - // a few milliseconds and try to reconnect again. - if (svc_handler != 0 && svc_handler->handle_timeout (tv, arg) == -1) - svc_handler->handle_close (svc_handler->get_handle (), - ACE_Event_Handler::TIMER_MASK); - - return retval; -} - - -template int -ACE_NonBlocking_Connect_Handler::handle_input (ACE_HANDLE) -{ - // Called when a failure occurs during asynchronous connection - // establishment. - ACE_TRACE ("ACE_NonBlocking_Connect_Handler::handle_input"); - - SVC_HANDLER *svc_handler = 0; - int const retval = this->close (svc_handler) ? 0 : -1; - - // Close Svc_Handler. - if (svc_handler != 0) - { - svc_handler->close (NORMAL_CLOSE_OPERATION); - } - - return retval; -} - -template int -ACE_NonBlocking_Connect_Handler::handle_output (ACE_HANDLE handle) -{ - // Called when a connection is establishment asynchronous. - ACE_TRACE ("ACE_NonBlocking_Connect_Handler::handle_output"); - - // Grab the connector ref before smashing ourselves in close(). - ACE_Connector_Base &connector = this->connector_; - SVC_HANDLER *svc_handler = 0; - int const retval = this->close (svc_handler) ? 0 : -1; - - if (svc_handler != 0) - { - connector.initialize_svc_handler (handle, svc_handler); - } - - return retval; -} - -template int -ACE_NonBlocking_Connect_Handler::handle_exception (ACE_HANDLE h) -{ - // On Win32, the except mask must also be set for asynchronous - // connects. - ACE_TRACE ("ACE_NonBlocking_Connect_Handler::handle_exception"); - return this->handle_output (h); -} - -template int -ACE_NonBlocking_Connect_Handler::resume_handler (void) -{ - return ACE_Event_Handler::ACE_EVENT_HANDLER_NOT_RESUMED; -} - -template void -ACE_Connector::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Connector::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nflags_ = %d"), this->flags_)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -template int -ACE_Connector::make_svc_handler (SVC_HANDLER *&sh) -{ - ACE_TRACE ("ACE_Connector::make_svc_handler"); - - if (sh == 0) - ACE_NEW_RETURN (sh, - SVC_HANDLER, - -1); - - // Set the reactor of the newly created to the same - // reactor that this is using. - sh->reactor (this->reactor ()); - return 0; -} - -template int -ACE_Connector::activate_svc_handler (SVC_HANDLER *svc_handler) -{ - ACE_TRACE ("ACE_Connector::activate_svc_handler"); - // No errors initially - int error = 0; - - // See if we should enable non-blocking I/O on the 's - // peer. - if (ACE_BIT_ENABLED (this->flags_, ACE_NONBLOCK) != 0) - { - if (svc_handler->peer ().enable (ACE_NONBLOCK) == -1) - error = 1; - } - // Otherwise, make sure it's disabled by default. - else if (svc_handler->peer ().disable (ACE_NONBLOCK) == -1) - error = 1; - - // We are connected now, so try to open things up. - if (error || svc_handler->open ((void *) this) == -1) - { - // Make sure to close down the to avoid descriptor - // leaks. - // The connection was already made; so this close is a "normal" - // close operation. - svc_handler->close (NORMAL_CLOSE_OPERATION); - return -1; - } - else - return 0; -} - -template ACE_PEER_CONNECTOR & -ACE_Connector::connector (void) const -{ - return const_cast (this->connector_); -} - -template int -ACE_Connector::connect_svc_handler -(SVC_HANDLER *&svc_handler, - const ACE_PEER_CONNECTOR_ADDR &remote_addr, - ACE_Time_Value *timeout, - const ACE_PEER_CONNECTOR_ADDR &local_addr, - int reuse_addr, - int flags, - int perms) -{ - ACE_TRACE ("ACE_Connector::connect_svc_handler"); - - return this->connector_.connect (svc_handler->peer (), - remote_addr, - timeout, - local_addr, - reuse_addr, - flags, - perms); -} - -template int -ACE_Connector::connect_svc_handler -(SVC_HANDLER *&svc_handler, - SVC_HANDLER *&sh_copy, - const ACE_PEER_CONNECTOR_ADDR &remote_addr, - ACE_Time_Value *timeout, - const ACE_PEER_CONNECTOR_ADDR &local_addr, - int reuse_addr, - int flags, - int perms) -{ - ACE_TRACE ("ACE_Connector::connect_svc_handler"); - - sh_copy = svc_handler; - return this->connector_.connect (svc_handler->peer (), - remote_addr, - timeout, - local_addr, - reuse_addr, - flags, - perms); -} - -template int -ACE_Connector::open (ACE_Reactor *r, int flags) -{ - ACE_TRACE ("ACE_Connector::open"); - this->reactor (r); - this->flags_ = flags; - return 0; -} - -template -ACE_Connector::ACE_Connector (ACE_Reactor *r, - int flags) -{ - ACE_TRACE ("ACE_Connector::ACE_Connector"); - (void) this->open (r, flags); -} - -template int -ACE_Connector::connect -(SVC_HANDLER *&sh, - const ACE_PEER_CONNECTOR_ADDR &remote_addr, - const ACE_Synch_Options &synch_options, - const ACE_PEER_CONNECTOR_ADDR &local_addr, - int reuse_addr, - int flags, - int perms) -{ - // Initiate connection to peer. - return this->connect_i (sh, - 0, - remote_addr, - synch_options, - local_addr, - reuse_addr, - flags, - perms); -} - -template int -ACE_Connector::connect -(SVC_HANDLER *&sh, - SVC_HANDLER *&sh_copy, - const ACE_PEER_CONNECTOR_ADDR &remote_addr, - const ACE_Synch_Options &synch_options, - const ACE_PEER_CONNECTOR_ADDR &local_addr, - int reuse_addr, - int flags, - int perms) -{ - // Initiate connection to peer. - return this->connect_i (sh, - &sh_copy, - remote_addr, - synch_options, - local_addr, - reuse_addr, - flags, - perms); -} - -template int -ACE_Connector::connect_i -(SVC_HANDLER *&sh, - SVC_HANDLER **sh_copy, - const ACE_PEER_CONNECTOR_ADDR &remote_addr, - const ACE_Synch_Options &synch_options, - const ACE_PEER_CONNECTOR_ADDR &local_addr, - int reuse_addr, - int flags, - int perms) -{ - ACE_TRACE ("ACE_Connector::connect_i"); - - // If the user hasn't supplied us with a we'll use the - // factory method to create one. Otherwise, things will remain as - // they are... - if (this->make_svc_handler (sh) == -1) - return -1; - - ACE_Time_Value *timeout = 0; - int const use_reactor = synch_options[ACE_Synch_Options::USE_REACTOR]; - - if (use_reactor) - timeout = const_cast (&ACE_Time_Value::zero); - else - timeout = const_cast (synch_options.time_value ()); - - int result; - if (sh_copy == 0) - result = this->connect_svc_handler (sh, - remote_addr, - timeout, - local_addr, - reuse_addr, - flags, - perms); - else - result = this->connect_svc_handler (sh, - *sh_copy, - remote_addr, - timeout, - local_addr, - reuse_addr, - flags, - perms); - - // Activate immediately if we are connected. - if (result != -1) - return this->activate_svc_handler (sh); - - // Delegate to connection strategy. - if (use_reactor && ACE_OS::last_error () == EWOULDBLOCK) - { - // If the connection hasn't completed and we are using - // non-blocking semantics then register - // ACE_NonBlocking_Connect_Handler with the ACE_Reactor so that - // it will call us back when the connection is complete or we - // timeout, whichever comes first... - int result; - - if (sh_copy == 0) - result = this->nonblocking_connect (sh, synch_options); - else - result = this->nonblocking_connect (*sh_copy, synch_options); - - // If for some reason the call failed, then - // will be set to the new error. If the call succeeds, however, - // we need to make sure that remains set to - // . - if (result == 0) - errno = EWOULDBLOCK; - } - else - { - // Save/restore errno. - ACE_Errno_Guard error (errno); - // Make sure to close down the service handler to avoid handle - // leaks. - if (sh_copy == 0) - { - if (sh) - sh->close (CLOSE_DURING_NEW_CONNECTION); - } - else if (*sh_copy) - (*sh_copy)->close (CLOSE_DURING_NEW_CONNECTION); - } - - return -1; -} - -template int -ACE_Connector::connect_n -(size_t n, - SVC_HANDLER *sh[], - ACE_PEER_CONNECTOR_ADDR remote_addrs[], - ACE_TCHAR *failed_svc_handlers, - const ACE_Synch_Options &synch_options) -{ - int result = 0; - - for (size_t i = 0; i < n; i++) - { - if (this->connect (sh[i], remote_addrs[i], synch_options) == -1 - && !(synch_options[ACE_Synch_Options::USE_REACTOR] - && errno == EWOULDBLOCK)) - { - result = -1; - if (failed_svc_handlers != 0) - // Mark this entry as having failed. - failed_svc_handlers[i] = 1; - } - else if (failed_svc_handlers != 0) - // Mark this entry as having succeeded. - failed_svc_handlers[i] = 0; - } - - return result; -} - -// Cancel a that was started asynchronously. -template int -ACE_Connector::cancel (SVC_HANDLER *sh) -{ - ACE_TRACE ("ACE_Connector::cancel"); - - ACE_Event_Handler *handler = - this->reactor ()->find_handler (sh->get_handle ()); - - if (handler == 0) - return -1; - - // find_handler() increments handler's refcount; ensure we decrement it. - ACE_Event_Handler_var safe_handler (handler); - - NBCH *nbch = - dynamic_cast (handler); - - if (nbch == 0) - return -1; - - SVC_HANDLER *tmp_sh = 0; - - if (nbch->close (tmp_sh) == false) - return -1; - - return 0; -} - -template int -ACE_Connector::nonblocking_connect -(SVC_HANDLER *sh, - const ACE_Synch_Options &synch_options) -{ - ACE_TRACE ("ACE_Connector::nonblocking_connect"); - - // Must have a valid Reactor for non-blocking connects to work. - if (this->reactor () == 0) - return -1; - - // Register the pending SVC_HANDLER so that it can be activated - // later on when the connection completes. - - ACE_HANDLE handle = sh->get_handle (); - long timer_id = -1; - ACE_Time_Value *tv = 0; - NBCH *nbch = 0; - - ACE_NEW_RETURN (nbch, - NBCH (*this, - sh, - -1), - -1); - - ACE_Event_Handler_var safe_nbch (nbch); - - // Exclusive access to the Reactor. - ACE_GUARD_RETURN (ACE_Lock, ace_mon, this->reactor ()->lock (), -1); - - // Register handle with the reactor for connection events. - ACE_Reactor_Mask mask = ACE_Event_Handler::CONNECT_MASK; - if (this->reactor ()->register_handler (handle, - nbch, - mask) == -1) - goto reactor_registration_failure; - - // Add handle to non-blocking handle set. - this->non_blocking_handles ().insert (handle); - - // If we're starting connection under timer control then we need to - // schedule a timeout with the ACE_Reactor. - tv = const_cast (synch_options.time_value ()); - if (tv != 0) - { - timer_id = - this->reactor ()->schedule_timer (nbch, - synch_options.arg (), - *tv); - if (timer_id == -1) - goto timer_registration_failure; - - // Remember timer id. - nbch->timer_id (timer_id); - } - - return 0; - - // Undo previous actions using the ol' "goto label and fallthru" - // trick... - timer_registration_failure: - - // Remove from Reactor. - this->reactor ()->remove_handler (handle, mask); - - // Remove handle from the set of non-blocking handles. - this->non_blocking_handles ().remove (handle); - - /* FALLTHRU */ - - reactor_registration_failure: - // Close the svc_handler - - sh->close (CLOSE_DURING_NEW_CONNECTION); - - return -1; -} - -template -ACE_Connector::~ACE_Connector (void) -{ - ACE_TRACE ("ACE_Connector::~ACE_Connector"); - - this->close (); -} - -template void -ACE_Connector::initialize_svc_handler -(ACE_HANDLE handle, - SVC_HANDLER *svc_handler) -{ - // Try to find out if the reactor uses event associations for the - // handles it waits on. If so we need to reset it. - bool reset_new_handle = - this->reactor ()->uses_event_associations (); - - if (reset_new_handle) - this->connector_.reset_new_handle (handle); - - // Transfer ownership of the ACE_HANDLE to the SVC_HANDLER. - svc_handler->set_handle (handle); - - ACE_PEER_CONNECTOR_ADDR raddr; - - // Check to see if we're connected. - if (svc_handler->peer ().get_remote_addr (raddr) != -1) - this->activate_svc_handler (svc_handler); - else // Somethings gone wrong, so close down... - { -#if defined (ACE_WIN32) - // Win32 (at least prior to Windows 2000) has a timing problem. - // If you check to see if the connection has completed too fast, - // it will fail - so wait 35 milliseconds to let it catch up. - ACE_Time_Value tv (0, ACE_NON_BLOCKING_BUG_DELAY); - ACE_OS::sleep (tv); - if (svc_handler->peer ().get_remote_addr (raddr) != -1) - this->activate_svc_handler (svc_handler); - else // do the svc handler close below... -#endif /* ACE_WIN32 */ - svc_handler->close (NORMAL_CLOSE_OPERATION); - } -} - -template void -ACE_Connector::reactor (ACE_Reactor *reactor) -{ - this->reactor_ = reactor; -} - -template ACE_Reactor * -ACE_Connector::reactor (void) const -{ - return this->reactor_; -} - -template ACE_Unbounded_Set & -ACE_Connector::non_blocking_handles (void) -{ - return this->non_blocking_handles_; -} - -template int -ACE_Connector::close (void) -{ - // If there are no non-blocking handle pending, return immediately. - if (this->non_blocking_handles ().size () == 0) - return 0; - - // Exclusive access to the Reactor. - ACE_GUARD_RETURN (ACE_Lock, ace_mon, this->reactor ()->lock (), -1); - - // Go through all the non-blocking handles. It is necessary to - // create a new iterator each time because we remove from the handle - // set when we cancel the Svc_Handler. - ACE_HANDLE *handle = 0; - while (1) - { - ACE_Unbounded_Set_Iterator - iterator (this->non_blocking_handles ()); - if (!iterator.next (handle)) - break; - - ACE_Event_Handler *handler = - this->reactor ()->find_handler (*handle); - if (handler == 0) - { - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%t: Connector::close h %d, no handler\n"), - *handle)); - // Remove handle from the set of non-blocking handles. - this->non_blocking_handles ().remove (*handle); - continue; - } - - // find_handler() incremented handler's refcount; ensure it's decremented - ACE_Event_Handler_var safe_handler (handler); - NBCH *nbch = dynamic_cast (handler); - if (nbch == 0) - { - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%t: Connector::close h %d handler %@ ") - ACE_TEXT ("not a legit handler\n"), - *handle, - handler)); - // Remove handle from the set of non-blocking handles. - this->non_blocking_handles ().remove (*handle); - continue; - } - SVC_HANDLER *svc_handler = nbch->svc_handler (); - - // Cancel the non-blocking connection. - this->cancel (svc_handler); - - // Close the associated Svc_Handler. - svc_handler->close (NORMAL_CLOSE_OPERATION); - } - - return 0; -} - -template int -ACE_Connector::fini (void) -{ - ACE_TRACE ("ACE_Connector::fini"); - - return this->close (); -} - -// Hook called by the explicit dynamic linking facility. - -template int -ACE_Connector::init (int, ACE_TCHAR *[]) -{ - ACE_TRACE ("ACE_Connector::init"); - return -1; -} - -template int -ACE_Connector::suspend (void) -{ - ACE_TRACE ("ACE_Connector::suspend"); - return -1; -} - -template int -ACE_Connector::resume (void) -{ - ACE_TRACE ("ACE_Connector::resume"); - return -1; -} - -template int -ACE_Connector::info (ACE_TCHAR **strp, size_t length) const -{ - ACE_TRACE ("ACE_Connector::info"); - ACE_TCHAR buf[BUFSIZ]; - - ACE_OS::sprintf (buf, - ACE_TEXT ("%s\t %s"), - ACE_TEXT ("ACE_Connector"), - ACE_TEXT ("# connector factory\n")); - - if (*strp == 0 && (*strp = ACE_OS::strdup (buf)) == 0) - return -1; - else - ACE_OS::strsncpy (*strp, buf, length); - return static_cast (ACE_OS::strlen (buf)); -} - -template int -ACE_Strategy_Connector::open (ACE_Reactor *r, - int flags) -{ - ACE_TRACE ("ACE_Strategy_Connector::open"); - return this->open (r, 0, 0, 0, flags); -} - -template int -ACE_Strategy_Connector::open -(ACE_Reactor *r, - ACE_Creation_Strategy *cre_s, - ACE_Connect_Strategy *conn_s, - ACE_Concurrency_Strategy *con_s, - int flags) -{ - ACE_TRACE ("ACE_Strategy_Connector::open"); - - this->reactor (r); - - // @@ Not implemented yet. - // this->flags_ = flags; - ACE_UNUSED_ARG (flags); - - // Initialize the creation strategy. - - // First we decide if we need to clean up. - if (this->creation_strategy_ != 0 && - this->delete_creation_strategy_ && - cre_s != 0) - { - delete this->creation_strategy_; - this->creation_strategy_ = 0; - this->delete_creation_strategy_ = false; - } - - if (cre_s != 0) - this->creation_strategy_ = cre_s; - else if (this->creation_strategy_ == 0) - { - ACE_NEW_RETURN (this->creation_strategy_, - CREATION_STRATEGY, - -1); - this->delete_creation_strategy_ = true; - } - - - // Initialize the accept strategy. - - if (this->connect_strategy_ != 0 && - this->delete_connect_strategy_ && - conn_s != 0) - { - delete this->connect_strategy_; - this->connect_strategy_ = 0; - this->delete_connect_strategy_ = false; - } - - if (conn_s != 0) - this->connect_strategy_ = conn_s; - else if (this->connect_strategy_ == 0) - { - ACE_NEW_RETURN (this->connect_strategy_, - CONNECT_STRATEGY, - -1); - this->delete_connect_strategy_ = true; - } - - // Initialize the concurrency strategy. - - if (this->concurrency_strategy_ != 0 && - this->delete_concurrency_strategy_ && - con_s != 0) - { - delete this->concurrency_strategy_; - this->concurrency_strategy_ = 0; - this->delete_concurrency_strategy_ = false; - } - - if (con_s != 0) - this->concurrency_strategy_ = con_s; - else if (this->concurrency_strategy_ == 0) - { - ACE_NEW_RETURN (this->concurrency_strategy_, - CONCURRENCY_STRATEGY, - -1); - this->delete_concurrency_strategy_ = true; - } - - return 0; -} - -template -ACE_Strategy_Connector::ACE_Strategy_Connector -(ACE_Reactor *reactor, - ACE_Creation_Strategy *cre_s, - ACE_Connect_Strategy *conn_s, - ACE_Concurrency_Strategy *con_s, - int flags) - : creation_strategy_ (0), - delete_creation_strategy_ (false), - connect_strategy_ (0), - delete_connect_strategy_ (false), - concurrency_strategy_ (0), - delete_concurrency_strategy_ (false) -{ - ACE_TRACE ("ACE_Connector::ACE_Strategy_Connector"); - - if (this->open (reactor, cre_s, conn_s, con_s, flags) == -1) - ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("ACE_Strategy_Connector::ACE_Strategy_Connector"))); -} - -template -ACE_Strategy_Connector::~ACE_Strategy_Connector (void) -{ - ACE_TRACE ("ACE_Strategy_Connector::~ACE_Strategy_Connector"); - - // Close down - this->close (); -} - -template int -ACE_Strategy_Connector::close (void) -{ - if (this->delete_creation_strategy_) - delete this->creation_strategy_; - this->delete_creation_strategy_ = false; - this->creation_strategy_ = 0; - - if (this->delete_connect_strategy_) - delete this->connect_strategy_; - this->delete_connect_strategy_ = false; - this->connect_strategy_ = 0; - - if (this->delete_concurrency_strategy_) - delete this->concurrency_strategy_; - this->delete_concurrency_strategy_ = false; - this->concurrency_strategy_ = 0; - - return SUPER::close (); -} - -template int -ACE_Strategy_Connector::make_svc_handler (SVC_HANDLER *&sh) -{ - return this->creation_strategy_->make_svc_handler (sh); -} - -template int -ACE_Strategy_Connector::connect_svc_handler -(SVC_HANDLER *&sh, - const ACE_PEER_CONNECTOR_ADDR &remote_addr, - ACE_Time_Value *timeout, - const ACE_PEER_CONNECTOR_ADDR &local_addr, - int reuse_addr, - int flags, - int perms) -{ - return this->connect_strategy_->connect_svc_handler (sh, - remote_addr, - timeout, - local_addr, - reuse_addr, - flags, - perms); -} - -template int -ACE_Strategy_Connector::connect_svc_handler -(SVC_HANDLER *&sh, - SVC_HANDLER *&sh_copy, - const ACE_PEER_CONNECTOR_ADDR &remote_addr, - ACE_Time_Value *timeout, - const ACE_PEER_CONNECTOR_ADDR &local_addr, - int reuse_addr, - int flags, - int perms) -{ - return this->connect_strategy_->connect_svc_handler (sh, - sh_copy, - remote_addr, - timeout, - local_addr, - reuse_addr, - flags, - perms); -} - -template int -ACE_Strategy_Connector::activate_svc_handler (SVC_HANDLER *svc_handler) -{ - return this->concurrency_strategy_->activate_svc_handler (svc_handler, this); -} - -template ACE_Creation_Strategy * -ACE_Strategy_Connector::creation_strategy (void) const -{ - return this->creation_strategy_; -} - -template ACE_Connect_Strategy * -ACE_Strategy_Connector::connect_strategy (void) const -{ - return this->connect_strategy_; -} - -template ACE_Concurrency_Strategy * -ACE_Strategy_Connector::concurrency_strategy (void) const -{ - return this->concurrency_strategy_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_CONNECTOR_C */ diff --git a/externals/ace/Connector.h b/externals/ace/Connector.h deleted file mode 100644 index d0b98cfa923..00000000000 --- a/externals/ace/Connector.h +++ /dev/null @@ -1,569 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Connector.h - * - * $Id: Connector.h 91058 2010-07-12 08:20:09Z johnnyw $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_CONNECTOR_H -#define ACE_CONNECTOR_H - -#include /**/ "ace/pre.h" - -#include "ace/Service_Object.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Strategies_T.h" -#include "ace/Synch_Options.h" -#include "ace/Unbounded_Set.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Connector_Base - * - * @brief This base interface allows ACE_NonBlocking_Connect_Handler - * to only care about the SVC_HANDLER template parameter of the - * ACE_Connector. Otherwise, ACE_NonBlocking_Connect_Handler would - * have to be configured with all the template parameters that - * ACE_Connector is configured with. - */ -template -class ACE_Connector_Base -{ -public: - - virtual ~ACE_Connector_Base (void) {} - - /// Initialize the Svc_Handler. - virtual void initialize_svc_handler (ACE_HANDLE handle, - SVC_HANDLER *svc_handler) = 0; - - /// Return the handle set representing the non-blocking connects in - /// progress. - virtual ACE_Unbounded_Set &non_blocking_handles (void) = 0; -}; - -/** - * @class ACE_NonBlocking_Connect_Handler - * - * @brief Performs non-blocking connects on behalf of the Connector. - */ -template -class ACE_NonBlocking_Connect_Handler : public ACE_Event_Handler -{ -public: - - /// Constructor. - ACE_NonBlocking_Connect_Handler (ACE_Connector_Base &connector, - SVC_HANDLER *, - long timer_id); - - /// Destructor. - ~ACE_NonBlocking_Connect_Handler (void); - - /// Close up and return underlying SVC_HANDLER through @c sh. - /** - * If the return value is true the close was performed succesfully, - * implying that this object was removed from the reactor and thereby - * (by means of reference counting decremented to 0) deleted. - * If the return value is false, the close was not successful. - * The @c sh does not have any connection to the return - * value. The argument will return a valid svc_handler object if a - * valid one exists within the object. Returning a valid svc_handler - * pointer also invalidates the svc_handler contained in this - * object. - */ - bool close (SVC_HANDLER *&sh); - - /// Get SVC_HANDLER. - SVC_HANDLER *svc_handler (void); - - /// Get handle. - ACE_HANDLE handle (void); - - /// Set handle. - void handle (ACE_HANDLE); - - /// Get timer id. - long timer_id (void); - - /// Set timer id. - void timer_id (long timer_id); - - /// Called by ACE_Reactor when asynchronous connections fail. - virtual int handle_input (ACE_HANDLE); - - /// Called by ACE_Reactor when asynchronous connections succeed. - virtual int handle_output (ACE_HANDLE); - - /// Called by ACE_Reactor when asynchronous connections suceeds (on - /// some platforms only). - virtual int handle_exception (ACE_HANDLE fd); - - /// This method is called if a connection times out before - /// completing. - virtual int handle_timeout (const ACE_Time_Value &tv, const void *arg); - - /// Should Reactor resume us if we have been suspended before the upcall? - virtual int resume_handler (void); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - - /// Connector base. - ACE_Connector_Base &connector_; - - /// Associated SVC_HANDLER. - SVC_HANDLER *svc_handler_; - - /// Same as svc_handler_ if svc_handler_ is reference counted. - SVC_HANDLER *cleanup_svc_handler_; - - /// Associated timer id. - long timer_id_; -}; - -/** - * @class ACE_Connector - * - * @brief Generic factory for actively connecting clients and creating - * service handlers (SVC_HANDLERs). - * - * Implements the strategy for actively establishing connections with - * clients. An ACE_Connector is parameterized by concrete types that - * conform to the interfaces of PEER_CONNECTOR and SVC_HANDLER. The - * PEER_CONNECTOR is instantiated with a transport mechanism that - * actively establishes connections. The SVC_HANDLER is instantiated - * with a concrete type that performs the application-specific - * service. Both blocking and non-blocking connects are supported. - * Further, non-blocking connects support timeouts. - */ -template -class ACE_Connector : public ACE_Connector_Base, public ACE_Service_Object -{ -public: - - // Useful STL-style traits. - typedef typename SVC_HANDLER::addr_type addr_type; - typedef ACE_PEER_CONNECTOR connector_type; - typedef SVC_HANDLER handler_type; - typedef typename SVC_HANDLER::stream_type stream_type; - typedef typename ACE_PEER_CONNECTOR::PEER_ADDR peer_addr_type; - typedef ACE_PEER_CONNECTOR_ADDR ACE_PEER_ADDR_TYPEDEF; - - /** - * Initialize a connector. @a flags indicates how SVC_HANDLER's - * should be initialized prior to being activated. Right now, the - * only flag that is processed is ACE_NONBLOCK, which enabled - * non-blocking I/O on the SVC_HANDLER when it is opened. - */ - ACE_Connector (ACE_Reactor *r = ACE_Reactor::instance (), - int flags = 0); - - /** - * Initialize a connector. @a flags indicates how SVC_HANDLER's - * should be initialized prior to being activated. Right now, the - * only flag that is processed is ACE_NONBLOCK, which enabled - * non-blocking I/O on the SVC_HANDLER when it is opened. - */ - virtual int open (ACE_Reactor *r = ACE_Reactor::instance (), - int flags = 0); - - /// Shutdown a connector and release resources. - virtual ~ACE_Connector (void); - - // = Connection establishment methods. - - /** - * Initiate connection of @a svc_handler to peer at @a remote_addr - * using @a synch_options. If the caller wants to designate the - * selected @a local_addr they can (and can also insist that the - * @a local_addr be reused by passing a value @a reuse_addr == - * 1). @a flags and @a perms can be used to pass any flags that are - * needed to perform specific operations such as opening a file - * within connect with certain permissions. If the connection fails - * the hook on the @a svc_handler will be called - * automatically to prevent resource leaks. - */ - virtual int connect (SVC_HANDLER *&svc_handler, - const ACE_PEER_CONNECTOR_ADDR &remote_addr, - const ACE_Synch_Options &synch_options = ACE_Synch_Options::defaults, - const ACE_PEER_CONNECTOR_ADDR &local_addr - = (peer_addr_type &) ACE_PEER_CONNECTOR_ADDR_ANY, - int reuse_addr = 0, - int flags = O_RDWR, - int perms = 0); - - /** - * This is a variation on the previous method. On cached - * connectors the @a svc_handler_hint variable can be used as a hint - * for future lookups. Since this variable is modified in the - * context of the internal cache its use is thread-safe. But the - * actual svc_handler for the current connection is returned in the - * second parameter @a svc_handler. If the connection fails the - * hook on the @a svc_handler will be called automatically to - * prevent resource leaks. - */ - virtual int connect (SVC_HANDLER *&svc_handler_hint, - SVC_HANDLER *&svc_handler, - const ACE_PEER_CONNECTOR_ADDR &remote_addr, - const ACE_Synch_Options &synch_options = ACE_Synch_Options::defaults, - const ACE_PEER_CONNECTOR_ADDR &local_addr - = (peer_addr_type &) ACE_PEER_CONNECTOR_ADDR_ANY, - int reuse_addr = 0, - int flags = O_RDWR, - int perms = 0); - - /** - * Initiate connection of @a n @a svc_handlers to peers at - * @a remote_addrs using @a synch_options. Returns -1 if failure - * occurs and 0 otherwise. If @a failed_svc_handlers is non-NULL, a - * 1 is placed in the corresponding index of @a failed_svc_handlers - * for each that failed to connect, else a 0 is - * placed in that index. - */ - virtual int connect_n (size_t n, - SVC_HANDLER *svc_handlers[], - ACE_PEER_CONNECTOR_ADDR remote_addrs[], - ACE_TCHAR *failed_svc_handlers = 0, - const ACE_Synch_Options &synch_options = - ACE_Synch_Options::defaults); - - /** - * Cancel the @a svc_handler that was started asynchronously. Note that - * this is the only case when the Connector does not actively close - * the @a svc_handler. It is left up to the caller of to - * decide the fate of the @a svc_handler. - */ - virtual int cancel (SVC_HANDLER *svc_handler); - - /// Close down the Connector. All pending non-blocking connects are - /// canceled and the corresponding svc_handler is closed. - virtual int close (void); - - /// Return the underlying PEER_CONNECTOR object. - virtual ACE_PEER_CONNECTOR &connector (void) const; - - /// Initialize Svc_Handler. - virtual void initialize_svc_handler (ACE_HANDLE handle, - SVC_HANDLER *svc_handler); - - /// Set Reactor. - virtual void reactor (ACE_Reactor *reactor); - - /// Get Reactor. - virtual ACE_Reactor *reactor (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - // = Helpful typedefs. - typedef ACE_NonBlocking_Connect_Handler NBCH; - - // = The following two methods define the Connector's strategies for - // creating, connecting, and activating SVC_HANDLER's, respectively. - - /** - * Bridge method for creating a SVC_HANDLER. The default is to - * create a new SVC_HANDLER only if @a sh == 0, else @a sh is - * unchanged. However, subclasses can override this policy to - * perform SVC_HANDLER creation in any way that they like (such as - * creating subclass instances of SVC_HANDLER, using a singleton, - * dynamically linking the handler, etc.). Returns -1 if failure, - * else 0. - */ - virtual int make_svc_handler (SVC_HANDLER *&sh); - - /** - * Bridge method for connecting the @a svc_handler to the - * @a remote_addr. The default behavior delegates to the - * . - */ - virtual int connect_svc_handler (SVC_HANDLER *&svc_handler, - const ACE_PEER_CONNECTOR_ADDR &remote_addr, - ACE_Time_Value *timeout, - const ACE_PEER_CONNECTOR_ADDR &local_addr, - int reuse_addr, - int flags, - int perms); - virtual int connect_svc_handler (SVC_HANDLER *&svc_handler, - SVC_HANDLER *&sh_copy, - const ACE_PEER_CONNECTOR_ADDR &remote_addr, - ACE_Time_Value *timeout, - const ACE_PEER_CONNECTOR_ADDR &local_addr, - int reuse_addr, - int flags, - int perms); - - /** - * Bridge method for activating a @a svc_handler with the appropriate - * concurrency strategy. The default behavior of this method is to - * activate the SVC_HANDLER by calling its method (which - * allows the SVC_HANDLER to define its own concurrency strategy). - * However, subclasses can override this strategy to do more - * sophisticated concurrency activations (such as creating the - * SVC_HANDLER as an "active object" via multi-threading or - * multi-processing). - */ - virtual int activate_svc_handler (SVC_HANDLER *svc_handler); - - /// Creates and registers ACE_NonBlocking_Connect_Handler. - int nonblocking_connect (SVC_HANDLER *, - const ACE_Synch_Options &); - - /// Implementation of the connect methods. - virtual int connect_i (SVC_HANDLER *&svc_handler, - SVC_HANDLER **sh_copy, - const ACE_PEER_CONNECTOR_ADDR &remote_addr, - const ACE_Synch_Options &synch_options, - const ACE_PEER_CONNECTOR_ADDR &local_addr, - int reuse_addr, - int flags, - int perms); - - /// Return the handle set representing the non-blocking connects in - /// progress. - ACE_Unbounded_Set &non_blocking_handles (void); - - // = Dynamic linking hooks. - /// Default version does no work and returns -1. Must be overloaded - /// by application developer to do anything meaningful. - virtual int init (int argc, ACE_TCHAR *argv[]); - - /// Calls handle_close() to shutdown the Connector gracefully. - virtual int fini (void); - - /// Default version returns address info in @a buf. - virtual int info (ACE_TCHAR **strp, size_t length) const; - - // = Service management hooks. - /// Default version does no work and returns -1. Must be overloaded - /// by application developer to do anything meaningful. - virtual int suspend (void); - - /// Default version does no work and returns -1. Must be overloaded - /// by application developer to do anything meaningful. - virtual int resume (void); - -private: - /// This is the peer connector factory. - ACE_PEER_CONNECTOR connector_; - - /** - * Flags that indicate how SVC_HANDLER's should be initialized - * prior to being activated. Right now, the only flag that is - * processed is ACE_NONBLOCK, which enabled non-blocking I/O on - * the SVC_HANDLER when it is opened. - */ - int flags_; - - /// Pointer to the Reactor. - ACE_Reactor *reactor_; - - /// Handle set representing the non-blocking connects in progress. - ACE_Unbounded_Set non_blocking_handles_; - -}; - -/** - * @class ACE_Strategy_Connector - * - * @brief Abstract factory for creating a service handler - * (SVC_HANDLER), connecting the SVC_HANDLER, and activating the - * SVC_HANDLER. - * - * Implements a flexible and extensible set of strategies for - * actively establishing connections with clients. There are - * three main strategies: (1) creating a SVC_HANDLER, (2) - * actively initiating a new connection from the client, - * and (3) activating the SVC_HANDLER with a - * particular concurrency mechanism after the connection is established. - */ -template -class ACE_Strategy_Connector - : public ACE_Connector -{ -public: - - // Useful STL-style traits. - typedef ACE_Creation_Strategy - creation_strategy_type; - typedef ACE_Connect_Strategy - connect_strategy_type; - typedef ACE_Concurrency_Strategy - concurrency_strategy_type; - typedef ACE_Connector - base_type; - - // = Define some useful (old style) traits. - typedef ACE_Creation_Strategy - CREATION_STRATEGY; - typedef ACE_Connect_Strategy - CONNECT_STRATEGY; - typedef ACE_Concurrency_Strategy - CONCURRENCY_STRATEGY; - typedef ACE_Connector - SUPER; - - /** - * Initialize a connector. @a flags indicates how SVC_HANDLER's - * should be initialized prior to being activated. Right now, the - * only flag that is processed is ACE_NONBLOCK, which enabled - * non-blocking I/O on the SVC_HANDLER when it is opened. - */ - ACE_Strategy_Connector (ACE_Reactor *r = ACE_Reactor::instance (), - ACE_Creation_Strategy * = 0, - ACE_Connect_Strategy * = 0, - ACE_Concurrency_Strategy * = 0, - int flags = 0); - - /** - * Initialize a connector. @a flags indicates how SVC_HANDLER's - * should be initialized prior to being activated. Right now, the - * only flag that is processed is ACE_NONBLOCK, which enabled - * non-blocking I/O on the SVC_HANDLER when it is opened. - * Default strategies would be created and used. - */ - virtual int open (ACE_Reactor *r, - int flags); - - /** - * Initialize a connector. @a flags indicates how SVC_HANDLER's - * should be initialized prior to being activated. Right now, the - * only flag that is processed is ACE_NONBLOCK, which enabled - * non-blocking I/O on the SVC_HANDLER when it is opened. - */ - virtual int open (ACE_Reactor *r = ACE_Reactor::instance (), - ACE_Creation_Strategy * = 0, - ACE_Connect_Strategy * = 0, - ACE_Concurrency_Strategy * = 0, - int flags = 0); - - /// Shutdown a connector and release resources. - virtual ~ACE_Strategy_Connector (void); - - /// Close down the Connector - virtual int close (void); - - // = Strategies accessors - virtual ACE_Creation_Strategy *creation_strategy (void) const; - virtual ACE_Connect_Strategy *connect_strategy (void) const; - virtual ACE_Concurrency_Strategy *concurrency_strategy (void) const; - -protected: - // = The following three methods define the 's strategies - // for creating, connecting, and activating SVC_HANDLER's, - // respectively. - - /** - * Bridge method for creating a SVC_HANDLER. The strategy for - * creating a SVC_HANDLER are configured into the Connector via - * it's . The default is to create a new - * SVC_HANDLER only if @a sh == 0, else @a sh is unchanged. - * However, subclasses can override this policy to perform - * SVC_HANDLER creation in any way that they like (such as - * creating subclass instances of SVC_HANDLER, using a singleton, - * dynamically linking the handler, etc.). Returns -1 if failure, - * else 0. - */ - virtual int make_svc_handler (SVC_HANDLER *&sh); - - /** - * Bridge method for connecting the new connection into the - * SVC_HANDLER. The default behavior delegates to the - * in the . - */ - virtual int connect_svc_handler (SVC_HANDLER *&sh, - const ACE_PEER_CONNECTOR_ADDR &remote_addr, - ACE_Time_Value *timeout, - const ACE_PEER_CONNECTOR_ADDR &local_addr, - int reuse_addr, - int flags, - int perms); - - /** - * Bridge method for connecting the new connection into the - * SVC_HANDLER. The default behavior delegates to the - * in the . - * @a sh_copy is used to obtain a copy of the @a sh pointer, but that - * can be kept in the stack; the motivation is a bit too long to - * include here, but basically we want to modify @a sh safely, using - * the internal locks in the Connect_Strategy, while saving a TSS - * copy in @a sh_copy, usually located in the stack. - */ - virtual int connect_svc_handler (SVC_HANDLER *&sh, - SVC_HANDLER *&sh_copy, - const ACE_PEER_CONNECTOR_ADDR &remote_addr, - ACE_Time_Value *timeout, - const ACE_PEER_CONNECTOR_ADDR &local_addr, - int reuse_addr, - int flags, - int perms); - - /** - * Bridge method for activating a SVC_HANDLER with the appropriate - * concurrency strategy. The default behavior of this method is to - * activate the SVC_HANDLER by calling its method (which - * allows the SVC_HANDLER to define its own concurrency strategy). - * However, subclasses can override this strategy to do more - * sophisticated concurrency activations (such as creating the - * SVC_HANDLER as an "active object" via multi-threading or - * multi-processing). - */ - virtual int activate_svc_handler (SVC_HANDLER *svc_handler); - - // = Strategy objects. - - /// Creation strategy for an Connector. - CREATION_STRATEGY *creation_strategy_; - - /// True if Connector created the creation strategy and thus should - /// delete it, else false. - bool delete_creation_strategy_; - - /// Connect strategy for a Connector. - CONNECT_STRATEGY *connect_strategy_; - - /// True if Connector created the connect strategy and thus should - /// delete it, else false. - bool delete_connect_strategy_; - - /// Concurrency strategy for a Connector. - CONCURRENCY_STRATEGY *concurrency_strategy_; - - /// True if Connector created the concurrency strategy and thus should - /// delete it, else false. - bool delete_concurrency_strategy_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Connector.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Connector.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" - -#endif /* ACE_CONNECTOR_H */ diff --git a/externals/ace/Containers.cpp b/externals/ace/Containers.cpp deleted file mode 100644 index 244a9ad4b1b..00000000000 --- a/externals/ace/Containers.cpp +++ /dev/null @@ -1,12 +0,0 @@ -// $Id: Containers.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Containers.h" - -ACE_RCSID (ace, - Containers, - "$Id: Containers.cpp 80826 2008-03-04 14:51:23Z wotte $") - -#if !defined (__ACE_INLINE__) -#include "ace/Containers.inl" -#endif /* __ACE_INLINE__ */ - diff --git a/externals/ace/Containers.h b/externals/ace/Containers.h deleted file mode 100644 index ecff8e368e4..00000000000 --- a/externals/ace/Containers.h +++ /dev/null @@ -1,71 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Containers.h - * - * $Id: Containers.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_CONTAINERS_H -#define ACE_CONTAINERS_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template class ACE_Double_Linked_List; -template class ACE_Double_Linked_List_Iterator_Base; -template class ACE_Double_Linked_List_Iterator; -template class ACE_Double_Linked_List_Reverse_Iterator; - -/** - * @class ACE_DLList_Node - * - * @brief Base implementation of element in a DL list. Needed for - * ACE_Double_Linked_List. - */ -class ACE_Export ACE_DLList_Node -{ -public: - friend class ACE_Double_Linked_List; - friend class ACE_Double_Linked_List_Iterator_Base; - friend class ACE_Double_Linked_List_Iterator; - friend class ACE_Double_Linked_List_Reverse_Iterator; - - ACE_DLList_Node (void *i, - ACE_DLList_Node *n = 0, - ACE_DLList_Node *p = 0); - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - - void *item_; - - ACE_DLList_Node *next_; - ACE_DLList_Node *prev_; - -protected: - ACE_DLList_Node (void); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Containers.inl" -#endif /* __ACE_INLINE__ */ - -#include "ace/Containers_T.h" - -#include /**/ "ace/post.h" - -#endif /* ACE_CONTAINERS_H */ diff --git a/externals/ace/Containers.inl b/externals/ace/Containers.inl deleted file mode 100644 index 8094672a8f6..00000000000 --- a/externals/ace/Containers.inl +++ /dev/null @@ -1,25 +0,0 @@ -// -*- C++ -*- -// -// $Id: Containers.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE -ACE_DLList_Node::ACE_DLList_Node (void) - : item_ (0), - next_ (0), - prev_ (0) -{ -} - -ACE_INLINE -ACE_DLList_Node::ACE_DLList_Node (void *i, - ACE_DLList_Node *n, - ACE_DLList_Node *p) - : item_ (i), - next_ (n), - prev_ (p) -{ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Containers_T.cpp b/externals/ace/Containers_T.cpp deleted file mode 100644 index f4b6bd8a7f0..00000000000 --- a/externals/ace/Containers_T.cpp +++ /dev/null @@ -1,1932 +0,0 @@ -// $Id: Containers_T.cpp 82588 2008-08-11 13:37:41Z johnnyw $ - -#ifndef ACE_CONTAINERS_T_CPP -#define ACE_CONTAINERS_T_CPP - -#include "ace/Log_Msg.h" -#include "ace/Malloc_Base.h" -#include "ace/OS_Memory.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Containers.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Containers_T.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Bounded_Stack) - -template void -ACE_Bounded_Stack::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Bounded_Stack::dump"); -#endif /* ACE_HAS_DUMP */ -} - -template -ACE_Bounded_Stack::ACE_Bounded_Stack (size_t size) - : size_ (size), - top_ (0) -{ - ACE_NEW (this->stack_, - T[size]); - ACE_TRACE ("ACE_Bounded_Stack::ACE_Bounded_Stack"); -} - -template -ACE_Bounded_Stack::ACE_Bounded_Stack (const ACE_Bounded_Stack &s) - : size_ (s.size_), - top_ (s.top_) -{ - ACE_NEW (this->stack_, - T[s.size_]); - - ACE_TRACE ("ACE_Bounded_Stack::ACE_Bounded_Stack"); - - for (size_t i = 0; i < this->top_; i++) - this->stack_[i] = s.stack_[i]; -} - -template void -ACE_Bounded_Stack::operator= (const ACE_Bounded_Stack &s) -{ - ACE_TRACE ("ACE_Bounded_Stack::operator="); - - if (&s != this) - { - if (this->size_ < s.size_) - { - delete [] this->stack_; - ACE_NEW (this->stack_, - T[s.size_]); - this->size_ = s.size_; - } - this->top_ = s.top_; - - for (size_t i = 0; i < this->top_; i++) - this->stack_[i] = s.stack_[i]; - } -} - -template -ACE_Bounded_Stack::~ACE_Bounded_Stack (void) -{ - ACE_TRACE ("ACE_Bounded_Stack::~ACE_Bounded_Stack"); - delete [] this->stack_; -} - -// ---------------------------------------- - -ACE_ALLOC_HOOK_DEFINE(ACE_Fixed_Stack) - -template void -ACE_Fixed_Stack::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Fixed_Stack::dump"); -#endif /* ACE_HAS_DUMP */ -} - -template -ACE_Fixed_Stack::ACE_Fixed_Stack (void) - : size_ (ACE_SIZE), - top_ (0) -{ - ACE_TRACE ("ACE_Fixed_Stack::ACE_Fixed_Stack"); -} - -template -ACE_Fixed_Stack::ACE_Fixed_Stack (const ACE_Fixed_Stack &s) - : size_ (s.size_), - top_ (s.top_) -{ - ACE_TRACE ("ACE_Fixed_Stack::ACE_Fixed_Stack"); - for (size_t i = 0; i < this->top_; i++) - this->stack_[i] = s.stack_[i]; -} - -template void -ACE_Fixed_Stack::operator= (const ACE_Fixed_Stack &s) -{ - ACE_TRACE ("ACE_Fixed_Stack::operator="); - - if (&s != this) - { - this->top_ = s.top_; - - for (size_t i = 0; i < this->top_; i++) - this->stack_[i] = s.stack_[i]; - } -} - -template -ACE_Fixed_Stack::~ACE_Fixed_Stack (void) -{ - ACE_TRACE ("ACE_Fixed_Stack::~ACE_Fixed_Stack"); -} - -//---------------------------------------- - -ACE_ALLOC_HOOK_DEFINE(ACE_Unbounded_Stack) - -template void -ACE_Unbounded_Stack::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - // ACE_TRACE ("ACE_Unbounded_Stack::dump"); -#endif /* ACE_HAS_DUMP */ -} - -template -ACE_Unbounded_Stack::ACE_Unbounded_Stack (ACE_Allocator *alloc) - : head_ (0), - cur_size_ (0), - allocator_ (alloc) -{ - // ACE_TRACE ("ACE_Unbounded_Stack::ACE_Unbounded_Stack"); - if (this->allocator_ == 0) - this->allocator_ = ACE_Allocator::instance (); - - ACE_NEW_MALLOC (this->head_, - (ACE_Node *) this->allocator_->malloc (sizeof (ACE_Node)), - ACE_Node); - this->head_->next_ = this->head_; -} - -template void -ACE_Unbounded_Stack::delete_all_nodes (void) -{ - // ACE_TRACE ("ACE_Unbounded_Stack::delete_all_nodes"); - - while (this->is_empty () == 0) - { - ACE_Node *temp = this->head_->next_; - this->head_->next_ = temp->next_; - ACE_DES_FREE_TEMPLATE (temp, this->allocator_->free, - ACE_Node, ); - } - - this->cur_size_ = 0; - - ACE_ASSERT (this->head_ == this->head_->next_ - && this->is_empty ()); -} - -template void -ACE_Unbounded_Stack::copy_all_nodes (const ACE_Unbounded_Stack &s) -{ - // ACE_TRACE ("ACE_Unbounded_Stack::copy_all_nodes"); - - ACE_ASSERT (this->head_ == this->head_->next_); - - ACE_Node *temp = this->head_; - - for (ACE_Node *s_temp = s.head_->next_; - s_temp != s.head_; - s_temp = s_temp->next_) - { - ACE_Node *nptr = temp->next_; - ACE_NEW_MALLOC (temp->next_, - (ACE_Node *) this->allocator_->malloc (sizeof (ACE_Node)), - ACE_Node (s_temp->item_, nptr)); - temp = temp->next_; - } - this->cur_size_ = s.cur_size_; -} - -template -ACE_Unbounded_Stack::ACE_Unbounded_Stack (const ACE_Unbounded_Stack &s) - : head_ (0), - cur_size_ (0), - allocator_ (s.allocator_) -{ - if (this->allocator_ == 0) - this->allocator_ = ACE_Allocator::instance (); - - ACE_NEW_MALLOC (this->head_, - (ACE_Node *) this->allocator_->malloc (sizeof (ACE_Node)), - ACE_Node); - this->head_->next_ = this->head_; - - // ACE_TRACE ("ACE_Unbounded_Stack::ACE_Unbounded_Stack"); - this->copy_all_nodes (s); -} - -template void -ACE_Unbounded_Stack::operator= (const ACE_Unbounded_Stack &s) -{ - // ACE_TRACE ("ACE_Unbounded_Stack::operator="); - - if (this != &s) - { - this->delete_all_nodes (); - this->copy_all_nodes (s); - } -} - -template -ACE_Unbounded_Stack::~ACE_Unbounded_Stack (void) -{ - // ACE_TRACE ("ACE_Unbounded_Stack::~ACE_Unbounded_Stack"); - - this->delete_all_nodes (); - ACE_DES_FREE_TEMPLATE (head_, - this->allocator_->free, - ACE_Node, - ); -} - -template int -ACE_Unbounded_Stack::push (const T &new_item) -{ - // ACE_TRACE ("ACE_Unbounded_Stack::push"); - - ACE_Node *temp = 0; - - ACE_NEW_MALLOC_RETURN (temp, - static_cast *> (this->allocator_->malloc (sizeof (ACE_Node))), - ACE_Node (new_item, this->head_->next_), - -1); - this->head_->next_ = temp; - ++this->cur_size_; - return 0; -} - -template int -ACE_Unbounded_Stack::pop (T &item) -{ - // ACE_TRACE ("ACE_Unbounded_Stack::pop"); - - if (this->is_empty ()) - return -1; - else - { - ACE_Node *temp = this->head_->next_; - item = temp->item_; - this->head_->next_ = temp->next_; - - ACE_DES_FREE_TEMPLATE (temp, - this->allocator_->free, - ACE_Node, - ); - --this->cur_size_; - return 0; - } -} - -template int -ACE_Unbounded_Stack::find (const T &item) const -{ - // ACE_TRACE ("ACE_Unbounded_Stack::find"); - // Set into the dummy node. - this->head_->item_ = item; - - ACE_Node *temp = this->head_->next_; - - // Keep looping until we find the item. - while (!(temp->item_ == item)) - temp = temp->next_; - - // If we found the dummy node then it's not really there, otherwise, - // it is there. - return temp == this->head_ ? -1 : 0; -} - -template int -ACE_Unbounded_Stack::insert (const T &item) -{ - // ACE_TRACE ("ACE_Unbounded_Stack::insert"); - - if (this->find (item) == 0) - return 1; - else - return this->push (item); -} - -template int -ACE_Unbounded_Stack::remove (const T &item) -{ - // ACE_TRACE ("ACE_Unbounded_Stack::remove"); - - // Insert the item to be founded into the dummy node. - this->head_->item_ = item; - - ACE_Node *curr = this->head_; - - while (!(curr->next_->item_ == item)) - curr = curr->next_; - - if (curr->next_ == this->head_) - return -1; // Item was not found. - else - { - ACE_Node *temp = curr->next_; - // Skip over the node that we're deleting. - curr->next_ = temp->next_; - --this->cur_size_; - ACE_DES_FREE_TEMPLATE (temp, - this->allocator_->free, - ACE_Node, - ); - return 0; - } -} - -//-------------------------------------------------- -ACE_ALLOC_HOOK_DEFINE(ACE_Double_Linked_List_Iterator_Base) - -template -ACE_Double_Linked_List_Iterator_Base::ACE_Double_Linked_List_Iterator_Base (const ACE_Double_Linked_List &dll) - : current_ (0), dllist_ (&dll) -{ - // Do nothing -} - -template -ACE_Double_Linked_List_Iterator_Base::ACE_Double_Linked_List_Iterator_Base (const ACE_Double_Linked_List_Iterator_Base &iter) - : current_ (iter.current_), - dllist_ (iter.dllist_) -{ - // Do nothing -} - - -template T * -ACE_Double_Linked_List_Iterator_Base::next (void) const -{ - return this->not_done (); -} - -template int -ACE_Double_Linked_List_Iterator_Base::next (T *&ptr) const -{ - ptr = this->not_done (); - return ptr ? 1 : 0; -} - - -template int -ACE_Double_Linked_List_Iterator_Base::done (void) const -{ - return this->not_done () ? 0 : 1; -} - -template T & -ACE_Double_Linked_List_Iterator_Base::operator* (void) const -{ - return *(this->not_done ()); -} - -// @@ Is this a valid retasking? Make sure to check with Purify and -// whatnot that we're not leaking memory or doing any other screwing things. -template void -ACE_Double_Linked_List_Iterator_Base::reset (ACE_Double_Linked_List &dll) -{ - current_ = 0; - dllist_ = &dll; -} - - template int -ACE_Double_Linked_List_Iterator_Base::go_head (void) -{ - this->current_ = static_cast (dllist_->head_->next_); - return this->current_ ? 1 : 0; -} - -template int -ACE_Double_Linked_List_Iterator_Base::go_tail (void) -{ - this->current_ = static_cast (dllist_->head_->prev_); - return this->current_ ? 1 : 0; -} - -template T * -ACE_Double_Linked_List_Iterator_Base::not_done (void) const -{ - if (this->current_ != this->dllist_->head_) - return this->current_; - else - return 0; -} - -template T * -ACE_Double_Linked_List_Iterator_Base::do_advance (void) -{ - if (this->not_done ()) - { - this->current_ = static_cast (this->current_->next_); - return this->not_done (); - } - else - return 0; -} - -template T * -ACE_Double_Linked_List_Iterator_Base::do_retreat (void) -{ - if (this->not_done ()) - { - this->current_ = static_cast (this->current_->prev_); - return this->not_done (); - } - else - return 0; -} - -template void -ACE_Double_Linked_List_Iterator_Base::dump_i (void) const -{ - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("current_ = %x"), this->current_)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -} - -//-------------------------------------------------- -ACE_ALLOC_HOOK_DEFINE(ACE_Double_Linked_List_Iterator) - -template -ACE_Double_Linked_List_Iterator::ACE_Double_Linked_List_Iterator (const ACE_Double_Linked_List &dll) - : ACE_Double_Linked_List_Iterator_Base (dll) -{ - this->current_ = static_cast (dll.head_->next_); - // Advance current_ out of the null area and onto the first item in - // the list -} - -template void -ACE_Double_Linked_List_Iterator::reset (ACE_Double_Linked_List &dll) -{ - this->ACE_Double_Linked_List_Iterator_Base ::reset (dll); - this->current_ = static_cast (dll.head_->next_); - // Advance current_ out of the null area and onto the first item in - // the list -} - -template int -ACE_Double_Linked_List_Iterator::first (void) -{ - return this->go_head (); -} - -template int -ACE_Double_Linked_List_Iterator::advance (void) -{ - return this->do_advance () ? 1 : 0; -} - -template T* -ACE_Double_Linked_List_Iterator::advance_and_remove (bool dont_remove) -{ - T* item = 0; - if (dont_remove) - this->do_advance (); - else - { - item = this->next (); - this->do_advance (); - // It seems dangerous to remove nodes in an iterator, but so it goes... - ACE_Double_Linked_List *dllist = - const_cast *> (this->dllist_); - dllist->remove (item); - } - return item; -} - -template void -ACE_Double_Linked_List_Iterator::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - this->dump_i (); -#endif /* ACE_HAS_DUMP */ -} - -// Prefix advance. - -template -ACE_Double_Linked_List_Iterator & -ACE_Double_Linked_List_Iterator::operator++ (void) -{ - this->do_advance (); - return *this; -} - - -// Postfix advance. - -template -ACE_Double_Linked_List_Iterator -ACE_Double_Linked_List_Iterator::operator++ (int) -{ - ACE_Double_Linked_List_Iterator retv (*this); - this->do_advance (); - return retv; -} - - -// Prefix reverse. - -template -ACE_Double_Linked_List_Iterator & -ACE_Double_Linked_List_Iterator::operator-- (void) -{ - this->do_retreat (); - return *this; -} - - -// Postfix reverse. - -template -ACE_Double_Linked_List_Iterator -ACE_Double_Linked_List_Iterator::operator-- (int) -{ - ACE_Double_Linked_List_Iterator retv (*this); - this->do_retreat (); - return retv; -} - - -//-------------------------------------------------- -ACE_ALLOC_HOOK_DEFINE(ACE_Double_Linked_List_Reverse_Iterator) - - template -ACE_Double_Linked_List_Reverse_Iterator::ACE_Double_Linked_List_Reverse_Iterator (ACE_Double_Linked_List &dll) - : ACE_Double_Linked_List_Iterator_Base (dll) -{ - this->current_ = static_cast (dll.head_->prev_); - // Advance current_ out of the null area and onto the last item in - // the list -} - -template void -ACE_Double_Linked_List_Reverse_Iterator::reset (ACE_Double_Linked_List &dll) -{ - this->ACE_Double_Linked_List_Iterator_Base ::reset (dll); - this->current_ = static_cast (dll.head_->prev_); - // Advance current_ out of the null area and onto the last item in - // the list -} - -template int -ACE_Double_Linked_List_Reverse_Iterator::first (void) -{ - return this->go_tail (); -} - -template int -ACE_Double_Linked_List_Reverse_Iterator::advance (void) -{ - return this->do_retreat () ? 1 : 0; -} - -template T* -ACE_Double_Linked_List_Reverse_Iterator::advance_and_remove (bool dont_remove) -{ - T* item = 0; - if (dont_remove) - { - this->do_retreat (); - } - else - { - item = this->next (); - this->do_retreat (); - // It seems dangerous to remove nodes in an iterator, but so it goes... - ACE_Double_Linked_List *dllist = - const_cast *> (this->dllist_); - dllist->remove (item); - } - return item; -} - -template void -ACE_Double_Linked_List_Reverse_Iterator::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - this->dump_i (); -#endif /* ACE_HAS_DUMP */ -} - -// Prefix advance. - -template -ACE_Double_Linked_List_Reverse_Iterator & -ACE_Double_Linked_List_Reverse_Iterator::operator++ (void) -{ - this->do_retreat (); - return *this; -} - - -// Postfix advance. - -template -ACE_Double_Linked_List_Reverse_Iterator -ACE_Double_Linked_List_Reverse_Iterator::operator++ (int) -{ - ACE_Double_Linked_List_Reverse_Iterator retv (*this); - this->do_retreat (); - return retv; -} - - -// Prefix reverse. - -template -ACE_Double_Linked_List_Reverse_Iterator & -ACE_Double_Linked_List_Reverse_Iterator::operator-- (void) -{ - this->do_advance (); - return *this; -} - - -// Postfix reverse. - -template -ACE_Double_Linked_List_Reverse_Iterator -ACE_Double_Linked_List_Reverse_Iterator::operator-- (int) -{ - ACE_Double_Linked_List_Reverse_Iterator retv (*this); - this->do_advance (); - return retv; -} - - -ACE_ALLOC_HOOK_DEFINE(ACE_Double_Linked_List) - - template -ACE_Double_Linked_List:: ACE_Double_Linked_List (ACE_Allocator *alloc) - : size_ (0), allocator_ (alloc) -{ - if (this->allocator_ == 0) - this->allocator_ = ACE_Allocator::instance (); - - ACE_NEW_MALLOC (this->head_, - (T *) this->allocator_->malloc (sizeof (T)), - T); - this->init_head (); -} - -template -ACE_Double_Linked_List::ACE_Double_Linked_List (const ACE_Double_Linked_List &cx) - : allocator_ (cx.allocator_) -{ - if (this->allocator_ == 0) - this->allocator_ = ACE_Allocator::instance (); - - ACE_NEW_MALLOC (this->head_, - (T *) this->allocator_->malloc (sizeof (T)), - T); - this->init_head (); - this->copy_nodes (cx); - this->size_ = cx.size_; -} - -template void -ACE_Double_Linked_List::operator= (const ACE_Double_Linked_List &cx) -{ - if (this != &cx) - { - this->delete_nodes (); - this->copy_nodes (cx); - } -} - -template -ACE_Double_Linked_List::~ACE_Double_Linked_List (void) -{ - this->delete_nodes (); - - ACE_DES_FREE (head_, - this->allocator_->free, - T); - - this->head_ = 0; -} - -template int -ACE_Double_Linked_List::is_empty (void) const -{ - return this->size () ? 0 : 1; -} - -template int -ACE_Double_Linked_List::is_full (void) const -{ - return 0; // We have no bound. -} - -template T * -ACE_Double_Linked_List::insert_tail (T *new_item) -{ - // Insert it before , i.e., at tail. - this->insert_element (new_item, 1); - return new_item; -} - -template T * -ACE_Double_Linked_List::insert_head (T *new_item) -{ - this->insert_element (new_item); // Insert it after , i.e., at head. - return new_item; -} - -template T * -ACE_Double_Linked_List::delete_head (void) -{ - if (this->is_empty ()) - return 0; - - T *temp = static_cast (this->head_->next_); - // Detach it from the list. - this->remove_element (temp); - return temp; -} - -template T * -ACE_Double_Linked_List::delete_tail (void) -{ - if (this->is_empty ()) - return 0; - - T *temp = static_cast (this->head_->prev_); - // Detach it from the list. - this->remove_element (temp); - return temp; -} - -template void -ACE_Double_Linked_List::reset (void) -{ - this->delete_nodes (); -} - -template int -ACE_Double_Linked_List::get (T *&item, size_t slot) -{ - ACE_Double_Linked_List_Iterator iter (*this); - - for (size_t i = 0; - i < slot && !iter.done (); - i++) - iter.advance (); - - item = iter.next (); - return item ? 0 : -1; -} - -template size_t -ACE_Double_Linked_List::size (void) const -{ - return this->size_; -} - -template void -ACE_Double_Linked_List::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - // Dump the state of an object. -#endif /* ACE_HAS_DUMP */ -} - -#if 0 -template T * -ACE_Double_Linked_List::find (const T &item) -{ - for (ACE_Double_Linked_List_Iterator iter (*this); - !iter.done (); - iter.advance ()) - { - T *temp = iter.next (); - - if (*temp == item) - return temp; - } - - return 0; -} - -template int -ACE_Double_Linked_List::remove (const T &item) -{ - T *temp = this->find (item); - - if (temp != 0) - return this->remove (temp); - else - return -1; -} -#endif /* 0 */ - -template int -ACE_Double_Linked_List::remove (T *n) -{ - return this->remove_element (n); -} - -template void -ACE_Double_Linked_List::delete_nodes (void) -{ - while (! this->is_empty ()) - { - T * temp = static_cast (this->head_->next_); - this->remove_element (temp); - ACE_DES_FREE (temp, - this->allocator_->free, - T); - } -} - -template void -ACE_Double_Linked_List::copy_nodes (const ACE_Double_Linked_List &c) -{ - for (ACE_Double_Linked_List_Iterator iter (c); - !iter.done (); - iter.advance ()) - { - T* temp = 0; - ACE_NEW_MALLOC (temp, - (T *)this->allocator_->malloc (sizeof (T)), - T (*iter.next ())); - this->insert_tail (temp); - } -} - -template void -ACE_Double_Linked_List::init_head (void) -{ - this->head_->next_ = this->head_; - this->head_->prev_ = this->head_; -} - -template int -ACE_Double_Linked_List::insert_element (T *new_item, - int before, - T *old_item) -{ - if (old_item == 0) - old_item = this->head_; - - if (before) - old_item = static_cast (old_item->prev_); - - new_item->next_ = old_item->next_; - new_item->next_->prev_ = new_item; - new_item->prev_ = old_item; - old_item->next_ = new_item; - ++this->size_; - return 0; // Well, what will cause errors here? -} - -template int -ACE_Double_Linked_List::remove_element (T *item) -{ - // Notice that you have to ensure that item is an element of this - // list. We can't do much checking here. - - if (item == this->head_ || item->next_ == 0 - || item->prev_ == 0 || this->size () == 0) // Can't remove head - return -1; - - item->prev_->next_ = item->next_; - item->next_->prev_ = item->prev_; - item->next_ = item->prev_ = 0; // reset pointers to prevent double removal. - --this->size_; - return 0; -} - -//-------------------------------------------------- -ACE_ALLOC_HOOK_DEFINE(ACE_Fixed_Set) - -template size_t -ACE_Fixed_Set::size (void) const -{ - ACE_TRACE ("ACE_Fixed_Set::size"); - return this->cur_size_; -} - -template void -ACE_Fixed_Set::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Fixed_Set::dump"); -#endif /* ACE_HAS_DUMP */ -} - -template -ACE_Fixed_Set::~ACE_Fixed_Set (void) -{ - ACE_TRACE ("ACE_Fixed_Set::~ACE_Fixed_Set"); - this->cur_size_ = 0; -} - -template -ACE_Fixed_Set::ACE_Fixed_Set (const ACE_Fixed_Set &fs) - : cur_size_ (fs.cur_size_) -{ - ACE_TRACE ("ACE_Fixed_Set::ACE_Fixed_Set"); - - for (size_t i = 0, j = 0; i < fs.max_size_ && j < this->cur_size_; ++i) - if (fs.search_structure_[i].is_free_ == 0) - this->search_structure_[j++] = fs.search_structure_[i]; -} - -template void -ACE_Fixed_Set::operator= (const ACE_Fixed_Set &fs) -{ - ACE_TRACE ("ACE_Fixed_Set::operator="); - - if (this != &fs) - { - this->cur_size_ = fs.cur_size_; - - for (size_t i = 0, j = 0; i < fs.max_size_ && j < this->cur_size_; ++i) - if (fs.search_structure_[i].is_free_ == 0) - this->search_structure_[j++] = fs.search_structure_[i]; - } -} - -template -ACE_Fixed_Set::ACE_Fixed_Set (void) - : cur_size_ (0), - max_size_ (ACE_SIZE) -{ - ACE_TRACE ("ACE_Fixed_Set::ACE_Fixed_Set"); - for (size_t i = 0; i < this->max_size_; i++) - this->search_structure_[i].is_free_ = 1; -} - -template int -ACE_Fixed_Set::find (const T &item) const -{ - ACE_TRACE ("ACE_Fixed_Set::find"); - - for (size_t i = 0, j = 0; i < this->max_size_ && j < this->cur_size_; ++i) - if (this->search_structure_[i].is_free_ == 0) - { - if (this->search_structure_[i].item_ == item) - return 0; - ++j; - } - - return -1; -} - -template int -ACE_Fixed_Set::insert (const T &item) -{ - ACE_TRACE ("ACE_Fixed_Set::insert"); - ssize_t first_free = -1; // Keep track of first free slot. - size_t i; - - for (i = 0; - i < this->max_size_ && first_free == -1; - ++i) - - // First, make sure we don't allow duplicates. - - if (this->search_structure_[i].is_free_ == 0) - { - if (this->search_structure_[i].item_ == item) - return 1; - } - else - first_free = static_cast (i); - - // If we found a free spot let's reuse it. - - if (first_free > -1) - { - this->search_structure_[first_free].item_ = item; - this->search_structure_[first_free].is_free_ = 0; - this->cur_size_++; - return 0; - } - else /* No more room! */ - { - errno = ENOMEM; - return -1; - } -} - -template int -ACE_Fixed_Set::remove (const T &item) -{ - ACE_TRACE ("ACE_Fixed_Set::remove"); - - for (size_t i = 0, j = 0; - i < this->max_size_ && j < this->cur_size_; - ++i) - if (this->search_structure_[i].is_free_ == 0) - { - if (this->search_structure_[i].item_ == item) - { - // Mark this entry as being free. - this->search_structure_[i].is_free_ = 1; - - --this->cur_size_; - return 0; - } - else - ++j; - } - - return -1; -} - -//-------------------------------------------------- -ACE_ALLOC_HOOK_DEFINE(ACE_Fixed_Set_Iterator_Base) - -template void -ACE_Fixed_Set_Iterator_Base::dump_i (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Fixed_Set_Iterator_Base::dump_i"); -#endif /* ACE_HAS_DUMP */ -} - -template -ACE_Fixed_Set_Iterator_Base::ACE_Fixed_Set_Iterator_Base (ACE_Fixed_Set &s) - : s_ (s), - next_ (-1), - iterated_items_ (0) -{ - ACE_TRACE ("ACE_Fixed_Set_Iterator_Base::ACE_Fixed_Set_Iterator_Base"); - this->advance (); -} - -template int -ACE_Fixed_Set_Iterator_Base::advance (void) -{ - ACE_TRACE ("ACE_Fixed_Set_Iterator_Base::advance"); - - if (this->iterated_items_ < this->s_.cur_size_) - { - for (++this->next_; - static_cast (this->next_) < this->s_.max_size_; - ++this->next_) - if (this->s_.search_structure_[this->next_].is_free_ == 0) - { - ++this->iterated_items_; - return 1; - } - } - else - ++this->next_; - - return 0; -} - -template int -ACE_Fixed_Set_Iterator_Base::first (void) -{ - ACE_TRACE ("ACE_Fixed_Set_Iterator_Base::first"); - - next_ = -1; - iterated_items_ = 0; - return this->advance (); -} - -template int -ACE_Fixed_Set_Iterator_Base::done (void) const -{ - ACE_TRACE ("ACE_Fixed_Set_Iterator_Base::done"); - - return ! (this->iterated_items_ < this->s_.cur_size_); -} - -template int -ACE_Fixed_Set_Iterator_Base::next_i (T *&item) -{ - ACE_TRACE ("ACE_Fixed_Set_Iterator_Base::next_i"); - - if (static_cast (this->next_) < this->s_.max_size_) - do - { - if (this->s_.search_structure_[this->next_].is_free_ == 0) - { - item = &this->s_.search_structure_[this->next_].item_; - this->advance (); - return 1; - } - } - while (this->advance () == 1); - - return 0; -} - -//-------------------------------------------------- -ACE_ALLOC_HOOK_DEFINE(ACE_Fixed_Set_Iterator) - -template void -ACE_Fixed_Set_Iterator::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - this->dump_i (); -#endif /* ACE_HAS_DUMP */ -} - -template -ACE_Fixed_Set_Iterator::ACE_Fixed_Set_Iterator (ACE_Fixed_Set &s) - : ACE_Fixed_Set_Iterator_Base (s) -{ - ACE_TRACE ("ACE_Fixed_Set_Iterator::ACE_Fixed_Set_Iterator"); -} - -template int -ACE_Fixed_Set_Iterator::next (T *&item) -{ - ACE_TRACE ("ACE_Fixed_Set_Iterator::next"); - return this->next_i (item); -} - -template int -ACE_Fixed_Set_Iterator::remove (T *&item) -{ - ACE_TRACE ("ACE_Fixed_Set_Iterator::remove"); - - if (this->s_.search_structure_[this->next_].is_free_ == 0) - { - item = &this->s_.search_structure_[this->next_].item_; - this->s_.remove (*item); - --(this->iterated_items_); - return 1; - } - - return 0; -} - -template T& -ACE_Fixed_Set_Iterator::operator* (void) -{ - T *retv = 0; - - if (this->s_.search_structure_[this->next_].is_free_ == 0) - retv = &this->s_.search_structure_[this->next_].item_; - - ACE_ASSERT (retv != 0); - - return *retv; -} - -//-------------------------------------------------- -ACE_ALLOC_HOOK_DEFINE(ACE_Fixed_Set_Const_Iterator) - -template void -ACE_Fixed_Set_Const_Iterator::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - this->dump_i (); -#endif /* ACE_HAS_DUMP */ -} - -template -ACE_Fixed_Set_Const_Iterator::ACE_Fixed_Set_Const_Iterator (const ACE_Fixed_Set &s) - : ACE_Fixed_Set_Iterator_Base (s) -{ - ACE_TRACE ("ACE_Fixed_Set_Const_Iterator::ACE_Fixed_Set_Const_Iterator"); -} - -template int -ACE_Fixed_Set_Const_Iterator::next (const T *&item) -{ - ACE_TRACE ("ACE_Fixed_Set_Const_Iterator::next"); - - return this->next_i (item); -} - -template const T& -ACE_Fixed_Set_Const_Iterator::operator* (void) const -{ - const T *retv = 0; - - if (this->s_.search_structure_[this->next_].is_free_ == 0) - retv = &this->s_.search_structure_[this->next_].item_; - - ACE_ASSERT (retv != 0); - - return *retv; -} - -//-------------------------------------------------- -ACE_ALLOC_HOOK_DEFINE(ACE_Bounded_Set) - -template void -ACE_Bounded_Set::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Bounded_Set::dump"); -#endif /* ACE_HAS_DUMP */ -} - -template -ACE_Bounded_Set::~ACE_Bounded_Set (void) -{ - ACE_TRACE ("ACE_Bounded_Set::~ACE_Bounded_Set"); - delete [] this->search_structure_; -} - -template -ACE_Bounded_Set::ACE_Bounded_Set (void) - : cur_size_ (0), - max_size_ (static_cast (ACE_Bounded_Set::DEFAULT_SIZE)) -{ - ACE_TRACE ("ACE_Bounded_Set::ACE_Bounded_Set"); - - ACE_NEW (this->search_structure_, - typename ACE_Bounded_Set::Search_Structure[this->max_size_]); - - for (size_t i = 0; i < this->max_size_; ++i) - this->search_structure_[i].is_free_ = 1; -} - -template size_t -ACE_Bounded_Set::size (void) const -{ - ACE_TRACE ("ACE_Bounded_Set::size"); - return this->cur_size_; -} - -template -ACE_Bounded_Set::ACE_Bounded_Set (const ACE_Bounded_Set &bs) - : cur_size_ (bs.cur_size_), - max_size_ (bs.max_size_) -{ - ACE_TRACE ("ACE_Bounded_Set::ACE_Bounded_Set"); - - ACE_NEW (this->search_structure_, - typename ACE_Bounded_Set::Search_Structure[this->max_size_]); - - for (size_t i = 0; i < this->cur_size_; i++) - this->search_structure_[i] = bs.search_structure_[i]; -} - -template void -ACE_Bounded_Set::operator= (const ACE_Bounded_Set &bs) -{ - ACE_TRACE ("ACE_Bounded_Set::operator="); - - if (this != &bs) - { - if (this->max_size_ < bs.cur_size_) - { - delete [] this->search_structure_; - ACE_NEW (this->search_structure_, - typename ACE_Bounded_Set::Search_Structure[bs.cur_size_]); - this->max_size_ = bs.cur_size_; - } - - this->cur_size_ = bs.cur_size_; - - for (size_t i = 0; i < this->cur_size_; i++) - this->search_structure_[i] = bs.search_structure_[i]; - } -} - -template -ACE_Bounded_Set::ACE_Bounded_Set (size_t size) - : cur_size_ (0), - max_size_ (size) -{ - ACE_TRACE ("ACE_Bounded_Set::ACE_Bounded_Set"); - ACE_NEW (this->search_structure_, - typename ACE_Bounded_Set::Search_Structure[size]); - - for (size_t i = 0; i < this->max_size_; i++) - this->search_structure_[i].is_free_ = 1; -} - -template int -ACE_Bounded_Set::find (const T &item) const -{ - ACE_TRACE ("ACE_Bounded_Set::find"); - - for (size_t i = 0; i < this->cur_size_; i++) - if (this->search_structure_[i].item_ == item - && this->search_structure_[i].is_free_ == 0) - return 0; - - return -1; -} - -template int -ACE_Bounded_Set::insert (const T &item) -{ - ACE_TRACE ("ACE_Bounded_Set::insert"); - int first_free = -1; // Keep track of first free slot. - size_t i; - - for (i = 0; i < this->cur_size_; i++) - // First, make sure we don't allow duplicates. - - if (this->search_structure_[i].item_ == item - && this->search_structure_[i].is_free_ == 0) - return 1; - else if (this->search_structure_[i].is_free_ && first_free == -1) - first_free = static_cast (i); - - if (first_free > -1) // If we found a free spot let's reuse it. - { - this->search_structure_[first_free].item_ = item; - this->search_structure_[first_free].is_free_ = 0; - return 0; - } - else if (i < this->max_size_) // Insert at the end of the active portion. - { - this->search_structure_[i].item_ = item; - this->search_structure_[i].is_free_ = 0; - this->cur_size_++; - return 0; - } - else /* No more room! */ - { - errno = ENOMEM; - return -1; - } -} - -template int -ACE_Bounded_Set::remove (const T &item) -{ - ACE_TRACE ("ACE_Bounded_Set::remove"); - for (size_t i = 0; i < this->cur_size_; i++) - if (this->search_structure_[i].item_ == item) - { - // Mark this entry as being free. - this->search_structure_[i].is_free_ = 1; - - // If we just unbound the highest entry, then we need to - // figure out where the next highest active entry is. - if (i + 1 == this->cur_size_) - { - while (i > 0 && this->search_structure_[--i].is_free_) - continue; - - if (i == 0 && this->search_structure_[i].is_free_) - this->cur_size_ = 0; - else - this->cur_size_ = i + 1; - } - return 0; - } - - return -1; -} - -ACE_ALLOC_HOOK_DEFINE(ACE_Bounded_Set_Iterator) - - template void -ACE_Bounded_Set_Iterator::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Bounded_Set_Iterator::dump"); -#endif /* ACE_HAS_DUMP */ -} - -template -ACE_Bounded_Set_Iterator::ACE_Bounded_Set_Iterator (ACE_Bounded_Set &s) - : s_ (s), - next_ (-1) -{ - ACE_TRACE ("ACE_Bounded_Set_Iterator::ACE_Bounded_Set_Iterator"); - this->advance (); -} - -template int -ACE_Bounded_Set_Iterator::advance (void) -{ - ACE_TRACE ("ACE_Bounded_Set_Iterator::advance"); - - for (++this->next_; - static_cast (this->next_) < this->s_.cur_size_ - && this->s_.search_structure_[this->next_].is_free_; - ++this->next_) - continue; - - return static_cast (this->next_) < this->s_.cur_size_; -} - -template int -ACE_Bounded_Set_Iterator::first (void) -{ - ACE_TRACE ("ACE_Bounded_Set_Iterator::first"); - - next_ = -1; - return this->advance (); -} - -template int -ACE_Bounded_Set_Iterator::done (void) const -{ - ACE_TRACE ("ACE_Bounded_Set_Iterator::done"); - - return static_cast (this->next_) >= - this->s_.cur_size_; -} - -template int -ACE_Bounded_Set_Iterator::next (T *&item) -{ - ACE_TRACE ("ACE_Bounded_Set_Iterator::next"); - if (static_cast (this->next_) < this->s_.cur_size_) - { - item = &this->s_.search_structure_[this->next_].item_; - return 1; - } - else - return 0; -} - -ACE_ALLOC_HOOK_DEFINE(ACE_DNode) - - template -ACE_DNode::ACE_DNode (const T &i, ACE_DNode *n, ACE_DNode *p) - : next_ (n), prev_ (p), item_ (i) -{ -} - -template -ACE_DNode::~ACE_DNode (void) -{ -} - -// **************************************************************** - -template void -ACE_Unbounded_Stack_Iterator::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - // ACE_TRACE ("ACE_Unbounded_Stack_Iterator::dump"); -#endif /* ACE_HAS_DUMP */ -} - -template -ACE_Unbounded_Stack_Iterator::ACE_Unbounded_Stack_Iterator (ACE_Unbounded_Stack &q) - : current_ (q.head_->next_), - stack_ (q) -{ - // ACE_TRACE ("ACE_Unbounded_Stack_Iterator::ACE_Unbounded_Stack_Iterator"); -} - -template int -ACE_Unbounded_Stack_Iterator::advance (void) -{ - // ACE_TRACE ("ACE_Unbounded_Stack_Iterator::advance"); - this->current_ = this->current_->next_; - return this->current_ != this->stack_.head_; -} - -template int -ACE_Unbounded_Stack_Iterator::first (void) -{ - // ACE_TRACE ("ACE_Unbounded_Stack_Iterator::first"); - this->current_ = this->stack_.head_->next_; - return this->current_ != this->stack_.head_; -} - -template int -ACE_Unbounded_Stack_Iterator::done (void) const -{ - ACE_TRACE ("ACE_Unbounded_Stack_Iterator::done"); - - return this->current_ == this->stack_.head_; -} - -template int -ACE_Unbounded_Stack_Iterator::next (T *&item) -{ - // ACE_TRACE ("ACE_Unbounded_Stack_Iterator::next"); - if (this->current_ == this->stack_.head_) - return 0; - else - { - item = &this->current_->item_; - return 1; - } -} - - -ACE_ALLOC_HOOK_DEFINE(ACE_Ordered_MultiSet) - - - template -ACE_Ordered_MultiSet::ACE_Ordered_MultiSet (ACE_Allocator *alloc) - : head_ (0) - , tail_ (0) - , cur_size_ (0) - , allocator_ (alloc) -{ - // ACE_TRACE ("ACE_Ordered_MultiSet::ACE_Ordered_MultiSet"); - - if (this->allocator_ == 0) - this->allocator_ = ACE_Allocator::instance (); -} - -template -ACE_Ordered_MultiSet::ACE_Ordered_MultiSet (const ACE_Ordered_MultiSet &us) - : head_ (0) - , tail_ (0) - , cur_size_ (0) - , allocator_ (us.allocator_) -{ - ACE_TRACE ("ACE_Ordered_MultiSet::ACE_Ordered_MultiSet"); - - if (this->allocator_ == 0) - this->allocator_ = ACE_Allocator::instance (); - - this->copy_nodes (us); -} - -template -ACE_Ordered_MultiSet::~ACE_Ordered_MultiSet (void) -{ - // ACE_TRACE ("ACE_Ordered_MultiSet::~ACE_Ordered_MultiSet"); - - this->delete_nodes (); -} - - -template void -ACE_Ordered_MultiSet::operator= (const ACE_Ordered_MultiSet &us) -{ - ACE_TRACE ("ACE_Ordered_MultiSet::operator="); - - if (this != &us) - { - this->delete_nodes (); - this->copy_nodes (us); - } -} - - -template int -ACE_Ordered_MultiSet::insert (const T &item) -{ - // ACE_TRACE ("ACE_Ordered_MultiSet::insert"); - - return this->insert_from (item, this->head_, 0); -} - -template int -ACE_Ordered_MultiSet::insert (const T &new_item, - ITERATOR &iter) -{ - // ACE_TRACE ("ACE_Ordered_MultiSet::insert using iterator"); - - return this->insert_from (new_item, iter.current_, &iter.current_); -} - -template int -ACE_Ordered_MultiSet::remove (const T &item) -{ - // ACE_TRACE ("ACE_Ordered_MultiSet::remove"); - - ACE_DNode *node = 0; - - int result = locate (item, 0, node); - - // if we found the node, remove from list and free it - if (node && (result == 0)) - { - if (node->prev_) - node->prev_->next_ = node->next_; - else - head_ = node->next_; - - if (node->next_) - node->next_->prev_ = node->prev_; - else - tail_ = node->prev_; - - --this->cur_size_; - - ACE_DES_FREE_TEMPLATE (node, - this->allocator_->free, - ACE_DNode, - ); - return 0; - } - - return -1; -} - -template int -ACE_Ordered_MultiSet::find (const T &item, - ITERATOR &iter) const -{ - // search an occurance of item, using iterator's current position as a hint - ACE_DNode *node = iter.current_; - int const result = locate (item, node, node); - - // if we found the node, update the iterator and indicate success - if (node && (result == 0)) - { - iter.current_ = node; - return 0; - } - - return -1; -} - - - -template void -ACE_Ordered_MultiSet::reset (void) -{ - ACE_TRACE ("reset"); - - this->delete_nodes (); -} - -template void -ACE_Ordered_MultiSet::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - // ACE_TRACE ("ACE_Ordered_MultiSet::dump"); - // - // ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - // ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nhead_ = %u"), this->head_)); - // ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nhead_->next_ = %u"), this->head_->next_)); - // ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ncur_size_ = %d\n"), this->cur_size_)); - // - // T *item = 0; - // size_t count = 1; - // - // for (ACE_Ordered_MultiSet_Iterator iter (*(ACE_Ordered_MultiSet *) this); - // iter.next (item) != 0; - // iter.advance ()) - // ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("count = %d\n"), count++)); - // - // ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -template int -ACE_Ordered_MultiSet::insert_from (const T &item, ACE_DNode *position, - ACE_DNode **new_position) -{ - // ACE_TRACE ("ACE_Ordered_MultiSet::insert_from"); - - // create a new node - ACE_DNode *temp = 0; - ACE_NEW_MALLOC_RETURN (temp, - static_cast*> (this->allocator_->malloc (sizeof (ACE_DNode))), - ACE_DNode (item), - -1); - // obtain approximate location of the node - int result = locate (item, position, position); - - // if there are nodes in the multiset - if (position) - { - switch (result) - { - // insert after the approximate position - case -1: - - // if there is a following node - if (position->next_) - { - // link up with the following node - position->next_->prev_ = temp; - temp->next_ = position->next_; - } - else - // appending to the end of the set - tail_ = temp; - - // link up with the preceeding node - temp->prev_ = position; - position->next_ = temp; - - break; - - // insert before the position - case 0: - case 1: - - // if there is a preceeding node - if (position->prev_) - { - // link up with the preceeding node - position->prev_->next_ = temp; - temp->prev_ = position->prev_; - } - else - // prepending to the start of the set - head_ = temp; - - // link up with the preceeding node - temp->next_ = position; - position->prev_ = temp; - - break; - - default: - return -1; - } - } - else - { - // point the head and tail to the new node. - this->head_ = temp; - this->tail_ = temp; - } - - ++this->cur_size_; - if (new_position) - *new_position = temp; - - return 0; -} - -template int -ACE_Ordered_MultiSet::locate (const T &item, ACE_DNode *start_position, - ACE_DNode *&new_position) const -{ - if (! start_position) - start_position = this->head_; - - // If starting before the item, move forward until at or just before - // item. - while (start_position && start_position->item_ < item && - start_position->next_) - start_position = start_position->next_; - - // If starting after the item, move back until at or just after item - while (start_position && item < start_position->item_ && - start_position->prev_) - start_position = start_position->prev_; - - // Save the (approximate) location in the passed pointer. - new_position = start_position; - - // Show the location is after (1), before (-1) , or at (0) the item - if (!new_position) - return 1; - else if (item < new_position->item_) - return 1; - else if (new_position->item_ < item) - return -1; - else - return 0; -} - -// Looks for first occurance of in the ordered set, using the -// passed starting position as a hint: if there is such an instance, -// it updates the new_position pointer to point to one such node and -// returns 0; if there is no such node, then if there is a node before -// where the item would have been, it updates the new_position pointer -// to point to this node and returns -1; if there is no such node, -// then if there is a node after where the item would have been, it -// updates the new_position pointer to point to this node (or 0 if -// there is no such node) and returns 1; - -template void -ACE_Ordered_MultiSet::copy_nodes (const ACE_Ordered_MultiSet &us) -{ - ACE_DNode *insertion_point = this->head_; - - for (ACE_DNode *curr = us.head_; - curr != 0; - curr = curr->next_) - this->insert_from (curr->item_, insertion_point, &insertion_point); -} - -template void -ACE_Ordered_MultiSet::delete_nodes (void) -{ - // iterate through list, deleting nodes - for (ACE_DNode *curr = this->head_; - curr != 0; - ) - { - ACE_DNode *temp = curr; - curr = curr->next_; - ACE_DES_FREE_TEMPLATE (temp, - this->allocator_->free, - ACE_DNode, - ); - } - - this->head_ = 0; - this->tail_ = 0; - this->cur_size_ = 0; -} - -ACE_ALLOC_HOOK_DEFINE(ACE_Ordered_MultiSet_Iterator) - -template -ACE_Ordered_MultiSet_Iterator::ACE_Ordered_MultiSet_Iterator (ACE_Ordered_MultiSet &s) - : current_ (s.head_), - set_ (s) -{ - // ACE_TRACE ("ACE_Ordered_MultiSet_Iterator::ACE_Ordered_MultiSet_Iterator"); -} - -template int -ACE_Ordered_MultiSet_Iterator::next (T *&item) const -{ - // ACE_TRACE ("ACE_Ordered_MultiSet_Iterator::next"); - if (this->current_) - { - item = &this->current_->item_; - return 1; - } - - return 0; -} - -template T& -ACE_Ordered_MultiSet_Iterator::operator* (void) -{ - //ACE_TRACE ("ACE_Ordered_MultiSet_Iterator::operator*"); - T *retv = 0; - - int const result = this->next (retv); - ACE_ASSERT (result != 0); - ACE_UNUSED_ARG (result); - - return *retv; -} - -ACE_ALLOC_HOOK_DEFINE (ACE_DLList_Node) - -template T * -ACE_DLList::insert_tail (T *new_item) -{ - ACE_DLList_Node *temp1 = 0; - ACE_NEW_MALLOC_RETURN (temp1, - static_cast (this->allocator_->malloc (sizeof (ACE_DLList_Node))), - ACE_DLList_Node (new_item), - 0); - ACE_DLList_Node *temp2 = ACE_DLList_Base::insert_tail (temp1); - return (T *) (temp2 ? temp2->item_ : 0); -} - -template T * -ACE_DLList::insert_head (T *new_item) -{ - ACE_DLList_Node *temp1 = 0; - ACE_NEW_MALLOC_RETURN (temp1, - (ACE_DLList_Node *) this->allocator_->malloc (sizeof (ACE_DLList_Node)), - ACE_DLList_Node (new_item), 0); - ACE_DLList_Node *temp2 = ACE_DLList_Base::insert_head (temp1); - return (T *) (temp2 ? temp2->item_ : 0); -} - -template T * -ACE_DLList::delete_head (void) -{ - ACE_DLList_Node *temp1 = ACE_DLList_Base::delete_head (); - T *temp2 = (T *) (temp1 ? temp1->item_ : 0); - ACE_DES_FREE (temp1, - this->allocator_->free, - ACE_DLList_Node); - - return temp2; -} - -template T * -ACE_DLList::delete_tail (void) -{ - ACE_DLList_Node *temp1 = ACE_DLList_Base::delete_tail (); - T *temp2 = (T *) (temp1 ? temp1->item_ : 0); - ACE_DES_FREE (temp1, - this->allocator_->free, - ACE_DLList_Node); - return temp2; -} - -// **************************************************************** - -// Compare this array with for equality. - -template bool -ACE_Array::operator== (const ACE_Array &s) const -{ - if (this == &s) - return true; - else if (this->size () != s.size ()) - return false; - - const size_t len = s.size (); - for (size_t slot = 0; slot < len; ++slot) - if ((*this)[slot] != s[slot]) - return false; - - return true; -} - -// **************************************************************** - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_CONTAINERS_T_CPP */ diff --git a/externals/ace/Containers_T.h b/externals/ace/Containers_T.h deleted file mode 100644 index 3f5463fe3d6..00000000000 --- a/externals/ace/Containers_T.h +++ /dev/null @@ -1,2068 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Containers_T.h - * - * $Id: Containers_T.h 88975 2010-02-12 19:19:38Z johnnyw $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_CONTAINERS_T_H -#define ACE_CONTAINERS_T_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -// Need by ACE_DLList_Node. -#include "ace/Containers.h" - -// Shared with "ace/Unbounded_Set.h" -#include "ace/Node.h" - -// Backwards compatibility, please include "ace/Array_Base.h" directly. -#include "ace/Array_Base.h" - -// Backwards compatibility, please include "ace/Unbounded_Set.h" directly. -#include "ace/Unbounded_Set.h" - -// Backwards compatibility, please include "ace/Unbounded_Queue.h" directly. -#include "ace/Unbounded_Queue.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -class ACE_Allocator; - - -/** - * @class ACE_Bounded_Stack - * - * @brief Implement a generic LIFO abstract data type. - * - * This implementation of a Stack uses a bounded array - * that is allocated dynamically. The Stack interface - * provides the standard constant time push, pop, and top - * operations. - * - * Requirements and Performance Characteristics - * - Internal Structure - * Dynamic array - * - Duplicates allowed? - * Yes - * - Random access allowed? - * No - * - Search speed - * N/A - * - Insert/replace speed - * N/A - * - Iterator still valid after change to container? - * N/A - * - Frees memory for removed elements? - * No - * - Items inserted by - * Value - * - Requirements for contained type - * -# Default constructor - * -# Copy constructor - * -# operator= - * - */ -template -class ACE_Bounded_Stack -{ -public: - // = Initialization, assignment, and termination methods. - - /// Initialize a new empty stack with the provided size.. - /** - * Initialize and allocate space for a new Bounded_Stack with the provided - * size. - */ - ACE_Bounded_Stack (size_t size); - - /// Initialize the stack to be a copy of the stack provided. - /** - * Initialize the stack to be an exact copy of the Bounded_Stack provided - * as a parameter. - */ - ACE_Bounded_Stack (const ACE_Bounded_Stack &s); - - /// Assignment operator - /** - * Perform a deep copy operation using the Bounded_Stack parameter. If the - * capacity of the lhs isn't sufficient for the rhs, then the underlying data - * structure will be reallocated to accomadate the larger number of elements. - */ - void operator= (const ACE_Bounded_Stack &s); - - /// Perform actions needed when stack goes out of scope. - /** - * Deallocate the memory used by the Bounded_Stack. - */ - ~ACE_Bounded_Stack (void); - - // = Classic Stack operations. - - ///Add an element to the top of the stack. - /** - * Place a new item on top of the stack. Returns -1 if the stack - * is already full, 0 if the stack is not already full, and -1 if - * failure occurs. - */ - int push (const T &new_item); - - ///Remove an item from the top of stack. - /** - * Remove and return the top stack item. Returns -1 if the stack is - * already empty, 0 if the stack is not already empty, and -1 if - * failure occurs. - */ - int pop (T &item); - - ///Examine the contents of the top of stack. - /** - * Return top stack item without removing it. Returns -1 if the - * stack is already empty, 0 if the stack is not already empty, and - * -1 if failure occurs. - */ - int top (T &item) const; - - // = Check boundary conditions. - - /// Returns 1 if the container is empty, otherwise returns 0. - /** - * Performs constant time check to determine if the stack is empty. - */ - int is_empty (void) const; - - /// Returns 1 if the container is full, otherwise returns 0. - /** - * Performs constant time check to determine if the stack is at capacity. - */ - int is_full (void) const; - - /// The number of items in the stack. - /** - * Return the number of items currently in the stack. - */ - size_t size (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - /// Size of the dynamically allocated data. - size_t size_; - - /// Keeps track of the current top of stack. - size_t top_; - - /// Holds the stack's contents. - T *stack_; -}; - -//---------------------------------------- - - -/** - * @class ACE_Fixed_Stack - * - * @brief Implement a generic LIFO abstract data type. - * - * This implementation of a Stack uses a fixed array - * with the size fixed at instantiation time. - * - * Requirements and Performance Characteristics - * - Internal Structure - * Fixed array - * - Duplicates allowed? - * Yes - * - Random access allowed? - * No - * - Search speed - * N/A - * - Insert/replace speed - * N/A - * - Iterator still valid after change to container? - * N/A - * - Frees memory for removed elements? - * No - * - Items inserted by - * Value - * - Requirements for contained type - * -# Default constructor - * -# Copy constructor - * -# operator= - * - */ -template -class ACE_Fixed_Stack -{ -public: - // = Initialization, assignment, and termination methods. - /// Initialize a new stack so that it is empty. - /** - * Initialize an empty stack. - */ - ACE_Fixed_Stack (void); - - /// The copy constructor (performs initialization). - /** - * Initialize the stack and copy the provided stack into the current stack. - */ - ACE_Fixed_Stack (const ACE_Fixed_Stack &s); - - /// Assignment operator (performs assignment). - /** - * Perform a deep copy of the provided stack. - */ - void operator= (const ACE_Fixed_Stack &s); - - /// Perform actions needed when stack goes out of scope. - /** - * Destroy the stack. - */ - ~ACE_Fixed_Stack (void); - - // = Classic Stack operations. - - ///Constant time placement of element on top of stack. - /** - * Place a new item on top of the stack. Returns -1 if the stack - * is already full, 0 if the stack is not already full, and -1 if - * failure occurs. - */ - int push (const T &new_item); - - ///Constant time removal of top of stack. - /** - * Remove and return the top stack item. Returns -1 if the stack is - * already empty, 0 if the stack is not already empty, and -1 if - * failure occurs. - */ - int pop (T &item); - - ///Constant time examination of top of stack. - /** - * Return top stack item without removing it. Returns -1 if the - * stack is already empty, 0 if the stack is not already empty, and - * -1 if failure occurs. - */ - int top (T &item) const; - - // = Check boundary conditions. - - /// Returns 1 if the container is empty, otherwise returns 0. - /** - * Performs constant time check to see if stack is empty. - */ - int is_empty (void) const; - - /// Returns 1 if the container is full, otherwise returns 0. - /** - * Performs constant time check to see if stack is full. - */ - int is_full (void) const; - - /// The number of items in the stack. - /** - * Constant time access to the current size of the stack. - */ - size_t size (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - /// Size of the allocated data. - size_t size_; - - /// Keeps track of the current top of stack. - size_t top_; - - /// Holds the stack's contents. - T stack_[ACE_SIZE]; -}; - -//---------------------------------------- - -template class ACE_Ordered_MultiSet; -template class ACE_Ordered_MultiSet_Iterator; - -/** - * @class ACE_DNode - * - * @brief Implementation element in a bilinked list. - */ -template -class ACE_DNode -{ - friend class ACE_Ordered_MultiSet; - friend class ACE_Ordered_MultiSet_Iterator; - -public: - - /// This isn't necessary, but it keeps some compilers happy. - ~ACE_DNode (void); - -private: - - // = Initialization methods - ACE_DNode (const T &i, ACE_DNode *n = 0, ACE_DNode *p = 0); - - /// Pointer to next element in the list of {ACE_DNode}s. - ACE_DNode *next_; - - /// Pointer to previous element in the list of {ACE_DNode}s. - ACE_DNode *prev_; - - /// Current value of the item in this node. - T item_; -}; - - - -/** - * @class ACE_Unbounded_Stack - * - * @brief Implement a generic LIFO abstract data type. - * - * This implementation of an unbounded Stack uses a linked list. - * If you use the {insert} or {remove} methods you should keep - * in mind that duplicate entries aren't allowed. In general, - * therefore, you should avoid the use of these methods since - * they aren't really part of the ADT stack. The stack is implemented - * as a doubly linked list. - * - * Requirements and Performance Characteristics - * - Internal Structure - * Double linked list - * - Duplicates allowed? - * No - * - Random access allowed? - * No - * - Search speed - * Linear - * - Insert/replace speed - * Linear - * - Iterator still valid after change to container? - * Yes - * - Frees memory for removed elements? - * Yes - * - Items inserted by - * Value - * - Requirements for contained type - * -# Default constructor - * -# Copy constructor - * -# operator= - * - */ -template -class ACE_Unbounded_Stack -{ -public: - friend class ACE_Unbounded_Stack_Iterator; - - // Trait definition. - typedef ACE_Unbounded_Stack_Iterator ITERATOR; - - // = Initialization, assignment, and termination methods. - /// Initialize a new stack so that it is empty. Use user defined - /// allocation strategy if specified. - /** - * Initialize an empty stack using the user specified allocation strategy - * if provided. - */ - ACE_Unbounded_Stack (ACE_Allocator *the_allocator = 0); - - /// The copy constructor (performs initialization). - /** - * Initialize this stack to be an exact copy of {s}. - */ - ACE_Unbounded_Stack (const ACE_Unbounded_Stack &s); - - /// Assignment operator (performs assignment). - /** - * Perform a deep copy of the rhs into the lhs. - */ - void operator= (const ACE_Unbounded_Stack &s); - - /// Perform actions needed when stack goes out of scope. - /** - * Destroy the underlying list for the stack. - */ - ~ACE_Unbounded_Stack (void); - - // = Classic Stack operations. - - - ///Push an element onto the top of stack. - /** - * Place a new item on top of the stack. Returns -1 if the stack - * is already full, 0 if the stack is not already full, and -1 if - * failure occurs. - */ - int push (const T &new_item); - - ///Pop the top element of the stack. - /** - * Remove and return the top stack item. Returns -1 if the stack is - * already empty, 0 if the stack is not already empty, and -1 if - * failure occurs. - */ - int pop (T &item); - - ///Examine the top of the stack. - /** - * Return top stack item without removing it. Returns -1 if the - * stack is already empty, 0 if the stack is not already empty, and - * -1 if failure occurs. - */ - int top (T &item) const; - - // = Check boundary conditions. - - /// Returns 1 if the container is empty, otherwise returns 0. - /** - * Constant time check to see if the stack is empty. - */ - int is_empty (void) const; - - /// Returns 1 if the container is full, otherwise returns 0. - /** - * Always resturns 0 since the stack is unbounded. - */ - int is_full (void) const; - - // = Auxiliary methods (not strictly part of the Stack ADT). - - ///Linear Insert of an item. - /** - * Insert {new_item} into the Stack at the head (but doesn't allow - * duplicates). Returns -1 if failures occur, 1 if item is already - * present (i.e., no duplicates are allowed), else 0. - */ - int insert (const T &new_item); - - /// Remove @a item from the Stack. Returns 0 if it removes the item, - /// -1 if it can't find the item, and -1 if a failure occurs. - /** - * Linear remove operation. - */ - int remove (const T &item); - - /// Finds if @a item occurs the set. Returns 0 if finds, else -1. - /** - * Linear find operation. - */ - int find (const T &item) const; - - /// The number of items in the stack. - /** - * Constant time access to the current stack size. - */ - size_t size (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - /// Delete all the nodes in the stack. - void delete_all_nodes (void); - - /// Copy all nodes from {s} to {this}. - void copy_all_nodes (const ACE_Unbounded_Stack &s); - - /// Head of the linked list of Nodes. - ACE_Node *head_; - - /// Current size of the stack. - size_t cur_size_; - - /// Allocation strategy of the stack. - ACE_Allocator *allocator_; -}; - -/** - * @class ACE_Unbounded_Stack_Iterator - * - * @brief Implement an iterator over an unbounded Stack. - */ -template -class ACE_Unbounded_Stack_Iterator -{ -public: - // = Initialization method. - /// Move to the first element in the {stack}. - ACE_Unbounded_Stack_Iterator (ACE_Unbounded_Stack &stack); - - // = Iteration methods. - - /// Pass back the @a next_item that hasn't been seen in the Stack. - /// Returns 0 when all items have been seen, else 1. - int next (T *&next_item); - - /// Move forward by one element in the Stack. Returns 0 when all the - /// items in the Stack have been seen, else 1. - int advance (void); - - /// Move to the first element in the Stack. Returns 0 if the - /// Stack is empty, else 1. - int first (void); - - /// Returns 1 when all items have been seen, else 0. - int done (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - /// Pointer to the current node in the iteration. - ACE_Node *current_; - - /// Pointer to the Stack we're iterating over. - ACE_Unbounded_Stack &stack_; -}; - -template -class ACE_Double_Linked_List; - -/** - * @class ACE_Double_Linked_List_Iterator_Base - * - * @brief Implements a common base class for iterators for a double - * linked list ADT - */ -template -class ACE_Double_Linked_List_Iterator_Base -{ -public: - // = Iteration methods. - - /// Passes back the {entry} under the iterator. Returns 0 if the - /// iteration has completed, otherwise 1 - int next (T *&) const; - - /** - * @deprecated Return the address of next (current) unvisited item in - * the list. 0 if there is no more element available. - */ - T *next (void) const; - - /// Returns 1 when all items have been seen, else 0. - int done (void) const; - - /// STL-like iterator dereference operator: returns a reference - /// to the node underneath the iterator. - T & operator* (void) const ; - - /** - * Retasks the iterator to iterate over a new - * Double_Linked_List. This allows clients to reuse an iterator - * without incurring the constructor overhead. If you do use this, - * be aware that if there are more than one reference to this - * iterator, the other "clients" may be very bothered when their - * iterator changes. @@ Here be dragons. Comments? - */ - void reset (ACE_Double_Linked_List &); - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - // = Initialization methods. - - /// Constructor - ACE_Double_Linked_List_Iterator_Base (const ACE_Double_Linked_List &); - - /// Copy constructor. - ACE_Double_Linked_List_Iterator_Base (const - ACE_Double_Linked_List_Iterator_Base - &iter); - - // = Iteration methods. - /** - * Move to the first element of the list. Returns 0 if the list is - * empty, else 1. - * @note the head of the ACE_DLList is actually a null entry, so the - * first element is actually the 2n'd entry - */ - int go_head (void); - - /// Move to the last element of the list. Returns 0 if the list is - /// empty, else 1. - int go_tail (void); - - /** - * Check if we reach the end of the list. Can also be used to get - * the *current* element in the list. Return the address of the - * current item if there are still elements left , 0 if we run out - * of element. - */ - T *not_done (void) const ; - - /// Advance to the next element in the list. Return the address of the - /// next element if there are more, 0 otherwise. - T *do_advance (void); - - /// Retreat to the previous element in the list. Return the address - /// of the previous element if there are more, 0 otherwise. - T *do_retreat (void); - - /// Dump the state of an object. - void dump_i (void) const; - - /// Remember where we are. - T *current_; - - const ACE_Double_Linked_List *dllist_; -}; - -/** - * @class ACE_Double_Linked_List_Iterator - * - * @brief Implements an iterator for a double linked list ADT - * - * Iterate thru the double-linked list. This class provides - * an interface that let users access the internal element - * addresses directly. Notice {class T} must declare - * ACE_Double_Linked_List<T>, - * ACE_Double_Linked_List_Iterator_Base <T> and - * ACE_Double_Linked_List_Iterator as friend classes and class T - * should also have data members T* next_ and T* prev_. - */ -template -class ACE_Double_Linked_List_Iterator : public ACE_Double_Linked_List_Iterator_Base -{ -public: - // = Initialization method. - ACE_Double_Linked_List_Iterator (const ACE_Double_Linked_List &); - - /** - * Retasks the iterator to iterate over a new - * Double_Linked_List. This allows clients to reuse an iterator - * without incurring the constructor overhead. If you do use this, - * be aware that if there are more than one reference to this - * iterator, the other "clients" may be very bothered when their - * iterator changes. - * @@ Here be dragons. Comments? - */ - void reset (ACE_Double_Linked_List &); - - /// Move to the first element in the list. Returns 0 if the - /// list is empty, else 1. - int first (void); - - /// Move forward by one element in the list. Returns 0 when all the - /// items in the list have been seen, else 1. - int advance (void); - - /** - * Advance the iterator while removing the original item from the - * list. Return a pointer points to the original (removed) item. - * If @a dont_remove equals false, this function behaves like {advance} - * but return 0 (NULL) instead. - */ - T* advance_and_remove (bool dont_remove); - - // = STL-style iteration methods - - /// Prefix advance. - ACE_Double_Linked_List_Iterator & operator++ (void); - - /// Postfix advance. - ACE_Double_Linked_List_Iterator operator++ (int); - - /// Prefix reverse. - ACE_Double_Linked_List_Iterator & operator-- (void); - - /// Postfix reverse. - ACE_Double_Linked_List_Iterator operator-- (int); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; -}; - -/** - * @class ACE_Double_Linked_List_Reverse_Iterator - * - * @brief Implements a reverse iterator for a double linked list ADT - * - * Iterate backwards over the double-linked list. This class - * provide an interface that let users access the internal - * element addresses directly, which seems to break the - * encapsulation. Notice {class T} must declare - * ACE_Double_Linked_List<T>, - * ACE_Double_Linked_List_Iterator_Base <T> and - * ACE_Double_Linked_List_Iterator as friend classes and class T - * should also have data members T* next_ and T* prev_. - */ -template -class ACE_Double_Linked_List_Reverse_Iterator : public ACE_Double_Linked_List_Iterator_Base -{ -public: - // = Initialization method. - ACE_Double_Linked_List_Reverse_Iterator (ACE_Double_Linked_List &); - - /** - * Retasks the iterator to iterate over a new - * Double_Linked_List. This allows clients to reuse an iterator - * without incurring the constructor overhead. If you do use this, - * be aware that if there are more than one reference to this - * iterator, the other "clients" may be very bothered when their - * iterator changes. - * @@ Here be dragons. Comments? - */ - void reset (ACE_Double_Linked_List &); - - /// Move to the first element in the list. Returns 0 if the - /// list is empty, else 1. - int first (void); - - /// Move forward by one element in the list. Returns 0 when all the - /// items in the list have been seen, else 1. - int advance (void); - - /** - * Advance the iterator while removing the original item from the - * list. Return a pointer points to the original (removed) item. - * If @a dont_remove equals false, this function behaves like {advance} - * but return 0 (NULL) instead. - */ - T* advance_and_remove (bool dont_remove); - - // = STL-style iteration methods - - /// Prefix advance. - ACE_Double_Linked_List_Reverse_Iterator & operator++ (void); - - /// Postfix advance. - ACE_Double_Linked_List_Reverse_Iterator operator++ (int); - - /// Prefix reverse. - ACE_Double_Linked_List_Reverse_Iterator & operator-- (void); - - /// Postfix reverse. - ACE_Double_Linked_List_Reverse_Iterator operator-- (int); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; -}; - - -/** - * @class ACE_Double_Linked_List - * - * @brief A double-linked list implementation. - * - * This implementation of an unbounded double-linked list uses a - * circular linked list with a dummy node. It is pretty much - * like the {ACE_Unbounded_Queue} except that it allows removing - * of a specific element from a specific location. - * Notice that this class is an implementation of a very simple - * data structure. This is *NOT* a container class. You can use the - * class to implement other contains classes but it is *NOT* a - * general purpose container class. - * The parameter class *MUST* have members T* prev and T* next - * and users of this class are responsible to follow the general - * rules of using double-linked lists to maintaining the list - * integrity. - * If you need a double linked container class, use the DLList - * class which is a container but delegates to the Double_Linked_List - * class. - * - * Requirements and Performance Characteristics - * - Internal Structure - * Double Linked List - * - Duplicates allowed? - * Yes - * - Random access allowed? - * No - * - Search speed - * N/A - * - Insert/replace speed - * Linear - * - Iterator still valid after change to container? - * Yes - * - Frees memory for removed elements? - * No - * - Items inserted by - * Value - * - Requirements for contained type - * -# Default constructor - * -# Copy constructor - * -# operator= - * - */ -template -class ACE_Double_Linked_List -{ -public: - friend class ACE_Double_Linked_List_Iterator_Base; - friend class ACE_Double_Linked_List_Iterator; - friend class ACE_Double_Linked_List_Reverse_Iterator; - - // Trait definition. - typedef ACE_Double_Linked_List_Iterator ITERATOR; - typedef ACE_Double_Linked_List_Reverse_Iterator REVERSE_ITERATOR; - - // = Initialization and termination methods. - /// construction. Use user specified allocation strategy - /// if specified. - /** - * Initialize an empy list using the allocation strategy specified by the user. - * If none is specified, then use default allocation strategy. - */ - ACE_Double_Linked_List (ACE_Allocator *the_allocator = 0); - - /// Copy constructor. - /** - * Create a double linked list that is a copy of the provided - * parameter. - */ - ACE_Double_Linked_List (const ACE_Double_Linked_List &); - - /// Assignment operator. - /** - * Perform a deep copy of the provided list by first deleting the nodes of the - * lhs and then copying the nodes of the rhs. - */ - void operator= (const ACE_Double_Linked_List &); - - /// Destructor. - /** - * Clean up the memory allocated for the nodes of the list. - */ - ~ACE_Double_Linked_List (void); - - // = Check boundary conditions. - - /// Returns 1 if the container is empty, 0 otherwise. - /** - * Performs constant time check to determine if the list is empty. - */ - int is_empty (void) const; - - /// The list is unbounded, so this always returns 0. - /** - * Since the list is unbounded, the method simply returns 0. - */ - int is_full (void) const; - - // = Classic queue operations. - - /// Adds @a new_item to the tail of the list. Returns the new item - /// that was inserted. - /** - * Provides constant time insertion at the end of the list structure. - */ - T *insert_tail (T *new_item); - - /// Adds @a new_item to the head of the list.Returns the new item that - /// was inserted. - /** - * Provides constant time insertion at the head of the list. - */ - T *insert_head (T *new_item); - - /// Removes the head of the list and returns a pointer to that item. - /** - * Removes and returns the first {item} in the list. Returns - * internal node's address on success, 0 if the queue was empty. - * This method will *not* free the internal node. - */ - T* delete_head (void); - - /// Removes the tail of the list and returns a pointer to that item. - /** - * Removes and returns the last {item} in the list. Returns - * internal nodes's address on success, 0 if the queue was - * empty. This method will *not* free the internal node. - */ - T *delete_tail (void); - - // = Additional utility methods. - - ///Empty the list. - /** - * Reset the {ACE_Double_Linked_List} to be empty. - * Notice that since no one is interested in the items within, - * This operation will delete all items. - */ - void reset (void); - - /// Get the {slot}th element in the set. Returns -1 if the element - /// isn't in the range {0..{size} - 1}, else 0. - /** - * Iterates through the list to the desired index and assigns the provides pointer - * with the address of the node occupying that index. - */ - int get (T *&item, size_t slot = 0); - - /// The number of items in the queue. - /** - * Constant time call to return the current size of the list. - */ - size_t size (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Use DNode address directly. - /** - * Constant time removal of an item from the list using it's address. - */ - int remove (T *n); - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - /// Delete all the nodes in the list. - /** - * Removes and deallocates memory for all of the list nodes. - */ - void delete_nodes (void); - - /// Copy nodes from {rhs} into this list. - /** - * Copy the elements of the provided list by allocated new nodes and assigning - * them with the proper data. - */ - void copy_nodes (const ACE_Double_Linked_List &rhs); - - /// Setup header pointer. Called after we create the head node in ctor. - /** - * Initialize the head pointer so that the list has a dummy node. - */ - void init_head (void); - - ///Constant time insert a new item into the list structure. - /** - * Insert a @a new_item into the list. It will be added before - * or after @a old_item. Default is to insert the new item *after* - * {head_}. Return 0 if succeed, -1 if error occured. - */ - int insert_element (T *new_item, - int before = 0, - T *old_item = 0); - - ///Constant time delete an item from the list structure. - /** - * Remove @a item from the list. Return 0 if succeed, -1 otherwise. - * Notice that this function checks if item is {head_} and either its - * {next_} or {prev_} is NULL. The function resets item's {next_} and - * {prev_} to 0 to prevent clobbering the double-linked list if a user - * tries to remove the same node again. - */ - int remove_element (T *item); - - /// Head of the circular double-linked list. - T *head_; - - /// Size of this list. - size_t size_; - - /// Allocation Strategy of the queue. - ACE_Allocator *allocator_; -}; - - -template class ACE_DLList; -template class ACE_DLList_Iterator; -template class ACE_DLList_Reverse_Iterator; - -typedef ACE_Double_Linked_List ACE_DLList_Base; - -//typedef ACE_Double_Linked_List_Iterator -// ACE_DLList_Iterator_Base; -//typedef ACE_Double_Linked_List_Reverse_Iterator -// ACE_DLList_Reverse_Iterator_Base; -//@@ These two typedefs (inherited from James Hu's original design) -// have been removed because Sun CC 4.2 had problems with it. I guess -// having the DLList_Iterators inheriting from a class which is -// actually a typedef leads to problems. #define'ing rather than -// typedef'ing worked, but as per Carlos's reccomendation, I'm just -// replacing all references to the base classes with their actual -// type. Matt Braun (6/15/99) - -/** - * @class ACE_DLList - * - * @brief A double-linked list container class. - * - * ACE_DLList is a simple, unbounded container implemented using a - * double-linked list. It is critical to remember that ACE_DLList inherits - * from ACE_Double_Linked_List, wrapping each T pointer in a ACE_DLList_Node - * object which satisfies the next/prev pointer requirements imposed by - * ACE_Double_Linked_List. - * - * Each item inserted to an ACE_DLList is a pointer to a T object. The - * caller is responsible for lifetime of the T object. ACE_DLList takes no - * action on the T object; it is not copied on insertion and it is not - * deleted on removal from the ACE_DLList. - */ -template -class ACE_DLList : public ACE_DLList_Base -{ - friend class ACE_DLList_Node; - friend class ACE_Double_Linked_List_Iterator; - friend class ACE_DLList_Iterator; - friend class ACE_DLList_Reverse_Iterator; - -public: - - /// Delegates to ACE_Double_Linked_List. - void operator= (const ACE_DLList &l); - - /** - * @name Queue-like insert and delete methods - */ - //@{ - - /** - * Insert pointer for a new item at the tail of the list. - * - * @return Pointer to item inserted; 0 on error. - */ - T *insert_tail (T *new_item); - - /** - * Insert pointer for a new item at the head of the list. - * - * @return Pointer to item inserted; 0 on error. - */ - T *insert_head (T *new_item); - - /** - * Removes the item at the head of the list and returns its pointer. - * - * @return Pointer to previously inserted item; 0 if the list is empty, - * an error occurred, or the original pointer inserted was 0. - */ - T *delete_head (void); - - /** - * Removes the item at the tail of the list and returns its pointer. - * - * @return Pointer to previously inserted item; 0 if the list is empty, - * an error occurred, or the original pointer inserted was 0. - */ - T *delete_tail (void); - //@} - - /** - * Provide random access to any item in the list. - * - * @param item Receives a pointer to the T object pointer held at the - * specified position in the list. - * @param slot Position in the list to access. The first position is 0. - * - * @retval 0 Success; T pointer returned in item. - * @retval -1 Error, most likely slot is outside the range of the list. - */ - int get (T *&item, size_t slot = 0); - - /// Delegates to ACE_Double_Linked_List. - void dump (void) const; - - /// Delegates to ACE_Double_Linked_List. - int remove (ACE_DLList_Node *n); - - /** - * Constructor. - * - * @param the_allocator Allocator to use for allocating ACE_DLList_Node - * objects that wrap T objects for inclusion in the - * list. If 0, ACE_Allocator::instance() is used. - */ - ACE_DLList (ACE_Allocator *the_allocator = 0); - - /// Delegates to ACE_Double_Linked_List. - ACE_DLList (const ACE_DLList &l); - - /** - * Deletes all ACE_DLList_Node objects in the list starting from the head. - * No T objects referred to by the deleted ACE_DLList_Node objects are - * modified or freed. If you desire all of the T objects in the list to - * be deleted as well, code such as this should be used prior to destroying - * the ACE_DLList: - * @code - ACE_DLList list; - ... // insert dynamically allocated Items... - Item *p; - while ((p = list.delete_head()) != 0) - delete *p; - @endcode - */ - ~ACE_DLList (void); -}; - -/** - * @class ACE_DLList_Iterator - * - * @brief A double-linked list container class iterator. - * - * This implementation uses ACE_Double_Linked_List_Iterator to - * perform the logic behind this container class. It delegates - * all of its calls to ACE_Double_Linked_List_Iterator. - */ -template -class ACE_DLList_Iterator : public ACE_Double_Linked_List_Iterator -{ - - friend class ACE_DLList; - friend class ACE_DLList_Node; - -public: - - // = Initialization method. - ACE_DLList_Iterator (ACE_DLList &l); - - /** - * Retasks the iterator to iterate over a new - * Double_Linked_List. This allows clients to reuse an iterator - * without incurring the constructor overhead. If you do use this, - * be aware that if there are more than one reference to this - * iterator, the other "clients" may be very bothered when their - * iterator changes. - * @@ Here be dragons. Comments? - */ - void reset (ACE_DLList &l); - - // = Iteration methods. - /// Move forward by one element in the list. Returns 0 when all the - /// items in the list have been seen, else 1. - int advance (void); - - /// Pass back the {next_item} that hasn't been seen in the list. - /// Returns 0 when all items have been seen, else 1. - int next (T *&); - - /** - * @deprecated Delegates to ACE_Double_Linked_List_Iterator, except that - * whereas the Double_Linked_List version of next returns the node, this next - * returns the contents of the node - */ - T *next (void) const; - - /** - * Removes the current item (i.e., {next}) from the list. - * Note that DLList iterators do not support {advance_and_remove} - * directly (defined in its base class) and you will need to - * release the element returned by it. - */ - int remove (void); - - /// Delegates to ACE_Double_Linked_List_Iterator. - void dump (void) const; - -private: - ACE_DLList *list_; -}; - -/** - * @class ACE_DLList_Reverse_Iterator - * - * @brief A double-linked list container class iterator. - * - * This implementation uses ACE_Double_Linked_List_Iterator to - * perform the logic behind this container class. It delegates - * all of its calls to ACE_Double_Linked_List_Iterator. - */ -template -class ACE_DLList_Reverse_Iterator : public ACE_Double_Linked_List_Reverse_Iterator -{ - - friend class ACE_DLList; - friend class ACE_DLList_Node; - -public: - - // = Initialization method. - ACE_DLList_Reverse_Iterator (ACE_DLList &l); - - /** - * Retasks the iterator to iterate over a new - * Double_Linked_List. This allows clients to reuse an iterator - * without incurring the constructor overhead. If you do use this, - * be aware that if there are more than one reference to this - * iterator, the other "clients" may be very bothered when their - * iterator changes. - * @@ Here be dragons. Comments? - */ - void reset (ACE_DLList &l); - - // = Iteration methods. - /// Move forward by one element in the list. Returns 0 when all the - /// items in the list have been seen, else 1. - int advance (void); - - /// Pass back the {next_item} that hasn't been seen in the list. - /// Returns 0 when all items have been seen, else 1. - int next (T *&); - - /// @deprecated Delegates to ACE_Double_Linked_List_Iterator. - T *next (void) const; - - /// Removes the current item (i.e., {next}) from the list. - /// Note that DLList iterators do not support {advance_and_remove} - /// directly (defined in its base class) and you will need to - /// release the element returned by it. - int remove (void); - - /// Delegates to ACE_Double_Linked_List_Iterator. - void dump (void) const; - -private: - ACE_DLList *list_; -}; - -// Forward declaration. -template -class ACE_Fixed_Set; - -/** - * @class ACE_Fixed_Set_Iterator_Base - * - * @brief Implements a common base class for iterators for a unordered set. - */ -template -class ACE_Fixed_Set_Iterator_Base -{ -public: - // = Iteration methods. - - /// Pass back the {next_item} that hasn't been seen in the Set. - /// Returns 0 when all items have been seen, else 1. - int next (T *&next_item); - - /// Move forward by one element in the set. Returns 0 when all the - /// items in the set have been seen, else 1. - int advance (void); - - /// Move to the first element in the set. Returns 0 if the - /// set is empty, else 1. - int first (void); - - /// Returns 1 when all items have been seen, else 0. - int done (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - // = Initialization method. - ACE_Fixed_Set_Iterator_Base (ACE_Fixed_Set &s); - - /// Set we are iterating over. - ACE_Fixed_Set &s_; - - /// How far we've advanced over the set. - ssize_t next_; - - /// The number of non free items that the iterator had pointed at. - size_t iterated_items_; - - /// Dump the state of an object. - void dump_i (void) const; - - /// Pass back the {next_item} that hasn't been seen in the Set. - /// Returns 0 when all items have been seen, else 1. - int next_i (T *&next_item); -}; - -/** - * @class ACE_Fixed_Set_Iterator - * - * @brief Iterates through an unordered set. - * - * This implementation of an unordered set uses a fixed array. - * Allows deletions while iteration is occurring. - */ -template -class ACE_Fixed_Set_Iterator : public ACE_Fixed_Set_Iterator_Base -{ -public: - // = Initialization method. - ACE_Fixed_Set_Iterator (ACE_Fixed_Set &s); - - // = Iteration methods. - - /// Pass back the {next_item} that hasn't been seen in the Set. - /// Returns 0 when all items have been seen, else 1. - int next (T *&next_item); - - /// Dump the state of an object. - void dump (void) const; - - /// Remove the item where the itearetor is located at. - /// Returns 1 if it removes a item, else 0. - /// Pass back the removed {item}. - int remove (T *&item); - - /// STL-like iterator dereference operator: returns a reference - /// to the node underneath the iterator. - T & operator* (void); - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; -}; - -/** - * @class ACE_Fixed_Set_Const_Iterator - * - * @brief Iterates through a const unordered set. - * - * This implementation of an unordered set uses a fixed array. - */ -template -class ACE_Fixed_Set_Const_Iterator : public ACE_Fixed_Set_Iterator_Base -{ -public: - // = Initialization method. - ACE_Fixed_Set_Const_Iterator (const ACE_Fixed_Set &s); - - // = Iteration methods. - - /// Pass back the {next_item} that hasn't been seen in the Set. - /// Returns 0 when all items have been seen, else 1. - int next (const T *&next_item); - - /// Dump the state of an object. - void dump (void) const; - - /// STL-like iterator dereference operator: returns a reference - /// to the node underneath the iterator. - const T & operator* (void) const ; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; -}; - -/** - * @class ACE_Fixed_Set - * - * @brief Implement a simple unordered set of {T} with maximum {ACE_SIZE}. - * - * This implementation of an unordered set uses a fixed array. - * It does not allow duplicate members. The set provides linear insertion/deletion - * operations. - * - * Requirements and Performance Characteristics - * - Internal Structure - * Fixed array - * - Duplicates allowed? - * No - * - Random access allowed? - * No - * - Search speed - * Linear - * - Insert/replace speed - * Linear - * - Iterator still valid after change to container? - * Yes - * - Frees memory for removed elements? - * No - * - Items inserted by - * Value - * - Requirements for contained type - * -# Default constructor - * -# Copy constructor - * -# operator= - * -# operator== - * - */ -template -class ACE_Fixed_Set -{ -public: - friend class ACE_Fixed_Set_Iterator_Base; - friend class ACE_Fixed_Set_Iterator; - friend class ACE_Fixed_Set_Const_Iterator; - - // Trait definitions. - typedef ACE_Fixed_Set_Iterator ITERATOR; - typedef ACE_Fixed_Set_Const_Iterator CONST_ITERATOR; - - // = Initialization and termination methods. - /// Default Constructor. - /** - * Creates an empy set - */ - ACE_Fixed_Set (void); - - /// Copy constructor. - /** - * Initializes a set to be a copy of the set parameter. - */ - ACE_Fixed_Set (const ACE_Fixed_Set &); - - /// Assignment operator. - /** - * Deep copy of one set to another. - */ - void operator= (const ACE_Fixed_Set &); - - /// Destructor. - /** - * Destroys a set. - */ - ~ACE_Fixed_Set (void); - - // = Check boundary conditions. - - /// Returns 1 if the container is empty, otherwise returns 0. - /** - * Performs constant time check to determine if a set is empty. - */ - int is_empty (void) const; - - /// Returns 1 if the container is full, otherwise returns 0. - /** - * Performs a constant time check to see if the set is full. - */ - int is_full (void) const; - - // = Classic unordered set operations. - - ///Linear time insertion of an item unique to the set. - /** - * Insert @a new_item into the set (doesn't allow duplicates). - * Returns -1 if failures occur, 1 if item is already present, else - * 0. - */ - int insert (const T &new_item); - - ///Linear time removal operation of an item. - /** - * Remove first occurrence of {item} from the set. Returns 0 if - * it removes the item, -1 if it can't find the item, and -1 if a - * failure occurs. Removal doesn't reclaim memory for the @a item. - */ - int remove (const T &item); - - /// Finds if @a item occurs in the set. Returns 0 if finds, else -1. - /** - * Performs a linear find operation for the specified @a item. - */ - int find (const T &item) const; - - /// Size of the set. - /** - * Returns the current size of the set. - */ - size_t size (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - /// Holds the contents of the set. - struct - { - /// Item in the set. - T item_; - - /// Keeps track of whether this item is in use or not. - int is_free_; - } search_structure_[ACE_SIZE]; - - /// Current size of the set. - size_t cur_size_; - - /// Maximum size of the set. - size_t max_size_; -}; - -// Forward declaration. -template -class ACE_Bounded_Set; - -/** - * @class ACE_Bounded_Set_Iterator - * - * @brief Iterates through an unordered set. - * - * This implementation of an unordered set uses a Bounded array. - * Allows deletions while iteration is occurring. - */ -template -class ACE_Bounded_Set_Iterator -{ -public: - // = Initialization method. - ACE_Bounded_Set_Iterator (ACE_Bounded_Set &s); - - // = Iteration methods. - - /// Pass back the {next_item} that hasn't been seen in the Set. - /// Returns 0 when all items have been seen, else 1. - int next (T *&next_item); - - /// Move forward by one element in the set. Returns 0 when all the - /// items in the set have been seen, else 1. - int advance (void); - - /// Move to the first element in the set. Returns 0 if the - /// set is empty, else 1. - int first (void); - - /// Returns 1 when all items have been seen, else 0. - int done (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - /// Set we are iterating over. - ACE_Bounded_Set &s_; - - /// How far we've advanced over the set. - ssize_t next_; -}; - - -/** - * @class ACE_Bounded_Set - * - * @brief Implement a simple unordered set of {T} with maximum - * set at creation time. - * - * This implementation of an unordered set uses a Bounded array. - * This implementation does not allow duplicates. It provides - * linear insert/remove/find operations. Insertion/removal does not - * invalidate iterators, but caution should be taken to ensure - * expected behavior. Once initialized, the object has a maximum size - * which can only be increased by the assignment of another larger Bounded_Set. - * - * Requirements and Performance Characteristics - * - Internal Structure - * Bounded array which can grow via assignment - * - Duplicates allowed? - * No - * - Random access allowed? - * No - * - Search speed - * Linear - * - Insert/replace speed - * Linear - * - Iterator still valid after change to container? - * Yes - * - Frees memory for removed elements? - * No - * - Items inserted by - * Value - * - Requirements for contained type - * -# Default constructor - * -# Copy constructor - * -# operator= - * -# operator== - * - */ -template -class ACE_Bounded_Set -{ -public: - friend class ACE_Bounded_Set_Iterator; - - // Trait definition. - typedef ACE_Bounded_Set_Iterator ITERATOR; - - enum - { - DEFAULT_SIZE = 10 - }; - - // = Initialization and termination methods. - /// Construct a Bounded_Set using the default size. - /** - * The default constructor initializes the Bounded_Set to a maximum size - * specified by the DEFAULT_SIZE. - */ - ACE_Bounded_Set (void); - - /// Construct a Bounded_Set with the provided sizeB. - /** - * Initialize the Bounded_Set to have a maximum size equal to the size - * parameter specified. - */ - ACE_Bounded_Set (size_t size); - - /// Construct a Bounded_Set that is a copy of the provides Bounded_Set. - /** - * Initialize the Bounded_Set to be a copy of the Bounded_Set parameter. - */ - ACE_Bounded_Set (const ACE_Bounded_Set &); - - /// Assignment operator. - /** - * The assignment will make a deep copy of the Bounded_Set provided. If the - * rhs has more elements than the capacity of the lhs, then the lhs will be - * deleted and reallocated to accomadate the larger number of elements. - */ - void operator= (const ACE_Bounded_Set &); - - /// Destructor - /** - * Clean up the underlying dynamically allocated memory that is used by - * the Bounded_Set. - */ - ~ACE_Bounded_Set (void); - - // = Check boundary conditions. - - /// Returns 1 if the container is empty, otherwise returns 0. - /** - * A constant time check is performed to determine if the Bounded_Set is - * empty. - */ - int is_empty (void) const; - - /// Returns 1 if the container is full, otherwise returns 0. - /** - * Performs a constant time check to determine if the Bounded_Set is at - * capacity. - */ - int is_full (void) const; - - // = Classic unordered set operations. - - ///Inserts a new element unique to the set. - /** - * Insert @a new_item into the set (doesn't allow duplicates) in linear - * time. - * Returns -1 if failures occur, 1 if item is already present, else - * 0. - */ - int insert (const T &new_item); - - ///Finds the specified element and removes it from the set. - /** - * Remove first occurrence of @a item from the set. Returns 0 if it - * removes the item, -1 if it can't find the item, and -1 if a - * failure occurs. The linear remove operation does not reclaim the - * memory associated with the removed item. - */ - int remove (const T &item); - - /// Finds if @a item occurs in the set. Returns 0 if finds, else -1. - /** - * find preforms a linear search for {item} and returns 0 on successful - * find and -1 otherwise. - */ - int find (const T &item) const; - - /// Size of the set. - /** - * Returns a size_t representing the current size of the set. - */ - size_t size (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - struct Search_Structure - { - /// Item in the set. - T item_; - - /// Keeps track of whether this item is in use or not. - int is_free_; - }; - - /// Holds the contents of the set. - Search_Structure *search_structure_; - - /// Current size of the set. - size_t cur_size_; - - /// Maximum size of the set. - size_t max_size_; -}; - -/** - * @class ACE_Ordered_MultiSet_Iterator - * - * @brief Implement a bidirectional iterator over an ordered multiset. - * This class template requires that < operator semantics be - * defined for the parameterized type {T}, but does not impose - * any restriction on how that ordering operator is implemented. - */ -template -class ACE_Ordered_MultiSet_Iterator -{ -public: - friend class ACE_Ordered_MultiSet; - - // = Initialization method. - ACE_Ordered_MultiSet_Iterator (ACE_Ordered_MultiSet &s); - - // = Iteration methods. - - /// Pass back the {next_item} that hasn't been seen in the ordered multiset. - /// Returns 0 when all items have been seen, else 1. - int next (T *&next_item) const; - - /// Repositions the iterator at the first item in the ordered multiset - /// Returns 0 if the list is empty else 1. - int first (void); - - /// Repositions the iterator at the last item in the ordered multiset - /// Returns 0 if the list is empty else 1. - int last (void); - - /// Move forward by one element in the set. Returns 0 when all the - /// items in the set have been seen, else 1. - int advance (void); - - /// Move backward by one element in the set. Returns 0 when all the - /// items in the set have been seen, else 1. - int retreat (void); - - /// Returns 1 when all items have been seen, else 0. - int done (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Returns a reference to the internal element {this} is pointing to. - T& operator* (void); - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - - /// Pointer to the current node in the iteration. - ACE_DNode *current_; - - /// Pointer to the set we're iterating over. - ACE_Ordered_MultiSet &set_; -}; - - -/** - * @class ACE_Ordered_MultiSet - * - * @brief Implement a simple ordered multiset of {T} of unbounded size - * that allows duplicates. This class template requires that < - * operator semantics be defined for the parameterized type {T}, but - * does not impose any restriction on how that ordering operator is - * implemented. The set is implemented as a linked list. - * - * - * Requirements and Performance Characteristics - * - Internal Structure - * Double linked list - * - Duplicates allowed? - * Yes - * - Random access allowed? - * No - * - Search speed - * Linear - * - Insert/replace speed - * Linear - * - Iterator still valid after change to container? - * Yes - * - Frees memory for removed elements? - * Yes - * - Items inserted by - * Value - * - Requirements for contained type - * -# Default constructor - * -# Copy constructor - * -# operator= - * -# operator== - * -# operator< - * - * - */ -template -class ACE_Ordered_MultiSet -{ -public: - friend class ACE_Ordered_MultiSet_Iterator; - - // Trait definition. - typedef ACE_Ordered_MultiSet_Iterator ITERATOR; - - // = Initialization and termination methods. - /// Constructor. Use user specified allocation strategy - /// if specified. - /** - * Initialize the set using the allocation strategy specified. If none, use the - * default strategy. - */ - ACE_Ordered_MultiSet (ACE_Allocator *the_allocator = 0); - - /// Copy constructor. - /** - * Initialize the set to be a copy of the provided set. - */ - ACE_Ordered_MultiSet (const ACE_Ordered_MultiSet &); - - /// Destructor. - /** - * Delete the nodes of the set. - */ - ~ACE_Ordered_MultiSet (void); - - /// Assignment operator. - /** - * Delete the nodes in lhs, and copy the nodes from the rhs. - */ - void operator= (const ACE_Ordered_MultiSet &); - - // = Check boundary conditions. - - /// Returns 1 if the container is empty, otherwise returns 0. - /** - * Constant time check to determine if the set is empty. - */ - int is_empty (void) const; - - /// Size of the set. - /** - * Constant time check to determine the size of the set. - */ - size_t size (void) const; - - // = Classic unordered set operations. - - /// Insert @a new_item into the ordered multiset. - /// Returns -1 if failures occur, else 0. - /** - * Linear time, order preserving insert into the set beginning at the head. - */ - int insert (const T &new_item); - - ///Linear time insert beginning at the point specified by the provided iterator. - /** - * Insert @a new_item into the ordered multiset, starting its search at - * the node pointed to by the iterator, and if insertion was successful, - * updates the iterator to point to the newly inserted node. - * Returns -1 if failures occur, else 0. - */ - int insert (const T &new_item, ITERATOR &iter); - - /// Remove first occurrence of @a item from the set. Returns 0 if - /// it removes the item, -1 if it can't find the item. - /** - * Linear time search operation which removes the item from the set if found . - */ - int remove (const T &item); - - ///Linear find operation. - /** - * Finds first occurrence of @a item in the multiset, using the iterator's - * current position as a hint to improve performance. If find succeeds, - * it positions the iterator at that node and returns 0, or if it cannot - * locate the node, it leaves the iterator alone and just returns -1. - */ - int find (const T &item, ITERATOR &iter) const; - - /// Reset the ACE_Ordered_MultiSet to be empty. - /** - * Delete the nodes inside the set. - */ - void reset (void); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - - /** - * Insert @a item, starting its search at the position given, - * and if successful updates the passed pointer to point to - * the newly inserted item's node. - */ - int insert_from (const T &item, ACE_DNode *start_position, - ACE_DNode **new_position); - - /** - * Looks for first occurance of @a item in the ordered set, using the - * passed starting position as a hint: if there is such an instance, it - * updates the new_position pointer to point to this node and returns 0; - * if there is no such node, then if there is a node before where the - * item would have been, it updates the new_position pointer to point - * to this node and returns -1; if there is no such node, then if there - * is a node after where the item would have been, it updates the - * new_position pointer to point to this node (or 0 if there is no such - * node) and returns 1; - */ - int locate (const T &item, ACE_DNode *start_position, - ACE_DNode *&new_position) const; - - /// Delete all the nodes in the Set. - void delete_nodes (void); - - /// Copy nodes into this set. - void copy_nodes (const ACE_Ordered_MultiSet &); - - /// Head of the bilinked list of Nodes. - ACE_DNode *head_; - - /// Head of the bilinked list of Nodes. - ACE_DNode *tail_; - - /// Current size of the set. - size_t cur_size_; - - /// Allocation strategy of the set. - ACE_Allocator *allocator_; -}; - -// **************************************************************** - -/** - * @class ACE_Array - * - * @brief A dynamic array class. - * - * This class extends ACE_Array_Base, adding comparison operators. - * - * Requirements and Performance Characteristics - * - Internal Structure - * Dynamic array - * - Duplicates allowed? - * Yes - * - Random access allowed? - * Yes - * - Search speed - * N/A - * - Insert/replace speed - * O(1) - * - Iterator still valid after change to container? - * - In general, yes. - * - If array size is changed during iteration, no. - * - Frees memory for removed elements? - * No - * - Items inserted by - * Value - * - Requirements for contained type - * -# Default constructor - * -# Copy constructor - * -# operator= - * -# operator!= - * - * @sa ACE_Array_Base. This class inherits its operations and requirements. - */ -template -class ACE_Array : public ACE_Array_Base -{ -public: - // Define a "trait" - typedef T TYPE; - typedef ACE_Array_Iterator ITERATOR; - - /// Dynamically create an uninitialized array. - /** - * Initialize an empty array of the specified size using the provided - * allocation strategy. - */ - ACE_Array (size_t size = 0, - ACE_Allocator* alloc = 0); - - /// Dynamically initialize the entire array to the {default_value}. - /** - * Initialize an array the given size placing the default_value in each index. - */ - ACE_Array (size_t size, - const T &default_value, - ACE_Allocator* alloc = 0); - - ///Copy constructor. - /** - * The copy constructor performs initialization by making an exact - * copy of the contents of parameter {s}, i.e., *this == s will - * return true. - */ - ACE_Array (const ACE_Array &s); - - ///Assignment operator - /** - * Assignment operator performs an assignment by making an exact - * copy of the contents of parameter {s}, i.e., *this == s will - * return true. Note that if the {max_size_} of {array_} is >= than - * {s.max_size_} we can copy it without reallocating. However, if - * {max_size_} is < {s.max_size_} we must delete the {array_}, - * reallocate a new {array_}, and then copy the contents of {s}. - */ - void operator= (const ACE_Array &s); - - // = Compare operators - - ///Equality comparison operator. - /** - * Compare this array with {s} for equality. Two arrays are equal - * if their {size}'s are equal and all the elements from 0 .. {size} - * are equal. - */ - bool operator== (const ACE_Array &s) const; - - ///Inequality comparison operator. - /** - * Compare this array with {s} for inequality such that {*this} != - * {s} is always the complement of the boolean return value of - * {*this} == {s}. - */ - bool operator!= (const ACE_Array &s) const; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Containers_T.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Containers_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Containers_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" - -#endif /* ACE_CONTAINERS_T_H */ diff --git a/externals/ace/Containers_T.inl b/externals/ace/Containers_T.inl deleted file mode 100644 index 912c9df8bb8..00000000000 --- a/externals/ace/Containers_T.inl +++ /dev/null @@ -1,479 +0,0 @@ -// -*- C++ -*- -// -// $Id: Containers_T.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template ACE_INLINE int -ACE_Bounded_Stack::is_empty (void) const -{ - ACE_TRACE ("ACE_Bounded_Stack::is_empty"); - return this->top_ == 0; -} - -template ACE_INLINE int -ACE_Bounded_Stack::is_full (void) const -{ - ACE_TRACE ("ACE_Bounded_Stack::is_full"); - return this->top_ >= this->size_; -} - -template ACE_INLINE int -ACE_Bounded_Stack::push (const T &new_item) -{ - ACE_TRACE ("ACE_Bounded_Stack::push"); - if (this->is_full () == 0) - { - this->stack_[this->top_++] = new_item; - return 0; - } - else - return -1; -} - -template ACE_INLINE int -ACE_Bounded_Stack::pop (T &item) -{ - ACE_TRACE ("ACE_Bounded_Stack::pop"); - if (this->is_empty () == 0) - { - item = this->stack_[--this->top_]; - return 0; - } - else - return -1; -} - -template ACE_INLINE int -ACE_Bounded_Stack::top (T &item) const -{ - ACE_TRACE ("ACE_Bounded_Stack::top"); - if (this->is_empty () == 0) - { - item = this->stack_[this->top_ - 1]; - return 0; - } - else - return -1; -} - -template ACE_INLINE size_t -ACE_Bounded_Stack::size (void) const -{ - return this->size_; -} - -//---------------------------------------- - -template ACE_INLINE int -ACE_Fixed_Stack::is_empty (void) const -{ - ACE_TRACE ("ACE_Fixed_Stack::is_empty"); - return this->top_ == 0; -} - -template ACE_INLINE int -ACE_Fixed_Stack::is_full (void) const -{ - ACE_TRACE ("ACE_Fixed_Stack::is_full"); - return this->top_ >= this->size_; -} - -template ACE_INLINE int -ACE_Fixed_Stack::push (const T &new_item) -{ - ACE_TRACE ("ACE_Fixed_Stack::push"); - if (this->is_full () == 0) - { - this->stack_[this->top_++] = new_item; - return 0; - } - else - return -1; -} - -template ACE_INLINE int -ACE_Fixed_Stack::pop (T &item) -{ - ACE_TRACE ("ACE_Fixed_Stack::pop"); - if (this->is_empty () == 0) - { - item = this->stack_[--this->top_]; - return 0; - } - else - return -1; -} - -template ACE_INLINE int -ACE_Fixed_Stack::top (T &item) const -{ - ACE_TRACE ("ACE_Fixed_Stack::top"); - if (this->is_empty () == 0) - { - item = this->stack_[this->top_ - 1]; - return 0; - } - else - return -1; -} - -template ACE_INLINE size_t -ACE_Fixed_Stack::size (void) const -{ - return this->size_; -} - -template ACE_INLINE int -ACE_Unbounded_Stack::is_empty (void) const -{ - // ACE_TRACE ("ACE_Unbounded_Stack::is_empty"); - return this->head_ == this->head_->next_; -} - -template ACE_INLINE int -ACE_Unbounded_Stack::top (T &item) const -{ - ACE_TRACE ("ACE_Unbounded_Stack::top"); - if (this->is_empty () == 0) - { - item = this->head_->next_->item_; - return 0; - } - else - return -1; -} - -template ACE_INLINE int -ACE_Unbounded_Stack::is_full (void) const -{ - ACE_TRACE ("ACE_Unbounded_Stack::is_full"); - return 0; // ??? -} - -template ACE_INLINE size_t -ACE_Unbounded_Stack::size (void) const -{ - return this->cur_size_; -} - -// --- - - -// --- - -template ACE_INLINE int -ACE_Fixed_Set::is_empty (void) const -{ - ACE_TRACE ("ACE_Fixed_Set::is_empty"); - return this->cur_size_ == 0; -} - -template ACE_INLINE int -ACE_Fixed_Set::is_full (void) const -{ - ACE_TRACE ("ACE_Fixed_Set::is_full"); - return this->cur_size_ == this->max_size_; -} - -// --- - -template ACE_INLINE int -ACE_Bounded_Set::is_empty (void) const -{ - ACE_TRACE ("ACE_Bounded_Set::is_empty"); - return this->cur_size_ == 0; -} - -template ACE_INLINE int -ACE_Bounded_Set::is_full (void) const -{ - ACE_TRACE ("ACE_Bounded_Set::is_full"); - return this->cur_size_ == this->max_size_; -} - -// -- - -template ACE_INLINE int -ACE_Ordered_MultiSet_Iterator::first (void) -{ - ACE_TRACE ("ACE_Ordered_MultiSet_Iterator::first"); - current_ = set_.head_; - - return (current_ ? 1 : 0); -} - -template ACE_INLINE int -ACE_Ordered_MultiSet_Iterator::last (void) -{ - ACE_TRACE ("ACE_Ordered_MultiSet_Iterator::last"); - current_ = set_.tail_; - - return (current_ ? 1 : 0); -} - -template ACE_INLINE int -ACE_Ordered_MultiSet_Iterator::advance (void) -{ - ACE_TRACE ("ACE_Ordered_MultiSet_Iterator::advance"); - - current_ = current_ ? current_->next_ : 0; - - return (current_ ? 1 : 0); -} - -template ACE_INLINE int -ACE_Ordered_MultiSet_Iterator::retreat (void) -{ - ACE_TRACE ("ACE_Ordered_MultiSet_Iterator::retreat"); - - current_ = current_ ? current_->prev_ : 0; - - return (current_ ? 1 : 0); -} - -template ACE_INLINE int -ACE_Ordered_MultiSet_Iterator::done (void) const -{ - ACE_TRACE ("ACE_Ordered_MultiSet_Iterator::done"); - - return (current_ ? 0 : 1); -} - -template ACE_INLINE void -ACE_Ordered_MultiSet_Iterator::dump (void) const -{ -#if defined (ACE_HAS_DUMP) -// ACE_TRACE ("ACE_Ordered_MultiSet_Iterator::dump"); -#endif /* ACE_HAS_DUMP */ -} - - - -// -- - -template ACE_INLINE int -ACE_Ordered_MultiSet::is_empty (void) const -{ - ACE_TRACE ("ACE_Ordered_MultiSet::is_empty"); - return this->cur_size_ > 0 ? 0 : 1; -} - -template ACE_INLINE size_t -ACE_Ordered_MultiSet::size (void) const -{ -// ACE_TRACE ("ACE_Ordered_MultiSet::size"); - return this->cur_size_; -} - -// **************************************************************** - -template ACE_INLINE -ACE_Array::ACE_Array (size_t size, - ACE_Allocator *alloc) - : ACE_Array_Base (size, alloc) -{ -} - -template ACE_INLINE -ACE_Array::ACE_Array (size_t size, - const T &default_value, - ACE_Allocator *alloc) - : ACE_Array_Base (size, default_value, alloc) -{ -} - -// The copy constructor (performs initialization). - -template ACE_INLINE -ACE_Array::ACE_Array (const ACE_Array &s) - : ACE_Array_Base (s) -{ -} - -// Assignment operator (performs assignment). - -template ACE_INLINE void -ACE_Array::operator= (const ACE_Array &s) -{ - // Check for "self-assignment". - - if (this != &s) - this->ACE_Array_Base::operator= (s); -} - -// Compare this array with for inequality. - -template ACE_INLINE bool -ACE_Array::operator!= (const ACE_Array &s) const -{ - return !(*this == s); -} - -// **************************************************************** - - -// **************************************************************** - -template ACE_INLINE void -ACE_DLList::operator= (const ACE_DLList &l) -{ - *(ACE_DLList_Base *) this = l; -} - -template ACE_INLINE int -ACE_DLList::get (T *&item, size_t index) -{ - ACE_DLList_Node *node; - int result = ACE_DLList_Base::get (node, index); - if (result != -1) - item = (T *) node->item_; - return result; -} - -template ACE_INLINE void -ACE_DLList::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_DLList_Base::dump (); -#endif /* ACE_HAS_DUMP */ -} - -template ACE_INLINE int -ACE_DLList::remove (ACE_DLList_Node *n) -{ - int result = ACE_DLList_Base::remove (n); - ACE_DES_FREE (n, - this->allocator_->free, - ACE_DLList_Node); - return result; -} - -template ACE_INLINE -ACE_DLList::ACE_DLList (ACE_Allocator *alloc) - : ACE_DLList_Base (alloc) -{ -} - -template ACE_INLINE -ACE_DLList::ACE_DLList (const ACE_DLList &l) - : ACE_DLList_Base ((ACE_DLList &) l) -{ -} - -template ACE_INLINE -ACE_DLList::~ACE_DLList (void) -{ - while (this->delete_head ()) ; -} - -template ACE_INLINE int -ACE_DLList_Iterator::remove (void) -{ - ACE_DLList_Node *temp = this->ACE_Double_Linked_List_Iterator ::next (); - this->ACE_Double_Linked_List_Iterator ::advance (); - return list_->remove (temp); -} - -template ACE_INLINE -ACE_DLList_Iterator::ACE_DLList_Iterator (ACE_DLList &l) - : ACE_Double_Linked_List_Iterator ((ACE_DLList_Base &)l), - list_ (&l) -{ -} - -template ACE_INLINE void -ACE_DLList_Iterator::reset (ACE_DLList &l) -{ - list_ = &l; - this->ACE_Double_Linked_List_Iterator ::reset ((ACE_DLList_Base &)l); -} - -template ACE_INLINE int -ACE_DLList_Iterator::next (T *&ptr) -{ - ACE_DLList_Node *temp = - ACE_Double_Linked_List_Iterator ::next (); - if (temp) - ptr = (T *) temp->item_; - return temp ? 1 : 0; -} - -template ACE_INLINE T * -ACE_DLList_Iterator::next (void) const -{ - ACE_DLList_Node *temp = ACE_Double_Linked_List_Iterator ::next (); - return (T *) (temp ? temp->item_ : 0); -} - -template ACE_INLINE int -ACE_DLList_Iterator::advance (void) -{ - return this->ACE_Double_Linked_List_Iterator ::advance (); -} - -template ACE_INLINE void -ACE_DLList_Iterator::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_Double_Linked_List_Iterator ::dump (); -#endif /* ACE_HAS_DUMP */ -} - - -template ACE_INLINE int -ACE_DLList_Reverse_Iterator::remove (void) -{ - ACE_DLList_Node *temp = ACE_Double_Linked_List_Reverse_Iterator ::next (); - this->ACE_Double_Linked_List_Reverse_Iterator ::advance (); - return list_->remove (temp); -} - -template ACE_INLINE -ACE_DLList_Reverse_Iterator::ACE_DLList_Reverse_Iterator (ACE_DLList &l) - : ACE_Double_Linked_List_Reverse_Iterator ((ACE_DLList_Base &)l), - list_ (&l) -{ -} - -template ACE_INLINE void -ACE_DLList_Reverse_Iterator::reset (ACE_DLList &l) -{ - list_ = &l; - this->ACE_Double_Linked_List_Reverse_Iterator ::reset ((ACE_DLList_Base &)l); -} - -template ACE_INLINE int -ACE_DLList_Reverse_Iterator::advance (void) -{ - return ACE_Double_Linked_List_Reverse_Iterator ::advance (); -} - -template ACE_INLINE int -ACE_DLList_Reverse_Iterator::next (T *&ptr) -{ - ACE_DLList_Node *temp = - ACE_Double_Linked_List_Reverse_Iterator ::next (); - if (temp == 0) - return 0; - ptr = (T *) temp->item_; - return 1; -} - -template ACE_INLINE T * -ACE_DLList_Reverse_Iterator::next (void) const -{ - ACE_DLList_Node *temp = ACE_Double_Linked_List_Reverse_Iterator ::next (); - return (T *) (temp ? temp->item_ : 0); -} - - -template ACE_INLINE void -ACE_DLList_Reverse_Iterator::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_Double_Linked_List_Reverse_Iterator ::dump (); -#endif /* ACE_HAS_DUMP */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Copy_Disabled.cpp b/externals/ace/Copy_Disabled.cpp deleted file mode 100644 index 6878311197d..00000000000 --- a/externals/ace/Copy_Disabled.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/** - * @file Copy_Disabled.cpp - * - * $Id: Copy_Disabled.cpp 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Carlos O'Ryan - */ - -#include "ace/Copy_Disabled.h" - - -ACE_RCSID (ace, - Copy_Disabled, - "$Id: Copy_Disabled.cpp 80826 2008-03-04 14:51:23Z wotte $") - - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_Copy_Disabled::ACE_Copy_Disabled (void) -{ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Copy_Disabled.h b/externals/ace/Copy_Disabled.h deleted file mode 100644 index f7b40e26422..00000000000 --- a/externals/ace/Copy_Disabled.h +++ /dev/null @@ -1,65 +0,0 @@ -// -*- C++ -*- - -//=========================================================================== -/** - * @file Copy_Disabled.h - * - * $Id: Copy_Disabled.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Carlos O'Ryan - */ -//=========================================================================== - -#ifndef ACE_COPY_DISABLED_H -#define ACE_COPY_DISABLED_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Copy_Disabled - * - * @brief Helper class to disable copy construction and assignment - * - * Classes used to control OS and other resources are not "canonical", - * i.e. they have their copy constructor and assignment operators - * disabled. - * This is often done by making the copy constructor and assignment - * operators private, effectively disallowing copying by clients of - * the class (including derived classes). If the copy constructor and - * assingment operators are left unimplemented then the class itself - * cannot make any copies of its instances, because it would result in - * link errors. - * - * To use this class simply use private inheritance: - * - * class Foo : private ACE_Copy_Disabled - * { - * // code here - * }; - * - */ -class ACE_Export ACE_Copy_Disabled -{ -public: - - /// Default constructor - ACE_Copy_Disabled (void); - -private: - ACE_Copy_Disabled (const ACE_Copy_Disabled &); - ACE_Copy_Disabled &operator= (const ACE_Copy_Disabled &); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" - -#endif /* ACE_COPY_DISABLED_H */ diff --git a/externals/ace/Countdown_Time.cpp b/externals/ace/Countdown_Time.cpp deleted file mode 100644 index d76a0fa4cf5..00000000000 --- a/externals/ace/Countdown_Time.cpp +++ /dev/null @@ -1,59 +0,0 @@ -#include "ace/Countdown_Time.h" -#include "ace/OS_NS_sys_time.h" - -ACE_RCSID (ace, - Countdown_Time, - "$Id: Countdown_Time.cpp 85382 2009-05-19 06:52:56Z johnnyw $") - -#if !defined (__ACE_INLINE__) -#include "ace/Countdown_Time.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_Countdown_Time::ACE_Countdown_Time (ACE_Time_Value *max_wait_time) - : max_wait_time_ (max_wait_time), - stopped_ (false) -{ - this->start (); -} - -ACE_Countdown_Time::~ACE_Countdown_Time (void) -{ - this->stop (); -} - -void -ACE_Countdown_Time::start (void) -{ - if (this->max_wait_time_ != 0) - { - this->start_time_ = ACE_OS::gettimeofday (); - this->stopped_ = false; - } -} - -void -ACE_Countdown_Time::stop (void) -{ - if (this->max_wait_time_ != 0 && !this->stopped_) - { - ACE_Time_Value const elapsed_time = - ACE_OS::gettimeofday () - this->start_time_; - - if (elapsed_time >= ACE_Time_Value::zero && - *this->max_wait_time_ > elapsed_time) - { - *this->max_wait_time_ -= elapsed_time; - } - else - { - // Used all of timeout. - *this->max_wait_time_ = ACE_Time_Value::zero; - // errno = ETIME; - } - this->stopped_ = true; - } -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Countdown_Time.h b/externals/ace/Countdown_Time.h deleted file mode 100644 index b9c9a467f62..00000000000 --- a/externals/ace/Countdown_Time.h +++ /dev/null @@ -1,81 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Countdown_Time.h - * - * $Id: Countdown_Time.h 85365 2009-05-18 08:27:42Z johnnyw $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_COUNTDOWN_TIME_H -#define ACE_COUNTDOWN_TIME_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Time_Value.h" -#include "ace/Copy_Disabled.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Countdown_Time - * - * @brief Keeps track of the amount of elapsed time. - * - * This class has a side-effect on the @c max_wait_time -- every - * time the stop() method is called the @c max_wait_time is - * updated. - */ -class ACE_Export ACE_Countdown_Time : private ACE_Copy_Disabled -{ -public: - /// Cache the @a max_wait_time and call @c start(). - ACE_Countdown_Time (ACE_Time_Value *max_wait_time); - - /// Destructor, makes sure the max_wait_time that got passed as pointer - /// to the constructor is updated with the time elapsed. - ~ACE_Countdown_Time (void); - - /// Cache the current time and enter a start state. - void start (void); - - /// Subtract the elapsed time from max_wait_time_ and enter a stopped - /// state. - void stop (void); - - /// Calls stop and then start. max_wait_time_ is modified by the - /// call to stop. - void update (void); - - /// Returns true if we've already been stopped, else false. - bool stopped (void) const; - -private: - /// Maximum time we were willing to wait. - ACE_Time_Value *max_wait_time_; - - /// Beginning of the start time. - ACE_Time_Value start_time_; - - /// Keeps track of whether we've already been stopped. - bool stopped_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" - -#if defined (__ACE_INLINE__) -#include "ace/Countdown_Time.inl" -#endif /* __ACE_INLINE__ */ - -#endif /* ACE_COUNTDOWN_TIME_H */ diff --git a/externals/ace/Countdown_Time.inl b/externals/ace/Countdown_Time.inl deleted file mode 100644 index 4a9eb8e0e43..00000000000 --- a/externals/ace/Countdown_Time.inl +++ /dev/null @@ -1,20 +0,0 @@ -// -*- C++ -*- -// -// $Id: Countdown_Time.inl 85368 2009-05-18 10:23:19Z johnnyw $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE bool -ACE_Countdown_Time::stopped (void) const -{ - return stopped_; -} - -ACE_INLINE void -ACE_Countdown_Time::update (void) -{ - this->stop (); - this->start (); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/DEV.cpp b/externals/ace/DEV.cpp deleted file mode 100644 index 42178a68e6b..00000000000 --- a/externals/ace/DEV.cpp +++ /dev/null @@ -1,43 +0,0 @@ -// $Id: DEV.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/DEV.h" - -#include "ace/OS_NS_unistd.h" - -#if !defined (__ACE_INLINE__) -#include "ace/DEV.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID(ace, DEV, "$Id: DEV.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_DEV) - -void -ACE_DEV::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_DEV::dump"); -#endif /* ACE_HAS_DUMP */ -} - -// This is the do-nothing constructor. - -ACE_DEV::ACE_DEV (void) -{ - ACE_TRACE ("ACE_DEV::ACE_DEV"); -} - -// Close the device - -int -ACE_DEV::close (void) -{ - ACE_TRACE ("ACE_DEV::close"); - int result = ACE_OS::close (this->get_handle ()); - this->set_handle (ACE_INVALID_HANDLE); - return result; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/DEV.h b/externals/ace/DEV.h deleted file mode 100644 index 86f8d5dc863..00000000000 --- a/externals/ace/DEV.h +++ /dev/null @@ -1,78 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file DEV.h - * - * $Id: DEV.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Gerhard Lenzer - */ -//============================================================================= - - -#ifndef ACE_DEV_H -#define ACE_DEV_H -#include /**/ "ace/pre.h" - -#include "ace/IO_SAP.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/DEV_Addr.h" - -// The following is necessary since many C++ compilers don't support -// typedef'd types inside of classes used as formal template -// arguments... ;-(. Luckily, using the C++ preprocessor I can hide -// most of this nastiness! - -#if defined (ACE_HAS_TEMPLATE_TYPEDEFS) -#define ACE_DEV_CONNECTOR ACE_DEV_Connector -#define ACE_DEV_STREAM ACE_DEV_IO -#else /* TEMPLATES are broken (must be a cfront-based compiler...) */ -#define ACE_DEV_CONNECTOR ACE_DEV_Connector, ACE_DEV_Addr -#define ACE_DEV_STREAM ACE_DEV_IO, ACE_DEV_Addr -#endif /* ACE_TEMPLATE_TYPEDEFS */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_DEV - * - * @brief Defines the member functions for the base class of the - * ACE_DEV abstraction. - */ -class ACE_Export ACE_DEV : public ACE_IO_SAP -{ -public: - /// Close down the DEVICE - int close (void); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - - /** - * Disable signal @a signum - * This is here to prevent Win32 from - * disabling SPIPE using socket calls - */ - int disable (int signum) const ; - -protected: - /// Ensure that this class is an abstract base class - ACE_DEV (void); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/DEV.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_DEV_H */ diff --git a/externals/ace/DEV.inl b/externals/ace/DEV.inl deleted file mode 100644 index 4d97a73d8e8..00000000000 --- a/externals/ace/DEV.inl +++ /dev/null @@ -1,18 +0,0 @@ -// -*- C++ -*- -// -// $Id: DEV.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE int -ACE_DEV::disable (int signum) const -{ -#if defined (ACE_WIN32) - ACE_UNUSED_ARG (signum) ; - return 0 ; -#else /* ACE_WIN32 */ - return ACE_IO_SAP::disable (signum) ; -#endif /* ACE_WIN32 */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/DEV_Addr.cpp b/externals/ace/DEV_Addr.cpp deleted file mode 100644 index 64bbb50873c..00000000000 --- a/externals/ace/DEV_Addr.cpp +++ /dev/null @@ -1,108 +0,0 @@ -// $Id: DEV_Addr.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/DEV_Addr.h" -#if !defined (__ACE_INLINE__) -#include "ace/DEV_Addr.inl" -#endif /* __ACE_INLINE__ */ - -#include "ace/Log_Msg.h" -#include "ace/OS_NS_string.h" - -ACE_RCSID (ace, - DEV_Addr, - "$Id: DEV_Addr.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_DEV_Addr) - -// Transform the current address into string format. - -int -ACE_DEV_Addr::addr_to_string (ACE_TCHAR *s, size_t len) const -{ - ACE_TRACE ("ACE_DEV_Addr::addr_to_string"); - - ACE_OS::strsncpy (s, this->devname_, len); - return 0; -} - -// Return a pointer to the address. - -void * -ACE_DEV_Addr::get_addr (void) const -{ - ACE_TRACE ("ACE_DEV_Addr::get_addr"); - - return (void *) &this->devname_; -} - -void -ACE_DEV_Addr::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_DEV_Addr::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("devname_ = %s"), this->devname_)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -// Do nothing constructor. - -ACE_DEV_Addr::ACE_DEV_Addr (void) - : ACE_Addr (AF_DEV, sizeof this->devname_) -{ - ACE_TRACE ("ACE_DEV_Addr::ACE_DEV_Addr"); - - (void) ACE_OS::memset ((void *) &this->devname_, - 0, sizeof this->devname_); -} - -int -ACE_DEV_Addr::set (const ACE_DEV_Addr &sa) -{ - this->base_set (sa.get_type (), sa.get_size ()); - - if (sa.get_type () == AF_ANY) - (void) ACE_OS::memset ((void *) &this->devname_, - 0, - sizeof this->devname_); - else - (void) ACE_OS::strsncpy (this->devname_, - sa.devname_, - ACE_DEV_Addr::DEVNAME_LENGTH); - return 0; -} - -// Copy constructor. - -ACE_DEV_Addr::ACE_DEV_Addr (const ACE_DEV_Addr &sa) - : ACE_Addr (AF_DEV, sizeof this->devname_) -{ - ACE_TRACE ("ACE_DEV_Addr::ACE_DEV_Addr"); - - this->set (sa); -} - -ACE_DEV_Addr::ACE_DEV_Addr (const ACE_TCHAR *devname) - : ACE_Addr (AF_DEV, sizeof this->devname_) -{ - ACE_TRACE ("ACE_DEV_Addr::ACE_DEV_Addr"); - - this->set (devname); -} - -ACE_DEV_Addr & -ACE_DEV_Addr::operator= (const ACE_DEV_Addr &sa) -{ - ACE_TRACE ("ACE_DEV_Addr::operator="); - - if (this != &sa) - this->set (sa); - - return *this; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/DEV_Addr.h b/externals/ace/DEV_Addr.h deleted file mode 100644 index 49ec5023a7c..00000000000 --- a/externals/ace/DEV_Addr.h +++ /dev/null @@ -1,90 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file DEV_Addr.h - * - * $Id: DEV_Addr.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Gerhard Lenzer and Douglas C. Schmidt - */ -//========================================================================== - -#ifndef ACE_DEV_ADDR_H -#define ACE_DEV_ADDR_H - -#include /**/ "ace/pre.h" - -#include "ace/Addr.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/os_dirent.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_DEV_Addr - * - * @brief Defines device address family address format. - */ -class ACE_Export ACE_DEV_Addr : public ACE_Addr -{ -public: - // = Initialization methods. - /// Default constructor. - ACE_DEV_Addr (void); - - /// Copy constructor. - ACE_DEV_Addr (const ACE_DEV_Addr &sa); - - /// Acts like a copy constructor. - int set (const ACE_DEV_Addr &sa); - - /// Create a ACE_DEV_Addr from a device name. - explicit ACE_DEV_Addr (const ACE_TCHAR *devname); - - /// Create a ACE_Addr from a ACE_DEV pathname. - void set (const ACE_TCHAR *devname); - - /// Assignment operator. - ACE_DEV_Addr &operator= (const ACE_DEV_Addr &); - - /// Return a pointer to the address. - virtual void *get_addr (void) const; - - /// Transform the current address into string format. - virtual int addr_to_string (ACE_TCHAR *addr, size_t) const; - - /// Compare two addresses for equality. - bool operator == (const ACE_DEV_Addr &SAP) const; - - /// Compare two addresses for inequality. - bool operator != (const ACE_DEV_Addr &SAP) const; - - /// Return the path name used for the rendezvous point. - const ACE_TCHAR *get_path_name (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - enum { DEVNAME_LENGTH = MAXPATHLEN + 1 }; - /// Name of the device. - ACE_TCHAR devname_[DEVNAME_LENGTH]; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/DEV_Addr.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" - -#endif /* ACE_DEV_ADDR_H */ diff --git a/externals/ace/DEV_Addr.inl b/externals/ace/DEV_Addr.inl deleted file mode 100644 index 5c1da68d7e7..00000000000 --- a/externals/ace/DEV_Addr.inl +++ /dev/null @@ -1,51 +0,0 @@ -// -*- C++ -*- -// -// $Id: DEV_Addr.inl 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/OS_NS_string.h" -#include "ace/Global_Macros.h" -#include "ace/os_include/sys/os_socket.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE void -ACE_DEV_Addr::set (const ACE_TCHAR *devname) -{ - ACE_TRACE ("ACE_DEV_Addr::set"); - - this->ACE_Addr::base_set - (AF_DEV, static_cast (ACE_OS::strlen (devname))); - ACE_OS::strsncpy (this->devname_, devname, ACE_DEV_Addr::DEVNAME_LENGTH); -} - -// Compare two addresses for equality. - -ACE_INLINE bool -ACE_DEV_Addr::operator == (const ACE_DEV_Addr &sap) const -{ - ACE_TRACE ("ACE_DEV_Addr::operator =="); - - return ACE_OS::strcmp (this->devname_, sap.devname_) == 0; -} - -// Compare two addresses for inequality. - -ACE_INLINE bool -ACE_DEV_Addr::operator != (const ACE_DEV_Addr &sap) const -{ - ACE_TRACE ("ACE_DEV_Addr::operator !="); - - return !((*this) == sap); // This is lazy, of course... ;-). -} - -// Return the path name used for the rendezvous point. - -ACE_INLINE const ACE_TCHAR * -ACE_DEV_Addr::get_path_name (void) const -{ - ACE_TRACE ("ACE_DEV_Addr::get_path_name"); - - return this->devname_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/DEV_Connector.cpp b/externals/ace/DEV_Connector.cpp deleted file mode 100644 index bdc2530acd8..00000000000 --- a/externals/ace/DEV_Connector.cpp +++ /dev/null @@ -1,53 +0,0 @@ -// $Id: DEV_Connector.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/DEV_Connector.h" - -#include "ace/Handle_Ops.h" - -#if !defined (__ACE_INLINE__) -#include "ace/DEV_Connector.inl" -#endif /* __ACE_INLINE__ */ - - -ACE_RCSID (ace, - DEV_Connector, - "$Id: DEV_Connector.cpp 80826 2008-03-04 14:51:23Z wotte $") - - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_DEV_Connector) - -void -ACE_DEV_Connector::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_DEV_Connector::dump"); -#endif /* ACE_HAS_DUMP */ -} - -ACE_DEV_Connector::ACE_DEV_Connector (void) -{ - ACE_TRACE ("ACE_DEV_Connector::ACE_DEV_Connector"); -} - -int -ACE_DEV_Connector::connect (ACE_DEV_IO &new_io, - const ACE_DEV_Addr &remote_sap, - ACE_Time_Value *timeout, - const ACE_Addr &, - int, - int flags, - int perms) -{ - ACE_TRACE ("ACE_DEV_Connector::connect"); - - ACE_HANDLE handle = ACE::handle_timed_open (timeout, - remote_sap.get_path_name (), - flags, perms); - new_io.set_handle (handle); - new_io.addr_ = remote_sap; // class copy. - return handle == ACE_INVALID_HANDLE ? -1 : 0; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/DEV_Connector.h b/externals/ace/DEV_Connector.h deleted file mode 100644 index 2f71f608882..00000000000 --- a/externals/ace/DEV_Connector.h +++ /dev/null @@ -1,110 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file DEV_Connector.h - * - * $Id: DEV_Connector.h 82723 2008-09-16 09:35:44Z johnnyw $ - * - * @author Gerhard Lenzer and Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_DEV_CONNECTOR_H -#define ACE_DEV_CONNECTOR_H -#include /**/ "ace/pre.h" - -#include "ace/DEV_IO.h" -#include "ace/Log_Msg.h" -#include "ace/os_include/os_fcntl.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_DEV_Connector - * - * @brief Defines an active connection factory for the ACE_DEV wrappers. - */ -class ACE_Export ACE_DEV_Connector -{ -public: - /// Default constructor. - ACE_DEV_Connector (void); - - /** - * Actively connect and produce a @a new_io if things go well. - * The @a remote_sap is the address that we are trying to connect - * with. The @a timeout is the amount of time to wait to connect. - * If it's 0 then we block indefinitely. If *timeout == {0, 0} then - * the connection is done using non-blocking mode. In this case, if - * the connection can't be made immediately the value of -1 is - * returned with @c errno == EWOULDBLOCK. If *timeout > {0, 0} then - * this is the maximum amount of time to wait before timing out. If the - * time expires before the connection is made @c errno == ETIME. The - * @a local_sap is the value of local address to bind to. If it's - * the default value of ACE_Addr::sap_any then the user is letting - * the OS do the binding. If @a reuse_addr == 1 then the - * is reused, even if it hasn't been cleanedup yet. - * The @a flags and @a perms arguments are passed down to the - * method. - */ - ACE_DEV_Connector (ACE_DEV_IO &new_io, - const ACE_DEV_Addr &remote_sap, - ACE_Time_Value *timeout = 0, - const ACE_Addr &local_sap = ACE_Addr::sap_any, - int reuse_addr = 0, - int flags = O_RDWR, - int perms = 0); - - /** - * Actively connect and produce a @a new_io if things go well. - * The @a remote_sap is the address that we are trying to connect - * with. The @a timeout is the amount of time to wait to connect. - * If it's 0 then we block indefinitely. If *timeout == {0, 0} then - * the connection is done using non-blocking mode. In this case, if - * the connection can't be made immediately the value of -1 is - * returned with @c errno == EWOULDBLOCK. If *timeout > {0, 0} then - * this is the maximum amount of time to wait before timing out. If the - * time expires before the connection is made @c errno == ETIME. The - * @a local_sap is the value of local address to bind to. If it's - * the default value of ACE_Addr::sap_any then the user is letting - * the OS do the binding. If @a reuse_addr == 1 then the - * is reused, even if it hasn't been cleanedup yet. - * The @a flags and @a perms arguments are passed down to the - * method. - */ - int connect (ACE_DEV_IO &new_io, - const ACE_DEV_Addr &remote_sap, - ACE_Time_Value *timeout = 0, - const ACE_Addr &local_sap = ACE_Addr::sap_any, - int reuse_addr = 0, - int flags = O_RDWR, - int perms = 0); - - /// Resets any event associations on this handle - bool reset_new_handle (ACE_HANDLE handle); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - - // = Meta-type info - typedef ACE_DEV_Addr PEER_ADDR; - typedef ACE_DEV_IO PEER_STREAM; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/DEV_Connector.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_DEV_CONNECTOR_H */ diff --git a/externals/ace/DEV_Connector.inl b/externals/ace/DEV_Connector.inl deleted file mode 100644 index a57a38b71f4..00000000000 --- a/externals/ace/DEV_Connector.inl +++ /dev/null @@ -1,33 +0,0 @@ -// -*- C++ -*- -// -// $Id: DEV_Connector.inl 82723 2008-09-16 09:35:44Z johnnyw $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Creates a Local ACE_DEV. - -ACE_INLINE -ACE_DEV_Connector::ACE_DEV_Connector (ACE_DEV_IO &new_io, - const ACE_DEV_Addr &remote_sap, - ACE_Time_Value *timeout, - const ACE_Addr &local_sap, - int reuse_addr, - int flags, - int perms) -{ - ACE_TRACE ("ACE_DEV_Connector::ACE_DEV_Connector"); - if (this->connect (new_io, remote_sap, timeout, local_sap, - reuse_addr, flags, perms) == ACE_IO_SAP::INVALID_HANDLE - && timeout != 0 && !(errno == EWOULDBLOCK || errno == ETIME)) - ACE_ERROR ((LM_ERROR, ACE_TEXT ("address %s, %p\n"), - remote_sap.get_path_name (), ACE_TEXT ("ACE_DEV_IO"))); -} - -ACE_INLINE bool -ACE_DEV_Connector::reset_new_handle (ACE_HANDLE) -{ - // Nothing to do here since the handle is not a socket - return false; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/DEV_IO.cpp b/externals/ace/DEV_IO.cpp deleted file mode 100644 index b9a8e1f46b9..00000000000 --- a/externals/ace/DEV_IO.cpp +++ /dev/null @@ -1,131 +0,0 @@ -// $Id: DEV_IO.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/DEV_IO.h" -#include "ace/Log_Msg.h" - -#if !defined (__ACE_INLINE__) -#include "ace/DEV_IO.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID(ace, DEV_IO, "$Id: DEV_IO.cpp 80826 2008-03-04 14:51:23Z wotte $") - - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_DEV_IO) - -// Return the local endpoint address. - -int -ACE_DEV_IO::get_local_addr (ACE_DEV_Addr &addr) const -{ - ACE_TRACE ("ACE_DEV_IO::get_local_addr"); - - addr = this->addr_; - return 0; -} - -// Return the address of the remotely connected peer (if there is -// one). - -int -ACE_DEV_IO::get_remote_addr (ACE_DEV_Addr &addr) const -{ - ACE_TRACE ("ACE_DEV_IO::get_remote_addr"); - addr = this->addr_; - return 0; -} - -void -ACE_DEV_IO::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_DEV_IO::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - this->addr_.dump (); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -// Simple-minded do nothing constructor. - -ACE_DEV_IO::ACE_DEV_IO (void) -{ - ACE_TRACE ("ACE_DEV_IO::ACE_DEV_IO"); -} - -// Send N char *ptrs and int lengths. Note that the char *'s precede -// the ints (basically, an varargs version of writev). The count N is -// the *total* number of trailing arguments, *not* a couple of the -// number of tuple pairs! - -ssize_t -ACE_DEV_IO::send (size_t n, ...) const -{ - ACE_TRACE ("ACE_DEV_IO::send"); - va_list argp; - int total_tuples = static_cast (n / 2); - iovec *iovp; -#if defined (ACE_HAS_ALLOCA) - iovp = (iovec *) alloca (total_tuples * sizeof (iovec)); -#else - ACE_NEW_RETURN (iovp, - iovec[total_tuples], - -1); -#endif /* !defined (ACE_HAS_ALLOCA) */ - - va_start (argp, n); - - for (int i = 0; i < total_tuples; i++) - { - iovp[i].iov_base = va_arg (argp, char *); - iovp[i].iov_len = va_arg (argp, int); - } - - ssize_t result = ACE_OS::writev (this->get_handle (), iovp, total_tuples); -#if !defined (ACE_HAS_ALLOCA) - delete [] iovp; -#endif /* !defined (ACE_HAS_ALLOCA) */ - va_end (argp); - return result; -} - -// This is basically an interface to ACE_OS::readv, that doesn't use the -// struct iovec explicitly. The ... can be passed as an arbitrary -// number of (char *ptr, int len) tuples. However, the count N is the -// *total* number of trailing arguments, *not* a couple of the number -// of tuple pairs! - -ssize_t -ACE_DEV_IO::recv (size_t n, ...) const -{ - ACE_TRACE ("ACE_DEV_IO::recv"); - va_list argp; - int total_tuples = static_cast (n / 2); - iovec *iovp; -#if defined (ACE_HAS_ALLOCA) - iovp = (iovec *) alloca (total_tuples * sizeof (iovec)); -#else - ACE_NEW_RETURN (iovp, - iovec[total_tuples], - -1); -#endif /* !defined (ACE_HAS_ALLOCA) */ - - va_start (argp, n); - - for (int i = 0; i < total_tuples; i++) - { - iovp[i].iov_base = va_arg (argp, char *); - iovp[i].iov_len = va_arg (argp, int); - } - - ssize_t result = ACE_OS::readv (this->get_handle (), iovp, total_tuples); -#if !defined (ACE_HAS_ALLOCA) - delete [] iovp; -#endif /* !defined (ACE_HAS_ALLOCA) */ - va_end (argp); - return result; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/DEV_IO.h b/externals/ace/DEV_IO.h deleted file mode 100644 index 3b1c3deb334..00000000000 --- a/externals/ace/DEV_IO.h +++ /dev/null @@ -1,185 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file DEV_IO.h - * - * $Id: DEV_IO.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Gerhard Lenzer - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_DEV_IO_H -#define ACE_DEV_IO_H -#include /**/ "ace/pre.h" - -#include "ace/DEV.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_STREAM_PIPES) -# include "ace/OS_NS_stropts.h" -#endif /* ACE_HAS_STREAM_PIPES */ - -#include "ace/os_include/os_stdio.h" -#include "ace/os_include/sys/os_uio.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -class ACE_Time_Value; - -/** - * @class ACE_DEV_IO - * - * @brief Read/Write operations on Devices. - */ -class ACE_Export ACE_DEV_IO : public ACE_DEV -{ -public: - friend class ACE_DEV_Connector; - - /// Default constructor. - ACE_DEV_IO (void); - - // = Various send operations. - /// send upto @a n bytes in @a buf. - ssize_t send (const void *buf, size_t n) const; - - /// Recv upto @a n bytes in @a buf. - ssize_t recv (void *buf, size_t n) const; - - /// Send n bytes, keep trying until n are sent. - ssize_t send_n (const void *buf, - size_t n) const; - - /** - * @name I/O operations - * - * Notes on common parameters: - * - * @a buf is the buffer to write from or receive into. - * - * @a len is the number of bytes to transfer. - * - * The @a timeout parameter in the following methods indicates how - * long to blocking trying to transfer data. If @a timeout == 0, - * then the call behaves as a normal send/recv call, i.e., for - * blocking sockets, the call will block until action is possible; - * for non-blocking sockets, EWOULDBLOCK will be returned if no - * action is immediately possible. - * - * If @a timeout != 0, the call will wait until the relative time - * specified in *@a timeout elapses. - * - * The "_n()" I/O methods keep looping until all the data has been - * transferred. These methods also work for sockets in non-blocking - * mode i.e., they keep looping on EWOULDBLOCK. @a timeout is used - * to make sure we keep making progress, i.e., the same timeout - * value is used for every I/O operation in the loop and the timeout - * is not counted down. - * - * The return values for the "*_n()" methods match the return values - * from the non "_n()" methods and are specified as follows: - * - * - On complete transfer, the number of bytes transferred is returned. - * - On timeout, -1 is returned, errno == ETIME. - * - On error, -1 is returned, errno is set to appropriate error. - * - On EOF, 0 is returned, errno is irrelevant. - * - * On partial transfers, i.e., if any data is transferred before - * timeout/error/EOF, @a bytes_transferred will contain the number of - * bytes transferred. - */ - ssize_t recv_n (void *buf, - size_t n, - const ACE_Time_Value *timeout = 0, - size_t *bytes_transferred = 0) const; - -#if defined (ACE_HAS_STREAM_PIPES) - /// Recv bytes via STREAM pipes using "band" mode. - ssize_t recv (ACE_Str_Buf *cntl, - ACE_Str_Buf *data, - int *band, - int *flags) const; - - /// Send bytes via STREAM pipes using "band" mode. - ssize_t send (const ACE_Str_Buf *cntl, - const ACE_Str_Buf *data, - int band, - int flags) const; - - /// Recv @a cntl and @a data via STREAM pipes. - ssize_t recv (ACE_Str_Buf *cntl, - ACE_Str_Buf *data, - int *flags) const; - - /// Send @a cntl and @a data via STREAM pipes. - ssize_t send (const ACE_Str_Buf *cntl, - const ACE_Str_Buf *data, - int flags = 0) const; -#endif /* ACE_HAS_STREAM_PIPES */ - - /// Send iovecs via <::writev>. - ssize_t send (const iovec iov[], size_t n) const; - - /// Recv iovecs via <::readv>. - ssize_t recv (iovec iov[], size_t n) const; - - /** - * Send N char *ptrs and int lengths. Note that the char *'s - * precede the ints (basically, an varargs version of writev). The - * count N is the *total* number of trailing arguments, *not* a - * couple of the number of tuple pairs! - */ - ssize_t send (size_t n, ...) const; - - /** - * This is an interface to ::readv, that doesn't use the struct - * iovec explicitly. The ... can be passed as an arbitrary number - * of (char *ptr, int len) tuples. However, the count N is the - * *total* number of trailing arguments, *not* a couple of the - * number of tuple pairs! - */ - ssize_t recv (size_t n, ...) const; - - /// Send @a n bytes via Win32 WriteFile using overlapped I/O. - ssize_t send (const void *buf, size_t n, ACE_OVERLAPPED *overlapped) const; - - /// Recv @a n bytes via Win32 ReadFile using overlapped I/O. - ssize_t recv (void *buf, size_t n, ACE_OVERLAPPED *overlapped) const; - - /// Dump the state of an object. - void dump (void) const; - - // = The following two methods are no-ops to keep the - // ACE_Connector happy. - /// Return the local endpoint address. - int get_local_addr (ACE_DEV_Addr &) const; - - /// Return the address of the remotely connected peer (if there is - /// one). - int get_remote_addr (ACE_DEV_Addr &) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - - // = Meta-type info - typedef ACE_DEV_Addr PEER_ADDR; - -private: - /// Address of device we are connected to. - ACE_DEV_Addr addr_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/DEV_IO.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_DEV_IO_H */ diff --git a/externals/ace/DEV_IO.inl b/externals/ace/DEV_IO.inl deleted file mode 100644 index 796d24e114a..00000000000 --- a/externals/ace/DEV_IO.inl +++ /dev/null @@ -1,126 +0,0 @@ -// -*- C++ -*- -// -// $Id: DEV_IO.inl 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/OS_NS_sys_uio.h" -#include "ace/OS_NS_unistd.h" -#include "ace/OS_Memory.h" - -#include "ace/ACE.h" - -// Send exactly N bytes from BUF to this device. Keeping trying until -// this many bytes are sent. - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE ssize_t -ACE_DEV_IO::send_n (const void *buf, size_t n) const -{ - ACE_TRACE ("ACE_DEV_IO::send_n"); - return ACE::write_n (this->get_handle (), buf, n); -} - -// Receive exactly N bytes from this file into BUF. Keep trying until -// this many bytes are received. - -ACE_INLINE ssize_t -ACE_DEV_IO::recv_n (void *buf, - size_t n, - const ACE_Time_Value *timeout, - size_t *bytes_transferred) const -{ - ACE_TRACE ("ACE_DEV_IO::recv_n"); -#if defined (ACE_WIN32) - ACE_UNUSED_ARG (timeout); - - return ACE::read_n (this->get_handle (), - buf, - n, - bytes_transferred); -#else - return ACE::recv_n (this->get_handle (), - buf, - n, - timeout, - bytes_transferred); -#endif /*ACE_WIN32*/ -} - -ACE_INLINE ssize_t -ACE_DEV_IO::send (const void *buf, size_t n) const -{ - ACE_TRACE ("ACE_DEV_IO::send"); - return ACE_OS::write (this->get_handle (), (const char *) buf, n); -} - -ACE_INLINE ssize_t -ACE_DEV_IO::recv (void *buf, size_t n) const -{ - ACE_TRACE ("ACE_DEV_IO::recv"); - return ACE_OS::read (this->get_handle (), (char *) buf, n); -} - -ACE_INLINE ssize_t -ACE_DEV_IO::send (const iovec iov[], size_t n) const -{ - ACE_TRACE ("ACE_DEV_IO::send"); - return ACE_OS::writev (this->get_handle (), iov, static_cast (n)); -} - -ACE_INLINE ssize_t -ACE_DEV_IO::recv (iovec iov[], size_t n) const -{ - ACE_TRACE ("ACE_DEV_IO::recv"); - return ACE_OS::readv (this->get_handle (), iov, static_cast (n)); -} - -ACE_INLINE ssize_t -ACE_DEV_IO::send (const void *buf, size_t n, - ACE_OVERLAPPED *overlapped) const -{ - ACE_TRACE ("ACE_DEV_IO::send"); - return ACE_OS::write (this->get_handle (), - (const char *) buf, n, - overlapped); -} - -ACE_INLINE ssize_t -ACE_DEV_IO::recv (void *buf, size_t n, - ACE_OVERLAPPED *overlapped) const -{ - ACE_TRACE ("ACE_DEV_IO::recv"); - return ACE_OS::read (this->get_handle (), (char *) buf, n, - overlapped); -} - -#if defined (ACE_HAS_STREAM_PIPES) -ACE_INLINE ssize_t -ACE_DEV_IO::recv (ACE_Str_Buf *cntl, ACE_Str_Buf *data, int *band, int *flags) const -{ - ACE_TRACE ("ACE_DEV_IO::recv"); - return ACE_OS::getpmsg (this->get_handle (), (strbuf *) cntl, (strbuf *) data, band, flags); -} - -ACE_INLINE ssize_t -ACE_DEV_IO::send (const ACE_Str_Buf *cntl, const ACE_Str_Buf *data, int band, int flags) const -{ - ACE_TRACE ("ACE_DEV_IO::send"); - return ACE_OS::putpmsg (this->get_handle (), (strbuf *) cntl, (strbuf *) data, band, flags); -} - -ACE_INLINE ssize_t -ACE_DEV_IO::recv (ACE_Str_Buf *cntl, ACE_Str_Buf *data, int *flags) const -{ - ACE_TRACE ("ACE_DEV_IO::recv"); - return ACE_OS::getmsg (this->get_handle (), (strbuf *) cntl, (strbuf *) data, flags); -} - -ACE_INLINE ssize_t -ACE_DEV_IO::send (const ACE_Str_Buf *cntl, const ACE_Str_Buf *data, int flags) const -{ - ACE_TRACE ("ACE_DEV_IO::send"); - return ACE_OS::putmsg (this->get_handle (), (strbuf *) cntl, (strbuf *) data, flags); -} -#endif /* ACE_HAS_STREAM_PIPES */ - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/DLL.cpp b/externals/ace/DLL.cpp deleted file mode 100644 index cad25110032..00000000000 --- a/externals/ace/DLL.cpp +++ /dev/null @@ -1,267 +0,0 @@ -// $Id: DLL.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/DLL.h" - -#include "ace/Log_Msg.h" -#include "ace/ACE.h" -#include "ace/DLL_Manager.h" -#include "ace/OS_NS_string.h" -#include "ace/OS_NS_dlfcn.h" -#include "ace/OS_NS_Thread.h" - -#include - -ACE_RCSID(ace, DLL, "$Id: DLL.cpp 80826 2008-03-04 14:51:23Z wotte $") - - ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Default constructor. Also, by default, the object will be closed -// before it is destroyed. - -ACE_DLL::ACE_DLL (bool close_handle_on_destruction) - : open_mode_ (0), - dll_name_ (0), - close_handle_on_destruction_ (close_handle_on_destruction), - dll_handle_ (0), - error_ (0) -{ - ACE_TRACE ("ACE_DLL::ACE_DLL (int)"); -} - -ACE_DLL::ACE_DLL (const ACE_DLL &rhs) - : open_mode_ (0), - dll_name_ (0), - close_handle_on_destruction_ (false), - dll_handle_ (0), - error_ (0) -{ - ACE_TRACE ("ACE_DLL::ACE_DLL (const ACE_DLL &)"); - - if (rhs.dll_name_ - // This will automatically up the refcount. - && this->open (rhs.dll_name_, - rhs.open_mode_, - rhs.close_handle_on_destruction_) != 0 - && ACE::debug ()) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("ACE_DLL::copy_ctor: error: %s\n"), - this->error ())); -} - -// Assignment operator - -ACE_DLL & -ACE_DLL::operator= (const ACE_DLL &rhs) -{ - ACE_TRACE ("ACE_DLL::operator= (const ACE_DLL &)"); - - ACE_DLL tmp (rhs); - - std::swap (this->open_mode_, tmp.open_mode_); - std::swap (this->dll_name_, tmp.dll_name_); - std::swap (this->close_handle_on_destruction_, - tmp.close_handle_on_destruction_); - std::swap (this->dll_handle_, tmp.dll_handle_); - std::swap (this->error_, tmp.error_); - - return *this; -} - - -// If the library name and the opening mode are specified than on -// object creation the library is implicitly opened. - -ACE_DLL::ACE_DLL (const ACE_TCHAR *dll_name, - int open_mode, - bool close_handle_on_destruction) - : open_mode_ (open_mode), - dll_name_ (0), - close_handle_on_destruction_ (close_handle_on_destruction), - dll_handle_ (0), - error_ (0) -{ - ACE_TRACE ("ACE_DLL::ACE_DLL"); - - if (this->open (dll_name, this->open_mode_, close_handle_on_destruction) != 0 - && ACE::debug ()) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("ACE_DLL::open: error calling open: %s\n"), - this->error ())); -} - -// The library is closed before the class gets destroyed depending on -// the close_handle_on_destruction value specified which is stored in -// close_handle_on_destruction_. - -ACE_DLL::~ACE_DLL (void) -{ - ACE_TRACE ("ACE_DLL::~ACE_DLL"); - - this->close (); - - // Normally delete()d in ACE_DLL::close(). However, that may not - // occur if full ACE_DLL initialization is interrupted due to errors - // (e.g. attempting to open a DSO/DLL that does not exist). Make - // sure this->dll_name_ is deallocated. - delete [] this->dll_name_; -} - -// This method opens the library based on the mode specified using the -// ACE_SHLIB_HANDLE which is obtained on making the ACE_OS::dlopen call. -// The default mode is: -// RTLD_LAZY Only references to data symbols are relocate when the -// object is first loaded. -// The other modes include: -// RTLD_NOW All necessary relocations are performed when the -// object is first loaded. -// RTLD_GLOBAL The object symbols are made available for the -// relocation processing of any other object. - -int -ACE_DLL::open (const ACE_TCHAR *dll_filename, - int open_mode, - bool close_handle_on_destruction) -{ - ACE_TRACE ("ACE_DLL::open"); - - return open_i (dll_filename, open_mode, close_handle_on_destruction); -} - -int -ACE_DLL::open_i (const ACE_TCHAR *dll_filename, - int open_mode, - bool close_handle_on_destruction, - ACE_SHLIB_HANDLE handle) -{ - ACE_TRACE ("ACE_DLL::open_i"); - - this->error_ = 0; - - if (!dll_filename) - { - if (ACE::debug ()) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("ACE_DLL::open_i: dll_name is %s\n"), - this->dll_name_ == 0 ? ACE_TEXT ("(null)") - : this->dll_name_)); - return -1; - } - - if (this->dll_handle_) - { - // If we have a good handle and its the same name, just return. - if (ACE_OS::strcmp (this->dll_name_, dll_filename) == 0) - return 0; - else - this->close (); - } - - if (!this->dll_name_) - this->dll_name_ = ACE::strnew (dll_filename); - - this->open_mode_ = open_mode; - this->close_handle_on_destruction_ = close_handle_on_destruction; - - this->dll_handle_ = ACE_DLL_Manager::instance()->open_dll (this->dll_name_, - this->open_mode_, - handle); - - if (!this->dll_handle_) - this->error_ = 1; - - return this->error_ ? -1 : 0; -} - -// The symbol refernce of the name specified is obtained. - -void * -ACE_DLL::symbol (const ACE_TCHAR *sym_name, int ignore_errors) -{ - ACE_TRACE ("ACE_DLL::symbol"); - - this->error_ = 0; - - void *sym = 0; - if (this->dll_handle_) - sym = this->dll_handle_->symbol (sym_name, ignore_errors); - - if (!sym) - this->error_ = 1; - - return sym; -} - -// The library is closed using the ACE_SHLIB_HANDLE object, i.e., the -// shared object is now disassociated form the current process. - -int -ACE_DLL::close (void) -{ - ACE_TRACE ("ACE_DLL::close"); - - int retval = 0; - - if (this->dll_handle_ - && this->close_handle_on_destruction_ - && this->dll_name_ - && (retval = ACE_DLL_Manager::instance ()->close_dll (this->dll_name_)) != 0) - this->error_ = 1; - - // Even if close_dll() failed, go ahead and cleanup. - this->dll_handle_ = 0; - delete [] this->dll_name_; - this->dll_name_ = 0; - this->close_handle_on_destruction_ = false; - - return retval; -} - -// This method is used return the last error of a library operation. - -ACE_TCHAR * -ACE_DLL::error (void) const -{ - ACE_TRACE ("ACE_DLL::error"); - if (this->error_) - { - return ACE_OS::dlerror (); - } - - return 0; -} - -// Return the handle to the user either temporarily or forever, thus -// orphaning it. If 0 means the user wants the handle forever and if 1 -// means the user temporarily wants to take the handle. - -ACE_SHLIB_HANDLE -ACE_DLL::get_handle (int become_owner) const -{ - ACE_TRACE ("ACE_DLL::get_handle"); - - ACE_SHLIB_HANDLE handle = ACE_SHLIB_INVALID_HANDLE; - - if (this->dll_handle_) - handle = this->dll_handle_->get_handle (become_owner); - - return handle; -} - -// Set the handle for the DLL. By default, the object will be closed -// before it is destroyed. - -int -ACE_DLL::set_handle (ACE_SHLIB_HANDLE handle, - bool close_handle_on_destruction) -{ - ACE_TRACE ("ACE_DLL::set_handle"); - - // Create a unique name. Note that this name is only quaranteed - // to be unique for the life of this object. - ACE_TCHAR temp[ACE_UNIQUE_NAME_LEN]; - ACE_OS::unique_name (this, temp, ACE_UNIQUE_NAME_LEN); - - return this->open_i (temp, 1, close_handle_on_destruction, handle); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/DLL.h b/externals/ace/DLL.h deleted file mode 100644 index 20d333db81a..00000000000 --- a/externals/ace/DLL.h +++ /dev/null @@ -1,196 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file DLL.h - * - * $Id: DLL.h 91064 2010-07-12 10:11:24Z johnnyw $ - * - * @author Kirthika Parameswaran - */ -//============================================================================= - -#ifndef ACE_DLL_H -#define ACE_DLL_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Global_Macros.h" -#include "ace/os_include/os_dlfcn.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -class ACE_DLL_Handle; - -/** - * @class ACE_DLL - * - * @brief Provides an abstract interface for handling various DLL - * operations. - * - * This class is a wrapper over the various methods for utilizing - * a dynamically linked library (DLL), which is called a shared - * library on some platforms. Operations @c open(), @c close(), and - * @c symbol() have been implemented to help opening/closing and - * extracting symbol information from a DLL, respectively. - */ -class ACE_Export ACE_DLL -{ -public: - // = Initialization and termination methods. - - /** - * Default constructor. By default, the close() operation on the - * object will be invoked before it is destroyed. - * @param close_handle_on_destruction Indicates whether or not the - * close() method will be called to close an open DLL when this - * object is destroyed. By default, close() will be called. - * Set this parameter to 0 for situations where the DLL's lifetime - * is controlled in a scope other than that of this ACE_DLL object. - * For example, termination by ACE_DLL_Manager via ACE::fini(). - */ - explicit ACE_DLL (bool close_handle_on_destruction = true); - - /// Allow assignment - ACE_DLL& operator= (const ACE_DLL &rhs); - - - /** - * This constructor performs the actions of open() during construction. - * @param dll_name The name or path of the DLL to load. - * @param open_mode Flags to alter the actions taken when loading the DLL. - * The possible values are: - * @li @c RTLD_LAZY (this the default): loads identifier symbols but - * not the symbols for functions, which are loaded dynamically - * on-demand. - * @li @c RTLD_NOW: performs all necessary relocations when - * @a dll_name is first loaded - * @li RTLD_GLOBAL: makes symbols available for relocation - * processing of any other DLLs. - * @param close_handle_on_destruction Indicates whether or not the - * close() method will be called to close an open DLL when this - * object is destroyed. By default, close() will be called. - * Set this parameter to 0 for situations where the DLL's lifetime - * is controlled in a scope other than that of this ACE_DLL object. - * For example, termination by ACE_DLL_Manager via ACE::fini(). - */ - explicit ACE_DLL (const ACE_TCHAR *dll_name, - int open_mode = ACE_DEFAULT_SHLIB_MODE, - bool close_handle_on_destruction = true); - - /// Copy constructor. - ACE_DLL (const ACE_DLL &); - - /** - * This method opens and dynamically links a specified DLL. - * @param dll_name The filename or path of the DLL to load. - * If a filename is given to @c open(), the @c ACE::ldfind() is used - * to locate DLLs via the following algorithms: (1) DLL filename - * expansion: @c ACE::ldfind() determines the name of the DLL by - * adding the appropriate prefix and suffix, e.g., it adds the @c lib - * prefix and @c .so suffix for Solaris and the @c .dll suffix for - * Windows and (2) DLL search path: @c ACE::ldfind() will also search - * for the designated DLL using the platform's DLL search path - * environment variable, e.g., it searches for DLLs using @c - * LD_LIBRARY_PATH on many UNIX systems and @c PATH on Windows. - * @param open_mode Flags to alter the actions taken when loading the DLL. - * The possible values are: - * @li @c RTLD_LAZY (this the default): loads identifier symbols but - * not the symbols for functions, which are loaded dynamically - * on-demand. - * @li @c RTLD_NOW: performs all necessary relocations when - * @a dll_name is first loaded - * @li RTLD_GLOBAL: makes symbols available for relocation - * processing of any other DLLs. - * @param close_handle_on_destruction Indicates whether or not the - * close() method will be called to close an open DLL when this - * object is destroyed. By default, close() will be called. - * Set this parameter to 0 for situations where the DLL's lifetime - * is controlled in a scope other than that of this ACE_DLL object. - * For example, termination by ACE_DLL_Manager via ACE::fini(). - * @retval -1 On failure - * @retval 0 On success. - */ - int open (const ACE_TCHAR *dll_name, - int open_mode = ACE_DEFAULT_SHLIB_MODE, - bool close_handle_on_destruction = true); - - /// Call to close the DLL object. - int close (void); - - /** - * Called when the DLL object is destroyed -- invokes close() if the - * @a close_handle_on_destruction flag was set to non-zero in the - * constructor or open() method. - */ - ~ACE_DLL (void); - - /** - * Look up a named symbol in the DLL. DLL must be successfully opened - * before calling symbol(). - * @param symbol_name The symbol name to look up. - * @param ignore_errors If set to 1, allows you to probe a dll without - * generating error messages in the log. Handy for determining - * the capabilities of a library. - * @return Returns the value of @a symbol_name if it is a valid symbol - * in the DLL. Otherwise, returns 0. - */ - void *symbol (const ACE_TCHAR *symbol_name, int ignore_errors = 0); - - /// Returns a pointer to a string explaining that an error occured. You - /// will need to consult the error log for the actual error string - /// returned by the OS. - ACE_TCHAR *error (void) const; - - /** - * Return the handle to the caller. If @a become_owner is non-0 then - * caller assumes ownership of the handle and the ACE_DLL object - * won't call close() when it goes out of scope, even if - * @c close_handle_on_destruction is set. - */ - ACE_SHLIB_HANDLE get_handle (int become_owner = 0) const; - - /// Set the handle for the DLL object. By default, the close() - /// operation on / the object will be invoked before it is destroyed. - int set_handle (ACE_SHLIB_HANDLE handle, - bool close_handle_on_destruction = true); - -private: - - int open_i (const ACE_TCHAR *dll_name, - int open_mode = ACE_DEFAULT_SHLIB_MODE, - bool close_handle_on_destruction = true, - ACE_SHLIB_HANDLE handle = 0); - - - //private: -public: - - /// Open mode. - int open_mode_; - - /// Keep track of the name of the loaded dll, so it can be used - /// to remove framework components, singletons that live in the dll, - /// prior to unloading the dll in the close() method. - ACE_TCHAR *dll_name_; - - /// This flag keeps track of whether we should close the handle - /// automatically when the object is destroyed. - bool close_handle_on_destruction_; - - ACE_DLL_Handle *dll_handle_; - - /// Flag to record if the last operation had an error. - bool error_; - -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" -#endif /* ACE_DLL_H */ diff --git a/externals/ace/DLL_Manager.cpp b/externals/ace/DLL_Manager.cpp deleted file mode 100644 index be73f455800..00000000000 --- a/externals/ace/DLL_Manager.cpp +++ /dev/null @@ -1,787 +0,0 @@ -// $Id: DLL_Manager.cpp 90712 2010-06-18 20:01:29Z shuston $ - -#include "ace/DLL_Manager.h" - -#include "ace/Log_Msg.h" -#include "ace/ACE.h" -#include "ace/Framework_Component.h" - -#include "ace/Lib_Find.h" -#include "ace/Object_Manager.h" -#include "ace/SString.h" -#include "ace/Recursive_Thread_Mutex.h" -#include "ace/Guard_T.h" -#include "ace/OS_NS_dlfcn.h" -#include "ace/OS_NS_string.h" - -ACE_RCSID (ace, - DLL_Manager, - "DLL_Manager.cpp,v 4.23 2003/11/05 23:30:46 shuston Exp") - -/******************************************************************/ - - ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -sig_atomic_t ACE_DLL_Handle::open_called_ = 0; - -ACE_DLL_Handle::ACE_DLL_Handle (void) - : refcount_ (0), - dll_name_ (0), - handle_ (ACE_SHLIB_INVALID_HANDLE) -{ - ACE_TRACE ("ACE_DLL_Handle::ACE_DLL_Handle"); -} - -ACE_DLL_Handle::~ACE_DLL_Handle (void) -{ - ACE_TRACE ("ACE_DLL_Handle::~ACE_DLL_Handle"); - this->close (1); - delete[] this->dll_name_; -} - -const ACE_TCHAR * -ACE_DLL_Handle::dll_name (void) const -{ - ACE_TRACE ("ACE_DLL_Handle::dll_name"); - return this->dll_name_; -} - -int -ACE_DLL_Handle::open (const ACE_TCHAR *dll_name, - int open_mode, - ACE_SHLIB_HANDLE handle) -{ - ACE_TRACE ("ACE_DLL_Handle::open"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0)); - - if (this->dll_name_) - { - // Once dll_name_ has been set, it can't be changed.. - if (ACE_OS::strcmp (this->dll_name_, dll_name) != 0) - { - if (ACE::debug ()) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("ACE (%P|%t) DLL_Handle::open: error, ") - ACE_TEXT ("tried to reopen %s with name %s\n"), - this->dll_name_, - dll_name)); - - return -1; - } - } - else - this->dll_name_ = ACE::strnew (dll_name); - - if (!this->open_called_) - this->open_called_ = 1; - - // If it hasn't been loaded yet, go ahead and do that now. - if (this->handle_ == ACE_SHLIB_INVALID_HANDLE) - { - if (handle) - this->handle_ = handle; - else - { - /* - ** Get the set of names to try loading. We need to do this to - ** properly support the ability for a user to specify a simple, - ** unadorned name (for example, "ACE") that will work across - ** platforms. We apply platform specifics to get a name that will - ** work (e.g. libACE, ACEd.dll, ACE.dll, etc.) We rely on the - ** underlying dlopen() implementation to "Do The Right Thing" in - ** terms of using relative paths, LD_LIBRARY_PATH, system security - ** rules, etc. except when ACE_MUST_HELP_DLOPEN_SEARCH_PATH is set. - ** If it is set, then ACE::ldfind() scans the configured path - ** looking for a match on the name and prefix/suffix applications. - ** NOTE: having ACE scan for a file and then pass a fully-qualified - ** pathname to dlopen() is a potential security hole; therefore, - ** do not use ACE_MUST_HELP_DLOPEN_SEARCH_PATH unless necessary - ** and only after considering the risks. - */ - ACE_Array dll_names; - dll_names.max_size (10); // Decent guess to avoid realloc later - -#if defined (ACE_MUST_HELP_DLOPEN_SEARCH_PATH) - // Find out where the library is - ACE_TCHAR dll_pathname[MAXPATHLEN + 1]; - - // Transform the pathname into the appropriate dynamic link library - // by searching the ACE_LD_SEARCH_PATH. - ACE::ldfind (dll_name, - dll_pathname, - (sizeof dll_pathname / sizeof (ACE_TCHAR))); - ACE_TString dll_str (dll_pathname); - dll_names.size (1); - dll_names.set (dll_str, 0); -#else - this->get_dll_names (dll_name, dll_names); -#endif - - ACE_Array_Iterator name_iter (dll_names); - ACE_TString *name = 0; - while (name_iter.next (name)) - { - // The ACE_SHLIB_HANDLE object is obtained. - this->handle_ = ACE_OS::dlopen (name->c_str (), - open_mode); - - if (ACE::debug ()) - { - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) DLL_Handle::open ") - ACE_TEXT ("(\"%s\", 0x%x) -> %s: %s\n"), - name->c_str (), - open_mode, - ((this->handle_ != ACE_SHLIB_INVALID_HANDLE) - ? ACE_TEXT ("succeeded") - : ACE_TEXT ("failed")), - this->error()->c_str())); - } - - if (this->handle_ != ACE_SHLIB_INVALID_HANDLE) // Good one? - break; - - // If errno is ENOENT we just skip over this one, - // anything else - like an undefined symbol, for - // instance must be flagged here or the next error will - // mask it. - // @TODO: If we've found our DLL _and_ it's - // broken, should we continue at all? - if ((errno != 0) && (errno != ENOENT) && ACE::debug ()) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("ACE (%P|%t) DLL_Handle::open ") - ACE_TEXT ("(\'%s\') failed, errno=") - ACE_TEXT ("%d: <%s>\n"), - name->c_str (), - ACE_ERRNO_GET, - this->error ()->c_str ())); - -#if defined (AIX) - // AIX often puts the shared library file (most often named - // shr.o) inside an archive library. If this is an archive - // library name, then try appending [shr.o] and retry. - if (ACE_TString::npos != name->strstr (ACE_TEXT (".a"))) - { - ACE_TCHAR aix_pathname[MAXPATHLEN + 1]; - ACE_OS::strncpy (aix_pathname, - name->c_str (), - name->length ()); - aix_pathname[name->length ()] = '\0'; - ACE_OS::strcat (aix_pathname, ACE_TEXT ("(shr.o)")); - open_mode |= RTLD_MEMBER; - - if (ACE::debug ()) - { - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) DLL_Handle::open ") - ACE_TEXT ("(\"%s\", 0x%x) -> %s: %s\n"), - aix_pathname, - open_mode, - (this->handle_ != ACE_SHLIB_INVALID_HANDLE - ? ACE_TEXT ("succeeded") - : ACE_TEXT ("failed")), - this->error()->c_str())); - } - - this->handle_ = ACE_OS::dlopen (aix_pathname, open_mode); - if (this->handle_ != ACE_SHLIB_INVALID_HANDLE) - break; - - // If errno is ENOENT we just skip over this one, anything - // else - like an undefined symbol, for instance - // must be flagged here or the next error will mask it. - // - // @TODO: If we've found our DLL _and_ it's broken, - // should we continue at all? - if (ACE::debug () && (errno != 0) && (errno != ENOENT)) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("ACE (%P|%t) DLL_Handle::open ") - ACE_TEXT ("(\'%s\') failed, errno=") - ACE_TEXT ("%d: %s\n"), - name->c_str (), - errno, - this->error ()->c_str ())); - - } -#endif /* AIX */ - - name_iter.advance (); - } - - if (this->handle_ == ACE_SHLIB_INVALID_HANDLE) - { - if (ACE::debug ()) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("ACE (%P|%t) DLL_Handle::open (\"%s\"): ") - ACE_TEXT ("Invalid handle error: %s\n"), - this->dll_name_, - this->error ()->c_str ())); - - return -1; - } - } - } - - ++this->refcount_; - - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) DLL_Handle::open - %s (%d), refcount=%d\n"), - this->dll_name_, - this->handle_, - this->refcount_)); - return 0; -} - - -int -ACE_DLL_Handle::close (int unload) -{ - ACE_TRACE ("ACE_DLL_Handle::close"); - - int retval = 0; - ACE_SHLIB_HANDLE h = ACE_SHLIB_INVALID_HANDLE; - - // Only hold the lock until it comes time to dlclose() the DLL. Closing - // the DLL can cause further shutdowns as DLLs and their dependents are - // unloaded. - { - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0)); - - // Since we don't actually unload the dll as soon as the refcount - // reaches zero, we need to make sure we don't decrement it below - // zero. - if (this->refcount_ > 0) - --this->refcount_; - else - this->refcount_ = 0; - - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) DLL_Handle::close - ") - ACE_TEXT ("%s (handle=%d, refcount=%d)\n"), - this->dll_name_, - this->handle_, - this->refcount_)); - - if (this->refcount_ == 0 && - this->handle_ != ACE_SHLIB_INVALID_HANDLE && - unload == 1) - { - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) DLL_Handle::close: ") - ACE_TEXT ("Unloading %s (handle=%d)\n"), - this->dll_name_, - this->handle_)); - - // First remove any associated Framework Components. - ACE_Framework_Repository *frPtr= ACE_Framework_Repository::instance (); - if (frPtr) - { - frPtr->remove_dll_components (this->dll_name_); - } - - h = this->handle_; - this->handle_ = ACE_SHLIB_INVALID_HANDLE; - } - } // Release lock_ here - - if (h != ACE_SHLIB_INVALID_HANDLE) - { - retval = ACE_OS::dlclose (h); - - if (retval != 0 && ACE::debug ()) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("ACE (%P|%t) DLL_Handle::close - ") - ACE_TEXT ("Failed with: \"%s\".\n"), - this->error ()->c_str ())); - } - - return retval; -} - -sig_atomic_t -ACE_DLL_Handle::refcount (void) const -{ - return this->refcount_; -} - -void * -ACE_DLL_Handle::symbol (const ACE_TCHAR *sym_name, int ignore_errors) -{ - ACE_TRACE ("ACE_DLL_Handle::symbol"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0)); - - ACE_Auto_Array_Ptr auto_name (ACE::ldname (sym_name)); - // handle_ can be invalid especially when ACE_DLL_Handle resigned ownership - // BTW. Handle lifecycle management is a little crazy in ACE - if (this->handle_ != ACE_SHLIB_INVALID_HANDLE) - { -#if defined (ACE_OPENVMS) - void *sym = ACE::ldsymbol (this->handle_, auto_name.get ()); -#else - void *sym = ACE_OS::dlsym (this->handle_, auto_name.get ()); -#endif - - // Linux says that the symbol could be null and that it isn't an - // error. So you should check the error message also, but since - // null symbols won't do us much good anyway, let's still report - // an error. - if (!sym && ignore_errors != 1) - { - if (ACE::debug ()) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("ACE (%P|%t) DLL_Handle::symbol (\"%s\") ") - ACE_TEXT (" failed with \"%s\".\n"), - auto_name.get (), - this->error ()->c_str ())); - - return 0; - } - return sym; - } - return 0; -} - -ACE_SHLIB_HANDLE -ACE_DLL_Handle::get_handle (int become_owner) -{ - ACE_TRACE ("ACE_DLL_Handle::get_handle"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0)); - - if (this->refcount_ == 0 && become_owner != 0) - { - if (ACE::debug ()) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("ACE (%P|%t) DLL_Handle::get_handle: ") - ACE_TEXT ("cannot become owner, refcount == 0.\n"))); - - return ACE_SHLIB_INVALID_HANDLE; - } - - ACE_SHLIB_HANDLE handle = this->handle_; - - if (become_owner != 0) - { - if (--this->refcount_ == 0) - this->handle_ = ACE_SHLIB_INVALID_HANDLE; - } - - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) DLL_Handle::get_handle: ") - ACE_TEXT ("post call: handle %s, refcount %d\n"), - this->handle_ == ACE_SHLIB_INVALID_HANDLE ? - ACE_TEXT ("invalid") : ACE_TEXT ("valid"), - this->refcount_)); - - return handle; -} - -// This method is used return the last error of a library operation. - -auto_ptr -ACE_DLL_Handle::error (void) -{ - ACE_TRACE ("ACE_DLL_Handle::error"); - const ACE_TCHAR *error = ACE_OS::dlerror (); - auto_ptr str - (new ACE_TString (error ? error : ACE_TEXT ("no error"))); - return str; -} - -void -ACE_DLL_Handle::get_dll_names (const ACE_TCHAR *dll_name, - ACE_Array &try_names) -{ - // Build the array of DLL names to try on this platform by applying the - // proper prefixes and/or suffixes to the specified dll_name. - ACE_TString base (dll_name); - ACE_TString base_dir, base_file, base_suffix; - - // 1. Separate the dll_name into the dir part and the file part. We - // only decorate the file part to determine the names to try loading. - ACE_TString::size_type pos = base.rfind (ACE_DIRECTORY_SEPARATOR_CHAR); - if (pos != ACE_TString::npos) - { - base_dir = base.substr (0, pos + 1); - base_file = base.substr (pos + 1); - } - else - base_file = base; - - // 2. Locate the file suffix, if there is one. Move the '.' and the - // suffix to base_suffix. - if ((pos = base_file.rfind (ACE_TEXT ('.'))) != ACE_TString::npos) - { - base_suffix = base_file.substr (pos); - base_file = base_file.substr (0, pos); - } - - // 3. Build the combinations to try for this platform. - // Try these combinations: - // - name with decorator and platform's suffix appended (if not supplied) - // - name with platform's suffix appended (if not supplied) - // - name with platform's dll prefix (if it has one) and suffix - // - name with platform's dll prefix, decorator, and suffix. - // - name as originally given - // We first try to find the file using the decorator so that when a - // filename with and without decorator is used, we get the file with - // the same decorator as the ACE dll has and then as last resort - // the one without. For example with msvc, the debug build has a "d" - // decorator, but the release build has none and we really want to get - // the debug version of the library in a debug application instead - // of the release one. - // So we need room for 5 entries in try_names. - try_names.size (0); - if ((try_names.max_size () - try_names.size ()) < 5) - try_names.max_size (try_names.max_size () + 5); -#if defined (ACE_LD_DECORATOR_STR) && !defined (ACE_DISABLE_DEBUG_DLL_CHECK) - ACE_TString decorator (ACE_LD_DECORATOR_STR); -#endif - ACE_TString suffix (ACE_DLL_SUFFIX); - ACE_TString prefix (ACE_DLL_PREFIX); - - for (size_t i = 0; i < 5 && try_names.size () < try_names.max_size (); ++i) - { - ACE_TString try_this; - size_t const j = try_names.size (); - switch (i) - { - case 0: // Name + decorator + suffix - case 1: // Name + suffix - case 2: // Prefix + name + decorator + suffix - case 3: // Prefix + name + suffix - if ( - base_suffix.length () > 0 -#if !(defined (ACE_LD_DECORATOR_STR) && !defined (ACE_DISABLE_DEBUG_DLL_CHECK)) - || (i == 1 || i == 3) // No decorator desired; skip -#endif - ) - break; - try_this = base_dir; - if (i > 1) - try_this += prefix; - try_this += base_file; - if (base_suffix.length () > 0) - try_this += base_suffix; - else - { -#if defined (ACE_LD_DECORATOR_STR) && !defined (ACE_DISABLE_DEBUG_DLL_CHECK) - try_this += decorator; -#endif - try_this += suffix; - } - break; - case 4: - try_this = dll_name; - break; - } - - if (try_this.length ()) - { - try_names.size (j + 1); - try_names.set (try_this, j); - } - } - return; -} - -/******************************************************************/ - -// Pointer to the Singleton instance. -ACE_DLL_Manager *ACE_DLL_Manager::instance_ = 0; - - -ACE_DLL_Manager * -ACE_DLL_Manager::instance (int size) -{ - ACE_TRACE ("ACE_DLL_Manager::instance"); - - if (ACE_DLL_Manager::instance_ == 0) - { - // Perform Double-Checked Locking Optimization. - ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, - *ACE_Static_Object_Lock::instance (), 0)); - if (ACE_DLL_Manager::instance_ == 0) - { - ACE_NEW_RETURN (ACE_DLL_Manager::instance_, - ACE_DLL_Manager (size), - 0); - } - } - - return ACE_DLL_Manager::instance_; -} - -void -ACE_DLL_Manager::close_singleton (void) -{ - ACE_TRACE ("ACE_DLL_Manager::close_singleton"); - - ACE_MT (ACE_GUARD (ACE_Recursive_Thread_Mutex, ace_mon, - *ACE_Static_Object_Lock::instance ())); - - delete ACE_DLL_Manager::instance_; - ACE_DLL_Manager::instance_ = 0; -} - -ACE_DLL_Manager::ACE_DLL_Manager (int size) - : handle_vector_ (0), - current_size_ (0), - total_size_ (0), - unload_policy_ (ACE_DLL_UNLOAD_POLICY_PER_DLL) -{ - ACE_TRACE ("ACE_DLL_Manager::ACE_DLL_Manager"); - - if (this->open (size) != 0 && ACE::debug ()) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("ACE (%P|%t) DLL_Manager ctor failed to allocate ") - ACE_TEXT ("handle_vector_.\n"))); -} - -ACE_DLL_Manager::~ACE_DLL_Manager (void) -{ - ACE_TRACE ("ACE_DLL_Manager::~ACE_DLL_Manager"); - - if (this->close () != 0 && ACE::debug ()) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("ACE (%P|%t) DLL_Manager dtor failed to close ") - ACE_TEXT ("properly.\n"))); -} - -ACE_DLL_Handle * -ACE_DLL_Manager::open_dll (const ACE_TCHAR *dll_name, - int open_mode, - ACE_SHLIB_HANDLE handle) -{ - ACE_TRACE ("ACE_DLL_Manager::open_dll"); - - ACE_DLL_Handle *temp_handle = 0; - ACE_DLL_Handle *dll_handle = 0; - { - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0)); - dll_handle = this->find_dll (dll_name); - if (!dll_handle) - { - if (this->current_size_ < this->total_size_) - { - ACE_NEW_RETURN (temp_handle, - ACE_DLL_Handle, - 0); - - dll_handle = temp_handle; - } - } - } - - if (dll_handle) - { - if (dll_handle->open (dll_name, open_mode, handle) != 0) - { - // Error while opening dll. Free temp handle - if (ACE::debug ()) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("ACE (%P|%t) DLL_Manager::open_dll: Could not ") - ACE_TEXT ("open dll %s.\n"), - dll_name)); - - delete temp_handle; - return 0; - } - - // Add the handle to the vector only if the dll is successfully - // opened. - if (temp_handle != 0) - { - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0)); - this->handle_vector_[this->current_size_] = dll_handle; - ++this->current_size_; - } - } - - return dll_handle; -} - -int -ACE_DLL_Manager::close_dll (const ACE_TCHAR *dll_name) -{ - ACE_TRACE ("ACE_DLL_Manager::close_dll"); - ACE_DLL_Handle *handle = 0; - - { - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0)); - handle = this->find_dll (dll_name); - } - - if (handle) - { - return this->unload_dll (handle, 0); - } - - return -1; -} - -u_long -ACE_DLL_Manager::unload_policy (void) const -{ - ACE_TRACE ("ACE_DLL_Manager::unload_policy"); - return this->unload_policy_; -} - -void -ACE_DLL_Manager::unload_policy (u_long unload_policy) -{ - ACE_TRACE ("ACE_DLL_Manager::unload_policy"); - ACE_MT (ACE_GUARD (ACE_Thread_Mutex, ace_mon, this->lock_)); - - u_long old_policy = this->unload_policy_; - this->unload_policy_ = unload_policy; - - // If going from LAZY to EAGER or from PER_DLL to PER_PROCESS|EAGER, - // call close(1) on all the ACE_DLL_Handle objects with refcount == 0 - // which will force those that are still loaded to be unloaded. - if (this->handle_vector_) - if (( ACE_BIT_ENABLED (old_policy, ACE_DLL_UNLOAD_POLICY_LAZY) && - ACE_BIT_DISABLED (this->unload_policy_, ACE_DLL_UNLOAD_POLICY_LAZY) ) || - ( ACE_BIT_DISABLED (this->unload_policy_, ACE_DLL_UNLOAD_POLICY_LAZY) && - ACE_BIT_ENABLED (old_policy, ACE_DLL_UNLOAD_POLICY_PER_DLL) && - ACE_BIT_DISABLED (this->unload_policy_, ACE_DLL_UNLOAD_POLICY_PER_DLL) )) - { - for (int i = this->current_size_ - 1; i >= 0; i--) - { - if (this->handle_vector_[i] && - this->handle_vector_[i]->refcount () == 0) - this->handle_vector_[i]->close (1); - } - } -} - -int -ACE_DLL_Manager::open (int size) -{ - ACE_TRACE ("ACE_DLL_Manager::open"); - - ACE_DLL_Handle **temp = 0; - - ACE_NEW_RETURN (temp, - ACE_DLL_Handle *[size], - -1); - - this->handle_vector_ = temp; - this->total_size_ = size; - return 0; -} - -int -ACE_DLL_Manager::close (void) -{ - ACE_TRACE ("ACE_DLL_Manager::close"); - - int force_close = 1; - - if (this->handle_vector_ != 0) - { - // Delete components in reverse order. - for (int i = this->current_size_ - 1; i >= 0; i--) - { - if (this->handle_vector_[i]) - { - ACE_DLL_Handle *s = - const_cast (this->handle_vector_[i]); - this->handle_vector_[i] = 0; - this->unload_dll (s, force_close); - delete s; - } - } - - delete [] this->handle_vector_; - this->handle_vector_ = 0; - this->current_size_ = 0; - } - return 0; -} - -ACE_DLL_Handle * -ACE_DLL_Manager::find_dll (const ACE_TCHAR *dll_name) const -{ - ACE_TRACE ("ACE_DLL_Manager::find_dll"); - - for (int i = 0; i < this->current_size_; i++) - if (this->handle_vector_[i] && - ACE_OS::strcmp (this->handle_vector_[i]->dll_name (), dll_name) == 0) - { - return this->handle_vector_[i]; - } - - return 0; -} - -int -ACE_DLL_Manager::unload_dll (ACE_DLL_Handle *dll_handle, int force_unload) -{ - ACE_TRACE ("ACE_DLL_Manager::unload_dll"); - - if (dll_handle) - { - int unload = force_unload; - if (unload == 0) - { - // apply strategy - if (ACE_BIT_DISABLED (this->unload_policy_, - ACE_DLL_UNLOAD_POLICY_PER_DLL)) - { - unload = ACE_BIT_DISABLED (this->unload_policy_, - ACE_DLL_UNLOAD_POLICY_LAZY); - } - else - { - // Declare the type of the symbol: - typedef int (*dll_unload_policy)(void); - - void * const unload_policy_ptr = - dll_handle->symbol (ACE_TEXT ("_get_dll_unload_policy"), 1); -#if defined (ACE_OPENVMS) && (!defined (__INITIAL_POINTER_SIZE) || (__INITIAL_POINTER_SIZE < 64)) - int const temp_p = - reinterpret_cast (unload_policy_ptr); -#else - intptr_t const temp_p = - reinterpret_cast (unload_policy_ptr); -#endif - - dll_unload_policy const the_policy = - reinterpret_cast (temp_p); - - if (the_policy != 0) - unload = ACE_BIT_DISABLED (the_policy (), - ACE_DLL_UNLOAD_POLICY_LAZY); - else - unload = ACE_BIT_DISABLED (this->unload_policy_, - ACE_DLL_UNLOAD_POLICY_LAZY); - } - } - - if (dll_handle->close (unload) != 0) - { - if (ACE::debug ()) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("ACE (%P|%t) DLL_Manager::unload error.\n"))); - - return -1; - } - } - else - { - if (ACE::debug ()) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("ACE (%P|%t) DLL_Manager::unload_dll called with ") - ACE_TEXT ("null pointer.\n"))); - - return -1; - } - - return 0; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/DLL_Manager.h b/externals/ace/DLL_Manager.h deleted file mode 100644 index 716e3299557..00000000000 --- a/externals/ace/DLL_Manager.h +++ /dev/null @@ -1,269 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file DLL_Manager.h - * - * $Id: DLL_Manager.h 91064 2010-07-12 10:11:24Z johnnyw $ - * - * @author Don Hinton - */ -//============================================================================= - -#ifndef ACE_DLL_MANAGER_H -#define ACE_DLL_MANAGER_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Auto_Ptr.h" -#include "ace/Containers_T.h" -#include "ace/SStringfwd.h" -#include "ace/os_include/os_dlfcn.h" - -#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) -# include "ace/Thread_Mutex.h" -#endif /* ACE_MT_SAFE */ - -#define ACE_DEFAULT_DLL_MANAGER_SIZE 1024 - - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_DLL_Handle - * - * @brief Provides an abstract interface for handling various DLL - * operations. - * - * This class is an wrapper over the various methods for utilizing a - * dynamically linked library (DLL), which is called a shared library - * on some platforms. It is refcounted and managed by - * ACE_DLL_Manager, so there will only be a single instance of this - * class for each dll loaded, no matter how many instances of ACE_DLL - * an application has open. Operations open(), close(), and symbol() - * have been implemented to help opening/closing and extracting symbol - * information from a DLL, respectively. - * - * Most of this class came from the original ACE_DLL class. ACE_DLL - * is now just an interface that passed all it's calls either directly - * or via ACE_DLL_Manager to this class for execution. - * - */ -class ACE_Export ACE_DLL_Handle -{ -public: - - /// Default construtor. - ACE_DLL_Handle (void); - - /// Destructor. - ~ACE_DLL_Handle (void); - - /// Returns the name of the shared library (without prefixes or suffixes). - const ACE_TCHAR *dll_name () const; - - /** - * This method opens and dynamically links @a dll_name. The default - * mode is @c RTLD_LAZY, which loads identifier symbols but not the - * symbols for functions, which are loaded dynamically on-demand. - * Other supported modes include: @c RTLD_NOW, which performs all - * necessary relocations when @a dll_name is first loaded and - * @c RTLD_GLOBAL, which makes symbols available for relocation - * processing of any other DLLs. Returns -1 on failure and 0 on - * success. - */ - int open (const ACE_TCHAR *dll_name, - int open_mode, - ACE_SHLIB_HANDLE handle); - - /// Call to close the DLL object. If unload = 0, it only decrements - /// the refcount, but if unload = 1, then it will actually unload - /// the library when the refcount == 0; - int close (int unload = 0); - - /// Return the current refcount. - sig_atomic_t refcount (void) const; - - /// If @a symbol_name is in the symbol table of the DLL a pointer to - /// the @a symbol_name is returned. Otherwise, returns 0. Set the - /// ignore_errors flag to supress logging errors if symbol_name isn't - /// found. This is nice if you just want to probe a dll to see what's - /// available, since missing functions in that case aren't really errors. - void *symbol (const ACE_TCHAR *symbol_name, int ignore_errors = 0); - - /** - * Return the handle to the caller. If @a become_owner is non-0 then - * caller assumes ownership of the handle so we decrement the retcount. - */ - ACE_SHLIB_HANDLE get_handle (int become_owner = 0); - -private: - - /// Returns a pointer to a string explaining why or - /// failed. This is used internal to print out the error to the log, - /// but since this object is shared, we can't store or return the error - /// to the caller. - auto_ptr error (void); - - /// Builds array of DLL names to try to dlopen, based on platform - /// and configured DLL prefixes/suffixes. - /// Returns the array of names to try in try_names. - void get_dll_names (const ACE_TCHAR *dll_name, - ACE_Array &try_names); - - /// Disallow copying and assignment since we don't handle them. - ACE_DLL_Handle (const ACE_DLL_Handle &); - void operator= (const ACE_DLL_Handle &); - -private: - - /// Keep track of how many ACE_DLL objects have a reference to this - /// dll. - sig_atomic_t refcount_; - - /// Name of the shared library. - ACE_TCHAR *dll_name_; - - /// Handle to the actual library loaded by the OS. - ACE_SHLIB_HANDLE handle_; - - /// Keeps track of whether or not open() has ever been called. This - /// helps get around problem on Linux, and perhaps other OS's, that - /// seg-fault if dlerror() is called before the ld library has been - /// initialized by a call to dlopen(). - static sig_atomic_t open_called_; - -#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) - /// Synchronization variable for the MT_SAFE Repository - ACE_Thread_Mutex lock_; -#endif /* ACE_MT_SAFE */ -}; - -class ACE_Framework_Repository; - -/** - * @class ACE_DLL_Manager - * - * @brief This class is a singleton and serves as a factory and - * repository for instances of ACE_DLL_Handle. - * - * This class is a singleton whose lifetime is managed by the - * ACE_Framework_Repository. Although it is normally meant to be - * used directly only by ACE_DLL, applications can call the unload_policy() - * methods in order get/set the the dll unload policy. Unload policies include - * per_process/per-dll and eager/lazy. Dlls can export set their own policy - * by using the ACE_DLL_UNLOAD_POLICY macro found in config-all.h. If a dll - * choses to set an unload policy, it will be used when the per-dll policy - * (the default) is in effect. If the per-dll policy is in effect and a dll - * has not chosen to set a policy, the current per-process policy will be - * used. - * - * The following policy macros are provided in config-all.h: - * - * ACE_DLL_UNLOAD_POLICY_PER_PROCESS - Per-process policy that unloads dlls - * eagerly. - * - * ACE_DLL_UNLOAD_POLICY_PER_DLL - Apply policy on a per-dll basis. If the - * dll doesn't use one of the macros below, the current per-process policy - * will be used. - * - * ACE_DLL_UNLOAD_POLICY_LAZY - Don't unload dll when refcount reaches - * zero, i.e., wait for either an explicit unload request or program exit. - * - * ACE_DLL_UNLOAD_POLICY_DEFAULT - Default policy allows dlls to control - * their own destinies, but will unload those that don't make a choice eagerly. - * - */ -class ACE_Export ACE_DLL_Manager -{ -public: - friend class ACE_Framework_Repository; - friend class ACE_Object_Manager; - - enum - { - DEFAULT_SIZE = ACE_DEFAULT_DLL_MANAGER_SIZE - }; - - /// Return a unique instance - static ACE_DLL_Manager *instance (int size = ACE_DLL_Manager::DEFAULT_SIZE); - - /// Factory for ACE_DLL_Handle objects. If one already exits, - /// its refcount is incremented. - ACE_DLL_Handle *open_dll (const ACE_TCHAR *dll_name, - int openmode, - ACE_SHLIB_HANDLE handle); - - /// Close the underlying dll. Decrements the refcount. - int close_dll (const ACE_TCHAR *dll_name); - - /// Returns the current per-process UNLOAD_POLICY. - u_long unload_policy (void) const; - - /// Set the per-process UNLOAD_POLICY. If the policy is changed from - /// LAZY to EAGER, then it will also unload any dlls with zero - /// refcounts. - void unload_policy (u_long unload_policy); - -protected: - - /// Default constructor. - ACE_DLL_Manager (int size = ACE_DLL_Manager::DEFAULT_SIZE); - - /// Destructor. - ~ACE_DLL_Manager (void); - - /// Allocate handle_vector_. - int open (int size); - - /// Close all open dlls and deallocate memory. - int close (void); - - /// Find dll in handle_vector_. - ACE_DLL_Handle *find_dll (const ACE_TCHAR *dll_name) const; - - /// Applies strategy for unloading dll. - int unload_dll (ACE_DLL_Handle *dll_handle, int force_unload = 0); - -private: - - /// Close the singleton instance. - static void close_singleton (void); - - /// Disallow copying and assignment since we don't handle these. - ACE_DLL_Manager (const ACE_DLL_Manager &); - void operator= (const ACE_DLL_Manager &); - -private: - - /// Vector containing all loaded handle objects. - ACE_DLL_Handle **handle_vector_; - - /// Current number of handles. - int current_size_; - - /// Maximum number of handles. - int total_size_; - - /// Unload strategy. - u_long unload_policy_; - - /// Pointer to a process-wide ACE_DLL_Manager. - static ACE_DLL_Manager *instance_; - -#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) - /// Synchronization variable for the MT_SAFE Repository - ACE_Thread_Mutex lock_; -#endif /* ACE_MT_SAFE */ - -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" -#endif /* ACE_DLL_MANAGER_H */ diff --git a/externals/ace/Date_Time.cpp b/externals/ace/Date_Time.cpp deleted file mode 100644 index eff0f273fe7..00000000000 --- a/externals/ace/Date_Time.cpp +++ /dev/null @@ -1,10 +0,0 @@ -// Date_Time.cpp -// $Id: Date_Time.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Date_Time.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Date_Time.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID(ace, Date_Time, "$Id: Date_Time.cpp 80826 2008-03-04 14:51:23Z wotte $") diff --git a/externals/ace/Date_Time.h b/externals/ace/Date_Time.h deleted file mode 100644 index a15d435eeb8..00000000000 --- a/externals/ace/Date_Time.h +++ /dev/null @@ -1,125 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file Date_Time.h - * - * $Id: Date_Time.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Tim Harrison (harrison@cs.wustl.edu) (and he's darn proud of this ;-)) - * - */ -//========================================================================== - -#ifndef ACE_DATE_TIME_H -#define ACE_DATE_TIME_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -class ACE_Time_Value; - -/** - * @class ACE_Date_Time - * - * @brief System independent representation of date and time. - */ -class ACE_Export ACE_Date_Time -{ -public: - /// Constructor initializes current time/date info. - ACE_Date_Time (void); - - /// Constructor initializes with the given ACE_Time_Value - explicit ACE_Date_Time (const ACE_Time_Value& timevalue); - - /// Constructor with init values, no check for validy - /// Set/get portions of ACE_Date_Time, no check for validity. - ACE_Date_Time (long day, - long month = 0, - long year = 0, - long hour = 0, - long minute = 0, - long second = 0, - long microsec = 0, - long wday = 0); - - /// Update to the current time/date. - void update (void); - - /// Update to the given ACE_Time_Value - void update (const ACE_Time_Value& timevalue); - - /// Get day. - long day (void) const; - - /// Set day. - void day (long day); - - /// Get month. - long month (void) const; - - /// Set month. - void month (long month); - - /// Get year. - long year (void) const; - - /// Set year. - void year (long year); - - /// Get hour. - long hour (void) const; - - /// Set hour. - void hour (long hour); - - /// Get minute. - long minute (void) const; - - /// Set minute. - void minute (long minute); - - /// Get second. - long second (void) const; - - /// Set second. - void second (long second); - - /// Get microsec. - long microsec (void) const; - - /// Set microsec. - void microsec (long microsec); - - /// Get weekday. - long weekday (void) const; - - /// Set weekday. - void weekday (long wday); - -private: - long day_; - long month_; - long year_; - long hour_; - long minute_; - long second_; - long microsec_; - long wday_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Date_Time.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_DATE_TIME_H */ diff --git a/externals/ace/Date_Time.inl b/externals/ace/Date_Time.inl deleted file mode 100644 index d34807d83a4..00000000000 --- a/externals/ace/Date_Time.inl +++ /dev/null @@ -1,219 +0,0 @@ -// -*- C++ -*- -// -// $Id: Date_Time.inl 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Global_Macros.h" -#include "ace/Time_Value.h" -#include "ace/OS_NS_sys_time.h" -#include "ace/OS_NS_time.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE void -ACE_Date_Time::update (const ACE_Time_Value& timevalue) -{ -#if defined (ACE_HAS_WINCE) - // CE doesn't do localtime(). - FILETIME file_time = timevalue; - FILETIME local_file_time; - SYSTEMTIME sys_time; - ::FileTimeToLocalFileTime (&file_time, &local_file_time); - ::FileTimeToSystemTime (&local_file_time, &sys_time); - this->day_ = sys_time.wDay; - this->month_ = sys_time.wMonth; - this->year_ = sys_time.wYear; - this->hour_ = sys_time.wHour; - this->minute_ = sys_time.wMinute; - this->second_ = sys_time.wSecond; - this->microsec_ = sys_time.wMilliseconds * 1000; - this->wday_ = sys_time.wDayOfWeek; -#else - time_t time = timevalue.sec (); - struct tm tm_time; - ACE_OS::localtime_r (&time, &tm_time); - this->day_ = tm_time.tm_mday; - this->month_ = tm_time.tm_mon + 1; // localtime's months are 0-11 - this->year_ = tm_time.tm_year + 1900; // localtime reports years since 1900 - this->hour_ = tm_time.tm_hour; - this->minute_ = tm_time.tm_min; - this->second_ = tm_time.tm_sec; - this->microsec_ = timevalue.usec (); - this->wday_ = tm_time.tm_wday; -#endif /* ACE_HAS_WINCE */ -} - -ACE_INLINE void -ACE_Date_Time::update (void) -{ - ACE_TRACE ("ACE_Date_Time::update"); - - update(ACE_OS::gettimeofday ()); -} - -ACE_INLINE -ACE_Date_Time::ACE_Date_Time (void) -{ - ACE_TRACE ("ACE_Date_Time::ACE_Date_Time"); - this->update (); -} - -ACE_INLINE -ACE_Date_Time::ACE_Date_Time (const ACE_Time_Value& timevalue) -{ - ACE_TRACE ("ACE_Date_Time::ACE_Date_Time: timevalue"); - this->update (timevalue); -} - -// Constructor with init values, no check for validy -ACE_INLINE -ACE_Date_Time::ACE_Date_Time (long day, - long month, - long year, - long hour, - long minute, - long second, - long microsec, - long wday) - : day_ (day), - month_ (month), - year_ (year), - hour_ (hour), - minute_ (minute), - second_ (second), - microsec_ (microsec), - wday_ (wday) -{ - ACE_TRACE ("ACE_Date_Time::ACE_Date_Time"); -} - -// set/get portions of ACE_Date_Time, no check for validy - -// get day -ACE_INLINE long -ACE_Date_Time::day (void) const -{ - ACE_TRACE ("ACE_Date_Time::day"); - return day_; -} - -// set day -ACE_INLINE void -ACE_Date_Time::day (long day) -{ - ACE_TRACE ("ACE_Date_Time::day"); - day_ = day; -} - -// get month -ACE_INLINE long -ACE_Date_Time::month (void) const -{ - ACE_TRACE ("ACE_Date_Time::month"); - return month_; -} - -// set month -ACE_INLINE void -ACE_Date_Time::month (long month) -{ - ACE_TRACE ("ACE_Date_Time::month"); - month_ = month; -} - -// get year -ACE_INLINE long -ACE_Date_Time::year (void) const -{ - ACE_TRACE ("ACE_Date_Time::year"); - return year_; -} - -// set year -ACE_INLINE void -ACE_Date_Time::year (long year) -{ - ACE_TRACE ("ACE_Date_Time::year"); - year_ = year; -} - -// get hour -ACE_INLINE long -ACE_Date_Time::hour (void) const -{ - ACE_TRACE ("ACE_Date_Time::hour"); - return hour_; -} - -// set hour -ACE_INLINE void -ACE_Date_Time::hour (long hour) -{ - ACE_TRACE ("ACE_Date_Time::hour"); - hour_ = hour; -} - -// get minute -ACE_INLINE long -ACE_Date_Time::minute (void) const -{ - ACE_TRACE ("ACE_Date_Time::minute"); - return minute_; -} - -// set minute -ACE_INLINE void -ACE_Date_Time::minute (long minute) -{ - ACE_TRACE ("ACE_Date_Time::minute"); - minute_ = minute; -} - -// get second -ACE_INLINE long -ACE_Date_Time::second (void) const -{ - ACE_TRACE ("ACE_Date_Time::second"); - return second_; -} - -// set second -ACE_INLINE void -ACE_Date_Time::second (long second) -{ - ACE_TRACE ("ACE_Date_Time::second"); - second_ = second; -} - -// get microsec -ACE_INLINE long -ACE_Date_Time::microsec (void) const -{ - ACE_TRACE ("ACE_Date_Time::microsec"); - return microsec_; -} - -// set microsec -ACE_INLINE void -ACE_Date_Time::microsec (long microsec) -{ - ACE_TRACE ("ACE_Date_Time::microsec"); - microsec_ = microsec; -} - -// get wday -ACE_INLINE long -ACE_Date_Time::weekday (void) const -{ - ACE_TRACE ("ACE_Date_Time::weekday"); - return wday_; -} - -// set wday -ACE_INLINE void -ACE_Date_Time::weekday (long wday) -{ - ACE_TRACE ("ACE_Date_Time::weekday"); - wday_ = wday; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Default_Constants.h b/externals/ace/Default_Constants.h deleted file mode 100644 index 1c0743b523c..00000000000 --- a/externals/ace/Default_Constants.h +++ /dev/null @@ -1,605 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Default_Constants.h - * - * $Id: Default_Constants.h 87487 2009-11-12 07:54:39Z johnnyw $ - * - * @author Douglas C. Schmidt - * @author Jesper S. M|ller - * @author and a cast of thousands... - * - * This one is split from the famous OS.h - */ -//============================================================================= - -#ifndef ACE_DEFAULT_CONSTANTS_H -#define ACE_DEFAULT_CONSTANTS_H -#include /**/ "ace/pre.h" - -// Included just keep compilers that see #pragma directive first -// happy. -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -// For _POSIX_TIMER_MAX -#include "ace/os_include/os_limits.h" - -// Define the default constants for ACE. Many of these are used for -// the ACE tests and applications. You can change these values by -// defining the macros in your config.h file. -# if !defined (ACE_DEFAULT_CLOSE_ALL_HANDLES) -# define ACE_DEFAULT_CLOSE_ALL_HANDLES true -# endif /* ACE_DEFAULT_CLOSE_ALL_HANDLES */ - -// The maximum length for a fully qualified Internet name. -# if !defined(ACE_MAX_FULLY_QUALIFIED_NAME_LEN) -# define ACE_MAX_FULLY_QUALIFIED_NAME_LEN 256 -# endif /* ACE_MAX_FULLY_QUALIFIED_NAME_LEN */ - -#if !defined (ACE_DEFAULT_PAGEFILE_POOL_BASE) -#define ACE_DEFAULT_PAGEFILE_POOL_BASE (void *) 0 -#endif /* ACE_DEFAULT_PAGEFILE_POOL_BASE */ - -#if !defined (ACE_DEFAULT_PAGEFILE_POOL_SIZE) -#define ACE_DEFAULT_PAGEFILE_POOL_SIZE (size_t) 0x01000000 -#endif /* ACE_DEFAULT_PAGEFILE_POOL_SIZE */ - -#if !defined (ACE_DEFAULT_PAGEFILE_POOL_CHUNK) -#define ACE_DEFAULT_PAGEFILE_POOL_CHUNK (size_t) 0x00010000 -#endif /* ACE_DEFAULT_PAGEFILE_POOL_CHUNK */ - -#if !defined (ACE_DEFAULT_PAGEFILE_POOL_NAME) -#define ACE_DEFAULT_PAGEFILE_POOL_NAME ACE_TEXT ("Default_ACE_Pagefile_Memory_Pool") -#endif /* ACE_DEFAULT_PAGEFILE_POOL_NAME */ - -#if !defined (ACE_DEFAULT_MESSAGE_BLOCK_PRIORITY) -#define ACE_DEFAULT_MESSAGE_BLOCK_PRIORITY 0 -#endif /* ACE_DEFAULT_MESSAGE_BLOCK_PRIORITY */ - -#if !defined (ACE_DEFAULT_SERVICE_REPOSITORY_SIZE) -#define ACE_DEFAULT_SERVICE_REPOSITORY_SIZE 1024 -#endif /* ACE_DEFAULT_SERVICE_REPOSITORY_SIZE */ - -#if !defined (ACE_DEFAULT_SERVICE_GESTALT_SIZE) -#define ACE_DEFAULT_SERVICE_GESTALT_SIZE 1024 -#endif /* ACE_DEFAULT_SERVICE_GESTALT_SIZE */ - -#if !defined (ACE_REACTOR_NOTIFICATION_ARRAY_SIZE) -#define ACE_REACTOR_NOTIFICATION_ARRAY_SIZE 1024 -#endif /* ACE_REACTOR_NOTIFICATION_ARRAY_SIZE */ - -# if !defined (ACE_DEFAULT_TIMEOUT) -# define ACE_DEFAULT_TIMEOUT 5 -# endif /* ACE_DEFAULT_TIMEOUT */ - -# if !defined (ACE_DEFAULT_BACKLOG) -# define ACE_DEFAULT_BACKLOG 5 -# endif /* ACE_DEFAULT_BACKLOG */ - -# if !defined (ACE_DEFAULT_ASYNCH_BACKLOG) -# define ACE_DEFAULT_ASYNCH_BACKLOG 5 -# endif /* ACE_DEFAULT_ASYNCH_BACKLOG */ - -# if !defined (ACE_DEFAULT_THREADS) -# define ACE_DEFAULT_THREADS 1 -# endif /* ACE_DEFAULT_THREADS */ - -// The following 3 defines are used in the IP multicast and broadcast tests. -# if !defined (ACE_DEFAULT_BROADCAST_PORT) -# define ACE_DEFAULT_BROADCAST_PORT 20000 -# endif /* ACE_DEFAULT_BROADCAST_PORT */ - -# if !defined (ACE_DEFAULT_MULTICAST_PORT) -# define ACE_DEFAULT_MULTICAST_PORT 20001 -# endif /* ACE_DEFAULT_MULTICAST_PORT */ - -# if !defined (ACE_DEFAULT_MULTICAST_ADDR) -// This address MUST be within the range for host group addresses: -// 224.0.0.0 to 239.255.255.255. -# define ACE_DEFAULT_MULTICAST_ADDR "224.9.9.2" -# endif /* ACE_DEFAULT_MULTICAST_ADDR */ - -# if defined (ACE_HAS_IPV6) -# if !defined (ACE_DEFAULT_MULTICASTV6_ADDR) -// This address should be within the range for site-local addresses: -// ff05::0/16 . -# define ACE_DEFAULT_MULTICASTV6_ADDR "ff05:0::ff01:1" -# endif /* ACE_DEFAULT_MULTICASTV6_ADDR */ -# endif - -// Default port number for HTTP. -# if !defined (ACE_DEFAULT_HTTP_SERVER_PORT) -# define ACE_DEFAULT_HTTP_SERVER_PORT 80 -# endif /* ACE_DEFAULT_HTTP_SERVER_PORT */ - -// Used in many IPC_SAP tests -# if !defined (ACE_DEFAULT_SERVER_PORT) -# define ACE_DEFAULT_SERVER_PORT 20002 -# endif /* ACE_DEFAULT_SERVER_PORT */ - -# if !defined (ACE_DEFAULT_HTTP_PORT) -# define ACE_DEFAULT_HTTP_PORT 80 -# endif /* ACE_DEFAULT_HTTP_PORT */ - -# if !defined (ACE_DEFAULT_MAX_SOCKET_BUFSIZ) -# define ACE_DEFAULT_MAX_SOCKET_BUFSIZ 65536 -# endif /* ACE_DEFAULT_MAX_SOCKET_BUFSIZ */ - -# if !defined (ACE_DEFAULT_SERVER_PORT_STR) -# define ACE_DEFAULT_SERVER_PORT_STR ACE_TEXT("20002") -# endif /* ACE_DEFAULT_SERVER_PORT_STR */ - -// Used for the Service_Directory test -# if !defined (ACE_DEFAULT_SERVICE_PORT) -# define ACE_DEFAULT_SERVICE_PORT 20003 -# endif /* ACE_DEFAULT_SERVICE_PORT */ - -// Used for the ACE_Thread_Spawn test -# if !defined (ACE_DEFAULT_THR_PORT ) -# define ACE_DEFAULT_THR_PORT 20004 -# endif /* ACE_DEFAULT_THR_PORT */ - -// Used for tests -# if !defined (ACE_DEFAULT_LOCAL_PORT) -# define ACE_DEFAULT_LOCAL_PORT 20005 -# endif /* ACE_DEFAULT_LOCAL_PORT */ - -// Used for Connector tests -# if !defined (ACE_DEFAULT_LOCAL_PORT_STR) -# define ACE_DEFAULT_LOCAL_PORT_STR "20005" -# endif /* ACE_DEFAULT_LOCAL_PORT_STR */ - -// Used for the name server. -# if !defined (ACE_DEFAULT_NAME_SERVER_PORT) -# define ACE_DEFAULT_NAME_SERVER_PORT 20006 -# endif /* ACE_DEFAULT_NAME_SERVER_PORT */ - -# if !defined (ACE_DEFAULT_NAME_SERVER_PORT_STR) -# define ACE_DEFAULT_NAME_SERVER_PORT_STR "20006" -# endif /* ACE_DEFAULT_NAME_SERVER_PORT_STR */ - -// Used for the token server. -# if !defined (ACE_DEFAULT_TOKEN_SERVER_PORT) -# define ACE_DEFAULT_TOKEN_SERVER_PORT 20007 -# endif /* ACE_DEFAULT_TOKEN_SERVER_PORT */ - -# if !defined (ACE_DEFAULT_TOKEN_SERVER_PORT_STR) -# define ACE_DEFAULT_TOKEN_SERVER_PORT_STR "20007" -# endif /* ACE_DEFAULT_TOKEN_SERVER_PORT_STR */ - -// Used for the logging server. -# if !defined (ACE_DEFAULT_LOGGING_SERVER_PORT) -# define ACE_DEFAULT_LOGGING_SERVER_PORT 20008 -# endif /* ACE_DEFAULT_LOGGING_SERVER_PORT */ - -# if !defined (ACE_DEFAULT_LOGGING_SERVER_PORT_STR) -# define ACE_DEFAULT_LOGGING_SERVER_PORT_STR "20008" -# endif /* ACE_DEFAULT_LOGGING_SERVER_PORT_STR */ - -// Used for the logging server. -# if !defined (ACE_DEFAULT_THR_LOGGING_SERVER_PORT) -# define ACE_DEFAULT_THR_LOGGING_SERVER_PORT 20008 -# endif /* ACE_DEFAULT_THR_LOGGING_SERVER_PORT */ - -# if !defined (ACE_DEFAULT_THR_LOGGING_SERVER_PORT_STR) -# define ACE_DEFAULT_THR_LOGGING_SERVER_PORT_STR "20008" -# endif /* ACE_DEFAULT_THR_LOGGING_SERVER_PORT_STR */ - -// Used for the time server. -# if !defined (ACE_DEFAULT_TIME_SERVER_PORT) -# define ACE_DEFAULT_TIME_SERVER_PORT 20009 -# endif /* ACE_DEFAULT_TIME_SERVER_PORT */ - -# if !defined (ACE_DEFAULT_TIME_SERVER_PORT_STR) -# define ACE_DEFAULT_TIME_SERVER_PORT_STR "20009" -# endif /* ACE_DEFAULT_TIME_SERVER_PORT_STR */ - -# if !defined (ACE_DEFAULT_TIME_SERVER_STR) -# define ACE_DEFAULT_TIME_SERVER_STR "ACE_TS_TIME" -# endif /* ACE_DEFAULT_TIME_SERVER_STR */ - -// Used by the FIFO tests -# if !defined (ACE_DEFAULT_RENDEZVOUS) -# if defined (ACE_HAS_STREAM_PIPES) -# define ACE_DEFAULT_RENDEZVOUS ACE_TEXT("/tmp/fifo.ace") -# else -# define ACE_DEFAULT_RENDEZVOUS ACE_TEXT("localhost:20010") -# endif /* ACE_HAS_STREAM_PIPES */ -# endif /* ACE_DEFAULT_RENDEZVOUS */ - -// Used for the UNIX syslog logging interface to ACE_Log_Msg. -# ifndef ACE_DEFAULT_SYSLOG_FACILITY -# define ACE_DEFAULT_SYSLOG_FACILITY LOG_USER -# endif /* ACE_DEFAULT_SYSLOG_FACILITY */ - -# if !defined (ACE_HAS_STREAM_LOG_MSG_IPC) -# if defined (ACE_HAS_STREAM_PIPES) -# define ACE_HAS_STREAM_LOG_MSG_IPC 1 -# else -# define ACE_HAS_STREAM_LOG_MSG_IPC 0 -# endif /* ACE_HAS_STREAM_PIPES */ -# endif /* !ACE_HAS_STREAM_LOG_MSG_IPC */ - -# if !defined (ACE_DEFAULT_LOGGER_KEY) -# if (ACE_HAS_STREAM_LOG_MSG_IPC == 1) -# define ACE_DEFAULT_LOGGER_KEY ACE_TEXT ("/tmp/server_daemon") -# else -# define ACE_DEFAULT_LOGGER_KEY ACE_TEXT ("localhost:20012") -# endif /* ACE_HAS_STREAM_LOG_MSG_IPC==1 */ -# endif /* ACE_DEFAULT_LOGGER_KEY */ - -// The way to specify the local host for loopback IP. This is usually -// "localhost" but it may need changing on some platforms. -# if !defined (ACE_LOCALHOST) -# define ACE_LOCALHOST ACE_TEXT ("localhost") -# endif - -// This specification for an IPv6 localhost should work on all platforms -// supporting IPv6 -# if defined (ACE_HAS_IPV6) -# if !defined (ACE_IPV6_LOCALHOST) -# define ACE_IPV6_LOCALHOST ACE_TEXT ("::1") -# endif /* ACE_IPV6_LOCALHOST*/ -#endif /* ACE_HAS_IPV6 */ - -// This specification for an IPv6 ANY address should work on all platforms -// supporting IPv6 -# if defined (ACE_HAS_IPV6) -# if !defined (ACE_IPV6_ANY) -# define ACE_IPV6_ANY ACE_TEXT ("::") -# endif /* ACE_IPV6_ANY*/ -#endif /* ACE_HAS_IPV6 */ - -# if !defined (ACE_DEFAULT_SERVER_HOST) -# if defined (ACE_HAS_IPV6) -# define ACE_DEFAULT_SERVER_HOST ACE_IPV6_LOCALHOST -# else /*ACE_HAS_IPV6*/ -# define ACE_DEFAULT_SERVER_HOST ACE_LOCALHOST -# endif /*ACE_HAS_IPV6*/ -# endif /* ACE_DEFAULT_SERVER_HOST */ - -// Default shared memory key -# if !defined (ACE_DEFAULT_SHM_KEY) -# define ACE_DEFAULT_SHM_KEY 1234 -# endif /* ACE_DEFAULT_SHM_KEY */ - -// Default address for shared memory mapped files and SYSV shared memory -// (defaults to 64 M). -# if !defined (ACE_DEFAULT_BASE_ADDR) -# define ACE_DEFAULT_BASE_ADDR ((char *) (64 * 1024 * 1024)) -# endif /* ACE_DEFAULT_BASE_ADDR */ - -// Default segment size used by SYSV shared memory (128 K) -# if !defined (ACE_DEFAULT_SEGMENT_SIZE) -# define ACE_DEFAULT_SEGMENT_SIZE 1024 * 128 -# endif /* ACE_DEFAULT_SEGMENT_SIZE */ - -// Maximum number of SYSV shared memory segments -// (does anyone know how to figure out the right values?!) -# if !defined (ACE_DEFAULT_MAX_SEGMENTS) -# define ACE_DEFAULT_MAX_SEGMENTS 6 -# endif /* ACE_DEFAULT_MAX_SEGMENTS */ - -// Name of the map that's stored in shared memory. -# if !defined (ACE_NAME_SERVER_MAP) -# define ACE_NAME_SERVER_MAP "Name Server Map" -# endif /* ACE_NAME_SERVER_MAP */ - -// Default file permissions. -# if !defined (ACE_DEFAULT_FILE_PERMS) -# if defined (ACE_VXWORKS) -# define ACE_DEFAULT_FILE_PERMS (S_IRUSR | S_IWUSR| S_IRGRP| S_IROTH) -# else -# define ACE_DEFAULT_FILE_PERMS 0644 -# endif /* ACE_VXWORKS */ -# endif /* ACE_DEFAULT_FILE_PERMS */ - -// Default directory permissions. -# if !defined (ACE_DEFAULT_DIR_PERMS) -# define ACE_DEFAULT_DIR_PERMS 0755 -# endif /* ACE_DEFAULT_DIR_PERMS */ - -# if !defined (ACE_DEFAULT_TIMEPROBE_TABLE_SIZE) -# define ACE_DEFAULT_TIMEPROBE_TABLE_SIZE 8 * 1024 -# endif /* ACE_DEFAULT_TIMEPROBE_TABLE_SIZE */ - -// Default size of the ACE Map_Manager. -# if !defined (ACE_DEFAULT_MAP_SIZE) -# define ACE_DEFAULT_MAP_SIZE 1024 -# endif /* ACE_DEFAULT_MAP_SIZE */ - -# if defined (ACE_DEFAULT_MAP_SIZE) && (ACE_DEFAULT_MAP_SIZE == 0) -# error ACE_DEFAULT_MAP_SIZE should not be zero -# endif /* ACE_DEFAULT_MAP_SIZE */ - -// Defaults for ACE Timer Wheel -# if !defined (ACE_DEFAULT_TIMER_WHEEL_SIZE) -# define ACE_DEFAULT_TIMER_WHEEL_SIZE 1024 -# endif /* ACE_DEFAULT_TIMER_WHEEL_SIZE */ - -# if !defined (ACE_DEFAULT_TIMER_WHEEL_RESOLUTION) -# define ACE_DEFAULT_TIMER_WHEEL_RESOLUTION 100 -# endif /* ACE_DEFAULT_TIMER_WHEEL_RESOLUTION */ - -// Default size for ACE Timer Hash table -# if !defined (ACE_DEFAULT_TIMER_HASH_TABLE_SIZE) -# define ACE_DEFAULT_TIMER_HASH_TABLE_SIZE 1024 -# endif /* ACE_DEFAULT_TIMER_HASH_TABLE_SIZE */ - -// Defaults for the ACE Free List -# if !defined (ACE_DEFAULT_FREE_LIST_PREALLOC) -# define ACE_DEFAULT_FREE_LIST_PREALLOC 0 -# endif /* ACE_DEFAULT_FREE_LIST_PREALLOC */ - -# if !defined (ACE_DEFAULT_FREE_LIST_LWM) -# define ACE_DEFAULT_FREE_LIST_LWM 0 -# endif /* ACE_DEFAULT_FREE_LIST_LWM */ - -# if !defined (ACE_DEFAULT_FREE_LIST_HWM) -# define ACE_DEFAULT_FREE_LIST_HWM 25000 -# endif /* ACE_DEFAULT_FREE_LIST_HWM */ - -# if !defined (ACE_DEFAULT_FREE_LIST_INC) -# define ACE_DEFAULT_FREE_LIST_INC 100 -# endif /* ACE_DEFAULT_FREE_LIST_INC */ - -# if !defined (ACE_UNIQUE_NAME_LEN) -# define ACE_UNIQUE_NAME_LEN 100 -# endif /* ACE_UNIQUE_NAME_LEN */ - -# if !defined (ACE_MAX_DGRAM_SIZE) - // This is just a guess. 8k is the normal limit on - // most machines because that's what NFS expects. -# define ACE_MAX_DGRAM_SIZE 8192 -# endif /* ACE_MAX_DGRAM_SIZE */ - -# if !defined (ACE_DEFAULT_ARGV_BUFSIZ) -# define ACE_DEFAULT_ARGV_BUFSIZ 1024 * 4 -# endif /* ACE_DEFAULT_ARGV_BUFSIZ */ - -// A free list which create more elements when there aren't enough -// elements. -# define ACE_FREE_LIST_WITH_POOL 1 - -// A simple free list which doen't allocate/deallocate elements. -# define ACE_PURE_FREE_LIST 2 - -# if defined (ACE_WIN32) - -// This is necessary to work around bugs with Win32 non-blocking -// connects... -# if !defined (ACE_NON_BLOCKING_BUG_DELAY) -# define ACE_NON_BLOCKING_BUG_DELAY 35000 -# endif /* ACE_NON_BLOCKING_BUG_DELAY */ -# endif /*ACE_WIN32*/ - -// Max size of an ACE Log Record data buffer. This can be reset in -// the config.h file if you'd like to increase or decrease the size. -# if !defined (ACE_MAXLOGMSGLEN) -# define ACE_MAXLOGMSGLEN 4 * 1024 -# endif /* ACE_MAXLOGMSGLEN */ - -// Max size of an ACE Token. -# define ACE_MAXTOKENNAMELEN 40 - -// Max size of an ACE Token client ID. -# define ACE_MAXCLIENTIDLEN MAXHOSTNAMELEN + 20 - -/// Max udp packet size -#if !defined (ACE_MAX_UDP_PACKET_SIZE) -#define ACE_MAX_UDP_PACKET_SIZE 65536 -#endif - -/** - * @name Default values to control CDR classes memory allocation strategies - */ -//@{ - -/// Control the initial size of all CDR buffers, application -/// developers may want to optimize this value to fit their request -/// size -#if !defined (ACE_DEFAULT_CDR_BUFSIZE) -# define ACE_DEFAULT_CDR_BUFSIZE 512 -#endif /* ACE_DEFAULT_CDR_BUFSIZE */ - -#if (ACE_DEFAULT_CDR_BUFSIZE == 0) -# error: ACE_DEFAULT_CDR_BUFSIZE should be bigger then 0 -#endif - -/// Stop exponential growth of CDR buffers to avoid overallocation -#if !defined (ACE_DEFAULT_CDR_EXP_GROWTH_MAX) -# define ACE_DEFAULT_CDR_EXP_GROWTH_MAX 65536 -#endif /* ACE_DEFAULT_CDR_EXP_GROWTH_MAX */ - -/// Control CDR buffer growth after maximum exponential growth is -/// reached -#if !defined (ACE_DEFAULT_CDR_LINEAR_GROWTH_CHUNK) -# define ACE_DEFAULT_CDR_LINEAR_GROWTH_CHUNK 65536 -#endif /* ACE_DEFAULT_CDR_LINEAR_GROWTH_CHUNK */ -//@} - -/// Control the zero-copy optimizations for octet sequences -/** - * Large octet sequences can be sent without any copies by chaining - * them in the list of message blocks that represent a single CDR - * stream. However, if the octet sequence is too small the zero copy - * optimizations actually hurt performance. Octet sequences smaller - * than this value will be copied. - */ -#if !defined (ACE_DEFAULT_CDR_MEMCPY_TRADEOFF) -#define ACE_DEFAULT_CDR_MEMCPY_TRADEOFF 256 -#endif /* ACE_DEFAULT_CDR_MEMCPY_TRADEOFF */ - -#if defined (ACE_WIN32) - // Define the pathname separator characters for Win32 (ugh). -# define ACE_DIRECTORY_SEPARATOR_STR_A "\\" -# define ACE_DIRECTORY_SEPARATOR_CHAR_A '\\' -#else - // Define the pathname separator characters for UNIX. -# define ACE_DIRECTORY_SEPARATOR_STR_A "/" -# define ACE_DIRECTORY_SEPARATOR_CHAR_A '/' -#endif /* ACE_WIN32 */ - -// Define the Wide character and normal versions of some of the string macros -#if defined (ACE_HAS_WCHAR) -# define ACE_DIRECTORY_SEPARATOR_STR_W ACE_TEXT_WIDE(ACE_DIRECTORY_SEPARATOR_STR_A) -# define ACE_DIRECTORY_SEPARATOR_CHAR_W ACE_TEXT_WIDE(ACE_DIRECTORY_SEPARATOR_CHAR_A) -#endif /* ACE_HAS_WCHAR */ - -#define ACE_DIRECTORY_SEPARATOR_STR ACE_TEXT (ACE_DIRECTORY_SEPARATOR_STR_A) -#define ACE_DIRECTORY_SEPARATOR_CHAR ACE_TEXT (ACE_DIRECTORY_SEPARATOR_CHAR_A) - -#if !defined (ACE_DEFAULT_THREAD_PRIORITY) -# define ACE_DEFAULT_THREAD_PRIORITY (-0x7fffffffL - 1L) -#endif /* ACE_DEFAULT_THREAD_PRIORITY */ - -#if !defined (ACE_DEFAULT_THREAD_STACKSIZE) -# define ACE_DEFAULT_THREAD_STACKSIZE 0 -#endif /* ACE_DEFAULT_THREAD_STACKSIZE */ - -#if !defined (ACE_MAX_DEFAULT_PORT) -# define ACE_MAX_DEFAULT_PORT 65535 -#endif /* ACE_MAX_DEFAULT_PORT */ - -// Default number of ACE_Event_Handlers supported by -// ACE_Timer_Heap. -#if !defined (ACE_DEFAULT_TIMERS) && defined (_POSIX_TIMER_MAX) -# define ACE_DEFAULT_TIMERS _POSIX_TIMER_MAX -#endif /* ACE_DEFAULT_TIMERS */ - -#if !defined (ACE_DEFAULT_TIMERS) || (defined (ACE_DEFAULT_TIMERS) && (ACE_DEFAULT_TIMERS == 0)) -#error ACE_DEFAULT_TIMERS should be defined and not be zero -#endif /* ACE_DEFAULT_TIMERS */ - -#if defined (ACE_WIN32) -# define ACE_PLATFORM_A "Win32" -# define ACE_PLATFORM_EXE_SUFFIX_A ".exe" -#elif defined (ACE_VXWORKS) -# define ACE_PLATFORM_A "VxWorks" -# if defined (__RTP__) -# define ACE_PLATFORM_EXE_SUFFIX_A ".vxe" -# else -# define ACE_PLATFORM_EXE_SUFFIX_A ".out" -# endif -#else /* !ACE_WIN32 && !ACE_VXWORKS */ -# define ACE_PLATFORM_A "UNIX" -# define ACE_PLATFORM_EXE_SUFFIX_A "" -#endif /* ACE_WIN32 */ - -// Define the Wide character and normal versions of some of the string macros -#if defined (ACE_HAS_WCHAR) -# define ACE_PLATFORM_W ACE_TEXT_WIDE(ACE_PLATFORM_A) -# define ACE_PLATFORM_EXE_SUFFIX_W ACE_TEXT_WIDE(ACE_PLATFORM_EXE_SUFFIX_A) -#endif /* ACE_HAS_WCHAR */ - -#define ACE_PLATFORM ACE_TEXT (ACE_PLATFORM_A) -#define ACE_PLATFORM_EXE_SUFFIX ACE_TEXT (ACE_PLATFORM_EXE_SUFFIX_A) - -#if defined (ACE_WIN32) -# define ACE_LD_SEARCH_PATH ACE_TEXT ("PATH") -# define ACE_LD_SEARCH_PATH_SEPARATOR_STR ACE_TEXT (";") -# define ACE_DLL_SUFFIX ACE_TEXT (".dll") -# if !defined (ACE_DLL_PREFIX) -# define ACE_DLL_PREFIX ACE_TEXT ("") -# endif /* !ACE_DLL_PREFIX */ -#else /* !ACE_WIN32 */ -# if !defined (ACE_LD_SEARCH_PATH) -# define ACE_LD_SEARCH_PATH ACE_TEXT ("LD_LIBRARY_PATH") -# endif /* ACE_LD_SEARCH_PATH */ -# if !defined (ACE_LD_SEARCH_PATH_SEPARATOR_STR) -# define ACE_LD_SEARCH_PATH_SEPARATOR_STR ACE_TEXT (":") -# endif /* ACE_LD_SEARCH_PATH_SEPARATOR_STR */ -#endif /* ACE_WIN32 */ - -#if !defined (ACE_DLL_SUFFIX) -# define ACE_DLL_SUFFIX ACE_TEXT (".so") -#endif /* ACE_DLL_SUFFIX */ - -#if !defined (ACE_DLL_PREFIX) -# define ACE_DLL_PREFIX ACE_TEXT ("lib") -#endif /* ACE_DLL_PREFIX */ - -#if defined (ACE_WIN32) -// Used for dynamic linking -# if !defined (ACE_DEFAULT_SVC_CONF) -# if (ACE_USES_CLASSIC_SVC_CONF == 1) -# define ACE_DEFAULT_SVC_CONF ACE_TEXT (".\\svc.conf") -# else -# define ACE_DEFAULT_SVC_CONF ACE_TEXT (".\\svc.conf.xml") -# endif /* ACE_USES_CLASSIC_SVC_CONF ==1 */ -# endif /* ACE_DEFAULT_SVC_CONF */ -#endif /* ACE_WIN32 */ - - // Used for dynamic linking. -#if !defined (ACE_DEFAULT_SVC_CONF) -# if (ACE_USES_CLASSIC_SVC_CONF == 1) -# define ACE_DEFAULT_SVC_CONF ACE_TEXT ("./svc.conf") -# else -# define ACE_DEFAULT_SVC_CONF ACE_TEXT ("./svc.conf.xml") -# endif /* ACE_USES_CLASSIC_SVC_CONF ==1 */ -#endif /* ACE_DEFAULT_SVC_CONF */ - -#if !defined (ACE_LOGGER_KEY) -# define ACE_LOGGER_KEY ACE_TEXT ("/tmp/server_daemon") -#endif /* ACE_LOGGER_KEY */ - -// Theses defines are used by the ACE Name Server. -#if !defined (ACE_DEFAULT_LOCALNAME_A) -# define ACE_DEFAULT_LOCALNAME_A "localnames" -#endif /* ACE_DEFAULT_LOCALNAME_A */ -#if !defined (ACE_DEFAULT_GLOBALNAME_A) -# define ACE_DEFAULT_GLOBALNAME_A "globalnames" -#endif /* ACE_DEFAULT_GLOBALNAME_A */ - -// ACE_DEFAULT_NAMESPACE_DIR is for legacy mode apps. A better -// way of doing this is something like ACE_Lib_Find::get_temp_dir, since -// this directory may not exist -#if defined (ACE_LEGACY_MODE) -# if defined (ACE_WIN32) -# define ACE_DEFAULT_NAMESPACE_DIR_A "C:\\temp" -# else /* ACE_WIN32 */ -# define ACE_DEFAULT_NAMESPACE_DIR_A "/tmp" -# endif /* ACE_WIN32 */ -# if defined (ACE_HAS_WCHAR) -# define ACE_DEFAULT_NAMESPACE_DIR_W ACE_TEXT_WIDE(ACE_DEFAULT_NAMESPACE_DIR_A) -# endif /* ACE_HAS_WCHAR */ -# define ACE_DEFAULT_NAMESPACE_DIR ACE_TEXT(ACE_DEFAULT_NAMESPACE_DIR_A) -#endif /* ACE_LEGACY_MODE */ - -#if defined (ACE_HAS_WCHAR) -# define ACE_DEFAULT_LOCALNAME_W ACE_TEXT_WIDE(ACE_DEFAULT_LOCALNAME_A) -# define ACE_DEFAULT_GLOBALNAME_W ACE_TEXT_WIDE(ACE_DEFAULT_GLOBALNAME_A) -#endif /* ACE_HAS_WCHAR */ - -#define ACE_DEFAULT_LOCALNAME ACE_TEXT (ACE_DEFAULT_LOCALNAME_A) -#define ACE_DEFAULT_GLOBALNAME ACE_TEXT (ACE_DEFAULT_GLOBALNAME_A) - -#if !defined (ACE_DEFAULT_OPEN_PERMS) -# define ACE_DEFAULT_OPEN_PERMS ACE_DEFAULT_FILE_PERMS -#endif /* ACE_DEFAULT_OPEN_PERMS */ - -#if !defined (ACE_DEFAULT_RW_PROCESS_MUTEX_PERMS) -# if defined (ACE_WIN32) -# define ACE_DEFAULT_RW_PROCESS_MUTEX_PERMS ACE_DEFAULT_OPEN_PERMS -# else -# define ACE_DEFAULT_RW_PROCESS_MUTEX_PERMS (S_IRUSR | S_IWUSR) -# endif /* ACE_WIN32 */ -#endif /* ACE_DEFAULT_RW_PROCESS_MUTEX_PERMS */ - -# if defined (ACE_WIN32) - // The "null" device on Win32. -# define ACE_DEV_NULL "nul" -# define ACE_SYSCALL_FAILED 0xFFFFFFFF -# else /* !ACE_WIN32 */ - // The "null" device on UNIX. -# define ACE_DEV_NULL "/dev/null" -# define ACE_SYSCALL_FAILED -1 -# endif /* ACE_WIN32 */ - -#include /**/ "ace/post.h" -#endif /*ACE_DEFAULT_CONSTANTS_H*/ diff --git a/externals/ace/Dev_Poll_Reactor.cpp b/externals/ace/Dev_Poll_Reactor.cpp deleted file mode 100644 index e0adc19a418..00000000000 --- a/externals/ace/Dev_Poll_Reactor.cpp +++ /dev/null @@ -1,2610 +0,0 @@ -// $Id: Dev_Poll_Reactor.cpp 90177 2010-05-19 11:44:22Z vzykov $ - -#include "ace/OS_NS_errno.h" -#include "ace/Dev_Poll_Reactor.h" -#include "ace/Signal.h" -#include "ace/Sig_Handler.h" - -ACE_RCSID (ace, - Dev_Poll_Reactor, - "$Id: Dev_Poll_Reactor.cpp 90177 2010-05-19 11:44:22Z vzykov $") - -#if defined (ACE_HAS_EVENT_POLL) || defined (ACE_HAS_DEV_POLL) - -# include "ace/OS_NS_unistd.h" -# include "ace/OS_NS_fcntl.h" -# include "ace/OS_NS_stropts.h" - -# if defined (ACE_HAS_DEV_POLL) -# if defined (linux) -# include /**/ -# elif defined (HPUX_VERS) && HPUX_VERS < 1123 -# include /**/ -# else -# include /**/ -# endif /* linux */ -# endif /* ACE_HAS_DEV_POLL */ - -#if !defined (__ACE_INLINE__) -# include "ace/Dev_Poll_Reactor.inl" -#endif /* __ACE_INLINE__ */ - - -#include "ace/Handle_Set.h" -#include "ace/Reactor.h" -#include "ace/Timer_Heap.h" -#include "ace/Timer_Queue.h" -#include "ace/ACE.h" -#include "ace/Reverse_Lock_T.h" -#include "ace/Recursive_Thread_Mutex.h" -#include "ace/Null_Mutex.h" -#include "ace/os_include/os_poll.h" -#include "ace/OS_NS_sys_mman.h" -#include "ace/Guard_T.h" -#include "ace/OS_NS_string.h" -#include "ace/OS_NS_sys_time.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_Dev_Poll_Reactor_Notify::ACE_Dev_Poll_Reactor_Notify (void) - : dp_reactor_ (0) - , notification_pipe_ () - , max_notify_iterations_ (-1) -#if defined (ACE_HAS_REACTOR_NOTIFICATION_QUEUE) - , notification_queue_ () -#endif /* ACE_HAS_REACTOR_NOTIFICATION_QUEUE */ - , dispatching_ (false) -{ -} - -int -ACE_Dev_Poll_Reactor_Notify::open (ACE_Reactor_Impl *r, - ACE_Timer_Queue * /* timer_queue */, - int disable_notify_pipe) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor_Notify::open"); - - if (disable_notify_pipe == 0) - { - this->dp_reactor_ = dynamic_cast (r); - - if (this->dp_reactor_ == 0) - { - errno = EINVAL; - return -1; - } - - if (this->notification_pipe_.open () == -1) - return -1; - -#if defined (F_SETFD) - // close-on-exec - ACE_OS::fcntl (this->notification_pipe_.read_handle (), F_SETFD, 1); - ACE_OS::fcntl (this->notification_pipe_.write_handle (), F_SETFD, 1); -#endif /* F_SETFD */ - -#if defined (ACE_HAS_REACTOR_NOTIFICATION_QUEUE) - if (notification_queue_.open () == -1) - { - return -1; - } - - if (ACE::set_flags (this->notification_pipe_.write_handle (), - ACE_NONBLOCK) == -1) - return -1; -#endif /* ACE_HAS_REACTOR_NOTIFICATION_QUEUE */ - - // Set the read handle into non-blocking mode since we need to - // perform a "speculative" read when determining if there are - // notifications to dispatch. - if (ACE::set_flags (this->notification_pipe_.read_handle (), - ACE_NONBLOCK) == -1) - return -1; - } - - return 0; -} - -int -ACE_Dev_Poll_Reactor_Notify::close (void) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor_Notify::close"); - -#if defined (ACE_HAS_REACTOR_NOTIFICATION_QUEUE) - notification_queue_.reset (); -#endif /* ACE_HAS_REACTOR_NOTIFICATION_QUEUE */ - - return this->notification_pipe_.close (); -} - -int -ACE_Dev_Poll_Reactor_Notify::notify (ACE_Event_Handler *eh, - ACE_Reactor_Mask mask, - ACE_Time_Value *timeout) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor_Notify::notify"); - - // Just consider this method a "no-op" if there's no - // ACE_Dev_Poll_Reactor configured. - if (this->dp_reactor_ == 0) - return 0; - - ACE_Notification_Buffer buffer (eh, mask); - -#if defined (ACE_HAS_REACTOR_NOTIFICATION_QUEUE) - ACE_UNUSED_ARG (timeout); - ACE_Dev_Poll_Handler_Guard eh_guard (eh); - - // When using the queue, the push call indicates whether or not a pipe - // write is needed. If it's not, don't waste pipe space. - int push_result = this->notification_queue_.push_new_notification (buffer); - if (-1 == push_result || 1 == push_result) - return -1 == push_result ? -1 : 0; // Also decrement eh's reference count - - // The notification has been queued, so it will be delivered at some - // point (and may have been already); release the refcnt guard. - eh_guard.release (); - - // Now pop the pipe to force the callback for dispatching when ready. If - // the send fails due to a full pipe, don't fail - assume the already-sent - // pipe bytes will cause the entire notification queue to be processed. - // Note that we don't need a timeout since the pipe is already in - // nonblocking mode and all we want is one attempt. - ssize_t n = ACE::send (this->notification_pipe_.write_handle (), - (char *) &buffer, - 1); // Only need one byte to pop the pipe - if (n == -1 && (errno != EAGAIN)) - return -1; - - return 0; -#else - - ACE_Dev_Poll_Handler_Guard eh_guard (eh); - - ssize_t n = ACE::send (this->notification_pipe_.write_handle (), - (char *) &buffer, - sizeof buffer, - timeout); - if (n == -1) - return -1; - - eh_guard.release (); - - return 0; -#endif /* ACE_HAS_REACTOR_NOTIFICATION_QUEUE */ -} - -int -ACE_Dev_Poll_Reactor_Notify::dispatch_notifications ( - int & /* number_of_active_handles */, - ACE_Handle_Set & /* rd_mask */) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor_Notify::dispatch_notifications"); - - // This method is unimplemented in the ACE_Dev_Poll_Reactor. - // Instead, the notification handler is invoked as part of the IO - // event set. Doing so alters the some documented semantics that - // state that the notifications are handled before IO events. - // Enforcing such semantics does not appear to be beneficial, and - // also serves to slow down event dispatching particularly with this - // ACE_Dev_Poll_Reactor. - - ACE_NOTSUP_RETURN (-1); -} - -int -ACE_Dev_Poll_Reactor_Notify::read_notify_pipe (ACE_HANDLE handle, - ACE_Notification_Buffer &buffer) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor_Notify::read_notify_pipe"); - - // This is a (non-blocking) "speculative" read, i.e., we attempt to - // read even if no event was polled on the read handle. A - // speculative read is necessary since notifications must be - // dispatched before IO events. We can avoid the speculative read - // by "walking" the array of pollfd structures returned from - // `/dev/poll' or `/dev/epoll' but that is potentially much more - // expensive than simply checking for an EWOULDBLOCK. - size_t to_read; - char *read_p; - -#if defined (ACE_HAS_REACTOR_NOTIFICATION_QUEUE) - // The idea in the queued case is to be sure we never end up with a notify - // queued but no byte in the pipe. If that happens, the notify won't be - // dispatched. So always try to empty the pipe, read the queue, then put - // a byte in if needed. The notify() method is enqueueing then writing the - // pipe, so be sure to do it in the reverse order here to avoid a race - // between removing the last notification from the queue and the notify - // side writing its byte. - char b[1024]; - read_p = b; - to_read = sizeof(b); - (void)ACE::recv (handle, read_p, to_read); - - bool more_messages_queued = false; - ACE_Notification_Buffer next; - int result = notification_queue_.pop_next_notification (buffer, - more_messages_queued, - next); - - if (result <= 0) // Nothing dequeued or error - return result; - - // If there are more messages, ensure there's a byte in the pipe - // in case the notification limit stops dequeuing notifies before - // emptying the queue. - if (more_messages_queued) - (void) ACE::send (this->notification_pipe_.write_handle (), - (char *)&next, - 1); /* one byte is enough */ - return 1; -#else - to_read = sizeof buffer; - read_p = (char *)&buffer; - - ssize_t n = ACE::recv (handle, read_p, to_read); - - if (n > 0) - { - // Check to see if we've got a short read. - if (static_cast (n) != to_read) - { - size_t remainder = to_read - n; - - // If so, try to recover by reading the remainder. If this - // doesn't work we're in big trouble since the input stream - // won't be aligned correctly. I'm not sure quite what to - // do at this point. It's probably best just to return -1. - if (ACE::recv (handle, &read_p[n], remainder) <= 0) - return -1; - } - - return 1; - } - - // Return -1 if things have gone seriously wrong. - if (n <= 0 && (errno != EWOULDBLOCK && errno != EAGAIN)) - return -1; - - return 0; -#endif /* ACE_HAS_REACTOR_NOTIFICATION_QUEUE */ -} - - -int -ACE_Dev_Poll_Reactor_Notify::handle_input (ACE_HANDLE handle) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor_Notify::handle_input"); - - { - ACE_MT (ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, mon, this->dispatching_lock_, -1)); - if (this->dispatching_) - return 0; - this->dispatching_ = true; - } - - int number_dispatched = 0; - int result = 0; - ACE_Notification_Buffer buffer; - - while ((result = this->read_notify_pipe (handle, buffer)) > 0) - { - // Dispatch the buffer - // NOTE: We count only if we made any dispatches ie. upcalls. - if (this->dispatch_notify (buffer) > 0) - ++number_dispatched; - - // Bail out if we've reached the . Note that - // by default is -1, so we'll loop until all - // the available notifications have been dispatched. - if (number_dispatched == this->max_notify_iterations_) - break; - } - - if (result == -1) - { - // Reassign number_dispatched to -1 if things have gone - // seriously wrong. - number_dispatched = -1; - } - - this->dispatching_ = false; - - return number_dispatched; -} - -ACE_HANDLE -ACE_Dev_Poll_Reactor_Notify::notify_handle (void) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor_Notify::notify_handle"); - - return this->notification_pipe_.read_handle (); -} - -int -ACE_Dev_Poll_Reactor_Notify::is_dispatchable (ACE_Notification_Buffer &) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor_Notify::is_dispatchable"); - - ACE_NOTSUP_RETURN (-1); -} - -int -ACE_Dev_Poll_Reactor_Notify::dispatch_notify (ACE_Notification_Buffer &buffer) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor_Notify::dispatch_notify"); - - // If eh == 0 then another thread is unblocking the - // ACE_Dev_Poll_Reactor to update the ACE_Dev_Poll_Reactor's - // internal structures. Otherwise, we need to dispatch the - // appropriate handle_* method on the ACE_Event_Handler - // pointer we've been passed. - if (buffer.eh_ != 0) - { - int result = 0; - - // Guard the handler's refcount. Recall that when the notify - // was queued, the refcount was incremented, so it need not be - // now. The guard insures that it is decremented properly. - ACE_Dev_Poll_Handler_Guard eh_guard (buffer.eh_, false); - - switch (buffer.mask_) - { - case ACE_Event_Handler::READ_MASK: - case ACE_Event_Handler::ACCEPT_MASK: - result = buffer.eh_->handle_input (ACE_INVALID_HANDLE); - break; - case ACE_Event_Handler::WRITE_MASK: - result = buffer.eh_->handle_output (ACE_INVALID_HANDLE); - break; - case ACE_Event_Handler::EXCEPT_MASK: - result = buffer.eh_->handle_exception (ACE_INVALID_HANDLE); - break; - default: - // Should we bail out if we get an invalid mask? - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("dispatch_notify invalid mask = %d\n"), - buffer.mask_)); - } - if (result == -1) - buffer.eh_->handle_close (ACE_INVALID_HANDLE, buffer.mask_); - } - - return 1; -} - -void -ACE_Dev_Poll_Reactor_Notify::max_notify_iterations (int iterations) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor_Notify::max_notify_iterations"); - - // Must always be > 0 or < 0 to optimize the loop exit condition. - if (iterations == 0) - iterations = 1; - - this->max_notify_iterations_ = iterations; -} - -int -ACE_Dev_Poll_Reactor_Notify::max_notify_iterations (void) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor_Notify::max_notify_iterations"); - - return this->max_notify_iterations_; -} - -int -ACE_Dev_Poll_Reactor_Notify::purge_pending_notifications ( - ACE_Event_Handler *eh, - ACE_Reactor_Mask mask) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor_Notify::purge_pending_notifications"); - -#if defined (ACE_HAS_REACTOR_NOTIFICATION_QUEUE) - - return notification_queue_.purge_pending_notifications (eh, mask); - -#else /* defined (ACE_HAS_REACTOR_NOTIFICATION_QUEUE) */ - ACE_UNUSED_ARG (eh); - ACE_UNUSED_ARG (mask); - ACE_NOTSUP_RETURN (-1); -#endif /* defined (ACE_HAS_REACTOR_NOTIFICATION_QUEUE) */ -} - -void -ACE_Dev_Poll_Reactor_Notify::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Dev_Poll_Reactor_Notify::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("dp_reactor_ = %@"), - this->dp_reactor_)); - this->notification_pipe_.dump (); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -// ----------------------------------------------------------------- - -ACE_Dev_Poll_Reactor::Handler_Repository::Handler_Repository (void) - : size_ (0), - max_size_ (0), - handlers_ (0) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::Handler_Repository::Handler_Repository"); -} - -bool -ACE_Dev_Poll_Reactor::Handler_Repository::invalid_handle ( - ACE_HANDLE handle) const -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::Handler_Repository::invalid_handle"); - - if (handle < 0 || handle >= this->max_size_) - { - errno = EINVAL; - return true; - } - else - return false; -} - -bool -ACE_Dev_Poll_Reactor::Handler_Repository::handle_in_range ( - ACE_HANDLE handle) const -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::Handler_Repository::handle_in_range"); - - if (handle >= 0 && handle < this->max_size_) - return true; - else - { - errno = EINVAL; - return false; - } -} - -int -ACE_Dev_Poll_Reactor::Handler_Repository::open (size_t size) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::Handler_Repository::open"); - - this->max_size_ = size; - - // Try to allocate the memory. - ACE_NEW_RETURN (this->handlers_, Event_Tuple[size], -1); - - // Try to increase the number of handles if is greater than - // the current limit. - return ACE::set_handle_limit (size); -} - -int -ACE_Dev_Poll_Reactor::Handler_Repository::unbind_all (void) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::Handler_Repository::unbind_all"); - - // Unbind all of the event handlers; similar to remove_handler() on all. - for (int handle = 0; - handle < this->max_size_; - ++handle) - { - Event_Tuple *entry = this->find (handle); - if (entry == 0) - continue; - - // Check for ref counting now - handle_close () may delete eh. - bool const requires_reference_counting = - entry->event_handler->reference_counting_policy ().value () == - ACE_Event_Handler::Reference_Counting_Policy::ENABLED; - - (void) entry->event_handler->handle_close (handle, entry->mask); - this->unbind (handle, requires_reference_counting); - } - - return 0; -} - -int -ACE_Dev_Poll_Reactor::Handler_Repository::close (void) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::Handler_Repository::close"); - - if (this->handlers_ != 0) - { - this->unbind_all (); - - delete [] this->handlers_; - this->handlers_ = 0; - } - - return 0; -} - -ACE_Dev_Poll_Reactor::Event_Tuple * -ACE_Dev_Poll_Reactor::Handler_Repository::find (ACE_HANDLE handle) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::Handler_Repository::find"); - - Event_Tuple *tuple = 0; - - // Only bother to search for the if it's in range. - if (!this->handle_in_range (handle)) - { - errno = ERANGE; - return 0; - } - - tuple = &(this->handlers_[handle]); - if (tuple->event_handler == 0) - { - errno = ENOENT; - tuple = 0; - } - - return tuple; -} - -int -ACE_Dev_Poll_Reactor::Handler_Repository::bind ( - ACE_HANDLE handle, - ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::Handler_Repository::bind"); - - if (event_handler == 0) - return -1; - - if (handle == ACE_INVALID_HANDLE) - handle = event_handler->get_handle (); - - if (this->invalid_handle (handle)) - return -1; - - this->handlers_[handle].event_handler = event_handler; - this->handlers_[handle].mask = mask; - event_handler->add_reference (); - ++this->size_; - - return 0; -} - -int -ACE_Dev_Poll_Reactor::Handler_Repository::unbind (ACE_HANDLE handle, - bool decr_refcnt) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::Handler_Repository::unbind"); - - Event_Tuple *entry = this->find (handle); - if (entry == 0) - return -1; - - if (decr_refcnt) - entry->event_handler->remove_reference (); - - entry->event_handler = 0; - entry->mask = ACE_Event_Handler::NULL_MASK; - entry->suspended = false; - entry->controlled = false; - --this->size_; - return 0; -} - -// ----------------------------------------------------------------- - -ACE_Dev_Poll_Reactor::ACE_Dev_Poll_Reactor (ACE_Sig_Handler *sh, - ACE_Timer_Queue *tq, - int disable_notify_pipe, - ACE_Reactor_Notify *notify, - int mask_signals, - int s_queue) - : initialized_ (false) - , poll_fd_ (ACE_INVALID_HANDLE) - // , ready_set_ () -#if defined (ACE_HAS_EVENT_POLL) - , epoll_wait_in_progress_ (false) -#endif /* ACE_HAS_EVENT_POLL */ -#if defined (ACE_HAS_DEV_POLL) - , dp_fds_ (0) - , start_pfds_ (0) - , end_pfds_ (0) -#endif /* ACE_HAS_DEV_POLL */ - , deactivated_ (0) - , token_ (*this, s_queue) - , lock_adapter_ (token_) - , timer_queue_ (0) - , delete_timer_queue_ (false) - , signal_handler_ (0) - , delete_signal_handler_ (false) - , notify_handler_ (0) - , delete_notify_handler_ (false) - , mask_signals_ (mask_signals) - , restart_ (0) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::ACE_Dev_Poll_Reactor"); - - if (this->open (ACE::max_handles (), - 0, - sh, - tq, - disable_notify_pipe, - notify) == -1) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_Dev_Poll_Reactor::open ") - ACE_TEXT ("failed inside ") - ACE_TEXT ("ACE_Dev_Poll_Reactor::CTOR"))); -} - -ACE_Dev_Poll_Reactor::ACE_Dev_Poll_Reactor (size_t size, - bool rs, - ACE_Sig_Handler *sh, - ACE_Timer_Queue *tq, - int disable_notify_pipe, - ACE_Reactor_Notify *notify, - int mask_signals, - int s_queue) - : initialized_ (false) - , poll_fd_ (ACE_INVALID_HANDLE) - // , ready_set_ () -#if defined (ACE_HAS_DEV_POLL) - , dp_fds_ (0) - , start_pfds_ (0) - , end_pfds_ (0) -#endif /* ACE_HAS_DEV_POLL */ - , deactivated_ (0) - , token_ (*this, s_queue) - , lock_adapter_ (token_) - , timer_queue_ (0) - , delete_timer_queue_ (false) - , signal_handler_ (0) - , delete_signal_handler_ (false) - , notify_handler_ (0) - , delete_notify_handler_ (false) - , mask_signals_ (mask_signals) - , restart_ (0) -{ - if (this->open (size, - rs, - sh, - tq, - disable_notify_pipe, - notify) == -1) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_Dev_Poll_Reactor::open ") - ACE_TEXT ("failed inside ACE_Dev_Poll_Reactor::CTOR"))); -} - -ACE_Dev_Poll_Reactor::~ACE_Dev_Poll_Reactor (void) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::~ACE_Dev_Poll_Reactor"); - - (void) this->close (); -} - -int -ACE_Dev_Poll_Reactor::open (size_t size, - bool restart, - ACE_Sig_Handler *sh, - ACE_Timer_Queue *tq, - int disable_notify_pipe, - ACE_Reactor_Notify *notify) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::open"); - - ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); - - // Can't initialize ourselves more than once. - if (this->initialized_) - return -1; - -#ifdef ACE_HAS_EVENT_POLL - ACE_OS::memset (&this->event_, 0, sizeof (this->event_)); - this->event_.data.fd = ACE_INVALID_HANDLE; -#endif /* ACE_HAS_EVENT_POLL */ - - this->restart_ = restart; - this->signal_handler_ = sh; - this->timer_queue_ = tq; - this->notify_handler_ = notify; - - int result = 0; - - // Allows the signal handler to be overridden. - if (this->signal_handler_ == 0) - { - ACE_NEW_RETURN (this->signal_handler_, - ACE_Sig_Handler, - -1); - - if (this->signal_handler_ == 0) - result = -1; - else - this->delete_signal_handler_ = true; - } - - // Allows the timer queue to be overridden. - if (result != -1 && this->timer_queue_ == 0) - { - ACE_NEW_RETURN (this->timer_queue_, - ACE_Timer_Heap, - -1); - - if (this->timer_queue_ == 0) - result = -1; - else - this->delete_timer_queue_ = true; - } - - // Allows the Notify_Handler to be overridden. - if (result != -1 && this->notify_handler_ == 0) - { - ACE_NEW_RETURN (this->notify_handler_, - ACE_Dev_Poll_Reactor_Notify, - -1); - - if (this->notify_handler_ == 0) - result = -1; - else - this->delete_notify_handler_ = true; - } - -#if defined (ACE_HAS_EVENT_POLL) - - // Initialize epoll: - this->poll_fd_ = ::epoll_create (size); - if (this->poll_fd_ == -1) - result = -1; - -#else - - // Allocate the array before opening the device to avoid a potential - // resource leak if allocation fails. - ACE_NEW_RETURN (this->dp_fds_, - pollfd[size], - -1); - - // Open the `/dev/poll' character device. - this->poll_fd_ = ACE_OS::open ("/dev/poll", O_RDWR); - if (this->poll_fd_ == ACE_INVALID_HANDLE) - result = -1; - -#endif /* ACE_HAS_EVENT_POLL */ - - if (result != -1 && this->handler_rep_.open (size) == -1) - result = -1; - - // Registration of the notification handler must be done after the - // /dev/poll device has been fully initialized. - else if (this->notify_handler_->open (this, - 0, - disable_notify_pipe) == -1 - || (disable_notify_pipe == 0 - && this->register_handler_i ( - this->notify_handler_->notify_handle (), - this->notify_handler_, - ACE_Event_Handler::READ_MASK) == -1)) - result = -1; - - if (result != -1) - // We're all set to go. - this->initialized_ = true; - else - // This will close down all the allocated resources properly. - (void) this->close (); - - return result; -} - -int -ACE_Dev_Poll_Reactor::current_info (ACE_HANDLE, size_t & /* size */) -{ - ACE_NOTSUP_RETURN (-1); -} - - -int -ACE_Dev_Poll_Reactor::set_sig_handler (ACE_Sig_Handler *signal_handler) -{ - if (this->delete_signal_handler_) - delete this->signal_handler_; - - this->signal_handler_ = signal_handler; - this->delete_signal_handler_ = false; - - return 0; -} - -int -ACE_Dev_Poll_Reactor::timer_queue (ACE_Timer_Queue *tq) -{ - if (this->delete_timer_queue_) - delete this->timer_queue_; - - this->timer_queue_ = tq; - this->delete_timer_queue_ = false; - - return 0; - -} - -ACE_Timer_Queue * -ACE_Dev_Poll_Reactor::timer_queue (void) const -{ - return this->timer_queue_; -} - -int -ACE_Dev_Poll_Reactor::close (void) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::close"); - - ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); - - int result = 0; - - if (this->poll_fd_ != ACE_INVALID_HANDLE) - { - result = ACE_OS::close (this->poll_fd_); - } - -#if defined (ACE_HAS_EVENT_POLL) - - ACE_OS::memset (&this->event_, 0, sizeof (this->event_)); - this->event_.data.fd = ACE_INVALID_HANDLE; - -#else - - delete [] this->dp_fds_; - this->dp_fds_ = 0; - this->start_pfds_ = 0; - this->end_pfds_ = 0; - -#endif /* ACE_HAS_EVENT_POLL */ - - if (this->delete_signal_handler_) - { - delete this->signal_handler_; - this->signal_handler_ = 0; - this->delete_signal_handler_ = false; - } - - (void) this->handler_rep_.close (); - - if (this->delete_timer_queue_) - { - delete this->timer_queue_; - this->timer_queue_ = 0; - this->delete_timer_queue_ = false; - } - - if (this->notify_handler_ != 0) - this->notify_handler_->close (); - - if (this->delete_notify_handler_) - { - delete this->notify_handler_; - this->notify_handler_ = 0; - this->delete_notify_handler_ = false; - } - - this->poll_fd_ = ACE_INVALID_HANDLE; - - this->initialized_ = false; - - return result; -} - -int -ACE_Dev_Poll_Reactor::work_pending (const ACE_Time_Value & max_wait_time) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::work_pending"); - - // Stash the current time - // - // The destructor of this object will automatically compute how much - // time elapsed since this method was called. - ACE_Time_Value mwt (max_wait_time); - ACE_MT (ACE_Countdown_Time countdown (&mwt)); - - Token_Guard guard (this->token_); - int const result = guard.acquire_quietly (&mwt); - - // If the guard is NOT the owner just return the retval - if (!guard.is_owner ()) - return result; - - // Update the countdown to reflect time waiting for the mutex. - ACE_MT (countdown.update ()); - - return this->work_pending_i (&mwt); -} - -int -ACE_Dev_Poll_Reactor::work_pending_i (ACE_Time_Value * max_wait_time) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::work_pending_i"); - - if (this->deactivated_) - return 0; - -#if defined (ACE_HAS_EVENT_POLL) - if (this->event_.data.fd != ACE_INVALID_HANDLE) -#else - if (this->start_pfds_ != this->end_pfds_) -#endif /* ACE_HAS_EVENT_POLL */ - return 1; // We still have work_pending (). Do not poll for - // additional events. - - ACE_Time_Value timer_buf (0); - ACE_Time_Value *this_timeout = - this->timer_queue_->calculate_timeout (max_wait_time, &timer_buf); - - // Check if we have timers to fire. - int const timers_pending = - ((this_timeout != 0 && max_wait_time == 0) - || (this_timeout != 0 && max_wait_time != 0 - && *this_timeout != *max_wait_time) ? 1 : 0); - - long const timeout = - (this_timeout == 0 - ? -1 /* Infinity */ - : static_cast (this_timeout->msec ())); - -#if defined (ACE_HAS_EVENT_POLL) - - // See if there are handlers that have to be resumed before waiting. - { - ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, grd, this->to_be_resumed_lock_, -1); - this->epoll_wait_in_progress_ = true; - for (Resume_Map::iterator i = this->to_be_resumed_.begin (); - i != this->to_be_resumed_.end (); - ++i) - { - // Make sure that 1) the handle is still registered, - // 2) the registered handler is the one we're waiting to resume. - Event_Tuple *info = this->handler_rep_.find (i->first); - if (info != 0 && info->event_handler == i->second) - { - this->resume_handler_i (i->first); - } - } - this->to_be_resumed_.clear (); - } - - // Wait for an event. - int const nfds = ::epoll_wait (this->poll_fd_, - &this->event_, - 1, - static_cast (timeout)); - // Count on this being an atomic update; at worst, we may get an - // extraneous notify() from dispatch_io_event. - this->epoll_wait_in_progress_ = false; - -#else - - struct dvpoll dvp; - - dvp.dp_fds = this->dp_fds_; - dvp.dp_nfds = this->handler_rep_.size (); - dvp.dp_timeout = timeout; // Milliseconds - - // Poll for events - int const nfds = ACE_OS::ioctl (this->poll_fd_, DP_POLL, &dvp); - - // Retrieve the results from the pollfd array. - this->start_pfds_ = dvp.dp_fds; - - // If nfds == 0 then end_pfds_ == start_pfds_ meaning that there is - // no work pending. If nfds > 0 then there is work pending. - // Otherwise an error occurred. - if (nfds > -1) - this->end_pfds_ = this->start_pfds_ + nfds; -#endif /* ACE_HAS_EVENT_POLL */ - - // If timers are pending, override any timeout from the poll. - return (nfds == 0 && timers_pending != 0 ? 1 : nfds); -} - - -int -ACE_Dev_Poll_Reactor::handle_events (ACE_Time_Value *max_wait_time) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::handle_events"); - - // Stash the current time - // - // The destructor of this object will automatically compute how much - // time elapsed since this method was called. - ACE_MT (ACE_Countdown_Time countdown (max_wait_time)); - - Token_Guard guard (this->token_); - int const result = guard.acquire_quietly (max_wait_time); - - // If the guard is NOT the owner just return the retval - if (!guard.is_owner ()) - return result; - - if (this->deactivated_) - return -1; - - // Update the countdown to reflect time waiting for the mutex. - ACE_MT (countdown.update ()); - - return this->handle_events_i (max_wait_time, guard); -} - -int -ACE_Dev_Poll_Reactor::handle_events_i (ACE_Time_Value *max_wait_time, - Token_Guard &guard) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::handle_events_i"); - - int result = 0; - - // Poll for events - // - // If the underlying event wait call was interrupted via the interrupt - // signal (i.e. returned -1 with errno == EINTR) then the loop will - // be restarted if so desired. - do - { - result = this->work_pending_i (max_wait_time); - if (result == -1 && (this->restart_ == 0 || errno != EINTR)) - ACE_ERROR ((LM_ERROR, ACE_TEXT("%t: %p\n"), ACE_TEXT("work_pending_i"))); - } - while (result == -1 && this->restart_ != 0 && errno == EINTR); - - if (result == 0 || (result == -1 && errno == ETIME)) - return 0; - else if (result == -1) - { - if (errno != EINTR) - return -1; - - // Bail out -- we got here since the poll was interrupted. - // If it was due to a signal registered through our ACE_Sig_Handler, - // then it was dispatched, so we count it in the number of events - // handled rather than cause an error return. - if (ACE_Sig_Handler::sig_pending () != 0) - { - ACE_Sig_Handler::sig_pending (0); - return 1; - } - return -1; - } - - // Dispatch an event. - return this->dispatch (guard); -} - -// Dispatch an event. On entry, the token is held by the caller. If an -// event is found to dispatch, the token is released before dispatching it. -int -ACE_Dev_Poll_Reactor::dispatch (Token_Guard &guard) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::dispatch"); - - // Perform the Template Method for dispatching the first located event. - // We dispatch only one to effectively dispatch events concurrently. - // As soon as an event is located, the token is released, allowing the - // next waiter to begin getting an event while we dispatch one here. - int result = 0; - - // Handle timers early since they may have higher latency - // constraints than I/O handlers. Ideally, the order of - // dispatching should be a strategy... - if ((result = this->dispatch_timer_handler (guard)) != 0) - return result; - - // If no timer dispatched, check for an I/O event. - result = this->dispatch_io_event (guard); - - return result; -} - -int -ACE_Dev_Poll_Reactor::dispatch_timer_handler (Token_Guard &guard) -{ - if (this->timer_queue_->is_empty ()) - return 0; // Empty timer queue so cannot have any expired timers. - - // Get the current time - ACE_Time_Value cur_time (this->timer_queue_->gettimeofday () + - this->timer_queue_->timer_skew ()); - - // Look for a node in the timer queue whose timer <= the present - // time. - ACE_Timer_Node_Dispatch_Info info; - if (this->timer_queue_->dispatch_info (cur_time, info)) - { - const void *upcall_act = 0; - - // Preinvoke (handles refcount if needed, etc.) - this->timer_queue_->preinvoke (info, cur_time, upcall_act); - - // Release the token before expiration upcall. - guard.release_token (); - - // call the functor - this->timer_queue_->upcall (info, cur_time); - - // Postinvoke (undo refcount if needed, etc.) - this->timer_queue_->postinvoke (info, cur_time, upcall_act); - - // We have dispatched a timer - return 1; - } - - return 0; -} - -#if 0 -int -ACE_Dev_Poll_Reactor::dispatch_notification_handlers ( - ACE_Select_Reactor_Handle_Set &dispatch_set, - int &number_of_active_handles, - int &number_of_handlers_dispatched) -{ - // Check to see if the ACE_HANDLE associated with the - // Dev_Poll_Reactor's notify hook is enabled. If so, it means that - // one or more other threads are trying to update the - // ACE_Dev_Poll_Reactor's internal tables or the notify pipe is - // enabled. We'll handle all these threads and notifications, and - // then break out to continue the event loop. - - const int n = - this->notify_handler_->dispatch_notifications (number_of_active_handles, - dispatch_set.rd_mask_); - - if (n == -1) - return -1; - else - number_of_handlers_dispatched += n; - - return /* this->state_changed_ ? -1 : */ 0; -} -#endif /* 0 */ - -int -ACE_Dev_Poll_Reactor::dispatch_io_event (Token_Guard &guard) -{ - - // Dispatch a ready event. - - // Define bits to check for while dispatching. -#if defined (ACE_HAS_EVENT_POLL) - const __uint32_t out_event = EPOLLOUT; - const __uint32_t exc_event = EPOLLPRI; - const __uint32_t in_event = EPOLLIN; - const __uint32_t err_event = EPOLLHUP | EPOLLERR; -#else - const short out_event = POLLOUT; - const short exc_event = POLLPRI; - const short in_event = POLLIN; - const short err_event = 0; // No known bits for this -#endif /* ACE_HAS_EVENT_POLL */ - -#if defined (ACE_HAS_EVENT_POLL) - // epoll_wait() pulls one event which is stored in event_. If the handle - // is invalid, there's no event there. Else process it. In any event, we - // have the event, so clear event_ for the next thread. - const ACE_HANDLE handle = this->event_.data.fd; - __uint32_t revents = this->event_.events; - this->event_.data.fd = ACE_INVALID_HANDLE; - this->event_.events = 0; - if (handle != ACE_INVALID_HANDLE) - -#else - // Since the underlying event demultiplexing mechansim (`/dev/poll' - // or '/dev/epoll') is stateful, and since only one result buffer is - // used, all pending events (i.e. those retrieved from a previous - // poll) must be dispatched before any additional event can be - // polled. As such, the Dev_Poll_Reactor keeps track of the - // progress of events that have been dispatched. - - // Select the first available handle with event (s) pending. Check for - // event type in defined order of dispatch: output, exception, input. - // When an event is located, clear its bit in the dispatch set. If there - // are no more events for the handle, also increment the pfds pointer - // to move to the next handle ready. - // - // Notice that pfds only contains file descriptors that have - // received events. - struct pollfd *& pfds = this->start_pfds_; - const ACE_HANDLE handle = pfds->fd; - short &revents = pfds->revents; - if (pfds < this->end_pfds_) -#endif /* ACE_HAS_EVENT_POLL */ - - { - /* When using sys_epoll, we can attach arbitrary user - data to the descriptor, so it can be delivered when - activity is detected. Perhaps we should store event - handler together with descriptor, instead of looking - it up in a repository ? Could it boost performance ? - */ - Event_Tuple *info = this->handler_rep_.find (handle); - if (info == 0) // No registered handler any longer - { -#ifdef ACE_HAS_EVENT_POLL - this->event_.data.fd = ACE_INVALID_HANDLE; // Dump the event -#endif /* ACE_HAS_EVENT_POLL */ - return 0; - } - - // Figure out what to do first in order to make it easier to manage - // the bit twiddling and possible pfds increment before releasing - // the token for dispatch. - // Note that if there's an error (such as the handle was closed - // without being removed from the event set) the EPOLLHUP and/or - // EPOLLERR bits will be set in revents. - ACE_Reactor_Mask disp_mask = 0; - ACE_Event_Handler *eh = info->event_handler; - int (ACE_Event_Handler::*callback)(ACE_HANDLE) = 0; - if (ACE_BIT_ENABLED (revents, out_event)) - { - disp_mask = ACE_Event_Handler::WRITE_MASK; - callback = &ACE_Event_Handler::handle_output; - ACE_CLR_BITS (revents, out_event); - } - else if (ACE_BIT_ENABLED (revents, exc_event)) - { - disp_mask = ACE_Event_Handler::EXCEPT_MASK; - callback = &ACE_Event_Handler::handle_exception; - ACE_CLR_BITS (revents, exc_event); - } - else if (ACE_BIT_ENABLED (revents, in_event)) - { - disp_mask = ACE_Event_Handler::READ_MASK; - callback = &ACE_Event_Handler::handle_input; - ACE_CLR_BITS (revents, in_event); - } - else if (ACE_BIT_ENABLED (revents, err_event)) - { - this->remove_handler_i (handle, - ACE_Event_Handler::ALL_EVENTS_MASK, - info->event_handler); -#ifdef ACE_HAS_DEV_POLL - ++pfds; -#endif /* ACE_HAS_DEV_POLL */ - return 1; - } - else - { - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("(%t) dispatch_io h %d unknown events 0x%x\n"), - handle, revents)); - } - -#ifdef ACE_HAS_DEV_POLL - // Increment the pointer to the next element before we - // release the token. Otherwise event handlers end up being - // dispatched multiple times for the same poll. - if (revents == 0) - ++pfds; -#else - // With epoll, events are registered with oneshot, so the handle is - // effectively suspended; future calls to epoll_wait() will select - // the next event, so they're not managed here. - // The hitch to this is that the notify handler is always registered - // WITHOUT oneshot and is never suspended/resumed. This avoids endless - // notify loops caused by the notify handler requiring a resumption - // which requires the token, which requires a notify, etc. described - // in Bugzilla 3714. So, never suspend the notify handler. - - bool reactor_resumes_eh = false; - if (eh != this->notify_handler_) - { - info->suspended = true; - - reactor_resumes_eh = - eh->resume_handler () == - ACE_Event_Handler::ACE_REACTOR_RESUMES_HANDLER; - } -#endif /* ACE_HAS_DEV_POLL */ - - int status = 0; // gets callback status, below. - { - // Modify the reference count in an exception-safe way. - // Note that eh could be the notify handler. It's not strictly - // necessary to manage its refcount, but since we don't enable - // the counting policy, it won't do much. Management of the - // notified handlers themselves is done in the notify handler. - ACE_Dev_Poll_Handler_Guard eh_guard (eh); - - // Release the reactor token before upcall. - guard.release_token (); - - // Dispatch the detected event; will do the repeated upcalls - // if callback returns > 0, unless it's the notify handler (which - // returns the number of notfies dispatched, not an indication of - // re-callback requested). If anything other than the notify, come - // back with either 0 or < 0. - status = this->upcall (eh, callback, handle); - - if (eh == this->notify_handler_) - return status; - - // If the callback returned 0, epoll-based needs to resume the - // suspended handler but dev/poll doesn't. - // The epoll case is optimized to not acquire the token in order - // to resume the handler; the handler is added to a list of those - // that need to be resumed and is handled by the next leader - // that does an epoll_wait(). - // In both epoll and dev/poll cases, if the callback returns <0, - // the token needs to be acquired and the handler checked and - // removed if it hasn't already been. - if (status == 0) - { -#ifdef ACE_HAS_EVENT_POLL - // epoll-based effectively suspends handlers around the upcall. - // If the handler must be resumed, add it to the list. - if (reactor_resumes_eh) - { - ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, - grd, - this->to_be_resumed_lock_, - -1); - bool map_was_empty = this->to_be_resumed_.empty(); - this->to_be_resumed_.insert - (Resume_Map::value_type (handle, eh)); - if (this->epoll_wait_in_progress_ && map_was_empty) - this->notify(); - } -#endif /* ACE_HAS_EVENT_POLL */ - return 1; - } - - // All state in the handler repository may have changed during the - // upcall while other threads had the token. Thus, reacquire the - // token and evaluate what's needed. If the upcalled handler is still - // the handler of record for handle, continue with checking whether - // or not to remove or resume the handler. - guard.acquire (); - info = this->handler_rep_.find (handle); - if (info != 0 && info->event_handler == eh) - { - if (status < 0) - this->remove_handler_i (handle, disp_mask); - } - } - // Scope close handles eh ref count decrement, if needed. - - return 1; - } - - return 0; -} - -int -ACE_Dev_Poll_Reactor::alertable_handle_events (ACE_Time_Value *max_wait_time) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::alertable_handle_events"); - - return this->handle_events (max_wait_time); -} - -int -ACE_Dev_Poll_Reactor::handle_events (ACE_Time_Value &max_wait_time) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::handle_events"); - - return this->handle_events (&max_wait_time); -} - -int -ACE_Dev_Poll_Reactor::alertable_handle_events (ACE_Time_Value &max_wait_time) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::alertable_handle_events"); - - return this->handle_events (max_wait_time); -} - -int -ACE_Dev_Poll_Reactor::deactivated (void) -{ - return this->deactivated_; -} - -void -ACE_Dev_Poll_Reactor::deactivate (int do_stop) -{ - this->deactivated_ = do_stop; - this->wakeup_all_threads (); -} - -int -ACE_Dev_Poll_Reactor::register_handler (ACE_Event_Handler *handler, - ACE_Reactor_Mask mask) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::register_handler"); - - ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); - - return this->register_handler_i (handler->get_handle (), - handler, - mask); -} - -int -ACE_Dev_Poll_Reactor::register_handler (ACE_HANDLE handle, - ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::register_handler"); - - ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); - - return this->register_handler_i (handle, - event_handler, - mask); -} - -int -ACE_Dev_Poll_Reactor::register_handler_i (ACE_HANDLE handle, - ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::register_handler_i"); - - if (handle == ACE_INVALID_HANDLE - || mask == ACE_Event_Handler::NULL_MASK) - { - errno = EINVAL; - return -1; - } - - if (this->handler_rep_.find (handle) == 0) - { - // Handler not present in the repository. Bind it. - if (this->handler_rep_.bind (handle, event_handler, mask) != 0) - return -1; - -#if defined (ACE_HAS_EVENT_POLL) - - Event_Tuple *info = this->handler_rep_.find (handle); - - struct epoll_event epev; - ACE_OS::memset (&epev, 0, sizeof (epev)); - static const int op = EPOLL_CTL_ADD; - - epev.data.fd = handle; - epev.events = this->reactor_mask_to_poll_event (mask); - // All but the notify handler get registered with oneshot to facilitate - // auto suspend before the upcall. See dispatch_io_event for more - // information. - if (event_handler != this->notify_handler_) - epev.events |= EPOLLONESHOT; - - if (::epoll_ctl (this->poll_fd_, op, handle, &epev) == -1) - { - ACE_ERROR ((LM_ERROR, ACE_TEXT("%p\n"), ACE_TEXT("epoll_ctl"))); - (void) this->handler_rep_.unbind (handle); - return -1; - } - info->controlled = true; - -#endif /* ACE_HAS_EVENT_POLL */ - } - else - { - // Handler is already present in the repository, so register it - // again, possibly for different event. Add new mask to the - // current one. - if (this->mask_ops_i (handle, mask, ACE_Reactor::ADD_MASK) == -1) - ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT("%p\n"), ACE_TEXT("mask_ops_i")), - -1); - } - -#ifdef ACE_HAS_DEV_POLL - - struct pollfd pfd; - - pfd.fd = handle; - pfd.events = this->reactor_mask_to_poll_event (mask); - pfd.revents = 0; - - // Add file descriptor to the "interest set." - if (ACE_OS::write (this->poll_fd_, &pfd, sizeof (pfd)) != sizeof (pfd)) - { - (void) this->handler_rep_.unbind (handle); - return -1; - } -#endif /*ACE_HAS_DEV_POLL*/ - - // Note the fact that we've changed the state of the wait_set_, - // which is used by the dispatching loop to determine whether it can - // keep going or if it needs to reconsult select (). - // this->state_changed_ = 1; - - return 0; -} - -int -ACE_Dev_Poll_Reactor::register_handler ( - ACE_HANDLE /* event_handle */, - ACE_HANDLE /* io_handle */, - ACE_Event_Handler * /* event_handler */, - ACE_Reactor_Mask /* mask */) -{ - ACE_NOTSUP_RETURN (-1); -} - -int -ACE_Dev_Poll_Reactor::register_handler (const ACE_Handle_Set &handle_set, - ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::register_handler"); - - ACE_Handle_Set_Iterator handle_iter (handle_set); - - ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); - - // @@ It might be more efficient to construct a pollfd array and - // pass it to the write () call in register_handler_i () only once, - // instead of calling write () (a system call) once for each file - // descriptor. - - for (ACE_HANDLE h = handle_iter (); - h != ACE_INVALID_HANDLE; - h = handle_iter ()) - if (this->register_handler_i (h, event_handler, mask) == -1) - return -1; - - return 0; -} - -int -ACE_Dev_Poll_Reactor::register_handler (int signum, - ACE_Event_Handler *new_sh, - ACE_Sig_Action *new_disp, - ACE_Event_Handler **old_sh, - ACE_Sig_Action *old_disp) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::register_handler"); - - return this->signal_handler_->register_handler (signum, - new_sh, - new_disp, - old_sh, - old_disp); -} - -int -ACE_Dev_Poll_Reactor::register_handler (const ACE_Sig_Set &sigset, - ACE_Event_Handler *new_sh, - ACE_Sig_Action *new_disp) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::register_handler"); - - int result = 0; - -#if (ACE_NSIG > 0) - - for (int s = 1; s < ACE_NSIG; ++s) - if ((sigset.is_member (s) == 1) - && this->signal_handler_->register_handler (s, - new_sh, - new_disp) == -1) - result = -1; - -#else /* ACE_NSIG <= 0 */ - - ACE_UNUSED_ARG (sigset); - ACE_UNUSED_ARG (new_sh); - ACE_UNUSED_ARG (new_disp); - -#endif /* ACE_NSIG <= 0 */ - - return result; -} - -int -ACE_Dev_Poll_Reactor::remove_handler (ACE_Event_Handler *handler, - ACE_Reactor_Mask mask) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::remove_handler"); - - ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); - - return this->remove_handler_i (handler->get_handle (), mask); -} - -int -ACE_Dev_Poll_Reactor::remove_handler (ACE_HANDLE handle, - ACE_Reactor_Mask mask) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::remove_handler"); - - ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); - - return this->remove_handler_i (handle, mask); -} - -int -ACE_Dev_Poll_Reactor::remove_handler_i (ACE_HANDLE handle, - ACE_Reactor_Mask mask, - ACE_Event_Handler *eh) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::remove_handler_i"); - - // If registered event handler not the same as eh, don't mess with - // the mask, but do the proper callback and refcount when needed. - bool handle_reg_changed = true; - Event_Tuple *info = this->handler_rep_.find (handle); - if (info == 0 && eh == 0) // Nothing to work with - return -1; - if (info != 0 && (eh == 0 || info->event_handler == eh)) - { - if (this->mask_ops_i (handle, mask, ACE_Reactor::CLR_MASK) == -1) - return -1; - handle_reg_changed = false; - eh = info->event_handler; - } - - // Check for ref counting now - handle_close () may delete eh. - bool const requires_reference_counting = - eh->reference_counting_policy ().value () == - ACE_Event_Handler::Reference_Counting_Policy::ENABLED; - - if (ACE_BIT_DISABLED (mask, ACE_Event_Handler::DONT_CALL)) - (void) eh->handle_close (handle, mask); - - // If there are no longer any outstanding events on the given handle - // then remove it from the handler repository. - if (!handle_reg_changed && info->mask == ACE_Event_Handler::NULL_MASK) - this->handler_rep_.unbind (handle, requires_reference_counting); - - return 0; -} - -int -ACE_Dev_Poll_Reactor::remove_handler (const ACE_Handle_Set &handle_set, - ACE_Reactor_Mask mask) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::remove_handler"); - - ACE_Handle_Set_Iterator handle_iter (handle_set); - - ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); - - // @@ It might be more efficient to construct a pollfd array and - // pass it to the write () call in register_handler_i () only once, - // instead of calling write () (a system call) once for each file - // descriptor. - - for (ACE_HANDLE h = handle_iter (); - h != ACE_INVALID_HANDLE; - h = handle_iter ()) - if (this->remove_handler_i (h, mask) == -1) - return -1; - - return 0; -} - -int -ACE_Dev_Poll_Reactor::remove_handler (int signum, - ACE_Sig_Action *new_disp, - ACE_Sig_Action *old_disp, - int sigkey) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::remove_handler"); - - return this->signal_handler_->remove_handler (signum, - new_disp, - old_disp, - sigkey); -} - -int -ACE_Dev_Poll_Reactor::remove_handler (const ACE_Sig_Set &sigset) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::remove_handler"); - - int result = 0; - -#if (ACE_NSIG > 0) - - for (int s = 1; s < ACE_NSIG; ++s) - if ((sigset.is_member (s) == 1) - && this->signal_handler_->remove_handler (s) == -1) - result = -1; - -#else /* ACE_NSIG <= 0 */ - - ACE_UNUSED_ARG (sigset); - -#endif /* ACE_NSIG <= 0 */ - - return result; -} - -int -ACE_Dev_Poll_Reactor::suspend_handler (ACE_Event_Handler *event_handler) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::suspend_handler"); - - if (event_handler == 0) - { - errno = EINVAL; - return -1; - } - - ACE_HANDLE handle = event_handler->get_handle (); - - ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); - - return this->suspend_handler_i (handle); -} - -int -ACE_Dev_Poll_Reactor::suspend_handler (ACE_HANDLE handle) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::suspend_handler"); - - ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); - - return this->suspend_handler_i (handle); -} - -int -ACE_Dev_Poll_Reactor::suspend_handler (const ACE_Handle_Set &handles) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::suspend_handler"); - - ACE_Handle_Set_Iterator handle_iter (handles); - ACE_HANDLE h; - - ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); - - while ((h = handle_iter ()) != ACE_INVALID_HANDLE) - if (this->suspend_handler_i (h) == -1) - return -1; - - return 0; -} - -int -ACE_Dev_Poll_Reactor::suspend_handlers (void) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::suspend_handlers"); - - ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); - - size_t const len = this->handler_rep_.max_size (); - - for (size_t i = 0; i < len; ++i) - { - Event_Tuple *info = this->handler_rep_.find (i); - if (info != 0 && !info->suspended && this->suspend_handler_i (i) != 0) - return -1; - } - return 0; -} - -int -ACE_Dev_Poll_Reactor::suspend_handler_i (ACE_HANDLE handle) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::suspend_handler_i"); - - Event_Tuple *info = this->handler_rep_.find (handle); - if (info == 0) - return -1; - - if (info->suspended) - return 0; // Already suspended. @@ Should this be an error? - - // Remove the handle from the "interest set." - // - // Note that the associated event handler is still in the handler - // repository, but no events will be polled on the given handle thus - // no event will be dispatched to the event handler. - -#if defined (ACE_HAS_EVENT_POLL) - - struct epoll_event epev; - ACE_OS::memset (&epev, 0, sizeof (epev)); - static const int op = EPOLL_CTL_DEL; - - epev.events = 0; - epev.data.fd = handle; - - if (::epoll_ctl (this->poll_fd_, op, handle, &epev) == -1) - return -1; - info->controlled = false; -#else - - struct pollfd pfd[1]; - - pfd[0].fd = handle; - pfd[0].events = POLLREMOVE; - pfd[0].revents = 0; - - if (ACE_OS::write (this->poll_fd_, pfd, sizeof (pfd)) != sizeof (pfd)) - return -1; - -#endif /* ACE_HAS_EVENT_POLL */ - - info->suspended = true; - - return 0; -} - -int -ACE_Dev_Poll_Reactor::resume_handler (ACE_Event_Handler *event_handler) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::resume_handler"); - - if (event_handler == 0) - { - errno = EINVAL; - return -1; - } - - ACE_HANDLE handle = event_handler->get_handle (); - - ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); - - return this->resume_handler_i (handle); -} - -int -ACE_Dev_Poll_Reactor::resume_handler (ACE_HANDLE handle) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::resume_handler"); - - ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); - - return this->resume_handler_i (handle); -} - -int -ACE_Dev_Poll_Reactor::resume_handler (const ACE_Handle_Set &handles) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::resume_handler"); - - ACE_Handle_Set_Iterator handle_iter (handles); - ACE_HANDLE h; - - ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); - - while ((h = handle_iter ()) != ACE_INVALID_HANDLE) - if (this->resume_handler_i (h) == -1) - return -1; - - return 0; -} - -int -ACE_Dev_Poll_Reactor::resume_handlers (void) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::resume_handlers"); - - ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); - - size_t const len = this->handler_rep_.max_size (); - - for (size_t i = 0; i < len; ++i) - { - Event_Tuple *info = this->handler_rep_.find (i); - if (info != 0 && info->suspended && this->resume_handler_i (i) != 0) - return -1; - } - - return 0; -} - -int -ACE_Dev_Poll_Reactor::resume_handler_i (ACE_HANDLE handle) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::resume_handler_i"); - - Event_Tuple *info = this->handler_rep_.find (handle); - if (info == 0) - return -1; - - if (!info->suspended) - return 0; - - ACE_Reactor_Mask mask = info->mask; - if (mask == ACE_Event_Handler::NULL_MASK) - { - info->suspended = false; - return 0; - } - - // Place the handle back in to the "interest set." - // - // Events for the given handle will once again be polled. - -#if defined (ACE_HAS_EVENT_POLL) - - struct epoll_event epev; - ACE_OS::memset (&epev, 0, sizeof (epev)); - int op = EPOLL_CTL_ADD; - if (info->controlled) - op = EPOLL_CTL_MOD; - epev.events = this->reactor_mask_to_poll_event (mask) | EPOLLONESHOT; - epev.data.fd = handle; - - if (::epoll_ctl (this->poll_fd_, op, handle, &epev) == -1) - return -1; - info->controlled = true; - -#else - - struct pollfd pfd[1]; - - pfd[0].fd = handle; - pfd[0].events = this->reactor_mask_to_poll_event (mask); - pfd[0].revents = 0; - - if (ACE_OS::write (this->poll_fd_, pfd, sizeof (pfd)) != sizeof (pfd)) - return -1; - -#endif /* ACE_HAS_EVENT_POLL */ - - info->suspended = false; - - return 0; -} - -int -ACE_Dev_Poll_Reactor::resumable_handler (void) -{ - // @@ Is this correct? - - return 0; -} - -bool -ACE_Dev_Poll_Reactor::uses_event_associations (void) -{ - // Since the Dev_Poll_Reactor does not do any event associations, - // this method always return false. - return false; -} - -long -ACE_Dev_Poll_Reactor::schedule_timer (ACE_Event_Handler *event_handler, - const void *arg, - const ACE_Time_Value &delay, - const ACE_Time_Value &interval) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::schedule_timer"); - - ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); - - if (0 != this->timer_queue_) - return this->timer_queue_->schedule - (event_handler, - arg, - this->timer_queue_->gettimeofday () + delay, - interval); - - errno = ESHUTDOWN; - return -1; -} - -int -ACE_Dev_Poll_Reactor::reset_timer_interval (long timer_id, - const ACE_Time_Value &interval) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::reset_timer_interval"); - - ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); - - if (0 != this->timer_queue_) - return this->timer_queue_->reset_interval (timer_id, interval); - - errno = ESHUTDOWN; - return -1; -} - -int -ACE_Dev_Poll_Reactor::cancel_timer (ACE_Event_Handler *event_handler, - int dont_call_handle_close) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::cancel_timer"); - - ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); - - return (this->timer_queue_ == 0 - ? 0 - : this->timer_queue_->cancel (event_handler, - dont_call_handle_close)); -} - -int -ACE_Dev_Poll_Reactor::cancel_timer (long timer_id, - const void **arg, - int dont_call_handle_close) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::cancel_timer"); - - ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); - - return (this->timer_queue_ == 0 - ? 0 - : this->timer_queue_->cancel (timer_id, - arg, - dont_call_handle_close)); -} - -int -ACE_Dev_Poll_Reactor::schedule_wakeup (ACE_Event_Handler *eh, - ACE_Reactor_Mask mask) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::schedule_wakeup"); - - return this->mask_ops (eh->get_handle (), mask, ACE_Reactor::ADD_MASK); -} - -int -ACE_Dev_Poll_Reactor::schedule_wakeup (ACE_HANDLE handle, - ACE_Reactor_Mask mask) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::schedule_wakeup"); - - return this->mask_ops (handle, mask, ACE_Reactor::ADD_MASK); -} - -int -ACE_Dev_Poll_Reactor::cancel_wakeup (ACE_Event_Handler *eh, - ACE_Reactor_Mask mask) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::cancel_wakeup"); - - return this->mask_ops (eh->get_handle (), mask, ACE_Reactor::CLR_MASK); -} - -int -ACE_Dev_Poll_Reactor::cancel_wakeup (ACE_HANDLE handle, - ACE_Reactor_Mask mask) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::cancel_wakeup"); - - return this->mask_ops (handle, mask, ACE_Reactor::CLR_MASK); -} - -int -ACE_Dev_Poll_Reactor::notify (ACE_Event_Handler *eh, - ACE_Reactor_Mask mask, - ACE_Time_Value *timeout) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::notify"); - - ssize_t n = 0; - - // Pass over both the Event_Handler *and* the mask to allow the - // caller to dictate which Event_Handler method the receiver - // invokes. Note that this call can timeout. - - n = this->notify_handler_->notify (eh, mask, timeout); - - return n == -1 ? -1 : 0; -} - -void -ACE_Dev_Poll_Reactor::max_notify_iterations (int iterations) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::max_notify_iterations"); - - ACE_MT (ACE_GUARD (ACE_Dev_Poll_Reactor_Token, mon, this->token_)); - - this->notify_handler_->max_notify_iterations (iterations); -} - -int -ACE_Dev_Poll_Reactor::max_notify_iterations (void) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::max_notify_iterations"); - - ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); - - return this->notify_handler_->max_notify_iterations (); -} - -int -ACE_Dev_Poll_Reactor::purge_pending_notifications (ACE_Event_Handler * eh, - ACE_Reactor_Mask mask) -{ - if (this->notify_handler_ == 0) - return 0; - - return this->notify_handler_->purge_pending_notifications (eh, mask); -} - -ACE_Event_Handler * -ACE_Dev_Poll_Reactor::find_handler (ACE_HANDLE handle) -{ - ACE_MT (ACE_READ_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, 0)); - - Event_Tuple *info = this->handler_rep_.find (handle); - if (info) - { - info->event_handler->add_reference (); - return info->event_handler; - } - else - { - return 0; - } -} - -int -ACE_Dev_Poll_Reactor::handler (ACE_HANDLE handle, - ACE_Reactor_Mask mask, - ACE_Event_Handler **event_handler) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::handler"); - - ACE_MT (ACE_READ_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); - - Event_Tuple *info = this->handler_rep_.find (handle); - - if (info != 0 - && ACE_BIT_CMP_MASK (info->mask, - mask, // Compare all bits in the mask - mask)) - { - if (event_handler != 0) - *event_handler = info->event_handler; - - return 0; - } - - return -1; -} - -int -ACE_Dev_Poll_Reactor::handler (int signum, - ACE_Event_Handler **eh) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::handler"); - - ACE_Event_Handler *handler = this->signal_handler_->handler (signum); - - if (handler == 0) - return -1; - else if (eh != 0) - *eh = handler; - - return 0; -} - -bool -ACE_Dev_Poll_Reactor::initialized (void) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::initialized"); - - ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, false)); - - return this->initialized_; -} - -size_t -ACE_Dev_Poll_Reactor::size (void) const -{ - return this->handler_rep_.size (); -} - -ACE_Lock & -ACE_Dev_Poll_Reactor::lock (void) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::lock"); - - return this->lock_adapter_; -} - -void -ACE_Dev_Poll_Reactor::wakeup_all_threads (void) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::wakeup_all_threads"); - - // Send a notification, but don't block if there's no one to receive - // it. - this->notify (0, - ACE_Event_Handler::NULL_MASK, - (ACE_Time_Value *) &ACE_Time_Value::zero); -} - -int -ACE_Dev_Poll_Reactor::owner (ACE_thread_t /* new_owner */, - ACE_thread_t * /* old_owner */) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::owner"); - - // There is no need to set the owner of the event loop. Multiple - // threads may invoke the event loop simulataneously. - - return 0; -} - -int -ACE_Dev_Poll_Reactor::owner (ACE_thread_t * /* owner */) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::owner"); - - // There is no need to set the owner of the event loop. Multiple - // threads may invoke the event loop simulataneously. - - return 0; -} - -bool -ACE_Dev_Poll_Reactor::restart (void) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::restart"); - - ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, false)); - - return this->restart_; -} - -bool -ACE_Dev_Poll_Reactor::restart (bool r) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::restart"); - - ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, false)); - - bool current_value = this->restart_; - this->restart_ = r; - return current_value; -} - -void -ACE_Dev_Poll_Reactor::requeue_position (int) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::requeue_position"); -} - -int -ACE_Dev_Poll_Reactor::requeue_position (void) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::requeue_position"); - - ACE_NOTSUP_RETURN (-1); -} - -int -ACE_Dev_Poll_Reactor::mask_ops (ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask, - int ops) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::mask_ops"); - - ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); - - return this->mask_ops_i (event_handler->get_handle (), mask, ops); -} - -int -ACE_Dev_Poll_Reactor::mask_ops (ACE_HANDLE handle, - ACE_Reactor_Mask mask, - int ops) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::mask_ops"); - - ACE_MT (ACE_GUARD_RETURN (ACE_Dev_Poll_Reactor_Token, mon, this->token_, -1)); - - return this->mask_ops_i (handle, mask, ops); -} - -int -ACE_Dev_Poll_Reactor::mask_ops_i (ACE_HANDLE handle, - ACE_Reactor_Mask mask, - int ops) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::mask_ops_i"); - - Event_Tuple *info = this->handler_rep_.find (handle); - if (info == 0) - return -1; - - // Block out all signals until method returns. - ACE_Sig_Guard sb; - - ACE_Reactor_Mask const old_mask = info->mask; - ACE_Reactor_Mask new_mask = old_mask; - - // Perform GET, CLR, SET, and ADD operations on the interest/wait - // set and the suspend set (if necessary). - // - // GET = 1, Retrieve current value - // SET = 2, Set value of bits to new mask (changes the entire mask) - // ADD = 3, Bitwise "or" the value into the mask (only changes - // enabled bits) - // CLR = 4 Bitwise "and" the negation of the value out of the mask - // (only changes enabled bits) - // - // Returns the original mask. - - switch (ops) - { - case ACE_Reactor::GET_MASK: - // The work for this operation is done in all cases at the - // begining of the function. - return old_mask; - - case ACE_Reactor::CLR_MASK: - ACE_CLR_BITS (new_mask, mask); - break; - - case ACE_Reactor::SET_MASK: - new_mask = mask; - break; - - case ACE_Reactor::ADD_MASK: - ACE_SET_BITS (new_mask, mask); - break; - - default: - return -1; - } - - /// Reset the mask for the given handle. - info->mask = new_mask; - - // Only attempt to alter events for the handle from the - // "interest set" if it hasn't been suspended. If it has been - // suspended, the revised mask will take affect when the - // handle is resumed. The exception is if all the mask bits are - // cleared, we can un-control the fd now. - if (!info->suspended || (info->controlled && new_mask == 0)) - { - - short const events = this->reactor_mask_to_poll_event (new_mask); - -#if defined (sun) - // Apparently events cannot be updated on-the-fly on Solaris so - // remove the existing events, and then add the new ones. - struct pollfd pfd[2]; - - pfd[0].fd = handle; - pfd[0].events = POLLREMOVE; - pfd[0].revents = 0; - pfd[1].fd = (events == POLLREMOVE ? ACE_INVALID_HANDLE : handle); - pfd[1].events = events; - pfd[1].revents = 0; - - // Change the events associated with the given file descriptor. - if (ACE_OS::write (this->poll_fd_, - pfd, - sizeof (pfd)) != sizeof (pfd)) - return -1; -#elif defined (ACE_HAS_EVENT_POLL) - - struct epoll_event epev; - ACE_OS::memset (&epev, 0, sizeof (epev)); - int op; - - // ACE_Event_Handler::NULL_MASK ??? - if (new_mask == 0) - { - op = EPOLL_CTL_DEL; - epev.events = 0; - } - else - { - op = EPOLL_CTL_MOD; - epev.events = events | EPOLLONESHOT; - } - - epev.data.fd = handle; - - if (::epoll_ctl (this->poll_fd_, op, handle, &epev) == -1) - { - // If a handle is closed, epoll removes it from the poll set - // automatically - we may not know about it yet. If that's the - // case, a mod operation will fail with ENOENT. Retry it as - // an add. - if (op == EPOLL_CTL_MOD && errno == ENOENT && - ::epoll_ctl (this->poll_fd_, EPOLL_CTL_ADD, handle, &epev) == -1) - return -1; - } - info->controlled = (op != EPOLL_CTL_DEL); -#else - pollfd pfd[1]; - - pfd[0].fd = handle; - pfd[0].events = events; - pfd[0].revents = 0; - - // Change the events associated with the given file descriptor. - if (ACE_OS::write (this->poll_fd_, - pfd, - sizeof (pfd)) != sizeof (pfd)) - return -1; -#endif /*ACE_HAS_EVENT_POLL */ - } - - return old_mask; -} - -int -ACE_Dev_Poll_Reactor::ready_ops (ACE_Event_Handler * /* event_handler */, - ACE_Reactor_Mask /* mask */, - int /* ops */) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::ready_ops"); - - // Since the Dev_Poll_Reactor uses the poll result buffer, the - // ready_set cannot be directly manipulated outside of the event - // loop. - ACE_NOTSUP_RETURN (-1); -} - -int -ACE_Dev_Poll_Reactor::ready_ops (ACE_HANDLE /* handle */, - ACE_Reactor_Mask /* mask */, - int /* ops */) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::ready_ops"); - - // Since the Dev_Poll_Reactor uses the poll result buffer, the - // ready_set cannot be directly manipulated outside of the event - // loop. - ACE_NOTSUP_RETURN (-1); -} - -void -ACE_Dev_Poll_Reactor::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Dev_Poll_Reactor::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("restart_ = %d\n"), this->restart_)); - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("initialized_ = %d"), - this->initialized_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("poll_fd_ = %d"), this->poll_fd_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("size_ = %u"), this->handler_rep_.size ())); - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("deactivated_ = %d"), - this->deactivated_)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -short -ACE_Dev_Poll_Reactor::reactor_mask_to_poll_event (ACE_Reactor_Mask mask) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::reactor_mask_to_poll_event"); - - if (mask == ACE_Event_Handler::NULL_MASK) - // No event. Remove from interest set. -#if defined (ACE_HAS_EVENT_POLL) - return EPOLL_CTL_DEL; -#else - return POLLREMOVE; -#endif /* ACE_HAS_EVENT_POLL */ - - short events = 0; - - // READ, ACCEPT, and CONNECT flag will place the handle in the - // read set. - if (ACE_BIT_ENABLED (mask, ACE_Event_Handler::READ_MASK) - || ACE_BIT_ENABLED (mask, ACE_Event_Handler::ACCEPT_MASK) - || ACE_BIT_ENABLED (mask, ACE_Event_Handler::CONNECT_MASK)) - { -#if defined (ACE_HAS_EVENT_POLL) - ACE_SET_BITS (events, EPOLLIN); -#else - ACE_SET_BITS (events, POLLIN); -#endif /*ACE_HAS_EVENT_POLL*/ - } - - // WRITE and CONNECT flag will place the handle in the write set. - if (ACE_BIT_ENABLED (mask, ACE_Event_Handler::WRITE_MASK) - || ACE_BIT_ENABLED (mask, ACE_Event_Handler::CONNECT_MASK)) - { -#if defined (ACE_HAS_EVENT_POLL) - ACE_SET_BITS (events, EPOLLOUT); -#else - ACE_SET_BITS (events, POLLOUT); -#endif /*ACE_HAS_EVENT_POLL*/ - } - - // EXCEPT flag will place the handle in the except set. - if (ACE_BIT_ENABLED (mask, ACE_Event_Handler::EXCEPT_MASK)) - { -#if defined (ACE_HAS_EVENT_POLL) - ACE_SET_BITS (events, EPOLLPRI); -#else - ACE_SET_BITS (events, POLLPRI); -#endif /*ACE_HAS_EVENT_POLL*/ - } - - return events; -} - -namespace { - void polite_sleep_hook (void *) { } -} - -int -ACE_Dev_Poll_Reactor::Token_Guard::acquire_quietly (ACE_Time_Value *max_wait) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::Token_Guard::acquire_quietly"); - - // Acquire the token but don't ping any waiters; just queue up politely. - int result = 0; - if (max_wait) - { - ACE_Time_Value tv = ACE_OS::gettimeofday (); - tv += *max_wait; - - ACE_MT (result = this->token_.acquire_read (&polite_sleep_hook, - 0, - &tv)); - } - else - { - ACE_MT (result = this->token_.acquire_read (&polite_sleep_hook)); - } - - // Check for timeouts and errors. - if (result == -1) - { - if (errno == ETIME) - return 0; - else - { - ACE_ERROR ((LM_ERROR, ACE_TEXT("%t: %p\n"), ACE_TEXT("token acquire_read"))); - return -1; - } - } - - // We got the token and so let us mark ourselves as owner - this->owner_ = 1; - - return result; -} - -int -ACE_Dev_Poll_Reactor::Token_Guard::acquire (ACE_Time_Value *max_wait) -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::Token_Guard::acquire"); - - // Try to grab the token. If someone if already there, don't wake - // them up, just queue up in the thread pool. - int result = 0; - if (max_wait) - { - ACE_Time_Value tv = ACE_OS::gettimeofday (); - tv += *max_wait; - - ACE_MT (result = this->token_.acquire (0, 0, &tv)); - } - else - { - ACE_MT (result = this->token_.acquire ()); - } - - // Check for timeouts and errors. - if (result == -1) - { - if (errno == ETIME) - return 0; - else - return -1; - } - - // We got the token and so let us mark ourseleves as owner - this->owner_ = 1; - - return result; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_EVENT_POLL || ACE_HAS_DEV_POLL */ diff --git a/externals/ace/Dev_Poll_Reactor.h b/externals/ace/Dev_Poll_Reactor.h deleted file mode 100644 index 68724bf8f9c..00000000000 --- a/externals/ace/Dev_Poll_Reactor.h +++ /dev/null @@ -1,1208 +0,0 @@ -// -*- C++ -*- - -// ========================================================================= -/** - * @file Dev_Poll_Reactor.h - * - * $Id: Dev_Poll_Reactor.h 91066 2010-07-12 11:05:04Z johnnyw $ - * - * @c /dev/poll (or Linux @c sys_epoll) based Reactor implementation. - * - * @author Ossama Othman - */ -// ========================================================================= - - -#ifndef ACE_DEV_POLL_REACTOR_H -#define ACE_DEV_POLL_REACTOR_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_EVENT_POLL) && defined (ACE_HAS_DEV_POLL) -# error ACE_HAS_EVENT_POLL and ACE_HAS_DEV_POLL are mutually exclusive. -#endif /* ACE_HAS_EVENT_POLL && defined ACE_HAS_DEV_POLL */ - -#if defined (ACE_HAS_EVENT_POLL) || defined (ACE_HAS_DEV_POLL) - -#include "ace/Pipe.h" -#include "ace/Lock_Adapter_T.h" -#include "ace/Reactor_Impl.h" -#include "ace/Reactor_Token_T.h" -#include "ace/Token.h" - -#if defined (ACE_HAS_REACTOR_NOTIFICATION_QUEUE) -# include "ace/Notification_Queue.h" -#endif /* ACE_HAS_REACTOR_NOTIFICATION_QUEUE */ - -#if defined (ACE_HAS_DEV_POLL) -struct pollfd; -#elif defined (ACE_HAS_EVENT_POLL) -# include "ace/Array_Map.h" -# include /**/ -#endif - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Forward declarations -class ACE_Sig_Handler; -class ACE_Dev_Poll_Reactor; - - -// --------------------------------------------------------------------- - -/** - * @class ACE_Dev_Poll_Reactor_Notify - * - * @brief Event handler used for unblocking the ACE_Dev_Poll_Reactor - * from its event loop. - * - * This event handler is used internally by the ACE_Dev_Poll_Reactor - * as a means to allow a thread other then the one running the event - * loop to unblock the event loop. - */ -class ACE_Dev_Poll_Reactor_Notify : public ACE_Reactor_Notify -{ -public: - - /// Constructor - ACE_Dev_Poll_Reactor_Notify (void); - - /** - * @name Initialization and Termination Methods - * - * Methods called when initializing and terminating this event - * handler. - */ - virtual int open (ACE_Reactor_Impl *, - ACE_Timer_Queue *timer_queue = 0, - int disable_notify = 0); - virtual int close (void); - - /** - * Called by a thread when it wants to unblock the Reactor_Impl. - * This wakes up the Reactor_Impl if currently blocked. Pass over - * both the Event_Handler and the mask to allow the caller to - * dictate which Event_Handler method the Reactor_Impl will - * invoke. The ACE_Time_Value indicates how long to block - * trying to notify the Reactor_Impl. If timeout == 0, the - * caller will block until action is possible, else will wait until - * the relative time specified in *timeout elapses). - */ - virtual int notify (ACE_Event_Handler *eh = 0, - ACE_Reactor_Mask mask = ACE_Event_Handler::EXCEPT_MASK, - ACE_Time_Value *timeout = 0); - - /// Unimplemented method required by pure virtual method in abstract - /// base class. - /** - * This method's interface is not very compatibile with this - * Reactor's design. It's not clear why this method is pure virtual - * either. - */ - virtual int dispatch_notifications (int &number_of_active_handles, - ACE_Handle_Set &rd_mask); - - /// Returns the ACE_HANDLE of the notify pipe on which the reactor - /// is listening for notifications so that other threads can unblock - /// the Reactor_Impl. - virtual ACE_HANDLE notify_handle (void); - - /// Verify whether the buffer has dispatchable info or not. - virtual int is_dispatchable (ACE_Notification_Buffer &buffer); - - /// Handle one notify call represented in @a buffer. This could be - /// because of a thread trying to unblock the Reactor_Impl. - virtual int dispatch_notify (ACE_Notification_Buffer &buffer); - - /// Read one notify call on the handle into @a buffer. - /// This could be because of a thread trying to unblock the Reactor_Impl. - virtual int read_notify_pipe (ACE_HANDLE handle, - ACE_Notification_Buffer &buffer); - - /// Called back by the ACE_Dev_Poll_Reactor when a thread wants to - /// unblock us. - virtual int handle_input (ACE_HANDLE handle); - - /** - * Set the maximum number of times that the handle_input method - * will iterate and dispatch the ACE_Event_Handlers that are - * passed in via the notify queue before breaking out of the event - * loop. By default, this is set to -1, which means "iterate until - * the queue is empty." Setting this to a value like "1 or 2" will - * increase "fairness" (and thus prevent starvation) at the expense - * of slightly higher dispatching overhead. - */ - virtual void max_notify_iterations (int); - - /** - * Get the maximum number of times that the handle_input method - * will iterate and dispatch the ACE_Event_Handlers that are - * passed in via the notify queue before breaking out of its event - * loop. - */ - virtual int max_notify_iterations (void); - - /** - * Purge any notifications pending in this reactor for the specified - * ACE_Event_Handler object. Returns the number of notifications - * purged. Returns -1 on error. - */ - virtual int purge_pending_notifications ( - ACE_Event_Handler * = 0, - ACE_Reactor_Mask = ACE_Event_Handler::ALL_EVENTS_MASK); - - /// Dump the state of an object. - virtual void dump (void) const; - -protected: - - /** - * Keep a back pointer to the ACE_Dev_Poll_Reactor. If this value - * if NULL then the ACE_Dev_Poll_Reactor has been initialized with - * disable_notify_pipe. - */ - ACE_Dev_Poll_Reactor *dp_reactor_; - - /** - * Contains the ACE_HANDLE the ACE_Dev_Poll_Reactor is listening - * on, as well as the ACE_HANDLE that threads wanting the attention - * of the ACE_Dev_Poll_Reactor will write to. - */ - ACE_Pipe notification_pipe_; - - /** - * Keeps track of the maximum number of times that the - * ACE_Dev_Poll_Reactor_Notify::handle_input method will iterate and - * dispatch the ACE_Event_Handlers that are passed in via the - * notify pipe before breaking out of its recv loop. By default, - * this is set to -1, which means "iterate until the pipe is empty." - */ - int max_notify_iterations_; - -#if defined (ACE_HAS_REACTOR_NOTIFICATION_QUEUE) - /** - * @brief A user-space queue to store the notifications. - * - * The notification pipe has OS-specific size restrictions. That - * is, no more than a certain number of bytes may be stored in the - * pipe without blocking. This limit may be too small for certain - * applications. In this case, ACE can be configured to store all - * the events in user-space. The pipe is still needed to wake up - * the reactor thread, but only one event is sent through the pipe - * at a time. - */ - ACE_Notification_Queue notification_queue_; -#endif /* ACE_HAS_REACTOR_NOTIFICATION_QUEUE */ - - /// Lock and flag to say whether we're already dispatching notifies. - /// Purpose is to only dispatch notifies from one thread at a time. - ACE_SYNCH_MUTEX dispatching_lock_; - volatile bool dispatching_; -}; - -// --------------------------------------------------------------------- - -/** - * @class ACE_Dev_Poll_Reactor - * - * @brief A `/dev/poll' or `/dev/epoll' based Reactor implemenatation. - * - * @attention The Linux epoll implementation works quite well and is - * fully supported; however, the /dev/poll implementation is @em experimental. - * - * The ACE_Dev_Poll_Reactor uses the `/dev/poll' or '/dev/epoll' - * character devices to demultiplex events on a given set of file - * descriptors. Unlike @c select(), `/dev/poll' and `/dev/epoll' have - * no hard-coded limit on the number of file descriptors that may be - * handled at any given time. As such, the ACE_Dev_Poll_Reactor can - * generally handle a much larger number of file descriptors than - * @c select() -based reactors. Furthermore, since `/dev/poll' and - * `/dev/epoll' both return a set of file descriptors that are active, - * there is no need to "walk" the set of file descriptors to determine - * which ones are active, such as what is done with the @c select() and - * @c poll() system calls. All returned file descriptors are active. - * This makes event dispatching very efficient. - * - * @note In general, this reactor may only be used to demultiplex - * events on sockets. Demultiplexing events on pipes, for - * example may not work. This is due to a limitation in the - * underlying `/dev/poll' device driver. - * - * @note It is only possible to achieve millisecond timeout - * resolutions with the @c ACE_Dev_Poll_Reactor. However, the - * timeout resolution for timers is independent of the reactors - * timeout resolution. As such, it may be possible to achieve - * sub-millisecond timeout resolutions for timers but that is - * entirely platform dependent. - */ - -#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) -typedef ACE_Token ACE_DEV_POLL_TOKEN; -#else -typedef ACE_Noop_Token ACE_DEV_POLL_TOKEN; -#endif /* ACE_MT_SAFE && ACE_MT_SAFE != 0 */ -typedef ACE_Reactor_Token_T ACE_Dev_Poll_Reactor_Token; - -class ACE_Export ACE_Dev_Poll_Reactor : public ACE_Reactor_Impl -{ - - /** - * @struct Event_Tuple - * - * @brief Struct that collects event registration information for a handle. - * - * @internal Internal use only - * - * This struct merely provides a means to associate an event mask - * with an event handler. Such an association is needed since it is - * not possible to retrieve the event mask from the "interest set" - * stored in the `/dev/poll' or `/dev/epoll' driver. Without this - * external association, it would not be possible keep track of the - * event mask for a given event handler when suspending it or resuming - * it. - * - * @note An ACE_Handle_Set is not used since the number of handles may - * exceed its capacity (ACE_DEFAULT_SELECT_REACTOR_SIZE). - */ - struct Event_Tuple - { - /// Constructor to set up defaults. - Event_Tuple (ACE_Event_Handler *eh = 0, - ACE_Reactor_Mask m = ACE_Event_Handler::NULL_MASK, - bool is_suspended = false, - bool is_controlled = false); - - /// The event handler. - ACE_Event_Handler *event_handler; - - /// The event mask for the above event handler. - ACE_Reactor_Mask mask; - - /// Flag that states whether or not the event handler is suspended. - bool suspended; - - /// Flag to say whether or not this handle is registered with epoll. - bool controlled; - }; - - - // --------------------------------------------------------------------- - - /** - * @class Handler_Repository - * - * @internal - * - * @brief Used to map ACE_HANDLEs onto the appropriate Event_Tuple. - * - * This class is simply a container that maps a handle to its - * corresponding event tuple. It is not meant for use outside of - * the Dev_Poll_Reactor. - * - * @note Calls to any method in this class, and any modification to a - * Event_Tuple returned from this class's methods, must be made - * while holding the reactor token. - */ - class Handler_Repository - { - public: - - /// Constructor. - Handler_Repository (void); - - /// Initialize a repository that can map handles up to the value @a size. - /// Since the event tuples are accessed directly using the handle as - /// an index, @a size sets the maximum handle value, minus 1. - int open (size_t size); - - /// Close down the repository. - int close (void); - - /** - * @name Repository Manipulation Operations - * - * Methods used to search and modify the handler repository. - */ - //@{ - - /// Return a pointer to the Event_Tuple associated with @a handle. - /// If there is none associated, returns 0 and sets errno. - Event_Tuple *find (ACE_HANDLE handle); - - - /// Bind the ACE_Event_Handler to the @c ACE_HANDLE with the - /// appropriate ACE_Reactor_Mask settings. - int bind (ACE_HANDLE handle, - ACE_Event_Handler *handler, - ACE_Reactor_Mask mask); - - /// Remove the binding for @a handle; optionally decrement the associated - /// handler's reference count. - int unbind (ACE_HANDLE handle, bool decr_refcnt = true); - - /// Remove all the registered tuples. - int unbind_all (void); - - //@} - - /** - * @name Sanity Checking - * - * Methods used to prevent "out-of-range" errors when indexing the - * underlying handler array. - */ - //@{ - - // Check the @a handle to make sure it's a valid @c ACE_HANDLE that - // within the range of legal handles (i.e., greater than or equal to - // zero and less than @c max_size_). - bool invalid_handle (ACE_HANDLE handle) const; - - // Check the handle to make sure it's a valid @c ACE_HANDLE that is - // within the range of currently registered handles (i.e., greater - // than or equal to zero and less than @c max_handlep1_). - bool handle_in_range (ACE_HANDLE handle) const; - - //@} - - /// Returns the current table size. - size_t size (void) const; - - /// Returns the current table size. - size_t max_size (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - - private: - - /// Current number of handles. - int size_; - - /// Maximum number of handles. - int max_size_; - - /// The underlying array of event handlers. - /** - * The array of event handlers is directly indexed directly using - * an @c ACE_HANDLE value. This is Unix-specific. - */ - Event_Tuple *handlers_; - - }; - -public: - - /// Initialize @c ACE_Dev_Poll_Reactor with the default size. - /** - * The default size for the @c ACE_Dev_Poll_Reactor is the maximum - * number of open file descriptors for the process. - */ - ACE_Dev_Poll_Reactor (ACE_Sig_Handler * = 0, - ACE_Timer_Queue * = 0, - int disable_notify_pipe = 0, - ACE_Reactor_Notify *notify = 0, - int mask_signals = 1, - int s_queue = ACE_DEV_POLL_TOKEN::FIFO); - - /// Initialize ACE_Dev_Poll_Reactor with size @a size. - /** - * @note On Unix platforms, the @a size parameter should be as large - * as the maximum number of file descriptors allowed for a - * given process. This is necessary since a file descriptor - * is used to directly index the array of event handlers - * maintained by the Reactor's handler repository. Direct - * indexing is used for efficiency reasons. If the size - * parameter is less than the process maximum, the process - * maximum will be decreased in order to prevent potential - * access violations. - */ - ACE_Dev_Poll_Reactor (size_t size, - bool restart = false, - ACE_Sig_Handler * = 0, - ACE_Timer_Queue * = 0, - int disable_notify_pipe = 0, - ACE_Reactor_Notify *notify = 0, - int mask_signals = 1, - int s_queue = ACE_DEV_POLL_TOKEN::FIFO); - - /// Close down and release all resources. - virtual ~ACE_Dev_Poll_Reactor (void); - - /// Initialization. - virtual int open (size_t size, - bool restart = false, - ACE_Sig_Handler * = 0, - ACE_Timer_Queue * = 0, - int disable_notify_pipe = 0, - ACE_Reactor_Notify * = 0); - - /** - * @param handle allows the reactor to check if the caller is - * valid. - * - * @return 0 if the size of the current message has been put in - * size. -1 if not. - */ - virtual int current_info (ACE_HANDLE handle, size_t & /* size */); - - /// Use a user specified signal handler instead. - virtual int set_sig_handler (ACE_Sig_Handler *signal_handler); - - /// Set a user-specified timer queue. - virtual int timer_queue (ACE_Timer_Queue *tq); - - /// Get the timer queue - /// @return The current @c ACE_Timer_Queue. - virtual ACE_Timer_Queue *timer_queue (void) const; - - /// Close down and release all resources. - virtual int close (void); - - // = Event loop drivers. - /** - * Returns non-zero if there are I/O events "ready" for dispatching, - * but does not actually dispatch the event handlers. By default, - * don't block while checking this, i.e., "poll". - * - * @note It is only possible to achieve millisecond timeout - * resolutions with the @c ACE_Dev_Poll_Reactor. - */ - virtual int work_pending ( - const ACE_Time_Value &max_wait_time = ACE_Time_Value::zero); - - /** - * This event loop driver blocks for up to @a max_wait_time before - * returning. It will return earlier if events occur. Note that - * @a max_wait_time can be 0, in which case this method blocks - * indefinitely until events occur. - * @par - * @a max_wait_time is decremented to reflect how much time this - * call took. For instance, if a time value of 3 seconds is passed - * to @c handle_events() and an event occurs after 2 seconds, - * @a max_wait_time will equal 1 second. This can be used if an - * application wishes to handle events for some fixed amount of - * time. - * @par - * The only difference between @c alertable_handle_events() and - * handle_events() is that in the alertable case, the event loop - * will return when the system queues an I/O completion routine or - * an Asynchronous Procedure Call. - * - * @return The total number of @c ACE_Event_Handlers that were - * dispatched, 0 if the @a max_wait_time elapsed without - * dispatching any handlers, or -1 if an error occurs. - - * @note It is only possible to achieve millisecond timeout - * resolutions with the @c ACE_Dev_Poll_Reactor. - */ - virtual int handle_events (ACE_Time_Value *max_wait_time = 0); - virtual int alertable_handle_events (ACE_Time_Value *max_wait_time = 0); - - /** - * This method is just like the one above, except the - * @a max_wait_time value is a reference and can therefore never be - * @c NULL. - * - * @note It is only possible to achieve millisecond timeout - * resolutions with the @c ACE_Dev_Poll_Reactor. - */ - virtual int handle_events (ACE_Time_Value &max_wait_time); - virtual int alertable_handle_events (ACE_Time_Value &max_wait_time); - - // = Event handling control. - - /** - * @return The status of Reactor. If this function returns 0, the - * reactor is actively handling events. If it returns - * non-zero, @c handle_events() and - * @c handle_alertable_events() return -1 immediately. - */ - virtual int deactivated (void); - - /** - * Control whether the Reactor will handle any more incoming events - * or not. If @a do_stop == 1, the Reactor will be disabled. By - * default, a reactor is in active state and can be - * deactivated/reactived as desired. - */ - virtual void deactivate (int do_stop); - - // = Register and remove Handlers. - - /// Register @a event_handler with @a mask. The I/O handle will - /// always come from get_handle on the event_handler. - virtual int register_handler (ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask); - - /// Register @a event_handler with @a mask. The I/O handle is - /// provided through the @a io_handle parameter. - virtual int register_handler (ACE_HANDLE io_handle, - ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask); - - /** - * Register an @a event_handler that will be notified when - * @a event_handle is signaled. @a mask specifies the network - * events that the @a event_handler is interested in. - */ - virtual int register_handler (ACE_HANDLE event_handle, - ACE_HANDLE io_handle, - ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask); - - /// Register @a event_handler> with all the @a handles> in the @c - /// Handle_Set. - virtual int register_handler (const ACE_Handle_Set &handles, - ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask); - - /** - * Register @a new_sh to handle the signal @a signum using the - * @a new_disp. Returns the @a old_sh that was previously - * registered (if any), along with the @a old_disp of the signal - * handler. - */ - virtual int register_handler (int signum, - ACE_Event_Handler *new_sh, - ACE_Sig_Action *new_disp = 0, - ACE_Event_Handler **old_sh = 0, - ACE_Sig_Action *old_disp = 0); - - /// Registers @a new_sh to handle a set of signals @a sigset using the - /// @a new_disp. - virtual int register_handler (const ACE_Sig_Set &sigset, - ACE_Event_Handler *new_sh, - ACE_Sig_Action *new_disp = 0); - - /// Removes @a event_handler. - /** - * @note The I/O handle will be obtained using @c get_handle() - * method of @a event_handler . If @a mask == - * @c ACE_Event_Handler::DONT_CALL then the @c handle_close() - * method of the @a event_handler is not invoked. - */ - virtual int remove_handler (ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask); - - /** - * Removes @a handle. If @a mask == ACE_Event_Handler::DONT_CALL - * then the method of the associated - * is not invoked. - */ - virtual int remove_handler (ACE_HANDLE handle, - ACE_Reactor_Mask mask); - - /** - * Removes all handles in @a handle_set. If @a mask == - * ACE_Event_Handler::DONT_CALL then the method of - * the associated s is not invoked. - */ - virtual int remove_handler (const ACE_Handle_Set &handle_set, - ACE_Reactor_Mask mask); - - /** - * Remove the ACE_Event_Handler currently associated with @a signum. - * Install the new disposition (if given) and return the previous - * disposition (if desired by the caller). Returns 0 on success and - * -1 if @a signum is invalid. - */ - virtual int remove_handler (int signum, - ACE_Sig_Action *new_disp, - ACE_Sig_Action *old_disp = 0, - int sigkey = -1); - - /// Calls for every signal in @a sigset. - virtual int remove_handler (const ACE_Sig_Set &sigset); - - // = Suspend and resume Handlers. - - /// Suspend event_handler temporarily. Use - /// ACE_Event_Handler::get_handle() to get the handle. - virtual int suspend_handler (ACE_Event_Handler *event_handler); - - /// Suspend handle temporarily. - virtual int suspend_handler (ACE_HANDLE handle); - - /// Suspend all handles in handle set temporarily. - virtual int suspend_handler (const ACE_Handle_Set &handles); - - /// Suspend all handles temporarily. - virtual int suspend_handlers (void); - - /// Resume event_handler. Use ACE_Event_Handler::get_handle() to - /// get the handle. - virtual int resume_handler (ACE_Event_Handler *event_handler); - - /// Resume handle. - virtual int resume_handler (ACE_HANDLE handle); - - /// Resume all handles in handle set. - virtual int resume_handler (const ACE_Handle_Set &handles); - - /// Resume all handles. - virtual int resume_handlers (void); - - /// Does the reactor allow the application to resume the handle on - /// its own, i.e., can it pass on the control of handle resumption to - /// the application. - virtual int resumable_handler (void); - - /// Return true if we any event associations were made by the reactor - /// for the handles that it waits on, false otherwise. - virtual bool uses_event_associations (void); - - // = Timer management. - - /** - * Schedule an ACE_Event_Handler that will expire after an amount - * of time. The return value of this method, a timer_id value, - * uniquely identifies the event_handler in the ACE_Reactor's - * internal list of timers. - * This timer_id value can be used to cancel the timer - * with the cancel_timer() call. - * - * @see cancel_timer() - * @see reset_timer_interval() - * - * @param event_handler event handler to schedule on reactor - * @param arg argument passed to the handle_timeout() method of - * event_handler. - * @param delay time interval after which the timer will expire. - * @param interval time interval for which the timer will be - * automatically rescheduled. - * @return -1 on failure, a timer_id value on success - */ - virtual long schedule_timer (ACE_Event_Handler *event_handler, - const void *arg, - const ACE_Time_Value &delay, - const ACE_Time_Value &interval = ACE_Time_Value::zero); - - /** - * Resets the interval of the timer represented by @a timer_id to - * @a interval, which is specified in relative time to the current - * . If @a interval is equal to - * ACE_Time_Value::zero, the timer will become a non-rescheduling - * timer. Returns 0 if successful, -1 if not. - */ - virtual int reset_timer_interval (long timer_id, - const ACE_Time_Value &interval); - - /// Cancel all Event_Handlers that match the address of - /// @a event_handler. Returns number of handlers cancelled. - virtual int cancel_timer (ACE_Event_Handler *event_handler, - int dont_call_handle_close = 1); - - /** - * Cancel the single event handler that matches the @a timer_id value - * (which was returned from the schedule method). If @a arg is - * non-NULL then it will be set to point to the ``magic cookie'' - * argument passed in when the event handler was registered. This - * makes it possible to free up the memory and avoid memory leaks. - * Returns 1 if cancellation succeeded and 0 if the @a timer_id - * wasn't found. - */ - virtual int cancel_timer (long timer_id, - const void **arg = 0, - int dont_call_handle_close = 1); - - // = High-level event handler scheduling operations - - /// Add @a masks_to_be_added to the @a event_handler's entry. - /// @a event_handler must already have been registered. - virtual int schedule_wakeup (ACE_Event_Handler *event_handler, - ACE_Reactor_Mask masks_to_be_added); - - /// Add @a masks_to_be_added to the @a handle's entry. - /// associated with @a handle must already have been registered. - virtual int schedule_wakeup (ACE_HANDLE handle, - ACE_Reactor_Mask masks_to_be_added); - - /// Clear @a masks_to_be_cleared from the @a event_handler's entry. - virtual int cancel_wakeup (ACE_Event_Handler *event_handler, - ACE_Reactor_Mask masks_to_be_cleared); - - /// Clear @a masks_to_be_cleared from the @a handle's entry. - virtual int cancel_wakeup (ACE_HANDLE handle, - ACE_Reactor_Mask masks_to_be_cleared); - - // = Notification methods. - - /** - * Notify @a event_handler of @a mask event. The ACE_Time_Value - * indicates how long to blocking trying to notify. If @a timeout == - * 0, the caller will block until action is possible, else will wait - * until the relative time specified in @a timeout elapses). - */ - virtual int notify (ACE_Event_Handler *event_handler = 0, - ACE_Reactor_Mask mask = ACE_Event_Handler::EXCEPT_MASK, - ACE_Time_Value * = 0); - - /** - * Set the maximum number of times that ACE_Reactor_Impl will - * iterate and dispatch the ACE_Event_Handlers that are passed in - * via the notify queue before breaking out of its - * loop. By default, this is set to - * -1, which means "iterate until the queue is empty." Setting this - * to a value like "1 or 2" will increase "fairness" (and thus - * prevent starvation) at the expense of slightly higher dispatching - * overhead. - */ - virtual void max_notify_iterations (int); - - /** - * Get the maximum number of times that the ACE_Reactor_Impl will - * iterate and dispatch the ACE_Event_Handlers that are passed in - * via the notify queue before breaking out of its - * loop. - */ - virtual int max_notify_iterations (void); - - /** - * Purge any notifications pending in this reactor for the specified - * ACE_Event_Handler object. Returns the number of notifications - * purged. Returns -1 on error. - */ - virtual int purge_pending_notifications (ACE_Event_Handler * = 0, - ACE_Reactor_Mask = ACE_Event_Handler::ALL_EVENTS_MASK); - - /** - * Return the Event_Handler associated with @a handle. Return 0 if - * @a handle is not registered. - */ - virtual ACE_Event_Handler *find_handler (ACE_HANDLE handle); - - /** - * Check to see if @a handle is associated with a valid Event_Handler - * bound to @a mask. Return the @a event_handler associated with this - * @c handler if @a event_handler != 0. - */ - virtual int handler (ACE_HANDLE handle, - ACE_Reactor_Mask mask, - ACE_Event_Handler **event_handler = 0); - - /** - * Check to see if @a signum is associated with a valid Event_Handler - * bound to a signal. Return the @a event_handler associated with - * this @c handler if @a event_handler != 0. - */ - virtual int handler (int signum, - ACE_Event_Handler ** = 0); - - /// Returns true if Reactor has been successfully initialized, else - /// false. - virtual bool initialized (void); - - /// Returns the current size of the Reactor's internal descriptor - /// table. - virtual size_t size (void) const; - - /// Returns a reference to the Reactor's internal lock. - virtual ACE_Lock &lock (void); - - /// Wake up all threads waiting in the event loop. - virtual void wakeup_all_threads (void); - - /// Transfers ownership of Reactor_Impl to the new_owner. - /** - * @note There is no need to set the owner of the event loop for the - * ACE_Dev_Poll_Reactor. Multiple threads may invoke the - * event loop simulataneously. As such, this method is a - * no-op. - */ - virtual int owner (ACE_thread_t new_owner, ACE_thread_t *old_owner = 0); - - /// Return the ID of the "owner" thread. - /** - * @note There is no need to set the owner of the event loop for the - * ACE_Dev_Poll_Reactor. Multiple threads may invoke the - * event loop simulataneously. As such, this method is a - * no-op. - */ - virtual int owner (ACE_thread_t *owner); - - /// Get the existing restart value. - virtual bool restart (void); - - /// Set a new value for restart and return the original value. - /** - * @param r If zero, then the event loop will not be automatically - * restarted if the underlying poll is interrupted via the - * INTR (interrupt) signal. - * - * @return Returns the previous "restart" value. - */ - virtual bool restart (bool r); - - /// Set position of the owner thread. - /** - * @note This is currently a no-op. - */ - virtual void requeue_position (int); - - /// Get position of the owner thread. - /** - * @note This is currently a no-op. - */ - virtual int requeue_position (void); - - /** - * @name Low-level wait_set mask manipulation methods - * - * Low-level methods to manipulate the event/reactor mask associated - * with a handle and event handler when polling for events. - * @par - * The "interest set," i.e. the wait set, can be directly - * manipulated with these methods. - */ - //@{ - - /// GET/SET/ADD/CLR the dispatch mask "bit" bound with the - /// event_handler and mask. - /** - * @return Old mask on success, -1 on error. - */ - virtual int mask_ops (ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask, - int ops); - - /// GET/SET/ADD/CLR the dispatch MASK "bit" bound with the handle - /// and mask. - /** - * @return Old mask on success, -1 on error. - */ - virtual int mask_ops (ACE_HANDLE handle, - ACE_Reactor_Mask mask, - int ops); - - //@} - - /** - * @name Low-level ready_set mask manipulation methods - * - * These methods are unimplemented. - */ - //@{ - - /// GET/SET/ADD/CLR the ready "bit" bound with the event_handler - /// and mask. - virtual int ready_ops (ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask, - int ops); - - /// GET/SET/ADD/CLR the ready "bit" bound with the handle and mask. - virtual int ready_ops (ACE_HANDLE handle, - ACE_Reactor_Mask, - int ops); - - //@} - - /// Dump the state of an object. - virtual void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - - class Token_Guard; - - /// Non-locking version of wait_pending(). - /** - * Returns non-zero if there are I/O events "ready" for dispatching, - * but does not actually dispatch the event handlers. By default, - * don't block while checking this, i.e., "poll". - * - * @note It is only possible to achieve millisecond timeout - * resolutions with the ACE_Dev_Poll_Reactor. - */ - int work_pending_i (ACE_Time_Value *max_wait_time); - - /// Poll for events and return the number of event handlers that - /// were dispatched. - /** - * This is a helper method called by all handle_events() methods. - */ - int handle_events_i (ACE_Time_Value *max_wait_time, Token_Guard &guard); - - /// Perform the upcall with the given event handler method. - int upcall (ACE_Event_Handler *event_handler, - int (ACE_Event_Handler::*callback)(ACE_HANDLE), - ACE_HANDLE handle); - - /** - * Dispatch ACE_Event_Handlers for time events, I/O events, and - * signal events. Returns the total number of ACE_Event_Handlers - * that were dispatched or -1 if something goes wrong. - */ - int dispatch (Token_Guard &guard); - - /// Dispatch a single timer, if ready. - /// Returns: 0 if no timers ready (token still held), - /// 1 if a timer was expired (token released), - /// -1 on error (token still held). - int dispatch_timer_handler (Token_Guard &guard); - - /// Dispatch an IO event to the corresponding event handler. Returns - /// Returns: 0 if no events ready (token still held), - /// 1 if an event was expired (token released), - /// -1 on error (token still held). - int dispatch_io_event (Token_Guard &guard); - - /// Register the given event handler with the reactor. - int register_handler_i (ACE_HANDLE handle, - ACE_Event_Handler *eh, - ACE_Reactor_Mask mask); - - /// Remove the event handler associated with the given handle and - /// event mask from the "interest set." If @a eh is supplied, only - /// do the remove if @eh matches the event handler that's registered - /// for @a handle. - int remove_handler_i (ACE_HANDLE handle, - ACE_Reactor_Mask mask, - ACE_Event_Handler *eh = 0); - - /// Temporarily remove the given handle from the "interest set." - int suspend_handler_i (ACE_HANDLE handle); - - /// Place the given handle that was temporarily removed from the - /// "interest set," i.e that was suspended, back in to the interest - /// set. The given handle will once again be polled for events. - int resume_handler_i (ACE_HANDLE handle); - - /// GET/SET/ADD/CLR the dispatch MASK "bit" bound with the handle - /// and mask. This internal helper method acquires no lock. - /** - * @return Old mask on success, -1 on error. - */ - int mask_ops_i (ACE_HANDLE handle, - ACE_Reactor_Mask mask, - int ops); - - /// Convert a reactor mask to its corresponding poll() event mask. - short reactor_mask_to_poll_event (ACE_Reactor_Mask mask); - -protected: - - /// Has the reactor been initialized. - bool initialized_; - - /// The file descriptor associated with the open `/dev/poll' or - /// `/dev/epoll' device. - /** - * All interactions with the `/dev/poll' or `/dev/epoll' device are - * done through this file descriptor. - */ - ACE_HANDLE poll_fd_; - -#if defined (ACE_HAS_EVENT_POLL) - /// Event structure to be filled by epoll_wait. epoll_wait() only gets - /// one event at a time and we rely on it's internals for fairness. - /// If this struct's fd is ACE_INVALID_HANDLE, the rest is indeterminate. - /// If the fd is good, the event is one that's been retrieved by - /// epoll_wait() but not yet processed. - struct epoll_event event_; - - /// Event handlers that are suspended/resumed around upcalls are not - /// immediately resumed; they're added to this list for resumption at - /// the next epoll_wait() call. This avoids always needing to acquire the - /// token just to resume a handler. Of course, if there are no other - /// handlers in the to-be-resumed list and an epoll_wait is already in - /// progress, the reactor needs to be notified to force another run around - /// the epoll_wait() call. - typedef ACE_Array_Map Resume_Map; - Resume_Map to_be_resumed_; - volatile bool epoll_wait_in_progress_; - ACE_SYNCH_MUTEX to_be_resumed_lock_; -#else - /// The pollfd array that `/dev/poll' will feed its results to. - struct pollfd *dp_fds_; - - - /// Pointer to the next pollfd array element that contains the next - /// event to be dispatched. - struct pollfd *start_pfds_; - - /// The last element in the pollfd array plus one. - /** - * The loop that dispatches IO events stops when this->start_pfds == - * this->end_pfds_. - */ - struct pollfd *end_pfds_; -#endif /* ACE_HAS_EVENT_POLL */ - - /// This flag is used to keep track of whether we are actively handling - /// events or not. - sig_atomic_t deactivated_; - - /// Lock used for synchronization of reactor state. - ACE_Dev_Poll_Reactor_Token token_; - - /// Adapter used to return internal lock to outside world. - ACE_Lock_Adapter lock_adapter_; - - /// The repository that contains all registered event handlers. - Handler_Repository handler_rep_; - - /// Defined as a pointer to allow overriding by derived classes... - ACE_Timer_Queue *timer_queue_; - - /// Keeps track of whether we should delete the timer queue (if we - /// didn't create it, then we don't delete it). - bool delete_timer_queue_; - - /// Handle signals without requiring global/static variables. - ACE_Sig_Handler *signal_handler_; - - /// Keeps track of whether we should delete the signal handler (if we - /// didn't create it, then we don't delete it). - bool delete_signal_handler_; - - /// Callback object that unblocks the if it's - /// sleeping. - ACE_Reactor_Notify *notify_handler_; - - /// Keeps track of whether we need to delete the notify handler (if - /// we didn't create it, then we don't delete it). - bool delete_notify_handler_; - - /// Flag that determines if signals are masked during event - /// dispatching. - /** - * If 0 then the Reactor will not mask the signals during the event - * dispatching. This is useful for applications that do not - * register any signal handlers and want to reduce the overhead - * introduce by the kernel level locks required to change the mask. - */ - int mask_signals_; - - /// Restart the handle_events event loop method automatically when - /// polling function in use (ioctl() in this case) is interrupted - /// via an EINTR signal. - bool restart_; - -protected: - - /** - * @class Token_Guard - * - * @brief A helper class that helps grabbing, releasing and waiting - * on tokens for a thread that needs access to the reactor's token. - */ - class ACE_Export Token_Guard - { - public: - - /// Constructor that will grab the token for us - Token_Guard (ACE_Dev_Poll_Reactor_Token &token); - - /// Destructor. This will release the token if it hasn't been - /// released till this point - ~Token_Guard (void); - - /// Release the token .. - void release_token (void); - - /// Returns whether the thread that created this object owns the - /// token or not. - int is_owner (void); - - /// A helper method that acquires the token 1) at a low priority, and - /// 2) wait quietly for the token, not waking another thread. This - /// is appropriate for cases where a thread wants to wait for and - /// dispatch an event, not causing an existing waiter to relinquish the - /// token, and also queueing up behind other threads waiting to modify - /// event records. - int acquire_quietly (ACE_Time_Value *max_wait = 0); - - /// A helper method that acquires the token at a high priority, and - /// does wake the current token holder. - int acquire (ACE_Time_Value *max_wait = 0); - - private: - - Token_Guard (void); - - private: - - /// The Reactor token. - ACE_Dev_Poll_Reactor_Token &token_; - - /// Flag that indicate whether the thread that created this object - /// owns the token or not. A value of 0 indicates that this class - /// hasn't got the token (and hence the thread) and a value of 1 - /// vice-versa. - int owner_; - - }; - -}; - - -/** - * @class ACE_Dev_Poll_Handler_Guard - * - * @brief Class used to make event handler reference count - * manipulation exception-safe. - * - * This class makes the reference count manipulation that occurs - * during an upcall exception-safe. Prior to dispatching the event - * handler, the reference count is increased. Once the upcall for the - * given event handler is complete, its reference count will be decreased. - */ -class ACE_Dev_Poll_Handler_Guard -{ -public: - - /// Constructor - /** - * The constructor checks to see if @a eh is a reference-counted handler and - * remember that for later. If @a eh is reference counted, its reference - * count is incremented unless @a do_incr is false. - * @a do_incr should be false if the reference count was incremented - * independently of this guard, for example, on a notify handler since - * the reference count is incremented when the notify is queued. - */ - ACE_Dev_Poll_Handler_Guard (ACE_Event_Handler *eh, bool do_incr = true); - - /// Destructor - /** - * The destructor decrements the reference count on the event - * handler corresponding to the given handle. - */ - ~ACE_Dev_Poll_Handler_Guard (void); - - /// Release the event handler from this guard; when the destructor is - /// called, the handler's reference count will not be decremented. - void release (void); - -private: - - /// The event handler being managed. - ACE_Event_Handler *eh_; - - /// true if eh_ is a reference-counted handler. - bool refcounted_; - -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -# include "ace/Dev_Poll_Reactor.inl" -#endif /* __ACE_INLINE__ */ - -#endif /* ACE_HAS_EVENT_POLL || ACE_HAS_DEV_POLL */ - -#include /**/ "ace/post.h" - -#endif /* ACE_DEV_POLL_REACTOR_H */ diff --git a/externals/ace/Dev_Poll_Reactor.inl b/externals/ace/Dev_Poll_Reactor.inl deleted file mode 100644 index 0e72b305c62..00000000000 --- a/externals/ace/Dev_Poll_Reactor.inl +++ /dev/null @@ -1,134 +0,0 @@ -// -*- C++ -*- -// $Id: Dev_Poll_Reactor.inl 91066 2010-07-12 11:05:04Z johnnyw $ - -#include "ace/Log_Msg.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE -ACE_Dev_Poll_Reactor::Event_Tuple::Event_Tuple (ACE_Event_Handler *eh, - ACE_Reactor_Mask m, - bool is_suspended, - bool is_controlled) - : event_handler (eh), - mask (m), - suspended (is_suspended), - controlled (is_controlled) -{ -} - -// --------------------------------------------------------------------- - -ACE_INLINE size_t -ACE_Dev_Poll_Reactor::Handler_Repository::size (void) const -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::Handler_Repository::size"); - - return this->size_; -} - -ACE_INLINE size_t -ACE_Dev_Poll_Reactor::Handler_Repository::max_size (void) const -{ - ACE_TRACE ("ACE_Dev_Poll_Reactor::Handler_Repository::max_size"); - - return this->max_size_; -} - -// ----------------------------------------------------------------- - -ACE_INLINE -ACE_Dev_Poll_Handler_Guard::ACE_Dev_Poll_Handler_Guard - (ACE_Event_Handler *eh, - bool do_incr) - : eh_ (eh), - refcounted_ (false) -{ - if (eh == 0) - return; - - this->refcounted_ = - eh->reference_counting_policy ().value () == - ACE_Event_Handler::Reference_Counting_Policy::ENABLED; - - if (do_incr && this->refcounted_) - eh->add_reference (); -} - -ACE_INLINE -ACE_Dev_Poll_Handler_Guard::~ACE_Dev_Poll_Handler_Guard (void) -{ - if (this->refcounted_ && this->eh_ != 0) - this->eh_->remove_reference (); -} - -ACE_INLINE void -ACE_Dev_Poll_Handler_Guard::release (void) -{ - this->eh_ = 0; -} - -// --------------------------------------------------------------------- - -ACE_INLINE int -ACE_Dev_Poll_Reactor::upcall (ACE_Event_Handler *event_handler, - int (ACE_Event_Handler::*callback)(ACE_HANDLE), - ACE_HANDLE handle) -{ - // If the handler returns positive value (requesting a reactor - // callback) just call back as many times as the handler requests - // it. The handler is suspended internally and other threads are off - // handling other things. - int status = 0; - - do - { - status = (event_handler->*callback) (handle); - } - while (status > 0 && event_handler != this->notify_handler_); - - return status; -} - - -/************************************************************************/ -// Methods for ACE_Dev_Poll_Reactor::Token_Guard -/************************************************************************/ - -ACE_INLINE -ACE_Dev_Poll_Reactor::Token_Guard::Token_Guard (ACE_Dev_Poll_Reactor_Token &token) - - : token_ (token), - owner_ (0) -{ -} - -ACE_INLINE -ACE_Dev_Poll_Reactor::Token_Guard::~Token_Guard (void) -{ - if (this->owner_ == 1) - { - ACE_MT (this->token_.release ()); - this->owner_ = 0; - } -} - -ACE_INLINE void -ACE_Dev_Poll_Reactor::Token_Guard::release_token (void) -{ - if (this->owner_) - { - ACE_MT (this->token_.release ()); - - // We are not the owner anymore.. - this->owner_ = 0; - } -} - -ACE_INLINE int -ACE_Dev_Poll_Reactor::Token_Guard::is_owner (void) -{ - return this->owner_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Dirent.cpp b/externals/ace/Dirent.cpp deleted file mode 100644 index df1290e1e53..00000000000 --- a/externals/ace/Dirent.cpp +++ /dev/null @@ -1,7 +0,0 @@ -// $Id: Dirent.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Dirent.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Dirent.inl" -#endif /* __ACE_INLINE__ */ diff --git a/externals/ace/Dirent.h b/externals/ace/Dirent.h deleted file mode 100644 index 7735fb1f293..00000000000 --- a/externals/ace/Dirent.h +++ /dev/null @@ -1,122 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Dirent.h - * - * $Id: Dirent.h 91064 2010-07-12 10:11:24Z johnnyw $ - * - * Define a portable C++ interface to ACE_OS_Dirent directory-entry - * manipulation. - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_DIRENT_H -#define ACE_DIRENT_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/OS_NS_dirent.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Dirent - * - * @brief Define a portable C++ directory-entry iterator based on the POSIX API. - */ -class ACE_Export ACE_Dirent -{ -public: - // = Initialization and termination methods. - /// Default constructor. - ACE_Dirent (void); - - /// Constructor calls @c opendir() - explicit ACE_Dirent (const ACE_TCHAR *dirname); - - /// Opens the directory named by filename and associates a directory - /// stream with it. - int open (const ACE_TCHAR *filename); - - /// Destructor calls @c closedir(). - ~ACE_Dirent (void); - - /// Closes the directory stream and frees the ACE_DIR structure. - void close (void); - - // = Iterator methods. - /** - * Returns a pointer to a structure representing the directory entry - * at the current position in the directory stream to which dirp - * refers, and positions the directory stream at the next entry, - * except on read-only filesystems. It returns a NULL pointer upon - * reaching the end of the directory stream, or upon detecting an - * invalid location in the directory. @c read() shall not return - * directory entries containing empty names. It is unspecified - * whether entries are returned for dot or dot-dot. The pointer - * returned by @c read() points to data that may be overwritten by - * another call to @c read() on the same directory stream. This - * data shall not be overwritten by another call to @c read() on a - * different directory stream. @c read() may buffer several - * directory entries per actual read operation; @c read() marks for - * update the st_atime field of the directory each time the - * directory is actually read. - */ - ACE_DIRENT *read (void); - - /** - * Has the equivalent functionality as @c read() except that an - * @a entry and @a result buffer must be supplied by the caller to - * store the result. - */ - int read (struct ACE_DIRENT *entry, - struct ACE_DIRENT **result); - - // = Manipulators. - /// Returns the current location associated with the directory - /// stream. - long tell (void); - - /** - * Sets the position of the next @c read() operation on the - * directory stream. The new position reverts to the position - * associated with the directory stream at the time the @c tell() - * operation that provides loc was performed. Values returned by - * @c tell() are good only for the lifetime of the ACE_DIR pointer from - * which they are derived. If the directory is closed and then - * reopened, the @c telldir() value may be invalidated due to - * undetected directory compaction. It is safe to use a previous - * @c telldir() value immediately after a call to @c opendir() and before - * any calls to readdir. - */ - void seek (long loc); - - /** - * Resets the position of the directory stream to the beginning of - * the directory. It also causes the directory stream to refer to - * the current state of the corresponding directory, as a call to - * @c opendir() would. - */ - void rewind (void); - -private: - /// Pointer to the directory stream. - ACE_DIR *dirp_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Dirent.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_DIRENT_H */ diff --git a/externals/ace/Dirent.inl b/externals/ace/Dirent.inl deleted file mode 100644 index 01ce3a96c4b..00000000000 --- a/externals/ace/Dirent.inl +++ /dev/null @@ -1,99 +0,0 @@ -// -*- C++ -*- -// -// $Id: Dirent.inl 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Log_Msg.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE int -ACE_Dirent::open (const ACE_TCHAR *dirname) -{ - // If the directory stream is already open, close it to prevent - // possible resource leaks. - - if (this->dirp_ != 0) - { - ACE_OS::closedir (this->dirp_); - this->dirp_ = 0; - } - - this->dirp_ = ACE_OS::opendir (dirname); - - if (this->dirp_ == 0) - return -1; - else - return 0; -} - -ACE_INLINE -ACE_Dirent::ACE_Dirent (void) - : dirp_ (0) -{ -} - -ACE_INLINE -ACE_Dirent::ACE_Dirent (const ACE_TCHAR *dirname) - : dirp_ (0) -{ - if (this->open (dirname) == -1) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_Dirent::ACE_Dirent"))); -} - -ACE_INLINE -ACE_Dirent::~ACE_Dirent (void) -{ - if (this->dirp_ != 0) - ACE_OS::closedir (this->dirp_); -} - -ACE_INLINE ACE_DIRENT * -ACE_Dirent::read (void) -{ - return this->dirp_ ? ACE_OS::readdir (this->dirp_) : 0; -} - -ACE_INLINE int -ACE_Dirent::read (struct ACE_DIRENT *entry, - struct ACE_DIRENT **result) -{ - return this->dirp_ - ? ACE_OS::readdir_r (this->dirp_, entry, result) - : 0; -} - -ACE_INLINE void -ACE_Dirent::close (void) -{ - if (this->dirp_ != 0) - { - ACE_OS::closedir (this->dirp_); - - // Prevent double closure - this->dirp_ = 0; - } -} - -ACE_INLINE void -ACE_Dirent::rewind (void) -{ - if (this->dirp_) - ACE_OS::rewinddir (this->dirp_); -} - -ACE_INLINE void -ACE_Dirent::seek (long loc) -{ - if (this->dirp_) - ACE_OS::seekdir (this->dirp_, loc); -} - -ACE_INLINE long -ACE_Dirent::tell (void) -{ - return this->dirp_ ? ACE_OS::telldir (this->dirp_) : 0; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Dirent_Selector.cpp b/externals/ace/Dirent_Selector.cpp deleted file mode 100644 index 8fcb5775b29..00000000000 --- a/externals/ace/Dirent_Selector.cpp +++ /dev/null @@ -1,59 +0,0 @@ -// $Id: Dirent_Selector.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Dirent_Selector.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Dirent_Selector.inl" -#endif /* __ACE_INLINE__ */ - -#include "ace/OS_NS_dirent.h" -#include "ace/OS_NS_stdlib.h" - -ACE_RCSID (ace, - Dirent_Selector, - "$Id: Dirent_Selector.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Construction/Destruction - -ACE_Dirent_Selector::ACE_Dirent_Selector (void) - : namelist_ (0), - n_ (0) -{ -} - -ACE_Dirent_Selector::~ACE_Dirent_Selector (void) -{ - // Free up any allocated resources. - this->close(); -} - -int -ACE_Dirent_Selector::open (const ACE_TCHAR *dir, - ACE_SCANDIR_SELECTOR sel, - ACE_SCANDIR_COMPARATOR cmp) -{ - n_ = ACE_OS::scandir (dir, &this->namelist_, sel, cmp); - return n_; -} - -int -ACE_Dirent_Selector::close (void) -{ - for (--n_; n_ >= 0; --n_) - { -#if defined (ACE_LACKS_STRUCT_DIR) - // Only the lacking-struct-dir emulation allocates this. Native - // scandir includes d_name in the dirent struct itself. - ACE_OS::free (this->namelist_[n_]->d_name); -#endif - ACE_OS::free (this->namelist_[n_]); - } - - ACE_OS::free (this->namelist_); - this->namelist_ = 0; - return 0; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Dirent_Selector.h b/externals/ace/Dirent_Selector.h deleted file mode 100644 index 20673c473a9..00000000000 --- a/externals/ace/Dirent_Selector.h +++ /dev/null @@ -1,75 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Dirent_Selector.h - * - * $Id: Dirent_Selector.h 80826 2008-03-04 14:51:23Z wotte $ - * - * Define a portable C++ interface to the method. - * - * @author Rich Newman - */ -//============================================================================= - -#ifndef ACE_DIRENT_SELECTOR_H -#define ACE_DIRENT_SELECTOR_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -#pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/OS_NS_dirent.h" /* Need ACE_SCANDIR_SELECTOR, COMPARATOR */ -#include "ace/os_include/os_dirent.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Dirent_Selector - * - * @brief Define a portable C++ directory-entry iterator based on the - * POSIX scandir API. - */ -class ACE_Export ACE_Dirent_Selector -{ -public: - /// Constructor - ACE_Dirent_Selector (void); - - /// Destructor. - virtual ~ACE_Dirent_Selector (void); - - /// Return the length of the list of matching directory entries. - int length (void) const; - - /// Return the entry at @a index. - ACE_DIRENT *operator[] (const int index) const; - - /// Free up resources. - int close (void); - - /// Open the directory @a dir and populate the current list of names with - /// directory entries that match the @a selector and @a comparator. - int open (const ACE_TCHAR *dir, - ACE_SCANDIR_SELECTOR selector = 0, - ACE_SCANDIR_COMPARATOR comparator = 0); - -protected: - /// Ptr to the namelist array. - ACE_DIRENT **namelist_; - - /// Number of entries in the array. - int n_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Dirent_Selector.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_DIRENT_SELECTOR_H */ diff --git a/externals/ace/Dirent_Selector.inl b/externals/ace/Dirent_Selector.inl deleted file mode 100644 index 15f804704bf..00000000000 --- a/externals/ace/Dirent_Selector.inl +++ /dev/null @@ -1,19 +0,0 @@ -// -*- C++ -*- -// -// $Id: Dirent_Selector.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE int -ACE_Dirent_Selector::length (void) const -{ - return n_; -} - -ACE_INLINE ACE_DIRENT * -ACE_Dirent_Selector::operator[] (const int n) const -{ - return this->namelist_[n]; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Dump.cpp b/externals/ace/Dump.cpp deleted file mode 100644 index 6e5c2d0c3ea..00000000000 --- a/externals/ace/Dump.cpp +++ /dev/null @@ -1,141 +0,0 @@ -// $Id: Dump.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Dump.h" -#include "ace/Guard_T.h" -#include "ace/Thread_Mutex.h" -#include "ace/Object_Manager.h" -#include "ace/Log_Msg.h" - -ACE_RCSID(ace, Dump, "$Id: Dump.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Implementations (very simple for now...) - -ACE_Dumpable::~ACE_Dumpable (void) -{ - ACE_TRACE ("ACE_Dumpable::~ACE_Dumpable"); -} - -ACE_Dumpable::ACE_Dumpable (const void *this_ptr) - : this_ (this_ptr) -{ - ACE_TRACE ("ACE_Dumpable::ACE_Dumpable"); -} - -ACE_Dumpable_Ptr::ACE_Dumpable_Ptr (const ACE_Dumpable *dumper) - : dumper_ (dumper) -{ - ACE_TRACE ("ACE_Dumpable_Ptr::ACE_Dumpable_Ptr"); -} - -const ACE_Dumpable * -ACE_Dumpable_Ptr::operator->() const -{ - ACE_TRACE ("ACE_Dumpable_Ptr::operator->"); - return this->dumper_; -} - -void -ACE_Dumpable_Ptr::operator= (const ACE_Dumpable *dumper) const -{ - ACE_TRACE ("ACE_Dumpable_Ptr::operator="); - if (this->dumper_ != dumper) - { - delete const_cast (this->dumper_); - (const_cast (this))->dumper_ = dumper; - } -} - -ACE_ODB::ACE_ODB (void) - // Let the Tuple default constructor initialize object_table_ - : current_size_ (0) -{ - ACE_TRACE ("ACE_ODB::ACE_ODB"); -} - -ACE_ODB * -ACE_ODB::instance (void) -{ - ACE_TRACE ("ACE_ODB::instance"); - - if (ACE_ODB::instance_ == 0) - { - ACE_MT (ACE_Thread_Mutex *lock = - ACE_Managed_Object::get_preallocated_object - (ACE_Object_Manager::ACE_DUMP_LOCK); - ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, *lock, 0)); - - if (ACE_ODB::instance_ == 0) - ACE_NEW_RETURN (ACE_ODB::instance_, - ACE_ODB, - 0); - } - - return ACE_ODB::instance_; -} - -void -ACE_ODB::dump_objects (void) -{ - ACE_TRACE ("ACE_ODB::dump_objects"); - for (int i = 0; i < this->current_size_; i++) - { - if (this->object_table_[i].this_ != 0) - // Dump the state of the object. - this->object_table_[i].dumper_->dump (); - } -} - -// This method registers a new . It detects -// duplicates and simply overwrites them. - -void -ACE_ODB::register_object (const ACE_Dumpable *dumper) -{ - ACE_TRACE ("ACE_ODB::register_object"); - int i; - int slot = 0; - - for (i = 0; i < this->current_size_; i++) - { - if (this->object_table_[i].this_ == 0) - slot = i; - else if (this->object_table_[i].this_ == dumper->this_) - { - slot = i; - break; - } - } - - if (i == this->current_size_) - { - slot = this->current_size_++; - ACE_ASSERT (this->current_size_ < ACE_ODB::MAX_TABLE_SIZE); - } - this->object_table_[slot].this_ = dumper->this_; - this->object_table_[slot].dumper_ = dumper; -} - -void -ACE_ODB::remove_object (const void *this_ptr) -{ - ACE_TRACE ("ACE_ODB::remove_object"); - int i; - - for (i = 0; i < this->current_size_; i++) - { - if (this->object_table_[i].this_ == this_ptr) - break; - } - - if (i < this->current_size_) - { - this->object_table_[i].this_ = 0; - this->object_table_[i].dumper_ = 0; - } -} - -ACE_ODB *ACE_ODB::instance_ = 0; - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Dump.h b/externals/ace/Dump.h deleted file mode 100644 index 4ccd64adb95..00000000000 --- a/externals/ace/Dump.h +++ /dev/null @@ -1,172 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file Dump.h - * - * $Id: Dump.h 80826 2008-03-04 14:51:23Z wotte $ - * - * - * A prototype mechanism that allow all ACE objects to be registered - * with a central in-memory "database" that can dump the state of all - * live ACE objects (e.g., from within a debugger). - * - * The macros which allow easy registration and removal of objects to be - * dumped (ACE_REGISTER_OBJECT and ACE_REMOVE_OBJECT) are turned into - * no-ops by compiling with the ACE_NDEBUG macro defined. This allows - * usage to be removed in "release mode" builds without changing code. - * - * There are several interesting aspects to this design: - * - * 1. It uses the External Polymorphism pattern to avoid having to - * derive all ACE classes from a common base class that has virtual - * methods (this is crucial to avoid unnecessary overhead). In - * addition, there is no additional space added to ACE objects - * (this is crucial to maintain binary layout compatibility). - * - * 2. This mechanism can be conditionally compiled in order to - * completely disable this feature entirely. Moreover, by - * using macros there are relatively few changes to ACE code. - * - * 3. This mechanism copes with single-inheritance hierarchies of - * dumpable classes. In such cases we typically want only one - * dump, corresponding to the most derived instance. Thanks to - * Christian Millour (chris@etca.fr) for illustrating how to do - * this. Note, however, that this scheme doesn't generalize to - * work with multiple-inheritance or virtual base classes. - * - * Future work includes: - * - * 1. Using a dynamic object table rather than a static table - * - * 2. Adding support to allow particular classes of objects to - * be selectively dumped. - * - * - * @author Doug Schmidt - */ -//============================================================================= - - -#ifndef ACE_DUMP_H -#define ACE_DUMP_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Dumpable - * - * @brief Base class that defines a uniform interface for all object - * dumping. - */ -class ACE_Export ACE_Dumpable -{ -public: - friend class ACE_ODB; - friend class ACE_Dumpable_Ptr; - - /// Constructor. - ACE_Dumpable (const void *); - - /// This pure virtual method must be filled in by a subclass. - virtual void dump (void) const = 0; - -protected: - virtual ~ACE_Dumpable (void); - -private: - /// Pointer to the object that is being stored. - const void *this_; -}; - -/** - * @class ACE_Dumpable_Ptr - * - * @brief A smart pointer stored in the in-memory object database - * ACE_ODB. The pointee (if any) is deleted when reassigned. - */ -class ACE_Export ACE_Dumpable_Ptr -{ -public: - ACE_Dumpable_Ptr (const ACE_Dumpable *dumper = 0); - const ACE_Dumpable *operator->() const; - void operator= (const ACE_Dumpable *dumper) const; - -private: - /// "Real" pointer to the underlying abstract base class - /// pointer that does the real work. - const ACE_Dumpable *dumper_; -}; - -/** - * @class ACE_ODB - * - * @brief This is the object database (ODB) that keeps track of all - * live ACE objects. - */ -class ACE_Export ACE_ODB -{ -public: - /// @todo This is clearly inadequate and should be dynamic... - enum {MAX_TABLE_SIZE = 100000}; - - /// Iterates through the entire set of registered objects and - /// dumps their state. - void dump_objects (void); - - /// Add the tuple to the list of registered ACE objects. - void register_object (const ACE_Dumpable *dumper); - - /// Use to locate and remove the associated from the - /// list of registered ACE objects. - void remove_object (const void *this_); - - /// Interface to the Singleton instance of the object database. - static ACE_ODB *instance (void); - -private: - ACE_ODB (void); // Ensure we have a Singleton... - - struct Tuple - { - /// Pointer to the object that is registered. - const void *this_; - - /// Smart pointer to the ACE_Dumpable object associated with this_. - /// This uses an ACE_Dumpable_Ptr, instead of a bare pointer, to - /// cope with hierarchies of dumpable classes. In such cases we - /// typically want only one dump, corresponding to the most derived - /// instance. To achieve this, the handle registered for the - /// subobject corresponding to the base class is destroyed (hence - /// on destruction of the subobject its handle won't exist anymore - /// and we'll have to check for that). - const ACE_Dumpable_Ptr dumper_; - - Tuple (void) : dumper_(0) {} - }; - - /// Singleton instance of this class. - static ACE_ODB *instance_; - - /// The current implementation is very simple-minded and will be - /// changed to be dynamic. - Tuple object_table_[ACE_ODB::MAX_TABLE_SIZE]; - - /// Current size of . - int current_size_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -// Include the templates classes at this point. -#include "ace/Dump_T.h" - -#include /**/ "ace/post.h" -#endif /* ACE_DUMP_H */ diff --git a/externals/ace/Dump_T.cpp b/externals/ace/Dump_T.cpp deleted file mode 100644 index da2b62a6fa3..00000000000 --- a/externals/ace/Dump_T.cpp +++ /dev/null @@ -1,48 +0,0 @@ -// Dump_T.cpp -// -// $Id: Dump_T.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#ifndef ACE_DUMP_T_CPP -#define ACE_DUMP_T_CPP - -#include "ace/Dump_T.h" -#include "ace/Global_Macros.h" -#include "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template -ACE_Dumpable_Adapter::~ACE_Dumpable_Adapter (void) -{ - ACE_TRACE ("ACE_Dumpable_Adapter::~ACE_Dumpable_Adapter"); -} - -template -ACE_Dumpable_Adapter::ACE_Dumpable_Adapter (const Concrete *t) - : ACE_Dumpable ((const void *) t), this_ (t) -{ - ACE_TRACE ("ACE_Dumpable_Adapter::ACE_Dumpable_Adapter"); -} - -template Concrete * -ACE_Dumpable_Adapter::operator->() const -{ - return (Concrete *) this->this_; -} - -template void -ACE_Dumpable_Adapter::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Dumpable_Adapter::dump"); - this->this_->dump (); -#endif /* ACE_HAS_DUMP */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_DUMP_T_CPP */ diff --git a/externals/ace/Dump_T.h b/externals/ace/Dump_T.h deleted file mode 100644 index 4186cabf937..00000000000 --- a/externals/ace/Dump_T.h +++ /dev/null @@ -1,83 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Dump_T.h - * - * $Id: Dump_T.h 91064 2010-07-12 10:11:24Z johnnyw $ - * - * @author Doug Schmidt - */ -//============================================================================= - - -#ifndef ACE_DUMP_T_H -#define ACE_DUMP_T_H -#include /**/ "ace/pre.h" - -#include "ace/Dump.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Dumpable_Adapter - * - * @brief - * This class inherits the interface of the abstract ACE_Dumpable - * class and is instantiated with the implementation of the - * concrete component class . - * - * This design is similar to the Adapter and Decorator patterns - * from the ``Gang of Four'' book. Note that - * need not inherit from a common class since ACE_Dumpable - * provides the uniform virtual interface! - */ -template -class ACE_Dumpable_Adapter : public ACE_Dumpable -{ -public: - // = Initialization and termination methods. - ACE_Dumpable_Adapter (const Concrete *t); - ~ACE_Dumpable_Adapter (void); - - /// Concrete dump method (simply delegates to the method of - /// ). - virtual void dump (void) const; - - /// Delegate to methods in the Concrete class. - Concrete *operator->() const; - -private: - /// Pointer to @c this of . - const Concrete *this_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -// Some useful macros for conditionally compiling this feature... -#if defined (ACE_NDEBUG) -#define ACE_REGISTER_OBJECT(CLASS) -#define ACE_REMOVE_OBJECT -#else -#define ACE_REGISTER_OBJECT(CLASS) \ - ACE_ODB::instance ()->register_object \ - (new ACE_Dumpable_Adapter (this)); -#define ACE_REMOVE_OBJECT \ - ACE_ODB::instance ()->remove_object \ - ((void *) this); -#endif /* ACE_NDEBUG */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Dump_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Dump_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" -#endif /* ACE_DUMP_T_H */ diff --git a/externals/ace/Dynamic.cpp b/externals/ace/Dynamic.cpp deleted file mode 100644 index 4eaedad0cfe..00000000000 --- a/externals/ace/Dynamic.cpp +++ /dev/null @@ -1,34 +0,0 @@ -// $Id: Dynamic.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Dynamic.h" -#include "ace/Singleton.h" -#include "ace/TSS_T.h" -#include "ace/Synch_Traits.h" -#include "ace/Null_Mutex.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Dynamic.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID(ace, Dynamic, "$Id: Dynamic.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_Dynamic::ACE_Dynamic (void) - : is_dynamic_ (false) -{ - ACE_TRACE ("ACE_Dynamic::ACE_Dynamic"); -} - -/* static */ ACE_Dynamic * -ACE_Dynamic::instance (void) -{ - return ACE_TSS_Singleton::instance (); -} - -#if defined (ACE_HAS_EXPLICIT_STATIC_TEMPLATE_MEMBER_INSTANTIATION) -template ACE_TSS_Singleton * - ACE_TSS_Singleton::singleton_; -#endif /* ACE_HAS_EXPLICIT_STATIC_TEMPLATE_MEMBER_INSTANTIATION */ - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Dynamic.h b/externals/ace/Dynamic.h deleted file mode 100644 index 70dfcd8d90a..00000000000 --- a/externals/ace/Dynamic.h +++ /dev/null @@ -1,75 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file Dynamic.h - * - * $Id: Dynamic.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Doug Schmidt - * @author Irfan Pyarali. - */ -//========================================================================== - -#ifndef ACE_DYNAMIC_H -#define ACE_DYNAMIC_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Dynamic - * - * @brief Checks to see if an object was dynamically allocated. - * - * This class holds the pointer in a thread-safe manner between - * the call to operator new and the call to the constructor. - */ -class ACE_Export ACE_Dynamic -{ -public: - // = Initialization and termination method. - /// Constructor. - ACE_Dynamic (void); - - /// Destructor. - ~ACE_Dynamic (void); - - /** - * Sets a flag that indicates that the object was dynamically - * created. This method is usually called in operator new and then - * checked and reset in the constructor. - */ - void set (void); - - /// @c true if we were allocated dynamically, else @c false. - bool is_dynamic (void); - - /// Resets state flag. - void reset (void); - - static ACE_Dynamic *instance (void); - -private: - /** - * Flag that indicates that the object was dynamically created. This - * method is usually called in operator new and then checked and - * reset in the constructor. - */ - bool is_dynamic_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Dynamic.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_DYNAMIC_H */ diff --git a/externals/ace/Dynamic.inl b/externals/ace/Dynamic.inl deleted file mode 100644 index 1e8e968f898..00000000000 --- a/externals/ace/Dynamic.inl +++ /dev/null @@ -1,34 +0,0 @@ -// -*- C++ -*- -// -// $Id: Dynamic.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE -ACE_Dynamic::~ACE_Dynamic (void) -{ - // ACE_TRACE ("ACE_Dynamic::~ACE_Dynamic"); -} - -ACE_INLINE void -ACE_Dynamic::set (void) -{ - // ACE_TRACE ("ACE_Dynamic::set"); - this->is_dynamic_ = true; -} - -ACE_INLINE bool -ACE_Dynamic::is_dynamic (void) -{ - // ACE_TRACE ("ACE_Dynamic::is_dynamic"); - return this->is_dynamic_; -} - -ACE_INLINE void -ACE_Dynamic::reset (void) -{ - // ACE_TRACE ("ACE_Dynamic::reset"); - this->is_dynamic_ = false; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Dynamic_Message_Strategy.cpp b/externals/ace/Dynamic_Message_Strategy.cpp deleted file mode 100644 index bce5865a1e6..00000000000 --- a/externals/ace/Dynamic_Message_Strategy.cpp +++ /dev/null @@ -1,205 +0,0 @@ -#include "ace/Dynamic_Message_Strategy.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Dynamic_Message_Strategy.inl" -#endif /* __ACE_INLINE__ */ - -#include "ace/Guard_T.h" -#include "ace/Log_Msg.h" -#include "ace/Malloc_Base.h" -#include "ace/OS_NS_string.h" - -ACE_RCSID (ace, - Dynamic_Message_Strategy, - "$Id: Dynamic_Message_Strategy.cpp 84565 2009-02-23 08:20:39Z johnnyw $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// ctor - -ACE_Dynamic_Message_Strategy::ACE_Dynamic_Message_Strategy (unsigned long static_bit_field_mask, - unsigned long static_bit_field_shift, - unsigned long dynamic_priority_max, - unsigned long dynamic_priority_offset) - : static_bit_field_mask_ (static_bit_field_mask), - static_bit_field_shift_ (static_bit_field_shift), - dynamic_priority_max_ (dynamic_priority_max), - dynamic_priority_offset_ (dynamic_priority_offset), - max_late_ (0, dynamic_priority_offset - 1), - min_pending_ (0, dynamic_priority_offset), - pending_shift_ (0, dynamic_priority_max) -{ -} - -// dtor - -ACE_Dynamic_Message_Strategy::~ACE_Dynamic_Message_Strategy (void) -{ -} - -ACE_Dynamic_Message_Strategy::Priority_Status -ACE_Dynamic_Message_Strategy::priority_status (ACE_Message_Block & mb, - const ACE_Time_Value & tv) -{ - // default the message to have pending priority status - Priority_Status status = ACE_Dynamic_Message_Strategy::PENDING; - - // start with the passed absolute time as the message's priority, then - // call the polymorphic hook method to (at least partially) convert - // the absolute time and message attributes into the message's priority - ACE_Time_Value priority (tv); - convert_priority (priority, mb); - - // if the priority is negative, the message is pending - if (priority < ACE_Time_Value::zero) - { - // priority for pending messages must be shifted - // upward above the late priority range - priority += pending_shift_; - if (priority < min_pending_) - priority = min_pending_; - } - // otherwise, if the priority is greater than the maximum late - // priority value that can be represented, it is beyond late - else if (priority > max_late_) - { - // all messages that are beyond late are assigned lowest priority (zero) - mb.msg_priority (0); - return ACE_Dynamic_Message_Strategy::BEYOND_LATE; - } - // otherwise, the message is late, but its priority is correct - else - status = ACE_Dynamic_Message_Strategy::LATE; - - // use (fast) bitwise operators to isolate and replace - // the dynamic portion of the message's priority - mb.msg_priority((mb.msg_priority() & static_bit_field_mask_) | - ((priority.usec () + - ACE_ONE_SECOND_IN_USECS * (suseconds_t)(priority.sec())) << - static_bit_field_shift_)); - - // returns the priority status of the message - return status; -} - - -// Dump the state of the strategy. - -void -ACE_Dynamic_Message_Strategy::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Dynamic_Message_Strategy::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("static_bit_field_mask_ = %u\n") - ACE_TEXT ("static_bit_field_shift_ = %u\n") - ACE_TEXT ("dynamic_priority_max_ = %u\n") - ACE_TEXT ("dynamic_priority_offset_ = %u\n") - ACE_TEXT ("max_late_ = [%d sec, %d usec]\n") - ACE_TEXT ("min_pending_ = [%d sec, %d usec]\n") - ACE_TEXT ("pending_shift_ = [%d sec, %d usec]\n"), - this->static_bit_field_mask_, - this->static_bit_field_shift_, - this->dynamic_priority_max_, - this->dynamic_priority_offset_, - this->max_late_.sec (), - this->max_late_.usec (), - this->min_pending_.sec (), - this->min_pending_.usec (), - this->pending_shift_.sec (), - this->pending_shift_.usec ())); - - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -ACE_Deadline_Message_Strategy::ACE_Deadline_Message_Strategy (unsigned long static_bit_field_mask, - unsigned long static_bit_field_shift, - unsigned long dynamic_priority_max, - unsigned long dynamic_priority_offset) - : ACE_Dynamic_Message_Strategy (static_bit_field_mask, - static_bit_field_shift, - dynamic_priority_max, - dynamic_priority_offset) -{ -} - -ACE_Deadline_Message_Strategy::~ACE_Deadline_Message_Strategy (void) -{ -} - -void -ACE_Deadline_Message_Strategy::convert_priority (ACE_Time_Value & priority, - const ACE_Message_Block & mb) -{ - // Convert absolute time passed in tv to negative time - // to deadline of mb with respect to that absolute time. - priority -= mb.msg_deadline_time (); -} - // dynamic priority conversion function based on time to deadline - -void -ACE_Deadline_Message_Strategy::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Deadline_Message_Strategy::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("ACE_Dynamic_Message_Strategy base class:\n"))); - this->ACE_Dynamic_Message_Strategy::dump (); - - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nderived class: ACE_Deadline_Message_Strategy\n"))); - - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -ACE_Laxity_Message_Strategy::ACE_Laxity_Message_Strategy (unsigned long static_bit_field_mask, - unsigned long static_bit_field_shift, - unsigned long dynamic_priority_max, - unsigned long dynamic_priority_offset) - : ACE_Dynamic_Message_Strategy (static_bit_field_mask, - static_bit_field_shift, - dynamic_priority_max, - dynamic_priority_offset) -{ -} - -ACE_Laxity_Message_Strategy::~ACE_Laxity_Message_Strategy (void) -{ -} - -void -ACE_Laxity_Message_Strategy::convert_priority (ACE_Time_Value & priority, - const ACE_Message_Block & mb) -{ - // Convert absolute time passed in tv to negative - // laxity of mb with respect to that absolute time. - priority += mb.msg_execution_time (); - priority -= mb.msg_deadline_time (); -} - // dynamic priority conversion function based on laxity - -void -ACE_Laxity_Message_Strategy::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Laxity_Message_Strategy::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("ACE_Dynamic_Message_Strategy base class:\n"))); - this->ACE_Dynamic_Message_Strategy::dump (); - - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nderived class: ACE_Laxity_Message_Strategy\n"))); - - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - // Dump the state of the strategy. - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Dynamic_Message_Strategy.h b/externals/ace/Dynamic_Message_Strategy.h deleted file mode 100644 index 090ad3a8f82..00000000000 --- a/externals/ace/Dynamic_Message_Strategy.h +++ /dev/null @@ -1,217 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file Dynamic_Message_Strategy.h - * - * $Id: Dynamic_Message_Strategy.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Douglas C. Schmidt - */ -//========================================================================== - -#ifndef ACE_DYNAMIC_MESSAGE_STRATEGY_H -#define ACE_DYNAMIC_MESSAGE_STRATEGY_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Message_Block.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Dynamic_Message_Strategy - * - * @brief An abstract base class which provides dynamic priority - * evaluation methods for use by the ACE_Dynamic_Message_Queue - * class or any other class which needs to manage the priorities - * of a collection of ACE_Message_Blocks dynamically. - * - * Methods for deadline and laxity based priority evaluation are - * provided. These methods assume a specific partitioning of - * the message priority number into a higher order dynamic bit - * field and a lower order static priority bit field. The - * default partitioning assumes an unsigned dynamic message - * priority field of 22 bits and an unsigned static message - * priority field of 10 bits. This corresponds to the initial - * values of the static class members. To provide a different - * partitioning, assign a different set of values to the static - * class memebers before using the static member functions. - */ -class ACE_Export ACE_Dynamic_Message_Strategy -{ -public: - - // = Message priority status - - // Values are defined as bit flags so that status combinations may - // be specified easily. - - enum Priority_Status - { - /// Message can still make its deadline - PENDING = 0x01, - /// Message cannot make its deadline - LATE = 0x02, - /// Message is so late its priority is undefined - BEYOND_LATE = 0x04, - /// Mask to match any priority status - ANY_STATUS = 0x07 - }; - - /// Constructor. - ACE_Dynamic_Message_Strategy (unsigned long static_bit_field_mask, - unsigned long static_bit_field_shift, - unsigned long dynamic_priority_max, - unsigned long dynamic_priority_offset); - - /// Virtual destructor. - virtual ~ACE_Dynamic_Message_Strategy (void); - - /// Updates the message's priority and returns its priority status. - Priority_Status priority_status (ACE_Message_Block &mb, - const ACE_Time_Value &tv); - - /// Get static bit field mask. - unsigned long static_bit_field_mask (void) const; - - /// Set static bit field mask. - void static_bit_field_mask (unsigned long); - - /// Get left shift value to make room for static bit field. - unsigned long static_bit_field_shift (void) const; - - /// Set left shift value to make room for static bit field. - void static_bit_field_shift (unsigned long); - - /// Get maximum supported priority value. - unsigned long dynamic_priority_max (void) const; - - /// Set maximum supported priority value. - void dynamic_priority_max (unsigned long); - - /// Get offset to boundary between signed range and unsigned range. - unsigned long dynamic_priority_offset (void) const; - - /// Set offset to boundary between signed range and unsigned range. - void dynamic_priority_offset (unsigned long); - - /// Dump the state of the strategy. - virtual void dump (void) const; - -protected: - /// Hook method for dynamic priority conversion. - virtual void convert_priority (ACE_Time_Value &priority, - const ACE_Message_Block &mb) = 0; - - /// This is a bit mask with all ones in the static bit field. - unsigned long static_bit_field_mask_; - - /** - * This is a left shift value to make room for static bit field: - * this value should be the logarithm base 2 of - * (static_bit_field_mask_ + 1). - */ - unsigned long static_bit_field_shift_; - - /// Maximum supported priority value. - unsigned long dynamic_priority_max_; - - /// Offset to boundary between signed range and unsigned range. - unsigned long dynamic_priority_offset_; - - /// Maximum late time value that can be represented. - ACE_Time_Value max_late_; - - /// Minimum pending time value that can be represented. - ACE_Time_Value min_pending_; - - /// Time value by which to shift pending priority. - ACE_Time_Value pending_shift_; -}; - -/** - * @class ACE_Deadline_Message_Strategy - * - * @brief Deadline based message priority strategy. - * - * Assigns dynamic message priority according to time to deadline. The - * message priority is divided into high and low order bit fields. The - * high order bit field is used for dynamic message priority, which is - * updated whenever the convert_priority() method is called. The - * low order bit field is used for static message priority and is left - * unchanged. The partitioning of the priority value into high and low - * order bit fields is done according to the arguments passed to the - * strategy object's constructor. - */ -class ACE_Export ACE_Deadline_Message_Strategy : public ACE_Dynamic_Message_Strategy -{ -public: - /// Ctor, with all arguments defaulted. - ACE_Deadline_Message_Strategy (unsigned long static_bit_field_mask = 0x3FFUL, // 2^(10) - 1 - unsigned long static_bit_field_shift = 10, // 10 low order bits - unsigned long dynamic_priority_max = 0x3FFFFFUL, // 2^(22)-1 - unsigned long dynamic_priority_offset = 0x200000UL); // 2^(22-1) - - /// Virtual dtor. - virtual ~ACE_Deadline_Message_Strategy (void); - - /// Dynamic priority conversion function based on time to deadline. - virtual void convert_priority (ACE_Time_Value &priority, - const ACE_Message_Block &mb); - - /// Dump the state of the strategy. - virtual void dump (void) const; -}; - -/** - * @class ACE_Laxity_Message_Strategy - * - * @brief Laxity based message priority strategy. - * - * Assigns dynamic message priority according to laxity (time to - * deadline minus worst case execution time). The message priority is - * divided into high and low order bit fields. The high order - * bit field is used for dynamic message priority, which is - * updated whenever the convert_priority() method is called. The - * low order bit field is used for static message priority and is left - * unchanged. The partitioning of the priority value into high and low - * order bit fields is done according to the arguments passed to the - * strategy object's constructor. - */ -class ACE_Export ACE_Laxity_Message_Strategy : public ACE_Dynamic_Message_Strategy -{ -public: - /// Ctor, with all arguments defaulted. - ACE_Laxity_Message_Strategy (unsigned long static_bit_field_mask = 0x3FFUL, // 2^(10) - 1 - unsigned long static_bit_field_shift = 10, // 10 low order bits - unsigned long dynamic_priority_max = 0x3FFFFFUL, // 2^(22)-1 - unsigned long dynamic_priority_offset = 0x200000UL); // 2^(22-1) - - /// virtual dtor. - virtual ~ACE_Laxity_Message_Strategy (void); - - /// Dynamic priority conversion function based on laxity. - virtual void convert_priority (ACE_Time_Value &priority, - const ACE_Message_Block &mb); - - /// Dump the state of the strategy. - virtual void dump (void) const; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Dynamic_Message_Strategy.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" - -#endif /* ACE_DYNAMIC_MESSAGE_STRATEGY_H */ diff --git a/externals/ace/Dynamic_Message_Strategy.inl b/externals/ace/Dynamic_Message_Strategy.inl deleted file mode 100644 index 9742a07fd88..00000000000 --- a/externals/ace/Dynamic_Message_Strategy.inl +++ /dev/null @@ -1,75 +0,0 @@ -// -*- C++ -*- -// -// $Id: Dynamic_Message_Strategy.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE unsigned long -ACE_Dynamic_Message_Strategy::static_bit_field_mask (void) const -{ - return static_bit_field_mask_; -} - // get static bit field mask - -ACE_INLINE void -ACE_Dynamic_Message_Strategy::static_bit_field_mask (unsigned long ul) -{ - static_bit_field_mask_ = ul; -} - // set static bit field mask - -ACE_INLINE unsigned long -ACE_Dynamic_Message_Strategy::static_bit_field_shift (void) const -{ - return static_bit_field_shift_; -} - // get left shift value to make room for static bit field - -ACE_INLINE void -ACE_Dynamic_Message_Strategy::static_bit_field_shift (unsigned long ul) -{ - static_bit_field_shift_ = ul; -} - // set left shift value to make room for static bit field - -ACE_INLINE unsigned long -ACE_Dynamic_Message_Strategy::dynamic_priority_max (void) const -{ - return dynamic_priority_max_; -} - // get maximum supported priority value - -ACE_INLINE void -ACE_Dynamic_Message_Strategy::dynamic_priority_max (unsigned long ul) -{ - // pending_shift_ depends on dynamic_priority_max_: for performance - // reasons, the value in pending_shift_ is (re)calculated only when - // dynamic_priority_max_ is initialized or changes, and is stored - // as a class member rather than being a derived value. - dynamic_priority_max_ = ul; - pending_shift_ = ACE_Time_Value (0, ul); -} - // set maximum supported priority value - -ACE_INLINE unsigned long -ACE_Dynamic_Message_Strategy::dynamic_priority_offset (void) const -{ - return dynamic_priority_offset_; -} - // get offset for boundary between signed range and unsigned range - -ACE_INLINE void -ACE_Dynamic_Message_Strategy::dynamic_priority_offset (unsigned long ul) -{ - // max_late_ and min_pending_ depend on dynamic_priority_offset_: - // for performance reasons, the values in max_late_ and min_pending_ - // are (re)calculated only when dynamic_priority_offset_ is - // initialized or changes, and are stored as a class member rather - // than being derived each time one of their values is needed. - dynamic_priority_offset_ = ul; - max_late_ = ACE_Time_Value (0, ul - 1); - min_pending_ = ACE_Time_Value (0, ul); -} - // set offset for boundary between signed range and unsigned range - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Dynamic_Service.cpp b/externals/ace/Dynamic_Service.cpp deleted file mode 100644 index 28d6e4526f2..00000000000 --- a/externals/ace/Dynamic_Service.cpp +++ /dev/null @@ -1,63 +0,0 @@ -// $Id: Dynamic_Service.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#ifndef ACE_DYNAMIC_SERVICE_CPP -#define ACE_DYNAMIC_SERVICE_CPP - -#include "ace/Dynamic_Service.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Service_Object.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Dynamic_Service.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - - -template TYPE * -ACE_Dynamic_Service::instance (const ACE_TCHAR *name) -{ - ACE_Service_Object * svc_obj = - static_cast - (ACE_Dynamic_Service_Base::instance (name,false)); - return dynamic_cast (svc_obj); -} - -template TYPE * -ACE_Dynamic_Service::instance (const ACE_TCHAR *name, - bool no_global) -{ - ACE_Service_Object * svc_obj = - static_cast - (ACE_Dynamic_Service_Base::instance (name, no_global)); - return dynamic_cast (svc_obj); -} - -template TYPE * -ACE_Dynamic_Service::instance (const ACE_Service_Gestalt* conf, - const ACE_TCHAR *name) -{ - ACE_Service_Object * svc_obj = - static_cast - (ACE_Dynamic_Service_Base::instance (conf, name, false)); - return dynamic_cast (svc_obj); -} - -template TYPE * -ACE_Dynamic_Service::instance (const ACE_Service_Gestalt* conf, - const ACE_TCHAR *name, - bool no_global) -{ - ACE_Service_Object * svc_obj = - static_cast - (ACE_Dynamic_Service_Base::instance (conf, name, no_global)); - return dynamic_cast (svc_obj); -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_DYNAMIC_SERVICE_CPP */ diff --git a/externals/ace/Dynamic_Service.h b/externals/ace/Dynamic_Service.h deleted file mode 100644 index b90095c766d..00000000000 --- a/externals/ace/Dynamic_Service.h +++ /dev/null @@ -1,89 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Dynamic_Service.h - * - * $Id: Dynamic_Service.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Prashant Jain - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_DYNAMIC_SERVICE_H -#define ACE_DYNAMIC_SERVICE_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" -#include "ace/Global_Macros.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Dynamic_Service_Base.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -class ACE_Service_Object; - -/** - * @class ACE_Dynamic_Service - * - * @brief Provides a general interface to retrieve arbitrary objects - * from the ACE service repository. - * - * Uses "name" for lookup in the ACE service repository. Obtains - * the object and returns it as the appropriate type. - */ -template -class ACE_Dynamic_Service : public ACE_Dynamic_Service_Base -{ -public: - /// Return instance using @a name to search the Service_Repository. - static TYPE* instance (const ACE_TCHAR *name); - static TYPE* instance (const ACE_TCHAR *name, bool no_global); - - static TYPE* instance (const ACE_Service_Gestalt* repo, - const ACE_TCHAR *name); - static TYPE* instance (const ACE_Service_Gestalt* repo, - const ACE_TCHAR *name, bool no_global); - -#if defined (ACE_USES_WCHAR) - - /// Return instance using @a name to search the Service_Repository. - static TYPE* instance (const ACE_ANTI_TCHAR *name); - - static TYPE* instance (const ACE_ANTI_TCHAR *name, bool no_global); - - static TYPE* instance (const ACE_Service_Gestalt* repo, - const ACE_ANTI_TCHAR *name); - static TYPE* instance (const ACE_Service_Gestalt* repo, - const ACE_ANTI_TCHAR *name, bool no_global); -#endif // ACE_USES_WCHAR - -private: - ACE_UNIMPLEMENTED_FUNC (ACE_Dynamic_Service ()) - ACE_UNIMPLEMENTED_FUNC (ACE_Dynamic_Service (const ACE_Dynamic_Service&)) - ACE_UNIMPLEMENTED_FUNC (ACE_Dynamic_Service& operator= (const ACE_Dynamic_Service&)) -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Dynamic_Service.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -# include "ace/Dynamic_Service.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -# pragma implementation ("Dynamic_Service.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" - -#endif /* ACE_DYNAMIC_SERVICE_H */ diff --git a/externals/ace/Dynamic_Service.inl b/externals/ace/Dynamic_Service.inl deleted file mode 100644 index 31324bf535b..00000000000 --- a/externals/ace/Dynamic_Service.inl +++ /dev/null @@ -1,39 +0,0 @@ -// -*- C++ -*- -// -// $Id: Dynamic_Service.inl 81318 2008-04-10 10:12:05Z johnnyw $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -#if defined (ACE_USES_WCHAR) - -template ACE_INLINE TYPE * -ACE_Dynamic_Service::instance (const ACE_ANTI_TCHAR *name) -{ - return instance (ACE_TEXT_CHAR_TO_TCHAR (name),false); -} - -template ACE_INLINE TYPE * -ACE_Dynamic_Service::instance (const ACE_ANTI_TCHAR *name, - bool no_global) -{ - return instance (ACE_TEXT_CHAR_TO_TCHAR (name),no_global); -} - -template ACE_INLINE TYPE * -ACE_Dynamic_Service::instance (const ACE_Service_Gestalt* repo, - const ACE_ANTI_TCHAR *name) -{ - return instance (repo, ACE_TEXT_CHAR_TO_TCHAR (name),false); -} - -template ACE_INLINE TYPE * -ACE_Dynamic_Service::instance (const ACE_Service_Gestalt* repo, - const ACE_ANTI_TCHAR *name, - bool no_global) -{ - return instance (repo, ACE_TEXT_CHAR_TO_TCHAR (name),no_global); -} - -#endif // ACE_USES_WCHAR - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Dynamic_Service_Base.cpp b/externals/ace/Dynamic_Service_Base.cpp deleted file mode 100644 index ecefcf17207..00000000000 --- a/externals/ace/Dynamic_Service_Base.cpp +++ /dev/null @@ -1,106 +0,0 @@ -#include "ace/Dynamic_Service_Base.h" -#include "ace/ACE.h" -#include "ace/Service_Config.h" -#include "ace/Service_Repository.h" -#include "ace/Service_Types.h" -#include "ace/Log_Msg.h" - - -ACE_RCSID (ace, - Dynamic_Service_Base, - "$Id: Dynamic_Service_Base.cpp 84282 2009-01-30 15:04:29Z msmit $") - - ACE_BEGIN_VERSIONED_NAMESPACE_DECL - - -void -ACE_Dynamic_Service_Base::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Dynamic_Service_Base::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n"))); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -// Get the instance using for the current global -// service configuration repository. - -void * -ACE_Dynamic_Service_Base::instance (const ACE_TCHAR *name, bool no_global) -{ - ACE_TRACE ("ACE_Dynamic_Service_Base::instance"); - return instance (ACE_Service_Config::current (), name, no_global); -} - -// Find a service registration - -const ACE_Service_Type * -ACE_Dynamic_Service_Base::find_i (const ACE_Service_Gestalt* &repo, - const ACE_TCHAR *name, - bool no_global) -{ - ACE_TRACE ("ACE_Dynamic_Service_Base::find_i"); - const ACE_Service_Type *svc_rec = 0; - - ACE_Service_Gestalt* global = ACE_Service_Config::global (); - - for ( ; (repo->find (name, &svc_rec) == -1) && !no_global; repo = global) - { - // Check the static repo, too if different - if (repo == global) - break; - } - - return svc_rec; -} - - -// Get the instance using for specific configuration repository. -void * -ACE_Dynamic_Service_Base::instance (const ACE_Service_Gestalt* repo, - const ACE_TCHAR *name, - bool no_global) -{ - ACE_TRACE ("ACE_Dynamic_Service_Base::instance"); - - void *obj = 0; - const ACE_Service_Type_Impl *type = 0; - - const ACE_Service_Gestalt* repo_found = repo; - const ACE_Service_Type *svc_rec = find_i (repo_found, name, no_global); - if (svc_rec != 0) - { - type = svc_rec->type (); - if (type != 0) - obj = type->object (); - } - - if (ACE::debug ()) - { - ACE_Guard log_guard (*ACE_Log_Msg::instance ()); - - if (repo->repo_ != repo_found->repo_) - { - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) DSB::instance, repo=%@, name=%s") - ACE_TEXT (" type=%@ => %@") - ACE_TEXT (" [in repo=%@]\n"), - repo->repo_, name, type, obj, - repo_found->repo_)); - } - else - { - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) DSB::instance, repo=%@, name=%s") - ACE_TEXT (" type=%@ => %@\n"), - repo->repo_, name, type, obj)); - } - } - - return obj; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Dynamic_Service_Base.h b/externals/ace/Dynamic_Service_Base.h deleted file mode 100644 index 31fdadaa152..00000000000 --- a/externals/ace/Dynamic_Service_Base.h +++ /dev/null @@ -1,73 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file Dynamic_Service_Base.h - * - * $Id: Dynamic_Service_Base.h 89454 2010-03-11 09:35:25Z johnnyw $ - * - * @author Prashant Jain - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_DYNAMIC_SERVICE_BASE_H -#define ACE_DYNAMIC_SERVICE_BASE_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -class ACE_Service_Gestalt; -class ACE_Service_Type; - -/** - * @class ACE_Dynamic_Service_Base - * - * @brief Base class for all ACE_Dynamic_Service instantiations. - * - * Factors out common code shared by all ACE_Dynamic_Service - * instantiations, this avoid code bloat. - */ -class ACE_Export ACE_Dynamic_Service_Base -{ -public: - /// Dump the current static of the object - void dump (void) const; - -protected: - /// Perform the default repo search, but optionally skip searching the global - /// repo. - static void* instance (const ACE_TCHAR *name, bool no_global = false); - - static void* instance (const ACE_Service_Gestalt* repo, - const ACE_TCHAR *name, - bool no_global = false); - - /// No need to create, or assign instances of this class - ACE_Dynamic_Service_Base (void); - ~ACE_Dynamic_Service_Base (void); - const ACE_Dynamic_Service_Base& operator= (const ACE_Dynamic_Service_Base&); - -private: - /// Implement the service search policy, i.e. "look for the service first - /// locally and then globally" - static const ACE_Service_Type *find_i (const ACE_Service_Gestalt* &repo, - const ACE_TCHAR *name, - bool no_global); - - /// The dependency declaration class needs access to the service search - /// policy, implemented by find_i() - friend class ACE_Dynamic_Service_Dependency; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" -#endif /* ACE_DYNAMIC_SERVICE_BASE_H */ diff --git a/externals/ace/Dynamic_Service_Dependency.cpp b/externals/ace/Dynamic_Service_Dependency.cpp deleted file mode 100644 index df7cd0f5d48..00000000000 --- a/externals/ace/Dynamic_Service_Dependency.cpp +++ /dev/null @@ -1,51 +0,0 @@ -#include "ace/ACE.h" -#include "ace/DLL_Manager.h" -#include "ace/Dynamic_Service_Dependency.h" -#include "ace/Service_Config.h" -#include "ace/Log_Msg.h" - -ACE_RCSID (ace, - Dynamic_Service_Dependency, - "$Id: Dynamic_Service_Dependency.cpp 80826 2008-03-04 14:51:23Z wotte $") - - - ACE_BEGIN_VERSIONED_NAMESPACE_DECL - - -ACE_Dynamic_Service_Dependency::ACE_Dynamic_Service_Dependency (const ACE_TCHAR *principal) -{ - this->init (ACE_Service_Config::current (), principal); -} - -ACE_Dynamic_Service_Dependency::ACE_Dynamic_Service_Dependency (const ACE_Service_Gestalt *cfg, - const ACE_TCHAR *principal) -{ - this->init (cfg, principal); -} - - -ACE_Dynamic_Service_Dependency::~ACE_Dynamic_Service_Dependency (void) -{ - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("(%P|%t) DSD, this=%@ - destroying\n"), - this)); -} - -void -ACE_Dynamic_Service_Dependency::init (const ACE_Service_Gestalt *cfg, - const ACE_TCHAR *principal) -{ - const ACE_Service_Type* st = - ACE_Dynamic_Service_Base::find_i (cfg, principal,false); - if (ACE::debug ()) - { - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("(%P|%t) DSD, this=%@ - creating dependency on "), this)); - st->dump (); - } - this->tracker_ = st->dll (); -} - - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Dynamic_Service_Dependency.h b/externals/ace/Dynamic_Service_Dependency.h deleted file mode 100644 index 0f187d0037a..00000000000 --- a/externals/ace/Dynamic_Service_Dependency.h +++ /dev/null @@ -1,70 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Dynamic_Service_Dependency.h - * - * $Id: Dynamic_Service_Dependency.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Iliyan Jeliazkov - */ -//============================================================================= - -#ifndef ACE_DYNAMIC_SERVICE_DEPENDENCY_H -#define ACE_DYNAMIC_SERVICE_DEPENDENCY_H - -#include /**/ "ace/pre.h" - - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Dynamic_Service_Base.h" -#include "ace/Service_Object.h" -#include "ace/DLL.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Dynamic_Service_Dependency - * - * @brief Provides a way to declare dependency on specific service, - * thus helping to avoid order of initialization issues with instances - * of an objects whose implementation code resides in dynamically loaded - * services. - * - * It is disastrous to have dynamically loadable services create and give away - * ownership of objects and then ending up being unloaded before all those - * instances have been deleted. Normally the code for such objects classes - * resides within the TEXT segment of the DLL, which implements the service. - * If a service gets removed, its DLL may be unmapped from memory and then - * any attempt to invoke a method on the said objects will cause SEGV. - * - * Such instances must contain a member of ACE_Dynamic_Service_Dependency - * initialized with the service they depend on. - * ACE_Dynamic_Service_Dependency's constructor and destructor are - * "magical" - they work by maintaining the underlying dynamic service's - * DLL reference count. - */ -class ACE_Export ACE_Dynamic_Service_Dependency -{ -public: - ACE_Dynamic_Service_Dependency (const ACE_Service_Gestalt *cfg, - const ACE_TCHAR *principal); - ACE_Dynamic_Service_Dependency (const ACE_TCHAR *principal); - ~ACE_Dynamic_Service_Dependency (void); - -private: - void init (const ACE_Service_Gestalt *cfg, const ACE_TCHAR *principal); - -private: - ACE_DLL tracker_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - - -#include /**/ "ace/post.h" - -#endif /* ACE_DYNAMIC_SERVICE_DEPENDENCY_H */ diff --git a/externals/ace/Encoding_Converter.cpp b/externals/ace/Encoding_Converter.cpp deleted file mode 100644 index b5fd2b35402..00000000000 --- a/externals/ace/Encoding_Converter.cpp +++ /dev/null @@ -1,12 +0,0 @@ -// $Id: Encoding_Converter.cpp 80826 2008-03-04 14:51:23Z wotte $ -#include "ace/Encoding_Converter.h" - -#if defined (ACE_USES_WCHAR) -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_Encoding_Converter::~ACE_Encoding_Converter (void) -{ -} - -ACE_END_VERSIONED_NAMESPACE_DECL -#endif /* ACE_USES_WCHAR */ diff --git a/externals/ace/Encoding_Converter.h b/externals/ace/Encoding_Converter.h deleted file mode 100644 index 34d22fa29a1..00000000000 --- a/externals/ace/Encoding_Converter.h +++ /dev/null @@ -1,70 +0,0 @@ -// -*- C++ -*- - -//========================================================================= -/** - * @file Encoding_Converter.h - * - * $Id: Encoding_Converter.h 80826 2008-03-04 14:51:23Z wotte $ - * - * This class is the base class for all encoding converters that convert - * to and from UTF-8. - * - * @author Chad Elliott - */ -//========================================================================= - -#ifndef ACE_ENCODING_CONVERTER_H -#define ACE_ENCODING_CONVERTER_H - -#include /**/ "ace/pre.h" - -#include "ace/Basic_Types.h" - -#if defined (ACE_USES_WCHAR) -#include /**/ "ace/ACE_export.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** The base class for all ACE UTF Encoding Converters. - * This class provides a generic interface that is used to implement - * various UTF encoding conversion classes. - */ -class ACE_Export ACE_Encoding_Converter -{ -public: - /// This enum describes the various states that can be returned - /// from the to_utf8() and from_utf8() methods which depends on - /// both the source buffer and the size of the target buffer. - enum Result {CONVERSION_OK, - SOURCE_EXHAUSTED, - TARGET_EXHAUSTED, - SOURCE_ILLEGAL - }; - - /// This destructor is here (and virtual) because we have virtual - /// functions. - virtual ~ACE_Encoding_Converter (void); - - /// Convert the source (which can be in any encoding) to UTF-8 and - /// store it in the provided target buffer. - virtual Result to_utf8 (const void* source, - size_t source_size, - ACE_Byte* target, - size_t target_size, - bool strict = true) = 0; - - /// Convert the UTF-8 source into an alternate encoding and store it - /// in the provided target buffer. - virtual Result from_utf8 (const ACE_Byte* source, - size_t source_size, - void* target, - size_t target_size, - bool strict = true) = 0; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL -#endif /* ACE_USES_WCHAR */ - -#include /**/ "ace/post.h" - -#endif /* ACE_ENCODING_CONVERTER_H */ diff --git a/externals/ace/Encoding_Converter_Factory.cpp b/externals/ace/Encoding_Converter_Factory.cpp deleted file mode 100644 index f603ae3e893..00000000000 --- a/externals/ace/Encoding_Converter_Factory.cpp +++ /dev/null @@ -1,74 +0,0 @@ -// $Id: Encoding_Converter_Factory.cpp 80826 2008-03-04 14:51:23Z wotte $ -#include "ace/Encoding_Converter_Factory.h" - -#if defined (ACE_USES_WCHAR) -#include "ace/UTF32_Encoding_Converter.h" -#include "ace/UTF16_Encoding_Converter.h" -#include "ace/UTF8_Encoding_Converter.h" -#include "ace/OS_Memory.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_Encoding_Converter* -ACE_Encoding_Converter_Factory::create ( - const ACE_Byte* source, - size_t source_size, - ACE_Encoding_Converter_Factory::Encoding_Hint hint) -{ -#if defined (ACE_BIG_ENDIAN) - bool const convert_for_bigendian = true; -#else - bool const convert_for_bigendian = false; -#endif /* ACE_BIG_ENDIAN */ - ACE_Encoding_Converter* converter = 0; - - switch (hint) - { - case ACE_UTF_32BE: - ACE_NEW_RETURN (converter, - ACE_UTF32_Encoding_Converter (!convert_for_bigendian), - 0); - break; - case ACE_UTF_32LE: - ACE_NEW_RETURN (converter, - ACE_UTF32_Encoding_Converter (convert_for_bigendian), - 0); - break; - case ACE_UTF_16BE: - ACE_NEW_RETURN (converter, - ACE_UTF16_Encoding_Converter (!convert_for_bigendian), - 0); - break; - case ACE_UTF_16LE: - ACE_NEW_RETURN (converter, - ACE_UTF16_Encoding_Converter (convert_for_bigendian), - 0); - break; - case ACE_UTF_8: - ACE_NEW_RETURN (converter, - ACE_UTF8_Encoding_Converter, - 0); - break; - default: - // First check for ASCII since much of ASCII text will appear to - // convert from UTF-16 to UTF-8. - converter = ACE_UTF8_Encoding_Converter::encoded (source, source_size); - if (converter != 0) - return converter; - - // Check for UTF-32 - converter = ACE_UTF32_Encoding_Converter::encoded (source, source_size); - if (converter != 0) - return converter; - - // Check for UTF-16 - converter = ACE_UTF16_Encoding_Converter::encoded (source, source_size); - if (converter != 0) - return converter; - } - - return converter; -} - -ACE_END_VERSIONED_NAMESPACE_DECL -#endif /* ACE_USES_WCHAR */ diff --git a/externals/ace/Encoding_Converter_Factory.h b/externals/ace/Encoding_Converter_Factory.h deleted file mode 100644 index 1441c690bef..00000000000 --- a/externals/ace/Encoding_Converter_Factory.h +++ /dev/null @@ -1,54 +0,0 @@ -// -*- C++ -*- - -//========================================================================= -/** - * @file Encoding_Converter_Factory.h - * - * $Id: Encoding_Converter_Factory.h 80826 2008-03-04 14:51:23Z wotte $ - * - * This class can be used to create encoding converters of various types. - * - * @author Chad Elliott - */ -//========================================================================= - -#ifndef ACE_ENCODING_CONVERTER_FACTORY_H -#define ACE_ENCODING_CONVERTER_FACTORY_H - -#include /**/ "ace/pre.h" - -#include "ace/Basic_Types.h" - -#if defined (ACE_USES_WCHAR) -#include /**/ "ace/ACE_export.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -class ACE_Encoding_Converter; - -/** Create an encoding converter based on the source or hint. - * This class allows users to avoid knowing any concrete converter types. - */ -class ACE_Export ACE_Encoding_Converter_Factory -{ -public: - /// This enum is used to tell what type of converter to create. - enum Encoding_Hint { ACE_UTF_32BE, ACE_UTF_32LE, - ACE_UTF_16BE, ACE_UTF_16LE, - ACE_UTF_8, ACE_NONE - }; - - /// Create an encoding converter based on the source. If a hint is - /// given, it just creates the specified type of converter without looking - /// at the source. - static ACE_Encoding_Converter* create (const ACE_Byte* source, - size_t source_size, - Encoding_Hint hint = ACE_NONE); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL -#endif /* ACE_USES_WCHAR */ - -#include /**/ "ace/post.h" - -#endif /* ACE_ENCODING_CONVERTER_FACTORY_H */ diff --git a/externals/ace/Env_Value_T.cpp b/externals/ace/Env_Value_T.cpp deleted file mode 100644 index 1997bbea484..00000000000 --- a/externals/ace/Env_Value_T.cpp +++ /dev/null @@ -1,12 +0,0 @@ -// $Id: Env_Value_T.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#ifndef ACE_ENV_VALUE_T_CPP -#define ACE_ENV_VALUE_T_CPP - -#include "ace/Env_Value_T.h" - -#if ! defined (__ACE_INLINE__) -#include "ace/Env_Value_T.inl" -#endif /* __ACE_INLINE__ */ - -#endif /* ACE_ENV_VALUE_T_CPP */ diff --git a/externals/ace/Env_Value_T.h b/externals/ace/Env_Value_T.h deleted file mode 100644 index df2178a0f11..00000000000 --- a/externals/ace/Env_Value_T.h +++ /dev/null @@ -1,166 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Env_Value_T.h - * - * $Id: Env_Value_T.h 80826 2008-03-04 14:51:23Z wotte $ - * - * Template to encapsulate getting a value from an environment variable - * and using a supplied default value if not in the environment. - * - * - * @author Chris Cleeland (derived from work by Carlos O'Ryan) - */ -//============================================================================= - -#ifndef ACE_ENV_VALUE_T_H -#define ACE_ENV_VALUE_T_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" -#include "ace/Global_Macros.h" -#include "ace/OS_NS_stdlib.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Env_Value - * - * @brief Environment Variable Value - * - * Reads a variable from the user environment, providing a default - * value. - */ -template -class ACE_Env_Value -{ -public: - /** - * Default constructor which isn't bound to a specific environment - * variable name or a default value. Before being useful it must - * 'd. - */ - ACE_Env_Value (void); - - /// Constructor that calls . - ACE_Env_Value (const ACE_TCHAR *varname, - const T &vardefault); - - /// Destroy the value. - ~ACE_Env_Value (void); - - /// Returns the value as type T. - operator T (void); - - /// The constructor, read @a varname from the environment, using - /// @a defval as its value if it is not defined. - void open (const ACE_TCHAR *varname, const T &defval); - - /// Returns the name of the variable being tracked. - const ACE_TCHAR *varname (void) const; - -private: - /// Disallow copying and assignment. - ACE_UNIMPLEMENTED_FUNC (ACE_Env_Value(const ACE_Env_Value &)) - ACE_UNIMPLEMENTED_FUNC (ACE_Env_Value operator=(const ACE_Env_Value &)) - - void fetch_value (void); - - const ACE_TCHAR *varname_; - T value_; -}; - -/// Function to convert a string @a s into type @c T. -template void ACE_Convert (const ACE_TCHAR *s, T &t); - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Env_Value_T.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Env_Value_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template <> inline void -ACE_Convert (const ACE_TCHAR *s, ACE_TCHAR *&v) -{ - v = (ACE_TCHAR *) s; -} - -template <> inline void -ACE_Convert (const ACE_TCHAR *s, const ACE_TCHAR *&v) -{ - v = (const ACE_TCHAR *) s; -} - -template <> inline void -ACE_Convert (const ACE_TCHAR *s, short &si) -{ - si = static_cast (ACE_OS::strtol (s, 0, 10)); -} - -template <> inline void -ACE_Convert (const ACE_TCHAR *s, u_short &us) -{ - us = static_cast (ACE_OS::strtol (s, 0, 10)); -} - -template <> inline void -ACE_Convert (const ACE_TCHAR *s, u_int &i) -{ - i = static_cast (ACE_OS::strtol (s, 0, 10)); -} - -template <> inline void -ACE_Convert (const ACE_TCHAR *s, long &l) -{ - l = ACE_OS::strtol (s, 0, 10); -} - -template <> inline void -ACE_Convert (const ACE_TCHAR *s, int &i) -{ - i = static_cast (ACE_OS::strtol (s, 0, 10)); -} - -template <> inline void -ACE_Convert (const ACE_TCHAR *s, u_long &ul) -{ - ul = ACE_OS::strtoul (s, 0, 10); -} - -template <> inline void -ACE_Convert (const ACE_TCHAR *s, double &d) -{ - d = ACE_OS::strtod (s, 0); -} - -// Default calls a CTOR on type T of the form 'T::T(const char*)', but -// users can feel free to create their own specialized conversion -// functions if necessary, as shown above. Note that for 'char*' the -// default is used because a simple cast will be performed and no -// conversion will be necessary. -template inline void -ACE_Convert (const ACE_TCHAR *s, T &t) -{ - t = T (s); -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Env_Value_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" -#endif /* ACE_ENV_VALUE_T_H */ diff --git a/externals/ace/Env_Value_T.inl b/externals/ace/Env_Value_T.inl deleted file mode 100644 index d9af1b03164..00000000000 --- a/externals/ace/Env_Value_T.inl +++ /dev/null @@ -1,60 +0,0 @@ -// $Id: Env_Value_T.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template ACE_INLINE -ACE_Env_Value::operator T (void) -{ - return value_; -} - -template ACE_INLINE -ACE_Env_Value::ACE_Env_Value (void) - : varname_ (0) -{ -} - -template ACE_INLINE -ACE_Env_Value::ACE_Env_Value (const ACE_TCHAR *varname, - const T &defval) - : varname_ (varname), - value_(defval) -{ - this->fetch_value (); -} - -template ACE_INLINE void -ACE_Env_Value::open (const ACE_TCHAR *varname, - const T &defval) -{ - this->varname_ = varname; - this->value_ = defval; - this->fetch_value (); -} - -template ACE_INLINE void -ACE_Env_Value::fetch_value (void) -{ -#if defined (ACE_WIN32) - const ACE_TCHAR *env = ACE_OS::getenv (this->varname_); - if (env != 0) - ACE_Convert (env, value_); -#else - char *nenv = ACE_OS::getenv (ACE_TEXT_ALWAYS_CHAR (this->varname_)); - if (nenv != 0) - ACE_Convert (ACE_TEXT_CHAR_TO_TCHAR (nenv), this->value_); -#endif -} - -template ACE_INLINE const ACE_TCHAR* -ACE_Env_Value::varname (void) const -{ - return this->varname_; -} - -template ACE_INLINE -ACE_Env_Value::~ACE_Env_Value (void) -{ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Event.cpp b/externals/ace/Event.cpp deleted file mode 100644 index ea5f86d99d1..00000000000 --- a/externals/ace/Event.cpp +++ /dev/null @@ -1,93 +0,0 @@ -// $Id: Event.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Event.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Event.inl" -#endif /* __ACE_INLINE__ */ - -#include "ace/Log_Msg.h" - -ACE_RCSID(ace, Event, "$Id: Event.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_Event::ACE_Event (int manual_reset, - int initial_state, - int type, - const ACE_TCHAR *name, - void *arg, - LPSECURITY_ATTRIBUTES sa) - : removed_ (false) -{ - if (ACE_OS::event_init (&this->handle_, - manual_reset, - initial_state, - type, - name, - arg, - sa) != 0) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_Event::ACE_Event"))); -} - -ACE_Event::~ACE_Event (void) -{ - this->remove (); -} - -int -ACE_Event::remove (void) -{ - int result = 0; - if (!this->removed_) - { - this->removed_ = true; - result = ACE_OS::event_destroy (&this->handle_); - } - return result; -} - -int -ACE_Event::wait (void) -{ - return ACE_OS::event_wait (&this->handle_); -} - -int -ACE_Event::wait (const ACE_Time_Value *abstime, int use_absolute_time) -{ - return ACE_OS::event_timedwait (&this->handle_, - const_cast (abstime), - use_absolute_time); -} - -int -ACE_Event::signal (void) -{ - return ACE_OS::event_signal (&this->handle_); -} - -int -ACE_Event::pulse (void) -{ - return ACE_OS::event_pulse (&this->handle_); -} - -int -ACE_Event::reset (void) -{ - return ACE_OS::event_reset (&this->handle_); -} - -void -ACE_Event::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Event.h b/externals/ace/Event.h deleted file mode 100644 index 887b504d8f9..00000000000 --- a/externals/ace/Event.h +++ /dev/null @@ -1,143 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file Event.h - * - * $Id: Event.h 80826 2008-03-04 14:51:23Z wotte $ - * - * Moved from Synch.h. - * - * @author Douglas C. Schmidt - */ -//========================================================================== - -#ifndef ACE_EVENT_H -#define ACE_EVENT_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/OS_NS_Thread.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Event - * - * @brief A wrapper around the Win32 event locking mechanism. - * - * Portable implementation of an Event mechanism, which is native to - * Win32, but must be emulated on UNIX. All platforms support - * process-scope locking support. However, only Win32 platforms - * support global naming and system-scope locking support. - */ -class ACE_Export ACE_Event -{ -public: - /// Constructor that creates event. - ACE_Event (int manual_reset = 0, - int initial_state = 0, - int type = USYNC_THREAD, - const ACE_TCHAR *name = 0, - void *arg = 0, - LPSECURITY_ATTRIBUTES sa = 0); - - /// Implicitly destroy the event variable. - ~ACE_Event (void); - - /** - * Explicitly destroy the event variable. Note that only one thread - * should call this method since it doesn't protect against race - * conditions. - */ - int remove (void); - - /// Underlying handle to event. - ACE_event_t handle (void) const; - - /** - * Set the underlying handle to event. Note that this method assumes - * ownership of the and will close it down in . If - * you want the to stay open when is called make - * sure to call on the before closing it. You are - * responsible for the closing the existing before - * overwriting it. - */ - void handle (ACE_event_t new_handle); - - /** - * if MANUAL reset - * sleep till the event becomes signaled - * event remains signaled after wait() completes. - * else AUTO reset - * sleep till the event becomes signaled - * event resets wait() completes. - */ - int wait (void); - - /// Same as wait() above, but this one can be timed - /// @a abstime is absolute time-of-day if if @a use_absolute_time - /// is non-0, else it is relative time. - int wait (const ACE_Time_Value *abstime, - int use_absolute_time = 1); - - /** - * if MANUAL reset - * wake up all waiting threads - * set to signaled state - * else AUTO reset - * if no thread is waiting, set to signaled state - * if thread(s) are waiting, wake up one waiting thread and - * reset event - */ - int signal (void); - - /** - * if MANUAL reset - * wakeup all waiting threads and - * reset event - * else AUTO reset - * wakeup one waiting thread (if present) and - * reset event - */ - int pulse (void); - - /// Set to nonsignaled state. - int reset (void); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks - ACE_ALLOC_HOOK_DECLARE; - -protected: - /// The underlying handle. - ACE_event_t handle_; - - /// Keeps track of whether has been called yet to avoid - /// multiple calls, e.g., explicitly and implicitly in the - /// destructor. This flag isn't protected by a lock, so make sure - /// that you don't have multiple threads simultaneously calling - /// on the same object, which is a bad idea anyway... - bool removed_; - -private: - // = Prevent copying. - ACE_Event (const ACE_Event& event); - const ACE_Event &operator= (const ACE_Event &rhs); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Event.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_EVENT_H */ diff --git a/externals/ace/Event.inl b/externals/ace/Event.inl deleted file mode 100644 index ae0805c95f0..00000000000 --- a/externals/ace/Event.inl +++ /dev/null @@ -1,18 +0,0 @@ -// -*- C++ -*- -// $Id: Event.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE ACE_event_t -ACE_Event::handle (void) const -{ - return this->handle_; -} - -ACE_INLINE void -ACE_Event::handle (ACE_event_t new_handle) -{ - this->handle_ = new_handle; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Event_Handler.cpp b/externals/ace/Event_Handler.cpp deleted file mode 100644 index e04e8cb5d10..00000000000 --- a/externals/ace/Event_Handler.cpp +++ /dev/null @@ -1,394 +0,0 @@ -// Event_Handler.cpp -// $Id: Event_Handler.cpp 85236 2009-05-01 11:43:56Z johnnyw $ - -#include "ace/Event_Handler.h" -#include "ace/OS_Errno.h" -#include "ace/Reactor.h" -#include "ace/Thread_Manager.h" -/* Need to see if ACE_HAS_BUILTIN_ATOMIC_OP defined */ -#include "ace/Atomic_Op.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Event_Handler.inl" -#endif /* __ACE_INLINE__ */ - -#include - -ACE_RCSID(ace, Event_Handler, "$Id: Event_Handler.cpp 85236 2009-05-01 11:43:56Z johnnyw $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Implement conceptually abstract virtual functions in the base class -// so derived classes don't have to implement unused ones. - -ACE_Event_Handler::ACE_Event_Handler (ACE_Reactor *r, - int p) - : reference_count_ (1), - priority_ (p), - reactor_ (r), - reference_counting_policy_ (Reference_Counting_Policy::DISABLED) -{ - // ACE_TRACE ("ACE_Event_Handler::ACE_Event_Handler"); -} - -ACE_Event_Handler::~ACE_Event_Handler (void) -{ - // ACE_TRACE ("ACE_Event_Handler::~ACE_Event_Handler"); -} - -// Gets the file descriptor associated with this I/O device. - -ACE_HANDLE -ACE_Event_Handler::get_handle (void) const -{ - ACE_TRACE ("ACE_Event_Handler::get_handle"); - return ACE_INVALID_HANDLE; -} - -// Sets the file descriptor associated with this I/O device. - -void -ACE_Event_Handler::set_handle (ACE_HANDLE) -{ - ACE_TRACE ("ACE_Event_Handler::set_handle"); -} - -// Gets the priority of this handler. - -int -ACE_Event_Handler::priority (void) const -{ - ACE_TRACE ("ACE_Event_Handler::priority"); - return this->priority_; -} - -// Sets the priority - -void -ACE_Event_Handler::priority (int priority) -{ - ACE_TRACE ("ACE_Event_Handler::priority"); - this->priority_ = priority; -} - -// Called when the object is about to be removed from the Dispatcher -// tables. - -int -ACE_Event_Handler::handle_close (ACE_HANDLE, ACE_Reactor_Mask) -{ - ACE_TRACE ("ACE_Event_Handler::handle_close"); - return -1; -} - -// Called when input becomes available on fd. - -int -ACE_Event_Handler::handle_input (ACE_HANDLE) -{ - ACE_TRACE ("ACE_Event_Handler::handle_input"); - return -1; -} - -// Called when output is possible on fd. - -int -ACE_Event_Handler::handle_output (ACE_HANDLE) -{ - ACE_TRACE ("ACE_Event_Handler::handle_output"); - return -1; -} - -// Called when urgent data is available on fd. - -int -ACE_Event_Handler::handle_exception (ACE_HANDLE) -{ - ACE_TRACE ("ACE_Event_Handler::handle_exception"); - return -1; -} - -// Called when timer expires, TV stores the current time. - -int -ACE_Event_Handler::handle_timeout (const ACE_Time_Value &, const void *) -{ - ACE_TRACE ("ACE_Event_Handler::handle_timeout"); - return -1; -} - -// Called when a monitored Process exits - -int -ACE_Event_Handler::handle_exit (ACE_Process *) -{ - ACE_TRACE ("ACE_Event_Handler::handle_exit"); - return -1; -} - -// Called when a registered signal occurs. - -int -ACE_Event_Handler::handle_signal (int, siginfo_t *, ucontext_t *) -{ - ACE_TRACE ("ACE_Event_Handler::handle_signal"); - return -1; -} - -int -ACE_Event_Handler::resume_handler (void) -{ - ACE_TRACE ("ACE_Event_Handler::resume_handler"); - - // Return a default value and allow the reactor to take care of - // resuming the handler - return ACE_Event_Handler::ACE_REACTOR_RESUMES_HANDLER; -} - - -int -ACE_Event_Handler::handle_qos (ACE_HANDLE) -{ - ACE_TRACE ("ACE_Event_Handler::handle_qos"); - return -1; -} - -int -ACE_Event_Handler::handle_group_qos (ACE_HANDLE) -{ - ACE_TRACE ("ACE_Event_Handler::handle_group_qos"); - return -1; -} - -void -ACE_Event_Handler::reactor (ACE_Reactor *reactor) -{ - ACE_TRACE ("ACE_Event_Handler::reactor"); - this->reactor_ = reactor; -} - -ACE_Reactor * -ACE_Event_Handler::reactor (void) const -{ - ACE_TRACE ("ACE_Event_Handler::reactor"); - return this->reactor_; -} - -ACE_Reactor_Timer_Interface * -ACE_Event_Handler::reactor_timer_interface (void) const -{ - ACE_TRACE ("ACE_Event_Handler::reactor_timer_interface"); - return this->reactor_; -} - -ACE_Event_Handler::Reference_Count -ACE_Event_Handler::add_reference (void) -{ - bool const reference_counting_required = - this->reference_counting_policy ().value () == - ACE_Event_Handler::Reference_Counting_Policy::ENABLED; - - if (reference_counting_required) - return ++this->reference_count_; - else - return 1; -} - -ACE_Event_Handler::Reference_Count -ACE_Event_Handler::remove_reference (void) -{ - bool const reference_counting_required = - this->reference_counting_policy ().value () == - ACE_Event_Handler::Reference_Counting_Policy::ENABLED; - - if (reference_counting_required) - { - Reference_Count result = - --this->reference_count_; - - if (result == 0) - delete this; - - return result; - } - else - { - return 1; - } -} - -ACE_Event_Handler::Policy::~Policy (void) -{ -} - -ACE_Event_Handler::Reference_Counting_Policy::Reference_Counting_Policy (Reference_Counting_Policy::Value value) - : value_ (value) -{ -} - -ACE_Event_Handler::Reference_Counting_Policy::Value -ACE_Event_Handler::Reference_Counting_Policy::value (void) const -{ - return this->value_; -} - -void -ACE_Event_Handler::Reference_Counting_Policy::value (ACE_Event_Handler::Reference_Counting_Policy::Value value) -{ - this->value_ = value; -} - -ACE_Event_Handler::Reference_Counting_Policy & -ACE_Event_Handler::reference_counting_policy (void) -{ - return this->reference_counting_policy_; -} - -ACE_THR_FUNC_RETURN -ACE_Event_Handler::read_adapter (void *args) -{ - ACE_Event_Handler *this_ptr = static_cast (args); - ACE_Reactor *r = this_ptr->reactor (); - - while (this_ptr->handle_input (ACE_STDIN) != -1) - continue; - - this_ptr->handle_close (ACE_STDIN, ACE_Event_Handler::READ_MASK); - // It's possible for handle_close() to "delete this" so we need to - // cache the reactor pointer and use it here. - r->notify (); - - return 0; -} - -int -ACE_Event_Handler::register_stdin_handler (ACE_Event_Handler *eh, - ACE_Reactor *reactor, - ACE_Thread_Manager *thr_mgr, - int flags) -{ -#if defined (ACE_WIN32) - ACE_UNUSED_ARG (reactor); - - eh->reactor (reactor); - return thr_mgr->spawn (&read_adapter, static_cast (eh), flags); -#else - // Keep compilers happy. - ACE_UNUSED_ARG (flags); - ACE_UNUSED_ARG (thr_mgr); - return reactor->register_handler (ACE_STDIN, - eh, - ACE_Event_Handler::READ_MASK); -#endif /* ACE_WIN32 */ -} - -int -ACE_Event_Handler::remove_stdin_handler (ACE_Reactor *reactor, - ACE_Thread_Manager * /* thr_mgr */) -{ -#if defined (ACE_WIN32) - ACE_UNUSED_ARG (reactor); - - // What should we do here? - ACE_NOTSUP_RETURN (-1); -#else - return reactor->remove_handler (ACE_STDIN, - ACE_Event_Handler::READ_MASK); -#endif /* ACE_WIN32 */ -} - -// --------------------------------------------------------------------- - -ACE_Event_Handler_var::ACE_Event_Handler_var (void) - : ptr_ (0) -{ -} - -ACE_Event_Handler_var::ACE_Event_Handler_var (ACE_Event_Handler *p) - : ptr_ (p) -{ -} - -ACE_Event_Handler_var::ACE_Event_Handler_var (const ACE_Event_Handler_var &b) - : ptr_ (b.ptr_) -{ - if (this->ptr_ != 0) - { - this->ptr_->add_reference (); - } -} - -ACE_Event_Handler_var::~ACE_Event_Handler_var (void) -{ - if (this->ptr_ != 0) - { - ACE_Errno_Guard eguard (errno); - this->ptr_->remove_reference (); - } -} - -ACE_Event_Handler_var & -ACE_Event_Handler_var::operator= (ACE_Event_Handler *p) -{ - if (this->ptr_ != p) - { - ACE_Event_Handler_var tmp (p); - std::swap (this->ptr_, tmp.ptr_); - } - - return *this; -} - -ACE_Event_Handler_var & -ACE_Event_Handler_var::operator= (const ACE_Event_Handler_var &b) -{ - ACE_Event_Handler_var tmp (b); - std::swap (this->ptr_, tmp.ptr_); - - return *this; -} - -ACE_Event_Handler * -ACE_Event_Handler_var::operator->() const -{ - return this->ptr_; -} - -ACE_Event_Handler * -ACE_Event_Handler_var::handler (void) const -{ - return this->ptr_; -} - -ACE_Event_Handler * -ACE_Event_Handler_var::release (void) -{ - ACE_Event_Handler * const old = this->ptr_; - this->ptr_ = 0; - return old; -} - -void -ACE_Event_Handler_var::reset (ACE_Event_Handler *p) -{ - *this = p; -} - -// --------------------------------------------------------------------- - -ACE_Notification_Buffer::ACE_Notification_Buffer (void) - : eh_ (0), - mask_ (ACE_Event_Handler::NULL_MASK) -{ - ACE_TRACE ("ACE_Notification_Buffer::ACE_Notification_Buffer"); -} - -ACE_Notification_Buffer::ACE_Notification_Buffer (ACE_Event_Handler *eh, - ACE_Reactor_Mask mask) - : eh_ (eh), - mask_ (mask) -{ - ACE_TRACE ("ACE_Notification_Buffer::ACE_Notification_Buffer"); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Event_Handler.h b/externals/ace/Event_Handler.h deleted file mode 100644 index 417f78578e7..00000000000 --- a/externals/ace/Event_Handler.h +++ /dev/null @@ -1,389 +0,0 @@ -/* -*- C++ -*- */ - -//========================================================================== -/** - * @file Event_Handler.h - * - * $Id: Event_Handler.h 91066 2010-07-12 11:05:04Z johnnyw $ - * - * @author Douglas C. Schmidt - */ -//========================================================================== - -#ifndef ACE_EVENT_HANDLER_H -#define ACE_EVENT_HANDLER_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/os_signal.h" -#include "ace/Atomic_Op.h" -#include "ace/Synch_Traits.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Forward declaration. -class ACE_Message_Block; -class ACE_Reactor; -class ACE_Reactor_Timer_Interface; -class ACE_Thread_Manager; -class ACE_Process; - -typedef unsigned long ACE_Reactor_Mask; - -/** - * @class ACE_Event_Handler - * - * @brief - * Provides an abstract interface for handling various types of - * I/O, timer, and signal events. - * - * Subclasses read/write input/output on an I/O descriptor, - * handle an exception raised on an I/O descriptor, handle a - * timer's expiration, or handle a signal. - */ -class ACE_Export ACE_Event_Handler -{ -public: - enum - { - LO_PRIORITY = 0, - HI_PRIORITY = 10, - NULL_MASK = 0, -#if defined (ACE_USE_POLL) - READ_MASK = POLLIN, - WRITE_MASK = POLLOUT, - EXCEPT_MASK = POLLPRI, -#else /* USE SELECT */ - READ_MASK = (1 << 0), - WRITE_MASK = (1 << 1), - EXCEPT_MASK = (1 << 2), -#endif /* ACE_USE_POLL */ - ACCEPT_MASK = (1 << 3), - CONNECT_MASK = (1 << 4), - TIMER_MASK = (1 << 5), - QOS_MASK = (1 << 6), - GROUP_QOS_MASK = (1 << 7), - SIGNAL_MASK = (1 << 8), - ALL_EVENTS_MASK = READ_MASK | - WRITE_MASK | - EXCEPT_MASK | - ACCEPT_MASK | - CONNECT_MASK | - TIMER_MASK | - QOS_MASK | - GROUP_QOS_MASK | - SIGNAL_MASK, - RWE_MASK = READ_MASK | - WRITE_MASK | - EXCEPT_MASK, - DONT_CALL = (1 << 9) - }; - - /// Destructor is virtual to enable proper cleanup. - virtual ~ACE_Event_Handler (void); - - /// Get the I/O handle. - virtual ACE_HANDLE get_handle (void) const; - - /// Set the I/O handle. - virtual void set_handle (ACE_HANDLE); - - // = Get/set priority - - /// Get the priority of the Event_Handler. - /// @note Priorities run from MIN_PRIORITY (which is the "lowest priority") - /// to MAX_PRIORITY (which is the "highest priority"). - virtual int priority (void) const; - - /// Set the priority of the Event_Handler. - virtual void priority (int priority); - - /// Called when input events occur (e.g., connection or data). - virtual int handle_input (ACE_HANDLE fd = ACE_INVALID_HANDLE); - - /// Called when output events are possible (e.g., when flow control - /// abates or non-blocking connection completes). - virtual int handle_output (ACE_HANDLE fd = ACE_INVALID_HANDLE); - - /// Called when an exceptional events occur (e.g., SIGURG). - virtual int handle_exception (ACE_HANDLE fd = ACE_INVALID_HANDLE); - - /** - * Called when timer expires. @a current_time represents the current - * time that the Event_Handler was selected for timeout - * dispatching and @a act is the asynchronous completion token that - * was passed in when was invoked. - */ - virtual int handle_timeout (const ACE_Time_Value ¤t_time, - const void *act = 0); - - /// Called when a process exits. - virtual int handle_exit (ACE_Process *); - - /// Called when a method returns -1 or when the - /// method is called on an ACE_Reactor. The - /// @a close_mask indicates which event has triggered the - /// method callback on a particular @a handle. - virtual int handle_close (ACE_HANDLE handle, - ACE_Reactor_Mask close_mask); - - /// Called when object is signaled by OS (either via UNIX signals or - /// when a Win32 object becomes signaled). - virtual int handle_signal (int signum, siginfo_t * = 0, ucontext_t * = 0); - - enum - { - /// The handler is not resumed at all. Could lead to deadlock.. - ACE_EVENT_HANDLER_NOT_RESUMED = -1, - /// The reactor takes responsibility of resuming the handler and - /// is the default - ACE_REACTOR_RESUMES_HANDLER = 0, - /// The application takes responsibility of resuming the handler - ACE_APPLICATION_RESUMES_HANDLER - }; - /** - * Called to figure out whether the handler needs to resumed by the - * reactor or the application can take care of it. The default - * value of 0 would be returned which would allow the reactor to - * take care of resumption of the handler. The application can - * return a value more than zero and decide to resume the handler - * themseleves. - * - * @note This method has an affect only when used with the - * ACE_Dev_Poll_Reactor (and then, only on Linux) or the ACE_TP_Reactor. - */ - virtual int resume_handler (void); - - virtual int handle_qos (ACE_HANDLE = ACE_INVALID_HANDLE); - virtual int handle_group_qos (ACE_HANDLE = ACE_INVALID_HANDLE); - - // = Accessors to set/get the various event demultiplexors. - /// Set the event demultiplexors. - virtual void reactor (ACE_Reactor *reactor); - - /// Get the event demultiplexors. - virtual ACE_Reactor *reactor (void) const; - - /// Get only the reactor's timer related interface. - virtual ACE_Reactor_Timer_Interface *reactor_timer_interface (void) const; - - /** - * Used to read from non-socket ACE_HANDLEs in our own thread to - * work around Win32 limitations that don't allow us to 'able on - * Win32. - */ - static int register_stdin_handler (ACE_Event_Handler *eh, - ACE_Reactor *reactor, - ACE_Thread_Manager *thr_mgr, - int flags = THR_DETACHED); - - /// Performs the inverse of the register_stdin_handler() method. - static int remove_stdin_handler (ACE_Reactor *reactor, - ACE_Thread_Manager *thr_mgr); - - /// Reference count type. - typedef long Reference_Count; - - /// Increment reference count on the handler. - /** - * This method is called when the handler is registered with the - * Reactor and when the Reactor makes an upcall on the handler. - * Reference count is 1 when the handler is created. - * - * @return Current reference count. - */ - virtual Reference_Count add_reference (void); - - /// Decrement reference count on the handler. - /** - * This method is called when the handler is removed from the - * Reactor and when an upcall made on the handler by the Reactor - * completes. Handler is deleted when the reference count reaches - * 0. - * - * @return Current reference count. - */ - virtual Reference_Count remove_reference (void); - - /** - * @class Policy - * - * @brief Base class for all handler policies. - */ - class ACE_Export Policy - { - - public: - - /// Virtual destructor. - virtual ~Policy (void); - }; - - /** - * @class Reference_Counting_Policy - * - * @brief - * This policy dictates the reference counting requirements - * for the handler. - * - * This policy allows applications to configure whether it wants the - * Reactor to call add_reference() and remove_reference() during - * registrations, removals, and upcalls. - * - * Default: DISABLED. - */ - class ACE_Export Reference_Counting_Policy : public Policy - { - /// This policy can only be created by the handler. - friend class ACE_Event_Handler; - - public: - - enum Value - { - /// Perform reference counting. - ENABLED, - /// Don't perform reference counting. - DISABLED - }; - - /// Current Reference_Counting_Policy. - Value value (void) const; - - /// Update Reference_Counting_Policy. - void value (Value value); - - private: - - /// Private constructor. - Reference_Counting_Policy (Value value); - - /// The value of the policy. - Value value_; - }; - - /// Current Reference_Counting_Policy. - Reference_Counting_Policy &reference_counting_policy (void); - -protected: - /// Force ACE_Event_Handler to be an abstract base class. - ACE_Event_Handler (ACE_Reactor * = 0, - int priority = ACE_Event_Handler::LO_PRIORITY); - - /// Typedef for implementation of reference counting. - typedef ACE_Atomic_Op Atomic_Reference_Count; - - /// Reference count. - Atomic_Reference_Count reference_count_; - -private: - - /// Priority of this Event_Handler. - int priority_; - - /// Pointer to the various event demultiplexors. - ACE_Reactor *reactor_; - - /// Reference counting requirements. - Reference_Counting_Policy reference_counting_policy_; -}; - -/** - * @class ACE_Event_Handler_var - * - * @brief Auto pointer like class for Event Handlers. - * - * Used to manage lifecycle of handlers. This class calls - * ACE_Event_Handler::remove_reference() in its destructor. - */ -class ACE_Export ACE_Event_Handler_var -{ - -public: - - /// Default constructor. - ACE_Event_Handler_var (void); - - /// Construct with a handler. - ACE_Event_Handler_var (ACE_Event_Handler *p); - - /// Copy constructor. - ACE_Event_Handler_var (const ACE_Event_Handler_var &b); - - /// Destructor. - ~ACE_Event_Handler_var (void); - - /// Assignment to a handler. - ACE_Event_Handler_var &operator= (ACE_Event_Handler *p); - - /// Assignment to a ACE_Event_Handler_var. - ACE_Event_Handler_var &operator= (const ACE_Event_Handler_var &b); - - /// Overloaded "->". - ACE_Event_Handler *operator-> () const; - - /// Access the handler. - ACE_Event_Handler *handler (void) const; - - /// Release the handler. - ACE_Event_Handler *release (void); - - /// Reset the handler. - void reset (ACE_Event_Handler *p = 0); - -private: - - /// Handler. - ACE_Event_Handler *ptr_; -}; - -/** - * @class ACE_Notification_Buffer - * - * @brief Simple wrapper for passing s and - * ACE_Reactor_Masks between threads. - */ -class ACE_Export ACE_Notification_Buffer -{ -public: - ACE_Notification_Buffer (void); - - ACE_Notification_Buffer (ACE_Event_Handler *eh, - ACE_Reactor_Mask mask); - - /// Default dtor. - ~ACE_Notification_Buffer (void); - - /// Pointer to the Event_Handler that will be dispatched - /// by the main event loop. - ACE_Event_Handler *eh_; - - /// Mask that indicates which method to call. - ACE_Reactor_Mask mask_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Event_Handler.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_EVENT_HANDLER_H */ diff --git a/externals/ace/Event_Handler.inl b/externals/ace/Event_Handler.inl deleted file mode 100644 index d97c45466ae..00000000000 --- a/externals/ace/Event_Handler.inl +++ /dev/null @@ -1,12 +0,0 @@ -// -*- C++ -*- -// -// $Id: Event_Handler.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE -ACE_Notification_Buffer::~ACE_Notification_Buffer (void) -{ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Event_Handler_T.cpp b/externals/ace/Event_Handler_T.cpp deleted file mode 100644 index 45d9d4e2767..00000000000 --- a/externals/ace/Event_Handler_T.cpp +++ /dev/null @@ -1,125 +0,0 @@ -// Event_Handler_T.cpp -// -// $Id: Event_Handler_T.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#ifndef ACE_EVENT_HANDLER_T_CPP -#define ACE_EVENT_HANDLER_T_CPP - -#include "ace/Event_Handler_T.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_TEMPLATE_TYPEDEFS) - -#if !defined (__ACE_INLINE__) -#include "ace/Event_Handler_T.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Event_Handler_T) - -template void -ACE_Event_Handler_T::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Event_Handler_T::dump"); -#endif /* ACE_HAS_DUMP */ -} - -template -ACE_Event_Handler_T::~ACE_Event_Handler_T (void) -{ - ACE_TRACE ("ACE_Event_Handler_T::~ACE_Event_Handler_T"); - if (this->delete_handler_) - delete this->op_handler_; -} - -template -ACE_Event_Handler_T::ACE_Event_Handler_T (T *op_handler, int delete_handler, - GET_HANDLE get_handle, - IO_HANDLER input_h, - CL_HANDLER close_h, - SIG_HANDLER sig_h, - TO_HANDLER timeout_h, - IO_HANDLER output_h, - SET_HANDLE set_handle, - IO_HANDLER except_h) - : op_handler_ (op_handler), - input_handler_ (input_h), - output_handler_ (output_h), - except_handler_ (except_h), - to_handler_ (timeout_h), - cl_handler_ (close_h), - sig_handler_ (sig_h), - delete_handler_ (delete_handler), - set_handle_ (set_handle), - get_handle_ (get_handle) -{ - ACE_TRACE ("ACE_Event_Handler_T::ACE_Event_Handler_T"); -} - -template ACE_HANDLE -ACE_Event_Handler_T::get_handle (void) const -{ - ACE_TRACE ("ACE_Event_Handler_T::get_handle"); - return this->get_handle_ == 0 ? ACE_INVALID_HANDLE : (this->op_handler_->*get_handle_) (); -} - -template void -ACE_Event_Handler_T::set_handle (ACE_HANDLE h) -{ - ACE_TRACE ("ACE_Event_Handler_T::set_handle"); - if (this->set_handle_ != 0) - (this->op_handler_->*set_handle_) (h); -} - -template int -ACE_Event_Handler_T::handle_input (ACE_HANDLE fd) -{ - ACE_TRACE ("ACE_Event_Handler_T::handle_input"); - return this->input_handler_ == 0 ? 0 : (this->op_handler_->*input_handler_) (fd); -} - -template int -ACE_Event_Handler_T::handle_output (ACE_HANDLE fd) -{ - ACE_TRACE ("ACE_Event_Handler_T::handle_output"); - return this->output_handler_ == 0 ? 0 : (this->op_handler_->*output_handler_) (fd); -} - -template int -ACE_Event_Handler_T::handle_exception (ACE_HANDLE fd) -{ - ACE_TRACE ("ACE_Event_Handler_T::handle_exception"); - return this->except_handler_ == 0 ? 0 : (this->op_handler_->*except_handler_) (fd); -} - -template int -ACE_Event_Handler_T::handle_timeout (const ACE_Time_Value &tv, const void *arg) -{ - ACE_TRACE ("ACE_Event_Handler_T::handle_timeout"); - return this->to_handler_ == 0 ? 0 : (this->op_handler_->*to_handler_) (tv, arg); -} - -template int -ACE_Event_Handler_T::handle_close (ACE_HANDLE fd, ACE_Reactor_Mask close_mask) -{ - ACE_TRACE ("ACE_Event_Handler_T::handle_close"); - return this->cl_handler_ == 0 ? 0 : (this->op_handler_->*cl_handler_) (fd, close_mask); -} - -template int -ACE_Event_Handler_T::handle_signal (int signum, siginfo_t *s, ucontext_t *u) -{ - ACE_TRACE ("ACE_Event_Handler_T::handle_signal"); - return this->sig_handler_ == 0 ? 0 : (this->op_handler_->*sig_handler_) (signum, s, u); -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_TEMPLATE_TYPEDEFS */ - -#endif /* ACE_EVENT_HANDLER_T_CPP */ diff --git a/externals/ace/Event_Handler_T.h b/externals/ace/Event_Handler_T.h deleted file mode 100644 index d86ac333221..00000000000 --- a/externals/ace/Event_Handler_T.h +++ /dev/null @@ -1,191 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file Event_Handler_T.h - * - * $Id: Event_Handler_T.h 83891 2008-11-28 11:01:50Z johnnyw $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_EVENT_HANDLER_T_H -#define ACE_EVENT_HANDLER_T_H -#include /**/ "ace/pre.h" - -#include "ace/Event_Handler.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_TEMPLATE_TYPEDEFS) - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Event_Handler_T - * - * @brief Enable a class that doesn't inherit from the - * ACE_Event_Handler to be incorporated into the ACE_Reactor - * framework. Thanks to Greg Lavender (g.lavender@isode.com) - * for sharing this idea. - * - * It is sometimes the case that an application has a hierarchy - * of operation dispatcher classes that have their own - * inheritance hierarchy but also would like to integrate with - * the ACE_Reactor. Rather than adopt a "mixin" approach, it is - * often cleaner to define a template as a subclass of - * ACE_Event_Handler and parameterize it with an operation - * dispatcher type. - * When constructing an instantiation of the ACE_Event_Handler_T - * object, a set of pointers to member functions must be - * provided so that when one of the handle_* methods is called - * by the ACE_Reactor, the appropriate method is called on the - * underlying operations object. This is done since in some - * cases it is useful to map any event that happens to the same - * method on an object. - * The ACE_Event_Handler_T template is instantiated by an - * operations object and registered with the ACE_Reactor, and it - * then calls the appropriate op_handler. So, it's basically - * just another level of indirection in event dispatching. The - * coupling betweent the ultimate handler of the event and the - * ACE_Event_Handler class is relaxed a bit by have this - * intermediate object of type around. The - * client object can then dynamically change the bindings for - * the various handlers so that during the life of one of the - * operation objects, it can change how it wants events to be - * handled. It just instantiates a new instance of the template - * with different bindings and reregisters this new object with - * the ACE_Reactor. - */ -template -class ACE_Event_Handler_T : public ACE_Event_Handler -{ -public: - // = Typedefs to simplify pointer-to-member-function registration. - - // Get/set the underlying handle. - typedef ACE_HANDLE (T::*GET_HANDLE) (void) const; - typedef void (T::*SET_HANDLE) (ACE_HANDLE); - - /// Handle I/O events. - typedef int (T::*IO_HANDLER) (ACE_HANDLE); - - /// Handle timeout events. - typedef int (T::*TO_HANDLER) (const ACE_Time_Value &, const void *); - - /// Handle close events. - typedef int (T::*CL_HANDLER) (ACE_HANDLE, ACE_Reactor_Mask); - - /// = Initialization and termination methods. - typedef int (T::*SIG_HANDLER) (int, siginfo_t*, ucontext_t*); - - /// Initialize the op_handler. - ACE_Event_Handler_T (T *op_handler, - int delete_handler, - GET_HANDLE get_handle = 0, - IO_HANDLER input = 0, - CL_HANDLER close = 0, - SIG_HANDLER sig = 0, - TO_HANDLER timeout = 0, - IO_HANDLER output = 0, - SET_HANDLE set_handle = 0, - IO_HANDLER except = 0); - - /// Close down and delete the - ~ACE_Event_Handler_T (void); - - // = Override all the ACE_Event_Handler methods. - - // These methods all delegate down to the operations handler. - virtual ACE_HANDLE get_handle (void) const; - virtual void set_handle (ACE_HANDLE); - virtual int handle_input (ACE_HANDLE fd = ACE_INVALID_HANDLE); - virtual int handle_output (ACE_HANDLE fd = ACE_INVALID_HANDLE); - virtual int handle_exception (ACE_HANDLE fd = ACE_INVALID_HANDLE); - virtual int handle_timeout (const ACE_Time_Value &tv, const void *arg = 0); - virtual int handle_close (ACE_HANDLE fd, ACE_Reactor_Mask close_mask); - virtual int handle_signal (int signum, siginfo_t * = 0, ucontext_t * = 0); - - // = Get/set the operations handler. - T *op_handler (void); - void op_handler (T *); - - // = Get/set the target pointer-to-method used for dispatching. - - GET_HANDLE handle_get (void); - void handle_get (GET_HANDLE); - - SET_HANDLE handle_set (void); - void handle_set (SET_HANDLE); - - IO_HANDLER input_handler (void); - void input_handler (IO_HANDLER); - - IO_HANDLER output_handler (void); - void output_handler (IO_HANDLER); - - IO_HANDLER except_handler (void); - void except_handler (IO_HANDLER); - - TO_HANDLER to_handler (void); - void to_handler (TO_HANDLER); - - CL_HANDLER cl_handler (void); - void cl_handler (CL_HANDLER); - - SIG_HANDLER sig_handler (void); - void sig_handler (SIG_HANDLER); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - /// Pointer to the object that handles all the delegated operations. - T *op_handler_; - - // = Handle input, output, and exception events. - IO_HANDLER input_handler_; - IO_HANDLER output_handler_; - IO_HANDLER except_handler_; - - /// Handle timeout events. - TO_HANDLER to_handler_; - - /// Handle close events. - CL_HANDLER cl_handler_; - - /// Handle signal events. - SIG_HANDLER sig_handler_; - - /// Keeps track of whether we need to delete the handler in the - /// destructor. - int delete_handler_; - - // = Get/set underlying handle. - SET_HANDLE set_handle_; - GET_HANDLE get_handle_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Event_Handler_T.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Event_Handler_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Event_Handler_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#endif /* ACE_HAS_TEMPLATE_TYPEDEFS */ -#include /**/ "ace/post.h" -#endif /* ACE_EVENT_HANDLER_H */ diff --git a/externals/ace/Event_Handler_T.inl b/externals/ace/Event_Handler_T.inl deleted file mode 100644 index 40db43e8e23..00000000000 --- a/externals/ace/Event_Handler_T.inl +++ /dev/null @@ -1,135 +0,0 @@ -// -*- C++ -*- -// -// $Id: Event_Handler_T.inl 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Global_Macros.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template ACE_INLINE void -ACE_Event_Handler_T::op_handler (T *op) -{ - ACE_TRACE ("ACE_Event_Handler_T::op_handler"); - this->op_handler_ = op; -} - -template ACE_INLINE T * -ACE_Event_Handler_T::op_handler (void) -{ - ACE_TRACE ("ACE_Event_Handler_T::op_handler"); - return this->op_handler_; -} - -template ACE_INLINE typename ACE_Event_Handler_T::GET_HANDLE -ACE_Event_Handler_T::handle_get (void) -{ - ACE_TRACE ("ACE_Event_Handler_T::handle_get"); - return this->get_handle_; -} - -template ACE_INLINE void -ACE_Event_Handler_T::handle_get (typename ACE_Event_Handler_T::GET_HANDLE h) -{ - ACE_TRACE ("ACE_Event_Handler_T::handle_get"); - this->get_handle_ = h; -} - -template ACE_INLINE typename ACE_Event_Handler_T::SET_HANDLE -ACE_Event_Handler_T::handle_set (void) -{ - ACE_TRACE ("ACE_Event_Handler_T::handle_set"); - return this->set_handle_; -} - -template ACE_INLINE void -ACE_Event_Handler_T::handle_set (typename ACE_Event_Handler_T::SET_HANDLE h) -{ - ACE_TRACE ("ACE_Event_Handler_T::handle_set"); - this->set_handle_ = h; -} - -template ACE_INLINE typename ACE_Event_Handler_T::IO_HANDLER -ACE_Event_Handler_T::input_handler (void) -{ - ACE_TRACE ("ACE_Event_Handler_T::input_handler"); - return this->input_handler_; -} - -template ACE_INLINE void -ACE_Event_Handler_T::input_handler (typename ACE_Event_Handler_T::IO_HANDLER h) -{ - ACE_TRACE ("ACE_Event_Handler_T::input_handler"); - this->input_handler_ = h; -} - -template ACE_INLINE typename ACE_Event_Handler_T::IO_HANDLER -ACE_Event_Handler_T::output_handler (void) -{ - ACE_TRACE ("ACE_Event_Handler_T::output_handler"); - return this->output_handler_; -} - -template ACE_INLINE void -ACE_Event_Handler_T::output_handler (typename ACE_Event_Handler_T::IO_HANDLER h) -{ - ACE_TRACE ("ACE_Event_Handler_T::output_handler"); - this->output_handler_ = h; -} - -template ACE_INLINE typename ACE_Event_Handler_T::IO_HANDLER -ACE_Event_Handler_T::except_handler (void) -{ - ACE_TRACE ("ACE_Event_Handler_T::except_handler"); - return this->except_handler_; -} - -template ACE_INLINE void -ACE_Event_Handler_T::except_handler (typename ACE_Event_Handler_T::IO_HANDLER h) -{ - ACE_TRACE ("ACE_Event_Handler_T::except_handler"); - this->except_handler_ = h; -} - -template ACE_INLINE typename ACE_Event_Handler_T::TO_HANDLER -ACE_Event_Handler_T::to_handler (void) -{ - ACE_TRACE ("ACE_Event_Handler_T::to_handler"); - return this->to_handler_; -} - -template ACE_INLINE void -ACE_Event_Handler_T::to_handler (typename ACE_Event_Handler_T::TO_HANDLER h) -{ - ACE_TRACE ("ACE_Event_Handler_T::to_handler"); - this->to_handler_ = h; -} - -template ACE_INLINE typename ACE_Event_Handler_T::CL_HANDLER -ACE_Event_Handler_T::cl_handler (void) -{ - ACE_TRACE ("ACE_Event_Handler_T::cl_handler"); - return this->cl_handler_; -} - -template ACE_INLINE void -ACE_Event_Handler_T::cl_handler (typename ACE_Event_Handler_T::CL_HANDLER h) -{ - ACE_TRACE ("ACE_Event_Handler_T::cl_handler"); - this->cl_handler_ = h; -} - -template ACE_INLINE typename ACE_Event_Handler_T::SIG_HANDLER -ACE_Event_Handler_T::sig_handler (void) -{ - ACE_TRACE ("ACE_Event_Handler_T::sig_handler"); - return this->sig_handler_; -} - -template ACE_INLINE void -ACE_Event_Handler_T::sig_handler (typename ACE_Event_Handler_T::SIG_HANDLER h) -{ - ACE_TRACE ("ACE_Event_Handler_T::sig_handler"); - this->sig_handler_ = h; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Exception_Macros.h b/externals/ace/Exception_Macros.h deleted file mode 100644 index bb74b1a2129..00000000000 --- a/externals/ace/Exception_Macros.h +++ /dev/null @@ -1,55 +0,0 @@ -// -*- C++ -*- - -// ============================================================================ -/** - * @file Exception_Macros.h - * - * $Id: Exception_Macros.h 80826 2008-03-04 14:51:23Z wotte $ - * - * Writing code that is portable between platforms with or without - * native C++ exceptions is hard. The following macros offer some - * help on this task. - * - * @author Nanbor Wang - * @author Aniruddha Gokhale - * @author Carlos O'Ryan - * @author Krishnakumar B , et al. - */ -// ============================================================================ - -// Macros for handling exceptions. - -#ifndef ACE_EXCEPTION_MACROS_H -#define ACE_EXCEPTION_MACROS_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -# if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -# endif /* ACE_LACKS_PRAGMA_ONCE */ - -// By default, if the compiler supports native exception handling, assume -// CORBA also support native exception handling. But it can be disabled by -// defining ACE_CORBA_HAS_EXCEPTIONS=0. If the compiler does not support -// exceptions handling, make sure native exception handling is disabled. -#if defined (ACE_HAS_EXCEPTIONS) -# if defined (ACE_CORBA_HAS_EXCEPTIONS) -# if (ACE_CORBA_HAS_EXCEPTIONS == 0) -# undef ACE_USES_NATIVE_EXCEPTIONS -# else /* ACE_CORBA_HAS_EXCEPTIONS != 0 */ -# define ACE_USES_NATIVE_EXCEPTIONS -# endif /* ACE_CORBA_HAS_EXCEPTIONS == 0 */ -# else -# define ACE_USES_NATIVE_EXCEPTIONS -# define ACE_CORBA_HAS_EXCEPTIONS -# endif /* ACE_CORBA_HAS_EXCEPTIONS */ -#else /* ! ACE_HAS_EXCEPTIONS */ -# undef ACE_CORBA_HAS_EXCEPTIONS -# undef ACE_USES_NATIVE_EXCEPTIONS -#endif /* ACE_HAS_EXCEPTIONS */ - -#include /**/ "ace/post.h" - -#endif /* ACE_EXCEPTION_MACROS_H */ diff --git a/externals/ace/FIFO.cpp b/externals/ace/FIFO.cpp deleted file mode 100644 index e3970015c43..00000000000 --- a/externals/ace/FIFO.cpp +++ /dev/null @@ -1,78 +0,0 @@ -// $Id: FIFO.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/FIFO.h" - -#if !defined (__ACE_INLINE__) -#include "ace/FIFO.inl" -#endif /* __ACE_INLINE__ */ - -#include "ace/Log_Msg.h" -#include "ace/OS_NS_string.h" -#include "ace/OS_NS_errno.h" -#include "ace/OS_NS_sys_stat.h" -#include "ace/OS_NS_fcntl.h" - -ACE_RCSID(ace, FIFO, "$Id: FIFO.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_FIFO) - -void -ACE_FIFO::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_FIFO::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("rendezvous_ = %s"), this->rendezvous_)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -int -ACE_FIFO::open (const ACE_TCHAR *r, int flags, mode_t perms, - LPSECURITY_ATTRIBUTES sa) -{ - ACE_TRACE ("ACE_FIFO::open"); - ACE_OS::strsncpy (this->rendezvous_, r, MAXPATHLEN); - - if ((flags & O_CREAT) != 0 - && ACE_OS::mkfifo (this->rendezvous_, perms) == -1 - && !(errno == EEXIST)) - return -1; - - this->set_handle (ACE_OS::open (this->rendezvous_, flags, 0, sa)); - return this->get_handle () == ACE_INVALID_HANDLE ? -1 : 0; -} - -ACE_FIFO::ACE_FIFO (const ACE_TCHAR *fifo_name, - int flags, - mode_t perms, - LPSECURITY_ATTRIBUTES sa) -{ - ACE_TRACE ("ACE_FIFO::ACE_FIFO"); - if (this->open (fifo_name, flags, perms, sa) == -1) - ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("ACE_FIFO"))); -} - -ACE_FIFO::ACE_FIFO (void) -{ -// ACE_TRACE ("ACE_FIFO::ACE_FIFO"); -} - -int -ACE_FIFO::close (void) -{ - ACE_TRACE ("ACE_FIFO::close"); - int result = 0; - - if (this->get_handle () != ACE_INVALID_HANDLE) - { - result = ACE_OS::close (this->get_handle ()); - this->set_handle (ACE_INVALID_HANDLE); - } - return result; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/FIFO.h b/externals/ace/FIFO.h deleted file mode 100644 index 2d590563a99..00000000000 --- a/externals/ace/FIFO.h +++ /dev/null @@ -1,85 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file FIFO.h - * - * $Id: FIFO.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Doug Schmidt - */ -//========================================================================== - - -#ifndef ACE_FIFO_H -#define ACE_FIFO_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/IPC_SAP.h" -#include "ace/os_include/os_limits.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_FIFO - * - * @brief Abstract base class for UNIX FIFOs - * - * UNIX FIFOs are also known Named Pipes, which are totally - * unrelated to Win32 Named Pipes. If you want to use a local - * IPC mechanism that will be portable to both UNIX and Win32, - * take a look at the classes. - */ -class ACE_Export ACE_FIFO : public ACE_IPC_SAP -{ -public: - /// Open up the named pipe on the in accordance with the - /// flags. - int open (const ACE_TCHAR *rendezvous, int flags, mode_t perms, - LPSECURITY_ATTRIBUTES sa = 0); - - /// Close down the ACE_FIFO without removing the rendezvous point. - int close (void); - - /// Close down the ACE_FIFO and remove the rendezvous point from the - /// file system. - int remove (void); - - /// Return the local address of this endpoint. - int get_local_addr (const ACE_TCHAR *&rendezvous) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - // = Make these protected to ensure that the class is "abstract." - /// Default constructor. - ACE_FIFO (void); - - /// Open up the named pipe on the in accordance with the - /// flags. - ACE_FIFO (const ACE_TCHAR *rendezvous, int flags, mode_t perms, - LPSECURITY_ATTRIBUTES sa = 0); - -private: - /// Rendezvous point in the file system. - ACE_TCHAR rendezvous_[MAXPATHLEN + 1]; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/FIFO.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_FIFO_H */ diff --git a/externals/ace/FIFO.inl b/externals/ace/FIFO.inl deleted file mode 100644 index 05cc030a917..00000000000 --- a/externals/ace/FIFO.inl +++ /dev/null @@ -1,25 +0,0 @@ -// -*- C++ -*- -// -// $Id: FIFO.inl 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/OS_NS_unistd.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE int -ACE_FIFO::get_local_addr (const ACE_TCHAR *&r) const -{ - ACE_TRACE ("ACE_FIFO::get_local_addr"); - r = this->rendezvous_; - return 0; -} - -ACE_INLINE int -ACE_FIFO::remove (void) -{ - ACE_TRACE ("ACE_FIFO::remove"); - int const result = this->close (); - return ACE_OS::unlink (this->rendezvous_) == -1 || result == -1 ? -1 : 0; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/FIFO_Recv.cpp b/externals/ace/FIFO_Recv.cpp deleted file mode 100644 index 254e30f21d1..00000000000 --- a/externals/ace/FIFO_Recv.cpp +++ /dev/null @@ -1,88 +0,0 @@ -// $Id: FIFO_Recv.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/FIFO_Recv.h" -#include "ace/Log_Msg.h" -#include "ace/OS_NS_fcntl.h" - -#if !defined (__ACE_INLINE__) -#include "ace/FIFO_Recv.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID(ace, FIFO_Recv, "$Id: FIFO_Recv.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_FIFO_Recv) - -void -ACE_FIFO_Recv::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_FIFO_Recv::dump"); - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_FIFO::dump (); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("aux_handle_ = %d"), this->aux_handle_)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -int -ACE_FIFO_Recv::close (void) -{ - ACE_TRACE ("ACE_FIFO_Recv::close"); - int result = ACE_FIFO::close (); - - if (this->aux_handle_ != ACE_INVALID_HANDLE) - return ACE_OS::close (this->aux_handle_); - else - return result; -} - -// Note that persistent means "open fifo for writing, as well as -// reading." This ensures that the fifo never gets EOF, even if there -// aren't any writers at the moment! - -int -ACE_FIFO_Recv::open (const ACE_TCHAR *fifo_name, - int flags, - mode_t perms, - int persistent, - LPSECURITY_ATTRIBUTES sa) -{ - ACE_TRACE ("ACE_FIFO_Recv::open"); - - if (ACE_FIFO::open (fifo_name, ACE_NONBLOCK | flags, perms, sa) == -1) - return -1; - else if (this->disable (ACE_NONBLOCK) == -1) - return -1; - else if (persistent - && (this->aux_handle_ = ACE_OS::open (fifo_name, O_WRONLY, 0, sa)) == ACE_INVALID_HANDLE) - return -1; - else - return this->get_handle () == ACE_INVALID_HANDLE ? -1 : 0; -} - -ACE_FIFO_Recv::ACE_FIFO_Recv (void) - : aux_handle_ (ACE_INVALID_HANDLE) -{ - ACE_TRACE ("ACE_FIFO_Recv::ACE_FIFO_Recv"); -} - -ACE_FIFO_Recv::ACE_FIFO_Recv (const ACE_TCHAR *fifo_name, - int flags, - mode_t perms, - int persistent, - LPSECURITY_ATTRIBUTES sa) - : aux_handle_ (ACE_INVALID_HANDLE) -{ - ACE_TRACE ("ACE_FIFO_Recv::ACE_FIFO_Recv"); - - if (this->ACE_FIFO_Recv::open (fifo_name, - flags, - perms, - persistent, - sa) == -1) - ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("ACE_FIFO_Recv"))); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/FIFO_Recv.h b/externals/ace/FIFO_Recv.h deleted file mode 100644 index c19d102c82a..00000000000 --- a/externals/ace/FIFO_Recv.h +++ /dev/null @@ -1,85 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file FIFO_Recv.h - * - * $Id: FIFO_Recv.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Doug Schmidt - */ -//========================================================================== - - -#ifndef ACE_FIFO_RECV_H -#define ACE_FIFO_RECV_H - -#include /**/ "ace/pre.h" - -#include "ace/FIFO.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/os_fcntl.h" -#include "ace/Default_Constants.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_FIFO_Recv - * - * @brief Receiver side of the bytestream C++ wrapper for UNIX - * FIFOs. - */ -class ACE_Export ACE_FIFO_Recv : public ACE_FIFO -{ -public: - // = Initialization methods. - /// Default constructor. - ACE_FIFO_Recv (void); - - /// Open up a bytestream named pipe for reading. - ACE_FIFO_Recv (const ACE_TCHAR *rendezvous, - int flags = O_CREAT | O_RDONLY, - mode_t perms = ACE_DEFAULT_FILE_PERMS, - int persistent = 1, - LPSECURITY_ATTRIBUTES sa = 0); - - /// Open up a bytestream named pipe for reading. - int open (const ACE_TCHAR *rendezvous, - int flags = O_CREAT | O_RDONLY, - mode_t perms = ACE_DEFAULT_FILE_PERMS, - int persistent = 1, - LPSECURITY_ATTRIBUTES sa = 0); - - /// Close down the named pipe. - int close (void); - - /// Recv @a buf of up to @a len bytes. - ssize_t recv (void *buf, size_t len); - - /// Recv @a buf of exactly @a len bytes (block until done). - ssize_t recv_n (void *buf, size_t len); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - /// Auxiliary handle that is used to implement persistent FIFOs. - ACE_HANDLE aux_handle_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/FIFO_Recv.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" - -#endif /* ACE_FIFO_RECV_H */ diff --git a/externals/ace/FIFO_Recv.inl b/externals/ace/FIFO_Recv.inl deleted file mode 100644 index d4c3fee4326..00000000000 --- a/externals/ace/FIFO_Recv.inl +++ /dev/null @@ -1,24 +0,0 @@ -// -*- C++ -*- -// -// $Id: FIFO_Recv.inl 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/ACE.h" -#include "ace/OS_NS_unistd.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE ssize_t -ACE_FIFO_Recv::recv (void *buf, size_t len) -{ - ACE_TRACE ("ACE_FIFO_Recv::recv"); - return ACE_OS::read (this->get_handle (), (char *) buf, len); -} - -ACE_INLINE ssize_t -ACE_FIFO_Recv::recv_n (void *buf, size_t n) -{ - ACE_TRACE ("ACE_FIFO_Recv::recv_n"); - return ACE::recv_n (this->get_handle (), buf, n); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/FIFO_Recv_Msg.cpp b/externals/ace/FIFO_Recv_Msg.cpp deleted file mode 100644 index f389d03d276..00000000000 --- a/externals/ace/FIFO_Recv_Msg.cpp +++ /dev/null @@ -1,67 +0,0 @@ -// $Id: FIFO_Recv_Msg.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/FIFO_Recv_Msg.h" - -#include "ace/Log_Msg.h" - -#if !defined (__ACE_INLINE__) -#include "ace/FIFO_Recv_Msg.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID(ace, FIFO_Recv_Msg, "$Id: FIFO_Recv_Msg.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_FIFO_Recv_Msg) - -void -ACE_FIFO_Recv_Msg::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_FIFO_Recv_Msg::dump"); - ACE_FIFO_Recv::dump (); -#endif /* ACE_HAS_DUMP */ -} - -// Note that persistent means "open FIFO for writing, as well as -// reading." This ensures that the FIFO never gets EOF, even if there -// aren't any writers at the moment! - -int -ACE_FIFO_Recv_Msg::open (const ACE_TCHAR *fifo_name, - int flags, - mode_t perms, - int persistent, - LPSECURITY_ATTRIBUTES sa) -{ - ACE_TRACE ("ACE_FIFO_Recv_Msg::open"); - - return ACE_FIFO_Recv::open (fifo_name, - flags, - perms, - persistent, - sa); -} - -ACE_FIFO_Recv_Msg::ACE_FIFO_Recv_Msg (void) -{ - ACE_TRACE ("ACE_FIFO_Recv_Msg::ACE_FIFO_Recv_Msg"); -} - -ACE_FIFO_Recv_Msg::ACE_FIFO_Recv_Msg (const ACE_TCHAR *fifo_name, - int flags, - mode_t perms, - int persistent, - LPSECURITY_ATTRIBUTES sa) -{ - ACE_TRACE ("ACE_FIFO_Recv_Msg::ACE_FIFO_Recv_Msg"); - - if (this->ACE_FIFO_Recv_Msg::open (fifo_name, - flags, - perms, - persistent, - sa) == -1) - ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("ACE_FIFO_Recv_Msg"))); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/FIFO_Recv_Msg.h b/externals/ace/FIFO_Recv_Msg.h deleted file mode 100644 index 6b691e97f10..00000000000 --- a/externals/ace/FIFO_Recv_Msg.h +++ /dev/null @@ -1,138 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file FIFO_Recv_Msg.h - * - * $Id: FIFO_Recv_Msg.h 84480 2009-02-16 18:58:16Z johnnyw $ - * - * @author Doug Schmidt - */ -//============================================================================= - - -#ifndef ACE_FIFO_RECV_MSG_H -#define ACE_FIFO_RECV_MSG_H -#include /**/ "ace/pre.h" - -#include "ace/FIFO_Recv.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Forward decls -class ACE_Str_Buf; - -/** - * @class ACE_FIFO_Recv_Msg - * - * @brief Receiver side for the record oriented C++ wrapper for UNIX FIFOs. - * - * This method works slightly differently on platforms with the - * @c ACE_HAS_STREAM_PIPES configuration setting than those without. - * With ACE_HAS_STREAM_PIPES, the @c getmsg() system function is used - * and it preserves message boundaries internally. Without - * @c ACE_HAS_STREAM_PIPES, the message boundaries are emulated by - * this class and ACE_FIFO_Send_Msg cooperating. The sending class - * first writes an integer number of bytes in the message, then the - * message. ACE_FIFO_Recv_Msg reads the count, then the data. - * The operational differences occur primarily when a message is larger - * than what a caller of this class requests. See recv() for details. - */ -class ACE_Export ACE_FIFO_Recv_Msg : public ACE_FIFO_Recv -{ -public: - // = Initialization methods. - /// Default constructor. - ACE_FIFO_Recv_Msg (void); - - /// Open up a record-oriented named pipe for reading. - ACE_FIFO_Recv_Msg (const ACE_TCHAR *rendezvous, - int flags = O_CREAT | O_RDONLY, - mode_t perms = ACE_DEFAULT_FILE_PERMS, - int persistent = 1, - LPSECURITY_ATTRIBUTES sa = 0); - - /// Open up a record-oriented named pipe for reading. - int open (const ACE_TCHAR *rendezvous, - int flags = O_CREAT | O_RDONLY, - mode_t perms = ACE_DEFAULT_FILE_PERMS, - int persistent = 1, - LPSECURITY_ATTRIBUTES sa = 0); - - /// Receive a message based on attributes in an ACE_Str_Buf. - /** - * @param msg Reference to an ACE_Str_Buf whose @c buf member points - * to the memory to receive the data and @c maxlen member - * contains the maximum number of bytes to receive. - * On return after successfully reading data, the - * @c len member contains the number of bytes received and - * placed in the buffer pointed to by @c msg.buf. - * - * @retval -1 Error; consult @c errno for specific error number. - * @return If the @c ACE_HAS_STREAM_PIPES configuration setting is - * defined, the return value is the number of bytes received - * in the message and will be the same as @c buf.len. - * The return value from the @c getmsg() system function - * is discarded. - * If @c ACE_HAS_STREAM_PIPES is not defined, the number - * of bytes in the message read from the FIFO is returned. - * If the message is larger than the maximum length - * requested in @c msg.maxlen, the return value reflects - * the entire message length, and the @c msg.len member - * reflects how many bytes were actually placed in the - * caller's buffer. Any part of the message longer than - * @c msg.maxlen is discarded. - */ - ssize_t recv (ACE_Str_Buf &msg); - - /// Receive a message based on buffer pointer and maximum size. - /** - * @param buf Pointer to the memory to receive the data. - * @param len The maximum number of bytes to receive. - * - * @retval -1 Error; consult @c errno for specific error number. - * @return The number of bytes received in the message. For messages - * that are larger than the requested maximum size, the - * behavior is different depending on the @c ACE_HAS_STREAM_PIPES - * configuration setting. With @c ACE_HAS_STREAM_PIPES, - * the return value will be the same as @arg len (this is - * also possible if the message is exactly the same length - * as @arg len, and the two cases are indistinguishable). - * Without @c ACE_HAS_STREAM_PIPES, the return value is - * the total length of the message, including bytes in - * excess of @arg len. The excess bytes are discarded. - */ - ssize_t recv (void *buf, size_t len); - -#if defined (ACE_HAS_STREAM_PIPES) - /// Recv @a data and @a cntl message via Stream pipes. - ssize_t recv (ACE_Str_Buf *data, - ACE_Str_Buf *cntl, - int *flags); - - /// Recv @a data and @a cntl message via Stream pipes in "band" mode. - ssize_t recv (int *band, - ACE_Str_Buf *data, - ACE_Str_Buf *cntl, - int *flags); -#endif /* ACE_HAS_STREAM_PIPES */ - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/FIFO_Recv_Msg.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_FIFO_RECV_MSG_H */ diff --git a/externals/ace/FIFO_Recv_Msg.inl b/externals/ace/FIFO_Recv_Msg.inl deleted file mode 100644 index 0a0b0673d38..00000000000 --- a/externals/ace/FIFO_Recv_Msg.inl +++ /dev/null @@ -1,137 +0,0 @@ -// -*- C++ -*- -// -// $Id: FIFO_Recv_Msg.inl 82559 2008-08-07 20:23:07Z parsons $ - -#include "ace/Min_Max.h" -#include "ace/OS_NS_stropts.h" -#include "ace/Truncate.h" - -#if !defined (ACE_HAS_STREAM_PIPES) -#include "ace/OS_NS_unistd.h" -#endif - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE ssize_t -ACE_FIFO_Recv_Msg::recv (ACE_Str_Buf &recv_msg) -{ - ACE_TRACE ("ACE_FIFO_Recv_Msg::recv"); -#if defined (ACE_HAS_STREAM_PIPES) - int i = 0; - if (ACE_OS::getmsg (this->get_handle (), - (strbuf *) 0, - (strbuf *) &recv_msg, - &i) == -1) - { - return -1; - } - else - { - return recv_msg.len; - } -#else /* Do the ol' 2-read trick... */ - if (ACE_OS::read (this->get_handle (), - (char *) &recv_msg.len, - sizeof recv_msg.len) != sizeof recv_msg.len) - { - return -1; - } - else - { - size_t remaining = static_cast (recv_msg.len); - size_t requested = static_cast (recv_msg.maxlen); - ssize_t recv_len = ACE_OS::read (this->get_handle (), - (char *) recv_msg.buf, - ACE_MIN (remaining, requested)); - - if (recv_len == -1) - { - return -1; - } - - // Tell caller what's really in the buffer. - recv_msg.len = static_cast (recv_len); - - // If there are more bytes remaining in the message, read them and - // throw them away. Leaving them in the FIFO would make it difficult - // to find the start of the next message in the fifo. - // Since the ACE_HAS_STREAM_PIPES version of this method doesn't - // return getmsg()'s indication of "data remaining", don't worry about - // saving the indication here either to read the remainder later. - size_t total_msg_size = remaining; - remaining -= recv_len; - - while (remaining > 0) - { - const size_t throw_away = 1024; - char dev_null[throw_away]; - recv_len = ACE_OS::read (this->get_handle (), - dev_null, - ACE_MIN (remaining, throw_away)); - - if (recv_len == -1) - { - break; - } - - remaining -= recv_len; - } - - return ACE_Utils::truncate_cast (total_msg_size); - } -#endif /* ACE_HAS_STREAM_PIPES */ -} - -ACE_INLINE ssize_t -ACE_FIFO_Recv_Msg::recv (void *buf, size_t max_len) -{ - ACE_TRACE ("ACE_FIFO_Recv_Msg::recv"); - ACE_Str_Buf recv_msg ((char *) buf, 0, static_cast (max_len)); - - return this->recv (recv_msg); -} - -#if defined (ACE_HAS_STREAM_PIPES) -ACE_INLINE ssize_t -ACE_FIFO_Recv_Msg::recv (ACE_Str_Buf *data, - ACE_Str_Buf *cntl, - int *flags) -{ - ACE_TRACE ("ACE_FIFO_Recv_Msg::recv"); - if (ACE_OS::getmsg (this->get_handle (), - (strbuf *) cntl, - (strbuf *) data, - flags) == -1) - { - return -1; - } - else - { - return (cntl == 0 ? 0 : cntl->len) + (data == 0 ? 0 : data->len); - } -} - -ACE_INLINE ssize_t -ACE_FIFO_Recv_Msg::recv (int *band, - ACE_Str_Buf *data, - ACE_Str_Buf *cntl, - int *flags) -{ - ACE_TRACE ("ACE_FIFO_Recv_Msg::recv"); - - if (ACE_OS::getpmsg (this->get_handle (), - (strbuf *) cntl, - (strbuf *) data, - band, - flags) == -1) - { - return -1; - } - else - { - return (cntl == 0 ? 0 : cntl->len) + (data == 0 ? 0 : data->len); - } -} -#endif /* ACE_HAS_STREAM_PIPES */ - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/FIFO_Send.cpp b/externals/ace/FIFO_Send.cpp deleted file mode 100644 index 720e63c5425..00000000000 --- a/externals/ace/FIFO_Send.cpp +++ /dev/null @@ -1,58 +0,0 @@ -// $Id: FIFO_Send.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/FIFO_Send.h" -#include "ace/Log_Msg.h" - -#if !defined (__ACE_INLINE__) -#include "ace/FIFO_Send.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID(ace, FIFO_Send, "$Id: FIFO_Send.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_FIFO_Send) - -void -ACE_FIFO_Send::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_FIFO_Send::dump"); - ACE_FIFO::dump (); -#endif /* ACE_HAS_DUMP */ -} - -ACE_FIFO_Send::ACE_FIFO_Send (void) -{ -// ACE_TRACE ("ACE_FIFO_Send::ACE_FIFO_Send"); -} - -int -ACE_FIFO_Send::open (const ACE_TCHAR *rendezvous_name, - int flags, - mode_t perms, - LPSECURITY_ATTRIBUTES sa) -{ - ACE_TRACE ("ACE_FIFO_Send::open"); - return ACE_FIFO::open (rendezvous_name, - flags | O_WRONLY, - perms, - sa); -} - -ACE_FIFO_Send::ACE_FIFO_Send (const ACE_TCHAR *fifo_name, - int flags, - mode_t perms, - LPSECURITY_ATTRIBUTES sa) -{ - ACE_TRACE ("ACE_FIFO_Send::ACE_FIFO_Send"); - if (this->ACE_FIFO_Send::open (fifo_name, - flags, - perms, - sa) == -1) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_FIFO_Send::ACE_FIFO_Send"))); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/FIFO_Send.h b/externals/ace/FIFO_Send.h deleted file mode 100644 index cc0fc282f83..00000000000 --- a/externals/ace/FIFO_Send.h +++ /dev/null @@ -1,75 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file FIFO_Send.h - * - * $Id: FIFO_Send.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Doug Schmidt - */ -//========================================================================== - - -#ifndef ACE_FIFO_SEND_H -#define ACE_FIFO_SEND_H - -#include /**/ "ace/pre.h" - -#include "ace/FIFO.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/os_fcntl.h" -#include "ace/Default_Constants.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_FIFO_Send - * - * @brief Sender side for the bytestream C++ wrapper for UNIX FIFOs - */ -class ACE_Export ACE_FIFO_Send : public ACE_FIFO -{ -public: - // = Initialization methods. - /// Default constructor. - ACE_FIFO_Send (void); - - /// Open up a bytestream named pipe for writing. - ACE_FIFO_Send (const ACE_TCHAR *rendezvous, - int flags = O_WRONLY, - mode_t perms = ACE_DEFAULT_FILE_PERMS, - LPSECURITY_ATTRIBUTES sa = 0); - - /// Open up a bytestream named pipe for writing. - int open (const ACE_TCHAR *rendezvous, - int flags = O_WRONLY, - mode_t perms = ACE_DEFAULT_FILE_PERMS, - LPSECURITY_ATTRIBUTES sa = 0); - - /// Send @a buf of up to @a len bytes. - ssize_t send (const void *buf, size_t len); - - /// Send @a buf of exactly @a len bytes (block until done). - ssize_t send_n (const void *buf, size_t len); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/FIFO_Send.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" - -#endif /* ACE_FIFO_SEND_H */ diff --git a/externals/ace/FIFO_Send.inl b/externals/ace/FIFO_Send.inl deleted file mode 100644 index a01facd61f0..00000000000 --- a/externals/ace/FIFO_Send.inl +++ /dev/null @@ -1,24 +0,0 @@ -// -*- C++ -*- -// -// $Id: FIFO_Send.inl 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/ACE.h" -#include "ace/OS_NS_unistd.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE ssize_t -ACE_FIFO_Send::send (const void *buf, size_t len) -{ - ACE_TRACE ("ACE_FIFO_Send::send"); - return ACE_OS::write (this->get_handle (), (const char *) buf, len); -} - -ACE_INLINE ssize_t -ACE_FIFO_Send::send_n (const void *buf, size_t n) -{ - ACE_TRACE ("ACE_FIFO_Send::send_n"); - return ACE::send_n (this->get_handle (), buf, n); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/FIFO_Send_Msg.cpp b/externals/ace/FIFO_Send_Msg.cpp deleted file mode 100644 index b3bbae00aed..00000000000 --- a/externals/ace/FIFO_Send_Msg.cpp +++ /dev/null @@ -1,80 +0,0 @@ -// $Id: FIFO_Send_Msg.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/FIFO_Send_Msg.h" - -#include "ace/Log_Msg.h" -#include "ace/OS_NS_sys_uio.h" - -#if !defined (__ACE_INLINE__) -#include "ace/FIFO_Send_Msg.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID(ace, FIFO_Send_Msg, "$Id: FIFO_Send_Msg.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_FIFO_Send_Msg) - -void -ACE_FIFO_Send_Msg::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_FIFO_Send_Msg::dump"); - ACE_FIFO_Send::dump (); -#endif /* ACE_HAS_DUMP */ -} - -ssize_t -ACE_FIFO_Send_Msg::send (const ACE_Str_Buf &send_msg) -{ - // ACE_TRACE ("ACE_FIFO_Send_Msg::send"); -#if defined (ACE_HAS_STREAM_PIPES) - if (ACE_OS::putmsg (this->get_handle (), - (strbuf *) 0, - (strbuf *) &send_msg, - 0) == -1) - return -1; - else - return send_msg.len; -#else - iovec iov[2]; - - iov[0].iov_base = (char *) &send_msg.len; - iov[0].iov_len = sizeof send_msg.len; - - iov[1].iov_base = (char *) send_msg.buf; - iov[1].iov_len = static_cast (send_msg.len); - - ssize_t sent = ACE_OS::writev (this->get_handle (), iov, 2); - if (sent > 0) - sent -= iov[0].iov_len; // Don't count the length we added. - return sent; -#endif /* ACE_HAS_STREAM_PIPES */ -} - -ACE_FIFO_Send_Msg::ACE_FIFO_Send_Msg (void) -{ -// ACE_TRACE ("ACE_FIFO_Send_Msg::ACE_FIFO_Send_Msg"); -} - -int -ACE_FIFO_Send_Msg::open (const ACE_TCHAR *fifo_name, - int flags, - mode_t perms, - LPSECURITY_ATTRIBUTES sa) -{ - ACE_TRACE ("ACE_FIFO_Send_Msg::open"); - return ACE_FIFO_Send::open (fifo_name, flags | O_WRONLY, perms, sa); -} - -ACE_FIFO_Send_Msg::ACE_FIFO_Send_Msg (const ACE_TCHAR *fifo_name, - int flags, - mode_t perms, - LPSECURITY_ATTRIBUTES sa) -{ - ACE_TRACE ("ACE_FIFO_Send_Msg::ACE_FIFO_Send_Msg"); - if (this->ACE_FIFO_Send_Msg::open (fifo_name, flags, perms, sa) == -1) - ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("ACE_FIFO_Send_Msg"))); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/FIFO_Send_Msg.h b/externals/ace/FIFO_Send_Msg.h deleted file mode 100644 index 434ae108130..00000000000 --- a/externals/ace/FIFO_Send_Msg.h +++ /dev/null @@ -1,91 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file FIFO_Send_Msg.h - * - * $Id: FIFO_Send_Msg.h 84480 2009-02-16 18:58:16Z johnnyw $ - * - * @author Doug Schmidt - */ -//============================================================================= - - -#ifndef ACE_FIFO_SEND_MSG_H -#define ACE_FIFO_SEND_MSG_H -#include /**/ "ace/pre.h" - -#include "ace/FIFO_Send.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_STREAM_PIPES) -# include "ace/OS_NS_stropts.h" -#endif /* ACE_HAS_STREAM_PIPES */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Forward Decls -class ACE_Str_Buf; - -/** - * @class ACE_FIFO_Send_Msg - * - * @brief Sender side for the Record oriented C++ wrapper for UNIX - * FIFOs. - */ -class ACE_Export ACE_FIFO_Send_Msg : public ACE_FIFO_Send -{ -public: - // = Initialization methods. - /// Default constructor. - ACE_FIFO_Send_Msg (void); - - /// Open up a record-oriented named pipe for writing. - ACE_FIFO_Send_Msg (const ACE_TCHAR *rendezvous, - int flags = O_WRONLY, - mode_t perms = ACE_DEFAULT_FILE_PERMS, - LPSECURITY_ATTRIBUTES sa = 0); - - /// Open up a record-oriented named pipe for writing. - int open (const ACE_TCHAR *rendezvous, - int flags = O_WRONLY, - mode_t perms = ACE_DEFAULT_FILE_PERMS, - LPSECURITY_ATTRIBUTES sa = 0); - - /// Send @a buf of up to @a len bytes. - ssize_t send (const ACE_Str_Buf &msg); - - /// Send @a buf of exactly @a len bytes (block until done). - ssize_t send (const void *buf, size_t len); - -#if defined (ACE_HAS_STREAM_PIPES) - /// Send @a data and @a cntl message via Stream pipes. - ssize_t send (const ACE_Str_Buf *data, - const ACE_Str_Buf *cntl = 0, - int flags = 0); - - /// Send @a data and @a cntl message via Stream pipes in "band" mode. - ssize_t send (int band, - const ACE_Str_Buf *data, - const ACE_Str_Buf *cntl = 0, - int flags = MSG_BAND); -#endif /* ACE_HAS_STREAM_PIPES */ - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/FIFO_Send_Msg.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_FIFO_SEND_MSG_H */ diff --git a/externals/ace/FIFO_Send_Msg.inl b/externals/ace/FIFO_Send_Msg.inl deleted file mode 100644 index 0a34e64e370..00000000000 --- a/externals/ace/FIFO_Send_Msg.inl +++ /dev/null @@ -1,53 +0,0 @@ -// -*- C++ -*- -// -// $Id: FIFO_Send_Msg.inl 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/OS_NS_stropts.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE ssize_t -ACE_FIFO_Send_Msg::send (const void *buf, size_t len) -{ - ACE_TRACE ("ACE_FIFO_Send_Msg::send"); - ACE_Str_Buf send_msg ((char *) buf, static_cast (len)); - - return this->send (send_msg); -} - -#if defined (ACE_HAS_STREAM_PIPES) -ACE_INLINE ssize_t -ACE_FIFO_Send_Msg::send (const ACE_Str_Buf *data, - const ACE_Str_Buf *cntl, - int flags) -{ - ACE_TRACE ("ACE_FIFO_Send_Msg::send"); - if (ACE_OS::putmsg (this->get_handle (), - (strbuf *) cntl, - (strbuf *) data, - flags) == -1) - return-1; - else - return (cntl == 0 ? 0 : cntl->len) + (data == 0 ? 0 : data->len); -} - -ACE_INLINE ssize_t -ACE_FIFO_Send_Msg::send (int band, - const ACE_Str_Buf *data, - const ACE_Str_Buf *cntl, - int flags) -{ - ACE_TRACE ("ACE_FIFO_Send_Msg::send"); - - if (ACE_OS::putpmsg (this->get_handle (), - (strbuf *) cntl, - (strbuf *) data, - band, - flags) == -1) - return -1; - else - return (cntl == 0 ? 0 : cntl->len) + (data == 0 ? 0 : data->len); -} -#endif /* ACE_HAS_STREAM_PIPES */ - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/FILE.cpp b/externals/ace/FILE.cpp deleted file mode 100644 index 8fe88d1b09c..00000000000 --- a/externals/ace/FILE.cpp +++ /dev/null @@ -1,147 +0,0 @@ -// $Id: FILE.cpp 80826 2008-03-04 14:51:23Z wotte $ - -/* Defines the member functions for the base class of the ACE_IO_SAP - ACE_FILE abstraction. */ - -#include "ace/FILE.h" - -#include "ace/OS_NS_unistd.h" -#include "ace/OS_NS_sys_stat.h" - -#if !defined (__ACE_INLINE__) -#include "ace/FILE.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID(ace, FILE, "$Id: FILE.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_FILE) - -void -ACE_FILE::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_FILE::dump"); - ACE_IO_SAP::dump (); -#endif /* ACE_HAS_DUMP */ -} - -// This is the do-nothing constructor. - -ACE_FILE::ACE_FILE (void) -{ - ACE_TRACE ("ACE_FILE::ACE_FILE"); -} - -// Close the file - -int -ACE_FILE::close (void) -{ - ACE_TRACE ("ACE_FILE::close"); - int result = 0; - - if (this->get_handle () != ACE_INVALID_HANDLE) - { - result = ACE_OS::close (this->get_handle ()); - this->set_handle (ACE_INVALID_HANDLE); - } - return result; -} - -int -ACE_FILE::get_info (ACE_FILE_Info *finfo) -{ - ACE_TRACE ("ACE_FILE::get_info"); - ACE_stat filestatus; - - int const result = ACE_OS::fstat (this->get_handle (), &filestatus); - - if (result == 0) - { - finfo->mode_ = filestatus.st_mode; - finfo->nlink_ = filestatus.st_nlink; - finfo->size_ = filestatus.st_size; - } - - return result; -} - -int -ACE_FILE::get_info (ACE_FILE_Info &finfo) -{ - ACE_TRACE ("ACE_FILE::get_info"); - - return this->get_info (&finfo); -} - -int -ACE_FILE::truncate (ACE_OFF_T length) -{ - ACE_TRACE ("ACE_FILE::truncate"); - return ACE_OS::ftruncate (this->get_handle (), length); -} - -ACE_OFF_T -ACE_FILE::seek (ACE_OFF_T offset, int startpos) -{ - return ACE_OS::lseek (this->get_handle (), offset, startpos); -} - -ACE_OFF_T -ACE_FILE::tell (void) -{ - ACE_TRACE ("ACE_FILE::tell"); - return ACE_OS::lseek (this->get_handle (), 0, SEEK_CUR); -} - -// Return the local endpoint address. - -int -ACE_FILE::get_local_addr (ACE_Addr &addr) const -{ - ACE_TRACE ("ACE_FILE::get_local_addr"); - - // Perform the downcast since had better be an - // . - ACE_FILE_Addr *file_addr = - dynamic_cast (&addr); - - if (file_addr == 0) - return -1; - else - { - *file_addr = this->addr_; - return 0; - } -} - -// Return the same result as . - -int -ACE_FILE::get_remote_addr (ACE_Addr &addr) const -{ - ACE_TRACE ("ACE_FILE::get_remote_addr"); - - return this->get_local_addr (addr); -} - -int -ACE_FILE::remove (void) -{ - ACE_TRACE ("ACE_FILE::remove"); - - this->close (); - return ACE_OS::unlink (this->addr_.get_path_name ()); -} - -int -ACE_FILE::unlink (void) -{ - ACE_TRACE ("ACE_FILE::unlink"); - - return ACE_OS::unlink (this->addr_.get_path_name ()); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/FILE.h b/externals/ace/FILE.h deleted file mode 100644 index 407a03379e5..00000000000 --- a/externals/ace/FILE.h +++ /dev/null @@ -1,139 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file FILE.h - * - * $Id: FILE.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Gerhard Lenzer - */ -//============================================================================= - -#ifndef ACE_FILE_H -#define ACE_FILE_H -#include /**/ "ace/pre.h" - -#include "ace/IO_SAP.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/FILE_Addr.h" - -// The following is necessary since many C++ compilers don't support -// typedef'd types inside of classes used as formal template -// arguments... ;-(. Luckily, using the C++ preprocessor I can hide -// most of this nastiness! - -#if defined (ACE_HAS_TEMPLATE_TYPEDEFS) -#define ACE_FILE_CONNECTOR ACE_FILE_Connector -#define ACE_FILE_STREAM ACE_FILE_IO -#else /* TEMPLATES are broken (must be a cfront-based compiler...) */ -#define ACE_FILE_CONNECTOR ACE_FILE_Connector, ACE_FILE_Addr -#define ACE_FILE_STREAM ACE_FILE_IO, ACE_FILE_Addr -#endif /* ACE_TEMPLATE_TYPEDEFS */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_FILE_Info - * - * @brief Abstracts basic OS FILE information. - */ -class ACE_Export ACE_FILE_Info -{ -public: - /// Mode of file - mode_t mode_; - - /// No of links - nlink_t nlink_; - - /// Size of file - ACE_OFF_T size_; -}; - -/** - * @class ACE_FILE - * - * @brief Defines the core methods of the ACE_FILE abstraction. - */ -class ACE_Export ACE_FILE : public ACE_IO_SAP -{ -public: - /// Close the ACE_FILE handle without removing the ACE_FILE from - /// the file system. - int close (void); - - /// Close and remove the ACE_FILE from the file system. - int remove (void); - - /// Remove the ACE_FILE from the file system without closing the - /// ACE_FILE handle. - int unlink (void); - - /// Get information on this ACE_FILE. - int get_info (ACE_FILE_Info *finfo); - - /// Get information on this ACE_FILE. - int get_info (ACE_FILE_Info &finfo); - - /// Set filesize to length byte. - int truncate (ACE_OFF_T length); - - /** - * Sets the file pointer as follows: - * o If is , the pointer is set to @a offset - * bytes. - * - * o If is , the pointer is set to its - * current location plus @a offset. - * - * o If is , the pointer is set to the size - * of the file plus offset. - */ - ACE_OFF_T seek (ACE_OFF_T offset, - int whence = SEEK_CUR); - - /// Return an offset for the file handle. - ACE_OFF_T tell (void); - - /** - * Disable signal @a signum - * This is here to prevent Win32 from - * disabling SPIPE using socket calls - */ - int disable (int signum) const ; - - /// Return the local endpoint address in the referenced ACE_Addr. - /// Returns 0 if successful, else -1. - int get_local_addr (ACE_Addr &) const; - - /// Return the same thing as get_local_addr(). - int get_remote_addr (ACE_Addr &) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - /// Ensure that this class is only created by the - /// ACE_FILE_Connector. - ACE_FILE (void); - - /// File we are "connected" with... - ACE_FILE_Addr addr_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/FILE.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_FILE_H */ diff --git a/externals/ace/FILE.inl b/externals/ace/FILE.inl deleted file mode 100644 index 288374afc58..00000000000 --- a/externals/ace/FILE.inl +++ /dev/null @@ -1,18 +0,0 @@ -// -*- C++ -*- -// -// $Id: FILE.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE int -ACE_FILE::disable (int signum) const -{ -#if defined (ACE_WIN32) - ACE_UNUSED_ARG (signum) ; - return 0 ; -#else /* ACE_WIN32 */ - return ACE_IO_SAP::disable (signum) ; -#endif /* ACE_WIN32 */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/FILE_Addr.cpp b/externals/ace/FILE_Addr.cpp deleted file mode 100644 index 6d8fbeb775b..00000000000 --- a/externals/ace/FILE_Addr.cpp +++ /dev/null @@ -1,124 +0,0 @@ -// $Id: FILE_Addr.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/FILE_Addr.h" -#include "ace/Lib_Find.h" -#include "ace/Log_Msg.h" -#include "ace/OS_NS_stdlib.h" -#include "ace/OS_NS_string.h" -#include "ace/os_include/sys/os_socket.h" - -#if !defined (__ACE_INLINE__) -#include "ace/FILE_Addr.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID(ace, FILE_Addr, "$Id: FILE_Addr.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_FILE_Addr) - -ACE_FILE_Addr::ACE_FILE_Addr (void) - : ACE_Addr (AF_FILE, sizeof this->filename_ / sizeof (ACE_TCHAR)) -{ - this->filename_[0] = '\0'; -} - -int -ACE_FILE_Addr::set (const ACE_FILE_Addr &sa) -{ - if (sa.get_type () == AF_ANY) - { -#if defined (ACE_DEFAULT_TEMP_FILE) - // Create a temporary file. - ACE_OS::strcpy (this->filename_, - ACE_DEFAULT_TEMP_FILE); -#else /* ACE_DEFAULT_TEMP_FILE */ - if (ACE::get_temp_dir (this->filename_, MAXPATHLEN - 15) == -1) - // -15 for ace-file-XXXXXX - { - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("Temporary path too long, ") - ACE_TEXT ("defaulting to current directory\n"))); - this->filename_[0] = 0; - } - - // Add the filename to the end - ACE_OS::strcat (this->filename_, ACE_TEXT ("ace-fileXXXXXX")); - -#endif /* ACE_DEFAULT_TEMP_FILE */ - - if (ACE_OS::mktemp (this->filename_) == 0) - return -1; - this->base_set (AF_FILE, - static_cast (ACE_OS::strlen (this->filename_) + 1)); - } - else - { - (void)ACE_OS::strsncpy (this->filename_, sa.filename_, sa.get_size ()); - - this->base_set (sa.get_type (), sa.get_size ()); - } - return 0; -} - -// Copy constructor. - -ACE_FILE_Addr::ACE_FILE_Addr (const ACE_FILE_Addr &sa) - : ACE_Addr (AF_FILE, sizeof this->filename_) -{ - this->set (sa); -} - -int -ACE_FILE_Addr::set (const ACE_TCHAR *filename) -{ - this->ACE_Addr::base_set (AF_FILE, - static_cast (ACE_OS::strlen (filename) + 1)); - (void) ACE_OS::strsncpy (this->filename_, - filename, - sizeof this->filename_ / sizeof (ACE_TCHAR)); - return 0; -} - -ACE_FILE_Addr & -ACE_FILE_Addr::operator= (const ACE_FILE_Addr &sa) -{ - if (this != &sa) - this->set (sa); - return *this; -} - -// Create a ACE_Addr from a ACE_FILE pathname. - -ACE_FILE_Addr::ACE_FILE_Addr (const ACE_TCHAR *filename) -{ - this->set (filename); -} - -int -ACE_FILE_Addr::addr_to_string (ACE_TCHAR *s, size_t len) const -{ - ACE_OS::strsncpy (s, this->filename_, len); - return 0; -} - -// Return the address. - -void * -ACE_FILE_Addr::get_addr (void) const -{ - return (void *)&this->filename_; -} - -void -ACE_FILE_Addr::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_FILE_Addr::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("filename_ = %s"), this->filename_)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/FILE_Addr.h b/externals/ace/FILE_Addr.h deleted file mode 100644 index 432275b9665..00000000000 --- a/externals/ace/FILE_Addr.h +++ /dev/null @@ -1,89 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file FILE_Addr.h - * - * $Id: FILE_Addr.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_FILE_ADDR_H -#define ACE_FILE_ADDR_H -#include /**/ "ace/pre.h" - -#include "ace/Addr.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Flag_Manip.h" -#include "ace/os_include/os_dirent.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_FILE_Addr - * - * @brief Defines the FILE address family address format. - */ -class ACE_Export ACE_FILE_Addr : public ACE_Addr -{ -public: - // = Initialization methods. - /// Default constructor. - ACE_FILE_Addr (void); - - /// Copy constructor. - ACE_FILE_Addr (const ACE_FILE_Addr &sa); - - /// Acts like a copy constructor. If @a sa == ACE_Addr::sap_any then - /// create a temporary filename using ACE_OS::mktemp. - int set (const ACE_FILE_Addr &sa); - - /// Create a ACE_FILE_Addr from a pathname. - explicit ACE_FILE_Addr (const ACE_TCHAR *filename); - - /// Create a ACE_FILE_Addr from a pathname. - int set (const ACE_TCHAR *filename); - - /// Assignment operator. - ACE_FILE_Addr &operator= (const ACE_FILE_Addr &); - - /// Return a pointer to the address. - virtual void *get_addr (void) const; - - /// Transform the current address into string format. - virtual int addr_to_string (ACE_TCHAR *addr, size_t) const; - - /// Compare two addresses for equality. - bool operator == (const ACE_FILE_Addr &SAP) const; - - /// Compare two addresses for inequality. - bool operator != (const ACE_FILE_Addr &SAP) const; - - /// Return the path name used for the rendezvous point. - const ACE_TCHAR *get_path_name (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - /// Name of the file. - ACE_TCHAR filename_[MAXPATHLEN + 1]; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/FILE_Addr.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_FILE_ADDR_H */ diff --git a/externals/ace/FILE_Addr.inl b/externals/ace/FILE_Addr.inl deleted file mode 100644 index 0ae7d31d278..00000000000 --- a/externals/ace/FILE_Addr.inl +++ /dev/null @@ -1,34 +0,0 @@ -// -*- C++ -*- -// -// $Id: FILE_Addr.inl 80826 2008-03-04 14:51:23Z wotte $ - - -#include "ace/SString.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Compare two addresses for equality. - -ACE_INLINE bool -ACE_FILE_Addr::operator == (const ACE_FILE_Addr &sap) const -{ - return ACE_OS::strcmp (this->filename_, sap.filename_) == 0; -} - -// Compare two addresses for inequality. - -ACE_INLINE bool -ACE_FILE_Addr::operator != (const ACE_FILE_Addr &sap) const -{ - return !((*this) == sap); // This is lazy, of course... ;-) -} - -// Return the path name used for the rendezvous point. - -ACE_INLINE const ACE_TCHAR * -ACE_FILE_Addr::get_path_name (void) const -{ - return this->filename_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/FILE_Connector.cpp b/externals/ace/FILE_Connector.cpp deleted file mode 100644 index b59b1e8913d..00000000000 --- a/externals/ace/FILE_Connector.cpp +++ /dev/null @@ -1,84 +0,0 @@ -// $Id: FILE_Connector.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/FILE_Connector.h" -#include "ace/Handle_Ops.h" -#include "ace/OS_NS_stdlib.h" - -#if !defined (__ACE_INLINE__) -#include "ace/FILE_Connector.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID(ace, FILE_Connector, "$Id: FILE_Connector.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_FILE_Connector) - -void -ACE_FILE_Connector::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_FILE_Connector::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n"))); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -ACE_FILE_Connector::ACE_FILE_Connector (void) -{ - ACE_TRACE ("ACE_FILE_Connector::ACE_FILE_Connector"); -} - -int -ACE_FILE_Connector::connect (ACE_FILE_IO &new_io, - const ACE_FILE_Addr &remote_sap, - ACE_Time_Value *timeout, - const ACE_Addr &, - int, - int flags, - int perms) -{ - ACE_TRACE ("ACE_FILE_Connector::connect"); - ACE_ASSERT (new_io.get_handle () == ACE_INVALID_HANDLE); - - ACE_HANDLE handle = ACE_INVALID_HANDLE; - - // Check to see if caller has requested that we create the filename. - if (reinterpret_cast ( - const_cast (remote_sap)) == ACE_Addr::sap_any) - { - // Create a new temporary file. - // Use ACE_OS::mkstemp() if it is available since it avoids a - // race condition, and subsequently a security hole due to that - // race condition (specifically, a denial-of-service attack). - // - // However, using mkstemp() prevents us from doing a timed open - // since it opens the file for us. Better to avoid the race - // condition. - char filename[] = "ace-file-XXXXXX"; - - handle = ACE_OS::mkstemp (filename); // mkstemp() replaces "XXXXXX" - - if (handle == ACE_INVALID_HANDLE - || new_io.addr_.set (ACE_TEXT_CHAR_TO_TCHAR (filename)) != 0) - return -1; - - new_io.set_handle (handle); - - return 0; - } - else - new_io.addr_ = remote_sap; // class copy. - - handle = ACE::handle_timed_open (timeout, - new_io.addr_.get_path_name (), - flags, - perms); - - new_io.set_handle (handle); - return handle == ACE_INVALID_HANDLE ? -1 : 0; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/FILE_Connector.h b/externals/ace/FILE_Connector.h deleted file mode 100644 index 624ab3d6a5f..00000000000 --- a/externals/ace/FILE_Connector.h +++ /dev/null @@ -1,113 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file FILE_Connector.h - * - * $Id: FILE_Connector.h 82723 2008-09-16 09:35:44Z johnnyw $ - * - * @author Doug Schmidt - */ -//============================================================================= - -#ifndef ACE_FILE_CONNECTOR_H -#define ACE_FILE_CONNECTOR_H -#include /**/ "ace/pre.h" - -#include "ace/FILE_IO.h" -#include "ace/Log_Msg.h" -#include "ace/os_include/os_fcntl.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_FILE_Connector - * - * @brief Defines an active connection factory for the ACE_FILE wrappers. - * - * Note that the O_APPEND flag is only partly supported on Win32. If - * you specify O_APPEND, then the file pointer will be positioned at - * the end of the file initially during open, but it is not - * re-positioned at the end prior to each write, as specified by - * POSIX. This is generally good enough for typical situations, but - * it is ``not quite right'' in its semantics. - */ -class ACE_Export ACE_FILE_Connector -{ -public: - // = Initialization methods. - /// Default constructor. - ACE_FILE_Connector (void); - - /** - * Actively ``connect'' and produce a @a new_io ACE_FILE_IO object - * if things go well. The @a remote_sap is the file that we are - * trying to create/open. If it's the default value of - * ACE_Addr::sap_any then the user is letting the OS create the - * filename (via ). The @a timeout is the amount of - * time to wait to create/open the file. If it's 0 then we block - * indefinitely. If *timeout == {0, 0} then the file is created - * using non-blocking mode. If *timeout > {0, 0} then this is the - * maximum amount of time to wait before timing out. The - * @a local_sap and @a reuse_addr parameters are ignored. The @a flags - * and @a perms arguments are passed down to the - * method. - */ - ACE_FILE_Connector (ACE_FILE_IO &new_io, - const ACE_FILE_Addr &remote_sap, - ACE_Time_Value *timeout = 0, - const ACE_Addr &local_sap = ACE_Addr::sap_any, - int reuse_addr = 0, - int flags = O_RDWR | O_CREAT, - int perms = ACE_DEFAULT_FILE_PERMS); - - /** - * Actively ``connect'' and produce a @a new_io object - * if things go well. The @a remote_sap is the file that we are - * trying to create/open. If it's the default value of - * ACE_Addr::sap_any then the user is letting the OS create the - * filename (via ). The @a timeout is the amount of - * time to wait to create/open the file. If it's 0 then we block - * indefinitely. If *timeout == {0, 0} then the file is created - * using non-blocking mode. In this case, if the create/open can't - * be done immediately the value of -1 is returned with . If *timeout > {0, 0} then this is the maximum amount of - * time to wait before timing out. If the time expires before the - * connection is made @c errno == ETIME. The @a local_sap and - * @a reuse_addr parameters are ignored. The @a flags and @a perms - * arguments are passed down to the method. - */ - int connect (ACE_FILE_IO &new_io, - const ACE_FILE_Addr &remote_sap, - ACE_Time_Value *timeout = 0, - const ACE_Addr &local_sap = ACE_Addr::sap_any, - int reuse_addr = 0, - int flags = O_RDWR | O_CREAT, - int perms = ACE_DEFAULT_FILE_PERMS); - - /// Resets any event associations on this handle - bool reset_new_handle (ACE_HANDLE handle); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - - // = Meta-type "trait" information. - typedef ACE_FILE_Addr PEER_ADDR; - typedef ACE_FILE_IO PEER_STREAM; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/FILE_Connector.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_FILE_CONNECTOR_H */ diff --git a/externals/ace/FILE_Connector.inl b/externals/ace/FILE_Connector.inl deleted file mode 100644 index 953f661fb05..00000000000 --- a/externals/ace/FILE_Connector.inl +++ /dev/null @@ -1,35 +0,0 @@ -// -*- C++ -*- -// -// $Id: FILE_Connector.inl 82723 2008-09-16 09:35:44Z johnnyw $ - -// Creates a Local ACE_FILE. - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE -ACE_FILE_Connector::ACE_FILE_Connector (ACE_FILE_IO &new_io, - const ACE_FILE_Addr &remote_sap, - ACE_Time_Value *timeout, - const ACE_Addr &local_sap, - int reuse_addr, - int flags, - int perms) -{ - ACE_TRACE ("ACE_FILE_Connector::ACE_FILE_Connector"); - if (this->connect (new_io, remote_sap, timeout, local_sap, - reuse_addr, flags, perms) == ACE_IO_SAP::INVALID_HANDLE - && timeout != 0 && !(errno == EWOULDBLOCK || errno == ETIME)) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("address %s, %p\n"), - remote_sap.get_path_name (), - ACE_TEXT ("ACE_FILE_IO"))); -} - -ACE_INLINE bool -ACE_FILE_Connector::reset_new_handle (ACE_HANDLE) -{ - // Nothing to do here since the handle is not a socket - return false; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/FILE_IO.cpp b/externals/ace/FILE_IO.cpp deleted file mode 100644 index d6bf084dfae..00000000000 --- a/externals/ace/FILE_IO.cpp +++ /dev/null @@ -1,145 +0,0 @@ -// $Id: FILE_IO.cpp 82559 2008-08-07 20:23:07Z parsons $ - -#include "ace/FILE_IO.h" - -#include "ace/Log_Msg.h" -#include "ace/OS_NS_sys_stat.h" -#include "ace/OS_Memory.h" -#include "ace/Truncate.h" - -#if !defined (__ACE_INLINE__) -#include "ace/FILE_IO.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID(ace, FILE_IO, "$Id: FILE_IO.cpp 82559 2008-08-07 20:23:07Z parsons $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_FILE_IO) - -void -ACE_FILE_IO::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_FILE_IO::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - this->addr_.dump (); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -// Simple-minded do nothing constructor. - -ACE_FILE_IO::ACE_FILE_IO (void) -{ - ACE_TRACE ("ACE_FILE_IO::ACE_FILE_IO"); -} - -// Send N char *ptrs and int lengths. Note that the char *'s precede -// the ints (basically, an varargs version of writev). The count N is -// the *total* number of trailing arguments, *not* a couple of the -// number of tuple pairs! - -ssize_t -ACE_FILE_IO::send (size_t n, ...) const -{ - ACE_TRACE ("ACE_FILE_IO::send"); - va_list argp; - int total_tuples = ACE_Utils::truncate_cast (n / 2); - iovec *iovp = 0; -#if defined (ACE_HAS_ALLOCA) - iovp = (iovec *) alloca (total_tuples * sizeof (iovec)); -#else - ACE_NEW_RETURN (iovp, - iovec[total_tuples], - -1); -#endif /* !defined (ACE_HAS_ALLOCA) */ - - va_start (argp, n); - - for (int i = 0; i < total_tuples; i++) - { - iovp[i].iov_base = va_arg (argp, char *); - iovp[i].iov_len = va_arg (argp, int); - } - - ssize_t result = ACE_OS::writev (this->get_handle (), - iovp, - total_tuples); -#if !defined (ACE_HAS_ALLOCA) - delete [] iovp; -#endif /* !defined (ACE_HAS_ALLOCA) */ - va_end (argp); - return result; -} - -// This is basically an interface to ACE_OS::readv, that doesn't use -// the struct iovec explicitly. The ... can be passed as an arbitrary -// number of (char *ptr, int len) tuples. However, the count N is the -// *total* number of trailing arguments, *not* a couple of the number -// of tuple pairs! - -ssize_t -ACE_FILE_IO::recv (size_t n, ...) const -{ - ACE_TRACE ("ACE_FILE_IO::recv"); - va_list argp; - int total_tuples = ACE_Utils::truncate_cast (n / 2); - iovec *iovp = 0; -#if defined (ACE_HAS_ALLOCA) - iovp = (iovec *) alloca (total_tuples * sizeof (iovec)); -#else - ACE_NEW_RETURN (iovp, - iovec[total_tuples], - -1); -#endif /* !defined (ACE_HAS_ALLOCA) */ - - va_start (argp, n); - - for (int i = 0; i < total_tuples; i++) - { - iovp[i].iov_base = va_arg (argp, char *); - iovp[i].iov_len = va_arg (argp, int); - } - - ssize_t const result = ACE_OS::readv (this->get_handle (), - iovp, - total_tuples); -#if !defined (ACE_HAS_ALLOCA) - delete [] iovp; -#endif /* !defined (ACE_HAS_ALLOCA) */ - va_end (argp); - return result; -} - -// Allows a client to read from a file without having to provide a -// buffer to read. This method determines how much data is in the -// file, allocates a buffer of this size, reads in the data, and -// returns the number of bytes read. - -ssize_t -ACE_FILE_IO::recvv (iovec *io_vec) -{ - ACE_TRACE ("ACE_FILE_IO::recvv"); - - io_vec->iov_base = 0; - size_t const length = - static_cast (ACE_OS::filesize (this->get_handle ())); - - if (length > 0) - { - ACE_NEW_RETURN (io_vec->iov_base, - char[length], - -1); - io_vec->iov_len = this->recv_n (io_vec->iov_base, - length); - return io_vec->iov_len; - } - else - { - return ACE_Utils::truncate_cast (length); - } -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/FILE_IO.h b/externals/ace/FILE_IO.h deleted file mode 100644 index 951069e3652..00000000000 --- a/externals/ace/FILE_IO.h +++ /dev/null @@ -1,170 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file FILE_IO.h - * - * $Id: FILE_IO.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_FILE_IO_H -#define ACE_FILE_IO_H -#include /**/ "ace/pre.h" - -#include "ace/FILE.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/FILE_Addr.h" - -// Used in the FILE_IO.h file... -#include "ace/os_include/os_stdio.h" -#include "ace/os_include/sys/os_uio.h" - -#if defined (ACE_HAS_STREAM_PIPES) -# include "ace/OS_NS_stropts.h" -#endif /* ACE_HAS_STREAM_PIPES */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Forward decl. -class ACE_Message_Block; -class ACE_Time_Value; - -/** - * @class ACE_FILE_IO - * - * @brief Read/Write operations on Files - */ -class ACE_Export ACE_FILE_IO : public ACE_FILE -{ -public: - friend class ACE_FILE_Connector; - - // = Initialization method. - /// Default constructor. - ACE_FILE_IO (void); - - /// send upto @a n bytes in @a buf. - ssize_t send (const void *buf, size_t n) const; - - /// Recv upto @a n bytes in @a buf. - ssize_t recv (void *buf, size_t n) const; - - /// Send n bytes, keep trying until n are sent. - ssize_t send_n (const void *buf, size_t n) const; - - /// Send all the @a message_blocks chained through their and - /// pointers. This call uses the underlying OS gather-write - /// operation to reduce the domain-crossing penalty. - ssize_t send_n (const ACE_Message_Block *message_block, - const ACE_Time_Value *timeout = 0, - size_t *bytes_transferred = 0); - - /// Recv n bytes, keep trying until n are received. - ssize_t recv_n (void *buf, size_t n) const; - -#if defined (ACE_HAS_STREAM_PIPES) - /// Send bytes via STREAM pipes. - ssize_t send (const ACE_Str_Buf *cntl, - const ACE_Str_Buf *data, - int flags = 0) const; - - /// Recv bytes via STREAM pipes. - ssize_t recv (ACE_Str_Buf *cntl, - ACE_Str_Buf *data, - int *flags) const; - - /// Send bytes via STREAM pipes using "band" mode. - ssize_t send (const ACE_Str_Buf *cntl, - const ACE_Str_Buf *data, - int band, - int flags) const; - - /// Recv bytes via STREAM pipes using "band" mode. - ssize_t recv (ACE_Str_Buf *cntl, - ACE_Str_Buf *data, - int *band, - int *flags) const; - -#endif /* ACE_HAS_STREAM_PIPES */ - - /// Send iovecs via <::writev>. - ssize_t send (const iovec iov[], int n) const; - - /// Recv iovecs via <::readv>. - ssize_t recv (iovec iov[], int n) const; - - /** - * Send N char *ptrs and int lengths. Note that the char *'s - * precede the ints (basically, an varargs version of writev). The - * count N is the *total* number of trailing arguments, *not* a - * couple of the number of tuple pairs! - */ - ssize_t send (size_t n, ...) const; - - /** - * This is an interface to ::readv, that doesn't use the struct - * iovec explicitly. The ... can be passed as an arbitrary number - * of (char *ptr, int len) tuples. However, the count N is the - * *total* number of trailing arguments, *not* a couple of the - * number of tuple pairs! - */ - ssize_t recv (size_t n, ...) const; - - /// Send @a n bytes via Win32 WriteFile using overlapped I/O. - ssize_t send (const void *buf, - size_t n, - ACE_OVERLAPPED *overlapped) const; - - /// Recv @a n bytes via Win32 ReadFile using overlapped I/O. - ssize_t recv (void *buf, - size_t n, - ACE_OVERLAPPED *overlapped) const; - - /// Send an @c iovec of size @a n to the file. - ssize_t sendv (const iovec iov[], - int n) const; - - /** - * Allows a client to read from a file without having to provide a - * buffer to read. This method determines how much data is in the - * file, allocates a buffer of this size, reads in the data, and - * returns the number of bytes read. The caller is responsible for - * deleting the member in the field of using - * delete [] io_vec->iov_base. - */ - ssize_t recvv (iovec *io_vec); - - /// Send an of size @a n to the file. Will block until all - /// bytes are sent or an error occurs. - ssize_t sendv_n (const iovec iov[], - int n) const; - - /// Receive an of size @a n to the file. - ssize_t recvv_n (iovec iov[], - int n) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - - // = Meta-type info - typedef ACE_FILE_Addr PEER_ADDR; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/FILE_IO.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_FILE_IO_H */ diff --git a/externals/ace/FILE_IO.inl b/externals/ace/FILE_IO.inl deleted file mode 100644 index d2e4f756c2c..00000000000 --- a/externals/ace/FILE_IO.inl +++ /dev/null @@ -1,152 +0,0 @@ -// -*- C++ -*- -// -// $Id: FILE_IO.inl 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/ACE.h" -#include "ace/OS_NS_sys_uio.h" -#include "ace/OS_NS_unistd.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE ssize_t -ACE_FILE_IO::sendv_n (const iovec iov[], int n) const -{ - ACE_TRACE ("ACE_FILE_IO::sendv_n"); - return ACE::writev_n (this->get_handle (), - iov, - n); -} - -ACE_INLINE ssize_t -ACE_FILE_IO::send_n (const ACE_Message_Block *message_block, - const ACE_Time_Value *timeout, - size_t *bytes_transferred) -{ - ACE_TRACE ("ACE_FILE_IO::send_n"); - ACE_UNUSED_ARG (timeout); - return ACE::write_n (this->get_handle (), - message_block, - bytes_transferred); -} - -// Recv an n byte message from the file. - -ACE_INLINE ssize_t -ACE_FILE_IO::recvv_n (iovec iov[], int n) const -{ - ACE_TRACE ("ACE_FILE_IO::recvv_n"); - // @@ Carlos, can you please update this to call the - // new ACE::recvv_n() method that you write? - return ACE_OS::readv (this->get_handle (), - iov, - n); -} - -// Send an of size to the file. - -ACE_INLINE ssize_t -ACE_FILE_IO::sendv (const iovec iov[], int n) const -{ - ACE_TRACE ("ACE_FILE_IO::sendv"); - return ACE_OS::writev (this->get_handle (), iov, n); -} - -// Send exactly N bytes from BUF to this file. Keeping trying until -// this many bytes are sent. - -ACE_INLINE ssize_t -ACE_FILE_IO::send_n (const void *buf, size_t n) const -{ - ACE_TRACE ("ACE_FILE_IO::send_n"); - return ACE::write_n (this->get_handle (), buf, n); -} - -// Receive exactly N bytes from this file into BUF. Keep trying until -// this many bytes are received. - -ACE_INLINE ssize_t -ACE_FILE_IO::recv_n (void *buf, size_t n) const -{ - ACE_TRACE ("ACE_FILE_IO::recv_n"); - return ACE::read_n (this->get_handle (), buf, n); -} - -ACE_INLINE ssize_t -ACE_FILE_IO::send (const void *buf, size_t n) const -{ - ACE_TRACE ("ACE_FILE_IO::send"); - return ACE_OS::write (this->get_handle (), buf, n); -} - -ACE_INLINE ssize_t -ACE_FILE_IO::recv (void *buf, size_t n) const -{ - ACE_TRACE ("ACE_FILE_IO::recv"); - return ACE_OS::read (this->get_handle (), buf, n); -} - -ACE_INLINE ssize_t -ACE_FILE_IO::send (const iovec iov[], int n) const -{ - ACE_TRACE ("ACE_FILE_IO::send"); - return ACE_OS::writev (this->get_handle (), iov, n); -} - -ACE_INLINE ssize_t -ACE_FILE_IO::recv (iovec iov[], int n) const -{ - ACE_TRACE ("ACE_FILE_IO::recv"); - return ACE_OS::readv (this->get_handle (), iov, n); -} - -#if defined (ACE_HAS_STREAM_PIPES) -ACE_INLINE ssize_t -ACE_FILE_IO::recv (ACE_Str_Buf *cntl, ACE_Str_Buf *data, int *band, int *flags) const -{ - ACE_TRACE ("ACE_FILE_IO::recv"); - return ACE_OS::getpmsg (this->get_handle (), (strbuf *) cntl, (strbuf *) data, band, flags); -} - -ACE_INLINE ssize_t -ACE_FILE_IO::send (const ACE_Str_Buf *cntl, const ACE_Str_Buf *data, int band, int flags) const -{ - ACE_TRACE ("ACE_FILE_IO::send"); - return ACE_OS::putpmsg (this->get_handle (), (strbuf *) cntl, (strbuf *) data, band, flags); -} - -ACE_INLINE ssize_t -ACE_FILE_IO::recv (ACE_Str_Buf *cntl, ACE_Str_Buf *data, int *flags) const -{ - ACE_TRACE ("ACE_FILE_IO::recv"); - return ACE_OS::getmsg (this->get_handle (), (strbuf *) cntl, (strbuf *) data, flags); -} - -ACE_INLINE ssize_t -ACE_FILE_IO::send (const ACE_Str_Buf *cntl, const ACE_Str_Buf *data, int flags) const -{ - ACE_TRACE ("ACE_FILE_IO::send"); - return ACE_OS::putmsg (this->get_handle (), (strbuf *) cntl, (strbuf *) data, flags); -} - -ACE_INLINE ssize_t -ACE_FILE_IO::send (const void *buf, size_t n, - ACE_OVERLAPPED *overlapped) const -{ - ACE_TRACE ("ACE_FILE_IO::send"); - return ACE_OS::write (this->get_handle (), - buf, n, - overlapped); -} - -ACE_INLINE ssize_t -ACE_FILE_IO::recv (void *buf, size_t n, - ACE_OVERLAPPED *overlapped) const -{ - ACE_TRACE ("ACE_FILE_IO::recv"); - return ACE_OS::read (this->get_handle (), buf, n, - overlapped); -} - -#endif /* ACE_HAS_STREAM_PIPES */ - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/File_Lock.cpp b/externals/ace/File_Lock.cpp deleted file mode 100644 index 9eac8883d48..00000000000 --- a/externals/ace/File_Lock.cpp +++ /dev/null @@ -1,72 +0,0 @@ -// $Id: File_Lock.cpp 87213 2009-10-23 13:11:34Z johnnyw $ - -#include "ace/File_Lock.h" -#include "ace/Log_Msg.h" - -#if !defined (__ACE_INLINE__) -#include "ace/File_Lock.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID(ace, File_Lock, "$Id: File_Lock.cpp 87213 2009-10-23 13:11:34Z johnnyw $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_File_Lock) - -void -ACE_File_Lock::dump (void) const -{ -#if defined (ACE_HAS_DUMP) -// ACE_TRACE ("ACE_File_Lock::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - this->lock_.dump (); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -ACE_File_Lock::ACE_File_Lock (ACE_HANDLE h, - bool unlink_in_destructor) - : removed_ (false), - unlink_in_destructor_ (unlink_in_destructor) -{ -// ACE_TRACE ("ACE_File_Lock::ACE_File_Lock"); - if (ACE_OS::flock_init (&this->lock_) == -1) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_File_Lock::ACE_File_Lock"))); - this->set_handle (h); -} - -ACE_File_Lock::ACE_File_Lock (const ACE_TCHAR *name, - int flags, - mode_t perms, - bool unlink_in_destructor) - : unlink_in_destructor_ (unlink_in_destructor) -{ -// ACE_TRACE ("ACE_File_Lock::ACE_File_Lock"); - - if (this->open (name, flags, perms) == -1) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p %s\n"), - ACE_TEXT ("ACE_File_Lock::ACE_File_Lock"), - name)); -} - -int -ACE_File_Lock::open (const ACE_TCHAR *name, - int flags, - mode_t perms) -{ -// ACE_TRACE ("ACE_File_Lock::open"); - this->removed_ = false; - return ACE_OS::flock_init (&this->lock_, flags, name, perms); -} - -ACE_File_Lock::~ACE_File_Lock (void) -{ -// ACE_TRACE ("ACE_File_Lock::~ACE_File_Lock"); - this->remove (this->unlink_in_destructor_); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/File_Lock.h b/externals/ace/File_Lock.h deleted file mode 100644 index 4cd58fcd184..00000000000 --- a/externals/ace/File_Lock.h +++ /dev/null @@ -1,170 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file File_Lock.h - * - * $Id: File_Lock.h 91064 2010-07-12 10:11:24Z johnnyw $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_FILE_LOCK_H -#define ACE_FILE_LOCK_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/OS_NS_stdio.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_File_Lock - * - * @brief A wrapper around the UNIX file locking mechanism. - * - * Allows us to "adapt" the UNIX file locking mechanisms to work - * with all of our Guard stuff... - */ -class ACE_Export ACE_File_Lock -{ -public: - /** - * Set the of the File_Lock to @a handle. Note that this - * constructor assumes ownership of the @a handle and will close it - * down in . If you want the @a handle to stay open when - * is called make sure to call on the @a handle. - * If you don't want the file unlinked in the destructor pass a - * zero value for . - */ - ACE_File_Lock (ACE_HANDLE handle = ACE_INVALID_HANDLE, - bool unlink_in_destructor = true); - - /// Open the @a filename with @a flags and @a mode and set the result - /// to . If you don't want the file unlinked in the - /// destructor pass a false value for @a unlink_in_destructor. - ACE_File_Lock (const ACE_TCHAR *filename, - int flags, - mode_t mode = 0, - bool unlink_in_destructor = true); - - /// Open the @a filename with @a flags and @a mode and set the result to - /// . - int open (const ACE_TCHAR *filename, - int flags, - mode_t mode = 0); - - /// Remove a File lock by releasing it and closing down the . - ~ACE_File_Lock (void); - - /// Remove a File lock by releasing it and closing down the - /// . If @a unlink_file is true then we unlink the file. - int remove (bool unlink_file = true); - - /** - * Note, for interface uniformity with other synchronization - * wrappers we include the acquire() method. This is implemented as - * a write-lock to be on the safe-side... - */ - int acquire (short whence = 0, ACE_OFF_T start = 0, ACE_OFF_T len = 1); - - /** - * Note, for interface uniformity with other synchronization - * wrappers we include the method. This is implemented - * as a write-lock to be on the safe-side... Returns -1 on failure. - * If we "failed" because someone else already had the lock, @c errno - * is set to @c EBUSY. - */ - int tryacquire (short whence = 0, ACE_OFF_T start = 0, ACE_OFF_T len = 1); - - /// Unlock a readers/writer lock. - int release (short whence = 0, ACE_OFF_T start = 0, ACE_OFF_T len = 1); - - /// Acquire a write lock, but block if any readers or a - /// writer hold the lock. - int acquire_write (short whence = 0, ACE_OFF_T start = 0, ACE_OFF_T len = 1); - - /** - * Conditionally acquire a write lock (i.e., won't block). Returns - * -1 on failure. If we "failed" because someone else already had - * the lock, @c errno is set to @c EBUSY. - */ - int tryacquire_write (short whence = 0, ACE_OFF_T start = 0, ACE_OFF_T len = 1); - - /** - * Conditionally upgrade to a write lock (i.e., won't block). Returns - * -1 on failure. If we "failed" because someone else already had - * the lock, @c errno is set to @c EBUSY. - */ - int tryacquire_write_upgrade (short whence = 0, - ACE_OFF_T start = 0, - ACE_OFF_T len = 1); - - /** - * Acquire a read lock, but block if a writer hold the lock. - * Returns -1 on failure. If we "failed" because someone else - * already had the lock, @c errno is set to @c EBUSY. - */ - int acquire_read (short whence = 0, ACE_OFF_T start = 0, ACE_OFF_T len = 1); - - /** - * Conditionally acquire a read lock (i.e., won't block). Returns - * -1 on failure. If we "failed" because someone else already had - * the lock, @c errno is set to @c EBUSY. - */ - int tryacquire_read (short whence = 0, ACE_OFF_T start = 0, ACE_OFF_T len = 1); - - /// Get underlying ACE_HANDLE for the file. - ACE_HANDLE get_handle (void) const; - - /** - * Set underlying ACE_HANDLE. Note that this method assumes - * ownership of the @a handle and will close it down in . If - * you want the @a handle to stay open when is called make - * sure to call on the @a handle before closing it. You are - * responsible for the closing the existing @a handle before - * overwriting it. - */ - void set_handle (ACE_HANDLE); - - /// Dump state of the object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - /// Locking structure for OS record locks. - ACE_OS::ace_flock_t lock_; - - /// Keeps track of whether has been called yet to avoid - /// multiple calls, e.g., explicitly and implicitly in the - /// destructor. This flag isn't protected by a lock, so make sure - /// that you don't have multiple threads simultaneously calling - /// on the same object, which is a bad idea anyway... - bool removed_; - - /// Keeps track of whether to unlink the underlying file in the - /// destructor. - bool const unlink_in_destructor_; - -private: - // = Prevent assignment and initialization. - void operator= (const ACE_File_Lock &); - ACE_File_Lock (const ACE_File_Lock &); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/File_Lock.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_FILE_LOCK_H */ diff --git a/externals/ace/File_Lock.inl b/externals/ace/File_Lock.inl deleted file mode 100644 index cf0cefed16e..00000000000 --- a/externals/ace/File_Lock.inl +++ /dev/null @@ -1,96 +0,0 @@ -// -*- C++ -*- -// -// $Id: File_Lock.inl 87213 2009-10-23 13:11:34Z johnnyw $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE int -ACE_File_Lock::acquire_read (short whence, ACE_OFF_T start, ACE_OFF_T len) -{ -// ACE_TRACE ("ACE_File_Lock::acquire_read"); - return ACE_OS::flock_rdlock (&this->lock_, whence, start, len); -} - -ACE_INLINE int -ACE_File_Lock::tryacquire_read (short whence, ACE_OFF_T start, ACE_OFF_T len) -{ -// ACE_TRACE ("ACE_File_Lock::tryacquire_read"); - return ACE_OS::flock_tryrdlock (&this->lock_, whence, start, len); -} - -ACE_INLINE int -ACE_File_Lock::tryacquire_write (short whence, ACE_OFF_T start, ACE_OFF_T len) -{ -// ACE_TRACE ("ACE_File_Lock::tryacquire_write"); - return ACE_OS::flock_trywrlock (&this->lock_, whence, start, len); -} - -ACE_INLINE int -ACE_File_Lock::tryacquire_write_upgrade (short whence, - ACE_OFF_T start, - ACE_OFF_T len) -{ -// ACE_TRACE ("ACE_File_Lock::tryacquire_write_upgrade"); - return ACE_OS::flock_trywrlock (&this->lock_, whence, start, len); -} - -ACE_INLINE int -ACE_File_Lock::tryacquire (short whence, ACE_OFF_T start, ACE_OFF_T len) -{ -// ACE_TRACE ("ACE_File_Lock::tryacquire"); - return this->tryacquire_write (whence, start, len); -} - -ACE_INLINE int -ACE_File_Lock::acquire_write (short whence, ACE_OFF_T start, ACE_OFF_T len) -{ -// ACE_TRACE ("ACE_File_Lock::acquire_write"); - return ACE_OS::flock_wrlock (&this->lock_, whence, start, len); -} - -ACE_INLINE int -ACE_File_Lock::acquire (short whence, ACE_OFF_T start, ACE_OFF_T len) -{ -// ACE_TRACE ("ACE_File_Lock::acquire"); - return this->acquire_write (whence, start, len); -} - -ACE_INLINE int -ACE_File_Lock::release (short whence, ACE_OFF_T start, ACE_OFF_T len) -{ -// ACE_TRACE ("ACE_File_Lock::release"); - return ACE_OS::flock_unlock (&this->lock_, whence, start, len); -} - -ACE_INLINE int -ACE_File_Lock::remove (bool unlink_file) -{ -// ACE_TRACE ("ACE_File_Lock::remove"); - - int result = 0; - - if (!this->removed_) - { - this->removed_ = true; - result = ACE_OS::flock_destroy (&this->lock_, - unlink_file); - } - return result; -} - -ACE_INLINE ACE_HANDLE -ACE_File_Lock::get_handle (void) const -{ -// ACE_TRACE ("ACE_File_Lock::get_handle"); - return this->lock_.handle_; -} - -ACE_INLINE void -ACE_File_Lock::set_handle (ACE_HANDLE h) -{ -// ACE_TRACE ("ACE_File_Lock::set_handle"); - this->lock_.handle_ = h; - this->removed_ = false; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Filecache.cpp b/externals/ace/Filecache.cpp deleted file mode 100644 index 494749ca7ce..00000000000 --- a/externals/ace/Filecache.cpp +++ /dev/null @@ -1,746 +0,0 @@ -// $Id: Filecache.cpp 83735 2008-11-14 09:41:52Z johnnyw $ - -#include "ace/Filecache.h" -#include "ace/Object_Manager.h" -#include "ace/Log_Msg.h" -#include "ace/ACE.h" -#include "ace/Guard_T.h" -#include "ace/OS_NS_string.h" -#include "ace/OS_NS_time.h" -#include "ace/OS_NS_unistd.h" -#include "ace/OS_NS_fcntl.h" -#include "ace/Truncate.h" - -ACE_RCSID (ace, - Filecache, - "$Id: Filecache.cpp 83735 2008-11-14 09:41:52Z johnnyw $") - -#if defined (ACE_WIN32) -// Specifies no sharing flags. -#define R_MASK ACE_DEFAULT_OPEN_PERMS -#define W_MASK 0 -#else -#define R_MASK S_IRUSR|S_IRGRP|S_IROTH -#define W_MASK S_IRUSR|S_IRGRP|S_IROTH|S_IWUSR|S_IWGRP|S_IWOTH -#endif /* ACE_WIN32 */ - -#if defined (ACE_WIN32) -// See if you can get rid of some of these. -#define READ_FLAGS (FILE_FLAG_SEQUENTIAL_SCAN | \ - FILE_FLAG_OVERLAPPED | \ - O_RDONLY) -// static const int RCOPY_FLAGS = (FILE_FLAG_SEQUENTIAL_SCAN | -// O_RDONLY); -#define WRITE_FLAGS (FILE_FLAG_SEQUENTIAL_SCAN | \ - FILE_FLAG_OVERLAPPED | \ - O_RDWR | O_CREAT | O_TRUNC) -// static const int WCOPY_FLAGS = (FILE_FLAG_SEQUENTIAL_SCAN | -// O_RDWR | O_CREAT | O_TRUNC); -#else -#define READ_FLAGS O_RDONLY -// static const int RCOPY_FLAGS = O_RDONLY; -#define WRITE_FLAGS (O_RDWR | O_CREAT | O_TRUNC) -// static const int WCOPY_FLAGS = O_RDWR | O_CREAT | O_TRUNC; -#endif /* ACE_WIN32 */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// static data members -ACE_Filecache *ACE_Filecache::cvf_ = 0; - -void -ACE_Filecache_Handle::init (void) -{ - this->file_ = 0; - this->handle_ = ACE_INVALID_HANDLE; -} - -ACE_Filecache_Handle::ACE_Filecache_Handle (void) - : file_ (0), handle_ (0), mapit_ (0) -{ - this->init (); -} - -ACE_Filecache_Handle::ACE_Filecache_Handle (const ACE_TCHAR *filename, - ACE_Filecache_Flag mapit) - : file_ (0), handle_ (0), mapit_ (mapit) -{ - this->init (); - // Fetch the file from the Virtual_Filesystem let the - // Virtual_Filesystem do the work of cache coherency. - - // Filecache will also do the acquire, since it holds the lock at - // that time. - this->file_ = ACE_Filecache::instance ()->fetch (filename, mapit); -} - -ACE_Filecache_Handle::ACE_Filecache_Handle (const ACE_TCHAR *filename, - int size, - ACE_Filecache_Flag mapit) - : file_ (0), handle_ (0), mapit_ (mapit) -{ - this->init (); - - if (size == 0) - ACE_Filecache::instance ()->remove (filename); - else - { - // Since this is being opened for a write, simply create a new - // ACE_Filecache_Object now, and let the destructor add it into CVF - // later - - // Filecache will also do the acquire, since it holds the lock at - // that time. - this->file_ = ACE_Filecache::instance ()->create (filename, size); - } -} - -ACE_Filecache_Handle::~ACE_Filecache_Handle (void) -{ - if (this->handle_ != ACE_INVALID_HANDLE) - // this was dup ()'d - ACE_OS::close (this->handle_); - - ACE_Filecache::instance ()->finish (this->file_); -} - -void * -ACE_Filecache_Handle::address (void) const -{ - return this->file_ == 0 ? 0 : this->file_->address (); -} - -ACE_HANDLE -ACE_Filecache_Handle::handle (void) const -{ - if (this->handle_ == ACE_INVALID_HANDLE && this->file_ != 0) - { - ACE_Filecache_Handle *mutable_this = - const_cast (this); - mutable_this->handle_ = ACE_OS::dup (this->file_->handle ()); - } - return this->handle_; -} - -int -ACE_Filecache_Handle::error (void) const -{ - if (this->file_ == 0) - return -1; - else - return this->file_->error (); -} - -ACE_OFF_T -ACE_Filecache_Handle::size (void) const -{ - if (this->file_ == 0) - return -1; - else - return this->file_->size (); -} - -// ------------------ -// ACE_Filecache_Hash -// ------------------ - -#define ACE_Filecache_Hash \ - ACE_Hash_Map_Manager_Ex, ACE_Equal_To, ACE_Null_Mutex> -#define ACE_Filecache_Hash_Entry \ - ACE_Hash_Map_Entry - -template <> -ACE_Filecache_Hash_Entry::ACE_Hash_Map_Entry ( - const ACE_TCHAR *const &ext_id, - ACE_Filecache_Object *const &int_id, - ACE_Filecache_Hash_Entry *next, - ACE_Filecache_Hash_Entry *prev) - : ext_id_ (ext_id - ? ACE_OS::strdup (ext_id) - : ACE_OS::strdup (ACE_TEXT (""))), - int_id_ (int_id), - next_ (next), - prev_ (prev) -{ -} - -template <> -ACE_Filecache_Hash_Entry::ACE_Hash_Map_Entry (ACE_Filecache_Hash_Entry *next, - ACE_Filecache_Hash_Entry *prev) - : ext_id_ (0), - next_ (next), - prev_ (prev) -{ -} - -template <> -ACE_Filecache_Hash_Entry::~ACE_Hash_Map_Entry (void) -{ - ACE_OS::free ((void *) ext_id_); -} - -// We need these template specializations since KEY is defined as a -// ACE_TCHAR*, which doesn't have a hash() or equal() method defined on it. - -template <> -unsigned long -ACE_Filecache_Hash::hash (const ACE_TCHAR *const &ext_id) -{ - return ACE::hash_pjw (ext_id); -} - -template <> -int -ACE_Filecache_Hash::equal (const ACE_TCHAR *const &id1, - const ACE_TCHAR *const &id2) -{ - return ACE_OS::strcmp (id1, id2) == 0; -} - -#undef ACE_Filecache_Hash -#undef ACE_Filecache_Hash_Entry - - -// ------------- -// ACE_Filecache -// ------------- - -ACE_Filecache * -ACE_Filecache::instance (void) -{ - // Double check locking pattern. - if (ACE_Filecache::cvf_ == 0) - { - ACE_SYNCH_RW_MUTEX &lock = - *ACE_Managed_Object::get_preallocated_object - (ACE_Object_Manager::ACE_FILECACHE_LOCK); - ACE_GUARD_RETURN (ACE_SYNCH_RW_MUTEX, ace_mon, lock, 0); - - // @@ James, please check each of the ACE_NEW_RETURN calls to - // make sure that it is safe to return if allocation fails. - if (ACE_Filecache::cvf_ == 0) - ACE_NEW_RETURN (ACE_Filecache::cvf_, - ACE_Filecache, - 0); - } - - return ACE_Filecache::cvf_; -} - -ACE_Filecache::ACE_Filecache (void) - : size_ (ACE_DEFAULT_VIRTUAL_FILESYSTEM_TABLE_SIZE), - hash_ (size_) -{ -} - -ACE_Filecache::~ACE_Filecache (void) -{ -} - -ACE_Filecache_Object * -ACE_Filecache::insert_i (const ACE_TCHAR *filename, - ACE_SYNCH_RW_MUTEX &filelock, - int mapit) -{ - ACE_Filecache_Object *handle = 0; - - if (this->hash_.find (filename, handle) == -1) - { - ACE_NEW_RETURN (handle, - ACE_Filecache_Object (filename, filelock, 0, mapit), - 0); - - // ACE_DEBUG ((LM_DEBUG, ACE_TEXT (" (%t) CVF: creating %s\n"), filename)); - - if (this->hash_.bind (filename, handle) == -1) - { - delete handle; - handle = 0; - } - } - else - handle = 0; - - return handle; -} - -ACE_Filecache_Object * -ACE_Filecache::remove_i (const ACE_TCHAR *filename) -{ - ACE_Filecache_Object *handle = 0; - - // Disassociate file from the cache. - if (this->hash_.unbind (filename, handle) == 0) - { - handle->stale_ = 1; - - // Try a lock. If it succeeds, we can delete it now. - // Otherwise, it will clean itself up later. - if (handle->lock_.tryacquire_write () == 0) - { - delete handle; - handle = 0; - } - } - else - handle = 0; - - return handle; -} - -ACE_Filecache_Object * -ACE_Filecache::update_i (const ACE_TCHAR *filename, - ACE_SYNCH_RW_MUTEX &filelock, - int mapit) -{ - ACE_Filecache_Object *handle = 0; - - handle = this->remove_i (filename); - handle = this->insert_i (filename, filelock, mapit); - - return handle; -} - -int -ACE_Filecache::find (const ACE_TCHAR *filename) -{ - return this->hash_.find (filename); -} - - -ACE_Filecache_Object * -ACE_Filecache::remove (const ACE_TCHAR *filename) -{ - ACE_Filecache_Object *handle = 0; - - ACE_OFF_T loc = ACE::hash_pjw (filename) % this->size_; - ACE_SYNCH_RW_MUTEX &hashlock = this->hash_lock_[loc]; - // ACE_SYNCH_RW_MUTEX &filelock = this->file_lock_[loc]; - - if (this->hash_.find (filename, handle) != -1) - { - ACE_WRITE_GUARD_RETURN (ACE_SYNCH_RW_MUTEX, - ace_mon, - hashlock, - 0); - - return this->remove_i (filename); - } - - return 0; -} - - -ACE_Filecache_Object * -ACE_Filecache::fetch (const ACE_TCHAR *filename, int mapit) -{ - ACE_Filecache_Object *handle = 0; - - ACE_OFF_T loc = ACE::hash_pjw (filename) % this->size_; - ACE_SYNCH_RW_MUTEX &hashlock = this->hash_lock_[loc]; - ACE_SYNCH_RW_MUTEX &filelock = this->file_lock_[loc]; - - filelock.acquire_read (); - - if (this->hash_.find (filename, handle) == -1) - { - ACE_WRITE_GUARD_RETURN (ACE_SYNCH_RW_MUTEX, - ace_mon, - hashlock, - 0); - - // Second check in the method call - handle = this->insert_i (filename, filelock, mapit); - - if (handle == 0) - filelock.release (); - } - else - { - if (handle->update ()) - { - { - // Double check locking pattern - ACE_WRITE_GUARD_RETURN (ACE_SYNCH_RW_MUTEX, - ace_mon, - hashlock, - 0); - - // Second check in the method call - handle = this->update_i (filename, filelock, mapit); - - if (handle == 0) - filelock.release (); - } - } - // ACE_DEBUG ((LM_DEBUG, ACE_TEXT (" (%t) CVF: found %s\n"), filename)); - } - - return handle; -} - -ACE_Filecache_Object * -ACE_Filecache::create (const ACE_TCHAR *filename, int size) -{ - ACE_Filecache_Object *handle = 0; - - ACE_OFF_T loc = ACE::hash_pjw (filename) % this->size_; - ACE_SYNCH_RW_MUTEX &filelock = this->file_lock_[loc]; - - ACE_NEW_RETURN (handle, - ACE_Filecache_Object (filename, size, filelock), - 0); - handle->acquire (); - - return handle; -} - -ACE_Filecache_Object * -ACE_Filecache::finish (ACE_Filecache_Object *&file) -{ - if (file == 0) - return file; - - ACE_OFF_T loc = ACE::hash_pjw (file->filename_) % this->size_; - ACE_SYNCH_RW_MUTEX &hashlock = this->hash_lock_[loc]; - - if (file != 0) - switch (file->action_) - { - case ACE_Filecache_Object::ACE_WRITING: - { - ACE_WRITE_GUARD_RETURN (ACE_SYNCH_RW_MUTEX, - ace_mon, - hashlock, - 0); - - file->release (); - - this->remove_i (file->filename_); -#if 0 - int result = this->hash_.bind (file->filename (), file); - - if (result == 0) - file->acquire (); -#else - // Last one using a stale file is resposible for deleting it. - if (file->stale_) - { - // Try a lock. If it succeds, we can delete it now. - // Otherwise, it will clean itself up later. - if (file->lock_.tryacquire_write () == 0) - { - delete file; - file = 0; - } - } -#endif - } - - break; - default: - file->release (); - - // Last one using a stale file is resposible for deleting it. - if (file->stale_) - { - // Try a lock. If it succeds, we can delete it now. - // Otherwise, it will clean itself up later. - if (file->lock_.tryacquire_write () == 0) - { - delete file; - file = 0; - } - } - - break; - } - - return file; -} - -void -ACE_Filecache_Object::init (void) -{ - this->filename_[0] = '\0'; - this->handle_ = ACE_INVALID_HANDLE; - this->error_ = ACE_SUCCESS; - this->tempname_ = 0; - this->size_ = 0; - - ACE_OS::memset (&(this->stat_), 0, sizeof (this->stat_)); -} - -ACE_Filecache_Object::ACE_Filecache_Object (void) - : tempname_ (0), - mmap_ (), - handle_ (0), - // stat_ (), - size_ (0), - action_ (0), - error_ (0), - stale_ (0), - // sa_ (), - junklock_ (), - lock_ (junklock_) -{ - this->init (); -} - -ACE_Filecache_Object::ACE_Filecache_Object (const ACE_TCHAR *filename, - ACE_SYNCH_RW_MUTEX &lock, - LPSECURITY_ATTRIBUTES sa, - int mapit) - : tempname_ (0), - mmap_ (), - handle_ (0), - // stat_ (), - size_ (0), - action_ (0), - error_ (0), - stale_ (0), - sa_ (sa), - junklock_ (), - lock_ (lock) -{ - this->init (); - - // ASSERT strlen(filename) < sizeof (this->filename_) - ACE_OS::strcpy (this->filename_, filename); - this->action_ = ACE_Filecache_Object::ACE_READING; - // place ourselves into the READING state - - // Can we access the file? - if (ACE_OS::access (this->filename_, R_OK) == -1) - { - this->error_i (ACE_Filecache_Object::ACE_ACCESS_FAILED); - return; - } - - // Can we stat the file? - if (ACE_OS::stat (this->filename_, &this->stat_) == -1) - { - this->error_i (ACE_Filecache_Object::ACE_STAT_FAILED); - return; - } - - this->size_ = ACE_Utils::truncate_cast (this->stat_.st_size); - this->tempname_ = this->filename_; - - // Can we open the file? - this->handle_ = ACE_OS::open (this->tempname_, - READ_FLAGS, R_MASK, this->sa_); - if (this->handle_ == ACE_INVALID_HANDLE) - { - this->error_i (ACE_Filecache_Object::ACE_OPEN_FAILED, - ACE_TEXT ("ACE_Filecache_Object::ctor: open")); - return; - } - - if (mapit) - { - // Can we map the file? - if (this->mmap_.map (this->handle_, static_cast (-1), - PROT_READ, ACE_MAP_PRIVATE, 0, 0, this->sa_) != 0) - { - this->error_i (ACE_Filecache_Object::ACE_MEMMAP_FAILED, - ACE_TEXT ("ACE_Filecache_Object::ctor: map")); - ACE_OS::close (this->handle_); - this->handle_ = ACE_INVALID_HANDLE; - return; - } - } - - // Ok, finished! - this->action_ = ACE_Filecache_Object::ACE_READING; -} - -ACE_Filecache_Object::ACE_Filecache_Object (const ACE_TCHAR *filename, - ACE_OFF_T size, - ACE_SYNCH_RW_MUTEX &lock, - LPSECURITY_ATTRIBUTES sa) - : stale_ (0), - sa_ (sa), - lock_ (lock) -{ - this->init (); - - this->size_ = size; - ACE_OS::strcpy (this->filename_, filename); - this->action_ = ACE_Filecache_Object::ACE_WRITING; - - // Can we access the file? - if (ACE_OS::access (this->filename_, R_OK|W_OK) == -1 - // Does it exist? - && ACE_OS::access (this->filename_, F_OK) != -1) - { - // File exists, but we cannot access it. - this->error_i (ACE_Filecache_Object::ACE_ACCESS_FAILED); - return; - } - - this->tempname_ = this->filename_; - - // Can we open the file? - this->handle_ = ACE_OS::open (this->tempname_, WRITE_FLAGS, W_MASK, this->sa_); - if (this->handle_ == ACE_INVALID_HANDLE) - { - this->error_i (ACE_Filecache_Object::ACE_OPEN_FAILED, - ACE_TEXT ("ACE_Filecache_Object::acquire: open")); - return; - } - - // Can we write? - if (ACE_OS::pwrite (this->handle_, "", 1, this->size_ - 1) != 1) - { - this->error_i (ACE_Filecache_Object::ACE_WRITE_FAILED, - ACE_TEXT ("ACE_Filecache_Object::acquire: write")); - ACE_OS::close (this->handle_); - return; - } - - // Can we map? - if (this->mmap_.map (this->handle_, this->size_, PROT_RDWR, MAP_SHARED, - 0, 0, this->sa_) != 0) - { - this->error_i (ACE_Filecache_Object::ACE_MEMMAP_FAILED, - ACE_TEXT ("ACE_Filecache_Object::acquire: map")); - ACE_OS::close (this->handle_); - } - - // Ok, done! -} - -ACE_Filecache_Object::~ACE_Filecache_Object (void) -{ - if (this->error_ == ACE_SUCCESS) - { - this->mmap_.unmap (); - ACE_OS::close (this->handle_); - this->handle_ = ACE_INVALID_HANDLE; - } - - this->lock_.release (); -} - -int -ACE_Filecache_Object::acquire (void) -{ - return this->lock_.tryacquire_read (); -} - -int -ACE_Filecache_Object::release (void) -{ - if (this->action_ == ACE_WRITING) - { - // We are safe since only one thread has a writable Filecache_Object - -#if 0 - ACE_HANDLE original = ACE_OS::open (this->filename_, WRITE_FLAGS, W_MASK, - this->sa_); - if (original == ACE_INVALID_HANDLE) - this->error_ = ACE_Filecache_Object::ACE_OPEN_FAILED; - else if (ACE_OS::write (original, this->mmap_.addr (), - this->size_) == -1) - { - this->error_ = ACE_Filecache_Object::ACE_WRITE_FAILED; - ACE_OS::close (original); - ACE_OS::unlink (this->filename_); - } - else if (ACE_OS::stat (this->filename_, &this->stat_) == -1) - this->error_ = ACE_Filecache_Object::ACE_STAT_FAILED; -#endif - - this->mmap_.unmap (); - ACE_OS::close (this->handle_); - this->handle_ = ACE_INVALID_HANDLE; - -#if 0 - // Leave the file in an acquirable state. - this->handle_ = ACE_OS::open (this->tempname_, READ_FLAGS, R_MASK); - if (this->handle_ == ACE_INVALID_HANDLE) - { - this->error_i (ACE_Filecache_Object::ACE_OPEN_FAILED, - "ACE_Filecache_Object::acquire: open"); - } - else if (this->mmap_.map (this->handle_, -1, - PROT_READ, - ACE_MAP_PRIVATE, - 0, - 0, - this->sa_) != 0) - { - this->error_i (ACE_Filecache_Object::ACE_MEMMAP_FAILED, - "ACE_Filecache_Object::acquire: map"); - ACE_OS::close (this->handle_); - this->handle_ = ACE_INVALID_HANDLE; - } - - this->action_ = ACE_Filecache_Object::ACE_READING; -#endif - } - - return this->lock_.release (); -} - -int -ACE_Filecache_Object::error (void) const -{ - // The existence of the object means a read lock is being held. - return this->error_; -} - -int -ACE_Filecache_Object::error_i (int error_value, const ACE_TCHAR *s) -{ - s = s; - ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p.\n"), s)); - this->error_ = error_value; - return error_value; -} - -const ACE_TCHAR * -ACE_Filecache_Object::filename (void) const -{ - // The existence of the object means a read lock is being held. - return this->filename_; -} - -ACE_OFF_T -ACE_Filecache_Object::size (void) const -{ - // The existence of the object means a read lock is being held. - return this->size_; -} - -ACE_HANDLE -ACE_Filecache_Object::handle (void) const -{ - // The existence of the object means a read lock is being held. - return this->handle_; -} - -void * -ACE_Filecache_Object::address (void) const -{ - // The existence of the object means a read lock is being held. - return this->mmap_.addr (); -} - -int -ACE_Filecache_Object::update (void) const -{ - // The existence of the object means a read lock is being held. - int result; - ACE_stat statbuf; - - if (ACE_OS::stat (this->filename_, &statbuf) == -1) - result = 1; - else - result = ACE_OS::difftime (this->stat_.st_mtime, statbuf.st_mtime) < 0; - - return result; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Filecache.h b/externals/ace/Filecache.h deleted file mode 100644 index 9165a70fcd3..00000000000 --- a/externals/ace/Filecache.h +++ /dev/null @@ -1,356 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Filecache.h - * - * $Id: Filecache.h 91066 2010-07-12 11:05:04Z johnnyw $ - * - * @author James Hu - */ -//============================================================================= - - -#ifndef ACE_FILECACHE_H -#define ACE_FILECACHE_H - -#include /**/ "ace/pre.h" - -#include "ace/Mem_Map.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Hash_Map_Manager_T.h" -#include "ace/Null_Mutex.h" -#include "ace/Synch_Traits.h" -#include "ace/RW_Thread_Mutex.h" -#include "ace/OS_NS_sys_stat.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -enum ACE_Filecache_Flag -{ - ACE_NOMAP = 0, - ACE_MAPIT = 1 -}; - -class ACE_Filecache_Object; - -/** - * @class ACE_Filecache_Handle - * - * @brief - * Abstraction over a real file. This is meant to be the entry - * point into the Cached Virtual Filesystem. - * - * This is a cached filesystem implementation based loosely on the - * implementation of JAWS_File. The interfaces will be nearly the - * same. The under-the-hood implementation should hopefully be a - * much faster thing. - * These will be given their own implementations later. For now, we - * borrow the implementation provided by JAWS. - * On creation, the cache is checked, and reference count is - * incremented. On destruction, reference count is decremented. If - * the reference count is 0, the file is removed from the cache. - * E.g. 1, - * { - * ACE_Filecache_Handle foo("foo.html"); - * this->peer ().send (foo.address (), foo.size ()); - * } - * E.g. 2, - * { - * ACE_Filecache_Handle foo("foo.html"); - * io->transmitfile (foo.handle (), this->peer ().handle ()); - * } - * E.g. 3, - * { - * ACE_Filecache_Handle foo("foo.html", content_length); - * this->peer ().recv (foo.address (), content_length); - * } - * TODO: - */ -class ACE_Export ACE_Filecache_Handle -{ - // (1) Get rid of the useless copying of files when reading. - // Although it does make sure the file you send isn't being changed, - // it doesn't make sure the file is in a sensible state before - // sending it. - // - // Alternative: if the file get's trashed while it is being shipped, - // let the client request the file again. The cache should have an - // updated copy by that point. - // - // (2) Use hashing for locating files. This means I need a hastable - // implementation with buckets. - // - // (3) Only lock when absolutely necessary. JAWS_Virtual_Filesystem was - // rather conservative, but for some reason it still ran into problems. - // Since this design should be simpler, problems should be easier to spot. - // -public: - - /// Query cache for file, and acquire it. Assumes the file is being - /// opened for reading. - ACE_Filecache_Handle (const ACE_TCHAR *filename, - ACE_Filecache_Flag mapit = ACE_MAPIT); - - /** - * Create new entry, and acquire it. Presence of SIZE assumes the - * file is being opened for writing. If SIZE is zero, assumes the - * file is to be removed from the cache. - */ - ACE_Filecache_Handle (const ACE_TCHAR *filename, - int size, - ACE_Filecache_Flag mapit = ACE_MAPIT); - - /// Closes any open handles, release acquired file. - ~ACE_Filecache_Handle (void); - - /// Base address of memory mapped file. - void *address (void) const; - - /// A handle (e.g., UNIX file descriptor, or NT file handle). - ACE_HANDLE handle (void) const; - - /// Any associated error in handle creation and acquisition. - int error (void) const; - - /// The size of the file. - ACE_OFF_T size (void) const; - -protected: - /// Default do nothing constructor. Prevent it from being called. - ACE_Filecache_Handle (void); - - /// Common initializations for constructors. - void init (void); - -public: - /// These come from ACE_Filecache_Object, which is an internal class. - enum - { - ACE_SUCCESS = 0, - ACE_ACCESS_FAILED, - ACE_OPEN_FAILED, - ACE_COPY_FAILED, - ACE_STAT_FAILED, - ACE_MEMMAP_FAILED, - ACE_WRITE_FAILED - }; - -private: - /// A reference to the low level instance. - ACE_Filecache_Object *file_; - - /// A dup'd version of the one from file_. - ACE_HANDLE handle_; - - int mapit_; -}; - -typedef ACE_Hash_Map_Manager_Ex, ACE_Equal_To, ACE_Null_Mutex> - ACE_Filecache_Hash; - -typedef ACE_Hash_Map_Entry ACE_Filecache_Hash_Entry; - -/** - * @class ACE_Filecache - * - * @brief - * A hash table holding the information about entry point into - * the Cached Virtual Filesystem. On insertion, the reference - * count is incremented. On destruction, reference count is - * decremented. - */ -class ACE_Export ACE_Filecache -{ -public: - /// Singleton pattern. - static ACE_Filecache *instance (void); - - ~ACE_Filecache (void); - - /// Returns 0 if the file associated with ``filename'' is in the cache, - /// or -1 if not. - int find (const ACE_TCHAR *filename); - - /// Return the file associated with ``filename'' if it is in the cache, - /// or create if not. - ACE_Filecache_Object *fetch (const ACE_TCHAR *filename, int mapit = 1); - - /// Remove the file associated with ``filename'' from the cache. - ACE_Filecache_Object *remove (const ACE_TCHAR *filename); - - /// Create a new Filecache_Object, returns it. - ACE_Filecache_Object *create (const ACE_TCHAR *filename, int size); - - /// Release an acquired Filecache_Object, returns it again or NULL if it - /// was deleted. - ACE_Filecache_Object *finish (ACE_Filecache_Object *&new_file); - -protected: - ACE_Filecache_Object *insert_i (const ACE_TCHAR *filename, - ACE_SYNCH_RW_MUTEX &filelock, - int mapit); - ACE_Filecache_Object *remove_i (const ACE_TCHAR *filename); - ACE_Filecache_Object *update_i (const ACE_TCHAR *filename, - ACE_SYNCH_RW_MUTEX &filelock, - int mapit); - -public: - - enum - { - /// For this stupid implementation, use an array. Someday, use a - /// balanced search tree, or real hash table. - ACE_DEFAULT_VIRTUAL_FILESYSTEM_TABLE_SIZE = 512, - - /// This determines the highwater mark in megabytes for the cache. - /// This will be ignored for now. - ACE_DEFAULT_VIRTUAL_FILESYSTEM_CACHE_SIZE = 20 - }; - -protected: - /// Prevent it from being called. - ACE_Filecache (void); - -private: - ACE_OFF_T size_; - - /// The hash table - ACE_Filecache_Hash hash_; - - /// The reference to the instance - static ACE_Filecache *cvf_; - - // = Synchronization variables. - ACE_SYNCH_RW_MUTEX hash_lock_[ACE_DEFAULT_VIRTUAL_FILESYSTEM_TABLE_SIZE]; - ACE_SYNCH_RW_MUTEX file_lock_[ACE_DEFAULT_VIRTUAL_FILESYSTEM_TABLE_SIZE]; -}; - -/** - * @class ACE_Filecache_Object - * - * @brief - * Abstraction over a real file. This is what the Virtual - * Filesystem contains. This class is not intended for general - * consumption. Please consult a physician before attempting to - * use this class. - */ -class ACE_Export ACE_Filecache_Object -{ -public: - friend class ACE_Filecache; - - /// Creates a file for reading. - ACE_Filecache_Object (const ACE_TCHAR *filename, - ACE_SYNCH_RW_MUTEX &lock, - LPSECURITY_ATTRIBUTES sa = 0, - int mapit = 1); - - /// Creates a file for writing. - ACE_Filecache_Object (const ACE_TCHAR *filename, - ACE_OFF_T size, - ACE_SYNCH_RW_MUTEX &lock, - LPSECURITY_ATTRIBUTES sa = 0); - - /// Only if reference count is zero should this be called. - ~ACE_Filecache_Object (void); - - /// Increment the reference_count_. - int acquire (void); - - /// Decrement the reference_count_. - int release (void); - - // = error_ accessors - int error (void) const; - int error (int error_value, - const ACE_TCHAR *s = ACE_TEXT ("ACE_Filecache_Object")); - - /// filename_ accessor - const ACE_TCHAR *filename (void) const; - - /// handle_ accessor. - ACE_HANDLE handle (void) const; - - /// Base memory address for memory mapped file. - void *address (void) const; - - /// size_ accessor. - ACE_OFF_T size (void) const; - - /// True if file on disk is newer than cached file. - int update (void) const; - -protected: - /// Prevent from being called. - ACE_Filecache_Object (void); - - /// Common initialization code, - void init (void); - -private: - /// Internal error logging method, no locking. - int error_i (int error_value, - const ACE_TCHAR *s = ACE_TEXT ("ACE_Filecache_Object")); - -public: - - enum Creation_States - { - ACE_READING = 1, - ACE_WRITING = 2 - }; - - enum Error_Conditions - { - ACE_SUCCESS = 0, - ACE_ACCESS_FAILED, - ACE_OPEN_FAILED, - ACE_COPY_FAILED, - ACE_STAT_FAILED, - ACE_MEMMAP_FAILED, - ACE_WRITE_FAILED - }; - -private: - /// The temporary file name and the real file name. The real file is - /// copied into the temporary file for safety reasons. - ACE_TCHAR *tempname_; - ACE_TCHAR filename_[MAXPATHLEN + 1]; - - /// Holds the memory mapped version of the temporary file. - ACE_Mem_Map mmap_; - - /// The descriptor to the temporary file. - ACE_HANDLE handle_; - - /// Used to compare against the real file to test if an update is needed. - ACE_stat stat_; - ACE_OFF_T size_; - - /// Status indicators. - int action_; - int error_; - - /// If set to 1, means the object is flagged for removal. - int stale_; - - /// Security attribute object. - LPSECURITY_ATTRIBUTES sa_; - - /// The default initializer - ACE_SYNCH_RW_MUTEX junklock_; - - /// Provides a bookkeeping mechanism for users of this object. - ACE_SYNCH_RW_MUTEX &lock_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" - -#endif /* ACE_FILECACHE_H */ diff --git a/externals/ace/Flag_Manip.cpp b/externals/ace/Flag_Manip.cpp deleted file mode 100644 index f9ac4083fa0..00000000000 --- a/externals/ace/Flag_Manip.cpp +++ /dev/null @@ -1,95 +0,0 @@ -// $Id: Flag_Manip.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Flag_Manip.h" - -#if defined (ACE_LACKS_FCNTL) -# include "ace/OS_NS_stropts.h" -# include "ace/OS_NS_errno.h" -#endif /* ACE_LACKS_FCNTL */ - -#if !defined (__ACE_INLINE__) -#include "ace/Flag_Manip.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (CYGWIN32) -# include "ace/os_include/os_termios.h" -#endif /* CYGWIN32 */ - -ACE_RCSID (ace, - Flag_Manip, - "$Id: Flag_Manip.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Flags are file status flags to turn on. - -int -ACE::set_flags (ACE_HANDLE handle, int flags) -{ - ACE_TRACE ("ACE::set_flags"); -#if defined (ACE_LACKS_FCNTL) - switch (flags) - { - case ACE_NONBLOCK: - // nonblocking argument (1) - // blocking: (0) - { - int nonblock = 1; - return ACE_OS::ioctl (handle, FIONBIO, &nonblock); - } - default: - ACE_NOTSUP_RETURN (-1); - } -#else - int val = ACE_OS::fcntl (handle, F_GETFL, 0); - - if (val == -1) - return -1; - - // Turn on flags. - ACE_SET_BITS (val, flags); - - if (ACE_OS::fcntl (handle, F_SETFL, val) == -1) - return -1; - else - return 0; -#endif /* ACE_LACKS_FCNTL */ -} - -// Flags are the file status flags to turn off. - -int -ACE::clr_flags (ACE_HANDLE handle, int flags) -{ - ACE_TRACE ("ACE::clr_flags"); - -#if defined (ACE_LACKS_FCNTL) - switch (flags) - { - case ACE_NONBLOCK: - // nonblocking argument (1) - // blocking: (0) - { - int nonblock = 0; - return ACE_OS::ioctl (handle, FIONBIO, &nonblock); - } - default: - ACE_NOTSUP_RETURN (-1); - } -#else - int val = ACE_OS::fcntl (handle, F_GETFL, 0); - - if (val == -1) - return -1; - - // Turn flags off. - ACE_CLR_BITS (val, flags); - - if (ACE_OS::fcntl (handle, F_SETFL, val) == -1) - return -1; - else - return 0; -#endif /* ACE_LACKS_FCNTL */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Flag_Manip.h b/externals/ace/Flag_Manip.h deleted file mode 100644 index 0457dcb4d95..00000000000 --- a/externals/ace/Flag_Manip.h +++ /dev/null @@ -1,58 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Flag_Manip.h - * - * $Id: Flag_Manip.h 80826 2008-03-04 14:51:23Z wotte $ - * - * This class includes the functions used for the Flag Manipulation. - * - * @author Priyanka Gontla - */ -//============================================================================= - -#ifndef ACE_FLAG_MANIP_H -#define ACE_FLAG_MANIP_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Global_Macros.h" -#include "ace/os_include/os_fcntl.h" /* For values passed to these methods */ - -#if defined (ACE_EXPORT_MACRO) -# undef ACE_EXPORT_MACRO -#endif -#define ACE_EXPORT_MACRO ACE_Export - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -namespace ACE -{ - // = Set/get/clear various flags related to I/O HANDLE. - /// Set flags associated with @a handle. - extern ACE_Export int set_flags (ACE_HANDLE handle, - int flags); - - /// Clear flags associated with @a handle. - extern ACE_Export int clr_flags (ACE_HANDLE handle, - int flags); - - /// Return the current setting of flags associated with @a handle. - ACE_NAMESPACE_INLINE_FUNCTION int get_flags (ACE_HANDLE handle); -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Flag_Manip.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_FLAG_MANIP_H */ diff --git a/externals/ace/Flag_Manip.inl b/externals/ace/Flag_Manip.inl deleted file mode 100644 index 229a4ee596c..00000000000 --- a/externals/ace/Flag_Manip.inl +++ /dev/null @@ -1,26 +0,0 @@ -// -*- C++ -*- -// -// $Id: Flag_Manip.inl 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/OS_NS_fcntl.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Return flags currently associated with handle. -ACE_INLINE int -ACE::get_flags (ACE_HANDLE handle) -{ - ACE_TRACE ("ACE::get_flags"); - -#if defined (ACE_LACKS_FCNTL) - // ACE_OS::fcntl is not supported. It - // would be better to store ACE's notion of the flags - // associated with the handle, but this works for now. - ACE_UNUSED_ARG (handle); - return 0; -#else - return ACE_OS::fcntl (handle, F_GETFL, 0); -#endif /* ACE_LACKS_FCNTL */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Framework_Component.cpp b/externals/ace/Framework_Component.cpp deleted file mode 100644 index 7b63ad5eeeb..00000000000 --- a/externals/ace/Framework_Component.cpp +++ /dev/null @@ -1,279 +0,0 @@ -// Framework_Component.cpp -// $Id: Framework_Component.cpp 84128 2009-01-09 15:07:40Z johnnyw $ - -#include "ace/Framework_Component.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Framework_Component.inl" -#endif /* __ACE_INLINE__ */ - -#include "ace/Object_Manager.h" -#include "ace/Log_Msg.h" -#include "ace/DLL_Manager.h" -#include "ace/Recursive_Thread_Mutex.h" -#include "ace/OS_NS_string.h" - -ACE_RCSID(ace, Framework_Component, "$Id: Framework_Component.cpp 84128 2009-01-09 15:07:40Z johnnyw $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_Framework_Component::~ACE_Framework_Component (void) -{ - ACE_TRACE ("ACE_Framework_Component::~ACE_Framework_Component"); - - ACE::strdelete (const_cast (this->dll_name_)); - ACE::strdelete (const_cast (this->name_)); -} - -/***************************************************************/ - -ACE_ALLOC_HOOK_DEFINE(ACE_Framework_Repository) - -sig_atomic_t ACE_Framework_Repository::shutting_down_ = 0; - -// Pointer to the Singleton instance. -ACE_Framework_Repository *ACE_Framework_Repository::repository_ = 0; - -ACE_Framework_Repository::~ACE_Framework_Repository (void) -{ - ACE_TRACE ("ACE_Framework_Repository::~ACE_Framework_Repository"); - this->close (); -} - -int -ACE_Framework_Repository::open (int size) -{ - ACE_TRACE ("ACE_Framework_Repository::open"); - - ACE_Framework_Component **temp = 0; - - ACE_NEW_RETURN (temp, - ACE_Framework_Component *[size], - -1); - - this->component_vector_ = temp; - this->total_size_ = size; - return 0; -} - -int -ACE_Framework_Repository::close (void) -{ - ACE_TRACE ("ACE_Framework_Repository::close"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - - this->shutting_down_ = 1; - - if (this->component_vector_ != 0) - { - // Delete components in reverse order. - for (int i = this->current_size_ - 1; i >= 0; i--) - if (this->component_vector_[i]) - { - ACE_Framework_Component *s = - const_cast ( - this->component_vector_[i]); - - this->component_vector_[i] = 0; - delete s; - } - - delete [] this->component_vector_; - this->component_vector_ = 0; - this->current_size_ = 0; - } - - ACE_DLL_Manager::close_singleton (); - return 0; -} - -ACE_Framework_Repository * -ACE_Framework_Repository::instance (int size) -{ - ACE_TRACE ("ACE_Framework_Repository::instance"); - - if (ACE_Framework_Repository::repository_ == 0) - { - // Perform Double-Checked Locking Optimization. - ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, - *ACE_Static_Object_Lock::instance (), 0)); - if (ACE_Framework_Repository::repository_ == 0) - { - if (ACE_Object_Manager::starting_up () || - !ACE_Object_Manager::shutting_down ()) - { - ACE_NEW_RETURN (ACE_Framework_Repository::repository_, - ACE_Framework_Repository (size), - 0); - } - } - } - - return ACE_Framework_Repository::repository_; -} - -void -ACE_Framework_Repository::close_singleton (void) -{ - ACE_TRACE ("ACE_Framework_Repository::close_singleton"); - - ACE_MT (ACE_GUARD (ACE_Recursive_Thread_Mutex, ace_mon, - *ACE_Static_Object_Lock::instance ())); - - delete ACE_Framework_Repository::repository_; - ACE_Framework_Repository::repository_ = 0; -} - -int -ACE_Framework_Repository::register_component (ACE_Framework_Component *fc) -{ - ACE_TRACE ("ACE_Framework_Repository::register_component"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - int i; - - // Check to see if it's already registered - for (i = 0; i < this->current_size_; i++) - if (this->component_vector_[i] && - fc->this_ == this->component_vector_[i]->this_) - { - ACE_ERROR_RETURN ((LM_ERROR, - "AFR::register_component: error, compenent already registered\n"), - -1); - } - - if (i < this->total_size_) - { - this->component_vector_[i] = fc; - ++this->current_size_; - return 0; - } - - return -1; -} - -int -ACE_Framework_Repository::remove_component (const ACE_TCHAR *name) -{ - ACE_TRACE ("ACE_Framework_Repository::remove_component"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - int i; - - for (i = 0; i < this->current_size_; i++) - if (this->component_vector_[i] && - ACE_OS::strcmp (this->component_vector_[i]->name_, name) == 0) - { - delete this->component_vector_[i]; - this->component_vector_[i] = 0; - this->compact (); - return 0; - } - - return -1; -} - -int -ACE_Framework_Repository::remove_dll_components (const ACE_TCHAR *dll_name) -{ - ACE_TRACE ("ACE_Framework_Repository::remove_dll_components"); - - if (this->shutting_down_) - return this->remove_dll_components_i (dll_name); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - - return this->remove_dll_components_i (dll_name); -} - -int -ACE_Framework_Repository::remove_dll_components_i (const ACE_TCHAR *dll_name) -{ - ACE_TRACE ("ACE_Framework_Repository::remove_dll_components_i"); - - int i; - int retval = -1; - - for (i = 0; i < this->current_size_; i++) - if (this->component_vector_[i] && - ACE_OS::strcmp (this->component_vector_[i]->dll_name_, dll_name) == 0) - { - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("AFR::remove_dll_components_i (%s) ") - ACE_TEXT ("component \"%s\"\n"), - dll_name, this->component_vector_[i]->name_)); - delete this->component_vector_[i]; - this->component_vector_[i] = 0; - ++retval; - } - - this->compact (); - - return retval == -1 ? -1 : 0; -} - -void -ACE_Framework_Repository::compact (void) -{ - ACE_TRACE ("ACE_Framework_Repository::compact"); - - int i; - int start_hole; - int end_hole; - - do - { - start_hole = this->current_size_; - end_hole = this->current_size_; - - // Find hole - for (i = 0; i < this->current_size_; ++i) - { - if (this->component_vector_[i] == 0) - { - if (start_hole == this->current_size_) - { - start_hole = i; - end_hole = i; - } - else - end_hole = i; - } - else if (end_hole != this->current_size_) - break; - } - - if (start_hole != this->current_size_) - { - // move the contents and reset current_size_ - while (end_hole + 1 < this->current_size_) - { - this->component_vector_[start_hole++] = - this->component_vector_[++end_hole]; - } - // Since start_hole is now one past the last - // active slot. - this->current_size_ = start_hole; - } - - } while (start_hole != this->current_size_); -} - -void -ACE_Framework_Repository::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Framework_Repository::dump"); -#endif /* ACE_HAS_DUMP */ -} - -ACE_Framework_Repository::ACE_Framework_Repository (int size) - : current_size_ (0) -{ - ACE_TRACE ("ACE_Framework_Repository::ACE_Framework_Repository"); - - if (this->open (size) == -1) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_Framework_Repository"))); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Framework_Component.h b/externals/ace/Framework_Component.h deleted file mode 100644 index 941960bf047..00000000000 --- a/externals/ace/Framework_Component.h +++ /dev/null @@ -1,210 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Framework_Component.h - * - * $Id: Framework_Component.h 80826 2008-03-04 14:51:23Z wotte $ - * - * A prototype mechanism that allows framework components, singletons - * such as ACE_Reactor, ACE_Proactor, etc, to be registered with a - * central repository managed by the ACE_Object_Manager or - * ACE_Service_Config that will handle destruction. - * - * This technique obviates changing ACE_Object_Manager and - * ACE_Service_Config everytime a new framework is added. Which also - * means that unused framework components don't need to linked into - * the final application which is important for applications with - * stringent footprint requirements. - * - * Framework components need only provide a static method, - * close_singleton() and add the ACE_REGISTER_FRAMEWORK_COMPONENT macro - * call to their instance() methods in order to participate. Components - * that don't have a close_singleton() method can also participate via - * template specialization of ACE_Framework_Component_T. - * - * This design uses the External Polymorphism pattern to avoid having - * to derive all framework components from a common base class that - * has virtual methods (this is crucial to avoid unnecessary overhead), - * and is based on the dump debugging implementation found in - * . - * - * @author Don Hinton . - */ -//============================================================================= - -#ifndef ACE_FRAMEWORK_COMPONENT_H -#define ACE_FRAMEWORK_COMPONENT_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/os_signal.h" -#include "ace/Thread_Mutex.h" - -#define ACE_DEFAULT_FRAMEWORK_REPOSITORY_SIZE 1024 - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Framework_Component - * - * @brief Base class that defines a uniform interface for all managed - * framework components. - */ -class ACE_Export ACE_Framework_Component -{ -public: - friend class ACE_Framework_Repository; - - /// Constructor. - ACE_Framework_Component (void *_this, - const ACE_TCHAR *dll_name = 0, - const ACE_TCHAR *name = 0); - - /// Close the contained singleton. - virtual void close_singleton (void) = 0; - -protected: - /// Destructor. - virtual ~ACE_Framework_Component (void); - -private: - // No copy possible - ACE_Framework_Component (const ACE_Framework_Component &); - void operator= (const ACE_Framework_Component &); - -private: - /// Pointer to the actual component. - const void *this_; - - /// Library associated with this component - const ACE_TCHAR *dll_name_; - - /// Component name - const ACE_TCHAR *name_; -}; - -/** - * @class ACE_Framework_Repository - * - * @brief Contains all framework components used by an application. - * - * This class contains a vector of ACE_Framework_Component *'s. On - * destruction, framework components are destroyed in the reverse order - * that they were added originally. - */ -class ACE_Export ACE_Framework_Repository -{ -public: - // This is just to silence a compiler warning about no public ctors - friend class ACE_Framework_Component; - - enum - { - DEFAULT_SIZE = ACE_DEFAULT_FRAMEWORK_REPOSITORY_SIZE - }; - - /// Close down the repository and free up dynamically allocated - /// resources. - ~ACE_Framework_Repository (void); - - /// Initialize the repository. - int open (int size = DEFAULT_SIZE); - - /// Close down the repository and free up dynamically allocated - /// resources, also called by dtor. - int close (void); - - /// Get pointer to a process-wide ACE_Framework_Repository. - static ACE_Framework_Repository *instance - (int size = ACE_Framework_Repository::DEFAULT_SIZE); - - /// Delete the dynamically allocated Singleton. - static void close_singleton (void); - - // = Search structure operations (all acquire locks as necessary). - - /// Insert a new component. Returns -1 when the repository is full - /// and 0 on success. - int register_component (ACE_Framework_Component *fc); - - /// Remove a component. Returns -1 on error or if component not found - /// and 0 on success. - int remove_component (const ACE_TCHAR *name); - - /// Remove all components associated with a particular dll. - int remove_dll_components (const ACE_TCHAR *dll_name); - - /// Return the current size of the repository. - int current_size (void) const; - - /// Return the total size of the repository. - int total_size (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - - /// Initialize the repository. - ACE_Framework_Repository (int size = ACE_Framework_Repository::DEFAULT_SIZE); - -private: - - /// Actually removes the dll components, must be called with locks held. - int remove_dll_components_i (const ACE_TCHAR *dll_name); - - /// Compact component_vector_ after components have been removed__maintains - /// order. - void compact (void); - - /// Disallow copying and assignment. - ACE_Framework_Repository (const ACE_Framework_Repository &); - ACE_Framework_Repository &operator= (const ACE_Framework_Repository &); - -private: - - /// Contains all the framework components. - ACE_Framework_Component **component_vector_; - - /// Current number of components. - int current_size_; - - /// Maximum number of components. - int total_size_; - - /// Pointer to a process-wide ACE_Framework_Repository. - static ACE_Framework_Repository *repository_; - - /// Flag set when repository is the process of shutting down. This - /// is necessary to keep from self-deadlocking since some of - /// the components might make calls back to the repository to - /// unload their components, e.g., ACE_DLL_Manager. - static sig_atomic_t shutting_down_; - -#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) - /// Synchronization variable for the MT_SAFE Repository - ACE_Thread_Mutex lock_; -#endif /* ACE_MT_SAFE */ - -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Framework_Component.inl" -#endif /* __ACE_INLINE__ */ - -// Include the templates classes at this point. -#include "ace/Framework_Component_T.h" - -#include /**/ "ace/post.h" -#endif /* ACE_FRAMEWORK_COMPONENT_H */ diff --git a/externals/ace/Framework_Component.inl b/externals/ace/Framework_Component.inl deleted file mode 100644 index 1fb2de38b85..00000000000 --- a/externals/ace/Framework_Component.inl +++ /dev/null @@ -1,39 +0,0 @@ -// -*- C++ -*- -// -// $Id: Framework_Component.inl 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/ACE.h" -#include "ace/Guard_T.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE -ACE_Framework_Component::ACE_Framework_Component (void *_this, - const ACE_TCHAR *dll_name, - const ACE_TCHAR *name) - : this_ (_this), - dll_name_ (ACE::strnew (dll_name ? dll_name : ACE_TEXT (""))), - name_ (ACE::strnew (name ? name : ACE_TEXT (""))) -{ - ACE_TRACE ("ACE_Framework_Component::ctor"); -} - -/***************************************************************/ - -ACE_INLINE int -ACE_Framework_Repository::current_size (void) const -{ - ACE_TRACE ("ACE_Framework_Repository::current_size"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, (ACE_Thread_Mutex &) this->lock_, -1)); - return this->current_size_; -} - -ACE_INLINE int -ACE_Framework_Repository::total_size (void) const -{ - ACE_TRACE ("ACE_Framework_Repository::total_size"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, (ACE_Thread_Mutex &) this->lock_, -1)); - return this->total_size_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Framework_Component_T.cpp b/externals/ace/Framework_Component_T.cpp deleted file mode 100644 index 6f0be7b5e2a..00000000000 --- a/externals/ace/Framework_Component_T.cpp +++ /dev/null @@ -1,33 +0,0 @@ -// $Id: Framework_Component_T.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#ifndef ACE_FRAMEWORK_COMPONENT_T_CPP -#define ACE_FRAMEWORK_COMPONENT_T_CPP - -#include "ace/Framework_Component_T.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template -ACE_Framework_Component_T::ACE_Framework_Component_T (Concrete *concrete) - : ACE_Framework_Component ((void *) concrete, concrete->dll_name (), concrete->name ()) -{ - ACE_TRACE ("ACE_Framework_Component_T::ctor"); -} - -template -ACE_Framework_Component_T::~ACE_Framework_Component_T (void) -{ - ACE_TRACE ("ACE_Framework_Component_T::~ACE_Framework_Component_T"); - Concrete::close_singleton (); -} - -template void -ACE_Framework_Component_T::close_singleton (void) -{ - ACE_TRACE ("ACE_Framework_Component_T::close_singleton"); - Concrete::close_singleton (); -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_FRAMEWORK_COMPONENT_T_CPP */ diff --git a/externals/ace/Framework_Component_T.h b/externals/ace/Framework_Component_T.h deleted file mode 100644 index 2dcef43e384..00000000000 --- a/externals/ace/Framework_Component_T.h +++ /dev/null @@ -1,71 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Framework_Component_T.h - * - * $Id: Framework_Component_T.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - */ -//============================================================================= - -#ifndef ACE_FRAMEWORK_COMPONENT_T_H -#define ACE_FRAMEWORK_COMPONENT_T_H -#include /**/ "ace/pre.h" -#include "ace/Framework_Component.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Framework_Component_T - * - * @brief This class inherits the interface of the abstract - * ACE_Framework_Component class and is instantiated with the - * implementation of the concrete component class @c class Concrete. - * - * This design is similar to the Adapter and Decorator patterns - * from the ``Gang of Four'' book. Note that @c class Concrete - * need not inherit from a common class since ACE_Framework_Component - * provides the uniform virtual interface! (implementation based on - * ACE_Dumpable_Adapter in . - */ -template -class ACE_Framework_Component_T : public ACE_Framework_Component -{ -public: - // = Initialization and termination methods. - - /// Constructor. - ACE_Framework_Component_T (Concrete *concrete); - - /// Destructor. - ~ACE_Framework_Component_T (void); - - /// Close the contained singleton. - void close_singleton (void); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -// This macro should be called in the instance() method -// of the Concrete class that will be managed. Along -// with the appropriate template instantiation. -#define ACE_REGISTER_FRAMEWORK_COMPONENT(CLASS, INSTANCE) \ - ACE_Framework_Repository::instance ()->register_component \ - (new ACE_Framework_Component_T (INSTANCE)); - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Framework_Component_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Framework_Component_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" -#endif /* ACE_FRAMEWORK_COMPONENT_T_H */ diff --git a/externals/ace/Free_List.cpp b/externals/ace/Free_List.cpp deleted file mode 100644 index 4da723f4898..00000000000 --- a/externals/ace/Free_List.cpp +++ /dev/null @@ -1,163 +0,0 @@ -// $Id: Free_List.cpp 81107 2008-03-27 11:12:42Z johnnyw $ - -#ifndef ACE_FREE_LIST_CPP -#define ACE_FREE_LIST_CPP - -#include "ace/Free_List.h" -#include "ace/Guard_T.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template -ACE_Free_List::~ACE_Free_List (void) -{ -} - -// Default constructor that takes in a preallocation number -// (), a low and high water mark ( and ) and an -// increment value () - -template -ACE_Locked_Free_List::ACE_Locked_Free_List (int mode, - size_t prealloc, - size_t lwm, - size_t hwm, - size_t inc) - : mode_ (mode), - free_list_ (0), - lwm_ (lwm), - hwm_ (hwm), - inc_ (inc), - size_ (0) -{ - this->alloc (prealloc); -} - -// Destructor - removes all the elements from the free_list - -template -ACE_Locked_Free_List::~ACE_Locked_Free_List (void) -{ - if (this->mode_ != ACE_PURE_FREE_LIST) - while (this->free_list_ != 0) - { - T *temp = this->free_list_; - this->free_list_ = this->free_list_->get_next (); - delete temp; - } -} - -// Inserts an element onto the free list (if we are allowed to manage -// elements withing and it pasts the high water mark, delete the -// element) - -template void -ACE_Locked_Free_List::add (T *element) -{ - ACE_MT (ACE_GUARD (ACE_LOCK, ace_mon, this->mutex_)); - - // Check to see that we not at the high water mark. - if (this->mode_ == ACE_PURE_FREE_LIST - || this->size_ < this->hwm_) - { - element->set_next (this->free_list_); - this->free_list_ = element; - this->size_++; - } - else - delete element; -} - -// Takes a element off the freelist and returns it. It creates -// new elements if we are allowed to do it and the size is at the low -// water mark. - -template T * -ACE_Locked_Free_List::remove (void) -{ - ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, 0)); - - // If we are at the low water mark, add some nodes - if (this->mode_ != ACE_PURE_FREE_LIST && this->size_ <= this->lwm_) - this->alloc (this->inc_); - - // Remove a node - T *temp = this->free_list_; - - if (temp != 0) - { - this->free_list_ = this->free_list_->get_next (); - this->size_--; - } - - return temp; -} - - -// Returns the current size of the free list - -template size_t -ACE_Locked_Free_List::size (void) -{ - return this->size_; -} - -// Resizes the free list to - -template void -ACE_Locked_Free_List::resize (size_t newsize) -{ - ACE_MT (ACE_GUARD (ACE_LOCK, ace_mon, this->mutex_)); - - // Check if we are allowed to resize - if (this->mode_ != ACE_PURE_FREE_LIST) - { - // Check to see if we grow or shrink - if (newsize < this->size_) - { - this->dealloc (this->size_ - newsize); - } - else - { - this->alloc (newsize - this->size_); - } - } -} - -// Allocates extra nodes for the freelist - -template void -ACE_Locked_Free_List::alloc (size_t n) -{ - for (; n > 0; n--) - { - T *temp = 0; - ACE_NEW (temp, T); - temp->set_next (this->free_list_); - this->free_list_ = temp; - this->size_++; - } -} - -// Removes and frees nodes from the freelist. - -template void -ACE_Locked_Free_List::dealloc (size_t n) -{ - for (; this->free_list_ != 0 && n > 0; - n--) - { - T *temp = this->free_list_; - this->free_list_ = this->free_list_->get_next (); - delete temp; - this->size_--; - } -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_FREE_LIST_CPP */ diff --git a/externals/ace/Free_List.h b/externals/ace/Free_List.h deleted file mode 100644 index 7f2ce593c7a..00000000000 --- a/externals/ace/Free_List.h +++ /dev/null @@ -1,150 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file Free_List.h - * - * $Id: Free_List.h 84619 2009-02-26 12:26:16Z johnnyw $ - * - * @author Darrell Brunsch (brunsch@cs.wustl.edu) - */ -//============================================================================= - -#ifndef ACE_FREE_LIST_H -#define ACE_FREE_LIST_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Global_Macros.h" -#include "ace/Default_Constants.h" -#include "ace/os_include/os_stddef.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Free_List - * - * @brief Implements a free list. - * - * This class maintains a free list of nodes of type T. - */ -template -class ACE_Free_List -{ -public: - /// Destructor - removes all the elements from the free_list. - virtual ~ACE_Free_List (void); - - /// Inserts an element onto the free list (if it isn't past the high - /// water mark). - virtual void add (T *element) = 0; - - /// Takes a element off the freelist and returns it. It creates - /// new elements if the size is at or below the low water mark. - virtual T *remove (void) = 0; - - /// Returns the current size of the free list. - virtual size_t size (void) = 0; - - /// Resizes the free list to @a newsize. - virtual void resize (size_t newsize) = 0; -}; - -/** - * @class ACE_Locked_Free_List - * - * @brief Implements a free list. - * - * This class maintains a free list of nodes of type T. It - * depends on the type T having a and - * method. It maintains a mutex so the freelist can be used in - * a multithreaded program . - */ -template -class ACE_Locked_Free_List : public ACE_Free_List -{ -public: - // = Initialization and termination. - /** - * Constructor takes a @a mode (i.e., ACE_FREE_LIST_WITH_POOL or - * ACE_PURE_FREE_LIST), a count of the number of nodes to - * @a prealloc, a low and high water mark (@a lwm and @a hwm) that - * indicate when to allocate more nodes, an increment value (@a inc) - * that indicates how many nodes to allocate when the list must - * grow. - */ - ACE_Locked_Free_List (int mode = ACE_FREE_LIST_WITH_POOL, - size_t prealloc = ACE_DEFAULT_FREE_LIST_PREALLOC, - size_t lwm = ACE_DEFAULT_FREE_LIST_LWM, - size_t hwm = ACE_DEFAULT_FREE_LIST_HWM, - size_t inc = ACE_DEFAULT_FREE_LIST_INC); - - /// Destructor - removes all the elements from the free_list. - virtual ~ACE_Locked_Free_List (void); - - /// Inserts an element onto the free list (if it isn't past the high - /// water mark). - virtual void add (T *element); - - /// Takes a element off the freelist and returns it. It creates - /// new elements if the size is at or below the low water mark. - virtual T *remove (void); - - /// Returns the current size of the free list. - virtual size_t size (void); - - /// Resizes the free list to @a newsize. - virtual void resize (size_t newsize); - -protected: - /// Allocates @a n extra nodes for the freelist. - virtual void alloc (size_t n); - - /// Removes and frees @a n nodes from the freelist. - virtual void dealloc (size_t n); - - /// Free list operation mode, either ACE_FREE_LIST_WITH_POOL or - /// ACE_PURE_FREE_LIST. - int mode_; - - /// Pointer to the first node in the freelist. - T *free_list_; - - /// Low water mark. - size_t lwm_; - - /// High water mark. - size_t hwm_; - - /// Increment value. - size_t inc_; - - /// Keeps track of the size of the list. - size_t size_; - - /// Synchronization variable for ACE_Timer_Queue. - ACE_LOCK mutex_; - -private: - // = Don't allow these operations for now. - ACE_UNIMPLEMENTED_FUNC (ACE_Locked_Free_List (const ACE_Locked_Free_List &)) - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Locked_Free_List &)) -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Free_List.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Free_List.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" -#endif /* ACE_FREE_LIST_H */ diff --git a/externals/ace/Functor.cpp b/externals/ace/Functor.cpp deleted file mode 100644 index 429aaac9f22..00000000000 --- a/externals/ace/Functor.cpp +++ /dev/null @@ -1,43 +0,0 @@ - -//============================================================================= -/** - * @file Functor.cpp - * - * $Id: Functor.cpp 80826 2008-03-04 14:51:23Z wotte $ - * - * Non-inlinable method definitions for non-templatized classes - * and template specializations implementing the GOF Command Pattern, - * and STL-style functors. - * - * - * @author Chris Gill - * - * Based on Command Pattern implementations originally done by - * - * Carlos O'Ryan - * Douglas C. Schmidt - * Sergio Flores-Gaitan - * - * and on STL-style functor implementations originally done by - * - * Irfan Pyarali - */ -//============================================================================= - - -#include "ace/Functor_T.h" -#include "ace/Functor.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Functor.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID(ace, Functor, "$Id: Functor.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_Command_Base::~ACE_Command_Base (void) -{ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Functor.h b/externals/ace/Functor.h deleted file mode 100644 index ec1d285061f..00000000000 --- a/externals/ace/Functor.h +++ /dev/null @@ -1,523 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file Functor.h - * - * $Id: Functor.h 86698 2009-09-13 15:58:17Z johnnyw $ - * - * Non-templatized classes and class template specializations for - * implementing function objects that are used in various places - * in ACE. There are currently two major categories of function - * objects in ACE: GoF Command Pattern objects, and STL-style - * functors for comparison of container elements. The command objects - * are invoked via an execute () method, while the STL-style functors are - * invoked via an operator() () method. - * Non-templatized classes for implementing the GoF Command Pattern, - * also known as functors or function objects. - * - * - * @author Chris Gill - * @author Based on Command Pattern implementations originally done by - * @author Carlos O'Ryan - * @author Douglas C. Schmidt - * @author Sergio Flores-Gaitan - * @author and on STL-style functor implementations originally done by - * @author Irfan Pyarali - */ -//========================================================================== - - -#ifndef ACE_FUNCTOR_H -#define ACE_FUNCTOR_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include /**/ "ace/ACE_export.h" -#include "ace/Basic_Types.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -////////////////////////////////////////////////////////////// -// GOF Command Pattern Classes and Template Specializations // -////////////////////////////////////////////////////////////// - -/** - * @class ACE_Command_Base - * - * @brief Defines an abstract class that allows us to invoke commands - * without knowing anything about the implementation. - * - * This class declares an interface to execute a command - * independent of the effect of the command, or the objects used - * to implement it. - */ -class ACE_Export ACE_Command_Base -{ -public: - // = Initialization and termination methods. - /// Default constructor. - ACE_Command_Base (void); - - /// Virtual destructor. - virtual ~ACE_Command_Base (void); - - /** - * Invokes the method encapsulated by the command, passing along the - * passed argument (if any). Users of classes derived from this - * class must ensure that the resulting invocation can tolerate a - * null void pointer being passed, or otherwise ensure that this - * will never occur. - */ - virtual int execute (void *arg = 0) = 0; -}; - -//////////////////////////////////////////////////////////// -// STL-style Functor Classes and Template Specializations // -//////////////////////////////////////////////////////////// - -// Forward declaration since we are going to specialize that template -// here. The template itself requires this file so every user of the -// template should also see the specialization. -template class ACE_Hash; -template class ACE_Equal_To; -template class ACE_Less_Than; - -/** - * @brief Function object for hashing a char - */ -template<> -class ACE_Export ACE_Hash -{ -public: - /// Simply returns t - unsigned long operator () (char t) const; -}; - -/** - * @brief Function object for hashing a signed char - */ -template<> -class ACE_Export ACE_Hash -{ -public: - /// Simply returns t - unsigned long operator () (signed char t) const; -}; - -/** - * @brief Function object for hashing an unsigned char - */ -template<> -class ACE_Export ACE_Hash -{ -public: - /// Simply returns t - unsigned long operator () (unsigned char t) const; -}; - -#if 0 -// @@ ADD HASHES FOR ACE TYPES - -/** - * @brief Function object for hashing a 16-bit signed number - */ -template<> -class ACE_Export ACE_Hash -{ -public: - /// Simply returns t - unsigned long operator () (ACE_INT16 t) const; -}; - -/** - * @brief Function object for hashing a 16-bit unsigned number - */ -template<> -class ACE_Export ACE_Hash -{ -public: - /// Simply returns t - unsigned long operator () (ACE_UINT16 t) const; -}; - -/** - * @brief Function object for hashing a 32-bit signed number - */ -template<> -class ACE_Export ACE_Hash -{ -public: - /// Simply returns t - unsigned long operator () (ACE_INT32 t) const; -}; - -/** - * @brief Function object for hashing a 32-bit unsigned number - */ -template<> -class ACE_Export ACE_Hash -{ -public: - /// Simply returns t - unsigned long operator () (ACE_UINT32 t) const; -}; - -/** - * @brief Function object for hashing a 64-bit unsigned number - */ -template<> -class ACE_Export ACE_Hash -{ -public: - /// Simply returns t - unsigned long operator () (ACE_UINT64 t) const; -}; - -// @@ DONE ADDING HASHES FOR ACE TYPES -#endif - -/** - * @brief Function object for hashing a short number - */ -template<> -class ACE_Export ACE_Hash -{ -public: - /// Simply returns t - unsigned long operator () (short t) const; -}; - -/** - * @brief Function object for hashing an unsigned short number - */ -template<> -class ACE_Export ACE_Hash -{ -public: - /// Simply returns t - unsigned long operator () (unsigned short t) const; -}; - -/** - * @brief Function object for hashing an int number - */ -template<> -class ACE_Export ACE_Hash -{ -public: - /// Simply returns t - unsigned long operator () (int t) const; -}; - -/** - * @brief Function object for hashing an unsigned int number - */ -template<> -class ACE_Export ACE_Hash -{ -public: - /// Simply returns t - unsigned long operator () (unsigned int t) const; -}; - -/** - * @brief Function object for hashing a long number - */ -template<> -class ACE_Export ACE_Hash -{ -public: - /// Simply returns t - unsigned long operator () (long t) const; -}; - -/** - * @brief Function object for hashing an unsigned long number - */ -template<> -class ACE_Export ACE_Hash -{ -public: - /// Simply returns t - unsigned long operator () (unsigned long t) const; -}; - -#if !defined (ACE_LACKS_LONGLONG_T) && (ACE_SIZEOF_LONG < 8) -/** - * @brief Function object for hashing a signed 64-bit number - */ -template<> -class ACE_Export ACE_Hash -{ -public: - /// Simply returns t - unsigned long operator () (ACE_INT64 t) const; -}; -#endif /* !ACE_LACKS_LONGLONG_T && ACE_SIZEOF_LONG < 8 */ - -// We can do this even if ACE_LACKS_UNSIGNEDLONGLONG_T because there's an -// emulation for it in ACE_U_LongLong. -#if (ACE_SIZEOF_LONG < 8) -/** - * @brief Function object for hashing an unsigned 64-bit number - */ -template<> -class ACE_Export ACE_Hash -{ -public: - /// Simply returns t - unsigned long operator () (const ACE_UINT64 &t) const; -}; -#endif /* ACE_SIZEOF_LONG < 8 */ - -/** - * @brief Function object for hashing a const string - */ -template<> -class ACE_Export ACE_Hash -{ -public: - /// Calls ACE::hash_pjw - unsigned long operator () (const char *t) const; -}; - -/** - * @brief Function object for hashing a string - */ -template<> -class ACE_Export ACE_Hash -{ -public: - /// Calls ACE::hash_pjw - unsigned long operator () (const char *t) const; -}; - -/** - * @brief Function object for hashing a void * - */ -template<> -class ACE_Export ACE_Hash -{ -public: - unsigned long operator () (const void *) const; -}; - -/** - * @brief Function object for determining whether two const strings are equal. - */ -template<> -class ACE_Export ACE_Equal_To -{ -public: - /// Simply calls ACE_OS::strcmp - int operator () (const char *lhs, - const char *rhs) const; -}; - -/** - * @brief Function object for determining whether two non-const - * strings are equal. - */ -template<> -class ACE_Export ACE_Equal_To -{ -public: - /// Simply calls ACE_OS::strcmp - int operator () (const char *lhs, - const char *rhs) const; -}; - -/** - * @brief Function object for determining whether two unsigned - * 16 bit ints are equal. - */ -template<> -class ACE_Export ACE_Equal_To -{ -public: - /// Simply calls built-in operators - int operator () (const ACE_UINT16 lhs, - const ACE_UINT16 rhs) const; -}; - -/** - * @brief Function object for determining whether two - * 16 bit ints are equal. - */ -template<> -class ACE_Export ACE_Equal_To -{ -public: - /// Simply calls built-in operators - int operator () (const ACE_INT16 lhs, - const ACE_INT16 rhs) const; -}; - -/** - * @brief Function object for determining whether two unsigned - * 32 bit ints are equal. - */ -template<> -class ACE_Export ACE_Equal_To -{ -public: - /// Simply calls built-in operators - int operator () (const ACE_UINT32 lhs, - const ACE_UINT32 rhs) const; -}; - -/** - * @brief Function object for determining whether two - * 32 bit ints are equal. - */ -template<> -class ACE_Export ACE_Equal_To -{ -public: - /// Simply calls built-in operators - int operator () (const ACE_INT32 lhs, - const ACE_INT32 rhs) const; -}; - -/** - * @brief Function object for determining whether two unsigned - * 64 bit ints are equal. - */ -template<> -class ACE_Export ACE_Equal_To -{ -public: - /// Simply calls built-in operators - int operator () (const ACE_UINT64 lhs, - const ACE_UINT64 rhs) const; -}; - -/** - * @brief Function object for determining whether the first const string - * is less than the second const string. - */ -template<> -class ACE_Export ACE_Less_Than -{ -public: - /// Simply calls ACE_OS::strcmp - int operator () (const char *lhs, - const char *rhs) const; -}; - -/** - * @brief Function object for determining whether the first string - * is less than the second string. - */ -template<> -class ACE_Export ACE_Less_Than -{ -public: - /// Simply calls ACE_OS::strcmp - int operator () (const char *lhs, - const char *rhs) const; -}; - -#if defined (ACE_HAS_WCHAR) - -# if ! defined (ACE_LACKS_NATIVE_WCHAR_T) -/** - * @brief Function object for hashing a wchar_t - */ -template<> -class ACE_Export ACE_Hash -{ -public: - /// Simply returns t - unsigned long operator () (wchar_t t) const; -}; -# endif /* ACE_LACKS_NATIVE_WCHAR_T */ -/** - * @brief Function object for hashing a const string - */ -template<> -class ACE_Export ACE_Hash -{ -public: - /// Calls ACE::hash_pjw - unsigned long operator () (const wchar_t *t) const; -}; - -/** - * @brief Function object for hashing a string - */ -template<> -class ACE_Export ACE_Hash -{ -public: - /// Calls ACE::hash_pjw - unsigned long operator () (const wchar_t *t) const; -}; - -/** - * @brief Function object for determining whether two const strings are equal. - */ -template<> -class ACE_Export ACE_Equal_To -{ -public: - /// Simply calls ACE_OS::strcmp - int operator () (const wchar_t *lhs, - const wchar_t *rhs) const; -}; - -/** - * @brief Function object for determining whether two non-const - * strings are equal. - */ -template<> -class ACE_Export ACE_Equal_To -{ -public: - /// Simply calls ACE_OS::strcmp - int operator () (const wchar_t *lhs, - const wchar_t *rhs) const; -}; - -/** - * @brief Function object for determining whether the first const string - * is less than the second const string. - */ -template<> -class ACE_Export ACE_Less_Than -{ -public: - /// Simply calls ACE_OS::strcmp - int operator () (const wchar_t *lhs, - const wchar_t *rhs) const; -}; - -/** - * @brief Function object for determining whether the first string - * is less than the second string. - */ -template<> -class ACE_Export ACE_Less_Than -{ -public: - /// Simply calls ACE_OS::strcmp - int operator () (const wchar_t *lhs, - const wchar_t *rhs) const; -}; - -#endif // ACE_HAS_WCHAR - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Functor.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_FUNCTOR_H */ diff --git a/externals/ace/Functor.inl b/externals/ace/Functor.inl deleted file mode 100644 index 30e539459a8..00000000000 --- a/externals/ace/Functor.inl +++ /dev/null @@ -1,284 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Functor.inl - * - * $Id: Functor.inl 80826 2008-03-04 14:51:23Z wotte $ - * - * Inlinable method definitions for non-templatized classes - * and template specializations implementing the GOF Command Pattern, - * and STL-style functors. - * - * - * @author Chris Gill - * - * Based on Command Pattern implementations originally done by - * - * Carlos O'Ryan - * Douglas C. Schmidt - * Sergio Flores-Gaitan - * - * and on STL-style functor implementations originally done by - * Irfan Pyarali - */ -//============================================================================= - - -#include "ace/ACE.h" -#include "ace/OS_NS_string.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -////////////////////////////////////////////////////////////// -// GOF Command Pattern Classes and Template Specializations // -////////////////////////////////////////////////////////////// - -// Default constructor. - -ACE_INLINE -ACE_Command_Base::ACE_Command_Base (void) -{ -} - -//////////////////////////////////////////////////////////// -// STL-style Functor Classes and Template Specializations // -//////////////////////////////////////////////////////////// - -ACE_INLINE unsigned long -ACE_Hash::operator () (char t) const -{ - return t; -} - -#if defined (ACE_HAS_WCHAR) && ! defined (ACE_LACKS_NATIVE_WCHAR_T) -ACE_INLINE unsigned long -ACE_Hash::operator () (wchar_t t) const -{ - return t; -} -#endif /* ACE_HAS_WCHAR && ! ACE_LACKS_NATIVE_WCHAR_T */ - -ACE_INLINE unsigned long -ACE_Hash::operator () (signed char t) const -{ - return t; -} - -ACE_INLINE unsigned long -ACE_Hash::operator () (unsigned char t) const -{ - return t; -} - -#if 0 -ACE_INLINE unsigned long -ACE_Hash::operator () (ACE_INT16 t) const -{ - return t; -} - -ACE_INLINE unsigned long -ACE_Hash::operator () (ACE_UINT16 t) const -{ - return t; -} - -ACE_INLINE unsigned long -ACE_Hash::operator () (ACE_INT32 t) const -{ - return static_cast (t); -} - -ACE_INLINE unsigned long -ACE_Hash::operator () (ACE_UINT32 t) const -{ - return t; -} - -ACE_INLINE unsigned long -ACE_Hash::operator () (ACE_UINT64 t) const -{ -#if (ACE_SIZEOF_LONG == 4) - return ACE_U64_TO_U32 (t); -#else - return static_cast (t); -#endif /* ACE_SIZEOF_LONG */ -} -#endif - -ACE_INLINE unsigned long -ACE_Hash::operator () (short t) const -{ - return static_cast (t); -} - -ACE_INLINE unsigned long -ACE_Hash::operator () (unsigned short t) const -{ - return static_cast (t); -} - -ACE_INLINE unsigned long -ACE_Hash::operator () (int t) const -{ - return static_cast (t); -} - -ACE_INLINE unsigned long -ACE_Hash::operator () (unsigned int t) const -{ - return static_cast (t); -} - -ACE_INLINE unsigned long -ACE_Hash::operator () (long t) const -{ - return static_cast (t); -} - -ACE_INLINE unsigned long -ACE_Hash::operator () (unsigned long t) const -{ - return t; -} - -// This #if needs to match the one in Functor.h -#if !defined (ACE_LACKS_LONGLONG_T) && (ACE_SIZEOF_LONG < 8) -ACE_INLINE unsigned long -ACE_Hash::operator () (ACE_INT64 t) const -{ - return static_cast (t); -} -#endif /* !ACE_LACKS_LONGLONG_T && ACE_SIZEOF_LONG < 8 */ - -#if (ACE_SIZEOF_LONG < 8) -ACE_INLINE unsigned long -ACE_Hash::operator () (const ACE_UINT64 &t) const -{ -#if (ACE_SIZEOF_LONG == 4) - return ACE_U64_TO_U32 (t); -#else - return static_cast (t); -#endif /* ACE_SIZEOF_LONG */ -} -#endif /* !ACE_LACKS_UNSIGNEDLONGLONG_T */ - -ACE_INLINE unsigned long -ACE_Hash::operator () (const char *t) const -{ - return ACE::hash_pjw (t); -} - -ACE_INLINE unsigned long -ACE_Hash::operator () (const char *t) const -{ - return ACE::hash_pjw (t); -} - -ACE_INLINE unsigned long -ACE_Hash::operator () (const void *t) const -{ - return static_cast (reinterpret_cast (t)); -} - -/***********************************************************************/ -ACE_INLINE int -ACE_Equal_To::operator () (const char *lhs, const char *rhs) const -{ - return !ACE_OS::strcmp (lhs, rhs); -} - -ACE_INLINE int -ACE_Equal_To::operator () (const char *lhs, const char *rhs) const -{ - return !ACE_OS::strcmp (lhs, rhs); -} - -ACE_INLINE int -ACE_Equal_To::operator () (const ACE_UINT16 lhs, const ACE_UINT16 rhs) const -{ - return (lhs == rhs); -} - -ACE_INLINE int -ACE_Equal_To::operator () (const ACE_INT16 lhs, const ACE_INT16 rhs) const -{ - return (lhs == rhs); -} - -ACE_INLINE int -ACE_Equal_To::operator () (const ACE_UINT32 lhs, const ACE_UINT32 rhs) const -{ - return (lhs == rhs); -} - -ACE_INLINE int -ACE_Equal_To::operator () (const ACE_INT32 lhs, const ACE_INT32 rhs) const -{ - return (lhs == rhs); -} - -ACE_INLINE int -ACE_Equal_To::operator () (const ACE_UINT64 lhs, const ACE_UINT64 rhs) const -{ - return (lhs == rhs); -} - -/****************************************************************************/ -ACE_INLINE int -ACE_Less_Than::operator () (const char *lhs, const char *rhs) const -{ - return (ACE_OS::strcmp (lhs, rhs) < 0) ? 1 : 0; -} - -ACE_INLINE int -ACE_Less_Than::operator () (const char *lhs, const char *rhs) const -{ - return (ACE_OS::strcmp (lhs, rhs) < 0) ? 1 : 0; -} - - -#if defined (ACE_HAS_WCHAR) - -ACE_INLINE unsigned long -ACE_Hash::operator () (const wchar_t *t) const -{ - return ACE::hash_pjw (t); -} - -ACE_INLINE unsigned long -ACE_Hash::operator () (const wchar_t *t) const -{ - return ACE::hash_pjw (t); -} - -ACE_INLINE int -ACE_Equal_To::operator () (const wchar_t *lhs, - const wchar_t *rhs) const -{ - return !ACE_OS::strcmp (lhs, rhs); -} - -ACE_INLINE int -ACE_Equal_To::operator () (const wchar_t *lhs, - const wchar_t *rhs) const -{ - return !ACE_OS::strcmp (lhs, rhs); -} - -ACE_INLINE int -ACE_Less_Than::operator () (const wchar_t *lhs, const wchar_t *rhs) const -{ - return (ACE_OS::strcmp (lhs, rhs) < 0) ? 1 : 0; -} - -ACE_INLINE int -ACE_Less_Than::operator () (const wchar_t *lhs, const wchar_t *rhs) const -{ - return (ACE_OS::strcmp (lhs, rhs) < 0) ? 1 : 0; -} - -#endif // ACE_HAS_WCHAR - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Functor_String.cpp b/externals/ace/Functor_String.cpp deleted file mode 100644 index c113f5cdf6f..00000000000 --- a/externals/ace/Functor_String.cpp +++ /dev/null @@ -1,7 +0,0 @@ -#include "ace/Functor_String.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Functor_String.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID(ace, Functor, "$Id: Functor_String.cpp 80826 2008-03-04 14:51:23Z wotte $") diff --git a/externals/ace/Functor_String.h b/externals/ace/Functor_String.h deleted file mode 100644 index 2adf561a65f..00000000000 --- a/externals/ace/Functor_String.h +++ /dev/null @@ -1,129 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file Functor_String.h - * - * $Id: Functor_String.h 86698 2009-09-13 15:58:17Z johnnyw $ - * - * Class template specializations for ACE_*String types implementing - * function objects that are used in various places in ATC. They - * could be placed in Functor.h. But we don't want to couple string - * types to the rest of ACE+TAO. Hence they are placed in a seperate - * file. - */ -//========================================================================== -#ifndef ACE_FUNCTOR_STRING_H -#define ACE_FUNCTOR_STRING_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include /**/ "ace/ACE_export.h" -#include "ace/SStringfwd.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -//////////////////////////////////////////////////////////// -// STL-style Functor Classes and Template Specializations // -//////////////////////////////////////////////////////////// - -// Forward declaration since we are going to specialize that template -// here. The template itself requires this file so every user of the -// template should also see the specialization. -template class ACE_Hash; -template class ACE_Equal_To; -template class ACE_Less_Than; - -/** - * @brief Function object for determining whether two ACE_CStrings are - * equal. - */ -template<> -class ACE_Export ACE_Equal_To -{ -public: - int operator () (const ACE_CString &lhs, - const ACE_CString &rhs) const; -}; - - -/** - * @brief Function object for hashing a ACE_CString - */ -template<> -class ACE_Export ACE_Hash -{ -public: - /// Calls ACE::hash_pjw - unsigned long operator () (const ACE_CString &lhs) const; -}; - - -/** - * @brief Function object for determining whether the first const string - * is less than the second const string. - */ -template<> -class ACE_Export ACE_Less_Than -{ -public: - /// Simply calls ACE_OS::strcmp - int operator () (const ACE_CString &lhs, - const ACE_CString &rhs) const; -}; - - -#if defined (ACE_USES_WCHAR) - -/** - * @brief Function object for determining whether two ACE_WStrings are - * equal. - */ -template<> -class ACE_Export ACE_Equal_To -{ -public: - int operator () (const ACE_WString &lhs, - const ACE_WString &rhs) const; -}; - - -/** - * @brief Function object for hashing a ACE_WString - */ -template<> -class ACE_Export ACE_Hash -{ -public: - /// Calls ACE::hash_pjw - unsigned long operator () (const ACE_WString &lhs) const; -}; - -/** - * @brief Function object for determining whether the first const wstring - * is less than the second const wstring. - */ -template<> -class ACE_Export ACE_Less_Than -{ -public: - /// Simply calls ACE_OS::strcmp - int operator () (const ACE_WString &lhs, - const ACE_WString &rhs) const; -}; - -#endif /*ACE_USES_WCHAR*/ - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Functor_String.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /*ACE_FUNCTOR_STRING_H*/ diff --git a/externals/ace/Functor_String.inl b/externals/ace/Functor_String.inl deleted file mode 100644 index bdac96386f8..00000000000 --- a/externals/ace/Functor_String.inl +++ /dev/null @@ -1,56 +0,0 @@ -// -*- C++ -*- -// -// $Id: Functor_String.inl 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/ACE.h" -#include "ace/String_Base.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE unsigned long -ACE_Hash::operator () (const ACE_CString &t) const -{ - return t.hash (); -} - - -ACE_INLINE int -ACE_Equal_To::operator () (const ACE_CString &lhs, - const ACE_CString &rhs) const -{ - return lhs == rhs; -} - -ACE_INLINE int -ACE_Less_Than::operator () (const ACE_CString &lhs, - const ACE_CString &rhs) const -{ - return (lhs < rhs); -} - - -#if defined (ACE_USES_WCHAR) -ACE_INLINE unsigned long -ACE_Hash::operator () (const ACE_WString &t) const -{ - return t.hash (); -} - - -ACE_INLINE int -ACE_Equal_To::operator () (const ACE_WString &lhs, - const ACE_WString &rhs) const -{ - return lhs == rhs; -} - -ACE_INLINE int -ACE_Less_Than::operator () (const ACE_WString &lhs, - const ACE_WString &rhs) const -{ - return (lhs < rhs); -} - -#endif /*ACE_USES_WCHAR*/ - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Functor_T.cpp b/externals/ace/Functor_T.cpp deleted file mode 100644 index 213b501aac1..00000000000 --- a/externals/ace/Functor_T.cpp +++ /dev/null @@ -1,49 +0,0 @@ -// $Id: Functor_T.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#ifndef ACE_FUNCTOR_T_CPP -#define ACE_FUNCTOR_T_CPP - -#include "ace/Functor_T.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (__ACE_INLINE__) -#include "ace/Functor_T.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Command_Callback) - -/////////////////////////////////// -// GOF Command Pattern Templates // -/////////////////////////////////// - -// Constructor. - -template -ACE_Command_Callback::ACE_Command_Callback (RECEIVER &recvr, - ACTION action) - : receiver_ (recvr), - action_ (action) -{ -} - -template -ACE_Command_Callback::~ACE_Command_Callback (void) -{ -} - -// Invokes an operation. - -template int -ACE_Command_Callback::execute (void *arg) -{ - return (receiver_.*action_) (arg); -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_FUNCTOR_T_CPP */ diff --git a/externals/ace/Functor_T.h b/externals/ace/Functor_T.h deleted file mode 100644 index f055c3c885e..00000000000 --- a/externals/ace/Functor_T.h +++ /dev/null @@ -1,158 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file Functor_T.h - * - * $Id: Functor_T.h 80826 2008-03-04 14:51:23Z wotte $ - * - * Templatized classes for implementing function objects that are - * used in various places in ACE. There are currently two major - * categories of function objects in ACE: GOF Command Pattern - * objects, and STL-style functors for comparison of container - * elements. The command objects are invoked via an - * method, while the STL-style functors are invoked via an - * method. - * - * - * @author Chris Gill - * @author Based on Command Pattern implementations originally done by - * @author Carlos O'Ryan - * @author Douglas C. Schmidt - * @author Sergio Flores-Gaitan - * @author and on STL-style functor implementations originally done by - * @author Irfan Pyarali - */ -//============================================================================= - - -#ifndef ACE_FUNCTOR_T_H -#define ACE_FUNCTOR_T_H -#include /**/ "ace/pre.h" - -#include "ace/Functor.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Functor_String.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/////////////////////////////////// -// GOF Command Pattern Templates // -/////////////////////////////////// - -/** - * @class ACE_Command_Callback - * - * @brief Defines a class template that allows us to invoke a GOF - * command style callback to an object without knowing anything - * about the object except its type. - * - * This class declares an interface to execute operations, - * binding a RECEIVER object with an ACTION. The RECEIVER knows - * how to implement the operation. A class can invoke operations - * without knowing anything about it, or how it was implemented. - */ -template -class ACE_Command_Callback : public ACE_Command_Base -{ -public: - /// Constructor: sets the of the Command to recvr, and the - /// of the Command to . - ACE_Command_Callback (RECEIVER &recvr, ACTION action); - - /// Virtual destructor. - virtual ~ACE_Command_Callback (void); - - /// Invokes the method from the object . - virtual int execute (void *arg = 0); - -private: - /// Object where the method resides. - RECEIVER &receiver_; - - /// Method that is going to be invoked. - ACTION action_; -}; - -///////////////////////////////// -// STL-style Functor Templates // -///////////////////////////////// - -/** - * @class ACE_Hash - * - * @brief Function object for hashing - */ -template -class ACE_Hash -{ -public: - /// Simply calls t.hash () - unsigned long operator () (const TYPE &t) const; -}; - -/** - * @class ACE_Pointer_Hash - * - * @brief Function object for hashing pointers - */ -template -class ACE_Pointer_Hash -{ -public: - /// Simply returns t. - unsigned long operator () (TYPE t) const; -}; - -/** - * @class ACE_Equal_To - * - * @brief Function object for comparing two objects of - * the given type for equality. - */ -template -class ACE_Equal_To -{ -public: - /// Simply calls operator== - bool operator () (const TYPE &lhs, - const TYPE &rhs) const; -}; - -/** - * @class ACE_Less_Than - * - * @brief Function object for determining whether the first object of - * the given type is less than the second object of the same - * type. - */ -template -class ACE_Less_Than -{ -public: - /// Simply calls operator< - bool operator () (const TYPE &lhs, - const TYPE &rhs) const; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Functor_T.inl" -#endif /* __ACE_INLINE__ */ - - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Functor_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Functor_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" -#endif /* ACE_FUNCTOR_T_H */ diff --git a/externals/ace/Functor_T.inl b/externals/ace/Functor_T.inl deleted file mode 100644 index 35cfed5b798..00000000000 --- a/externals/ace/Functor_T.inl +++ /dev/null @@ -1,42 +0,0 @@ -// -*- C++ -*- -// -// $Id: Functor_T.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template ACE_INLINE unsigned long -ACE_Hash::operator () (const TYPE &t) const -{ - return t.hash (); -} - -template ACE_INLINE unsigned long -ACE_Pointer_Hash::operator () (TYPE t) const -{ -#if defined (ACE_WIN64) - // The cast below is legit... we only want a hash, and need not convert - // the hash back to a pointer. -# pragma warning(push) -# pragma warning(disable : 4311) /* Truncate pointer to unsigned long */ -#endif /* ACE_WIN64 */ - return reinterpret_cast (t); -#if defined (ACE_WIN64) -# pragma warning(pop) -#endif /* ACE_WIN64 */ -} - -template ACE_INLINE bool -ACE_Equal_To::operator () (const TYPE &lhs, - const TYPE &rhs) const -{ - return lhs == rhs; -} - -template ACE_INLINE bool -ACE_Less_Than::operator () (const TYPE &lhs, - const TYPE &rhs) const -{ - return lhs < rhs; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Future.cpp b/externals/ace/Future.cpp deleted file mode 100644 index da40c468f31..00000000000 --- a/externals/ace/Future.cpp +++ /dev/null @@ -1,434 +0,0 @@ - // $Id: Future.cpp 85358 2009-05-17 10:34:33Z johnnyw $ - -#ifndef ACE_FUTURE_CPP -#define ACE_FUTURE_CPP - -#include "ace/Future.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_RCSID (ace, Future, "$Id: Future.cpp 85358 2009-05-17 10:34:33Z johnnyw $") - -#if defined (ACE_HAS_THREADS) - -# include "ace/Guard_T.h" -# include "ace/Recursive_Thread_Mutex.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template -ACE_Future_Holder::ACE_Future_Holder (void) -{ -} - -template -ACE_Future_Holder::ACE_Future_Holder (const ACE_Future &item) - : item_ (item) -{ -} - -template -ACE_Future_Holder::~ACE_Future_Holder (void) -{ -} - -template -ACE_Future_Observer::ACE_Future_Observer (void) -{ -} - -template -ACE_Future_Observer::~ACE_Future_Observer (void) -{ -} - -// Dump the state of an object. - -template void -ACE_Future_Rep::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, - "ref_count_ = %d\n", - (int) this->ref_count_)); - ACE_DEBUG ((LM_INFO,"value_:\n")); - if (this->value_) - ACE_DEBUG ((LM_DEBUG, ACE_TEXT (" (NON-NULL)\n"))); - else - //FUZZ: disable check_for_NULL - ACE_DEBUG ((LM_DEBUG, ACE_TEXT (" (NULL)\n"))); - //FUZZ: enable check_for_NULL - - ACE_DEBUG ((LM_INFO,"value_ready_:\n")); - this->value_ready_.dump (); - ACE_DEBUG ((LM_INFO,"value_ready_mutex_:\n")); - this->value_ready_mutex_.dump (); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -template ACE_Future_Rep * -ACE_Future_Rep::internal_create (void) -{ - ACE_Future_Rep *temp = 0; - ACE_NEW_RETURN (temp, - ACE_Future_Rep (), - 0); - return temp; -} - -template ACE_Future_Rep * -ACE_Future_Rep::create (void) -{ - // Yes set ref count to zero. - ACE_Future_Rep *temp = internal_create (); -#if defined (ACE_NEW_THROWS_EXCEPTIONS) - if (temp == 0) - ACE_throw_bad_alloc; -#else - ACE_ASSERT (temp != 0); -#endif /* ACE_NEW_THROWS_EXCEPTIONS */ - return temp; - } - - -template ACE_Future_Rep * -ACE_Future_Rep::attach (ACE_Future_Rep*& rep) -{ - ACE_ASSERT (rep != 0); - // Use value_ready_mutex_ for both condition and ref count management - ACE_MT (ACE_Guard r_mon (rep->value_ready_mutex_)); - ++rep->ref_count_; - return rep; -} - -template void -ACE_Future_Rep::detach (ACE_Future_Rep*& rep) -{ - ACE_ASSERT (rep != 0); - // Use value_ready_mutex_ for both condition and ref count management - ACE_MT (ACE_GUARD (ACE_Recursive_Thread_Mutex, r_mon, rep->value_ready_mutex_)); - - if (rep->ref_count_-- == 0) - { - ACE_MT (r_mon.release ()); - // We do not need the lock when deleting the representation. - // There should be no side effects from deleting rep and we don - // not want to release a deleted mutex. - delete rep; - } -} - -template void -ACE_Future_Rep::assign (ACE_Future_Rep*& rep, ACE_Future_Rep* new_rep) -{ - ACE_ASSERT (rep != 0); - ACE_ASSERT (new_rep != 0); - // Use value_ready_mutex_ for both condition and ref count management - ACE_MT (ACE_GUARD (ACE_Recursive_Thread_Mutex, r_mon, rep->value_ready_mutex_)); - - ACE_Future_Rep* old = rep; - rep = new_rep; - - // detached old last for exception safety - if (old->ref_count_-- == 0) - { - ACE_MT (r_mon.release ()); - // We do not need the lock when deleting the representation. - // There should be no side effects from deleting rep and we don - // not want to release a deleted mutex. - delete old; - } -} - -template -ACE_Future_Rep::ACE_Future_Rep (void) - : value_ (0), - ref_count_ (0), - value_ready_ (value_ready_mutex_) -{ -} - -template -ACE_Future_Rep::~ACE_Future_Rep (void) -{ - delete this->value_; -} - -template int -ACE_Future_Rep::ready (void) const -{ - return this->value_ != 0; -} - -template int -ACE_Future_Rep::set (const T &r, - ACE_Future &caller) -{ - // If the value is already produced, ignore it... - if (this->value_ == 0) - { - ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, - ace_mon, - this->value_ready_mutex_, - -1)); - // Otherwise, create a new result value. Note the use of the - // Double-checked locking pattern to avoid multiple allocations. - - if (this->value_ == 0) // Still no value, so proceed - { - ACE_NEW_RETURN (this->value_, - T (r), - -1); - - // Remove and notify all subscribed observers. - typename OBSERVER_COLLECTION::iterator iterator = - this->observer_collection_.begin (); - - typename OBSERVER_COLLECTION::iterator end = - this->observer_collection_.end (); - - while (iterator != end) - { - OBSERVER *observer = *iterator++; - observer->update (caller); - } - - // Signal all the waiting threads. - return this->value_ready_.broadcast (); - } - // Destructor releases the lock. - } - return 0; -} - -template int -ACE_Future_Rep::get (T &value, - ACE_Time_Value *tv) const -{ - // If the value is already produced, return it. - if (this->value_ == 0) - { - ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, - this->value_ready_mutex_, - -1)); - // If the value is not yet defined we must block until the - // producer writes to it. - - while (this->value_ == 0) - // Perform a timed wait. - if (this->value_ready_.wait (tv) == -1) - return -1; - - // Destructor releases the lock. - } - - value = *this->value_; - return 0; -} - -template int -ACE_Future_Rep::attach (ACE_Future_Observer *observer, - ACE_Future &caller) -{ - ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, this->value_ready_mutex_, -1)); - - // Otherwise, create a new result value. Note the use of the - // Double-checked locking pattern to avoid corrupting the list. - - int result = 1; - - // If the value is already produced, then notify observer - if (this->value_ == 0) - result = this->observer_collection_.insert (observer); - else - observer->update (caller); - - return result; -} - -template int -ACE_Future_Rep::detach (ACE_Future_Observer *observer) -{ - ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, this->value_ready_mutex_, -1)); - - // Remove all occurrences of the specified observer from this - // objects hash map. - return this->observer_collection_.remove (observer); -} - -template -ACE_Future_Rep::operator T () -{ - // If the value is already produced, return it. - if (this->value_ == 0) - { - // Constructor of ace_mon acquires the mutex. - ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, this->value_ready_mutex_, 0)); - - // If the value is not yet defined we must block until the - // producer writes to it. - - // Wait ``forever.'' - - while (this->value_ == 0) - if (this->value_ready_.wait () == -1) - // What to do in this case since we've got to indicate - // failure somehow? Exceptions would be nice, but they're - // not portable... - return 0; - - // Destructor releases the mutex - } - - return *this->value_; -} - -template -ACE_Future::ACE_Future (void) - : future_rep_ (FUTURE_REP::create ()) -{ -} - -template -ACE_Future::ACE_Future (const ACE_Future &r) - : future_rep_ (FUTURE_REP::attach (((ACE_Future &) r).future_rep_)) -{ -} - -template -ACE_Future::ACE_Future (const T &r) - : future_rep_ (FUTURE_REP::create ()) -{ - this->future_rep_->set (r, *this); -} - -template -ACE_Future::~ACE_Future (void) -{ - FUTURE_REP::detach (future_rep_); -} - -template bool -ACE_Future::operator== (const ACE_Future &r) const -{ - return r.future_rep_ == this->future_rep_; -} - -template bool -ACE_Future::operator!= (const ACE_Future &r) const -{ - return r.future_rep_ != this->future_rep_; -} - -template int -ACE_Future::cancel (const T &r) -{ - this->cancel (); - return this->future_rep_->set (r, *this); -} - -template int -ACE_Future::cancel (void) -{ - // If this ACE_Future is already attached to a ACE_Future_Rep, - // detach it (maybe delete the ACE_Future_Rep). - FUTURE_REP::assign (this->future_rep_, - FUTURE_REP::create ()); - return 0; -} - -template int -ACE_Future::set (const T &r) -{ - // Give the pointer to the result to the ACE_Future_Rep. - return this->future_rep_->set (r, *this); -} - -template int -ACE_Future::ready (void) const -{ - // We're ready if the ACE_Future_rep is ready... - return this->future_rep_->ready (); -} - -template int -ACE_Future::get (T &value, - ACE_Time_Value *tv) const -{ - // We return the ACE_Future_rep. - return this->future_rep_->get (value, tv); -} - -template int -ACE_Future::attach (ACE_Future_Observer *observer) -{ - return this->future_rep_->attach (observer, *this); -} - -template int -ACE_Future::detach (ACE_Future_Observer *observer) -{ - return this->future_rep_->detach (observer); -} - -template -ACE_Future::operator T () -{ - // note that this will fail (and COREDUMP!) - // if future_rep_ == 0 ! - // - // but... - // this is impossible unless somebody is so stupid to - // try something like this: - // - // Future futT; - // T t; - // t = futT; - - // perform type conversion on Future_Rep. - return *future_rep_; -} - -template void -ACE_Future::operator = (const ACE_Future &rhs) -{ - // assignment: - // - // bind to the same as . - - // This will work if &r == this, by first increasing the ref count - ACE_Future &r = (ACE_Future &) rhs; - FUTURE_REP::assign (this->future_rep_, - FUTURE_REP::attach (r.future_rep_)); -} - -template void -ACE_Future::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_DEBUG ((LM_DEBUG, - ACE_BEGIN_DUMP, this)); - - if (this->future_rep_) - this->future_rep_->dump (); - - ACE_DEBUG ((LM_DEBUG, - ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -template ACE_Future_Rep * -ACE_Future::get_rep () -{ - return this->future_rep_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_THREADS */ - -#endif /* ACE_FUTURE_CPP */ diff --git a/externals/ace/Future.h b/externals/ace/Future.h deleted file mode 100644 index e30159eaf96..00000000000 --- a/externals/ace/Future.h +++ /dev/null @@ -1,387 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Future.h - * - * $Id: Future.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Andres Kruse - * @author Douglas C. Schmidt - * @author Per Andersson and - * @author John Tucker - */ -//============================================================================= - -#ifndef ACE_FUTURE_H -#define ACE_FUTURE_H - -#include /**/ "ace/pre.h" - -#include "ace/Unbounded_Set.h" -#include "ace/Strategies_T.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_THREADS) - -#include "ace/Recursive_Thread_Mutex.h" -#include "ace/Condition_Recursive_Thread_Mutex.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Forward decl. -template class ACE_Future_Holder; -template class ACE_Future_Observer; -template class ACE_Future_Rep; -template class ACE_Future; - -/** - * @class ACE_Future_Holder - * - * @brief Implementation of object that holds an ACE_Future. - */ -template -class ACE_Future_Holder -{ -public: - ACE_Future_Holder (const ACE_Future &future); - ~ACE_Future_Holder (void); - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - - ACE_Future item_; - -protected: - ACE_Future_Holder (void); -}; - -/** - * @class ACE_Future_Observer - * - * @brief ACE_Future_Observer - * - * An ACE_Future_Observer object implements an object that is - * subscribed with an ACE_Future object so that it may be notified - * when the value of the ACE_Future object is written to by a writer - * thread. It uses the Observer pattern. - */ -template -class ACE_Future_Observer -{ -public: - /// Destructor - virtual ~ACE_Future_Observer (void); - - /// Called by the ACE_Future in which we are subscribed to when - /// its value is written to. - virtual void update (const ACE_Future &future) = 0; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; -protected: - - /// Constructor - ACE_Future_Observer (void); -}; - -/** - * @class ACE_Future_Rep - * - * @internal - * - * @brief ACE_Future_Rep - * - * An ACE_Future_Rep object encapsules a pointer to an object - * of class T which is the result of an asynchronous method - * invocation. It is pointed to by ACE_Future object[s] and - * only accessible through them. - */ -template -class ACE_Future_Rep -{ -private: - friend class ACE_Future; - - /** - * Set the result value. The specified represents the - * future that invoked this method, which is used to notify - * the list of future observers. Returns 0 for success, -1 on error. - * This function only has an effect the first time it is called for - * the object. Subsequent calls return 0 (success) but have no effect. - */ - int set (const T &r, - ACE_Future &caller); - - /// Wait up to @a tv time to get the @a value. Note that @a tv must be - /// specified in absolute time rather than relative time. - int get (T &value, - ACE_Time_Value *tv) const; - - /** - * Attaches the specified observer to a subject (i.e., the ACE_Future_Rep). - * The update method of the specified subject will be invoked with a copy of - * the written-to ACE_Future as input when the result gets set. - * - * Returns 0 if the observer is successfully attached, 1 if the - * observer is already attached, and -1 if failures occur. - */ - int attach (ACE_Future_Observer *observer, - ACE_Future &caller); - - /** - * Detaches the specified observer from a subject (i.e., the ACE_Future_Rep). - * The update method of the specified subject will not be invoked when the - * ACE_Future_Reps result gets set. Returns 1 if the specified observer was - * actually attached to the subject prior to this call and 0 if was not. - * - * Returns 0 if the observer was successfully detached, and -1 if the - * observer was not attached in the first place. - */ - int detach (ACE_Future_Observer *observer); - - /** - * Type conversion. will block forever until the result is - * available. Note that this method is going away in a subsequent - * release since it doesn't distinguish between failure results and - * success results (exceptions should be used, but they aren't - * portable...). The method should be used instead since it - * separates the error value from the result, and also permits - * timeouts. - */ - operator T (); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - - // = Encapsulate reference count and object lifetime of instances. - - // These methods must go after the others to work around a bug with - // Borland's C++ Builder... - - /// Allocate a new ACE_Future_Rep instance, returning NULL if it - /// cannot be created. - static ACE_Future_Rep *internal_create (void); - - /// Create a ACE_Future_Rep and initialize the reference count. - static ACE_Future_Rep *create (void); - - /** - * Increase the reference count and return argument. Uses the - * attribute "value_ready_mutex_" to synchronize reference count - * updating. - * - * Precondition (rep != 0). - */ - static ACE_Future_Rep *attach (ACE_Future_Rep *&rep); - - /** - * Decreases the reference count and deletes rep if there are no - * more references to rep. - * - * Precondition (rep != 0) - */ - static void detach (ACE_Future_Rep *&rep); - - /** - * Decreases the rep's reference count and deletes rep if there - * are no more references to rep. Then assigns new_rep to rep. - * - * Precondition (rep != 0 && new_rep != 0) - */ - static void assign (ACE_Future_Rep *&rep, ACE_Future_Rep *new_rep); - - /// Is result available? - int ready (void) const; - - /// Pointer to the result. - T *value_; - - /// Reference count. - int ref_count_; - - typedef ACE_Future_Observer OBSERVER; - - typedef ACE_Unbounded_Set OBSERVER_COLLECTION; - - /// Keep a list of ACE_Future_Observers unread by client's reader thread. - OBSERVER_COLLECTION observer_collection_; - - // = Condition variable and mutex that protect the . - mutable ACE_Recursive_Thread_Mutex value_ready_mutex_; - mutable ACE_Condition_Recursive_Thread_Mutex value_ready_; - -private: - - ACE_Future_Rep (void); - -protected: - - ~ACE_Future_Rep (void); - -}; - -/** - * @class ACE_Future - * - * @brief This class implements a ``single write, multiple read'' - * pattern that can be used to return results from asynchronous - * method invocations. - */ -template -class ACE_Future -{ -public: - // = Initialization and termination methods. - /// Constructor. - ACE_Future (void); - - /// Copy constructor binds @a this and @a r to the same - /// ACE_Future_Rep. An ACE_Future_Rep is created if necessary. - ACE_Future (const ACE_Future &r); - - /// Constructor that initialises an ACE_Future to point to the - /// result @a r immediately. - ACE_Future (const T &r); - - /// Destructor. - ~ACE_Future (void); - - /// Assignment operator that binds @a this and @a r to the same - /// ACE_Future_Rep. An ACE_Future_Rep is created if necessary. - void operator = (const ACE_Future &r); - - /// Cancel an ACE_Future and assign the value @a r. It is used if a - /// client does not want to wait for the value to be produced. - int cancel (const T &r); - - /** - * Cancel an ACE_Future. Put the future into its initial - * state. Returns 0 on succes and -1 on failure. It is now possible - * to reuse the ACE_Future. But remember, the ACE_Future - * is now bound to a new ACE_Future_Rep. - */ - int cancel (void); - - /** - * Equality operator that returns @c true if both ACE_Future objects - * point to the same ACE_Future_Rep object. - * - * @note It also returns @c true if both objects have just been - * instantiated and not used yet. - */ - bool operator == (const ACE_Future &r) const; - - /// Inequality operator, which is the opposite of equality. - bool operator != (const ACE_Future &r) const; - - /** - * Make the result available. Is used by the server thread to give - * the result to all waiting clients. Returns 0 for success, -1 on failure. - * This function only has an effect the first time it is called for - * the object (actually, the first time the underlying ACE_Future_Rep has a - * value assigned to it). Subsequent calls return 0 (success) but have no - * effect. - */ - int set (const T &r); - - /** - * Wait to get the object's value. - * - * @param value Receives the value of this ACE_Future when it is set. - * @param tv Pointer to an ACE_Time_Value containing the absolute - * time to wait until for the value to be set. If @a tv - * is 0, the call waits indefinitely for the value to be - * set, unless an error occurs. - * - * @retval 0 Success; @a value contains the value of the ACE_Future. - * @retval -1 Error; check ACE_OS::last_error() for an error code. - */ - int get (T &value, - ACE_Time_Value *tv = 0) const; - - /** - * @deprecated Note that this method is going away in a subsequent - * release since it doesn't distinguish between failure - * results and success results (exceptions should be - * used, but they aren't portable...). - * Type conversion, which obtains the result of the asynchronous - * method invocation. Will block forever. The get() method should be - * used instead since it separates the error value from the result, - * and also permits timeouts. - */ - operator T (); - - /// Check if the result is available. - int ready (void) const; - - /** - * Attaches the specified observer to a subject (this ACE_Future). - * The update method of the specified subject will be invoked with a copy of - * the associated ACE_Future as input when the result gets set. If the - * result is already set when this method gets invoked, then the update - * method of the specified subject will be invoked immediately. - * - * @param observer The observer to attach to the subject. - * - * @retval 0 Success. - * @retval 1 The observer was already attached. - * @retval -1 Error; check ACE_OS::last_error() for an error code. - */ - int attach (ACE_Future_Observer *observer); - - /** - * Detaches the specified observer from a subject (this ACE_Future). - * The update method of the specified subject will not be invoked when the - * ACE_Future_Rep result gets set. - * - * @param observer The observer to attach to the subject. - * - * @retval 0 The observer was successfully detached. - * @retval -1 Error, including the observer not attached prior - * to calling this method. - */ - int detach (ACE_Future_Observer *observer); - - /// Dump the state of an object. - void dump (void) const; - - /** - * Get the underlying ACE_Future_Rep pointer. Note that this method should - * rarely, if ever, be used and that modifying the underlying - * ACE_Future_Rep should be done with extreme caution. - */ - ACE_Future_Rep *get_rep (void); - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - - // the ACE_Future_Rep - /// Protect operations on the . - typedef ACE_Future_Rep FUTURE_REP; - FUTURE_REP *future_rep_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Future.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Future.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#endif /* ACE_HAS_THREADS */ - -#include /**/ "ace/post.h" - -#endif /* ACE_FUTURE_H */ diff --git a/externals/ace/Future_Set.cpp b/externals/ace/Future_Set.cpp deleted file mode 100644 index a40b0700dc5..00000000000 --- a/externals/ace/Future_Set.cpp +++ /dev/null @@ -1,136 +0,0 @@ -// $Id: Future_Set.cpp 88128 2009-12-14 02:17:22Z schmidt $ - -#ifndef ACE_FUTURE_SET_CPP -#define ACE_FUTURE_SET_CPP - -#include "ace/Future_Set.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -#pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_THREADS) - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template -ACE_Future_Set::ACE_Future_Set (ACE_Message_Queue *new_queue) - : delete_queue_ (false) -{ - if (new_queue) - this->future_notification_queue_ = new_queue; - else - { - ACE_NEW (this->future_notification_queue_, - ACE_Message_Queue); - this->delete_queue_ = true; - } -} - -template -ACE_Future_Set::~ACE_Future_Set (void) -{ - // Detach ourselves from all remaining futures, if any, in our map. - typename FUTURE_HASH_MAP::iterator iterator = - this->future_map_.begin (); - - typename FUTURE_HASH_MAP::iterator end = - this->future_map_.end (); - - for (; - iterator != end; - ++iterator) - { - FUTURE_HOLDER *future_holder = (*iterator).int_id_; - future_holder->item_.detach (this); - delete future_holder; - } - - if (this->delete_queue_) - delete this->future_notification_queue_; -} - -template int -ACE_Future_Set::is_empty () const -{ - return (((ACE_Future_Set*)this)->future_map_.current_size () == 0 ); -} - -template int -ACE_Future_Set::insert (ACE_Future &future) -{ - FUTURE_HOLDER *future_holder; - ACE_NEW_RETURN (future_holder, - FUTURE_HOLDER (future), - -1); - - FUTURE_REP *future_rep = future.get_rep (); - int result = this->future_map_.bind (future_rep, - future_holder); - - // If a new map entry was created, then attach to the future, - // otherwise we were already attached to the future or some error - // occurred so just delete the future holder. - if (result == 0) - // Attach ourself to the ACE_Futures list of observer - future.attach (this); - else - delete future_holder; - - return result; -} - -template void -ACE_Future_Set::update (const ACE_Future &future) -{ - ACE_Message_Block *mb; - FUTURE &local_future = const_cast &> (future); - - ACE_NEW (mb, - ACE_Message_Block ((char *) local_future.get_rep (), 0)); - - // Enqueue in priority order. - this->future_notification_queue_->enqueue (mb, 0); -} - -template int -ACE_Future_Set::next_readable (ACE_Future &future, - ACE_Time_Value *tv) -{ - if (this->is_empty ()) - return 0; - - ACE_Message_Block *mb = 0; - FUTURE_REP *future_rep = 0; - - // Wait for a "readable future" signal from the message queue. - if (this->future_notification_queue_->dequeue_head (mb, - tv) != -1) - { - // Extract future rep from the message block. - future_rep = reinterpret_cast (mb->base ()); - - // Delete the message block. - mb->release (); - } - else - return 0; - - // Remove the hash map entry with the specified future rep from our map. - FUTURE_HOLDER *future_holder; - if (this->future_map_.find (future_rep, - future_holder) != -1) - { - future = future_holder->item_; - this->future_map_.unbind (future_rep); - delete future_holder; - return 1; - } - - return 0; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_THREADS */ -#endif /* ACE_FUTURE_SET_CPP */ diff --git a/externals/ace/Future_Set.h b/externals/ace/Future_Set.h deleted file mode 100644 index 3d07f4f73e2..00000000000 --- a/externals/ace/Future_Set.h +++ /dev/null @@ -1,146 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Future_Set.h - * - * $Id: Future_Set.h 88128 2009-12-14 02:17:22Z schmidt $ - * - * @author John Tucker - */ -//============================================================================= - -#ifndef ACE_FUTURE_SET_H -#define ACE_FUTURE_SET_H -#include /**/ "ace/pre.h" - -#include "ace/Thread.h" -#include "ace/Message_Queue.h" -#include "ace/Future.h" -#include "ace/Hash_Map_Manager_T.h" -#include "ace/Null_Mutex.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -#pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_THREADS) - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Future_Set - * - * @brief This class implements a mechanism that allows the values of - * a collection of ACE_Future objects to be accessed by reader threads - * as they become available. The caller(s) provide the ACE_Future_Set - * (i.e. the observer...) with the collection of ACE_Future objects - * (i.e. the subjects...) that are to be observed using the the - * ACE_Future_Set::insert() method. The caller(s) may then iterate - * over the collection in the order in which they become readable - * using the ACE_Future_Set::next_readable() method. - */ -template -class ACE_Future_Set : public ACE_Future_Observer -{ -public: - // = Initialization and termination methods. - - /// Constructor. - ACE_Future_Set (ACE_Message_Queue *future_notification_queue_ = 0); - - /// Destructor. - ~ACE_Future_Set (void); - - /** - * Return 1 if their are no ACE_Future objects left on its queue and - * 0 otherwise. - * - * When an ACE_Future_Set has no ACE_Future>subjects to observe it is - * empty. The ACE_Future_Set is in the empty state when either the caller(s) - * have retrieved every readable ACE_Future subject assigned the - * ACE_Future_Set via the ACE_Future_Set::next_readable() method, - * or when the ACE_Future_Set has not been assigned any subjects. - */ - int is_empty (void) const; - - /** - * Enqueus the given ACE_Future into this objects queue when it is - * readable. - * - * Returns 0 if the future is successfully inserted, 1 if the - * future is already inserted, and -1 if failures occur. - */ - int insert (ACE_Future &future); - - /** - * Wait up to @a tv time to get the @a value. Note that @a tv must be - * specified in absolute time rather than relative time.); get the - * next ACE_Future that is readable. If @a tv = 0, the will block - * forever. - * - * If a readable future becomes available, then the input - * ACE_Future object param will be assigned with it and 1 will - * be returned. If the ACE_Future_Set is empty (i.e. see definition - * of ACE_Future_Set::is_empty()), then 0 is returned. - * - * When a readable ACE_Future object is retrieved via the - * ACE_Future_Set::next_readable() method, the ACE_Future_Set will - * remove that ACE_Future object from its list of subjects. - */ - int next_readable (ACE_Future &result, - ACE_Time_Value *tv = 0); - - /// Called by the ACE_Future subject in which we are subscribed to - /// when its value is written to. - virtual void update (const ACE_Future &future); - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - // = Disallow these operations. - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Future_Set &)) - ACE_UNIMPLEMENTED_FUNC (ACE_Future_Set (const ACE_Future_Set &)) - - typedef ACE_Future FUTURE; - - typedef ACE_Future_Rep FUTURE_REP; - - typedef ACE_Future_Holder FUTURE_HOLDER; - - typedef ACE_Pointer_Hash FUTURE_REP_HASH; - - typedef ACE_Equal_To FUTURE_REP_COMPARE; - - typedef ACE_Hash_Map_Manager_Ex FUTURE_HASH_MAP; - - /// Map of , subjects, which have not been written to by - /// client's writer thread. - FUTURE_HASH_MAP future_map_; - - /// Message queue for notifying the reader thread of which - /// have been written to by client's writer thread. - ACE_Message_Queue *future_notification_queue_; - - /// Keeps track of whether we need to delete the message queue. - bool delete_queue_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Future_Set.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Future_Set.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#endif /* ACE_HAS_THREADS */ -#include /**/ "ace/post.h" -#endif /* ACE_FUTURE_SET_H */ diff --git a/externals/ace/Get_Opt.cpp b/externals/ace/Get_Opt.cpp deleted file mode 100644 index 915ff8a87a9..00000000000 --- a/externals/ace/Get_Opt.cpp +++ /dev/null @@ -1,734 +0,0 @@ -// $Id: Get_Opt.cpp 81840 2008-06-05 13:46:45Z sma $ - -#include "ace/Get_Opt.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Get_Opt.inl" -#endif /* __ACE_INLINE__ */ - -#include "ace/ACE.h" -#include "ace/Log_Msg.h" -#include "ace/SString.h" -#include "ace/OS_Memory.h" -#include "ace/OS_NS_string.h" -#include "ace/OS_NS_ctype.h" -#include "ace/OS_NS_stdlib.h" - -ACE_RCSID (ace, - Get_Opt, - "$Id: Get_Opt.cpp 81840 2008-06-05 13:46:45Z sma $") - -/* - * Copyright (c) 1987, 1993, 1994 - * The Regents of the University of California. 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. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University 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 REGENTS 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 REGENTS 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. - */ - -/*- - * Copyright (c) 2000 The NetBSD Foundation, Inc. - * All rights reserved. - * - * This code is derived from software contributed to The NetBSD Foundation - * by Dieter Baron and Thomas Klausner. - * - * 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. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the NetBSD - * Foundation, Inc. and its contributors. - * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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. - */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Get_Opt) - -#ifdef ACE_USES_WCHAR -void ACE_Get_Opt::ACE_Get_Opt_Init (const ACE_TCHAR *optstring) -#else -ACE_Get_Opt::ACE_Get_Opt (int argc, - ACE_TCHAR **argv, - const ACE_TCHAR *optstring, - int skip, - int report_errors, - int ordering, - int long_only) - : argc_ (argc), - argv_ (argv), - optind (skip), - opterr (report_errors), - optarg (0), - optstring_ (0), - long_only_ (long_only), - has_colon_ (0), - last_option_ (0), - nextchar_ (0), - optopt_ (0), - ordering_ (ordering), - nonopt_start_ (optind), - nonopt_end_ (optind), - long_option_ (0) -#endif -{ - ACE_TRACE ("ACE_Get_Opt::ACE_Get_Opt"); - - ACE_NEW (this->optstring_, ACE_TString (optstring)); - ACE_NEW (this->last_option_, ACE_TString (ACE_TEXT (""))); - - // First check to see if POSIXLY_CORRECT was set. - // Win32 is the only platform capable of wide-char env var. -#if defined (ACE_WIN32) - const ACE_TCHAR *env_check = ACE_TEXT ("POSIXLY_CORRECT"); -#else - const char *env_check = "POSIXLY_CORRECT"; -#endif - if (ACE_OS::getenv (env_check) != 0) - this->ordering_ = REQUIRE_ORDER; - - // Now, check to see if any or the following were passed at - // the begining of optstring: '+' same as POSIXLY_CORRECT; - // '-' turns off POSIXLY_CORRECT; or ':' which signifies we - // should return ':' if a parameter is missing for an option. - // We use a loop here, since a combination of "{+|-}:" in any - // order should be legal. - int done = 0; - int offset = 0; - while (!done) - { - switch (optstring[offset++]) - { - case '+': - this->ordering_ = REQUIRE_ORDER; - break; - case '-': - this->ordering_ = RETURN_IN_ORDER; - break; - case ':': - this->has_colon_ = 1; - break; - default: - // Quit as soon as we see something else... - done = 1; - break; - } - } -} - -ACE_Get_Opt::~ACE_Get_Opt (void) -{ - ACE_TRACE ("ACE_Get_Opt::~ACE_Get_Opt"); - - size_t i = 0; - size_t size = this->long_opts_.size (); - ACE_Get_Opt_Long_Option *option = 0; - for (i = 0; i < size; ++i) - { - int retval = this->long_opts_.get (option, i); - if (retval != 0) - { - // Should never happen. - retval = 0; - continue; - } - if (option) - { - delete option; - option = 0; - } - } - delete this->optstring_; - delete this->last_option_; -} - -int -ACE_Get_Opt::nextchar_i (void) -{ - ACE_TRACE ("ACE_Get_Opt::nextchar_i"); - - if (this->ordering_ == PERMUTE_ARGS) - if (this->permute () == EOF) - return EOF; - - // Update scanning pointer. - if (this->optind >= this->argc_) - { - // We're done... - this->nextchar_ = 0; - return EOF; - } - else if (*(this->nextchar_ = this->argv_[this->optind]) != '-' - || this->nextchar_[1] == '\0') - { - // We didn't get an option. - - if (this->ordering_ == REQUIRE_ORDER - || this->ordering_ == PERMUTE_ARGS) - // If we permuted or require the options to be in order, we're done. - return EOF; - - // It must be RETURN_IN_ORDER... - this->optarg = this->argv_[this->optind++]; - this->nextchar_ = 0; - return 1; - } - else if (this->nextchar_[1] != 0 - && *++this->nextchar_ == '-' - && this->nextchar_[1] == 0) - { - // Found "--" so we're done... - ++this->optind; - this->nextchar_ = 0; - return EOF; - } - - // If it's a long option, and we allow long options advance nextchar_. - if (*this->nextchar_ == '-' && this->long_opts_.size () != 0) - this->nextchar_++; - - return 0; -} - -int -ACE_Get_Opt::long_option_i (void) -{ - ACE_TRACE ("ACE_Get_Opt::long_option_i"); - - ACE_Get_Opt_Long_Option *p; - ACE_TCHAR *s = this->nextchar_; - int hits = 0; - int exact = 0; - ACE_Get_Opt_Long_Option *pfound = 0; - int indfound = 0; - - // Advance to the end of the long option name so we can use - // it to get the length for a string compare. - while (*s && *s != '=') - s++; - - size_t len = s - this->nextchar_; - // set last_option_ to nextchar_, up to the '='. - this->last_option (ACE_TString (this->nextchar_, len)); - - size_t size = this->long_opts_.size (); - u_int option_index = 0; - for (option_index = 0; option_index < size ; option_index++) - { - p = this->long_opts_[option_index]; - ACE_ASSERT (p); - - if (!ACE_OS::strncmp (p->name_, this->nextchar_, len)) - { - // Got at least a partial match. - pfound = p; - indfound = option_index; - hits += 1; - if (len == ACE_OS::strlen(p->name_)) - { - // And in fact, it's an exact match, so let's use it. - exact = 1; - break; - } - } - } - - if ((hits > 1) && !exact) - { - // Great, we found a match, but unfortunately we found more than - // one and it wasn't exact. - if (this->opterr) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%s: option `%s' is ambiguous\n"), - this->argv_[0], this->argv_[this->optind])); - this->nextchar_ = 0; - this->optind++; - return '?'; - } - - if (pfound != 0) - { - // Okay, we found a good one (either a single hit or an exact match). - option_index = indfound; - this->optind++; - if (*s) - { - // s must point to '=' which means there's an argument (well - // close enough). - if (pfound->has_arg_ != NO_ARG) - // Good, we want an argument and here it is. - this->optarg = ++s; - else - { - // Whoops, we've got what looks like an argument, but we - // don't want one. - if (this->opterr) - ACE_ERROR - ((LM_ERROR, - ACE_TEXT ("%s: long option `--%s' doesn't allow ") - ACE_TEXT ("an argument\n"), - this->argv_[0], pfound->name_)); - // The spec doesn't cover this, so we keep going and the program - // doesn't know we ignored an argument if opt_err is off!!! - } - } - else if (pfound->has_arg_ == ARG_REQUIRED) - { - // s didn't help us, but we need an argument. Note that - // optional arguments for long options must use the "=" syntax, - // so we won't get here in that case. - if (this->optind < this->argc_) - // We still have some elements left, so use the next one. - this->optarg = this->argv_[this->optind++]; - else - { - // All out of elements, so we have to punt... - if (this->opterr) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%s: long option '--%s' requires ") - ACE_TEXT ("an argument\n"), - this->argv_[0], pfound->name_)); - this->nextchar_ = 0; - this->optopt_ = pfound->val_; // Remember matching short equiv - return this->has_colon_ ? ':' : '?'; - } - } - this->nextchar_ = 0; - this->long_option_ = pfound; - // Since val_ has to be either a valid short option or 0, this works - // great. If the user really wants to know if a long option was passed. - this->optopt_ = pfound->val_; - return pfound->val_; - } - if (!this->long_only_ || this->argv_[this->optind][1] == '-' - || this->optstring_->find (*this->nextchar_) == ACE_TString::npos) - { - // Okay, we couldn't find a long option. If it isn't long_only (which - // means try the long first, and if not found try the short) or a long - // signature was passed, e.g. "--", or it's not a short (not sure when - // this could happen) it's an error. - if (this->opterr) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%s: illegal long option '--%s'\n"), - this->argv_[0], this->nextchar_)); - this->nextchar_ = 0; - this->optind++; - return '?'; - } - return this->short_option_i (); -} - -int -ACE_Get_Opt::short_option_i (void) -{ - ACE_TRACE ("ACE_Get_Opt::short_option_i"); - - /* Look at and handle the next option-character. */ - ACE_TCHAR opt = *this->nextchar_++; - // Set last_option_ to opt - this->last_option (opt); - - ACE_TCHAR *oli = 0; - oli = - const_cast (ACE_OS::strchr (this->optstring_->c_str (), opt)); - - /* Increment `optind' when we start to process its last character. */ - if (*this->nextchar_ == '\0') - ++this->optind; - - if (oli == 0 || opt == ':') - { - if (this->opterr) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%s: illegal short option -- %c\n"), - this->argv_[0], opt)); - return '?'; - } - if (opt == 'W' && oli[1] == ';') - { - if (this->nextchar_[0] == 0) - this->nextchar_ = this->argv_[this->optind]; - return long_option_i (); - } - this->optopt_ = oli[0]; // Remember the option that matched - if (oli[1] == ':') - { - if (oli[2] == ':') - { - // Takes an optional argument, and since short option args must - // must follow directly in the same argument, a NULL nextchar_ - // means we didn't get one. - if (*this->nextchar_ != '\0') - { - this->optarg = this->nextchar_; - this->optind++; - } - else - this->optarg = 0; - this->nextchar_ = 0; - } - else - { - // Takes a required argument. - if (*this->nextchar_ != '\0') - { - // Found argument in same argv-element. - this->optarg = this->nextchar_; - this->optind++; - } - else if (this->optind == this->argc_) - { - // Ran out of arguments before finding required argument. - if (this->opterr) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%s: short option requires ") - ACE_TEXT ("an argument -- %c\n"), - this->argv_[0], opt)); - opt = this->has_colon_ ? ':' : '?'; - } - else - // Use the next argv-element as the argument. - this->optarg = this->argv_[this->optind++]; - this->nextchar_ = 0; - } - } - return opt; -} - -int -ACE_Get_Opt::operator () (void) -{ - ACE_TRACE ("ACE_Get_Opt_Long::operator"); - - // First of all, make sure we reinitialize any pointers.. - this->optarg = 0; - this->long_option_ = 0; - - if (this->argv_ == 0) - { - // It can happen, e.g., on VxWorks. - this->optind = 0; - return -1; - } - - // We check this because we can string short options together if the - // preceding one doesn't take an argument. - if (this->nextchar_ == 0 || *this->nextchar_ == '\0') - { - int retval = this->nextchar_i (); - if (retval != 0) - return retval; - } - - if (((this->argv_[this->optind][0] == '-') - && (this->argv_[this->optind][1] == '-')) || this->long_only_) - return this->long_option_i (); - - return this->short_option_i (); -} - -int -ACE_Get_Opt::long_option (const ACE_TCHAR *name, - OPTION_ARG_MODE has_arg) -{ - ACE_TRACE ("ACE_Get_Opt::long_option (const ACE_TCHAR *name, OPTION_ARG_MODE has_arg)"); - return this->long_option (name, 0, has_arg); -} - -int -ACE_Get_Opt::long_option (const ACE_TCHAR *name, - int short_option, - OPTION_ARG_MODE has_arg) -{ - ACE_TRACE ("ACE_Get_Opt::long_option (const ACE_TCHAR *name, int short_option, OPTION_ARG_MODE has_arg)"); - - // We only allow valid alpha-numeric characters as short options. - // If short_options is not a valid alpha-numeric, we can still return it - // when the long option is found, but won't allow the caller to pass it on - // the command line (how could they?). The special case is 0, but since - // we always return it, we let the caller worry about that. - if (ACE_OS::ace_isalnum (short_option) != 0) - { - // If the short_option already exists, make sure it matches, otherwise - // add it. - ACE_TCHAR *s = 0; - if ((s = const_cast ( - ACE_OS::strchr (this->optstring_->c_str (), - short_option))) != 0) - { - // Short option exists, so verify the argument options - if (s[1] == ':') - { - if (s[2] == ':') - { - if (has_arg != ARG_OPTIONAL) - { - if (this->opterr) - ACE_ERROR - ((LM_ERROR, - ACE_TEXT ("Existing short option '%c' takes ") - ACE_TEXT ("optional argument; adding %s ") - ACE_TEXT ("requires ARG_OPTIONAL\n"), - short_option, name)); - return -1; - } - } - else - if (has_arg != ARG_REQUIRED) - { - if (this->opterr) - ACE_ERROR - ((LM_ERROR, - ACE_TEXT ("Existing short option '%c' requires ") - ACE_TEXT ("an argument; adding %s ") - ACE_TEXT ("requires ARG_REQUIRED\n"), - short_option, name)); - return -1; - } - } - else if (has_arg != NO_ARG) - { - if (this->opterr) - ACE_ERROR - ((LM_ERROR, - ACE_TEXT ("Existing short option '%c' does not ") - ACE_TEXT ("accept an argument; adding %s ") - ACE_TEXT ("requires NO_ARG\n"), - short_option, name)); - return -1; - } - } - else - { - // Didn't find short option, so add it... - *this->optstring_ += (ACE_TCHAR) short_option; - if (has_arg == ARG_REQUIRED) - *this->optstring_ += ACE_TEXT (":"); - else if (has_arg == ARG_OPTIONAL) - *this->optstring_ += ACE_TEXT ("::"); - } - } - - ACE_Get_Opt_Long_Option *option = - new ACE_Get_Opt_Long_Option (name, has_arg, short_option); - - if (!option) - return -1; - - // Add to array - size_t size = this->long_opts_.size (); - if (this->long_opts_.size (size + 1) != 0 - || this->long_opts_.set (option, size) != 0) - { - delete option; - ACE_ERROR_RETURN - ((LM_ERROR, ACE_TEXT ("Could not add long option to array.\n")), - -1); - } - return 0; -} - -const ACE_TCHAR* -ACE_Get_Opt::long_option (void) const -{ - ACE_TRACE ("ACE_Get_Opt::long_option (void)"); - if (this->long_option_) - return this->long_option_->name_; - return 0; -} - -const ACE_TCHAR* -ACE_Get_Opt::last_option (void) const -{ - return this->last_option_->c_str (); -} - -void -ACE_Get_Opt::last_option (const ACE_TString &last_option) -{ - *this->last_option_ = last_option; -} - -void -ACE_Get_Opt::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Get_Opt::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n") - ACE_TEXT ("opstring_ = %s\n") - ACE_TEXT ("long_only_ = %d\n") - ACE_TEXT ("has_colon_ = %d\n") - ACE_TEXT ("last_option_ = %s\n") - ACE_TEXT ("nextchar_ = %s\n") - ACE_TEXT ("optopt_ = %c\n") - ACE_TEXT ("ordering_ = %d\n"), - this->optstring_->c_str (), - this->long_only_, - this->has_colon_, - this->last_option_->c_str (), - this->nextchar_, - this->optopt_, - this->ordering_)); - - // now loop through the - size_t size = this->long_opts_.size (); - for (u_int i = 0; i < size ; ++i) - { - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n") - ACE_TEXT ("long_option name_ = %s\n") - ACE_TEXT ("has_arg_ = %d\n") - ACE_TEXT ("val_ = %d\n"), - this->long_opts_[i]->name_, - this->long_opts_[i]->has_arg_, - this->long_opts_[i]->val_)); - } - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -void -ACE_Get_Opt::permute_args (void) -{ - ACE_TRACE ("ACE_Get_Opt::permute_args"); - - u_long cyclelen, i, j, ncycle, nnonopts, nopts; - u_long opt_end = this->optind; - int cstart, pos = 0; - ACE_TCHAR *swap = 0; - - nnonopts = this->nonopt_end_ - this->nonopt_start_; - nopts = opt_end - this->nonopt_end_; - ncycle = ACE::gcd (nnonopts, nopts); - cyclelen = (opt_end - this->nonopt_start_) / ncycle; - - this->optind = this->optind - nnonopts; - - for (i = 0; i < ncycle; i++) - { - cstart = this->nonopt_end_ + i; - pos = cstart; - for (j = 0; j < cyclelen; j++) - { - if (pos >= this->nonopt_end_) - pos -= nnonopts; - else - pos += nopts; - swap = this->argv_[pos]; - - ((ACE_TCHAR **)this->argv_)[pos] = argv_[cstart]; - - ((ACE_TCHAR **)this->argv_)[cstart] = swap; - } - } -} - -int -ACE_Get_Opt::permute (void) -{ - ACE_TRACE ("ACE_Get_Opt::permute"); - - if (this->nonopt_start_ != this->nonopt_end_ - && this->nonopt_start_ != this->optind) - this->permute_args (); - - this->nonopt_start_ = this->optind; - - // Skip over args untill we find the next option. - while (this->optind < this->argc_ - && (this->argv_[this->optind][0] != '-' - || this->argv_[this->optind][1] == '\0')) - this->optind++; - - // Got an option, so mark this as the end of the non options. - this->nonopt_end_ = this->optind; - - if (this->optind != this->argc_ - && ACE_OS::strcmp (this->argv_[this->optind], - ACE_TEXT ("--")) == 0) - { - // We found the marker for the end of the options. - ++this->optind; - - if (this->nonopt_start_ != this->nonopt_end_ - && this->nonopt_end_ != this->optind) - this->permute_args (); - } - - if (this->optind == this->argc_) - { - if (this->nonopt_start_ != this->nonopt_end_) - this->optind = this->nonopt_start_; - return EOF; - } - return 0; -} - -const ACE_TCHAR * -ACE_Get_Opt::optstring (void) const -{ - return this->optstring_->c_str (); -} - -ACE_Get_Opt::ACE_Get_Opt_Long_Option::ACE_Get_Opt_Long_Option ( - const ACE_TCHAR *name, - int has_arg, - int val) - : name_ (ACE::strnew (name)), - has_arg_ (has_arg), - val_ (val) -{} - -ACE_Get_Opt::ACE_Get_Opt_Long_Option::~ACE_Get_Opt_Long_Option (void) -{ - delete [] this->name_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Get_Opt.h b/externals/ace/Get_Opt.h deleted file mode 100644 index 1c30096ea6d..00000000000 --- a/externals/ace/Get_Opt.h +++ /dev/null @@ -1,494 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file Get_Opt.h - * - * $Id: Get_Opt.h 86367 2009-08-05 09:41:11Z johnnyw $ - * - * @author Douglas C. Schmidt - * @author Don Hinton (added long option support) - */ -//========================================================================== - -#ifndef ACE_GET_OPT_H -#define ACE_GET_OPT_H -#include /**/ "ace/pre.h" - -#include "ace/SStringfwd.h" -#include "ace/Containers.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#undef optind -#undef optarg -#undef opterr - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/* - * These definitions are for backward compatibility with previous versions. - * of ACE_Get_Opt. - */ - -/** - * @class ACE_Get_Opt - * - * @brief Iterator for parsing command-line arguments. - * - * This is a C++ wrapper for getopt(3c) and getopt_long(3c). - */ - -class ACE_Export ACE_Get_Opt -{ -public: - /// Mutually exclusive ordering values. - enum - { - /** - * REQUIRE_ORDER means that processing stops and @c EOF is - * returned as soon as a non-option argument is found. @c opt_ind() - * will return the index of the next @a argv element so the program - * can continue processing the rest of the @a argv elements. - */ - REQUIRE_ORDER = 1, - - /** - * PERMUTE_ARGS means the @a argv elements are reordered dynamically - * (permuted) so that all options appear first. When the elements are - * permuted, the order of the options and the following arguments are - * maintained. When the last option has been processed, @c EOF is - * returned and @c opt_ind() returns the index into the next non-option - * element. - */ - PERMUTE_ARGS = 2, - - /** - * RETURN_IN_ORDER means each @a argv element is processed in the - * order is it seen. If the element is not recognized as an option, '1' - * is returned and @c opt_arg() refers to the @a argv element found. - */ - RETURN_IN_ORDER = 3 - }; - - /// Mutually exclusive option argument mode used by long options. - enum OPTION_ARG_MODE - { - /// Doesn't take an argument. - NO_ARG = 0, - - /// Requires an argument, same as passing ":" after a short option - /// character in @a optstring. - ARG_REQUIRED = 1, - - /// Argument is optional, same as passing "::" after a short - /// option character in @a optstring. - ARG_OPTIONAL = 2 - }; - - /** - * Constructor initializes the command line to be parsed. All information - * for parsing must be supplied to this constructor. - * - * @param argc The number of @a argv elements to parse. - * @param argv Command line tokens, such as would be passed - * to @c main(). - * @param optstring Nul-terminated string containing the legitimate - * short option characters. A single colon ":" - * following an option character means the option - * requires an argument. A double colon "::" following - * an option character means the argument is optional. - * The argument is taken from the rest of the current - * @a argv element, or from the following @a argv - * element (only valid for required arguments; - * optional arguments must always reside in the same - * @a argv element). The argument value, if any is - * returned by the @c opt_arg() method. - * @a optstring can be extended by adding long options - * with corresponding short options via the - * @c long_option() method. If the short option - * already appears in @a optstring, the argument - * characteristics must match, otherwise it is added. - * See @c long_option() for more information. - * If 'W', followed by a semi-colon ';' appears in - * @a optstring, then any time a 'W' appears on the - * command line, the following argument is treated as - * a long option. For example, if the command line - * contains "program -W foo", "foo" is treated as a - * long option, that is, as if "program --foo" had - * been passed. - * The following characters can appear in @a optstring - * before any option characters, with the described - * effect: - * - '+' changes the @a ordering to @a REQUIRE_ORDER. - * - '-' changes the @a ordering to @a RETURN_IN_ORDER. - * - ':' changes the return value from @c operator() - * and get_opt() from '?' to ':' when an option - * requires an argument but none is specified. - * - * @param skip_args Optional (default 1). The specified number of - * initial elements in @a argv are skipped before - * parsing begins. Thus, the default prevents - * @a argv[0] (usually the command name) from being - * parsed. @a argc includes all @a argv elements, - * including any skipped elements. - * @param report_errors Optional, if non-zero then parsing errors cause - * an error message to be displayed from the - * @c operator() method before it returns. The - * error message is suppressed if this argument is 0. - * This setting also controls whether or not an error - * message is displayed in @c long_option() encounters - * an error. - * @param ordering Optional (default is @c PERMUTE_ARGS); determines - * how the @a argv elements are processed. This argument - * is overridden by two factors: - * -# The @c POSIXLY_CORRECT environment variable. If - * this environment variable is set, the ordering - * is changed to @c REQUIRE_ORDER. - * -# Leading characters in @a optstring (see above). - * Any leading ordering characters override both - * the @a ordering argument and any effect of the - * @c POSIXLY_CORRECT environment variable. - * @param long_only Optional. If non-zero, then long options can be - * specified using a single '-' on the command line. - * If the token is not a long option, it is processed - * as usual, that is, as a short option or set of - * short options. - * - * Multiple short options can be combined as long as only the last - * one can takes an argument. For example, if @a optstring is defined as - * @c "abc:" or @c "abc::" then the command line @e "program -abcxxx" short - * options @e a, @e b, and @e c are found with @e "xxx" as the argument for - * @e c. - * However, if the command line is specified as @e "program -acb" only - * options @e a and @e c are found with @e "b" as the argument for @e c. - * Also, for options with optional arguments, that is, those followed by - * "::", the argument must be in the same @a argv element, so "program -abc - * xxx" will only find "xxx" as the argument for @e c if @a optstring is - * specified as @c "abc:" not @c "abc::". - */ -#ifndef ACE_USES_WCHAR - ACE_Get_Opt (int argc, - ACE_TCHAR **argv, - const ACE_TCHAR *optstring = ACE_TEXT (""), - int skip_args = 1, - int report_errors = 0, - int ordering = PERMUTE_ARGS, - int long_only = 0); - -#else -private: - void ACE_Get_Opt_Init (const ACE_TCHAR *optstring); -public: - ACE_Get_Opt (int argc, - ACE_TCHAR **argv, - const ACE_TCHAR *optstring = ACE_TEXT (""), - int skip_args = 1, - int report_errors = 0, - int ordering = PERMUTE_ARGS, - int long_only = 0); - ACE_Get_Opt (int argc, - ACE_TCHAR **argv, - const char *optstring, - int skip_args = 1, - int report_errors = 0, - int ordering = PERMUTE_ARGS, - int long_only = 0); -#endif - /// Default dtor. - ~ACE_Get_Opt (void); - - /** - * Scan elements of @a argv (whose length is @a argc) for short option - * characters given in @a optstring or long options (with no short - * option equivalents). - * - * If an element of @a argv starts with '-', and is not exactly "-" - * or "--", then it is a short option element. The characters of this - * element (aside from the initial '-') are option characters. If - * it starts with "--" followed by other characters it is treated as - * a long option. If @c operator() is called repeatedly, it returns - * each of the option characters from each of the option elements. - * - * @return The parsed option character. The following characters have - * special significance. - * @retval 0 A long option was found - * @retval '\?' Either an unknown option character was found, or the - * option is known but requires an argument, none was - * specified, and @a optstring did not contain a leading - * colon. - * @retval ':' A known option character was found but it requires an - * argument and none was supplied, and the first character - * of @a optstring was a colon. @c opt_opt() indicates - * which option was specified. - * @retval '1' @c RETURN_IN_ORDER was specified and a non-option argument - * was found. - * @retval EOF No more option characters were found. @c opt_ind() will - * return the index in @a argv of the first @a argv element - * that is not an option. If @c PERMUTE_ARGS was - * specified, the @a argv elements have been permuted so that - * those that are not options now come last. - * - * @note The standards are unclear with respect to the conditions under - * which '?' and ':' are returned, so we scan the initial characters of - * @a optstring up unto the first short option character for '+', '-', - * and ':' in order to determine ordering and missing argument behavior. - */ - int operator () (void); - - /** - * For communication from @c operator() to the caller. When - * @c operator() finds an option that takes an argument, the argument - * value is returned from this method, otherwise it returns 0. - */ - ACE_TCHAR *opt_arg (void) const; - - /** - * Returns the most recently matched option character. Especially - * useful when operator() returns ':' for an unspecified argument - * that's required, since this allows the caller to learn what option - * was specified without its required argument. - */ - int opt_opt (void); - - /** - * Index in @a argv of the next element to be scanned. This is used - * for communication to and from the caller and for communication - * between successive calls to @c operator(). On entry to - * @c operator(), zero means this is the first call; initialize. - * - * When @c operator() returns @c EOF, this is the index of the first of - * the non-option elements that the caller should itself scan. - * - * Otherwise, @c opt_ind() communicates from one call to the next how - * much of @a argv has been scanned so far. - */ - int &opt_ind (void); - - /// Adds a long option with no corresponding short option. - /** - * If the @a name option is seen, @c operator() returns 0. - * - * @param name The long option to add. - * @param has_arg Defines the argument requirements for - * the new option. - * - * @retval 0 Success - * @retval -1 The long option can not be added. - */ - int long_option (const ACE_TCHAR *name, - OPTION_ARG_MODE has_arg = NO_ARG); - - /// Adds a long option with a corresponding short option. - /** - * @param name The long option to add. - * @param short_option A character, the short option that corresponds - * to @a name. - * @param has_arg Defines the argument requirements for - * the new option. If the short option has already - * been supplied in the @a optstring, @a has_arg - * must match or an error is returned; otherwise, the - * new short option is added to the @a optstring. - * - * @retval 0 Success - * @retval -1 The long option can not be added. - */ - int long_option (const ACE_TCHAR *name, - int short_option, - OPTION_ARG_MODE has_arg = NO_ARG); - - /// Returns the name of the long option found on the last call to - /// @c operator() or 0 if none was found. - const ACE_TCHAR *long_option (void) const; - - /// The number of arguments in the internal @c argv_. - int argc (void) const; - - /// Accessor for the internal @c argv_ pointer. - ACE_TCHAR **argv (void) const; - - /// Accessor for the @c last_option that was processed. This allows - /// applications to know if the found option was a short or long - /// option, and is especially useful in cases where it was invalid - /// and the caller wants to print out the invalid value. - const ACE_TCHAR *last_option (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Return the @a optstring. This is handy to verify that calls to - /// long_option added short options as expected. - const ACE_TCHAR *optstring (void) const; - -public: - /* - * The following five data members should be private, but that - * would break backwards compatibility. However, we recommend not - * writing code that uses these fields directly. - */ - - /// Holds the @a argc count. - /** - * @deprecated This is public for backwards compatibility only. - * It will be made private in a release of ACE past 5.3. Do not - * write code that relies on this member being public; use the - * @c argc() accessor method instead. - */ - int argc_; - - /// Holds the @a argv pointer. - /** - * @deprecated This is public for backwards compatibility only. - * It will be made private in a release of ACE past 5.3. Do not - * write code that relies on this member being public; use the - * @c argv() accessor method instead. - */ - ACE_TCHAR **argv_; - - /// Index in @c argv_ of the next element to be scanned. - /** - * @deprecated This is public for backwards compatibility only. - * It will be made private in a release of ACE past 5.3. Do not - * write code that relies on this member being public; use the - * @c opt_ind() accessor method instead. - */ - int optind; - - /// Callers store zero here to inhibit the error message for - /// unrecognized options. - /** - * @deprecated This is public for backwards compatibility only. - * It will be made private in a release of ACE past 5.3. Do not - * write code that relies on this member being public; use the - * @a report_errors argument to this class's constructor instead. - */ - int opterr; - - /// Points to the option argument when one is found on last call to - /// @c operator(). - /** - * @deprecated This is public for backwards compatibility only. - * It will be made private in a release of ACE past 5.3. Do not - * write code that relies on this member being public; use the - * @c opt_arg() accessor method instead. - */ - ACE_TCHAR *optarg; - -private: - /** - * @class ACE_Get_Opt_Long_Option This class is for internal use - * in the ACE_Get_Opt class, and is inaccessible to users. - */ - class ACE_Get_Opt_Long_Option - { - public: - /// ctor - ACE_Get_Opt_Long_Option (const ACE_TCHAR *name, - int has_arg, - int val = 0); - - /// Dtor. - ~ACE_Get_Opt_Long_Option (void); - - bool operator < (const ACE_Get_Opt_Long_Option &rhs); - - /// Long option name. - const ACE_TCHAR *name_; - - /// Contains value for . - int has_arg_; - - /// Contains a valid short option character or zero if it doesn't - /// have a corresponding short option. It can also contain a - /// non-printable value that cannot be passed to but - /// will be returned by . This is handy for - /// simplifying long option handling, see tests/Get_Opt_Test.cpp - /// for an example of this technique. - int val_; - }; - - /// Updates nextchar_. - int nextchar_i (void); - - /// Handles long options. - int long_option_i (void); - - /// Handles short options. - int short_option_i (void); - - /// If permuting args, this functions manages the nonopt_start_ and - /// nonopt_end_ indexes and makes calls to permute to actually - /// reorder the -elements. - void permute_args (void); - - /// Handles reordering -elements. - int permute (void); - - /// Set last_option. - void last_option (const ACE_TString &s); - - // Disallow copying and assignment. - ACE_Get_Opt (const ACE_Get_Opt &); - ACE_Get_Opt &operator= (const ACE_Get_Opt &); - -private: - - /// Holds the option string. - ACE_TString *optstring_; - - /// Treat all options as long options. - int long_only_; - - /// Keeps track of whether or not a colon was passed in . - /// This is used to determine the return value when required - /// arguments are missing. - int has_colon_; - - /// This is the last option, short or long, that was processed. This - /// is handy to have in cases where the option passed was invalid. - ACE_TString *last_option_; - - /** - * The next char to be scanned in the option-element in which the - * last option character we returned was found. This allows us to - * pick up the scan where we left off * - * If this is zero, or a null string, it means resume the scan - * by advancing to the next -element. - */ - ACE_TCHAR *nextchar_; - - /// Most recently matched short option character. - int optopt_; - - /// Keeps track of ordering mode (default ). - int ordering_; - - /// Index of the first non-option -element found (only valid - /// when permuting). - int nonopt_start_; - - /// Index of the -element following the last non-option element - /// (only valid when permuting). - int nonopt_end_; - - /// Points to the long_option found on last call to . - ACE_Get_Opt_Long_Option *long_option_; - - /// Array of long options. - ACE_Array long_opts_; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Get_Opt.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_GET_OPT_H */ diff --git a/externals/ace/Get_Opt.inl b/externals/ace/Get_Opt.inl deleted file mode 100644 index e307fb5e400..00000000000 --- a/externals/ace/Get_Opt.inl +++ /dev/null @@ -1,97 +0,0 @@ -// -*- C++ -*- -// -// $Id: Get_Opt.inl 81840 2008-06-05 13:46:45Z sma $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE bool -ACE_Get_Opt::ACE_Get_Opt_Long_Option::operator < (const ACE_Get_Opt_Long_Option &rhs) -{ - return this->name_ < rhs.name_; -} - -ACE_INLINE int -ACE_Get_Opt::argc (void) const -{ - return this->argc_; -} - -ACE_INLINE ACE_TCHAR ** -ACE_Get_Opt::argv (void) const -{ - return this->argv_; -} - -ACE_INLINE ACE_TCHAR* -ACE_Get_Opt::opt_arg (void) const -{ - return this->optarg; -} - -ACE_INLINE int -ACE_Get_Opt::opt_opt (void) -{ - return this->optopt_; -} - -ACE_INLINE int & -ACE_Get_Opt::opt_ind (void) -{ - return this->optind; -} - -#ifdef ACE_USES_WCHAR -ACE_INLINE ACE_Get_Opt::ACE_Get_Opt (int argc, - ACE_TCHAR **argv, - const ACE_TCHAR *optstring, - int skip_args, - int report_errors, - int ordering, - int long_only) - : argc_ (argc), - argv_ (argv), - optind (skip_args), - opterr (report_errors), - optarg (0), - optstring_ (0), - long_only_ (long_only), - has_colon_ (0), - last_option_ (0), - nextchar_ (0), - optopt_ (0), - ordering_ (ordering), - nonopt_start_ (optind), - nonopt_end_ (optind), - long_option_ (0) -{ - ACE_Get_Opt_Init (optstring); -} - -ACE_INLINE ACE_Get_Opt::ACE_Get_Opt (int argc, - ACE_TCHAR **argv, - const char *optstring, - int skip_args, - int report_errors, - int ordering, - int long_only) - : argc_ (argc), - argv_ (argv), - optind (skip_args), - opterr (report_errors), - optarg (0), - optstring_ (), - long_only_ (long_only), - has_colon_ (0), - last_option_ (0), - nextchar_ (0), - optopt_ (0), - ordering_ (ordering), - nonopt_start_ (optind), - nonopt_end_ (optind), - long_option_ (0) -{ - ACE_Get_Opt_Init (ACE_TEXT_CHAR_TO_TCHAR (optstring)); -} -#endif - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Global_Macros.h b/externals/ace/Global_Macros.h deleted file mode 100644 index d1bf6420b05..00000000000 --- a/externals/ace/Global_Macros.h +++ /dev/null @@ -1,1121 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Global_Macros.h - * - * $Id: Global_Macros.h 82442 2008-07-28 13:11:29Z johnnyw $ - * - * @author Douglas C. Schmidt - * @author Jesper S. M|ller - * @author and a cast of thousands... - * - * This one is split from the famous OS.h - */ -//============================================================================= - -#ifndef ACE_GLOBAL_MACROS_H -#define ACE_GLOBAL_MACROS_H - -#include /**/ "ace/pre.h" - -// Included just keep compilers that see #pragma dierctive first -// happy. -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/config-lite.h" -#include "ace/Assert.h" // For ACE_ASSERT - -// Start Global Macros -# define ACE_BEGIN_DUMP ACE_TEXT ("\n====\n(%P|%t|%x)\n") -# define ACE_END_DUMP ACE_TEXT ("====\n") - -# if defined (ACE_NDEBUG) -# define ACE_DB(X) -# else -# define ACE_DB(X) X -# endif /* ACE_NDEBUG */ - -// ACE_NO_HEAP_CHECK macro can be used to suppress false report of -// memory leaks. It turns off the built-in heap checking until the -// block is left. The old state will then be restored Only used for -// Win32 (in the moment). -# if defined (ACE_WIN32) - -# if defined (_DEBUG) && !defined (ACE_HAS_WINCE) && !defined (__BORLANDC__) -# include /**/ - -// Open versioned namespace, if enabled by the user. -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -class ACE_Export ACE_No_Heap_Check -{ -public: - ACE_No_Heap_Check (void) - : old_state (_CrtSetDbgFlag (_CRTDBG_REPORT_FLAG)) - { _CrtSetDbgFlag (old_state & ~_CRTDBG_ALLOC_MEM_DF);} - ~ACE_No_Heap_Check (void) { _CrtSetDbgFlag (old_state);} -private: - int old_state; -}; - -// Close versioned namespace, if enabled by the user. -ACE_END_VERSIONED_NAMESPACE_DECL - -# define ACE_NO_HEAP_CHECK ACE_No_Heap_Check ____no_heap; -# else /* !_DEBUG */ -# define ACE_NO_HEAP_CHECK -# endif /* _DEBUG */ -# else /* !ACE_WIN32 */ -# define ACE_NO_HEAP_CHECK -# endif /* ACE_WIN32 */ - -// Turn a number into a string. -# define ACE_ITOA(X) #X - -// Create a string of a server address with a "host:port" format. -# define ACE_SERVER_ADDRESS(H,P) H ACE_TEXT(":") P - -// A couple useful inline functions for checking whether bits are -// enabled or disabled. - -// Efficiently returns the least power of two >= X... -# define ACE_POW(X) (((X) == 0)?1:(X-=1,X|=X>>1,X|=X>>2,X|=X>>4,X|=X>>8,X|=X>>16,(++X))) -# define ACE_EVEN(NUM) (((NUM) & 1) == 0) -# define ACE_ODD(NUM) (((NUM) & 1) == 1) -# define ACE_BIT_ENABLED(WORD, BIT) (((WORD) & (BIT)) != 0) -# define ACE_BIT_DISABLED(WORD, BIT) (((WORD) & (BIT)) == 0) -# define ACE_BIT_CMP_MASK(WORD, BIT, MASK) (((WORD) & (BIT)) == MASK) -# define ACE_SET_BITS(WORD, BITS) (WORD |= (BITS)) -# define ACE_CLR_BITS(WORD, BITS) (WORD &= ~(BITS)) - -# if !defined (ACE_ENDLESS_LOOP) -# define ACE_ENDLESS_LOOP -# endif /* ! ACE_ENDLESS_LOOP */ - -# if defined (ACE_NEEDS_FUNC_DEFINITIONS) - // It just evaporated ;-) Not pleasant. -# define ACE_UNIMPLEMENTED_FUNC(f) -# else -# define ACE_UNIMPLEMENTED_FUNC(f) f; -# endif /* ACE_NEEDS_FUNC_DEFINITIONS */ - -#if !defined (ACE_LACKS_DEPRECATED_MACROS) - // Easy way to designate that a class is used as a pseudo-namespace. - // Insures that g++ "friendship" anamolies are properly handled. - # define ACE_CLASS_IS_NAMESPACE(CLASSNAME) \ - private: \ - CLASSNAME (void); \ - CLASSNAME (const CLASSNAME&); \ - friend class ace_dewarn_gplusplus -#endif /* ACE_LACKS_DEPRECATED_MACROS */ - -// ---------------------------------------------------------------- - -//FUZZ: disable check_for_exception_sepc -#if !defined (ACE_LACKS_DEPRECATED_MACROS) - #if defined (ACE_HAS_NO_THROW_SPEC) - # define ACE_THROW_SPEC(X) - #else - # if defined (ACE_HAS_EXCEPTIONS) - # if defined (ACE_WIN32) && defined (_MSC_VER) && \ - (_MSC_VER >= 1400) && (_MSC_VER <= 1500) - # define ACE_THROW_SPEC(X) throw(...) - # else - # define ACE_THROW_SPEC(X) throw X - # endif /* ACE_WIN32 && VC8 */ - # else /* ! ACE_HAS_EXCEPTIONS */ - # define ACE_THROW_SPEC(X) - # endif /* ! ACE_HAS_EXCEPTIONS */ - #endif /*ACE_HAS_NO_THROW_SPEC*/ -#endif /* ACE_LACKS_DEPRECATED_MACROS */ -//FUZZ: enable check_for_exception_sepc - -// ---------------------------------------------------------------- - -#if !defined (ACE_LACKS_DEPRECATED_MACROS) - /** - * This macro is deprecated - */ - #define ACE_NESTED_CLASS(TYPE, NAME) TYPE::NAME -#endif /* ACE_LACKS_DEPRECATED_MACROS */ - -#if !defined (ACE_LACKS_DEPRECATED_MACROS) - /** - * @name CORBA namespace macros. - * - * CORBA namespace macros. - * - * @deprecated These macros were formerly used by TAO but are now - * deprecated, and only remain to retain some backward - * compatibility. They will be removed in a future ACE - * release. - */ - //@{ - #define ACE_CORBA_1(NAME) CORBA::NAME - #define ACE_CORBA_2(TYPE, NAME) CORBA::TYPE::NAME - #define ACE_CORBA_3(TYPE, NAME) CORBA::TYPE::NAME - //@} -#endif /* ACE_LACKS_DEPRECATED_MACROS */ - -// ---------------------------------------------------------------- - -// Convenient macro for testing for deadlock, as well as for detecting -// when mutexes fail. -#define ACE_GUARD_ACTION(MUTEX, OBJ, LOCK, ACTION, REACTION) \ - ACE_Guard< MUTEX > OBJ (LOCK); \ - if (OBJ.locked () != 0) { ACTION; } \ - else { REACTION; } -#define ACE_GUARD_REACTION(MUTEX, OBJ, LOCK, REACTION) \ - ACE_GUARD_ACTION(MUTEX, OBJ, LOCK, ;, REACTION) -#define ACE_GUARD(MUTEX, OBJ, LOCK) \ - ACE_GUARD_REACTION(MUTEX, OBJ, LOCK, return) -#define ACE_GUARD_RETURN(MUTEX, OBJ, LOCK, RETURN) \ - ACE_GUARD_REACTION(MUTEX, OBJ, LOCK, return RETURN) -# define ACE_WRITE_GUARD(MUTEX,OBJ,LOCK) \ - ACE_Write_Guard< MUTEX > OBJ (LOCK); \ - if (OBJ.locked () == 0) return; -# define ACE_WRITE_GUARD_RETURN(MUTEX,OBJ,LOCK,RETURN) \ - ACE_Write_Guard< MUTEX > OBJ (LOCK); \ - if (OBJ.locked () == 0) return RETURN; -# define ACE_READ_GUARD(MUTEX,OBJ,LOCK) \ - ACE_Read_Guard< MUTEX > OBJ (LOCK); \ - if (OBJ.locked () == 0) return; -# define ACE_READ_GUARD_RETURN(MUTEX,OBJ,LOCK,RETURN) \ - ACE_Read_Guard< MUTEX > OBJ (LOCK); \ - if (OBJ.locked () == 0) return RETURN; - -// ---------------------------------------------------------------- - -# define ACE_DES_NOFREE(POINTER,CLASS) \ - do { \ - if (POINTER) \ - { \ - (POINTER)->~CLASS (); \ - } \ - } \ - while (0) - -# define ACE_DES_ARRAY_NOFREE(POINTER,SIZE,CLASS) \ - do { \ - if (POINTER) \ - { \ - for (size_t i = 0; \ - i < SIZE; \ - ++i) \ - { \ - (&(POINTER)[i])->~CLASS (); \ - } \ - } \ - } \ - while (0) - -# define ACE_DES_FREE(POINTER,DEALLOCATOR,CLASS) \ - do { \ - if (POINTER) \ - { \ - (POINTER)->~CLASS (); \ - DEALLOCATOR (POINTER); \ - } \ - } \ - while (0) - -# define ACE_DES_ARRAY_FREE(POINTER,SIZE,DEALLOCATOR,CLASS) \ - do { \ - if (POINTER) \ - { \ - for (size_t i = 0; \ - i < SIZE; \ - ++i) \ - { \ - (&(POINTER)[i])->~CLASS (); \ - } \ - DEALLOCATOR (POINTER); \ - } \ - } \ - while (0) - -# if defined (ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR) -# define ACE_DES_NOFREE_TEMPLATE(POINTER,T_CLASS,T_PARAMETER) \ - do { \ - if (POINTER) \ - { \ - (POINTER)->~T_CLASS (); \ - } \ - } \ - while (0) -# define ACE_DES_ARRAY_NOFREE_TEMPLATE(POINTER,SIZE,T_CLASS,T_PARAMETER) \ - do { \ - if (POINTER) \ - { \ - for (size_t i = 0; \ - i < SIZE; \ - ++i) \ - { \ - (&(POINTER)[i])->~T_CLASS (); \ - } \ - } \ - } \ - while (0) - -#if defined (ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS) -# define ACE_DES_FREE_TEMPLATE(POINTER,DEALLOCATOR,T_CLASS,T_PARAMETER) \ - do { \ - if (POINTER) \ - { \ - (POINTER)->~T_CLASS T_PARAMETER (); \ - DEALLOCATOR (POINTER); \ - } \ - } \ - while (0) -#else -# define ACE_DES_FREE_TEMPLATE(POINTER,DEALLOCATOR,T_CLASS,T_PARAMETER) \ - do { \ - if (POINTER) \ - { \ - (POINTER)->~T_CLASS (); \ - DEALLOCATOR (POINTER); \ - } \ - } \ - while (0) -#endif /* defined(ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS) */ -# define ACE_DES_ARRAY_FREE_TEMPLATE(POINTER,SIZE,DEALLOCATOR,T_CLASS,T_PARAMETER) \ - do { \ - if (POINTER) \ - { \ - for (size_t i = 0; \ - i < SIZE; \ - ++i) \ - { \ - (&(POINTER)[i])->~T_CLASS (); \ - } \ - DEALLOCATOR (POINTER); \ - } \ - } \ - while (0) -#if defined(ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS) -# define ACE_DES_FREE_TEMPLATE2(POINTER,DEALLOCATOR,T_CLASS,T_PARAM1,T_PARAM2) \ - do { \ - if (POINTER) \ - { \ - (POINTER)->~T_CLASS (); \ - DEALLOCATOR (POINTER); \ - } \ - } \ - while (0) -#else -# define ACE_DES_FREE_TEMPLATE2(POINTER,DEALLOCATOR,T_CLASS,T_PARAM1,T_PARAM2) \ - do { \ - if (POINTER) \ - { \ - (POINTER)->~T_CLASS (); \ - DEALLOCATOR (POINTER); \ - } \ - } \ - while (0) -#endif /* defined(ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS) */ -#if defined(ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS) -# define ACE_DES_FREE_TEMPLATE3(POINTER,DEALLOCATOR,T_CLASS,T_PARAM1,T_PARAM2,T_PARAM3) \ - do { \ - if (POINTER) \ - { \ - (POINTER)->~T_CLASS (); \ - DEALLOCATOR (POINTER); \ - } \ - } \ - while (0) -#else -# define ACE_DES_FREE_TEMPLATE3(POINTER,DEALLOCATOR,T_CLASS,T_PARAM1,T_PARAM2,T_PARAM3) \ - do { \ - if (POINTER) \ - { \ - (POINTER)->~T_CLASS (); \ - DEALLOCATOR (POINTER); \ - } \ - } \ - while (0) -#endif /* defined(ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS) */ -#if defined(ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS) -# define ACE_DES_FREE_TEMPLATE4(POINTER,DEALLOCATOR,T_CLASS,T_PARAM1,T_PARAM2,T_PARAM3, T_PARAM4) \ - do { \ - if (POINTER) \ - { \ - (POINTER)->~T_CLASS (); \ - DEALLOCATOR (POINTER); \ - } \ - } \ - while (0) -#else -# define ACE_DES_FREE_TEMPLATE4(POINTER,DEALLOCATOR,T_CLASS,T_PARAM1,T_PARAM2,T_PARAM3, T_PARAM4) \ - do { \ - if (POINTER) \ - { \ - (POINTER)->~T_CLASS (); \ - DEALLOCATOR (POINTER); \ - } \ - } \ - while (0) -#endif /* defined(ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS) */ -# define ACE_DES_ARRAY_FREE_TEMPLATE2(POINTER,SIZE,DEALLOCATOR,T_CLASS,T_PARAM1,T_PARAM2) \ - do { \ - if (POINTER) \ - { \ - for (size_t i = 0; \ - i < SIZE; \ - ++i) \ - { \ - (&(POINTER)[i])->~T_CLASS (); \ - } \ - DEALLOCATOR (POINTER); \ - } \ - } \ - while (0) -# else /* ! ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR */ -# define ACE_DES_NOFREE_TEMPLATE(POINTER,T_CLASS,T_PARAMETER) \ - do { \ - if (POINTER) \ - { \ - (POINTER)->T_CLASS T_PARAMETER::~T_CLASS (); \ - } \ - } \ - while (0) -# define ACE_DES_ARRAY_NOFREE_TEMPLATE(POINTER,SIZE,T_CLASS,T_PARAMETER) \ - do { \ - if (POINTER) \ - { \ - for (size_t i = 0; \ - i < SIZE; \ - ++i) \ - { \ - (POINTER)[i].T_CLASS T_PARAMETER::~T_CLASS (); \ - } \ - } \ - } \ - while (0) -# define ACE_DES_FREE_TEMPLATE(POINTER,DEALLOCATOR,T_CLASS,T_PARAMETER) \ - do { \ - if (POINTER) \ - { \ - POINTER->T_CLASS T_PARAMETER::~T_CLASS (); \ - DEALLOCATOR (POINTER); \ - } \ - } \ - while (0) -# define ACE_DES_ARRAY_FREE_TEMPLATE(POINTER,SIZE,DEALLOCATOR,T_CLASS,T_PARAMETER) \ - do { \ - if (POINTER) \ - { \ - for (size_t i = 0; \ - i < SIZE; \ - ++i) \ - { \ - POINTER[i].T_CLASS T_PARAMETER::~T_CLASS (); \ - } \ - DEALLOCATOR (POINTER); \ - } \ - } \ - while (0) -# define ACE_DES_FREE_TEMPLATE2(POINTER,DEALLOCATOR,T_CLASS,T_PARAM1,T_PARAM2) \ - do { \ - if (POINTER) \ - { \ - POINTER->T_CLASS ::~T_CLASS (); \ - DEALLOCATOR (POINTER); \ - } \ - } \ - while (0) -# define ACE_DES_FREE_TEMPLATE3(POINTER,DEALLOCATOR,T_CLASS,T_PARAM1,T_PARAM2,T_PARAM3) \ - do { \ - if (POINTER) \ - { \ - POINTER->T_CLASS ::~T_CLASS (); \ - DEALLOCATOR (POINTER); \ - } \ - } \ - while (0) -# define ACE_DES_FREE_TEMPLATE4(POINTER,DEALLOCATOR,T_CLASS,T_PARAM1,T_PARAM2,T_PARAM3,T_PARAM4) \ - do { \ - if (POINTER) \ - { \ - POINTER->T_CLASS ::~T_CLASS (); \ - DEALLOCATOR (POINTER); \ - } \ - } \ - while (0) -# define ACE_DES_ARRAY_FREE_TEMPLATE2(POINTER,SIZE,DEALLOCATOR,T_CLASS,T_PARAM1,T_PARAM2) \ - do { \ - if (POINTER) \ - { \ - for (size_t i = 0; \ - i < SIZE; \ - ++i) \ - { \ - POINTER[i].T_CLASS ::~T_CLASS (); \ - } \ - DEALLOCATOR (POINTER); \ - } \ - } \ - while (0) -# endif /* defined ! ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR */ - - -/*******************************************************************/ - -/// Service Objects, i.e., objects dynamically loaded via the service -/// configurator, must provide a destructor function with the -/// following prototype to perform object cleanup. -typedef void (*ACE_Service_Object_Exterminator)(void *); - -/** @name Service Configurator macros - * - * The following macros are used to define helper objects used in - * ACE's Service Configurator framework, which is described in - * Chapter 5 of C++NPv2 . This - * framework implements the Component Configurator pattern, which is - * described in Chapter 2 of POSA2 . - * The intent of this pattern is to allow developers to dynamically - * load and configure services into a system. With a little help from - * this macros statically linked services can also be dynamically - * configured. - * - * More details about this component are available in the documentation - * of the ACE_Service_Configurator class and also - * ACE_Dynamic_Service. - * - * Notice that in all the macros the SERVICE_CLASS parameter must be - * the name of a class derived from ACE_Service_Object. - */ -//@{ -/// Declare a the data structure required to register a statically -/// linked service into the service configurator. -/** - * The macro should be used in the header file where the service is - * declared, its only argument is usually the name of the class that - * implements the service. - * - * @param SERVICE_CLASS The name of the class implementing the - * service. - */ -# define ACE_STATIC_SVC_DECLARE(SERVICE_CLASS) \ -extern ACE_Static_Svc_Descriptor ace_svc_desc_##SERVICE_CLASS ; - -/// As ACE_STATIC_SVC_DECLARE, but using an export macro for NT -/// compilers. -/** - * NT compilers require the use of explicit directives to export and - * import symbols from a DLL. If you need to define a service in a - * dynamic library you should use this version instead. - * Normally ACE uses a macro to inject the correct export/import - * directives on NT. Naturally it also the macro expands to a blank - * on platforms that do not require such directives. - * The first argument (EXPORT_NAME) is the prefix for this export - * macro, the full name is formed by appending _Export. - * ACE provides tools to generate header files that define the macro - * correctly on all platforms, please see - * $ACE_ROOT/bin/generate_export_file.pl - * - * @param EXPORT_NAME The export macro name prefix. - * @param SERVICE_CLASS The name of the class implementing the service. - */ -#define ACE_STATIC_SVC_DECLARE_EXPORT(EXPORT_NAME,SERVICE_CLASS) \ -extern EXPORT_NAME##_Export ACE_Static_Svc_Descriptor ace_svc_desc_##SERVICE_CLASS; - -/// Define the data structure used to register a statically linked -/// service into the Service Configurator. -/** - * The service configurator requires several arguments to build and - * control an statically linked service, including its name, the - * factory function used to construct the service, and some flags. - * All those parameters are configured in a single structure, an - * instance of this structure is statically initialized using the - * following macro. - * - * @param SERVICE_CLASS The name of the class that implements the - * service, must be derived (directly or indirectly) from - * ACE_Service_Object. - * @param NAME The name for this service, this name is used by the - * service configurator to match configuration options provided in - * the svc.conf file. - * @param TYPE The type of object. Objects can be streams or service - * objects. Please read the ACE_Service_Configurator and ASX - * documentation for more details. - * @param FN The name of the factory function, usually the - * ACE_SVC_NAME macro can be used to generate the name. The - * factory function is often defined using ACE_FACTORY_DECLARE and - * ACE_FACTORY_DEFINE. - * @param FLAGS Flags to control the ownership and lifecycle of the - * object. Please read the ACE_Service_Configurator documentation - * for more details. - * @param ACTIVE If not zero then a thread will be dedicate to the - * service. Please read the ACE_Service_Configurator documentation - * for more details. - */ -# define ACE_STATIC_SVC_DEFINE(SERVICE_CLASS, NAME, TYPE, FN, FLAGS, ACTIVE) \ -ACE_Static_Svc_Descriptor ace_svc_desc_##SERVICE_CLASS = { NAME, TYPE, FN, FLAGS, ACTIVE }; - -/// Automatically register a service with the service configurator -/** - * In some applications the services must be automatically registered - * with the service configurator, before main() starts. - * The ACE_STATIC_SVC_REQUIRE macro defines a class whose constructor - * register the service, it also defines a static instance of that - * class to ensure that the service is registered before main. - * - * On platforms that lack adequate support for static C++ objects the - * macro ACE_STATIC_SVC_REGISTER can be used to explicitly register - * the service. - * - * @todo One class per-Service_Object seems wasteful. It should be - * possible to define a single class and re-use it for all the - * service objects, just by passing the Service_Descriptor as an - * argument to the constructor. - */ -#if defined(ACE_LACKS_STATIC_CONSTRUCTORS) -# define ACE_STATIC_SVC_REQUIRE(SERVICE_CLASS)\ -class ACE_Static_Svc_##SERVICE_CLASS {\ -public:\ - ACE_Static_Svc_##SERVICE_CLASS() { \ - ACE_Service_Config::insert (\ - &ace_svc_desc_##SERVICE_CLASS); \ - } \ -}; -#define ACE_STATIC_SVC_REGISTER(SERVICE_CLASS)\ -ACE_Static_Svc_##SERVICE_CLASS ace_static_svc_##SERVICE_CLASS - -#else /* !ACE_LACKS_STATIC_CONSTRUCTORS */ - -# define ACE_STATIC_SVC_REQUIRE(SERVICE_CLASS)\ -class ACE_Static_Svc_##SERVICE_CLASS {\ -public:\ - ACE_Static_Svc_##SERVICE_CLASS() { \ - ACE_Service_Config::insert (\ - &ace_svc_desc_##SERVICE_CLASS); \ - } \ -};\ -static ACE_Static_Svc_##SERVICE_CLASS ace_static_svc_##SERVICE_CLASS; -#define ACE_STATIC_SVC_REGISTER(SERVICE_CLASS) do {} while (0) - -#endif /* !ACE_LACKS_STATIC_CONSTRUCTORS */ - -// Preprocessor symbols will not be expanded if they are -// concatenated. Force the preprocessor to expand them during the -// argument prescan by calling a macro that itself calls another that -// performs the actual concatenation. -#define ACE_PREPROC_CONCATENATE_IMPL(A,B) A ## B -#define ACE_PREPROC_CONCATENATE(A,B) ACE_PREPROC_CONCATENATE_IMPL(A,B) - -#if defined (ACE_HAS_VERSIONED_NAMESPACE) && ACE_HAS_VERSIONED_NAMESPACE == 1 -// Preprocessor symbols will not be expanded if they are -// concatenated. Force the preprocessor to expand them during the -// argument prescan by calling a macro that itself calls another that -// performs the actual concatenation. -# define ACE_MAKE_SVC_CONFIG_FUNCTION_NAME(PREFIX,VERSIONED_NAMESPACE,SERVICE_CLASS) PREFIX ## _ ## VERSIONED_NAMESPACE ## _ ## SERVICE_CLASS -#else -# define ACE_MAKE_SVC_CONFIG_FUNCTION_NAME(PREFIX,VERSIONED_NAMESPACE,SERVICE_CLASS) PREFIX ## _ ## SERVICE_CLASS -#endif /* ACE_HAS_VERSIONED_NAMESPACE == 1 */ - -#define ACE_MAKE_SVC_CONFIG_FACTORY_NAME(VERSIONED_NAMESPACE,SERVICE_CLASS) ACE_MAKE_SVC_CONFIG_FUNCTION_NAME(_make,VERSIONED_NAMESPACE,SERVICE_CLASS) -#define ACE_MAKE_SVC_CONFIG_GOBBLER_NAME(VERSIONED_NAMESPACE,SERVICE_CLASS) ACE_MAKE_SVC_CONFIG_FUNCTION_NAME(_gobble,VERSIONED_NAMESPACE,SERVICE_CLASS) - - -/// Declare the factory method used to create dynamically loadable -/// services. -/** - * Once the service implementation is dynamically loaded the Service - * Configurator uses a factory method to create the object. - * This macro declares such a factory function with the proper - * interface and export macros. - * Normally used in the header file that declares the service - * implementation. - * - * @param CLS must match the prefix of the export macro used for this - * service. - * @param SERVICE_CLASS must match the name of the class that - * implements the service. - * - */ -# define ACE_FACTORY_DECLARE(CLS,SERVICE_CLASS) \ -extern "C" CLS##_Export ACE_VERSIONED_NAMESPACE_NAME::ACE_Service_Object * \ -ACE_MAKE_SVC_CONFIG_FACTORY_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS) (ACE_Service_Object_Exterminator *); - -/// Define the factory method (and destructor) for a dynamically -/// loadable service. -/** - * Use with arguments matching ACE_FACTORY_DECLARE. - * Normally used in the .cpp file that defines the service - * implementation. - * - * This macro defines both the factory method and the function used to - * cleanup the service object. - * - * If this macro is used to define a factory function that need not be - * exported (for example, in a static service situation), CLS can be - * specified as ACE_Local_Service. - */ -# define ACE_Local_Service_Export - -#if defined (ACE_OPENVMS) -# define ACE_PREPROC_STRINGIFY(A) #A -# define ACE_MAKE_SVC_REGISTRAR_ARG(A) ACE_PREPROC_STRINGIFY(A), (void*)&A -# define ACE_FACTORY_DEFINE(CLS,SERVICE_CLASS) \ -void ACE_MAKE_SVC_CONFIG_GOBBLER_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS) (void *p) { \ - ACE_VERSIONED_NAMESPACE_NAME::ACE_Service_Object * _p = \ - static_cast< ACE_VERSIONED_NAMESPACE_NAME::ACE_Service_Object *> (p); \ - ACE_ASSERT (_p != 0); \ - delete _p; } \ -extern "C" CLS##_Export ACE_VERSIONED_NAMESPACE_NAME::ACE_Service_Object *\ -ACE_MAKE_SVC_CONFIG_FACTORY_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS) (ACE_Service_Object_Exterminator *gobbler) \ -{ \ - ACE_TRACE (#SERVICE_CLASS); \ - if (gobbler != 0) \ - *gobbler = (ACE_Service_Object_Exterminator) ACE_MAKE_SVC_CONFIG_GOBBLER_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS); \ - return new SERVICE_CLASS; \ -} \ -ACE_Dynamic_Svc_Registrar ace_svc_reg_##SERVICE_CLASS \ - (ACE_MAKE_SVC_REGISTRAR_ARG(ACE_MAKE_SVC_CONFIG_FACTORY_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS))); -#else -# define ACE_FACTORY_DEFINE(CLS,SERVICE_CLASS) \ -void ACE_MAKE_SVC_CONFIG_GOBBLER_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS) (void *p) { \ - ACE_VERSIONED_NAMESPACE_NAME::ACE_Service_Object * _p = \ - static_cast< ACE_VERSIONED_NAMESPACE_NAME::ACE_Service_Object *> (p); \ - ACE_ASSERT (_p != 0); \ - delete _p; } \ -extern "C" CLS##_Export ACE_VERSIONED_NAMESPACE_NAME::ACE_Service_Object *\ -ACE_MAKE_SVC_CONFIG_FACTORY_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS) (ACE_Service_Object_Exterminator *gobbler) \ -{ \ - ACE_TRACE (#SERVICE_CLASS); \ - if (gobbler != 0) \ - *gobbler = (ACE_Service_Object_Exterminator) ACE_MAKE_SVC_CONFIG_GOBBLER_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS); \ - return new SERVICE_CLASS; \ -} -#endif - -/** - * For service classes scoped within namespaces, use this macro in - * place of ACE_FACTORY_DEFINE. The third argument in this case is - * the fully scoped name of the class as it is to be - * instantiated. For example, given: - * namespace ACE - * { - * namespace Foo - * { - * class Bar : public ACE_Service_Object - * {}; - * }; - * }; - * - * ACE_FACTORY_DECLARE(ACE,ACE_Foo_Bar) - * - * you would then use: - * - * ACE_FACTORY_NAMESPACE_DEFINE(ACE,ACE_Foo_Bar,ACE::Foo::Bar) - * - * Note that in this example, the ACE_FACTORY_DECLARE is done outside - * the namespace scope. Then, the SERVICE_CLASS name is the same as - * the fully scoped class name, but with '::' replaced with '_'. Doing - * this will ensure unique generated signatures for the various C - * style functions. - */ -#if defined (ACE_OPENVMS) -# define ACE_PREPROC_STRINGIFY(A) #A -# define ACE_MAKE_SVC_REGISTRAR_ARG(A) ACE_PREPROC_STRINGIFY(A), (void*)&A -# define ACE_FACTORY_NAMESPACE_DEFINE(CLS,SERVICE_CLASS,NAMESPACE_CLASS) \ -void ACE_MAKE_SVC_CONFIG_GOBBLER_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS) (void *p) { \ - ACE_VERSIONED_NAMESPACE_NAME::ACE_Service_Object * _p = \ - static_cast< ACE_VERSIONED_NAMESPACE_NAME::ACE_Service_Object *> (p); \ - ACE_ASSERT (_p != 0); \ - delete _p; } \ -extern "C" CLS##_Export ACE_VERSIONED_NAMESPACE_NAME::ACE_Service_Object *\ -ACE_MAKE_SVC_CONFIG_FACTORY_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS) (ACE_Service_Object_Exterminator *gobbler) \ -{ \ - ACE_TRACE (#SERVICE_CLASS); \ - if (gobbler != 0) \ - *gobbler = (ACE_Service_Object_Exterminator) ACE_MAKE_SVC_CONFIG_GOBBLER_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS); \ - return new NAMESPACE_CLASS; \ -} \ -ACE_Dynamic_Svc_Registrar ace_svc_reg_##SERVICE_CLASS \ - (ACE_MAKE_SVC_REGISTRAR_ARG(ACE_MAKE_SVC_CONFIG_FACTORY_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS))); -#else -# define ACE_FACTORY_NAMESPACE_DEFINE(CLS,SERVICE_CLASS,NAMESPACE_CLASS) \ -void ACE_MAKE_SVC_CONFIG_GOBBLER_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS) (void *p) { \ - ACE_VERSIONED_NAMESPACE_NAME::ACE_Service_Object * _p = \ - static_cast< ACE_VERSIONED_NAMESPACE_NAME::ACE_Service_Object *> (p); \ - ACE_ASSERT (_p != 0); \ - delete _p; } \ -extern "C" CLS##_Export ACE_VERSIONED_NAMESPACE_NAME::ACE_Service_Object *\ -ACE_MAKE_SVC_CONFIG_FACTORY_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS) (ACE_Service_Object_Exterminator *gobbler) \ -{ \ - ACE_TRACE (#SERVICE_CLASS); \ - if (gobbler != 0) \ - *gobbler = (ACE_Service_Object_Exterminator) ACE_MAKE_SVC_CONFIG_GOBBLER_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS); \ - return new NAMESPACE_CLASS; \ -} -#endif - -/// The canonical name for a service factory method -# define ACE_SVC_NAME(SERVICE_CLASS) ACE_MAKE_SVC_CONFIG_FACTORY_NAME(ACE_VERSIONED_NAMESPACE_NAME,SERVICE_CLASS) - -/// The canonical way to invoke (i.e. construct) a service factory -/// method. -#define ACE_SVC_INVOKE(SERVICE_CLASS) ACE_SVC_NAME(SERVICE_CLASS) (0) - -//@} - -/** @name Helper macros for services defined in the netsvcs library. - * - * The ACE services defined in netsvcs use this helper macros for - * simplicity. - * - */ -//@{ -# define ACE_SVC_FACTORY_DECLARE(X) ACE_FACTORY_DECLARE (ACE_Svc, X) -# define ACE_SVC_FACTORY_DEFINE(X) ACE_FACTORY_DEFINE (ACE_Svc, X) -//@} - -#if defined (ACE_WIN32) -// These are used in SPIPE_Acceptor/Connector, but are ignored at runtime. -# if defined (ACE_HAS_WINCE) -# if !defined (PIPE_TYPE_MESSAGE) -# define PIPE_TYPE_MESSAGE 0 -# endif -# if !defined (PIPE_READMODE_MESSAGE) -# define PIPE_READMODE_MESSAGE 0 -# endif -# if !defined (PIPE_WAIT) -# define PIPE_WAIT 0 -# endif -# endif /* ACE_HAS_WINCE */ -#else /* !ACE_WIN32 */ -// Add some typedefs and macros to enhance Win32 conformance... -# if !defined (LPSECURITY_ATTRIBUTES) -# define LPSECURITY_ATTRIBUTES int -# endif /* !defined LPSECURITY_ATTRIBUTES */ -# if !defined (GENERIC_READ) -# define GENERIC_READ 0 -# endif /* !defined GENERIC_READ */ -# if !defined (FILE_SHARE_READ) -# define FILE_SHARE_READ 0 -# endif /* !defined FILE_SHARE_READ */ -# if !defined (OPEN_EXISTING) -# define OPEN_EXISTING 0 -# endif /* !defined OPEN_EXISTING */ -# if !defined (FILE_ATTRIBUTE_NORMAL) -# define FILE_ATTRIBUTE_NORMAL 0 -# endif /* !defined FILE_ATTRIBUTE_NORMAL */ -# if !defined (MAXIMUM_WAIT_OBJECTS) -# define MAXIMUM_WAIT_OBJECTS 0 -# endif /* !defined MAXIMUM_WAIT_OBJECTS */ -# if !defined (FILE_FLAG_OVERLAPPED) -# define FILE_FLAG_OVERLAPPED 0 -# endif /* !defined FILE_FLAG_OVERLAPPED */ -# if !defined (FILE_FLAG_SEQUENTIAL_SCAN) -# define FILE_FLAG_SEQUENTIAL_SCAN 0 -# endif /* FILE_FLAG_SEQUENTIAL_SCAN */ -# if !defined(FILE_FLAG_WRITE_THROUGH) -# define FILE_FLAG_WRITE_THROUGH 0 -# endif /* !defined FILE_FLAG_WRITE_THROUGH */ -# if !defined(PIPE_WAIT) -# define PIPE_WAIT 0 -# endif /* !defined PIPE_WAIT */ -# if !defined(PIPE_NOWAIT) -# define PIPE_NOWAIT 0 -# endif /* !defined PIPE_WAIT */ -# if !defined(PIPE_READMODE_BYTE) -# define PIPE_READMODE_BYTE 0 -# endif /* !defined PIPE_READMODE_BYTE */ -# if !defined(PIPE_READMODE_MESSAGE) -# define PIPE_READMODE_MESSAGE 0 -# endif /* !defined PIPE_READMODE_MESSAGE */ -# if !defined(PIPE_TYPE_BYTE) -# define PIPE_TYPE_BYTE 0 -# endif /* !defined PIPE_TYPE_BYTE */ -# if !defined(PIPE_TYPE_MESSAGE) -# define PIPE_TYPE_MESSAGE 0 -# endif /* !defined PIPE_TYPE_MESSAGE */ -#endif /* ACE_WIN32 */ - - -// Some useful abstrations for expressions involving -// ACE_Allocator.malloc (). The difference between ACE_NEW_MALLOC* -// with ACE_ALLOCATOR* is that they call constructors also. - -#include "ace/OS_Errno.h" /* Need errno and ENOMEM */ - -# define ACE_ALLOCATOR_RETURN(POINTER,ALLOCATOR,RET_VAL) \ - do { POINTER = ALLOCATOR; \ - if (POINTER == 0) { errno = ENOMEM; return RET_VAL; } \ - } while (0) -# define ACE_ALLOCATOR(POINTER,ALLOCATOR) \ - do { POINTER = ALLOCATOR; \ - if (POINTER == 0) { errno = ENOMEM; return; } \ - } while (0) -# define ACE_ALLOCATOR_NORETURN(POINTER,ALLOCATOR) \ - do { POINTER = ALLOCATOR; \ - if (POINTER == 0) { errno = ENOMEM; } \ - } while (0) - -# define ACE_NEW_MALLOC_RETURN(POINTER,ALLOCATOR,CONSTRUCTOR,RET_VAL) \ - do { POINTER = ALLOCATOR; \ - if (POINTER == 0) { errno = ENOMEM; return RET_VAL;} \ - else { (void) new (POINTER) CONSTRUCTOR; } \ - } while (0) -# define ACE_NEW_MALLOC(POINTER,ALLOCATOR,CONSTRUCTOR) \ - do { POINTER = ALLOCATOR; \ - if (POINTER == 0) { errno = ENOMEM; return;} \ - else { (void) new (POINTER) CONSTRUCTOR; } \ - } while (0) -# define ACE_NEW_MALLOC_NORETURN(POINTER,ALLOCATOR,CONSTRUCTOR) \ - do { POINTER = ALLOCATOR; \ - if (POINTER == 0) { errno = ENOMEM;} \ - else { (void) new (POINTER) CONSTRUCTOR; } \ - } while (0) - -/* ACE_Metrics */ -#if defined ACE_LACKS_ARRAY_PLACEMENT_NEW -# define ACE_NEW_MALLOC_ARRAY_RETURN(POINTER,ALLOCATOR,CONSTRUCTOR,COUNT,RET_VAL) \ - do { POINTER = ALLOCATOR; \ - if (POINTER == 0) { errno = ENOMEM; return RET_VAL;} \ - else { for (u_int i = 0; i < COUNT; ++i) \ - {(void) new (POINTER) CONSTRUCTOR; ++POINTER;} \ - POINTER -= COUNT;} \ - } while (0) -# define ACE_NEW_MALLOC_ARRAY(POINTER,ALLOCATOR,CONSTRUCTOR,COUNT) \ - do { POINTER = ALLOCATOR; \ - if (POINTER == 0) { errno = ENOMEM; return;} \ - else { for (u_int i = 0; i < COUNT; ++i) \ - {(void) new (POINTER) CONSTRUCTOR; ++POINTER;} \ - POINTER -= COUNT;} \ - } while (0) -#else /* ! defined ACE_LACKS_ARRAY_PLACEMENT_NEW */ -# define ACE_NEW_MALLOC_ARRAY_RETURN(POINTER,ALLOCATOR,CONSTRUCTOR,COUNT,RET_VAL) \ - do { POINTER = ALLOCATOR; \ - if (POINTER == 0) { errno = ENOMEM; return RET_VAL;} \ - else { (void) new (POINTER) CONSTRUCTOR [COUNT]; } \ - } while (0) -# define ACE_NEW_MALLOC_ARRAY(POINTER,ALLOCATOR,CONSTRUCTOR,COUNT) \ - do { POINTER = ALLOCATOR; \ - if (POINTER == 0) { errno = ENOMEM; return;} \ - else { (void) new (POINTER) CONSTRUCTOR [COUNT]; } \ - } while (0) -#endif /* defined ACE_LACKS_ARRAY_PLACEMENT_NEW */ - -// This is being placed here temporarily to help stablelize the builds, but will -// be moved out along with the above macros as part of the subsetting. dhinton -#if !defined (ACE_LACKS_NEW_H) -# if defined (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB) -# include /**/ -# else -# include /**/ -# endif /* ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB */ -#endif /* ! ACE_LACKS_NEW_H */ - -# define ACE_NOOP(x) - -#if defined (ACE_WIN32) && defined (ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS) -# define ACE_SEH_TRY __try -# define ACE_SEH_EXCEPT(X) __except(X) -# define ACE_SEH_FINALLY __finally -#else /* !ACE_WIN32 */ -# define ACE_SEH_TRY if (1) -# define ACE_SEH_EXCEPT(X) while (0) -# define ACE_SEH_FINALLY if (1) -#endif /* ACE_WIN32 */ - -// These should probably be put into a seperate header. - -// The following is necessary since many C++ compilers don't support -// typedef'd types inside of classes used as formal template -// arguments... ;-(. Luckily, using the C++ preprocessor I can hide -// most of this nastiness! - -# if defined (ACE_HAS_TEMPLATE_TYPEDEFS) - -// Handle ACE_Message_Queue. -# define ACE_SYNCH_DECL class _ACE_SYNCH -# define ACE_SYNCH_USE _ACE_SYNCH -# define ACE_SYNCH_MUTEX_T typename _ACE_SYNCH::MUTEX -# define ACE_SYNCH_CONDITION_T typename _ACE_SYNCH::CONDITION -# define ACE_SYNCH_SEMAPHORE_T typename _ACE_SYNCH::SEMAPHORE - -// Handle ACE_Malloc* -# define ACE_MEM_POOL_1 class _ACE_MEM_POOL -# define ACE_MEM_POOL_2 _ACE_MEM_POOL -# define ACE_MEM_POOL _ACE_MEM_POOL -# define ACE_MEM_POOL_OPTIONS typename _ACE_MEM_POOL::OPTIONS - -// Handle ACE_Svc_Handler -# define ACE_PEER_STREAM_1 class _ACE_PEER_STREAM -# define ACE_PEER_STREAM_2 _ACE_PEER_STREAM -# define ACE_PEER_STREAM _ACE_PEER_STREAM -# define ACE_PEER_STREAM_ADDR typename _ACE_PEER_STREAM::PEER_ADDR - -// Handle ACE_Acceptor -# define ACE_PEER_ACCEPTOR_1 class _ACE_PEER_ACCEPTOR -# define ACE_PEER_ACCEPTOR_2 _ACE_PEER_ACCEPTOR -# define ACE_PEER_ACCEPTOR _ACE_PEER_ACCEPTOR -# define ACE_PEER_ACCEPTOR_ADDR typename _ACE_PEER_ACCEPTOR::PEER_ADDR - -// Handle ACE_Connector -# define ACE_PEER_CONNECTOR_1 class _ACE_PEER_CONNECTOR -# define ACE_PEER_CONNECTOR_2 _ACE_PEER_CONNECTOR -# define ACE_PEER_CONNECTOR _ACE_PEER_CONNECTOR -# define ACE_PEER_CONNECTOR_ADDR typename ACE_PEER_CONNECTOR::PEER_ADDR -# define ACE_PEER_CONNECTOR_ADDR_ANY ACE_PEER_ADDR_TYPEDEF::sap_any - -// Handle ACE_SOCK_* -# define ACE_SOCK_ACCEPTOR ACE_SOCK_Acceptor -# define ACE_SOCK_CONNECTOR ACE_SOCK_Connector -# define ACE_SOCK_STREAM ACE_SOCK_Stream -# define ACE_SOCK_DGRAM ACE_SOCK_Dgram -# define ACE_SOCK_DGRAM_BCAST ACE_SOCK_Dgram_Bcast -# define ACE_SOCK_DGRAM_MCAST ACE_SOCK_Dgram_Mcast - -// Handle ACE_SOCK_SEQPACK_* -# define ACE_SOCK_SEQPACK_ACCEPTOR ACE_SOCK_SEQPACK_Acceptor -# define ACE_SOCK_SEQPACK_CONNECTOR ACE_SOCK_SEQPACK_Connector -# define ACE_SOCK_SEQPACK_ASSOCIATION ACE_SOCK_SEQPACK_Association - -// Handle ACE_MEM_* -# define ACE_MEM_ACCEPTOR ACE_MEM_Acceptor -# define ACE_MEM_CONNECTOR ACE_MEM_Connector -# define ACE_MEM_STREAM ACE_MEM_Stream - -// Handle ACE_LSOCK_* -# define ACE_LSOCK_ACCEPTOR ACE_LSOCK_Acceptor -# define ACE_LSOCK_CONNECTOR ACE_LSOCK_Connector -# define ACE_LSOCK_STREAM ACE_LSOCK_Stream - -// Handle ACE_TLI_* -# define ACE_TLI_ACCEPTOR ACE_TLI_Acceptor -# define ACE_TLI_CONNECTOR ACE_TLI_Connector -# define ACE_TLI_STREAM ACE_TLI_Stream - -// Handle ACE_SPIPE_* -# define ACE_SPIPE_ACCEPTOR ACE_SPIPE_Acceptor -# define ACE_SPIPE_CONNECTOR ACE_SPIPE_Connector -# define ACE_SPIPE_STREAM ACE_SPIPE_Stream - -// Handle ACE_UPIPE_* -# define ACE_UPIPE_ACCEPTOR ACE_UPIPE_Acceptor -# define ACE_UPIPE_CONNECTOR ACE_UPIPE_Connector -# define ACE_UPIPE_STREAM ACE_UPIPE_Stream - -// Handle ACE_FILE_* -# define ACE_FILE_CONNECTOR ACE_FILE_Connector -# define ACE_FILE_STREAM ACE_FILE_IO - -// Handle ACE_*_Memory_Pool. -# define ACE_MMAP_MEMORY_POOL ACE_MMAP_Memory_Pool -# define ACE_LITE_MMAP_MEMORY_POOL ACE_Lite_MMAP_Memory_Pool -# define ACE_SBRK_MEMORY_POOL ACE_Sbrk_Memory_Pool -# define ACE_SHARED_MEMORY_POOL ACE_Shared_Memory_Pool -# define ACE_LOCAL_MEMORY_POOL ACE_Local_Memory_Pool -# define ACE_PAGEFILE_MEMORY_POOL ACE_Pagefile_Memory_Pool - -# else /* TEMPLATES are broken in some form or another (i.e., most C++ compilers) */ - -// Handle ACE_Message_Queue. -# if defined (ACE_HAS_OPTIMIZED_MESSAGE_QUEUE) -# define ACE_SYNCH_DECL class _ACE_SYNCH_MUTEX_T, class _ACE_SYNCH_CONDITION_T, class _ACE_SYNCH_SEMAPHORE_T -# define ACE_SYNCH_USE _ACE_SYNCH_MUTEX_T, _ACE_SYNCH_CONDITION_T, _ACE_SYNCH_SEMAPHORE_T -# else -# define ACE_SYNCH_DECL class _ACE_SYNCH_MUTEX_T, class _ACE_SYNCH_CONDITION_T -# define ACE_SYNCH_USE _ACE_SYNCH_MUTEX_T, _ACE_SYNCH_CONDITION_T -# endif /* ACE_HAS_OPTIMIZED_MESSAGE_QUEUE */ -# define ACE_SYNCH_MUTEX_T _ACE_SYNCH_MUTEX_T -# define ACE_SYNCH_CONDITION_T _ACE_SYNCH_CONDITION_T -# define ACE_SYNCH_SEMAPHORE_T _ACE_SYNCH_SEMAPHORE_T - -// Handle ACE_Malloc* -# define ACE_MEM_POOL_1 class _ACE_MEM_POOL, class _ACE_MEM_POOL_OPTIONS -# define ACE_MEM_POOL_2 _ACE_MEM_POOL, _ACE_MEM_POOL_OPTIONS -# define ACE_MEM_POOL _ACE_MEM_POOL -# define ACE_MEM_POOL_OPTIONS _ACE_MEM_POOL_OPTIONS - -// Handle ACE_Svc_Handler -# define ACE_PEER_STREAM_1 class _ACE_PEER_STREAM, class _ACE_PEER_ADDR -# define ACE_PEER_STREAM_2 _ACE_PEER_STREAM, _ACE_PEER_ADDR -# define ACE_PEER_STREAM _ACE_PEER_STREAM -# define ACE_PEER_STREAM_ADDR _ACE_PEER_ADDR - -// Handle ACE_Acceptor -# define ACE_PEER_ACCEPTOR_1 class _ACE_PEER_ACCEPTOR, class _ACE_PEER_ADDR -# define ACE_PEER_ACCEPTOR_2 _ACE_PEER_ACCEPTOR, _ACE_PEER_ADDR -# define ACE_PEER_ACCEPTOR _ACE_PEER_ACCEPTOR -# define ACE_PEER_ACCEPTOR_ADDR _ACE_PEER_ADDR - -// Handle ACE_Connector -# define ACE_PEER_CONNECTOR_1 class _ACE_PEER_CONNECTOR, class _ACE_PEER_ADDR -# define ACE_PEER_CONNECTOR_2 _ACE_PEER_CONNECTOR, _ACE_PEER_ADDR -# define ACE_PEER_CONNECTOR _ACE_PEER_CONNECTOR -# define ACE_PEER_CONNECTOR_ADDR _ACE_PEER_ADDR -# define ACE_PEER_CONNECTOR_ADDR_ANY ACE_PEER_CONNECTOR_ADDR::sap_any - -// Handle ACE_SOCK_* -# define ACE_SOCK_ACCEPTOR ACE_SOCK_Acceptor, ACE_INET_Addr -# define ACE_SOCK_CONNECTOR ACE_SOCK_Connector, ACE_INET_Addr -# define ACE_SOCK_STREAM ACE_SOCK_Stream, ACE_INET_Addr -# define ACE_SOCK_DGRAM ACE_SOCK_Dgram, ACE_INET_Addr -# define ACE_SOCK_DGRAM_BCAST ACE_SOCK_Dgram_Bcast, ACE_INET_Addr -# define ACE_SOCK_DGRAM_MCAST ACE_SOCK_Dgram_Mcast, ACE_INET_Addr - -// Handle ACE_SOCK_SEQPACK_* -# define ACE_SOCK_SEQPACK_ACCEPTOR ACE_SOCK_SEQPACK_Acceptor, ACE_Multihomed_INET_Addr -# define ACE_SOCK_SEQPACK_CONNECTOR ACE_SOCK_SEQPACK_Connector, ACE_Multihomed_INET_Addr -# define ACE_SOCK_SEQPACK_ASSOCIATION ACE_SOCK_SEQPACK_Association, ACE_Multihomed_INET_Addr - -// Handle ACE_MEM_* -# define ACE_MEM_ACCEPTOR ACE_MEM_Acceptor, ACE_MEM_Addr -# define ACE_MEM_CONNECTOR ACE_MEM_Connector, ACE_INET_Addr -# define ACE_MEM_STREAM ACE_MEM_Stream, ACE_INET_Addr - -// Handle ACE_LSOCK_* -# define ACE_LSOCK_ACCEPTOR ACE_LSOCK_Acceptor, ACE_UNIX_Addr -# define ACE_LSOCK_CONNECTOR ACE_LSOCK_Connector, ACE_UNIX_Addr -# define ACE_LSOCK_STREAM ACE_LSOCK_Stream, ACE_UNIX_Addr - -// Handle ACE_TLI_* -# define ACE_TLI_ACCEPTOR ACE_TLI_Acceptor, ACE_INET_Addr -# define ACE_TLI_CONNECTOR ACE_TLI_Connector, ACE_INET_Addr -# define ACE_TLI_STREAM ACE_TLI_Stream, ACE_INET_Addr - -// Handle ACE_SPIPE_* -# define ACE_SPIPE_ACCEPTOR ACE_SPIPE_Acceptor, ACE_SPIPE_Addr -# define ACE_SPIPE_CONNECTOR ACE_SPIPE_Connector, ACE_SPIPE_Addr -# define ACE_SPIPE_STREAM ACE_SPIPE_Stream, ACE_SPIPE_Addr - -// Handle ACE_UPIPE_* -# define ACE_UPIPE_ACCEPTOR ACE_UPIPE_Acceptor, ACE_SPIPE_Addr -# define ACE_UPIPE_CONNECTOR ACE_UPIPE_Connector, ACE_SPIPE_Addr -# define ACE_UPIPE_STREAM ACE_UPIPE_Stream, ACE_SPIPE_Addr - -// Handle ACE_FILE_* -# define ACE_FILE_CONNECTOR ACE_FILE_Connector, ACE_FILE_Addr -# define ACE_FILE_STREAM ACE_FILE_IO, ACE_FILE_Addr - -// Handle ACE_*_Memory_Pool. -# define ACE_MMAP_MEMORY_POOL ACE_MMAP_Memory_Pool, ACE_MMAP_Memory_Pool_Options -# define ACE_LITE_MMAP_MEMORY_POOL ACE_Lite_MMAP_Memory_Pool, ACE_MMAP_Memory_Pool_Options -# define ACE_SBRK_MEMORY_POOL ACE_Sbrk_Memory_Pool, ACE_Sbrk_Memory_Pool_Options -# define ACE_SHARED_MEMORY_POOL ACE_Shared_Memory_Pool, ACE_Shared_Memory_Pool_Options -# define ACE_LOCAL_MEMORY_POOL ACE_Local_Memory_Pool, ACE_Local_Memory_Pool_Options -# define ACE_PAGEFILE_MEMORY_POOL ACE_Pagefile_Memory_Pool, ACE_Pagefile_Memory_Pool_Options -# endif /* ACE_HAS_TEMPLATE_TYPEDEFS */ - -// Work around compilers that don't like in-class static integral -// constants. Constants in this case are meant to be compile-time -// constants so that they may be used as template arguments, for -// example. BOOST provides a similar macro. -#ifndef ACE_LACKS_STATIC_IN_CLASS_CONSTANTS -# define ACE_STATIC_CONSTANT(TYPE, ASSIGNMENT) static TYPE const ASSIGNMENT -#else -# define ACE_STATIC_CONSTANT(TYPE, ASSIGNMENT) enum { ASSIGNMENT } -#endif /* !ACE_LACKS_STATIC_IN_CLASS_CONSTANTS */ - -#include /**/ "ace/post.h" - -#endif /*ACE_GLOBAL_MACROS_H*/ diff --git a/externals/ace/Guard_T.cpp b/externals/ace/Guard_T.cpp deleted file mode 100644 index 2090ddda2b7..00000000000 --- a/externals/ace/Guard_T.cpp +++ /dev/null @@ -1,61 +0,0 @@ -// $Id: Guard_T.cpp 85141 2009-04-22 08:48:30Z johnnyw $ - -#ifndef ACE_GUARD_T_CPP -#define ACE_GUARD_T_CPP - -#include "ace/Guard_T.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (__ACE_INLINE__) -#include "ace/Guard_T.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_HAS_DUMP) -# include "ace/Log_Msg.h" -#endif /* ACE_HAS_DUMP */ - -// **************************************************************** - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// ACE_ALLOC_HOOK_DEFINE(ACE_Guard) - -template void -ACE_Guard::dump (void) const -{ -#if defined (ACE_HAS_DUMP) -// ACE_TRACE ("ACE_Guard::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("mutex_ = %x\n"), this->lock_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("owner_ = %d\n"), this->owner_)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP, this)); -#endif /* ACE_HAS_DUMP */ -} - -// ACE_ALLOC_HOOK_DEFINE(ACE_Write_Guard) - -template void -ACE_Write_Guard::dump (void) const -{ -#if defined (ACE_HAS_DUMP) -// ACE_TRACE ("ACE_Write_Guard::dump"); - ACE_Guard::dump (); -#endif /* ACE_HAS_DUMP */ -} - -// ACE_ALLOC_HOOK_DEFINE(ACE_Read_Guard) - -template void -ACE_Read_Guard::dump (void) const -{ -// ACE_TRACE ("ACE_Read_Guard::dump"); - ACE_Guard::dump (); -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_GUARD_T_CPP */ diff --git a/externals/ace/Guard_T.h b/externals/ace/Guard_T.h deleted file mode 100644 index aee5c266c63..00000000000 --- a/externals/ace/Guard_T.h +++ /dev/null @@ -1,365 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file Guard_T.h - * - * $Id: Guard_T.h 83306 2008-10-17 12:19:53Z johnnyw $ - * - * Moved from Synch.h. - * - * @author Douglas C. Schmidt - */ -//========================================================================== - -#ifndef ACE_GUARD_T_H -#define ACE_GUARD_T_H -#include /**/ "ace/pre.h" - -#include "ace/Lock.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Global_Macros.h" -#include "ace/OS_NS_Thread.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Guard - * - * @brief This data structure is meant to be used within a method or - * function... It performs automatic aquisition and release of - * a parameterized synchronization object ACE_LOCK. - * - * The class given as an actual parameter must provide at - * the very least the , , , and - * methods. - */ -template -class ACE_Guard -{ -public: - - // = Initialization and termination methods. - ACE_Guard (ACE_LOCK &l); - - /// Implicitly and automatically acquire (or try to acquire) the - /// lock. If @a block is non-0 then the , else - /// it. - ACE_Guard (ACE_LOCK &l, bool block); - - /// Initialise the guard without implicitly acquiring the lock. The - /// @a become_owner parameter indicates whether the guard should release - /// the lock implicitly on destruction. The @a block parameter is - /// ignored and is used here to disambiguate with the preceding - /// constructor. - ACE_Guard (ACE_LOCK &l, bool block, int become_owner); - - /// Implicitly release the lock. - ~ACE_Guard (void); - - // = Lock accessors. - - /// Explicitly acquire the lock. - int acquire (void); - - /// Conditionally acquire the lock (i.e., won't block). - int tryacquire (void); - - /// Explicitly release the lock, but only if it is held! - int release (void); - - /// Relinquish ownership of the lock so that it is not released - /// implicitly in the destructor. - void disown (void); - - // = Utility methods. - /// true if locked, false if couldn't acquire the lock - /// (errno will contain the reason for this). - bool locked (void) const; - - /// Explicitly remove the lock. - int remove (void); - - /// Dump the state of an object. - void dump (void) const; - - // ACE_ALLOC_HOOK_DECLARE; - // Declare the dynamic allocation hooks. - -protected: - - /// Helper, meant for subclass only. - ACE_Guard (ACE_LOCK *lock): lock_ (lock), owner_ (0) {} - - /// Pointer to the ACE_LOCK we're guarding. - ACE_LOCK *lock_; - - /// Keeps track of whether we acquired the lock or failed. - int owner_; - -private: - // = Prevent assignment and initialization. - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Guard &)) - ACE_UNIMPLEMENTED_FUNC (ACE_Guard (const ACE_Guard &)) -}; - -/** - * @class ACE_Write_Guard - * - * @brief This class is similar to class ACE_Guard, though it - * acquires/releases a write lock automatically (naturally, the - * it is instantiated with must support the appropriate - * API). - */ -template -class ACE_Write_Guard : public ACE_Guard -{ -public: - // = Initialization method. - - /// Implicitly and automatically acquire a write lock. - ACE_Write_Guard (ACE_LOCK &m); - - /// Implicitly and automatically acquire (or try to acquire) a write - /// lock. - ACE_Write_Guard (ACE_LOCK &m, bool block); - - // = Lock accessors. - - /// Explicitly acquire the write lock. - int acquire_write (void); - - /// Explicitly acquire the write lock. - int acquire (void); - - /// Conditionally acquire the write lock (i.e., won't block). - int tryacquire_write (void); - - /// Conditionally acquire the write lock (i.e., won't block). - int tryacquire (void); - - // = Utility methods. - - /// Dump the state of an object. - void dump (void) const; - - // ACE_ALLOC_HOOK_DECLARE; - // Declare the dynamic allocation hooks. -}; - -/** - * @class ACE_Read_Guard - * - * @brief This class is similar to class ACE_Guard, though it - * acquires/releases a read lock automatically (naturally, the - * it is instantiated with must support the appropriate - * API). - */ -template -class ACE_Read_Guard : public ACE_Guard -{ -public: - // = Initialization methods. - - /// Implicitly and automatically acquire a read lock. - ACE_Read_Guard (ACE_LOCK& m); - - /// Implicitly and automatically acquire (or try to acquire) a read - /// lock. - ACE_Read_Guard (ACE_LOCK &m, bool block); - - // = Lock accessors. - - /// Explicitly acquire the read lock. - int acquire_read (void); - - /// Explicitly acquire the read lock. - int acquire (void); - - /// Conditionally acquire the read lock (i.e., won't block). - int tryacquire_read (void); - - /// Conditionally acquire the read lock (i.e., won't block). - int tryacquire (void); - - // = Utility methods. - - /// Dump the state of an object. - void dump (void) const; - - // ACE_ALLOC_HOOK_DECLARE; - // Declare the dynamic allocation hooks. -}; - -#if !(defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION))) - -#define ACE_TSS_Guard ACE_Guard -#define ACE_TSS_Write_GUARD ACE_Write_Guard -#define ACE_TSS_Read_GUARD ACE_Read_Guard - -#else - /* ACE platform supports some form of threading and - thread-specific storage. */ - -/** - * @class ACE_TSS_Guard - * - * @brief This data structure is meant to be used within a method or - * function... It performs automatic aquisition and release of - * a synchronization object. Moreover, it ensures that the lock - * is released even if a thread exits via ! - */ -template -class ACE_TSS_Guard -{ -public: - // = Initialization and termination methods. - - /// Implicitly and automatically acquire the thread-specific lock. - ACE_TSS_Guard (ACE_LOCK &lock, bool block = true); - - /// Implicitly release the thread-specific lock. - ~ACE_TSS_Guard (void); - - // = Lock accessors. - - /// Explicitly acquire the thread-specific lock. - int acquire (void); - - /// Conditionally acquire the thread-specific lock (i.e., won't - /// block). - int tryacquire (void); - - /// Explicitly release the thread-specific lock. - int release (void); - - // = Utility methods. - /// Explicitly release the thread-specific lock. - int remove (void); - - /// Dump the state of an object. - void dump (void) const; - - // ACE_ALLOC_HOOK_DECLARE; - // Declare the dynamic allocation hooks. - -protected: - /// Helper, meant for subclass only. - ACE_TSS_Guard (void); - - /// Initialize the key. - void init_key (void); - - /// Called when thread exits to clean up the lock. - static void cleanup (void *ptr); - - /// Thread-specific key... - ACE_thread_key_t key_; - -private: - // = Prevent assignment and initialization. - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_TSS_Guard &)) - ACE_UNIMPLEMENTED_FUNC (ACE_TSS_Guard (const ACE_TSS_Guard &)) -}; - -/** - * @class ACE_TSS_Write_Guard - * - * @brief This class is similar to class ACE_TSS_Guard, though it - * acquires/releases a write-lock automatically (naturally, the - * ACE_LOCK it is instantiated with must support the appropriate - * API). - */ -template -class ACE_TSS_Write_Guard : public ACE_TSS_Guard -{ -public: - // = Initialization method. - - /// Implicitly and automatically acquire the thread-specific write lock. - ACE_TSS_Write_Guard (ACE_LOCK &lock, bool block = true); - - // = Lock accessors. - - /// Explicitly acquire the thread-specific write lock. - int acquire_write (void); - - /// Explicitly acquire the thread-specific write lock. - int acquire (void); - - /// Conditionally acquire the thread-specific write lock (i.e., won't block). - int tryacquire_write (void); - - /// Conditionally acquire the thread-specific write lock (i.e., won't block). - int tryacquire (void); - - // = Utility methods. - - /// Dump the state of an object. - void dump (void) const; - - // ACE_ALLOC_HOOK_DECLARE; - // Declare the dynamic allocation hooks. -}; - -/** - * @class ACE_TSS_Read_Guard - * - * @brief This class is similar to class , though it - * acquires/releases a read lock automatically (naturally, the - * it is instantiated with must support the - * appropriate API). - */ -template -class ACE_TSS_Read_Guard : public ACE_TSS_Guard -{ -public: - // = Initialization method. - /// Implicitly and automatically acquire the thread-specific read lock. - ACE_TSS_Read_Guard (ACE_LOCK &lock, bool block = true); - - // = Lock accessors. - /// Explicitly acquire the thread-specific read lock. - int acquire_read (void); - - /// Explicitly acquire the thread-specific read lock. - int acquire (void); - - /// Conditionally acquire the thread-specific read lock (i.e., won't - /// block). - int tryacquire_read (void); - - /// Conditionally acquire the thread-specific read lock (i.e., won't - /// block). - int tryacquire (void); - - // = Utility methods. - /// Dump the state of an object. - void dump (void) const; - - // ACE_ALLOC_HOOK_DECLARE; - // Declare the dynamic allocation hooks. -}; - -#endif /* !(defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION))) */ - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Guard_T.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Guard_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Guard_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" -#endif /* ACE_GUARD_T_H */ diff --git a/externals/ace/Guard_T.inl b/externals/ace/Guard_T.inl deleted file mode 100644 index 3e7d5b61f8d..00000000000 --- a/externals/ace/Guard_T.inl +++ /dev/null @@ -1,170 +0,0 @@ -// -*- C++ -*- -// -// $Id: Guard_T.inl 82723 2008-09-16 09:35:44Z johnnyw $ - -#include "ace/RW_Thread_Mutex.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template ACE_INLINE int -ACE_Guard::acquire (void) -{ - return this->owner_ = this->lock_->acquire (); -} - -template ACE_INLINE int -ACE_Guard::tryacquire (void) -{ - return this->owner_ = this->lock_->tryacquire (); -} - -template ACE_INLINE int -ACE_Guard::release (void) -{ - if (this->owner_ == -1) - return -1; - else - { - this->owner_ = -1; - return this->lock_->release (); - } -} - -template ACE_INLINE -ACE_Guard::ACE_Guard (ACE_LOCK &l) - : lock_ (&l), - owner_ (0) -{ - this->acquire (); -} - -template ACE_INLINE -ACE_Guard::ACE_Guard (ACE_LOCK &l, bool block) - : lock_ (&l), - owner_ (0) -{ - if (block) - this->acquire (); - else - this->tryacquire (); -} - -template ACE_INLINE -ACE_Guard::ACE_Guard (ACE_LOCK &l, bool /* block */, int become_owner) - : lock_ (&l), - owner_ (become_owner == 0 ? -1 : 0) -{ -} - -// Implicitly and automatically acquire (or try to acquire) the -// lock. - -template ACE_INLINE -ACE_Guard::~ACE_Guard (void) -{ - this->release (); -} - -template ACE_INLINE bool -ACE_Guard::locked (void) const -{ - return this->owner_ != -1; -} - -template ACE_INLINE int -ACE_Guard::remove (void) -{ - return this->lock_->remove (); -} - -template ACE_INLINE void -ACE_Guard::disown (void) -{ - this->owner_ = -1; -} - -template ACE_INLINE -ACE_Write_Guard::ACE_Write_Guard (ACE_LOCK &m) - : ACE_Guard (&m) -{ - this->acquire_write (); -} - -template ACE_INLINE int -ACE_Write_Guard::acquire_write (void) -{ - return this->owner_ = this->lock_->acquire_write (); -} - -template ACE_INLINE int -ACE_Write_Guard::acquire (void) -{ - return this->owner_ = this->lock_->acquire_write (); -} - -template ACE_INLINE int -ACE_Write_Guard::tryacquire_write (void) -{ - return this->owner_ = this->lock_->tryacquire_write (); -} - -template ACE_INLINE int -ACE_Write_Guard::tryacquire (void) -{ - return this->owner_ = this->lock_->tryacquire_write (); -} - -template ACE_INLINE -ACE_Write_Guard::ACE_Write_Guard (ACE_LOCK &m, - bool block) - : ACE_Guard (&m) -{ - if (block) - this->acquire_write (); - else - this->tryacquire_write (); -} - -template ACE_INLINE int -ACE_Read_Guard::acquire_read (void) -{ - return this->owner_ = this->lock_->acquire_read (); -} - -template ACE_INLINE int -ACE_Read_Guard::acquire (void) -{ - return this->owner_ = this->lock_->acquire_read (); -} - -template ACE_INLINE int -ACE_Read_Guard::tryacquire_read (void) -{ - return this->owner_ = this->lock_->tryacquire_read (); -} - -template ACE_INLINE int -ACE_Read_Guard::tryacquire (void) -{ - return this->owner_ = this->lock_->tryacquire_read (); -} - -template ACE_INLINE -ACE_Read_Guard::ACE_Read_Guard (ACE_LOCK &m) - : ACE_Guard (&m) -{ - this->acquire_read (); -} - -template ACE_INLINE -ACE_Read_Guard::ACE_Read_Guard (ACE_LOCK &m, - bool block) - : ACE_Guard (&m) -{ - if (block) - this->acquire_read (); - else - this->tryacquire_read (); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Handle_Gobbler.h b/externals/ace/Handle_Gobbler.h deleted file mode 100644 index 9d6890a03fc..00000000000 --- a/externals/ace/Handle_Gobbler.h +++ /dev/null @@ -1,68 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Handle_Gobbler.h - * - * $Id: Handle_Gobbler.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Kirthika Parameswaran - * @author Irfan Pyarali - */ -//============================================================================= - - -#ifndef ACE_HANDLE_GOBBLER_H -#define ACE_HANDLE_GOBBLER_H -#include /**/ "ace/pre.h" - -#include "ace/Handle_Set.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Handle_Gobbler - * - * @brief This class gobbles up handles. - * - * This is useful when we need to control the number of handles - * available for a process. This class is mostly used for - * testing purposes. - */ -class ACE_Handle_Gobbler -{ -public: - - /// Destructor. Cleans up any remaining handles. - inline ~ACE_Handle_Gobbler (void); - - /** - * Handles are opened continously until the process runs out of - * them, and then handles are closed - * (freed) thereby making them usable in the future. - */ - inline int consume_handles (size_t n_handles_to_keep_available); - - /// Free up @a n_handles. - inline int free_handles (size_t n_handles); - - /// All remaining handles are closed. - inline void close_remaining_handles (void); - -private: - typedef ACE_Handle_Set HANDLE_SET; - - /// The container which holds the open descriptors. - HANDLE_SET handle_set_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include "ace/Handle_Gobbler.inl" - -#include /**/ "ace/post.h" -#endif /* ACE_HANDLE_GOBBLER_H */ diff --git a/externals/ace/Handle_Gobbler.inl b/externals/ace/Handle_Gobbler.inl deleted file mode 100644 index 6a053d88be0..00000000000 --- a/externals/ace/Handle_Gobbler.inl +++ /dev/null @@ -1,79 +0,0 @@ -// -*- C++ -*- -// -// $Id: Handle_Gobbler.inl 90388 2010-06-02 15:27:59Z vzykov $ - -// Since this is only included in Handle_Gobbler.h, these should be -// inline, not ACE_INLINE. -// FUZZ: disable check_for_inline - -#include "ace/ACE.h" -#include "ace/OS_NS_unistd.h" -#include "ace/OS_NS_fcntl.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -inline void -ACE_Handle_Gobbler::close_remaining_handles (void) -{ - ACE_Handle_Set_Iterator iter (this->handle_set_); - for (ACE_HANDLE h = iter (); h != ACE_INVALID_HANDLE; h = iter ()) - ACE_OS::close (h); -} - -inline -ACE_Handle_Gobbler::~ACE_Handle_Gobbler (void) -{ - this->close_remaining_handles (); -} - -inline int -ACE_Handle_Gobbler::free_handles (size_t n_handles) -{ - ACE_Handle_Set_Iterator iter (this->handle_set_); - for (ACE_HANDLE h = iter (); - h != ACE_INVALID_HANDLE && n_handles > 0; - --n_handles, h = iter ()) - ACE_OS::close (h); - - return 0; -} - -inline int -ACE_Handle_Gobbler::consume_handles (size_t n_handles_to_keep_available) -{ - int result = 0; - -#if defined(ACE_WIN32) - // On Win32, this style of gobbling doesn't seem to work. - ACE_UNUSED_ARG(n_handles_to_keep_available); - -#else - - while (1) - { - ACE_HANDLE handle = ACE_OS::open (ACE_DEV_NULL, O_WRONLY); - - if (handle == ACE_INVALID_HANDLE) - { - if (ACE::out_of_handles (errno)) - { - result = this->free_handles (n_handles_to_keep_available); - break; - } - else - { - result = -1; - break; - } - } - if (handle >= static_cast(FD_SETSIZE)) - break; - this->handle_set_.set_bit (handle); - } - -#endif /* ACE_WIN32 */ - - return result; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Handle_Ops.cpp b/externals/ace/Handle_Ops.cpp deleted file mode 100644 index 0ec856cf1c9..00000000000 --- a/externals/ace/Handle_Ops.cpp +++ /dev/null @@ -1,48 +0,0 @@ -// $Id: Handle_Ops.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Handle_Ops.h" - -#include "ace/OS_NS_errno.h" -#include "ace/OS_NS_fcntl.h" -#include "ace/Time_Value.h" - -ACE_RCSID (ace, - Handle_Ops, - "$Id: Handle_Ops.cpp 80826 2008-03-04 14:51:23Z wotte $") - - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_HANDLE -ACE::handle_timed_open (ACE_Time_Value *timeout, - const ACE_TCHAR *name, - int flags, - int perms, - LPSECURITY_ATTRIBUTES sa) -{ - ACE_TRACE ("ACE::handle_timed_open"); - - if (timeout != 0) - { -#if !defined (ACE_WIN32) - // On Win32, ACE_NONBLOCK gets recognized as O_WRONLY so we - // don't use it there - flags |= ACE_NONBLOCK; -#endif /* ACE_WIN32 */ - - // Open the named pipe or file using non-blocking mode... - ACE_HANDLE const handle = ACE_OS::open (name, flags, perms, sa); - - if (handle == ACE_INVALID_HANDLE - && (errno == EWOULDBLOCK - && (timeout->sec () > 0 || timeout->usec () > 0))) - // This expression checks if we were polling. - errno = ETIMEDOUT; - - return handle; - } - else - return ACE_OS::open (name, flags, perms, sa); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Handle_Ops.h b/externals/ace/Handle_Ops.h deleted file mode 100644 index c615380f8dd..00000000000 --- a/externals/ace/Handle_Ops.h +++ /dev/null @@ -1,50 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Handle_Ops.h - * - * $Id: Handle_Ops.h 80826 2008-03-04 14:51:23Z wotte $ - * - * Handle operations. - */ -//============================================================================= - -#ifndef ACE_HANDLE_OPS_H -#define ACE_HANDLE_OPS_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Global_Macros.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -class ACE_Time_Value; - -// = Operations on HANDLEs. -namespace ACE -{ - /** - * Wait up to @a timeout amount of time to actively open a device. - * This method doesn't perform the @c connect, it just does the - * timed wait. - */ - extern ACE_Export ACE_HANDLE handle_timed_open ( - ACE_Time_Value *timeout, - const ACE_TCHAR *name, - int flags, - int perms, - LPSECURITY_ATTRIBUTES sa = 0); -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" - -#endif /* ACE_HANDLE_OPS_H */ diff --git a/externals/ace/Handle_Set.cpp b/externals/ace/Handle_Set.cpp deleted file mode 100644 index 168acca86cd..00000000000 --- a/externals/ace/Handle_Set.cpp +++ /dev/null @@ -1,565 +0,0 @@ -// Handle_Set.cpp -// $Id: Handle_Set.cpp 83306 2008-10-17 12:19:53Z johnnyw $ - -#include "ace/Handle_Set.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Handle_Set.inl" -#endif /* __ACE_INLINE__ */ - -#include "ace/OS_NS_string.h" - -ACE_RCSID(ace, Handle_Set, "$Id: Handle_Set.cpp 83306 2008-10-17 12:19:53Z johnnyw $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Handle_Set) - - // ACE_MSB_MASK is only used here. - // This needs to go here to avoid overflow problems on some compilers. -#if defined (ACE_WIN32) - // Does ACE_WIN32 have an fd_mask? -# define ACE_MSB_MASK (~(1 << (NFDBITS - 1))) -#else /* ! ACE_WIN32 */ -# define ACE_MSB_MASK (~((fd_mask) 1 << (NFDBITS - 1))) -#endif /* ! ACE_WIN32 */ - -#if defined (linux) && __GLIBC__ > 1 && __GLIBC_MINOR__ >= 1 && !defined (_XOPEN_SOURCE) - // XPG4.2 requires the fds_bits member name, so it is not enabled by - // default on Linux/glibc-2.1.x systems. Instead use "__fds_bits." - // Ugly, but "what are you going to do?" 8-) -#define fds_bits __fds_bits -#endif /* linux && __GLIBC__ > 1 && __GLIBC_MINOR__ >= 1 && !_XOPEN_SOURCE */ - -void -ACE_Handle_Set::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Handle_Set::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nsize_ = %d"), this->size_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nmax_handle_ = %d"), this->max_handle_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n[ "))); - -#if defined (ACE_WIN32) - for (size_t i = 0; i < (size_t) this->mask_.fd_count + 1; i++) - ACE_DEBUG ((LM_DEBUG, ACE_TEXT (" %x "), this->mask_.fd_array[i])); -#else /* !ACE_WIN32 */ - for (ACE_HANDLE i = 0; i < this->max_handle_ + 1; i++) - if (this->is_set (i)) - ACE_DEBUG ((LM_DEBUG, ACE_TEXT (" %d "), i)); -#endif /* ACE_WIN32 */ - - ACE_DEBUG ((LM_DEBUG, ACE_TEXT (" ]\n"))); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -// Table that maps bytes to counts of the enabled bits in each value -// from 0 to 255, -// -// nbits_[0] == 0 -// -// because there are no bits enabled for the value 0. -// -// nbits_[5] == 2 -// -// because there are 2 bits enabled in the value 5, i.e., it's -// 101 in binary. - -const char ACE_Handle_Set::nbits_[256] = -{ - 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8}; - -// Constructor, initializes the bitmask to all 0s. - -ACE_Handle_Set::ACE_Handle_Set (void) -{ - ACE_TRACE ("ACE_Handle_Set::ACE_Handle_Set"); - this->reset (); -} - -ACE_Handle_Set::ACE_Handle_Set (const fd_set &fd_mask) -{ - ACE_TRACE ("ACE_Handle_Set::ACE_Handle_Set"); - this->reset (); - ACE_OS::memcpy ((void *) &this->mask_, - (void *) &fd_mask, - sizeof this->mask_); -#if !defined (ACE_WIN32) - this->sync (ACE_Handle_Set::MAXSIZE); -#if defined (ACE_HAS_BIG_FD_SET) - this->min_handle_ = 0; -#endif /* ACE_HAS_BIG_FD_SET */ -#endif /* !ACE_WIN32 */ -} - -// Counts the number of bits enabled in N. Uses a table lookup to -// speed up the count. - -int -ACE_Handle_Set::count_bits (u_long n) -{ - - ACE_TRACE ("ACE_Handle_Set::count_bits"); -#if defined (ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT) - register int rval = 0; - - // Count the number of enabled bits in . This algorithm is very - // fast, i.e., O(enabled bits in n). - - for (register u_long m = n; - m != 0; - m &= m - 1) - rval++; - - return rval; -#else - return (ACE_Handle_Set::nbits_[n & 0xff] - + ACE_Handle_Set::nbits_[(n >> 8) & 0xff] - + ACE_Handle_Set::nbits_[(n >> 16) & 0xff] - + ACE_Handle_Set::nbits_[(n >> 24) & 0xff]); -#endif /* ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT */ -} - -#if defined (ACE_HAS_BIG_FD_SET) -// Find the bit position counting from right to left worst case -// (1<<31) is 8. - -int -ACE_Handle_Set::bitpos (u_long bit) -{ - register int l = 0; - register u_long n = bit - 1; - - // This is a fast count method when have the most significative bit. - - while (n >> 8) - { - n >>= 8; - l += 8; - } - - // Is greater than 15? - if (n & 16) - { - n >>= 4; - l += 4; - } - - // Count number remaining bits. - while (n != 0) - { - n &= n - 1; - l++; - } - return l; -} -#endif /* ACE_HAS_BIG_FD_SET */ - -// Synchronize the underlying FD_SET with the MAX_FD and the SIZE. - -#if defined (ACE_USE_SHIFT_FOR_EFFICIENCY) -// These don't work because shifting right 3 bits is not the same as -// dividing by 3, e.g., dividing by 8 requires shifting right 3 bits. -// In order to do the shift, we need to calculate the number of bits -// at some point. -#define ACE_DIV_BY_WORDSIZE(x) ((x) >> ((int) ACE_Handle_Set::WORDSIZE)) -#define ACE_MULT_BY_WORDSIZE(x) ((x) << ((int) ACE_Handle_Set::WORDSIZE)) -#else -#define ACE_DIV_BY_WORDSIZE(x) ((x) / ((int) ACE_Handle_Set::WORDSIZE)) -#define ACE_MULT_BY_WORDSIZE(x) ((x) * ((int) ACE_Handle_Set::WORDSIZE)) -#endif /* ACE_USE_SHIFT_FOR_EFFICIENCY */ - -void -ACE_Handle_Set::sync (ACE_HANDLE max) -{ - ACE_TRACE ("ACE_Handle_Set::sync"); -#if !defined (ACE_WIN32) - fd_mask *maskp = (fd_mask *)(this->mask_.fds_bits); - this->size_ = 0; - - for (int i = ACE_DIV_BY_WORDSIZE (max - 1); - i >= 0; - i--) - this->size_ += ACE_Handle_Set::count_bits (maskp[i]); - - this->set_max (max); -#else - ACE_UNUSED_ARG (max); -#endif /* !ACE_WIN32 */ -} - -// Resets the MAX_FD after a clear of the original MAX_FD. - -void -ACE_Handle_Set::set_max (ACE_HANDLE current_max) -{ - ACE_TRACE ("ACE_Handle_Set::set_max"); -#if !defined(ACE_WIN32) - fd_mask * maskp = (fd_mask *)(this->mask_.fds_bits); - - if (this->size_ == 0) - this->max_handle_ = ACE_INVALID_HANDLE; - else - { - int i; - - for (i = ACE_DIV_BY_WORDSIZE (current_max - 1); - maskp[i] == 0; - i--) - continue; -#if defined (ACE_TANDEM_NSK_BIT_ORDER) - // bits are in reverse order, MSB (sign bit) = bit 0. - this->max_handle_ = ACE_MULT_BY_WORDSIZE (i); - for (fd_mask val = maskp[i]; - (val & ACE_MSB_MASK) != 0; - val = (val << 1)) - ++this->max_handle_; -#elif 1 /* !defined(ACE_HAS_BIG_FD_SET) */ - this->max_handle_ = ACE_MULT_BY_WORDSIZE (i); - for (fd_mask val = maskp[i]; - (val & ~1) != 0; // This obscure code is needed since "bit 0" is in location 1... - val = (val >> 1) & ACE_MSB_MASK) - ++this->max_handle_; -#else - register u_long val = this->mask_.fds_bits[i]; - this->max_handle_ = ACE_MULT_BY_WORDSIZE (i) - + ACE_Handle_Set::bitpos(val & ~(val - 1)); -#endif /* 1 */ - } - - // Do some sanity checking... - if (this->max_handle_ >= ACE_Handle_Set::MAXSIZE) - this->max_handle_ = ACE_Handle_Set::MAXSIZE - 1; -#else - ACE_UNUSED_ARG (current_max); -#endif /* !ACE_WIN32 */ -} - -ACE_ALLOC_HOOK_DEFINE(ACE_Handle_Set_Iterator) - -void -ACE_Handle_Set_Iterator::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Handle_Set_Iterator::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); -#if defined(ACE_WIN32) || !defined(ACE_HAS_BIG_FD_SET) - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nhandle_index_ = %d"), this->handle_index_)); -#elif defined(ACE_HAS_BIG_FD_SET) - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nword_max_ = %d"), this->word_max_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nword_val_ = %d"), this->word_val_)); -#endif - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nword_num_ = %d"), this->word_num_)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -ACE_HANDLE -ACE_Handle_Set_Iterator::operator () (void) -{ - ACE_TRACE ("ACE_Handle_Set_Iterator::operator"); -#if defined (ACE_WIN32) - if (this->handle_index_ < this->handles_.mask_.fd_count) - // Return the handle and advance the iterator. - return (ACE_HANDLE) this->handles_.mask_.fd_array[this->handle_index_++]; - else - return ACE_INVALID_HANDLE; - -#elif !defined (ACE_HAS_BIG_FD_SET) /* !ACE_WIN32 */ - // No sense searching further than the max_handle_ + 1; - ACE_HANDLE maxhandlep1 = this->handles_.max_handle_ + 1; - - // HP-UX 11 plays some games with the fd_mask type - fd_mask is - // defined as an int_32t, but the fds_bits is an array of longs. - // This makes plainly indexing through the array by hand tricky, - // since the FD_* macros treat the array as int32_t. So the bits - // are in the right place for int32_t, even though the array is - // long. This, they say, is to preserve the same in-memory layout - // for 32-bit and 64-bit processes. So, we play the same game as - // the FD_* macros to get the bits right. On all other systems, - // this amounts to practically a NOP, since this is what would have - // been done anyway, without all this type jazz. - fd_mask * maskp = (fd_mask *)(this->handles_.mask_.fds_bits); - - if (this->handle_index_ >= maxhandlep1) - // We've seen all the handles we're interested in seeing for this - // iterator. - return ACE_INVALID_HANDLE; - else - { - ACE_HANDLE result = this->handle_index_; - - // Increment the iterator and advance to the next bit in this - // word. - this->handle_index_++; -#if defined (ACE_TANDEM_NSK_BIT_ORDER) - // bits are in reverse order, MSB (sign bit) = bit 0. - this->word_val_ = (this->word_val_ << 1); -# else - this->word_val_ = (this->word_val_ >> 1) & ACE_MSB_MASK; -# endif /* ACE_TANDEM_NSK_BIT_ORDER */ - - // If we've examined all the bits in this word, we'll go onto - // the next word. - - if (this->word_val_ == 0) - { - // Start the handle_index_ at the beginning of the next word - // and then loop until we've found the first non-zero bit or - // we run past the of the bitset. - - for (this->handle_index_ = ACE_MULT_BY_WORDSIZE(++this->word_num_); - this->handle_index_ < maxhandlep1 - && maskp[this->word_num_] == 0; - this->word_num_++) - this->handle_index_ += ACE_Handle_Set::WORDSIZE; - - // If the bit index becomes >= the maxhandlep1 that means - // there weren't any more bits set that we want to consider. - // Therefore, we'll just store the maxhandlep1, which will - // cause to return - // immediately next time it's called. - if (this->handle_index_ >= maxhandlep1) - { - this->handle_index_ = maxhandlep1; - return result; - } - else - // Load the bits of the next word. - this->word_val_ = maskp[this->word_num_]; - } - - // Loop until we get to have its least significant - // bit enabled, keeping track of which this - // represents (this information is used by subsequent calls to - // ). - -#if defined (ACE_TANDEM_NSK_BIT_ORDER) - // bits are in reverse order, MSB (sign bit) = bit 0. - for (; - this->word_val_ > 0; - this->word_val_ = (this->word_val_ << 1)) - this->handle_index_++; -# else - for (; - ACE_BIT_DISABLED (this->word_val_, 1); - this->handle_index_++) - this->word_val_ = (this->word_val_ >> 1) & ACE_MSB_MASK; -# endif /* ACE_TANDEM_NSK_BIT_ORDER */ - - return result; - } -#else /* !ACE_HAS_BIG_FD_SET */ - // Find the first word in fds_bits with bit on - register u_long lsb = this->word_val_; - - if (lsb == 0) - { - do - { - // We have exceeded the word count in Handle_Set? - if (++this->word_num_ >= this->word_max_) - return ACE_INVALID_HANDLE; - - lsb = this->handles_.mask_.fds_bits[this->word_num_]; - } - while (lsb == 0); - - // Set index to word boundary. - this->handle_index_ = ACE_MULT_BY_WORDSIZE (this->word_num_); - - // Put new word_val. - this->word_val_ = lsb; - - // Find the least significative bit. - lsb &= ~(lsb - 1); - - // Remove least significative bit. - this->word_val_ ^= lsb; - - // Save to calculate bit distance. - this->oldlsb_ = lsb; - - // Move index to least significative bit. - while (lsb >>= 1) - this->handle_index_++; - } - else - { - // Find the least significative bit. - lsb &= ~(lsb - 1); - - // Remove least significative bit. - this->word_val_ ^= lsb; - - register u_long n = lsb - this->oldlsb_; - - // Move index to bit distance between new lsb and old lsb. - do - { - this->handle_index_++; - n &= n >> 1; - } - while (n != 0); - - this->oldlsb_ = lsb; - } - - return this->handle_index_; -#endif /* ACE_WIN32 */ -} - -ACE_Handle_Set_Iterator::ACE_Handle_Set_Iterator (const ACE_Handle_Set &hs) - : handles_ (hs), -#if !defined (ACE_HAS_BIG_FD_SET) || defined (ACE_WIN32) - handle_index_ (0), - word_num_ (-1) -#elif defined (ACE_HAS_BIG_FD_SET) - oldlsb_ (0), - word_max_ (hs.max_handle_ == ACE_INVALID_HANDLE - ? 0 - : ((ACE_DIV_BY_WORDSIZE (hs.max_handle_)) + 1)) -#endif /* ACE_HAS_BIG_FD_SET */ -{ - ACE_TRACE ("ACE_Handle_Set_Iterator::ACE_Handle_Set_Iterator"); -#if !defined (ACE_WIN32) && !defined (ACE_HAS_BIG_FD_SET) - // No sense searching further than the max_handle_ + 1; - ACE_HANDLE maxhandlep1 = - this->handles_.max_handle_ + 1; - - fd_mask *maskp = - (fd_mask *)(this->handles_.mask_.fds_bits); - - // Loop until we've found the first non-zero bit or we run past the - // of the bitset. - while (this->handle_index_ < maxhandlep1 - && maskp[++this->word_num_] == 0) - this->handle_index_ += ACE_Handle_Set::WORDSIZE; - - // If the bit index becomes >= the maxhandlep1 that means there - // weren't any bits set. Therefore, we'll just store the - // maxhandlep1, which will cause to return - // immediately. - if (this->handle_index_ >= maxhandlep1) - this->handle_index_ = maxhandlep1; - else - // Loop until we get to have its least significant bit - // enabled, keeping track of which this represents - // (this information is used by ). -#if defined (ACE_TANDEM_NSK_BIT_ORDER) - // bits are in reverse order, MSB (sign bit) = bit 0. - for (this->word_val_ = maskp[this->word_num_]; - this->word_val_ > 0; - this->word_val_ = (this->word_val_ << 1)) - this->handle_index_++; -# else - for (this->word_val_ = maskp[this->word_num_]; - ACE_BIT_DISABLED (this->word_val_, 1) - && this->handle_index_ < maxhandlep1; - this->handle_index_++) - this->word_val_ = (this->word_val_ >> 1) & ACE_MSB_MASK; -# endif /* ACE_TANDEM_NSK_BIT_ORDER */ -#elif !defined (ACE_WIN32) && defined (ACE_HAS_BIG_FD_SET) - if (this->word_max_==0) - { - this->word_num_ = -1; - this->word_val_ = 0; - } - else - { - this->word_num_ = - ACE_DIV_BY_WORDSIZE (this->handles_.min_handle_) - 1; - this->word_val_ = 0; - } -#endif /* !ACE_WIN32 && !ACE_HAS_BIG_FD_SET */ -} - - -void -ACE_Handle_Set_Iterator::reset_state (void) -{ - ACE_TRACE ("ACE_Handle_Set_Iterator::reset_state"); - -#if !defined (ACE_HAS_BIG_FD_SET) || defined (ACE_WIN32) - this->handle_index_ = 0; - this->word_num_ = -1; -#elif defined (ACE_HAS_BIG_FD_SET) - this->oldlsb_ = 0; - this->word_max_ = - this->handles_.max_handle_ == ACE_INVALID_HANDLE ? 0 - : ((ACE_DIV_BY_WORDSIZE (this->handles_.max_handle_)) + 1); -#endif /* ACE_HAS_BIG_FD_SET */ - -#if !defined (ACE_WIN32) && !defined (ACE_HAS_BIG_FD_SET) - // No sense searching further than the max_handle_ + 1; - ACE_HANDLE maxhandlep1 = - this->handles_.max_handle_ + 1; - - fd_mask *maskp = - (fd_mask *)(this->handles_.mask_.fds_bits); - - // Loop until we've found the first non-zero bit or we run past the - // of the bitset. - while (this->handle_index_ < maxhandlep1 - && maskp[++this->word_num_] == 0) - this->handle_index_ += ACE_Handle_Set::WORDSIZE; - - // If the bit index becomes >= the maxhandlep1 that means there - // weren't any bits set. Therefore, we'll just store the - // maxhandlep1, which will cause to return - // immediately. - if (this->handle_index_ >= maxhandlep1) - this->handle_index_ = maxhandlep1; - else - // Loop until we get to have its least significant bit - // enabled, keeping track of which this represents - // (this information is used by ). -#if defined (ACE_TANDEM_NSK_BIT_ORDER) - // bits are in reverse order, MSB (sign bit) = bit 0. - for (this->word_val_ = maskp[this->word_num_]; - this->word_val_ > 0; - this->word_val_ = (this->word_val_ << 1)) - this->handle_index_++; -# else - for (this->word_val_ = maskp[this->word_num_]; - ACE_BIT_DISABLED (this->word_val_, 1) - && this->handle_index_ < maxhandlep1; - this->handle_index_++) - this->word_val_ = (this->word_val_ >> 1) & ACE_MSB_MASK; -# endif /* ACE_TANDEM_NSK_BIT_ORDER */ -#elif !defined (ACE_WIN32) && defined (ACE_HAS_BIG_FD_SET) - if (this->word_max_==0) - { - this->word_num_ = -1; - this->word_val_ = 0; - } - else - { - this->word_num_ = - ACE_DIV_BY_WORDSIZE (this->handles_.min_handle_) - 1; - this->word_val_ = 0; - } -#endif /* !ACE_WIN32 && !ACE_HAS_BIG_FD_SET */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Handle_Set.h b/externals/ace/Handle_Set.h deleted file mode 100644 index 11188f9fc38..00000000000 --- a/externals/ace/Handle_Set.h +++ /dev/null @@ -1,236 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file Handle_Set.h - * - * $Id: Handle_Set.h 82723 2008-09-16 09:35:44Z johnnyw $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_HANDLE_SET_H -#define ACE_HANDLE_SET_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_select.h" -#include "ace/os_include/os_limits.h" - -// Default size of the ACE Reactor. -#if defined (FD_SETSIZE) - int const ACE_FD_SETSIZE = FD_SETSIZE; -#else /* !FD_SETSIZE */ -# define ACE_FD_SETSIZE FD_SETSIZE -#endif /* ACE_FD_SETSIZE */ - -#if !defined (ACE_DEFAULT_SELECT_REACTOR_SIZE) -# define ACE_DEFAULT_SELECT_REACTOR_SIZE ACE_FD_SETSIZE -#endif /* ACE_DEFAULT_SELECT_REACTOR_SIZE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Handle_Set - * - * @brief C++ wrapper facade for the socket @c fd_set abstraction. - * - * This abstraction is a very efficient wrapper facade over - * @c fd_set. In particular, no range checking is performed, so - * it's important not to set or clear bits that are outside the - * @c ACE_DEFAULT_SELECT_REACTOR_SIZE. - */ -class ACE_Export ACE_Handle_Set -{ -public: - friend class ACE_Handle_Set_Iterator; - - // = Initialization and termination. - - enum - { - MAXSIZE = ACE_DEFAULT_SELECT_REACTOR_SIZE - }; - - // = Initialization methods. - /// Constructor, initializes the bitmask to all 0s. - ACE_Handle_Set (void); - - /** - * Constructor, initializes the handle set from a given mask. - */ - ACE_Handle_Set (const fd_set &mask); - - // = Methods for manipulating bitsets. - /// Initialize the bitmask to all 0s and reset the associated fields. - void reset (void); - - /** - * Checks whether @a handle is enabled. No range checking is - * performed so @a handle must be less than - * @c ACE_DEFAULT_SELECT_REACTOR_SIZE. - */ - int is_set (ACE_HANDLE handle) const; - - /// Enables the @a handle. No range checking is performed so @a handle - /// must be less than @c ACE_DEFAULT_SELECT_REACTOR_SIZE. - void set_bit (ACE_HANDLE handle); - - /// Disables the @a handle. No range checking is performed so - /// @a handle must be less than @c ACE_DEFAULT_SELECT_REACTOR_SIZE. - void clr_bit (ACE_HANDLE handle); - - /// Returns a count of the number of enabled bits. - int num_set (void) const; - - /// Returns the number of the large bit. - ACE_HANDLE max_set (void) const; - - /** - * Rescan the underlying @c fd_set up to handle @a max to find the new - * (highest bit set) and (how many bits set) values. - * This is useful for evaluating the changes after the handle set has - * been manipulated in some way other than member functions; for example, - * after - ACE_Select_Reactor_Handle_Set dispatch_set_; - - /// Tracks handles that are waited for by . - ACE_Select_Reactor_Handle_Set ready_set_; - - /// Defined as a pointer to allow overriding by derived classes... - ACE_Timer_Queue *timer_queue_; - - /// Handle signals without requiring global/static variables. - ACE_Sig_Handler *signal_handler_; - - /// Callback object that unblocks the ACE_Select_Reactor if it's - /// sleeping. - ACE_Reactor_Notify *notify_handler_; - - /// Keeps track of whether we should delete the timer queue (if we - /// didn't create it, then we don't delete it). - bool delete_timer_queue_; - - /// Keeps track of whether we should delete the signal handler (if we - /// didn't create it, then we don't delete it). - bool delete_signal_handler_; - - /// Keeps track of whether we need to delete the notify handler (if - /// we didn't create it, then we don't delete it). - bool delete_notify_handler_; - - /// True if we've been initialized yet... - bool initialized_; - - /// Restart the event-loop method automatically when - /// . - - if (number_of_active_handles == 0) - { - do - { - if (this->timer_queue_ == 0) - return 0; - - this_timeout = - this->timer_queue_->calculate_timeout (max_wait_time, - &timer_buf); -#ifdef ACE_WIN32 - // This arg is ignored on Windows and causes pointer - // truncation warnings on 64-bit compiles. - int const width = 0; -#else - int const width = this->handler_rep_.max_handlep1 (); -#endif /* ACE_WIN32 */ - - dispatch_set.rd_mask_ = this->wait_set_.rd_mask_; - dispatch_set.wr_mask_ = this->wait_set_.wr_mask_; - dispatch_set.ex_mask_ = this->wait_set_.ex_mask_; - number_of_active_handles = ACE_OS::select (width, - dispatch_set.rd_mask_, - dispatch_set.wr_mask_, - dispatch_set.ex_mask_, - this_timeout); - } - while (number_of_active_handles == -1 && this->handle_error () > 0); - - if (number_of_active_handles > 0) - { -#if !defined (ACE_WIN32) - // Resynchronize the fd_sets so their "max" is set properly. - dispatch_set.rd_mask_.sync (this->handler_rep_.max_handlep1 ()); - dispatch_set.wr_mask_.sync (this->handler_rep_.max_handlep1 ()); - dispatch_set.ex_mask_.sync (this->handler_rep_.max_handlep1 ()); -#endif /* ACE_WIN32 */ - } - else if (number_of_active_handles == -1) - { - // Normally, select() will reset the bits in dispatch_set - // so that only those filed descriptors that are ready will - // have bits set. However, when an error occurs, the bit - // set remains as it was when the select call was first made. - // Thus, we now have a dispatch_set that has every file - // descriptor that was originally waited for, which is not - // correct. We must clear all the bit sets because we - // have no idea if any of the file descriptors is ready. - // - // NOTE: We dont have a test case to reproduce this - // problem. But pleae dont ignore this and remove it off. - dispatch_set.rd_mask_.reset (); - dispatch_set.wr_mask_.reset (); - dispatch_set.ex_mask_.reset (); - } - } - - // Return the number of events to dispatch. - return number_of_active_handles; -} - -template int -ACE_Select_Reactor_T::dispatch_timer_handlers - (int &number_of_handlers_dispatched) -{ - number_of_handlers_dispatched += this->timer_queue_->expire (); - - return 0; -} - -template int -ACE_Select_Reactor_T::dispatch_notification_handlers - (ACE_Select_Reactor_Handle_Set &dispatch_set, - int &number_of_active_handles, - int &number_of_handlers_dispatched) -{ - // Check to see if the ACE_HANDLE associated with the - // Select_Reactor's notify hook is enabled. If so, it means that - // one or more other threads are trying to update the - // ACE_Select_Reactor_T's internal tables or the notify pipe is - // enabled. We'll handle all these threads and notifications, and - // then break out to continue the event loop. - int const n = - this->notify_handler_->dispatch_notifications (number_of_active_handles, - dispatch_set.rd_mask_); - - if (n == -1) - return -1; - else - { - number_of_handlers_dispatched += n; - number_of_active_handles -= n; - } - - // Same as dispatch_timer_handlers - // No need to do anything with the state changed. That is because - // unbind already handles the case where someone unregister some - // kind of handle and unbind it. (::unbind calls the function - // state_changed () to reflect ant change with that) - // return this->state_changed_ ? -1 : 0; - return 0; -} - -template int -ACE_Select_Reactor_T::dispatch_io_set - (int number_of_active_handles, - int &number_of_handlers_dispatched, - int mask, - ACE_Handle_Set &dispatch_mask, - ACE_Handle_Set &ready_mask, - ACE_EH_PTMF callback) -{ - ACE_TRACE ("ACE_Select_Reactor_T::dispatch_io_set"); - ACE_HANDLE handle; - - ACE_Handle_Set_Iterator handle_iter (dispatch_mask); - - while ((handle = handle_iter ()) != ACE_INVALID_HANDLE && - number_of_handlers_dispatched < number_of_active_handles) - { - ++number_of_handlers_dispatched; - - this->notify_handle (handle, - mask, - ready_mask, - this->handler_rep_.find (handle), - callback); - - // clear the bit from that dispatch mask, - // so when we need to restart the iteration (rebuilding the iterator...) - // we will not dispatch the already dispatched handlers - this->clear_dispatch_mask (handle, mask); - - if (this->state_changed_) - { - - handle_iter.reset_state (); - this->state_changed_ = false; - } - } - - return 0; -} - -template int -ACE_Select_Reactor_T::dispatch_io_handlers - (ACE_Select_Reactor_Handle_Set &dispatch_set, - int &number_of_active_handles, - int &number_of_handlers_dispatched) -{ - ACE_TRACE ("ACE_Select_Reactor_T::dispatch_io_handlers"); - - // Handle output events (this code needs to come first to handle the - // obscure case of piggy-backed data coming along with the final - // handshake message of a nonblocking connection). - - if (this->dispatch_io_set (number_of_active_handles, - number_of_handlers_dispatched, - ACE_Event_Handler::WRITE_MASK, - dispatch_set.wr_mask_, - this->ready_set_.wr_mask_, - &ACE_Event_Handler::handle_output) == -1) - { - number_of_active_handles -= number_of_handlers_dispatched; - return -1; - } - - // ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("ACE_Select_Reactor_T::dispatch - EXCEPT\n"))); - if (this->dispatch_io_set (number_of_active_handles, - number_of_handlers_dispatched, - ACE_Event_Handler::EXCEPT_MASK, - dispatch_set.ex_mask_, - this->ready_set_.ex_mask_, - &ACE_Event_Handler::handle_exception) == -1) - { - number_of_active_handles -= number_of_handlers_dispatched; - return -1; - } - - // ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("ACE_Select_Reactor_T::dispatch - READ\n"))); - if (this->dispatch_io_set (number_of_active_handles, - number_of_handlers_dispatched, - ACE_Event_Handler::READ_MASK, - dispatch_set.rd_mask_, - this->ready_set_.rd_mask_, - &ACE_Event_Handler::handle_input) == -1) - { - number_of_active_handles -= number_of_handlers_dispatched; - return -1; - } - - number_of_active_handles -= number_of_handlers_dispatched; - return 0; -} - -template int -ACE_Select_Reactor_T::dispatch - (int active_handle_count, - ACE_Select_Reactor_Handle_Set &dispatch_set) -{ - ACE_TRACE ("ACE_Select_Reactor_T::dispatch"); - - int io_handlers_dispatched = 0; - int other_handlers_dispatched = 0; - int signal_occurred = 0; - // The following do/while loop keeps dispatching as long as there - // are still active handles. Note that the only way we should ever - // iterate more than once through this loop is if signals occur - // while we're dispatching other handlers. - - do - { - // We expect that the loop will decrease the number of active - // handles in each iteration. If it does not, then something is - // inconsistent in the state of the Reactor and we should avoid - // the loop. Please read the comments on bug 2540 for more - // details. - int initial_handle_count = active_handle_count; - - // Note that we keep track of changes to our state. If any of - // the dispatch_*() methods below return -1 it means that the - // state has changed as the result of an - // being dispatched. This means that we - // need to bail out and rerun the select() loop since our - // existing notion of handles in may no longer be - // correct. - // - // In the beginning, our state starts out unchanged. After - // every iteration (i.e., due to signals), our state starts out - // unchanged again. - - this->state_changed_ = false; - - // Perform the Template Method for dispatching all the handlers. - - // First check for interrupts. - if (active_handle_count == -1) - { - // Bail out -- we got here since /. Pass over both the Event_Handler *and* the - * @a mask to allow the caller to dictate which - * method the will invoke. The ACE_Time_Value - * indicates how long to blocking trying to notify the - * . If @a timeout == 0, the caller will block until - * action is possible, else will wait until the relative time - * specified in *@a timeout elapses). - */ - virtual int notify (ACE_Event_Handler * = 0, - ACE_Reactor_Mask = ACE_Event_Handler::EXCEPT_MASK, - ACE_Time_Value * = 0); - - /** - * Set the maximum number of times that the - * method will iterate and - * dispatch the ACE_Event_Handlers that are passed in via the - * notify pipe before breaking out of its loop. By default, - * this is set to -1, which means "iterate until the pipe is empty." - * Setting this to a value like "1 or 2" will increase "fairness" - * (and thus prevent starvation) at the expense of slightly higher - * dispatching overhead. - */ - virtual void max_notify_iterations (int); - - /** - * Get the maximum number of times that the - * method will iterate and - * dispatch the ACE_Event_Handlers that are passed in via the - * notify pipe before breaking out of its loop. - */ - virtual int max_notify_iterations (void); - - /// Get the existing restart value. - virtual bool restart (void); - - /// Set a new value for restart and return the original value. - virtual bool restart (bool r); - - /// Set position that the main ACE_Select_Reactor thread is requeued in the - /// list of waiters during a callback. - virtual void requeue_position (int); - - /// Get position that the main ACE_Select_Reactor thread is requeued in the - /// list of waiters during a callback. - virtual int requeue_position (void); - - // = Low-level wait_set mask manipulation methods. - /// GET/SET/ADD/CLR the dispatch mask "bit" bound with the @a eh and - /// @a mask. - virtual int mask_ops (ACE_Event_Handler *eh, - ACE_Reactor_Mask mask, - int ops); - - /// GET/SET/ADD/CLR the dispatch MASK "bit" bound with the @a handle - /// and @a mask. - virtual int mask_ops (ACE_HANDLE handle, - ACE_Reactor_Mask mask, - int ops); - - // = Low-level ready_set mask manipulation methods. - /// GET/SET/ADD/CLR the ready "bit" bound with the @a eh and @a mask. - virtual int ready_ops (ACE_Event_Handler *eh, - ACE_Reactor_Mask mask, - int ops); - - /// GET/SET/ADD/CLR the ready "bit" bound with the @a handle and @a mask. - virtual int ready_ops (ACE_HANDLE handle, - ACE_Reactor_Mask, - int ops); - - /// Wake up all threads in waiting in the event loop - virtual void wakeup_all_threads (void); - - // = Only the owner thread can perform a . - - /// Set the new owner of the thread and return the old owner. - virtual int owner (ACE_thread_t n_id, ACE_thread_t *o_id = 0); - - /// Return the current owner of the thread. - virtual int owner (ACE_thread_t *); - - // = Miscellaneous Handler operations. - - /** - * Return the Event_Handler associated with @a handle. Return 0 if - * @a handle is not registered. - */ - virtual ACE_Event_Handler *find_handler (ACE_HANDLE handle); - - /** - * Check to see if @a handle is associated with a valid Event_Handler - * bound to @a mask. Return the @a eh associated with this @a handler - * if @a eh != 0. - */ - virtual int handler (ACE_HANDLE handle, - ACE_Reactor_Mask mask, - ACE_Event_Handler **eh = 0); - - /** - * Check to see if @a signum is associated with a valid Event_Handler - * bound to a signal. Return the @a eh associated with this - * handler if @a eh != 0. - */ - virtual int handler (int signum, - ACE_Event_Handler ** = 0); - - /// Returns true if we've been successfully initialized, else false. - virtual bool initialized (void); - - /// Returns the current size of the Reactor's internal descriptor - /// table. - virtual size_t size (void) const; - - /** - * Returns a reference to the ACE_Reactor_Token that is - * used to serialize the internal processing logic. - * This can be useful for situations where you need to avoid - * deadlock efficiently when ACE_Event_Handlers are used in - * multiple threads. - */ - virtual ACE_Lock &lock (void); - - /// Dump the state of an object. - virtual void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - // = Internal methods that do the actual work. - - // All of these methods assume that the token - // lock is held by the public methods that call down to them. - - /// Do the work of actually binding the @a handle and @a eh with the - /// @a mask. - virtual int register_handler_i (ACE_HANDLE handle, - ACE_Event_Handler *eh, - ACE_Reactor_Mask mask); - - /// Register a set of @a handles. - virtual int register_handler_i (const ACE_Handle_Set &handles, - ACE_Event_Handler *handler, - ACE_Reactor_Mask mask); - - /// Do the work of actually unbinding the @a handle and @a eh with the - /// @a mask. - virtual int remove_handler_i (ACE_HANDLE handle, - ACE_Reactor_Mask); - - /// Remove a set of @a handles. - virtual int remove_handler_i (const ACE_Handle_Set &handles, - ACE_Reactor_Mask); - - /// Suspend the associated with @a handle - virtual int suspend_i (ACE_HANDLE handle); - - /// Check to see if the associated with @a handle is - /// suspended. Returns 0 if not, 1 if so. - virtual int is_suspended_i (ACE_HANDLE handle); - - /// Resume the associated with @a handle - virtual int resume_i (ACE_HANDLE handle); - - /// Implement the public handler method. - virtual ACE_Event_Handler *find_handler_i (ACE_HANDLE handle); - - /// Implement the public handler method. - virtual int handler_i (ACE_HANDLE handle, - ACE_Reactor_Mask, - ACE_Event_Handler ** = 0); - - /// Implement the public handler method. - virtual int handler_i (int signum, ACE_Event_Handler ** = 0); - - /** - * Check if there are any HANDLEs enabled in the , and - * if so, update the @a handle_set and return the number ready. If - * there aren't any HANDLEs enabled return 0. - */ - virtual int any_ready (ACE_Select_Reactor_Handle_Set &handle_set); - - /// Implement the method, assuming that the Sig_Guard is - /// beign held - virtual int any_ready_i (ACE_Select_Reactor_Handle_Set &handle_set); - - /// Take corrective action when errors occur. - virtual int handle_error (void); - - /// Make sure the handles are all valid. - virtual int check_handles (void); - - /// Wait for events to occur. - virtual int wait_for_multiple_events (ACE_Select_Reactor_Handle_Set &, - ACE_Time_Value *); - - // = Dispatching methods. - - /** - * Template Method that dispatches ACE_Event_Handlers for time - * events, I/O events, and signal events. Returns the total number - * of ACE_Event_Handlers that were dispatched or -1 if something - * goes wrong. - */ - virtual int dispatch (int nfound, - ACE_Select_Reactor_Handle_Set &); - - /** - * Dispatch all timer handlers that have expired. Returns -1 if the - * state of the has changed, else 0. - * is set to the number of timer handlers - * dispatched. - */ - virtual int dispatch_timer_handlers (int &number_dispatched); - - /** - * Dispatch any notification handlers. Returns -1 if the state of - * the has changed, else returns number of handlers - * notified. - */ - virtual int dispatch_notification_handlers (ACE_Select_Reactor_Handle_Set &dispatch_set, - int &number_of_active_handles, - int &number_of_handlers_dispatched); - - /** - * Dispatch all the input/output/except handlers that are enabled in - * the @a dispatch_set. Updates @a number_of_active_handles and - * @a number_of_handlers_dispatched according to the behavior of the - * number Returns -1 if the state of the has changed, - * else 0. - */ - virtual int dispatch_io_handlers (ACE_Select_Reactor_Handle_Set &dispatch_set, - int &number_of_active_handles, - int &number_of_handlers_dispatched); - - /** - * Factors the dispatching of an io handle set (each WRITE, EXCEPT - * or READ set of handles). It updates the - * @a number_of_handlers_dispatched and invokes this->notify_handle - * for all the handles in using the @a mask, - * and @a callback parameters. Must return -1 if - * this->state_changed otherwise it must return 0. - */ - virtual int dispatch_io_set (int number_of_active_handles, - int &number_of_handlers_dispatched, - int mask, - ACE_Handle_Set& dispatch_mask, - ACE_Handle_Set& ready_mask, - ACE_EH_PTMF callback); - - /// Notify the appropriate @a callback in the context of the @a eh - /// associated with @a handle that a particular event has occurred. - virtual void notify_handle (ACE_HANDLE handle, - ACE_Reactor_Mask mask, - ACE_Handle_Set &, - ACE_Event_Handler *eh, - ACE_EH_PTMF callback); - - /// Enqueue ourselves into the list of waiting threads at the - /// appropriate point specified by . - virtual void renew (void); - - /// Synchronization token for the MT_SAFE ACE_Select_Reactor. - ACE_SELECT_REACTOR_TOKEN token_; - - /// Adapter used to return internal lock to outside world. - ACE_Lock_Adapter lock_adapter_; - - /// Release the token lock when a Win32 structured exception occurs. - int release_token (void); - - /// Stops the VC++ compiler from bitching about exceptions and destructors - int handle_events_i (ACE_Time_Value *max_wait_time = 0); - - /// This flag is used to keep track of whether we are actively handling - /// events or not. - sig_atomic_t deactivated_; - -private: - /// Deny access since member-wise won't work... - ACE_UNIMPLEMENTED_FUNC (ACE_Select_Reactor_T (const ACE_Select_Reactor_T &)) - ACE_UNIMPLEMENTED_FUNC (ACE_Select_Reactor_T &operator= (const ACE_Select_Reactor_T &) ) -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Select_Reactor_T.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Select_Reactor_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Select_Reactor_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" -#endif /* ACE_SELECT_REACTOR_T_H */ diff --git a/externals/ace/Select_Reactor_T.inl b/externals/ace/Select_Reactor_T.inl deleted file mode 100644 index 30c8cbc6b7d..00000000000 --- a/externals/ace/Select_Reactor_T.inl +++ /dev/null @@ -1,236 +0,0 @@ -// -*- C++ -*- -// -// $Id: Select_Reactor_T.inl 82723 2008-09-16 09:35:44Z johnnyw $ - -#include "ace/Reactor.h" -#include "ace/Signal.h" -#include "ace/Sig_Handler.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template -ACE_INLINE int -ACE_Select_Reactor_T::resume_handler (ACE_Event_Handler *h) -{ - ACE_TRACE ("ACE_Select_Reactor_T::resume_handler"); - return this->resume_handler (h->get_handle ()); -} - -template -ACE_INLINE int -ACE_Select_Reactor_T::resume_handler (const ACE_Handle_Set &handles) -{ - ACE_TRACE ("ACE_Select_Reactor_T::resume_handler"); - ACE_Handle_Set_Iterator handle_iter (handles); - ACE_HANDLE h; - - ACE_MT (ACE_GUARD_RETURN (ACE_SELECT_REACTOR_TOKEN, ace_mon, this->token_, -1)); - - while ((h = handle_iter ()) != ACE_INVALID_HANDLE) - if (this->resume_i (h) == -1) - return -1; - - return 0; -} - -template -ACE_INLINE int -ACE_Select_Reactor_T::suspend_handler (ACE_Event_Handler *h) -{ - ACE_TRACE ("ACE_Select_Reactor_T::suspend_handler"); - return this->suspend_handler (h->get_handle ()); -} - -template -ACE_INLINE int -ACE_Select_Reactor_T::suspend_handler (const ACE_Handle_Set &handles) -{ - ACE_TRACE ("ACE_Select_Reactor_T::suspend_handler"); - ACE_Handle_Set_Iterator handle_iter (handles); - ACE_HANDLE h; - - ACE_MT (ACE_GUARD_RETURN (ACE_SELECT_REACTOR_TOKEN, ace_mon, this->token_, -1)); - - while ((h = handle_iter ()) != ACE_INVALID_HANDLE) - if (this->suspend_i (h) == -1) - return -1; - - return 0; -} - -template -ACE_INLINE int -ACE_Select_Reactor_T::register_handler (int signum, - ACE_Event_Handler *new_sh, - ACE_Sig_Action *new_disp, - ACE_Event_Handler **old_sh, - ACE_Sig_Action *old_disp) -{ - ACE_TRACE ("ACE_Select_Reactor_T::register_handler"); - return this->signal_handler_->register_handler (signum, - new_sh, new_disp, - old_sh, old_disp); -} - -#if defined (ACE_WIN32) - -template -ACE_INLINE int -ACE_Select_Reactor_T::register_handler (ACE_Event_Handler *, - ACE_HANDLE ) -{ - // Don't have an implementation for this yet... - ACE_NOTSUP_RETURN (-1); -} - -#endif /* ACE_WIN32 */ - -template -ACE_INLINE int -ACE_Select_Reactor_T::register_handler (ACE_HANDLE , - ACE_HANDLE , - ACE_Event_Handler *, - ACE_Reactor_Mask ) -{ - // Don't have an implementation for this yet... - ACE_NOTSUP_RETURN (-1); -} - -template -ACE_INLINE int -ACE_Select_Reactor_T::handler (int signum, ACE_Event_Handler **handler) -{ - ACE_TRACE ("ACE_Select_Reactor_T::handler"); - return this->handler_i (signum, handler); -} - -template -ACE_INLINE int -ACE_Select_Reactor_T::remove_handler (int signum, - ACE_Sig_Action *new_disp, - ACE_Sig_Action *old_disp, - int sigkey) -{ - ACE_TRACE ("ACE_Select_Reactor_T::remove_handler"); - return this->signal_handler_->remove_handler (signum, new_disp, old_disp, sigkey); -} - -template -ACE_INLINE bool -ACE_Select_Reactor_T::uses_event_associations (void) -{ - // Since the Select_Reactor does not do any event associations, this - // function always return false. - return false; -} - -// = The remaining methods in this file must be called with locks -// held. - -// Performs operations on the "ready" bits. - -template ACE_INLINE int -ACE_Select_Reactor_T::ready_ops (ACE_Event_Handler *handler, - ACE_Reactor_Mask mask, - int ops) -{ - ACE_TRACE ("ACE_Select_Reactor_T::ready_ops"); - return this->ready_ops (handler->get_handle (), mask, ops); -} - -// Performs operations on the "dispatch" masks. - -template ACE_INLINE int -ACE_Select_Reactor_T::mask_ops (ACE_Event_Handler *handler, - ACE_Reactor_Mask mask, - int ops) -{ - ACE_TRACE ("ACE_Select_Reactor_T::mask_ops"); - return this->mask_ops (handler->get_handle (), mask, ops); -} - -template ACE_INLINE int -ACE_Select_Reactor_T::schedule_wakeup (ACE_Event_Handler *eh, - ACE_Reactor_Mask mask) -{ - ACE_TRACE ("ACE_Select_Reactor_T::schedule_wakeup"); - return this->mask_ops (eh->get_handle (), mask, ACE_Reactor::ADD_MASK); -} - -template ACE_INLINE int -ACE_Select_Reactor_T::cancel_wakeup (ACE_Event_Handler *eh, - ACE_Reactor_Mask mask) -{ - ACE_TRACE ("ACE_Select_Reactor_T::cancel_wakeup"); - return this->mask_ops (eh->get_handle (), mask, ACE_Reactor::CLR_MASK); -} - -template ACE_INLINE int -ACE_Select_Reactor_T::schedule_wakeup (ACE_HANDLE handle, - ACE_Reactor_Mask mask) -{ - ACE_TRACE ("ACE_Select_Reactor_T::schedule_wakeup"); - return this->mask_ops (handle, mask, ACE_Reactor::ADD_MASK); -} - -template ACE_INLINE int -ACE_Select_Reactor_T::cancel_wakeup (ACE_HANDLE handle, - ACE_Reactor_Mask mask) -{ - ACE_TRACE ("ACE_Select_Reactor_T::cancel_wakeup"); - return this->mask_ops (handle, mask, ACE_Reactor::CLR_MASK); -} - -template ACE_INLINE ACE_Lock & -ACE_Select_Reactor_T::lock (void) -{ - ACE_TRACE ("ACE_Select_Reactor_T::lock"); - return this->lock_adapter_; -} - -template ACE_INLINE void -ACE_Select_Reactor_T::wakeup_all_threads (void) -{ - // Send a notification, but don't block if there's no one to receive - // it. - this->notify (0, ACE_Event_Handler::NULL_MASK, (ACE_Time_Value *) &ACE_Time_Value::zero); -} - -template ACE_INLINE int -ACE_Select_Reactor_T::alertable_handle_events (ACE_Time_Value *max_wait_time) -{ - return this->handle_events (max_wait_time); -} - -template ACE_INLINE int -ACE_Select_Reactor_T::alertable_handle_events (ACE_Time_Value &max_wait_time) -{ - return this->handle_events (max_wait_time); -} - -template ACE_INLINE int -ACE_Select_Reactor_T::deactivated (void) -{ - return this->deactivated_; -} - -template ACE_INLINE void -ACE_Select_Reactor_T::deactivate (int do_stop) -{ - { - ACE_MT (ACE_GUARD (ACE_SELECT_REACTOR_TOKEN, - ace_mon, - this->token_)); - this->deactivated_ = do_stop; - } - - this->wakeup_all_threads (); -} - -template ACE_INLINE size_t -ACE_Select_Reactor_T::size (void) const -{ - return this->handler_rep_.size (); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Semaphore.cpp b/externals/ace/Semaphore.cpp deleted file mode 100644 index 2be156b8d7c..00000000000 --- a/externals/ace/Semaphore.cpp +++ /dev/null @@ -1,64 +0,0 @@ -// $Id: Semaphore.cpp 84282 2009-01-30 15:04:29Z msmit $ - -#include "ace/Semaphore.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Semaphore.inl" -#endif /* __ACE_INLINE__ */ - -#include "ace/Log_Msg.h" -#include "ace/ACE.h" - -ACE_RCSID (ace, - Semaphore, - "$Id: Semaphore.cpp 84282 2009-01-30 15:04:29Z msmit $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Semaphore) - -void -ACE_Semaphore::dump (void) const -{ -#if defined (ACE_HAS_DUMP) -// ACE_TRACE ("ACE_Semaphore::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n"))); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -ACE_Semaphore::ACE_Semaphore (unsigned int count, - int type, - const ACE_TCHAR *name, - void *arg, - int max) - : removed_ (false) -{ -// ACE_TRACE ("ACE_Semaphore::ACE_Semaphore"); -#if defined(ACE_LACKS_UNNAMED_SEMAPHORE) -// if the user does not provide a name, we generate a unique name here - ACE_TCHAR iname[ACE_UNIQUE_NAME_LEN]; - if (name == 0) - ACE::unique_name (this, iname, ACE_UNIQUE_NAME_LEN); - if (ACE_OS::sema_init (&this->semaphore_, count, type, - name ? name : iname, - arg, max) != 0) -#else - if (ACE_OS::sema_init (&this->semaphore_, count, type, - name, arg, max) != 0) -#endif - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_Semaphore::ACE_Semaphore"))); -} - -ACE_Semaphore::~ACE_Semaphore (void) -{ -// ACE_TRACE ("ACE_Semaphore::~ACE_Semaphore"); - - this->remove (); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Semaphore.h b/externals/ace/Semaphore.h deleted file mode 100644 index 7c4936abfd3..00000000000 --- a/externals/ace/Semaphore.h +++ /dev/null @@ -1,183 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file Semaphore.h - * - * $Id: Semaphore.h 81014 2008-03-19 11:41:31Z johnnyw $ - * - * Moved from Synch.h. - * - * @author Douglas C. Schmidt - */ -//========================================================================== - -#ifndef ACE_SEMAPHORE_H -#define ACE_SEMAPHORE_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/OS_NS_Thread.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -class ACE_Time_Value; - -/** - * @class ACE_Semaphore - * - * @brief Wrapper for Dijkstra style general semaphores. - */ -class ACE_Export ACE_Semaphore -{ -public: - // = Initialization and termination. - /// Initialize the semaphore, with initial value of "count". - ACE_Semaphore (unsigned int count = 1, // By default make this unlocked. - int type = USYNC_THREAD, - const ACE_TCHAR *name = 0, - void * = 0, - int max = 0x7fffffff); - - /// Implicitly destroy the semaphore. - ~ACE_Semaphore (void); - - /** - * Explicitly destroy the semaphore. Note that only one thread - * should call this method since it doesn't protect against race - * conditions. - */ - int remove (void); - - /// Block the thread until the semaphore count becomes - /// greater than 0, then decrement it. - int acquire (void); - - /** - * Block the thread until the semaphore count becomes greater than 0 - * (at which point it is decremented) or until @a tv times out (in - * which case -1 is returned and @c errno == @c ETIME). Note that @a tv - * is assumed to be in "absolute" rather than "relative" time. The - * value of @a tv is updated upon return to show the actual - * (absolute) acquisition time. - * - * @note Solaris threads do not support timed semaphores. - * Therefore, if you're running on Solaris you might want to - * consider using the ACE POSIX pthreads implementation instead, - * which can be enabled by compiling ACE with - * -DACE_HAS_PTHREADS, rather than -DACE_HAS_STHREADS or - * -DACE_HAS_POSIX_SEM. - */ - int acquire (ACE_Time_Value &tv); - - /** - * If @a tv == 0 then call directly. Otherwise, Block - * the thread until the semaphore count becomes greater than 0 - * (at which point it is decremented) or until @a tv times out (in - * which case -1 is returned and @c errno == @c ETIME). Note that - * <*tv> is assumed to be in "absolute" rather than "relative" time. - * The value of <*tv> is updated upon return to show the actual - * (absolute) acquisition time. - * - * @note Solaris threads do not support timed semaphores. - * Therefore, if you're running on Solaris you might want to - * consider using the ACE POSIX pthreads implementation instead, - * which can be enabled by compiling ACE with - * -DACE_HAS_PTHREADS, rather than -DACE_HAS_STHREADS or - * -DACE_HAS_POSIX_SEM. */ - int acquire (ACE_Time_Value *tv); - - /** - * Conditionally decrement the semaphore if count is greater than 0 - * (i.e., won't block). Returns -1 on failure. If we "failed" - * because someone else already had the lock, @c errno is set to - * @c EBUSY. - */ - int tryacquire (void); - - /// Increment the semaphore by 1, potentially unblocking a waiting - /// thread. - int release (void); - - /// Increment the semaphore by @a release_count, potentially - /// unblocking waiting threads. - int release (unsigned int release_count); - - /** - * Acquire semaphore ownership. This calls and is only - * here to make the ACE_Semaphore interface consistent with the - * other synchronization APIs. - */ - int acquire_read (void); - - /** - * Acquire semaphore ownership. This calls and is only - * here to make the ACE_Semaphore interface consistent with the - * other synchronization APIs. - */ - int acquire_write (void); - - /** - * Conditionally acquire semaphore (i.e., won't block). This calls - * and is only here to make the ACE_Semaphore - * interface consistent with the other synchronization APIs. - * Returns -1 on failure. If we "failed" because someone else - * already had the lock, @c errno is set to @c EBUSY. - */ - int tryacquire_read (void); - - /** - * Conditionally acquire semaphore (i.e., won't block). This calls - * and is only here to make the ACE_Semaphore - * interface consistent with the other synchronization APIs. - * Returns -1 on failure. If we "failed" because someone else - * already had the lock, @c errno is set to @c EBUSY. - */ - int tryacquire_write (void); - - /** - * This is only here to make the ACE_Semaphore - * interface consistent with the other synchronization APIs. - * Assumes the caller has already acquired the semaphore using one of - * the above calls, and returns 0 (success) always. - */ - int tryacquire_write_upgrade (void); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - - /// Return the underlying lock. - const ACE_sema_t &lock (void) const; - -protected: - ACE_sema_t semaphore_; - - /// Keeps track of whether remove() has been called yet to avoid - /// multiple remove() calls, e.g., explicitly and implicitly in the - /// destructor. This flag isn't protected by a lock, so make sure - /// that you don't have multiple threads simultaneously calling - /// remove () on the same object, which is a bad idea anyway... - bool removed_; - -private: - // = Prevent assignment and initialization. - void operator= (const ACE_Semaphore &); - ACE_Semaphore (const ACE_Semaphore &); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Semaphore.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_SEMAPHORE_H */ diff --git a/externals/ace/Semaphore.inl b/externals/ace/Semaphore.inl deleted file mode 100644 index e0162dc247b..00000000000 --- a/externals/ace/Semaphore.inl +++ /dev/null @@ -1,119 +0,0 @@ -// -*- C++ -*- -// -// $Id: Semaphore.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE const ACE_sema_t & -ACE_Semaphore::lock (void) const -{ -// ACE_TRACE ("ACE_Semaphore::lock"); - return this->semaphore_; -} - -ACE_INLINE int -ACE_Semaphore::remove (void) -{ -// ACE_TRACE ("ACE_Semaphore::remove"); - int result = 0; - if (!this->removed_) - { - this->removed_ = true; - result = ACE_OS::sema_destroy (&this->semaphore_); - } - return result; -} - -ACE_INLINE int -ACE_Semaphore::acquire (void) -{ -// ACE_TRACE ("ACE_Semaphore::acquire"); - return ACE_OS::sema_wait (&this->semaphore_); -} - -ACE_INLINE int -ACE_Semaphore::acquire (ACE_Time_Value &tv) -{ -// ACE_TRACE ("ACE_Semaphore::acquire"); - return ACE_OS::sema_wait (&this->semaphore_, tv); -} - -ACE_INLINE int -ACE_Semaphore::acquire (ACE_Time_Value *tv) -{ -// ACE_TRACE ("ACE_Semaphore::acquire"); - return ACE_OS::sema_wait (&this->semaphore_, tv); -} - -ACE_INLINE int -ACE_Semaphore::tryacquire (void) -{ -// ACE_TRACE ("ACE_Semaphore::tryacquire"); - return ACE_OS::sema_trywait (&this->semaphore_); -} - -ACE_INLINE int -ACE_Semaphore::release (void) -{ -// ACE_TRACE ("ACE_Semaphore::release"); - return ACE_OS::sema_post (&this->semaphore_); -} - -ACE_INLINE int -ACE_Semaphore::release (unsigned int release_count) -{ -// ACE_TRACE ("ACE_Semaphore::release"); - return ACE_OS::sema_post (&this->semaphore_, release_count); -} - -// Acquire semaphore ownership. This calls and is only -// here to make the interface consistent with the -// other synchronization APIs. - -ACE_INLINE int -ACE_Semaphore::acquire_read (void) -{ - return this->acquire (); -} - -// Acquire semaphore ownership. This calls and is only -// here to make the interface consistent with the -// other synchronization APIs. - -ACE_INLINE int -ACE_Semaphore::acquire_write (void) -{ - return this->acquire (); -} - -// Conditionally acquire semaphore (i.e., won't block). This calls -// and is only here to make the -// interface consistent with the other synchronization APIs. - -ACE_INLINE int -ACE_Semaphore::tryacquire_read (void) -{ - return this->tryacquire (); -} - -// Conditionally acquire semaphore (i.e., won't block). This calls -// and is only here to make the -// interface consistent with the other synchronization APIs. - -ACE_INLINE int -ACE_Semaphore::tryacquire_write (void) -{ - return this->tryacquire (); -} - -// This is only here to make the interface consistent -// with the other synchronization APIs. Assumes the caller has -// already acquired the semaphore using one of the above calls, and -// returns 0 (success) always. -ACE_INLINE int -ACE_Semaphore::tryacquire_write_upgrade (void) -{ - return 0; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Service_Config.cpp b/externals/ace/Service_Config.cpp deleted file mode 100644 index b1ec0329eb5..00000000000 --- a/externals/ace/Service_Config.cpp +++ /dev/null @@ -1,610 +0,0 @@ -// $Id: Service_Config.cpp 84619 2009-02-26 12:26:16Z johnnyw $ - -#include "ace/Service_Config.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Service_Config.inl" -#endif /* __ACE_INLINE__ */ - -#include "ace/Service_Types.h" -#include "ace/Reactor.h" -#include "ace/Singleton.h" -#include "ace/Service_Repository.h" - -#ifndef ACE_LACKS_UNIX_SIGNALS -# include "ace/Sig_Adapter.h" -#endif /* !ACE_LACKS_UNIX_SIGNALS */ - -#include "ace/OS_NS_time.h" -#include "ace/OS_NS_stdio.h" -#include "ace/OS_NS_unistd.h" -#include "ace/Thread.h" -#include "ace/Get_Opt.h" -#include "ace/ARGV.h" -#include "ace/Log_Msg.h" -#include "ace/ACE.h" - -ACE_RCSID (ace, - Service_Config, - "$Id: Service_Config.cpp 84619 2009-02-26 12:26:16Z johnnyw $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_Threading_Helper::~ACE_Threading_Helper () -{ - ACE_OS::thr_key_detach (this->key_, 0); - ACE_OS::thr_keyfree (this->key_); -} - -ACE_Threading_Helper::ACE_Threading_Helper () - : key_ (ACE_OS::NULL_key) -{ -# if defined (ACE_HAS_TSS_EMULATION) - ACE_Object_Manager::init_tss (); -# endif - - if (ACE_Thread::keycreate (&key_, 0, 0) == -1) - { - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("(%P|%t) Failed to create thread key: %p\n"), - ACE_TEXT (""))); - } -} - -void -ACE_Threading_Helper::set (void* p) -{ - if (ACE_Thread::setspecific (key_, p) == -1) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("(%P|%t) Service Config failed to set thread key value: %p\n"), - ACE_TEXT(""))); -} - -void* -ACE_Threading_Helper::get (void) -{ - void* temp = 0; - if (ACE_Thread::getspecific (key_, &temp) == -1) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("(%P|%t) Service Config failed to get thread key value: %p\n"), - ACE_TEXT("")), - 0); - return temp; -} - -ACE_Threading_Helper::~ACE_Threading_Helper () -{ -} - -ACE_Threading_Helper::ACE_Threading_Helper () -{ -} - -void -ACE_Threading_Helper::set (void*) -{ -} - -void* -ACE_Threading_Helper::get (void) -{ - return ACE_Service_Config::singleton()->instance_.get (); -} - -/** - * @c ACE_Service_Config is supposed to be a Singleton. This is the - * only Configuration Gestalt available for access from static - * initializers at proces start-up time. Using Unmanaged Singleton - * is safer because (a) the Object Manager may not yet be fully initialized - * in the context of a static initializer that uses SC, and (b) because we - * know that upon process exit the SC will still be automaticaly and explicitly - * closed by @c ACE_Object_Manager::fini(). - */ -typedef ACE_Unmanaged_Singleton ACE_SERVICE_CONFIG_SINGLETON; - - -/// ctor -ACE_Service_Config_Guard::ACE_Service_Config_Guard (ACE_Service_Gestalt * psg) - : saved_ (ACE_Service_Config::current ()) -{ - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) - SCG:") - ACE_TEXT (" - config=%@ repo=%@ superceded by repo=%@\n"), - this, - this->saved_.get (), - this->saved_->repo_, - psg->repo_)); - - // Modify the TSS if the repo has changed - ACE_Service_Config::current (psg); -} - -ACE_Service_Config_Guard::~ACE_Service_Config_Guard (void) -{ - ACE_Service_Gestalt* s = this->saved_.get (); - ACE_ASSERT (s != 0); - - ACE_Service_Config::current (s); - - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) SCG:") - ACE_TEXT (" - new repo=%@\n"), - this, - this->saved_->repo_)); -} - - -ACE_ALLOC_HOOK_DEFINE (ACE_Service_Config) - -// Set the signal handler to point to the handle_signal() function. -ACE_Sig_Adapter *ACE_Service_Config::signal_handler_ = 0; - -// Trigger a reconfiguration. -sig_atomic_t ACE_Service_Config::reconfig_occurred_ = 0; - -// = Set by command-line options. - -/// Pathname of file to write process id. -ACE_TCHAR *ACE_Service_Config::pid_file_name_ = 0; - -/// Shall we become a daemon process? -bool ACE_Service_Config::be_a_daemon_ = false; - -/// Number of the signal used to trigger reconfiguration. -int ACE_Service_Config::signum_ = SIGHUP; - -void -ACE_Service_Config::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Service_Config::dump"); -#endif /* ACE_HAS_DUMP */ -} - -int -ACE_Service_Config::parse_args_i (int argc, ACE_TCHAR *argv[]) -{ - ACE_TRACE ("ACE_Service_Config::parse_args_i"); - - // Using PERMUTE_ARGS (default) in order to have all - // unrecognized options and their value arguments moved - // to the end of the argument vector. We'll pick them up - // after processing our options and pass them on to the - // base class for further parsing. - //FUZZ: disable check_for_lack_ACE_OS - ACE_Get_Opt getopt (argc, - argv, - ACE_TEXT ("bs:p:"), - 1 , // Start at argv[1]. - 0, // Do not report errors - ACE_Get_Opt::RETURN_IN_ORDER); - //FUZZ: enable check_for_lack_ACE_OS - - //FUZZ: disable check_for_lack_ACE_OS - for (int c; (c = getopt ()) != -1; ) - //FUZZ: enable check_for_lack_ACE_OS - switch (c) - { - case 'p': - ACE_Service_Config::pid_file_name_ = getopt.opt_arg (); - break; - case 'b': - ACE_Service_Config::be_a_daemon_ = true; - break; - case 's': - { - // There's no point in dealing with this on NT since it - // doesn't really support signals very well... -#if !defined (ACE_LACKS_UNIX_SIGNALS) - ACE_Service_Config::signum_ = - ACE_OS::atoi (getopt.opt_arg ()); - - if (ACE_Reactor::instance ()->register_handler - (ACE_Service_Config::signum_, - ACE_Service_Config::signal_handler_) == -1) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("cannot obtain signal handler\n")), - -1); -#endif /* ACE_LACKS_UNIX_SIGNALS */ - break; - } - default:; // unknown arguments are benign - - } - - return 0; -} /* parse_args_i () */ - - -int -ACE_Service_Config::open_i (const ACE_TCHAR program_name[], - const ACE_TCHAR *logger_key, - bool , - bool , - bool ) -{ - ACE_TRACE ("ACE_Service_Config::open_i"); - ACE_MT (ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, ace_mon, this->lock_, -1)); - - ACE_Log_Msg *log_msg = ACE_LOG_MSG; - - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) SC::open_i - this=%@, opened=%d\n"), - this, this->is_opened_)); - - // Guard against reentrant processing. - if (this->is_opened_) - return 0; - - this->is_opened_ = true; - - // Check for things we need to do on a per-process basis and which - // may not be safe, or wise to do an a per instance basis - - // Become a daemon before doing anything else. - if (ACE_Service_Config::be_a_daemon_) - ACE::daemonize (); - - // Write process id to file. - if (this->pid_file_name_ != 0) - { - FILE* pidf = ACE_OS::fopen (this->pid_file_name_, - ACE_TEXT("w")); - - if (pidf != 0) - { - ACE_OS::fprintf (pidf, - "%ld\n", - static_cast (ACE_OS::getpid())); - ACE_OS::fclose (pidf); - } - } - - u_long flags = log_msg->flags (); - - // Only use STDERR if the caller hasn't already set the flags. - if (flags == 0) - flags = (u_long) ACE_Log_Msg::STDERR; - - const ACE_TCHAR *key = logger_key; - - if (key == 0 || ACE_OS::strcmp (key, ACE_DEFAULT_LOGGER_KEY) == 0) - { - // Only use the static if the caller doesn't - // override it in the parameter list or if the key supplied is - // equal to the default static logger key. - key = ACE_Service_Config::current()->logger_key_; - } - else - { - ACE_SET_BITS (flags, ACE_Log_Msg::LOGGER); - } - - if (log_msg->open (program_name, - flags, - key) == -1) - return -1; - - if (ACE::debug ()) - ACE_DEBUG ((LM_STARTUP, - ACE_TEXT ("starting up daemon %n\n"))); - - // Initialize the Service Repository (this will still work if - // user forgets to define an object of type ACE_Service_Config). - ACE_Service_Repository::instance (ACE_Service_Gestalt::MAX_SERVICES); - - // Initialize the ACE_Reactor (the ACE_Reactor should be the - // same size as the ACE_Service_Repository). - ACE_Reactor::instance (); - - // There's no point in dealing with this on NT since it doesn't - // really support signals very well... -#if !defined (ACE_LACKS_UNIX_SIGNALS) - // Only attempt to register a signal handler for positive - // signal numbers. - if (ACE_Service_Config::signum_ > 0) - { - ACE_Sig_Set ss; - ss.sig_add (ACE_Service_Config::signum_); - if ((ACE_Reactor::instance () != 0) && - (ACE_Reactor::instance ()->register_handler - (ss, ACE_Service_Config::signal_handler_) == -1)) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("can't register signal handler\n"))); - } -#endif /* ACE_LACKS_UNIX_SIGNALS */ - - return 0; -} - -/// Return the global configuration instance. Always returns the same -/// instance -ACE_Service_Config * -ACE_Service_Config::singleton (void) -{ - return ACE_SERVICE_CONFIG_SINGLETON::instance (); -} - -int -ACE_Service_Config::insert (ACE_Static_Svc_Descriptor* stsd) -{ - return ACE_Service_Config::instance ()->insert (stsd); -} - - -// Totally remove from the daemon by removing it from the -// ACE_Reactor, and unlinking it if necessary. -int -ACE_Service_Config::remove (const ACE_TCHAR svc_name[]) -{ - ACE_TRACE ("ACE_Service_Config::remove"); - return ACE_Service_Repository::instance ()->remove (svc_name); -} - -// Suspend . Note that this will not unlink the service -// from the daemon if it was dynamically linked, it will mark it as -// being suspended in the Service Repository and call the -// member function on the appropriate . A service -// can be resumed later on by calling the method... - -int -ACE_Service_Config::suspend (const ACE_TCHAR svc_name[]) -{ - ACE_TRACE ("ACE_Service_Config::suspend"); - return ACE_Service_Repository::instance ()->suspend (svc_name); -} - -// Resume a SVC_NAME that was previously suspended or has not yet -// been resumed (e.g., a static service). - -int -ACE_Service_Config::resume (const ACE_TCHAR svc_name[]) -{ - ACE_TRACE ("ACE_Service_Config::resume"); - return ACE_Service_Repository::instance ()->resume (svc_name); -} - - -ACE_Service_Config::ACE_Service_Config (bool ignore_static_svcs, - size_t size, - int signum) -{ - ACE_TRACE ("ACE_Service_Config::ACE_Service_Config"); - - // TODO: Need to find a more customizable way of instantiating the - // gestalt but perhaps we should leave this out untill such - // customizations are identified. - ACE_Service_Gestalt* tmp = 0; - ACE_NEW_NORETURN (tmp, - ACE_Service_Gestalt (size, false, ignore_static_svcs)); - - this->is_opened_ = false; - this->instance_ = tmp; - this->threadkey_.set (tmp); - - ACE_Service_Config::signum_ = signum; -} - -ACE_Service_Config::ACE_Service_Config (const ACE_TCHAR program_name[], - const ACE_TCHAR *logger_key) -{ - ACE_TRACE ("ACE_Service_Config::ACE_Service_Config"); - - // TODO: Need to find a more customizable way of instantiating the - // gestalt but perhaps we should leave this out untill such - // customizations are identified. - ACE_Service_Gestalt* tmp = 0; - ACE_NEW_NORETURN (tmp, - ACE_Service_Gestalt (ACE_Service_Repository::DEFAULT_SIZE, false)); - - this->is_opened_ = false; - this->instance_ = tmp; - this->threadkey_.set (tmp); - - if (this->open (program_name, - logger_key) == -1 && errno != ENOENT) - { - // Only print out an error if it wasn't the svc.conf file that was - // missing. - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("(%P|%t) SC failed to open: %p\n"), - program_name)); - } -} - -/// Return the "global" configuration instance, for the current -/// thread. This may be the same as instance(), but on some occasions, -/// it may be a different one. For example, ACE_Service_Config_Guard -/// provides a way of temporarily replacing the "current" -/// configuration instance in the context of a thread. -ACE_Service_Gestalt* -ACE_Service_Config::current (void) -{ - void* temp = ACE_Service_Config::singleton()->threadkey_.get (); - if (temp == 0) { - - // The most likely reason is that the current thread was spawned - // by some native primitive, like pthreads or Windows API - not - // from ACE. This is perfectly legal for callers who are not, or - // do not need to be ACE-aware. Such callers must have no - // expectation that the pluggable, multi-context configuration - // support will work - they would always get the global context, - // because at this point there is no information what the "parent" - // thread's configuration context was. - - temp = global(); - singleton()->threadkey_.set (temp); - } - - return static_cast (temp); -} - -/// A mutator to set the "current" (TSS) gestalt instance. -void -ACE_Service_Config::current (ACE_Service_Gestalt* newcurrent) -{ - ACE_Service_Config::singleton()->threadkey_.set (newcurrent); -} - - - -#if (ACE_USES_CLASSIC_SVC_CONF == 0) -ACE_Service_Type * -ACE_Service_Config::create_service_type (const ACE_TCHAR *n, - ACE_Service_Type_Impl *o, - ACE_DLL &dll, - int active) -{ - ACE_Service_Type *sp = 0; - ACE_NEW_RETURN (sp, - ACE_Service_Type (n, o, dll, active), - 0); - return sp; -} -#endif /* ACE_USES_CLASSIC_SVC_CONF == 0 */ - -ACE_Service_Type_Impl * -ACE_Service_Config::create_service_type_impl (const ACE_TCHAR *name, - int type, - void *symbol, - u_int flags, - ACE_Service_Object_Exterminator gobbler) -{ - ACE_Service_Type_Impl *stp = 0; - - // Note, the only place we need to put a case statement. This is - // also the place where we'd put the RTTI tests, if the compiler - // actually supported them! - - switch (type) - { - case ACE_Service_Type::SERVICE_OBJECT: - ACE_NEW_RETURN (stp, - ACE_Service_Object_Type ((ACE_Service_Object *) symbol, - name, flags, - gobbler), - 0); - break; - case ACE_Service_Type::MODULE: - ACE_NEW_RETURN (stp, - ACE_Module_Type (symbol, name, flags), - 0); - break; - case ACE_Service_Type::STREAM: - ACE_NEW_RETURN (stp, - ACE_Stream_Type (symbol, name, flags), - 0); - break; - default: - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("unknown case\n"))); - break; - } - return stp; - -} - - -// Signal handling API to trigger dynamic reconfiguration. -void -ACE_Service_Config::handle_signal (int sig, - siginfo_t *, - ucontext_t *) -{ -#if defined (ACE_NDEBUG) - ACE_UNUSED_ARG (sig); -#else /* ! ACE_NDEBUG */ - ACE_ASSERT (ACE_Service_Config::signum_ == sig); -#endif /* ! ACE_NDEBUG */ - - ACE_Service_Config::reconfig_occurred_ = 1; -} - -// Trigger reconfiguration to re-read configuration files. -void -ACE_Service_Config::reconfigure (void) -{ - ACE_TRACE ("ACE_Service_Config::reconfigure"); - - ACE_Service_Config::reconfig_occurred_ = 0; - - if (ACE::debug ()) - { -#if !defined (ACE_NLOGGING) - time_t t = ACE_OS::time (0); -#endif /* ! ACE_NLOGGING */ - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("beginning reconfiguration at %s"), - ACE_OS::ctime (&t))); - } - if (ACE_Service_Config::process_directives () == -1) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("process_directives"))); -} - -// Tidy up and perform last rites on a terminating ACE_Service_Config. -int -ACE_Service_Config::close (void) -{ - ACE_Service_Config::singleton ()->instance_->close (); - - // Delete the service repository. All the objects inside the - // service repository should already have been finalized. - ACE_Service_Repository::close_singleton (); - - // Do away with the singleton ACE_Service_Config (calls dtor) - ACE_SERVICE_CONFIG_SINGLETON::close (); - - return 0; -} - - -int -ACE_Service_Config::fini_svcs (void) -{ - ACE_TRACE ("ACE_Service_Config::fini_svcs"); - - // Clear the LM_DEBUG bit from log messages if appropriate - if (ACE::debug ()) - ACE_Log_Msg::disable_debug_messages (); - - int result = 0; - if (ACE_Service_Repository::instance () != 0) - result = ACE_Service_Repository::instance ()->fini (); - - if (ACE::debug ()) - ACE_Log_Msg::enable_debug_messages (); - - return result; -} - -/// Perform user-specified close activities and remove dynamic memory. -ACE_Service_Config::~ACE_Service_Config (void) -{ - ACE_TRACE ("ACE_Service_Config::~ACE_Service_Config"); -} - -// ************************************************************ - -/* static */ -int -ACE_Service_Config::reconfig_occurred (void) -{ - ACE_TRACE ("ACE_Service_Config::reconfig_occurred"); - return ACE_Service_Config::reconfig_occurred_ != 0; -} - -void -ACE_Service_Config::reconfig_occurred (int config_occurred) -{ - ACE_TRACE ("ACE_Service_Config::reconfig_occurred"); - ACE_Service_Config::reconfig_occurred_ = config_occurred; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Service_Config.h b/externals/ace/Service_Config.h deleted file mode 100644 index 5269d8f367e..00000000000 --- a/externals/ace/Service_Config.h +++ /dev/null @@ -1,692 +0,0 @@ -// -*- C++ -*- - -//==================================================================== -/** - * @file Service_Config.h - * - * $Id: Service_Config.h 89501 2010-03-17 08:59:56Z vzykov $ - * - * @author Douglas C. Schmidt - */ -//==================================================================== - -#ifndef ACE_SERVICE_CONFIG_H -#define ACE_SERVICE_CONFIG_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" -#include "ace/Default_Constants.h" -#include "ace/Intrusive_Auto_Ptr.h" -#include "ace/Service_Gestalt.h" -#include "ace/Synch_Traits.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/OS_NS_signal.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Forward decl. -class ACE_Service_Object; -class ACE_Service_Type; -class ACE_Service_Type_Impl; -class ACE_Service_Repository; -class ACE_Sig_Adapter; -class ACE_Allocator; -class ACE_Reactor; -class ACE_Thread_Manager; -class ACE_DLL; - -#if (ACE_USES_CLASSIC_SVC_CONF == 1) -#define ACE_STATIC_SERVICE_DIRECTIVE(ident, parameters) \ - ACE_TEXT ("static ") \ - ACE_TEXT (ident) \ - ACE_TEXT (" \"") \ - ACE_TEXT (parameters) \ - ACE_TEXT ("\"") -#define ACE_DYNAMIC_SERVICE_DIRECTIVE(ident, libpathname, objectclass, parameters) \ - ACE_TEXT ("dynamic ") \ - ACE_TEXT (ident) \ - ACE_TEXT (" Service_Object * ") \ - ACE_TEXT (libpathname) \ - ACE_TEXT (":") \ - ACE_TEXT (objectclass) \ - ACE_TEXT ("() \"") \ - ACE_TEXT (parameters) \ - ACE_TEXT ("\"") -#define ACE_REMOVE_SERVICE_DIRECTIVE(ident) \ - ACE_TEXT ("remove ") \ - ACE_TEXT (ident) -class ACE_Svc_Conf_Param; -#else -#define ACE_STATIC_SERVICE_DIRECTIVE(ident, parameters) \ - ACE_TEXT ("") -#define ACE_DYNAMIC_SERVICE_DIRECTIVE(ident, libpathname, objectclass, parameters) \ - ACE_TEXT ("") \ - ACE_TEXT ("") -#define ACE_REMOVE_SERVICE_DIRECTIVE(ident) \ - ACE_TEXT ("") -class ACE_XML_Svc_Conf; -#endif /* ACE_USES_CLASSIC_SVC_CONF == 1 */ - -ACE_END_VERSIONED_NAMESPACE_DECL - -extern "C" -{ - typedef ACE_Service_Object *(*ACE_SERVICE_ALLOCATOR) (ACE_Service_Object_Exterminator *); -} - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Static_Svc_Descriptor - * - * @brief Holds the information necessary to describe a statically linked - * Svc. - */ -class ACE_Static_Svc_Descriptor -{ -public: - /// Name of the service. - const ACE_TCHAR *name_; - - /// Type of service. - int type_; - - /// Factory function that allocates the service. - ACE_SERVICE_ALLOCATOR alloc_; - - /// Bitmask flags indicating how the framework should delete memory. - u_int flags_; - - /// Flag indicating whether the service starts out active. - int active_; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -public: - /// Compare two service descriptors for equality. - bool operator== (ACE_Static_Svc_Descriptor &) const; - - /// Compare two service descriptors for inequality. - bool operator!= (ACE_Static_Svc_Descriptor &) const; -}; - - -/** - * @class ACE_Threading_Helper - * - * @brief Encapsulates responsibility for allocating, destroying and - * manipulating the value, associated with a thread-specific - * key. Relates to the ability of the created thread to inherit the - * parent thread's gestalt. Designed to be used as an instance member - * of @c ACE_Service_Config. - * - * Partial specialization over ACE_SYNCH_MUTEX is used to implement - * specific behavior in both multi- and single-threaded builds. - */ -template -class ACE_Threading_Helper -{ -}; - -/* - * Specialization for a multi threaded program - */ -template<> -class ACE_Export ACE_Threading_Helper -{ -public: - ACE_Threading_Helper (); - ~ACE_Threading_Helper (); - - void set (void*); - void* get (void); - -private: - /// Key for the thread-specific data, which is a simple pointer to - /// the thread's (currently-) global configuration context. - ACE_thread_key_t key_; -}; - -/* - * Specialization for a single threaded program - */ -template<> -class ACE_Export ACE_Threading_Helper -{ -public: - ACE_Threading_Helper (); - ~ACE_Threading_Helper (); - - void set (void*); - void* get (void); -}; - -#define ACE_Component_Config ACE_Service_Config - -/** - * @class ACE_Service_Config - * - * @brief Supplies common server operations for dynamic and static - * configuration of service. - * - * The ACE_Service_Config uses the Monostate pattern. Therefore, - * you can only have one of these instantiated per-process. It - * represents the process-wide collection of services, which is - * typicaly shared among all other configurable entities. The only - * ACE_Service_Config instance is registered with and owned by the - * ACE_Object_Manager. - * - * By contrast, the ACE_Service_Gestalt represents the collection - * of services, pertaining to a configurable entity. Typicaly, a - * "configurable entity" is an instance, which owns an instance of - * ACE_Service_Gestalt in order to ensure full controll over the - * services it needs. - * - * Another facet of ACE_Service_Config is that for a given thread, - * it provides access to its current, process-global - * ACE_Service_Gestalt instance through its curent() method. - * - * @note The signal_handler_ static member is allocated by the - * ACE_Object_Manager. The ACE_Service_Config constructor - * uses signal_handler_. Therefore, if the program has any - * static ACE_Service_Config objects, there might be - * initialization order problems. They can be minimized, but - * not eliminated, by _not_ #defining - * ACE_HAS_NONSTATIC_OBJECT_MANAGER. - */ -class ACE_Export ACE_Service_Config -{ - - /// The Instance, or the global (default) configuration context. - /// The monostate would forward the calls to that instance. The TSS - /// will point here - ACE_Intrusive_Auto_Ptr instance_; - - /// A helper instance to manage thread-specific key creation. - /// Dependent on the syncronization mutex ACE uses, the corresponding - /// partial template instantiation will perform the right services - /// that have to do with managing thread-specific storage. Note that, - /// for single-threaded builds they would do (next to) nothing. - ACE_Threading_Helper threadkey_; - -public: - - // = Initialization and termination methods. - - /** - * Initialize the Service Repository. Note that initialising @a - * signum to a negative number will prevent a signal handler being - * registered when the repository is opened. - */ - ACE_Service_Config (bool ignore_static_svcs = true, - size_t size = ACE_DEFAULT_SERVICE_REPOSITORY_SIZE, - int signum = SIGHUP); - - /** - * Performs an open without parsing command-line arguments. The - * @a logger_key indicates where to write the logging output, which - * is typically either a STREAM pipe or a socket address. - */ - ACE_Service_Config (const ACE_TCHAR program_name[], - const ACE_TCHAR *logger_key = ACE_DEFAULT_LOGGER_KEY); - - /// Perform user-specified close activities and remove dynamic - /// memory. - virtual ~ACE_Service_Config (void); - -private: - - /** - * Performs an open without parsing command-line arguments. - * Implements whats different in the opening sequence - * for this class, as opposed to the base class. - * - * The @a logger_key indicates where to write the logging output, which - * is typically either a STREAM pipe or a socket address. If - * @a ignore_default_svc_conf_file is non-0 then the "svc.conf" file - * will be ignored. If @a ignore_debug_flag is non-0 then the - * application is responsible for setting the - * @c ACE_Log_Msg::priority_mask() appropriately. Returns number of - * errors that occurred on failure and 0 otherwise. - */ - virtual int open_i (const ACE_TCHAR program_name[], - const ACE_TCHAR *logger_key, - bool ignore_static_svcs, - bool ignore_default_svc_conf_file, - bool ignore_debug_flag); - - /** - * Implements whats different in the command line parameter processing - * for this class, as opposed to the base class. - */ - virtual int parse_args_i (int argc, ACE_TCHAR *argv[]); - - /// = Static interfaces - - public: - /** - * Returns the process-wide global singleton instance. It would - * have been created and will be managed by the Object Manager. - */ - static ACE_Service_Config* singleton (void); - - /** - * Mutator for the currently active configuration context instance - * (gestalt). Intended for use by helper classes like @see - * ACE_Service_Config_Guard. Stack-based instances can be used to - * temporarily change which gestalt is seen as global by static - * initializers (especially those in DLLs loaded at run-time). - */ - static void current (ACE_Service_Gestalt*); - - /** - * Accessor for the "current" service gestalt - */ - static ACE_Service_Gestalt* current (void); - - /** - * This is what the static service initializators are hard-wired to - * use, so in order to avoid interface changes this method merely - * forwards to @c ACE_Service_Config::current. This enables us to - * enforce which Service Gestalt is used for services registering - * through static initializers. Especially important for DLL-based - * dynamic services, which can contain their own static services and - * static initializers. - * - * @deprecated Use current() instead. - */ - static ACE_Service_Gestalt* instance (void); - - /** - * Returns a process-wide global singleton instance in contrast with - * current (), which may return a different instance at different - * times, dependent on the context. Modifying this method's return - * value is strongly discouraged as it will circumvent the mechanism - * for dynamically loading services. If you must, use with extreme - * caution! - */ - static ACE_Service_Gestalt* global (void); - - /** - * Performs an open without parsing command-line arguments. The - * @a logger_key indicates where to write the logging output, which - * is typically either a STREAM pipe or a socket address. If - * @a ignore_static_svcs is true then static services are not loaded, - * otherwise, they are loaded. If @a ignore_default_svc_conf_file is - * non-0 then the configuration file will be ignored. - * Returns zero upon success, -1 if the file is not found or cannot - * be opened (errno is set accordingly), otherwise returns the - * number of errors encountered loading the services in the - * specified svc.conf configuration file. If @a ignore_debug_flag is - * non-0 then the application is responsible for setting the - * @c ACE_Log_Msg::priority_mask appropriately. - */ - static int open (const ACE_TCHAR program_name[], - const ACE_TCHAR *logger_key = ACE_DEFAULT_LOGGER_KEY, - bool ignore_static_svcs = true, - bool ignore_default_svc_conf_file = false, - bool ignore_debug_flag = false); - - /** - * This is the primary entry point into the ACE_Service_Config (the - * constructor just handles simple initializations). It parses - * arguments passed in from @a argc and @a argv parameters. The - * arguments that are valid in a call to this method include: - * - * - '-b' Option to indicate that we should be a daemon. Note that when - * this option is used, the process will be daemonized before the - * service configuration file(s) are read. During daemonization, - * (on POSIX systems) the current directory will be changed to "/" - * so the caller should either fully specify the file names, or - * execute a @c chroot() to the appropriate directory. - * @sa ACE::daemonize(). - * - '-d' Turn on debugging mode - * - '-f' Specifies a configuration file name other than the default - * svc.conf. Can be specified multiple times to use multiple files. - * If any configuration file is provided with this option then - * the default svc.conf will be ignored. - * - '-k' Specifies the rendezvous point to use for the ACE distributed - * logger. - * - '-y' Explicitly enables the use of static services. This flag - * overrides the @a ignore_static_svcs parameter value. - * - '-n' Explicitly disables the use of static services. This flag - * overrides the @a ignore_static_svcs parameter value. - * - '-p' Specifies a pathname which is used to store the process id. - * - '-s' Specifies a signal number other than SIGHUP to trigger reprocessing - * of the configuration file(s). Ignored for platforms that do not - * have POSIX signals, such as Windows. - * - '-S' Specifies a service directive string. Enclose the string in quotes - * and escape any embedded quotes with a backslash. This option - * specifies service directives without the need for a configuration - * file. Can be specified multiple times. - * - * Note: Options '-f' and '-S' complement each other. Directives from files - * and from '-S' option are processed together in the following order. First, - * all files are processed in the order they are specified in @a argv - * parameter. Second, all directive strings are executed in the order the - * directives appear in @a argv parameter. - * - * @param argc The number of commandline arguments. - * @param argv The array with commandline arguments - * @param logger_key Indicates where to write the logging output, - * which is typically either a STREAM pipe or a - * socket address. - * @param ignore_static_svcs If true then static services are not loaded, - * otherwise, they are loaded. - * @param ignore_default_svc_conf_file If non-0 then the @c svc.conf - * configuration file will be ignored. - * @param ignore_debug_flag If true then the application is responsible - * for setting the @c ACE_Log_Msg::priority_mask - * appropriately. - * - * @retval -1 The configuration file is not found or cannot - * be opened (errno is set accordingly). - * @retval 0 Success. - * @retval >0 The number of errors encountered while processing - * the service configuration file(s). - */ - static int open (int argc, - ACE_TCHAR *argv[], - const ACE_TCHAR *logger_key = ACE_DEFAULT_LOGGER_KEY, - bool ignore_static_svcs = true, - bool ignore_default_svc_conf_file = false, - bool ignore_debug_flag = false); - - /// Tidy up and perform last rites when ACE_Service_Config is shut - /// down. This method calls close_svcs(). Returns 0. - static int close (void); - - /// Perform user-specified close hooks and possibly delete all of the - /// configured services in the . - static int fini_svcs (void); - - /// True if reconfiguration occurred. - static int reconfig_occurred (void); - - /// Indicate that reconfiguration occurred. - static void reconfig_occurred (int); - - /// Perform the reconfiguration process. - static void reconfigure (void); - - // = The following methods are static in order to enforce Singleton - // semantics for the Reactor, Service_Repository, Thread_Manager, - // and Acceptor/Connector Strategy factory. Other portions of the - // system may need to access them at some point or another... - - // = This is not strictly needed, anymore since the service configurator - // has been refactored to allow multiple service configuration - // instances (called gestalts). The interfaces, however were retained in for - // the sake of maintaining source-code compatibility. - - - // = Accessors and mutators for process-wide Singletons. - - /// Returns a pointer to the list of statically linked services. - /// - /// @deprecated - Same as instance(), but still useful in legacy code, - /// (notably, one that can not be easily modified) which uses the following - /// idiom for registering static services: - /// - /// ACE_Service_Config::static_svcs ()->insert (...); - static ACE_Service_Gestalt* static_svcs (void); - - /// Insert a static service descriptor for processing on open_i(). The - /// corresponding ACE_STATIC_SVC_* macros were chaged to use this method - /// instead of obtaining a ptr to a container. See the note on static_svcs(). - /// Added to prevent exposing the internal storage representation of the - /// services repository and provide a better way of debugging service - /// loading and registration problems. - static int insert (ACE_Static_Svc_Descriptor *svc); - - // = Utility methods. - /// Dynamically link the shared object file and retrieve a pointer to - /// the designated shared object in this file. - static int initialize (const ACE_Service_Type *, - const ACE_TCHAR *parameters); - - /// Initialize and activate a statically @a svc_name service. - static int initialize (const ACE_TCHAR *svc_name, - const ACE_TCHAR *parameters); - - /// Resume a @a svc_name that was previously suspended or has not yet - /// been resumed (e.g., a static service). - static int resume (const ACE_TCHAR svc_name[]); - - /** - * Suspend @a svc_name. Note that this will not unlink the service - * from the daemon if it was dynamically linked, it will mark it as - * being suspended in the Service Repository and call the - * member function on the appropriate ACE_Service_Object. A - * service can be resumed later on by calling the member - * function... - */ - static int suspend (const ACE_TCHAR svc_name[]); - - /// Totally remove @a svc_name from the daemon by removing it - /// from the ACE_Reactor, and unlinking it if necessary. - static int remove (const ACE_TCHAR svc_name[]); - -#if defined (ACE_HAS_WINCE) && defined (ACE_USES_WCHAR) - // We must provide these function to bridge the Svc_Conf parser - // with ACE. - static int initialize (const ACE_Service_Type *, ACE_ANTI_TCHAR []); - static int initialize (const char svc_name[], ACE_ANTI_TCHAR parameters[]); - static int resume (const ACE_ANTI_TCHAR svc_name[]); - static int suspend (const ACE_ANTI_TCHAR svc_name[]); - static int remove (const ACE_ANTI_TCHAR svc_name[]); -#endif /* ACE_HAS_WINCE */ - - /// Dump the state of an object. - void dump (void) const; - - /// Set the signal_handler;for internal use by ACE_Object_Manager only. - static ACE_INLINE void signal_handler (ACE_Sig_Adapter *); - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - - /// Process a file containing a list of service configuration - /// directives. - static int process_file (const ACE_TCHAR file[]); - - /// Process one service configuration @a directive, which is passed as - /// a string. Returns the number of errors that occurred. - static int process_directive (const ACE_TCHAR directive[]); - - /** - * Process one static service definition. Load a new static service - * into the ACE_Service_Repository. - * - * @param ssd Service descriptor, see the document of - * ACE_Static_Svc_Descriptor for more details. - * - * @param force_replace If set the new service descriptor replaces - * any previous instance in the ACE_Service_Repository. - * - * @return Returns -1 if the service cannot be 'loaded'. - */ - static int process_directive (const ACE_Static_Svc_Descriptor &ssd, - bool force_replace = false); - - /** - * Process (or re-process) service configuration requests that are - * provided in the svc.conf file(s). Returns the number of errors - * that occurred. - */ - static int process_directives (void); - - /// Handles signals to trigger reconfigurations. - static void handle_signal (int sig, siginfo_t *, ucontext_t *); - - /** - * Handle the command-line options intended for the - * ACE_Service_Config. Note that @c argv[0] is assumed to be the - * program name. - * The arguments that are valid in a call to this method are - * - '-b' Option to indicate that we should be a daemon - * - '-d' Turn on debugging mode - * - '-f' Option to read in the list of svc.conf file names - * - '-k' Option to read a wide string where in the logger output can - * be written - * - '-y' Turn on the flag for a repository of statically - * linked services - * - '-n' Need not have a repository of statically linked services - * - '-S' Option to read in the list of services on the command-line - * Please observe the difference between options '-f' that looks - * for a list of files and here a list of services. - */ - static int parse_args (int, ACE_TCHAR *argv[]); - -#if (ACE_USES_CLASSIC_SVC_CONF == 0) - static ACE_Service_Type *create_service_type (const ACE_TCHAR *n, - ACE_Service_Type_Impl *o, - ACE_DLL &dll, - int active); -#endif /* ACE_USES_CLASSIC_SVC_CONF == 0 */ - - static ACE_Service_Type_Impl * - create_service_type_impl (const ACE_TCHAR *name, - int type, - void *symbol, - u_int flags, - ACE_Service_Object_Exterminator gobbler); - - /// @deprecated - /// Process service configuration requests that were provided on the - /// command-line. Returns the number of errors that occurred. - static int process_commandline_directives (void); - - /// Become a daemon. - static int start_daemon (void); - - // @deprecated - // Add the default statically-linked services to the - // ACE_Service_Repository. - static int load_static_svcs (void); - -protected: - -#if (ACE_USES_CLASSIC_SVC_CONF == 1) - /// @deprecated - /// This is the implementation function that process_directives() - /// and process_directive() both call. Returns the number of errors - /// that occurred. - static int process_directives_i (ACE_Svc_Conf_Param *param); -#endif /* ACE_USES_CLASSIC_SVC_CONF == 1 */ - - - // = Process-wide state. - -private: - - /// Have we called ACE_Service_Config::open() yet? - bool is_opened_; - -#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) - /// Synchronization variable for open, etc. - mutable ACE_SYNCH_MUTEX lock_; -#endif /* ACE_MT_SAFE */ - - /// True if reconfiguration occurred. - static sig_atomic_t reconfig_occurred_; - - // = Set by command-line options. - /// Shall we become a daemon process? - static bool be_a_daemon_; - - /// Pathname of file to write process id. - static ACE_TCHAR *pid_file_name_; - - /// Number of the signal used to trigger reconfiguration. - static int signum_; - - /// Handles the reconfiguration signals. - static ACE_Sig_Adapter *signal_handler_; - - /// Pointer to the Singleton (ACE_Cleanup) Gestalt instance. - /// There is thread-specific global instance pointer, which is used to - /// temporarily change which Gestalt instance is used for static service - /// registrations. - /// - /// A specific use case is a thread, which loads a _dynamic_ service from - /// a DLL. If the said DLL also contains additional _static_ services, - /// those *must* be registered with the same configuration repository as - /// the dynamic service. Otherwise, the DLL's static services would be - /// registered with the global Gestalt and may outlive the DLL that - /// contains their code and perhaps the memory in which they are in. - /// This is a problem because if the DLL gets unloaded (as it will, if - /// it was loaded in an instance of Gestalt), the DLL's memory will be - /// deallocated, but the global service repository will still "think" - /// it must finalize the (DLL's) static services - with disastrous - /// consequences, occurring in the post-main code (at_exit()). - - /// This class needs the intimate access to be able to swap the - /// current TSS pointer for the global Gestalt. - friend class ACE_Service_Config_Guard; - - /// The helper needs intimate access (when building with no threads) - friend class ACE_Threading_Helper ; - friend class ACE_Threading_Helper ; -}; - -/** - * @class ACE_Service_Config_Guard - * - * @brief A guard class, designed to be instantiated on the stack. - * - * Instantiating it with a specific configuration ensures any references to - * ACE_Service_Config::instance(), even when occuring in static constructors, - * will allways access the designated configuration instance. - * This comes very handy when a dynamic service also registers any static - * services of its own and their static factories. - */ -class ACE_Export ACE_Service_Config_Guard -{ -public: - ACE_Service_Config_Guard (ACE_Service_Gestalt* psg); - ~ACE_Service_Config_Guard (void); - -private: - // Private AND not implemented to disable copying - ACE_Service_Config_Guard(const ACE_Service_Config_Guard&); - ACE_Service_Config_Guard& operator= (const ACE_Service_Config_Guard&); - -private: - ACE_Intrusive_Auto_Ptr saved_; -}; - - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Service_Config.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" - -#endif /* ACE_SERVICE_CONFIG_H */ diff --git a/externals/ace/Service_Config.inl b/externals/ace/Service_Config.inl deleted file mode 100644 index 35be0e84db9..00000000000 --- a/externals/ace/Service_Config.inl +++ /dev/null @@ -1,208 +0,0 @@ -// -*- C++ -*- -// -// $Id: Service_Config.inl 83302 2008-10-16 19:28:11Z mesnier_p $ - -#include "ace/OS_NS_string.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// This is the primary entry point into the ACE_Service_Config (the -// constructor just handles simple initializations). -ACE_INLINE int -ACE_Service_Config::open (const ACE_TCHAR program_name[], - const ACE_TCHAR *logger_key, - bool ignore_static_svcs, - bool ignore_default_svc_conf, - bool ignore_debug_flag) -{ - ACE_TRACE ("ACE_Service_Config::open"); - if (singleton()->open_i (program_name, - logger_key, - ignore_static_svcs, - ignore_default_svc_conf, - ignore_debug_flag) == -1) - return -1; - - return current()->open (program_name, - logger_key, - ignore_static_svcs, - ignore_default_svc_conf, - ignore_debug_flag); -} - - -ACE_INLINE int -ACE_Service_Config::open (int argc, - ACE_TCHAR *argv[], - const ACE_TCHAR *logger_key, - bool ignore_static_svcs, - bool ignore_default_svc_conf, - bool ignore_debug_flag) -{ - ACE_TRACE ("ACE_Service_Config::open"); - - if (singleton()->parse_args_i(argc, argv) == -1) - return -1; - - if (singleton()->open_i (argv[0], - logger_key, - ignore_static_svcs, - ignore_default_svc_conf, - ignore_debug_flag) == -1) - return -1; - - return current()->open (argc, - argv, - logger_key, - ignore_static_svcs, - ignore_default_svc_conf, - ignore_debug_flag); -} - -// Handle the command-line options intended for the -// ACE_Service_Config. -ACE_INLINE int -ACE_Service_Config::parse_args (int argc, ACE_TCHAR *argv[]) -{ - return ACE_Service_Config::current ()->parse_args (argc, argv); -} - -/// Return the global configuration instance. Allways returns the same -/// instance -ACE_INLINE ACE_Service_Gestalt * -ACE_Service_Config::global (void) -{ - return ACE_Service_Config::singleton()->instance_.get (); -} - -/// Return the configuration instance, considered "global" in the -/// current thread. This may be the same as instance(), but on some -/// occasions, it may be a different one. For example, -/// ACE_Service_Config_Guard provides a way of temporarily replacing -/// the "current" configuration instance in the context of a thread. -ACE_INLINE ACE_Service_Gestalt * -ACE_Service_Config::instance (void) -{ - return ACE_Service_Config::current (); -} - -// This method has changed to return the gestalt instead of the -// container, underlying the service repository and defined -// ACE_Service_Gestalt::insert (ACE_Static_Svc_Descriptor*). This way -// the existing source code can keep using -// ACE_Service_Config::static_svcs(), however now it is not necessary -// to expose the repository storage *and* it is much easier to debug -// service registration problems. - -ACE_INLINE ACE_Service_Gestalt* -ACE_Service_Config::static_svcs (void) -{ - return ACE_Service_Config::current (); -} - -/// Compare two service descriptors for equality. -ACE_INLINE bool -ACE_Static_Svc_Descriptor::operator== (ACE_Static_Svc_Descriptor &d) const -{ - return ACE_OS::strcmp (name_, d.name_) == 0; -} - -/// Compare two service descriptors for inequality. -ACE_INLINE bool -ACE_Static_Svc_Descriptor::operator!= (ACE_Static_Svc_Descriptor &d) const -{ - return !(*this == d); -} - -ACE_INLINE void -ACE_Service_Config::signal_handler (ACE_Sig_Adapter *signal_handler) -{ - signal_handler_ = signal_handler; -} - -/// Initialize and activate a statically linked service. -ACE_INLINE int -ACE_Service_Config::initialize (const ACE_TCHAR *svc_name, - const ACE_TCHAR *parameters) -{ - ACE_TRACE ("ACE_Service_Config::initialize"); - return ACE_Service_Config::current ()->initialize (svc_name, - parameters); -} - -/// Dynamically link the shared object file and retrieve a pointer to -/// the designated shared object in this file. -ACE_INLINE int -ACE_Service_Config::initialize (const ACE_Service_Type *sr, - const ACE_TCHAR *parameters) -{ - ACE_TRACE ("ACE_Service_Config::initialize"); - return ACE_Service_Config::current ()->initialize (sr, parameters); -} - -/// Process a file containing a list of service configuration -/// directives. -ACE_INLINE int ACE_Service_Config::process_file (const ACE_TCHAR file[]) -{ - return ACE_Service_Config::current ()->process_file (file); -} - -/// -ACE_INLINE int -ACE_Service_Config::process_directive (const ACE_TCHAR directive[]) -{ - return ACE_Service_Config::current ()->process_directive (directive); -} - -/// Process service configuration requests as indicated in the queue of -/// svc.conf files. -ACE_INLINE int -ACE_Service_Config::process_directives (void) -{ - return ACE_Service_Config::current ()->process_directives (false); -} - -ACE_INLINE int -ACE_Service_Config::process_directive (const ACE_Static_Svc_Descriptor &ssd, - bool force_replace) -{ - return ACE_Service_Config::current ()->process_directive (ssd, force_replace); -} - - -#if defined (ACE_HAS_WINCE) && defined (ACE_USES_WCHAR) -// We must provide these function to bridge Svc_Conf parser with ACE. - -ACE_INLINE int -ACE_Service_Config::initialize (const ACE_Service_Type *sp, ACE_ANTI_TCHAR parameters[]) -{ - return ACE_Service_Config::initialize (sp, ACE_TEXT_ANTI_TO_TCHAR (parameters)); -} - -ACE_INLINE int -ACE_Service_Config::initialize (const ACE_ANTI_TCHAR svc_name[], ACE_ANTI_TCHAR parameters[]) -{ - return ACE_Service_Config::initialize (ACE_TEXT_ANTI_TO_TCHAR (svc_name), - ACE_TEXT_ANTI_TO_TCHAR (parameters)); -} - -ACE_INLINE int -ACE_Service_Config::resume (const ACE_ANTI_TCHAR svc_name[]) -{ - return ACE_Service_Config::resume (ACE_TEXT_ANTI_TO_TCHAR (svc_name)); -} - -ACE_INLINE int -ACE_Service_Config::suspend (const ACE_ANTI_TCHAR svc_name[]) -{ - return ACE_Service_Config::suspend (ACE_TEXT_ANTI_TO_TCHAR (svc_name)); -} - -ACE_INLINE int -ACE_Service_Config::remove (const ACE_ANTI_TCHAR svc_name[]) -{ - return ACE_Service_Config::remove (ACE_TEXT_ANTI_TO_TCHAR (svc_name)); -} -#endif /* ACE_HAS_WINCE && !ACE_USES_WCHAR */ - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Service_Gestalt.cpp b/externals/ace/Service_Gestalt.cpp deleted file mode 100644 index 47ea3d1e81b..00000000000 --- a/externals/ace/Service_Gestalt.cpp +++ /dev/null @@ -1,1327 +0,0 @@ -// $Id: Service_Gestalt.cpp 91158 2010-07-21 15:54:12Z mesnier_p $ - -#include "ace/Svc_Conf.h" -#include "ace/Get_Opt.h" -#include "ace/ARGV.h" -#include "ace/Malloc.h" -#include "ace/Service_Manager.h" -#include "ace/Service_Types.h" -#include "ace/Containers.h" -#include "ace/Auto_Ptr.h" -#include "ace/Reactor.h" -#include "ace/Thread_Manager.h" -#include "ace/DLL.h" -#include "ace/XML_Svc_Conf.h" -#include "ace/SString.h" - -#ifndef ACE_LACKS_UNIX_SIGNALS -# include "ace/Signal.h" -#endif /* !ACE_LACKS_UNIX_SIGNALS */ - -#include "ace/OS_NS_stdio.h" -#include "ace/OS_NS_string.h" -#include "ace/OS_NS_time.h" -#include "ace/OS_NS_unistd.h" -#include "ace/OS_NS_sys_stat.h" - -#include "ace/TSS_T.h" -#include "ace/Service_Gestalt.h" - -#include "ace/Svc_Conf_Param.h" - -ACE_RCSID (ace, - Service_Gestalt, - "$Id: Service_Gestalt.cpp 91158 2010-07-21 15:54:12Z mesnier_p $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_Service_Type_Dynamic_Guard::ACE_Service_Type_Dynamic_Guard - (ACE_Service_Repository &r, const ACE_TCHAR *name) - : repo_ (r) - // Relocation starts where the next service will be inserted (if any) - , repo_begin_ (r.current_size ()) - , name_ (name) -# if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) - // On this thread (for the duration of the initialize() method), - // we're about to do two things that require locking: (1) fiddle - // with the repository and (2) load a DLL and hence lock the - // DLL_Manager. - // - // Now if we don't lock the repo here, it is possible that two - // threads may deadlock on initialization because they can acquire - // locks (1) and (2) in different order, for instance: - // - // T1: loads a DLL (2) and registers a service (1); - // - // T2: may be relocating a service (1), which could lead to a - // (re)opening or uping the ref count on a DLL (2); - // - // To prevent this, we lock the repo here, using the repo_monitor_ - // member guard. - , repo_monitor_ (r.lock_) -#endif -{ - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) STDG::, repo=%@") - ACE_TEXT(", name=%s - begining at [%d]\n"), - &this->repo_, - this->name_, - this->repo_begin_)); - - ACE_ASSERT (this->name_ != 0); // No name? -} - - -/// Destructor -ACE_Service_Type_Dynamic_Guard::~ACE_Service_Type_Dynamic_Guard (void) -{ - const ACE_Service_Type *tmp = 0; - - // Lookup without ignoring suspended services. Making sure - // not to ignore any inactive services, since those may be forward - // declarations - size_t slot = 0; - int const ret = this->repo_.find_i (this->name_, slot, &tmp, false); - - // We inserted it (as inactive), so we expect to find it, right? - if ((ret < 0 && ret != -2) || tmp == 0) - { - if (ACE::debug ()) - ACE_ERROR ((LM_WARNING, - ACE_TEXT ("ACE (%P|%t) STDG:: - Failed (%d) to find %s -> %@\n"), - ret, this->name_, tmp)); - return; - } - - if (tmp->type () != 0) - { - // Something has registered a proper (non-forward-decl) service with - // the same name as our dummy. - - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) STDG::, repo=%@ [%d], ") - ACE_TEXT ("name=%s - updating dependents [%d - %d)\n"), - &this->repo_, - slot, - this->name_, - this->repo_begin_, - this->repo_.current_size ())); - - // Relocate any services inserted since we were created. - // Any (static, i.e. DLL = 0) services registered in - // the context of this guard aren't really static because - // their code belongs in the DLL's code segment - this->repo_.relocate_i (this->repo_begin_, this->repo_.current_size (), tmp->dll()); - - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) STDG::, repo=%@ [%d], ") - ACE_TEXT ("name=%s - loaded (type=%@, impl=%@, object=%@, active=%d)\n"), - &this->repo_, - slot, - this->name_, - tmp, - tmp->type (), - tmp->type ()->object (), - tmp->active ())); - } -} - - - -// ---------------------------------------- - -ACE_Service_Gestalt::Processed_Static_Svc:: -Processed_Static_Svc (const ACE_Static_Svc_Descriptor *assd) - :name_(0), - assd_(assd) -{ - ACE_NEW_NORETURN (name_, ACE_TCHAR[ACE_OS::strlen(assd->name_)+1]); - ACE_OS::strcpy(name_,assd->name_); -} - -ACE_Service_Gestalt::Processed_Static_Svc::~Processed_Static_Svc (void) -{ - delete [] name_; -} - -void -ACE_Service_Gestalt::intrusive_add_ref (ACE_Service_Gestalt* g) -{ - if (g != 0) - { - ++g->refcnt_; - ACE_ASSERT (g->refcnt_ > 0); - } -} - -void -ACE_Service_Gestalt::intrusive_remove_ref (ACE_Service_Gestalt* g) -{ - if (g != 0) - { - long tmp = --g->refcnt_; - if (tmp <= 0) delete g; - ACE_ASSERT (tmp >= 0); - } -} - - -ACE_Service_Gestalt::~ACE_Service_Gestalt (void) -{ - - if (this->svc_repo_is_owned_) - delete this->repo_; - - this->repo_ =0; - - delete this->static_svcs_; - this->static_svcs_ = 0; - - // Delete the dynamically allocated static_svcs instance. -#ifndef ACE_NLOGGING - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) SG::~SG - this=%@, pss = %@\n"), - this, this->processed_static_svcs_)); -#endif - - if (this->processed_static_svcs_ && - !this->processed_static_svcs_->is_empty()) - { - Processed_Static_Svc **pss = 0; - for (ACE_PROCESSED_STATIC_SVCS_ITERATOR iter (*this->processed_static_svcs_); - iter.next (pss) != 0; - iter.advance ()) - { - delete *pss; - } - } - - delete this->processed_static_svcs_; - this->processed_static_svcs_ = 0; - - delete this->svc_conf_file_queue_; - this->svc_conf_file_queue_ = 0; -} - -ACE_Service_Gestalt::ACE_Service_Gestalt (size_t size, - bool svc_repo_is_owned, - bool no_static_svcs) - : svc_repo_is_owned_ (svc_repo_is_owned) - , svc_repo_size_ (size) - , is_opened_ (0) - , logger_key_ (ACE_DEFAULT_LOGGER_KEY) - , no_static_svcs_ (no_static_svcs) - , svc_queue_ (0) - , svc_conf_file_queue_ (0) - , repo_ (0) - , static_svcs_ (0) - , processed_static_svcs_ (0) - , refcnt_ (0) -{ - (void)this->init_i (); - -#ifndef ACE_NLOGGING - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) SG::ctor - this = %@, pss = %@\n"), - this, this->processed_static_svcs_)); -#endif -} - -/// Performs the common initialization tasks for a new or previously -/// closed instance. Must not be virtual, as it is also called from -/// the constructor. -int -ACE_Service_Gestalt::init_i (void) -{ - // Only initialize the repo_ if (a) we are being constructed, or; - // (b) we're being open()-ed, perhaps after previously having been - // close()-ed. In both cases: repo_ == 0 and we need a repository. - if (this->repo_ == 0) - { - if (this->svc_repo_is_owned_) - { - ACE_NEW_RETURN (this->repo_, - ACE_Service_Repository (this->svc_repo_size_), - -1); - } - else - { - this->repo_ = - ACE_Service_Repository::instance (this->svc_repo_size_); - } - } - - if (init_svc_conf_file_queue () == -1) - return -1; - - return 0; -} - - -/// Add the default statically-linked services to the Service -/// Repository. -int -ACE_Service_Gestalt::load_static_svcs (void) -{ - ACE_TRACE ("ACE_Service_Gestalt::load_static_svcs"); - - if (this->static_svcs_ == 0) - return 0; // Nothing to do - - ACE_Static_Svc_Descriptor **ssdp = 0; - for (ACE_STATIC_SVCS_ITERATOR iter (*this->static_svcs_); - iter.next (ssdp) != 0; - iter.advance ()) - { - ACE_Static_Svc_Descriptor *ssd = *ssdp; - - if (this->process_directive (*ssd, 1) == -1) - return -1; - } - return 0; - -} /* load_static_svcs () */ - - - -/// Find a static service descriptor by name -int -ACE_Service_Gestalt::find_static_svc_descriptor (const ACE_TCHAR* name, - ACE_Static_Svc_Descriptor **ssd) const -{ - ACE_TRACE ("ACE_Service_Gestalt::find_static_svc_descriptor"); - - if (this->static_svcs_ == 0) - return -1; - - ACE_Static_Svc_Descriptor **ssdp = 0; - for (ACE_STATIC_SVCS_ITERATOR iter ( *this->static_svcs_); - iter.next (ssdp) != 0; - iter.advance ()) - { - if (ACE_OS::strcmp ((*ssdp)->name_, name) == 0) - { - if (ssd != 0) - *ssd = *ssdp; - - return 0; - } - } - - return -1; -} - -/// @brief -const ACE_Static_Svc_Descriptor* -ACE_Service_Gestalt::find_processed_static_svc (const ACE_TCHAR* name) -{ - if (this->processed_static_svcs_ == 0 || name == 0) - return 0; - - Processed_Static_Svc **pss = 0; - for (ACE_PROCESSED_STATIC_SVCS_ITERATOR iter (*this->processed_static_svcs_); - iter.next (pss) != 0; - iter.advance ()) - { - if (ACE_OS::strcmp ((*pss)->name_, name) == 0) - return (*pss)->assd_; - } - return 0; -} - - - -/// @brief Captures a list of the direcives processed (explicitely) for this -/// Gestalt so that services can be replicated in other repositories -/// upon their first initialization. -/// -/// This is part of the mechanism ensuring distinct local instances -/// for static service objects, loaded in another repository. -void -ACE_Service_Gestalt::add_processed_static_svc - (const ACE_Static_Svc_Descriptor *assd) -{ - - /// When process_directive(Static_Svc_Descriptor&) is called, it - /// associates a service object with the Gestalt and makes the - /// resource (a Service Object) local to the repository. This is but - /// the first step in using such SO. The next is the - /// "initialization" step. It is typicaly done through a "static" - /// service configuration directive. - /// - /// In contrast a "dynamic" directive, when processed through the - /// overloaded process_directives(string) both creates the SO - /// locally and initializes it, where the statics directive must - /// first locate the SO and then calls the init() method. This means - /// that durig the "static" initialization there's no specific - /// information about the hosting repository and the gestalt must - /// employ some lookup strategy to find it elsewhere. - - if (this->processed_static_svcs_ == 0) - ACE_NEW (this->processed_static_svcs_, - ACE_PROCESSED_STATIC_SVCS); - - Processed_Static_Svc **pss = 0; - for (ACE_PROCESSED_STATIC_SVCS_ITERATOR iter (*this->processed_static_svcs_); - iter.next (pss) != 0; - iter.advance ()) - { - if (ACE_OS::strcmp ((*pss)->name_, assd->name_) == 0) - { - (*pss)->assd_ = assd; - return; - } - } - Processed_Static_Svc *tmp = 0; - ACE_NEW (tmp,Processed_Static_Svc(assd)); - this->processed_static_svcs_->insert(tmp); - - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) SG::add_processed_static_svc, ") - ACE_TEXT ("repo=%@ - %s\n"), - this->repo_, - assd->name_)); -} - - -/// Queues a static service object descriptor which, during open() -/// will be given to process_directive() to create the Service -/// Object. Normally, only called from static initializers, prior to -/// calling open() but loading a service from a DLL can cause it too. - -int -ACE_Service_Gestalt::insert (ACE_Static_Svc_Descriptor *stsd) -{ - if (this->static_svcs_ == 0) - ACE_NEW_RETURN (this->static_svcs_, - ACE_STATIC_SVCS, - -1); - - return this->static_svcs_->insert (stsd); -} - - -ACE_ALLOC_HOOK_DEFINE (ACE_Service_Gestalt) - - -void -ACE_Service_Gestalt::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Service_Gestalt::dump"); -#endif /* ACE_HAS_DUMP */ -} - -int -ACE_Service_Gestalt::initialize (const ACE_TCHAR *svc_name, - const ACE_TCHAR *parameters) -{ - ACE_TRACE ("ACE_Service_Gestalt_Base::initialize (repo)"); - ACE_ARGV args (parameters); - -#ifndef ACE_NLOGGING - if (ACE::debug ()) - { - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) SG::initialize - () repo=%@, ") - ACE_TEXT ("looking up static ") - ACE_TEXT ("service \'%s\' to initialize\n"), - this->repo_, - svc_name)); - } -#endif - - const ACE_Service_Type *srp = 0; - for (int i = 0; this->find (svc_name, &srp) == -1 && i < 2; i++) - // if (this->repo_->find (svc_name, &srp) == -1) - { - const ACE_Static_Svc_Descriptor *assd = - ACE_Service_Config::global()->find_processed_static_svc(svc_name); - if (assd != 0) - { - this->process_directive_i(*assd, 0); - } - else - { - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("ACE (%P|%t) ERROR: SG::initialize - service \'%s\'") - ACE_TEXT (" was not located.\n"), - svc_name), - -1); - } - } - if (srp == 0) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("ACE (%P|%t) ERROR: SG::initialize - service \'%s\'") - ACE_TEXT (" was not located.\n"), - svc_name), - -1); - - /// If initialization fails ... - if (srp->type ()->init (args.argc (), - args.argv ()) == -1) - { - // ... report and remove this entry. - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("ACE (%P|%t) ERROR: SG::initialize - static init of \'%s\'") - ACE_TEXT (" failed (%p)\n"), - svc_name, ACE_TEXT ("error"))); - this->repo_->remove (svc_name); - return -1; - } - - // If everything is ok, activate it - const_cast(srp)->active (1); - return 0; -} - - -#if (ACE_USES_CLASSIC_SVC_CONF == 1) -int -ACE_Service_Gestalt::initialize (const ACE_Service_Type_Factory *stf, - const ACE_TCHAR *parameters) -{ - ACE_TRACE ("ACE_Service_Gestalt::initialize"); - -#ifndef ACE_NLOGGING - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) SG::initialize - repo=%@, name=%s") - ACE_TEXT (" - looking up in the repo\n"), - this->repo_, - stf->name ())); -#endif - - ACE_Service_Type *srp = 0; - int const retv = this->repo_->find (stf->name (), - (const ACE_Service_Type **) &srp); - - // If there is an active service already, remove it first - // before it can be re-installed. - if (retv >= 0) - { -#ifndef ACE_NLOGGING - if (ACE::debug ()) - ACE_DEBUG ((LM_WARNING, - ACE_TEXT ("ACE (%P|%t) SG::initialize - repo=%@,") - ACE_TEXT (" name=%s - removing a pre-existing namesake.\n"), - this->repo_, - stf->name ())); -#endif - this->repo_->remove (stf->name ()); - } - - // If there is an inactive service by that name it may have been - // either inactivated, or just a forward declaration for a service, - // that is in the process of being initialized. If it is the latter, - // then we have detected an attempt to initialize the same dynamic - // service while still processing previous attempt. This can lock up - // the process, because the ACE_DLL_Manager::open () is not - // re-entrant - it uses a Singleton lock to serialize concurent - // invocations. This use case must be handled here, because if the - // DLL_Manager was re-entrant we would have entered an infinite - // recursion here. - if (retv == -2 && srp->type () == 0) - ACE_ERROR_RETURN ((LM_WARNING, - ACE_TEXT ("ACE (%P|%t) SG::initialize - repo=%@,") - ACE_TEXT (" name=%s - forward-declared; ") - ACE_TEXT (" recursive initialization requests are") - ACE_TEXT (" ignored.\n"), - this->repo_, - stf->name ()), - -1); - - // Reserve a spot for the dynamic service by inserting an incomplete - // service declaration, i.e. one that can not produce a service - // object if asked (a forward declaration). This declaration - // ensures maintaining the proper partial ordering of the services - // with respect to their finalization. For example, dependent static - // services must be registered *after* the dynamic service that - // loads them, so that their finalization is complete *before* - // finalizing the dynamic service. - ACE_Service_Type_Dynamic_Guard dummy (*this->repo_, - stf->name ()); - - // make_service_type() is doing the dynamic loading and also runs - // any static initializers - ACE_Auto_Ptr tmp (stf->make_service_type (this)); - - if (tmp.get () != 0 && - this->initialize_i (tmp.get (), parameters) == 0) - { - // All good. Tthe ACE_Service_Type instance is now owned by the - // repository and we should make sure it is not destroyed upon - // exit from this method. - tmp.release (); - return 0; - } - - return -1; -} -#endif /* (ACE_USES_CLASSIC_SVC_CONF == 1) */ - - -/// Dynamically link the shared object file and retrieve a pointer to -/// the designated shared object in this file. -/// @note This is obsolete (and error-prone) in the presense of dynamic -/// services with their own static services. This method will allow those -/// static services to register *before* the dynamic service that owns them. -/// Upon finalization of the static services the process may crash, because -/// the dynamic service's DLL may have been already released, together with -/// the memory in which the static services reside. -/// It may not crash, for instance, when the first static service to register -/// is the same as the dynamic service being loaded. You should be so lucky! .. -int -ACE_Service_Gestalt::initialize (const ACE_Service_Type *sr, - const ACE_TCHAR *parameters) -{ - ACE_TRACE ("ACE_Service_Gestalt::initialize"); - - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) SG::initialize - repo=%@, name=%s") - ACE_TEXT (" - looking up in the repo\n"), - this->repo_, - sr->name ())); - - ACE_Service_Type *srp = 0; - if (this->repo_->find (sr->name (), - (const ACE_Service_Type **) &srp) >= 0) - { -#ifndef ACE_NLOGGING - ACE_DEBUG ((LM_WARNING, - ACE_TEXT ("ACE (%P|%t) SG::initialize - repo=%@, name=%s") - ACE_TEXT (" - removing a pre-existing namesake.\n"), - this->repo_, - sr->name ())); -#endif - this->repo_->remove (sr->name ()); - } - - return this->initialize_i (sr, parameters); - -} - -/// Dynamically link the shared object file and retrieve a pointer to -/// the designated shared object in this file. -int -ACE_Service_Gestalt::initialize_i (const ACE_Service_Type *sr, - const ACE_TCHAR *parameters) -{ - ACE_TRACE ("ACE_Service_Gestalt::initialize_i"); - ACE_ARGV args (parameters); - if (sr->type ()->init (args.argc (), - args.argv ()) == -1) - { - // We just get ps to avoid having remove() delete it. - ACE_Service_Type *ps = 0; - this->repo_->remove (sr->name (), &ps); - -#ifndef ACE_NLOGGING - // Not using LM_ERROR here to avoid confusing the test harness - if (ACE::debug ()) - ACE_ERROR_RETURN ((LM_WARNING, - ACE_TEXT ("ACE (%P|%t) SG::initialize_i -") - ACE_TEXT (" repo=%@, name=%s - remove failed: %m\n"), - this->repo_, - sr->name ()), - -1); -#endif - return -1; - } - - if (this->repo_->insert (sr) == -1) - { -#ifndef ACE_NLOGGING - // Not using LM_ERROR here to avoid confusing the test harness - if (ACE::debug ()) - ACE_ERROR_RETURN ((LM_WARNING, - ACE_TEXT ("ACE (%P|%t) SG::initialize_i -") - ACE_TEXT (" repo=%@, name=%s - insert failed: %m\n"), - this->repo_, - sr->name ()), - -1); -#endif - return -1; - } - - return 0; -} - -// Totally remove from the daemon by removing it from the -// ACE_Reactor, and unlinking it if necessary. - -int -ACE_Service_Gestalt::remove (const ACE_TCHAR svc_name[]) -{ - ACE_TRACE ("ACE_Service_Gestalt::remove"); - if (this->repo_ == 0) - return -1; - - return this->repo_->remove (svc_name); -} - -/// Suspend @a svc_name. Note that this will not unlink the service -/// from the daemon if it was dynamically linked, it will mark it as -/// being suspended in the Service Repository and call the -/// member function on the appropriate . A service -/// can be resumed later on by calling the method... -int -ACE_Service_Gestalt::suspend (const ACE_TCHAR svc_name[]) -{ - ACE_TRACE ("ACE_Service_Gestalt::suspend"); - if (this->repo_ == 0) - return -1; - - return this->repo_->suspend (svc_name); -} - -// Resume a SVC_NAME that was previously suspended or has not yet -// been resumed (e.g., a static service). - -int -ACE_Service_Gestalt::resume (const ACE_TCHAR svc_name[]) -{ - ACE_TRACE ("ACE_Service_Gestalt::resume"); - if (this->repo_ == 0) - return -1; - - return this->repo_->resume (svc_name); -} - - -int -ACE_Service_Gestalt::process_directive (const ACE_Static_Svc_Descriptor &ssd, - bool force_replace) -{ - int const result = process_directive_i (ssd, force_replace); - if (result == 0) - { - this->add_processed_static_svc(&ssd); - } - return result; -} - -int -ACE_Service_Gestalt::process_directive_i (const ACE_Static_Svc_Descriptor &ssd, - bool force_replace) -{ - if (this->repo_ == 0) - return -1; - - if (!force_replace) - { - if (this->repo_->find (ssd.name_, 0, 0) >= 0) - { - // The service is already there, just return - return 0; - } - } - - - ACE_Service_Object_Exterminator gobbler; - void *sym = (ssd.alloc_)(&gobbler); - - ACE_Service_Type_Impl *stp = - ACE_Service_Config::create_service_type_impl (ssd.name_, - ssd.type_, - sym, - ssd.flags_, - gobbler); - if (stp == 0) - return 0; - - ACE_Service_Type *service_type = 0; - - // This is just a temporary to force the compiler to use the right - // constructor in ACE_Service_Type. Note that, in cases where we are - // called from a static initializer which is part of a DLL, there is - // not enough information about the actuall DLL in this context. - ACE_DLL tmp_dll; - - ACE_NEW_RETURN (service_type, - ACE_Service_Type (ssd.name_, - stp, - tmp_dll, - ssd.active_), - -1); - -#ifndef ACE_NLOGGING - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) SG::process_directive_i, ") - ACE_TEXT ("repo=%@ - %s, dll=%s, force=%d\n"), - this->repo_, - ssd.name_, - (tmp_dll.dll_name_ == 0) ? ACE_TEXT ("") : tmp_dll.dll_name_, - force_replace)); -#endif - - return this->repo_->insert (service_type); -} - -#if (ACE_USES_CLASSIC_SVC_CONF == 1) - -int -ACE_Service_Gestalt::process_directives_i (ACE_Svc_Conf_Param *param) -{ -#ifndef ACE_NLOGGING - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) SG::process_directives_i, ") - ACE_TEXT ("repo=%@ - %s\n"), - this->repo_, - (param->type == ACE_Svc_Conf_Param::SVC_CONF_FILE) - ? ACE_TEXT ("") - : param->source.directive)); -#endif - - // AC 970827 Skip the heap check because yacc allocates a buffer - // here which will be reported as a memory leak for some reason. - ACE_NO_HEAP_CHECK - - // Were we called in the context of the current instance? - ACE_ASSERT (this == param->config); - - // Temporarily (for the duration of this call) make sure that *any* - // static service registrations will happen with this instance. Such - // registrations are possible as a side-effect of dynamically - // loading a DLL, which has other static services registered. Thus - // this instance will own both the DLL and those static services, - // which implies that their finalization will be performed in the - // correct order, i.e. prior to finalizing the DLL - ACE_Service_Config_Guard guard (this); - - ::ace_yyparse (param); - - // This is a hack, better errors should be provided... - if (param->yyerrno > 0) - { - // Always set the last error if ace_yyparse() fails. - // Other code may use errno to determine the type - // of problem that occurred from processing directives. - ACE_OS::last_error (EINVAL); - return param->yyerrno; - } - else - return 0; -} - -#else - -ACE_XML_Svc_Conf * -ACE_Service_Gestalt::get_xml_svc_conf (ACE_DLL &xmldll) -{ - if (xmldll.open (ACE_TEXT ("ACEXML_XML_Svc_Conf_Parser")) == -1) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("ACE (%P|%t) Failure to open ACEXML_XML_Svc_Conf_Parser: %p\n"), - ACE_TEXT("ACE_Service_Config::get_xml_svc_conf")), - 0); - - void * foo = - xmldll.symbol (ACE_TEXT ("_ACEXML_create_XML_Svc_Conf_Object")); - -#if defined (ACE_OPENVMS) && (!defined (__INITIAL_POINTER_SIZE) || (__INITIAL_POINTER_SIZE < 64)) - int const temp_p = reinterpret_cast (foo); -#else - intptr_t const temp_p = reinterpret_cast (foo); -#endif - - ACE_XML_Svc_Conf::Factory factory = reinterpret_cast (temp_p); - - if (factory == 0) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("ACE (%P|%t) Unable to resolve factory: %p\n"), - xmldll.error ()), - 0); - - return factory (); -} -#endif /* ACE_USES_CLASSIC_SVC_CONF == 1 */ - -int -ACE_Service_Gestalt::process_file (const ACE_TCHAR file[]) -{ - ACE_TRACE ("ACE_Service_Gestalt::process_file"); - - // To avoid recursive processing of the same file and the same repository - // we maintain an implicit stack of dummy "services" named after the file - // being processed. Anytime we have to open a new file, we then can check - // to see if it is not already being processed by searching for a dummy - // service with a matching name. - if (this->repo_->find (file, 0, 0) >=0) - { - ACE_DEBUG ((LM_WARNING, - ACE_TEXT ("ACE (%P|%t) Configuration file %s is currently") - ACE_TEXT (" being processed. Ignoring recursive process_file().\n"), - file)); - return 0; - } - - // Register a dummy service as a forward decl, using the file name as name. - // The entry will be automaticaly removed once the thread exits this block. - ACE_Service_Type_Dynamic_Guard recursion_guard (*this->repo_, - file); - - /* - * @TODO: Test with ACE_USES_CLASSIC_SVC_CONF turned off! - */ -#if (ACE_USES_CLASSIC_SVC_CONF == 1) - int result = 0; - - FILE *fp = ACE_OS::fopen (file, - ACE_TEXT ("r")); - - if (fp == 0) - { - // Invalid svc.conf file. We'll report it here and break out of - // the method. - if (ACE::debug ()) - ACE_DEBUG ((LM_ERROR, - ACE_TEXT ("ACE (%P|%t): %p\n"), - file)); - - // Use stat to find out if the file exists. I didn't use access() - // because stat is better supported on most non-unix platforms. - ACE_stat exists; - if (ACE_OS::stat (file, &exists) == 0) - // If it exists, but we couldn't open it for reading then we - // must not have permission to read it. - errno = EPERM; - else - errno = ENOENT; - result = -1; - } - else - { - ACE_Svc_Conf_Param f (this, fp); - - // Keep track of the number of errors. - result = this->process_directives_i (&f); - - (void) ACE_OS::fclose (fp); - } - return result; -#else - ACE_DLL dll; - - auto_ptr xml_svc_conf (this->get_xml_svc_conf (dll)); - - if (xml_svc_conf.get () == 0) - return -1; - - return xml_svc_conf->parse_file (file); -#endif /* ACE_USES_CLASSIC_SVC_CONF == 1 */ -} - -int -ACE_Service_Gestalt::process_directive (const ACE_TCHAR directive[]) -{ - ACE_TRACE ("ACE_Service_Gestalt::process_directive"); - -#ifndef ACE_NLOGGING - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) SG::process_directive, repo=%@ - %s\n"), - this->repo_, - directive)); -#endif - -#if (ACE_USES_CLASSIC_SVC_CONF == 1) - ACE_UNUSED_ARG (directive); - - ACE_Svc_Conf_Param d (this, directive); - - return this->process_directives_i (&d); -#else - ACE_DLL dll; - - auto_ptr - xml_svc_conf (this->get_xml_svc_conf (dll)); - - if (xml_svc_conf.get () == 0) - return -1; - - // Temporarily (for the duration of this call) make sure that *any* static - // service registrations will happen with this instance. Such registrations - // are possible as a side-effect of dynamically loading a DLL, which has - // other static services registered. Thus this instance will own both the - // DLL and those static services, which implies that their finalization - // will be performed in the correct order, i.e. prior to finalizing the DLL - ACE_Service_Config_Guard guard (this); - - return xml_svc_conf->parse_string (directive); -#endif /* ACE_USES_CLASSIC_SVC_CONF == 1 */ - -} /* process_directive () */ - - -int -ACE_Service_Gestalt::init_svc_conf_file_queue (void) -{ - if (this->svc_conf_file_queue_ == 0) - { - ACE_SVC_QUEUE *tmp = 0; - ACE_NEW_RETURN (tmp, - ACE_SVC_QUEUE, - -1); - this->svc_conf_file_queue_ = tmp; - } - -#ifndef ACE_NLOGGING - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) SG::init_svc_conf_file_queue ") - ACE_TEXT ("- this=%@, repo=%@\n"), - this, this->repo_)); -#endif - - return 0; - -} /* init_svc_conf_file_queue () */ - - -int -ACE_Service_Gestalt::open_i (const ACE_TCHAR program_name[], - const ACE_TCHAR* logger_key, - bool ignore_static_svcs, - bool ignore_default_svc_conf_file, - bool ignore_debug_flag) -{ - ACE_TRACE ("ACE_Service_Gestalt::open_i"); - int result = 0; - ACE_Log_Msg *log_msg = ACE_LOG_MSG; - - this->no_static_svcs_ = ignore_static_svcs; - - // Record the current log setting upon entering this thread. - u_long old_process_mask = log_msg->priority_mask - (ACE_Log_Msg::PROCESS); - - u_long old_thread_mask = log_msg->priority_mask - (ACE_Log_Msg::THREAD); - -#ifndef ACE_NLOGGING - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) SG::open_i - this=%@, ") - ACE_TEXT ("opened=%d, loadstatics=%d\n"), - this, this->is_opened_, this->no_static_svcs_)); -#endif - - // Guard against reentrant processing. For example, - // if the singleton gestalt (ubergestalt) was already open, - // do not open it again... - if (this->is_opened_++ != 0) - return 0; - - if (this->init_i () != 0) - return -1; - - u_long flags = log_msg->flags (); - - // Only use STDERR if the caller hasn't already set the flags. - if (flags == 0) - flags = (u_long) ACE_Log_Msg::STDERR; - - const ACE_TCHAR *key = logger_key; - - if (key == 0 || ACE_OS::strcmp (key, ACE_DEFAULT_LOGGER_KEY) == 0) - { - // Only use the static if the caller doesn't - // override it in the parameter list or if the key supplied is - // equal to the default static logger key. - key = this->logger_key_; - } - else - { - ACE_SET_BITS (flags, ACE_Log_Msg::LOGGER); - } - - if (log_msg->open (program_name, - flags, - key) == -1) - return -1; - - if (!ignore_debug_flag) - { - // If -d was included as a startup parameter, the user wants debug - // information printed during service initialization. - if (ACE::debug ()) - ACE_Log_Msg::enable_debug_messages (); - else - // The user has requested no debugging info. - ACE_Log_Msg::disable_debug_messages (); - } - - if (!ignore_default_svc_conf_file) - { - bool add_default = true; - bool has_files = this->svc_conf_file_queue_ && - !this->svc_conf_file_queue_->is_empty (); - bool has_cmdline = this->svc_queue_ && !this->svc_queue_->is_empty (); - if (has_files || has_cmdline) - { - // check if default file is already listed - ACE_TString *sptr = 0; - ACE_TString default_svc_conf (ACE_DEFAULT_SVC_CONF); - - for (ACE_SVC_QUEUE_ITERATOR iter (*this->svc_conf_file_queue_); - iter.next (sptr) != 0 && add_default; - iter.advance ()) - { - add_default = (*sptr != default_svc_conf); - } - - if (add_default) - { - FILE *fp = ACE_OS::fopen (ACE_DEFAULT_SVC_CONF, ACE_TEXT ("r")); - if (fp != 0) - ACE_OS::fclose(fp); - else - add_default = false; - - } - } - - // Load the default "svc.conf" entry. here if there weren't - // overriding -f arguments in . - if (add_default && svc_conf_file_queue_->enqueue_head - (ACE_TString (ACE_DEFAULT_SVC_CONF)) == -1) - { - errno = ENOENT; - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("enqueuing ") - ACE_DEFAULT_SVC_CONF - ACE_TEXT(" file")), - -1); - } - } - - // See if we need to load the static services. - if (this->no_static_svcs_ == 0 - && this->load_static_svcs () == -1) - result = -1; - else - { - result = this->process_directives (); - if (result != -1 || errno == ENOENT) - result = this->process_commandline_directives (); - } - - // Reset debugging back to the way it was when we came into - // into . - { - // Make sure to save/restore errno properly. - ACE_Errno_Guard error (errno); - - if (!ignore_debug_flag) - { - log_msg->priority_mask (old_process_mask, ACE_Log_Msg::PROCESS); - log_msg->priority_mask (old_thread_mask, ACE_Log_Msg::THREAD); - } - } - - return result; -} /* open_i () */ - - -int -ACE_Service_Gestalt::is_opened (void) -{ - return this->is_opened_; -} - -int -ACE_Service_Gestalt::process_commandline_directives (void) -{ - int result = 0; - if (this->svc_queue_ != 0) - { - ACE_TString *sptr = 0; - for (ACE_SVC_QUEUE_ITERATOR iter (*this->svc_queue_); - iter.next (sptr) != 0; - iter.advance ()) - { - // Process just a single directive. - if (this->process_directive ((sptr->fast_rep ())) != 0) - { - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("ACE (%P|%t) %p\n"), - ACE_TEXT ("process_directive"))); - result = -1; - } - } - - delete this->svc_queue_; - this->svc_queue_ = 0; - } - - return result; - -} /* process_commandline_directives () */ - - -int -ACE_Service_Gestalt::parse_args (int argc, ACE_TCHAR *argv[]) -{ - ACE_TRACE ("ACE_Service_Gestalt::parse_args"); - bool unused_ignore_default_svc_conf = true; - return parse_args_i (argc, argv, unused_ignore_default_svc_conf); -} - -int -ACE_Service_Gestalt::parse_args_i (int argc, - ACE_TCHAR *argv[], - bool &ignore_default_svc_conf_file) -{ - ACE_TRACE ("ACE_Service_Gestalt::parse_args_i"); - ACE_Get_Opt get_opt (argc, - argv, - ACE_TEXT ("df:k:nyS:"), - 1); // Start at argv[1]. - - if (this->init_svc_conf_file_queue () == -1) - return -1; - - for (int c; (argc != 0) && ((c = get_opt ()) != -1); ) - switch (c) - { - case 'd': - ACE::debug (1); - break; - case 'f': - if (this->svc_conf_file_queue_->enqueue_tail (ACE_TString (get_opt.opt_arg ())) == -1) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("enqueue_tail")), - -1); - ignore_default_svc_conf_file = true; - break; - case 'k': - /* - * @TODO: Is this always a static storage? Shouldn't we copy - * & gain ownership of the value? - */ - this->logger_key_ = get_opt.opt_arg (); - break; - case 'n': - this->no_static_svcs_ = 1; - break; - case 'y': - this->no_static_svcs_ = 0; - break; - case 'S': - if (this->svc_queue_ == 0) - { - ACE_NEW_RETURN (this->svc_queue_, - ACE_SVC_QUEUE, - -1); - } - - if (this->svc_queue_->enqueue_tail (ACE_TString (get_opt.opt_arg ())) == -1) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("enqueue_tail")), - -1); - break; - default: - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) %c is not a ACE_Service_Config option\n"), - c)); - } - - return 0; -} /* parse_args_i () */ - - - -// Process service configuration directives from the files queued for -// processing -int -ACE_Service_Gestalt::process_directives (bool ) -{ - ACE_TRACE ("ACE_Service_Gestalt::process_directives"); - if (this->svc_conf_file_queue_ == 0 - || this->svc_conf_file_queue_->is_empty ()) - { - return 0; - } - - ACE_TString *sptr = 0; - int failed = 0; - - // Iterate through all the svc.conf files. - for (ACE_SVC_QUEUE_ITERATOR iter (*this->svc_conf_file_queue_); - iter.next (sptr) != 0; - iter.advance ()) - { - int result = this->process_file (sptr->fast_rep ()); - if (result < 0) - return result; - failed += result; - } - - return failed; - -} /* process_directives () */ - -// Tidy up and perform last rites on a terminating ACE_Service_Gestalt. -int -ACE_Service_Gestalt::close (void) -{ - ACE_TRACE ("ACE_Service_Gestalt::close"); - - if (!this->is_opened_ || --this->is_opened_ != 0) - return 0; - - // Delete the list fo svc.conf files - delete this->svc_conf_file_queue_; - this->svc_conf_file_queue_ = 0; - - if (this->processed_static_svcs_ && - !this->processed_static_svcs_->is_empty()) - { - Processed_Static_Svc **pss = 0; - for (ACE_PROCESSED_STATIC_SVCS_ITERATOR iter (*this->processed_static_svcs_); - iter.next (pss) != 0; - iter.advance ()) - { - delete *pss; - } - } - delete this->processed_static_svcs_; - this->processed_static_svcs_ = 0; - -#ifndef ACE_NLOGGING - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) SG::close - complete this=%@, repo=%@, owned=%d\n"), - this, this->repo_, this->svc_repo_is_owned_)); -#endif - - if (this->svc_repo_is_owned_) - delete this->repo_; - - this->repo_ = 0; - - return 0; -} /* close () */ - - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if !defined (__ACE_INLINE__) -#include "ace/Service_Gestalt.inl" -#endif /* __ACE_INLINE__ */ - -// Allocate a Service Manager. -ACE_FACTORY_DEFINE (ACE, ACE_Service_Manager) diff --git a/externals/ace/Service_Gestalt.h b/externals/ace/Service_Gestalt.h deleted file mode 100644 index 68a2ce7e7cc..00000000000 --- a/externals/ace/Service_Gestalt.h +++ /dev/null @@ -1,530 +0,0 @@ -// -*- C++ -*- - -//==================================================================== -/** - * @file Service_Gestalt.h - * - * $Id: Service_Gestalt.h 91158 2010-07-21 15:54:12Z mesnier_p $ - * - * @author Iliyan Jeliazkov - */ -//==================================================================== - -#ifndef ACE_SERVICE_GESTALT_H -#define ACE_SERVICE_GESTALT_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" -#include "ace/Default_Constants.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Auto_Ptr.h" -#include "ace/SString.h" -#include "ace/Unbounded_Queue.h" -#include "ace/Unbounded_Set.h" -#include "ace/Service_Repository.h" -#include "ace/Singleton.h" -#include "ace/OS_NS_signal.h" -#include "ace/Synch_Traits.h" -#include "ace/Atomic_Op.h" -#include "ace/Guard_T.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -#if (ACE_USES_CLASSIC_SVC_CONF == 1) -class ACE_Service_Type_Factory; -class ACE_Location_Node; -#else -class ACE_XML_Svc_Conf; -class ACE_DLL; -#endif /* ACE_USES_CLASSIC_SVC_CONF == 1 */ - -class ACE_Static_Svc_Descriptor; -class ACE_Svc_Conf_Param; - -/** - * @class ACE_Service_Gestalt - * - * @brief Supplies common server operations for dynamic and static - * configuration of services. - * - * The Gestalt embodies the concept of configuration context. On one - * hand, it is a flat namespace, where names correspond to a Service - * Object instance. A Gestalt owns the Service Repository instance, - * which in turn owns the Service Object instances. - * - * Another aspect of a Gestalt is its responsibility for - * record-keeping and accounting for the meta-data, necessary for - * locating, removing or instantiating a service. - * - * A repository underlies an instance of a gestalt and its lifetime - * may or may not be bounded by the lifetime of the gestalt, that owns - * it. This feature is important for the derived classes and the - * Service Config in particular. - * - */ -class ACE_Export ACE_Service_Gestalt -{ -private: - /// - /// Not implemented to enforce no copying - // - ACE_UNIMPLEMENTED_FUNC (ACE_Service_Gestalt(const ACE_Service_Gestalt&)) - ACE_UNIMPLEMENTED_FUNC (ACE_Service_Gestalt& operator=(const ACE_Service_Gestalt&)) - -public: - enum - { - MAX_SERVICES = ACE_DEFAULT_SERVICE_REPOSITORY_SIZE - }; - - enum - { - DEFAULT_SIZE = ACE_DEFAULT_SERVICE_GESTALT_SIZE - }; - - /// Constructor either associates the instance with the process-wide - /// singleton instance of ACE_Service_Repository, or creates and - /// manages its own instance of the specified size. - ACE_Service_Gestalt (size_t size = DEFAULT_SIZE, - bool svc_repo_is_owned = true, - bool no_static_svcs = true); - - /// Perform user-specified close activities and remove dynamic - /// memory. - ~ACE_Service_Gestalt (void); - - /// Dump the state of an object. - void dump (void) const; - - /** - * Performs an open without parsing command-line arguments. The - * @a logger_key indicates where to write the logging output, which - * is typically either a STREAM pipe or a socket address. If - * @a ignore_static_svcs is true then static services are not loaded, - * otherwise, they are loaded. If @a ignore_default_svc_conf_file is - * true then the @c svc.conf configuration file will be ignored. - * Returns zero upon success, -1 if the file is not found or cannot - * be opened (errno is set accordingly), otherwise returns the - * number of errors encountered loading the services in the - * specified svc.conf configuration file. If @a ignore_debug_flag is - * true then the application is responsible for setting the - * ACE_Log_Msg::priority_mask appropriately. - */ - int open (const ACE_TCHAR program_name[], - const ACE_TCHAR *logger_key = 0, - bool ignore_static_svcs = true, - bool ignore_default_svc_conf_file = false, - bool ignore_debug_flag = false); - - /** - * This is the primary entry point into the ACE_Service_Config (the - * constructor just handles simple initializations). It parses - * arguments passed in from @a argc and @a argv parameters. The - * arguments that are valid in a call to this method include: - * - * - '-b' Option to indicate that we should be a daemon. Note that when - * this option is used, the process will be daemonized before the - * service configuration file(s) are read. During daemonization, - * (on POSIX systems) the current directory will be changed to "/" - * so the caller should either fully specify the file names, or - * execute a @c chroot() to the appropriate directory. - * @sa ACE::daemonize(). - * - '-d' Turn on debugging mode - * - '-f' Specifies a configuration file name other than the default - * svc.conf. Can be specified multiple times to use multiple files. - * If any configuration file is provided with this option then - * the default svc.conf will be ignored. - * - '-k' Specifies the rendezvous point to use for the ACE distributed - * logger. - * - '-y' Explicitly enables the use of static services. This flag - * overrides the @a ignore_static_svcs parameter value. - * - '-n' Explicitly disables the use of static services. This flag - * overrides the @a ignore_static_svcs parameter value. - * - '-p' Specifies a pathname which is used to store the process id. - * - '-s' Specifies a signal number other than SIGHUP to trigger reprocessing - * of the configuration file(s). Ignored for platforms that do not - * have POSIX signals, such as Windows. - * - '-S' Specifies a service directive string. Enclose the string in quotes - * and escape any embedded quotes with a backslash. This option - * specifies service directives without the need for a configuration - * file. Can be specified multiple times. - * - * Note: Options '-f' and '-S' complement each other. Directives - * from files and from '-S' option are processed together in the - * following order. First, the default file "./svc.conf" is - * evaluated if not ignored, then all files are processed in the - * order they are specified in '-f' @a argv parameter. Finally, all - * '-S' directive strings are executed in the order the directives - * appear in @a argv parameter. - * - * If no files or directives are added via the '-f' and '-S' - * arguments, and the default file is not ignored, it will be - * evaluated whether it exists or not, possibly causing a failure - * return. If any other directives are added then the default file - * will be evaluated only if it exists. - * - * @param argc The number of commandline arguments. - * @param argv The array with commandline arguments - * @param logger_key Indicates where to write the logging output, - * which is typically either a STREAM pipe or a - * socket address. - * @param ignore_static_svcs If true then static services are not loaded, - * otherwise, they are loaded. - * @param ignore_default_svc_conf_file If false then the @c ./svc.conf - * configuration file will be ignored. - * @param ignore_debug_flag If false then the application is responsible - * for setting the @c ACE_Log_Msg::priority_mask - * appropriately. - * - * @retval -1 A configuration file is not found or cannot - * be opened (errno is set accordingly). - * @retval 0 Success. - * @retval >0 The number of directive errors encountered while processing - * the service configuration file(s). - */ - int open (int argc, - ACE_TCHAR *argv[], - const ACE_TCHAR *logger_key = 0, - bool ignore_static_svcs = true, - bool ignore_default_svc_conf_file = false, - bool ignore_debug_flag = false); - - /// Has it been opened? Returns the difference between the times - /// open and close have been called on this instance - int is_opened (void); - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - - /// Process one service configuration @a directive, which is passed as - /// a string. Returns the number of errors that occurred. - int process_directive (const ACE_TCHAR directive[]); - - /// Process one static service definition. - /** - * Load a new static service. - * - * @param ssd Service descriptor, see the document of - * ACE_Static_Svc_Descriptor for more details. - * - * @param force_replace If set the new service descriptor replaces - * any previous instance in the repository. - * - * @return Returns -1 if the service cannot be 'loaded'. - */ - int process_directive (const ACE_Static_Svc_Descriptor &ssd, - bool force_replace = false); - - /// Process a file containing a list of service configuration - /// directives. - int process_file (const ACE_TCHAR file[]); - - /** - * Locate an entry with @a name in the table. If @a ignore_suspended - * is set then only consider services marked as resumed. If the - * caller wants the located entry, pass back a pointer to the - * located entry via @a srp. If @a name is not found, -1 is returned. - * If @a name is found, but it is suspended and the caller wants to - * ignore suspended services a -2 is returned. - */ - int find (const ACE_TCHAR name[], - const ACE_Service_Type **srp = 0, - bool ignore_suspended = true) const; - - /** - * Handle the command-line options intended for the - * ACE_Service_Gestalt. Note that @c argv[0] is assumed to be the - * program name. - * - * The arguments that are valid in a call to this method are - * - '-d' Turn on debugging mode - * - '-f' Option to read in the list of svc.conf file names - * - '-k' Option to read a wide string where in the logger output can - * be written - * - '-y' Turn on the flag for a repository of statically - * linked services - * - '-n' Need not have a repository of statically linked services - * - '-S' Option to read in the list of services on the command-line - * Please observe the difference between options '-f' that looks - * for a list of files and here a list of services. - */ - int parse_args (int argc, ACE_TCHAR *argv[]); - - /** - * Process (or re-process) service configuration requests that are - * provided in the svc.conf file(s). Returns the number of errors - * that occurred. - */ - int process_directives (bool defunct_option = false); - - /// Tidy up and perform last rites when ACE_Service_Config is shut - /// down. This method calls @c close_svcs. Returns 0. - int close (void); - - /// Registers a service descriptor for a static service object - int insert (ACE_Static_Svc_Descriptor *stsd); - - // = Utility methods. - -#if (ACE_USES_CLASSIC_SVC_CONF == 1) - /// Dynamically link the shared object file and retrieve a pointer to - /// the designated shared object in this file. Also account for the - /// possiblity to have static services registered when loading the DLL, by - /// ensuring that the dynamic sevice is registered before any of its - /// subordibnate static services. Thus avoiding any finalization order - /// problems. - int initialize (const ACE_Service_Type_Factory *, - const ACE_TCHAR *parameters); -#endif /* (ACE_USES_CLASSIC_SVC_CONF == 1) */ - - /// Dynamically link the shared object file and retrieve a pointer to - /// the designated shared object in this file. - /// @deprecated - /// @note This is error-prone in the presense of dynamic services, - /// which in turn initialize their own static services. This method - /// will allow those static services to register *before* the dynamic - /// service that owns them. Upon finalization of the static services - /// the process will typically crash, because the dynamic service's - /// DLL may have been already released, together with the memory in - /// which the static services reside. It may not crash, for - /// instance, when the first static service to register is the same - /// as the dynamic service being loaded. You should be so lucky! - int initialize (const ACE_Service_Type *, - const ACE_TCHAR *parameters); - - /// Initialize and activate a statically @a svc_name service. - int initialize (const ACE_TCHAR *svc_name, - const ACE_TCHAR *parameters); - - /// Resume a @a svc_name that was previously suspended or has not yet - /// been resumed (e.g., a static service). - int resume (const ACE_TCHAR svc_name[]); - - /** - * Suspend @a svc_name. Note that this will not unlink the service - * from the daemon if it was dynamically linked, it will mark it as - * being suspended in the Service Repository and call the @c suspend() - * member function on the appropriate ACE_Service_Object. A - * service can be resumed later on by calling the @c resume() member - * function... - */ - int suspend (const ACE_TCHAR svc_name[]); - - /// Totally remove @a svc_name from the daemon by removing it - /// from the ACE_Reactor, and unlinking it if necessary. - int remove (const ACE_TCHAR svc_name[]); - - /** - * Using the supplied name, finds and (if needed) returns a pointer to a - * static service descriptor. Returns 0 for success and -1 for failure - */ - int find_static_svc_descriptor (const ACE_TCHAR* name, - ACE_Static_Svc_Descriptor **ssd = 0) const; - - struct Processed_Static_Svc - { - Processed_Static_Svc (const ACE_Static_Svc_Descriptor *); - ~Processed_Static_Svc (void); - ACE_TCHAR * name_; - const ACE_Static_Svc_Descriptor *assd_; - }; - - /// Get the current ACE_Service_Repository held by this object. - ACE_Service_Repository* current_service_repository (void); - -protected: - - int parse_args_i (int, ACE_TCHAR *argv[], - bool& ignore_default_svc_conf_file); - - /** - * Performs an open without parsing command-line arguments. The @a - * logger_key indicates where to write the logging output, which is - * typically either a STREAM pipe or a socket address. If @a - * ignore_default_svc_conf_file is non-0 then the "svc.conf" file - * will not be added by default. If @a ignore_debug_flag is non-0 - * then the application is responsible for setting the @c - * ACE_Log_Msg::priority_mask() appropriately. Returns number of - * errors that occurred on failure and 0 otherwise. - */ - int open_i (const ACE_TCHAR program_name[], - const ACE_TCHAR *logger_key = 0, - bool ignore_static_svcs = true, - bool ignore_default_svc_conf_file = false, - bool ignore_debug_flag = false); - - /// Initialize the @c svc_conf_file_queue_ if necessary. - int init_svc_conf_file_queue (void); - - /// Add the default statically-linked services to the - /// ACE_Service_Repository. - int load_static_svcs (void); - - /// Process service configuration requests that were provided on the - /// command-line. Returns the number of errors that occurred. - int process_commandline_directives (void); - - /// Process a static directive without also inserting its descriptor - /// the global table. This avoids multiple additions when processing - /// directives in non-global gestalts. - int process_directive_i (const ACE_Static_Svc_Descriptor &ssd, - bool force_replace = false); - -#if (ACE_USES_CLASSIC_SVC_CONF == 1) - /// This is the implementation function that process_directives() - /// and process_directive() both call. Returns the number of errors - /// that occurred. - int process_directives_i (ACE_Svc_Conf_Param *param); -#else - /// Helper function to dynamically link in the XML Service Configurator - /// parser. - ACE_XML_Svc_Conf* get_xml_svc_conf (ACE_DLL &d); -#endif /* ACE_USES_CLASSIC_SVC_CONF == 1 */ - - /// Dynamically link the shared object file and retrieve a pointer to - /// the designated shared object in this file. - int initialize_i (const ACE_Service_Type *sr, const ACE_TCHAR *parameters); - - const ACE_Static_Svc_Descriptor* find_processed_static_svc (const ACE_TCHAR*); - void add_processed_static_svc (const ACE_Static_Svc_Descriptor *); - - /// Performs the common initialization tasks for a new or previously - /// closed instance. Must not be virtual, as it is called from the - /// constructor. - int init_i (void); - -protected: - - /// Maintain a queue of services to be configured from the - /// command-line. - typedef ACE_Unbounded_Queue ACE_SVC_QUEUE; - typedef ACE_Unbounded_Queue_Iterator ACE_SVC_QUEUE_ITERATOR; - - /// Maintain a set of the statically linked service descriptors. - typedef ACE_Unbounded_Set - ACE_STATIC_SVCS; - - typedef ACE_Unbounded_Set_Iterator - ACE_STATIC_SVCS_ITERATOR; - - typedef ACE_Unbounded_Set - ACE_PROCESSED_STATIC_SVCS; - - typedef ACE_Unbounded_Set_Iterator - ACE_PROCESSED_STATIC_SVCS_ITERATOR; - - friend class ACE_Dynamic_Service_Base; - friend class ACE_Service_Object; - friend class ACE_Service_Config; - friend class ACE_Service_Config_Guard; - -protected: - - /// Do we own the service repository instance, or have only been - /// given a ptr to the singleton? - bool svc_repo_is_owned_; - - /// Repository size is necessary, so that we can close (which may - /// destroy the repository instance), and then re-open again. - size_t svc_repo_size_; - - /// Keep track of the number of times the instance has been - /// initialized (opened). "If so, we can't allow to be called since - /// it's not reentrant" is the original motivation, but that does not seem - /// to be the case anymore. This variable is incremented by the - /// method and decremented by the - /// method. - int is_opened_; - - /// Indicates where to write the logging output. This is typically - /// either a STREAM pipe or a socket - const ACE_TCHAR *logger_key_; - - /// Should we avoid loading the static services? - bool no_static_svcs_; - - /// Queue of services specified on the command-line. - ACE_SVC_QUEUE* svc_queue_; - - /** - * Queue of svc.conf files specified on the command-line. - * @@ This should probably be made to handle unicode filenames... - */ - ACE_SVC_QUEUE* svc_conf_file_queue_; - - /// The service repository to hold the services. - ACE_Service_Repository* repo_; - - /// Repository of statically linked services. - ACE_STATIC_SVCS* static_svcs_; - - /// Repository of statically linked services for which process - /// directive was called, but the service is not already a member of - /// the static_svcs_ list. - ACE_PROCESSED_STATIC_SVCS* processed_static_svcs_; - - /// Support for intrusive reference counting - ACE_Atomic_Op refcnt_; - - public: - static void intrusive_add_ref (ACE_Service_Gestalt*); - static void intrusive_remove_ref (ACE_Service_Gestalt*); - -}; /* class ACE_Service_Gestalt */ - - -/** - * @class ACE_Service_Type_Dynamic_Guard - * - * @brief A forward service declaration guard. - * - * Helps to resolve an issue with hybrid services, i.e. dynamic - * services, accompanied by static services in the same DLL. Only - * automatic instances of this class are supposed to exist. Those are - * created during (dynamic) service initialization and serve to: - * - * (a) Ensure the service we are loading is ordered last in the - * repository, following any other services it may cause to register, - * as part of its own registration. This is a common case when - * loading dynamic services from DLLs - there are often static - * initializers, which register static services. - * - * (b) The SDG instance destructor detects if the dynamic service - * initialized successfully and "fixes-up" all the newly registered - * static services to hold a reference to the DLL, from which they - * have originated. - */ -class ACE_Export ACE_Service_Type_Dynamic_Guard -{ -public: - ACE_Service_Type_Dynamic_Guard (ACE_Service_Repository &r, - ACE_TCHAR const *name); - - ~ACE_Service_Type_Dynamic_Guard (void); - -private: - ACE_Service_Repository & repo_; - size_t repo_begin_; - ACE_TCHAR const * const name_; - -# if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) - ACE_Guard< ACE_Recursive_Thread_Mutex > repo_monitor_; -#endif -}; - - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Service_Gestalt.inl" -#endif /* __ACE_INLINE__ */ - - -#include /**/ "ace/post.h" - -#endif /* ACE_SERVICE_GESTALT_H */ diff --git a/externals/ace/Service_Gestalt.inl b/externals/ace/Service_Gestalt.inl deleted file mode 100644 index 436037b71a1..00000000000 --- a/externals/ace/Service_Gestalt.inl +++ /dev/null @@ -1,78 +0,0 @@ -// -*- C++ -*- -// -// $Id: Service_Gestalt.inl 91158 2010-07-21 15:54:12Z mesnier_p $ - - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - - -// This is the primary entry point into the ACE_Service_Config (the -// constructor just handles simple initializations). - -ACE_INLINE int -ACE_Service_Gestalt::open (const ACE_TCHAR program_name[], - const ACE_TCHAR *logger_key, - bool ignore_static_svcs, - bool ignore_default_svc_conf, - bool ignore_debug_flag) -{ - ACE_TRACE ("ACE_Service_Gestalt::open"); - this->no_static_svcs_ = ignore_static_svcs; - - return this->open_i (program_name, - logger_key, - ignore_static_svcs, - ignore_default_svc_conf, - ignore_debug_flag); -} - -ACE_INLINE int -ACE_Service_Gestalt::open (int argc, - ACE_TCHAR *argv[], - const ACE_TCHAR *logger_key, - bool ignore_static_svcs, - bool ignore_default_svc_conf, - bool ignore_debug_flag) -{ - ACE_TRACE ("ACE_Service_Gestalt::open"); - - // Parsing argv may change no_static_svcs_ so set the default here, then - // parse, then pass the final value to open_i(). - this->no_static_svcs_ = ignore_static_svcs; - - if (this->parse_args_i (argc, - argv, - ignore_default_svc_conf) == -1) - return -1; - - return this->open_i (argv == 0 ? 0 : argv[0], - logger_key, - this->no_static_svcs_, - ignore_default_svc_conf, - ignore_debug_flag); -} - -/// Searches for a service object declaration in the local repo, only - -ACE_INLINE int -ACE_Service_Gestalt::find (const ACE_TCHAR name[], - const ACE_Service_Type **srp, - bool ignore_suspended) const -{ - // Closing the gestalt will have disassociated it from the - // repository. If the repository used to be owned by the gestalt, it - // will also have been destroyed - so just check for repo_ before - // doing anything with it. - if (this->repo_ != 0) - return this->repo_->find (name, srp, ignore_suspended); - - return 0; -} - -ACE_INLINE ACE_Service_Repository* -ACE_Service_Gestalt::current_service_repository (void) -{ - return this->repo_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Service_Manager.cpp b/externals/ace/Service_Manager.cpp deleted file mode 100644 index 5a4dbcb89bd..00000000000 --- a/externals/ace/Service_Manager.cpp +++ /dev/null @@ -1,437 +0,0 @@ -// $Id: Service_Manager.cpp 82723 2008-09-16 09:35:44Z johnnyw $ - -#include "ace/Service_Manager.h" - -#include "ace/Get_Opt.h" -#include "ace/Log_Msg.h" -#include "ace/Service_Repository.h" -#include "ace/Service_Config.h" -#include "ace/Service_Types.h" -#include "ace/Reactor.h" -#include "ace/WFMO_Reactor.h" -#include "ace/OS_NS_stdio.h" -#include "ace/OS_NS_string.h" - -ACE_RCSID (ace, - Service_Manager, - "$Id: Service_Manager.cpp 82723 2008-09-16 09:35:44Z johnnyw $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE (ACE_Service_Manager) - -void -ACE_Service_Manager::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Service_Manager::dump"); -#endif /* ACE_HAS_DUMP */ -} - -// Static variables. - -u_short ACE_Service_Manager::DEFAULT_PORT_ = 10000; - -ACE_Service_Manager::ACE_Service_Manager (void) - : debug_ (false), - signum_ (SIGHUP) -{ - ACE_TRACE ("ACE_Service_Manager::ACE_Service_Manager"); -} - -ACE_Service_Manager::~ACE_Service_Manager (void) -{ - ACE_TRACE ("ACE_Service_Manager::~ACE_Service_Manager"); -} - -int -ACE_Service_Manager::suspend (void) -{ - ACE_TRACE ("ACE_Service_Manager::suspend"); - return ACE_Reactor::instance ()->suspend_handler (this); -} - -int -ACE_Service_Manager::resume (void) -{ - ACE_TRACE ("ACE_Service_Manager::resume"); - return ACE_Reactor::instance ()->resume_handler (this); -} - -int -ACE_Service_Manager::open (const ACE_INET_Addr &sia) -{ - ACE_TRACE ("ACE_Service_Manager::open"); - - // Reuse the listening address, even if it's already in use! - if (this->acceptor_.open (sia, 1) == -1) - { - return -1; - } - - return 0; -} - -int -ACE_Service_Manager::info (ACE_TCHAR **strp, size_t length) const -{ - ACE_TRACE ("ACE_Service_Manager::info"); - ACE_INET_Addr sa; - ACE_TCHAR buf[BUFSIZ]; - - if (this->acceptor_.get_local_addr (sa) == -1) - { - return -1; - } - - ACE_OS::sprintf (buf, - ACE_TEXT ("%d/%s %s"), - sa.get_port_number (), - ACE_TEXT ("tcp"), - ACE_TEXT ("# lists all services in the daemon\n")); - - if (*strp == 0 && (*strp = ACE_OS::strdup (buf)) == 0) - { - return -1; - } - else - { - ACE_OS::strsncpy (*strp, buf, length); - } - - return static_cast (ACE_OS::strlen (buf)); -} - -int -ACE_Service_Manager::init (int argc, ACE_TCHAR *argv[]) -{ - ACE_TRACE ("ACE_Service_Manager::init"); - ACE_INET_Addr local_addr (ACE_Service_Manager::DEFAULT_PORT_); - - //FUZZ: disable check_for_lack_ACE_OS - ACE_Get_Opt getopt (argc, argv, ACE_TEXT ("dp:s:"), 0); // Start at argv[0] - - for (int c; (c = getopt ()) != -1; ) - //FUZZ: enable check_for_lack_ACE_OS - switch (c) - { - case 'd': - this->debug_ = true; - break; - case 'p': - local_addr.set ((u_short) ACE_OS::atoi (getopt.opt_arg ())); - break; - case 's': - this->signum_ = ACE_OS::atoi (getopt.opt_arg ()); - break; - default: - break; - } - - if (this->get_handle () == ACE_INVALID_HANDLE && - this->open (local_addr) == -1) - { - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("open")), -1); - } - else if (ACE_Reactor::instance ()->register_handler - (this, - ACE_Event_Handler::ACCEPT_MASK) == -1) - { - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("registering service with ACE_Reactor\n")), - -1); - } - - return 0; -} - -int -ACE_Service_Manager::handle_close (ACE_HANDLE, ACE_Reactor_Mask) -{ - ACE_TRACE ("ACE_Service_Manager::handle_close"); - return this->acceptor_.close (); -} - -int -ACE_Service_Manager::fini (void) -{ - ACE_TRACE ("ACE_Service_Manager::fini"); - - int retv = 0; - - if (this->get_handle () != ACE_INVALID_HANDLE) - { - retv = - ACE_Reactor::instance ()->remove_handler ( - this, - ACE_Event_Handler::ACCEPT_MASK | ACE_Event_Handler::DONT_CALL); - - this->handle_close (ACE_INVALID_HANDLE, - ACE_Event_Handler::NULL_MASK); - } - - return retv; -} - -ACE_HANDLE -ACE_Service_Manager::get_handle (void) const -{ - ACE_TRACE ("ACE_Service_Manager::get_handle"); - return this->acceptor_.get_handle (); -} - -int -ACE_Service_Manager::handle_signal (int, siginfo_t *, ucontext_t *) -{ - return 0; -} - -// Determine all the services offered by this daemon and return the -// information back to the client. - -int -ACE_Service_Manager::list_services (void) -{ - ACE_TRACE ("ACE_Service_Manager::list_services"); - ACE_Service_Repository_Iterator sri (*ACE_Service_Repository::instance (), 0); - - for (const ACE_Service_Type *sr; - sri.next (sr) != 0; - sri.advance ()) - { - ssize_t len = static_cast (ACE_OS::strlen (sr->name ())) + 11; - ACE_TCHAR buf[BUFSIZ]; - ACE_TCHAR *p = buf + len; - - ACE_OS::strcpy (buf, sr->name ()); - ACE_OS::strcat (buf, (sr->active ()) ? - ACE_TEXT (" (active) ") : - ACE_TEXT (" (paused) ")); - - p[-1] = ' '; - p[0] = '\0'; - - len += sr->type ()->info (&p, sizeof buf - len); - - if (this->debug_) - { - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("len = %d, info = %s%s"), - len, - buf, - buf[len - 1] == '\n' ? ACE_TEXT ("") : ACE_TEXT ("\n"))); - } - - if (len > 0) - { - ssize_t n = this->client_stream_.send_n (buf, len); - - if (n <= 0 && errno != EPIPE) - { - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("send_n"))); - } - } - } - - return 0; -} - -// Trigger a reconfiguration of the Service Configurator via its -// svc.conf file. - -int -ACE_Service_Manager::reconfigure_services (void) -{ - ACE_TRACE ("ACE_Service_Manager::reconfigure_services"); - -#if 0 -// Send ourselves a signal! ACE_OS::kill (ACE_OS::getpid (), -// this->signum_); -#endif /* 0 */ - - // Flag the main event loop that a reconfiguration should occur. - // The next trip through the should - // pick this up and cause a reconfiguration. Note that we can't - // trigger the reconfiguration automatically since that might "pull - // the rug" out from underneath the existing services in a - // problematic way. - ACE_Service_Config::reconfig_occurred ((sig_atomic_t) 1); - return static_cast (this->client_stream_.send_n ("done\n", - sizeof ("done\n"))); -} - -// isolate the request-processing code -void -ACE_Service_Manager::process_request (ACE_TCHAR *request) -{ - ACE_TRACE("ACE_Service_Manager::process_request"); - ACE_TCHAR *p; - - // Kill trailing newlines. - for (p = request; - (*p != '\0') && (*p != '\r') && (*p != '\n'); - p++) - { - continue; - } - - *p = '\0'; - - if (ACE_OS::strcmp (request, ACE_TEXT ("help")) == 0) - { - // Return a list of the configured services. - this->list_services (); - } - else if (ACE_OS::strcmp (request, ACE_TEXT ("reconfigure") )== 0) - { - // Trigger a reconfiguration by re-reading the local file. - this->reconfigure_services (); - } - else - { - // Just process a single request passed in via the socket - // remotely. - ACE_Service_Config_Guard guard (ACE_Service_Config::global ()); - ACE_Service_Config::process_directive (request); - } - - // Additional management services may be handled here... -} - -// Accept new connection from client and carry out the service they -// request. - -int -ACE_Service_Manager::handle_input (ACE_HANDLE) -{ - ACE_TRACE ("ACE_Service_Manager::handle_input"); - - // Try to find out if the implementation of the reactor that we are - // using requires us to reset the event association for the newly - // created handle. This is because the newly created handle will - // inherit the properties of the listen handle, including its event - // associations. - bool reset_new_handle = - ACE_Reactor::instance ()->uses_event_associations (); - - if (this->acceptor_.accept (this->client_stream_, // stream - 0, // remote address - 0, // timeout - 1, // restart - reset_new_handle // reset new handler - ) == -1) - { - return -1; - } - - if (this->debug_) - { - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("client_stream fd = %d\n"), - this->client_stream_.get_handle ())); - ACE_INET_Addr sa; - - if (this->client_stream_.get_remote_addr (sa) == -1) - { - return -1; - } - - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("accepted from host %C at port %d\n"), - sa.get_host_name (), - sa.get_port_number ())); - } - - ACE_TCHAR request[BUFSIZ]; - ACE_TCHAR* offset = request; - ssize_t remaining = sizeof (request); - - // Read service request from client. - - ssize_t result; - - // Keep looping until we actually get the request. Note that Win32 - // sets the socket into non-blocking mode, so we may need to loop if - // the system is heavily loaded. Read bytes into the buffer until a - // '\n' or '\r' is found in the buffer, otherwise the buffer - // contains an incomplete string. - - int error; - - do - { - result = client_stream_.recv (offset, remaining); - error = errno; - - if (result == 0 && error != EWOULDBLOCK) - { - remaining = 0; - } - - if (result >= 0) - { - if ((remaining -= result) <= 0) - { - ACE_DEBUG ((LM_ERROR, - ACE_TEXT ("Request buffer overflow.\n"))); - result = 0; - break; - } - - offset += result; - *offset = 0; - - if (ACE_OS::strchr (request, '\r') != 0 - || ACE_OS::strchr (request, '\n') != 0) - { - remaining = 0; - } - } - } - while ((result == -1 && error == EWOULDBLOCK) || remaining > 0); - - switch (result) - { - case -1: - if (this->debug_) - { - ACE_DEBUG ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("recv"))); - } - - break; - case 0: - return 0; - /* NOTREACHED */ - default: - { - ACE_Event_Handler *old_signal_handler = 0; - ACE_Reactor::instance ()->register_handler (SIGPIPE, - this, - 0, - &old_signal_handler); - - this->process_request (request); - - // Restore existing SIGPIPE handler - ACE_Reactor::instance ()->register_handler (SIGPIPE, - old_signal_handler); - } - } - - if (this->client_stream_.close () == -1 && this->debug_) - { - ACE_DEBUG ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("close"))); - } - - return 0; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Service_Manager.h b/externals/ace/Service_Manager.h deleted file mode 100644 index 13ce60405ff..00000000000 --- a/externals/ace/Service_Manager.h +++ /dev/null @@ -1,120 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Service_Manager.h - * - * $Id: Service_Manager.h 81388 2008-04-23 14:02:05Z johnnyw $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_SERVICE_MANAGER_H -#define ACE_SERVICE_MANAGER_H -#include /**/ "ace/pre.h" - -#include "ace/SOCK_Stream.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/SOCK_Acceptor.h" -#include "ace/INET_Addr.h" -#include "ace/Service_Object.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Service_Manager - * - * @brief Provide a standard ACE service for managing all the services - * configured in an ACE_Service_Repository. - * - * This implementation is simple and just handles each client - * request one at a time. There are currently 3 types of requests: - * - List services: If the string "help" is sent, return a list of all - * the services supported by the Service Configurator. - * - Reconfigure: If the string "reconfigure" is sent trigger a - * reconfiguration, which will re-read the local file. - * - Process directive: If neither "help" nor "reconfigure" is sent, - * simply treat the incoming string as a process directive and pass - * it along to . This allows - * remote configuration via command-line instructions like - * % echo suspend My_Remote_Service | telnet hostname 3911 - * - * Each request is associated with a new connection, which is closed - * when the request is processed. In addition, you must be using the - * singleton in order to trigger - * reconfigurations. - */ -class ACE_Export ACE_Service_Manager : public ACE_Service_Object -{ -public: - // = Initialization and termination hooks. - /// Constructor. - ACE_Service_Manager (void); - - /// Destructor. - virtual ~ACE_Service_Manager (void); - -protected: - // = Perform the various meta-services. - - /// Trigger a reconfiguration of the Service Configurator by - /// re-reading its local file. - virtual int reconfigure_services (void); - - /// Determine all the services offered by this daemon and return the - /// information back to the client. - virtual int list_services (void); - - // = Dynamic linking hooks. - virtual int init (int argc, ACE_TCHAR *argv[]); - virtual int info (ACE_TCHAR **info_string, size_t length) const; - virtual int fini (void); - - // = Scheduling hooks. - virtual int suspend (void); - virtual int resume (void); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - int open (const ACE_INET_Addr &sia); - - // = Demultiplexing hooks. - virtual ACE_HANDLE get_handle (void) const; - virtual int handle_input (ACE_HANDLE fd); - virtual int handle_close (ACE_HANDLE fd, ACE_Reactor_Mask); - virtual int handle_signal (int signum, siginfo_t *, ucontext_t *); - - /// Handle one request. - virtual void process_request (ACE_TCHAR *request); - - /// Connection to the client (we only support one client connection - /// at a time). - ACE_SOCK_Stream client_stream_; - - /// Acceptor instance. - ACE_SOCK_Acceptor acceptor_; - - /// Keep track whether we debug or not. - bool debug_; - - /// The signal used to trigger reconfiguration. - int signum_; - - /// Default port for the Acceptor to listen on. - static u_short DEFAULT_PORT_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" -#endif /* _SERVICE_MANAGER_H */ diff --git a/externals/ace/Service_Object.cpp b/externals/ace/Service_Object.cpp deleted file mode 100644 index 0ac76be21cb..00000000000 --- a/externals/ace/Service_Object.cpp +++ /dev/null @@ -1,183 +0,0 @@ -// $Id: Service_Object.cpp 90077 2010-05-05 16:19:16Z cbeaulac $ - -#include "ace/config-all.h" - -#include "ace/Service_Object.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Service_Object.inl" -#endif /* __ACE_INLINE__ */ - -#include "ace/OS_NS_stdio.h" -#include "ace/Service_Types.h" -#include "ace/DLL.h" -#include "ace/ACE.h" -#include "ace/Log_Msg.h" -#if defined (ACE_OPENVMS) -# include "ace/Lib_Find.h" -#endif - -ACE_RCSID (ace, - Service_Object, - "$Id: Service_Object.cpp 90077 2010-05-05 16:19:16Z cbeaulac $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Service_Object) -ACE_ALLOC_HOOK_DEFINE(ACE_Service_Type) - -void -ACE_Service_Type::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Service_Type::dump"); -#endif /* ACE_HAS_DUMP */ - - - // Using printf, since the log facility may not have been - // initialized yet. Using a "//" prefix, in case the executable - // happens to be a code generator and the output gets embedded in - // the generated C++ code. - ACE_OS::fprintf(stderr, - "// [ST] dump, this=%p, name=%s, type=%p, so=%p, active=%d\n", - this, - this->name_, - this->type_, - (this->type_ != 0) ? this->type_->object () : 0, - this->active_); - -} - -ACE_Service_Type::ACE_Service_Type (const ACE_TCHAR *n, - ACE_Service_Type_Impl *t, - const ACE_DLL &dll, - bool active) - : name_ (0), - type_ (t), - dll_ (dll), - active_ (active), - fini_already_called_ (false) -{ - ACE_TRACE ("ACE_Service_Type::ACE_Service_Type"); - this->name (n); -} - -ACE_Service_Type::ACE_Service_Type (const ACE_TCHAR *n, - ACE_Service_Type_Impl *t, - ACE_SHLIB_HANDLE handle, - bool active) - : name_ (0), - type_ (t), - active_ (active), - fini_already_called_ (false) -{ - ACE_TRACE ("ACE_Service_Type::ACE_Service_Type"); - this->dll_.set_handle (handle); - this->name (n); -} - -ACE_Service_Type::~ACE_Service_Type (void) -{ - ACE_TRACE ("ACE_Service_Type::~ACE_Service_Type"); - this->fini (); - - delete [] const_cast (this->name_); -} - -int -ACE_Service_Type::fini (void) -{ - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) ST::fini - destroying name=%s, dll=%s\n"), - this->name_, - this->dll_.dll_name_)); - - if (this->fini_already_called_) - return 0; - - this->fini_already_called_ = true; - - if (this->type_ == 0) - { - // Returning 1 currently only makes sense for dummy instances, used - // to "reserve" a spot (kind of like forward-declarations) for a - // dynamic service. This is necessary to help enforce the correct - // finalization order, when such service also has any (dependent) - // static services - - return 1; // No implementation was found. - } - - int ret = this->type_->fini (); - - // Ensure type is 0 to prevent invalid access after call to fini. - this->type_ = 0; - - // Ensure that closing the DLL is done after type_->fini() as it may - // require access to the code for the service object destructor, - // which resides in the DLL - - return (ret | this->dll_.close ()); -} - -int -ACE_Service_Type::suspend (void) const -{ - ACE_TRACE ("ACE_Service_Type::suspend"); - (const_cast (this))->active_ = false; - return this->type_->suspend (); -} - -int -ACE_Service_Type::resume (void) const -{ - ACE_TRACE ("ACE_Service_Type::resume"); - (const_cast (this))->active_ = true; - return this->type_->resume (); -} - -ACE_Service_Object::ACE_Service_Object (ACE_Reactor *r) - : ACE_Event_Handler (r) -{ - ACE_TRACE ("ACE_Service_Object::ACE_Service_Object"); -} - -ACE_Service_Object::~ACE_Service_Object (void) -{ - ACE_TRACE ("ACE_Service_Object::~ACE_Service_Object"); -} - -int -ACE_Service_Object::suspend (void) -{ - ACE_TRACE ("ACE_Service_Object::suspend"); - return 0; -} - -int -ACE_Service_Object::resume (void) -{ - ACE_TRACE ("ACE_Service_Object::resume"); - return 0; -} - -void -ACE_Service_Type::name (const ACE_TCHAR *n) -{ - ACE_TRACE ("ACE_Service_Type::name"); - - delete [] const_cast (this->name_); - this->name_ = ACE::strnew (n); -} - -#if defined (ACE_OPENVMS) -ACE_Dynamic_Svc_Registrar::ACE_Dynamic_Svc_Registrar (const ACE_TCHAR* alloc_name, - void* svc_allocator) -{ - // register service allocator function by full name in ACE singleton registry - ACE::ldregister (alloc_name, svc_allocator); -} -#endif - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Service_Object.h b/externals/ace/Service_Object.h deleted file mode 100644 index 2f24ccbd47d..00000000000 --- a/externals/ace/Service_Object.h +++ /dev/null @@ -1,206 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file Service_Object.h - * - * $Id: Service_Object.h 84170 2009-01-15 13:31:50Z johnnyw $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_SERVICE_OBJECT_H -#define ACE_SERVICE_OBJECT_H -#include /**/ "ace/pre.h" - -#include "ace/Shared_Object.h" -#include "ace/Svc_Conf_Tokens.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Event_Handler.h" -#include "ace/DLL.h" - -#include "ace/Service_Gestalt.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -#define ACE_Component ACE_Service_Object - -/** - * @class ACE_Service_Object - * - * @brief Provide the abstract base class common to all service - * implementations. - * - * Classes that inherit from ACE_Service_Objects are capable - * of being registered with the ACE_Reactor (due to the - * ACE_Event_Handler, as well as being dynamically linked by - * the ACE_Service_Config (due to the ACE_Shared_Object). - */ -class ACE_Export ACE_Service_Object - : public ACE_Event_Handler, - public ACE_Shared_Object -{ -public: - // = Initialization and termination methods. - /// Constructor. - ACE_Service_Object (ACE_Reactor * = 0); - - /// Destructor. - virtual ~ACE_Service_Object (void); - - /// Temporarily disable a service without removing it completely. - virtual int suspend (void); - - /// Re-enable a previously suspended service. - virtual int resume (void); -}; - -// Forward decl. -class ACE_Service_Type_Impl; - -/** - * @class ACE_Service_Type - * - * @brief Keeps track of information related to the various - * ACE_Service_Type_Impl subclasses. - * - * This class acts as the interface of the "Bridge" pattern. - */ -class ACE_Export ACE_Service_Type -{ -public: - enum - { - /// Delete the payload object. - DELETE_OBJ = 1, - - /// Delete the enclosing object. - DELETE_THIS = 2 - }; - - enum - { - SERVICE_OBJECT = ACE_SVC_OBJ_T, - MODULE = ACE_MODULE_T, - STREAM = ACE_STREAM_T, - INVALID_TYPE = -1 - }; - - // = Initialization and termination methods. - ACE_Service_Type (const ACE_TCHAR *n, - ACE_Service_Type_Impl *o, - const ACE_DLL &dll, - bool active); - ACE_Service_Type (const ACE_TCHAR *n, - ACE_Service_Type_Impl *o, - ACE_SHLIB_HANDLE handle, - bool active); - ~ACE_Service_Type (void); - - const ACE_TCHAR *name (void) const; - void name (const ACE_TCHAR *); - - const ACE_Service_Type_Impl *type (void) const; - void type (const ACE_Service_Type_Impl *, bool active = true); - - /// Is this just a stub for the real thing? - bool is_forward_declaration (void) const; - - int suspend (void) const; - int resume (void) const; - bool active (void) const; - void active (bool turnon); - - /// Calls @c fini on @c type_ - int fini (void); - - /// Check if the service has been fini'ed. - bool fini_called (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Get to the DLL's implentation - const ACE_DLL & dll (void) const; - - /// Sets the DLL - void dll (const ACE_DLL&); - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - /// Humanly readible name of svc. - const ACE_TCHAR *name_; - - /// Pointer to C++ object that implements the svc. - const ACE_Service_Type_Impl *type_; - - /// ACE_DLL representing the shared object file (non-zero if - /// dynamically linked). - mutable ACE_DLL dll_; - - /// true if svc is currently active, otherwise false. - bool active_; - - /// true if @c fini on @c type_ has already been called, otherwise false. - bool fini_already_called_; -}; - -/** - * @class ACE_Service_Object_Ptr - * - * @brief This is a smart pointer that holds onto the associated - * ACE_Service_Object * until the current scope is left, at - * which point the object's fini() hook is called and the - * service_object_ gets deleted. - * - * This class is similar to the Standard C++ Library class - * auto_ptr. It is used in conjunction with statically linked - * ACE_Service_Objects, as shown in the ./netsvcs/server/main.cpp example. - */ -class ACE_Export ACE_Service_Object_Ptr -{ -public: - // = Initialization and termination methods. - /// Acquire ownership of the @a so. - ACE_Service_Object_Ptr (ACE_Service_Object *so); - - /// Release the held ACE_Service_Object by calling its fini() hook. - ~ACE_Service_Object_Ptr (void); - - /// Smart pointer to access the underlying ACE_Service_Object. - ACE_Service_Object *operator-> (); - -private: - /// Holds the service object until we're done. - ACE_Service_Object *service_object_; -}; - -#if defined (ACE_OPENVMS) -/** - * @class ACE_Dynamic_Svc_Registrar - * - * @brief Used to register Service allocator function by its full name. - */ -class ACE_Dynamic_Svc_Registrar -{ -public: - ACE_Dynamic_Svc_Registrar (const ACE_TCHAR* alloc_name, - void* svc_allocator); -}; -#endif - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Service_Object.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_SERVICE_OBJECT_H */ diff --git a/externals/ace/Service_Object.inl b/externals/ace/Service_Object.inl deleted file mode 100644 index 6283f3e9981..00000000000 --- a/externals/ace/Service_Object.inl +++ /dev/null @@ -1,79 +0,0 @@ -// -*- C++ -*- -// $Id: Service_Object.inl 81388 2008-04-23 14:02:05Z johnnyw $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE ACE_Service_Object_Ptr::ACE_Service_Object_Ptr (ACE_Service_Object *so) - : service_object_ (so) -{ -} - -ACE_INLINE ACE_Service_Object_Ptr::~ACE_Service_Object_Ptr (void) -{ - this->service_object_->fini (); - delete this->service_object_; -} - -ACE_INLINE ACE_Service_Object * -ACE_Service_Object_Ptr::operator-> () -{ - return this->service_object_; -} - -ACE_INLINE const ACE_TCHAR * -ACE_Service_Type::name (void) const -{ - ACE_TRACE ("ACE_Service_Type::name"); - return this->name_; -} - -ACE_INLINE const ACE_Service_Type_Impl * -ACE_Service_Type::type (void) const -{ - ACE_TRACE ("ACE_Service_Type::type"); - return this->type_; -} - -ACE_INLINE void -ACE_Service_Type::type (const ACE_Service_Type_Impl *o, bool enabled) -{ - ACE_TRACE ("ACE_Service_Type::type"); - this->type_ = o; - ((ACE_Service_Type *) this)->active_ = enabled; -} - -ACE_INLINE bool -ACE_Service_Type::active (void) const -{ - ACE_TRACE ("ACE_Service_Type::active"); - return this->active_; -} - -ACE_INLINE void -ACE_Service_Type::active (bool turnon) -{ - ACE_TRACE ("ACE_Service_Type::active"); - this->active_ = turnon; -} - -ACE_INLINE bool -ACE_Service_Type::fini_called (void) const -{ - ACE_TRACE ("ACE_Service_Type::fini_called"); - return this->fini_already_called_; -} - -ACE_INLINE const ACE_DLL & ACE_Service_Type::dll () const -{ - ACE_TRACE ("ACE_Service_Type::dll"); - return this->dll_; -} - -ACE_INLINE void ACE_Service_Type::dll (const ACE_DLL &adll) -{ - ACE_TRACE ("ACE_Service_Type::dll"); - this->dll_ = adll; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - diff --git a/externals/ace/Service_Repository.cpp b/externals/ace/Service_Repository.cpp deleted file mode 100644 index 10195145ff1..00000000000 --- a/externals/ace/Service_Repository.cpp +++ /dev/null @@ -1,630 +0,0 @@ -// $Id: Service_Repository.cpp 90337 2010-05-28 20:00:49Z cbeaulac $ - -#include "ace/Service_Repository.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Service_Repository.inl" -#endif /* __ACE_INLINE__ */ - -#include "ace/Service_Types.h" -#include "ace/Object_Manager.h" -#include "ace/Log_Msg.h" -#include "ace/ACE.h" -#include "ace/OS_NS_unistd.h" -#include "ace/OS_NS_errno.h" -#include "ace/OS_NS_string.h" - -ACE_RCSID (ace, - Service_Repository, - "$Id: Service_Repository.cpp 90337 2010-05-28 20:00:49Z cbeaulac $") - - ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Service_Repository) - -/// Process-wide Service Repository. -ACE_Service_Repository *ACE_Service_Repository::svc_rep_ = 0; - -/// Controls whether the Service_Repository is deleted when we shut -/// down (we can only delete it safely if we created it)! -bool ACE_Service_Repository::delete_svc_rep_ = false; - -void -ACE_Service_Repository::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Service_Repository::dump"); -#endif /* ACE_HAS_DUMP */ -} - -ACE_Service_Repository * -ACE_Service_Repository::instance (size_t size) -{ - ACE_TRACE ("ACE_Service_Repository::instance"); - - if (ACE_Service_Repository::svc_rep_ == 0) - { - // Perform Double-Checked Locking Optimization. - ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, - *ACE_Static_Object_Lock::instance (), 0)); - if (ACE_Service_Repository::svc_rep_ == 0) - { - if (ACE_Object_Manager::starting_up () || - !ACE_Object_Manager::shutting_down ()) - { - ACE_NEW_RETURN (ACE_Service_Repository::svc_rep_, - ACE_Service_Repository (size), - 0); - ACE_Service_Repository::delete_svc_rep_ = true; - } - } - } - - return ACE_Service_Repository::svc_rep_; -} - -ACE_Service_Repository * -ACE_Service_Repository::instance (ACE_Service_Repository *s) -{ - ACE_TRACE ("ACE_Service_Repository::instance"); - ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, - *ACE_Static_Object_Lock::instance (), 0)); - - ACE_Service_Repository *t = ACE_Service_Repository::svc_rep_; - // We can't safely delete it since we don't know who created it! - ACE_Service_Repository::delete_svc_rep_ = false; - - ACE_Service_Repository::svc_rep_ = s; - return t; -} - -void -ACE_Service_Repository::close_singleton (void) -{ - ACE_TRACE ("ACE_Service_Repository::close_singleton"); - - ACE_MT (ACE_GUARD (ACE_Recursive_Thread_Mutex, ace_mon, - *ACE_Static_Object_Lock::instance ())); - - if (ACE_Service_Repository::delete_svc_rep_) - { - delete ACE_Service_Repository::svc_rep_; - ACE_Service_Repository::svc_rep_ = 0; - ACE_Service_Repository::delete_svc_rep_ = false; - } -} - -/// Initialize the Repository to a clean slate. -int -ACE_Service_Repository::open (size_t size) -{ - ACE_TRACE ("ACE_Service_Repository::open"); - - // Create a new array and swap it with the local array - array_type local_array (size); - this->service_array_.swap (local_array); - - return 0; -} - -ACE_Service_Repository::ACE_Service_Repository (size_t size) - : service_array_ (size) -{ - ACE_TRACE ("ACE_Service_Repository::ACE_Service_Repository"); -} - - -/// Finalize (call fini() and possibly delete) all the services. - -int -ACE_Service_Repository::fini (void) -{ - ACE_TRACE ("ACE_Service_Repository::fini"); - ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, this->lock_, -1)); - - int retval = 0; - // Do not be tempted to use the prefix decrement operator. Use - // postfix decrement operator since the index is unsigned and may - // wrap around the 0 - // - // debug output for empty service entries -#ifndef ACE_NLOGGING - if (ACE::debug ()) - { - for (size_t i = this->service_array_.size (); i-- != 0;) - { - ACE_Service_Type *s = - const_cast (this->service_array_[i]); - if (s == 0) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) SR::fini, repo=%@ [%d] -> 0\n"), - this, - i)); - } - } -#endif - // - // Remove all the Service_Object and Stream instances - // - for (size_t i = this->service_array_.size (); i-- != 0;) - { - // the services in reverse order. - ACE_Service_Type *s = - const_cast (this->service_array_[i]); - - if (s != 0 && - s->type () != 0 && - (s->type ()->service_type () != ACE_Service_Type::MODULE)) - { -#ifndef ACE_NLOGGING - if (ACE::debug ()) - { - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) SR::fini, repo=%@ [%d], ") - ACE_TEXT ("name=%s, type=%@, object=%@, active=%d\n"), - this, - i, - s->name (), - s->type (), - (s->type () != 0) ? s->type ()->object () : 0, - s->active ())); - } -#endif - - // Collect any errors. - retval += s->fini (); - } - } - // - // Remove all the Module instances - // - for (size_t i = this->service_array_.size (); i-- != 0;) - { - // the services in reverse order. - ACE_Service_Type *s = - const_cast (this->service_array_[i]); - - if (s != 0 && - s->type () != 0 && - (s->type ()->service_type () == ACE_Service_Type::MODULE)) - { -#ifndef ACE_NLOGGING - if (ACE::debug ()) - { - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) SR::fini, repo=%@ [%d], ") - ACE_TEXT ("name=%s, type=%@, object=%@, active=%d\n"), - this, - i, - s->name (), - s->type (), - (s->type () != 0) ? s->type ()->object () : 0, - s->active ())); - } -#endif - // Collect any errors. - retval += s->fini (); - } - } - return (retval == 0) ? 0 : -1; -} - - -/// Close down all the services. -int -ACE_Service_Repository::close (void) -{ - ACE_TRACE ("ACE_Service_Repository::close"); - ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, this->lock_, -1)); - -#ifndef ACE_NLOGGING - if(ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) SR::close - repo=%@, size=%d\n"), - this, - this->service_array_.size())); -#endif - - // Do not use the prefix decrement operator since the index is - // unsigned and may wrap around the 0. - for (size_t i = this->service_array_.size(); i-- != 0; ) - { - // Delete services in reverse order. - ACE_Service_Type *s = - const_cast (this->service_array_[i]); - -#ifndef ACE_NLOGGING - if(ACE::debug ()) - { - if (s == 0) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) SR::close - repo=%@ [%d] -> 0\n"), - this, - i)); - else - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) SR::close - repo=%@ [%d], name=%s, object=%@\n"), - this, - i, - s->name (), - s)); - } -#endif - delete s; - } - - this->service_array_.clear (); - - return 0; -} - -ACE_Service_Repository::~ACE_Service_Repository (void) -{ - ACE_TRACE ("ACE_Service_Repository::~ACE_Service_Repository"); -#ifndef ACE_NLOGGING - if(ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, "ACE (%P|%t) SR::, this=%@\n", this)); -#endif - this->close (); -} - -/// Locate an entry with @a name in the table. If @a ignore_suspended is -/// set then only consider services marked as resumed. If the caller -/// wants the located entry, pass back a pointer to the located entry -/// via @a srp. If @a name is not found -1 is returned. If @a name is -/// found, but it is suspended and the caller wants to ignore suspended -/// services a -2 is returned. Must be called with locks held. -int -ACE_Service_Repository::find_i (const ACE_TCHAR name[], - size_t &slot, - const ACE_Service_Type **srp, - bool ignore_suspended) const -{ - ACE_TRACE ("ACE_Service_Repository::find_i"); - size_t i = 0; - array_type::const_iterator element = this->service_array_.end (); - - for (i = 0; i < this->service_array_.size(); i++) - { - array_type::const_iterator iter = this->service_array_.find (i); - if (iter != this->service_array_.end () - && (*iter).second != 0 // skip any empty slots - && ACE_OS::strcmp (name, (*iter).second->name ()) == 0) - { - element = iter; - break; - } - } - - if (element != this->service_array_.end ()) - { - slot = i; - if ((*element).second->fini_called ()) - { - if (srp != 0) - *srp = 0; - return -1; - } - - if (srp != 0) - *srp = (*element).second; - - if (ignore_suspended - && (*element).second->active () == 0) - return -2; - - return 0; - } - - return -1; -} - - -/// @brief Relocate (a static) service to another DLL. -/// -/// Works by having the service type keep a reference to a specific -/// DLL. No locking, caller makes sure calling it is safe. You can -/// forcefully relocate any DLLs in the given range, not only the -/// static ones - but that will cause Very Bad Things (tm) to happen. -int -ACE_Service_Repository::relocate_i (size_t begin, - size_t end, - const ACE_DLL& adll) -{ - ACE_SHLIB_HANDLE new_handle = adll.get_handle (0); - - for (size_t i = begin; i < end; i++) - { - ACE_Service_Type *type = - const_cast (this->service_array_[i]); - - ACE_SHLIB_HANDLE old_handle = (type == 0) ? ACE_SHLIB_INVALID_HANDLE - : type->dll ().get_handle (0); - -#ifndef ACE_NLOGGING - if (ACE::debug ()) - { - if (type == 0) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) SR::relocate_i - repo=%@ [%d]") - ACE_TEXT (": skipping empty slot\n"), - this, - i)); - else - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) SR::relocate_i - repo=%@ [%d]") - ACE_TEXT (": trying name=%s, handle: %d -> %d\n"), - this, - i, - type->name (), - old_handle, - new_handle)); - } -#endif - - if (type != 0 // skip any gaps - && old_handle == ACE_SHLIB_INVALID_HANDLE - && new_handle != old_handle) - { -#ifndef ACE_NLOGGING - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) SR::relocate_i - repo=%@ [%d]") - ACE_TEXT (": relocating name=%s, handle: %d -> %d\n"), - this, - i, - type->name (), - old_handle, - new_handle)); -#endif - type->dll (adll); // ups the refcount on adll - } - } - - return 0; -} - -int -ACE_Service_Repository::find (const ACE_TCHAR name[], - const ACE_Service_Type **srp, - bool ignore_suspended) const -{ - ACE_TRACE ("ACE_Service_Repository::find"); - ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, this->lock_, -1)); - size_t ignore_location = 0; - return this->find_i (name, ignore_location, srp, ignore_suspended); -} - -/// Insert the ACE_Service_Type SR into the repository. Note that -/// services may be inserted either resumed or suspended. Using same -/// name as in an existing service causes the delete () to be called -/// for the old one, i.e. make sure @code sr is allocated on the heap! -int -ACE_Service_Repository::insert (const ACE_Service_Type *sr) -{ - ACE_TRACE ("ACE_Service_Repository::insert"); - - size_t i = 0; - int return_value = -1; - ACE_Service_Type const *s = 0; - - // Establish scope for locking while manipulating the service - // storage - { - // @TODO: Do we need a recursive mutex here? - ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, - ace_mon, - this->lock_, - -1)); - - return_value = find_i (sr->name (), i, &s, false); - - // Adding an entry. - if (s != 0) - { - this->service_array_[i] = sr; - } - else - { - // New services are always added where current_size_ points, - // because if any DLL relocation needs to happen, it will be - // performed on services with indexes between some old - // current_size_ and the new current_size_ value. See - // ACE_Service_Type_Dynamic_Guard ctor and dtor for details. - - if (i < this->service_array_.size ()) - i = this->service_array_.size (); - - this->service_array_[i] = sr; - return_value = 0; - } - } -#ifndef ACE_NLOGGING - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) SR::insert - repo=%@ [%d],") - ACE_TEXT (" name=%s (%C) (type=%@, object=%@, active=%d)\n"), - this, - i, - sr->name(), - (return_value == 0 ? ((s==0) ? "new" : "replacing") : "failed"), - sr->type (), - (sr->type () != 0) ? sr->type ()->object () : 0, - sr->active ())); -#endif - - // If necessary, delete but outside the lock. (s may be 0, but - // that's okay, too) - delete s; - - if (return_value == -1) - ACE_OS::last_error (ENOSPC); - - return return_value; -} - -/// Resume a service that was previously suspended. -int -ACE_Service_Repository::resume (const ACE_TCHAR name[], - const ACE_Service_Type **srp) -{ - ACE_TRACE ("ACE_Service_Repository::resume"); - ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, this->lock_, -1)); - - size_t i = 0; - if (-1 == this->find_i (name, i, srp, 0)) - return -1; - - return this->service_array_[i]->resume (); -} - -/// Suspend a service so that it will not be considered active under -/// most circumstances by other portions of the ACE_Service_Repository. -int -ACE_Service_Repository::suspend (const ACE_TCHAR name[], - const ACE_Service_Type **srp) -{ - ACE_TRACE ("ACE_Service_Repository::suspend"); - ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, this->lock_, -1)); - size_t i = 0; - if (-1 == this->find_i (name, i, srp, 0)) - return -1; - - return this->service_array_[i]->suspend (); -} - -/** - * @brief Completely remove a @a name entry from the Repository and - * dynamically unlink it if it was originally dynamically linked. - */ -int -ACE_Service_Repository::remove (const ACE_TCHAR name[], ACE_Service_Type **ps) -{ - ACE_TRACE ("ACE_Service_Repository::remove"); - ACE_Service_Type *s = 0; - { - ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, this->lock_, -1)); - - // Not found!? - if (this->remove_i (name, &s) == -1) - return -1; - } - - if (ps != 0) - *ps = s; - else - delete s; - return 0; -} - -/** - * @brief Completely remove a @a name entry from the Repository and - * dynamically unlink it if it was originally dynamically linked. - * - * Return a ptr to the entry in @code ps. There is no locking so make - * sure you hold the repo lock when calling. - * - * Since the order of services in the Respository matters, we can't - * simply overwrite the entry being deleted with the last and - * decrement the @c current_size by 1. A good example of why the order - * matters is a dynamic service, in whose DLL there is at least one - * static service. In order to prevent SEGV during finalization, those - * static services must be finalized _before_the dynamic service that - * owns them. Otherwice the TEXT segment, containing the code for the - * static service's desructor may be unloaded with the DLL. - * - * Neither can we "pack" the array because this may happen inside the - * scope of a Service_Dynamic_Guard, which caches an index where - * loading of a DLL started in order to relocate dependent services. - */ -int -ACE_Service_Repository::remove_i (const ACE_TCHAR name[], ACE_Service_Type **ps) -{ - size_t i = 0; - if (-1 == this->find_i (name, i, 0, false)) - return -1; // Not found - - // We may need the old ptr - to be delete outside the lock! - *ps = const_cast (this->service_array_[i]); - -#ifndef ACE_NLOGGING - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ACE (%P|%t) SR::remove_i - repo=%@ [%d],") - ACE_TEXT (" name=%s (removed) (type=%@, active=%d)\n"), - this, - i, - name, - *ps, - (*ps)->active ())); -#endif - - this->service_array_[i] = 0; // simply leave a gap - return 0; -} - -ACE_ALLOC_HOOK_DEFINE(ACE_Service_Repository_Iterator) - -void -ACE_Service_Repository_Iterator::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Service_Repository_Iterator::dump"); -#endif /* ACE_HAS_DUMP */ -} - -/// Initializes the iterator and skips over any suspended entries at -/// the beginning of the table, if necessary. Note, you must not -/// perform destructive operations on elements during this iteration... -ACE_Service_Repository_Iterator::ACE_Service_Repository_Iterator - (ACE_Service_Repository &sr, bool ignored_suspended) - : svc_rep_ (sr), - next_ (0), - ignore_suspended_ (ignored_suspended) -{ - while (!(done() || valid())) - this->next_++; -} - -/// Obtains a pointer to the next valid service in the table. If there -/// are no more entries, returns 0, else 1. -int -ACE_Service_Repository_Iterator::next (const ACE_Service_Type *&sr) -{ - ACE_TRACE ("ACE_Service_Repository_Iterator::next"); - - if (done ()) - return 0; - - sr = this->svc_rep_.service_array_[this->next_]; - return 1; -} - -/// Advance the iterator by the proper amount. If we are ignoring -/// suspended entries and the current entry is suspended, then we must -/// skip over this entry. Otherwise, we must advance the NEXT index to -/// reference the next valid service entry. -int -ACE_Service_Repository_Iterator::advance (void) -{ - ACE_TRACE ("ACE_Service_Repository_Iterator::advance"); - - if (done()) return 0; - - do this->next_++; while (!(done () || valid ())); - - return !done(); -} - -bool -ACE_Service_Repository_Iterator::valid (void) const -{ - ACE_TRACE ("ACE_Service_Repository_Iterator::valid"); - if (!this->ignore_suspended_) - return (this->svc_rep_.service_array_[this->next_] != 0); // skip over gaps - - return (this->svc_rep_.service_array_[this->next_] != 0 - && this->svc_rep_.service_array_[this->next_]->active ()); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Service_Repository.h b/externals/ace/Service_Repository.h deleted file mode 100644 index 9d03b113381..00000000000 --- a/externals/ace/Service_Repository.h +++ /dev/null @@ -1,271 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Service_Repository.h - * - * $Id: Service_Repository.h 91016 2010-07-06 11:29:50Z johnnyw $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_SERVICE_REPOSITORY_H -#define ACE_SERVICE_REPOSITORY_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Default_Constants.h" -#include "ace/Recursive_Thread_Mutex.h" -#include "ace/Array_Map.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -class ACE_Service_Type; -class ACE_DLL; - -#define ACE_Component_Repository ACE_Service_Repository -/** - * @class ACE_Service_Repository - * - * @brief Contains all the services offered by a Service - * Configurator-based application. - * - * This class contains a vector of ACE_Service_Types *'s and - * allows an administrative entity to centrally manage and - * control the behavior of application services. Note that if - * services are removed from the middle of the repository the - * order won't necessarily be maintained since the @a remove - * method performs compaction. However, the common case is not - * to remove services, so typically they are deleted in the - * reverse order that they were added originally. - */ -class ACE_Export ACE_Service_Repository -{ -public: - friend class ACE_Service_Repository_Iterator; - - enum - { - DEFAULT_SIZE = ACE_DEFAULT_SERVICE_REPOSITORY_SIZE - }; - - // = Initialization and termination methods. - /// Initialize the repository. - ACE_Service_Repository (size_t size = DEFAULT_SIZE); - - /// Initialize the repository. - int open (size_t size = DEFAULT_SIZE); - - /// Close down the repository and free up dynamically allocated - /// resources. - ~ACE_Service_Repository (void); - - /// Close down the repository and free up dynamically allocated - /// resources. - int close (void); - - /// Finalize all the services by calling fini() and deleting - /// dynamically allocated services. - int fini (void); - - /// Get pointer to a process-wide ACE_Service_Repository. - static ACE_Service_Repository * instance - (size_t size = ACE_Service_Repository::DEFAULT_SIZE); - - /// Set pointer to a process-wide ACE_Service_Repository and return - /// existing pointer. - static ACE_Service_Repository *instance (ACE_Service_Repository *); - - /// Delete the dynamically allocated Singleton. - static void close_singleton (void); - - // = Search structure operations (all acquire locks as necessary). - - /// Insert a new service record. Returns -1 when the service repository - /// is full and 0 on success. - int insert (const ACE_Service_Type *sr); - - /** - * Locate a named entry in the service table, optionally ignoring - * suspended entries. - * - * @param name The name of the service to search for. - * @param srp Optional; if not 0, it is a pointer to a location - * to receive the ACE_Service_Type pointer for the - * located service. Meaningless if this method - * returns -1. - * @param ignore_suspended If true, the search ignores suspended services. - * - * @retval 0 Named service was located. - * @retval -1 Named service was not found. - * @retval -2 Named service was found, but is suspended and - * @a ignore_suspended is true. - */ - int find (const ACE_TCHAR name[], - const ACE_Service_Type **srp = 0, - bool ignore_suspended = true) const; - - /// Remove an existing service record. If @a sr == 0, the service record - /// is deleted before control is returned to the caller. If @a sr != 0, - /// the service's record is removed from the repository, but not deleted; - /// *sr receives the service record pointer and the caller is responsible - /// for properly disposing of it. - int remove (const ACE_TCHAR name[], ACE_Service_Type **sr = 0); - - // = Liveness control - /// Resume a service record. - int resume (const ACE_TCHAR name[], const ACE_Service_Type **srp = 0); - - /// Suspend a service record. - int suspend (const ACE_TCHAR name[], const ACE_Service_Type **srp = 0); - - /// Return the current size of the repository. - size_t current_size (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - - friend class ACE_Service_Type_Dynamic_Guard; - - /// Remove an existing service record. It requires @a sr != 0, which - /// receives the service record pointer and the caller is - /// responsible for properly disposing of it. - int remove_i (const ACE_TCHAR[], ACE_Service_Type **sr); - - /** - * Locate a named entry in the service table, optionally ignoring - * suspended entries. - * - * @param service_name The name of the service to search for. - * @param slot Receives the position index of the service if it - * is found. Contents are meaningless if this method - * returns -1. - * @param srp Optional; if not 0, it is a pointer to a location - * to receive the ACE_Service_Type pointer for the - * located service. Meaningless if this method - * returns -1. - * @param ignore_suspended If true, the search ignores suspended services. - * - * @retval 0 Named service was located; index in the table is set in - * @a slot. - * @retval -1 Named service was not found. - * @retval -2 Named service was found, but is suspended and - * @a ignore_suspended is true. - */ - int find_i (const ACE_TCHAR service_name[], - size_t &slot, - const ACE_Service_Type **srp = 0, - bool ignore_suspended = true) const; - - /// @brief Relocate (static) services to another DLL. - /// - /// If any have been registered in the context of a "forward - /// declaration" guard, those really aren't static services. Their - /// code is in the DLL's code segment, or in one of the dependent - /// DLLs. Therefore, such services need to be associated with the - /// proper DLL in order to prevent failures upon finalization. The - /// method locks the repo. - /// - /// Works by having the service type keep a reference to a specific - /// DLL. No locking, caller makes sure calling it is safe. You can - /// forcefully relocate any DLLs in the given range, not only the - /// static ones - but that will cause Very Bad Things (tm) to happen. - int relocate_i (size_t begin, - size_t end, - const ACE_DLL &adll); - - /// The typedef of the array used to store the services. - typedef ACE_Array_Map array_type; - - /// Contains all the configured services. - array_type service_array_; - - /// Pointer to a process-wide ACE_Service_Repository. - static ACE_Service_Repository *svc_rep_; - - /// Must delete the @c svc_rep_ if true. - static bool delete_svc_rep_; - -#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) - /// Synchronization variable for the MT_SAFE Repository - mutable ACE_Recursive_Thread_Mutex lock_; -#endif /* ACE_MT_SAFE */ -}; - -/** - * @class ACE_Service_Repository_Iterator - * - * @brief Iterate through the ACE_Service_Repository. - * - * Make sure not to delete entries as the iteration is going on - * since this class is not designed as a robust iterator. - */ -class ACE_Export ACE_Service_Repository_Iterator -{ -public: - // = Initialization and termination methods. - /// Constructor initializes the iterator. - ACE_Service_Repository_Iterator (ACE_Service_Repository &sr, - bool ignored_suspended = true); - - /// Destructor. - ~ACE_Service_Repository_Iterator (void); - - -public: - // = Iteration methods. - - /// Pass back the @a next_item that hasn't been seen in the repository. - /// Returns 0 when all items have been seen, else 1. - int next (const ACE_Service_Type *&next_item); - - /// Returns 1 when all items have been seen, else 0. - int done (void) const; - - /// Move forward by one element in the repository. Returns 0 when all the - /// items in the set have been seen, else 1. - int advance (void); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - bool valid (void) const; - -private: - ACE_Service_Repository_Iterator (const ACE_Service_Repository_Iterator&); - - /// Reference to the Service Repository we are iterating over. - ACE_Service_Repository &svc_rep_; - - /// Next index location that we haven't yet seen. - size_t next_; - - /// Are we ignoring suspended services? - bool const ignore_suspended_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Service_Repository.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" - -#endif /* _SERVICE_REPOSITORY_H */ diff --git a/externals/ace/Service_Repository.inl b/externals/ace/Service_Repository.inl deleted file mode 100644 index 1645f380335..00000000000 --- a/externals/ace/Service_Repository.inl +++ /dev/null @@ -1,38 +0,0 @@ -// -*- C++ -*- -// -// $Id: Service_Repository.inl 84170 2009-01-15 13:31:50Z johnnyw $ - -// Returns a count of the number of currently valid entries (counting -// both resumed and suspended entries). - -#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) -#include "ace/Guard_T.h" -#include "ace/Thread_Mutex.h" -#endif /* ACE_MT_SAFE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE size_t -ACE_Service_Repository::current_size (void) const -{ - ACE_TRACE ("ACE_Service_Repository::current_size"); - ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, - ace_mon, - (ACE_Recursive_Thread_Mutex &) this->lock_, 0)); - return this->service_array_.size (); -} - -ACE_INLINE int -ACE_Service_Repository_Iterator::done (void) const -{ - ACE_TRACE ("ACE_Service_Repository_Iterator::done"); - - return this->next_ >= this->svc_rep_.current_size (); -} - -ACE_INLINE -ACE_Service_Repository_Iterator::~ACE_Service_Repository_Iterator (void) -{ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Service_Templates.h b/externals/ace/Service_Templates.h deleted file mode 100644 index d05d0d611d2..00000000000 --- a/externals/ace/Service_Templates.h +++ /dev/null @@ -1,29 +0,0 @@ - -//============================================================================= -/** - * @file Service_Templates.h - * - * $Id: Service_Templates.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Priyanka Gontla - */ -//============================================================================= - - -#ifndef ACE_SERVICE_TEMPLATES_H -#define ACE_SERVICE_TEMPLATES_H -#include /**/ "ace/pre.h" - -#include "ace/Svc_Conf.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Auto_Ptr.h" -#include "ace/Thread_Manager.h" -#include "ace/Stream_Modules.h" -#include "ace/Stream.h" - -#include /**/ "ace/post.h" -#endif /* ACE_SERVICE_TEMPLATES_H */ diff --git a/externals/ace/Service_Types.cpp b/externals/ace/Service_Types.cpp deleted file mode 100644 index 3465d774d53..00000000000 --- a/externals/ace/Service_Types.cpp +++ /dev/null @@ -1,461 +0,0 @@ -// $Id: Service_Types.cpp 90072 2010-05-04 21:34:39Z cbeaulac $ - -#include "ace/Service_Types.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Service_Types.inl" -#endif /* __ACE_INLINE__ */ - -#include "ace/Stream_Modules.h" -#include "ace/Stream.h" -#include "ace/OS_NS_stdio.h" -#include "ace/OS_NS_string.h" - - -ACE_RCSID (ace, - Service_Types, - "$Id: Service_Types.cpp 90072 2010-05-04 21:34:39Z cbeaulac $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -typedef ACE_Stream MT_Stream; -typedef ACE_Module MT_Module; -typedef ACE_Task MT_Task; - -ACE_ALLOC_HOOK_DEFINE(ACE_Service_Type_Impl) - -void -ACE_Service_Type_Impl::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Service_Type_Impl::dump"); -#endif /* ACE_HAS_DUMP */ -} - -ACE_Service_Type_Impl::ACE_Service_Type_Impl (void *so, - const ACE_TCHAR *s_name, - u_int f, - ACE_Service_Object_Exterminator gobbler, - int stype) - : name_ (0), - obj_ (so), - gobbler_ (gobbler), - flags_ (f), - service_type_ (stype) -{ - ACE_TRACE ("ACE_Service_Type_Impl::ACE_Service_Type_Impl"); - this->name (s_name); -} - -ACE_Service_Type_Impl::~ACE_Service_Type_Impl (void) -{ - ACE_TRACE ("ACE_Service_Type_Impl::~ACE_Service_Type_Impl"); - - // It's ok to call this, even though we may have already deleted it - // in the fini() method since it would then be NULL. - delete [] const_cast (this->name_); -} - -int -ACE_Service_Type_Impl::fini (void) const -{ - ACE_TRACE ("ACE_Service_Type_Impl::fini"); - - delete [] const_cast (this->name_); - (const_cast (this))->name_ = 0; - - if (ACE_BIT_ENABLED (this->flags_, - ACE_Service_Type::DELETE_OBJ)) - { - if (gobbler_ != 0) - gobbler_ (this->object ()); - else - // Cast to remove const-ness. - operator delete ((void *) this->object ()); - } - - if (ACE_BIT_ENABLED (this->flags_, - ACE_Service_Type::DELETE_THIS)) - delete const_cast (this); - - return 0; -} - -ACE_Service_Object_Type::ACE_Service_Object_Type (void *so, - const ACE_TCHAR *s_name, - u_int f, - ACE_Service_Object_Exterminator gobbler, - int stype) - : ACE_Service_Type_Impl (so, s_name, f, gobbler, stype) - , initialized_ (-1) -{ - ACE_TRACE ("ACE_Service_Object_Type::ACE_Service_Object_Type"); -} - -int -ACE_Service_Object_Type::init (int argc, ACE_TCHAR *argv[]) const -{ - ACE_TRACE ("ACE_Service_Object_Type::init"); - - void * const obj = this->object (); - - ACE_Service_Object * const so = - static_cast (obj); - - if (so == 0) - return -1; - - this->initialized_ = so->init (argc, argv); - - return this->initialized_; -} - -int -ACE_Service_Object_Type::fini (void) const -{ - ACE_TRACE ("ACE_Service_Object_Type::fini"); - - void * const obj = this->object (); - - ACE_Service_Object * const so = - static_cast (obj); - - // Call fini() if an only if, the object was successfuly - // initialized, i.e. init() returned 0. This is necessary to - // maintain the ctor/dtor-like semantics for init/fini. - if (so != 0 && this->initialized_ == 0) - so->fini (); - - return ACE_Service_Type_Impl::fini (); -} - -ACE_Service_Object_Type::~ACE_Service_Object_Type (void) -{ - ACE_TRACE ("ACE_Service_Object_Type::~ACE_Service_Object_Type"); -} - -int -ACE_Service_Object_Type::suspend (void) const -{ - ACE_TRACE ("ACE_Service_Object_Type::suspend"); - return static_cast (this->object ())->suspend (); -} - -int -ACE_Service_Object_Type::resume (void) const -{ - ACE_TRACE ("ACE_Service_Object_Type::resume"); - return static_cast (this->object ())->resume (); -} - -int -ACE_Service_Object_Type::info (ACE_TCHAR **str, size_t len) const -{ - ACE_TRACE ("ACE_Service_Object_Type::info"); - return static_cast (this->object ())->info (str, len); -} - -ACE_ALLOC_HOOK_DEFINE(ACE_Module_Type) - -void -ACE_Module_Type::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Module_Type::dump"); -#endif /* ACE_HAS_DUMP */ -} - -ACE_Module_Type::ACE_Module_Type (void *m, - const ACE_TCHAR *m_name, - u_int f, - int stype) - : ACE_Service_Type_Impl (m, m_name, f, 0, stype) -{ - ACE_TRACE ("ACE_Module_Type::ACE_Module_Type"); -} - -ACE_Module_Type::~ACE_Module_Type (void) -{ - ACE_TRACE ("ACE_Module_Type::~ACE_Module_Type"); -} - -int -ACE_Module_Type::init (int argc, ACE_TCHAR *argv[]) const -{ - ACE_TRACE ("ACE_Module_Type::init"); - void *obj = this->object (); - MT_Module *mod = (MT_Module *) obj; - // - // Change the Module's name to what's in the svc.conf file. - // We must do this so the names match up so everything shuts - // down properly during the call to ACE_Stream_Type::fini - // which calls MT_Stream::remove([name]) for all the modules. - // If the calls to remove fail, we end up with a double delete - // during shutdown. Bugzilla #3847 - // - mod->name (this->name_); - MT_Task *reader = mod->reader (); - MT_Task *writer = mod->writer (); - - if (reader->init (argc, argv) == -1 - || writer->init (argc, argv) == -1) - return -1; - else - return 0; -} - -int -ACE_Module_Type::suspend (void) const -{ - ACE_TRACE ("ACE_Module_Type::suspend"); - void *obj = this->object (); - MT_Module *mod = (MT_Module *) obj; - MT_Task *reader = mod->reader (); - MT_Task *writer = mod->writer (); - - if (reader->suspend () == -1 - || writer->suspend () == -1) - return -1; - else - return 0; -} - -int -ACE_Module_Type::resume (void) const -{ - ACE_TRACE ("ACE_Module_Type::resume"); - void *obj = this->object (); - MT_Module *mod = (MT_Module *) obj; - MT_Task *reader = mod->reader (); - MT_Task *writer = mod->writer (); - - if (reader->resume () == -1 - || writer->resume () == -1) - return -1; - else - return 0; -} - -// Note, these operations are somewhat too familiar with the -// implementation of ACE_Module and ACE_Module::close... - -int -ACE_Module_Type::fini (void) const -{ - ACE_TRACE ("ACE_Module_Type::fini"); - void *obj = this->object (); - MT_Module *mod = (MT_Module *) obj; - MT_Task *reader = mod->reader (); - MT_Task *writer = mod->writer (); - - if (reader != 0) - reader->fini (); - - if (writer != 0) - writer->fini (); - - // Close the module and delete the memory. - mod->close (MT_Module::M_DELETE); - return ACE_Service_Type_Impl::fini (); -} - -int -ACE_Module_Type::info (ACE_TCHAR **str, size_t len) const -{ - ACE_TRACE ("ACE_Module_Type::info"); - ACE_TCHAR buf[BUFSIZ]; - - ACE_OS::sprintf (buf, - ACE_TEXT ("%s\t %s"), - this->name (), - ACE_TEXT ("# ACE_Module\n")); - - if (*str == 0 && (*str = ACE_OS::strdup (buf)) == 0) - return -1; - else - ACE_OS::strsncpy (*str, buf, len); - return static_cast (ACE_OS::strlen (buf)); -} - -void -ACE_Module_Type::link (ACE_Module_Type *n) -{ - ACE_TRACE ("ACE_Module_Type::link"); - this->link_ = n; -} - -ACE_Module_Type * -ACE_Module_Type::link (void) const -{ - ACE_TRACE ("ACE_Module_Type::link"); - return this->link_; -} - -ACE_ALLOC_HOOK_DEFINE(ACE_Stream_Type) - -void -ACE_Stream_Type::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Stream_Type::dump"); -#endif /* ACE_HAS_DUMP */ -} - -int -ACE_Stream_Type::init (int, ACE_TCHAR *[]) const -{ - ACE_TRACE ("ACE_Stream_Type::init"); - return 0; -} - -int -ACE_Stream_Type::suspend (void) const -{ - ACE_TRACE ("ACE_Stream_Type::suspend"); - - for (ACE_Module_Type *m = this->head_; - m != 0; - m = m->link ()) - m->suspend (); - - return 0; -} - -int -ACE_Stream_Type::resume (void) const -{ - ACE_TRACE ("ACE_Stream_Type::resume"); - - for (ACE_Module_Type *m = this->head_; - m != 0; - m = m->link ()) - m->resume (); - - return 0; -} - -ACE_Stream_Type::ACE_Stream_Type (void *s, - const ACE_TCHAR *s_name, - u_int f, - int stype) - : ACE_Service_Type_Impl (s, s_name, f, 0, stype), - head_ (0) -{ - ACE_TRACE ("ACE_Stream_Type::ACE_Stream_Type"); -} - -ACE_Stream_Type::~ACE_Stream_Type (void) -{ - ACE_TRACE ("ACE_Stream_Type::~ACE_Stream_Type"); -} - -int -ACE_Stream_Type::info (ACE_TCHAR **str, size_t len) const -{ - ACE_TRACE ("ACE_Stream_Type::info"); - ACE_TCHAR buf[BUFSIZ]; - - ACE_OS::sprintf (buf, - ACE_TEXT ("%s\t %s"), - this->name (), - ACE_TEXT ("# STREAM\n")); - - if (*str == 0 && (*str = ACE_OS::strdup (buf)) == 0) - return -1; - else - ACE_OS::strsncpy (*str, buf, len); - return static_cast (ACE_OS::strlen (buf)); -} - -int -ACE_Stream_Type::fini (void) const -{ - ACE_TRACE ("ACE_Stream_Type::fini"); - void *obj = this->object (); - MT_Stream *str = (MT_Stream *) obj; - - for (ACE_Module_Type *m = this->head_; m != 0;) - { - ACE_Module_Type *t = m->link (); - - // Final arg is an indication to *not* delete the Module. - str->remove (m->name (), - MT_Module::M_DELETE_NONE); - m = t; - } - str->close (); - - return ACE_Service_Type_Impl::fini (); -} - -// Locate and remove from the ACE_Stream. - -int -ACE_Stream_Type::remove (ACE_Module_Type *mod) -{ - ACE_TRACE ("ACE_Stream_Type::remove"); - - ACE_Module_Type *prev = 0; - void *obj = this->object (); - MT_Stream *str = (MT_Stream *) obj; - int result = 0; - - for (ACE_Module_Type *m = this->head_; m != 0; ) - { - // We need to do this first so we don't bomb out if we delete m! - ACE_Module_Type *link = m->link (); - - if (m == mod) - { - if (prev == 0) - this->head_ = link; - else - prev->link (link); - - // Final arg is an indication to *not* delete the Module. - if (str->remove (m->name (), - MT_Module::M_DELETE_NONE) == -1) - result = -1; - - // Do not call m->fini (); as this will result in a double delete - // of the ACE_Module_type when ACE_Service_Repository::fini is called - } - else - prev = m; - - m = link; - } - - return result; -} - -int -ACE_Stream_Type::push (ACE_Module_Type *new_module) -{ - ACE_TRACE ("ACE_Stream_Type::push"); - void *obj = this->object (); - MT_Stream *str = (MT_Stream *) obj; - - new_module->link (this->head_); - this->head_ = new_module; - obj = new_module->object (); - return str->push ((MT_Module *) obj); -} - -ACE_Module_Type * -ACE_Stream_Type::find (const ACE_TCHAR *module_name) const -{ - ACE_TRACE ("ACE_Stream_Type::find"); - - for (ACE_Module_Type *m = this->head_; - m != 0; - m = m->link ()) - if (ACE_OS::strcmp (m->name (), module_name) == 0) - return m; - - return 0; -} - -// @@@ Eliminated ommented out explicit template instantiation code - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Service_Types.h b/externals/ace/Service_Types.h deleted file mode 100644 index 70a7ac4f566..00000000000 --- a/externals/ace/Service_Types.h +++ /dev/null @@ -1,221 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file Service_Types.h - * - * $Id: Service_Types.h 89925 2010-04-19 12:49:11Z cbeaulac $ - * - * @author Douglas C. Schmidt - */ -//========================================================================== - -#ifndef ACE_SERVICE_TYPE_H -#define ACE_SERVICE_TYPE_H - -#include /**/ "ace/pre.h" - -#include "ace/Service_Object.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Service_Type_Impl - * - * @brief The abstract base class of the hierarchy that defines the - * contents of the ACE_Service_Repository. The subclasses of - * this class allow the configuration of ACE_Service_Objects, - * ACE_Modules, and ACE_Streams. - * - * This class provides the root of the implementation hierarchy - * of the "Bridge" pattern. It maintains a pointer to the - * appropriate type of service implementation, i.e., - * ACE_Service_Object, ACE_Module, or ACE_Stream. - */ -class ACE_Export ACE_Service_Type_Impl -{ -public: - // = Initialization and termination methods. - ACE_Service_Type_Impl (void *object, - const ACE_TCHAR *s_name, - u_int flags = 0, - ACE_Service_Object_Exterminator gobbler = 0, - int stype = ACE_Service_Type::INVALID_TYPE); - virtual ~ACE_Service_Type_Impl (void); - - // = Pure virtual interface (must be defined by the subclass). - virtual int suspend (void) const = 0; - virtual int resume (void) const = 0; - virtual int init (int argc, ACE_TCHAR *argv[]) const = 0; - virtual int fini (void) const; - virtual int info (ACE_TCHAR **str, size_t len) const = 0; - - /// The pointer to the service. - void *object (void) const; - - /// Get the name of the service. - const ACE_TCHAR *name (void) const; - - /// Set the name of the service. - void name (const ACE_TCHAR *); - - /// Dump the state of an object. - void dump (void) const; - - /// get the service_type of this service - int service_type (void) const; - - /// set the service_type of this service - void service_type (int stype); - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - /// Name of the service. - const ACE_TCHAR *name_; - - /// Pointer to object that implements the service. This actually - /// points to an ACE_Service_Object, ACE_Module, or ACE_Stream. - void *obj_; - - /// Destroy function to deallocate obj_. - ACE_Service_Object_Exterminator gobbler_; - - /// Flags that control serivce behavior (particularly deletion). - u_int flags_; - - /// type of this service - /// Used to properly manage the lifecycle of ACE_Modules and ACE_Streams - /// during shutdown - int service_type_; -}; - -/** - * @class ACE_Service_Object_Type - * - * @brief Define the methods for handling the configuration of - * ACE_Service_Objects. - */ -class ACE_Export ACE_Service_Object_Type : public ACE_Service_Type_Impl -{ -public: - // = Initialization method. - ACE_Service_Object_Type (void *so, - const ACE_TCHAR *name, - u_int flags = 0, - ACE_Service_Object_Exterminator gobbler = 0, - int stype = ACE_Service_Type::SERVICE_OBJECT); - - ~ACE_Service_Object_Type (void); - - // = Implement the hooks for . - virtual int suspend (void) const; - virtual int resume (void) const; - virtual int init (int argc, ACE_TCHAR *argv[]) const; - virtual int fini (void) const; - virtual int info (ACE_TCHAR **str, size_t len) const; - -private: - /// Holds the initialization status (result of object->init()) - mutable int initialized_; -}; - -/** - * @class ACE_Module_Type - * - * @brief Define the methods for handling the configuration of - * ACE_Modules. - */ -class ACE_Export ACE_Module_Type : public ACE_Service_Type_Impl -{ -public: - // = Initialization method. - ACE_Module_Type (void *m, // Really an ACE_Module *. - const ACE_TCHAR *identifier, - u_int flags = 0, - int stype = ACE_Service_Type::MODULE); - - ~ACE_Module_Type (void); - - // = Implement the hooks for . - virtual int suspend (void) const; - virtual int resume (void) const; - virtual int init (int argc, ACE_TCHAR *argv[]) const; - virtual int fini (void) const; - virtual int info (ACE_TCHAR **str, size_t len) const; - - /// Get the link pointer. - ACE_Module_Type *link (void) const; - - /// Set the link pointer. - void link (ACE_Module_Type *); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - /// Pointer to the next ACE_Module_Type in an ACE_Stream_Type. - ACE_Module_Type *link_; -}; - -/** - * @class ACE_Stream_Type - * - * @brief Define the methods for handling the configuration of - * ACE_Streams. - */ -class ACE_Export ACE_Stream_Type : public ACE_Service_Type_Impl -{ -public: - // = Initialization method. - ACE_Stream_Type (void *s, // Really an ACE_Stream *. - const ACE_TCHAR *identifier, - u_int flags = 0, - int stype = ACE_Service_Type::STREAM); - - ~ACE_Stream_Type (void); - - // = Implement the hooks for . - virtual int suspend (void) const; - virtual int resume (void) const; - virtual int init (int argc, ACE_TCHAR *argv[]) const; - virtual int fini (void) const; - virtual int info (ACE_TCHAR **str, size_t len) const; - - /// Add a new ACE_Module to the top of the ACE_Stream. - int push (ACE_Module_Type *new_module); - - /// Search for @a module and remove it from the ACE_Stream. - int remove (ACE_Module_Type *module); - - /// Locate the ACE_Module with @a mod_name. - ACE_Module_Type *find (const ACE_TCHAR *module_name) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - /// Pointer to the head of the ACE_Module list. - ACE_Module_Type *head_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Service_Types.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" - -#endif /* _SERVICE_TYPE_H */ diff --git a/externals/ace/Service_Types.inl b/externals/ace/Service_Types.inl deleted file mode 100644 index 4586ac6122a..00000000000 --- a/externals/ace/Service_Types.inl +++ /dev/null @@ -1,43 +0,0 @@ -// -*- C++ -*- -// -// $Id: Service_Types.inl 89925 2010-04-19 12:49:11Z cbeaulac $ - -#include "ace/ACE.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE void * -ACE_Service_Type_Impl::object (void) const -{ - ACE_TRACE ("ACE_Service_Type_Impl::object"); - return this->obj_; -} - -ACE_INLINE const ACE_TCHAR * -ACE_Service_Type_Impl::name (void) const -{ - ACE_TRACE ("ACE_Service_Type_Impl::name"); - return this->name_; -} - -ACE_INLINE void -ACE_Service_Type_Impl::name (const ACE_TCHAR *n) -{ - ACE_TRACE ("ACE_Service_Type_Impl::name"); - - ACE::strdelete (const_cast (this->name_)); - this->name_ = ACE::strnew (n); -} - -ACE_INLINE int -ACE_Service_Type_Impl::service_type (void) const -{ - return service_type_; -} - -ACE_INLINE void -ACE_Service_Type_Impl::service_type (int stype) -{ - service_type_ = stype; -} -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Shared_Memory.cpp b/externals/ace/Shared_Memory.cpp deleted file mode 100644 index ccb1f26c401..00000000000 --- a/externals/ace/Shared_Memory.cpp +++ /dev/null @@ -1,13 +0,0 @@ -// $Id: Shared_Memory.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Shared_Memory.h" - -ACE_RCSID(ace, Shared_Memory, "$Id: Shared_Memory.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_Shared_Memory::~ACE_Shared_Memory (void) -{ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Shared_Memory.h b/externals/ace/Shared_Memory.h deleted file mode 100644 index 6dbd17ff492..00000000000 --- a/externals/ace/Shared_Memory.h +++ /dev/null @@ -1,58 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file Shared_Memory.h - * - * $Id: Shared_Memory.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Doug Schmidt - */ -//========================================================================== - - -#ifndef ACE_SHARED_MEMORY_H -#define ACE_SHARED_MEMORY_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#include "ace/os_include/os_stddef.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Shared_Memory - * - * @brief This base class adapts both System V shared memory and "BSD" - * mmap to a common API. - * - * This is a very simple-minded wrapper, i.e., it really is only - * useful for allocating large contiguous chunks of shared - * memory. For a much more sophisticated version, please check - * out the class. - */ -class ACE_Export ACE_Shared_Memory -{ -public: - virtual ~ACE_Shared_Memory (void); - - // = Note that all the following methods are pure virtual. - virtual int close (void) = 0; - virtual int remove (void) = 0; - virtual void *malloc (size_t = 0) = 0; - virtual int free (void *p) = 0; - virtual size_t get_segment_size (void) const = 0; - virtual ACE_HANDLE get_id (void) const = 0; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" - -#endif /* ACE_SHARED_MEMORY_H */ diff --git a/externals/ace/Shared_Memory_MM.cpp b/externals/ace/Shared_Memory_MM.cpp deleted file mode 100644 index d6d1ed90cce..00000000000 --- a/externals/ace/Shared_Memory_MM.cpp +++ /dev/null @@ -1,111 +0,0 @@ -// $Id: Shared_Memory_MM.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Shared_Memory_MM.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Shared_Memory_MM.inl" -#endif /* __ACE_INLINE__ */ - - -ACE_RCSID (ace, - Shared_Memory_MM, - "$Id: Shared_Memory_MM.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Shared_Memory_MM) - -void -ACE_Shared_Memory_MM::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Shared_Memory_MM::dump"); -#endif /* ACE_HAS_DUMP */ -} - -// Creates a shared memory segment of SIZE bytes. - -ACE_Shared_Memory_MM::ACE_Shared_Memory_MM (ACE_HANDLE handle, - size_t length, - int prot, - int share, - char *addr, - ACE_OFF_T pos) - : shared_memory_ (handle, length, prot, share, addr, pos) -{ - ACE_TRACE ("ACE_Shared_Memory_MM::ACE_Shared_Memory_MM"); -} - -ACE_Shared_Memory_MM::ACE_Shared_Memory_MM (const ACE_TCHAR *file_name, - size_t len, - int flags, - int mode, - int prot, - int share, - char *addr, - ACE_OFF_T pos) - : shared_memory_ (file_name, len, flags, mode, - prot, share, addr, pos) -{ - ACE_TRACE ("ACE_Shared_Memory_MM::ACE_Shared_Memory_MM"); -} - -// The "do-nothing" constructor. - -ACE_Shared_Memory_MM::ACE_Shared_Memory_MM (void) -{ - ACE_TRACE ("ACE_Shared_Memory_MM::ACE_Shared_Memory_MM"); -} - -// The overall size of the segment. - -size_t -ACE_Shared_Memory_MM::get_segment_size (void) const -{ - ACE_TRACE ("ACE_Shared_Memory_MM::get_segment_size"); - // This cast is legit since the original length in open() is an int. - return this->shared_memory_.size (); -} - -// Unmaps the shared memory segment. - -int -ACE_Shared_Memory_MM::remove (void) -{ - ACE_TRACE ("ACE_Shared_Memory_MM::remove"); - return shared_memory_.remove (); -} - -// Closes (unmaps) the shared memory segment. - -int -ACE_Shared_Memory_MM::close (void) -{ - ACE_TRACE ("ACE_Shared_Memory_MM::close"); - return shared_memory_.unmap (); -} - -void * -ACE_Shared_Memory_MM::malloc (size_t) -{ - ACE_TRACE ("ACE_Shared_Memory_MM::malloc"); - void *addr = 0; - - return this->shared_memory_ (addr) == -1 ? 0 : addr; -} - -ACE_HANDLE -ACE_Shared_Memory_MM::get_id (void) const -{ - ACE_TRACE ("ACE_Shared_Memory_MM::get_id"); - return this->shared_memory_.handle (); -} - -int -ACE_Shared_Memory_MM::free (void *p) -{ - ACE_TRACE ("ACE_Shared_Memory_MM::free"); - return p != 0; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Shared_Memory_MM.h b/externals/ace/Shared_Memory_MM.h deleted file mode 100644 index e02b21249ac..00000000000 --- a/externals/ace/Shared_Memory_MM.h +++ /dev/null @@ -1,120 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file Shared_Memory_MM.h - * - * $Id: Shared_Memory_MM.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - - -#ifndef ACE_SHARED_MALLOC_MM_H -#define ACE_SHARED_MALLOC_MM_H -#include /**/ "ace/pre.h" - -#include "ace/Shared_Memory.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Mem_Map.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Shared_Memory_MM - * - * @brief Shared memory wrapper based on MMAP. - * - * This class provides a very simple-minded shared memory manager. We - * strongly recommend that you do NOT use this class. Instead, please - * use @c ACE_Malloc, which has much more powerful capabilities. - */ -class ACE_Export ACE_Shared_Memory_MM : public ACE_Shared_Memory -{ -public: - // = Initialization and termination methods. - /// Default constructor. - ACE_Shared_Memory_MM (void); - - /// Constructor. - ACE_Shared_Memory_MM (ACE_HANDLE handle, - size_t length = static_cast (-1), - int prot = PROT_RDWR, - int share = ACE_MAP_PRIVATE, - char *addr = 0, - ACE_OFF_T pos = 0); - - /// Constructor. - ACE_Shared_Memory_MM (const ACE_TCHAR *file_name, - size_t length = static_cast (-1), - int flags = O_RDWR | O_CREAT, - int mode = ACE_DEFAULT_FILE_PERMS, - int prot = PROT_RDWR, - int share = ACE_MAP_SHARED, - char *addr = 0, ACE_OFF_T pos = 0); - - /// Open method. - int open (ACE_HANDLE handle, - size_t length = static_cast (-1), - int prot = PROT_RDWR, - int share = ACE_MAP_PRIVATE, - char *addr = 0, - ACE_OFF_T pos = 0); - - /// Open method. - int open (const ACE_TCHAR *file_name, - size_t length = static_cast (-1), - int flags = O_RDWR | O_CREAT, - int mode = ACE_DEFAULT_FILE_PERMS, - int prot = PROT_RDWR, - int share = ACE_MAP_SHARED, - char *addr = 0, - ACE_OFF_T pos = 0); - - /// Return the name of file that is mapped (if any). - const ACE_TCHAR *filename (void) const; - - /// Close down the shared memory segment. - virtual int close (void); - - /// Remove the shared memory segment and the underlying file. - virtual int remove (void); - - // = Allocation and deallocation methods. - /// Create a new chuck of memory containing @a size bytes. - virtual void *malloc (size_t size = 0); - - /// Free a chuck of memory allocated by - /// . - virtual int free (void *p); - - /// Return the size of the shared memory segment. - virtual size_t get_segment_size (void) const; - - /// Return the ID of the shared memory segment (i.e., an ACE_HANDLE). - virtual ACE_HANDLE get_id (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - /// This version is implemented with memory-mapped files. - ACE_Mem_Map shared_memory_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Shared_Memory_MM.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_SHARED_MALLOC_MM_H */ diff --git a/externals/ace/Shared_Memory_MM.inl b/externals/ace/Shared_Memory_MM.inl deleted file mode 100644 index 6e1f4b76616..00000000000 --- a/externals/ace/Shared_Memory_MM.inl +++ /dev/null @@ -1,42 +0,0 @@ -// -*- C++ -*- -// -// $Id: Shared_Memory_MM.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Return the name of file that is mapped (if any). - -ACE_INLINE const ACE_TCHAR * -ACE_Shared_Memory_MM::filename (void) const -{ - return this->shared_memory_.filename (); -} - -ACE_INLINE int -ACE_Shared_Memory_MM::open (ACE_HANDLE handle, - size_t length, - int prot, - int share, - char *addr, - ACE_OFF_T pos) -{ - ACE_TRACE ("ACE_Shared_Memory_MM::open"); - return shared_memory_.map (handle, length, prot, share, addr, pos); -} - -ACE_INLINE int -ACE_Shared_Memory_MM::open (const ACE_TCHAR *file_name, - size_t len, - int flags, - int mode, - int prot, - int share, - char *addr, - ACE_OFF_T pos) -{ - ACE_TRACE ("ACE_Shared_Memory_MM::open"); - return shared_memory_.map (file_name, len, flags, mode, - prot, share, addr, pos); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Shared_Memory_Pool.cpp b/externals/ace/Shared_Memory_Pool.cpp deleted file mode 100644 index 0ef93925e89..00000000000 --- a/externals/ace/Shared_Memory_Pool.cpp +++ /dev/null @@ -1,461 +0,0 @@ -// $Id: Shared_Memory_Pool.cpp 84455 2009-02-13 13:31:02Z johnnyw $ - -// Shared_Memory_Pool.cpp -#include "ace/Shared_Memory_Pool.h" -#include "ace/OS_NS_sys_shm.h" -#include "ace/Log_Msg.h" - -ACE_RCSID(ace, Shared_Memory_Pool, "$Id: Shared_Memory_Pool.cpp 84455 2009-02-13 13:31:02Z johnnyw $") - -#if !defined (ACE_LACKS_SYSV_SHMEM) - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Shared_Memory_Pool) - -ACE_Shared_Memory_Pool_Options::ACE_Shared_Memory_Pool_Options ( - const char *base_addr, - size_t max_segments, - size_t file_perms, - ACE_OFF_T minimum_bytes, - size_t segment_size) - : base_addr_ (base_addr), - max_segments_ (max_segments), - minimum_bytes_ (minimum_bytes), - file_perms_ (file_perms), - segment_size_ (segment_size) -{ - ACE_TRACE ("ACE_Shared_Memory_Pool_Options::ACE_Shared_Memory_Pool_Options"); -} - -void -ACE_Shared_Memory_Pool::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Shared_Memory_Pool::dump"); -#endif /* ACE_HAS_DUMP */ -} - -int -ACE_Shared_Memory_Pool::in_use (ACE_OFF_T &offset, - size_t &counter) -{ - offset = 0; - SHM_TABLE *st = reinterpret_cast (this->base_addr_); - shmid_ds buf; - - for (counter = 0; - counter < this->max_segments_ && st[counter].used_ == 1; - counter++) - { - if (ACE_OS::shmctl (st[counter].shmid_, IPC_STAT, &buf) == -1) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("(%P|%t) %p\n"), - ACE_TEXT ("shmctl")), - -1); - offset += buf.shm_segsz; - // ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) segment size = %d, offset = %d\n"), buf.shm_segsz, offset)); - } - - return 0; -} - -int -ACE_Shared_Memory_Pool::find_seg (const void* const searchPtr, - ACE_OFF_T &offset, - size_t &counter) -{ - offset = 0; - SHM_TABLE *st = reinterpret_cast (this->base_addr_); - shmid_ds buf; - - for (counter = 0; - counter < this->max_segments_ - && st[counter].used_ == 1; - counter++) - { - if (ACE_OS::shmctl (st[counter].shmid_, IPC_STAT, &buf) == -1) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("(%P|%t) %p\n"), - ACE_TEXT ("shmctl")), - -1); - offset += buf.shm_segsz; - - // If segment 'counter' starts at a location greater than the - // place we are searching for. We then decrement the offset to - // the start of counter-1. (flabar@vais.net) - if (((ptrdiff_t) offset + (ptrdiff_t) (this->base_addr_)) > (ptrdiff_t) searchPtr) - { - --counter; - offset -= buf.shm_segsz; - return 0; - } - // ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) segment size = %d, offset = %d\n"), buf.shm_segsz, offset)); - } - - return 0; -} - -int -ACE_Shared_Memory_Pool::commit_backing_store_name (size_t rounded_bytes, - ACE_OFF_T &offset) -{ - ACE_TRACE ("ACE_Shared_Memory_Pool::commit_backing_store_name"); - - size_t counter; - SHM_TABLE *st = reinterpret_cast (this->base_addr_); - - if (this->in_use (offset, counter) == -1) - return -1; - - if (counter == this->max_segments_) - ACE_ERROR_RETURN ((LM_ERROR, - "exceeded max number of segments = %d, base = %u, offset = %u\n", - counter, - this->base_addr_, - offset), - -1); - else - { - int shmid = ACE_OS::shmget (st[counter].key_, - rounded_bytes, - this->file_perms_ | IPC_CREAT | IPC_EXCL); - if (shmid == -1) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("(%P|%t) %p\n"), - ACE_TEXT ("shmget")), - -1); - st[counter].shmid_ = shmid; - st[counter].used_ = 1; - - void *address = (void *) (((char *) this->base_addr_) + offset); - void *shmem = ACE_OS::shmat (st[counter].shmid_, - (char *) address, - 0); - - if (shmem != address) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT("(%P|%t) %p, shmem = %u, address = %u\n"), - ACE_TEXT("shmat"), - shmem, - address), - -1); - } - return 0; -} - -// Handle SIGSEGV and SIGBUS signals to remap shared memory properly. - -int -ACE_Shared_Memory_Pool::handle_signal (int , siginfo_t *siginfo, ucontext_t *) -{ - ACE_TRACE ("ACE_Shared_Memory_Pool::handle_signal"); - // ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("signal %S occurred\n"), signum)); - - // While FreeBSD 5.X has a siginfo_t struct with a si_addr field, - // it does not define SEGV_MAPERR. -#if defined (ACE_HAS_SIGINFO_T) && !defined (ACE_LACKS_SI_ADDR) && \ - (defined (SEGV_MAPERR) || defined (SEGV_MEMERR)) - ACE_OFF_T offset; - // Make sure that the pointer causing the problem is within the - // range of the backing store. - - if (siginfo != 0) - { - // ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) si_signo = %d, si_code = %d, addr = %u\n"), siginfo->si_signo, siginfo->si_code, siginfo->si_addr)); - size_t counter; - if (this->in_use (offset, counter) == -1) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("(%P|%t) %p\n"), - ACE_TEXT ("in_use"))); -#if !defined(_UNICOS) - else if (!(siginfo->si_code == SEGV_MAPERR - && siginfo->si_addr < (((char *) this->base_addr_) + offset) - && siginfo->si_addr >= ((char *) this->base_addr_))) - ACE_ERROR_RETURN ((LM_ERROR, - "(%P|%t) address %u out of range\n", - siginfo->si_addr), - -1); -#else /* ! _UNICOS */ - else if (!(siginfo->si_code == SEGV_MEMERR - && siginfo->si_addr < (((unsigned long) this->base_addr_) + offset) - && siginfo->si_addr >= ((unsigned long) this->base_addr_))) - ACE_ERROR_RETURN ((LM_ERROR, - "(%P|%t) address %u out of range\n", - siginfo->si_addr), - -1); -#endif /* ! _UNICOS */ - } - - // The above if case will check to see that the address is in the - // proper range. Therefore there is a segment out there that the - // pointer wants to point into. Find the segment that someone else - // has used and attach to it (flabar@vais.net) - - size_t counter; // ret value to get shmid from the st table. - -#if !defined(_UNICOS) - if (this->find_seg (siginfo->si_addr, offset, counter) == -1) -#else /* ! _UNICOS */ - if (this->find_seg ((const void *)siginfo->si_addr, offset, counter) == -1) -#endif /* ! _UNICOS */ - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("(%P|%t) %p\n"), - ACE_TEXT ("in_use")), - -1); - - void *address = (void *) (((char *) this->base_addr_) + offset); - SHM_TABLE *st = reinterpret_cast (this->base_addr_); - - void *shmem = ACE_OS::shmat (st[counter].shmid_, (char *) address, 0); - - if (shmem != address) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT("(%P|%t) %p, shmem = %u, address = %u\n"), - ACE_TEXT("shmat"), - shmem, - address), - -1); - - // NOTE: this won't work if we dont have SIGINFO_T or SI_ADDR -#else - ACE_UNUSED_ARG (siginfo); -#endif /* ACE_HAS_SIGINFO_T && !defined (ACE_LACKS_SI_ADDR) */ - - return 0; -} - -ACE_Shared_Memory_Pool::ACE_Shared_Memory_Pool ( - const ACE_TCHAR *backing_store_name, - const OPTIONS *options) - : base_addr_ (0), - file_perms_ (ACE_DEFAULT_FILE_PERMS), - max_segments_ (ACE_DEFAULT_MAX_SEGMENTS), - minimum_bytes_ (0), - segment_size_ (ACE_DEFAULT_SEGMENT_SIZE) -{ - ACE_TRACE ("ACE_Shared_Memory_Pool::ACE_Shared_Memory_Pool"); - - // Only change the defaults if != 0. - if (options) - { - this->base_addr_ = - reinterpret_cast (const_cast (options->base_addr_)); - this->max_segments_ = options->max_segments_; - this->file_perms_ = options->file_perms_; - this->minimum_bytes_ = options->minimum_bytes_; - this->segment_size_ = options->segment_size_; - } - - if (backing_store_name) - { - // Convert the string into a number that is used as the segment - // key. - - int segment_key; - int result = ::sscanf (ACE_TEXT_ALWAYS_CHAR (backing_store_name), - "%d", - &segment_key); - - if (result == 0 || result == EOF) - // The conversion to a number failed so hash with crc32 - // ACE::crc32 is also used in . - this->base_shm_key_ = - (key_t) ACE::crc32 (ACE_TEXT_ALWAYS_CHAR (backing_store_name)); - else - this->base_shm_key_ = segment_key; - - if (this->base_shm_key_ == IPC_PRIVATE) - // Make sure that the segment can be shared between unrelated - // processes. - this->base_shm_key_ = ACE_DEFAULT_SHM_KEY; - } - else - this->base_shm_key_ = ACE_DEFAULT_SHM_KEY; - - if (this->signal_handler_.register_handler (SIGSEGV, this) == -1) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_Sig_Handler::register_handler"))); -} - -ACE_Shared_Memory_Pool::~ACE_Shared_Memory_Pool (void) -{ -} - -// Ask system for more shared memory. - -void * -ACE_Shared_Memory_Pool::acquire (size_t nbytes, - size_t &rounded_bytes) -{ - ACE_TRACE ("ACE_Shared_Memory_Pool::acquire"); - - rounded_bytes = this->round_up (nbytes); - - // ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) acquiring more chunks, nbytes = %d, rounded_bytes = %d\n"), nbytes, rounded_bytes)); - - ACE_OFF_T offset; - - if (this->commit_backing_store_name (rounded_bytes, offset) == -1) - return 0; - - // ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) acquired more chunks, nbytes = %d, rounded_bytes = %d\n"), nbytes, rounded_bytes)); - return ((char *) this->base_addr_) + offset; -} - -// Ask system for initial chunk of shared memory. - -void * -ACE_Shared_Memory_Pool::init_acquire (size_t nbytes, - size_t &rounded_bytes, - int &first_time) -{ - ACE_TRACE ("ACE_Shared_Memory_Pool::init_acquire"); - - ACE_OFF_T shm_table_offset = ACE::round_to_pagesize (sizeof (SHM_TABLE)); - rounded_bytes = this->round_up (nbytes > (size_t) this->minimum_bytes_ - ? nbytes - : (size_t) this->minimum_bytes_); - - // Acquire the semaphore to serialize initialization and prevent - // race conditions. - - int shmid = ACE_OS::shmget (this->base_shm_key_, - rounded_bytes + shm_table_offset, - this->file_perms_ | IPC_CREAT | IPC_EXCL); - if (shmid == -1) - { - if (errno != EEXIST) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("(%P|%t) %p\n"), - ACE_TEXT ("shmget")), - 0); - first_time = 0; - - shmid = ACE_OS::shmget (this->base_shm_key_, 0, 0); - - if (shmid == -1) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("(%P|%t) %p\n"), - ACE_TEXT ("shmget")), - 0); - - // This implementation doesn't care if we don't get the key we - // want... - this->base_addr_ = - ACE_OS::shmat (shmid, - reinterpret_cast (this->base_addr_), - 0); - if (this->base_addr_ == reinterpret_cast (-1)) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT("(%P|%t) %p, base_addr = %u\n"), - ACE_TEXT("shmat"), - this->base_addr_), - 0); - } - else - { - first_time = 1; - - // This implementation doesn't care if we don't get the key we - // want... - this->base_addr_ = - ACE_OS::shmat (shmid, - reinterpret_cast (this->base_addr_), - 0); - if (this->base_addr_ == reinterpret_cast (-1)) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT("(%P|%t) %p, base_addr = %u\n"), - ACE_TEXT("shmat"), - this->base_addr_), 0); - - SHM_TABLE *st = reinterpret_cast (this->base_addr_); - st[0].key_ = this->base_shm_key_; - st[0].shmid_ = shmid; - - st[0].used_ = 1; - - for (size_t counter = 1; // Skip over the first entry... - counter < this->max_segments_; - counter++) - { - st[counter].key_ = this->base_shm_key_ + counter; - st[counter].shmid_ = 0; - st[counter].used_ = 0; - } - } - - return (void *) (((char *) this->base_addr_) + shm_table_offset); -} - -// Instruct the memory pool to release all of its resources. - -int -ACE_Shared_Memory_Pool::release (int) -{ - ACE_TRACE ("ACE_Shared_Memory_Pool::release"); - - int result = 0; - SHM_TABLE *st = reinterpret_cast (this->base_addr_); - - for (size_t counter = 0; - counter < this->max_segments_ && st[counter].used_ == 1; - counter++) - if (ACE_OS::shmctl (st[counter].shmid_, IPC_RMID, 0) == -1) - result = -1; - - return result; -} - -int -ACE_Shared_Memory_Pool::sync (ssize_t, int) -{ - ACE_TRACE ("ACE_Shared_Memory_Pool::sync"); - return 0; -} - -int -ACE_Shared_Memory_Pool::sync (void *, size_t, int) -{ - ACE_TRACE ("ACE_Shared_Memory_Pool::sync"); - return 0; -} - -int -ACE_Shared_Memory_Pool::protect (ssize_t, int) -{ - ACE_TRACE ("ACE_Shared_Memory_Pool::protect"); - return 0; -} - -int -ACE_Shared_Memory_Pool::protect (void *, size_t, int) -{ - ACE_TRACE ("ACE_Shared_Memory_Pool::protect"); - return 0; -} - -void * -ACE_Shared_Memory_Pool::base_addr (void) const -{ - ACE_TRACE ("ACE_Shared_Memory_Pool::base_addr"); - return this->base_addr_; -} - -// Implement the algorithm for rounding up the request to an -// appropriate chunksize. - -size_t -ACE_Shared_Memory_Pool::round_up (size_t nbytes) -{ - ACE_TRACE ("ACE_Shared_Memory_Pool::round_up"); - if (nbytes < this->segment_size_) - nbytes = this->segment_size_; - - return ACE::round_to_pagesize (nbytes); -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* !ACE_LACKS_SYSV_SHMEM */ diff --git a/externals/ace/Shared_Memory_Pool.h b/externals/ace/Shared_Memory_Pool.h deleted file mode 100644 index 79cb970e712..00000000000 --- a/externals/ace/Shared_Memory_Pool.h +++ /dev/null @@ -1,210 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Shared_Memory_Pool.h - * - * $Id: Shared_Memory_Pool.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Dougls C. Schmidt - * @author Prashant Jain - */ -//============================================================================= - -#ifndef ACE_SHARED_MEMORY_POOL_H -#define ACE_SHARED_MEMORY_POOL_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_SYSV_SHMEM) - -#include "ace/ACE.h" -#include "ace/Event_Handler.h" -#include "ace/Sig_Handler.h" -#include "ace/os_include/sys/os_mman.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Shared_Memory_Pool_Options - * - * @brief Helper class for Shared Memory Pool constructor options. - * - * This should be a nested class, but that breaks too many - * compilers. - */ -class ACE_Export ACE_Shared_Memory_Pool_Options -{ -public: - /// Initialization method. - ACE_Shared_Memory_Pool_Options ( - const char *base_addr = ACE_DEFAULT_BASE_ADDR, - size_t max_segments = ACE_DEFAULT_MAX_SEGMENTS, - size_t file_perms = ACE_DEFAULT_FILE_PERMS, - ACE_OFF_T minimum_bytes = 0, - size_t segment_size = ACE_DEFAULT_SEGMENT_SIZE); - - /// Base address of the memory-mapped backing store. - const char *base_addr_; - - /// Number of shared memory segments to allocate. - size_t max_segments_; - - /// What the minimum bytes of the initial segment should be. - ACE_OFF_T minimum_bytes_; - - /// File permissions to use when creating/opening a segment. - size_t file_perms_; - - /// Shared memory segment size. - size_t segment_size_; -}; - -/** - * @class ACE_Shared_Memory_Pool - * - * @brief Make a memory pool that is based on System V shared memory - * (shmget(2) etc.). This implementation allows memory to be - * shared between processes. If your platform doesn't support - * System V shared memory (e.g., Win32 and many RTOS platforms - * do not) then you should use ACE_MMAP_Memory_Pool instead of this - * class. In fact, you should probably use ACE_MMAP_Memory_Pool on - * platforms that *do* support System V shared memory since it - * provides more powerful features, such as persistent backing store - * and greatly scalability. - */ -class ACE_Export ACE_Shared_Memory_Pool : public ACE_Event_Handler -{ -public: - typedef ACE_Shared_Memory_Pool_Options OPTIONS; - - /// Initialize the pool. - ACE_Shared_Memory_Pool (const ACE_TCHAR *backing_store_name = 0, - const OPTIONS *options = 0); - - virtual ~ACE_Shared_Memory_Pool (void); - - /// Ask system for initial chunk of local memory. - virtual void *init_acquire (size_t nbytes, - size_t &rounded_bytes, - int &first_time); - - /** - * Acquire at least @a nbytes from the memory pool. @a rounded_byes is - * the actual number of bytes allocated. Also acquires an internal - * semaphore that ensures proper serialization of Memory_Pool - * initialization across processes. - */ - virtual void *acquire (size_t nbytes, - size_t &rounded_bytes); - - /// Instruct the memory pool to release all of its resources. - virtual int release (int destroy = 1); - - /// Sync the memory region to the backing store starting at - /// @c this->base_addr_. - virtual int sync (ssize_t len = -1, int flags = MS_SYNC); - - /// Sync the memory region to the backing store starting at @a addr. - virtual int sync (void *addr, size_t len, int flags = MS_SYNC); - - /** - * Change the protection of the pages of the mapped region to @a prot - * starting at @c this->base_addr_ up to @a len bytes. If @a len == -1 - * then change protection of all pages in the mapped region. - */ - virtual int protect (ssize_t len = -1, int prot = PROT_RDWR); - - /// Change the protection of the pages of the mapped region to @a prot - /// starting at @a addr up to @a len bytes. - virtual int protect (void *addr, size_t len, int prot = PROT_RDWR); - - /// Return the base address of this memory pool, 0 if base_addr - /// never changes. - virtual void *base_addr (void) const; - - /// Dump the state of an object. - virtual void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - /// Implement the algorithm for rounding up the request to an - /// appropriate chunksize. - virtual size_t round_up (size_t nbytes); - - /** - * Commits a new shared memory segment if necessary after an - * or a signal. @a offset is set to the new offset into - * the backing store. - */ - virtual int commit_backing_store_name (size_t rounded_bytes, - ACE_OFF_T &offset); - - /// Keeps track of all the segments being used. - struct SHM_TABLE - { - /// Shared memory segment key. - key_t key_; - - /// Shared memory segment internal id. - int shmid_; - - /// Is the segment currently used.; - int used_; - }; - - /** - * Base address of the shared memory segment. If this has the value - * of 0 then the OS is free to select any address, otherwise this - * value is what the OS must try to use to map the shared memory - * segment. - */ - void *base_addr_; - - /// File permissions to use when creating/opening a segment. - size_t file_perms_; - - /// Number of shared memory segments in the table. - size_t max_segments_; - - /// What the minimim bytes of the initial segment should be. - ACE_OFF_T minimum_bytes_; - - /// Shared memory segment size. - size_t segment_size_; - - /// Base shared memory key for the segment. - key_t base_shm_key_; - - /// Find the segment that contains the @a searchPtr - virtual int find_seg (const void *const searchPtr, - ACE_OFF_T &offset, - size_t &counter); - - /// Determine how much memory is currently in use. - virtual int in_use (ACE_OFF_T &offset, - size_t &counter); - - /// Handles SIGSEGV. - ACE_Sig_Handler signal_handler_; - - /// Handle SIGSEGV and SIGBUS signals to remap shared memory - /// properly. - virtual int handle_signal (int signum, siginfo_t *, ucontext_t *); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* !ACE_LACKS_SYSV_SHMEM */ - -#include /**/ "ace/post.h" - -#endif /* ACE_SHARED_MEMORY_POOL_H */ diff --git a/externals/ace/Shared_Memory_SV.cpp b/externals/ace/Shared_Memory_SV.cpp deleted file mode 100644 index fe26688b098..00000000000 --- a/externals/ace/Shared_Memory_SV.cpp +++ /dev/null @@ -1,88 +0,0 @@ -// $Id: Shared_Memory_SV.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Shared_Memory_SV.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Shared_Memory_SV.inl" -#endif /* __ACE_INLINE__ */ - - -ACE_RCSID (ace, - Shared_Memory_SV, - "$Id: Shared_Memory_SV.cpp 80826 2008-03-04 14:51:23Z wotte $") - - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Shared_Memory_SV) - -void -ACE_Shared_Memory_SV::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Shared_Memory_SV::dump"); -#endif /* ACE_HAS_DUMP */ -} - -ACE_Shared_Memory_SV::ACE_Shared_Memory_SV (key_t id, - size_t length, - int create, - int perms, - void *addr, - int flags) - : shared_memory_ (id, length, create, perms, addr, flags) -{ - ACE_TRACE ("ACE_Shared_Memory_SV::ACE_Shared_Memory_SV"); -} - -// The overall size of the segment. - -size_t -ACE_Shared_Memory_SV::get_segment_size (void) const -{ - ACE_TRACE ("ACE_Shared_Memory_SV::get_segment_size"); - // This cast is ok since the 'open' method for this class allows only - // an 'int' size. Therefore, this case should not lose information. - return this->shared_memory_.get_segment_size (); -} - -// Removes the shared memory segment. - -int -ACE_Shared_Memory_SV::remove (void) -{ - ACE_TRACE ("ACE_Shared_Memory_SV::remove"); - return shared_memory_.remove (); -} - -// Closes (detaches) the shared memory segment. - -int -ACE_Shared_Memory_SV::close (void) -{ - ACE_TRACE ("ACE_Shared_Memory_SV::close"); - return shared_memory_.detach (); -} - -void * -ACE_Shared_Memory_SV::malloc (size_t) -{ - ACE_TRACE ("ACE_Shared_Memory_SV::malloc"); - return this->shared_memory_.get_segment_ptr (); -} - -ACE_HANDLE -ACE_Shared_Memory_SV::get_id (void) const -{ - ACE_TRACE ("ACE_Shared_Memory_SV::get_id"); - return this->shared_memory_.get_id (); -} - -int -ACE_Shared_Memory_SV::free (void *p) -{ - ACE_TRACE ("ACE_Shared_Memory_SV::free"); - return p != 0; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Shared_Memory_SV.h b/externals/ace/Shared_Memory_SV.h deleted file mode 100644 index 7ae62a3323f..00000000000 --- a/externals/ace/Shared_Memory_SV.h +++ /dev/null @@ -1,101 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Shared_Memory_SV.h - * - * $Id: Shared_Memory_SV.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - - -#ifndef ACE_SHARED_MALLOC_SV_H -#define ACE_SHARED_MALLOC_SV_H -#include /**/ "ace/pre.h" - -#include "ace/Shared_Memory.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/SV_Shared_Memory.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Shared_Memory_SV - * - * @brief Shared memory wrapper based on System V shared memory. - * - * This class provides a very simple-minded shared memory manager. We - * strongly recommend that you do NOT use this class. Instead, please - * use @c ACE_Malloc, which has much more powerful capabilities. - */ -class ACE_Export ACE_Shared_Memory_SV : public ACE_Shared_Memory -{ -public: - enum - { - ACE_CREATE = IPC_CREAT, - ACE_OPEN = 0 - }; - - // = Initialization and termination methods. - ACE_Shared_Memory_SV (void); - ACE_Shared_Memory_SV (key_t id, - size_t length, - int create = ACE_Shared_Memory_SV::ACE_OPEN, - int perms = ACE_DEFAULT_FILE_PERMS, - void *addr = 0, - int flags = 0); - - int open (key_t id, - size_t length, - int create = ACE_Shared_Memory_SV::ACE_OPEN, - int perms = ACE_DEFAULT_FILE_PERMS, - void *addr = 0, - int flags = 0); - - /// Close down the shared memory segment. - virtual int close (void); - - /// Remove the underlying shared memory segment. - virtual int remove (void); - - // = Allocation and deallocation methods. - /// Create a new chuck of memory containing @a size bytes. - virtual void *malloc (size_t = 0); - - /// Free a chuck of memory allocated by . - virtual int free (void *p); - - /// Return the size of the shared memory segment. - virtual size_t get_segment_size (void) const; - - /// Return the ID of the shared memory segment (i.e., a System V - /// shared memory internal id). - virtual ACE_HANDLE get_id (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - /// This version is implemented with System V shared memory - /// segments. - ACE_SV_Shared_Memory shared_memory_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Shared_Memory_SV.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_SHARED_MALLOC_SV_H */ diff --git a/externals/ace/Shared_Memory_SV.inl b/externals/ace/Shared_Memory_SV.inl deleted file mode 100644 index 1a586701cc3..00000000000 --- a/externals/ace/Shared_Memory_SV.inl +++ /dev/null @@ -1,30 +0,0 @@ -// -*- C++ -*- -// -// $Id: Shared_Memory_SV.inl 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Global_Macros.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE int -ACE_Shared_Memory_SV::open (key_t id, - size_t length, - int create, - int perms, - void *addr, - int flags) -{ - ACE_TRACE ("ACE_Shared_Memory_SV::open"); - return shared_memory_.open_and_attach (id, length, create, - perms, addr, flags); -} - -// The "do-nothing" constructor. - -ACE_INLINE -ACE_Shared_Memory_SV::ACE_Shared_Memory_SV (void) -{ - ACE_TRACE ("ACE_Shared_Memory_SV::ACE_Shared_Memory_SV"); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Shared_Object.cpp b/externals/ace/Shared_Object.cpp deleted file mode 100644 index 76c27df1cb1..00000000000 --- a/externals/ace/Shared_Object.cpp +++ /dev/null @@ -1,54 +0,0 @@ -// $Id: Shared_Object.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Shared_Object.h" -#include "ace/Global_Macros.h" -#include "ace/config-all.h" - -/* Provide the abstract base class used to access dynamic linking - facilities */ - -#if !defined (__ACE_INLINE__) -#include "ace/Shared_Object.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID (ace, - Shared_Object, - "$Id: Shared_Object.cpp 80826 2008-03-04 14:51:23Z wotte $") - - ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Initializes object when dynamic linking occurs. - -int -ACE_Shared_Object::init (int, ACE_TCHAR *[]) -{ - ACE_TRACE ("ACE_Shared_Object::init"); - return 0; -} - -// Terminates object when dynamic unlinking occurs. - -int -ACE_Shared_Object::fini (void) -{ - ACE_TRACE ("ACE_Shared_Object::fini"); - return 0; -} - -// Returns information on active object. - -int -ACE_Shared_Object::info (ACE_TCHAR **, size_t) const -{ - ACE_TRACE ("ACE_Shared_Object::info"); - return 0; -} - -// Need to give a default implementation. - -ACE_Shared_Object::~ACE_Shared_Object (void) -{ - ACE_TRACE ("ACE_Shared_Object::~ACE_Shared_Object"); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Shared_Object.h b/externals/ace/Shared_Object.h deleted file mode 100644 index fedf051ba6f..00000000000 --- a/externals/ace/Shared_Object.h +++ /dev/null @@ -1,62 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file Shared_Object.h - * - * $Id: Shared_Object.h 81348 2008-04-14 09:00:32Z johnnyw $ - * - * @author Douglas C. Schmidt - */ -//========================================================================== - -#ifndef ACE_SHARED_OBJECT_H -#define ACE_SHARED_OBJECT_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_types.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Shared_Object - * - * @brief Provide the abstract base class used to access dynamic - * linking facilities. - */ -class ACE_Export ACE_Shared_Object -{ -public: - /// Constructor - ACE_Shared_Object (void); - - /// Destructor - virtual ~ACE_Shared_Object (void); - - /// Initializes object when dynamic linking occurs. - virtual int init (int argc, ACE_TCHAR *argv[]); - - /// Terminates object when dynamic unlinking occurs. - virtual int fini (void); - - /// Returns information on a service object. - virtual int info (ACE_TCHAR **info_string, size_t length = 0) const; - -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Shared_Object.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" - -#endif /* ACE_SHARED_OBJECT_H */ diff --git a/externals/ace/Shared_Object.inl b/externals/ace/Shared_Object.inl deleted file mode 100644 index 4f5f0020604..00000000000 --- a/externals/ace/Shared_Object.inl +++ /dev/null @@ -1,12 +0,0 @@ -// -*- C++ -*- -// -// $Id: Shared_Object.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE -ACE_Shared_Object::ACE_Shared_Object (void) -{ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Sig_Adapter.cpp b/externals/ace/Sig_Adapter.cpp deleted file mode 100644 index d1af40f12d5..00000000000 --- a/externals/ace/Sig_Adapter.cpp +++ /dev/null @@ -1,80 +0,0 @@ -// $Id: Sig_Adapter.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Sig_Adapter.h" - -ACE_RCSID(ace, Sig_Adapter, "$Id: Sig_Adapter.cpp 80826 2008-03-04 14:51:23Z wotte $") - - -ACE_Sig_Adapter::ACE_Sig_Adapter (ACE_Sig_Action &sa, int sigkey) - : sigkey_ (sigkey), - type_ (SIG_ACTION), - sa_ (sa) -{ - // ACE_TRACE ("ACE_Sig_Adapter::ACE_Sig_Adapter"); -} - -ACE_Sig_Adapter::ACE_Sig_Adapter (ACE_Event_Handler *eh, - int sigkey) - : sigkey_ (sigkey), - type_ (ACE_HANDLER), - eh_ (eh) -{ - // ACE_TRACE ("ACE_Sig_Adapter::ACE_Sig_Adapter"); -} - -ACE_Sig_Adapter::ACE_Sig_Adapter (ACE_Sig_Handler_Ex sig_func, - int sigkey) - : sigkey_ (sigkey), - type_ (C_FUNCTION), - sig_func_ (sig_func) -{ - // ACE_TRACE ("ACE_Sig_Adapter::ACE_Sig_Adapter"); -} - -ACE_Sig_Adapter::~ACE_Sig_Adapter () -{ -} - -int -ACE_Sig_Adapter::sigkey (void) -{ - ACE_TRACE ("ACE_Sig_Adapter::sigkey"); - return this->sigkey_; -} - -int -ACE_Sig_Adapter::handle_signal (int signum, - siginfo_t *siginfo, - ucontext_t *ucontext) -{ - ACE_TRACE ("ACE_Sig_Adapter::handle_signal"); - - switch (this->type_) - { - case SIG_ACTION: - { - // We have to dispatch a handler that was registered by a - // third-party library. - - ACE_Sig_Action old_disp; - - // Make sure this handler executes in the context it was - // expecting... - this->sa_.register_action (signum, &old_disp); - - ACE_Sig_Handler_Ex sig_func = ACE_Sig_Handler_Ex (this->sa_.handler ()); - - (*sig_func) (signum, siginfo, ucontext); - // Restore the original disposition. - old_disp.register_action (signum); - break; - } - case ACE_HANDLER: - this->eh_->handle_signal (signum, siginfo, ucontext); - break; - case C_FUNCTION: - (*this->sig_func_) (signum, siginfo, ucontext); - break; - } - return 0; -} diff --git a/externals/ace/Sig_Adapter.h b/externals/ace/Sig_Adapter.h deleted file mode 100644 index cbd6b399867..00000000000 --- a/externals/ace/Sig_Adapter.h +++ /dev/null @@ -1,81 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Sig_Adapter.h - * - * $Id: Sig_Adapter.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_SIG_ADAPTER_H -#define ACE_SIG_ADAPTER_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Event_Handler.h" -#include "ace/Signal.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Sig_Adapter - * - * @brief Provide an adapter that transforms various types of signal - * handlers into the scheme used by the ACE_Reactor. - */ -class ACE_Export ACE_Sig_Adapter : public ACE_Event_Handler -{ -public: - ACE_Sig_Adapter (ACE_Sig_Action &, int sigkey); - ACE_Sig_Adapter (ACE_Event_Handler *, int sigkey); - ACE_Sig_Adapter (ACE_Sig_Handler_Ex, int sigkey = 0); - ~ACE_Sig_Adapter (void); - - /// Returns this signal key that's used to remove this from the - /// ACE_Reactor's internal table. - int sigkey (void); - - /// Called by the to dispatch the signal handler. - virtual int handle_signal (int, siginfo_t *, ucontext_t *); - -private: - /// Key for this signal handler (used to remove it). - int sigkey_; - - /// Is this an external handler or an ACE handler? - enum - { - /// We're just wrapping an ACE_Event_Handler. - ACE_HANDLER, - /// An ACE_Sig_Action. - SIG_ACTION, - /// A normal C function. - C_FUNCTION - } type_; - - // = This should be a union, but C++ won't allow that because the - // has a constructor. - /// This is an external handler (ugh). - ACE_Sig_Action sa_; - - /// This is an ACE hander. - ACE_Event_Handler *eh_; - - /// This is a normal C function. - ACE_Sig_Handler_Ex sig_func_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" - -#endif /* ACE_SIG_ADAPTER_H */ diff --git a/externals/ace/Sig_Handler.cpp b/externals/ace/Sig_Handler.cpp deleted file mode 100644 index 8691f817fa0..00000000000 --- a/externals/ace/Sig_Handler.cpp +++ /dev/null @@ -1,616 +0,0 @@ -// $Id: Sig_Handler.cpp 88360 2009-12-30 08:42:20Z olli $ - -#include "ace/Sig_Handler.h" -#include "ace/Sig_Adapter.h" -#include "ace/Signal.h" -#include "ace/Recursive_Thread_Mutex.h" -#include "ace/Managed_Object.h" -#include "ace/Containers.h" -#include "ace/Guard_T.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Sig_Handler.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID(ace, Sig_Handler, "$Id: Sig_Handler.cpp 88360 2009-12-30 08:42:20Z olli $") - -#if defined (ACE_HAS_SIG_C_FUNC) - -extern "C" void -ace_sig_handler_dispatch (int signum, siginfo_t *info, ucontext_t *context) -{ - ACE_TRACE ("ace_sig_handler_dispatch"); - ACE_Sig_Handler::dispatch (signum, info, context); -} - -#define ace_signal_handler_dispatcher ACE_SignalHandler(ace_sig_handler_dispatch) - -extern "C" void -ace_sig_handlers_dispatch (int signum, siginfo_t *info, ucontext_t *context) -{ - ACE_TRACE ("ace_sig_handlers_dispatch"); - ACE_Sig_Handlers::dispatch (signum, info, context); -} - -#define ace_signal_handlers_dispatcher ACE_SignalHandler(ace_sig_handlers_dispatch) - -#else -#define ace_signal_handler_dispatcher ACE_SignalHandler(ACE_Sig_Handler::dispatch) - -#define ace_signal_handlers_dispatcher ACE_SignalHandler(ACE_Sig_Handlers::dispatch) -#endif /* ACE_HAS_SIG_C_FUNC */ - - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Array of Event_Handlers that will handle the signals. -ACE_Event_Handler *ACE_Sig_Handler::signal_handlers_[ACE_NSIG]; - -// Remembers if a signal has occurred. -sig_atomic_t ACE_Sig_Handler::sig_pending_ = 0; - - -ACE_ALLOC_HOOK_DEFINE(ACE_Sig_Handler) - -ACE_Sig_Handler::~ACE_Sig_Handler (void) -{ -} - -void -ACE_Sig_Handler::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Sig_Handler::dump"); -#endif /* ACE_HAS_DUMP */ -} - -int -ACE_Sig_Handler::sig_pending (void) -{ - ACE_TRACE ("ACE_Sig_Handler::sig_pending"); - ACE_MT (ACE_Recursive_Thread_Mutex *lock = - ACE_Managed_Object::get_preallocated_object - (ACE_Object_Manager::ACE_SIG_HANDLER_LOCK); - ACE_Guard m (*lock)); - return ACE_Sig_Handler::sig_pending_ != 0; -} - -void -ACE_Sig_Handler::sig_pending (int pending) -{ - ACE_TRACE ("ACE_Sig_Handler::sig_pending"); - - ACE_MT (ACE_Recursive_Thread_Mutex *lock = - ACE_Managed_Object::get_preallocated_object - (ACE_Object_Manager::ACE_SIG_HANDLER_LOCK); - ACE_Guard m (*lock)); - ACE_Sig_Handler::sig_pending_ = pending; -} - -ACE_Event_Handler * -ACE_Sig_Handler::handler (int signum) -{ - ACE_TRACE ("ACE_Sig_Handler::handler"); - ACE_MT (ACE_Recursive_Thread_Mutex *lock = - ACE_Managed_Object::get_preallocated_object - (ACE_Object_Manager::ACE_SIG_HANDLER_LOCK); - ACE_Guard m (*lock)); - - if (ACE_Sig_Handler::in_range (signum)) - return ACE_Sig_Handler::signal_handlers_[signum]; - else - return 0; -} - -ACE_Event_Handler * -ACE_Sig_Handler::handler_i (int signum, - ACE_Event_Handler *new_sh) -{ - ACE_TRACE ("ACE_Sig_Handler::handler_i"); - - if (ACE_Sig_Handler::in_range (signum)) - { - ACE_Event_Handler *sh = ACE_Sig_Handler::signal_handlers_[signum]; - - ACE_Sig_Handler::signal_handlers_[signum] = new_sh; - return sh; - } - else - return 0; -} - -ACE_Event_Handler * -ACE_Sig_Handler::handler (int signum, - ACE_Event_Handler *new_sh) -{ - ACE_TRACE ("ACE_Sig_Handler::handler"); - ACE_MT (ACE_Recursive_Thread_Mutex *lock = - ACE_Managed_Object::get_preallocated_object - (ACE_Object_Manager::ACE_SIG_HANDLER_LOCK); - ACE_Guard m (*lock)); - - return ACE_Sig_Handler::handler_i (signum, new_sh); -} - -// Register an ACE_Event_Handler along with the corresponding SIGNUM. -// This method does NOT acquire any locks, so it can be called from a -// signal handler. - -int -ACE_Sig_Handler::register_handler_i (int signum, - ACE_Event_Handler *new_sh, - ACE_Sig_Action *new_disp, - ACE_Event_Handler **old_sh, - ACE_Sig_Action *old_disp) -{ - ACE_TRACE ("ACE_Sig_Handler::register_handler_i"); - - if (ACE_Sig_Handler::in_range (signum)) - { - ACE_Sig_Action sa; // Define a "null" action. - ACE_Event_Handler *sh = ACE_Sig_Handler::handler_i (signum, new_sh); - - // Return a pointer to the old if the user - // asks for this. - if (old_sh != 0) - *old_sh = sh; - - // Make sure that points to a valid location if the - // user doesn't care... - if (new_disp == 0) - new_disp = &sa; - - new_disp->handler (ace_signal_handler_dispatcher); -#if !defined (ACE_HAS_LYNXOS4_SIGNALS) - new_disp->flags (new_disp->flags () | SA_SIGINFO); -#endif /* ACE_HAS_LYNXOS4_SIGNALS */ - return new_disp->register_action (signum, old_disp); - } - else - return -1; -} - -// Register an ACE_Event_Handler along with the corresponding SIGNUM. -// This method acquires a lock, so it can't be called from a signal -// handler, e.g., . - -int -ACE_Sig_Handler::register_handler (int signum, - ACE_Event_Handler *new_sh, - ACE_Sig_Action *new_disp, - ACE_Event_Handler **old_sh, - ACE_Sig_Action *old_disp) -{ - ACE_TRACE ("ACE_Sig_Handler::register_handler"); - ACE_MT (ACE_Recursive_Thread_Mutex *lock = - ACE_Managed_Object::get_preallocated_object - (ACE_Object_Manager::ACE_SIG_HANDLER_LOCK); - ACE_Guard m (*lock)); - - return ACE_Sig_Handler::register_handler_i (signum, - new_sh, - new_disp, - old_sh, - old_disp); -} - -// Remove an ACE_Event_Handler. - -int -ACE_Sig_Handler::remove_handler (int signum, - ACE_Sig_Action *new_disp, - ACE_Sig_Action *old_disp, - int) -{ - ACE_TRACE ("ACE_Sig_Handler::remove_handler"); - ACE_MT (ACE_Recursive_Thread_Mutex *lock = - ACE_Managed_Object::get_preallocated_object - (ACE_Object_Manager::ACE_SIG_HANDLER_LOCK); - ACE_Guard m (*lock)); - - if (ACE_Sig_Handler::in_range (signum)) - { - ACE_Sig_Action sa (SIG_DFL, (sigset_t *) 0); // Define the default disposition. - - if (new_disp == 0) - new_disp = &sa; - - ACE_Sig_Handler::signal_handlers_[signum] = 0; - - // Register either the new disposition or restore the default. - return new_disp->register_action (signum, old_disp); - } - - return -1; -} - -// Master dispatcher function that gets called by a signal handler and -// dispatches one handler... - -void -ACE_Sig_Handler::dispatch (int signum, - siginfo_t *siginfo, - ucontext_t *ucontext) -{ - ACE_TRACE ("ACE_Sig_Handler::dispatch"); - - // Save/restore errno. - ACE_Errno_Guard error (errno); - - // We can't use the call here because that acquires - // the lock, which is non-portable... - ACE_Sig_Handler::sig_pending_ = 1; - - // Darn well better be in range since the OS dispatched this... - ACE_ASSERT (ACE_Sig_Handler::in_range (signum)); - - ACE_Event_Handler *eh = ACE_Sig_Handler::signal_handlers_[signum]; - - if (eh != 0) - { - if (eh->handle_signal (signum, siginfo, ucontext) == -1) - { - // Define the default disposition. - ACE_Sig_Action sa ((ACE_SignalHandler) SIG_DFL, (sigset_t *) 0); - - ACE_Sig_Handler::signal_handlers_[signum] = 0; - - // Remove the current disposition by registering the default - // disposition. - sa.register_action (signum); - - // Allow the event handler to close down if necessary. - eh->handle_close (ACE_INVALID_HANDLE, - ACE_Event_Handler::SIGNAL_MASK); - } -#if defined (ACE_WIN32) - else - // Win32 is weird in the sense that it resets the signal - // disposition to SIG_DFL after a signal handler is - // dispatched. Therefore, to workaround this "feature" we - // must re-register the with - // explicitly. - ACE_Sig_Handler::register_handler_i (signum, - eh); -#endif /* ACE_WIN32*/ - } -} - -// ---------------------------------------- -// The following classes are local to this file. - -// There are bugs with HP/UX's C++ compiler that prevents this stuff -// from compiling... -#define ACE_MAX_SIGNAL_HANDLERS ((size_t) 20) - -// Keeps track of the id that uniquely identifies each registered -// signal handler. This id can be used to cancel a timer via the -// method. -int ACE_Sig_Handlers::sigkey_ = 0; - -// If this is true then a 3rd party library has registered a -// handler... -bool ACE_Sig_Handlers::third_party_sig_handler_ = false; - -// Make life easier by defining typedefs... -typedef ACE_Fixed_Set ACE_SIG_HANDLERS_SET; -typedef ACE_Fixed_Set_Iterator ACE_SIG_HANDLERS_ITERATOR; - -class ACE_Sig_Handlers_Set -{ -public: - static ACE_SIG_HANDLERS_SET *instance (int signum); - -private: - static ACE_SIG_HANDLERS_SET *sig_handlers_[ACE_NSIG]; -}; - -/* static */ -ACE_SIG_HANDLERS_SET *ACE_Sig_Handlers_Set::sig_handlers_[ACE_NSIG]; - -/* static */ -ACE_SIG_HANDLERS_SET * -ACE_Sig_Handlers_Set::instance (int signum) -{ - if (signum <= 0 || signum >= ACE_NSIG) - return 0; // This will cause problems... - else if (ACE_Sig_Handlers_Set::sig_handlers_[signum] == 0) - ACE_NEW_RETURN (ACE_Sig_Handlers_Set::sig_handlers_[signum], - ACE_SIG_HANDLERS_SET, - 0); - return ACE_Sig_Handlers_Set::sig_handlers_[signum]; -} - -ACE_ALLOC_HOOK_DEFINE(ACE_Sig_Handlers) - -void -ACE_Sig_Handlers::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Sig_Handlers::dump"); -#endif /* ACE_HAS_DUMP */ -} - -// This is the method that does all the dirty work... The basic -// structure of this method was devised by Detlef Becker. - -int -ACE_Sig_Handlers::register_handler (int signum, - ACE_Event_Handler *new_sh, - ACE_Sig_Action *new_disp, - ACE_Event_Handler **, - ACE_Sig_Action *old_disp) -{ - ACE_TRACE ("ACE_Sig_Handlers::register_handler"); - ACE_MT (ACE_Recursive_Thread_Mutex *lock = - ACE_Managed_Object::get_preallocated_object - (ACE_Object_Manager::ACE_SIG_HANDLER_LOCK); - ACE_Guard m (*lock)); - - if (ACE_Sig_Handler::in_range (signum)) - { - ACE_Sig_Adapter *ace_sig_adapter = 0; // Our signal handler. - ACE_Sig_Adapter *extern_sh = 0; // An external signal handler. - ACE_Sig_Action sa; - - // Get current signal disposition. - sa.retrieve_action (signum); - - // Check whether we are already in control of the signal - // handling disposition... - - if (!(sa.handler () == ace_signal_handlers_dispatcher - || sa.handler () == ACE_SignalHandler (SIG_IGN) - || sa.handler () == ACE_SignalHandler (SIG_DFL))) - { - // Drat, a 3rd party library has already installed a signal ;-( - - // Upto here we never disabled RESTART_MODE. Thus, - // RESTART_MODE can only be changed by 3rd party libraries. - - if (ACE_BIT_DISABLED (sa.flags (), SA_RESTART) - && ACE_Sig_Handlers::third_party_sig_handler_) - // Toggling is disallowed since we might break 3rd party - // code. - return -1; - - // Note that we've seen a 3rd party handler... - ACE_Sig_Handlers::third_party_sig_handler_ = true; - - // Create a new 3rd party disposition, remembering its - // preferred signal blocking etc...; - ACE_NEW_RETURN (extern_sh, - ACE_Sig_Adapter (sa, - ++ACE_Sig_Handlers::sigkey_), - -1); - // Add the external signal handler to the set of handlers - // for this signal. - if (ACE_Sig_Handlers_Set::instance (signum)->insert (extern_sh) == -1) - { - delete extern_sh; - return -1; - } - } - // Add our new handler at this point. - ACE_NEW_RETURN (ace_sig_adapter, - ACE_Sig_Adapter (new_sh, - ++ACE_Sig_Handlers::sigkey_), - -1); - // Add the ACE signal handler to the set of handlers for this - // signal (make sure it goes before the external one if there is - // one of these). - - int result = ACE_Sig_Handlers_Set::instance (signum)->insert (ace_sig_adapter); - - if (result == -1) - { - // We couldn't reinstall our handler, so let's pretend like - // none of this happened... - if (extern_sh) - { - ACE_Sig_Handlers_Set::instance (signum)->remove (extern_sh); - delete extern_sh; - } - delete ace_sig_adapter; - return -1; - } - // If ACE_Sig_Handlers::dispatch() was set we're done. - else if (sa.handler () == ace_signal_handlers_dispatcher) - return ace_sig_adapter->sigkey (); - - // Otherwise, we need to register our handler function so that - // all signals will be dispatched through ACE. - else - { - // Make sure that new_disp points to a valid location if the - // user doesn't care... - if (new_disp == 0) - new_disp = &sa; - - new_disp->handler (ace_signal_handlers_dispatcher); - - // Default is to restart signal handlers. - new_disp->flags (new_disp->flags () | SA_RESTART); -#if !defined (ACE_HAS_LYNXOS4_SIGNALS) - new_disp->flags (new_disp->flags () | SA_SIGINFO); -#endif /* ACE_HAS_LYNXOS4_SIGNALS */ - - // Finally install (possibly reinstall) the ACE signal - // handler disposition with the SA_RESTART mode enabled. - if (new_disp->register_action (signum, old_disp) == -1) - { - // Yikes, lots of roll back at this point... - ACE_Sig_Handlers_Set::instance (signum)->remove (ace_sig_adapter); - delete ace_sig_adapter; - - if (extern_sh) - { - ACE_Sig_Handlers_Set::instance (signum)->remove (extern_sh); - delete extern_sh; - } - return -1; - } - else // Return the signal key so that programs can cancel this - // handler if they want! - return ace_sig_adapter->sigkey (); - } - } - - return -1; -} - -// Remove the ACE_Event_Handler currently associated with . -// Install the new disposition (if given) and return the previous -// disposition (if desired by the caller). Returns 0 on success and -// -1 if is invalid. - -int -ACE_Sig_Handlers::remove_handler (int signum, - ACE_Sig_Action *new_disp, - ACE_Sig_Action *old_disp, - int sigkey) -{ - ACE_TRACE ("ACE_Sig_Handlers::remove_handler"); - ACE_MT (ACE_Recursive_Thread_Mutex *lock = - ACE_Managed_Object::get_preallocated_object - (ACE_Object_Manager::ACE_SIG_HANDLER_LOCK); - ACE_Guard m (*lock)); - - if (ACE_Sig_Handler::in_range (signum)) - { - ACE_SIG_HANDLERS_SET *handler_set = - ACE_Sig_Handlers_Set::instance (signum); - - ACE_SIG_HANDLERS_ITERATOR handler_iterator (*handler_set); - - // Iterate through the set of handlers for this signal. - - for (ACE_Event_Handler **eh; - handler_iterator.next (eh) != 0; - ) - { - // Type-safe downcast would be nice here... - ACE_Sig_Adapter *sh = (ACE_Sig_Adapter *) *eh; - - // Remove the handler if (1) its key matches the key we've - // been told to remove or (2) if we've been told to remove - // *all* handlers (i.e., == -1). - - if (sh->sigkey () == sigkey || sigkey == -1) - { - handler_set->remove (*eh); - delete *eh; - } - } - - if (handler_set->size () == 0) - { - // If there are no more handlers left for a signal then - // register the new disposition or restore the default - // disposition. - - ACE_Sig_Action sa (SIG_DFL, (sigset_t *) 0); - - if (new_disp == 0) - new_disp = &sa; - - return new_disp->register_action (signum, old_disp); - } - return 0; - } - else - return -1; -} - -// Master dispatcher function that gets called by a signal handler and -// dispatches *all* the handlers... - -void -ACE_Sig_Handlers::dispatch (int signum, - siginfo_t *siginfo, - ucontext_t *ucontext) -{ - ACE_TRACE ("ACE_Sig_Handlers::dispatch"); - // The following is #ifdef'd out because it's entirely non-portable - // to acquire a mutex in a signal handler... -#if 0 - ACE_MT (ACE_Recursive_Thread_Mutex *lock = - ACE_Managed_Object::get_preallocated_object - (ACE_Object_Manager::ACE_SIG_HANDLER_LOCK); - ACE_TSS_Guard m (*lock)); -#endif /* 0 */ - - // Save/restore errno. - ACE_Errno_Guard error (errno); - - ACE_Sig_Handler::sig_pending_ = 1; - - // Darn well better be in range since the OS dispatched this... - ACE_ASSERT (ACE_Sig_Handler::in_range (signum)); - - ACE_SIG_HANDLERS_SET *handler_set = - ACE_Sig_Handlers_Set::instance (signum); - - ACE_SIG_HANDLERS_ITERATOR handler_iterator (*handler_set); - - for (ACE_Event_Handler **eh = 0; - handler_iterator.next (eh) != 0; - ) - if ((*eh)->handle_signal (signum, siginfo, ucontext) == -1) - { - handler_set->remove (*eh); - delete *eh; - } -} - -// Return the first item in the list of handlers. Note that this will -// trivially provide the same behavior as the ACE_Sig_Handler -// version if there is only 1 handler registered! - -ACE_Event_Handler * -ACE_Sig_Handlers::handler (int signum) -{ - ACE_TRACE ("ACE_Sig_Handlers::handler"); - ACE_SIG_HANDLERS_SET *handler_set = - ACE_Sig_Handlers_Set::instance (signum); - ACE_SIG_HANDLERS_ITERATOR handler_iterator (*handler_set); - ACE_Event_Handler **eh = 0; - handler_iterator.next (eh); - return *eh; -} - -// The following is a strange bit of logic that tries to give the same -// semantics as what happens in ACE_Sig_Handler when we replace the -// current signal handler with a new one. Note that if there is only -// one signal handler the behavior will be identical. If there is -// more than one handler then things get weird... - -ACE_Event_Handler * -ACE_Sig_Handlers::handler (int signum, ACE_Event_Handler *new_sh) -{ - ACE_TRACE ("ACE_Sig_Handlers::handler"); - ACE_SIG_HANDLERS_SET *handler_set = - ACE_Sig_Handlers_Set::instance (signum); - ACE_SIG_HANDLERS_ITERATOR handler_iterator (*handler_set); - ACE_Event_Handler **eh = 0; - - // Find the first handler... - handler_iterator.next (eh); - - // ... then remove it from the set ... - handler_set->remove (*eh); - - // ... and then insert the new signal handler into the beginning of - // the set (note, this is a bit too tied up in the implementation of - // ACE_Unbounded_Set...). - ACE_Sig_Adapter *temp = 0; - - ACE_NEW_RETURN (temp, - ACE_Sig_Adapter (new_sh, - ++ACE_Sig_Handlers::sigkey_), - 0); - handler_set->insert (temp); - return *eh; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Sig_Handler.h b/externals/ace/Sig_Handler.h deleted file mode 100644 index df1f0bfc495..00000000000 --- a/externals/ace/Sig_Handler.h +++ /dev/null @@ -1,237 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Sig_Handler.h - * - * $Id: Sig_Handler.h 84727 2009-03-05 19:22:29Z johnnyw $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_SIGNAL_HANDLER_H -#define ACE_SIGNAL_HANDLER_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Event_Handler.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -class ACE_Sig_Action; - -/** - * @class ACE_Sig_Handler - * - * @brief This is the main dispatcher of signals for ACE. It improves - * the existing UNIX signal handling mechanism by allowing C++ - * objects to handle signals in a way that avoids the use of - * global/static variables and functions. - * - * Using this class a program can register an ACE_Event_Handler - * with the ACE_Sig_Handler in order to handle a designated - * @a signum. When a signal occurs that corresponds to this - * @a signum, the @c handle_signal method of the registered - * ACE_Event_Handler is invoked automatically. - */ -class ACE_Export ACE_Sig_Handler -{ -public: - /// Default constructor. - ACE_Sig_Handler (void); - - /// Destructor - virtual ~ACE_Sig_Handler (void); - - // = Registration and removal methods. - /** - * Add a new ACE_Event_Handler and a new sigaction associated with - * @a signum. Passes back the existing ACE_Event_Handler and its - * sigaction if pointers are non-zero. Returns -1 on failure and >= - * 0 on success. - */ - virtual int register_handler (int signum, - ACE_Event_Handler *new_sh, - ACE_Sig_Action *new_disp = 0, - ACE_Event_Handler **old_sh = 0, - ACE_Sig_Action *old_disp = 0); - - /** - * Remove the ACE_Event_Handler currently associated with - * @a signum. @a sigkey is ignored in this implementation since there - * is only one instance of a signal handler. Install the new - * disposition (if given) and return the previous disposition (if - * desired by the caller). Returns 0 on success and -1 if @a signum - * is invalid. - */ - virtual int remove_handler (int signum, - ACE_Sig_Action *new_disp = 0, - ACE_Sig_Action *old_disp = 0, - int sigkey = -1); - - // Set/get signal status. - /// True if there is a pending signal. - static int sig_pending (void); - - /// Reset the value of so that no signal is pending. - static void sig_pending (int); - - // = Set/get the handler associated with a particular signal. - - /// Return the ACE_Sig_Handler associated with @a signum. - virtual ACE_Event_Handler *handler (int signum); - - /// Set a new ACE_Event_Handler that is associated with @a signum. - /// Return the existing handler. - virtual ACE_Event_Handler *handler (int signum, ACE_Event_Handler *); - - /** - * Callback routine registered with sigaction(2) that dispatches the - * method of the appropriate pre-registered - * ACE_Event_Handler. - */ - static void dispatch (int, siginfo_t *, - ucontext_t *); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - // = These methods and data members are shared by derived classes. - - /** - * Set a new ACE_Event_Handler that is associated with @a signum. - * Return the existing handler. Does not acquire any locks so that - * it can be called from a signal handler, such as . - */ - static ACE_Event_Handler *handler_i (int signum, - ACE_Event_Handler *); - - /** - * This implementation method is called by and - * @c dispatch. It doesn't do any locking so that it can be called - * within a signal handler, such as @c dispatch. It adds a new - * ACE_Event_Handler and a new sigaction associated with @a signum. - * Passes back the existing ACE_Event_Handler and its sigaction if - * pointers are non-zero. Returns -1 on failure and >= 0 on - * success. - */ - static int register_handler_i (int signum, - ACE_Event_Handler *new_sh, - ACE_Sig_Action *new_disp = 0, - ACE_Event_Handler **old_sh = 0, - ACE_Sig_Action *old_disp = 0); - - /// Check whether the SIGNUM is within the legal range of signals. - static int in_range (int signum); - - /// Keeps track of whether a signal is pending. - static sig_atomic_t sig_pending_; - -private: - /// Array used to store one user-defined Event_Handler for every - /// signal. - static ACE_Event_Handler *signal_handlers_[ACE_NSIG]; -}; - -/** - * @class ACE_Sig_Handlers - * - * @brief This is an alternative signal handling dispatcher for ACE. It - * allows a list of signal handlers to be registered for each - * signal. It also makes SA_RESTART the default mode. - * - * Using this class a program can register one or more - * ACE_Event_Handler with the ACE_Sig_Handler in order to - * handle a designated @a signum. When a signal occurs that - * corresponds to this @a signum, the methods of - * all the registered ACE_Event_Handlers are invoked - * automatically. - */ -class ACE_Export ACE_Sig_Handlers : public ACE_Sig_Handler -{ -public: - // = Registration and removal methods. - /** - * Add a new ACE_Event_Handler and a new sigaction associated with - * @a signum. Passes back the existing ACE_Event_Handler and its - * sigaction if pointers are non-zero. Returns -1 on failure and - * a that is >= 0 on success. - */ - virtual int register_handler (int signum, - ACE_Event_Handler *new_sh, - ACE_Sig_Action *new_disp = 0, - ACE_Event_Handler **old_sh = 0, - ACE_Sig_Action *old_disp = 0); - - /** - * Remove an ACE_Event_Handler currently associated with @a signum. - * We remove the handler if (1) its sigkey> matches the @a sigkey - * passed as a parameter or (2) if we've been told to remove all the - * handlers, i.e., @a sigkey == -1. If a new disposition is given it - * is installed and the previous disposition is returned (if desired - * by the caller). Returns 0 on success and -1 if @a signum is - * invalid. - */ - virtual int remove_handler (int signum, - ACE_Sig_Action *new_disp = 0, - ACE_Sig_Action *old_disp = 0, - int sigkey = -1); - - // = Set/get the handler associated with a particular signal. - - /// Return the head of the list of s associated with - /// SIGNUM. - virtual ACE_Event_Handler *handler (int signum); - - /** - * Set a new ACE_Event_Handler that is associated with SIGNUM at - * the head of the list of signals. Return the existing handler - * that was at the head. - */ - virtual ACE_Event_Handler *handler (int signum, - ACE_Event_Handler *); - - /** - * Callback routine registered with sigaction(2) that dispatches the - * method of all the pre-registered - * ACE_Event_Handlers for @a signum - */ - static void dispatch (int signum, siginfo_t *, ucontext_t *); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - /** - * Keeps track of the id that uniquely identifies each registered - * signal handler. This id can be used to cancel a timer via the - * method. - */ - static int sigkey_; - - /// If this is true then a 3rd party library has registered a - /// handler... - static bool third_party_sig_handler_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Sig_Handler.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_SIG_HANDLER_H */ diff --git a/externals/ace/Sig_Handler.inl b/externals/ace/Sig_Handler.inl deleted file mode 100644 index de02c09ab16..00000000000 --- a/externals/ace/Sig_Handler.inl +++ /dev/null @@ -1,15 +0,0 @@ -// -*- C++ -*- -// -// $Id: Sig_Handler.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_INLINE -ACE_Sig_Handler::ACE_Sig_Handler (void) -{ -} - -ACE_INLINE int -ACE_Sig_Handler::in_range (int signum) -{ - ACE_TRACE ("ACE_Sig_Handler::in_range"); - return signum > 0 && signum < ACE_NSIG; -} diff --git a/externals/ace/Signal.cpp b/externals/ace/Signal.cpp deleted file mode 100644 index 5f17455502b..00000000000 --- a/externals/ace/Signal.cpp +++ /dev/null @@ -1,221 +0,0 @@ -// $Id: Signal.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Signal.h" -// #include "ace/Log_Msg.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Signal.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID(ace, Signal, "$Id: Signal.cpp 80826 2008-03-04 14:51:23Z wotte $") - - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Sig_Action) - -void -ACE_Sig_Action::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Sig_Action::dump"); -#endif /* ACE_HAS_DUMP */ -} - -ACE_ALLOC_HOOK_DEFINE(ACE_Sig_Set) - -ACE_Sig_Set::~ACE_Sig_Set (void) -{ - ACE_TRACE ("ACE_Sig_Set::~ACE_Sig_Set"); - ACE_OS::sigemptyset (&this->sigset_); -} - -ACE_Sig_Action::~ACE_Sig_Action (void) -{ - ACE_TRACE ("ACE_Sig_Action::~ACE_Sig_Action"); -} - -// Restore the signal mask. - -ACE_Sig_Guard::~ACE_Sig_Guard (void) -{ - //ACE_TRACE ("ACE_Sig_Guard::~ACE_Sig_Guard"); - if (!this->condition_) - return; - -#if !defined (ACE_LACKS_UNIX_SIGNALS) -#if defined (ACE_LACKS_PTHREAD_THR_SIGSETMASK) - ACE_OS::sigprocmask (SIG_SETMASK, - (sigset_t *) this->omask_, - 0); -#else - ACE_OS::thr_sigsetmask (SIG_SETMASK, - (sigset_t *) this->omask_, - 0); -#endif /* ACE_LACKS_PTHREAD_THR_SIGSETMASK */ -#endif /* !ACE_LACKS_UNIX_SIGNALS */ -} - -void -ACE_Sig_Set::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Sig_Set::dump"); -#endif /* ACE_HAS_DUMP */ -} - -ACE_ALLOC_HOOK_DEFINE(ACE_Sig_Guard) - -void -ACE_Sig_Guard::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Sig_Guard::dump"); -#endif /* ACE_HAS_DUMP */ -} - -ACE_Sig_Action::ACE_Sig_Action (void) -{ - // ACE_TRACE ("ACE_Sig_Action::ACE_Sig_Action"); - this->sa_.sa_flags = 0; - - // Since Service_Config::signal_handler_ is static and has an - // ACE_Sig_Action instance, Win32 will get errno set unless this is - // commented out. -#if !defined (ACE_WIN32) - ACE_OS::sigemptyset (&this->sa_.sa_mask); -#endif /* ACE_WIN32 */ - this->sa_.sa_handler = 0; -} - -ACE_Sig_Action::ACE_Sig_Action (ACE_SignalHandler sig_handler, - sigset_t *sig_mask, - int sig_flags) -{ - // ACE_TRACE ("ACE_Sig_Action::ACE_Sig_Action"); - this->sa_.sa_flags = sig_flags; - - if (sig_mask == 0) - ACE_OS::sigemptyset (&this->sa_.sa_mask); - else - this->sa_.sa_mask = *sig_mask; // Structure assignment... - -#if !defined(ACE_HAS_TANDEM_SIGNALS) - this->sa_.sa_handler = ACE_SignalHandlerV (sig_handler); -#else - this->sa_.sa_handler = (void (*)()) ACE_SignalHandlerV (sig_handler); -#endif /* !ACE_HAS_TANDEM_SIGNALS */ -} - -ACE_Sig_Action::ACE_Sig_Action (ACE_SignalHandler sig_handler, - const ACE_Sig_Set &sig_mask, - int sig_flags) -{ - // ACE_TRACE ("ACE_Sig_Action::ACE_Sig_Action"); - this->sa_.sa_flags = sig_flags; - - // Structure assignment... - this->sa_.sa_mask = sig_mask.sigset (); - -#if !defined(ACE_HAS_TANDEM_SIGNALS) - this->sa_.sa_handler = ACE_SignalHandlerV (sig_handler); -#else - this->sa_.sa_handler = (void (*)()) ACE_SignalHandlerV (sig_handler); -#endif /* !ACE_HAS_TANDEM_SIGNALS */ -} - -ACE_Sig_Action::ACE_Sig_Action (ACE_SignalHandler sig_handler, - int signum, - sigset_t *sig_mask, - int sig_flags) -{ - // ACE_TRACE ("ACE_Sig_Action::ACE_Sig_Action"); - this->sa_.sa_flags = sig_flags; - - if (sig_mask == 0) - ACE_OS::sigemptyset (&this->sa_.sa_mask); - else - this->sa_.sa_mask = *sig_mask; // Structure assignment... - -#if !defined(ACE_HAS_TANDEM_SIGNALS) - this->sa_.sa_handler = ACE_SignalHandlerV (sig_handler); -#else - this->sa_.sa_handler = (void (*)()) ACE_SignalHandlerV (sig_handler); -#endif /* !ACE_HAS_TANDEM_SIGNALS */ - ACE_OS::sigaction (signum, &this->sa_, 0); -} - -ACE_Sig_Action::ACE_Sig_Action (ACE_SignalHandler sig_handler, - int signum, - const ACE_Sig_Set &sig_mask, - int sig_flags) -{ - // ACE_TRACE ("ACE_Sig_Action::ACE_Sig_Action"); - this->sa_.sa_flags = sig_flags; - - // Structure assignment... - this->sa_.sa_mask = sig_mask.sigset (); - -#if !defined(ACE_HAS_TANDEM_SIGNALS) - this->sa_.sa_handler = ACE_SignalHandlerV (sig_handler); -#else - this->sa_.sa_handler = (void (*)()) ACE_SignalHandlerV (sig_handler); -#endif /* !ACE_HAS_TANDEM_SIGNALS */ - ACE_OS::sigaction (signum, &this->sa_, 0); -} - -ACE_Sig_Action::ACE_Sig_Action (const ACE_Sig_Set &signals, - ACE_SignalHandler sig_handler, - const ACE_Sig_Set &sig_mask, - int sig_flags) -{ - // ACE_TRACE ("ACE_Sig_Action::ACE_Sig_Action"); - this->sa_.sa_flags = sig_flags; - - // Structure assignment... - this->sa_.sa_mask = sig_mask.sigset (); - -#if !defined(ACE_HAS_TANDEM_SIGNALS) - this->sa_.sa_handler = ACE_SignalHandlerV (sig_handler); -#else - this->sa_.sa_handler = (void (*)()) ACE_SignalHandlerV (sig_handler); -#endif /* !ACE_HAS_TANDEM_SIGNALS */ - -#if (ACE_NSIG > 0) - for (int s = 1; s < ACE_NSIG; s++) - if ((signals.is_member (s)) == 1) - ACE_OS::sigaction (s, &this->sa_, 0); -#else /* ACE_NSIG <= 0 */ - ACE_UNUSED_ARG (signals); -#endif /* ACE_NSIG <= 0 */ -} - -ACE_Sig_Action::ACE_Sig_Action (const ACE_Sig_Set &signals, - ACE_SignalHandler sig_handler, - sigset_t *sig_mask, - int sig_flags) -{ - // ACE_TRACE ("ACE_Sig_Action::ACE_Sig_Action"); - this->sa_.sa_flags = sig_flags; - - if (sig_mask == 0) - ACE_OS::sigemptyset (&this->sa_.sa_mask); - else - this->sa_.sa_mask = *sig_mask; // Structure assignment... - -#if !defined(ACE_HAS_TANDEM_SIGNALS) - this->sa_.sa_handler = ACE_SignalHandlerV (sig_handler); -#else - this->sa_.sa_handler = (void (*)()) ACE_SignalHandlerV (sig_handler); -#endif /* !ACE_HAS_TANDEM_SIGNALS */ - -#if (ACE_NSIG > 0) - for (int s = 1; s < ACE_NSIG; s++) - if ((signals.is_member (s)) == 1) - ACE_OS::sigaction (s, &this->sa_, 0); -#else /* ACE_NSIG <= 0 */ - ACE_UNUSED_ARG (signals); -#endif /* ACE_NSIG <= 0 */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Signal.h b/externals/ace/Signal.h deleted file mode 100644 index 736d62e5c08..00000000000 --- a/externals/ace/Signal.h +++ /dev/null @@ -1,267 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Signal.h - * - * $Id: Signal.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_SIGNAL_H -#define ACE_SIGNAL_H -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if defined (ACE_DONT_INCLUDE_ACE_SIGNAL_H) -# error ace/Signal.h was #included instead of signal.h by ace/OS_NS_signal.h: fix!!!! -#endif /* ACE_DONT_INCLUDE_ACE_SIGNAL_H */ - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/OS_NS_signal.h" - -// Type of the extended signal handler. -typedef void (*ACE_Sig_Handler_Ex) (int, siginfo_t *siginfo, ucontext_t *ucontext); - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Sig_Set - * - * @brief Provide a C++ wrapper for the C sigset_t interface. - * - * Handle signals via a more elegant C++ interface (e.g., - * doesn't require the use of global variables or global - * functions in an application). - */ -class ACE_Export ACE_Sig_Set -{ -public: - // = Initialization and termination methods. - /// Initialize with @a sigset. If @a sigset == 0 then fill - /// the set. - ACE_Sig_Set (sigset_t *sigset); - - /// Initialize with @a sigset. If @a sigset == 0 then fill - /// the set. - ACE_Sig_Set (ACE_Sig_Set *sigset); - - /// If @a fill == 0 then initialize the to be empty, else - /// full. - ACE_Sig_Set (int fill = 0); - - ~ACE_Sig_Set (void); - - /// Create a set that excludes all signals defined by the system. - int empty_set (void); - - /// Create a set that includes all signals defined by the system. - int fill_set (void); - - /// Adds the individual signal specified by @a signo to the set. - int sig_add (int signo); - - /// Deletes the individual signal specified by @a signo from the set. - int sig_del (int signo); - - /// Checks whether the signal specified by @a signo is in the set. - int is_member (int signo) const; - - /// Returns a pointer to the underlying @c sigset_t. - operator sigset_t *(); - - /// Returns a copy of the underlying @c sigset_t. - sigset_t sigset (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - /// Set of signals. - sigset_t sigset_; -}; - -/** - * @class ACE_Sig_Action - * - * @brief C++ wrapper facade for the @c sigaction struct. - */ -class ACE_Export ACE_Sig_Action -{ -public: - // = Initialization methods. - /// Default constructor. Initializes everything to 0. - ACE_Sig_Action (void); - - /// Assigns the various fields of a @c sigaction struct but doesn't - /// register for signal handling via the @c sigaction function. - ACE_Sig_Action (ACE_SignalHandler handler, - sigset_t *sigmask = 0, - int flags = 0); - - /// Assigns the various fields of a @c sigaction struct but doesn't - /// register for signal handling via the @c sigaction function. - ACE_Sig_Action (ACE_SignalHandler handler, - const ACE_Sig_Set &sigmask, - int flags = 0); - - /** - * Assigns the various fields of a @c sigaction struct and registers - * the @a handler to process signal @a signum via the @c sigaction - * function. - */ - ACE_Sig_Action (ACE_SignalHandler handler, - int signum, - sigset_t *sigmask = 0, - int flags = 0); - - /** - * Assigns the various fields of a @c sigaction struct and registers - * the @a handler to process signal @a signum via the @c sigaction - * function. - */ - ACE_Sig_Action (ACE_SignalHandler handler, - int signum, - const ACE_Sig_Set &sigmask, - int flags = 0); - - - // @@ The next two methods have a parameter as "signalss". Please do - // not change the argument name as "signals". This causes the - // following problem as reported by - // . - - // In the file Signal.h two of the functions have and argument name - // of signals. signals is a Qt macro (to do with their meta object - // stuff. - // We could as well have it as "signal", but I am nost sure whether - // that would cause a problem with something else - Bala - - /** - * Assigns the various fields of a @c sigaction struct and registers - * the @a handler to process all @a signalss via the @c sigaction - * function. - */ - ACE_Sig_Action (const ACE_Sig_Set &signalss, - ACE_SignalHandler handler, - const ACE_Sig_Set &sigmask, - int flags = 0); - - /** - * Assigns the various fields of a @c sigaction struct and registers - * the @a handler to process all @a signalss via the @c sigaction - * function. - */ - ACE_Sig_Action (const ACE_Sig_Set &signalss, - ACE_SignalHandler handler, - sigset_t *sigmask = 0, - int flags = 0); - - /// Copy constructor. - ACE_Sig_Action (const ACE_Sig_Action &s); - - /// Default dtor. - ~ACE_Sig_Action (void); - - // = Signal action management. - /// Register @c this as the current disposition and store old - /// disposition into @a oaction if it is non-NULL. - int register_action (int signum, - ACE_Sig_Action *oaction = 0); - - /// Assign the value of @a oaction to @c this and make it become the - /// new signal disposition. - int restore_action (int signum, - ACE_Sig_Action &oaction); - - /// Retrieve the current disposition into @c this. - int retrieve_action (int signum); - - /// Set current signal action. - void set (struct sigaction *); - - /// Get current signal action. - struct sigaction *get (void); - operator struct sigaction *(); - - /// Set current signal flags. - void flags (int); - - /// Get current signal flags. - int flags (void); - - /// Set current signal mask. - void mask (sigset_t *); - void mask (ACE_Sig_Set &); - - /// Get current signal mask. - sigset_t *mask (void); - - /// Set current signal handler (pointer to function). - void handler (ACE_SignalHandler); - - /// Get current signal handler (pointer to function). - ACE_SignalHandler handler (void); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - /// Controls signal behavior. - struct sigaction sa_; -}; - -/** - * @class ACE_Sig_Guard - * - * @brief Hold signals in MASK for duration of a C++ statement block. - * Note that a "0" for mask causes all signals to be held. - */ -class ACE_Export ACE_Sig_Guard -{ -public: - // = Initialization and termination methods. - /// This is kind of conditional Guard, needed when guard should be - /// activated only when a spcific condition met. When condition == - /// true (default), Guard is activated - ACE_Sig_Guard (ACE_Sig_Set *mask = 0, bool condition = true); - - /// Restore blocked signals. - ~ACE_Sig_Guard (void); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - /// Original signal mask. - ACE_Sig_Set omask_; - - /// Guard Condition - bool condition_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Signal.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_SIGNAL_HANDLER_H */ diff --git a/externals/ace/Signal.inl b/externals/ace/Signal.inl deleted file mode 100644 index 858c33c26fb..00000000000 --- a/externals/ace/Signal.inl +++ /dev/null @@ -1,265 +0,0 @@ -// -*- C++ -*- -// -// $Id: Signal.inl 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/OS_NS_signal.h" -#include "ace/config-all.h" -#include "ace/Trace.h" -#include "ace/Object_Manager_Base.h" -#include "ace/OS_NS_Thread.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE -ACE_Sig_Set::ACE_Sig_Set (sigset_t *ss) - // : sigset_ () -{ - ACE_TRACE ("ACE_Sig_Set::ACE_Sig_Set"); - - if (ss == 0) - ACE_OS::sigfillset (&this->sigset_); - else - // Structure assignment. - this->sigset_ = *ss; -} - -ACE_INLINE -ACE_Sig_Set::ACE_Sig_Set (int fill) - // : sigset_ () -{ - ACE_TRACE ("ACE_Sig_Set::ACE_Sig_Set"); - - if (fill) - ACE_OS::sigfillset (&this->sigset_); - else - ACE_OS::sigemptyset (&this->sigset_); -} - -ACE_INLINE -ACE_Sig_Set::ACE_Sig_Set (ACE_Sig_Set *ss) - // : sigset_ () -{ - ACE_TRACE ("ACE_Sig_Set::ACE_Sig_Set"); - - if (ss == 0) - ACE_OS::sigfillset (&this->sigset_); - else - this->sigset_ = ss->sigset_; -} - -ACE_INLINE int -ACE_Sig_Set::empty_set (void) -{ - ACE_TRACE ("ACE_Sig_Set::empty_set"); - return ACE_OS::sigemptyset (&this->sigset_); -} - -ACE_INLINE int -ACE_Sig_Set::fill_set (void) -{ - ACE_TRACE ("ACE_Sig_Set::fill_set"); - return ACE_OS::sigfillset (&this->sigset_); -} - -ACE_INLINE int -ACE_Sig_Set::sig_add (int signo) -{ - ACE_TRACE ("ACE_Sig_Set::sig_add"); - return ACE_OS::sigaddset (&this->sigset_, signo); -} - -ACE_INLINE int -ACE_Sig_Set::sig_del (int signo) -{ - ACE_TRACE ("ACE_Sig_Set::sig_del"); - return ACE_OS::sigdelset (&this->sigset_, signo); -} - -ACE_INLINE int -ACE_Sig_Set::is_member (int signo) const -{ - ACE_TRACE ("ACE_Sig_Set::is_member"); - return ACE_OS::sigismember (const_cast (&this->sigset_), signo); -} - -ACE_INLINE -ACE_Sig_Set::operator sigset_t *(void) -{ - ACE_TRACE ("ACE_Sig_Set::operator sigset_t *"); - return &this->sigset_; -} - -ACE_INLINE sigset_t -ACE_Sig_Set::sigset (void) const -{ - ACE_TRACE ("ACE_Sig_Set::sigset"); - return this->sigset_; -} - -ACE_INLINE int -ACE_Sig_Action::flags (void) -{ - ACE_TRACE ("ACE_Sig_Action::flags"); - return this->sa_.sa_flags; -} - -ACE_INLINE void -ACE_Sig_Action::flags (int flags) -{ - ACE_TRACE ("ACE_Sig_Action::flags"); - this->sa_.sa_flags = flags; -} - -ACE_INLINE sigset_t * -ACE_Sig_Action::mask (void) -{ - ACE_TRACE ("ACE_Sig_Action::mask"); - return &this->sa_.sa_mask; -} - -ACE_INLINE void -ACE_Sig_Action::mask (sigset_t *ss) -{ - ACE_TRACE ("ACE_Sig_Action::mask"); - if (ss != 0) - this->sa_.sa_mask = *ss; // Structure assignment -} - -ACE_INLINE void -ACE_Sig_Action::mask (ACE_Sig_Set &ss) -{ - ACE_TRACE ("ACE_Sig_Action::mask"); - this->sa_.sa_mask = ss.sigset (); // Structure assignment -} - -ACE_INLINE ACE_SignalHandler -ACE_Sig_Action::handler (void) -{ - ACE_TRACE ("ACE_Sig_Action::handler"); - return ACE_SignalHandler (this->sa_.sa_handler); -} - -ACE_INLINE void -ACE_Sig_Action::handler (ACE_SignalHandler handler) -{ - ACE_TRACE ("ACE_Sig_Action::handler"); -#if !defined(ACE_HAS_TANDEM_SIGNALS) - this->sa_.sa_handler = ACE_SignalHandlerV (handler); -#else - this->sa_.sa_handler = (void (*)()) ACE_SignalHandlerV (handler); -#endif /* !ACE_HAS_TANDEM_SIGNALS */ -} - -#if 0 -ACE_INLINE ACE_SignalHandler -ACE_Sig_Action::sigaction (void) -{ - ACE_TRACE ("ACE_Sig_Action::sigaction"); - return ACE_SignalHandler (this->sa_.sa_sigaction); -} - -ACE_INLINE void -ACE_Sig_Action::sigaction (ACE_SignalHandler handler) -{ - ACE_TRACE ("ACE_Sig_Action::sigaction"); - this->sa_.sa_sigaction = (void (*)()) ACE_SignalHandlerV (handler); -} -#endif /* 0 */ - -ACE_INLINE void -ACE_Sig_Action::set (struct sigaction *sa) -{ - ACE_TRACE ("ACE_Sig_Action::set"); - this->sa_ = *sa; // Structure assignment. -} - -ACE_INLINE struct sigaction * -ACE_Sig_Action::get (void) -{ - ACE_TRACE ("ACE_Sig_Action::get"); - return &this->sa_; -} - -ACE_INLINE -ACE_Sig_Action::operator struct sigaction * () -{ - ACE_TRACE ("ACE_Sig_Action::operator struct sigaction *"); - return &this->sa_; -} - -ACE_INLINE -ACE_Sig_Action::ACE_Sig_Action (const ACE_Sig_Action &s) - // : sa_ () -{ - ACE_TRACE ("ACE_Sig_Action::ACE_Sig_Action"); - *this = s; // structure copy. -} - -ACE_INLINE int -ACE_Sig_Action::register_action (int signum, ACE_Sig_Action *oaction) -{ - ACE_TRACE ("ACE_Sig_Action::register_action"); - struct sigaction *sa = oaction == 0 ? 0 : oaction->get (); - - return ACE_OS::sigaction (signum, &this->sa_, sa); -} - -ACE_INLINE int -ACE_Sig_Action::retrieve_action (int signum) -{ - ACE_TRACE ("ACE_Sig_Action::retrieve_action"); - return ACE_OS::sigaction (signum, 0, &this->sa_); -} - -ACE_INLINE int -ACE_Sig_Action::restore_action (int signum, ACE_Sig_Action &oaction) -{ - ACE_TRACE ("ACE_Sig_Action::restore_action"); - this->sa_ = *oaction.get (); // Structure assignment - return ACE_OS::sigaction (signum, &this->sa_, 0); -} - -// Block out the signal MASK until the destructor is called. - -ACE_INLINE -ACE_Sig_Guard::ACE_Sig_Guard (ACE_Sig_Set *mask, - bool condition) - : omask_ () - , condition_ (condition) -{ - //ACE_TRACE ("ACE_Sig_Guard::ACE_Sig_Guard"); - if (!this->condition_) - return; - -#if defined (ACE_LACKS_UNIX_SIGNALS) - ACE_UNUSED_ARG (mask); -#else - // If MASK is 0 then block all signals! - if (mask == 0) - { -# if defined (ACE_LACKS_PTHREAD_THR_SIGSETMASK) - ACE_OS::sigprocmask (SIG_BLOCK, - ACE_OS_Object_Manager::default_mask (), - (sigset_t *) this->omask_); -# else - ACE_OS::thr_sigsetmask (SIG_BLOCK, - ACE_OS_Object_Manager::default_mask (), - (sigset_t *) this->omask_); -# endif /* ACE_LACKS_PTHREAD_THR_SIGSETMASK */ - } - else -# if defined (ACE_LACKS_PTHREAD_THR_SIGSETMASK) - ACE_OS::sigprocmask (SIG_BLOCK, - (sigset_t *) *mask, - (sigset_t *) - this->omask_); -# else - ACE_OS::thr_sigsetmask (SIG_BLOCK, - (sigset_t *) *mask, - (sigset_t *) - this->omask_); -# endif /* ACE_LACKS_PTHREAD_THR_SIGSETMASK */ -#endif /* ACE_LACKS_UNIX_SIGNALS */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Singleton.cpp b/externals/ace/Singleton.cpp deleted file mode 100644 index 25b7983a2a6..00000000000 --- a/externals/ace/Singleton.cpp +++ /dev/null @@ -1,548 +0,0 @@ -// $Id: Singleton.cpp 84273 2009-01-30 12:55:25Z johnnyw $ - -#ifndef ACE_SINGLETON_CPP -#define ACE_SINGLETON_CPP - -#include "ace/Singleton.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (__ACE_INLINE__) -#include "ace/Singleton.inl" -#endif /* __ACE_INLINE__ */ - -#include "ace/Object_Manager.h" -#include "ace/Log_Msg.h" -#include "ace/Framework_Component.h" -#include "ace/Guard_T.h" -#include "ace/os_include/os_typeinfo.h" - -ACE_RCSID (ace, - Singleton, - "$Id: Singleton.cpp 84273 2009-01-30 12:55:25Z johnnyw $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template void -ACE_Singleton::dump (void) -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Singleton::dump"); - -#if !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("instance_ = %x"), - ACE_Singleton::instance_i ())); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ -#endif /* ACE_HAS_DUMP */ -} - -template ACE_Singleton *& -ACE_Singleton::instance_i (void) -{ -#if defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) - // Pointer to the Singleton instance. This works around a bug with - // G++ and it's (mis-)handling of templates and statics... - static ACE_Singleton *singleton_ = 0; - - return singleton_; -#else - return ACE_Singleton::singleton_; -#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ -} - -template TYPE * -ACE_Singleton::instance (void) -{ - ACE_TRACE ("ACE_Singleton::instance"); - - ACE_Singleton *&singleton = - ACE_Singleton::instance_i (); - - // Perform the Double-Check pattern... - if (singleton == 0) - { - if (ACE_Object_Manager::starting_up () || - ACE_Object_Manager::shutting_down ()) - { - // The program is still starting up, and therefore assumed - // to be single threaded. There's no need to double-check. - // Or, the ACE_Object_Manager instance has been destroyed, - // so the preallocated lock is not available. Either way, - // don't register for destruction with the - // ACE_Object_Manager: we'll have to leak this instance. - - ACE_NEW_RETURN (singleton, (ACE_Singleton), 0); - } - else - { -#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) - // Obtain a lock from the ACE_Object_Manager. The pointer - // is static, so we only obtain one per ACE_Singleton - // instantiation. - static ACE_LOCK *lock = 0; - if (ACE_Object_Manager::get_singleton_lock (lock) != 0) - // Failed to acquire the lock! - return 0; - - ACE_GUARD_RETURN (ACE_LOCK, ace_mon, *lock, 0); - - if (singleton == 0) - { -#endif /* ACE_MT_SAFE */ - ACE_NEW_RETURN (singleton, (ACE_Singleton), 0); - - // Register for destruction with ACE_Object_Manager. - ACE_Object_Manager::at_exit (singleton, 0, typeid (TYPE).name ()); -#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) - } -#endif /* ACE_MT_SAFE */ - } - } - - return &singleton->instance_; -} - -template void -ACE_Singleton::cleanup (void *) -{ - ACE_Object_Manager::remove_at_exit (this); - delete this; - ACE_Singleton::instance_i () = 0; -} - -template void -ACE_Singleton::close (void) -{ - ACE_Singleton *&singleton = - ACE_Singleton::instance_i (); - - if (singleton) - { - singleton->cleanup (); - ACE_Singleton::instance_i () = 0; - } -} - -#if !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) -// Pointer to the Singleton instance. -template ACE_Singleton * -ACE_Singleton::singleton_ = 0; - -template ACE_Unmanaged_Singleton * -ACE_Unmanaged_Singleton::singleton_ = 0; -#endif /* !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) */ - -template void -ACE_Unmanaged_Singleton::dump (void) -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Unmanaged_Singleton::dump"); - -#if !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("instance_ = %x"), - ACE_Unmanaged_Singleton::instance_i ())); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ -#endif /* ACE_HAS_DUMP */ -} - -template -ACE_Unmanaged_Singleton *& -ACE_Unmanaged_Singleton::instance_i (void) -{ -#if defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) - // Pointer to the Singleton instance. This works around a bug with - // G++ and it's (mis-)handling of templates and statics... - static ACE_Unmanaged_Singleton *singleton_ = 0; - - return singleton_; -#else - return ACE_Unmanaged_Singleton::singleton_; -#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ -} - -template TYPE * -ACE_Unmanaged_Singleton::instance (void) -{ - ACE_TRACE ("ACE_Unmanaged_Singleton::instance"); - - ACE_Unmanaged_Singleton *&singleton = - ACE_Unmanaged_Singleton::instance_i (); - - // Perform the Double-Check pattern... - if (singleton == 0) - { - if (ACE_Object_Manager::starting_up () || - ACE_Object_Manager::shutting_down ()) - { - // The program is still starting up, and therefore assumed - // to be single threaded. There's no need to double-check. - // Or, the ACE_Object_Manager instance has been destroyed, - // so the preallocated lock is not available. Either way, - // don't register for destruction with the - // ACE_Object_Manager: we'll have to leak this instance. - - ACE_NEW_RETURN (singleton, (ACE_Unmanaged_Singleton), - 0); - } - else - { -#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) - // Obtain a lock from the ACE_Object_Manager. The pointer - // is static, so we only obtain one per - // ACE_Unmanaged_Singleton instantiation. - static ACE_LOCK *lock = 0; - if (ACE_Object_Manager::get_singleton_lock (lock) != 0) - // Failed to acquire the lock! - return 0; - - ACE_GUARD_RETURN (ACE_LOCK, ace_mon, *lock, 0); -#endif /* ACE_MT_SAFE */ - - if (singleton == 0) - ACE_NEW_RETURN (singleton, - (ACE_Unmanaged_Singleton), - 0); - } - } - - return &singleton->instance_; -} - -template void -ACE_Unmanaged_Singleton::close (void) -{ - ACE_Unmanaged_Singleton *&singleton = - ACE_Unmanaged_Singleton::instance_i (); - - if (singleton) - { - singleton->cleanup (); - ACE_Unmanaged_Singleton::instance_i () = 0; - } -} - -template void -ACE_TSS_Singleton::dump (void) -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_TSS_Singleton::dump"); - -#if !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("instance_ = %x"), - ACE_TSS_Singleton::instance_i ())); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ -#endif /* ACE_HAS_DUMP */ -} - -template ACE_TSS_Singleton *& -ACE_TSS_Singleton::instance_i (void) -{ -#if defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) - // Pointer to the Singleton instance. This works around a bug with - // G++ and it's (mis-)handling of templates and statics... - static ACE_TSS_Singleton *singleton_ = 0; - - return singleton_; -#else - return ACE_TSS_Singleton::singleton_; -#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ -} - -template TYPE * -ACE_TSS_Singleton::instance (void) -{ - ACE_TRACE ("ACE_TSS_Singleton::instance"); - - ACE_TSS_Singleton *&singleton = - ACE_TSS_Singleton::instance_i (); - - // Perform the Double-Check pattern... - if (singleton == 0) - { - if (ACE_Object_Manager::starting_up () || - ACE_Object_Manager::shutting_down ()) - { - // The program is still starting up, and therefore assumed - // to be single threaded. There's no need to double-check. - // Or, the ACE_Object_Manager instance has been destroyed, - // so the preallocated lock is not available. Either way, - // don't register for destruction with the - // ACE_Object_Manager: we'll have to leak this instance. - - ACE_NEW_RETURN (singleton, (ACE_TSS_Singleton), 0); - } - else - { -#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) - - // Obtain a lock from the ACE_Object_Manager. The pointer - // is static, so we only obtain one per ACE_Singleton instantiation. - static ACE_LOCK *lock = 0; - if (ACE_Object_Manager::get_singleton_lock (lock) != 0) - // Failed to acquire the lock! - return 0; - - ACE_GUARD_RETURN (ACE_LOCK, ace_mon, *lock, 0); - - if (singleton == 0) - { -#endif /* ACE_MT_SAFE */ - ACE_NEW_RETURN (singleton, (ACE_TSS_Singleton), - 0); - - // Register for destruction with ACE_Object_Manager. - ACE_Object_Manager::at_exit (singleton, 0, typeid (TYPE).name ()); -#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) - } -#endif /* ACE_MT_SAFE */ - } - } - - return ACE_TSS_GET (&singleton->instance_, TYPE); -} - -template void -ACE_TSS_Singleton::cleanup (void *) -{ - delete this; - ACE_TSS_Singleton::instance_i () = 0; -} - -template void -ACE_Unmanaged_TSS_Singleton::dump (void) -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Unmanaged_TSS_Singleton::dump"); - -#if !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("instance_ = %x"), - ACE_Unmanaged_TSS_Singleton::instance_i ())); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ -#endif /* ACE_HAS_DUMP */ -} - -template -ACE_Unmanaged_TSS_Singleton *& -ACE_Unmanaged_TSS_Singleton::instance_i (void) -{ -#if defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) - // Pointer to the Singleton instance. This works around a bug with - // G++ and it's (mis-)handling of templates and statics... - static ACE_Unmanaged_TSS_Singleton *singleton_ = 0; - - return singleton_; -#else - return ACE_Unmanaged_TSS_Singleton::singleton_; -#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ -} - -template TYPE * -ACE_Unmanaged_TSS_Singleton::instance (void) -{ - ACE_TRACE ("ACE_Unmanaged_TSS_Singleton::instance"); - - ACE_Unmanaged_TSS_Singleton *&singleton = - ACE_Unmanaged_TSS_Singleton::instance_i (); - - // Perform the Double-Check pattern... - if (singleton == 0) - { - if (ACE_Object_Manager::starting_up () || - ACE_Object_Manager::shutting_down ()) - { - // The program is still starting up, and therefore assumed - // to be single threaded. There's no need to double-check. - // Or, the ACE_Object_Manager instance has been destroyed, - // so the preallocated lock is not available. Either way, - // don't register for destruction with the - // ACE_Object_Manager: we'll have to leak this instance. - - ACE_NEW_RETURN (singleton, - (ACE_Unmanaged_TSS_Singleton), - 0); - } - else - { -#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) - // Obtain a lock from the ACE_Object_Manager. The pointer - // is static, so we only obtain one per - // ACE_Unmanaged_Singleton instantiation. - static ACE_LOCK *lock = 0; - if (ACE_Object_Manager::get_singleton_lock (lock) != 0) - // Failed to acquire the lock! - return 0; - - ACE_GUARD_RETURN (ACE_LOCK, ace_mon, *lock, 0); -#endif /* ACE_MT_SAFE */ - - if (singleton == 0) - ACE_NEW_RETURN (singleton, - (ACE_Unmanaged_TSS_Singleton), - 0); - } - } - - return ACE_TSS_GET (&singleton->instance_, TYPE); -} - -template void -ACE_Unmanaged_TSS_Singleton::close (void) -{ - ACE_Unmanaged_TSS_Singleton *&singleton = - ACE_Unmanaged_TSS_Singleton::instance_i (); - - if (singleton) - singleton->cleanup (); -} - -#if !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) -// Pointer to the Singleton instance. -template ACE_TSS_Singleton * -ACE_TSS_Singleton::singleton_ = 0; - -template -ACE_Unmanaged_TSS_Singleton * -ACE_Unmanaged_TSS_Singleton::singleton_ = 0; -#endif /* !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) */ - -/*************************************************************************/ - -#if !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) -// Pointer to the Singleton instance. -template ACE_DLL_Singleton_T * -ACE_DLL_Singleton_T::singleton_ = 0; -#endif /* !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) */ - -template void -ACE_DLL_Singleton_T::dump (void) -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_DLL_Singleton_T::dump"); - -#if !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("instance_ = %x"), - ACE_DLL_Singleton_T::instance_i ())); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ -#endif /* ACE_HAS_DUMP */ -} - -template -ACE_DLL_Singleton_T *& -ACE_DLL_Singleton_T::instance_i (void) -{ - ACE_TRACE ("ACE_DLL_Singleton_T::instance_i"); - -#if defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) - // Pointer to the Singleton instance. This works around a bug with - // G++ and it's (mis-)handling of templates and statics... - static ACE_DLL_Singleton_T *singleton_ = 0; - - return singleton_; -#else - return ACE_DLL_Singleton_T::singleton_; -#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ -} - -template TYPE * -ACE_DLL_Singleton_T::instance (void) -{ - ACE_TRACE ("ACE_DLL_Singleton_T::instance"); - - ACE_DLL_Singleton_T *&singleton = - ACE_DLL_Singleton_T::instance_i (); - - // Perform the Double-Check pattern... - if (singleton == 0) - { - if (ACE_Object_Manager::starting_up () || - ACE_Object_Manager::shutting_down ()) - { - // The program is still starting up, and therefore assumed - // to be single threaded. There's no need to double-check. - // Or, the ACE_Object_Manager instance has been destroyed, - // so the preallocated lock is not available. Either way, - // don't register for destruction with the - // ACE_Object_Manager: we'll have to leak this instance. - - ACE_NEW_RETURN (singleton, (ACE_DLL_Singleton_T), - 0); - } - else - { -#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) - // Obtain a lock from the ACE_Object_Manager. The pointer - // is static, so we only obtain one per - // ACE_Unmanaged_Singleton instantiation. - static ACE_LOCK *lock = 0; - if (ACE_Object_Manager::get_singleton_lock (lock) != 0) - // Failed to acquire the lock! - return 0; - - ACE_GUARD_RETURN (ACE_LOCK, ace_mon, *lock, 0); -#endif /* ACE_MT_SAFE */ - - if (singleton == 0) - ACE_NEW_RETURN (singleton, - (ACE_DLL_Singleton_T), - 0); - } - //ACE_REGISTER_FRAMEWORK_COMPONENT(ACE_DLL_Singleton, singleton); - ACE_Framework_Repository::instance ()->register_component - (new ACE_Framework_Component_T > (singleton)); - } - - return &singleton->instance_; -} - -template void -ACE_DLL_Singleton_T::close (void) -{ - ACE_TRACE ("ACE_DLL_Singleton_T::close"); - - ACE_DLL_Singleton_T *&singleton = - ACE_DLL_Singleton_T::instance_i (); - - delete singleton; - singleton = 0; -} - -template void -ACE_DLL_Singleton_T::close_singleton (void) -{ - ACE_TRACE ("ACE_DLL_Singleton_T::close_singleton"); - ACE_DLL_Singleton_T::close (); -} - -template const ACE_TCHAR * -ACE_DLL_Singleton_T::dll_name (void) -{ - return this->instance ()->dll_name (); -} - -template const ACE_TCHAR * -ACE_DLL_Singleton_T::name (void) -{ - return this->instance ()->name (); -} - - -/**********************************************************************/ - -template const ACE_TCHAR* -ACE_DLL_Singleton_Adapter_T::dll_name (void) -{ - // @todo make this a constant somewhere (or it there already is one - // then use it. - return ACE_TEXT("ACE"); -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_SINGLETON_CPP */ diff --git a/externals/ace/Singleton.h b/externals/ace/Singleton.h deleted file mode 100644 index 308ddc3c245..00000000000 --- a/externals/ace/Singleton.h +++ /dev/null @@ -1,330 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Singleton.h - * - * $Id: Singleton.h 84273 2009-01-30 12:55:25Z johnnyw $ - * - * @brief - * - * @author Tim Harrison - * @author Douglas C. Schmidt - * @author Chris Lahey - * @author Rich Christy - * @author David Levine - */ -//============================================================================= - -#ifndef ACE_SINGLETON_H -#define ACE_SINGLETON_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" -#include "ace/TSS_T.h" -#include "ace/Cleanup.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Singleton - * - * @brief A Singleton Adapter uses the Adapter pattern to turn ordinary - * classes into Singletons optimized with the Double-Checked - * Locking optimization pattern. - * - * This implementation is a slight variation on the GoF - * Singleton pattern. In particular, a single - * > instance is allocated here, - * not a instance. The reason for this is to allow - * registration with the ACE_Object_Manager, so that the - * Singleton can be cleaned up when the process exits. For this - * scheme to work, a (static) cleanup() function must be - * provided. ACE_Singleton provides one so that TYPE doesn't - * need to. - * If you want to make sure that only the singleton instance of - * is created, and that users cannot create their own - * instances of , do the following to class : - * (a) Make the constructor of private (or protected) - * (b) Make Singleton a friend of - * Here is an example: - * @verbatim - * class foo - * { - * friend class ACE_Singleton; - * private: - * foo () { cout << "foo constructed" << endl; } - * ~foo () { cout << "foo destroyed" << endl; } - * }; - * typedef ACE_Singleton FOO; - * @endverbatim - * - * @note The best types to use for ACE_LOCK are - * ACE_Recursive_Thread_Mutex and ACE_Null_Mutex. - * ACE_Recursive_Thread_Mutex should be used in multi-threaded - * programs in which it is possible for more than one thread to - * access the > instance. - * ACE_Null_Mutex can be used otherwise. The reason that these - * types of locks are best has to do with their allocation by - * the ACE_Object_Manager. Single ACE_Recursive_Thread_Mutex - * and ACE_Null_Mutex instances are used for all ACE_Singleton - * instantiations. However, other types of locks are allocated - * per ACE_Singleton instantiation. - */ -template -class ACE_Singleton : public ACE_Cleanup -{ -public: - /// Global access point to the Singleton. - static TYPE *instance (void); - - /// Cleanup method, used by @c ace_cleanup_destroyer to destroy the - /// ACE_Singleton. - virtual void cleanup (void *param = 0); - - /// Explicitly delete the Singleton instance. - static void close (void); - - /// Dump the state of the object. - static void dump (void); - -protected: - /// Default constructor. - ACE_Singleton (void); - - /// Contained instance. - TYPE instance_; - -#if !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) - /// Pointer to the Singleton (ACE_Cleanup) instance. - static ACE_Singleton *singleton_; -#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ - - /// Get pointer to the Singleton instance. - static ACE_Singleton *&instance_i (void); -}; - -/** - * @class ACE_Unmanaged_Singleton - * - * @brief Same as ACE_Singleton, except does _not_ register with - * ACE_Object_Manager for destruction. - * - * This version of ACE_Singleton can be used if, for example, - * its DLL will be unloaded before the ACE_Object_Manager - * destroys the instance. Unlike with ACE_Singleton, the - * application is responsible for explicitly destroying the - * instance after it is no longer needed (if it wants to avoid - * memory leaks, at least). The close() static member function - * must be used to explicitly destroy the Singleton. - * Usage is the same as for ACE_Singleton, but note that if you - * you declare a friend, the friend class must still be an - * *ACE_Singleton*, not an ACE_Unmanaged_Singleton. - */ -template -class ACE_Unmanaged_Singleton : public ACE_Singleton -{ -public: - /// Global access point to the Singleton. - static TYPE *instance (void); - - /// Explicitly delete the Singleton instance. - static void close (void); - - /// Dump the state of the object. - static void dump (void); - -protected: - /// Default constructor. - ACE_Unmanaged_Singleton (void); - -#if !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) - /// Pointer to the Singleton (ACE_Cleanup) instance. - static ACE_Unmanaged_Singleton *singleton_; -#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ - - /// Get pointer to the Singleton instance. - static ACE_Unmanaged_Singleton *&instance_i (void); -}; - -/** - * @class ACE_TSS_Singleton - * - * @brief This class uses the Adapter pattern to turn ordinary classes - * into Thread-specific Singletons optimized with the - * Double-Checked Locking optimization pattern. - * - * This implementation is another variation on the GoF Singleton - * pattern. In this case, a single > instance is allocated here, not a instance. - * Each call to the static method returns a Singleton - * whose pointer resides in thread-specific storage. As with - * ACE_Singleton, we use the ACE_Object_Manager so that the - * Singleton can be cleaned up when the process exits. For this - * scheme to work, a (static) cleanup() function must be - * provided. ACE_Singleton provides one so that TYPE doesn't - * need to. - */ -template -class ACE_TSS_Singleton : public ACE_Cleanup -{ -public: - /// Global access point to the singleton. - static TYPE *instance (void); - - /// Cleanup method, used by to destroy the - /// singleton. - virtual void cleanup (void *param = 0); - - /// Dump the state of the object. - static void dump (void); - -protected: - /// Default constructor. - ACE_TSS_Singleton (void); - - /// Contained instance. - ACE_TSS_TYPE (TYPE) instance_; - - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_TSS_Singleton &)) - ACE_UNIMPLEMENTED_FUNC (ACE_TSS_Singleton (const ACE_TSS_Singleton &)) - -#if !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) - /// Pointer to the Singleton (ACE_Cleanup) instance. - static ACE_TSS_Singleton *singleton_; -#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ - - /// Get pointer to the TSS Singleton instance. - static ACE_TSS_Singleton *&instance_i (void); -}; - -/** - * @class ACE_Unmanaged_TSS_Singleton - * - * @brief Same as ACE_TSS_Singleton, except does _not_ register with - * ACE_Object_Manager for destruction. - * - * This version of ACE_TSS_Singleton can be used if, for example, its DLL will - * be unloaded before the ACE_Object_Manager destroys the instance. Unlike with - * ACE_Singleton, the application is responsible for explicitly destroying the - * instance after it is no longer needed (if it wants to avoid memory leaks, - * at least). The close() static member function must be used to explicitly - * destroy the Singleton. - */ -template -class ACE_Unmanaged_TSS_Singleton : public ACE_TSS_Singleton -{ -public: - /// Global access point to the singleton. - static TYPE *instance (void); - - /// Explicitly delete the singleton instance. - static void close (void); - - /// Dump the state of the object. - static void dump (void); - -protected: - /// Default constructor. - ACE_Unmanaged_TSS_Singleton (void); - -#if !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) - /// Pointer to the Singleton (ACE_Cleanup) instance. - static ACE_Unmanaged_TSS_Singleton *singleton_; -#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ - - /// Get pointer to the Singleton instance. - static ACE_Unmanaged_TSS_Singleton *&instance_i (void); -}; - -/** - * @class ACE_DLL_Singleton_T - * - * @brief Same as ACE_Singleton, except that it registers for - * destruction with the ACE_Framework_Repository instead of - * with the ACE_Object_Manager directly. - * - * This version of ACE_Singleton should be used for singletons - * that live in a dll loaded either directly by ACE_DLL or indirectly - * by the ACE Service Configuration framework. Whenever ACE_DLL is ready - * to actually unload the dll, ACE_DLL_Singleton based dlls associated - * with that dll will be destroyed first. In fact, any singleton can - * safely use ACE_DLL_Singleton, even those that don't live in dlls. In - * that case, the singleton will be destroyed at normal program shutdown. - * - * The only additional requirement is that the contained class - * export name() and dll_name() methods. See ACE_DLL_Singleton_Adapter_T - * below for a convenient example of how to satisfy this - * requirement for the dll_name(). - * - * Usage is the same as for ACE_Singleton, but note that if you - * you declare a friend, the friend class must still be an - * *ACE_Singleton*, not an ACE_Unmanaged_Singleton. - */ -template -class ACE_DLL_Singleton_T -{ -public: - //void cleanup (void *param = 0); - - /// Global access point to the Singleton. - static TYPE *instance (void); - - /// Explicitly delete the Singleton instance. - static void close (void); - - static void close_singleton (void); - - /// Dump the state of the object. - static void dump (void); - - const ACE_TCHAR *dll_name (void); - - const ACE_TCHAR *name (void); - -protected: - /// Default constructor. - ACE_DLL_Singleton_T (void); - - /// Destructor. - ~ACE_DLL_Singleton_T (void); - - /// Contained instance. - TYPE instance_; - -#if !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES) - /// Pointer to the Singleton instance. - static ACE_DLL_Singleton_T *singleton_; -#endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */ - - /// Get pointer to the singleton instance. - static ACE_DLL_Singleton_T *&instance_i (void); -}; - -template -class ACE_DLL_Singleton_Adapter_T : public TYPE -{ -public: - const ACE_TCHAR *dll_name (void); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Singleton.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Singleton.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Singleton.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" -#endif /* ACE_SINGLETON_H */ diff --git a/externals/ace/Singleton.inl b/externals/ace/Singleton.inl deleted file mode 100644 index 107a8b78c6d..00000000000 --- a/externals/ace/Singleton.inl +++ /dev/null @@ -1,42 +0,0 @@ -// -*- C++ -*- -// -// $Id: Singleton.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Default constructors. -// -// Note: don't explicitly initialize "instance_", because TYPE may not -// have a default constructor. Let the compiler figure it out . . . - -template ACE_INLINE -ACE_Singleton::ACE_Singleton (void) -{ -} - -template ACE_INLINE -ACE_Unmanaged_Singleton::ACE_Unmanaged_Singleton (void) -{ -} - -template ACE_INLINE -ACE_TSS_Singleton::ACE_TSS_Singleton (void) -{ -} - -template ACE_INLINE -ACE_Unmanaged_TSS_Singleton::ACE_Unmanaged_TSS_Singleton (void) -{ -} - -template ACE_INLINE -ACE_DLL_Singleton_T::ACE_DLL_Singleton_T (void) -{ -} - -template -ACE_DLL_Singleton_T::~ACE_DLL_Singleton_T (void) -{ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Sock_Connect.cpp b/externals/ace/Sock_Connect.cpp deleted file mode 100644 index dc4362e697e..00000000000 --- a/externals/ace/Sock_Connect.cpp +++ /dev/null @@ -1,1594 +0,0 @@ -// $Id: Sock_Connect.cpp 90399 2010-06-03 21:35:20Z mesnier_p $ - -#include "ace/Sock_Connect.h" -#include "ace/INET_Addr.h" -#include "ace/Log_Msg.h" -#include "ace/Handle_Set.h" -#include "ace/Auto_Ptr.h" -#include "ace/SString.h" -#include "ace/OS_Memory.h" -#include "ace/OS_NS_stdio.h" -#include "ace/ACE.h" - -#if defined (sparc) -# include "ace/OS_NS_fcntl.h" -#endif // sparc - -#include "ace/OS_NS_stdlib.h" -#include "ace/OS_NS_string.h" -#include "ace/OS_NS_sys_socket.h" -#include "ace/OS_NS_netdb.h" -#include "ace/OS_NS_unistd.h" -#include "ace/os_include/net/os_if.h" - -#if defined (ACE_HAS_IPV6) -# include "ace/Guard_T.h" -# include "ace/Recursive_Thread_Mutex.h" -# if defined (_AIX) -# include /**/ -# endif /* _AIX */ -#endif /* ACE_HAS_IPV6 */ - -# if defined (ACE_HAS_GETIFADDRS) -# if defined (ACE_VXWORKS) -# include /**/ -# else -# include /**/ -# endif /*ACE_VXWORKS */ -# endif /* ACE_HAS_GETIFADDRS */ - -#if defined (ACE_VXWORKS) && (ACE_VXWORKS < 0x600) -#include /**/ -#include /**/ -#if defined (ACE_HAS_IPV6) -#include /**/ -extern "C" { - extern struct in_ifaddr* in_ifaddr; - extern LIST_HEAD(in_ifaddrhashhead, in_ifaddr) *in_ifaddrhashtbl; -} -#endif /* ACE_HAS_IPV6 */ -#include "ace/OS_NS_stdio.h" -#endif /* ACE_VXWORKS < 0x600 */ - -#if defined (ACE_VXWORKS) && ((ACE_VXWORKS >= 0x630) && (ACE_VXWORKS <= 0x670)) && defined (__RTP__) && defined (ACE_HAS_IPV6) -const struct in6_addr in6addr_any = IN6ADDR_ANY_INIT; -const struct in6_addr in6addr_nodelocal_allnodes = IN6ADDR_NODELOCAL_ALLNODES_INIT; -const struct in6_addr in6addr_linklocal_allnodes = IN6ADDR_LINKLOCAL_ALLNODES_INIT; -const struct in6_addr in6addr_linklocal_allrouters = IN6ADDR_LINKLOCAL_ALLROUTERS_INIT; -#endif /* ACE_VXWORKS >= 0x630 && <= 0x670 && __RTP__ && ACE_HAS_IPV6 */ - -#if defined (ACE_HAS_WINCE) -#include /**/ -# if defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0) && (_WIN32_WCE < 0x600) && defined (ACE_HAS_IPV6) -# include /**/ -const struct in6_addr in6addr_any = IN6ADDR_ANY_INIT; -const struct in6_addr in6addr_loopback = IN6ADDR_LOOPBACK_INIT; -# endif -#endif // ACE_HAS_WINCE - -#if defined (ACE_WIN32) && defined (ACE_HAS_PHARLAP) -# include "ace/OS_NS_stdio.h" -#endif - -#if defined (ACE_HAS_IPV6) - -// These defines support a generic usage based on -// the various SIGCF*IF ioctl implementations - -# if defined (SIOCGLIFCONF) -# define SIOCGIFCONF_CMD SIOCGLIFCONF -# if defined (__hpux) -# define IFREQ if_laddrreq -# define IFCONF if_laddrconf -# define IFC_REQ iflc_req -# define IFC_LEN iflc_len -# define IFC_BUF iflc_buf -# define IFR_ADDR iflr_addr -# define IFR_NAME iflr_name -# define IFR_FLAGS iflr_flags -# undef SETFAMILY -# define SA_FAMILY sa_family -# else -# define IFREQ lifreq -# define IFCONF lifconf -# define IFC_REQ lifc_req -# define IFC_LEN lifc_len -# define IFC_BUF lifc_buf -# define IFR_ADDR lifr_addr -# define IFR_NAME lifr_name -# define IFR_FLAGS lifr_flags -# define SETFAMILY -# define IFC_FAMILY lifc_family -# define IFC_FLAGS lifc_flags -# define SA_FAMILY ss_family -# endif -# else -# define SIOCGIFCONF_CMD SIOCGIFCONF -# define IFREQ ifreq -# define IFCONF ifconf -# define IFC_REQ ifc_req -# define IFC_LEN ifc_len -# define IFC_BUF ifc_buf -# define IFR_ADDR ifr_addr -# define IFR_NAME ifr_name -# define IFR_FLAGS ifr_flags -# undef SETFAMILY -# define SA_FAMILY sa_family -# endif /* SIOCGLIFCONF */ - -# if defined (ACE_HAS_THREADS) -# include "ace/Object_Manager.h" -# endif /* ACE_HAS_THREADS */ - -namespace -{ - // private: - // Used internally so not exported. - - // Does this box have ipv4 turned on? - int ace_ipv4_enabled = -1; - - // Does this box have ipv6 turned on? - int ace_ipv6_enabled = -1; - -} -#else /* ACE_HAS_IPV6 */ -# define SIOCGIFCONF_CMD SIOCGIFCONF -# define IFREQ ifreq -# define IFCONF ifconf -# define IFC_REQ ifc_req -# define IFC_LEN ifc_len -# define IFC_BUF ifc_buf -# define IFR_ADDR ifr_addr -# define IFR_NAME ifr_name -# define IFR_FLAGS ifr_flags -# undef SETFAMILY -# define SA_FAMILY sa_family -#endif /* ACE_HAS_IPV6 */ - -// This is a hack to work around a problem with Visual Age C++ 5 and 6 on AIX. -// Without this, the compiler auto-instantiates the ACE_Auto_Array_Ptr for -// ifreq (contained in this module) but only adds the #include for -// and not the one for which is also needed. Although we -// don't need the template defined here, it makes the compiler pull in -// and the build runs clean. -#if defined (AIX) && defined (__IBMCPP__) && (__IBMCPP__ >= 500) && (__IBMCPP__ < 700) -static ACE_Auto_Array_Ptr force_compiler_to_include_socket_h; -#endif /* AIX && __IBMCPP__ >= 500 */ - - -ACE_RCSID (ace, - Sock_Connect, - "$Id: Sock_Connect.cpp 90399 2010-06-03 21:35:20Z mesnier_p $") - - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Bind socket to an unused port. - -int -ACE::bind_port (ACE_HANDLE handle, ACE_UINT32 ip_addr, int address_family) -{ - ACE_TRACE ("ACE::bind_port"); - - ACE_INET_Addr addr; - -#if defined (ACE_HAS_IPV6) - if (address_family != PF_INET6) - // What do we do if it is PF_"INET6? Since it's 4 bytes, it must be an - // IPV4 address. Is there a difference? Why is this test done? dhinton -#else /* ACE_HAS_IPV6 */ - ACE_UNUSED_ARG (address_family); -#endif /* !ACE_HAS_IPV6 */ - addr = ACE_INET_Addr ((u_short)0, ip_addr); -#if defined (ACE_HAS_IPV6) - else if (ip_addr != INADDR_ANY) - // address_family == PF_INET6 and a non default IP address means to bind - // to the IPv4-mapped IPv6 address - addr.set ((u_short)0, ip_addr, 1, 1); -#endif /* ACE_HAS_IPV6 */ - - // The OS kernel should select a free port for us. - return ACE_OS::bind (handle, - (sockaddr*)addr.get_addr(), - addr.get_size()); -} - -int -ACE::get_bcast_addr (ACE_UINT32 &bcast_addr, - const ACE_TCHAR *host_name, - ACE_UINT32 host_addr, - ACE_HANDLE handle) -{ - ACE_TRACE ("ACE::get_bcast_addr"); - -#if defined (ACE_LACKS_GET_BCAST_ADDR) - ACE_UNUSED_ARG (bcast_addr); - ACE_UNUSED_ARG (host_name); - ACE_UNUSED_ARG (host_addr); - ACE_UNUSED_ARG (handle); - ACE_NOTSUP_RETURN (-1); -#elif !defined(ACE_WIN32) && !defined(__INTERIX) - ACE_HANDLE s = handle; - - if (s == ACE_INVALID_HANDLE) - s = ACE_OS::socket (AF_INET, SOCK_STREAM, 0); - - if (s == ACE_INVALID_HANDLE) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_OS::socket")), - -1); - - struct ifconf ifc; - char buf[BUFSIZ]; - - ifc.ifc_len = sizeof buf; - ifc.ifc_buf = buf; - - // Get interface structure and initialize the addresses using UNIX - // techniques - if (ACE_OS::ioctl (s, SIOCGIFCONF_CMD, (char *) &ifc) == -1) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE::get_bcast_addr:") - ACE_TEXT ("ioctl (get interface configuration)")), - -1); - - struct ifreq *ifr = ifc.ifc_req; - - struct sockaddr_in ip_addr; - - // Get host ip address if necessary. - if (host_name) - { - hostent *hp = ACE_OS::gethostbyname (ACE_TEXT_ALWAYS_CHAR (host_name)); - - if (hp == 0) - return -1; - else -#if !defined(_UNICOS) - ACE_OS::memcpy ((char *) &ip_addr.sin_addr.s_addr, - (char *) hp->h_addr, - hp->h_length); -#else /* _UNICOS */ - { - ACE_UINT64 haddr; // a place to put the address - char * haddrp = (char *) &haddr; // convert to char pointer - ACE_OS::memcpy(haddrp,(char *) hp->h_addr,hp->h_length); - ip_addr.sin_addr.s_addr = haddr; - } -#endif /* ! _UNICOS */ - } - else - { - ACE_OS::memset ((void *) &ip_addr, 0, sizeof ip_addr); -#if !defined(_UNICOS) - ACE_OS::memcpy ((void *) &ip_addr.sin_addr, - (void*) &host_addr, - sizeof ip_addr.sin_addr); -#else /* _UNICOS */ - ip_addr.sin_addr.s_addr = host_addr; // just copy to the bitfield -#endif /* ! _UNICOS */ - } - -#if !defined(AIX) && !defined (__QNX__) && !defined (__FreeBSD__) && !defined(__NetBSD__) && !defined (__Lynx__) - for (int n = ifc.ifc_len / sizeof (struct ifreq) ; n > 0; - n--, ifr++) -#else - // see mk_broadcast@SOCK_Dgram_Bcast.cpp - for (int nbytes = ifc.ifc_len; nbytes >= (int) sizeof (struct ifreq) && - ((ifr->ifr_addr.sa_len > sizeof (struct sockaddr)) ? - (nbytes >= (int) sizeof (ifr->ifr_name) + ifr->ifr_addr.sa_len) : 1); - ((ifr->ifr_addr.sa_len > sizeof (struct sockaddr)) ? - (nbytes -= sizeof (ifr->ifr_name) + ifr->ifr_addr.sa_len, - ifr = (struct ifreq *) - ((caddr_t) &ifr->ifr_addr + ifr->ifr_addr.sa_len)) : - (nbytes -= sizeof (struct ifreq), ifr++))) -#endif /* !defined(AIX) && !defined (__QNX__) && !defined (__FreeBSD__) && !defined(__NetBSD__) && !defined (__Lynx__) */ - { - struct sockaddr_in if_addr; - - // Compare host ip address with interface ip address. - ACE_OS::memcpy (&if_addr, - &ifr->ifr_addr, - sizeof if_addr); - - if (ip_addr.sin_addr.s_addr != if_addr.sin_addr.s_addr) - continue; - - if (ifr->ifr_addr.sa_family != AF_INET) - { - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE::get_bcast_addr:") - ACE_TEXT ("Not AF_INET"))); - continue; - } - - struct ifreq flags = *ifr; - struct ifreq if_req = *ifr; - - if (ACE_OS::ioctl (s, SIOCGIFFLAGS, (char *) &flags) == -1) - { - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE::get_bcast_addr:") - ACE_TEXT (" ioctl (get interface flags)"))); - continue; - } - - if (ACE_BIT_DISABLED (flags.ifr_flags, IFF_UP)) - { - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE::get_bcast_addr:") - ACE_TEXT ("Network interface is not up"))); - continue; - } - - if (ACE_BIT_ENABLED (flags.ifr_flags, IFF_LOOPBACK)) - continue; - - if (ACE_BIT_ENABLED (flags.ifr_flags, IFF_BROADCAST)) - { - if (ACE_OS::ioctl (s, - SIOCGIFBRDADDR, - (char *) &if_req) == -1) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE::get_bcast_addr:") - ACE_TEXT ("ioctl (get broadaddr)"))); - else - { - ACE_OS::memcpy (&ip_addr, - &if_req.ifr_broadaddr, - sizeof if_req.ifr_broadaddr); - - ACE_OS::memcpy ((void *) &host_addr, - (void *) &ip_addr.sin_addr, - sizeof host_addr); - - if (handle == ACE_INVALID_HANDLE) - ACE_OS::close (s); - - bcast_addr = host_addr; - return 0; - } - } - else - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE::get_bcast_addr:") - ACE_TEXT ("Broadcast is not enable for this interface."))); - - if (handle == ACE_INVALID_HANDLE) - ACE_OS::close (s); - - bcast_addr = host_addr; - return 0; - } - - return 0; -#else - ACE_UNUSED_ARG (handle); - ACE_UNUSED_ARG (host_addr); - ACE_UNUSED_ARG (host_name); - bcast_addr = (ACE_UINT32 (INADDR_BROADCAST)); - return 0; -#endif /* !ACE_WIN32 && !__INTERIX */ -} - -int -ACE::get_fqdn (ACE_INET_Addr const & addr, - char hostname[], - size_t len) -{ - int h_error; // Not the same as errno! - hostent hentry; - ACE_HOSTENT_DATA buf; - - char * ip_addr = 0; - int ip_addr_size = 0; - if (addr.get_type () == AF_INET) - { - sockaddr_in * const sock_addr = - reinterpret_cast (addr.get_addr ()); - ip_addr_size = sizeof sock_addr->sin_addr; - ip_addr = (char*) &sock_addr->sin_addr; - } -#ifdef ACE_HAS_IPV6 - else - { - sockaddr_in6 * sock_addr = - reinterpret_cast (addr.get_addr ()); - - ip_addr_size = sizeof sock_addr->sin6_addr; - ip_addr = (char*) &sock_addr->sin6_addr; - } -#endif /* ACE_HAS_IPV6 */ - - // get the host entry for the address in question - hostent * const hp = ACE_OS::gethostbyaddr_r (ip_addr, - ip_addr_size, - addr.get_type (), - &hentry, - buf, - &h_error); - - // if it's not found in the host file or the DNS datase, there is nothing - // much we can do. embed the IP address - if (hp == 0 || hp->h_name == 0) - return -1; - - if (ACE::debug()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("(%P|%t) - ACE::get_fqdn, ") - ACE_TEXT ("canonical host name is %C\n"), - hp->h_name)); - - // check if the canonical name is the FQDN - if (!ACE_OS::strchr(hp->h_name, '.')) - { - // list of address - char** p; - // list of aliases - char** q; - - // for every address and for every alias within the address, check and - // see if we can locate a FQDN - for (p = hp->h_addr_list; *p != 0; ++p) - { - for (q = hp->h_aliases; *q != 0; ++q) - { - if (ACE_OS::strchr(*q, '.')) - { - // we got an FQDN from an alias. use this - if (ACE_OS::strlen (*q) >= len) - // the hostname is too huge to fit into a - // buffer of size MAXHOSTNAMELEN - // should we check other aliases as well - // before bailing out prematurely? - // for right now, let's do it. this (short name) - // is atleast better than embedding the IP - // address in the profile - continue; - - if (ACE::debug ()) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("(%P|%t) - ACE::get_fqdn, ") - ACE_TEXT ("found fqdn within alias as %C\n"), - *q)); - ACE_OS::strcpy (hostname, *q); - - return 0; - } - } - } - } - - // The canonical name may be an FQDN when we reach here. - // Alternatively, the canonical name (a non FQDN) may be the best - // we can do. - if (ACE_OS::strlen (hp->h_name) >= len) - { - // The hostname is too large to fit into a buffer of size - // MAXHOSTNAMELEN. - return -2; - } - else - { - ACE_OS::strcpy (hostname, hp->h_name); - } - - return 0; -} - -#if defined (ACE_WIN32) - -static int -get_ip_interfaces_win32 (size_t &count, - ACE_INET_Addr *&addrs) -{ -# if defined (ACE_HAS_WINCE) && defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0) - // moved the ACE_HAS_WINCE impl ahaid of ACE_HAS_WINSOCK2 because - // WINCE in fact has winsock2, but doesn't properly support the - // WSAIoctl for obtaining IPv6 address info. - PIP_ADAPTER_ADDRESSES AdapterAddresses = 0; - ULONG OutBufferLength = 0; - ULONG RetVal = 0; - unsigned char *octet_buffer = 0; - - RetVal = - GetAdaptersAddresses(AF_UNSPEC, - 0, - 0, - AdapterAddresses, - &OutBufferLength); - - if (RetVal != ERROR_BUFFER_OVERFLOW) - { - return -1; - } - - ACE_NEW_RETURN (octet_buffer, unsigned char[OutBufferLength],-1); - AdapterAddresses = (IP_ADAPTER_ADDRESSES *)octet_buffer; - - RetVal = - GetAdaptersAddresses(AF_UNSPEC, - 0, - 0, - AdapterAddresses, - &OutBufferLength); - - if (RetVal != NO_ERROR) - { - delete [] octet_buffer; - return -1; - } - - // If successful, output some information from the data we received - PIP_ADAPTER_ADDRESSES AdapterList = AdapterAddresses; - while (AdapterList) - { - if (AdapterList->OperStatus == IfOperStatusUp) - { - if (AdapterList->IfIndex != 0) - ++count; - if (AdapterList->Ipv6IfIndex != 0) - ++count; - } - AdapterList = AdapterList->Next; - } - - AdapterList = AdapterAddresses; - - ACE_NEW_RETURN (addrs, ACE_INET_Addr[count],-1); - count = 0; - for (AdapterList = AdapterAddresses; - AdapterList != 0; - AdapterList = AdapterList->Next) - { - if (AdapterList->OperStatus != IfOperStatusUp) - continue; - - IP_ADAPTER_UNICAST_ADDRESS *uni = 0; - if (AdapterList->IfIndex != 0) - for (uni = AdapterList->FirstUnicastAddress; - uni != 0; - uni = uni->Next) - { - SOCKET_ADDRESS *sa_addr = &uni->Address; - if (sa_addr->lpSockaddr->sa_family == AF_INET) - { - sockaddr_in *sin = (sockaddr_in*)sa_addr->lpSockaddr; - addrs[count].set(sin,sa_addr->iSockaddrLength); - ++count; - break; - } - } - if (AdapterList->Ipv6IfIndex != 0) - { - for (uni = AdapterList->FirstUnicastAddress; - uni != 0; - uni = uni->Next) - { - SOCKET_ADDRESS *sa_addr = &uni->Address; - if (sa_addr->lpSockaddr->sa_family == AF_INET6) - { - sockaddr_in *sin = (sockaddr_in*)sa_addr->lpSockaddr; - addrs[count].set(sin,sa_addr->iSockaddrLength); - ++count; - break; - } - } - } - } - - delete [] octet_buffer; - return 0; - -# elif defined (ACE_HAS_PHARLAP) - // PharLap ETS has its own kernel routines to rummage through the device - // configs and extract the interface info, but only for Pharlap RT. -# if !defined (ACE_HAS_PHARLAP_RT) - ACE_NOTSUP_RETURN (-1); -# endif /* ACE_HAS_PHARLAP_RT */ - - // Locate all of the IP devices in the system, saving a DEVHANDLE - // for each. Then allocate the ACE_INET_Addrs needed and fetch all - // the IP addresses. To locate the devices, try the available - // device name roots and increment the device number until the - // kernel says there are no more of that type. - const size_t ACE_MAX_ETS_DEVICES = 64; // Arbitrary, but should be enough. - DEVHANDLE ip_dev[ACE_MAX_ETS_DEVICES]; - EK_TCPIPCFG *devp = 0; - size_t i, j; - ACE_TCHAR dev_name[16]; - - count = 0; - for (i = 0; count < ACE_MAX_ETS_DEVICES; i++, ++count) - { - // Ethernet. - ACE_OS::sprintf (dev_name, - "ether%d", - i); - ip_dev[count] = EtsTCPGetDeviceHandle (dev_name); - if (ip_dev[count] == 0) - break; - } - for (i = 0; count < ACE_MAX_ETS_DEVICES; i++, ++count) - { - // SLIP. - ACE_OS::sprintf (dev_name, - "sl%d", - i); - ip_dev[count] = EtsTCPGetDeviceHandle (dev_name); - if (ip_dev[count] == 0) - break; - } - for (i = 0; count < ACE_MAX_ETS_DEVICES; i++, ++count) - { - // PPP. - ACE_OS::sprintf (dev_name, - "ppp%d", - i); - ip_dev[count] = EtsTCPGetDeviceHandle (dev_name); - if (ip_dev[count] == 0) - break; - } - - if (count > 0) - ACE_NEW_RETURN (addrs, - ACE_INET_Addr[count], - -1); - else - addrs = 0; - - for (i = 0, j = 0; i < count; i++) - { - devp = EtsTCPGetDeviceCfg (ip_dev[i]); - if (devp != 0) - { - addrs[j].set (0, - devp->nwIPAddress, - 0); // Already in net order. - ++j; - } - // There's no call to close the DEVHANDLE. - } - - count = j; - if (count == 0 && addrs != 0) - { - delete [] addrs; - addrs = 0; - } - - return 0; - - -# else - // All non-CE, non-Pharlap Windows. Must support Winsock2. - - int i, n_interfaces, status; - - INTERFACE_INFO info[64]; - SOCKET sock; - - // Get an (overlapped) DGRAM socket to test with - sock = socket (AF_INET, SOCK_DGRAM, 0); - if (sock == INVALID_SOCKET) - return -1; - - DWORD bytes; - status = WSAIoctl(sock, - SIO_GET_INTERFACE_LIST, - 0, - 0, - info, - sizeof(info), - &bytes, - 0, - 0); - closesocket (sock); - if (status == SOCKET_ERROR) - return -1; - - n_interfaces = bytes / sizeof(INTERFACE_INFO); - - // SIO_GET_INTERFACE_LIST does not work for IPv6 - // Instead recent versions of Winsock2 add the new opcode - // SIO_ADDRESS_LIST_QUERY. - // If this is not available forget about IPv6 local interfaces:-/ - int n_v6_interfaces = 0; - -# if defined (ACE_HAS_IPV6) && defined (SIO_ADDRESS_LIST_QUERY) - - LPSOCKET_ADDRESS_LIST v6info; - char *buffer; - DWORD buflen = sizeof (SOCKET_ADDRESS_LIST) + (63 * sizeof (SOCKET_ADDRESS)); - ACE_NEW_RETURN (buffer, - char[buflen], - -1); - v6info = reinterpret_cast (buffer); - - // Get an (overlapped) DGRAM socket to test with. - // If it fails only return IPv4 interfaces. - sock = socket (AF_INET6, SOCK_DGRAM, IPPROTO_UDP); - if (sock != INVALID_SOCKET) - { - status = WSAIoctl(sock, - SIO_ADDRESS_LIST_QUERY, - 0, - 0, - v6info, - buflen, - &bytes, - 0, - 0); - closesocket (sock); - if (status != SOCKET_ERROR) - n_v6_interfaces = v6info->iAddressCount; - } -# endif /* ACE_HAS_IPV6 */ - - ACE_NEW_RETURN (addrs, - ACE_INET_Addr[n_interfaces + n_v6_interfaces], - -1); - - // Now go through the list and transfer the good ones to the list of - // because they're down or don't have an IP address. - for (count = 0, i = 0; i < n_interfaces; ++i) - { - LPINTERFACE_INFO lpii; - struct sockaddr_in *addrp = 0; - - lpii = &info[i]; - if (!(lpii->iiFlags & IFF_UP)) - continue; - - // We assume IPv4 addresses here - addrp = reinterpret_cast (&lpii->iiAddress.AddressIn); - if (addrp->sin_addr.s_addr == INADDR_ANY) - continue; - - // Set the address for the caller. - addrs[count].set(addrp, sizeof(sockaddr_in)); - ++count; - } - -# if defined (ACE_HAS_IPV6) && defined (SIO_ADDRESS_LIST_QUERY) - // Now go through the list and transfer the good ones to the list of - // because they're down or don't have an IP address. - for (i = 0; i < n_v6_interfaces; i++) - { - struct sockaddr_in6 *addr6p; - - if (v6info->Address[i].lpSockaddr->sa_family != AF_INET6) - continue; - - addr6p = reinterpret_cast (v6info->Address[i].lpSockaddr); - if (IN6_IS_ADDR_UNSPECIFIED(&addr6p->sin6_addr)) // IN6ADDR_ANY? - continue; - - // Set the address for the caller. - addrs[count].set(reinterpret_cast (addr6p), sizeof(sockaddr_in6)); - ++count; - } - - delete [] buffer; // Clean up -# endif /* ACE_HAS_IPV6 */ - - if (count == 0) - { - delete [] addrs; - addrs = 0; - } - - return 0; - -# endif /* ACE_HAS_WINCE */ -} -#elif defined (ACE_HAS_GETIFADDRS) -static int -get_ip_interfaces_getifaddrs (size_t &count, - ACE_INET_Addr *&addrs) -{ - // Take advantage of the BSD getifaddrs function that simplifies - // access to connected interfaces. - struct ifaddrs *ifap = 0; - struct ifaddrs *p_if = 0; - - if (::getifaddrs (&ifap) != 0) - return -1; - - // Count number of interfaces. - size_t num_ifs = 0; - for (p_if = ifap; p_if != 0; p_if = p_if->ifa_next) - ++num_ifs; - - // Now create and initialize output array. - ACE_NEW_RETURN (addrs, - ACE_INET_Addr[num_ifs], - -1); // caller must free - - // Pull the address out of each INET interface. Not every interface - // is for IP, so be careful to count properly. When setting the - // INET_Addr, note that the 3rd arg (0) says to leave the byte order - // (already in net byte order from the interface structure) as is. - count = 0; - - for (p_if = ifap; - p_if != 0; - p_if = p_if->ifa_next) - { - if (p_if->ifa_addr && - p_if->ifa_addr->sa_family == AF_INET) - { - struct sockaddr_in *addr = - reinterpret_cast (p_if->ifa_addr); - - // Sometimes the kernel returns 0.0.0.0 as the interface - // address, skip those... - if (addr->sin_addr.s_addr != INADDR_ANY) - { - addrs[count].set ((u_short) 0, - addr->sin_addr.s_addr, - 0); - ++count; - } - } -# if defined (ACE_HAS_IPV6) - else if (p_if->ifa_addr && - p_if->ifa_addr->sa_family == AF_INET6) - { - struct sockaddr_in6 *addr = - reinterpret_cast (p_if->ifa_addr); - - // Skip the ANY address - if (!IN6_IS_ADDR_UNSPECIFIED(&addr->sin6_addr)) - { - addrs[count].set(reinterpret_cast (addr), - sizeof(sockaddr_in6)); - ++count; - } - } -# endif /* ACE_HAS_IPV6 */ - } - - ::freeifaddrs (ifap); - - return 0; -} -#elif defined (__hpux) -static int -get_ip_interfaces_hpux (size_t &count, - ACE_INET_Addr *&addrs) -{ - size_t num_ifs = 0; - size_t num_ifs_found = 0; - - // Call specific routine as necessary. - ACE_HANDLE handle = ACE_OS::socket (PF_INET, SOCK_DGRAM, 0); - ACE_HANDLE handle_ipv6 = ACE_INVALID_HANDLE; - - if (handle == ACE_INVALID_HANDLE) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE::get_ip_interfaces:open")), - -1); - - int result = 0; - int tmp_how_many = 0; - - result = ACE_OS::ioctl (handle, - SIOCGIFNUM, - (caddr_t) &tmp_how_many); - if (result != -1) - num_ifs = (size_t)tmp_how_many; - -# if defined (ACE_HAS_IPV6) - tmp_how_many = 0; - handle_ipv6 = ACE_OS::socket (PF_INET6, SOCK_DGRAM, 0); - result = ACE_OS::ioctl (handle_ipv6, - SIOCGLIFNUM, - (caddr_t) &tmp_how_many); - if (result != -1) - num_ifs += (size_t)tmp_how_many; -# endif - - if (num_ifs == 0) - { - ACE_OS::close (handle); - ACE_OS::close (handle_ipv6); - return -1; - } - - // ioctl likes to have an extra IFREQ structure to mark the end of - // what it returned, so increase the num_ifs by one. - ++num_ifs; - - //HPUX requires two passes, First for IPv4, then for IPv6 - - struct ifreq *ifs = 0; - ACE_NEW_RETURN (ifs, - struct ifreq[num_ifs], - -1); - ACE_OS::memset (ifs, 0, num_ifs * sizeof (struct ifreq)); - - ACE_Auto_Array_Ptr p_ifs (ifs); - - if (p_ifs.get() == 0) - { - ACE_OS::close (handle); - ACE_OS::close (handle_ipv6); - errno = ENOMEM; - return -1; - } - - struct ifconf ifcfg; - ACE_OS::memset (&ifcfg, 0, sizeof (struct ifconf)); - - ifcfg.ifc_req = p_ifs.get (); - ifcfg.ifc_len = num_ifs * sizeof (struct ifreq); - - if (ACE_OS::ioctl (handle, - SIOCGIFCONF, - (char *) &ifcfg) == -1) - { - ACE_OS::close (handle); - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE::get_ip_interfaces:") - ACE_TEXT ("ioctl - SIOCGIFCONF failed")), - -1); - } - - ACE_OS::close (handle); - - // Now create and initialize output array. - - ACE_NEW_RETURN (addrs, - ACE_INET_Addr[num_ifs], - -1); // caller must free - - struct ifreq *pcur = p_ifs.get (); - num_ifs_found = ifcfg.ifc_len / sizeof (struct ifreq); // get the number of returned ifs - - for (size_t i = 0; - i < num_ifs_found; - i++) - { - struct sockaddr_in *addr = - reinterpret_cast (&pcur->ifr_addr); - if (addr->sin_addr.s_addr != 0) - { - addrs[count].set ((u_short) 0, - addr->sin_addr.s_addr, - 0); - ++count; - } - ++pcur; - } - -# if defined (ACE_HAS_IPV6) - - if (handle_ipv6 != ACE_INVALID_HANDLE) - { - struct if_laddrreq *lifs = 0; - ACE_NEW_RETURN (lifs, - struct if_laddrreq[num_ifs], - -1); - ACE_OS::memset (lifs, 0, num_ifs * sizeof (struct if_laddrreq)); - - ACE_Auto_Array_Ptr p_lifs (lifs); - - if (p_lifs.get() == 0) - { - ACE_OS::close (handle); - ACE_OS::close (handle_ipv6); - errno = ENOMEM; - return -1; - } - - struct if_laddrconf lifcfg; - ACE_OS::memset (&lifcfg, 0, sizeof (struct if_laddrconf)); - - lifcfg.iflc_req = p_lifs.get (); - lifcfg.iflc_len = num_ifs * sizeof (struct if_laddrreq); - - if (ACE_OS::ioctl (handle_ipv6, - SIOCGLIFCONF, - (char *) &lifcfg) == -1) - { - ACE_OS::close (handle); - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE::get_ip_interfaces:") - ACE_TEXT ("ioctl - SIOCGLIFCONF failed")), - -1); - } - - ACE_OS::close (handle_ipv6); - - struct if_laddrreq *plcur = p_lifs.get (); - num_ifs_found = lifcfg.iflc_len / sizeof (struct if_laddrreq); - - for (size_t i = 0; - i < num_ifs_found; - i++) - { - struct sockaddr_in *addr = - reinterpret_cast (&plcur->iflr_addr); - if (!IN6_IS_ADDR_UNSPECIFIED(&reinterpret_cast(addr)->sin6_addr)) - { - addrs[count].set(addr, sizeof(struct sockaddr_in6)); - ++count; - } - ++plcur; - } - } -# endif /* ACE_HAS_IPV6 */ - return 0; -} -#elif defined (_AIX) -static int -get_ip_interfaces_aix (size_t &count, - ACE_INET_Addr *&addrs) -{ - ACE_HANDLE handle = ACE::get_handle(); - size_t num_ifs = 0; - struct ifconf ifc; - - if (handle == ACE_INVALID_HANDLE) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE::get_ip_interfaces_aix:")), - -1); - - if (ACE_OS::ioctl (handle, - SIOCGSIZIFCONF, - (caddr_t)&ifc.ifc_len) == -1) - { - ACE_OS::close (handle); - ACE_ERROR_RETURN((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("get ifconf size")), - -1); - } - - ACE_NEW_RETURN (ifc.ifc_buf,char [ifc.ifc_len], -1); - - ACE_Auto_Array_Ptr safe_buf (ifc.ifc_buf); - ACE_OS::memset (safe_buf.get(), 0, ifc.ifc_len); - - if (ACE_OS::ioctl(handle, SIOCGIFCONF, (caddr_t)&ifc) == -1) - { - ACE_OS::close (handle); - ACE_ERROR_RETURN((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("get ifconf")), - -1); - } - - ACE_OS::close (handle); - - char *buf_start = safe_buf.get(); - char *buf_end = buf_start + ifc.ifc_len; - - num_ifs = 0; - for (char *ptr = buf_start; ptr < buf_end; ) - { - struct ifreq *req = reinterpret_cast(ptr); - ptr += IFNAMSIZ; - ptr += req->ifr_addr.sa_len; - if (req->ifr_addr.sa_family == AF_INET -# if defined (ACE_HAS_IPV6) - || req->ifr_addr.sa_family == AF_INET6 -# endif - ) - ++num_ifs; - } - ACE_NEW_RETURN (addrs,ACE_INET_Addr[num_ifs], -1); - - for (char * ptr = buf_start; ptr < buf_end; ) - { - struct ifreq *req = reinterpret_cast(ptr); - // skip the interface name - ptr += IFNAMSIZ; - if (req->ifr_addr.sa_family == AF_INET -# if defined (ACE_HAS_IPV6) - || req->ifr_addr.sa_family == AF_INET6 -# endif - ) - { - sockaddr_in *addr = (sockaddr_in*)&req->ifr_addr; - addrs[count++].set(addr, addr->sin_len); - } - ptr += req->ifr_addr.sa_len; - } - - return 0; -} - -#elif defined (ACE_VXWORKS) && (ACE_VXWORKS < 0x600) && !defined (ACE_HAS_VXWORKS551_MEDUSA) -int -get_ip_interfaces_vxworks_lt600 (size_t &count, - ACE_INET_Addr *&addrs) -{ - count = 0; - // Loop through each address structure - -# if defined (ACE_HAS_IPV6) && defined (TAILQ_ENTRY) -# define ia_next ia_link.tqe_next -# endif /* TAILQ_ENTRY */ - - for (struct in_ifaddr* ia = in_ifaddr; ia != 0; ia = ia->ia_next) - { - ++count; - } - - // Now create and initialize output array. - ACE_NEW_RETURN (addrs, - ACE_INET_Addr[count], - -1); // caller must free - count = 0; - for (struct in_ifaddr* ia = in_ifaddr; ia != 0; ia = ia->ia_next) - { - struct ifnet* ifp = ia->ia_ifa.ifa_ifp; - if (ifp != 0) - { - // Get the current interface name - char interface[64]; - ACE_OS::sprintf(interface, "%s%d", ifp->if_name, ifp->if_unit); - - // Get the address for the current interface - char address [INET_ADDR_LEN]; - STATUS status = ifAddrGet(interface, address); - - if (status == OK) - { - // Concatenate a ':' at the end. This is because in - // ACE_INET_Addr::string_to_addr, the ip_address is - // obtained using ':' as the delimiter. Since, using - // ifAddrGet(), we just get the IP address, I am adding - // a ":" to get with the general case. - ACE_OS::strcat (address, ":"); - addrs[count].set (address); - } - else - { - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("ACE::get_ip_interface failed\n") - ACE_TEXT ("Couldnt get the IP Address\n")), - -1); - } - ++count; - } - } - return 0; -} -#endif // ACE_WIN32 || ACE_HAS_GETIFADDRS || __hpux || _AIX || ACE_VXWORKS < 0x600 - - -// return an array of all configured IP interfaces on this host, count -// rc = 0 on success (count == number of interfaces else -1 caller is -// responsible for calling delete [] on parray - -int -ACE::get_ip_interfaces (size_t &count, ACE_INET_Addr *&addrs) -{ - ACE_TRACE ("ACE::get_ip_interfaces"); - - count = 0; - addrs = 0; - -#if defined (ACE_WIN32) - return get_ip_interfaces_win32 (count, addrs); -#elif defined (ACE_HAS_GETIFADDRS) - return get_ip_interfaces_getifaddrs (count, addrs); -#elif defined (__hpux) - return get_ip_interfaces_hpux (count, addrs); -#elif defined (_AIX) - return get_ip_interfaces_aix (count, addrs); -#elif defined (ACE_VXWORKS) && (ACE_VXWORKS < 0x600) && !defined (ACE_HAS_VXWORKS551_MEDUSA) - return get_ip_interfaces_vxworks_lt600 (count, addrs); -#elif (defined (__unix) || defined (__unix__) || defined (ACE_OPENVMS) || (defined (ACE_VXWORKS) && !defined (ACE_HAS_GETIFADDRS)) || defined (ACE_HAS_RTEMS)) && !defined (ACE_LACKS_NETWORKING) - // COMMON (SVR4 and BSD) UNIX CODE - - // Call specific routine as necessary. - ACE_HANDLE handle = ACE::get_handle(); - - if (handle == ACE_INVALID_HANDLE) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE::get_ip_interfaces:open")), - -1); - - size_t num_ifs = 0; - - if (ACE::count_interfaces (handle, num_ifs)) - { - ACE_OS::close (handle); - return -1; - } - - // ioctl likes to have an extra ifreq structure to mark the end of - // what it returned, so increase the num_ifs by one. - ++num_ifs; - - struct IFREQ *ifs = 0; - ACE_NEW_RETURN (ifs, - struct IFREQ[num_ifs], - -1); - ACE_OS::memset (ifs, 0, num_ifs * sizeof (struct IFREQ)); - - ACE_Auto_Array_Ptr p_ifs (ifs); - - if (p_ifs.get() == 0) - { - ACE_OS::close (handle); - errno = ENOMEM; - return -1; - } - - struct IFCONF ifcfg; - ACE_OS::memset (&ifcfg, 0, sizeof (struct IFCONF)); - -# ifdef SETFAMILY - ifcfg.IFC_FAMILY = AF_UNSPEC; // request all families be returned - ifcfg.IFC_FLAGS = 0; -# endif - - ifcfg.IFC_REQ = p_ifs.get (); - ifcfg.IFC_LEN = num_ifs * sizeof (struct IFREQ); - - if (ACE_OS::ioctl (handle, - SIOCGIFCONF_CMD, - (caddr_t) &ifcfg) == -1) - { - ACE_OS::close (handle); - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE::get_ip_interfaces:") - ACE_TEXT ("ioctl - SIOCGIFCONF failed")), - -1); - } - - ACE_OS::close (handle); - - // Now create and initialize output array. - - ACE_NEW_RETURN (addrs, - ACE_INET_Addr[num_ifs], - -1); // caller must free - - struct IFREQ *pcur = p_ifs.get (); - size_t num_ifs_found = ifcfg.IFC_LEN / sizeof (struct IFREQ); // get the number of returned ifs - - // Pull the address out of each INET interface. Not every interface - // is for IP, so be careful to count properly. When setting the - // INET_Addr, note that the 3rd arg (0) says to leave the byte order - // (already in net byte order from the interface structure) as is. - count = 0; - - for (size_t i = 0; - i < num_ifs_found; - i++) - { - if (pcur->IFR_ADDR.SA_FAMILY == AF_INET -# if defined (ACE_HAS_IPV6) - || pcur->IFR_ADDR.SA_FAMILY == AF_INET6 -# endif - ) - - { -# if !defined(_UNICOS) - struct sockaddr_in *addr = - reinterpret_cast (&pcur->IFR_ADDR); - - // Sometimes the kernel returns 0.0.0.0 as an IPv4 interface - // address; skip those... - if (addr->sin_addr.s_addr != 0 -# if defined (ACE_HAS_IPV6) - || (addr->sin_family == AF_INET6 && - !IN6_IS_ADDR_UNSPECIFIED(&reinterpret_cast(addr)->sin6_addr)) -# endif - ) - { - int addrlen = static_cast (sizeof (struct sockaddr_in)); -# if defined (ACE_HAS_IPV6) - if (addr->sin_family == AF_INET6) - addrlen = static_cast (sizeof (struct sockaddr_in6)); -# endif - addrs[count].set (addr, addrlen); - ++count; - } -# else /* ! _UNICOS */ - // need to explicitly copy on the Cray, since the bitfields kinda - // screw things up here - struct sockaddr_in inAddr; - - inAddr.sin_len = pcur->IFR_ADDR.sa_len; - inAddr.sin_family = pcur->IFR_ADDR.sa_family; - memcpy((void *)&(inAddr.sin_addr), - (const void *)&(pcur->IFR_ADDR.sa_data[8]), - sizeof(struct in_addr)); - - if (inAddr.sin_addr.s_addr != 0) - { - addrs[count].set(&inAddr, sizeof(struct sockaddr_in)); - ++count; - } -# endif /* ! _UNICOS */ - } - -#if !defined (__QNX__) && !defined (__FreeBSD__) && !defined(__NetBSD__) && !defined (ACE_HAS_RTEMS) && !defined (__Lynx__) - ++pcur; -#else - if (pcur->ifr_addr.sa_len <= sizeof (struct sockaddr)) - { - ++pcur; - } - else - { - pcur = (struct ifreq *) - (pcur->ifr_addr.sa_len + (caddr_t) &pcur->ifr_addr); - } -#endif /* !defined (__QNX__) && !defined (__FreeBSD__) && !defined(__NetBSD__) && !defined (ACE_HAS_RTEMS) && !defined (__Lynx__) */ - } - -# if defined (ACE_HAS_IPV6) - // Retrieve IPv6 local interfaces by scanning /proc/net/if_inet6 if - // it exists. If we cannot open it then ignore possible IPv6 - // interfaces, we did our best;-) - FILE* fp = 0; - char addr_p[8][5]; - char s_ipaddr[64]; - int scopeid; - struct addrinfo hints, *res0; - int error; - - ACE_OS::memset (&hints, 0, sizeof (hints)); - hints.ai_flags = AI_NUMERICHOST; - hints.ai_family = AF_INET6; - - if ((fp = ACE_OS::fopen (ACE_TEXT ("/proc/net/if_inet6"), ACE_TEXT ("r"))) != 0) - { - while (fscanf (fp, - "%4s%4s%4s%4s%4s%4s%4s%4s %02x %*02x %*02x %*02x %*8s\n", - addr_p[0], addr_p[1], addr_p[2], addr_p[3], - addr_p[4], addr_p[5], addr_p[6], addr_p[7], &scopeid) != EOF) - { - // Format the address intoa proper IPv6 decimal address specification and - // resolve the resulting text using getaddrinfo(). - - const char* ip_fmt = "%s:%s:%s:%s:%s:%s:%s:%s%%%d"; - ACE_OS::sprintf (s_ipaddr, - ip_fmt, - addr_p[0], addr_p[1], addr_p[2], addr_p[3], - addr_p[4], addr_p[5], addr_p[6], addr_p[7], scopeid); - - error = getaddrinfo (s_ipaddr, 0, &hints, &res0); - if (error) - continue; - - if (res0->ai_family == AF_INET6 && - !IN6_IS_ADDR_UNSPECIFIED (&reinterpret_cast (res0->ai_addr)->sin6_addr)) - { - addrs[count].set(reinterpret_cast (res0->ai_addr), res0->ai_addrlen); - ++count; - } - freeaddrinfo (res0); - - } - ACE_OS::fclose (fp); - } -# endif /* ACE_HAS_IPV6 */ - - return 0; -#else - ACE_UNUSED_ARG (count); - ACE_UNUSED_ARG (addrs); - ACE_NOTSUP_RETURN (-1); // no implementation -#endif /* ACE_WIN32 */ -} - -// Helper routine for get_ip_interfaces, differs by UNIX platform so -// put into own subroutine. perform some ioctls to retrieve ifconf -// list of ifreq structs. - -int -ACE::count_interfaces (ACE_HANDLE handle, size_t &how_many) -{ -#if defined (SIOCGIFNUM) -# if defined (SIOCGLIFNUM) && !defined (ACE_LACKS_STRUCT_LIFNUM) - int cmd = SIOCGLIFNUM; - struct lifnum if_num = {AF_UNSPEC,0,0}; -# else - int cmd = SIOCGIFNUM; - int if_num = 0; -# endif /* SIOCGLIFNUM */ - if (ACE_OS::ioctl (handle, cmd, (caddr_t)&if_num) == -1) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE::count_interfaces:") - ACE_TEXT ("ioctl - SIOCGLIFNUM failed")), - -1); -# if defined (SIOCGLIFNUM) && !defined (ACE_LACKS_STRUCT_LIFNUM) - how_many = if_num.lifn_count; -# else - how_many = if_num; -# endif /* SIOCGLIFNUM */ -return 0; - -#elif (defined (__unix) || defined (__unix__) || defined (ACE_OPENVMS) || defined (ACE_HAS_RTEMS) || (defined (ACE_VXWORKS) && !defined (ACE_HAS_GETIFADDRS))) && !defined (ACE_LACKS_NETWORKING) - // Note: DEC CXX doesn't define "unix". BSD compatible OS: HP UX, - // AIX, SunOS 4.x perform some ioctls to retrieve ifconf list of - // ifreq structs no SIOCGIFNUM on SunOS 4.x, so use guess and scan - // algorithm - - // Probably hard to put this many ifs in a unix box.. - int const MAX_IF = 50; - - // HACK - set to an unreasonable number - int const num_ifs = MAX_IF; - - struct ifconf ifcfg; - size_t ifreq_size = num_ifs * sizeof (struct ifreq); - struct ifreq *p_ifs = (struct ifreq *) ACE_OS::malloc (ifreq_size); - - if (!p_ifs) - { - errno = ENOMEM; - return -1; - } - - ACE_OS::memset (p_ifs, 0, ifreq_size); - ACE_OS::memset (&ifcfg, 0, sizeof (struct ifconf)); - - ifcfg.ifc_req = p_ifs; - ifcfg.ifc_len = ifreq_size; - - if (ACE_OS::ioctl (handle, - SIOCGIFCONF_CMD, - (caddr_t) &ifcfg) == -1) - { - ACE_OS::free (ifcfg.ifc_req); - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE::count_interfaces:") - ACE_TEXT ("ioctl - SIOCGIFCONF failed")), - -1); - } - - int if_count = 0; - int i = 0; - - // get if address out of ifreq buffers. ioctl puts a blank-named - // interface to mark the end of the returned interfaces. - for (i = 0; - i < num_ifs; - i++) - { - /* In OpenBSD, the length of the list is returned. */ - ifcfg.ifc_len -= sizeof (struct ifreq); - if (ifcfg.ifc_len < 0) - break; - - ++if_count; -#if !defined (__QNX__) && !defined (__FreeBSD__) && !defined(__NetBSD__) && !defined (ACE_HAS_RTEMS) && !defined (__Lynx__) - ++p_ifs; -#else - if (p_ifs->ifr_addr.sa_len <= sizeof (struct sockaddr)) - { - ++p_ifs; - } - else - { - p_ifs = (struct ifreq *) - (p_ifs->ifr_addr.sa_len + (caddr_t) &p_ifs->ifr_addr); - } -#endif /* !defined (__QNX__) && !defined (__FreeBSD__) && !defined(__NetBSD__) && !defined (ACE_HAS_RTEMS) && !defined (__Lynx__)*/ - } - - ACE_OS::free (ifcfg.ifc_req); - -# if defined (ACE_HAS_IPV6) - FILE* fp = 0; - - if ((fp = ACE_OS::fopen (ACE_TEXT ("/proc/net/if_inet6"), ACE_TEXT ("r"))) != 0) - { - // Scan the lines according to the expected format but don't really read any input - while (fscanf (fp, "%*32s %*02x %*02x %*02x %*02x %*8s\n") != EOF) - { - ++if_count; - } - ACE_OS::fclose (fp); - } -# endif /* ACE_HAS_IPV6 */ - - how_many = if_count; - return 0; -#else - ACE_UNUSED_ARG (handle); - ACE_UNUSED_ARG (how_many); - ACE_NOTSUP_RETURN (-1); // no implementation -#endif /* sparc && SIOCGIFNUM */ -} - -// Routine to return a handle from which ioctl() requests can be made. - -ACE_HANDLE -ACE::get_handle (void) -{ - // Solaris 2.x - ACE_HANDLE handle = ACE_INVALID_HANDLE; -#if defined (sparc) - handle = ACE_OS::open ("/dev/udp", O_RDONLY); -#elif defined (__unix) || defined (__unix__) || defined (_AIX) || defined (__hpux) || (defined (ACE_VXWORKS) && (ACE_VXWORKS >= 0x600)) || defined (ACE_OPENVMS) || defined (ACE_HAS_RTEMS) - // Note: DEC CXX doesn't define "unix" BSD compatible OS: HP UX, - // AIX, SunOS 4.x - - handle = ACE_OS::socket (PF_INET, SOCK_DGRAM, 0); -#endif /* sparc */ - return handle; -} - - -#if defined (ACE_HAS_IPV6) -static int -ip_check (int &ipvn_enabled, int pf) -{ - // We only get to this point if ipvn_enabled was -1 in the caller. - // Perform Double-Checked Locking Optimization. - ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, - *ACE_Static_Object_Lock::instance (), 0)); - - if (ipvn_enabled == -1) - { - // Determine if the kernel has IPv6 support by attempting to - // create a PF_INET socket and see if it fails. - ACE_HANDLE const s = ACE_OS::socket (pf, SOCK_DGRAM, 0); - if (s == ACE_INVALID_HANDLE) - { - ipvn_enabled = 0; - } - else - { - ipvn_enabled = 1; - ACE_OS::closesocket (s); - } - } - return ipvn_enabled; -} -#endif /* ACE_HAS_IPV6 */ - -bool -ACE::ipv4_enabled (void) -{ -#if defined (ACE_HAS_IPV6) - return static_cast (ace_ipv4_enabled == -1 ? - ::ip_check (ace_ipv4_enabled, PF_INET) : - ace_ipv4_enabled); -#else - // Assume it's always enabled since ACE requires some version of - // TCP/IP to exist. - return true; -#endif /* ACE_HAS_IPV6*/ -} - -int -ACE::ipv6_enabled (void) -{ -#if defined (ACE_HAS_IPV6) - return ace_ipv6_enabled == -1 ? - ::ip_check (ace_ipv6_enabled, PF_INET6) : - ace_ipv6_enabled; -#else /* ACE_HAS_IPV6 */ - return 0; -#endif /* !ACE_HAS_IPV6 */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Sock_Connect.h b/externals/ace/Sock_Connect.h deleted file mode 100644 index d6a72c718b8..00000000000 --- a/externals/ace/Sock_Connect.h +++ /dev/null @@ -1,107 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file Sock_Connect.h - * - * $Id: Sock_Connect.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Priyanka Gontla - * @author Based on code that existed formerly in ACE.h. - */ -//========================================================================== - -#ifndef ACE_SOCK_CONNECT_H -#define ACE_SOCK_CONNECT_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Basic_Types.h" -#include "ace/os_include/netinet/os_in.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Forward Declarations -class ACE_INET_Addr; - -namespace ACE -{ - // = Socket connection establishment calls. - - /// Bind a new unused port to @a handle. - extern ACE_Export int bind_port (ACE_HANDLE handle, - ACE_UINT32 ip_addr = INADDR_ANY, - int address_family = AF_UNSPEC); - - /** - * Get our broadcast address based on our @a host_addr. If - * @a hostname is non-0 we'll use it to determine our IP address. If - * @a handle is not ACE_INVALID_HANDLE then we'll use this to - * determine our broadcast address, otherwise we'll have to create a - * socket internally (and free it). Returns -1 on failure and 0 on - * success. - */ - extern ACE_Export int get_bcast_addr ( - ACE_UINT32 &bcast_addr, - const ACE_TCHAR *hostname = 0, - ACE_UINT32 host_addr = 0, - ACE_HANDLE handle = ACE_INVALID_HANDLE); - - /// Get fully qualified host/domain name. - extern ACE_Export int get_fqdn (ACE_INET_Addr const & addr, - char hostname[], - size_t len); - - /** - * Return count and array of all configured IP interfaces on this - * host, rc = 0 on success (count == number of interfaces else -1). - * Caller is responsible for calling delete [] on @a addr_array. - */ - extern ACE_Export int get_ip_interfaces (size_t &count, - ACE_INET_Addr *&addr_array); - - /** - * Helper routine for get_ip_interfaces, differs by UNIX platform so - * put into own subroutine. perform some ioctls to retrieve ifconf - * list of ifreq structs. - */ - extern ACE_Export int count_interfaces (ACE_HANDLE handle, - size_t &how_many); - - /// Routine to return a handle from which @c ioctl requests can be - /// made. Caller must close the handle. - extern ACE_Export ACE_HANDLE get_handle (void); - - /// Returns @c true if IPv4 is enabled on the current host; @c false - /// if not. - /** - * This is an execution-time check. If ACE has not been compiled - * with @c ACE_HAS_IPV6, it always returns @c true. This function - * tries to create a @c PF_INET socket, returning @c true if it - * succeeds, and @c false if it fails. Caches the result so it only - gets checked once. - */ - extern ACE_Export bool ipv4_enabled (void); - - /** - * Returns 1 if IPv6 is enabled on the current host; 0 if not. - * This is an execution-time check. If ACE has not been compiled - * with ACE_HAS_IPV6, it always returns 0. If ACE_HAS_IPV6 is - * enabled, this function tries to create a PF_INET6 socket, - * returning 1 if it succeeds, and 0 if it fails. Caches the result - * so it only gets checked once. - */ - extern ACE_Export int ipv6_enabled (void); -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" - -#endif /* ACE_SOCK_CONNECT_H */ diff --git a/externals/ace/Stack_Trace.cpp b/externals/ace/Stack_Trace.cpp deleted file mode 100644 index 3beb1c52f3e..00000000000 --- a/externals/ace/Stack_Trace.cpp +++ /dev/null @@ -1,723 +0,0 @@ -//============================================================================= -/** - * @file Stack_Trace.cpp - * - * $Id: Stack_Trace.cpp 90041 2010-04-29 03:38:07Z cleeland $ - * - * @brief Encapsulate string representation of stack trace. - * - * Some platform-specific areas of this code have been adapted from - * examples found elsewhere. Specifically, - * - the GLIBC stack generation uses the documented "backtrace" API - * and is adapted from examples shown in relevant documentation - * and repeated elsewhere, e.g., - * http://www.linuxselfhelp.com/gnu/glibc/html_chapter/libc_33.html - * - the Solaris stack generation is adapted from a 1995 post on - * comp.unix.solaris by Bart Smaalders, - * http://groups.google.com/group/comp.unix.solaris/browse_thread/thread/8b9f3de8be288f1c/31550f93a48231d5?lnk=gst&q=how+to+get+stack+trace+on+solaris+group:comp.unix.solaris#31550f93a48231d5 - * - VxWorks kernel-mode stack tracing is adapted from a code example - * in the VxWorks FAQ at http://www.xs4all.nl/~borkhuis/vxworks/vxw_pt5.html - * although the undocumented functions it uses are also mentioned in - * various documents available on the WindRiver support website. - * - * If you add support for a new platform, please add a bullet to the - * above list with durable references to the origins of your code. - * - */ -//============================================================================= - -#include "ace/Stack_Trace.h" -#include "ace/Min_Max.h" -#include "ace/OS_NS_string.h" -#include "ace/OS_NS_stdio.h" - -ACE_RCSID (ace, Stack_Trace, "$Id: Stack_Trace.cpp 90041 2010-04-29 03:38:07Z cleeland $") - -/* - This is ugly, simply because it's very platform-specific. -*/ - -const char ACE_Stack_Trace::UNSUPPORTED[] = ""; -const char ACE_Stack_Trace::UNABLE_TO_GET_TRACE[] = ""; - -ACE_Stack_Trace::ACE_Stack_Trace (ssize_t starting_frame_offset, size_t num_frames) - : buflen_(0) -{ - // cannot initialize arrays, so we must assign. - this->buf_[0] = '\0'; - this->generate_trace (starting_frame_offset, num_frames); -} - -const char* -ACE_Stack_Trace::c_str () const -{ - return &this->buf_[0]; -} - -static inline size_t -determine_starting_frame (ssize_t initial_frame, ssize_t offset) -{ - return ACE_MAX( initial_frame + offset, static_cast(0)); -} - -#if (defined(__GLIBC__) || defined(ACE_HAS_EXECINFO_H)) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 3)) -// This is the code for glibc -# include - -void -ACE_Stack_Trace::generate_trace (ssize_t starting_frame_offset, size_t num_frames) -{ - const size_t MAX_FRAMES = 128; - const ssize_t INITIAL_FRAME = 3; - - void* stack[MAX_FRAMES]; - size_t stack_size = 0; - char** stack_syms; - - if (num_frames == 0) - num_frames = MAX_FRAMES; - - size_t starting_frame = - determine_starting_frame (INITIAL_FRAME, starting_frame_offset); - - stack_size = ::backtrace (&stack[0], sizeof(stack)/sizeof(stack[0])); - if (stack_size != 0) - { - stack_syms = ::backtrace_symbols (stack, stack_size); - - for (size_t i = starting_frame; - i < stack_size && num_frames > 0; - i++, num_frames--) - { - // this could be more efficient by remembering where we left off in buf_ - char *symp = &stack_syms[i][0]; - while (this->buflen_ < SYMBUFSIZ - 2 && *symp != '\0') - { - this->buf_[this->buflen_++] = *symp++; - } - this->buf_[this->buflen_++] = '\n'; // put a newline at the end - } - this->buf_[this->buflen_] = '\0'; // zero terminate the string - - ::free (stack_syms); - } - else - { - ACE_OS::strcpy (&this->buf_[0], UNABLE_TO_GET_TRACE); - } -} -#elif defined(VXWORKS) && !defined(__RTP__) -# include -# include // hopefully this is enough to get all the necessary #defines. - -struct ACE_Stack_Trace_stackstate -{ - ACE_Stack_Trace_stackstate (char* b, size_t& bl, size_t nf, size_t sf) - : buf(b), buflen(bl), num_frames(nf), starting_frame(sf) - { } - - char* buf; - size_t& buflen; - size_t num_frames; - size_t starting_frame; -}; - -//@TODO: Replace with a TSS-based pointer to avoid problems in multithreaded environs, -// or use a mutex to serialize access to this. -static ACE_Stack_Trace_stackstate* ACE_Stack_Trace_stateptr = 0; - -static void -ACE_Stack_Trace_Add_Frame_To_Buf (INSTR *caller, - unsigned int func, - unsigned int nargs, - unsigned int *args) -{ - if (ACE_Stack_Trace_stateptr == 0) - return; - - ACE_Stack_Trace_stackstate *stackstate = ACE_Stack_Trace_stateptr; - - // Decrement the num_frames and starting_frame elements, - // then see if we're ready to start or ready to finish. - --stackstate->num_frames; - --stackstate->starting_frame; - - if (stackstate->num_frames == 0 || stackstate->starting_frame > 0) - return; - - // These are references so that the structure gets updated - // in the code below. - char*& buf = stackstate->buf; - unsigned int& len = stackstate->buflen; - - // At some point try using symFindByValue() to lookup func (and caller?) - // to print out symbols rather than simply addresses. - - // VxWorks can pass -1 for "nargs" if there was an error - if (nargs == static_cast (-1)) nargs = 0; - - len += ACE_OS::sprintf (&buf[len], "%#10x: %#10x (", (int)caller, func); - for (unsigned int i = 0; i < nargs; ++i) - { - if (i != 0) - len += ACE_OS::sprintf (&buf[len], ", "); - len += ACE_OS::sprintf(&buf [len], "%#x", args [i]); - } - - len += ACE_OS::sprintf(&buf[len], ")\n"); -} - -void -ACE_Stack_Trace::generate_trace (ssize_t starting_frame_offset, - size_t num_frames) -{ - const size_t MAX_FRAMES = 128; - const ssize_t INITIAL_FRAME = 3; - - if (num_frames == 0) - num_frames = MAX_FRAMES; - - size_t starting_frame = - determine_starting_frame (INITIAL_FRAME, starting_frame_offset); - - ACE_Stack_Trace_stackstate state (&this->buf_[0], this->buflen_, - num_frames, starting_frame); - - REG_SET regs; - - taskRegsGet ((int)taskIdSelf(), ®s); - // Maybe we should take a lock here to guard stateptr? - ACE_Stack_Trace_stateptr = &state; - trcStack (®s, (FUNCPTR)ACE_Stack_Trace_Add_Frame_To_Buf, taskIdSelf ()); -} - - -#elif defined(VXWORKS) && defined(__RTP__) -# include -# include -# include - -// See memEdrLib.c in VxWorks RTP sources for an example of stack tracing. - -static STATUS ace_vx_rtp_pc_validate (INSTR *pc, TRC_OS_CTX *pOsCtx) -{ - return ALIGNED (pc, sizeof (INSTR)) ? OK : ERROR; -} - -void -ACE_Stack_Trace::generate_trace (ssize_t starting_frame_offset, - size_t num_frames) -{ - const size_t MAX_FRAMES = 128; - const ssize_t INITIAL_FRAME = 2; - - if (num_frames == 0) num_frames = MAX_FRAMES; - size_t starting_frame = - determine_starting_frame (INITIAL_FRAME, starting_frame_offset); - - jmp_buf regs; - setjmp (regs); - - TASK_DESC desc; - if (taskInfoGet (taskIdSelf (), &desc) == ERROR) return; - - TRC_OS_CTX osCtx; - osCtx.stackBase = desc.td_pStackBase; - osCtx.stackEnd = desc.td_pStackEnd; - osCtx.pcValidateRtn = reinterpret_cast (ace_vx_rtp_pc_validate); - - char *fp = _WRS_FRAMEP_FROM_JMP_BUF (regs); - INSTR *pc = _WRS_RET_PC_FROM_JMP_BUF (regs); - - for (size_t depth = 0; depth < num_frames + starting_frame; ++depth) - { - char *prevFp; - INSTR *prevPc; - INSTR *prevFn; - - if (trcLibFuncs.lvlInfoGet (fp, pc, &osCtx, &prevFp, &prevPc, &prevFn) - == ERROR) - { - ACE_OS::strcpy (this->buf_, UNABLE_TO_GET_TRACE); - return; - } - - if(prevPc == 0 || prevFp == 0) break; - - if (depth >= starting_frame) - { - //Hopefully a future version of VxWorks will have a system call - //for an RTP to query its own symbols, but this is not possible now. - //An enhancement request has been filed under WIND00123307. - const char *fnName = "(no symbols)"; - - static const int N_ARGS = 12; - int buf[N_ARGS]; - int *pArgs = 0; - int numArgs = - trcLibFuncs.lvlArgsGet (prevPc, prevFn, prevFp, - buf, N_ARGS, &pArgs); - - // VxWorks can return -1 for "numArgs" if there was an error - if (numArgs == -1) numArgs = 0; - - size_t len = ACE_OS::strlen (this->buf_); - size_t space = SYMBUFSIZ - len - 1; - char *cursor = this->buf_ + len; - size_t written = ACE_OS::snprintf (cursor, space, "%x %s", - prevFn, fnName); - cursor += written; - space -= written; - - if (space < 1) return; //no point in logging when we're out of buffer - for (int arg = 0; numArgs != -1 && pArgs && arg < numArgs; ++arg) - { - if (arg == 0) *cursor++ = '(', --space; - written = ACE_OS::snprintf (cursor, space, - (arg < numArgs - 1) ? "%x, " : "%x", - pArgs[arg]); - cursor += written; - space -= written; - if (space && arg == numArgs - 1) *cursor++ = ')', --space; - } - if (space) *cursor++ = '\n', --space; - *cursor++ = 0; //we saved space for the null terminator - } - - fp = prevFp; - pc = prevPc; - } -} - -#elif defined(sun) -/* - * walks up call stack, printing library:routine+offset for each routine - */ - -# include -# include -# include -# include -# include -# define ACE_STACK_TRACE_BIAS 0 - -# if defined(sparc) || defined(__sparc) -# define ACE_STACK_TRACE_FLUSHWIN() asm("ta 3"); -# define ACE_STACK_TRACE_FRAME_PTR_INDEX 1 -# define ACE_STACK_TRACE_SKIP_FRAMES 0 -# if defined(__sparcv9) -# undef ACE_STACK_TRACE_BIAS -# define ACE_STACK_TRACE_BIAS 2047 -# endif -# endif - -# if defined(i386) || defined(__i386) -# define ACE_STACK_TRACE_FLUSHWIN() -# define ACE_STACK_TRACE_FRAME_PTR_INDEX 3 -# define ACE_STACK_TRACE_SKIP_FRAMES 0 -# endif - -# if defined(__amd64) || defined(__x86_64) -# define ACE_STACK_TRACE_FLUSHWIN() -# define ACE_STACK_TRACE_FRAME_PTR_INDEX 5 -# define ACE_STACK_TRACE_SKIP_FRAMES 0 -# endif - -# if defined(ppc) || defined(__ppc) -# define ACE_STACK_TRACE_FLUSHWIN() -# define ACE_STACK_TRACE_FRAME_PTR_INDEX 0 -# define ACE_STACK_TRACE_SKIP_FRAMES 2 -# endif - -static frame* -cs_frame_adjust(frame* sp) -{ - unsigned char* sp_byte = (unsigned char*)sp; - sp_byte += ACE_STACK_TRACE_BIAS; - return (frame*) sp_byte; -} - -/* - this function walks up call stack, calling user-supplied - function once for each stack frame, passing the pc and the user-supplied - usrarg as the argument. - */ - -static int -cs_operate(int (*func)(void *, void *), void * usrarg, - size_t starting_frame, size_t num_frames_arg) -{ - ACE_STACK_TRACE_FLUSHWIN(); - - jmp_buf env; - setjmp(env); - frame* sp = cs_frame_adjust((frame*) env[ACE_STACK_TRACE_FRAME_PTR_INDEX]); - - // make a copy of num_frames_arg to eliminate the following warning on some - // solaris platforms: - // Stack_Trace.cpp:318: warning: argument `size_t num_frames' might be clobbered by `longjmp' or `vfork' - size_t num_frames = num_frames_arg; - - // I would like to use ACE_MAX below rather than ?:, but - // I get linker relocation errors such as the following when - // I use it: - // ld: fatal: relocation error: file: .shobj/Stack_Trace.o section: - // .rela.debug_line symbol: : relocation against a discarded symbol, - // symbol is part of discarded section: - // .text%const __type_0&ace_max(const __type_0&,const __type_0&) - // - const size_t starting_skip = starting_frame - 1; -#if ACE_STACK_TRACE_SKIP_FRAMES == 0 - size_t skip_frames = starting_skip; -#else - size_t skip_frames = - ACE_STACK_TRACE_SKIP_FRAMES > starting_skip ? - ACE_STACK_TRACE_SKIP_FRAMES : starting_skip; -#endif /* ACE_STACK_TRACE_SKIP_FRAMES == 0 */ - size_t i; - for (i = 0; i < skip_frames && sp; ++i) - { - sp = cs_frame_adjust((frame*) sp->fr_savfp); - } - - i = 0; - - while ( sp - && sp->fr_savpc - && ++i - && --num_frames - && (*func)((void*)sp->fr_savpc, usrarg)) - { - sp = cs_frame_adjust((frame*) sp->fr_savfp); - } - - return(i); -} - -static int -add_frame_to_buf (void* pc, void* usrarg) -{ - char* buf = (char*)usrarg; - Dl_info info; - const char* func = "??"; - const char* lib = "??"; - - if(dladdr(pc, & info) != 0) - { - lib = (const char *) info.dli_fname; - func = (const char *) info.dli_sname; - } - - (void) ACE_OS::snprintf(buf, - ACE_Stack_Trace::SYMBUFSIZ, - "%s%s:%s+0x%x\n", - buf, - lib, - func, - //@@ Should the arithmetic on the following - //line be done with two void* ptrs? The result - //would be ptrdiff_t, and what is the correct - //sprintf() conversion character for that? - (size_t)pc - (size_t)info.dli_saddr); - - return(1); -} - -void -ACE_Stack_Trace::generate_trace (ssize_t starting_frame_offset, - size_t num_frames) -{ - const size_t MAX_FRAMES = 128; - const ssize_t INITIAL_FRAME = 3; - - if (num_frames == 0) - num_frames = MAX_FRAMES; - - size_t starting_frame = - determine_starting_frame (INITIAL_FRAME, starting_frame_offset); - - cs_operate (&add_frame_to_buf, &this->buf_[0], starting_frame, num_frames); -} - -#elif defined(ACE_WIN64) && (_WIN32_WINNT <= _WIN32_WINNT_WIN2K) -# if defined(_MSC_VER) -# define STRING2(X) #X -# define STRING(X) STRING2(X) -# pragma message (__FILE__ "(" STRING(__LINE__) ") : warning: stack traces"\ - " can't be generated on 64-bit Windows when _WIN32_WINNT is less than "\ - "0x501.") -# undef STRING -# undef STRING2 -# endif /*_MSC_VER*/ -void -ACE_Stack_Trace::generate_trace (ssize_t, size_t) -{ - ACE_OS::strcpy (&this->buf_[0], ""); -} - -#elif defined(ACE_WIN32) && !defined(ACE_HAS_WINCE) && !defined (__MINGW32__) \ - && !defined(__BORLANDC__) -# include -# include - -# define MAXTEXT 5000 -# define SYMSIZE 100 - -//@TODO: Test with WCHAR -//@TODO: Need a common CriticalSection since dbghelp is not thread-safe - -typedef struct _dbghelp_functions -{ - HMODULE hMod; //our handle to dbghelp.dll - - //these already have typedefs in DbgHelp.h - DWORD64 (WINAPI *SymGetModuleBase64) (HANDLE hProc, DWORD64 dwAddr); - PVOID (WINAPI *SymFunctionTableAccess64) (HANDLE hProc, DWORD64 AddrBase); - - typedef BOOL (WINAPI *SymFromAddr_t) - (HANDLE hProc, DWORD64 Addr, PDWORD64 Disp, PSYMBOL_INFO Symbol); - SymFromAddr_t SymFromAddr; - - typedef BOOL (WINAPI *SymGetLineFromAddr64_t) (HANDLE hProc, DWORD64 dwAddr, - PDWORD pdwDisplacement, - PIMAGEHLP_LINE64 Line); - SymGetLineFromAddr64_t SymGetLineFromAddr64; - - typedef DWORD (WINAPI *SymSetOptions_t) (DWORD SymOptions); - SymSetOptions_t SymSetOptions; - - typedef DWORD (WINAPI *SymGetOptions_t) (); - SymGetOptions_t SymGetOptions; - - typedef BOOL (WINAPI *SymInitialize_t) (HANDLE hProc, PCTSTR UserSearchPath, - BOOL invasive); - SymInitialize_t SymInitialize; - - typedef BOOL - (WINAPI *StackWalk64_t) (DWORD MachineType, HANDLE hPRoc, HANDLE hThr, - LPSTACKFRAME64 StackFrame, PVOID ContextRecord, - PREAD_PROCESS_MEMORY_ROUTINE64 RMRoutine, - PFUNCTION_TABLE_ACCESS_ROUTINE64 FTARoutine, - PGET_MODULE_BASE_ROUTINE64 GMBRoutine, - PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress); - StackWalk64_t StackWalk64; - - typedef BOOL (WINAPI *SymCleanup_t) (HANDLE hProc); - SymCleanup_t SymCleanup; -} dbghelp_functions; - - -# pragma warning (push) -# pragma warning (disable:4706) -static bool load_dbghelp_library_if_needed (dbghelp_functions *pDbg) -{ - //@TODO: See codeproject's StackWalker.cpp for the list of locations to - //search so we get the "enhanced" dbghelp if the user has it but it is not - //first on the path. - if (!(pDbg->hMod = ACE_TEXT_LoadLibrary (ACE_TEXT ("Dbghelp")))) - return false; - - //@TODO: Cache this so we don't have to re-link every time. When to unload? - -# define LINK(TYPE, NAME) (pDbg->NAME = \ - (TYPE) GetProcAddress (pDbg->hMod, #NAME)) -# define LINK_T(NAME) LINK (dbghelp_functions::NAME##_t, NAME) - return LINK (PGET_MODULE_BASE_ROUTINE64, SymGetModuleBase64) - && LINK (PFUNCTION_TABLE_ACCESS_ROUTINE64, SymFunctionTableAccess64) - && LINK_T (SymFromAddr) && LINK_T (SymGetLineFromAddr64) - && LINK_T (SymSetOptions)&& LINK_T (SymGetOptions) - && LINK_T (SymInitialize) && LINK_T (StackWalk64) && LINK_T (SymCleanup); -# undef LINK -# undef LINK_T -} -# pragma warning (pop) - - -struct frame_state { - STACKFRAME64 sf; - PSYMBOL_INFO pSym; - dbghelp_functions *pDbg; -}; - -static int -add_frame_to_buf (struct frame_state const *fs, void *usrarg) -{ - if (fs == 0 || usrarg == 0) - return -1; - - char *buf = static_cast (usrarg); - - DWORD64 disp; - DWORD64 dwModBase = fs->pDbg->SymGetModuleBase64 (GetCurrentProcess (), - fs->sf.AddrPC.Offset); - if (fs->pDbg->SymFromAddr (GetCurrentProcess (), - fs->sf.AddrPC.Offset, &disp, fs->pSym)) - { - IMAGEHLP_LINE64 line = {sizeof (IMAGEHLP_LINE64)}; - DWORD lineDisp; - if (fs->pDbg->SymGetLineFromAddr64 (GetCurrentProcess (), - fs->sf.AddrPC.Offset, - &lineDisp, &line)) - { - (void) ACE_OS::snprintf (buf, ACE_Stack_Trace::SYMBUFSIZ, - "%s%s() %s: %d + 0x%x\n", - buf, fs->pSym->Name, line.FileName, - line.LineNumber, lineDisp); - } - else - { - (void) ACE_OS::snprintf (buf, ACE_Stack_Trace::SYMBUFSIZ, - "%s%s()+0x%x [0x%x]\n", - buf, fs->pSym->Name, disp, - fs->sf.AddrPC.Offset - dwModBase); - } - } - else - { - (void) ACE_OS::snprintf (buf, ACE_Stack_Trace::SYMBUFSIZ, - "%s[0x%x]\n", - buf, fs->sf.AddrPC.Offset - dwModBase); - } - return 0; -} - -static void emptyStack () { } - -#if defined (_MSC_VER) -# pragma warning(push) -// Suppress warning 4748 "/GS can not protect parameters and local -// variables from local buffer overrun because optimizations are -// disabled in function" -# pragma warning(disable: 4748) -#endif /* _MSC_VER */ - -static int -cs_operate(int (*func)(struct frame_state const *, void *), void *usrarg, - size_t starting_frame, size_t num_frames) -{ - dbghelp_functions dbg; - if (!load_dbghelp_library_if_needed (&dbg)) - { - ACE_OS::strcpy (static_cast (usrarg), - ""); - if (dbg.hMod) FreeLibrary (dbg.hMod); - return 1; - } - - frame_state fs; - ZeroMemory (&fs.sf, sizeof (fs.sf)); - fs.pDbg = &dbg; - emptyStack (); //Not sure what this should do, Chad? - - CONTEXT c; - ZeroMemory (&c, sizeof (CONTEXT)); - c.ContextFlags = CONTEXT_FULL; - -# if defined (_M_IX86) - DWORD machine = IMAGE_FILE_MACHINE_I386; - __asm { - call x - x: pop eax - mov c.Eip, eax - mov c.Ebp, ebp - mov c.Esp, esp - } - fs.sf.AddrPC.Offset = c.Eip; - fs.sf.AddrStack.Offset = c.Esp; - fs.sf.AddrFrame.Offset = c.Ebp; - fs.sf.AddrPC.Mode = AddrModeFlat; - fs.sf.AddrStack.Mode = AddrModeFlat; - fs.sf.AddrFrame.Mode = AddrModeFlat; -# elif defined (_M_X64) - DWORD machine = IMAGE_FILE_MACHINE_AMD64; - RtlCaptureContext (&c); - fs.sf.AddrPC.Offset = c.Rip; - fs.sf.AddrFrame.Offset = c.Rsp; //should be Rbp or Rdi instead? - fs.sf.AddrStack.Offset = c.Rsp; - fs.sf.AddrPC.Mode = AddrModeFlat; - fs.sf.AddrFrame.Mode = AddrModeFlat; - fs.sf.AddrStack.Mode = AddrModeFlat; -# elif defined (_M_IA64) - DWORD machine = IMAGE_FILE_MACHINE_IA64; - RtlCaptureContext (&c); - fs.sf.AddrPC.Offset = c.StIIP; - fs.sf.AddrFrame.Offset = c.RsBSP; - fs.sf.AddrBStore.Offset = c.RsBSP; - fs.sf.AddrStack.Offset = c.IntSp; - fs.sf.AddrPC.Mode = AddrModeFlat; - fs.sf.AddrFrame.Mode = AddrModeFlat; - fs.sf.AddrBStore.Mode = AddrModeFlat; - fs.sf.AddrStack.Mode = AddrModeFlat; -# endif - - fs.pSym = (PSYMBOL_INFO) GlobalAlloc (GMEM_FIXED, - sizeof (SYMBOL_INFO) + - sizeof (ACE_TCHAR) * (SYMSIZE - 1)); - fs.pSym->SizeOfStruct = sizeof (SYMBOL_INFO); - fs.pSym->MaxNameLen = SYMSIZE * sizeof (ACE_TCHAR); - dbg.SymSetOptions (SYMOPT_DEFERRED_LOADS | SYMOPT_LOAD_LINES - | SYMOPT_FAIL_CRITICAL_ERRORS | dbg.SymGetOptions ()); - dbg.SymInitialize (GetCurrentProcess (), 0, true); - //What does the "true" parameter mean when tracing the current process? - - for (size_t current_frame = 0; current_frame < num_frames + starting_frame; - ++current_frame) - { - BOOL ok = dbg.StackWalk64 (machine, - GetCurrentProcess (), - GetCurrentThread (), - &fs.sf, &c, 0, - dbg.SymFunctionTableAccess64, - dbg.SymGetModuleBase64, 0); - if (!ok || fs.sf.AddrFrame.Offset == 0) - break; - - if (current_frame < starting_frame) - continue; - - func (&fs, usrarg); - } - - dbg.SymCleanup (GetCurrentProcess ()); - GlobalFree (fs.pSym); - FreeLibrary (dbg.hMod); - - return 0; -} - -#if defined (_MSC_VER) -// Restore the warning state to what it was before entry. -# pragma warning(pop) -#endif /* _MSC_VER */ - -void -ACE_Stack_Trace::generate_trace (ssize_t starting_frame_offset, - size_t num_frames) -{ - const size_t MAX_FRAMES = 128; - const ssize_t INITIAL_FRAME = 3; - - if (num_frames == 0) - num_frames = MAX_FRAMES; - - size_t starting_frame = - determine_starting_frame (INITIAL_FRAME, starting_frame_offset); - - cs_operate (&add_frame_to_buf, &this->buf_[0], starting_frame, num_frames); -} - -#else // Unsupported platform -void -ACE_Stack_Trace::generate_trace (ssize_t, size_t) -{ -// Call determine_starting_frame() on HP aCC build to resolve declared -// method never referenced warning. -#if defined (__HP_aCC) - size_t starting_frame = determine_starting_frame (0, 0); -#endif - - ACE_OS::strcpy (&this->buf_[0], UNSUPPORTED); -} -#endif - diff --git a/externals/ace/Stack_Trace.h b/externals/ace/Stack_Trace.h deleted file mode 100644 index 56cf8a09208..00000000000 --- a/externals/ace/Stack_Trace.h +++ /dev/null @@ -1,107 +0,0 @@ -// -*- C++ -*- -//============================================================================= -/** - * @file Stack_Trace.h - * - * $Id: Stack_Trace.h 81926 2008-06-12 14:43:09Z mitza $ - * - * @author Chris Cleeland (cleeland.ociweb.com) - */ -//============================================================================= - -#ifndef ACE_STACK_TRACE_H -#define ACE_STACK_TRACE_H - -#include /**/ "ace/pre.h" - -#include "ace/ACE_export.h" -#include "ace/Basic_Types.h" - -# if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -# endif /* ACE_LACKS_PRAGMA_ONCE */ - -# ifndef ACE_STACK_TRACE_SYMBUFSIZ -# define ACE_STACK_TRACE_SYMBUFSIZ 4096 -# endif - -/** - * @class ACE_Stack_Trace - * - * @brief Encapsulate a string representation of a stack trace on supported platforms. - * Stack traces for code built with optimize=1 (or "Release" configs on Visual - * Studio) may be misleading (missng frames) due to inlining performed by the - * compiler, which is indepenent of the inline=0 / inline=1 build option and - * the __ACE_INLINE__ / ACE_NO_INLINE macros. - * - * A new conversion character, the question mark, was added to ACE_Log_Msg for stack - * trace logging. The %? conversion character was added as a convenience so that users - * need not instantiate an ACE_Stack_Trace instance solely for the purpose of printing - * it in an ACE logging message. The following are functionally equivalent: - * - * \code - * ACE_DEBUG((LM_DEBUG, "%?")); - * - * ACE_Stack_Trace st; - * ACE_DEBUG ((LM_DEBUG, "%s", st.c_str() )); - * \endcode - * - * These usage examples were shown in $ACE_ROOT/tests/Stack_Trace_Test.cpp. - * - * @note The stack trace functionality was currently supported on platforms: - * - Any platform using glibc as its runtime library, or where ACE_HAS_EXECINFO_H is defined - * (this covers Linux and Mac) and gcc version >= 3.3. - * - VxWorks, both kernel and RTP - * - Solaris - * - Windows 32 and 64 bit (Visual C++, excluding WinCE/mobile) - * - * @note Since stack trace buffer size has limitation(@c ACE_STACK_TRACE_SYMBUFSIZ), you will not - * get a complete stack trace if @c ACE_STACK_TRACE_SYMBUFSIZ value is less than actual stack - * trace data length. To get a complete stack trace, you need set @c ACE_STACK_TRACE_SYMBUFSIZ - * with a larger value that is enough for the stack trace data in your @c config.h file - * and rebuild ACE. - * - * @note Using ACE logging mechanism (%?) to log the stack trace also has ACE_MAXLOGMSGLEN size limitation. - * To get a complete stack trace, you could use different output method. Following is an example. - * - * \code - * ACE_Stack_Trace st; - * ACE_OS::printf("at [%s]\n", st.c_str()); - * \endcode - */ -class ACE_Export ACE_Stack_Trace -{ -public: - /** - * @brief Grab a snapshot of the current stack trace and hold it for later use. - * - * @param starting_frame_offset offset into the array of frames to start printing; 0 is the - * platform-specific offset for the first frame, positive numbers give less frames, negative give - * more frames - * @param num_frames the number of stack frames to include (0 indicates platform-specific maximum) - * - */ - explicit ACE_Stack_Trace (ssize_t starting_frame_offset = 0, size_t num_frames = 0); - - /** - * @brief Return buffer as a C-style string. - * @return C-style string with string representation of stack trace. - * @note Lifecycle of string follows lifecycle of ACE_Stack_Trace instance. - */ - const char* c_str() const; - - static const size_t SYMBUFSIZ = ACE_STACK_TRACE_SYMBUFSIZ; - -private: - char buf_[SYMBUFSIZ]; - size_t buflen_; - - static const char UNSUPPORTED[]; - static const char UNABLE_TO_GET_TRACE[]; - - void generate_trace (ssize_t starting_frame_offset, size_t num_frames); -}; - -#include /**/ "ace/post.h" -#endif /* ACE_STACK_TRACE_H */ - diff --git a/externals/ace/Static_Object_Lock.h b/externals/ace/Static_Object_Lock.h deleted file mode 100644 index ad780258ee1..00000000000 --- a/externals/ace/Static_Object_Lock.h +++ /dev/null @@ -1,78 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Static_Object_Lock.h - * - * $Id: Static_Object_Lock.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author David L. Levine - * @author Matthias Kerkhoff - * @author Per Andersson - */ -//============================================================================= - -#ifndef ACE_STATIC_OBJECT_LOCK_H -#define ACE_STATIC_OBJECT_LOCK_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_THREADS) - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -class ACE_Recursive_Thread_Mutex; - -/** - * @class ACE_Static_Object_Lock - * - * @brief Provide an interface to access a global lock. - * - * This class is used to serialize the creation of static - * singleton objects. It really isn't needed any more, because - * anyone can access ACE_STATIC_OBJECT_LOCK directly. But, it - * is retained for backward compatibility. - */ -class ACE_Export ACE_Static_Object_Lock -{ -public: - /// Static lock access point. - static ACE_Recursive_Thread_Mutex *instance (void); - - /// For use only by ACE_Object_Manager to clean up lock if it - /// what dynamically allocated. - static void cleanup_lock (void); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_THREADS */ - -// hack to get around errors while compiling using split-cpp -#if defined (ACE_HAS_THREADS) - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -# if defined (ACE_IS_SPLITTING) -typedef ACE_Cleanup_Adapter ACE_Static_Object_Lock_Type; - -# if defined (__GNUC__) -// With g++, suppress the warning that this is unused. -static ACE_Static_Object_Lock_Type *ACE_Static_Object_Lock_lock __attribute__ ((unused)) = 0; -# else -static ACE_Static_Object_Lock_Type *ACE_Static_Object_Lock_lock = 0; -# endif /* __GNUC__ */ - -# endif /* ACE_IS_SPLITTING */ - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_THREADS */ - -#include /**/ "ace/post.h" -#endif /* ACE_STATIC_OBJECT_LOCK_H */ diff --git a/externals/ace/Stats.cpp b/externals/ace/Stats.cpp deleted file mode 100644 index 840dc40e7f5..00000000000 --- a/externals/ace/Stats.cpp +++ /dev/null @@ -1,421 +0,0 @@ -// $Id: Stats.cpp 83735 2008-11-14 09:41:52Z johnnyw $ - -#include "ace/Stats.h" - -#if !defined (__ACE_INLINE__) -# include "ace/Stats.inl" -#endif /* __ACE_INLINE__ */ - -#include "ace/OS_NS_stdio.h" -#include "ace/OS_NS_string.h" - -ACE_RCSID(ace, Stats, "$Id: Stats.cpp 83735 2008-11-14 09:41:52Z johnnyw $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_UINT32 -ACE_Stats_Value::fractional_field (void) const -{ - if (precision () == 0) - { - return 1; - } - else - { - ACE_UINT32 field = 10; - for (u_int i = 0; i < precision () - 1; ++i) - { - field *= 10; - } - - return field; - } -} - -int -ACE_Stats::sample (const ACE_INT32 value) -{ - if (samples_.enqueue_tail (value) == 0) - { - ++number_of_samples_; - if (number_of_samples_ == 0) - { - // That's a lot of samples :-) - overflow_ = EFAULT; - return -1; - } - - if (value < min_) - min_ = value; - - if (value > max_) - max_ = value; - - return 0; - } - else - { - // Probably failed due to running out of memory when trying to - // enqueue the new value. - overflow_ = errno; - return -1; - } -} - -void -ACE_Stats::mean (ACE_Stats_Value &m, - const ACE_UINT32 scale_factor) -{ - if (number_of_samples_ > 0) - { -#if defined ACE_LACKS_LONGLONG_T - // If ACE_LACKS_LONGLONG_T, then ACE_UINT64 is a user-defined class. - // To prevent having to construct a static of that class, declare it - // on the stack, and construct it, in each function that needs it. - const ACE_U_LongLong ACE_STATS_INTERNAL_OFFSET (0, 8); -#else /* ! ACE_LACKS_LONGLONG_T */ - const ACE_UINT64 ACE_STATS_INTERNAL_OFFSET = - ACE_UINT64_LITERAL (0x100000000); -#endif /* ! ACE_LACKS_LONGLONG_T */ - - ACE_UINT64 sum = ACE_STATS_INTERNAL_OFFSET; - ACE_Unbounded_Queue_Iterator i (samples_); - while (! i.done ()) - { - ACE_INT32 *sample; - if (i.next (sample)) - { - sum += *sample; - i.advance (); - } - } - - // sum_ was initialized with ACE_STATS_INTERNAL_OFFSET, so - // subtract that off here. - quotient (sum - ACE_STATS_INTERNAL_OFFSET, - number_of_samples_ * scale_factor, - m); - } - else - { - m.whole (0); - m.fractional (0); - } -} - -int -ACE_Stats::std_dev (ACE_Stats_Value &std_dev, - const ACE_UINT32 scale_factor) -{ - if (number_of_samples_ <= 1) - { - std_dev.whole (0); - std_dev.fractional (0); - } - else - { - const ACE_UINT32 field = std_dev.fractional_field (); - - // The sample standard deviation is: - // - // sqrt (sum (sample_i - mean)^2 / (number_of_samples_ - 1)) - - ACE_UINT64 mean_scaled; - // Calculate the mean, scaled, so that we don't lose its - // precision. - ACE_Stats_Value avg (std_dev.precision ()); - mean (avg, 1u); - avg.scaled_value (mean_scaled); - - // Calculate the summation term, of squared differences from the - // mean. - ACE_UINT64 sum_of_squares = 0; - ACE_Unbounded_Queue_Iterator i (samples_); - while (! i.done ()) - { - ACE_INT32 *sample; - if (i.next (sample)) - { - const ACE_UINT64 original_sum_of_squares = sum_of_squares; - - // Scale up by field width so that we don't lose the - // precision of the mean. Carefully . . . - const ACE_UINT64 product (*sample * field); - - ACE_UINT64 difference; - // NOTE: please do not reformat this code! It // - // works with the Diab compiler the way it is! // - if (product >= mean_scaled) // - { // - difference = product - mean_scaled; // - } // - else // - { // - difference = mean_scaled - product; // - } // - // NOTE: please do not reformat this code! It // - // works with the Diab compiler the way it is! // - - // Square using 64-bit arithmetic. - sum_of_squares += difference * ACE_U64_TO_U32 (difference); - i.advance (); - - if (sum_of_squares < original_sum_of_squares) - { - overflow_ = ENOSPC; - return -1; - } - } - } - - // Divide the summation by (number_of_samples_ - 1), to get the - // variance. In addition, scale the variance down to undo the - // mean scaling above. Otherwise, it can get too big. - ACE_Stats_Value variance (std_dev.precision ()); - quotient (sum_of_squares, - (number_of_samples_ - 1) * field * field, - variance); - - // Take the square root of the variance to get the standard - // deviation. First, scale up . . . - ACE_UINT64 scaled_variance; - variance.scaled_value (scaled_variance); - - // And scale up, once more, because we'll be taking the square - // root. - scaled_variance *= field; - ACE_Stats_Value unscaled_standard_deviation (std_dev.precision ()); - square_root (scaled_variance, - unscaled_standard_deviation); - - // Unscale. - quotient (unscaled_standard_deviation, - scale_factor * field, - std_dev); - } - - return 0; -} - - -void -ACE_Stats::reset (void) -{ - overflow_ = 0u; - number_of_samples_ = 0u; - min_ = 0x7FFFFFFF; - max_ = -0x8000 * 0x10000; - samples_.reset (); -} - -int -ACE_Stats::print_summary (const u_int precision, - const ACE_UINT32 scale_factor, - FILE *file) const -{ - ACE_TCHAR mean_string [128]; - ACE_TCHAR std_dev_string [128]; - ACE_TCHAR min_string [128]; - ACE_TCHAR max_string [128]; - int success = 0; - - for (int tmp_precision = precision; - ! overflow_ && ! success && tmp_precision >= 0; - --tmp_precision) - { - // Build a format string, in case the C library doesn't support %*u. - ACE_TCHAR format[32]; - if (tmp_precision == 0) - ACE_OS::sprintf (format, ACE_TEXT ("%%%d"), tmp_precision); - else - ACE_OS::sprintf (format, ACE_TEXT ("%%d.%%0%du"), tmp_precision); - - ACE_Stats_Value u (tmp_precision); - ((ACE_Stats *) this)->mean (u, scale_factor); - ACE_OS::sprintf (mean_string, format, u.whole (), u.fractional ()); - - ACE_Stats_Value sd (tmp_precision); - if (((ACE_Stats *) this)->std_dev (sd, scale_factor)) - { - success = 0; - continue; - } - else - { - success = 1; - } - ACE_OS::sprintf (std_dev_string, format, sd.whole (), sd.fractional ()); - - ACE_Stats_Value minimum (tmp_precision), maximum (tmp_precision); - if (min_ != 0) - { - const ACE_UINT64 m (min_); - quotient (m, scale_factor, minimum); - } - if (max_ != 0) - { - const ACE_UINT64 m (max_); - quotient (m, scale_factor, maximum); - } - ACE_OS::sprintf (min_string, format, - minimum.whole (), minimum.fractional ()); - ACE_OS::sprintf (max_string, format, - maximum.whole (), maximum.fractional ()); - } - - if (success == 1) - { - ACE_OS::fprintf (file, ACE_TEXT ("samples: %u (%s - %s); mean: ") - ACE_TEXT ("%s; std dev: %s\n"), - samples (), min_string, max_string, - mean_string, std_dev_string); - return 0; - } - else - { - ACE_OS::fprintf (file, - ACE_TEXT ("ACE_Stats::print_summary: OVERFLOW: %s\n"), - ACE_OS::strerror (overflow_)); - - return -1; - } -} - -void -ACE_Stats::quotient (const ACE_UINT64 dividend, - const ACE_UINT32 divisor, - ACE_Stats_Value "ient) -{ - // The whole part of the division comes from simple integer division. - quotient.whole (static_cast (divisor == 0 - ? 0 : dividend / divisor)); - - if (quotient.precision () > 0 || divisor == 0) - { - const ACE_UINT32 field = quotient.fractional_field (); - - // Fractional = (dividend % divisor) * 10^precision / divisor - - // It would be nice to add round-up term: - // Fractional = (dividend % divisor) * 10^precision / divisor + - // 10^precision/2 / 10^precision - // = ((dividend % divisor) * 10^precision + divisor) / - // divisor - quotient.fractional (static_cast ( - dividend % divisor * field / divisor)); - } - else - { - // No fractional portion is requested, so don't bother - // calculating it. - quotient.fractional (0); - } -} - -void -ACE_Stats::quotient (const ACE_Stats_Value ÷nd, - const ACE_UINT32 divisor, - ACE_Stats_Value "ient) -{ - // The whole part of the division comes from simple integer division. - quotient.whole (divisor == 0 ? 0 : dividend.whole () / divisor); - - if (quotient.precision () > 0 || divisor == 0) - { - const ACE_UINT32 field = quotient.fractional_field (); - - // Fractional = (dividend % divisor) * 10^precision / divisor. - quotient.fractional (dividend.whole () % divisor * field / divisor + - dividend.fractional () / divisor); - } - else - { - // No fractional portion is requested, so don't bother - // calculating it. - quotient.fractional (0); - } -} - -void -ACE_Stats::square_root (const ACE_UINT64 n, - ACE_Stats_Value &square_root) -{ - ACE_UINT32 floor = 0; - ACE_UINT32 ceiling = 0xFFFFFFFFu; - ACE_UINT32 mid = 0; - u_int i; - - // The maximum number of iterations is log_2 (2^64) == 64. - for (i = 0; i < 64; ++i) - { - mid = (ceiling - floor) / 2 + floor; - if (floor == mid) - // Can't divide the interval any further. - break; - else - { - // Multiply carefully to avoid overflow. - ACE_UINT64 mid_squared = mid; mid_squared *= mid; - if (mid_squared == n) - break; - else if (mid_squared < n) - floor = mid; - else - ceiling = mid; - } - } - - square_root.whole (mid); - ACE_UINT64 mid_squared = mid; mid_squared *= mid; - - if (square_root.precision () && mid_squared < n) - { - // (mid * 10^precision + fractional)^2 == - // n^2 * 10^(precision * 2) - - const ACE_UINT32 field = square_root.fractional_field (); - - floor = 0; - ceiling = field; - mid = 0; - - // Do the 64-bit arithmetic carefully to avoid overflow. - ACE_UINT64 target = n; - target *= field; - target *= field; - - ACE_UINT64 difference = 0; - - for (i = 0; i < square_root.precision (); ++i) - { - mid = (ceiling - floor) / 2 + floor; - - ACE_UINT64 current = square_root.whole () * field + mid; - current *= square_root.whole () * field + mid; - - if (floor == mid) - { - difference = target - current; - break; - } - else if (current <= target) - floor = mid; - else - ceiling = mid; - } - - // Check to see if the fractional part should be one greater. - ACE_UINT64 next = square_root.whole () * field + mid + 1; - next *= square_root.whole () * field + mid + 1; - - square_root.fractional (next - target < difference ? mid + 1 : mid); - } - else - { - // No fractional portion is requested, so don't bother - // calculating it. - square_root.fractional (0); - } -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Stats.h b/externals/ace/Stats.h deleted file mode 100644 index 2590ec95c10..00000000000 --- a/externals/ace/Stats.h +++ /dev/null @@ -1,222 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file Stats.h - * - * $Id: Stats.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author David L. Levine - */ -//========================================================================== - - -#ifndef ACE_STATS_H -#define ACE_STATS_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Unbounded_Queue.h" -#include "ace/Log_Msg.h" -#include "ace/Basic_Stats.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Stats_Value - * - * @brief Helper class for ACE_Stats. - * - * Container struct for 64-bit signed quantity and its - * precision. It would be nicer to use a fixed-point class, but - * this is sufficient. Users typically don't need to use this - * class directly; see ACE_Stats below. - */ -class ACE_Export ACE_Stats_Value -{ -public: - /** - * Constructor, which requires precision in terms of number of - * decimal digits. The more variation in the data, and the greater - * the data values, the smaller the precision must be to avoid - * overflow in the standard deviation calculation. 3 might be a - * good value, or maybe 4. 5 will probably be too large for - * non-trivial data sets. - */ - ACE_Stats_Value (const u_int precision); - - /// Accessor for precision. - u_int precision (void) const; - - /// Set the whole_ field. - void whole (const ACE_UINT32); - - /// Accessor for the whole_ field. - ACE_UINT32 whole (void) const; - - /// Set the fractional_ field. - void fractional (const ACE_UINT32); - - /// Accessor for the fractional_ field. - ACE_UINT32 fractional (void) const; - - /// Calculates the maximum value of the fractional portion, given its - /// precision. - ACE_UINT32 fractional_field (void) const; - - /** - * Access the value as an _unsigned_ 64 bit quantity. It scales the - * value up by {precision} decimal digits, so that no precision will - * be lost. It assumes that {whole_} is >= 0. - */ - void scaled_value (ACE_UINT64 &) const; - - /// Print to stdout. - void dump (void) const; - -private: - - ACE_Stats_Value (void) {} - -private: - /// The integer portion of the value. - ACE_UINT32 whole_; - - /// The fractional portion of the value. - ACE_UINT32 fractional_; - - /** - * The number of decimal digits of precision represented by - * {fractional_}. Not declared const, so the only way to change it - * is via the assignment operator. - */ - u_int precision_; - -}; - -/** - * @class ACE_Stats - * - * @brief Provides simple statistical analysis. - * - * Simple statistical analysis package. Prominent features are: - * -# It does not use any floating point arithmetic. - * -# It handles positive and/or negative sample values. The - * sample value type is ACE_INT32. - * -# It uses 64 bit unsigned, but not 64 bit signed, quantities - * internally. - * -# It checks for overflow of internal state. - * -# It has no static variables of other than built-in types. - * - * Example usage: - * - * @verbatim - * ACE_Stats stats; - * for (u_int i = 0; i < n; ++i) - * { - * const ACE_UINT32 sample = ...; - * stats.sample (sample); - * } - * stats.print_summary (3); - * @endverbatim - */ -class ACE_Export ACE_Stats -{ -public: - /// Default constructor. - ACE_Stats (void); - - /// Provide a new sample. Returns 0 on success, -1 if it fails due - /// to running out of memory, or to rolling over of the sample count. - int sample (const ACE_INT32 value); - - /// Access the number of samples provided so far. - ACE_UINT32 samples (void) const; - - /// Value of the minimum sample provided so far. - ACE_INT32 min_value (void) const; - - /// Value of the maximum sample provided so far. - ACE_INT32 max_value (void) const; - - /** - * Access the mean of all samples provided so far. The fractional - * part is to the specified number of digits. E.g., 3 fractional - * digits specifies that the fractional part is in thousandths. - */ - void mean (ACE_Stats_Value &mean, - const ACE_UINT32 scale_factor = 1); - - /// Access the standard deviation, whole and fractional parts. See - /// description of {mean} method for argument descriptions. - int std_dev (ACE_Stats_Value &std_dev, - const ACE_UINT32 scale_factor = 1); - - /** - * Print summary statistics. If scale_factor is not 1, then the - * results are divided by it, i.e., each of the samples is scaled - * down by it. If internal overflow is reached with the specified - * scale factor, it successively tries to reduce it. Returns -1 if - * there is overflow even with a 0 scale factor. - */ - int print_summary (const u_int precision, - const ACE_UINT32 scale_factor = 1, - FILE * = stdout) const; - - /// Initialize internal state. - void reset (void); - - /// Utility division function, for ACE_UINT64 dividend. - static void quotient (const ACE_UINT64 dividend, - const ACE_UINT32 divisor, - ACE_Stats_Value "ient); - - /// Utility division function, for ACE_Stats_Value dividend. - static void quotient (const ACE_Stats_Value ÷nd, - const ACE_UINT32 divisor, - ACE_Stats_Value "ient); - - /** - * Sqrt function, which uses an oversimplified version of Newton's - * method. It's not fast, but it doesn't require floating point - * support. - */ - static void square_root (const ACE_UINT64 n, - ACE_Stats_Value &square_root); - - /// Print summary statistics to stdout. - void dump (void) const; - -protected: - /// Internal indication of whether there has been overflow. Contains - /// the errno corresponding to the cause of overflow. - u_int overflow_; - - /// Number of samples. - ACE_UINT32 number_of_samples_; - - /// Minimum sample value. - ACE_INT32 min_; - - /// Maximum sample value. - ACE_INT32 max_; - - /// The samples. - ACE_Unbounded_Queue samples_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -# include "ace/Stats.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" - -#endif /* ! ACE_STATS_H */ diff --git a/externals/ace/Stats.inl b/externals/ace/Stats.inl deleted file mode 100644 index 4c76838c207..00000000000 --- a/externals/ace/Stats.inl +++ /dev/null @@ -1,104 +0,0 @@ -// -*- C++ -*- -// -// $Id: Stats.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE -ACE_Stats_Value::ACE_Stats_Value (const u_int precision) - : whole_ (0), - fractional_ (0), - precision_ (precision) -{ -} - -ACE_INLINE -u_int -ACE_Stats_Value::precision (void) const -{ - return precision_; -} - -ACE_INLINE -void -ACE_Stats_Value::whole (const ACE_UINT32 value) -{ - whole_ = value; -} - -ACE_INLINE -ACE_UINT32 -ACE_Stats_Value::whole (void) const -{ - return whole_; -} - -ACE_INLINE -void -ACE_Stats_Value::fractional (const ACE_UINT32 value) -{ - fractional_ = value; -} - -ACE_INLINE -ACE_UINT32 -ACE_Stats_Value::fractional (void) const -{ - return fractional_; -} - -ACE_INLINE -void -ACE_Stats_Value::scaled_value (ACE_UINT64 &sv) const -{ - sv = whole () * fractional_field () + fractional (); -} - -ACE_INLINE -void -ACE_Stats_Value::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("precision: %u digits; whole: %u, fractional: %u\n"), - precision_, whole_, fractional_)); -#endif /* ACE_HAS_DUMP */ -} - -ACE_INLINE -ACE_Stats::ACE_Stats (void) -{ - reset (); -} - -ACE_INLINE -ACE_UINT32 -ACE_Stats::samples (void) const -{ - return number_of_samples_; -} - -ACE_INLINE -ACE_INT32 -ACE_Stats::min_value (void) const -{ - return min_; -} - -ACE_INLINE -ACE_INT32 -ACE_Stats::max_value (void) const -{ - return max_; -} - -ACE_INLINE -void -ACE_Stats::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - print_summary (3u); -#endif /* ACE_HAS_DUMP */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Strategies.h b/externals/ace/Strategies.h deleted file mode 100644 index 484ffa9a510..00000000000 --- a/externals/ace/Strategies.h +++ /dev/null @@ -1,33 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Strategies.h - * - * $Id: Strategies.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_STRATEGIES_H -#define ACE_STRATEGIES_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -/// Place holder for backward compatibility.. -#include "ace/Connection_Recycling_Strategy.h" -#include "ace/Hashable.h" -#include "ace/Notification_Strategy.h" -#include "ace/Reactor_Notification_Strategy.h" -#include "ace/Recyclable.h" -#include "ace/Refcountable.h" - - -#include /**/ "ace/post.h" -#endif /*ACE_STRATEGIES_H*/ diff --git a/externals/ace/Strategies_T.cpp b/externals/ace/Strategies_T.cpp deleted file mode 100644 index fbbc1a5bc93..00000000000 --- a/externals/ace/Strategies_T.cpp +++ /dev/null @@ -1,1502 +0,0 @@ -// $Id: Strategies_T.cpp 89510 2010-03-17 12:21:14Z vzykov $ - -#ifndef ACE_STRATEGIES_T_CPP -#define ACE_STRATEGIES_T_CPP - -#include "ace/Strategies_T.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Service_Repository.h" -#include "ace/Service_Types.h" -#include "ace/Thread_Manager.h" -#include "ace/WFMO_Reactor.h" -#include "ace/ACE.h" -#include "ace/OS_NS_dlfcn.h" -#include "ace/OS_NS_string.h" -#include "ace/OS_Errno.h" -#include "ace/Svc_Handler.h" -#if defined (ACE_OPENVMS) -# include "ace/Lib_Find.h" -#endif - -#if !defined (__ACE_INLINE__) -#include "ace/Strategies_T.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template -ACE_Recycling_Strategy::~ACE_Recycling_Strategy (void) -{ -} - -template int -ACE_Recycling_Strategy::assign_recycler (SVC_HANDLER *svc_handler, - ACE_Connection_Recycling_Strategy *recycler, - const void *recycling_act) -{ - svc_handler->recycler (recycler, recycling_act); - return 0; -} - -template int -ACE_Recycling_Strategy::prepare_for_recycling (SVC_HANDLER *svc_handler) -{ - return svc_handler->recycle (); -} - -template -ACE_Singleton_Strategy::~ACE_Singleton_Strategy (void) -{ - ACE_TRACE ("ACE_Singleton_Strategy::~ACE_Singleton_Strategy"); - if (this->delete_svc_handler_) - delete this->svc_handler_; -} - -// Create a Singleton SVC_HANDLER by always returning the same -// SVC_HANDLER. - -template int -ACE_Singleton_Strategy::make_svc_handler (SVC_HANDLER *&sh) -{ - ACE_TRACE ("ACE_Singleton_Strategy::make_svc_handler"); - sh = this->svc_handler_; - return 0; -} - -template int -ACE_Singleton_Strategy::open (SVC_HANDLER *sh, - ACE_Thread_Manager *) -{ - ACE_TRACE ("ACE_Singleton_Strategy::open"); - - if (this->delete_svc_handler_) - delete this->svc_handler_; - - // If is NULL then create a new . - if (sh == 0) - { - ACE_NEW_RETURN (this->svc_handler_, - SVC_HANDLER, - -1); - this->delete_svc_handler_ = true; - } - else - { - this->svc_handler_ = sh; - this->delete_svc_handler_ = false; - } - - return 0; -} - -template int -ACE_DLL_Strategy::open (const ACE_TCHAR dll_name[], - const ACE_TCHAR factory_function[], - const ACE_TCHAR svc_name[], - ACE_Service_Repository *svc_rep, - ACE_Thread_Manager *thr_mgr) -{ - ACE_TRACE ("ACE_DLL_Strategy::open"); - this->inherited::open (thr_mgr); - ACE_OS::strcpy (this->dll_name_, dll_name); - ACE_OS::strcpy (this->factory_function_, factory_function); - ACE_OS::strcpy (this->svc_name_, svc_name); - this->svc_rep_ = svc_rep; - return 0; -} - -// Create a SVC_HANDLER by dynamically linking it from a DLL. - -template int -ACE_DLL_Strategy::make_svc_handler (SVC_HANDLER *&sh) -{ - ACE_TRACE ("ACE_DLL_Strategy::make_svc_handler"); - - // Open the shared library. - ACE_SHLIB_HANDLE handle = ACE_OS::dlopen (this->dll_name_); - - // Extract the factory function. -#if defined (ACE_OPENVMS) - SVC_HANDLER *(*factory)(void) = - (SVC_HANDLER *(*)(void)) ACE::ldsymbol (handle, - this->factory_function_); -#else - SVC_HANDLER *(*factory)(void) = - (SVC_HANDLER *(*)(void)) ACE_OS::dlsym (handle, - this->factory_function_); -#endif - - // Call the factory function to obtain the new SVC_Handler (should - // use RTTI here when it becomes available...) - SVC_HANDLER *svc_handler = 0; - - ACE_ALLOCATOR_RETURN (svc_handler, (*factory)(), -1); - - if (svc_handler != 0) - { - // Create an ACE_Service_Type containing the SVC_Handler and - // insert into this->svc_rep_; - - ACE_Service_Type_Impl *stp = 0; - ACE_NEW_RETURN (stp, - ACE_Service_Object_Type (svc_handler, - this->svc_name_), - -1); - - ACE_Service_Type *srp = 0; - - ACE_NEW_RETURN (srp, - ACE_Service_Type (this->svc_name_, - stp, - handle, - 1), - -1); - if (srp == 0) - { - delete stp; - errno = ENOMEM; - return -1; - } - - if (this->svc_rep_->insert (srp) == -1) - return -1; - // @@ Somehow, we need to deal with this->thr_mgr_... - } - - sh = svc_handler; - return 0; -} - -// Default behavior is to activate the SVC_HANDLER by calling it's -// open() method, which allows the SVC_HANDLER to determine its own -// concurrency strategy. - -template int -ACE_Concurrency_Strategy::activate_svc_handler (SVC_HANDLER *svc_handler, - void *arg) -{ - ACE_TRACE ("ACE_Concurrency_Strategy::activate_svc_handler"); - - int result = 0; - - // See if we should enable non-blocking I/O on the 's - // peer. - if (ACE_BIT_ENABLED (this->flags_, ACE_NONBLOCK) != 0) - { - if (svc_handler->peer ().enable (ACE_NONBLOCK) == -1) - result = -1; - } - // Otherwise, make sure it's disabled by default. - else if (svc_handler->peer ().disable (ACE_NONBLOCK) == -1) - result = -1; - - if (result == 0 && svc_handler->open (arg) == -1) - result = -1; - - if (result == -1) - // The connection was already made; so this close is a "normal" close - // operation. - svc_handler->close (NORMAL_CLOSE_OPERATION); - - return result; -} - -template int -ACE_Reactive_Strategy::open (ACE_Reactor *reactor, - ACE_Reactor_Mask mask, - int flags) -{ - ACE_TRACE ("ACE_Reactive_Strategy::open"); - this->reactor_ = reactor; - this->mask_ = mask; - this->flags_ = flags; - - // Must have a - if (this->reactor_ == 0) - return -1; - else - return 0; -} - -template int -ACE_Reactive_Strategy::activate_svc_handler (SVC_HANDLER *svc_handler, - void *arg) -{ - ACE_TRACE ("ACE_Reactive_Strategy::activate_svc_handler"); - - int result = 0; - - if (this->reactor_ == 0) - result = -1; - - // Register with the Reactor with the appropriate . - else if (this->reactor_->register_handler (svc_handler, this->mask_) == -1) - result = -1; - - // If the implementation of the reactor uses event associations - else if (this->reactor_->uses_event_associations ()) - { - // If we don't have non-block on, it won't work with - // WFMO_Reactor - // This maybe too harsh - // if (!ACE_BIT_ENABLED (this->flags_, ACE_NONBLOCK)) - // goto failure; - if (svc_handler->open (arg) != -1) - return 0; - else - result = -1; - } - else - // Call up to our parent to do the SVC_HANDLER initialization. - return this->inherited::activate_svc_handler (svc_handler, arg); - - if (result == -1) - // The connection was already made; so this close is a "normal" close - // operation. - svc_handler->close (NORMAL_CLOSE_OPERATION); - - return result; -} - -template int -ACE_Thread_Strategy::open (ACE_Thread_Manager *thr_mgr, - long thr_flags, - int n_threads, - int flags) -{ - ACE_TRACE ("ACE_Thread_Strategy::open"); - this->thr_mgr_ = thr_mgr; - this->n_threads_ = n_threads; - this->thr_flags_ = thr_flags; - this->flags_ = flags; - - // Must have a thread manager! - if (this->thr_mgr_ == 0) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("error: must have a non-NULL thread manager\n")), - -1); - else - return 0; -} - -template int -ACE_Thread_Strategy::activate_svc_handler (SVC_HANDLER *svc_handler, - void *arg) -{ - ACE_TRACE ("ACE_Thread_Strategy::activate_svc_handler"); - // Call up to our parent to do the SVC_HANDLER initialization. - if (this->inherited::activate_svc_handler (svc_handler, - arg) == -1) - return -1; - else - // Turn the into an active object (if it isn't - // already one as a result of the first activation...) - return svc_handler->activate (this->thr_flags_, - this->n_threads_); -} - -template int -ACE_Accept_Strategy::open - (const ACE_PEER_ACCEPTOR_ADDR &local_addr, bool reuse_addr) -{ - this->reuse_addr_ = reuse_addr; - this->peer_acceptor_addr_ = local_addr; - if (this->peer_acceptor_.open (local_addr, reuse_addr) == -1) - return -1; - - // Set the peer acceptor's handle into non-blocking mode. This is a - // safe-guard against the race condition that can otherwise occur - // between the time when was interrupted. - if (ACE_Sig_Handler::sig_pending () != 0) - { - ACE_Sig_Handler::sig_pending (0); - - // This piece of code comes from the old TP_Reactor. We did not - // handle signals at all then. If we happen to handle signals - // in the TP_Reactor, we should then start worryiung about this - // - Bala 21-Aug- 01 -if 0 - // Not sure if this should be done in the TP_Reactor - // case... leave it out for now. -Steve Huston 22-Aug-00 - - // If any HANDLES in the are activated as a - // result of signals they should be dispatched since - // they may be time critical... - active_handle_count = this->any_ready (dispatch_set); -else - // active_handle_count = 0; -endif - - // Record the fact that the Reactor has dispatched a - // handle_signal() method. We need this to return the - // appropriate count. - return 1; - } - - return -1; -} -#endif // #if 0 - - -int -ACE_TP_Reactor::handle_timer_events (int & /*event_count*/, - ACE_TP_Token_Guard &guard) -{ - if (this->timer_queue_ == 0 || this->timer_queue_->is_empty()) - { // Empty timer queue so cannot have any expired timers. - return 0; - } - - // Get the current time - ACE_Time_Value cur_time (this->timer_queue_->gettimeofday () + - this->timer_queue_->timer_skew ()); - - // Look for a node in the timer queue whose timer <= the present - // time. - ACE_Timer_Node_Dispatch_Info info; - - if (this->timer_queue_->dispatch_info (cur_time, info)) - { - const void *upcall_act = 0; - - // Preinvoke. - this->timer_queue_->preinvoke (info, cur_time, upcall_act); - - // Release the token before dispatching notifies... - guard.release_token (); - - // call the functor - this->timer_queue_->upcall (info, cur_time); - - // Postinvoke - this->timer_queue_->postinvoke (info, cur_time, upcall_act); - - // We have dispatched a timer - return 1; - } - - return 0; -} - -int -ACE_TP_Reactor::handle_notify_events (int & /*event_count*/, - ACE_TP_Token_Guard &guard) -{ - // Get the handle on which notify calls could have occured - ACE_HANDLE notify_handle = this->get_notify_handle (); - - int result = 0; - - // The notify was not in the list returned by - // wait_for_multiple_events (). - if (notify_handle == ACE_INVALID_HANDLE) - return result; - - // Now just do a read on the pipe.. - ACE_Notification_Buffer buffer; - - // Clear the handle of the read_mask of our - this->ready_set_.rd_mask_.clr_bit (notify_handle); - - // Keep reading notifies till we empty it or till we have a - // dispatchable buffer - while (this->notify_handler_->read_notify_pipe (notify_handle, buffer) > 0) - { - // Just figure out whether we can read any buffer that has - // dispatchable info. If not we have just been unblocked by - // another thread trying to update the reactor. If we get any - // buffer that needs dispatching we will dispatch that after - // releasing the lock - if (this->notify_handler_->is_dispatchable (buffer) > 0) - { - // Release the token before dispatching notifies... - guard.release_token (); - - // Dispatch the upcall for the notify - this->notify_handler_->dispatch_notify (buffer); - - // We had a successful dispatch. - result = 1; - - // break out of the while loop - break; - } - } - - // If we did some work, then we just return 1 which will allow us - // to get out of here. If we return 0, then we will be asked to do - // some work ie. dispacth socket events - return result; -} - -int -ACE_TP_Reactor::handle_socket_events (int &event_count, - ACE_TP_Token_Guard &guard) -{ - - // We got the lock, lets handle some I/O events. - ACE_EH_Dispatch_Info dispatch_info; - - this->get_socket_event_info (dispatch_info); - - // If there is any event handler that is ready to be dispatched, the - // dispatch information is recorded in dispatch_info. - if (!dispatch_info.dispatch ()) - { - // Check for removed handlers. - if (dispatch_info.event_handler_ == 0) - { - this->handler_rep_.unbind(dispatch_info.handle_, - dispatch_info.mask_); - } - - - return 0; - } - - // Suspend the handler so that other threads don't start dispatching - // it, if we can't suspend then return directly - // - // NOTE: This check was performed in older versions of the - // TP_Reactor. Looks like it is a waste.. - if (dispatch_info.event_handler_ != this->notify_handler_) - if (this->suspend_i (dispatch_info.handle_) == -1) - return 0; - - // Call add_reference() if needed. - if (dispatch_info.reference_counting_required_) - dispatch_info.event_handler_->add_reference (); - - // Release the lock. Others threads can start waiting. - guard.release_token (); - - int result = 0; - - // If there was an event handler ready, dispatch it. - // Decrement the event left - --event_count; - - // Dispatched an event - if (this->dispatch_socket_event (dispatch_info) == 0) - ++result; - - return result; -} - -int -ACE_TP_Reactor::get_event_for_dispatching (ACE_Time_Value *max_wait_time) -{ - // If the reactor handler state has changed, clear any remembered - // ready bits and re-scan from the master wait_set. - if (this->state_changed_) - { - this->ready_set_.rd_mask_.reset (); - this->ready_set_.wr_mask_.reset (); - this->ready_set_.ex_mask_.reset (); - - this->state_changed_ = false; - } - else - { - // This is a hack... somewhere, under certain conditions (which - // I don't understand...) the mask will have all of its bits clear, - // yet have a size_ > 0. This is an attempt to remedy the affect, - // without knowing why it happens. - - this->ready_set_.rd_mask_.sync (this->ready_set_.rd_mask_.max_set ()); - this->ready_set_.wr_mask_.sync (this->ready_set_.wr_mask_.max_set ()); - this->ready_set_.ex_mask_.sync (this->ready_set_.ex_mask_.max_set ()); - } - - return this->wait_for_multiple_events (this->ready_set_, max_wait_time); -} - -int -ACE_TP_Reactor::get_socket_event_info (ACE_EH_Dispatch_Info &event) -{ - // Check for dispatch in write, except, read. Only catch one, but if - // one is caught, be sure to clear the handle from each mask in case - // there is more than one mask set for it. This would cause problems - // if the handler is suspended for dispatching, but its set bit in - // another part of ready_set_ kept it from being dispatched. - int found_io = 0; - ACE_HANDLE handle; - - // @@todo: We can do quite a bit of code reduction here. Let me get - // it to work before I do this. - { - ACE_Handle_Set_Iterator handle_iter (this->ready_set_.wr_mask_); - - while (!found_io && (handle = handle_iter ()) != ACE_INVALID_HANDLE) - { - if (this->is_suspended_i (handle)) - continue; - - // Remember this info - event.set (handle, - this->handler_rep_.find (handle), - ACE_Event_Handler::WRITE_MASK, - &ACE_Event_Handler::handle_output); - - this->clear_handle_read_set (handle); - found_io = 1; - } - } - - if (!found_io) - { - ACE_Handle_Set_Iterator handle_iter (this->ready_set_.ex_mask_); - - while (!found_io && (handle = handle_iter ()) != ACE_INVALID_HANDLE) - { - if (this->is_suspended_i (handle)) - continue; - - // Remember this info - event.set (handle, - this->handler_rep_.find (handle), - ACE_Event_Handler::EXCEPT_MASK, - &ACE_Event_Handler::handle_exception); - - this->clear_handle_read_set (handle); - - found_io = 1; - } - } - - if (!found_io) - { - ACE_Handle_Set_Iterator handle_iter (this->ready_set_.rd_mask_); - - while (!found_io && (handle = handle_iter ()) != ACE_INVALID_HANDLE) - { - if (this->is_suspended_i (handle)) - continue; - - // Remember this info - event.set (handle, - this->handler_rep_.find (handle), - ACE_Event_Handler::READ_MASK, - &ACE_Event_Handler::handle_input); - - this->clear_handle_read_set (handle); - found_io = 1; - } - } - - return found_io; -} - -// Dispatches a single event handler -int -ACE_TP_Reactor::dispatch_socket_event (ACE_EH_Dispatch_Info &dispatch_info) -{ - ACE_TRACE ("ACE_TP_Reactor::dispatch_socket_event"); - - ACE_Event_Handler * const event_handler = dispatch_info.event_handler_; - ACE_EH_PTMF const callback = dispatch_info.callback_; - - // Check for removed handlers. - if (event_handler == 0) - return -1; - - // Upcall. If the handler returns positive value (requesting a - // reactor callback) don't set the ready-bit because it will be - // ignored if the reactor state has changed. Just call back - // as many times as the handler requests it. Other threads are off - // handling other things. - int status = 1; - while (status > 0) - status = (event_handler->*callback) (dispatch_info.handle_); - - // Post process socket event - return this->post_process_socket_event (dispatch_info, status); -} - -int -ACE_TP_Reactor::post_process_socket_event (ACE_EH_Dispatch_Info &dispatch_info, - int status) -{ - int result = 0; - - // First check if we really have to post process something, if not, then - // we don't acquire the token which saves us a lot of time. - if (status < 0 || - (dispatch_info.event_handler_ != this->notify_handler_ && - dispatch_info.resume_flag_ == - ACE_Event_Handler::ACE_REACTOR_RESUMES_HANDLER)) - { - // Get the reactor token and with this token acquired remove first the - // handler and resume it at the same time. This must be atomic, see also - // bugzilla 2395. When this is not atomic it can be that we resume the - // handle after it is reused by the OS. - ACE_TP_Token_Guard guard (this->token_); - - result = guard.acquire_token (); - - // If the guard is NOT the owner just return the retval - if (!guard.is_owner ()) - return result; - - // A different event handler may have been registered during the - // upcall if the handle was closed and then reopened, for - // example. Make sure we're removing and/or resuming the event - // handler used during the upcall. - ACE_Event_Handler const * const eh = - this->handler_rep_.find (dispatch_info.handle_); - - // Only remove or resume the event handler used during the - // upcall. - if (eh == dispatch_info.event_handler_) - { - if (status < 0) - { - result = - this->remove_handler_i (dispatch_info.handle_, - dispatch_info.mask_); - } - - // Resume handler if required. - if (dispatch_info.event_handler_ != this->notify_handler_ && - dispatch_info.resume_flag_ == - ACE_Event_Handler::ACE_REACTOR_RESUMES_HANDLER) - this->resume_i (dispatch_info.handle_); - } - } - - // Call remove_reference() if needed. - if (dispatch_info.reference_counting_required_) - dispatch_info.event_handler_->remove_reference (); - - return result; -} - -int -ACE_TP_Reactor::resumable_handler (void) -{ - return 1; -} - -int -ACE_TP_Reactor::handle_events (ACE_Time_Value &max_wait_time) -{ - return this->handle_events (&max_wait_time); -} - -void -ACE_TP_Reactor::notify_handle (ACE_HANDLE, - ACE_Reactor_Mask, - ACE_Handle_Set &, - ACE_Event_Handler *eh, - ACE_EH_PTMF) -{ - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("ACE_TP_Reactor::notify_handle: ") - ACE_TEXT ("Wrong version of notify_handle() got called\n"))); - - ACE_ASSERT (eh == 0); - ACE_UNUSED_ARG (eh); -} - -ACE_HANDLE -ACE_TP_Reactor::get_notify_handle (void) -{ - // Call the notify handler to get a handle on which we would have a - // notify waiting - ACE_HANDLE const read_handle = - this->notify_handler_->notify_handle (); - - // Check whether the rd_mask has been set on that handle. If so - // return the handle. - if (read_handle != ACE_INVALID_HANDLE && - this->ready_set_.rd_mask_.is_set (read_handle)) - { - return read_handle; - } - - // None found.. - return ACE_INVALID_HANDLE; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/TP_Reactor.h b/externals/ace/TP_Reactor.h deleted file mode 100644 index 33e00c2e57f..00000000000 --- a/externals/ace/TP_Reactor.h +++ /dev/null @@ -1,320 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file TP_Reactor.h - * - * $Id: TP_Reactor.h 82723 2008-09-16 09:35:44Z johnnyw $ - * - * The ACE_TP_Reactor (aka, Thread Pool Reactor) uses the - * Leader/Followers pattern to demultiplex events among a pool of - * threads. When using a thread pool reactor, an application - * pre-spawns a fixed number of threads. When these threads - * invoke the ACE_TP_Reactor's handle_events() method, one thread - * will become the leader and wait for an event. The other - * follower threads will queue up waiting for their turn to become - * the leader. When an event occurs, the leader will pick a - * follower to become the leader and go on to handle the event. - * The consequence of using ACE_TP_Reactor is the amortization of - * the costs used to create threads. The context switching cost - * will also reduce. Moreover, the total resources used by - * threads are bounded because there are a fixed number of threads. - * - * @author Irfan Pyarali - * @author Nanbor Wang - */ -//============================================================================= - - -#ifndef ACE_TP_REACTOR_H -#define ACE_TP_REACTOR_H - -#include /**/ "ace/pre.h" - -#include "ace/Select_Reactor.h" -#include "ace/Timer_Queue.h" /* Simple forward decl won't work... */ - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_EH_Dispatch_Info - * - * @brief This structure contains information of the activated event - * handler. - */ -class ACE_EH_Dispatch_Info -{ -public: - ACE_EH_Dispatch_Info (void); - - void set (ACE_HANDLE handle, - ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask, - ACE_EH_PTMF callback); - - bool dispatch (void) const; - - ACE_HANDLE handle_; - ACE_Event_Handler *event_handler_; - ACE_Reactor_Mask mask_; - ACE_EH_PTMF callback_; - int resume_flag_; - bool reference_counting_required_; - -private: - bool dispatch_; - - // Disallow copying and assignment. - ACE_EH_Dispatch_Info (const ACE_EH_Dispatch_Info &); - ACE_EH_Dispatch_Info &operator= (const ACE_EH_Dispatch_Info &); -}; - - -/** - * @class ACE_TP_Token_Guard - * - * @brief A helper class that helps grabbing, releasing and waiting - * on tokens for a thread that tries calling handle_events (). - * - * In short, this class will be owned by one thread by creating on the - * stack. This class gives the status of the ownership of the token - * and manages the ownership - */ - -class ACE_TP_Token_Guard -{ -public: - - /// Constructor that will grab the token for us - ACE_TP_Token_Guard (ACE_Select_Reactor_Token &token); - - /// Destructor. This will release the token if it hasnt been - /// released till this point - ~ACE_TP_Token_Guard (void); - - /// Release the token .. - void release_token (void); - - /// Returns whether the thread that created this object ownes the - /// token or not. - bool is_owner (void); - - /// A helper method that grabs the token for us, after which the - /// thread that owns that can do some actual work. - int acquire_read_token (ACE_Time_Value *max_wait_time = 0); - - /** - * A helper method that grabs the token for us, after which the - * thread that owns that can do some actual work. This differs from - * acquire_read_token() as it uses acquire () to get the token instead of - * acquire_read () - */ - int acquire_token (ACE_Time_Value *max_wait_time = 0); - -private: - - // Disallow default construction. - ACE_TP_Token_Guard (void); - - // Disallow copying and assignment. - ACE_TP_Token_Guard (const ACE_TP_Token_Guard &); - ACE_TP_Token_Guard &operator= (const ACE_TP_Token_Guard &); - -private: - - /// The Select Reactor token. - ACE_Select_Reactor_Token &token_; - - /// Flag that indicate whether the thread that created this object - /// owns the token or not. A value of false indicates that this class - /// hasnt got the token (and hence the thread) and a value of true - /// vice-versa. - bool owner_; - -}; - -/** - * @class ACE_TP_Reactor - * - * @brief Specialization of ACE_Select_Reactor to support thread-pool - * based event dispatching. - * - * One of the shortcomings of the ACE_Select_Reactor is that it - * does not support a thread pool-based event dispatching model, - * similar to the one in ACE_WFMO_Reactor. In ACE_Select_Reactor, only - * thread can call handle_events() at any given time. ACE_TP_Reactor - * removes this short-coming. - * - * ACE_TP_Reactor is a specialization of ACE_Select_Reactor to support - * thread pool-based event dispatching. This reactor takes advantage - * of the fact that events reported by @c select() are persistent if not - * acted upon immediately. It works by remembering the event handler - * which was just activated, suspending it for further I/O activities, - * releasing the internal lock (so that another thread can start waiting - * in the event loop) and then dispatching the event's handler outside the - * scope of the reactor lock. After the event handler has been dispatched - * the event handler is resumed for further I/O activity. - * - * This reactor implementation is best suited for situations when the - * callbacks to event handlers can take arbitrarily long and/or a number - * of threads are available to run the event loop. Note that I/O-processing - * callback code in event handlers (e.g. handle_input()) does not have to - * be modified or made thread-safe for this reactor. This is because - * before an I/O event is dispatched to an event handler, the handler is - * suspended; it is resumed by the reactor after the upcall completes. - * Therefore, multiple I/O events will not be made to one event handler - * multiple threads simultaneously. This suspend/resume protection does not - * apply to either timers scheduled with the reactor or to notifications - * requested via the reactor. When using timers and/or notifications you - * must provide proper protection for your class in the context of multiple - * threads. - */ -class ACE_Export ACE_TP_Reactor : public ACE_Select_Reactor -{ -public: - - /// Initialize ACE_TP_Reactor with the default size. - ACE_TP_Reactor (ACE_Sig_Handler * = 0, - ACE_Timer_Queue * = 0, - bool mask_signals = true, - int s_queue = ACE_Select_Reactor_Token::FIFO); - - /** - * Initialize the ACE_TP_Reactor to manage - * @a max_number_of_handles. If @a restart is non-0 then the - * ACE_Reactor's @c handle_events() method will be restarted - * automatically when @c EINTR occurs. If @a sh or - * @a tq are non-0 they are used as the signal handler and - * timer queue, respectively. - */ - ACE_TP_Reactor (size_t max_number_of_handles, - bool restart = false, - ACE_Sig_Handler *sh = 0, - ACE_Timer_Queue *tq = 0, - bool mask_signals = true, - int s_queue = ACE_Select_Reactor_Token::FIFO); - - /** - * This event loop driver that blocks for @a max_wait_time before - * returning. It will return earlier if timer events, I/O events, - * or signal events occur. Note that @a max_wait_time can be 0, in - * which case this method blocks indefinitely until events occur. - * - * @a max_wait_time is decremented to reflect how much time this call - * took. For instance, if a time value of 3 seconds is passed to - * handle_events and an event occurs after 2 seconds, - * @a max_wait_time will equal 1 second. This can be used if an - * application wishes to handle events for some fixed amount of - * time. - * - * @return The total number of events that were dispatched; 0 if the - * @a max_wait_time elapsed without dispatching any handlers, or -1 - * if an error occurs (check @c errno for more information). - */ - virtual int handle_events (ACE_Time_Value *max_wait_time = 0); - - virtual int handle_events (ACE_Time_Value &max_wait_time); - - /// Does the reactor allow the application to resume the handle on - /// its own ie. can it pass on the control of handle resumption to - /// the application. The TP reactor has can allow applications to - /// resume handles. So return a positive value. - virtual int resumable_handler (void); - - /// Called from handle events - static void no_op_sleep_hook (void *); - - /// The ACE_TP_Reactor implementation does not have a single owner thread. - /// Attempts to set the owner explicitly are ignored. The reported owner - /// thread is the current Leader in the pattern. - virtual int owner (ACE_thread_t n_id, ACE_thread_t *o_id = 0); - - /// Return the thread ID of the current Leader. - virtual int owner (ACE_thread_t *t_id); - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - // = Internal methods that do the actual work. - - /// Template method from the base class. - virtual void clear_dispatch_mask (ACE_HANDLE handle, - ACE_Reactor_Mask mask); - - /// Dispatch just 1 signal, timer, notification handlers - int dispatch_i (ACE_Time_Value *max_wait_time, - ACE_TP_Token_Guard &guard); - - /// Get the event that needs dispatching. It could be either a - /// signal, timer, notification handlers or return possibly 1 I/O - /// handler for dispatching. In the most common use case, this would - /// return 1 I/O handler for dispatching - int get_event_for_dispatching (ACE_Time_Value *max_wait_time); - -#if 0 - // @Ciju - // signal handling isn't in a production state yet. - // Commenting it out for now. - - /// Method to handle signals - /// @note It is just busted at this point in time. - int handle_signals (int &event_count, - ACE_TP_Token_Guard &g); -#endif // #if 0 - - /// Handle timer events - int handle_timer_events (int &event_count, - ACE_TP_Token_Guard &g); - - /// Handle notify events - int handle_notify_events (int &event_count, - ACE_TP_Token_Guard &g); - - /// handle socket events - int handle_socket_events (int &event_count, - ACE_TP_Token_Guard &g); - - /// This method shouldn't get called. - virtual void notify_handle (ACE_HANDLE handle, - ACE_Reactor_Mask mask, - ACE_Handle_Set &, - ACE_Event_Handler *eh, - ACE_EH_PTMF callback); -private: - - /// Get the handle of the notify pipe from the ready set if there is - /// an event in the notify pipe. - ACE_HANDLE get_notify_handle (void); - - /// Get socket event dispatch information. - int get_socket_event_info (ACE_EH_Dispatch_Info &info); - - /// Notify the appropriate in the context of the - /// associated with that a particular event has occurred. - int dispatch_socket_event (ACE_EH_Dispatch_Info &dispatch_info); - - /// Clear the @a handle from the read_set - void clear_handle_read_set (ACE_HANDLE handle); - - int post_process_socket_event (ACE_EH_Dispatch_Info &dispatch_info,int status); - -private: - /// Deny access since member-wise won't work... - ACE_TP_Reactor (const ACE_TP_Reactor &); - ACE_TP_Reactor &operator = (const ACE_TP_Reactor &); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/TP_Reactor.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" - -#endif /* ACE_TP_REACTOR_H */ diff --git a/externals/ace/TP_Reactor.inl b/externals/ace/TP_Reactor.inl deleted file mode 100644 index 2b14a8c9b96..00000000000 --- a/externals/ace/TP_Reactor.inl +++ /dev/null @@ -1,119 +0,0 @@ -// -*- C++ -*- -// -// $Id: TP_Reactor.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/************************************************************************/ -// Methods for ACE_EH_Dispatch_Info -/************************************************************************/ - -ACE_INLINE -ACE_EH_Dispatch_Info::ACE_EH_Dispatch_Info (void) : - handle_ (ACE_INVALID_HANDLE), - event_handler_ (0), - mask_ (ACE_Event_Handler::NULL_MASK), - callback_ (0), - resume_flag_ (ACE_Event_Handler::ACE_REACTOR_RESUMES_HANDLER), - reference_counting_required_ (false), - dispatch_ (false) -{ -} - -ACE_INLINE void -ACE_EH_Dispatch_Info::set (ACE_HANDLE handle, - ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask, - ACE_EH_PTMF callback) -{ - this->dispatch_ = true; - - this->handle_ = handle; - this->event_handler_ = event_handler; - this->mask_ = mask; - this->callback_ = callback; - if (event_handler_) - { - this->resume_flag_ = event_handler->resume_handler (); - this->reference_counting_required_ = - (event_handler_->reference_counting_policy ().value () == - ACE_Event_Handler::Reference_Counting_Policy::ENABLED); - } - else - this->dispatch_ = false; -} - -ACE_INLINE bool -ACE_EH_Dispatch_Info::dispatch (void) const -{ - return this->dispatch_; -} - -/************************************************************************/ -// Methods for ACE_TP_Token_Guard -/************************************************************************/ - -ACE_INLINE -ACE_TP_Token_Guard::ACE_TP_Token_Guard (ACE_Select_Reactor_Token &token) - - : token_ (token), - owner_ (false) -{ -} - -ACE_INLINE -ACE_TP_Token_Guard::~ACE_TP_Token_Guard (void) -{ - if (this->owner_) - { - ACE_MT (this->token_.release ()); - this->owner_ = false; - } -} - -ACE_INLINE void -ACE_TP_Token_Guard::release_token (void) -{ - if (this->owner_) - { - ACE_MT (this->token_.release ()); - - // We are not the owner anymore.. - this->owner_ = false; - } -} - -ACE_INLINE bool -ACE_TP_Token_Guard::is_owner (void) -{ - return this->owner_; -} - - -/************************************************************************/ -// Methods for ACE_TP_Reactor -/************************************************************************/ - -ACE_INLINE void -ACE_TP_Reactor::no_op_sleep_hook (void *) -{ -} - -ACE_INLINE void -ACE_TP_Reactor::clear_handle_read_set (ACE_HANDLE handle) -{ - this->ready_set_.wr_mask_.clr_bit (handle); - this->ready_set_.ex_mask_.clr_bit (handle); - this->ready_set_.rd_mask_.clr_bit (handle); -} - -ACE_INLINE void -ACE_TP_Reactor::clear_dispatch_mask (ACE_HANDLE , - ACE_Reactor_Mask ) -{ - this->ready_set_.rd_mask_.reset (); - this->ready_set_.wr_mask_.reset (); - this->ready_set_.ex_mask_.reset (); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/TSS_Adapter.cpp b/externals/ace/TSS_Adapter.cpp deleted file mode 100644 index da6218dddb8..00000000000 --- a/externals/ace/TSS_Adapter.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/** - * @file TSS_Adapter.cpp - * - * $Id: TSS_Adapter.cpp 80826 2008-03-04 14:51:23Z wotte $ - * - * Originally in Synch.cpp - * - * @author Douglas C. Schmidt - */ - -#include "ace/TSS_Adapter.h" - -ACE_RCSID(ace, TSS_Adapter, "$Id: TSS_Adapter.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_TSS_Adapter::ACE_TSS_Adapter (void *object, ACE_THR_DEST f) - : ts_obj_ (object), - func_ (f) -{ - // ACE_TRACE ("ACE_TSS_Adapter::ACE_TSS_Adapter"); -} - -void -ACE_TSS_Adapter::cleanup (void) -{ - // ACE_TRACE ("ACE_TSS_Adapter::cleanup"); - (*this->func_)(this->ts_obj_); // call cleanup routine for ts_obj_ -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -extern "C" void -ACE_TSS_C_cleanup (void *object) -{ - // ACE_TRACE ("ACE_TSS_C_cleanup"); - if (object != 0) - { - ACE_TSS_Adapter * const tss_adapter = (ACE_TSS_Adapter *) object; - // Perform cleanup on the real TS object. - tss_adapter->cleanup (); - // Delete the adapter object. - delete tss_adapter; - } -} diff --git a/externals/ace/TSS_Adapter.h b/externals/ace/TSS_Adapter.h deleted file mode 100644 index b8ff85e3210..00000000000 --- a/externals/ace/TSS_Adapter.h +++ /dev/null @@ -1,61 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file TSS_Adapter.h - * - * $Id: TSS_Adapter.h 80826 2008-03-04 14:51:23Z wotte $ - * - * Originally in Synch.h - * - * @author Douglas C. Schmidt - */ -//========================================================================== - -#ifndef ACE_TSS_ADAPTER_H -#define ACE_TSS_ADAPTER_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_TSS_Adapter - * - * @brief This class encapsulates a TSS object and its associated - * C++ destructor function. It is used by the ACE_TSS... - * methods (in Synch_T.cpp) in order to allow an extern - * "C" cleanup routine to be used. Needed by the "frigging" - * MVS C++ compiler. - * - * Objects of this class are stored in thread specific - * storage. ts_obj_ points to the "real" object and - * func_ is a pointer to the C++ cleanup function for ts_obj_. - */ -class ACE_Export ACE_TSS_Adapter -{ -public: - /// Initialize the adapter. - ACE_TSS_Adapter (void *object, ACE_THR_DEST f); - - /// Perform the cleanup operation. - void cleanup (void); - -//private: - - /// The real TS object. - void * const ts_obj_; - - /// The real cleanup routine for ts_obj; - ACE_THR_DEST func_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" -#endif /* ACE_TSS_ADAPTER_H */ diff --git a/externals/ace/TSS_T.cpp b/externals/ace/TSS_T.cpp deleted file mode 100644 index 79603f8467c..00000000000 --- a/externals/ace/TSS_T.cpp +++ /dev/null @@ -1,709 +0,0 @@ -// $Id: TSS_T.cpp 91136 2010-07-20 08:56:37Z vzykov $ - -#ifndef ACE_TSS_T_CPP -#define ACE_TSS_T_CPP - -#include "ace/TSS_T.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (__ACE_INLINE__) -#include "ace/TSS_T.inl" -#endif /* __ACE_INLINE__ */ - -#include "ace/Thread.h" -#include "ace/Log_Msg.h" -#include "ace/Guard_T.h" -#include "ace/OS_NS_stdio.h" - -#if defined (ACE_HAS_THR_C_DEST) -# include "ace/TSS_Adapter.h" -#endif /* ACE_HAS_THR_C_DEST */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_TSS) - -#if defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION)) -# if defined (ACE_HAS_THR_C_DEST) -extern "C" void ACE_TSS_C_cleanup (void *); // defined in Synch.cpp -# endif /* ACE_HAS_THR_C_DEST */ -#endif /* defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION)) */ - -template -ACE_TSS::~ACE_TSS (void) -{ -#if defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION)) - if (this->once_) - { -# if defined (ACE_HAS_THR_C_DEST) - ACE_TSS_Adapter *tss_adapter = this->ts_value (); - this->ts_value (0); - ACE_TSS_C_cleanup (tss_adapter); -# else - TYPE *ts_obj = this->ts_value (); - this->ts_value (0); - ACE_TSS::cleanup (ts_obj); -# endif /* ACE_HAS_THR_C_DEST */ - - ACE_OS::thr_key_detach (this->key_, this); - ACE_OS::thr_keyfree (this->key_); - } -#else // defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION)) - // We own it, we need to delete it. - delete type_; -#endif // defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION)) -} - -template TYPE * -ACE_TSS::operator-> () const -{ - return this->ts_get (); -} - -template -ACE_TSS::operator TYPE *(void) const -{ - return this->ts_get (); -} - -template TYPE * -ACE_TSS::make_TSS_TYPE (void) const -{ - TYPE *temp = 0; - ACE_NEW_RETURN (temp, - TYPE, - 0); - return temp; -} - -template void -ACE_TSS::dump (void) const -{ -#if defined (ACE_HAS_DUMP) -// ACE_TRACE ("ACE_TSS::dump"); -#if defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION)) - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - this->keylock_.dump (); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("key_ = %d\n"), this->key_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nonce_ = %d\n"), this->once_)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION)) */ -#endif /* ACE_HAS_DUMP */ -} - -#if defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION)) - -template void -ACE_TSS::cleanup (void *ptr) -{ - // Cast this to the concrete TYPE * so the destructor gets called. - delete (TYPE *) ptr; -} - -template int -ACE_TSS::ts_init (void) -{ - // Ensure that we are serialized! - ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->keylock_, 0); - - // Use the Double-Check pattern to make sure we only create the key - // once! - if (!this->once_) - { - if (ACE_Thread::keycreate (&this->key_, -#if defined (ACE_HAS_THR_C_DEST) - &ACE_TSS_C_cleanup, -#else - &ACE_TSS::cleanup, -#endif /* ACE_HAS_THR_C_DEST */ - (void *) this) != 0) - return -1; // Major problems, this should *never* happen! - else - { - // This *must* come last to avoid race conditions! - this->once_ = true; - return 0; - } - } - - return 0; -} - -template -ACE_TSS::ACE_TSS (TYPE *ts_obj) - : once_ (false), - key_ (ACE_OS::NULL_key) -{ - // If caller has passed us a non-NULL TYPE *, then we'll just use - // this to initialize the thread-specific value. Thus, subsequent - // calls to operator->() will return this value. This is useful - // since it enables us to assign objects to thread-specific data - // that have arbitrarily complex constructors! - - if (ts_obj != 0) - { - if (this->ts_init () == -1) - { - // Save/restore errno. - ACE_Errno_Guard error (errno); - // What should we do if this call fails?! -#if defined (ACE_HAS_WINCE) - ::MessageBox (0, - ACE_TEXT ("ACE_Thread::keycreate() failed!"), - ACE_TEXT ("ACE_TSS::ACE_TSS"), - MB_OK); -#else - ACE_OS::fprintf (stderr, - "ACE_Thread::keycreate() failed!"); -#endif /* ACE_HAS_WINCE */ - return; - } - -#if defined (ACE_HAS_THR_C_DEST) - // Encapsulate a ts_obj and it's destructor in an - // ACE_TSS_Adapter. - ACE_TSS_Adapter *tss_adapter = 0; - ACE_NEW (tss_adapter, - ACE_TSS_Adapter ((void *) ts_obj, - ACE_TSS::cleanup)); - - // Put the adapter in thread specific storage - if (this->ts_value (tss_adapter) == -1) - { - delete tss_adapter; - } -#else - this->ts_value (ts_obj); -#endif /* ACE_HAS_THR_C_DEST */ - } -} - -template TYPE * -ACE_TSS::ts_get (void) const -{ - if (!this->once_) - { - // Create and initialize thread-specific ts_obj. - if (const_cast< ACE_TSS < TYPE > * >(this)->ts_init () == -1) - // Seriously wrong.. - return 0; - } - - TYPE *ts_obj = 0; - -#if defined (ACE_HAS_THR_C_DEST) - ACE_TSS_Adapter *tss_adapter = this->ts_value (); - ACE_TSS_Adapter *fake_tss_adapter = 0; - - // If tss_adapter is not 0 but its ts_obj_ is 0 then we still need to create - // a proper ts_obj. That's the intent of this member function. - if (tss_adapter != 0 && tss_adapter->ts_obj_ == 0) - { - fake_tss_adapter = tss_adapter; - tss_adapter = 0; - } - - // Check to see if this is the first time in for this thread. - if (tss_adapter == 0) -#else - ts_obj = this->ts_value (); - - // Check to see if this is the first time in for this thread. - if (ts_obj == 0) -#endif /* ACE_HAS_THR_C_DEST */ - { - // Allocate memory off the heap and store it in a pointer in - // thread-specific storage (on the stack...). - - ts_obj = this->make_TSS_TYPE (); - - if (ts_obj == 0) - return 0; - -#if defined (ACE_HAS_THR_C_DEST) - // Encapsulate a ts_obj and it's destructor in an - // ACE_TSS_Adapter. - ACE_NEW_RETURN (tss_adapter, - ACE_TSS_Adapter (ts_obj, - ACE_TSS::cleanup), 0); - - // Put the adapter in thread specific storage - if (this->ts_value (tss_adapter) == -1) - { - delete tss_adapter; - delete ts_obj; - return 0; // Major problems, this should *never* happen! - } -#else - // Store the dynamically allocated pointer in thread-specific - // storage. - if (this->ts_value (ts_obj) == -1) - { - delete ts_obj; - return 0; // Major problems, this should *never* happen! - } -#endif /* ACE_HAS_THR_C_DEST */ - } - -#if defined (ACE_HAS_THR_C_DEST) - // Delete the adapter that didn't actually have a real ts_obj. - delete fake_tss_adapter; - // Return the underlying ts object. - return static_cast (tss_adapter->ts_obj_); -#else - return ts_obj; -#endif /* ACE_HAS_THR_C_DEST */ -} - -// Get the thread-specific object for the key associated with this -// object. Returns 0 if the ts_obj has never been initialized, -// otherwise returns a pointer to the ts_obj. - -template TYPE * -ACE_TSS::ts_object (void) const -{ - if (!this->once_) // Return 0 if we've never been initialized. - return 0; - - TYPE *ts_obj = 0; - -#if defined (ACE_HAS_THR_C_DEST) - ACE_TSS_Adapter *tss_adapter = this->ts_value (); - - if (tss_adapter != 0) - { - // Extract the real TS object. - ts_obj = static_cast (tss_adapter->ts_obj_); - } -#else - ts_obj = this->ts_value (); -#endif /* ACE_HAS_THR_C_DEST */ - - return ts_obj; -} - -template TYPE * -ACE_TSS::ts_object (TYPE *new_ts_obj) -{ - // Note, we shouldn't hold the keylock at this point because - // does it for us and we'll end up with deadlock - // otherwise... - if (!this->once_) - { - // Create and initialize thread-specific ts_obj. - if (this->ts_init () == -1) - return 0; - } - - TYPE *ts_obj = 0; - -#if defined (ACE_HAS_THR_C_DEST) - ACE_TSS_Adapter *tss_adapter = this->ts_value (); - - if (tss_adapter != 0) - { - ts_obj = static_cast (tss_adapter->ts_obj_); - // Don't delete tss_adapter yet. It can be double-deleted - // in case setspecific below fails. - } - - ACE_TSS_Adapter *new_tss_adapter = 0; - ACE_NEW_RETURN (new_tss_adapter, - ACE_TSS_Adapter ((void *) new_ts_obj, - ACE_TSS::cleanup), - 0); - - if (this->ts_value (new_tss_adapter) == -1) - { - delete new_tss_adapter; - } - else - { - // Now it's fine to delete the old tss_adapter. - delete tss_adapter; - } -#else - ts_obj = this->ts_value (); - this->ts_value (new_ts_obj); -#endif /* ACE_HAS_THR_C_DEST */ - - return ts_obj; -} - -ACE_ALLOC_HOOK_DEFINE(ACE_TSS_Guard) - -template void -ACE_TSS_Guard::dump (void) const -{ -#if defined (ACE_HAS_DUMP) -// ACE_TRACE ("ACE_TSS_Guard::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("key_ = %d\n"), this->key_)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -template void -ACE_TSS_Guard::init_key (void) -{ -// ACE_TRACE ("ACE_TSS_Guard::init_key"); - - this->key_ = ACE_OS::NULL_key; - ACE_Thread::keycreate (&this->key_, -#if defined (ACE_HAS_THR_C_DEST) - &ACE_TSS_C_cleanup, -#else - &ACE_TSS_Guard::cleanup, -#endif /* ACE_HAS_THR_C_DEST */ - (void *) this); -} - -template -ACE_TSS_Guard::ACE_TSS_Guard (void) -{ -// ACE_TRACE ("ACE_TSS_Guard::ACE_TSS_Guard"); - this->init_key (); -} - -template int -ACE_TSS_Guard::release (void) -{ -// ACE_TRACE ("ACE_TSS_Guard::release"); - - ACE_Guard *guard = 0; - -#if defined (ACE_HAS_THR_C_DEST) - ACE_TSS_Adapter *tss_adapter = 0; - void *temp = tss_adapter; // Need this temp to keep G++ from complaining. - ACE_Thread::getspecific (this->key_, &temp); - tss_adapter = static_cast (temp); - guard = static_cast *> (tss_adapter->ts_obj_); -#else - void *temp = guard; // Need this temp to keep G++ from complaining. - ACE_Thread::getspecific (this->key_, &temp); - guard = static_cast *> (temp); -#endif /* ACE_HAS_THR_C_DEST */ - - return guard->release (); -} - -template int -ACE_TSS_Guard::remove (void) -{ -// ACE_TRACE ("ACE_TSS_Guard::remove"); - - ACE_Guard *guard = 0; - -#if defined (ACE_HAS_THR_C_DEST) - ACE_TSS_Adapter *tss_adapter = 0; - void *temp = tss_adapter; // Need this temp to keep G++ from complaining. - ACE_Thread::getspecific (this->key_, &temp); - tss_adapter = static_cast (temp); - guard = static_cast *> (tss_adapter->ts_obj_); -#else - void *temp = guard; // Need this temp to keep G++ from complaining. - ACE_Thread::getspecific (this->key_, &temp); - guard = static_cast *> (temp); -#endif /* ACE_HAS_THR_C_DEST */ - - return guard->remove (); -} - -template -ACE_TSS_Guard::~ACE_TSS_Guard (void) -{ -// ACE_TRACE ("ACE_TSS_Guard::~ACE_TSS_Guard"); - - ACE_Guard *guard = 0; - -#if defined (ACE_HAS_THR_C_DEST) - ACE_TSS_Adapter *tss_adapter = 0; - void *temp = tss_adapter; // Need this temp to keep G++ from complaining. - ACE_Thread::getspecific (this->key_, &temp); - tss_adapter = static_cast (temp); - guard = static_cast *> (tss_adapter->ts_obj_); -#else - void *temp = guard; // Need this temp to keep G++ from complaining. - ACE_Thread::getspecific (this->key_, &temp); - guard = static_cast *> (temp); -#endif /* ACE_HAS_THR_C_DEST */ - - // Make sure that this pointer is NULL when we shut down... - ACE_Thread::setspecific (this->key_, 0); - ACE_Thread::keyfree (this->key_); - // Destructor releases lock. - delete guard; -} - -template void -ACE_TSS_Guard::cleanup (void *ptr) -{ -// ACE_TRACE ("ACE_TSS_Guard::cleanup"); - - // Destructor releases lock. - delete (ACE_Guard *) ptr; -} - -template -ACE_TSS_Guard::ACE_TSS_Guard (ACE_LOCK &lock, bool block) -{ -// ACE_TRACE ("ACE_TSS_Guard::ACE_TSS_Guard"); - - this->init_key (); - ACE_Guard *guard = 0; - ACE_NEW (guard, - ACE_Guard (lock, - block)); - -#if defined (ACE_HAS_THR_C_DEST) - ACE_TSS_Adapter *tss_adapter = 0; - ACE_NEW (tss_adapter, - ACE_TSS_Adapter ((void *) guard, - ACE_TSS_Guard::cleanup)); - ACE_Thread::setspecific (this->key_, - (void *) tss_adapter); -#else - ACE_Thread::setspecific (this->key_, - (void *) guard); -#endif /* ACE_HAS_THR_C_DEST */ -} - -template int -ACE_TSS_Guard::acquire (void) -{ -// ACE_TRACE ("ACE_TSS_Guard::acquire"); - - ACE_Guard *guard = 0; - -#if defined (ACE_HAS_THR_C_DEST) - ACE_TSS_Adapter *tss_adapter = 0; - void *temp = tss_adapter; // Need this temp to keep G++ from complaining. - ACE_Thread::getspecific (this->key_, &temp); - tss_adapter = static_cast (temp); - guard = static_cast *> (tss_adapter->ts_obj_); -#else - void *temp = guard; // Need this temp to keep G++ from complaining. - ACE_Thread::getspecific (this->key_, &temp); - guard = static_cast *> (temp); -#endif /* ACE_HAS_THR_C_DEST */ - - return guard->acquire (); -} - -template int -ACE_TSS_Guard::tryacquire (void) -{ -// ACE_TRACE ("ACE_TSS_Guard::tryacquire"); - - ACE_Guard *guard = 0; - -#if defined (ACE_HAS_THR_C_DEST) - ACE_TSS_Adapter *tss_adapter = 0; - void *temp = tss_adapter; // Need this temp to keep G++ from complaining. - ACE_Thread::getspecific (this->key_, &temp); - tss_adapter = static_cast (temp); - guard = static_cast *> (tss_adapter->ts_obj_); -#else - void *temp = guard; // Need this temp to keep G++ from complaining. - ACE_Thread::getspecific (this->key_, &temp); - guard = static_cast *> (temp); -#endif /* ACE_HAS_THR_C_DEST */ - - return guard->tryacquire (); -} - -template -ACE_TSS_Write_Guard::ACE_TSS_Write_Guard (ACE_LOCK &lock, - bool block) -{ -// ACE_TRACE ("ACE_TSS_Write_Guard::ACE_TSS_Write_Guard"); - - this->init_key (); - ACE_Guard *guard = 0; - ACE_NEW (guard, - ACE_Write_Guard (lock, - block)); - -#if defined (ACE_HAS_THR_C_DEST) - ACE_TSS_Adapter *tss_adapter = 0; - ACE_NEW (tss_adapter, - ACE_TSS_Adapter ((void *) guard, - ACE_TSS_Guard::cleanup)); - ACE_Thread::setspecific (this->key_, - (void *) tss_adapter); -#else - ACE_Thread::setspecific (this->key_, - (void *) guard); -#endif /* ACE_HAS_THR_C_DEST */ -} - -template int -ACE_TSS_Write_Guard::acquire (void) -{ -// ACE_TRACE ("ACE_TSS_Write_Guard::acquire"); - - ACE_Write_Guard *guard = 0; - -#if defined (ACE_HAS_THR_C_DEST) - ACE_TSS_Adapter *tss_adapter = 0; - void *temp = tss_adapter; // Need this temp to keep G++ from complaining. - ACE_Thread::getspecific (this->key_, &temp); - tss_adapter = static_cast (temp); - guard = static_cast *> (tss_adapter->ts_obj_); -#else - void *temp = guard; // Need this temp to keep G++ from complaining. - ACE_Thread::getspecific (this->key_, &temp); - guard = static_cast *> (temp); -#endif /* ACE_HAS_THR_C_DEST */ - - return guard->acquire_write (); -} - -template int -ACE_TSS_Write_Guard::tryacquire (void) -{ -// ACE_TRACE ("ACE_TSS_Write_Guard::tryacquire"); - - ACE_Write_Guard *guard = 0; - -#if defined (ACE_HAS_THR_C_DEST) - ACE_TSS_Adapter *tss_adapter = 0; - void *temp = tss_adapter; // Need this temp to keep G++ from complaining. - ACE_Thread::getspecific (this->key_, &temp); - tss_adapter = static_cast (temp); - guard = static_cast *> (tss_adapter->ts_obj_); -#else - void *temp = guard; // Need this temp to keep G++ from complaining. - ACE_Thread::getspecific (this->key_, &temp); - guard = static_cast *> (temp); -#endif /* ACE_HAS_THR_C_DEST */ - - return guard->tryacquire_write (); -} - -template int -ACE_TSS_Write_Guard::acquire_write (void) -{ -// ACE_TRACE ("ACE_TSS_Write_Guard::acquire_write"); - - return this->acquire (); -} - -template int -ACE_TSS_Write_Guard::tryacquire_write (void) -{ -// ACE_TRACE ("ACE_TSS_Write_Guard::tryacquire_write"); - - return this->tryacquire (); -} - -template void -ACE_TSS_Write_Guard::dump (void) const -{ -#if defined (ACE_HAS_DUMP) -// ACE_TRACE ("ACE_TSS_Write_Guard::dump"); - ACE_TSS_Guard::dump (); -#endif /* ACE_HAS_DUMP */ -} - -template -ACE_TSS_Read_Guard::ACE_TSS_Read_Guard (ACE_LOCK &lock, bool block) -{ -// ACE_TRACE ("ACE_TSS_Read_Guard::ACE_TSS_Read_Guard"); - - this->init_key (); - ACE_Guard *guard = 0; - ACE_NEW (guard, - ACE_Read_Guard (lock, - block)); -#if defined (ACE_HAS_THR_C_DEST) - ACE_TSS_Adapter *tss_adapter; - ACE_NEW (tss_adapter, - ACE_TSS_Adapter ((void *)guard, - ACE_TSS_Guard::cleanup)); - ACE_Thread::setspecific (this->key_, - (void *) tss_adapter); -#else - ACE_Thread::setspecific (this->key_, - (void *) guard); -#endif /* ACE_HAS_THR_C_DEST */ -} - -template int -ACE_TSS_Read_Guard::acquire (void) -{ -// ACE_TRACE ("ACE_TSS_Read_Guard::acquire"); - - ACE_Read_Guard *guard = 0; - -#if defined (ACE_HAS_THR_C_DEST) - ACE_TSS_Adapter *tss_adapter = 0; - void *temp = tss_adapter; // Need this temp to keep G++ from complaining. - ACE_Thread::getspecific (this->key_, &temp); - tss_adapter = static_cast (temp); - guard = static_cast *> (tss_adapter->ts_obj_); -#else - void *temp = guard; // Need this temp to keep G++ from complaining. - ACE_Thread::getspecific (this->key_, &temp); - guard = static_cast *> (temp); -#endif /* ACE_HAS_THR_C_DEST */ - - return guard->acquire_read (); -} - -template int -ACE_TSS_Read_Guard::tryacquire (void) -{ -// ACE_TRACE ("ACE_TSS_Read_Guard::tryacquire"); - - ACE_Read_Guard *guard = 0; - -#if defined (ACE_HAS_THR_C_DEST) - ACE_TSS_Adapter *tss_adapter = 0; - void *temp = tss_adapter; // Need this temp to keep G++ from complaining. - ACE_Thread::getspecific (this->key_, &temp); - tss_adapter = static_cast (temp); - guard = static_cast *> (tss_adapter->ts_obj_); -#else - void *temp = guard; // Need this temp to keep G++ from complaining. - ACE_Thread::getspecific (this->key_, &temp); - guard = static_cast *> (temp); -#endif /* ACE_HAS_THR_C_DEST */ - - return guard->tryacquire_read (); -} - -template int -ACE_TSS_Read_Guard::acquire_read (void) -{ -// ACE_TRACE ("ACE_TSS_Read_Guard::acquire_read"); - - return this->acquire (); -} - -template int -ACE_TSS_Read_Guard::tryacquire_read (void) -{ -// ACE_TRACE ("ACE_TSS_Read_Guard::tryacquire_read"); - - return this->tryacquire (); -} - -template void -ACE_TSS_Read_Guard::dump (void) const -{ -#if defined (ACE_HAS_DUMP) -// ACE_TRACE ("ACE_TSS_Read_Guard::dump"); - ACE_TSS_Guard::dump (); -#endif /* ACE_HAS_DUMP */ -} - -#endif /* defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION)) */ - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_TSS_T_CPP */ diff --git a/externals/ace/TSS_T.h b/externals/ace/TSS_T.h deleted file mode 100644 index d4fa8d52974..00000000000 --- a/externals/ace/TSS_T.h +++ /dev/null @@ -1,271 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file TSS_T.h - * - * $Id: TSS_T.h 91124 2010-07-19 11:54:35Z vzykov $ - * - * Moved from Synch.h. - * - * @author Douglas C. Schmidt - */ -//========================================================================== - -#ifndef ACE_TSS_T_H -#define ACE_TSS_T_H -#include /**/ "ace/pre.h" - -#include "ace/Lock.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -// This should probably go somewhere else, but it's only used here and -// in Thread_Manager. -// Note there is no ACE_TSS_SET because one would typicaly do -// 'ACE_TSS_GET()->xyz_ = value', so the macro would have been too -// complicated. -# if defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION)) -# define ACE_TSS_TYPE(T) ACE_TSS< T > -# define ACE_TSS_GET(I, T) ((I)->operator T * ()) -# else -# define ACE_TSS_TYPE(T) T -# define ACE_TSS_GET(I, T) (I) -# endif /* ACE_HAS_THREADS && (ACE_HAS_THREAD_SPECIFIC_STORAGE || ACE_HAS_TSS_EMULATION) */ - -#include "ace/Thread_Mutex.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -#if defined (ACE_HAS_THR_C_DEST) -class ACE_TSS_Adapter; -#endif - -/** - * @class ACE_TSS - * - * @brief Allows objects that are "physically" in thread specific - * storage (i.e., private to a thread) to be accessed as though - * they were "logically" global to a program. - * - * This class helps to maintain a separate copy of an object for each thread - * that needs access to it. All threads access a single instance of ACE_TSS - * to obtain a pointer to a thread-specific copy of a TYPE object. Using - * a pointer to TYPE in TSS instead of TYPE itself is useful because, - * in addition to avoiding copies on what may be a complex class, it allows - * assignment of objects to thread-specific data that have arbitrarily - * complex constructors. - * - * When the ACE_TSS object is destroyed, all threads's instances of the - * data are deleted. - * - * Modern compilers have no problem using a built-in type for @c TYPE. - * However, if you must use an older compiler that won't work with a built-in - * type, the ACE_TSS_Type_Adapter class template, below, can be used for - * adapting built-in types to work with ACE_TSS. - * - * @note Beware when creating static instances of this type - * (as with any other, btw). The unpredictable order of initialization - * across different platforms may cause a situation where one uses - * the instance before it is fully initialized. That's why typically - * instances of this type are dynamicaly allocated. On the stack it is - * typically allocated inside the ACE_Thread::svc() method which - * limits its lifetime appropriately. - * - */ -template -class ACE_TSS -{ -public: - /** - * Default constructor. Can also initialize this ACE_TSS instance, - * readying it for use by the calling thread as well as all other - * threads in the process. If the constructor does not initialize this - * object, the first access to it will perform the initialization, which - * could possibly (under odd error conditions) fail. - * - * @param ts_obj If non-zero, this object is initialized for use by - * all threads and @a ts_obj is used to set the - * thread-specific value for the calling thread. Other - * threads use the ts_object (TYPE *) method to set - * a specific value. - */ - ACE_TSS (TYPE *ts_obj = 0); - - /// Deregister this object from thread-specific storage administration. - /// Will cause all threads' copies of TYPE to be destroyed. - virtual ~ACE_TSS (void); - - /** - * Set the thread-specific object for the calling thread. - * If this object has not been initialized yet, this method performs the - * initialization. - * - * @param new_ts_obj The new value for the calling thread's copy of - * this object. - * - * @return The previous value of the calling thread's copy of this - * object; 0 if there was no previous value. This method also - * returns 0 on errors. To tell the difference between an error - * and a returned 0 pointer, it's recommended that one set errno - * to 0 prior to calling ts_object() and check for a new errno - * value if ts_object() returns 0. - */ - TYPE *ts_object (TYPE *new_ts_obj); - - /** @name Accessors - * - * All accessors return a pointer to the calling thread's copy of the - * TYPE data. The pointer may be 0 on error conditions or if the calling - * thread's copy of the data has not yet been set. See specific method - * descriptions for complete details. - */ - //@{ - /** - * Get the thread-specific object for this object. - * - * @return 0 if the object has never been initialized, otherwise returns - * the calling thread's copy of the data. The returned pointer - * may be 0 under odd error conditions; check errno for further - * information. - */ - TYPE *ts_object (void) const; - - /** - * Use a "smart pointer" to get the thread-specific data associated - * with this object. - * If this ACE_TSS object hasn't been initialized, this method - * will initialize it as a side-affect. If the calling thread has not - * set a value, a default-constructed instance of TYPE is allocated and it - * becomes the thread's instance. - * - * @return The calling thread's copy of the data. The returned pointer - * may be 0 under odd error conditions; check errno for further - * information. - */ - TYPE *operator-> () const; - - /** - * Obtain a pointer to the calling thread's TYPE object. - * If this ACE_TSS object hasn't been initialized, this method - * will initialize it as a side-affect. If the calling thread has not - * set a value, a default-constructed instance of TYPE is allocated and it - * becomes the thread's instance. - * - * @return The calling thread's copy of the data. The returned pointer - * may be 0 under odd error conditions; check errno for further - * information. - */ - operator TYPE *(void) const; - - //@} - - /// Hook for construction parameters. - virtual TYPE *make_TSS_TYPE (void) const; - - // = Utility methods. - - /// Dump the state of an object. - void dump (void) const; - - // ACE_ALLOC_HOOK_DECLARE; - // Declare the dynamic allocation hooks. - -protected: - /// Actually implements the code that retrieves the object from - /// thread-specific storage. - TYPE *ts_get (void) const; - - /// Factors out common code for initializing TSS. This must NOT be - /// called with the lock held... - int ts_init (void); - -#if !(defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION))) - /// This implementation only works for non-threading systems... - TYPE *type_; -#else - /// Avoid race conditions during initialization. - ACE_Thread_Mutex keylock_; - - /// "First time in" flag. - volatile bool once_; - - /// Key for the thread-specific error data. - ACE_thread_key_t key_; - - /// "Destructor" that deletes internal TYPE * when thread exits. - static void cleanup (void *ptr); - - /// Obtains a plain value stored in the thread-specific storage. -# if defined (ACE_HAS_THR_C_DEST) - ACE_TSS_Adapter *ts_value (void) const; -# else - TYPE *ts_value (void) const; -# endif /* ACE_HAS_THR_C_DEST */ - - /// Stores a new plain value in the thread-specific storage. -# if defined (ACE_HAS_THR_C_DEST) - int ts_value (ACE_TSS_Adapter *new_tss_adapter) const; -# else - int ts_value (TYPE *new_ts_obj) const; -# endif /* ACE_HAS_THR_C_DEST */ -#endif /* defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION)) */ - // = Disallow copying... - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_TSS &)) - ACE_UNIMPLEMENTED_FUNC (ACE_TSS (const ACE_TSS &)) -}; - -/** - * @class ACE_TSS_Type_Adapter - * - * @brief Adapter that allows built-in types to be used with ACE_TSS. - * - * Wraps a value of a built-in type, providing conversions to - * and from the type. Example use with ACE_TSS: - * ACE_TSS > i; - * *i = 37; - * ACE_OS::fprintf (stderr, "%d\n", *i); - * Unfortunately, though, some compilers have trouble with the - * implicit type conversions. This seems to work better: - * ACE_TSS > i; - * i->operator int & () = 37; - * ACE_OS::fprintf (stderr, "%d\n", i->operator int ()); - */ -template -class ACE_TSS_Type_Adapter -{ -public: - /// Constructor. Inlined here so that it should _always_ be inlined. - ACE_TSS_Type_Adapter (const TYPE value = 0): value_ (value) {} - - /// TYPE conversion. Inlined here so that it should _always_ be - /// inlined. - operator TYPE () const { return value_; }; - - /// TYPE & conversion. Inlined here so that it should _always_ be - /// inlined. - operator TYPE &() { return value_; }; - -private: - /// The wrapped value. - TYPE value_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/TSS_T.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/TSS_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("TSS_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" -#endif /* ACE_TSS_T_H */ diff --git a/externals/ace/TSS_T.inl b/externals/ace/TSS_T.inl deleted file mode 100644 index 16c7b5de487..00000000000 --- a/externals/ace/TSS_T.inl +++ /dev/null @@ -1,103 +0,0 @@ -// -*- C++ -*- -// -// $Id: TSS_T.inl 91124 2010-07-19 11:54:35Z vzykov $ - -#include "ace/Thread.h" -#include "ace/Log_Msg.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -#if !(defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION))) - -template ACE_INLINE -ACE_TSS::ACE_TSS (TYPE *type) - : type_ (type) -{ -} - -template ACE_INLINE int -ACE_TSS::ts_init (void) -{ - return 0; -} - -template ACE_INLINE TYPE * -ACE_TSS::ts_object (void) const -{ - return this->type_; -} - -template ACE_INLINE TYPE * -ACE_TSS::ts_object (TYPE *type) -{ - this->type_ = type; - return this->type_; -} - -template ACE_INLINE TYPE * -ACE_TSS::ts_get (void) const -{ - return this->type_; -} - -#else - -# if defined (ACE_HAS_THR_C_DEST) -template ACE_INLINE ACE_TSS_Adapter * -ACE_TSS::ts_value (void) const -{ - // Get the tss adapter from thread-specific storage - void *temp = 0; - if (ACE_Thread::getspecific (this->key_, &temp) == -1) - { - return 0; // This should not happen! - } - return static_cast (temp); -} -# else -template ACE_INLINE TYPE * -ACE_TSS::ts_value (void) const -{ - void *temp = 0; - if (ACE_Thread::getspecific (this->key_, &temp) == -1) - { - return 0; // This should not happen! - } - return static_cast (temp); -} -# endif /* ACE_HAS_THR_C_DEST */ - -# if defined (ACE_HAS_THR_C_DEST) -template ACE_INLINE int -ACE_TSS::ts_value (ACE_TSS_Adapter *new_tss_adapter) const -{ - if (ACE_Thread::setspecific (this->key_, - (void *) new_tss_adapter) != 0) - { - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_Thread::setspecific() failed!"))); - return -1; - } - - return 0; -} -# else -template ACE_INLINE int -ACE_TSS::ts_value (TYPE *new_ts_obj) const -{ - if (ACE_Thread::setspecific (this->key_, (void *) new_ts_obj) != 0) - { - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_Thread::setspecific() failed!"))); - return -1; - } - - return 0; -} -# endif /* ACE_HAS_THR_C_DEST */ - -#endif /* ! (defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION))) */ - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/TTY_IO.cpp b/externals/ace/TTY_IO.cpp deleted file mode 100644 index 6d5be6f2c38..00000000000 --- a/externals/ace/TTY_IO.cpp +++ /dev/null @@ -1,705 +0,0 @@ -// $Id: TTY_IO.cpp 86739 2009-09-21 07:33:22Z olli $ - -#include "ace/TTY_IO.h" -#include "ace/OS_NS_errno.h" -#include "ace/OS_NS_string.h" -#include "ace/OS_NS_strings.h" - -#if defined (ACE_HAS_TERMIOS) -# include "ace/os_include/os_termios.h" -#elif defined (ACE_HAS_TERMIO) -# include -#endif - -ACE_RCSID (ace, - TTY_IO, - "$Id: TTY_IO.cpp 86739 2009-09-21 07:33:22Z olli $") - -namespace -{ - const char ACE_TTY_IO_NONE[] = "none"; -#if defined (ACE_HAS_TERMIOS) || defined (ACE_HAS_TERMIO) || defined (ACE_WIN32) - const char ACE_TTY_IO_ODD[] = "odd"; - const char ACE_TTY_IO_EVEN[] = "even"; -#endif -#if defined (ACE_WIN32) - const char ACE_TTY_IO_MARK[] = "mark"; - const char ACE_TTY_IO_SPACE[] = "space"; -#endif /* ACE_WIN32 */ -} - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_TTY_IO::Serial_Params::Serial_Params (void) -{ - baudrate = 9600; - xonlim = 0; - xofflim = 0; - readmincharacters = 0; - readtimeoutmsec = 10000; - paritymode = ACE_TTY_IO_NONE; - ctsenb = false; - rtsenb = 0; - xinenb = false; - xoutenb = false; - modem = false; - rcvenb = true; - dsrenb = false; - dtrdisable = false; - databits = 8; - stopbits = 1; -} - -// Interface for reading/writing serial device parameters - -int ACE_TTY_IO::control (Control_Mode cmd, Serial_Params *arg) const -{ -#if defined (ACE_HAS_TERMIOS) || defined (ACE_HAS_TERMIO) - -#if defined (ACE_HAS_TERMIOS) - struct termios devpar; - speed_t newbaudrate = 0; - if (tcgetattr (get_handle () , &devpar) == -1) -#elif defined (TCGETS) - struct termios devpar; - unsigned int newbaudrate = 0; - if (this->ACE_IO_SAP::control (TCGETS, static_cast(&devpar)) == -1) -#elif defined (TCGETA) - struct termio devpar; - unsigned int newbaudrate = 0; - if (this->ACE_IO_SAP::control (TCGETA, static_cast(&devpar)) == -1) -#else - errno = ENOSYS; -#endif /* ACE_HAS_TERMIOS */ - return -1; - - switch (cmd) - { - case SETPARAMS: - switch (arg->baudrate) - { -#if defined (B0) - case 0: newbaudrate = B0; break; -#endif /* B0 */ -#if defined (B50) - case 50: newbaudrate = B50; break; -#endif /* B50 */ -#if defined (B75) - case 75: newbaudrate = B75; break; -#endif /* B75 */ -#if defined (B110) - case 110: newbaudrate = B110; break; -#endif /* B110 */ -#if defined (B134) - case 134: newbaudrate = B134; break; -#endif /* B134 */ -#if defined (B150) - case 150: newbaudrate = B150; break; -#endif /* B150 */ -#if defined (B200) - case 200: newbaudrate = B200; break; -#endif /* B200 */ -#if defined (B300) - case 300: newbaudrate = B300; break; -#endif /* B300 */ -#if defined (B600) - case 600: newbaudrate = B600; break; -#endif /* B600 */ -#if defined (B1200) - case 1200: newbaudrate = B1200; break; -#endif /* B1200 */ -#if defined (B1800) - case 1800: newbaudrate = B1800; break; -#endif /* B1800 */ -#if defined (B2400) - case 2400: newbaudrate = B2400; break; -#endif /* B2400 */ -#if defined (B4800) - case 4800: newbaudrate = B4800; break; -#endif /* B4800 */ -#if defined (B9600) - case 9600: newbaudrate = B9600; break; -#endif /* B9600 */ -#if defined (B19200) - case 19200: newbaudrate = B19200; break; -#endif /* B19200 */ -#if defined (B38400) - case 38400: newbaudrate = B38400; break; -#endif /* B38400 */ -#if defined (B56000) - case 56000: newbaudrate = B56000; break; -#endif /* B56000 */ -#if defined (B57600) - case 57600: newbaudrate = B57600; break; -#endif /* B57600 */ -#if defined (B76800) - case 76800: newbaudrate = B76800; break; -#endif /* B76800 */ -#if defined (B115200) - case 115200: newbaudrate = B115200; break; -#endif /* B115200 */ -#if defined (B128000) - case 128000: newbaudrate = B128000; break; -#endif /* B128000 */ -#if defined (B153600) - case 153600: newbaudrate = B153600; break; -#endif /* B153600 */ -#if defined (B230400) - case 230400: newbaudrate = B230400; break; -#endif /* B230400 */ -#if defined (B307200) - case 307200: newbaudrate = B307200; break; -#endif /* B307200 */ -#if defined (B256000) - case 256000: newbaudrate = B256000; break; -#endif /* B256000 */ -#if defined (B460800) - case 460800: newbaudrate = B460800; break; -#endif /* B460800 */ -#if defined (B500000) - case 500000: newbaudrate = B500000; break; -#endif /* B500000 */ -#if defined (B576000) - case 576000: newbaudrate = B576000; break; -#endif /* B576000 */ -#if defined (B921600) - case 921600: newbaudrate = B921600; break; -#endif /* B921600 */ -#if defined (B1000000) - case 1000000: newbaudrate = B1000000; break; -#endif /* B1000000 */ -#if defined (B1152000) - case 1152000: newbaudrate = B1152000; break; -#endif /* B1152000 */ -#if defined (B1500000) - case 1500000: newbaudrate = B1500000; break; -#endif /* B1500000 */ -#if defined (B2000000) - case 2000000: newbaudrate = B2000000; break; -#endif /* B2000000 */ -#if defined (B2500000) - case 2500000: newbaudrate = B2500000; break; -#endif /* B2500000 */ -#if defined (B3000000) - case 3000000: newbaudrate = B3000000; break; -#endif /* B3000000 */ -#if defined (B3500000) - case 3500000: newbaudrate = B3500000; break; -#endif /* B3500000 */ -#if defined (B4000000) - case 4000000: newbaudrate = B4000000; break; -#endif /* B4000000 */ - default: - return -1; - } - -#if defined (ACE_HAS_TERMIOS) - // Can you really have different input and output baud rates?! - if (cfsetospeed (&devpar, newbaudrate) == -1) - return -1; - if (cfsetispeed (&devpar, newbaudrate) == -1) - return -1; -#else - devpar.c_cflag &= ~CBAUD; -# if defined (CBAUDEX) - devpar.c_cflag &= ~CBAUDEX; -# endif /* CBAUDEX */ - devpar.c_cflag |= newbaudrate; -#endif /* ACE_HAS_TERMIOS */ - - devpar.c_cflag &= ~CSIZE; - switch (arg->databits) - { - case 5: - devpar.c_cflag |= CS5; - break; - case 6: - devpar.c_cflag |= CS6; - break; - case 7: - devpar.c_cflag |= CS7; - break; - case 8: - devpar.c_cflag |= CS8; - break; - default: - return -1; - } - - switch (arg->stopbits) - { - case 1: - devpar.c_cflag &= ~CSTOPB; - break; - case 2: - devpar.c_cflag |= CSTOPB; - break; - default: - return -1; - } - - if (arg->paritymode) - { - if (ACE_OS::strcasecmp (arg->paritymode, ACE_TTY_IO_ODD) == 0) - { - devpar.c_cflag |= PARENB; - devpar.c_cflag |= PARODD; - } - else if (ACE_OS::strcasecmp (arg->paritymode, ACE_TTY_IO_EVEN) == 0) - { - devpar.c_cflag |= PARENB; - devpar.c_cflag &= ~PARODD; - } - else if (ACE_OS::strcasecmp (arg->paritymode, ACE_TTY_IO_NONE) == 0) - devpar.c_cflag &= ~PARENB; - else - return -1; - } - else - { - devpar.c_cflag &= ~PARENB; - } - -#if defined (CNEW_RTSCTS) - if ((arg->ctsenb) || (arg->rtsenb)) // Enable RTS/CTS protocol - devpar.c_cflag |= CNEW_RTSCTS; - else - devpar.c_cflag &= ~CNEW_RTSCTS; -#elif defined (CRTSCTS) - if ((arg->ctsenb) || (arg->rtsenb)) // Enable RTS/CTS protocol - devpar.c_cflag |= CRTSCTS; - else - devpar.c_cflag &= ~CRTSCTS; -#endif /* NEW_RTSCTS || CRTSCTS */ - -#if defined (CREAD) - // Enable/disable receiver - if (arg->rcvenb) - devpar.c_cflag |= CREAD; - else - devpar.c_cflag &= ~CREAD; -#endif /* CREAD */ - -#if defined (HUPCL) - // Cause DTR to drop after port close. - devpar.c_cflag |= HUPCL; -#endif /* HUPCL */ - -#if defined (CLOCAL) - // If device is not a modem set to local device. - if (arg->modem) - devpar.c_cflag &= ~CLOCAL; - else - devpar.c_cflag |= CLOCAL; -#endif /* CLOCAL */ - - devpar.c_iflag = IGNPAR | INPCK; - if (arg->databits < 8) - devpar.c_iflag |= ISTRIP; - -#if defined (IGNBRK) - // If device is not a modem set to ignore break points - if(arg->modem) - devpar.c_iflag &= ~IGNBRK; - else - devpar.c_iflag |= IGNBRK; -#endif /* IGNBRK */ - -#if defined (IXOFF) - // Enable/disable software flow control on input - if (arg->xinenb) - devpar.c_iflag |= IXOFF; - else - devpar.c_iflag &= ~IXOFF; -#endif /* IXOFF */ - -#if defined (IXON) - // Enable/disable software flow control on output - if (arg->xoutenb) - devpar.c_iflag |= IXON; - else - devpar.c_iflag &= ~IXON; -#endif /* IXON */ - -#if defined (ICANON) - // Enable noncanonical input processing mode - devpar.c_lflag &= ~ICANON; -#endif /* ICANON */ - -#if defined (ECHO) - // Disable echoing of input characters - devpar.c_lflag &= ~ECHO; -#endif /* ECHO */ - -#if defined (ECHOE) - // Disable echoing erase chareacter as BS-SP-BS - devpar.c_lflag &= ~ECHOE; -#endif /* ECHOE */ - -#if defined (ISIG) - // Disable SIGINTR, SIGSUSP, SIGDSUSP and SIGQUIT signals - devpar.c_lflag &= ~ISIG; -#endif /* ISIG */ - -#if defined (OPOST) - // Disable post-processing of output data - devpar.c_oflag &= ~OPOST; -#endif /* OPOST */ - - if (arg->readtimeoutmsec < 0) - { - // Settings for infinite timeout. - devpar.c_cc[VTIME] = 0; - // In case of infinite timeout [VMIN] must be at least 1. - if (arg->readmincharacters > UCHAR_MAX) - devpar.c_cc[VMIN] = UCHAR_MAX; - else if (arg->readmincharacters < 1) - devpar.c_cc[VMIN] = 1; - else - devpar.c_cc[VMIN] = static_cast(arg->readmincharacters); - } - else - { - devpar.c_cc[VTIME] = static_cast(arg->readtimeoutmsec / 100); - - if (arg->readmincharacters > UCHAR_MAX) - devpar.c_cc[VMIN] = UCHAR_MAX; - else if (arg->readmincharacters < 1) - devpar.c_cc[VMIN] = 0; - else - devpar.c_cc[VMIN] = static_cast(arg->readmincharacters); - } - -#if defined (TIOCMGET) - int status; - this->ACE_IO_SAP::control (TIOCMGET, &status); - - if (arg->dtrdisable) - status &= ~TIOCM_DTR; - else - status |= TIOCM_DTR; - - this->ACE_IO_SAP::control (TIOCMSET, &status); -#endif /* definded (TIOCMGET) */ - -#if defined (ACE_HAS_TERMIOS) - return tcsetattr (get_handle (), TCSANOW, &devpar); -#elif defined (TCSETS) - return this->ACE_IO_SAP::control (TCSETS, static_cast(&devpar)); -#elif defined (TCSETA) - return this->ACE_IO_SAP::control (TCSETA, static_cast(&devpar)); -#else - errno = ENOSYS; - return -1; -#endif /* ACE_HAS_TERMIOS */ - - case GETPARAMS: - return -1; // Not yet implemented. - default: - return -1; // Wrong cmd. - } -#elif defined (ACE_WIN32) - DCB dcb; - dcb.DCBlength = sizeof dcb; - if (!::GetCommState (this->get_handle (), &dcb)) - { - ACE_OS::set_errno_to_last_error (); - return -1; - } - - COMMTIMEOUTS timeouts; - if (!::GetCommTimeouts (this->get_handle(), &timeouts)) - { - ACE_OS::set_errno_to_last_error (); - return -1; - } - - switch (cmd) - { - case SETPARAMS: - dcb.BaudRate = arg->baudrate; - - switch (arg->databits) - { - case 4: - case 5: - case 6: - case 7: - case 8: - dcb.ByteSize = arg->databits; - break; - default: - return -1; - } - - switch (arg->stopbits) - { - case 1: - dcb.StopBits = ONESTOPBIT; - break; - case 2: - dcb.StopBits = TWOSTOPBITS; - break; - default: - return -1; - } - - if (arg->paritymode) - { - dcb.fParity = TRUE; - if (ACE_OS::strcasecmp (arg->paritymode, ACE_TTY_IO_ODD) == 0) - dcb.Parity = ODDPARITY; - else if (ACE_OS::strcasecmp (arg->paritymode, ACE_TTY_IO_EVEN) == 0) - dcb.Parity = EVENPARITY; - else if (ACE_OS::strcasecmp (arg->paritymode, ACE_TTY_IO_NONE) == 0) - dcb.Parity = NOPARITY; - else if (ACE_OS::strcasecmp (arg->paritymode, ACE_TTY_IO_MARK) == 0) - dcb.Parity = MARKPARITY; - else if (ACE_OS::strcasecmp (arg->paritymode, ACE_TTY_IO_SPACE) == 0) - dcb.Parity = SPACEPARITY; - else - return -1; - } - else - { - dcb.fParity = FALSE; - dcb.Parity = NOPARITY; - } - - // Enable/disable RTS protocol. - switch (arg->rtsenb) - { - case 1: - dcb.fRtsControl = RTS_CONTROL_ENABLE; - break; - case 2: - dcb.fRtsControl = RTS_CONTROL_HANDSHAKE; - break; - case 3: - dcb.fRtsControl = RTS_CONTROL_TOGGLE; - break; - default: - dcb.fRtsControl = RTS_CONTROL_DISABLE; - } - - // Enable/disable CTS protocol. - if (arg->ctsenb) - dcb.fOutxCtsFlow = TRUE; - else - dcb.fOutxCtsFlow = FALSE; - - // Enable/disable DSR protocol. - if (arg->dsrenb) - dcb.fOutxDsrFlow = TRUE; - else - dcb.fOutxDsrFlow = FALSE; - - // Disable/enable DTR protocol - if (arg->dtrdisable) - dcb.fDtrControl = DTR_CONTROL_DISABLE; - else - dcb.fDtrControl = DTR_CONTROL_ENABLE; - - // Enable/disable software flow control on input - if (arg->xinenb) - dcb.fInX = TRUE; - else - dcb.fInX = FALSE; - - // Enable/disable software flow control on output - if (arg->xoutenb) - dcb.fOutX = TRUE; - else - dcb.fOutX = FALSE; - - // Always set limits unless set to negative to use default. - if (arg->xonlim >= 0) - dcb.XonLim = static_cast(arg->xonlim); - if (arg->xofflim >= 0) - dcb.XoffLim = static_cast(arg->xofflim); - - dcb.fAbortOnError = FALSE; - dcb.fErrorChar = FALSE; - dcb.fNull = FALSE; - dcb.fBinary = TRUE; - - if (!::SetCommState (this->get_handle (), &dcb)) - { - ACE_OS::set_errno_to_last_error (); - return -1; - } - - if (arg->readtimeoutmsec < 0) - { - // Settings for infinite timeout. - timeouts.ReadIntervalTimeout = 0; - timeouts.ReadTotalTimeoutMultiplier = 0; - timeouts.ReadTotalTimeoutConstant = 0; - } - else if (arg->readtimeoutmsec == 0) - { - // Return immediately if no data in the input buffer. - timeouts.ReadIntervalTimeout = MAXDWORD; - timeouts.ReadTotalTimeoutMultiplier = 0; - timeouts.ReadTotalTimeoutConstant = 0; - } - else - { - // Wait for specified timeout for char to arrive before returning. - timeouts.ReadIntervalTimeout = MAXDWORD; - timeouts.ReadTotalTimeoutMultiplier = MAXDWORD; - timeouts.ReadTotalTimeoutConstant = arg->readtimeoutmsec; - } - - if (!::SetCommTimeouts (this->get_handle (), &timeouts)) - { - ACE_OS::set_errno_to_last_error (); - return -1; - } - - return 0; - - case GETPARAMS: - arg->baudrate = dcb.BaudRate; - - switch (dcb.ByteSize) - { - case 4: - case 5: - case 6: - case 7: - case 8: - arg->databits = dcb.ByteSize; - break; - default: - return -1; - } - - switch (dcb.StopBits) - { - case ONESTOPBIT: - arg->stopbits = 1; - break; - case TWOSTOPBITS: - arg->stopbits = 2; - break; - default: - return -1; - } - - if (!dcb.fParity) - { - arg->paritymode = ACE_TTY_IO_NONE; - } - else - { - switch (dcb.Parity) - { - case ODDPARITY: - arg->paritymode = ACE_TTY_IO_ODD; - break; - case EVENPARITY: - arg->paritymode = ACE_TTY_IO_EVEN; - break; - case NOPARITY: - arg->paritymode = ACE_TTY_IO_NONE; - break; - case MARKPARITY: - arg->paritymode = ACE_TTY_IO_MARK; - break; - case SPACEPARITY: - arg->paritymode = ACE_TTY_IO_SPACE; - break; - default: - return -1; - } - } - - // Enable/disable RTS protocol. - switch (dcb.fRtsControl) - { - case RTS_CONTROL_ENABLE: - arg->rtsenb = 1; - break; - case RTS_CONTROL_HANDSHAKE: - arg->rtsenb = 2; - break; - case RTS_CONTROL_TOGGLE: - arg->rtsenb = 3; - break; - case RTS_CONTROL_DISABLE: - arg->rtsenb = 0; - break; - default: - return -1; - } - - // Enable/disable CTS protocol. - if (dcb.fOutxCtsFlow) - arg->ctsenb = true; - else - arg->ctsenb = false; - - // Enable/disable DSR protocol. - if (dcb.fOutxDsrFlow) - arg->dsrenb = true; - else - arg->dsrenb = false; - - // Disable/enable DTR protocol - // Attention: DTR_CONTROL_HANDSHAKE is not supported. - switch (dcb.fDtrControl) - { - case DTR_CONTROL_DISABLE: - arg->dtrdisable = true; - break; - case DTR_CONTROL_ENABLE: - arg->dtrdisable = false; - break; - default: - return -1; - } - - // Enable/disable software flow control on input - if (dcb.fInX) - arg->xinenb = true; - else - arg->xinenb = false; - - // Enable/disable software flow control on output - if (dcb.fOutX) - arg->xoutenb = true; - else - arg->xoutenb = false; - - arg->xonlim = static_cast(dcb.XonLim); - arg->xofflim = static_cast(dcb.XoffLim); - - if (timeouts.ReadIntervalTimeout == 0 && - timeouts.ReadTotalTimeoutMultiplier == 0 && - timeouts.ReadTotalTimeoutConstant == 0) - arg->readtimeoutmsec = -1; - else - arg->readtimeoutmsec = timeouts.ReadTotalTimeoutConstant; - - return 0; - - default: - return -1; // Wrong cmd. - - } // arg switch -#else - ACE_UNUSED_ARG (cmd); - ACE_UNUSED_ARG (arg); - ACE_NOTSUP_RETURN (-1); -#endif /* ACE_HAS_TERMIOS || ACE_HAS_TERMIO */ -} - -#if defined (ACE_NEEDS_DEV_IO_CONVERSION) -ACE_TTY_IO::operator ACE_DEV_IO &() -{ - return static_cast(*this); -} -#endif /* ACE_NEEDS_DEV_IO_CONVERSION */ - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/TTY_IO.h b/externals/ace/TTY_IO.h deleted file mode 100644 index 1029966e56c..00000000000 --- a/externals/ace/TTY_IO.h +++ /dev/null @@ -1,113 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file TTY_IO.h - * - * $Id: TTY_IO.h 82271 2008-07-09 09:23:03Z olli $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_TTY_IO_H -#define ACE_TTY_IO_H - -#include "ace/DEV_IO.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_TTY_IO - * - * @brief Class definitions for platform specific TTY features. - * - * This class represents an example interface for a specific - * device (a serial line). It extends the capability of the - * underlying DEV_IO class by adding a control method that takes - * a special structure (Serial_Params) as argument to allow a - * comfortable user interface (away from that annoying termios - * structure, which is very specific to UNIX). - */ -class ACE_Export ACE_TTY_IO : public ACE_DEV_IO -{ -public: - enum Control_Mode - { - SETPARAMS, ///< Set control parameters. - GETPARAMS ///< Get control parameters. - }; - - struct ACE_Export Serial_Params - { - Serial_Params (void); - - /** Specifies the baudrate at which the communnication port operates. */ - int baudrate; - /** Specifies the minimum number of bytes in input buffer before XON char - is sent. Negative value indicates that default value should - be used (Win32). */ - int xonlim; - /** Specifies the maximum number of bytes in input buffer before XOFF char - is sent. Negative value indicates that default value should - be used (Win32). */ - int xofflim; - /** Specifies the minimum number of characters for non-canonical - read (POSIX). */ - unsigned int readmincharacters; - /** Specifies the time to wait before returning from read. Negative value - means infinite timeout. */ - int readtimeoutmsec; - /** Specifies the parity mode. POSIX supports "none", "even" and - "odd" parity. Additionally Win32 supports "mark" and "space" - parity modes. */ - const char *paritymode; - /** Enable & set CTS mode. Note that RTS & CTS are enabled/disabled - together on some systems (RTS/CTS is enabled if either - ctsenb or rtsenb is set). */ - bool ctsenb; - /** Enable & set RTS mode. Note that RTS & CTS are enabled/disabled - together on some systems (RTS/CTS is enabled if either - ctsenb or rtsenb is set). - - 0 = Disable RTS. - - 1 = Enable RTS. - - 2 = Enable RTS flow-control handshaking (Win32). - - 3 = Specifies that RTS line will be high if bytes are available - for transmission. After transmission RTS will be low (Win32). */ - unsigned char rtsenb; - /** Enable/disable software flow control on input. */ - bool xinenb; - /** Enable/disable software flow control on output. */ - bool xoutenb; - /** Specifies if device is a modem (POSIX). If not set modem status - lines are ignored. */ - bool modem; - /** Enable/disable receiver (POSIX). */ - bool rcvenb; - /** Controls whether DSR is disabled or enabled (Win32). */ - bool dsrenb; - /** Controls whether DTR is disabled or enabled. */ - bool dtrdisable; - /** Data bits. Valid values 5, 6, 7 and 8 data bits. - Additionally Win32 supports 4 data bits. */ - unsigned char databits; - /** Stop bits. Valid values are 1 and 2. */ - unsigned char stopbits; - }; - - /** Interface for reading/writing serial device parameters. */ - int control (Control_Mode cmd, Serial_Params *arg) const; - -#if defined (ACE_NEEDS_DEV_IO_CONVERSION) - /** This is necessary to pass ACE_TTY_IO as parameter to DEV_Connector. */ - operator ACE_DEV_IO &(); -#endif /* ACE_NEEDS_DEV_IO_CONVERSION */ -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_TTY_IO_H */ diff --git a/externals/ace/Task.cpp b/externals/ace/Task.cpp deleted file mode 100644 index b3d8aad7a86..00000000000 --- a/externals/ace/Task.cpp +++ /dev/null @@ -1,299 +0,0 @@ -// $Id: Task.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Task.h" -#include "ace/Module.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Task.inl" -#endif /* __ACE_INLINE__ */ - - -ACE_RCSID (ace, - Task, - "$Id: Task.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_Task_Base::ACE_Task_Base (ACE_Thread_Manager *thr_man) - : thr_count_ (0), - thr_mgr_ (thr_man), - flags_ (0), - grp_id_ (-1) -#if !(defined (ACE_MVS) || defined(__TANDEM)) - ,last_thread_id_ (0) -#endif /* !defined (ACE_MVS) */ -{ -#if (defined (ACE_MVS) || defined(__TANDEM)) - ACE_OS::memset( &this->last_thread_id_, '\0', sizeof( this->last_thread_id_ )); -#endif /* defined (ACE_MVS) */ -} - -ACE_Task_Base::~ACE_Task_Base (void) -{ -} - -// Default ACE_Task service routine - -int -ACE_Task_Base::svc (void) -{ - ACE_TRACE ("ACE_Task_Base::svc"); - return 0; -} - -// Default ACE_Task open routine - -int -ACE_Task_Base::open (void *) -{ - ACE_TRACE ("ACE_Task_Base::open"); - return 0; -} - -// Default ACE_Task close routine - -int -ACE_Task_Base::close (u_long) -{ - ACE_TRACE ("ACE_Task_Base::close"); - return 0; -} - -// Forward the call to close() so that existing applications don't -// break. - -int -ACE_Task_Base::module_closed (void) -{ - return this->close (1); -} - -// Default ACE_Task put routine. - -int -ACE_Task_Base::put (ACE_Message_Block *, ACE_Time_Value *) -{ - ACE_TRACE ("ACE_Task_Base::put"); - return 0; -} - -// Wait for all threads running in a task to exit. - -int -ACE_Task_Base::wait (void) -{ - ACE_TRACE ("ACE_Task_Base::wait"); - - // If we don't have a thread manager, we probably were never - // activated. - if (this->thr_mgr () != 0) - return this->thr_mgr ()->wait_task (this); - else - return 0; -} - -// Suspend a task. -int -ACE_Task_Base::suspend (void) -{ - ACE_TRACE ("ACE_Task_Base::suspend"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - if (this->thr_count_ > 0) - return this->thr_mgr_->suspend_task (this); - - return 0; -} - -// Resume a suspended task. -int -ACE_Task_Base::resume (void) -{ - ACE_TRACE ("ACE_Task_Base::resume"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - if (this->thr_count_ > 0) - return this->thr_mgr_->resume_task (this); - - return 0; -} - -int -ACE_Task_Base::activate (long flags, - int n_threads, - int force_active, - long priority, - int grp_id, - ACE_Task_Base *task, - ACE_hthread_t thread_handles[], - void *stack[], - size_t stack_size[], - ACE_thread_t thread_ids[], - const char* thr_name[]) -{ - ACE_TRACE ("ACE_Task_Base::activate"); - -#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) - ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1); - - // If the task passed in is zero, we will use - if (task == 0) - task = this; - - if (this->thr_count_ > 0 && force_active == 0) - return 1; // Already active. - else - { - if (this->thr_count_ > 0 && this->grp_id_ != -1) - // If we're joining an existing group of threads then make - // sure to use its group id. - grp_id = this->grp_id_; - this->thr_count_ += n_threads; - } - - // Use the ACE_Thread_Manager singleton if we're running as an - // active object and the caller didn't supply us with a - // Thread_Manager. - if (this->thr_mgr_ == 0) -# if defined (ACE_THREAD_MANAGER_LACKS_STATICS) - this->thr_mgr_ = ACE_THREAD_MANAGER_SINGLETON::instance (); -# else /* ! ACE_THREAD_MANAGER_LACKS_STATICS */ - this->thr_mgr_ = ACE_Thread_Manager::instance (); -# endif /* ACE_THREAD_MANAGER_LACKS_STATICS */ - - int grp_spawned = -1; - if (thread_ids == 0) - // Thread Ids were not specified - grp_spawned = - this->thr_mgr_->spawn_n (n_threads, - &ACE_Task_Base::svc_run, - (void *) this, - flags, - priority, - grp_id, - task, - thread_handles, - stack, - stack_size, - thr_name); - else - // thread names were specified - grp_spawned = - this->thr_mgr_->spawn_n (thread_ids, - n_threads, - &ACE_Task_Base::svc_run, - (void *) this, - flags, - priority, - grp_id, - stack, - stack_size, - thread_handles, - task, - thr_name); - if (grp_spawned == -1) - { - // If spawn_n fails, restore original thread count. - this->thr_count_ -= n_threads; - return -1; - } - - if (this->grp_id_ == -1) - this->grp_id_ = grp_spawned; - -#if defined (ACE_MVS) || defined(__TANDEM) - ACE_OS::memcpy( &this->last_thread_id_, '\0', sizeof(this->last_thread_id_)); -#else - this->last_thread_id_ = 0; // Reset to prevent inadvertant match on ID -#endif /* defined (ACE_MVS) */ - - return 0; - -#else - { - // Keep the compiler from complaining. - ACE_UNUSED_ARG (flags); - ACE_UNUSED_ARG (n_threads); - ACE_UNUSED_ARG (force_active); - ACE_UNUSED_ARG (priority); - ACE_UNUSED_ARG (grp_id); - ACE_UNUSED_ARG (task); - ACE_UNUSED_ARG (thread_handles); - ACE_UNUSED_ARG (stack); - ACE_UNUSED_ARG (stack_size); - ACE_UNUSED_ARG (thread_ids); - ACE_UNUSED_ARG (thr_name); - ACE_NOTSUP_RETURN (-1); - } -#endif /* ACE_MT_SAFE */ -} - -void -ACE_Task_Base::cleanup (void *object, void *) -{ - ACE_Task_Base *t = (ACE_Task_Base *) object; - - // The thread count must be decremented first in case the - // hook does something crazy like "delete this". - { - ACE_MT (ACE_GUARD (ACE_Thread_Mutex, ace_mon, t->lock_)); - t->thr_count_--; - if (0 == t->thr_count_) - t->last_thread_id_ = ACE_Thread::self (); - } - - // @@ Is it possible to pass in the exit status somehow? - t->close (); - // t is undefined here. close() could have deleted it. -} - - -#if defined (ACE_HAS_SIG_C_FUNC) -extern "C" void -ACE_Task_Base_cleanup (void *object, void *) -{ - ACE_Task_Base::cleanup (object, 0); -} -#endif /* ACE_HAS_SIG_C_FUNC */ - -ACE_THR_FUNC_RETURN -ACE_Task_Base::svc_run (void *args) -{ - ACE_TRACE ("ACE_Task_Base::svc_run"); - - ACE_Task_Base *t = (ACE_Task_Base *) args; - - // Register ourself with our 's thread exit hook - // mechanism so that our close() hook will be sure to get invoked - // when this thread exits. - -#if defined ACE_HAS_SIG_C_FUNC - t->thr_mgr ()->at_exit (t, ACE_Task_Base_cleanup, 0); -#else - t->thr_mgr ()->at_exit (t, ACE_Task_Base::cleanup, 0); -#endif /* ACE_HAS_SIG_C_FUNC */ - - // Call the Task's svc() hook method. - int const svc_status = t->svc (); - ACE_THR_FUNC_RETURN status; -#if defined (ACE_HAS_INTEGRAL_TYPE_THR_FUNC_RETURN) - // Reinterpret case between integral types is not mentioned in the C++ spec - status = static_cast (svc_status); -#else - status = reinterpret_cast (svc_status); -#endif /* ACE_HAS_INTEGRAL_TYPE_THR_FUNC_RETURN */ - -// If we changed this zero change the other if in OS.cpp Thread_Adapter::invoke -#if 1 - // Call the close> hook. - ACE_Thread_Manager *thr_mgr_ptr = t->thr_mgr (); - - // This calls the Task->close () hook. - t->cleanup (t, 0); - - // This prevents a second invocation of the cleanup code - // (called later by . - thr_mgr_ptr->at_exit (t, 0, 0); -#endif - return status; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Task.h b/externals/ace/Task.h deleted file mode 100644 index 08147a6459a..00000000000 --- a/externals/ace/Task.h +++ /dev/null @@ -1,307 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Task.h - * - * $Id: Task.h 91058 2010-07-12 08:20:09Z johnnyw $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_TASK_H -#define ACE_TASK_H -#include /**/ "ace/pre.h" - -#include "ace/Service_Object.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Thread_Manager.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Task_Flags - * - * @brief These flags are used within the ACE_Task. - * - * These flags should be hidden within ACE_Task. Unfortunately, the - * HP/UX C++ compiler can't grok this... Fortunately, there's no - * code defined here, so we don't have to worry about multiple - * definitions. - */ -namespace ACE_Task_Flags -{ - enum - { - /// Identifies a Task as being the "reader" in a Module. - ACE_READER = 01, - /// Just flush data messages in the queue. - ACE_FLUSHDATA = 02, - /// Flush all messages in the Queue. - ACE_FLUSHALL = 04, - /// Flush read queue - ACE_FLUSHR = 010, - /// Flush write queue - ACE_FLUSHW = 020, - /// Flush both queues - ACE_FLUSHRW = 030 - }; -} - -/** - * @class ACE_Task_Base - * - * @brief Direct base class for the ACE_Task template. - * - * This class factors out the non-template code in order to - * reduce template bloat, as well as to make it possible for the - * ACE_Thread_Manager to store ACE_Task_Base *'s - * polymorphically. - */ -class ACE_Export ACE_Task_Base : public ACE_Service_Object -{ -public: - // = Initialization and termination methods. - /// Constructor. - ACE_Task_Base (ACE_Thread_Manager * = 0); - - /// Destructor. - virtual ~ACE_Task_Base (void); - - // = Initialization and termination hooks. - - // These methods should be overridden by subclasses if you'd like to - // provide -specific initialization and termination behavior. - - /// Hook called to initialize a task and prepare it for execution. - /// @a args can be used to pass arbitrary information into . - virtual int open (void *args = 0); - - /** - * Hook called from ACE_Thread_Exit when during thread exit and from - * the default implementation of @c module_closed(). In general, this - * method shouldn't be called directly by an application, - * particularly if the Task is running as an Active Object. - * Instead, a special message should be passed into the Task via - * the put() method defined below, and the svc() method should - * interpret this as a flag to shut down the Task. - */ - virtual int close (u_long flags = 0); - - /** - * Hook called during ACE_Module::close(). The default - * implementation calls forwards the call to close(1). Please - * notice the changed value of the default argument of close(). - * This allows tasks to differ between the call has been originated - * from ACE_Thread_Exit or from module_closed(). Be aware that - * close(0) will be also called when a thread associated with the - * ACE_Task instance exits. - */ - virtual int module_closed (void); - - // = Immediate and deferred processing methods, respectively. - - // These methods should be overridden by subclasses if you'd like to - // provide -specific message processing behavior. - - /// A hook method that can be used to pass a message to a - /// task, where it can be processed immediately or queued for subsequent - /// processing in the svc() hook method. - virtual int put (ACE_Message_Block *, ACE_Time_Value * = 0); - - /// Run by a daemon thread to handle deferred processing. - virtual int svc (void); - - // = Active object activation method. - /** - * Turn the task into an active object, i.e., having @a n_threads of - * control, all running at the @a priority level (see below) with the - * same @a grp_id, all of which invoke . Returns -1 if - * failure occurs, returns 1 if Task is already an active object and - * @a force_active is false (i.e., do *not* create a new thread in - * this case), and returns 0 if Task was not already an active - * object and a thread is created successfully or thread is an - * active object and @a force_active is true. Note that if - * @a force_active is true and there are already threads spawned in - * this , the @a grp_id parameter is ignored and the @a grp_id - * of any newly activated thread(s) will inherit the existing - * @a grp_id of the existing thread(s) in the . - * - * The <{flags}> are a bitwise-OR of the following: - * = BEGIN - * THR_CANCEL_DISABLE, THR_CANCEL_ENABLE, THR_CANCEL_DEFERRED, - * THR_CANCEL_ASYNCHRONOUS, THR_BOUND, THR_NEW_LWP, THR_DETACHED, - * THR_SUSPENDED, THR_DAEMON, THR_JOINABLE, THR_SCHED_FIFO, - * THR_SCHED_RR, THR_SCHED_DEFAULT, THR_EXPLICIT_SCHED, - * THR_SCOPE_SYSTEM, THR_SCOPE_PROCESS - * = END - * If THR_SCHED_INHERIT is not desirable, applications should - * specifically pass in THR_EXPLICIT_SCHED. - * - * - * By default, or if <{priority}> is set to - * ACE_DEFAULT_THREAD_PRIORITY, an "appropriate" priority value for - * the given scheduling policy (specified in <{flags}>, e.g., - * ) is used. This value is calculated - * dynamically, and is the median value between the minimum and - * maximum priority values for the given policy. If an explicit - * value is given, it is used. Note that actual priority values are - * EXTREMEMLY implementation-dependent, and are probably best - * avoided. - * - * If @a thread_handles != 0 it is assumed to be an array of @a n - * thread_handles that will be assigned the values of the thread - * handles being spawned. Returns -1 on failure (@c errno will - * explain...), otherwise returns the group id of the threads. - * - * Assigning @a task allows you to associate the newly spawned - * threads with an instance of ACE_Task_Base. If @a task == 0, then - * the new threads are associated automatically with @c this - * ACE_Task_Base. Setting the @a task argument to value other than - * @c this makes the thread manipulating methods, such as wait(), - * suspend(), resume(), useless. Threads spawned with user - * specified @a task value must therefore be manipulated thru - * ACE_Thread_Manager directly. - * - * If @a stack != 0 it is assumed to be an array of @a n pointers to - * the base of the stacks to use for the threads being spawned. - * Likewise, if @a stack_size != 0 it is assumed to be an array of - * @a n values indicating how big each of the corresponding @a stacks - * are. - * - * - */ - virtual int activate (long flags = THR_NEW_LWP | THR_JOINABLE | THR_INHERIT_SCHED, - int n_threads = 1, - int force_active = 0, - long priority = ACE_DEFAULT_THREAD_PRIORITY, - int grp_id = -1, - ACE_Task_Base *task = 0, - ACE_hthread_t thread_handles[] = 0, - void *stack[] = 0, - size_t stack_size[] = 0, - ACE_thread_t thread_ids[] = 0, - const char* thr_name[] = 0); - - /** - * Block until there are no more threads running in this task. - * This method will not wait for either detached or daemon threads; - * the threads must have been spawned with the @c THR_JOINABLE flag. - * Upon successful completion, the threads have been joined, so further - * attempts to join with any of the waited-for threads will fail. - * - * @retval 0 Success. - * @retval -1 Failure (consult errno for further information). - */ - virtual int wait (void); - - // = Suspend/resume a Task. - - // Note that these methods are not portable and should be avoided - // since they are inherently error-prone to use. They are only here - // for (the rare) applications that know how to use them correctly. - /// Suspend a task. - virtual int suspend (void); - /// Resume a suspended task. - virtual int resume (void); - - /// Get the current group id. - int grp_id (void) const; - - /// Set the current group id. - void grp_id (int); - - /// Get the thread manager associated with this Task. - ACE_Thread_Manager *thr_mgr (void) const; - - /// Set the thread manager associated with this Task. - void thr_mgr (ACE_Thread_Manager *); - - /// True if queue is a reader, else false. - int is_reader (void) const; - - /// True if queue is a writer, else false. - int is_writer (void) const; - - /** - * Returns the number of threads currently running within a task. - * If we're a passive object this value is 0, else it's greater than - * 0. - */ - size_t thr_count (void) const; - - /** - * Returns the thread ID of the thread whose exit caused this object's - * thread count to be decremented to 0. - * - * When a thread spawned in the context of this object (using activate()) - * returns from its svc() method ACE calls the close() hook. Before it does - * so, it decrements the number of active threads. If the number of threads - * is decremented to 0, the thread ID of the current thread is stored for - * access by this method. If the returned thread ID matches the calling - * thread's ID, the calling thread knows that there are no other threads - * still active in the ACE_Task. - * - * @retval ACE_thread_t of the last thread to close. 0 if the last thread - * is not yet known; for example, if no threads are active, or if - * multiple threads are active. - */ - ACE_thread_t last_thread (void) const; - - /// Routine that runs the service routine as a daemon thread. - static ACE_THR_FUNC_RETURN svc_run (void *); - - /// Cleanup hook that is called when a thread exits to gracefully - /// shutdown an ACE_Task. - static void cleanup (void *object, void *params); - -protected: - /** - * Count of the number of threads running within the task. If this - * value is greater than 0 then we're an active object and the value - * of is the number of active threads at this instant. - * If the value == 0, then we're a passive object. - */ - size_t thr_count_; - - /// Multi-threading manager. - ACE_Thread_Manager *thr_mgr_; - - /// ACE_Task flags. - u_long flags_; - - /// This maintains the group id of the Task. - int grp_id_; - -#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) - /// Protect the state of a Task during concurrent operations, but - /// only if we're configured as MT safe... - ACE_Thread_Mutex lock_; -#endif /* ACE_MT_SAFE */ - - /// Holds the thread ID of the last thread to exit svc() in this object. - ACE_thread_t last_thread_id_; - -private: - - // = Disallow these operations. - ACE_Task_Base &operator= (const ACE_Task_Base &); - ACE_Task_Base (const ACE_Task_Base &); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Task.inl" -#endif /* __ACE_INLINE__ */ - -// Include the ACE_Task templates classes at this point. -#include "ace/Task_T.h" - -#include /**/ "ace/post.h" -#endif /* ACE_TASK_H */ diff --git a/externals/ace/Task.inl b/externals/ace/Task.inl deleted file mode 100644 index 9f70371e5f5..00000000000 --- a/externals/ace/Task.inl +++ /dev/null @@ -1,77 +0,0 @@ -// -*- C++ -*- -// -// $Id: Task.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Get the current group id. -ACE_INLINE int -ACE_Task_Base::grp_id (void) const -{ - ACE_TRACE ("ACE_Task_Base::grp_id"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, const_cast (this->lock_), -1)); - return this->grp_id_; -} - -// Set the current group id. - -ACE_INLINE void -ACE_Task_Base::grp_id (int identifier) -{ - ACE_TRACE ("ACE_Task_Base::grp_id"); - ACE_MT (ACE_GUARD (ACE_Thread_Mutex, ace_mon, this->lock_)); - - // Cache the group id in the task and then set it in the - // Thread_Manager, if there is one. - this->grp_id_ = identifier; - if (this->thr_mgr ()) - this->thr_mgr ()->set_grp (this, identifier); -} - -ACE_INLINE ACE_Thread_Manager * -ACE_Task_Base::thr_mgr (void) const -{ - ACE_TRACE ("ACE_Task_Base::thr_mgr"); - return this->thr_mgr_; -} - -ACE_INLINE void -ACE_Task_Base::thr_mgr (ACE_Thread_Manager *thr_mgr) -{ - ACE_TRACE ("ACE_Task_Base::thr_mgr"); - this->thr_mgr_ = thr_mgr; -} - -ACE_INLINE int -ACE_Task_Base::is_reader (void) const -{ - ACE_TRACE ("ACE_Task_Base::is_reader"); - return (ACE_BIT_ENABLED (this->flags_, ACE_Task_Flags::ACE_READER)); -} - -ACE_INLINE int -ACE_Task_Base::is_writer (void) const -{ - ACE_TRACE ("ACE_Task_Base::is_writer"); - return (ACE_BIT_DISABLED (this->flags_, ACE_Task_Flags::ACE_READER)); -} - -// Return the count of the current number of threads. -ACE_INLINE size_t -ACE_Task_Base::thr_count (void) const -{ - ACE_TRACE ("ACE_Task_Base::thr_count"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, const_cast (this->lock_), 0)); - - return this->thr_count_; -} - -// Return the thread ID of the last thread to exit svc(). -ACE_INLINE ACE_thread_t -ACE_Task_Base::last_thread (void) const -{ - ACE_TRACE ("ACE_Task_Base::last_thread"); - return this->last_thread_id_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Task_Ex_T.cpp b/externals/ace/Task_Ex_T.cpp deleted file mode 100644 index de97e5ba6b4..00000000000 --- a/externals/ace/Task_Ex_T.cpp +++ /dev/null @@ -1,114 +0,0 @@ -// $Id: Task_Ex_T.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#ifndef ACE_TASK_EX_T_CPP -#define ACE_TASK_EX_T_CPP - -#include "ace/Task_Ex_T.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Module.h" -#include "ace/Null_Condition.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Task_Ex_T.inl" -#endif /* __ACE_INLINE__ */ - - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template void -ACE_Task_Ex::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Task_Ex::dump"); - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nthr_mgr_ = %x"), this->thr_mgr_)); - this->msg_queue_->dump (); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("delete_msg_queue_ = %d\n"), this->delete_msg_queue_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nflags = %x"), this->flags_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nmod_ = %x"), this->mod_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nnext_ = %x"), this->next_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ngrp_id_ = %d"), this->grp_id_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nthr_count_ = %d"), this->thr_count_)); -#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) - this->lock_.dump (); -#endif /* ACE_MT_SAFE */ - - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -// If the user doesn't supply a ACE_Message_Queue_Ex pointer then we'll -// allocate one dynamically. Otherwise, we'll use the one they give. - -template -ACE_Task_Ex::ACE_Task_Ex (ACE_Thread_Manager *thr_man, - ACE_Message_Queue_Ex *mq) - : ACE_Task_Base (thr_man), - msg_queue_ (0), - delete_msg_queue_ (false), - mod_ (0), - next_ (0) -{ - ACE_TRACE ("ACE_Task_Ex::ACE_Task_Ex"); - - if (mq == 0) - { - ACE_NEW (mq, - (ACE_Message_Queue_Ex)); - this->delete_msg_queue_ = true; - } - - this->msg_queue_ = mq; -} - -template -ACE_Task_Ex::~ACE_Task_Ex (void) -{ - ACE_TRACE ("ACE_Task_Ex::~ACE_Task_Ex"); - if (this->delete_msg_queue_) - delete this->msg_queue_; - - // These assignments aren't strickly necessary but they help guard - // against odd race conditions... - this->delete_msg_queue_ = false; -} - -template ACE_Task * -ACE_Task_Ex::sibling (void) -{ - ACE_TRACE ("ACE_Task_Ex::sibling"); - /// @todo FIXME Need to impl ACE_Moudle to support ACE_Task as well. - /// Now always return 0 for sibling - return 0; -/* - if (this->mod_ == 0) - return 0; - else - return this->mod_->sibling (this); -*/ -} - -template const ACE_TCHAR * -ACE_Task_Ex::name (void) const -{ - ACE_TRACE ("ACE_Task_Ex::name"); - if (this->mod_ == 0) - return 0; - else - return this->mod_->name (); -} - -template ACE_Module * -ACE_Task_Ex::module (void) const -{ - ACE_TRACE ("ACE_Task_Ex::module"); - return this->mod_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_TASK_EX_T_CPP */ diff --git a/externals/ace/Task_Ex_T.h b/externals/ace/Task_Ex_T.h deleted file mode 100644 index 00233d4e7d9..00000000000 --- a/externals/ace/Task_Ex_T.h +++ /dev/null @@ -1,205 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Task_Ex_T.h - * - * $Id: Task_Ex_T.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Kobi Cohen-Arazi - */ -//============================================================================= - -#ifndef ACE_TASK_EX_T_H -#define ACE_TASK_EX_T_H -#include /**/ "ace/pre.h" - -#include "ace/Service_Object.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Synch_Traits.h" -#include "ace/Task.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Forward decls... -template class ACE_Module; - -/** - * @class ACE_Task_Ex - * - * @brief Primary interface for application message processing, as well - * as input and output message queueing. - * - * Unlike ACE_Task, these class doesn't have the ability to be a part of - * a Stream chain. I.e. You cannot (yet) chain modules based on ACE_Task_Ex. - * - * @todo: We can merge ACE_Task and ACE_Task_Ex to be one class. - * something like that: - * template - * class ACE_Task : public ACE_Task_Base - * { - * // use here the code from ACE_Task_Ex using ACE_Message_Queue_Ex - * }; - * - * Now specialized version of ACE_Task with ACE_Message_Block as its - * ACE_MESSAGE_TYPE... - * - * template - * class ACE_Task : public ACE_Task_Base - * { - * // put here the good old ACE_Task code - * }; - * - * When User (and legacy code) write ACE_Task, specialized ACE_Task - * code is in action. - */ -template -class ACE_Task_Ex : public ACE_Task_Base -{ -public: - friend class ACE_Module; - friend class ACE_Module_Type; - typedef ACE_Message_Queue_Ex MESSAGE_QUEUE_EX; - - // = Initialization/termination methods. - /** - * Initialize a Task, supplying a thread manager and a message - * queue. If the user doesn't supply a ACE_Message_Queue pointer - * then we'll allocate one dynamically. Otherwise, we'll use the - * one passed as a parameter. - */ - ACE_Task_Ex (ACE_Thread_Manager *thr_mgr = 0, - MESSAGE_QUEUE_EX *mq = 0); - - /// Destructor. - virtual ~ACE_Task_Ex (void); - - /// Gets the message queue associated with this task. - MESSAGE_QUEUE_EX *msg_queue (void); - - /// Sets the message queue associated with this task. - void msg_queue (MESSAGE_QUEUE_EX *); - -public: // Should be protected: - // = Message queue manipulation methods. - - // = Enqueue and dequeue methods. - - // For the following five method if @a timeout == 0, the caller will - // block until action is possible, else will wait until the - // <{absolute}> time specified in *@a timeout elapses). These calls - // will return, however, when queue is closed, deactivated, when a - // signal occurs, or if the time specified in timeout elapses, (in - // which case errno = EWOULDBLOCK). - - /// Insert message into the message queue. Note that @a timeout uses - /// <{absolute}> time rather than <{relative}> time. - int putq (ACE_MESSAGE_TYPE *, ACE_Time_Value *timeout = 0); - - /** - * Extract the first message from the queue (blocking). Note that - * @a timeout uses <{absolute}> time rather than <{relative}> time. - * Returns number of items in queue if the call succeeds or -1 otherwise. - */ - int getq (ACE_MESSAGE_TYPE *&mb, ACE_Time_Value *timeout = 0); - - /// Return a message to the queue. Note that @a timeout uses - /// <{absolute}> time rather than <{relative}> time. - int ungetq (ACE_MESSAGE_TYPE *, ACE_Time_Value *timeout = 0); - - /** - * Turn the message around and send it back down the Stream. Note - * that @a timeout uses <{absolute}> time rather than <{relative}> - * time. - */ - int reply (ACE_MESSAGE_TYPE *, ACE_Time_Value *timeout = 0); - - /** - * Transfer message to the adjacent ACE_Task_Ex in a ACE_Stream. Note - * that @a timeout uses <{absolute}> time rather than <{relative}> - * time. - */ - int put_next (ACE_MESSAGE_TYPE *msg, ACE_Time_Value *timeout = 0); - - /** - * Tests whether we can enqueue a message without blocking. - * @deprecated This method is deprecated and will go away in the future. - */ - int can_put (ACE_MESSAGE_TYPE *); - - // = ACE_Task utility routines to identify names et al. - /// Return the name of the enclosing Module if there's one associated - /// with the Task, else returns 0. - const ACE_TCHAR *name (void) const; - - // = Pointers to next ACE_Task_Base (if ACE is part of an ACE_Stream). - /// Get next Task pointer. - ACE_Task *next (void); - - /// Set next Task pointer. - void next (ACE_Task *); - - /// Alwasy return 0. @todo FIXME - ACE_Task *sibling (void); - - /// Return the Task's Module if there is one, else returns 0. - ACE_Module *module (void) const; - - /** - * Flush the task's queue, i.e., free all of the enqueued - * message blocks and releases any threads blocked on the queue. - * Note that if this conflicts with the C++ iostream - * function, just rewrite the iostream function as ::. - */ - int flush (u_long flag = ACE_Task_Flags::ACE_FLUSHALL); - - // = Special routines corresponding to certain message types. - - /// Manipulate watermarks. - void water_marks (ACE_IO_Cntl_Msg::ACE_IO_Cntl_Cmds, size_t); - - /// Queue of messages on the ACE_Task.. - MESSAGE_QUEUE_EX *msg_queue_; - - /// true if should delete Message_Queue, false otherwise. - bool delete_msg_queue_; - - /// Back-pointer to the enclosing module. - ACE_Module *mod_; - - /// Pointer to adjacent ACE_Task. - ACE_Task *next_; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - - // = Disallow these operations. - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Task_Ex &)) - ACE_UNIMPLEMENTED_FUNC (ACE_Task_Ex (const ACE_Task_Ex &)) -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Task_Ex_T.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Task_Ex_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Task_Ex_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" -#endif /* ACE_TASK_EX_H */ diff --git a/externals/ace/Task_Ex_T.inl b/externals/ace/Task_Ex_T.inl deleted file mode 100644 index dd90bcd499a..00000000000 --- a/externals/ace/Task_Ex_T.inl +++ /dev/null @@ -1,109 +0,0 @@ -// -*- C++ -*- -// -// $Id: Task_Ex_T.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template ACE_INLINE void -ACE_Task_Ex::water_marks (ACE_IO_Cntl_Msg::ACE_IO_Cntl_Cmds cmd, - size_t wm_size) -{ - ACE_TRACE ("ACE_Task_Ex::water_marks"); - if (cmd == ACE_IO_Cntl_Msg::SET_LWM) - this->msg_queue_->low_water_mark (wm_size); - else /* cmd == ACE_IO_Cntl_Msg::SET_HWM */ - this->msg_queue_->high_water_mark (wm_size); -} - -template ACE_INLINE int -ACE_Task_Ex::getq (ACE_MESSAGE_TYPE *&mb, ACE_Time_Value *tv) -{ - ACE_TRACE ("ACE_Task_Ex::getq"); - return this->msg_queue_->dequeue_head (mb, tv); -} - -template ACE_INLINE int -ACE_Task_Ex::can_put (ACE_MESSAGE_TYPE *) -{ - ACE_TRACE ("ACE_Task_Ex::can_put"); - ACE_NOTSUP_RETURN (-1); -} - -template ACE_INLINE int -ACE_Task_Ex::putq (ACE_MESSAGE_TYPE *mb, ACE_Time_Value *tv) -{ - ACE_TRACE ("ACE_Task_Ex::putq"); - return this->msg_queue_->enqueue_tail (mb, tv); -} - -template ACE_INLINE int -ACE_Task_Ex::ungetq (ACE_MESSAGE_TYPE *mb, ACE_Time_Value *tv) -{ - ACE_TRACE ("ACE_Task_Ex::ungetq"); - return this->msg_queue_->enqueue_head (mb, tv); -} - -template ACE_INLINE int -ACE_Task_Ex::flush (u_long flag) -{ - ACE_TRACE ("ACE_Task_Ex::flush"); - if (ACE_BIT_ENABLED (flag, ACE_Task_Flags::ACE_FLUSHALL)) - return this->msg_queue_ != 0 && this->msg_queue_->close (); - else - return -1; // Note, need to be more careful about what we free... -} - -template ACE_INLINE void -ACE_Task_Ex::msg_queue (ACE_Message_Queue_Ex *mq) -{ - ACE_TRACE ("ACE_Task_Ex::msg_queue"); - if (this->delete_msg_queue_) - { - delete this->msg_queue_; - this->delete_msg_queue_ = false; - } - this->msg_queue_ = mq; -} - -template ACE_Message_Queue_Ex * -ACE_Task_Ex::msg_queue (void) -{ - ACE_TRACE ("ACE_Task_Ex::msg_queue"); - return this->msg_queue_; -} - -template ACE_INLINE int -ACE_Task_Ex::reply (ACE_MESSAGE_TYPE *mb, ACE_Time_Value *tv) -{ - ACE_TRACE ("ACE_Task_Ex::reply"); - ACE_UNUSED_ARG (mb); - ACE_UNUSED_ARG (tv); - return -1 ; // this->sibling ()->put_next (mb, tv); -} - -template ACE_INLINE ACE_Task * -ACE_Task_Ex::next (void) -{ - ACE_TRACE ("ACE_Task_Ex::next"); - return this->next_; -} - -template ACE_INLINE void -ACE_Task_Ex::next (ACE_Task *q) -{ - ACE_TRACE ("ACE_Task_Ex::next"); - this->next_ = q; -} - -// Transfer msg to the next ACE_Task_Ex. - -template ACE_INLINE int -ACE_Task_Ex::put_next ( - ACE_MESSAGE_TYPE * /* msg */, - ACE_Time_Value * /* tv */) -{ - ACE_TRACE ("ACE_Task_Ex::put_next"); - return -1; // this->next_ == 0 ? -1 : this->next_->put (msg, tv); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Task_T.cpp b/externals/ace/Task_T.cpp deleted file mode 100644 index 08b36f82f08..00000000000 --- a/externals/ace/Task_T.cpp +++ /dev/null @@ -1,108 +0,0 @@ -// $Id: Task_T.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#ifndef ACE_TASK_T_CPP -#define ACE_TASK_T_CPP - -#include "ace/Task_T.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Module.h" -#include "ace/Null_Condition.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Task_T.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template void -ACE_Task::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Task::dump"); - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nthr_mgr_ = %x"), this->thr_mgr_)); - this->msg_queue_->dump (); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("delete_msg_queue_ = %d\n"), this->delete_msg_queue_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nflags = %x"), this->flags_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nmod_ = %x"), this->mod_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nnext_ = %x"), this->next_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ngrp_id_ = %d"), this->grp_id_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nthr_count_ = %d"), this->thr_count_)); -#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) - this->lock_.dump (); -#endif /* ACE_MT_SAFE */ - - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -// If the user doesn't supply a ACE_Message_Queue pointer then we'll -// allocate one dynamically. Otherwise, we'll use the one they give. - -template -ACE_Task::ACE_Task (ACE_Thread_Manager *thr_man, - ACE_Message_Queue *mq) - : ACE_Task_Base (thr_man), - msg_queue_ (0), - delete_msg_queue_ (false), - mod_ (0), - next_ (0) -{ - ACE_TRACE ("ACE_Task::ACE_Task"); - - if (mq == 0) - { - ACE_NEW (mq, - ACE_Message_Queue); - this->delete_msg_queue_ = true; - } - - this->msg_queue_ = mq; -} - -template -ACE_Task::~ACE_Task (void) -{ - ACE_TRACE ("ACE_Task::~ACE_Task"); - if (this->delete_msg_queue_) - delete this->msg_queue_; - - // These assignments aren't strickly necessary but they help guard - // against odd race conditions... - this->delete_msg_queue_ = false; -} - -template ACE_Task * -ACE_Task::sibling (void) -{ - ACE_TRACE ("ACE_Task::sibling"); - if (this->mod_ == 0) - return 0; - else - return this->mod_->sibling (this); -} - -template const ACE_TCHAR * -ACE_Task::name (void) const -{ - ACE_TRACE ("ACE_Task::name"); - if (this->mod_ == 0) - return 0; - else - return this->mod_->name (); -} - -template ACE_Module * -ACE_Task::module (void) const -{ - ACE_TRACE ("ACE_Task::module"); - return this->mod_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_TASK_T_CPP */ diff --git a/externals/ace/Task_T.h b/externals/ace/Task_T.h deleted file mode 100644 index d79a5fb0e46..00000000000 --- a/externals/ace/Task_T.h +++ /dev/null @@ -1,198 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Task_T.h - * - * $Id: Task_T.h 91016 2010-07-06 11:29:50Z johnnyw $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_TASK_T_H -#define ACE_TASK_T_H -#include /**/ "ace/pre.h" - -#include "ace/Message_Queue.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Synch_Traits.h" -#include "ace/Task.h" -#include "ace/IO_Cntl_Msg.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Forward decls... -template class ACE_Module; - -/** - * @class ACE_Task - * - * @brief Primary interface for application message processing, as well - * as input and output message queueing. - * - * This class serves as the basis for passive and active objects - * in ACE. - */ -template -class ACE_Task : public ACE_Task_Base -{ -public: - friend class ACE_Module; - friend class ACE_Module_Type; - - // = Initialization/termination methods. - /** - * Initialize a Task, supplying a thread manager and a message - * queue. If the user doesn't supply a ACE_Message_Queue pointer - * then we'll allocate one dynamically. Otherwise, we'll use the - * one passed as a parameter. - */ - ACE_Task (ACE_Thread_Manager *thr_mgr = 0, - ACE_Message_Queue *mq = 0); - - /// Destructor. - virtual ~ACE_Task (void); - - /// Gets the message queue associated with this task. - ACE_Message_Queue *msg_queue (void); - - /// Sets the message queue associated with this task. - void msg_queue (ACE_Message_Queue *); - -public: // Should be protected: - // = Message queue manipulation methods. - - // = Enqueue and dequeue methods. - - // For the following five method if @a timeout == 0, the caller will - // block until action is possible, else will wait until the - // <{absolute}> time specified in *@a timeout elapses). These calls - // will return, however, when queue is closed, deactivated, when a - // signal occurs, or if the time specified in timeout elapses, (in - // which case errno = EWOULDBLOCK). - - /// Insert message into the message queue. Note that @a timeout uses - /// <{absolute}> time rather than <{relative}> time. - int putq (ACE_Message_Block *, ACE_Time_Value *timeout = 0); - - /** - * Extract the first message from the queue (blocking). Note that - * @a timeout uses <{absolute}> time rather than <{relative}> time. - * Returns number of items in queue if the call succeeds or -1 otherwise. - */ - int getq (ACE_Message_Block *&mb, ACE_Time_Value *timeout = 0); - - /// Return a message to the queue. Note that @a timeout uses - /// <{absolute}> time rather than <{relative}> time. - int ungetq (ACE_Message_Block *, ACE_Time_Value *timeout = 0); - - /** - * Turn the message around, sending it in the opposite direction in - * the stream. To do this, the message is put onto the task next in - * the stream after this task's sibling. - * - * @param mb Pointer to the block that is used in the reply. - * @param tv The absolute time at which the put operation used to - * send the message block to the next module in the stream - * will time out. If 0, this call blocks until it can be - * completed. - */ - int reply (ACE_Message_Block *mb, ACE_Time_Value *tv = 0); - - /** - * Transfer message to the adjacent ACE_Task in a ACE_Stream. Note - * that @a timeout uses <{absolute}> time rather than <{relative}> - * time. - */ - int put_next (ACE_Message_Block *msg, ACE_Time_Value *timeout = 0); - - /** - * Tests whether we can enqueue a message without blocking. - * - * @deprecated This method is deprecated and will go away in the future. - */ - int can_put (ACE_Message_Block *); - - // = ACE_Task utility routines to identify names et al. - /// Return the name of the enclosing Module if there's one associated - /// with the Task, else returns 0. - const ACE_TCHAR *name (void) const; - - // = Pointers to next ACE_Task_Base (if ACE is part of an ACE_Stream). - /// Get next Task pointer. - ACE_Task *next (void); - - /// Set next Task pointer. - void next (ACE_Task *); - - /// Return the Task's sibling if there's one associated with the - /// Task's Module, else returns 0. - ACE_Task *sibling (void); - - /// Return the Task's Module if there is one, else returns 0. - ACE_Module *module (void) const; - - /** - * Flush the task's queue, i.e., free all of the enqueued - * message blocks and unblocks any threads waiting on the queue. - * Note that if this conflicts with the C++ iostream - * function, just rewrite the iostream function as ::. - */ - int flush (u_long flag = ACE_Task_Flags::ACE_FLUSHALL); - - // = Special routines corresponding to certain message types. - - /// Manipulate watermarks. - void water_marks (ACE_IO_Cntl_Msg::ACE_IO_Cntl_Cmds, size_t); - - /// Queue of messages on the ACE_Task.. - ACE_Message_Queue *msg_queue_; - - /// true if should delete Message_Queue, false otherwise. - bool delete_msg_queue_; - - /// Back-pointer to the enclosing module. - ACE_Module *mod_; - - /// Pointer to adjacent ACE_Task. - ACE_Task *next_; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - - // = Disallow these operations. - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Task &)) - ACE_UNIMPLEMENTED_FUNC (ACE_Task (const ACE_Task &)) -}; - -#if defined ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION_EXPORT -template class ACE_Export ACE_Task; -template class ACE_Export ACE_Task; -#endif /* ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION_EXPORT */ - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Task_T.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Task_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Task_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" -#endif /* ACE_TASK_T_H */ diff --git a/externals/ace/Task_T.inl b/externals/ace/Task_T.inl deleted file mode 100644 index a441ca9d0b3..00000000000 --- a/externals/ace/Task_T.inl +++ /dev/null @@ -1,105 +0,0 @@ -// -*- C++ -*- -// -// $Id: Task_T.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template ACE_INLINE void -ACE_Task::water_marks (ACE_IO_Cntl_Msg::ACE_IO_Cntl_Cmds cmd, - size_t wm_size) -{ - ACE_TRACE ("ACE_Task::water_marks"); - if (cmd == ACE_IO_Cntl_Msg::SET_LWM) - this->msg_queue_->low_water_mark (wm_size); - else /* cmd == ACE_IO_Cntl_Msg::SET_HWM */ - this->msg_queue_->high_water_mark (wm_size); -} - -template ACE_INLINE int -ACE_Task::getq (ACE_Message_Block *&mb, ACE_Time_Value *tv) -{ - ACE_TRACE ("ACE_Task::getq"); - return this->msg_queue_->dequeue_head (mb, tv); -} - -template ACE_INLINE int -ACE_Task::can_put (ACE_Message_Block *) -{ - ACE_TRACE ("ACE_Task::can_put"); - ACE_NOTSUP_RETURN (-1); -} - -template ACE_INLINE int -ACE_Task::putq (ACE_Message_Block *mb, ACE_Time_Value *tv) -{ - ACE_TRACE ("ACE_Task::putq"); - return this->msg_queue_->enqueue_tail (mb, tv); -} - -template ACE_INLINE int -ACE_Task::ungetq (ACE_Message_Block *mb, ACE_Time_Value *tv) -{ - ACE_TRACE ("ACE_Task::ungetq"); - return this->msg_queue_->enqueue_head (mb, tv); -} - -template ACE_INLINE int -ACE_Task::flush (u_long flag) -{ - ACE_TRACE ("ACE_Task::flush"); - if (ACE_BIT_ENABLED (flag, ACE_Task_Flags::ACE_FLUSHALL)) - return this->msg_queue_ != 0 && this->msg_queue_->close (); - else - return -1; // Note, need to be more careful about what we free... -} - -template ACE_INLINE void -ACE_Task::msg_queue (ACE_Message_Queue *mq) -{ - ACE_TRACE ("ACE_Task::msg_queue"); - if (this->delete_msg_queue_) - { - delete this->msg_queue_; - this->delete_msg_queue_ = false; - } - this->msg_queue_ = mq; -} - -template ACE_Message_Queue * -ACE_Task::msg_queue (void) -{ - ACE_TRACE ("ACE_Task::msg_queue"); - return this->msg_queue_; -} - -template ACE_INLINE int -ACE_Task::reply (ACE_Message_Block *mb, ACE_Time_Value *tv) -{ - ACE_TRACE ("ACE_Task::reply"); - return this->sibling ()->put_next (mb, tv); -} - -template ACE_INLINE ACE_Task * -ACE_Task::next (void) -{ - ACE_TRACE ("ACE_Task::next"); - return this->next_; -} - -template ACE_INLINE void -ACE_Task::next (ACE_Task *q) -{ - ACE_TRACE ("ACE_Task::next"); - this->next_ = q; -} - -// Transfer msg to the next ACE_Task. - -template ACE_INLINE int -ACE_Task::put_next (ACE_Message_Block *msg, ACE_Time_Value *tv) -{ - ACE_TRACE ("ACE_Task::put_next"); - return this->next_ == 0 ? -1 : this->next_->put (msg, tv); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Test_and_Set.cpp b/externals/ace/Test_and_Set.cpp deleted file mode 100644 index 15fbfe084f5..00000000000 --- a/externals/ace/Test_and_Set.cpp +++ /dev/null @@ -1,51 +0,0 @@ -// $Id: Test_and_Set.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#ifndef ACE_TEST_AND_SET_CPP -#define ACE_TEST_AND_SET_CPP - -#include "ace/Test_and_Set.h" -#include "ace/Guard_T.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template -ACE_Test_and_Set::ACE_Test_and_Set (TYPE initial_value) - : is_set_ (initial_value) -{ -} - -// Returns true if we are done, else false. -template TYPE -ACE_Test_and_Set::is_set (void) const -{ - ACE_GUARD_RETURN (ACE_LOCK, ace_mon, (ACE_LOCK &) this->lock_, this->is_set_); - return this->is_set_; -} - -// Sets the status. -template TYPE -ACE_Test_and_Set::set (TYPE status) -{ - ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->lock_, this->is_set_); - TYPE o_status = this->is_set_; - this->is_set_ = status; - return o_status; -} - -template int -ACE_Test_and_Set::handle_signal (int, siginfo_t *, ucontext_t *) -{ - // By setting this to 1, we are "signaling" to anyone calling - // or or that the "test and set" object is in the - // "signaled" state, i.e., it's "available" to be set back to 0. - this->set (1); - return 0; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_TEST_AND_SET_CPP */ diff --git a/externals/ace/Test_and_Set.h b/externals/ace/Test_and_Set.h deleted file mode 100644 index 062de0bc804..00000000000 --- a/externals/ace/Test_and_Set.h +++ /dev/null @@ -1,75 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Test_and_Set.h - * - * $Id: Test_and_Set.h 80826 2008-03-04 14:51:23Z wotte $ - */ -//============================================================================= - - -#ifndef ACE_TEST_AND_SET_H -#define ACE_TEST_AND_SET_H - -#include /**/ "ace/pre.h" -#include "ace/Event_Handler.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Test_and_Set - * - * @brief Implements the classic ``test and set'' operation. - * - * - * This class keeps track of the status of , which can - * be set based on various events (such as receipt of a - * signal). This class is derived from ACE_Event_Handler so - * that it can be "signaled" by a Reactor when a signal occurs. - * We assume that is a data type that can be assigned the - * value 0 or 1. - */ -template -class ACE_Test_and_Set : public ACE_Event_Handler -{ -public: - ACE_Test_and_Set (TYPE initial_value = 0); - - /// Returns true if we are set, else false. - TYPE is_set (void) const; - - /// Sets the status, returning the original value of - /// . - TYPE set (TYPE); - - /// Called when object is signaled by OS (either via UNIX signals or - /// when a Win32 object becomes signaled). - virtual int handle_signal (int signum, - siginfo_t * = 0, - ucontext_t * = 0); - -private: - /// Keeps track of our state. - TYPE is_set_; - - /// Protect the state from race conditions. - ACE_LOCK lock_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Test_and_Set.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Test_and_Set.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" -#endif /* ACE_TEST_AND_SET_H */ diff --git a/externals/ace/Thread.cpp b/externals/ace/Thread.cpp deleted file mode 100644 index 2fb009b67d2..00000000000 --- a/externals/ace/Thread.cpp +++ /dev/null @@ -1,101 +0,0 @@ -// $Id: Thread.cpp 84163 2009-01-15 07:57:27Z johnnyw $ - -#include "ace/Thread.h" - -ACE_RCSID(ace, - Thread, - "$Id: Thread.cpp 84163 2009-01-15 07:57:27Z johnnyw $") - -#if !defined (__ACE_INLINE__) -#include "ace/Thread.inl" -#endif /* !defined (__ACE_INLINE__) */ - -#if defined (ACE_HAS_THREADS) - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -size_t -ACE_Thread::spawn_n (size_t n, - ACE_THR_FUNC func, - void *arg, - long flags, - long priority, - void *stack[], - size_t stack_size[], - ACE_Thread_Adapter *thread_adapter, - const char* thr_name[]) -{ - ACE_TRACE ("ACE_Thread::spawn_n"); - size_t i; - - for (i = 0; i < n; i++) - { - ACE_thread_t t_id; - // Bail out if error occurs. - if (ACE_OS::thr_create (func, - arg, - flags, - &t_id, - 0, - priority, - stack == 0 ? 0 : stack[i], - stack_size == 0 ? ACE_DEFAULT_THREAD_STACKSIZE : stack_size[i], - thread_adapter, - thr_name == 0 ? 0 : &thr_name[i]) != 0) - break; - } - - return i; -} - -size_t -ACE_Thread::spawn_n (ACE_thread_t thread_ids[], - size_t n, - ACE_THR_FUNC func, - void *arg, - long flags, - long priority, - void *stack[], - size_t stack_size[], - ACE_hthread_t thread_handles[], - ACE_Thread_Adapter *thread_adapter, - const char* thr_name[]) -{ - ACE_TRACE ("ACE_Thread::spawn_n"); - size_t i = 0; - - for (i = 0; i < n; i++) - { - ACE_thread_t t_id; - ACE_hthread_t t_handle; - - int const result = - ACE_OS::thr_create (func, - arg, - flags, - &t_id, - &t_handle, - priority, - stack == 0 ? 0 : stack[i], - stack_size == 0 ? ACE_DEFAULT_THREAD_STACKSIZE : stack_size[i], - thread_adapter, - thr_name == 0 ? 0 : &thr_name[i]); - - if (result == 0) - { - if (thread_ids != 0) - thread_ids[i] = t_id; - if (thread_handles != 0) - thread_handles[i] = t_handle; - } - else - // Bail out if error occurs. - break; - } - - return i; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_THREADS */ diff --git a/externals/ace/Thread.h b/externals/ace/Thread.h deleted file mode 100644 index 4d44858fa5b..00000000000 --- a/externals/ace/Thread.h +++ /dev/null @@ -1,282 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file Thread.h - * - * $Id: Thread.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Douglas Schmidt - */ -//========================================================================== - -#ifndef ACE_THREAD_H -#define ACE_THREAD_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/OS_NS_Thread.h" -#include "ace/Thread_Adapter.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -struct cancel_state -{ - /// e.g., PTHREAD_CANCEL_ENABLE, PTHREAD_CANCEL_DISABLE, - /// PTHREAD_CANCELED. - int cancelstate; - - /// e.g., PTHREAD_CANCEL_DEFERRED and PTHREAD_CANCEL_ASYNCHRONOUS. - int canceltype; -}; - -/** - * @class ACE_Thread - * - * @brief Provides a wrapper for threads. - * - * This class provides a common interface that is mapped onto - * POSIX Pthreads, Solaris threads, Win32 threads, VxWorks - * threads, or pSoS threads. Note, however, that it is - * generally a better idea to use the ACE_Thread_Manager - * programming API rather than the API since the - * thread manager is more powerful. - */ -class ACE_Export ACE_Thread -{ -public: - /** - * Creates a new thread having @a flags attributes and running @a func - * with (if is non-0 then @a func and - * are ignored and are obtained from ). - * and are set to the thread's ID and handle (?), - * respectively. The thread runs at @a priority priority (see - * below). - * - * The @a flags are a bitwise-OR of the following: - * = BEGIN - * THR_CANCEL_DISABLE, THR_CANCEL_ENABLE, THR_CANCEL_DEFERRED, - * THR_CANCEL_ASYNCHRONOUS, THR_BOUND, THR_NEW_LWP, THR_DETACHED, - * THR_SUSPENDED, THR_DAEMON, THR_JOINABLE, THR_SCHED_FIFO, - * THR_SCHED_RR, THR_SCHED_DEFAULT, THR_EXPLICIT_SCHED, - * THR_SCOPE_SYSTEM, THR_SCOPE_PROCESS - * = END - * - * By default, or if @a priority is set to - * ACE_DEFAULT_THREAD_PRIORITY, an "appropriate" priority value for - * the given scheduling policy (specified in , e.g., - * ) is used. This value is calculated - * dynamically, and is the median value between the minimum and - * maximum priority values for the given policy. If an explicit - * value is given, it is used. Note that actual priority values are - * EXTREMEMLY implementation-dependent, and are probably best - * avoided. - * - * Note that is always deleted when - * is called, so it must be allocated with global operator new. - */ - static int spawn (ACE_THR_FUNC func, - void *arg = 0, - long flags = THR_NEW_LWP | THR_JOINABLE, - ACE_thread_t *t_id = 0, - ACE_hthread_t *t_handle = 0, - long priority = ACE_DEFAULT_THREAD_PRIORITY, - void *stack = 0, - size_t stack_size = ACE_DEFAULT_THREAD_STACKSIZE, - ACE_Thread_Adapter *thread_adapter = 0, - const char** thr_name = 0); - - /** - * Spawn N new threads, which execute @a func with argument @a arg (if - * @a thread_adapter is non-0 then @a func and @a args are ignored and - * are obtained from @a thread_adapter). If @a stack != 0 it is - * assumed to be an array of @a n pointers to the base of the stacks - * to use for the threads being spawned. Likewise, if @a stack_size - * != 0 it is assumed to be an array of @a n values indicating how - * big each of the corresponding @a stacks are. Returns the number - * of threads actually spawned (if this doesn't equal the number - * requested then something has gone wrong and @c errno will - * explain...). - * - * @see spawn() - */ - static size_t spawn_n (size_t n, - ACE_THR_FUNC func, - void *arg = 0, - long flags = THR_NEW_LWP | THR_JOINABLE, - long priority = ACE_DEFAULT_THREAD_PRIORITY, - void *stack[] = 0, - size_t stack_size[] = 0, - ACE_Thread_Adapter *thread_adapter = 0, - const char* thr_name[] = 0); - - /** - * Spawn @a n new threads, which execute @a func with argument @a arg - * (if @a thread_adapter is non-0 then @a func and @a args are ignored - * and are obtained from @a thread_adapter). The thread_ids of - * successfully spawned threads will be placed into the - * buffer (which must be the same size as @a n). If @a stack != 0 it - * is assumed to be an array of @a n pointers to the base of the - * stacks to use for the threads being spawned. If @a stack_size != - * 0 it is assumed to be an array of @a n values indicating how big - * each of the corresponding @a stacks are. If @a thread_handles != 0 - * it is assumed to be an array of @a n thread_handles that will be - * assigned the values of the thread handles being spawned. Returns - * the number of threads actually spawned (if this doesn't equal the - * number requested then something has gone wrong and @c errno will - * explain...). - * - * @see spawn() - */ - static size_t spawn_n (ACE_thread_t thread_ids[], - size_t n, - ACE_THR_FUNC func, - void *arg, - long flags, - long priority = ACE_DEFAULT_THREAD_PRIORITY, - void *stack[] = 0, - size_t stack_size[] = 0, - ACE_hthread_t thread_handles[] = 0, - ACE_Thread_Adapter *thread_adapter = 0, - const char* thr_name[] = 0); - - /** - * Wait for one or more threads to exit and reap their exit status. - * thr_join() returns successfully when the target thread terminates. - * - * @param thread_id is the ACE_thread_t ID of the thread to wait for. - * If @a thread_id is 0, join() waits for any - * undetached thread in the process to terminate - * on platforms that support this capability - * (for example, Solaris). - * @param departed points to a location that is set to the ID of the - * terminated thread if join() returns successfully. - * If @a departed is 0, it is ignored. - * @param status Points to the location that receives the joined - * thread's exit value. If @a status is 0, it is ignored. - * - * @retval 0 for success - * @retval -1 (with errno set) for failure. - */ - static int join (ACE_thread_t thread_id, - ACE_thread_t *departed, - ACE_THR_FUNC_RETURN *status); - - /// Wait for one thread to exit and reap its exit status. - static int join (ACE_hthread_t, - ACE_THR_FUNC_RETURN * = 0); - - /// Continue the execution of a previously suspended thread. - static int resume (ACE_hthread_t); - - /// Suspend the execution of a particular thread. - static int suspend (ACE_hthread_t); - - /// Get the priority of a particular thread. - static int getprio (ACE_hthread_t ht_id, int &priority); - - /// Get the priority and policy of a particular thread. - static int getprio (ACE_hthread_t ht_id, int &priority, int &policy); - - /// Set the priority of a particular thread. - static int setprio (ACE_hthread_t ht_id, int priority, int policy = -1); - - /// Send a signal to the thread. - static int kill (ACE_thread_t, int signum); - - /// Yield the thread to another. - static void yield (void); - - /** - * Return the unique kernel handle of the thread. Note that on - * Win32 this is actually a pseudohandle, which cannot be shared - * with other processes or waited on by threads. To locate the real - * handle, please use the ACE_Thread_Manager::thr_self() method. - */ - static void self (ACE_hthread_t &t_handle); - - /// Return the unique ID of the thread. - static ACE_thread_t self (void); - - /// Exit the current thread and return "status". - /// Should _not_ be called by main thread. - static void exit (ACE_THR_FUNC_RETURN status = 0); - - /// Get the LWP concurrency level of the process. - static int getconcurrency (void); - - /// Set the LWP concurrency level of the process. - static int setconcurrency (int new_level); - - /// Change and/or examine calling thread's signal mask. - static int sigsetmask (int how, - const sigset_t *sigset, - sigset_t *osigset = 0); - - /** - * Allocates a @a keyp that is used to identify data that is specific - * to each thread in the process. The key is global to all threads - * in the process. - */ - static int keycreate (ACE_thread_key_t *keyp, -#if defined (ACE_HAS_THR_C_DEST) - ACE_THR_C_DEST destructor, -#else - ACE_THR_DEST destructor, -#endif /* ACE_HAS_THR_C_DEST */ - void * = 0); - - /// Free up the key so that other threads can reuse it. - static int keyfree (ACE_thread_key_t key); - - /// Bind value to the thread-specific data key, @a key, for the calling - /// thread. - static int setspecific (ACE_thread_key_t key, - void *value); - - /// Stores the current value bound to @a key for the calling thread - /// into the location pointed to by @a valuep. - static int getspecific (ACE_thread_key_t key, - void **valuep); - - /// Disable thread cancellation. - static int disablecancel (struct cancel_state *old_state); - - /// Enable thread cancellation. - static int enablecancel (struct cancel_state *old_state, - int flag); - - /// Set the cancellation state. - static int setcancelstate (struct cancel_state &new_state, - struct cancel_state *old_state); - - /** - * Cancel a thread. - * @note This method is only portable on platforms, such as POSIX pthreads, - * that support thread cancellation. - */ - static int cancel (ACE_thread_t t_id); - - /// Test the cancel. - static void testcancel (void); - -private: - /// Ensure that we don't get instantiated. - ACE_Thread (void); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Thread.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" - -#endif /* ACE_THREAD_H */ diff --git a/externals/ace/Thread.inl b/externals/ace/Thread.inl deleted file mode 100644 index 87e47e13580..00000000000 --- a/externals/ace/Thread.inl +++ /dev/null @@ -1,286 +0,0 @@ -// -*- C++ -*- -// -// $Id: Thread.inl 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/OS_NS_string.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Allocates a that is used to identify data that is specific -// to each thread in the process. The key is global to all threads in -// the process. - -ACE_INLINE int -ACE_Thread::keycreate (ACE_thread_key_t *keyp, -#if defined (ACE_HAS_THR_C_DEST) - ACE_THR_C_DEST destructor, -#else - ACE_THR_DEST destructor, -#endif /* ACE_HAS_THR_C_DEST */ - void *inst) -{ - // ACE_TRACE ("ACE_Thread::keycreate"); - return ACE_OS::thr_keycreate (keyp, destructor, inst); -} - -// Free up the key so that other threads can reuse it. - -ACE_INLINE int -ACE_Thread::keyfree (ACE_thread_key_t key) -{ - ACE_TRACE ("ACE_Thread::keyfree"); - return ACE_OS::thr_keyfree (key); -} - -// Bind value to the thread-specific data key, , for the calling -// thread. - -ACE_INLINE int -ACE_Thread::setspecific (ACE_thread_key_t key, void *value) -{ - // ACE_TRACE ("ACE_Thread::setspecific"); - return ACE_OS::thr_setspecific (key, value); -} - -// Stores the current value bound to for the calling thread -// into the location pointed to by . - -ACE_INLINE int -ACE_Thread::getspecific (ACE_thread_key_t key, void **valuep) -{ - // ACE_TRACE ("ACE_Thread::getspecific"); - return ACE_OS::thr_getspecific (key, valuep); -} - -ACE_INLINE ACE_thread_t -ACE_Thread::self (void) -{ -// ACE_TRACE ("ACE_Thread::self"); - return ACE_OS::thr_self (); -} - -ACE_INLINE void -ACE_Thread::exit (ACE_THR_FUNC_RETURN status) -{ - ACE_TRACE ("ACE_Thread::exit"); - ACE_OS::thr_exit (status); -} - -ACE_INLINE void -ACE_Thread::yield (void) -{ - ACE_TRACE ("ACE_Thread::yield"); - ACE_OS::thr_yield (); -} - -ACE_INLINE int -ACE_Thread::spawn (ACE_THR_FUNC func, - void *arg, - long flags, - ACE_thread_t *t_id, - ACE_hthread_t *t_handle, - long priority, - void *thr_stack, - size_t thr_stack_size, - ACE_Thread_Adapter *thread_adapter, - const char** thr_name) -{ - ACE_TRACE ("ACE_Thread::spawn"); - - return ACE_OS::thr_create (func, - arg, - flags, - t_id, - t_handle, - priority, - thr_stack, - thr_stack_size, - thread_adapter, - thr_name); -} - -ACE_INLINE int -ACE_Thread::resume (ACE_hthread_t t_id) -{ - ACE_TRACE ("ACE_Thread::resume"); - return ACE_OS::thr_continue (t_id); -} - -ACE_INLINE int -ACE_Thread::suspend (ACE_hthread_t t_id) -{ - ACE_TRACE ("ACE_Thread::suspend"); - return ACE_OS::thr_suspend (t_id); -} - -ACE_INLINE int -ACE_Thread::kill (ACE_thread_t t_id, int signum) -{ - ACE_TRACE ("ACE_Thread::kill"); - return ACE_OS::thr_kill (t_id, signum); -} - -ACE_INLINE int -ACE_Thread::join (ACE_thread_t wait_for, - ACE_thread_t *departed, - ACE_THR_FUNC_RETURN *status) -{ - ACE_TRACE ("ACE_Thread::join"); - return ACE_OS::thr_join (wait_for, departed, status); -} - -ACE_INLINE int -ACE_Thread::join (ACE_hthread_t wait_for, - ACE_THR_FUNC_RETURN *status) -{ - ACE_TRACE ("ACE_Thread::join"); - return ACE_OS::thr_join (wait_for, status); -} - -ACE_INLINE int -ACE_Thread::getconcurrency (void) -{ - ACE_TRACE ("ACE_Thread::getconcurrency"); - return ACE_OS::thr_getconcurrency (); -} - -ACE_INLINE int -ACE_Thread::setconcurrency (int new_level) -{ - ACE_TRACE ("ACE_Thread::setconcurrency"); - return ACE_OS::thr_setconcurrency (new_level); -} - -ACE_INLINE int -ACE_Thread::sigsetmask (int how, - const sigset_t *sigset, - sigset_t *osigset) -{ - ACE_TRACE ("ACE_Thread::sigsetmask"); - return ACE_OS::thr_sigsetmask (how, sigset, osigset); -} - -ACE_INLINE int -ACE_Thread::disablecancel (struct cancel_state *old_state) -{ - ACE_TRACE ("ACE_Thread::disablecancel"); - int old_cstate = 0; - int result = ACE_OS::thr_setcancelstate (THR_CANCEL_DISABLE, - &old_cstate); - if (result == 0 && old_state != 0) - { - ACE_OS::memset (old_state, - 0, - sizeof (old_state)); - old_state->cancelstate = old_cstate; - } - - return result; -} - -ACE_INLINE int -ACE_Thread::enablecancel (struct cancel_state *old_state, - int flag) -{ - ACE_TRACE ("ACE_Thread::enablecancel"); - int old_cstate = 0; - int old_ctype = 0; - int result; - - result = ACE_OS::thr_setcancelstate (THR_CANCEL_ENABLE, - &old_cstate); - if (result != 0) - return result; - - result = ACE_OS::thr_setcanceltype (flag, - &old_ctype); - if (result != 0) - return result; - - if (old_state != 0) - { - old_state->cancelstate = old_cstate; - old_state->canceltype = old_ctype; - } - - return 0; -} - -ACE_INLINE int -ACE_Thread::setcancelstate (struct cancel_state &new_state, - struct cancel_state *old_state) -{ - ACE_TRACE ("ACE_Thread::setcancelstate"); - int old_cstate = 0; - int old_ctype = 0; - - if (new_state.cancelstate != 0 - && ACE_OS::thr_setcancelstate (new_state.cancelstate, - &old_cstate) != 0) - return -1; - - if (new_state.canceltype != 0 - && ACE_OS::thr_setcanceltype (new_state.canceltype, - &old_ctype) != 0) - { - int o_cstate; - - ACE_OS::thr_setcancelstate (old_cstate, - &o_cstate); - return -1; - } - - if (old_state != 0) - { - old_state->cancelstate = old_cstate; - old_state->canceltype = old_ctype; - } - - return 0; -} - -ACE_INLINE int -ACE_Thread::cancel (ACE_thread_t t_id) -{ - ACE_TRACE ("ACE_Thread::cancel"); - - return ACE_OS::thr_cancel (t_id); -} - -ACE_INLINE void -ACE_Thread::testcancel (void) -{ - ACE_TRACE ("ACE_Thread::testcancel"); - - ACE_OS::thr_testcancel (); -} - -ACE_INLINE void -ACE_Thread::self (ACE_hthread_t &t_id) -{ -// ACE_TRACE ("ACE_Thread::self"); - ACE_OS::thr_self (t_id); -} - -ACE_INLINE int -ACE_Thread::getprio (ACE_hthread_t ht_id, int &priority) -{ - ACE_TRACE ("ACE_Thread::getprio"); - return ACE_OS::thr_getprio (ht_id, priority); -} - -ACE_INLINE int -ACE_Thread::getprio (ACE_hthread_t ht_id, int &priority, int &policy) -{ - ACE_TRACE ("ACE_Thread::getprio"); - return ACE_OS::thr_getprio (ht_id, priority, policy); -} - -ACE_INLINE int -ACE_Thread::setprio (ACE_hthread_t ht_id, int priority, int policy) -{ - ACE_TRACE ("ACE_Thread::setprio"); - return ACE_OS::thr_setprio (ht_id, priority, policy); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Thread_Adapter.cpp b/externals/ace/Thread_Adapter.cpp deleted file mode 100644 index 9dbad0580b8..00000000000 --- a/externals/ace/Thread_Adapter.cpp +++ /dev/null @@ -1,228 +0,0 @@ -// $Id: Thread_Adapter.cpp 81239 2008-04-04 22:28:48Z iliyan $ - -#include "ace/Thread_Adapter.h" -#include "ace/Thread_Manager.h" -#include "ace/Thread_Exit.h" -#include "ace/Thread_Hook.h" -#include "ace/Object_Manager_Base.h" -#include "ace/Service_Config.h" - -ACE_RCSID (ace, - Thread_Adapter, - "$Id: Thread_Adapter.cpp 81239 2008-04-04 22:28:48Z iliyan $") - -#if !defined (ACE_HAS_INLINED_OSCALLS) -# include "ace/Thread_Adapter.inl" -#endif /* ACE_HAS_INLINED_OSCALLS */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_Thread_Adapter::ACE_Thread_Adapter (ACE_THR_FUNC user_func, - void *arg, - ACE_THR_C_FUNC entry_point, - ACE_Thread_Manager *tm, - ACE_Thread_Descriptor *td -#if defined (ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS) - , ACE_SEH_EXCEPT_HANDLER selector, - ACE_SEH_EXCEPT_HANDLER handler -#endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */ - ) - : ACE_Base_Thread_Adapter ( - user_func - , arg - , entry_point - , td -#if defined (ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS) - , selector - , handler -#endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */ - ) - , thr_mgr_ (tm) -{ - ACE_OS_TRACE ("ACE_Thread_Adapter::ACE_Thread_Adapter"); -} - -ACE_Thread_Adapter::~ACE_Thread_Adapter (void) -{ -} - -ACE_THR_FUNC_RETURN -ACE_Thread_Adapter::invoke (void) -{ - // Inherit the logging features if the parent thread has an - // ACE_Log_Msg instance in thread-specific storage. - this->inherit_log_msg (); - - ACE_Service_Config::current (ACE_Service_Config::global()); - -#if !defined(ACE_USE_THREAD_MANAGER_ADAPTER) - // NOTE: this preprocessor directive should match the one in above - // ACE_Thread_Exit::instance (). With the Xavier Pthreads package, - // the exit_hook in TSS causes a seg fault. So, this works around - // that by creating exit_hook on the stack. -# if defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION) - // Obtain our thread-specific exit hook and make sure that it knows - // how to clean us up! Note that we never use this pointer directly - // (it's stored in thread-specific storage), so it's ok to - // dereference it here and only store it as a reference. - - // Except if it is null, then the thr_mgr() method crashes. - // -jxh - - ACE_Thread_Exit *exit_hook_instance = ACE_Thread_Exit::instance (); - ACE_Thread_Exit_Maybe exit_hook_maybe (exit_hook_instance == 0); - ACE_Thread_Exit *exit_hook_ptr = exit_hook_instance - ? exit_hook_instance - : exit_hook_maybe.instance (); - ACE_Thread_Exit &exit_hook = *exit_hook_ptr; - - if (this->thr_mgr () != 0) - { - // Keep track of the that's associated with this - // . - exit_hook.thr_mgr (this->thr_mgr ()); - } -# else - // Without TSS, create an instance. When this - // function returns, its destructor will be called because the - // object goes out of scope. The drawback with this appraoch is - // that the destructor _won't_ get called if is called. - // So, threads shouldn't exit that way. Instead, they should return - // from . - ACE_Thread_Exit exit_hook; - exit_hook.thr_mgr (this->thr_mgr ()); -# endif /* ACE_HAS_THREAD_SPECIFIC_STORAGE || ACE_HAS_TSS_EMULATION */ - -#endif /* ! ACE_USE_THREAD_MANAGER_ADAPTER */ - - return this->invoke_i (); -} - -ACE_THR_FUNC_RETURN -ACE_Thread_Adapter::invoke_i (void) -{ - // Extract the arguments. - ACE_THR_FUNC func = reinterpret_cast (this->user_func_); - void *arg = this->arg_; - -#if defined (ACE_WIN32) && defined (ACE_HAS_MFC) && (ACE_HAS_MFC != 0) - ACE_OS_Thread_Descriptor *thr_desc = this->thr_desc_; -#endif /* ACE_WIN32 && ACE_HAS_MFC && (ACE_HAS_MFC != 0) */ - - // Delete ourselves since we don't need anymore. Make sure - // not to access anywhere below this point. - delete this; - -#if defined (ACE_NEEDS_LWP_PRIO_SET) - // On SunOS, the LWP priority needs to be set in order to get - // preemption when running in the RT class. This is the ACE way to - // do that . . . - ACE_hthread_t thr_handle; - ACE_OS::thr_self (thr_handle); - int prio; - - // thr_getprio () on the current thread should never fail. - ACE_OS::thr_getprio (thr_handle, prio); - - // ACE_OS::thr_setprio () has the special logic to set the LWP priority, - // if running in the RT class. - ACE_OS::thr_setprio (prio); - -#endif /* ACE_NEEDS_LWP_PRIO_SET */ - - ACE_THR_FUNC_RETURN status = 0; - - ACE_SEH_TRY - { - ACE_SEH_TRY - { - ACE_Thread_Hook *hook = - ACE_OS_Object_Manager::thread_hook (); - - if (hook) - // Invoke the start hook to give the user a chance to - // perform some initialization processing before the - // is invoked. - status = hook->start (func, arg); - else - // Call thread entry point. - status = (*func) (arg); - } - -#if defined (ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS) - ACE_SEH_EXCEPT (ACE_OS_Object_Manager::seh_except_selector ()( - (void *) GetExceptionInformation ())) - { - ACE_OS_Object_Manager::seh_except_handler ()(0); - } -#endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */ - } - - ACE_SEH_FINALLY - { - // If we changed this to 1, change the respective if in - // Task::svc_run to 0. -#if 0 - // Call the close> hook. - if (func == reinterpret_cast ( - ACE_Task_Base::svc_run)) - { - ACE_Task_Base *task_ptr = (ACE_Task_Base *) arg; - ACE_Thread_Manager *thr_mgr_ptr = task_ptr->thr_mgr (); - - // This calls the Task->close () hook. - task_ptr->cleanup (task_ptr, 0); - - // This prevents a second invocation of the cleanup code - // (called later by . - thr_mgr_ptr->at_exit (task_ptr, 0, 0); - } -#endif /* 0 */ - -#if defined (ACE_WIN32) || defined (ACE_HAS_TSS_EMULATION) -# if defined (ACE_WIN32) && defined (ACE_HAS_MFC) && (ACE_HAS_MFC != 0) - int using_afx = -1; - if (thr_desc) - using_afx = ACE_BIT_ENABLED (thr_desc->flags (), THR_USE_AFX); -# endif /* ACE_WIN32 && ACE_HAS_MFC && (ACE_HAS_MFC != 0) */ - // Call TSS destructors. - ACE_OS::cleanup_tss (0 /* not main thread */); - -# if defined (ACE_WIN32) - // Exit the thread. Allow CWinThread-destructor to be invoked - // from AfxEndThread. _endthreadex will be called from - // AfxEndThread so don't exit the thread now if we are running - // an MFC thread. -# if defined (ACE_HAS_MFC) && (ACE_HAS_MFC != 0) - if (using_afx != -1) - { - if (using_afx) - ::AfxEndThread ((DWORD) status); - else - ACE_ENDTHREADEX (status); - } - else - { - // Not spawned by ACE_Thread_Manager, use the old buggy - // version. You should seriously consider using - // ACE_Thread_Manager to spawn threads. The following code - // is know to cause some problem. - CWinThread *pThread = ::AfxGetThread (); - - if (!pThread || pThread->m_nThreadID != ACE_OS::thr_self ()) - ACE_ENDTHREADEX (status); - else - ::AfxEndThread ((DWORD)status); - } -# else - - ACE_ENDTHREADEX (status); -# endif /* ACE_HAS_MFC && ACE_HAS_MFS != 0*/ -# endif /* ACE_WIN32 */ -#endif /* ACE_WIN32 || ACE_HAS_TSS_EMULATION */ - } - - return status; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Thread_Adapter.h b/externals/ace/Thread_Adapter.h deleted file mode 100644 index 8f1f259eff3..00000000000 --- a/externals/ace/Thread_Adapter.h +++ /dev/null @@ -1,100 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Thread_Adapter.h - * - * $Id: Thread_Adapter.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Carlos O'Ryan - */ -//============================================================================= - -#ifndef ACE_THREAD_ADAPTER_H -#define ACE_THREAD_ADAPTER_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Base_Thread_Adapter.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Forward decl. -class ACE_Thread_Manager; -class ACE_Thread_Descriptor; - -/** - * @class ACE_Thread_Adapter - * - * @brief Converts a C++ function into a function that - * can be called from a thread creation routine - * (e.g., pthread_create() or _beginthreadex()) that expects an - * extern "C" entry point. This class also makes it possible to - * transparently provide hooks to register a thread with an - * ACE_Thread_Manager. - * - * This class is used in ACE_OS::thr_create(). In general, the - * thread that creates an object of this class is different from - * the thread that calls @c invoke() on this object. Therefore, - * the @c invoke() method is responsible for deleting itself. - */ -class ACE_Export ACE_Thread_Adapter : public ACE_Base_Thread_Adapter -{ -public: - /// Constructor. - ACE_Thread_Adapter (ACE_THR_FUNC user_func, - void *arg, - ACE_THR_C_FUNC entry_point = (ACE_THR_C_FUNC) ACE_THREAD_ADAPTER_NAME, - ACE_Thread_Manager *thr_mgr = 0, - ACE_Thread_Descriptor *td = 0 -# if defined (ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS) - , ACE_SEH_EXCEPT_HANDLER selector = 0, - ACE_SEH_EXCEPT_HANDLER handler = 0 -# endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */ - ); - - /** - * Execute the with the . This function deletes - * @c this, thereby rendering the object useless after the call - * returns. - */ - virtual ACE_THR_FUNC_RETURN invoke (void); - - /// Accessor for the optional ACE_Thread_Manager. - ACE_Thread_Manager *thr_mgr (void); - -protected: - - /// Ensure that this object must be allocated on the heap. - ~ACE_Thread_Adapter (void); - -private: - - /// Called by invoke, mainly here to separate the SEH stuff because - /// SEH on Win32 doesn't compile with local vars with destructors. - virtual ACE_THR_FUNC_RETURN invoke_i (void); - -private: - - /// Optional thread manager. - ACE_Thread_Manager *thr_mgr_; - -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -# if defined (ACE_HAS_INLINED_OSCALLS) -# if defined (ACE_INLINE) -# undef ACE_INLINE -# endif /* ACE_INLINE */ -# define ACE_INLINE inline -# include "ace/Thread_Adapter.inl" -# endif /* ACE_HAS_INLINED_OSCALLS */ - -#include /**/ "ace/post.h" -#endif /* ACE_THREAD_ADAPTER_H */ diff --git a/externals/ace/Thread_Adapter.inl b/externals/ace/Thread_Adapter.inl deleted file mode 100644 index 6def13be5ab..00000000000 --- a/externals/ace/Thread_Adapter.inl +++ /dev/null @@ -1,13 +0,0 @@ -// -*- C++ -*- -// -// $Id: Thread_Adapter.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE ACE_Thread_Manager * -ACE_Thread_Adapter::thr_mgr (void) -{ - return this->thr_mgr_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Thread_Control.cpp b/externals/ace/Thread_Control.cpp deleted file mode 100644 index 51d0f4c18eb..00000000000 --- a/externals/ace/Thread_Control.cpp +++ /dev/null @@ -1,96 +0,0 @@ -// $Id: Thread_Control.cpp 80826 2008-03-04 14:51:23Z wotte $ - -// -#include "ace/config-all.h" -#if defined (ACE_LEGACY_MODE) -// This silly include breaks a cycle when compiling in backwards -// compatibility mode -# include "ace/Thread_Exit.h" -#endif /* ACE_LEGACY_MODE */ -// - -#include "ace/Thread_Control.h" -#include "ace/Thread_Manager.h" - -ACE_RCSID(ace, Thread_Control, "$Id: Thread_Control.cpp 80826 2008-03-04 14:51:23Z wotte $") - -#if !defined (ACE_HAS_INLINED_OSCALLS) -# include "ace/Thread_Control.inl" -#endif /* ACE_HAS_INLINED_OSCALLS */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -void -ACE_Thread_Control::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_OS_TRACE ("ACE_Thread_Control::dump"); -#endif /* ACE_HAS_DUMP */ -} - -int -ACE_Thread_Control::insert (ACE_Thread_Manager *tm, int insert) -{ - ACE_OS_TRACE ("ACE_Thread_Control::insert"); - - ACE_hthread_t t_id; - ACE_OS::thr_self (t_id); - this->tm_ = tm; - - if (insert) - return this->tm_->insert_thr (ACE_OS::thr_self (), t_id); - else - return 0; -} - -// Initialize the thread controller. - -ACE_Thread_Control::ACE_Thread_Control (ACE_Thread_Manager *t, - int insert) - : tm_ (t), - status_ (0) -{ - ACE_OS_TRACE ("ACE_Thread_Control::ACE_Thread_Control"); - - if (this->tm_ != 0 && insert) - { - ACE_hthread_t t_id; - ACE_OS::thr_self (t_id); - this->tm_->insert_thr (ACE_OS::thr_self (), t_id); - } -} - -// Automatically kill thread on exit. - -ACE_Thread_Control::~ACE_Thread_Control (void) -{ - ACE_OS_TRACE ("ACE_Thread_Control::~ACE_Thread_Control"); - -#if defined (ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS) || defined (ACE_HAS_TSS_EMULATION) || defined (ACE_WIN32) - this->exit (this->status_, 0); -#else - this->exit (this->status_, 1); -#endif /* ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS */ -} - -// Exit from thread (but clean up first). - -ACE_THR_FUNC_RETURN -ACE_Thread_Control::exit (ACE_THR_FUNC_RETURN exit_status, int do_thr_exit) -{ - ACE_OS_TRACE ("ACE_Thread_Control::exit"); - - if (this->tm_ != 0) - return this->tm_->exit (exit_status, do_thr_exit); - else - { -#if !defined (ACE_HAS_TSS_EMULATION) - // With ACE_HAS_TSS_EMULATION, we let ACE_Thread_Adapter::invoke () - // exit the thread after cleaning up TSS. - ACE_OS::thr_exit (exit_status); -#endif /* ! ACE_HAS_TSS_EMULATION */ - return 0; - } -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Thread_Control.h b/externals/ace/Thread_Control.h deleted file mode 100644 index 3eb5185c84c..00000000000 --- a/externals/ace/Thread_Control.h +++ /dev/null @@ -1,102 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Thread_Control.h - * - * $Id: Thread_Control.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Carlos O'Ryan - */ -//============================================================================= - - -#ifndef ACE_THREAD_CONTROL_H -#define ACE_THREAD_CONTROL_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -class ACE_Thread_Manager; - -/** - * @class ACE_Thread_Control - * - * @brief Used to keep track of a thread's activities within its entry - * point function. - * - * A ACE_Thread_Manager uses this class to ensure that threads - * it spawns automatically register and unregister themselves - * with it. - * This class can be stored in thread-specific storage using the - * ACE_TSS wrapper. When a thread exits the - * function deletes this object, thereby - * ensuring that it gets removed from its associated - * ACE_Thread_Manager. - */ -class ACE_Export ACE_Thread_Control -{ -public: - /// Initialize the thread control object. If @a insert != 0, then - /// register the thread with the Thread_Manager. - ACE_Thread_Control (ACE_Thread_Manager *tm = 0, - int insert = 0); - - /// Remove the thread from its associated and exit - /// the thread if is enabled. - ~ACE_Thread_Control (void); - - /// Remove this thread from its associated ACE_Thread_Manager and exit - /// the thread if @a do_thr_exit is enabled. - ACE_THR_FUNC_RETURN exit (ACE_THR_FUNC_RETURN status, - int do_thr_exit); - - /// Store the and use it to register ourselves for - /// correct shutdown. - int insert (ACE_Thread_Manager *tm, int insert = 0); - - /// Returns the current . - ACE_Thread_Manager *thr_mgr (void); - - /// Atomically set a new and return the old - /// . - ACE_Thread_Manager *thr_mgr (ACE_Thread_Manager *); - - /// Set the exit status (and return existing status). - ACE_THR_FUNC_RETURN status (ACE_THR_FUNC_RETURN status); - - /// Get the current exit status. - ACE_THR_FUNC_RETURN status (void); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - /// Pointer to the thread manager for this block of code. - ACE_Thread_Manager *tm_; - - /// Keeps track of the exit status for the thread. - ACE_THR_FUNC_RETURN status_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -# if defined (ACE_HAS_INLINED_OSCALLS) -# if defined (ACE_INLINE) -# undef ACE_INLINE -# endif /* ACE_INLINE */ -# define ACE_INLINE inline -# include "ace/Thread_Control.inl" -# endif /* ACE_HAS_INLINED_OSCALLS */ - -#include /**/ "ace/post.h" -#endif /* ACE_THREAD_CONTROL_H */ diff --git a/externals/ace/Thread_Control.inl b/externals/ace/Thread_Control.inl deleted file mode 100644 index 6ebd3ac2c56..00000000000 --- a/externals/ace/Thread_Control.inl +++ /dev/null @@ -1,46 +0,0 @@ -// -*- C++ -*- -// -// $Id: Thread_Control.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Set the exit status. - -ACE_INLINE ACE_THR_FUNC_RETURN -ACE_Thread_Control::status (ACE_THR_FUNC_RETURN s) -{ - ACE_OS_TRACE ("ACE_Thread_Control::status"); - return this->status_ = s; -} - -// Get the exit status. - -ACE_INLINE ACE_THR_FUNC_RETURN -ACE_Thread_Control::status (void) -{ - ACE_OS_TRACE ("ACE_Thread_Control::status"); - return this->status_; -} - -// Returns the current . - -ACE_INLINE ACE_Thread_Manager * -ACE_Thread_Control::thr_mgr (void) -{ - ACE_OS_TRACE ("ACE_Thread_Control::thr_mgr"); - return this->tm_; -} - -// Atomically set a new and return the old -// . - -ACE_INLINE ACE_Thread_Manager * -ACE_Thread_Control::thr_mgr (ACE_Thread_Manager *tm) -{ - ACE_OS_TRACE ("ACE_Thread_Control::thr_mgr"); - ACE_Thread_Manager *o_tm = this->tm_; - this->tm_ = tm; - return o_tm; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Thread_Exit.cpp b/externals/ace/Thread_Exit.cpp deleted file mode 100644 index cc6a8620cbe..00000000000 --- a/externals/ace/Thread_Exit.cpp +++ /dev/null @@ -1,123 +0,0 @@ -// $Id: Thread_Exit.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Thread_Exit.h" -#include "ace/Managed_Object.h" -#include "ace/Thread_Manager.h" -#include "ace/Guard_T.h" - -ACE_RCSID(ace, Thread_Exit, "$Id: Thread_Exit.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -bool ACE_Thread_Exit::is_constructed_ = false; - -void -ACE_Thread_Exit::cleanup (void *instance) -{ - ACE_OS_TRACE ("ACE_Thread_Exit::cleanup"); - - delete (ACE_TSS_TYPE (ACE_Thread_Exit) *) instance; - - // Set the thr_exit_ static to null to keep things from crashing if - // ACE::fini() is enabled here. - ACE_Thread_Manager::thr_exit_ = 0; - - ACE_Thread_Exit::is_constructed_ = false; - // All TSS objects have been destroyed. Reset this flag so - // ACE_Thread_Exit singleton can be created again. -} - -// NOTE: this preprocessor directive should match the one in -// ACE_Task_Base::svc_run () below. This prevents the two statics -// from being defined. - -ACE_Thread_Exit * -ACE_Thread_Exit::instance (void) -{ -#if defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION) - ACE_OS_TRACE ("ACE_Thread_Exit::instance"); - - // Determines if we were dynamically allocated. - static ACE_TSS_TYPE (ACE_Thread_Exit) * volatile instance_; - - // Implement the Double Check pattern. - - if (!ACE_Thread_Exit::is_constructed_) - { - ACE_MT (ACE_Thread_Mutex *lock = - ACE_Managed_Object::get_preallocated_object - (ACE_Object_Manager::ACE_THREAD_EXIT_LOCK); - ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, *lock, 0)); - - if (!ACE_Thread_Exit::is_constructed_) - { - ACE_NEW_RETURN (instance_, - ACE_TSS_TYPE (ACE_Thread_Exit), - 0); - - ACE_Thread_Exit::is_constructed_ = true; - - ACE_Thread_Manager::set_thr_exit (instance_); - } - } - - return ACE_TSS_GET (instance_, ACE_Thread_Exit); -#else - return 0; -#endif /* ACE_HAS_THREAD_SPECIFIC_STORAGE || ACE_HAS_TSS_EMULATION */ -} - -// Grab hold of the Task * so that we can close() it in the -// destructor. - -ACE_Thread_Exit::ACE_Thread_Exit (void) -{ - ACE_OS_TRACE ("ACE_Thread_Exit::ACE_Thread_Exit"); -} - -// Set the this pointer... - -void -ACE_Thread_Exit::thr_mgr (ACE_Thread_Manager *tm) -{ - ACE_OS_TRACE ("ACE_Thread_Exit::thr_mgr"); - - if (tm != 0) - this->thread_control_.insert (tm, 0); -} - -// When this object is destroyed the Task is automatically closed -// down! - -ACE_Thread_Exit::~ACE_Thread_Exit (void) -{ - ACE_OS_TRACE ("ACE_Thread_Exit::~ACE_Thread_Exit"); -} - -ACE_Thread_Exit_Maybe::ACE_Thread_Exit_Maybe (int flag) - : instance_ (0) -{ - if (flag) - { - ACE_NEW (instance_, ACE_Thread_Exit); - } -} - -ACE_Thread_Exit_Maybe::~ACE_Thread_Exit_Maybe (void) -{ - delete this->instance_; -} - -ACE_Thread_Exit * -ACE_Thread_Exit_Maybe::operator -> (void) const -{ - return this->instance_; -} - -ACE_Thread_Exit * -ACE_Thread_Exit_Maybe::instance (void) const -{ - return this->instance_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Thread_Exit.h b/externals/ace/Thread_Exit.h deleted file mode 100644 index 5b614e2e807..00000000000 --- a/externals/ace/Thread_Exit.h +++ /dev/null @@ -1,111 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Thread_Exit.h - * - * $Id: Thread_Exit.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Carlos O'Ryan - */ -//============================================================================= - - -#ifndef ACE_THREAD_EXIT_H -#define ACE_THREAD_EXIT_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Thread_Control.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Thread_Exit - * - * @brief Keep exit information for a Thread in thread specific storage. - * so that the thread-specific exit hooks will get called no - * matter how the thread exits (e.g., via , C++ - * or Win32 exception, "falling off the end" of the thread entry - * point function, etc.). - * - * This clever little helper class is stored in thread-specific - * storage using the wrapper. When a thread exits the - * function deletes this object, thereby - * closing it down gracefully. - */ -class ACE_Export ACE_Thread_Exit -{ -public: - /// Capture the Thread that will be cleaned up automatically. - ACE_Thread_Exit (void); - - /// Set the ACE_Thread_Manager. - void thr_mgr (ACE_Thread_Manager *tm); - - /// Destructor calls the thread-specific exit hooks when a thread - /// exits. - ~ACE_Thread_Exit (void); - - /// Singleton access point. - static ACE_Thread_Exit *instance (void); - - /// Cleanup method, used by the ACE_Object_Manager to destroy the - /// singleton. - static void cleanup (void *instance); - -private: - /// Automatically add/remove the thread from the - /// ACE_Thread_Manager. - ACE_Thread_Control thread_control_; - - /** - * Used to detect whether we should create a new instance (or not) - * within the instance method -- we don't trust the instance_ ptr - * because the destructor may have run (if ACE::fini() was called). - * See bug #526. - * We don't follow the singleton pattern due to dependency issues. - */ - static bool is_constructed_; -}; - -/** - * @class ACE_Thread_Exit_Maybe - * - * @brief A version of ACE_Thread_Exit that is created dynamically - * under the hood if the flag is set to TRUE. - * - * Allows the appearance of a "smart pointer", but is not - * always created. - */ -class ACE_Export ACE_Thread_Exit_Maybe -{ -public: - /// Don't create an ACE_Thread_Exit instance by default. - ACE_Thread_Exit_Maybe (int flag = 0); - - /// Destroys the underlying ACE_Thread_Exit instance if it exists. - ~ACE_Thread_Exit_Maybe (void); - - /// Delegates to underlying instance. - ACE_Thread_Exit * operator -> (void) const; - - /// Returns the underlying instance. - ACE_Thread_Exit * instance (void) const; - -private: - - /// Holds the underlying instance. - ACE_Thread_Exit *instance_; - -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" -#endif /* ACE_THREAD_EXIT_H */ diff --git a/externals/ace/Thread_Hook.cpp b/externals/ace/Thread_Hook.cpp deleted file mode 100644 index 79d937f9ff5..00000000000 --- a/externals/ace/Thread_Hook.cpp +++ /dev/null @@ -1,33 +0,0 @@ -// $Id: Thread_Hook.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Thread_Hook.h" -#include "ace/Object_Manager_Base.h" - -ACE_RCSID(ace, Thread_Hook, "$Id: Thread_Hook.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_Thread_Hook::~ACE_Thread_Hook () -{ -} - -ACE_THR_FUNC_RETURN -ACE_Thread_Hook::start (ACE_THR_FUNC func, - void *arg) -{ - return (func) (arg); -} - -ACE_Thread_Hook * -ACE_Thread_Hook::thread_hook (ACE_Thread_Hook *hook) -{ - return ACE_OS_Object_Manager::thread_hook (hook); -} - -ACE_Thread_Hook * -ACE_Thread_Hook::thread_hook (void) -{ - return ACE_OS_Object_Manager::thread_hook (); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Thread_Hook.h b/externals/ace/Thread_Hook.h deleted file mode 100644 index 7bc3bcce492..00000000000 --- a/externals/ace/Thread_Hook.h +++ /dev/null @@ -1,65 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Thread_Hook.h - * - * $Id: Thread_Hook.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Carlos O'Ryan - */ -//============================================================================= - - -#ifndef ACE_THREAD_HOOK_H -#define ACE_THREAD_HOOK_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include /**/ "ace/ACE_export.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Thread_Hook - * - * @brief This class makes it possible to provide user-defined "start" - * hooks that are called before the thread entry point function - * is invoked. - */ -class ACE_Export ACE_Thread_Hook -{ - -public: - - /// Destructor. - virtual ~ACE_Thread_Hook (void); - - /** - * This method can be overridden in a subclass to customize this - * pre-function call "hook" invocation that can perform - * initialization processing before the thread entry point @a func - * method is called back. The @a func and @a arg passed into the - * start hook are the same as those passed by the application that - * spawned the thread. - */ - virtual ACE_THR_FUNC_RETURN start (ACE_THR_FUNC func, - void *arg); - - /// sets the system wide thread hook, returns the previous thread - /// hook or 0 if none is set. - static ACE_Thread_Hook *thread_hook (ACE_Thread_Hook *hook); - - /// Returns the current system thread hook. - static ACE_Thread_Hook *thread_hook (void); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" -#endif /* ACE_THREAD_HOOK_H */ diff --git a/externals/ace/Thread_Manager.cpp b/externals/ace/Thread_Manager.cpp deleted file mode 100644 index 4737dcbfaad..00000000000 --- a/externals/ace/Thread_Manager.cpp +++ /dev/null @@ -1,2223 +0,0 @@ -// $Id: Thread_Manager.cpp 85341 2009-05-14 11:07:37Z johnnyw $ - -#include "ace/TSS_T.h" -#include "ace/Thread_Manager.h" -#include "ace/Dynamic.h" -#include "ace/Object_Manager.h" -#include "ace/Singleton.h" -#include "ace/Auto_Ptr.h" -#include "ace/Guard_T.h" -#include "ace/Time_Value.h" -#include "ace/OS_NS_sys_time.h" -#include "ace/Truncate.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Thread_Manager.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID (ace, - Thread_Manager, - "$Id: Thread_Manager.cpp 85341 2009-05-14 11:07:37Z johnnyw $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_At_Thread_Exit::~ACE_At_Thread_Exit (void) -{ - this->do_apply (); -} - -ACE_At_Thread_Exit_Func::~ACE_At_Thread_Exit_Func (void) -{ - this->do_apply (); -} - -void -ACE_At_Thread_Exit_Func::apply (void) -{ - this->func_ (this->object_, this->param_); -} - -ACE_ALLOC_HOOK_DEFINE(ACE_Thread_Control) -ACE_ALLOC_HOOK_DEFINE(ACE_Thread_Manager) - -#if ! defined (ACE_THREAD_MANAGER_LACKS_STATICS) -// Process-wide Thread Manager. -ACE_Thread_Manager *ACE_Thread_Manager::thr_mgr_ = 0; - -// Controls whether the Thread_Manager is deleted when we shut down -// (we can only delete it safely if we created it!) -bool ACE_Thread_Manager::delete_thr_mgr_ = false; -#endif /* ! defined (ACE_THREAD_MANAGER_LACKS_STATICS) */ - -ACE_TSS_TYPE (ACE_Thread_Exit) *ACE_Thread_Manager::thr_exit_ = 0; - -int -ACE_Thread_Manager::set_thr_exit (ACE_TSS_TYPE (ACE_Thread_Exit) *ptr) -{ - if (ACE_Thread_Manager::thr_exit_ == 0) - ACE_Thread_Manager::thr_exit_ = ptr; - else - return -1; - return 0; -} - -void -ACE_Thread_Manager::dump (void) -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Thread_Manager::dump"); - // Cast away const-ness of this in order to use its non-const lock_. - ACE_MT (ACE_GUARD (ACE_Thread_Mutex, ace_mon, - ((ACE_Thread_Manager *) this)->lock_)); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ngrp_id_ = %d"), this->grp_id_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ncurrent_count_ = %d"), this->thr_list_.size ())); - - for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); - !iter.done (); - iter.advance ()) - { - iter.next ()->dump (); - } - - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -ACE_Thread_Descriptor::~ACE_Thread_Descriptor (void) -{ - delete this->sync_; -} - -void -ACE_Thread_Descriptor::at_pop (int apply) -{ - ACE_TRACE ("ACE_Thread_Descriptor::at_pop"); - // Get first at from at_exit_list - ACE_At_Thread_Exit* at = this->at_exit_list_; - // Remove at from at_exit list - this->at_exit_list_ = at->next_; - // Apply if required - if (apply) - { - at->apply (); - // Do the apply method - at->was_applied (true); - // Mark at has been applied to avoid double apply from - // at destructor - } - // If at is not owner delete at. - if (!at->is_owner ()) - delete at; -} - -void -ACE_Thread_Descriptor::at_push (ACE_At_Thread_Exit* cleanup, bool is_owner) -{ - ACE_TRACE ("ACE_Thread_Descriptor::at_push"); - cleanup->is_owner (is_owner); - cleanup->td_ = this; - cleanup->next_ = at_exit_list_; - at_exit_list_ = cleanup; -} - -int -ACE_Thread_Descriptor::at_exit (ACE_At_Thread_Exit& cleanup) -{ - ACE_TRACE ("ACE_Thread_Descriptor::at_exit"); - at_push (&cleanup, 1); - return 0; -} - -int -ACE_Thread_Descriptor::at_exit (ACE_At_Thread_Exit* cleanup) -{ - ACE_TRACE ("ACE_Thread_Descriptor::at_exit"); - if (cleanup==0) - return -1; - else - { - this->at_push (cleanup); - return 0; - } -} - -void -ACE_Thread_Descriptor::do_at_exit () -{ - ACE_TRACE ("ACE_Thread_Descriptor::do_at_exit"); - while (at_exit_list_!=0) - this->at_pop (); -} - -void -ACE_Thread_Descriptor::terminate () -{ - ACE_TRACE ("ACE_Thread_Descriptor::terminate"); - - if (!terminated_) - { - ACE_Log_Msg* log_msg = this->log_msg_; - terminated_ = true; - // Run at_exit hooks - this->do_at_exit (); - // We must remove Thread_Descriptor from Thread_Manager list - if (this->tm_ != 0) - { - int close_handle = 0; - -#if !defined (ACE_HAS_VXTHREADS) - // Threads created with THR_DAEMON shouldn't exist here, but - // just to be safe, let's put it here. - - if (ACE_BIT_DISABLED (this->thr_state_, ACE_Thread_Manager::ACE_THR_JOINING)) - { - if (ACE_BIT_DISABLED (this->flags_, THR_DETACHED | THR_DAEMON) - || ACE_BIT_ENABLED (this->flags_, THR_JOINABLE)) - { - // Mark thread as terminated. - ACE_SET_BITS (this->thr_state_, ACE_Thread_Manager::ACE_THR_TERMINATED); - tm_->register_as_terminated (this); - // Must copy the information here because td will be - // "freed" below. - } -#if defined (ACE_WIN32) - else - { - close_handle = 1; - } -#endif /* ACE_WIN32 */ - } -#endif /* !ACE_HAS_VXTHREADS */ - - // Remove thread descriptor from the table. - if (this->tm_ != 0) - tm_->remove_thr (this, close_handle); - } - - // Check if we need delete ACE_Log_Msg instance - // If ACE_TSS_cleanup was not executed first log_msg == 0 - if (log_msg == 0) - { - // Only inform to ACE_TSS_cleanup that it must delete the log instance - // setting ACE_LOG_MSG thr_desc to 0. - ACE_LOG_MSG->thr_desc (0); - } - else - { - // Thread_Descriptor is the owner of the Log_Msg instance!! - // deleted. - this->log_msg_ = 0; - delete log_msg; - } - } -} - -int -ACE_Thread_Descriptor::at_exit (void *object, - ACE_CLEANUP_FUNC cleanup_hook, - void *param) -{ - ACE_TRACE ("ACE_Thread_Descriptor::at_exit"); - // To keep compatibility, when cleanup_hook is null really is a at_pop - // without apply. - if (cleanup_hook == 0) - { - if (this->at_exit_list_!= 0) - this->at_pop(0); - } - else - { - ACE_At_Thread_Exit* cleanup = 0; - ACE_NEW_RETURN (cleanup, - ACE_At_Thread_Exit_Func (object, - cleanup_hook, - param), - -1); - this->at_push (cleanup); - } - return 0; -} - -void -ACE_Thread_Descriptor::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Thread_Descriptor::dump"); - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nthr_id_ = %d"), this->thr_id_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nthr_handle_ = %d"), this->thr_handle_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ngrp_id_ = %d"), this->grp_id_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nthr_state_ = %d"), this->thr_state_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nflags_ = %x\n"), this->flags_)); - - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -ACE_Thread_Descriptor::ACE_Thread_Descriptor (void) - : log_msg_ (0), - at_exit_list_ (0), - terminated_ (false) -{ - ACE_TRACE ("ACE_Thread_Descriptor::ACE_Thread_Descriptor"); - ACE_NEW (this->sync_, - ACE_DEFAULT_THREAD_MANAGER_LOCK); -} - -void -ACE_Thread_Descriptor::acquire_release (void) -{ - // Just try to acquire the lock then release it. -#if defined (ACE_THREAD_MANAGER_USES_SAFE_SPAWN) - if (ACE_BIT_DISABLED (this->thr_state_, ACE_Thread_Manager::ACE_THR_SPAWNED)) -#endif /* ACE_THREAD_MANAGER_USES_SAFE_SPAWN */ - { - this->sync_->acquire (); - // Acquire the lock before removing from the thread table. If - // this thread is in the table already, it should simply acquire the - // lock easily. - - // Once we get the lock, we must have registered. - ACE_ASSERT (ACE_BIT_ENABLED (this->thr_state_, ACE_Thread_Manager::ACE_THR_SPAWNED)); - - this->sync_->release (); - // Release the lock before putting it back to freelist. - } -} - -void -ACE_Thread_Descriptor::acquire (void) -{ - // Just try to acquire the lock then release it. -#if defined (ACE_THREAD_MANAGER_USES_SAFE_SPAWN) - if (ACE_BIT_DISABLED (this->thr_state_, ACE_Thread_Manager::ACE_THR_SPAWNED)) -#endif /* ACE_THREAD_MANAGER_USES_SAFE_SPAWN */ - { - this->sync_->acquire (); - } -} - -void -ACE_Thread_Descriptor::release (void) -{ - // Just try to acquire the lock then release it. -#if defined (ACE_THREAD_MANAGER_USES_SAFE_SPAWN) - if (ACE_BIT_DISABLED (this->thr_state_, ACE_Thread_Manager::ACE_THR_SPAWNED)) -#endif /* ACE_THREAD_MANAGER_USES_SAFE_SPAWN */ - { - this->sync_->release (); - // Release the lock before putting it back to freelist. - } -} - -// The following macro simplifies subsequence code. -#define ACE_FIND(OP,INDEX) \ - ACE_Thread_Descriptor *INDEX = OP; \ - -ACE_Thread_Descriptor * -ACE_Thread_Manager::thread_descriptor (ACE_thread_t thr_id) -{ - ACE_TRACE ("ACE_Thread_Manager::thread_descriptor"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0)); - - ACE_FIND (this->find_thread (thr_id), ptr); - return ptr; -} - -ACE_Thread_Descriptor * -ACE_Thread_Manager::hthread_descriptor (ACE_hthread_t thr_handle) -{ - ACE_TRACE ("ACE_Thread_Manager::hthread_descriptor"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0)); - - ACE_FIND (this->find_hthread (thr_handle), ptr); - return ptr; -} - -// Return the thread descriptor (indexed by ACE_hthread_t). - -int -ACE_Thread_Manager::thr_self (ACE_hthread_t &self) -{ - ACE_TRACE ("ACE_Thread_Manager::thr_self"); - - ACE_Thread_Descriptor *desc = - this->thread_desc_self (); - - if (desc == 0) - return -1; - else - desc->self (self); - - return 0; -} - -// Initialize the synchronization variables. - -ACE_Thread_Manager::ACE_Thread_Manager (size_t prealloc, - size_t lwm, - size_t inc, - size_t hwm) - : grp_id_ (1), - automatic_wait_ (1) -#if defined (ACE_HAS_THREADS) - , zero_cond_ (lock_) -#endif /* ACE_HAS_THREADS */ - , thread_desc_freelist_ (ACE_FREE_LIST_WITH_POOL, - prealloc, lwm, hwm, inc) -{ - ACE_TRACE ("ACE_Thread_Manager::ACE_Thread_Manager"); -} - -#if ! defined (ACE_THREAD_MANAGER_LACKS_STATICS) -ACE_Thread_Manager * -ACE_Thread_Manager::instance (void) -{ - ACE_TRACE ("ACE_Thread_Manager::instance"); - - if (ACE_Thread_Manager::thr_mgr_ == 0) - { - // Perform Double-Checked Locking Optimization. - ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, - *ACE_Static_Object_Lock::instance (), 0)); - - if (ACE_Thread_Manager::thr_mgr_ == 0) - { - ACE_NEW_RETURN (ACE_Thread_Manager::thr_mgr_, - ACE_Thread_Manager, - 0); - ACE_Thread_Manager::delete_thr_mgr_ = true; - } - } - - return ACE_Thread_Manager::thr_mgr_; -} - -ACE_Thread_Manager * -ACE_Thread_Manager::instance (ACE_Thread_Manager *tm) -{ - ACE_TRACE ("ACE_Thread_Manager::instance"); - ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon, - *ACE_Static_Object_Lock::instance (), 0)); - - ACE_Thread_Manager *t = ACE_Thread_Manager::thr_mgr_; - // We can't safely delete it since we don't know who created it! - ACE_Thread_Manager::delete_thr_mgr_ = false; - - ACE_Thread_Manager::thr_mgr_ = tm; - return t; -} - -void -ACE_Thread_Manager::close_singleton (void) -{ - ACE_TRACE ("ACE_Thread_Manager::close_singleton"); - - ACE_MT (ACE_GUARD (ACE_Recursive_Thread_Mutex, ace_mon, - *ACE_Static_Object_Lock::instance ())); - - if (ACE_Thread_Manager::delete_thr_mgr_) - { - // First, we clean up the thread descriptor list. - ACE_Thread_Manager::thr_mgr_->close (); - delete ACE_Thread_Manager::thr_mgr_; - ACE_Thread_Manager::thr_mgr_ = 0; - ACE_Thread_Manager::delete_thr_mgr_ = false; - } - - ACE_Thread_Exit::cleanup (ACE_Thread_Manager::thr_exit_); -} -#endif /* ! defined (ACE_THREAD_MANAGER_LACKS_STATICS) */ - -// Close up and release all resources. - -int -ACE_Thread_Manager::close () -{ - ACE_TRACE ("ACE_Thread_Manager::close"); - - // Clean up the thread descriptor list. - if (this->automatic_wait_) - this->wait (0, 1); - else - { - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - - this->remove_thr_all (); - } - - return 0; -} - -ACE_Thread_Manager::~ACE_Thread_Manager (void) -{ - ACE_TRACE ("ACE_Thread_Manager::~ACE_Thread_Manager"); - this->close (); -} - - -// Run the entry point for thread spawned under the control of the -// . This must be an extern "C" to make certain -// compilers happy... -// -// The interaction with and -// works like this, with -// ACE_HAS_THREAD_SPECIFIC_STORAGE or ACE_HAS_TSS_EMULATION: -// -// o Every thread in the is run with -// . -// -// o retrieves the singleton -// instance from . -// The singleton gets created in thread-specific storage -// in the first call to that function. The key point is that the -// instance is in thread-specific storage. -// -// o A thread can exit by various means, such as , C++ -// or Win32 exception, "falling off the end" of the thread entry -// point function, etc. -// -// o If you follow this so far, now it gets really fun . . . -// When the thread-specific storage (for the thread that -// is being destroyed) is cleaned up, the OS threads package (or -// the ACE emulation of thread-specific storage) will destroy any -// objects that are in thread-specific storage. It has a list of -// them, and just walks down the list and destroys each one. -// -// o That's where the ACE_Thread_Exit destructor gets called. - -#if defined(ACE_USE_THREAD_MANAGER_ADAPTER) -extern "C" void * -ace_thread_manager_adapter (void *args) -{ -#if defined (ACE_HAS_TSS_EMULATION) - // As early as we can in the execution of the new thread, allocate - // its local TS storage. Allocate it on the stack, to save dynamic - // allocation/dealloction. - void *ts_storage[ACE_TSS_Emulation::ACE_TSS_THREAD_KEYS_MAX]; - ACE_TSS_Emulation::tss_open (ts_storage); -#endif /* ACE_HAS_TSS_EMULATION */ - - ACE_Thread_Adapter *thread_args = reinterpret_cast (args); - - // NOTE: this preprocessor directive should match the one in above - // ACE_Thread_Exit::instance (). With the Xavier Pthreads package, - // the exit_hook in TSS causes a seg fault. So, this works around - // that by creating exit_hook on the stack. -#if defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION) - // Obtain our thread-specific exit hook and make sure that it knows - // how to clean us up! Note that we never use this pointer directly - // (it's stored in thread-specific storage), so it's ok to - // dereference it here and only store it as a reference. - ACE_Thread_Exit &exit_hook = *ACE_Thread_Exit::instance (); -#else - // Without TSS, create an instance. When this - // function returns, its destructor will be called because the - // object goes out of scope. The drawback with this appraoch is - // that the destructor _won't_ get called if is called. - // So, threads shouldn't exit that way. Instead, they should return - // from . - ACE_Thread_Exit exit_hook; -#endif /* ACE_HAS_THREAD_SPECIFIC_STORAGE || ACE_HAS_TSS_EMULATION */ - - // Keep track of the that's associated with this - // . - exit_hook.thr_mgr (thread_args->thr_mgr ()); - - // Invoke the user-supplied function with the args. - void *status = thread_args->invoke (); - - delete static_cast (thread_args); - return status; -} -#endif - -// Call the appropriate OS routine to spawn a thread. Should *not* be -// called with the lock_ held... - -int -ACE_Thread_Manager::spawn_i (ACE_THR_FUNC func, - void *args, - long flags, - ACE_thread_t *t_id, - ACE_hthread_t *t_handle, - long priority, - int grp_id, - void *stack, - size_t stack_size, - ACE_Task_Base *task, - const char** thr_name) -{ - // First, threads created by Thread Manager should not be daemon threads. - // Using assertion is probably a bit too strong. However, it helps - // finding this kind of error as early as possible. Perhaps we can replace - // assertion by returning error. - ACE_ASSERT (ACE_BIT_DISABLED (flags, THR_DAEMON)); - - // Create a new thread running . *Must* be called with the - // held... - // Get a "new" Thread Descriptor from the freelist. - auto_ptr new_thr_desc (this->thread_desc_freelist_.remove ()); - - // Reset thread descriptor status - new_thr_desc->reset (this); - - ACE_Thread_Adapter *thread_args = 0; -# if defined (ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS) - ACE_NEW_RETURN (thread_args, - ACE_Thread_Adapter (func, - args, - (ACE_THR_C_FUNC) ACE_THREAD_ADAPTER_NAME, - this, - new_thr_desc.get (), - ACE_OS_Object_Manager::seh_except_selector(), - ACE_OS_Object_Manager::seh_except_handler()), - -1); -# else - ACE_NEW_RETURN (thread_args, - ACE_Thread_Adapter (func, - args, - (ACE_THR_C_FUNC) ACE_THREAD_ADAPTER_NAME, - this, - new_thr_desc.get ()), - -1); -# endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */ - auto_ptr auto_thread_args (static_cast (thread_args)); - - ACE_TRACE ("ACE_Thread_Manager::spawn_i"); - ACE_hthread_t thr_handle; - - ACE_thread_t thr_id; - if (t_id == 0) - t_id = &thr_id; - - // Acquire the lock to block the spawned thread from - // removing this Thread Descriptor before it gets put into our - // thread table. - new_thr_desc->sync_->acquire (); - - int const result = ACE_Thread::spawn (func, - args, - flags, - t_id, - &thr_handle, - priority, - stack, - stack_size, - thread_args, - thr_name); - - if (result != 0) - { - // _Don't_ clobber errno here! result is either 0 or -1, and - // ACE_OS::thr_create () already set errno! D. Levine 28 Mar 1997 - // errno = result; - ACE_Errno_Guard guard (errno); // Lock release may smash errno - new_thr_desc->sync_->release (); - return -1; - } - auto_thread_args.release (); - -#if defined (ACE_HAS_WTHREADS) - // Have to duplicate handle if client asks for it. - // @@ How are thread handles implemented on AIX? Do they - // also need to be duplicated? - if (t_handle != 0) -# if defined (ACE_LACKS_DUPLICATEHANDLE) - *t_handle = thr_handle; -# else /* ! ACE_LACKS_DUP */ - (void) ::DuplicateHandle (::GetCurrentProcess (), - thr_handle, - ::GetCurrentProcess (), - t_handle, - 0, - TRUE, - DUPLICATE_SAME_ACCESS); -# endif /* ! ACE_LACKS_DUP */ -#else /* ! ACE_HAS_WTHREADS */ - if (t_handle != 0) - *t_handle = thr_handle; -#endif /* ! ACE_HAS_WTHREADS */ - - // append_thr also put the into Thread_Manager's - // double-linked list. Only after this point, can we manipulate - // double-linked list from a spawned thread's context. - return this->append_thr (*t_id, - thr_handle, - ACE_THR_SPAWNED, - grp_id, - task, - flags, - new_thr_desc.release ()); -} - -int -ACE_Thread_Manager::spawn (ACE_THR_FUNC func, - void *args, - long flags, - ACE_thread_t *t_id, - ACE_hthread_t *t_handle, - long priority, - int grp_id, - void *stack, - size_t stack_size, - const char** thr_name) -{ - ACE_TRACE ("ACE_Thread_Manager::spawn"); - - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - - if (grp_id == -1) - grp_id = this->grp_id_++; // Increment the group id. - - if (priority != ACE_DEFAULT_THREAD_PRIORITY) - ACE_CLR_BITS (flags, THR_INHERIT_SCHED); - - if (this->spawn_i (func, - args, - flags, - t_id, - t_handle, - priority, - grp_id, - stack, - stack_size, - 0, - thr_name) == -1) - return -1; - - return grp_id; -} - -// Create N new threads running FUNC. - -int -ACE_Thread_Manager::spawn_n (size_t n, - ACE_THR_FUNC func, - void *args, - long flags, - long priority, - int grp_id, - ACE_Task_Base *task, - ACE_hthread_t thread_handles[], - void *stack[], - size_t stack_size[], - const char* thr_name[]) -{ - ACE_TRACE ("ACE_Thread_Manager::spawn_n"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - - if (grp_id == -1) - grp_id = this->grp_id_++; // Increment the group id. - - for (size_t i = 0; i < n; i++) - { - // @@ What should happen if this fails?! e.g., should we try to - // cancel the other threads that we've already spawned or what? - if (this->spawn_i (func, - args, - flags, - 0, - thread_handles == 0 ? 0 : &thread_handles[i], - priority, - grp_id, - stack == 0 ? 0 : stack[i], - stack_size == 0 ? ACE_DEFAULT_THREAD_STACKSIZE : stack_size[i], - task, - thr_name == 0 ? 0 : &thr_name [i]) == -1) - return -1; - } - - return grp_id; -} - -// Create N new threads running FUNC. - -int -ACE_Thread_Manager::spawn_n (ACE_thread_t thread_ids[], - size_t n, - ACE_THR_FUNC func, - void *args, - long flags, - long priority, - int grp_id, - void *stack[], - size_t stack_size[], - ACE_hthread_t thread_handles[], - ACE_Task_Base *task, - const char* thr_name[]) -{ - ACE_TRACE ("ACE_Thread_Manager::spawn_n"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - - if (grp_id == -1) - grp_id = this->grp_id_++; // Increment the group id. - - for (size_t i = 0; i < n; i++) - { - // @@ What should happen if this fails?! e.g., should we try to - // cancel the other threads that we've already spawned or what? - if (this->spawn_i (func, - args, - flags, - thread_ids == 0 ? 0 : &thread_ids[i], - thread_handles == 0 ? 0 : &thread_handles[i], - priority, - grp_id, - stack == 0 ? 0 : stack[i], - stack_size == 0 ? ACE_DEFAULT_THREAD_STACKSIZE : stack_size[i], - task, - thr_name == 0 ? 0 : &thr_name [i]) == -1) - return -1; - } - - return grp_id; -} - -// Append a thread into the pool (does not check for duplicates). -// Must be called with locks held. - -int -ACE_Thread_Manager::append_thr (ACE_thread_t t_id, - ACE_hthread_t t_handle, - ACE_UINT32 thr_state, - int grp_id, - ACE_Task_Base *task, - long flags, - ACE_Thread_Descriptor *td) -{ - ACE_TRACE ("ACE_Thread_Manager::append_thr"); - ACE_Thread_Descriptor *thr_desc = 0; - - if (td == 0) - { - ACE_NEW_RETURN (thr_desc, - ACE_Thread_Descriptor, - -1); - thr_desc->tm_ = this; - // Setup the Thread_Manager. - } - else - thr_desc = td; - - thr_desc->thr_id_ = t_id; - thr_desc->thr_handle_ = t_handle; - thr_desc->grp_id_ = grp_id; - thr_desc->task_ = task; - thr_desc->flags_ = flags; - - this->thr_list_.insert_head (thr_desc); - ACE_SET_BITS (thr_desc->thr_state_, thr_state); - thr_desc->sync_->release (); - - return 0; -} - -// Return the thread descriptor (indexed by ACE_hthread_t). - -ACE_Thread_Descriptor * -ACE_Thread_Manager::find_hthread (ACE_hthread_t h_id) -{ - for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); - !iter.done (); - iter.advance ()) - { - if (ACE_OS::thr_cmp (iter.next ()->thr_handle_, h_id)) - { - return iter.next (); - } - } - - return 0; -} - -// Locate the index in the table associated with . Must be -// called with the lock held. - -ACE_Thread_Descriptor * -ACE_Thread_Manager::find_thread (ACE_thread_t t_id) -{ - ACE_TRACE ("ACE_Thread_Manager::find_thread"); - - for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); - !iter.done (); - iter.advance ()) - { - if (ACE_OS::thr_equal (iter.next ()->thr_id_, t_id)) - { - return iter.next (); - } - } - return 0; -} - -// Insert a thread into the pool (checks for duplicates and doesn't -// allow them to be inserted twice). - -int -ACE_Thread_Manager::insert_thr (ACE_thread_t t_id, - ACE_hthread_t t_handle, - int grp_id, - long flags) -{ - ACE_TRACE ("ACE_Thread_Manager::insert_thr"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - - // Check for duplicates and bail out if we're already registered... - if (this->find_thread (t_id) != 0 ) - return -1; - - if (grp_id == -1) - grp_id = this->grp_id_++; - - if (this->append_thr (t_id, - t_handle, - ACE_THR_SPAWNED, - grp_id, - 0, - flags) == -1) - return -1; - - return grp_id; -} - -// Run the registered hooks when the thread exits. - -void -ACE_Thread_Manager::run_thread_exit_hooks (int i) -{ -#if 0 // currently unused! - ACE_TRACE ("ACE_Thread_Manager::run_thread_exit_hooks"); - - // @@ Currently, we have just one hook. This should clearly be - // generalized to support an arbitrary number of hooks. - - ACE_Thread_Descriptor *td = this->thread_desc_self (); - for (ACE_Cleanup_Info_Node *iter = td->cleanup_info_->pop_front (); - iter != 0; - iter = cleanup_info_->pop_front ()) - { - if (iter->cleanup_hook () != 0) - { - (*iter->cleanup_hook ()) (iter->object (), iter->param ()); - } - delete iter; - } - - ACE_UNUSED_ARG (i); -#else - ACE_UNUSED_ARG (i); -#endif /* 0 */ -} - -// Remove a thread from the pool. Must be called with locks held. - -void -ACE_Thread_Manager::remove_thr (ACE_Thread_Descriptor *td, - int close_handler) -{ - ACE_TRACE ("ACE_Thread_Manager::remove_thr"); - - td->tm_ = 0; - this->thr_list_.remove (td); - -#if defined (ACE_WIN32) - if (close_handler != 0) - ::CloseHandle (td->thr_handle_); -#else - ACE_UNUSED_ARG (close_handler); -#endif /* ACE_WIN32 */ - - this->thread_desc_freelist_.add (td); - -#if defined (ACE_HAS_THREADS) - // Tell all waiters when there are no more threads left in the pool. - if (this->thr_list_.size () == 0) - this->zero_cond_.broadcast (); -#endif /* ACE_HAS_THREADS */ -} - -// Repeatedly call remove_thr on all table entries until there -// is no thread left. Must be called with lock held. -void -ACE_Thread_Manager::remove_thr_all (void) -{ - ACE_Thread_Descriptor *td = 0; - - while ((td = this->thr_list_.delete_head ()) != 0) - { - this->remove_thr (td, 1); - } -} - -// ------------------------------------------------------------------ -// Factor out some common behavior to simplify the following methods. -#define ACE_THR_OP(OP,STATE) \ - int result = OP (td->thr_handle_); \ - if (result == -1) { \ - if (errno != ENOTSUP) \ - this->thr_to_be_removed_.enqueue_tail (td); \ - return -1; \ - } \ - else { \ - ACE_SET_BITS (td->thr_state_, STATE); \ - return 0; \ - } - -int -ACE_Thread_Manager::join_thr (ACE_Thread_Descriptor *td, int) -{ - ACE_TRACE ("ACE_Thread_Manager::join_thr"); - int const result = ACE_Thread::join (td->thr_handle_); - if (result != 0) - { - // Since the thread are being joined, we should - // let it remove itself from the list. - - // this->remove_thr (td); - errno = result; - return -1; - } - - return 0; -} - -int -ACE_Thread_Manager::suspend_thr (ACE_Thread_Descriptor *td, int) -{ - ACE_TRACE ("ACE_Thread_Manager::suspend_thr"); - - int const result = ACE_Thread::suspend (td->thr_handle_); - if (result == -1) { - if (errno != ENOTSUP) - this->thr_to_be_removed_.enqueue_tail (td); - return -1; - } - else { - ACE_SET_BITS (td->thr_state_, ACE_THR_SUSPENDED); - return 0; - } -} - -int -ACE_Thread_Manager::resume_thr (ACE_Thread_Descriptor *td, int) -{ - ACE_TRACE ("ACE_Thread_Manager::resume_thr"); - - int const result = ACE_Thread::resume (td->thr_handle_); - if (result == -1) { - if (errno != ENOTSUP) - this->thr_to_be_removed_.enqueue_tail (td); - return -1; - } - else { - ACE_CLR_BITS (td->thr_state_, ACE_THR_SUSPENDED); - return 0; - } -} - -int -ACE_Thread_Manager::cancel_thr (ACE_Thread_Descriptor *td, int async_cancel) -{ - ACE_TRACE ("ACE_Thread_Manager::cancel_thr"); - // Must set the state first and then try to cancel the thread. - ACE_SET_BITS (td->thr_state_, ACE_THR_CANCELLED); - - if (async_cancel != 0) - // Note that this call only does something relevant if the OS - // platform supports asynchronous thread cancellation. Otherwise, - // it's a no-op. - return ACE_Thread::cancel (td->thr_id_); - - return 0; -} - -int -ACE_Thread_Manager::kill_thr (ACE_Thread_Descriptor *td, int signum) -{ - ACE_TRACE ("ACE_Thread_Manager::kill_thr"); - - ACE_thread_t tid = td->thr_id_; - - int const result = ACE_Thread::kill (tid, signum); - - if (result != 0) - { - // Only remove a thread from us when there is a "real" error. - if (errno != ENOTSUP) - this->thr_to_be_removed_.enqueue_tail (td); - - return -1; - } - - return 0; -} - -// ------------------------------------------------------------------ -// Factor out some common behavior to simplify the following methods. -#define ACE_EXECUTE_OP(OP, ARG) \ - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); \ - ACE_ASSERT (this->thr_to_be_removed_.is_empty ()); \ - ACE_FIND (this->find_thread (t_id), ptr); \ - if (ptr == 0) \ - { \ - errno = ENOENT; \ - return -1; \ - } \ - int const result = OP (ptr, ARG); \ - ACE_Errno_Guard error (errno); \ - while (! this->thr_to_be_removed_.is_empty ()) { \ - ACE_Thread_Descriptor * td = 0; \ - this->thr_to_be_removed_.dequeue_head (td); \ - this->remove_thr (td, 1); \ - } \ - return result - -// Suspend a single thread. - -int -ACE_Thread_Manager::suspend (ACE_thread_t t_id) -{ - ACE_TRACE ("ACE_Thread_Manager::suspend"); - ACE_EXECUTE_OP (this->suspend_thr, 0); -} - -// Resume a single thread. - -int -ACE_Thread_Manager::resume (ACE_thread_t t_id) -{ - ACE_TRACE ("ACE_Thread_Manager::resume"); - ACE_EXECUTE_OP (this->resume_thr, 0); -} - -// Cancel a single thread. - -int -ACE_Thread_Manager::cancel (ACE_thread_t t_id, int async_cancel) -{ - ACE_TRACE ("ACE_Thread_Manager::cancel"); - ACE_EXECUTE_OP (this->cancel_thr, async_cancel); -} - -// Send a signal to a single thread. - -int -ACE_Thread_Manager::kill (ACE_thread_t t_id, int signum) -{ - ACE_TRACE ("ACE_Thread_Manager::kill"); - ACE_EXECUTE_OP (this->kill_thr, signum); -} - -int -ACE_Thread_Manager::check_state (ACE_UINT32 state, - ACE_thread_t id, - int enable) -{ - ACE_TRACE ("ACE_Thread_Manager::check_state"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - - ACE_UINT32 thr_state; - - int self_check = ACE_OS::thr_equal (id, ACE_OS::thr_self ()); - - // If we're checking the state of our thread, try to get the cached - // value out of TSS to avoid lookup. - if (self_check) - { - ACE_Thread_Descriptor *desc = ACE_LOG_MSG->thr_desc (); - if (desc == 0) - return 0; // Always return false. - thr_state = desc->thr_state_; - } - else - { - // Not calling from self, have to look it up from the list. - ACE_FIND (this->find_thread (id), ptr); - if (ptr == 0) - return 0; - thr_state = ptr->thr_state_; - } - if (enable) - return ACE_BIT_ENABLED (thr_state, state); - - return ACE_BIT_DISABLED (thr_state, state); -} - -// Test if a single thread has terminated. - -int -ACE_Thread_Manager::testterminate (ACE_thread_t t_id) -{ - ACE_TRACE ("ACE_Thread_Manager::testterminate"); - return this->check_state (ACE_THR_TERMINATED, t_id); -} - -// Test if a single thread is suspended. - -int -ACE_Thread_Manager::testsuspend (ACE_thread_t t_id) -{ - ACE_TRACE ("ACE_Thread_Manager::testsuspend"); - return this->check_state (ACE_THR_SUSPENDED, t_id); -} - -// Test if a single thread is active (i.e., resumed). - -int -ACE_Thread_Manager::testresume (ACE_thread_t t_id) -{ - ACE_TRACE ("ACE_Thread_Manager::testresume"); - return this->check_state (ACE_THR_SUSPENDED, t_id, 0); -} - -// Test if a single thread is cancelled. - -int -ACE_Thread_Manager::testcancel (ACE_thread_t t_id) -{ - ACE_TRACE ("ACE_Thread_Manager::testcancel"); - return this->check_state (ACE_THR_CANCELLED, t_id); -} - -// Thread information query functions. - -int -ACE_Thread_Manager::hthread_within (ACE_hthread_t handle) -{ - ACE_TRACE ("ACE_Thread_Manager::hthread_within"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_monx, this->lock_, -1)); - - for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); - !iter.done (); - iter.advance ()) - { - if (ACE_OS::thr_cmp(iter.next ()->thr_handle_, handle)) - { - return 1; - } - } - - return 0; -} - -int -ACE_Thread_Manager::thread_within (ACE_thread_t tid) -{ - ACE_TRACE ("ACE_Thread_Manager::thread_within"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_monx, this->lock_, -1)); - - for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); - !iter.done (); - iter.advance ()) - { - if (ACE_OS::thr_equal (iter.next ()->thr_id_, tid)) - { - return 1; - } - } - - return 0; -} - -// Get group ids for a particular thread id. - -int -ACE_Thread_Manager::get_grp (ACE_thread_t t_id, int &grp_id) -{ - ACE_TRACE ("ACE_Thread_Manager::get_grp"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - - ACE_FIND (this->find_thread (t_id), ptr); - - if (ptr) - grp_id = ptr->grp_id_; - else - return -1; - return 0; -} - -// Set group ids for a particular thread id. - -int -ACE_Thread_Manager::set_grp (ACE_thread_t t_id, int grp_id) -{ - ACE_TRACE ("ACE_Thread_Manager::set_grp"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - - ACE_FIND (this->find_thread (t_id), ptr); - if (ptr) - ptr->grp_id_ = grp_id; - else - return -1; - return 0; -} - -// Suspend a group of threads. - -int -ACE_Thread_Manager::apply_grp (int grp_id, - ACE_THR_MEMBER_FUNC func, - int arg) -{ - ACE_TRACE ("ACE_Thread_Manager::apply_grp"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_monx, this->lock_, -1)); - ACE_ASSERT (this->thr_to_be_removed_.is_empty ()); - - int result = 0; - - for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); - !iter.done (); - iter.advance ()) - { - if (iter.next ()->grp_id_ == grp_id) - { - if ((this->*func) (iter.next (), arg) == -1) - { - result = -1; - } - } - } - - // Must remove threads after we have traversed the thr_list_ to - // prevent clobber thr_list_'s integrity. - - if (! this->thr_to_be_removed_.is_empty ()) - { - // Save/restore errno. - ACE_Errno_Guard error (errno); - - for (ACE_Thread_Descriptor *td; - this->thr_to_be_removed_.dequeue_head (td) != -1; - ) - this->remove_thr (td, 1); - } - - return result; -} - -int -ACE_Thread_Manager::suspend_grp (int grp_id) -{ - ACE_TRACE ("ACE_Thread_Manager::suspend_grp"); - return this->apply_grp (grp_id, - ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::suspend_thr)); -} - -// Resume a group of threads. - -int -ACE_Thread_Manager::resume_grp (int grp_id) -{ - ACE_TRACE ("ACE_Thread_Manager::resume_grp"); - return this->apply_grp (grp_id, - ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::resume_thr)); -} - -// Kill a group of threads. - -int -ACE_Thread_Manager::kill_grp (int grp_id, int signum) -{ - ACE_TRACE ("ACE_Thread_Manager::kill_grp"); - return this->apply_grp (grp_id, - ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::kill_thr), signum); -} - -// Cancel a group of threads. - -int -ACE_Thread_Manager::cancel_grp (int grp_id, int async_cancel) -{ - ACE_TRACE ("ACE_Thread_Manager::cancel_grp"); - return this->apply_grp (grp_id, - ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::cancel_thr), - async_cancel); -} - -int -ACE_Thread_Manager::apply_all (ACE_THR_MEMBER_FUNC func, int arg) -{ - ACE_TRACE ("ACE_Thread_Manager::apply_all"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - ACE_ASSERT (this->thr_to_be_removed_.is_empty ()); - - int result = 0; - - for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); - !iter.done (); - iter.advance ()) - { - if ((this->*func)(iter.next (), arg) == -1) - { - result = -1; - } - } - - // Must remove threads after we have traversed the thr_list_ to - // prevent clobber thr_list_'s integrity. - - if (! this->thr_to_be_removed_.is_empty ()) - { - // Save/restore errno. - ACE_Errno_Guard error (errno); - - for (ACE_Thread_Descriptor *td; - this->thr_to_be_removed_.dequeue_head (td) != -1; - ) - this->remove_thr (td, 1); - } - - return result; -} - -// Resume all threads that are suspended. - -int -ACE_Thread_Manager::resume_all (void) -{ - ACE_TRACE ("ACE_Thread_Manager::resume_all"); - return this->apply_all (ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::resume_thr)); -} - -int -ACE_Thread_Manager::suspend_all (void) -{ - ACE_TRACE ("ACE_Thread_Manager::suspend_all"); - return this->apply_all (ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::suspend_thr)); -} - -int -ACE_Thread_Manager::kill_all (int sig) -{ - ACE_TRACE ("ACE_Thread_Manager::kill_all"); - return this->apply_all (&ACE_Thread_Manager::kill_thr, sig); -} - -int -ACE_Thread_Manager::cancel_all (int async_cancel) -{ - ACE_TRACE ("ACE_Thread_Manager::cancel_all"); - return this->apply_all (ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::cancel_thr), - async_cancel); -} - -int -ACE_Thread_Manager::join (ACE_thread_t tid, ACE_THR_FUNC_RETURN *status) -{ - ACE_TRACE ("ACE_Thread_Manager::join"); - - bool found = false; - ACE_Thread_Descriptor_Base tdb; - - { - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - -#if !defined (ACE_HAS_VXTHREADS) - for (ACE_Double_Linked_List_Iterator biter (this->terminated_thr_list_); - !biter.done (); - biter.advance ()) - { - if (ACE_OS::thr_equal (biter.next ()->thr_id_, tid)) - { - ACE_Thread_Descriptor_Base *tdb = biter.advance_and_remove (false); - if (ACE_Thread::join (tdb->thr_handle_, status) == -1) - { - return -1; - } - delete tdb; - - // return immediately if we've found the thread we want to join. - return 0; - } - } -#endif /* !ACE_HAS_VXTHREADS */ - - for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); - !iter.done (); - iter.advance ()) - { - // If threads are created as THR_DETACHED or THR_DAEMON, we - // can't help much. - if (ACE_OS::thr_equal (iter.next ()->thr_id_,tid) && - (ACE_BIT_DISABLED (iter.next ()->flags_, THR_DETACHED | THR_DAEMON) - || ACE_BIT_ENABLED (iter.next ()->flags_, THR_JOINABLE))) - { - tdb = *iter.next (); - ACE_SET_BITS (iter.next ()->thr_state_, ACE_THR_JOINING); - found = 1; - break; - } - } - - if (!found) - return -1; - // Didn't find the thread we want or the thread is not joinable. - } - - if (ACE_Thread::join (tdb.thr_handle_, status) == -1) - return -1; - - return 0; -} - -// Wait for group of threads - -int -ACE_Thread_Manager::wait_grp (int grp_id) -{ - ACE_TRACE ("ACE_Thread_Manager::wait_grp"); - - int copy_count = 0; - ACE_Thread_Descriptor_Base *copy_table = 0; - - // We have to make sure that while we wait for these threads to - // exit, we do not have the lock. Therefore we make a copy of all - // interesting entries and let go of the lock. - { - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - -#if !defined (ACE_HAS_VXTHREADS) - ACE_NEW_RETURN (copy_table, - ACE_Thread_Descriptor_Base [this->thr_list_.size () - + this->terminated_thr_list_.size ()], - -1); -#else - ACE_NEW_RETURN (copy_table, - ACE_Thread_Descriptor_Base [this->thr_list_.size ()], - -1); -#endif /* !ACE_HAS_VXTHREADS */ - - for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); - !iter.done (); - iter.advance ()) - { - // If threads are created as THR_DETACHED or THR_DAEMON, we - // can't help much. - if (iter.next ()->grp_id_ == grp_id && - (ACE_BIT_DISABLED (iter.next ()->flags_, THR_DETACHED | THR_DAEMON) - || ACE_BIT_ENABLED (iter.next ()->flags_, THR_JOINABLE))) - { - ACE_SET_BITS (iter.next ()->thr_state_, ACE_THR_JOINING); - copy_table[copy_count++] = *iter.next (); - } - } - -#if !defined (ACE_HAS_VXTHREADS) - for (ACE_Double_Linked_List_Iterator biter (this->terminated_thr_list_); - !biter.done (); - biter.advance ()) - { - // If threads are created as THR_DETACHED or THR_DAEMON, we - // can't help much. - if (biter.next ()->grp_id_ == grp_id) - { - ACE_Thread_Descriptor_Base *tdb = biter.advance_and_remove (false); - copy_table[copy_count++] = *tdb; - delete tdb; - } - } -#endif /* !ACE_HAS_VXTHREADS */ - } - - // Now actually join() with all the threads in this group. - int result = 0; - - for (int i = 0; - i < copy_count && result != -1; - i++) - { - if (ACE_Thread::join (copy_table[i].thr_handle_) == -1) - result = -1; - } - - delete [] copy_table; - - return result; -} - -// Must be called when thread goes out of scope to clean up its table -// slot. - -ACE_THR_FUNC_RETURN -ACE_Thread_Manager::exit (ACE_THR_FUNC_RETURN status, bool do_thread_exit) -{ - ACE_TRACE ("ACE_Thread_Manager::exit"); -#if defined (ACE_WIN32) - // Remove detached thread handle. - - if (do_thread_exit) - { -#if 0 - // @@ This callback is now taken care of by TSS_Cleanup. Do we - // need it anymore? - - // On Win32, if we really wants to exit from a thread, we must - // first clean up the thread specific storage. By doing so, - // ACE_Thread_Manager::exit will be called again with - // do_thr_exit = 0 and cleaning up the ACE_Cleanup_Info (but not - // exiting the thread.) After the following call returns, we - // are safe to exit this thread. - delete ACE_Thread_Exit::instance (); -#endif /* 0 */ - ACE_Thread::exit (status); - } -#endif /* ACE_WIN32 */ - - // Just hold onto the guard while finding this thread's id and - { - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0)); - - // Find the thread id, but don't use the cache. It might have been - // deleted already. - ACE_thread_t const id = ACE_OS::thr_self (); - ACE_Thread_Descriptor* td = this->find_thread (id); - if (td != 0) - { - // @@ We call Thread_Descriptor terminate this realize the cleanup - // process itself. - td->terminate(); - } - } - - if (do_thread_exit) - { - ACE_Thread::exit (status); - // On reasonable systems should not return. - // However, due to horrible semantics with Win32 thread-specific - // storage this call can return (don't ask...). - } - - return 0; -} - -// Wait for all the threads to exit. - -int -ACE_Thread_Manager::wait (const ACE_Time_Value *timeout, - bool abandon_detached_threads, - bool use_absolute_time) -{ - ACE_TRACE ("ACE_Thread_Manager::wait"); - - ACE_Time_Value local_timeout; - // Check to see if we're using absolute time or not. - if (use_absolute_time == false && timeout != 0) - { - local_timeout = *timeout; - local_timeout += ACE_OS::gettimeofday (); - timeout = &local_timeout; - } - -#if !defined (ACE_HAS_VXTHREADS) - ACE_Double_Linked_List term_thr_list_copy; -#endif /* ACE_HAS_VXTHREADS */ - -#if defined (ACE_HAS_THREADS) - { - // Just hold onto the guard while waiting. - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - - if (ACE_Object_Manager::shutting_down () != 1) - { - // Program is not shutting down. Perform a normal wait on threads. - if (abandon_detached_threads != 0) - { - ACE_ASSERT (this->thr_to_be_removed_.is_empty ()); - for (ACE_Double_Linked_List_Iterator - iter (this->thr_list_); - !iter.done (); - iter.advance ()) - { - if (ACE_BIT_ENABLED (iter.next ()->flags_, - THR_DETACHED | THR_DAEMON) - && ACE_BIT_DISABLED (iter.next ()->flags_, THR_JOINABLE)) - { - this->thr_to_be_removed_.enqueue_tail (iter.next ()); - ACE_SET_BITS (iter.next ()->thr_state_, ACE_THR_JOINING); - } - } - - if (! this->thr_to_be_removed_.is_empty ()) - { - ACE_Thread_Descriptor *td = 0; - while (this->thr_to_be_removed_.dequeue_head (td) != -1) - this->remove_thr (td, 1); - } - } - - while (this->thr_list_.size () > 0) - if (this->zero_cond_.wait (timeout) == -1) - return -1; - } - else - // Program is shutting down, no chance to wait on threads. - // Therefore, we'll just remove threads from the list. - this->remove_thr_all (); - -#if !defined (ACE_HAS_VXTHREADS) - ACE_Thread_Descriptor_Base* item = 0; - while ((item = this->terminated_thr_list_.delete_head ()) != 0) - { - term_thr_list_copy.insert_tail (item); - } -#endif /* ACE_HAS_VXTHREADS */ - // Release the guard, giving other threads a chance to run. - } - -#if !defined (ACE_HAS_VXTHREADS) - // @@ VxWorks doesn't support thr_join (yet.) We are working - // on our implementation. Chorus'es thr_join seems broken. - ACE_Thread_Descriptor_Base *item = 0; - - while ((item = term_thr_list_copy.delete_head ()) != 0) - { - if (ACE_BIT_DISABLED (item->flags_, THR_DETACHED | THR_DAEMON) - || ACE_BIT_ENABLED (item->flags_, THR_JOINABLE)) - // Detached handles shouldn't reached here. - (void) ACE_Thread::join (item->thr_handle_); - - delete item; - } - -#endif /* !ACE_HAS_VXTHREADS */ -#else - ACE_UNUSED_ARG (timeout); - ACE_UNUSED_ARG (abandon_detached_threads); -#endif /* ACE_HAS_THREADS */ - - return 0; -} - -int -ACE_Thread_Manager::apply_task (ACE_Task_Base *task, - ACE_THR_MEMBER_FUNC func, - int arg) -{ - ACE_TRACE ("ACE_Thread_Manager::apply_task"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - ACE_ASSERT (this->thr_to_be_removed_.is_empty ()); - - int result = 0; - - for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); - !iter.done (); - iter.advance ()) - if (iter.next ()->task_ == task - && (this->*func) (iter.next (), arg) == -1) - result = -1; - - // Must remove threads after we have traversed the thr_list_ to - // prevent clobber thr_list_'s integrity. - - if (! this->thr_to_be_removed_.is_empty ()) - { - // Save/restore errno. - ACE_Errno_Guard error (errno); - - for (ACE_Thread_Descriptor *td = 0; - this->thr_to_be_removed_.dequeue_head (td) != -1; - ) - this->remove_thr (td, 1); - } - - return result; -} - -// Wait for all threads to exit a task. - -int -ACE_Thread_Manager::wait_task (ACE_Task_Base *task) -{ - int copy_count = 0; - ACE_Thread_Descriptor_Base *copy_table = 0; - - // We have to make sure that while we wait for these threads to - // exit, we do not have the lock. Therefore we make a copy of all - // interesting entries and let go of the lock. - { - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - -#if !defined (ACE_HAS_VXTHREADS) - ACE_NEW_RETURN (copy_table, - ACE_Thread_Descriptor_Base [this->thr_list_.size () - + this->terminated_thr_list_.size ()], - -1); -#else - ACE_NEW_RETURN (copy_table, - ACE_Thread_Descriptor_Base [this->thr_list_.size ()], - -1); -#endif /* !ACE_HAS_VXTHREADS */ - - for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); - !iter.done (); - iter.advance ()) - { - // If threads are created as THR_DETACHED or THR_DAEMON, we - // can't wait on them here. - if (iter.next ()->task_ == task && - (ACE_BIT_DISABLED (iter.next ()->flags_, - THR_DETACHED | THR_DAEMON) - || ACE_BIT_ENABLED (iter.next ()->flags_, - THR_JOINABLE))) - { - ACE_SET_BITS (iter.next ()->thr_state_, - ACE_THR_JOINING); - copy_table[copy_count++] = *iter.next (); - } - } - -#if !defined (ACE_HAS_VXTHREADS) - for (ACE_Double_Linked_List_Iterator titer (this->terminated_thr_list_); - !titer.done (); - titer.advance ()) - { - // If threads are created as THR_DETACHED or THR_DAEMON, we can't help much here. - if (titer.next ()->task_ == task) - { - ACE_Thread_Descriptor_Base *tdb = titer.advance_and_remove (false); - copy_table[copy_count++] = *tdb; - delete tdb; - } - } -#endif /* !ACE_HAS_VXTHREADS */ - } - - // Now to do the actual work - int result = 0; - - for (int i = 0; - i < copy_count && result != -1; - i++) - { - if (ACE_Thread::join (copy_table[i].thr_handle_) == -1) - result = -1; - } - - delete [] copy_table; - - return result; -} - -// Suspend a task - -int -ACE_Thread_Manager::suspend_task (ACE_Task_Base *task) -{ - ACE_TRACE ("ACE_Thread_Manager::suspend_task"); - return this->apply_task (task, - ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::suspend_thr)); -} - -// Resume a task. -int -ACE_Thread_Manager::resume_task (ACE_Task_Base *task) -{ - ACE_TRACE ("ACE_Thread_Manager::resume_task"); - return this->apply_task (task, - ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::resume_thr)); -} - -// Kill a task. - -int -ACE_Thread_Manager::kill_task (ACE_Task_Base *task, int /* signum */) -{ - ACE_TRACE ("ACE_Thread_Manager::kill_task"); - return this->apply_task (task, - ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::kill_thr)); -} - -// Cancel a task. -int -ACE_Thread_Manager::cancel_task (ACE_Task_Base *task, - int async_cancel) -{ - ACE_TRACE ("ACE_Thread_Manager::cancel_task"); - return this->apply_task (task, - ACE_THR_MEMBER_FUNC (&ACE_Thread_Manager::cancel_thr), - async_cancel); -} - -// Locate the index in the table associated with from the -// beginning of the table up to an index. Must be called with the -// lock held. - -ACE_Thread_Descriptor * -ACE_Thread_Manager::find_task (ACE_Task_Base *task, size_t slot) -{ - ACE_TRACE ("ACE_Thread_Manager::find_task"); - - size_t i = 0; - - for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); - !iter.done (); - iter.advance ()) - { - if (i >= slot) - break; - - if (task == iter.next ()->task_) - return iter.next (); - - ++i; - } - - return 0; -} - -// Returns the number of ACE_Task in a group. - -int -ACE_Thread_Manager::num_tasks_in_group (int grp_id) -{ - ACE_TRACE ("ACE_Thread_Manager::num_tasks_in_group"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - - int tasks_count = 0; - size_t i = 0; - - for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); - !iter.done (); - iter.advance ()) - { - if (iter.next ()->grp_id_ == grp_id - && this->find_task (iter.next ()->task_, i) == 0 - && iter.next ()->task_ != 0) - { - ++tasks_count; - } - - ++i; - } - return tasks_count; -} - -// Returns the number of threads in an ACE_Task. - -int -ACE_Thread_Manager::num_threads_in_task (ACE_Task_Base *task) -{ - ACE_TRACE ("ACE_Thread_Manager::num_threads_in_task"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - - int threads_count = 0; - - for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); - !iter.done (); - iter.advance ()) - { - if (iter.next ()->task_ == task) - { - ++threads_count; - } - } - - return threads_count; -} - -// Returns in task_list a list of ACE_Tasks registered with ACE_Thread_Manager. - -ssize_t -ACE_Thread_Manager::task_all_list (ACE_Task_Base *task_list[], - size_t n) -{ - ACE_TRACE ("ACE_Thread_Manager::task_all_list"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - - size_t task_list_count = 0; - - for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); - !iter.done (); - iter.advance ()) - { - if (task_list_count >= n) - { - break; - } - - ACE_Task_Base *task_p = iter.next ()->task_; - - if (0 != task_p) - { - // This thread has a task pointer; see if it's already in the - // list. Don't add duplicates. - size_t i = 0; - - for (; i < task_list_count; ++i) - { - if (task_list[i] == task_p) - { - break; - } - } - - if (i == task_list_count) // No match - add this one - { - task_list[task_list_count++] = task_p; - } - } - } - - return ACE_Utils::truncate_cast (task_list_count); -} - -// Returns in thread_list a list of all thread ids - -ssize_t -ACE_Thread_Manager::thread_all_list (ACE_thread_t thread_list[], - size_t n) -{ - ACE_TRACE ("ACE_Thread_Manager::thread_all_list"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - - size_t thread_count = 0; - - for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); - !iter.done (); - iter.advance ()) - { - if (thread_count >= n) - { - break; - } - - thread_list[thread_count] = iter.next ()->thr_id_; - ++thread_count; - } - - return ACE_Utils::truncate_cast (thread_count); -} - - -int -ACE_Thread_Manager::thr_state (ACE_thread_t id, - ACE_UINT32& state) -{ - ACE_TRACE ("ACE_Thread_Manager::thr_state"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - - int const self_check = ACE_OS::thr_equal (id, ACE_OS::thr_self ()); - - // If we're checking the state of our thread, try to get the cached - // value out of TSS to avoid lookup. - if (self_check) - { - ACE_Thread_Descriptor *desc = ACE_LOG_MSG->thr_desc (); - - if (desc == 0) - { - return 0; // Always return false. - } - - state = desc->thr_state_; - } - else - { - // Not calling from self, have to look it up from the list. - ACE_FIND (this->find_thread (id), ptr); - - if (ptr == 0) - { - return 0; - } - - state = ptr->thr_state_; - } - - return 1; -} - -// Returns in task_list a list of ACE_Tasks in a group. - -ssize_t -ACE_Thread_Manager::task_list (int grp_id, - ACE_Task_Base *task_list[], - size_t n) -{ - ACE_TRACE ("ACE_Thread_Manager::task_list"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - - ACE_Task_Base **task_list_iterator = task_list; - size_t task_list_count = 0; - size_t i = 0; - - for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); - !iter.done (); - iter.advance ()) - { - if (task_list_count >= n) - { - break; - } - - if (iter.next ()->grp_id_ == grp_id - && this->find_task (iter.next ()->task_, i) == 0) - { - task_list_iterator[task_list_count] = iter.next ()->task_; - ++task_list_count; - } - - ++i; - } - - return ACE_Utils::truncate_cast (task_list_count); -} - -// Returns in thread_list a list of thread ids in an ACE_Task. - -ssize_t -ACE_Thread_Manager::thread_list (ACE_Task_Base *task, - ACE_thread_t thread_list[], - size_t n) -{ - ACE_TRACE ("ACE_Thread_Manager::thread_list"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - - size_t thread_count = 0; - - for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); - !iter.done (); - iter.advance ()) - { - if (thread_count >= n) - { - break; - } - - if (iter.next ()->task_ == task) - { - thread_list[thread_count] = iter.next ()->thr_id_; - ++thread_count; - } - } - - return ACE_Utils::truncate_cast (thread_count); -} - -// Returns in thread_list a list of thread handles in an ACE_Task. - -ssize_t -ACE_Thread_Manager::hthread_list (ACE_Task_Base *task, - ACE_hthread_t hthread_list[], - size_t n) -{ - ACE_TRACE ("ACE_Thread_Manager::hthread_list"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - - size_t hthread_count = 0; - - for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); - !iter.done (); - iter.advance ()) - { - if (hthread_count >= n) - { - break; - } - - if (iter.next ()->task_ == task) - { - hthread_list[hthread_count] = iter.next ()->thr_handle_; - ++hthread_count; - } - } - - return ACE_Utils::truncate_cast (hthread_count); -} - -ssize_t -ACE_Thread_Manager::thread_grp_list (int grp_id, - ACE_thread_t thread_list[], - size_t n) -{ - ACE_TRACE ("ACE_Thread_Manager::thread_grp_list"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - - size_t thread_count = 0; - - for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); - !iter.done (); - iter.advance ()) - { - if (thread_count >= n) - { - break; - } - - if (iter.next ()->grp_id_ == grp_id) - { - thread_list[thread_count] = iter.next ()->thr_id_; - thread_count++; - } - } - - return ACE_Utils::truncate_cast (thread_count); -} - -// Returns in thread_list a list of thread handles in an ACE_Task. - -ssize_t -ACE_Thread_Manager::hthread_grp_list (int grp_id, - ACE_hthread_t hthread_list[], - size_t n) -{ - ACE_TRACE ("ACE_Thread_Manager::hthread_grp_list"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - - size_t hthread_count = 0; - - for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); - !iter.done (); - iter.advance ()) - { - if (hthread_count >= n) - { - break; - } - - if (iter.next ()->grp_id_ == grp_id) - { - hthread_list[hthread_count] = iter.next ()->thr_handle_; - hthread_count++; - } - } - - return ACE_Utils::truncate_cast (hthread_count); -} - -int -ACE_Thread_Manager::set_grp (ACE_Task_Base *task, int grp_id) -{ - ACE_TRACE ("ACE_Thread_Manager::set_grp"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - - for (ACE_Double_Linked_List_Iterator iter (this->thr_list_); - !iter.done (); - iter.advance ()) - { - if (iter.next ()->task_ == task) - { - iter.next ()->grp_id_ = grp_id; - } - } - - return 0; -} - -int -ACE_Thread_Manager::get_grp (ACE_Task_Base *task, int &grp_id) -{ - ACE_TRACE ("ACE_Thread_Manager::get_grp"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - - ACE_FIND (this->find_task (task), ptr); - grp_id = ptr->grp_id_; - return 0; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Thread_Manager.h b/externals/ace/Thread_Manager.h deleted file mode 100644 index 650287277d7..00000000000 --- a/externals/ace/Thread_Manager.h +++ /dev/null @@ -1,1267 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Thread_Manager.h - * - * $Id: Thread_Manager.h 83956 2008-12-03 07:57:38Z johnnyw $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_THREAD_MANAGER_H -#define ACE_THREAD_MANAGER_H -#include /**/ "ace/pre.h" - -#include "ace/Thread.h" -#include "ace/Thread_Adapter.h" -#include "ace/Thread_Exit.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Condition_Thread_Mutex.h" -#include "ace/Unbounded_Queue.h" -#include "ace/Containers.h" -#include "ace/Free_List.h" -#include "ace/Singleton.h" -#include "ace/Log_Msg.h" -#include "ace/Synch_Traits.h" -#include "ace/Basic_Types.h" - -// The following macros control how a Thread Manager manages a pool of -// Thread_Descriptor. Currently, the default behavior is not to -// preallocate any thread descriptor and never (well, almost never) -// free up any thread descriptor until the Thread Manager gets -// destructed. Which means, once your system is stable, you rarely -// need to pay the price of memory allocation. On a deterministic -// system, which means, the number of threads spawned can be -// determined before hand, you can either redefine the memory pool -// size macros to suit your need or constructed the Thread_Manager -// accordingly. That way, you don't pay the price of memory -// allocation when the system is really doing its job. OTOH, on -// system with resources constraint, you may want to lower the size of -// ACE_DEFAULT_THREAD_MANAGER_HWM to avoid unused memory hanging -// around. - -#if !defined (ACE_DEFAULT_THREAD_MANAGER_PREALLOC) -# define ACE_DEFAULT_THREAD_MANAGER_PREALLOC 0 -#endif /* ACE_DEFAULT_THREAD_MANAGER_PREALLOC */ - -#if !defined (ACE_DEFAULT_THREAD_MANAGER_LWM) -# define ACE_DEFAULT_THREAD_MANAGER_LWM 1 -#endif /* ACE_DEFAULT_THREAD_MANAGER_LWM */ - -#if !defined (ACE_DEFAULT_THREAD_MANAGER_INC) -# define ACE_DEFAULT_THREAD_MANAGER_INC 1 -#endif /* ACE_DEFAULT_THREAD_MANAGER_INC */ - -#if !defined (ACE_DEFAULT_THREAD_MANAGER_HWM) -# define ACE_DEFAULT_THREAD_MANAGER_HWM ACE_DEFAULT_FREE_LIST_HWM -// this is a big number -#endif /* ACE_DEFAULT_THREAD_MANAGER_HWM */ - -// This is the synchronization mechanism used to prevent a thread -// descriptor gets removed from the Thread_Manager before it gets -// stash into it. If you want to disable this feature (and risk of -// corrupting the freelist,) you define the lock as ACE_Null_Mutex. -// Usually, if you can be sure that your threads will run for an -// extended period of time, you can safely disable the lock. - -#if !defined (ACE_DEFAULT_THREAD_MANAGER_LOCK) -# define ACE_DEFAULT_THREAD_MANAGER_LOCK ACE_SYNCH_MUTEX -#endif /* ACE_DEFAULT_THREAD_MANAGER_LOCK */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Forward declarations. -class ACE_Task_Base; -class ACE_Thread_Manager; -class ACE_Thread_Descriptor; - -/** - * @class ACE_At_Thread_Exit - * - * @brief Contains a method to be applied when a thread is terminated. - */ -class ACE_Export ACE_At_Thread_Exit -{ - friend class ACE_Thread_Descriptor; - friend class ACE_Thread_Manager; -public: - /// Default constructor - ACE_At_Thread_Exit (void); - - /// The destructor - virtual ~ACE_At_Thread_Exit (void); - - /// At_Thread_Exit has the ownership? - bool is_owner (void) const; - - /// Set the ownership of the At_Thread_Exit. - bool is_owner (bool owner); - - /// This At_Thread_Exit was applied? - bool was_applied (void) const; - - /// Set applied state of At_Thread_Exit. - bool was_applied (bool applied); - -protected: - /// The next At_Thread_Exit hook in the list. - ACE_At_Thread_Exit *next_; - - /// Do the apply if necessary - void do_apply (void); - - /// The apply method. - virtual void apply (void) = 0; - - /// The Thread_Descriptor where this at is registered. - ACE_Thread_Descriptor* td_; - - /// The at was applied? - bool was_applied_; - - /// The at has the ownership of this? - bool is_owner_; -}; - -class ACE_Export ACE_At_Thread_Exit_Func : public ACE_At_Thread_Exit -{ -public: - /// Constructor - ACE_At_Thread_Exit_Func (void *object, - ACE_CLEANUP_FUNC func, - void *param = 0); - - virtual ~ACE_At_Thread_Exit_Func (void); - -protected: - /// The object to be cleanup - void *object_; - - /// The cleanup func - ACE_CLEANUP_FUNC func_; - - /// A param if required - void *param_; - - /// The apply method - void apply (void); -}; - -/** - * @class ACE_Thread_Descriptor_Base - * - * @brief Basic information for thread descriptors. These information - * gets extracted out because we need it after a thread is - * terminated. - * - * @internal - */ -class ACE_Export ACE_Thread_Descriptor_Base : public ACE_OS_Thread_Descriptor -{ - - friend class ACE_Thread_Manager; - friend class ACE_Double_Linked_List; - friend class ACE_Double_Linked_List_Iterator_Base; - friend class ACE_Double_Linked_List_Iterator; - friend class ACE_Double_Linked_List; - friend class ACE_Double_Linked_List_Iterator_Base; - friend class ACE_Double_Linked_List_Iterator; -public: - ACE_Thread_Descriptor_Base (void); - ~ACE_Thread_Descriptor_Base (void); - - // = We need the following operators to make Borland happy. - - /// Equality operator. - bool operator== (const ACE_Thread_Descriptor_Base &rhs) const; - - /// Inequality operator. - bool operator!= (const ACE_Thread_Descriptor_Base &rhs) const; - - /// Group ID. - int grp_id (void) const; - - /// Current state of the thread. - ACE_UINT32 state (void) const; - - /// Return the pointer to an ACE_Task_Base or NULL if there's no - /// ACE_Task_Base associated with this thread.; - ACE_Task_Base *task (void) const; - -protected: - /// Reset this base thread descriptor. - void reset (void); - - /// Unique thread ID. - ACE_thread_t thr_id_; - - /// Unique handle to thread (used by Win32 and AIX). - ACE_hthread_t thr_handle_; - - /// Group ID. - int grp_id_; - - /// Current state of the thread. - ACE_UINT32 thr_state_; - - /// Pointer to an ACE_Task_Base or NULL if there's no - /// ACE_Task_Base. - ACE_Task_Base *task_; - - /// We need these pointers to maintain the double-linked list in a - /// thread managers. - ACE_Thread_Descriptor_Base *next_; - ACE_Thread_Descriptor_Base *prev_; -}; - -/** - * @class ACE_Thread_Descriptor - * - * @brief Information for controlling threads that run under the control - * of the . - */ -class ACE_Export ACE_Thread_Descriptor : public ACE_Thread_Descriptor_Base -{ - friend class ACE_At_Thread_Exit; - friend class ACE_Thread_Manager; - friend class ACE_Double_Linked_List; - friend class ACE_Double_Linked_List_Iterator; -public: - // = Initialization method. - ACE_Thread_Descriptor (void); - - // = Accessor methods. - /// Unique thread id. - ACE_thread_t self (void) const; - - /// Unique handle to thread (used by Win32 and AIX). - void self (ACE_hthread_t &); - - /// Dump the state of an object. - void dump (void) const; - - /** - * This cleanup function must be called only for ACE_TSS_cleanup. - * The ACE_TSS_cleanup delegate Log_Msg instance destruction when - * Log_Msg cleanup is called before terminate. - */ - void log_msg_cleanup(ACE_Log_Msg* log_msg); - - /** - * Register an At_Thread_Exit hook and the ownership is acquire by - * Thread_Descriptor, this is the usual case when the AT is dynamically - * allocated. - */ - int at_exit (ACE_At_Thread_Exit* cleanup); - - /// Register an At_Thread_Exit hook and the ownership is retained for the - /// caller. Normally used when the at_exit hook is created in stack. - int at_exit (ACE_At_Thread_Exit& cleanup); - - /** - * Register an object (or array) for cleanup at thread termination. - * "cleanup_hook" points to a (global, or static member) function - * that is called for the object or array when it to be destroyed. - * It may perform any necessary cleanup specific for that object or - * its class. "param" is passed as the second parameter to the - * "cleanup_hook" function; the first parameter is the object (or - * array) to be destroyed. Returns 0 on success, non-zero on - * failure: -1 if virtual memory is exhausted or 1 if the object (or - * arrayt) had already been registered. - */ - int at_exit (void *object, - ACE_CLEANUP_FUNC cleanup_hook, - void *param); - - /// Do nothing destructor to keep some compilers happy - ~ACE_Thread_Descriptor (void); - - /** - * Do nothing but to acquire the thread descriptor's lock and - * release. This will first check if the thread is registered or - * not. If it is already registered, there's no need to reacquire - * the lock again. This is used mainly to get newly spawned thread - * in synch with thread manager and prevent it from accessing its - * thread descriptor before it gets fully built. This function is - * only called from ACE_Log_Msg::thr_desc. - */ - void acquire_release (void); - void acquire (void); - void release (void); - - /** - * Set/get the @c next_ pointer. These are required by the - * ACE_Free_List. - */ - void set_next (ACE_Thread_Descriptor *td); - ACE_Thread_Descriptor *get_next (void) const; - -private: - /// Reset this thread descriptor. - void reset (ACE_Thread_Manager *tm); - - /// Pop an At_Thread_Exit from at thread termination list, apply the at - /// if apply is true. - void at_pop (int apply = 1); - - /// Push an At_Thread_Exit to at thread termination list and set the - /// ownership of at. - void at_push (ACE_At_Thread_Exit* cleanup, - bool is_owner = false); - - /// Run the AT_Thread_Exit hooks. - void do_at_exit (void); - - /// Terminate realize the cleanup process to thread termination - void terminate (void); - - /// Thread_Descriptor is the ownership of ACE_Log_Msg if log_msg_!=0 - /// This can occur because ACE_TSS_cleanup was executed before terminate. - ACE_Log_Msg *log_msg_; - - /// The AT_Thread_Exit list - ACE_At_Thread_Exit *at_exit_list_; - -#if 0 -/// Currently not used - /** - * Stores the cleanup info for a thread. - * @note This should be generalized to be a stack of ACE_Cleanup_Info's. - */ - ACE_Cleanup_Info_Node_List cleanup_info_; -#endif - - /// Pointer to an ACE_Thread_Manager or NULL if there's no - /// ACE_Thread_Manager> - ACE_Thread_Manager* tm_; - - /// Registration lock to prevent premature removal of thread descriptor. - ACE_DEFAULT_THREAD_MANAGER_LOCK *sync_; - - /// Keep track of termination status. - bool terminated_; -}; - -// Forward declaration. -class ACE_Thread_Control; - -// This typedef should be (and used to be) inside the -// ACE_Thread_Manager declaration. But, it caused compilation -// problems on g++/VxWorks/i960 with -g. Note that -// ACE_Thread_Manager::THR_FUNC is only used internally in -// ACE_Thread_Manager, so it's not useful for anyone else. -// It also caused problems on IRIX5 with g++. -#if defined (__GNUG__) -typedef int (ACE_Thread_Manager::*ACE_THR_MEMBER_FUNC)(ACE_Thread_Descriptor *, int); -#endif /* __GNUG__ */ - -/** - * @class ACE_Thread_Manager - * - * @brief Manages a pool of threads. - * - * This class allows operations on groups of threads atomically. - * The default behavior of thread manager is to wait on - * all threads under it's management when it gets destructed. - * Therefore, remember to remove a thread from thread manager if - * you don't want it to wait for the thread. There are also - * functions to disable this default wait-on-exit behavior. - * However, if your program depends on turning this off to run - * correctly, you are probably doing something wrong. Rule of - * thumb, use ACE_Thread to manage your daemon threads. - * Notice that if there're threads which live beyond the scope of - * main(), you are sure to have resource leaks in your program. - * Remember to wait on threads before exiting your main program if that - * could happen in your programs. - */ -class ACE_Export ACE_Thread_Manager -{ -public: - friend class ACE_Thread_Control; - - // Allow ACE_THread_Exit to register the global TSS instance object. - friend class ACE_Thread_Exit; - friend class ACE_Thread_Descriptor; - -#if !defined (__GNUG__) - typedef int (ACE_Thread_Manager::*ACE_THR_MEMBER_FUNC)(ACE_Thread_Descriptor *, int); -#endif /* !__GNUG__ */ - - /// These are the various states a thread managed by the - /// ACE_Thread_Manager can be in. - enum - { - /// Uninitialized. - ACE_THR_IDLE = 0x00000000, - - /// Created but not yet running. - ACE_THR_SPAWNED = 0x00000001, - - /// Thread is active (naturally, we don't know if it's actually - /// *running* because we aren't the scheduler...). - ACE_THR_RUNNING = 0x00000002, - - /// Thread is suspended. - ACE_THR_SUSPENDED = 0x00000004, - - /// Thread has been cancelled (which is an indiction that it needs to - /// terminate...). - ACE_THR_CANCELLED = 0x00000008, - - /// Thread has shutdown, but the slot in the thread manager hasn't - /// been reclaimed yet. - ACE_THR_TERMINATED = 0x00000010, - - /// Join operation has been invoked on the thread by thread manager. - ACE_THR_JOINING = 0x10000000 - }; - - /** - * @brief Initialization and termination methods. - * - * Internally, ACE_Thread_Manager keeps a freelist for caching - * resources it uses to keep track of managed threads (not the - * threads themselves.) @a prealloc, @a lwm, @a inc, @hwm - * determine the initial size, the low water mark, increment step, - * and high water mark of the freelist. - * - * @sa ACE_Free_List - */ - ACE_Thread_Manager (size_t preaolloc = ACE_DEFAULT_THREAD_MANAGER_PREALLOC, - size_t lwm = ACE_DEFAULT_THREAD_MANAGER_LWM, - size_t inc = ACE_DEFAULT_THREAD_MANAGER_INC, - size_t hwm = ACE_DEFAULT_THREAD_MANAGER_HWM); - ~ACE_Thread_Manager (void); - -#if ! defined (ACE_THREAD_MANAGER_LACKS_STATICS) - /// Get pointer to a process-wide ACE_Thread_Manager. - static ACE_Thread_Manager *instance (void); - - /// Set pointer to a process-wide ACE_Thread_Manager and return - /// existing pointer. - static ACE_Thread_Manager *instance (ACE_Thread_Manager *); - - /// Delete the dynamically allocated Singleton - static void close_singleton (void); -#endif /* ! defined (ACE_THREAD_MANAGER_LACKS_STATICS) */ - - /// No-op. Currently unused. - int open (size_t size = 0); - - /** - * Release all resources. - * By default, this method will wait until all threads exit. - * However, when called from close_singleton(), most global resources - * are destroyed and thus, close() does not try to wait; it simply cleans - * up internal thread records (the thread descriptor list). - */ - int close (void); - - /** - * Create a new thread, which executes @a func with argument @a arg. - * - * @param func The function that is called in the spawned thread. - * - * @param arg The value passed to each spawned thread's @a func. - * - * @param flags Flags to control attributes of the spawned threads. - * @sa ACE_OS::thr_create() for descriptions of the - * possible flags values and their interactions. - * - * @param t_id Pointer to a location to receive the spawned thread's - * ID. If 0, the ID is not returned. - * - * @param t_handle Pointer to a location to receive the spawned thread's - * thread handle. If 0, the handle is not returned. - * - * @param priority The priority at which the thread is spawned. - * - * @param grp_id The thread group that the spawned thread is - * added to. If -1 is specified, a new thread group is - * created for the spawned thread. - * - * @param stack Pointers to the base of a pre-allocated stack space - * for the thread's stack. If 0, the platform allocates - * stack space for the thread. If a stack is specified, - * it is recommended that @a stack_size also be supplied - * to specify the size of the stack. - * Not all platforms support pre-allocated stacks. If - * @a stack is specified for a platform which does not - * allow pre-allocated stack space this parameter is - * ignored. - * - * @param stack_size Indicate how large the thread's stack should be, in - * bytes. If a pre-allocated stack pointer is passed in - * @a stack, @a stack_size indicates the size of that - * stack area. If no pre-allocated stack is passed, - * the stack size specified is passed to the - * operating system to request that it allocate a stack - * of the specified size. - * - * @param thr_name Pointer to a name to assign to the spawned thread. - * This is only meaningful for platforms that have a - * capacity to name threads (e.g., VxWorks and some - * varieties of Pthreads). This argument is ignored if - * specified as 0 and on platforms that do not have the - * capability to name threads. - * - * @retval -1 on failure; @c errno contains an error value. - * @retval The group id of the spawned thread. - */ - int spawn (ACE_THR_FUNC func, - void *arg = 0, - long flags = THR_NEW_LWP | THR_JOINABLE | THR_INHERIT_SCHED, - ACE_thread_t *t_id = 0, - ACE_hthread_t *t_handle = 0, - long priority = ACE_DEFAULT_THREAD_PRIORITY, - int grp_id = -1, - void *stack = 0, - size_t stack_size = ACE_DEFAULT_THREAD_STACKSIZE, - const char** thr_name = 0); - - /** - * Spawn a specified number of threads, all of which execute @a func - * with argument @a arg. - * - * @param n The number of threads to spawn. - * - * @param func The function that is called in the spawned thread. - * - * @param arg The value passed to each spawned thread's @a func. - * - * @param flags Flags to control attributes of the spawned threads. - * @sa ACE_OS::thr_create() for descriptions of the - * possible flags values and their interactions. - * - * @param priority The priority at which the threads are spawned. - * - * @param grp_id The thread group that the spawned threads are - * added to. If -1 is specified, a new thread group is - * created for the spawned threads. - * - * @param task The ACE_Task that the spawned threads are associated - * with. If 0, the threads are not associated with an - * ACE_Task. This argument is usually assigned by the - * ACE_Task_Base::activate() method to associate the - * spawned threads with the spawning ACE_Task object. - * - * @param thread_handles An array of @a n entries which will receive - * the thread handles of the spawned threads. - * - * @param stack An array of @a n pointers to pre-allocated stack space - * for each thread's stack. If specified as 0, the - * platform allocates stack space for each thread. If - * a stack is specified, it is recommended that a - * @a stack_size element also be supplied that specifies - * the size of the stack. - * Not all platforms support pre-allocated stacks. If - * @a stack is specified for a platform which does not - * allow pre-allocated stack space this parameter is - * ignored. - * - * @param stack_size An array of @a n values which indicate how large - * each thread's stack should be, in bytes. - * If pre-allocated stacks are passed in @a stacks, these - * sizes are for those stacks. If no pre-allocated stacks - * are passed, the stack sizes are specified to the - * operating system to request that it allocate stacks - * of the specified sizes. If an array entry is 0, the - * platform defaults are used for the corresponding thread. - * If a 0 array pointer is specified, platform defaults - * are used for all thread stack sizes. - * - * @param thr_name An array of names to assign to the spawned threads. - * This is only meaningful for platforms that have a - * capacity to name threads (e.g., VxWorks and some - * varieties of Pthreads). This argument is ignored if - * specified as 0 and on platforms that do not have the - * capability to name threads. - * - * ACE_Thread_Manager can manipulate threads in groups based on - * @a grp_id or @a task using functions such as kill_grp() or - * cancel_task(). - * - * @retval -1 on failure; @c errno contains an error value. - * @retval The group id of the threads. - */ - int spawn_n (size_t n, - ACE_THR_FUNC func, - void *arg = 0, - long flags = THR_NEW_LWP | THR_JOINABLE | THR_INHERIT_SCHED, - long priority = ACE_DEFAULT_THREAD_PRIORITY, - int grp_id = -1, - ACE_Task_Base *task = 0, - ACE_hthread_t thread_handles[] = 0, - void *stack[] = 0, - size_t stack_size[] = 0, - const char* thr_name[] = 0); - - /** - * Spawn a specified number of threads, all of which execute @a func - * with argument @a arg. - * - * @param thread_ids An array to receive the thread IDs of successfully - * spawned buffer. If 0, the thread IDs are not returned. - * If specified, the array must be at least @a n entries. - * - * @param n The number of threads to spawn. - * - * @param func The function that is called in the spawned thread. - * - * @param arg The value passed to each spawned thread's @a func. - * - * @param flags Flags to control attributes of the spawned threads. - * @sa ACE_OS::thr_create() for descriptions of the - * possible flags values and their interactions. - * - * @param priority The priority at which the threads are spawned. - * - * @param grp_id The thread group that the spawned threads are - * added to. If -1 is specified, a new thread group is - * created for the spawned threads. - * - * @param stack An array of @a n pointers to pre-allocated stack space - * for each thread's stack. If specified as 0, the - * platform allocates stack space for each thread. If - * a stack is specified, it is recommended that a - * @a stack_size element also be supplied that specifies - * the size of the stack. - * Not all platforms support pre-allocated stacks. If - * @a stack is specified for a platform which does not - * allow pre-allocated stack space this parameter is - * ignored. - * - * @param stack_size An array of @a n values which indicate how large - * each thread's stack should be, in bytes. - * If pre-allocated stacks are passed in @a stacks, these - * sizes are for those stacks. If no pre-allocated stacks - * are passed, the stack sizes are specified to the - * operating system to request that it allocate stacks - * of the specified sizes. If an array entry is 0, the - * platform defaults are used for the corresponding thread. - * If a 0 array pointer is specified, platform defaults - * are used for all thread stack sizes. - * - * @param thread_handles An array of @a n entries which will receive - * the thread handles of the spawned threads. - * - * @param task The ACE_Task that the spawned threads are associated - * with. If 0, the threads are not associated with an - * ACE_Task. This argument is usually assigned by the - * ACE_Task_Base::activate() method to associate the - * spawned threads with the spawning ACE_Task object. - * - * @param thr_name An array of names to assign to the spawned threads. - * This is only meaningful for platforms that have a - * capacity to name threads (e.g., VxWorks and some - * varieties of Pthreads). This argument is ignored if - * specified as 0 and on platforms that do not have the - * capability to name threads. - * - * ACE_Thread_Manager can manipulate threads in groups based on - * @a grp_id or @a task using functions such as kill_grp() or - * cancel_task(). - * - * @retval -1 on failure; @c errno contains an error value. - * @retval The group id of the threads. - - */ - int spawn_n (ACE_thread_t thread_ids[], - size_t n, - ACE_THR_FUNC func, - void *arg, - long flags, - long priority = ACE_DEFAULT_THREAD_PRIORITY, - int grp_id = -1, - void *stack[] = 0, - size_t stack_size[] = 0, - ACE_hthread_t thread_handles[] = 0, - ACE_Task_Base *task = 0, - const char* thr_name[] = 0); - - /** - * Called to clean up when a thread exits. - * - * @param do_thread_exit If non-0 then ACE_Thread::exit is called to - * exit the thread - * @param status If ACE_Thread_Exit is called, this is passed as - * the exit value of the thread. - * Should _not_ be called by main thread. - */ - ACE_THR_FUNC_RETURN exit (ACE_THR_FUNC_RETURN status = 0, - bool do_thread_exit = true); - - /** - * Block until there are no more threads running in this thread - * manager or @c timeout expires. - * - * @param timeout is treated as "absolute" time by default, but this - * can be changed to "relative" time by setting the @c - * use_absolute_time to false. - * @param abandon_detached_threads If true, @c wait() will first - * check thru its thread list for - * threads with THR_DETACHED or - * THR_DAEMON flags set and remove - * these threads. Notice that - * unlike other @c wait_*() methods, - * by default, @c wait() does wait on - * all thread spawned by this - * thread manager no matter the detached - * flags are set or not unless it is - * called with @c - * abandon_detached_threads flag set. - * @param use_absolute_time If true then treat @c timeout as - * absolute time, else relative time. - * @return 0 on success * and -1 on failure. - * - * @note If this function is called while the @c - * ACE_Object_Manager is shutting down (as a result of program - * rundown via @c ACE::fini()), it will not wait for any threads to - * complete. If you must wait for threads spawned by this thread - * manager to complete and you are in a ACE rundown situation (such - * as your object is being destroyed by the @c ACE_Object_Manager) - * you can use @c wait_grp() instead. - */ - int wait (const ACE_Time_Value *timeout = 0, - bool abandon_detached_threads = false, - bool use_absolute_time = true); - - /// Join a thread specified by @a tid. Do not wait on a detached thread. - int join (ACE_thread_t tid, ACE_THR_FUNC_RETURN *status = 0); - - /** - * Block until there are no more threads running in a group. - * Returns 0 on success and -1 on failure. Notice that wait_grp - * will not wait on detached threads. - */ - int wait_grp (int grp_id); - - /** - * Return the "real" handle to the calling thread, caching it if - * necessary in TSS to speed up subsequent lookups. This is - * necessary since on some platforms (e.g., Windows) we can't get this - * handle via direct method calls. Notice that you should *not* - * close the handle passed back from this method. It is used - * internally by Thread Manager. On the other hand, you *have to* - * use this internal thread handle when working on Thread_Manager. - * Return -1 if fail. - */ - int thr_self (ACE_hthread_t &); - - /** - * Return the unique ID of the calling thread. - * Same as calling ACE_Thread::self(). - */ - ACE_thread_t thr_self (void); - - /** - * Returns a pointer to the current ACE_Task_Base we're executing - * in if this thread is indeed running in an ACE_Task_Base, else - * return 0. - */ - ACE_Task_Base *task (void); - - /** - * @name Suspend and resume methods - * - * Suspend/resume is not supported on all platforms. For example, Pthreads - * does not support these functions. - */ - //@{ - - /// Suspend all threads - int suspend_all (void); - - /// Suspend a single thread. - int suspend (ACE_thread_t); - - /// Suspend a group of threads. - int suspend_grp (int grp_id); - - /** - * True if @a t_id is inactive (i.e., suspended), else false. Always - * return false if @a t_id is not managed by the Thread_Manager. - */ - int testsuspend (ACE_thread_t t_id); - - /// Resume all stopped threads - int resume_all (void); - - /// Resume a single thread. - int resume (ACE_thread_t); - - /// Resume a group of threads. - int resume_grp (int grp_id); - - /** - * True if @a t_id is active (i.e., resumed), else false. Always - * return false if @a t_id is not managed by the Thread_Manager. - */ - int testresume (ACE_thread_t t_id); - - //@} - - // = Send signals to one or more threads without blocking. - /** - * Send @a signum to all stopped threads. Not supported on platforms - * that do not have advanced signal support, such as Win32. - */ - int kill_all (int signum); - /** - * Send the @a signum to a single thread. Not supported on platforms - * that do not have advanced signal support, such as Win32. - */ - int kill (ACE_thread_t, int signum); - /** - * Send @a signum to a group of threads, not supported on platforms - * that do not have advanced signal support, such as Win32. - */ - int kill_grp (int grp_id, int signum); - - // = Cancel methods, which provides a cooperative thread-termination mechanism (will not block). - /** - * Cancel's all the threads. - */ - int cancel_all (int async_cancel = 0); - - /** - * Cancel a single thread. - */ - int cancel (ACE_thread_t, int async_cancel = 0); - - /** - * Cancel a group of threads. - */ - int cancel_grp (int grp_id, int async_cancel = 0); - - /** - * True if @a t_id is cancelled, else false. Always return false if - * @a t_id is not managed by the Thread_Manager. - */ - int testcancel (ACE_thread_t t_id); - - /** - * True if @a t_id has terminated (i.e., is no longer running), - * but the slot in the thread manager hasn't been reclaimed yet, - * else false. Always return false if @a t_id is not managed by the - * Thread_Manager. - */ - int testterminate (ACE_thread_t t_id); - - /// Set group ids for a particular thread id. - int set_grp (ACE_thread_t, - int grp_id); - - /// Get group ids for a particular thread id. - int get_grp (ACE_thread_t, - int &grp_id); - - /** - * @name Task-related operations - */ - //@{ - /** - * Block until there are no more threads running in a specified task. - * This method will not wait for either detached or daemon threads; - * the threads must have been spawned with the @c THR_JOINABLE flag. - * Upon successful completion, the threads have been joined, so further - * attempts to join with any of the waited-for threads will fail. - * - * @param task The ACE_Task_Base object whose threads are to waited for. - * - * @retval 0 Success. - * @retval -1 Failure (consult errno for further information). - */ - int wait_task (ACE_Task_Base *task); - - /** - * Suspend all threads in an ACE_Task. - */ - int suspend_task (ACE_Task_Base *task); - - /** - * Resume all threads in an ACE_Task. - */ - int resume_task (ACE_Task_Base *task); - - /** - * Send a signal @a signum to all threads in an ACE_Task. - */ - int kill_task (ACE_Task_Base *task, int signum); - - /** - * Cancel all threads in an ACE_Task. If is non-0, - * then asynchronously cancel these threads if the OS platform - * supports cancellation. Otherwise, perform a "cooperative" - * cancellation. - */ - int cancel_task (ACE_Task_Base *task, int async_cancel = 0); - - //@} - - // = Collect thread handles in the thread manager. Notice that - // the collected information is just a snapshot. - /// Check if the thread is managed by the thread manager. Return true if - /// the thread is found, false otherwise. - int hthread_within (ACE_hthread_t handle); - int thread_within (ACE_thread_t tid); - - /// Returns the number of ACE_Task_Base in a group. - int num_tasks_in_group (int grp_id); - - /// Returns the number of threads in an ACE_Task_Base. - int num_threads_in_task (ACE_Task_Base *task); - - /** - * Returns a list of ACE_Task_Base pointers corresponding to the tasks - * that have active threads in a specified thread group. - * - * @param grp_id The thread group ID to obtain task pointers for. - * - * @param task_list is a pointer to an array to receive the list of pointers. - * The caller is responsible for supplying an array with at - * least @arg n entries. - * - * @param n The maximum number of ACE_Task_Base pointers to write - * in @arg task_list. - * - * @retval If successful, the number of pointers returned, which will be - * no greater than @arg n. Returns -1 on error. - * - * @note This method has no way to indicate if there are more than - * @arg n ACE_Task_Base pointers available. Therefore, it may be - * wise to guess a larger value of @arg n than one thinks in cases - * where the exact number of tasks is not known. - * - * @sa num_tasks_in_group(), task_all_list() - */ - ssize_t task_list (int grp_id, - ACE_Task_Base *task_list[], - size_t n); - - /** - * Returns in @a thread_list a list of up to @a n thread ids in an - * ACE_Task_Base. The caller must allocate the memory for - * @a thread_list. In case of an error, -1 is returned. If no - * requested values are found, 0 is returned, otherwise correct - * number of retrieved values are returned. - */ - ssize_t thread_list (ACE_Task_Base *task, - ACE_thread_t thread_list[], - size_t n); - - /** - * Returns in @a hthread_list a list of up to @a n thread handles in - * an ACE_Task_Base. The caller must allocate memory for - * @a hthread_list. In case of an error, -1 is returned. If no - * requested values are found, 0 is returned, otherwise correct - * number of retrieved values are returned. - */ - ssize_t hthread_list (ACE_Task_Base *task, - ACE_hthread_t hthread_list[], - size_t n); - - /** - * Returns in @a thread_list a list of up to @a n thread ids in a - * group @a grp_id. The caller must allocate the memory for - * @a thread_list. In case of an error, -1 is returned. If no - * requested values are found, 0 is returned, otherwise correct - * number of retrieved values are returned. - */ - ssize_t thread_grp_list (int grp_id, - ACE_thread_t thread_list[], - size_t n); - - /** - * Returns in @a hthread_list a list of up to @a n thread handles in - * a group @a grp_id. The caller must allocate memory for - * @a hthread_list. - */ - ssize_t hthread_grp_list (int grp_id, - ACE_hthread_t hthread_list[], - size_t n); - - /** - * Returns a list of ACE_Task_Base pointers corresponding to the tasks - * that have active threads managed by this instance. - * - * @param task_list is a pointer to an array to receive the list of pointers. - * The caller is responsible for supplying an array with at - * least @arg n entries. - * - * @param n The maximum number of ACE_Task_Base pointers to write - * in @arg task_list. - * - * @retval If successful, the number of pointers returned, which will be - * no greater than @arg n. Returns -1 on error. - * - * @note This method has no way to indicate if there are more than - * @arg n ACE_Task_Base pointers available. Therefore, it may be - * wise to guess a larger value of @arg n than one thinks in cases - * where the exact number of tasks is not known. - * - * @sa count_threads() - */ - ssize_t task_all_list (ACE_Task_Base *task_list[], - size_t n); - - /** - * Returns in @a thread_list a list of up to @a n thread ids. The - * caller must allocate the memory for @a thread_list. In case of an - * error, -1 is returned. If no requested values are found, 0 is - * returned, otherwise correct number of retrieved values are - * returned. - */ - ssize_t thread_all_list (ACE_thread_t thread_list[], - size_t n); - - /// Set group ids for a particular task. - int set_grp (ACE_Task_Base *task, int grp_id); - - /// Get group ids for a particular task. - int get_grp (ACE_Task_Base *task, int &grp_id); - - /// Return a count of the current number of threads active in the - /// . - size_t count_threads (void) const; - - /// Get the state of the thread. Returns false if the thread is not - /// managed by this thread manager. - int thr_state (ACE_thread_t id, ACE_UINT32& state); - - /** - * Register an At_Thread_Exit hook and the ownership is acquire by - * Thread_Descriptor, this is the usual case when the AT is dynamically - * allocated. - */ - int at_exit (ACE_At_Thread_Exit* cleanup); - - /// Register an At_Thread_Exit hook and the ownership is retained for the - /// caller. Normally used when the at_exit hook is created in stack. - int at_exit (ACE_At_Thread_Exit& cleanup); - - /** - * - ***** - * @deprecated This function is deprecated. Please use the previous two - * at_exit method. Notice that you should avoid mixing this method - * with the previous two at_exit methods. - ***** - * - * Register an object (or array) for cleanup at - * thread termination. "cleanup_hook" points to a (global, or - * static member) function that is called for the object or array - * when it to be destroyed. It may perform any necessary cleanup - * specific for that object or its class. "param" is passed as the - * second parameter to the "cleanup_hook" function; the first - * parameter is the object (or array) to be destroyed. - * "cleanup_hook", for example, may delete the object (or array). - * If == 0, the will _NOT_ get cleanup at - * thread exit. You can use this to cancel the previously added - * at_exit. - */ - int at_exit (void *object, - ACE_CLEANUP_FUNC cleanup_hook, - void *param); - - /// Access function to determine whether the Thread_Manager will - /// wait for its thread to exit or not when being closing down. - void wait_on_exit (int dowait); - int wait_on_exit (void); - - /// Dump the state of an object. - void dump (void); - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - // = Accessors for ACE_Thread_Descriptors. - /** - * Get a pointer to the calling thread's own thread_descriptor. - * This must be called from a spawn thread. This function will - * fetch the info from TSS. - */ - ACE_Thread_Descriptor *thread_desc_self (void); - - /// Return a pointer to the thread's Thread_Descriptor, - /// 0 if fail. - ACE_Thread_Descriptor *thread_descriptor (ACE_thread_t); - - /// Return a pointer to the thread's Thread_Descriptor, - /// 0 if fail. - ACE_Thread_Descriptor *hthread_descriptor (ACE_hthread_t); - - /// Create a new thread (must be called with locks held). - int spawn_i (ACE_THR_FUNC func, - void *arg, - long flags, - ACE_thread_t * = 0, - ACE_hthread_t *t_handle = 0, - long priority = ACE_DEFAULT_THREAD_PRIORITY, - int grp_id = -1, - void *stack = 0, - size_t stack_size = 0, - ACE_Task_Base *task = 0, - const char** thr_name = 0); - - /// Run the registered hooks when the thread exits. - void run_thread_exit_hooks (int i); - - /// Locate the index of the table slot occupied by . Returns - /// -1 if is not in the table doesn't contain . - ACE_Thread_Descriptor *find_thread (ACE_thread_t t_id); - - /// Locate the index of the table slot occupied by . Returns - /// -1 if is not in the table doesn't contain . - ACE_Thread_Descriptor *find_hthread (ACE_hthread_t h_id); - - /** - * Locate the thread descriptor address of the list occupied by - * @a task. Returns 0 if @a task is not in the table doesn't contain - * @a task. - */ - ACE_Thread_Descriptor *find_task (ACE_Task_Base *task, - size_t slot = 0); - - /// Insert a thread in the table (checks for duplicates). - int insert_thr (ACE_thread_t t_id, - ACE_hthread_t, - int grp_id = -1, - long flags = 0); - - /// Append a thread in the table (adds at the end, growing the table - /// if necessary). - int append_thr (ACE_thread_t t_id, ACE_hthread_t, - ACE_UINT32, - int grp_id, - ACE_Task_Base *task = 0, - long flags = 0, - ACE_Thread_Descriptor *td = 0); - - /// Remove thread from the table. - void remove_thr (ACE_Thread_Descriptor *td, - int close_handler); - - /// Remove all threads from the table. - void remove_thr_all (void); - - // = The following four methods implement a simple scheme for - // operating on a collection of threads atomically. - - /** - * Efficiently check whether @a thread is in a particular @a state. - * This call updates the TSS cache if possible to speed up - * subsequent searches. - */ - int check_state (ACE_UINT32 state, - ACE_thread_t thread, - int enable = 1); - - /// Apply @a func to all members of the table that match the @a task - int apply_task (ACE_Task_Base *task, - ACE_THR_MEMBER_FUNC func, - int = 0); - - /// Apply @a func to all members of the table that match the @a grp_id. - int apply_grp (int grp_id, - ACE_THR_MEMBER_FUNC func, - int arg = 0); - - /// Apply @a func to all members of the table. - int apply_all (ACE_THR_MEMBER_FUNC, - int = 0); - - /// Join the thread described in @a td. - int join_thr (ACE_Thread_Descriptor *td, - int = 0); - - /// Resume the thread described in @a td. - int resume_thr (ACE_Thread_Descriptor *td, - int = 0); - - /// Suspend the thread described in @a td. - int suspend_thr (ACE_Thread_Descriptor *td, - int = 0); - - /// Send signal @a signum to the thread described in @a td. - int kill_thr (ACE_Thread_Descriptor *td, - int signum); - - /// Set the cancellation flag for the thread described in @a td. - int cancel_thr (ACE_Thread_Descriptor *td, - int async_cancel = 0); - - /// Register a thread as terminated and put it into the . - int register_as_terminated (ACE_Thread_Descriptor *td); - - /// Setting the static ACE_TSS_TYPE (ACE_Thread_Exit) *thr_exit_ pointer. - static int set_thr_exit (ACE_TSS_TYPE (ACE_Thread_Exit) *ptr); - - /** - * Keeping a list of thread descriptors within the thread manager. - * Double-linked list enables us to cache the entries in TSS - * and adding/removing thread descriptor entries without - * affecting other thread's descriptor entries. - */ - ACE_Double_Linked_List thr_list_; - -#if !defined (ACE_HAS_VXTHREADS) - /// Collect terminated but not yet joined thread entries. - ACE_Double_Linked_List terminated_thr_list_; -#endif /* !ACE_HAS_VXTHREADS */ - - /// Collect pointers to thread descriptors of threads to be removed later. - ACE_Unbounded_Queue thr_to_be_removed_; - - /// Keeps track of the next group id to assign. - int grp_id_; - - /// Set if we want the Thread_Manager to wait on all threads before - /// being closed, reset otherwise. - int automatic_wait_; - - // = ACE_Thread_Mutex and condition variable for synchronizing termination. -#if defined (ACE_HAS_THREADS) - /// Serialize access to the . - ACE_Thread_Mutex lock_; - - /// Keep track of when there are no more threads. - ACE_Condition_Thread_Mutex zero_cond_; -#endif /* ACE_HAS_THREADS */ - - ACE_Locked_Free_List thread_desc_freelist_; - -private: -#if ! defined (ACE_THREAD_MANAGER_LACKS_STATICS) - /// Pointer to a process-wide ACE_Thread_Manager. - static ACE_Thread_Manager *thr_mgr_; - - /// Must delete the thr_mgr_ if true. - static bool delete_thr_mgr_; - - /// Global ACE_TSS (ACE_Thread_Exit) object ptr. - static ACE_TSS_TYPE (ACE_Thread_Exit) *thr_exit_; -#endif /* ! defined (ACE_THREAD_MANAGER_LACKS_STATICS) */ -}; - -#if defined (ACE_THREAD_MANAGER_LACKS_STATICS) -#define ACE_THREAD_MANAGER_SINGLETON_DEFINE \ - ACE_Singleton; -typedef ACE_Singleton ACE_THREAD_MANAGER_SINGLETON; -#endif /* defined (ACE_THREAD_MANAGER_LACKS_STATICS) */ - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Thread_Manager.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif /* ACE_THREAD_MANAGER_H */ diff --git a/externals/ace/Thread_Manager.inl b/externals/ace/Thread_Manager.inl deleted file mode 100644 index 4b9afe979c0..00000000000 --- a/externals/ace/Thread_Manager.inl +++ /dev/null @@ -1,305 +0,0 @@ -// -*- C++ -*- -// -// $Id: Thread_Manager.inl 85341 2009-05-14 11:07:37Z johnnyw $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE -ACE_At_Thread_Exit::ACE_At_Thread_Exit (void) - : next_ (0), - td_ (0), - was_applied_ (false), - is_owner_ (true) -{ -} - -ACE_INLINE bool -ACE_At_Thread_Exit::was_applied() const -{ - return was_applied_; -} - -ACE_INLINE bool -ACE_At_Thread_Exit::was_applied (bool applied) -{ - was_applied_ = applied; - if (was_applied_) - td_ = 0; - return was_applied_; -} - -ACE_INLINE bool -ACE_At_Thread_Exit::is_owner() const -{ - return is_owner_; -} - -ACE_INLINE bool -ACE_At_Thread_Exit::is_owner (bool owner) -{ - is_owner_ = owner; - return is_owner_; -} - -ACE_INLINE void -ACE_At_Thread_Exit::do_apply (void) -{ - if (!this->was_applied_ && this->is_owner_) - td_->at_pop(); -} - -ACE_INLINE -ACE_At_Thread_Exit_Func::ACE_At_Thread_Exit_Func (void *object, - ACE_CLEANUP_FUNC func, - void *param) - : object_(object), - func_(func), - param_(param) -{ -} - -ACE_INLINE -ACE_Thread_Descriptor_Base::ACE_Thread_Descriptor_Base (void) - : ACE_OS_Thread_Descriptor (), - thr_id_ (ACE_OS::NULL_thread), - thr_handle_ (ACE_OS::NULL_hthread), - grp_id_ (0), - thr_state_ (ACE_Thread_Manager::ACE_THR_IDLE), - task_ (0), - next_ (0), - prev_ (0) -{ -} - -ACE_INLINE -ACE_Thread_Descriptor_Base::~ACE_Thread_Descriptor_Base (void) -{ -} - -ACE_INLINE bool -ACE_Thread_Descriptor_Base::operator== ( - const ACE_Thread_Descriptor_Base &rhs) const -{ - return - ACE_OS::thr_cmp (this->thr_handle_, rhs.thr_handle_) - && ACE_OS::thr_equal (this->thr_id_, rhs.thr_id_); -} - -ACE_INLINE bool -ACE_Thread_Descriptor_Base::operator!=(const ACE_Thread_Descriptor_Base &rhs) const -{ - return !(*this == rhs); -} - -ACE_INLINE ACE_Task_Base * -ACE_Thread_Descriptor_Base::task (void) const -{ - ACE_TRACE ("ACE_Thread_Descriptor_Base::task"); - return this->task_; -} - -// Group ID. - -ACE_INLINE int -ACE_Thread_Descriptor_Base::grp_id (void) const -{ - ACE_TRACE ("ACE_Thread_Descriptor_Base::grp_id"); - return grp_id_; -} - -// Current state of the thread. -ACE_INLINE ACE_UINT32 -ACE_Thread_Descriptor_Base::state (void) const -{ - ACE_TRACE ("ACE_Thread_Descriptor_Base::state"); - return thr_state_; -} - -// Reset this base descriptor. -ACE_INLINE void -ACE_Thread_Descriptor_Base::reset (void) -{ - ACE_TRACE ("ACE_Thread_Descriptor_Base::reset"); - this->thr_id_ = ACE_OS::NULL_thread; - this->thr_handle_ = ACE_OS::NULL_hthread; - this->grp_id_ = 0; - this->thr_state_ = ACE_Thread_Manager::ACE_THR_IDLE; - this->task_ = 0; - this->flags_ = 0; -} - -// Unique thread id. -ACE_INLINE ACE_thread_t -ACE_Thread_Descriptor::self (void) const -{ - ACE_TRACE ("ACE_Thread_Descriptor::self"); - return this->thr_id_; -} - -// Unique kernel-level thread handle. - -ACE_INLINE void -ACE_Thread_Descriptor::self (ACE_hthread_t &handle) -{ - ACE_TRACE ("ACE_Thread_Descriptor::self"); - handle = this->thr_handle_; -} - -ACE_INLINE void -ACE_Thread_Descriptor::log_msg_cleanup (ACE_Log_Msg* log_msg) - -{ - log_msg_ = log_msg; -} - -// Set the pointer -ACE_INLINE void -ACE_Thread_Descriptor::set_next (ACE_Thread_Descriptor *td) -{ - ACE_TRACE ("ACE_Thread_Descriptor::set_next"); - this->next_ = td; -} - -// Get the pointer -ACE_INLINE ACE_Thread_Descriptor * -ACE_Thread_Descriptor::get_next (void) const -{ - ACE_TRACE ("ACE_Thread_Descriptor::get_next"); - return static_cast (this->next_); -} - -// Reset this thread descriptor -ACE_INLINE void -ACE_Thread_Descriptor::reset (ACE_Thread_Manager *tm) -{ - ACE_TRACE ("ACE_Thread_Descriptor::reset"); - this->ACE_Thread_Descriptor_Base::reset (); - this->at_exit_list_ = 0; - // Start the at_exit hook list. - this->tm_ = tm; - // Setup the Thread_Manager. - this->log_msg_ = 0; - this->terminated_ = false; -} - -ACE_INLINE ACE_Thread_Descriptor * -ACE_Thread_Manager::thread_desc_self (void) -{ - // This method must be called with lock held. - - // Try to get it from cache. - ACE_Thread_Descriptor *desc = ACE_LOG_MSG->thr_desc (); - -#if 1 - // ACE_ASSERT (desc != 0); - // Thread descriptor should always get cached. -#else - if (desc == 0) - { - ACE_thread_t id = ACE_OS::thr_self (); - - desc = this->find_thread (id); - - // Thread descriptor adapter might not have been put into the - // list yet. - if (desc != 0) - // Update the TSS cache. - ACE_LOG_MSG->thr_desc (desc); - } -#endif - return desc; -} - -// Return the unique ID of the thread. - -ACE_INLINE ACE_thread_t -ACE_Thread_Manager::thr_self (void) -{ - ACE_TRACE ("ACE_Thread_Manager::thr_self"); - return ACE_Thread::self (); -} - -ACE_INLINE ACE_Task_Base * -ACE_Thread_Manager::task (void) -{ - ACE_TRACE ("ACE_Thread_Manager::task"); - - ACE_Thread_Descriptor *td = this->thread_desc_self () ; - - if (td == 0) - return 0; - else - return td->task (); -} - -ACE_INLINE int -ACE_Thread_Manager::open (size_t) -{ - // Currently no-op. - return 0; -} - -ACE_INLINE int -ACE_Thread_Manager::at_exit (ACE_At_Thread_Exit* at) -{ - ACE_Thread_Descriptor *td = this->thread_desc_self (); - if (td == 0) - return -1; - else - return td->at_exit (at); -} - -ACE_INLINE int -ACE_Thread_Manager::at_exit (ACE_At_Thread_Exit& at) -{ - ACE_Thread_Descriptor *td = this->thread_desc_self (); - if (td == 0) - return -1; - else - return td->at_exit (at); -} - -ACE_INLINE int -ACE_Thread_Manager::at_exit (void *object, - ACE_CLEANUP_FUNC cleanup_hook, - void *param) -{ - ACE_Thread_Descriptor *td = this->thread_desc_self (); - if (td == 0) - return -1; - else - return td->at_exit (object, cleanup_hook, param); -} - -ACE_INLINE void -ACE_Thread_Manager::wait_on_exit (int do_wait) -{ - this->automatic_wait_ = do_wait; -} - -ACE_INLINE int -ACE_Thread_Manager::wait_on_exit (void) -{ - return this->automatic_wait_; -} - -ACE_INLINE int -ACE_Thread_Manager::register_as_terminated (ACE_Thread_Descriptor *td) -{ -#if defined (ACE_HAS_VXTHREADS) - ACE_UNUSED_ARG (td); -#else /* ! ACE_HAS_VXTHREADS */ - ACE_Thread_Descriptor_Base *tdb = 0; - ACE_NEW_RETURN (tdb, ACE_Thread_Descriptor_Base (*td), -1); - this->terminated_thr_list_.insert_tail (tdb); -#endif /* !ACE_HAS_VXTHREADS */ - return 0; -} - -ACE_INLINE size_t -ACE_Thread_Manager::count_threads (void) const -{ - return this->thr_list_.size (); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Thread_Mutex.cpp b/externals/ace/Thread_Mutex.cpp deleted file mode 100644 index 4ebdc412e6f..00000000000 --- a/externals/ace/Thread_Mutex.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/** - * @file Thread_Mutex.cpp - * - * $Id: Thread_Mutex.cpp 80826 2008-03-04 14:51:23Z wotte $ - * - * Originally in Synch.cpp - * - * @author Douglas C. Schmidt - */ - -#include "ace/Thread_Mutex.h" - -#if defined (ACE_HAS_THREADS) - -#if !defined (__ACE_INLINE__) -#include "ace/Thread_Mutex.inl" -#endif /* __ACE_INLINE__ */ - -#include "ace/Log_Msg.h" -#include "ace/Malloc_T.h" - -ACE_RCSID(ace, Thread_Mutex, "$Id: Thread_Mutex.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Thread_Mutex) - -void -ACE_Thread_Mutex::dump (void) const -{ -#if defined (ACE_HAS_DUMP) -// ACE_TRACE ("ACE_Thread_Mutex::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n"))); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -ACE_Thread_Mutex::~ACE_Thread_Mutex (void) -{ -// ACE_TRACE ("ACE_Thread_Mutex::~ACE_Thread_Mutex"); - this->remove (); -} - -ACE_Thread_Mutex::ACE_Thread_Mutex (const ACE_TCHAR *name, ACE_mutexattr_t *arg) - : removed_ (false) -{ -// ACE_TRACE ("ACE_Thread_Mutex::ACE_Thread_Mutex"); - - if (ACE_OS::thread_mutex_init (&this->lock_, - 0, - name, - arg) != 0) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_Thread_Mutex::ACE_Thread_Mutex"))); -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_THREADS */ diff --git a/externals/ace/Thread_Mutex.h b/externals/ace/Thread_Mutex.h deleted file mode 100644 index fd8f3959587..00000000000 --- a/externals/ace/Thread_Mutex.h +++ /dev/null @@ -1,176 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file Thread_Mutex.h - * - * $Id: Thread_Mutex.h 89127 2010-02-22 19:58:18Z schmidt $ - * - * Moved from Synch.h. - * - * @author Douglas C. Schmidt - */ -//========================================================================== - -#ifndef ACE_THREAD_MUTEX_H -#define ACE_THREAD_MUTEX_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_HAS_THREADS) -# include "ace/Null_Mutex.h" -#else /* ACE_HAS_THREADS */ -// ACE platform supports some form of threading. - -#include /**/ "ace/ACE_export.h" -#include "ace/OS_NS_Thread.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Thread_Mutex - * - * @brief ACE_Thread_Mutex wrapper (only valid for threads in the same - * process). - * - * This implementation is optimized for locking threads that are - * in the same process. It maps to s on NT - * and with set to on UNIX. - * ACE_Thread_Mutex is recursive on some platforms (like - * Win32). However, on most platforms (like Solaris) it is not - * recursive. To be totally safe and portable, developers - * should use ACE_Recursive_Thread_Mutex when they need a - * recursive mutex. - */ -class ACE_Export ACE_Thread_Mutex -{ - friend class ACE_Condition_Thread_Mutex; -public: - /// Constructor. - ACE_Thread_Mutex (const ACE_TCHAR *name = 0, - ACE_mutexattr_t *attributes = 0); - - /// Implicitly destroy the mutex. - ~ACE_Thread_Mutex (void); - - /** - * Explicitly destroy the mutex. Note that only one thread should - * call this method since it doesn't protect against race - * conditions. - */ - int remove (void); - - /// Acquire lock ownership (wait on queue if necessary). - int acquire (void); - - /** - * Block the thread until we acquire the mutex or until @a tv times - * out, in which case -1 is returned with @c errno == @c ETIME. Note - * that @a tv is assumed to be in "absolute" rather than "relative" - * time. The value of @a tv is updated upon return to show the - * actual (absolute) acquisition time. - */ - int acquire (ACE_Time_Value &tv); - - /** - * If @a tv == 0 the call directly. Otherwise, Block the - * thread until we acquire the mutex or until @a tv times out, in - * which case -1 is returned with @c errno == @c ETIME. Note that - * @a tv is assumed to be in "absolute" rather than "relative" time. - * The value of @a tv is updated upon return to show the actual - * (absolute) acquisition time. - */ - int acquire (ACE_Time_Value *tv); - - /** - * Conditionally acquire lock (i.e., don't wait on queue). Returns - * -1 on failure. If we "failed" because someone else already had - * the lock, @c errno is set to @c EBUSY. - */ - int tryacquire (void); - - /// Release lock and unblock a thread at head of queue. - int release (void); - - /** - * Acquire mutex ownership. This calls acquire() and is only here - * to make the ACE_Thread_Mutex interface consistent with the - * other synchronization APIs. - */ - int acquire_read (void); - - /** - * Acquire mutex ownership. This calls acquire() and is only here - * to make the ACE_Thread_Mutex interface consistent with the - * other synchronization APIs. - */ - int acquire_write (void); - - /** - * Conditionally acquire mutex (i.e., won't block). This calls - * tryacquire() and is only here to make the ACE_Thread_Mutex - * interface consistent with the other synchronization APIs. - * Returns -1 on failure. If we "failed" because someone else - * already had the lock, @c errno is set to @c EBUSY. - */ - int tryacquire_read (void); - - /** - * Conditionally acquire mutex (i.e., won't block). This calls - * tryacquire() and is only here to make the ACE_Thread_Mutex - * interface consistent with the other synchronization APIs. - * Returns -1 on failure. If we "failed" because someone else - * already had the lock, @c errno is set to @c EBUSY. - */ - int tryacquire_write (void); - - /** - * This is only here to make the ACE_Thread_Mutex interface - * consistent with the other synchronization APIs. Assumes the - * caller has already acquired the mutex using one of the above - * calls, and returns 0 (success) always. - */ - int tryacquire_write_upgrade (void); - - /// Return the underlying mutex. - const ACE_thread_mutex_t &lock (void) const; - ACE_thread_mutex_t &lock (void); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - /// Mutex type that supports single-process locking efficiently. - ACE_thread_mutex_t lock_; - - /// Keeps track of whether remove() has been called yet to avoid - /// multiple calls, e.g., explicitly and implicitly in the - /// destructor. This flag isn't protected by a lock, so make sure - /// that you don't have multiple threads simultaneously calling - /// on the same object, which is a bad idea anyway... - bool removed_; - -private: - // = Prevent assignment and initialization. - void operator= (const ACE_Thread_Mutex &); - ACE_Thread_Mutex (const ACE_Thread_Mutex &); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Thread_Mutex.inl" -#endif /* __ACE_INLINE__ */ - -#endif /* !ACE_HAS_THREADS */ - -#include /**/ "ace/post.h" -#endif /* ACE_THREAD_MUTEX_H */ diff --git a/externals/ace/Thread_Mutex.inl b/externals/ace/Thread_Mutex.inl deleted file mode 100644 index d52fce904d0..00000000000 --- a/externals/ace/Thread_Mutex.inl +++ /dev/null @@ -1,104 +0,0 @@ -// -*- C++ -*- -// -// $Id: Thread_Mutex.inl 89127 2010-02-22 19:58:18Z schmidt $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE const ACE_thread_mutex_t & -ACE_Thread_Mutex::lock (void) const -{ -// ACE_TRACE ("ACE_Thread_Mutex::lock"); - return this->lock_; -} - -ACE_INLINE ACE_thread_mutex_t & -ACE_Thread_Mutex::lock (void) -{ -// ACE_TRACE ("ACE_Thread_Mutex::lock"); - return this->lock_; -} - -ACE_INLINE int -ACE_Thread_Mutex::acquire_read (void) -{ -// ACE_TRACE ("ACE_Thread_Mutex::acquire_read"); - return ACE_OS::thread_mutex_lock (&this->lock_); -} - -ACE_INLINE int -ACE_Thread_Mutex::acquire_write (void) -{ -// ACE_TRACE ("ACE_Thread_Mutex::acquire_write"); - return ACE_OS::thread_mutex_lock (&this->lock_); -} - -ACE_INLINE int -ACE_Thread_Mutex::tryacquire_read (void) -{ -// ACE_TRACE ("ACE_Thread_Mutex::tryacquire_read"); - return ACE_OS::thread_mutex_trylock (&this->lock_); -} - -ACE_INLINE int -ACE_Thread_Mutex::tryacquire_write (void) -{ -// ACE_TRACE ("ACE_Thread_Mutex::tryacquire_write"); - return ACE_OS::thread_mutex_trylock (&this->lock_); -} - -ACE_INLINE int -ACE_Thread_Mutex::tryacquire_write_upgrade (void) -{ -// ACE_TRACE ("ACE_Thread_Mutex::tryacquire_write_upgrade"); - return 0; -} - -ACE_INLINE int -ACE_Thread_Mutex::acquire (void) -{ -// ACE_TRACE ("ACE_Thread_Mutex::acquire"); - return ACE_OS::thread_mutex_lock (&this->lock_); -} - -ACE_INLINE int -ACE_Thread_Mutex::acquire (ACE_Time_Value &tv) -{ - // ACE_TRACE ("ACE_Thread_Mutex::acquire"); - return ACE_OS::thread_mutex_lock (&this->lock_, tv); -} - -ACE_INLINE int -ACE_Thread_Mutex::acquire (ACE_Time_Value *tv) -{ - // ACE_TRACE ("ACE_Thread_Mutex::acquire"); - return ACE_OS::thread_mutex_lock (&this->lock_, tv); -} - -ACE_INLINE int -ACE_Thread_Mutex::tryacquire (void) -{ -// ACE_TRACE ("ACE_Thread_Mutex::tryacquire"); - return ACE_OS::thread_mutex_trylock (&this->lock_); -} - -ACE_INLINE int -ACE_Thread_Mutex::release (void) -{ -// ACE_TRACE ("ACE_Thread_Mutex::release"); - return ACE_OS::thread_mutex_unlock (&this->lock_); -} - -ACE_INLINE int -ACE_Thread_Mutex::remove (void) -{ -// ACE_TRACE ("ACE_Thread_Mutex::remove"); - int result = 0; - if (!this->removed_) - { - this->removed_ = true; - result = ACE_OS::thread_mutex_destroy (&this->lock_); - } - return result; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Thread_Semaphore.cpp b/externals/ace/Thread_Semaphore.cpp deleted file mode 100644 index 39b28931db5..00000000000 --- a/externals/ace/Thread_Semaphore.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/** - * @file Thread_Semaphore.cpp - * - * $Id: Thread_Semaphore.cpp 80826 2008-03-04 14:51:23Z wotte $ - * - * Originally in Synch.cpp - * - * @author Douglas C. Schmidt - */ - -#include "ace/Thread_Semaphore.h" - -#if defined (ACE_HAS_THREADS) - -#if !defined (__ACE_INLINE__) -#include "ace/Thread_Semaphore.inl" -#endif /* __ACE_INLINE__ */ - -#include "ace/ACE.h" - -ACE_RCSID(ace, Thread_Semaphore, "$Id: Thread_Semaphore.cpp 80826 2008-03-04 14:51:23Z wotte $") - - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -void -ACE_Thread_Semaphore::dump (void) const -{ -#if defined (ACE_HAS_DUMP) -// ACE_TRACE ("ACE_Thread_Semaphore::dump"); - - ACE_Semaphore::dump (); -#endif /* ACE_HAS_DUMP */ -} - -ACE_Thread_Semaphore::ACE_Thread_Semaphore (unsigned int count, - const ACE_TCHAR *name, - void *arg, - int max) - : ACE_Semaphore (count, USYNC_THREAD, name, arg, max) -{ -// ACE_TRACE ("ACE_Thread_Semaphore::ACE_Thread_Semaphore"); -} - -/*****************************************************************************/ - -ACE_Thread_Semaphore * -ACE_Malloc_Lock_Adapter_T::operator () (const ACE_TCHAR *name) -{ - ACE_Thread_Semaphore *p = 0; - if (name == 0) - ACE_NEW_RETURN (p, ACE_Thread_Semaphore (1, name), 0); - else - ACE_NEW_RETURN (p, ACE_Thread_Semaphore (1, ACE::basename (name, - ACE_DIRECTORY_SEPARATOR_CHAR)), - 0); - return p; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_THREADS */ diff --git a/externals/ace/Thread_Semaphore.h b/externals/ace/Thread_Semaphore.h deleted file mode 100644 index d7013d9c3f2..00000000000 --- a/externals/ace/Thread_Semaphore.h +++ /dev/null @@ -1,87 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file Thread_Semaphore.h - * - * $Id: Thread_Semaphore.h 86731 2009-09-17 12:23:48Z johnnyw $ - * - * Moved from Synch.h. - * - * @author Douglas C. Schmidt - */ -//========================================================================== - -#ifndef ACE_THREAD_SEMAPHORE_H -#define ACE_THREAD_SEMAPHORE_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_HAS_THREADS) -# include "ace/Null_Semaphore.h" -#else /* ACE_HAS_THREADS */ -// ACE platform supports some form of threading. - -#include "ace/Semaphore.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Thread_Semaphore - * - * @brief Wrapper for Dijkstra style general semaphores that work - * only within one process. - */ -class ACE_Export ACE_Thread_Semaphore : public ACE_Semaphore -{ -public: - /// Initialize the semaphore, with an initial value of @a count, - /// maximum value of @a max, and unlocked by default. - ACE_Thread_Semaphore (unsigned int count = 1, // By default make this unlocked. - const ACE_TCHAR *name = 0, - void * = 0, - int max = 0x7FFFFFFF); - - /// Default dtor. - ~ACE_Thread_Semaphore (void); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; -}; - -/*****************************************************************************/ - -template class ACE_Malloc_Lock_Adapter_T; - -/** - * @brief Template specialization of ACE_Malloc_Lock_Adapter_T for - * ACE_Thread_Semaphore. - * - * This is needed since the ctor for ACE_Thread_Semaphore doesn't match - * the standard form used by other lock strategy classes. - */ -template<> -class ACE_Export ACE_Malloc_Lock_Adapter_T -{ -public: - ACE_Thread_Semaphore * operator () (const ACE_TCHAR *name); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Thread_Semaphore.inl" -#endif /* __ACE_INLINE__ */ - -#endif /* !ACE_HAS_THREADS */ - -#include /**/ "ace/post.h" -#endif /* ACE_THREAD_SEMAPHORE_H */ diff --git a/externals/ace/Thread_Semaphore.inl b/externals/ace/Thread_Semaphore.inl deleted file mode 100644 index b64ec3c08f5..00000000000 --- a/externals/ace/Thread_Semaphore.inl +++ /dev/null @@ -1,12 +0,0 @@ -// -*- C++ -*- -// -// $Id: Thread_Semaphore.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE -ACE_Thread_Semaphore::~ACE_Thread_Semaphore (void) -{ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Throughput_Stats.cpp b/externals/ace/Throughput_Stats.cpp deleted file mode 100644 index 6e667299729..00000000000 --- a/externals/ace/Throughput_Stats.cpp +++ /dev/null @@ -1,202 +0,0 @@ -// $Id: Throughput_Stats.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Throughput_Stats.h" - -#include "ace/OS_NS_stdio.h" -#include "ace/OS_NS_string.h" -#include "ace/High_Res_Timer.h" -#include "ace/Log_Msg.h" - -ACE_RCSID(ace, Throughput_Stats, "$Id: Throughput_Stats.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_Throughput_Stats::ACE_Throughput_Stats (void) - : ACE_Basic_Stats () - , throughput_last_ (0) -#if 0 - // @@TODO: This is what I really wanted to compute, but it just - // does not work. - , throughput_sum_x_ (0) - , throughput_sum_x2_ (0) - , throughput_sum_y_ (0) - , throughput_sum_y2_ (0) - , throughput_sum_xy_ (0) -#endif /* 0 */ -{ -} - -void -ACE_Throughput_Stats::sample (ACE_UINT64 throughput, - ACE_UINT64 latency) -{ - this->ACE_Basic_Stats::sample (latency); - - if (this->samples_count () == 1u) - { - - this->throughput_last_ = throughput; -#if 0 - // @@TODO: This is what I really wanted to compute, but it just - // does not work. - this->throughput_sum_y_ = this->samples_count_; - this->throughput_sum_y2_ = this->samples_count_ * this->samples_count_; - this->throughput_sum_x_ = throughput; - this->throughput_sum_x2_ = throughput * throughput; - this->throughput_sum_xy_ = throughput * this->samples_count_; - - ACE_OS::printf ("%f %qu\n", throughput / 400000000.0, this->samples_count_); -#endif /* 0 */ - } - else - { - this->throughput_last_ = throughput; - -#if 0 - // @@TODO: This is what I really wanted to compute, but it just - // does not work. - this->throughput_sum_y_ += this->samples_count_; - this->throughput_sum_y2_ += this->samples_count_ * this->samples_count_; - this->throughput_sum_x_ += throughput; - this->throughput_sum_x2_ += throughput * throughput; - this->throughput_sum_xy_ += throughput * this->samples_count_; - - ACE_OS::printf ("%f %qu\n", throughput / 400000000.0, this->samples_count_); -#endif /* 0 */ - } -} - -void -ACE_Throughput_Stats::accumulate (const ACE_Throughput_Stats &rhs) -{ - if (rhs.samples_count () == 0u) - return; - - this->ACE_Basic_Stats::accumulate (rhs); - - if (this->samples_count () == 0u) - { - this->throughput_last_ = rhs.throughput_last_; -#if 0 - // @@TODO: This is what I really wanted to compute, but it just - // does not work. - this->throughput_sum_x_ = rhs.throughput_sum_x_; - this->throughput_sum_x2_ = rhs.throughput_sum_x2_; - this->throughput_sum_y_ = rhs.throughput_sum_y_; - this->throughput_sum_y2_ = rhs.throughput_sum_y2_; - this->throughput_sum_xy_ = rhs.throughput_sum_xy_; -#endif /* 0 */ - - return; - } - - - if (this->throughput_last_ < rhs.throughput_last_) - this->throughput_last_ = rhs.throughput_last_; - -#if 0 - // @@TODO: This is what I really wanted to compute, but it just - // does not work. - this->throughput_sum_x_ += rhs.throughput_sum_x_; - this->throughput_sum_x2_ += rhs.throughput_sum_x2_; - this->throughput_sum_y_ += rhs.throughput_sum_y_; - this->throughput_sum_y2_ += rhs.throughput_sum_y2_; - this->throughput_sum_xy_ += rhs.throughput_sum_xy_; -#endif /* 0 */ -} - -void -ACE_Throughput_Stats::dump_results (const ACE_TCHAR* msg, - ACE_UINT32 sf) -{ - if (this->samples_count () == 0u) - { - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("%s : no data collected\n"), msg)); - return; - } - - this->ACE_Basic_Stats::dump_results (msg, sf); - - ACE_Throughput_Stats::dump_throughput (msg, sf, - this->throughput_last_, - this->samples_count ()); - -#if 0 - // @@TODO: This is what I really wanted to generate, but it just - // doesn't work. - double t_sum_x = - ACE_CU64_TO_CU32 (this->throughput_sum_x_);// / sf); - //t_sum_x /= 1000000.0; - double t_sum_y = - ACE_CU64_TO_CU32 (this->throughput_sum_y_); - double t_sum_x2 = - ACE_CU64_TO_CU32 (this->throughput_sum_x2_);// / (sf*sf)); - //t_sum_x2 /= 1000000.0; - //t_sum_x2 /= 1000000.0; - double t_sum_y2 = - ACE_CU64_TO_CU32 (this->throughput_sum_y2_); - double t_sum_xy = - ACE_CU64_TO_CU32 (this->throughput_sum_xy_);// / sf); - //t_sum_xy /= 1000000.0; - double t_avgx = t_sum_x / this->samples_count (); - double t_avgy = t_sum_y / this->samples_count (); - - double t_a = - (this->samples_count () * t_sum_xy - t_sum_x * t_sum_y) - / (this->samples_count () * t_sum_x2 - t_sum_x * t_sum_x); - double t_b = (t_avgy - t_a * t_avgx); - - t_a *= 1000000.0; - - double d_r = - (t_sum_xy - t_avgx * t_sum_y - t_avgy * t_sum_x - + this->samples_count () * t_avgx * t_avgy); - double n_r = - (t_sum_x2 - - this->samples_count () * t_avgx * t_avgx) - * (t_sum_y2 - - this->samples_count () * t_avgy * t_avgy); - double t_r = d_r * d_r / n_r; - - // ACE_DEBUG ((LM_DEBUG, - // "%s throughput: %.2f/%.2f/%.2f/%.6f/%.2f (avg/a/b/r/elapsed)\n", - // msg, t_avg, t_a, t_b, t_r, seconds)); - // ACE_DEBUG ((LM_DEBUG, - // "%s data: %.2f/%.2f/%.2f/%.6f/%.2f (x/x2/y/y2/xy)\n", - // msg, t_sum_x, t_sum_x2, t_sum_y, t_sum_y2, t_sum_xy)); -#endif -} - -void -ACE_Throughput_Stats::dump_throughput (const ACE_TCHAR *msg, - ACE_UINT32 sf, - ACE_UINT64 elapsed_time, - ACE_UINT32 samples_count) -{ -#ifndef ACE_NLOGGING - double seconds = -# if defined ACE_LACKS_LONGLONG_T - elapsed_time / sf; -#elif defined (ACE_LACKS_UNSIGNEDLONGLONG_T) - static_cast (ACE_UINT64_DBLCAST_ADAPTER ( - ACE_U_LongLong(elapsed_time / sf))); -# else /* ! ACE_LACKS_LONGLONG_T */ - static_cast (ACE_UINT64_DBLCAST_ADAPTER (elapsed_time / sf)); -# endif /* ! ACE_LACKS_LONGLONG_T */ - seconds /= ACE_HR_SCALE_CONVERSION; - - const double t_avg = samples_count / seconds; - - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("%s throughput: %.2f (events/second)\n"), - msg, t_avg)); -#else - ACE_UNUSED_ARG (msg); - ACE_UNUSED_ARG (sf); - ACE_UNUSED_ARG (elapsed_time); - ACE_UNUSED_ARG (samples_count); -#endif /* ACE_NLOGGING */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Throughput_Stats.h b/externals/ace/Throughput_Stats.h deleted file mode 100644 index c306c856c5e..00000000000 --- a/externals/ace/Throughput_Stats.h +++ /dev/null @@ -1,86 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file Throughput_Stats.h - * - * $Id: Throughput_Stats.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author David L. Levine - */ -//========================================================================== - - -#ifndef ACE_THROUGHPUT_STATS_H -#define ACE_THROUGHPUT_STATS_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Basic_Stats.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/// A simple class to make throughput and latency analysis. -/** - * - * Keep the relevant information to perform throughput and latency - * analysis, including: - * -# Minimum, Average and Maximum latency - * -# Jitter for the latency - * -# Linear regression for throughput - * -# Accumulate results from several samples to obtain aggregated - * results, across several threads or experiments. - * - * @todo The idea behind this class was to use linear regression to - * determine if the throughput was linear or exhibited jitter. - * Unfortunately it never worked quite right, so only average - * throughput is computed. - */ -class ACE_Export ACE_Throughput_Stats : public ACE_Basic_Stats -{ -public: - /// Constructor - ACE_Throughput_Stats (void); - - /// Store one sample - void sample (ACE_UINT64 throughput, ACE_UINT64 latency); - - /// Update the values to reflect the stats in @a throughput - void accumulate (const ACE_Throughput_Stats &throughput); - - /// Print down the stats - void dump_results (const ACE_TCHAR* msg, ACE_UINT32 scale_factor); - - /// Dump the average throughput stats. - static void dump_throughput (const ACE_TCHAR *msg, - ACE_UINT32 scale_factor, - ACE_UINT64 elapsed_time, - ACE_UINT32 samples_count); -private: - /// The last throughput measurement. - ACE_UINT64 throughput_last_; - -#if 0 - /// These are the fields that we should keep to perform linear - /// regression - //@{ - ///@} - ACE_UINT64 throughput_sum_x_; - ACE_UINT64 throughput_sum_x2_; - ACE_UINT64 throughput_sum_y_; - ACE_UINT64 throughput_sum_y2_; - ACE_UINT64 throughput_sum_xy_; -#endif /* 0 */ -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" - -#endif /* ! ACE_THROUGHPUT_STATS_H */ diff --git a/externals/ace/Time_Value.cpp b/externals/ace/Time_Value.cpp deleted file mode 100644 index af07c54422a..00000000000 --- a/externals/ace/Time_Value.cpp +++ /dev/null @@ -1,359 +0,0 @@ -#include "ace/Time_Value.h" - -ACE_RCSID (ace, - Time_Value, - "$Id: Time_Value.cpp 89791 2010-04-07 14:36:21Z schmidt $") - -#if !defined (__ACE_INLINE__) -#include "ace/Time_Value.inl" -#endif /* __ACE_INLINE__ */ - -#include "ace/Numeric_Limits.h" -#include "ace/If_Then_Else.h" -#include "ace/OS_NS_math.h" - -#ifdef ACE_HAS_CPP98_IOSTREAMS -#include -#include -#endif /* ACE_HAS_CPP98_IOSTREAMS */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/// Static constant representing `zero-time'. -/// Note: this object requires static construction. -const ACE_Time_Value ACE_Time_Value::zero; - -/// Constant for maximum time representable. Note that this time -/// is not intended for use with select () or other calls that may -/// have *their own* implementation-specific maximum time representations. -/// Its primary use is in time computations such as those used by the -/// dynamic subpriority strategies in the ACE_Dynamic_Message_Queue class. -/// Note: this object requires static construction. -const ACE_Time_Value ACE_Time_Value::max_time ( - ACE_Numeric_Limits::max (), - ACE_ONE_SECOND_IN_USECS - 1); - -ACE_ALLOC_HOOK_DEFINE (ACE_Time_Value) - -/// Increment microseconds (the only reason this is here is to allow -/// the use of ACE_Atomic_Op with ACE_Time_Value). -ACE_Time_Value -ACE_Time_Value::operator ++ (int) -{ - // ACE_OS_TRACE ("ACE_Time_Value::operator ++ (int)"); - ACE_Time_Value tv (*this); - ++*this; - return tv; -} - -ACE_Time_Value & -ACE_Time_Value::operator ++ (void) -{ - // ACE_OS_TRACE ("ACE_Time_Value::operator ++ (void)"); - this->usec (this->usec () + 1); - this->normalize (); - return *this; -} - -/// Decrement microseconds (the only reason this is here is / to allow -/// the use of ACE_Atomic_Op with ACE_Time_Value). -ACE_Time_Value -ACE_Time_Value::operator -- (int) -{ - // ACE_OS_TRACE ("ACE_Time_Value::operator -- (int)"); - ACE_Time_Value tv (*this); - --*this; - return tv; -} - -ACE_Time_Value & -ACE_Time_Value::operator -- (void) -{ - // ACE_OS_TRACE ("ACE_Time_Value::operator -- (void)"); - this->usec (this->usec () - 1); - this->normalize (); - return *this; -} - -#if defined (ACE_WIN32) -/// Static constant to remove time skew between FILETIME and POSIX -/// time. POSIX and Win32 use different epochs (Jan. 1, 1970 v.s. -/// Jan. 1, 1601). The following constant defines the difference -/// in 100ns ticks. -/// -/// In the beginning (Jan. 1, 1601), there was no time and no computer. -/// And Bill said: "Let there be time," and there was time.... -# if defined (ACE_LACKS_LONGLONG_T) -const ACE_U_LongLong ACE_Time_Value::FILETIME_to_timval_skew = -ACE_U_LongLong (0xd53e8000, 0x19db1de); -# else -const DWORDLONG ACE_Time_Value::FILETIME_to_timval_skew = -ACE_INT64_LITERAL (0x19db1ded53e8000); -# endif - -/// Initializes the ACE_Time_Value object from a Win32 FILETIME -ACE_Time_Value::ACE_Time_Value (const FILETIME &file_time) -{ - // // ACE_OS_TRACE ("ACE_Time_Value::ACE_Time_Value"); - this->set (file_time); -} - -void ACE_Time_Value::set (const FILETIME &file_time) -{ - // Initializes the ACE_Time_Value object from a Win32 FILETIME -#if defined (ACE_LACKS_LONGLONG_T) - ACE_U_LongLong LL_100ns(file_time.dwLowDateTime, file_time.dwHighDateTime); - LL_100ns -= ACE_Time_Value::FILETIME_to_timval_skew; - // Convert 100ns units to seconds; - this->tv_.tv_sec = (long) (LL_100ns / ((double) (10000 * 1000))); - // Convert remainder to microseconds; - this->tv_.tv_usec = (suseconds_t)((LL_100ns % ((ACE_UINT32)(10000 * 1000))) / 10); -#else - // Don't use a struct initializer, gcc don't like it. - ULARGE_INTEGER _100ns; - _100ns.LowPart = file_time.dwLowDateTime; - _100ns.HighPart = file_time.dwHighDateTime; - - _100ns.QuadPart -= ACE_Time_Value::FILETIME_to_timval_skew; - - // Convert 100ns units to seconds; - this->tv_.tv_sec = (long) (_100ns.QuadPart / (10000 * 1000)); - // Convert remainder to microseconds; - this->tv_.tv_usec = (suseconds_t) ((_100ns.QuadPart % (10000 * 1000)) / 10); -#endif // ACE_LACKS_LONGLONG_T - this->normalize (); -} - -/// Returns the value of the object as a Win32 FILETIME. -ACE_Time_Value::operator FILETIME () const -{ - FILETIME file_time; - // ACE_OS_TRACE ("ACE_Time_Value::operator FILETIME"); - -#if defined (ACE_LACKS_LONGLONG_T) - ACE_U_LongLong LL_sec(this->tv_.tv_sec); - ACE_U_LongLong LL_usec(this->tv_.tv_usec); - ACE_U_LongLong LL_100ns = LL_sec * (ACE_UINT32)(10000 * 1000) + - LL_usec * (ACE_UINT32)10 + - ACE_Time_Value::FILETIME_to_timval_skew; - file_time.dwLowDateTime = LL_100ns.lo(); - file_time.dwHighDateTime = LL_100ns.hi(); -#else - ULARGE_INTEGER _100ns; - _100ns.QuadPart = (((DWORDLONG) this->tv_.tv_sec * (10000 * 1000) + - this->tv_.tv_usec * 10) + - ACE_Time_Value::FILETIME_to_timval_skew); - - file_time.dwLowDateTime = _100ns.LowPart; - file_time.dwHighDateTime = _100ns.HighPart; -#endif //ACE_LACKS_LONGLONG_T - - return file_time; -} - -#endif /* ACE_WIN32 */ - -void -ACE_Time_Value::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - // ACE_OS_TRACE ("ACE_Time_Value::dump"); -#if 0 - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ntv_sec_ = %d"), this->tv_.tv_sec)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ntv_usec_ = %d\n"), this->tv_.tv_usec)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* 0 */ -#endif /* ACE_HAS_DUMP */ -} - -void -ACE_Time_Value::normalize (bool saturate) -{ - // // ACE_OS_TRACE ("ACE_Time_Value::normalize"); - // From Hans Rohnert... - - if (this->tv_.tv_usec >= ACE_ONE_SECOND_IN_USECS) - { - /*! \todo This loop needs some optimization. - */ - if (!saturate) // keep the conditionnal expression outside the while loop to minimize performance cost - do - { - ++this->tv_.tv_sec; - this->tv_.tv_usec -= ACE_ONE_SECOND_IN_USECS; - } - while (this->tv_.tv_usec >= ACE_ONE_SECOND_IN_USECS); - else - do - if (this->tv_.tv_sec < ACE_Numeric_Limits::max()) - { - ++this->tv_.tv_sec; - this->tv_.tv_usec -= ACE_ONE_SECOND_IN_USECS; - } - else - this->tv_.tv_usec = ACE_ONE_SECOND_IN_USECS - 1; - while (this->tv_.tv_usec >= ACE_ONE_SECOND_IN_USECS); - } - else if (this->tv_.tv_usec <= -ACE_ONE_SECOND_IN_USECS) - { - /*! \todo This loop needs some optimization. - */ - if (!saturate) - do - { - --this->tv_.tv_sec; - this->tv_.tv_usec += ACE_ONE_SECOND_IN_USECS; - } - while (this->tv_.tv_usec <= -ACE_ONE_SECOND_IN_USECS); - else - do - if (this->tv_.tv_sec > ACE_Numeric_Limits::min()) - { - --this->tv_.tv_sec; - this->tv_.tv_usec += ACE_ONE_SECOND_IN_USECS; - } - else - this->tv_.tv_usec = -ACE_ONE_SECOND_IN_USECS + 1; - while (this->tv_.tv_usec <= -ACE_ONE_SECOND_IN_USECS); - } - - if (this->tv_.tv_sec >= 1 && this->tv_.tv_usec < 0) - { - --this->tv_.tv_sec; - this->tv_.tv_usec += ACE_ONE_SECOND_IN_USECS; - } - // tv_sec in qnxnto is unsigned -#if !defined ( __QNXNTO__) - else if (this->tv_.tv_sec < 0 && this->tv_.tv_usec > 0) - { - ++this->tv_.tv_sec; - this->tv_.tv_usec -= ACE_ONE_SECOND_IN_USECS; - } -#endif /* __QNXNTO__ */ -} - - -ACE_Time_Value & -ACE_Time_Value::operator *= (double d) -{ - // To work around the lack of precision of a long double to contain - // a 64-bits time_t + 6 digits after the decimal point for the usec part, - // we perform the multiplication of the 2 timeval parts separately. - // - // This extra precision step is adding a cost when transfering the - // seconds resulting from the usec multiplication. This operation - // correspond to the normalization process performed in normalize() - // but we must absolutly do it here because the usec multiplication - // result value could exceed what can be stored in a suseconds_t - // type variable. - // - // Since this is a costly operation, we try to detect as soon as - // possible if we are having a saturation in order to abort the rest - // of the computation. - typedef ACE::If_Then_Else<(sizeof (double) > sizeof (time_t)), - double, - long double>::result_type float_type; - - float_type sec_total = static_cast (this->sec()); - sec_total *= d; - - // shall we saturate the result? - static const float_type max_int = - ACE_Numeric_Limits::max() + 0.999999; - static const float_type min_int = - ACE_Numeric_Limits::min() - 0.999999; - - if (sec_total > max_int) - { - this->set(ACE_Numeric_Limits::max(), ACE_ONE_SECOND_IN_USECS-1); - } - else if (sec_total < min_int) - { - this->set(ACE_Numeric_Limits::min(), -ACE_ONE_SECOND_IN_USECS+1); - } - else - { - time_t time_sec = static_cast (sec_total); - - float_type usec_total = this->usec(); - usec_total *= d; - - // adding usec resulting from tv_sec mult - usec_total += (sec_total-time_sec) * ACE_ONE_SECOND_IN_USECS; - - // extract seconds component of the usec mult - sec_total = usec_total / ACE_ONE_SECOND_IN_USECS; - // keep remaining usec - if (sec_total > 0) - { - usec_total = (sec_total - ACE_OS::floor(sec_total)); - } - else - { - usec_total = (sec_total - ACE_OS::ceil(sec_total)); - } - - sec_total -= usec_total; - usec_total *= ACE_ONE_SECOND_IN_USECS; - - // add the seconds component of the usec mult with the tv_sec mult prod. - sec_total += time_sec; - - // recheck for saturation - if (sec_total > max_int) - { - this->set (ACE_Numeric_Limits::max(), ACE_ONE_SECOND_IN_USECS - 1); - } - else if (sec_total < min_int) - { - this->set (ACE_Numeric_Limits::min(), -ACE_ONE_SECOND_IN_USECS + 1); - } - else - { - time_sec = static_cast (sec_total); - suseconds_t time_usec = static_cast (usec_total); - - // round up the result to save the last usec - if (time_usec > 0 && (usec_total - time_usec) >= 0.5) - { - ++time_usec; - } - else if (time_usec < 0 && (usec_total - time_usec) <= -0.5) - { - --time_usec; - } - - this->set (time_sec, time_usec); - } - } - return *this; -} - -#ifdef ACE_HAS_CPP98_IOSTREAMS -ostream &operator<<(ostream &o, const ACE_Time_Value &v) -{ - char oldFiller = o.fill (); - o.fill ('0'); - const timeval *tv = v; - if (tv->tv_sec) - { - o << tv->tv_sec; - if (tv->tv_usec) - o << '.' << std::setw (6) << ACE_STD_NAMESPACE::abs (tv->tv_usec); - } - else if (tv->tv_usec < 0) - o << "-0." << std::setw (6) << - tv->tv_usec; - else - { - o << '0'; - if (tv->tv_usec > 0) - o << '.'<< std::setw (6) << tv->tv_usec; - } - - o.fill (oldFiller); - return o; -} -#endif /* ACE_HAS_CPP98_IOSTREAMS */ - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Time_Value.h b/externals/ace/Time_Value.h deleted file mode 100644 index f92c8c7f7f5..00000000000 --- a/externals/ace/Time_Value.h +++ /dev/null @@ -1,397 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Time_Value.h - * - * $Id: Time_Value.h 90683 2010-06-17 22:07:42Z shuston $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_TIME_VALUE_H -#define ACE_TIME_VALUE_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -# include "ace/os_include/os_time.h" - -// Define some helpful constants. -// Not type-safe, and signed. For backward compatibility. -#define ACE_ONE_SECOND_IN_MSECS 1000L -suseconds_t const ACE_ONE_SECOND_IN_USECS = 1000000; -#define ACE_ONE_SECOND_IN_NSECS 1000000000L - -// needed for ACE_UINT64 -#include "ace/Basic_Types.h" - -// needed to determine if iostreams are present -#include "ace/iosfwd.h" - -// This forward declaration is needed by the set() and FILETIME() functions -#if defined (ACE_LACKS_LONGLONG_T) -ACE_BEGIN_VERSIONED_NAMESPACE_DECL -class ACE_Export ACE_U_LongLong; -ACE_END_VERSIONED_NAMESPACE_DECL -#endif /* ACE_LACKS_LONGLONG_T */ - -// ------------------------------------------------------------------- - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - - -/** - * @class ACE_Time_Value - * - * @brief Operations on "timeval" structures, which express time in - * seconds (secs) and microseconds (usecs). - * - * This class centralizes all the time related processing in - * ACE. These time values are typically used in conjunction with OS - * mechanisms like or other calls that may have - * *their own* implementation-specific maximum time representations. - * Its primary use is in time computations such as those used by the - * dynamic subpriority strategies in the ACE_Dynamic_Message_Queue - * class. - */ - static const ACE_Time_Value max_time; - - // = Initialization methods. - - /// Default Constructor. - ACE_Time_Value (void); - - /// Constructor. - explicit ACE_Time_Value (time_t sec, suseconds_t usec = 0); - - // = Methods for converting to/from various time formats. - - /// Construct the ACE_Time_Value from a timeval. - explicit ACE_Time_Value (const struct timeval &t); - - /// Construct the ACE_Time_Value object from a timespec_t. - explicit ACE_Time_Value (const timespec_t &t); - -# if defined (ACE_WIN32) - /// Construct the ACE_Time_Value object from a Win32 FILETIME - explicit ACE_Time_Value (const FILETIME &ft); -# endif /* ACE_WIN32 */ - - /// Initializes the ACE_Time_Value from seconds and useconds. - void set (time_t sec, suseconds_t usec); - - /// Initializes the ACE_Time_Value from a double, which is assumed to be - /// in second format, with any remainder treated as microseconds. - void set (double d); - - /// Initializes the ACE_Time_Value from a timeval. - void set (const timeval &t); - - /// Initializes the ACE_Time_Value object from a timespec_t. - void set (const timespec_t &t); - -# if defined (ACE_WIN32) - /// Initializes the ACE_Time_Value object from a Win32 FILETIME. - void set (const FILETIME &ft); -# endif /* ACE_WIN32 */ - - /// Converts from ACE_Time_Value format into milliseconds format. - /** - * @return Sum of second field (in milliseconds) and microsecond field - * (in milliseconds). Note that this method can overflow if - * the second and microsecond field values are large, so use - * the msec (ACE_UINT64 &ms) method instead. - * - * @note The semantics of this method differs from the sec() and - * usec() methods. There is no analogous "millisecond" - * component in an ACE_Time_Value. - */ - unsigned long msec (void) const; - - /// Converts from ACE_Time_Value format into milliseconds format. - /** - * @return Sum of second field (in milliseconds) and microsecond field - * (in milliseconds). - * - * @note The semantics of this method differs from the sec() and - * usec() methods. There is no analogous "millisecond" - * component in an ACE_Time_Value. - */ - ACE_UINT64 get_msec () const; - - /// Converts from ACE_Time_Value format into milliseconds format. - /** - * @return Sum of second field (in milliseconds) and microsecond field - * (in milliseconds) and return them via the @param ms parameter. - * - * @note The semantics of this method differs from the sec() and - * usec() methods. There is no analogous "millisecond" - * component in an ACE_Time_Value. - * - * @deprecated Use get_msec() instead. - */ - void msec (ACE_UINT64 &ms) const; - - /// Converts from ACE_Time_Value format into milliseconds format. - /** - * @return Sum of second field (in milliseconds) and microsecond field - * (in milliseconds) and return them via the @param ms parameter. - * - * @note The semantics of this method differs from the sec() and - * usec() methods. There is no analogous "millisecond" - * component in an ACE_Time_Value. - * - * @deprecated Use get_msec() instead. - */ - void msec (ACE_UINT64 &ms) /* const */; - - /// Converts from milli-seconds format into ACE_Time_Value format. - /** - * @note The semantics of this method differs from the sec() and - * usec() methods. There is no analogous "millisecond" - * component in an ACE_Time_Value. - */ - void set_msec (const ACE_UINT64 &ms); - - /// Converts from milli-seconds format into ACE_Time_Value format. - /** - * @note The semantics of this method differs from the sec() and - * usec() methods. There is no analogous "millisecond" - * component in an ACE_Time_Value. - */ - void msec (long); - - /// Converts from milli-seconds format into ACE_Time_Value format. - /** - * @note The semantics of this method differs from the sec() and - * usec() methods. There is no analogous "millisecond" - * component in an ACE_Time_Value. - */ - void msec (int); // converted to long then calls above. - - /// Returns the value of the object as a timespec_t. - operator timespec_t () const; - - /// Returns the value of the object as a timeval. - operator timeval () const; - - /// Returns a pointer to the object as a timeval. - operator const timeval *() const; - -# if defined (ACE_WIN32) - /// Returns the value of the object as a Win32 FILETIME. - operator FILETIME () const; -# endif /* ACE_WIN32 */ - - // = The following are accessor/mutator methods. - - /// Get seconds. - /** - * @return The second field/component of this ACE_Time_Value. - * - * @note The semantics of this method differs from the msec() - * method. - */ - time_t sec (void) const; - - /// Set seconds. - void sec (time_t sec); - - /// Get microseconds. - /** - * @return The microsecond field/component of this ACE_Time_Value. - * - * @note The semantics of this method differs from the msec() - * method. - */ - suseconds_t usec (void) const; - - /// Set microseconds. - void usec (suseconds_t usec); - - /** - * @return Sum of second field (in microseconds) and microsecond field - * and return them via the @param usec parameter. - */ - void to_usec (ACE_UINT64 &usec) const; - - // = The following arithmetic methods operate on ACE_Time_Value's. - - /// Add @a tv to this. - ACE_Time_Value &operator += (const ACE_Time_Value &tv); - - /// Add @a tv to this. - ACE_Time_Value &operator += (time_t tv); - - /// Assign @ tv to this - ACE_Time_Value &operator = (const ACE_Time_Value &tv); - - /// Assign @ tv to this - ACE_Time_Value &operator = (time_t tv); - - /// Subtract @a tv to this. - ACE_Time_Value &operator -= (const ACE_Time_Value &tv); - - /// Substract @a tv to this. - ACE_Time_Value &operator -= (time_t tv); - - /** - \brief Multiply the time value by the @a d factor. - \note The result of the operator is valid for results from range - < (ACE_INT32_MIN, -999999), (ACE_INT32_MAX, 999999) >. Result - outside this range are saturated to a limit. - */ - ACE_Time_Value &operator *= (double d); - - /// Increment microseconds as postfix. - /** - * @note The only reason this is here is to allow the use of ACE_Atomic_Op - * with ACE_Time_Value. - */ - ACE_Time_Value operator++ (int); - - /// Increment microseconds as prefix. - /** - * @note The only reason this is here is to allow the use of ACE_Atomic_Op - * with ACE_Time_Value. - */ - ACE_Time_Value &operator++ (void); - - /// Decrement microseconds as postfix. - /** - * @note The only reason this is here is to allow the use of ACE_Atomic_Op - * with ACE_Time_Value. - */ - ACE_Time_Value operator-- (int); - - /// Decrement microseconds as prefix. - /** - * @note The only reason this is here is to allow the use of ACE_Atomic_Op - * with ACE_Time_Value. - */ - ACE_Time_Value &operator-- (void); - - /// Adds two ACE_Time_Value objects together, returns the sum. - friend ACE_Export ACE_Time_Value operator + (const ACE_Time_Value &tv1, - const ACE_Time_Value &tv2); - - /// Subtracts two ACE_Time_Value objects, returns the difference. - friend ACE_Export ACE_Time_Value operator - (const ACE_Time_Value &tv1, - const ACE_Time_Value &tv2); - - /// True if @a tv1 < @a tv2. - friend ACE_Export bool operator < (const ACE_Time_Value &tv1, - const ACE_Time_Value &tv2); - - /// True if @a tv1 > @a tv2. - friend ACE_Export bool operator > (const ACE_Time_Value &tv1, - const ACE_Time_Value &tv2); - - /// True if @a tv1 <= @a tv2. - friend ACE_Export bool operator <= (const ACE_Time_Value &tv1, - const ACE_Time_Value &tv2); - - /// True if @a tv1 >= @a tv2. - friend ACE_Export bool operator >= (const ACE_Time_Value &tv1, - const ACE_Time_Value &tv2); - - /// True if @a tv1 == @a tv2. - friend ACE_Export bool operator == (const ACE_Time_Value &tv1, - const ACE_Time_Value &tv2); - - /// True if @a tv1 != @a tv2. - friend ACE_Export bool operator != (const ACE_Time_Value &tv1, - const ACE_Time_Value &tv2); - - //@{ - /// Multiplies the time value by @a d - friend ACE_Export ACE_Time_Value operator * (double d, - const ACE_Time_Value &tv); - - friend ACE_Export ACE_Time_Value operator * (const ACE_Time_Value &tv, - double d); - //@} - - /// Dump is a no-op. - /** - * The dump() method is a no-op. It's here for backwards compatibility - * only, but does not dump anything. Invoking logging methods here - * violates layering restrictions in ACE because this class is part - * of the OS layer and @c ACE_Log_Msg is at a higher level. - */ - void dump (void) const; - -# if defined (ACE_WIN32) - /// Const time difference between FILETIME and POSIX time. -# if defined (ACE_LACKS_LONGLONG_T) - static const ACE_U_LongLong FILETIME_to_timval_skew; -# else - static const DWORDLONG FILETIME_to_timval_skew; -# endif // ACE_LACKS_LONGLONG_T -# endif /* ACE_WIN32 */ - -private: - /// Put the timevalue into a canonical form. - void normalize (bool saturate = false); - - /// Store the values as a timeval. -#if defined (ACE_HAS_TIME_T_LONG_MISMATCH) - // Windows' timeval is non-conformant, so swap in a struct that conforms - // to the proper data types to represent the entire time range that this - // class's API can accept. - // Also, since this class can supply a pointer to a timeval that things - // like select() expect, we need the OS-defined one as well. To make this - // available, use a real timeval called ext_tv_ and set it up when needed. - // Since this is most often for relative times that don't approach 32 bits - // in size, reducing a time_t to fit should be no problem. - struct { - time_t tv_sec; - suseconds_t tv_usec; - } tv_; - timeval ext_tv_; -#else - timeval tv_; -#endif /* ACE_HAS_TIME_T_LONG_MISMATCH */ -}; - -#ifdef ACE_HAS_CPP98_IOSTREAMS -extern ACE_Export ostream &operator<<( ostream &o, const ACE_Time_Value &v ); -#endif - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Time_Value.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (__MINGW32__) -ACE_BEGIN_VERSIONED_NAMESPACE_DECL -// The MingW linker has problems with the exported statics -// zero and max_time with these two statics the linker will be able to -// resolve the static exported symbols. -static const ACE_Time_Value& __zero_time = ACE_Time_Value::zero; -static const ACE_Time_Value& __max_time = ACE_Time_Value::max_time; -ACE_END_VERSIONED_NAMESPACE_DECL -#endif /* __MINGW32__ */ - -#include /**/ "ace/post.h" - -#endif /* ACE_TIME_VALUE_H */ diff --git a/externals/ace/Time_Value.inl b/externals/ace/Time_Value.inl deleted file mode 100644 index 8f7bf23d837..00000000000 --- a/externals/ace/Time_Value.inl +++ /dev/null @@ -1,418 +0,0 @@ -// -*- C++ -*- -// -// $Id: Time_Value.inl 90689 2010-06-18 11:14:47Z shuston $ - -#include "ace/Truncate.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/// Returns the value of the object as a timeval. -ACE_INLINE -ACE_Time_Value::operator timeval () const -{ - // ACE_OS_TRACE ("ACE_Time_Value::operator timeval"); -#if defined (ACE_HAS_TIME_T_LONG_MISMATCH) - // Recall that on some Windows we substitute another type for timeval in tv_ - ACE_Time_Value *me = const_cast (this); - me->ext_tv_.tv_sec = ACE_Utils::truncate_cast (this->tv_.tv_sec); - me->ext_tv_.tv_usec = ACE_Utils::truncate_cast (this->tv_.tv_usec); - return this->ext_tv_; -#else - return this->tv_; -#endif /* ACE_HAS_TIME_T_LONG_MISMATCH */ -} - -ACE_INLINE void -ACE_Time_Value::set (const timeval &tv) -{ - // ACE_OS_TRACE ("ACE_Time_Value::set"); - this->tv_.tv_sec = tv.tv_sec; - this->tv_.tv_usec = tv.tv_usec; - - this->normalize (); -} - -ACE_INLINE -ACE_Time_Value::ACE_Time_Value (const struct timeval &tv) -{ - // ACE_OS_TRACE ("ACE_Time_Value::ACE_Time_Value"); - this->set (tv); -} - -ACE_INLINE -ACE_Time_Value::operator const timeval * () const -{ - // ACE_OS_TRACE ("ACE_Time_Value::operator const timeval *"); -#if defined (ACE_HAS_TIME_T_LONG_MISMATCH) - // Recall that on some Windows we substitute another type for timeval in tv_ - ACE_Time_Value *me = const_cast (this); - me->ext_tv_.tv_sec = ACE_Utils::truncate_cast (this->tv_.tv_sec); - me->ext_tv_.tv_usec = ACE_Utils::truncate_cast (this->tv_.tv_usec); - return (const timeval *) &this->ext_tv_; -#else - return (const timeval *) &this->tv_; -#endif /* ACE_HAS_TIME_T_LONG_MISMATCH */ -} - -ACE_INLINE void -ACE_Time_Value::set (time_t sec, suseconds_t usec) -{ - // ACE_OS_TRACE ("ACE_Time_Value::set"); -# if defined (_WIN32_WCE) && (_WIN32_WCE == 0x600) && !defined (_USE_32BIT_TIME_T) && defined (_MSC_VER) - // The WinCE 6.0 SDK ships with a timeval tv_sec member that uses long as type - // not time_t. This resolves in compilation warnings because time_t - // can be 64bit. Disable at this momemt the warning for just this method - // else we get a compile warnings each time this inline file is included - // this file. -# pragma warning (push) -# pragma warning (disable: 4244) -# endif - this->tv_.tv_sec = sec; -# if defined (_WIN32_WCE) && (_WIN32_WCE == 0x600) && !defined (_USE_32BIT_TIME_T) && defined (_MSC_VER) -# pragma warning (pop) -# endif - this->tv_.tv_usec = usec; -#if __GNUC__ - if (__builtin_constant_p(sec) && - __builtin_constant_p(usec) && - (sec >= 0 && usec >= 0 && usec < ACE_ONE_SECOND_IN_USECS)) - return; -#endif - this->normalize (); -} - -ACE_INLINE void -ACE_Time_Value::set (double d) -{ - // ACE_OS_TRACE ("ACE_Time_Value::set"); - long l = (long) d; - this->tv_.tv_sec = l; - this->tv_.tv_usec = (suseconds_t) ((d - (double) l) * ACE_ONE_SECOND_IN_USECS + .5); - this->normalize (); -} - -/// Initializes a timespec_t. Note that this approach loses precision -/// since it converts the nano-seconds into micro-seconds. But then -/// again, do any real systems have nano-second timer precision?! -ACE_INLINE void -ACE_Time_Value::set (const timespec_t &tv) -{ - // ACE_OS_TRACE ("ACE_Time_Value::set"); - - this->set (tv.tv_sec, - tv.tv_nsec / 1000); // Convert nanoseconds into microseconds. -} - -ACE_INLINE -ACE_Time_Value::ACE_Time_Value (void) - // : tv_ () -{ - // ACE_OS_TRACE ("ACE_Time_Value::ACE_Time_Value"); - this->set (0, 0); -} - -ACE_INLINE -ACE_Time_Value::ACE_Time_Value (time_t sec, suseconds_t usec) -{ - // ACE_OS_TRACE ("ACE_Time_Value::ACE_Time_Value"); - this->set (sec, usec); -} - -/// Returns number of seconds. -ACE_INLINE time_t -ACE_Time_Value::sec (void) const -{ - // ACE_OS_TRACE ("ACE_Time_Value::sec"); - return this->tv_.tv_sec; -} - -/// Sets the number of seconds. -ACE_INLINE void -ACE_Time_Value::sec (time_t sec) -{ - // ACE_OS_TRACE ("ACE_Time_Value::sec"); - this->tv_.tv_sec = ACE_Utils::truncate_cast (sec); -} - -/// Converts from Time_Value format into milli-seconds format. -ACE_INLINE unsigned long -ACE_Time_Value::msec (void) const -{ - // ACE_OS_TRACE ("ACE_Time_Value::msec"); - - // Note - we're truncating a value here, which can lose data. This is - // called out in the user documentation for this with a recommendation to - // use msec(ACE_UINT64&) instead, so just go ahead and truncate. - time_t secs = this->tv_.tv_sec * 1000 + this->tv_.tv_usec / 1000; - return ACE_Utils::truncate_cast (secs); -} - -ACE_INLINE ACE_UINT64 -ACE_Time_Value::get_msec () const -{ - // ACE_OS_TRACE ("ACE_Time_Value::get_msec"); - ACE_UINT64 ms = ACE_Utils::truncate_cast (this->tv_.tv_sec); - ms *= 1000; - ms += (this->tv_.tv_usec / 1000); - return ms; -} - -ACE_INLINE void -ACE_Time_Value::msec (ACE_UINT64 &ms) const -{ - // ACE_OS_TRACE ("ACE_Time_Value::msec"); - ms = this->get_msec (); -} - -ACE_INLINE void -ACE_Time_Value::msec (ACE_UINT64 &ms) /*const*/ -{ - // ACE_OS_TRACE ("ACE_Time_Value::msec"); - const ACE_Time_Value *tv = this; - tv->msec (ms); -} - -ACE_INLINE void -ACE_Time_Value::set_msec (const ACE_UINT64 &ms) -{ - // ACE_OS_TRACE ("ACE_Time_Value::set_msec"); - // Convert millisecond units to seconds; - ACE_UINT64 secs = ms / 1000; - this->tv_.tv_sec = static_cast (secs); - // Convert remainder to microseconds; - this->tv_.tv_usec = static_cast((ms - (secs * 1000)) * 1000); -} - -/// Converts from milli-seconds format into Time_Value format. -ACE_INLINE void -ACE_Time_Value::msec (long milliseconds) -{ - // ACE_OS_TRACE ("ACE_Time_Value::msec"); - // Convert millisecond units to seconds; - long secs = milliseconds / 1000; - this->tv_.tv_sec = secs; - // Convert remainder to microseconds; - this->tv_.tv_usec = (milliseconds - (secs * 1000)) * 1000; -} - -/// Converts from milli-seconds format into Time_Value format. -ACE_INLINE void -ACE_Time_Value::msec (int milliseconds) -{ - ACE_Time_Value::msec (static_cast (milliseconds)); -} - -/// Returns number of micro-seconds. -ACE_INLINE suseconds_t -ACE_Time_Value::usec (void) const -{ - // ACE_OS_TRACE ("ACE_Time_Value::usec"); - return this->tv_.tv_usec; -} - -/// Sets the number of micro-seconds. -ACE_INLINE void -ACE_Time_Value::usec (suseconds_t usec) -{ - // ACE_OS_TRACE ("ACE_Time_Value::usec"); - this->tv_.tv_usec = usec; -} - -ACE_INLINE void -ACE_Time_Value::to_usec (ACE_UINT64 & usec) const -{ - // ACE_OS_TRACE ("ACE_Time_Value::to_usec"); - -#if defined (ACE_LACKS_UNSIGNEDLONGLONG_T) - usec = ACE_U_LongLong (static_cast (this->tv_.tv_sec)); -#elif defined (ACE_LACKS_LONGLONG_T) - // No native 64-bit type, meaning time_t is most likely 32 bits. - usec = ACE_U_LongLong (this->tv_.tv_sec); -#else - usec = static_cast (this->tv_.tv_sec); -#endif /* ACE_LACKS_LONGLONG_T */ - usec *= 1000000; - usec += this->tv_.tv_usec; -} - -ACE_INLINE ACE_Time_Value -operator * (double d, const ACE_Time_Value &tv) -{ - return ACE_Time_Value (tv) *= d; -} - -ACE_INLINE ACE_Time_Value -operator * (const ACE_Time_Value &tv, double d) -{ - return ACE_Time_Value (tv) *= d; -} - -/// True if tv1 > tv2. -ACE_INLINE bool -operator > (const ACE_Time_Value &tv1, - const ACE_Time_Value &tv2) -{ - // ACE_OS_TRACE ("operator >"); - if (tv1.sec () > tv2.sec ()) - return 1; - else if (tv1.sec () == tv2.sec () - && tv1.usec () > tv2.usec ()) - return 1; - else - return 0; -} - -/// True if tv1 >= tv2. -ACE_INLINE bool -operator >= (const ACE_Time_Value &tv1, - const ACE_Time_Value &tv2) -{ - // ACE_OS_TRACE ("operator >="); - if (tv1.sec () > tv2.sec ()) - return 1; - else if (tv1.sec () == tv2.sec () - && tv1.usec () >= tv2.usec ()) - return 1; - else - return 0; -} - -/// Returns the value of the object as a timespec_t. -ACE_INLINE -ACE_Time_Value::operator timespec_t () const -{ - // ACE_OS_TRACE ("ACE_Time_Value::operator timespec_t"); - timespec_t tv; - tv.tv_sec = this->sec (); - // Convert microseconds into nanoseconds. - tv.tv_nsec = this->tv_.tv_usec * 1000; - return tv; -} - -/// Initializes the ACE_Time_Value object from a timespec_t. -ACE_INLINE -ACE_Time_Value::ACE_Time_Value (const timespec_t &tv) - // : tv_ () -{ - // ACE_OS_TRACE ("ACE_Time_Value::ACE_Time_Value"); - this->set (tv); -} - -/// True if tv1 < tv2. -ACE_INLINE bool -operator < (const ACE_Time_Value &tv1, - const ACE_Time_Value &tv2) -{ - // ACE_OS_TRACE ("operator <"); - return tv2 > tv1; -} - -/// True if tv1 >= tv2. -ACE_INLINE bool -operator <= (const ACE_Time_Value &tv1, - const ACE_Time_Value &tv2) -{ - // ACE_OS_TRACE ("operator <="); - return tv2 >= tv1; -} - -/// True if tv1 == tv2. -ACE_INLINE bool -operator == (const ACE_Time_Value &tv1, - const ACE_Time_Value &tv2) -{ - // ACE_OS_TRACE ("operator =="); - return tv1.sec () == tv2.sec () - && tv1.usec () == tv2.usec (); -} - -/// True if tv1 != tv2. -ACE_INLINE bool -operator != (const ACE_Time_Value &tv1, - const ACE_Time_Value &tv2) -{ - // ACE_OS_TRACE ("operator !="); - return !(tv1 == tv2); -} - -/// Add TV to this. -ACE_INLINE ACE_Time_Value & -ACE_Time_Value::operator+= (const ACE_Time_Value &tv) -{ - // ACE_OS_TRACE ("ACE_Time_Value::operator+="); - this->sec (this->sec () + tv.sec ()); - this->usec (this->usec () + tv.usec ()); - this->normalize (); - return *this; -} - -ACE_INLINE ACE_Time_Value & -ACE_Time_Value::operator+= (time_t tv) -{ - // ACE_OS_TRACE ("ACE_Time_Value::operator+="); - this->sec (this->sec () + tv); - return *this; -} - -ACE_INLINE ACE_Time_Value & -ACE_Time_Value::operator= (const ACE_Time_Value &tv) -{ - // ACE_OS_TRACE ("ACE_Time_Value::operator="); - this->sec (tv.sec ()); - this->usec (tv.usec ()); - return *this; -} - -ACE_INLINE ACE_Time_Value & -ACE_Time_Value::operator= (time_t tv) -{ - // ACE_OS_TRACE ("ACE_Time_Value::operator="); - this->sec (tv); - this->usec (0); - return *this; -} - -/// Subtract TV to this. -ACE_INLINE ACE_Time_Value & -ACE_Time_Value::operator-= (const ACE_Time_Value &tv) -{ - // ACE_OS_TRACE ("ACE_Time_Value::operator-="); - this->sec (this->sec () - tv.sec ()); - this->usec (this->usec () - tv.usec ()); - this->normalize (); - return *this; -} - -ACE_INLINE ACE_Time_Value & -ACE_Time_Value::operator-= (time_t tv) -{ - // ACE_OS_TRACE ("ACE_Time_Value::operator-="); - this->sec (this->sec () - tv); - return *this; -} - -/// Adds two ACE_Time_Value objects together, returns the sum. -ACE_INLINE ACE_Time_Value -operator + (const ACE_Time_Value &tv1, - const ACE_Time_Value &tv2) -{ - // ACE_OS_TRACE ("operator +"); - ACE_Time_Value sum (tv1); - sum += tv2; - - return sum; -} - -/// Subtracts two ACE_Time_Value objects, returns the difference. -ACE_INLINE ACE_Time_Value -operator - (const ACE_Time_Value &tv1, - const ACE_Time_Value &tv2) -{ - // ACE_OS_TRACE ("operator -"); - ACE_Time_Value delta (tv1); - delta -= tv2; - - return delta; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Timeprobe.cpp b/externals/ace/Timeprobe.cpp deleted file mode 100644 index 1fe8459ed8d..00000000000 --- a/externals/ace/Timeprobe.cpp +++ /dev/null @@ -1,15 +0,0 @@ -// $Id: Timeprobe.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/config-all.h" - -ACE_RCSID(ace, Timeprobe, "$Id: Timeprobe.cpp 80826 2008-03-04 14:51:23Z wotte $") - -#if defined (ACE_COMPILE_TIMEPROBES) - -#include "ace/Timeprobe.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Timeprobe.inl" -#endif /* __ACE_INLINE__ */ - -#endif /* ACE_COMPILE_TIMEPROBES */ diff --git a/externals/ace/Timeprobe.h b/externals/ace/Timeprobe.h deleted file mode 100644 index ac2abe38d0e..00000000000 --- a/externals/ace/Timeprobe.h +++ /dev/null @@ -1,201 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Timeprobe.h - * - * $Id: Timeprobe.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Irfan Pyarali - * - * If users want to use time probes, the ACE_COMPILE_TIMEPROBES - * flag must be defined when compiling ACE. This can be achieved - * by doing one of the following: - * - * . Use make probe = 1, if you are using the make utility. - * - * . Define ACE_COMPILE_TIMEPROBES in config.h - * - * . Define ACE_COMPILE_TIMEPROBES in the VC project file. - * - * . Other regular methods will also work. - * - * It is not necessary to define ACE_COMPILE_TIMEPROBES when using - * time probes, you simply need ACE_ENABLE_TIMEPROBES. You can use - * the ACE_TIMEPROBE_* macros to program the time probes, and use - * the ACE_ENABLE_TIMEPROBE to enable the time probes. If you - * define ACE_ENABLE_TIMEPROBE in your code, but forget to compile - * ACE with ACE_COMPILE_TIMEPROBES, you will end up with linker - * errors. - * - * Remember that ACE_COMPILE_TIMEPROBES means that the ACE library - * will contain code for time probes. This is only useful when - * compiling ACE. ACE_ENABLE_TIMEPROBES means that the - * ACE_TIMEPROBE_* macros should spring to life. - */ -//============================================================================= - -#ifndef ACE_TIMEPROBE_H -#define ACE_TIMEPROBE_H -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" -#include /**/ "ace/ACE_export.h" -#include "ace/Malloc_Allocator.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -/* Enable ACE Timeprobes */ -#if defined (ACE_ENABLE_TIMEPROBES) - #if !defined (ACE_COMPILE_TIMEPROBES) - #define ACE_COMPILE_TIMEPROBES - #endif /* ACE_COMPILE_TIMEPROBES */ -#endif /* ACE_ENABLE_TIMEPROBES */ - -#if defined (ACE_COMPILE_TIMEPROBES) - -#include "ace/OS_NS_time.h" -#include "ace/OS_NS_Thread.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Event_Descriptions - * - * @brief Event Descriptions. - */ -class ACE_Export ACE_Event_Descriptions -{ -public: - /// Event descriptions - const char **descriptions_; - - /// Minimum id of this description set - u_long minimum_id_; - - /// Comparison - bool operator== (const ACE_Event_Descriptions &rhs) const; -}; - -/** - * @class ACE_timeprobe_t - * - * @brief Time probe record. - */ -class ACE_Export ACE_timeprobe_t -{ -public: - /// Events are record as strings or numbers. - union event - { - u_long event_number_; - const char *event_description_; - }; - - /// Type of event. - enum event_type - { - NUMBER, - STRING - }; - - /// Event. - event event_; - - /// Type of event. - event_type event_type_; - - /// Timestamp. - ACE_hrtime_t time_; - - /// Id of thread posting the time probe. - ACE_thread_t thread_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Timeprobe.inl" -#endif /* __ACE_INLINE__ */ - -#include "ace/Synch_Traits.h" -#include "ace/Null_Mutex.h" -#include "ace/Singleton.h" -#include "ace/Timeprobe_T.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// If ACE_MT_TIMEPROBES is defined, use a Thread_Mutex to lock the -// internal state of ACE_Timerprobe. This allows multiple threads to -// use the same ACE_Timerprobe. -# if defined (ACE_MT_TIMEPROBES) -typedef ACE_SYNCH_MUTEX ACE_TIMEPROBE_MUTEX; -# else /* ACE_MT_TIMEPROBES */ -typedef ACE_SYNCH_NULL_MUTEX ACE_TIMEPROBE_MUTEX; -# endif /* ACE_MT_TIMEPROBES */ - -typedef ACE_New_Allocator ACE_TIMEPROBE_ALLOCATOR; - -typedef ACE_Timeprobe_Ex - ACE_TIMEPROBE_WITH_LOCKING; - -// If ACE_TSS_TIMEPROBES is defined, store the ACE_Timeprobe singleton -// in thread specific storage. This allows multiple threads to use -// their own instance of ACE_Timerprobe, without interfering with each -// other. - -# if defined (ACE_TSS_TIMEPROBES) -# define ACE_TIMEPROBE_SINGLETON_TYPE ACE_TSS_Singleton -# define ACE_TIMEPROBE_SINGLETON_LOCK_TYPE ACE_SYNCH_NULL_MUTEX -# else /* ACE_TSS_TIMEPROBES */ -# define ACE_TIMEPROBE_SINGLETON_TYPE ACE_Singleton -# define ACE_TIMEPROBE_SINGLETON_LOCK_TYPE ACE_SYNCH_MUTEX -# endif /* ACE_TSS_TIMEPROBES */ - -ACE_SINGLETON_DECLARE (ACE_TIMEPROBE_SINGLETON_TYPE, \ - ACE_TIMEPROBE_WITH_LOCKING, \ - ACE_TIMEPROBE_SINGLETON_LOCK_TYPE) - -typedef ACE_TIMEPROBE_SINGLETON_TYPE - ACE_TIMEPROBE_SINGLETON; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_COMPILE_TIMEPROBES */ - -// If ACE_ENABLE_TIMEPROBES is defined, the macros below will -// work. Otherwise, they just vanish. Using this macro, you can -// control which files/libraries are probed. -#if defined (ACE_ENABLE_TIMEPROBES) && defined (ACE_COMPILE_TIMEPROBES) - -# define ACE_TIMEPROBE_RESET ACE_TIMEPROBE_SINGLETON::instance ()->reset () - -# define ACE_TIMEPROBE(id) ACE_TIMEPROBE_SINGLETON::instance ()->timeprobe (id) - -# define ACE_TIMEPROBE_PRINT ACE_TIMEPROBE_SINGLETON::instance ()->print_times () - -# define ACE_TIMEPROBE_PRINT_ABSOLUTE ACE_TIMEPROBE_SINGLETON::instance ()->print_absolute_times () - -# define ACE_TIMEPROBE_EVENT_DESCRIPTIONS(descriptions, minimum_id) \ -static int ace_timeprobe_##descriptions##_return = \ - ACE_TIMEPROBE_SINGLETON::instance ()->event_descriptions \ - (descriptions, minimum_id) - -# define ACE_FUNCTION_TIMEPROBE(X) \ - ACE_Function_Timeprobe function_timeprobe \ - (*ACE_TIMEPROBE_SINGLETON::instance (), X) - -#else /* ACE_ENABLE_TIMEPROBES && ACE_COMPILE_TIMEPROBES */ - -# define ACE_TIMEPROBE_RESET -# define ACE_TIMEPROBE(id) -# define ACE_TIMEPROBE_PRINT -# define ACE_TIMEPROBE_PRINT_ABSOLUTE -# define ACE_TIMEPROBE_EVENT_DESCRIPTIONS(descriptions, minimum_id) -# define ACE_FUNCTION_TIMEPROBE(X) - -#endif /* ACE_ENABLE_TIMEPROBES && ACE_COMPILE_TIMEPROBES */ -#include /**/ "ace/post.h" -#endif /* ACE_TIMEPROBE_H */ diff --git a/externals/ace/Timeprobe.inl b/externals/ace/Timeprobe.inl deleted file mode 100644 index aa7a9240648..00000000000 --- a/externals/ace/Timeprobe.inl +++ /dev/null @@ -1,14 +0,0 @@ -// -*- C++ -*- -// -// $Id: Timeprobe.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE bool -ACE_Event_Descriptions::operator== (const ACE_Event_Descriptions &rhs) const -{ - return this->minimum_id_ == rhs.minimum_id_ && - this->descriptions_ == rhs.descriptions_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Timeprobe_T.cpp b/externals/ace/Timeprobe_T.cpp deleted file mode 100644 index d23b7b8b869..00000000000 --- a/externals/ace/Timeprobe_T.cpp +++ /dev/null @@ -1,427 +0,0 @@ -// $Id: Timeprobe_T.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#ifndef ACE_TIMEPROBE_T_CPP -#define ACE_TIMEPROBE_T_CPP - -#include "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_COMPILE_TIMEPROBES) - -#include "ace/Timeprobe.h" -#include "ace/High_Res_Timer.h" -#include "ace/OS_NS_string.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template -ACE_Timeprobe_Ex::ACE_Timeprobe_Ex (u_long size) - : timeprobes_ (0), - lock_ (), - max_size_ (size), - current_size_ (0), - report_buffer_full_ (0), - allocator_ (0) -{ - ACE_timeprobe_t *temp; - //FUZZ: disable check_for_lack_ACE_OS - ACE_NEW_MALLOC_ARRAY (temp, - (ACE_timeprobe_t *) this->allocator ()-> - malloc (this->max_size_*sizeof(ACE_timeprobe_t)), - ACE_timeprobe_t, - this->max_size_); - //FUZZ: enable check_for_lack_ACE_OS - this->timeprobes_ = temp; - -} - -template -ACE_Timeprobe_Ex:: -ACE_Timeprobe_Ex (ALLOCATOR *allocator, - u_long size) - : timeprobes_ (0), - lock_ (), - max_size_ (size), - current_size_ (0), - report_buffer_full_ (0), - allocator_ (allocator) -{ - ACE_timeprobe_t *temp = 0; - //FUZZ: disable check_for_lack_ACE_OS - ACE_NEW_MALLOC_ARRAY (temp, - (ACE_timeprobe_t *) this->allocator ()-> - malloc (this->max_size_*sizeof(ACE_timeprobe_t)), - ACE_timeprobe_t, - this->max_size_); - //FUZZ: enable check_for_lack_ACE_OS - this->timeprobes_ = temp; - -} - -template -ACE_Timeprobe_Ex::ACE_Timeprobe_Ex (const ACE_Timeprobe_Ex &) -{ - // - // Stupid MSVC is forcing me to define this; please don't use it. - // - - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("ACE_NOTSUP: %N, line %l\n"))); - errno = ENOTSUP; -} - -template -ACE_Timeprobe_Ex::~ACE_Timeprobe_Ex (void) -{ - ACE_DES_ARRAY_FREE ((ACE_timeprobe_t *) (this->timeprobes_), - this->max_size_, - this->allocator ()->free, - ACE_timeprobe_t); -} - -template void -ACE_Timeprobe_Ex::timeprobe (u_long event) -{ - ACE_GUARD (ACE_LOCK, ace_mon, this->lock_); - - this->timeprobes_[this->current_size_].event_.event_number_ = event; - this->timeprobes_[this->current_size_].event_type_ = ACE_timeprobe_t::NUMBER; - this->timeprobes_[this->current_size_].time_ = ACE_OS::gethrtime (); - this->timeprobes_[this->current_size_].thread_ = ACE_OS::thr_self (); - - ++this->current_size_; - -#if !defined (ACE_TIMEPROBE_ASSERTS_FIXED_SIZE) - // wrap around to the beginning on overflow - if (this->current_size_ >= this->max_size_) - { - this->current_size_ = 0; - this->report_buffer_full_ = 1; - } -#endif /* ACE_TIMEPROBE_ASSERTS_FIXED_SIZE */ - - ACE_ASSERT (this->current_size_ < this->max_size_); -} - -template void -ACE_Timeprobe_Ex::timeprobe (const char *event) -{ - ACE_GUARD (ACE_LOCK, ace_mon, this->lock_); - - this->timeprobes_[this->current_size_].event_.event_description_ = event; - this->timeprobes_[this->current_size_].event_type_ = ACE_timeprobe_t::STRING; - this->timeprobes_[this->current_size_].time_ = ACE_OS::gethrtime (); - this->timeprobes_[this->current_size_].thread_ = ACE_OS::thr_self (); - - ++this->current_size_; - -#if !defined (ACE_TIMEPROBE_ASSERTS_FIXED_SIZE) - // wrap around to the beginning on overflow - if (this->current_size_ >= this->max_size_) - { - this->current_size_ = 0; - this->report_buffer_full_ = 1; - } -#endif /* ACE_TIMEPROBE_ASSERTS_FIXED_SIZE */ - - ACE_ASSERT (this->current_size_ < this->max_size_); -} - -template void -ACE_Timeprobe_Ex::reset (void) -{ - ACE_GUARD (ACE_LOCK, ace_mon, this->lock_); - - this->current_size_ = 0; - this->report_buffer_full_ = 0; -} - -template void -ACE_Timeprobe_Ex::increase_size (u_long size) -{ - ACE_GUARD (ACE_LOCK, ace_mon, this->lock_); - - if (size > this->max_size_) - { - ACE_timeprobe_t *temp = 0; - //FUZZ: disable check_for_lack_ACE_OS - ACE_NEW_MALLOC_ARRAY (temp, - (ACE_timeprobe_t *) this->allocator ()-> - malloc (this->max_size_ - * sizeof (ACE_timeprobe_t)), - ACE_timeprobe_t, - size); - //FUZZ: enable check_for_lack_ACE_OS - - if (this->max_size_ > 0) - { - ACE_OS::memcpy (temp, - this->timeprobes_, - this->max_size_ * sizeof (ACE_timeprobe_t)); - - // Iterates over the array explicitly calling the destructor for - // each probe instance, then deallocates the memory - - ACE_DES_ARRAY_FREE ((ACE_timeprobe_t *)(this->timeprobes_), - this->max_size_, - this->allocator ()->free, - ACE_timeprobe_t); - } - this->timeprobes_ = temp; - this->max_size_ = size; - } -} - -template ACE_Unbounded_Set & -ACE_Timeprobe_Ex::event_descriptions (void) -{ - return this->event_descriptions_; -} - -template ACE_Unbounded_Set & -ACE_Timeprobe_Ex::sorted_event_descriptions (void) -{ - return this->sorted_event_descriptions_; -} - -template ACE_timeprobe_t * -ACE_Timeprobe_Ex::timeprobes (void) -{ - return this->timeprobes_; -} - -template ACE_LOCK & -ACE_Timeprobe_Ex::lock (void) -{ - return this->lock_; -} - -template u_long -ACE_Timeprobe_Ex::max_size (void) -{ - return this->max_size_; -} - -template u_long -ACE_Timeprobe_Ex::current_size (void) -{ - return this->current_size_; -} - -template int -ACE_Timeprobe_Ex::event_descriptions (const char **descriptions, - u_long minimum_id) -{ - ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->lock_, -1); - - ACE_Event_Descriptions events; - events.descriptions_ = descriptions; - events.minimum_id_ = minimum_id; - - this->event_descriptions_.insert (events); - - return 0; -} - -template void -ACE_Timeprobe_Ex::print_times (void) -{ - ACE_GUARD (ACE_LOCK, ace_mon, this->lock_); - - // Sort the event descriptions - this->sort_event_descriptions_i (); - - u_long size = this->report_buffer_full_ ? this->max_size_ - : this->current_size_; - - ACE_DEBUG ((LM_DEBUG, - "\nACE_Timeprobe_Ex; %u timestamps were recorded:\n", - size)); - - if (size == 0) - return; - - ACE_DEBUG ((LM_DEBUG, - "\n%-50.50s %8.8s %13.13s\n\n", - "Event", - "thread", - "usec")); - - double gsf = ACE_High_Res_Timer::global_scale_factor (); - u_long i, j; - - // First element - i = this->report_buffer_full_ ? this->current_size_ : 0; - - ACE_DEBUG ((LM_DEBUG, - "%-50.50s %8.8x %13.13s\n", - this->find_description_i (i), - this->timeprobes_[i].thread_, - "START")); - - if (size == 1) - return; - - bool has_timestamp_inversion = false; - - j = i; - i = (i + 1) % this->max_size_; - - do - { - // When reusing the same ACE_Timeprobe from multiple threads - // with Linux on Intel SMP, it sometimes happens that the - // recorded times go backward in time if they are recorded from - // different threads (see bugzilla #2342). To obtain the - // correct signed difference between consecutive recorded times, - // one has to cast the time difference to an intermediate signed - // integral type of the same size as ACE_hrtime_t. - - double time_difference = - (ACE_INT64) (this->timeprobes_[i].time_ - this->timeprobes_[j].time_); - - if (time_difference < 0) - has_timestamp_inversion = true; - - // Convert to microseconds. - time_difference /= gsf; - - ACE_DEBUG ((LM_DEBUG, - "%-50.50s %8.8x %14.3f\n", - this->find_description_i (i), - this->timeprobes_[i].thread_, - time_difference)); - - j = i; - i = (i + 1) % this->max_size_; - } - while (i != this->current_size_); - - static bool inversion_warning_printed = false; - if (!inversion_warning_printed && has_timestamp_inversion) - { - inversion_warning_printed = true; - ACE_DEBUG ((LM_DEBUG, - "\nWARNING: The timestamps recorded by gethrtime() on" - " this platform are\n" - "not monotonic across different threads.\n")); - } -} - -template void -ACE_Timeprobe_Ex::print_absolute_times (void) -{ - ACE_GUARD (ACE_LOCK, ace_mon, this->lock_); - - // Sort the event descriptions - this->sort_event_descriptions_i (); - - u_long size = this->report_buffer_full_ ? this->max_size_ - : this->current_size_; - - ACE_DEBUG ((LM_DEBUG, - "\nACE_Timeprobe_Ex; %u timestamps were recorded:\n", - size)); - - if (size == 0) - return; - - ACE_DEBUG ((LM_DEBUG, - "\n%-50.50s %8.8s %13.13s\n\n", - "Event", - "thread", - "stamp")); - - u_long i = this->report_buffer_full_ ? this->current_size_ : 0; - - ACE_Time_Value tv; // to convert ACE_hrtime_t - do - { - ACE_High_Res_Timer::hrtime_to_tv (tv, this->timeprobes_ [i].time_); - - ACE_DEBUG ((LM_DEBUG, - "%-50.50s %8.8x %12.12u\n", - this->find_description_i (i), - this->timeprobes_ [i].thread_, - tv.sec () * 1000000 - + tv.usec ())); - - // Modulus increment: loops around at the end. - i = (i + 1) % this->max_size_; - } - while (i != this->current_size_); -} - -template const char * -ACE_Timeprobe_Ex::find_description_i (u_long i) -{ - if (this->timeprobes_[i].event_type_ == ACE_timeprobe_t::STRING) - return this->timeprobes_[i].event_.event_description_; - else - { - EVENT_DESCRIPTIONS::iterator iterator = this->sorted_event_descriptions_.begin (); - for (u_long j = 0; - j < this->sorted_event_descriptions_.size () - 1; - iterator++, j++) - { - EVENT_DESCRIPTIONS::iterator next_event_descriptions = iterator; - ++next_event_descriptions; - - if (this->timeprobes_[i].event_.event_number_ < (*next_event_descriptions).minimum_id_) - break; - } - return (*iterator).descriptions_[this->timeprobes_[i].event_.event_number_ - (*iterator).minimum_id_]; - } -} - -template void -ACE_Timeprobe_Ex::sort_event_descriptions_i (void) -{ - size_t total_elements = this->event_descriptions_.size (); - - for (size_t i = 0; - i < total_elements; - i++) - { - EVENT_DESCRIPTIONS::iterator iterator = this->event_descriptions_.begin (); - ACE_Event_Descriptions min_entry = *iterator; - - for (; - iterator != this->event_descriptions_.end (); - iterator++) - if ((*iterator).minimum_id_ < min_entry.minimum_id_) - min_entry = *iterator; - - this->sorted_event_descriptions_.insert (min_entry); - this->event_descriptions_.remove (min_entry); - } -} - -template ALLOCATOR * -ACE_Timeprobe_Ex::allocator (void) -{ - return allocator_ ? allocator_ : ACE_Singleton::instance (); -} - -template -ACE_Function_Timeprobe::ACE_Function_Timeprobe (Timeprobe &timeprobe, - u_long event) - : timeprobe_ (timeprobe), - event_ (event) -{ - this->timeprobe_.timeprobe (this->event_); -} - -template -ACE_Function_Timeprobe::~ACE_Function_Timeprobe (void) -{ - this->timeprobe_.timeprobe (this->event_ + 1); -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_COMPILE_TIMEPROBES */ -#endif /* ACE_TIMEPROBE_T_CPP */ diff --git a/externals/ace/Timeprobe_T.h b/externals/ace/Timeprobe_T.h deleted file mode 100644 index 54e5ff4c185..00000000000 --- a/externals/ace/Timeprobe_T.h +++ /dev/null @@ -1,220 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Timeprobe_T.h - * - * $Id: Timeprobe_T.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Irfan Pyarali - */ -//============================================================================= - - -#ifndef ACE_TIMEPROBE_T_H -#define ACE_TIMEPROBE_T_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_COMPILE_TIMEPROBES) - -#include "ace/Unbounded_Set.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Timeprobe_Ex - * - * @brief This class is used to instrument code. This is accomplished - * by inserting time probes at different location in the code. - * ACE_Timeprobe then measures the time difference between two - * time probes. - * - * This class provides a lightweight implementation for - * measuring the time required to execute code between two time - * probes. When a time probe executes, it records the time, the - * id of the calling thread, and an event description. The - * event description can either be an unsigned long or a string - * (char *). If string are used, care must be taken cause only - * pointer copies are done and the string data is *not* copied. - * The recorded time probes can then be printed by calling - * . If you have used unsigned longs as event - * descriptions in any of your time probes, you must have - * provided an event description table that maps the unsigned - * longs to readable strings. This map is a simple array of - * strings, and the event number is used as the index into the - * array when looking for the event description. If you have - * only used strings for the event description, this map is not - * necessary. - * Multiple maps can also be used to chunk up the time probes. - * Each one can be added by calling . - * Different tables are used internally by consulting the - * minimum_id for each table. It is up to the user to make sure - * that multiple tables do not share the same event id range. - */ -template -class ACE_Timeprobe_Ex -{ -public: - - /// Self - typedef ACE_Timeprobe_Ex - SELF; - - /** - * ACE_Timeprobe - */ - typedef ACE_Timeprobe_Ex ACE_Timeprobe; - - - /// We can hold multiple event description tables. - typedef ACE_Unbounded_Set - EVENT_DESCRIPTIONS; - - /// Create Timeprobes with @a size slots - ACE_Timeprobe_Ex (u_long size = ACE_DEFAULT_TIMEPROBE_TABLE_SIZE); - - /// Create Timeprobes with @a size slots - ACE_Timeprobe_Ex (ALLOCATOR *allocator, - u_long size = ACE_DEFAULT_TIMEPROBE_TABLE_SIZE); - /// Destructor. - ~ACE_Timeprobe_Ex (void); - - /// Record a time. @a event is used to describe this time probe. - void timeprobe (u_long event); - - /// Record a time. @a id is used to describe this time probe. - void timeprobe (const char *id); - - /// Record event descriptions. - int event_descriptions (const char **descriptions, - u_long minimum_id); - - /// Print the time probes. - void print_times (void); - - /// Print the time probes. - void print_absolute_times (void); - - /// Reset the slots. All old time probes will be lost. - void reset (void); - - void increase_size (u_long size); - - /// Not implemented (stupid MSVC won't let it be protected). - ACE_Timeprobe_Ex (const ACE_Timeprobe_Ex &); - - // = (Somewhat private) Accessors - - /// Event Descriptions - ACE_Unbounded_Set &event_descriptions (void); - - /// Sorted Event Descriptions. - ACE_Unbounded_Set &sorted_event_descriptions (void); - - /// Find description of event @a i - const char *find_description_i (u_long i); - - /// Sort event descriptions - void sort_event_descriptions_i (void); - - /// Time probe slots - ACE_timeprobe_t *timeprobes (void); - - /// Synchronization variable. - ACE_LOCK &lock (void); - - /// Max size of timestamp table - u_long max_size (void); - - /// Current size of timestamp table - u_long current_size (void); - -protected: - - /// Obtain an allocator pointer. If there is no allocator stored in - /// the instance, the singleton allocator in the current process is used. - ALLOCATOR * allocator (void); - - /// Event Descriptions - EVENT_DESCRIPTIONS event_descriptions_; - - /// Sorted Event Descriptions. - EVENT_DESCRIPTIONS sorted_event_descriptions_; - - /// Time probe slots - ACE_timeprobe_t *timeprobes_; - - /// Synchronization variable. - ACE_LOCK lock_; - - /// Max size of timestamp table - u_long max_size_; - - /// Current size of timestamp table - u_long current_size_; - - /// Flag indicating the report buffer has filled up, and is now - /// acting as a ring-buffer using modulus arithmetic: this saves the - /// max_size_ most recent time stamps and loses earlier ones until - /// drained. - u_short report_buffer_full_; - -private: - ALLOCATOR * allocator_; -}; - -// template -// class ACE_Timeprobe : public ACE_Timeprobe_Ex -// { -// public: -// // Initialize a ACE_Timeprobe with default size -// ACE_Timeprobe (ACE_Allocator *allocator = ACE_Allocator::instance()); - -// /// Create Timeprobes with @a size slots -// ACE_Timeprobe (ACE_Allocator *allocator = ACE_Allocator::instance(), -// u_long size = ACE_DEFAULT_TIMEPROBE_TABLE_SIZE); -// }; - -/** - * @class ACE_Function_Timeprobe - * - * @brief Auto pointer like time probes. It will record on - * construction and on destruction. - */ -template -class ACE_Function_Timeprobe -{ -public: - /// Constructor. - ACE_Function_Timeprobe (Timeprobe &timeprobe, u_long event); - - /// Destructor. - ~ACE_Function_Timeprobe (void); - -protected: - /// Reference to timeprobe. - Timeprobe &timeprobe_; - - /// Event. - u_long event_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Timeprobe_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Timeprobe_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#endif /* ACE_COMPILE_TIMEPROBES */ -#include /**/ "ace/post.h" -#endif /* ACE_TIMEPROBE_T_H */ diff --git a/externals/ace/Timer_Hash.h b/externals/ace/Timer_Hash.h deleted file mode 100644 index b381419da44..00000000000 --- a/externals/ace/Timer_Hash.h +++ /dev/null @@ -1,75 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file Timer_Hash.h - * - * $Id: Timer_Hash.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Darrell Brunsch - */ -//============================================================================= - - -#ifndef ACE_TIMER_HASH_H -#define ACE_TIMER_HASH_H -#include /**/ "ace/pre.h" - -#include "ace/Timer_Hash_T.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Timer_Heap_T.h" -#include "ace/Timer_List_T.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// The following typedef are here for ease of use - -typedef ACE_Timer_Hash_Upcall , - ACE_SYNCH_RECURSIVE_MUTEX> - ACE_Hash_Upcall; - -typedef ACE_Timer_List_T - ACE_Hash_Timer_List; - -typedef ACE_Timer_Heap_T - ACE_Hash_Timer_Heap; - - -typedef ACE_Timer_Hash_T, - ACE_SYNCH_RECURSIVE_MUTEX, - ACE_Hash_Timer_List> - - ACE_Timer_Hash; - -typedef ACE_Timer_Hash_Iterator_T, - ACE_SYNCH_RECURSIVE_MUTEX, - ACE_Hash_Timer_List> - ACE_Timer_Hash_Iterator; - -typedef ACE_Timer_Hash_T, - ACE_SYNCH_RECURSIVE_MUTEX, - ACE_Hash_Timer_Heap> - ACE_Timer_Hash_Heap; - -typedef ACE_Timer_Hash_Iterator_T, - ACE_SYNCH_RECURSIVE_MUTEX, - ACE_Hash_Timer_Heap> - ACE_Timer_Hash_Heap_Iterator; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" -#endif /* ACE_TIMER_HASH_H */ diff --git a/externals/ace/Timer_Hash_T.cpp b/externals/ace/Timer_Hash_T.cpp deleted file mode 100644 index d8153c1eee2..00000000000 --- a/externals/ace/Timer_Hash_T.cpp +++ /dev/null @@ -1,870 +0,0 @@ -// $Id: Timer_Hash_T.cpp 89254 2010-02-25 22:10:39Z cleeland $ - -#ifndef ACE_TIMER_HASH_T_CPP -#define ACE_TIMER_HASH_T_CPP - -#include "ace/Timer_Hash_T.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/OS_NS_sys_time.h" -#include "ace/Guard_T.h" -#include "ace/Log_Msg.h" - -ACE_RCSID(ace, - Timer_Hash_T, - "$Id: Timer_Hash_T.cpp 89254 2010-02-25 22:10:39Z cleeland $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template -class Hash_Token -{ -public: - // This constructor is required by ACE_Locked_Free_List::alloc. - Hash_Token (void) - {} - - Hash_Token *get_next (void) - { - return this->next_; - } - - void set_next (Hash_Token *next) - { - this->next_ = next; - } - - void set (const void *act, - size_t pos, - long orig_id, - const TYPE &type) - { - this->act_ = act; - this->pos_ = pos; - this->orig_id_ = orig_id; - this->type_ = type; - this->next_ = 0; - } - - const void *act_; - size_t pos_; - long orig_id_; - TYPE type_; - /// Pointer to next token. - Hash_Token *next_; -}; - -// Default constructor - -template -ACE_Timer_Hash_Upcall::ACE_Timer_Hash_Upcall (void) - : timer_hash_ (0) -{ - // Nothing -} - -// Constructor that specifies a Timer_Hash to call up to - -template -ACE_Timer_Hash_Upcall::ACE_Timer_Hash_Upcall ( - ACE_Timer_Queue_T *timer_hash) - : timer_hash_ (timer_hash) -{ - // Nothing -} - -template int -ACE_Timer_Hash_Upcall::registration ( - TIMER_QUEUE &, - ACE_Event_Handler *, - const void *) -{ - // Registration will be handled by the upcall functor of the timer - // hash. - return 0; -} - -template int -ACE_Timer_Hash_Upcall::preinvoke (TIMER_QUEUE &, - ACE_Event_Handler *, - const void *, - int, - const ACE_Time_Value &, - const void *&) -{ - // This method should never be invoked since we don't invoke - // expire() on the buckets. - ACE_ASSERT (0); - return 0; -} - -template int -ACE_Timer_Hash_Upcall::postinvoke ( - TIMER_QUEUE &, - ACE_Event_Handler *, - const void *, - int, - const ACE_Time_Value &, - const void *) -{ - // This method should never be invoked since we don't invoke - // expire() on the buckets. - ACE_ASSERT (0); - return 0; -} - -// Calls up to timer_hash's upcall functor -template int -ACE_Timer_Hash_Upcall::timeout ( - TIMER_QUEUE &, - ACE_Event_Handler *, - const void *, - int, - const ACE_Time_Value &) -{ - // This method should never be invoked since we don't invoke - // expire() on the buckets. - ACE_ASSERT (0); - return 0; -} - -template int -ACE_Timer_Hash_Upcall::cancel_type ( - TIMER_QUEUE &, - ACE_Event_Handler *, - int, - int &) -{ - // Cancellation will be handled by the upcall functor of the timer - // hash. - return 0; -} - -template int -ACE_Timer_Hash_Upcall::cancel_timer ( - TIMER_QUEUE &, - ACE_Event_Handler *, - int, - int) -{ - // Cancellation will be handled by the upcall functor of the timer - // hash. - return 0; -} - -template int -ACE_Timer_Hash_Upcall::deletion ( - TIMER_QUEUE &, - ACE_Event_Handler *event_handler, - const void *arg) -{ - // Call up to the upcall functor of the timer hash since the timer - // hash does not invoke deletion() on its upcall functor directly. - Hash_Token *h = - reinterpret_cast *> (const_cast (arg)); - - int result = - this->timer_hash_->upcall_functor (). - deletion (*this->timer_hash_, - event_handler, - h->act_); - - return result; -} - -template -ACE_Timer_Hash_Iterator_T::ACE_Timer_Hash_Iterator_T (ACE_Timer_Hash_T &hash) - : timer_hash_ (hash) -{ - this->first (); - // Nothing -} - -// Positions the iterator at the first node in the timing hash table - -template void -ACE_Timer_Hash_Iterator_T::first (void) -{ - for (this->position_ = 0; - this->position_ < this->timer_hash_.table_size_; - ++this->position_) - { - // Check for an empty entry - if (!this->timer_hash_.table_[this->position_]->is_empty ()) - { - this->iter_ = &this->timer_hash_.table_[this->position_]->iter (); - this->iter_->first (); - return; - } - } - - // Didn't find any - this->iter_ = 0; -} - -// Positions the iterator at the next node in the bucket or goes to the next -// bucket - -template void -ACE_Timer_Hash_Iterator_T::next (void) -{ - if (this->isdone ()) - return; - - // If there is no more in the current bucket, go to the next - if (this->iter_->isdone ()) - { - for (++this->position_; - this->position_ < this->timer_hash_.table_size_; - ++this->position_) - { - // Check for an empty entry - if (!this->timer_hash_.table_[this->position_]->is_empty ()) - { - this->iter_ = &this->timer_hash_.table_[this->position_]->iter (); - this->iter_->first (); - return; - } - } - - // Didn't find any. - this->iter_ = 0; - } - else - this->iter_->next (); -} - -// Returns true when we are at the end (when bucket_item_ == 0) - -template bool -ACE_Timer_Hash_Iterator_T::isdone (void) const -{ - return this->iter_ == 0; -} - -// Returns the node at the current position in the sequence - -template -ACE_Timer_Node_T * -ACE_Timer_Hash_Iterator_T::item (void) -{ - if (this->isdone ()) - return 0; - - return this->iter_->item (); -} - -template -ACE_Timer_Queue_Iterator_T & -ACE_Timer_Hash_T::iter (void) -{ - this->iterator_->first (); - return *this->iterator_; -} - -// Create an empty queue. - -template -ACE_Timer_Hash_T::ACE_Timer_Hash_T ( - size_t table_size, - FUNCTOR *upcall_functor, - ACE_Free_List > *freelist) - : ACE_Timer_Queue_T (upcall_functor, freelist), - size_ (0), - table_size_ (table_size), - table_functor_ (this), - earliest_position_ (0) -#if defined (ACE_WIN64) - , pointer_base_ (0) -#endif /* ACE_WIN64 */ - , token_list_ () -{ - ACE_TRACE ("ACE_Timer_Hash_T::ACE_Timer_Hash_T"); - - ACE_NEW (table_, - BUCKET *[table_size]); - - this->gettimeofday (ACE_OS::gettimeofday); - - for (size_t i = 0; - i < table_size; - ++i) - { - ACE_NEW (this->table_[i], - BUCKET (&this->table_functor_, - this->free_list_)); - this->table_[i]->gettimeofday (ACE_OS::gettimeofday); - } - - ACE_NEW (iterator_, - HASH_ITERATOR (*this)); -} - - -template -ACE_Timer_Hash_T::ACE_Timer_Hash_T ( - FUNCTOR *upcall_functor, - ACE_Free_List > *freelist) - : ACE_Timer_Queue_T (upcall_functor, freelist), - size_ (0), - table_size_ (ACE_DEFAULT_TIMER_HASH_TABLE_SIZE), - table_functor_ (this), - earliest_position_ (0) -#if defined (ACE_WIN64) - , pointer_base_ (0) -#endif /* ACE_WIN64 */ - , token_list_ () -{ - ACE_TRACE ("ACE_Timer_Hash_T::ACE_Timer_Hash_T"); - - ACE_NEW (table_, - BUCKET *[ACE_DEFAULT_TIMER_HASH_TABLE_SIZE]); - - - this->gettimeofday (ACE_OS::gettimeofday); - - for (size_t i = 0; - i < this->table_size_; - ++i) - { - ACE_NEW (this->table_[i], - BUCKET (&this->table_functor_, - this->free_list_)); - this->table_[i]->gettimeofday (ACE_OS::gettimeofday); - } - - ACE_NEW (iterator_, - HASH_ITERATOR (*this)); -} - -// Remove all remaining items in the Queue. - -template -ACE_Timer_Hash_T::~ACE_Timer_Hash_T (void) -{ - ACE_TRACE ("ACE_Timer_Hash_T::~ACE_Timer_Hash_T"); - ACE_MT (ACE_GUARD (ACE_LOCK, ace_mon, this->mutex_)); - - delete iterator_; - - for (size_t i = 0; - i < this->table_size_; - ++i) - delete this->table_[i]; - - delete [] this->table_; -} - -// Checks if queue is empty. - -template bool -ACE_Timer_Hash_T::is_empty (void) const -{ - ACE_TRACE ("ACE_Timer_Hash_T::is_empty"); - return this->table_[this->earliest_position_]->is_empty (); -} - -// Returns earliest time in a non-empty bucket - -template -const ACE_Time_Value & -ACE_Timer_Hash_T::earliest_time (void) const -{ - ACE_TRACE ("ACE_Timer_Hash_T::earliest_time"); - return this->table_[this->earliest_position_]->earliest_time (); -} - -template void -ACE_Timer_Hash_T::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Timer_Hash_T::dump"); - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ntable_size_ = %d"), this->table_size_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nearliest_position_ = %d"), this->earliest_position_)); - - for (size_t i = 0; i < this->table_size_; ++i) - if (!this->table_[i]->is_empty ()) - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nBucket %d contains nodes"), i)); - - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n"))); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -// Reschedule a periodic timer. This function must be called with the -// mutex lock held. - -template -void -ACE_Timer_Hash_T::reschedule ( - ACE_Timer_Node_T *expired) -{ - ACE_TRACE ("ACE_Timer_Hash_T::reschedule"); - - Hash_Token *h = - reinterpret_cast *> ( - const_cast (expired->get_act ())); - - // Don't use ACE_Utils::truncate_cast<> here. A straight - // static_cast<> will provide more unique results when the number - // of seconds is greater than std::numeric_limits::max(). - size_t const secs_hash_input = - static_cast (expired->get_timer_value ().sec ()); - h->pos_ = secs_hash_input % this->table_size_; - - h->orig_id_ = - this->table_[h->pos_]->schedule (expired->get_type (), - h, - expired->get_timer_value (), - expired->get_interval ()); - ACE_ASSERT (h->orig_id_ != -1); - -#if 0 - ACE_DEBUG ((LM_DEBUG, "Hash::reschedule() resets %d in slot %d where it's id is %d and token is %x\n", - expired->get_timer_value ().msec (), - h->pos_, - h->orig_id_, - h)); -#endif - - // Since schedule() above will allocate a new node - // then here schedule for deletion. Don't call - // this->free_node() because that will invalidate - // and that's what user have as timer_id. - ACE_Timer_Queue_T::free_node (expired); - - if (this->table_[this->earliest_position_]->is_empty () - || this->table_[h->pos_]->earliest_time () - < this->table_[this->earliest_position_]->earliest_time ()) - this->earliest_position_ = h->pos_; -} - -// Insert a new handler that expires at time future_time; if interval -// is > 0, the handler will be reinvoked periodically. - -template -long -ACE_Timer_Hash_T::schedule_i ( - const TYPE &type, - const void *act, - const ACE_Time_Value &future_time, - const ACE_Time_Value &interval) -{ - ACE_TRACE ("ACE_Timer_Hash_T::schedule_i"); - - // Don't use ACE_Utils::truncate_cast<> here. A straight - // static_cast<> will provide more unique results when the number - // of seconds is greater than std::numeric_limits::max(). - size_t const secs_hash_input = static_cast (future_time.sec ()); - size_t const position = secs_hash_input % this->table_size_; - - // Don't create Hash_Token directly. Instead we get one from Free_List - // and then set it properly. - Hash_Token *h = this->token_list_.remove (); - h->set (act, position, 0, type); - - h->orig_id_ = - this->table_[position]->schedule (type, - h, - future_time, - interval); - ACE_ASSERT (h->orig_id_ != -1); - -#if 0 - ACE_DEBUG ((LM_DEBUG, "Hash::schedule() placing %d in slot %d where it's id is %d and token is %x\n", - future_time.msec (), - position, - h->orig_id_, - h)); -#endif - - if (this->table_[this->earliest_position_]->is_empty () - || this->table_[position]->earliest_time () - < this->table_[this->earliest_position_]->earliest_time ()) - this->earliest_position_ = position; - - ++this->size_; - -#if defined (ACE_WIN64) - // This is a Win64 hack, necessary because of the original (bad) decision - // to use a pointer as the timer ID. This class doesn't follow the usual - // timer expiration rules (see comments in header file) and is probably - // not used much. The dynamic allocation of Hash_Tokens without - // recording them anywhere is a large problem for Win64 since the - // size of a pointer is 64 bits, but a long is 32. Since this class - // is not much used, I'm hacking this, at least for now. If it becomes - // an issue, I'll look at it again then. - intptr_t hi = reinterpret_cast (h); - if (this->pointer_base_ == 0) - this->pointer_base_ = hi & 0xffffffff00000000; - return static_cast (hi & 0xffffffff); -#else - return reinterpret_cast (h); -#endif -} - -// Locate and update the inteval on the timer_id - -template -int -ACE_Timer_Hash_T::reset_interval ( - long timer_id, - const ACE_Time_Value & interval) -{ - ACE_TRACE ("ACE_Timer_Hash_T::reset_interval"); - - // Make sure we are getting a valid , not an error - // returned by . - if (timer_id == -1) - return -1; - -#if defined (ACE_WIN64) - unsigned long const timer_offset = - static_cast (timer_id); - - ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); - - Hash_Token * const h = - reinterpret_cast *> (this->pointer_base_ + timer_offset); -#else - Hash_Token * const h = - reinterpret_cast *> (timer_id); - - // Grab the lock before accessing the table. We don't need to do so - // before this point since no members are accessed until now. - ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); -#endif /* ACE_WIN64 */ - - return this->table_[h->pos_]->reset_interval (h->orig_id_, - interval); -} - -// Locate and remove the single with a value of -// @a timer_id from the correct table timer queue. - -template -int -ACE_Timer_Hash_T::cancel (long timer_id, - const void **act, - int dont_call) -{ - ACE_TRACE ("ACE_Timer_Hash_T::cancel"); - - // Make sure we are getting a valid , not an error - // returned by . - if (timer_id == -1) - return 0; - -#if defined (ACE_WIN64) - unsigned long const timer_offset = - static_cast (timer_id); - - ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); - - Hash_Token * const h = - reinterpret_cast *> (this->pointer_base_ + timer_offset); -#else - Hash_Token * const h = - reinterpret_cast *> (timer_id); - - // Grab the lock before accessing the table. We don't need to do so - // before this point since no members are accessed until now. - ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); -#endif /* ACE_WIN64 */ - - int const result = this->table_[h->pos_]->cancel (h->orig_id_, - 0, - dont_call); - - if (result == 1) - { - // Call the close hooks. - int cookie = 0; - - // cancel_type() called once per . - this->upcall_functor ().cancel_type (*this, - h->type_, - dont_call, - cookie); - - // cancel_timer() called once per . - this->upcall_functor ().cancel_timer (*this, - h->type_, - dont_call, - cookie); - - if (h->pos_ == this->earliest_position_) - this->find_new_earliest (); - - if (act != 0) - *act = h->act_; - - // We could destruct Hash_Token explicitly but we better - // schedule it for destruction. In this case next - // token_list_.remove () will use it. - this->token_list_.add (h); - - --this->size_; - } - - return result; -} - -// Locate and remove all values of from the timer queue. - -template -int -ACE_Timer_Hash_T::cancel (const TYPE &type, - int dont_call) -{ - ACE_TRACE ("ACE_Timer_Hash_T::cancel"); - - size_t i; // loop variable. - - Hash_Token **timer_ids = 0; - size_t pos = 0; - - ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); - - ACE_NEW_RETURN (timer_ids, - Hash_Token *[this->size_], - -1); - - for (i = 0; - i < this->table_size_; - ++i) - { - ACE_Timer_Queue_Iterator_T, - ACE_Null_Mutex> &iter = - this->table_[i]->iter (); - - for (iter.first (); - !iter.isdone (); - iter.next ()) - if (iter.item ()->get_type () == type) - timer_ids[pos++] = - reinterpret_cast *> ( - const_cast (iter.item ()->get_act ())); - } - - if (pos > this->size_) - return -1; - - for (i = 0; i < pos; ++i) - { - int const result = - this->table_[timer_ids[i]->pos_]->cancel (timer_ids[i]->orig_id_, - 0, - dont_call); - ACE_ASSERT (result == 1); - ACE_UNUSED_ARG (result); - - // We could destruct Hash_Token explicitly but we better - // schedule it for destruction. - this->token_list_.add (timer_ids[i]); - - --this->size_; - } - - delete [] timer_ids; - - this->find_new_earliest (); - - // Call the close hooks. - int cookie = 0; - - // cancel_type() called once per . - this->upcall_functor ().cancel_type (*this, - type, - dont_call, - cookie); - - for (i = 0; - i < pos; - ++i) - { - // cancel_timer() called once per . - this->upcall_functor ().cancel_timer (*this, - type, - dont_call, - cookie); - } - - return static_cast (pos); -} - -// Removes the earliest node and finds the new earliest position - -template ACE_Timer_Node_T * -ACE_Timer_Hash_T::remove_first (void) -{ - if (this->is_empty ()) - return 0; - - ACE_Timer_Node_T *temp = - this->table_[this->earliest_position_]->remove_first (); - - this->find_new_earliest (); - - --this->size_; - - return temp; -} - -// Finds a new earliest position - -template void -ACE_Timer_Hash_T::find_new_earliest (void) -{ - for (size_t i = 0; i < this->table_size_; ++i) - if (!this->table_[i]->is_empty ()) - if (this->table_[this->earliest_position_]->is_empty () - || this->earliest_time () == ACE_Time_Value::zero - || this->table_[i]->earliest_time () <= this->earliest_time ()) - this->earliest_position_ = i; -} - -// Returns the earliest node without removing it - -template ACE_Timer_Node_T * -ACE_Timer_Hash_T::get_first (void) -{ - ACE_TRACE ("ACE_Timer_Hash_T::get_first"); - - if (this->is_empty ()) - return 0; - - return this->table_[this->earliest_position_]->get_first (); -} - -template void -ACE_Timer_Hash_T::free_node (ACE_Timer_Node_T *node) -{ - ACE_Timer_Queue_T::free_node (node); - - Hash_Token *h = - reinterpret_cast *> (const_cast (node->get_act ())); - this->token_list_.add (h); -} - -template int -ACE_Timer_Hash_T::dispatch_info_i (const ACE_Time_Value &cur_time, - ACE_Timer_Node_Dispatch_Info_T &info) -{ - int const result = - ACE_Timer_Queue_T::dispatch_info_i (cur_time, - info); - - if (result == 1) - { - Hash_Token *h = - reinterpret_cast *> (const_cast (info.act_)); - - info.act_ = h->act_; - } - - return result; -} - -// Dummy version of expire to get rid of warnings in Sun CC 4.2 - -template int -ACE_Timer_Hash_T::expire () -{ - return ACE_Timer_Queue_T::expire(); -} - -// Specialized expire for Timer Hash - -template int -ACE_Timer_Hash_T::expire (const ACE_Time_Value &cur_time) -{ - ACE_TRACE ("ACE_Timer_Hash_T::expire"); - - int number_of_timers_expired = 0; - - ACE_Timer_Node_T *expired = 0; - - ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); - - // Go through the table and expire anything that can be expired - - for (size_t i = 0; - i < this->table_size_; - ++i) - { - while (!this->table_[i]->is_empty () - && this->table_[i]->earliest_time () <= cur_time) - { - expired = this->table_[i]->remove_first (); - const void *act = expired->get_act (); - bool reclaim = true; - - Hash_Token *h = - reinterpret_cast *> (const_cast (act)); - - ACE_ASSERT (h->pos_ == i); - -#if 0 - ACE_DEBUG ((LM_DEBUG, "Hash::expire() expiring %d in slot %d where it's id is %d and token is %x\n", - expired->get_timer_value ().msec (), - h->pos_, - h->orig_id_, - h)); -#endif - - // Check if this is an interval timer. - if (expired->get_interval () > ACE_Time_Value::zero) - { - // Make sure that we skip past values that have already - // "expired". - this->recompute_next_abs_interval_time (expired, cur_time); - - // Since this is an interval timer, we need to - // reschedule it. - this->reschedule (expired); - reclaim = false; - } - else - { - this->free_node (expired); - } - - ACE_Timer_Node_Dispatch_Info_T info; - - // Get the dispatch info - expired->get_dispatch_info (info); - - info.act_ = h->act_; - - const void *upcall_act = 0; - - this->preinvoke (info, cur_time, upcall_act); - - this->upcall (info, cur_time); - - this->postinvoke (info, cur_time, upcall_act); - - if (reclaim) - { - --this->size_; - } - - ++number_of_timers_expired; - } - } - - if (number_of_timers_expired > 0) - this->find_new_earliest (); - - return number_of_timers_expired; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_TIMER_HASH_T_CPP */ diff --git a/externals/ace/Timer_Hash_T.h b/externals/ace/Timer_Hash_T.h deleted file mode 100644 index b04e7cfbcf3..00000000000 --- a/externals/ace/Timer_Hash_T.h +++ /dev/null @@ -1,342 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file Timer_Hash_T.h - * - * $Id: Timer_Hash_T.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Darrell Brunsch - */ -//============================================================================= - -#ifndef ACE_TIMER_HASH_T_H -#define ACE_TIMER_HASH_T_H -#include /**/ "ace/pre.h" - -#include "ace/Timer_Queue_T.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Free_List.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Forward declaration. -template -class ACE_Timer_Hash_T; -template -class Hash_Token; - -/** - * @class ACE_Timer_Hash_Upcall - * - * @brief Functor for Timer_Hash - * - * This class calls up to the Timer Hash's functor from the - * timer queues in the hash table - */ -template -class ACE_Timer_Hash_Upcall -{ -public: - typedef ACE_Timer_Queue_T, - ACE_Null_Mutex> - TIMER_QUEUE; - - /// Default constructor (creates an invalid object, but needs to be here - /// so timer queues using this functor can be constructed) - ACE_Timer_Hash_Upcall (void); - - /// Constructor that specifies a Timer_Hash to call up to - ACE_Timer_Hash_Upcall (ACE_Timer_Queue_T *timer_hash); - - /// This method is called when a timer is registered. - int registration (TIMER_QUEUE &timer_queue, - ACE_Event_Handler *handler, - const void *arg); - - /// This method is called before the timer expires. - int preinvoke (TIMER_QUEUE &timer_queue, - ACE_Event_Handler *handler, - const void *arg, - int recurring_timer, - const ACE_Time_Value &cur_time, - const void *&upcall_act); - - /// This method is called when the timer expires. - int timeout (TIMER_QUEUE &timer_queue, - ACE_Event_Handler *handler, - const void *arg, - int recurring_timer, - const ACE_Time_Value &cur_time); - - /// This method is called after the timer expires. - int postinvoke (TIMER_QUEUE &timer_queue, - ACE_Event_Handler *handler, - const void *arg, - int recurring_timer, - const ACE_Time_Value &cur_time, - const void *upcall_act); - - /// This method is called when a handler is cancelled - int cancel_type (TIMER_QUEUE &timer_queue, - ACE_Event_Handler *handler, - int dont_call, - int &requires_reference_counting); - - /// This method is called when a timer is cancelled - int cancel_timer (TIMER_QUEUE &timer_queue, - ACE_Event_Handler *handler, - int dont_call, - int requires_reference_counting); - - /// This method is called when the timer queue is destroyed and - /// the timer is still contained in it - int deletion (TIMER_QUEUE &timer_queue, - ACE_Event_Handler *handler, - const void *arg); - -private: - /// Timer Queue to do the calling up to - ACE_Timer_Queue_T *timer_hash_; - - // = Don't allow these operations for now. - ACE_UNIMPLEMENTED_FUNC (ACE_Timer_Hash_Upcall (const ACE_Timer_Hash_Upcall &)) - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Timer_Hash_Upcall &)) -}; - -/** - * @class ACE_Timer_Hash_Iterator_T - * - * @brief Iterates over an ACE_Timer_Hash_T. - * - * This is a generic iterator that can be used to visit every - * node of a timer queue. Be aware that it doesn't transverse - * in the order of timeout values. - */ -template -class ACE_Timer_Hash_Iterator_T : public ACE_Timer_Queue_Iterator_T -{ -public: - /// Constructor. - ACE_Timer_Hash_Iterator_T (ACE_Timer_Hash_T &); - - /// Positions the iterator at the earliest node in the Timer Queue - virtual void first (void); - - /// Positions the iterator at the next node in the Timer Queue - virtual void next (void); - - /// Returns true when there are no more nodes in the sequence - virtual bool isdone (void) const; - - /// Returns the node at the current position in the sequence - virtual ACE_Timer_Node_T *item (void); - -protected: - /// Pointer to the ACE_Timer_Hash that we are iterating over. - ACE_Timer_Hash_T &timer_hash_; - - /// Current position in 's table - size_t position_; - - /// Current iterator used on 's bucket - ACE_Timer_Queue_Iterator_T, ACE_Null_Mutex> *iter_; -}; - -/** - * @class ACE_Timer_Hash_T - * - * @brief Provides a hash table of BUCKETs as an implementation for - * a timer queue. - * - * This implementation uses a hash table of BUCKETs. The hash - * is based on the time_value of the event. Unlike other Timer - * Queues, ACE_Timer_Hash does not expire events in order. - */ -template -class ACE_Timer_Hash_T : public ACE_Timer_Queue_T -{ -public: - /// Type of iterator - typedef ACE_Timer_Hash_Iterator_T - HASH_ITERATOR; - - /// Iterator is a friend - friend class ACE_Timer_Hash_Iterator_T; - - /// Type inherited from - typedef ACE_Timer_Queue_T INHERITED; - - // = Initialization and termination methods. - /** - * Default constructor. @a table_size determines the size of the - * hash table. @a upcall_functor is the instance of the FUNCTOR - * to be used by the buckets. If @a upcall_functor is 0, a default - * FUNCTOR will be created. - */ - ACE_Timer_Hash_T (size_t table_size, - FUNCTOR *upcall_functor = 0, - ACE_Free_List > *freelist = 0); - - /** - * Default constructor. @a upcall_functor is the instance of the - * FUNCTOR to be used by the queue. If @a upcall_functor is 0, Timer - * Hash will create a default FUNCTOR. @a freelist the freelist of - * timer nodes. If 0, then a default freelist will be created. The default - * size will be ACE_DEFAULT_TIMERS and there will be no preallocation. - */ - ACE_Timer_Hash_T (FUNCTOR *upcall_functor = 0, ACE_Free_List > *freelist = 0); - - /// Destructor - virtual ~ACE_Timer_Hash_T (void); - - /// True if queue is empty, else false. - virtual bool is_empty (void) const; - - /// Returns the time of the earlier node in the . - /// Must be called on a non-empty queue. - virtual const ACE_Time_Value &earliest_time (void) const; - - /** - * Resets the interval of the timer represented by @a timer_id to - * @a interval, which is specified in relative time to the current - * . If @a interval is equal to - * ACE_Time_Value::zero, the timer will become a non-rescheduling - * timer. Returns 0 if successful, -1 if not. - */ - virtual int reset_interval (long timer_id, - const ACE_Time_Value &interval); - - /** - * Cancel all timer associated with @a type. If is 0 - * then the will be invoked. Returns number of timers - * cancelled. If any valid timer is not cancelled before destruction - * of this instance of ACE_Timer_Hash_T then user will get a memory - * leak. - */ - virtual int cancel (const TYPE &type, - int dont_call_handle_close = 1); - - /** - * Cancel the single timer that matches the @a timer_id value (which - * was returned from the method). If act is non-NULL - * then it will be set to point to the ``magic cookie'' argument - * passed in when the timer was registered. This makes it possible - * to free up the memory and avoid memory leaks. If is - * 0 then the will be invoked. Returns 1 if cancellation - * succeeded and 0 if the @a timer_id wasn't found. If any valid - * timer is not cancelled before destruction of this instance of - * ACE_Timer_Hash_T then user will get a memory leak. - */ - virtual int cancel (long timer_id, - const void **act = 0, - int dont_call_handle_close = 1); - - /** - * Run the for all timers whose values are <= - * . Also accounts for . Returns - * the number of timers canceled. - */ - virtual int expire (void); - - /** - * Run the for all timers whose values are <= @a current_time. - * This does not account for . Returns the number of - * timers canceled. - */ - virtual int expire (const ACE_Time_Value ¤t_time); - - /// Returns a pointer to this ACE_Timer_Queue's iterator. - virtual ACE_Timer_Queue_Iterator_T &iter (void); - - /// Removes the earliest node from the queue and returns it - virtual ACE_Timer_Node_T *remove_first (void); - - /// Dump the state of an object. - virtual void dump (void) const; - - /// Reads the earliest node from the queue and returns it. - virtual ACE_Timer_Node_T *get_first (void); - -protected: - /// Factory method that frees a previously allocated node. - virtual void free_node (ACE_Timer_Node_T *); - -private: - - /** - * Schedule @a type that will expire at @a future_time, - * which is specified in absolute time. If it expires then @a act is - * passed in as the value to the . If @a interval is != to - * ACE_Time_Value::zero then it is used to reschedule the @a type - * automatically, using relative time to the current . - * This method returns a that is a pointer to a token - * which stores information about the event. This can be - * used to cancel the timer before it expires. Returns -1 on - * failure. - */ - virtual long schedule_i (const TYPE &type, - const void *act, - const ACE_Time_Value &future_time, - const ACE_Time_Value &interval); - - /// Non-locking version of dispatch_info () - virtual int dispatch_info_i (const ACE_Time_Value ¤t_time, - ACE_Timer_Node_Dispatch_Info_T &info); - - /// Reschedule an "interval" ACE_Timer_Node. - virtual void reschedule (ACE_Timer_Node_T *); - - /// Finds the earliest node - void find_new_earliest (void); - - /// Keeps track of the size of the queue - size_t size_; - - /// Table of BUCKETS - BUCKET **table_; - - /// Keeps track of the size of table_ - size_t table_size_; - - /// Functor used for the table's timer queues - ACE_Timer_Hash_Upcall table_functor_; - - /// Index to the position with the earliest entry - size_t earliest_position_; - - /// Iterator used to expire timers. - HASH_ITERATOR *iterator_; - -#if defined (ACE_WIN64) - // Part of a hack... see comments in schedule(). - // This is, essentially, the upper 32 bits of a 64-bit pointer on Win64. - ptrdiff_t pointer_base_; -#endif - - /// Hash_Token is usually allocated in schedule but its - /// deallocation is problematic and token_list_ helps with this. - ACE_Locked_Free_List, ACE_Null_Mutex> token_list_; - - // = Don't allow these operations for now. - ACE_UNIMPLEMENTED_FUNC (ACE_Timer_Hash_T (const ACE_Timer_Hash_T &)) - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Timer_Hash_T &)) -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Timer_Hash_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Timer_Hash_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" -#endif /* ACE_TIMER_HASH_T_H */ diff --git a/externals/ace/Timer_Heap.h b/externals/ace/Timer_Heap.h deleted file mode 100644 index 7dec5ec22b4..00000000000 --- a/externals/ace/Timer_Heap.h +++ /dev/null @@ -1,41 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file Timer_Heap.h - * - * $Id: Timer_Heap.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_TIMER_HEAP_H -#define ACE_TIMER_HEAP_H -#include /**/ "ace/pre.h" - -#include "ace/Timer_Heap_T.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// The following typedefs are here for ease of use and backward -// compatibility. - -typedef ACE_Timer_Heap_T, - ACE_SYNCH_RECURSIVE_MUTEX> - ACE_Timer_Heap; - -typedef ACE_Timer_Heap_Iterator_T, - ACE_SYNCH_RECURSIVE_MUTEX> - ACE_Timer_Heap_Iterator; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" -#endif /* ACE_TIMER_HEAP_H */ diff --git a/externals/ace/Timer_Heap_T.cpp b/externals/ace/Timer_Heap_T.cpp deleted file mode 100644 index 75ec9ef70fc..00000000000 --- a/externals/ace/Timer_Heap_T.cpp +++ /dev/null @@ -1,889 +0,0 @@ -// $Id: Timer_Heap_T.cpp 84962 2009-03-24 15:16:25Z johnnyw $ - -#ifndef ACE_TIMER_HEAP_T_CPP -#define ACE_TIMER_HEAP_T_CPP - -#include "ace/Timer_Heap_T.h" -#include "ace/Log_Msg.h" -#include "ace/Guard_T.h" -#include "ace/OS_NS_errno.h" -#include "ace/OS_NS_string.h" -#include "ace/Numeric_Limits.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -/* -** The ACE_Timer_Heap::max_size_ and array loops, checks, etc. are all size_t. -** The timer IDs are long, and since they are indices into the heap, we need -** to be sure that the timer heap size can fit in a long. Hence, when size -** is (re)set, limit it to the maximum long value. We use the C++ standard -** limits if available. -*/ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Define some simple inlined functions to clarify the code. -inline size_t -ACE_HEAP_PARENT (size_t X) -{ - return (X == 0 ? 0 : ((X - 1) / 2)); -} - -inline size_t -ACE_HEAP_LCHILD (size_t X) -{ - return X + X + 1; -} - -// Constructor that takes in an to iterate over. - -template -ACE_Timer_Heap_Iterator_T::ACE_Timer_Heap_Iterator_T ( - ACE_Timer_Heap_T &heap) - : timer_heap_ (heap) -{ - ACE_TRACE ("ACE_Timer_Heap_Iterator_T::ACE_Timer_Heap_Iterator"); - this->first (); -} - -template -ACE_Timer_Heap_Iterator_T::~ACE_Timer_Heap_Iterator_T (void) -{ -} - -// Positions the iterator at the first node in the heap array - -template -void -ACE_Timer_Heap_Iterator_T::first (void) -{ - this->position_ = 0; -} - -// Positions the iterator at the next node in the heap array - -template -void -ACE_Timer_Heap_Iterator_T::next (void) -{ - if (this->position_ != this->timer_heap_.cur_size_) - ++this->position_; -} - -// Returns true the is at the end of the heap array - -template bool -ACE_Timer_Heap_Iterator_T::isdone (void) const -{ - return this->position_ == this->timer_heap_.cur_size_; -} - -// Returns the node at the current position in the heap or 0 if at the end - -template ACE_Timer_Node_T * -ACE_Timer_Heap_Iterator_T::item (void) -{ - if (this->position_ != this->timer_heap_.cur_size_) - return this->timer_heap_.heap_[this->position_]; - return 0; -} - -// Constructor -// Note that timer_ids_curr_ and timer_ids_min_free_ both start at 0. -// Since timer IDs are assigned by first incrementing the timer_ids_curr_ -// value, the first ID assigned will be 1 (just as in the previous design). -// When it's time to wrap, the next ID given out will be 0. -template -ACE_Timer_Heap_T::ACE_Timer_Heap_T ( - size_t size, - bool preallocated, - FUNCTOR *upcall_functor, - ACE_Free_List > *freelist) - : ACE_Timer_Queue_T (upcall_functor, freelist), - max_size_ (size), - cur_size_ (0), - cur_limbo_ (0), - timer_ids_curr_ (0), - timer_ids_min_free_ (0), - preallocated_nodes_ (0), - preallocated_nodes_freelist_ (0) -{ - ACE_TRACE ("ACE_Timer_Heap_T::ACE_Timer_Heap_T"); - - // Possibly reduce size to fit in a long. - if (size > static_cast (ACE_Numeric_Limits::max ())) - { - size = static_cast (ACE_Numeric_Limits::max ()); - this->max_size_ = size; - } - - // Create the heap array. - ACE_NEW (this->heap_, - ACE_Timer_Node_T *[size]); - - // Create the parallel - ACE_NEW (this->timer_ids_, - ssize_t[size]); - - // Initialize the "freelist," which uses negative values to - // distinguish freelist elements from "pointers" into the - // array. - for (size_t i = 0; i < size; ++i) - this->timer_ids_[i] = -1; - - if (preallocated) - { - ACE_NEW (this->preallocated_nodes_, - ACE_Timer_Node_T[size]); - - // Add allocated array to set of such arrays for deletion on - // cleanup. - this->preallocated_node_set_.insert (this->preallocated_nodes_); - - // Form the freelist by linking the next_ pointers together. - for (size_t j = 1; j < size; ++j) - this->preallocated_nodes_[j - 1].set_next (&this->preallocated_nodes_[j]); - - // NULL-terminate the freelist. - this->preallocated_nodes_[size - 1].set_next (0); - - // Assign the freelist pointer to the front of the list. - this->preallocated_nodes_freelist_ = - &this->preallocated_nodes_[0]; - } - - ACE_NEW (iterator_, - HEAP_ITERATOR (*this)); -} - -// Note that timer_ids_curr_ and timer_ids_min_free_ both start at 0. -// Since timer IDs are assigned by first incrementing the timer_ids_curr_ -// value, the first ID assigned will be 1 (just as in the previous design). -// When it's time to wrap, the next ID given out will be 0. -template -ACE_Timer_Heap_T::ACE_Timer_Heap_T ( - FUNCTOR *upcall_functor, - ACE_Free_List > *freelist) - : ACE_Timer_Queue_T (upcall_functor, freelist), - max_size_ (ACE_DEFAULT_TIMERS), - cur_size_ (0), - cur_limbo_ (0), - timer_ids_curr_ (0), - timer_ids_min_free_ (0), - preallocated_nodes_ (0), - preallocated_nodes_freelist_ (0) -{ - ACE_TRACE ("ACE_Timer_Heap_T::ACE_Timer_Heap_T"); - - // Possibly reduce size to fit in a long. - if (this->max_size_ > static_cast (ACE_Numeric_Limits::max ())) - this->max_size_ = static_cast (ACE_Numeric_Limits::max ()); - - // Create the heap array. - ACE_NEW (this->heap_, - ACE_Timer_Node_T *[this->max_size_]); - - // Create the parallel array. - ACE_NEW (this->timer_ids_, - ssize_t[this->max_size_]); - - // Initialize the "freelist," which uses negative values to - // distinguish freelist elements from "pointers" into the - // array. - for (size_t i = 0; i < this->max_size_; ++i) - this->timer_ids_[i] = -1; - - ACE_NEW (iterator_, - HEAP_ITERATOR (*this)); -} - -template -ACE_Timer_Heap_T::~ACE_Timer_Heap_T (void) -{ - ACE_TRACE ("ACE_Timer_Heap_T::~ACE_Timer_Heap_T"); - - delete iterator_; - - size_t current_size = - this->cur_size_; - - // Clean up all the nodes still in the queue - for (size_t i = 0; i < current_size; ++i) - { - // Grab the event_handler and act, then delete the node before calling - // back to the handler. Prevents a handler from trying to cancel_timer() - // inside handle_close(), ripping the current timer node out from - // under us. - TYPE eh = this->heap_[i]->get_type (); - const void *act = this->heap_[i]->get_act (); - this->free_node (this->heap_[i]); - this->upcall_functor ().deletion (*this, eh, act); - } - - delete [] this->heap_; - delete [] this->timer_ids_; - - // clean up any preallocated timer nodes - if (preallocated_nodes_ != 0) - { - ACE_Unbounded_Set_Iterator *> - set_iterator (this->preallocated_node_set_); - - for (ACE_Timer_Node_T **entry = 0; - set_iterator.next (entry) !=0; - set_iterator.advance ()) - delete [] *entry; - } -} - -template -long -ACE_Timer_Heap_T::pop_freelist (void) -{ - ACE_TRACE ("ACE_Timer_Heap_T::pop_freelist"); - - // Scan for a free timer ID. Note that since this function is called - // _after_ the check for a full timer heap, we are guaranteed to find - // a free ID, even if we need to wrap around and start reusing freed IDs. - // On entry, the curr_ index is at the previous ID given out; start - // up where we left off last time. - // NOTE - a timer_ids_ slot with -2 is out of the heap, but not freed. - // It must be either freed (free_node) or rescheduled (reschedule). - ++this->timer_ids_curr_; - while (this->timer_ids_curr_ < this->max_size_ && - (this->timer_ids_[this->timer_ids_curr_] >= 0 || - this->timer_ids_[this->timer_ids_curr_] == -2 )) - ++this->timer_ids_curr_; - if (this->timer_ids_curr_ == this->max_size_) - { - ACE_ASSERT (this->timer_ids_min_free_ < this->max_size_); - this->timer_ids_curr_ = this->timer_ids_min_free_; - // We restarted the free search at min. Since min won't be - // free anymore, and curr_ will just keep marching up the list - // on each successive need for an ID, reset min_free_ to the - // size of the list until an ID is freed that curr_ has already - // gone past (see push_freelist). - this->timer_ids_min_free_ = this->max_size_; - } - - return static_cast (this->timer_ids_curr_); -} - -template -void -ACE_Timer_Heap_T::push_freelist (long old_id) -{ - ACE_TRACE ("ACE_Timer_Heap_T::push_freelist"); - - // Since this ID has already been checked by one of the public - // functions, it's safe to cast it here. - size_t oldid = static_cast (old_id); - - // The freelist values in the are negative, so set the - // freed entry back to 'free'. If this is the new lowest value free - // timer ID that curr_ won't see on it's normal march through the list, - // remember it. - ACE_ASSERT (this->timer_ids_[oldid] >= 0 || this->timer_ids_[oldid] == -2); - if (this->timer_ids_[oldid] == -2) - --this->cur_limbo_; - else - --this->cur_size_; - this->timer_ids_[oldid] = -1; - if (oldid < this->timer_ids_min_free_ && oldid <= this->timer_ids_curr_) - this->timer_ids_min_free_ = oldid; - return; -} - -template -long -ACE_Timer_Heap_T::timer_id (void) -{ - ACE_TRACE ("ACE_Timer_Heap_T::timer_id"); - - // Return the next item off the freelist and use it as the timer id. - return this->pop_freelist (); -} - -// Checks if queue is empty. - -template -bool -ACE_Timer_Heap_T::is_empty (void) const -{ - ACE_TRACE ("ACE_Timer_Heap_T::is_empty"); - return this->cur_size_ == 0; -} - -template -ACE_Timer_Queue_Iterator_T & -ACE_Timer_Heap_T::iter (void) -{ - this->iterator_->first (); - return *this->iterator_; -} - -// Returns earliest time in a non-empty queue. - -template const ACE_Time_Value & -ACE_Timer_Heap_T::earliest_time (void) const -{ - ACE_TRACE ("ACE_Timer_Heap_T::earliest_time"); - return this->heap_[0]->get_timer_value (); -} - -template -void -ACE_Timer_Heap_T::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Timer_Heap_T::dump"); - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nmax_size_ = %d"), this->max_size_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ncur_size_ = %d"), this->cur_size_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ncur_limbo_= %d"), this->cur_limbo_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nids_curr_ = %d"), - this->timer_ids_curr_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nmin_free_ = %d"), - this->timer_ids_min_free_)); - - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nheap_ =\n"))); - - for (size_t i = 0; i < this->cur_size_; ++i) - { - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("%d\n"), - i)); - this->heap_[i]->dump (); - } - - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ntimer_ids_ =\n"))); - - for (size_t j = 0; j < this->max_size_; ++j) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("%d\t%d\n"), - j, - this->timer_ids_[j])); - - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -template -void -ACE_Timer_Heap_T::copy ( - size_t slot, - ACE_Timer_Node_T *moved_node) -{ - // Insert into its new location in the heap. - this->heap_[slot] = moved_node; - - ACE_ASSERT (moved_node->get_timer_id () >= 0 - && moved_node->get_timer_id () < (int) this->max_size_); - - // Update the corresponding slot in the parallel array. - this->timer_ids_[moved_node->get_timer_id ()] = static_cast (slot); -} - -// Remove the slot'th timer node from the heap, but do not reclaim its -// timer ID or change the size of this timer heap object. The caller of -// this function must call either free_node (to reclaim the timer ID -// and the timer node memory, as well as decrement the size of the queue) -// or reschedule (to reinsert the node in the heap at a new time). -template -ACE_Timer_Node_T * -ACE_Timer_Heap_T::remove (size_t slot) -{ - ACE_Timer_Node_T *removed_node = - this->heap_[slot]; - - // NOTE - the cur_size_ is being decremented since the queue has one - // less active timer in it. However, this ACE_Timer_Node is not being - // freed, and there is still a place for it in timer_ids_ (the timer ID - // is not being relinquished). The node can still be rescheduled, or - // it can be freed via free_node. - --this->cur_size_; - - // Only try to reheapify if we're not deleting the last entry. - - if (slot < this->cur_size_) - { - ACE_Timer_Node_T *moved_node = - this->heap_[this->cur_size_]; - - // Move the end node to the location being removed and update - // the corresponding slot in the parallel array. - this->copy (slot, moved_node); - - // If the time_value_> is great than or equal its - // parent it needs be moved down the heap. - size_t parent = ACE_HEAP_PARENT (slot); - - if (moved_node->get_timer_value () - >= this->heap_[parent]->get_timer_value ()) - this->reheap_down (moved_node, - slot, - ACE_HEAP_LCHILD (slot)); - else - this->reheap_up (moved_node, - slot, - parent); - } - - this->timer_ids_[removed_node->get_timer_id ()] = -2; - ++this->cur_limbo_; - return removed_node; -} - -template void -ACE_Timer_Heap_T::reheap_down ( - ACE_Timer_Node_T *moved_node, - size_t slot, - size_t child) -{ - // Restore the heap property after a deletion. - - while (child < this->cur_size_) - { - // Choose the smaller of the two children. - if (child + 1 < this->cur_size_ - && this->heap_[child + 1]->get_timer_value () - < this->heap_[child]->get_timer_value ()) - child++; - - // Perform a if the child has a larger timeout value than - // the . - if (this->heap_[child]->get_timer_value () - < moved_node->get_timer_value ()) - { - this->copy (slot, - this->heap_[child]); - slot = child; - child = ACE_HEAP_LCHILD (child); - } - else - // We've found our location in the heap. - break; - } - - this->copy (slot, moved_node); -} - -template -void -ACE_Timer_Heap_T::reheap_up ( - ACE_Timer_Node_T *moved_node, - size_t slot, - size_t parent) -{ - // Restore the heap property after an insertion. - - while (slot > 0) - { - // If the parent node is greater than the we need - // to copy it down. - if (moved_node->get_timer_value () - < this->heap_[parent]->get_timer_value ()) - { - this->copy (slot, this->heap_[parent]); - slot = parent; - parent = ACE_HEAP_PARENT (slot); - } - else - break; - } - - // Insert the new node into its proper resting place in the heap and - // update the corresponding slot in the parallel array. - this->copy (slot, - moved_node); -} - -template -void -ACE_Timer_Heap_T::insert ( - ACE_Timer_Node_T *new_node) -{ - if (this->cur_size_ + this->cur_limbo_ + 2 >= this->max_size_) - this->grow_heap (); - - this->reheap_up (new_node, - this->cur_size_, - ACE_HEAP_PARENT (this->cur_size_)); - this->cur_size_++; -} - -template -void -ACE_Timer_Heap_T::grow_heap (void) -{ - // All the containers will double in size from max_size_. - size_t new_size = this->max_size_ * 2; - -#if 0 - // Yikes - there's no way to flag a failure of going out of range of - // a 'long' - this is a problem that should be addressed at some point. - if (new_size > ACE_Numeric_Limits::max ()) - new_size = ACE_Numeric_Limits::max (); - - if (new_size <= this->max_size_) // We are already at the limit - { - errno = ENOMEM; - return -1; - } -#endif /* 0 */ - - // First grow the heap itself. - - ACE_Timer_Node_T **new_heap = 0; - - ACE_NEW (new_heap, - ACE_Timer_Node_T *[new_size]); - - ACE_OS::memcpy (new_heap, - this->heap_, - this->max_size_ * sizeof *new_heap); - delete [] this->heap_; - this->heap_ = new_heap; - - // Grow the array of timer ids. - - ssize_t *new_timer_ids = 0; - - ACE_NEW (new_timer_ids, - ssize_t[new_size]); - - ACE_OS::memcpy (new_timer_ids, - this->timer_ids_, - this->max_size_ * sizeof (ssize_t)); - - delete [] timer_ids_; - this->timer_ids_ = new_timer_ids; - - // And add the new elements to the end of the "freelist". - for (size_t i = this->max_size_; i < new_size; ++i) - this->timer_ids_[i] = -(static_cast (i) + 1); - - // Grow the preallocation array (if using preallocation) - if (this->preallocated_nodes_ != 0) - { - // Create a new array with max_size elements to link in to - // existing list. - ACE_NEW (this->preallocated_nodes_, - ACE_Timer_Node_T[this->max_size_]); - - // Add it to the set for later deletion - this->preallocated_node_set_.insert (this->preallocated_nodes_); - - // Link new nodes together (as for original list). - for (size_t k = 1; k < this->max_size_; ++k) - this->preallocated_nodes_[k - 1].set_next (&this->preallocated_nodes_[k]); - - // NULL-terminate the new list. - this->preallocated_nodes_[this->max_size_ - 1].set_next (0); - - // Link new array to the end of the existling list. - if (this->preallocated_nodes_freelist_ == 0) - this->preallocated_nodes_freelist_ = - &preallocated_nodes_[0]; - else - { - ACE_Timer_Node_T *previous = - this->preallocated_nodes_freelist_; - - for (ACE_Timer_Node_T *current = this->preallocated_nodes_freelist_->get_next (); - current != 0; - current = current->get_next ()) - previous = current; - - previous->set_next (&this->preallocated_nodes_[0]); - } - } - - this->max_size_ = new_size; - // Force rescan of list from beginning for a free slot (I think...) - // This fixed Bugzilla #2447. - this->timer_ids_min_free_ = this->max_size_; -} - -// Reschedule a periodic timer. This function must be called with the -// mutex lock held. - -template -void -ACE_Timer_Heap_T::reschedule ( - ACE_Timer_Node_T *expired) -{ - ACE_TRACE ("ACE_Timer_Heap_T::reschedule"); - - // If we are rescheduling, then the most recent call was to - // remove_first (). That called remove () to remove the node from the - // heap, but did not free the timer ID. The ACE_Timer_Node still has - // its assigned ID - just needs to be inserted at the new proper - // place, and the heap restored properly. - if (this->timer_ids_[expired->get_timer_id ()] == -2) - --this->cur_limbo_; - this->insert (expired); -} - -template -ACE_Timer_Node_T * -ACE_Timer_Heap_T::alloc_node (void) -{ - ACE_Timer_Node_T *temp = 0; - - // Only allocate a node if we are *not* using the preallocated heap. - if (this->preallocated_nodes_ == 0) - ACE_NEW_RETURN (temp, - ACE_Timer_Node_T, - 0); - else - { - // check to see if the heap needs to grow - if (this->preallocated_nodes_freelist_ == 0) - this->grow_heap (); - - temp = this->preallocated_nodes_freelist_; - - // Remove the first element from the freelist. - this->preallocated_nodes_freelist_ = - this->preallocated_nodes_freelist_->get_next (); - } - return temp; -} - -template -void -ACE_Timer_Heap_T::free_node ( - ACE_Timer_Node_T *node) -{ - // Return this timer id to the freelist. - this->push_freelist (node->get_timer_id ()); - - // Only free up a node if we are *not* using the preallocated heap. - if (this->preallocated_nodes_ == 0) - delete node; - else - { - node->set_next (this->preallocated_nodes_freelist_); - this->preallocated_nodes_freelist_ = node; - } -} - -// Insert a new timer that expires at time future_time; if interval is -// > 0, the handler will be reinvoked periodically. - -template -long -ACE_Timer_Heap_T::schedule_i ( - const TYPE &type, - const void *act, - const ACE_Time_Value &future_time, - const ACE_Time_Value &interval) -{ - ACE_TRACE ("ACE_Timer_Heap_T::schedule_i"); - - if ((this->cur_size_ + this->cur_limbo_) < this->max_size_) - { - // Obtain the next unique sequence number. - long const timer_id = this->timer_id (); - - // Obtain the memory to the new node. - ACE_Timer_Node_T *temp = 0; - - ACE_ALLOCATOR_RETURN (temp, - this->alloc_node (), - -1); - temp->set (type, - act, - future_time, - interval, - 0, - timer_id); - - this->insert (temp); - return timer_id; - } - else - return -1; -} - -// Locate and remove the single timer with a value of @a timer_id from -// the timer queue. - -template -int -ACE_Timer_Heap_T::cancel (long timer_id, - const void **act, - int dont_call) -{ - ACE_TRACE ("ACE_Timer_Heap_T::cancel"); - ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); - - // Locate the ACE_Timer_Node that corresponds to the timer_id. - - // Check to see if the timer_id is out of range - if (timer_id < 0 - || (size_t) timer_id > this->max_size_) - return 0; - - ssize_t timer_node_slot = this->timer_ids_[timer_id]; - - // Check to see if timer_id is still valid. - if (timer_node_slot < 0) - return 0; - - if (timer_id != this->heap_[timer_node_slot]->get_timer_id ()) - { - ACE_ASSERT (timer_id == this->heap_[timer_node_slot]->get_timer_id ()); - return 0; - } - else - { - ACE_Timer_Node_T *temp = - this->remove (timer_node_slot); - - // Call the close hooks. - int cookie = 0; - - // cancel_type() called once per . - this->upcall_functor ().cancel_type (*this, - temp->get_type (), - dont_call, - cookie); - - // cancel_timer() called once per . - this->upcall_functor ().cancel_timer (*this, - temp->get_type (), - dont_call, - cookie); - - if (act != 0) - *act = temp->get_act (); - - this->free_node (temp); - return 1; - } -} - -// Locate and update the inteval on the timer_id - -template -int -ACE_Timer_Heap_T::reset_interval (long timer_id, - const ACE_Time_Value &interval) -{ - ACE_TRACE ("ACE_Timer_Heap_T::reset_interval"); - ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); - - // Locate the ACE_Timer_Node that corresponds to the timer_id. - - // Check to see if the timer_id is out of range - if (timer_id < 0 - || (size_t) timer_id > this->max_size_) - return -1; - - ssize_t timer_node_slot = this->timer_ids_[timer_id]; - - // Check to see if timer_id is still valid. - if (timer_node_slot < 0) - return -1; - - if (timer_id != this->heap_[timer_node_slot]->get_timer_id ()) - { - ACE_ASSERT (timer_id == this->heap_[timer_node_slot]->get_timer_id ()); - return -1; - } - else - { - // Reset the timer interval - this->heap_[timer_node_slot]->set_interval (interval); - return 0; - } -} - -// Locate and remove all values of @a type from the timer queue. - -template -int -ACE_Timer_Heap_T::cancel (const TYPE &type, - int dont_call) -{ - ACE_TRACE ("ACE_Timer_Heap_T::cancel"); - - ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); - - int number_of_cancellations = 0; - - // Try to locate the ACE_Timer_Node that matches the timer_id. - - for (size_t i = 0; i < this->cur_size_; ) - { - if (this->heap_[i]->get_type () == type) - { - ACE_Timer_Node_T *temp = this->remove (i); - - ++number_of_cancellations; - - this->free_node (temp); - - // We reset to zero so that we don't miss checking any nodes - // if a reheapify occurs when a node is removed. There - // may be a better fix than this, however. - i = 0; - } - else - ++i; - } - - // Call the close hooks. - int cookie = 0; - - // cancel_type() called once per . - this->upcall_functor ().cancel_type (*this, - type, - dont_call, - cookie); - - for (int j = 0; - j < number_of_cancellations; - ++j) - { - // cancel_timer() called once per . - this->upcall_functor ().cancel_timer (*this, - type, - dont_call, - cookie); - } - - return number_of_cancellations; -} - -// Returns the earliest node or returns 0 if the heap is empty. - -template -ACE_Timer_Node_T * -ACE_Timer_Heap_T::remove_first (void) -{ - ACE_TRACE ("ACE_Timer_Heap_T::remove_first"); - - if (this->cur_size_ == 0) - return 0; - - return this->remove (0); -} - -template -ACE_Timer_Node_T * -ACE_Timer_Heap_T::get_first (void) -{ - ACE_TRACE ("ACE_Timer_Heap_T::get_first"); - - return this->cur_size_ == 0 ? 0 : this->heap_[0]; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_TIMER_HEAP_T_CPP */ diff --git a/externals/ace/Timer_Heap_T.h b/externals/ace/Timer_Heap_T.h deleted file mode 100644 index d6a6221aeed..00000000000 --- a/externals/ace/Timer_Heap_T.h +++ /dev/null @@ -1,338 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Timer_Heap_T.h - * - * $Id: Timer_Heap_T.h 84619 2009-02-26 12:26:16Z johnnyw $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_TIMER_HEAP_T_H -#define ACE_TIMER_HEAP_T_H -#include /**/ "ace/pre.h" - -#include "ace/Timer_Queue_T.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Free_List.h" -#include "ace/Unbounded_Set.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Forward declaration -template -class ACE_Timer_Heap_T; - -/** - * @class ACE_Timer_Heap_Iterator_T - * - * @brief Iterates over an ACE_Timer_Heap_T. - * - * This is a generic iterator that can be used to visit every - * node of a timer queue. Be aware that it doesn't transverse - * in the order of timeout values. - */ -template -class ACE_Timer_Heap_Iterator_T : public ACE_Timer_Queue_Iterator_T -{ -public: - /// Constructor. - ACE_Timer_Heap_Iterator_T (ACE_Timer_Heap_T &); - - /// Destructor. - ~ACE_Timer_Heap_Iterator_T (void); - - /// Positions the iterator at the earliest node in the Timer Queue - virtual void first (void); - - /// Positions the iterator at the next node in the Timer Queue - virtual void next (void); - - /// Returns true when there are no more nodes in the sequence - virtual bool isdone (void) const; - - /// Returns the node at the current position in the sequence - virtual ACE_Timer_Node_T *item (void); - -protected: - /// Pointer to the ACE_Timer_Heap that we are iterating over. - ACE_Timer_Heap_T &timer_heap_; - - /// Position in the array where the iterator is at - size_t position_; -}; - -/** - * @class ACE_Timer_Heap_T - * - * @brief Provides a very fast and predictable timer implementation. - * - * This implementation uses a heap-based callout queue of - * absolute times. Therefore, in the average and worst case, - * scheduling, canceling, and expiring timers is O(log N) (where - * N is the total number of timers). In addition, we can also - * preallocate as many @c ACE_Timer_Node objects as there are slots - * in the heap. This allows us to completely remove the need for - * dynamic memory allocation, which is important for real-time - * systems. - */ -template -class ACE_Timer_Heap_T : public ACE_Timer_Queue_T -{ -public: - typedef ACE_Timer_Heap_Iterator_T HEAP_ITERATOR; - friend class ACE_Timer_Heap_Iterator_T; - - typedef ACE_Timer_Queue_T INHERITED; - - // = Initialization and termination methods. - /** - * The Constructor creates a heap with specified number of elements. - * This can also take in a upcall functor and freelist (if 0, then - * defaults will be created). - * - * @param size The maximum number of timers that can be - * inserted into the new object. - * @param preallocated Default false, true then all the memory - * for the @c ACE_Timer_Node objects will be pre-allocated. This saves - * time and is more predictable (though it requires more space). - * Otherwise, timer nodes are allocated as needed. - * @param freelist is the freelist of timer nodes. - * @param upcall_functor If 0 Timer Heap will create a default FUNCTOR. - */ - ACE_Timer_Heap_T (size_t size, - bool preallocated = false, - FUNCTOR *upcall_functor = 0, - ACE_Free_List > *freelist = 0); - - /** - * Default constructor. @c upcall_functor is the instance of the - * FUNCTOR to be used by the queue. If @c upcall_functor is 0, Timer - * Heap will create a default FUNCTOR. @c freelist is the freelist of - * timer nodes. If 0, then a default freelist will be created. The default - * size will be ACE_DEFAULT_TIMERS and there will be no preallocation. - */ - ACE_Timer_Heap_T (FUNCTOR *upcall_functor = 0, - ACE_Free_List > *freelist = 0); - - /// Destructor. - virtual ~ACE_Timer_Heap_T (void); - - /// True if heap is empty, else false. - virtual bool is_empty (void) const; - - /// Returns the time of the earliest node in the Timer_Queue. - /// Must be called on a non-empty queue. - virtual const ACE_Time_Value &earliest_time (void) const; - - /** - * Resets the interval of the timer represented by @a timer_id to - * @a interval, which is specified in relative time to the current - * . If @a interval is equal to - * ACE_Time_Value::zero, the timer will become a non-rescheduling - * timer. Returns 0 if successful, -1 if not. - */ - virtual int reset_interval (long timer_id, - const ACE_Time_Value &interval); - - /** - * Cancel all timers associated with @a type. If @a dont_call_handle_close - * is 0 then the will be invoked. Returns number of timers - * cancelled. - */ - virtual int cancel (const TYPE &type, - int dont_call_handle_close = 1); - - /** - * Cancel the single timer that matches the @a timer_id value (which - * was returned from the method). If act is non-NULL - * then it will be set to point to the ``magic cookie'' argument - * passed in when the timer was registered. This makes it possible - * to free up the memory and avoid memory leaks. If @a dont_call_handle_close - * is 0 then the will be invoked. Returns 1 if cancellation - * succeeded and 0 if the @a timer_id wasn't found. - */ - virtual int cancel (long timer_id, - const void **act = 0, - int dont_call_handle_close = 1); - - /// Returns a pointer to this ACE_Timer_Queue's iterator. - virtual ACE_Timer_Queue_Iterator_T &iter (void); - - /** - * Removes the earliest node from the queue and returns it. Note that - * the timer is removed from the heap, but is not freed, and its ID - * is not reclaimed. The caller is responsible for calling either - * @c reschedule() or @c free_node() after this function returns. Thus, - * this function is for support of @c ACE_Timer_Queue::expire and - * should not be used unadvisedly in other conditions. - */ - ACE_Timer_Node_T *remove_first (void); - - /// Dump the state of an object. - virtual void dump (void) const; - - /// Reads the earliest node from the queue and returns it. - virtual ACE_Timer_Node_T *get_first (void); - -protected: - - /** - * Schedule a timer that may optionally auto-reset. - * Schedule @a type that will expire at @a future_time, - * which is specified in absolute time. If it expires then @a act is - * passed in as the value to the . If @a interval is != to - * ACE_Time_Value::zero then it is used to reschedule the @a type - * automatically, using relative time to the current . - * This method returns a that uniquely identifies the the - * @a type entry in an internal list. This can be used to - * cancel the timer before it expires. The cancellation ensures - * that are unique up to values of greater than 2 - * billion timers. As long as timers don't stay around longer than - * this there should be no problems with accidentally deleting the - * wrong timer. Returns -1 on failure (which is guaranteed never to - * be a valid ). - */ - virtual long schedule_i (const TYPE &type, - const void *act, - const ACE_Time_Value &future_time, - const ACE_Time_Value &interval); - - /// Reschedule an "interval" ACE_Timer_Node. - virtual void reschedule (ACE_Timer_Node_T *); - - /// Factory method that allocates a new node (uses operator new if - /// we're *not* preallocating, otherwise uses an internal freelist). - virtual ACE_Timer_Node_T *alloc_node (void); - - /** - * Factory method that frees a previously allocated node (uses - * operator delete if we're *not* preallocating, otherwise uses an - * internal freelist). - */ - virtual void free_node (ACE_Timer_Node_T *); - -private: - /// Remove and return the @a sloth ACE_Timer_Node and restore the - /// heap property. - ACE_Timer_Node_T *remove (size_t slot); - - /// Insert @a new_node into the heap and restore the heap property. - void insert (ACE_Timer_Node_T *new_node); - - /** - * Doubles the size of the heap and the corresponding timer_ids array. - * If preallocation is used, will also double the size of the - * preallocated array of ACE_Timer_Nodes. - */ - void grow_heap (void); - - /// Restore the heap property, starting at @a slot. - void reheap_up (ACE_Timer_Node_T *new_node, - size_t slot, - size_t parent); - - /// Restore the heap property, starting at @a slot. - void reheap_down (ACE_Timer_Node_T *moved_node, - size_t slot, - size_t child); - - /// Copy @a moved_node into the @a slot slot of and move - /// @a slot into the corresponding slot in the array. - void copy (size_t slot, ACE_Timer_Node_T *moved_node); - - /** - * Returns a timer id that uniquely identifies this timer. This id - * can be used to cancel a timer via the method. The - * timer id returned from this method will never == -1 to avoid - * conflicts with other failure return values. - */ - long timer_id (void); - - /// Pops and returns a new timer id from the freelist. - long pop_freelist (void); - - /// Pushes @a old_id onto the freelist. - void push_freelist (long old_id); - - /// Maximum size of the heap. - size_t max_size_; - - /// Current size of the heap. - size_t cur_size_; - - /// Number of heap entries in transition (removed from the queue, but - /// not freed) and may be rescheduled or freed. - size_t cur_limbo_; - - /// Iterator used to expire timers. - HEAP_ITERATOR *iterator_; - - /** - * Current contents of the Heap, which is organized as a "heap" of - * ACE_Timer_Node *'s. In this context, a heap is a "partially - * ordered, almost complete" binary tree, which is stored in an - * array. - */ - ACE_Timer_Node_T **heap_; - - /** - * An array of "pointers" that allows each ACE_Timer_Node in the - * to be located in O(1) time. Basically, - * contains the slot in the array where an ACE_Timer_Node - * * with timer id \ resides. Thus, the timer id passed back from - * is really a slot into the array. The - * array serves two purposes: negative values are - * indications of free timer IDs, whereas positive values are - * "pointers" into the array for assigned timer IDs. - */ - ssize_t *timer_ids_; - - /// "Pointer" to the element in the array that was - /// last given out as a timer ID. - size_t timer_ids_curr_; - - /// Index representing the lowest timer ID that has been freed. When - /// the timer_ids_next_ value wraps around, it starts back at this - /// point. - size_t timer_ids_min_free_; - - /** - * If this is non-0, then we preallocate number of - * ACE_Timer_Node objects in order to reduce dynamic allocation - * costs. In auto-growing implementation, this points to the - * last array of nodes allocated. - */ - ACE_Timer_Node_T *preallocated_nodes_; - - /// This points to the head of the freelist, - /// which is organized as a stack. - ACE_Timer_Node_T *preallocated_nodes_freelist_; - - /// Set of pointers to the arrays of preallocated timer nodes. - /// Used to delete the allocated memory when required. - ACE_Unbounded_Set *> preallocated_node_set_; - - // = Don't allow these operations for now. - ACE_UNIMPLEMENTED_FUNC (ACE_Timer_Heap_T (const ACE_Timer_Heap_T &)) - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Timer_Heap_T &)) -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Timer_Heap_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Timer_Heap_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" -#endif /* ACE_TIMER_HEAP_T_H */ diff --git a/externals/ace/Timer_List.h b/externals/ace/Timer_List.h deleted file mode 100644 index f2d9cc2a458..00000000000 --- a/externals/ace/Timer_List.h +++ /dev/null @@ -1,42 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Timer_List.h - * - * $Id: Timer_List.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Doug Schmidt - */ -//============================================================================= - - -#ifndef ACE_TIMER_LIST_H -#define ACE_TIMER_LIST_H -#include /**/ "ace/pre.h" - -#include "ace/Timer_List_T.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// The following typedefs are here for ease of use and backward -// compatibility. - -typedef ACE_Timer_List_T, - ACE_SYNCH_RECURSIVE_MUTEX> - ACE_Timer_List; - -typedef ACE_Timer_List_Iterator_T, - ACE_SYNCH_RECURSIVE_MUTEX> - ACE_Timer_List_Iterator; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" -#endif /* ACE_TIMER_LIST_H */ diff --git a/externals/ace/Timer_List_T.cpp b/externals/ace/Timer_List_T.cpp deleted file mode 100644 index c3b837bb289..00000000000 --- a/externals/ace/Timer_List_T.cpp +++ /dev/null @@ -1,418 +0,0 @@ -// $Id: Timer_List_T.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#ifndef ACE_TIMER_LIST_T_C -#define ACE_TIMER_LIST_T_C - -#include "ace/Timer_List_T.h" -#include "ace/Guard_T.h" -#include "ace/Log_Msg.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_RCSID(ace, Timer_List_T, "$Id: Timer_List_T.cpp 80826 2008-03-04 14:51:23Z wotte $") - -// Default Constructor - -template -ACE_Timer_List_Iterator_T::ACE_Timer_List_Iterator_T (List& lst) - : list_ (lst) -{ - this->first(); -} - -template -ACE_Timer_List_Iterator_T::~ACE_Timer_List_Iterator_T (void) -{ -} - -// Positions the iterator at the node right after the dummy node - -template void -ACE_Timer_List_Iterator_T::first (void) -{ - this->current_node_ = this->list_.get_first(); -} - -// Positions the iterator at the next node in the Timer Queue - -template void -ACE_Timer_List_Iterator_T::next (void) -{ - // Make sure that if we are at the end, we don't wrap around - if (! this->isdone()) - this->current_node_ = this->current_node_->get_next (); - if (this->current_node_ == this->list_.head_) - this->current_node_ = 0; -} - -// Returns true when we are at - -template bool -ACE_Timer_List_Iterator_T::isdone (void) const -{ - return this->current_node_ == 0; -} - -// Returns the node at or 0 if we are at the end - -template ACE_Timer_Node_T * -ACE_Timer_List_Iterator_T::item (void) -{ - if (! this->isdone()) - return this->current_node_; - return 0; -} - -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// - -// Return our instance of the iterator - -template ACE_Timer_Queue_Iterator_T & -ACE_Timer_List_T::iter (void) -{ - this->iterator_->first (); - return *this->iterator_; -} - -// Create an empty list. - -template -ACE_Timer_List_T::ACE_Timer_List_T (FUNCTOR* uf, FreeList* fl) - : Base(uf, fl) - , head_ (new ACE_Timer_Node_T) - , id_counter_ (0) -{ - ACE_TRACE ("ACE_Timer_List_T::ACE_Timer_List_T"); - - this->head_->set_next (this->head_); - this->head_->set_prev (this->head_); - - ACE_NEW (iterator_, Iterator(*this)); -} - - -// Checks if list is empty. - -template bool -ACE_Timer_List_T::is_empty (void) const -{ - ACE_TRACE ("ACE_Timer_List_T::is_empty"); - return this->get_first_i() == 0; -} - - -// Returns earliest time in a non-empty list. - -template const ACE_Time_Value & -ACE_Timer_List_T::earliest_time (void) const -{ - ACE_TRACE ("ACE_Timer_List_T::earliest_time"); - ACE_Timer_Node_T* first = this->get_first_i(); - if (first != 0) - return first->get_timer_value (); - return ACE_Time_Value::zero; -} - - -// Remove all remaining items in the list. - -template -ACE_Timer_List_T::~ACE_Timer_List_T (void) -{ - ACE_TRACE ("ACE_Timer_List_T::~ACE_Timer_List_T"); - ACE_MT (ACE_GUARD (ACE_LOCK, ace_mon, this->mutex_)); - - delete iterator_; - - if (!this->is_empty()) - { - for (ACE_Timer_Node_T* n = this->get_first(); - n != this->head_; - ) - { - this->upcall_functor ().deletion (*this, - n->get_type(), - n->get_act()); - - ACE_Timer_Node_T *next = - n->get_next (); - - this->free_node (n); - - n = next; - } - } - - // delete the dummy node - delete this->head_; -} - -template void -ACE_Timer_List_T::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Timer_List_T::dump"); - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - - int count = 0; - - ACE_Timer_Node_T* n = this->get_first_i(); - if (n != 0) { - for (; n != this->head_; n = n->get_next()) { - ++count; - } - } - - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nsize_ = %d"), count)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - - -// Reschedule a periodic timer. This function must be called with the -// lock held. - -template void -ACE_Timer_List_T::reschedule (ACE_Timer_Node_T* n) -{ - ACE_TRACE ("ACE_Timer_List_T::reschedule"); - this->schedule_i(n, n->get_timer_value()); -} - - -// Insert a new handler that expires at time future_time; if interval -// is > 0, the handler will be reinvoked periodically. - -template long -ACE_Timer_List_T::schedule_i (const TYPE &type, - const void *act, - const ACE_Time_Value &future_time, - const ACE_Time_Value &interval) -{ - ACE_TRACE ("ACE_Timer_List_T::schedule_i"); - - ACE_Timer_Node_T* n = this->alloc_node(); - - if (n != 0) - { - long id = this->id_counter_++; - - if (id != -1) { - n->set (type, act, future_time, interval, 0, 0, id); - this->schedule_i (n, future_time); - } - return id; - } - - // Failure return - errno = ENOMEM; - return -1; -} - -/// The shared scheduling functionality between schedule() and reschedule() -template void -ACE_Timer_List_T::schedule_i (ACE_Timer_Node_T* n, - const ACE_Time_Value& expire) -{ - if (this->is_empty()) { - n->set_prev(this->head_); - n->set_next(this->head_); - this->head_->set_prev(n); - this->head_->set_next(n); - return; - } - - // We always want to search backwards from the tail of the list, because - // this minimizes the search in the extreme case when lots of timers are - // scheduled for exactly the same time, and it also assumes that most of - // the timers will be scheduled later than existing timers. - ACE_Timer_Node_T* p = this->head_->get_prev(); - while (p != this->head_ && p->get_timer_value() > expire) - p = p->get_prev(); - - // insert after - n->set_prev(p); - n->set_next(p->get_next()); - p->get_next()->set_prev(n); - p->set_next(n); -} - -template -ACE_Timer_Node_T* -ACE_Timer_List_T::find_node (long timer_id) const -{ - ACE_Timer_Node_T* n = this->get_first_i(); - if (n == 0) - return 0; - - for (; n != this->head_; n = n->get_next()) { - if (n->get_timer_id() == timer_id) { - return n; - } - } - return 0; -} - -// Locate and update the inteval on the timer_id -template int -ACE_Timer_List_T::reset_interval (long timer_id, - const ACE_Time_Value &interval) -{ - ACE_TRACE ("ACE_Timer_List_T::reset_interval"); - ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); - ACE_Timer_Node_T* n = this->find_node(timer_id); - if (n != 0) { - n->set_interval(interval); // The interval will take effect the next time this node is expired. - return 0; - } - return -1; -} - -// Locate and remove the single with a value of -// @a timer_id from the timer queue. -template int -ACE_Timer_List_T::cancel (long timer_id, - const void **act, - int skip_close) -{ - ACE_TRACE ("ACE_Timer_List_T::cancel"); - ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); - ACE_Timer_Node_T* n = this->find_node(timer_id); - if (n != 0) - { - if (act != 0) - *act = n->get_act (); - - // Call the close hooks. - int cookie = 0; - - // cancel_type() called once per . - this->upcall_functor ().cancel_type (*this, - n->get_type (), - skip_close, - cookie); - - // cancel_timer() called once per . - this->upcall_functor ().cancel_timer (*this, - n->get_type (), - skip_close, - cookie); - - this->cancel_i (n); - - return 1; - } - - return 0; -} - -// Locate and remove all values of from the timer queue. -template int -ACE_Timer_List_T::cancel (const TYPE &type, int skip_close) -{ - ACE_TRACE ("ACE_Timer_List_T::cancel"); - - int num_canceled = 0; // Note : Technically this can overflow. - - int cookie = 0; - - ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); - - if (!this->is_empty ()) - { - for (ACE_Timer_Node_T* n = this->get_first(); - n != this->head_; - ) - { - if (n->get_type() == type) // Note: Typically Type is an ACE_Event_Handler* - { - ++num_canceled; - - ACE_Timer_Node_T* tmp = n; - n = n->get_next(); - - this->cancel_i (tmp); - } - else - { - n = n->get_next(); - } - } - } - - // Call the close hooks. - - // cancel_type() called once per . - this->upcall_functor ().cancel_type (*this, - type, - skip_close, - cookie); - - for (int i = 0; - i < num_canceled; - ++i) - { - // cancel_timer() called once per . - this->upcall_functor ().cancel_timer (*this, - type, - skip_close, - cookie); - } - - return num_canceled; -} - -template void -ACE_Timer_List_T::unlink (ACE_Timer_Node_T* n) -{ - n->get_prev()->set_next(n->get_next()); - n->get_next()->set_prev(n->get_prev()); - n->set_prev(0); - n->set_next(0); -} - -/// Shared subset of the two cancel() methods. -template void -ACE_Timer_List_T::cancel_i (ACE_Timer_Node_T* n) -{ - this->unlink (n); - this->free_node (n); -} - -// Reads the first node on the list and returns it. -template ACE_Timer_Node_T * -ACE_Timer_List_T::get_first (void) -{ - ACE_TRACE ("ACE_Timer_List_T::get_first"); - return this->get_first_i(); -} - -template ACE_Timer_Node_T * -ACE_Timer_List_T::get_first_i (void) const -{ - ACE_TRACE ("ACE_Timer_List_T::get_first_i"); - ACE_Timer_Node_T* first = this->head_->get_next(); - if (first != this->head_) // Note : is_empty() uses get_first() - return first; - return 0; -} - - -// Removes the first node on the list and returns it. - -template ACE_Timer_Node_T * -ACE_Timer_List_T::remove_first (void) -{ - ACE_TRACE ("ACE_Timer_List_T::remove_first"); - ACE_Timer_Node_T* first = this->get_first(); - if (first != 0) { - this->unlink(first); - return first; - } - return 0; -} - -#endif /* ACE_TIMER_LIST_T_C */ diff --git a/externals/ace/Timer_List_T.h b/externals/ace/Timer_List_T.h deleted file mode 100644 index cabd47aeaf0..00000000000 --- a/externals/ace/Timer_List_T.h +++ /dev/null @@ -1,226 +0,0 @@ -/* -*- C++ -*- */ - -//============================================================================= -/** - * @file Timer_List_T.h - * - * $Id: Timer_List_T.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_TIMER_LIST_T_H -#define ACE_TIMER_LIST_T_H -#include /**/ "ace/pre.h" - -#include "ace/Timer_Queue_T.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -// Forward declaration. -template -class ACE_Timer_List_T; - -/** - * @class ACE_Timer_List_Iterator_T - * - * @brief Iterates over an ACE_Timer_List. - * - * This is a generic iterator that can be used to visit every - * node of a timer queue. - */ -template -class ACE_Timer_List_Iterator_T -: public ACE_Timer_Queue_Iterator_T -{ -public: - typedef ACE_Timer_List_T List; - /// Constructor. - ACE_Timer_List_Iterator_T (List& lst); - - /// Destructor. - virtual ~ACE_Timer_List_Iterator_T (void); - - /// Positions the iterator at the earliest node in the Timer Queue - virtual void first (void); - - /// Positions the iterator at the next node in the Timer Queue - virtual void next (void); - - /// Returns true when there are no more nodes in the sequence - virtual bool isdone (void) const; - - /// Returns the node at the current position in the sequence - virtual ACE_Timer_Node_T *item (void); - -protected: - /// Pointer to the ACE_Timer_List that we are iterating over. - List& list_; - - /// Current position in the ACE_Timer_List - ACE_Timer_Node_T* current_node_; -}; - -/** - * @class ACE_Timer_List_T - * - * @brief Provides a simple implementation of timers. - * - * This implementation uses a linked list of absolute times. - * Therefore, in the average case, scheduling and canceling - * timers is O(N) (where N is the total number of timers) and - * expiring timers is O(K) (where K is the total number of timers - * that are < the current time of day). - * More clever implementations could use a delta-list, a heap, - * or timing wheels, etc. For instance, ACE_Timer_Heap - * is a subclass of ACE_Timer_List that implements a - * heap-based callout queue. For most applications, the - * ACE_Timer_Heap will perform substantially faster than the - * ACE_Timer_List. - */ -template -class ACE_Timer_List_T : public ACE_Timer_Queue_T -{ -public: - /// Type of iterator - typedef ACE_Timer_List_Iterator_T Iterator; - - /// Iterator is a friend - friend class ACE_Timer_List_Iterator_T; - - typedef ACE_Timer_Node_T Node; - /// Type inherited from - typedef ACE_Timer_Queue_T Base; - typedef ACE_Free_List FreeList; - - // = Initialization and termination methods. - /** - * Default constructor. @a upcall_functor is the instance of the - * FUNCTOR to be used by the list. If @a upcall_functor is 0, a - * default FUNCTOR will be created. @a freelist is the freelist of - * timer nodes. If 0, then a default freelist will be created. - */ - ACE_Timer_List_T (FUNCTOR* upcall_functor = 0, FreeList* freelist = 0); - - /// Destructor - virtual ~ACE_Timer_List_T (void); - - /// True if queue is empty, else false. - virtual bool is_empty (void) const; - - /// Returns the time of the earlier node in the ACE_Timer_List. - /// Must be called on a non-empty queue. - virtual const ACE_Time_Value& earliest_time (void) const; - - /** - * Resets the interval of the timer represented by @a timer_id to - * @a interval, which is specified in relative time to the current - * . If @a interval is equal to - * ACE_Time_Value::zero, the timer will become a non-rescheduling - * timer. Returns 0 if successful, -1 if not. - */ - virtual int reset_interval (long timer_id, - const ACE_Time_Value& interval); - - /** - * Cancel all timers associated with @a type. If dont_call_handle_close is 0 - * then the @a functor will be invoked. Returns the number of timers - * cancelled. - */ - virtual int cancel (const TYPE& type, - int dont_call_handle_close = 1); - - /** - * Cancel the single timer that matches the @a timer_id value (which - * was returned from the method). If act is non-NULL - * then it will be set to point to the ``magic cookie'' argument - * passed in when the timer was registered. This makes it possible - * to free up the memory and avoid memory leaks. If is - * 0 then the will be invoked. Returns 1 if cancellation - * succeeded and 0 if the @a timer_id wasn't found. - */ - virtual int cancel (long timer_id, - const void** act = 0, - int dont_call_handle_close = 1); - - /// Returns a pointer to this ACE_Timer_Queue's iterator. - virtual ACE_Timer_Queue_Iterator_T& iter (void); - - /// Removes the earliest node from the queue and returns it - virtual ACE_Timer_Node_T* remove_first (void); - - /// Dump the state of an object. - virtual void dump (void) const; - - /// Reschedule an "interval" ACE_Timer_Node_T. This should be private - /// but for now it needs to be public for - virtual void reschedule (ACE_Timer_Node_T *); - - /// Reads the earliest node from the queue and returns it. - virtual ACE_Timer_Node_T* get_first (void); - -private: - - /** - * Schedule @a type that will expire at @a future_time, which is - * specified in absolute time. If it expires then @a act is passed - * in as the value to the . If @a interval is != to - * ACE_Time_Value::zero then it is used to reschedule the @a type - * automatically, using relative time to the current . - * This method returns a that uniquely identifies the the - * @a type entry in an internal list. This can be used to - * cancel the timer before it expires. The cancellation ensures - * that are unique up to values of greater than 2 - * billion timers. As long as timers don't stay around longer than - * this there should be no problems with accidentally deleting the - * wrong timer. Returns -1 on failure (which is guaranteed never to - * be a valid ). - */ - virtual long schedule_i (const TYPE& type, - const void* act, - const ACE_Time_Value& future_time, - const ACE_Time_Value& interval); - - void schedule_i(ACE_Timer_Node_T* n, const ACE_Time_Value& exp); - - ACE_Timer_Node_T* find_node(long timer_id) const; - - void cancel_i (ACE_Timer_Node_T* n); - - void unlink (ACE_Timer_Node_T* n); - - ACE_Timer_Node_T* get_first_i(void) const; - -private: - - /// Pointer to linked list of . - ACE_Timer_Node_T* head_; - - /// Iterator used to expire timers. - Iterator* iterator_; - - /** - * Keeps track of the timer id that uniquely identifies each timer. - * This id can be used to cancel a timer via the - * method. - */ - long id_counter_; - - // = Don't allow these operations for now. - ACE_UNIMPLEMENTED_FUNC (ACE_Timer_List_T (const ACE_Timer_List_T &)) - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Timer_List_T &)) -}; - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Timer_List_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Timer_List_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" -#endif /* ACE_TIMER_LIST_T_H */ diff --git a/externals/ace/Timer_Queue.h b/externals/ace/Timer_Queue.h deleted file mode 100644 index 4644aa1b43d..00000000000 --- a/externals/ace/Timer_Queue.h +++ /dev/null @@ -1,52 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Timer_Queue.h - * - * $Id: Timer_Queue.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Douglas C. Schmidt - * @author Irfan Pyarali - */ -//============================================================================= - -#ifndef ACE_TIMER_QUEUE_H -#define ACE_TIMER_QUEUE_H - -#include /**/ "ace/pre.h" - -#include "ace/Synch_Traits.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Timer_Queuefwd.h" -#include "ace/Timer_Queue_T.h" -#if defined (ACE_HAS_THREADS) -# include "ace/Recursive_Thread_Mutex.h" -#else -# include "ace/Null_Mutex.h" -#endif /* ACE_HAS_THREADS */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// The following typedef are here for ease of use and backward -// compatibility. -typedef ACE_Timer_Node_Dispatch_Info_T - ACE_Timer_Node_Dispatch_Info; - -typedef ACE_Timer_Node_T - ACE_Timer_Node; - -typedef ACE_Timer_Queue_Iterator_T, - ACE_SYNCH_RECURSIVE_MUTEX> - ACE_Timer_Queue_Iterator; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" - -#endif /* ACE_TIMER_QUEUE_H */ diff --git a/externals/ace/Timer_Queue_Adapters.cpp b/externals/ace/Timer_Queue_Adapters.cpp deleted file mode 100644 index 54e8f8ade5f..00000000000 --- a/externals/ace/Timer_Queue_Adapters.cpp +++ /dev/null @@ -1,361 +0,0 @@ -// $Id: Timer_Queue_Adapters.cpp 89482 2010-03-15 07:58:50Z johnnyw $ - -#ifndef ACE_TIMER_QUEUE_ADAPTERS_CPP -#define ACE_TIMER_QUEUE_ADAPTERS_CPP - -#include "ace/Timer_Queue_Adapters.h" - -#if defined (ACE_HAS_DEFERRED_TIMER_COMMANDS) -#include "ace/Functor.h" -#endif /* ACE_HAS_DEFERRED_TIMER_COMMANDS */ - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -# if !defined (__ACE_INLINE__) -# include "ace/Timer_Queue_Adapters.inl" -# endif /* __ACE_INLINE__ */ - -#include "ace/Signal.h" -#include "ace/OS_NS_unistd.h" -#include "ace/OS_NS_sys_time.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template TQ & -ACE_Async_Timer_Queue_Adapter::timer_queue (void) -{ - return this->timer_queue_; -} - -template int -ACE_Async_Timer_Queue_Adapter::cancel (long timer_id, - const void **act) -{ - // Block designated signals. - ACE_Sig_Guard sg (&this->mask_); - ACE_UNUSED_ARG (sg); - - return this->timer_queue_.cancel (timer_id, act); -} - -template int -ACE_Async_Timer_Queue_Adapter::expire (void) -{ - // Block designated signals. - ACE_Sig_Guard sg (&this->mask_); - ACE_UNUSED_ARG (sg); - - return this->timer_queue_.expire (); -} - -template int -ACE_Async_Timer_Queue_Adapter::schedule_ualarm (void) -{ - ACE_Time_Value tv = this->timer_queue_.earliest_time () - - this->timer_queue_.gettimeofday (); - - // Beware of negative times and zero times (which cause problems for - // ). - if (tv < ACE_Time_Value::zero) - tv = ACE_Time_Value (0, 1); - - // @@ This code should be clever enough to avoid updating the - // if we haven't actually changed the earliest time. - // Schedule a new timer. - ACE_OS::ualarm (tv); - return 0; -} - -template long -ACE_Async_Timer_Queue_Adapter::schedule (TYPE eh, - const void *act, - const ACE_Time_Value &future_time, - const ACE_Time_Value &interval) -{ - ACE_UNUSED_ARG (act); - ACE_UNUSED_ARG (interval); - - // Block designated signals. - ACE_Sig_Guard sg (&this->mask_); - ACE_UNUSED_ARG (sg); - - // @@ We still need to implement interval timers... - long tid = this->timer_queue_.schedule (eh, act, future_time); - - if (tid == -1) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("schedule_timer")), - -1); - - if (this->schedule_ualarm () == -1) - return 0; - - return tid; -} - -template -ACE_Async_Timer_Queue_Adapter::ACE_Async_Timer_Queue_Adapter (ACE_Sig_Set *mask) - // If == 0, block *all* signals when the SIGARLM handler is - // running, else just block those in the mask. - : mask_ (mask) -{ - // The following code is necessary to selectively "block" certain - // signals when SIGALRM is running. Also, we always restart system - // calls that are interrupted by the signals. - - ACE_Sig_Action sa ((ACE_SignalHandler) 0, - this->mask_, - SA_RESTART); - - if (this->sig_handler_.register_handler (SIGALRM, this, &sa) == -1) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("register_handler"))); -} - -// This is the signal handler function for the asynchronous timer -// list. It gets invoked asynchronously when the SIGALRM signal -// occurs. - -template int -ACE_Async_Timer_Queue_Adapter::handle_signal (int signum, - siginfo_t *, - ucontext_t *) -{ - switch (signum) - { - case SIGALRM: - { - // Expire the pending timers. - - // @@ We need to figure out how to implement interval - // timers... - this->timer_queue_.expire (); - - // Only schedule a new timer if there is one in the list. - - // @@ This code should also become smarter to avoid - // unnecessary calls to ualarm(). - if (this->timer_queue_.is_empty () == 0) - return this->schedule_ualarm (); - else - return 0; - /* NOTREACHED */ - } - default: - ACE_ERROR_RETURN ((LM_ERROR, - "unexpected signal %S\n", - signum), - -1); - /* NOTREACHED */ - } -} - -template -ACE_Thread_Timer_Queue_Adapter::ACE_Thread_Timer_Queue_Adapter (ACE_Thread_Manager *tm, - TQ* timer_queue) - : ACE_Task_Base (tm), - timer_queue_(timer_queue), - delete_timer_queue_(false), - condition_ (mutex_), - active_ (true), // Assume that we start in active mode. - thr_id_ (ACE_OS::NULL_thread) -{ - if (timer_queue_ == 0) - { - ACE_NEW (this->timer_queue_, - TQ); - this->delete_timer_queue_ = true; - } -} - -template -ACE_Thread_Timer_Queue_Adapter::~ACE_Thread_Timer_Queue_Adapter (void) -{ - if (this->delete_timer_queue_) - { - delete this->timer_queue_; - this->timer_queue_ = 0; - this->delete_timer_queue_ = false; - } -} - -template ACE_SYNCH_RECURSIVE_MUTEX & -ACE_Thread_Timer_Queue_Adapter::mutex (void) -{ - return this->mutex_; -} - -template long -ACE_Thread_Timer_Queue_Adapter::schedule - (TYPE handler, - const void *act, - const ACE_Time_Value &future_time, - const ACE_Time_Value &interval) -{ - ACE_GUARD_RETURN (ACE_SYNCH_RECURSIVE_MUTEX, guard, this->mutex_, -1); - - long result = this->timer_queue_->schedule (handler, act, future_time, interval); - this->condition_.signal (); - return result; -} - -template int -ACE_Thread_Timer_Queue_Adapter::cancel (long timer_id, - const void **act) -{ - ACE_GUARD_RETURN (ACE_SYNCH_RECURSIVE_MUTEX, guard, this->mutex_, -1); - - int result = this->timer_queue_->cancel (timer_id, act); - condition_.signal (); - return result; -} - -template void -ACE_Thread_Timer_Queue_Adapter::deactivate (void) -{ - ACE_GUARD (ACE_SYNCH_RECURSIVE_MUTEX, guard, this->mutex_); - - this->active_ = false; - this->condition_.signal (); -} - -template int -ACE_Thread_Timer_Queue_Adapter::svc (void) -{ - ACE_GUARD_RETURN (ACE_SYNCH_RECURSIVE_MUTEX, guard, this->mutex_, -1); - - this->thr_id_ = ACE_Thread::self (); - - // Thread cancellation point, if ACE supports it. - // - // Note: This call generates a warning under Solaris because the header - // file /usr/include/pthread.h redefines the routine argument. This - // is a bug in the Solaris header files and has nothing to do with - // ACE. -# if !defined (ACE_LACKS_PTHREAD_CANCEL) - ACE_PTHREAD_CLEANUP_PUSH (&this->condition_.mutex ().get_nesting_mutex ()); -# endif /* ACE_LACKS_PTHREAD_CANCEL */ - - while (this->active_) - { -# if defined (ACE_HAS_DEFERRED_TIMER_COMMANDS) - // Temporarily suspend ownership of the timer queue mutex in - // order to dispatch deferred execution commands. These - // commands are to be treated as executing in a context - // "external" to the timer queue adapter, and thus must compete - // separately for this lock. - mutex_.release (); - this->dispatch_commands (); - - // Re-acquire ownership of the timer queue mutex in order to - // restore the "internal" timer queue adapter context - mutex_.acquire (); -# endif /* ACE_HAS_DEFERRED_TIMER_COMMANDS */ - - // If the queue is empty, sleep until there is a change on it. - if (this->timer_queue_->is_empty ()) - this->condition_.wait (); - else - { - // Compute the remaining time, being careful not to sleep - // for "negative" amounts of time. - ACE_Time_Value const tv_curr = this->timer_queue_->gettimeofday (); - ACE_Time_Value const tv_earl = this->timer_queue_->earliest_time (); - - if (tv_earl > tv_curr) - { - // The earliest time on the Timer_Queue is in future, so - // use ACE_OS::gettimeofday() to convert the tv to the - // absolute time. - ACE_Time_Value const tv = ACE_OS::gettimeofday () + (tv_earl - tv_curr); - // ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("waiting until %u.%3.3u secs\n"), - // tv.sec(), tv.msec())); - this->condition_.wait (&tv); - } - } - - // Expire timers anyway, at worst this is a no-op. - this->timer_queue_->expire (); - } - - // Thread cancellation point, if ACE supports it. -# if !defined (ACE_LACKS_PTHREAD_CANCEL) - ACE_PTHREAD_CLEANUP_POP (0); -# endif /* ACE_LACKS_PTHREAD_CANCEL */ - - return 0; -} - -template int -ACE_Thread_Timer_Queue_Adapter::activate (long flags, - int , - int , - long priority, - int grp_id, - ACE_Task_Base *task, - ACE_hthread_t [], - void *stack[], - size_t stack_size[], - ACE_thread_t thread_ids[], - const char* thr_name[]) -{ - // Make sure to set this flag in case we were deactivated earlier. - this->active_ = true; - - // Make sure that we only allow a single thread to be spawned for - // our adapter. Otherwise, too many weird things can happen. - return ACE_Task_Base::activate (flags, 1, 0, priority, grp_id, task, 0, - stack, stack_size, thread_ids, thr_name); -} - -# if defined (ACE_HAS_DEFERRED_TIMER_COMMANDS) - -// Enqueues a command object for execution just before waiting on the next -// timer event. This allows deferred execution of commands that cannot -// be performed in the timer event handler context, such as registering -// or cancelling timers on platforms where the timer queue mutex is not -// recursive. - -template int -ACE_Thread_Timer_Queue_Adapter::enqueue_command (ACE_Command_Base *cmd, - COMMAND_ENQUEUE_POSITION pos) -{ - // Serialize access to the command queue. - ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, guard, this->command_mutex_, -1); - - if (pos == ACE_Thread_Timer_Queue_Adapter::TAIL) - return command_queue_.enqueue_tail (cmd); - else - return command_queue_.enqueue_head (cmd); -} - -// Dispatches all command objects enqueued in the most recent event -// handler context. - -template int -ACE_Thread_Timer_Queue_Adapter::dispatch_commands (void) -{ - // Serialize access to the command queue. - ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, guard, this->command_mutex_, -1); - - // loop through the enqueued commands - ACE_Command_Base *cmd = 0; - while (command_queue_.dequeue_head (cmd) == 0) - if (cmd) - { - cmd->execute (); - delete cmd; - } - - return 0; -} - -# endif /* ACE_HAS_DEFERRED_TIMER_COMMANDS */ - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_TIMER_QUEUE_ADAPTERS_CPP */ diff --git a/externals/ace/Timer_Queue_Adapters.h b/externals/ace/Timer_Queue_Adapters.h deleted file mode 100644 index d5561717142..00000000000 --- a/externals/ace/Timer_Queue_Adapters.h +++ /dev/null @@ -1,261 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Timer_Queue_Adapters.h - * - * $Id: Timer_Queue_Adapters.h 89482 2010-03-15 07:58:50Z johnnyw $ - * - * @author Douglas C. Schmidt and - * Carlos O'Ryan - */ -//============================================================================= - -#ifndef ACE_TIMER_QUEUE_ADAPTERS_H -#define ACE_TIMER_QUEUE_ADAPTERS_H -#include /**/ "ace/pre.h" - -#include "ace/Task.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Signal.h" -#include "ace/Sig_Handler.h" -#include "ace/Condition_Recursive_Thread_Mutex.h" - -#if defined (ACE_HAS_DEFERRED_TIMER_COMMANDS) -# include "ace/Unbounded_Queue.h" -ACE_BEGIN_VERSIONED_NAMESPACE_DECL -class ACE_Command_Base; -ACE_END_VERSIONED_NAMESPACE_DECL -#endif /* ACE_HAS_DEFERRED_TIMER_COMMANDS */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -class ACE_Sig_Set; - -/** - * @class ACE_Async_Timer_Queue_Adapter - * - * @brief Adapts an ACE timer queue to be driven asynchronously using signals. - * - * This implementation uses the ACE_OS::ualarm call, to generate - * the SIGARLM signal that is caught by this class. - * - * @note This adapter only works on platforms that support ualarm(). - * POSIX platforms generally do; Windows and some others do not. - * - * @todo This adapter does not automatically reschedule repeating timers. - */ -template -class ACE_Async_Timer_Queue_Adapter : public ACE_Event_Handler -{ -public: - typedef TQ TIMER_QUEUE; - - /// Constructor - /** - * Register the SIGALRM handler. If @a mask == 0 then block all - * signals when @c SIGALRM is run. Otherwise, just block the signals - * indicated in @a mask. - */ - ACE_Async_Timer_Queue_Adapter (ACE_Sig_Set *mask = 0); - - /// Schedule the timer according to the semantics of the - /// ACE_Timer_List. - /** - * This timer gets dispatched via a signal, rather than by a user - * calling expire(). Note that interval timers are not implemented - * yet. - */ - long schedule (TYPE type, - const void *act, - const ACE_Time_Value &future_time, - const ACE_Time_Value &interval = ACE_Time_Value::zero); - - /// Cancel the @a timer_id and pass back the @a act if an address is - /// passed in. - int cancel (long timer_id, const void **act = 0); - - /// Dispatch all timers with expiry time at or before the current time. - /// Returns the number of timers expired. - int expire (void); - - /// Return a reference to the underlying timer queue. - TQ &timer_queue (void); - -private: - /// Perform the logic to compute the new ualarm(2) setting. - virtual int schedule_ualarm (void); - - /// Called back by @c SIGALRM handler. - virtual int handle_signal (int signum, siginfo_t *, ucontext_t *); - - /// Handler for the @c SIGALRM signal, so that we can access our state - /// without requiring any global variables. - ACE_Sig_Handler sig_handler_; - - /// Implementation of the timer queue (e.g., ACE_Timer_List, - /// ACE_Timer_Heap, etc.). - TQ timer_queue_; - - /// Mask of signals to be blocked when we're servicing @c SIGALRM. - ACE_Sig_Set mask_; -}; - -/** - * @class ACE_Thread_Timer_Queue_Adapter - * - * @brief Adapts an ACE timer queue using a separate thread for dispatching. - * - * This implementation uses a separate thread to dispatch the timers. - * The base queue need not be thread safe; this class takes all the - * necessary locks. - * - * @note This is a case where template parameters will be useful, but - * (IMHO) the effort and portability problems discourage their - * use. - * - */ -template -class ACE_Thread_Timer_Queue_Adapter : public ACE_Task_Base -{ -public: - /// Trait for the underlying queue type. - typedef TQ TIMER_QUEUE; - -# if defined (ACE_HAS_DEFERRED_TIMER_COMMANDS) - - /// Typedef for the position at which to enqueue a deferred - /// execution command. - enum COMMAND_ENQUEUE_POSITION {HEAD, TAIL}; - -# endif /* ACE_HAS_DEFERRED_TIMER_COMMANDS */ - - /// Creates the timer queue. Activation of the task is the user's - /// responsibility. Optionally a pointer to a timer queue can be passed, - /// when no pointer is passed, a TQ is dynamically created - ACE_Thread_Timer_Queue_Adapter (ACE_Thread_Manager * = ACE_Thread_Manager::instance (), - TQ* timer_queue = 0); - - /// Destructor. - virtual ~ACE_Thread_Timer_Queue_Adapter (void); - - /// Schedule the timer according to the semantics of the ; wakes - /// up the dispatching thread. - long schedule (TYPE handler, - const void *act, - const ACE_Time_Value &future_time, - const ACE_Time_Value &interval = ACE_Time_Value::zero); - - /// Cancel the @a timer_id and return the @a act parameter if an - /// address is passed in. Also wakes up the dispatching thread. - int cancel (long timer_id, const void **act = 0); - - /// Runs the dispatching thread. - virtual int svc (void); - - /// Inform the dispatching thread that it should terminate. - virtual void deactivate (void); - - /// Access the locking mechanism, useful for iteration. - ACE_SYNCH_RECURSIVE_MUTEX &mutex (void); - - /// Set a user-specified timer queue. - int timer_queue (TQ *tq); - - /// Return the current . - TQ *timer_queue (void) const; - - /// Return the thread id of our active object. - ACE_thread_t thr_id (void) const; - - /** - * We override the default activate() method so that we can ensure - * that only a single thread is ever spawned. Otherwise, too many - * weird things can happen... - */ - virtual int activate (long flags = THR_NEW_LWP | THR_JOINABLE, - int n_threads = 1, - int force_active = 0, - long priority = ACE_DEFAULT_THREAD_PRIORITY, - int grp_id = -1, - ACE_Task_Base *task = 0, - ACE_hthread_t thread_handles[] = 0, - void *stack[] = 0, - size_t stack_size[] = 0, - ACE_thread_t thread_ids[] = 0, - const char* thr_name[] = 0); - -# if defined (ACE_HAS_DEFERRED_TIMER_COMMANDS) - - /** - * Enqueues a command object for execution just before waiting on the next - * timer event. This allows deferred execution of commands that cannot - * be performed in the timer event handler context, such as registering - * or cancelling timers on platforms where the timer queue mutex is not - * recursive. - */ - int enqueue_command (ACE_Command_Base *command_, - COMMAND_ENQUEUE_POSITION pos = TAIL); - -# endif /* ACE_HAS_DEFERRED_TIMER_COMMANDS */ - -private: - -# if defined (ACE_HAS_DEFERRED_TIMER_COMMANDS) - /// Dispatches all command objects enqueued in the most - /// recent event handler context. - int dispatch_commands (void); - - /// Queue of commands for deferred execution. - ACE_Unbounded_Queue command_queue_; - - /// The mutual exclusion mechanism for the command queue. - ACE_SYNCH_MUTEX command_mutex_; -# endif /* ACE_HAS_DEFERRED_TIMER_COMMANDS */ - - /// The underlying Timer_Queue. - TQ* timer_queue_; - - /// Keeps track of whether we should delete the timer queue (if we - /// didn't create it, then we don't delete it). - bool delete_timer_queue_; - - /// The mutual exclusion mechanism that is required to use the - /// . - ACE_SYNCH_RECURSIVE_MUTEX mutex_; - - /** - * The dispatching thread sleeps on this condition while waiting to - * dispatch the next timer; it is used to wake it up if there is a - * change on the timer queue. - */ - ACE_SYNCH_RECURSIVE_CONDITION condition_; - - /// When deactivate is called this variable turns to false and the - /// dispatching thread is signalled, to terminate its main loop. - bool active_; - - /// Thread id of our active object task. - ACE_thread_t thr_id_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -# include "ace/Timer_Queue_Adapters.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -# include "ace/Timer_Queue_Adapters.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -# pragma implementation ("Timer_Queue_Adapters.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" -#endif /* ACE_TIMER_QUEUE_ADAPTERS_H */ diff --git a/externals/ace/Timer_Queue_Adapters.inl b/externals/ace/Timer_Queue_Adapters.inl deleted file mode 100644 index d73ef024246..00000000000 --- a/externals/ace/Timer_Queue_Adapters.inl +++ /dev/null @@ -1,29 +0,0 @@ -// -*- C++ -*- -// -// $Id: Timer_Queue_Adapters.inl 89482 2010-03-15 07:58:50Z johnnyw $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template ACE_INLINE TQ * -ACE_Thread_Timer_Queue_Adapter::timer_queue (void) const -{ - return this->timer_queue_; -} - -template ACE_INLINE int -ACE_Thread_Timer_Queue_Adapter::timer_queue (TQ *tq) -{ - if (this->delete_timer_queue_) - delete this->timer_queue_; - this->timer_queue_ = tq; - this->delete_timer_queue_ = false; - return 0; -} - -template ACE_INLINE ACE_thread_t -ACE_Thread_Timer_Queue_Adapter::thr_id (void) const -{ - return this->thr_id_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Timer_Queue_T.cpp b/externals/ace/Timer_Queue_T.cpp deleted file mode 100644 index 258e68edd55..00000000000 --- a/externals/ace/Timer_Queue_T.cpp +++ /dev/null @@ -1,538 +0,0 @@ -// $Id: Timer_Queue_T.cpp 89254 2010-02-25 22:10:39Z cleeland $ - -#ifndef ACE_TIMER_QUEUE_T_CPP -#define ACE_TIMER_QUEUE_T_CPP - -#include "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -/* - * Hook to specialize to add includes - */ -//@@ REACTOR_SPL_INCLUDE_FORWARD_DECL_ADD_HOOK - -#include "ace/Timer_Queue_T.h" -#include "ace/Guard_T.h" -#include "ace/Log_Msg.h" -#include "ace/Reactor_Timer_Interface.h" -#include "ace/Null_Mutex.h" -#include "ace/OS_NS_sys_time.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Timer_Queue_T.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// This fudge factor can be overriden for timers that need it, such as on -// Solaris, by defining the ACE_TIMER_SKEW symbol in the appropriate config -// header. -#if !defined (ACE_TIMER_SKEW) -# define ACE_TIMER_SKEW 0 -#endif /* ACE_TIMER_SKEW */ - -template void -ACE_Timer_Node_T::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Timer_Node_T::dump"); - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nact_ = %x"), this->act_)); - this->timer_value_.dump (); - this->interval_.dump (); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nprev_ = %x"), this->prev_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nnext_ = %x"), this->next_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ntimer_id_ = %d\n"), this->timer_id_)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -template -ACE_Timer_Node_T::ACE_Timer_Node_T (void) -{ - ACE_TRACE ("ACE_Timer_Node_T::ACE_Timer_Node_T"); -} - -template -ACE_Timer_Node_T::~ACE_Timer_Node_T (void) -{ - ACE_TRACE ("ACE_Timer_Node_T::~ACE_Timer_Node_T"); -} - -template -ACE_Timer_Queue_Iterator_T::ACE_Timer_Queue_Iterator_T (void) -{ -} - -template -ACE_Timer_Queue_Iterator_T::~ACE_Timer_Queue_Iterator_T (void) -{ -} - -template ACE_Time_Value * -ACE_Timer_Queue_T::calculate_timeout (ACE_Time_Value *max_wait_time) -{ - ACE_TRACE ("ACE_Timer_Queue_T::calculate_timeout"); - ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, max_wait_time)); - - if (this->is_empty ()) - // Nothing on the Timer_Queue, so use whatever the caller gave us. - return max_wait_time; - else - { - ACE_Time_Value const cur_time = this->gettimeofday (); - - if (this->earliest_time () > cur_time) - { - // The earliest item on the Timer_Queue is still in the - // future. Therefore, use the smaller of (1) caller's wait - // time or (2) the delta time between now and the earliest - // time on the Timer_Queue. - - this->timeout_ = this->earliest_time () - cur_time; - if (max_wait_time == 0 || *max_wait_time > timeout_) - return &this->timeout_; - else - return max_wait_time; - } - else - { - // The earliest item on the Timer_Queue is now in the past. - // Therefore, we've got to "poll" the Reactor, i.e., it must - // just check the descriptors and then dispatch timers, etc. - this->timeout_ = ACE_Time_Value::zero; - return &this->timeout_; - } - } -} - -template ACE_Time_Value * -ACE_Timer_Queue_T::calculate_timeout (ACE_Time_Value *max_wait_time, - ACE_Time_Value *the_timeout) -{ - ACE_TRACE ("ACE_Timer_Queue_T::calculate_timeout"); - - if (the_timeout == 0) - return 0; - - if (this->is_empty ()) - { - // Nothing on the Timer_Queue, so use whatever the caller gave us. - if (max_wait_time) - *the_timeout = *max_wait_time; - else - return 0; - } - else - { - ACE_Time_Value cur_time = this->gettimeofday (); - - if (this->earliest_time () > cur_time) - { - // The earliest item on the Timer_Queue is still in the - // future. Therefore, use the smaller of (1) caller's wait - // time or (2) the delta time between now and the earliest - // time on the Timer_Queue. - - *the_timeout = this->earliest_time () - cur_time; - if (!(max_wait_time == 0 || *max_wait_time > *the_timeout)) - *the_timeout = *max_wait_time; - } - else - { - // The earliest item on the Timer_Queue is now in the past. - // Therefore, we've got to "poll" the Reactor, i.e., it must - // just check the descriptors and then dispatch timers, etc. - *the_timeout = ACE_Time_Value::zero; - } - } - return the_timeout; -} - -template void -ACE_Timer_Queue_T::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Timer_Queue_T::dump"); - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - this->timeout_.dump (); - this->timer_skew_.dump (); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -template -ACE_Timer_Queue_T::ACE_Timer_Queue_T (FUNCTOR *upcall_functor, - ACE_Free_List > *freelist) - : gettimeofday_ (ACE_OS::gettimeofday), - delete_upcall_functor_ (upcall_functor == 0), - delete_free_list_ (freelist == 0), - timer_skew_ (0, ACE_TIMER_SKEW) -{ - ACE_TRACE ("ACE_Timer_Queue_T::ACE_Timer_Queue_T"); - - if (!freelist) - ACE_NEW (free_list_, - (ACE_Locked_Free_List,ACE_Null_Mutex>)); - else - free_list_ = freelist; - - if (!upcall_functor) - ACE_NEW (upcall_functor_, - FUNCTOR); - else - upcall_functor_ = upcall_functor; -} - -template -ACE_Timer_Queue_T::~ACE_Timer_Queue_T (void) -{ - ACE_TRACE ("ACE_Timer_Queue_T::~ACE_Timer_Queue_T"); - - // Cleanup the functor and free_list on the way out - if (this->delete_upcall_functor_) - delete this->upcall_functor_; - - if (this->delete_free_list_) - delete this->free_list_; -} - -template ACE_Timer_Node_T * -ACE_Timer_Queue_T::alloc_node (void) -{ - return this->free_list_->remove (); -} - -template void -ACE_Timer_Queue_T::free_node (ACE_Timer_Node_T *node) -{ - this->free_list_->add (node); -} - -template ACE_LOCK & -ACE_Timer_Queue_T::mutex (void) -{ - return this->mutex_; -} - -template long -ACE_Timer_Queue_T::schedule (const TYPE &type, - const void *act, - const ACE_Time_Value &future_time, - const ACE_Time_Value &interval) -{ - ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); - - // Schedule the timer. - long const result = - this->schedule_i (type, - act, - future_time, - interval); - - // Return on failure. - if (result == -1) - return result; - - // Inform upcall functor of successful registration. - this->upcall_functor ().registration (*this, - type, - act); - - // Return result; - return result; -} - -// Run the method for all Timers whose values are <= -// . -template int -ACE_Timer_Queue_T::expire (const ACE_Time_Value &cur_time) -{ - ACE_TRACE ("ACE_Timer_Queue_T::expire"); - ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); - - // Keep looping while there are timers remaining and the earliest - // timer is <= the passed in to the method. - - if (this->is_empty ()) - return 0; - - int number_of_timers_expired = 0; - int result = 0; - - ACE_Timer_Node_Dispatch_Info_T info; - - while ((result = this->dispatch_info_i (cur_time, info)) != 0) - { - const void *upcall_act = 0; - - this->preinvoke (info, cur_time, upcall_act); - - this->upcall (info, cur_time); - - this->postinvoke (info, cur_time, upcall_act); - - ++number_of_timers_expired; - - } - - ACE_UNUSED_ARG (result); - return number_of_timers_expired; -} - -template void -ACE_Timer_Queue_T::recompute_next_abs_interval_time - (ACE_Timer_Node_T *expired, - const ACE_Time_Value &cur_time) -{ - if ( expired->get_timer_value () <= cur_time ) - { - /* - * Somehow the current time is past when this time was - * supposed to expire (e.g., timer took too long, - * somebody changed system time, etc.). There used to - * be a simple loop here that skipped ahead one timer - * interval at a time, but that was horribly inefficient - * (an O(n) algorithm) when the timer duration was small - * relative to the amount of time skipped. - * - * So, we replace the loop with a simple computation, - * which also happens to be O(1). All times get - * normalized in the computation to microseconds. - * - * For reference, the loop looked like this: - * - * do - * expired->set_timer_value (expired->get_timer_value () + - * expired->get_interval ()); - * while (expired->get_timer_value () <= cur_time); - * - */ - - // Compute the duration of the timer's interval - ACE_UINT64 interval_usec; - expired->get_interval ().to_usec (interval_usec); - - // Compute the span between the current time and when - // the timer would have expired in the past (and - // normalize to microseconds). - ACE_Time_Value old_diff = cur_time - expired->get_timer_value (); - ACE_UINT64 old_diff_usec; - old_diff.to_usec (old_diff_usec); - - // Compute the delta time in the future when the timer - // should fire as if it had advanced incrementally. The - // modulo arithmetic accomodates the likely case that - // the current time doesn't fall precisely on a timer - // firing interval. - ACE_UINT64 new_timer_usec = - interval_usec - (old_diff_usec % interval_usec); - - // Compute the absolute time in the future when this - // interval timer should expire. - ACE_Time_Value new_timer_value - (cur_time.sec () - + static_cast(new_timer_usec / ACE_ONE_SECOND_IN_USECS), - cur_time.usec () - + static_cast(new_timer_usec % ACE_ONE_SECOND_IN_USECS)); - - expired->set_timer_value (new_timer_value); - } -} - -template int -ACE_Timer_Queue_T::dispatch_info_i (const ACE_Time_Value &cur_time, - ACE_Timer_Node_Dispatch_Info_T &info) -{ - ACE_TRACE ("ACE_Timer_Queue_T::dispatch_info_i"); - - if (this->is_empty ()) - return 0; - - ACE_Timer_Node_T *expired = 0; - - if (this->earliest_time () <= cur_time) - { - expired = this->remove_first (); - - // Get the dispatch info - expired->get_dispatch_info (info); - - // Check if this is an interval timer. - if (expired->get_interval () > ACE_Time_Value::zero) - { - // Make sure that we skip past values that have already - // "expired". - this->recompute_next_abs_interval_time (expired, cur_time); - - // Since this is an interval timer, we need to reschedule - // it. - this->reschedule (expired); - } - else - { - // Call the factory method to free up the node. - this->free_node (expired); - } - - return 1; - } - - return 0; -} - -template void -ACE_Timer_Queue_T::return_node (ACE_Timer_Node_T *node) -{ - ACE_MT (ACE_GUARD (ACE_LOCK, ace_mon, this->mutex_)); - this->free_node (node); -} - - -template -ACE_Event_Handler_Handle_Timeout_Upcall::ACE_Event_Handler_Handle_Timeout_Upcall (void) -{ -} - -template -ACE_Event_Handler_Handle_Timeout_Upcall::~ACE_Event_Handler_Handle_Timeout_Upcall (void) -{ -} - -template int -ACE_Event_Handler_Handle_Timeout_Upcall::registration (TIMER_QUEUE &, - ACE_Event_Handler *event_handler, - const void *) -{ - event_handler->add_reference (); - return 0; -} - -template int -ACE_Event_Handler_Handle_Timeout_Upcall::preinvoke (TIMER_QUEUE & /* timer_queue */, - ACE_Event_Handler *event_handler, - const void * /* timer_act */, - int /* recurring_timer */, - const ACE_Time_Value & /* cur_time */, - const void *&upcall_act) -{ - bool const requires_reference_counting = - event_handler->reference_counting_policy ().value () == - ACE_Event_Handler::Reference_Counting_Policy::ENABLED; - - if (requires_reference_counting) - { - event_handler->add_reference (); - - upcall_act = &this->requires_reference_counting_; - } - - return 0; -} - -template int -ACE_Event_Handler_Handle_Timeout_Upcall::postinvoke (TIMER_QUEUE & /* timer_queue */, - ACE_Event_Handler *event_handler, - const void * /* timer_act */, - int /* recurring_timer */, - const ACE_Time_Value & /* cur_time */, - const void *upcall_act) -{ - if (upcall_act == &this->requires_reference_counting_) - { - event_handler->remove_reference (); - } - - return 0; -} - -template int -ACE_Event_Handler_Handle_Timeout_Upcall::timeout (TIMER_QUEUE &timer_queue, - ACE_Event_Handler *event_handler, - const void *act, - int recurring_timer, - const ACE_Time_Value &cur_time) -{ - int requires_reference_counting = 0; - - if (!recurring_timer) - { - requires_reference_counting = - event_handler->reference_counting_policy ().value () == - ACE_Event_Handler::Reference_Counting_Policy::ENABLED; - } - - // Upcall to the s handle_timeout method. - if (event_handler->handle_timeout (cur_time, act) == -1) - { - if (event_handler->reactor_timer_interface ()) - event_handler->reactor_timer_interface ()->cancel_timer (event_handler, 0); - else - timer_queue.cancel (event_handler, 0); // 0 means "call handle_close()". - } - - if (!recurring_timer && - requires_reference_counting) - { - event_handler->remove_reference (); - } - - return 0; -} - -template int -ACE_Event_Handler_Handle_Timeout_Upcall::cancel_type (TIMER_QUEUE &, - ACE_Event_Handler *event_handler, - int dont_call, - int &requires_reference_counting) -{ - requires_reference_counting = - event_handler->reference_counting_policy ().value () == - ACE_Event_Handler::Reference_Counting_Policy::ENABLED; - - // Upcall to the s handle_close method - if (dont_call == 0) - event_handler->handle_close (ACE_INVALID_HANDLE, - ACE_Event_Handler::TIMER_MASK); - - return 0; -} - -template int -ACE_Event_Handler_Handle_Timeout_Upcall::cancel_timer (TIMER_QUEUE &, - ACE_Event_Handler *event_handler, - int, - int requires_reference_counting) -{ - if (requires_reference_counting) - event_handler->remove_reference (); - - return 0; -} - -template int -ACE_Event_Handler_Handle_Timeout_Upcall::deletion (TIMER_QUEUE &timer_queue, - ACE_Event_Handler *event_handler, - const void *) -{ - int requires_reference_counting = 0; - - this->cancel_type (timer_queue, - event_handler, - 0, - requires_reference_counting); - - this->cancel_timer (timer_queue, - event_handler, - 0, - requires_reference_counting); - - return 0; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_TIMER_QUEUE_T_CPP */ diff --git a/externals/ace/Timer_Queue_T.h b/externals/ace/Timer_Queue_T.h deleted file mode 100644 index 5e316e1e04b..00000000000 --- a/externals/ace/Timer_Queue_T.h +++ /dev/null @@ -1,566 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Timer_Queue_T.h - * - * $Id: Timer_Queue_T.h 89254 2010-02-25 22:10:39Z cleeland $ - * - * @author Doug Schmidt - * @author Irfan Pyarali and - * @author Darrell Brunsch - */ -//============================================================================= - -#ifndef ACE_TIMER_QUEUE_T_H -#define ACE_TIMER_QUEUE_T_H -#include /**/ "ace/pre.h" - -#include "ace/Free_List.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Event_Handler.h" -#include "ace/Time_Value.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Timer_Node_Dispatch_Info_T - * - * @brief Maintains generated dispatch information for Timer nodes. - * - */ -template -class ACE_Timer_Node_Dispatch_Info_T -{ -public: - /// The type of object held in the queue - TYPE type_; - - /// Asynchronous completion token associated with the timer. - const void *act_; - - /// Flag to check if the timer is recurring. - int recurring_timer_; -}; - -/** - * @class ACE_Timer_Node_T - * - * @brief Maintains the state associated with a Timer entry. - */ -template -class ACE_Timer_Node_T -{ -public: - /// Default constructor - ACE_Timer_Node_T (void); - - /// Destructor - ~ACE_Timer_Node_T (void); - - /// Useful typedef .. - typedef ACE_Timer_Node_Dispatch_Info_T DISPATCH_INFO; - - /// Singly linked list - void set (const TYPE &type, - const void *a, - const ACE_Time_Value &t, - const ACE_Time_Value &i, - ACE_Timer_Node_T *n, - long timer_id); - - /// Doubly linked list version - void set (const TYPE &type, - const void *a, - const ACE_Time_Value &t, - const ACE_Time_Value &i, - ACE_Timer_Node_T *p, - ACE_Timer_Node_T *n, - long timer_id); - - // = Accessors - - /// Get the type. - TYPE &get_type (void); - - /// Set the type. - void set_type (TYPE &type); - - /// Get the asynchronous completion token. - const void *get_act (void); - - /// Set the asynchronous completion token. - void set_act (void *act); - - /// Get the timer value. - const ACE_Time_Value &get_timer_value (void) const; - - /// Set the timer value. - void set_timer_value (const ACE_Time_Value &timer_value); - - /// Get the timer interval. - const ACE_Time_Value &get_interval (void) const; - - /// Set the timer interval. - void set_interval (const ACE_Time_Value &interval); - - /// Get the previous pointer. - ACE_Timer_Node_T *get_prev (void); - - /// Set the previous pointer. - void set_prev (ACE_Timer_Node_T *prev); - - /// Get the next pointer. - ACE_Timer_Node_T *get_next (void); - - /// Set the next pointer. - void set_next (ACE_Timer_Node_T *next); - - /// Get the timer_id. - long get_timer_id (void) const; - - /// Set the timer_id. - void set_timer_id (long timer_id); - - /// Get the dispatch info. The dispatch information is got - /// through . This form helps us in preventing allocation and - /// deleting data along the criticl path. - /// @@TODO: We may want to have a copying version too, so that our - /// interface will be complete.. - void get_dispatch_info (ACE_Timer_Node_Dispatch_Info_T &info); - - /// Dump the state of an TYPE. - void dump (void) const; - -private: - /// Type of object stored in the Queue - TYPE type_; - - /// Asynchronous completion token associated with the timer. - const void *act_; - - /// Time until the timer expires. - ACE_Time_Value timer_value_; - - /// If this is a periodic timer this holds the time until the next - /// timeout. - ACE_Time_Value interval_; - - /// Pointer to previous timer. - ACE_Timer_Node_T *prev_; - - /// Pointer to next timer. - ACE_Timer_Node_T *next_; - - /// Id of this timer (used to cancel timers before they expire). - long timer_id_; -}; - -/** - * @class ACE_Timer_Queue_Iterator_T - * - * @brief Generic interface for iterating over a subclass of - * ACE_Timer_Queue. - * - * This is a generic iterator that can be used to visit every - * node of a timer queue. Be aware that it isn't guaranteed - * that the transversal will be in order of timeout values. - */ -template -class ACE_Timer_Queue_Iterator_T -{ -public: - // = Initialization and termination methods. - /// Constructor. - ACE_Timer_Queue_Iterator_T (void); - - /// Destructor. - virtual ~ACE_Timer_Queue_Iterator_T (void); - - /// Positions the iterator at the earliest node in the Timer Queue - virtual void first (void) = 0; - - /// Positions the iterator at the next node in the Timer Queue - virtual void next (void) = 0; - - /// Returns true when there are no more nodes in the sequence - virtual bool isdone (void) const = 0; - - /// Returns the node at the current position in the sequence - virtual ACE_Timer_Node_T *item (void) = 0; -}; - -/** - * @class ACE_Timer_Queue_T - * - * @brief Provides an interface to timers. - * - * This is an abstract base class that provides hook for - * implementing specialized policies such as ACE_Timer_List - * and ACE_Timer_Heap. - */ -template -class ACE_Timer_Queue_T -{ -public: - /// Type of Iterator. - typedef ACE_Timer_Queue_Iterator_T ITERATOR; - - // = Initialization and termination methods. - /** - * Default constructor. @a upcall_functor is the instance of the - * FUNCTOR to be used by the queue. If @a upcall_functor is 0, Timer - * Queue will create a default FUNCTOR. @a freelist the freelist of - * timer nodes. If 0, then a default freelist will be created. - */ - ACE_Timer_Queue_T (FUNCTOR *upcall_functor = 0, - ACE_Free_List > *freelist = 0); - - /// Destructor - make virtual for proper destruction of inherited - /// classes. - virtual ~ACE_Timer_Queue_T (void); - - /// True if queue is empty, else false. - virtual bool is_empty (void) const = 0; - - /// Returns the time of the earlier node in the Timer_Queue. Must - /// be called on a non-empty queue. - virtual const ACE_Time_Value &earliest_time (void) const = 0; - - /** - * Schedule @a type that will expire at @a future_time, which is - * specified in absolute time. If it expires then @a act is passed - * in as the value to the . If @a interval is != to - * ACE_Time_Value::zero then it is used to reschedule the @a type - * automatically, using relative time to the current . - * This method returns a that uniquely identifies the the - * @a type entry in an internal list. This can be used to - * cancel the timer before it expires. The cancellation ensures - * that are unique up to values of greater than 2 - * billion timers. As long as timers don't stay around longer than - * this there should be no problems with accidentally deleting the - * wrong timer. Returns -1 on failure (which is guaranteed never to - * be a valid ). - */ - virtual long schedule (const TYPE &type, - const void *act, - const ACE_Time_Value &future_time, - const ACE_Time_Value &interval = ACE_Time_Value::zero); - - /** - * Resets the interval of the timer represented by @a timer_id to - * @a interval, which is specified in relative time to the current - * . If @a interval is equal to - * ACE_Time_Value::zero, the timer will become a non-rescheduling - * timer. Returns 0 if successful, -1 if not. - */ - virtual int reset_interval (long timer_id, - const ACE_Time_Value &interval) = 0; - - /** - * Cancel all timer associated with @a type. If - * @a dont_call_handle_close is 0 then the will be invoked, - * which typically invokes the hook. Returns number - * of timers cancelled. - */ - virtual int cancel (const TYPE &type, - int dont_call_handle_close = 1) = 0; - - /** - * Cancel the single timer that matches the @a timer_id value (which - * was returned from the method). If act is non-NULL - * then it will be set to point to the ``magic cookie'' argument - * passed in when the timer was registered. This makes it possible - * to free up the memory and avoid memory leaks. If - * @a dont_call_handle_close is 0 then the will be invoked, - * which typically calls the hook. Returns 1 if - * cancellation succeeded and 0 if the @a timer_id wasn't found. - */ - virtual int cancel (long timer_id, - const void **act = 0, - int dont_call_handle_close = 1) = 0; - - /** - * Run the for all timers whose values are <= @a current_time. - * This does not account for . Returns the number of - * timers canceled. - */ - virtual int expire (const ACE_Time_Value ¤t_time); - - /** - * Get the dispatch information for a timer whose value is <= @a current_time. - * This does not account for . Returns 1 if - * there is a node whose value <= @a current_time else returns a 0. - * - */ - virtual int dispatch_info (const ACE_Time_Value ¤t_time, - ACE_Timer_Node_Dispatch_Info_T &info); - - /** - * Run the for all timers whose values are <= - * . Also accounts for . - * - * Depending on the resolution of the underlying OS the system calls - * like select()/poll() might return at time different than that is - * specified in the timeout. Suppose the OS guarantees a resolution of t ms. - * The timeline will look like - * - * A B - * | | - * V V - * |-------------|-------------|-------------|-------------| - * t t t t t - * - * - * If you specify a timeout value of A, then the timeout will not occur - * at A but at the next interval of the timer, which is later than - * that is expected. Similarly, if your timeout value is equal to B, - * then the timeout will occur at interval after B. Now depending upon the - * resolution of your timeouts and the accuracy of the timeouts - * needed for your application, you should set the value of - * . In the above case, if you want the timeout A to fire - * no later than A, then you should specify your to be - * A % t. - * - * The timeout value should be specified via the macro ACE_TIMER_SKEW - * in your config.h file. The default value is zero. - * - * Things get interesting if the t before the timeout value B is zero - * i.e your timeout is less than the interval. In that case, you are - * almost sure of not getting the desired timeout behaviour. Maybe you - * should look for a better OS :-) - * - * Returns the number of timers canceled. - */ - - /* virtual */ int expire (void); - - /** - * Returns the current time of day. This method allows different - * implementations of the timer queue to use special high resolution - * timers. - */ - /* virtual */ ACE_Time_Value gettimeofday (void); - - /// Allows applications to control how the timer queue gets the time - /// of day. - void gettimeofday (ACE_Time_Value (*gettimeofday)(void)); - - /// Determine the next event to timeout. Returns @a max if there are - /// no pending timers or if all pending timers are longer than max. - /// This method acquires a lock internally since it modifies internal state. - virtual ACE_Time_Value *calculate_timeout (ACE_Time_Value *max); - - /** - * Determine the next event to timeout. Returns @a max if there are - * no pending timers or if all pending timers are longer than max. - * should be a pointer to storage for the timeout value, - * and this value is also returned. This method does not acquire a - * lock internally since it doesn't modify internal state. If you - * need to call this method when the queue is being modified - * concurrently, however, you should make sure to acquire the - * externally before making the call. - */ - virtual ACE_Time_Value *calculate_timeout (ACE_Time_Value *max, - ACE_Time_Value *the_timeout); - - /// Set the timer skew for the Timer_Queue. - void timer_skew (const ACE_Time_Value &skew); - - /// Get the timer skew for the Timer_Queue. - const ACE_Time_Value &timer_skew (void) const; - - /// Synchronization variable used by the queue - ACE_LOCK &mutex (void); - - /// Accessor to the upcall functor - FUNCTOR &upcall_functor (void); - - /// Returns a pointer to this ACE_Timer_Queue's iterator. - virtual ITERATOR &iter (void) = 0; - - /// Removes the earliest node from the queue and returns it - virtual ACE_Timer_Node_T *remove_first (void) = 0; - - /// Dump the state of a object. - virtual void dump (void) const; - - /// Reads the earliest node from the queue and returns it. - virtual ACE_Timer_Node_T *get_first (void) = 0; - - /// Method used to return a timer node to the queue's ownership - /// after it is returned by a method like . - virtual void return_node (ACE_Timer_Node_T *); - - /// This method will call the preinvoke() on . - void preinvoke (ACE_Timer_Node_Dispatch_Info_T &info, - const ACE_Time_Value &cur_time, - const void *&upcall_act); - - /// This method will call the timeout() on . - void upcall (ACE_Timer_Node_Dispatch_Info_T &info, - const ACE_Time_Value &cur_time); - - /// This method will call the postinvoke() on . - void postinvoke (ACE_Timer_Node_Dispatch_Info_T &info, - const ACE_Time_Value &cur_time, - const void *upcall_act); - -protected: - - /// Schedule a timer. - virtual long schedule_i (const TYPE &type, - const void *act, - const ACE_Time_Value &future_time, - const ACE_Time_Value &interval) = 0; - - /// Reschedule an "interval" ACE_Timer_Node. - virtual void reschedule (ACE_Timer_Node_T *) = 0; - - /// Factory method that allocates a new node. - virtual ACE_Timer_Node_T *alloc_node (void); - - /// Factory method that frees a previously allocated node. - virtual void free_node (ACE_Timer_Node_T *); - - /// Non-locking version of dispatch_info () - virtual int dispatch_info_i (const ACE_Time_Value ¤t_time, - ACE_Timer_Node_Dispatch_Info_T &info); - - /// Recompute when the next time is that this interval timer should fire. - void recompute_next_abs_interval_time (ACE_Timer_Node_T* expired, - const ACE_Time_Value &cur_time); - - /// Synchronization variable for ACE_Timer_Queue. - /// @note The right name would be lock_, but HP/C++ will choke on that! - ACE_LOCK mutex_; - - /// Class that implements a free list - ACE_Free_List > *free_list_; - - /// Pointer to function that returns the current time of day. - ACE_Time_Value (*gettimeofday_)(void); - - /// Upcall functor - FUNCTOR *upcall_functor_; - - /// To delete or not to delete is the question? - bool const delete_upcall_functor_; - - /// Flag to delete only if the class created the - bool const delete_free_list_; - -private: - - /// Returned by . - ACE_Time_Value timeout_; - - /// Adjusts for timer skew in various clocks. - ACE_Time_Value timer_skew_; - - // = Don't allow these operations for now. - ACE_UNIMPLEMENTED_FUNC (ACE_Timer_Queue_T (const ACE_Timer_Queue_T &)) - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Timer_Queue_T &)) -}; - -/** - * @class ACE_Event_Handler_Handle_Timeout_Upcall - * - * @brief Functor for Timer_Queues. - * - * This class implements the functor required by the Timer - * Queue to call on ACE_Event_Handlers. - */ -template -class ACE_Event_Handler_Handle_Timeout_Upcall -{ -public: - typedef ACE_Timer_Queue_T, - ACE_LOCK> - TIMER_QUEUE; - - // = Initialization and termination methods. - /// Constructor. - ACE_Event_Handler_Handle_Timeout_Upcall (void); - - /// Destructor. - ~ACE_Event_Handler_Handle_Timeout_Upcall (void); - - /// This method is called when a timer is registered. - int registration (TIMER_QUEUE &timer_queue, - ACE_Event_Handler *handler, - const void *arg); - - /// This method is called before the timer expires. - int preinvoke (TIMER_QUEUE &timer_queue, - ACE_Event_Handler *handler, - const void *arg, - int recurring_timer, - const ACE_Time_Value &cur_time, - const void *&upcall_act); - - /// This method is called when the timer expires. - int timeout (TIMER_QUEUE &timer_queue, - ACE_Event_Handler *handler, - const void *arg, - int recurring_timer, - const ACE_Time_Value &cur_time); - - /// This method is called after the timer expires. - int postinvoke (TIMER_QUEUE &timer_queue, - ACE_Event_Handler *handler, - const void *arg, - int recurring_timer, - const ACE_Time_Value &cur_time, - const void *upcall_act); - - /// This method is called when a handler is cancelled - int cancel_type (TIMER_QUEUE &timer_queue, - ACE_Event_Handler *handler, - int dont_call, - int &requires_reference_counting); - - /// This method is called when a timer is cancelled - int cancel_timer (TIMER_QUEUE &timer_queue, - ACE_Event_Handler *handler, - int dont_call, - int requires_reference_counting); - - /// This method is called when the timer queue is destroyed and - /// the timer is still contained in it - int deletion (TIMER_QUEUE &timer_queue, - ACE_Event_Handler *handler, - const void *arg); - -private: - - /// Flag indicating that reference counting is required for this - /// event handler upcall. - int requires_reference_counting_; - - // = Don't allow these operations for now. - ACE_UNIMPLEMENTED_FUNC (ACE_Event_Handler_Handle_Timeout_Upcall (const ACE_Event_Handler_Handle_Timeout_Upcall &)) - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Event_Handler_Handle_Timeout_Upcall &)) -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Timer_Queue_T.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Timer_Queue_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Timer_Queue_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" -#endif /* ACE_TIMER_QUEUE_T_H */ diff --git a/externals/ace/Timer_Queue_T.inl b/externals/ace/Timer_Queue_T.inl deleted file mode 100644 index 7606a2e1f62..00000000000 --- a/externals/ace/Timer_Queue_T.inl +++ /dev/null @@ -1,222 +0,0 @@ -// -*- C++ -*- -// -// $Id: Timer_Queue_T.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template ACE_INLINE void -ACE_Timer_Node_T::set (const TYPE &type, - const void *a, - const ACE_Time_Value &t, - const ACE_Time_Value &i, - ACE_Timer_Node_T *n, - long timer_id) -{ - this->type_ = type; - this->act_ = a; - this->timer_value_ = t; - this->interval_ = i; - this->next_ = n; - this->timer_id_ = timer_id; -} - -template ACE_INLINE void -ACE_Timer_Node_T::set (const TYPE &type, - const void *a, - const ACE_Time_Value &t, - const ACE_Time_Value &i, - ACE_Timer_Node_T *p, - ACE_Timer_Node_T *n, - long timer_id) -{ - this->type_ = type; - this->act_ = a; - this->timer_value_ = t; - this->interval_ = i; - this->prev_ = p; - this->next_ = n; - this->timer_id_ = timer_id; -} - -template ACE_INLINE TYPE & -ACE_Timer_Node_T::get_type (void) -{ - return this->type_; -} - -template ACE_INLINE void -ACE_Timer_Node_T::set_type (TYPE &type) -{ - this->type_ = type; -} - -template ACE_INLINE const void * -ACE_Timer_Node_T::get_act (void) -{ - return this->act_; -} - -template ACE_INLINE void -ACE_Timer_Node_T::set_act (void *act) -{ - this->act_ = act; -} - -template ACE_INLINE const ACE_Time_Value & -ACE_Timer_Node_T::get_timer_value (void) const -{ - return this->timer_value_; -} - -template ACE_INLINE void -ACE_Timer_Node_T::set_timer_value (const ACE_Time_Value &timer_value) -{ - this->timer_value_ = timer_value; -} - -template ACE_INLINE const ACE_Time_Value & -ACE_Timer_Node_T::get_interval (void) const -{ - return this->interval_; -} - -template ACE_INLINE void -ACE_Timer_Node_T::set_interval (const ACE_Time_Value &interval) -{ - this->interval_ = interval; -} - -template ACE_INLINE ACE_Timer_Node_T * -ACE_Timer_Node_T::get_prev (void) -{ - return this->prev_; -} - -template ACE_INLINE void -ACE_Timer_Node_T::set_prev (ACE_Timer_Node_T *prev) -{ - this->prev_ = prev; -} - -template ACE_INLINE ACE_Timer_Node_T * -ACE_Timer_Node_T::get_next (void) -{ - return this->next_; -} - -template ACE_INLINE void -ACE_Timer_Node_T::set_next (ACE_Timer_Node_T *next) -{ - this->next_ = next; -} - -template ACE_INLINE long -ACE_Timer_Node_T::get_timer_id (void) const -{ - return this->timer_id_; -} - -template ACE_INLINE void -ACE_Timer_Node_T::set_timer_id (long timer_id) -{ - this->timer_id_ = timer_id; -} - -template ACE_INLINE void -ACE_Timer_Node_T::get_dispatch_info (ACE_Timer_Node_Dispatch_Info_T &info) -{ - // Yes, do a copy - info.type_ = this->type_; - info.act_ = this->act_; - info.recurring_timer_ = - this->interval_ > ACE_Time_Value::zero; -} - -template ACE_INLINE void -ACE_Timer_Queue_T::timer_skew (const ACE_Time_Value &skew) -{ - timer_skew_ = skew; -} - -template ACE_INLINE const ACE_Time_Value & -ACE_Timer_Queue_T::timer_skew (void) const -{ - return timer_skew_; -} - -template ACE_INLINE int -ACE_Timer_Queue_T::expire (void) -{ - if (!this->is_empty ()) - return this->expire (this->gettimeofday () + timer_skew_); - else - return 0; -} - -template int -ACE_Timer_Queue_T::dispatch_info (const ACE_Time_Value &cur_time, - ACE_Timer_Node_Dispatch_Info_T &info) -{ - ACE_TRACE ("ACE_Timer_Queue_T::dispatch_info"); - ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, 0)); - - return this->dispatch_info_i (cur_time, info); -} - -template ACE_INLINE void -ACE_Timer_Queue_T::upcall (ACE_Timer_Node_Dispatch_Info_T &info, - const ACE_Time_Value &cur_time) -{ - this->upcall_functor ().timeout (*this, - info.type_, - info.act_, - info.recurring_timer_, - cur_time); -} - -template ACE_INLINE void -ACE_Timer_Queue_T::preinvoke (ACE_Timer_Node_Dispatch_Info_T &info, - const ACE_Time_Value &cur_time, - const void *&upcall_act) -{ - this->upcall_functor ().preinvoke (*this, - info.type_, - info.act_, - info.recurring_timer_, - cur_time, - upcall_act); -} - -template ACE_INLINE void -ACE_Timer_Queue_T::postinvoke (ACE_Timer_Node_Dispatch_Info_T &info, - const ACE_Time_Value &cur_time, - const void *upcall_act) -{ - this->upcall_functor ().postinvoke (*this, - info.type_, - info.act_, - info.recurring_timer_, - cur_time, - upcall_act); -} - -template ACE_INLINE ACE_Time_Value -ACE_Timer_Queue_T::gettimeofday (void) -{ - // Invoke gettimeofday via pointer to function. - return this->gettimeofday_ (); -} - -template ACE_INLINE void -ACE_Timer_Queue_T::gettimeofday (ACE_Time_Value (*gettimeofday)(void)) -{ - this->gettimeofday_ = gettimeofday; -} - -template ACE_INLINE FUNCTOR & -ACE_Timer_Queue_T::upcall_functor (void) -{ - return *this->upcall_functor_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Timer_Queuefwd.h b/externals/ace/Timer_Queuefwd.h deleted file mode 100644 index 662f29c0411..00000000000 --- a/externals/ace/Timer_Queuefwd.h +++ /dev/null @@ -1,38 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Timer_Queuefwd.h - * - * $Id: Timer_Queuefwd.h 80826 2008-03-04 14:51:23Z wotte $ - * - * Forward declarations and typedefs of ACE_Timer_Queue class. - * - * @author Ossama Othman - */ -//============================================================================= - -#ifndef ACE_TIMER_QUEUE_FWD_H -#define ACE_TIMER_QUEUE_FWD_H - -#include /**/ "ace/pre.h" - -#include "ace/Synch_Traits.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template class ACE_Timer_Queue_T; -template class ACE_Event_Handler_Handle_Timeout_Upcall; - -class ACE_Event_Handler; - -typedef ACE_Timer_Queue_T, - ACE_SYNCH_RECURSIVE_MUTEX> - ACE_Timer_Queue; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" - -#endif /* ACE_TIMER_QUEUE_FWD_H */ diff --git a/externals/ace/Timer_Wheel.h b/externals/ace/Timer_Wheel.h deleted file mode 100644 index 21ba8776102..00000000000 --- a/externals/ace/Timer_Wheel.h +++ /dev/null @@ -1,42 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Timer_Wheel.h - * - * $Id: Timer_Wheel.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Darrell Brunsch (brunsch@cs.wustl.edu) - */ -//============================================================================= - - -#ifndef ACE_TIMER_WHEEL_H -#define ACE_TIMER_WHEEL_H -#include /**/ "ace/pre.h" - -#include "ace/Timer_Wheel_T.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// The following typedefs are here for ease of use and backward -// compatibility. - -typedef ACE_Timer_Wheel_T, - ACE_SYNCH_RECURSIVE_MUTEX> - ACE_Timer_Wheel; - -typedef ACE_Timer_Wheel_Iterator_T, - ACE_SYNCH_RECURSIVE_MUTEX> - ACE_Timer_Wheel_Iterator; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" -#endif /* ACE_TIMER_WHEEL_H */ diff --git a/externals/ace/Timer_Wheel_T.cpp b/externals/ace/Timer_Wheel_T.cpp deleted file mode 100644 index 529cc456d50..00000000000 --- a/externals/ace/Timer_Wheel_T.cpp +++ /dev/null @@ -1,964 +0,0 @@ -// $Id: Timer_Wheel_T.cpp 89254 2010-02-25 22:10:39Z cleeland $ - -#ifndef ACE_TIMER_WHEEL_T_CPP -#define ACE_TIMER_WHEEL_T_CPP - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/OS_NS_sys_time.h" -#include "ace/Guard_T.h" -#include "ace/Timer_Wheel_T.h" -#include "ace/Log_Msg.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Design/implementation notes for ACE_Timer_Wheel_T. -// -// Each timer queue entry is represented by a ACE_Timer_Node. -// The timing wheel is divided into a number of "spokes"; there are -// spoke_count_ spokes in the wheel. Each timer is hashed into one of the -// spokes. Entries within each spoke are linked in a double-linked list -// in order of increasing expiration. The first ACE_Timer_Node in each -// spoke is a "dummy node" that marks the end of the list of ACE_Timer_Nodes -// in that spoke. -// -// The timer ID for a scheduled timer is formed by its spoke position in -// the wheel, and the number of timers that have been inserted in that spoke -// since the queue was initialized. N bits of the long timer_id are used -// to determine the spoke, and M bits are used as a counter. -// Each time a Node is inserted into a spoke, it's counter -// is incremented. The count is kept in the timer ID field -// of the dummy root Node. In the event of overflow of the counter, the spoke -// must be searched for each new id to make sure it's not already in use. To -// prevent having to do an exhaustive search each time, we keep extra data -// in the dummy root Node. -/** -* Default Constructor that sets defaults for spoke_count_ and resolution_ -* and doesn't do any preallocation. -* -* @param upcall_functor A pointer to a functor to use instead of the default -* @param freelist A pointer to a freelist to use instead of the default -*/ -template -ACE_Timer_Wheel_T::ACE_Timer_Wheel_T -(FUNCTOR* upcall_functor - , FreeList* freelist - ) -: Base (upcall_functor, freelist) -, spokes_(0) -, spoke_count_(0) // calculated in open_i -, spoke_bits_(0) -, res_bits_ (0) -, earliest_spoke_ (0) -, iterator_(0) -, timer_count_(0) -{ - ACE_TRACE ("ACE_Timer_Wheel_T::ACE_Timer_Wheel_T"); - this->open_i (0, - ACE_DEFAULT_TIMER_WHEEL_SIZE, - ACE_DEFAULT_TIMER_WHEEL_RESOLUTION); -} - -/** -* Constructor that sets up the timing wheel and also may preallocate -* some nodes on the free list -* -* @param spoke_count The number of lists in the timer wheel -* @param resolution The time resolution in milliseconds used by the hashing function -* @param prealloc The number of entries to prealloc in the free_list -* @param upcall_functor A pointer to a functor to use instead of the default -* @param freelist A pointer to a freelist to use instead of the default -*/ -template -ACE_Timer_Wheel_T::ACE_Timer_Wheel_T - (u_int spoke_count, - u_int resolution, - size_t prealloc, - FUNCTOR* upcall_functor, - FreeList* freelist) -: Base (upcall_functor, freelist) -, spokes_ (0) -, spoke_count_ (0) // calculated in open_i -, spoke_bits_ (0) -, res_bits_ (0) -, earliest_spoke_ (0) -, iterator_ (0) -, timer_count_ (0) -{ - ACE_TRACE ("ACE_Timer_Wheel_T::ACE_Timer_Wheel_T"); - this->open_i (prealloc, spoke_count, resolution); -} - -template int -ACE_Timer_Wheel_T::power2bits (int n, - int min_bits, - int max_bits) -{ - int max = (1 << max_bits) - 1; - if (n > max) - return max_bits; - - // count the bits in n. - int i = 0; - int tmp = n; - do - { - tmp >>= 1; - ++i; - } - while (tmp != 0); - - if (i <= min_bits) - return min_bits; - - // Which is nearest? - int a = (1 << i) - n; - int b = (1 << (i - 1)) - n; - if (b < 0) - b = -b; - if (b < a) - return i - 1; - return i; -} - -/** -* Initialize the queue. Uses the established members for all needed -* information. -*/ -template void -ACE_Timer_Wheel_T::open_i - (size_t prealloc, u_int spokes, u_int res) -{ - ACE_TRACE ("ACE_Timer_Wheel_T::open_i"); - - this->gettimeofday (ACE_OS::gettimeofday); - - // Rather than waste bits in our timer id, we might as well round up - // the spoke count to the next power of two - 1 . (i.e 1,3,7,15,...127,etc.) - const int MIN_SPOKE_BITS = 3; // Allow between 8 and 4096 spokes - const int MAX_SPOKE_BITS = 12; - const int MAX_RES_BITS = 20; // 20 is plenty, even on 64 bit platforms. - - this->spoke_bits_ = power2bits (spokes, MIN_SPOKE_BITS, MAX_SPOKE_BITS); - this->res_bits_ = power2bits (res, 1, MAX_RES_BITS); - - this->spoke_count_ = 1 << this->spoke_bits_; - - this->free_list_->resize (prealloc + this->spoke_count_); - - this->wheel_time_.msec (1 << (this->res_bits_)); - - ACE_NEW (this->spokes_, ACE_Timer_Node_T* [this->spoke_count_]); - - // Create the root nodes. These will be treated specially - for (u_int i = 0; i < this->spoke_count_; ++i) - { - ACE_Timer_Node_T* root = this->alloc_node (); - root->set (0, 0, ACE_Time_Value::zero, ACE_Time_Value::zero, root, root, 0); - this->spokes_[i] = root; - } - - ACE_NEW (iterator_, Iterator (*this)); -} - -/// Destructor just cleans up its memory -template -ACE_Timer_Wheel_T::~ACE_Timer_Wheel_T (void) -{ - ACE_TRACE ("ACE_Timer_Wheel_T::~ACE_Timer_Wheel_T"); - - delete iterator_; - - for (u_int i = 0; i < this->spoke_count_; ++i) - { - // Free all the nodes starting at the root - ACE_Timer_Node_T* root = this->spokes_[i]; - for (ACE_Timer_Node_T* n = root->get_next (); n != root;) - { - ACE_Timer_Node_T* next = n->get_next (); - this->upcall_functor ().deletion (*this, - n->get_type (), - n->get_act ()); - this->free_node (n); - n = next; - } - delete root; - } - delete[] this->spokes_; -} - -/// Searches for a node by timer_id within one spoke. -template -ACE_Timer_Node_T* -ACE_Timer_Wheel_T::find_spoke_node - (u_int spoke, long timer_id) const -{ - ACE_Timer_Node_T* root = this->spokes_[spoke]; - for (ACE_Timer_Node_T* n = root->get_next (); - n != root; - n = n->get_next ()) - { - if (n->get_timer_id () == timer_id) - return n; - } - return 0; -} - -/// Searches all spokes for a node matching the specified timer_id -/// Uses the spoke encoded in the timer_id as a starting place. -template -ACE_Timer_Node_T* -ACE_Timer_Wheel_T::find_node (long timer_id) const -{ - if (timer_id == -1) - return 0; - - // Search the spoke where timer_id was originally scheduled - u_int spoke_mask = this->spoke_count_ - 1; - u_int start = timer_id & spoke_mask; - ACE_Timer_Node_T* n = this->find_spoke_node (start, timer_id); - if (n != 0) - return n; - - //ACE_ERROR((LM_ERROR, "Node not found in original spoke.\n")); - - // Search the rest of the spokes - for (u_int i = 0; i < this->spoke_count_; ++i) - { - if (i != start) - { // already searched this one - n = this->find_spoke_node (i, timer_id); - if (n != 0) - return n; - } - } - - //ACE_ERROR((LM_ERROR, "Node not found.\n")); - return 0; -} - -/** -* Check to see if the wheel is empty -* -* @return True if empty -*/ -template bool -ACE_Timer_Wheel_T::is_empty (void) const -{ - ACE_TRACE ("ACE_Timer_Wheel_T::is_empty"); - return timer_count_ == 0; -} - - -/** -* @return First (earliest) node in the wheel_'s earliest_spoke_ list -*/ -template const ACE_Time_Value & -ACE_Timer_Wheel_T::earliest_time (void) const -{ - ACE_TRACE ("ACE_Timer_Wheel_T::earliest_time"); - ACE_Timer_Node_T* n = this->get_first_i (); - if (n != 0) - return n->get_timer_value (); - return ACE_Time_Value::zero; -} - -/// Uses a simple hash to find which spoke to use based on when the -/// timer is due to expire. Hopefully the 64bit int operations avoid -/// any overflow problems. -template u_int -ACE_Timer_Wheel_T::calculate_spoke - (const ACE_Time_Value& t) const -{ - return static_cast ((t.msec () >> this->res_bits_) & (this->spoke_count_ - 1)); -} - -/// Generates a unique timer_id for the given spoke. It should be pretty -/// fast until the point where the counter overflows. At that time you -/// have to do exhaustive searches within the spoke to ensure that a particular -/// timer id is not already in use. Some optimizations are in place so -/// that this hopefully doesn't have to happen often. -template long -ACE_Timer_Wheel_T::generate_timer_id (u_int spoke) -{ - - int cnt_bits = sizeof (long) * 8 - this->spoke_bits_; - long max_cnt = ((long)1 << cnt_bits) - 1; - if (spoke == this->spoke_count_) - --max_cnt; // Because -1 is used as a special invalid timer_id. - - ACE_Timer_Node_T* root = this->spokes_[spoke]; - - if (root == root->get_next ()) - root->set_act(0); - - // We use this field to keep track of the next counter value that - // may be in use. Of course it may have expired, so we just use - // this field so that we know when we don't have to check for duplicates -#if defined (ACE_WIN64) - // The cast below is legit... we know that long is shorter than a - // pointer, but are only using it as a 'long' storage area. -# pragma warning(push) -# pragma warning(disable : 4311) -#endif /* ACE_WIN64 */ - long next_cnt = reinterpret_cast (root->get_act ()); -#if defined (ACE_WIN64) -# pragma warning(pop) -#endif /* ACE_WIN64 */ - - // This field is used as a counter instead of a timer_id. - long cnt = root->get_timer_id (); - - if (cnt >= max_cnt && root == root->get_next ()) - { - // Special case when we overflow on an empty spoke. We can just - // wrap the count around without searching for duplicates. We only - // want to do this when the counter overflows, so that we return - // unique timer_id values as often as possible. - root->set_timer_id (1); - return spoke; - } - else if (cnt >= max_cnt) - { // overflow - cnt = 0; // try again starting at zero - } - else if (next_cnt == 0 || cnt < next_cnt) - { - root->set_timer_id (cnt + 1); - return (cnt << this->spoke_bits_) | spoke; - } - - //ACE_ERROR((LM_ERROR, "Timer id overflow. We have to search now.\n")); - - // We've run out of consecutive id numbers so now we have to search - // for a unique id. - // We'll try increasing numbers until we find one that is not in use, - // and we'll record the next highest number so that we can avoid this - // search as often as possible. - for (; cnt < max_cnt - 1; ++cnt) - { - long id = (cnt << this->spoke_bits_) | spoke; - ACE_Timer_Node_T* n = this->find_spoke_node (spoke, id); - if (n == 0) - { - root->set_timer_id (cnt + 1); - // Now we need to find the next highest cnt in use - next_cnt = 0; - for (; n != root; n = n->get_next ()) - { - long tmp = n->get_timer_id () >> this->spoke_bits_; - if (tmp > cnt && (tmp < next_cnt || next_cnt == 0)) - next_cnt = tmp; - } -#if defined (ACE_WIN64) - // The cast below is legit... we know we're storing a long in - // a pointer, but are only using it as a 'long' storage area. -# pragma warning(push) -# pragma warning(disable : 4312) -#endif /* ACE_WIN64 */ - root->set_act (reinterpret_cast (next_cnt)); -#if defined (ACE_WIN64) -# pragma warning(pop) -#endif /* ACE_WIN64 */ - return id; - } - } - - return -1; // We did our best, but the spoke is full. -} - -/** -* Creates a ACE_Timer_Node_T based on the input parameters. Then inserts -* the node into the wheel using reschedule (). Then returns a timer_id. -* -* @param type The data of the timer node -* @param act Asynchronous Completion Token (AKA magic cookie) -* @param future_time The time the timer is scheduled for (absolute time) -* @param interval If not ACE_Time_Value::zero, then this is a periodic -* timer and interval is the time period -* -* @return Unique identifier (can be used to cancel the timer). -* -1 on failure. -*/ -template long -ACE_Timer_Wheel_T::schedule_i (const TYPE& type, - const void* act, - const ACE_Time_Value& future_time, - const ACE_Time_Value& interval) -{ - ACE_TRACE ("ACE_Timer_Wheel_T::schedule_i"); - - ACE_Timer_Node_T* n = this->alloc_node (); - - if (n != 0) - { - u_int spoke = calculate_spoke (future_time); - long id = generate_timer_id (spoke); - - //ACE_ERROR((LM_ERROR, "Scheduling %x spoke:%d id:%d\n", (long) n, spoke, id)); - - if (id != -1) - { - n->set (type, act, future_time, interval, 0, 0, id); - this->schedule_i (n, spoke, future_time); - } - return id; - } - - // Failure return - errno = ENOMEM; - return -1; -} - -/** -* Takes an ACE_Timer_Node and inserts it into the correct position in -* the correct list. Also makes sure to update the earliest time. -* -* @param n The timer node to reschedule -*/ -template void -ACE_Timer_Wheel_T::reschedule (ACE_Timer_Node_T* n) -{ - ACE_TRACE ("ACE_Timer_Wheel_T::reschedule"); - const ACE_Time_Value& expire = n->get_timer_value (); - u_int spoke = calculate_spoke (expire); - this->schedule_i (n, spoke, expire); -} - -/// The shared scheduling functionality between schedule() and reschedule() -template void -ACE_Timer_Wheel_T::schedule_i - (ACE_Timer_Node_T* n, - u_int spoke, - const ACE_Time_Value& expire) -{ - // See if we need to update the earliest time - if (this->is_empty() || expire < this->earliest_time ()) - this->earliest_spoke_ = spoke; - - ACE_Timer_Node_T* root = this->spokes_[spoke]; - ACE_Timer_Node_T* last = root->get_prev (); - - ++timer_count_; - - // If the spoke is empty - if (last == root) { - n->set_prev (root); - n->set_next (root); - root->set_prev (n); - root->set_next (n); - return; - } - - // We always want to search backwards from the tail of the list, because - // this minimizes the search in the extreme case when lots of timers are - // scheduled for exactly the same time - ACE_Timer_Node_T* p = root->get_prev (); - while (p != root && p->get_timer_value () > expire) - p = p->get_prev (); - - // insert after - n->set_prev (p); - n->set_next (p->get_next ()); - p->get_next ()->set_prev (n); - p->set_next (n); -} - - -/** -* Find the timer node by using the id as a pointer. Then use set_interval() -* on the node to update the interval. -* -* @param timer_id The timer identifier -* @param interval The new interval -* -* @return 0 if successful, -1 if no. -*/ -template int -ACE_Timer_Wheel_T::reset_interval (long timer_id, - const ACE_Time_Value &interval - ) -{ - ACE_TRACE ("ACE_Timer_Wheel_T::reset_interval"); - ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); - ACE_Timer_Node_T* n = this->find_node (timer_id); - if (n != 0) - { - // The interval will take effect the next time this node is expired. - n->set_interval (interval); - return 0; - } - return -1; -} - - -/** -* Goes through every list in the wheel and whenever we find one with the -* correct type value, we remove it and continue. At the end make sure -* we reset the earliest time value in case the earliest timers were -* removed. -* -* @param type The value to search for. -* @param skip_close If this non-zero, the cancellation method of the -* functor will not be called for each cancelled timer. -* -* @return Number of timers cancelled -*/ -template int -ACE_Timer_Wheel_T::cancel (const TYPE& type, int skip_close) -{ - ACE_TRACE ("ACE_Timer_Wheel_T::cancel"); - - int num_canceled = 0; // Note : Technically this can overflow. - int cookie = 0; - - ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); - - if (!this->is_empty ()) - { - ACE_Timer_Node_T* first = this->get_first (); - ACE_Time_Value last = first->get_timer_value (); - int recalc = 0; - - for (u_int i = 0; i < this->spoke_count_; ++i) - { - ACE_Timer_Node_T* root = this->spokes_[i]; - for (ACE_Timer_Node_T* n = root->get_next (); n != root; ) - { - if (n->get_type () == type) - { - ++num_canceled; - if (n == first) - recalc = 1; - - ACE_Timer_Node_T* tmp = n; - n = n->get_next (); - - this->cancel_i (tmp); - } - else - { - n = n->get_next (); - } - } - } - - if (recalc) - this->recalc_earliest (last); - } - - // Call the close hooks. - - // cancel_type() called once per . - this->upcall_functor ().cancel_type (*this, - type, - skip_close, - cookie); - - for (int i = 0; - i < num_canceled; - ++i) - { - // cancel_timer() called once per . - this->upcall_functor ().cancel_timer (*this, - type, - skip_close, - cookie); - } - - return num_canceled; -} - - -/** -* Cancels the single timer that is specified by the timer_id. In this -* case the timer_id is actually a pointer to the node, so we cast it -* to the node. This can be dangerous if the timer_id is made up -* (or deleted twice) so we do a little sanity check. Finally we update -* the earliest time in case the earliest timer was removed. -* -* @param timer_id Timer Identifier -* @param act Asychronous Completion Token (AKA magic cookie): -* If this is non-zero, stores the magic cookie of -* the cancelled timer here. -* @param skip_close If this non-zero, the cancellation method of the -* functor will not be called. -* -* @return 1 for sucess and 0 if the timer_id wasn't found (or was -* found to be invalid) -*/ -template int -ACE_Timer_Wheel_T::cancel (long timer_id, - const void **act, - int skip_close) -{ - ACE_TRACE ("ACE_Timer_Wheel_T::cancel"); - ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); - ACE_Timer_Node_T* n = this->find_node (timer_id); - if (n != 0) - { - ACE_Time_Value last = n->get_timer_value (); - - int recalc = (this->get_first_i () == n); - - // Call the close hooks. - int cookie = 0; - - // cancel_type() called once per . - this->upcall_functor ().cancel_type (*this, - n->get_type (), - skip_close, - cookie); - - // cancel_timer() called once per . - this->upcall_functor ().cancel_timer (*this, - n->get_type (), - skip_close, - cookie); - if (act != 0) - *act = n->get_act (); - - this->cancel_i (n); - - if (recalc) - this->recalc_earliest (last); - - return 1; - } - return 0; -} - -/// Shared subset of the two cancel() methods. -template void -ACE_Timer_Wheel_T::cancel_i (ACE_Timer_Node_T* n) -{ - this->unlink (n); - this->free_node (n); -} - -/// There are a few places where we have to figure out which timer -/// will expire next. This method makes the assumption that spokes -/// are always sorted, and that timers are always in the correct spoke -/// determined from their expiration time. -/// The last time is always passed in, even though you can often calculate -/// it as get_first()->get_timer_value(). -template void -ACE_Timer_Wheel_T::recalc_earliest - (const ACE_Time_Value& last) -{ - // This is possible because we use a count for is_empty() - if (this->is_empty ()) - return; - - ACE_Time_Value et = ACE_Time_Value::zero; - u_int es = 0; - u_int spoke = this->earliest_spoke_; - - // We will have to go around the wheel at most one time. - for (u_int i = 0; i < this->spoke_count_; ++i) - { - ACE_Timer_Node_T* root = this->spokes_[spoke]; - ACE_Timer_Node_T* n = root->get_next (); - if (n != root) - { - ACE_Time_Value t = n->get_timer_value (); - if (t < last + this->wheel_time_) - { - this->earliest_spoke_ = spoke; - return; - } - else if (et == ACE_Time_Value::zero || t < et) - { - et = t; - es = spoke; - } - } - if (++spoke >= this->spoke_count_) - spoke = 0; - } - - this->earliest_spoke_ = es; - //ACE_ERROR((LM_ERROR, "We had to search the whole wheel.\n")); -} - -/** -* Dumps out the size of the wheel, the resolution, and the contents -* of the wheel. -*/ -template void -ACE_Timer_Wheel_T::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Timer_Wheel_T::dump"); - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("\nspoke_count_ = %d"), this->spoke_count_)); - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("\nresolution_ = %d"), 1 << this->res_bits_)); - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("\nwheel_ =\n"))); - - for (u_int i = 0; i < this->spoke_count_; ++i) - { - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("%d\n"), i)); - ACE_Timer_Node_T* root = this->spokes_[i]; - for (ACE_Timer_Node_T* n = root->get_next (); - n != root; - n = n->get_next ()) - { - n->dump (); - } - } - - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - - -/** -* Removes the earliest node and then find the new -* -* @return The earliest timer node. -*/ -template ACE_Timer_Node_T * -ACE_Timer_Wheel_T::remove_first (void) -{ - ACE_TRACE ("ACE_Timer_Wheel_T::remove_first"); - return remove_first_expired (ACE_Time_Value::max_time); -} - -template void -ACE_Timer_Wheel_T::unlink (ACE_Timer_Node_T* n) -{ - ACE_TRACE ("ACE_Timer_Wheel_T::unlink"); - --timer_count_; - n->get_prev ()->set_next (n->get_next ()); - n->get_next ()->set_prev (n->get_prev ()); - n->set_prev (0); - n->set_next (0); -} - -template ACE_Timer_Node_T * -ACE_Timer_Wheel_T::remove_first_expired (const ACE_Time_Value& now) -{ - ACE_Timer_Node_T* n = this->get_first (); - if (n != 0 && n->get_timer_value() <= now) - { - this->unlink (n); - this->recalc_earliest (n->get_timer_value ()); - return n; - } - return 0; -} - -/** -* Returns the earliest node without removing it -* -* @return The earliest timer node. -*/ -template -ACE_Timer_Node_T* -ACE_Timer_Wheel_T::get_first (void) -{ - ACE_TRACE ("ACE_Timer_Wheel_T::get_first"); - return this->get_first_i (); -} - -template -ACE_Timer_Node_T* -ACE_Timer_Wheel_T::get_first_i (void) const -{ - ACE_Timer_Node_T* root = this->spokes_[this->earliest_spoke_]; - ACE_Timer_Node_T* first = root->get_next (); - if (first != root) - return first; - return 0; -} - - -/** -* @return The iterator -*/ -template -ACE_Timer_Queue_Iterator_T& -ACE_Timer_Wheel_T::iter (void) -{ - this->iterator_->first (); - return *this->iterator_; -} - -/** -* Dummy version of expire to get rid of warnings in Sun CC 4.2 -* Just call the expire of the base class. -*/ -template int -ACE_Timer_Wheel_T::expire () -{ - return ACE_Timer_Queue_T::expire (); -} - -/** -* This is a specialized version of expire that is more suited for the -* internal data representation. -* -* @param cur_time The time to expire timers up to. -* -* @return Number of timers expired -*/ -template int -ACE_Timer_Wheel_T::expire (const ACE_Time_Value& cur_time) -{ - ACE_TRACE ("ACE_Timer_Wheel_T::expire"); - - int expcount = 0; - - ACE_MT (ACE_GUARD_RETURN (ACE_LOCK, ace_mon, this->mutex_, -1)); - - ACE_Timer_Node_T* n = this->remove_first_expired (cur_time); - - while (n != 0) - { - ++expcount; - - //ACE_ERROR((LM_ERROR, "Expiring %x\n", (long) n)); - - ACE_Timer_Node_Dispatch_Info_T info; - - // Get the dispatch info - n->get_dispatch_info (info); - - if (n->get_interval () > ACE_Time_Value::zero) - { - // Make sure that we skip past values that have already - // "expired". - this->recompute_next_abs_interval_time (n, cur_time); - - this->reschedule (n); - } - else - { - this->free_node (n); - } - - const void *upcall_act = 0; - - this->preinvoke (info, cur_time, upcall_act); - - this->upcall (info, cur_time); - - this->postinvoke (info, cur_time, upcall_act); - - n = this->remove_first_expired (cur_time); - } - - return expcount; -} - -/////////////////////////////////////////////////////////////////////////// -// ACE_Timer_Wheel_Iterator_T - -/** -* Just initializes the iterator with a ACE_Timer_Wheel_T and then calls -* first() to initialize the rest of itself. -* -* @param wheel A reference for a timer queue to iterate over -*/ -template -ACE_Timer_Wheel_Iterator_T::ACE_Timer_Wheel_Iterator_T -(Wheel& wheel) -: timer_wheel_ (wheel) -{ - this->first(); -} - - -/** -* Destructor, at this level does nothing. -*/ -template -ACE_Timer_Wheel_Iterator_T::~ACE_Timer_Wheel_Iterator_T (void) -{ -} - - -/** -* Positions the iterator at the first position in the timing wheel -* that contains something. spoke_ will be set to the spoke position of -* this entry and current_node_ will point to the first entry in that spoke. -* -* If the wheel is empty, spoke_ will be equal timer_wheel_.spoke_count_ and -* current_node_ would be 0. -*/ -template void -ACE_Timer_Wheel_Iterator_T::first (void) -{ - this->goto_next(0); -} - - -/** -* Positions the iterator at the next node. -*/ -template void -ACE_Timer_Wheel_Iterator_T::next (void) -{ - if (this->isdone()) - return; - - ACE_Timer_Node_T* n = this->current_node_->get_next (); - ACE_Timer_Node_T* root = this->timer_wheel_.spokes_[this->spoke_]; - if (n == root) - this->goto_next (this->spoke_ + 1); - else - this->current_node_ = n; -} - -/// Helper class for common functionality of next() and first() -template void -ACE_Timer_Wheel_Iterator_T::goto_next (u_int start_spoke) -{ - // Find the first non-empty entry. - u_int sc = this->timer_wheel_.spoke_count_; - for (u_int i = start_spoke; i < sc; ++i) - { - ACE_Timer_Node_T* root = this->timer_wheel_.spokes_[i]; - ACE_Timer_Node_T* n = root->get_next (); - if (n != root) - { - this->spoke_ = i; - this->current_node_ = n; - return; - } - } - // empty - this->spoke_ = sc; - this->current_node_ = 0; -} - -/** -* @return True when we there aren't any more items (when current_node_ == 0) -*/ -template bool -ACE_Timer_Wheel_Iterator_T::isdone (void) const -{ - return this->current_node_ == 0; -} - -/** -* @return The node at the current spokeition in the sequence or 0 if the wheel -* is empty -*/ -template ACE_Timer_Node_T * -ACE_Timer_Wheel_Iterator_T::item (void) -{ - return this->current_node_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_TIMER_WHEEL_T_CPP */ diff --git a/externals/ace/Timer_Wheel_T.h b/externals/ace/Timer_Wheel_T.h deleted file mode 100644 index 266099f2e6a..00000000000 --- a/externals/ace/Timer_Wheel_T.h +++ /dev/null @@ -1,226 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Timer_Wheel_T.h - * - * $Id: Timer_Wheel_T.h 84619 2009-02-26 12:26:16Z johnnyw $ - * - * @author Darrell Brunsch - */ -//============================================================================= - -#ifndef ACE_TIMER_WHEEL_T_H -#define ACE_TIMER_WHEEL_T_H -#include /**/ "ace/pre.h" - -#include "ace/Timer_Queue_T.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Forward declaration -template -class ACE_Timer_Wheel_T; - -/** - * @class ACE_Timer_Wheel_Iterator_T - * - * @brief Iterates over an ACE_Timer_Wheel. - * - * This is a generic iterator that can be used to visit every - * node of a timer queue. Be aware that it doesn't traverse - * in the order of timeout values. - */ -template -class ACE_Timer_Wheel_Iterator_T - : public ACE_Timer_Queue_Iterator_T -{ -public: - typedef ACE_Timer_Wheel_T Wheel; - typedef ACE_Timer_Node_T Node; - - /// Constructor - ACE_Timer_Wheel_Iterator_T (Wheel &); - - /// Destructor - ~ACE_Timer_Wheel_Iterator_T (void); - - /// Positions the iterator at the earliest node in the Timer Queue - virtual void first (void); - - /// Positions the iterator at the next node in the Timer Queue - virtual void next (void); - - /// Returns true when there are no more nodes in the sequence - virtual bool isdone (void) const; - - /// Returns the node at the current position in the sequence - virtual ACE_Timer_Node_T* item (void); - -protected: - /// Pointer to the ACE_Timer_List that we are iterating over. - Wheel& timer_wheel_; - - /// Current position in the timing wheel - u_int spoke_; - - /// Pointer to the position in the the th list - ACE_Timer_Node_T* current_node_; -private: - void goto_next(u_int start_spoke); -}; - -/** - * @class ACE_Timer_Wheel_T - * - * @brief Provides a Timing Wheel version of ACE_Timer_Queue. - * - * This implementation uses a hash table of ordered doubly- - * linked lists of absolute times. The enhancements over the - * @c ACE_Timer_List include adding a free list and the ability - * to preallocate nodes. Timer Wheel is based on the timing - * wheel implementation used in Adam M. Costello and - * George Varghese's paper "Redesigning the BSD Callout and - * Timer Facilities" - * (http://dworkin.wustl.edu/~varghese/PAPERS/newbsd.ps.Z) - */ -template -class ACE_Timer_Wheel_T : public ACE_Timer_Queue_T -{ -public: - /// Type of iterator - typedef ACE_Timer_Wheel_Iterator_T Iterator; - /// Iterator is a friend - friend class ACE_Timer_Wheel_Iterator_T; - typedef ACE_Timer_Node_T Node; - /// Type inherited from - typedef ACE_Timer_Queue_T Base; - typedef ACE_Free_List FreeList; - - /// Default constructor - ACE_Timer_Wheel_T (FUNCTOR* upcall_functor = 0, FreeList* freelist = 0); - - /// Constructor with opportunities to set the wheelsize and resolution - ACE_Timer_Wheel_T (u_int spoke_count, - u_int resolution, - size_t prealloc = 0, - FUNCTOR* upcall_functor = 0, - FreeList* freelist = 0); - - /// Destructor - virtual ~ACE_Timer_Wheel_T (void); - - /// True if queue is empty, else false. - virtual bool is_empty (void) const; - - /// Returns the time of the earlier node in the ACE_Timer_Wheel. - /// Must be called on a non-empty queue. - virtual const ACE_Time_Value& earliest_time (void) const; - - /// Changes the interval of a timer (and can make it periodic or non - /// periodic by setting it to ACE_Time_Value::zero or not). - virtual int reset_interval (long timer_id, - const ACE_Time_Value& interval); - - /// Cancel all timer associated with @a type. If @a dont_call_handle_close is - /// 0 then the will be invoked. Returns number of timers - /// cancelled. - virtual int cancel (const TYPE& type, - int dont_call_handle_close = 1); - - // Cancel a timer, storing the magic cookie in act (if nonzero). - // Calls the functor if dont_call_handle_close is 0 and returns 1 - // on success - virtual int cancel (long timer_id, - const void** act = 0, - int dont_call_handle_close = 1); - - /// Run the for all timers whose values are <= - /// . Also accounts for . Returns - /// the number of timers canceled. - virtual int expire (void); - - // Run the for all timers whose values are <= @a current_time. - // This does not account for . Returns the number of - // timers canceled. - int expire (const ACE_Time_Value& current_time); - - /// Returns a pointer to this 's iterator. - virtual ACE_Timer_Queue_Iterator_T& iter (void); - - /// Removes the earliest node from the queue and returns it - virtual ACE_Timer_Node_T* remove_first (void); - - /// Dump the state of an object. - virtual void dump (void) const; - - /// Reads the earliest node from the queue and returns it. - virtual ACE_Timer_Node_T* get_first (void); - -protected: - - /// Schedules a timer. - virtual long schedule_i (const TYPE& type, - const void* act, - const ACE_Time_Value& future_time, - const ACE_Time_Value& interval); - -private: - // The following are documented in the .cpp file. - ACE_Timer_Node_T* get_first_i (void) const; - ACE_Timer_Node_T* remove_first_expired (const ACE_Time_Value& now); - void open_i (size_t prealloc, u_int spokes, u_int res); - virtual void reschedule (ACE_Timer_Node_T *); - ACE_Timer_Node_T* find_spoke_node(u_int spoke, long timer_id) const; - ACE_Timer_Node_T* find_node(long timer_id) const; - u_int calculate_spoke(const ACE_Time_Value& expire) const; - long generate_timer_id(u_int spoke); - void schedule_i (ACE_Timer_Node_T* n, u_int spoke, const ACE_Time_Value& expire); - void cancel_i (ACE_Timer_Node_T* n); - void unlink (ACE_Timer_Node_T* n); - void recalc_earliest(const ACE_Time_Value& last); - -private: - int power2bits (int n, int min_bits, int max_bits); - - /// Timing Wheel. - ACE_Timer_Node_T** spokes_; - /// Size of the timing wheel. - u_int spoke_count_; - /// Number of timer_id bits used for the spoke - int spoke_bits_; - /// Maximum number of timers per spoke - u_int max_per_spoke_; - /// Resolution (in microsoconds) of the timing wheel. - int res_bits_; - /// Index of the list with the earliest time - u_int earliest_spoke_; - /// Iterator used to expire timers. - Iterator* iterator_; - /// The total amount of time in one iteration of the wheel. (resolution * spoke_count) - ACE_Time_Value wheel_time_; - /// The total number of timers currently scheduled. - u_int timer_count_; - - // = Don't allow these operations for now, don't split into multiple lines - // breaks sun compilers - ACE_UNIMPLEMENTED_FUNC (ACE_Timer_Wheel_T (const ACE_Timer_Wheel_T &)) - ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Timer_Wheel_T &)) -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Timer_Wheel_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Timer_Wheel_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" -#endif /* ACE_TIMER_WHEEL_T_H */ diff --git a/externals/ace/Token.cpp b/externals/ace/Token.cpp deleted file mode 100644 index 9993261be17..00000000000 --- a/externals/ace/Token.cpp +++ /dev/null @@ -1,545 +0,0 @@ -// $Id: Token.cpp 83735 2008-11-14 09:41:52Z johnnyw $ - -#include "ace/Token.h" - -#if !defined (__ACE_INLINE__) -# include "ace/Token.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID(ace, Token, "$Id: Token.cpp 83735 2008-11-14 09:41:52Z johnnyw $") - -#if defined (ACE_HAS_THREADS) - -#include "ace/Thread.h" -#include "ace/Log_Msg.h" - -#if defined (ACE_TOKEN_DEBUGGING) -// FUZZ: disable check_for_streams_include -#include "ace/streams.h" -#endif /* ACE_TOKEN_DEBUGGING */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Token) - -void -ACE_Token::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Token::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nthread = %d"), ACE_Thread::self ())); - // @@ Is there a portable way to do this? - // ACE_DEBUG ((LM_DEBUG, "\nowner_ = %d", (long) this->owner_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nowner_ addr = %x"), &this->owner_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nwaiters_ = %d"), this->waiters_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nin_use_ = %d"), this->in_use_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nnesting level = %d"), this->nesting_level_)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -ACE_Token::ACE_Token_Queue_Entry::ACE_Token_Queue_Entry (ACE_Thread_Mutex &m, - ACE_thread_t t_id) - : next_ (0), - thread_id_ (t_id), -#if defined (ACE_TOKEN_USES_SEMAPHORE) - cv_ (0), -#else - cv_ (m), -#endif /* ACE_TOKEN_USES_SEMAPHORE */ - runable_ (0) -{ -#if defined (ACE_TOKEN_USES_SEMAPHORE) - ACE_UNUSED_ARG (m); -#endif /* ACE_TOKEN_USES_SEMAPHORE */ - - ACE_TRACE ("ACE_Token::ACE_Token_Queue_Entry::ACE_Token_Queue_Entry"); -} - -ACE_Token::ACE_Token_Queue_Entry::ACE_Token_Queue_Entry (ACE_Thread_Mutex &m, - ACE_thread_t t_id, - ACE_Condition_Attributes &attributes) - : next_ (0), - thread_id_ (t_id), -#if defined (ACE_TOKEN_USES_SEMAPHORE) - cv_ (0), -#else - cv_ (m, attributes), -#endif /* ACE_TOKEN_USES_SEMAPHORE */ - runable_ (0) -{ -#if defined (ACE_TOKEN_USES_SEMAPHORE) - ACE_UNUSED_ARG (m); - ACE_UNUSED_ARG (attributes); -#endif /* ACE_TOKEN_USES_SEMAPHORE */ - - ACE_TRACE ("ACE_Token::ACE_Token_Queue_Entry::ACE_Token_Queue_Entry"); -} - -ACE_Token::ACE_Token_Queue::ACE_Token_Queue (void) - : head_ (0), - tail_ (0) -{ - ACE_TRACE ("ACE_Token::ACE_Token_Queue::ACE_Token_Queue"); -} - -// -// Remove an entry from the list. Must be called with locks held. -// -void -ACE_Token::ACE_Token_Queue::remove_entry (ACE_Token::ACE_Token_Queue_Entry *entry) -{ - ACE_TRACE ("ACE_Token::ACE_Token_Queue::remove_entry"); - ACE_Token_Queue_Entry *curr = 0; - ACE_Token_Queue_Entry *prev = 0; - - if (this->head_ == 0) - return; - - for (curr = this->head_; - curr != 0 && curr != entry; - curr = curr->next_) - prev = curr; - - if (curr == 0) - // Didn't find the entry... - return; - else if (prev == 0) - // Delete at the head. - this->head_ = this->head_->next_; - else - // Delete in the middle. - prev->next_ = curr->next_; - - // We need to update the tail of the list if we've deleted the last - // entry. - if (curr->next_ == 0) - this->tail_ = prev; -} - -// -// Add an entry into the list. Must be called with locks held. -// -void -ACE_Token::ACE_Token_Queue::insert_entry (ACE_Token::ACE_Token_Queue_Entry &entry, - int requeue_position) -{ - if (this->head_ == 0) - { - // No other threads - just add me - this->head_ = &entry; - this->tail_ = &entry; - } - else if (requeue_position == -1) - { - // Insert at the end of the queue. - this->tail_->next_ = &entry; - this->tail_ = &entry; - } - else if (requeue_position == 0) - { - // Insert at head of queue. - entry.next_ = this->head_; - this->head_ = &entry; - } - else - // Insert in the middle of the queue somewhere. - { - // Determine where our thread should go in the queue of waiters. - - ACE_Token::ACE_Token_Queue_Entry *insert_after = this->head_; - while (requeue_position-- && insert_after->next_ != 0) - insert_after = insert_after->next_; - - entry.next_ = insert_after->next_; - - if (entry.next_ == 0) - this->tail_ = &entry; - - insert_after->next_ = &entry; - } -} - -ACE_Token::ACE_Token (const ACE_TCHAR *name, void *any) - : lock_ (name, (ACE_mutexattr_t *) any), - owner_ (ACE_OS::NULL_thread), - in_use_ (0), - waiters_ (0), - nesting_level_ (0), - attributes_ (USYNC_THREAD), - queueing_strategy_ (FIFO) -{ -// ACE_TRACE ("ACE_Token::ACE_Token"); -} - -ACE_Token::~ACE_Token (void) -{ - ACE_TRACE ("ACE_Token::~ACE_Token"); -} - -int -ACE_Token::shared_acquire (void (*sleep_hook_func)(void *), - void *arg, - ACE_Time_Value *timeout, - ACE_Token_Op_Type op_type) -{ - ACE_TRACE ("ACE_Token::shared_acquire"); - ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1); - -#if defined (ACE_TOKEN_DEBUGGING) - this->dump (); -#endif /* ACE_TOKEN_DEBUGGING */ - - ACE_thread_t const thr_id = ACE_Thread::self (); - - // Nobody holds the token. - if (!this->in_use_) - { - // Its mine! - this->in_use_ = op_type; - this->owner_ = thr_id; - return 0; - } - - // - // Someone already holds the token. - // - - // Check if it is us. - if (ACE_OS::thr_equal (thr_id, this->owner_)) - { - ++this->nesting_level_; - return 0; - } - - // Do a quick check for "polling" behavior. - if (timeout != 0 && *timeout == ACE_Time_Value::zero) - { - errno = ETIME; - return -1; - } - - // - // We've got to sleep until we get the token. - // - - // Which queue we should end up in... - ACE_Token_Queue *queue = (op_type == ACE_Token::READ_TOKEN - ? &this->readers_ - : &this->writers_); - - // Allocate queue entry on stack. This works since we don't exit - // this method's activation record until we've got the token. - ACE_Token::ACE_Token_Queue_Entry my_entry (this->lock_, - thr_id, - this->attributes_); - queue->insert_entry (my_entry, this->queueing_strategy_); - ++this->waiters_; - - // Execute appropriate callback. (@@ should these - // methods return a success/failure status, and if so, what should - // we do with it?) - int ret = 0; - if (sleep_hook_func) - { - (*sleep_hook_func) (arg); - ++ret; - } - else - { - // Execute virtual method. - this->sleep_hook (); - ++ret; - } - - bool timed_out = false; - bool error = false; - - // Sleep until we've got the token (ignore signals). - do - { - int const result = my_entry.wait (timeout, this->lock_); - - if (result == -1) - { - // Note, this should obey whatever thread-specific interrupt - // policy is currently in place... - if (errno == EINTR) - continue; - -#if defined (ACE_TOKEN_DEBUGGING) - cerr << '(' << ACE_Thread::self () << ')' - << " acquire: " - << (errno == ETIME ? "timed out" : "error occurred") - << endl; -#endif /* ACE_TOKEN_DEBUGGING */ - - // We come here if a timeout occurs or some serious - // ACE_Condition object error. - if (errno == ETIME) - timed_out = true; - else - error = true; - - // Stop the loop. - break; - } - } - while (!ACE_OS::thr_equal (thr_id, this->owner_)); - - // Do this always and irrespective of the result of wait(). - --this->waiters_; - queue->remove_entry (&my_entry); - -#if defined (ACE_TOKEN_DEBUGGING) - ACE_DEBUG ((LM_DEBUG, "(%t) ACE_Token::shared_acquire (UNBLOCKED)\n")); -#endif /* ACE_TOKEN_DEBUGGING */ - - // If timeout occured - if (timed_out) - { - // This thread was still selected to own the token. - if (my_entry.runable_) - { - // Wakeup next waiter since this thread timed out. - this->wakeup_next_waiter (); - } - - // Return error. - return -1; - } - else if (error) - { - // Return error. - return -1; - } - - // If this is a normal wakeup, this thread should be runnable. - ACE_ASSERT (my_entry.runable_); - - return ret; -} - -// By default this is a no-op. - -/* virtual */ -void -ACE_Token::sleep_hook (void) -{ - ACE_TRACE ("ACE_Token::sleep_hook"); -} - -int -ACE_Token::acquire (ACE_Time_Value *timeout) -{ - ACE_TRACE ("ACE_Token::acquire"); - return this->shared_acquire (0, 0, timeout, ACE_Token::WRITE_TOKEN); -} - -// Acquire the token, sleeping until it is obtained or until -// expires. - -int -ACE_Token::acquire (void (*sleep_hook_func)(void *), - void *arg, - ACE_Time_Value *timeout) -{ - ACE_TRACE ("ACE_Token::acquire"); - return this->shared_acquire (sleep_hook_func, arg, timeout, ACE_Token::WRITE_TOKEN); -} - -// Try to renew the token. - -int -ACE_Token::renew (int requeue_position, - ACE_Time_Value *timeout) -{ - ACE_TRACE ("ACE_Token::renew"); - ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1); - -#if defined (ACE_TOKEN_DEBUGGING) - this->dump (); -#endif /* ACE_TOKEN_DEBUGGING */ - // ACE_ASSERT (ACE_OS::thr_equal (ACE_Thread::self (), this->owner_)); - - // Check to see if there are any waiters worth giving up the lock - // for. - - // If no writers and either we are a writer or there are no readers. - if (this->writers_.head_ == 0 && - (this->in_use_ == ACE_Token::WRITE_TOKEN || - this->readers_.head_ == 0)) - // Immediate return. - return 0; - - // We've got to sleep until we get the token again. - - // Determine which queue should this thread go to. - ACE_Token::ACE_Token_Queue *this_threads_queue = - this->in_use_ == ACE_Token::READ_TOKEN ? - &this->readers_ : &this->writers_; - - ACE_Token::ACE_Token_Queue_Entry my_entry (this->lock_, - this->owner_); - - this_threads_queue->insert_entry (my_entry, - // if requeue_position == 0 then we want to go next, - // otherwise use the queueing strategy, which might also - // happen to be 0. - requeue_position == 0 ? 0 : this->queueing_strategy_); - ++this->waiters_; - - // Remember nesting level... - int const save_nesting_level_ = this->nesting_level_; - - // Reset state for new owner. - this->nesting_level_ = 0; - - // Wakeup waiter. - this->wakeup_next_waiter (); - - bool timed_out = false; - bool error = false; - - // Sleep until we've got the token (ignore signals). - do - { - int const result = my_entry.wait (timeout, this->lock_); - - if (result == -1) - { - // Note, this should obey whatever thread-specific interrupt - // policy is currently in place... - if (errno == EINTR) - continue; - -#if defined (ACE_TOKEN_DEBUGGING) - cerr << '(' << ACE_Thread::self () << ')' - << " renew: " - << (errno == ETIME ? "timed out" : "error occurred") - << endl; -#endif /* ACE_TOKEN_DEBUGGING */ - - // We come here if a timeout occurs or some serious - // ACE_Condition object error. - if (errno == ETIME) - timed_out = true; - else - error = true; - - // Stop the loop. - break; - } - } - while (!ACE_OS::thr_equal (my_entry.thread_id_, this->owner_)); - - // Do this always and irrespective of the result of wait(). - --this->waiters_; - this_threads_queue->remove_entry (&my_entry); - -#if defined (ACE_TOKEN_DEBUGGING) - ACE_DEBUG ((LM_DEBUG, "(%t) ACE_Token::renew (UNBLOCKED)\n")); -#endif /* ACE_TOKEN_DEBUGGING */ - - // If timeout occured - if (timed_out) - { - // This thread was still selected to own the token. - if (my_entry.runable_) - { - // Wakeup next waiter since this thread timed out. - this->wakeup_next_waiter (); - } - - // Return error. - return -1; - } - else if (error) - { - // Return error. - return -1; - } - - // If this is a normal wakeup, this thread should be runnable. - ACE_ASSERT (my_entry.runable_); - - // Reinstate nesting level. - this->nesting_level_ = save_nesting_level_; - - return 0; -} - -// Release the current holder of the token (which had -// better be the caller's thread!). - -int -ACE_Token::release (void) -{ - ACE_TRACE ("ACE_Token::release"); - ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1); - -#if defined (ACE_TOKEN_DEBUGGING) - this->dump (); -#endif /* ACE_TOKEN_DEBUGGING */ - - // Nested release... - if (this->nesting_level_ > 0) - --this->nesting_level_; - else - { - // - // Regular release... - // - - // Wakeup waiter. - this->wakeup_next_waiter (); - } - - return 0; -} - -void -ACE_Token::wakeup_next_waiter (void) -{ - ACE_TRACE ("ACE_Token::wakeup_next_waiter"); - - // Reset state for new owner. - this->owner_ = ACE_OS::NULL_thread; - this->in_use_ = 0; - - // Any waiters... - if (this->writers_.head_ == 0 && - this->readers_.head_ == 0) - { - // No more waiters... - return; - } - - // Wakeup next waiter. - ACE_Token_Queue *queue = 0; - - // Writer threads get priority to run first. - if (this->writers_.head_ != 0) - { - this->in_use_ = ACE_Token::WRITE_TOKEN; - queue = &this->writers_; - } - else - { - this->in_use_ = ACE_Token::READ_TOKEN; - queue = &this->readers_; - } - - // Wake up waiter and make it runable. - queue->head_->runable_ = 1; - queue->head_->signal (); - - this->owner_ = queue->head_->thread_id_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_THREADS */ diff --git a/externals/ace/Token.h b/externals/ace/Token.h deleted file mode 100644 index 7857c44dfb5..00000000000 --- a/externals/ace/Token.h +++ /dev/null @@ -1,376 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Token.h - * - * $Id: Token.h 85367 2009-05-18 10:11:54Z johnnyw $ - * - * @author Original author - * @author Karl-Heinz Dorn (kdorn@erlh.siemens.de) - * @author Ported to ACE by - * @author Douglas C. Schmidt (schmidt@cs.wustl.edu) - */ -//============================================================================= - -#ifndef ACE_TOKEN_H -#define ACE_TOKEN_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Null_Mutex.h" - -#if defined (ACE_HAS_THREADS) - -#include "ace/Thread_Mutex.h" - -#if (defined (ACE_WIN32) && !defined (ACE_USES_WINCE_SEMA_SIMULATION)) || defined (ACE_HAS_VXTHREADS) -// If platforms support semaphores with timed wait, then we use semaphores instead of c.v. -# define ACE_TOKEN_USES_SEMAPHORE -#endif /* ACE_WIN32 || ACE_HAS_VXTHREADS */ - -#if defined (ACE_TOKEN_USES_SEMAPHORE) -# include "ace/Semaphore.h" -#endif /* ACE_TOKEN_USES_SEMAPHORE */ - -#include "ace/Condition_Thread_Mutex.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -class ACE_Time_Value; - -/** - * @class ACE_Token - * - * @brief Class that acquires, renews, and releases a synchronization - * token that is serviced in strict FIFO/LIFO ordering and that also - * supports (1) recursion and (2) readers/writer semantics. - * - * This class is a more general-purpose synchronization mechanism - * than many native OS mutexes. For example, it implements - * "recursive mutex" semantics, where a thread that owns the token - * can reacquire it without deadlocking. If the same thread calls - * multiple times, however, it must call an - * equal number of times before the token is actually released. - * Threads that are blocked awaiting the token are serviced in - * strict FIFO/LIFO order as other threads release the token (Solaris - * and Pthread mutexes don't strictly enforce an acquisition - * order). There are two lists within the class. Write - * acquires always have higher priority over read acquires. Which - * means, if you use both write/read operations, care must be - * taken to avoid starvation on the readers. Notice that the - * read/write acquire operations do not have the usual semantic of - * reader/writer locks. Only one reader can acquire the token at - * a time (which is different from the usual reader/writer locks - * where several readers can acquire a lock at the same time as - * long as there is no writer waiting for the lock). We choose - * the names to (1) borrow the semantic to give writers higher - * priority and (2) support a common interface for all locking - * classes in ACE. - */ -class ACE_Export ACE_Token -{ -public: - - /** - * Available queueing strategies. - */ - enum QUEUEING_STRATEGY - { - /// FIFO, First In, First Out. - FIFO = -1, - /// LIFO, Last In, First Out - LIFO = 0 - }; - - // = Initialization and termination. - - /// Constructor - ACE_Token (const ACE_TCHAR *name = 0, void * = 0); - - /// Destructor - virtual ~ACE_Token (void); - - // = Strategies - - /// Retrieve the current queueing strategy. - int queueing_strategy (void); - - /// Set the queueing strategy. - void queueing_strategy (int queueing_strategy); - - // = Synchronization operations. - - /** - * Acquire the token, sleeping until it is obtained or until the - * expiration of @a timeout, which is treated as "absolute" time. If - * some other thread currently holds the token then is - * called before our thread goes to sleep. This can be - * used by the requesting thread to unblock a token-holder that is - * sleeping, e.g., by means of writing to a pipe (the ACE - * ACE_Reactor uses this functionality). Return values: 0 if - * acquires without calling 1 if is - * called. 2 if the token is signaled. -1 if failure or timeout - * occurs (if timeout occurs errno == ETIME) If @a timeout == - * <&ACE_Time_Value::zero> then acquire has polling semantics (and - * does *not* call ). - */ - int acquire (void (*sleep_hook)(void *), - void *arg = 0, - ACE_Time_Value *timeout = 0); - - /** - * This behaves just like the previous method, except that - * it invokes the virtual function called that can be - * overridden by a subclass of ACE_Token. - */ - int acquire (ACE_Time_Value *timeout = 0); - - /** - * This should be overridden by a subclass to define the appropriate - * behavior before goes to sleep. By default, this is a - * no-op... - */ - virtual void sleep_hook (void); - - /** - * An optimized method that efficiently reacquires the token if no - * other threads are waiting. This is useful for situations where - * you don't want to degrade the quality of service if there are - * other threads waiting to get the token. If == - * -1 and there are other threads waiting to obtain the token we are - * queued according to the queueing strategy. If - * > -1 then it indicates how many entries to skip over before - * inserting our thread into the list of waiters (e.g., - * == 0 means "insert at front of the queue"). - * Renew has the rather odd semantics such that if there are other - * waiting threads it will give up the token even if the - * nesting_level_ > 1. I'm not sure if this is really the right - * thing to do (since it makes it possible for shared data to be - * changed unexpectedly) so use with caution... This method - * maintians the original token priority. As in , the - * @a timeout value is an absolute time. - */ - int renew (int requeue_position = 0, - ACE_Time_Value *timeout = 0); - - /// Become interface-compliant with other lock mechanisms (implements - /// a non-blocking ). - int tryacquire (void); - - /// Shuts down the ACE_Token instance. - int remove (void); - - /// Relinquish the token. If there are any waiters then the next one - /// in line gets it. - int release (void); - - /// Behaves like acquire() but at a lower priority. It should probably - /// be called acquire_yield() since the semantics aren't really - /// what's commonly expected for readers/writer locks. See the class - /// documentation above for more details. - int acquire_read (void); - - /// Behaves like acquire() but at a lower priority. It should probably - /// be called acquire_yield() since the semantics aren't really - /// what's commonly expected for readers/writer locks. See the class - /// documentation above for more details. - int acquire_read (void (*sleep_hook)(void *), - void *arg = 0, - ACE_Time_Value *timeout = 0); - - /// Calls acquire(). - int acquire_write (void); - - /// Calls acquire(). - int acquire_write (void (*sleep_hook)(void *), - void *arg = 0, - ACE_Time_Value *timeout = 0); - - /// Lower priority try_acquire(). - int tryacquire_read (void); - - /// Just calls . - int tryacquire_write (void); - - /// Assumes the caller has acquired the token and returns 0. - int tryacquire_write_upgrade (void); - - // = Accessor methods. - - /// Return the number of threads that are currently waiting to get - /// the token. - int waiters (void); - - /// Return the id of the current thread that owns the token. - ACE_thread_t current_owner (void); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - - /// The following structure implements a LIFO/FIFO queue of waiter threads - /// that are asleep waiting to obtain the token. - struct ACE_Token_Queue_Entry - { - /// Constructor - ACE_Token_Queue_Entry (ACE_Thread_Mutex &m, - ACE_thread_t t_id); - - /// Constructor using a pre-allocated attributes - ACE_Token_Queue_Entry (ACE_Thread_Mutex &m, - ACE_thread_t t_id, - ACE_Condition_Attributes &attributes); - - /// Entry blocks on the token. - int wait (ACE_Time_Value *timeout, ACE_Thread_Mutex &lock); - - /// Notify (unblock) the entry. - int signal (void); - - /// Pointer to next waiter. - ACE_Token_Queue_Entry *next_; - - /// ACE_Thread id of this waiter. - ACE_thread_t thread_id_; - -#if defined (ACE_TOKEN_USES_SEMAPHORE) - /// ACE_Semaphore object used to wake up waiter when it can run again. - ACE_Semaphore cv_; -#else - /// ACE_Condition object used to wake up waiter when it can run again. - ACE_Condition_Thread_Mutex cv_; -#endif /* ACE_TOKEN_USES_SEMAPHORE */ - - /// Ok to run. - int runable_; - }; - -private: - enum ACE_Token_Op_Type - { - READ_TOKEN = 1, - WRITE_TOKEN - }; - - struct ACE_Token_Queue - { - /// Constructor - ACE_Token_Queue (void); - - /// Remove a waiter from the queue. - void remove_entry (ACE_Token_Queue_Entry *); - - /// Insert a waiter into the queue. - void insert_entry (ACE_Token_Queue_Entry &entry, - int requeue_position = -1); - - /// Head of the list of waiting threads. - ACE_Token_Queue_Entry *head_; - - /// Tail of the list of waiting threads. - ACE_Token_Queue_Entry *tail_; - }; - - /// Implements the and methods above. - int shared_acquire (void (*sleep_hook_func)(void *), - void *arg, - ACE_Time_Value *timeout, - ACE_Token_Op_Type op_type); - - /// Wake next in line for ownership. - void wakeup_next_waiter (void); - - /// A queue of writer threads. - ACE_Token_Queue writers_; - - /// A queue of reader threads. - ACE_Token_Queue readers_; - - /// ACE_Thread_Mutex used to lock internal data structures. - ACE_Thread_Mutex lock_; - - /// Current owner of the token. - ACE_thread_t owner_; - - /// Some thread (i.e., ) is using the token. We need this - /// extra variable to deal with POSIX pthreads madness... - int in_use_; - - /// Number of waiters. - int waiters_; - - /// Current nesting level. - int nesting_level_; - - /// The attributes for the condition variables, optimizes lock time. - ACE_Condition_Attributes attributes_; - - /// Queueing strategy, LIFO/FIFO. - int queueing_strategy_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#else - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -class ACE_Export ACE_Token -{ -public: - int queueing_strategy (void) { ACE_NOTSUP_RETURN (-1); } - void queueing_strategy (int /*queueing_strategy*/) { } - int acquire (ACE_Time_Value * = 0) { ACE_NOTSUP_RETURN (-1); } - int tryacquire (void) { ACE_NOTSUP_RETURN (-1); } - int remove (void) { ACE_NOTSUP_RETURN (-1); } - int release (void) { ACE_NOTSUP_RETURN (-1); } -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_THREADS */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -class ACE_Export ACE_Noop_Token : public ACE_Null_Mutex -{ -public: - /// Queueing strategy - enum QUEUEING_STRATEGY - { - FIFO = -1, - LIFO = 0 - }; - - /// Get queueing strategy. - int queueing_strategy (void); - - /// Set queueing strategy. - void queueing_strategy (int queueing_strategy); - - int renew (int = 0, ACE_Time_Value * =0); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Token.inl" -#endif /* __ACE_INLINE__ */ - - -#include /**/ "ace/post.h" -#endif /* ACE_TOKEN_H */ diff --git a/externals/ace/Token.inl b/externals/ace/Token.inl deleted file mode 100644 index f09a0e6f3de..00000000000 --- a/externals/ace/Token.inl +++ /dev/null @@ -1,176 +0,0 @@ -// -*- C++ -*- -// -// $Id: Token.inl 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/config-macros.h" - -#if defined (ACE_HAS_THREADS) - -#include "ace/Guard_T.h" -#include "ace/Time_Value.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE int -ACE_Token::queueing_strategy (void) -{ - return this->queueing_strategy_; -} - -ACE_INLINE void -ACE_Token::queueing_strategy (int queueing_strategy) -{ - this->queueing_strategy_ = queueing_strategy == -1 ? -1 : 0; -} - -ACE_INLINE int -ACE_Token::remove (void) -{ - ACE_TRACE ("ACE_Token::remove"); - // Don't have an implementation for this yet... - ACE_NOTSUP_RETURN (-1); -} - -ACE_INLINE int -ACE_Token::tryacquire (void) -{ - ACE_TRACE ("ACE_Token::tryacquire"); - return this->shared_acquire - (0, 0, (ACE_Time_Value *) &ACE_Time_Value::zero, ACE_Token::WRITE_TOKEN); -} - -ACE_INLINE int -ACE_Token::waiters (void) -{ - ACE_TRACE ("ACE_Token::waiters"); - ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1); - - int const ret = this->waiters_; - return ret; -} - -ACE_INLINE ACE_thread_t -ACE_Token::current_owner (void) -{ - ACE_TRACE ("ACE_Token::current_owner"); - ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, this->owner_); - - return this->owner_; -} - -ACE_INLINE int -ACE_Token::acquire_read (void) -{ - ACE_TRACE ("ACE_Token::acquire_read"); - return this->shared_acquire - (0, 0, 0, ACE_Token::READ_TOKEN); -} - -ACE_INLINE int -ACE_Token::acquire_write (void) -{ - ACE_TRACE ("ACE_Token::acquire_write"); - return this->shared_acquire - (0, 0, 0, ACE_Token::WRITE_TOKEN); -} - -ACE_INLINE int -ACE_Token::tryacquire_read (void) -{ - ACE_TRACE ("ACE_Token::tryacquire_read"); - return this->shared_acquire - (0, 0, (ACE_Time_Value *) &ACE_Time_Value::zero, ACE_Token::READ_TOKEN); -} - -ACE_INLINE int -ACE_Token::acquire_read (void (*sleep_hook_func)(void *), - void *arg, - ACE_Time_Value *timeout) -{ - ACE_TRACE ("ACE_Token::acquire_read"); - return this->shared_acquire (sleep_hook_func, arg, timeout, ACE_Token::READ_TOKEN); -} - -ACE_INLINE int -ACE_Token::tryacquire_write (void) -{ - ACE_TRACE ("ACE_Token::tryacquire_write"); - return this->shared_acquire - (0, 0, (ACE_Time_Value *) &ACE_Time_Value::zero, ACE_Token::WRITE_TOKEN); -} - -ACE_INLINE int -ACE_Token::tryacquire_write_upgrade (void) -{ - ACE_TRACE ("ACE_Token::tryacquire_write_upgrade"); - return 0; -} - -ACE_INLINE int -ACE_Token::acquire_write (void (*sleep_hook_func)(void *), - void *arg, - ACE_Time_Value *timeout) -{ - ACE_TRACE ("ACE_Token::acquire_write"); - return this->shared_acquire (sleep_hook_func, arg, timeout, ACE_Token::WRITE_TOKEN); -} - -ACE_INLINE int -ACE_Token::ACE_Token_Queue_Entry::wait (ACE_Time_Value *timeout, ACE_Thread_Mutex &lock) -{ -#if defined (ACE_TOKEN_USES_SEMAPHORE) - lock.release (); - int const retv = (timeout == 0 ? - this->cv_.acquire () : - this->cv_.acquire (*timeout)); - lock.acquire (); - return retv; -#else - ACE_UNUSED_ARG (lock); - return this->cv_.wait (timeout); -#endif /* ACE_TOKEN_USES_SEMAPHORE */ -} - -ACE_INLINE int -ACE_Token::ACE_Token_Queue_Entry::signal (void) -{ - return -#if defined (ACE_TOKEN_USES_SEMAPHORE) - this->cv_.release (); -#else - this->cv_.signal (); -#endif /* ACE_TOKEN_USES_SEMAPHORE */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_THREADS */ - -/*****************************************************************************/ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE int -ACE_Noop_Token::queueing_strategy (void) -{ - return -1; -} - -ACE_INLINE void -ACE_Noop_Token::queueing_strategy (int /* queueing_strategy */) -{ -} - -ACE_INLINE int -ACE_Noop_Token::renew (int, ACE_Time_Value *) -{ - return 0; -} - -ACE_INLINE void -ACE_Noop_Token::dump (void) const -{ -} - -ACE_END_VERSIONED_NAMESPACE_DECL - diff --git a/externals/ace/Token_Collection.cpp b/externals/ace/Token_Collection.cpp deleted file mode 100644 index 23a5813c958..00000000000 --- a/externals/ace/Token_Collection.cpp +++ /dev/null @@ -1,294 +0,0 @@ -#include "ace/Token_Collection.h" - -#if defined (ACE_HAS_TOKENS_LIBRARY) - -#if !defined (__ACE_INLINE__) -#include "ace/Token_Collection.inl" -#endif /* __ACE_INLINE__ */ - - -ACE_RCSID (ace, - Token_Collection, - "$Id: Token_Collection.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_Token_Collection::ACE_Token_Collection (bool debug, - const ACE_TCHAR *name) -: debug_ (debug) -{ - ACE_TRACE ("ACE_Token_Collection::ACE_Token_Collection"); - - if (name == 0) - name = ACE_TEXT ("no name"); - - ACE_OS::strsncpy (this->name_, - const_cast (name), - ACE_MAXTOKENNAMELEN); -} - -int -ACE_Token_Collection::insert (ACE_Token_Proxy &new_token) -{ - ACE_TRACE ("ACE_Token_Collection::insert"); - - TOKEN_NAME name (new_token.name ()); - - // Check if the new_proxy is already in the list. - if (collection_.find (name) == 1) - // One already exists, so fail. - return -1; - - // Clone the new token. - ACE_Token_Proxy *temp = new_token.clone (); - - if (collection_.bind (name, temp) == -1) - ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("bind failed\n")), -1); - return 0; -} - -int -ACE_Token_Collection::extract (const ACE_TCHAR *token_name, ACE_Token_Proxy *&proxy) -{ - ACE_TRACE ("ACE_Token_Collection::extract"); - TOKEN_NAME name (token_name); - return collection_.unbind (token_name, proxy); -} - -ACE_Token_Proxy * -ACE_Token_Collection::is_member (const ACE_TCHAR *token_name) -{ - ACE_TRACE ("ACE_Token_Collection::is_member"); - TOKEN_NAME name (token_name); - ACE_Token_Proxy *temp; - // Get the token from the collection. - return collection_.find (name, temp) == -1 ? 0 : temp; -} - -int -ACE_Token_Collection::is_member (const ACE_Token_Proxy &token) -{ - ACE_TRACE ("ACE_Token_Collection::is_member"); - TOKEN_NAME token_name (token.name ()); - return collection_.find (token_name) == 0; -} - -int -ACE_Token_Collection::acquire (int notify, - void (*sleep_hook)(void *), - ACE_Synch_Options &options) -{ - ACE_TRACE ("ACE_Token_Collection::acquire"); - - COLLECTION::ITERATOR iterator (collection_); - - for (COLLECTION::ENTRY *temp = 0; - iterator.next (temp) != 0; - iterator.advance ()) - { - if (debug_) - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("collection acquiring %s\n"), - temp->int_id_->name ())); - if (temp->int_id_->acquire (notify, - sleep_hook, - options) == -1) - { - // Save/restore errno. - ACE_Errno_Guard error (errno); - this->release (); - ACE_RETURN (-1); - } - } - - return 0; -} - -int -ACE_Token_Collection::acquire (const ACE_TCHAR *token_name, - int notify, - void (*sleep_hook)(void *), - ACE_Synch_Options &options) -{ - ACE_TRACE ("ACE_Token_Collection::acquire"); - TOKEN_NAME name (token_name); - ACE_Token_Proxy *temp; - // Get the token from the collection. - int result = collection_.find (name, temp); - // did we find it? - if (result == -1) - return result; - // perform the operation - return temp->acquire (notify, sleep_hook, options); -} - - -int -ACE_Token_Collection::tryacquire (const ACE_TCHAR *token_name, - void (*sleep_hook)(void *)) -{ - ACE_TRACE ("ACE_Token_Collection::tryacquire"); - TOKEN_NAME name (token_name); - ACE_Token_Proxy *temp; - // Get the token from the collection. - int result = collection_.find (name, temp); - // did we find it? - if (result == -1) - return result; - - // perform the operation - return temp->tryacquire (sleep_hook); -} - -int -ACE_Token_Collection::tryacquire (void (*sleep_hook)(void *)) -{ - ACE_TRACE ("ACE_Token_Collection::tryacquire"); - - COLLECTION::ITERATOR iterator (collection_); - - for (COLLECTION::ENTRY *temp = 0; - iterator.next (temp) != 0; - iterator.advance ()) - { - if (debug_) - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("collection acquiring %s\n"), - temp->int_id_->name ())); - // We will fail if _any_ token is not free. - if (temp->int_id_->tryacquire (sleep_hook) == -1) - return -1; - } - - return 0; -} - -int -ACE_Token_Collection::renew (int requeue_position, - ACE_Synch_Options &options) -{ - ACE_TRACE ("ACE_Token_Collection::renew"); - - COLLECTION::ITERATOR iterator (collection_); - - for (COLLECTION::ENTRY *temp = 0; - iterator.next (temp) != 0; - iterator.advance ()) - { - if (debug_) - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("collection renewing %s\n"), - temp->int_id_->name ())); - if (temp->int_id_->renew (requeue_position, options) == -1) - return -1; - } - - return 0; -} - -int -ACE_Token_Collection::renew (const ACE_TCHAR *token_name, - int requeue_position, - ACE_Synch_Options &options) -{ - ACE_TRACE ("ACE_Token_Collection::renew"); - TOKEN_NAME name (token_name); - ACE_Token_Proxy *temp; - - // Get the token from the collection. - int result = collection_.find (name, temp); - - // Did we find it? - if (result == -1) - ACE_ERROR_RETURN ((LM_DEBUG, ACE_TEXT ("%p %s\n"), - ACE_TEXT ("not in collection "), - token_name), -1); - // perform the operation - return temp->renew (requeue_position, options); -} - -int -ACE_Token_Collection::release (ACE_Synch_Options &) - -{ - ACE_TRACE ("ACE_Token_Collection::release"); - COLLECTION::ITERATOR iterator (collection_); - - for (COLLECTION::ENTRY *temp = 0; - iterator.next (temp) != 0; - iterator.advance ()) - { - if (debug_) - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("collection releasing %s\n"), - temp->int_id_->name ())); - temp->int_id_->release (); - } - - return 0; -} - -int -ACE_Token_Collection::release (const ACE_TCHAR *token_name, - ACE_Synch_Options &options) -{ - ACE_TRACE ("ACE_Token_Collection::release"); - TOKEN_NAME name (token_name); - ACE_Token_Proxy *temp; - // get the token from the collection - int result = collection_.find (name, temp); - // did we find it? - if (result != 0) - return result; - // perform the operation - return temp->release (options); -} - -ACE_Token_Collection::~ACE_Token_Collection (void) -{ - ACE_TRACE ("ACE_Token_Collection::~ACE_Token_Collection"); - COLLECTION::ITERATOR iterator (collection_); - - for (COLLECTION::ENTRY *temp = 0; - iterator.next (temp) != 0; - iterator.advance ()) - { - delete temp->int_id_; - // The ext_id_'s delete themselves when the array of - // COLLECTION::ENTRYs goes away. - } -} - - -// This method doesn't mean anything for a collection. -ACE_Token_Proxy * -ACE_Token_Collection::clone (void) const -{ - ACE_TRACE ("ACE_Token_Collection::clone"); - return (ACE_Token_Proxy *) 0; -} - -// This method doesn't mean anything for a collection. -ACE_Tokens * -ACE_Token_Collection::create_token (const ACE_TCHAR *) -{ - ACE_TRACE ("ACE_Token_Collection::create_token"); - return (ACE_Tokens *) 0; -} - -void -ACE_Token_Collection::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Token_Collection::dump"); - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("ACE_Token_Collection::dump:\n") - ACE_TEXT (" debug_ = %d\n"), debug_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("collection_\n"))); - collection_.dump (); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("base:\n"))); - ACE_Token_Proxy::dump (); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_TOKENS_LIBRARY */ diff --git a/externals/ace/Token_Collection.h b/externals/ace/Token_Collection.h deleted file mode 100644 index 16a9bb412b0..00000000000 --- a/externals/ace/Token_Collection.h +++ /dev/null @@ -1,243 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Token_Collection.h - * - * $Id: Token_Collection.h 80826 2008-03-04 14:51:23Z wotte $ - * - * The ACE_Token class offers methods for acquiring, renewing, - * and releasing a synchronization token on a per-token basis. The - * ACE_Token_Collection offers an interface for performing - * operations on groups of tokens as a whole, or on a single token - * within the collection. - * - * The atomic group operations are not yet implemented. - * - * - * @author Douglas C. Schmidt (schmidt@cs.wustl.edu) - * @author Tim Harrison (harrison@cs.wustl.edu) - */ -//============================================================================= - -#ifndef ACE_TOKEN_COLLECTION_H -#define ACE_TOKEN_COLLECTION_H -#include /**/ "ace/pre.h" - -#include "ace/Map_Manager.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_TOKENS_LIBRARY) - -#include "ace/Local_Tokens.h" -#include "ace/Null_Mutex.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Token_Collection - * - * @brief Allows atomic token group operations AND - * provides a ACE_Token manager interface. - * - * There are two types of operations offered by - * ACE_Token_Collection. The first is atomic operations on - * collections of Token_Proxies. In this respect, the - * ACE_Token_Collection can be thought of as a single token - * consisting of multiple Token_Proxies. The second role of the - * ACE_Token_Collection is as a ACE_Token manager. - * ACE_Token_Collection allows individual operations on single - * members of a collection of Token_Proxies. This provides a - * single access point for operations on multiple tokens. - * - * @bug Although ACE_Token_Collection inherits from ACE_Token_Proxy, it - * can not be including in a collection. This is because - * returns zero for now. - * - */ -class ACE_Export ACE_Token_Collection : public ACE_Token_Proxy -{ -public: - /** - * @a debug print out verbose debugging messages. @a name will give a - * name to the collection. Collections don't really need names, but - * are sometimes useful for debugging. - */ - ACE_Token_Collection (bool debug = false, - const ACE_TCHAR *name = 0); - -// Collection Management operations - - /** - * Insert a Token into the collection. All ACE_Token type - * operations performed on the collection will also be performed on - * the new_proxy until it is removed. Note that no operations - * performed prior to the insertion will be performed. Returns: 0 - * on success, -1 on failure with @c errno == problem. If a token - * proxy already exists in the collection with the same name, the - * insertion will fail. Also, is copied. Note that during - * the copy, client_id's are *not* inherited. The client ID of the - * thread using the collection will be used. Client ID's can be - * changed explicity on each proxy using is_member. - */ - int insert (ACE_Token_Proxy &token); - - /** - * Removes the ACE_Token matching the given token_name from the - * collection. On success, extract returns 0. On failure - * (token_name was not in the collection,) extract returns -1. On - * success, the state of the token found is copied into proxy. - * The returned ACE_Token_Proxy* must be deleted by the user. - */ - int extract (const ACE_TCHAR *token_name, ACE_Token_Proxy *&proxy); - - /// Returns the proxy if true. 0 otherwise. - ACE_Token_Proxy *is_member (const ACE_TCHAR *token_name); - - /** - * Is the specified token in the collection? - * 1, yes. - * 0, no. - */ - int is_member (const ACE_Token_Proxy &token); - -// = Collective operation semantics. - -// For acquire, renew, and release, there are two interfaces. Once -// interface allows an operation on a single token in the -// collection. The collective interfaces perform atomic operations -// on the entire collection. For instance, a collective acquire -// will perform an acquire for each and every token in the -// collection or the operation will fail. Currently, these -// operations are performed with no ordering heuristics. That is, -// the Collection steps through the tokens in the order they were -// inserted. For each one it performs the operation (acquire, -// renew, or release). - - /** - * Acquire "atomically" all resources in the collection. This is - * only successfull if all tokens in the collection could be - * acquired. options contains the blocking semantics, timeout - * value, etc. Returns: 0 on success, -1 on failure with @c errno == - * problem. If and error or deadlock occurs for one of the tokens, - * all the tokens will be released and the method will return -1. - * Note that returning on detection of deadlock prevents livelock - * between competing collections. If a collection returns after - * detecting deadlock, it is the application's responsibility to not - * to blindly loop on the collection::acquire operation. In other - * words, once the collection reports deadlock, it is out of our - * hands. - */ - virtual int acquire (int notify = 0, - void (*sleep_hook)(void *) = 0, - ACE_Synch_Options &options = - ACE_Synch_Options::defaults); - - /// Acquire the token corresponding to @a token_name. The other - /// parameters are passed to ::acquire. - virtual int acquire (const ACE_TCHAR *token_name, - int notify = 0, - void (*sleep_hook)(void *) = 0, - ACE_Synch_Options &options = - ACE_Synch_Options::defaults); - - /// Try to acquire all tokens in collection. - virtual int tryacquire (void (*sleep_hook)(void *) = 0); - - /// Try to acquire @a token_name. - virtual int tryacquire (const ACE_TCHAR *token_name, - void (*sleep_hook)(void *) = 0); - - /** - * Renews "atomically" all resources in the collection. This is - * only successfull if all tokens in the collection could be - * renewed. options contains the blocking semantics, timeout - * value, etc. Returns: 0 on success, -1 on failure with @c errno == - * problem. - */ - virtual int renew (int requeue_position = 0, - ACE_Synch_Options &options = - ACE_Synch_Options::defaults); - - - /// Renew the token corresponding to @a token_name. The other - /// parameters are passed to ::renew. - virtual int renew (const ACE_TCHAR *token_name, - int requeue_position = 0, - ACE_Synch_Options &options = - ACE_Synch_Options::defaults); - - /** - * Releases "atomically" all resources in the collection. This is - * only successfull if all tokens in the collection could be - * released. options contains the blocking semantics, timeout - * value, etc. Returns: 0 on success, -1 on failure with @c errno == - * problem. - */ - virtual int release (ACE_Synch_Options &options = - ACE_Synch_Options::defaults); - - - /// Release the token corresponding to . The other - /// parameters are passed to ::release. - virtual int release (const ACE_TCHAR *token_name, - ACE_Synch_Options &options = - ACE_Synch_Options::defaults); - - ~ACE_Token_Collection (void); - - /// Dump the state of the class. - void dump (void) const; - - /// Return the name of the collection. Not very functionally - /// important, but sometimes a useful debugging tool. - virtual const ACE_TCHAR *name (void) const; - -protected: - - typedef ACE_Token_Name TOKEN_NAME; - - /// COLLECTION maintains a mapping from token names to ACE_Tokens* - typedef ACE_Map_Manager - COLLECTION; - - /// Allows iterations through collection_ - /** - * @deprecated Deprecated typedef. Use COLLECTION::ITERATOR trait instead. - */ - typedef COLLECTION::ITERATOR COLLECTION_ITERATOR; - - /// Allows iterations through collection_ - /** - * @deprecated Deprecated typedef. Use COLLECTION::ENTRY trait instead. - */ - typedef COLLECTION::ENTRY COLLECTION_ENTRY; - - /// COLLECTION maintains a mapping from token names to ACE_Tokens*. - COLLECTION collection_; - - /// Whether to print out debug messages or not. - bool debug_; - - /// Name of the collection. - ACE_TCHAR name_[ACE_MAXTOKENNAMELEN]; - - // = I'm not sure what these mean, but they have to be defined since they're - // pure virtual in ACE_Token_Proxy. - virtual ACE_Token_Proxy *clone (void) const; - virtual ACE_Tokens *create_token (const ACE_TCHAR *name); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Token_Collection.inl" -#endif /* __ACE_INLINE__ */ - -#endif /* ACE_HAS_TOKENS_LIBRARY */ - -#include /**/ "ace/post.h" -#endif /* ACE_TOKEN_COLLECTION_H */ diff --git a/externals/ace/Token_Collection.inl b/externals/ace/Token_Collection.inl deleted file mode 100644 index 73f1e95d76e..00000000000 --- a/externals/ace/Token_Collection.inl +++ /dev/null @@ -1,17 +0,0 @@ -// -*- C++ -*- -// -// $Id: Token_Collection.inl 80826 2008-03-04 14:51:23Z wotte $ - -#if defined (ACE_HAS_TOKENS_LIBRARY) - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE const ACE_TCHAR * -ACE_Token_Collection::name (void) const -{ - return name_; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_TOKENS_LIBRARY */ diff --git a/externals/ace/Token_Invariants.cpp b/externals/ace/Token_Invariants.cpp deleted file mode 100644 index 52b1f85eebe..00000000000 --- a/externals/ace/Token_Invariants.cpp +++ /dev/null @@ -1,356 +0,0 @@ -#include "ace/Token_Invariants.h" - -#if defined (ACE_HAS_TOKENS_LIBRARY) - -#include "ace/Object_Manager.h" -#include "ace/os_include/os_typeinfo.h" - -ACE_RCSID (ace, - Token_Invariants, - "$Id: Token_Invariants.cpp 84179 2009-01-16 07:26:45Z johnnyw $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_Token_Invariant_Manager *ACE_Token_Invariant_Manager::instance_ = 0; - -ACE_Token_Invariant_Manager * -ACE_Token_Invariant_Manager::instance (void) -{ - ACE_TRACE ("ACE_Token_Invariant_Manager::instance"); - - // Perform the Double-Check pattern... - if (instance_ == 0) - { - ACE_MT (ACE_TOKEN_CONST::MUTEX *lock = - ACE_Managed_Object::get_preallocated_object - (ACE_Object_Manager::ACE_TOKEN_INVARIANTS_CREATION_LOCK); - ACE_GUARD_RETURN (ACE_TOKEN_CONST::MUTEX, ace_mon, *lock, 0)); - - if (instance_ == 0) - { - ACE_NEW_RETURN (instance_, - ACE_Token_Invariant_Manager, - 0); - // Register for destruction with ACE_Object_Manager. - ACE_Object_Manager::at_exit (instance_, 0, typeid (instance_).name ()); - } - } - - return instance_; -} - -ACE_Token_Invariant_Manager::ACE_Token_Invariant_Manager (void) -{ - ACE_TRACE ("ACE_Token_Invariant_Manager::ACE_Token_Invariant_Manager"); -} - -int -ACE_Token_Invariant_Manager::mutex_acquired (const ACE_TCHAR *token_name) -{ - ACE_TRACE ("ACE_Token_Invariant_Manager::mutex_acquired"); - - ACE_GUARD_RETURN (ACE_TOKEN_CONST::MUTEX, ace_mon, this->lock_, -1); - - ACE_Mutex_Invariants *inv = 0; - if (this->get_mutex (token_name, inv) == -1) - return -1; - - return inv->acquired (); -} - -int -ACE_Token_Invariant_Manager::acquired (const ACE_Token_Proxy *proxy) -{ - ACE_TRACE ("ACE_Token_Invariant_Manager::acquired"); - - // Reach into the proxy to find the token type. - if (proxy->token_->type () == ACE_Tokens::MUTEX) - return this->mutex_acquired (proxy->name ()); - else // ACE_Tokens::RWLOCK. - { - if (proxy->type () == ACE_RW_Token::READER) - return this->reader_acquired (proxy->name ()); - else // ACE_RW_Token::WRITER. - return this->writer_acquired (proxy->name ()); - } -} - -void -ACE_Token_Invariant_Manager::releasing (const ACE_Token_Proxy *proxy) -{ - ACE_TRACE ("ACE_Token_Invariant_Manager::releasing"); - - // Reach into the proxy to find the token type. - if (proxy->token_->type () == ACE_Tokens::MUTEX) - this->mutex_releasing (proxy->name ()); - else // ACE_Tokens::RWLOCK. - this->rwlock_releasing (proxy->name ()); -} - -void -ACE_Token_Invariant_Manager::mutex_releasing (const ACE_TCHAR *token_name) -{ - ACE_TRACE ("ACE_Token_Invariant_Manager::mutex_releasing"); - ACE_GUARD (ACE_TOKEN_CONST::MUTEX, ace_mon, this->lock_); - - ACE_Mutex_Invariants *inv = 0; - if (this->get_mutex (token_name, inv) == 0) - inv->releasing (); -} - -int -ACE_Token_Invariant_Manager::reader_acquired (const ACE_TCHAR *token_name) -{ - ACE_TRACE ("ACE_Token_Invariant_Manager::reader_acquired"); - ACE_GUARD_RETURN (ACE_TOKEN_CONST::MUTEX, ace_mon, this->lock_, -1); - - ACE_RWLock_Invariants *inv = 0; - if (this->get_rwlock (token_name, inv) == -1) - return -1; - - return inv->reader_acquired (); -} - -int -ACE_Token_Invariant_Manager::writer_acquired (const ACE_TCHAR *token_name) -{ - ACE_TRACE ("ACE_Token_Invariant_Manager::writer_acquired"); - - ACE_GUARD_RETURN (ACE_TOKEN_CONST::MUTEX, ace_mon, this->lock_, -1); - - ACE_RWLock_Invariants *inv = 0; - if (this->get_rwlock (token_name, inv) == -1) - return -1; - - return inv->writer_acquired (); -} - -void -ACE_Token_Invariant_Manager::rwlock_releasing (const ACE_TCHAR *token_name) -{ - ACE_TRACE ("ACE_Token_Invariant_Manager::rwlock_releasing"); - - ACE_GUARD (ACE_TOKEN_CONST::MUTEX, ace_mon, this->lock_); - - ACE_RWLock_Invariants *inv = 0; - if (this->get_rwlock (token_name, inv) == 0) - inv->releasing (); -} - -void -ACE_Token_Invariant_Manager::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Token_Invariant_Manager::dump"); - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("mutex_collection_:\n"))); - mutex_collection_.dump (); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("rwlock_collection_:\n"))); - rwlock_collection_.dump (); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - - -int -ACE_Token_Invariant_Manager::get_mutex (const ACE_TCHAR *token_name, - ACE_Mutex_Invariants *&inv) -{ - ACE_TRACE ("ACE_Token_Invariant_Manager::get_mutex"); - TOKEN_NAME name (token_name); - if (mutex_collection_.find (name, inv) == -1) - // We did not find one in the collection. - { - ACE_Mutex_Invariants *new_invariant; - - ACE_NEW_RETURN (new_invariant, - ACE_Mutex_Invariants, - -1); - if (mutex_collection_.bind (name, new_invariant) == -1) - { - delete new_invariant; - return -1; - } - - if (mutex_collection_.find (name, inv) == -1) - // We did not find one in the collection. - return -1; - } - - return 0; -} - -int -ACE_Token_Invariant_Manager::get_rwlock (const ACE_TCHAR *token_name, - ACE_RWLock_Invariants *&inv) -{ - ACE_TRACE ("ACE_Token_Invariant_Manager::get_rwlock"); - TOKEN_NAME name (token_name); - if (rwlock_collection_.find (name, inv) == -1) - // We did not find one in the collection. - { - ACE_RWLock_Invariants *new_invariant; - - ACE_NEW_RETURN (new_invariant, - ACE_RWLock_Invariants, - -1); - if (rwlock_collection_.bind (name, new_invariant) == -1) - return -1; - - if (rwlock_collection_.find (name, inv) == -1) - // We did not find one in the collection. - return -1; - } - - return 0; -} - - -ACE_Token_Invariant_Manager::~ACE_Token_Invariant_Manager (void) -{ - ACE_TRACE ("ACE_Token_Invariant_Manager::~ACE_Token_Invariant_Manager"); - - MUTEX_COLLECTION::ITERATOR iterator (mutex_collection_); - - for (MUTEX_COLLECTION::ENTRY *temp = 0; - iterator.next (temp) != 0; - iterator.advance ()) - delete temp->int_id_; - - RWLOCK_COLLECTION::ITERATOR iterator2 (rwlock_collection_); - - for (RWLOCK_COLLECTION::ENTRY *temp2 = 0; - iterator2.next (temp2) != 0; - iterator2.advance ()) - delete temp2->int_id_; -} - -// ************************************************** -// ************************************************** -// ************************************************** - -ACE_Mutex_Invariants::ACE_Mutex_Invariants (void) -: owners_ (0) -{ -} - -int -ACE_Mutex_Invariants::acquired (void) -{ - if (++owners_ > 1) - { - owners_ = 42; - return 0; - } - else - return 1; -} - -void -ACE_Mutex_Invariants::releasing (void) -{ - if (owners_ == 1) - --owners_; -} - -ACE_Mutex_Invariants::ACE_Mutex_Invariants (const ACE_Mutex_Invariants &rhs) -: owners_ (rhs.owners_) -{ -} - -void -ACE_Mutex_Invariants::operator= (const ACE_Mutex_Invariants &rhs) -{ - owners_ = rhs.owners_; -} - -void -ACE_Mutex_Invariants::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Mutex_Invariants::dump"); - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("owners_ = %d\n"), owners_)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -// ************************************************** -// ************************************************** -// ************************************************** - -ACE_RWLock_Invariants::ACE_RWLock_Invariants (void) -: writers_ (0), - readers_ (0) -{ -} - -int -ACE_RWLock_Invariants::writer_acquired (void) -{ - if (readers_ > 0) - { - writers_ = readers_ = 42; - return 0; - } - else if (++writers_ > 1) - { - writers_ = readers_ = 42; - return 0; - } - else - return 1; -} - -int -ACE_RWLock_Invariants::reader_acquired (void) -{ - if (writers_ > 0) - { - writers_ = readers_ = 42; - return 0; - } - else - { - ++readers_; - return 1; - } -} - -void -ACE_RWLock_Invariants::releasing (void) -{ - if (writers_ == 1) - writers_ = 0; - else if (readers_ > 0) - --readers_; -} - -ACE_RWLock_Invariants::ACE_RWLock_Invariants (const ACE_RWLock_Invariants &rhs) -: writers_ (rhs.writers_), - readers_ (rhs.readers_) -{ -} - -void -ACE_RWLock_Invariants::operator= (const ACE_RWLock_Invariants &rhs) -{ - writers_ = rhs.writers_; - readers_ = rhs.readers_; -} - -void -ACE_RWLock_Invariants::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_RWLock_Invariants::dump"); - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("writers_ = %d readers_ = %d\n"), - writers_, readers_)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_TOKENS_LIBRARY */ diff --git a/externals/ace/Token_Invariants.h b/externals/ace/Token_Invariants.h deleted file mode 100644 index 5cec394763d..00000000000 --- a/externals/ace/Token_Invariants.h +++ /dev/null @@ -1,245 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Token_Invariants.h - * - * $Id: Token_Invariants.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Tim Harrison (harrison@cs.wustl.edu) - * - * Allows applications to test that invariants are always - * satisfied. Can test mutexes and readers/writer locks. Does - * not test recursive acquisition. - * - * - */ -//============================================================================= - -#ifndef ACE_TOKEN_INVARIANTS_H -#define ACE_TOKEN_INVARIANTS_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_TOKENS_LIBRARY) - -#include "ace/Map_Manager.h" -#include "ace/Local_Tokens.h" -#include "ace/Null_Mutex.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Mutex_Invariants - * - * @brief Mutex Invariants - * = INVARIANTS - * 1. Only one owner at a time. - */ -class ACE_Export ACE_Mutex_Invariants -{ -public: - /// Default construction. - ACE_Mutex_Invariants (void); - - /// Returns 1 on success, 0 when an invariant has been violated and - /// -1 on error. - int acquired (void); - - /// Updates internal database. - void releasing (void); - - // = Map_Manager operations. - - /// Copy construction. - ACE_Mutex_Invariants (const ACE_Mutex_Invariants &rhs); - - /// Copy. - void operator= (const ACE_Mutex_Invariants &rhs); - - /// Dump the state of the class. - void dump (void) const; - -private: - /// Number of owners. This had better be 0 >= owners_ <= 1; - int owners_; -}; - -/** - * @class ACE_RWLock_Invariants - * - * @brief RWLock Invariants - * - * Preserve the following invariants: - * -# Only one writer at a time. - * -# If there is an owning writer, there are no owning readers. - */ -class ACE_Export ACE_RWLock_Invariants -{ -public: - /// Default construction. - ACE_RWLock_Invariants (void); - - /// Returns 1 on success, 0 when an invariant has been violated and - /// -1 on error. - int writer_acquired (void); - - /// Returns 1 on success, 0 when an invariant has been violated and - /// -1 on error. - int reader_acquired (void); - - /// Updates internal database. - void releasing (void); - - // = Map_Manager operations. - - /// Copy construction. - ACE_RWLock_Invariants (const ACE_RWLock_Invariants &rhs); - - /// Copy. - void operator= (const ACE_RWLock_Invariants &rhs); - - /// Dump the state of the class. - void dump (void) const; - -private: - /// Number of owning writers. - int writers_; - - /// Number of owning readers. - int readers_; -}; - -/** - * @class ACE_Token_Invariant_Manager - * - * @brief Token Invariants - * - * The Token Invariant Manager allows applications to test that - * invariants are always satisfied. Currently, Token_Invariants - * can test mutexes and readers/writer locks. Does not test - * recursive acquisition. - * Note that this class does not ever clean its database. Until - * destroyed, it's size will forever increase. - */ -class ACE_Export ACE_Token_Invariant_Manager : public ACE_Cleanup -{ -public: - - /// Singleton access point. - static ACE_Token_Invariant_Manager *instance (void); - - // = Polymorphic methods. Just pass in the proxy and the method - // figures out the type of the token. - - /// Returns 1 on success, 0 when an invariant has been violated and - /// -1 on error. - int acquired (const ACE_Token_Proxy *proxy); - - /// Updates internal database. - void releasing (const ACE_Token_Proxy *proxy); - - // = Explicit methods. These to not require actual proxies in order - // to test a scenario. - - /// Returns 1 on success, 0 when an invariant has been violated and - /// -1 on error. - int mutex_acquired (const ACE_TCHAR *token_name); - - /// Updates internal database. - void mutex_releasing (const ACE_TCHAR *token_name); - - /// Returns 1 on success, 0 when an invariant has been violated and - /// -1 on error. - int reader_acquired (const ACE_TCHAR *token_name); - - /// Returns 1 on success, 0 when an invariant has been violated and - /// -1 on error. - int writer_acquired (const ACE_TCHAR *token_name); - - /// Updates internal database. - void rwlock_releasing (const ACE_TCHAR *token_name); - - /// Dump the state of the class. - void dump (void) const; - - // = The following two method should be in the protected part of the - // class. Bugs with certain compilers preclude this. - /// Prevent non-singleton construction. - ACE_Token_Invariant_Manager (void); - - /// Destruction. - virtual ~ACE_Token_Invariant_Manager (void); - -protected: - /// Return or create. - int get_mutex (const ACE_TCHAR *token_name, - ACE_Mutex_Invariants *&inv); - - /// Return or create. - int get_rwlock (const ACE_TCHAR *token_name, - ACE_RWLock_Invariants *&inv); - - /// ACE_Mutex_Token used to lock internal data structures. - ACE_TOKEN_CONST::MUTEX lock_; - - /// This may be changed to a template type. - typedef ACE_Token_Name TOKEN_NAME; - - /// COLLECTION maintains a mapping from token names to mutexes. - typedef ACE_Map_Manager - MUTEX_COLLECTION; - - /// Allows iterations through collection. - /** - * @deprecated Deprecated typedef. Use MUTEX_COLLECTION::ITERATOR trait - * instead. - */ - typedef MUTEX_COLLECTION::ITERATOR MUTEX_COLLECTION_ITERATOR; - - /// Allows iterations through collection. - /** - * @deprecated Deprecated typedef. Use MUTEX_COLLECTION::ENTRY trait - * instead. - */ - typedef MUTEX_COLLECTION::ENTRY MUTEX_COLLECTION_ENTRY; - - /// MUTEX_COLLECTION maintains a mapping from token names to mutexes. - MUTEX_COLLECTION mutex_collection_; - - /// COLLECTION maintains a mapping from token names to mutexes. - typedef ACE_Map_Manager - RWLOCK_COLLECTION; - - /// Allows iterations through collection. - /** - * @deprecated Deprecated typedef. Use RWLOCK_COLLECTION::ITERATOR trait - * instead. - */ - typedef RWLOCK_COLLECTION::ITERATOR RWLOCK_COLLECTION_ITERATOR; - - /// Allows iterations through collection. - /** - * @deprecated Deprecated typedef. Use RWLOCK_COLLECTION::ENTRY trait - * instead. - */ - typedef RWLOCK_COLLECTION::ENTRY RWLOCK_COLLECTION_ENTRY; - - /// MUTEX_COLLECTION maintains a mapping from token names to mutexes. - RWLOCK_COLLECTION rwlock_collection_; - - /// Singleton pointer. - static ACE_Token_Invariant_Manager *instance_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_TOKENS_LIBRARY */ - -#include /**/ "ace/post.h" -#endif /* ACE_TOKEN_INVARIANTS_H */ diff --git a/externals/ace/Token_Manager.cpp b/externals/ace/Token_Manager.cpp deleted file mode 100644 index 1127622d96e..00000000000 --- a/externals/ace/Token_Manager.cpp +++ /dev/null @@ -1,274 +0,0 @@ -#include "ace/Token_Manager.h" - -#if defined (ACE_HAS_TOKENS_LIBRARY) - -#include "ace/Object_Manager.h" -#include "ace/os_include/os_typeinfo.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Token_Manager.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID (ace, - Token_Manager, - "$Id: Token_Manager.cpp 84179 2009-01-16 07:26:45Z johnnyw $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// singleton token manager -ACE_Token_Manager *ACE_Token_Manager::token_manager_ = 0; - -ACE_Token_Manager::ACE_Token_Manager () -{ - ACE_TRACE ("ACE_Token_Manager::ACE_Token_Manager"); -} - -ACE_Token_Manager::~ACE_Token_Manager () -{ - ACE_TRACE ("ACE_Token_Manager::~ACE_Token_Manager"); - - COLLECTION::ITERATOR iterator (collection_); - - for (COLLECTION::ENTRY *temp = 0; - iterator.next (temp) != 0; - iterator.advance ()) - { - // @ should I be doing an unbind here? - delete temp->int_id_; - // The ext_id_'s delete themselves when the array of - // COLLECTION::ENTRYs goes away. - } -} - -ACE_Token_Manager * -ACE_Token_Manager::instance (void) -{ - ACE_TRACE ("ACE_Token_Manager::instance"); - - // This first check is to avoid acquiring the mutex in the common - // case. Double-Check pattern rules. - if (token_manager_ == 0) - { -#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) - ACE_TOKEN_CONST::MUTEX *lock = - ACE_Managed_Object::get_preallocated_object - (ACE_Object_Manager::ACE_TOKEN_MANAGER_CREATION_LOCK); - ACE_GUARD_RETURN (ACE_TOKEN_CONST::MUTEX, ace_mon, *lock, 0); -#endif /* ACE_MT_SAFE */ - - if (token_manager_ == 0) - { - ACE_NEW_RETURN (token_manager_, - ACE_Token_Manager, - 0); - // Register for destruction with ACE_Object_Manager. - ACE_Object_Manager::at_exit (token_manager_, 0, typeid (token_manager_).name ()); - } - } - - return token_manager_; -} - -void -ACE_Token_Manager::get_token (ACE_Token_Proxy *proxy, - const ACE_TCHAR *token_name) -{ - ACE_TRACE ("ACE_Token_Manager::get_token"); - // Hmm. I think this makes sense. We perform our own locking here - // (see safe_acquire.) We have to make sure that only one thread - // uses the collection at a time. - - ACE_GUARD (ACE_TOKEN_CONST::MUTEX, ace_mon, this->lock_); - - TOKEN_NAME name (token_name); - - if (collection_.find (name, proxy->token_) == -1) - // We did not find one in the collection. - { - // Make one. - proxy->token_ = proxy->create_token (token_name); - - // Put it in the collection. - if (collection_.bind (name, proxy->token_) == -1) - { - delete proxy->token_; - proxy->token_ = 0; - } - } - - if (proxy->token_ != 0) - proxy->token_->inc_reference (); - - // We may be returning proxy->token_ == 0 if new failed, caller must - // check. -} - -// 0. check_deadlock (TOKEN) -// 1. if TOKEN->visited (), return 0. -// 2. mark TOKEN visited. -// 3. get ALL_OWNERS -// 4. if CLIENT in ALL_OWNERS, return *DEADLOCK*. -// 5. for each OWNER in ALL_OWNERS, -// 6. if OWNER is not waiting for a NEW_TOKEN, continue. -// 7. else, if check_deadlock (NEW_TOKEN) == 1, return *DEADLOCK* -// 8. return 0. - -int -ACE_Token_Manager::check_deadlock (ACE_Token_Proxy *proxy) -{ - ACE_TRACE ("ACE_Token_Manager::check_deadlock"); - - // Start the recursive deadlock detection algorithm. - int result = this->check_deadlock (proxy->token_, proxy); - - // Whether or not we detect deadlock, we have to unmark all tokens - // for the next time. - COLLECTION::ITERATOR iterator (collection_); - for (COLLECTION::ENTRY *temp = 0; - iterator.next (temp) != 0; - iterator.advance ()) - temp->int_id_->visit (0); - - return result; -} - -int -ACE_Token_Manager::check_deadlock (ACE_Tokens *token, ACE_Token_Proxy *proxy) -{ - ACE_TRACE ("ACE_Token_Manager::check_deadlock"); - - if (token->visited ()) - return 0; - - token->visit (1); - - ACE_Tokens::OWNER_STACK owners; - - int is_owner = token->owners (owners, proxy->client_id ()); - - switch (is_owner) - { - case -1: - // Error. - return -1; - case 1: - // The caller is an owner, so we have a deadlock situation. - if (debug_) - { - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Deadlock detected.\n"))); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("%s owns %s and is waiting for %s.\n"), - proxy->client_id (), - token->name (), - proxy->token_->name ())); - } - - return 1; - case 0: - default: - // Recurse on each owner. - while (!owners.is_empty ()) - { - ACE_TPQ_Entry *e; - owners.pop (e); - // If the owner is waiting on another token, recurse. - ACE_Tokens *twf = this->token_waiting_for (e->client_id ()); - if ((twf != 0) && - (this->check_deadlock (twf, proxy) == 1)) - { - if (debug_) - { - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("%s owns %s and is waiting for %s.\n"), - e->client_id (), - token->name (), - twf->name ())); - } - return 1; - } - // else, check the next owner. - } - - // We've checked all the owners and found no deadlock. - return 0; - } -} - - -ACE_Tokens * -ACE_Token_Manager::token_waiting_for (const ACE_TCHAR *client_id) -{ - COLLECTION::ITERATOR iterator (collection_); - for (COLLECTION::ENTRY *temp = 0; - iterator.next (temp) != 0; - iterator.advance ()) - { - if (temp->int_id_->is_waiting_for (client_id)) - return temp->int_id_; - } - - // nothing was found, return NULL. - return 0; -} - -// Notify the token manager that a token is has been released. If -// as a result, there is no owner of the token, the token is -// deleted. -void -ACE_Token_Manager::release_token (ACE_Tokens *&token) -{ - ACE_TRACE ("ACE_Token_Manager::release_token"); - // again, let's perform our own locking here. - - ACE_GUARD (ACE_TOKEN_CONST::MUTEX, ace_mon, this->lock_); - - if (token->dec_reference () == 0) - { - // No one has the token, so we can delete it and remove it from - // our collection. First, let's get it from the collection. - TOKEN_NAME token_name (token->name ()); - - ACE_Tokens *temp; - - if (collection_.unbind (token_name, temp) == -1) - // we did not find one in the collection - { - errno = ENOENT; - ACE_ERROR ((LM_ERROR, ACE_TEXT ("Token Manager could not release %s:%d\n"), - token->name (), token->type ())); - // @@ bad - } - else - // we found it - { - // sanity pointer comparison. The token referenced by the - // proxy better be the one we found in the list. - ACE_ASSERT (token == temp); - delete token; // or delete temp - // we set their token to zero. if the calling proxy is - // still going to be used, it had better check it's token - // value before calling a method on it! - token = 0; - } - } - // else - // someone is still interested in the token, so keep it around. -} - -void -ACE_Token_Manager::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Token_Manager::dump"); - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("ACE_Token_Manager::dump:\n"))); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("lock_\n"))); - lock_.dump (); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("collection_\n"))); - collection_.dump (); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_TOKENS_LIBRARY */ diff --git a/externals/ace/Token_Manager.h b/externals/ace/Token_Manager.h deleted file mode 100644 index 9882e28ef67..00000000000 --- a/externals/ace/Token_Manager.h +++ /dev/null @@ -1,150 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Token_Manager.h - * - * $Id: Token_Manager.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Tim Harrison (harrison@cs.wustl.edu) - */ -//============================================================================= - -#ifndef ACE_TOKEN_MANAGER_H -#define ACE_TOKEN_MANAGER_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Local_Tokens.h" - -#if defined (ACE_HAS_TOKENS_LIBRARY) - -#include "ace/Null_Mutex.h" -#include "ace/Map_Manager.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -class ACE_Local_Mutex; -class ACE_Mutex_Token; - -/** - * @class ACE_Token_Manager - * - * @brief Manages all tokens in a process space. - * - * Factory: Proxies use the token manager to obtain token - * references. This allows multiple proxies to reference the same - * logical token. - * Deadlock detection: Tokens use the manager to check for - * deadlock situations during acquires. - */ -class ACE_Export ACE_Token_Manager : public ACE_Cleanup -{ - - // To add a new type of token (e.g. semaphore), do the following - // steps: 1. Create a new derivation of ACE_Token. This class - // defines the semantics of the new Token. 2. Create a - // derivation of ACE_Token_Manager. You will only need to - // redefine make_mutex. -public: - ACE_Token_Manager (void); - virtual ~ACE_Token_Manager (void); - - /// Get the pointer to token manager singleton. - static ACE_Token_Manager *instance (void); - - /// Set the pointer to token manager singleton. - void instance (ACE_Token_Manager *); - - /** - * The Token manager uses ACE_Token_Proxy::token_id_ to look for - * an existing token. If none is found, the Token Manager calls - * ACE_Token_Proxy::create_token to create a new one. When - * finished, sets ACE_Token_Proxy::token_. @a token_name uniquely - * id's the token name. - */ - void get_token (ACE_Token_Proxy *, const ACE_TCHAR *token_name); - - /** - * Check whether acquire will cause deadlock or not. - * returns 1 if the acquire will _not_ cause deadlock. - * returns 0 if the acquire _will_ cause deadlock. - * This method ignores recursive acquisition. That is, it will not - * report deadlock if the client holding the token requests the - * token again. Thus, it assumes recursive mutexes. - */ - int check_deadlock (ACE_Token_Proxy *proxy); - int check_deadlock (ACE_Tokens *token, ACE_Token_Proxy *proxy); - - /// Notify the token manager that a token has been released. If as a - /// result, there is no owner of the token, the token is deleted. - void release_token (ACE_Tokens *&token); - - /** - * This is to allow Tokens to perform atomic transactions. The - * typical usage is to acquire this mutex, check for a safe_acquire, - * perform some queueing (if need be) and then release the lock. - * This is necessary since safe_acquire is implemented in terms of - * the Token queues. - */ - ACE_TOKEN_CONST::MUTEX &mutex (void); - - /// Dump the state of the class. - void dump (void) const; - - /// Turn debug mode on/off. - void debug (bool d); - -private: - /// Whether to print debug messages or not. - bool debug_; - - /// pointer to singleton token manager. - static ACE_Token_Manager *token_manager_; - - /// Return the token that the given client_id is waiting for, if any - ACE_Tokens *token_waiting_for (const ACE_TCHAR *client_id); - - /// ACE_Mutex_Token used to lock internal data structures. - ACE_TOKEN_CONST::MUTEX lock_; - - /// This may be changed to a template type. - typedef ACE_Token_Name TOKEN_NAME; - - /// COLLECTION maintains a mapping from token names to ACE_Tokens* - typedef ACE_Map_Manager - COLLECTION; - - /// Allows iterations through collection_ - /** - * @deprecated Deprecated typedef. Use COLLECTION::ITERATOR trait - * instead. - */ - typedef COLLECTION::ITERATOR COLLECTION_ITERATOR; - - /// Allows iterations through collection_ - /** - * @deprecated Deprecated typedef. Use COLLECTION::ENTRY trait - * instead. - */ - typedef COLLECTION::ENTRY COLLECTION_ENTRY; - - /// COLLECTION maintains a mapping from token names to ACE_Tokens*. - COLLECTION collection_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Token_Manager.inl" -#endif /* __ACE_INLINE__ */ - -#endif /* ACE_HAS_TOKENS_LIBRARY */ - -#include /**/ "ace/post.h" -#endif /* ACE_TOKEN_MANAGER_H */ diff --git a/externals/ace/Token_Manager.inl b/externals/ace/Token_Manager.inl deleted file mode 100644 index a44778c89b2..00000000000 --- a/externals/ace/Token_Manager.inl +++ /dev/null @@ -1,25 +0,0 @@ -// -*- C++ -*- -// -// $Id: Token_Manager.inl 80826 2008-03-04 14:51:23Z wotte $ - -#if defined (ACE_HAS_TOKENS_LIBRARY) - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE ACE_TOKEN_CONST::MUTEX & -ACE_Token_Manager::mutex (void) -{ - ACE_TRACE ("ACE_Token_Manager::mutex"); - return lock_; -} - -ACE_INLINE void -ACE_Token_Manager::debug (bool d) -{ - ACE_TRACE ("ACE_Token_Manager::debug"); - debug_ = d; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_TOKENS_LIBRARY */ diff --git a/externals/ace/Token_Request_Reply.cpp b/externals/ace/Token_Request_Reply.cpp deleted file mode 100644 index 598afe01388..00000000000 --- a/externals/ace/Token_Request_Reply.cpp +++ /dev/null @@ -1,186 +0,0 @@ -// $Id: Token_Request_Reply.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/Token_Request_Reply.h" - -#if defined (ACE_HAS_TOKENS_LIBRARY) - -#if !defined (__ACE_INLINE__) -#include "ace/Token_Request_Reply.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID(ace, Token_Request_Reply, "$Id: Token_Request_Reply.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Default "do nothing" constructor. - -ACE_Token_Request::ACE_Token_Request (void) - : token_name_ (0), - client_id_ (0) -{ -} - -// Create a ACE_Token_Request message. - -ACE_Token_Request::ACE_Token_Request (int token_type, - int proxy_type, - ACE_UINT32 operation_type, - const ACE_TCHAR token_name[], - const ACE_TCHAR client_id[], - const ACE_Synch_Options &options) -{ - this->token_type (token_type); - this->proxy_type (proxy_type); - this->operation_type (operation_type); - this->requeue_position (0); // to avoid Purify UMR - this->notify (0); // to avoid Purify UMR - transfer_.arg_ = 0; // to avoid Purify UMR - ACE_OS::memset (transfer_.data_, 0, sizeof transfer_.data_); // to avoid Purify UMR - this->token_name (token_name, client_id); - this->options (options); -} - -// Encode the transfer buffer into network byte order -// so that it can be sent to the server. - -int -ACE_Token_Request::encode (void *&buf) -{ - buf = (void *) &this->transfer_; - return this->length (); -} - -// Decode the transfer buffer into host byte byte order -// so that it can be used by the server. - -int -ACE_Token_Request::decode (void) -{ - this->token_name_ = this->transfer_.data_; - - options_.set (transfer_.use_timeout_ == 1 ? ACE_Synch_Options::USE_TIMEOUT : 0, - ACE_Time_Value (transfer_.sec_, transfer_.usec_), - (void *) transfer_.arg_); - - // Decode the variable-sized portion. - size_t token_len = ACE_OS::strlen (this->token_name_); - - // Check to make sure this->tokenName_ isn't too long! - if (token_len >= ACE_MAXTOKENNAMELEN) - { - errno = ENAMETOOLONG; - return -1; - } - else // Skip this->tokenName_ + '\0' + ':'. - this->client_id_ = - &this->token_name_[(token_len + 2) * sizeof (ACE_TCHAR)]; - - // Fixed size header - // token_name_ plus '\0' - // ':' - // client_id_ plus '\0' - size_t data_size = ACE_TOKEN_REQUEST_HEADER_SIZE - + ACE_OS::strlen (this->token_name_) + 1 - + ACE_OS::strlen (this->client_id_) + 1 - + 1; - - // Make sure the message was correctly received and framed. - return this->length () == data_size ? 0 : -1; -} - -// Print out the current values of the ACE_Token_Request. - -void -ACE_Token_Request::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("*******\nlength = %d\ntoken name = %s\nclient id = %s\n"), - this->length (), this->token_name (), this->client_id ())); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("type = "))); - - if (this->token_type () == ACE_Tokens::MUTEX) - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("MUTEX\n"))); - else // == ACE_Tokens::RWLOCK - { - if (this->proxy_type () == ACE_RW_Token::READER) - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("RLOCK\n"))); - else // == WRITER - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("WLOCK\n"))); - } - - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("operation = "))); - switch (this->operation_type ()) - { - case ACE_Token_Request::ACQUIRE: - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("ACQUIRE\n"))); - break; - case ACE_Token_Request::RELEASE: - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("RELEASE\n"))); - break; - case ACE_Token_Request::RENEW: - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("RENEW\n"))); - break; - default: - ACE_DEBUG ((LM_DEBUG, ACE_TEXT (" = %d\n"), this->operation_type ())); - break; - } - - if (this->options ()[ACE_Synch_Options::USE_TIMEOUT] == 0) - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("blocking forever\n"))); - else - { - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("waiting for %d secs and %d usecs\n"), - this->options ().timeout ().sec (), this->options ().timeout ().usec ())); - } - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -// ************************************************************ -// ************************************************************ -// ************************************************************ - -// Create a ACE_Token_Reply message. - -ACE_Token_Reply::ACE_Token_Reply (void) // Type of reply. -{ - this->arg (0); - this->errnum (0); - this->length (sizeof (Transfer)); -} - -// Encode the transfer buffer into network byte order -// so that it can be sent to the client. - -int -ACE_Token_Reply::encode (void *&buf) -{ - buf = (void *) &this->transfer_; - return this->length (); -} - -// Decode the transfer buffer into host byte order -// so that it can be used by the client. - -int -ACE_Token_Reply::decode (void) -{ - return 0; -} - -// Print out current values of the ACE_Token_Reply object. - -void -ACE_Token_Reply::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("*******\nlength = %d\nerrnum = %d"), - this->length (), this->errnum ())); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("arg = %d"), this->arg ())); -#endif /* ACE_HAS_DUMP */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_TOKENS_LIBRARY */ diff --git a/externals/ace/Token_Request_Reply.h b/externals/ace/Token_Request_Reply.h deleted file mode 100644 index 01a7cfd3e82..00000000000 --- a/externals/ace/Token_Request_Reply.h +++ /dev/null @@ -1,270 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Token_Request_Reply.h - * - * $Id: Token_Request_Reply.h 80826 2008-03-04 14:51:23Z wotte $ - * - * Define the format used to exchange messages between the - * ACE_Token Server and its clients. - * - * - * @author Douglas C. Schmidt (schmidt@cs.wustl.edu) - * @author Tim Harrison (harrison@cs.wustl.edu) - */ -//============================================================================= - - -#ifndef ACE_TOKEN_REQUEST_REPLY_H -#define ACE_TOKEN_REQUEST_REPLY_H -#include /**/ "ace/pre.h" - -#include "ace/Local_Tokens.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_TOKENS_LIBRARY) - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/// Specifies the size of the fixed length portion of -/// the Transfer structure in ACE_Token_Request -#define ACE_TOKEN_REQUEST_HEADER_SIZE 40 - -/** - * @class ACE_Token_Request - * - * @brief Message format for delivering requests to the ACE_Token Server. - * - * This class is implemented to minimize data copying. - * In particular, all marshaling is done in situ... - */ -class ACE_Export ACE_Token_Request -{ -public: - /// Operation types. - enum OPERATION - { - /// Acquire the token. - ACQUIRE, - /// Release the token. - RELEASE, - /// Renew the token. - RENEW, - /// Remove the token. - REMOVE, - // Try to acquire the token. - TRY_ACQUIRE - }; - - /// Default constructor. - ACE_Token_Request (void); - - /** - * @param token_type MUTEX, RWLOCK - * @param proxy_type MUTEX, RLOCK, WLOCK (acquires mean different things) - * @param operation method - * @param token_name - * @param client_id - * @param options We check USE_TIMEOUT and use the arg. - */ - ACE_Token_Request (int token_type, - int proxy_type, - ACE_UINT32 operation, - const ACE_TCHAR token_name[], - const ACE_TCHAR client_id[], - const ACE_Synch_Options &options); - - /// Get the length of the encoded/decoded message. - ACE_UINT32 length (void) const; - - /// Set the length of the encoded/decoded message. - void length (ACE_UINT32); - - /// Get the type of proxy - int proxy_type (void) const; - - /// Set the type of proxy - void proxy_type (int proxy_type); - - /// Get the type of token - int token_type (void) const; - - /// Set the type of token - void token_type (int token_type); - - /// Get the type of the operation. - ACE_UINT32 operation_type (void) const; - - /// Set the type of the operation. - void operation_type (ACE_UINT32); - - /// Get the requeue position. These should be used when renew - /// is the operation type. - ACE_UINT32 requeue_position (void) const; - - /// Set the requeue position. These should be used when renew - /// is the operation type. - void requeue_position (ACE_UINT32); - - /// Get notify. These should be used when acquire is the operation type. - ACE_UINT32 notify (void) const; - - /// Set notify. These should be used when acquire is the operation type. - void notify (ACE_UINT32); - - /// Get the timeout. - ACE_Synch_Options &options (void) const; - - /// Set the timeout. - void options (const ACE_Synch_Options &options); - - // = Set/get the name of the token and the client id. The set - // method is combined to make it easier on us. We're copying the - // names as a contiguous buffer. - ACE_TCHAR *token_name (void) const; - ACE_TCHAR *client_id (void) const; - void token_name (const ACE_TCHAR *token_name, const ACE_TCHAR *client_id); - - /// Encode the message before transmission. - int encode (void *&); - - /// Decode message after reception. This must be called to set the - /// internal options. - int decode (void); - - /// Print out the values of the message for debugging purposes. - void dump (void) const; - -private: - // = The 5 fields in the struct are transmitted to the server. - // The remaining 2 fields are not tranferred -- they are used only on - // the server-side to simplify lookups. - - struct Transfer - { - /// Length of entire request. - ACE_UINT32 length_; - - /// Type of the request (i.e., MUTEX, RLOCK, WLOCK... - ACE_UINT32 token_type_; - - /// Type of the request (i.e., MUTEX, RLOCK, WLOCK... - ACE_UINT32 proxy_type_; - - /// Type of the request (i.e., , , , and ). - ACE_UINT32 operation_type_; - - /// this only makes sense when operation type is renew - ACE_UINT32 requeue_position_; - - /// this only makes sense when operation type is renew - ACE_UINT32 notify_; - - // = ACE_Synch_Options stuff - - /// Indicates if we should block forever. If 1, then - /// and indicates how long we should wait. If 0, - /// then we block forever. - ACE_UINT32 use_timeout_; - - /// Max seconds willing to wait for token if not blocking forever. - ACE_UINT32 sec_; - - /// Max micro seconds to wait for token if not blocking forever. - ACE_UINT32 usec_; - - /// value returned in ; - ACE_UINT32 arg_; - - /// The data portion contains the including a 0 terminator, - /// a ':', then the including a 0 terminator - ACE_TCHAR data_[ACE_MAXTOKENNAMELEN + ACE_MAXCLIENTIDLEN + 3]; - } transfer_; - - /// Pointer to the beginning of the token name in this->data_. - ACE_TCHAR *token_name_; - - /// Pointer to the beginning of the client id in this->data_; - ACE_TCHAR *client_id_; - - /// Holds arg, sec, usec, etc. - ACE_Synch_Options options_; -}; - -/** - * @class ACE_Token_Reply - * - * @brief Message format for delivering replies from the ACE_Token Server. - * - * This class is implemented to minimize data copying. - * In particular, all marshaling is done in situ... - */ -class ACE_Export ACE_Token_Reply -{ -public: - /// Default constructor. - ACE_Token_Reply (void); - - /// Get the length of the encoded/decoded message. - ACE_UINT32 length (void) const; - - /// Set the length of the encoded/decoded message. - void length (ACE_UINT32); - - /// Get the errno of a reply. - ACE_UINT32 errnum (void) const; - - /// Set the errno of a reply. - void errnum (ACE_UINT32); - - /// Get the arg of a reply. - ACE_UINT32 arg (void) const; - - /// Set the arg of a reply. - void arg (ACE_UINT32); - - /// Encode the message before transfer. - int encode (void *&); - - /// Decode a message after reception. - int decode (void); - - /// Print out the values of the message for debugging purposes. - void dump (void) const; - -private: - // = The 2 fields in the struct are transmitted to the server. - - struct Transfer - { - /// Length of entire reply. - ACE_UINT32 length_; - - /// Indicates why error occurred if type_> == . - /// Typical reasons include: - /// @c EWOULDBLOCK (if client requested a non-blocking check for the token). - /// @c ETIME (if the client timed out after waiting for the token). - /// (if the token lock was removed out from underneath a waiter). - /// (attempt to renew a token that isn't owned by the client). - ACE_UINT32 errno_; - - /// magic cookie - ACE_UINT32 arg_; - - } transfer_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Token_Request_Reply.inl" -#endif /* __ACE_INLINE__ */ - -#endif /* ACE_HAS_TOKENS_LIBRARY */ - -#include /**/ "ace/post.h" -#endif /* ACE_TOKEN_REQUEST_REPLY_H */ diff --git a/externals/ace/Token_Request_Reply.inl b/externals/ace/Token_Request_Reply.inl deleted file mode 100644 index 4291bfa6089..00000000000 --- a/externals/ace/Token_Request_Reply.inl +++ /dev/null @@ -1,205 +0,0 @@ -// -*- C++ -*- -// -// $Id: Token_Request_Reply.inl 80826 2008-03-04 14:51:23Z wotte $ - -#if defined (ACE_HAS_TOKENS_LIBRARY) - -#include "ace/Truncate.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// = Set/get the length of the encoded/decoded message. - -ACE_INLINE ACE_UINT32 -ACE_Token_Request::length (void) const -{ - return ntohl (this->transfer_.length_); -} - -ACE_INLINE void -ACE_Token_Request::length (ACE_UINT32 l) -{ - this->transfer_.length_ = htonl (l); -} - -// = Set/get the type of the message. -ACE_INLINE int -ACE_Token_Request::token_type (void) const -{ - return (int) ntohl (this->transfer_.token_type_); -} - -ACE_INLINE void -ACE_Token_Request::token_type (int t) -{ - this->transfer_.token_type_ = htonl ((ACE_UINT32) t); -} - -// = Set/get the type of the message. -ACE_INLINE int -ACE_Token_Request::proxy_type (void) const -{ - return (int) ntohl (this->transfer_.proxy_type_); -} - -ACE_INLINE void -ACE_Token_Request::proxy_type (int t) -{ - this->transfer_.proxy_type_ = htonl ((ACE_UINT32) t); -} - -// = Set/get the type of the message. -ACE_INLINE ACE_UINT32 -ACE_Token_Request::operation_type (void) const -{ - return ntohl (this->transfer_.operation_type_); -} - -ACE_INLINE void -ACE_Token_Request::operation_type (ACE_UINT32 t) -{ - this->transfer_.operation_type_ = htonl (t); -} - -// = Set/get the requeue position -ACE_INLINE ACE_UINT32 -ACE_Token_Request::requeue_position (void) const -{ - return ntohl (this->transfer_.requeue_position_); -} - -ACE_INLINE void -ACE_Token_Request::requeue_position (ACE_UINT32 rq) -{ - this->transfer_.requeue_position_ = htonl (rq); -} - -// = Set/get the requeue position -ACE_INLINE ACE_UINT32 -ACE_Token_Request::notify (void) const -{ - return ntohl (this->transfer_.notify_); -} - -ACE_INLINE void -ACE_Token_Request::notify (ACE_UINT32 rq) -{ - this->transfer_.notify_ = htonl (rq); -} - -// = Set/get the blocking semantics. -ACE_INLINE ACE_Synch_Options & -ACE_Token_Request::options (void) const -{ - return (ACE_Synch_Options &) options_; -} - -ACE_INLINE void -ACE_Token_Request::options (const ACE_Synch_Options &opt) -{ - // fight the friggin const from hell - ACE_Synch_Options *options = (ACE_Synch_Options *) &opt; - - transfer_.use_timeout_ = options->operator[](ACE_Synch_Options::USE_TIMEOUT); - if (transfer_.use_timeout_ == 1) - { - transfer_.usec_ = options->timeout ().usec (); - if (options->timeout ().sec () > (time_t) ACE_UINT32_MAX) - transfer_.sec_ = ACE_UINT32_MAX; - else - transfer_.sec_ = static_cast (options->timeout ().sec ()); - } - else - { - transfer_.usec_ = 0; - transfer_.sec_ = 0; - } -} - -// = Set/get the name of the token. -ACE_INLINE ACE_TCHAR * -ACE_Token_Request::token_name (void) const -{ - return token_name_; -} - -ACE_INLINE void -ACE_Token_Request::token_name (const ACE_TCHAR *token_name, - const ACE_TCHAR *client_id) -{ - size_t token_name_length = ACE_OS::strlen (token_name) + 1; // Add 1 for '\0'. - size_t client_id_length = ACE_OS::strlen (client_id) + 1; // Add 1 for '\0'. - - // Set up pointers and copy token_name and client_id into request. - token_name_ = this->transfer_.data_; - client_id_ = &this->token_name_[token_name_length + 1]; // Add 1 for ':'; - client_id_[-1] = ACE_TEXT (':'); // Insert the ':' before this->clientId_. - - (void) ACE_OS::memcpy (this->token_name_, - token_name, - token_name_length * sizeof (ACE_TCHAR)); - (void) ACE_OS::memcpy (this->client_id_, - client_id, - client_id_length * sizeof (ACE_TCHAR)); - - // Fixed length header size - size_t len = ACE_TOKEN_REQUEST_HEADER_SIZE; - - // ... then add in the amount of the variable-sized portion. - len += token_name_length + client_id_length + 1; - this->length (ACE_Utils::truncate_cast (len)); -} - -// = Set/get the id of the client. -ACE_INLINE ACE_TCHAR * -ACE_Token_Request::client_id (void) const -{ - return this->client_id_; -} - -// ************************************************************ -// ************************************************************ -// ************************************************************ - -// = Set/get the length of the encoded/decoded message. -ACE_INLINE ACE_UINT32 -ACE_Token_Reply::length (void) const -{ - return ntohl (this->transfer_.length_); -} - -ACE_INLINE void -ACE_Token_Reply::length (ACE_UINT32 l) -{ - this->transfer_.length_ = htonl (l); -} - -// = Set/get the errno of a failed reply. -ACE_INLINE ACE_UINT32 -ACE_Token_Reply::errnum (void) const -{ - return ntohl (this->transfer_.errno_); -} - -ACE_INLINE void -ACE_Token_Reply::errnum (ACE_UINT32 e) -{ - this->transfer_.errno_ = htonl (e); -} - -// = Set/get the length of the encoded/decoded message. -ACE_INLINE ACE_UINT32 -ACE_Token_Reply::arg (void) const -{ - return ntohl (this->transfer_.arg_); -} - -ACE_INLINE void -ACE_Token_Reply::arg (ACE_UINT32 arg) -{ - this->transfer_.arg_ = htonl (arg); -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_TOKENS_LIBRARY */ diff --git a/externals/ace/Tokenizer_T.cpp b/externals/ace/Tokenizer_T.cpp deleted file mode 100644 index 00aa2abdc79..00000000000 --- a/externals/ace/Tokenizer_T.cpp +++ /dev/null @@ -1,242 +0,0 @@ -// $Id: Tokenizer_T.cpp 88793 2010-02-01 17:50:34Z cleeland $ - -#ifndef ACE_TOKENIZER_T_CPP -#define ACE_TOKENIZER_T_CPP - -#include "ace/ACE.h" -#include "ace/Malloc_Base.h" -#include "ace/String_Base.h" -#include "ace/Auto_Ptr.h" -#include "ace/OS_NS_string.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template -ACE_Tokenizer_T::ACE_Tokenizer_T (ACE_CHAR_T *buffer) - : buffer_ (buffer), - index_ (0), - preserves_index_ (0), - delimiter_index_ (0) -{ -} - -template -int -ACE_Tokenizer_T::delimiter (ACE_CHAR_T d) -{ - if (delimiter_index_ == MAX_DELIMITERS) - return -1; - - delimiters_[delimiter_index_].delimiter_ = d; - delimiters_[delimiter_index_].replace_ = 0; - ++delimiter_index_; - return 0; -} - -template -int -ACE_Tokenizer_T::delimiter_replace (ACE_CHAR_T d, - ACE_CHAR_T replacement) -{ - // Make it possible to replace delimiters on-the-fly, e.g., parse - // string until certain token count and then copy rest of the - // original string. - for (int i = 0; i < delimiter_index_; i++) - if (delimiters_[i].delimiter_ == d) - { - delimiters_[i].replacement_ = replacement; - delimiters_[i].replace_ = 1; - return 0; - } - - if (delimiter_index_ >= MAX_DELIMITERS) - return -1; - - delimiters_[delimiter_index_].delimiter_ = d; - delimiters_[delimiter_index_].replacement_ = replacement; - delimiters_[delimiter_index_].replace_ = 1; - ++delimiter_index_; - return 0; -} - -template -int -ACE_Tokenizer_T::preserve_designators (ACE_CHAR_T start, - ACE_CHAR_T stop, - int strip) -{ - if (preserves_index_ == MAX_PRESERVES) - return -1; - - preserves_[preserves_index_].start_ = start; - preserves_[preserves_index_].stop_ = stop; - preserves_[preserves_index_].strip_ = strip; - ++preserves_index_; - return 0; -} - -template -int -ACE_Tokenizer_T::is_delimiter (ACE_CHAR_T d, - int &replace, - ACE_CHAR_T &r) -{ - replace = 0; - - for (int x = 0; x < delimiter_index_; x++) - if (delimiters_[x].delimiter_ == d) - { - if (delimiters_[x].replace_) - { - r = delimiters_[x].replacement_; - replace = 1; - } - return 1; - } - - return 0; -} - -template -int -ACE_Tokenizer_T::is_preserve_designator (ACE_CHAR_T start, - ACE_CHAR_T &stop, - int &strip) -{ - for (int x = 0; x < preserves_index_; x++) - if (preserves_[x].start_ == start) - { - stop = preserves_[x].stop_; - strip = preserves_[x].strip_; - return 1; - } - - return 0; -} - -template -ACE_CHAR_T * -ACE_Tokenizer_T::next (void) -{ - // Check if the previous pass was the last one in the buffer. - if (index_ == -1) - { - index_ = 0; - return 0; - } - - // Check if a buffer has been passed - if (!buffer_) - { - return 0; - } - - ACE_CHAR_T replacement = 0; - int replace; - ACE_CHAR_T *next_token = 0; - - // Skip all leading delimiters. - for (;;) - { - // Check for end of string. - if (buffer_[index_] == '\0') - { - // If we hit EOS at the start, return 0. - index_ = 0; - return 0; - } - - if (this->is_delimiter (buffer_[index_], - replace, - replacement)) - ++index_; - else - break; - } - - // When we reach this point, buffer_[index_] is a non-delimiter and - // not EOS - the start of our next_token. - next_token = buffer_ + index_; - - // A preserved region is it's own token. - ACE_CHAR_T stop; - int strip; - if (this->is_preserve_designator (buffer_[index_], - stop, - strip)) - { - while (++index_) - { - if (buffer_[index_] == '\0') - { - index_ = -1; - goto EXIT_LABEL; - } - - if (buffer_[index_] == stop) - break; - } - - if (strip) - { - // Skip start preserve designator. - next_token += 1; - // Zap the stop preserve designator. - buffer_[index_] = '\0'; - // Increment to the next token. - ++index_; - } - - goto EXIT_LABEL; - } - - // Step through finding the next delimiter or EOS. - for (;;) - { - // Advance pointer. - ++index_; - - // Check for delimiter. - if (this->is_delimiter (buffer_[index_], - replace, - replacement)) - { - // Replace the delimiter. - if (replace != 0) - buffer_[index_] = replacement; - - // Move the pointer up and return. - ++index_; - goto EXIT_LABEL; - } - - // A preserve designator is NESTED inside this token - // We can't strip such preserve designators, just skip - // over them so that delimiters nested within arn't seen. - if (this->is_preserve_designator (buffer_[index_], - stop, - strip)) - { - ++index_; // Skip starting preserve_designator - while (('\0' != buffer_[index_]) && (stop != buffer_[index_])) - ++index_; // Skip enclosed character - } - - // Check for end of string. - if (buffer_[index_] == '\0') - { - index_ = -1; - goto EXIT_LABEL; - } - } - -EXIT_LABEL: - return next_token; -} - -// ************************************************************* - - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_TOKENIZER_T_CPP */ diff --git a/externals/ace/Tokenizer_T.h b/externals/ace/Tokenizer_T.h deleted file mode 100644 index b13f5bb5ab6..00000000000 --- a/externals/ace/Tokenizer_T.h +++ /dev/null @@ -1,241 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Tokenizer_T.h - * - * $Id: Tokenizer_T.h 88793 2010-02-01 17:50:34Z cleeland $ - * - * @author Douglas C. Schmidt (schmidt@cs.wustl.edu) - * @author Nanbor Wang - */ -//============================================================================= - -#ifndef ACE_TOKENIZER_T_H -#define ACE_TOKENIZER_T_H - -#include /**/ "ace/pre.h" - -#include "ace/Global_Macros.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Tokenizer_T - * - * @brief Tokenizer - * - * Tokenizes a buffer. Allows application to set delimiters and - * preserve designators. Does not allow special characters, yet - * (e.g., printf ("\"like a quoted string\"")). - */ -template -class ACE_Tokenizer_T -{ -public: - /** - * \a buffer will be parsed. Notice that ACE_Tokenizer_T will modify - * \a buffer if you use delimiter_replace or - * preserve_designators to do character substitution. - * @note You should NOT pass a constant string or string literal - * to this constructor, since ACE_Tokenizer_T will try to modify - * the string. - * \sa preserve_designators - * \sa preserve_designators - */ - ACE_Tokenizer_T (ACE_CHAR_T *buffer); - - /** - * \a d is a delimiter. - * \return Returns 0 on success, -1 if there is no memory left. - * - * Example: - * \verbatim - char buf[30]; - ACE_OS::strcpy(buf, "William/Joseph/Hagins"); - - ACE_Tokenizer_T tok (buf); - tok.delimiter ('/'); - for (char *p = tok.next (); p; p = tok.next ()) - cout << p << endl; - \endverbatim - * - * This will print out: - * \verbatim - William/Joseph/Hagins - Joseph/Hagins - Hagins \endverbatim - */ - int delimiter (ACE_CHAR_T d); - - /** - * \a d is a delimiter and, when found, will be replaced by - * \a replacement. - * \return 0 on success, -1 if there is no memory left. - * - * Example: - * \verbatim - char buf[30]; - ACE_OS::strcpy(buf, "William/Joseph/Hagins"); - - ACE_Tokenizer tok (buf); - tok.delimiter_replace ('/', 0); - for (char *p = tok.next (); p; p = tok.next ()) - cout << p << endl; - \endverbatim - * - * This will print out: - * \verbatim - William - Joseph - Hagins \endverbatim - */ - int delimiter_replace (ACE_CHAR_T d, ACE_CHAR_T replacement); - - /** - * Extract string between a pair of designator characters. - * For instance, quotes, or '(' and ')'. - * \a start specifies the begin designator. - * \a stop specifies the end designator. - * \a strip If \a strip == 1, then the preserve - * designators will be stripped from the tokens returned by next. - * \return 0 on success, -1 if there is no memory left. - * - * Example with strip = 0: - * \verbatim - char buf[30]; - ACE_OS::strcpy(buf, "William(Joseph)Hagins"); - - ACE_Tokenizer tok (buf); - tok.preserve_designators ('(', ')', 0); - for (char *p = tok.next (); p; p = tok.next ()) - cout << p << endl; - \endverbatim - * - * This will print out: - * \verbatim - William(Joseph)Hagins - (Joseph)Hagins - )Hagins \endverbatim - * - * Example with strip = 1: - * \verbatim - char buf[30]; - ACE_OS::strcpy(buf, "William(Joseph)Hagins"); - - ACE_Tokenizer tok (buf); - tok.preserve_designators ('(', ')', 1); - for (char *p = tok.next (); p; p = tok.next ()) - cout << p << endl; - \endverbatim - * - * This will print out: - * \verbatim - William - Joseph - Hagins \endverbatim - */ - int preserve_designators (ACE_CHAR_T start, ACE_CHAR_T stop, int strip=1); - - /// Returns the next token. - ACE_CHAR_T *next (void); - - enum { - MAX_DELIMITERS=16, - MAX_PRESERVES=16 - }; - -protected: - /// Returns 1 if @a d is a delimiter, 0 otherwise. If @a d should be - /// replaced with @a r, @a replace is set to 1, otherwise 0. - int is_delimiter (ACE_CHAR_T d, int &replace, ACE_CHAR_T &r); - - /** - * If @a start is a start preserve designator, returns 1 and sets - * @a stop to the stop designator. Returns 0 if @a start is not a - * preserve designator. - */ - int is_preserve_designator (ACE_CHAR_T start, ACE_CHAR_T &stop, int &strip); - - ACE_CHAR_T *buffer_; - int index_; - - /** - * @class Preserve_Entry - * - * @brief Preserve Entry - * - * Defines a set of characters that designate an area that - * should not be parsed, but should be treated as a complete - * token. For instance, in: (this is a preserve region), start - * would be a left paren -(- and stop would be a right paren - * -)-. The strip determines whether the designators should be - * removed from the token. - */ - class Preserve_Entry - { - public: - /** - * E.g., "(". - * E.g., ")". - * Whether the designators should be removed from the token. - */ - ACE_CHAR_T start_; - ACE_CHAR_T stop_; - int strip_; - }; - - /// The application can specify MAX_PRESERVES preserve designators. - Preserve_Entry preserves_[MAX_PRESERVES]; - - /// Pointer to the next free spot in preserves_. - int preserves_index_; - - /** - * @class Delimiter_Entry - * - * @brief Delimiter Entry - * - * Describes a delimiter for the tokenizer. - */ - class Delimiter_Entry - { - public: - /** - * Most commonly a space ' '. - * What occurrences of delimiter_ should be replaced with. - * Whether replacement_ should be used. This should be replaced - * with a technique that sets replacement_ = delimiter by - * default. I'll do that next iteration. - */ - ACE_CHAR_T delimiter_; - ACE_CHAR_T replacement_; - int replace_; - }; - - /// The tokenizer allows MAX_DELIMITERS number of delimiters. - Delimiter_Entry delimiters_[MAX_DELIMITERS]; - - /// Pointer to the next free space in delimiters_. - int delimiter_index_; -}; - -typedef ACE_Tokenizer_T ACE_Tokenizer; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Tokenizer_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Tokenizer_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" - -#endif /* ACE_TOKENIZER_T_H */ diff --git a/externals/ace/Trace.cpp b/externals/ace/Trace.cpp deleted file mode 100644 index 06269ccac1f..00000000000 --- a/externals/ace/Trace.cpp +++ /dev/null @@ -1,136 +0,0 @@ -// $Id: Trace.cpp 87823 2009-11-30 12:38:34Z johnnyw $ - -#include "ace/Trace.h" - -ACE_RCSID (ace, - Trace, - "$Id: Trace.cpp 87823 2009-11-30 12:38:34Z johnnyw $") - -// Turn off tracing for the duration of this file. -#if defined (ACE_NTRACE) -#undef ACE_NTRACE -#endif /* ACE_NTRACE */ -#define ACE_NTRACE 1 - -#include "ace/Log_Msg.h" -#include "ace/Object_Manager_Base.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// = Static initialization. - -// Keeps track of how far to indent per trace call. -int ACE_Trace::nesting_indent_ = ACE_Trace::DEFAULT_INDENT; - -// Is tracing enabled? -bool ACE_Trace::enable_tracing_ = ACE_Trace::DEFAULT_TRACING; - -ACE_ALLOC_HOOK_DEFINE(ACE_Trace) - -void -ACE_Trace::dump (void) const -{ -#if defined (ACE_HAS_DUMP) -#endif /* ACE_HAS_DUMP */ -} - -// Determine whether or not tracing is enabled - -bool -ACE_Trace::is_tracing (void) -{ - return ACE_Trace::enable_tracing_; -} - -// Enable the tracing facility. - -void -ACE_Trace::start_tracing (void) -{ - ACE_Trace::enable_tracing_ = true; -} - -// Disable the tracing facility. - -void -ACE_Trace::stop_tracing (void) -{ - ACE_Trace::enable_tracing_ = false; -} - -// Change the nesting indentation level. - -void -ACE_Trace::set_nesting_indent (int indent) -{ - ACE_Trace::nesting_indent_ = indent; -} - -// Get the nesting indentation level. - -int -ACE_Trace::get_nesting_indent (void) -{ - return ACE_Trace::nesting_indent_; -} - -// Perform the first part of the trace, which prints out the string N, -// the LINE, and the ACE_FILE as the function is entered. - -ACE_Trace::ACE_Trace (const ACE_TCHAR *n, - int line, - const ACE_TCHAR *file) -{ -#if defined (ACE_NLOGGING) - ACE_UNUSED_ARG (line); - ACE_UNUSED_ARG (file); -#endif /* ACE_NLOGGING */ - - this->name_ = n; - - // If ACE has not yet been initialized, don't try to trace... there's - // too much stuff not yet initialized. - if (ACE_Trace::enable_tracing_ && !ACE_OS_Object_Manager::starting_up ()) - { - ACE_Log_Msg *lm = ACE_LOG_MSG; - if (lm->tracing_enabled () - && lm->trace_active () == 0) - { - lm->trace_active (1); - ACE_DEBUG ((LM_TRACE, - ACE_TEXT ("%*s(%t) calling %s in file `%s' on line %d\n"), - ACE_Trace::nesting_indent_ * lm->inc (), - ACE_TEXT (""), - this->name_, - file, - line)); - lm->trace_active (0); - } - } -} - -// Perform the second part of the trace, which prints out the NAME as -// the function is exited. - -ACE_Trace::~ACE_Trace (void) -{ - // If ACE has not yet been initialized, don't try to trace... there's - // too much stuff not yet initialized. - if (ACE_Trace::enable_tracing_ && !ACE_OS_Object_Manager::starting_up ()) - { - ACE_Log_Msg *lm = ACE_LOG_MSG; - if (lm->tracing_enabled () - && lm->trace_active () == 0) - { - lm->trace_active (1); - ACE_DEBUG ((LM_TRACE, - ACE_TEXT ("%*s(%t) leaving %s\n"), - ACE_Trace::nesting_indent_ * lm->dec (), - ACE_TEXT (""), - this->name_)); - lm->trace_active (0); - } - } -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Trace.h b/externals/ace/Trace.h deleted file mode 100644 index 3fbc9ce0be5..00000000000 --- a/externals/ace/Trace.h +++ /dev/null @@ -1,96 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Trace.h - * - * $Id: Trace.h 87823 2009-11-30 12:38:34Z johnnyw $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_TRACE_H -#define ACE_TRACE_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Trace - * - * @brief A C++ trace facility that keeps track of which methods are - * entered and exited. - * - * This class uses C++ constructors and destructors to automate - * the ACE_Trace nesting. In addition, thread-specific storage - * is used to enable multiple threads to work correctly. - */ -class ACE_Export ACE_Trace -{ -public: - // = Initialization and termination methods. - - /// Perform the first part of the trace, which prints out the string - /// N, the LINE, and the ACE_FILE as the function is entered. - ACE_Trace (const ACE_TCHAR *n, - int line = 0, - const ACE_TCHAR *file = ACE_TEXT ("")); - - /// Perform the second part of the trace, which prints out the NAME - /// as the function is exited. - ~ACE_Trace (void); - - // = Control the tracing level. - /// Determine if tracing is enabled or not - static bool is_tracing(void); - - /// Enable the tracing facility. - static void start_tracing (void); - - /// Disable the tracing facility. - static void stop_tracing (void); - - /// Change the nesting indentation level. - static void set_nesting_indent (int indent); - - /// Get the nesting indentation level. - static int get_nesting_indent (void); - - /// Dump the state of an object. - void dump (void) const; - -private: - // Keeps track of how deeply the call stack is nested (this is - // maintained in thread-specific storage to ensure correctness in - // multiple threads of control. - - /// Name of the method we are in. - const ACE_TCHAR *name_; - - /// Keeps track of how far to indent per trace call. - static int nesting_indent_; - - /// Is tracing enabled? - static bool enable_tracing_; - - /// Default values. - enum - { - DEFAULT_INDENT = 3, - DEFAULT_TRACING = 1 - }; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" - -#endif /* ACE_TRACE_H */ diff --git a/externals/ace/Truncate.h b/externals/ace/Truncate.h deleted file mode 100644 index 223513a56d9..00000000000 --- a/externals/ace/Truncate.h +++ /dev/null @@ -1,517 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Truncate.h - * - * $Id: Truncate.h 83306 2008-10-17 12:19:53Z johnnyw $ - * - * @author Steve Huston - * @author Ossama Othman - * @author Russell Mora - */ -//============================================================================= - -#ifndef ACE_TRUNCATE_H -#define ACE_TRUNCATE_H - -#include /**/ "ace/pre.h" - -#include "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Global_Macros.h" -#include "ace/If_Then_Else.h" -#include "ace/Numeric_Limits.h" - -#if defined (ACE_LACKS_LONGLONG_T) -# include "ace/Basic_Types.h" -#endif /* ACE_LACKS_LONGLONG_T */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -namespace ACE_Utils -{ - template struct Sign_Check; - - // Specialize the unsigned signed cases. - template<> struct Sign_Check { ACE_STATIC_CONSTANT (bool, is_signed = 0); }; - template<> struct Sign_Check { ACE_STATIC_CONSTANT (bool, is_signed = 0); }; - template<> struct Sign_Check { ACE_STATIC_CONSTANT (bool, is_signed = 0); }; - template<> struct Sign_Check { ACE_STATIC_CONSTANT (bool, is_signed = 0); }; -#if !(defined(ACE_LACKS_LONGLONG_T) || defined(ACE_LACKS_UNSIGNEDLONGLONG_T)) -# ifdef __GNUC__ - // Silence g++ "-pedantic" warnings regarding use of "long long" - // type. - __extension__ -# endif /* __GNUC__ */ - template<> struct Sign_Check { ACE_STATIC_CONSTANT (bool, is_signed = 0); }; -#else - template<> struct Sign_Check { ACE_STATIC_CONSTANT (bool, is_signed = 0); }; -#endif /* !ACE_LACKS_LONGLONG_T */ - - // Specialize the signed cases. - template<> struct Sign_Check { ACE_STATIC_CONSTANT (bool, is_signed = 1); }; - template<> struct Sign_Check { ACE_STATIC_CONSTANT (bool, is_signed = 1); }; - template<> struct Sign_Check { ACE_STATIC_CONSTANT (bool, is_signed = 1); }; - template<> struct Sign_Check { ACE_STATIC_CONSTANT (bool, is_signed = 1); }; -#ifndef ACE_LACKS_LONGLONG_T -# ifdef __GNUC__ - // Silence g++ "-pedantic" warnings regarding use of "long long" - // type. - __extension__ -# endif /* __GNUC__ */ - template<> struct Sign_Check { ACE_STATIC_CONSTANT (bool, is_signed = 1); }; -#endif /* !ACE_LACKS_LONGLONG_T */ - - // ----------------------------------------------------- - - /** - * @struct To_Unsigned - * - * @brief Retrieve unsigned counterpart to given type or value. - * - * Retrieve unsigned counterpart to given type or value. - */ - template struct To_Unsigned; - - template<> - struct To_Unsigned - { - typedef unsigned char unsigned_type; - - unsigned_type operator() (unsigned_type x) { return x; } - }; - - template<> - struct To_Unsigned - { - typedef unsigned short unsigned_type; - - unsigned_type operator() (unsigned_type x) { return x; } - }; - - template<> - struct To_Unsigned - { - typedef unsigned int unsigned_type; - - unsigned_type operator() (unsigned_type x) { return x; } - }; - - template<> - struct To_Unsigned - { - typedef unsigned long unsigned_type; - - unsigned_type operator() (unsigned_type x) { return x; } - }; - -#if !(defined(ACE_LACKS_LONGLONG_T) || defined(ACE_LACKS_UNSIGNEDLONGLONG_T)) -# ifdef __GNUC__ - // Silence g++ "-pedantic" warnings regarding use of "long long" - // type. - __extension__ -# endif /* __GNUC__ */ - template<> - struct To_Unsigned - { - typedef unsigned long long unsigned_type; - - unsigned_type operator() (unsigned_type x) { return x; } - }; -#else - template<> - struct To_Unsigned - { - typedef ACE_U_LongLong unsigned_type; - - unsigned_type operator() (unsigned_type x) { return x; } - }; -#endif /* !ACE_LACKS_LONGLONG_T */ - - // ---------------- - - template<> - struct To_Unsigned - { - typedef signed char signed_type; - typedef unsigned char unsigned_type; - - unsigned_type operator() (signed_type x) - { - return static_cast (x); - } - }; - - template<> - struct To_Unsigned - { - typedef signed short signed_type; - typedef unsigned short unsigned_type; - - unsigned_type operator() (signed_type x) - { - return static_cast (x); - } - }; - - template<> - struct To_Unsigned - { - typedef signed int signed_type; - typedef unsigned int unsigned_type; - - unsigned_type operator() (signed_type x) - { - return static_cast (x); - } - }; - - template<> - struct To_Unsigned - { - typedef signed long signed_type; - typedef unsigned long unsigned_type; - - unsigned_type operator() (signed_type x) - { - return static_cast (x); - } - }; - -#if !(defined(ACE_LACKS_LONGLONG_T) || defined(ACE_LACKS_UNSIGNEDLONGLONG_T)) -# ifdef __GNUC__ - // Silence g++ "-pedantic" warnings regarding use of "long long" - // type. - __extension__ -# endif /* __GNUC__ */ - template<> - struct To_Unsigned - { - typedef signed long long signed_type; - typedef unsigned long long unsigned_type; - - unsigned_type operator() (signed_type x) - { - return static_cast (x); - } - }; -#endif /* !ACE_LACKS_LONGLONG_T */ - - // ----------------------------------------------------- - - /** - * @struct Safe_Comparator - * - * @brief Conservative comparison of types that may not be safely - * promoted and/or converted to each other. - * - * The comparison operations provided by this structure perform - * negative value checking when necessary to prevent wrap-around - * when explicitly casting to an unsigned type. - * - * @internal This structure is not meant for general use. - */ - template struct Safe_Comparator; - - // LEFT: signed, RIGHT: unsigned - template - struct Safe_Comparator - { - static bool greater_than (LEFT lhs, RIGHT rhs) - { - // Prevent wrap-around when casting to unsigned. - if (lhs < 0) - return false; // since rhs is always positive - else - { - // Implicit promotion of unsigned LEFT and RIGHT types here. - return To_Unsigned() (lhs) > rhs; - } - } - }; - - // LEFT: unsigned, RIGHT: signed - template - struct Safe_Comparator - { - static bool greater_than (LEFT lhs, RIGHT rhs) - { - // Prevent wrap-around when casting to unsigned. - if (rhs < 0) - return true; // since lhs is always positive - else - { - // Implicit promotion of unsigned LEFT and RIGHT types here. - return lhs > To_Unsigned() (rhs); - } - } - }; - - // LEFT: unsigned, RIGHT: unsigned - template - struct Safe_Comparator - { - static bool greater_than (LEFT lhs, RIGHT rhs) - { - // Implicit promotion of unsigned LEFT and RIGHT types here. - return lhs > rhs; - } - }; - - // LEFT: signed, RIGHT: signed - template - struct Safe_Comparator - { - static bool greater_than (LEFT lhs, RIGHT rhs) - { - // Implicit promotion of signed LEFT and RIGHT types here. - return lhs > rhs; - } - }; - - // ----------------------------------------------------- - - /** - * @struct Fast_Comparator - * - * @brief Quick comparison of types that can be safely promoted - * and/or converted to each other. - * - * The comparison operations provided by this structure perform no - * negative value checking, meaning it is not applicable to all - * types. Check the value of the @c USABLE enumerator to determine - * if it applies to the types in question. - * - * @internal This structure is not meant for general use. - */ - template - struct Fast_Comparator - { - ACE_STATIC_CONSTANT ( - bool, - USE_LEFT = ((sizeof (LEFT) > sizeof (RIGHT) - && (Sign_Check::is_signed == 1 - || Sign_Check::is_signed == 0)) - - // The following is basically the case where LEFT - // and RIGHT are the same integral type. - || (sizeof (LEFT) == sizeof (RIGHT) - // Can't portably do - // Sign_Check::is_signed == - // Sign_Check::is_signed, - // i.e. comparison of anonymous enumerations, - // without triggering a compiler diagnostic - // so expand the comparison. - && ((Sign_Check::is_signed == 1 - && Sign_Check::is_signed == 1) - || (Sign_Check::is_signed == 0 - && Sign_Check::is_signed == 0))))); - - ACE_STATIC_CONSTANT ( - bool, - USE_RIGHT = (sizeof (RIGHT) > sizeof (LEFT) - && (Sign_Check::is_signed == 1 - || Sign_Check::is_signed == 0))); - - ACE_STATIC_CONSTANT (bool, USABLE = (USE_LEFT || USE_RIGHT)); - - typedef typename ACE::If_Then_Else< - USE_LEFT, - LEFT, - typename ACE::If_Then_Else< - USE_RIGHT, - RIGHT, - void>::result_type>::result_type promote_type; - - static bool greater_than (LEFT lhs, RIGHT rhs) - { - // The explicit cast is assumed to change the type of rhs without - // changing its value. - return - (static_cast (lhs) > static_cast (rhs)); - } - - }; - - // ----------------------------------------------------- - - /** - * @struct Comparator - * - * @brief Structure that provides optimal comparison operation for - * given types. - * - * The comparison operations provided by this structure are chosen - * at compile time based on the signs and sizes of types being - * compared. - * @par - * Comparisons of values with the same sign or those with types that - * can be promoted safely are done quickly, without any range - * checking. - * @par - * Comparisons of values of different types that cannot be safely - * promoted incur an additional check for a negative value to allow - * the compiler to perform the appropriate implicit unsigned type - * promotion. - * - * @note In general, the operations found in this structure should - * not be used to work around compiler diagnostics regarding - * comparison of signed and unsigned types. Verify that your - * types are correct before relying on those operations. - * - * @internal This structure is not meant for general use. - */ - template - struct Comparator - { - typedef typename ACE::If_Then_Else< - Fast_Comparator::USABLE, - Fast_Comparator, - Safe_Comparator::is_signed, - Sign_Check::is_signed> >::result_type comp_type; - }; - - // ----------------------------------------------------- - - /** - * @struct Truncator - * - * @brief Truncate value of type @c FROM to value of type @c TO. - * - * Truncate a value of type @c FROM to value of type @c TO, if the - * value is larger than the maximum of value of type @c TO. - */ - template - struct Truncator - { - ACE_STATIC_CONSTANT ( - bool, - // max FROM always greater than max TO - MAX_FROM_GT_MAX_TO = (sizeof(FROM) > sizeof (TO) - || (sizeof(FROM) == sizeof (TO) - && Sign_Check::is_signed == 0))); - - typedef typename ACE::If_Then_Else< - MAX_FROM_GT_MAX_TO, - FROM, - TO>::result_type comp_to_type; - - // Take advantage of knowledge that we're casting a positive value - // to a type large enough to hold it so that we can bypass - // negative value checks at compile-time. Otherwise fallback on - // the safer comparison. - typedef typename ACE::If_Then_Else< - MAX_FROM_GT_MAX_TO, - Fast_Comparator, - typename Comparator::comp_type>::result_type comparator; - - /// Truncate a value of type @c FROM to value of type @c TO, if - /// the value is larger than the maximum of value of type @c TO. - TO operator() (FROM val) - { - return - (comparator::greater_than (val, ACE_Numeric_Limits::max ()) - ? ACE_Numeric_Limits::max () - : static_cast (val)); - } - - }; - - // Partial specialization for the case where the types are the same. - // No truncation is necessary. - template - struct Truncator - { - T operator() (T val) - { - return val; - } - }; - - -#if defined (ACE_LACKS_LONGLONG_T) || defined (ACE_LACKS_UNSIGNEDLONGLONG_T) - // Partial specialization for the case where we're casting from - // ACE_U_LongLong to a smaller integer. We assume that we're always - // truncating from ACE_U_LongLong to a smaller type. The partial - // specialization above handles the case where both the FROM and TO - // types are ACE_U_LongLong. - template - struct Truncator - { - TO operator() (ACE_U_LongLong const & val) - { - // If val less than or equal to ACE_Numeric_Limits::max(), - // val.lo() must be less than or equal to - // ACE_Numeric_Limits::max (), as well. - return - (val > ACE_Numeric_Limits::max () - ? ACE_Numeric_Limits::max () - : static_cast (val.lo ())); - } - }; -#endif /* ACE_LACKS_LONGLONG_T || ACE_LACKS_UNSIGNEDLONGLONG_T */ - - // ----------------------------------------------------- - /** - * @struct Noop_Truncator - * - * @brief No-op truncation. - * - * This structure/functor performs no truncation since it assumes - * that @c sizeof(FROM) @c < @c sizeof(TO), meaning that - * @c numeric_limits::max() @c < @c numeric_limits::max(). - */ - template - struct Noop_Truncator - { - TO operator() (FROM val) - { - return static_cast (val); - } - }; - // ----------------------------------------------------- - - /** - * @class truncate_cast - * - * @brief Helper function to truncate an integral value to the - * maximum value of the given type. - * - * Very useful since ACE methods return @c int very often and - * the value's source is often a different-size integral - * type, such as @c size_t. This function hides the - * truncation logic and resolves compiler diagnostics. - * - * @internal Internal use only. - */ - template - inline TO truncate_cast (FROM val) - { - // If the size of FROM is less than the size of TO, "val" will - // never be greater than the maximum "TO" value, so there is no - // need to attempt to truncate. - typedef typename ACE::If_Then_Else< - (sizeof (FROM) < sizeof (TO)), - Noop_Truncator, - Truncator >::result_type truncator; - - return truncator() (val); - } - -} // namespace ACE_Utils - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" - -#endif /* ACE_TRUNCATE_H*/ diff --git a/externals/ace/Typed_SV_Message.cpp b/externals/ace/Typed_SV_Message.cpp deleted file mode 100644 index 6be3d4c682a..00000000000 --- a/externals/ace/Typed_SV_Message.cpp +++ /dev/null @@ -1,30 +0,0 @@ -// $Id: Typed_SV_Message.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#ifndef ACE_TYPED_SV_MESSAGE_CPP -#define ACE_TYPED_SV_MESSAGE_CPP - -#include "ace/Typed_SV_Message.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (__ACE_INLINE__) -#include "ace/Typed_SV_Message.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Typed_SV_Message) - -template void -ACE_Typed_SV_Message::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Typed_SV_Message::dump"); -#endif /* ACE_HAS_DUMP */ -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_TYPED_SV_MESSAGE_CPP */ diff --git a/externals/ace/Typed_SV_Message.h b/externals/ace/Typed_SV_Message.h deleted file mode 100644 index b43258e01a3..00000000000 --- a/externals/ace/Typed_SV_Message.h +++ /dev/null @@ -1,107 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file Typed_SV_Message.h - * - * $Id: Typed_SV_Message.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Doug Schmidt - */ -//========================================================================== - - -#ifndef ACE_TYPED_SV_MESSAGE_H -#define ACE_TYPED_SV_MESSAGE_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Typed_SV_Message - * - * @brief Defines the header file for the C++ wrapper for System V - * message queues. - */ -template -class ACE_Typed_SV_Message -{ -public: - // = Initialization and termination methods. - ACE_Typed_SV_Message (long type = 0, - int length = sizeof (T), - int max_size = sizeof (T)); - ACE_Typed_SV_Message (const T &data, - long type = 0, - int length = sizeof (T), - int max_size = sizeof (T)); - ~ACE_Typed_SV_Message (void); - - /// Get the type of the message. - long type (void) const; - - /// Set the type of the message. - void type (long type); - - /// Get the length of the message. - int length (void) const; - - /// Set the length of the message. - void length (int l); - - /// Get the maximum size of the message. - int max_size (void) const; - - /// Set the maximum size of the message. - void max_size (int m); - - /// Get a pointer to the data in the message. - T &data (void); - - /// Set a pointer to the data in the message. - void data (const T &data); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - /// Type of message. - long type_; - - /// Length of this message. - int length_; - - /// Maximum length of any message. - int max_; - - /// Data stored in a message. - T data_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Typed_SV_Message.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Typed_SV_Message.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Typed_SV_Message.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" - -#endif /* ACE_TYPED_SV_MESSAGE_H */ diff --git a/externals/ace/Typed_SV_Message.inl b/externals/ace/Typed_SV_Message.inl deleted file mode 100644 index 6d8ea702321..00000000000 --- a/externals/ace/Typed_SV_Message.inl +++ /dev/null @@ -1,96 +0,0 @@ -// -*- C++ -*- -// -// $Id: Typed_SV_Message.inl 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/config-all.h" -#include "ace/Global_Macros.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template ACE_INLINE -ACE_Typed_SV_Message::ACE_Typed_SV_Message (long t, - int l, - int m) - : type_ (t) -{ - ACE_TRACE ("ACE_Typed_SV_Message::ACE_Typed_SV_Message"); - this->length (l); - this->max_size (m); -} - -template ACE_INLINE -ACE_Typed_SV_Message::ACE_Typed_SV_Message (const T &d, - long t, - int l, - int m) - : type_ (t), - data_ (d) -{ - ACE_TRACE ("ACE_Typed_SV_Message::ACE_Typed_SV_Message"); - this->length (l); - this->max_size (m); -} - -template ACE_INLINE -ACE_Typed_SV_Message::~ACE_Typed_SV_Message (void) -{ - ACE_TRACE ("ACE_Typed_SV_Message::~ACE_Typed_SV_Message"); -} - -template ACE_INLINE long -ACE_Typed_SV_Message::type (void) const -{ - ACE_TRACE ("ACE_Typed_SV_Message::type"); - return this->type_; -} - -template ACE_INLINE void -ACE_Typed_SV_Message::type (long t) -{ - ACE_TRACE ("ACE_Typed_SV_Message::type"); - this->type_ = t; -} - -template ACE_INLINE int -ACE_Typed_SV_Message::length (void) const -{ - ACE_TRACE ("ACE_Typed_SV_Message::length"); - return this->length_; -} - -template ACE_INLINE void -ACE_Typed_SV_Message::length (int len) -{ - ACE_TRACE ("ACE_Typed_SV_Message::length"); - this->length_ = len + (sizeof *this - (sizeof this->type_ + sizeof this->data_)); -} - -template ACE_INLINE int -ACE_Typed_SV_Message::max_size (void) const -{ - ACE_TRACE ("ACE_Typed_SV_Message::max_size"); - return this->max_; -} - -template ACE_INLINE void -ACE_Typed_SV_Message::max_size (int m) -{ - ACE_TRACE ("ACE_Typed_SV_Message::max_size"); - this->max_ = m + (sizeof *this - (sizeof this->type_ + sizeof this->data_)); -} - -template T & -ACE_Typed_SV_Message::data (void) -{ - ACE_TRACE ("ACE_Typed_SV_Message::data"); - return this->data_; -} - -template void -ACE_Typed_SV_Message::data (const T &d) -{ - ACE_TRACE ("ACE_Typed_SV_Message::data"); - this->data_ = d; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Typed_SV_Message_Queue.cpp b/externals/ace/Typed_SV_Message_Queue.cpp deleted file mode 100644 index 0adb589e62b..00000000000 --- a/externals/ace/Typed_SV_Message_Queue.cpp +++ /dev/null @@ -1,56 +0,0 @@ -// $Id: Typed_SV_Message_Queue.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#ifndef ACE_TYPED_SV_MESSAGE_QUEUE_CPP -#define ACE_TYPED_SV_MESSAGE_QUEUE_CPP - -#include "ace/Typed_SV_Message.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Typed_SV_Message_Queue.h" -#include "ace/Log_Msg.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Typed_SV_Message_Queue.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Typed_SV_Message_Queue) - -template void -ACE_Typed_SV_Message_Queue::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Typed_SV_Message_Queue::dump"); -#endif /* ACE_HAS_DUMP */ -} - -template -ACE_Typed_SV_Message_Queue::ACE_Typed_SV_Message_Queue (void) -{ - ACE_TRACE ("ACE_Typed_SV_Message_Queue::ACE_Typed_SV_Message_Queue"); -} - -template -ACE_Typed_SV_Message_Queue::ACE_Typed_SV_Message_Queue (key_t external_id, - int create, - int perms) -{ - ACE_TRACE ("ACE_Typed_SV_Message_Queue::ACE_Typed_SV_Message_Queue"); - if (this->open (external_id, create, perms) == -1) - ACE_ERROR ((LM_ERROR, - "ACE_Typed_SV_Message_Queue::ACE_Typed_SV_Message_Queue")); -} - -template -ACE_Typed_SV_Message_Queue::~ACE_Typed_SV_Message_Queue (void) -{ - ACE_TRACE ("ACE_Typed_SV_Message_Queue::~ACE_Typed_SV_Message_Queue"); -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_TYPED_SV_MESSAGE_QUEUE_CPP */ diff --git a/externals/ace/Typed_SV_Message_Queue.h b/externals/ace/Typed_SV_Message_Queue.h deleted file mode 100644 index 12c0e50921b..00000000000 --- a/externals/ace/Typed_SV_Message_Queue.h +++ /dev/null @@ -1,92 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Typed_SV_Message_Queue.h - * - * $Id: Typed_SV_Message_Queue.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_TYPED_MESSAGE_QUEUE_H -#define ACE_TYPED_MESSAGE_QUEUE_H -#include /**/ "ace/pre.h" - -#include "ace/SV_Message_Queue.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Typed_SV_Message.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Typed_SV_Message_Queue - * - * @brief Defines the header file for the C++ wrapper facade for typed message queues. - */ -template -class ACE_Typed_SV_Message_Queue -{ -public: - enum - { - ACE_CREATE = IPC_CREAT, - ACE_OPEN = 0, - ACE_NOWAIT = IPC_NOWAIT - }; - - // = Initialization and termination operations. - ACE_Typed_SV_Message_Queue (void); - ACE_Typed_SV_Message_Queue (key_t external_id, - int create = ACE_OPEN, - int perms = ACE_DEFAULT_FILE_PERMS); - int open (key_t external_id, - int create = ACE_OPEN, - int perms = ACE_DEFAULT_FILE_PERMS); - int close (void); - int remove (void); - ~ACE_Typed_SV_Message_Queue (void); - - /// Send method. - int send (const ACE_Typed_SV_Message &mb, int mflags = 0); - - /// Recv method. - int recv (ACE_Typed_SV_Message &mb, int mflags = 0); - - /// Return the id of the underlying ACE_SV_Message_Queue. - int get_id (void) const; - - /// Control the underlying message queue. - int control (int option, void *arg = 0); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - ACE_SV_Message_Queue message_queue_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Typed_SV_Message_Queue.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Typed_SV_Message_Queue.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Typed_SV_Message_Queue.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" -#endif /* ACE_TYPED_MESSAGE_QUEUE_H */ diff --git a/externals/ace/Typed_SV_Message_Queue.inl b/externals/ace/Typed_SV_Message_Queue.inl deleted file mode 100644 index 90539936e62..00000000000 --- a/externals/ace/Typed_SV_Message_Queue.inl +++ /dev/null @@ -1,80 +0,0 @@ -// -*- C++ -*- -// -// $Id: Typed_SV_Message_Queue.inl 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/SV_Message_Queue.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template ACE_INLINE int -ACE_Typed_SV_Message_Queue::open (key_t external_id, - int create, - int perms) -{ - ACE_TRACE ("ACE_Typed_SV_Message_Queue::open"); - return this->message_queue_.open (external_id, create, perms); -} - -// What does it mean to close a message queue?! - -template ACE_INLINE int -ACE_Typed_SV_Message_Queue::close (void) -{ - ACE_TRACE ("ACE_Typed_SV_Message_Queue::close"); - return 1; -} - -template ACE_INLINE int -ACE_Typed_SV_Message_Queue::recv (ACE_Typed_SV_Message &mb, - int mflags) -{ - ACE_TRACE ("ACE_Typed_SV_Message_Queue::recv"); - - int length = - this->message_queue_.recv (reinterpret_cast (mb), - mb.max_size (), - mb.type (), - mflags); - if (length != -1) - mb.length (length); - - return length; -} - -template ACE_INLINE int -ACE_Typed_SV_Message_Queue::send (const ACE_Typed_SV_Message &mb, - int mflags) -{ - ACE_TRACE ("ACE_Typed_SV_Message_Queue::send"); - return - this->message_queue_.send ( - reinterpret_cast ( - const_cast &> (mb)), - mb.length (), - mflags); -} - -template ACE_INLINE int -ACE_Typed_SV_Message_Queue::remove (void) -{ - ACE_TRACE ("ACE_Typed_SV_Message_Queue::remove"); - - return this->message_queue_.remove (); -} - -template ACE_INLINE int -ACE_Typed_SV_Message_Queue::control (int option, - void *arg) -{ - ACE_TRACE ("ACE_Typed_SV_Message_Queue::control"); - - return this->message_queue_.control (option, arg); -} - -template ACE_INLINE int -ACE_Typed_SV_Message_Queue::get_id (void) const -{ - return this->message_queue_.get_id (); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/UNIX_Addr.cpp b/externals/ace/UNIX_Addr.cpp deleted file mode 100644 index 013af8a33ec..00000000000 --- a/externals/ace/UNIX_Addr.cpp +++ /dev/null @@ -1,151 +0,0 @@ -// $Id: UNIX_Addr.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/UNIX_Addr.h" - -ACE_RCSID(ace, UNIX_Addr, "$Id: UNIX_Addr.cpp 80826 2008-03-04 14:51:23Z wotte $") - -#if !defined (ACE_LACKS_UNIX_DOMAIN_SOCKETS) - -#if !defined (__ACE_INLINE__) -#include "ace/UNIX_Addr.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_UNIX_Addr) - -// Set a pointer to the address. -void -ACE_UNIX_Addr::set_addr (void *addr, int len) -{ - ACE_TRACE ("ACE_UNIX_Addr::set_addr"); - - this->ACE_Addr::base_set (AF_UNIX, len); - ACE_OS::memcpy ((void *) &this->unix_addr_, - (void *) addr, - len); -} - -// Return a pointer to the underlying address. - -void * -ACE_UNIX_Addr::get_addr (void) const -{ - return (void *) &this->unix_addr_; -} - -// Transform the string into the current addressing format. - -int -ACE_UNIX_Addr::string_to_addr (const char addr[]) -{ - ACE_OS::strsncpy (this->unix_addr_.sun_path, addr, - sizeof this->unix_addr_.sun_path); - return 0; -} - -// Transform the current address into string format. - -int -ACE_UNIX_Addr::addr_to_string (ACE_TCHAR s[], size_t len) const -{ - ACE_OS::strsncpy (s, - ACE_TEXT_CHAR_TO_TCHAR (this->unix_addr_.sun_path), - len); - return 0; -} - -u_long -ACE_UNIX_Addr::hash (void) const -{ - return ACE::hash_pjw (this->unix_addr_.sun_path); -} - -void -ACE_UNIX_Addr::dump (void) const -{ -#if defined (ACE_HAS_DUMP) -#endif /* ACE_HAS_DUMP */ -} - -// Do nothing constructor. - -ACE_UNIX_Addr::ACE_UNIX_Addr (void) - : ACE_Addr (AF_UNIX, sizeof this->unix_addr_) -{ - (void) ACE_OS::memset ((void *) &this->unix_addr_, - 0, - sizeof this->unix_addr_); - - this->unix_addr_.sun_family = AF_UNIX; -} - -int -ACE_UNIX_Addr::set (const ACE_UNIX_Addr &sa) -{ - if (sa.get_type () == AF_ANY) - (void) ACE_OS::memset ((void *) &this->unix_addr_, - 0, - sizeof this->unix_addr_); - else - ACE_OS::strcpy (this->unix_addr_.sun_path, - sa.unix_addr_.sun_path); - - this->unix_addr_.sun_family = AF_UNIX; - this->base_set (sa.get_type (), sa.get_size ()); - - return 0; -} - -// Copy constructor. - -ACE_UNIX_Addr::ACE_UNIX_Addr (const ACE_UNIX_Addr &sa) - : ACE_Addr (AF_UNIX, sa.get_size ()) -{ - this->set (sa); -} - -int -ACE_UNIX_Addr::set (const sockaddr_un *un, int len) -{ - (void) ACE_OS::memset ((void *) &this->unix_addr_, 0, - sizeof this->unix_addr_); - this->unix_addr_.sun_family = AF_UNIX; - ACE_OS::strcpy (this->unix_addr_.sun_path, un->sun_path); - this->base_set (AF_UNIX, len); - return 0; -} - -ACE_UNIX_Addr::ACE_UNIX_Addr (const sockaddr_un *un, int len) -{ - this->set (un, len); -} - -int -ACE_UNIX_Addr::set (const char rendezvous_point[]) -{ - (void) ACE_OS::memset ((void *) &this->unix_addr_, - 0, - sizeof this->unix_addr_); - this->unix_addr_.sun_family = AF_UNIX; - (void) ACE_OS::strsncpy (this->unix_addr_.sun_path, - rendezvous_point, - sizeof this->unix_addr_.sun_path); - - this->ACE_Addr::base_set (AF_UNIX, - sizeof this->unix_addr_ - - sizeof (this->unix_addr_.sun_path) + - ACE_OS::strlen (this->unix_addr_.sun_path)); - return 0; -} - -// Create a ACE_Addr from a UNIX pathname. - -ACE_UNIX_Addr::ACE_UNIX_Addr (const char rendezvous_point[]) -{ - this->set (rendezvous_point); -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_LACKS_UNIX_DOMAIN_SOCKETS */ diff --git a/externals/ace/UNIX_Addr.h b/externals/ace/UNIX_Addr.h deleted file mode 100644 index 887529fe152..00000000000 --- a/externals/ace/UNIX_Addr.h +++ /dev/null @@ -1,117 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file UNIX_Addr.h - * - * $Id: UNIX_Addr.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Doug Schmidt - */ -//============================================================================= - - -#ifndef ACE_UNIX_ADDR_H -#define ACE_UNIX_ADDR_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_UNIX_DOMAIN_SOCKETS) - -#include "ace/Addr.h" -#include "ace/Log_Msg.h" -#include "ace/ACE.h" -#include "ace/os_include/sys/os_un.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_UNIX_Addr - * - * @brief Defines the ``UNIX domain address family'' address format. - */ -class ACE_Export ACE_UNIX_Addr : public ACE_Addr -{ -public: - // = Initialization methods. - /// Default constructor. - ACE_UNIX_Addr (void); - - /// Copy constructor. - ACE_UNIX_Addr (const ACE_UNIX_Addr &sa); - - /// Creates an ACE_UNIX_Addr from a string. - ACE_UNIX_Addr (const char rendezvous_point[]); - - /// Creates an ACE_INET_Addr from a sockaddr_un structure. - ACE_UNIX_Addr (const sockaddr_un *, int len); - - /// Creates an ACE_UNIX_Addr from another ACE_UNIX_Addr. - int set (const ACE_UNIX_Addr &sa); - - /// Creates an ACE_UNIX_Addr from a string. - int set (const char rendezvous_point[]); - - /// Creates an ACE_UNIX_Addr from a sockaddr_un structure. - int set (const sockaddr_un *, int len); - - /// Return a pointer to the underlying network address. - virtual void *get_addr (void) const; - - /// Set a pointer to the underlying network address. - virtual void set_addr (void *addr, int len); - - /// Transform the current address into string format. - virtual int addr_to_string (ACE_TCHAR addr[], size_t) const; - - /// Transform the string into the current addressing format. - virtual int string_to_addr (const char addr[]); - -#if defined (ACE_HAS_WCHAR) - /// Creates an ACE_UNIX_Addr from a string. - ACE_UNIX_Addr (const wchar_t rendezvous_point[]); - - /// Creates an ACE_UNIX_Addr from a string. - int set (const wchar_t rendezvous_point[]); -#endif /* ACE_HAS_WCHAR */ - - /// Compare two addresses for equality. - bool operator == (const ACE_UNIX_Addr &SAP) const; - - /// Compare two addresses for inequality. - bool operator != (const ACE_UNIX_Addr &SAP) const; - - /// Return the path name of the underlying rendezvous point. - const char *get_path_name (void) const; - - /// Computes and returns hash value. - virtual u_long hash (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - /// Underlying socket address. - sockaddr_un unix_addr_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/UNIX_Addr.inl" -#endif /* __ACE_INLINE__ */ - -#endif /* ACE_LACKS_UNIX_DOMAIN_SOCKETS */ - -#include /**/ "ace/post.h" - -#endif /* ACE_UNIX_ADDR_H */ diff --git a/externals/ace/UNIX_Addr.inl b/externals/ace/UNIX_Addr.inl deleted file mode 100644 index 5e801b56fea..00000000000 --- a/externals/ace/UNIX_Addr.inl +++ /dev/null @@ -1,57 +0,0 @@ -// -*- C++ -*- -// -// $Id: UNIX_Addr.inl 80826 2008-03-04 14:51:23Z wotte $ - - -#include "ace/OS_NS_string.h" - - -#if !defined (ACE_LACKS_UNIX_DOMAIN_SOCKETS) - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -#if defined (ACE_HAS_WCHAR) -/// Creates an ACE_UNIX_Addr from a string. -ACE_INLINE -ACE_UNIX_Addr::ACE_UNIX_Addr (const wchar_t rendezvous_point[]) -{ - this->set (ACE_Wide_To_Ascii (rendezvous_point).char_rep ()); -} - -/// Creates an ACE_UNIX_Addr from a string. -ACE_INLINE int -ACE_UNIX_Addr::set (const wchar_t rendezvous_point[]) -{ - return this->set (ACE_Wide_To_Ascii (rendezvous_point).char_rep ()); -} -#endif /* ACE_HAS_WCHAR */ - -// Compare two addresses for equality. - -ACE_INLINE bool -ACE_UNIX_Addr::operator == (const ACE_UNIX_Addr &sap) const -{ - return ACE_OS::strncmp (this->unix_addr_.sun_path, - sap.unix_addr_.sun_path, - sizeof this->unix_addr_.sun_path) == 0; -} - -// Compare two addresses for inequality. - -ACE_INLINE bool -ACE_UNIX_Addr::operator != (const ACE_UNIX_Addr &sap) const -{ - return !((*this) == sap); // This is lazy, of course... ;-) -} - -// Return the path name used for the rendezvous point. - -ACE_INLINE const char * -ACE_UNIX_Addr::get_path_name (void) const -{ - return this->unix_addr_.sun_path; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_LACKS_UNIX_DOMAIN_SOCKETS */ diff --git a/externals/ace/UPIPE_Acceptor.cpp b/externals/ace/UPIPE_Acceptor.cpp deleted file mode 100644 index c2c10155c35..00000000000 --- a/externals/ace/UPIPE_Acceptor.cpp +++ /dev/null @@ -1,129 +0,0 @@ -// $Id: UPIPE_Acceptor.cpp 82723 2008-09-16 09:35:44Z johnnyw $ - -#include "ace/UPIPE_Acceptor.h" - -ACE_RCSID(ace, UPIPE_Acceptor, "$Id: UPIPE_Acceptor.cpp 82723 2008-09-16 09:35:44Z johnnyw $") - -#if defined (ACE_HAS_THREADS) - -#include "ace/OS_NS_unistd.h" - -#if !defined (__ACE_INLINE__) -#include "ace/UPIPE_Acceptor.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_UPIPE_Acceptor) - -void -ACE_UPIPE_Acceptor::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_UPIPE_Acceptor::dump"); -#endif /* ACE_HAS_DUMP */ -} - -/* Do nothing routine for constructor. */ - -ACE_UPIPE_Acceptor::ACE_UPIPE_Acceptor (void) - : mb_ (sizeof (ACE_UPIPE_Stream *)) -{ - ACE_TRACE ("ACE_UPIPE_Acceptor::ACE_UPIPE_Acceptor"); -} - -ACE_UPIPE_Acceptor::~ACE_UPIPE_Acceptor (void) -{ - ACE_TRACE ("ACE_UPIPE_Acceptor::~ACE_UPIPE_Acceptor"); -} - -// General purpose routine for performing server ACE_UPIPE. - -int -ACE_UPIPE_Acceptor::open (const ACE_UPIPE_Addr &local_addr, - int reuse_addr) -{ - ACE_TRACE ("ACE_UPIPE_Acceptor::open"); - return this->ACE_SPIPE_Acceptor::open (local_addr, reuse_addr); -} - -int -ACE_UPIPE_Acceptor::close (void) -{ - ACE_TRACE ("ACE_UPIPE_Acceptor::close"); - return this->ACE_SPIPE_Acceptor::close (); -} - -// General purpose routine for accepting new connections. - -ACE_UPIPE_Acceptor::ACE_UPIPE_Acceptor (const ACE_UPIPE_Addr &local_addr, - int reuse_addr) - : mb_ (sizeof (ACE_UPIPE_Stream *)) -{ - ACE_TRACE ("ACE_UPIPE_Acceptor::ACE_UPIPE_Acceptor"); - - if (this->open (local_addr, reuse_addr) == -1) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_UPIPE_Acceptor"))); -} - -int -ACE_UPIPE_Acceptor::accept (ACE_UPIPE_Stream &new_stream, - ACE_UPIPE_Addr *remote_addr, - ACE_Time_Value *timeout, - bool restart, - bool reset_new_handle) -{ - ACE_TRACE ("ACE_UPIPE_Acceptor::accept"); - ACE_UNUSED_ARG (reset_new_handle); - - ACE_SPIPE_Stream new_io; - - if (this->ACE_SPIPE_Acceptor::accept (new_io, remote_addr, - timeout, restart) == -1) - return -1; - else - { - ACE_UPIPE_Stream *remote_stream = 0; - - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, new_stream.lock_, -1)); - - new_stream.set_handle (new_io.get_handle ()); - new_stream.reference_count_++; - - // Transfer address ownership. - new_io.get_local_addr (new_stream.local_addr_); - new_io.get_remote_addr (new_stream.remote_addr_); - - // Now that we got the handle, we'll read the address of the - // connector-side ACE_UPIPE_Stream out of the pipe and link that - // ACE_UPIPE_Stream to our ACE_UPIPE_Stream. - - if (ACE_OS::read (new_stream.get_handle (), - (char *) &remote_stream, - sizeof remote_stream) == -1) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("ACE_UPIPE_Acceptor: %p\n"), - ACE_TEXT ("read stream address failed"))); - else if (new_stream.stream_.link (remote_stream->stream_) == -1) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("ACE_UPIPE_Acceptor: %p\n"), - ACE_TEXT ("link streams failed"))); - // Send a message over the new streampipe to confirm acceptance. - else if (new_stream.send (&mb_, 0) == -1) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("ACE_UPIPE_Acceptor: %p\n"), - ACE_TEXT ("linked stream.put failed"))); - - // Close down the new_stream at this point in order to conserve - // handles. Note that we don't need the SPIPE connection - // anymore since we're now linked via the . - new_stream.ACE_SPIPE::close (); - return 0; - } -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_THREADS */ diff --git a/externals/ace/UPIPE_Acceptor.h b/externals/ace/UPIPE_Acceptor.h deleted file mode 100644 index e4925a045a2..00000000000 --- a/externals/ace/UPIPE_Acceptor.h +++ /dev/null @@ -1,99 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file UPIPE_Acceptor.h - * - * $Id: UPIPE_Acceptor.h 82723 2008-09-16 09:35:44Z johnnyw $ - * - * @author Gerhard Lenzer - * @author Douglas C. Schmidt - */ -//============================================================================= - - -#ifndef ACE_UPIPE_ACCEPTOR_H -#define ACE_UPIPE_ACCEPTOR_H -#include /**/ "ace/pre.h" - -#include "ace/UPIPE_Stream.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_THREADS) - -#include "ace/SPIPE_Acceptor.h" -#include "ace/Thread_Manager.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_UPIPE_Acceptor - * - * @brief Defines the format and interface for the listener side of the - * ACE_UPIPE_Stream. - */ -class ACE_Export ACE_UPIPE_Acceptor : public ACE_SPIPE_Acceptor -{ -public: - // = Initialization and termination. - /// Default constructor. - ACE_UPIPE_Acceptor (void); - - /// Initialize passive endpoint. - ACE_UPIPE_Acceptor (const ACE_UPIPE_Addr &local_sap, - int reuse_addr = 0); - - /// Initialize passive endpoint. - int open (const ACE_UPIPE_Addr &local_sap, - int reuse_addr = 0); - - /// Close down and release resources. - ~ACE_UPIPE_Acceptor (void); - - /// Close down and release resources. - int close (void); - - /// Close down and release resources and remove the underlying SPIPE - /// rendezvous point. - int remove (void); - - // = Passive connection acceptance method. - /** - * Accept a new data transfer connection. A @a timeout of 0 means - * block forever, a @a timeout of {0, 0} means poll. @a restart == 1 - * means "restart if interrupted." - */ - int accept (ACE_UPIPE_Stream &server_stream, - ACE_UPIPE_Addr *remote_addr = 0, - ACE_Time_Value *timeout = 0, - bool restart = true, - bool reset_new_handle = false); - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - /// Manage threads. - ACE_Thread_Manager tm; - - /// To confirm connection establishment. - ACE_Message_Block mb_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/UPIPE_Acceptor.inl" -#endif /* __ACE_INLINE__ */ - -#endif /* ACE_HAS_THREADS */ - -#include /**/ "ace/post.h" - -#endif /* ACE_UPIPE_ACCEPTOR_H */ diff --git a/externals/ace/UPIPE_Acceptor.inl b/externals/ace/UPIPE_Acceptor.inl deleted file mode 100644 index 9432ad7bb88..00000000000 --- a/externals/ace/UPIPE_Acceptor.inl +++ /dev/null @@ -1,14 +0,0 @@ -// -*- C++ -*- -// -// $Id: UPIPE_Acceptor.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE int -ACE_UPIPE_Acceptor::remove (void) -{ - ACE_TRACE ("ACE_UPIPE_Acceptor::remove"); - return this->ACE_SPIPE_Acceptor::remove (); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/UPIPE_Addr.h b/externals/ace/UPIPE_Addr.h deleted file mode 100644 index aaf33b683fa..00000000000 --- a/externals/ace/UPIPE_Addr.h +++ /dev/null @@ -1,33 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file UPIPE_Addr.h - * - * $Id: UPIPE_Addr.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Doug Schmidt - */ -//============================================================================= - - -#ifndef ACE_UPIPE_ADDR_H -#define ACE_UPIPE_ADDR_H - -#include /**/ "ace/pre.h" - -#include "ace/SPIPE_Addr.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -typedef ACE_SPIPE_Addr ACE_UPIPE_Addr; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#include /**/ "ace/post.h" - -#endif /* ACE_UPIPE_ADDR_H */ diff --git a/externals/ace/UPIPE_Connector.cpp b/externals/ace/UPIPE_Connector.cpp deleted file mode 100644 index 9b9bfcd3878..00000000000 --- a/externals/ace/UPIPE_Connector.cpp +++ /dev/null @@ -1,101 +0,0 @@ -// $Id: UPIPE_Connector.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/UPIPE_Connector.h" - -ACE_RCSID(ace, UPIPE_Connector, "$Id: UPIPE_Connector.cpp 80826 2008-03-04 14:51:23Z wotte $") - -#if defined (ACE_HAS_THREADS) - -#include "ace/Handle_Ops.h" -#include "ace/OS_NS_unistd.h" -#include "ace/OS_NS_stropts.h" - -#if !defined (__ACE_INLINE__) -#include "ace/UPIPE_Connector.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_UPIPE_Connector) - -void -ACE_UPIPE_Connector::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_UPIPE_Connector::dump"); -#endif /* ACE_HAS_DUMP */ -} - -ACE_UPIPE_Connector::ACE_UPIPE_Connector (void) -{ - ACE_TRACE ("ACE_UPIPE_Connector::ACE_UPIPE_Connector"); -} - -int -ACE_UPIPE_Connector::connect (ACE_UPIPE_Stream &new_stream, - const ACE_UPIPE_Addr &addr, - ACE_Time_Value *timeout, - const ACE_Addr & /* local_sap */, - int /* reuse_addr */, - int flags, - int perms) -{ - ACE_TRACE ("ACE_UPIPE_Connector::connect"); - ACE_ASSERT (new_stream.get_handle () == ACE_INVALID_HANDLE); - - ACE_HANDLE handle = ACE::handle_timed_open (timeout, - addr.get_path_name (), - flags, perms); - - if (handle == ACE_INVALID_HANDLE) - return -1; -#if !defined (ACE_WIN32) - else if (ACE_OS::isastream (handle) != 1) - return -1; -#endif - else // We're connected! - { - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, new_stream.lock_, -1)); - - ACE_UPIPE_Stream *ustream = &new_stream; - - new_stream.set_handle (handle); - new_stream.remote_addr_ = addr; // class copy. - new_stream.reference_count_++; - - // Now send the address of our ACE_UPIPE_Stream over this pipe - // to our corresponding ACE_UPIPE_Acceptor, so he may link the - // two streams. - ssize_t result = ACE_OS::write (handle, - (const char *) &ustream, - sizeof ustream); - if (result == -1) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("ACE_UPIPE_Connector %p\n"), - ACE_TEXT ("write to pipe failed"))); - - // Wait for confirmation of stream linking. - ACE_Message_Block *mb_p = 0; - - // Our part is done, wait for server to confirm connection. - result = new_stream.recv (mb_p, 0); - - // Do *not* coalesce the following two checks for result == -1. - // They perform different checks and cannot be merged. - if (result == -1) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("ACE_UPIPE_Connector %p\n"), - ACE_TEXT ("no confirmation from server"))); - else - // Close down the new_stream at this point in order to - // conserve handles. Note that we don't need the SPIPE - // connection anymore since we're linked via the Message_Queue - // now. - new_stream.ACE_SPIPE::close (); - return static_cast (result); - } -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_THREADS */ diff --git a/externals/ace/UPIPE_Connector.h b/externals/ace/UPIPE_Connector.h deleted file mode 100644 index b2ad1787aaf..00000000000 --- a/externals/ace/UPIPE_Connector.h +++ /dev/null @@ -1,115 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file UPIPE_Connector.h - * - * $Id: UPIPE_Connector.h 82723 2008-09-16 09:35:44Z johnnyw $ - * - * @author Gerhard Lenzer and Douglas C. Schmidt - */ -//============================================================================= - - -#ifndef ACE_UPIPE_CONNECTOR_H -#define ACE_UPIPE_CONNECTOR_H -#include /**/ "ace/pre.h" - -#include "ace/UPIPE_Stream.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_THREADS) - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_UPIPE_Connector - * - * @brief Defines an active connection factory for the - * ACE_UPIPE_STREAM wrappers. - */ -class ACE_Export ACE_UPIPE_Connector -{ -public: - // = Initialization methods. - /// Default constructor. - ACE_UPIPE_Connector (void); - - /** - * Actively connect and produce a @a new_stream if things go well. - * The @a addr is the address that we are trying to connect - * with. The @a timeout is the amount of time to wait to connect. - * If it's 0 then we block indefinitely. If *timeout == {0, 0} then - * the connection is done using non-blocking mode. In this case, if - * the connection can't be made immediately the value of -1 is - * returned with @c errno == EWOULDBLOCK. If *timeout > {0, 0} then - * this is the maximum amount of time to wait before timing out. If the - * time expires before the connection is made @c errno == ETIME. The - * @a local_sap is the value of local address to bind to. If it's - * the default value of ACE_Addr::sap_any then the user is letting - * the OS do the binding. If @a reuse_addr == 1 then the - * @a local_addr is reused, even if it hasn't been cleanedup yet. - * The @a flags and @a perms arguments are passed down to the open() - * method. - */ - ACE_UPIPE_Connector (ACE_UPIPE_Stream &new_stream, - const ACE_UPIPE_Addr &addr, - ACE_Time_Value *timeout = 0, - const ACE_Addr &local_sap = ACE_Addr::sap_any, - int reuse_addr = 0, - int flags = O_RDWR, - int perms = 0); - - /** - * Actively connect and produce a @a new_stream if things go well. - * The @a addr is the address that we are trying to connect - * with. The @a timeout is the amount of time to wait to connect. - * If it's 0 then we block indefinitely. If *timeout == {0, 0} then - * the connection is done using non-blocking mode. In this case, if - * the connection can't be made immediately the value of -1 is - * returned with @c errno == EWOULDBLOCK. If *timeout > {0, 0} then - * this is the maximum amount of time to wait before timing out. If the - * time expires before the connection is made @c errno == ETIME. The - * @a local_sap is the value of local address to bind to. If it's - * the default value of ACE_Addr::sap_any then the user is letting - * the OS do the binding. If @a reuse_addr == 1 then the - * @a local_addr is reused, even if it hasn't been cleanedup yet. - * The @a flags and @a perms arguments are passed down to the open() - * method. - */ - int connect (ACE_UPIPE_Stream &new_stream, - const ACE_UPIPE_Addr &addr, - ACE_Time_Value *timeout = 0, - const ACE_Addr &local_sap = ACE_Addr::sap_any, - int reuse_addr = 0, - int flags = O_RDWR, - int perms = 0); - - /// Resets any event associations on this handle - bool reset_new_handle (ACE_HANDLE handle); - - // = Meta-type info - typedef ACE_UPIPE_Addr PEER_ADDR; - typedef ACE_UPIPE_Stream PEER_STREAM; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/UPIPE_Connector.inl" -#endif /* __ACE_INLINE__ */ - -#endif /* ACE_HAS_THREADS */ - -#include /**/ "ace/post.h" - -#endif /* ACE_UPIPE_CONNECTOR_H */ diff --git a/externals/ace/UPIPE_Connector.inl b/externals/ace/UPIPE_Connector.inl deleted file mode 100644 index 07b7502cce0..00000000000 --- a/externals/ace/UPIPE_Connector.inl +++ /dev/null @@ -1,34 +0,0 @@ -// -*- C++ -*- -// -// $Id: UPIPE_Connector.inl 82723 2008-09-16 09:35:44Z johnnyw $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Creates a Local ACE_UPIPE. -ACE_INLINE -ACE_UPIPE_Connector::ACE_UPIPE_Connector (ACE_UPIPE_Stream &new_stream, - const ACE_UPIPE_Addr &addr, - ACE_Time_Value *timeout, - const ACE_Addr &local_sap, - int reuse_addr, - int flags, - int perms) -{ - ACE_TRACE ("ACE_UPIPE_Connector::ACE_UPIPE_Connector"); - if (this->connect (new_stream, addr, timeout, local_sap, - reuse_addr, flags, perms) == -1 - && timeout != 0 && !(errno == EWOULDBLOCK || errno == ETIME)) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("address %s, %p\n"), - addr.get_path_name (), - ACE_TEXT ("ACE_UPIPE_Connector"))); -} - -ACE_INLINE bool -ACE_UPIPE_Connector::reset_new_handle (ACE_HANDLE /* handle */) -{ - // Nothing to do here since the handle is not a socket - return false; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/UPIPE_Stream.cpp b/externals/ace/UPIPE_Stream.cpp deleted file mode 100644 index d07722a482e..00000000000 --- a/externals/ace/UPIPE_Stream.cpp +++ /dev/null @@ -1,234 +0,0 @@ -// $Id: UPIPE_Stream.cpp 82559 2008-08-07 20:23:07Z parsons $ - -#include "ace/UPIPE_Stream.h" - -ACE_RCSID(ace, UPIPE_Stream, "$Id: UPIPE_Stream.cpp 82559 2008-08-07 20:23:07Z parsons $") - -#if defined (ACE_HAS_THREADS) - -#include "ace/OS_NS_string.h" - -#if !defined (__ACE_INLINE__) -#include "ace/UPIPE_Stream.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_UPIPE_Stream) - -ACE_UPIPE_Stream::ACE_UPIPE_Stream (void) - : mb_last_ (0), - reference_count_ (0) -{ - ACE_TRACE ("ACE_UPIPE_Stream::ACE_UPIPE_STREAM"); -} - -ACE_UPIPE_Stream::~ACE_UPIPE_Stream (void) -{ - if (this->mb_last_ != 0) - { - this->mb_last_->release (); - this->mb_last_ = 0; - } -} - -int -ACE_UPIPE_Stream::control (int cmd, - void * val) const -{ - ACE_TRACE ("ACE_UPIPE_Stream::control"); - - return ((ACE_UPIPE_Stream *) this)->stream_.control - ((ACE_IO_Cntl_Msg::ACE_IO_Cntl_Cmds) cmd, val); -} - -void -ACE_UPIPE_Stream::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_UPIPE_Stream::dump"); -#endif /* ACE_HAS_DUMP */ -} - -int -ACE_UPIPE_Stream::close (void) -{ - ACE_TRACE ("ACE_UPIPE_Stream::close"); - ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, -1)); - - this->reference_count_--; - - if (this->reference_count_ == 0) - { - // Since the UPIPE should have been closed earlier we won't bother - // checking to see if closing it now fails. - - if (this->ACE_SPIPE::get_handle () != ACE_INVALID_HANDLE) - this->ACE_SPIPE::close (); - - // Close down the ACE_stream. - return this->stream_.close (); - } - return 0; -} - -int -ACE_UPIPE_Stream::get_remote_addr (ACE_UPIPE_Addr &remote_sap) const -{ - ACE_TRACE ("ACE_UPIPE_Stream::get_remote_addr"); - remote_sap = this->remote_addr_; - return 0; -} - -int -ACE_UPIPE_Stream::send (ACE_Message_Block *mb_p, - ACE_Time_Value *timeout) -{ - ACE_TRACE ("ACE_UPIPE_Stream::send_msg"); - return this->stream_.put (mb_p, timeout) == -1 ? -1 : 0; -} - -int ACE_UPIPE_Stream::recv (ACE_Message_Block *& mb_p, - ACE_Time_Value *timeout) -{ - return this->stream_.get (mb_p, timeout) == -1 ? -1 : 0; -} - -// Send a buffer. - -ssize_t -ACE_UPIPE_Stream::send (const char *buffer, - size_t n, - ACE_Time_Value *timeout) -{ - ACE_TRACE ("ACE_UPIPE_Stream::send"); - - ACE_Message_Block *mb_p; - ACE_NEW_RETURN (mb_p, - ACE_Message_Block (n), - -1); - mb_p->copy (buffer, n); - return - this->stream_.put (mb_p, timeout) == -1 - ? -1 - : static_cast (n); -} - -// Receive a buffer. - -ssize_t -ACE_UPIPE_Stream::recv (char *buffer, - size_t n, - ACE_Time_Value *timeout) -{ - ACE_TRACE ("ACE_UPIPE_Stream::recv"); - // Index in buffer. - size_t bytes_read = 0; - - while (bytes_read < n) - if (this->mb_last_ != 0) - { - // We have remaining data in our last read Message_Buffer. - size_t this_len = this->mb_last_->length (); - if (this_len < n) - { - // The remaining data is not enough. - - ACE_OS::memcpy ((void *) &buffer[bytes_read], - this->mb_last_->rd_ptr (), - this_len); - bytes_read += this_len; - this->mb_last_ = this->mb_last_->release (); // mb_last_ now 0 - return static_cast (bytes_read); - } - else - { - // The remaining data is at least enough. If there's - // more, we'll get it the next time through. - ACE_OS::memcpy (&buffer[bytes_read], - this->mb_last_->rd_ptr (), - n); - bytes_read += n; - - // Advance rd_ptr. - this->mb_last_->rd_ptr (n); - - if (this->mb_last_->length () == 0) - // Now the Message_Buffer is empty. - this->mb_last_ = this->mb_last_->release (); - } - } - else - { - // We have to get a new Message_Buffer from our stream. - int result = this->stream_.get (this->mb_last_, timeout); - - if (result == -1) - { - if (errno == EWOULDBLOCK && bytes_read > 0) - // Return the number of bytes read before we timed out. - return static_cast (bytes_read); - else - return -1; - } - } - - return static_cast (bytes_read); -} - -ssize_t -ACE_UPIPE_Stream::send_n (const char *buf, - size_t n, - ACE_Time_Value *timeout) -{ - ACE_TRACE ("ACE_UPIPE_Stream::send_n"); - - size_t bytes_written; - ssize_t len = 0; - - for (bytes_written = 0; bytes_written < n; bytes_written += len) - { - len = this->send (buf + bytes_written, - n - bytes_written, - timeout); - - if (len == -1) - { - return -1; - } - } - - return static_cast (bytes_written); -} - -ssize_t -ACE_UPIPE_Stream::recv_n (char *buf, - size_t n, - ACE_Time_Value *timeout) -{ - ACE_TRACE ("ACE_UPIPE_Stream::recv_n"); - size_t bytes_read; - ssize_t len = 0; - - for (bytes_read = 0; bytes_read < n; bytes_read += len) - { - len = this->recv (buf + bytes_read, - n - bytes_read, - timeout); - - if (len == -1) - { - return -1; - } - else if (len == 0) - { - break; - } - } - - return static_cast< ssize_t> (bytes_read); -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_THREADS */ diff --git a/externals/ace/UPIPE_Stream.h b/externals/ace/UPIPE_Stream.h deleted file mode 100644 index b10aef11591..00000000000 --- a/externals/ace/UPIPE_Stream.h +++ /dev/null @@ -1,140 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file UPIPE_Stream.h - * - * $Id: UPIPE_Stream.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Gerhard Lenzer - * @author Douglas C. Schmidt - */ -//============================================================================= - - -#ifndef ACE_UPIPE_STREAM_H -#define ACE_UPIPE_STREAM_H -#include /**/ "ace/pre.h" - -#include "ace/Stream.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_THREADS) - -#include "ace/SPIPE.h" -#include "ace/Message_Queue.h" -#include "ace/UPIPE_Addr.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_UPIPE_Stream - * - * @brief Defines the method that transfer data on a UPIPE. - */ -class ACE_Export ACE_UPIPE_Stream : public ACE_SPIPE -{ -public: - friend class ACE_UPIPE_Acceptor; - friend class ACE_UPIPE_Connector; - - typedef ACE_Stream MT_Stream; - - // = Initialization and Termination. - - ACE_UPIPE_Stream (void); - - virtual ~ACE_UPIPE_Stream (void); - - /// Shut down the UPIPE and release resources. - int close (void); - - /// Return the underlying I/O handle. - ACE_HANDLE get_handle (void) const; - - // = Send/recv ACE Message_Blocks. - /// Send a message through the message queue. Returns -1 on error, - /// else 0. - int send (ACE_Message_Block *mb_p, - ACE_Time_Value *timeout = 0); - - /// Recv a message from the message queue. Returns -1 on error, else - /// 0. - int recv (ACE_Message_Block *&mb_p, - ACE_Time_Value *timeout = 0); - - // = Send/recv char buffers. - /// Send a buffer of @a n bytes through the message queue. Returns -1 - /// on error, else number of bytes sent. - ssize_t send (const char *buffer, - size_t n, - ACE_Time_Value *timeout = 0); - - /// Recv a buffer of upto @a n bytes from the message queue. Returns - /// -1 on error, else number of bytes read. - ssize_t recv (char *buffer, - size_t n, - ACE_Time_Value *timeout = 0); - - /// Send a buffer of exactly @a n bytes to the message queue. Returns - /// -1 on error, else number of bytes written (which should == n). - ssize_t send_n (const char *buffer, - size_t n, - ACE_Time_Value *timeout = 0); - - /// Recv a buffer of exactly @a n bytes from the message queue. - /// Returns -1 on error, else the number of bytes read. - ssize_t recv_n (char *buffer, - size_t n, - ACE_Time_Value *timeout = 0); - - /// Perform control operations on the UPIPE_Stream. - int control (int cmd, void *val) const; - - /// Return the remote address we are connected to. - int get_remote_addr (ACE_UPIPE_Addr &remote_sap) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - - // = Meta-type info - typedef ACE_UPIPE_Addr PEER_ADDR; - -private: - /// To hold the last ACE_Message_Block read out of the stream. Thus - /// allowing subsequent reads from one ACE_Message_Block - ACE_Message_Block *mb_last_; - - /// Address of who we are connected to. - ACE_UPIPE_Addr remote_addr_; - - /// Stream component used by the @c UPIPE_Acceptor and - /// @c UPIPE_Connector to link together two UPIPE_Streams. - MT_Stream stream_; - - /// Keep track of whether the sender and receiver have both shutdown. - int reference_count_; - -#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) - /// Ensure that we are thread-safe. - ACE_Thread_Mutex lock_; -#endif /* ACE_MT_SAFE */ -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/UPIPE_Stream.inl" -#endif /* __ACE_INLINE__ */ - -#endif /* ACE_HAS_THREADS */ - -#include /**/ "ace/post.h" - -#endif /*ACE_UPIPE_STREAM_H */ diff --git a/externals/ace/UPIPE_Stream.inl b/externals/ace/UPIPE_Stream.inl deleted file mode 100644 index 7a0d73c3179..00000000000 --- a/externals/ace/UPIPE_Stream.inl +++ /dev/null @@ -1,14 +0,0 @@ -// -*- C++ -*- -// -// $Id: UPIPE_Stream.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE ACE_HANDLE -ACE_UPIPE_Stream::get_handle (void) const -{ - ACE_TRACE ("ACE_UPIPE_Stream::get_handle"); - return this->ACE_SPIPE::get_handle (); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/UTF16_Encoding_Converter.cpp b/externals/ace/UTF16_Encoding_Converter.cpp deleted file mode 100644 index da883734c39..00000000000 --- a/externals/ace/UTF16_Encoding_Converter.cpp +++ /dev/null @@ -1,364 +0,0 @@ -// $Id: UTF16_Encoding_Converter.cpp 83735 2008-11-14 09:41:52Z johnnyw $ - -// ====================================================================== -// -// The actual conversion methods are covered by the copyright information -// below. It is not the actual code provided by Unicode, Inc. but is an -// ACE-ified and only slightly modified version. -// Chad Elliott 4/28/2005 -// -// Copyright 2001-2004 Unicode, Inc. -// -// Limitations on Rights to Redistribute This Code -// -// Unicode, Inc. hereby grants the right to freely use the information -// supplied in this file in the creation of products supporting the -// Unicode Standard, and to make copies of this file in any form -// for internal or external distribution as long as this notice -// remains attached. -// -// ====================================================================== - -#include "ace/UTF16_Encoding_Converter.h" - -#if defined (ACE_USES_WCHAR) -#include "ace/OS_NS_stdio.h" -#include "ace/OS_Memory.h" -#include "ace/Min_Max.h" - -#if !defined (__ACE_INLINE__) -#include "ace/UTF16_Encoding_Converter.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -static const ACE_UINT32 halfShift = 10; -static const ACE_UINT32 halfBase = 0x00010000; -static const ACE_UINT32 halfMask = 0x000003FF; - -static const ACE_UINT32 UNI_SUR_HIGH_START = 0x0000D800; -static const ACE_UINT32 UNI_SUR_HIGH_END = 0x0000DBFF; -static const ACE_UINT32 UNI_SUR_LOW_START = 0x0000DC00; -static const ACE_UINT32 UNI_SUR_LOW_END = 0x0000DFFF; -static const ACE_UINT32 UNI_REPLACEMENT_CHAR = 0x0000FFFD; -static const ACE_UINT32 UNI_MAX_BMP = 0x0000FFFF; -static const ACE_UINT32 UNI_MAX_UTF16 = 0x0010FFFF; - -// Once the bits are split out into bytes of UTF-8, this is a mask OR-ed -// into the first byte, depending on how many bytes follow. There are -// as many entries in this table as there are UTF-8 sequence types. -// (I.e., one byte sequence, two byte... etc.). Remember that sequencs -// for *legal* UTF-8 will be 4 or fewer bytes total. -static const ACE_Byte firstByteMark[7] = { 0x00, 0x00, 0xC0, - 0xE0, 0xF0, 0xF8, 0xFC }; - -// Index into the table below with the first byte of a UTF-8 sequence to -// get the number of trailing bytes that are supposed to follow it. -// Note that *legal* UTF-8 values can't have 4 or 5-bytes. The table is -// left as-is for anyone who may want to do such conversion, which was -// allowed in earlier algorithms. -static const ACE_Byte trailingBytesForUTF8[256] = { - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, - 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 -}; - -// Magic values subtracted from a buffer value during UTF8 conversion. -// This table contains as many values as there might be trailing bytes -// in a UTF-8 sequence. -static const ACE_UINT32 offsetsFromUTF8[6] = { 0x00000000, 0x00003080, - 0x000E2080, 0x03C82080, - 0xFA082080, 0x82082080 }; - - -ACE_UTF16_Encoding_Converter::ACE_UTF16_Encoding_Converter (bool swap) - : swap_ (swap) -{ -} - -ACE_UTF16_Encoding_Converter::~ACE_UTF16_Encoding_Converter (void) -{ -} - -ACE_UTF16_Encoding_Converter::Result -ACE_UTF16_Encoding_Converter::to_utf8 (const void* source, - size_t source_size, - ACE_Byte* target, - size_t target_size, - bool strict) -{ - static const ACE_UINT32 byteMask = 0xBF; - static const ACE_UINT32 byteMark = 0x80; - Result result = CONVERSION_OK; - - ACE_Byte* targetEnd = target + target_size; - const ACE_UINT16* sourceStart = static_cast (source); - const ACE_UINT16* sourceEnd = sourceStart + - (source_size / sizeof (ACE_UINT16)); - - while (sourceStart < sourceEnd) - { - ACE_UINT16 nw = *sourceStart++; - ACE_UINT32 ch = (this->swap_ ? ACE_SWAP_WORD (nw) : nw); - - // If we have a surrogate pair, convert to ACE_UINT32 first. - if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) - { - // If the 16 bits following the high surrogate are in the - // sourceStart buffer... - if (sourceStart < sourceEnd) - { - ACE_UINT32 ch2 = (this->swap_ ? ACE_SWAP_WORD (*sourceStart) : - *sourceStart); - // If it's a low surrogate, convert to ACE_UINT32. - if (ch2 >= UNI_SUR_LOW_START && ch2 <= UNI_SUR_LOW_END) - { - ch = ((ch - UNI_SUR_HIGH_START) << halfShift) - + (ch2 - UNI_SUR_LOW_START) + halfBase; - ++sourceStart; - } - else if (strict) - { - // it's an unpaired high surrogate - result = SOURCE_ILLEGAL; - break; - } - } - else - { - // We don't have the 16 bits following the high surrogate. - result = SOURCE_EXHAUSTED; - break; - } - } - else if (strict) - { - // UTF-16 surrogate values are illegal in UTF-32 - if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) - { - result = SOURCE_ILLEGAL; - break; - } - } - - // Figure out how many bytes the result will require - unsigned short bytesToWrite = 0; - if (ch < 0x80) - bytesToWrite = 1; - else if (ch < 0x800) - bytesToWrite = 2; - else if (ch < 0x10000) - bytesToWrite = 3; - else if (ch < 0x110000) - bytesToWrite = 4; - else - { - bytesToWrite = 3; - ch = UNI_REPLACEMENT_CHAR; - } - - target += bytesToWrite; - if (target > targetEnd) - { - result = TARGET_EXHAUSTED; - break; - } - - // NOTE: Everything falls through for efficiency purposes. - switch (bytesToWrite) - { - case 4: - *--target = (ACE_Byte)((ch | byteMark) & byteMask); - ch >>= 6; - case 3: - *--target = (ACE_Byte)((ch | byteMark) & byteMask); - ch >>= 6; - case 2: - *--target = (ACE_Byte)((ch | byteMark) & byteMask); - ch >>= 6; - case 1: - *--target = (ACE_Byte)(ch | firstByteMark[bytesToWrite]); - } - target += bytesToWrite; - } - - return result; -} - -ACE_UTF16_Encoding_Converter::Result -ACE_UTF16_Encoding_Converter::from_utf8 (const ACE_Byte* source, - size_t source_size, - void* target, - size_t target_size, - bool strict) -{ - Result result = CONVERSION_OK; - const ACE_Byte* sourceEnd = source + source_size; - ACE_UINT16* targetStart = static_cast (target); - ACE_UINT16* targetEnd = targetStart + target_size; - - while (source < sourceEnd) - { - ACE_UINT32 ch = 0; - unsigned short extraBytesToRead = trailingBytesForUTF8[*source]; - if (source + extraBytesToRead >= sourceEnd) - { - result = SOURCE_EXHAUSTED; - break; - } - - // Do this check whether lenient or strict - if (!this->is_legal_utf8 (source, extraBytesToRead + 1)) - { - result = SOURCE_ILLEGAL; - break; - } - - // The cases all fall through. See "Note A" below. - switch (extraBytesToRead) - { - case 5: // remember, illegal UTF-8 - ch += *source++; - ch <<= 6; - case 4: // remember, illegal UTF-8 - ch += *source++; - ch <<= 6; - case 3: - ch += *source++; - ch <<= 6; - case 2: - ch += *source++; - ch <<= 6; - case 1: - ch += *source++; - ch <<= 6; - case 0: - ch += *source++; - } - ch -= offsetsFromUTF8[extraBytesToRead]; - - if (targetStart >= targetEnd) - { - result = TARGET_EXHAUSTED; - break; - } - - if (ch <= UNI_MAX_BMP) // Target is a character <= 0xFFFF - { - // UTF-16 surrogate values are illegal in UTF-32 - if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) - { - if (strict) - { - result = SOURCE_ILLEGAL; - break; - } - else - { - *targetStart++ = UNI_REPLACEMENT_CHAR; - } - } - else - { - *targetStart++ = (ACE_UINT16)ch; - } - } - else if (ch > UNI_MAX_UTF16) - { - if (strict) - { - result = SOURCE_ILLEGAL; - break; - } - else - { - *targetStart++ = UNI_REPLACEMENT_CHAR; - } - } - else - { - // targetStart is a character in range 0xFFFF - 0x10FFFF. - if (targetStart + 1 >= targetEnd) - { - result = TARGET_EXHAUSTED; - break; - } - ch -= halfBase; - *targetStart++ = (ACE_UINT16)((ch >> halfShift) + UNI_SUR_HIGH_START); - *targetStart++ = (ACE_UINT16)((ch & halfMask) + UNI_SUR_LOW_START); - } - } - - return result; -} - -ACE_UTF16_Encoding_Converter* -ACE_UTF16_Encoding_Converter::encoded (const ACE_Byte* source, - size_t source_size) -{ - static const size_t begin = 16; - static const size_t converted = begin * 4; - - ACE_Byte target[converted]; - ACE_UTF16_Encoding_Converter* converter = 0; - ACE_NEW_RETURN (converter, - ACE_UTF16_Encoding_Converter (false), - 0); - if (converter->to_utf8 (source, - ACE_MIN (begin, source_size), - target, - converted) == CONVERSION_OK) - { - return converter; - } - else - { - delete converter; - } - - return 0; -} - -ACE_UINT32 -ACE_UTF16_Encoding_Converter::get_UNI_SUR_HIGH_START (void) -{ - return UNI_SUR_HIGH_START; -} - -ACE_UINT32 -ACE_UTF16_Encoding_Converter::get_UNI_SUR_LOW_END (void) -{ - return UNI_SUR_LOW_END; -} - -ACE_UINT32 -ACE_UTF16_Encoding_Converter::get_UNI_REPLACEMENT_CHAR (void) -{ - return UNI_REPLACEMENT_CHAR; -} - -const ACE_Byte* -ACE_UTF16_Encoding_Converter::get_first_byte_mark (void) -{ - return firstByteMark; -} - -const ACE_Byte* -ACE_UTF16_Encoding_Converter::get_trailing_bytes_for_utf8 (void) -{ - return trailingBytesForUTF8; -} - -const ACE_UINT32* -ACE_UTF16_Encoding_Converter::get_offsets_from_utf8 (void) -{ - return offsetsFromUTF8; -} - -ACE_END_VERSIONED_NAMESPACE_DECL -#endif /* ACE_USES_WCHAR */ diff --git a/externals/ace/UTF16_Encoding_Converter.h b/externals/ace/UTF16_Encoding_Converter.h deleted file mode 100644 index 9bdcb21a07f..00000000000 --- a/externals/ace/UTF16_Encoding_Converter.h +++ /dev/null @@ -1,86 +0,0 @@ -// -*- C++ -*- - -//========================================================================= -/** - * @file UTF16_Encoding_Converter.h - * - * $Id: UTF16_Encoding_Converter.h 80826 2008-03-04 14:51:23Z wotte $ - * - * This class contains declarations for methods that convert between - * UTF-16 (both BE and LE) and UTF-8 - * - * @author Chad Elliott - */ -//========================================================================= - -#ifndef ACE_UTF16_ENCODING_CONVERTER_H -#define ACE_UTF16_ENCODING_CONVERTER_H - -#include /**/ "ace/pre.h" - -#include "ace/Encoding_Converter.h" - -#if defined (ACE_USES_WCHAR) -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** Convert from UTF-16 to UTF-8 and from UTF-8 to UTF-16. - * This class implements the ACE_Encoding_Converter interface. - */ -class ACE_UTF16_Encoding_Converter: public ACE_Encoding_Converter -{ -public: - /// The swap parameter determines whether we need to swap byte order on - /// the stream as each word is pulled off when converting to UTF-8. - ACE_UTF16_Encoding_Converter (bool swap = false); - - /// This is a do nothing destructor. - virtual ~ACE_UTF16_Encoding_Converter (void); - - /// Convert the source from UTF-16 to UTF-8 and store it in the - /// provided target buffer. - virtual Result to_utf8 (const void* source, - size_t source_size, - ACE_Byte* target, - size_t target_size, - bool strict = true); - - /// Convert the UTF-8 source into a UTF-16 encoding and store it - /// in the provided target buffer. - virtual Result from_utf8 (const ACE_Byte* source, - size_t source_size, - void* target, - size_t target_size, - bool strict = true); - - /// This factory helper method determines if the source stream is UTF-16 - /// encoded. If it is, allocate an ACE_UTF16_Encoding_Converter and - /// return it. The caller then owns the allocated object. - static ACE_UTF16_Encoding_Converter* encoded (const ACE_Byte* source, - size_t source_size); - -protected: - /// Determines if the source buffer is legal UTF-8 - bool is_legal_utf8 (const ACE_Byte* source, - size_t length) const; - - static ACE_UINT32 get_UNI_SUR_HIGH_START (void); - static ACE_UINT32 get_UNI_SUR_LOW_END (void); - static ACE_UINT32 get_UNI_REPLACEMENT_CHAR (void); - static const ACE_Byte* get_first_byte_mark (void); - static const ACE_Byte* get_trailing_bytes_for_utf8 (void); - static const ACE_UINT32* get_offsets_from_utf8 (void); - - bool swap_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/UTF16_Encoding_Converter.inl" -#endif /* __ACE_INLINE__ */ - -#endif /* ACE_USES_WCHAR */ - -#include /**/ "ace/post.h" - -#endif /* ACE_UTF16_ENCODING_CONVERTER_H */ diff --git a/externals/ace/UTF16_Encoding_Converter.inl b/externals/ace/UTF16_Encoding_Converter.inl deleted file mode 100644 index e5292757889..00000000000 --- a/externals/ace/UTF16_Encoding_Converter.inl +++ /dev/null @@ -1,76 +0,0 @@ -/* -*- C++ -*- */ -// $Id: UTF16_Encoding_Converter.inl 80826 2008-03-04 14:51:23Z wotte $ - -// ====================================================================== -// -// The actual conversion methods are covered by the copyright information -// below. -// Chad Elliott 4/28/2005 -// -// Copyright 2001-2004 Unicode, Inc. -// -// Limitations on Rights to Redistribute This Code -// -// Unicode, Inc. hereby grants the right to freely use the information -// supplied in this file in the creation of products supporting the -// Unicode Standard, and to make copies of this file in any form -// for internal or external distribution as long as this notice -// remains attached. -// -// ====================================================================== - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE bool -ACE_UTF16_Encoding_Converter::is_legal_utf8 (const ACE_Byte* source, - size_t length) const -{ - ACE_Byte a; - const ACE_Byte* srcptr = source + length; - - switch (length) - { - default: - return false; - - // Everything else falls through when "true"... - case 4: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false; - case 3: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false; - case 2: if ((a = (*--srcptr)) > 0xBF) return false; - - switch (*source) - { - // no fall-through in this inner switch - case 0xE0: - if (a < 0xA0) - return false; - break; - case 0xED: - if (a > 0x9F) - return false; - break; - case 0xF0: - if (a < 0x90) - return false; - break; - case 0xF4: - if (a > 0x8F) - return false; - break; - default: - if (a < 0x80) - return false; - } - - case 1: - if (*source >= 0x80 && *source < 0xC2) - return false; - } - - if (*source > 0xF4) - return false; - - return true; -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/UTF32_Encoding_Converter.cpp b/externals/ace/UTF32_Encoding_Converter.cpp deleted file mode 100644 index 459bf2530b0..00000000000 --- a/externals/ace/UTF32_Encoding_Converter.cpp +++ /dev/null @@ -1,254 +0,0 @@ -// $Id: UTF32_Encoding_Converter.cpp 80826 2008-03-04 14:51:23Z wotte $ - -// ====================================================================== -// -// The actual conversion methods are covered by the copyright information -// below. It is not the actual code provided by Unicode, Inc. but is an -// ACE-ified and only slightly modified version. -// -// Chad Elliott 4/28/2005 -// -// Copyright 2001-2004 Unicode, Inc. -// -// Limitations on Rights to Redistribute This Code -// -// Unicode, Inc. hereby grants the right to freely use the information -// supplied in this file in the creation of products supporting the -// Unicode Standard, and to make copies of this file in any form -// for internal or external distribution as long as this notice -// remains attached. -// -// ====================================================================== - -#include "ace/UTF32_Encoding_Converter.h" - -#if defined (ACE_USES_WCHAR) -#include "ace/OS_NS_stdio.h" -#include "ace/OS_Memory.h" -#include "ace/Min_Max.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -static const ACE_UINT32 UNI_MAX_LEGAL_UTF32 = 0x0010FFFF; - -ACE_UTF32_Encoding_Converter::ACE_UTF32_Encoding_Converter (bool swap) - : ACE_UTF16_Encoding_Converter (swap) -{ -} - -ACE_UTF32_Encoding_Converter::~ACE_UTF32_Encoding_Converter (void) -{ -} - -ACE_UTF32_Encoding_Converter::Result -ACE_UTF32_Encoding_Converter::to_utf8 (const void* source, - size_t source_size, - ACE_Byte* target, - size_t target_size, - bool strict) -{ - static const ACE_UINT32 byteMask = 0xBF; - static const ACE_UINT32 byteMark = 0x80; - static const ACE_UINT32 UNI_SUR_HIGH_START = get_UNI_SUR_HIGH_START (); - static const ACE_UINT32 UNI_SUR_LOW_END = get_UNI_SUR_LOW_END (); - static const ACE_Byte* firstByteMark = get_first_byte_mark (); - - Result result = CONVERSION_OK; - ACE_Byte* targetEnd = target + target_size; - const ACE_UINT32* sourceStart = static_cast (source); - const ACE_UINT32* sourceEnd = sourceStart + (source_size / sizeof (ACE_UINT32)); - - while (sourceStart < sourceEnd) - { - ACE_UINT32 nw = *sourceStart++; - ACE_UINT32 ch = (this->swap_ ? ACE_SWAP_LONG (nw) : nw); - unsigned short bytesToWrite = 0; - - if (strict) - { - // UTF-16 surrogate values are illegal in UTF-32 - if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) - { - result = SOURCE_ILLEGAL; - break; - } - } - - // Figure out how many bytes the result will require. Turn any - // illegally large ACE_UINT32 things (> Plane 17) into replacement - // chars. - if (ch < 0x80) - { - bytesToWrite = 1; - } - else if (ch < 0x800) - { - bytesToWrite = 2; - } - else if (ch < 0x10000) - { - bytesToWrite = 3; - } - else if (ch <= UNI_MAX_LEGAL_UTF32) - { - bytesToWrite = 4; - } - else - { - result = SOURCE_ILLEGAL; - break; - } - - target += bytesToWrite; - if (target > targetEnd) - { - result = TARGET_EXHAUSTED; - break; - } - - // NOTE: everything falls through. - switch (bytesToWrite) - { - case 4: - *--target = (ACE_Byte)((ch | byteMark) & byteMask); - ch >>= 6; - case 3: - *--target = (ACE_Byte)((ch | byteMark) & byteMask); - ch >>= 6; - case 2: - *--target = (ACE_Byte)((ch | byteMark) & byteMask); - ch >>= 6; - case 1: - *--target = (ACE_Byte) (ch | firstByteMark[bytesToWrite]); - } - target += bytesToWrite; - } - - return result; -} - -ACE_UTF32_Encoding_Converter::Result -ACE_UTF32_Encoding_Converter::from_utf8 (const ACE_Byte* source, - size_t source_size, - void* target, - size_t target_size, - bool strict) -{ - static const ACE_UINT32 UNI_SUR_HIGH_START = get_UNI_SUR_HIGH_START (); - static const ACE_UINT32 UNI_SUR_LOW_END = get_UNI_SUR_LOW_END (); - static const ACE_UINT32 UNI_REPLACEMENT_CHAR = get_UNI_REPLACEMENT_CHAR (); - static const ACE_Byte* trailingBytesForUTF8 = get_trailing_bytes_for_utf8 (); - static const ACE_UINT32* offsetsFromUTF8 = get_offsets_from_utf8 (); - - Result result = CONVERSION_OK; - const ACE_Byte* sourceEnd = source + source_size; - ACE_UINT32* targetStart = static_cast (target); - ACE_UINT32* targetEnd = targetStart + target_size; - - while (source < sourceEnd) - { - ACE_UINT32 ch = 0; - unsigned short extraBytesToRead = trailingBytesForUTF8[*source]; - if (source + extraBytesToRead >= sourceEnd) - { - result = SOURCE_EXHAUSTED; - break; - } - - // Do this check whether lenient or strict - if (!this->is_legal_utf8 (source, extraBytesToRead + 1)) - { - result = SOURCE_ILLEGAL; - break; - } - - // The cases all fall through. See "Note A" below. - switch (extraBytesToRead) - { - case 5: - ch += *source++; - ch <<= 6; - case 4: - ch += *source++; - ch <<= 6; - case 3: - ch += *source++; - ch <<= 6; - case 2: - ch += *source++; - ch <<= 6; - case 1: - ch += *source++; - ch <<= 6; - case 0: - ch += *source++; - } - ch -= offsetsFromUTF8[extraBytesToRead]; - - if (targetStart >= targetEnd) - { - result = TARGET_EXHAUSTED; - break; - } - - if (ch <= UNI_MAX_LEGAL_UTF32) - { - // UTF-16 surrogate values are illegal in UTF-32, and anything - // over Plane 17 (> 0x10FFFF) is illegal. - if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) - { - if (strict) - { - result = SOURCE_ILLEGAL; - break; - } - else - { - *targetStart++ = UNI_REPLACEMENT_CHAR; - } - } - else - { - *targetStart++ = ch; - } - } - else - { - result = SOURCE_ILLEGAL; - break; - } - } - - return result; -} - -ACE_UTF32_Encoding_Converter* -ACE_UTF32_Encoding_Converter::encoded (const ACE_Byte* source, - size_t source_size) -{ - static const size_t begin = 16; - static const size_t converted = begin * 4; - - ACE_Byte target[converted]; - ACE_UTF32_Encoding_Converter* converter = 0; - ACE_NEW_RETURN (converter, - ACE_UTF32_Encoding_Converter (false), - 0); - - if (converter->to_utf8 (source, - ACE_MIN (begin, source_size), - target, - converted) == CONVERSION_OK) - { - return converter; - } - else - { - delete converter; - } - - return 0; -} - -ACE_END_VERSIONED_NAMESPACE_DECL -#endif /* ACE_USES_WCHAR */ diff --git a/externals/ace/UTF32_Encoding_Converter.h b/externals/ace/UTF32_Encoding_Converter.h deleted file mode 100644 index 214edeeeed8..00000000000 --- a/externals/ace/UTF32_Encoding_Converter.h +++ /dev/null @@ -1,67 +0,0 @@ -// -*- C++ -*- - -//========================================================================= -/** - * @file UTF32_Encoding_Converter.h - * - * $Id: UTF32_Encoding_Converter.h 80826 2008-03-04 14:51:23Z wotte $ - * - * This class contains declarations for methods that convert between - * UTF-32 (both BE and LE) and UTF-8 - * - * @author Chad Elliott - */ -//========================================================================= - -#ifndef ACE_UTF32_ENCODING_CONVERTER_H -#define ACE_UTF32_ENCODING_CONVERTER_H - -#include /**/ "ace/pre.h" - -#include "ace/UTF16_Encoding_Converter.h" - -#if defined (ACE_USES_WCHAR) -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** Convert from UTF-32 to UTF-8 and from UTF-8 to UTF-32. - * This class implements the ACE_Encoding_Converter interface. - */ -class ACE_UTF32_Encoding_Converter: public ACE_UTF16_Encoding_Converter -{ -public: - /// This class has some similarities to the UTF16 converter, so - /// we just construct our base class and pass the swap parameter. - ACE_UTF32_Encoding_Converter (bool swap = false); - - /// This is a do nothing destructor. - virtual ~ACE_UTF32_Encoding_Converter (void); - - /// Convert the source from UTF-32 to UTF-8 and store it in the - /// provided target buffer. - virtual Result to_utf8 (const void* source, - size_t source_size, - ACE_Byte* target, - size_t target_size, - bool strict = true); - - /// Convert the UTF-8 source into a UTF-32 encoding and store it - /// in the provided target buffer. - virtual Result from_utf8 (const ACE_Byte* source, - size_t source_size, - void* target, - size_t target_size, - bool strict = true); - - /// This factory helper method determines if the source stream is UTF-32 - /// encoded. If it is, allocate an ACE_UTF32_Encoding_Converter and - /// return it. The caller then owns the allocated object. - static ACE_UTF32_Encoding_Converter* encoded (const ACE_Byte* source, - size_t source_size); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL -#endif /* ACE_USES_WCHAR */ - -#include /**/ "ace/post.h" - -#endif /* ACE_UTF32_ENCODING_CONVERTER_H */ diff --git a/externals/ace/UTF8_Encoding_Converter.cpp b/externals/ace/UTF8_Encoding_Converter.cpp deleted file mode 100644 index cd6c409d0f8..00000000000 --- a/externals/ace/UTF8_Encoding_Converter.cpp +++ /dev/null @@ -1,92 +0,0 @@ -// $Id: UTF8_Encoding_Converter.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/UTF8_Encoding_Converter.h" - -#if defined (ACE_USES_WCHAR) -#include "ace/UTF16_Encoding_Converter.h" -#include "ace/UTF32_Encoding_Converter.h" -#include "ace/OS_NS_string.h" -#include "ace/OS_Memory.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_UTF8_Encoding_Converter::ACE_UTF8_Encoding_Converter (void) - : native_ (0) -{ - // Choose a converter for the ASCII or UTF-8 string to a wide character - // string which we will use in from_utf8. We have to make an - // assumption here about the encoding based on the size of ACE_TCHAR. - switch (sizeof (ACE_TCHAR)) - { - case 4: - ACE_NEW(this->native_, ACE_UTF32_Encoding_Converter); - break; - case 2: - ACE_NEW(this->native_, ACE_UTF16_Encoding_Converter); - break; - } -} - -ACE_UTF8_Encoding_Converter::~ACE_UTF8_Encoding_Converter (void) -{ - delete native_; -} - -ACE_UTF8_Encoding_Converter::Result -ACE_UTF8_Encoding_Converter::to_utf8 (const void* source, - size_t source_size, - ACE_Byte* target, - size_t target_size, - bool /*strict*/) -{ - if (target_size >= source_size) - { - ACE_OS::memcpy (target, source, source_size); - return CONVERSION_OK; - } - - return TARGET_EXHAUSTED; -} - -ACE_UTF8_Encoding_Converter::Result -ACE_UTF8_Encoding_Converter::from_utf8 (const ACE_Byte* source, - size_t source_size, - void* target, - size_t target_size, - bool strict) -{ - if (this->native_ != 0) - { - return this->native_->from_utf8(source, source_size, - target, target_size, strict); - } - - ACE_TCHAR* targetStart = static_cast (target); - ACE_OS::strncpy (targetStart, - ACE_TEXT_CHAR_TO_TCHAR ( - reinterpret_cast (source)), - source_size); - targetStart[source_size] = 0; - return CONVERSION_OK; -} - -ACE_UTF8_Encoding_Converter* -ACE_UTF8_Encoding_Converter::encoded (const ACE_Byte* source, - size_t source_size) -{ - for(size_t i = 0; i < source_size; i++) - { - if (source[i] < 0x01 || source[i] > 0x7f) - return 0; - } - - // All characters are "valid" ASCII - ACE_UTF8_Encoding_Converter* converter = 0; - ACE_NEW_RETURN (converter, - ACE_UTF8_Encoding_Converter, - 0); - return converter; -} - -ACE_END_VERSIONED_NAMESPACE_DECL -#endif /* ACE_USES_WCHAR */ diff --git a/externals/ace/UTF8_Encoding_Converter.h b/externals/ace/UTF8_Encoding_Converter.h deleted file mode 100644 index 2cb6ed4e452..00000000000 --- a/externals/ace/UTF8_Encoding_Converter.h +++ /dev/null @@ -1,72 +0,0 @@ -// -*- C++ -*- - -//========================================================================= -/** - * @file UTF8_Encoding_Converter.h - * - * $Id: UTF8_Encoding_Converter.h 80826 2008-03-04 14:51:23Z wotte $ - * - * This class contains declarations for methods that convert between - * UTF-8 and the native ACE_TCHAR representation. - * - * @author Chad Elliott - */ -//========================================================================= - -#ifndef ACE_UTF8_ENCODING_CONVERTER_H -#define ACE_UTF8_ENCODING_CONVERTER_H - -#include /**/ "ace/pre.h" - -#include "ace/Encoding_Converter.h" - -#if defined (ACE_USES_WCHAR) -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** Convert from UTF-16 or UTF-32 to UTF-8. - * This class implements the ACE_Encoding_Converter interface. - */ -class ACE_UTF8_Encoding_Converter: public ACE_Encoding_Converter -{ -public: - /// Allocate the converter to be used by the from_utf8() method based - /// on the size of the native wide character. - ACE_UTF8_Encoding_Converter (void); - - /// De-allocate the native converter. - virtual ~ACE_UTF8_Encoding_Converter (void); - - /// Since the source *must be* UTF-8, there is no conversion required. - /// This method just copies the source to the target given that there - /// is enough space. - virtual Result to_utf8 (const void* source, - size_t source_size, - ACE_Byte* target, - size_t target_size, - bool strict = true); - - /// Utilize the native converter to convert the UTF-8 source into an - /// alternate encoding and store it in the provided target buffer. - virtual Result from_utf8 (const ACE_Byte* source, - size_t source_size, - void* target, - size_t target_size, - bool strict = true); - - - /// This factory helper method determines if the source stream is UTF-8 - /// encoded. If it is, allocate an ACE_UTF8_Encoding_Converter and - /// return it. The caller then owns the allocated object. - static ACE_UTF8_Encoding_Converter* encoded (const ACE_Byte* source, - size_t source_size); - -private: - ACE_Encoding_Converter* native_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL -#endif /* ACE_USES_WCHAR */ - -#include /**/ "ace/post.h" - -#endif /* ACE_UTF8_ENCODING_CONVERTER_H */ diff --git a/externals/ace/UUID.cpp b/externals/ace/UUID.cpp deleted file mode 100644 index 800469481e7..00000000000 --- a/externals/ace/UUID.cpp +++ /dev/null @@ -1,506 +0,0 @@ -//$Id: UUID.cpp 88515 2010-01-13 08:47:38Z johnnyw $ - -#include "ace/UUID.h" -#include "ace/Guard_T.h" - -#if !defined (__ACE_INLINE__) -#include "ace/UUID.inl" -#endif /* __ACE_INLINE__ */ - -#include "ace/Log_Msg.h" -#include "ace/OS_NS_stdio.h" -#include "ace/OS_NS_string.h" -#include "ace/OS_NS_sys_time.h" -#include "ace/OS_NS_netdb.h" -#include "ace/OS_NS_unistd.h" -#include "ace/ACE.h" - -ACE_RCSID (ace, - UUID, - "$Id: UUID.cpp 88515 2010-01-13 08:47:38Z johnnyw $") - - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -namespace ACE_Utils -{ - // NIL version of the UUID - const UUID UUID::NIL_UUID; - - UUID::UUID (const ACE_CString& uuid_string) - { - this->init (); - this->from_string_i (uuid_string); - } - - const UUID & - UUID::operator = (const UUID & rhs) - { - if (this != &rhs) - { - // Reset the string version of the UUID a string version - // exist, and the UUID is not equal to the old UUID. - if (0 != this->as_string_.get ()) - { - if (0 == rhs.as_string_.get () || *this != rhs) - this->as_string_.reset (); - } - - // Copy the contents of the UUID. - ACE_OS::memcpy (&this->uuid_, &rhs.uuid_, BINARY_SIZE); - - /// @todo We should create an UUID_Ex class for UUIDs that - /// contain the thread id and process id. - this->thr_id_ = rhs.thr_id_; - this->pid_ = rhs.pid_; - } - - return *this; - } - - const ACE_CString * UUID::to_string (void) const - { - // Compute the string representation only once. - if (0 != this->as_string_.get ()) - return this->as_string_.get (); - - // Get a buffer exactly the correct size. Use the nil UUID as a - // gauge. Don't forget the trailing nul. - ACE_Auto_Array_Ptr auto_clean; - size_t UUID_STRING_LENGTH = 36 + thr_id_.length () + pid_.length (); - char *buf = 0; - - if (36 == UUID_STRING_LENGTH) - { - ACE_NEW_RETURN (buf, - char[UUID_STRING_LENGTH + 1], - 0); - - // Let the auto array pointer manage the buffer. - auto_clean.reset (buf); - - ACE_OS::sprintf (buf, - "%8.8x-%4.4x-%4.4x-%2.2x%2.2x-%2.2x%2.2x%2.2x%2.2x%2.2x%2.2x", - this->uuid_.time_low_, - this->uuid_.time_mid_, - this->uuid_.time_hi_and_version_, - this->uuid_.clock_seq_hi_and_reserved_, - this->uuid_.clock_seq_low_, - (this->uuid_.node_.node_ID ()) [0], - (this->uuid_.node_.node_ID ()) [1], - (this->uuid_.node_.node_ID ()) [2], - (this->uuid_.node_.node_ID ()) [3], - (this->uuid_.node_.node_ID ()) [4], - (this->uuid_.node_.node_ID ()) [5]); - } - else - { - UUID_STRING_LENGTH += 2; //for '-' - ACE_NEW_RETURN (buf, - char[UUID_STRING_LENGTH + 1], - 0); - - // Let the auto array pointer manage the buffer. - auto_clean.reset (buf); - - ACE_OS::sprintf (buf, - "%8.8x-%4.4x-%4.4x-%2.2x%2.2x-%2.2x%2.2x%2.2x%2.2x%2.2x%2.2x-%s-%s", - this->uuid_.time_low_, - this->uuid_.time_mid_, - this->uuid_.time_hi_and_version_, - this->uuid_.clock_seq_hi_and_reserved_, - this->uuid_.clock_seq_low_, - (this->uuid_.node_.node_ID ()) [0], - (this->uuid_.node_.node_ID ()) [1], - (this->uuid_.node_.node_ID ()) [2], - (this->uuid_.node_.node_ID ()) [3], - (this->uuid_.node_.node_ID ()) [4], - (this->uuid_.node_.node_ID ()) [5], - thr_id_.c_str (), - pid_.c_str ()); - } - - // Save the string. - ACE_CString * as_string = 0; - - ACE_NEW_RETURN (as_string, - ACE_CString (buf, UUID_STRING_LENGTH), - 0); - - this->as_string_.reset (as_string); - return this->as_string_.get (); - } - - void - UUID::from_string_i (const ACE_CString& uuid_string) - { - if (uuid_string.length () < NIL_UUID.to_string ()->length ()) - { - ACE_ERROR ((LM_ERROR, - "%N ACE_UUID::from_string_i - " - "IllegalArgument (incorrect string length)\n")); - return; - } - - /// Special case for the nil UUID. - if (uuid_string == *NIL_UUID.to_string ()) - { - *this = NIL_UUID; - return; - } - - unsigned int time_low; - unsigned int time_mid; - unsigned int time_hi_and_version; - unsigned int clock_seq_hi_and_reserved; - unsigned int clock_seq_low; - unsigned int node [UUID_Node::NODE_ID_SIZE]; - char thr_pid_buf [BUFSIZ]; - - if (uuid_string.length () == NIL_UUID.to_string ()->length ()) - { - // This might seem quite strange this being in ACE, but it - // seems to be a bit difficult to write a facade for ::sscanf - // because some compilers dont support vsscanf, including - // MSVC. It appears that most platforms support sscanf though - // so we need to use it directly. - const int nScanned = -#if defined (ACE_HAS_TR24731_2005_CRT) - sscanf_s ( -#else - ::sscanf ( -#endif /* ACE_HAS_TR24731_2005_CRT */ - uuid_string.c_str (), - "%8x-%4x-%4x-%2x%2x-%2x%2x%2x%2x%2x%2x", - &time_low, - &time_mid, - &time_hi_and_version, - &clock_seq_hi_and_reserved, - &clock_seq_low, - &node[0], - &node[1], - &node[2], - &node[3], - &node[4], - &node[5] - ); - - if (nScanned != 11) - { - ACE_DEBUG ((LM_DEBUG, - "UUID::from_string_i - " - "IllegalArgument (invalid string representation)\n")); - return; - } - } - else - { - const int nScanned = -#if defined (ACE_HAS_TR24731_2005_CRT) - sscanf_s (uuid_string.c_str (), - "%8x-%4x-%4x-%2x%2x-%2x%2x%2x%2x%2x%2x-%s", - &time_low, - &time_mid, - &time_hi_and_version, - &clock_seq_hi_and_reserved, - &clock_seq_low, - &node[0], - &node[1], - &node[2], - &node[3], - &node[4], - &node[5], - thr_pid_buf, - BUFSIZ - ); -#else - ::sscanf (uuid_string.c_str (), - "%8x-%4x-%4x-%2x%2x-%2x%2x%2x%2x%2x%2x-%s", - &time_low, - &time_mid, - &time_hi_and_version, - &clock_seq_hi_and_reserved, - &clock_seq_low, - &node[0], - &node[1], - &node[2], - &node[3], - &node[4], - &node[5], - thr_pid_buf - ); -#endif /* ACE_HAS_TR24731_2005_CRT */ - - if (nScanned != 12) - { - ACE_DEBUG ((LM_DEBUG, - "ACE_UUID::from_string_i - " - "IllegalArgument (invalid string representation)\n")); - return; - } - } - - this->uuid_.time_low_ = static_cast (time_low); - this->uuid_.time_mid_ = static_cast (time_mid); - this->uuid_.time_hi_and_version_ = static_cast (time_hi_and_version); - this->uuid_.clock_seq_hi_and_reserved_ = static_cast (clock_seq_hi_and_reserved); - this->uuid_.clock_seq_low_ = static_cast (clock_seq_low); - - for (size_t i = 0; i < UUID_Node::NODE_ID_SIZE; ++ i) - this->uuid_.node_.node_ID ()[i] = static_cast (node[i]); - - // Support varient 10- only - if ((this->uuid_.clock_seq_hi_and_reserved_ & 0xc0) != 0x80 && - (this->uuid_.clock_seq_hi_and_reserved_ & 0xc0) != 0xc0) - { - ACE_DEBUG ((LM_DEBUG, - "ACE_UUID::from_string_i - " - "IllegalArgument (unsupported variant)\n")); - return; - } - - /// Support versions 1, 3, and 4 only - ACE_UINT16 V1 = this->uuid_.time_hi_and_version_; - - if ((V1 & 0xF000) != 0x1000 && - (V1 & 0xF000) != 0x3000 && - (V1 & 0xF000) != 0x4000) - { - ACE_DEBUG ((LM_DEBUG, - "ACE_UUID::from_string_i - " - "IllegalArgument (unsupported version)\n")); - return; - } - - if ((this->uuid_.clock_seq_hi_and_reserved_ & 0xc0) == 0xc0) - { - if (uuid_string.length () == NIL_UUID.to_string ()->length ()) - { - ACE_DEBUG ((LM_DEBUG, - "ACE_UUID::from_string_i - " - "IllegalArgument (Missing Thread and Process Id)\n")); - return; - } - ACE_CString thr_pid_str (thr_pid_buf); - ssize_t pos = static_cast (thr_pid_str.find ('-')); - if (pos == -1) - ACE_DEBUG ((LM_DEBUG, - "ACE_UUID::from_string_i - " - "IllegalArgument (Thread and Process Id format incorrect)\n")); - - this->thr_id_ = thr_pid_str.substr (0, pos); - this->pid_ = thr_pid_str.substr (pos+1, thr_pid_str.length ()-pos-1); - } - } - - UUID_Generator::UUID_Generator (void) - : time_last_ (0), - destroy_lock_ (true), - is_init_ (false) - { - ACE_NEW (lock_, ACE_SYNCH_MUTEX); - this->init (); - } - - UUID_Generator::~UUID_Generator (void) - { - if (destroy_lock_) - delete lock_; - } - - void - UUID_Generator::init (void) - { - if (this->is_init_) - return; - - ACE_OS::macaddr_node_t macaddress; - int const result = ACE_OS::getmacaddress (&macaddress); - - UUID_Node::Node_ID node_id; - - if (-1 != result) - { - ACE_OS::memcpy (node_id, - macaddress.node, - UUID_Node::NODE_ID_SIZE); - } - else - { - node_id [0] = static_cast (ACE_OS::rand ()); - node_id [1] = static_cast (ACE_OS::rand ()); - node_id [2] = static_cast (ACE_OS::rand ()); - node_id [3] = static_cast (ACE_OS::rand ()); - node_id [4] = static_cast (ACE_OS::rand ()); - node_id [5] = static_cast (ACE_OS::rand ()); - } - - this->get_timestamp (time_last_); - - { - ACE_GUARD (ACE_SYNCH_MUTEX, ace_mon, *lock_); - uuid_state_.timestamp = time_last_; - - ACE_OS::memcpy (uuid_state_.node.node_ID (), - node_id, - UUID_Node::NODE_ID_SIZE); - } - - this->is_init_ = true; - } - - void - UUID_Generator:: - generate_UUID (UUID& uuid, ACE_UINT16 version, u_char variant) - { - UUID_Time timestamp; - ACE_UINT16 clock_sequence; - - this->get_timestamp_and_clocksequence (timestamp, - clock_sequence); - - // Construct a Version 1 UUID with the information in the arguements. - uuid.time_low (static_cast (timestamp & 0xFFFFFFFF)); - uuid.time_mid (static_cast ((timestamp >> 32) & 0xFFFF)); - - ACE_UINT16 tHAV = static_cast ((timestamp >> 48) & 0xFFFF); - tHAV |= (version << 12); - uuid.time_hi_and_version (tHAV); - - u_char cseqHAV; - uuid.clock_seq_low (static_cast (clock_sequence & 0xFF)); - cseqHAV = static_cast ((clock_sequence & 0x3f00) >> 8); - uuid_state_.timestamp = timestamp; - - cseqHAV |= variant; - uuid.clock_seq_hi_and_reserved (cseqHAV); - uuid.node (uuid_state_.node); - - if (variant == 0xc0) - { - ACE_Thread_ID thread_id; - char buf [BUFSIZ]; - thread_id.to_string (buf); - uuid.thr_id (buf); - - ACE_OS::sprintf (buf, - "%d", - static_cast (ACE_OS::getpid ())); - uuid.pid (buf); - } - } - - UUID* - UUID_Generator::generate_UUID (ACE_UINT16 version, u_char variant) - { - UUID* uuid = 0; - ACE_NEW_RETURN (uuid, - UUID, - 0); - - this->generate_UUID (*uuid, version, variant); - return uuid; - } - - /// Obtain a new timestamp. If UUID's are being generated too quickly - /// the clock sequence will be incremented - void - UUID_Generator::get_timestamp (UUID_Time& timestamp) - { - ACE_GUARD (ACE_SYNCH_MUTEX, mon, *lock_); - - this->get_systemtime (timestamp); - - // Account for the clock being set back. Increment the clock / - // sequence. - if (timestamp <= time_last_) - { - uuid_state_.clock_sequence = static_cast - ((uuid_state_.clock_sequence + 1) & ACE_UUID_CLOCK_SEQ_MASK); - } - // If the system time ticked since the last UUID was - // generated. Set / the clock sequence back. - else if (timestamp > time_last_) - { - uuid_state_.clock_sequence = 0; - } - - time_last_ = timestamp; - } - - void - UUID_Generator::get_timestamp_and_clocksequence (UUID_Time& timestamp, - ACE_UINT16& clock_sequence) - { - ACE_GUARD (ACE_SYNCH_MUTEX, mon, *lock_); - - this->get_systemtime (timestamp); - - // Account for the clock being set back. Increment the clock / - // sequence. - if (timestamp <= time_last_) - uuid_state_.clock_sequence = static_cast ((uuid_state_.clock_sequence + 1) & ACE_UUID_CLOCK_SEQ_MASK); - - // If the system time ticked since the last UUID was - // generated. Set / the clock sequence back. - else if (timestamp > time_last_) - uuid_state_.clock_sequence = 0; - - time_last_ = timestamp; - clock_sequence = uuid_state_.clock_sequence; - } - - /** - * ACE_Time_Value is in POSIX time, seconds since Jan 1, 1970. UUIDs use - * time in 100ns ticks since 15 October 1582. The difference is: - * 15 Oct 1582 - 1 Jan 1600: 17 days in Oct, 30 in Nov, 31 in Dec + - * 17 years and 4 leap days (1584, 88, 92 and 96) - * 1 Jan 1600 - 1 Jan 1900: 3 centuries + 73 leap days ( 25 in 17th cent. - * and 24 each in 18th and 19th centuries) - * 1 Jan 1900 - 1 Jan 1970: 70 years + 17 leap days. - * This adds up, in days: (17+30+31+365*17+4)+ (365*300+73)+ (365*70+17) or - * 122192928000000000U (0x1B21DD213814000) 100 ns ticks. - */ - void - UUID_Generator::get_systemtime (UUID_Time & timestamp) - { - const UUID_Time timeOffset = -#if defined (ACE_LACKS_UNSIGNEDLONGLONG_T) - ACE_U_LongLong (ACE_INT64_LITERAL (0x1B21DD213814000)); -#elif defined (ACE_LACKS_LONGLONG_T) - ACE_U_LongLong (0x13814000u, 0x1B21DD2u); -#else - ACE_UINT64_LITERAL (0x1B21DD213814000); -#endif /* ACE_LACKS_UNSIGNEDLONGLONG_T */ - - /// Get the time of day, convert to 100ns ticks then add the offset. - ACE_Time_Value now = ACE_OS::gettimeofday (); - ACE_UINT64 time; - now.to_usec (time); - time = time * 10; - timestamp = time + timeOffset; - } - - ACE_SYNCH_MUTEX* - UUID_Generator::lock (void) - { - return this->lock_; - } - - void - UUID_Generator::lock (ACE_SYNCH_MUTEX* lock, bool release_lock) - { - if (this->destroy_lock_) - delete this->lock_; - - this->lock_ = lock; - this->destroy_lock_ = release_lock; - } -} - -#if defined (ACE_HAS_EXPLICIT_STATIC_TEMPLATE_MEMBER_INSTANTIATION) - template ACE_Singleton * - ACE_Singleton ::singleton_; -#endif /* ACE_HAS_EXPLICIT_STATIC_TEMPLATE_MEMBER_INSTANTIATION */ - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/UUID.h b/externals/ace/UUID.h deleted file mode 100644 index ae43c145dbb..00000000000 --- a/externals/ace/UUID.h +++ /dev/null @@ -1,282 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file UUID.h - * - * $Id: UUID.h 88604 2010-01-18 18:01:19Z hillj $ - * - * @author Andrew T. Finnel - * @author Yamuna Krishnmaurthy - */ -//============================================================================= - -#ifndef ACE_UUID_H -#define ACE_UUID_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Auto_Ptr.h" -#include "ace/SString.h" -#include "ace/Singleton.h" -#include "ace/Synch_Traits.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -namespace ACE_Utils -{ - /** - * @class UUID_Node - * - * @brief Holds the MAC-address of the UUID. - */ - class ACE_Export UUID_Node - { - public: - /// Size of the node in bytes. - enum {NODE_ID_SIZE = 6}; - - /// Type definition of the node. - typedef u_char Node_ID[NODE_ID_SIZE]; - - /// Get the node id - Node_ID & node_ID (void); - - /** - * @overload - */ - const Node_ID & node_ID (void) const; - - /// Test for equality. - bool operator == (const UUID_Node & right) const; - - /// Test for inequality. - bool operator != (const UUID_Node & right) const; - - private: - /// The value of the node id. - Node_ID node_ID_; - }; - - /** - * @class ACE_UUID - * - * ACE_UUID represents a Universally Unique IDentifier (UUID) as - * described in (the expired) INTERNET-DRAFT specification entitled - * UUIDs and GUIDs. All instances of UUID are of the time-based - * variety. That is, the version number part of the timeHiAndVersion - * field is 1. - * - * The default constructor creates a nil UUID. - * - * UUIDs have value semantics. In addition, they may be compared for - * ordering and equality. - * - * Additionally in this implementation provisions have been made to include - * process and thread ids to make the UUIDs more unique. The variant 0xc0 - * has been added to facilitate this. - */ - class ACE_Export UUID - { - public: - /// The size of a binary UUID. - enum { BINARY_SIZE = 16 }; - - /// Constructor - UUID (void); - - /// Constructs a UUID from a string representation. - UUID (const ACE_CString& uuidString); - - UUID (const UUID &right); - - // Destructor - ~UUID (void); - - ACE_UINT32 time_low (void) const; - void time_low (ACE_UINT32); - - ACE_UINT16 time_mid (void) const; - void time_mid (ACE_UINT16); - - ACE_UINT16 time_hi_and_version (void) const; - void time_hi_and_version (ACE_UINT16); - - u_char clock_seq_hi_and_reserved (void) const; - void clock_seq_hi_and_reserved (u_char); - - u_char clock_seq_low (void) const; - void clock_seq_low (u_char); - - UUID_Node & node (void); - const UUID_Node & node (void) const; - - void node (const UUID_Node & node); - - ACE_CString* thr_id (void); - void thr_id (char*); - - ACE_CString* pid (void); - void pid (char*); - - /// Returns a string representation of the UUID - const ACE_CString* to_string (void) const; - - /// Set the value using a string - void from_string (const ACE_CString& uuid_string); - - /// NIL UUID - static const UUID NIL_UUID; - - /// Equality Operations - bool operator == (const UUID &right) const; - bool operator != (const UUID &right) const; - - /// Compute a hash value for the UUID. - unsigned long hash (void) const; - - /// Assign an existing UUID to this UUID. - const UUID & operator = (const UUID & rhs); - - private: - /// Initialize the UUID - void init (void); - - /** - * Helper method to convert from a string UUID. - * - * @param[in] uuid_string String version of UUID. - */ - void from_string_i (const ACE_CString& uuid_string); - - /// Data Members for Class Attributes - struct data - { - /// Time low. - ACE_UINT32 time_low_; - - /// Time mid. - ACE_UINT16 time_mid_; - - /// Time high and version. - ACE_UINT16 time_hi_and_version_; - - /// Clock sequence high and reserved space. - u_char clock_seq_hi_and_reserved_; - - /// Clock sequence low. - u_char clock_seq_low_; - - /// MAC-address within the UUID. - UUID_Node node_; - } uuid_; - - ACE_CString thr_id_; - ACE_CString pid_; - - /// The string representation of the UUID. This is created and - /// updated only on demand. - mutable ACE_Auto_Ptr as_string_; - }; - - /** - * @class ACE_UUID_Generator - * - * Singleton class that generates UUIDs. - * - */ - class ACE_Export UUID_Generator - { - public: - - enum {ACE_UUID_CLOCK_SEQ_MASK = 0x3FFF}; - - /// Default constructor. - UUID_Generator(void); - - /// Destructor. - ~UUID_Generator(); - - /// Initialize the UUID generator - /// @deprecated This method may go away in some future release. - void init (void); - - /// Format timestamp, clockseq, and nodeID into an UUID of the - /// specified version and variant. For generating UUID's with - /// thread and process ids use variant=0xc0 - void generate_UUID (UUID&, ACE_UINT16 version=0x0001, u_char variant=0x80); - - /// Format timestamp, clockseq, and nodeID into a VI UUID. For - /// generating UUID's with thread and process ids use variant=0xc0 - UUID* generate_UUID (ACE_UINT16 version=0x0001, u_char variant=0x80); - - /// Type to represent UTC as a count of 100 nanosecond intervals - /// since 00:00:00.00, 15 October 1582. - typedef ACE_UINT64 UUID_Time; - - /// The locking strategy prevents multiple generators from accessing - /// the UUID_state at the same time. Get the locking strategy. - ACE_SYNCH_MUTEX* lock (void); - - /// Set a new locking strategy and return the old one. - void lock (ACE_SYNCH_MUTEX* lock, bool release_lock); - - private: - /// The system time when that last uuid was generated. - UUID_Time time_last_; - - /// Type to contain the UUID generator persistent state. This will - /// be kept in memory mapped shared memory - struct UUID_State - { - UUID_Time timestamp; - UUID_Node node; - ACE_UINT16 clock_sequence; - }; - - /// Obtain a UUID timestamp. Compensate for the fact that the time - /// obtained from getSystem time has a resolution less than 100ns. - void get_timestamp (UUID_Time& timestamp); - - /// Obtain a UUID timestamp and clock sequence. Compensate for the - /// fact that the time obtained from getSystem time has a - /// resolution less than 100ns. - void get_timestamp_and_clocksequence (UUID_Time& timestamp, - ACE_UINT16& clockSequence); - - /// Obtain the system time in UTC as a count of 100 nanosecond intervals - /// since 00:00:00.00, 15 October 1582 (the date of Gregorian reform to - /// the Christian calendar). - void get_systemtime( UUID_Time& timeNow); - - /// The UUID generator persistent state. - UUID_State uuid_state_; - - ACE_SYNCH_MUTEX* lock_; - - bool destroy_lock_; - - /// Initalization state of the generator. - bool is_init_; - }; - - typedef ACE_Singleton - UUID_GENERATOR; -} - -ACE_SINGLETON_DECLARE (ACE_Singleton, ACE_Utils::UUID_Generator, ACE_SYNCH_MUTEX) - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/UUID.inl" -#endif /* __ACE_INLINE__ */ - -#include /**/ "ace/post.h" -#endif // ACE_UUID_H - diff --git a/externals/ace/UUID.inl b/externals/ace/UUID.inl deleted file mode 100644 index 568adfa00d0..00000000000 --- a/externals/ace/UUID.inl +++ /dev/null @@ -1,204 +0,0 @@ -// -*- C++ -*- -// -//$Id: UUID.inl 85331 2009-05-14 00:04:12Z hillj $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -namespace ACE_Utils -{ - ACE_INLINE - const UUID_Node::Node_ID & UUID_Node::node_ID (void) const - { - return this->node_ID_; - } - - ACE_INLINE - UUID_Node::Node_ID & UUID_Node::node_ID (void) - { - return this->node_ID_; - } - - ACE_INLINE - UUID::UUID (void) - { - this->init (); - } - - ACE_INLINE - UUID::UUID (const UUID &right) - : thr_id_ (right.thr_id_), - pid_ (right.pid_) - { - ACE_OS::memcpy (&this->uuid_, &right.uuid_, BINARY_SIZE); - } - - ACE_INLINE - UUID::~UUID (void) - { - - } - - ACE_INLINE void - UUID::init (void) - { - ACE_OS::memset (&this->uuid_, 0, BINARY_SIZE); - } - - ACE_INLINE unsigned long - UUID::hash (void) const - { - return ACE::hash_pjw (reinterpret_cast (&this->uuid_), - UUID::BINARY_SIZE); - } - - ACE_INLINE ACE_UINT32 - UUID::time_low (void) const - { - return this->uuid_.time_low_; - } - - ACE_INLINE void - UUID::time_low (ACE_UINT32 timelow) - { - this->uuid_.time_low_ = timelow; - } - - ACE_INLINE ACE_UINT16 - UUID::time_mid (void) const - { - return this->uuid_.time_mid_; - } - - ACE_INLINE void - UUID::time_mid (ACE_UINT16 time_mid) - { - this->uuid_.time_mid_ = time_mid; - } - - ACE_INLINE ACE_UINT16 - UUID::time_hi_and_version (void) const - { - return this->uuid_.time_hi_and_version_; - } - - ACE_INLINE void - UUID::time_hi_and_version (ACE_UINT16 time_hi_and_version) - { - this->uuid_.time_hi_and_version_ = time_hi_and_version; - } - - ACE_INLINE u_char - UUID::clock_seq_hi_and_reserved (void) const - { - return this->uuid_.clock_seq_hi_and_reserved_; - } - - ACE_INLINE void - UUID::clock_seq_hi_and_reserved (u_char clock_seq_hi_and_reserved) - { - this->uuid_.clock_seq_hi_and_reserved_ = clock_seq_hi_and_reserved; - } - - ACE_INLINE u_char - UUID::clock_seq_low (void) const - { - return this->uuid_.clock_seq_low_; - } - - ACE_INLINE void - UUID::clock_seq_low (u_char clock_seq_low) - { - this->uuid_.clock_seq_low_ = clock_seq_low; - } - - ACE_INLINE const UUID_Node & - UUID::node (void) const - { - return this->uuid_.node_; - } - - ACE_INLINE UUID_Node & - UUID::node (void) - { - return this->uuid_.node_; - } - - ACE_INLINE void - UUID::node (const UUID_Node & node) - { - ACE_OS::memcpy (&this->uuid_.node_, - node.node_ID (), - UUID_Node::NODE_ID_SIZE); - } - - ACE_INLINE ACE_CString* - UUID::thr_id (void) - { - return &this->thr_id_; - } - - ACE_INLINE void - UUID::thr_id (char* thr_id) - { - this->thr_id_ = thr_id; - } - - ACE_INLINE ACE_CString* - UUID::pid (void) - { - return &this->pid_; - } - - ACE_INLINE void - UUID::pid (char* pid) - { - this->pid_ = pid; - } - - ACE_INLINE void - UUID::from_string (const ACE_CString& uuidString) - { - this->from_string_i (uuidString); - } - - ACE_INLINE bool - UUID::operator == (const UUID &right) const - { - return 0 == ACE_OS::memcmp (&this->uuid_, &right.uuid_, BINARY_SIZE); - } - - ACE_INLINE bool - UUID::operator != (const UUID &right) const - { - return 0 != ACE_OS::memcmp (&this->uuid_, &right.uuid_, BINARY_SIZE); - } - - ACE_INLINE bool - UUID_Node::operator == (const UUID_Node& rt) const - { - for (size_t i = 0; i < NODE_ID_SIZE; ++i) - if (node_ID_ [i] != rt.node_ID_ [i]) - return false; - - return true; - } - - ACE_INLINE bool - UUID_Node::operator != (const UUID_Node& right) const - { - return !(*this == right); - } - -// ACE_INLINE bool -// UUID_node::operator < (const UUID_node& rt) const -// { -// UUID_node right = rt; -// for (size_t i = 0; i < NODE_ID_SIZE; ++i) -// if (nodeID_ [i] < right.nodeID ()[i]) -// return true; -// -// return false; -// } -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Unbounded_Queue.cpp b/externals/ace/Unbounded_Queue.cpp deleted file mode 100644 index 2890650fbe1..00000000000 --- a/externals/ace/Unbounded_Queue.cpp +++ /dev/null @@ -1,433 +0,0 @@ -// $Id: Unbounded_Queue.cpp 82723 2008-09-16 09:35:44Z johnnyw $ - -#ifndef ACE_UNBOUNDED_QUEUE_CPP -#define ACE_UNBOUNDED_QUEUE_CPP - -#include "ace/Unbounded_Queue.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (__ACE_INLINE__) -#include "ace/Unbounded_Queue.inl" -#endif /* __ACE_INLINE__ */ - -#include "ace/Malloc_Base.h" -#include "ace/Log_Msg.h" -#include "ace/os_include/os_errno.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Unbounded_Queue) - -template -ACE_Unbounded_Queue::ACE_Unbounded_Queue (ACE_Allocator *alloc) - : head_ (0), - cur_size_ (0), - allocator_ (alloc) -{ - // ACE_TRACE ("ACE_Unbounded_Queue::ACE_Unbounded_Queue (void)"); - - if (this->allocator_ == 0) - this->allocator_ = ACE_Allocator::instance (); - - ACE_NEW_MALLOC (this->head_, - (ACE_Node *) this->allocator_->malloc (sizeof (ACE_Node)), - ACE_Node); - // Make the list circular by pointing it back to itself. - this->head_->next_ = this->head_; -} - -template -ACE_Unbounded_Queue::ACE_Unbounded_Queue (const ACE_Unbounded_Queue &us) - : head_ (0), - cur_size_ (0), - allocator_ (us.allocator_) -{ - // ACE_TRACE ("ACE_Unbounded_Queue::ACE_Unbounded_Queue"); - - if (this->allocator_ == 0) - this->allocator_ = ACE_Allocator::instance (); - - ACE_NEW_MALLOC (this->head_, - (ACE_Node *) this->allocator_->malloc (sizeof (ACE_Node)), - ACE_Node); - this->head_->next_ = this->head_; - this->copy_nodes (us); -} - -template void -ACE_Unbounded_Queue::operator= (const ACE_Unbounded_Queue &us) -{ - // ACE_TRACE ("ACE_Unbounded_Queue::operator="); - - if (this != &us) - { - this->delete_nodes (); - this->copy_nodes (us); - } -} - -template ACE_Unbounded_Queue_Iterator -ACE_Unbounded_Queue::begin (void) -{ - // ACE_TRACE ("ACE_Unbounded_Queue::begin"); - return ACE_Unbounded_Queue_Iterator (*this); -} - -template ACE_Unbounded_Queue_Iterator -ACE_Unbounded_Queue::end (void) -{ - // ACE_TRACE ("ACE_Unbounded_Queue::end"); - return ACE_Unbounded_Queue_Iterator (*this, 1); -} - -template void -ACE_Unbounded_Queue::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - // ACE_TRACE ("ACE_Unbounded_Queue::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nhead_ = %u"), this->head_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nhead_->next_ = %u"), this->head_->next_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ncur_size_ = %d\n"), this->cur_size_)); - - T *item = 0; -#if !defined (ACE_NLOGGING) - size_t count = 1; -#endif /* ! ACE_NLOGGING */ - - for (ACE_Unbounded_Queue_Iterator iter (*(ACE_Unbounded_Queue *) this); - iter.next (item) != 0; - iter.advance ()) - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("count = %d\n"), count++)); - - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -template void -ACE_Unbounded_Queue::copy_nodes (const ACE_Unbounded_Queue &us) -{ - for (ACE_Node *curr = us.head_->next_; - curr != us.head_; - curr = curr->next_) - if (this->enqueue_tail (curr->item_) == -1) - // @@ What's the right thing to do here? - this->delete_nodes (); -} - -template void -ACE_Unbounded_Queue::delete_nodes (void) -{ - for (ACE_Node *curr = this->head_->next_; - // Keep looking until we've hit the dummy node. - curr != this->head_; - ) - { - ACE_Node *temp = curr; - curr = curr->next_; - - ACE_DES_FREE_TEMPLATE (temp, - this->allocator_->free, - ACE_Node, - ); - --this->cur_size_; - // @@ Doesnt make sense to have this check since - // this will always be true. - // ACE_ASSERT (this->cur_size_ >= 0); - } - - // Reset the list to be a circular list with just a dummy node. - this->head_->next_ = this->head_; -} - -template -ACE_Unbounded_Queue::~ACE_Unbounded_Queue (void) -{ - // ACE_TRACE ("ACE_Unbounded_Queue::~ACE_Unbounded_Queue (void)"); - - this->delete_nodes (); - ACE_DES_FREE_TEMPLATE (head_, - this->allocator_->free, - ACE_Node, - ); -} - -template int -ACE_Unbounded_Queue::enqueue_head (const T &new_item) -{ - // ACE_TRACE ("ACE_Unbounded_Queue::enqueue_head"); - - ACE_Node *temp = 0; - - // Create a new node that points to the original head. - ACE_NEW_MALLOC_RETURN (temp, - static_cast *> (this->allocator_->malloc (sizeof (ACE_Node))), - ACE_Node (new_item, this->head_->next_), - -1); - // Link this pointer into the front of the list. Note that the - // "real" head of the queue is next_>, whereas is - // just a pointer to the dummy node. - this->head_->next_ = temp; - - ++this->cur_size_; - return 0; -} - -template int -ACE_Unbounded_Queue::enqueue_tail (const T &new_item) -{ - // ACE_TRACE ("ACE_Unbounded_Queue::enqueue_tail"); - - // Insert into the old dummy node location. Note that this - // isn't actually the "head" item in the queue, it's a dummy node at - // the "tail" of the queue... - this->head_->item_ = new_item; - - ACE_Node *temp = 0; - - // Create a new dummy node. - ACE_NEW_MALLOC_RETURN (temp, - static_cast *> (this->allocator_->malloc (sizeof (ACE_Node))), - ACE_Node (this->head_->next_), - -1); - // Link this dummy pointer into the list. - this->head_->next_ = temp; - - // Point the head to the new dummy node. - this->head_ = temp; - - ++this->cur_size_; - return 0; -} - -template int -ACE_Unbounded_Queue::dequeue_head (T &item) -{ - // ACE_TRACE ("ACE_Unbounded_Queue::dequeue_head"); - - // Check for empty queue. - if (this->is_empty ()) - return -1; - - ACE_Node *temp = this->head_->next_; - - item = temp->item_; - this->head_->next_ = temp->next_; - ACE_DES_FREE_TEMPLATE (temp, - this->allocator_->free, - ACE_Node, - ); - --this->cur_size_; - return 0; -} - -template void -ACE_Unbounded_Queue::reset (void) -{ - ACE_TRACE ("reset"); - - this->delete_nodes (); -} - -template int -ACE_Unbounded_Queue::get (T *&item, size_t slot) const -{ - // ACE_TRACE ("ACE_Unbounded_Queue::get"); - - ACE_Node *curr = this->head_->next_; - - size_t i; - - for (i = 0; i < this->cur_size_; i++) - { - if (i == slot) - break; - - curr = curr->next_; - } - - if (i < this->cur_size_) - { - item = &curr->item_; - return 0; - } - else - return -1; -} - -template int -ACE_Unbounded_Queue::set (const T &item, - size_t slot) -{ - // ACE_TRACE ("ACE_Unbounded_Queue::set"); - - ACE_Node *curr = this->head_->next_; - - size_t i; - - for (i = 0; - i < slot && i < this->cur_size_; - ++i) - curr = curr->next_; - - if (i < this->cur_size_) - { - // We're in range, so everything's cool. - curr->item_ = item; - return 0; - } - else - { - // We need to expand the list. - - // A common case will be increasing the set size by 1. - // Therefore, we'll optimize for this case. - if (i == slot) - { - // Try to expand the size of the set by 1. - if (this->enqueue_tail (item) == -1) - return -1; - else - return 0; - } - else - { - T const dummy = T (); - - // We need to expand the list by multiple (dummy) items. - for (; i < slot; ++i) - { - // This head points to the existing dummy node, which is - // about to be overwritten when we add the new dummy - // node. - curr = this->head_; - - // Try to expand the size of the set by 1, but don't - // store anything in the dummy node (yet). - if (this->enqueue_tail (dummy) == -1) - return -1; - } - - curr->item_ = item; - return 0; - } - } -} - -// **************************************************************** - -template void -ACE_Unbounded_Queue_Const_Iterator::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - // ACE_TRACE ("ACE_Unbounded_Queue_Const_Iterator::dump"); -#endif /* ACE_HAS_DUMP */ -} - -template -ACE_Unbounded_Queue_Const_Iterator::ACE_Unbounded_Queue_Const_Iterator (const ACE_Unbounded_Queue &q, int end) - : current_ (end == 0 ? q.head_->next_ : q.head_ ), - queue_ (q) -{ - // ACE_TRACE ("ACE_Unbounded_Queue_Const_Iterator::ACE_Unbounded_Queue_Const_Iterator"); -} - -template int -ACE_Unbounded_Queue_Const_Iterator::advance (void) -{ - // ACE_TRACE ("ACE_Unbounded_Queue_Const_Iterator::advance"); - this->current_ = this->current_->next_; - return this->current_ != this->queue_.head_; -} - -template int -ACE_Unbounded_Queue_Const_Iterator::first (void) -{ - // ACE_TRACE ("ACE_Unbounded_Queue_Const_Iterator::first"); - this->current_ = this->queue_.head_->next_; - return this->current_ != this->queue_.head_; -} - -template int -ACE_Unbounded_Queue_Const_Iterator::done (void) const -{ - ACE_TRACE ("ACE_Unbounded_Queue_Const_Iterator::done"); - - return this->current_ == this->queue_.head_; -} - -template int -ACE_Unbounded_Queue_Const_Iterator::next (T *&item) -{ - // ACE_TRACE ("ACE_Unbounded_Queue_Const_Iterator::next"); - if (this->current_ == this->queue_.head_) - return 0; - else - { - item = &this->current_->item_; - return 1; - } -} - -// **************************************************************** - -template void -ACE_Unbounded_Queue_Iterator::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - // ACE_TRACE ("ACE_Unbounded_Queue_Iterator::dump"); -#endif /* ACE_HAS_DUMP */ -} - -template -ACE_Unbounded_Queue_Iterator::ACE_Unbounded_Queue_Iterator (ACE_Unbounded_Queue &q, int end) - : current_ (end == 0 ? q.head_->next_ : q.head_ ), - queue_ (q) -{ - // ACE_TRACE ("ACE_Unbounded_Queue_Iterator::ACE_Unbounded_Queue_Iterator"); -} - -template int -ACE_Unbounded_Queue_Iterator::advance (void) -{ - // ACE_TRACE ("ACE_Unbounded_Queue_Iterator::advance"); - this->current_ = this->current_->next_; - return this->current_ != this->queue_.head_; -} - -template int -ACE_Unbounded_Queue_Iterator::first (void) -{ - // ACE_TRACE ("ACE_Unbounded_Queue_Iterator::first"); - this->current_ = this->queue_.head_->next_; - return this->current_ != this->queue_.head_; -} - -template int -ACE_Unbounded_Queue_Iterator::done (void) const -{ - ACE_TRACE ("ACE_Unbounded_Queue_Iterator::done"); - - return this->current_ == this->queue_.head_; -} - -template int -ACE_Unbounded_Queue_Iterator::next (T *&item) -{ - // ACE_TRACE ("ACE_Unbounded_Queue_Iterator::next"); - if (this->current_ == this->queue_.head_) - return 0; - else - { - item = &this->current_->item_; - return 1; - } -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_UNBOUNDED_QUEUE_CPP */ diff --git a/externals/ace/Unbounded_Queue.h b/externals/ace/Unbounded_Queue.h deleted file mode 100644 index 65be7aaaec6..00000000000 --- a/externals/ace/Unbounded_Queue.h +++ /dev/null @@ -1,297 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Unbounded_Queue.h - * - * $Id: Unbounded_Queue.h 84316 2009-02-03 19:46:05Z johnnyw $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_UNBOUNDED_QUEUE_H -#define ACE_UNBOUNDED_QUEUE_H -#include /**/ "ace/pre.h" - -#include "ace/Node.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/os_stddef.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -class ACE_Allocator; - -template -class ACE_Unbounded_Queue; - -/** - * @class ACE_Unbounded_Queue_Iterator - * - * @brief Implement an iterator over an unbounded queue. - */ -template -class ACE_Unbounded_Queue_Iterator -{ -public: - // = Initialization method. - ACE_Unbounded_Queue_Iterator (ACE_Unbounded_Queue &q, int end = 0); - - // = Iteration methods. - - /// Pass back the @a next_item that hasn't been seen in the queue. - /// Returns 0 when all items have been seen, else 1. - int next (T *&next_item); - - /// Move forward by one element in the set. Returns 0 when all the - /// items in the queue have been seen, else 1. - int advance (void); - - /// Move to the first element in the queue. Returns 0 if the - /// queue is empty, else 1. - int first (void); - - /// Returns 1 when all items have been seen, else 0. - int done (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - /// Pointer to the current node in the iteration. - ACE_Node *current_; - - /// Pointer to the queue we're iterating over. - ACE_Unbounded_Queue &queue_; -}; - -/** - * @class ACE_Unbounded_Queue_Const_Iterator - * - * @brief Implement an iterator over an const unbounded queue. - */ -template -class ACE_Unbounded_Queue_Const_Iterator -{ -public: - // = Initialization method. - ACE_Unbounded_Queue_Const_Iterator (const ACE_Unbounded_Queue &q, int end = 0); - - // = Iteration methods. - - /// Pass back the @a next_item that hasn't been seen in the queue. - /// Returns 0 when all items have been seen, else 1. - int next (T *&next_item); - - /// Move forward by one element in the set. Returns 0 when all the - /// items in the queue have been seen, else 1. - int advance (void); - - /// Move to the first element in the queue. Returns 0 if the - /// queue is empty, else 1. - int first (void); - - /// Returns 1 when all items have been seen, else 0. - int done (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - /// Pointer to the current node in the iteration. - ACE_Node *current_; - - /// Pointer to the queue we're iterating over. - const ACE_Unbounded_Queue &queue_; -}; - -/** - * @class ACE_Unbounded_Queue - * - * @brief A Queue of "infinite" length. - * - * This implementation of an unbounded queue uses a circular - * linked list with a dummy node. - * - * Requirements and Performance Characteristics - * - Internal Structure - * Circular linked list - * - Duplicates allowed? - * Yes - * - Random access allowed? - * No - * - Search speed - * N/A - * - Insert/replace speed - * N/A - * - Iterator still valid after change to container? - * Yes - * - Frees memory for removed elements? - * Yes - * - Items inserted by - * Value - * - Requirements for contained type - * -# Default constructor - * -# Copy constructor - * -# operator= - * - */ -template -class ACE_Unbounded_Queue -{ -public: - friend class ACE_Unbounded_Queue_Iterator; - friend class ACE_Unbounded_Queue_Const_Iterator; - - // Trait definition. - typedef ACE_Unbounded_Queue_Iterator ITERATOR; - typedef ACE_Unbounded_Queue_Const_Iterator CONST_ITERATOR; - - // = Initialization and termination methods. - /// Construction. Use user specified allocation strategy - /// if specified. - /** - * Initialize an empty queue using the strategy provided. - */ - ACE_Unbounded_Queue (ACE_Allocator *alloc = 0); - - /// Copy constructor. - /** - * Initialize the queue to be a copy of the provided queue. - */ - ACE_Unbounded_Queue (const ACE_Unbounded_Queue &); - - /// Assignment operator. - /** - * Perform a deep copy of rhs. - */ - void operator= (const ACE_Unbounded_Queue &); - - /// Destructor. - /** - * Clean up the memory for the queue. - */ - ~ACE_Unbounded_Queue (void); - - // = Check boundary conditions. - - /// Returns true if the container is empty, otherwise returns false. - /** - * Constant time check to see if the queue is empty. - */ - bool is_empty (void) const; - - /// Returns 0. - /** - * The queue cannot be full, so it always returns 0. - */ - bool is_full (void) const; - - // = Classic queue operations. - - /// Adds @a new_item to the tail of the queue. Returns 0 on success, - /// -1 on failure. - /** - * Insert an item at the end of the queue. - */ - int enqueue_tail (const T &new_item); - - /// Adds @a new_item to the head of the queue. Returns 0 on success, - /// -1 on failure. - /** - * Insert an item at the head of the queue. - */ - int enqueue_head (const T &new_item); - - /// Removes and returns the first @a item on the queue. Returns 0 on - /// success, -1 if the queue was empty. - /** - * Remove an item from the head of the queue. - */ - int dequeue_head (T &item); - - // = Additional utility methods. - - /// Reset the ACE_Unbounded_Queue to be empty and release all its - /// dynamically allocated resources. - /** - * Delete the queue nodes. - */ - void reset (void); - - /// Get the @a slot th element in the set. Returns -1 if the element - /// isn't in the range {0..#cur_size_ - 1}, else 0. - /** - * Find the item in the queue between 0 and the provided index of the - * queue. - */ - int get (T *&item, size_t slot = 0) const; - - /// Set the @a slot th element of the queue to @a item. - /** - * Set the @a slot th element in the set. Will pad out the set with - * empty nodes if @a slot is beyond the range {0..#cur_size_ - 1}. - * Returns -1 on failure, 0 if @a slot isn't initially in range, and - * 0 otherwise. - */ - int set (const T &item, size_t slot); - - /// The number of items in the queue. - /** - * Return the size of the queue. - */ - size_t size (void) const; - - /// Dump the state of an object. - void dump (void) const; - - // = STL-styled unidirectional iterator factory. - ACE_Unbounded_Queue_Iterator begin (void); - ACE_Unbounded_Queue_Iterator end (void); - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -protected: - /// Delete all the nodes in the queue. - void delete_nodes (void); - - /// Copy nodes into this queue. - void copy_nodes (const ACE_Unbounded_Queue &); - - /// Pointer to the dummy node in the circular linked Queue. - ACE_Node *head_; - - /// Current size of the queue. - size_t cur_size_; - - /// Allocation Strategy of the queue. - ACE_Allocator *allocator_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Unbounded_Queue.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Unbounded_Queue.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Unbounded_Queue.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" -#endif /* ACE_UNBOUNDED_QUEUE_H */ diff --git a/externals/ace/Unbounded_Queue.inl b/externals/ace/Unbounded_Queue.inl deleted file mode 100644 index 81e3ded3e04..00000000000 --- a/externals/ace/Unbounded_Queue.inl +++ /dev/null @@ -1,27 +0,0 @@ -// -*- C++ -*- -// -// $Id: Unbounded_Queue.inl 84316 2009-02-03 19:46:05Z johnnyw $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template ACE_INLINE size_t -ACE_Unbounded_Queue::size (void) const -{ - return this->cur_size_; -} - -template ACE_INLINE bool -ACE_Unbounded_Queue::is_empty (void) const -{ - // ACE_TRACE ("ACE_Unbounded_Queue::is_empty"); - return this->head_ == this->head_->next_; -} - -template ACE_INLINE bool -ACE_Unbounded_Queue::is_full (void) const -{ - // ACE_TRACE ("ACE_Unbounded_Queue::is_full"); - return false; // We should implement a "node of last resort for this..." -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Unbounded_Set.cpp b/externals/ace/Unbounded_Set.cpp deleted file mode 100644 index c54e3fcfa2f..00000000000 --- a/externals/ace/Unbounded_Set.cpp +++ /dev/null @@ -1,18 +0,0 @@ -// $Id: Unbounded_Set.cpp 81624 2008-05-06 17:14:57Z wotte $ - -#ifndef ACE_UNBOUNDED_SET_CPP -#define ACE_UNBOUNDED_SET_CPP - -#include "ace/Unbounded_Set.h" -#include "ace/Malloc_Base.h" -#include "ace/Log_Msg.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (__ACE_INLINE__) -#include "ace/Unbounded_Set.inl" -#endif /* __ACE_INLINE__ */ - -#endif /* ACE_UNBOUNDED_SET_CPP */ diff --git a/externals/ace/Unbounded_Set.h b/externals/ace/Unbounded_Set.h deleted file mode 100644 index a75eac18fc3..00000000000 --- a/externals/ace/Unbounded_Set.h +++ /dev/null @@ -1,103 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Unbounded_Set.h - * - * $Id: Unbounded_Set.h 81642 2008-05-07 19:30:35Z shuston $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_UNBOUNDED_SET_H -#define ACE_UNBOUNDED_SET_H -#include /**/ "ace/pre.h" - -#include "ace/Unbounded_Set_Ex.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -class ACE_Allocator; - -/** - * @struct ACE_Unbounded_Set_Default_Comparator - * @brief Simple comparator that evaluates equality using == operator. - */ -template -struct ACE_Unbounded_Set_Default_Comparator -{ - bool operator() (const T&lhs, const T&rhs) const; -}; - -template -class ACE_Unbounded_Set; - -/** - * @class ACE_Unbounded_Set_Iterator - * @brief Compatibility wrapper for ACE_Unbounded_Set_Ex_Iterator. - */ -template -class ACE_Unbounded_Set_Iterator : public - ACE_Unbounded_Set_Ex_Iterator > -{ -public: - typedef ACE_Unbounded_Set_Ex_Iterator > base_type; - - // = Initialization method. - ACE_Unbounded_Set_Iterator (ACE_Unbounded_Set &s, bool end = false); - - ACE_Unbounded_Set_Iterator (const base_type &s); -}; - -/** - * @class ACE_Unbounded_Set_Const_Iterator - * @brief Compatibility wrapper for ACE_Unbounded_Set_Ex_Const_Iterator. - */ -template -class ACE_Unbounded_Set_Const_Iterator : public - ACE_Unbounded_Set_Ex_Const_Iterator > -{ -public: - - typedef ACE_Unbounded_Set_Ex_Const_Iterator > base_type; - - // = Initialization method. - ACE_Unbounded_Set_Const_Iterator (const ACE_Unbounded_Set &s, - bool end = false); - - ACE_Unbounded_Set_Const_Iterator (const base_type &s); -}; - -/** - * @class ACE_Unbounded_Set - * @brief Compatibility wrapper for ACE_Unbounded_Set_Ex. - */ -template -class ACE_Unbounded_Set : public - ACE_Unbounded_Set_Ex > -{ -public: - ACE_Unbounded_Set (ACE_Allocator *alloc = 0); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Unbounded_Set.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Unbounded_Set.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Unbounded_Set.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" -#endif /* ACE_UNBOUNDED_SET_H */ diff --git a/externals/ace/Unbounded_Set.inl b/externals/ace/Unbounded_Set.inl deleted file mode 100644 index 365b025c0be..00000000000 --- a/externals/ace/Unbounded_Set.inl +++ /dev/null @@ -1,49 +0,0 @@ -// -*- C++ -*- -// -// $Id: Unbounded_Set.inl 81642 2008-05-07 19:30:35Z shuston $ - -#include "ace/Global_Macros.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template ACE_INLINE bool -ACE_Unbounded_Set_Default_Comparator::operator () (const T &lhs, const T &rhs) const -{ - return lhs == rhs; -} - -template -ACE_Unbounded_Set_Iterator::ACE_Unbounded_Set_Iterator (ACE_Unbounded_Set &s, - bool end) - : base_type (s, end) -{ -} - -template -ACE_Unbounded_Set_Iterator::ACE_Unbounded_Set_Iterator (const base_type & s) - : base_type (s) -{ -} - -template -ACE_Unbounded_Set_Const_Iterator:: -ACE_Unbounded_Set_Const_Iterator (const ACE_Unbounded_Set &s, - bool end) - : base_type (s, end) -{ -} - -template -ACE_Unbounded_Set_Const_Iterator::ACE_Unbounded_Set_Const_Iterator (const base_type & s) - : base_type (s) -{ -} - -template -ACE_Unbounded_Set::ACE_Unbounded_Set (ACE_Allocator *alloc) - : ACE_Unbounded_Set_Ex > (alloc) -{ -} - - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Unbounded_Set_Ex.cpp b/externals/ace/Unbounded_Set_Ex.cpp deleted file mode 100644 index c5cd9e27b21..00000000000 --- a/externals/ace/Unbounded_Set_Ex.cpp +++ /dev/null @@ -1,499 +0,0 @@ -// $Id: Unbounded_Set_Ex.cpp 81702 2008-05-15 10:18:07Z johnnyw $ - -#ifndef ACE_UNBOUNDED_SET_EX_CPP -#define ACE_UNBOUNDED_SET_EX_CPP - -#include "ace/Unbounded_Set.h" -#include "ace/Malloc_Base.h" -#include "ace/Log_Msg.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (__ACE_INLINE__) -#include "ace/Unbounded_Set_Ex.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Unbounded_Set_Ex) - -template size_t -ACE_Unbounded_Set_Ex::size (void) const -{ - // ACE_TRACE ("ACE_Unbounded_Set_Ex::size"); - return this->cur_size_; -} - -template int -ACE_Unbounded_Set_Ex::insert_tail (const T &item) -{ - // ACE_TRACE ("ACE_Unbounded_Set_Ex::insert_tail"); - NODE *temp = 0; - - // Insert into the old dummy node location. - this->head_->item_ = item; - - // Create a new dummy node. - ACE_NEW_MALLOC_RETURN (temp, - static_cast (this->allocator_->malloc (sizeof (NODE))), - NODE (this->head_->next_), - -1); - // Link this pointer into the list. - this->head_->next_ = temp; - - // Point the head to the new dummy node. - this->head_ = temp; - - ++this->cur_size_; - return 0; -} - -template void -ACE_Unbounded_Set_Ex::reset (void) -{ - ACE_TRACE ("reset"); - - this->delete_nodes (); -} - -template void -ACE_Unbounded_Set_Ex::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_Unbounded_Set_Ex::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nhead_ = %u"), this->head_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nhead_->next_ = %u"), this->head_->next_)); - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ncur_size_ = %d\n"), this->cur_size_)); - - T *item = 0; -#if !defined (ACE_NLOGGING) - size_t count = 1; -#endif /* ! ACE_NLOGGING */ - - const_iterator const the_end = this->end (); - for (const_iterator i (this->begin ()); - i != end; - ++i) - ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("count = %u\n"), count++)); - - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -template void -ACE_Unbounded_Set_Ex::copy_nodes (const ACE_Unbounded_Set_Ex &us) -{ - for (NODE *curr = us.head_->next_; - curr != us.head_; - curr = curr->next_) - this->insert_tail (curr->item_); -} - -template void -ACE_Unbounded_Set_Ex::delete_nodes (void) -{ - NODE *curr = this->head_->next_; - - // Keep looking until we've hit the dummy node. - - while (curr != this->head_) - { - NODE *temp = curr; - curr = curr->next_; - ACE_DES_FREE_TEMPLATE2 (temp, - this->allocator_->free, - ACE_Node, - T, C); - --this->cur_size_; - } - - // Reset the list to be a circular list with just a dummy node. - this->head_->next_ = this->head_; -} - -template -ACE_Unbounded_Set_Ex::~ACE_Unbounded_Set_Ex (void) -{ - // ACE_TRACE ("ACE_Unbounded_Set_Ex::~ACE_Unbounded_Set_Ex"); - - this->delete_nodes (); - - // Delete the dummy node. - ACE_DES_FREE_TEMPLATE2 (head_, - this->allocator_->free, - ACE_Node, - T, C); - this->head_ = 0; -} - -template -ACE_Unbounded_Set_Ex::ACE_Unbounded_Set_Ex (ACE_Allocator *alloc) - : head_ (0), - cur_size_ (0), - allocator_ (alloc) -{ - // ACE_TRACE ("ACE_Unbounded_Set_Ex::ACE_Unbounded_Set_Ex"); - - if (this->allocator_ == 0) - this->allocator_ = ACE_Allocator::instance (); - - ACE_NEW_MALLOC (this->head_, - (NODE*) this->allocator_->malloc (sizeof (NODE)), - NODE); - // Make the list circular by pointing it back to itself. - this->head_->next_ = this->head_; -} - -template -ACE_Unbounded_Set_Ex::ACE_Unbounded_Set_Ex (const C &comp, - ACE_Allocator *alloc) - : head_ (0), - cur_size_ (0), - allocator_ (alloc), - comp_ (comp) -{ - // ACE_TRACE ("ACE_Unbounded_Set_Ex::ACE_Unbounded_Set_Ex"); - - if (this->allocator_ == 0) - this->allocator_ = ACE_Allocator::instance (); - - ACE_NEW_MALLOC (this->head_, - (NODE*) this->allocator_->malloc (sizeof (NODE)), - NODE); - // Make the list circular by pointing it back to itself. - this->head_->next_ = this->head_; -} - -template -ACE_Unbounded_Set_Ex::ACE_Unbounded_Set_Ex (const ACE_Unbounded_Set_Ex &us) - : head_ (0), - cur_size_ (0), - allocator_ (us.allocator_), - comp_ (us.comp_) -{ - ACE_TRACE ("ACE_Unbounded_Set_Ex::ACE_Unbounded_Set_Ex"); - - if (this->allocator_ == 0) - this->allocator_ = ACE_Allocator::instance (); - - ACE_NEW_MALLOC (this->head_, - (NODE*) this->allocator_->malloc (sizeof (NODE)), - NODE); - this->head_->next_ = this->head_; - this->copy_nodes (us); -} - -template ACE_Unbounded_Set_Ex & -ACE_Unbounded_Set_Ex::operator= (const ACE_Unbounded_Set_Ex &us) -{ - ACE_TRACE ("ACE_Unbounded_Set_Ex::operator="); - - if (this != &us) - { - this->delete_nodes (); - this->copy_nodes (us); - } - - return *this; -} - -template int -ACE_Unbounded_Set_Ex::find (const T &item) const -{ - // ACE_TRACE ("ACE_Unbounded_Set_Ex::find"); - const_iterator const the_end = this->end (); - for (const_iterator i = this->begin (); i != the_end; ++i) - if (this->comp_(*i, item)) - return 0; - - return -1; -} - -template int -ACE_Unbounded_Set_Ex::insert (const T &item) -{ - // ACE_TRACE ("ACE_Unbounded_Set_Ex::insert"); - if (this->find (item) == 0) - return 1; - else - return this->insert_tail (item); -} - -template int -ACE_Unbounded_Set_Ex::remove (const T &item) -{ - // ACE_TRACE ("ACE_Unbounded_Set_Ex::remove"); - - // Insert the item to be founded into the dummy node. - this->head_->item_ = item; - - NODE *curr = this->head_; - - while (!(this->comp_ (curr->next_->item_, item))) - curr = curr->next_; - - if (curr->next_ == this->head_) - return -1; // Item was not found. - else - { - NODE *temp = curr->next_; - // Skip over the node that we're deleting. - curr->next_ = temp->next_; - --this->cur_size_; - ACE_DES_FREE_TEMPLATE2 (temp, - this->allocator_->free, - ACE_Node, - T, C); - return 0; - } -} - -template typename ACE_Unbounded_Set_Ex::iterator -ACE_Unbounded_Set_Ex::begin (void) -{ - // ACE_TRACE ("ACE_Unbounded_Set_Ex::begin"); - return iterator (*this); -} - -template typename ACE_Unbounded_Set_Ex::iterator -ACE_Unbounded_Set_Ex::end (void) -{ - // ACE_TRACE ("ACE_Unbounded_Set_Ex::end"); - return iterator (*this, 1); -} - -template typename ACE_Unbounded_Set_Ex::const_iterator -ACE_Unbounded_Set_Ex::begin (void) const -{ - // ACE_TRACE ("ACE_Unbounded_Set_Ex::begin"); - return const_iterator (*this); -} - -template typename ACE_Unbounded_Set_Ex::const_iterator -ACE_Unbounded_Set_Ex::end (void) const -{ - // ACE_TRACE ("ACE_Unbounded_Set_Ex::end"); - return const_iterator (*this, 1); -} - -ACE_ALLOC_HOOK_DEFINE(ACE_Unbounded_Set_Ex_Iterator) - -template void -ACE_Unbounded_Set_Ex_Iterator::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - // ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator::dump"); -#endif /* ACE_HAS_DUMP */ -} - -template -ACE_Unbounded_Set_Ex_Iterator::ACE_Unbounded_Set_Ex_Iterator ( - ACE_Unbounded_Set_Ex &s, - bool end) - : current_ (!end ? s.head_->next_ : s.head_ ), - set_ (&s) -{ - // ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator::ACE_Unbounded_Set_Ex_Iterator"); -} - -template int -ACE_Unbounded_Set_Ex_Iterator::advance (void) -{ - // ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator::advance"); - this->current_ = this->current_->next_; - return this->current_ != this->set_->head_; -} - -template int -ACE_Unbounded_Set_Ex_Iterator::first (void) -{ - // ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator::first"); - this->current_ = this->set_->head_->next_; - return this->current_ != this->set_->head_; -} - -template int -ACE_Unbounded_Set_Ex_Iterator::done (void) const -{ - ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator::done"); - - return this->current_ == this->set_->head_; -} - -template int -ACE_Unbounded_Set_Ex_Iterator::next (T *&item) -{ - // ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator::next"); - if (this->current_ == this->set_->head_) - return 0; - else - { - item = &this->current_->item_; - return 1; - } -} - -template ACE_Unbounded_Set_Ex_Iterator -ACE_Unbounded_Set_Ex_Iterator::operator++ (int) -{ - //ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator::operator++ (int)"); - ACE_Unbounded_Set_Ex_Iterator retv (*this); - - // postfix operator - - this->advance (); - return retv; -} - -template ACE_Unbounded_Set_Ex_Iterator& -ACE_Unbounded_Set_Ex_Iterator::operator++ (void) -{ - // ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator::operator++ (void)"); - - // prefix operator - - this->advance (); - return *this; -} - -template T& -ACE_Unbounded_Set_Ex_Iterator::operator* (void) -{ - //ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator::operator*"); - T *retv = 0; - - int result = this->next (retv); - ACE_ASSERT (result != 0); - ACE_UNUSED_ARG (result); - - return *retv; -} - -template bool -ACE_Unbounded_Set_Ex_Iterator::operator== (const ACE_Unbounded_Set_Ex_Iterator &rhs) const -{ - //ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator::operator=="); - return (this->set_ == rhs.set_ && this->current_ == rhs.current_); -} - -template bool -ACE_Unbounded_Set_Ex_Iterator::operator!= (const ACE_Unbounded_Set_Ex_Iterator &rhs) const -{ - //ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator::operator!="); - return (this->set_ != rhs.set_ || this->current_ != rhs.current_); -} - -ACE_ALLOC_HOOK_DEFINE(ACE_Unbounded_Set_Ex_Const_Iterator) - -template void -ACE_Unbounded_Set_Ex_Const_Iterator::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - // ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator::dump"); -#endif /* ACE_HAS_DUMP */ -} - -template -ACE_Unbounded_Set_Ex_Const_Iterator::ACE_Unbounded_Set_Ex_Const_Iterator ( - const ACE_Unbounded_Set_Ex &s, - bool end) - : current_ (!end ? s.head_->next_ : s.head_ ), - set_ (&s) -{ - // ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator::ACE_Unbounded_Set_Ex_Const_Iterator"); -} - -template int -ACE_Unbounded_Set_Ex_Const_Iterator::advance (void) -{ - // ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator::advance"); - this->current_ = this->current_->next_; - return this->current_ != this->set_->head_; -} - -template int -ACE_Unbounded_Set_Ex_Const_Iterator::first (void) -{ - // ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator::first"); - this->current_ = this->set_->head_->next_; - return this->current_ != this->set_->head_; -} - -template int -ACE_Unbounded_Set_Ex_Const_Iterator::done (void) const -{ - ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator::done"); - - return this->current_ == this->set_->head_; -} - -template int -ACE_Unbounded_Set_Ex_Const_Iterator::next (T *&item) -{ - // ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator::next"); - if (this->current_ == this->set_->head_) - return 0; - else - { - item = &this->current_->item_; - return 1; - } -} - -template ACE_Unbounded_Set_Ex_Const_Iterator -ACE_Unbounded_Set_Ex_Const_Iterator::operator++ (int) -{ - //ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator::operator++ (int)"); - ACE_Unbounded_Set_Ex_Const_Iterator retv (*this); - - // postfix operator - - this->advance (); - return retv; -} - -template ACE_Unbounded_Set_Ex_Const_Iterator& -ACE_Unbounded_Set_Ex_Const_Iterator::operator++ (void) -{ - // ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator::operator++ (void)"); - - // prefix operator - - this->advance (); - return *this; -} - -template T& -ACE_Unbounded_Set_Ex_Const_Iterator::operator* (void) -{ - //ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator::operator*"); - T *retv = 0; - - int const result = this->next (retv); - ACE_ASSERT (result != 0); - ACE_UNUSED_ARG (result); - - return *retv; -} - -template bool -ACE_Unbounded_Set_Ex_Const_Iterator::operator== (const ACE_Unbounded_Set_Ex_Const_Iterator &rhs) const -{ - //ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator::operator=="); - return (this->set_ == rhs.set_ && this->current_ == rhs.current_); -} - -template bool -ACE_Unbounded_Set_Ex_Const_Iterator::operator!= (const ACE_Unbounded_Set_Ex_Const_Iterator &rhs) const -{ - //ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator::operator!="); - return (this->set_ != rhs.set_ || this->current_ != rhs.current_); -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_UNBOUNDED_SET_EX_CPP */ diff --git a/externals/ace/Unbounded_Set_Ex.h b/externals/ace/Unbounded_Set_Ex.h deleted file mode 100644 index 3d290a6acb3..00000000000 --- a/externals/ace/Unbounded_Set_Ex.h +++ /dev/null @@ -1,376 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Unbounded_Set_Ex.h - * - * $Id: Unbounded_Set_Ex.h 88978 2010-02-13 16:03:31Z hillj $ - * - * @author Douglas C. Schmidt - */ -//============================================================================= - -#ifndef ACE_UNBOUNDED_SET_EX_H -#define ACE_UNBOUNDED_SET_EX_H -#include /**/ "ace/pre.h" - -#include "ace/Node.h" -#include "ace/os_include/os_stddef.h" -#include - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -class ACE_Allocator; - -template -class ACE_Unbounded_Set_Ex_Iterator; - -template -class ACE_Unbounded_Set_Ex_Const_Iterator; - -template -class ACE_Unbounded_Set_Ex; - -/** - * @class ACE_Unbounded_Set_Ex_Iterator - * - * @brief Implement an iterator over an unbounded set. - */ -template -class ACE_Unbounded_Set_Ex_Iterator -{ -public: - /// Type definition of the container type. - typedef ACE_Unbounded_Set_Ex container_type; - - // = std::iterator_traits typedefs/traits. - typedef std::forward_iterator_tag iterator_category; - typedef typename container_type::value_type value_type; - typedef typename container_type::reference reference; - typedef typename container_type::pointer pointer; - typedef typename container_type::difference_type difference_type; - - // = Initialization method. - ACE_Unbounded_Set_Ex_Iterator (ACE_Unbounded_Set_Ex &s, bool end = false); - - // = Iteration methods. - - /// Pass back the @a next_item that hasn't been seen in the Set. - /// Returns 0 when all items have been seen, else 1. - int next (T *&next_item); - - /// Move forward by one element in the set. Returns 0 when all the - /// items in the set have been seen, else 1. - int advance (void); - - /// Move to the first element in the set. Returns 0 if the - /// set is empty, else 1. - int first (void); - - /// Returns 1 when all items have been seen, else 0. - int done (void) const; - - /// Dump the state of an object. - void dump (void) const; - - // = STL styled iteration, compare, and reference functions. - - /// Postfix advance. - ACE_Unbounded_Set_Ex_Iterator operator++ (int); - - /// Prefix advance. - ACE_Unbounded_Set_Ex_Iterator& operator++ (void); - - /// Returns a reference to the internal element @c this is pointing to. - T& operator* (void); - - /// Check if two iterators point to the same position - bool operator== (const ACE_Unbounded_Set_Ex_Iterator &) const; - bool operator!= (const ACE_Unbounded_Set_Ex_Iterator &) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - - /// Pointer to the current node in the iteration. - ACE_Node *current_; - - /// Pointer to the set we're iterating over. - ACE_Unbounded_Set_Ex *set_; -}; - -/** - * @class ACE_Unbounded_Set_Ex_Const_Iterator - * - * @brief Implement an const iterator over an unbounded set. - */ -template -class ACE_Unbounded_Set_Ex_Const_Iterator -{ -public: - typedef ACE_Unbounded_Set_Ex container_type; - - // = std::iterator_traits typedefs/traits. - typedef std::forward_iterator_tag iterator_category; - typedef typename container_type::const_value_type value_type; - typedef typename container_type::const_reference reference; - typedef typename container_type::const_pointer pointer; - typedef typename container_type::difference_type difference_type; - - // = Initialization method. - ACE_Unbounded_Set_Ex_Const_Iterator (const ACE_Unbounded_Set_Ex &s, - bool end = false); - - // = Iteration methods. - - /// Pass back the @a next_item that hasn't been seen in the Set. - /// @return Returns 0 when all items have been seen, else 1. - int next (T *&next_item); - - /// Move forward by one element in the set. Returns 0 when all the - /// items in the set have been seen, else 1. - int advance (void); - - /// Move to the first element in the set. Returns 0 if the - /// set is empty, else 1. - int first (void); - - /// Returns 1 when all items have been seen, else 0. - int done (void) const; - - /// Dump the state of an object. - void dump (void) const; - - // = STL styled iteration, compare, and reference functions. - - /// Postfix advance. - ACE_Unbounded_Set_Ex_Const_Iterator operator++ (int); - - /// Prefix advance. - ACE_Unbounded_Set_Ex_Const_Iterator& operator++ (void); - - /// Returns a reference to the internal element @c this is pointing to. - T& operator* (void); - - /// Check if two iterators point to the same position - bool operator== (const ACE_Unbounded_Set_Ex_Const_Iterator &) const; - bool operator!= (const ACE_Unbounded_Set_Ex_Const_Iterator &) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - - /// Pointer to the current node in the iteration. - ACE_Node *current_; - - /// Pointer to the set we're iterating over. - const ACE_Unbounded_Set_Ex *set_; -}; - -/** - * @class ACE_Unbounded_Set_Ex - * - * @brief Implement a simple unordered set of of unbounded size. - * - * This implementation of an unordered set uses a circular - * linked list with a dummy node. This implementation does not - * allow duplicates, but it maintains FIFO ordering of insertions. - * - * This implementation may also be parameterized with a comparator - * functor, which must implement bool operator () (const T&, const T&) const, - * returning true if the given items are equivalent. The default comparator - * is sufficient for objects reliably compared with operator==. - * - * Requirements and Performance Characteristics - * - Internal Structure - * Circular linked list - * - Duplicates allowed? - * No - * - Random access allowed? - * No - * - Search speed - * Linear - * - Insert/replace speed - * Linear - * - Iterator still valid after change to container? - * Yes - * - Frees memory for removed elements? - * Yes - * - Items inserted by - * Value - * - Requirements for contained type - * -# Default constructor - * -# Copy constructor - * -# operator= - * -# operator== const - * - */ -template -class ACE_Unbounded_Set_Ex -{ -public: - friend class ACE_Unbounded_Set_Ex_Iterator; - friend class ACE_Unbounded_Set_Ex_Const_Iterator; - - // Trait definition. - typedef ACE_Unbounded_Set_Ex_Iterator ITERATOR; - typedef ACE_Unbounded_Set_Ex_Iterator iterator; - typedef ACE_Unbounded_Set_Ex_Const_Iterator CONST_ITERATOR; - typedef ACE_Unbounded_Set_Ex_Const_Iterator const_iterator; - typedef C COMP; - typedef ACE_Node NODE; - - // = STL typedefs/traits. - typedef T value_type; - typedef T const const_value_type; - typedef value_type & reference; - typedef const_value_type & const_reference; - typedef value_type * pointer; - typedef const_value_type * const_pointer; - typedef ptrdiff_t difference_type; - - // = Initialization and termination methods. - /// Constructor. Use user specified allocation strategy - /// if specified. - /** - * Initialize an empty set using the allocation strategy of the user if - * provided. - */ - ACE_Unbounded_Set_Ex (ACE_Allocator *alloc = 0); - - /** - * Initialize an empty set using the allocation strategy of the user if - * provided, and a given comparator functor. - */ - ACE_Unbounded_Set_Ex (const C &comparator, ACE_Allocator *alloc = 0); - - /// Copy constructor. - /** - * Initialize this set to be an exact copy of the set provided. - */ - ACE_Unbounded_Set_Ex (const ACE_Unbounded_Set_Ex &); - - /// Assignment operator. - /** - * Perform a deep copy of the rhs into the lhs. - */ - ACE_Unbounded_Set_Ex & operator= (const ACE_Unbounded_Set_Ex &); - - /// Destructor. - /** - * Destroy the nodes of the set. - */ - ~ACE_Unbounded_Set_Ex (void); - - // = Check boundary conditions. - - /// Returns @c true if the container is empty, otherwise returns @c false. - /** - * Constant time is_empty check. - */ - bool is_empty (void) const; - - /// Returns @c false. - /** - * Always returns @c false since the set can never fill up. - */ - bool is_full (void) const; - - // = Classic unordered set operations. - - /// Linear insertion of an item. - /** - * Insert @a new_item into the set (doesn't allow duplicates). - * Returns -1 if failures occur, 1 if item is already present, else - * 0. - */ - int insert (const T &new_item); - - /// Insert @a item at the tail of the set (doesn't check for - /// duplicates). - /** - * Constant time insert at the end of the set. - */ - int insert_tail (const T &item); - - /// Linear remove operation. - /** - * Remove first occurrence of @a item from the set. Returns 0 if - * it removes the item, -1 if it can't find the item, and -1 if a - * failure occurs. - */ - int remove (const T &item); - - /// Finds if @a item occurs in the set. Returns 0 if find succeeds, - /// else -1. - /** - * Performs a linear find operation. - */ - int find (const T &item) const; - - /// Size of the set. - /** - * Access the size of the set. - */ - size_t size (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Reset the ACE_Unbounded_Set_Ex to be empty. - /** - * Delete the nodes of the set. - */ - void reset (void); - - // = STL-styled unidirectional iterator factory. - iterator begin (void); - iterator end (void); - const_iterator begin (void) const; - const_iterator end (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - /// Delete all the nodes in the Set. - void delete_nodes (void); - - /// Copy nodes into this set. - void copy_nodes (const ACE_Unbounded_Set_Ex &); - - /// Head of the linked list of Nodes. - NODE *head_; - - /// Current size of the set. - size_t cur_size_; - - /// Allocation strategy of the set. - ACE_Allocator *allocator_; - - /// Comparator to be used - COMP comp_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Unbounded_Set_Ex.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Unbounded_Set_Ex.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Unbounded_Set_Ex.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" -#endif /* ACE_UNBOUNDED_SET_H */ diff --git a/externals/ace/Unbounded_Set_Ex.inl b/externals/ace/Unbounded_Set_Ex.inl deleted file mode 100644 index 356a1f58f1d..00000000000 --- a/externals/ace/Unbounded_Set_Ex.inl +++ /dev/null @@ -1,23 +0,0 @@ -// -*- C++ -*- -// -// $Id: Unbounded_Set_Ex.inl 81624 2008-05-06 17:14:57Z wotte $ - -#include "ace/Global_Macros.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template ACE_INLINE bool -ACE_Unbounded_Set_Ex::is_empty (void) const -{ - ACE_TRACE ("ACE_Unbounded_Set_Ex::is_empty"); - return this->head_ == this->head_->next_; -} - -template ACE_INLINE bool -ACE_Unbounded_Set_Ex::is_full (void) const -{ - ACE_TRACE ("ACE_Unbounded_Set_Ex::is_full"); - return 0; // We should implement a "node of last resort for this..." -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/Value_Ptr.h b/externals/ace/Value_Ptr.h deleted file mode 100644 index c9272a90cff..00000000000 --- a/externals/ace/Value_Ptr.h +++ /dev/null @@ -1,167 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file Value_Ptr.h - * - * $Id: Value_Ptr.h 80826 2008-03-04 14:51:23Z wotte $ - * - * Value_Ptr implementation based on code in Herb Sutter's book "More - * Exceptional C++". - * - * @author Ossama Othman - */ -//========================================================================== - -#ifndef ACE_VALUE_PTR_H -#define ACE_VALUE_PTR_H - -#include "ace/config-lite.h" - -#include - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -namespace ACE -{ - /** - * @struct VP_traits - * - * @brief @c Value_Ptr traits template structure. - * - * The @c Value_Ptr template class delegates some operations to this - * template traits structure. - * - * Specialize this trait template if cloning through copy - * construction is not sufficient. For example, to avoid slicing - * when copying an object through a base class pointer, one can - * implement a virtual "clone" method that can be used to - * polymorphically invoke the appropriate cloning operation(s). - * That virtual method would then be invoked by the @c VP_traits\<\> - * specialization. - */ - template - struct VP_traits - { - /// Copy the given object. - static T * clone (T const * p) { return new T (*p); } - }; - - /** - * @class Value_Ptr - * - * @brief Smart pointer implementation designed for use as a class - * member. - * - * Using a @c std::auto_ptr\<\> as a class member is sometimes - * problematic since ownership of memory is transferred when copying - * such members. This @c Value_Ptr class is explicitly designed to - * avoid such problems by performing copies of the underlying object - * rather than transfer ownership. This, for example, allows it to - * be readily used as a member in classes placed inside STL - * containers. - * - * @see Item 31 in "More Exceptional C++" by Herb Sutter. - */ - template - class Value_Ptr - { - public: - - /// Constructor. - explicit Value_Ptr (T * p = 0) : p_ (p) { } - - /// Destructor. - ~Value_Ptr (void) { delete this->p_; } - - /// Deference operator. - T & operator* (void) const { return *this->p_; } - - /// Pointer operator. - T * operator-> (void) const { return this->p_; } - - /// Non-throwing swap operation used to make assignment strongly - /// exception-safe. - /** - * @note As implemented, the swap operation may not work correctly - * for @c auto_ptr\<\>s, but why would one use an @c - * auto_ptr\<\> as the template argument for this particular - * template class!? - */ - void swap (Value_Ptr & other) { std::swap (this->p_, other.p_); } - - /// Copy constructor. - Value_Ptr (Value_Ptr const & other) - : p_ (create_from (other.p_)) { } - - /// Assignment operator. - Value_Ptr & operator= (Value_Ptr const & other) - { - // Strongly exception-safe. - Value_Ptr temp (other); - this->swap (temp); - return *this; - } - -#ifndef ACE_LACKS_MEMBER_TEMPLATES - - // Compiler can't handle member templates so we lose converting - // copy operations. - - /// Converting copy constructor. - template - Value_Ptr (Value_Ptr const & other) - : p_ (create_from (other.p_)) { } - - /// Converting assignment operator. - template - Value_Ptr & operator= (Value_Ptr const & other) - { - // Strongly exception-safe. - Value_Ptr temp (other); - this->swap (temp); - return *this; - } - -#endif /* !ACE_LACKS_MEMBER_TEMPLATES */ - - private: - -#ifndef ACE_LACKS_MEMBER_TEMPLATES - - /// Copying method invoked when copy constructing. - template - T * create_from (U const * p) const - { - return p ? VP_traits::clone (p) : 0; - } - -#else - - // Compiler can't handle member templates so we lose converting - // copy operations. - - /// Copying method invoked when copy constructing. - T * create_from (T const * p) const - { - return p ? VP_traits::clone (p) : 0; - } - -#endif /* !ACE_LACKS_MEMBER_TEMPLATES */ - - private: - -#ifndef ACE_LACKS_MEMBER_TEMPLATES - template friend class Value_Ptr; -#endif /* !ACE_LACKS_MEMBER_TEMPLATES */ - - /// Object owned by this @c Value_Ptr. - T * p_; - - }; - -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_VALUE_PTR_H */ diff --git a/externals/ace/Vector_T.cpp b/externals/ace/Vector_T.cpp deleted file mode 100644 index 006e6db1b4a..00000000000 --- a/externals/ace/Vector_T.cpp +++ /dev/null @@ -1,154 +0,0 @@ -// $Id: Vector_T.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#ifndef ACE_VECTOR_T_CPP -#define ACE_VECTOR_T_CPP - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/Vector_T.h" - -#if !defined (__ACE_INLINE__) -#include "ace/Vector_T.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_Vector) - -template -void ACE_Vector::resize (const size_t new_size, - const T& t) -{ - ACE_Array::size (new_size); - if (new_size > length_) - for (size_t i = length_; i < new_size; ++i) - (*this)[i]=t; - - curr_max_size_ = this->max_size (); - length_ = new_size; -} - -template -void ACE_Vector::push_back (const T& elem) -{ - if (length_ == curr_max_size_) - { - ACE_Array::size (curr_max_size_ * 2); - curr_max_size_ = this->max_size (); - } - else - ACE_Array::size (length_ + 1); - - ++length_; - (*this)[length_-1] = elem; -} - -template -void ACE_Vector::dump (void) const -{ -#if defined (ACE_HAS_DUMP) -#if 0 - // Can't do this unless the vector is an object with a dump - // function. - for (size_t i = 0; i < this->size (); ++i) - (*this)[i].dump (); -#endif /* 0 */ -#endif /* ACE_HAS_DUMP */ -} - -// Compare this vector with for equality. -template bool -ACE_Vector::operator== (const ACE_Vector &s) const -{ - if (this == &s) - return true; - else if (this->size () != s.size ()) - return false; - - const size_t len = s.size (); - for (size_t slot = 0; slot < len; ++slot) - if ((*this)[slot] != s[slot]) - return false; - - return true; -} - -#if 0 -template -int compare(const ACE_Vector& v1, - const ACE_Vector& v2, - const size_t from_ndx, - const size_t to_ndx) -{ - size_t last1 = v1.size () - 1; - size_t last2 = v2.size () - 1; - if (last1 < from_ndx || last1 < to_ndx) - return false; - if (last2 < from_ndx || last2 < to_ndx) - return false; - if (last1 != last2) - return false; - - // cout<<"compare() <================="<"< -int partial_compare(const ACE_Vector& v1, - const ACE_Vector& v2, - const size_t from_ndx, - const size_t to_ndx) -{ - size_t last1 = v1.size () - 1; - size_t last2 = v2.size () - 1; - - if (last1 < from_ndx || last1 < to_ndx) - return false; - if (last2 < from_ndx || last2 < to_ndx) - return false; - - // cout<<"partial_compare() <================="<"< int -ACE_Vector_Iterator::next (T *&item) -{ - // ACE_TRACE ("ACE_Vector_Iterator::next"); - - if (this->done ()) - { - item = 0; - return 0; - } - else - { - item = &vector_[current_]; - return 1; - } -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_VECTOR_T_CPP */ diff --git a/externals/ace/Vector_T.h b/externals/ace/Vector_T.h deleted file mode 100644 index 3d49f4391bb..00000000000 --- a/externals/ace/Vector_T.h +++ /dev/null @@ -1,316 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file Vector_T.h - * - * $Id: Vector_T.h 84477 2009-02-16 13:30:38Z johnnyw $ - * - * @author Craig L. Ching - * @author Gonzalo Diethelm - */ -//========================================================================== - -#ifndef ACE_VECTOR_T_H -#define ACE_VECTOR_T_H - -#include /**/ "ace/pre.h" - -#include "ace/Array.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/* - * Default size for an ACE_Vector. - */ -static const size_t ACE_VECTOR_DEFAULT_SIZE = 32; - -// Forward declaration. -template class ACE_Vector_Iterator; - -/** - * @class ACE_Vector - * - * @brief Defines an STL-like vector container. - * - * This is an STL-like template vector container, a wrapper around - * ACE_Array. It provides at least the basic std::vector look and - * feel: push_back(), clear(), resize(), capacity(). This template - * class uses the copy semantic paradigm, though it is okay to use - * reference counted smart pointers (see ACE_Ptr<T>) with this - * template class. - * - * Requirements and Performance Characteristics - * - Internal Structure - * ACE_Array - * - Duplicates allowed? - * Yes - * - Random access allowed? - * No - * - Search speed - * N/A - * - Insert/replace speed - * Linear - * - Iterator still valid after change to container? - * Yes - * - Frees memory for removed elements? - * No - * - Items inserted by - * Value - * - Requirements for contained type - * -# Default constructor - * -# Copy constructor - * -# operator= - */ -template -class ACE_Vector : public ACE_Array -{ -public: - /** - * A short name for iterator for ACE_Vector. - */ - typedef ACE_Vector_Iterator Iterator; - - - /** - * General constructor. - * - * @param init_size Initial size of the vector with the default - * value of DEFAULT_SIZE - * @param alloc Pointer to an ACE allocator. If it is NULL then the - * default ACE allocator is used - */ - ACE_Vector (const size_t init_size = DEFAULT_SIZE, - ACE_Allocator* alloc = 0); - - /** - * Destructor. - */ - ~ACE_Vector (); - - /** - * Returns the current vector capacity, that is, the currently - * allocated buffer size. - * - * @return Current buffer size of the vector - */ - size_t capacity (void) const; - - /** - * Returns the vector's dynamic size / actual current size of the - * vector. Do not confuse it with ACE_Array::size(), which returns - * the array's capacity. Unfortunately, ACE is not very consistent - * with the function names. - * - * @return Dynamic size / actual current size of the vector. - */ - size_t size (void) const; - - /** - * Clears out the vector. It does not reallocate the vector's - * buffer, it is just sets the vector's dynamic size to 0. - */ - void clear (void); - - /** - * Resizes the vector to the new capacity. If the vector's current - * capacity is smaller than the size to be specified, then the - * buffer gets reallocated. If the new capacity is less than the - * current capacity of the vector, the buffer size stays the same. - * - * @param new_size New capacity of the vector - * @param t A filler value (of the class T) for initializing the - * elements of the vector with. By default, if this - * parameter is not specified, the default value of the - * class T will be used (for more detail, see the - * initialization clause for this parameter). - */ - void resize (const size_t new_size, - const T& t); - - /** - * Appends a new element to the vector ("push back"). If the - * dynamic size of the vector is equal to the capacity of the vector - * (vector is at capacity), the vector automatically doubles its - * capacity. - * - * @param elem A reference to the new element to be appended. By - * default, this parameters gets initialized with the - * default value of the class T. - */ - void push_back (const T& elem); - - /** - * Deletes the last element from the vector ("pop back"). What this - * function really does is decrement the dynamic size of the - * vector. The vector's buffer does not get reallocated for - * performance. - */ - void pop_back (void); - - /** - * This function dumps the content of the vector. TO BE MOVED out - * of this class. It needs to be implemented as a global template - * function that accepts a const ACE_Vector<T>, in order to - * make instances of this class compile on Linux, AIX. G++ and xlC - * have template instantiation algoriths, which are different from - * the one in Visual C++. The algorithms try to instantiate ALL - * methods declared in the template class, regardless of whether the - * functions are used or not. That is, all of the classes, that are - * used as elements in ACE_Vector's, have to have the dump() methods - * defined in them (seems to be overkill). - * - * This function calls T::dump() for each element of the vector. - */ - void dump (void) const; - - // = Compare operators - - /// Equality comparison operator. - /** - * Compare this vector with @arg s for equality. Two vectors are equal - * if their sizes are equal and all the elements are equal. - */ - bool operator== (const ACE_Vector &s) const; - - /// Inequality comparison operator. - /** - * Compare this vector with @arg s for inequality such that @c *this != - * @arg s is always the complement of the boolean return value of - * @c *this == @arg s. - */ - bool operator!= (const ACE_Vector &s) const; - - void swap (ACE_Vector &rhs); - -protected: - - /** - * Dynamic size (length) of the vector. - */ - size_t length_; - - /** - * Current capacity (buffer size) of the vector. - */ - size_t curr_max_size_; - - friend class ACE_Vector_Iterator; -}; - -#if 0 -/* - * Not sure about including these functions, if for no other reason, - * because they polute the global namespace! - */ - -/** - * Compare two vectors in the range of [from_ndx..to_ndx]. This - * template function requires class T to have the bool operator!=() - * declared in the class. It is safe to define vectors of scalar data - * types, like int, double, etc., including class ACE_TString. - * - * @param v1 The first vector (out of the two) to be compared. - * @param v2 The Second vector (out of the two) to be compared. - * @param from_ndx Compare vector v1 and v2, starting with the - * "from_ndx" index . - * @param to_ndx Compare vector v1 and v2, from "from_ndx" to - * "to_ndx". - * @return Returns true if v1==v2 in the specified index range, - * returns false otherwise. Also, returns false in case if - * v1's size is not equal to v2's size. - */ -template -int compare (const ACE_Vector& v1, - const ACE_Vector& v2, - const size_t from_ndx, - const size_t to_ndx); - -/** - * Does a partial comparison of two vectors in the range of - * [from_ndx..to_ndx]. The only difference between this function and - * the template compare<T> function is that this function does - * not require v1 and v2 to be of equal size. - * - * @param v1 The first vector (out of the two) to be compared. - * @param v2 The Second vector (out of the two) to be compared. - * @param from_ndx Compare vector v1 and v2, starting with the - * "from_ndx" index . - * @param to_ndx Compare vector v1 and v2, from "from_ndx" to - * "to_ndx". - * @return Returns true if vector v1 and v2 are equal in the specified - * index range. - */ - -template -int partial_compare (const ACE_Vector& v1, - const ACE_Vector& v2, - const size_t from_ndx, - const size_t to_ndx); -#endif /* 0 */ -// **************************************************************** - -/** - * @class ACE_Vector_Iterator - * - * @brief Implement an iterator over an ACE_Vector. - * - * This iterator is safe in the face of vector element deletions. - * But it is NOT safe if the vector is resized via the assignment - * operator during iteration. That would be very odd, and dangerous. - */ -template -class ACE_Vector_Iterator -{ -public: - // = Initialization method. - ACE_Vector_Iterator (ACE_Vector &); - - // = Iteration methods. - - /// Pass back the @a next_item that hasn't been seen in the vector. - /// Returns 0 when all items have been seen, else 1. - int next (T *&next_item); - - /// Move forward by one element in the vector. Returns 0 when all the - /// items in the vector have been seen, else 1. - int advance (void); - - /// Returns 1 when all items have been seen, else 0. - int done (void) const; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - -private: - /// Pointer to the current item in the iteration. - size_t current_; - - /// Reference to the vector we're iterating over. - ACE_Vector &vector_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/Vector_T.inl" -#endif /* __ACE_INLINE__ */ - -#if defined (ACE_TEMPLATES_REQUIRE_SOURCE) -#include "ace/Vector_T.cpp" -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ - -#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) -#pragma implementation ("Vector_T.cpp") -#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ - -#include /**/ "ace/post.h" - -#endif /* ACE_VECTOR_T_H */ diff --git a/externals/ace/Vector_T.inl b/externals/ace/Vector_T.inl deleted file mode 100644 index 4b773109a84..00000000000 --- a/externals/ace/Vector_T.inl +++ /dev/null @@ -1,107 +0,0 @@ -// -*- C++ -*- -// -// $Id: Vector_T.inl 81478 2008-04-28 13:22:26Z schmidt $ - -#include - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -template ACE_INLINE -ACE_Vector::ACE_Vector (const size_t init_size, - ACE_Allocator* alloc) - : ACE_Array (init_size == 0 ? DEFAULT_SIZE : init_size, alloc), - length_ (0) -{ - this->curr_max_size_ = this->max_size (); -} - -template ACE_INLINE -ACE_Vector::~ACE_Vector () -{ -} - -template ACE_INLINE -size_t ACE_Vector::capacity (void) const -{ - return curr_max_size_; -} - -template ACE_INLINE -size_t ACE_Vector::size (void) const -{ - return length_; -} - -template ACE_INLINE -void ACE_Vector::clear (void) -{ - length_ = 0; -} - -template ACE_INLINE -void ACE_Vector::pop_back (void) -{ - if (length_ > 0) - { - --length_; - ACE_Array::size (length_); - } -} - -// Compare this vector with for inequality. - -template ACE_INLINE bool -ACE_Vector::operator!= (const ACE_Vector &s) const -{ - return !(*this == s); -} - -template ACE_INLINE void -ACE_Vector::swap (ACE_Vector &rhs) -{ - ACE_Array::swap (rhs); - std::swap (this->length_, rhs.length_); - std::swap (this->curr_max_size_, rhs.curr_max_size_); -} - -// **************************************************************** - -template ACE_INLINE void -ACE_Vector_Iterator::dump (void) const -{ - // ACE_TRACE ("ACE_Vector_Iterator::dump"); -} - -template ACE_INLINE -ACE_Vector_Iterator::ACE_Vector_Iterator (ACE_Vector &v) - : current_ (0), - vector_ (v) -{ - // ACE_TRACE ("ACE_Vector_Iterator::ACE_Vector_Iterator"); -} - -template ACE_INLINE int -ACE_Vector_Iterator::advance (void) -{ - // ACE_TRACE ("ACE_Vector_Iterator::advance"); - - if (this->current_ < vector_.size ()) - { - ++this->current_; - return 1; - } - else - // Already finished iterating. - return 0; -} - -template ACE_INLINE int -ACE_Vector_Iterator::done (void) const -{ - ACE_TRACE ("ACE_Vector_Iterator::done"); - - return this->current_ >= vector_.size (); -} - -ACE_END_VERSIONED_NAMESPACE_DECL - diff --git a/externals/ace/Version.h b/externals/ace/Version.h deleted file mode 100644 index 92d70e802ec..00000000000 --- a/externals/ace/Version.h +++ /dev/null @@ -1,9 +0,0 @@ - -// -*- C++ -*- -// $Id: Version.h 91247 2010-08-01 09:46:33Z johnnyw $ -// This is file was automatically generated by \$ACE_ROOT/bin/make_release. - -#define ACE_MAJOR_VERSION 5 -#define ACE_MINOR_VERSION 8 -#define ACE_BETA_VERSION 1 -#define ACE_VERSION "5.8.1" diff --git a/externals/ace/Versioned_Namespace.h b/externals/ace/Versioned_Namespace.h deleted file mode 100644 index 542254876ff..00000000000 --- a/externals/ace/Versioned_Namespace.h +++ /dev/null @@ -1,51 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file Versioned_Namespace.h - * - * $Id$ - * - * Versioned namespace support. - * - * Useful for preventing conflicts when using a third party library. - * - * @author Ossama Othman - */ -//============================================================================= - -#ifndef ACE_VERSIONED_NAMESPACE_H -#define ACE_VERSIONED_NAMESPACE_H - -#ifndef ACE_CONFIG_MACROS_H -# error This header is only meant to be included by or after "ace/config-lite.h". -#endif /* !ACE_CONFIG_LITE_H */ - - -#if defined (ACE_HAS_VERSIONED_NAMESPACE) && ACE_HAS_VERSIONED_NAMESPACE == 1 - -# ifndef ACE_VERSIONED_NAMESPACE_NAME -//# include "ace/Version.h" - -// Preprocessor symbols will not be expanded if they are -// concatenated. Force the preprocessor to expand them during the -// argument prescan by calling a macro that itself calls another that -// performs the actual concatenation. -# define ACE_MAKE_VERSIONED_NAMESPACE_NAME_IMPL(MAJOR,MINOR,BETA) ACE_ ## MAJOR ## _ ## MINOR ## _ ## BETA -# define ACE_MAKE_VERSIONED_NAMESPACE_NAME(MAJOR,MINOR,BETA) ACE_MAKE_VERSIONED_NAMESPACE_NAME_IMPL(MAJOR,MINOR,BETA) -# define ACE_VERSIONED_NAMESPACE_NAME ACE_MAKE_VERSIONED_NAMESPACE_NAME(ACE_MAJOR_VERSION,ACE_MINOR_VERSION,ACE_BETA_VERSION) -# endif /* !ACE_VERSIONED_NAMESPACE_NAME */ - -# define ACE_BEGIN_VERSIONED_NAMESPACE_DECL namespace ACE_VERSIONED_NAMESPACE_NAME { -# define ACE_END_VERSIONED_NAMESPACE_DECL } \ - using namespace ACE_VERSIONED_NAMESPACE_NAME; - -#else - -# define ACE_VERSIONED_NAMESPACE_NAME -# define ACE_BEGIN_VERSIONED_NAMESPACE_DECL -# define ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_VERSIONED_NAMESPACE */ - -#endif /* !ACE_VERSIONED_NAMESPACE_H */ diff --git a/externals/ace/WFMO_Reactor.cpp b/externals/ace/WFMO_Reactor.cpp deleted file mode 100644 index 713b5689cdb..00000000000 --- a/externals/ace/WFMO_Reactor.cpp +++ /dev/null @@ -1,2748 +0,0 @@ -// $Id: WFMO_Reactor.cpp 85125 2009-04-20 16:47:38Z johnnyw $ - -#include "ace/WFMO_Reactor.h" - -#if defined (ACE_WIN32) - -#include "ace/Handle_Set.h" -#include "ace/Timer_Heap.h" -#include "ace/Thread.h" -#include "ace/OS_NS_errno.h" -#include "ace/Null_Condition.h" - -#if !defined (__ACE_INLINE__) -#include "ace/WFMO_Reactor.inl" -#endif /* __ACE_INLINE__ */ - -ACE_RCSID(ace, WFMO_Reactor, "$Id: WFMO_Reactor.cpp 85125 2009-04-20 16:47:38Z johnnyw $") - -#include "ace/Auto_Ptr.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_WFMO_Reactor_Handler_Repository::ACE_WFMO_Reactor_Handler_Repository (ACE_WFMO_Reactor &wfmo_reactor) - : wfmo_reactor_ (wfmo_reactor) -{ -} - -int -ACE_WFMO_Reactor_Handler_Repository::open (size_t size) -{ - if (size > MAXIMUM_WAIT_OBJECTS) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("%d exceeds MAXIMUM_WAIT_OBJECTS (%d)\n"), - size, - MAXIMUM_WAIT_OBJECTS), - -1); - - // Dynamic allocation - ACE_NEW_RETURN (this->current_handles_, - ACE_HANDLE[size], - -1); - ACE_NEW_RETURN (this->current_info_, - Current_Info[size], - -1); - ACE_NEW_RETURN (this->current_suspended_info_, - Suspended_Info[size], - -1); - ACE_NEW_RETURN (this->to_be_added_info_, - To_Be_Added_Info[size], - -1); - - // Initialization - this->max_size_ = size; - this->max_handlep1_ = 0; - this->suspended_handles_ = 0; - this->handles_to_be_added_ = 0; - this->handles_to_be_deleted_ = 0; - this->handles_to_be_suspended_ = 0; - this->handles_to_be_resumed_ = 0; - - for (size_t i = 0; i < size; ++i) - this->current_handles_[i] = ACE_INVALID_HANDLE; - - return 0; -} - -ACE_WFMO_Reactor_Handler_Repository::~ACE_WFMO_Reactor_Handler_Repository (void) -{ - // Free up dynamically allocated space - delete [] this->current_handles_; - delete [] this->current_info_; - delete [] this->current_suspended_info_; - delete [] this->to_be_added_info_; -} - -ACE_Reactor_Mask -ACE_WFMO_Reactor_Handler_Repository::bit_ops (long &existing_masks, - ACE_Reactor_Mask change_masks, - int operation) -{ - // Find the old reactor masks. This automatically does the work of - // the GET_MASK operation. - - ACE_Reactor_Mask old_masks = ACE_Event_Handler::NULL_MASK; - - if (ACE_BIT_ENABLED (existing_masks, FD_READ) - || ACE_BIT_ENABLED (existing_masks, FD_CLOSE)) - ACE_SET_BITS (old_masks, ACE_Event_Handler::READ_MASK); - - if (ACE_BIT_ENABLED (existing_masks, FD_WRITE)) - ACE_SET_BITS (old_masks, ACE_Event_Handler::WRITE_MASK); - - if (ACE_BIT_ENABLED (existing_masks, FD_OOB)) - ACE_SET_BITS (old_masks, ACE_Event_Handler::EXCEPT_MASK); - - if (ACE_BIT_ENABLED (existing_masks, FD_ACCEPT)) - ACE_SET_BITS (old_masks, ACE_Event_Handler::ACCEPT_MASK); - - if (ACE_BIT_ENABLED (existing_masks, FD_CONNECT)) - ACE_SET_BITS (old_masks, ACE_Event_Handler::CONNECT_MASK); - - if (ACE_BIT_ENABLED (existing_masks, FD_QOS)) - ACE_SET_BITS (old_masks, ACE_Event_Handler::QOS_MASK); - - if (ACE_BIT_ENABLED (existing_masks, FD_GROUP_QOS)) - ACE_SET_BITS (old_masks, ACE_Event_Handler::GROUP_QOS_MASK); - - switch (operation) - { - case ACE_Reactor::CLR_MASK: - // For the CLR_MASK operation, clear only the specific masks. - - if (ACE_BIT_ENABLED (change_masks, ACE_Event_Handler::READ_MASK)) - { - ACE_CLR_BITS (existing_masks, FD_READ); - ACE_CLR_BITS (existing_masks, FD_CLOSE); - } - - if (ACE_BIT_ENABLED (change_masks, ACE_Event_Handler::WRITE_MASK)) - ACE_CLR_BITS (existing_masks, FD_WRITE); - - if (ACE_BIT_ENABLED (change_masks, ACE_Event_Handler::EXCEPT_MASK)) - ACE_CLR_BITS (existing_masks, FD_OOB); - - if (ACE_BIT_ENABLED (change_masks, ACE_Event_Handler::ACCEPT_MASK)) - ACE_CLR_BITS (existing_masks, FD_ACCEPT); - - if (ACE_BIT_ENABLED (change_masks, ACE_Event_Handler::CONNECT_MASK)) - ACE_CLR_BITS (existing_masks, FD_CONNECT); - - if (ACE_BIT_ENABLED (change_masks, ACE_Event_Handler::QOS_MASK)) - ACE_CLR_BITS (existing_masks, FD_QOS); - - if (ACE_BIT_ENABLED (change_masks, ACE_Event_Handler::GROUP_QOS_MASK)) - ACE_CLR_BITS (existing_masks, FD_GROUP_QOS); - - break; - - case ACE_Reactor::SET_MASK: - // If the operation is a set, first reset any existing masks - - existing_masks = 0; - /* FALLTHRU */ - - case ACE_Reactor::ADD_MASK: - // For the ADD_MASK and the SET_MASK operation, add only the - // specific masks. - - if (ACE_BIT_ENABLED (change_masks, ACE_Event_Handler::READ_MASK)) - { - ACE_SET_BITS (existing_masks, FD_READ); - ACE_SET_BITS (existing_masks, FD_CLOSE); - } - - if (ACE_BIT_ENABLED (change_masks, ACE_Event_Handler::WRITE_MASK)) - ACE_SET_BITS (existing_masks, FD_WRITE); - - if (ACE_BIT_ENABLED (change_masks, ACE_Event_Handler::EXCEPT_MASK)) - ACE_SET_BITS (existing_masks, FD_OOB); - - if (ACE_BIT_ENABLED (change_masks, ACE_Event_Handler::ACCEPT_MASK)) - ACE_SET_BITS (existing_masks, FD_ACCEPT); - - if (ACE_BIT_ENABLED (change_masks, ACE_Event_Handler::CONNECT_MASK)) - ACE_SET_BITS (existing_masks, FD_CONNECT); - - if (ACE_BIT_ENABLED (change_masks, ACE_Event_Handler::QOS_MASK)) - ACE_SET_BITS (existing_masks, FD_QOS); - - if (ACE_BIT_ENABLED (change_masks, ACE_Event_Handler::GROUP_QOS_MASK)) - ACE_SET_BITS (existing_masks, FD_GROUP_QOS); - - break; - - case ACE_Reactor::GET_MASK: - - // The work for this operation is done in all cases at the - // begining of the function. - - ACE_UNUSED_ARG (change_masks); - - break; - } - - return old_masks; -} - -int -ACE_WFMO_Reactor_Handler_Repository::unbind_i (ACE_HANDLE handle, - ACE_Reactor_Mask mask, - bool &changes_required) -{ - int error = 0; - - // Remember this value; only if it changes do we need to wakeup - // the other threads - size_t const original_handle_count = this->handles_to_be_deleted_; - size_t i; - - // Go through all the handles looking for . Even if we find - // it, we continue through the rest of the list since could - // appear multiple times. All handles are checked. - - // First check the current entries - for (i = 0; i < this->max_handlep1_ && error == 0; ++i) - // Since the handle can either be the event or the I/O handle, - // we have to check both - if ((this->current_handles_[i] == handle - || this->current_info_[i].io_handle_ == handle) - && // Make sure that it is not already marked for deleted - !this->current_info_[i].delete_entry_) - { - if (this->remove_handler_i (i, mask) == -1) - error = 1; - } - - // Then check the suspended entries - for (i = 0; i < this->suspended_handles_ && error == 0; ++i) - // Since the handle can either be the event or the I/O handle, we - // have to check both - if ((this->current_suspended_info_[i].io_handle_ == handle - || this->current_suspended_info_[i].event_handle_ == handle) - && - // Make sure that it is not already marked for deleted - !this->current_suspended_info_[i].delete_entry_) - { - if (this->remove_suspended_handler_i (i, mask) == -1) - error = 1; - } - - // Then check the to_be_added entries - for (i = 0; i < this->handles_to_be_added_ && error == 0; ++i) - // Since the handle can either be the event or the I/O handle, - // we have to check both - if ((this->to_be_added_info_[i].io_handle_ == handle - || this->to_be_added_info_[i].event_handle_ == handle) - && - // Make sure that it is not already marked for deleted - !this->to_be_added_info_[i].delete_entry_) - { - if (this->remove_to_be_added_handler_i (i, mask) == -1) - error = 1; - } - - // Only if the number of handlers to be deleted changes do we need - // to wakeup the other threads - if (original_handle_count < this->handles_to_be_deleted_) - changes_required = true; - - return error ? -1 : 0; -} - -int -ACE_WFMO_Reactor_Handler_Repository::remove_handler_i (size_t slot, - ACE_Reactor_Mask to_be_removed_masks) -{ - // I/O entries - if (this->current_info_[slot].io_entry_) - { - // See if there are other events that the is - // interested in - this->bit_ops (this->current_info_[slot].network_events_, - to_be_removed_masks, - ACE_Reactor::CLR_MASK); - - // Disassociate/Reassociate the event from/with the I/O handle. - // This will depend on the value of remaining set of network - // events that the is interested in. I don't - // think we can do anything about errors here, so I will not - // check this. - ::WSAEventSelect ((SOCKET) this->current_info_[slot].io_handle_, - this->current_handles_[slot], - this->current_info_[slot].network_events_); - } - // Normal event entries. - else if (ACE_BIT_ENABLED (to_be_removed_masks, ACE_Event_Handler::DONT_CALL)) - // Preserve DONT_CALL - to_be_removed_masks = ACE_Event_Handler::DONT_CALL; - else - // Make sure that the is the NULL_MASK - to_be_removed_masks = ACE_Event_Handler::NULL_MASK; - - // If this event was marked for suspension, undo the suspension flag - // and reduce the to be suspended count. - if (this->current_info_[slot].suspend_entry_) - { - // Undo suspension - this->current_info_[slot].suspend_entry_ = false; - // Decrement the handle count - --this->handles_to_be_suspended_; - } - - // If there are no more events that the is - // interested in, or this is a non-I/O entry, schedule the - // for removal - if (this->current_info_[slot].network_events_ == 0) - { - // Mark to be deleted - this->current_info_[slot].delete_entry_ = true; - // Remember the mask - this->current_info_[slot].close_masks_ = to_be_removed_masks; - // Increment the handle count - ++this->handles_to_be_deleted_; - } - - // Since it is not a complete removal, we'll call handle_close - // for all the masks that were removed. This does not change - // the internal state of the reactor. - // - // Note: this condition only applies to I/O entries - else if (ACE_BIT_ENABLED (to_be_removed_masks, ACE_Event_Handler::DONT_CALL) == 0) - { - ACE_HANDLE handle = this->current_info_[slot].io_handle_; - this->current_info_[slot].event_handler_->handle_close (handle, - to_be_removed_masks); - } - - return 0; -} - -int -ACE_WFMO_Reactor_Handler_Repository::remove_suspended_handler_i (size_t slot, - ACE_Reactor_Mask to_be_removed_masks) -{ - // I/O entries - if (this->current_suspended_info_[slot].io_entry_) - { - // See if there are other events that the is - // interested in - this->bit_ops (this->current_suspended_info_[slot].network_events_, - to_be_removed_masks, - ACE_Reactor::CLR_MASK); - - // Disassociate/Reassociate the event from/with the I/O handle. - // This will depend on the value of remaining set of network - // events that the is interested in. I don't - // think we can do anything about errors here, so I will not - // check this. - ::WSAEventSelect ((SOCKET) this->current_suspended_info_[slot].io_handle_, - this->current_suspended_info_[slot].event_handle_, - this->current_suspended_info_[slot].network_events_); - } - // Normal event entries. - else if (ACE_BIT_ENABLED (to_be_removed_masks, ACE_Event_Handler::DONT_CALL)) - // Preserve DONT_CALL - to_be_removed_masks = ACE_Event_Handler::DONT_CALL; - else - // Make sure that the is the NULL_MASK - to_be_removed_masks = ACE_Event_Handler::NULL_MASK; - - // If this event was marked for resumption, undo the resumption flag - // and reduce the to be resumed count. - if (this->current_suspended_info_[slot].resume_entry_) - { - // Undo resumption - this->current_suspended_info_[slot].resume_entry_ = false; - // Decrement the handle count - --this->handles_to_be_resumed_; - } - - // If there are no more events that the is - // interested in, or this is a non-I/O entry, schedule the - // for removal - if (this->current_suspended_info_[slot].network_events_ == 0) - { - // Mark to be deleted - this->current_suspended_info_[slot].delete_entry_ = true; - // Remember the mask - this->current_suspended_info_[slot].close_masks_ = to_be_removed_masks; - // Increment the handle count - ++this->handles_to_be_deleted_; - } - // Since it is not a complete removal, we'll call handle_close for - // all the masks that were removed. This does not change the - // internal state of the reactor. - // - // Note: this condition only applies to I/O entries - else if (ACE_BIT_ENABLED (to_be_removed_masks, ACE_Event_Handler::DONT_CALL) == 0) - { - ACE_HANDLE handle = this->current_suspended_info_[slot].io_handle_; - this->current_suspended_info_[slot].event_handler_->handle_close (handle, - to_be_removed_masks); - } - - return 0; -} - -int -ACE_WFMO_Reactor_Handler_Repository::remove_to_be_added_handler_i (size_t slot, - ACE_Reactor_Mask to_be_removed_masks) -{ - // I/O entries - if (this->to_be_added_info_[slot].io_entry_) - { - // See if there are other events that the is - // interested in - this->bit_ops (this->to_be_added_info_[slot].network_events_, - to_be_removed_masks, - ACE_Reactor::CLR_MASK); - - // Disassociate/Reassociate the event from/with the I/O handle. - // This will depend on the value of remaining set of network - // events that the is interested in. I don't - // think we can do anything about errors here, so I will not - // check this. - ::WSAEventSelect ((SOCKET) this->to_be_added_info_[slot].io_handle_, - this->to_be_added_info_[slot].event_handle_, - this->to_be_added_info_[slot].network_events_); - } - // Normal event entries. - else if (ACE_BIT_ENABLED (to_be_removed_masks, ACE_Event_Handler::DONT_CALL)) - // Preserve DONT_CALL - to_be_removed_masks = ACE_Event_Handler::DONT_CALL; - else - // Make sure that the is the NULL_MASK - to_be_removed_masks = ACE_Event_Handler::NULL_MASK; - - // If this event was marked for suspension, undo the suspension flag - // and reduce the to be suspended count. - if (this->to_be_added_info_[slot].suspend_entry_) - { - // Undo suspension - this->to_be_added_info_[slot].suspend_entry_ = false; - // Decrement the handle count - --this->handles_to_be_suspended_; - } - - // If there are no more events that the is - // interested in, or this is a non-I/O entry, schedule the - // for removal - if (this->to_be_added_info_[slot].network_events_ == 0) - { - // Mark to be deleted - this->to_be_added_info_[slot].delete_entry_ = true; - // Remember the mask - this->to_be_added_info_[slot].close_masks_ = to_be_removed_masks; - // Increment the handle count - ++this->handles_to_be_deleted_; - } - // Since it is not a complete removal, we'll call handle_close - // for all the masks that were removed. This does not change - // the internal state of the reactor. - // - // Note: this condition only applies to I/O entries - else if (ACE_BIT_ENABLED (to_be_removed_masks, ACE_Event_Handler::DONT_CALL) == 0) - { - ACE_HANDLE handle = this->to_be_added_info_[slot].io_handle_; - this->to_be_added_info_[slot].event_handler_->handle_close (handle, - to_be_removed_masks); - } - - return 0; -} - -int -ACE_WFMO_Reactor_Handler_Repository::suspend_handler_i (ACE_HANDLE handle, - bool &changes_required) -{ - size_t i = 0; - - // Go through all the handles looking for . Even if we find - // it, we continue through the rest of the list since could - // appear multiple times. All handles are checked. - - // Check the current entries first. - for (i = 0; i < this->max_handlep1_; ++i) - // Since the handle can either be the event or the I/O handle, - // we have to check both - if ((this->current_handles_[i] == handle || - this->current_info_[i].io_handle_ == handle) && - // Make sure that it is not already marked for suspension - !this->current_info_[i].suspend_entry_) - { - // Mark to be suspended - this->current_info_[i].suspend_entry_ = true; - // Increment the handle count - ++this->handles_to_be_suspended_; - // Changes will be required - changes_required = true; - } - - // Then check the suspended entries. - for (i = 0; i < this->suspended_handles_; ++i) - // Since the handle can either be the event or the I/O handle, - // we have to check both - if ((this->current_suspended_info_[i].event_handle_ == handle || - this->current_suspended_info_[i].io_handle_ == handle) && - // Make sure that the resumption is not already undone - this->current_suspended_info_[i].resume_entry_) - { - // Undo resumption - this->current_suspended_info_[i].resume_entry_ = false; - // Decrement the handle count - --this->handles_to_be_resumed_; - // Changes will be required - changes_required = true; - } - - // Then check the to_be_added entries. - for (i = 0; i < this->handles_to_be_added_; ++i) - // Since the handle can either be the event or the I/O handle, - // we have to check both - if ((this->to_be_added_info_[i].io_handle_ == handle || - this->to_be_added_info_[i].event_handle_ == handle) && - // Make sure that it is not already marked for suspension - !this->to_be_added_info_[i].suspend_entry_) - { - // Mark to be suspended - this->to_be_added_info_[i].suspend_entry_ = true; - // Increment the handle count - ++this->handles_to_be_suspended_; - // Changes will be required - changes_required = true; - } - - return 0; -} - -int -ACE_WFMO_Reactor_Handler_Repository::resume_handler_i (ACE_HANDLE handle, - bool &changes_required) -{ - size_t i = 0; - - // Go through all the handles looking for . Even if we find - // it, we continue through the rest of the list since could - // appear multiple times. All handles are checked. - - // Check the current entries first. - for (i = 0; i < this->max_handlep1_; ++i) - // Since the handle can either be the event or the I/O handle, - // we have to check both - if ((this->current_handles_[i] == handle || - this->current_info_[i].io_handle_ == handle) && - // Make sure that the suspension is not already undone - this->current_info_[i].suspend_entry_) - { - // Undo suspension - this->current_info_[i].suspend_entry_ = false; - // Decrement the handle count - --this->handles_to_be_suspended_; - // Changes will be required - changes_required = true; - } - - // Then check the suspended entries. - for (i = 0; i < this->suspended_handles_; ++i) - // Since the handle can either be the event or the I/O handle, - // we have to check both - if ((this->current_suspended_info_[i].event_handle_ == handle || - this->current_suspended_info_[i].io_handle_ == handle) && - // Make sure that it is not already marked for resumption - !this->current_suspended_info_[i].resume_entry_) - { - // Mark to be resumed - this->current_suspended_info_[i].resume_entry_ = true; - // Increment the handle count - ++this->handles_to_be_resumed_; - // Changes will be required - changes_required = true; - } - - // Then check the to_be_added entries. - for (i = 0; i < this->handles_to_be_added_; ++i) - // Since the handle can either be the event or the I/O handle, - // we have to check both - if ((this->to_be_added_info_[i].io_handle_ == handle || - this->to_be_added_info_[i].event_handle_ == handle) && - // Make sure that the suspension is not already undone - this->to_be_added_info_[i].suspend_entry_) - { - // Undo suspension - this->to_be_added_info_[i].suspend_entry_ = false; - // Decrement the handle count - --this->handles_to_be_suspended_; - // Changes will be required - changes_required = true; - } - - return 0; -} - -void -ACE_WFMO_Reactor_Handler_Repository::unbind_all (void) -{ - { - ACE_GUARD (ACE_Process_Mutex, ace_mon, this->wfmo_reactor_.lock_); - - bool dummy; - size_t i; - - // Remove all the current handlers - for (i = 0; i < this->max_handlep1_; ++i) - this->unbind_i (this->current_handles_[i], - ACE_Event_Handler::ALL_EVENTS_MASK, - dummy); - - // Remove all the suspended handlers - for (i = 0; i < this->suspended_handles_; ++i) - this->unbind_i (this->current_suspended_info_[i].event_handle_, - ACE_Event_Handler::ALL_EVENTS_MASK, - dummy); - - // Remove all the to_be_added handlers - for (i = 0; i < this->handles_to_be_added_; ++i) - this->unbind_i (this->to_be_added_info_[i].event_handle_, - ACE_Event_Handler::ALL_EVENTS_MASK, - dummy); - } - - // The guard is released here - - // Wake up all threads in WaitForMultipleObjects so that they can - // reconsult the handle set - this->wfmo_reactor_.wakeup_all_threads (); -} - -int -ACE_WFMO_Reactor_Handler_Repository::bind_i (bool io_entry, - ACE_Event_Handler *event_handler, - long network_events, - ACE_HANDLE io_handle, - ACE_HANDLE event_handle, - bool delete_event) -{ - if (event_handler == 0) - return -1; - - // Make sure that the is valid - if (event_handle == ACE_INVALID_HANDLE) - event_handle = event_handler->get_handle (); - if (this->invalid_handle (event_handle)) - return -1; - - size_t current_size = this->max_handlep1_ + - this->handles_to_be_added_ - - this->handles_to_be_deleted_ + - this->suspended_handles_; - - // Make sure that there's room in the table and that total pending - // additions should not exceed what the array - // can hold. - if (current_size < this->max_size_ && - this->handles_to_be_added_ < this->max_size_) - { - // Cache this set into the , till we come - // around to actually adding this to the - this->to_be_added_info_[this->handles_to_be_added_].set (event_handle, - io_entry, - event_handler, - io_handle, - network_events, - delete_event); - - ++this->handles_to_be_added_; - - event_handler->add_reference (); - - // Wake up all threads in WaitForMultipleObjects so that they can - // reconsult the handle set - this->wfmo_reactor_.wakeup_all_threads (); - } - else - { - errno = EMFILE; // File descriptor table is full (better than nothing) - return -1; - } - - return 0; -} - -int -ACE_WFMO_Reactor_Handler_Repository::make_changes_in_current_infos (void) -{ - // Go through the entire valid array and check for all handles that - // have been schedule for deletion - if (this->handles_to_be_deleted_ > 0 || this->handles_to_be_suspended_ > 0) - { - size_t i = 0; - while (i < this->max_handlep1_) - { - // This stuff is necessary here, since we should not make - // the upcall until all the internal data structures have - // been updated. This is to protect against upcalls that - // try to deregister again. - ACE_HANDLE handle = ACE_INVALID_HANDLE; - ACE_Reactor_Mask masks = ACE_Event_Handler::NULL_MASK; - ACE_Event_Handler *event_handler = 0; - - // See if this entry is scheduled for deletion - if (this->current_info_[i].delete_entry_) - { - // Calling the method here will ensure that we - // will only call it once per deregistering . - // This is essential in the case when the will - // do something like delete itself and we have multiple - // threads in WFMO_Reactor. - // - // Make sure that the DONT_CALL mask is not set - masks = this->current_info_[i].close_masks_; - if (ACE_BIT_ENABLED (masks, ACE_Event_Handler::DONT_CALL) == 0) - { - // Grab the correct handle depending on the type entry - if (this->current_info_[i].io_entry_) - handle = this->current_info_[i].io_handle_; - else - handle = this->current_handles_[i]; - - // Event handler - event_handler = this->current_info_[i].event_handler_; - } - - // If created the event, we need to clean it up - if (this->current_info_[i].delete_event_) - ACE_OS::event_destroy (&this->current_handles_[i]); - - // Reduce count by one - --this->handles_to_be_deleted_; - } - - // See if this entry is scheduled for suspension - else if (this->current_info_[i].suspend_entry_) - { - this->current_suspended_info_ [this->suspended_handles_].set (this->current_handles_[i], - this->current_info_[i]); - // Increase number of suspended handles - ++this->suspended_handles_; - - // Reduce count by one - --this->handles_to_be_suspended_; - } - - // See if this entry is scheduled for deletion or suspension - // If so we need to clean up - if (this->current_info_[i].delete_entry_ || - this->current_info_[i].suspend_entry_ ) - { - size_t last_valid_slot = this->max_handlep1_ - 1; - // If this is the last handle in the set, no need to swap - // places. Simply remove it. - if (i < last_valid_slot) - // Swap this handle with the last valid handle - { - // Struct copy - this->current_info_[i] = - this->current_info_[last_valid_slot]; - this->current_handles_[i] = - this->current_handles_[last_valid_slot]; - } - // Reset the info in this slot - this->current_info_[last_valid_slot].reset (); - this->current_handles_[last_valid_slot] = ACE_INVALID_HANDLE; - --this->max_handlep1_; - } - else - { - // This current entry is not up for deletion or - // suspension. Proceed to the next entry in the current - // handles. - ++i; - } - - // Now that all internal structures have been updated, make - // the upcall. - if (event_handler != 0) - { - bool const requires_reference_counting = - event_handler->reference_counting_policy ().value () == - ACE_Event_Handler::Reference_Counting_Policy::ENABLED; - - event_handler->handle_close (handle, masks); - - if (requires_reference_counting) - { - event_handler->remove_reference (); - } - } - } - } - - return 0; -} - -int -ACE_WFMO_Reactor_Handler_Repository::make_changes_in_suspension_infos (void) -{ - // Go through the array - if (this->handles_to_be_deleted_ > 0 || this->handles_to_be_resumed_ > 0) - { - size_t i = 0; - while (i < this->suspended_handles_) - { - // This stuff is necessary here, since we should not make - // the upcall until all the internal data structures have - // been updated. This is to protect against upcalls that - // try to deregister again. - ACE_HANDLE handle = ACE_INVALID_HANDLE; - ACE_Reactor_Mask masks = ACE_Event_Handler::NULL_MASK; - ACE_Event_Handler *event_handler = 0; - - // See if this entry is scheduled for deletion - if (this->current_suspended_info_[i].delete_entry_) - { - // Calling the method here will ensure that we - // will only call it once per deregistering . - // This is essential in the case when the will - // do something like delete itself and we have multiple - // threads in WFMO_Reactor. - // - // Make sure that the DONT_CALL mask is not set - masks = this->current_suspended_info_[i].close_masks_; - if (ACE_BIT_ENABLED (masks, ACE_Event_Handler::DONT_CALL) == 0) - { - // Grab the correct handle depending on the type entry - if (this->current_suspended_info_[i].io_entry_) - handle = this->current_suspended_info_[i].io_handle_; - else - handle = this->current_suspended_info_[i].event_handle_; - - // Upcall - event_handler = this->current_suspended_info_[i].event_handler_; - } - - // If created the event, we need to clean it up - if (this->current_suspended_info_[i].delete_event_) - ACE_OS::event_destroy (&this->current_suspended_info_[i].event_handle_); - - // Reduce count by one - --this->handles_to_be_deleted_; - } - - else if (this->current_suspended_info_[i].resume_entry_) - { - // Add to the end of the current handles set - this->current_handles_[this->max_handlep1_] = this->current_suspended_info_[i].event_handle_; - // Struct copy - this->current_info_[this->max_handlep1_].set (this->current_suspended_info_[i]); - ++this->max_handlep1_; - - // Reduce count by one - --this->handles_to_be_resumed_; - } - - // If an entry needs to be removed, either because it - // was deleted or resumed, remove it now before doing - // the upcall. - if (this->current_suspended_info_[i].resume_entry_ || - this->current_suspended_info_[i].delete_entry_) - { - size_t last_valid_slot = this->suspended_handles_ - 1; - // Net effect is that we're removing an entry and - // compressing the list from the end. So, if removing - // an entry from the middle, copy the last valid one to the - // removed slot. Reset the end and decrement the number - // of suspended handles. - if (i < last_valid_slot) - // Struct copy - this->current_suspended_info_[i] = - this->current_suspended_info_[last_valid_slot]; - this->current_suspended_info_[last_valid_slot].reset (); - --this->suspended_handles_; - } - else - { - // This current entry is not up for deletion or - // resumption. Proceed to the next entry in the - // suspended handles. - ++i; - } - - // Now that all internal structures have been updated, make - // the upcall. - if (event_handler != 0) - { - int requires_reference_counting = - event_handler->reference_counting_policy ().value () == - ACE_Event_Handler::Reference_Counting_Policy::ENABLED; - - event_handler->handle_close (handle, masks); - - if (requires_reference_counting) - { - event_handler->remove_reference (); - } - } - } - } - - return 0; -} - -int -ACE_WFMO_Reactor_Handler_Repository::make_changes_in_to_be_added_infos (void) -{ - // Go through the arrays - for (size_t i = 0; i < this->handles_to_be_added_; ++i) - { - // This stuff is necessary here, since we should not make - // the upcall until all the internal data structures have - // been updated. This is to protect against upcalls that - // try to deregister again. - ACE_HANDLE handle = ACE_INVALID_HANDLE; - ACE_Reactor_Mask masks = ACE_Event_Handler::NULL_MASK; - ACE_Event_Handler *event_handler = 0; - - // See if this entry is scheduled for deletion - if (this->to_be_added_info_[i].delete_entry_) - { - // Calling the method here will ensure that we - // will only call it once per deregistering . - // This is essential in the case when the will - // do something like delete itself and we have multiple - // threads in WFMO_Reactor. - // - // Make sure that the DONT_CALL mask is not set - masks = this->to_be_added_info_[i].close_masks_; - if (ACE_BIT_ENABLED (masks, ACE_Event_Handler::DONT_CALL) == 0) - { - // Grab the correct handle depending on the type entry - if (this->to_be_added_info_[i].io_entry_) - handle = this->to_be_added_info_[i].io_handle_; - else - handle = this->to_be_added_info_[i].event_handle_; - - // Upcall - event_handler = this->to_be_added_info_[i].event_handler_; - } - - // If created the event, we need to clean it up - if (this->to_be_added_info_[i].delete_event_) - ACE_OS::event_destroy (&this->to_be_added_info_[i].event_handle_); - - // Reduce count by one - --this->handles_to_be_deleted_; - } - - // See if this entry is scheduled for suspension - else if (this->to_be_added_info_[i].suspend_entry_) - { - this->current_suspended_info_ [this->suspended_handles_].set (this->to_be_added_info_[i].event_handle_, - this->to_be_added_info_[i]); - // Increase number of suspended handles - ++this->suspended_handles_; - - // Reduce count by one - --this->handles_to_be_suspended_; - } - - // If neither of the two flags are on, add to current - else - { - // Add to the end of the current handles set - this->current_handles_[this->max_handlep1_] = this->to_be_added_info_[i].event_handle_; - // Struct copy - this->current_info_[this->max_handlep1_].set (this->to_be_added_info_[i]); - ++this->max_handlep1_; - } - - // Reset the - this->to_be_added_info_[i].reset (); - - // Now that all internal structures have been updated, make the - // upcall. - if (event_handler != 0) - { - int requires_reference_counting = - event_handler->reference_counting_policy ().value () == - ACE_Event_Handler::Reference_Counting_Policy::ENABLED; - - event_handler->handle_close (handle, masks); - - if (requires_reference_counting) - { - event_handler->remove_reference (); - } - } - } - - // Since all to be added handles have been taken care of, reset the - // counter - this->handles_to_be_added_ = 0; - - return 0; -} - -void -ACE_WFMO_Reactor_Handler_Repository::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - size_t i = 0; - - ACE_TRACE ("ACE_WFMO_Reactor_Handler_Repository::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("Max size = %d\n"), - this->max_size_)); - - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("Current info table\n\n"))); - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("\tSize = %d\n"), - this->max_handlep1_)); - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("\tHandles to be suspended = %d\n"), - this->handles_to_be_suspended_)); - - for (i = 0; i < this->max_handlep1_; ++i) - this->current_info_[i].dump (this->current_handles_[i]); - - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("\n"))); - - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("To-be-added info table\n\n"))); - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("\tSize = %d\n"), - this->handles_to_be_added_)); - - for (i = 0; i < this->handles_to_be_added_; ++i) - this->to_be_added_info_[i].dump (); - - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("\n"))); - - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("Suspended info table\n\n"))); - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("\tSize = %d\n"), - this->suspended_handles_)); - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("\tHandles to be resumed = %d\n"), - this->handles_to_be_resumed_)); - - for (i = 0; i < this->suspended_handles_; ++i) - this->current_suspended_info_[i].dump (); - - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("\n"))); - - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("Total handles to be deleted = %d\n"), - this->handles_to_be_deleted_)); - - ACE_DEBUG ((LM_DEBUG, - ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -/************************************************************/ - -int -ACE_WFMO_Reactor::work_pending (const ACE_Time_Value &) -{ - ACE_NOTSUP_RETURN (-1); -} - -#if defined (ACE_WIN32_VC8) -# pragma warning (push) -# pragma warning (disable:4355) /* Use of 'this' in initializer list */ -# endif -ACE_WFMO_Reactor::ACE_WFMO_Reactor (ACE_Sig_Handler *sh, - ACE_Timer_Queue *tq, - ACE_Reactor_Notify *notify) - : signal_handler_ (0), - delete_signal_handler_ (false), - timer_queue_ (0), - delete_timer_queue_ (false), - delete_handler_rep_ (false), - notify_handler_ (0), - delete_notify_handler_ (false), - lock_adapter_ (lock_), - handler_rep_ (*this), - // this event is initially signaled - ok_to_wait_ (1), - // this event is initially unsignaled - wakeup_all_threads_ (0), - // this event is initially unsignaled - waiting_to_change_state_ (0), - active_threads_ (0), - owner_ (ACE_Thread::self ()), - new_owner_ (0), - change_state_thread_ (0), - open_for_business_ (false), - deactivated_ (0) -{ - if (this->open (ACE_WFMO_Reactor::DEFAULT_SIZE, 0, sh, tq, 0, notify) == -1) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("WFMO_Reactor"))); -} - -ACE_WFMO_Reactor::ACE_WFMO_Reactor (size_t size, - int unused, - ACE_Sig_Handler *sh, - ACE_Timer_Queue *tq, - ACE_Reactor_Notify *notify) - : signal_handler_ (0), - delete_signal_handler_ (false), - timer_queue_ (0), - delete_timer_queue_ (false), - delete_handler_rep_ (false), - notify_handler_ (0), - delete_notify_handler_ (false), - lock_adapter_ (lock_), - handler_rep_ (*this), - // this event is initially signaled - ok_to_wait_ (1), - // this event is initially unsignaled - wakeup_all_threads_ (0), - // this event is initially unsignaled - waiting_to_change_state_ (0), - active_threads_ (0), - owner_ (ACE_Thread::self ()), - new_owner_ (0), - change_state_thread_ (0), - open_for_business_ (false), - deactivated_ (0) -{ - ACE_UNUSED_ARG (unused); - - if (this->open (size, 0, sh, tq, 0, notify) == -1) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("WFMO_Reactor"))); -} -#if defined (ACE_WIN32_VC8) -# pragma warning (pop) -#endif - -int -ACE_WFMO_Reactor::current_info (ACE_HANDLE, size_t &) -{ - return -1; -} - -int -ACE_WFMO_Reactor::open (size_t size, - bool, - ACE_Sig_Handler *sh, - ACE_Timer_Queue *tq, - int, - ACE_Reactor_Notify *notify) -{ - // This GUARD is necessary since we are updating shared state. - ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); - - // If we are already open, return -1 - if (this->open_for_business_) - return -1; - - // Timer Queue - if (this->delete_timer_queue_) - delete this->timer_queue_; - - if (tq == 0) - { - ACE_NEW_RETURN (this->timer_queue_, - ACE_Timer_Heap, - -1); - this->delete_timer_queue_ = true; - } - else - { - this->timer_queue_ = tq; - this->delete_timer_queue_ = false; - } - - // Signal Handler - if (this->delete_signal_handler_) - delete this->signal_handler_; - - if (sh == 0) - { - ACE_NEW_RETURN (this->signal_handler_, - ACE_Sig_Handler, - -1); - this->delete_signal_handler_ = true; - } - else - { - this->signal_handler_ = sh; - this->delete_signal_handler_ = false; - } - - // Setup the atomic wait array (used later in ) - this->atomic_wait_array_[0] = this->lock_.lock ().proc_mutex_; - this->atomic_wait_array_[1] = this->ok_to_wait_.handle (); - - // Prevent memory leaks when the ACE_WFMO_Reactor is reopened. - if (this->delete_handler_rep_) - { - if (this->handler_rep_.changes_required ()) - { - // Make necessary changes to the handler repository - this->handler_rep_.make_changes (); - // Turn off since all necessary changes - // have completed - this->wakeup_all_threads_.reset (); - } - - this->handler_rep_.~ACE_WFMO_Reactor_Handler_Repository (); - } - - // Open the handle repository. Two additional handles for internal - // purposes - if (this->handler_rep_.open (size + 2) == -1) - ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"), - ACE_TEXT ("opening handler repository")), - -1); - else - this->delete_handler_rep_ = true; - - if (this->notify_handler_ != 0 && this->delete_notify_handler_) - delete this->notify_handler_; - - this->notify_handler_ = notify; - - if (this->notify_handler_ == 0) - { - ACE_NEW_RETURN (this->notify_handler_, - ACE_WFMO_Reactor_Notify, - -1); - - if (this->notify_handler_ == 0) - return -1; - else - this->delete_notify_handler_ = true; - } - - /* NOTE */ - // The order of the following two registrations is very important - - // Open the notification handler - if (this->notify_handler_->open (this, this->timer_queue_) == -1) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("opening notify handler ")), - -1); - - // Register for event - if (this->register_handler (&this->wakeup_all_threads_handler_, - this->wakeup_all_threads_.handle ()) == -1) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("registering thread wakeup handler")), - -1); - - // Since we have added two handles into the handler repository, - // update the - if (this->handler_rep_.changes_required ()) - { - // Make necessary changes to the handler repository - this->handler_rep_.make_changes (); - // Turn off since all necessary changes - // have completed - this->wakeup_all_threads_.reset (); - } - - // We are open for business - this->open_for_business_ = true; - - return 0; -} - -int -ACE_WFMO_Reactor::set_sig_handler (ACE_Sig_Handler *signal_handler) -{ - if (this->signal_handler_ != 0 && this->delete_signal_handler_) - delete this->signal_handler_; - this->signal_handler_ = signal_handler; - this->delete_signal_handler_ = false; - return 0; -} - -ACE_Timer_Queue * -ACE_WFMO_Reactor::timer_queue (void) const -{ - return this->timer_queue_; -} - -int -ACE_WFMO_Reactor::timer_queue (ACE_Timer_Queue *tq) -{ - if (this->timer_queue_ != 0 && this->delete_timer_queue_) - delete this->timer_queue_; - this->timer_queue_ = tq; - this->delete_timer_queue_ = false; - return 0; -} - -int -ACE_WFMO_Reactor::close (void) -{ - // This GUARD is necessary since we are updating shared state. - ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); - - // If we are already closed, return error - if (!this->open_for_business_) - return -1; - - // We are now closed - this->open_for_business_ = false; - // This will unregister all handles - this->handler_rep_.close (); - - return 0; -} - -ACE_WFMO_Reactor::~ACE_WFMO_Reactor (void) -{ - // Assumption: No threads are left in the Reactor when this method - // is called (i.e., active_threads_ == 0) - - // Close down - this->close (); - - // Make necessary changes to the handler repository that we caused - // by . - this->handler_rep_.make_changes (); - - if (this->delete_timer_queue_) - { - delete this->timer_queue_; - this->timer_queue_ = 0; - this->delete_timer_queue_ = false; - } - - if (this->delete_signal_handler_) - { - delete this->signal_handler_; - this->signal_handler_ = 0; - this->delete_signal_handler_ = false; - } - - if (this->delete_notify_handler_) - { - delete this->notify_handler_; - this->notify_handler_ = 0; - this->delete_notify_handler_ = false; - } -} - -int -ACE_WFMO_Reactor::register_handler_i (ACE_HANDLE event_handle, - ACE_HANDLE io_handle, - ACE_Event_Handler *event_handler, - ACE_Reactor_Mask new_masks) -{ - // If this is a Winsock 1 system, the underlying event assignment will - // not work, so don't try. Winsock 1 must use ACE_Select_Reactor for - // reacting to socket activity. - -#if !defined (ACE_HAS_WINSOCK2) || (ACE_HAS_WINSOCK2 == 0) - - ACE_UNUSED_ARG (event_handle); - ACE_UNUSED_ARG (io_handle); - ACE_UNUSED_ARG (event_handler); - ACE_UNUSED_ARG (new_masks); - ACE_NOTSUP_RETURN (-1); - -#else - - // Make sure that the is valid - if (io_handle == ACE_INVALID_HANDLE) - io_handle = event_handler->get_handle (); - - if (this->handler_rep_.invalid_handle (io_handle)) - { - errno = ERROR_INVALID_HANDLE; - return -1; - } - - long new_network_events = 0; - bool delete_event = false; - auto_ptr event; - - // Look up the repository to see if the is already - // there. - ACE_Reactor_Mask old_masks; - int found = this->handler_rep_.modify_network_events_i (io_handle, - new_masks, - old_masks, - new_network_events, - event_handle, - delete_event, - ACE_Reactor::ADD_MASK); - - // Check to see if the user passed us a valid event; If not then we - // need to create one - if (event_handle == ACE_INVALID_HANDLE) - { - // Note: don't change this since some C++ compilers have - // s that don't work properly... - auto_ptr tmp (new ACE_Auto_Event); - event = tmp; - event_handle = event->handle (); - delete_event = true; - } - - int result = ::WSAEventSelect ((SOCKET) io_handle, - event_handle, - new_network_events); - // If we had found the there is nothing more to do - if (found) - return result; - else if (result != SOCKET_ERROR && - this->handler_rep_.bind_i (1, - event_handler, - new_network_events, - io_handle, - event_handle, - delete_event) != -1) - { - // The was not found in the repository, add to - // the repository. - if (delete_event) - { - // Clear out the handle in the ACE_Auto_Event so that when - // it is destroyed, the handle isn't closed out from under - // the reactor. After setting it, running down the event - // (via auto_ptr<> event, above) at function return will - // cause an error because it'll try to close an invalid handle. - // To avoid that smashing the errno value, save the errno - // here, explicitly remove the event so the dtor won't do it - // again, then restore errno. - ACE_Errno_Guard guard (errno); - event->handle (ACE_INVALID_HANDLE); - event->remove (); - } - return 0; - } - else - return -1; - -#endif /* ACE_HAS_WINSOCK2 || ACE_HAS_WINSOCK2 == 0 */ - -} - -int -ACE_WFMO_Reactor::mask_ops_i (ACE_HANDLE io_handle, - ACE_Reactor_Mask new_masks, - int operation) -{ - // Make sure that the is valid - if (this->handler_rep_.invalid_handle (io_handle)) - return -1; - - long new_network_events = 0; - bool delete_event = false; - ACE_HANDLE event_handle = ACE_INVALID_HANDLE; - - // Look up the repository to see if the is already - // there. - ACE_Reactor_Mask old_masks; - int found = this->handler_rep_.modify_network_events_i (io_handle, - new_masks, - old_masks, - new_network_events, - event_handle, - delete_event, - operation); - if (found) - { - int result = ::WSAEventSelect ((SOCKET) io_handle, - event_handle, - new_network_events); - if (result == 0) - return old_masks; - else - return result; - } - else - return -1; -} - - - -int -ACE_WFMO_Reactor_Handler_Repository::modify_network_events_i (ACE_HANDLE io_handle, - ACE_Reactor_Mask new_masks, - ACE_Reactor_Mask &old_masks, - long &new_network_events, - ACE_HANDLE &event_handle, - bool &delete_event, - int operation) -{ - long *modified_network_events = &new_network_events; - int found = 0; - size_t i; - - // First go through the current entries - // - // Look for all entries in the current handles for matching handle - // (except those that have been scheduled for deletion) - for (i = 0; i < this->max_handlep1_ && !found; ++i) - if (io_handle == this->current_info_[i].io_handle_ && - !this->current_info_[i].delete_entry_) - { - found = 1; - modified_network_events = &this->current_info_[i].network_events_; - delete_event = this->current_info_[i].delete_event_; - event_handle = this->current_handles_[i]; - } - - // Then pass through the suspended handles - // - // Look for all entries in the suspended handles for matching handle - // (except those that have been scheduled for deletion) - for (i = 0; i < this->suspended_handles_ && !found; ++i) - if (io_handle == this->current_suspended_info_[i].io_handle_ && - !this->current_suspended_info_[i].delete_entry_) - { - found = 1; - modified_network_events = &this->current_suspended_info_[i].network_events_; - delete_event = this->current_suspended_info_[i].delete_event_; - event_handle = this->current_suspended_info_[i].event_handle_; - } - - // Then check the to_be_added handles - // - // Look for all entries in the to_be_added handles for matching - // handle (except those that have been scheduled for deletion) - for (i = 0; i < this->handles_to_be_added_ && !found; ++i) - if (io_handle == this->to_be_added_info_[i].io_handle_ && - !this->to_be_added_info_[i].delete_entry_) - { - found = 1; - modified_network_events = &this->to_be_added_info_[i].network_events_; - delete_event = this->to_be_added_info_[i].delete_event_; - event_handle = this->to_be_added_info_[i].event_handle_; - } - - old_masks = this->bit_ops (*modified_network_events, - new_masks, - operation); - - new_network_events = *modified_network_events; - - return found; -} - -ACE_Event_Handler * -ACE_WFMO_Reactor_Handler_Repository::find_handler (ACE_HANDLE handle) -{ - long existing_masks_ignored = 0; - return this->handler (handle, existing_masks_ignored); -} - -ACE_Event_Handler * -ACE_WFMO_Reactor_Handler_Repository::handler (ACE_HANDLE handle, - long &existing_masks) -{ - int found = 0; - size_t i = 0; - ACE_Event_Handler *event_handler = 0; - existing_masks = 0; - - // Look for the handle first - - // First go through the current entries - // - // Look for all entries in the current handles for matching handle - // (except those that have been scheduled for deletion) - for (i = 0; i < this->max_handlep1_ && !found; ++i) - if ((handle == this->current_info_[i].io_handle_ || - handle == this->current_handles_[i]) && - !this->current_info_[i].delete_entry_) - { - found = 1; - event_handler = this->current_info_[i].event_handler_; - existing_masks = this->current_info_[i].network_events_; - } - - // Then pass through the suspended handles - // - // Look for all entries in the suspended handles for matching handle - // (except those that have been scheduled for deletion) - for (i = 0; i < this->suspended_handles_ && !found; ++i) - if ((handle == this->current_suspended_info_[i].io_handle_ || - handle == this->current_suspended_info_[i].event_handle_) && - !this->current_suspended_info_[i].delete_entry_) - { - found = 1; - event_handler = this->current_suspended_info_[i].event_handler_; - existing_masks = this->current_suspended_info_[i].network_events_; - } - - // Then check the to_be_added handles - // - // Look for all entries in the to_be_added handles for matching - // handle (except those that have been scheduled for deletion) - for (i = 0; i < this->handles_to_be_added_ && !found; ++i) - if ((handle == this->to_be_added_info_[i].io_handle_ || - handle == this->to_be_added_info_[i].event_handle_) && - !this->to_be_added_info_[i].delete_entry_) - { - found = 1; - event_handler = this->to_be_added_info_[i].event_handler_; - existing_masks = this->to_be_added_info_[i].network_events_; - } - - if (event_handler) - event_handler->add_reference (); - - return event_handler; -} - -int -ACE_WFMO_Reactor_Handler_Repository::handler (ACE_HANDLE handle, - ACE_Reactor_Mask user_masks, - ACE_Event_Handler **user_event_handler) -{ - long existing_masks = 0; - int found = 0; - - ACE_Event_Handler_var safe_event_handler = - this->handler (handle, - existing_masks); - - if (safe_event_handler.handler ()) - found = 1; - - if (!found) - return -1; - - // Otherwise, make sure that the masks that the user is looking for - // are on. - if (found && - ACE_BIT_ENABLED (user_masks, ACE_Event_Handler::READ_MASK)) - if (!ACE_BIT_ENABLED (existing_masks, FD_READ) && - !ACE_BIT_ENABLED (existing_masks, FD_CLOSE)) - found = 0; - - if (found && - ACE_BIT_ENABLED (user_masks, ACE_Event_Handler::WRITE_MASK)) - if (!ACE_BIT_ENABLED (existing_masks, FD_WRITE)) - found = 0; - - if (found && - ACE_BIT_ENABLED (user_masks, ACE_Event_Handler::EXCEPT_MASK)) - if (!ACE_BIT_ENABLED (existing_masks, FD_OOB)) - found = 0; - - if (found && - ACE_BIT_ENABLED (user_masks, ACE_Event_Handler::ACCEPT_MASK)) - if (!ACE_BIT_ENABLED (existing_masks, FD_ACCEPT)) - found = 0; - - if (found && - ACE_BIT_ENABLED (user_masks, ACE_Event_Handler::CONNECT_MASK)) - if (!ACE_BIT_ENABLED (existing_masks, FD_CONNECT)) - found = 0; - - if (found && - ACE_BIT_ENABLED (user_masks, ACE_Event_Handler::QOS_MASK)) - if (!ACE_BIT_ENABLED (existing_masks, FD_QOS)) - found = 0; - - if (found && - ACE_BIT_ENABLED (user_masks, ACE_Event_Handler::GROUP_QOS_MASK)) - if (!ACE_BIT_ENABLED (existing_masks, FD_GROUP_QOS)) - found = 0; - - if (found && - user_event_handler) - *user_event_handler = safe_event_handler.release (); - - if (found) - return 0; - else - return -1; -} - -// Waits for and dispatches all events. Returns -1 on error, 0 if -// max_wait_time expired, or the number of events that were dispatched. -int -ACE_WFMO_Reactor::event_handling (ACE_Time_Value *max_wait_time, - int alertable) -{ - ACE_TRACE ("ACE_WFMO_Reactor::event_handling"); - - // Make sure we are not closed - if (!this->open_for_business_ || this->deactivated_) - return -1; - - // Stash the current time -- the destructor of this object will - // automatically compute how much time elapsed since this method was - // called. - ACE_Countdown_Time countdown (max_wait_time); - - int result; - do - { - // Check to see if it is ok to enter ::WaitForMultipleObjects - // This will acquire lock_> on success On failure, the - // lock will not be acquired - result = this->ok_to_wait (max_wait_time, alertable); - if (result != 1) - return result; - - // Increment the number of active threads - ++this->active_threads_; - - // Release the - this->lock_.release (); - - // Update the countdown to reflect time waiting to play with the - // mut and event. - countdown.update (); - - // Calculate timeout - int timeout = this->calculate_timeout (max_wait_time); - - // Wait for event to happen - DWORD wait_status = this->wait_for_multiple_events (timeout, - alertable); - - // Upcall - result = this->safe_dispatch (wait_status); - if (0 == result) - { - // wait_for_multiple_events timed out without dispatching - // anything. Because of rounding and conversion errors and - // such, it could be that the wait loop timed out, but - // the timer queue said it wasn't quite ready to expire a - // timer. In this case, max_wait_time won't have quite been - // reduced to 0, and we need to go around again. If max_wait_time - // is all the way to 0, just return, as the entire time the - // caller wanted to wait has been used up. - countdown.update (); // Reflect time waiting for events - if (0 == max_wait_time || max_wait_time->usec () == 0) - break; - } - } - while (result == 0); - - return result; -} - -int -ACE_WFMO_Reactor::ok_to_wait (ACE_Time_Value *max_wait_time, - int alertable) -{ - // Calculate the max time we should spend here - // - // Note: There is really no need to involve the here - // because even if a timeout in the does expire we - // will not be able to dispatch it - - // We need to wait for both the and event. - // If not on WinCE, use WaitForMultipleObjects() to wait for both atomically. - // On WinCE, the waitAll arg to WFMO must be false, so wait for the - // ok_to_wait_ event first (since that's likely to take the longest) then - // grab the lock and recheck the ok_to_wait_ event. When we can get them - // both, or there's an error/timeout, return. -#if defined (ACE_HAS_WINCE) - ACE_UNUSED_ARG (alertable); - ACE_Time_Value timeout; - if (max_wait_time != 0) - { - timeout = ACE_OS::gettimeofday (); - timeout += *max_wait_time; - } - while (1) - { - int status; - if (max_wait_time == 0) - status = this->ok_to_wait_.wait (); - else - status = this->ok_to_wait_.wait (&timeout); - if (status == -1) - return -1; - // The event is signaled, so it's ok to wait; grab the lock and - // recheck the event. If something has changed, restart the wait. - if (max_wait_time == 0) - status = this->lock_.acquire (); - else - { - status = this->lock_.acquire (timeout); - } - if (status == -1) - return -1; - - // Have the lock_, now re-check the event. If it's not signaled, - // another thread changed something so go back and wait again. - if (this->ok_to_wait_.wait (&ACE_Time_Value::zero, 0) == 0) - break; - this->lock_.release (); - } - return 1; - -#else - int timeout = max_wait_time == 0 ? INFINITE : max_wait_time->msec (); - DWORD result = 0; - while (1) - { -# if defined (ACE_HAS_PHARLAP) - // PharLap doesn't implement WaitForMultipleObjectsEx, and doesn't - // do async I/O, so it's not needed in this case anyway. - result = ::WaitForMultipleObjects (sizeof this->atomic_wait_array_ / sizeof (ACE_HANDLE), - this->atomic_wait_array_, - TRUE, - timeout); - - if (result != WAIT_IO_COMPLETION) - break; - -# else - result = ::WaitForMultipleObjectsEx (sizeof this->atomic_wait_array_ / sizeof (ACE_HANDLE), - this->atomic_wait_array_, - TRUE, - timeout, - alertable); - - if (result != WAIT_IO_COMPLETION) - break; - -# endif /* ACE_HAS_PHARLAP */ - } - - switch (result) - { - case WAIT_TIMEOUT: - errno = ETIME; - return 0; - case WAIT_FAILED: - case WAIT_ABANDONED_0: - ACE_OS::set_errno_to_last_error (); - return -1; - default: - break; - } - - // It is ok to enter ::WaitForMultipleObjects - return 1; -#endif /* ACE_HAS_WINCE */ -} - -DWORD -ACE_WFMO_Reactor::wait_for_multiple_events (int timeout, - int alertable) -{ - // Wait for any of handles_ to be active, or until timeout expires. - // If is enabled allow asynchronous completion of - // ReadFile and WriteFile operations. - -#if defined (ACE_HAS_PHARLAP) || defined (ACE_HAS_WINCE) - // PharLap doesn't do async I/O and doesn't implement - // WaitForMultipleObjectsEx, so use WaitForMultipleObjects. - ACE_UNUSED_ARG (alertable); - return ::WaitForMultipleObjects (this->handler_rep_.max_handlep1 (), - this->handler_rep_.handles (), - FALSE, - timeout); -#else - return ::WaitForMultipleObjectsEx (this->handler_rep_.max_handlep1 (), - this->handler_rep_.handles (), - FALSE, - timeout, - alertable); -#endif /* ACE_HAS_PHARLAP */ -} - -DWORD -ACE_WFMO_Reactor::poll_remaining_handles (DWORD slot) -{ - return ::WaitForMultipleObjects (this->handler_rep_.max_handlep1 () - slot, - this->handler_rep_.handles () + slot, - FALSE, - 0); -} - -int -ACE_WFMO_Reactor::calculate_timeout (ACE_Time_Value *max_wait_time) -{ - ACE_Time_Value *time = 0; - if (this->owner_ == ACE_Thread::self ()) - time = this->timer_queue_->calculate_timeout (max_wait_time); - else - time = max_wait_time; - - if (time == 0) - return INFINITE; - else - return time->msec (); -} - - -int -ACE_WFMO_Reactor::expire_timers (void) -{ - // If "owner" thread - if (ACE_Thread::self () == this->owner_) - // expire all pending timers. - return this->timer_queue_->expire (); - - else - // Nothing to expire - return 0; -} - -int -ACE_WFMO_Reactor::dispatch (DWORD wait_status) -{ - // Expire timers - int handlers_dispatched = this->expire_timers (); - - switch (wait_status) - { - case WAIT_FAILED: // Failure. - ACE_OS::set_errno_to_last_error (); - return -1; - - case WAIT_TIMEOUT: // Timeout. - errno = ETIME; - return handlers_dispatched; - -#ifndef ACE_HAS_WINCE - case WAIT_IO_COMPLETION: // APC. - return handlers_dispatched; -#endif // ACE_HAS_WINCE - - default: // Dispatch. - // We'll let dispatch worry about abandoned mutes. - handlers_dispatched += this->dispatch_handles (wait_status); - return handlers_dispatched; - } -} - -// Dispatches any active handles from to -// , polling through our handle set looking -// for active handles. -int -ACE_WFMO_Reactor::dispatch_handles (DWORD wait_status) -{ - // dispatch_slot is the absolute slot. Only += is used to - // increment it. - DWORD dispatch_slot = 0; - - // Cache this value, this is the absolute value. - DWORD const max_handlep1 = this->handler_rep_.max_handlep1 (); - - // nCount starts off at , this is a transient count of - // handles last waited on. - DWORD nCount = max_handlep1; - - for (int number_of_handlers_dispatched = 1; - ; - ++number_of_handlers_dispatched) - { - const bool ok = ( -#if ! defined(__BORLANDC__) \ - && !defined (ghs) \ - && !defined (__MINGW32__) \ - && !defined (_MSC_VER) - // wait_status is unsigned in Borland, Green Hills, - // mingw32 and MSVC++ - // This >= is always true, with a warning. - wait_status >= WAIT_OBJECT_0 && -#endif - wait_status <= (WAIT_OBJECT_0 + nCount)); - - if (ok) - dispatch_slot += wait_status - WAIT_OBJECT_0; - else - // Otherwise, a handle was abandoned. - dispatch_slot += wait_status - WAIT_ABANDONED_0; - - // Dispatch handler - if (this->dispatch_handler (dispatch_slot, max_handlep1) == -1) - return -1; - - // Increment slot - ++dispatch_slot; - - // We're done. - if (dispatch_slot >= max_handlep1) - return number_of_handlers_dispatched; - - // Readjust nCount - nCount = max_handlep1 - dispatch_slot; - - // Check the remaining handles - wait_status = this->poll_remaining_handles (dispatch_slot); - switch (wait_status) - { - case WAIT_FAILED: // Failure. - ACE_OS::set_errno_to_last_error (); - /* FALLTHRU */ - case WAIT_TIMEOUT: - // There are no more handles ready, we can return. - return number_of_handlers_dispatched; - } - } -} - -int -ACE_WFMO_Reactor::dispatch_handler (DWORD slot, - DWORD max_handlep1) -{ - // Check if there are window messages that need to be dispatched - if (slot == max_handlep1) - return this->dispatch_window_messages (); - - // Dispatch the handler if it has not been scheduled for deletion. - // Note that this is a very week test if there are multiple threads - // dispatching this slot as no locks are held here. Generally, you - // do not want to do something like deleting the this pointer in - // handle_close() if you have registered multiple times and there is - // more than one thread in WFMO_Reactor->handle_events(). - else if (!this->handler_rep_.scheduled_for_deletion (slot)) - { - ACE_HANDLE event_handle = *(this->handler_rep_.handles () + slot); - - if (this->handler_rep_.current_info ()[slot].io_entry_) - return this->complex_dispatch_handler (slot, - event_handle); - else - return this->simple_dispatch_handler (slot, - event_handle); - } - else - // The handle was scheduled for deletion, so we will skip it. - return 0; -} - -int -ACE_WFMO_Reactor::simple_dispatch_handler (DWORD slot, - ACE_HANDLE event_handle) -{ - // This dispatch is used for non-I/O entires - - // Assign the ``signaled'' HANDLE so that callers can get it. - // siginfo_t is an ACE - specific fabrication. Constructor exists. - siginfo_t sig (event_handle); - - ACE_Event_Handler *event_handler = - this->handler_rep_.current_info ()[slot].event_handler_; - - int requires_reference_counting = - event_handler->reference_counting_policy ().value () == - ACE_Event_Handler::Reference_Counting_Policy::ENABLED; - - if (requires_reference_counting) - { - event_handler->add_reference (); - } - - // Upcall - if (event_handler->handle_signal (0, &sig) == -1) - this->handler_rep_.unbind (event_handle, - ACE_Event_Handler::NULL_MASK); - - // Call remove_reference() if needed. - if (requires_reference_counting) - { - event_handler->remove_reference (); - } - - return 0; -} - -int -ACE_WFMO_Reactor::complex_dispatch_handler (DWORD slot, - ACE_HANDLE event_handle) -{ - // This dispatch is used for I/O entires. - - ACE_WFMO_Reactor_Handler_Repository::Current_Info ¤t_info = - this->handler_rep_.current_info ()[slot]; - - WSANETWORKEVENTS events; - ACE_Reactor_Mask problems = ACE_Event_Handler::NULL_MASK; - if (::WSAEnumNetworkEvents ((SOCKET) current_info.io_handle_, - event_handle, - &events) == SOCKET_ERROR) - problems = ACE_Event_Handler::ALL_EVENTS_MASK; - else - { - // Prepare for upcalls. Clear the bits from representing - // events the handler is not interested in. If there are any left, - // do the upcall(s). upcall will replace events.lNetworkEvents - // with bits representing any functions that requested a repeat - // callback before checking handles again. In this case, continue - // to call back unless the handler is unregistered as a result of - // one of the upcalls. The way this is written, the upcalls will - // keep being done even if one or more upcalls reported problems. - // In practice this may turn out not so good, but let's see. If any - // problems, please notify Steve Huston - // before or after you change this code. - events.lNetworkEvents &= current_info.network_events_; - while (events.lNetworkEvents != 0) - { - ACE_Event_Handler *event_handler = - current_info.event_handler_; - - int reference_counting_required = - event_handler->reference_counting_policy ().value () == - ACE_Event_Handler::Reference_Counting_Policy::ENABLED; - - // Call add_reference() if needed. - if (reference_counting_required) - { - event_handler->add_reference (); - } - - // Upcall - problems |= this->upcall (current_info.event_handler_, - current_info.io_handle_, - events); - - // Call remove_reference() if needed. - if (reference_counting_required) - { - event_handler->remove_reference (); - } - - if (this->handler_rep_.scheduled_for_deletion (slot)) - break; - } - } - - if (problems != ACE_Event_Handler::NULL_MASK - && !this->handler_rep_.scheduled_for_deletion (slot) ) - this->handler_rep_.unbind (event_handle, problems); - - return 0; -} - -ACE_Reactor_Mask -ACE_WFMO_Reactor::upcall (ACE_Event_Handler *event_handler, - ACE_HANDLE io_handle, - WSANETWORKEVENTS &events) -{ - // This method figures out what exactly has happened to the socket - // and then calls appropriate methods. - ACE_Reactor_Mask problems = ACE_Event_Handler::NULL_MASK; - - // Go through the events and do the indicated upcalls. If the handler - // doesn't want to be called back, clear the bit for that event. - // At the end, set the bits back to to request a repeat call. - - long actual_events = events.lNetworkEvents; - int action; - - if (ACE_BIT_ENABLED (actual_events, FD_WRITE)) - { - action = event_handler->handle_output (io_handle); - if (action <= 0) - { - ACE_CLR_BITS (actual_events, FD_WRITE); - if (action == -1) - ACE_SET_BITS (problems, ACE_Event_Handler::WRITE_MASK); - } - } - - if (ACE_BIT_ENABLED (actual_events, FD_CONNECT)) - { - if (events.iErrorCode[FD_CONNECT_BIT] == 0) - { - // Successful connect - action = event_handler->handle_output (io_handle); - if (action <= 0) - { - ACE_CLR_BITS (actual_events, FD_CONNECT); - if (action == -1) - ACE_SET_BITS (problems, - ACE_Event_Handler::CONNECT_MASK); - } - } - // Unsuccessful connect - else - { - action = event_handler->handle_input (io_handle); - if (action <= 0) - { - ACE_CLR_BITS (actual_events, FD_CONNECT); - if (action == -1) - ACE_SET_BITS (problems, - ACE_Event_Handler::CONNECT_MASK); - } - } - } - - if (ACE_BIT_ENABLED (actual_events, FD_OOB)) - { - action = event_handler->handle_exception (io_handle); - if (action <= 0) - { - ACE_CLR_BITS (actual_events, FD_OOB); - if (action == -1) - ACE_SET_BITS (problems, ACE_Event_Handler::EXCEPT_MASK); - } - } - - if (ACE_BIT_ENABLED (actual_events, FD_READ)) - { - action = event_handler->handle_input (io_handle); - if (action <= 0) - { - ACE_CLR_BITS (actual_events, FD_READ); - if (action == -1) - ACE_SET_BITS (problems, ACE_Event_Handler::READ_MASK); - } - } - - if (ACE_BIT_ENABLED (actual_events, FD_CLOSE) - && ACE_BIT_DISABLED (problems, ACE_Event_Handler::READ_MASK)) - { - action = event_handler->handle_input (io_handle); - if (action <= 0) - { - ACE_CLR_BITS (actual_events, FD_CLOSE); - if (action == -1) - ACE_SET_BITS (problems, ACE_Event_Handler::READ_MASK); - } - } - - if (ACE_BIT_ENABLED (actual_events, FD_ACCEPT)) - { - action = event_handler->handle_input (io_handle); - if (action <= 0) - { - ACE_CLR_BITS (actual_events, FD_ACCEPT); - if (action == -1) - ACE_SET_BITS (problems, ACE_Event_Handler::ACCEPT_MASK); - } - } - - if (ACE_BIT_ENABLED (actual_events, FD_QOS)) - { - action = event_handler->handle_qos (io_handle); - if (action <= 0) - { - ACE_CLR_BITS (actual_events, FD_QOS); - if (action == -1) - ACE_SET_BITS (problems, ACE_Event_Handler::QOS_MASK); - } - } - - if (ACE_BIT_ENABLED (actual_events, FD_GROUP_QOS)) - { - action = event_handler->handle_group_qos (io_handle); - if (action <= 0) - { - ACE_CLR_BITS (actual_events, FD_GROUP_QOS); - if (action == -1) - ACE_SET_BITS (problems, ACE_Event_Handler::GROUP_QOS_MASK); - } - } - - events.lNetworkEvents = actual_events; - return problems; -} - - -int -ACE_WFMO_Reactor::update_state (void) -{ - // This GUARD is necessary since we are updating shared state. - ACE_GUARD_RETURN (ACE_Process_Mutex, monitor, this->lock_, -1); - - // Decrement active threads - --this->active_threads_; - - // Check if the state of the handler repository has changed or new - // owner has to be set - if (this->handler_rep_.changes_required () || this->new_owner ()) - { - if (this->change_state_thread_ == 0) - // Try to become the thread which will be responsible for the - // changes - { - this->change_state_thread_ = ACE_Thread::self (); - // Make sure no new threads are allowed to enter - this->ok_to_wait_.reset (); - - if (this->active_threads_ > 0) - // Check for other active threads - { - // Wake up all other threads - this->wakeup_all_threads_.signal (); - // Release - monitor.release (); - // Go to sleep waiting for all other threads to get done - this->waiting_to_change_state_.wait (); - // Re-acquire again - monitor.acquire (); - } - - // Note that make_changes() calls into user code which can - // request other changes. So keep looping until all - // requested changes are completed. - while (this->handler_rep_.changes_required ()) - // Make necessary changes to the handler repository - this->handler_rep_.make_changes (); - if (this->new_owner ()) - // Update the owner - this->change_owner (); - // Turn off - this->wakeup_all_threads_.reset (); - // Let everyone know that it is ok to go ahead - this->ok_to_wait_.signal (); - // Reset this flag - this->change_state_thread_ = 0; - } - else if (this->active_threads_ == 0) - // This thread did not get a chance to become the change - // thread. If it is the last one out, it will wakeup the - // change thread - this->waiting_to_change_state_.signal (); - } - // This is if we were woken up explicitily by the user and there are - // no state changes required. - else if (this->active_threads_ == 0) - // Turn off - this->wakeup_all_threads_.reset (); - - return 0; -} - -void -ACE_WFMO_Reactor::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_WFMO_Reactor::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("Count of currently active threads = %d\n"), - this->active_threads_)); - - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("ID of owner thread = %d\n"), - this->owner_)); - - this->handler_rep_.dump (); - this->signal_handler_->dump (); - this->timer_queue_->dump (); - - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -int -ACE_WFMO_Reactor_Notify::dispatch_notifications (int & /*number_of_active_handles*/, - ACE_Handle_Set & /*rd_mask*/) -{ - return -1; -} - -int -ACE_WFMO_Reactor_Notify::is_dispatchable (ACE_Notification_Buffer & /*buffer*/) -{ - return 0; -} - -ACE_HANDLE -ACE_WFMO_Reactor_Notify::notify_handle (void) -{ - return ACE_INVALID_HANDLE; -} - -int -ACE_WFMO_Reactor_Notify::read_notify_pipe (ACE_HANDLE , - ACE_Notification_Buffer &) -{ - return 0; -} - -int -ACE_WFMO_Reactor_Notify::dispatch_notify (ACE_Notification_Buffer &) -{ - return 0; -} - -int -ACE_WFMO_Reactor_Notify::close (void) -{ - return -1; -} - -ACE_WFMO_Reactor_Notify::ACE_WFMO_Reactor_Notify (size_t max_notifies) - : timer_queue_ (0), - message_queue_ (max_notifies * sizeof (ACE_Notification_Buffer), - max_notifies * sizeof (ACE_Notification_Buffer)), - max_notify_iterations_ (-1) -{ -} - -int -ACE_WFMO_Reactor_Notify::open (ACE_Reactor_Impl *wfmo_reactor, - ACE_Timer_Queue *timer_queue, - int ignore_notify) -{ - ACE_UNUSED_ARG (ignore_notify); - timer_queue_ = timer_queue; - return wfmo_reactor->register_handler (this); -} - -ACE_HANDLE -ACE_WFMO_Reactor_Notify::get_handle (void) const -{ - return this->wakeup_one_thread_.handle (); -} - -// Handle all pending notifications. - -int -ACE_WFMO_Reactor_Notify::handle_signal (int signum, - siginfo_t *siginfo, - ucontext_t *) -{ - ACE_UNUSED_ARG (signum); - - // Just check for sanity... - if (siginfo->si_handle_ != this->wakeup_one_thread_.handle ()) - return -1; - - // This will get called when wakeup_one_thread_> event - // is signaled. - // ACE_DEBUG ((LM_DEBUG, - // ACE_TEXT ("(%t) waking up to handle internal notifications\n"))); - - for (int i = 1; ; ++i) - { - ACE_Message_Block *mb = 0; - // Copy ACE_Time_Value::zero since dequeue_head will modify it. - ACE_Time_Value zero_timeout (ACE_Time_Value::zero); - if (this->message_queue_.dequeue_head (mb, &zero_timeout) == -1) - { - if (errno == EWOULDBLOCK) - // We've reached the end of the processing, return - // normally. - return 0; - else - return -1; // Something weird happened... - } - else - { - ACE_Notification_Buffer *buffer = - reinterpret_cast (mb->base ()); - - // If eh == 0 then we've got major problems! Otherwise, we - // need to dispatch the appropriate handle_* method on the - // ACE_Event_Handler pointer we've been passed. - - if (buffer->eh_ != 0) - { - ACE_Event_Handler *event_handler = - buffer->eh_; - - bool const requires_reference_counting = - event_handler->reference_counting_policy ().value () == - ACE_Event_Handler::Reference_Counting_Policy::ENABLED; - - int result = 0; - - switch (buffer->mask_) - { - case ACE_Event_Handler::READ_MASK: - case ACE_Event_Handler::ACCEPT_MASK: - result = event_handler->handle_input (ACE_INVALID_HANDLE); - break; - case ACE_Event_Handler::WRITE_MASK: - result = event_handler->handle_output (ACE_INVALID_HANDLE); - break; - case ACE_Event_Handler::EXCEPT_MASK: - result = event_handler->handle_exception (ACE_INVALID_HANDLE); - break; - case ACE_Event_Handler::QOS_MASK: - result = event_handler->handle_qos (ACE_INVALID_HANDLE); - break; - case ACE_Event_Handler::GROUP_QOS_MASK: - result = event_handler->handle_group_qos (ACE_INVALID_HANDLE); - break; - default: - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("invalid mask = %d\n"), - buffer->mask_)); - break; - } - - if (result == -1) - event_handler->handle_close (ACE_INVALID_HANDLE, - ACE_Event_Handler::EXCEPT_MASK); - - if (requires_reference_counting) - { - event_handler->remove_reference (); - } - } - - // Make sure to delete the memory regardless of success or - // failure! - mb->release (); - - // Bail out if we've reached the . - // Note that by default is -1, so - // we'll loop until we're done. - if (i == this->max_notify_iterations_) - { - // If there are still notification in the queue, we need - // to wake up again - if (!this->message_queue_.is_empty ()) - this->wakeup_one_thread_.signal (); - - // Break the loop as we have reached max_notify_iterations_ - return 0; - } - } - } -} - -// Notify the WFMO_Reactor, potentially enqueueing the -// for subsequent processing in the WFMO_Reactor -// thread of control. - -int -ACE_WFMO_Reactor_Notify::notify (ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask, - ACE_Time_Value *timeout) -{ - if (event_handler != 0) - { - ACE_Message_Block *mb = 0; - ACE_NEW_RETURN (mb, - ACE_Message_Block (sizeof (ACE_Notification_Buffer)), - -1); - - ACE_Notification_Buffer *buffer = - (ACE_Notification_Buffer *) mb->base (); - buffer->eh_ = event_handler; - buffer->mask_ = mask; - - // Convert from relative time to absolute time by adding the - // current time of day. This is what - // expects. - if (timeout != 0) - *timeout += timer_queue_->gettimeofday (); - - if (this->message_queue_.enqueue_tail - (mb, timeout) == -1) - { - mb->release (); - return -1; - } - - event_handler->add_reference (); - } - - return this->wakeup_one_thread_.signal (); -} - -void -ACE_WFMO_Reactor_Notify::max_notify_iterations (int iterations) -{ - ACE_TRACE ("ACE_WFMO_Reactor_Notify::max_notify_iterations"); - // Must always be > 0 or < 0 to optimize the loop exit condition. - if (iterations == 0) - iterations = 1; - - this->max_notify_iterations_ = iterations; -} - -int -ACE_WFMO_Reactor_Notify::max_notify_iterations (void) -{ - ACE_TRACE ("ACE_WFMO_Reactor_Notify::max_notify_iterations"); - return this->max_notify_iterations_; -} - -int -ACE_WFMO_Reactor_Notify::purge_pending_notifications (ACE_Event_Handler *eh, - ACE_Reactor_Mask mask) -{ - ACE_TRACE ("ACE_WFMO_Reactor_Notify::purge_pending_notifications"); - - // Go over message queue and take out all the matching event - // handlers. If eh == 0, purge all. Note that reactor notifies (no - // handler specified) are never purged, as this may lose a needed - // notify the reactor queued for itself. - - if (this->message_queue_.is_empty ()) - return 0; - - // Guard against new and/or delivered notifications while purging. - // WARNING!!! The use of the notification queue's lock object for - // this guard makes use of the knowledge that on Win32, the mutex - // protecting the queue is really a CriticalSection, which is - // recursive. This is how we can get away with locking it down here - // and still calling member functions on the queue object. - ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, monitor, this->message_queue_.lock(), -1); - - // first, copy all to our own local queue. Since we've locked everyone out - // of here, there's no need to use any synchronization on this queue. - ACE_Message_Queue local_queue; - - size_t queue_size = this->message_queue_.message_count (); - int number_purged = 0; - - size_t index; - - for (index = 0; index < queue_size; ++index) - { - ACE_Message_Block *mb = 0; - if (-1 == this->message_queue_.dequeue_head (mb)) - return -1; // This shouldn't happen... - - ACE_Notification_Buffer *buffer = - reinterpret_cast (mb->base ()); - - // If this is not a Reactor notify (it is for a particular handler), - // and it matches the specified handler (or purging all), - // and applying the mask would totally eliminate the notification, then - // release it and count the number purged. - if ((0 != buffer->eh_) && - (0 == eh || eh == buffer->eh_) && - ACE_BIT_DISABLED (buffer->mask_, ~mask)) // the existing notification mask - // is left with nothing when - // applying the mask - { - ACE_Event_Handler *event_handler = buffer->eh_; - - event_handler->remove_reference (); - - mb->release (); - ++number_purged; - } - else - { - // To preserve it, move it to the local_queue. But first, if - // this is not a Reactor notify (it is for a - // particularhandler), and it matches the specified handler - // (or purging all), then apply the mask - if ((0 != buffer->eh_) && - (0 == eh || eh == buffer->eh_)) - ACE_CLR_BITS(buffer->mask_, mask); - if (-1 == local_queue.enqueue_head (mb)) - return -1; - } - } - - if (this->message_queue_.message_count ()) - { // Should be empty! - ACE_ASSERT (0); - return -1; - } - - // Now copy back from the local queue to the class queue, taking - // care to preserve the original order... - queue_size = local_queue.message_count (); - for (index = 0; index < queue_size; ++index) - { - ACE_Message_Block *mb = 0; - if (-1 == local_queue.dequeue_head (mb)) - { - ACE_ASSERT (0); - return -1; - } - - if (-1 == this->message_queue_.enqueue_head (mb)) - { - ACE_ASSERT (0); - return -1; - } - } - - return number_purged; -} - -void -ACE_WFMO_Reactor_Notify::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_WFMO_Reactor_Notify::dump"); - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - this->timer_queue_->dump (); - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("Max. iteration: %d\n"), - this->max_notify_iterations_)); - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -void -ACE_WFMO_Reactor::max_notify_iterations (int iterations) -{ - ACE_TRACE ("ACE_WFMO_Reactor::max_notify_iterations"); - ACE_GUARD (ACE_Process_Mutex, monitor, this->lock_); - - // Must always be > 0 or < 0 to optimize the loop exit condition. - this->notify_handler_->max_notify_iterations (iterations); -} - -int -ACE_WFMO_Reactor::max_notify_iterations (void) -{ - ACE_TRACE ("ACE_WFMO_Reactor::max_notify_iterations"); - ACE_GUARD_RETURN (ACE_Process_Mutex, monitor, this->lock_, -1); - - return this->notify_handler_->max_notify_iterations (); -} - -int -ACE_WFMO_Reactor::purge_pending_notifications (ACE_Event_Handler *eh, - ACE_Reactor_Mask mask) -{ - ACE_TRACE ("ACE_WFMO_Reactor::purge_pending_notifications"); - if (this->notify_handler_ == 0) - return 0; - else - return this->notify_handler_->purge_pending_notifications (eh, mask); -} - -int -ACE_WFMO_Reactor::resumable_handler (void) -{ - ACE_TRACE ("ACE_WFMO_Reactor::resumable_handler"); - return 0; -} - - -// No-op WinSOCK2 methods to help WFMO_Reactor compile -#if !defined (ACE_HAS_WINSOCK2) || (ACE_HAS_WINSOCK2 == 0) -int -WSAEventSelect (SOCKET /* s */, - WSAEVENT /* hEventObject */, - long /* lNetworkEvents */) -{ - return -1; -} - -int -WSAEnumNetworkEvents (SOCKET /* s */, - WSAEVENT /* hEventObject */, - LPWSANETWORKEVENTS /* lpNetworkEvents */) -{ - return -1; -} -#endif /* !defined ACE_HAS_WINSOCK2 */ - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_WIN32 */ diff --git a/externals/ace/WFMO_Reactor.h b/externals/ace/WFMO_Reactor.h deleted file mode 100644 index fb3a14d28cd..00000000000 --- a/externals/ace/WFMO_Reactor.h +++ /dev/null @@ -1,1368 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file WFMO_Reactor.h - * - * $Id: WFMO_Reactor.h 84727 2009-03-05 19:22:29Z johnnyw $ - * - * @author Irfan Pyarali - * @author Tim Harrison - * @author Doug Schmidt - */ -//============================================================================= - -#ifndef ACE_WFMO_REACTOR_H -#define ACE_WFMO_REACTOR_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_WIN32) - -#include "ace/Signal.h" -#include "ace/Timer_Queue.h" -#include "ace/Event_Handler.h" -#include "ace/Auto_Event.h" -#include "ace/Manual_Event.h" -#include "ace/Condition_Thread_Mutex.h" -#include "ace/Lock_Adapter_T.h" -#include "ace/Reactor_Impl.h" -#include "ace/Message_Queue.h" -#include "ace/Process_Mutex.h" - -// If we don't have WinSOCK2, we need these defined -#if !defined (ACE_HAS_WINSOCK2) || (ACE_HAS_WINSOCK2 == 0) -/* - * WinSock 2 extension -- bit values and indices for FD_XXX network events - */ -#define FD_READ_BIT 0 -#define FD_WRITE_BIT 1 -#define FD_OOB_BIT 2 -#define FD_ACCEPT_BIT 3 -#define FD_CONNECT_BIT 4 -#define FD_CLOSE_BIT 5 -#define FD_QOS_BIT 6 -#define FD_GROUP_QOS_BIT 7 - -#define FD_QOS (1 << FD_QOS_BIT) -#define FD_GROUP_QOS (1 << FD_GROUP_QOS_BIT) - -#define FD_MAX_EVENTS 8 -#define FD_ALL_EVENTS ((1 << FD_MAX_EVENTS) - 1) - -#define WSAEVENT HANDLE - -typedef struct _WSANETWORKEVENTS -{ - long lNetworkEvents; - int iErrorCode[FD_MAX_EVENTS]; -} WSANETWORKEVENTS, FAR * LPWSANETWORKEVENTS; - -int WSAEventSelect (SOCKET s, - WSAEVENT hEventObject, - long lNetworkEvents); - -int WSAEnumNetworkEvents (SOCKET s, - WSAEVENT hEventObject, - LPWSANETWORKEVENTS lpNetworkEvents); - -#endif /* !defined ACE_HAS_WINSOCK2 */ - -class ACE_WFMO_Reactor_Test; // Must be out of versioned namespace. - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Forward decl. -class ACE_WFMO_Reactor; -class ACE_Handle_Set; - -/** - * @class ACE_Wakeup_All_Threads_Handler - * - * @brief This is a helper class whose sole purpose is to handle events - * on wakeup_all_threads_> - */ -class ACE_Export ACE_Wakeup_All_Threads_Handler : public ACE_Event_Handler -{ -public: - /// Called when the wakeup_all_threads_> - virtual int handle_signal (int signum, siginfo_t * = 0, ucontext_t * = 0); -}; - -/** - * @class ACE_WFMO_Reactor_Handler_Repository - * - * @internal This class is for internal ACE use only. - * - * @brief Used to map ACE_HANDLEs onto the appropriate - * ACE_Event_Handler * and other information. - */ -class ACE_Export ACE_WFMO_Reactor_Handler_Repository -{ -public: - friend class ACE_WFMO_Reactor; - friend class ACE_WFMO_Reactor_Test; - - /** - * @class Common_Info - * - * @brief This struct contains the necessary information for every - * entry. The reason the event is not in this - * structure is because we need to pass an event array into - * WaitForMultipleObjects and therefore keeping the events - * seperate makes sense. - */ - class Common_Info - { - public: - /// This indicates whether this entry is for I/O or for a regular - /// event - bool io_entry_; - - /// The assosiated - ACE_Event_Handler *event_handler_; - - /// The I/O handle related to the . This entry is - /// only valid if the flag is true. - ACE_HANDLE io_handle_; - - /** - * This is the set of events that the is - * interested in. This entry is only valid if the flag - * is true. - */ - long network_events_; - - /** - * This flag indicates that created the event on - * behalf of the user. Therefore we need to clean this up when the - * removes itself from . This entry - * is only valid if the flag is true. - */ - bool delete_event_; - - /// This is set when the entry needed to be deleted. - bool delete_entry_; - - /** - * These are the masks related to for the - * . This is only valid when is - * set. - */ - ACE_Reactor_Mask close_masks_; - - /// Constructor used for initializing the structure - Common_Info (void); - - /// Reset the state of the structure - void reset (void); - - /// Set the structure to these new values - void set (bool io_entry, - ACE_Event_Handler *event_handler, - ACE_HANDLE io_handle, - long network_events, - bool delete_event, - bool delete_entry, - ACE_Reactor_Mask close_masks); - - /// Set the structure to these new values - void set (Common_Info &common_info); - - /// Dump the state of an object. - void dump (void) const; - }; - - /** - * @class Current_Info - * - * @brief This structure inherits from the common structure to add - * information for current entries. - */ - class Current_Info : public Common_Info - { - public: - /// This is set when the entry needed to be suspended. - bool suspend_entry_; - - /// Default constructor - Current_Info (void); - - /// Reset the state of the structure - void reset (void); - - /// Set the structure to these new values - void set (bool io_entry, - ACE_Event_Handler *event_handler, - ACE_HANDLE io_handle, - long network_events, - bool delete_event, - bool delete_entry = false, - ACE_Reactor_Mask close_masks = ACE_Event_Handler::NULL_MASK, - bool suspend_entry = false); - - /// Set the structure to these new values - void set (Common_Info &common_info, - bool suspend_entry = false); - - /// Dump the state of an object. - void dump (ACE_HANDLE event_handle) const; - }; - - /** - * @class To_Be_Added_Info - * - * @brief This structure inherits from the common structure to add - * information for entries. - */ - class To_Be_Added_Info : public Common_Info - { - public: - /// Handle for the event - ACE_HANDLE event_handle_; - - /// This is set when the entry needed to be suspended. - bool suspend_entry_; - - /// Default constructor - To_Be_Added_Info (void); - - /// Reset the state of the structure - void reset (void); - - /// Set the structure to these new values - void set (ACE_HANDLE event_handle, - bool io_entry, - ACE_Event_Handler *event_handler, - ACE_HANDLE io_handle, - long network_events, - bool delete_event, - bool delete_entry = false, - ACE_Reactor_Mask close_masks = ACE_Event_Handler::NULL_MASK, - bool suspend_entry = false); - - /// Set the structure to these new values - void set (ACE_HANDLE event_handle, - Common_Info &common_info, - bool suspend_entry = false); - - /// Dump the state of an object. - void dump (void) const; - }; - - /** - * @class Suspended_Info - * - * @brief This structure inherits from the common structure to add - * information for suspended entries. - */ - class Suspended_Info : public Common_Info - { - public: - /// Handle for the event - ACE_HANDLE event_handle_; - - /// This is set when the entry needed to be resumed. - bool resume_entry_; - - /// Constructor used for initializing the structure - Suspended_Info (void); - - /// Reset the state of the structure - void reset (void); - - /// Set the structure to these new values - void set (ACE_HANDLE event_handle, - bool io_entry, - ACE_Event_Handler *event_handler, - ACE_HANDLE io_handle, - long network_events, - bool delete_event, - bool delete_entry = false, - ACE_Reactor_Mask close_masks = 0, - bool resume_entry = false); - - /// Set the structure to these new values - void set (ACE_HANDLE event_handle, - Common_Info &common_info, - bool resume_entry = false); - - /// Dump the state of an object. - void dump (void) const; - }; - - /// Constructor. - ACE_WFMO_Reactor_Handler_Repository (ACE_WFMO_Reactor &wfmo_reactor); - - /// Destructor. - virtual ~ACE_WFMO_Reactor_Handler_Repository (void); - - /// Initialize the repository of the approriate @a size. - int open (size_t size); - - /// Close down the handler repository. - int close (void); - - // = Search structure operations. - - /// Bind the to the ACE_HANDLE. This is for - /// the simple event entry. - int bind (ACE_HANDLE, ACE_Event_Handler *); - - /// Insert I/O entry into the system. This method - /// assumes that the lock are head *before* this method is invoked. - int bind_i (bool io_entry, - ACE_Event_Handler *event_handler, - long network_events, - ACE_HANDLE io_handle, - ACE_HANDLE event_handle, - bool delete_event); - - /// Remove the binding of ACE_HANDLE in accordance with the @a mask. - int unbind (ACE_HANDLE, - ACE_Reactor_Mask mask); - - /// Non-lock-grabbing version of - int unbind_i (ACE_HANDLE, - ACE_Reactor_Mask mask, - bool &changes_required); - - /// Remove all bindings of tuples. - void unbind_all (void); - - // = Sanity checking. - - // Check the @a handle to make sure it's a valid ACE_HANDLE - int invalid_handle (ACE_HANDLE handle) const; - - // = Accessors. - /// Maximum ACE_HANDLE value, plus 1. - DWORD max_handlep1 (void) const; - - /// Pointer to the beginning of the current array of ACE_HANDLE - /// *'s. - ACE_HANDLE *handles (void) const; - - /// Pointer to the beginning of the current array of - /// ACE_Event_Handler *'s. - Current_Info *current_info (void) const; - - /// Check if changes to the handle set are required. - virtual bool changes_required (void); - - /// Make changes to the handle set - virtual int make_changes (void); - - /// Check to see if @a slot has been scheduled for deletion - int scheduled_for_deletion (size_t slot) const; - - /** - * This method is used to calculate the network mask after a mask_op - * request to . Note that because the - * may already be in the handler repository, we may have to find the - * old event and the old network events - */ - int modify_network_events_i (ACE_HANDLE io_handle, - ACE_Reactor_Mask new_masks, - ACE_Reactor_Mask &old_masks, - long &new_network_events, - ACE_HANDLE &event_handle, - bool &delete_event, - int operation); - - /// This method is used to change the network mask left (if any) - /// after a remove request to - ACE_Reactor_Mask bit_ops (long &existing_masks, - ACE_Reactor_Mask to_be_removed_masks, - int operation); - - /// Temporarily suspend entry - int suspend_handler_i (ACE_HANDLE handle, - bool &changes_required); - - /// Resume suspended entry - int resume_handler_i (ACE_HANDLE handle, - bool &changes_required); - - /// Deletions and suspensions in current_info_ - int make_changes_in_current_infos (void); - - /// Deletions and resumptions in current_suspended_info_ - int make_changes_in_suspension_infos (void); - - /// Deletions in to_be_added_info_, or transfers to current_info_ or - /// current_suspended_info_ from to_be_added_info_ - int make_changes_in_to_be_added_infos (void); - - /// Removes the ACE_Event_Handler at @a slot from the table. - int remove_handler_i (size_t slot, - ACE_Reactor_Mask mask); - - /// Removes the ACE_Event_Handler at @a slot from the table. - int remove_suspended_handler_i (size_t slot, - ACE_Reactor_Mask mask); - - /// Removes the ACE_Event_Handler at @a slot from the table. - int remove_to_be_added_handler_i (size_t slot, - ACE_Reactor_Mask to_be_removed_masks); - - /** - * Return the Event_Handler associated with @a handle. Return 0 if - * @a handle is not registered. - */ - ACE_Event_Handler *find_handler (ACE_HANDLE handle); - - /** - * Check to see if @a handle is associated with a valid Event_Handler - * bound to @a mask. Return the @a event_handler associated with this - * @a handler if @a event_handler != 0. - */ - int handler (ACE_HANDLE handle, - ACE_Reactor_Mask mask, - ACE_Event_Handler **event_handler = 0); - - /** - * Check to see if @a handle is associated with a valid - * Event_Handler. Return Event_Handler and associated masks. - */ - ACE_Event_Handler *handler (ACE_HANDLE handle, - long &existing_masks); - - /// Dump the state of an object. - void dump (void) const; - -protected: - /// Reference to our . - ACE_WFMO_Reactor &wfmo_reactor_; - - /// Maximum number of handles. - size_t max_size_; - - /** - * Array of passed to . This - * is not part of the structure as the handle array needs to be - * passed directly to . - */ - ACE_HANDLE *current_handles_; - - /// Array of current entries in the table - Current_Info *current_info_; - - /// A count of the number of active handles. - DWORD max_handlep1_; - - /// Information for entries to be added - To_Be_Added_Info *to_be_added_info_; - - /// Number of records to be added - size_t handles_to_be_added_; - - /// Currently suspended handles - Suspended_Info *current_suspended_info_; - - /// Number of currently suspended handles - size_t suspended_handles_; - - /// Number of records to be suspended - size_t handles_to_be_suspended_; - - /// Number of records to be resumed - size_t handles_to_be_resumed_; - - /// Number of records to be deleted - size_t handles_to_be_deleted_; - -}; - -/** - * @class ACE_WFMO_Reactor_Notify - * - * @brief Unblock the from its event loop, passing - * it an optional ACE_Event_Handler to dispatch. - * - * This implementation is necessary for cases where the - * is run in a multi-threaded program. In - * this case, we need to be able to unblock - * when updates occur other than in the - * main thread. To do this, we signal an - * auto-reset event the is listening on. If - * an ACE_Event_Handler and ACE_Reactor_Mask is passed to - * , the appropriate method is dispatched. - */ -class ACE_Export ACE_WFMO_Reactor_Notify : public ACE_Reactor_Notify -{ -public: - /// Constructor - ACE_WFMO_Reactor_Notify (size_t max_notifies = 1024); - - /// Initialization. is stored to call . - virtual int open (ACE_Reactor_Impl *wfmo_reactor, - ACE_Timer_Queue *timer_queue, - int disable_notify = 0); - - /// No-op. - virtual int close (void); - - /** - * Special trick to unblock when updates - * occur. All we do is enqueue @a event_handler and @a mask onto the - * ACE_Message_Queue and wakeup the by signaling - * its handle. The ACE_Time_Value indicates how long - * to blocking trying to notify the . If @a timeout == - * 0, the caller will block until action is possible, else will wait - * until the relative time specified in @a timeout elapses). - */ - virtual int notify (ACE_Event_Handler *event_handler = 0, - ACE_Reactor_Mask mask = ACE_Event_Handler::EXCEPT_MASK, - ACE_Time_Value *timeout = 0); - - /// No-op. - virtual int dispatch_notifications (int &number_of_active_handles, - ACE_Handle_Set &rd_mask); - - /// Returns a handle to the . - virtual ACE_HANDLE get_handle (void) const; - - /// Returns the ACE_HANDLE of the notify pipe on which the reactor - /// is listening for notifications so that other threads can unblock - /// the - virtual ACE_HANDLE notify_handle (void); - - /// Handle one of the notify call on the . This could be - /// because of a thread trying to unblock the - virtual int dispatch_notify (ACE_Notification_Buffer &buffer); - - /// Verify whether the buffer has dispatchable info or not. - virtual int is_dispatchable (ACE_Notification_Buffer &buffer); - - /// Read one of the notify call on the @a handle into the - /// . This could be because of a thread trying to unblock - /// the - virtual int read_notify_pipe (ACE_HANDLE handle, - ACE_Notification_Buffer &buffer); - - /** - * Set the maximum number of times that the - * method will iterate and - * dispatch the ACE_Event_Handlers that are passed in via the - * notify queue before breaking out of its - * loop. By default, this is set to - * -1, which means "iterate until the queue is empty." Setting this - * to a value like "1 or 2" will increase "fairness" (and thus - * prevent starvation) at the expense of slightly higher dispatching - * overhead. - */ - void max_notify_iterations (int); - - /** - * Get the maximum number of times that the - * method will iterate and - * dispatch the ACE_Event_Handlers that are passed in via the - * notify queue before breaking out of its - * loop. - */ - int max_notify_iterations (void); - - /** - * Purge any notifications pending in this reactor for the specified - * ACE_Event_Handler object. If @a eh == 0, all notifications for all - * handlers are removed (but not any notifications posted just to wake up - * the reactor itself). Returns the number of notifications purged. - * Returns -1 on error. - */ - virtual int purge_pending_notifications (ACE_Event_Handler *, - ACE_Reactor_Mask = ACE_Event_Handler::ALL_EVENTS_MASK); - - /// Dump the state of an object. - virtual void dump (void) const; - -private: - /// Pointer to the wfmo_reactor's timer queue. - ACE_Timer_Queue *timer_queue_; - - /** - * Called when the notification event waited on by - * is signaled. This dequeues all pending - * ACE_Event_Handlers and dispatches them. - */ - virtual int handle_signal (int signum, siginfo_t * = 0, ucontext_t * = 0); - - /// An auto event is used so that we can it to wakeup one - /// thread up (e.g., when the method is called). - ACE_Auto_Event wakeup_one_thread_; - - /// Message queue that keeps track of pending ACE_Event_Handlers. - /// This queue must be thread-safe because it can be called by - /// multiple threads of control. - ACE_Message_Queue message_queue_; - - /** - * Keeps track of the maximum number of times that the - * method will iterate and - * dispatch the ACE_Event_Handlers that are passed in via the - * notify queue before breaking out of its - * loop. By default, this is set to - * -1, which means "iterate until the queue is empty." - */ - int max_notify_iterations_; -}; - -/** - * @class ACE_WFMO_Reactor - * - * @brief An object oriented event demultiplexor and event handler. - * ACE_WFMO_Reactor is a Windows-only implementation of the ACE_Reactor - * interface that uses the WaitForMultipleObjects() event demultiplexer. - * - * Like the other ACE Reactors, ACE_WFMO_Reactor can schedule timers. - * It also reacts to signalable handles, such as events (see the documentation - * for WaitForMultipleObjects() for a complete list of signalable handle - * types). Therefore, I/O handles are not directly usable for registering - * for input, output, and exception notification. The exception to this - * is ACE_SOCK-based handles, which can be registered for input, output, and - * exception notification just as with other platforms. See Chapter 4 in - * C++NPv2 for complete details. - * - * Note that changes to the state of ACE_WFMO_Reactor are not - * instantaneous. Most changes (registration, removal, - * suspension, and resumption of handles, and changes in - * ownership) are made when the ACE_WFMO_Reactor reaches a stable - * state. Users should be careful, especially when removing - * handlers. This is because the ACE_WFMO_Reactor will call - * handle_close() on the handler when it is finally removed and - * not when remove_handler() is called. If the registered handler's pointer - * is not valid when ACE_WFMO_Reactor calls ACE_Event_Handler::handle_close(), - * use the DONT_CALL flag with remove_handler(). Preferably, use dynamically - * allocated event handlers and call "delete this" inside the handle_close() - * hook method. - * - * Note that although multiple threads can concurrently run the - * ACE_WFMO_Reactor event loop, the concept of the reactor "owner" is still - * important. Only the owner thread can expire timers and wait on the - * notifications handle. Thus, be careful to properly set the owner thread - * when spawning threads to run the event loop while you are using timers - * or notifications. - */ -class ACE_Export ACE_WFMO_Reactor : public ACE_Reactor_Impl -{ -public: - friend class ACE_WFMO_Reactor_Handler_Repository; - friend class ACE_WFMO_Reactor_Test; - - enum - { - /// Default size of the WFMO_Reactor's handle table. - /** - * Two slots will be added to the @a size parameter in the - * constructor and open methods which will store handles used for - * internal management purposes. - */ - DEFAULT_SIZE = MAXIMUM_WAIT_OBJECTS - 2 - }; - - // = Initialization and termination methods. - - /// Initialize ACE_WFMO_Reactor with the default size. - ACE_WFMO_Reactor (ACE_Sig_Handler * = 0, - ACE_Timer_Queue * = 0, - ACE_Reactor_Notify * = 0); - - /** - * Initialize ACE_WFMO_Reactor with the specified size. - * - * @param size The maximum number of handles the reactor can - * register. The value should not exceed - * ACE_WFMO_Reactor::DEFAULT_SIZE. Two slots will be - * added to the @a size parameter which will store handles - * used for internal management purposes. - */ - ACE_WFMO_Reactor (size_t size, - int unused = 0, - ACE_Sig_Handler * = 0, - ACE_Timer_Queue * = 0, - ACE_Reactor_Notify * = 0); - - /** - * Initialize ACE_WFMO_Reactor with the specified size. - * - * @param size The maximum number of handles the reactor can - * register. The value should not exceed - * ACE_WFMO_Reactor::DEFAULT_SIZE. Two slots will be - * added to the @a size parameter which will store handles - * used for internal management purposes. - */ - virtual int open (size_t size = ACE_WFMO_Reactor::DEFAULT_SIZE, - bool restart = false, - ACE_Sig_Handler * = 0, - ACE_Timer_Queue * = 0, - int disable_notify_pipe = 0, - ACE_Reactor_Notify * = 0); - - /// Returns -1 (not used in this implementation); - virtual int current_info (ACE_HANDLE, size_t & /* size */); - - /// Use a user specified signal handler instead. - virtual int set_sig_handler (ACE_Sig_Handler *signal_handler); - - /// Set a user-specified timer queue. - virtual int timer_queue (ACE_Timer_Queue *tq); - - /// Return the current ACE_Timer_Queue. - virtual ACE_Timer_Queue *timer_queue (void) const; - - /// Close down the ACE_WFMO_Reactor and release all of its resources. - virtual int close (void); - - /// Close down the ACE_WFMO_Reactor and release all of its resources. - virtual ~ACE_WFMO_Reactor (void); - - // = Event loop drivers. - - /** - * This method is not currently implemented. We recommend that you - * use handle_events (ACE_Time_Value::zero) to get basically the - * same effect, i.e., it won't block the caller if there are no events. - */ - virtual int work_pending (const ACE_Time_Value &max_wait_time = ACE_Time_Value::zero); - - /** - * This event loop driver blocks for up to @a max_wait_time before - * returning. It will return earlier if timer events, I/O events, - * or signal events occur. Note that @a max_wait_time can be 0, in - * which case this method blocks indefinitely until events occur. - * - * @a max_wait_time is decremented to reflect how much time this call - * took. For instance, if a time value of 3 seconds is passed to - * handle_events and an event occurs after 2 seconds, - * @a max_wait_time will equal 1 second. This can be used if an - * application wishes to handle events for some fixed amount of - * time. - * - * is used as the demultiplexing call - * - * Returns the total number of I/O and timer ACE_Event_Handlers - * that were dispatched, 0 if the @a max_wait_time elapsed without - * dispatching any handlers, or -1 if an error occurs. - * - * The only difference between and - * is that in the alertable case, TRUE is passed to - * for the option. - */ - virtual int handle_events (ACE_Time_Value *max_wait_time = 0); - virtual int alertable_handle_events (ACE_Time_Value *max_wait_time = 0); - - /** - * This method is just like the one above, except the - * @a max_wait_time value is a reference and can therefore never be - * NULL. - * - * The only difference between and - * is that in the alertable case, TRUE is passed to - * for the option. - */ - virtual int handle_events (ACE_Time_Value &max_wait_time); - virtual int alertable_handle_events (ACE_Time_Value &max_wait_time); - - - // = Event handling control. - - /** - * Return the status of Reactor. If this function returns 0, the reactor is - * actively handling events. If it returns non-zero, and - * return -1 immediately. - */ - virtual int deactivated (void); - - /** - * Control whether the Reactor will handle any more incoming events or not. - * If == 1, the Reactor will be disabled. By default, a reactor - * is in active state and can be deactivated/reactived as wish. - */ - virtual void deactivate (int do_stop); - - // = Register and remove Handlers. - - /** - * Register an ACE_Event_Handler @a event_handler. Since no Event - * Mask is passed through this interface, it is assumed that the - * @a handle being passed in is an event handle and when the event - * becomes signaled, will call handle_signal on - * @a event_handler. If @a handle == the - * will call the method of - * @a event_handler to extract the underlying event handle. - */ - virtual int register_handler (ACE_Event_Handler *event_handler, - ACE_HANDLE event_handle = ACE_INVALID_HANDLE); - - /** - * Register an ACE_Event_Handler . @a mask specifies - * the network events that the is interested in. If - * == the will - * call the method of to extract the - * underlying I/O handle. If the == - * , WFMO_Reactor will create an event for - * associating it with the I/O handle. When the is - * signalled, the appropriate callback will be invoked on - * the - */ - virtual int register_handler (ACE_HANDLE event_handle, - ACE_HANDLE io_handle, - ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask); - - /** - * This is a simple version of the above method - * where the I/O handle is passed in and the event handle will - * always be created by - */ - virtual int register_handler (ACE_HANDLE io_handle, - ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask); - - /** - * This is a simple version of the above method - * where the I/O handle will always come from on the - * and the event handle will always be created by - * - */ - virtual int register_handler (ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask); - - /// Register @a event_handler with all the @a handles in the - /// . - virtual int register_handler (const ACE_Handle_Set &handles, - ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask); - - /** - * Register @a new_sh to handle the signal @a signum using the - * @a new_disp. Returns the @a old_sh that was previously registered - * (if any), along with the @a old_disp of the signal handler. - */ - virtual int register_handler (int signum, - ACE_Event_Handler *new_sh, - ACE_Sig_Action *new_disp = 0, - ACE_Event_Handler **old_sh = 0, - ACE_Sig_Action *old_disp = 0); - - /// Registers @a new_sh to handle a set of signals @a sigset using the - /// @a new_disp. - virtual int register_handler (const ACE_Sig_Set &sigset, - ACE_Event_Handler *new_sh, - ACE_Sig_Action *new_disp = 0); - - /** - * Removes @a event_handler from the . Note that - * the will call the method of - * @a event_handler to extract the underlying handle. If @a mask == - * ACE_Event_Handler::DONT_CALL then the method of - * the @a event_handler is not invoked. Note that the @a handle can - * either be the or the - */ - virtual int remove_handler (ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask); - - /** - * Removes @a handle from the . If @a mask == - * ACE_Event_Handler::DONT_CALL then the method of - * the is not invoked. Note that the @a handle can - * either be the or the - * - * For the case of I/O entries, this removes the @a mask binding of - * whose handle is @a handle from . If - * there are no more bindings for this then it is - * removed from the WFMO_Reactor. For simple event entries, mask is - * mostly ignored and the is always removed from - * - */ - virtual int remove_handler (ACE_HANDLE handle, - ACE_Reactor_Mask mask); - - /** - * Removes all the @a mask bindings for handles in the @a handle_set - * bind of . If there are no more bindings for any - * of these handles then they are removed from WFMO_Reactor. - */ - virtual int remove_handler (const ACE_Handle_Set &handle_set, - ACE_Reactor_Mask); - - /** - * Remove the ACE_Event_Handler currently associated with @a signum. - * @a sigkey is ignored in this implementation since there is only - * one instance of a signal handler. Install the new disposition - * (if given) and return the previous disposition (if desired by the - * caller). Returns 0 on success and -1 if @a signum is invalid. - */ - virtual int remove_handler (int signum, - ACE_Sig_Action *new_disp, - ACE_Sig_Action *old_disp = 0, - int sigkey = -1); - - /// Calls for every signal in @a sigset. - virtual int remove_handler (const ACE_Sig_Set &sigset); - - // = Suspend and resume Handlers. - - /// Suspend @a event_handler temporarily. Use - /// to get the handle. - virtual int suspend_handler (ACE_Event_Handler *event_handler); - - /// Suspend @a handle temporarily. - virtual int suspend_handler (ACE_HANDLE handle); - - /// Suspend all @a handles in handle set temporarily. - virtual int suspend_handler (const ACE_Handle_Set &handles); - - /// Suspend all temporarily. - virtual int suspend_handlers (void); - - /// Resume @a event_handler. Use to - /// get the handle. - virtual int resume_handler (ACE_Event_Handler *event_handler); - - /// Resume @a handle. - virtual int resume_handler (ACE_HANDLE handle); - - /// Resume all @a handles in handle set. - virtual int resume_handler (const ACE_Handle_Set &handles); - - /// Resume all . - virtual int resume_handlers (void); - - /// Does the reactor allow the application to resume the handle on - /// its own ie. can it pass on the control of handle resumption to - /// the application. A positive value indicates that the handlers - /// are application resumable. A value of 0 indicates otherwise. - virtual int resumable_handler (void); - - /** - * Return true if we any event associations were made by the reactor - * for the handles that it waits on, false otherwise. Since the - * WFMO_Reactor does use event associations, this function always - * return true. - */ - virtual bool uses_event_associations (void); - - // Timer management. - - /** - * Schedule an ACE_Event_Handler that will expire after an amount - * of time. The return value of this method, a timer_id value, - * uniquely identifies the event_handler in the ACE_Reactor's - * internal list of timers. - * This timer_id value can be used to cancel the timer - * with the cancel_timer() call. - * - * @see cancel_timer() - * @see reset_timer_interval() - * - * @param event_handler event handler to schedule on reactor - * @param arg argument passed to the handle_timeout() method of event_handler - * @param delay time interval after which the timer will expire - * @param interval time interval after which the timer will be automatically rescheduled - * @return -1 on failure, a timer_id value on success - */ - virtual long schedule_timer (ACE_Event_Handler *event_handler, - const void *arg, - const ACE_Time_Value &delay, - const ACE_Time_Value &interval = ACE_Time_Value::zero); - - /** - * Resets the interval of the timer represented by @a timer_id to - * @a interval, which is specified in relative time to the current - * . If @a interval is equal to - * ACE_Time_Value::zero, the timer will become a non-rescheduling - * timer. Returns 0 if successful, -1 if not. - */ - virtual int reset_timer_interval (long timer_id, - const ACE_Time_Value &interval); - - /// Cancel all Event_Handlers that match the address of - /// @a event_handler. Returns number of handler's cancelled. - virtual int cancel_timer (ACE_Event_Handler *event_handler, - int dont_call_handle_close = 1); - - /** - * Cancel the single Event_Handler that matches the @a timer_id value - * (which was returned from the schedule method). If arg is - * non-NULL then it will be set to point to the ``magic cookie'' - * argument passed in when the Event_Handler was registered. This - * makes it possible to free up the memory and avoid memory leaks. - * Returns 1 if cancellation succeeded and 0 if the @a timer_id - * wasn't found. - */ - virtual int cancel_timer (long timer_id, - const void **arg = 0, - int dont_call_handle_close = 1); - - // = High-level Event_Handler scheduling operations - - /** - * Add @a masks_to_be_added to the @a event_handler's entry in - * WFMO_Reactor. @a event_handler must already have been registered - * with WFMO_Reactor. - */ - virtual int schedule_wakeup (ACE_Event_Handler *event_handler, - ACE_Reactor_Mask masks_to_be_added); - - /** - * Add @a masks_to_be_added to the @a handle's entry in WFMO_Reactor. - * The Event_Handler associated with @a handle must already have been - * registered with WFMO_Reactor. - */ - virtual int schedule_wakeup (ACE_HANDLE handle, - ACE_Reactor_Mask masks_to_be_added); - - /** - * Remove to the 's entry in - * WFMO_Reactor. The Event_Handler associated with must - * already have been registered with WFMO_Reactor. - */ - virtual int cancel_wakeup (ACE_Event_Handler *event_handler, - ACE_Reactor_Mask masks_to_be_deleted); - - /** - * Remove to the 's entry in - * WFMO_Reactor. The Event_Handler associated with must - * already have been registered with WFMO_Reactor. - */ - virtual int cancel_wakeup (ACE_HANDLE handle, - ACE_Reactor_Mask masks_to_be_deleted); - - // = Notification methods. - - /** - * Wakeup one thread if it is currently blocked - * in . The ACE_Time_Value indicates how - * long to blocking trying to notify the . If - * @a timeout == 0, the caller will block until action is possible, - * else will wait until the relative time specified in @a timeout - * elapses). - */ - virtual int notify (ACE_Event_Handler * = 0, - ACE_Reactor_Mask = ACE_Event_Handler::EXCEPT_MASK, - ACE_Time_Value * = 0); - - /** - * Set the maximum number of times that the - * method will iterate and - * dispatch the ACE_Event_Handlers that are passed in via the - * notify queue before breaking out of its - * loop. By default, this is set to - * -1, which means "iterate until the queue is empty." Setting this - * to a value like "1 or 2" will increase "fairness" (and thus - * prevent starvation) at the expense of slightly higher dispatching - * overhead. - */ - virtual void max_notify_iterations (int); - - /** - * Get the maximum number of times that the - * method will iterate and - * dispatch the ACE_Event_Handlers that are passed in via the - * notify queue before breaking out of its - * loop. - */ - virtual int max_notify_iterations (void); - - /** - * Purge any notifications pending in this reactor for the specified - * ACE_Event_Handler object. Returns the number of notifications - * purged. Returns -1 on error. - */ - virtual int purge_pending_notifications (ACE_Event_Handler * = 0, - ACE_Reactor_Mask = ACE_Event_Handler::ALL_EVENTS_MASK); - - // = Assorted helper methods. - - /** - * Return the Event_Handler associated with . Return 0 if - * is not registered. - */ - ACE_Event_Handler *find_handler (ACE_HANDLE handle); - - /** - * Check to see if is associated with a valid Event_Handler - * bound to @a mask. Return the @a event_handler associated with this - * @a handler if @a event_handler != 0. - */ - virtual int handler (ACE_HANDLE handle, - ACE_Reactor_Mask mask, - ACE_Event_Handler **event_handler = 0); - - /** - * Check to see if @a signum is associated with a valid Event_Handler - * bound to a signal. Return the associated with - * this @a handler if != 0. - */ - virtual int handler (int signum, - ACE_Event_Handler ** = 0); - - /// Returns true if WFMO_Reactor has been successfully initialized, else - /// false. - virtual bool initialized (void); - - /// Returns the current size of the WFMO_Reactor's internal - /// descriptor table. - virtual size_t size (void) const; - - /// Returns a reference to the WFMO_Reactor's internal lock. - virtual ACE_Lock &lock (void); - - /// Wake up all threads in WaitForMultipleObjects so that they can - /// reconsult the handle set - virtual void wakeup_all_threads (void); - - /** - * Transfers ownership of the WFMO_Reactor to the @a new_owner. The - * transfer will not complete until all threads are ready (just like - * the handle set). - */ - virtual int owner (ACE_thread_t new_owner, ACE_thread_t *old_owner = 0); - - /// Return the ID of the "owner" thread. - virtual int owner (ACE_thread_t *owner); - - /// Get the existing restart value. - virtual bool restart (void); - - /// Set a new value for restart and return the original value. - virtual bool restart (bool r); - - /// Not implemented - virtual void requeue_position (int); - - /// Not implemented - virtual int requeue_position (void); - - // = Low-level wait_set mask manipulation methods. - - /** - * Modify @a masks of the @a event_handler's entry in WFMO_Reactor - * depending upon . @a event_handler must already have - * been registered with WFMO_Reactor. - */ - virtual int mask_ops (ACE_Event_Handler *event_handler, - ACE_Reactor_Mask masks, - int operation); - - /** - * Modify @a masks of the 's entry in WFMO_Reactor depending - * upon . must already have been registered - * with WFMO_Reactor. - */ - virtual int mask_ops (ACE_HANDLE handle, - ACE_Reactor_Mask masks, - int ops); - - // = Low-level ready_set mask manipulation methods. - - /// Not implemented - virtual int ready_ops (ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask, - int ops); - - /// Not implemented - virtual int ready_ops (ACE_HANDLE handle, - ACE_Reactor_Mask, - int ops); - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; - - /// Dump the state of an object. - virtual void dump (void) const; - -protected: - /// Registration workhorse - virtual int register_handler_i (ACE_HANDLE event_handle, - ACE_HANDLE io_handle, - ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask); - - /// Event handling workhorse - virtual int event_handling (ACE_Time_Value *max_wait_time = 0, - int alertable = 0); - - /// Bit masking workhorse - virtual int mask_ops_i (ACE_HANDLE io_handle, - ACE_Reactor_Mask masks, - int operation); - - /// Return the ID of the "owner" thread. Does not do any locking. - virtual ACE_thread_t owner_i (void); - - /// Wait up to @a max_wait_time until it's ok to enter - /// WaitForMultipleObjects. Returns 1 (and holding lock_) if ok to wait; - /// -1 (and not holding lock_) if not. - virtual int ok_to_wait (ACE_Time_Value *max_wait_time, - int alertable); - - /// Wait for timer and I/O events to occur. - virtual DWORD wait_for_multiple_events (int timeout, - int alertable); - - /// Check for activity on remaining handles. - virtual DWORD poll_remaining_handles (DWORD slot); - - /// Expire timers. Only the owner thread does useful stuff in this - /// function. - virtual int expire_timers (void); - - /// Dispatches the timers and I/O handlers. - virtual int dispatch (DWORD wait_status); - - /// Protect against structured exceptions caused by user code when - /// dispatching handles - virtual int safe_dispatch (DWORD wait_status); - - /** - * Dispatches any active handles from handles_[@a slot] to - * handles_[active_handles_] using to poll - * through our handle set looking for active handles. - */ - virtual int dispatch_handles (DWORD slot); - - /// Dispatches a single handler. Returns 0 on success, -1 if the - /// handler was removed. - virtual int dispatch_handler (DWORD slot, - DWORD max_handlep1); - - /// Dispatches a single handler. Returns 0 on success, -1 if the - /// handler was removed. - virtual int simple_dispatch_handler (DWORD slot, - ACE_HANDLE event_handle); - - /// Dispatches a single handler. Returns 0 on success, -1 if the - /// handler was removed. - virtual int complex_dispatch_handler (DWORD slot, - ACE_HANDLE event_handle); - - /// Dispatches window messages. Noop for WFMO_Reactor. - virtual int dispatch_window_messages (void); - - virtual ACE_Reactor_Mask upcall (ACE_Event_Handler *event_handler, - ACE_HANDLE io_handle, - WSANETWORKEVENTS &events); - - /// Used to caluculate the next timeout - virtual int calculate_timeout (ACE_Time_Value *time); - - /// Update the state of the handler repository - virtual int update_state (void); - - /// Check to see if we have a new owner - virtual int new_owner (void); - - /// Set owner to new owner - virtual int change_owner (void); - - /// Handle signals without requiring global/static variables. - ACE_Sig_Handler *signal_handler_; - - /// Keeps track of whether we should delete the signal handler (if we - /// didn't create it, then we don't delete it). - bool delete_signal_handler_; - - /// Defined as a pointer to allow overriding by derived classes... - ACE_Timer_Queue *timer_queue_; - - /// Keeps track of whether we should delete the timer queue (if we - /// didn't create it, then we don't delete it). - bool delete_timer_queue_; - - /// Keeps track of whether we should delete the handler repository - bool delete_handler_rep_; - - /// Used when is called. - ACE_Reactor_Notify *notify_handler_; - - /// Keeps track of whether we should delete the notify handler. - bool delete_notify_handler_; - - /** - * Synchronization for the ACE_WFMO_Reactor. - * - * A Process Mutex is used here because of two reasons: - * (a) The implementation of ACE_Thread_Mutex uses CriticalSections - * CriticalSections are not waitable using ::WaitForMultipleObjects - * (b) This is really not a process mutex because it is not - * named. No other process can use this mutex. - */ - ACE_Process_Mutex lock_; - - /// Adapter used to return internal lock to outside world. - ACE_Lock_Adapter lock_adapter_; - - /// Table that maps to 's. - ACE_WFMO_Reactor_Handler_Repository handler_rep_; - - /// A manual event used to block threads from proceeding into - /// WaitForMultipleObjects - ACE_Manual_Event ok_to_wait_; - - /** - * A manual event is used so that we can wake everyone up (e.g., - * when ACE_Event_Handlers are bounded and unbound from the - * handler repository). - */ - ACE_Manual_Event wakeup_all_threads_; - - /// Used when is signaled - ACE_Wakeup_All_Threads_Handler wakeup_all_threads_handler_; - - /// The changing thread waits on this event, till all threads are not - /// active anymore - ACE_Auto_Event waiting_to_change_state_; - - /// Count of currently active threads - size_t active_threads_; - - /** - * The thread which is "owner" of the WFMO_Reactor. The owner - * concept is used because we don't want multiple threads to try to - * expire timers. Therefore the "owner" thread is the only one - * allowed to expire timers. Also, the owner thread is the only - * thread which waits on the notify handle. Note that the ownership - * can be transferred. - */ - ACE_thread_t owner_; - - /// The owner to be of the WFMO_Reactor - ACE_thread_t new_owner_; - - /// This is the thread which is responsible for the changing the - /// state of the handle set - ACE_thread_t change_state_thread_; - - /// This is an array of ACE_HANDLEs which keep track of the - /// and handles - ACE_HANDLE atomic_wait_array_ [2]; - - /// This flag is used to keep track of whether we are already closed. - bool open_for_business_; - - /// This flag is used to keep track of whether we are actively handling - /// events or not. - sig_atomic_t deactivated_; - -private: - /// Deny access since member-wise won't work... - ACE_WFMO_Reactor (const ACE_WFMO_Reactor &); - ACE_WFMO_Reactor &operator = (const ACE_WFMO_Reactor &); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/WFMO_Reactor.inl" -#endif /* __ACE_INLINE__ */ - -#endif /* ACE_WIN32 */ -#include /**/ "ace/post.h" -#endif /* ACE_WFMO_REACTOR_H */ diff --git a/externals/ace/WFMO_Reactor.inl b/externals/ace/WFMO_Reactor.inl deleted file mode 100644 index 6d3e43db67e..00000000000 --- a/externals/ace/WFMO_Reactor.inl +++ /dev/null @@ -1,1202 +0,0 @@ -// -*- C++ -*- -// -// $Id: WFMO_Reactor.inl 82949 2008-10-06 22:32:10Z shuston $ - -#include "ace/Handle_Set.h" -#include "ace/Reactor.h" -#include "ace/Thread.h" -#include "ace/Sig_Handler.h" -#include "ace/OS_NS_errno.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/************************************************************/ - -ACE_INLINE int -ACE_Wakeup_All_Threads_Handler::handle_signal (int /* signum */, - siginfo_t * /* siginfo */, - ucontext_t *) -{ - // This will get called when wakeup_all_threads_> event - // is signaled. There is nothing to be done here. - // ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) waking up to get updated handle set info\n"))); - return 0; -} - -#if defined (ACE_WIN32) - -/************************************************************/ - -ACE_INLINE -ACE_WFMO_Reactor_Handler_Repository::Common_Info::Common_Info (void) - : io_entry_ (false), - event_handler_ (0), - io_handle_ (ACE_INVALID_HANDLE), - network_events_ (0), - delete_event_ (false), - delete_entry_ (false), - close_masks_ (ACE_Event_Handler::NULL_MASK) -{ -} - -ACE_INLINE void -ACE_WFMO_Reactor_Handler_Repository::Common_Info::reset (void) -{ - this->event_handler_ = 0; - this->io_entry_ = false; - this->io_handle_ = ACE_INVALID_HANDLE; - this->network_events_ = 0; - this->delete_event_ = false; - this->delete_entry_ = false; - this->close_masks_ = ACE_Event_Handler::NULL_MASK; -} - -ACE_INLINE void -ACE_WFMO_Reactor_Handler_Repository::Common_Info::set (bool io_entry, - ACE_Event_Handler *event_handler, - ACE_HANDLE io_handle, - long network_events, - bool delete_event, - bool delete_entry, - ACE_Reactor_Mask close_masks) -{ - this->event_handler_ = event_handler; - this->io_entry_ = io_entry; - this->io_handle_ = io_handle; - this->network_events_ = network_events; - this->delete_event_ = delete_event; - this->delete_entry_ = delete_entry; - this->close_masks_ = close_masks; -} - -ACE_INLINE void -ACE_WFMO_Reactor_Handler_Repository::Common_Info::set (Common_Info &common_info) -{ - *this = common_info; -} - -ACE_INLINE void -ACE_WFMO_Reactor_Handler_Repository::Common_Info::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_WFMO_Reactor_Handler_Repository::Common_Info::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("I/O Entry = %d\n"), - this->io_entry_)); - - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("Event Handler = %d\n"), - this->event_handler_)); - - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("I/O Handle = %d\n"), - this->io_handle_)); - - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("Network Events = %d\n"), - this->network_events_)); - - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("Delete Event = %d\n"), - this->delete_event_)); - - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("Delete Entry = %d\n"), - this->delete_entry_)); - - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("Close Masks = %d\n"), - this->close_masks_)); - - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -/************************************************************/ - -ACE_INLINE -ACE_WFMO_Reactor_Handler_Repository::Current_Info::Current_Info (void) - : suspend_entry_ (false) -{ -} - -ACE_INLINE void -ACE_WFMO_Reactor_Handler_Repository::Current_Info::set (bool io_entry, - ACE_Event_Handler *event_handler, - ACE_HANDLE io_handle, - long network_events, - bool delete_event, - bool delete_entry, - ACE_Reactor_Mask close_masks, - bool suspend_entry) -{ - this->suspend_entry_ = suspend_entry; - Common_Info::set (io_entry, - event_handler, - io_handle, - network_events, - delete_event, - delete_entry, - close_masks); -} - -ACE_INLINE void -ACE_WFMO_Reactor_Handler_Repository::Current_Info::set (Common_Info &common_info, - bool suspend_entry) -{ - this->suspend_entry_ = suspend_entry; - Common_Info::set (common_info); -} - -ACE_INLINE void -ACE_WFMO_Reactor_Handler_Repository::Current_Info::reset (void) -{ - this->suspend_entry_ = false; - Common_Info::reset (); -} - -ACE_INLINE void -ACE_WFMO_Reactor_Handler_Repository::Current_Info::dump (ACE_HANDLE event_handle) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_WFMO_Reactor_Handler_Repository::Current_Info::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - - Common_Info::dump (); - - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("Event Handle = %d\n"), - event_handle)); - - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("Suspend Entry = %d\n"), - this->suspend_entry_)); - - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#else /* !ACE_HAS_DUMP */ - ACE_UNUSED_ARG (event_handle); -#endif /* ACE_HAS_DUMP */ -} - -/************************************************************/ - -ACE_INLINE -ACE_WFMO_Reactor_Handler_Repository::To_Be_Added_Info::To_Be_Added_Info (void) - : event_handle_ (ACE_INVALID_HANDLE), - suspend_entry_ (false) -{ -} - -ACE_INLINE void -ACE_WFMO_Reactor_Handler_Repository::To_Be_Added_Info::set (ACE_HANDLE event_handle, - bool io_entry, - ACE_Event_Handler *event_handler, - ACE_HANDLE io_handle, - long network_events, - bool delete_event, - bool delete_entry, - ACE_Reactor_Mask close_masks, - bool suspend_entry) -{ - this->event_handle_ = event_handle; - this->suspend_entry_ = suspend_entry; - Common_Info::set (io_entry, - event_handler, - io_handle, - network_events, - delete_event, - delete_entry, - close_masks); -} - -ACE_INLINE void -ACE_WFMO_Reactor_Handler_Repository::To_Be_Added_Info::set (ACE_HANDLE event_handle, - Common_Info &common_info, - bool suspend_entry) -{ - this->event_handle_ = event_handle; - this->suspend_entry_ = suspend_entry; - Common_Info::set (common_info); -} - -ACE_INLINE void -ACE_WFMO_Reactor_Handler_Repository::To_Be_Added_Info::reset (void) -{ - this->event_handle_ = ACE_INVALID_HANDLE; - this->suspend_entry_ = false; - Common_Info::reset (); -} - -ACE_INLINE void -ACE_WFMO_Reactor_Handler_Repository::To_Be_Added_Info::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_WFMO_Reactor_Handler_Repository::To_Be_Added_Info::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - - Common_Info::dump (); - - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("Event Handle = %d\n"), - this->event_handle_)); - - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("Suspend Entry = %d\n"), - this->suspend_entry_)); - - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -/************************************************************/ - -ACE_INLINE -ACE_WFMO_Reactor_Handler_Repository::Suspended_Info::Suspended_Info (void) - : event_handle_ (ACE_INVALID_HANDLE), - resume_entry_ (false) -{ -} - -ACE_INLINE void -ACE_WFMO_Reactor_Handler_Repository::Suspended_Info::reset (void) -{ - this->event_handle_ = ACE_INVALID_HANDLE; - this->resume_entry_ = false; - Common_Info::reset (); -} - -ACE_INLINE void -ACE_WFMO_Reactor_Handler_Repository::Suspended_Info::set (ACE_HANDLE event_handle, - bool io_entry, - ACE_Event_Handler *event_handler, - ACE_HANDLE io_handle, - long network_events, - bool delete_event, - bool delete_entry, - ACE_Reactor_Mask close_masks, - bool resume_entry) -{ - this->event_handle_ = event_handle; - this->resume_entry_ = resume_entry; - Common_Info::set (io_entry, - event_handler, - io_handle, - network_events, - delete_event, - delete_entry, - close_masks); -} - -ACE_INLINE void -ACE_WFMO_Reactor_Handler_Repository::Suspended_Info::set (ACE_HANDLE event_handle, - Common_Info &common_info, - bool resume_entry) -{ - this->event_handle_ = event_handle; - this->resume_entry_ = resume_entry; - Common_Info::set (common_info); -} - -ACE_INLINE void -ACE_WFMO_Reactor_Handler_Repository::Suspended_Info::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_WFMO_Reactor_Handler_Repository::Suspended_Info::dump"); - - ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); - - Common_Info::dump (); - - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("Event Handle = %d\n"), - this->event_handle_)); - - ACE_DEBUG ((LM_DEBUG, - ACE_TEXT ("Resume Entry = %d\n"), - this->resume_entry_)); - - ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); -#endif /* ACE_HAS_DUMP */ -} - -/************************************************************/ - -ACE_INLINE int -ACE_WFMO_Reactor_Handler_Repository::close (void) -{ - // Let all the handlers know that the is closing down - this->unbind_all (); - - return 0; -} - -ACE_INLINE ACE_HANDLE * -ACE_WFMO_Reactor_Handler_Repository::handles (void) const -{ - // This code is probably too subtle to be useful in the long run... - // The basic idea is that all threads wait on all user handles plus - // the handle. The owner thread additional - // waits on the handle. This is to ensure that only the - // thread get to expire timers and handle event on the - // notify pipe. - if (ACE_Thread::self () == this->wfmo_reactor_.owner_i ()) - return this->current_handles_; - else - return this->current_handles_ + 1; -} - -ACE_INLINE ACE_WFMO_Reactor_Handler_Repository::Current_Info * -ACE_WFMO_Reactor_Handler_Repository::current_info (void) const -{ - if (ACE_Thread::self () == this->wfmo_reactor_.owner_i ()) - return this->current_info_; - else - return this->current_info_ + 1; -} - -ACE_INLINE DWORD -ACE_WFMO_Reactor_Handler_Repository::max_handlep1 (void) const -{ - if (ACE_Thread::self () == this->wfmo_reactor_.owner_i ()) - return this->max_handlep1_; - else - return this->max_handlep1_ - 1; -} - -ACE_INLINE int -ACE_WFMO_Reactor_Handler_Repository::scheduled_for_deletion (size_t slot) const -{ - if (ACE_Thread::self () == this->wfmo_reactor_.owner_i ()) - return this->current_info_[slot].delete_entry_ == true; - else - return this->current_info_[slot + 1].delete_entry_ == true; -} - -ACE_INLINE int -ACE_WFMO_Reactor_Handler_Repository::invalid_handle (ACE_HANDLE handle) const -{ - ACE_TRACE ("ACE_WFMO_Reactor_Handler_Repository::invalid_handle"); - // It's too expensive to perform more exhaustive validity checks on - // Win32 due to the way that they implement SOCKET HANDLEs. - if (handle == ACE_INVALID_HANDLE) - { - errno = EINVAL; - return 1; - } - else - return 0; -} - -ACE_INLINE bool -ACE_WFMO_Reactor_Handler_Repository::changes_required (void) -{ - // Check if handles have be scheduled for additions or removal - return this->handles_to_be_added_ > 0 - || this->handles_to_be_deleted_ > 0 - || this->handles_to_be_suspended_ > 0 - || this->handles_to_be_resumed_ > 0; -} - -ACE_INLINE int -ACE_WFMO_Reactor_Handler_Repository::make_changes (void) -{ - // This method must ONLY be called by the - // change_state_thread_>. We therefore assume that - // there will be no contention for this method and hence no guards - // are neccessary. - - // Deletions and suspensions in current_info_ - this->make_changes_in_current_infos (); - - // Deletions and resumptions in current_suspended_info_ - this->make_changes_in_suspension_infos (); - - // Deletions in to_be_added_info_, or transfers to current_info_ or - // current_suspended_info_ from to_be_added_info_ - this->make_changes_in_to_be_added_infos (); - - return 0; -} - -ACE_INLINE int -ACE_WFMO_Reactor_Handler_Repository::unbind (ACE_HANDLE handle, - ACE_Reactor_Mask mask) -{ - if (this->invalid_handle (handle)) - return -1; - - ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->wfmo_reactor_.lock_, -1); - - bool changes_required = false; - int const result = this->unbind_i (handle, - mask, - changes_required); - - if (changes_required) - // Wake up all threads in WaitForMultipleObjects so that they can - // reconsult the handle set - this->wfmo_reactor_.wakeup_all_threads (); - - return result; -} - -ACE_INLINE int -ACE_WFMO_Reactor::reset_timer_interval - (long timer_id, - const ACE_Time_Value &interval) -{ - ACE_TRACE ("ACE_WFMO_Reactor::reset_timer_interval"); - - if (0 != this->timer_queue_) - { - long result = this->timer_queue_->reset_interval - (timer_id, - interval); - - // Wakeup the owner thread so that it gets the latest timer values - this->notify (); - - return result; - } - - errno = ESHUTDOWN; - return -1; -} - -ACE_INLINE long -ACE_WFMO_Reactor::schedule_timer (ACE_Event_Handler *handler, - const void *arg, - const ACE_Time_Value &delay_time, - const ACE_Time_Value &interval) -{ - ACE_TRACE ("ACE_WFMO_Reactor::schedule_timer"); - - if (0 != this->timer_queue_) - { - long result = this->timer_queue_->schedule - (handler, - arg, - timer_queue_->gettimeofday () + delay_time, - interval); - - // Wakeup the owner thread so that it gets the latest timer values - this->notify (); - - return result; - } - - errno = ESHUTDOWN; - return -1; -} - -ACE_INLINE int -ACE_WFMO_Reactor::cancel_timer (ACE_Event_Handler *handler, - int dont_call_handle_close) -{ - ACE_TRACE ("ACE_WFMO_Reactor::cancel_timer"); - if (0 != this->timer_queue_) - return this->timer_queue_->cancel (handler, dont_call_handle_close); - return 0; -} - -ACE_INLINE int -ACE_WFMO_Reactor::cancel_timer (long timer_id, - const void **arg, - int dont_call_handle_close) -{ - ACE_TRACE ("ACE_WFMO_Reactor::cancel_timer"); - if (0 != this->timer_queue_) - return this->timer_queue_->cancel (timer_id, arg, dont_call_handle_close); - return 0; -} - -ACE_INLINE int -ACE_WFMO_Reactor::register_handler (ACE_Event_Handler *event_handler, - ACE_HANDLE event_handle) -{ - // This GUARD is necessary since we are updating shared state. - ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); - - return this->handler_rep_.bind_i (0, - event_handler, - 0, - ACE_INVALID_HANDLE, - event_handle, - 0); -} - -ACE_INLINE int -ACE_WFMO_Reactor::register_handler (ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask) -{ - // This GUARD is necessary since we are updating shared state. - ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); - - return this->register_handler_i (ACE_INVALID_HANDLE, - ACE_INVALID_HANDLE, - event_handler, - mask); -} - -ACE_INLINE int -ACE_WFMO_Reactor::register_handler (ACE_HANDLE io_handle, - ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask) -{ - // This GUARD is necessary since we are updating shared state. - ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); - - return this->register_handler_i (ACE_INVALID_HANDLE, - io_handle, - event_handler, - mask); -} - -ACE_INLINE int -ACE_WFMO_Reactor::register_handler (ACE_HANDLE event_handle, - ACE_HANDLE io_handle, - ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask) -{ - // This GUARD is necessary since we are updating shared state. - ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); - - return this->register_handler_i (event_handle, - io_handle, - event_handler, - mask); -} - -ACE_INLINE int -ACE_WFMO_Reactor::register_handler (const ACE_Handle_Set &handles, - ACE_Event_Handler *handler, - ACE_Reactor_Mask mask) -{ - // This GUARD is necessary since we are updating shared state. - ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); - - ACE_Handle_Set_Iterator handle_iter (handles); - ACE_HANDLE h; - - while ((h = handle_iter ()) != ACE_INVALID_HANDLE) - if (this->register_handler_i (h, - ACE_INVALID_HANDLE, - handler, - mask) == -1) - return -1; - - return 0; -} - -ACE_INLINE int -ACE_WFMO_Reactor::schedule_wakeup (ACE_HANDLE io_handle, - ACE_Reactor_Mask masks_to_be_added) -{ - // This GUARD is necessary since we are updating shared state. - ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); - - return this->mask_ops_i (io_handle, - masks_to_be_added, - ACE_Reactor::ADD_MASK); -} - -ACE_INLINE int -ACE_WFMO_Reactor::schedule_wakeup (ACE_Event_Handler *event_handler, - ACE_Reactor_Mask masks_to_be_added) -{ - // This GUARD is necessary since we are updating shared state. - ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); - - return this->mask_ops_i (event_handler->get_handle (), - masks_to_be_added, - ACE_Reactor::ADD_MASK); -} - -ACE_INLINE int -ACE_WFMO_Reactor::cancel_wakeup (ACE_HANDLE io_handle, - ACE_Reactor_Mask masks_to_be_removed) -{ - // This GUARD is necessary since we are updating shared state. - ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); - - return this->mask_ops_i (io_handle, - masks_to_be_removed, - ACE_Reactor::CLR_MASK); -} - -ACE_INLINE int -ACE_WFMO_Reactor::cancel_wakeup (ACE_Event_Handler *event_handler, - ACE_Reactor_Mask masks_to_be_removed) -{ - // This GUARD is necessary since we are updating shared state. - ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); - - return this->mask_ops_i (event_handler->get_handle (), - masks_to_be_removed, - ACE_Reactor::CLR_MASK); -} - -ACE_INLINE int -ACE_WFMO_Reactor::remove_handler (ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask) -{ - return this->handler_rep_.unbind (event_handler->get_handle (), - mask); -} - -ACE_INLINE int -ACE_WFMO_Reactor::remove_handler (ACE_HANDLE handle, - ACE_Reactor_Mask mask) -{ - return this->handler_rep_.unbind (handle, - mask); -} - -ACE_INLINE int -ACE_WFMO_Reactor::remove_handler (const ACE_Handle_Set &handles, - ACE_Reactor_Mask mask) -{ - ACE_Handle_Set_Iterator handle_iter (handles); - ACE_HANDLE h; - bool changes_required = false; - - ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); - - while ((h = handle_iter ()) != ACE_INVALID_HANDLE) - if (this->handler_rep_.unbind_i (h, - mask, - changes_required) == -1) - return -1; - - // Wake up all threads in WaitForMultipleObjects so that they can - // reconsult the handle set - this->wakeup_all_threads (); - - return 0; -} - -ACE_INLINE int -ACE_WFMO_Reactor::suspend_handler (ACE_HANDLE handle) -{ - ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); - - bool changes_required = false; - int const result = - this->handler_rep_.suspend_handler_i (handle, - changes_required); - - if (changes_required) - // Wake up all threads in WaitForMultipleObjects so that they can - // reconsult the handle set - this->wakeup_all_threads (); - - return result; -} - -ACE_INLINE int -ACE_WFMO_Reactor::suspend_handler (ACE_Event_Handler *event_handler) -{ - return this->suspend_handler (event_handler->get_handle ()); -} - -ACE_INLINE int -ACE_WFMO_Reactor::suspend_handler (const ACE_Handle_Set &handles) -{ - ACE_Handle_Set_Iterator handle_iter (handles); - ACE_HANDLE h; - bool changes_required = false; - - ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); - - while ((h = handle_iter ()) != ACE_INVALID_HANDLE) - if (this->handler_rep_.suspend_handler_i (h, - changes_required) == -1) - return -1; - - // Wake up all threads in WaitForMultipleObjects so that they can - // reconsult the handle set - this->wakeup_all_threads (); - - return 0; -} - -ACE_INLINE int -ACE_WFMO_Reactor::suspend_handlers (void) -{ - bool error = false; - int result = 0; - ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); - - // First suspend all current handles - bool changes_required = false; - - // Skip over the notify and wakeup_all_threads handles. These are registered - // by ACE_WFMO_Reactor::open(), not by users, and should not be suspended. - for (size_t i = 2; - i < this->handler_rep_.max_handlep1_ && !error; - i++) - { - result = - this->handler_rep_.suspend_handler_i (this->handler_rep_.current_handles_[i], - changes_required); - if (result == -1) - error = true; - } - - // Then suspend all to_be_added_handles - for (size_t i = 0; - i < this->handler_rep_.handles_to_be_added_ && !error; - i++) - { - if (this->handler_rep_.to_be_added_info_[i].io_entry_) - { - result = - this->handler_rep_.suspend_handler_i (this->handler_rep_.to_be_added_info_[i].io_handle_, - changes_required); - } - else - { - result = - this->handler_rep_.suspend_handler_i (this->handler_rep_.to_be_added_info_[i].event_handle_, - changes_required); - } - if (result == -1) - error = true; - } - - // Wake up all threads in WaitForMultipleObjects so that they can - // reconsult the handle set - this->wakeup_all_threads (); - - return error ? -1 : 0; -} - -ACE_INLINE int -ACE_WFMO_Reactor::resume_handler (ACE_HANDLE handle) -{ - ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); - - bool changes_required = false; - int result = - this->handler_rep_.resume_handler_i (handle, changes_required); - - if (changes_required) - // Wake up all threads in WaitForMultipleObjects so that they can - // reconsult the handle set - this->wakeup_all_threads (); - - return result; -} - -ACE_INLINE int -ACE_WFMO_Reactor::resume_handler (ACE_Event_Handler *event_handler) -{ - return this->resume_handler (event_handler->get_handle ()); -} - -ACE_INLINE int -ACE_WFMO_Reactor::resume_handler (const ACE_Handle_Set &handles) -{ - ACE_Handle_Set_Iterator handle_iter (handles); - ACE_HANDLE h; - bool changes_required = false; - - ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); - - while ((h = handle_iter ()) != ACE_INVALID_HANDLE) - if (this->handler_rep_.resume_handler_i (h, - changes_required) == -1) - return -1; - - // Wake up all threads in WaitForMultipleObjects so that they can - // reconsult the handle set - this->wakeup_all_threads (); - - return 0; -} - -ACE_INLINE int -ACE_WFMO_Reactor::resume_handlers (void) -{ - bool error = false; - int result = 0; - ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); - - bool changes_required = false; - for (size_t i = 0; - i < this->handler_rep_.suspended_handles_ && !error; - i++) - { - result = - this->handler_rep_.resume_handler_i (this->handler_rep_.current_suspended_info_[i].event_handle_, - changes_required); - if (result == -1) - error = true; - } - - // Then resume all to_be_added_handles - for (size_t i = 0; - i < this->handler_rep_.handles_to_be_added_ && !error; - i++) - { - if (this->handler_rep_.to_be_added_info_[i].io_entry_) - { - result = - this->handler_rep_.resume_handler_i (this->handler_rep_.to_be_added_info_[i].io_handle_, - changes_required); - } - else - { - result = - this->handler_rep_.resume_handler_i (this->handler_rep_.to_be_added_info_[i].event_handle_, - changes_required); - } - if (result == -1) - error = true; - } - - // Wake up all threads in WaitForMultipleObjects so that they can - // reconsult the handle set - this->wakeup_all_threads (); - - return error ? -1 : 0; -} - -ACE_INLINE bool -ACE_WFMO_Reactor::uses_event_associations (void) -{ - // Since the WFMO_Reactor does use event associations, this function - // always return 1. - return true; -} - -ACE_INLINE int -ACE_WFMO_Reactor::handle_events (ACE_Time_Value &how_long) -{ - return this->event_handling (&how_long, FALSE); -} - -ACE_INLINE int -ACE_WFMO_Reactor::alertable_handle_events (ACE_Time_Value &how_long) -{ - return this->event_handling (&how_long, TRUE); -} - -ACE_INLINE int -ACE_WFMO_Reactor::handle_events (ACE_Time_Value *how_long) -{ - return this->event_handling (how_long, FALSE); -} - -ACE_INLINE int -ACE_WFMO_Reactor::alertable_handle_events (ACE_Time_Value *how_long) -{ - return this->event_handling (how_long, TRUE); -} - -ACE_INLINE int -ACE_WFMO_Reactor::deactivated (void) -{ - return this->deactivated_; -} - -ACE_INLINE void -ACE_WFMO_Reactor::deactivate (int do_stop) -{ - this->deactivated_ = do_stop; - this->wakeup_all_threads (); -} - -ACE_INLINE int -ACE_WFMO_Reactor::owner (ACE_thread_t *t) -{ - ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); - *t = this->owner_i (); - return 0; -} - -ACE_INLINE ACE_thread_t -ACE_WFMO_Reactor::owner_i (void) -{ - return this->owner_; -} - -ACE_INLINE int -ACE_WFMO_Reactor::owner (ACE_thread_t new_owner, ACE_thread_t *old_owner) -{ - ACE_GUARD_RETURN (ACE_Process_Mutex, monitor, this->lock_, -1); - this->new_owner_ = new_owner; - - if (old_owner != 0) - *old_owner = this->owner_i (); - - // Wake up all threads in WaitForMultipleObjects so that they can - // reconsult the new owner responsibilities - this->wakeup_all_threads (); - - return 0; -} - -ACE_INLINE int -ACE_WFMO_Reactor::new_owner (void) -{ - return this->new_owner_ != ACE_thread_t (0); -} - -ACE_INLINE int -ACE_WFMO_Reactor::change_owner (void) -{ - this->owner_ = this->new_owner_; - this->new_owner_ = ACE_thread_t (0); - return 0; -} - -ACE_INLINE int -ACE_WFMO_Reactor::safe_dispatch (DWORD wait_status) -{ - int result = -1; - ACE_SEH_TRY - { - result = this->dispatch (wait_status); - } - ACE_SEH_FINALLY - { - this->update_state (); - } - - return result; -} - -ACE_INLINE int -ACE_WFMO_Reactor::dispatch_window_messages (void) -{ - return 0; -} - -ACE_INLINE void -ACE_WFMO_Reactor::wakeup_all_threads (void) -{ - this->wakeup_all_threads_.signal (); -} - -ACE_INLINE int -ACE_WFMO_Reactor::notify (ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask, - ACE_Time_Value *timeout) -{ - return this->notify_handler_->notify (event_handler, mask, timeout); -} - -ACE_INLINE int -ACE_WFMO_Reactor::register_handler (int signum, - ACE_Event_Handler *new_sh, - ACE_Sig_Action *new_disp, - ACE_Event_Handler **old_sh, - ACE_Sig_Action *old_disp) -{ - return this->signal_handler_->register_handler (signum, - new_sh, new_disp, - old_sh, old_disp); -} - -ACE_INLINE int -ACE_WFMO_Reactor::register_handler (const ACE_Sig_Set &sigset, - ACE_Event_Handler *new_sh, - ACE_Sig_Action *new_disp) -{ - int result = 0; - -#if (ACE_NSIG > 0) - for (int s = 1; s < ACE_NSIG; s++) - if (sigset.is_member (s) - && this->signal_handler_->register_handler (s, - new_sh, - new_disp) == -1) - result = -1; -#else - ACE_UNUSED_ARG (sigset); - ACE_UNUSED_ARG (new_sh); - ACE_UNUSED_ARG (new_disp); -#endif /* ACE_NSIG */ - - return result; -} - -ACE_INLINE int -ACE_WFMO_Reactor::remove_handler (int signum, - ACE_Sig_Action *new_disp, - ACE_Sig_Action *old_disp, - int sigkey) -{ - return this->signal_handler_->remove_handler (signum, - new_disp, - old_disp, - sigkey); -} - -ACE_INLINE int -ACE_WFMO_Reactor::remove_handler (const ACE_Sig_Set &sigset) -{ - int result = 0; - -#if (ACE_NSIG > 0) - for (int s = 1; s < ACE_NSIG; s++) - if (sigset.is_member (s) - && this->signal_handler_->remove_handler (s) == -1) - result = -1; -#else - ACE_UNUSED_ARG (sigset); -#endif /* ACE_NSIG */ - - return result; -} - -ACE_INLINE int -ACE_WFMO_Reactor::handler (int signum, ACE_Event_Handler **eh) -{ - ACE_Event_Handler *handler = - this->signal_handler_->handler (signum); - - if (handler == 0) - return -1; - else if (eh != 0) - *eh = handler; - return 0; -} - -ACE_INLINE int -ACE_WFMO_Reactor::mask_ops (ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask, - int operation) -{ - ACE_GUARD_RETURN (ACE_Process_Mutex, monitor, this->lock_, -1); - - return this->mask_ops_i (event_handler->get_handle (), - mask, - operation); -} - -ACE_INLINE int -ACE_WFMO_Reactor::mask_ops (ACE_HANDLE io_handle, - ACE_Reactor_Mask mask, - int operation) -{ - ACE_GUARD_RETURN (ACE_Process_Mutex, monitor, this->lock_, -1); - - return this->mask_ops_i (io_handle, - mask, - operation); -} - -ACE_INLINE void -ACE_WFMO_Reactor::requeue_position (int) -{ - // Not implemented -} - -ACE_INLINE int -ACE_WFMO_Reactor::requeue_position (void) -{ - // Don't have an implementation for this yet... - ACE_NOTSUP_RETURN (-1); -} - -ACE_INLINE bool -ACE_WFMO_Reactor::restart (void) -{ - return false; -} - -ACE_INLINE bool -ACE_WFMO_Reactor::restart (bool) -{ - return false; -} - -ACE_INLINE int -ACE_WFMO_Reactor::ready_ops (ACE_Event_Handler *event_handler, - ACE_Reactor_Mask mask, - int ops) -{ - // Don't have an implementation for this yet... - ACE_UNUSED_ARG (event_handler); - ACE_UNUSED_ARG (mask); - ACE_UNUSED_ARG (ops); - ACE_NOTSUP_RETURN (-1); -} - -ACE_INLINE int -ACE_WFMO_Reactor::ready_ops (ACE_HANDLE handle, - ACE_Reactor_Mask, - int ops) -{ - // Don't have an implementation for this yet... - ACE_UNUSED_ARG (handle); - ACE_UNUSED_ARG (ops); - ACE_NOTSUP_RETURN (-1); -} - -ACE_INLINE ACE_Event_Handler * -ACE_WFMO_Reactor::find_handler (ACE_HANDLE handle) -{ - ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, 0); - - return this->handler_rep_.find_handler (handle); -} - -ACE_INLINE int -ACE_WFMO_Reactor::handler (ACE_HANDLE handle, - ACE_Reactor_Mask mask, - ACE_Event_Handler **event_handler) -{ - ACE_GUARD_RETURN (ACE_Process_Mutex, ace_mon, this->lock_, -1); - - return this->handler_rep_.handler (handle, - mask, - event_handler); -} - -ACE_INLINE bool -ACE_WFMO_Reactor::initialized (void) -{ - return this->open_for_business_; -} - -ACE_INLINE ACE_Lock & -ACE_WFMO_Reactor::lock (void) -{ - return this->lock_adapter_; -} - -ACE_INLINE size_t -ACE_WFMO_Reactor::size (void) const -{ - // Size of repository minus the 2 used for internal purposes - return this->handler_rep_.max_size_ - 2; -} -#else -ACE_INLINE bool -ACE_WFMO_Reactor_Handler_Repository::changes_required (void) -{ - return false; -} - -ACE_INLINE int -ACE_WFMO_Reactor_Handler_Repository::make_changes (void) -{ - return 0; -} - -ACE_INLINE -ACE_WFMO_Reactor_Handler_Repository::~ACE_WFMO_Reactor_Handler_Repository (void) -{ -} - -#endif /* ACE_WIN32 */ - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/WIN32_Asynch_IO.cpp b/externals/ace/WIN32_Asynch_IO.cpp deleted file mode 100644 index 3dd6efcd1c5..00000000000 --- a/externals/ace/WIN32_Asynch_IO.cpp +++ /dev/null @@ -1,3782 +0,0 @@ -// $Id: WIN32_Asynch_IO.cpp 89454 2010-03-11 09:35:25Z johnnyw $ - -#include "ace/WIN32_Asynch_IO.h" - -ACE_RCSID (ace, - Win32_Asynch_IO, - "$Id: WIN32_Asynch_IO.cpp 89454 2010-03-11 09:35:25Z johnnyw $") - -#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) && \ - (defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 == 1)) - -#include "ace/WIN32_Proactor.h" -#include "ace/Proactor.h" -#include "ace/Message_Block.h" -#include "ace/Service_Config.h" -#include "ace/INET_Addr.h" -#include "ace/Task_T.h" -#include "ace/OS_NS_errno.h" -#include "ace/OS_NS_unistd.h" -#include "ace/OS_NS_sys_socket.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -size_t -ACE_WIN32_Asynch_Result::bytes_transferred (void) const -{ - return this->bytes_transferred_; -} - -const void * -ACE_WIN32_Asynch_Result::act (void) const -{ - return this->act_; -} - -int -ACE_WIN32_Asynch_Result::success (void) const -{ - return this->success_; -} - -const void * -ACE_WIN32_Asynch_Result::completion_key (void) const -{ - return this->completion_key_; -} - -u_long -ACE_WIN32_Asynch_Result::error (void) const -{ - return this->error_; -} - -ACE_HANDLE -ACE_WIN32_Asynch_Result::event (void) const -{ - return this->hEvent; -} - -u_long -ACE_WIN32_Asynch_Result::offset (void) const -{ - return this->Offset; -} - -u_long -ACE_WIN32_Asynch_Result::offset_high (void) const -{ - return this->OffsetHigh; -} - -int -ACE_WIN32_Asynch_Result::priority (void) const -{ - ACE_NOTSUP_RETURN (0); -} - -int -ACE_WIN32_Asynch_Result::signal_number (void) const -{ - ACE_NOTSUP_RETURN (0); -} - -int -ACE_WIN32_Asynch_Result::post_completion (ACE_Proactor_Impl *proactor) -{ - // Get to the platform specific implementation. - ACE_WIN32_Proactor *win32_proactor = dynamic_cast (proactor); - - if (win32_proactor == 0) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("Dynamic cast to WIN32 Proactor failed\n")), - -1); - - // Post myself. - return win32_proactor->post_completion (this); -} - -void -ACE_WIN32_Asynch_Result::set_bytes_transferred (size_t nbytes) -{ - this->bytes_transferred_ = nbytes; -} - -void -ACE_WIN32_Asynch_Result::set_error (u_long errcode) -{ - this->error_ = errcode; -} - -ACE_WIN32_Asynch_Result::~ACE_WIN32_Asynch_Result (void) -{ -} - -ACE_WIN32_Asynch_Result::ACE_WIN32_Asynch_Result - (const ACE_Handler::Proxy_Ptr &handler_proxy, - const void* act, - ACE_HANDLE event, - u_long offset, - u_long offset_high, - int priority, - int signal_number) - : ACE_Asynch_Result_Impl (), - OVERLAPPED (), - handler_proxy_ (handler_proxy), - act_ (act), - bytes_transferred_ (0), - success_ (0), - completion_key_ (0), - error_ (0) -{ - // Set the ACE_OVERLAPPED structure - this->Internal = 0; - this->InternalHigh = 0; - this->Offset = offset; - this->OffsetHigh = offset_high; - this->hEvent = event; - - ACE_UNUSED_ARG (priority); - ACE_UNUSED_ARG (signal_number); -} - -int -ACE_WIN32_Asynch_Operation::open (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor) -{ - this->proactor_ = proactor; - this->handler_proxy_ = handler_proxy; - this->handle_ = handle; - - // Grab the handle from the if is invalid - if (this->handle_ == ACE_INVALID_HANDLE) - { - ACE_Handler *handler = handler_proxy.get ()->handler (); - if (handler != 0) - this->handle_ = handler->handle (); - } - if (this->handle_ == ACE_INVALID_HANDLE) - return -1; - - if (this->proactor_!= 0) - // update implementation. - this->win32_proactor_ = - dynamic_cast (this->proactor_->implementation ()); - - // Register with the . - return this->win32_proactor_->register_handle (this->handle_, - completion_key); -} - -int -ACE_WIN32_Asynch_Operation::cancel (void) -{ -#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) - // All I/O operations that are canceled will complete with the error - // ERROR_OPERATION_ABORTED. All completion notifications for the I/O - // operations will occur normally. - - // @@ This API returns 0 on failure. So, I am returning -1 in that - // case. Is that right? (Alex). - int const result = (int) ::CancelIo (this->handle_); - - if (result == 0) - // Couldn't cancel the operations. - return 2; - - // result is non-zero. All the operations are cancelled then. - return 0; - -#else /* !ACE_HAS_WIN32_OVERLAPPED_IO */ - ACE_NOTSUP_RETURN (-1); -#endif /* ACE_HAS_AIO_CALLS */ -} - -ACE_Proactor * -ACE_WIN32_Asynch_Operation::proactor (void) const -{ - return this->proactor_; -} - -ACE_WIN32_Asynch_Operation::ACE_WIN32_Asynch_Operation (ACE_WIN32_Proactor *win32_proactor) - : ACE_Asynch_Operation_Impl (), - win32_proactor_ (win32_proactor), - proactor_ (0), - handle_ (ACE_INVALID_HANDLE) -{ -} - -ACE_WIN32_Asynch_Operation::~ACE_WIN32_Asynch_Operation (void) -{ -} - -// ************************************************************ - -size_t -ACE_WIN32_Asynch_Read_Stream_Result::bytes_to_read (void) const -{ - return this->bytes_to_read_; -} - -ACE_Message_Block & -ACE_WIN32_Asynch_Read_Stream_Result::message_block (void) const -{ - return this->message_block_; -} - -ACE_HANDLE -ACE_WIN32_Asynch_Read_Stream_Result::handle (void) const -{ - return this->handle_; -} - -ACE_WIN32_Asynch_Read_Stream_Result::ACE_WIN32_Asynch_Read_Stream_Result ( - const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - ACE_Message_Block &message_block, - size_t bytes_to_read, - const void* act, - ACE_HANDLE event, - int priority, - int signal_number, - int scatter_enabled) - : ACE_Asynch_Result_Impl (), - ACE_Asynch_Read_Stream_Result_Impl (), - ACE_WIN32_Asynch_Result (handler_proxy, - act, - event, - 0, - 0, - priority, - signal_number), - bytes_to_read_ (bytes_to_read), - message_block_ (message_block), - handle_ (handle), - scatter_enabled_ (scatter_enabled) -{ -} - -void -ACE_WIN32_Asynch_Read_Stream_Result::complete (size_t bytes_transferred, - int success, - const void *completion_key, - u_long error) -{ - // Copy the data which was returned by GetQueuedCompletionStatus - this->bytes_transferred_ = bytes_transferred; - this->success_ = success; - this->completion_key_ = completion_key; - this->error_ = error; - - // Appropriately move the pointers in the message block. - if (!this->scatter_enabled ()) - this->message_block_.wr_ptr (bytes_transferred); - else - { - for (ACE_Message_Block* mb = &this->message_block_; - (mb != 0) && (bytes_transferred > 0); - mb = mb->cont ()) - { - size_t len_part = mb->space (); - - if (len_part > bytes_transferred) - len_part = bytes_transferred; - - mb->wr_ptr (len_part); - - bytes_transferred -= len_part; - } - } - - // Create the interface result class. - ACE_Asynch_Read_Stream::Result result (this); - - // Call the application handler. - ACE_Handler *handler = this->handler_proxy_.get ()->handler (); - if (handler != 0) - handler->handle_read_stream (result); -} - -ACE_WIN32_Asynch_Read_Stream_Result::~ACE_WIN32_Asynch_Read_Stream_Result (void) -{ -} - -// Base class operations. These operations are here to kill dominance -// warnings. These methods call the base class methods. - -size_t -ACE_WIN32_Asynch_Read_Stream_Result::bytes_transferred (void) const -{ - return ACE_WIN32_Asynch_Result::bytes_transferred (); -} - -const void * -ACE_WIN32_Asynch_Read_Stream_Result::act (void) const -{ - return ACE_WIN32_Asynch_Result::act (); -} - -int -ACE_WIN32_Asynch_Read_Stream_Result::success (void) const -{ - return ACE_WIN32_Asynch_Result::success (); -} - -const void * -ACE_WIN32_Asynch_Read_Stream_Result::completion_key (void) const -{ - return ACE_WIN32_Asynch_Result::completion_key (); -} - -u_long -ACE_WIN32_Asynch_Read_Stream_Result::error (void) const -{ - return ACE_WIN32_Asynch_Result::error (); -} - -ACE_HANDLE -ACE_WIN32_Asynch_Read_Stream_Result::event (void) const -{ - return ACE_WIN32_Asynch_Result::event (); -} - -u_long -ACE_WIN32_Asynch_Read_Stream_Result::offset (void) const -{ - return ACE_WIN32_Asynch_Result::offset (); -} - -u_long -ACE_WIN32_Asynch_Read_Stream_Result::offset_high (void) const -{ - return ACE_WIN32_Asynch_Result::offset_high (); -} - -int -ACE_WIN32_Asynch_Read_Stream_Result::priority (void) const -{ - return ACE_WIN32_Asynch_Result::priority (); -} - -int -ACE_WIN32_Asynch_Read_Stream_Result::signal_number (void) const -{ - return ACE_WIN32_Asynch_Result::signal_number (); -} - -int -ACE_WIN32_Asynch_Read_Stream_Result::post_completion (ACE_Proactor_Impl *proactor) -{ - return ACE_WIN32_Asynch_Result::post_completion (proactor); -} - -int -ACE_WIN32_Asynch_Read_Stream_Result::scatter_enabled (void) const -{ - return this->scatter_enabled_; -} - -ACE_WIN32_Asynch_Read_Stream::ACE_WIN32_Asynch_Read_Stream (ACE_WIN32_Proactor *win32_proactor) - : ACE_Asynch_Operation_Impl (), - ACE_Asynch_Read_Stream_Impl (), - ACE_WIN32_Asynch_Operation (win32_proactor) -{ -} - -int -ACE_WIN32_Asynch_Read_Stream::read (ACE_Message_Block &message_block, - size_t bytes_to_read, - const void *act, - int priority, - int signal_number) -{ - size_t space = message_block.space (); - if (bytes_to_read > space) - bytes_to_read = space; - - if (bytes_to_read == 0) - { - errno = ENOSPC; - return -1; - } - - // Create the Asynch_Result. - ACE_WIN32_Asynch_Read_Stream_Result *result = 0; - ACE_NEW_RETURN (result, - ACE_WIN32_Asynch_Read_Stream_Result (this->handler_proxy_, - this->handle_, - message_block, - bytes_to_read, - act, - this->win32_proactor_->get_handle (), - priority, - signal_number), - -1); - - // Shared read - int const return_val = this->shared_read (result); - - // Upon errors - if (return_val == -1) - delete result; - - return return_val; -} - -int -ACE_WIN32_Asynch_Read_Stream::readv (ACE_Message_Block &message_block, - size_t bytes_to_read, - const void *act, - int priority, - int signal_number) -{ -#if (defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0)) - iovec iov[ACE_IOV_MAX]; - int iovcnt = 0; - - // We should not read more than user requested, - // but it is allowed to read less - - for (const ACE_Message_Block* msg = &message_block; - msg != 0 && bytes_to_read > 0 && iovcnt < ACE_IOV_MAX; - msg = msg->cont () , ++iovcnt ) - { - size_t msg_space = msg->space (); - - // OS should correctly process zero length buffers - // if ( msg_space == 0 ) - // ACE_ERROR_RETURN ((LM_ERROR, - // ACE_TEXT ("ACE_WIN32_Asynch_Read_Stream::readv:") - // ACE_TEXT ("No space in the message block\n")), - // -1); - - if (msg_space > bytes_to_read) - msg_space = bytes_to_read; - bytes_to_read -= msg_space; - - // Make as many iovec as needed to fit all of msg_space. - size_t wr_ptr_offset = 0; - - while (msg_space > 0 && iovcnt < ACE_IOV_MAX) - { - u_long this_chunk_length; - if (msg_space > ULONG_MAX) - this_chunk_length = ULONG_MAX; - else - this_chunk_length = static_cast (msg_space); - // Collect the data in the iovec. - iov[iovcnt].iov_base = msg->wr_ptr () + wr_ptr_offset; - iov[iovcnt].iov_len = this_chunk_length; - msg_space -= this_chunk_length; - wr_ptr_offset += this_chunk_length; - - // Increment iovec counter if there's more to do. - if (msg_space > 0) - ++iovcnt; - } - if (msg_space > 0) // Ran out of iovecs before msg_space exhausted - { - errno = ERANGE; - return -1; - } - } - - // Re-calculate number bytes to read - bytes_to_read = 0; - - for (int i = 0; i < iovcnt ; ++i) - bytes_to_read += iov[i].iov_len; - - if (bytes_to_read == 0) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("ACE_WIN32_Asynch_Read_Stream::readv:") - ACE_TEXT ("Attempt to read 0 bytes\n")), - -1); - - // Create the Asynch_Result. - ACE_WIN32_Asynch_Read_Stream_Result *result = 0; - ACE_NEW_RETURN (result, - ACE_WIN32_Asynch_Read_Stream_Result (this->handler_proxy_, - this->handle_, - message_block, - bytes_to_read, - act, - this->win32_proactor_->get_handle (), - priority, - signal_number, - 1), // scatter read enabled - -1); - - // do the scatter recv - - result->set_error (0); // Clear error before starting IO. - - DWORD bytes_recvd = 0; - u_long flags = 0; - - int initiate_result = ::WSARecv (reinterpret_cast (result->handle ()), - reinterpret_cast (iov), - iovcnt, - &bytes_recvd, - &flags, - result, - 0); - - if (0 == initiate_result) - // Immediate success: the OVERLAPPED will still get queued. - return 1; - - ACE_ASSERT (initiate_result == SOCKET_ERROR); - - // If initiate failed, check for a bad error. - ACE_OS::set_errno_to_last_error (); - switch (errno) - { - case ERROR_IO_PENDING: - // The IO will complete proactively: the OVERLAPPED will still - // get queued. - initiate_result = 0; - break; - - default: - // Something else went wrong: the OVERLAPPED will not get - // queued. - - if (ACE::debug ()) - { - ACE_DEBUG ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("WSARecv"))); - } - - delete result; - initiate_result = -1; - break; - } - - return initiate_result; -#else - ACE_UNUSED_ARG (message_block); - ACE_UNUSED_ARG (bytes_to_read); - ACE_UNUSED_ARG (act); - ACE_UNUSED_ARG (priority); - ACE_UNUSED_ARG (signal_number); - ACE_NOTSUP_RETURN (-1); -#endif /* ACE_HAS_WINSOCK2 && ACE_HAS_WINSOCK2 != 0 */ -} - -ACE_WIN32_Asynch_Read_Stream::~ACE_WIN32_Asynch_Read_Stream (void) -{ -} - -int -ACE_WIN32_Asynch_Read_Stream::shared_read (ACE_WIN32_Asynch_Read_Stream_Result *result) -{ - // ReadFile API limits us to DWORD range. - if (result->bytes_to_read () > MAXDWORD) - { - errno = ERANGE; - return -1; - } - DWORD bytes_to_read = static_cast (result->bytes_to_read ()); - u_long bytes_read; - - result->set_error (0); // Clear error before starting IO. - - // Initiate the read - int initiate_result = ::ReadFile (result->handle (), - result->message_block ().wr_ptr (), - bytes_to_read, - &bytes_read, - result); - if (initiate_result == 1) - // Immediate success: the OVERLAPPED will still get queued. - return 0; - - // If initiate failed, check for a bad error. - ACE_OS::set_errno_to_last_error (); - switch (errno) - { - case ERROR_IO_PENDING: - /* FALLTHRU */ - case ERROR_MORE_DATA: - // The IO will complete proactively: the OVERLAPPED will still - // get queued. - return 0; - - default: - // Something else went wrong: the OVERLAPPED will not get - // queued. - - if (ACE::debug ()) - { - ACE_DEBUG ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ReadFile"))); - } - - return -1; - } -} - -// Methods belong to ACE_WIN32_Asynch_Operation base class. These -// methods are defined here to avoid VC++ warnings. They route the -// call to the ACE_WIN32_Asynch_Operation base class. - -int -ACE_WIN32_Asynch_Read_Stream::open (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor) -{ - return ACE_WIN32_Asynch_Operation::open (handler_proxy, - handle, - completion_key, - proactor); -} - -int -ACE_WIN32_Asynch_Read_Stream::cancel (void) -{ - return ACE_WIN32_Asynch_Operation::cancel (); -} - -ACE_Proactor * -ACE_WIN32_Asynch_Read_Stream::proactor (void) const -{ - return ACE_WIN32_Asynch_Operation::proactor (); -} - -size_t -ACE_WIN32_Asynch_Write_Stream_Result::bytes_to_write (void) const -{ - return this->bytes_to_write_; -} - -ACE_Message_Block & -ACE_WIN32_Asynch_Write_Stream_Result::message_block (void) const -{ - return this->message_block_; -} - -ACE_HANDLE -ACE_WIN32_Asynch_Write_Stream_Result::handle (void) const -{ - return this->handle_; -} - -ACE_WIN32_Asynch_Write_Stream_Result::ACE_WIN32_Asynch_Write_Stream_Result ( - const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - ACE_Message_Block &message_block, - size_t bytes_to_write, - const void* act, - ACE_HANDLE event, - int priority, - int signal_number, - int gather_enabled) - : ACE_Asynch_Result_Impl (), - ACE_Asynch_Write_Stream_Result_Impl (), - ACE_WIN32_Asynch_Result - (handler_proxy, act, event, 0, 0, priority, signal_number), - bytes_to_write_ (bytes_to_write), - message_block_ (message_block), - handle_ (handle), - gather_enabled_ (gather_enabled) -{ -} - -void -ACE_WIN32_Asynch_Write_Stream_Result::complete (size_t bytes_transferred, - int success, - const void *completion_key, - u_long error) -{ - // Copy the data which was returned by . - this->bytes_transferred_ = bytes_transferred; - this->success_ = success; - this->completion_key_ = completion_key; - this->error_ = error; - - // Appropriately move the pointers in the message block. - if (!this->gather_enabled ()) - this->message_block_.rd_ptr (bytes_transferred); - else - { - for (ACE_Message_Block* mb = &this->message_block_; - (mb != 0) && (bytes_transferred > 0); - mb = mb->cont ()) - { - size_t len_part = mb->length (); - - if ( len_part > bytes_transferred) - len_part = bytes_transferred; - - mb->rd_ptr (len_part); - - bytes_transferred -= len_part; - } - } - - // Create the interface result class. - ACE_Asynch_Write_Stream::Result result (this); - - // Call the application handler. - ACE_Handler *handler = this->handler_proxy_.get ()->handler (); - if (handler != 0) - handler->handle_write_stream (result); -} - -ACE_WIN32_Asynch_Write_Stream_Result::~ACE_WIN32_Asynch_Write_Stream_Result (void) -{ -} - -// Base class operations. These operations are here to kill dominance -// warnings. These methods call the base class methods. - -size_t -ACE_WIN32_Asynch_Write_Stream_Result::bytes_transferred (void) const -{ - return ACE_WIN32_Asynch_Result::bytes_transferred (); -} - -const void * -ACE_WIN32_Asynch_Write_Stream_Result::act (void) const -{ - return ACE_WIN32_Asynch_Result::act (); -} - -int -ACE_WIN32_Asynch_Write_Stream_Result::success (void) const -{ - return ACE_WIN32_Asynch_Result::success (); -} - -const void * -ACE_WIN32_Asynch_Write_Stream_Result::completion_key (void) const -{ - return ACE_WIN32_Asynch_Result::completion_key (); -} - -u_long -ACE_WIN32_Asynch_Write_Stream_Result::error (void) const -{ - return ACE_WIN32_Asynch_Result::error (); -} - -ACE_HANDLE -ACE_WIN32_Asynch_Write_Stream_Result::event (void) const -{ - return ACE_WIN32_Asynch_Result::event (); -} - -u_long -ACE_WIN32_Asynch_Write_Stream_Result::offset (void) const -{ - return ACE_WIN32_Asynch_Result::offset (); -} - -u_long -ACE_WIN32_Asynch_Write_Stream_Result::offset_high (void) const -{ - return ACE_WIN32_Asynch_Result::offset_high (); -} - -int -ACE_WIN32_Asynch_Write_Stream_Result::priority (void) const -{ - return ACE_WIN32_Asynch_Result::priority (); -} - -int -ACE_WIN32_Asynch_Write_Stream_Result::signal_number (void) const -{ - return ACE_WIN32_Asynch_Result::signal_number (); -} - -int -ACE_WIN32_Asynch_Write_Stream_Result::post_completion (ACE_Proactor_Impl *proactor) -{ - return ACE_WIN32_Asynch_Result::post_completion (proactor); -} - -int -ACE_WIN32_Asynch_Write_Stream_Result::gather_enabled (void) const -{ - return this->gather_enabled_; -} - -ACE_WIN32_Asynch_Write_Stream::ACE_WIN32_Asynch_Write_Stream (ACE_WIN32_Proactor *win32_proactor) - : ACE_Asynch_Operation_Impl (), - ACE_Asynch_Write_Stream_Impl (), - ACE_WIN32_Asynch_Operation (win32_proactor) -{ -} - -int -ACE_WIN32_Asynch_Write_Stream::write (ACE_Message_Block &message_block, - size_t bytes_to_write, - const void *act, - int priority, - int signal_number) -{ - size_t len = message_block.length(); - - if (bytes_to_write > len) - bytes_to_write = len ; - - if (bytes_to_write == 0) - ACE_ERROR_RETURN - ((LM_ERROR, - ACE_TEXT ("ACE_WIN32_Asynch_Write_Stream::write:") - ACE_TEXT ("Attempt to write 0 bytes\n")), - -1); - - ACE_WIN32_Asynch_Write_Stream_Result *result = 0; - ACE_NEW_RETURN (result, - ACE_WIN32_Asynch_Write_Stream_Result (this->handler_proxy_, - this->handle_, - message_block, - bytes_to_write, - act, - this->win32_proactor_->get_handle (), - priority, - signal_number), - -1); - - // Shared write - int const return_val = this->shared_write (result); - - // Upon errors - if (return_val == -1) - { - delete result; - } - - return return_val; -} - -int -ACE_WIN32_Asynch_Write_Stream::writev (ACE_Message_Block &message_block, - size_t bytes_to_write, - const void *act, - int priority, - int signal_number) -{ -#if (defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0)) - iovec iov[ACE_IOV_MAX]; - int iovcnt = 0; - - // We should not write more than user requested, - // but it is allowed to write less - - for (const ACE_Message_Block* msg = &message_block; - msg != 0 && bytes_to_write > 0 && iovcnt < ACE_IOV_MAX; - msg = msg->cont ()) - { - size_t msg_len = msg->length (); - - // Skip 0-length blocks. - if (msg_len == 0) - continue; - if (msg_len > bytes_to_write) - msg_len = bytes_to_write; - bytes_to_write -= msg_len; - - // Make as many iovec as needed to fit all of msg_len. - size_t rd_ptr_offset = 0; - - while (msg_len > 0 && iovcnt < ACE_IOV_MAX) - { - u_long this_chunk_length; - if (msg_len > ULONG_MAX) - this_chunk_length = ULONG_MAX; - else - this_chunk_length = static_cast (msg_len); - // Collect the data in the iovec. - iov[iovcnt].iov_base = msg->rd_ptr () + rd_ptr_offset; - iov[iovcnt].iov_len = this_chunk_length; - msg_len -= this_chunk_length; - rd_ptr_offset += this_chunk_length; - - // Increment iovec counter if there's more to do. - if (msg_len > 0) - iovcnt++; - } - if (msg_len > 0) // Ran out of iovecs before msg_space exhausted - { - errno = ERANGE; - return -1; - } - ++iovcnt; - } - - // Re-calculate number bytes to write - bytes_to_write = 0; - - for ( int i=0; i < iovcnt ; ++i ) - bytes_to_write += iov[i].iov_len; - - if ( bytes_to_write == 0 ) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("ACE_WIN32_Asynch_Write_Stream::writev:") - ACE_TEXT ("Attempt to write 0 bytes\n")), - -1); - - - ACE_WIN32_Asynch_Write_Stream_Result *result = 0; - ACE_NEW_RETURN (result, - ACE_WIN32_Asynch_Write_Stream_Result (this->handler_proxy_, - this->handle_, - message_block, - bytes_to_write, - act, - this->win32_proactor_->get_handle (), - priority, - signal_number, - 1), // gather write enabled - -1); - - // do the gather send - - u_long bytes_sent = 0; - - int initiate_result = ::WSASend (reinterpret_cast (result->handle ()), - reinterpret_cast (iov), - iovcnt, - &bytes_sent, - 0, // flags - result, - 0); - - if (0 == initiate_result) - // Immediate success: the OVERLAPPED will still get queued. - return 1; - - ACE_ASSERT (initiate_result == SOCKET_ERROR); - - // If initiate failed, check for a bad error. - ACE_OS::set_errno_to_last_error (); - switch (errno) - { - case ERROR_IO_PENDING: - // The IO will complete proactively: the OVERLAPPED will still - // get queued. - initiate_result = 0; - break; - - default: - // Something else went wrong: the OVERLAPPED will not get - // queued. - - if (ACE::debug ()) - { - ACE_DEBUG ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("WSASend"))); - } - - delete result; - initiate_result = -1; - break; - } - - return initiate_result; -#else - ACE_UNUSED_ARG (message_block); - ACE_UNUSED_ARG (bytes_to_write); - ACE_UNUSED_ARG (act); - ACE_UNUSED_ARG (priority); - ACE_UNUSED_ARG (signal_number); - ACE_NOTSUP_RETURN (-1); -#endif /* ACE_HAS_WINSOCK2 && ACE_HAS_WINSOCK2 != 0 */ -} - -ACE_WIN32_Asynch_Write_Stream::~ACE_WIN32_Asynch_Write_Stream (void) -{ -} - -int -ACE_WIN32_Asynch_Write_Stream::shared_write (ACE_WIN32_Asynch_Write_Stream_Result *result) -{ - u_long bytes_written; - if (result->bytes_to_write () > MAXDWORD) - { - errno = ERANGE; - return -1; - } - DWORD bytes_to_write = static_cast (result->bytes_to_write ()); - - result->set_error (0); // Clear error before starting IO. - - // Initiate the write; Winsock 2 is required for the higher-performing - // WSASend() function. For Winsock 1, fall back to the slower WriteFile(). - int initiate_result = 0; -#if (defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0)) - WSABUF iov; - iov.buf = result->message_block ().rd_ptr (); - iov.len = bytes_to_write; - initiate_result = ::WSASend (reinterpret_cast (result->handle ()), - &iov, - 1, - &bytes_written, - 0, // flags - result, - 0); - if (initiate_result == 0) - { - // Immediate success: the OVERLAPPED will still get queued. - return 0; - } -#else - initiate_result = ::WriteFile (result->handle (), - result->message_block ().rd_ptr (), - bytes_to_write, - &bytes_written, - result); - if (initiate_result == 1) - // Immediate success: the OVERLAPPED will still get queued. - return 0; -#endif /* ACE_HAS_WINSOCK2 */ - - // If initiate failed, check for a bad error. - ACE_OS::set_errno_to_last_error (); - switch (errno) - { - case ERROR_IO_PENDING: - // The IO will complete proactively: the OVERLAPPED will still - // get queued. - return 0; - - default: - // Something else went wrong: the OVERLAPPED will not get - // queued. - - if (ACE::debug ()) - ACE_DEBUG ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("Initiating write"))); - return -1; - } -} - -// Methods belong to ACE_WIN32_Asynch_Operation base class. These -// methods are defined here to avoid VC++ warnings. They route the -// call to the ACE_WIN32_Asynch_Operation base class. - -int -ACE_WIN32_Asynch_Write_Stream::open (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor) -{ - return ACE_WIN32_Asynch_Operation::open (handler_proxy, - handle, - completion_key, - proactor); -} - -int -ACE_WIN32_Asynch_Write_Stream::cancel (void) -{ - return ACE_WIN32_Asynch_Operation::cancel (); -} - -ACE_Proactor * -ACE_WIN32_Asynch_Write_Stream::proactor (void) const -{ - return ACE_WIN32_Asynch_Operation::proactor (); -} - -ACE_WIN32_Asynch_Read_File_Result::ACE_WIN32_Asynch_Read_File_Result ( - const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - ACE_Message_Block &message_block, - size_t bytes_to_read, - const void* act, - u_long offset, - u_long offset_high, - ACE_HANDLE event, - int priority, - int signal_number, - int scatter_enabled) - : ACE_Asynch_Result_Impl (), - ACE_Asynch_Read_Stream_Result_Impl (), - ACE_Asynch_Read_File_Result_Impl (), - ACE_WIN32_Asynch_Read_Stream_Result (handler_proxy, - handle, - message_block, - bytes_to_read, - act, - event, - priority, - signal_number, - scatter_enabled) -{ - this->Offset = offset; - this->OffsetHigh = offset_high; -} - -void -ACE_WIN32_Asynch_Read_File_Result::complete (size_t bytes_transferred, - int success, - const void *completion_key, - u_long error) -{ - // Copy the data which was returned by GetQueuedCompletionStatus. - this->bytes_transferred_ = bytes_transferred; - this->success_ = success; - this->completion_key_ = completion_key; - this->error_ = error; - - // Appropriately move the pointers in the message block. - if (!this->scatter_enabled ()) - this->message_block_.wr_ptr (bytes_transferred); - else - { - static const size_t page_size = ACE_OS::getpagesize(); - - for (ACE_Message_Block* mb = &this->message_block_; - (mb != 0) && (bytes_transferred > 0); - mb = mb->cont ()) - { - // mb->space () is ought to be >= page_size. - // this is verified in the readv method - // ACE_ASSERT (mb->space () >= page_size); - - size_t len_part = page_size ; - - if ( len_part > bytes_transferred) - len_part = bytes_transferred; - - mb->wr_ptr (len_part); - - bytes_transferred -= len_part; - } - } - - // Create the interface result class. - ACE_Asynch_Read_File::Result result (this); - - // Call the application handler. - ACE_Handler *handler = this->handler_proxy_.get ()->handler (); - if (handler != 0) - handler->handle_read_file (result); -} - -ACE_WIN32_Asynch_Read_File_Result::~ACE_WIN32_Asynch_Read_File_Result (void) -{ -} - -// Base class operations. These operations are here to kill dominance -// warnings. These methods call the base class methods. - -size_t -ACE_WIN32_Asynch_Read_File_Result::bytes_transferred (void) const -{ - return ACE_WIN32_Asynch_Result::bytes_transferred (); -} - -const void * -ACE_WIN32_Asynch_Read_File_Result::act (void) const -{ - return ACE_WIN32_Asynch_Result::act (); -} - -int -ACE_WIN32_Asynch_Read_File_Result::success (void) const -{ - return ACE_WIN32_Asynch_Result::success (); -} - -const void * -ACE_WIN32_Asynch_Read_File_Result::completion_key (void) const -{ - return ACE_WIN32_Asynch_Result::completion_key (); -} - -u_long -ACE_WIN32_Asynch_Read_File_Result::error (void) const -{ - return ACE_WIN32_Asynch_Result::error (); -} - -ACE_HANDLE -ACE_WIN32_Asynch_Read_File_Result::event (void) const -{ - return ACE_WIN32_Asynch_Result::event (); -} - -u_long -ACE_WIN32_Asynch_Read_File_Result::offset (void) const -{ - return ACE_WIN32_Asynch_Result::offset (); -} - -u_long -ACE_WIN32_Asynch_Read_File_Result::offset_high (void) const -{ - return ACE_WIN32_Asynch_Result::offset_high (); -} - -int -ACE_WIN32_Asynch_Read_File_Result::priority (void) const -{ - return ACE_WIN32_Asynch_Result::priority (); -} - -int -ACE_WIN32_Asynch_Read_File_Result::signal_number (void) const -{ - return ACE_WIN32_Asynch_Result::signal_number (); -} - -// The following methods belong to -// ACE_WIN32_Asynch_Read_Stream_Result. They are here to avoid VC++ -// warnings. These methods route their call to the -// ACE_WIN32_Asynch_Read_Stream_Result base class. - -size_t -ACE_WIN32_Asynch_Read_File_Result::bytes_to_read (void) const -{ - return ACE_WIN32_Asynch_Read_Stream_Result::bytes_to_read (); -} - -ACE_Message_Block & -ACE_WIN32_Asynch_Read_File_Result::message_block (void) const -{ - return ACE_WIN32_Asynch_Read_Stream_Result::message_block (); -} - -ACE_HANDLE -ACE_WIN32_Asynch_Read_File_Result::handle (void) const -{ - return ACE_WIN32_Asynch_Read_Stream_Result::handle (); -} - -int -ACE_WIN32_Asynch_Read_File_Result::post_completion (ACE_Proactor_Impl *proactor) -{ - return ACE_WIN32_Asynch_Result::post_completion (proactor); -} - -// ************************************************************ - -ACE_WIN32_Asynch_Read_File::ACE_WIN32_Asynch_Read_File (ACE_WIN32_Proactor *win32_proactor) - : ACE_Asynch_Operation_Impl (), - ACE_Asynch_Read_Stream_Impl (), - ACE_Asynch_Read_File_Impl (), - ACE_WIN32_Asynch_Read_Stream (win32_proactor) -{ -} - -int -ACE_WIN32_Asynch_Read_File::read (ACE_Message_Block &message_block, - size_t bytes_to_read, - u_long offset, - u_long offset_high, - const void *act, - int priority, - int signal_number) -{ - size_t space = message_block.space (); - if ( bytes_to_read > space ) - bytes_to_read = space; - - if ( bytes_to_read == 0 ) - ACE_ERROR_RETURN - ((LM_ERROR, - ACE_TEXT ("ACE_WIN32_Asynch_Read_File::read:") - ACE_TEXT ("Attempt to read 0 bytes or no space in the message block\n")), - -1); - - - ACE_WIN32_Asynch_Read_File_Result *result = 0; - ACE_NEW_RETURN (result, - ACE_WIN32_Asynch_Read_File_Result (this->handler_proxy_, - this->handle_, - message_block, - bytes_to_read, - act, - offset, - offset_high, - this->win32_proactor_->get_handle (), - priority, - signal_number), - -1); - - // Shared read - int return_val = this->shared_read (result); - - // Upon errors - if (return_val == -1) - delete result; - - return return_val; -} - -int -ACE_WIN32_Asynch_Read_File::readv (ACE_Message_Block &message_block, - size_t bytes_to_read, - u_long offset, - u_long offset_high, - const void *act, - int priority, - int signal_number) -{ -#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) - static const size_t page_size = ACE_OS::getpagesize(); - - FILE_SEGMENT_ELEMENT buffer_pointers[ACE_IOV_MAX + 1]; - int buffer_pointers_count = 0; - - // Each buffer must be at least the size of a system memory page - // and must be aligned on a system memory page size boundary - - // We should not read more than user requested, - // but it is allowed to read less - - size_t total_space = 0; - - for (const ACE_Message_Block* msg = &message_block; - msg != 0 && buffer_pointers_count < ACE_IOV_MAX && total_space < bytes_to_read; - msg = msg->cont(), ++buffer_pointers_count ) - { - size_t msg_space = msg->space (); - - if (msg_space < page_size) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("ACE_WIN32_Asynch_Read_File::readv:") - ACE_TEXT ("Invalid message block size\n")), - -1); - - buffer_pointers[buffer_pointers_count].Buffer = msg->wr_ptr (); - total_space += page_size; - } - - // not read more than buffers space - if (bytes_to_read > total_space) - bytes_to_read = total_space; - - // ReadFileScatter API limits us to DWORD range. - if (bytes_to_read > MAXDWORD) - { - errno = ERANGE; - return -1; - } - DWORD dword_bytes_to_read = static_cast (bytes_to_read); - - // last one should be completely 0 - buffer_pointers[buffer_pointers_count].Buffer = 0; - - ACE_WIN32_Asynch_Read_File_Result *result = 0; - ACE_NEW_RETURN (result, - ACE_WIN32_Asynch_Read_File_Result (this->handler_proxy_, - this->handle_, - message_block, - bytes_to_read, - act, - offset, - offset_high, - this->win32_proactor_->get_handle (), - priority, - signal_number, - 1), // scatter read enabled - -1); - - // do the scatter read - result->set_error (0); // Clear error before starting IO. - - int initiate_result = ::ReadFileScatter (result->handle (), - buffer_pointers, - dword_bytes_to_read, - 0, // reserved, must be NULL - result); - - if (0 != initiate_result) - // Immediate success: the OVERLAPPED will still get queued. - return 1; - - // If initiate failed, check for a bad error. - ACE_OS::set_errno_to_last_error (); - switch (errno) - { - case ERROR_IO_PENDING: - // The IO will complete proactively: the OVERLAPPED will still - // get queued. - initiate_result = 0; - break; - - default: - // Something else went wrong: the OVERLAPPED will not get - // queued. - - if (ACE::debug ()) - { - ACE_DEBUG ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ReadFileScatter"))); - } - - delete result; - initiate_result = -1; - break; - } - - return initiate_result; -#else - ACE_NOTSUP_RETURN (-1); -#endif /* ACE_WIN32_OVERLAPPED_IO */ -} - - -ACE_WIN32_Asynch_Read_File::~ACE_WIN32_Asynch_Read_File (void) -{ -} - -int -ACE_WIN32_Asynch_Read_File::read (ACE_Message_Block &message_block, - size_t bytes_to_read, - const void *act, - int priority, - int signal_number) -{ - return ACE_WIN32_Asynch_Read_Stream::read (message_block, - bytes_to_read, - act, - priority, - signal_number); -} - -int -ACE_WIN32_Asynch_Read_File::readv (ACE_Message_Block &message_block, - size_t bytes_to_read, - const void *act, - int priority, - int signal_number) -{ - return ACE_WIN32_Asynch_Read_Stream::readv (message_block, - bytes_to_read, - act, - priority, - signal_number); -} - -// Methods belong to ACE_WIN32_Asynch_Operation base class. These -// methods are defined here to avoid VC++ warnings. They route the -// call to the ACE_WIN32_Asynch_Operation base class. - -int -ACE_WIN32_Asynch_Read_File::open (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor) -{ - return ACE_WIN32_Asynch_Operation::open (handler_proxy, - handle, - completion_key, - proactor); -} - -int -ACE_WIN32_Asynch_Read_File::cancel (void) -{ - return ACE_WIN32_Asynch_Operation::cancel (); -} - -ACE_Proactor * -ACE_WIN32_Asynch_Read_File::proactor (void) const -{ - return ACE_WIN32_Asynch_Operation::proactor (); -} - -ACE_WIN32_Asynch_Write_File_Result::ACE_WIN32_Asynch_Write_File_Result ( - const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - ACE_Message_Block &message_block, - size_t bytes_to_write, - const void* act, - u_long offset, - u_long offset_high, - ACE_HANDLE event, - int priority, - int signal_number, - int gather_enabled) - : ACE_Asynch_Result_Impl (), - ACE_Asynch_Write_Stream_Result_Impl (), - ACE_Asynch_Write_File_Result_Impl (), - ACE_WIN32_Asynch_Write_Stream_Result (handler_proxy, - handle, - message_block, - bytes_to_write, - act, - event, - priority, - signal_number, - gather_enabled) -{ - this->Offset = offset; - this->OffsetHigh = offset_high; -} - -void -ACE_WIN32_Asynch_Write_File_Result::complete (size_t bytes_transferred, - int success, - const void *completion_key, - u_long error) -{ - // Copy the data which was returned by GetQueuedCompletionStatus - this->bytes_transferred_ = bytes_transferred; - this->success_ = success; - this->completion_key_ = completion_key; - this->error_ = error; - - // Appropriately move the pointers in the message block. - if (!this->gather_enabled ()) - this->message_block_.rd_ptr (bytes_transferred); - else - { - static const size_t page_size = ACE_OS::getpagesize(); - - for (ACE_Message_Block* mb = &this->message_block_; - (mb != 0) && (bytes_transferred > 0); - mb = mb->cont ()) - { - // mb->length () is ought to be >= page_size. - // this is verified in the writev method - // ACE_ASSERT (mb->length () >= page_size); - - size_t len_part = page_size; - - if ( len_part > bytes_transferred) - len_part = bytes_transferred; - - mb->rd_ptr (len_part); - - bytes_transferred -= len_part; - } - - } - - // Create the interface result class. - ACE_Asynch_Write_File::Result result (this); - - // Call the application handler. - ACE_Handler *handler = this->handler_proxy_.get ()->handler (); - if (handler != 0) - handler->handle_write_file (result); -} - -ACE_WIN32_Asynch_Write_File_Result::~ACE_WIN32_Asynch_Write_File_Result (void) -{ -} - -// Base class operations. These operations are here to kill dominance -// warnings. These methods call the base class methods. - -size_t -ACE_WIN32_Asynch_Write_File_Result::bytes_transferred (void) const -{ - return ACE_WIN32_Asynch_Result::bytes_transferred (); -} - -const void * -ACE_WIN32_Asynch_Write_File_Result::act (void) const -{ - return ACE_WIN32_Asynch_Result::act (); -} - -int -ACE_WIN32_Asynch_Write_File_Result::success (void) const -{ - return ACE_WIN32_Asynch_Result::success (); -} - -const void * -ACE_WIN32_Asynch_Write_File_Result::completion_key (void) const -{ - return ACE_WIN32_Asynch_Result::completion_key (); -} - -u_long -ACE_WIN32_Asynch_Write_File_Result::error (void) const -{ - return ACE_WIN32_Asynch_Result::error (); -} - -ACE_HANDLE -ACE_WIN32_Asynch_Write_File_Result::event (void) const -{ - return ACE_WIN32_Asynch_Result::event (); -} - -u_long -ACE_WIN32_Asynch_Write_File_Result::offset (void) const -{ - return ACE_WIN32_Asynch_Result::offset (); -} - -u_long -ACE_WIN32_Asynch_Write_File_Result::offset_high (void) const -{ - return ACE_WIN32_Asynch_Result::offset_high (); -} - -int -ACE_WIN32_Asynch_Write_File_Result::priority (void) const -{ - return ACE_WIN32_Asynch_Result::priority (); -} - -int -ACE_WIN32_Asynch_Write_File_Result::signal_number (void) const -{ - return ACE_WIN32_Asynch_Result::signal_number (); -} - -// The following methods belong to -// ACE_WIN32_Asynch_Write_Stream_Result. They are here to avoid VC++ -// warnings. These methods route their call to the -// ACE_WIN32_Asynch_Write_Stream_Result base class. - -size_t -ACE_WIN32_Asynch_Write_File_Result::bytes_to_write (void) const -{ - return ACE_WIN32_Asynch_Write_Stream_Result::bytes_to_write (); -} - -ACE_Message_Block & -ACE_WIN32_Asynch_Write_File_Result::message_block (void) const -{ - return ACE_WIN32_Asynch_Write_Stream_Result::message_block (); -} - -ACE_HANDLE -ACE_WIN32_Asynch_Write_File_Result::handle (void) const -{ - return ACE_WIN32_Asynch_Write_Stream_Result::handle (); -} - -int -ACE_WIN32_Asynch_Write_File_Result::post_completion (ACE_Proactor_Impl *proactor) -{ - return ACE_WIN32_Asynch_Result::post_completion (proactor); -} - -ACE_WIN32_Asynch_Write_File::ACE_WIN32_Asynch_Write_File (ACE_WIN32_Proactor *win32_proactor) - : ACE_Asynch_Operation_Impl (), - ACE_Asynch_Write_Stream_Impl (), - ACE_Asynch_Write_File_Impl (), - ACE_WIN32_Asynch_Write_Stream (win32_proactor) -{ -} - -int -ACE_WIN32_Asynch_Write_File::write (ACE_Message_Block &message_block, - size_t bytes_to_write, - u_long offset, - u_long offset_high, - const void *act, - int priority, - int signal_number) -{ - size_t len = message_block.length (); - if ( bytes_to_write > len ) - bytes_to_write = len; - - if ( bytes_to_write == 0 ) - ACE_ERROR_RETURN - ((LM_ERROR, - ACE_TEXT ("ACE_WIN32_Asynch_Write_File::write:") - ACE_TEXT ("Attempt to read 0 bytes\n")), - -1); - - ACE_WIN32_Asynch_Write_File_Result *result = 0; - ACE_NEW_RETURN (result, - ACE_WIN32_Asynch_Write_File_Result (this->handler_proxy_, - this->handle_, - message_block, - bytes_to_write, - act, - offset, - offset_high, - this->win32_proactor_->get_handle (), - priority, - signal_number), - -1); - - // Shared write - int return_val = this->shared_write (result); - - // Upon errors - if (return_val == -1) - delete result; - - return return_val; -} - -int -ACE_WIN32_Asynch_Write_File::writev (ACE_Message_Block &message_block, - size_t bytes_to_write, - u_long offset, - u_long offset_high, - const void *act, - int priority, - int signal_number) -{ -#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) - static const size_t page_size = ACE_OS::getpagesize(); - - FILE_SEGMENT_ELEMENT buffer_pointers[ACE_IOV_MAX + 1]; - int buffer_pointers_count = 0; - - // Each buffer must be at least the size of a system memory page - // and must be aligned on a system memory page size boundary - - // We should not read more than user requested, - // but it is allowed to read less - - size_t total_len = 0; - - for (const ACE_Message_Block* msg = &message_block; - msg != 0 && buffer_pointers_count < ACE_IOV_MAX && total_len < bytes_to_write; - msg = msg->cont (), ++buffer_pointers_count ) - { - size_t msg_len = msg->length (); - - // Don't allow writing less than page_size, unless - // the size of the message block is big enough (so we don't write from - // memory which does not belong to the message block), and the message - // block is the last in the chain. - if (msg_len < page_size && - (msg->size () - (msg->rd_ptr () - msg->base ()) < page_size || // message block too small - bytes_to_write - total_len > page_size ))// NOT last chunk - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("ACE_WIN32_Asynch_Write_File::writev:") - ACE_TEXT ("Invalid message block length\n")), - -1); - - buffer_pointers[buffer_pointers_count].Buffer = msg->rd_ptr (); - total_len += page_size; - } - - // not write more than we have in buffers - if (bytes_to_write > total_len) - bytes_to_write = total_len; - // WriteFileGather API limits us to DWORD range. - if (bytes_to_write > MAXDWORD) - { - errno = ERANGE; - return -1; - } - DWORD dword_bytes_to_write = static_cast (bytes_to_write); - - // last one should be completely 0 - buffer_pointers[buffer_pointers_count].Buffer = 0; - - ACE_WIN32_Asynch_Write_File_Result *result = 0; - ACE_NEW_RETURN (result, - ACE_WIN32_Asynch_Write_File_Result (this->handler_proxy_, - this->handle_, - message_block, - bytes_to_write, - act, - offset, - offset_high, - this->win32_proactor_->get_handle (), - priority, - signal_number, - 1), // gather write enabled - -1); - - result->set_error(0); - - // do the gather write - int initiate_result = ::WriteFileGather (result->handle (), - buffer_pointers, - dword_bytes_to_write, - 0, // reserved, must be NULL - result); - - if (0 != initiate_result) - // Immediate success: the OVERLAPPED will still get queued. - return 1; - - // If initiate failed, check for a bad error. - ACE_OS::set_errno_to_last_error (); - switch (errno) - { - case ERROR_IO_PENDING: - // The IO will complete proactively: the OVERLAPPED will still - // get queued. - initiate_result = 0; - break; - - default: - // Something else went wrong: the OVERLAPPED will not get - // queued. - - if (ACE::debug ()) - { - ACE_DEBUG ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("WriteFileGather"))); - } - - delete result; - initiate_result = -1; - break; - } - - return initiate_result; -#else - - ACE_NOTSUP_RETURN (-1); - -#endif /* ACE_HAS_WIN32_OVERLAPPED_IO */ -} - - -ACE_WIN32_Asynch_Write_File::~ACE_WIN32_Asynch_Write_File (void) -{ -} - -int -ACE_WIN32_Asynch_Write_File::write (ACE_Message_Block &message_block, - size_t bytes_to_write, - const void *act, - int priority, - int signal_number) -{ - return ACE_WIN32_Asynch_Write_Stream::write (message_block, - bytes_to_write, - act, - priority, - signal_number); -} - -int -ACE_WIN32_Asynch_Write_File::writev (ACE_Message_Block &message_block, - size_t bytes_to_write, - const void *act, - int priority, - int signal_number) -{ - return ACE_WIN32_Asynch_Write_Stream::writev (message_block, - bytes_to_write, - act, - priority, - signal_number); -} - -// Methods belong to ACE_WIN32_Asynch_Operation base class. These -// methods are defined here to avoid VC++ warnings. They route the -// call to the ACE_WIN32_Asynch_Operation base class. - -int -ACE_WIN32_Asynch_Write_File::open (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor) -{ - return ACE_WIN32_Asynch_Operation::open (handler_proxy, - handle, - completion_key, - proactor); -} - -int -ACE_WIN32_Asynch_Write_File::cancel (void) -{ - return ACE_WIN32_Asynch_Operation::cancel (); -} - -ACE_Proactor * -ACE_WIN32_Asynch_Write_File::proactor (void) const -{ - return ACE_WIN32_Asynch_Operation::proactor (); -} - -size_t -ACE_WIN32_Asynch_Accept_Result::bytes_to_read (void) const -{ - return this->bytes_to_read_; -} - -ACE_Message_Block & -ACE_WIN32_Asynch_Accept_Result::message_block (void) const -{ - return this->message_block_; -} - -ACE_HANDLE -ACE_WIN32_Asynch_Accept_Result::listen_handle (void) const -{ - return this->listen_handle_; -} - -ACE_HANDLE -ACE_WIN32_Asynch_Accept_Result::accept_handle (void) const -{ - return this->accept_handle_; -} - -ACE_WIN32_Asynch_Accept_Result::ACE_WIN32_Asynch_Accept_Result ( - const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE listen_handle, - ACE_HANDLE accept_handle, - ACE_Message_Block &message_block, - size_t bytes_to_read, - const void* act, - ACE_HANDLE event, - int priority, - int signal_number) - : ACE_Asynch_Result_Impl (), - ACE_Asynch_Accept_Result_Impl (), - ACE_WIN32_Asynch_Result (handler_proxy, - act, - event, - 0, - 0, - priority, - signal_number), - bytes_to_read_ (bytes_to_read), - message_block_ (message_block), - listen_handle_ (listen_handle), - accept_handle_ (accept_handle) -{ -} - -void -ACE_WIN32_Asynch_Accept_Result::complete (size_t bytes_transferred, - int success, - const void *completion_key, - u_long error) -{ - // Copy the data which was returned by GetQueuedCompletionStatus - this->bytes_transferred_ = bytes_transferred; - this->success_ = success; - this->completion_key_ = completion_key; - this->error_ = error; - - // Appropriately move the pointers in the message block. - this->message_block_.wr_ptr (bytes_transferred); - - if (!success && this->accept_handle_ != ACE_INVALID_HANDLE) - { - ACE_OS::closesocket (this->accept_handle_); - this->accept_handle_ = ACE_INVALID_HANDLE; - } - - // Create the interface result class. - ACE_Asynch_Accept::Result result (this); - - // Call the application handler. - ACE_Handler *handler = this->handler_proxy_.get ()->handler (); - if (handler != 0) - handler->handle_accept (result); -} - -ACE_WIN32_Asynch_Accept_Result::~ACE_WIN32_Asynch_Accept_Result (void) -{ -} - -// Base class operations. These operations are here to kill dominance -// warnings. These methods call the base class methods. - -size_t -ACE_WIN32_Asynch_Accept_Result::bytes_transferred (void) const -{ - return ACE_WIN32_Asynch_Result::bytes_transferred (); -} - -const void * -ACE_WIN32_Asynch_Accept_Result::act (void) const -{ - return ACE_WIN32_Asynch_Result::act (); -} - -int -ACE_WIN32_Asynch_Accept_Result::success (void) const -{ - return ACE_WIN32_Asynch_Result::success (); -} - -const void * -ACE_WIN32_Asynch_Accept_Result::completion_key (void) const -{ - return ACE_WIN32_Asynch_Result::completion_key (); -} - -u_long -ACE_WIN32_Asynch_Accept_Result::error (void) const -{ - return ACE_WIN32_Asynch_Result::error (); -} - -ACE_HANDLE -ACE_WIN32_Asynch_Accept_Result::event (void) const -{ - return ACE_WIN32_Asynch_Result::event (); -} - -u_long -ACE_WIN32_Asynch_Accept_Result::offset (void) const -{ - return ACE_WIN32_Asynch_Result::offset (); -} - -u_long -ACE_WIN32_Asynch_Accept_Result::offset_high (void) const -{ - return ACE_WIN32_Asynch_Result::offset_high (); -} - -int -ACE_WIN32_Asynch_Accept_Result::priority (void) const -{ - return ACE_WIN32_Asynch_Result::priority (); -} - -int -ACE_WIN32_Asynch_Accept_Result::signal_number (void) const -{ - return ACE_WIN32_Asynch_Result::signal_number (); -} - -int -ACE_WIN32_Asynch_Accept_Result::post_completion (ACE_Proactor_Impl *proactor) -{ - return ACE_WIN32_Asynch_Result::post_completion (proactor); -} - -ACE_WIN32_Asynch_Accept::ACE_WIN32_Asynch_Accept (ACE_WIN32_Proactor *win32_proactor) - : ACE_Asynch_Operation_Impl (), - ACE_Asynch_Accept_Impl (), - ACE_WIN32_Asynch_Operation (win32_proactor) -{ -} - -int -ACE_WIN32_Asynch_Accept::accept (ACE_Message_Block &message_block, - size_t bytes_to_read, - ACE_HANDLE accept_handle, - const void *act, - int priority, - int signal_number, - int addr_family) -{ -#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) || (defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0)) - // Sanity check: make sure that enough space has been allocated by - // the caller. - size_t address_size = -#if defined (ACE_HAS_IPV6) - addr_family == AF_INET ? sizeof (sockaddr_in) : sizeof (sockaddr_in6); -#else - sizeof (sockaddr_in); -#endif /* ACE_HAS_IPV6 */ - address_size += 16; // AcceptEx requires address size + 16 (minimum) - size_t available_space = message_block.space (); - size_t space_needed = bytes_to_read + 2 * address_size; - if (available_space < space_needed) - ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("Buffer too small\n")), -1); - - // WIN Specific. - - // AcceptEx API limits us to DWORD range. - if (bytes_to_read > MAXDWORD) - { - errno = ERANGE; - return -1; - } - DWORD dword_bytes_to_read = static_cast (bytes_to_read); - - int close_accept_handle = 0; - // If the is invalid, we will create a new socket. - if (accept_handle == ACE_INVALID_HANDLE) - { - accept_handle = ACE_OS::socket (addr_family, - SOCK_STREAM, - 0); - if (accept_handle == ACE_INVALID_HANDLE) - { - if (ACE::debug ()) - { - ACE_DEBUG ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("ACE_OS::socket"))); - } - return -1; - } - else - // Remember to close the socket down if failures occur. - close_accept_handle = 1; - } - - // Common code for both WIN and POSIX. - ACE_WIN32_Asynch_Accept_Result *result = 0; - ACE_NEW_RETURN (result, - ACE_WIN32_Asynch_Accept_Result (this->handler_proxy_, - this->handle_, - accept_handle, - message_block, - bytes_to_read, - act, - this->win32_proactor_->get_handle (), - priority, - signal_number), - -1); - - u_long bytes_read; - - // Initiate the accept. - int initiate_result = ::AcceptEx ((SOCKET) result->listen_handle (), - (SOCKET) result->accept_handle (), - result->message_block ().wr_ptr (), - dword_bytes_to_read, - static_cast (address_size), - static_cast (address_size), - &bytes_read, - result); - if (initiate_result == 1) - // Immediate success: the OVERLAPPED will still get queued. - return 1; - - // If initiate failed, check for a bad error. - ACE_OS::set_errno_to_last_error (); - switch (errno) - { - case ERROR_IO_PENDING: - // The IO will complete proactively: the OVERLAPPED will still - // get queued. - return 0; - - default: - // Something else went wrong: the OVERLAPPED will not get - // queued. - - if (close_accept_handle == 1) - // Close the newly created socket - ACE_OS::closesocket (accept_handle); - - // Cleanup dynamically allocated Asynch_Result. - delete result; - - if (ACE::debug ()) - { - ACE_DEBUG ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("AcceptEx"))); - } - return -1; - } -#else - ACE_UNUSED_ARG (message_block); - ACE_UNUSED_ARG (bytes_to_read); - ACE_UNUSED_ARG (accept_handle); - ACE_UNUSED_ARG (act); - ACE_UNUSED_ARG (priority); - ACE_UNUSED_ARG (signal_number); - ACE_UNUSED_ARG (addr_family); - ACE_NOTSUP_RETURN (-1); -#endif /* defined (ACE_HAS_WIN32_OVERLAPPED_IO) || (defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0)) */ -} - -ACE_WIN32_Asynch_Accept::~ACE_WIN32_Asynch_Accept (void) -{ -} - -// Methods belong to ACE_WIN32_Asynch_Operation base class. These -// methods are defined here to avoid VC++ warnings. They route the -// call to the ACE_WIN32_Asynch_Operation base class. - -int -ACE_WIN32_Asynch_Accept::open (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor) -{ - return ACE_WIN32_Asynch_Operation::open (handler_proxy, - handle, - completion_key, - proactor); -} - -int -ACE_WIN32_Asynch_Accept::cancel (void) -{ - return ACE_WIN32_Asynch_Operation::cancel (); -} - -ACE_Proactor * -ACE_WIN32_Asynch_Accept::proactor (void) const -{ - return ACE_WIN32_Asynch_Operation::proactor (); -} - -// ********************************************************************* - -ACE_HANDLE -ACE_WIN32_Asynch_Connect_Result::connect_handle (void) const -{ - return this->connect_handle_; -} - -void ACE_WIN32_Asynch_Connect_Result::connect_handle ( ACE_HANDLE handle ) -{ - this->connect_handle_ = handle; -} - - -ACE_WIN32_Asynch_Connect_Result::ACE_WIN32_Asynch_Connect_Result - (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE connect_handle, - const void* act, - ACE_HANDLE event, - int priority, - int signal_number) - : ACE_Asynch_Result_Impl (), - ACE_Asynch_Connect_Result_Impl (), - ACE_WIN32_Asynch_Result - (handler_proxy, act, event, 0, 0, priority, signal_number), - connect_handle_ (connect_handle) -{ - ; -} - -void -ACE_WIN32_Asynch_Connect_Result::complete (size_t bytes_transferred, - int success, - const void *completion_key, - u_long error) -{ - // Copy the data. - this->bytes_transferred_ = bytes_transferred; - this->success_ = success; - this->completion_key_ = completion_key; - this->error_ = error; - - // Create the interface result class. - ACE_Asynch_Connect::Result result (this); - - // Call the application handler. - ACE_Handler *handler = this->handler_proxy_.get ()->handler (); - if (handler != 0) - handler->handle_connect (result); -} - -ACE_WIN32_Asynch_Connect_Result::~ACE_WIN32_Asynch_Connect_Result (void) -{ -} - -// Base class operations. These operations are here to kill dominance -// warnings. These methods call the base class methods. - -size_t -ACE_WIN32_Asynch_Connect_Result::bytes_transferred (void) const -{ - return ACE_WIN32_Asynch_Result::bytes_transferred (); -} - -const void * -ACE_WIN32_Asynch_Connect_Result::act (void) const -{ - return ACE_WIN32_Asynch_Result::act (); -} - -int -ACE_WIN32_Asynch_Connect_Result::success (void) const -{ - return ACE_WIN32_Asynch_Result::success (); -} - -const void * -ACE_WIN32_Asynch_Connect_Result::completion_key (void) const -{ - return ACE_WIN32_Asynch_Result::completion_key (); -} - -u_long -ACE_WIN32_Asynch_Connect_Result::error (void) const -{ - return ACE_WIN32_Asynch_Result::error (); -} - -ACE_HANDLE -ACE_WIN32_Asynch_Connect_Result::event (void) const -{ - return ACE_WIN32_Asynch_Result::event (); -} - -u_long -ACE_WIN32_Asynch_Connect_Result::offset (void) const -{ - return ACE_WIN32_Asynch_Result::offset (); -} - -u_long -ACE_WIN32_Asynch_Connect_Result::offset_high (void) const -{ - return ACE_WIN32_Asynch_Result::offset_high (); -} - -int -ACE_WIN32_Asynch_Connect_Result::priority (void) const -{ - return ACE_WIN32_Asynch_Result::priority (); -} - -int -ACE_WIN32_Asynch_Connect_Result::signal_number (void) const -{ - return ACE_WIN32_Asynch_Result::signal_number (); -} - -int -ACE_WIN32_Asynch_Connect_Result::post_completion (ACE_Proactor_Impl *proactor) -{ - return ACE_WIN32_Asynch_Result::post_completion (proactor); -} - -// ********************************************************************* - -ACE_WIN32_Asynch_Connect::ACE_WIN32_Asynch_Connect (ACE_WIN32_Proactor * win32_proactor) - : ACE_Asynch_Operation_Impl (), - ACE_Asynch_Connect_Impl (), - ACE_WIN32_Asynch_Operation (win32_proactor), - flg_open_ (false) -{ -} - -ACE_WIN32_Asynch_Connect::~ACE_WIN32_Asynch_Connect (void) -{ - this->close (); - this->reactor (0); // to avoid purge_pending_notifications -} - -ACE_Proactor * -ACE_WIN32_Asynch_Connect::proactor (void) const -{ - return ACE_WIN32_Asynch_Operation::proactor (); -} - -ACE_HANDLE -ACE_WIN32_Asynch_Connect::get_handle (void) const -{ - - ACE_ASSERT (0); - return ACE_INVALID_HANDLE; -} - -void -ACE_WIN32_Asynch_Connect::set_handle (ACE_HANDLE) -{ - ACE_ASSERT (0) ; -} - -int -ACE_WIN32_Asynch_Connect::open (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE, - const void *completion_key, - ACE_Proactor *proactor) -{ - ACE_TRACE ("ACE_WIN32_Asynch_Connect::open"); - - // if we are already opened, - // we could not create a new handler without closing the previous - if (this->flg_open_) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("%N:%l:ACE_WIN32_Asynch_Connect::open:") - ACE_TEXT ("connector already open\n")), - -1); - - //int result = - ACE_WIN32_Asynch_Operation::open (handler_proxy, - ACE_INVALID_HANDLE, - completion_key, - proactor); - - // Ignore result as we pass ACE_INVALID_HANDLE - //if (result == -1) - // return result; - - this->flg_open_ = true; - - return 0; -} - -int -ACE_WIN32_Asynch_Connect::connect (ACE_HANDLE connect_handle, - const ACE_Addr & remote_sap, - const ACE_Addr & local_sap, - int reuse_addr, - const void *act, - int priority, - int signal_number) -{ - ACE_TRACE ("ACE_WIN32_Asynch_Connect::connect"); - - if (!this->flg_open_) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("%N:%l:ACE_WIN32_Asynch_Connect::connect") - ACE_TEXT ("connector was not opened before\n")), - -1); - - // Common code for both WIN and WIN32. - // Create future Asynch_Connect_Result - ACE_WIN32_Asynch_Connect_Result *result = 0; - ACE_NEW_RETURN (result, - ACE_WIN32_Asynch_Connect_Result (this->handler_proxy_, - connect_handle, - act, - this->win32_proactor_->get_handle (), - priority, - signal_number), - -1); - - int rc = connect_i (result, - remote_sap, - local_sap, - reuse_addr); - - // update handle - connect_handle = result->connect_handle (); - - if (rc != 0) - return post_result (result, true); - - // Enqueue result we will wait for completion - { - ACE_MT (ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, ace_mon, this->lock_, -1)); - - if (this->result_map_.bind (connect_handle, result) == -1) - { - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("ACE_WIN32_Asynch_Connect::connect: %p\n"), - ACE_TEXT ("bind"))); - result->set_error (EFAULT); - return post_result (result, true); - } - } - - ACE_Asynch_Pseudo_Task & task = - this->win32_proactor_->get_asynch_pseudo_task (); - - if (-1 == task.register_io_handler (connect_handle, - this, - ACE_Event_Handler::CONNECT_MASK, - 0)) // not to suspend after register - { - result = 0; - { - ACE_MT (ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, ace_mon, this->lock_, -1)); - this->result_map_.unbind (connect_handle, result); - } - if (result != 0) - { - result->set_error (EFAULT); - this->post_result (result, true); - } - } - - return 0; -} - -int ACE_WIN32_Asynch_Connect::post_result (ACE_WIN32_Asynch_Connect_Result * result, - bool post_enable) -{ - ACE_HANDLE handle = result->connect_handle (); - if (this->flg_open_ && post_enable) - { - // NOTE: result is invalid after post_completion(). It's either deleted - // or will be shortly via the proactor dispatch, regardless of success - // or fail of the call. - if (this->win32_proactor_ ->post_completion (result) == 0) - return 0; - - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("Error:(%P | %t):%p\n"), - ACE_TEXT ("ACE_WIN32_Asynch_Connect::post_result: ") - ACE_TEXT (" failed"))); - } - else - { - // There was no call to post_completion() so manually delete result. - delete result; - } - - if (handle != ACE_INVALID_HANDLE) - ACE_OS::closesocket (handle); - - return -1; -} - -// connect_i -// return code : -// -1 errors before attempt to connect -// 0 connect started -// 1 connect finished ( may be unsuccessfully) - -int -ACE_WIN32_Asynch_Connect::connect_i (ACE_WIN32_Asynch_Connect_Result *result, - const ACE_Addr & remote_sap, - const ACE_Addr & local_sap, - int reuse_addr) -{ - result->set_bytes_transferred (0); - - ACE_HANDLE handle = result->connect_handle (); - if (handle == ACE_INVALID_HANDLE) - { - int protocol_family = remote_sap.get_type (); - handle = ACE_OS::socket (protocol_family, - SOCK_STREAM, - 0); - - // save it - result->connect_handle (handle); - if (handle == ACE_INVALID_HANDLE) - { - result->set_error (errno); - ACE_ERROR_RETURN - ((LM_ERROR, - ACE_TEXT ("ACE_WIN32_Asynch_Connect::connect_i: %p\n"), - ACE_TEXT ("socket")), - -1); - } - - // Reuse the address - int one = 1; - if (protocol_family != PF_UNIX && - reuse_addr != 0 && - ACE_OS::setsockopt (handle, - SOL_SOCKET, - SO_REUSEADDR, - (const char*) &one, - sizeof one) == -1) - { - result->set_error (errno); - ACE_ERROR_RETURN - ((LM_ERROR, - ACE_TEXT ("ACE_WIN32_Asynch_Connect::connect_i: %p\n"), - ACE_TEXT ("setsockopt")), - -1); - } - } - - if (local_sap != ACE_Addr::sap_any) - { - sockaddr * laddr = reinterpret_cast (local_sap.get_addr ()); - int size = local_sap.get_size (); - if (ACE_OS::bind (handle, laddr, size) == -1) - { - result->set_error (errno); - ACE_ERROR_RETURN - ((LM_ERROR, - ACE_TEXT ("ACE_WIN32_Asynch_Connect::connect_i: %p\n"), - ACE_TEXT ("bind")), - -1); - } - } - - // set non blocking mode - if (ACE::set_flags (handle, ACE_NONBLOCK) != 0) - { - result->set_error (errno); - ACE_ERROR_RETURN - ((LM_ERROR, - ACE_TEXT ("ACE_WIN32_Asynch_Connect::connect_i: %p\n"), - ACE_TEXT ("set_flags")), - -1); - } - - for (;;) - { - int rc = ACE_OS::connect - (handle, - reinterpret_cast (remote_sap.get_addr ()), - remote_sap.get_size ()); - - if (rc < 0) // failure - { - if (errno == EWOULDBLOCK || errno == EINPROGRESS) - return 0; // connect started - - if (errno == EINTR) - continue; - - result->set_error (errno); - } - return 1 ; // connect finished - } -} - - -// cancel_uncompleted -// It performs cancellation of all pending requests -// -// Parameter flg_notify can be -// 0 - don't send notifications about canceled accepts -// !0 - notify user about canceled accepts -// according WIN32 standards we should receive notifications -// on canceled AIO requests -// -// Return value : number of cancelled requests -// - -int -ACE_WIN32_Asynch_Connect::cancel_uncompleted (bool flg_notify, - ACE_Handle_Set &set) -{ - ACE_TRACE ("ACE_WIN32_Asynch_Connect::cancel_uncompleted"); - - int retval = 0; - - MAP_MANAGER::ITERATOR iter (result_map_); - MAP_MANAGER::ENTRY * me = 0; - - set.reset (); - - for (; iter.next (me) != 0; retval++, iter.advance ()) - { - ACE_HANDLE handle = me->ext_id_; - ACE_WIN32_Asynch_Connect_Result* result = me->int_id_ ; - - set.set_bit (handle); - - result->set_bytes_transferred (0); - result->set_error (ERROR_OPERATION_ABORTED); - this->post_result (result, flg_notify); - } - - result_map_.unbind_all (); - - return retval; -} - -int -ACE_WIN32_Asynch_Connect::cancel (void) -{ - ACE_TRACE ("ACE_WIN32_Asynch_Connect::cancel"); - - int rc = -1 ; // ERRORS - - ACE_Handle_Set set; - int num_cancelled = 0; - { - ACE_MT (ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, ace_mon, this->lock_, -1)); - - num_cancelled = cancel_uncompleted (flg_open_, set); - } - if (num_cancelled == 0) - rc = 1; // AIO_ALLDONE - else if (num_cancelled > 0) - rc = 0; // AIO_CANCELED - - if (!this->flg_open_) - return rc; - - ACE_Asynch_Pseudo_Task & task = - this->win32_proactor_->get_asynch_pseudo_task (); - - task.remove_io_handler (set); - return rc; -} - -int -ACE_WIN32_Asynch_Connect::close (void) -{ - ACE_TRACE ("ACE_WIN32_Asynch_Connect::close"); - - ACE_Handle_Set set; - int num_cancelled = 0; - { - ACE_MT (ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, ace_mon, this->lock_, -1)); - - num_cancelled = cancel_uncompleted (flg_open_, set); - } - if (num_cancelled == 0 || this->flg_open_ == 0) - { - this->flg_open_ = false; - return 0; - } - - ACE_Asynch_Pseudo_Task & task = - this->win32_proactor_->get_asynch_pseudo_task (); - - task.remove_io_handler (set); - return 0; -} - -int -ACE_WIN32_Asynch_Connect::handle_exception (ACE_HANDLE fd) -{ - ACE_TRACE ("ACE_WIN32_Asynch_Connect::handle_exception"); - return handle_output (fd); -} - -int -ACE_WIN32_Asynch_Connect::handle_input (ACE_HANDLE fd) -{ - ACE_TRACE ("ACE_WIN32_Asynch_Connect::handle_input"); - return handle_output (fd); -} - -int -ACE_WIN32_Asynch_Connect::handle_output (ACE_HANDLE fd) -{ - ACE_TRACE ("ACE_WIN32_Asynch_Connect::handle_output"); - - ACE_WIN32_Asynch_Connect_Result* result = 0; - - { - ACE_MT (ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, ace_mon, this->lock_, 0)); - if (this->result_map_.unbind (fd, result) != 0) // not found - return -1; - } - - int sockerror = 0 ; - int lsockerror = sizeof sockerror; - - ACE_OS::getsockopt (fd, - SOL_SOCKET, - SO_ERROR, - (char*) & sockerror, - & lsockerror); - - // This previously just did a "return -1" and let handle_close() clean - // things up. However, this entire object may be gone as a result of - // the application's completion handler, so don't count on 'this' being - // legitimate on return from post_result(). - // remove_io_handler() contains flag DONT_CALL - this->win32_proactor_->get_asynch_pseudo_task().remove_io_handler (fd); - - result->set_bytes_transferred (0); - result->set_error (sockerror); - this->post_result (result, this->flg_open_); - return 0; -} - - -int -ACE_WIN32_Asynch_Connect::handle_close (ACE_HANDLE fd, ACE_Reactor_Mask) -{ - ACE_TRACE ("ACE_WIN32_Asynch_Connect::handle_close"); - - ACE_Asynch_Pseudo_Task & task = - this->win32_proactor_->get_asynch_pseudo_task (); - task.remove_io_handler (fd); - - ACE_WIN32_Asynch_Connect_Result* result = 0; - - { - ACE_MT (ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, ace_mon, this->lock_, 0)); - if (this->result_map_.unbind (fd, result) != 0) // not found - return -1; - } - - result->set_bytes_transferred (0); - result->set_error (ERROR_OPERATION_ABORTED); - this->post_result (result, this->flg_open_); - - return 0; -} - -// ********************************************************************* - -ACE_HANDLE -ACE_WIN32_Asynch_Transmit_File_Result::socket (void) const -{ - return this->socket_; -} - -ACE_HANDLE -ACE_WIN32_Asynch_Transmit_File_Result::file (void) const -{ - return this->file_; -} - -ACE_Asynch_Transmit_File::Header_And_Trailer * -ACE_WIN32_Asynch_Transmit_File_Result::header_and_trailer (void) const -{ - return this->header_and_trailer_; -} - -size_t -ACE_WIN32_Asynch_Transmit_File_Result::bytes_to_write (void) const -{ - return this->bytes_to_write_; -} - -size_t -ACE_WIN32_Asynch_Transmit_File_Result::bytes_per_send (void) const -{ - return this->bytes_per_send_; -} - -u_long -ACE_WIN32_Asynch_Transmit_File_Result::flags (void) const -{ - return this->flags_; -} - -ACE_WIN32_Asynch_Transmit_File_Result::ACE_WIN32_Asynch_Transmit_File_Result ( - const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE socket, - ACE_HANDLE file, - ACE_Asynch_Transmit_File::Header_And_Trailer *header_and_trailer, - size_t bytes_to_write, - u_long offset, - u_long offset_high, - size_t bytes_per_send, - u_long flags, - const void *act, - ACE_HANDLE event, - int priority, - int signal_number) - : ACE_Asynch_Result_Impl (), - ACE_Asynch_Transmit_File_Result_Impl (), - ACE_WIN32_Asynch_Result (handler_proxy, - act, - event, - offset, - offset_high, - priority, - signal_number), - socket_ (socket), - file_ (file), - header_and_trailer_ (header_and_trailer), - bytes_to_write_ (bytes_to_write), - bytes_per_send_ (bytes_per_send), - flags_ (flags) -{ -} - -void -ACE_WIN32_Asynch_Transmit_File_Result::complete (size_t bytes_transferred, - int success, - const void *completion_key, - u_long error) -{ - // Copy the data which was returned by GetQueuedCompletionStatus - this->bytes_transferred_ = bytes_transferred; - this->success_ = success; - this->completion_key_ = completion_key; - this->error_ = error; - - // We will not do this because (a) the header and trailer blocks may - // be the same message_blocks and (b) in cases of failures we have - // no idea how much of what (header, data, trailer) was sent. - /* - if (this->success_ && this->header_and_trailer_ != 0) - { - ACE_Message_Block *header = this->header_and_trailer_->header (); - if (header != 0) - header->rd_ptr (this->header_and_trailer_->header_bytes ()); - - ACE_Message_Block *trailer = this->header_and_trailer_->trailer (); - if (trailer != 0) - trailer->rd_ptr (this->header_and_trailer_->trailer_bytes ()); - } - */ - - // Create the interface result class. - ACE_Asynch_Transmit_File::Result result (this); - - // Call the application handler. - ACE_Handler *handler = this->handler_proxy_.get ()->handler (); - if (handler != 0) - handler->handle_transmit_file (result); -} - -ACE_WIN32_Asynch_Transmit_File_Result::~ACE_WIN32_Asynch_Transmit_File_Result (void) -{ -} - -// Base class operations. These operations are here to kill dominance -// warnings. These methods call the base class methods. - -size_t -ACE_WIN32_Asynch_Transmit_File_Result::bytes_transferred (void) const -{ - return ACE_WIN32_Asynch_Result::bytes_transferred (); -} - -const void * -ACE_WIN32_Asynch_Transmit_File_Result::act (void) const -{ - return ACE_WIN32_Asynch_Result::act (); -} - -int -ACE_WIN32_Asynch_Transmit_File_Result::success (void) const -{ - return ACE_WIN32_Asynch_Result::success (); -} - -const void * -ACE_WIN32_Asynch_Transmit_File_Result::completion_key (void) const -{ - return ACE_WIN32_Asynch_Result::completion_key (); -} - -u_long -ACE_WIN32_Asynch_Transmit_File_Result::error (void) const -{ - return ACE_WIN32_Asynch_Result::error (); -} - -ACE_HANDLE -ACE_WIN32_Asynch_Transmit_File_Result::event (void) const -{ - return ACE_WIN32_Asynch_Result::event (); -} - -u_long -ACE_WIN32_Asynch_Transmit_File_Result::offset (void) const -{ - return ACE_WIN32_Asynch_Result::offset (); -} - -u_long -ACE_WIN32_Asynch_Transmit_File_Result::offset_high (void) const -{ - return ACE_WIN32_Asynch_Result::offset_high (); -} - -int -ACE_WIN32_Asynch_Transmit_File_Result::priority (void) const -{ - return ACE_WIN32_Asynch_Result::priority (); -} - -int -ACE_WIN32_Asynch_Transmit_File_Result::signal_number (void) const -{ - return ACE_WIN32_Asynch_Result::signal_number (); -} - -int -ACE_WIN32_Asynch_Transmit_File_Result::post_completion (ACE_Proactor_Impl *proactor) -{ - return ACE_WIN32_Asynch_Result::post_completion (proactor); -} - -ACE_WIN32_Asynch_Transmit_File::ACE_WIN32_Asynch_Transmit_File (ACE_WIN32_Proactor *win32_proactor) - : ACE_Asynch_Operation_Impl (), - ACE_Asynch_Transmit_File_Impl (), - ACE_WIN32_Asynch_Operation (win32_proactor) -{ -} - -int -ACE_WIN32_Asynch_Transmit_File::transmit_file (ACE_HANDLE file, - ACE_Asynch_Transmit_File::Header_And_Trailer *header_and_trailer, - size_t bytes_to_write, - u_long offset, - u_long offset_high, - size_t bytes_per_send, - u_long flags, - const void *act, - int priority, - int signal_number) -{ -#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) || (defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0)) - - // TransmitFile API limits us to DWORD range. - if (bytes_to_write > MAXDWORD || bytes_per_send > MAXDWORD) - { - errno = ERANGE; - return -1; - } - DWORD dword_bytes_to_write = static_cast (bytes_to_write); - DWORD dword_bytes_per_send = static_cast (bytes_per_send); - - ACE_WIN32_Asynch_Transmit_File_Result *result = 0; - ACE_NEW_RETURN (result, - ACE_WIN32_Asynch_Transmit_File_Result (this->handler_proxy_, - this->handle_, - file, - header_and_trailer, - bytes_to_write, - offset, - offset_high, - bytes_per_send, - flags, - act, - this->win32_proactor_->get_handle (), - priority, - signal_number), - -1); - - ACE_LPTRANSMIT_FILE_BUFFERS transmit_buffers = 0; - if (result->header_and_trailer () != 0) - transmit_buffers = result->header_and_trailer ()->transmit_buffers (); - - // Initiate the transmit file - int initiate_result = ::TransmitFile ((SOCKET) result->socket (), - result->file (), - dword_bytes_to_write, - dword_bytes_per_send, - result, - transmit_buffers, - result->flags ()); - if (initiate_result == 1) - // Immediate success: the OVERLAPPED will still get queued. - return 1; - - // If initiate failed, check for a bad error. - ACE_OS::set_errno_to_last_error (); - switch (errno) - { - case ERROR_IO_PENDING: - // The IO will complete proactively: the OVERLAPPED will still - // get queued. - return 0; - - default: - // Something else went wrong: the OVERLAPPED will not get - // queued. - - // Cleanup dynamically allocated Asynch_Result - delete result; - - if (ACE::debug ()) - { - ACE_DEBUG ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("TransmitFile"))); - } - return -1; - } -#else - ACE_UNUSED_ARG (file); - ACE_UNUSED_ARG (header_and_trailer); - ACE_UNUSED_ARG (bytes_to_write); - ACE_UNUSED_ARG (offset); - ACE_UNUSED_ARG (offset_high); - ACE_UNUSED_ARG (bytes_per_send); - ACE_UNUSED_ARG (flags); - ACE_UNUSED_ARG (act); - ACE_UNUSED_ARG (priority); - ACE_UNUSED_ARG (signal_number); - ACE_NOTSUP_RETURN (-1); -#endif /* ACE_HAS_WIN32_OVERLAPPED_IO || ACE_HAS_WINSOCK2 */ -} - -ACE_WIN32_Asynch_Transmit_File::~ACE_WIN32_Asynch_Transmit_File (void) -{ -} - -// Methods belong to ACE_WIN32_Asynch_Operation base class. These -// methods are defined here to avoid VC++ warnings. They route the -// call to the ACE_WIN32_Asynch_Operation base class. - -int -ACE_WIN32_Asynch_Transmit_File::open (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor) -{ - return ACE_WIN32_Asynch_Operation::open (handler_proxy, - handle, - completion_key, - proactor); -} - -int -ACE_WIN32_Asynch_Transmit_File::cancel (void) -{ - return ACE_WIN32_Asynch_Operation::cancel (); -} - -ACE_Proactor * -ACE_WIN32_Asynch_Transmit_File::proactor (void) const -{ - return ACE_WIN32_Asynch_Operation::proactor (); -} - -size_t -ACE_WIN32_Asynch_Read_Dgram_Result::bytes_to_read (void) const -{ - return this->bytes_to_read_; -} - -ACE_Message_Block* -ACE_WIN32_Asynch_Read_Dgram_Result::message_block (void) const -{ - return this->message_block_; -} - - -int -ACE_WIN32_Asynch_Read_Dgram_Result::remote_address (ACE_Addr& addr) const -{ - int retVal = -1; // failure - - // make sure the addresses are of the same type - if (addr.get_type () == this->remote_address_->get_type ()) - { // copy the remote_address_ into addr - addr.set_addr (this->remote_address_->get_addr (), - this->remote_address_->get_size ()); - retVal = 0; // success - } - - return retVal; -} - -sockaddr * -ACE_WIN32_Asynch_Read_Dgram_Result::saddr () const -{ - return (sockaddr *) this->remote_address_->get_addr (); -} - - -int -ACE_WIN32_Asynch_Read_Dgram_Result::flags (void) const -{ - return this->flags_; -} - -ACE_HANDLE -ACE_WIN32_Asynch_Read_Dgram_Result::handle (void) const -{ - return this->handle_; -} - -size_t -ACE_WIN32_Asynch_Read_Dgram_Result::bytes_transferred (void) const -{ - return ACE_WIN32_Asynch_Result::bytes_transferred (); -} - -const void * -ACE_WIN32_Asynch_Read_Dgram_Result::act (void) const -{ - return ACE_WIN32_Asynch_Result::act (); -} - -int -ACE_WIN32_Asynch_Read_Dgram_Result::success (void) const -{ - return ACE_WIN32_Asynch_Result::success (); -} - -const void * -ACE_WIN32_Asynch_Read_Dgram_Result::completion_key (void) const -{ - return ACE_WIN32_Asynch_Result::completion_key (); -} - -u_long -ACE_WIN32_Asynch_Read_Dgram_Result::error (void) const -{ - return ACE_WIN32_Asynch_Result::error (); -} - -ACE_HANDLE -ACE_WIN32_Asynch_Read_Dgram_Result::event (void) const -{ - return ACE_WIN32_Asynch_Result::event (); -} - -u_long -ACE_WIN32_Asynch_Read_Dgram_Result::offset (void) const -{ - return ACE_WIN32_Asynch_Result::offset (); -} - -u_long -ACE_WIN32_Asynch_Read_Dgram_Result::offset_high (void) const -{ - return ACE_WIN32_Asynch_Result::offset_high (); -} - -int -ACE_WIN32_Asynch_Read_Dgram_Result::priority (void) const -{ - return ACE_WIN32_Asynch_Result::priority (); -} - -int -ACE_WIN32_Asynch_Read_Dgram_Result::signal_number (void) const -{ - return ACE_WIN32_Asynch_Result::signal_number (); -} - -int -ACE_WIN32_Asynch_Read_Dgram_Result::post_completion (ACE_Proactor_Impl *proactor) -{ - return ACE_WIN32_Asynch_Result::post_completion (proactor); -} - -ACE_WIN32_Asynch_Read_Dgram_Result::ACE_WIN32_Asynch_Read_Dgram_Result ( - const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - ACE_Message_Block *message_block, - size_t bytes_to_read, - int flags, - int protocol_family, - const void* act, - ACE_HANDLE event, - int priority, - int signal_number) - : ACE_Asynch_Result_Impl (), - ACE_Asynch_Read_Dgram_Result_Impl(), - ACE_WIN32_Asynch_Result (handler_proxy, act, event, 0, 0, priority, signal_number), - bytes_to_read_ (bytes_to_read), - message_block_ (message_block), - remote_address_ (0), - addr_len_ (0), - flags_ (flags), - handle_ (handle) -{ - ACE_ASSERT (protocol_family == PF_INET); // only supporting INET addresses - - ACE_NEW (remote_address_, ACE_INET_Addr); - addr_len_ = remote_address_->get_size (); - - ACE_UNUSED_ARG (protocol_family); -} - -void -ACE_WIN32_Asynch_Read_Dgram_Result::complete (size_t bytes_transferred, - int success, - const void *completion_key, - u_long error) -{ - // Copy the data which was returned by GetQueuedCompletionStatus - this->bytes_transferred_ = bytes_transferred; - this->success_ = success; - this->completion_key_ = completion_key; - this->error_ = error; - - // Appropriately move the pointers in the message block. - for (ACE_Message_Block* mb = this->message_block_; - (mb != 0) && (bytes_transferred > 0); - mb = mb->cont ()) - { - size_t len_part = mb->space (); - - if ( len_part > bytes_transferred) - len_part = bytes_transferred; - - mb->wr_ptr (len_part); - - bytes_transferred -= len_part; - } - - // Adjust the address length - this->remote_address_->set_size (this->addr_len_); - - // Create the interface result class. - ACE_Asynch_Read_Dgram::Result result (this); - - // Call the application handler. - ACE_Handler *handler = this->handler_proxy_.get ()->handler (); - if (handler != 0) - handler->handle_read_dgram (result); -} - -ACE_WIN32_Asynch_Read_Dgram_Result::~ACE_WIN32_Asynch_Read_Dgram_Result (void) -{ - delete this->remote_address_; -} - -//*************************************************************************** - -ACE_WIN32_Asynch_Read_Dgram::~ACE_WIN32_Asynch_Read_Dgram (void) -{ -} - -ssize_t -ACE_WIN32_Asynch_Read_Dgram::recv (ACE_Message_Block *message_block, - size_t & number_of_bytes_recvd, - int flags, - int protocol_family, - const void *act, - int priority, - int signal_number) -{ - number_of_bytes_recvd = 0; - - size_t bytes_to_read = 0; - - iovec iov[ACE_IOV_MAX]; - int iovcnt = 0; - - for (const ACE_Message_Block* msg = message_block; - msg != 0 && iovcnt < ACE_IOV_MAX; - msg = msg->cont () , ++iovcnt ) - { - size_t msg_space = msg->space (); - - // OS should correctly process zero length buffers - // if ( msg_space == 0 ) - // ACE_ERROR_RETURN ((LM_ERROR, - // ACE_TEXT ("ACE_WIN32_Asynch_Read_Dgram::recv:") - // ACE_TEXT ("No space in the message block\n")), - // -1); - - bytes_to_read += msg_space; - - // Make as many iovec as needed to fit all of msg_len. - size_t wr_ptr_offset = 0; - - while (msg_space > 0 && iovcnt < ACE_IOV_MAX) - { - u_long this_chunk_length; - if (msg_space > ULONG_MAX) - this_chunk_length = ULONG_MAX; - else - this_chunk_length = static_cast (msg_space); - // Collect the data in the iovec. - iov[iovcnt].iov_base = msg->wr_ptr () + wr_ptr_offset; - iov[iovcnt].iov_len = this_chunk_length; - msg_space -= this_chunk_length; - wr_ptr_offset += this_chunk_length; - - // Increment iovec counter if there's more to do. - if (msg_space > 0) - iovcnt++; - } - if (msg_space > 0) // Ran out of iovecs before msg_space exhausted - { - errno = ERANGE; - return -1; - } - } - - if (bytes_to_read == 0) - ACE_ERROR_RETURN ((LM_ERROR, - ACE_TEXT ("ACE_WIN32_Asynch_Read_Dgram::recv:") - ACE_TEXT ("Attempt to read 0 bytes\n")), - -1); - - // Create the Asynch_Result. - ACE_WIN32_Asynch_Read_Dgram_Result *result = 0; - ACE_NEW_RETURN (result, - ACE_WIN32_Asynch_Read_Dgram_Result (this->handler_proxy_, - this->handle_, - message_block, - bytes_to_read, - flags, - protocol_family, - act, - this->win32_proactor_->get_handle (), - priority, - signal_number), - -1); - - // do the scatter/gather recv - ssize_t initiate_result = ACE_OS::recvfrom (result->handle (), - iov, - iovcnt, - number_of_bytes_recvd, - result->flags_, - result->saddr (), - &(result->addr_len_), - result, - 0); - if (initiate_result == SOCKET_ERROR) - { - // If initiate failed, check for a bad error. - ACE_OS::set_errno_to_last_error (); - switch (errno) - { - case ERROR_IO_PENDING: - // The IO will complete proactively: the OVERLAPPED will still - // get queued. - initiate_result = 0; - break; - - default: - // Something else went wrong: the OVERLAPPED will not get - // queued. - - if (ACE::debug ()) - { - ACE_DEBUG ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("WSARecvFrom"))); - } - - delete result; - initiate_result = -1; - break; - } - - } - else - { - // Immediate success: the OVERLAPPED will still get queued. - // number_of_bytes_recvd contains the number of bytes recvd - // addr contains the peer address - // flags was updated - - // number_of_bytes_recvd = bytes_recvd; - initiate_result = 1; - } - - return initiate_result; -} - -int -ACE_WIN32_Asynch_Read_Dgram::open (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor) -{ - return ACE_WIN32_Asynch_Operation::open (handler_proxy, - handle, - completion_key, - proactor); -} - -int -ACE_WIN32_Asynch_Read_Dgram::cancel (void) -{ - return ACE_WIN32_Asynch_Operation::cancel (); -} - -ACE_Proactor * -ACE_WIN32_Asynch_Read_Dgram::proactor (void) const -{ - return ACE_WIN32_Asynch_Operation::proactor (); -} - -ACE_WIN32_Asynch_Read_Dgram::ACE_WIN32_Asynch_Read_Dgram (ACE_WIN32_Proactor *win32_proactor) - : ACE_Asynch_Operation_Impl (), - ACE_Asynch_Read_Dgram_Impl (), - ACE_WIN32_Asynch_Operation (win32_proactor) -{ -} - -//*********************************************** - -size_t -ACE_WIN32_Asynch_Write_Dgram_Result::bytes_to_write (void) const -{ - return this->bytes_to_write_; -} - -ACE_Message_Block* -ACE_WIN32_Asynch_Write_Dgram_Result::message_block () const -{ - return this->message_block_; -} - -int -ACE_WIN32_Asynch_Write_Dgram_Result::flags (void) const -{ - return this->flags_; -} - -ACE_HANDLE -ACE_WIN32_Asynch_Write_Dgram_Result::handle (void) const -{ - return this->handle_; -} - -size_t -ACE_WIN32_Asynch_Write_Dgram_Result::bytes_transferred (void) const -{ - return ACE_WIN32_Asynch_Result::bytes_transferred (); -} - -const void * -ACE_WIN32_Asynch_Write_Dgram_Result::act (void) const -{ - return ACE_WIN32_Asynch_Result::act (); -} - -int -ACE_WIN32_Asynch_Write_Dgram_Result::success (void) const -{ - return ACE_WIN32_Asynch_Result::success (); -} - -const void * -ACE_WIN32_Asynch_Write_Dgram_Result::completion_key (void) const -{ - return ACE_WIN32_Asynch_Result::completion_key (); -} - -u_long -ACE_WIN32_Asynch_Write_Dgram_Result::error (void) const -{ - return ACE_WIN32_Asynch_Result::error (); -} - -ACE_HANDLE -ACE_WIN32_Asynch_Write_Dgram_Result::event (void) const -{ - return ACE_WIN32_Asynch_Result::event (); -} - -u_long -ACE_WIN32_Asynch_Write_Dgram_Result::offset (void) const -{ - return ACE_WIN32_Asynch_Result::offset (); -} - -u_long -ACE_WIN32_Asynch_Write_Dgram_Result::offset_high (void) const -{ - return ACE_WIN32_Asynch_Result::offset_high (); -} - -int -ACE_WIN32_Asynch_Write_Dgram_Result::priority (void) const -{ - return ACE_WIN32_Asynch_Result::priority (); -} - -int -ACE_WIN32_Asynch_Write_Dgram_Result::signal_number (void) const -{ - return ACE_WIN32_Asynch_Result::signal_number (); -} - -int -ACE_WIN32_Asynch_Write_Dgram_Result::post_completion (ACE_Proactor_Impl *proactor) -{ - return ACE_WIN32_Asynch_Result::post_completion (proactor); -} - -ACE_WIN32_Asynch_Write_Dgram_Result::ACE_WIN32_Asynch_Write_Dgram_Result ( - const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - ACE_Message_Block *message_block, - size_t bytes_to_write, - int flags, - const void* act, - ACE_HANDLE event, - int priority, - int signal_number) - : ACE_Asynch_Result_Impl (), - ACE_Asynch_Write_Dgram_Result_Impl(), - ACE_WIN32_Asynch_Result (handler_proxy, - act, - event, - 0, - 0, - priority, - signal_number), - bytes_to_write_ (bytes_to_write), - message_block_ (message_block), - flags_ (flags), - handle_ (handle) -{ -} - -void -ACE_WIN32_Asynch_Write_Dgram_Result::complete (size_t bytes_transferred, - int success, - const void *completion_key, - u_long error) -{ - // Copy the data which was returned by GetQueuedCompletionStatus - this->bytes_transferred_ = bytes_transferred; - this->success_ = success; - this->completion_key_ = completion_key; - this->error_ = error; - - // Appropriately move the pointers in the message block. - for (ACE_Message_Block* mb = this->message_block_; - (mb != 0) && (bytes_transferred > 0); - mb = mb->cont ()) - { - size_t len_part = mb->length (); - - if ( len_part > bytes_transferred) - len_part = bytes_transferred; - - mb->rd_ptr (len_part); - - bytes_transferred -= len_part; - } - - // Create the interface result class. - ACE_Asynch_Write_Dgram::Result result (this); - - // Call the application handler. - ACE_Handler *handler = this->handler_proxy_.get ()->handler (); - if (handler != 0) - handler->handle_write_dgram (result); -} - -ACE_WIN32_Asynch_Write_Dgram_Result::~ACE_WIN32_Asynch_Write_Dgram_Result (void) -{ -} - - -//*********************************************** - -ACE_WIN32_Asynch_Write_Dgram::~ACE_WIN32_Asynch_Write_Dgram (void) -{ -} - -ssize_t -ACE_WIN32_Asynch_Write_Dgram::send (ACE_Message_Block *message_block, - size_t &number_of_bytes_sent, - int flags, - const ACE_Addr &addr, - const void *act, - int priority, - int signal_number) -{ - number_of_bytes_sent = 0; - - size_t bytes_to_write = 0; - - iovec iov[ACE_IOV_MAX]; - int iovcnt = 0; - - for (const ACE_Message_Block* msg = message_block; - msg != 0 && iovcnt < ACE_IOV_MAX; - msg = msg->cont () , ++iovcnt ) - { - size_t msg_len = msg->length (); - - bytes_to_write += msg_len; - - // Make as many iovec as needed to fit all of msg_len. - size_t rd_ptr_offset = 0; - - do - { - if (msg_len >= 0 && iovcnt < ACE_IOV_MAX) - { - u_long this_chunk_length; - if (msg_len > ULONG_MAX) - this_chunk_length = ULONG_MAX; - else - this_chunk_length = static_cast (msg_len); - - // Collect the data in the iovec. - iov[iovcnt].iov_base = msg->rd_ptr () + rd_ptr_offset; - iov[iovcnt].iov_len = this_chunk_length; - msg_len -= this_chunk_length; - rd_ptr_offset += this_chunk_length; - - // Increment iovec counter if there's more to do. - if (msg_len > 0) - iovcnt++; - } - } - while (msg_len > 0 && iovcnt < ACE_IOV_MAX); - - if (msg_len > 0) // Ran out of iovecs before msg_space exhausted - { - errno = ERANGE; - return -1; - } - } - - // Create the Asynch_Result. - ACE_WIN32_Asynch_Write_Dgram_Result *result = 0; - ACE_NEW_RETURN (result, - ACE_WIN32_Asynch_Write_Dgram_Result (this->handler_proxy_, - this->handle_, - message_block, - bytes_to_write, - flags, - act, - this->win32_proactor_->get_handle (), - priority, - signal_number), - -1); - - // do the scatter/gather send - - ssize_t initiate_result = ACE_OS::sendto (result->handle (), - iov, - iovcnt, - number_of_bytes_sent, - result->flags_, - (sockaddr *) addr.get_addr (), - addr.get_size(), - result, - 0); - - - if (initiate_result == SOCKET_ERROR) - { - // If initiate failed, check for a bad error. - ACE_OS::set_errno_to_last_error (); - switch (errno) - { - case ERROR_IO_PENDING: - // The IO will complete proactively: the OVERLAPPED will still - // get queued. - initiate_result = 0; - break; - - default: - // Something else went wrong: the OVERLAPPED will not get - // queued. - - if (ACE::debug ()) - { - ACE_DEBUG ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("WSASendTo"))); - } - - delete result; - initiate_result = -1; - break; - } - - } - else - { - // Immediate success: the OVERLAPPED will still get queued. - // number_of_bytes_recvd contains the number of bytes recvd - // addr contains the peer address - // flags was updated - - // number_of_bytes_sent = bytes_sent; - initiate_result = 1; - } - - return initiate_result; -} - -int -ACE_WIN32_Asynch_Write_Dgram::open (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor) -{ - return ACE_WIN32_Asynch_Operation::open (handler_proxy, - handle, - completion_key, - proactor); -} - -int -ACE_WIN32_Asynch_Write_Dgram::cancel (void) -{ - return ACE_WIN32_Asynch_Operation::cancel (); -} - -ACE_Proactor * -ACE_WIN32_Asynch_Write_Dgram::proactor (void) const -{ - return ACE_WIN32_Asynch_Operation::proactor (); -} - -ACE_WIN32_Asynch_Write_Dgram::ACE_WIN32_Asynch_Write_Dgram (ACE_WIN32_Proactor *win32_proactor) - : ACE_Asynch_Operation_Impl (), - ACE_Asynch_Write_Dgram_Impl (), - ACE_WIN32_Asynch_Operation (win32_proactor) -{ -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_WIN32_OVERLAPPED_IO && ACE_HAS_WINSOCK2 */ diff --git a/externals/ace/WIN32_Asynch_IO.h b/externals/ace/WIN32_Asynch_IO.h deleted file mode 100644 index 34af77dabb2..00000000000 --- a/externals/ace/WIN32_Asynch_IO.h +++ /dev/null @@ -1,1937 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file WIN32_Asynch_IO.h - * - * $Id: WIN32_Asynch_IO.h 80826 2008-03-04 14:51:23Z wotte $ - * - * - * These classes only works on Win32 platforms. - * - * The implementation of ACE_Asynch_Transmit_File, - * ACE_Asynch_Accept, and ACE_Asynch_Connect are only supported if - * ACE_HAS_WINSOCK2 is defined or you are on WinNT 4.0 or higher. - * - * - * @author Irfan Pyarali - * @author Tim Harrison - * @author Alexander Babu Arulanthu - * @author Roger Tragin - * @author Alexander Libman - */ -//============================================================================= - -#ifndef ACE_WIN32_ASYNCH_IO_H -#define ACE_WIN32_ASYNCH_IO_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -#pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) && \ - (defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 == 1)) - -#include "ace/Asynch_IO_Impl.h" -#include "ace/Addr.h" -#include "ace/Event_Handler.h" -#include "ace/Handle_Set.h" -#include "ace/Map_Manager.h" -#include "ace/Null_Mutex.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Forward declaration -class ACE_WIN32_Proactor; - -/** - * @class ACE_WIN32_Asynch_Result - * - * @brief An abstract class which adds information to the OVERLAPPED - * structure to make it more useful. - * - * An abstract base class from which you can obtain some basic - * information like the number of bytes transferred, the ACT - * associated with the asynchronous operation, indication of - * success or failure, etc. Subclasses may want to store more - * information that is particular to the asynchronous operation - * it represents. - */ -class ACE_Export ACE_WIN32_Asynch_Result : public virtual ACE_Asynch_Result_Impl, - public OVERLAPPED -{ - /// Factory class has special permissions. - friend class ACE_WIN32_Asynch_Accept; - - /// Proactor class has special permission. - friend class ACE_WIN32_Proactor; - -public: - /// Number of bytes transferred by the operation. - size_t bytes_transferred (void) const; - - /// ACT associated with the operation. - const void *act (void) const; - - /// Did the operation succeed? - int success (void) const; - - /** - * This returns the ACT associated with the handle when it was - * registered with the I/O completion port. This ACT is not the - * same as the ACT associated with the asynchronous operation. - */ - const void *completion_key (void) const; - - /// Error value if the operation fail. - u_long error (void) const; - - /// Event associated with the OVERLAPPED structure. - ACE_HANDLE event (void) const; - - /// This really make sense only when doing file I/O. - u_long offset (void) const; - - /// Offset_high associated with the OVERLAPPED structure. - u_long offset_high (void) const; - - /// The priority of the asynchronous operation. Currently, this is - /// not supported on Win32. - int priority (void) const; - - /// Returns 0. - int signal_number (void) const; - - /// Post @c this to the Proactor's completion port. - int post_completion (ACE_Proactor_Impl *proactor); - - /// Destructor. - virtual ~ACE_WIN32_Asynch_Result (void); - - /// Simulate error value to use in the post_completion () - void set_error (u_long errcode); - - /// Simulate value to use in the post_completion () - void set_bytes_transferred (size_t nbytes); - -protected: - /// Constructor. - ACE_WIN32_Asynch_Result (const ACE_Handler::Proxy_Ptr &handler_proxy, - const void* act, - ACE_HANDLE event, - u_long offset, - u_long offset_high, - int priority, - int signal_number = 0); - - /// Proxy for the ACE_Handler that will be called back. - ACE_Handler::Proxy_Ptr handler_proxy_; - - /// ACT for this operation. - const void *act_; - - /// Bytes transferred by this operation. - size_t bytes_transferred_; - - /// Success indicator. - int success_; - - /// ACT associated with handle. - const void *completion_key_; - - /// Error if operation failed. - u_long error_; -}; - -/** - * @class ACE_WIN32_Asynch_Operation - * - * @brief This class abstracts out the common things needed for - * implementing Asynch_Operation for WIN32 platform. - * - */ -class ACE_Export ACE_WIN32_Asynch_Operation : public virtual ACE_Asynch_Operation_Impl -{ -public: - /** - * Initializes the factory with information which will be used with - * each asynchronous call. If ( == ACE_INVALID_HANDLE), - * will be called on the @a handler to get the - * correct handle. - */ - int open (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor); - - /** - * This cancels all pending accepts operations that were issued by - * the calling thread. The function does not cancel asynchronous - * operations issued by other threads. - */ - int cancel (void); - - // = Access methods. - - /// Return the underlying proactor. - ACE_Proactor* proactor (void) const; - -protected: - /// Constructor. - ACE_WIN32_Asynch_Operation (ACE_WIN32_Proactor *win32_proactor); - - /// Destructor. - virtual ~ACE_WIN32_Asynch_Operation (void); - - /// Win32 Proactor. - ACE_WIN32_Proactor *win32_proactor_; - - /// Proactor that this asynch IO is registered with. - ACE_Proactor *proactor_; - - /// Handler that will receive the callback. - ACE_Handler::Proxy_Ptr handler_proxy_; - - /// I/O handle used for reading. - ACE_HANDLE handle_; -}; - -/** - * @class ACE_WIN32_Asynch_Read_Stream_Result - * - * @brief This class provides concrete implementation for - * ACE_Asynch_Read_Stream::Result class. - */ -class ACE_Export ACE_WIN32_Asynch_Read_Stream_Result : public virtual ACE_Asynch_Read_Stream_Result_Impl, - public ACE_WIN32_Asynch_Result -{ - /// Factory class will have special permissions. - friend class ACE_WIN32_Asynch_Read_Stream; - - /// Proactor class has special permission. - friend class ACE_WIN32_Proactor; - -public: - /// The number of bytes which were requested at the start of the - /// asynchronous read. - size_t bytes_to_read (void) const; - - /// Message block which contains the read data. - ACE_Message_Block &message_block (void) const; - - /// I/O handle used for reading. - ACE_HANDLE handle (void) const; - - // Base class operations. These operations are here to kill - // dominance warnings. These methods call the base class methods. - - /// Number of bytes transferred by the operation. - size_t bytes_transferred (void) const; - - /// ACT associated with the operation. - const void *act (void) const; - - /// Did the operation succeed? - int success (void) const; - - /** - * This returns the ACT associated with the handle when it was - * registered with the I/O completion port. This ACT is not the - * same as the ACT associated with the asynchronous operation. - */ - const void *completion_key (void) const; - - /// Error value if the operation fail. - u_long error (void) const; - - /// Event associated with the OVERLAPPED structure. - ACE_HANDLE event (void) const; - - /// This really make sense only when doing file I/O. - u_long offset (void) const; - - /// Offset_high associated with the OVERLAPPED structure. - u_long offset_high (void) const; - - /// The priority of the asynchronous operation. Currently, this is - /// not supported on Win32. - int priority (void) const; - - /// No-op. Returns 0. - int signal_number (void) const; - - /// Post @c this to the Proactor's completion port. - int post_completion (ACE_Proactor_Impl *proactor); - - /// Accessor for the scatter read flag - int scatter_enabled (void) const; - -protected: - /// Constructor is protected since creation is limited to - /// ACE_Asynch_Read_Stream factory. - ACE_WIN32_Asynch_Read_Stream_Result (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - ACE_Message_Block &message_block, - size_t bytes_to_read, - const void* act, - ACE_HANDLE event, - int priority, - int signal_number = 0, - int scatter_enabled = 0); - - /// Proactor will call this method when the read completes. - virtual void complete (size_t bytes_transferred, - int success, - const void *completion_key, - u_long error); - - /// Destructor. - virtual ~ACE_WIN32_Asynch_Read_Stream_Result (void); - - /// Bytes requested when the asynchronous read was initiated. - size_t bytes_to_read_; - - /// Message block for reading the data into. - ACE_Message_Block &message_block_; - - /// I/O handle used for reading. - ACE_HANDLE handle_; - - /// Flag for scatter read - int scatter_enabled_; -}; - -/** - * @class ACE_WIN32_Asynch_Read_Stream - * - * @brief This class is a factory for starting off asynchronous reads - * on a stream. - * - * Once is called, multiple asynchronous s can - * started using this class. An ACE_Asynch_Read_Stream::Result - * will be passed back to the @a handler when the asynchronous - * reads completes through the - * callback. - */ -class ACE_Export ACE_WIN32_Asynch_Read_Stream : public virtual ACE_Asynch_Read_Stream_Impl, - public ACE_WIN32_Asynch_Operation -{ - -public: - /// Constructor. - ACE_WIN32_Asynch_Read_Stream (ACE_WIN32_Proactor *win32_proactor); - - /// This starts off an asynchronous read. Upto @a bytes_to_read will - /// be read and stored in the @a message_block. - int read (ACE_Message_Block &message_block, - size_t bytes_to_read, - const void *act, - int priority, - int signal_number = 0); - - /** - * Same as above but with scatter support, through chaining of composite - * message blocks using the continuation field. - */ - int readv (ACE_Message_Block &message_block, - size_t bytes_to_read, - const void *act, - int priority, - int signal_number = 0); - - /// Destructor. - virtual ~ACE_WIN32_Asynch_Read_Stream (void); - - // Methods belong to ACE_WIN32_Asynch_Operation base class. These - // methods are defined here to avoid VC++ warnings. They route the - // call to the ACE_WIN32_Asynch_Operation base class. - - /** - * Initializes the factory with information which will be used with - * each asynchronous call. If ( == ACE_INVALID_HANDLE), - * will be called on the @a handler to get the - * correct handle. - */ - int open (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor); - - /** - * This cancels all pending accepts operations that were issued by - * the calling thread. The function does not cancel asynchronous - * operations issued by other threads. - */ - int cancel (void); - - /// Return the underlying proactor. - ACE_Proactor* proactor (void) const; - -protected: - /// This is the method which does the real work and is there so that - /// the ACE_Asynch_Read_File class can use it too. - int shared_read (ACE_WIN32_Asynch_Read_Stream_Result *result); -}; - -/** - * @class ACE_WIN32_Asynch_Write_Stream_Result - * - * @brief This class provides concrete implementation for - * ACE_Asynch_Write_Stream::Result class. - */ -class ACE_Export ACE_WIN32_Asynch_Write_Stream_Result : public virtual ACE_Asynch_Write_Stream_Result_Impl, - public ACE_WIN32_Asynch_Result -{ - /// Factory class willl have special permissions. - friend class ACE_WIN32_Asynch_Write_Stream; - - /// Proactor class has special permission. - friend class ACE_WIN32_Proactor; - -public: - /// The number of bytes which were requested at the start of the - /// asynchronous write. - size_t bytes_to_write (void) const; - - /// Message block that contains the data to be written. - ACE_Message_Block &message_block (void) const; - - /// I/O handle used for writing. - ACE_HANDLE handle (void) const; - - // = Base class operations. These operations are here to kill some - // warnings. These methods call the base class methods. - - /// Number of bytes transferred by the operation. - size_t bytes_transferred (void) const; - - /// ACT associated with the operation. - const void *act (void) const; - - /// Did the operation succeed? - int success (void) const; - - /** - * This returns the ACT associated with the handle when it was - * registered with the I/O completion port. This ACT is not the - * same as the ACT associated with the asynchronous operation. - */ - const void *completion_key (void) const; - - /// Error value if the operation fail. - u_long error (void) const; - - /// Event associated with the OVERLAPPED structure. - ACE_HANDLE event (void) const; - - /// This really make sense only when doing file I/O. - u_long offset (void) const; - - /// Offset_high associated with the OVERLAPPED structure. - u_long offset_high (void) const; - - /// The priority of the asynchronous operation. Currently, this is - /// not supported on Win32. - int priority (void) const; - - /// No-op. Returns 0. - int signal_number (void) const; - - /// Post @c this to the Proactor's completion port. - int post_completion (ACE_Proactor_Impl *proactor); - - /// Accessor for the gather write flag - int gather_enabled (void) const; - -protected: - /// Constructor is protected since creation is limited to - /// ACE_Asynch_Write_Stream factory. - ACE_WIN32_Asynch_Write_Stream_Result (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - ACE_Message_Block &message_block, - size_t bytes_to_write, - const void* act, - ACE_HANDLE event, - int priority, - int signal_number = 0, - int gather_enabled = 0); - - /// ACE_Proactor will call this method when the write completes. - virtual void complete (size_t bytes_transferred, - int success, - const void *completion_key, - u_long error); - - /// Destructor. - virtual ~ACE_WIN32_Asynch_Write_Stream_Result (void); - - /// The number of bytes which were requested at the start of the - /// asynchronous write. - size_t bytes_to_write_; - - /// Message block that contains the data to be written. - ACE_Message_Block &message_block_; - - /// I/O handle used for writing. - ACE_HANDLE handle_; - - /// Flag for gather write - int gather_enabled_; -}; - -/** - * @class ACE_WIN32_Asynch_Write_Stream - * - * @brief This class is a factory for starting off asynchronous writes - * on a stream. - * - * - * Once is called, multiple asynchronous s can - * started using this class. A ACE_Asynch_Write_Stream::Result - * will be passed back to the @a handler when the asynchronous - * write completes through the - * callback. - */ -class ACE_Export ACE_WIN32_Asynch_Write_Stream : public virtual ACE_Asynch_Write_Stream_Impl, - public ACE_WIN32_Asynch_Operation -{ -public: - /// Constructor. - ACE_WIN32_Asynch_Write_Stream (ACE_WIN32_Proactor *win32_proactor); - - /// This starts off an asynchronous write. Upto @a bytes_to_write - /// will be written from the @a message_block. - int write (ACE_Message_Block &message_block, - size_t bytes_to_write, - const void *act, - int priority, - int signal_number = 0); - - /** - * Same as above but with gather support, through chaining of composite - * message blocks using the continuation field. - */ - int writev (ACE_Message_Block &message_block, - size_t bytes_to_write, - const void *act, - int priority, - int signal_number = 0); - - /// Destructor. - virtual ~ACE_WIN32_Asynch_Write_Stream (void); - - // = Methods belonging to base class. - - // These methods are defined here to avoid VC++ warnings. They route - // the call to the base class. - - /** - * Initializes the factory with information which will be used with - * each asynchronous call. If ( == ACE_INVALID_HANDLE), - * will be called on the @a handler to get the - * correct handle. - */ - int open (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor); - - /** - * This cancels all pending accepts operations that were issued by - * the calling thread. The function does not cancel asynchronous - * operations issued by other threads. - */ - int cancel (void); - - /// Return the underlying proactor. - ACE_Proactor* proactor (void) const; - -protected: - /// This is the method which does the real work and is there so that - /// the ACE_Asynch_Write_File class can use it too. - int shared_write (ACE_WIN32_Asynch_Write_Stream_Result *result); -}; - -/** - * @class ACE_WIN32_Asynch_Read_File_Result - * - * @brief This class provides concrete implementation for - * ACE_Asynch_Read_File::Result class. - */ -class ACE_Export ACE_WIN32_Asynch_Read_File_Result : public virtual ACE_Asynch_Read_File_Result_Impl, - public ACE_WIN32_Asynch_Read_Stream_Result -{ - /// Factory class will have special permissions. - friend class ACE_WIN32_Asynch_Read_File; - - /// Proactor class has special permission. - friend class ACE_WIN32_Proactor; - -public: - // = These methods belong to ACE_WIN32_Asynch_Result class base - // class. These operations are here to kill some warnings. These - // methods call the base class methods. - - /// Number of bytes transferred by the operation. - size_t bytes_transferred (void) const; - - /// ACT associated with the operation. - const void *act (void) const; - - /// Did the operation succeed? - int success (void) const; - - /** - * This returns the ACT associated with the handle when it was - * registered with the I/O completion port. This ACT is not the - * same as the ACT associated with the asynchronous operation. - */ - const void *completion_key (void) const; - - /// Error value if the operation fail. - u_long error (void) const; - - /// Event associated with the OVERLAPPED structure. - ACE_HANDLE event (void) const; - - /// This really make sense only when doing file I/O. - u_long offset (void) const; - - /// Offset_high associated with the OVERLAPPED structure. - u_long offset_high (void) const; - - /// The priority of the asynchronous operation. Currently, this is - /// not supported on Win32. - int priority (void) const; - - /// No-op. Returns 0. - int signal_number (void) const; - - // The following methods belong to - // ACE_WIN32_Asynch_Read_Stream_Result. They are here to avoid VC++ - // dominance warnings. These methods route their call to the - // ACE_WIN32_Asynch_Read_Stream_Result base class. - - /// The number of bytes which were requested at the start of the - /// asynchronous read. - size_t bytes_to_read (void) const; - - /// Message block which contains the read data. - ACE_Message_Block &message_block (void) const; - - /// I/O handle used for reading. - ACE_HANDLE handle (void) const; - - /// Post @c this to the Proactor's completion port. - int post_completion (ACE_Proactor_Impl *proactor); - -protected: - /// Constructor is protected since creation is limited to - /// ACE_Asynch_Read_File factory. - ACE_WIN32_Asynch_Read_File_Result (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - ACE_Message_Block &message_block, - size_t bytes_to_read, - const void* act, - u_long offset, - u_long offset_high, - ACE_HANDLE event, - int priority, - int signal_number = 0, - int scatter_enabled = 0); - - /// ACE_Proactor will call this method when the read completes. - virtual void complete (size_t bytes_transferred, - int success, - const void *completion_key, - u_long error); - - /// Destructor. - virtual ~ACE_WIN32_Asynch_Read_File_Result (void); -}; - -/** - * @class ACE_WIN32_Asynch_Read_File - * - * @brief This class is a factory for starting off asynchronous reads - * on a file. - * - * Once is called, multiple asynchronous s can - * started using this class. A ACE_Asynch_Read_File::Result - * will be passed back to the @a handler when the asynchronous - * reads completes through the - * callback. - * - * This class differs slightly from ACE_Asynch_Read_Stream as it - * allows the user to specify an offset for the read. - */ -class ACE_Export ACE_WIN32_Asynch_Read_File : public virtual ACE_Asynch_Read_File_Impl, - public ACE_WIN32_Asynch_Read_Stream -{ - -public: - /// Constructor. - ACE_WIN32_Asynch_Read_File (ACE_WIN32_Proactor *win32_proactor); - - /** - * This starts off an asynchronous read. Upto @a bytes_to_read will - * be read and stored in the @a message_block. The read will start - * at @a offset from the beginning of the file. - */ - int read (ACE_Message_Block &message_block, - size_t bytes_to_read, - u_long offset, - u_long offset_high, - const void *act, - int priority, - int signal_number = 0); - - /** - * Same as above but with scatter support, through chaining of - * composite message blocks using the continuation field. - * @note Each data block payload must be at least the size of a - * system memory page and must be aligned on a system memory page - * size boundary - */ - int readv (ACE_Message_Block &message_block, - size_t bytes_to_read, - u_long offset, - u_long offset_high, - const void *act, - int priority, - int signal_number = 0); - - - /// Destructor. - virtual ~ACE_WIN32_Asynch_Read_File (void); - - // = Methods belong to ACE_WIN32_Asynch_Operation base class. These - // methods are defined here to avoid VC++ warnings. They route the - // call to the ACE_WIN32_Asynch_Operation base class. - - /** - * Initializes the factory with information which will be used with - * each asynchronous call. If ( == ACE_INVALID_HANDLE), - * will be called on the @a handler to get the - * correct handle. - */ - int open (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor); - - /** - * This cancels all pending accepts operations that were issued by - * the calling thread. The function does not cancel asynchronous - * operations issued by other threads. - */ - int cancel (void); - - /// Return the underlying proactor. - ACE_Proactor* proactor (void) const; - -private: - /** - * This method belongs to ACE_WIN32_Asynch_Read_Stream. It is here - * to avoid the compiler warnings. We forward this call to the - * ACE_WIN32_Asynch_Read_Stream class. - */ - int read (ACE_Message_Block &message_block, - size_t bytes_to_read, - const void *act, - int priority, - int signal_number = 0); - - /** - * Same as above but with scatter support, through chaining of composite - * message blocks using the continuation field. - */ - int readv (ACE_Message_Block &message_block, - size_t bytes_to_read, - const void *act, - int priority, - int signal_number = 0); -}; - -/** - * @class ACE_WIN32_Asynch_Write_File_Result - * - * @brief This class provides implementation for - * ACE_Asynch_Write_File_Result for WIN32 platforms. - * - * This class has all the information necessary for the - * @a handler to uniquiely identify the completion of the - * asynchronous write. - * - * This class differs slightly from - * ACE_Asynch_Write_Stream::Result as it calls back - * on the @a handler instead - * of . No additional state - * is required by this class as ACE_Asynch_Result can store - * the @a offset. - */ -class ACE_Export ACE_WIN32_Asynch_Write_File_Result : public virtual ACE_Asynch_Write_File_Result_Impl, - public ACE_WIN32_Asynch_Write_Stream_Result -{ - /// Factory class will have special permission. - friend class ACE_WIN32_Asynch_Write_File; - - /// Proactor class has special permission. - friend class ACE_WIN32_Proactor; - -public: - // = Base class operations. These operations are here to kill some - // warnings. These methods call the base class methods. - - /// Number of bytes transferred by the operation. - size_t bytes_transferred (void) const; - - /// ACT associated with the operation. - const void *act (void) const; - - /// Did the operation succeed? - int success (void) const; - - /** - * This returns the ACT associated with the handle when it was - * registered with the I/O completion port. This ACT is not the - * same as the ACT associated with the asynchronous operation. - */ - const void *completion_key (void) const; - - /// Error value if the operation fail. - u_long error (void) const; - - /// Event associated with the OVERLAPPED structure. - ACE_HANDLE event (void) const; - - /// This really make sense only when doing file I/O. - u_long offset (void) const; - - /// Offset_high associated with the OVERLAPPED structure. - u_long offset_high (void) const; - - /// The priority of the asynchronous operation. Currently, this is - /// not supported on Win32. - int priority (void) const; - - /// No-op. Returns 0. - int signal_number (void) const; - - // The following methods belong to - // ACE_WIN32_Asynch_Read_Stream_Result. They are here to avoid VC++ - // warnings. These methods route their call to the - // ACE_WIN32_Asynch_Read_Stream_Result base class. - - /// The number of bytes which were requested at the start of the - /// asynchronous write. - size_t bytes_to_write (void) const; - - /// Message block that contains the data to be written. - ACE_Message_Block &message_block (void) const; - - /// I/O handle used for writing. - ACE_HANDLE handle (void) const; - - /// Post @c this to the Proactor's completion port. - int post_completion (ACE_Proactor_Impl *proactor); - -protected: - /// Constructor is protected since creation is limited to - /// ACE_Asynch_Write_File factory. - ACE_WIN32_Asynch_Write_File_Result (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - ACE_Message_Block &message_block, - size_t bytes_to_write, - const void* act, - u_long offset, - u_long offset_high, - ACE_HANDLE event, - int priority, - int signal_number = 0, - int gather_enabled = 0); - - /// ACE_Proactor will call this method when the write completes. - virtual void complete (size_t bytes_transferred, - int success, - const void *completion_key, - u_long error); - - /// Destructor. - virtual ~ACE_WIN32_Asynch_Write_File_Result (void); -}; - -/** - * @class ACE_WIN32_Asynch_Write_File - * - * @brief This class is a factory for starting off asynchronous writes - * on a file. - * - * Once is called, multiple asynchronous s can be - * started using this class. A ACE_Asynch_Write_File::Result - * will be passed back to the @a handler when the asynchronous - * writes completes through the - * callback. - */ -class ACE_Export ACE_WIN32_Asynch_Write_File : public virtual ACE_Asynch_Write_File_Impl, - public ACE_WIN32_Asynch_Write_Stream -{ -public: - /// Constructor. - ACE_WIN32_Asynch_Write_File (ACE_WIN32_Proactor *win32_proactor); - - /** - * This starts off an asynchronous write. Upto @a bytes_to_write - * will be write and stored in the @a message_block. The write will - * start at @a offset from the beginning of the file. - */ - int write (ACE_Message_Block &message_block, - size_t bytes_to_write, - u_long offset, - u_long offset_high, - const void *act, - int priority, - int signal_number = 0); - - /** - * Same as above but with gather support, through chaining of - * composite message blocks using the continuation field. - * @note Each data block payload must be at least the size of a - * system memory page and must be aligned on a system memory page - * size boundary - */ - int writev (ACE_Message_Block &message_block, - size_t bytes_to_write, - u_long offset, - u_long offset_high, - const void *act, - int priority, - int signal_number = 0); - - /// Destrcutor. - virtual ~ACE_WIN32_Asynch_Write_File (void); - - // = Methods belong to ACE_WIN32_Asynch_Operation base class. These - // methods are defined here to avoid VC++ warnings. They route the - // call to the ACE_WIN32_Asynch_Operation base class. - - /** - * Initializes the factory with information which will be used with - * each asynchronous call. If ( == ACE_INVALID_HANDLE), - * will be called on the @a handler to get the - * correct handle. - */ - int open (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor); - - /** - * This cancels all pending accepts operations that were issued by - * the calling thread. The function does not cancel asynchronous - * operations issued by other threads. - */ - int cancel (void); - - /// Return the underlying proactor. - ACE_Proactor* proactor (void) const; - -private: - /** - * This method belongs to ACE_WIN32_Asynch_Write_Stream. It is here - * to avoid compiler warnings. This method is forwarded to the - * ACE_WIN32_Asynch_Write_Stream class. - */ - int write (ACE_Message_Block &message_block, - size_t bytes_to_write, - const void *act, - int priority, - int signal_number = 0); - - /** - * Same as above but with gather support, through chaining of composite - * message blocks using the continuation field. - */ - int writev (ACE_Message_Block &message_block, - size_t bytes_to_write, - const void *act, - int priority, - int signal_number = 0); -}; - -/** - * @class ACE_WIN32_Asynch_Accept_Result - * - * @brief This class implements ACE_Asynch_Accept::Result for WIN32 - * platform. - * - * This class has all the information necessary for the - * @a handler to uniquiely identify the completion of the - * asynchronous accept. - */ -class ACE_Export ACE_WIN32_Asynch_Accept_Result : public virtual ACE_Asynch_Accept_Result_Impl, - public ACE_WIN32_Asynch_Result -{ - /// Factory will have special permission. - friend class ACE_WIN32_Asynch_Accept; - - /// Proactor class has special permission. - friend class ACE_WIN32_Proactor; - -public: - /// The number of bytes which were requested at the start of the - /// asynchronous accept. - size_t bytes_to_read (void) const; - - /// Message block which contains the read data. - ACE_Message_Block &message_block (void) const; - - /// I/O handle used for accepting new connections. - ACE_HANDLE listen_handle (void) const; - - /// I/O handle for the new connection. - ACE_HANDLE accept_handle (void) const; - - // = Base class operations. These operations are here to kill some - // warnings. These methods call the base class methods. - - /// Number of bytes transferred by the operation. - size_t bytes_transferred (void) const; - - /// ACT associated with the operation. - const void *act (void) const; - - /// Did the operation succeed? - int success (void) const; - - /** - * This returns the ACT associated with the handle when it was - * registered with the I/O completion port. This ACT is not the - * same as the ACT associated with the asynchronous operation. - */ - const void *completion_key (void) const; - - /// Error value if the operation fail. - u_long error (void) const; - - /// Event associated with the OVERLAPPED structure. - ACE_HANDLE event (void) const; - - /// This really make sense only when doing file I/O. - u_long offset (void) const; - - /// Offset_high associated with the OVERLAPPED structure. - u_long offset_high (void) const; - - /// The priority of the asynchronous operation. Currently, this is - /// not supported on Win32. - int priority (void) const; - - /// No-op. Returns 0. - int signal_number (void) const; - - /// Post @c this to the Proactor's completion port. - int post_completion (ACE_Proactor_Impl *proactor); - -protected: - /// Constructor is protected since creation is limited to - /// ACE_Asynch_Accept factory. - ACE_WIN32_Asynch_Accept_Result (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE listen_handle, - ACE_HANDLE accept_handle, - ACE_Message_Block &message_block, - size_t bytes_to_read, - const void* act, - ACE_HANDLE event, - int priority, - int signal_number = 0); - - /// ACE_Proactor will call this method when the accept completes. - virtual void complete (size_t bytes_transferred, - int success, - const void *completion_key, - u_long error); - - /// Destructor. - virtual ~ACE_WIN32_Asynch_Accept_Result (void); - - /// Bytes requested when the asynchronous read was initiated. - size_t bytes_to_read_; - - /// Message block for reading the data into. - ACE_Message_Block &message_block_; - - /// I/O handle used for accepting new connections. - ACE_HANDLE listen_handle_; - - /// I/O handle for the new connection. - ACE_HANDLE accept_handle_; -}; - -/** - * @class ACE_WIN32_Asynch_Accept - * - * @brief This class is a factory for starting off asynchronous accepts - * on a listen handle. - * - * Once is called, multiple asynchronous s can - * started using this class. A ACE_Asynch_Accept::Result will - * be passed back to the @a handler when the asynchronous accept - * completes through the - * callback. - */ -class ACE_Export ACE_WIN32_Asynch_Accept : public virtual ACE_Asynch_Accept_Impl, - public ACE_WIN32_Asynch_Operation -{ -public: - /// Constructor. - ACE_WIN32_Asynch_Accept (ACE_WIN32_Proactor *win32_proactor); - - /** - * This starts off an asynchronous accept. The asynchronous accept - * call also allows any initial data to be returned to the - * @a handler. Upto @a bytes_to_read will be read and stored in the - * @a message_block. The will be used for the - * call. If ( == INVALID_HANDLE), a new - * handle will be created. - * - * @a message_block must be specified. This is because the address of - * the new connection is placed at the end of this buffer. - */ - int accept (ACE_Message_Block &message_block, - size_t bytes_to_read, - ACE_HANDLE accept_handle, - const void *act, - int priority, - int signal_number = 0, - int addr_family = AF_INET); - - /// Destructor. - ~ACE_WIN32_Asynch_Accept (void); - - // Methods belong to ACE_WIN32_Asynch_Operation base class. These - // methods are defined here to avoid VC++ warnings. They route the - // call to the ACE_WIN32_Asynch_Operation base class. - - /** - * Initializes the factory with information which will be used with - * each asynchronous call. If ( == ACE_INVALID_HANDLE), - * will be called on the @a handler to get the - * correct handle. - */ - int open (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor); - - /** - * This cancels all pending accepts operations that were issued by - * the calling thread. The function does not cancel asynchronous - * operations issued by other threads. - */ - int cancel (void); - - /// Return the underlying proactor. - ACE_Proactor* proactor (void) const; -}; - -/** - * @class ACE_WIN32_Asynch_Connect_Result - * - * @brief This is that class which will be passed back to the - * completion handler when the asynchronous connect completes. - * - * This class has all the information necessary for the - * completion handler to uniquiely identify the completion of the - * asynchronous connect. - */ -class ACE_Export ACE_WIN32_Asynch_Connect_Result : public virtual ACE_Asynch_Connect_Result_Impl, - public ACE_WIN32_Asynch_Result -{ - /// Factory classes will have special permissions. - friend class ACE_WIN32_Asynch_Connect; - - /// The Proactor constructs the Result class for faking results. - friend class ACE_WIN32_Proactor; - -public: - - /// I/O handle for the connection. - ACE_HANDLE connect_handle (void) const; - - // = Base class operations. These operations are here to kill some - // warnings. These methods call the base class methods. - - /// Number of bytes transferred by the operation. - size_t bytes_transferred (void) const; - - /// ACT associated with the operation. - const void *act (void) const; - - /// Did the operation succeed? - int success (void) const; - - /** - * Returns the ACT associated with the handle when it was - * registered with the I/O completion port. This ACT is not the - * same as the ACT associated with the asynchronous operation. - */ - const void *completion_key (void) const; - - /// Error value if the operation fail. - u_long error (void) const; - - /// Event associated with the OVERLAPPED structure. - ACE_HANDLE event (void) const; - - /// This really make sense only when doing file I/O. - u_long offset (void) const; - - /// Offset_high associated with the OVERLAPPED structure. - u_long offset_high (void) const; - - /// The priority of the asynchronous operation. Currently, this is - /// not supported on Win32. - int priority (void) const; - - /// No-op. Returns 0. - int signal_number (void) const; - - /// Post this object to the Proactor's completion port. - int post_completion (ACE_Proactor_Impl *proactor); - -protected: - /// Constructor is protected since creation is limited to - /// ACE_Asynch_Connect factory. - ACE_WIN32_Asynch_Connect_Result (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE connect_handle, - const void* act, - ACE_HANDLE event, - int priority, - int signal_number); - - /// ACE_Proactor will call this method when the accept completes. - virtual void complete (size_t bytes_transferred, - int success, - const void *completion_key, - u_long error); - - /// Destructor. - virtual ~ACE_WIN32_Asynch_Connect_Result (void); - - /// Set the I/O handle for the new connection. - void connect_handle (ACE_HANDLE handle); - - ACE_HANDLE connect_handle_; -}; - - -/** - * @class ACE_WIN32_Asynch_Connect - */ -class ACE_Export ACE_WIN32_Asynch_Connect : - public virtual ACE_Asynch_Connect_Impl, - public ACE_WIN32_Asynch_Operation, - public ACE_Event_Handler -{ -public: - - /// Constructor. - ACE_WIN32_Asynch_Connect (ACE_WIN32_Proactor * win32_proactor); - - /// Destructor. - virtual ~ACE_WIN32_Asynch_Connect (void); - - /** - * This open belongs to ACE_WIN32_Asynch_Operation. We forward - * this call to that method. We have put this here to avoid the - * compiler warnings. - */ - int open (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor = 0); - - /** - * Start an asynchronous connect. - * - * @param connect_handle Handle to use for the connect. If the value - * ACE_INVALID_HANDLE, a new handle will be created. - * - * @retval 0 Success - * @retval -1 Error - */ - int connect (ACE_HANDLE connect_handle, - const ACE_Addr &remote_sap, - const ACE_Addr &local_sap, - int reuse_addr, - const void *act, - int priority, - int signal_number = 0); - - /** - * Cancel all pending pseudo-asynchronus requests - * Behavior as usual AIO request - */ - int cancel (void); - - /** - * Close performs cancellation of all pending requests - * and close the connect handle - */ - int close (void); - - /// Virtual from ACE_Event_Handler - ACE_HANDLE get_handle (void) const; - - /// Virtual from ACE_Event_Handler - void set_handle (ACE_HANDLE handle); - - /// Virtual from ACE_Event_Handler - int handle_input ( ACE_HANDLE handle); - int handle_output ( ACE_HANDLE handle); - int handle_exception ( ACE_HANDLE handle); - - /// Virtual from ACE_Event_Handler - int handle_close (ACE_HANDLE handle, ACE_Reactor_Mask close_mask) ; - - // = Methods belong to ACE_WIN32_Asynch_Operation base class. These - // methods are defined here to avoid dominace warnings. They route - // the call to the ACE_WIN32_Asynch_Operation base class. - /// Return the underlying proactor. - ACE_Proactor* proactor (void) const; - -private: - int connect_i (ACE_WIN32_Asynch_Connect_Result *result, - const ACE_Addr &remote_sap, - const ACE_Addr &local_sap, - int reuse_addr); - - int post_result (ACE_WIN32_Asynch_Connect_Result *result, bool flg_post); - - /// Cancel uncompleted connect operations. - /** - * @param flg_notify Indicates whether or not to send notification about - * canceled connect operations. If false, don't send - * notifications. If true, notify user about canceled - * connects. - * According WIN32 standards we should receive - * notifications on canceled AIO requests. - * - * @param set Receives the set of I/O handles on which asynchronous - * connect requests were canceled as a result of this - * method. The contents of @a set are completely - * replaced. - */ - int cancel_uncompleted (bool flg_notify, ACE_Handle_Set &set); - - /// true - Connect is registered in ACE_Asynch_Pseudo_Task - /// false - Accept is deregisted in ACE_Asynch_Pseudo_Task - bool flg_open_ ; - - typedef ACE_Map_Manager - MAP_MANAGER; - - /// Map of Result pointers that correspond to all the 's - /// pending. - MAP_MANAGER result_map_; - - /// The lock to protect the result map which is shared. The queue - /// is updated by main thread in the register function call and - /// through the auxillary thread in the asynch pseudo task. - ACE_SYNCH_MUTEX lock_; -}; - -/** - * @class ACE_WIN32_Asynch_Transmit_File_Result - * - * - * @brief This class implements ACE_Asynch_Transmit_File::Result for - * WIN32 platforms. - * - * This class has all the information necessary for the - * @a handler to uniquiely identify the completion of the - * asynchronous transmit file. - */ -class ACE_Export ACE_WIN32_Asynch_Transmit_File_Result : public virtual ACE_Asynch_Transmit_File_Result_Impl, - public ACE_WIN32_Asynch_Result -{ - /// Factory class will have special permission. - friend class ACE_WIN32_Asynch_Transmit_File; - - /// Proactor class has special permission. - friend class ACE_WIN32_Proactor; - -public: - /// Socket used for transmitting the file. - ACE_HANDLE socket (void) const; - - /// File from which the data is read. - ACE_HANDLE file (void) const; - - /// Header and trailer data associated with this transmit file. - ACE_Asynch_Transmit_File::Header_And_Trailer *header_and_trailer (void) const; - - /// The number of bytes which were requested at the start of the - /// asynchronous transmit file. - size_t bytes_to_write (void) const; - - /// Number of bytes per send requested at the start of the transmit - /// file. - size_t bytes_per_send (void) const; - - /// Flags which were passed into transmit file. - u_long flags (void) const; - - // Base class operations. These operations are here to kill some - // warnings. These methods call the base class methods. - - /// Number of bytes transferred by the operation. - size_t bytes_transferred (void) const; - - /// ACT associated with the operation. - const void *act (void) const; - - /// Did the operation succeed? - int success (void) const; - - /** - * This returns the ACT associated with the handle when it was - * registered with the I/O completion port. This ACT is not the - * same as the ACT associated with the asynchronous operation. - */ - const void *completion_key (void) const; - - /// Error value if the operation fail. - u_long error (void) const; - - /// Event associated with the OVERLAPPED structure. - ACE_HANDLE event (void) const; - - /// This really make sense only when doing file I/O. - u_long offset (void) const; - - /// Offset_high associated with the OVERLAPPED structure. - u_long offset_high (void) const; - - /// The priority of the asynchronous operation. Currently, this is - /// not supported on Win32. - int priority (void) const; - - /// No-op. Returns 0. - int signal_number (void) const; - - /// Post @c this to the Proactor's completion port. - int post_completion (ACE_Proactor_Impl *proactor); - -protected: - /// Constructor is protected since creation is limited to - /// ACE_Asynch_Transmit_File factory. - ACE_WIN32_Asynch_Transmit_File_Result (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE socket, - ACE_HANDLE file, - ACE_Asynch_Transmit_File::Header_And_Trailer *header_and_trailer, - size_t bytes_to_write, - u_long offset, - u_long offset_high, - size_t bytes_per_send, - u_long flags, - const void *act, - ACE_HANDLE event, - int priority, - int signal_number = 0); - - /// Proactor will call this method when the write completes. - virtual void complete (size_t bytes_transferred, - int success, - const void *completion_key, - u_long error); - - /// Destructor. - virtual ~ACE_WIN32_Asynch_Transmit_File_Result (void); - - /// Network I/O handle. - ACE_HANDLE socket_; - - /// File I/O handle. - ACE_HANDLE file_; - - /// Header and trailer data associated with this transmit file. - ACE_Asynch_Transmit_File::Header_And_Trailer *header_and_trailer_; - - /// The number of bytes which were requested at the start of the - /// asynchronous transmit file. - size_t bytes_to_write_; - - /// Number of bytes per send requested at the start of the transmit - /// file. - size_t bytes_per_send_; - - /// Flags which were passed into transmit file. - u_long flags_; -}; - -/** - * @class ACE_WIN32_Asynch_Transmit_File - * - * @brief This class is a factory for starting off asynchronous - * transmit files on a stream. - * - * Once is called, multiple asynchronous s - * can started using this class. A - * ACE_Asynch_Transmit_File::Result will be passed back to the - * @a handler when the asynchronous transmit file completes - * through the callback. - * - * The transmit_file function transmits file data over a - * connected network connection. The function uses the operating - * system's cache manager to retrieve the file data. This - * function provides high-performance file data transfer over - * network connections. This function would be of great use in - * a Web Server, Image Server, etc. - */ -class ACE_Export ACE_WIN32_Asynch_Transmit_File : public virtual ACE_Asynch_Transmit_File_Impl, - public ACE_WIN32_Asynch_Operation -{ -public: - /// Constructor. - ACE_WIN32_Asynch_Transmit_File (ACE_WIN32_Proactor *win32_proactor); - - /** - * This starts off an asynchronous transmit file. The is a - * handle to an open file. is a pointer to a - * data structure that contains pointers to data to send before and - * after the file data is sent. Set this parameter to 0 if you only - * want to transmit the file data. Upto @a bytes_to_write will be - * written to the . If you want to send the entire file, - * let @a bytes_to_write = 0. @a bytes_per_send is the size of each - * block of data sent per send operation. Please read the Win32 - * documentation on what the flags should be. - */ - int transmit_file (ACE_HANDLE file, - ACE_Asynch_Transmit_File::Header_And_Trailer *header_and_trailer, - size_t bytes_to_write, - u_long offset, - u_long offset_high, - size_t bytes_per_send, - u_long flags, - const void *act, - int priority, - int signal_number = 0); - - /// Destructor. - ~ACE_WIN32_Asynch_Transmit_File (void); - - // Methods belong to ACE_WIN32_Asynch_Operation base class. These - // methods are defined here to avoid VC++ warnings. They route the - // call to the ACE_WIN32_Asynch_Operation base class. - - /** - * Initializes the factory with information which will be used with - * each asynchronous call. If ( == ACE_INVALID_HANDLE), - * will be called on the @a handler to get the - * correct handle. - */ - int open (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor); - - /** - * This cancels all pending accepts operations that were issued by - * the calling thread. The function does not cancel asynchronous - * operations issued by other threads. - */ - int cancel (void); - - /// Return the underlying proactor. - ACE_Proactor* proactor (void) const; -}; - -/** - * @class ACE_WIN32_Asynch_Read_Dgram_Result - * - * @brief This class provides concrete implementation for - * ACE_Asynch_Read_Dgram::Result class. - */ -class ACE_Export ACE_WIN32_Asynch_Read_Dgram_Result : public virtual ACE_Asynch_Read_Dgram_Result_Impl, - public ACE_WIN32_Asynch_Result -{ - /// Factory class will have special permissions. - friend class ACE_WIN32_Asynch_Read_Dgram; - - /// Proactor class has special permission. - friend class ACE_WIN32_Proactor; - -public: - /// The number of bytes which were requested at the start of the - /// asynchronous read. - size_t bytes_to_read (void) const; - - /// Message block which contains the read data - ACE_Message_Block *message_block (void) const; - - /// The address of where the packet came from - int remote_address (ACE_Addr& addr) const; - - sockaddr *saddr () const; - - /// The flags used in the read - int flags (void) const; - - /// I/O handle used for reading. - ACE_HANDLE handle (void) const; - - // Base class operations. These operations are here to kill - // dominance warnings. These methods call the base class methods. - - /// Number of bytes transferred by the operation. - size_t bytes_transferred (void) const; - - /// ACT associated with the operation. - const void *act (void) const; - - /// Did the operation succeed? - int success (void) const; - - /** - * This returns the ACT associated with the handle when it was - * registered with the I/O completion port. This ACT is not the - * same as the ACT associated with the asynchronous operation. - */ - const void *completion_key (void) const; - - /// Error value if the operation fail. - u_long error (void) const; - - /// Event associated with the OVERLAPPED structure. - ACE_HANDLE event (void) const; - - /// This really make sense only when doing file I/O. - u_long offset (void) const; - - /// Offset_high associated with the OVERLAPPED structure. - u_long offset_high (void) const; - - /// The priority of the asynchronous operation. Currently, this is - /// not supported on Win32. - int priority (void) const; - - /// No-op. Returns 0. - int signal_number (void) const; - - /// Post @c this to the Proactor's completion port. - int post_completion (ACE_Proactor_Impl *proactor); - -protected: - /// Constructor is protected since creation is limited to - /// ACE_Asynch_Read_Dgram factory. - ACE_WIN32_Asynch_Read_Dgram_Result (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - ACE_Message_Block *message_block, - size_t bytes_to_read, - int flags, - int protocol_family, - const void* act, - ACE_HANDLE event, - int priority, - int signal_number = 0); - - /// Proactor will call this method when the read completes. - virtual void complete (size_t bytes_transferred, - int success, - const void *completion_key, - u_long error); - - /// Destructor. - virtual ~ACE_WIN32_Asynch_Read_Dgram_Result (void); - - /// Bytes requested when the asynchronous read was initiated. - size_t bytes_to_read_; - - /// Message block for reading the data into. - ACE_Message_Block *message_block_; - - /// The address of where the packet came from - ACE_Addr *remote_address_; - - int addr_len_; - - /// The flags used in the read - int flags_; - - /// I/O handle used for reading. - ACE_HANDLE handle_; -}; - -/** - * @class ACE_WIN32_Asynch_Read_Dgram - * - * @brief This class is a factory for starting off asynchronous reads - * on a UDP socket. - * - * Once is called, multiple asynchronous s can be - * started using this class. An ACE_Asynch_Read_Dgram::Result - * will be passed back to the @a handler when the asynchronous - * reads completes through the - * callback. - * - */ -class ACE_Export ACE_WIN32_Asynch_Read_Dgram : public virtual ACE_Asynch_Read_Dgram_Impl, - public ACE_WIN32_Asynch_Operation -{ -public: - /// Constructor. - ACE_WIN32_Asynch_Read_Dgram (ACE_WIN32_Proactor *win32_proactor); - - /// Destructor. - virtual ~ACE_WIN32_Asynch_Read_Dgram (void); - - /** This starts off an asynchronous read. Upto - * total_size()> will be read and stored in the - * @a message_block. @a message_block's will be updated to reflect - * the added bytes if the read operation is successfully completed. - * Return code of 1 means immediate success and - * will contain number of bytes read. The - * method will still be called. Return code of 0 means the IO will - * complete proactively. Return code of -1 means there was an error, use - * errno to get the error code. - * - * Scatter/gather is supported on WIN32 by using the cont()> - * method. Up to ACE_IOV_MAX @a message_block's are supported. Upto - * size()> bytes will be read into each for - * a total of total_size()> bytes. All @a message_block's - * 's will be updated to reflect the added bytes for each - * @a message_block - */ - virtual ssize_t recv (ACE_Message_Block *message_block, - size_t &number_of_bytes_recvd, - int flags, - int protocol_family, - const void *act, - int priority, - int signal_number); - - // Methods belong to ACE_WIN32_Asynch_Operation base class. These - // methods are defined here to avoid VC++ warnings. They route the - // call to the ACE_WIN32_Asynch_Operation base class. - - /** - * Initializes the factory with information which will be used with - * each asynchronous call. If ( == ACE_INVALID_HANDLE), - * will be called on the @a handler to get the - * correct handle. - */ - int open (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor); - - /** - * This cancels all pending accepts operations that were issued by - * the calling thread. The function does not cancel asynchronous - * operations issued by other threads. - */ - int cancel (void); - - /// Return the underlying proactor. - ACE_Proactor* proactor (void) const; - -protected: - /// Do-nothing constructor. - ACE_WIN32_Asynch_Read_Dgram (void); -}; - -/** - * @class ACE_WIN32_Asynch_Write_Dgram_Result - * - * @brief This class provides concrete implementation for - * ACE_Asynch_Write_Dgram::Result class. - */ -class ACE_Export ACE_WIN32_Asynch_Write_Dgram_Result : public virtual ACE_Asynch_Write_Dgram_Result_Impl, - public ACE_WIN32_Asynch_Result -{ - /// Factory class willl have special permissions. - friend class ACE_WIN32_Asynch_Write_Dgram; - - /// Proactor class has special permission. - friend class ACE_WIN32_Proactor; - -public: - /// The number of bytes which were requested at the start of the - /// asynchronous write. - size_t bytes_to_write (void) const; - - /// Message block which contains the sent data - ACE_Message_Block *message_block (void) const; - - /// The flags using in the write - int flags (void) const; - - /// I/O handle used for writing. - ACE_HANDLE handle (void) const; - - // = Base class operations. These operations are here to kill some - // warnings. These methods call the base class methods. - - /// Number of bytes transferred by the operation. - size_t bytes_transferred (void) const; - - /// ACT associated with the operation. - const void *act (void) const; - - /// Did the operation succeed? - int success (void) const; - - /** - * This returns the ACT associated with the handle when it was - * registered with the I/O completion port. This ACT is not the - * same as the ACT associated with the asynchronous operation. - */ - const void *completion_key (void) const; - - /// Error value if the operation fail. - u_long error (void) const; - - /// Event associated with the OVERLAPPED structure. - ACE_HANDLE event (void) const; - - /// This really make sense only when doing file I/O. - u_long offset (void) const; - - /// Offset_high associated with the OVERLAPPED structure. - u_long offset_high (void) const; - - /// The priority of the asynchronous operation. Currently, this is - /// not supported on Win32. - int priority (void) const; - - /// No-op. Returns 0. - int signal_number (void) const; - - /// Post @c this to the Proactor's completion port. - int post_completion (ACE_Proactor_Impl *proactor); - -protected: - /// Constructor is protected since creation is limited to - /// ACE_Asynch_Write_Stream factory. - ACE_WIN32_Asynch_Write_Dgram_Result (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - ACE_Message_Block *message_block, - size_t bytes_to_write, - int flags, - const void* act, - ACE_HANDLE event, - int priority, - int signal_number = 0); - - /// ACE_Proactor will call this method when the write completes. - virtual void complete (size_t bytes_transferred, - int success, - const void *completion_key, - u_long error); - - /// Destructor. - virtual ~ACE_WIN32_Asynch_Write_Dgram_Result (void); - - /// The number of bytes which were requested at the start of the - /// asynchronous write. - size_t bytes_to_write_; - - /// Message block used for the send. - ACE_Message_Block *message_block_; - - /// The flags using in the write - int flags_; - - /// I/O handle used for writing. - ACE_HANDLE handle_; -}; - -/** - * @class ACE_WIN32_Asynch_Write_Dgram - * - * @brief This class is a factory for starting off asynchronous writes - * on a UDP socket. - * - * - * Once is called, multiple asynchronous s can - * started using this class. A ACE_Asynch_Write_Stream::Result - * will be passed back to the @a handler when the asynchronous - * write completes through the - * callback. - */ -class ACE_Export ACE_WIN32_Asynch_Write_Dgram : public virtual ACE_Asynch_Write_Dgram_Impl, - public ACE_WIN32_Asynch_Operation -{ -public: - /// Constructor. - ACE_WIN32_Asynch_Write_Dgram (ACE_WIN32_Proactor *win32_proactor); - - /// Destructor. - virtual ~ACE_WIN32_Asynch_Write_Dgram (void); - - /** This starts off an asynchronous send. Upto - * total_length()> will be sent. @a message_block's - * will be updated to reflect the sent bytes if the send operation - * is successfully completed. - * Return code of 1 means immediate success and - * is updated to number of bytes sent. The - * method will still be called. Return code of 0 means the IO will - * complete proactively. Return code of -1 means there was an error, use - * errno to get the error code. - * - * Scatter/gather is supported on WIN32 by using the cont()> - * method. Up to ACE_IOV_MAX @a message_block's are supported. Upto - * length()> bytes will be sent from each - * for a total of total_length()> bytes. All - * @a message_block's 's will be updated to reflect the bytes sent - * from each @a message_block. - */ - virtual ssize_t send (ACE_Message_Block *message_block, - size_t &number_of_bytes_sent, - int flags, - const ACE_Addr &addr, - const void *act, - int priority, - int signal_number); - - // = Methods belonging to base class. - - // These methods are defined here to avoid VC++ warnings. They route - // the call to the base class. - - /** - * Initializes the factory with information which will be used with - * each asynchronous call. If ( == ACE_INVALID_HANDLE), - * will be called on the @a handler to get the - * correct handle. - */ - int open (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - const void *completion_key, - ACE_Proactor *proactor); - - /** - * This cancels all pending accepts operations that were issued by - * the calling thread. The function does not cancel asynchronous - * operations issued by other threads. - */ - int cancel (void); - - /// Return the underlying proactor. - ACE_Proactor* proactor (void) const; - -protected: - /// Do-nothing constructor. - ACE_WIN32_Asynch_Write_Dgram (void); -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_WIN32_OVERLAPPED_IO && ACE_HAS_WINSOCK2 */ -#include /**/ "ace/post.h" -#endif /* ACE_WIN32_ASYNCH_IO_H */ diff --git a/externals/ace/WIN32_Proactor.cpp b/externals/ace/WIN32_Proactor.cpp deleted file mode 100644 index a559838976f..00000000000 --- a/externals/ace/WIN32_Proactor.cpp +++ /dev/null @@ -1,804 +0,0 @@ -// $Id: WIN32_Proactor.cpp 80826 2008-03-04 14:51:23Z wotte $ - -// ACE_RCSID(ace, Proactor, "$Id: WIN32_Proactor.cpp 80826 2008-03-04 14:51:23Z wotte $") - -#include "ace/WIN32_Proactor.h" - -#if defined (ACE_WIN32) && defined (ACE_HAS_WIN32_OVERLAPPED_IO) -// WIN implemenatation of the Proactor. - -#include "ace/Log_Msg.h" -#include "ace/Object_Manager.h" -#include "ace/OS_NS_errno.h" -#include "ace/OS_NS_unistd.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_WIN32_Wakeup_Completion - * - * This is result object is used by the of the - * ACE_Proactor interface to wake up all the threads blocking - * for completions. - */ -class ACE_WIN32_Wakeup_Completion : public ACE_WIN32_Asynch_Result -{ - -public: - /// Constructor. - ACE_WIN32_Wakeup_Completion (ACE_Handler::Proxy_Ptr &handler_proxy, - const void *act = 0, - ACE_HANDLE event = ACE_INVALID_HANDLE, - int priority = 0, - int signal_number = ACE_SIGRTMIN); - - /// Destructor. - virtual ~ACE_WIN32_Wakeup_Completion (void); - - /// This method calls the 's method. - virtual void complete (size_t bytes_transferred = 0, - int success = 1, - const void *completion_key = 0, - u_long error = 0); -}; - -ACE_WIN32_Proactor::ACE_WIN32_Proactor (size_t number_of_threads, - bool used_with_reactor_event_loop) - : completion_port_ (0), - // This *MUST* be 0, *NOT* ACE_INVALID_HANDLE !!! - number_of_threads_ (static_cast (number_of_threads)), - used_with_reactor_event_loop_ (used_with_reactor_event_loop) -{ - // Create the completion port. - this->completion_port_ = ::CreateIoCompletionPort (INVALID_HANDLE_VALUE, - 0, - 0, - this->number_of_threads_); - if (this->completion_port_ == 0) - ACE_ERROR ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("CreateIoCompletionPort"))); - - this->get_asynch_pseudo_task ().start (); -} - -ACE_WIN32_Proactor::~ACE_WIN32_Proactor (void) -{ - this->get_asynch_pseudo_task ().stop (); - - this->close (); -} - -ACE_Asynch_Pseudo_Task & -ACE_WIN32_Proactor::get_asynch_pseudo_task () -{ - return this->pseudo_task_; -} - -int -ACE_WIN32_Proactor::close (void) -{ - // Close the completion port - if (this->completion_port_ != 0) - { - // To avoid memory leaks we should delete all results from queue. - - for (;;) - { - ACE_OVERLAPPED *overlapped = 0; - u_long bytes_transferred = 0; - ULONG_PTR completion_key = 0; - - // Get the next asynchronous operation that completes - BOOL res = ::GetQueuedCompletionStatus - (this->completion_port_, - &bytes_transferred, - &completion_key, - &overlapped, - 0); // poll - - if (overlapped == 0 || res == FALSE) - break; - - ACE_WIN32_Asynch_Result *asynch_result = - (ACE_WIN32_Asynch_Result *) overlapped; - - delete asynch_result; - } - - int result = ACE_OS::close (this->completion_port_); - this->completion_port_ = 0; - return result; - } - - return 0; -} - -int -ACE_WIN32_Proactor::register_handle (ACE_HANDLE handle, - const void *completion_key) -{ - ULONG_PTR comp_key (reinterpret_cast (completion_key)); - - // No locking is needed here as no state changes. - ACE_HANDLE cp = ::CreateIoCompletionPort (handle, - this->completion_port_, - comp_key, - this->number_of_threads_); - if (cp == 0) - { - ACE_OS::set_errno_to_last_error (); - // If errno == ERROR_INVALID_PARAMETER, then this handle was - // already registered. - if (errno != ERROR_INVALID_PARAMETER) - { - if (ACE::debug ()) - { - ACE_DEBUG ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("CreateIoCompletionPort"))); - } - return -1; - } - } - return 0; -} - -ACE_Asynch_Read_Stream_Impl * -ACE_WIN32_Proactor::create_asynch_read_stream (void) -{ - ACE_Asynch_Read_Stream_Impl *implementation = 0; - ACE_NEW_RETURN (implementation, - ACE_WIN32_Asynch_Read_Stream (this), - 0); - return implementation; -} - -ACE_Asynch_Write_Stream_Impl * -ACE_WIN32_Proactor::create_asynch_write_stream (void) -{ - ACE_Asynch_Write_Stream_Impl *implementation = 0; - ACE_NEW_RETURN (implementation, - ACE_WIN32_Asynch_Write_Stream (this), - 0); - return implementation; -} - -ACE_Asynch_Read_Dgram_Impl * -ACE_WIN32_Proactor::create_asynch_read_dgram (void) -{ - ACE_Asynch_Read_Dgram_Impl *implementation = 0; - ACE_NEW_RETURN (implementation, - ACE_WIN32_Asynch_Read_Dgram (this), - 0); - return implementation; -} - -ACE_Asynch_Write_Dgram_Impl * -ACE_WIN32_Proactor::create_asynch_write_dgram (void) -{ - ACE_Asynch_Write_Dgram_Impl *implementation = 0; - ACE_NEW_RETURN (implementation, - ACE_WIN32_Asynch_Write_Dgram (this), - 0); - return implementation; -} - -ACE_Asynch_Read_File_Impl * -ACE_WIN32_Proactor::create_asynch_read_file (void) -{ - ACE_Asynch_Read_File_Impl *implementation = 0; - ACE_NEW_RETURN (implementation, - ACE_WIN32_Asynch_Read_File (this), - 0); - return implementation; -} - -ACE_Asynch_Write_File_Impl * -ACE_WIN32_Proactor::create_asynch_write_file (void) -{ - ACE_Asynch_Write_File_Impl *implementation = 0; - ACE_NEW_RETURN (implementation, - ACE_WIN32_Asynch_Write_File (this), - 0); - return implementation; -} - -ACE_Asynch_Accept_Impl * -ACE_WIN32_Proactor::create_asynch_accept (void) -{ - ACE_Asynch_Accept_Impl *implementation = 0; - ACE_NEW_RETURN (implementation, - ACE_WIN32_Asynch_Accept (this), - 0); - return implementation; -} - -ACE_Asynch_Connect_Impl * -ACE_WIN32_Proactor::create_asynch_connect (void) -{ - ACE_Asynch_Connect_Impl *implementation = 0; - ACE_NEW_RETURN (implementation, - ACE_WIN32_Asynch_Connect (this), - 0); - return implementation; -} - -ACE_Asynch_Transmit_File_Impl * -ACE_WIN32_Proactor::create_asynch_transmit_file (void) -{ - ACE_Asynch_Transmit_File_Impl *implementation = 0; - ACE_NEW_RETURN (implementation, - ACE_WIN32_Asynch_Transmit_File (this), - 0); - return implementation; -} - -ACE_Asynch_Read_Stream_Result_Impl * -ACE_WIN32_Proactor::create_asynch_read_stream_result - (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - ACE_Message_Block &message_block, - size_t bytes_to_read, - const void* act, - ACE_HANDLE event, - int priority, - int signal_number) -{ - ACE_Asynch_Read_Stream_Result_Impl *implementation = 0; - ACE_NEW_RETURN (implementation, - ACE_WIN32_Asynch_Read_Stream_Result (handler_proxy, - handle, - message_block, - bytes_to_read, - act, - event, - priority, - signal_number), - 0); - return implementation; -} - -ACE_Asynch_Write_Stream_Result_Impl * -ACE_WIN32_Proactor::create_asynch_write_stream_result - (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - ACE_Message_Block &message_block, - size_t bytes_to_write, - const void* act, - ACE_HANDLE event, - int priority, - int signal_number) -{ - ACE_Asynch_Write_Stream_Result_Impl *implementation = 0; - ACE_NEW_RETURN (implementation, - ACE_WIN32_Asynch_Write_Stream_Result (handler_proxy, - handle, - message_block, - bytes_to_write, - act, - event, - priority, - signal_number), - 0); - return implementation; -} - -ACE_Asynch_Read_File_Result_Impl * -ACE_WIN32_Proactor::create_asynch_read_file_result - (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - ACE_Message_Block &message_block, - size_t bytes_to_read, - const void* act, - u_long offset, - u_long offset_high, - ACE_HANDLE event, - int priority, - int signal_number) -{ - ACE_Asynch_Read_File_Result_Impl *implementation = 0; - ACE_NEW_RETURN (implementation, - ACE_WIN32_Asynch_Read_File_Result (handler_proxy, - handle, - message_block, - bytes_to_read, - act, - offset, - offset_high, - event, - priority, - signal_number), - 0); - return implementation; -} - -ACE_Asynch_Write_File_Result_Impl * -ACE_WIN32_Proactor::create_asynch_write_file_result - (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - ACE_Message_Block &message_block, - size_t bytes_to_write, - const void* act, - u_long offset, - u_long offset_high, - ACE_HANDLE event, - int priority, - int signal_number) -{ - ACE_Asynch_Write_File_Result_Impl *implementation = 0; - ACE_NEW_RETURN (implementation, - ACE_WIN32_Asynch_Write_File_Result (handler_proxy, - handle, - message_block, - bytes_to_write, - act, - offset, - offset_high, - event, - priority, - signal_number), - 0); - return implementation; -} - -ACE_Asynch_Read_Dgram_Result_Impl * -ACE_WIN32_Proactor::create_asynch_read_dgram_result - (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - ACE_Message_Block *message_block, - size_t bytes_to_read, - int flags, - int protocol_family, - const void* act, - ACE_HANDLE event, - int priority, - int signal_number) -{ - ACE_Asynch_Read_Dgram_Result_Impl *implementation = 0; - ACE_NEW_RETURN (implementation, - ACE_WIN32_Asynch_Read_Dgram_Result (handler_proxy, - handle, - message_block, - bytes_to_read, - flags, - protocol_family, - act, - event, - priority, - signal_number), - 0); - return implementation; -} - -ACE_Asynch_Write_Dgram_Result_Impl * -ACE_WIN32_Proactor::create_asynch_write_dgram_result - (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - ACE_Message_Block *message_block, - size_t bytes_to_read, - int flags, - const void* act, - ACE_HANDLE event, - int priority, - int signal_number) -{ - ACE_Asynch_Write_Dgram_Result_Impl *implementation = 0; - ACE_NEW_RETURN (implementation, - ACE_WIN32_Asynch_Write_Dgram_Result(handler_proxy, - handle, - message_block, - bytes_to_read, - flags, - act, - event, - priority, - signal_number), - 0); - return implementation; -} - -ACE_Asynch_Accept_Result_Impl * -ACE_WIN32_Proactor::create_asynch_accept_result - (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE listen_handle, - ACE_HANDLE accept_handle, - ACE_Message_Block &message_block, - size_t bytes_to_read, - const void* act, - ACE_HANDLE event, - int priority, - int signal_number) -{ - ACE_Asynch_Accept_Result_Impl *implementation = 0; - ACE_NEW_RETURN (implementation, - ACE_WIN32_Asynch_Accept_Result (handler_proxy, - listen_handle, - accept_handle, - message_block, - bytes_to_read, - act, - event, - priority, - signal_number), - 0); - return implementation; -} - -ACE_Asynch_Connect_Result_Impl * -ACE_WIN32_Proactor::create_asynch_connect_result - (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE connect_handle, - const void *act, - ACE_HANDLE event, - int priority, - int signal_number) -{ - ACE_Asynch_Connect_Result_Impl *implementation = 0; - ACE_NEW_RETURN (implementation, - ACE_WIN32_Asynch_Connect_Result (handler_proxy, - connect_handle, - act, - event, - priority, - signal_number), - 0); - return implementation; -} - -ACE_Asynch_Transmit_File_Result_Impl * -ACE_WIN32_Proactor::create_asynch_transmit_file_result - (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE socket, - ACE_HANDLE file, - ACE_Asynch_Transmit_File::Header_And_Trailer *header_and_trailer, - size_t bytes_to_write, - u_long offset, - u_long offset_high, - size_t bytes_per_send, - u_long flags, - const void *act, - ACE_HANDLE event, - int priority, - int signal_number) -{ - ACE_Asynch_Transmit_File_Result_Impl *implementation = 0; - ACE_NEW_RETURN (implementation, - ACE_WIN32_Asynch_Transmit_File_Result (handler_proxy, - socket, - file, - header_and_trailer, - bytes_to_write, - offset, - offset_high, - bytes_per_send, - flags, - act, - event, - priority, - signal_number), - 0); - return implementation; -} - -ACE_Asynch_Result_Impl * -ACE_WIN32_Proactor::create_asynch_timer (const ACE_Handler::Proxy_Ptr &handler_proxy, - const void *act, - const ACE_Time_Value &tv, - ACE_HANDLE event, - int priority, - int signal_number) -{ - ACE_Asynch_Result_Impl *implementation = 0; - ACE_NEW_RETURN (implementation, - ACE_WIN32_Asynch_Timer (handler_proxy, - act, - tv, - event, - priority, - signal_number), - 0); - return implementation; -} - -int -ACE_WIN32_Proactor::handle_signal (int, siginfo_t *, ucontext_t *) -{ - // Perform a non-blocking "poll" for all the I/O events that have - // completed in the I/O completion queue. - - int result = 0; - - for (ACE_Time_Value timeout (0, 0); - ; - ) - { - result = this->handle_events (timeout); - - if (result != 1) - break; - } - - // If our handle_events failed, we'll report a failure to the - // Reactor. - return result == -1 ? -1 : 0; -} - -int -ACE_WIN32_Proactor::handle_close (ACE_HANDLE handle, - ACE_Reactor_Mask close_mask) -{ - ACE_UNUSED_ARG (close_mask); - ACE_UNUSED_ARG (handle); - - return this->close (); -} - -ACE_HANDLE -ACE_WIN32_Proactor::get_handle (void) const -{ - if (this->used_with_reactor_event_loop_) - return this->event_.handle (); - else - return 0; -} - -int -ACE_WIN32_Proactor::handle_events (ACE_Time_Value &wait_time) -{ - // Decrement with the amount of time spent in the method - ACE_Countdown_Time countdown (&wait_time); - return this->handle_events (wait_time.msec ()); -} - -int -ACE_WIN32_Proactor::handle_events (void) -{ - return this->handle_events (ACE_INFINITE); -} - -int -ACE_WIN32_Proactor::handle_events (unsigned long milli_seconds) -{ - ACE_OVERLAPPED *overlapped = 0; - u_long bytes_transferred = 0; - ULONG_PTR completion_key = 0; - - // Get the next asynchronous operation that completes - BOOL result = ::GetQueuedCompletionStatus (this->completion_port_, - &bytes_transferred, - &completion_key, - &overlapped, - milli_seconds); - if (result == FALSE && overlapped == 0) - { - ACE_OS::set_errno_to_last_error (); - - switch (errno) - { - case WAIT_TIMEOUT: - errno = ETIME; - return 0; - - case ERROR_SUCCESS: - // Calling GetQueuedCompletionStatus with timeout value 0 - // returns FALSE with extended errno "ERROR_SUCCESS" errno = - // ETIME; ?? I don't know if this has to be done !! - return 0; - - default: - if (ACE::debug ()) - ACE_DEBUG ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("GetQueuedCompletionStatus"))); - return -1; - } - } - else if (overlapped != 0) - { - // Narrow the result. - ACE_WIN32_Asynch_Result *asynch_result = (ACE_WIN32_Asynch_Result *) overlapped; - - // If errors happen, grab the error. - if (result == FALSE) - ACE_OS::set_errno_to_last_error (); - else - errno = 0; - - u_long result_err = asynch_result->error (); - - // if "result_err" is 0 than - // It is normal OS/WIN32 AIO completion. - // We have cleared asynch_result->error_ - // during shared_read/shared_write. - // The real error code is already stored in "errno", - // so copy "errno" value to the "result_err" - // and pass this "result_err" code - // to the application_specific_code () - // else - // "result_err" non zero - // it means we have "post_completed" result - // so pass this "result_err" code - // to the application_specific_code () - - if (result_err == 0) - result_err = errno ; - - this->application_specific_code (asynch_result, - static_cast (bytes_transferred), - (void *) completion_key, - result_err); - } - return 1; -} - -void -ACE_WIN32_Proactor::application_specific_code (ACE_WIN32_Asynch_Result *asynch_result, - size_t bytes_transferred, - const void *completion_key, - u_long error) -{ - ACE_SEH_TRY - { - // Call completion hook - asynch_result->complete (bytes_transferred, - error ? 0 : 1, - (void *) completion_key, - error); - } - ACE_SEH_FINALLY - { - // This is crucial to prevent memory leaks - delete asynch_result; - } -} - -int -ACE_WIN32_Proactor::post_completion (ACE_WIN32_Asynch_Result *result) -{ - // Grab the event associated with the Proactor - HANDLE handle = this->get_handle (); - - // pass - // bytes_transferred - // completion_key - // to the ::PostQueuedCompletionStatus() - // error will be extracted later in handle_events() - - DWORD bytes_transferred = 0; - const void * completion_key = 0 ; - - if (result != 0) - { - // This cast is ok since the original API calls restricted the transfer - // counts to DWORD range. - bytes_transferred = static_cast (result->bytes_transferred ()); - completion_key = result->completion_key(); - } - - ULONG_PTR comp_key (reinterpret_cast (completion_key)); - - // Post a completion - if (::PostQueuedCompletionStatus (this->completion_port_, // completion port - bytes_transferred, // xfer count - comp_key, // completion key - result // overlapped - ) == FALSE) - { - delete result; - - if (ACE::debug ()) - { - ACE_DEBUG ((LM_ERROR, - ACE_TEXT ("%p\n"), - ACE_TEXT ("PostQueuedCompletionStatus failed"))); - } - return -1; - } - - // If Proactor event is valid, signal it - if (handle != ACE_INVALID_HANDLE - && handle != 0) - ACE_OS::event_signal (&handle); - - return 0; -} - -int -ACE_WIN32_Proactor::post_wakeup_completions (int how_many) -{ - ACE_WIN32_Wakeup_Completion *wakeup_completion = 0; - - for (ssize_t ci = 0; ci < how_many; ci++) - { - ACE_NEW_RETURN - (wakeup_completion, - ACE_WIN32_Wakeup_Completion (this->wakeup_handler_.proxy ()), - -1); - - if (wakeup_completion->post_completion (this) == -1) - return -1; - } - - return 0; -} - -int -ACE_WIN32_Proactor::wake_up_dispatch_threads (void) -{ - return 0; -} - -int -ACE_WIN32_Proactor::close_dispatch_threads (int) -{ - return 0; -} - -size_t -ACE_WIN32_Proactor::number_of_threads (void) const -{ - return static_cast (this->number_of_threads_); -} - -void -ACE_WIN32_Proactor::number_of_threads (size_t threads) -{ - this->number_of_threads_ = static_cast (threads); -} - -ACE_WIN32_Asynch_Timer::ACE_WIN32_Asynch_Timer - (const ACE_Handler::Proxy_Ptr &handler_proxy, - const void *act, - const ACE_Time_Value &tv, - ACE_HANDLE event, - int priority, - int signal_number) - : ACE_Asynch_Result_Impl (), - ACE_WIN32_Asynch_Result (handler_proxy, act, event, 0, 0, priority, - signal_number), - time_ (tv) -{ -} - -void -ACE_WIN32_Asynch_Timer::complete (size_t, - int, - const void *, - u_long) -{ - ACE_Handler *handler = this->handler_proxy_.get ()->handler (); - if (handler != 0) - handler->handle_time_out (this->time_, this->act ()); -} - -ACE_WIN32_Wakeup_Completion::ACE_WIN32_Wakeup_Completion - (ACE_Handler::Proxy_Ptr &handler_proxy, - const void *act, - ACE_HANDLE event, - int priority, - int signal_number) - : ACE_Asynch_Result_Impl (), - ACE_WIN32_Asynch_Result - (handler_proxy, act, event, 0, 0, priority, signal_number) -{ -} - -ACE_WIN32_Wakeup_Completion::~ACE_WIN32_Wakeup_Completion (void) -{ -} - -void -ACE_WIN32_Wakeup_Completion::complete (size_t /* bytes_transferred */, - int /* success */, - const void * /* completion_key */, - u_long /* error */) -{ - ACE_Handler *handler = this->handler_proxy_.get ()->handler (); - if (handler != 0) - handler->handle_wakeup (); -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_WIN32 */ diff --git a/externals/ace/WIN32_Proactor.h b/externals/ace/WIN32_Proactor.h deleted file mode 100644 index 4fb686d7a7e..00000000000 --- a/externals/ace/WIN32_Proactor.h +++ /dev/null @@ -1,325 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file WIN32_Proactor.h - * - * $Id: WIN32_Proactor.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Irfan Pyarali (irfan@cs.wustl.edu) - * @author Tim Harrison (harrison@cs.wustl.edu) - * @author Alexander Babu Arulanthu - * @author Roger Tragin - * @author Alexander Libman - */ -//============================================================================= - -#ifndef ACE_WIN32_PROACTOR_H -#define ACE_WIN32_PROACTOR_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -#pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_WIN32) && defined (ACE_HAS_WIN32_OVERLAPPED_IO) -// WIN32 implementation of the Proactor. - -#include "ace/WIN32_Asynch_IO.h" -#include "ace/Event_Handler.h" - -#include "ace/Proactor_Impl.h" -#include "ace/Asynch_Pseudo_Task.h" -#include "ace/Auto_Event.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Forward declarations. -class ACE_WIN32_Asynch_Result; -class ACE_WIN32_Proactor_Timer_Handler; - -/** - * @class ACE_WIN32_Proactor - * - * @brief A manager for asynchronous event demultiplexing on Win32. - * - * See the Proactor pattern description at - * http://www.cs.wustl.edu/~schmidt/PDF/proactor.pdf for more - * details. - */ -class ACE_Export ACE_WIN32_Proactor : public ACE_Proactor_Impl -{ - friend class ACE_WIN32_Asynch_Connect; - -public: - /// A do nothing constructor. - ACE_WIN32_Proactor (size_t number_of_threads = 0, - bool used_with_reactor_event_loop = false); - - /// Virtual destruction. - virtual ~ACE_WIN32_Proactor (void); - - /// Close the IO completion port. - virtual int close (void); - - /// This method adds the @a handle to the I/O completion port. This - /// function is a no-op function for Unix systems. - virtual int register_handle (ACE_HANDLE handle, - const void *completion_key); - - /** - * Dispatch a single set of events. If @a wait_time elapses before - * any events occur, return 0. Return 1 on success i.e., when a - * completion is dispatched, non-zero (-1) on errors and errno is - * set accordingly. - */ - virtual int handle_events (ACE_Time_Value &wait_time); - - /** - * Block indefinitely until at least one event is dispatched. - * Dispatch a single set of events. Return 1 on success i.e., when a - * completion is dispatched, non-zero (-1) on errors and errno is - * set accordingly. - */ - virtual int handle_events (void); - - /** - * Post a result to the completion port of the Proactor. If errors - * occur, the result will be deleted by this method. If successful, - * the result will be deleted by the Proactor when the result is - * removed from the completion port. Therefore, the result should - * have been dynamically allocated and should be orphaned by the - * user once this method is called. - */ - virtual int post_completion (ACE_WIN32_Asynch_Result *result); - - /// Add wakeup dispatch threads (reinit). - int wake_up_dispatch_threads (void); - - /// Close all dispatch threads. - int close_dispatch_threads (int wait); - - /// Get number of thread used as a parameter to @c CreateIoCompletionPort. - size_t number_of_threads (void) const; - - /// Set number of thread used as a parameter to @c CreateIoCompletionPort. - void number_of_threads (size_t threads); - - /// Get the event handle. - virtual ACE_HANDLE get_handle (void) const; - - virtual ACE_Asynch_Read_Stream_Impl *create_asynch_read_stream (void); - virtual ACE_Asynch_Write_Stream_Impl *create_asynch_write_stream (void); - virtual ACE_Asynch_Read_File_Impl *create_asynch_read_file (void); - virtual ACE_Asynch_Write_File_Impl *create_asynch_write_file (void); - virtual ACE_Asynch_Read_Dgram_Impl *create_asynch_read_dgram (void); - virtual ACE_Asynch_Write_Dgram_Impl *create_asynch_write_dgram (void); - virtual ACE_Asynch_Accept_Impl *create_asynch_accept (void); - virtual ACE_Asynch_Connect_Impl *create_asynch_connect (void); - virtual ACE_Asynch_Transmit_File_Impl *create_asynch_transmit_file (void); - - // Methods used to create Asynch_IO_Result objects. We create the right - // objects here in these methods. - - virtual ACE_Asynch_Read_Stream_Result_Impl *create_asynch_read_stream_result (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - ACE_Message_Block &message_block, - size_t bytes_to_read, - const void* act, - ACE_HANDLE event, - int priority, - int signal_number = 0); - - virtual ACE_Asynch_Write_Stream_Result_Impl *create_asynch_write_stream_result (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - ACE_Message_Block &message_block, - size_t bytes_to_write, - const void* act, - ACE_HANDLE event, - int priority, - int signal_number = 0); - - virtual ACE_Asynch_Read_File_Result_Impl *create_asynch_read_file_result (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - ACE_Message_Block &message_block, - size_t bytes_to_read, - const void* act, - u_long offset, - u_long offset_high, - ACE_HANDLE event, - int priority, - int signal_number = 0); - - virtual ACE_Asynch_Write_File_Result_Impl *create_asynch_write_file_result (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - ACE_Message_Block &message_block, - size_t bytes_to_write, - const void* act, - u_long offset, - u_long offset_high, - ACE_HANDLE event, - int priority, - int signal_number = 0); - - /// Create the correct implementation class for ACE_Asynch_Read_Dgram::Result. - virtual ACE_Asynch_Read_Dgram_Result_Impl *create_asynch_read_dgram_result (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - ACE_Message_Block *message_block, - size_t bytes_to_read, - int flags, - int protocol_family, - const void* act, - ACE_HANDLE event, - int priority, - int signal_number = 0); - - /// Create the correct implementation class for ACE_Asynch_Write_Dgram::Result. - virtual ACE_Asynch_Write_Dgram_Result_Impl *create_asynch_write_dgram_result (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE handle, - ACE_Message_Block *message_block, - size_t bytes_to_write, - int flags, - const void* act, - ACE_HANDLE event, - int priority, - int signal_number = 0); - - virtual ACE_Asynch_Accept_Result_Impl *create_asynch_accept_result (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE listen_handle, - ACE_HANDLE accept_handle, - ACE_Message_Block &message_block, - size_t bytes_to_read, - const void* act, - ACE_HANDLE event, - int priority, - int signal_number = 0); - - virtual ACE_Asynch_Connect_Result_Impl *create_asynch_connect_result (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE connect_handle, - const void *act, - ACE_HANDLE event, - int priority, - int signal_number = 0); - - - virtual ACE_Asynch_Transmit_File_Result_Impl *create_asynch_transmit_file_result (const ACE_Handler::Proxy_Ptr &handler_proxy, - ACE_HANDLE socket, - ACE_HANDLE file, - ACE_Asynch_Transmit_File::Header_And_Trailer *header_and_trailer, - size_t bytes_to_write, - u_long offset, - u_long offset_high, - size_t bytes_per_send, - u_long flags, - const void *act, - ACE_HANDLE event, - int priority, - int signal_number = 0); - - /// Create a timer result object which can be used with the Timer - /// mechanism of the Proactor. - virtual ACE_Asynch_Result_Impl *create_asynch_timer (const ACE_Handler::Proxy_Ptr &handler_proxy, - const void *act, - const ACE_Time_Value &tv, - ACE_HANDLE event, - int priority, - int signal_number = 0); - -protected: - /// Task to process pseudo-asynchronous operations - ACE_Asynch_Pseudo_Task & get_asynch_pseudo_task (void); - - /// Called when object is signaled by OS (either via UNIX signals or - /// when a Win32 object becomes signaled). - virtual int handle_signal (int signum, siginfo_t * = 0, ucontext_t * = 0); - - /// Called when object is removed from the ACE_Reactor. - virtual int handle_close (ACE_HANDLE handle, - ACE_Reactor_Mask close_mask); - - /** - * Dispatch a single set of events. If @a milli_seconds elapses - * before any events occur, return 0. Return 1 if a completion is - * dispatched. Return -1 on errors. - */ - virtual int handle_events (unsigned long milli_seconds); - - /// Protect against structured exceptions caused by user code when - /// dispatching handles. - void application_specific_code (ACE_WIN32_Asynch_Result *asynch_result, - size_t bytes_transferred, - const void *completion_key, - u_long error); - - /** - * Post @a how_many completions to the completion port so that all - * threads can wake up. This is used in conjunction with the - * run_event_loop(). - */ - virtual int post_wakeup_completions (int how_many); - - /// Handle for the completion port. Unix doesnt have completion - /// ports. - ACE_HANDLE completion_port_; - - /// This number is passed to the @c CreateIOCompletionPort system - /// call. - DWORD number_of_threads_; - - /// This event is used in conjunction with Reactor when we try to - /// integrate the event loops of Reactor and the Proactor. - ACE_Auto_Event event_; - - /// Flag that indicates whether we are used in conjunction with - /// Reactor. - bool const used_with_reactor_event_loop_; - - /// Handler to handle the wakeups. This works in conjunction with the - /// ACE_Proactor::run_event_loop(). - ACE_Handler wakeup_handler_; - - /// Pseudo-task for asynch connect ( NT/2000) - /// In future should removed in XP with ConnectEx support - ACE_Asynch_Pseudo_Task pseudo_task_; -}; - -/** - * @class ACE_WIN32_Asynch_Timer - * - * @brief This class is posted to the completion port when a timer - * expires. When the complete method of this object is - * called, the @a handler's handle_timeout method will be - * called. - */ -class ACE_WIN32_Asynch_Timer : public ACE_WIN32_Asynch_Result -{ - /// The factory method for this class is with the POSIX_Proactor - /// class. - friend class ACE_WIN32_Proactor; - -protected: - /// Constructor. - ACE_WIN32_Asynch_Timer (const ACE_Handler::Proxy_Ptr &handler_proxy, - const void *act, - const ACE_Time_Value &tv, - ACE_HANDLE event = ACE_INVALID_HANDLE, - int priority = 0, - int signal_number = 0); - - /// This method calls the @a handler's handle_timeout method. - virtual void complete (size_t bytes_transferred, - int success, - const void *completion_key, - u_long error = 0); - - /// Time value requested by caller - ACE_Time_Value time_; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_WIN32 */ -#include /**/ "ace/post.h" -#endif /* ACE_PROACTOR_H */ diff --git a/externals/ace/XML_Svc_Conf.cpp b/externals/ace/XML_Svc_Conf.cpp deleted file mode 100644 index 23dddad8469..00000000000 --- a/externals/ace/XML_Svc_Conf.cpp +++ /dev/null @@ -1,15 +0,0 @@ -// $Id: XML_Svc_Conf.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/XML_Svc_Conf.h" - -#if (ACE_USES_CLASSIC_SVC_CONF == 0) - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_XML_Svc_Conf::~ACE_XML_Svc_Conf (void) -{ -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_USES_CLASSIC_SVC_CONF == 0 */ diff --git a/externals/ace/XML_Svc_Conf.h b/externals/ace/XML_Svc_Conf.h deleted file mode 100644 index 883151e05d2..00000000000 --- a/externals/ace/XML_Svc_Conf.h +++ /dev/null @@ -1,65 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file XML_Svc_Conf.h - * - * $Id: XML_Svc_Conf.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Nanbor Wang - */ -//============================================================================= - - -#ifndef ACE_XML_SVC_CONF_H -#define ACE_XML_SVC_CONF_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/ACE_export.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if (ACE_USES_CLASSIC_SVC_CONF==0) - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_XML_Svc_Conf - * - * @brief This abstract class defines the common operations - * ACE_Service_Config expects when using the XML Service Config Parser. - * - * When implementing a concret XML_Svc_Conf class, be sure to overload - * the new/delete function so the dynamically created concret XML_Svc_Conf - * instance can be deleted from the original heap in the DLL/SO. The - * concret XML_Svc_Conf implementation will be put into a DLL/SO that - * ACE applications can link to dynamically using the ACE_DLL class. - * This DLL should include an operation as follow: - * - * extern "C" ACE_XML_Svc_Conf_Parser * _ACEXML_create_XML_Svc_Conf_Object (void); - * - * - */ - -class ACE_Export ACE_XML_Svc_Conf -{ -public: - typedef ACE_XML_Svc_Conf *(*Factory)(void); - - virtual ~ACE_XML_Svc_Conf (void) = 0; - - virtual int parse_file (const ACE_TCHAR file[]) = 0; - - virtual int parse_string (const ACE_TCHAR str[]) = 0; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_USES_CLASSIC_SVC_CONF == 0 */ - -#include /**/ "ace/post.h" - -#endif /* ACE_XML_SVC_CONF_H */ diff --git a/externals/ace/XTI_ATM_Mcast.cpp b/externals/ace/XTI_ATM_Mcast.cpp deleted file mode 100644 index 503e3fea0e2..00000000000 --- a/externals/ace/XTI_ATM_Mcast.cpp +++ /dev/null @@ -1,70 +0,0 @@ -// $Id: XTI_ATM_Mcast.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/XTI_ATM_Mcast.h" - -ACE_RCSID(ace, XTI_ATM_Mcast, "$Id: XTI_ATM_Mcast.cpp 80826 2008-03-04 14:51:23Z wotte $") - -#if defined (ACE_HAS_XTI_ATM) - -#if !defined (__ACE_INLINE__) -#include "ace/XTI_ATM_Mcast.inl" -#endif /* __ACE_INLINE__ */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_ALLOC_HOOK_DEFINE(ACE_XTI_ATM_Mcast) - -void -ACE_XTI_ATM_Mcast::dump (void) const -{ -#if defined (ACE_HAS_DUMP) - ACE_TRACE ("ACE_XTI_ATM_Mcast::dump"); -#endif /* ACE_HAS_DUMP */ -} - -ACE_XTI_ATM_Mcast::ACE_XTI_ATM_Mcast (void) -{ - ACE_TRACE ("ACE_XTI_ATM_Mcast::ACE_XTI_ATM_Mcast"); -} - -// Add a leaf to the current connection (i.e., multicast). - -int -ACE_XTI_ATM_Mcast::add_leaf (ACE_TLI_Stream ¤t_stream, - const ACE_Addr &remote_sap, - ACE_INT32 leaf_id, - ACE_Time_Value *timeout) -{ - ACE_TRACE ("ACE_XTI_ATM_Mcast::add_leaf"); - - struct netbuf call_req; - memset(&call_req, 0, sizeof(call_req)); - call_req.len = remote_sap.get_size (); - call_req.buf = (char *)remote_sap.get_addr (); - - if (::t_addleaf(current_stream.get_handle(), - leaf_id, - &call_req) < 0) - { - // Check for asynchronous event - if (t_errno == TLOOK) - { - int const event = ACE_OS::t_look(current_stream.get_handle()); - if (event != TNODATA && event != T_DATA) - return -1; - else - // If this doesn't work for asynchronous calls we need to call - // the XTI/ATM t_rcvleafchange() function to check for t_addleaf - // completion. - return complete (current_stream, 0, timeout); - } - else - return -1; - } - - return 0; -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_XTI_ATM */ diff --git a/externals/ace/XTI_ATM_Mcast.h b/externals/ace/XTI_ATM_Mcast.h deleted file mode 100644 index bfdfa92c957..00000000000 --- a/externals/ace/XTI_ATM_Mcast.h +++ /dev/null @@ -1,137 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file XTI_ATM_Mcast.h - * - * $Id: XTI_ATM_Mcast.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Joe Hoffert - */ -//============================================================================= - - -#ifndef ACE_XTI_ATM_MCAST_H -#define ACE_XTI_ATM_MCAST_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -#pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_XTI_ATM) - -#include "ace/TLI_Connector.h" -#include "ace/ATM_Addr.h" - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_XTI_ATM_Mcast - * - * @brief Defines an active connection factory for the ACE_TLI C++ - * wrappers to support XTI/ATM multicast. - */ -class ACE_Export ACE_XTI_ATM_Mcast : public ACE_TLI_Connector -{ -public: - // = Initialization methods. - /// Default constructor. - ACE_XTI_ATM_Mcast (void); - - /** - * Actively connect and produce a @a new_stream if things go well. - * The @a remote_sap is the address that we are trying to connect - * with. The @a timeout is the amount of time to wait to connect. - * If it's 0 then we block indefinitely. If *timeout == {0, 0} then - * the connection is done using non-blocking mode. In this case, if - * the connection can't be made immediately the value of -1 is - * returned with @c errno == EWOULDBLOCK. If *timeout > {0, 0} then - * this is the amount of time to wait before timing out. If the - * time expires before the connection is made @c errno == ETIME. The - * @a local_sap is the value of local address to bind to. If it's - * the default value of ACE_Addr::sap_any then the user is letting - * the OS do the binding. If @a reuse_addr == 1 then the - * is reused, even if it hasn't been cleanedup yet. - */ - ACE_XTI_ATM_Mcast (ACE_TLI_Stream &new_stream, - const ACE_Addr &remote_sap, - ACE_Time_Value *timeout = 0, - const ACE_Addr &local_sap = ACE_Addr::sap_any, - int reuse_addr = 0, - int flags = O_RDWR, - int perms = 0, - const char device[] = ACE_XTI_ATM_DEVICE, - struct t_info *info = 0, - int rw_flag = 1, - struct netbuf *udata = 0, - struct netbuf *opt = 0); - - /** - * Actively connect and produce a @a new_stream if things go well. - * The @a remote_sap is the address that we are trying to connect - * with. The @a timeout is the amount of time to wait to connect. - * If it's 0 then we block indefinitely. If *timeout == {0, 0} then - * the connection is done using non-blocking mode. In this case, if - * the connection can't be made immediately the value of -1 is - * returned with @c errno == EWOULDBLOCK. If *timeout > {0, 0} then - * this is the amount of time to wait before timing out. If the - * time expires before the connection is made @c errno == ETIME. The - * @a local_sap is the value of local address to bind to. If it's - * the default value of ACE_Addr::sap_any then the user is letting - * the OS do the binding. If @a reuse_addr == 1 then the - * is reused, even if it hasn't been cleanedup yet. - */ - int connect (ACE_TLI_Stream &new_stream, - const ACE_Addr &remote_sap, - ACE_Time_Value *timeout = 0, - const ACE_Addr &local_sap = ACE_Addr::sap_any, - int reuse_addr = 0, - int flags = O_RDWR, - int perms = 0, - const char device[] = ACE_XTI_ATM_DEVICE, - struct t_info *info = 0, - int rw_flag = 1, - struct netbuf *udata = 0, - struct netbuf *opt = 0); - - /** - * Actively add a leaf to the currently connected stream (i.e., - * multicast). The @a remote_sap is the address of the leaf that we - * are trying to add. The @a timeout is the amount of time to wait to - * connect. If it's 0 then we block indefinitely. If *timeout == - * {0, 0} then the connection is done using non-blocking mode. In - * this case, if the connection can't be made immediately the value - * of -1 is returned with @c errno == EWOULDBLOCK. If *timeout > - * {0, 0} then this is the amount of time to wait before timing out. - * If the time expires before the connection is made @c errno == ETIME. - */ - int add_leaf (ACE_TLI_Stream ¤t_stream, - const ACE_Addr &remote_sap, - ACE_INT32 leaf_id, - ACE_Time_Value *timeout = 0); - - // = Meta-type info - typedef ACE_ATM_Addr PEER_ADDR; - typedef ACE_TLI_Stream PEER_STREAM; - - /// Dump the state of an object. - void dump (void) const; - - /// Declare the dynamic allocation hooks. - ACE_ALLOC_HOOK_DECLARE; -}; - -ACE_END_VERSIONED_NAMESPACE_DECL - -#if defined (__ACE_INLINE__) -#include "ace/XTI_ATM_Mcast.inl" -#endif /* __ACE_INLINE__ */ - -#endif /* ACE_HAS_XTI_ATM */ - -#include /**/ "ace/post.h" - -#endif /* ACE_XTI_ATM_MCAST_H */ diff --git a/externals/ace/XTI_ATM_Mcast.inl b/externals/ace/XTI_ATM_Mcast.inl deleted file mode 100644 index b182bb41b20..00000000000 --- a/externals/ace/XTI_ATM_Mcast.inl +++ /dev/null @@ -1,65 +0,0 @@ -// -*- C++ -*- -// -// $Id: XTI_ATM_Mcast.inl 80826 2008-03-04 14:51:23Z wotte $ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -ACE_INLINE -ACE_XTI_ATM_Mcast::ACE_XTI_ATM_Mcast (ACE_TLI_Stream &new_stream, - const ACE_Addr &remote_sap, - ACE_Time_Value *timeout, - const ACE_Addr &local_sap, - int reuse_addr, - int flags, - int perms, - const char device[], - struct t_info *info, - int rw_flag, - struct netbuf *udata, - struct netbuf *opt) -{ - ACE_TRACE ("ACE_XTI_ATM_Mcast::ACE_XTI_ATM_Mcast"); - if (this->connect (new_stream, remote_sap, timeout, local_sap, reuse_addr, - flags, perms, device, - info, rw_flag, - udata, opt) == ACE_INVALID_HANDLE - && timeout != 0 && !(errno == EWOULDBLOCK || errno == ETIME)) - ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("ACE_TLI_Stream::ACE_TLI_Stream"))); -} - -// Connect the to the , waiting up to -// amount of time if necessary. This is simple a pass- -// through function to ACE_TLI_Connector::connect(). It is over- -// ridden to change the default device from TCP to XTI/ATM. - -ACE_INLINE -int -ACE_XTI_ATM_Mcast::connect (ACE_TLI_Stream &new_stream, - const ACE_Addr &remote_sap, - ACE_Time_Value *timeout, - const ACE_Addr &local_sap, - int reuse_addr, - int flags, - int perms, - const char device[], - struct t_info *info, - int rw_flag, - struct netbuf *udata, - struct netbuf *opt) -{ - ACE_TRACE ("ACE_XTI_ATM_Mcast::connect"); - return ACE_TLI_Connector::connect(new_stream, - remote_sap, - timeout, - local_sap, - reuse_addr, - flags, - perms, - device, - info, - rw_flag, - udata, - opt); -} - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/ace.rc b/externals/ace/ace.rc deleted file mode 100644 index 54792491900..00000000000 --- a/externals/ace/ace.rc +++ /dev/null @@ -1,38 +0,0 @@ -#include "Version.h" - -1 VERSIONINFO - FILEVERSION ACE_MAJOR_VERSION,ACE_MINOR_VERSION,ACE_BETA_VERSION,0 - PRODUCTVERSION ACE_MAJOR_VERSION,ACE_MINOR_VERSION,ACE_BETA_VERSION,0 - FILEFLAGSMASK 0x3fL - FILEFLAGS 0x0L - FILEOS 0x4L - FILETYPE 0x1L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904B0" - BEGIN - VALUE "FileDescription", "ACE\0" - VALUE "FileVersion", ACE_VERSION "\0" - VALUE "InternalName", "ACEDLL\0" - VALUE "LegalCopyright", "\0" - VALUE "LegalTrademarks", "\0" - VALUE "OriginalFilename", "ACE.DLL\0" - VALUE "ProductName", "ACE\0" - VALUE "ProductVersion", ACE_VERSION "\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - -/* - * The following resource is used by the ACE logger to write messages - * to the NT event log. If you are statically linking to the ACE - * library, and you wish to use the NT event log, you should copy this - * message table to your application's resource script. - */ -1 MESSAGETABLE ace_message_table.bin diff --git a/externals/ace/ace_message_table.bin b/externals/ace/ace_message_table.bin deleted file mode 100644 index 6ac08e5dc69..00000000000 Binary files a/externals/ace/ace_message_table.bin and /dev/null differ diff --git a/externals/ace/ace_wchar.cpp b/externals/ace/ace_wchar.cpp deleted file mode 100644 index bec8255447d..00000000000 --- a/externals/ace/ace_wchar.cpp +++ /dev/null @@ -1,17 +0,0 @@ -// -*- C++ -*- -// -// $Id: ace_wchar.cpp 80826 2008-03-04 14:51:23Z wotte $ - -#include "ace/config-macros.h" -#include "ace/ace_wchar.h" - -ACE_RCSID(ace, ace_wchar, "$Id: ace_wchar.cpp 80826 2008-03-04 14:51:23Z wotte $") - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -#if defined(ACE_HAS_ICONV) -iconv_t ACE_Wide_To_Ascii::ACE_Wide_To_Ascii_iconv_env = 0; -iconv_t ACE_Ascii_To_Wide::ACE_Ascii_To_Wide_iconv_env = 0; -#endif - -ACE_END_VERSIONED_NAMESPACE_DECL diff --git a/externals/ace/ace_wchar.h b/externals/ace/ace_wchar.h deleted file mode 100644 index f556e0f9cf8..00000000000 --- a/externals/ace/ace_wchar.h +++ /dev/null @@ -1,385 +0,0 @@ -//* -*- C++ -*- */ - -//============================================================================= -/** - * @file ace_wchar.h - * - * $Id: ace_wchar.h 82441 2008-07-28 13:04:13Z johnnyw $ - * - * @author Darrell Brunsch - */ -//============================================================================= - -#ifndef ACE_WCHAR_H -#define ACE_WCHAR_H - -#include "ace/config-macros.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -// These macros have been deprecated and should be replaced by their -// ACE_TEXT_* equivalents. These macros are just hacks and may not -// completely provide the old functionality. -#if defined (ACE_LEGACY_MODE) -// Convert the old unicode indicators -# if defined (ACE_HAS_MOSTLY_UNICODE_APIS) -# define ACE_USES_WCHAR -# endif /* ACE_HAS_MOSTLY_UNICODE_APIS */ -# if defined (ACE_HAS_UNICODE) -# define ACE_HAS_WCHAR -# endif /* ACE_HAS_UNICODE */ - -// These are defined to get older stuff to compile -// FUZZ: disable check_for_tchar -# define ASYS_TCHAR ACE_TCHAR -# define ASYS_TEXT ACE_TEXT -# define ASYS_ONLY_MULTIBYTE_STRING ACE_TEXT_ALWAYS_CHAR -# define ASYS_MULTIBYTE_STRING ACE_TEXT_CHAR_TO_TCHAR -# define ASYS_WIDE_STRING ACE_TEXT_CHAR_TO_TCHAR -# define ACE_WIDE_STRING ACE_TEXT_CHAR_TO_TCHAR - -# if defined (ACE_USES_WCHAR) -# define ASYS_ONLY_WIDE_STRING(STRING) STRING -# else /* ACE_USES_WCHAR */ -# define ASYS_ONLY_WIDE_STRING(STRING) \ - ACE_Ascii_To_Wide (STRING).wchar_rep () -# endif /* ACE_USES_WCHAR */ - -# define ACE_TEXT_STRING ACE_TString - -#endif /* ACE_LEGACY_MODE */ - -#if defined (ACE_HAS_XPG4_MULTIBYTE_CHAR) -# if !defined (ACE_HAS_WCHAR) -# define ACE_HAS_WCHAR -# endif -# include /**/ -#endif /* ACE_HAS_XPG4_MULTIBYTE_CHAR */ - -#if defined (ACE_HAS_WCHAR) -# if defined (ACE_VXWORKS) -# include /**/ /* For wchar_t */ -# include /**/ /* For mbstowcs, etc. */ -# include /**/ /* For strlen */ -# if !defined (__RTP__) -# define wint_t unsigned int /* VxWorks has wchar_t but not wint_t */ -# else -# include /**/ -# include /**/ -# endif -# elif defined (ACE_OPENVMS) -# include /**/ -# include /**/ -# elif defined (ACE_HAS_STANDARD_CPP_LIBRARY) && \ - (ACE_HAS_STANDARD_CPP_LIBRARY != 0) -# include /**/ -# include /**/ -# elif defined (ACE_HAS_WINCE) -# include /**/ -# else -# include /**/ -# endif /* ACE_HAS_STANDARD_CPP_LIBRARY */ -#endif /* ACE_HAS_WCHAR */ - -#if defined (ACE_HAS_ICONV) -# include /**/ -# if !defined (ACE_MAX_ICONV_BUFFER) -# define ACE_MAX_ICONV_BUFFER 16*1024 -# endif -#endif /* ACE_HAS_ICONV */ - -#if defined (ACE_USES_STD_NAMESPACE_FOR_STDC_LIB) && \ - (ACE_USES_STD_NAMESPACE_FOR_STDC_LIB != 0) -using std::size_t; -#endif /* ACE_USES_STD_NAMESPACE_FOR_STDC_LIB */ - -// This makes the somewhat dubious assumption that if a platform lacks -// a native wchar_t type, then it will typedef it as unsigned short. -#if defined (ACE_HAS_WCHAR) && !defined (ACE_LACKS_NATIVE_WCHAR_T) -# if !defined (ACE_WSTRING_HAS_USHORT_SUPPORT) -# define ACE_WSTRING_HAS_USHORT_SUPPORT -# endif /* ACE_WSTRING_HAS_USHORT_SUPPORT */ -#endif /* ACE_HAS_WCHAR && !ACE_LACKS_NATIVE_WCHAR_T */ - -// Set the default behaviour for ACE_TEXT_WIDE to use the L-prefix -#if !defined (ACE_USES_L_PREFIX) -# define ACE_USES_L_PREFIX 1 -#endif /* ACE_USES_L_PREFIX */ - -// Define the unicode/wchar related macros correctly - -# if !defined (ACE_TEXT_WIDE) -# if (ACE_USES_L_PREFIX == 1) -# define ACE_TEXT_WIDE_I(STRING) L##STRING -# else /* ACE_USES_L_PREFIX */ -# define ACE_TEXT_WIDE_I(STRING) STRING -# endif /* ACE_USES_L_PREFIX */ -# define ACE_TEXT_WIDE(STRING) ACE_TEXT_WIDE_I (STRING) -# endif /* ACE_TEXT_WIDE */ - -#if defined (ACE_USES_WCHAR) -typedef wchar_t ACE_TCHAR; -typedef char ACE_ANTI_TCHAR; -# define ACE_TEXT(STRING) ACE_TEXT_WIDE (STRING) -# if !defined (ACE_LACKS_DEPRECATED_MACROS) -# define ACE_LIB_TEXT(STRING) ACE_TEXT_WIDE (STRING) -# endif -# define ACE_TEXT_ALWAYS_CHAR(STRING) ACE_Wide_To_Ascii (STRING).char_rep () -# define ACE_TEXT_ALWAYS_WCHAR(STRING) STRING -# define ACE_TEXT_CHAR_TO_TCHAR(STRING) ACE_Ascii_To_Wide (STRING).wchar_rep () -# define ACE_TEXT_WCHAR_TO_TCHAR(STRING) STRING -# define ACE_TEXT_ANTI_TO_TCHAR(STRING) ACE_Ascii_To_Wide (STRING).wchar_rep () -#else /* ACE_USES_WCHAR */ -typedef char ACE_TCHAR; -typedef wchar_t ACE_ANTI_TCHAR; -# define ACE_TEXT(STRING) STRING -# if !defined (ACE_LACKS_DEPRECATED_MACROS) -# define ACE_LIB_TEXT(STRING) STRING -# endif -# define ACE_TEXT_ALWAYS_CHAR(STRING) STRING -# define ACE_TEXT_ALWAYS_WCHAR(STRING) ACE_Ascii_To_Wide (STRING).wchar_rep () -# define ACE_TEXT_CHAR_TO_TCHAR(STRING) STRING -# define ACE_TEXT_WCHAR_TO_TCHAR(STRING) ACE_Wide_To_Ascii (STRING).char_rep () -# define ACE_TEXT_ANTI_TO_TCHAR(STRING) ACE_Wide_To_Ascii (STRING).char_rep () -#endif /* ACE_USES_WCHAR */ - -// The OS_String module defines some wide-char functions that are not -// universally available. In particular, they're not part of the -// XPG4 Worldwide Portability Interface wide-character string handling -// functions. So, if ACE_HAS_XPG4_MULTIBYTE_CHAR is defined, note that -// these functions are missing. -#if defined (ACE_HAS_XPG4_MULTIBYTE_CHAR) - -# if !defined (ACE_LACKS_ITOW) -# define ACE_LACKS_ITOW -# endif - -# if !defined (ACE_LACKS_WCSICMP) -# define ACE_LACKS_WCSICMP -# endif - -# if !defined (ACE_LACKS_WCSNICMP) -# define ACE_LACKS_WCSNICMP -# endif - -# if !defined (ACE_LACKS_WCSDUP) -# define ACE_LACKS_WCSDUP -# endif - -#endif /* ACE_HAS_XPG4_MULTIBYTE_CHAR */ - -#if defined ACE_HAS_WCHAR - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -/** - * @class ACE_Wide_To_Ascii - * - * @brief A lightweight wchar* to char* string conversion class. - * - * The purpose of this class is to perform conversion from - * wchar* to char* strings. It is not intended for general - * purpose use. - */ -class ACE_Wide_To_Ascii -{ -public: - /// Ctor must take a wchar string. - ACE_Wide_To_Ascii (const wchar_t *s); - - /// Dtor will free up the memory. - ~ACE_Wide_To_Ascii (void); - - /// Return the internal char* representation. - char *char_rep (void); - - /// Converts an wchar_t string to ascii and returns a new string. - static char *convert (const wchar_t *wstr); - -private: - /// Internal pointer to the converted string. - char *s_; - -#if defined (ACE_HAS_ICONV) - static iconv_t ACE_Wide_To_Ascii_iconv_env; -#endif /* ACE_HAS_ICONV */ - - /// Disallow these operation. - ACE_Wide_To_Ascii (void); - ACE_Wide_To_Ascii (ACE_Wide_To_Ascii &); - ACE_Wide_To_Ascii& operator= (ACE_Wide_To_Ascii &); -}; - -/** - * @class ACE_Ascii_To_Wide - * - * @brief A lightweight char* to wchar* string conversion class. - * - * The purpose of this class is to perform conversion from - * char* to wchar* strings. It is not intended for general - * purpose use. - */ -class ACE_Ascii_To_Wide -{ -public: - /// Ctor must take a wchar string. - ACE_Ascii_To_Wide (const char *s); - - /// Dtor will free up the memory. - ~ACE_Ascii_To_Wide (void); - - /// Return the internal wchar* representation. - wchar_t *wchar_rep (void); - - /// Converts an char string to unicode/wide and returns a new string. - static wchar_t *convert (const char *str); - -private: - /// Internal pointer to the converted string. - wchar_t *s_; - -#if defined (ACE_HAS_ICONV) - static iconv_t ACE_Ascii_To_Wide_iconv_env; -#endif /* ACE_HAS_ICONV */ - - /// Disallow these operation. - ACE_Ascii_To_Wide (void); - ACE_Ascii_To_Wide (ACE_Ascii_To_Wide &); - ACE_Ascii_To_Wide operator= (ACE_Ascii_To_Wide &); -}; - -#if defined (ACE_LEGACY_MODE) -typedef ACE_Ascii_To_Wide ACE_OS_CString; -typedef ACE_Wide_To_Ascii ACE_OS_WString; -#endif /* ACE_LEGACY_MODE */ - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_WCHAR */ - -#if defined (ACE_WIN32) -#if defined (ACE_USES_WCHAR) -#define ACE_LPSTR LPWSTR -#define ACE_TEXT_SERVICE_TABLE_ENTRY SERVICE_TABLE_ENTRYW -#define ACE_TEXT_STARTUPINFO STARTUPINFOW -#define ACE_TEXT_WIN32_FIND_DATA WIN32_FIND_DATAW -#define ACE_TEXT_OSVERSIONINFO OSVERSIONINFOW -#define ACE_TEXT_EXPLICIT_ACCESS EXPLICIT_ACCESS_W - -#define ACE_TEXT_CreateEvent ::CreateEventW -#define ACE_TEXT_CreateFile ::CreateFileW -#define ACE_TEXT_CreateFileMapping ::CreateFileMappingW -#define ACE_TEXT_CreateMutex ::CreateMutexW -#define ACE_TEXT_CreateProcess ::CreateProcessW -#define ACE_TEXT_CreateSemaphore ::CreateSemaphoreW -#define ACE_TEXT_CreateService ::CreateServiceW -#define ACE_TEXT_ExpandEnvironmentStrings ::ExpandEnvironmentStringsW -#define ACE_TEXT_FindFirstChangeNotification ::FindFirstChangeNotificationW -#define ACE_TEXT_FindFirstFile ::FindFirstFileW -#define ACE_TEXT_FindNextFile ::FindNextFileW -#define ACE_TEXT_FormatMessage ::FormatMessageW -#define ACE_TEXT_FreeEnvironmentStrings ::FreeEnvironmentStringsW -#define ACE_TEXT_GetComputerName ::GetComputerNameW -#define ACE_TEXT_GetEnvironmentStrings ::GetEnvironmentStringsW -#define ACE_TEXT_GetFileAttributes ::GetFileAttributesW -#define ACE_TEXT_GetModuleFileName ::GetModuleFileNameW -#define ACE_TEXT_GetTempPath ::GetTempPathW -#define ACE_TEXT_GetUserName ::GetUserNameW -#define ACE_TEXT_GetUserNameEx ::GetUserNameExW -#define ACE_TEXT_GetVersionEx ::GetVersionExW -#define ACE_TEXT_LoadLibrary ::LoadLibraryW -#define ACE_TEXT_MoveFileEx ::MoveFileExW -#define ACE_TEXT_WaitNamedPipe ::WaitNamedPipeW -#define ACE_TEXT_OpenFileMapping ::OpenFileMappingW -#define ACE_TEXT_OpenSCManager ::OpenSCManagerW -#define ACE_TEXT_OpenService ::OpenServiceW -#define ACE_TEXT_OutputDebugString ::OutputDebugStringW -#define ACE_TEXT_RegisterEventSource ::RegisterEventSourceW -#define ACE_TEXT_RegisterServiceCtrlHandler ::RegisterServiceCtrlHandlerW -#define ACE_TEXT_RegConnectRegistry ::RegConnectRegistryW -#define ACE_TEXT_RegCreateKeyEx ::RegCreateKeyExW -#define ACE_TEXT_RegDeleteKey ::RegDeleteKeyW -#define ACE_TEXT_RegDeleteValue ::RegDeleteValueW -#define ACE_TEXT_RegEnumKeyEx ::RegEnumKeyExW -#define ACE_TEXT_RegEnumValue ::RegEnumValueW -#define ACE_TEXT_RegCreateKey ::RegCreateKeyW -#define ACE_TEXT_RegOpenKey ::RegOpenKeyW -#define ACE_TEXT_RegOpenKeyEx ::RegOpenKeyExW -#define ACE_TEXT_RegQueryValueEx ::RegQueryValueExW -#define ACE_TEXT_RegSetValueEx ::RegSetValueExW -#define ACE_TEXT_ReportEvent ::ReportEventW -#define ACE_TEXT_SearchPath ::SearchPathW -#define ACE_TEXT_StartService ::StartServiceW -#define ACE_TEXT_StartServiceCtrlDispatcher ::StartServiceCtrlDispatcherW -#define ACE_TEXT_SetFileSecurity ::SetFileSecurityW -#define ACE_TEXT_SetEntriesInAcl ::SetEntriesInAclW -#define ACE_TEXT_PdhExpandCounterPath ::PdhExpandCounterPathW -#define ACE_TEXT_PdhOpenQuery ::PdhOpenQueryW -#define ACE_TEXT_PdhAddCounter ::PdhAddCounterW - -#else /* ACE_USES_WCHAR */ -#define ACE_LPSTR LPSTR -#define ACE_TEXT_SERVICE_TABLE_ENTRY SERVICE_TABLE_ENTRYA -#define ACE_TEXT_STARTUPINFO STARTUPINFOA -#define ACE_TEXT_WIN32_FIND_DATA WIN32_FIND_DATAA -#define ACE_TEXT_OSVERSIONINFO OSVERSIONINFOA -#define ACE_TEXT_EXPLICIT_ACCESS EXPLICIT_ACCESS_A - -#define ACE_TEXT_CreateEvent ::CreateEventA -#define ACE_TEXT_CreateFile ::CreateFileA -#define ACE_TEXT_CreateFileMapping ::CreateFileMappingA -#define ACE_TEXT_CreateMutex ::CreateMutexA -#define ACE_TEXT_CreateProcess ::CreateProcessA -#define ACE_TEXT_CreateSemaphore ::CreateSemaphoreA -#define ACE_TEXT_CreateService ::CreateServiceA -#define ACE_TEXT_ExpandEnvironmentStrings ::ExpandEnvironmentStringsA -#define ACE_TEXT_FindFirstChangeNotification ::FindFirstChangeNotificationA -#define ACE_TEXT_FindFirstFile ::FindFirstFileA -#define ACE_TEXT_FindNextFile ::FindNextFileA -#define ACE_TEXT_FormatMessage ::FormatMessageA -#define ACE_TEXT_FreeEnvironmentStrings ::FreeEnvironmentStringsA -#define ACE_TEXT_GetComputerName ::GetComputerNameA -#define ACE_TEXT_GetEnvironmentStrings ::GetEnvironmentStringsA -#define ACE_TEXT_GetFileAttributes ::GetFileAttributesA -#define ACE_TEXT_GetModuleFileName ::GetModuleFileNameA -#define ACE_TEXT_GetTempPath ::GetTempPathA -#define ACE_TEXT_GetUserName ::GetUserNameA -#define ACE_TEXT_GetUserNameEx ::GetUserNameExA -#define ACE_TEXT_GetVersionEx ::GetVersionExA -#define ACE_TEXT_LoadLibrary ::LoadLibraryA -#define ACE_TEXT_MoveFileEx ::MoveFileExA -#define ACE_TEXT_WaitNamedPipe ::WaitNamedPipeA -#define ACE_TEXT_OpenFileMapping ::OpenFileMappingA -#define ACE_TEXT_OpenSCManager ::OpenSCManagerA -#define ACE_TEXT_OpenService ::OpenServiceA -#define ACE_TEXT_OutputDebugString ::OutputDebugStringA -#define ACE_TEXT_RegisterEventSource ::RegisterEventSourceA -#define ACE_TEXT_RegisterServiceCtrlHandler ::RegisterServiceCtrlHandlerA -#define ACE_TEXT_RegConnectRegistry ::RegConnectRegistryA -#define ACE_TEXT_RegCreateKeyEx ::RegCreateKeyExA -#define ACE_TEXT_RegDeleteKey ::RegDeleteKeyA -#define ACE_TEXT_RegDeleteValue ::RegDeleteValueA -#define ACE_TEXT_RegEnumKeyEx ::RegEnumKeyExA -#define ACE_TEXT_RegEnumValue ::RegEnumValueA -#define ACE_TEXT_RegCreateKey ::RegCreateKeyA -#define ACE_TEXT_RegOpenKey ::RegOpenKeyA -#define ACE_TEXT_RegOpenKeyEx ::RegOpenKeyExA -#define ACE_TEXT_RegQueryValueEx ::RegQueryValueExA -#define ACE_TEXT_RegSetValueEx ::RegSetValueExA -#define ACE_TEXT_ReportEvent ::ReportEventA -#define ACE_TEXT_SearchPath ::SearchPathA -#define ACE_TEXT_StartService ::StartServiceA -#define ACE_TEXT_StartServiceCtrlDispatcher ::StartServiceCtrlDispatcherA -#define ACE_TEXT_SetFileSecurity ::SetFileSecurityA -#define ACE_TEXT_SetEntriesInAcl ::SetEntriesInAclA -#define ACE_TEXT_PdhExpandCounterPath ::PdhExpandCounterPathA -#define ACE_TEXT_PdhOpenQuery ::PdhOpenQueryA -#define ACE_TEXT_PdhAddCounter ::PdhAddCounterA -#endif /* ACE_USES_WCHAR */ -#endif /* ACE_WIN32 */ - -#include "ace/ace_wchar.inl" - -#endif /* ACE_WCHAR_H */ diff --git a/externals/ace/ace_wchar.inl b/externals/ace/ace_wchar.inl deleted file mode 100644 index 744b44f5e73..00000000000 --- a/externals/ace/ace_wchar.inl +++ /dev/null @@ -1,183 +0,0 @@ -// -*- C++ -*- -// -// $Id: ace_wchar.inl 80826 2008-03-04 14:51:23Z wotte $ - -// These are always inlined -// FUZZ: disable check_for_inline - -#if defined (ACE_HAS_WCHAR) - -#if !defined (ACE_WIN32) -# include /**/ // Need to see strlen() -#endif /* ACE_WIN32 */ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -inline -ACE_Wide_To_Ascii::~ACE_Wide_To_Ascii (void) -{ - delete [] this->s_; -} - -inline char * -ACE_Wide_To_Ascii::char_rep (void) -{ - return this->s_; -} - -inline char * -ACE_Wide_To_Ascii::convert (const wchar_t *wstr) -{ - // Short circuit null pointer case - if (wstr == 0) - return 0; - -# if defined (ACE_WIN32) - UINT const cp = GetACP (); // Codepage - int const len = ::WideCharToMultiByte (cp, - 0, - wstr, - -1, - 0, - 0, - 0, - 0); -# elif defined (ACE_LACKS_WCSLEN) - const wchar_t * wtemp = wstr; - while ((*wtemp) != 0) // Hopefully the string is null terminated! - ++wtemp; - - int const len = wtemp - wstr + 1; -# else /* ACE_WIN32 */ - size_t const len = ::wcslen (wstr) + 1; -# endif /* ACE_WIN32 */ - -#if !defined (ACE_HAS_ICONV) - char *str = new char[len]; -#endif - -# if defined (ACE_WIN32) - ::WideCharToMultiByte (cp, 0, wstr, -1, str, len, 0, 0); -# elif defined (ACE_VXWORKS) - ::wcstombs (str, wstr, len); -# elif defined (ACE_HAS_ICONV) - wchar_t * wstri = const_cast (wstr); - size_t lensi = ACE_MAX_ICONV_BUFFER; - size_t lenwi = len * sizeof(wchar_t); - char buf[ACE_MAX_ICONV_BUFFER]; - char *stri = buf; - - size_t hr = iconv (ACE_Wide_To_Ascii_iconv_env, (char**)&wstri, &lenwi, &stri, &lensi); - if ((hr==size_t(-1))||(lensi==ACE_MAX_ICONV_BUFFER)) - { - char *str=new char[len]; - for (size_t i = 0; i < len; i++) - { - wchar_t *t = const_cast (wstr); - str[i] = static_cast (*(t + i)); - } - - return str; - } - char *str = new char[ACE_MAX_ICONV_BUFFER-lensi]; - ::memcpy(str, buf, ACE_MAX_ICONV_BUFFER-lensi); -# else /* ACE_HAS_ICONV */ - for (size_t i = 0; i < len; ++i) - { - wchar_t *t = const_cast (wstr); - str[i] = static_cast (*(t + i)); - } -# endif /* ACE_WIN32 */ - return str; -} - -inline -ACE_Wide_To_Ascii::ACE_Wide_To_Ascii (const wchar_t *s) -{ -#if defined(ACE_HAS_ICONV) - if (ACE_Wide_To_Ascii_iconv_env == 0) - { - ACE_Wide_To_Ascii_iconv_env = iconv_open("", "WCHAR_T"); - } -#endif - s_ = ACE_Wide_To_Ascii::convert (s); -} - -inline -ACE_Ascii_To_Wide::~ACE_Ascii_To_Wide (void) -{ - delete [] this->s_; -} - -inline wchar_t * -ACE_Ascii_To_Wide::wchar_rep (void) -{ - return this->s_; -} - -inline wchar_t * -ACE_Ascii_To_Wide::convert (const char *str) -{ - // Short circuit null pointer case - if (str == 0) - return 0; - -# if defined (ACE_WIN32) - UINT const cp = GetACP (); // Codepage - int const len = ::MultiByteToWideChar (cp, 0, str, -1, 0, 0); -# else /* ACE_WIN32 */ - size_t const len = strlen (str) + 1; -# endif /* ACE_WIN32 */ - -#if !defined (ACE_HAS_ICONV) - wchar_t *wstr = new wchar_t[len]; -#endif - -# if defined (ACE_WIN32) - ::MultiByteToWideChar (cp, 0, str, -1, wstr, len); -# elif defined (ACE_VXWORKS) - ::mbstowcs (wstr, str, len); -# elif defined (ACE_HAS_ICONV) /* ACE_VXWORKS */ - char *stri = const_cast(str); - size_t lensi = len; - size_t lenwi = ACE_MAX_ICONV_BUFFER; - wchar_t buf[ACE_MAX_ICONV_BUFFER/sizeof(wchar_t)]; - wchar_t *wstri=buf; - - size_t hr=iconv(ACE_Ascii_To_Wide_iconv_env, &stri, &lensi, (char**)&wstri, &lenwi); - if((hr==size_t(-1))||(lenwi==ACE_MAX_ICONV_BUFFER)){ - wchar_t *wstr=new wchar_t[len*sizeof(wchar_t)]; - for (size_t i = 0; i < len; i++){ - char *t = const_cast (str); - wstr[i] = static_cast (*((unsigned char*)t + i)); - } - - return wstr; - } - wchar_t *wstr=new wchar_t[(ACE_MAX_ICONV_BUFFER-lenwi)/sizeof(wchar_t)]; - ::memcpy(wstr,buf,ACE_MAX_ICONV_BUFFER-lenwi); -# else /* ACE_HAS_ICONV */ - for (size_t i = 0; i < len; ++i) - { - char *t = const_cast (str); - wstr[i] = static_cast (*((unsigned char*)(t + i))); - } -# endif /* ACE_WIN32 */ - return wstr; -} - -inline -ACE_Ascii_To_Wide::ACE_Ascii_To_Wide (const char *s) -{ -#if defined(ACE_HAS_ICONV) - if (ACE_Ascii_To_Wide_iconv_env == 0) - { - ACE_Ascii_To_Wide_iconv_env = iconv_open("WCHAR_T", ""); - } -#endif - s_ = ACE_Ascii_To_Wide::convert (s); -} - -ACE_END_VERSIONED_NAMESPACE_DECL - -#endif /* ACE_HAS_WCHAR */ diff --git a/externals/ace/checked_iterator.h b/externals/ace/checked_iterator.h deleted file mode 100644 index 08940e62bbb..00000000000 --- a/externals/ace/checked_iterator.h +++ /dev/null @@ -1,58 +0,0 @@ -// -*- C++ -*- - -#ifndef ACE_CHECKED_ITERATOR_H -#define ACE_CHECKED_ITERATOR_H - -/** - * @file checked_iterator.h - * - * @brief Checked iterator factory function. - * - * Some compilers (e.g. MSVC++ >= 8) issue security related - * diagnostics if algorithms such as std::copy() are used in an unsafe - * way. Normally this isn't an issue if STL container iterators are - * used in conjuction with the standard algorithms. However, in cases - * where application-specific iterators are use with standard - * algorithms that could potentially overrun a buffer, extra care must - * be taken to prevent such an overrun. If supported, checked - * iterators can be used to address the potential destination buffer - * overrun. - * - * This header provides function templates that generate the - * appropriate checked iterator. In cases where checked iterators are - * not supported, the pointer passed to the function is returned - * instead. - * - * $Id: checked_iterator.h 88263 2009-12-20 07:58:09Z johnnyw $ - * - * @internal The functions and types in this header are meant for - * internal use. They may change at any point between - * releases. - * - * @author Ossama Othman - */ - -# if defined (_MSC_VER) && (_MSC_FULL_VER >= 140050000) && (!defined (_STLPORT_VERSION)) -// Checked iterators are currently only supported in MSVC++ 8 or better. -# include -# endif /* _MSC_VER >= 1400 && !_STLPORT_VERSION */ - -# if defined (_MSC_VER) && (_MSC_FULL_VER >= 140050000) && (!defined (_STLPORT_VERSION)) -template -stdext::checked_array_iterator -ACE_make_checked_array_iterator (PTR buf, size_t len) -{ - return stdext::checked_array_iterator (buf, len); -} -# else -template -PTR -ACE_make_checked_array_iterator (PTR buf, size_t /* len */) -{ - // Checked iterators are unsupported. Just return the pointer to - // the buffer itself. - return buf; -} -# endif /* _MSC_VER >= 1400 && !_STLPORT_VERSION */ - -#endif /* ACE_CHECKED_ITERATOR_H */ diff --git a/externals/ace/config-WinCE.h b/externals/ace/config-WinCE.h deleted file mode 100644 index 93040583980..00000000000 --- a/externals/ace/config-WinCE.h +++ /dev/null @@ -1,229 +0,0 @@ -// $Id: config-WinCE.h 89494 2010-03-15 20:11:18Z olli $ - -// Note: For WinCE build, simply use: #include "ace/config-win32.h" -// It is same as config.h for Windows NT/2k so that you can -// share same files and directories for both WinCE and NT/2k -// builds, unless you add additional definition(s) for each -// specific build or change the output directory. - -#ifndef ACE_CONFIG_WINCE_H -#define ACE_CONFIG_WINCE_H - -#include /**/ "ace/pre.h" - -#ifndef ACE_CONFIG_WIN32_H -# error Use config-win32.h in config.h instead of this header -#endif // ACE_CONFIG_WIN32_H - -#if !defined (_WIN32_WCE) -# error Define _WIN32_WCE to version (i.e. 500 = 5.0) -#endif // _WIN32_WCE - -#if (_WIN32_WCE < 500) -# error ACE requires Windows CE 5.0 and later. -#endif // _WIN32_WCE - -#if !defined (ACE_HAS_WINCE) -# define ACE_HAS_WINCE 1 -#endif - -#if defined (_MSC_VER) && (_MSC_VER < 1400) -// WinCE prior to Visual Studio 2005 integration doesn't have most of -// the standard C library time functions. It also doesn't define struct tm. -// SYSTEMTIME has pretty much the same info though, so we can map it when -// needed. Define struct tm here and use it when needed. This is taken -// from the standard C library. -# define ACE_LACKS_STRUCT_TM -#endif - -// We need these libraries to build: -#if defined (_MSC_VER) -# pragma comment(lib,"corelibc.lib") -# pragma comment(linker, "/nodefaultlib:oldnames.lib") -#endif - -// Only DLL version is supported on CE. -//#if defined (ACE_HAS_DLL) -//# undef ACE_HAS_DLL -//#endif // ACE_HAS_DLL -//#define ACE_HAS_DLL 1 - -// Need to define LD search path explicitly on CE because -// CE doesn't have environment variables and we can't get -// the information using getenv. -#define ACE_DEFAULT_LD_SEARCH_PATH ACE_TEXT (".\\;\\windows") - -#define ACE_LACKS_FCNTL_H -#define ACE_LACKS_SYS_TYPES_H -#define ACE_LACKS_GETCWD -#define ACE_LACKS_ASCTIME -#define ACE_LACKS_ASCTIME_R -#define ACE_LACKS_GMTIME -#define ACE_LACKS_GMTIME_R -#define ACE_LACKS_LOCALTIME -#define ACE_LACKS_PERROR -#define ACE_LACKS_STRFTIME -#define ACE_LACKS_WIN32_SETFILEPOINTEREX -#define ACE_LACKS_WIN32_SERVICES -#define ACE_LACKS_WIN32_SECURITY_DESCRIPTORS -#define ACE_LACKS_GETPROCESSTIMES -#define ACE_LACKS_PDH_H -#define ACE_LACKS_PDHMSG_H -#define ACE_LACKS_TIME -#define ACE_LACKS_TZSET -#define ACE_LACKS_RAISE -#define ACE_LACKS_BSEARCH - -#define ACE_HAS_POSITION_INDEPENDENT_POINTERS 1 - -#define ACE_LACKS_MSG_WFMO -#define ACE_LACKS_UMASK -#define ACE_HAS_TYPES_H -#define ACE_LACKS_DEV_T - -#define ACE_ISCTYPE_EQUIVALENT ::_isctype - -// WinCE only supports the UNICODE API -#if !defined (ACE_USES_WCHAR) -# define ACE_USES_WCHAR -#endif /* ACE_USES_WCHAR */ - -#if (_WIN32_WCE < 0x600) -# define ACE_USES_WINCE_SEMA_SIMULATION -# define ACE_LACKS_ERRNO_H -# define ACE_LACKS_DUP -# define ACE_LACKS_GETSYSTEMTIMEASFILETIME -#endif /* (_WIN32_WCE < 0x600) */ - -#define ACE_LACKS_REGNOTIFYCHANGEKEYVALUE - -#define ACE_HAS_NONSTATIC_OBJECT_MANAGER 1 - -#if ! defined(ACE_DEFAULT_THREAD_KEYS) -# define ACE_DEFAULT_THREAD_KEYS TLS_MINIMUM_AVAILABLE -#endif // ! defined(ACE_DEFAULT_THREAD_KEYS) - -// FILE stuff isn't always defined in CE -#if (_MSC_VER < 1400) && !defined (_FILE_DEFINED) - typedef void FILE; -# define _FILE_DEFINED -#endif /* _MSC_VER < 1400 && !_FILE_DEFINED */ - -// This was defined in previous versions of CE, but not 2.11 -#define EXCEPTION_ACCESS_VIOLATION STATUS_ACCESS_VIOLATION - -#define ACE_MAIN WINAPI WinMain - -// SH3 cross-compiler can't handle inline functions correctly -// (along with other bugs.) -#if defined (SH3) -# define ACE_LACKS_INLINE_FUNCTIONS -#endif // SH3 && _DEBUG - -#ifndef ACE_DEFAULT_SERVER_HOST -# define ACE_DEFAULT_SERVER_HOST ACE_TEXT("localhost") -#endif // ACE_DEFAULT_SERVER_HOST - -// @@ Need to remap every function that uses any of these flags to -// Win32 API. These are for ANSI styled function and are not -// available on WinCE. - -#define _O_RDONLY 0x0000 // open for reading only -#define _O_WRONLY 0x0001 // open for writing only -#define _O_RDWR 0x0002 // open for reading and writing -#define _O_APPEND 0x0008 // writes done at eof - -#define _O_CREAT 0x0100 // create and open file -#define _O_TRUNC 0x0200 // open and truncate -#define _O_EXCL 0x0400 // open only if file doesn't already exist - -// O_TEXT files have sequences translated to on read()'s, -// and sequences translated to on write()'s -#define _O_TEXT 0x4000 // file mode is text (translated) -#define _O_BINARY 0x8000 // file mode is binary (untranslated) - -// Temporary file bit - file is deleted when last handle is closed -#define _O_TEMPORARY 0x0040 // temporary file bit - -// Non-ANSI names -#define O_RDONLY _O_RDONLY -#define O_WRONLY _O_WRONLY -#define O_RDWR _O_RDWR -#define O_APPEND _O_APPEND -#define O_CREAT _O_CREAT -#define O_TRUNC _O_TRUNC -#define O_EXCL _O_EXCL -#define O_TEXT _O_TEXT -#define O_BINARY _O_BINARY -#define O_TEMPORARY _O_TEMPORARY - -// @@ NSIG value. This is definitely not correct. -#define NSIG 23 - -#if !defined (FILE_MAP_COPY) -#define FILE_MAP_COPY 0 -#endif - -#define ACE_HAS_INTERLOCKED_EXCHANGEADD -#define ACE_LACKS_ACCESS -#define ACE_LACKS__WACCESS -#define ACE_HAS_ACCESS_EMULATION -#define ACE_LACKS_EXEC -#define ACE_LACKS_MKTEMP -#define ACE_LACKS_ISATTY -#define ACE_LACKS_STRERROR -#define ACE_LACKS_SYSTEM -#define ACE_LACKS_PIPE - -#define ACE_LACKS_CHDIR -#define ACE_LACKS_GETENV -#define ACE_LACKS_SETENV -#define ACE_LACKS_UNSETENV -#define ACE_LACKS_PUTENV -#define ACE_LACKS_GETENVSTRINGS -#define ACE_LACKS_STRENVDUP -#define ACE_LACKS_REALPATH -#define ACE_LACKS_SWAB -#define ACE_LACKS_TEMPNAM - -#if defined (_WIN32_WCE_EMULATION) -// @@ For some reason, qsort isn't defined correctly (_stdcall vs _cdecl) -// under emulation. So for right now, exclude it. -# define ACE_LACKS_QSORT -#endif // _WIN32_WCE_EMULATION - -#if !defined (BUFSIZ) -# define BUFSIZ 1024 -#endif - -#define ACE_LACKS_MALLOC_H // We do have malloc.h, but don't use it. - -#define ACE_HAS_WINCE_BROKEN_ERRNO - -#define ACE_HAS_STRDUP_EMULATION - -#if !defined (MAXSYMLINKS) -# define MAXSYMLINKS 0 -#endif - -// WinCE can't do fixed addresses for memory-mapped files. -#if defined (ACE_DEFAULT_BASE_ADDR) -# undef ACE_DEFAULT_BASE_ADDR -#endif -#define ACE_DEFAULT_BASE_ADDR 0 - -#if (_WIN32_WCE < 0x600) -# define ACE_HAS_TSS_EMULATION -#endif // WinCE version < 6.0 - -// CE doesn't support FILE_SHARE_DELETE like regular windows -#if !defined (ACE_DEFAULT_FILE_PERMS) -# define ACE_DEFAULT_FILE_PERMS (FILE_SHARE_READ | FILE_SHARE_WRITE) -#endif - -#define ACE_LACKS_SIGNAL_H -#define ACE_LACKS_SYS_STAT_H - -#include /**/ "ace/post.h" - -#endif // ACE_CONFIG_WINCE_H diff --git a/externals/ace/config-aix-5.x.h b/externals/ace/config-aix-5.x.h deleted file mode 100644 index d524e9530fc..00000000000 --- a/externals/ace/config-aix-5.x.h +++ /dev/null @@ -1,326 +0,0 @@ -// $Id: config-aix-5.x.h 87268 2009-10-29 21:06:06Z olli $ -// -// Config file for AIX 5.1 and higher. - -#ifndef ACE_CONFIG_AIX_5_X_H -#define ACE_CONFIG_AIX_5_X_H - -// This define is needed for building with Visual Age C++ 5 in incremental -// mode. In the batch mode build, platform_aix_ibm.GNU sets it. The incremental -// mode compiler won't be supported after ACE 5.3, so this will also go away -// in that timeframe, so don't worry about future AIX versions. -#if !defined (ACE_AIX_VERS) -# define ACE_AIX_VERS 501 -#endif - -// AIX 5.1 has AIO, but it doesn't have the same API as other POSIX -// systems, and the semantics of operations are a bit different. Will take -// some real work to get this going. -// AIX 5.2, however, has the POSIX API implemented. However, the libc functions -// to implement it aren't exported by default. You need to use smit to enable -// them. So, leave AIO disabled unless the user explicitly enables it. -// config-aix-4.x.h will set ACE_HAS_AIO_CALLS if config-posix.h senses the -// feature-test macros, so set up _ACE_DISABLE_AIO_CALLS_ if the user didn't -// set it. Then check for it after including config-aix-4.x.h and remove -// ACE_HAS_AIO_CALLS if so. -#if !defined (ACE_HAS_AIO_CALLS) -# define _ACE_DISABLE_AIO_CALLS_ -#endif - -// Both IBM and g++ compilers set _THREAD_SAFE if compiler is asked to compile -// threaded code (xlC_r, as opposed to xlC; and g++ -pthread) -#if !defined (ACE_MT_SAFE) || (ACE_MT_SAFE != 0) -# if defined (ACE_HAS_THREADS) -# undef ACE_HAS_THREADS -# endif -# if defined (_THREAD_SAFE) -# define ACE_HAS_THREADS 1 -// # else -// # define ACE_HAS_THREADS 0 -# endif /* _THREAD_SAFE */ -#endif /* !ACE_MT_SAFE || (ACE_MT_SAFE != 0) */ - -#if defined (__IBMCPP__) - // AIX xlC, IBM C/C++ compiler - //******************************************************************** - // - - // Compiler does this with a builtin - it's not in libc. - // Although ACE does have alloca() on this compiler/platform combination, - // it is disabled by default since it can be dangerous. Uncomment the - // following line if you ACE to use it. - //# define ACE_HAS_ALLOCA - - // Compiler supports the ssize_t typedef. -# define ACE_HAS_SSIZE_T - - // Keep an eye on this as the compiler and standards converge... -# define ACE_LACKS_LINEBUFFERED_STREAMBUF -# define ACE_LACKS_PRAGMA_ONCE - -# define ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS - // When using -qtempinc, we don't need to see template implementation - // source (though we do need a pragma to find the correct source file). - // However, without -qtempinc (either -qnotempinc or -qtemplateregistry) - // we do need to see the source. -# if defined (__TEMPINC__) -# if !defined ACE_TEMPLATES_REQUIRE_PRAGMA -# define ACE_TEMPLATES_REQUIRE_PRAGMA -# endif -# else -# if !defined (ACE_TEMPLATES_REQUIRE_SOURCE) -# define ACE_TEMPLATES_REQUIRE_SOURCE -# endif -# endif /* __TEMPINC__ */ - -# undef WIFEXITED -# undef WEXITSTATUS -# define ACE_HAS_STANDARD_CPP_LIBRARY 1 -# define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 - -# define ACE_HAS_TEMPLATE_TYPEDEFS -# define ACE_HAS_CUSTOM_EXPORT_MACROS -# define ACE_Proper_Export_Flag -# define ACE_Proper_Import_Flag - // There's no explicit import/export per-se, but to be sure that declared - // template code is exported, explicitly instantiate the class. -# define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) template class SINGLETON_TYPE < CLASS, LOCK >; -# define ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) extern template class SINGLETON_TYPE < CLASS, LOCK >; - -#elif defined (__GNUG__) - // config-g++-common.h undef's ACE_HAS_STRING_CLASS with -frepo, so - // this must appear before its #include. -# define ACE_HAS_STRING_CLASS - -# include "ace/config-g++-common.h" - -# define ACE_HAS_SSIZE_T - -# if (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ == 0)) -// We have to explicitly instantiate static template members prior to g++ 4.1 -# define ACE_HAS_EXPLICIT_STATIC_TEMPLATE_MEMBER_INSTANTIATION -#endif /* g++ prior to 4.1 */ - -# if !defined (ACE_MT_SAFE) || ACE_MT_SAFE != 0 - // ACE_MT_SAFE is #defined below, for all compilers. -# if !defined (_REENTRANT) -# define _REENTRANT -# endif /* _REENTRANT */ -# endif /* !ACE_MT_SAFE */ - -#else /* ! __IBMCPP__ && ! __GNUG__ */ -# ifdef __cplusplus /* Let it slide for C compilers. */ -# error unsupported compiler in ace/config-aix-5.x.h -# endif /* __cplusplus */ -#endif /* ! __xlC__ && ! __GNUG__ */ - -// Compiling for AIX. -#ifndef AIX -# define AIX -#endif /* AIX */ - -// Pick up all the detectable settings. -#include "ace/config-posix.h" - -// Regardless of what config-posix.h may indicate, AIX 5.3 is the first -// to support sem_timedwait(). Prior to that, use the emulation. -#if defined (ACE_HAS_POSIX_SEM_TIMEOUT) && \ - (defined (ACE_AIX_VERS) && (ACE_AIX_VERS < 503)) -# undef ACE_HAS_POSIX_SEM_TIMEOUT -#endif /* ACE_HAS_POSIX_SEM_TIMEOUT && ACE_AIX_VERS < 503 */ - -#if defined (ACE_DLL_SUFFIX) -# undef ACE_DLL_SUFFIX -#endif -#define ACE_DLL_SUFFIX ACE_TEXT (".so") - -#define ACE_DEFAULT_BASE_ADDR ((char *) 0x80000000) - -#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R - -#define ACE_HAS_SOCKLEN_T -#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG - -// AIX has AIO, but the functions don't match those of other AIO-enabled -// platforms. If this is to work, it'll require some significant work, -// maybe moving the OS-abstraction stuff to an OS_AIO or some such thing. -//# define ACE_HAS_AIO_CALLS - -#define ACE_HAS_AIX_HI_RES_TIMER - -// Compiler/platform has correctly prototyped header files. -#define ACE_HAS_CPLUSPLUS_HEADERS - -// Prototypes for both signal() and struct sigaction are consistent. -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES - -// OS has readdir and friends. -#define ACE_HAS_DIRENT - -// OS supports the getrusage() system call -#define ACE_HAS_GETRUSAGE - -#define ACE_HAS_GPERF - -#define ACE_HAS_H_ERRNO - -#define ACE_LACKS_STDINT_H -#define ACE_LACKS_SYS_SYSCTL_H - -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT -#define ACE_HAS_NONCONST_SELECT_TIMEVAL -#define ACE_HAS_ICMP_SUPPORT 1 -#define ACE_HAS_IP_MULTICAST - -// Lacks perfect filtering, must bind group address. -#if !defined ACE_LACKS_PERFECT_MULTICAST_FILTERING -# define ACE_LACKS_PERFECT_MULTICAST_FILTERING 1 -#endif /* ACE_LACKS_PERFECT_MULTICAST_FILTERING */ - -#define ACE_HAS_MSG - -// Compiler/platform supports poll(). -#define ACE_HAS_POLL - -// Platform supports POSIX O_NONBLOCK semantics. -#define ACE_HAS_POSIX_NONBLOCK - -#define ACE_HAS_POSIX_TIME -// ... but needs to include another header for it on 4.2+ -# define ACE_HAS_BROKEN_POSIX_TIME -// ... and needs another typedef -#define ACE_LACKS_TIMESPEC_T -#define ACE_HAS_SELECT_H - -#define ACE_HAS_REENTRANT_FUNCTIONS - -// Compiler/platform defines the sig_atomic_t typedef -#define ACE_HAS_SIG_ATOMIC_T -#define ACE_HAS_SIGINFO_T -#define ACE_LACKS_SIGINFO_H -#define ACE_HAS_P_READ_WRITE - -#define ACE_HAS_SIGWAIT -#define ACE_HAS_SOCKADDR_IN_SIN_LEN -#define ACE_HAS_STRBUF_T - -// Compiler supports stropts.h -#define ACE_HAS_STREAMS -// #define ACE_HAS_STREAM_PIPES - -// AIX bzero() -#define ACE_HAS_STRINGS - -#define ACE_HAS_STRUCT_NETDB_DATA - -// Dynamic linking is in good shape on newer OS/patch levels. If you have -// trouble with the dynamic linking parts of ACE, and can't patch your OS -// up to latest levels, comment this out. -#define ACE_HAS_SVR4_DYNAMIC_LINKING -// This is tightly related to dynamic linking... -#define ACE_HAS_AUTOMATIC_INIT_FINI - -#define ACE_HAS_SVR4_GETTIMEOFDAY - -#define ACE_HAS_SYSV_IPC -#define ACE_HAS_TIMOD_H -#define ACE_HAS_XTI -#define ACE_HAS_BROKEN_T_ERROR -#define ACE_TLI_TCP_DEVICE "/dev/xti/tcp" - -#define ACE_HAS_UALARM - -#define ACE_HAS_UCONTEXT_T - -#define ACE_HAS_UTIME - -#define ACE_HAS_CTYPE_T - -// Platform has XPG4 wide character type and functions. However, the size -// of wchar_t changes for 32- vs. 64-bit builds (unsigned short vs. unsigned -// int, respectively). -#define ACE_HAS_XPG4_MULTIBYTE_CHAR -#ifdef __64BIT__ -# define ACE_SIZEOF_WCHAR 4 -#else -# define ACE_SIZEOF_WCHAR 2 -#endif /* __64BIT__ */ - -#define ACE_LACKS_NETINET_TCP_H - -// AIX uses LIBPATH to search for libraries -#define ACE_LD_SEARCH_PATH ACE_TEXT ("LIBPATH") - -// Defines the page size of the system. -#define ACE_PAGE_SIZE 4096 - -//************************************************************** -// -// Threads related definitions. -// -// The threads on AIX are generally POSIX P1003.1c (ACE_HAS_PTHREADS). -// However, there is also a kernel thread ID (tid_t) that is used in -// ACE_Log_Msg (printing the thread ID). The tid_t is not the same as -// pthread_t, and can't derive one from the other - thread_self() gets -// the tid_t (kernel thread ID) if called from a thread. -// Thanks very much to Chris Lahey for straightening this out. - -#if defined (ACE_HAS_THREADS) -# if !defined (ACE_MT_SAFE) -# define ACE_MT_SAFE 1 -# endif - -# define ACE_HAS_PTHREADS -# define ACE_HAS_PTHREADS_UNIX98_EXT -# define ACE_HAS_PTHREAD_CONTINUE_NP -# define ACE_HAS_PTHREAD_SUSPEND_NP -# define ACE_HAS_RECURSIVE_MUTEXES -# define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS -# define ACE_HAS_SIGTHREADMASK -# define ACE_HAS_THREAD_SPECIFIC_STORAGE - -# define ACE_LACKS_THREAD_PROCESS_SCOPING -#else -# undef ACE_HAS_THREADS -#endif /* ACE_HAS_THREADS != 0 */ - -#define ACE_MALLOC_ALIGN 8 - -#if (defined _XOPEN_SOURCE && (_XOPEN_SOURCE - 0) >= 500) && !defined(_UNIX95) -# define ACE_HAS_3_PARAM_WCSTOK -#endif /* (_XOPEN_SOURCE -0) >= 500 && !_UNIX95 */ - -#if defined (_ACE_DISABLE_AIO_CALLS_) -# if defined (ACE_HAS_AIO_CALLS) -# undef ACE_HAS_AIO_CALLS -# endif -# undef _ACE_DISABLE_AIO_CALLS_ -#endif - -// AIX's /usr/include/unistd.h sets _POSIX_SEMAPHORE to indicate the system -// supplies such a facility, but the headers don't enable it unless -// _XOPEN_SOURCE >= 500. So disable semaphores here if _XOPEN_SOURCE isn't -// up to snuff. -#if defined (ACE_HAS_POSIX_SEM) && \ - (!defined (_XOPEN_SOURCE) || (_XOPEN_SOURCE-0 < 500)) -# undef ACE_HAS_POSIX_SEM -#endif - -// I think this is correct, but needs to be verified... -Steve Huston -#define ACE_HAS_SIGTIMEDWAIT - -// AIX 5.1 has netinet/tcp.h -#undef ACE_LACKS_NETINET_TCP_H - -#define ACE_HAS_3_PARAM_READDIR_R -#define ACE_HAS_POSIX_GETPWNAM_R -#define ACE_HAS_SCANDIR -#define ACE_SCANDIR_CMP_USES_VOIDPTR -#define ACE_SCANDIR_SEL_LACKS_CONST -#define ACE_HAS_SIGSUSPEND -#define ACE_HAS_TIMEZONE /* Call tzset() to set timezone */ -#define ACE_LACKS_ISCTYPE -#define ACE_HAS_STRSIGNAL -#define ACE_NEEDS_STRSIGNAL_RANGE_CHECK - -#endif /* ACE_CONFIG_AIX_5_X_H */ diff --git a/externals/ace/config-all.h b/externals/ace/config-all.h deleted file mode 100644 index e19caec8e45..00000000000 --- a/externals/ace/config-all.h +++ /dev/null @@ -1,93 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file config-all.h - * - * $Id: config-all.h 84216 2009-01-22 18:34:40Z johnnyw $ - * - * @author (Originally in OS.h)Doug Schmidt - * @author Jesper S. M|ller - * @author and a cast of thousands... - */ -//========================================================================== - -#ifndef ACE_CONFIG_ALL_H -#define ACE_CONFIG_ALL_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -// This is used to indicate that a platform doesn't support a -// particular feature. -#if defined ACE_HAS_VERBOSE_NOTSUP - // Print a console message with the file and line number of the - // unsupported function. -# include "ace/OS_NS_stdio.h" -# define ACE_NOTSUP_RETURN(FAILVALUE) do { errno = ENOTSUP; ACE_OS::fprintf (stderr, ACE_TEXT ("ACE_NOTSUP: %s, line %d\n"), __FILE__, __LINE__); return FAILVALUE; } while (0) -# define ACE_NOTSUP do { errno = ENOTSUP; ACE_OS::fprintf (stderr, ACE_TEXT ("ACE_NOTSUP: %s, line %d\n"), __FILE__, __LINE__); return; } while (0) -#else /* ! ACE_HAS_VERBOSE_NOTSUP */ -# define ACE_NOTSUP_RETURN(FAILVALUE) do { errno = ENOTSUP ; return FAILVALUE; } while (0) -# define ACE_NOTSUP do { errno = ENOTSUP; return; } while (0) -#endif /* ! ACE_HAS_VERBOSE_NOTSUP */ - -// ---------------------------------------------------------------- - -# define ACE_TRACE_IMPL(X) ACE_Trace ____ (ACE_TEXT (X), __LINE__, ACE_TEXT (__FILE__)) - -// By default tracing is turned off. -#if !defined (ACE_NTRACE) -# define ACE_NTRACE 1 -#endif /* ACE_NTRACE */ - -#if (ACE_NTRACE == 1) -# define ACE_TRACE(X) -#else -# if !defined (ACE_HAS_TRACE) -# define ACE_HAS_TRACE -# endif /* ACE_HAS_TRACE */ -# define ACE_TRACE(X) ACE_TRACE_IMPL(X) -# include "ace/Trace.h" -#endif /* ACE_NTRACE */ - -// By default we perform no tracing on the OS layer, otherwise the -// coupling between the OS layer and Log_Msg is too tight. But the -// application can override the default if they wish to. -#if !defined (ACE_OS_NTRACE) -# define ACE_OS_NTRACE 1 -#endif /* ACE_OS_NTRACE */ - -#if (ACE_OS_NTRACE == 1) -# define ACE_OS_TRACE(X) -#else -# if !defined (ACE_HAS_TRACE) -# define ACE_HAS_TRACE -# endif /* ACE_HAS_TRACE */ -# define ACE_OS_TRACE(X) ACE_TRACE_IMPL(X) -# include "ace/Trace.h" -#endif /* ACE_OS_NTRACE */ - -#if !defined (ACE_HAS_MONITOR_FRAMEWORK) -# define ACE_HAS_MONITOR_FRAMEWORK 1 -#endif - -#if !defined (ACE_HAS_SENDFILE) -# define ACE_HAS_SENDFILE 0 -#endif - -#if !defined (ACE_HAS_MONITOR_POINTS) -# define ACE_HAS_MONITOR_POINTS 0 -#endif - -// These includes are here to avoid circular dependencies. -// Keep this at the bottom of the file. It contains the main macros. -#include "ace/OS_main.h" - -#include /**/ "ace/post.h" - -#endif /* ACE_CONFIG_ALL_H */ diff --git a/externals/ace/config-cray.h b/externals/ace/config-cray.h deleted file mode 100644 index 1b944876112..00000000000 --- a/externals/ace/config-cray.h +++ /dev/null @@ -1,205 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-cray.h 87169 2009-10-19 20:26:55Z olli $ - -#ifndef ACE_CONFIG_CRAY_H -#define ACE_CONFIG_CRAY_H -#include /**/ "ace/pre.h" - -/* - The following predefined macros are used within ACE ifdefs. - These are defined when using the Cray compilers. _CRAYMPP - is defined, for example, if you are running on a Cray T3E - massively parallel machine. Moreover, in the case of the T3E, - _CRAYT3E will be defined. This is used to determine the - ACE_SIZEOF defines for primitive types. - - _UNICOS is defined as either the major version of UNICOS being run, - e.g. 9 or 10 on the vector machines (e.g. C90, T90, J90, YMP, ...) - or the major+minor+level UNICOS/mk version, e.g. 2.0.3 => 203, - being run on an MPP machine. - - Summary: - - _CRAYMPP (defined only if running on MPP machine, e.g. T3E, UNICOS/mk) - _CRAYT3E (defined specifically if compiling on a Cray T3E) - _UNICOS (defined if running UNICOS or UNICOS/mk) - - Tested on UNICOS 10.0.0.5, UNICOS/mk 2.0.4.57 - Compiles on UNICOS 9.0.2.8, but some tests deadlock - - Contributed by Doug Anderson -*/ - -#if defined (_UNICOS) && !defined (MAXPATHLEN) -#define MAXPATHLEN 1023 -#endif /* _UNICOS */ - -#define ACE_DEFAULT_CLOSE_ALL_HANDLES 0 - -// Defines the page size of the system. -#define ACE_PAGE_SIZE 4096 - -#define ACE_HAS_CPLUSPLUS_HEADERS - -#define ACE_HAS_SSIZE_T - -#define ACE_HAS_SYSV_IPC - -#define ACE_MT_SAFE 1 - -#define ACE_HAS_THREADS - -#define ACE_HAS_PTHREADS - -#define ACE_HAS_THREAD_SPECIFIC_STORAGE - -#define ACE_HAS_PTHREAD_MUTEXATTR_SETKIND_NP - -#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R - -#define ACE_HAS_POSIX_TIME - -#define ACE_HAS_TIMEZONE_GETTIMEOFDAY - -#define ACE_HAS_POSIX_NONBLOCK - -// Platform has POSIX terminal interface. -#define ACE_HAS_TERMIOS - -#define ACE_HAS_DIRENT - -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT - -#define ACE_HAS_IP_MULTICAST - -#define ACE_HAS_SOCKADDR_IN_SIN_LEN - -#define ACE_HAS_NONCONST_SELECT_TIMEVAL - -#define ACE_HAS_NONCONST_READLINK - -#define ACE_HAS_CHARPTR_SOCKOPT - -#define ACE_HAS_NONCONST_GETBY -#define ACE_HAS_NONCONST_INET_ADDR - -// has man pages, but links with missing symbols and I can't find lib yet -/* #define ACE_HAS_REGEX */ - -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES - -#if _UNICOS > 9 -# define ACE_HAS_SIGWAIT -#endif - -#define ACE_HAS_SIG_ATOMIC_T - -#define ACE_HAS_SIGISMEMBER_BUG - -#define ACE_HAS_MSG - -#define ACE_HAS_GPERF - -// Special modifications that apply to UNICOS/mk -#if defined(_CRAYMPP) - -# define ACE_HAS_SIGINFO_T -# define ACE_HAS_UCONTEXT_T - -#endif - -// The Cray T90 supposedly supports SYSV SHMEM, but I was unable to get it -// working. Of course, all other Cray PVP and MPP systems do NOT support it, -// so it's probably good to just define like this for consistency -#define ACE_LACKS_SYSV_SHMEM -#define ACE_LACKS_MMAP -#define ACE_LACKS_CONST_TIMESPEC_PTR -#define ACE_LACKS_SYSCALL -#define ACE_LACKS_STRRECVFD -#define ACE_LACKS_MADVISE -#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS -#define ACE_LACKS_LINEBUFFERED_STREAMBUF -#define ACE_LACKS_PTHREAD_CLEANUP -#define ACE_LACKS_CONDATTR_PSHARED -#define ACE_LACKS_THREAD_PROCESS_SCOPING - -#if !defined(_CRAYMPP) - -#define ACE_LACKS_PTHREAD_CANCEL -#define ACE_LACKS_PTHREAD_KILL - -#endif - -#define ACE_LACKS_MUTEXATTR_PSHARED -#define ACE_LACKS_RWLOCK_T -#define ACE_LACKS_PRI_T -#define ACE_LACKS_GETPGID -#define ACE_LACKS_SETPGID -#define ACE_LACKS_SETREGID -#define ACE_LACKS_SETREUID -#define ACE_LACKS_MPROTECT -#define ACE_LACKS_MSYNC -#define ACE_LACKS_READV -#define ACE_LACKS_RLIMIT - -// we probably want to fake not having this, since Cray memory mgmt is different -#define ACE_LACKS_SBRK - -#define ACE_LACKS_SETSCHED - -#define ACE_LACKS_SIGINFO_H - -#define ACE_LACKS_TIMESPEC_T - -#define ACE_LACKS_WRITEV - -// Cray vector machines are "word" oriented, and modern ones are hard 64-bit. -// "char" is somewhat of a special case. Most problems arise when code thinks -// it can address 32-bit quantities and the like. MPP crays are typically -// byte oriented, e.g. T3E uses Alpha processors, so we don't need as much -// special treatment. - -#ifndef _CRAYMPP - -# define ACE_SIZEOF_CHAR 1 -# define ACE_SIZEOF_SHORT 8 -# define ACE_SIZEOF_INT 8 -# define ACE_SIZEOF_LONG 8 -# define ACE_SIZEOF_LONG_LONG 8 -# define ACE_SIZEOF_FLOAT 8 -# define ACE_SIZEOF_DOUBLE 8 -# define ACE_SIZEOF_LONG_DOUBLE 16 -# define ACE_SIZEOF_VOID_P 8 - -#elif defined(_CRAYT3E) - -# define ACE_SIZEOF_CHAR 1 -# define ACE_SIZEOF_SHORT 4 -# define ACE_SIZEOF_INT 8 -# define ACE_SIZEOF_LONG 8 -# define ACE_SIZEOF_LONG_LONG 8 -# define ACE_SIZEOF_FLOAT 4 -# define ACE_SIZEOF_DOUBLE 8 -# define ACE_SIZEOF_LONG_DOUBLE 8 -# define ACE_SIZEOF_VOID_P 8 - -#endif - -// Ones to check out at some point - -// C++ Compiler stuff to verify -/* #define ACE_NEW_THROWS_EXCEPTIONS */ -/* #define ACE_HAS_TEMPLATE_TYPEDEFS */ - -// thread issues to check out -/* #define ACE_LACKS_TIMEDWAIT_PROTOTYPES */ - -// Cray does seem to support it, in -lnsl and has tiuser.h header -/* #define ACE_HAS_TLI */ -/* #define ACE_HAS_TIUSER_H */ -/* #define ACE_HAS_TLI_PROTOTYPES */ - -/* #define ACE_LACKS_NAMED_POSIX_SEM */ - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_CRAY_H */ diff --git a/externals/ace/config-cxx-common.h b/externals/ace/config-cxx-common.h deleted file mode 100644 index 024c25fd27e..00000000000 --- a/externals/ace/config-cxx-common.h +++ /dev/null @@ -1,86 +0,0 @@ -// -*- C++ -*- -// -// $Id: config-cxx-common.h 81935 2008-06-12 22:01:53Z jtc $ - -#ifndef ACE_CXX_COMMON_H -#define ACE_CXX_COMMON_H -#include /**/ "ace/pre.h" - -#if !defined (ACE_CONFIG_INCLUDE_CXX_COMMON) -# error ace/config-cxx-common.h: ACE configuration error! Do not #include this file directly! -#endif - -#if defined (__DECCXX) -# if !defined (linux) -# define ACE_HAS_STRING_CLASS -# if (__DECCXX_VER >= 60090010) -# define ACE_HAS_STDCPP_STL_INCLUDES -# endif /* __DECCXX_VER < 60090010 */ -# endif /* ! linux */ - -# define DEC_CXX -# define ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR -# define ACE_LACKS_LINEBUFFERED_STREAMBUF -# define ACE_LACKS_SIGNED_CHAR -# define ACE_HAS_CPLUSPLUS_HEADERS -# define ACE_TEMPLATES_REQUIRE_SOURCE -# if (__DECCXX_VER >= 60090010) - // DEC CXX 6.0 supports exceptions, etc., by default. Exceptions - // are enabled by platform_osf1_4.x.GNU/wrapper_macros.GNU. -# if defined (ACE_HAS_EXCEPTIONS) -# define ACE_NEW_THROWS_EXCEPTIONS -# endif /* ACE_HAS_EXCEPTIONS */ -# define ACE_HAS_STANDARD_CPP_LIBRARY 1 -# define ACE_HAS_TEMPLATE_TYPEDEFS - -# define ACE_ENDLESS_LOOP \ - unsigned int ace_endless_loop____ = 0; if (ace_endless_loop____) break; - -# if defined (__USE_STD_IOSTREAM) -# define ACE_LACKS_CHAR_RIGHT_SHIFTS -# define ACE_LACKS_IOSTREAM_FX -# define ACE_LACKS_UNBUFFERED_STREAMBUF -# define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 -# else /* ! __USE_STD_IOSTREAM */ -# define ACE_USES_OLD_IOSTREAMS -# endif /* ! __USE_STD_IOSTREAM */ - -// 9: nested comment not allowed. (/usr/include/pdsc.h!) (nestcomment) -// 177: variable was declared but never referenced (declbutnotref) -// 193: zero used for undefined preprocessing identifier (undpreid) -// 236: controlling expression is constant (boolexprconst) -// 401: base_class_with_nonvirtual_dtor (basclsnondto) -// 1016: expected type is incompatible with declared type of int (incint) -// 1136: conversion to smaller size integer could lose data (intconlosbit) - -# pragma message disable basclsnondto -# pragma message disable boolexprconst -# pragma message disable undpreid -# pragma message disable notusetmpfunprm -# pragma message disable bltinclnk - -# if (__DECCXX_VER >= 60190029) - // 6.1-029 and later support msg 1136. Disable it because it - // causes warnings from ACE and/or TAO. -# pragma message disable intconlosbit -# endif /* __DECCXX_VER >= 60190029 */ - -# if (__DECCXX_VER == 60190027) - // Seems that this version of cxx doesn't have reset -# define ACE_AUTO_PTR_LACKS_RESET -# endif /* __DECCXX_VER == 60190027 */ - -# if defined (DIGITAL_UNIX) && DIGITAL_UNIX >= 0x40D - // variable "PTHREAD_THIS_CATCH_NP" was declared but never referenced -# pragma message disable declbutnotref -# endif /* DIGITAL_UNIX >= 4.0f */ - -# else /* __DECCXX_VER < 60090010 */ -# define ACE_LACKS_PRAGMA_ONCE -# endif /* __DECCXX_VER < 60090010 */ -#else /* ! __DECCXX */ -# error ace/config-cxx-common.h can only be used with Compaq CXX! -#endif /* ! __DECCXX */ - -#include /**/ "ace/post.h" -#endif /* ACE_CXX_COMMON_H */ diff --git a/externals/ace/config-cygwin32.h b/externals/ace/config-cygwin32.h deleted file mode 100644 index 35c517c3ca6..00000000000 --- a/externals/ace/config-cygwin32.h +++ /dev/null @@ -1,216 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-cygwin32.h 87169 2009-10-19 20:26:55Z olli $ - -// The following configuration file is designed to work for CygWin -// platforms using GNU C++. - -#ifndef ACE_CONFIG_CYGWIN32_H -#define ACE_CONFIG_CYGWIN32_H - -#include /**/ "ace/pre.h" - -#if !defined (ACE_MT_SAFE) -#define ACE_MT_SAFE 1 -#endif - -#define CYGWIN32 - -// We trust this file will get included before -#if !defined(FD_SETSIZE) -# define FD_SETSIZE 1024 -#endif - -#if !defined (ACE_IOV_MAX) -# define ACE_IOV_MAX 64 -#endif /* ACE_IOV_MAX */ - -// Define custom export macros for export/import of symbols from/of dll's -#if !defined (ACE_HAS_CUSTOM_EXPORT_MACROS) -# define ACE_HAS_CUSTOM_EXPORT_MACROS 1 -# define ACE_Proper_Export_Flag __declspec (dllexport) -# define ACE_Proper_Import_Flag __declspec (dllimport) -# define ACE_EXPORT_SINGLETON_DECLARATION(T) template class __declspec (dllexport) T -# define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) template class __declspec (dllexport) SINGLETON_TYPE; -# define ACE_IMPORT_SINGLETON_DECLARATION(T) extern template class T -# define ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) extern template class SINGLETON_TYPE ; -#endif - -#define ACE_HAS_SELECT_H - -#define ACE_LACKS_PRAGMA_ONCE - -#if ! defined (__ACE_INLINE__) -# define __ACE_INLINE__ -#endif /* ! __ACE_INLINE__ */ - -#include /**/ - -// Needed to differentiate between libc 5 and libc 6 (aka glibc). -// It's there on all libc 5 systems I checked. -#include /**/ - -// config-g++-common.h undef's ACE_HAS_STRING_CLASS with -frepo, so -// this must appear before its #include. -#define ACE_HAS_STRING_CLASS - -#if defined (__GNUG__) -# include "ace/config-g++-common.h" -#else -# ifdef __cplusplus /* Let it slide for C compilers. */ -# error unsupported compiler in ace/config-cygwin32.h -# endif /* __cplusplus */ -#endif /* __GNUG__ */ - -#define ACE_HAS_VOIDPTR_SOCKOPT 1 -#define ACE_HAS_UALARM 1 -#define ACE_HAS_STRNLEN 1 -#define ACE_HAS_POSIX_GETPWNAM_R 1 -#define ACE_HAS_POSIX_NONBLOCK 1 -#define ACE_HAS_POSIX_TIME -#define ACE_HAS_CLOCK_GETTIME 1 -#define ACE_HAS_TIMEZONE_GETTIMEOFDAY -#define ACE_HAS_MSG -#define ACE_DEFAULT_BASE_ADDR ((char *) 0x8000000) -#define ACE_HAS_NONCONST_SELECT_TIMEVAL -#define ACE_HAS_SVR4_DYNAMIC_LINKING -//#define ACE_HAS_SYSV_IPC -#define ACE_HAS_VOIDPTR_MMAP -#define ACE_HAS_CPLUSPLUS_HEADERS -#define ACE_HAS_POLL -#define ACE_HAS_POSITION_INDEPENDENT_POINTERS 1 -#define ACE_HAS_SOCKADDR_MSG_NAME 1 -#define ACE_LACKS_PRI_T 1 -#define ACE_HAS_3_PARAM_READDIR_R - -// Compiler/platform supports alloca(). -// Although ACE does have alloca() on this compiler/platform combination, it is -// disabled by default since it can be dangerous. Uncomment the following line -// if you want ACE to use it. -//#define ACE_HAS_ALLOCA - -// Compiler/platform has the getrusage() system call. -#define ACE_HAS_GETRUSAGE - -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES - -// Optimize ACE_Handle_Set for select(). -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT - -#define ACE_HAS_IP_MULTICAST - -#define ACE_HAS_BIG_FD_SET - -// Platform has POSIX terminal interface. -#define ACE_HAS_TERMIOS - -#define ACE_DEFAULT_MAX_SOCKET_BUFSIZ 65535 - -#define ACE_DEFAULT_SELECT_REACTOR_SIZE 256 - -#define ACE_HAS_GETPAGESIZE - -#define ACE_HAS_VOIDPTR_GETTIMEOFDAY - -#define ACE_HAS_STRSIGNAL - -// Compiler supports the ssize_t typedef. -#define ACE_HAS_SSIZE_T - -#define ACE_HAS_SOCKLEN_T 1 - -#define ACE_HAS_GPERF - -#define ACE_HAS_DIRENT -#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG - -#define ACE_LACKS_MKFIFO -#define ACE_LACKS_SIGINFO_H -#define ACE_LACKS_UCONTEXT_H -#define ACE_LACKS_STROPTS_H -#define ACE_LACKS_FGETWC 1 -#define ACE_LACKS_NAMED_POSIX_SEM -#define ACE_LACKS_STRRECVFD -#define ACE_LACKS_MADVISE -#define ACE_LACKS_GETPGID_PROTOTYPE -#define ACE_LACKS_GETHOSTENT -#define ACE_LACKS_ITOW 1 -#define ACE_LACKS_LINEBUFFERED_STREAMBUF 1 -#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS 1 -#define ACE_LACKS_RLIMIT -#define ACE_LACKS_RWLOCK_T 1 -#define ACE_LACKS_SUSECONDS_T -#define ACE_LACKS_SYS_SYSCTL_H - -#define ACE_LACKS_FGETWS 1 -#define ACE_LACKS_FPUTWS 1 - -#define ACE_LACKS_WCSTOULL 1 -#define ACE_LACKS_ISCTYPE - -#define ACE_HAS_AUTOMATIC_INIT_FINI - -#define ACE_HAS_SIGWAIT -#define ACE_HAS_SIGINFO_T -#define ACE_HAS_SIGACTION_CONSTP2 -#define ACE_HAS_SIGSUSPEND -#define ACE_HAS_SIG_C_FUNC 1 -#define ACE_HAS_SIG_ATOMIC_T - -#define ACE_HAS_POSIX_SEM - -#define ACE_HAS_P_READ_WRITE - -#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R - -// Cygwin DLL suffix is .dll -#define ACE_DLL_SUFFIX ACE_TEXT (".dll") - -// Cygwin runs on Windows, so we have to get the environment variable PATH and -// not LD_LIBRARY_PATH which is the default in ACE -#define ACE_LD_SEARCH_PATH ACE_TEXT ("PATH") - -#if ACE_MT_SAFE -// Yes, we do have threads. -# define ACE_HAS_THREADS -// And they're even POSIX pthreads (LinuxThreads implementation) -# define ACE_HAS_PTHREADS - -# define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS - -// Compiler/platform has thread-specific storage -# define ACE_HAS_THREAD_SPECIFIC_STORAGE - -# define ACE_HAS_PTHREADS_UNIX98_EXT -# define ACE_HAS_PTHREAD_CONTINUE 1 -# define ACE_HAS_PTHREAD_SUSPEND 1 - -# define ACE_LACKS_PTHREAD_ATTR_SETSTACKADDR -// Cygwin (see pthread.h): Not supported or implemented. -# define ACE_LACKS_SETSCHED -# define ACE_LACKS_SETDETACH -# define ACE_LACKS_PTHREAD_CANCEL -# define ACE_LACKS_THREAD_PROCESS_SCOPING -# define ACE_LACKS_MUTEXATTR_PSHARED -# define ACE_LACKS_RWLOCKATTR_PSHARED -# define ACE_LACKS_PTHREAD_THR_SIGSETMASK 1 -# define ACE_LACKS_PTHREAD_YIELD 1 -# define ACE_LACKS_PTHREAD_ATTR_SETSTACK - -#if CYGWIN_VERSION_API_MINOR < 207 -// In the 1.5.9 release of Cygwin the pthread_kill gives an access violation -// so for the time being we say Cygwin doesn't support pthread_kill. -# define ACE_LACKS_PTHREAD_KILL -#endif - -#endif /* ACE_MT_SAFE */ - -#if CYGWIN_VERSION_API_MINOR >= 207 -// > Cygwin 1.7 -#define ACE_HAS_VWPRINTF -#define ACE_HAS_VFWPRINTF -#define ACE_HAS_VSWPRINTF -#endif - -#include /**/ "ace/post.h" - -#endif /* ACE_CONFIG_CYGWIN32_H */ diff --git a/externals/ace/config-doxygen.h b/externals/ace/config-doxygen.h deleted file mode 100644 index ddd84e88e7a..00000000000 --- a/externals/ace/config-doxygen.h +++ /dev/null @@ -1,128 +0,0 @@ -// -*- C++ -*- - -/** - * This is a configuration file to define all the macros that Doxygen - * needs - * - * @file config-doxygen.h - * - * $Id: config-doxygen.h 91101 2010-07-15 09:49:28Z johnnyw $ - * - * @author Carlos O'Ryan - * @author Darrell Brunsch - * - */ -#ifndef ACE_CONFIG_DOXYGEN_H -#define ACE_CONFIG_DOXYGEN_H - -/// Make sure that we always turn inlining on. -#define __ACE_INLINE__ - -/// Make the wchar_t interfaces available. -#define ACE_HAS_WCHAR - -/// Make all the emulation versions of string operations visible -// #define ACE_LACKS_WCSTOK -#define ACE_LACKS_ITOW -#define ACE_LACKS_STRCASECMP -#define ACE_LACKS_STRRCHR -#define ACE_LACKS_WCSCAT -#define ACE_LACKS_WCSCHR -#define ACE_LACKS_WCSCMP -#define ACE_LACKS_WCSCPY -#define ACE_LACKS_WCSICMP -#define ACE_LACKS_WCSLEN -#define ACE_LACKS_WCSNCAT -#define ACE_LACKS_WCSNCMP -#define ACE_LACKS_WCSNCPY -#define ACE_LACKS_WCSNICMP -#define ACE_LACKS_WCSPBRK -#define ACE_LACKS_WCSRCHR -#define ACE_LACKS_WCSCSPN -#define ACE_LACKS_WCSSPN -#define ACE_LACKS_WCSSTR - -/// Support for threads enables several important classes -#define ACE_HAS_THREADS - -/// Support for Win32 enables the WFMO_Reactor and several Async I/O -/// classes -#define ACE_WIN32 - -/// Enable support for POSIX Asynchronous I/O calls -#define ACE_HAS_AIO_CALLS - -/// Enable support for TLI interfaces -#define ACE_HAS_TLI - -/// Enable support for the SSL wrappers -#define ACE_HAS_SSL 1 - -/// Enable exceptions -#define ACE_HAS_EXCEPTIONS - -/// Enable timeprobes -#define ACE_COMPILE_TIMEPROBES - -/// Enable unicode to generate ACE_Registry_Name_Space -#define UNICODE - -/// These defines make sure that Svc_Conf_y.cpp and Svc_Conf_l.cpp are correctly -/// parsed -#define __cplusplus -#define ACE_YY_USE_PROTOS - -/// TAO features that should be documented too -#define TAO_HAS_RT_CORBA 1 -#define TAO_HAS_MINIMUM_CORBA 0 -#define TAO_HAS_AMI 1 -#define TAO_HAS_INTERCEPTORS 1 -#define TAO_HAS_SCIOP 1 -#define TAO_HAS_COIOP 1 -#define TAO_HAS_TRANSPORT_CURRENT 1 - -/// Generate token library documentation -#define ACE_HAS_TOKENS_LIBRARY - -/// Generate ACE ATM classes documentation -#define ACE_HAS_ATM - -/// Generate ACE XTI ATM class documentation -#define ACE_HAS_XTI_ATM - -/// Generate ACE_Dev_Poll_Reactor documentation -#define ACE_HAS_DEV_POLL - -/// Generate ACE_Event_Handler_T documentation -#define ACE_HAS_TEMPLATE_TYPEDEFS - -/// Generate ACE_Log_Msg_NT_Event_Log documentation -#define ACE_HAS_LOG_MSG_NT_EVENT_LOG - -/// Generate icmp documentation -#define ACE_HAS_ICMP_SUPPORT 1 - -/// Don't expand ACE_RCSID macro -#define ACE_USE_RCSID 0 - -/// Parse some ACE_SSL classes that depend on recent versions of -/// OpenSSL. -#define OPENSSL_VERSION_NUMBER 0x00905820L - -/// Enable IPv6 -#define ACE_HAS_IPV6 - -/// Enable netlink socket support -#define ACE_HAS_NETLINK - -#define ACE_HAS_IP_MULTICAST - -#define ACE_INLINE -#define ACE_BEGIN_VERSIONED_NAMESPACE_DECL -#define ACE_END_VERSIONED_NAMESPACE_DECL -#define TAO_BEGIN_VERSIONED_NAMESPACE_DECL -#define TAO_END_VERSIONED_NAMESPACE_DECL - -#define ACE_HAS_POSITION_INDEPENDENT_POINTERS 1 - -#endif /* ACE_CONFIG_DOXYGEN_H */ diff --git a/externals/ace/config-freebsd.h b/externals/ace/config-freebsd.h deleted file mode 100644 index b83394ddece..00000000000 --- a/externals/ace/config-freebsd.h +++ /dev/null @@ -1,215 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-freebsd.h 87483 2009-11-11 13:50:04Z olli $ - -// The following configuration file is designed to work for FreeBSD - -#ifndef ACE_CONFIG_H -#define ACE_CONFIG_H -#include /**/ "ace/pre.h" - -#if !defined (ACE_MT_SAFE) -# define ACE_MT_SAFE 1 -#endif - -#if ACE_MT_SAFE - // Yes, we do have threads. -# define ACE_HAS_THREADS 1 -#else - // Set to 0 since that's what config-posix.h checks for. -# define ACE_HAS_THREADS 0 -#endif /* ACE_MT_SAFE */ - -#include "ace/config-posix.h" - -// Make sure we source in the OS version. -#include - -#if !defined (__ACE_INLINE__) -# define __ACE_INLINE__ -#endif /* ! __ACE_INLINE__ */ - -#if (__FreeBSD_version < 220000) -# if defined (ACE_HAS_THREADS) -# error Threads are not supported. -# endif /* ACE_HAS_THREADS */ -#endif /* __FreeBSD_version < 220000 */ - -#if defined (__GNUG__) -# include "ace/config-g++-common.h" -#endif /* __GNUG__ */ - -#if defined (ACE_HAS_PENTIUM) -# undef ACE_HAS_PENTIUM -#endif /* ACE_HAS_PENTIUM */ - -// Platform specific directives -// gcc defines __FreeBSD__ automatically for us. -#ifdef ACE_HAS_THREADS -# if !defined (_THREAD_SAFE) -# define _THREAD_SAFE -# endif /* _THREAD_SAFE */ -#endif - - -#define ACE_HAS_3_PARAM_READDIR_R -#define ACE_HAS_3_PARAM_WCSTOK -#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG -#define ACE_HAS_ALLOCA -#define ACE_HAS_ALT_CUSERID -#define ACE_HAS_AUTOMATIC_INIT_FINI -#define ACE_HAS_CHARPTR_DL -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES -#define ACE_HAS_DIRENT -#define ACE_HAS_GETRUSAGE -#define ACE_HAS_GPERF -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT -#define ACE_HAS_IP_MULTICAST -#define ACE_HAS_MSG -#define ACE_HAS_NONCONST_SELECT_TIMEVAL -#define ACE_HAS_POSIX_NONBLOCK -#define ACE_HAS_POSIX_TIME -#define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS -#define ACE_HAS_RTLD_LAZY_V -#define ACE_HAS_SEMUN -#define ACE_HAS_SIGISMEMBER_BUG -#define ACE_HAS_SIGSUSPEND -#define ACE_HAS_SIGWAIT -#define ACE_HAS_SIG_ATOMIC_T -#define ACE_HAS_SOCKADDR_IN6_SIN6_LEN -#define ACE_HAS_SOCKADDR_IN_SIN_LEN -#define ACE_HAS_SSIZE_T -#define ACE_HAS_STRSIGNAL -#define ACE_HAS_SVR4_DYNAMIC_LINKING -#define ACE_HAS_SVR4_SIGNAL_T -#define ACE_HAS_SYSCTL -#define ACE_HAS_SYSV_IPC -#define ACE_HAS_SYS_FILIO_H -#define ACE_HAS_SYS_SOCKIO_H -#define ACE_HAS_SYS_SYSCALL_H -#define ACE_HAS_TERMIOS -#define ACE_HAS_THREAD_SPECIFIC_STORAGE -#define ACE_HAS_TIMEZONE_GETTIMEOFDAY -#define ACE_HAS_UALARM - -#define ACE_LACKS_CONDATTR_PSHARED -#define ACE_LACKS_ISCTYPE -#define ACE_LACKS_ITOW -#define ACE_LACKS_LOG2 -#define ACE_LACKS_MALLOC_H -#define ACE_LACKS_MUTEXATTR_PSHARED -#define ACE_LACKS_SIGINFO_H -#define ACE_LACKS_SI_ADDR -#define ACE_LACKS_STROPTS_H -#define ACE_LACKS_STRRECVFD -#define ACE_LACKS_THREAD_PROCESS_SCOPING -#define ACE_LACKS_TIMESPEC_T -#define ACE_LACKS_WCSDUP -#define ACE_LACKS_WCSICMP -#define ACE_LACKS_WCSNICMP - -#define ACE_NEEDS_SCHED_H - -// Defines the page size of the system. -#define ACE_PAGE_SIZE 4096 - -// Note, on FreeBSD 5, POSIX aio is now an optional kernel module which -// must be loaded. -// Read the aio(4) man page for what to do, otherwise any aio_* call -// will coredump. - -// By default use Proactor which does not use POSIX Real-time Signals. -#ifdef ACE_HAS_AIO_CALLS -# ifndef ACE_POSIX_AIOCB_PROACTOR -# define ACE_POSIX_AIOCB_PROACTOR -# endif /* ACE_POSIX_AIOCB_PROACTOR */ -#endif /* ACE_HAS_AIO_CALLS */ - -#if !defined ACE_LACKS_PERFECT_MULTICAST_FILTERING -# define ACE_LACKS_PERFECT_MULTICAST_FILTERING 1 -#endif /* ACE_LACKS_PERFECT_MULTICAST_FILTERING */ - -// -// Version specific settings -// - -#if (__FreeBSD_version >= 220000) -# define ACE_HAS_VASPRINTF -#endif - -#if (__FreeBSD_version >= 300000) -# define ACE_HAS_SIGINFO_T -#endif /* __FreeBSD_version >= 300000 */ - -#if (__FreeBSD_version >= 320000) -# define ACE_HAS_REENTRANT_FUNCTIONS -# define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS -# define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R -#endif /* __FreeBSD_version >= 320000 */ - -#if (__FreeBSD_version > 400000) -# define ACE_HAS_UCONTEXT_T -# define ACE_HAS_SOCKLEN_T -# define ACE_HAS_GETIFADDRS -# define ACE_HAS_PTHREADS_UNIX98_EXT -#endif - -#if (__FreeBSD_version < 400000) -# define ACE_LACKS_SIGSET -# define ACE_LACKS_RWLOCK_T -# define ACE_LACKS_READDIR_R -# define ACE_LACKS_SETSCHED -# define ACE_LACKS_PTHREAD_THR_SIGSETMASK -# define ACE_LACKS_UCONTEXT_H -# define ACE_LACKS_RAND_REENTRANT_FUNCTIONS - -enum schedparam_policy { - SCHED_RR, - SCHED_IO, - SCHED_FIFO, - SCHED_OTHER -}; -#endif - -#if (__FreeBSD_version < 420000) -# define ACE_LACKS_GETPGID -# define ACE_LACKS_SETPGID -# define ACE_LACKS_SETREGID -# define ACE_LACKS_SETREUID -# define ACE_LACKS_PTHREAD_CANCEL -#endif /* __FreeBSD_version < 420000 */ - -#if (__FreeBSD_version >= 440000) -# define ACE_HAS_GETPROGNAME -# define ACE_HAS_SETPROGNAME -#endif - -#if (__FreeBSD_version < 500100) -# define ACE_HAS_NONCONST_MSGSND -#endif - -#if (__FreeBSD_version < 501000) -# define ACE_LACKS_STDINT_H -# define ACE_LACKS_PWD_REENTRANT_FUNCTIONS -#endif - -#if (__FreeBSD_version >= 501000) -# define ACE_HAS_PTHREAD_SETSTACK -#endif - -#if (__FreeBSD_version < 700007) -# define ACE_HAS_SIGVAL_SIGVAL_INT -# define ACE_HAS_BROKEN_SIGEVENT_STRUCT -#endif - -#if (__FreeBSD_version >= 700028) -# define ACE_HAS_SCTP -# define ACE_HAS_LKSCTP -#endif - -#if (__FreeBSD_version < 700038) -# define ACE_HAS_VOID_UNSETENV -#endif - -#include /**/ "ace/post.h" - -#endif /* ACE_CONFIG_H */ diff --git a/externals/ace/config-g++-common.h b/externals/ace/config-g++-common.h deleted file mode 100644 index dc010182a70..00000000000 --- a/externals/ace/config-g++-common.h +++ /dev/null @@ -1,183 +0,0 @@ -// -*- C++ -*- -// -// $Id: config-g++-common.h 89454 2010-03-11 09:35:25Z johnnyw $ - -// This configuration file is designed to be included by another, -// specific configuration file. It provides config information common -// to all g++ platforms, including egcs. - -#ifndef ACE_GNUG_COMMON_H -#define ACE_GNUG_COMMON_H -#include /**/ "ace/pre.h" - -#define ACE_HAS_CPLUSPLUS_HEADERS -#define ACE_HAS_STDCPP_STL_INCLUDES -#define ACE_HAS_TEMPLATE_TYPEDEFS -#define ACE_HAS_STANDARD_CPP_LIBRARY 1 -#define ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR -#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 -#define ACE_TEMPLATES_REQUIRE_SOURCE - -#if ( __GNUC__ == 2 && __GNUC_MINOR__ < 97 ) - // gcc 2.97 and lower use old iostreams -# define ACE_USES_OLD_IOSTREAMS -#endif /* __GNUC__ >= 2.97 */ - -#if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) -# define ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS -#endif /* __GNUC__ >= 3.4 */ - -#if (__GNUC__ < 3) -# define ACE_LACKS_MEMBER_TEMPLATES -# define ACE_LACKS_NUMERIC_LIMITS -#endif /* __GNUC__ < 3 */ - -// __EXCEPTIONS is defined with -fexceptions, the egcs default. It -// is not defined with -fno-exceptions, the ACE default for g++. -// ACE_HAS_EXCEPTIONS is defined in -// include/makeinclude/wrapper_macros.GNU, so this really isn't -// necessary. Just in case . . . -#if defined (__EXCEPTIONS) && !defined (ACE_HAS_EXCEPTIONS) -# define ACE_HAS_EXCEPTIONS -#endif /* __EXCEPTIONS && ! ACE_HAS_EXCEPTIONS */ - -#if defined (ACE_HAS_EXCEPTIONS) -# define ACE_NEW_THROWS_EXCEPTIONS -# if (__GNUC__ >= 4 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 3)) -// Versions of g++ prior to 3.3 had a buggy operator // new(nothrow)[](). -# define ACE_HAS_NEW_NOTHROW -# endif /* __GNUC__ >= 3.3 */ -#endif /* ACE_HAS_EXCEPTIONS */ - -#if (defined (i386) || defined (__i386__)) && !defined (ACE_SIZEOF_LONG_DOUBLE) -# define ACE_SIZEOF_LONG_DOUBLE 12 -#endif /* i386 */ - -#if !defined (__MINGW32__) && (defined (i386) || defined (__i386__)) - // If running an Intel, assume that it's a Pentium so that - // ACE_OS::gethrtime () can use the RDTSC instruction. If running a - // 486 or lower, be sure to comment this out. (If not running an - // Intel CPU, this #define will not be seen because of the i386 - // protection, so it can be ignored.) -# define ACE_HAS_PENTIUM -#endif /* i386 */ - -#if (defined (ACE_HAS_PENTIUM) || defined (__amd64__) || defined (__x86_64__)) -# define ACE_HAS_INTEL_ASSEMBLY -#endif - -#if !defined (ACE_HAS_GCC_CONSTRUCTOR_ATTRIBUTE) -#define ACE_HAS_GCC_CONSTRUCTOR_ATTRIBUTE 1 -#endif - -#if !defined (ACE_HAS_GCC_DESTRUCTOR_ATTRIBUTE) -#define ACE_HAS_GCC_DESTRUCTOR_ATTRIBUTE 1 -#endif - -#if !defined (ACE_HAS_GCC_DEPRECATED_ATTRIBUTE) -#define ACE_HAS_GCC_DEPRECATED_ATTRIBUTE 1 -#endif - -#if (ACE_HAS_GCC_CONSTRUCTOR_ATTRIBUTE == 1) -# define ACE_GCC_CONSTRUCTOR_ATTRIBUTE __attribute__ ((constructor)) -#endif - -#if (ACE_HAS_GCC_DESTRUCTOR_ATTRIBUTE == 1) -# define ACE_GCC_DESTRUCTOR_ATTRIBUTE __attribute__ ((destructor)) -#endif - -#if (ACE_HAS_GCC_DEPRECATED_ATTRIBUTE == 1) -#define ACE_DEPRECATED __attribute__ ((deprecated)) -#endif - -// GNU g++ >= 4.x implements "#pragma once". -#if (__GNUC__ < 4) && !defined (ACE_LACKS_PRAGMA_ONCE) -// We define it with a -D with make depend. -# define ACE_LACKS_PRAGMA_ONCE -#endif /* ! ACE_LACKS_PRAGMA_ONCE */ - -// Take advantage of G++ (>= 4.x) visibility attributes to generate -// improved shared library binaries. -#if (__GNUC__ >= 4) && !defined (__MINGW32__) && !defined (ACE_HAS_CEGCC) - -# if defined (ACE_HAS_CUSTOM_EXPORT_MACROS) && ACE_HAS_CUSTOM_EXPORT_MACROS == 0 -# undef ACE_HAS_CUSTOM_EXPORT_MACROS -# if defined (ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS) -# undef ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS -# endif /* ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS */ -# define ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS 0 -# else -# ifndef ACE_HAS_CUSTOM_EXPORT_MACROS -# define ACE_HAS_CUSTOM_EXPORT_MACROS -# endif /* !ACE_HAS_CUSTOM_EXPORT_MACROS */ -# define ACE_Proper_Export_Flag __attribute__ ((visibility("default"))) -# define ACE_Proper_Import_Flag __attribute__ ((visibility("default"))) - -# if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 2)) -// Sadly, G++ 4.x silently ignores visibility attributes on -// template instantiations, which breaks singletons. -// As a workaround, we use the GCC visibility pragmas. -// And to make them fit in a macro, we use C99's _Pragma() -// http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17470 -// This has been fixed in GCC 4.1.1 with FC6 but not with SuSE 10.2 -// that gets shipped with GCC 4.1.2 so we assume that with GCC 4.2 -// this will be fixed on the head. With FC6 just set this define yourself -# ifndef ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS -# define ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS 1 -# endif -# endif - -# if defined (ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS) && ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS == 1 -# define ACE_EXPORT_SINGLETON_DECLARATION(T) template class ACE_Proper_Export_Flag T -# define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) template class ACE_Proper_Export_Flag SINGLETON_TYPE ; -# else /* ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS */ -# define ACE_EXPORT_SINGLETON_DECLARATION(T) \ - _Pragma ("GCC visibility push(default)") \ - template class T \ - _Pragma ("GCC visibility pop") -# define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) \ - _Pragma ("GCC visibility push(default)") \ - template class SINGLETON_TYPE; \ - _Pragma ("GCC visibility pop") -# endif /* ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS */ - -// Note that the "__extension__" is needed to prevent g++ from issuing -// an error when using its "-pedantic" command line flag. -# define ACE_IMPORT_SINGLETON_DECLARATION(T) __extension__ extern template class T -# define ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) __extension__ extern template class SINGLETON_TYPE; - -# endif /* ACE_HAS_CUSTOM_EXPORT_MACROS == 0 */ -#endif /* __GNU__ >= 4 */ - -// GCC >= 4.1 provides __sync_XXXX builtins for use in atomic operations -// although the builtins are provided globally they are not supported on all platforms -#if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 1)) -# if defined (__powerpc__) -// The builtins seem to be provided for all powerpc platforms -# define ACE_HAS_GCC_ATOMIC_BUILTINS 1 -# if ((__GNUC__ == 4) && (__GNUC_MINOR__ == 1) && (__GNUC_PATCHLEVEL__ == 1)) -// PPU GCC 4.1.1 doesn't have builtin atomic ops for size 1/2 -# define ACE_LACKS_GCC_ATOMIC_BUILTINS_2 -# define ACE_LACKS_GCC_ATOMIC_BUILTINS_1 -# endif -# endif -# if defined (__ia64) -// The builtins seem to be provided for the IA64 platforms -# define ACE_HAS_GCC_ATOMIC_BUILTINS 1 -# endif -# if defined (__amd64__) || defined (__x86_64__) -// The builtin's are provided also for 64bit linux -# define ACE_HAS_GCC_ATOMIC_BUILTINS 1 -# endif -#endif - -#if defined (ACE_HAS_GNU_REPO) - // -frepo causes unresolved symbols of basic_string left- and - // right-shift operators with ACE_HAS_STRING_CLASS. -# if defined (ACE_HAS_STRING_CLASS) -# undef ACE_HAS_STRING_CLASS -# endif /* ACE_HAS_STRING_CLASS */ -#endif /* ! ACE_HAS_GNU_REPO */ - -#include /**/ "ace/post.h" -#endif /* ACE_GNUG_COMMON_H */ diff --git a/externals/ace/config-ghs-common.h b/externals/ace/config-ghs-common.h deleted file mode 100644 index ffa554c047e..00000000000 --- a/externals/ace/config-ghs-common.h +++ /dev/null @@ -1,43 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-ghs-common.h 80826 2008-03-04 14:51:23Z wotte $ - -// This configuration file is designed to be included by another, -// specific configuration file. It provides config information common -// to all Green Hills platforms. - -#ifndef ACE_GHS_COMMON_H -#define ACE_GHS_COMMON_H -#include /**/ "ace/pre.h" - -#if !defined (ACE_CONFIG_INCLUDE_GHS_COMMON) -# error ace/config-ghs-common.h: ACE configuration error! Do not #include this file directly! -#endif - -#if defined (ghs) - -# if defined (sun) - // Need nonstatic Object_Manager on Solaris to prevent seg fault - // on startup. -# define ACE_HAS_NONSTATIC_OBJECT_MANAGER -# endif /* sun */ - -# if defined (__STANDARD_CXX) - // Green Hills 1.8.9, but not 1.8.8. -# define ACE_HAS_STANDARD_CPP_LIBRARY 1 -# define ACE_LACKS_AUTO_PTR -# define ACE_LACKS_CHAR_RIGHT_SHIFTS -# define ACE_LACKS_UNBUFFERED_STREAMBUF -# else -# define ACE_HAS_TEMPLATE_INSTANTIATION_PRAGMA -# endif /* __STANDARD_CXX */ - -# define ACE_LACKS_LINEBUFFERED_STREAMBUF -# define ACE_LACKS_LONGLONG_T -# define ACE_LACKS_SIGNED_CHAR - -#else /* ! ghs */ -# error ace/config-ghs-common.h can only be used with Green Hills compilers! -#endif /* ! ghs */ - -#include /**/ "ace/post.h" -#endif /* ACE_GHS_COMMON_H */ diff --git a/externals/ace/config-hpux-11.00.h b/externals/ace/config-hpux-11.00.h deleted file mode 100644 index 82420f210f3..00000000000 --- a/externals/ace/config-hpux-11.00.h +++ /dev/null @@ -1,451 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-hpux-11.00.h 89494 2010-03-15 20:11:18Z olli $ - -// The following configuration file is designed to work for HP -// platforms running HP-UX 11.00 using aC++ or gcc (2.95 and up). - -#ifndef ACE_CONFIG_H -#define ACE_CONFIG_H -#include /**/ "ace/pre.h" - -#define ACE_LACKS_STDINT_H -#define ACE_LACKS_SYS_SELECT_H - -#if defined (__GNUG__) - -// config-g++-common.h undef's ACE_HAS_STRING_CLASS with -frepo, so -// this must appear before its #include. -# define ACE_HAS_STRING_CLASS - -# include "ace/config-g++-common.h" - -#else - -// aC++... - -// Precompiler needs extra flags to ignore "invalid #pragma directive" -# ifndef ACE_USING_MCPP_PREPROCESSOR -# define ACE_CC_PREPROCESSOR_ARGS "-E +W 67" -# endif -// Compiler supports C++ exception handling. It's on by default. If the -// +noeh compiler option is used to disable exceptions, the compiler defines -// __HPACC_NOEH. -# if !defined (__HPACC_NOEH) -# define ACE_HAS_EXCEPTIONS 1 -# endif - -// If the -AA compile option is used, the compiler defines _HP_NAMESPACE_STD. -// The -AA option enables the 2.0 standard C++ library. If not used, then -// we have the old, 1.2.1 C++ library. -# if defined (_HP_NAMESPACE_STD) -# if defined (ACE_HAS_STANDARD_CPP_LIBRARY) -# undef ACE_HAS_STANDARD_CPP_LIBRARY -# endif -# define ACE_HAS_STANDARD_CPP_LIBRARY 1 -# if defined (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB) -# undef ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB -# endif -# if defined (RWSTD_NO_NAMESPACE) - namespace std {} using namespace std; -# else -# define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 -# endif /* RWSTD_NO_NAMESPACE */ -# else -# define ACE_USES_OLD_IOSTREAMS - // There's no support in ACE's use of numeric_limits for those that - // aren't in std:: -# define ACE_LACKS_NUMERIC_LIMITS -# endif /* _HP_NAMESPACE_STD */ - -// Compiler implements templates that support typedefs inside of classes -// used as formal arguments to a template class. -# define ACE_HAS_TEMPLATE_TYPEDEFS - -# define ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR - -// Platform lacks streambuf "linebuffered ()". -# define ACE_LACKS_LINEBUFFERED_STREAMBUF 1 - -// Lack of (and broken) support for placement operator delete is a known -// bug by HP, up until aC++ A.03.55.02. -# if (__HP_aCC < 35502) -# define ACE_LACKS_PLACEMENT_OPERATOR_DELETE -# endif /* __HP_aCC < 35502 */ - -// Compiler's 'new' throws exceptions on failure, regardless of whether or -// not exception handling is enabled in the compiler options. Fortunately, -// new(nothrow_t) is offered. -# define ACE_NEW_THROWS_EXCEPTIONS -# define ACE_HAS_NEW_NOTHROW -# define ACE_HAS_NEW_NO_H 1 - -// Compiler's template mechanism must see source code (i.e., .C files). -# define ACE_TEMPLATES_REQUIRE_SOURCE - -// Compiler doesn't handle 'signed char' correctly (used in ace/IOStream.h) -# define ACE_LACKS_SIGNED_CHAR - -#endif /* __GNUG__, HP */ - -//********************************************************************* -// -// From here down is the compiler-INdependent OS settings. -// -//********************************************************************* - -// Compiling for HPUX. -#if !defined (HPUX) -#define HPUX -#endif /* HPUX */ -#define HPUX_11 - -#ifndef _HPUX_SOURCE -#define _HPUX_SOURCE -#endif - -#include /**/ - -// HP-UX is a POSIX-compliant system - see what's available. -#include "ace/config-posix.h" - -// config-posix.h sets up ACE_HAS_AIO_CALLS if the headers define the -// proper things. In HP-UX 11's case, the AIOCB Proactor works the best -// overall. If the user hasn't overridden it, select AIOCB. -#if defined (ACE_HAS_AIO_CALLS) -# if !defined (ACE_POSIX_AIOCB_PROACTOR) && !defined (ACE_POSIX_SIG_PROACTOR) -# define ACE_POSIX_AIOCB_PROACTOR -# endif /* !ACE_HAS_POSIX_AIOCB_PROACTOR && !ACE_POSIX_SIG_PROACTOR */ -#endif /* ACE_HAS_AIO_CALLS */ - -//////////////////////////////////////////////////////////////////////////// -// -// General OS information - see README for more details on what they mean -// -/////////////////////////////////////////////////////////////////////////// - -// HP/UX needs to have these addresses in a special range. -// If this is on a 64-bit model, the default is to use 64-bit addressing. -// It can also be set so that the mapped region is shareable with 32-bit -// programs. To enable the 32/64 sharing, comment out the first definition -// of ACE_DEFAULT_BASE_ADDR and uncomment the two lines after it. -#if defined (__LP64__) -# define ACE_DEFAULT_BASE_ADDR ((char *) 0x0000001100000000) -//# define ACE_DEFAULT_BASE_ADDR ((char *) 0x80000000) -//# define ACE_OS_EXTRA_MMAP_FLAGS MAP_ADDR32 - -# define ACE_DEFAULT_BASE_ADDRL (0x0000001100000000) -//# define ACE_DEFAULT_BASE_ADDRL (0x80000000) -#else -# define ACE_DEFAULT_BASE_ADDR ((char *) 0x80000000) -#endif /* __LP64__ */ - -// Preprocessor needs some help with data types -#if defined (__LP64__) -# define ACE_SIZEOF_LONG 8 -#else -# define ACE_SIZEOF_LONG 4 -#endif - -// Platform can do async I/O (aio_*) (set up in config-posix.h) -// ... but seems to require this in order to keep from hanging. Needs some -// investigation, maybe with HP. John Mulhern determined this value -// empirically. YMMV. If it does vary, set it up in your own config.h which -// then includes the ACE-supplied config. -#if !defined (ACE_INFINITE) -# define ACE_INFINITE 10000000 -#endif - -/* Compiler/platform correctly calls init()/fini() for shared libraries. */ -#define ACE_HAS_AUTOMATIC_INIT_FINI 1 - -// Manually tweak the malloc control block paddings to properly align -// things. -#define ACE_MALLOC_PADDING 16 -#define ACE_MALLOC_ALIGN 8 -#define ACE_PI_CONTROL_BLOCK_ALIGN_LONGS 3 - -// Compiler/platform contains the file. -#define ACE_HAS_SYS_SYSCALL_H - -#define ACE_HAS_SYS_PSTAT_H - -// But doesn't have a prototype for syscall() -#define ACE_LACKS_SYSCALL - -// Platform supports POSIX.1b clock_gettime () -#define ACE_HAS_CLOCK_GETTIME -#define ACE_HAS_CLOCK_SETTIME - -// Prototypes for both signal() and struct sigaction are consistent. -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES - -// Compiler/platform has correctly prototyped header files. -#define ACE_HAS_CPLUSPLUS_HEADERS - -// Compiler/platform has Dirent iterator functions. -#define ACE_HAS_DIRENT - -#define ACE_HAS_VSWPRINTF - -// Platform supports getpagesize() call -#define ACE_HAS_GETPAGESIZE -// But we define this just to be safe -#define ACE_PAGE_SIZE 4096 - -// Can run gperf on this platform (needed for TAO) -# define ACE_HAS_GPERF - -// Optimize ACE_Handle_Set for select(). -# define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT - -// Platform supports IP multicast -#define ACE_HAS_IP_MULTICAST -// At least for 11iv2, lacks perfect filtering. -#if (HPUX_VERS >= 1123) && !defined (ACE_LACKS_PERFECT_MULTICAST_FILTERING) -# define ACE_LACKS_PERFECT_MULTICAST_FILTERING 1 -#endif - -/* Platform defines MAP_FAILED as a long constant. */ -#define ACE_HAS_LONG_MAP_FAILED 1 - -// Platform supports recvmsg and sendmsg. -#define ACE_HAS_MSG - -// Platform's select() has non-const timeval argument -#define ACE_HAS_NONCONST_SELECT_TIMEVAL - -// Compiler/platform supports poll(). -#define ACE_HAS_POLL - -/* Platform supports "position-independent" features provided by - ACE_Based_Pointer<>. */ -#define ACE_HAS_POSITION_INDEPENDENT_POINTERS 1 - -/* Platform supports POSIX getpwnam_r() function */ -#define ACE_HAS_POSIX_GETPWNAM_R 1 - -// Platform supports POSIX O_NONBLOCK semantics. -#define ACE_HAS_POSIX_NONBLOCK - -// Platform supports the POSIX struct timespec type -#define ACE_HAS_POSIX_TIME - -/* Platform has pread() and pwrite() support. */ -#define ACE_HAS_P_READ_WRITE 1 - -/* Platform will recurse infinitely on thread exits from TSS cleanup routines - (e.g., AIX) */ -#define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS 1 - -// Platform supports reentrant functions (all the POSIX *_r functions). -#define ACE_HAS_REENTRANT_FUNCTIONS -// ctime_r and asctime_r conform to POSIX.1c (2 param version) -#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R - -// Platform offers scandir(), and requires no adjustments for its API. -#define ACE_HAS_SCANDIR - -// HP-UX 11 has reentrant netdb functions. The catch is that the old -// functions (gethostbyname, etc.) are thread-safe and the _r versions are -// not used and will be removed at some point. So, define things so -// the _r versions are not used. This will slow things down a bit due to -// the extra mutex lock in the ACE_NETDBCALL_RETURN macro, and will be fixed -// in the future (problem ID P64). -#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS - -/* Platform lacks pri_t (e.g., Tandem NonStop UNIX). */ -#define ACE_LACKS_PRI_T 1 - -// Platform has shm_open -#define ACE_HAS_SHM_OPEN - -// Compiler/platform defines the sig_atomic_t typedef -#define ACE_HAS_SIG_ATOMIC_T - -/* Compiler requires extern "C" functions for signals. */ -#define ACE_HAS_SIG_C_FUNC 1 - -// Platform's sigaction() function takes const sigaction* as 2nd parameter. -#define ACE_HAS_SIGACTION_CONSTP2 - -#define ACE_HAS_SSIZE_T - -// Platform supports SVR4 extended signals -#define ACE_HAS_SIGINFO_T - -/* Define to 1 if platform has sigsuspend(). */ -#define ACE_HAS_SIGSUSPEND 1 - -// Platform doesn't detect a signal out of range unless it's way out of range. -#define ACE_HAS_SIGISMEMBER_BUG - -/* Platform provides socklen_t type, such as Linux with glibc2. */ -#define ACE_HAS_SOCKLEN_T 1 - -#define ACE_HAS_XPG4_MULTIBYTE_CHAR - -#define ACE_HAS_UALARM - -// Platform supports ucontext_t (which is used in the extended signal API). -#define ACE_HAS_UCONTEXT_T - -// Platform/compiler supports void * as second parameter to gettimeofday(). -#define ACE_HAS_VOIDPTR_GETTIMEOFDAY - -/* Platform requires void * for mmap(). */ -#define ACE_HAS_VOIDPTR_MMAP 1 - -/* OS/compiler uses void * arg 4 setsockopt() rather than const char * */ -#define ACE_HAS_VOIDPTR_SOCKOPT 1 - -// Platform supports SVR4 dynamic linking semantics. -// When used, this requires -ldl on the ACE library link line. -#define ACE_HAS_SVR4_DYNAMIC_LINKING - -// Platform supports the getrusage() system call. -#define ACE_HAS_GETRUSAGE - -/* Define to 1 if platform has the declaration of getrusage(). */ -#define ACE_HAS_GETRUSAGE_PROTOTYPE 1 - -// Platform has the sigwait function in a header file -#define ACE_HAS_SIGWAIT -#define ACE_HAS_SIGTIMEDWAIT - -// Platform supports System V IPC (most versions of UNIX, but not Win32) -#define ACE_HAS_SYSV_IPC - -// accept() is thread-safe -#define ACE_HAS_THREAD_SAFE_ACCEPT - -// Platform lacks a typedef for timespec_t, but has struct timespec -#define ACE_LACKS_TIMESPEC_T - -// dlopen() takes a char* instead of const char* -#define ACE_HAS_CHARPTR_DL - -// lacks setegid and seteuid -#define ACE_LACKS_SETEGID -#define ACE_LACKS_SETEUID - -#define ACE_LACKS_SUSECONDS_T -#define ACE_LACKS_SYS_SYSCTL_H - -// @@ TODO: It looks like HP-UX provides strtoll, strtoull, wcstoll and -// wcstoull but some more work is needed to plug them in correctly. -#define ACE_LACKS_STRTOLL -#define ACE_LACKS_WCSTOLL -#define ACE_LACKS_STRTOULL -#define ACE_LACKS_WCSTOULL - -#define ACE_LACKS_ISWASCII - -#define ACE_LACKS_SETENV -#define ACE_LACKS_UNSETENV - -// Shared library name/path components -#if defined (__ia64) -# define ACE_DLL_SUFFIX ACE_TEXT (".so") -#else -# define ACE_DLL_SUFFIX ACE_TEXT (".sl") -#endif /* __ia64 */ -#if defined (__LP64__) -# define ACE_LD_SEARCH_PATH ACE_TEXT ("LD_LIBRARY_PATH") -#else -# define ACE_LD_SEARCH_PATH ACE_TEXT ("SHLIB_PATH") -#endif /* __LP64__ */ - -#if defined (_INCLUDE__STDC_A1_SOURCE) -# define ACE_HAS_3_PARAM_WCSTOK -#endif - -#define ACE_HAS_3_PARAM_READDIR_R - -#define ACE_LACKS_STRUCT_LIFNUM - -////////////////////////////////////////////////////////////////////////// -// -// STREAMS information -// -////////////////////////////////////////////////////////////////////////// - -// Platform supports STREAMS -#define ACE_HAS_STREAMS -// Compiler/platform supports struct strbuf. -#define ACE_HAS_STRBUF_T -// But the putmsg signature doesn't have it as const... -// Well, it really does, but it depends on preprocessor defines. -#define ACE_LACKS_CONST_STRBUF_PTR -/* Platform supports TLI timod STREAMS module */ -#define ACE_HAS_TIMOD_H 1 - -// Platform supports STREAM pipes -// This is possible, but not by default - need to rebuild the kernel to -// get them enabled - see pipe(2) and "STREAMS/UX for the HP 9000" -// #define ACE_HAS_STREAM_PIPES - -///////////////////////////////////////////////////////////////////////// -// -// TLI/XTI information -// -//////////////////////////////////////////////////////////////////////// - -// Platform supports XTI (includes TLI). -#define ACE_HAS_XTI -// HP-UX 11 conforms to the XPG4 spec, which ACE calls broken for the -// errmsg not being const... -#define ACE_HAS_BROKEN_T_ERROR -// The definitions of TCP_NODELAY and TCP_MAXSEG conflict between -// sys/xti.h and netinet/tcp.h. -#define ACE_HAS_CONFLICTING_XTI_MACROS -/* Platform provides header */ -#define ACE_HAS_SYS_XTI_H 1 - -///////////////////////////////////////////////////////////////////////// -// -// Threads information. -// -// Use of threads is controlled by the 'threads' argument to make. See -// include/makeinclude/platform_hpux_aCC.GNU for details. If it's not set, -// the default is to enable it, since kernel threads are always available -// on HP-UX 11, as opposed to 10.x where it was optional software. -// -//////////////////////////////////////////////////////////////////////// - -#if defined (ACE_HAS_THREADS) -# if (ACE_HAS_THREADS == 0) -# undef ACE_HAS_THREADS -# endif /* ACE_HAS_THREADS == 0 */ -#else -# define ACE_HAS_THREADS -#endif /* ACE_HAS_THREADS */ - -#if defined (ACE_HAS_THREADS) - -# if !defined (ACE_MT_SAFE) -# define ACE_MT_SAFE 1 -# endif - -// HP-UX doesn't define _POSIX_THREADS since it doesn't implement all -// features (lacks thread priority inheritance and protection), so -// config-posix.h doesn't get this one... -# define ACE_HAS_PTHREADS -# define ACE_HAS_PTHREADS_UNIX98_EXT -# define ACE_HAS_PTHREAD_CONTINUE -# define ACE_HAS_PTHREAD_RESUME_NP -# define ACE_HAS_PTHREAD_SUSPEND -# define ACE_HAS_RECURSIVE_MUTEXES -# define ACE_HAS_THREAD_SPECIFIC_STORAGE -# define ACE_LACKS_PTHREAD_ATTR_SETSTACK -#endif /* ACE_HAS_THREADS */ - -#define ACE_HAS_POSIX_SEM - -// Platform has POSIX terminal interface. -#define ACE_HAS_TERMIOS - -// gethostbyaddr does not handle IPv6-mapped-IPv4 addresses -#define ACE_HAS_BROKEN_GETHOSTBYADDR_V4MAPPED - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_H */ diff --git a/externals/ace/config-icc-common.h b/externals/ace/config-icc-common.h deleted file mode 100644 index 1ebd0c52ed7..00000000000 --- a/externals/ace/config-icc-common.h +++ /dev/null @@ -1,113 +0,0 @@ -// -*- C++ -*- -// -// $Id: config-icc-common.h 81935 2008-06-12 22:01:53Z jtc $ - -#ifndef ACE_LINUX_ICC_COMMON_H -#define ACE_LINUX_ICC_COMMON_H -#include /**/ "ace/pre.h" - -# define ACE_HAS_CPLUSPLUS_HEADERS -# define ACE_HAS_STDCPP_STL_INCLUDES -# define ACE_HAS_TEMPLATE_TYPEDEFS -# define ACE_HAS_STANDARD_CPP_LIBRARY 1 -# define ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR -# define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 -# define ACE_HAS_STRING_CLASS - -#if defined (ACE_HAS_CUSTOM_EXPORT_MACROS) && ACE_HAS_CUSTOM_EXPORT_MACROS == 0 -# undef ACE_HAS_CUSTOM_EXPORT_MACROS -# if defined (ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS) -# undef ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS -# endif /* ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS */ -# define ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS 0 -#else -# ifndef ACE_HAS_CUSTOM_EXPORT_MACROS -# define ACE_HAS_CUSTOM_EXPORT_MACROS -# endif /* !ACE_HAS_CUSTOM_EXPORT_MACROS */ -# define ACE_Proper_Export_Flag __attribute__ ((visibility("default"))) -# define ACE_Proper_Import_Flag __attribute__ ((visibility("default"))) - -# if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 2)) -// Sadly, G++ 4.x silently ignores visibility attributes on -// template instantiations, which breaks singletons. -// As a workaround, we use the GCC visibility pragmas. -// And to make them fit in a macro, we use C99's _Pragma() -// http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17470 -// This has been fixed in GCC 4.1.1 with FC6 but not with SuSE 10.2 -// that gets shipped with GCC 4.1.2 so we assume that with GCC 4.2 -// this will be fixed on the head. With FC6 just set this define yourself -# ifndef ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS -# define ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS 1 -# endif -# endif - -# if defined (ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS) && ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS == 1 -# define ACE_EXPORT_SINGLETON_DECLARATION(T) template class ACE_Proper_Export_Flag T -# define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) template class ACE_Proper_Export_Flag SINGLETON_TYPE ; -# else /* ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS */ -# define ACE_EXPORT_SINGLETON_DECLARATION(T) \ - _Pragma ("GCC visibility push(default)") \ - template class T \ - _Pragma ("GCC visibility pop") -# define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) \ - _Pragma ("GCC visibility push(default)") \ - template class SINGLETON_TYPE; \ - _Pragma ("GCC visibility pop") -# endif /* ACE_GCC_HAS_TEMPLATE_INSTANTIATION_VISIBILITY_ATTRS */ - -// Note that the "__extension__" is needed to prevent g++ from issuing -// an error when using its "-pedantic" command line flag. -# define ACE_IMPORT_SINGLETON_DECLARATION(T) __extension__ extern template class T -# define ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) __extension__ extern template class SINGLETON_TYPE; -#endif /* ACE_HAS_CUSTOM_EXPORT_MACROS == 0 */ - -// __EXCEPTIONS is defined with -fexceptions, the egcs default. It -// is not defined with -fno-exceptions, the ACE default for g++. -// ACE_HAS_EXCEPTIONS is defined in -// include/makeinclude/wrapper_macros.GNU, so this really isn't -// necessary. Just in case . . . -# if defined (__EXCEPTIONS) && !defined (ACE_HAS_EXCEPTIONS) -# define ACE_HAS_EXCEPTIONS -# endif /* __EXCEPTIONS && ! ACE_HAS_EXCEPTIONS */ - -# if defined (ACE_HAS_EXCEPTIONS) -# define ACE_NEW_THROWS_EXCEPTIONS -# endif /* ACE_HAS_EXCEPTIONS */ - -#if (defined (i386) || defined (__i386__)) && !defined (ACE_SIZEOF_LONG_DOUBLE) -# define ACE_SIZEOF_LONG_DOUBLE 12 -#endif /* i386 */ - -#if !defined (__MINGW32__) && (defined (i386) || defined (__i386__)) - // If running an Intel, assume that it's a Pentium so that - // ACE_OS::gethrtime () can use the RDTSC instruction. If running a - // 486 or lower, be sure to comment this out. (If not running an - // Intel CPU, this #define will not be seen because of the i386 - // protection, so it can be ignored.) -# define ACE_HAS_PENTIUM -#endif /* i386 */ - -#if (defined (ACE_HAS_PENTIUM) || defined (__amd64__) || defined (__x86_64__)) -# define ACE_HAS_INTEL_ASSEMBLY -#endif - -#if !defined (ACE_LACKS_PRAGMA_ONCE) - // We define it with a -D with make depend. -# define ACE_LACKS_PRAGMA_ONCE -#endif /* ! ACE_LACKS_PRAGMA_ONCE */ - -#define ACE_TEMPLATES_REQUIRE_SOURCE - -#if (__INTEL_COMPILER >= 910) -# define ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS -#endif - -#if defined (__ia64) -# define ACE_HAS_IA64INTRIN_H -# define ACE_HAS_INTRINSIC_INTERLOCKED -#else -# define ACE_HAS_IA32INTRIN_H -#endif - -#include /**/ "ace/post.h" -#endif /* ACE_LINUX_ICC_COMMON_H */ diff --git a/externals/ace/config-integritySCA.h b/externals/ace/config-integritySCA.h deleted file mode 100644 index 41afec58758..00000000000 --- a/externals/ace/config-integritySCA.h +++ /dev/null @@ -1,229 +0,0 @@ -// -*- C++ -*- - -#ifndef ACE_INT_CONFIG_H -#define ACE_INT_CONFIG_H - -/* - * This config.h file is for version 4.0.x of the - * Integrity RTOS with SCA from Green Hills Software - * http://www.ghs.com/products/rtos/integrity.html - * - * $Id: config-integritySCA.h 88501 2010-01-12 19:41:53Z olli $ - */ - -#define ghs -/* compilation defines */ -#define ACE_LACKS_GETPGID -#define ACE_LACKS_SETPGID -#define ACE_LACKS_SETREUID -#define ACE_LACKS_SETREGID -#define ACE_LACKS_SETSID -#define ACE_LACKS_SETEGID -#define ACE_LACKS_SETUID -#define ACE_LACKS_SETEUID -#define ACE_LACKS_GETEUID -#define ACE_LACKS_GETUID -#define ACE_LACKS_GETEGID -#define ACE_LACKS_GETGID - -#ifndef ACE_HAS_EXCEPTIONS - #define ACE_HAS_EXCEPTIONS -#endif -#define ACE_NEW_THROWS_EXCEPTIONS -#define ACE_HAS_STANDARD_CPP_LIBRARY 1 -#define ACE_TEMPLATES_REQUIRE_SOURCE 1 -#define ACE_HAS_TEMPLATE_TYPEDEFS -#define TAO_USE_SEQUENCE_TEMPLATES -#define ACE_NEEDS_FUNC_DEFINITIONS -#define _REENTRANT -#define ACE_MT_SAFE 1 - -// Compiler/platform has correctly prototyped header files. -#define ACE_HAS_CPLUSPLUS_HEADERS - -#define ACE_HAS_SHM_OPEN - -/***** Operating System Defines *****/ - -/***** ANSI defines *****/ -#define ACE_LACKS_TEMPNAM /* believe it or not, this is ANSI C */ -#define ACE_LACKS_PUTENV_PROTOTYPE - -#define ACE_LACKS_SENDMSG - -/***** End Stack Defines *****/ - - -/* SCA STUFF */ -#if defined(INTEGRITY_VERSION) && (INTEGRITY_VERSION >= 40108) -#define ACE_HAS_SIG_ATOMIC_T -#endif /* INTEGRITY_VERSION */ -#define ACE_HAS_SIGWAIT -#define ACE_HAS_SIGACTION -#define ACE_HAS_SIGINFO_T -#define ACE_LACKS_SIGINFO_H -#define ACE_LACKS_UCONTEXT_H -#define ACE_HAS_SIG_C_FUNC -#define ACE_LACKS_SI_ADDR -#define ACE_HAS_AIO_CALLS - -#define ACE_HAS_POSIX_NONBLOCK -#define ACE_HAS_DIRENT - -#define ACE_HAS_THREADS - -#define ACE_HAS_PTHREADS -/***** End Threading Defines *****/ - -/***** Hardware Defines *****/ -#define ACE_PAGE_SIZE 4096 -/***** End Hardware Defines *****/ - -/****** SYSV_IPC STUFF *****/ -#define ACE_LACKS_KEY_T - -/****** Posix Defines *****/ -#define ACE_LACKS_WAIT -#define ACE_LACKS_WAITPID -#define ACE_HAS_POSIX_TIME -#define ACE_HAS_POSIX_SEM -#define ACE_HAS_STRDUP_EMULATION -#define ACE_HAS_MSG -#define ACE_LACKS_CONDATTR_PSHARED -#define ACE_LACKS_EXEC -#define ACE_LACKS_FORK -#define ACE_LACKS_MKFIFO -#define ACE_LACKS_MKTEMP -#define ACE_LACKS_MKSTEMP -#define ACE_LACKS_MPROTECT -#define ACE_LACKS_MUTEXATTR_PSHARED -#define ACE_LACKS_PIPE -#define ACE_LACKS_RLIMIT -#define ACE_LACKS_RECVMSG -#define ACE_LACKS_RWLOCK_T -#define ACE_LACKS_SEMBUF_T -#define ACE_LACKS_UNIX_DOMAIN_SOCKETS -#define ACE_LACKS_FCNTL -#define ACE_LACKS_UMASK -#define ACE_LACKS_SEEK -#define ACE_LACKS_MSYNC -#define ACE_LACKS_PID_STUFF -#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS -#define ACE_LACKS_IPC_H -#define ACE_LACKS_SETGID -#define ACE_LACKS_PIPE -#define ACE_LACKS_SYS_PARAM_H -#define ACE_LACKS_SYS_MSG_H -#define ACE_LACKS_UTSNAME_T -#define ACE_LACKS_UNAME -#define ACE_LACKS_UMASK -#define ACE_LACKS_ISATTY -#define ACE_LACKS_GETOPT -#define ACE_LACKS_STRCASECMP -#define ACE_LACKS_TRUNCATE -#define ACE_LACKS_PWD_FUNCTIONS -#define ACE_LACKS_UNIX_SIGNALS -#define ACE_HAS_THREAD_SPECIFIC_STORAGE -#define ACE_LACKS_SYSV_SHMEM -#define ACE_LACKS_PUTENV -#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG -#define ACE_HAS_CLOCK_GETTIME -#define ACE_HAS_CLOCK_SETTIME -#define ACE_LACKS_THREAD_PROCESS_SCOPING -#define ACE_LACKS_SETSCHED -#define ACE_LACKS_STRRECVFD -#define ACE_LACKS_WRITEV -#define ACE_LACKS_READV -#define ACE_LACKS_SYSCONF -#define ACE_LACKS_GETOPT -/* below refers to fcntl style locking */ -#define ACE_LACKS_FILELOCKS - -#define ACE_LACKS_REALPATH -#define ACE_HAS_CONST_CHAR_SWAB -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES - -/***** Not tied to standards AFAIK ****/ -#define ACE_LACKS_MADVISE /* paging optimization not needed with INTEGRITY */ -#define ACE_LACKS_MALLOC_H /* netbsd's just includes stdlib.h */ -#define ACE_LACKS_MEMORY_H /* netbsd's just includes string.h */ -#define ACE_LACKS_INTTYPES_H -#define ACE_LACKS_SYS_RESOURCE_H -#define ACE_LACKS_SYS_WAIT_H -#define ACE_LACKS_SEARCH_H -#define ACE_LACKS_SYS_IPC_H -#define ACE_LACKS_SYS_SEM_H -#define ACE_LACKS_PWD_H -#define ACE_LACKS_STROPTS_H -#define ACE_LACKS_DLFCN_H -#define ACE_LACKS_REGEX_H -#define ACE_LACKS_POLL_H -#define ACE_LACKS_SYS_SHM_H -#define ACE_LACKS_TERMIOS_H - -/***** STUFF INTEGRITY 4.0.8 APPEARS TO SUPPORT ****/ -/* note, possibly untested with ace */ - -/***** TAO STUFF ****/ -#define TAO_USE_DOTTED_DECIMAL_ADDRESSES 1 - -#include - -#include - -typedef void (*__sighandler_t)(int); - -extern "C" -{ - inline int isatty(int) { return 0; } -} - -#ifdef ppc -#define ACE_HAS_POWERPC_TIMER -#endif - -/* MIKEC Addtions */ -#define ACE_HAS_NONCONST_SELECT_TIMEVAL -#include // needed to define iovec -#define ACE_LACKS_READLINK -#define ACE_LACKS_GETPPID -#define NSIG (SIGRTMAX+1) -#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 -#define ACE_USE_RCSID 0 -#define ACE_LACKS_CUSERID -#define ACE_NEEDS_HUGE_THREAD_STACKSIZE 0x5000 -#define fileno(file) ((file)->io_channel) //Hack to get Svc_Conf_l.cpp compiled -#define ACE_DEFAULT_THREAD_PRIORITY 127 -#define PRI_FIFO_MIN 1 -#define PRI_FIFO_MAX 127 -#define ACE_THR_PRI_FIFO_DEF 127 -#define PRI_RR_MIN 1 -#define PRI_RR_MAX 127 -#define ACE_THR_PRI_RR_DEF 127 -#define PRI_OTHER_MIN 1 -#define PRI_OTHER_MAX 127 -#define ACE_THR_PRI_OTHER_DEF 127 -#define ACE_PTHREAD_RETURN_ON_EXIT -#undef ACE_LACKS_UNLINK - -#define ACE_HAS_TIMED_MESSAGE_BLOCKS - -extern "C" { -int unlink(const char *); -} - -#define ACE_LACKS_SETSID -#define ACE_HAS_VOIDPTR_GETTIMEOFDAY -#define ACE_LACKS_UNIX_SYSLOG -#define ACE_LACKS_TELLDIR -#define ACE_LACKS_SEEKDIR -#define ACE_LACKS_GETHOSTENT - - -/* end MIKEC Addtions */ - -// Hack to avoid ensure that things defined in ind_io.h -// have the right linkage -#include - -#endif /* ACE_CONFIG_H */ diff --git a/externals/ace/config-irix6.5.x-sgic++.h b/externals/ace/config-irix6.5.x-sgic++.h deleted file mode 100644 index 2d501010b68..00000000000 --- a/externals/ace/config-irix6.5.x-sgic++.h +++ /dev/null @@ -1,18 +0,0 @@ -// -*- C++ -*- -// $Id: config-irix6.5.x-sgic++.h 80826 2008-03-04 14:51:23Z wotte $ - -// Use this file for IRIX 6.5.x - -#ifndef ACE_CONFIG_IRIX65X_H -#define ACE_CONFIG_IRIX65X_H -#include /**/ "ace/pre.h" - -// Include IRIX 6.[234] configuration -#include "ace/config-irix6.x-sgic++.h" - -// Irix 6.5 man pages show that they exist -#undef ACE_LACKS_CONDATTR_PSHARED -#undef ACE_LACKS_MUTEXATTR_PSHARED - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_IRIX65X_H */ diff --git a/externals/ace/config-irix6.x-common.h b/externals/ace/config-irix6.x-common.h deleted file mode 100644 index 1de756d530c..00000000000 --- a/externals/ace/config-irix6.x-common.h +++ /dev/null @@ -1,254 +0,0 @@ -/* -*- C++ -*- */ -// -// $Id: config-irix6.x-common.h 87167 2009-10-19 19:33:53Z olli $ -// -// This file contains the common configuration options for both -// SGI/MIPSPro C++ and g++ under IRIX 6.X -// -// For IRIX 6.2 there are several patches that should be applied to -// get reliable operation with multi-threading and exceptions. -// Specifically you should get a reasonable current IRIX, Compiler -// and POSIX patch-sets. - -// For IRIX 6.[34] it's less critical, but it's still recommended -// that you apply the applicable patch-sets (IRIX and Compiler I believe). - -// These patches are updated frequently, so you should ask your support -// contact or search SGI's web site (http://www.sgi.com) for the latest -// version. - -// Use this file for IRIX 6.[234] if you have the pthreads patches -// installed. - -#ifndef ACE_CONFIG_IRIX6X_COMMON_H - -#ifndef IRIX6 -# define IRIX6 -#endif - -#if ! defined(ACE_CONFIG_H) -#error "This file may only be included by config-irix6.x-sgic++.h, config-irix6.x-kcc.h or config-irix6.x-g++.h" -#endif - -// The Irix 6.x float.h doesn't allow us to distinguish between a -// double and a long double. So, we have to hard-code this. Thanks -// to Bob Laferriere for figuring it out. -#if defined (_MIPS_SIM) /* 6.X System */ -# include -# if defined (__GNUC__) -# define ACE_SIZEOF_LONG_DOUBLE 16 -# elif defined (_MIPS_SIM_NABI32) && (_MIPS_SIM == _MIPS_SIM_NABI32) -# define ACE_SIZEOF_LONG_DOUBLE 16 -# elif defined (_MIPS_SIM_ABI32) && (_MIPS_SIM == _MIPS_SIM_ABI32) -# define ACE_SIZEOF_LONG_DOUBLE 8 -# elif defined (_MIPS_SIM_ABI64) && (_MIPS_SIM == _MIPS_SIM_ABI64) -# define ACE_SIZEOF_LONG_DOUBLE 16 -# elif !defined (ACE_SIZEOF_LONG_DOUBLE) -# define ACE_SIZEOF_LONG_DOUBLE 8 -# endif -#else -# define ACE_SIZEOF_LONG_DOUBLE 8 /* 5.3 System */ -#endif - -// petern, Next part of it: - -// Platform supports getpagesize() call. -#define ACE_HAS_GETPAGESIZE - -// Platform has no implementation of pthread_condattr_setpshared(), -// even though it supports pthreads! (like Irix 6.2) -#define ACE_LACKS_CONDATTR_PSHARED -#define ACE_LACKS_MUTEXATTR_PSHARED - -#define ACE_LACKS_SUSECONDS_T - -// Platform/compiler has the sigwait(2) prototype -#define ACE_HAS_SIGWAIT -#define ACE_HAS_SIGTIMEDWAIT -#define ACE_HAS_SIGSUSPEND - -// Platform supports System V IPC (most versions of UNIX, but not Win32) -#define ACE_HAS_SYSV_IPC - -// Platform requires void * for mmap(). -#define ACE_HAS_VOIDPTR_MMAP - -// Platform supports recvmsg and sendmsg. -#define ACE_HAS_MSG - -// Compiler/platform contains the file. -#define ACE_HAS_SYS_SYSCALL_H - -// Compiler/platform supports alloca() -// Although ACE does have alloca() on this compiler/platform combination, it is -// disabled by default since it can be dangerous. Uncomment the following line -// if you ACE to use it. -//#define ACE_HAS_ALLOCA - -// Compiler/platform has -#define ACE_HAS_ALLOCA_H - -// Irix needs to define bzero() in this odd file -#define ACE_HAS_BSTRING - -// Compiler/platform has the getrusage() system call. -#define ACE_HAS_GETRUSAGE - -// Platform supports POSIX O_NONBLOCK semantics. -#define ACE_HAS_POSIX_NONBLOCK - -// Compiler/platform has correctly prototyped header files. -#define ACE_HAS_CPLUSPLUS_HEADERS - -// Platform contains . -#define ACE_HAS_POLL - -// Platform supports the /proc file system. -#define ACE_HAS_PROC_FS - -// Compiler/platform defines the sig_atomic_t typedef. -#define ACE_HAS_SIG_ATOMIC_T - -// Platform supports SVR4 extended signals. -#define ACE_HAS_SIGINFO_T -#define ACE_HAS_UCONTEXT_T - -// Compiler supports the ssize_t typedef. -#define ACE_HAS_SSIZE_T - -// Platform supports STREAMS. -#define ACE_HAS_STREAMS - -// Compiler/platform supports struct strbuf. -#define ACE_HAS_STRBUF_T - -// Compiler/platform supports SVR4 dynamic linking semantics. -#define ACE_HAS_SVR4_DYNAMIC_LINKING - -// Platform provides header. -#define ACE_HAS_SYS_FILIO_H - -// Compiler/platform defines a union semun for SysV shared memory. -#define ACE_HAS_SEMUN - -// Platform supports IP multicast -#define ACE_HAS_IP_MULTICAST -#ifdef ACE_LACKS_PERFECT_MULTICAST_FILTERING - #undef ACE_LACKS_PERFECT_MULTICAST_FILTERING -#endif -#define ACE_LACKS_PERFECT_MULTICAST_FILTERING 1 - -//************************************************************** -// Not so sure how next lines should look like - -// Platform supports POSIX timers via timestruc_t. -#define ACE_HAS_POSIX_TIME - -//************************************************************** - -// IRIX 6.4 and below do not support reentrant netdb functions -// (getprotobyname_r, getprotobynumber_r, gethostbyaddr_r, -// gethostbyname_r, getservbyname_r). -#if (ACE_IRIX_VERS <= 64) && !defined (ACE_HAS_NETDB_REENTRANT_FUNCTIONS) -#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS -#endif /* ACE_HAS_NETDB_REENTRANT_FUNCTIONS */ - -#define ACE_HAS_DIRENT -// Unless the thread enabled version is used the readdir_r interface -// does not get defined in IRIX 6.2 -#define ACE_LACKS_READDIR_R -#define ACE_LACKS_RWLOCK_T - -#define ACE_HAS_GPERF - -#define ACE_HAS_NONCONST_SELECT_TIMEVAL -#define ACE_HAS_BROKEN_DGRAM_SENDV - -#define ACE_LACKS_PLACEMENT_OPERATOR_DELETE -#define ACE_PI_CONTROL_BLOCK_ALIGN_LONGS 2 - -// Platform has POSIX terminal interface. -#define ACE_HAS_TERMIOS - -// IRIX 6.5 supports AIO -#define ACE_HAS_AIO_CALLS -#define ACE_POSIX_AIOCB_PROACTOR -#define ACE_HAS_SGIDLADD -#define ACE_HAS_P_READ_WRITE -#define ACE_LACKS_LINEBUFFERED_STREAMBUF -#define ACE_LACKS_STDINT_H -#define ACE_HAS_SYSENT_H -#define ACE_HAS_SYSV_SYSINFO -#define ACE_HAS_SYS_SYSTEMINFO_H - -// Platform has support for multi-byte character support compliant -// with the XPG4 Worldwide Portability Interface wide-character -// classification. -#define ACE_HAS_XPG4_MULTIBYTE_CHAR - -// We need to setup a very high address or Naming_Test won't run. -#define ACE_DEFAULT_BASE_ADDR ((char *) (1024U * 1024 * 1024)) - -#define ACE_LACKS_SIGNED_CHAR - -// Platform supports reentrant functions (i.e., all the POSIX *_r -// functions). -#define ACE_HAS_REENTRANT_FUNCTIONS - -// Optimize ACE_Handle_Set for select(). -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT - -// Platform does not support reentrant password file accessor functiions. -#define ACE_LACKS_PWD_REENTRANT_FUNCTIONS - -// uses ctime_r & asctime_r with only two parameters vs. three -#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R - -// Prototypes for both signal() and struct sigaction are consistent. -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES - -#define ACE_HAS_UALARM - -// Scheduling functions are declared in -#define ACE_NEEDS_SCHED_H - -// Compile using multi-thread libraries by default -#if !defined (ACE_MT_SAFE) - #define ACE_MT_SAFE 1 -#endif /* ACE_MT_SAFE */ - -#if (ACE_MT_SAFE != 0) - -// Add threading support - -#define ACE_HAS_IRIX62_THREADS - -// Needed for the threading stuff? -#include /**/ -#define PTHREAD_MIN_PRIORITY PX_PRIO_MIN -#define PTHREAD_MAX_PRIORITY PX_PRIO_MAX - -// ACE supports threads. -#define ACE_HAS_THREADS - -// Platform has no implementation of pthread_condattr_setpshared(), -// even though it supports pthreads! (like Irix 6.2) -#define ACE_LACKS_CONDATTR_PSHARED -#define ACE_LACKS_MUTEXATTR_PSHARED - -// IRIX 6.2 supports a variant of POSIX Pthreads, supposedly POSIX 1c -#define ACE_HAS_PTHREADS - -// Compiler/platform has thread-specific storage -#define ACE_HAS_THREAD_SPECIFIC_STORAGE - -// The pthread_cond_timedwait call does not reset the timer. -#define ACE_LACKS_COND_TIMEDWAIT_RESET 1 - -// When threads are enabled READDIR_R is supported on IRIX. -#undef ACE_LACKS_READDIR_R - -#endif /* (ACE_MT_SAFE == 0) */ - - -#endif /* ACE_CONFIG_IRIX6X_COMMON_H */ diff --git a/externals/ace/config-irix6.x-g++.h b/externals/ace/config-irix6.x-g++.h deleted file mode 100644 index 94c79119a64..00000000000 --- a/externals/ace/config-irix6.x-g++.h +++ /dev/null @@ -1,15 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-irix6.x-g++.h 87268 2009-10-29 21:06:06Z olli $ - -// The following configuration file is designed to work for the SGI -// Indigo2EX running Irix 6.2 platform using the GNU C++ Compiler - -#ifndef ACE_CONFIG_H -#define ACE_CONFIG_H -#include /**/ "ace/pre.h" - -#include "ace/config-g++-common.h" -#include "ace/config-irix6.x-common.h" - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_H */ diff --git a/externals/ace/config-irix6.x-sgic++.h b/externals/ace/config-irix6.x-sgic++.h deleted file mode 100644 index 8bba07ac671..00000000000 --- a/externals/ace/config-irix6.x-sgic++.h +++ /dev/null @@ -1,36 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-irix6.x-sgic++.h 81935 2008-06-12 22:01:53Z jtc $ - -// Use this file for IRIX 6.[234] if you have the pthreads patches -// installed. - -#ifndef ACE_CONFIG_H -#define ACE_CONFIG_H -#include /**/ "ace/pre.h" - -#include "ace/config-irix6.x-common.h" - -// This is the config file for IRIX 6.2, 6.4 and hopefully 6.3, using -// the SGI C++ compiler (7.1 or higher). - -// The following three should be enabled/disabled together. -#if _COMPILER_VERSION < 720 -#define ACE_HAS_TEMPLATE_INSTANTIATION_PRAGMA -#endif /* _COMPILER_VERSION < 720 */ -#define ACE_TEMPLATES_REQUIRE_SOURCE -#define ACE_NEEDS_FUNC_DEFINITIONS - -// Platform supports STREAM pipes (note that this is disabled by -// default, see the manual page on pipe(2) to find out how to enable -// it). -// #define ACE_HAS_STREAM_PIPES - -#if defined (_COMPILER_VERSION) -# define ACE_CC_NAME ACE_TEXT ("SGI/MIPSPro") -# define ACE_CC_MAJOR_VERSION (_COMPILER_VERSION / 100) -# define ACE_CC_MINOR_VERSION (_COMPILER_VERSION % 100) -# define ACE_CC_BETA_VERSION (0) -#endif /* _COMPILER_VERSION */ - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_H */ diff --git a/externals/ace/config-linux-common.h b/externals/ace/config-linux-common.h deleted file mode 100644 index b787a1447ad..00000000000 --- a/externals/ace/config-linux-common.h +++ /dev/null @@ -1,464 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-linux-common.h 88663 2010-01-22 10:49:22Z mcorino $ - -// Do not use this configuration file directly since it's designed to -// be included by another, specific configuration file, such as -// config-linux.h. It provides config information common to all Linux -// platforms. It automatically determines the CPU architecture, -// compiler (g++ or egcs), and libc (libc5 or glibc), and configures -// based on those. - -#ifndef ACE_LINUX_COMMON_H -#define ACE_LINUX_COMMON_H -#include /**/ "ace/pre.h" - -#define ACE_HAS_BYTESEX_H - -#if ! defined (__ACE_INLINE__) -#define __ACE_INLINE__ -#endif /* ! __ACE_INLINE__ */ - -// Needed to differentiate between libc 5 and libc 6 (aka glibc). -#include - -#if (defined _XOPEN_SOURCE && (_XOPEN_SOURCE - 0) >= 500) -# define ACE_HAS_PTHREADS_UNIX98_EXT -#endif /* _XOPEN_SOURCE - 0 >= 500 */ - -#if !defined (ACE_LACKS_LINUX_NPTL) - -# include "ace/config-posix.h" - - // Temporary fix because NPTL kernels do have shm_open but there is a problem - // with shm_open/shm_unlink pairing in ACE which needs to be fixed when I have time. -# if defined (ACE_HAS_SHM_OPEN) -# undef ACE_HAS_SHM_OPEN -# endif /* ACE_HAS_SHM_OPEN */ - -# if defined (ACE_USES_FIFO_SEM) - // Don't use this for Linux NPTL since this has complete - // POSIX semaphores which are more efficient -# undef ACE_USES_FIFO_SEM -# endif /* ACE_USES_FIFO_SEM */ - -# if defined (ACE_HAS_POSIX_SEM) - // Linux NPTL may not define the right POSIX macro - // but they have the actual runtime support for this stuff -# if !defined (ACE_HAS_POSIX_SEM_TIMEOUT) && (((_POSIX_C_SOURCE - 0) >= 200112L) || (_XOPEN_SOURCE >= 600)) -# define ACE_HAS_POSIX_SEM_TIMEOUT -# endif /* !ACE_HAS_POSIX_SEM_TIMEOUT && (((_POSIX_C_SOURCE - 0) >= 200112L) || (_XOPEN_SOURCE >= 600)) */ -# endif /* ACE_HAS_POSIX_SEM */ -#endif /* !ACE_LACKS_LINUX_NPTL */ - -// First the machine specific part - -#if defined (__powerpc__) || defined (__x86_64__) -# if !defined (ACE_DEFAULT_BASE_ADDR) -# define ACE_DEFAULT_BASE_ADDR ((char *) 0x40000000) -# endif /* ! ACE_DEFAULT_BASE_ADDR */ -#elif defined (__ia64) -# if !defined (ACE_DEFAULT_BASE_ADDR) -// Zero base address should work fine for Linux of IA-64: it just lets -// the kernel to choose the right value. -# define ACE_DEFAULT_BASE_ADDR ((char *) 0x0000000000000000) -# endif /* ! ACE_DEFAULT_BASE_ADDR */ -#endif /* ! __powerpc__ && ! __ia64 */ - -// Then glibc/libc5 specific parts - -#if defined(__GLIBC__) -# if (__GLIBC__ < 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 1) -# define ACE_HAS_NONCONST_SETRLIMIT -# endif -# if (__GLIBC__ < 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 3) -# define ACE_HAS_RUSAGE_WHO_ENUM enum __rusage_who -# define ACE_HAS_RLIMIT_RESOURCE_ENUM enum __rlimit_resource -# define ACE_LACKS_ISCTYPE -# endif -# define ACE_HAS_SOCKLEN_T -# define ACE_HAS_4_4BSD_SENDMSG_RECVMSG - - // glibc defines both of these, used in OS_String. -# if defined (_GNU_SOURCE) -# define ACE_HAS_STRNLEN -# define ACE_HAS_WCSNLEN - - // This is probably not a 100%-sure-fire check... Red Hat Linux 9 - // and Enterprise Linux 3 and up have a new kernel that can send signals - // across threads. This was not possible prior because there was no real - // difference between a process and a thread. With this, the - // ACE_POSIX_SIG_Proactor is the only chance of getting asynch I/O working. - // There are restrictions, such as all socket operations being silently - // converted to synchronous by the kernel, that make aio a non-starter - // for most Linux platforms at this time. But we'll start to crawl... -# define ACE_POSIX_SIG_PROACTOR -# endif - - // To avoid the strangeness with Linux's ::select (), which modifies - // its timeout argument, use ::poll () instead. -# define ACE_HAS_POLL - -// Don't define _XOPEN_SOURCE and _XOPEN_SOURCE_EXTENDED in ACE to make -// getpgid() prototype visible. ACE shouldn't depend on feature test -// macros to make prototypes visible. -# define ACE_LACKS_GETPGID_PROTOTYPE - -// @note the following defines are necessary with glibc 2.0 (0.961212-5) -// on Alpha. I assume that they're necessary on Intel as well, -// but that may depend on the version of glibc that is used. -//# define ACE_HAS_DLFCN_H_BROKEN_EXTERN_C -# define ACE_HAS_VOIDPTR_SOCKOPT - -// Don't define _POSIX_SOURCE in ACE to make strtok() prototype -// visible. ACE shouldn't depend on feature test macros to make -// prototypes visible. -# define ACE_LACKS_STRTOK_R_PROTOTYPE -// @note end of glibc 2.0 (0.961212-5)-specific configuration. - -# if __GLIBC__ > 1 && __GLIBC_MINOR__ >= 1 - // These were suggested by Robert Hanzlik to get - // ACE to compile on Linux using glibc 2.1 and libg++/gcc 2.8. -# undef ACE_HAS_BYTESEX_H -# define ACE_HAS_SIGINFO_T -# define ACE_LACKS_SIGINFO_H -# define ACE_HAS_UCONTEXT_T - - // Pre-glibc (RedHat 5.2) doesn't have sigtimedwait. -# define ACE_HAS_SIGTIMEDWAIT -# endif /* __GLIBC__ 2.1+ */ -#else /* ! __GLIBC__ */ - // Fixes a problem with some non-glibc versions of Linux... -# define ACE_LACKS_MADVISE -# define ACE_LACKS_MSG_ACCRIGHTS -#endif /* ! __GLIBC__ */ - -// Don't define _LARGEFILE64_SOURCE in ACE to make llseek() or -// lseek64() prototype visible. ACE shouldn't depend on feature test -// macros to make prototypes visible. -#if __GLIBC__ > 1 -# if __GLIBC_MINOR__ == 0 -# define ACE_HAS_LLSEEK -# define ACE_LACKS_LLSEEK_PROTOTYPE -# else /* __GLIBC_MINOR__ > 0 */ -# define ACE_HAS_LSEEK64 -# define ACE_LACKS_LSEEK64_PROTOTYPE -# endif -#endif /* __GLIBC__ > 1 */ - -#if __GLIBC__ > 1 && __GLIBC_MINOR__ >= 1 -# define ACE_HAS_P_READ_WRITE -# define ACE_LACKS_PREAD_PROTOTYPE -// Use ACE's alternate cuserid() implementation since the use of the -// system cuserid() is discouraged. -# define ACE_HAS_ALT_CUSERID -#endif /* __GLIBC__ > 1 && __GLIBC_MINOR__ >= 0 */ - -#if (__GLIBC__ > 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3) -# define ACE_HAS_ISASTREAM_PROTOTYPE -# define ACE_HAS_PTHREAD_SIGMASK_PROTOTYPE -# define ACE_HAS_CPU_SET_T -#endif /* __GLIBC__ > 2 || __GLIBC__ === 2 && __GLIBC_MINOR__ >= 3) */ - -// Then the compiler specific parts - -#if defined (__INTEL_COMPILER) -# include "ace/config-icc-common.h" -#elif defined (__GNUG__) - // config-g++-common.h undef's ACE_HAS_STRING_CLASS with -frepo, so - // this must appear before its #include. -# define ACE_HAS_STRING_CLASS -# include "ace/config-g++-common.h" -#define ACE_CC_NAME ACE_TEXT ("g++") -#define ACE_CC_MAJOR_VERSION __GNUC__ -#define ACE_CC_MINOR_VERSION __GNUC_MINOR__ -//#define ACE_CC_BETA_VERSION 0 /* ??? */ -#elif defined (__DECCXX) -# define ACE_CONFIG_INCLUDE_CXX_COMMON -# include "ace/config-cxx-common.h" -#elif defined (__SUNCC_PRO) || defined (__SUNPRO_CC) -# include "ace/config-suncc-common.h" -#elif defined (__PGI) -// Portable group compiler -# define ACE_HAS_CPLUSPLUS_HEADERS -# define ACE_HAS_STDCPP_STL_INCLUDES -# define ACE_HAS_TEMPLATE_TYPEDEFS -# define ACE_HAS_STANDARD_CPP_LIBRARY 1 -# define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 -# define ACE_LACKS_SWAB -#elif defined (__GNUC__) -/** - * GNU C compiler. - * - * We need to recognize the GNU C compiler since TAO has at least one - * C source header and file - * (TAO/orbsvcs/orbsvcs/SSLIOP/params_dup.{h,c}) that may indirectly - * include this - */ -#else /* ! __GNUG__ && !__DECCXX && !__INTEL_COMPILER && && !__PGI */ -# ifdef __cplusplus /* Let it slide for C compilers. */ -# error unsupported compiler in ace/config-linux-common.h -# endif /* __cplusplus */ -#endif /* ! __GNUG__*/ - -// Completely common part :-) - -// Platform/compiler has the sigwait(2) prototype -#define ACE_HAS_SIGWAIT - -#define ACE_HAS_SIGSUSPEND - -#define ACE_HAS_UALARM - -#define ACE_HAS_STRSIGNAL - -#if __GLIBC__ >= 2 -#ifndef ACE_HAS_POSIX_REALTIME_SIGNALS -#define ACE_HAS_POSIX_REALTIME_SIGNALS -#endif /* ACE_HAS_POSIX_REALTIME_SIGNALS */ - -#ifndef ACE_HAS_AIO_CALLS -#define ACE_HAS_AIO_CALLS -#endif /* ACE_HAS_AIO_CALLS */ -#endif - -#if __GLIBC__ >= 2 -// glibc 2 and higher has wchar support -# define ACE_HAS_XPG4_MULTIBYTE_CHAR -# define ACE_HAS_VFWPRINTF -#endif - -#if __GLIBC__ < 2 -// These are present in glibc 2 and higher -# define ACE_LACKS_WCSTOK -# define ACE_LACKS_WCSDUP_PROTOTYPE -#endif /* __GLIBC__ < 2 */ - -#define ACE_LACKS_ITOW -#define ACE_LACKS_WCSICMP -#define ACE_LACKS_WCSNICMP -#define ACE_LACKS_ISWASCII - -#if __GLIBC__ >= 2 -# define ACE_HAS_3_PARAM_WCSTOK -#endif - -#define ACE_HAS_3_PARAM_READDIR_R - -#if !defined (ACE_DEFAULT_BASE_ADDR) -# define ACE_DEFAULT_BASE_ADDR ((char *) 0x80000000) -#endif /* ! ACE_DEFAULT_BASE_ADDR */ - -// Compiler/platform supports alloca(). -// Although ACE does have alloca() on this compiler/platform combination, it is -// disabled by default since it can be dangerous. Uncomment the following line -// if you ACE to use it. -//#define ACE_HAS_ALLOCA - -// Compiler/platform has -#define ACE_HAS_ALLOCA_H -#define ACE_HAS_SYS_SYSINFO_H -#define ACE_HAS_LINUX_SYSINFO - -// Compiler/platform has the getrusage() system call. -#define ACE_HAS_GETRUSAGE -#define ACE_HAS_GETRUSAGE_PROTOTYPE - -#define ACE_HAS_BYTESWAP_H -#define ACE_HAS_BSWAP_16 -#define ACE_HAS_BSWAP_32 - -#if defined __GNUC__ && __GNUC__ >= 2 -# define ACE_HAS_BSWAP_64 -#endif - -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES - -// Optimize ACE_Handle_Set for select(). -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT - -// ONLY define this if you have config'd multicast into a 2.0.34 or -// prior kernel. It is enabled by default in 2.0.35 kernels. -#if !defined (ACE_HAS_IP_MULTICAST) -# define ACE_HAS_IP_MULTICAST -#endif /* ! ACE_HAS_IP_MULTICAST */ - -// At least for IPv4, Linux lacks perfect filtering. -#if !defined ACE_LACKS_PERFECT_MULTICAST_FILTERING -# define ACE_LACKS_PERFECT_MULTICAST_FILTERING 1 -#endif /* ACE_LACKS_PERFECT_MULTICAST_FILTERING */ - -#define ACE_HAS_BIG_FD_SET - -// Linux defines struct msghdr in /usr/include/socket.h -#define ACE_HAS_MSG - -// Linux "improved" the interface to select() so that it modifies -// the struct timeval to reflect the amount of time not slept -// (see NOTES in Linux's select(2) man page). -#define ACE_HAS_NONCONST_SELECT_TIMEVAL - -#define ACE_DEFAULT_MAX_SOCKET_BUFSIZ 65535 - -#define ACE_CDR_IMPLEMENT_WITH_NATIVE_DOUBLE 1 - -#define ACE_HAS_GETPAGESIZE 1 - -#if (__GLIBC__ < 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 2) -// glibc supports wchar, but lacks fgetwc and ungetwc -# define ACE_LACKS_FGETWC -# define ACE_HAS_NONCONST_MSGSND -# define ACE_LACKS_STRNLEN_PROTOTYPE -#endif - -// glibc requires _XOPEN_SOURCE_EXTENDED to make this prototype -// visible, so force ACE to declare one. Yuk! -#ifndef _XOPEN_SOURCE_EXTENDED -# define ACE_LACKS_MKSTEMP_PROTOTYPE -#endif /* !_XOPEN_SOURCE_EXTENDED */ - -// Platform defines struct timespec but not timespec_t -#define ACE_LACKS_TIMESPEC_T - -// Platform supplies scandir() -#define ACE_HAS_SCANDIR -#if (__GLIBC__ < 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 10) -// Although the scandir man page says otherwise, this setting is correct. -// The setting was fixed in 2.10, so do not use the hack after that. -#define ACE_SCANDIR_CMP_USES_CONST_VOIDPTR -#endif - -// A conflict appears when including both and -// with recent glibc headers. -//#define ACE_HAS_PROC_FS - -// Platform supports System V IPC (most versions of UNIX, but not Win32) -#define ACE_HAS_SYSV_IPC - -// Compiler/platform contains the file. -#define ACE_HAS_SYS_SYSCALL_H - -// Platform/compiler supports global timezone variable. -#define ACE_HAS_TIMEZONE - -#define ACE_HAS_TIMEZONE_GETTIMEOFDAY - -// Don't define _XOPEN_SOURCE in ACE to make strptime() prototype -// visible. ACE shouldn't depend on feature test macros to make -// prototypes visible. -#define ACE_LACKS_STRPTIME_PROTOTYPE - -// Compiler supports the ssize_t typedef. -#define ACE_HAS_SSIZE_T - -// Compiler/platform defines the sig_atomic_t typedef. -#define ACE_HAS_SIG_ATOMIC_T - -// Compiler/platform defines a union semun for SysV shared memory. -#define ACE_HAS_SEMUN - -#define ACE_HAS_POSIX_TIME - -#define ACE_HAS_GPERF - -#define ACE_HAS_DIRENT - -// Starting with FC9 rawhide this file is not available anymore but -// this define is set -#if defined _XOPEN_STREAMS && _XOPEN_STREAMS == -1 -# define ACE_LACKS_STROPTS_H -# define ACE_LACKS_STRRECVFD -#endif - -#if !defined (ACE_LACKS_STROPTS_H) -# define ACE_HAS_STRBUF_T -#endif - -#if defined (__ia64) || defined(__alpha) || defined (__x86_64__) -// On 64 bit platforms, the "long" type is 64-bits. Override the -// default 32-bit platform-specific format specifiers appropriately. -# define ACE_UINT64_FORMAT_SPECIFIER_ASCII "%lu" -# define ACE_SSIZE_T_FORMAT_SPECIFIER_ASCII "%ld" -# define ACE_SIZE_T_FORMAT_SPECIFIER_ASCII "%lu" -#endif /* __ia64 */ - -#define ACE_SIZEOF_WCHAR 4 - -#if defined (__powerpc__) && !defined (ACE_SIZEOF_LONG_DOUBLE) -// 32bit PowerPC Linux uses 128bit long double -# define ACE_SIZEOF_LONG_DOUBLE 16 -#endif - -#define ACE_LACKS_GETIPNODEBYADDR -#define ACE_LACKS_GETIPNODEBYNAME - -// Platform has POSIX terminal interface. -#define ACE_HAS_TERMIOS - -// Linux implements sendfile(). -#define ACE_HAS_SENDFILE 1 - -#define ACE_HAS_VOIDPTR_MMAP - -#define ACE_HAS_ICMP_SUPPORT 1 - -#define ACE_HAS_VASPRINTF - -// According to man pages Linux uses different (compared to UNIX systems) types -// for setting IP_MULTICAST_TTL and IPV6_MULTICAST_LOOP / IP_MULTICAST_LOOP -// in setsockopt/getsockopt. -#define ACE_HAS_IP_MULTICAST_TTL_AS_INT 1 -#define ACE_HAS_IPV6_MULTICAST_LOOP_AS_BOOL 1 -#define ACE_HAS_IP_MULTICAST_LOOP_AS_INT 1 - -#if defined (ACE_LACKS_NETWORKING) -# include "ace/config-posix-nonetworking.h" -#else -# define ACE_HAS_NETLINK -# if (__GLIBC__ > 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 2) -# define ACE_HAS_GETIFADDRS -# endif -#endif - -#if !defined (ACE_GETNAME_RETURNS_RANDOM_SIN_ZERO) -// Detect if getsockname() and getpeername() returns random values in -// the sockaddr_in::sin_zero field by evaluation of the kernel -// version. Since version 2.5.47 this problem is fixed. -# if !defined (ACE_LACKS_LINUX_VERSION_H) -# include -# endif /* !ACE_LACKS_LINUX_VERSION_H */ -# if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,47)) -# define ACE_GETNAME_RETURNS_RANDOM_SIN_ZERO 0 -# else -# define ACE_GETNAME_RETURNS_RANDOM_SIN_ZERO 1 -# endif /* (LINUX_VERSION_CODE <= KERNEL_VERSION(2,5,47)) */ -#endif /* ACE_GETNAME_RETURNS_RANDOM_SIN_ZERO */ - -#if defined (ACE_HAS_EVENT_POLL) -// The sys_epoll interface was introduced in Linux kernel 2.5.45. -// Don't support backported versions since they appear to be buggy. -// The obsolete ioctl()-based interface is no longer supported. -#if 0 -// linux/version.h may not be accurate. It's not for Fedora Core 2... -# if !defined (ACE_LACKS_LINUX_VERSION_H) -# include -# endif /* !ACE_LACKS_LINUX_VERSION_H */ -# if (LINUX_VERSION_CODE < KERNEL_VERSION (2,5,45)) -# undef ACE_HAS_EVENT_POLL -# error Disabling Linux epoll support. Kernel used in C library is too old. -# error Linux kernel 2.5.45 or better is required. -# endif /* LINUX_VERSION_CODE < KERNEL_VERSION (2,5,45) */ -#endif /* ACE_HAS_EVENT_POLL */ -#endif - -#if !defined (ACE_HAS_EVENT_POLL) && !defined (ACE_HAS_DEV_POLL) -# if !defined (ACE_LACKS_LINUX_VERSION_H) -# include -# endif /* !ACE_LACKS_LINUX_VERSION_H */ -# if (LINUX_VERSION_CODE > KERNEL_VERSION (2,6,0)) -# define ACE_HAS_EVENT_POLL -# endif -#endif - -#include /**/ "ace/post.h" - -#endif /* ACE_LINUX_COMMON_H */ diff --git a/externals/ace/config-linux.h b/externals/ace/config-linux.h deleted file mode 100644 index 8b79c13a415..00000000000 --- a/externals/ace/config-linux.h +++ /dev/null @@ -1,75 +0,0 @@ -// -*- C++ -*- -// -// $Id: config-linux.h 80826 2008-03-04 14:51:23Z wotte $ - -// The following configuration file is designed to work for Linux -// platforms using GNU C++. - -#ifndef ACE_CONFIG_LINUX_H -#define ACE_CONFIG_LINUX_H -#include /**/ "ace/pre.h" - -#define ACE_PLATFORM_CONFIG config-linux.h - -#include "ace/config-linux-common.h" - -#define ACE_HAS_SVR4_DYNAMIC_LINKING -#define ACE_HAS_AUTOMATIC_INIT_FINI -#define ACE_HAS_DLSYM_SEGFAULT_ON_INVALID_HANDLE - -#if !defined (ACE_MT_SAFE) -#define ACE_MT_SAFE 1 // JCEJ 12/22/96 #1 -#endif - -#if ACE_MT_SAFE -// Yes, we do have threads. -#define ACE_HAS_THREADS -// And they're even POSIX pthreads (LinuxThreads implementation) -#define ACE_HAS_PTHREADS - -// On linux this is part of pthreads -# if (defined _POSIX_C_SOURCE && (_POSIX_C_SOURCE - 0) >= 199309L) -# if !defined (ACE_HAS_CLOCK_GETTIME) -# if !defined(__PGI) -# define ACE_HAS_CLOCK_GETTIME -# endif /* __PGI */ -# define ACE_HAS_CLOCK_SETTIME -# endif /* !ACE_HAS_CLOCK_GETTIME */ -# endif /* _POSIX_C_SOURCE >= 199309L */ - -#if !defined (ACE_HAS_PTHREADS_UNIX98_EXT) -# define ACE_LACKS_RWLOCK_T -#else -# define ACE_HAS_RECURSIVE_MUTEXES -#endif /* !ACE_HAS_PTHREADS_UNIX98_EXT */ - -#define ACE_HAS_THREAD_SPECIFIC_STORAGE // jcej 12/22/96 #2 - -#define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS // JCEJ 1/7-8/96 - -#if defined(__GLIBC__) -// Platform supports reentrant functions (i.e., all the POSIX *_r -// functions). -#define ACE_HAS_REENTRANT_FUNCTIONS - -#if (__GLIBC__ < 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 1) - // Older versions of glibc lacked reentrant netdb functions -# define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS - - // glibc < 2.1 lacks pthread_attr_setstacksize() -# define ACE_LACKS_PTHREAD_ATTR_SETSTACKSIZE -#endif /* (__GLIBC__ < 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 1) */ - -// uses ctime_r & asctime_r with only two parameters vs. three -#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R -#endif - -#else -// AIO support pulls in the rt library, which pulls in the pthread -// library. Disable AIO in single-threaded builds. -# undef ACE_HAS_AIO_CALLS -#endif /* ACE_MT_SAFE */ - -#include /**/ "ace/post.h" - -#endif /* ACE_CONFIG_LINUX_H */ diff --git a/externals/ace/config-lite.h b/externals/ace/config-lite.h deleted file mode 100644 index 1a6937c851b..00000000000 --- a/externals/ace/config-lite.h +++ /dev/null @@ -1,164 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file config-lite.h - * - * $Id: config-lite.h 85832 2009-06-28 16:14:59Z johnnyw $ - * - * @author (Originally in OS.h)Doug Schmidt - * @author Jesper S. M|ller - * @author and a cast of thousands... - * - * This file contains the contents of the old config-all.h in order to - * avoid a circular dependency problem caused by some of the new - * includes added to config-all.h, e.g., OS_main.h. - */ -//========================================================================== - -#ifndef ACE_CONFIG_LITE_H -#define ACE_CONFIG_LITE_H - -#include /**/ "ace/pre.h" - -#include "ace/config-macros.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -// Empty ACE_OS namespace to help identify compiler errors more -// easily. -- @@ Do we really need this? -ACE_BEGIN_VERSIONED_NAMESPACE_DECL -namespace ACE_OS {} -ACE_END_VERSIONED_NAMESPACE_DECL - -// ============================================================================ -// UNICODE macros (to be added later) -// ============================================================================ - -// Get the unicode (i.e. ACE_TCHAR) defines -# include "ace/ace_wchar.h" - -// ============================================================================ -// at_exit declarations -// ============================================================================ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -// Marker for cleanup, used by ACE_Exit_Info. -extern int ace_exit_hook_marker; - -ACE_END_VERSIONED_NAMESPACE_DECL - -// For use by . -extern "C" -{ - typedef void (*ACE_EXIT_HOOK) (void); -} - -// Signature for registering a cleanup function that is used by the -// ACE_Object_Manager and the ACE_Thread_Manager. -# if defined (ACE_HAS_SIG_C_FUNC) -extern "C" { -# endif /* ACE_HAS_SIG_C_FUNC */ -typedef void (*ACE_CLEANUP_FUNC)(void *object, void *param) /* throw () */; -# if defined (ACE_HAS_SIG_C_FUNC) -} -# endif /* ACE_HAS_SIG_C_FUNC */ - -// ============================================================================ -// log_msg declarations -// ============================================================================ - -ACE_BEGIN_VERSIONED_NAMESPACE_DECL - -# if defined (ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS) -typedef int (*ACE_SEH_EXCEPT_HANDLER)(void *); -// Prototype of win32 structured exception handler functions. -// They are used to get the exception handling expression or -// as exception handlers. -# endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */ - -class ACE_OS_Thread_Descriptor; -class ACE_OS_Log_Msg_Attributes; -typedef void (*ACE_INIT_LOG_MSG_HOOK) (ACE_OS_Log_Msg_Attributes &attr -# if defined (ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS) - , ACE_SEH_EXCEPT_HANDLER selector - , ACE_SEH_EXCEPT_HANDLER handler -# endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */ - ); -typedef void (*ACE_INHERIT_LOG_MSG_HOOK) (ACE_OS_Thread_Descriptor*, - ACE_OS_Log_Msg_Attributes &); - -typedef void (*ACE_CLOSE_LOG_MSG_HOOK) (void); - -typedef void (*ACE_SYNC_LOG_MSG_HOOK) (const ACE_TCHAR *prog_name); - -typedef ACE_OS_Thread_Descriptor *(*ACE_THR_DESC_LOG_MSG_HOOK) (void); - -ACE_END_VERSIONED_NAMESPACE_DECL - -/** - * @deprecated ACE_DECLARE_STL_REVERSE_ITERATORS is a crutch to be - * used until all C++ compiler supported by ACE support - * the standard reverse_iterator adapters. - * @internal ACE_DECLARE_STL_REVERSE_ITERATORS is not meant for use - * outside of ACE. - */ -// STL reverse_iterator declaration generator -// Make sure you include in the file you're using this -// generator, and that the following traits are available: -// -// iterator -// const_iterator -// value_type -// reference -// pointer -// const_reference -// const_pointer -// difference_type -// -// Once all C++ compilers support the standard reverse_iterator -// adapters, we can drop this generator macro or at least drop the -// MSVC++ or Sun Studio preprocessor conditional blocks. -#if defined (__SUNPRO_CC) && __SUNPRO_CC <= 0x5100 \ - && !defined (_STLPORT_VERSION) - // If we're not using the stlport4 C++ library (which has standard - // iterators), we need to ensure this is included in order to test - // the _RWSTD_NO_CLASS_PARTIAL_SPEC feature test macro below. -# include -#endif /* __SUNPRO_CC <= 0x5100 */ -#if (defined (_MSC_VER) && (_MSC_VER <= 1310) && defined (_WIN64)) \ - || defined (ACE_HAS_BROKEN_STD_REVERSE_ITERATOR) - // VC 7.1 and the latest 64-bit platform SDK still don't define a standard - // compliant reverse_iterator adapter. -# define ACE_DECLARE_STL_REVERSE_ITERATORS \ - typedef std::reverse_iterator reverse_iterator; \ - typedef std::reverse_iterator const_reverse_iterator; -#elif defined (__SUNPRO_CC) && __SUNPRO_CC <= 0x5100 \ - && defined (_RWSTD_NO_CLASS_PARTIAL_SPEC) -# define ACE_DECLARE_STL_REVERSE_ITERATORS \ - typedef std::reverse_iterator reverse_iterator; \ - typedef std::reverse_iterator const_reverse_iterator; -#else -# define ACE_DECLARE_STL_REVERSE_ITERATORS \ - typedef std::reverse_iterator reverse_iterator; \ - typedef std::reverse_iterator const_reverse_iterator; -#endif /* _MSC_VER && _WIN64 */ - - -#include /**/ "ace/post.h" - -#endif /* ACE_CONFIG_LITE_H */ diff --git a/externals/ace/config-lynxos.h b/externals/ace/config-lynxos.h deleted file mode 100644 index 81176f615b9..00000000000 --- a/externals/ace/config-lynxos.h +++ /dev/null @@ -1,199 +0,0 @@ -// $Id: config-lynxos.h 89494 2010-03-15 20:11:18Z olli $ - -// The following configuration file is designed to work for LynxOS, -// version 4.0.0 and later, using the GNU g++ compiler. - -#ifndef ACE_CONFIG_H -#define ACE_CONFIG_H -#include /**/ "ace/pre.h" - -// System include files are not in sys/, this gets rid of warning. -#define __NO_INCLUDE_WARN__ - -#define __FREEBSDCODE__ -#include -#undef __FREEBSDCODE__ - -#if ! defined (__ACE_INLINE__) -# define __ACE_INLINE__ -#endif /* ! __ACE_INLINE__ */ - -#if defined (__GNUG__) -# include "ace/config-g++-common.h" -#endif /* __GNUG__ */ - -// Compile using multi-thread libraries. -#if !defined (ACE_MT_SAFE) -# define ACE_MT_SAFE 1 -#endif - -#include "ace/config-posix.h" - -#if defined (__x86__) -# define ACE_HAS_PENTIUM -#elif defined (__powerpc__) - // It looks like the default stack size is 15000. - // ACE's Recursive_Mutex_Test needs more. -# define ACE_NEEDS_HUGE_THREAD_STACKSIZE 65536 - // This doesn't work on LynxOS 3.0.0, because it resets the TimeBaseRegister. - // # define ACE_HAS_POWERPC_TIMER -#endif /* __x86__ || __powerpc__ */ - -#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R -#define ACE_HAS_3_PARAM_READDIR_R -#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG -#define ACE_HAS_ALLOCA -#define ACE_HAS_ALLOCA_H -#define ACE_HAS_AUTOMATIC_INIT_FINI -#define ACE_HAS_BROKEN_PREALLOCATED_OBJECTS_AFTER_FORK 1 -#define ACE_HAS_BROKEN_SIGEVENT_STRUCT -#define ACE_HAS_CHARPTR_SHMAT -#define ACE_HAS_CHARPTR_SHMDT -#define ACE_HAS_CLOCK_GETTIME -#define ACE_HAS_CLOCK_SETTIME -#define ACE_HAS_CPLUSPLUS_HEADERS -#define ACE_HAS_DIRENT -#define ACE_HAS_GETIFADDRS -#define ACE_HAS_GETPAGESIZE -#define ACE_HAS_GETRUSAGE -#define ACE_HAS_GETRUSAGE_PROTOTYPE -#define ACE_HAS_GPERF -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT -#define ACE_HAS_ICMP_SUPPORT 1 -#define ACE_HAS_IP_MULTICAST -#define ACE_HAS_MEMCHR -#define ACE_HAS_MKDIR -#define ACE_HAS_MSG -#define ACE_HAS_NANOSLEEP -#define ACE_HAS_NEW_NOTHROW -#define ACE_HAS_NONCONST_CLOCK_SETTIME -#define ACE_HAS_NONCONST_MSGSND -#define ACE_HAS_NONCONST_READV -#define ACE_HAS_NONCONST_SELECT_TIMEVAL -#define ACE_HAS_NONCONST_SETRLIMIT -#define ACE_HAS_NONCONST_WRITEV -#define ACE_HAS_POSITION_INDEPENDENT_POINTERS 1 -#define ACE_HAS_POSIX_NONBLOCK -#define ACE_HAS_POSIX_TIME -#define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS -#define ACE_HAS_SCANDIR -#define ACE_HAS_SIGACTION_CONSTP2 -#define ACE_HAS_SIGINFO_T -#define ACE_HAS_SIGSUSPEND -#define ACE_HAS_SIGTIMEDWAIT -#define ACE_HAS_SIGWAIT -#define ACE_HAS_SIG_ATOMIC_T -#define ACE_HAS_SIG_C_FUNC -#define ACE_HAS_SOCKADDR_IN6_SIN6_LEN -#define ACE_HAS_SOCKADDR_IN_SIN_LEN -#define ACE_HAS_SOCKADDR_MSG_NAME -#define ACE_HAS_SOCKLEN_T -#define ACE_HAS_SSIZE_T -#define ACE_HAS_STREAMS -#define ACE_HAS_STRINGS -#define ACE_HAS_STRING_CLASS -#define ACE_HAS_SYSCTL -#define ACE_HAS_SYS_FILIO_H -#define ACE_HAS_SYS_SOCKIO_H -#define ACE_HAS_TERMIOS -#define ACE_HAS_TIMEZONE_GETTIMEOFDAY - -#define ACE_LACKS_ALPHASORT_PROTOTYPE -#define ACE_LACKS_CONST_TIMESPEC_PTR -#define ACE_LACKS_GETPGID -#define ACE_LACKS_ISCTYPE -#define ACE_LACKS_MADVISE -#define ACE_LACKS_MKSTEMP_PROTOTYPE -#define ACE_LACKS_MKTEMP_PROTOTYPE -#define ACE_LACKS_PUTENV_PROTOTYPE -#define ACE_LACKS_REALPATH -#define ACE_LACKS_RLIMIT_NOFILE -#define ACE_LACKS_RWLOCK_T -#define ACE_LACKS_SCANDIR_PROTOTYPE -#define ACE_LACKS_SETEGID -#define ACE_LACKS_SETEUID -#define ACE_LACKS_SIGINFO_H -#define ACE_LACKS_STRPTIME -#define ACE_LACKS_SWAB_PROTOTYPE -#define ACE_LACKS_TIMESPEC_T -#define ACE_LACKS_UCONTEXT_H -#define ACE_LACKS_SUSECONDS_T - -#define ACE_DEFAULT_BASE_ADDR ((char *) 0) -#define ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS -#define ACE_MALLOC_ALIGN 8 -#define ACE_PAGE_SIZE 4096 -#define ACE_POSIX_SIG_PROACTOR -#define ACE_SCANDIR_CMP_USES_CONST_VOIDPTR - -// LynxOS has poll.h but it is unusable since implementation is not provided -#define ACE_LACKS_POLL_H - -#if ACE_MT_SAFE == 1 - // Platform supports threads. -# define ACE_HAS_PTHREADS -# define ACE_HAS_PTHREADS_STD -# define ACE_HAS_PTHREADS_UNIX98_EXT -# define ACE_HAS_PTHREAD_GETCONCURRENCY -# define ACE_HAS_PTHREAD_SETCONCURRENCY -# define ACE_HAS_PTHREAD_SIGMASK_PROTOTYPE -# define ACE_HAS_THREAD_SPECIFIC_STORAGE -# define ACE_LACKS_PTHREAD_ATTR_SETSTACK -# define ACE_LACKS_THREAD_PROCESS_SCOPING -# if ACE_LYNXOS_MAJOR == 4 && ACE_LYNXOS_MINOR == 0 -# define ACE_LACKS_SETDETACH -# define ACE_LACKS_PTHREAD_ATTR_SETSTACKADDR -# endif -#endif /* ACE_MT_SAFE */ - -// By default, don't include RCS Id strings in object code. -#if !defined (ACE_USE_RCSID) -# define ACE_USE_RCSID 0 -#endif /* ! ACE_USE_RCSID */ - -#if ACE_LYNXOS_MAJOR == 4 && ACE_LYNXOS_MINOR == 0 -# define ACE_LACKS_GETOPT_PROTOTYPE -# define ACE_LACKS_INET_ATON_PROTOTYPE -# define ACE_LACKS_REGEX_H -# define ACE_LACKS_STRCASECMP_PROTOTYPE -# define ACE_LACKS_STRNCASECMP_PROTOTYPE -# define ACE_LACKS_SYS_SELECT_H -#endif - -#if (ACE_LYNXOS_MAJOR > 4) || (ACE_LYNXOS_MAJOR == 4 && ACE_LYNXOS_MINOR >= 2) -// LynxOS 4.2 additons -# define ACE_HAS_POSIX_SEM_TIMEOUT -# define ACE_HAS_MUTEX_TIMEOUTS -#endif - -#if (ACE_LYNXOS_MAJOR >=5) -// LynxOS 5.0 Additons -# define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES -# define ACE_HAS_NONCONST_INET_ADDR -# define ACE_LACKS_INET_ATON_PROTOTYPE -# define ACE_LACKS_SEMBUF_T -# define ACE_LACKS_STROPTS_H -# define ACE_LACKS_STRRECVFD -# define ACE_LACKS_SYS_SEM_H -# define ACE_SYS_SIGLIST __sys_siglist -#else -// LynxOS 5.0 Removals -# define ACE_HAS_LYNXOS4_SIGNALS -# define ACE_HAS_SEMUN -# define ACE_HAS_STRBUF_T -# define ACE_HAS_SYSV_IPC -# define ACE_LACKS_ISBLANK -# define ACE_LACKS_SETENV -# define ACE_LACKS_UNSETENV -# define ACE_LACKS_USECONDS_T -# define ACE_LACKS_VSNPRINTF -# define ACE_LACKS_WCHAR_H -# define ACE_SYS_SIGLIST sys_siglist -#endif - -#if defined (ACE_HAS_SVR4_DYNAMIC_LINKING) -# define ACE_HAS_BROKEN_THREAD_KEYFREE -#endif /* ACE_HAS_SVR4_DYNAMIC_LINKING */ - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_H */ diff --git a/externals/ace/config-macosx-iphone-hardware.h b/externals/ace/config-macosx-iphone-hardware.h deleted file mode 100644 index 6201d8e824b..00000000000 --- a/externals/ace/config-macosx-iphone-hardware.h +++ /dev/null @@ -1,15 +0,0 @@ -// $Id: config-macosx-iphone-hardware.h 88739 2010-01-27 05:35:23Z sowayaa $ -#ifndef ACE_CONFIG_MACOSX_IPHONE_HARDWARE_H -#define ACE_CONFIG_MACOSX_IPHONE_HARDWARE_H - -#define ACE_HAS_IPHONE -#define ACE_SIZEOF_LONG_DOUBLE 8 - -#include "ace/config-macosx-snowleopard.h" - -#ifdef ACE_HAS_SYSV_IPC -#undef ACE_HAS_SYSV_IPC -#endif - -#endif ACE_CONFIG_MACOSX_IPHONE_HARDWARE_H - diff --git a/externals/ace/config-macosx-iphone-simulator.h b/externals/ace/config-macosx-iphone-simulator.h deleted file mode 100644 index 024cf8480a3..00000000000 --- a/externals/ace/config-macosx-iphone-simulator.h +++ /dev/null @@ -1,9 +0,0 @@ -// $Id: config-macosx-iphone-simulator.h 88653 2010-01-21 23:19:50Z sowayaa $ -#ifndef ACE_CONFIG_MACOSX_IPHONE_SIMULATOR_H -#define ACE_CONFIG_MACOSX_IPHONE_SIMULATOR_H - -#define ACE_HAS_IPHONE -#include "ace/config-macosx-snowleopard.h" - -#endif ACE_CONFIG_MACOSX_IPHONE_SIMULATOR_H - diff --git a/externals/ace/config-macosx-leopard.h b/externals/ace/config-macosx-leopard.h deleted file mode 100644 index dfaaf870947..00000000000 --- a/externals/ace/config-macosx-leopard.h +++ /dev/null @@ -1,231 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-macosx-leopard.h 90343 2010-05-29 02:18:47Z wotte $ - -// This configuration file is designed to work with the MacOS X operating system. - -#ifndef ACE_CONFIG_MACOSX_LEOPARD_H -#define ACE_CONFIG_MACOSX_LEOPARD_H - -#define ACE_HAS_MAC_OSX -#define ACE_HAS_NET_IF_DL_H - -#define ACE_HAS_VOID_UNSETENV - -#if ! defined (__ACE_INLINE__) -#define __ACE_INLINE__ -#endif /* ! __ACE_INLINE__ */ - -#if !defined (ACE_SIZEOF_LONG_DOUBLE) -# if (__GNUC__ == 3 && __GNUC_MINOR__ == 3) - // Size of long double in GCC 3.3 is 8. -# define ACE_SIZEOF_LONG_DOUBLE 8 -# else // Else, the compiler is GCC4 - // For GCC4, the size is 16. -# define ACE_SIZEOF_LONG_DOUBLE 16 -# endif // GCC 3.3 -#endif // ACE_SIZEOF_LONG_DOUBLE - -#if defined (__GNUG__) -# include "ace/config-g++-common.h" -#endif /* __GNUG__ */ - -#define ACE_ISCTYPE_EQUIVALENT __isctype - -#ifndef ACE_HAS_NONCONST_FD_ISSET -#define ACE_HAS_NONCONST_FD_ISSET -#endif - -#define ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR - -#define ACE_SIZE_T_FORMAT_SPECIFIER_ASCII "%lu" - -#if !defined (__i386__) -# if defined (ACE_HAS_PENTIUM) -# undef ACE_HAS_PENTIUM -# endif /* ACE_HAS_PENTIUM */ -#else // __i386__ -# define ACE_HAS_PENTIUM -#endif //__i386__ - -#if !defined (_THREAD_SAFE) -#define _THREAD_SAFE -#endif /* _THREAD_SAFE */ - -#define ACE_HAS_GPERF -#define ACE_HAS_POSIX_SEM - -#define ACE_HAS_SUNOS4_GETTIMEOFDAY - -#define ACE_LACKS_STROPTS_H - -// Platform provides header. -#define ACE_HAS_EXECINFO_H - -// Wcharness.... -#define ACE_HAS_WCHAR -#define ACE_SIZEOF_WCHAR 4 - - -#define ACE_HAS_3_PARAM_WCSTOK -#define ACE_LACKS_ITOW -#define ACE_LACKS_WCSICMP -#define ACE_LACKS_WCSNICMP -#define ACE_LACKS_WCSDUP - -// Mac lacks the following pthread features -#define ACE_LACKS_MUTEXATTR_PSHARED -#define ACE_LACKS_CONDATTR_PSHARED -// -// Compiler/platform defines the sig_atomic_t typedef. -#define ACE_HAS_SIG_ATOMIC_T - -// Compiler/platform supports SVR4 signal typedef -#define ACE_HAS_SVR4_SIGNAL_T - -//Platform/compiler has the sigwait(2) prototype -#define ACE_HAS_SIGWAIT - -#define ACE_HAS_AIO_CALLS - -//Platform supports sigsuspend() -#define ACE_HAS_SIGSUSPEND - -#define ACE_LACKS_GETPGID -#define ACE_LACKS_RWLOCK_T - -// Optimize ACE_Handle_Set for select(). -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT - -#define ACE_HAS_NONCONST_SELECT_TIMEVAL - -#define ACE_NEEDS_SCHED_H - -// Use of is deprecated. -#define ACE_LACKS_MALLOC_H - -#define ACE_HAS_ALT_CUSERID - -// Platform supports POSIX timers via struct timespec. -#define ACE_HAS_POSIX_TIME -#define ACE_HAS_UALARM - -// Platform defines struct timespec but not timespec_t -#define ACE_LACKS_TIMESPEC_T - -#define ACE_LACKS_STRRECVFD - -#define ACE_HAS_SOCKADDR_IN_SIN_LEN -#define ACE_HAS_SOCKADDR_IN6_SIN6_LEN - -// Platform supports System V IPC (most versions of UNIX, but not Win32) -#define ACE_HAS_SYSV_IPC - -// Compiler/platform contains the file. -#define ACE_HAS_SYS_SYSCALL_H - -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES - -// Compiler/platform supports alloca(). -// Although ACE does have alloca() on this compiler/platform combination, it is -// disabled by default since it can be dangerous. Uncomment the following line -// if you ACE to use it. -//#define ACE_HAS_ALLOCA - -// Compiler/platform correctly calls init()/fini() for shared libraries. -#define ACE_HAS_AUTOMATIC_INIT_FINI - -// platform supports POSIX O_NONBLOCK semantics -#define ACE_HAS_POSIX_NONBLOCK - -// platform supports IP multicast -#define ACE_HAS_IP_MULTICAST -#define ACE_LACKS_PERFECT_MULTICAST_FILTERING 1 - -// Compiler/platform has the getrusage() system call. -#define ACE_HAS_GETRUSAGE - -// Compiler supports the ssize_t typedef. -#define ACE_HAS_SSIZE_T - -// Compiler/platform provides the sockio.h file. -#define ACE_HAS_SYS_SOCKIO_H - -// Compiler/platform provides the socklen_t type. -#define ACE_HAS_SOCKLEN_T - -// Defines the page size of the system. -#define ACE_HAS_GETPAGESIZE - -// Platform provides header. -#define ACE_HAS_SYS_FILIO_H - -// Platform/compiler supports timezone * as second parameter to gettimeofday(). -#define ACE_HAS_TIMEZONE_GETTIMEOFDAY - -#define ACE_LACKS_SYS_MSG_H -#define ACE_LACKS_SYSV_MSQ_PROTOS -#define ACE_HAS_MSG -#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG -#define ACE_HAS_NONCONST_MSGSND - -#if !defined (ACE_MT_SAFE) -# define ACE_MT_SAFE 1 -#endif - -#if ACE_MT_SAFE == 1 -// Yes, we do have threads. -# define ACE_HAS_THREADS -// And they're even POSIX pthreads -# define ACE_HAS_PTHREADS -# define ACE_HAS_PTHREADS_STD -# define ACE_HAS_PTHREAD_SCHEDPARAM -# define ACE_HAS_THREAD_SPECIFIC_STORAGE -#endif /* ACE_MT_SAFE == 1 */ - -#define ACE_LACKS_THREAD_PROCESS_SCOPING - -#define ACE_HAS_DIRENT -#define ACE_LACKS_POLL_H -#define ACE_LACKS_SEARCH_H - -#define ACE_LACKS_SETSCHED -//#define ACE_HAS_RECURSIVE_MUTEXES - -// Platform has POSIX terminal interface. -#define ACE_HAS_TERMIOS - -#define ACE_HAS_SEMUN -#define ACE_HAS_SIGINFO_T -#define ACE_LACKS_SIGINFO_H -#define ACE_HAS_UCONTEXT_T -#define ACE_HAS_GETIFADDRS -#define ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES -#define ACE_LACKS_UNNAMED_SEMAPHORE - -#if !defined (__DARWIN_UNIX03) -#define ACE_HAS_VOID_UNSETENV -#endif - - -// dlcompat package (not part of base Darwin) is needed for dlopen(). -// You may download directly from sourceforge and install or use fink -// Fink installer puts libraries in /sw/lib and headers in /sw/include -// In order to install dlcompat do the following: -// - download fink from http://fink.sf.net -// - type: -// fink install dlcompat -// as of Dec 2002, if you use fink you will need to uncomment the next line -// #define ACE_NEEDS_DL_UNDERSCORE -#define ACE_HAS_SVR4_DYNAMIC_LINKING -#define ACE_LD_SEARCH_PATH ACE_TEXT ("DYLD_LIBRARY_PATH") -#define ACE_DLL_SUFFIX ACE_TEXT (".dylib") -//#define ACE_LACKS_DLCLOSE - -// gperf seems to need this -//#define ACE_HAS_NONSTATIC_OBJECT_MANAGER - -#if defined(__APPLE_CC__) && (__APPLE_CC__ < 1173) -#error "Compiler must be upgraded, see http://developer.apple.com" -#endif /* __APPLE_CC__ */ - -#endif /* ACE_CONFIG_MACOSX_TIGER_H */ diff --git a/externals/ace/config-macosx-panther.h b/externals/ace/config-macosx-panther.h deleted file mode 100644 index 4b131f9867a..00000000000 --- a/externals/ace/config-macosx-panther.h +++ /dev/null @@ -1,182 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-macosx-panther.h 87167 2009-10-19 19:33:53Z olli $ - -// This configuration file is designed to work with the MacOS X operating system. - -#ifndef ACE_CONFIG_MACOSX_H -#define ACE_CONFIG_MACOSX_H - -#if ! defined (__ACE_INLINE__) -#define __ACE_INLINE__ -#endif /* ! __ACE_INLINE__ */ - -#if defined (__GNUG__) -# include "ace/config-g++-common.h" -#endif /* __GNUG__ */ - -#define ACE_LACKS_SUSECONDS_T -#define ACE_SIZE_T_FORMAT_SPECIFIER_ASCII "%lu" - -#if defined (ACE_HAS_PENTIUM) -# undef ACE_HAS_PENTIUM -#endif /* ACE_HAS_PENTIUM */ - -#if !defined (_THREAD_SAFE) -#define _THREAD_SAFE -#endif /* _THREAD_SAFE */ - -#define ACE_HAS_GPERF -#define ACE_HAS_POSIX_SEM - -//#define ACE_HAS_SVR4_TLI - -#define ACE_LACKS_STROPTS_H -#define ACE_LACKS_WCHAR_H - -// -// Compiler/platform defines the sig_atomic_t typedef. -#define ACE_HAS_SIG_ATOMIC_T - -// Compiler/platform supports SVR4 signal typedef -#define ACE_HAS_SVR4_SIGNAL_T - -//Platform/compiler has the sigwait(2) prototype -#define ACE_HAS_SIGWAIT - -//Platform supports sigsuspend() -#define ACE_HAS_SIGSUSPEND - -//#define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS -#define ACE_LACKS_GETPGID -#define ACE_LACKS_RWLOCK_T - -// Optimize ACE_Handle_Set for select(). -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT - -#define ACE_HAS_NONCONST_SELECT_TIMEVAL - -#define ACE_NEEDS_SCHED_H - -// Use of is deprecated. -#define ACE_LACKS_MALLOC_H - -#define ACE_HAS_ALT_CUSERID - -// Platform supports POSIX timers via struct timespec. -#define ACE_HAS_POSIX_TIME -#define ACE_HAS_UALARM - -// Platform defines struct timespec but not timespec_t -#define ACE_LACKS_TIMESPEC_T - -#define ACE_LACKS_STRRECVFD - -#define ACE_HAS_SOCKADDR_IN_SIN_LEN -#define ACE_HAS_SOCKADDR_IN6_SIN6_LEN - -// Platform supports System V IPC (most versions of UNIX, but not Win32) -#define ACE_HAS_SYSV_IPC - -// Compiler/platform contains the file. -#define ACE_HAS_SYS_SYSCALL_H - -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES - -// Compiler/platform supports alloca(). -// Although ACE does have alloca() on this compiler/platform combination, it is -// disabled by default since it can be dangerous. Uncomment the following line -// if you ACE to use it. -//#define ACE_HAS_ALLOCA - -// Compiler/platform correctly calls init()/fini() for shared libraries. -#define ACE_HAS_AUTOMATIC_INIT_FINI - -// Explicit dynamic linking permits "lazy" symbol resolution -//#define ACE_HAS_RTLD_LAZY_V - -// platform supports POSIX O_NONBLOCK semantics -#define ACE_HAS_POSIX_NONBLOCK - -// platform supports IP multicast -#define ACE_HAS_IP_MULTICAST -#define ACE_LACKS_PERFECT_MULTICAST_FILTERING 1 - -// Compiler/platform has the getrusage() system call. -#define ACE_HAS_GETRUSAGE - -// Compiler supports the ssize_t typedef. -#define ACE_HAS_SSIZE_T - -// Compiler/platform provides the sockio.h file. -#define ACE_HAS_SYS_SOCKIO_H - -// Defines the page size of the system. -#define ACE_HAS_GETPAGESIZE - -// Platform provides header. -#define ACE_HAS_SYS_FILIO_H - -// Platform/compiler supports timezone * as second parameter to gettimeofday(). -#define ACE_HAS_TIMEZONE_GETTIMEOFDAY - -#define ACE_LACKS_SYS_MSG_H -#define ACE_LACKS_SYSV_MSQ_PROTOS -#define ACE_HAS_MSG -#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG -#define ACE_HAS_NONCONST_MSGSND - -#if !defined (ACE_MT_SAFE) -# define ACE_MT_SAFE 1 -#endif - -#if ACE_MT_SAFE == 1 -// Yes, we do have threads. -# define ACE_HAS_THREADS -// And they're even POSIX pthreads -# define ACE_HAS_PTHREADS -# define ACE_HAS_PTHREAD_SCHEDPARAM -# define ACE_HAS_THREAD_SPECIFIC_STORAGE -#endif /* ACE_MT_SAFE == 1 */ - -# define ACE_LACKS_THREAD_PROCESS_SCOPING - -#define ACE_HAS_DIRENT -#define ACE_LACKS_POLL_H -#define ACE_LACKS_SEARCH_H - -#define ACE_LACKS_SETSCHED -//#define ACE_HAS_RECURSIVE_MUTEXES - -// Platform has POSIX terminal interface. -#define ACE_HAS_TERMIOS - -#define ACE_HAS_SEMUN -#define ACE_HAS_SIGINFO_T -#define ACE_LACKS_SIGINFO_H -#define ACE_HAS_UCONTEXT_T -#define ACE_HAS_GETIFADDRS -#define ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES -#define ACE_LACKS_UNNAMED_SEMAPHORE - -// dlcompat package (not part of base Darwin) is needed for dlopen(). -// You may download directly from sourceforge and install or use fink -// Fink installer puts libraries in /sw/lib and headers in /sw/include -// In order to install dlcompat do the following: -// - download fink from http://fink.sf.net -// - type: -// fink install dlcompat -// as of Dec 2002, if you use fink you will need to uncomment the next line -//#define ACE_NEEDS_DL_UNDERSCORE -#define ACE_HAS_SVR4_DYNAMIC_LINKING -#define ACE_LD_SEARCH_PATH ACE_TEXT ("DYLD_LIBRARY_PATH") -#define ACE_DLL_SUFFIX ACE_TEXT (".dylib") -//#define ACE_LACKS_DLCLOSE - -// gperf seems to need this -//#define ACE_HAS_NONSTATIC_OBJECT_MANAGER - -#if defined(__APPLE_CC__) && (__APPLE_CC__ < 1173) -#error "Compiler must be upgraded, see http://developer.apple.com" -#endif /* __APPLE_CC__ */ - -#endif /* ACE_CONFIG_MACOSX_H */ diff --git a/externals/ace/config-macosx-snowleopard.h b/externals/ace/config-macosx-snowleopard.h deleted file mode 100644 index 09e9458d6b9..00000000000 --- a/externals/ace/config-macosx-snowleopard.h +++ /dev/null @@ -1,17 +0,0 @@ -// $Id: config-macosx-snowleopard.h 91093 2010-07-15 09:12:20Z wotte $ -#ifndef ACE_CONFIG_MACOSX_SNOWLEOPARD_H -#define ACE_CONFIG_MACOSX_SNOWLEOPARD_H - - -#include "ace/config-macosx-leopard.h" - -#ifdef __clang__ -#ifdef ACE_HAS_GCC_ATOMIC_BUILTINS -#undef ACE_HAS_GCC_ATOMIC_BUILTINS -#endif -#endif - -// This header has been deprecated in Snow Leopard. -#define ACE_LACKS_UCONTEXT_H - -#endif // ACE_CONFIG_MACOSX_SNOWLEOPARD_H diff --git a/externals/ace/config-macosx-tiger.h b/externals/ace/config-macosx-tiger.h deleted file mode 100644 index f3d1ddcf8ad..00000000000 --- a/externals/ace/config-macosx-tiger.h +++ /dev/null @@ -1,213 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-macosx-tiger.h 87167 2009-10-19 19:33:53Z olli $ - -// This configuration file is designed to work with the MacOS X operating system. - -#ifndef ACE_CONFIG_MACOSX_TIGER_H -#define ACE_CONFIG_MACOSX_TIGER_H - -#if ! defined (__ACE_INLINE__) -#define __ACE_INLINE__ -#endif /* ! __ACE_INLINE__ */ - -#if !defined (ACE_SIZEOF_LONG_DOUBLE) -# if (__GNUC__ == 3 && __GNUC_MINOR__ == 3) - // Size of long double in GCC 3.3 is 8. -# define ACE_SIZEOF_LONG_DOUBLE 8 -# else // Else, the compiler is GCC4 - // For GCC4, the size is 16. -# define ACE_SIZEOF_LONG_DOUBLE 16 -# endif // GCC 3.3 -#endif // ACE_SIZEOF_LONG_DOUBLE - -#if defined (__GNUG__) -# include "ace/config-g++-common.h" -#endif /* __GNUG__ */ - -#define ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR - -#define ACE_SIZE_T_FORMAT_SPECIFIER_ASCII "%lu" - -#if !defined (__i386__) -# if defined (ACE_HAS_PENTIUM) -# undef ACE_HAS_PENTIUM -# endif /* ACE_HAS_PENTIUM */ -#else // __i386__ -# define ACE_HAS_PENTIUM -#endif //__i386__ - -#if !defined (_THREAD_SAFE) -#define _THREAD_SAFE -#endif /* _THREAD_SAFE */ - -#define ACE_HAS_GPERF -#define ACE_HAS_POSIX_SEM - -#define ACE_HAS_SUNOS4_GETTIMEOFDAY - -#define ACE_LACKS_STROPTS_H - -// Wcharness.... -#define ACE_HAS_WCHAR -#define ACE_SIZEOF_WCHAR 4 - - -#define ACE_HAS_3_PARAM_WCSTOK -#define ACE_LACKS_ITOW -#define ACE_LACKS_WCSICMP -#define ACE_LACKS_WCSNICMP -#define ACE_LACKS_WCSDUP - -// Mac lacks the following pthread features -#define ACE_LACKS_MUTEXATTR_PSHARED -#define ACE_LACKS_CONDATTR_PSHARED -// -// Compiler/platform defines the sig_atomic_t typedef. -#define ACE_HAS_SIG_ATOMIC_T - -// Compiler/platform supports SVR4 signal typedef -#define ACE_HAS_SVR4_SIGNAL_T - -//Platform/compiler has the sigwait(2) prototype -#define ACE_HAS_SIGWAIT - -#define ACE_HAS_AIO_CALLS - -//Platform supports sigsuspend() -#define ACE_HAS_SIGSUSPEND - -#define ACE_LACKS_GETPGID -#define ACE_LACKS_RWLOCK_T - -// Optimize ACE_Handle_Set for select(). -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT - -#define ACE_HAS_NONCONST_SELECT_TIMEVAL - -#define ACE_NEEDS_SCHED_H - -// Use of is deprecated. -#define ACE_LACKS_MALLOC_H - -#define ACE_HAS_ALT_CUSERID - -// Platform supports POSIX timers via struct timespec. -#define ACE_HAS_POSIX_TIME -#define ACE_HAS_UALARM - -// Platform defines struct timespec but not timespec_t -#define ACE_LACKS_TIMESPEC_T - -#define ACE_LACKS_STRRECVFD - -#define ACE_HAS_SOCKADDR_IN6_SIN6_LEN - -// Platform supports System V IPC (most versions of UNIX, but not Win32) -#define ACE_HAS_SYSV_IPC - -// Compiler/platform contains the file. -#define ACE_HAS_SYS_SYSCALL_H - -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES - -// Compiler/platform supports alloca(). -// Although ACE does have alloca() on this compiler/platform combination, it is -// disabled by default since it can be dangerous. Uncomment the following line -// if you ACE to use it. -//#define ACE_HAS_ALLOCA - -// Compiler/platform correctly calls init()/fini() for shared libraries. -#define ACE_HAS_AUTOMATIC_INIT_FINI - -// platform supports POSIX O_NONBLOCK semantics -#define ACE_HAS_POSIX_NONBLOCK - -// platform supports IP multicast -#define ACE_HAS_IP_MULTICAST -#define ACE_LACKS_PERFECT_MULTICAST_FILTERING 1 - -// Compiler/platform has the getrusage() system call. -#define ACE_HAS_GETRUSAGE - -// Compiler supports the ssize_t typedef. -#define ACE_HAS_SSIZE_T - -// Compiler/platform provides the sockio.h file. -#define ACE_HAS_SYS_SOCKIO_H - -// Compiler/platform provides the socklen_t type. -#define ACE_HAS_SOCKLEN_T - -// Defines the page size of the system. -#define ACE_HAS_GETPAGESIZE - -// Platform provides header. -#define ACE_HAS_SYS_FILIO_H - -// Platform/compiler supports timezone * as second parameter to gettimeofday(). -#define ACE_HAS_TIMEZONE_GETTIMEOFDAY - -#define ACE_LACKS_SYS_MSG_H -#define ACE_LACKS_SYSV_MSQ_PROTOS -#define ACE_HAS_MSG -#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG -#define ACE_HAS_NONCONST_MSGSND - -#if !defined (ACE_MT_SAFE) -# define ACE_MT_SAFE 1 -#endif - -#if ACE_MT_SAFE == 1 -// Yes, we do have threads. -# define ACE_HAS_THREADS -// And they're even POSIX pthreads -# define ACE_HAS_PTHREADS -# define ACE_HAS_PTHREAD_SCHEDPARAM -# define ACE_HAS_THREAD_SPECIFIC_STORAGE -#endif /* ACE_MT_SAFE == 1 */ - -#define ACE_LACKS_THREAD_PROCESS_SCOPING - -#define ACE_HAS_DIRENT -#define ACE_LACKS_POLL_H -#define ACE_LACKS_SEARCH_H - -#define ACE_LACKS_SETSCHED -//#define ACE_HAS_RECURSIVE_MUTEXES - -// Platform has POSIX terminal interface. -#define ACE_HAS_TERMIOS - -#define ACE_HAS_SEMUN -#define ACE_HAS_SIGINFO_T -#define ACE_LACKS_SIGINFO_H -#define ACE_HAS_UCONTEXT_T -#define ACE_HAS_GETIFADDRS -#define ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES -#define ACE_LACKS_UNNAMED_SEMAPHORE - -// dlcompat package (not part of base Darwin) is needed for dlopen(). -// You may download directly from sourceforge and install or use fink -// Fink installer puts libraries in /sw/lib and headers in /sw/include -// In order to install dlcompat do the following: -// - download fink from http://fink.sf.net -// - type: -// fink install dlcompat -// as of Dec 2002, if you use fink you will need to uncomment the next line -// #define ACE_NEEDS_DL_UNDERSCORE -#define ACE_HAS_SVR4_DYNAMIC_LINKING -#define ACE_LD_SEARCH_PATH ACE_TEXT ("DYLD_LIBRARY_PATH") -#define ACE_DLL_SUFFIX ACE_TEXT (".dylib") -//#define ACE_LACKS_DLCLOSE - -// gperf seems to need this -//#define ACE_HAS_NONSTATIC_OBJECT_MANAGER - -#define ACE_LACKS_UNSETENV -#define ACE_LACKS_ISCTYPE - -#if defined(__APPLE_CC__) && (__APPLE_CC__ < 1173) -#error "Compiler must be upgraded, see http://developer.apple.com" -#endif /* __APPLE_CC__ */ - -#endif /* ACE_CONFIG_MACOSX_TIGER_H */ diff --git a/externals/ace/config-macosx.h b/externals/ace/config-macosx.h deleted file mode 100644 index ae2552f14a2..00000000000 --- a/externals/ace/config-macosx.h +++ /dev/null @@ -1,182 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-macosx.h 87167 2009-10-19 19:33:53Z olli $ - -// This configuration file is designed to work with the MacOS X operating system, version 10.2 (Jaguar). - -#ifndef ACE_CONFIG_MACOSX_H -#define ACE_CONFIG_MACOSX_H - -#if ! defined (__ACE_INLINE__) -#define __ACE_INLINE__ -#endif /* ! __ACE_INLINE__ */ - -#if defined (__GNUG__) -# include "ace/config-g++-common.h" -#endif /* __GNUG__ */ - -#define ACE_SIZE_T_FORMAT_SPECIFIER_ASCII "%lu" - -#if defined (ACE_HAS_PENTIUM) -# undef ACE_HAS_PENTIUM -#endif /* ACE_HAS_PENTIUM */ - -#if !defined (_THREAD_SAFE) -#define _THREAD_SAFE -#endif /* _THREAD_SAFE */ - -#define ACE_HAS_GPERF -#define ACE_HAS_POSIX_SEM - -//#define ACE_HAS_SVR4_TLI - -#define ACE_LACKS_STROPTS_H -#define ACE_LACKS_WCHAR_H - -#define ACE_SYS_SELECT_NEEDS_UNISTD_H - -// -// Compiler/platform defines the sig_atomic_t typedef. -#define ACE_HAS_SIG_ATOMIC_T - -// Compiler/platform supports SVR4 signal typedef -#define ACE_HAS_SVR4_SIGNAL_T - -//Platform/compiler has the sigwait(2) prototype -#define ACE_HAS_SIGWAIT - -//Platform supports sigsuspend() -#define ACE_HAS_SIGSUSPEND - -//#define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS -#define ACE_LACKS_GETPGID -#define ACE_LACKS_RWLOCK_T - -// Optimize ACE_Handle_Set for select(). -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT - -#define ACE_HAS_NONCONST_SELECT_TIMEVAL - -#define ACE_HAS_SYSCTL - -#define ACE_NEEDS_SCHED_H - -// Use of is deprecated. -#define ACE_LACKS_MALLOC_H - -#define ACE_HAS_ALT_CUSERID - -// Platform supports POSIX timers via struct timespec. -#define ACE_HAS_POSIX_TIME -#define ACE_HAS_UALARM - -// Platform defines struct timespec but not timespec_t -#define ACE_LACKS_TIMESPEC_T - -#define ACE_LACKS_STRRECVFD - -#define ACE_HAS_SOCKADDR_IN6_SIN6_LEN - -// Platform supports System V IPC (most versions of UNIX, but not Win32) -//#define ACE_HAS_SYSV_IPC - -// Compiler/platform contains the file. -#define ACE_HAS_SYS_SYSCALL_H - -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES - -// Compiler/platform supports alloca(). -// Although ACE does have alloca() on this compiler/platform combination, it is -// disabled by default since it can be dangerous. Uncomment the following line -// if you ACE to use it. -//#define ACE_HAS_ALLOCA - -// Compiler/platform correctly calls init()/fini() for shared libraries. -#define ACE_HAS_AUTOMATIC_INIT_FINI - -// Explicit dynamic linking permits "lazy" symbol resolution -//#define ACE_HAS_RTLD_LAZY_V - -// platform supports POSIX O_NONBLOCK semantics -#define ACE_HAS_POSIX_NONBLOCK - -// platform supports IP multicast -#define ACE_HAS_IP_MULTICAST -#define ACE_LACKS_PERFECT_MULTICAST_FILTERING 1 - -// Compiler/platform has the getrusage() system call. -#define ACE_HAS_GETRUSAGE - -// Compiler supports the ssize_t typedef. -#define ACE_HAS_SSIZE_T - -// Compiler/platform provides the sockio.h file. -#define ACE_HAS_SYS_SOCKIO_H - -// Defines the page size of the system. -#define ACE_HAS_GETPAGESIZE - -// Platform provides header. -#define ACE_HAS_SYS_FILIO_H - -// Platform/compiler supports timezone * as second parameter to gettimeofday(). -#define ACE_HAS_TIMEZONE_GETTIMEOFDAY - -#define ACE_LACKS_SYS_MSG_H -#define ACE_LACKS_SYSV_MSQ_PROTOS -#define ACE_HAS_MSG -#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG -#define ACE_HAS_NONCONST_MSGSND - -#if !defined (ACE_MT_SAFE) -# define ACE_MT_SAFE 1 -#endif - -#if ACE_MT_SAFE == 1 -// Yes, we do have threads. -# define ACE_HAS_THREADS -// And they're even POSIX pthreads -# define ACE_HAS_PTHREADS -# define ACE_HAS_THREAD_SPECIFIC_STORAGE -# define ACE_LACKS_THREAD_PROCESS_SCOPING -#endif /* ACE_MT_SAFE == 1 */ - -#define ACE_HAS_DIRENT -#define ACE_LACKS_POLL_H -#define ACE_LACKS_SEARCH_H - -#define ACE_LACKS_SETSCHED -//#define ACE_HAS_RECURSIVE_MUTEXES - -// Platform has POSIX terminal interface. -#define ACE_HAS_TERMIOS - -#define ACE_HAS_SEMUN -#define ACE_HAS_SIGINFO_T -#define ACE_LACKS_SIGINFO_H -#define ACE_HAS_UCONTEXT_T -#define ACE_HAS_GETIFADDRS -#define ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES -#define ACE_LACKS_UNNAMED_SEMAPHORE - -// dlcompat package (not part of base Darwin) is needed for dlopen(). -// You may download directly from sourceforge and install or use fink -// Fink installer puts libraries in /sw/lib and headers in /sw/include -// In order to install dlcompat do the following: -// - download fink from http://fink.sf.net -// - type: -// fink install dlcompat -// as of Dec 2002, if you use fink you will need to uncomment the next line -//#define ACE_NEEDS_DL_UNDERSCORE -#define ACE_HAS_SVR4_DYNAMIC_LINKING -#define ACE_LD_SEARCH_PATH ACE_TEXT ("DYLD_LIBRARY_PATH") -#define ACE_DLL_SUFFIX ACE_TEXT (".dylib") -#define ACE_LACKS_DLCLOSE - -// gperf seems to need this -#define ACE_HAS_NONSTATIC_OBJECT_MANAGER - -#if defined(__APPLE_CC__) && (__APPLE_CC__ < 1173) -#error "Compiler must be upgraded, see http://developer.apple.com" -#endif /* __APPLE_CC__ */ - -#endif /* ACE_CONFIG_MACOSX_H */ diff --git a/externals/ace/config-macros.h b/externals/ace/config-macros.h deleted file mode 100644 index 6820fc351d9..00000000000 --- a/externals/ace/config-macros.h +++ /dev/null @@ -1,655 +0,0 @@ -// -*- C++ -*- - -//========================================================================== -/** - * @file config-macros.h - * - * $Id: config-macros.h 88485 2010-01-12 13:36:59Z schmidt $ - * - * @author (Originally in OS.h)Doug Schmidt - * @author Jesper S. M|ller - * @author and a cast of thousands... - * - * This file contains the contents of the old config-lite.h header - * without C++ code (except for C++ code in macros). Specifically, - * only macros or C language constructs are found in this header. - * Allows configuration values and macros to be used by some C - * language sources. - */ -//========================================================================== - -#ifndef ACE_CONFIG_MACROS_H -#define ACE_CONFIG_MACROS_H - -#ifdef _WIN32 - #include "ace/config-win32.h" -#else - #include "ace/config.h" -#endif - -#include "ace/Version.h" -#include "ace/Versioned_Namespace.h" - -// ACE_HAS_TLI is used to decide whether to try any XTI/TLI functionality -// so if it isn't set, set it. Capabilities and differences between -// XTI and TLI favor XTI, but when deciding to do anything, as opposed to -// ACE_NOTSUP_RETURN for example, ACE_HAS_TLI is the deciding factor. -#if !defined (ACE_HAS_TLI) -# if defined (ACE_HAS_XTI) -# define ACE_HAS_TLI -# endif /* ACE_HAS_XTI */ -#endif /* ACE_HAS_TLI */ - -#define ACE_BITS_PER_ULONG (8 * sizeof (u_long)) - -#if !defined (ACE_OSTREAM_TYPE) -# if defined (ACE_LACKS_IOSTREAM_TOTALLY) -# define ACE_OSTREAM_TYPE FILE -# else /* ! ACE_LACKS_IOSTREAM_TOTALLY */ -# define ACE_OSTREAM_TYPE ostream -# endif /* ! ACE_LACKS_IOSTREAM_TOTALLY */ -#endif /* ! ACE_OSTREAM_TYPE */ - -#if !defined (ACE_DEFAULT_LOG_STREAM) -# if defined (ACE_LACKS_IOSTREAM_TOTALLY) -# define ACE_DEFAULT_LOG_STREAM 0 -# else /* ! ACE_LACKS_IOSTREAM_TOTALLY */ -# define ACE_DEFAULT_LOG_STREAM (&cerr) -# endif /* ! ACE_LACKS_IOSTREAM_TOTALLY */ -#endif /* ! ACE_DEFAULT_LOG_STREAM */ - -// These two are only for backward compatibility. You should avoid -// using them if not necessary. -#if !defined (ACE_LACKS_DEPRECATED_MACROS) -/** - * @deprecated The ACE_SYNCH_1 macro is deprecated - */ -# define ACE_SYNCH_1 ACE_SYNCH_DECL -/** - * @deprecated The ACE_SYNCH_2 macro is deprecated - */ -# define ACE_SYNCH_2 ACE_SYNCH_USE -#endif - -// For Win32 compatibility... -# if !defined (ACE_WSOCK_VERSION) -# define ACE_WSOCK_VERSION 0, 0 -# endif /* ACE_WSOCK_VERSION */ - -# if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) -# define ACE_MT(X) X -# if !defined (_REENTRANT) -# define _REENTRANT -# endif /* _REENTRANT */ -# else -# define ACE_MT(X) -# endif /* ACE_MT_SAFE */ - -# if defined (ACE_HAS_PURIFY) -# define ACE_INITIALIZE_MEMORY_BEFORE_USE -# endif /* ACE_HAS_PURIFY */ - -# if defined (ACE_HAS_VALGRIND) -# define ACE_INITIALIZE_MEMORY_BEFORE_USE -# endif /* ACE_HAS_VALGRIND */ - -#if !defined (ACE_LACKS_DEPRECATED_MACROS) -/** - * @deprecated The @c ACE_HAS_USING macros are deprecated - */ -# define ACE_USING using -#endif /* !ACE_LACKS_DEPRECATED_MACROS */ - -#if !defined (ACE_LACKS_DEPRECATED_MACROS) -/** - * @deprecated The @c ACE_TYPENAME macros is deprecated. Use standard - * C++ keyword typename instead. - */ -# define ACE_TYPENAME typename -#endif /* !ACE_LACKS_DEPRECATED_MACROS */ - -#if !defined (ACE_LACKS_DEPRECATED_MACROS) -/** - * @deprecated The @c ACE_TEMPLATE_SPECIALIZATION and - * @c ACE_TEMPLATE_CLASS_MEMBER_SPECIALIZATION macros are - * deprecated. Use standard C++ template specialization - * syntax instead. - */ -# define ACE_TEMPLATE_SPECIALIZATION template<> -# define ACE_TEMPLATE_CLASS_MEMBER_SPECIALIZATION -#endif /* !ACE_LACKS_DEPRECATED_MACROS */ - -// ========================================================================= -// Perfect Multicast filting refers to RFC 3376, where a socket is only -// delivered dgrams for groups joined even if it didn't bind the group -// address. We turn this option off by default, although most OS's -// except for Windows and Solaris probably lack perfect filtering. -// ========================================================================= - -# if !defined (ACE_LACKS_PERFECT_MULTICAST_FILTERING) -# define ACE_LACKS_PERFECT_MULTICAST_FILTERING 0 -# endif /* ACE_LACKS_PERFECT_MULTICAST_FILTERING */ - -// ========================================================================= -// Enable/Disable Features By Default -// ========================================================================= - -# if !defined (ACE_HAS_POSITION_INDEPENDENT_POINTERS) -# define ACE_HAS_POSITION_INDEPENDENT_POINTERS 1 -# endif /* ACE_HAS_POSITION_INDEPENDENT_POINTERS */ - -# if !defined (ACE_HAS_PROCESS_SPAWN) -# if !defined (ACE_LACKS_FORK) || \ - (defined (ACE_WIN32) && !defined (ACE_HAS_PHARLAP)) || \ - defined (ACE_WINCE) || defined (ACE_OPENVMS) -# define ACE_HAS_PROCESS_SPAWN 1 -# endif -# endif /* ACE_HAS_PROCESS_SPAWN */ - -# if !defined (ACE_HAS_DYNAMIC_LINKING) -# if defined (ACE_HAS_SVR4_DYNAMIC_LINKING) || defined (ACE_WIN32) || defined (ACE_VXWORKS) || defined (__hpux) -# define ACE_HAS_DYNAMIC_LINKING 1 -# endif -# endif /* ACE_HAS_DYNAMIC_LINKING */ - -# if defined (ACE_USES_FIFO_SEM) -# if defined (ACE_HAS_POSIX_SEM) || defined (ACE_LACKS_MKFIFO) || defined (ACE_LACKS_FCNTL) -# undef ACE_USES_FIFO_SEM -# endif -# endif /* ACE_USES_FIFO_SEM */ - -// ========================================================================= -// RCSID Macros -// ========================================================================= - -// By default, DO NOT include RCS Id strings in object code. -#if ! defined (ACE_USE_RCSID) -# define ACE_USE_RCSID 0 -#endif /* #if ! defined (ACE_USE_RCSID) */ - -#if (defined (ACE_USE_RCSID) && (ACE_USE_RCSID != 0)) -# if ! defined (ACE_RCSID) - - // This hack has the following purposes: - // 1. To define the RCS id string variable as a static char*, so - // that there won't be any duplicate extern symbols at link - // time. - // 2. To have a RCS id string variable with a unique name for each - // file. - // 3. To avoid warnings of the type "variable declared and never - // used". - -# define ACE_RCSID(path, file, id) \ - static inline const char* get_rcsid_ ## path ## _ ## file (const char*) \ - { \ - return id ; \ - } \ - static const char* rcsid_ ## path ## _ ## file = \ - get_rcsid_ ## path ## _ ## file ( rcsid_ ## path ## _ ## file ) ; - -# endif /* #if ! defined (ACE_RCSID) */ -#else - - // RCS id strings are not wanted. -# if defined (ACE_RCSID) -# undef ACE_RCSID -# endif /* #if defined (ACE_RCSID) */ -# define ACE_RCSID(path, file, id) /* noop */ -#endif /* #if (defined (ACE_USE_RCSID) && (ACE_USE_RCSID != 0)) */ - -// ========================================================================= -// INLINE macros -// -// These macros handle all the inlining of code via the .i or .inl files -// ========================================================================= - -#if defined (ACE_LACKS_INLINE_FUNCTIONS) && !defined (ACE_NO_INLINE) -# define ACE_NO_INLINE -#endif /* defined (ACE_LACKS_INLINE_FUNCTIONS) && !defined (ACE_NO_INLINE) */ - -// ACE inlining has been explicitly disabled. Implement -// internally within ACE by undefining __ACE_INLINE__. -#if defined (ACE_NO_INLINE) -# undef __ACE_INLINE__ -#endif /* ! ACE_NO_INLINE */ - -#if defined (__ACE_INLINE__) -# define ACE_INLINE inline -# if !defined (ACE_HAS_INLINED_OSCALLS) -# define ACE_HAS_INLINED_OSCALLS -# endif /* !ACE_HAS_INLINED_OSCALLS */ -#else -# define ACE_INLINE -#endif /* __ACE_INLINE__ */ - -#if !defined (ACE_LACKS_DEPRECATED_MACROS) - // ========================================================================= - // EXPLICIT macro - // ========================================================================= - - /** - * @deprecated explicit is deprecated. ACE requires C++ - * "explicit" keyword support. - */ - # define ACE_EXPLICIT explicit -#endif /* ACE_LACKS_DEPRECATED_MACROS */ - -#if !defined (ACE_LACKS_DEPRECATED_MACROS) - // ========================================================================= - // MUTABLE macro - // ========================================================================= - - /** - * @deprecated ACE_MUTABLE is deprecated. ACE requires C++ "mutable" - * keyword support. - */ - # define ACE_MUTABLE mutable - # define ACE_CONST_WHEN_MUTABLE const -#endif /* ACE_LACKS_DEPRECATED_MACROS */ - -// ============================================================================ -// EXPORT macros -// -// Since Win32 DLL's do not export all symbols by default, they must be -// explicitly exported (which is done by *_Export macros). -// ============================================================================ - -// Win32 should have already defined the macros in config-win32-common.h -#if !defined (ACE_HAS_CUSTOM_EXPORT_MACROS) -# define ACE_Proper_Export_Flag -# define ACE_Proper_Import_Flag -# define ACE_EXPORT_SINGLETON_DECLARATION(T) -# define ACE_IMPORT_SINGLETON_DECLARATION(T) -# define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) -# define ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) -#else -// An export macro should at the very least have been defined. - -# ifndef ACE_Proper_Import_Flag -# define ACE_Proper_Import_Flag -# endif /* !ACE_Proper_Import_Flag */ - -# ifndef ACE_EXPORT_SINGLETON_DECLARATION -# define ACE_EXPORT_SINGLETON_DECLARATION(T) -# endif /* !ACE_EXPORT_SINGLETON_DECLARATION */ - -# ifndef ACE_IMPORT_SINGLETON_DECLARATION -# define ACE_IMPORT_SINGLETON_DECLARATION(T) -# endif /* !ACE_IMPORT_SINGLETON_DECLARATION */ - -# ifndef ACE_EXPORT_SINGLETON_DECLARE -# define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) -# endif /* !ACE_EXPORT_SINGLETON_DECLARE */ - -# ifndef ACE_IMPORT_SINGLETON_DECLARE -# define ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) -# endif /* !ACE_IMPORT_SINGLETON_DECLARE */ - -#endif /* !ACE_HAS_CUSTOM_EXPORT_MACROS */ - -// This is a whim of mine -- that instead of annotating a class with -// ACE_Export in its declaration, we make the declaration near the TOP -// of the file with ACE_DECLARE_EXPORT. -// TS = type specifier (e.g., class, struct, int, etc.) -// ID = identifier -// So, how do you use it? Most of the time, just use ... -// ACE_DECLARE_EXPORT(class, someobject); -// If there are global functions to be exported, then use ... -// ACE_DECLARE_EXPORT(void, globalfunction) (int, ...); -// Someday, when template libraries are supported, we made need ... -// ACE_DECLARE_EXPORT(template class, sometemplate) ; -# define ACE_DECLARE_EXPORT(TS,ID) TS ACE_Export ID - -// ============================================================================ -// Cast macros -// -// These macros are used to choose between the old cast style and the new -// *_cast<> operators -// ============================================================================ - -# define ACE_sap_any_cast(TYPE) reinterpret_cast (const_cast (ACE_Addr::sap_any)) - -#if !defined (ACE_LACKS_DEPRECATED_MACROS) - /** - * @deprecated ACE_{static,reinterpret,dynamic,const}_cast@<@> is - * deprecated. Directly use standard C++ casts instead. - */ - # define ACE_static_cast(TYPE, EXPR) static_cast (EXPR) - # define ACE_static_cast_1_ptr(TYPE, T1, EXPR) static_cast *> (EXPR) - # define ACE_static_cast_2_ptr(TYPE, T1, T2, EXPR) static_cast *> (EXPR) - # define ACE_static_cast_3_ptr(TYPE, T1, T2, T3, EXPR) static_cast *> (EXPR) - # define ACE_static_cast_4_ptr(TYPE, T1, T2, T3, T4, EXPR) static_cast *> (EXPR) - # define ACE_static_cast_5_ptr(TYPE, T1, T2, T3, T4, T5, EXPR) static_cast *> (EXPR) - # define ACE_static_cast_1_ref(TYPE, T1, EXPR) static_cast &> (EXPR) - # define ACE_static_cast_2_ref(TYPE, T1, T2, EXPR) static_cast &> (EXPR) - # define ACE_static_cast_3_ref(TYPE, T1, T2, T3, EXPR) static_cast &> (EXPR) - # define ACE_static_cast_4_ref(TYPE, T1, T2, T3, T4, EXPR) static_cast &> (EXPR) - # define ACE_static_cast_5_ref(TYPE, T1, T2, T3, T4, T5, EXPR) static_cast &> (EXPR) - - # define ACE_const_cast(TYPE, EXPR) const_cast (EXPR) - # define ACE_const_cast_1_ptr(TYPE, T1, EXPR) const_cast *> (EXPR) - # define ACE_const_cast_2_ptr(TYPE, T1, T2, EXPR) const_cast *> (EXPR) - # define ACE_const_cast_3_ptr(TYPE, T1, T2, T3, EXPR) const_cast *> (EXPR) - # define ACE_const_cast_4_ptr(TYPE, T1, T2, T3, T4, EXPR) const_cast *> (EXPR) - # define ACE_const_cast_5_ptr(TYPE, T1, T2, T3, T4, T5, EXPR) const_cast *> (EXPR) - # define ACE_const_cast_1_ref(TYPE, T1, EXPR) const_cast &> (EXPR) - # define ACE_const_cast_2_ref(TYPE, T1, T2, EXPR) const_cast &> (EXPR) - # define ACE_const_cast_3_ref(TYPE, T1, T2, T3, EXPR) const_cast &> (EXPR) - # define ACE_const_cast_4_ref(TYPE, T1, T2, T3, T4, EXPR) const_cast &> (EXPR) - # define ACE_const_cast_5_ref(TYPE, T1, T2, T3, T4, T5, EXPR) const_cast &> (EXPR) - - # define ACE_reinterpret_cast(TYPE, EXPR) reinterpret_cast (EXPR) - # define ACE_reinterpret_cast_1_ptr(TYPE, T1, EXPR) reinterpret_cast *> (EXPR) - # define ACE_reinterpret_cast_2_ptr(TYPE, T1, T2, EXPR) reinterpret_cast *> (EXPR) - # define ACE_reinterpret_cast_3_ptr(TYPE, T1, T2, T3, EXPR) reinterpret_cast *> (EXPR) - # define ACE_reinterpret_cast_4_ptr(TYPE, T1, T2, T3, T4, EXPR) reinterpret_cast *> (EXPR) - # define ACE_reinterpret_cast_5_ptr(TYPE, T1, T2, T3, T4, T5, EXPR) reinterpret_cast *> (EXPR) - # define ACE_reinterpret_cast_1_ref(TYPE, T1, EXPR) reinterpret_cast &> (EXPR) - # define ACE_reinterpret_cast_2_ref(TYPE, T1, T2, EXPR) reinterpret_cast &> (EXPR) - # define ACE_reinterpret_cast_3_ref(TYPE, T1, T2, T3, EXPR) reinterpret_cast &> (EXPR) - # define ACE_reinterpret_cast_4_ref(TYPE, T1, T2, T3, T4, EXPR) reinterpret_cast &> (EXPR) - # define ACE_reinterpret_cast_5_ref(TYPE, T1, T2, T3, T4, T5, EXPR) reinterpret_cast &> (EXPR) - - # define ACE_dynamic_cast(TYPE, EXPR) dynamic_cast (EXPR) - # define ACE_dynamic_cast_1_ptr(TYPE, T1, EXPR) dynamic_cast *> (EXPR) - # define ACE_dynamic_cast_2_ptr(TYPE, T1, T2, EXPR) dynamic_cast *> (EXPR) - # define ACE_dynamic_cast_3_ptr(TYPE, T1, T2, T3, EXPR) dynamic_cast *> (EXPR) - # define ACE_dynamic_cast_4_ptr(TYPE, T1, T2, T3, T4, EXPR) dynamic_cast *> (EXPR) - # define ACE_dynamic_cast_5_ptr(TYPE, T1, T2, T3, T4, T5, EXPR) dynamic_cast *> (EXPR) - # define ACE_dynamic_cast_1_ref(TYPE, T1, EXPR) dynamic_cast &> (EXPR) - # define ACE_dynamic_cast_2_ref(TYPE, T1, T2, EXPR) dynamic_cast &> (EXPR) - # define ACE_dynamic_cast_3_ref(TYPE, T1, T2, T3, EXPR) dynamic_cast &> (EXPR) - # define ACE_dynamic_cast_4_ref(TYPE, T1, T2, T3, T4, EXPR) dynamic_cast &> (EXPR) - # define ACE_dynamic_cast_5_ref(TYPE, T1, T2, T3, T4, T5, EXPR) dynamic_cast &> (EXPR) -#endif /* ACE_LACKS_DEPRECATED_MACROS */ - -# if !defined (ACE_CAST_CONST) - // Sun CC 4.2, for example, requires const in reinterpret casts of - // data members in const member functions. But, other compilers - // complain about the useless const. This keeps everyone happy. -# if defined (__SUNPRO_CC) -# define ACE_CAST_CONST const -# else /* ! __SUNPRO_CC */ -# define ACE_CAST_CONST -# endif /* ! __SUNPRO_CC */ -# endif /* ! ACE_CAST_CONST */ - -// ============================================================================ -// Compiler Silencing macros -// -// Some compilers complain about parameters that are not used. This macro -// should keep them quiet. -// ============================================================================ - -#if !defined (ACE_UNUSED_ARG) -# if defined (__GNUC__) && ((__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2))) -# define ACE_UNUSED_ARG(a) (void) (a) -# elif defined (__GNUC__) || defined (ghs) || defined (__hpux) || defined (__sgi) || defined (__DECCXX) || defined (__rational__) || defined (__USLC__) || defined (ACE_RM544) || defined (__DCC__) || defined (__PGI) || defined (__TANDEM) -// Some compilers complain about "statement with no effect" with (a). -// This eliminates the warnings, and no code is generated for the null -// conditional statement. @note that may only be true if -O is enabled, -// such as with GreenHills (ghs) 1.8.8. -# define ACE_UNUSED_ARG(a) do {/* null */} while (&a == 0) -# elif defined (__DMC__) - #define ACE_UNUSED_ID(identifier) - template - inline void ACE_UNUSED_ARG(const T& ACE_UNUSED_ID(t)) { } -# else /* ghs || __GNUC__ || ..... */ -# define ACE_UNUSED_ARG(a) (a) -# endif /* ghs || __GNUC__ || ..... */ -#endif /* !ACE_UNUSED_ARG */ - -#if defined (_MSC_VER) || defined(__sgi) || defined (ghs) || defined (__DECCXX) || defined(__BORLANDC__) || defined (ACE_RM544) || defined (__USLC__) || defined (__DCC__) || defined (__PGI) || defined (__TANDEM) || (defined (__HP_aCC) && (__HP_aCC < 40000 || __HP_aCC >= 60500)) -# define ACE_NOTREACHED(a) -#else /* __sgi || ghs || ..... */ -# define ACE_NOTREACHED(a) a -#endif /* __sgi || ghs || ..... */ - -// ============================================================================ -// ACE_ALLOC_HOOK* macros -// -// Macros to declare and define class-specific allocation operators. -// ============================================================================ - -# if defined (ACE_HAS_ALLOC_HOOKS) -# define ACE_ALLOC_HOOK_DECLARE \ - void *operator new (size_t bytes); \ - void operator delete (void *ptr); - - // Note that these are just place holders for now. Some day they - // may be be replaced by . -# define ACE_ALLOC_HOOK_DEFINE(CLASS) \ - void *CLASS::operator new (size_t bytes) { return ::new char[bytes]; } \ - void CLASS::operator delete (void *ptr) { delete [] ((char *) ptr); } -# else -# define ACE_ALLOC_HOOK_DECLARE struct __Ace {} /* Just need a dummy... */ -# define ACE_ALLOC_HOOK_DEFINE(CLASS) -# endif /* ACE_HAS_ALLOC_HOOKS */ - -// ============================================================================ -/** - * ACE_OSCALL* macros - * - * @deprecated ACE_OSCALL_RETURN and ACE_OSCALL should not be used. - * Please restart system calls in your application code. - * See the @c sigaction(2) man page for documentation - * regarding enabling restartable system calls across - * signals via the @c SA_RESTART flag. - * - * The following two macros used ensure that system calls are properly - * restarted (if necessary) when interrupts occur. However, that - * capability was never enabled by any of our supported platforms. - * In fact, some parts of ACE would not function properly when that - * ability was enabled. Furthermore, they assumed that ability to - * restart system calls was determined statically. That assumption - * does not hold for modern platforms, where that ability is - * determined dynamically at run-time. - */ -// ============================================================================ - -#define ACE_OSCALL_RETURN(X,TYPE,FAILVALUE) \ - do \ - return (TYPE) (X); \ - while (0) -#define ACE_OSCALL(X,TYPE,FAILVALUE,RESULT) \ - do \ - RESULT = (TYPE) (X); \ - while (0) - -#if defined (ACE_WIN32) -# define ACE_WIN32CALL_RETURN(X,TYPE,FAILVALUE) \ - do { \ - TYPE ace_result_; \ - ace_result_ = (TYPE) X; \ - if (ace_result_ == FAILVALUE) \ - ACE_OS::set_errno_to_last_error (); \ - return ace_result_; \ - } while (0) -# define ACE_WIN32CALL(X,TYPE,FAILVALUE,RESULT) \ - do { \ - RESULT = (TYPE) X; \ - if (RESULT == FAILVALUE) \ - ACE_OS::set_errno_to_last_error (); \ - } while (0) -#endif /* ACE_WIN32 */ - -// The C99 security-improved run-time returns an error value on failure; -// 0 on success. -#if defined (ACE_HAS_TR24731_2005_CRT) -# define ACE_SECURECRTCALL(X,TYPE,FAILVALUE,RESULT) \ - do { \ - errno_t ___ = X; \ - if (___ != 0) { errno = ___; RESULT = FAILVALUE; } \ - } while (0) -#endif /* ACE_HAS_TR24731_2005_CRT */ - -// ============================================================================ -// Fundamental types -// ============================================================================ - -#if defined (ACE_WIN32) - -typedef HANDLE ACE_HANDLE; -typedef SOCKET ACE_SOCKET; -# define ACE_INVALID_HANDLE INVALID_HANDLE_VALUE - -#else /* ! ACE_WIN32 */ - -typedef int ACE_HANDLE; -typedef ACE_HANDLE ACE_SOCKET; -# define ACE_INVALID_HANDLE -1 - -#endif /* ACE_WIN32 */ - -// Define the type that's returned from the platform's native thread -// functions. ACE_THR_FUNC_RETURN is the type defined as the thread -// function's return type, except when the thread function doesn't return -// anything (pSoS). The ACE_THR_FUNC_NO_RETURN_VAL macro is used to -// indicate that the actual thread function doesn't return anything. The -// rest of ACE uses a real type so there's no a ton of conditional code -// everywhere to deal with the possibility of no return type. -# if defined (ACE_VXWORKS) && !defined (ACE_HAS_PTHREADS) -# include /**/ -typedef int ACE_THR_FUNC_RETURN; -#define ACE_HAS_INTEGRAL_TYPE_THR_FUNC_RETURN -# elif defined (ACE_WIN32) -typedef DWORD ACE_THR_FUNC_RETURN; -#define ACE_HAS_INTEGRAL_TYPE_THR_FUNC_RETURN -# else -typedef void* ACE_THR_FUNC_RETURN; -# endif /* ACE_VXWORKS */ -typedef ACE_THR_FUNC_RETURN (*ACE_THR_FUNC)(void *); - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ -typedef void (*ACE_THR_C_DEST)(void *); -#ifdef __cplusplus -} -#endif /* __cplusplus */ -typedef void (*ACE_THR_DEST)(void *); - -// Now some platforms have special requirements... -# if defined (ACE_VXWORKS) && !defined (ACE_HAS_PTHREADS) -typedef FUNCPTR ACE_THR_FUNC_INTERNAL; // where typedef int (*FUNCPTR) (...) -# else -typedef ACE_THR_FUNC ACE_THR_FUNC_INTERNAL; -# endif /* ACE_VXWORKS */ - -# ifdef __cplusplus -extern "C" -{ -# endif /* __cplusplus */ -# if defined (ACE_VXWORKS) && !defined (ACE_HAS_PTHREADS) -typedef FUNCPTR ACE_THR_C_FUNC; // where typedef int (*FUNCPTR) (...) -# else -typedef ACE_THR_FUNC_RETURN (*ACE_THR_C_FUNC)(void *); -# endif /* ACE_VXWORKS */ -# ifdef __cplusplus -} -# endif /* __cplusplus */ - -// ============================================================================ -// Macros for controlling the lifetimes of dlls loaded by ACE_DLL--including -// all dlls loaded via the ACE Service Config framework. -// -// Please don't change these values or add new ones wantonly, since we use -// the ACE_BIT_ENABLED, etc..., macros to test them. -// ============================================================================ - -// Per-process policy that unloads dlls eagerly. -#define ACE_DLL_UNLOAD_POLICY_PER_PROCESS 0 -// Apply policy on a per-dll basis. If the dll doesn't use one of the macros -// below, the current per-process policy will be used. -#define ACE_DLL_UNLOAD_POLICY_PER_DLL 1 -// Don't unload dll when refcount reaches zero, i.e., wait for either an -// explicit unload request or program exit. -#define ACE_DLL_UNLOAD_POLICY_LAZY 2 -// Default policy allows dlls to control their own destinies, but will -// unload those that don't make a choice eagerly. -#define ACE_DLL_UNLOAD_POLICY_DEFAULT ACE_DLL_UNLOAD_POLICY_PER_DLL - -// Add this macro you one of your cpp file in your dll. X should -// be either ACE_DLL_UNLOAD_POLICY_DEFAULT or ACE_DLL_UNLOAD_POLICY_LAZY. -#define ACE_DLL_UNLOAD_POLICY(CLS,X) \ -extern "C" u_long CLS##_Export _get_dll_unload_policy (void) \ - { return X;} - -// ============================================================================ -// ACE_USES_CLASSIC_SVC_CONF macro -// ============================================================================ - -// For now, default is to use the classic svc.conf format. -#if !defined (ACE_USES_CLASSIC_SVC_CONF) -# if defined (ACE_HAS_CLASSIC_SVC_CONF) && defined (ACE_HAS_XML_SVC_CONF) -# error You can only use either CLASSIC or XML svc.conf, not both. -# endif -// Change the ACE_HAS_XML_SVC_CONF to ACE_HAS_CLASSIC_SVC_CONF when -// we switch ACE to use XML svc.conf as default format. -# if defined (ACE_HAS_XML_SVC_CONF) -# define ACE_USES_CLASSIC_SVC_CONF 0 -# else -# define ACE_USES_CLASSIC_SVC_CONF 1 -# endif /* ACE_HAS_XML_SVC_CONF */ -#endif /* ACE_USES_CLASSIC_SVC_CONF */ - -// ============================================================================ -// Default svc.conf file extension. -// ============================================================================ -#if defined (ACE_USES_CLASSIC_SVC_CONF) && (ACE_USES_CLASSIC_SVC_CONF == 1) -# define ACE_DEFAULT_SVC_CONF_EXT ".conf" -#else -# define ACE_DEFAULT_SVC_CONF_EXT ".conf.xml" -#endif /* ACE_USES_CLASSIC_SVC_CONF && ACE_USES_CLASSIC_SVC_CONF == 1 */ - -// ============================================================================ -// Miscellaneous macros -// ============================================================================ - -#if defined (ACE_USES_EXPLICIT_STD_NAMESPACE) -# define ACE_STD_NAMESPACE std -#else -# define ACE_STD_NAMESPACE -#endif - -#if !defined (ACE_OS_String) -# define ACE_OS_String ACE_OS -#endif /* ACE_OS_String */ -#if !defined (ACE_OS_Memory) -# define ACE_OS_Memory ACE_OS -#endif /* ACE_OS_Memory */ -#if !defined (ACE_OS_Dirent) -# define ACE_OS_Dirent ACE_OS -#endif /* ACE_OS_Dirent */ -#if !defined (ACE_OS_TLI) -# define ACE_OS_TLI ACE_OS -#endif /* ACE_OS_TLI */ - -// ------------------------------------------------------------------- -// Preprocessor symbols will not be expanded if they are -// concatenated. Force the preprocessor to expand them during the -// argument prescan by calling a macro that itself calls another that -// performs the actual concatenation. -#define ACE_PREPROC_CONCATENATE_IMPL(A,B) A ## B -#define ACE_PREPROC_CONCATENATE(A,B) ACE_PREPROC_CONCATENATE_IMPL(A,B) -// ------------------------------------------------------------------- - -/// If MPC is using a lib modifier this define will be set and this then -/// is used by the service configurator framework -#if defined MPC_LIB_MODIFIER && !defined (ACE_LD_DECORATOR_STR) -#define ACE_LD_DECORATOR_STR ACE_TEXT( MPC_LIB_MODIFIER ) -#endif /* MPC_LIB_MODIFIER */ - -#ifndef ACE_GCC_CONSTRUCTOR_ATTRIBUTE -# define ACE_GCC_CONSTRUCTOR_ATTRIBUTE -#endif - -#ifndef ACE_GCC_DESTRUCTOR_ATTRIBUTE -# define ACE_GCC_DESTRUCTOR_ATTRIBUTE -#endif - -#ifndef ACE_DEPRECATED -# define ACE_DEPRECATED -#endif - -#endif /* ACE_CONFIG_MACROS_H */ diff --git a/externals/ace/config-minimal.h b/externals/ace/config-minimal.h deleted file mode 100644 index 4cf2e8a487b..00000000000 --- a/externals/ace/config-minimal.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-minimal.h 80826 2008-03-04 14:51:23Z wotte $ - -// This configuration file is designed to build only the minimal -// ACE_OS adaptation layer. - -#ifndef ACE_CONFIG_MINIMAL_H -#define ACE_CONFIG_MINIMAL_H -#include /**/ "ace/pre.h" - -#define ACE_HAS_MINIMAL_ACE_OS - -// Only instantiate the ACE_OS_Object_Manager. -#define ACE_MAIN_OBJECT_MANAGER \ - ACE_OS_Object_Manager ace_os_object_manager; - -#if !defined(ACE_USE_THREAD_MANAGER_ADAPTER) - // To prevent use of ACE_Thread_Exit functions in - // ACE_Thread_Adapter::invoke (). -# define ACE_USE_THREAD_MANAGER_ADAPTER -#endif /* ! ACE_USE_THREAD_MANAGER_ADAPTER */ - -#if defined (ACE_ASSERT) -# undef ACE_ASSERT -#endif /* ACE_ASSERT */ -#define ACE_ASSERT(x) - -#if defined (ACE_DEBUG) -# undef ACE_DEBUG -#endif /* ACE_DEBUG */ -#define ACE_DEBUG(x) - -#if defined (ACE_ERROR) -# undef ACE_ERROR -#endif /* ACE_ERROR */ -#define ACE_ERROR(x) - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_MINIMAL_H */ diff --git a/externals/ace/config-mvs.h b/externals/ace/config-mvs.h deleted file mode 100644 index 3f438a776ba..00000000000 --- a/externals/ace/config-mvs.h +++ /dev/null @@ -1,127 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-mvs.h 88495 2010-01-12 19:23:11Z olli $ - -// Config file for MVS with OpenEdition - -#ifndef ACE_CONFIG_H -#define ACE_CONFIG_H -#include /**/ "ace/pre.h" - -// The following #defines are hacks to get around things -// that seem to be missing or different in MVS land -#define MAXPATHLEN 1024 /* sys/param.h not on MVS */ -#define NSIG 44 /* missing from Signal.h */ -#define MAXHOSTNAMELEN 256 /* missing form netdb.h */ -#define howmany __howmany /* MVS uses different names than most others */ -#define MAXNAMLEN __DIR_NAME_MAX -#if defined (log) /* log is a macro in math.h */ -# undef log /* conflicts with log function in ACE */ -#endif /* log */ - -#define ACE_MVS - -// Preprocesor requires an extra argument -#ifndef ACE_USING_MCPP_PREPROCESSOR -# define ACE_CC_PREPROCESSOR_ARGS "-+ -E" -#endif - -// See the README file in this directory -// for a description of the following ACE_ macros - -#if __COMPILER_VER__ >= 0x21020000 /* OS/390 r2 or higher */ -# define ACE_HAS_4_4BSD_SENDMSG_RECVMSG -# define ACE_HAS_UCONTEXT_T -#else /* __COMPILER_VER__ < 0x21020000 */ -# define ACE_LACKS_UCONTEXT_H -#endif /* __COMPILER_VER__ < 0x21020000 */ - -#if __COMPILER_VER__ < 0x22060000 /* before OS/390 r2.6 */ -# define ACE_LACKS_LONGLONG_T -#endif /* __COMPILER_VER__ < 0x22060000 */ - -#define ERRMAX __sys_nerr - -#define ACE_HAS_3_PARAM_WCSTOK -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES -#define ACE_HAS_CPLUSPLUS_HEADERS -#define ACE_HAS_DIRENT -#define ACE_HAS_GETPAGESIZE -#define ACE_HAS_GETRUSAGE -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT -#define ACE_HAS_LIMITED_RUSAGE_T -#define ACE_HAS_MSG -#define ACE_HAS_NONCONST_SELECT_TIMEVAL -#define ACE_HAS_NONSCALAR_THREAD_KEY_T -#define ACE_HAS_POLL -#define ACE_HAS_POSIX_NONBLOCK -#define ACE_HAS_POSIX_TIME -#define ACE_HAS_PTHREADS -#define ACE_HAS_PTHREAD_CONDATTR_SETKIND_NP -#define ACE_HAS_PTHREAD_MUTEXATTR_SETKIND_NP -#define ACE_HAS_SIGINFO_T -#define ACE_HAS_SIGWAIT -#define ACE_HAS_SIG_ATOMIC_T -#define ACE_HAS_SIG_C_FUNC -#define ACE_HAS_SOCKADDR_IN_SIN_LEN -#define ACE_HAS_SIZET_SOCKET_LEN -#define ACE_HAS_SSIZE_T -#define ACE_HAS_STRBUF_T -#define ACE_HAS_STRINGS -#define ACE_HAS_SYSV_IPC -#define ACE_HAS_TEMPLATE_TYPEDEFS -#define ACE_HAS_THREADS -#define ACE_HAS_THREAD_SPECIFIC_STORAGE -#define ACE_HAS_THR_C_DEST -#define ACE_HAS_THR_C_FUNC -#define ACE_HAS_TIMEZONE_GETTIMEOFDAY -#define ACE_HAS_UALARM -#define ACE_HAS_UTIME -#define ACE_HAS_VOIDPTR_MMAP -#define ACE_HAS_VOIDPTR_SOCKOPT -#define ACE_HAS_XPG4_MULTIBYTE_CHAR - -#define ACE_LACKS_CONDATTR_PSHARED -#define ACE_LACKS_INET_ATON -#define ACE_LACKS_MUTEXATTR_PSHARED -#define ACE_LACKS_IOSTREAM_FX -#define ACE_LACKS_LINEBUFFERED_STREAMBUF -#define ACE_LACKS_MADVISE -#define ACE_LACKS_MALLOC_H -#define ACE_LACKS_PARAM_H -#define ACE_LACKS_SYS_PARAM_H -#define ACE_LACKS_PLACEMENT_OPERATOR_DELETE -#define ACE_LACKS_PTHREAD_THR_SIGSETMASK -#define ACE_LACKS_READDIR_R -#define ACE_LACKS_RWLOCK_T -#define ACE_LACKS_SCHED_H -#define ACE_LACKS_SETSCHED -#define ACE_LACKS_SEMAPHORE_H -#define ACE_LACKS_SIGINFO_H -#define ACE_LACKS_STDINT_H -#define ACE_LACKS_SYS_SELECT_H -#define ACE_LACKS_SYS_SYSCTL_H -#define ACE_LACKS_SYSTIME_H -#define ACE_LACKS_NETINET_TCP_H -#define ACE_LACKS_TCP_H -#define ACE_LACKS_THREAD_PROCESS_SCOPING -#define ACE_LACKS_PTHREAD_ATTR_SETSTACKADDR -#define ACE_LACKS_TIMESPEC_T -#define ACE_LACKS_FD_MASK - -#if !defined (ACE_MT_SAFE) -# define ACE_MT_SAFE 1 -#endif - -#define ACE_NEEDS_DEV_IO_CONVERSION - -#define ACE_SIZEOF_FLOAT 4 -#define ACE_SIZEOF_DOUBLE 8 -#define ACE_SIZEOF_LONG_DOUBLE 16 -#define ACE_HAS_EBCDIC - -#define ACE_TEMPLATES_REQUIRE_SOURCE - -#define IN_CLASSD(a) ((((in_addr_t)(a)) & 0xf0000000) == 0xe0000000) -#define IN_MULTICAST(a) IN_CLASSD(a) -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_H */ diff --git a/externals/ace/config-netbsd.h b/externals/ace/config-netbsd.h deleted file mode 100644 index 07b26c9cc1c..00000000000 --- a/externals/ace/config-netbsd.h +++ /dev/null @@ -1,165 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-netbsd.h 89494 2010-03-15 20:11:18Z olli $ - -#ifndef ACE_CONFIG_H -#define ACE_CONFIG_H - -#ifndef ACE_MT_SAFE -#define ACE_MT_SAFE 1 -#endif - -#if defined (__GNUG__) -# include "ace/config-g++-common.h" -#endif /* __GNUG__ */ - -#if defined(ACE_MT_SAFE) && (ACE_MT_SAFE != 0) -# define ACE_HAS_THREADS 1 -# define ACE_HAS_PTHREADS 1 -# define ACE_HAS_PTHREADS_UNIX98_EXT 1 -# define ACE_HAS_PTHREAD_RESUME_NP 1 -# define ACE_HAS_PTHREAD_SUSPEND_NP 1 -# define ACE_LACKS_PTHREAD_THR_SIGSETMASK 1 -# define ACE_LACKS_PTHREAD_YIELD 1 -#endif /* ACE_MT_SAFE */ - -#define ACE_HAS_CLOCK_SETTIME 1 -#define ACE_HAS_CLOCK_GETTIME 1 -#define ACE_HAS_SETTIMEOFDAY 1 -#define ACE_HAS_GETTIMEOFDAY 1 -#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R 1 -#define ACE_HAS_3_PARAM_WCSTOK 1 -#define ACE_HAS_3_PARAM_READDIR_R 1 -#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG 1 -#define ACE_HAS_ALT_CUSERID 1 -#define ACE_HAS_AUTOMATIC_INIT_FINI 1 -#define ACE_HAS_CLOCK_GETTIME 1 -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES 1 -#define ACE_HAS_DIRENT 1 -#define ACE_HAS_EXCEPTIONS 1 -#define ACE_HAS_GETIFADDRS 1 -#define ACE_HAS_GETPAGESIZE 1 -#define ACE_HAS_GETPROGNAME 1 -#define ACE_HAS_GETRUSAGE 1 -#define ACE_HAS_GETRUSAGE_PROTOTYPE 1 -#define ACE_HAS_GPERF 1 -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT 1 -#define ACE_HAS_IP_MULTICAST 1 -#define ACE_HAS_MSG 1 -#define ACE_HAS_NEW_NO_H 1 -#define ACE_HAS_NONCONST_SELECT_TIMEVAL 1 -#define ACE_HAS_ONLY_SCHED_OTHER 1 -#define ACE_HAS_POLL 1 -#define ACE_HAS_POSITION_INDEPENDENT_POINTERS 1 -#define ACE_HAS_POSIX_NONBLOCK 1 -#define ACE_HAS_POSIX_TIME 1 -#define ACE_HAS_P_READ_WRITE 1 -#define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS 1 -#define ACE_HAS_REENTRANT_FUNCTIONS 1 -#define ACE_HAS_SCANDIR 1 -#define ACE_HAS_SETPROGNAME 1 -#define ACE_HAS_SIGACTION_CONSTP2 1 -#define ACE_HAS_SIGINFO_T 1 -#define ACE_HAS_SIGSUSPEND 1 -#define ACE_HAS_SIGTIMEDWAIT 1 -#define ACE_HAS_SIGWAIT 1 -#define ACE_HAS_SIG_ATOMIC_T 1 -#define ACE_HAS_SIG_C_FUNC 1 -#define ACE_HAS_SOCKADDR_IN_SIN_LEN 1 -#define ACE_HAS_SOCKADDR_IN6_SIN6_LEN 1 -#define ACE_HAS_SOCKADDR_MSG_NAME 1 -#define ACE_HAS_SOCKLEN_T 1 -#define ACE_HAS_SSIZE_T 1 -#define ACE_HAS_STANDARD_CPP_LIBRARY 1 -#define ACE_HAS_STDEXCEPT_NO_H 1 -#define ACE_HAS_STRINGS 1 -#define ACE_HAS_STRING_CLASS 1 -#define ACE_HAS_SVR4_DYNAMIC_LINKING 1 -#define ACE_HAS_SYSV_IPC 1 -#define ACE_HAS_SYS_FILIO_H 1 -#define ACE_HAS_STRSIGNAL -#define ACE_HAS_SYS_SOCKIO_H 1 -#define ACE_HAS_SYS_SYSCALL_H 1 -#define ACE_HAS_SYSCTL -#define ACE_HAS_TERMIOS 1 -#define ACE_HAS_THREAD_SPECIFIC_STORAGE 1 -#define ACE_HAS_TIMEZONE 1 -#define ACE_HAS_TIMEZONE_GETTIMEOFDAY 1 -#define ACE_HAS_UALARM 1 -#define ACE_HAS_UCONTEXT_T 1 -#define ACE_HAS_VOIDPTR_MMAP 1 -#define ACE_HAS_VOIDPTR_SOCKOPT 1 -#define ACE_HAS_WCHAR 1 -#define ACE_HAS_XPG4_MULTIBYTE_CHAR 1 -#define ACE_IOCTL_TYPE_ARG2 u_long -#define ACE_LACKS_CONDATTR_PSHARED 1 -#define ACE_LACKS_GETHOSTENT 1 -#define ACE_LACKS_GETIPNODEBYADDR 1 -#define ACE_LACKS_GETIPNODEBYNAME 1 -#define ACE_LACKS_IOSTREAM_FX 1 -#define ACE_LACKS_ITOW 1 -#define ACE_LACKS_LINEBUFFERED_STREAMBUF 1 -#define ACE_LACKS_LOG2 1 -#define ACE_LACKS_MSG_ACCRIGHTS 1 -#define ACE_LACKS_MUTEXATTR_PSHARED 1 -#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS 1 -#define ACE_LACKS_PERFECT_MULTICAST_FILTERING 1 -#define ACE_LACKS_PRI_T 1 -#define ACE_LACKS_PTHREAD_THR_SIGSETMASK 1 -#define ACE_LACKS_PTHREAD_YIELD 1 -#define ACE_LACKS_PWD_REENTRANT_FUNCTIONS 1 -#define ACE_LACKS_RWLOCKATTR_PSHARED 1 -#define ACE_LACKS_RWLOCK_T 1 -#define ACE_LACKS_SETSCHED 1 -#define ACE_LACKS_SIGINFO_H 1 -#define ACE_LACKS_STROPTS_H 1 -#define ACE_LACKS_STRRECVFD 1 -#define ACE_LACKS_TIMEDWAIT_PROTOTYPES 1 -#define ACE_LACKS_TIMESPEC_T 1 -#define ACE_LACKS_UNBUFFERED_STREAMBUF 1 -#define ACE_LACKS_WCSDUP 1 -#define ACE_LACKS_WCSICMP 1 -#define ACE_LACKS_WCSNICMP 1 -#define ACE_SCANDIR_CMP_USES_CONST_VOIDPTR 1 -#define ACE_LACKS_ISCTYPE - -#if defined(__x86_64__) -#define ACE_SIZEOF_DOUBLE 8 -#define ACE_SIZEOF_FLOAT 4 -#define ACE_SIZEOF_INT 4 -#define ACE_SIZEOF_LONG 8 -#define ACE_SIZEOF_LONG_DOUBLE 16 -#define ACE_SIZEOF_LONG_LONG 8 -#define ACE_SIZEOF_SHORT 2 -#define ACE_SIZEOF_VOID_P 8 -#define ACE_SIZEOF_WCHAR 4 - -typedef unsigned long ACE_UINT64; -typedef signed long ACE_INT64; - -#define ACE_SSIZE_T_FORMAT_SPECIFIER_ASCII "%ld" -#define ACE_SIZE_T_FORMAT_SPECIFIER_ASCII "%lu" - -#elif defined(__i386__) - -#define ACE_SIZEOF_DOUBLE 8 -#define ACE_SIZEOF_FLOAT 4 -#define ACE_SIZEOF_INT 4 -#define ACE_SIZEOF_LONG 4 -#define ACE_SIZEOF_LONG_DOUBLE 12 -#define ACE_SIZEOF_LONG_LONG 8 -#define ACE_SIZEOF_SHORT 2 -#define ACE_SIZEOF_VOID_P 4 -#define ACE_SIZEOF_WCHAR 4 - -typedef unsigned long long ACE_UINT64; -typedef signed long long ACE_INT64; - -#else -# error unknown CPU architecture -#endif - -#endif /* ACE_CONFIG_H */ - -// Local Variables: -// mode:C++ -// End: diff --git a/externals/ace/config-openbsd.h b/externals/ace/config-openbsd.h deleted file mode 100644 index aab03106aab..00000000000 --- a/externals/ace/config-openbsd.h +++ /dev/null @@ -1,208 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-openbsd.h 89494 2010-03-15 20:11:18Z olli $ - -// The following configuration file is designed to work for OpenBSD -// platforms using GNU g++. - -#ifndef ACE_CONFIG_H -# define ACE_CONFIG_H -#include /**/ "ace/pre.h" - -// Platform specific directives -// gcc defines __OpenBSD__ automatically for us. -#include - -#if defined (ACE_HAS_THREADS) -# include /**/ -#endif /* ACE_HAS_THREADS */ - -#include "ace/config-posix.h" - -#if !defined (__ACE_INLINE__) -# define __ACE_INLINE__ -#endif /* !__ACE_INLINE__ */ - -#if defined (__GNUG__) -# include "ace/config-g++-common.h" -#endif /* __GNUG__ */ - - -#if defined (ACE_HAS_THREADS) - -# if !defined (_THREAD_SAFE) -# define _THREAD_SAFE -# endif /* _THREAD_SAFE */ - -// And they're even POSIX pthreads -# if !defined (ACE_MT_SAFE) -# define ACE_MT_SAFE 1 -# endif /* ! ACE_MT_SAFE */ - - -// Check if pthreads and native exceptions are being used together. -// This causes SEGVs to tbe thrown somewhat randomly for some -// reason. According to newsgroup postings, it appears to be an -// OpenBSD or gcc bug. -# if defined (ACE_USES_NATIVE_EXCEPTIONS) -# error "OpenBSD pthreads and native exceptions currently do not work. See OpenBSD bug #1750" -# endif /* ACE_USES_NATIVE_EXCEPTIONS */ - -#else -// OpenBSD really has readdir_r () in single threaded mode, -// but the #ifdefs in OS.i select one with the wrong parameter -// sets if the ACE_HAS_POSIX_STD isn't defined (which is defined -// when ACE_HAS_THREADS is defined.) -# define ACE_LACKS_READDIR_R - -#endif /* ACE_HAS_THREADS */ - - -#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R -#define ACE_HAS_3_PARAM_READDIR_R -#define ACE_HAS_3_PARAM_WCSTOK -#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG -#define ACE_HAS_ALLOCA -#define ACE_HAS_ALT_CUSERID -#define ACE_HAS_AUTOMATIC_INIT_FINI -#define ACE_HAS_CHARPTR_DL -#define ACE_HAS_CLOCK_GETTIME -#define ACE_HAS_CLOCK_SETTIME -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES -#define ACE_HAS_DIRENT -#define ACE_HAS_GETIFADDRS -#define ACE_HAS_GETPAGESIZE -#define ACE_HAS_GETRUSAGE -#define ACE_HAS_GPERF -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT -#define ACE_HAS_ICMP_SUPPORT 1 -#define ACE_HAS_IPV6 -#define ACE_HAS_IP_MULTICAST -#define ACE_HAS_MEMCHR -#define ACE_HAS_MKDIR -#define ACE_HAS_MSG -#define ACE_HAS_NANOSLEEP -#define ACE_HAS_NEW_NO_H -#define ACE_HAS_NONCONST_MSGSND -#define ACE_HAS_NONCONST_SELECT_TIMEVAL -#define ACE_HAS_NONCONST_SWAB -#define ACE_HAS_POLL -#define ACE_HAS_POSITION_INDEPENDENT_POINTERS 1 -#define ACE_HAS_POSIX_GETPWNAM_R -#define ACE_HAS_POSIX_NONBLOCK -#define ACE_HAS_POSIX_TIME -#define ACE_HAS_PTHREADS_STD -#define ACE_HAS_PTHREADS_UNIX98_EXT -#define ACE_HAS_PTHREAD_ATTR_SETCREATESUSPEND_NP -#define ACE_HAS_PTHREAD_GETCONCURRENCY -#define ACE_HAS_PTHREAD_MUTEXATTR_SETKIND_NP -#define ACE_HAS_PTHREAD_NP_H -#define ACE_HAS_PTHREAD_RESUME_NP -#define ACE_HAS_PTHREAD_SETCONCURRENCY -#define ACE_HAS_PTHREAD_SIGMASK_PROTOTYPE -#define ACE_HAS_PTHREAD_SUSPEND_NP -#define ACE_HAS_P_READ_WRITE -#define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS -#define ACE_HAS_REENTRANT_FUNCTIONS -#define ACE_HAS_RTLD_LAZY_V -#define ACE_HAS_SCANDIR -#define ACE_HAS_SEMUN -#define ACE_HAS_SIGACTION_CONSTP2 -#define ACE_HAS_SIGINFO_T -#define ACE_HAS_SIGSUSPEND -#define ACE_HAS_SIGWAIT -#define ACE_HAS_SIG_ATOMIC_T -#define ACE_HAS_SIG_C_FUNC -#define ACE_HAS_SOCKADDR_IN6_SIN6_LEN -#define ACE_HAS_SOCKADDR_IN_SIN_LEN -#define ACE_HAS_SOCKADDR_MSG_NAME -#define ACE_HAS_SOCKLEN_T -#define ACE_HAS_SSIZE_T -#define ACE_HAS_STRINGS -#define ACE_HAS_STRING_CLASS -#define ACE_HAS_SVR4_DYNAMIC_LINKING -#define ACE_HAS_SVR4_SIGNAL_T -#define ACE_HAS_SYSCTL -#define ACE_HAS_SYSV_IPC -#define ACE_HAS_SYS_FILIO_H -#define ACE_HAS_STRSIGNAL -#define ACE_HAS_SYS_SOCKIO_H -#define ACE_HAS_SYS_SYSCALL_H -#define ACE_HAS_TERMIOS -#define ACE_HAS_THREAD_SPECIFIC_STORAGE -#define ACE_HAS_TIMEZONE_GETTIMEOFDAY -#define ACE_HAS_UALARM -#define ACE_HAS_VASPRINTF -#define ACE_HAS_VOIDPTR_MMAP -#define ACE_HAS_VOIDPTR_SOCKOPT -#define ACE_HAS_VOID_UNSETENV -#define ACE_HAS_WCHAR -#define ACE_HAS_XPG4_MULTIBYTE_CHAR - -#define ACE_LACKS_CONDATTR_PSHARED -#define ACE_LACKS_GETIPNODEBYADDR -#define ACE_LACKS_GETIPNODEBYNAME -#define ACE_LACKS_GETPGID -#define ACE_LACKS_IOSTREAM_FX -#define ACE_LACKS_ISCTYPE -#define ACE_LACKS_ITOW -#define ACE_LACKS_LINEBUFFERED_STREAMBUF -#define ACE_LACKS_LOG2 -#define ACE_LACKS_MALLOC_H -#define ACE_LACKS_MSG_ACCRIGHTS -#define ACE_LACKS_MUTEXATTR_PSHARED -#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS -#define ACE_LACKS_PERFECT_MULTICAST_FILTERING -#define ACE_LACKS_PRI_T -#define ACE_LACKS_PTHREAD_THR_SIGSETMASK -#define ACE_LACKS_PWD_REENTRANT_FUNCTIONS -#define ACE_LACKS_RAND_REENTRANT_FUNCTIONS -#define ACE_LACKS_RLIMIT_PROTOTYPE -#define ACE_LACKS_RWLOCK_T -#define ACE_LACKS_SETPGID -#define ACE_LACKS_SETREGID -#define ACE_LACKS_SETREUID -#define ACE_LACKS_SETSCHED -#define ACE_LACKS_SIGINFO_H -#define ACE_LACKS_STDINT_H -#define ACE_LACKS_STROPTS_H -#define ACE_LACKS_STRRECVFD -#define ACE_LACKS_TERMIO_H -#define ACE_LACKS_THREAD_PROCESS_SCOPING -#define ACE_LACKS_TIMEDWAIT_PROTOTYPES -#define ACE_LACKS_TIMESPEC_T -#define ACE_LACKS_UCONTEXT_H -#define ACE_LACKS_UNBUFFERED_STREAMBUF -#define ACE_LACKS_U_LONGLONG_T -#define ACE_LACKS_WCHAR_H -#define ACE_LACKS_WCSCASECMP -#define ACE_LACKS_WCSDUP -#define ACE_LACKS_WCSNCASECMP -#define ACE_LACKS_WCSNICMP - -#define ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS -#define ACE_PAGE_SIZE 4096 -#define ACE_SCANDIR_CMP_USES_CONST_VOIDPTR -#define ACE_SCANDIR_SEL_LACKS_CONST - -// OpenBSD 3.6 -#if (OpenBSD < 200411) -# define ACE_USES_ASM_SYMBOL_IN_DLSYM -#endif - -// ucontext_t is in OpenBSD 3.5 and later. -#if (OpenBSD >= 200405) -# define ACE_HAS_UCONTEXT_T -#endif /* OpenBSD >= 200405 */ - -// Lacks perfect filtering, must bind group address. -#if !defined ACE_LACKS_PERFECT_MULTICAST_FILTERING -# define ACE_LACKS_PERFECT_MULTICAST_FILTERING -#endif /* ACE_LACKS_PERFECT_MULTICAST_FILTERING */ - -// OpenBSD's dlsym call segfaults when passed an invalid handle. -// It seems as if most other OSs detect this and just report an error. -#define ACE_HAS_DLSYM_SEGFAULT_ON_INVALID_HANDLE - -#include /**/ "ace/post.h" - -#endif /* ACE_CONFIG_H */ diff --git a/externals/ace/config-openvms.h b/externals/ace/config-openvms.h deleted file mode 100644 index ac57aad9707..00000000000 --- a/externals/ace/config-openvms.h +++ /dev/null @@ -1,198 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-openvms.h 87167 2009-10-19 19:33:53Z olli $ - -// The following configuration file is designed to work for OpenVMS 7.3-2 - -#ifndef ACE_CONFIG_H -#define ACE_CONFIG_H - -#if !defined (ACE_USE_RCSID) -# define ACE_USE_RCSID 0 -#endif - -#ifdef __cplusplus -#pragma message disable CODCAUUNR -#pragma message disable CODEUNREACHABLE -//#pragma message disable DOLLARID -//#pragma message disable NOSIMPINT -//#pragma message disable NOSTDLONGLONG -#pragma message disable NARROWPTR -//#pragma message disable LONGEXTERN -#pragma message disable UNSCOMZER -#endif - -// Use a signed int to match POSIX -#define __SIGNED_INT_TIME_T - -#define ACE_OPENVMS __VMS_VER - -#define ACE_DLL_SUFFIX ACE_TEXT("") - -#define ACE_HAS_DUMP 1 - -// need this includes to ensure proper sequence of definitions so that -// f.i. HP C/C++ does not '#define ' memcpy, memmove etc. -#include -#include -#include -#undef memset -#undef memcpy -#undef memmove - -#if defined(__ia64__) - // on OpenVMS IA64 we need this get the singleton exported since we build - // ACE/TAO with the NOTEMPLATES export option which prohibits exporting - // of any template symbols unless explicitly exported - #define ACE_HAS_CUSTOM_EXPORT_MACROS - #define ACE_Proper_Export_Flag - #define ACE_Proper_Import_Flag - #define ACE_EXPORT_SINGLETON_DECLARATION(T) template class __declspec (dllexport) T - #define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) template class __declspec (dllexport) SINGLETON_TYPE; -#else - #define ACE_HAS_EXPLICIT_STATIC_TEMPLATE_MEMBER_INSTANTIATION -#endif - -#define ACE_DEFAULT_BASE_ADDR ((char*)(0x30000000)) - -#define ACE_MAX_UDP_PACKET_SIZE 65535 - -#define ACE_HAS_STDCPP_STL_INCLUDES 1 - -/* missing system headers */ -#define ACE_LACKS_STDINT_H 1 -#define ACE_LACKS_SYS_IPC_H 1 -#define ACE_LACKS_SYS_SEM_H 1 -#define ACE_LACKS_SEMAPHORE_H 1 -#define ACE_LACKS_SYS_SELECT_H 1 -#define ACE_LACKS_TERMIOS_H 1 -#define ACE_LACKS_SYS_SHM_H 1 -#define ACE_LACKS_SYS_MSG_H 1 -#define ACE_LACKS_REGEX_H 1 -#define ACE_LACKS_SEARCH_H 1 -#define ACE_LACKS_SCHED_H 1 -#define ACE_LACKS_SYS_SYSCTL_H 1 -#define ACE_LACKS_MALLOC_H 1 -#define ACE_LACKS_SYS_PARAM_H 1 -#define ACE_LACKS_SIGINFO_H 1 -#define ACE_LACKS_UCONTEXT_H 1 - -/* missing rtl functions */ -#define ACE_LACKS_SETPGID 1 -#define ACE_LACKS_SETREUID 1 -#define ACE_LACKS_SETREGID 1 -#define ACE_LACKS_FORK 1 -#define ACE_LACKS_GETPGID 1 -#define ACE_LACKS_SETSID 1 -#define ACE_LACKS_FCNTL 1 -#define ACE_LACKS_SETEGID 1 -#define ACE_LACKS_SETEUID 1 - -#define ACE_LACKS_REALPATH 1 - -#define ACE_LACKS_SYMLINKS 1 - -#define ACE_LACKS_PWD_REENTRANT_FUNCTIONS 1 -#define ACE_LACKS_RAND_REENTRANT_FUNCTIONS 1 - -#define ACE_HAS_P_READ_WRITE -#define ACE_HAS_CHARPTR_DL 1 -#define ACE_HAS_CLOCK_GETTIME 1 -#define ACE_HAS_CLOCK_SETTIME 1 -#define ACE_HAS_VOIDPTR_GETTIMEOFDAY 1 -#define ACE_HAS_DIRENT 1 -#define ACE_HAS_GETPAGESIZE 1 -#define ACE_HAS_MSG -#define ACE_HAS_NONCONST_SELECT_TIMEVAL 1 -#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R 1 -#define ACE_HAS_3_PARAM_WCSTOK 1 -#define ACE_HAS_SIGSUSPEND 1 -#define ACE_HAS_SIGWAIT 1 -#define ACE_HAS_SIGTIMEDWAIT 1 - -#define ACE_HAS_SIG_C_FUNC 1 -#define ACE_HAS_SIGISMEMBER_BUG -#define ACE_HAS_STRNLEN 1 -#define ACE_HAS_STREAMS 1 -#define ACE_HAS_UALARM 1 -#define ACE_HAS_VOIDPTR_MMAP 1 -#define ACE_HAS_VOIDPTR_SOCKOPT 1 -#define ACE_LACKS_LSTAT 1 -#define ACE_LACKS_MADVISE 1 -#define ACE_LACKS_MKFIFO 1 -#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS 1 -#define ACE_LACKS_READLINK 1 -#define ACE_LACKS_RLIMIT 1 -#define ACE_LACKS_RLIMIT_PROTOTYPE 1 -#define ACE_LACKS_SETSCHED -#define ACE_LACKS_SYSCALL 1 -#define ACE_LACKS_WCSTOULL 1 -#define ACE_LACKS_WCSTOLL - -/* (missing) standard data types */ -#define ACE_LACKS_CONST_TIMESPEC_PTR 1 -#define ACE_LACKS_SUSECONDS_T 1 -#define ACE_HAS_IDTYPE_T 1 -#define ACE_HAS_SIGINFO_T 1 -#define ACE_HAS_XPG4_MULTIBYTE_CHAR 1 -#define ACE_HAS_SIZET_SOCKET_LEN 1 -#define ACE_HAS_SSIZE_T 1 -#define ACE_LACKS_PRI_T 1 -#define ACE_LACKS_SEMBUF_T 1 -#define ACE_LACKS_STRRECVFD 1 -#define ACE_LACKS_T_ERRNO 1 - -/* POSIX threads ompatibilities */ -#define ACE_LACKS_RWLOCK_T 1 -#define ACE_LACKS_PTHREAD_KILL 1 -#define ACE_LACKS_THREAD_PROCESS_SCOPING 1 - -#define ACE_HAS_PTHREADS 1 -#define ACE_HAS_PTHREAD_PROCESS_ENUM 1 -#define ACE_LACKS_UNNAMED_SEMAPHORE 1 -#define ACE_MT_SAFE 1 -#define ACE_HAS_THREADS 1 -#define ACE_HAS_THREAD_SPECIFIC_STORAGE 1 -#define ACE_HAS_THR_C_DEST 1 -#define ACE_HAS_THR_C_FUNC 1 -#define ACE_LACKS_PTHREAD_SIGMASK 1 -#define ACE_LACKS_PTHREAD_THR_SIGSETMASK 1 -#define ACE_NEEDS_HUGE_THREAD_STACKSIZE (64U*1024) -#define ACE_HAS_PTHREAD_SETCONCURRENCY 1 -#define ACE_HAS_PTHREAD_GETCONCURRENCY 1 -#define ACE_HAS_PTHREAD_SCHEDPARAM 1 - -/* language/platform conformance */ -#define ACE_NEW_THROWS_EXCEPTIONS 1 -#define ACE_TEMPLATES_REQUIRE_SOURCE 1 -#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 -#define ACE_HAS_AUTOMATIC_INIT_FINI 1 -#define ACE_LACKS_UNIX_SIGNALS 1 - -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES 1 -#define ACE_HAS_CPLUSPLUS_HEADERS 1 -#define ACE_HAS_EXCEPTIONS 1 -#define ACE_LACKS_LINEBUFFERED_STREAMBUF 1 - -#define ACE_HAS_GPERF 1 -#define ACE_HAS_IP_MULTICAST 1 -#define ACE_LACKS_PERFECT_MULTICAST_FILTERING 1 -#define ACE_HAS_POSIX_NONBLOCK 1 -#define ACE_HAS_POSIX_TIME 1 -#define ACE_HAS_BROKEN_POSIX_TIME 1 -#define ACE_HAS_STANDARD_CPP_LIBRARY 1 -#define ACE_HAS_STRING_CLASS 1 -#define ACE_HAS_SVR4_DYNAMIC_LINKING 1 - -#define ACE_HAS_TEMPLATE_TYPEDEFS 1 -#define ACE_LACKS_NAMED_POSIX_SEM 1 -#define ACE_LACKS_SYSV_SHMEM 1 -#define ACE_LACKS_UNIX_DOMAIN_SOCKETS 1 -#define ACE_LACKS_UNIX_SYSLOG 1 -#define ACE_LACKS_ALPHASORT 1 -#define ACE_LACKS_ISCTYPE -#define ACE_LACKS_ISBLANK - -#define ACE_LACKS_SETENV -#define ACE_LACKS_UNSETENV - -#endif diff --git a/externals/ace/config-pharlap.h b/externals/ace/config-pharlap.h deleted file mode 100644 index dad0e91a913..00000000000 --- a/externals/ace/config-pharlap.h +++ /dev/null @@ -1,91 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-pharlap.h 84373 2009-02-10 18:21:50Z johnnyw $ - -// This configuration file is for use with the PharLap Realtime ETS Kernel. -// It has been tested with PharLap TNT Embedded ToolSuite version 9.1. - -#ifndef ACE_CONFIG_PHARLAP_H -#define ACE_CONFIG_PHARLAP_H -#include /**/ "ace/pre.h" - -#define ACE_HAS_PHARLAP -// Some features are only available with the Realtime edition of ETS. -// Assume that if using ACE, the realtime version is also being used, but -// allow it to be turned off as well. -#ifndef ACE_HAS_PHARLAP_RT -# define ACE_HAS_PHARLAP_RT -#else -# if (ACE_HAS_PHARLAP_RT == 0) -# undef ACE_HAS_PHARLAP_RT -# endif -#endif - -// Fortunately, PharLap ETS offers much of the Win32 API. But it's still on -// Winsock 1.1 -#define ACE_HAS_WINSOCK2 0 -#define ACE_HAS_WINSOCK1 1 - -// The TSS implementation doesn't pass muster on the TSS_Test, but it works -// well with ACE's TSS emulation. -#define ACE_HAS_TSS_EMULATION - -#define ACE_LACKS_MMAP -#define ACE_LACKS_MPROTECT -#define ACE_LACKS_MSYNC -#define ACE_LACKS_TCP_NODELAY -#define ACE_LACKS_MSG_WFMO -#define ACE_LACKS_WIN32_MOVEFILEEX -#define ACE_LACKS_WIN32_REGISTRY -#define ACE_LACKS_WIN32_SECURITY_DESCRIPTORS -#define ACE_LACKS_WIN32_SERVICES -#define ACE_LACKS_WIN32_SETFILEPOINTEREX - -// There's no host table, by default. So using "localhost" won't work. -// If your system does have the ability to use "localhost" and you want to, -// define it before including this file. -#if !defined (ACE_LOCALHOST) -# define ACE_LOCALHOST "127.0.0.1" -#endif /* ACE_LOCALHOST */ - -// The normal Windows default stack size doesn't hold for ETS. Set what you -// want explicitly. -#if !defined (ACE_DEFAULT_THREAD_STACKSIZE) -# define ACE_DEFAULT_THREAD_STACKSIZE (1024*1024) -#endif /* ACE_DEFAULT_THREAD_STACKSIZE */ - -// Don't know how to get the page size at execution time. This is most likely -// the correct value. -#define ACE_PAGE_SIZE 4096 - -#if defined (ACE_HAS_PHARLAP_RT) -# define ACE_HAS_IP_MULTICAST - // ETS winsock doesn't define IP level socket options -//# define IP_TOS 8 -#endif /* ACE_HAS_PHARLAP_RT */ - -// Let the config-win32.h file do its thing -#undef ACE_CONFIG_H -#include "ace/config-win32.h" -// Now remove things that desktop/server Windows has but Pharlap ETS doesn't. -#undef ACE_HAS_INTERLOCKED_EXCHANGEADD -#undef ACE_HAS_WCHAR - -// PharLap's exports apparantly define LockFile, but it's documented as -// unsupported. LockFileEx is not present. -#define ACE_LACKS_FILELOCKS - -#include /**/ -#if defined (ACE_HAS_PHARLAP_RT) -# include /**/ -#define ACE_LACKS_IP_ADD_MEMBERSHIP -#endif /* ACE_HAS_PHARLAP_RT */ - -// Although IN_CLASSD is defined in both winsock.h and winsock2.h, it ends -// up undefined for Pharlap ETS builds. If this is the case, set things up -// so nothing looks like class D. -#if !defined (IN_CLASSD) -# define IN_CLASSD(i) (0) -#endif - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_PHARLAP_H */ diff --git a/externals/ace/config-posix-nonetworking.h b/externals/ace/config-posix-nonetworking.h deleted file mode 100644 index 7edc31d0dab..00000000000 --- a/externals/ace/config-posix-nonetworking.h +++ /dev/null @@ -1,86 +0,0 @@ -/* -*- C -*- */ -// $Id: config-posix-nonetworking.h 80826 2008-03-04 14:51:23Z wotte $ - -/* The following configuration file is designed to work for RTEMS - platforms using GNU C. -*/ - -#ifndef ACE_CONFIG_POSIX_NONETWORKING_H -#define ACE_CONFIG_POSIX_NONETWORKING_H - -// Missing header files -# define ACE_LACKS_SYS_UIO_H -# define ACE_LACKS_SYS_SOCKET_H -# define ACE_LACKS_NETINET_IN_H -# define ACE_LACKS_NETDB_H -# define ACE_LACKS_ARPA_INET_H -# define ACE_LACKS_SYS_SELECT_H -# define ACE_LACKS_NET_IF_H -# define ACE_LACKS_SYSLOG_H -# define ACE_LACKS_SYS_UN_H -# define ACE_LACKS_MEMORY_H -# define ACE_LACKS_SYS_SYSCTL_H -# define ACE_LACKS_NETINET_TCP_H - -// Missing types -# define ACE_LACKS_IOVEC -# define ACE_LACKS_IN_ADDR -# define ACE_LACKS_SOCKADDR_IN -# define ACE_LACKS_SOCKADDR_UN -# define ACE_LACKS_HOSTENT -# define ACE_LACKS_SOCKADDR -# define ACE_LACKS_IP_MREQ -# define ACE_LACKS_PROTOENT -# define ACE_LACKS_SERVENT -# define ACE_LACKS_IFREQ -# define ACE_LACKS_IFCONF -# define ACE_LACKS_LINGER - -// Missing methods -# define ACE_LACKS_GETHOSTBYADDR -# define ACE_LACKS_GETHOSTBYNAME -# define ACE_LACKS_GETIPNODEBYADDR -# define ACE_LACKS_LISTEN -# define ACE_LACKS_BIND -# define ACE_LACKS_NTOHL -# define ACE_LACKS_HTONL -# define ACE_LACKS_HTONS -# define ACE_LACKS_NTOHS -# define ACE_LACKS_SELECT -# define ACE_LACKS_SOCKET -# define ACE_LACKS_SHUTDOWN -# define ACE_LACKS_SETSOCKOPT -# define ACE_LACKS_INET_ATON -# define ACE_LACKS_INET_ADDR -# define ACE_LACKS_INET_NTOA -# define ACE_LACKS_GET_BCAST_ADDR -# define ACE_LACKS_GETHOSTENT -# define ACE_LACKS_GETSERVBYNAME -# define ACE_LACKS_ACCEPT -# define ACE_LACKS_CONNECT -# define ACE_LACKS_GETPEERNAME -# define ACE_LACKS_GETSOCKNAME -# define ACE_LACKS_GETSOCKOPT -# define ACE_LACKS_RECV -# define ACE_LACKS_SEND -# define ACE_LACKS_SENDTO -# define ACE_LACKS_RECVFROM -# define ACE_LACKS_RECVMSG -# define ACE_LACKS_SENDMSG -# define ACE_LACKS_GETHOSTBYADDR_R -# define ACE_LACKS_GETPROTOBYNAME -# define ACE_LACKS_GETPROTOBYNUMBER -# define ACE_LACKS_GETSERVBYNAME -# define ACE_LACKS_READV -# define ACE_LACKS_WRITEV -# define ACE_LACKS_SOCKETPAIR -# undef ACE_HAS_MSG - -// Missing OS features -# define ACE_LACKS_UNIX_SYSLOG -# define ACE_LACKS_TCP_NODELAY - -// Missing ACE features -# define ACE_DISABLE_NOTIFY_PIPE_DEFAULT 1 - -#endif /* ACE_CONFIG_POSIX_NONETWORKING_H */ diff --git a/externals/ace/config-posix.h b/externals/ace/config-posix.h deleted file mode 100644 index 09b4e0671f3..00000000000 --- a/externals/ace/config-posix.h +++ /dev/null @@ -1,73 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-posix.h 82517 2008-08-05 19:36:26Z shuston $ - -#ifndef ACE_CONFIG_POSIX_H -#define ACE_CONFIG_POSIX_H - -#include - -/* The following POSIX constants are defined after is - * included. They are documented in: - * http://www.opengroup.org/onlinepubs/007904975/basedefs/unistd.h.html - */ -#if defined(_POSIX_REALTIME_SIGNALS) && (_POSIX_REALTIME_SIGNALS-0 != -1 ) -# if !defined(ACE_HAS_POSIX_REALTIME_SIGNALS) -# define ACE_HAS_POSIX_REALTIME_SIGNALS -# endif /* ACE_HAS_POSIX_REALTIME_SIGNALS */ -#endif /* _POSIX_REALTIME_SIGNALS */ - -#if defined(_POSIX_ASYNCHRONOUS_IO) && (_POSIX_ASYNCHRONOUS_IO-0 != -1 ) -# if !defined(ACE_HAS_AIO_CALLS) -# define ACE_HAS_AIO_CALLS -# endif /* ACE_HAS_AIO_CALLS */ -#endif /* _POSIX_ASYNCHRONOUS_IO */ - -#if !defined (ACE_MT_SAFE) || (ACE_MT_SAFE != 0) -# if defined(_POSIX_SEMAPHORES) && (_POSIX_SEMAPHORES-0 != -1 ) -# if !defined(ACE_HAS_POSIX_SEM) -# define ACE_HAS_POSIX_SEM -# endif /* ACE_HAS_POSIX_SEM */ -# if defined(ACE_HAS_POSIX_SEM) -# if !defined (ACE_HAS_POSIX_SEM_TIMEOUT) && \ - (defined (_POSIX_TIMEOUTS) && (_POSIX_TIMEOUTS-0 != -1)) -# define ACE_HAS_POSIX_SEM_TIMEOUT -# endif /* ACE_HAS_POSIX_SEM_TIMEOUT && _POSIX_TIMEOUTS */ -# endif /* ACE_HAS_POSIX_SEM */ -# endif /* ACE_HAS_POSIX_SEM */ -#endif /* !ACE_MT_SAFE */ - -#if defined(_POSIX_SHARED_MEMORY_OBJECTS) && (_POSIX_SHARED_MEMORY_OBJECTS-0 != -1 ) -# if !defined(ACE_HAS_SHM_OPEN) -# define ACE_HAS_SHM_OPEN -# endif /* ACE_HAS_SHM_OPEN */ -#endif /* _POSIX_SHARED_MEMORY_OBJECTS */ - -// Check if threading enabled/disable through platform_macros -#if !defined (ACE_MT_SAFE) || (ACE_MT_SAFE != 0) -// Allow the user to disable use of threads by setting ACE_HAS_THREADS to 0 -// before including this file. The platform config (not macros) file can -// often detect that the compiler was invoked with or without threads support -// and set this accordingly. -# if defined (ACE_HAS_THREADS) && (ACE_HAS_THREADS == 0) -# undef ACE_HAS_THREADS -# else -# if defined(_POSIX_THREADS) && (_POSIX_THREADS-0 != -1 ) -# if !defined(ACE_HAS_THREADS) -# define ACE_HAS_THREADS -# endif /* ACE_HAS_THREADS */ - -# if !defined(ACE_HAS_PTHREADS) -# define ACE_HAS_PTHREADS -# endif /* ACE_HAS_PTHREADS */ - -# endif /* _POSIX_THREADS */ -# endif /* ACE_HAS_THREADS */ -#endif /* !ACE_MT_SAFE */ - -#if defined(_POSIX_MESSAGE_PASSING) && (_POSIX_MESSAGE_PASSING-0 != -1 ) -# if !defined(ACE_HAS_POSIX_MESSAGE_PASSING) -# define ACE_HAS_POSIX_MESSAGE_PASSING -# endif /* ACE_HAS_POSIX_MESSAGE_PASSING */ -#endif /* _POSIX_MESSAGE_PASSING */ - -#endif /* ACE_CONFIG_POSIX_H */ diff --git a/externals/ace/config-qnx-neutrino.h b/externals/ace/config-qnx-neutrino.h deleted file mode 100644 index 86525567c38..00000000000 --- a/externals/ace/config-qnx-neutrino.h +++ /dev/null @@ -1,136 +0,0 @@ -// -*- C++ -*- -// $Id: config-qnx-neutrino.h 87167 2009-10-19 19:33:53Z olli $ -// The following configuration file is designed to work for Neutrino -// 2.0 (Beta) with GNU C++ and the POSIX (pthread) threads package. - -#ifndef ACE_CONFIG_H -#define ACE_CONFIG_H -#include /**/ "ace/pre.h" - -#define _POSIX_C_SOURCE 199506 -#define _QNX_SOURCE - -// These constants are in i386-nto/include/limits.h, but egcs -// picks up its own limits.h instead: -#define _POSIX_NAME_MAX 14 /* Max bytes in a filename */ -#define _POSIX_PATH_MAX 256 /* Num. bytes in pathname (excl. NULL) */ - -#if defined(__OPTIMIZE__) -# if defined(__X86__) - // string.h can't be used by ACE with __OPTIMIZE__. -# undef __OPTIMIZE__ -# include -# define __OPTIMIZE__ -# endif /* __X86__ */ -#endif /* __OPTIMIZE__ */ - -#include "ace/config-g++-common.h" - -// The following defines the Neutrino compiler. -// gcc should know to call g++ as necessary -#ifdef __GNUC__ -# define ACE_CC_NAME ACE_TEXT ("gcc") -#else -# define ACE_CC_NAME ACE_TEXT ("NTO compiler ??") -#endif - -// /usr/nto/include/float.h defines -// FLT_MAX_EXP 127 -// DBL_MAX_EXP 1023 -// ace expects 128 & 1024 respectively -// to set the following macros in ace/Basic_Types.h -// These macros are: -// #define ACE_SIZEOF_DOUBLE 8 -// #define ACE_SIZEOF_FLOAT 4 - -#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R -#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG -// Although ACE does have alloca() on this compiler/platform combination, it is -// disabled by default since it can be dangerous. Uncomment the following line -// if you ACE to use it. -//#define ACE_HAS_ALLOCA -#define ACE_HAS_ALLOCA_H -#define ACE_HAS_AUTOMATIC_INIT_FINI -#define ACE_HAS_CLOCK_GETTIME -#define ACE_HAS_CLOCK_SETTIME -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES -#define ACE_HAS_DIRENT -#define ACE_HAS_GETPAGESIZE -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT -#define ACE_HAS_NONSTATIC_OBJECT_MANAGER -#define ACE_HAS_INLINED_OSCALLS -#define ACE_HAS_IP_MULTICAST -#define ACE_HAS_MSG -#define ACE_HAS_MT_SAFE_MKTIME -#define ACE_HAS_MUTEX_TIMEOUTS -#define ACE_HAS_NONCONST_SELECT_TIMEVAL -#define ACE_HAS_NONCONST_SWAB -#define ACE_HAS_POSIX_SEM -#define ACE_HAS_POSIX_TIME -#define ACE_HAS_PTHREADS -#define ACE_HAS_P_READ_WRITE -#define ACE_HAS_REENTRANT_FUNCTIONS -#define ACE_HAS_SELECT_H -#define ACE_HAS_SIGINFO_T -#define ACE_HAS_SIGISMEMBER_BUG -#define ACE_HAS_SIGWAIT -#define ACE_HAS_SIG_ATOMIC_T -#define ACE_HAS_SOCKADDR_IN_SIN_LEN -#define ACE_HAS_SSIZE_T -#define ACE_HAS_STRINGS -#define ACE_HAS_SVR4_GETTIMEOFDAY -#define ACE_HAS_TERMIOS -#define ACE_HAS_THREADS -#define ACE_HAS_THREAD_SPECIFIC_STORAGE -#define ACE_HAS_THR_C_DEST -#define ACE_HAS_THR_C_FUNC -#define ACE_HAS_TIMEZONE_GETTIMEOFDAY -#define ACE_HAS_UALARM -#define ACE_HAS_UCONTEXT_T -#define ACE_HAS_VOIDPTR_MMAP -#define ACE_HAS_VOIDPTR_SOCKOPT -#define ACE_LACKS_CONDATTR_PSHARED -#define ACE_LACKS_CONST_TIMESPEC_PTR -#define ACE_LACKS_CUSERID -#define ACE_LACKS_FORK -#define ACE_LACKS_LINEBUFFERED_STREAMBUF -#define ACE_LACKS_MADVISE -#define ACE_LACKS_MUTEXATTR_PSHARED -#define ACE_LACKS_NAMED_POSIX_SEM -#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS -#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS -#define ACE_LACKS_POLL_H -#define ACE_LACKS_PTHREAD_THR_SIGSETMASK -#define ACE_LACKS_RWLOCK_T -#define ACE_LACKS_SBRK -#define ACE_LACKS_SEEKDIR -#define ACE_LACKS_SO_SNDBUF -#define ACE_LACKS_SO_RCVBUF -#define ACE_LACKS_SOCKETPAIR -#define ACE_LACKS_STROPTS_H -#define ACE_LACKS_STREAM_MODULES -#define ACE_LACKS_STRRECVFD -#define ACE_LACKS_SYSCALL -#define ACE_LACKS_SYS_MSG_H -#define ACE_LACKS_SYS_SHM_H -#define ACE_LACKS_SYSV_SHMEM -#define ACE_LACKS_TCP_NODELAY -#define ACE_LACKS_TELLDIR -#define ACE_LACKS_TIMESPEC_T -#define ACE_LACKS_TRUNCATE -#define ACE_LACKS_T_ERRNO -#define ACE_LACKS_UALARM_PROTOTYPE -#define ACE_LACKS_UCONTEXT_H -#define ACE_LACKS_UNIX_DOMAIN_SOCKETS -#define ACE_LACKS_U_LONGLONG_T -#define ACE_MT_SAFE 1 -#define ACE_NEEDS_FUNC_DEFINITIONS -#define ACE_NEEDS_HUGE_THREAD_STACKSIZE 65536 -#define ACE_TEMPLATES_REQUIRE_SOURCE -#define ACE_THR_PRI_FIFO_DEF 10 -#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 -#define ACE_HAS_SIGTIMEDWAIT -#define ACE_HAS_SIGSUSPEND - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_H */ diff --git a/externals/ace/config-qnx-rtp-62x.h b/externals/ace/config-qnx-rtp-62x.h deleted file mode 100644 index 7fa7514a1c8..00000000000 --- a/externals/ace/config-qnx-rtp-62x.h +++ /dev/null @@ -1,131 +0,0 @@ -// -*- C++ -*- -// $Id: config-qnx-rtp-62x.h 87167 2009-10-19 19:33:53Z olli $ -// The following configuration file is designed to work for QNX RTP 621 -// GNU C++ and the POSIX (pthread) threads package. You can get QNX -// RTP at http://get.qnx.com -#ifndef ACE_CONFIG_QNX_RTP_62x_H -#define ACE_CONFIG_QNX_RTP_62x_H -#include /**/ "ace/pre.h" -#include /**/ "ace/config-qnx-rtp-common.h" - -///////////////////////////////////////////////////////////////// -// Definition of the features that are available. -// -// ACE_HAS Section -///////////////////////////////////////////////////////////////// -#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R -#define ACE_HAS_3_PARAM_WCSTOK -#define ACE_HAS_3_PARAM_READDIR_R -#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG -// Although ACE does have alloca() on this compiler/platform combination, it is -// disabled by default since it can be dangerous. Uncomment the following line -// if you ACE to use it. -//#define ACE_HAS_ALLOCA -#define ACE_HAS_ALLOCA_H -#define ACE_HAS_ALT_CUSERID -#define ACE_HAS_AUTOMATIC_INIT_FINI -#define ACE_HAS_CLOCK_GETTIME -#define ACE_HAS_CLOCK_SETTIME -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES -#define ACE_HAS_DIRENT -#define ACE_HAS_GETPAGESIZE -#define ACE_HAS_GETIFADDRS -// Enable gperf, this is a hosted configuration. -#define ACE_HAS_GPERF -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT -//#define ACE_HAS_NONSTATIC_OBJECT_MANAGER -#define ACE_HAS_IP_MULTICAST -#define ACE_HAS_MSG -#define ACE_HAS_MT_SAFE_MKTIME -#define ACE_HAS_MUTEX_TIMEOUTS -#define ACE_HAS_NONCONST_SELECT_TIMEVAL -#define ACE_HAS_NONCONST_SWAB -#define ACE_HAS_POSIX_SEM -#define ACE_HAS_POSIX_TIME -#define ACE_HAS_PTHREADS -#define ACE_HAS_P_READ_WRITE -#define ACE_HAS_REENTRANT_FUNCTIONS -#define ACE_HAS_SELECT_H -#define ACE_HAS_SHM_OPEN -#define ACE_HAS_SIGINFO_T -#define ACE_HAS_SIGISMEMBER_BUG -#define ACE_HAS_SIGWAIT -#define ACE_HAS_SIG_ATOMIC_T -#define ACE_HAS_SOCKADDR_IN_SIN_LEN -#define ACE_HAS_SOCKLEN_T -#define ACE_HAS_SSIZE_T -#define ACE_HAS_STRINGS -#define ACE_HAS_SVR4_DYNAMIC_LINKING -#define ACE_HAS_SVR4_GETTIMEOFDAY -#define ACE_HAS_TERMIOS -#define ACE_HAS_THREADS -#define ACE_HAS_THREAD_SPECIFIC_STORAGE -#define ACE_HAS_THR_C_DEST -#define ACE_HAS_THR_C_FUNC -#define ACE_HAS_TIMEZONE_GETTIMEOFDAY -#define ACE_HAS_UALARM -#define ACE_HAS_UCONTEXT_T -#define ACE_HAS_VOIDPTR_MMAP -#define ACE_HAS_VOIDPTR_SOCKOPT - -///////////////////////////////////////////////////////////////// -// Definition of the features that are not available. -// -// ACE_LACKS Section -///////////////////////////////////////////////////////////////// -#define ACE_LACKS_CONST_TIMESPEC_PTR -#define ACE_LACKS_LINEBUFFERED_STREAMBUF -#define ACE_LACKS_MADVISE -// lacks mqueue mgr or speed-up named sem by shm emulation -#define ACE_LACKS_NAMED_POSIX_SEM -#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS -// Multicast_Tests reports for NTO 621 frames from unsubscribed groups -#define ACE_LACKS_PERFECT_MULTICAST_FILTERING 1 -#define ACE_LACKS_POLL_H -#define ACE_LACKS_PTHREAD_THR_SIGSETMASK -#define ACE_LACKS_RWLOCK_T -#define ACE_LACKS_SO_SNDBUF -#define ACE_LACKS_SO_RCVBUF -#define ACE_LACKS_STREAM_MODULES -#define ACE_LACKS_STROPTS_H -#define ACE_LACKS_STRPTIME -#define ACE_LACKS_STRRECVFD -#define ACE_LACKS_SYSCALL -#define ACE_LACKS_SYS_MSG_H -#define ACE_LACKS_SYSV_SHMEM -#define ACE_LACKS_SYS_SHM_H -#define ACE_LACKS_TIMESPEC_T -#define ACE_LACKS_T_ERRNO -#define ACE_LACKS_U_LONGLONG_T -#define ACE_LACKS_ALPHASORT -#define ACE_LACKS_FD_MASK -#define ACE_LACKS_NFDBITS -#define ACE_LACKS_ISCTYPE - -#define ACE_LACKS_RLIMIT // QNX rlimit syscalls don't work properly with ACE. - -#define ACE_MT_SAFE 1 -#define ACE_NEEDS_FUNC_DEFINITIONS -#define ACE_NEEDS_HUGE_THREAD_STACKSIZE 64000 -#define ACE_THR_PRI_FIFO_DEF 10 -#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 -#define ACE_HAS_SIGTIMEDWAIT -#define ACE_HAS_SIGSUSPEND - -#define ACE_HAS_BROKEN_PREALLOCATED_OBJECTS_AFTER_FORK 1 - -#define ACE_SIZEOF_WCHAR 4 - -// No prototypes -#define ACE_LACKS_ITOW -#define ACE_LACKS_WCSICMP -#define ACE_LACKS_WCSNICMP -#define ACE_LACKS_WCSDUP -// The default value of FD_SETSIZE is 32, but actually x86 NTO -// supports by default at least 1000 descriptors in fd_set. -#if defined( FD_SETSIZE ) -#undef FD_SETSIZE -#endif -#define FD_SETSIZE 1000 -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_QNX_RTP_62x_H*/ diff --git a/externals/ace/config-qnx-rtp-common.h b/externals/ace/config-qnx-rtp-common.h deleted file mode 100644 index 79eb2397b4f..00000000000 --- a/externals/ace/config-qnx-rtp-common.h +++ /dev/null @@ -1,50 +0,0 @@ -// -*- C++ -*- -// $Id: config-qnx-rtp-common.h 85074 2009-04-10 03:17:24Z mesnier_p $ -// several macros common to various qnx neutrino version. - -#ifndef ACE_CONFIG_QNX_RTP_COMMON_H -#define ACE_CONFIG_QNX_RTP_COMMON_H -#include /**/ "ace/pre.h" - -#define _POSIX_C_SOURCE 199506 -#define _QNX_SOURCE - -// These constants are in i386-nto/include/limits.h, but egcs -// picks up its own limits.h instead: -#define _POSIX_NAME_MAX 14 /* Max bytes in a filename */ -#define _POSIX_PATH_MAX 256 /* Num. bytes in pathname (excl. NULL) */ - -#if defined(__OPTIMIZE__) -# if defined(__X86__) - // string.h can't be used by ACE with __OPTIMIZE__. -# undef __OPTIMIZE__ -# include -# define __OPTIMIZE__ -# endif /* __X86__ */ -#endif /* __OPTIMIZE__ */ - -#include "ace/config-g++-common.h" - -// The following defines the Neutrino compiler. -// gcc should know to call g++ as necessary -#ifdef __GNUC__ -# define ACE_CC_NAME ACE_TEXT ("gcc") -#else -# define ACE_CC_NAME ACE_TEXT ("QNX-RTP compiler ??") -#endif - -// /usr/nto/include/float.h defines -// FLT_MAX_EXP 127 -// DBL_MAX_EXP 1023 -// ace expects 128 & 1024 respectively -// to set the following macros in ace/Basic_Types.h -// These macros are: -#define ACE_SIZEOF_DOUBLE 8 -#define ACE_SIZEOF_FLOAT 4 - -// At least qnx 6.3.2 uses a void return for unsetenv -// This assumes that older versions do too. -#define ACE_HAS_VOID_UNSETENV - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_QNX_RTP_COMMON_H */ diff --git a/externals/ace/config-qnx-rtp-pre62x.h b/externals/ace/config-qnx-rtp-pre62x.h deleted file mode 100644 index 504d3a3ac09..00000000000 --- a/externals/ace/config-qnx-rtp-pre62x.h +++ /dev/null @@ -1,152 +0,0 @@ -// -*- C++ -*- -// $Id: config-qnx-rtp-pre62x.h 87167 2009-10-19 19:33:53Z olli $ -// The following configuration file is designed to work for QNX RTP -// GNU C++ and the POSIX (pthread) threads package. You can get QNX -// RTP at http://get.qnx.com - -#ifndef ACE_CONFIG_RTP_PRE62x_H -#define ACE_CONFIG_RTP_PRE62x_H -#include /**/ "ace/pre.h" -#include /**/ "ace/config-qnx-rtp-common.h" - -///////////////////////////////////////////////////////////////// -// Definition of the features that are available. -// -// ACE_HAS Section -///////////////////////////////////////////////////////////////// - -#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R -#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG -// Although ACE does have alloca() on this compiler/platform combination, it is -// disabled by default since it can be dangerous. Uncomment the following line -// if you ACE to use it. -//#define ACE_HAS_ALLOCA -#define ACE_HAS_ALLOCA_H -#define ACE_HAS_AUTOMATIC_INIT_FINI -#define ACE_HAS_CLOCK_GETTIME -#define ACE_HAS_CLOCK_SETTIME -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES -#define ACE_HAS_DIRENT -#define ACE_HAS_GETPAGESIZE -// Enable gperf, this is a hosted configuration. -#define ACE_HAS_GPERF -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT -//#define ACE_HAS_NONSTATIC_OBJECT_MANAGER -#define ACE_HAS_INLINED_OSCALLS -#define ACE_HAS_IP_MULTICAST -#define ACE_HAS_MSG -#define ACE_HAS_MT_SAFE_MKTIME -#define ACE_HAS_MUTEX_TIMEOUTS -#define ACE_HAS_NONCONST_SELECT_TIMEVAL -#define ACE_HAS_POSIX_SEM -#define ACE_HAS_POSIX_TIME -#define ACE_HAS_PTHREADS -#define ACE_HAS_P_READ_WRITE -#define ACE_HAS_REENTRANT_FUNCTIONS -#define ACE_HAS_SELECT_H -#define ACE_HAS_SIGINFO_T -#define ACE_HAS_SIGISMEMBER_BUG -#define ACE_HAS_SIGWAIT -#define ACE_HAS_SIG_ATOMIC_T -#define ACE_HAS_SOCKADDR_IN_SIN_LEN -// #define ACE_HAS_SIZET_SOCKET_LEN -#define ACE_HAS_SOCKLEN_T -#define ACE_HAS_SSIZE_T -#define ACE_HAS_STRINGS -#define ACE_HAS_SVR4_GETTIMEOFDAY -#define ACE_HAS_TERMIOS -#define ACE_HAS_THREADS -#define ACE_HAS_THREAD_SPECIFIC_STORAGE -#define ACE_HAS_THR_C_DEST -#define ACE_HAS_THR_C_FUNC -#define ACE_HAS_TIMEZONE_GETTIMEOFDAY -#define ACE_HAS_UALARM -#define ACE_HAS_UCONTEXT_T -#define ACE_HAS_VOIDPTR_MMAP -#define ACE_HAS_VOIDPTR_SOCKOPT - -///////////////////////////////////////////////////////////////// -// Definition of the features that are not available. -// -// ACE_LACKS Section -///////////////////////////////////////////////////////////////// -#define ACE_LACKS_CONDATTR_PSHARED -#define ACE_LACKS_CONST_TIMESPEC_PTR -#define ACE_LACKS_LINEBUFFERED_STREAMBUF -#define ACE_LACKS_MADVISE -#define ACE_LACKS_MUTEXATTR_PSHARED -#define ACE_LACKS_NAMED_POSIX_SEM -#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS -#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS -#define ACE_LACKS_PTHREAD_THR_SIGSETMASK -#define ACE_LACKS_RWLOCK_T -#define ACE_LACKS_SBRK -#define ACE_LACKS_SEEKDIR -#define ACE_LACKS_SO_SNDBUF -#define ACE_LACKS_SO_RCVBUF -#define ACE_LACKS_SOCKETPAIR -// Even if the QNX RTP docs says that socket pair are -// available, there is actually no implementation of -// soket-pairs. -#define ACE_LACKS_STREAM_MODULES -#define ACE_LACKS_STRRECVFD -#define ACE_LACKS_SYSCALL -#define ACE_LACKS_SYS_MSG_H -#define ACE_LACKS_SYSV_SHMEM -#define ACE_LACKS_ALPHASORT -//#define ACE_LACKS_TCP_NODELAY // Based on the QNX RTP documentation, this option seems to - // to be supported. -#define ACE_LACKS_TELLDIR -#define ACE_LACKS_TIMESPEC_T -#define ACE_LACKS_TRUNCATE -#define ACE_LACKS_T_ERRNO -#define ACE_LACKS_UALARM_PROTOTYPE -#define ACE_LACKS_UCONTEXT_H -#define ACE_LACKS_UNIX_DOMAIN_SOCKETS -#define ACE_LACKS_U_LONGLONG_T -#define ACE_LACKS_FD_MASK -#define ACE_LACKS_NFDBITS - -#define ACE_LACKS_RLIMIT // QNX rlimit syscalls don't work properly with ACE. - -#define ACE_MT_SAFE 1 -#define ACE_NEEDS_FUNC_DEFINITIONS -#define ACE_NEEDS_HUGE_THREAD_STACKSIZE 64000 -#define ACE_TEMPLATES_REQUIRE_SOURCE -#define ACE_THR_PRI_FIFO_DEF 10 -#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 -#define ACE_HAS_SIGTIMEDWAIT -#define ACE_HAS_SIGSUSPEND - -#define ACE_HAS_BROKEN_PREALLOCATED_OBJECTS_AFTER_FORK 1 - -#define ACE_SIZEOF_WCHAR 4 - -// Not really, but the prototype returns wchar_t instead of wchar_t * -#define ACE_LACKS_WCSSTR - -// No prototypes -#define ACE_LACKS_ITOW -#define ACE_LACKS_WCSICMP -#define ACE_LACKS_WCSNICMP -#define ACE_LACKS_WCSDUP - -// And these have prototypes but no implementation -#define ACE_LACKS_WCSLEN -#define ACE_LACKS_WCSNCMP -#define ACE_LACKS_WCSCPY -#define ACE_LACKS_WCSNCPY -#define ACE_LACKS_TOWLOWER -#define ACE_LACKS_TOWUPPER -#define ACE_LACKS_WCSCMP -#define ACE_LACKS_WCSCAT -#define ACE_LACKS_WCSNCAT -#define ACE_LACKS_WCSSPN -#define ACE_LACKS_WCSCHR -#define ACE_LACKS_WCSPBRK -#define ACE_LACKS_WCSRCHR - -#define ACE_LACKS_ACE_IOSTREAM - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_RTP_PRE62x_H */ diff --git a/externals/ace/config-qnx-rtp.h b/externals/ace/config-qnx-rtp.h deleted file mode 100644 index c55a4abb988..00000000000 --- a/externals/ace/config-qnx-rtp.h +++ /dev/null @@ -1,25 +0,0 @@ -// -*- C++ -*- -// $Id: config-qnx-rtp.h 80826 2008-03-04 14:51:23Z wotte $ -// The following configuration file is designed to work for QNX RTP -// GNU C++ and the POSIX (pthread) threads package. You can get QNX -// RTP at http://get.qnx.com. -// This header is intended to switch between configuration for -// various NTO versions. -#ifndef ACE_CONFIG_QNX_RTP_H -#define ACE_CONFIG_QNX_RTP_H -#include /**/ "ace/pre.h" - -#include -#if !defined(_NTO_VERSION) -# error "Could not detect QNX version from macro _NTO_VERSION" -#else -# define ACE_NTO_VERS _NTO_VERSION -# if ACE_NTO_VERS < 620 -# include /**/ "ace/config-qnx-rtp-pre62x.h" -# else -# include /**/ "ace/config-qnx-rtp-62x.h" -# endif -#endif - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_QNX_RTP_H */ diff --git a/externals/ace/config-rtems.h b/externals/ace/config-rtems.h deleted file mode 100644 index d113a1434a4..00000000000 --- a/externals/ace/config-rtems.h +++ /dev/null @@ -1,164 +0,0 @@ -/* -*- C -*- */ -// $Id: config-rtems.h 87169 2009-10-19 20:26:55Z olli $ - -/* The following configuration file is designed to work for RTEMS - platforms using GNU C. -*/ - -#ifndef ACE_CONFIG_H -#define ACE_CONFIG_H - -#if ! defined (__ACE_INLINE__) -#define __ACE_INLINE__ -#endif /* ! __ACE_INLINE__ */ - -// Needed to make some prototypes visible. -// #if ! defined (_GNU_SOURCE) -// #define _GNU_SOURCE -// #endif /* ! _GNU_SOURCE */ - -// First the machine specific part -// There are no known port specific issues with the RTEMS port of ACE. -// XXX Pentium and PowerPC have high res timer support in ACE. - -// Then the compiler specific parts -#if defined (__GNUG__) - // config-g-common.h undef's ACE_HAS_STRING_CLASS with -frepo, so - // this must appear before its #include. -# define ACE_HAS_STRING_CLASS -# include "ace/config-g++-common.h" -#else /* ! __GNUG__ */ -# ifdef __cplusplus /* Let it slide for C compilers. */ -# error unsupported compiler in ace/config-rtems.h -# endif /* __cplusplus */ -#endif /* ! __GNUG__ */ - -#include "ace/config-posix.h" - -// Completely common part :-) - -#define ACE_HAS_NONSTATIC_OBJECT_MANAGER - -#define ACE_LACKS_ALPHASORT -#define ACE_LACKS_REGEX_H -#define ACE_LACKS_STROPTS_H -#define ACE_LACKS_DLFCN_H -#define ACE_LACKS_SIGINFO_H -#define ACE_LACKS_SYS_IPC_H -#define ACE_LACKS_SYS_SEM_H -#define ACE_LACKS_STRINGS_H -#define ACE_LACKS_SYS_SHM_H -#define ACE_LACKS_SETEGID -#define ACE_LACKS_SETEUID -#define ACE_LACKS_POLL_H -#define ACE_HAS_NONCONST_SELECT_TIMEVAL -#define ACE_LACKS_STRCASECMP -#define ACE_LACKS_MKSTEMP -#define ACE_LACKS_STRDUP -#define ACE_LACKS_STRTOK_R -#define ACE_LACKS_RAND_REENTRANT_FUNCTIONS -#define ACE_LACKS_REALPATH -#define ACE_LACKS_TEMPNAM -#define ACE_LACKS_TZSET - -// Temporarily, enabling this results in compile errors with -// rtems 4.6.6. -#define ACE_LACKS_WCHAR_H - -#if !defined (ACE_MT_SAFE) -#define ACE_MT_SAFE 1 -#endif - -#if ACE_MT_SAFE -# define ACE_HAS_THREADS -# define ACE_HAS_PTHREADS -# define ACE_HAS_THREAD_SPECIFIC_STORAGE -# define ACE_HAS_PTHREAD_SCHEDPARAM -# define ACE_LACKS_THREAD_PROCESS_SCOPING -#else -# define ACE_HAS_POSIX_GETPWNAM_R -# define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R -#endif - -#define ACE_HAS_ALT_CUSERID -#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG -#define ACE_HAS_3_PARAM_READDIR_R -#define ACE_HAS_CLOCK_GETTIME -#define ACE_HAS_CLOCK_SETTIME -#define ACE_HAS_DIRENT -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT -#define ACE_HAS_MSG -#define ACE_HAS_MT_SAFE_MKTIME -#define ACE_HAS_NONCONST_READV -#define ACE_HAS_GETPAGESIZE -#define ACE_HAS_POSIX_SEM -#define ACE_HAS_POSIX_TIME -#define ACE_HAS_REENTRANT_FUNCTIONS -#define ACE_HAS_SIGACTION_CONSTP2 -#define ACE_HAS_SIGINFO_T -#define ACE_HAS_SIGSUSPEND -#define ACE_HAS_SSIZE_T -#define ACE_HAS_VOIDPTR_GETTIMEOFDAY -#define ACE_HAS_SYS_FILIO_H -#define ACE_HAS_TIMEZONE_GETTIMEOFDAY -#define ACE_LACKS_EXEC -#define ACE_LACKS_FILELOCKS -#define ACE_LACKS_FORK -#define ACE_LACKS_GETPGID -#define ACE_LACKS_TIMESPEC_T -#define ACE_LACKS_MADVISE -#define ACE_LACKS_MMAP -#define ACE_LACKS_MPROTECT -#define ACE_LACKS_MSYNC -#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS -#define ACE_LACKS_PTHREAD_THR_SIGSETMASK -#define ACE_LACKS_READDIR_R -#define ACE_LACKS_READLINK -#define ACE_LACKS_READV -#define ACE_LACKS_RLIMIT -#define ACE_LACKS_RLIMIT_PROTOTYPE -#define ACE_LACKS_RWLOCK_T -#define ACE_LACKS_SBRK -#define ACE_LACKS_SEMBUF_T -#define ACE_LACKS_SETREUID -#define ACE_LACKS_SETREUID_PROTOTYPE -#define ACE_LACKS_SETREGID -#define ACE_LACKS_SETREGID_PROTOTYPE -#define ACE_LACKS_STRPTIME -#define ACE_LACKS_STRRECVFD -#define ACE_LACKS_SI_ADDR -#define ACE_LACKS_SOCKETPAIR -#define ACE_LACKS_SYS_MSG_H -#define ACE_LACKS_SYSV_SHMEM -#define ACE_LACKS_SYSCALL -#define ACE_LACKS_UCONTEXT_H -#define ACE_HAS_NONCONST_WRITEV -#define ACE_LACKS_WRITEV -#define ACE_NEEDS_HUGE_THREAD_STACKSIZE 65536 -#define ACE_NEEDS_SCHED_H -#define ACE_HAS_POSIX_NONBLOCK -#define ACE_HAS_TERMIOS - -// rtems 4.7 or higher -#if (__RTEMS_MAJOR__ > 4) || (__RTEMS_MAJOR__ == 4 && __RTEMS_MINOR__ > 6) -# define ACE_HAS_UALARM -#else -# define ACE_HAS_NOTSUP_SC_PAGESIZE -# define ACE_LACKS_SUSECONDS_T -# define ACE_LACKS_INTPTR_T -# undef ACE_HAS_SHM_OPEN -# undef ACE_HAS_AIO_CALLS -#endif - -// __RTEMS_REVISION__ could also be used but this is broken according -// to the rtems people - -#if !defined (_POSIX_REALTIME_SIGNALS) -# define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES -#endif - -#if defined (ACE_LACKS_NETWORKING) -# include "ace/config-posix-nonetworking.h" -#endif - -#endif /* ACE_CONFIG_H */ diff --git a/externals/ace/config-sco-5.0.0-nothread.h b/externals/ace/config-sco-5.0.0-nothread.h deleted file mode 100644 index 259bd55c273..00000000000 --- a/externals/ace/config-sco-5.0.0-nothread.h +++ /dev/null @@ -1,12 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-sco-5.0.0-nothread.h 87268 2009-10-29 21:06:06Z olli $ - -#ifndef ACE_CONFIG_H -#define ACE_CONFIG_H -#include /**/ "ace/pre.h" - -#include "ace/config-g++-common.h" -#include "ace/config-sco-5.0.0.h" - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_H */ diff --git a/externals/ace/config-sco-5.0.0.h b/externals/ace/config-sco-5.0.0.h deleted file mode 100644 index 61b68213bc1..00000000000 --- a/externals/ace/config-sco-5.0.0.h +++ /dev/null @@ -1,90 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-sco-5.0.0.h 87167 2009-10-19 19:33:53Z olli $ - -#ifndef ACE_CONFIG_SCO_5_0_0_H -#define ACE_CONFIG_SCO_5_0_0_H -#include /**/ "ace/pre.h" - -// Compiling for SCO. -#if !defined (SCO) -#define SCO -#endif /* SCO */ - -#if defined (SCO) && !defined (MAXPATHLEN) -#define MAXPATHLEN 1023 -#endif /* SCO */ - -#define ACE_HAS_NONCONST_SELECT_TIMEVAL -#define ACE_LACKS_CONST_TIMESPEC_PTR -#define ACE_LACKS_SYSCALL -#define ACE_LACKS_STRRECVFD -#define ACE_NEEDS_FTRUNCATE -#define ACE_LACKS_MADVISE -#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS - -#define ACE_DEFAULT_CLOSE_ALL_HANDLES 0 - -// Platform supports System V IPC (most versions of UNIX, but not Win32) -#define ACE_HAS_SYSV_IPC -#define ACE_HAS_NONCONST_MSGSND -#define ACE_HAS_BIG_FD_SET -#define ACE_HAS_SVR4_DYNAMIC_LINKING -#define ACE_HAS_AUTOMATIC_INIT_FINI - -// Platform has POSIX terminal interface. -#define ACE_HAS_TERMIOS - -// Compiler/platform contains the file. -//#define ACE_HAS_SYS_SYSCALL_H - -// Fixes a problem with HP/UX not wrapping the mmap(2) header files -// with extern "C". -//#define ACE_HAS_BROKEN_MMAP_H - -// Prototypes for both signal() and struct sigaction are consistent. -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES - -// Compiler/platform has correctly prototyped header files. -#define ACE_HAS_CPLUSPLUS_HEADERS - -// Compiler/platform supports poll(). -// #define ACE_HAS_POLL - -// Platform supports POSIX O_NONBLOCK semantics. -#define ACE_HAS_POSIX_NONBLOCK - -// Compiler/platform defines the sig_atomic_t typedef -#define ACE_HAS_SIG_ATOMIC_T - -// Compiler supports the ssize_t typedef. -//#define ACE_HAS_SSIZE_T - -// Defines the page size of the system. -#define ACE_PAGE_SIZE 4096 - -#define ACE_HAS_TIMEZONE_GETTIMEOFDAY - -// Note, this only works if the flag is set above! -//#define ACE_HAS_GETRUSAGE - -// Platform uses int for select() rather than fd_set. -#define ACE_HAS_SELECT_H - -// Platform has prototypes for ACE_TLI. -#define ACE_HAS_TLI_PROTOTYPES -// Platform has the XLI version of ACE_TLI. -// #define ACE_HAS_XLI - -#define ACE_HAS_SIGINFO_T -#define ACE_HAS_UCONTEXT_T - -#define ACE_LACKS_STRCASECMP - -// #define ACE_HAS_POSIX_TIME -#define ACE_HAS_IP_MULTICAST -#define ACE_HAS_DIRENT -#define ACE_LACKS_READDIR_R -#define ACE_HAS_GPERF - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_SCO_5_0_0_H */ diff --git a/externals/ace/config-suncc-common.h b/externals/ace/config-suncc-common.h deleted file mode 100644 index 3f0bae8a295..00000000000 --- a/externals/ace/config-suncc-common.h +++ /dev/null @@ -1,67 +0,0 @@ -// -*- C++ -*- -// -// $Id: config-suncc-common.h 81935 2008-06-12 22:01:53Z jtc $ - -#ifndef ACE_SUNCC_COMMON_H -#define ACE_SUNCC_COMMON_H -#include /**/ "ace/pre.h" - -# define ACE_HAS_CPLUSPLUS_HEADERS -# define ACE_HAS_STDCPP_STL_INCLUDES -# define ACE_HAS_TEMPLATE_TYPEDEFS -# define ACE_HAS_STANDARD_CPP_LIBRARY 1 -# define ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR -# define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 -# define ACE_HAS_STRING_CLASS -# define ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS -# define ACE_HAS_THR_C_DEST 1 -# define ACE_LACKS_SWAB -#if defined (ACE_HAS_CUSTOM_EXPORT_MACROS) && ACE_HAS_CUSTOM_EXPORT_MACROS == 0 -# undef ACE_HAS_CUSTOM_EXPORT_MACROS -#else -# ifndef ACE_HAS_CUSTOM_EXPORT_MACROS -# define ACE_HAS_CUSTOM_EXPORT_MACROS -# endif /* !ACE_HAS_CUSTOM_EXPORT_MACROS */ -# define ACE_Proper_Export_Flag __attribute__ ((visibility("default"))) -# define ACE_Proper_Import_Flag -# define ACE_EXPORT_SINGLETON_DECLARATION(T) template class ACE_Proper_Export_Flag T -# define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) template class ACE_Proper_Export_Flag SINGLETON_TYPE ; -# define ACE_IMPORT_SINGLETON_DECLARATION(T) __extension__ extern template class T -# define ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) __extension__ extern template class SINGLETON_TYPE; -#endif /* ACE_HAS_CUSTOM_EXPORT_MACROS == 0 */ - -// __EXCEPTIONS is defined with -fexceptions, the egcs default. It -// is not defined with -fno-exceptions, the ACE default for g++. -// ACE_HAS_EXCEPTIONS is defined in -// include/makeinclude/wrapper_macros.GNU, so this really isn't -// necessary. Just in case . . . -# if defined (__EXCEPTIONS) && !defined (ACE_HAS_EXCEPTIONS) -# define ACE_HAS_EXCEPTIONS -# endif /* __EXCEPTIONS && ! ACE_HAS_EXCEPTIONS */ - -# if defined (ACE_HAS_EXCEPTIONS) -# define ACE_NEW_THROWS_EXCEPTIONS -# endif /* ACE_HAS_EXCEPTIONS */ - -#if (defined (i386) || defined (__i386__)) && !defined (ACE_SIZEOF_LONG_DOUBLE) -# define ACE_SIZEOF_LONG_DOUBLE 12 -#endif /* i386 */ - -#if defined (i386) || defined (__i386__) - // If running an Intel, assume that it's a Pentium so that - // ACE_OS::gethrtime () can use the RDTSC instruction. If running a - // 486 or lower, be sure to comment this out. (If not running an - // Intel CPU, this #define will not be seen because of the i386 - // protection, so it can be ignored.) -# define ACE_HAS_PENTIUM -#endif /* i386 */ - -#if !defined (ACE_LACKS_PRAGMA_ONCE) - // We define it with a -D with make depend. -# define ACE_LACKS_PRAGMA_ONCE -#endif /* ! ACE_LACKS_PRAGMA_ONCE */ - -#define ACE_TEMPLATES_REQUIRE_SOURCE - -#include /**/ "ace/post.h" -#endif /* ACE_SUNCC_COMMON_H */ diff --git a/externals/ace/config-sunos5.10.h b/externals/ace/config-sunos5.10.h deleted file mode 100644 index df6f095fec9..00000000000 --- a/externals/ace/config-sunos5.10.h +++ /dev/null @@ -1,66 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-sunos5.10.h 89905 2010-04-16 13:04:47Z johnnyw $ - -// The following configuration file is designed to work for SunOS 5.10 -// (Solaris 10) platforms using the SunC++ 5.x (Sun Studio 8-10), or g++ -// compilers. - -#ifndef ACE_CONFIG_H - -// ACE_CONFIG_H is defined by one of the following #included headers. - -// #include the SunOS 5.9 config, then add any SunOS 5.10 updates below. -#include "ace/config-sunos5.9.h" - -// Solaris 10 can do sem_timedwait() (see ACE_OS::sema_wait). -#define ACE_HAS_POSIX_SEM_TIMEOUT - -#define ACE_HAS_SCANDIR - -// Solaris 10 offers a useable alphasort() unlike previous Solaris versions. -#if defined (ACE_LACKS_ALPHASORT) -# undef ACE_LACKS_ALPHASORT -#endif - -// Solaris 10 offers a useable log2() unlike previous Solaris versions. -#if defined (ACE_LACKS_LOG2) -# undef ACE_LACKS_LOG2 -#endif - -// Solaris 10 offers a useable isblank() unlike previous Solaris versions. -#if defined (ACE_LACKS_ISBLANK) -# undef ACE_LACKS_ISBLANK -#endif - -// Solaris 10 delivers pthread_attr_setstack -#if defined (ACE_LACKS_PTHREAD_ATTR_SETSTACK) -# undef ACE_LACKS_PTHREAD_ATTR_SETSTACK -#endif - -// Solaris 10 introduced printf() modifiers for [s]size_t types. -#if defined (ACE_SSIZE_T_FORMAT_SPECIFIER_ASCII) -# undef ACE_SSIZE_T_FORMAT_SPECIFIER_ASCII -# define ACE_SSIZE_T_FORMAT_SPECIFIER_ASCII "%zd" -#endif /* ACE_SSIZE_T_FORMAT_SPECIFIER_ASCII */ - -#if defined (ACE_SIZE_T_FORMAT_SPECIFIER_ASCII) -# undef ACE_SIZE_T_FORMAT_SPECIFIER_ASCII -# define ACE_SIZE_T_FORMAT_SPECIFIER_ASCII "%zu" -#endif /* ACE_SIZE_T_FORMAT_SPECIFIER_ASCII */ - -// Solaris 10 offers wcstoll() and wcstoull() -#if defined (ACE_LACKS_WCSTOLL) -# undef ACE_LACKS_WCSTOLL -#endif /* ACE_LACKS_WCSTOLL */ -#if defined (ACE_LACKS_WCSTOULL) -# undef ACE_LACKS_WCSTOULL -#endif /* ACE_LACKS_WCSTOULL */ - -#if defined (ACE_HAS_SCTP) && defined (ACE_HAS_LKSCTP) -# define ACE_HAS_VOID_PTR_SCTP_GETLADDRS -# define ACE_HAS_VOID_PTR_SCTP_GETPADDRS -#endif - -#define ACE_HAS_SOLARIS_ATOMIC_LIB - -#endif /* ACE_CONFIG_H */ diff --git a/externals/ace/config-sunos5.11.h b/externals/ace/config-sunos5.11.h deleted file mode 100644 index bbfd91c82fe..00000000000 --- a/externals/ace/config-sunos5.11.h +++ /dev/null @@ -1,15 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-sunos5.11.h 80826 2008-03-04 14:51:23Z wotte $ - -// The following configuration file is designed to work for SunOS 5.11 -// (Solaris 11) platforms using the SunC++ 5.x (Sun Studio 10-12), or g++ -// compilers. - -#ifndef ACE_CONFIG_H - -// ACE_CONFIG_H is defined by one of the following #included headers. - -// #include the SunOS 5.10 config, then add any SunOS 5.11 updates below. -#include "ace/config-sunos5.10.h" - -#endif /* ACE_CONFIG_H */ diff --git a/externals/ace/config-sunos5.4-g++.h b/externals/ace/config-sunos5.4-g++.h deleted file mode 100644 index a678389e78d..00000000000 --- a/externals/ace/config-sunos5.4-g++.h +++ /dev/null @@ -1,176 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-sunos5.4-g++.h 87268 2009-10-29 21:06:06Z olli $ - -// The following configuration file is designed to work for SunOS 5.4 -// platforms using the GNU g++ compiler. - -#ifndef ACE_CONFIG_H -#define ACE_CONFIG_H -#include /**/ "ace/pre.h" - -#if ! defined (__ACE_INLINE__) -# define __ACE_INLINE__ -#endif /* ! __ACE_INLINE__ */ - -// config-g++-common.h undef's ACE_HAS_STRING_CLASS with -frepo, so -// this must appear before its #include. -#define ACE_HAS_STRING_CLASS - -#include "ace/config-g++-common.h" - -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT - -// Platform supports pread() and pwrite() -#define ACE_HAS_P_READ_WRITE - -#define ACE_HAS_XPG4_MULTIBYTE_CHAR - -// Platform has POSIX terminal interface. -#define ACE_HAS_TERMIOS - -// Platform supports System V IPC (most versions of UNIX, but not Win32) -#define ACE_HAS_SYSV_IPC - -// Sun has the wrong prototype for sendmsg. -#define ACE_HAS_NONCONST_SENDMSG - -// The SunOS 5.x version of rand_r is inconsistent with the header files... -#define ACE_HAS_BROKEN_RANDR - -// Platform supports system configuration information. -#define ACE_HAS_SYS_SYSTEMINFO_H -#define ACE_HAS_SYSV_SYSINFO - -// Platform supports the POSIX regular expression library -#define ACE_HAS_REGEX - -// Platform supports recvmsg and sendmsg. -#define ACE_HAS_MSG - -// Compiler/platform contains the file. -#define ACE_HAS_SYS_SYSCALL_H - -// Compiler/platform correctly calls init()/fini() for shared libraries. -#define ACE_HAS_AUTOMATIC_INIT_FINI - -// Platform supports POSIX O_NONBLOCK semantics. -#define ACE_HAS_POSIX_NONBLOCK - -// Compiler/platform has correctly prototyped header files. -#define ACE_HAS_CPLUSPLUS_HEADERS - -// Compiler/platform supports SunOS high resolution timers. -#define ACE_HAS_HI_RES_TIMER - -// Platform supports IP multicast -#define ACE_HAS_IP_MULTICAST - -// Compiler/platform supports alloca() -// Although ACE does have alloca() on this compiler/platform combination, it is -// disabled by default since it can be dangerous. Uncomment the following line -// if you ACE to use it. -//#define ACE_HAS_ALLOCA - -// Compiler/platform has -#define ACE_HAS_ALLOCA_H - -// Platform contains . -#define ACE_HAS_POLL - -// Platform supports POSIX timers via timestruc_t. -#define ACE_HAS_POSIX_TIME - -// Platform supports the /proc file system. -#define ACE_HAS_PROC_FS - -// Platform supports the prusage_t struct. -#define ACE_HAS_PRUSAGE_T - -// Compiler/platform defines the sig_atomic_t typedef. -#define ACE_HAS_SIG_ATOMIC_T - -// Platform supports SVR4 extended signals. -#define ACE_HAS_SIGINFO_T -#define ACE_HAS_UCONTEXT_T - -// Compiler/platform provides the sockio.h file. -#define ACE_HAS_SYS_SOCKIO_H - -// Compiler supports the ssize_t typedef. -#define ACE_HAS_SSIZE_T - -// Platform supports STREAMS. -#define ACE_HAS_STREAMS - -// Platform supports STREAM pipes. -#define ACE_HAS_STREAM_PIPES - -// Compiler/platform supports struct strbuf. -#define ACE_HAS_STRBUF_T - -// Compiler/platform supports SVR4 dynamic linking semantics. -#define ACE_HAS_SVR4_DYNAMIC_LINKING - -// Compiler/platform supports SVR4 gettimeofday() prototype. -#define ACE_HAS_SVR4_GETTIMEOFDAY - -// Platform lacks pthread_sigaction -#define ACE_LACKS_PTHREAD_THR_SIGSETMASK - -// Compiler/platform supports SVR4 TLI (in particular, T_GETNAME stuff)... -#define ACE_HAS_SVR4_TLI - -// Platform provides header. -#define ACE_HAS_SYS_FILIO_H - -#define ACE_HAS_STRSIGNAL - -/* Turn off the following defines if you want to disable threading. */ -// Compile using multi-thread libraries. -#if !defined (ACE_MT_SAFE) -# define ACE_MT_SAFE 1 -# if !defined (_REENTRANT) -# define _REENTRANT -# endif /* _REENTRANT */ -#endif /* !ACE_MT_SAFE */ - -// Platform supports Solaris threads. -#define ACE_HAS_STHREADS - -// Platform supports threads. -#define ACE_HAS_THREADS - -// Compiler/platform has thread-specific storage -#define ACE_HAS_THREAD_SPECIFIC_STORAGE - -// Platform supports reentrant functions (i.e., all the POSIX *_r functions). -#define ACE_HAS_REENTRANT_FUNCTIONS - -/* end threading defines */ - -#define ACE_HAS_PRIOCNTL -#define ACE_NEEDS_LWP_PRIO_SET - -// Platform supports TLI timod STREAMS module. -#define ACE_HAS_TIMOD_H - -// Platform supports TLI tiuser header. -#define ACE_HAS_TIUSER_H - -// Platform provides TLI function prototypes. -#define ACE_HAS_TLI_PROTOTYPES - -// Platform supports TLI. -#define ACE_HAS_TLI - -// Use the poll() event demultiplexor rather than select(). -//#define ACE_USE_POLL - -// Defines the page size of the system. -#define ACE_PAGE_SIZE 4096 -#define ACE_HAS_IDTYPE_T -#define ACE_HAS_GPERF -#define ACE_HAS_DIRENT - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_H */ diff --git a/externals/ace/config-sunos5.4-sunc++-4.x.h b/externals/ace/config-sunos5.4-sunc++-4.x.h deleted file mode 100644 index d7d0862e328..00000000000 --- a/externals/ace/config-sunos5.4-sunc++-4.x.h +++ /dev/null @@ -1,186 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-sunos5.4-sunc++-4.x.h 87250 2009-10-28 11:57:17Z olli $ - -// The following configuration file is designed to work for SunOS 5.4 -// platforms using the SunC++ 4.0.x compiler. - -#ifndef ACE_CONFIG_H -#define ACE_CONFIG_H -#include /**/ "ace/pre.h" - -#if ! defined (__ACE_INLINE__) -# define __ACE_INLINE__ -#endif /* ! __ACE_INLINE__ */ - -// Optimize ACE_Handle_Set for select(). -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT - -// Platform supports pread() and pwrite() -#define ACE_HAS_P_READ_WRITE - -#define ACE_HAS_XPG4_MULTIBYTE_CHAR - -// Platform supports System V IPC (most versions of UNIX, but not Win32) -#define ACE_HAS_SYSV_IPC - -// Sun has the wrong prototype for sendmsg. -#define ACE_HAS_NONCONST_SENDMSG - -// The SunOS 5.x version of rand_r is inconsistent with the header files... -#define ACE_HAS_BROKEN_RANDR - -// Platform supports system configuration information. -#define ACE_HAS_SYS_SYSTEMINFO_H -#define ACE_HAS_SYSV_SYSINFO - -// Platform supports the POSIX regular expression library. -#define ACE_HAS_REGEX - -// Platform supports recvmsg and sendmsg. -#define ACE_HAS_MSG - -// Compiler/platform contains the file. -#define ACE_HAS_SYS_SYSCALL_H - -// Platform has POSIX terminal interface. -#define ACE_HAS_TERMIOS - -// Compiler/platform correctly calls init()/fini() for shared libraries. -#define ACE_HAS_AUTOMATIC_INIT_FINI - -// Platform supports POSIX O_NONBLOCK semantics. -#define ACE_HAS_POSIX_NONBLOCK - -// Compiler/platform has correctly prototyped header files. -#define ACE_HAS_CPLUSPLUS_HEADERS - -// Compiler/platform supports SunOS high resolution timers. -#define ACE_HAS_HI_RES_TIMER - -// Platform supports IP multicast -#define ACE_HAS_IP_MULTICAST - -// Compiler/platform supports alloca() -// Although ACE does have alloca() on this compiler/platform combination, it is -// disabled by default since it can be dangerous. Uncomment the following line -// if you ACE to use it. -//#define ACE_HAS_ALLOCA - -// Compiler/platform has -#define ACE_HAS_ALLOCA_H - -// Platform contains . -#define ACE_HAS_POLL - -// Platform supports POSIX timers via timestruc_t. -#define ACE_HAS_POSIX_TIME - -// Platform supports the /proc file system. -#define ACE_HAS_PROC_FS - -// Platform supports the prusage_t struct. -#define ACE_HAS_PRUSAGE_T - -// Compiler/platform defines the sig_atomic_t typedef. -#define ACE_HAS_SIG_ATOMIC_T - -// Platform supports SVR4 extended signals. -#define ACE_HAS_SIGINFO_T -#define ACE_HAS_UCONTEXT_T - -// Compiler/platform provides the sockio.h file. -#define ACE_HAS_SYS_SOCKIO_H - -// Compiler supports the ssize_t typedef. -#define ACE_HAS_SSIZE_T - -// Platform supports STREAMS. -#define ACE_HAS_STREAMS - -// Platform supports STREAM pipes. -#define ACE_HAS_STREAM_PIPES - -// Compiler/platform supports struct strbuf. -#define ACE_HAS_STRBUF_T - -// Compiler/platform supports SVR4 dynamic linking semantics. -#define ACE_HAS_SVR4_DYNAMIC_LINKING - -// Compiler/platform supports SVR4 gettimeofday() prototype. -#define ACE_HAS_SVR4_GETTIMEOFDAY - -// Compiler/platform supports SVR4 signal typedef. -#define ACE_HAS_SVR4_SIGNAL_T - -// Platform lacks pthread_sigaction -#define ACE_LACKS_PTHREAD_THR_SIGSETMASK - -// Compiler/platform supports SVR4 ACE_TLI (in particular, T_GETNAME stuff)... -#define ACE_HAS_SVR4_TLI - -// Platform provides header. -#define ACE_HAS_SYS_FILIO_H - -#define ACE_HAS_STRSIGNAL - -/* Turn off the following defines if you want to disable threading. */ -// Compile using multi-thread libraries. -#if !defined (ACE_MT_SAFE) -# define ACE_MT_SAFE 1 -#endif - -// Platform supports Solaris threads. -#define ACE_HAS_STHREADS - -// Platform supports threads. -#define ACE_HAS_THREADS - -// Compiler/platform has thread-specific storage -#define ACE_HAS_THREAD_SPECIFIC_STORAGE - -// Platform supports reentrant functions (i.e., all the POSIX *_r functions). -#define ACE_HAS_REENTRANT_FUNCTIONS - -/* end threading defines */ - -#define ACE_HAS_PRIOCNTL -#define ACE_NEEDS_LWP_PRIO_SET - -// Reactor detects deadlock -// #define ACE_REACTOR_HAS_DEADLOCK_DETECTION - -// Platform supports ACE_TLI timod STREAMS module. -#define ACE_HAS_TIMOD_H - -// Platform supports ACE_TLI tiuser header. -#define ACE_HAS_TIUSER_H - -// Platform provides ACE_TLI function prototypes. -#define ACE_HAS_TLI_PROTOTYPES - -// Platform supports ACE_TLI. -#define ACE_HAS_TLI - -#define ACE_LACKS_LINEBUFFERED_STREAMBUF -#define ACE_LACKS_SIGNED_CHAR - -// Use the poll() event demultiplexor rather than select(). -//#define ACE_USE_POLL - -#define ACE_NEEDS_DEV_IO_CONVERSION - -// Defines the page size of the system. -#define ACE_PAGE_SIZE 4096 -#define ACE_HAS_IDTYPE_T - -#define ACE_HAS_GPERF -#define ACE_HAS_DIRENT - -# if defined (ACE_HAS_EXCEPTIONS) - // If exceptions are enabled and we are using Sun/CC then - // throws an exception instead of returning 0. -# define ACE_NEW_THROWS_EXCEPTIONS -# endif /* ACE_HAS_EXCEPTIONS */ - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_H */ diff --git a/externals/ace/config-sunos5.5.h b/externals/ace/config-sunos5.5.h deleted file mode 100644 index f16b50394bd..00000000000 --- a/externals/ace/config-sunos5.5.h +++ /dev/null @@ -1,432 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-sunos5.5.h 89494 2010-03-15 20:11:18Z olli $ - -// This configuration file is designed to work for SunOS 5.5 platforms -// using the following compilers: -// * Sun C++ 4.2 and later (including 5.x), patched as noted below -// * g++ 2.7.2 and later, including egcs -// * Green Hills 1.8.8 and later - -#ifndef ACE_CONFIG_H -#define ACE_CONFIG_H -#include /**/ "ace/pre.h" - -#define ACE_LACKS_STDINT_H - -// alphasort() is present on earlier Solaris versions but is marked as not for -// use on non-BSD systems and not supported for use in applications that use -// system libraries or with multiple threads. So it's mostly useless. -#define ACE_LACKS_ALPHASORT - -// Solaris doesn't support log2() -#define ACE_LACKS_LOG2 - -// SunOS 5.5 does not provide getloadavg() -#define ACE_LACKS_GETLOADAVG - -// Some SunOS releases define _POSIX_PTHREAD_SEMANTICS automatically. -// We need to be check if the user has manually defined the macro before -// including . -#if defined (_POSIX_PTHREAD_SEMANTICS) -# define ACE_HAS_POSIX_PTHREAD_SEMANTICS -#endif /* _POSIX_PTHREAD_SEMANTICS */ - -// Before we do anything, we should include to -// ensure that things are set up properly. -#include - -// Some SunOS releases define _POSIX_PTHREAD_SEMANTICS automatically. -// We need to undef if the macro is set and not defined by the user. -#if defined (_POSIX_PTHREAD_SEMANTICS) && \ - !defined (ACE_HAS_POSIX_PTHREAD_SEMANTICS) -# undef _POSIX_PTHREAD_SEMANTICS -#endif /* _POSIX_PTHREAD_SEMANTICS && !ACE_HAS_POSIX_PTHREAD_SEMANTICS */ - -// Sun has the posix defines so let this file sort out what Sun delivers -#include "ace/config-posix.h" - -// Compiler version-specific settings: -#if defined (__SUNPRO_CC) -# if (__SUNPRO_CC < 0x410) - // The following might not be necessary, but I can't tell: my build - // with Sun C++ 4.0.1 never completes. -# define ACE_NEEDS_DEV_IO_CONVERSION -# elif (__SUNPRO_CC >= 0x420) -# if (__SUNPRO_CC >= 0x500) - // string.h and memory.h conflict for memchr definitions -# define ACE_LACKS_MEMORY_H - // If -compat=4 is turned on, the old 4.2 settings for iostreams are used, - // but the newer, explicit instantiation is used (above) -# if (__SUNPRO_CC_COMPAT >= 5) -# define ACE_HAS_TEMPLATE_TYPEDEFS -# define ACE_HAS_STANDARD_CPP_LIBRARY 1 -# define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 -# define ACE_HAS_THR_C_DEST -# endif /* __SUNPRO_CC_COMPAT >= 5 */ -# if defined (ACE_HAS_EXCEPTIONS) -# define ACE_HAS_NEW_NOTHROW -# else - // See /opt/SUNWspro_5.0/SC5.0/include/CC/stdcomp.h: -# define _RWSTD_NO_EXCEPTIONS 1 -# endif /* ! ACE_HAS_EXCEPTIONS */ -# elif (__SUNPRO_CC == 0x420) || (__SUNPRO_CC == 0x410) -# define ACE_LACKS_PLACEMENT_OPERATOR_DELETE -# endif /* __SUNPRO_CC >= 0x500 */ -# endif /* __SUNPRO_CC >= 0x420 */ - -# define ACE_CAST_CONST const -# define ACE_HAS_HI_RES_TIMER -# define ACE_HAS_SIG_C_FUNC /* Sun CC 5.0 needs this, 4.2 doesn't mind. */ -# define ACE_HAS_XPG4_MULTIBYTE_CHAR -# define ACE_LACKS_LINEBUFFERED_STREAMBUF -# define ACE_LACKS_SIGNED_CHAR - - // ACE_HAS_EXCEPTIONS precludes -noex in - // include/makeinclude/platform_macros.GNU. But beware, we have - // seen problems with exception handling on multiprocessor - // UltraSparcs: threaded executables core dump when threads exit. - // This problem does not seem to appear on single-processor UltraSparcs. - // And, it is solved with the application of patch - // 104631-02 "C++ 4.2: Jumbo Patch for C++ 4.2 on Solaris SPARC" - // to Sun C++ 4.2. - // To provide optimum performance, ACE_HAS_EXCEPTIONS is disabled by - // default. It can be enabled by adding "exceptions=1" to the "make" - // invocation. See include/makeinclude/platform_sunos5_sunc++.GNU - // for details. - -# if defined (ACE_HAS_EXCEPTIONS) - // If exceptions are enabled and we are using Sun/CC then - // throws an exception instead of returning 0. -# define ACE_NEW_THROWS_EXCEPTIONS -# endif /* ACE_HAS_EXCEPTIONS */ - - /* If you want to disable threading with Sun CC, remove -mt - from your CFLAGS, e.g., using make threads=0. */ - - -// Take advantage of Sun Studio 8 (Sun C++ 5.5) or better symbol -// visibility to generate improved shared library binaries. -# if (__SUNPRO_CC > 0x540) - -# if defined (ACE_HAS_CUSTOM_EXPORT_MACROS) && ACE_HAS_CUSTOM_EXPORT_MACROS == 0 -# undef ACE_HAS_CUSTOM_EXPORT_MACROS -# else -# ifndef ACE_HAS_CUSTOM_EXPORT_MACROS -# define ACE_HAS_CUSTOM_EXPORT_MACROS -# endif /* !ACE_HAS_CUSTOM_EXPORT_MACROS */ -# define ACE_Proper_Export_Flag __symbolic -# define ACE_Proper_Import_Flag __global - -# define ACE_EXPORT_SINGLETON_DECLARATION(T) template class ACE_Proper_Export_Flag T -# define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) template class ACE_Proper_Export_Flag SINGLETON_TYPE ; - -// # define ACE_IMPORT_SINGLETON_DECLARATION(T) extern template class T -// # define ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) extern template class SINGLETON_TYPE; - -# endif /* ACE_HAS_CUSTOM_EXPORT_MACROS == 0 */ -# endif /* __SUNPRO_CC > 0x540 (> Sun C++ 5.4) */ - -#elif defined (__GNUG__) - // config-g++-common.h undef's ACE_HAS_STRING_CLASS with -frepo, so - // this must appear before its #include. -# define ACE_HAS_STRING_CLASS - -# include "ace/config-g++-common.h" - -# define ACE_HAS_HI_RES_TIMER -# define ACE_HAS_XPG4_MULTIBYTE_CHAR - -# if !defined (ACE_MT_SAFE) || ACE_MT_SAFE != 0 - // ACE_MT_SAFE is #defined below, for all compilers. -# if !defined (_REENTRANT) - /* If you want to disable threading, comment out the following - line. Or, add -DACE_MT_SAFE=0 to your CFLAGS, e.g., using - make threads=0. */ -# define _REENTRANT -# endif /* _REENTRANT */ -# endif /* !ACE_MT_SAFE */ - -#elif defined (ghs) - -# if !defined (ACE_MT_SAFE) || ACE_MT_SAFE != 0 - // ACE_MT_SAFE is #defined below, for all compilers. -# if !defined (_REENTRANT) - /* If you want to disable threading, comment out the following - line. Or, add -DACE_MT_SAFE=0 to your CFLAGS, e.g., using - make threads=0. */ -# define _REENTRANT -# endif /* _REENTRANT */ -# endif /* !ACE_MT_SAFE */ - -# define ACE_CONFIG_INCLUDE_GHS_COMMON -# include "ace/config-ghs-common.h" - - // To avoid warning about inconsistent declaration between Sun's - // stdlib.h and Green Hills' ctype.h. -# include - - // IOStream_Test never halts with Green Hills 1.8.9. -# define ACE_LACKS_ACE_IOSTREAM - -#else /* ! __SUNPRO_CC && ! __GNUG__ && ! ghs */ -# ifdef __cplusplus /* Let it slide for C compilers. */ -# error unsupported compiler in ace/config-sunos5.5.h -# endif /* __cplusplus */ -#endif /* ! __SUNPRO_CC && ! __GNUG__ && ! ghs */ - -#if !defined (__ACE_INLINE__) -// @note If you have link problems with undefined inline template -// functions with Sun C++, be sure that the #define of __ACE_INLINE__ -// below is not commented out. -# define __ACE_INLINE__ -#endif /* ! __ACE_INLINE__ */ - -// Platform supports the POSIX regular expression library. -// @note Please comment out the ACE_HAS_REGEX #define if you -// have link problems with g++ or egcs on SunOS 5.5. -#define ACE_HAS_REGEX - -// Optimize ACE_Handle_Set for select(). -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT - -// select()'s timeval arg is not declared as const and may be modified -#define ACE_HAS_NONCONST_SELECT_TIMEVAL - -// Platform supports pread() and pwrite() -#define ACE_HAS_P_READ_WRITE -#define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS -#define ACE_HAS_UALARM -#define ACE_LACKS_UALARM_PROTOTYPE - -// Platform supports System V IPC (most versions of UNIX, but not Win32) -#define ACE_HAS_SYSV_IPC - -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES - -// Platform supports system configuration information. -#define ACE_HAS_SYS_SYSTEMINFO_H -#define ACE_HAS_SYSV_SYSINFO - -// Platform supports recvmsg and sendmsg. -#define ACE_HAS_MSG - -// Compiler/platform contains the file. -#define ACE_HAS_SYS_SYSCALL_H - -// Platform has POSIX terminal interface. -#define ACE_HAS_TERMIOS - -// Compiler/platform correctly calls init()/fini() for shared libraries. -#define ACE_HAS_AUTOMATIC_INIT_FINI - -// Platform supports POSIX O_NONBLOCK semantics. -#define ACE_HAS_POSIX_NONBLOCK - -// Compiler/platform has correctly prototyped header files. -#define ACE_HAS_CPLUSPLUS_HEADERS - -// Platform supports IP multicast -#define ACE_HAS_IP_MULTICAST - -// This setting was determined by running the autoconf tests. If it doesn't -// work uniformly, will need some tweaking, possibly based on other -// XPG feature-test macros. -#define ACE_HAS_CONST_CHAR_SWAB - -// Compiler/platform supports alloca() -// Although ACE does have alloca() on this compiler/platform combination, it is -// disabled by default since it can be dangerous. Uncomment the following line -// if you ACE to use it. -//#define ACE_HAS_ALLOCA - -// Compiler/platform has -#define ACE_HAS_ALLOCA_H - -// Platform contains . -#define ACE_HAS_POLL - -// Platform supports POSIX timers via timestruc_t. -#define ACE_HAS_POSIX_TIME - -// ACE_HAS_CLOCK_GETTIME requires linking with -lposix4. -#define ACE_HAS_CLOCK_GETTIME -#define ACE_HAS_CLOCK_SETTIME - -// Platform supports the /proc file system. -#define ACE_HAS_PROC_FS - -// Platform supports the prusage_t struct. -#define ACE_HAS_PRUSAGE_T -#define ACE_HAS_GETRUSAGE - -// Compiler/platform defines the sig_atomic_t typedef. -#define ACE_HAS_SIG_ATOMIC_T - -// Platform supports SVR4 extended signals. -#define ACE_HAS_SIGINFO_T -#define ACE_HAS_UCONTEXT_T - -// Compiler/platform provides the sockio.h file. -#define ACE_HAS_SYS_SOCKIO_H - -// Compiler supports the ssize_t typedef. -#define ACE_HAS_SSIZE_T - -// Platform supports STREAMS. -#define ACE_HAS_STREAMS - -// Platform supports STREAM pipes. -#define ACE_HAS_STREAM_PIPES - -// Compiler/platform supports struct strbuf. -#define ACE_HAS_STRBUF_T - -// Compiler/platform supports SVR4 dynamic linking semantics. -#define ACE_HAS_SVR4_DYNAMIC_LINKING - -// Compiler/platform supports SVR4 gettimeofday() prototype. -#define ACE_HAS_SVR4_GETTIMEOFDAY - -// Compiler/platform supports SVR4 ACE_TLI (in particular, T_GETNAME stuff)... -#define ACE_HAS_SVR4_TLI - -// Platform provides header. -#define ACE_HAS_SYS_FILIO_H - -#define ACE_HAS_STRSIGNAL - -// SunOS 5.5.x does not support mkstemp -#define ACE_LACKS_MKSTEMP -#define ACE_LACKS_SYS_SYSCTL_H - -#if !(defined(_XOPEN_SOURCE) && (_XOPEN_VERSION - 0 >= 4)) -# define ACE_HAS_CHARPTR_SHMDT -#endif - -// Platform has posix getpwnam_r -#if (defined (_POSIX_C_SOURCE) && _POSIX_C_SOURCE - 0 >= 199506L) || \ - defined(_POSIX_PTHREAD_SEMANTICS) -# define ACE_HAS_POSIX_GETPWNAM_R -#endif /* _POSIX_C_SOURCE || _POSIX_PTHREAD_SEMANTICS */ - -#if !defined (ACE_MT_SAFE) || (ACE_MT_SAFE == 1) -#if defined (_REENTRANT) || \ - (defined (_POSIX_C_SOURCE) && (_POSIX_C_SOURCE - 0 >= 199506L)) || \ - defined (_POSIX_PTHREAD_SEMANTICS) - // Compile using multi-thread libraries. -# define ACE_HAS_THREADS - -# if !defined (ACE_MT_SAFE) -# define ACE_MT_SAFE 1 -# endif /* ACE_MT_SAFE */ - - // Platform supports POSIX pthreads *and* Solaris threads, by - // default! If you only want to use POSIX pthreads, add - // -D_POSIX_PTHREAD_SEMANTICS to your CFLAGS. Or, #define it right - // here. See the Intro (3) man page for information on - // -D_POSIX_PTHREAD_SEMANTICS. -# if defined (_POSIX_PTHREAD_SEMANTICS) -# define ACE_LACKS_RWLOCK_T -# else -# define ACE_HAS_STHREADS -# endif /* ! _POSIX_PTHREAD_SEMANTICS */ - -# define ACE_HAS_PTHREADS - // . . . but only supports SCHED_OTHER scheduling policy -# define ACE_HAS_ONLY_SCHED_OTHER -# define ACE_HAS_SIGWAIT -# define ACE_HAS_SIGTIMEDWAIT -# define ACE_HAS_SIGSUSPEND -# define ACE_LACKS_PTHREAD_ATTR_SETSTACK - - // Compiler/platform has thread-specific storage -# define ACE_HAS_THREAD_SPECIFIC_STORAGE - - // Platform supports reentrant functions (i.e., all the POSIX *_r functions). -# define ACE_HAS_REENTRANT_FUNCTIONS - -# define ACE_NEEDS_LWP_PRIO_SET -# define ACE_HAS_THR_YIELD -# define ACE_LACKS_PTHREAD_YIELD -#endif /* _REENTRANT || _POSIX_C_SOURCE >= 199506L || \ - _POSIX_PTHREAD_SEMANTICS */ -#endif /* !ACE_MT_SAFE || ACE_MT_SAFE == 1 */ - -#define ACE_HAS_PRIOCNTL - -// Platform supports ACE_TLI timod STREAMS module. -#define ACE_HAS_TIMOD_H - -// Platform supports ACE_TLI tiuser header. -#define ACE_HAS_TIUSER_H - -// Platform provides ACE_TLI function prototypes. -#define ACE_HAS_TLI_PROTOTYPES - -// Platform has broken t_error() prototype. -#define ACE_HAS_BROKEN_T_ERROR - -// Platform supports ACE_TLI. -#define ACE_HAS_TLI - -#define ACE_HAS_GETPAGESIZE 1 - -#define ACE_HAS_IDTYPE_T - -#define ACE_HAS_GPERF -#define ACE_HAS_DIRENT - -#define ACE_LACKS_ISCTYPE -#define ACE_LACKS_ISBLANK - -#if defined (__SUNPRO_CC) -# define ACE_CC_NAME ACE_TEXT ("SunPro C++") -# define ACE_CC_MAJOR_VERSION (__SUNPRO_CC >> 8) -# define ACE_CC_MINOR_VERSION (__SUNPRO_CC & 0x00ff) -# define ACE_CC_BETA_VERSION (0) -#elif defined (__GNUG__) -# define ACE_CC_MAJOR_VERSION __GNUC__ -# define ACE_CC_MINOR_VERSION __GNUC_MINOR__ -# define ACE_CC_BETA_VERSION (0) -# if __GNUC_MINOR__ >= 90 -# define ACE_CC_NAME ACE_TEXT ("egcs") -# else -# define ACE_CC_NAME ACE_TEXT ("g++") -# endif /* __GNUC_MINOR__ */ -#endif /* __GNUG__ */ - -#if defined (i386) && (_FILE_OFFSET_BITS==32) -# define ACE_HAS_X86_STAT_MACROS -#endif /* i386 && _FILE_OFFSET_BITS==32 */ - -#define ACE_MALLOC_ALIGN ((size_t)8) -#define ACE_LACKS_SETREUID_PROTOTYPE -#define ACE_LACKS_SETREGID_PROTOTYPE - -// Solaris does indeed implement the inet_aton() function, but it is -// found in `libresolv.*'. It doesn't seem worth it to link another -// library just for that function. Just use the emulation in ACE that -// has been used for years. -#define ACE_LACKS_INET_ATON - -// Solaris doesn't have wcstoull -#define ACE_LACKS_WCSTOLL -#define ACE_LACKS_WCSTOULL - -#if defined (_LARGEFILE_SOURCE) || (_FILE_OFFSET_BITS==64) -#undef ACE_HAS_PROC_FS -#undef ACE_HAS_PRUSAGE_T -#endif /* (_LARGEFILE_SOURCE) || (_FILE_OFFSET_BITS==64) */ - -#if defined (_POSIX_PTHREAD_SEMANTICS) || (_FILE_OFFSET_BITS == 64) || (_POSIX_C_SOURCE - 0 >= 199506L) -# define ACE_HAS_3_PARAM_READDIR_R -#endif - -// Sum of the iov_len values can't be larger then SSIZE_MAX -#define ACE_HAS_SOCK_BUF_SIZE_MAX - -#define ACE_LACKS_SETENV -#define ACE_LACKS_UNSETENV - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_H */ diff --git a/externals/ace/config-sunos5.6.h b/externals/ace/config-sunos5.6.h deleted file mode 100644 index d100627a212..00000000000 --- a/externals/ace/config-sunos5.6.h +++ /dev/null @@ -1,126 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-sunos5.6.h 81935 2008-06-12 22:01:53Z jtc $ - -// The following configuration file is designed to work for SunOS 5.6 -// platforms using the SunC++ 4.x or g++ compilers. - -#ifndef ACE_CONFIG_H - -// ACE_CONFIG_H is defined by one of the following #included headers. - -// #include the SunOS 5.5 config file, then add SunOS 5.6 updates below. - -#include "ace/config-sunos5.5.h" - -#if (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE > 2) || \ - defined (__EXTENSIONS__) -// The asctime_r/ctime_r parameters change at POSIX.1c-1995 -# if (defined (_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199506L) -# define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R -# endif /* POSIX_C_SOURCE >= 199506L */ -# define ACE_HAS_SIGWAIT -// Hack 'cuz _POSIX_C_SOURCE > 2 and -DEXTENSIONS hides this. -# define ACE_LACKS_MADVISE_PROTOTYPE -#endif /* _POSIX_C_SOURCE > 2 || __EXTENSIONS__ */ - -// Support for the SunC++ 5.2 compiler. -// Do not undefine for compat mode < 5 -#if defined (__SUNPRO_CC) && __SUNPRO_CC > 0x510 -#if defined (__SUNPRO_CC_COMPAT) && (__SUNPRO_CC_COMPAT >= 5) -#ifdef ACE_LACKS_ACE_IOSTREAM -#undef ACE_LACKS_ACE_IOSTREAM -#endif /* ACE_LACKS_ACE_IOSTREAM */ -#endif /* defined (__SUNPRO_CC_COMPAT) && (__SUNPRO_CC_COMPAT >= 5) */ - -#ifndef ACE_LACKS_UNBUFFERED_STREAMBUF -#define ACE_LACKS_UNBUFFERED_STREAMBUF 1 -#endif /* ACE_LACKS_UNBUFFERED_STREAMBUF */ -#ifndef ACE_TEMPLATES_REQUIRE_SOURCE -#define ACE_TEMPLATES_REQUIRE_SOURCE 1 -#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ -#ifndef ACE_HAS_TEMPLATE_TYPEDEFS -#define ACE_HAS_TEMPLATE_TYPEDEFS 1 -#endif /* ACE_HAS_TEMPLATE_TYPEDEFS */ -// Forte 7 seems to botch this one... -#if __SUNPRO_CC == 0x540 -#undef ACE_HAS_TEMPLATE_TYPEDEFS -#endif -#ifndef ACE_HAS_THR_C_DEST -#define ACE_HAS_THR_C_DEST 1 -#endif /* ACE_HAS_THR_C_DEST */ -#ifndef ACE_HAS_THR_C_FUNC -#define ACE_HAS_THR_C_FUNC 1 -#endif /* ACE_HAS_THR_C_FUNC */ -#ifndef ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES 1 -#endif /* ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES */ -#ifndef ACE_HAS_SIG_C_FUNC -#define ACE_HAS_SIG_C_FUNC 1 -#endif /* ACE_HAS_SIG_C_FUNC */ -#ifndef ACE_HAS_STDCPP_STL_INCLUDES -#define ACE_HAS_STDCPP_STL_INCLUDES 1 -#endif /* ACE_HAS_STDCPP_STL_INCLUDES */ -#ifndef ACE_HAS_STRING_CLASS -#define ACE_HAS_STRING_CLASS 1 -#endif /* ACE_HAS_STRING_CLASS */ -#ifndef ACE_HAS_STANDARD_CPP_LIBRARY -#define ACE_HAS_STANDARD_CPP_LIBRARY 1 -#endif /* ACE_HAS_STANDARD_CPP_LIBRARY */ -#ifndef ACE_HAS_STDCPP_STL_INCLUDES -#define ACE_HAS_STDCPP_STL_INCLUDES 1 -#endif /* ACE_HAS_STDCPP_STL_INCLUDES */ -#ifndef ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB -#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 -#endif /* ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB */ -#ifndef ACE_LACKS_IOSTREAM_FX -#define ACE_LACKS_IOSTREAM_FX 1 -#endif /* ACE_LACKS_IOSTREAM_FX */ -#ifndef ACE_LACKS_LINEBUFFERED_STREAMBUF -#define ACE_LACKS_LINEBUFFERED_STREAMBUF 1 -#endif /* ACE_LACKS_LINEBUFFERED_STREAMBUF */ - -#endif /* defined (__SUNPRO_CC) && __SUNPRO_CC > 0x510 */ - -// SunOS 5.6 and above support mkstemp -#undef ACE_LACKS_MKSTEMP - - -// SunOS 5.6 has AIO calls. -#if !defined (ACE_HAS_AIO_CALLS) -#define ACE_HAS_AIO_CALLS -#endif /* ACE_HAS_AIO_CALLS */ - -#if !defined (ACE_HAS_POSIX_REALTIME_SIGNALS) -#define ACE_HAS_POSIX_REALTIME_SIGNALS -#endif /* ACE_HAS_POSIX_REALTIME_SIGNALS */ - -#if !defined (ACE_HAS_POSIX_MESSAGE_PASSING) -#define ACE_HAS_POSIX_MESSAGE_PASSING -#endif /* ACE_HAS_POSIX_MESSAGE_PASSING */ - -#if !defined (ACE_HAS_POSIX_SEM) -#define ACE_HAS_POSIX_SEM -#endif /* ACE_HAS_POSIX_SEM */ - -// Sunos 5.6's aio_* with RT signals is broken. -#if !defined (ACE_POSIX_AIOCB_PROACTOR) -#define ACE_POSIX_AIOCB_PROACTOR -#endif /* ACE_POSIX_AIOCB_PROACTOR */ - -// SunOS 5.6 has a buggy select -#define ACE_HAS_LIMITED_SELECT - -// SunOS 5.6 introduced shm_open, but need to turn on POSIX.1b or higher -// to pick it up. -#if defined (_POSIX_C_SOURCE) && (_POSIX_C_SOURCE > 2) -# define ACE_HAS_SHM_OPEN -#else -# undef ACE_HAS_SHM_OPEN -#endif /* _POSIX_C_SOURCE > 2 */ - -// The struct msghdr is conditional on SunOS 5.6 based on _XPG4_2 -#if defined(_XPG4_2) -# define ACE_HAS_4_4BSD_SENDMSG_RECVMSG -#endif /* _XPG4_2 */ - -#endif /* ACE_CONFIG_H */ diff --git a/externals/ace/config-sunos5.7.h b/externals/ace/config-sunos5.7.h deleted file mode 100644 index 60e1d993a13..00000000000 --- a/externals/ace/config-sunos5.7.h +++ /dev/null @@ -1,78 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-sunos5.7.h 80826 2008-03-04 14:51:23Z wotte $ - -// The following configuration file is designed to work for SunOS 5.7 -// (Solaris 7) platforms using the SunC++ 4.x, 5.x, or g++ compilers. - -#ifndef ACE_CONFIG_H - -// ACE_CONFIG_H is defined by one of the following #included headers. - -// #include the SunOS 5.6 config file, then add SunOS 5.7 updates below. - -#include "ace/config-sunos5.6.h" - -// This may be true for earlier Solaris versions, but I can only verify -// it for Solaris 7 and later. -#define ACE_HAS_VFWPRINTF -#if defined (ACE_HAS_SHM_OPEN) -# define ACE_SHM_OPEN_REQUIRES_ONE_SLASH -#endif - -// Sun began distributing with SunOS 5.7 -#define ACE_HAS_SYS_LOADAVG_H - -// SunOS 5.7 has getloadavg() -#undef ACE_LACKS_GETLOADAVG - -#if defined (ghs) - // SunOS 5.7's /usr/include/sys/procfs_isa.h needs uint64_t, - // but /usr/include/sys/int_types.h doesn't #define it because - // _NO_LONGLONG is # -# undef ACE_HAS_PROC_FS -# undef ACE_HAS_PRUSAGE_T - -#elif defined (__SUNPRO_CC) && (__SUNPRO_CC <= 0x530) - // Wide character methods are in std:: when using SunCC 5.3 -# define ACE_WCHAR_IN_STD_NAMESPACE -#endif /* __GNUG__ || ghs */ - -// SunOS 5.7 supports SCHED_FIFO and SCHED_RR, as well as SCHED_OTHER. -#undef ACE_HAS_ONLY_SCHED_OTHER - -// SunOS 5.7 gets this right . . . -#undef ACE_HAS_BROKEN_T_ERROR - -// And doesn't need to set LWP priorities, as shown by -// performance-tests/Misc/preempt. -#undef ACE_NEEDS_LWP_PRIO_SET - -// SunOS 5.7 can support Real-Time Signals and POSIX4 AIO operations -// are supported. - -#if !defined (ACE_HAS_AIO_CALLS) -#define ACE_HAS_AIO_CALLS -#endif /* !ACE_HAS_AIO_CALLS */ - -#ifdef ACE_HAS_LIMITED_SELECT -#undef ACE_HAS_LIMITED_SELECT -#endif /* ACE_HAS_LIMITED_SELECT */ - -// SunOS 5.7 has socklen_t -#define ACE_HAS_SOCKLEN_T - -#if defined (__sparcv9) -#define _LP64 -#define ACE_SIZEOF_LONG 8 /* Needed to circumvent compiler bug #4294969 */ -#endif /* __sparcv9 */ - -#if (defined(_XOPEN_SOURCE) && (_XOPEN_VERSION - 0 == 4)) /* XPG4 or XPG4v2 */ -// 2 parameter wcstok() -#else /* XPG4 or XPG4v2 */ -# define ACE_HAS_3_PARAM_WCSTOK -#endif - -// Solaris 7 started to support /dev/poll -#define ACE_HAS_DEV_POLL - -#endif /* ACE_CONFIG_H */ diff --git a/externals/ace/config-sunos5.8.h b/externals/ace/config-sunos5.8.h deleted file mode 100644 index eb83e91490b..00000000000 --- a/externals/ace/config-sunos5.8.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-sunos5.8.h 80826 2008-03-04 14:51:23Z wotte $ - -// The following configuration file is designed to work for SunOS 5.8 -// (Solaris 8) platforms using the SunC++ 4.x, 5.x, 6.x, or g++ compilers. - -#ifndef ACE_CONFIG_H - -// ACE_CONFIG_H is defined by one of the following #included headers. - -// #include the SunOS 5.7 config, then add any SunOS 5.8 updates below. -#include "ace/config-sunos5.7.h" - -#undef ACE_WCHAR_IN_STD_NAMESPACE - -// This may be true for versions prior to Solaris 8 as well, but I don't -// have any to try it on. -#if !defined (ACE_HAS_TIMEZONE) -# define ACE_HAS_TIMEZONE -#endif - -// The range of thread priorities for 5.8 differs from 5.7 in the -// minimum priority for the SCHED_OTHER policy (i.e., -// ACE_THR_PRI_OTHER_MIN) -# define ACE_THR_PRI_OTHER_MIN (long) -20 - -# if defined (_POSIX_PTHREAD_SEMANTICS) -# ifdef ACE_LACKS_RWLOCK_T -# undef ACE_LACKS_RWLOCK_T -# endif /* ACE_LACKS_RWLOCK_T */ -# endif /* _POSIX_PTHREAD_SEMANTICS */ - -// This is no longer the case for Sun 5.9 onwards -# undef ACE_HAS_X86_STAT_MACROS - -// gethostbyaddr does not handle IPv6-mapped-IPv4 addresses -#define ACE_HAS_BROKEN_GETHOSTBYADDR_V4MAPPED - -#endif /* ACE_CONFIG_H */ diff --git a/externals/ace/config-sunos5.9.h b/externals/ace/config-sunos5.9.h deleted file mode 100644 index b8d09447eb2..00000000000 --- a/externals/ace/config-sunos5.9.h +++ /dev/null @@ -1,18 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-sunos5.9.h 84213 2009-01-22 15:45:13Z johnnyw $ - -// The following configuration file is designed to work for SunOS 5.9 -// (Solaris 9) platforms using the SunC++ 5.x (Forte 6 and 7), or g++ -// compilers. - -#ifndef ACE_CONFIG_H - -// ACE_CONFIG_H is defined by one of the following #included headers. - -// #include the SunOS 5.8 config, then add any SunOS 5.9 updates below. -#include "ace/config-sunos5.8.h" - -#define ACE_HAS_SENDFILE 1 -#define ACE_LACKS_THR_CONCURRENCY_FUNCS - -#endif /* ACE_CONFIG_H */ diff --git a/externals/ace/config-tandem-nsk-mips-v2.h b/externals/ace/config-tandem-nsk-mips-v2.h deleted file mode 100644 index 61747272087..00000000000 --- a/externals/ace/config-tandem-nsk-mips-v2.h +++ /dev/null @@ -1,394 +0,0 @@ -// -*- C++ -*- -// -// $Id: config-tandem-nsk-mips-v2.h 87167 2009-10-19 19:33:53Z olli $ - -#ifndef ACE_CONFIG_NSK_H -#define ACE_CONFIG_NSK_H - -#include /**/ "ace/pre.h" - -// The following configuration file contains defines for Tandem NSK -// platform, MIPS processor, version 2 C++ compiler. - - -//========================================================================= -// Tandem NSK specific parts -//========================================================================= - - -// Disable pthread renaming of symbols such as "open" and "close" -#define _CMA_NOWRAPPERS_ 1 - -// Get Handle_Set.cpp to generate correct bit operations for NSK platform -#define ACE_TANDEM_NSK_BIT_ORDER - -// Use facilities provided by T1248 version of pthreads. -// (If not defined, will use old version of pthreads.) -#define ACE_TANDEM_T1248_PTHREADS - -// Use all available T1248 thread aware wrapper functions for providing -// non-blocking I/O. -// [@note this causes a significant performance degradation] -//#define ACE_TANDEM_T1248_PTHREADS_ALL_IO_WRAPPERS - - -// Need this include here because some symbols defined by pthreads -// (e.g. timespec_t) are needed before spthread.h is normally included -// by ACE -#ifdef ACE_TANDEM_T1248_PTHREADS -#include -#else -#include "pthread.h" -#include "dce/cma_dispatch_coop.h" -#endif - -// The following #defines are hacks to get around things -// that seem to be missing or different in Tandem land -#define NSIG 32 // missing from Signal.h - // note: on nsk TNS/R there is room in - // sigset_t for 128 signals but those - // above 31 are not valid. -#define MAXNAMLEN 248 // missing from dirent.h -#define ERRMAX 4218 // from errno.h - -// Following seems to be missing from G06.20 version of standard -// pthreads includes (it appeared in older version of standard pthreads) -// (SCHED_FIFO (aka cma_c_sched_fifo) used in Dynamic_Priority_Test) -#ifdef ACE_TANDEM_T1248_PTHREADS -typedef enum CMA_T_SCHED_POLICY { - cma_c_sched_fifo = 0, - cma_c_sched_rr = 1, - cma_c_sched_throughput = 2, - cma_c_sched_background = 3, - cma_c_sched_ada_low = 4 - } cma_t_sched_policy; -#endif - -// T1248 doesn't define these constants. They're defined in spt/cma.h -// (formerly dce/cma.h), but this header is not included or provided -// by T1248 G07-AAL. -#define cma_c_prio_fifo_min 16 -#define cma_c_prio_fifo_mid 24 -#define cma_c_prio_fifo_max 31 -#define cma_c_prio_rr_min 16 -#define cma_c_prio_rr_mid 24 -#define cma_c_prio_rr_max 31 -#define cma_c_prio_through_min 8 -#define cma_c_prio_through_mid 12 -#define cma_c_prio_through_max 15 -#define cma_c_prio_back_min 1 -#define cma_c_prio_back_mid 4 -#define cma_c_prio_back_max 7 - -// Enable NSK Pluggable Protocols -#define TAO_HAS_NSKPW 1 -#define TAO_HAS_NSKFS 1 - -//========================================================================= -// Platform specific parts -//========================================================================= - -// Platform lacks getpwnam_r() methods (e.g., SGI 6.2). -#define ACE_LACKS_PWD_REENTRANT_FUNCTIONS - -// Platform/compiler lacks {get,set}rlimit() function -#define ACE_LACKS_RLIMIT - -// The platform doesn't have mmap(2) -#define ACE_LACKS_MMAP - -// Platform lacks streambuf "linebuffered ()". [C++ iostream] -#define ACE_LACKS_LINEBUFFERED_STREAMBUF - -// Platform supports recvmsg and sendmsg -#define ACE_HAS_MSG - -// Platform defines ACE_HAS_MSG, but lacks msg_accrights{,len}. -#define ACE_LACKS_MSG_ACCRIGHTS - -// Platform supports sigsuspend() -#define ACE_HAS_SIGSUSPEND - -// Platform/compiler has the sigwait(2) prototype -#define ACE_HAS_SIGWAIT - -// Compiler/platform defines the sig_atomic_t typedef -#define ACE_HAS_SIG_ATOMIC_T - -// OS/compiler uses size_t * rather than int * for socket lengths -#define ACE_HAS_SIZET_SOCKET_LEN - -// OS/compiler uses void * arg 4 setsockopt() rather than const char * -#define ACE_HAS_VOIDPTR_SOCKOPT - -// The platform doesn't have mprotect(2) -#define ACE_LACKS_MPROTECT - -// Platform lacks msync() -#define ACE_LACKS_MSYNC - -// Platform does not support reentrant netdb functions (getprotobyname_r, -// getprotobynumber_r, gethostbyaddr_r, gethostbyname_r, getservbyname_r). -#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS Platform does not support - -// Platform lacks madvise() -#define ACE_LACKS_MADVISE - -// Platform lacks pri_t -#define ACE_LACKS_PRI_T - -// Platform lacks a working sbrk() -#define ACE_LACKS_SBRK - -// Platform doesn't have syscall() prototype -#define ACE_LACKS_SYSCALL - -// Platform lacks the inet_aton() function. -#define ACE_LACKS_INET_ATON - -// Compiler/platform has Dirent iterator functions -#define ACE_HAS_DIRENT - -// Platform uses ACE_HAS_DIRENT but does not have readdir_r() -#define ACE_LACKS_READDIR_R - -// Platform supports getpagesize() call (otherwise, -// ACE_PAGE_SIZE must be defined) -#define ACE_HAS_GETPAGESIZE - -// Platform supports IP multicast -#define ACE_HAS_IP_MULTICAST - -// Platform's select() uses non-const timeval* -#define ACE_HAS_NONCONST_SELECT_TIMEVAL - -// Platform supports POSIX O_NONBLOCK semantics -#define ACE_HAS_POSIX_NONBLOCK - -// Platform lacks named POSIX semaphores -#define ACE_LACKS_NAMED_POSIX_SEM - -// Platform has support for multi-byte character support compliant -// with the XPG4 Worldwide Portability Interface wide-character -// classification. -#define ACE_HAS_XPG4_MULTIBYTE_CHAR - -// No wcsstr function available for this compiler -#define ACE_LACKS_WCSSTR - -// No wctype.h available for this compiler -#define ACE_LACKS_WCTYPE_H - -// Platform supports the POSIX regular expression library. -// [Note Tandem NSK platform does have regular expresson support but it -// does not follow the assumptions made by ACE. To use it would need -// to make some ACE modifications.] -//#define ACE_HAS_REGEX - -// Platform doesn't have truncate() -#define ACE_LACKS_TRUNCATE - -// Platform lacks readers/writer locks. -#define ACE_LACKS_RWLOCK_T - -// Compiler's 'new' throws exception on failure (ANSI C++ behavior). -#define ACE_NEW_THROWS_EXCEPTIONS - -// Optimize ACE_Handle_Set::count_bits for select() operations (common -// case) -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT - -// Platform lacks setreuid() -#define ACE_LACKS_SETREUID - -// Platform lacks setregid() -#define ACE_LACKS_SETREGID - -// Compile using multi-thread libraries -#define ACE_MT_SAFE 1 - - - -// Platform supports System V IPC -#define ACE_HAS_SYSV_IPC - -#define ACE_LACKS_SO_SNDBUF -#define ACE_LACKS_SO_RCVBUF - -// Platform lacks the socketpair() call -#define ACE_LACKS_SOCKETPAIR - -// Platform limits the maximum socket message size. -#define ACE_HAS_SOCK_BUF_SIZE_MAX - -// hrtime_t is a basic type that doesn't require ACE_U64_TO_U32 conversion -#define ACE_HRTIME_T_IS_BASIC_TYPE - -// printf format specifiers for 64 bit integers -# define ACE_UINT64_FORMAT_SPECIFIER_ASCII "%Ld" -# define ACE_INT64_FORMAT_SPECIFIER_ASCII "%Ld" - -//========================================================================= -// Threads specific parts -//========================================================================= - -// Platform supports threads -#define ACE_HAS_THREADS - -// Platform supports POSIX Pthreads, of one form or another. This -// macro says the platform has a pthreads variety - should also define -// one of the below to say which one. Also may need some -// ACE_HAS_... thing for extensions. -#define ACE_HAS_PTHREADS - -// Standard pthreads supports only SCHED_FIFO -#define ACE_HAS_ONLY_SCHED_FIFO - -// Compiler/platform has thread-specific storage -#define ACE_HAS_THREAD_SPECIFIC_STORAGE - -// Platform has no implementation of pthread_condattr_setpshared(), -// even though it supports pthreads! -#define ACE_LACKS_CONDATTR_PSHARED - -// pthread_cond_timedwait does *not* reset the time argument when the -// lock is acquired. -#define ACE_LACKS_COND_TIMEDWAIT_RESET - -// Platform lacks pthread_attr_setsched() -#define ACE_LACKS_SETSCHED - -// Platform has pthread_mutexattr_setkind_np(). -#define ACE_HAS_PTHREAD_MUTEXATTR_SETKIND_NP - -// Platform lacks pthread_mutexattr_setpshared(). -#define ACE_LACKS_MUTEXATTR_PSHARED - -// Platform lacks pthread_attr_setscope() -#define ACE_LACKS_THREAD_PROCESS_SCOPING - -// Platform lacks pthread_attr_setstackaddr -#define ACE_LACKS_PTHREAD_ATTR_SETSTACKADDR - -// Defining ACE_HAS_UCONTEXT_T since G06.21 version of spthreads has -// a definition for it. -#ifdef ACE_TANDEM_T1248_PTHREADS -#define ACE_HAS_UCONTEXT_T -#endif - -#define ACE_LACKS_FD_MASK - -//========================================================================= -// Include file characteristics -//========================================================================= - -// Compiler/platform contains the file. -#define ACE_HAS_SYS_SYSCALL_H - -// Platform lacks malloc.h -#define ACE_LACKS_MALLOC_H - -// Platform lacks the siginfo.h include file -#define ACE_LACKS_SIGINFO_H - -// Platform doesn't define struct strrecvfd. -#define ACE_LACKS_STRRECVFD - -// Platform lacks the ucontext.h file -#define ACE_LACKS_UCONTEXT_H - -// Prototypes for both signal() and struct sigaction are consistent. -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES - -// Platform supports the POSIX struct timespec type -#define ACE_HAS_POSIX_TIME - -// Platform/compiler supports timezone * as second parameter to gettimeofday() -#define ACE_HAS_TIMEZONE_GETTIMEOFDAY - -// Platform has (which contains bzero() prototype) -#define ACE_HAS_STRINGS 1 - - -// OS/compiler omits the const from the iovec parameter in the -// writev() prototype. -#define ACE_HAS_NONCONST_WRITEV - -// Platform lacks -#define ACE_LACKS_STDINT_H - -// Platform lacks -#define ACE_LACKS_INTTYPES_H - -// Platform lacks -#define ACE_LACKS_SYS_SELECT_H - -// Platform lacks -#define ACE_LACKS_DLFCN_H - -// Platform lacks -#define ACE_LACKS_SEMAPHORE_H - -// Platform lacks -#define ACE_LACKS_POLL_H - -//========================================================================= -// Compiler specific parts -//========================================================================= - -// Compiler supports C++ exception handling -#define ACE_HAS_EXCEPTIONS - -// Compiler/platform has correctly prototyped header files -#define ACE_HAS_CPLUSPLUS_HEADERS - -// Compiler/platform does not support the unsigned long long datatype. -#define ACE_LACKS_LONGLONG_T - -// Compiler supports the ssize_t typedef -#define ACE_HAS_SSIZE_T - -// Platform/compiler supports Standard C++ Library -#define ACE_HAS_STANDARD_CPP_LIBRARY 0 - -// Compiler's template mechanism must see source code (i.e., -// .cpp files). -#define ACE_TEMPLATES_REQUIRE_SOURCE - -// Compiler implements templates that support typedefs inside -// of classes used as formal arguments to a template class. -#define ACE_HAS_TEMPLATE_TYPEDEFS - -// Platform has its standard c++ library in the namespace std. -#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 - -// Compiler doesn't support static data member templates -#define ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES - -// Platform lacks "signed char" type (broken!) -// Following will not be needed if use standard c library (G06.20 and later) -#define ACE_LACKS_SIGNED_CHAR - -//========================================================================= -// Build options -//========================================================================= - -// Disable the inclusion of RCS ids in the generated code. -#define ACE_USE_RCSID 0 - -// For debugging problems in os calls (but this doesn't work too well -// since output is not interleaved properly with output from ACE_TRACE -//# define ACE_OS_TRACE(X) ::printf(X) - -// Uncomment the following if timed message blocks are needed (e.g. -// for Dynamic_Priority_Test. Otherwise leave this disabled because -// enabling it adds overhead to message blocks and timed message blocks -// are "rarely used." -//#define ACE_HAS_TIMED_MESSAGE_BLOCKS - -// Uncomment the following if tokens library is needed. -//#define ACE_HAS_TOKENS_LIBRARY - -#include /**/ "ace/post.h" - -#endif /* ACE_CONFIG_NSK_H */ diff --git a/externals/ace/config-tandem-nsk-mips-v3.h b/externals/ace/config-tandem-nsk-mips-v3.h deleted file mode 100644 index e6c05a890b1..00000000000 --- a/externals/ace/config-tandem-nsk-mips-v3.h +++ /dev/null @@ -1,464 +0,0 @@ -// -*- C++ -*- -// -// $Id: config-tandem-nsk-mips-v3.h 87167 2009-10-19 19:33:53Z olli $ - - -#ifndef ACE_CONFIG_NSK_H -#define ACE_CONFIG_NSK_H - -#include /**/ "ace/pre.h" - -// The following configuration file contains defines for Tandem NSK -// platform, MIPS processor, version 3 C++ compiler. - - -//========================================================================= -// Tandem NSK specific parts -//========================================================================= - - -// Disable pthread renaming of symbols such as "open" and "close" -#define _CMA_NOWRAPPERS_ 1 - -// Get Handle_Set.cpp to generate correct bit operations for NSK platform -#define ACE_TANDEM_NSK_BIT_ORDER - -// Use facilities provided by T1248 version of pthreads. -// (If not defined, will use old version of pthreads.) -#define ACE_TANDEM_T1248_PTHREADS - -// Use all available T1248 thread aware wrapper functions for providing -// non-blocking I/O. -// [Note: this causes a significant performance degradation] -//#define ACE_TANDEM_T1248_PTHREADS_ALL_IO_WRAPPERS - - -// Need this include here because some symbols defined by pthreads -// (e.g. timespec_t) are needed before spthread.h is normally included -// by ACE -#ifdef ACE_TANDEM_T1248_PTHREADS -#include -#else -#include "pthread.h" -#include "dce/cma_dispatch_coop.h" -#endif - -// The following #defines are hacks to get around things -// that seem to be missing or different in Tandem land -#define NSIG 32 // missing from Signal.h - // note: on nsk TNS/R there is room in - // sigset_t for 128 signals but those - // above 31 are not valid. -#define MAXNAMLEN 248 // missing from dirent.h -#define ERRMAX 4218 // from errno.h - -// Following seems to be missing from G06.20 version of standard -// pthreads includes (it appeared in older version of standard pthreads) -// (SCHED_FIFO (aka cma_c_sched_fifo) used in Dynamic_Priority_Test) -#ifdef ACE_TANDEM_T1248_PTHREADS -typedef enum CMA_T_SCHED_POLICY { - cma_c_sched_fifo = 0, - cma_c_sched_rr = 1, - cma_c_sched_throughput = 2, - cma_c_sched_background = 3, - cma_c_sched_ada_low = 4 - } cma_t_sched_policy; -#endif - -// T1248 doesn't define these constants. They're defined in spt/cma.h -// (formerly dce/cma.h), but this header is not included or provided -// by T1248 G07-AAL. -#define cma_c_prio_fifo_min 16 -#define cma_c_prio_fifo_mid 24 -#define cma_c_prio_fifo_max 31 -#define cma_c_prio_rr_min 16 -#define cma_c_prio_rr_mid 24 -#define cma_c_prio_rr_max 31 -#define cma_c_prio_through_min 8 -#define cma_c_prio_through_mid 12 -#define cma_c_prio_through_max 15 -#define cma_c_prio_back_min 1 -#define cma_c_prio_back_mid 4 -#define cma_c_prio_back_max 7 - -// Enable NSK Pluggable Protocols -#define TAO_HAS_NSKPW 1 -#define TAO_HAS_NSKFS 1 - -//========================================================================= -// Platform specific parts -//========================================================================= - -// Platform lacks getpwnam_r() methods (e.g., SGI 6.2). -#define ACE_LACKS_PWD_REENTRANT_FUNCTIONS - -// Platform/compiler lacks {get,set}rlimit() function -#define ACE_LACKS_RLIMIT - -// The platform doesn't have mmap(2) -#define ACE_LACKS_MMAP - -// Platform lacks streambuf "linebuffered ()". [C++ iostream] -#define ACE_LACKS_LINEBUFFERED_STREAMBUF - -// Platform supports recvmsg and sendmsg -#define ACE_HAS_MSG - -// Platform defines ACE_HAS_MSG, but lacks msg_accrights{,len}. -#define ACE_LACKS_MSG_ACCRIGHTS - -// Platform supports sigsuspend() -#define ACE_HAS_SIGSUSPEND - -// Platform/compiler has the sigwait(2) prototype -#define ACE_HAS_SIGWAIT - -// Compiler/platform defines the sig_atomic_t typedef -#define ACE_HAS_SIG_ATOMIC_T - -// OS/compiler uses size_t * rather than int * for socket lengths -#define ACE_HAS_SIZET_SOCKET_LEN - -// OS/compiler uses void * arg 4 setsockopt() rather than const char * -#define ACE_HAS_VOIDPTR_SOCKOPT - -// The platform doesn't have mprotect(2) -#define ACE_LACKS_MPROTECT - -// Platform lacks msync() -#define ACE_LACKS_MSYNC - -// Platform does not support reentrant netdb functions (getprotobyname_r, -// getprotobynumber_r, gethostbyaddr_r, gethostbyname_r, getservbyname_r). -#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS Platform does not support - -// Platform lacks madvise() -#define ACE_LACKS_MADVISE - -// Platform lacks pri_t -#define ACE_LACKS_PRI_T - -// Platform lacks a working sbrk() -#define ACE_LACKS_SBRK - -// Platform doesn't have syscall() prototype -#define ACE_LACKS_SYSCALL - -// Platform lacks the inet_aton() function. -#define ACE_LACKS_INET_ATON - -// Compiler/platform has Dirent iterator functions -#define ACE_HAS_DIRENT - -// Platform uses ACE_HAS_DIRENT but does not have readdir_r() -#define ACE_LACKS_READDIR_R - -// Platform supports getpagesize() call (otherwise, -// ACE_PAGE_SIZE must be defined) -#define ACE_HAS_GETPAGESIZE - -// Platform supports IP multicast -#define ACE_HAS_IP_MULTICAST - -// Platform's select() uses non-const timeval* -#define ACE_HAS_NONCONST_SELECT_TIMEVAL - -// Platform supports POSIX O_NONBLOCK semantics -#define ACE_HAS_POSIX_NONBLOCK - -// Platform lacks named POSIX semaphores -#define ACE_LACKS_NAMED_POSIX_SEM - -// Platform has support for multi-byte character support compliant -// with the XPG4 Worldwide Portability Interface wide-character -// classification. -#define ACE_HAS_XPG4_MULTIBYTE_CHAR - -// No wcsstr function available for this compiler -#define ACE_LACKS_WCSSTR - -// No wctype.h available for this compiler -#define ACE_LACKS_WCTYPE_H - -// Platform supports the POSIX regular expression library. -// [Note Tandem NSK platform does have regular expresson support but it -// does not follow the assumptions made by ACE. To use it would need -// to make some ACE modifications.] -//#define ACE_HAS_REGEX - -// Platform doesn't have truncate() -#define ACE_LACKS_TRUNCATE - -// Platform lacks readers/writer locks. -#define ACE_LACKS_RWLOCK_T - -// Compiler's 'new' throws exception on failure (ANSI C++ behavior). -#define ACE_NEW_THROWS_EXCEPTIONS - -// Optimize ACE_Handle_Set::count_bits for select() operations (common -// case) -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT - -// Platform lacks setreuid() -#define ACE_LACKS_SETREUID - -// Platform lacks setregid() -#define ACE_LACKS_SETREGID - -// Compile using multi-thread libraries -#define ACE_MT_SAFE 1 - - - -// Platform supports System V IPC -#define ACE_HAS_SYSV_IPC - -#define ACE_LACKS_SO_SNDBUF -#define ACE_LACKS_SO_RCVBUF - -// Platform lacks the socketpair() call -#define ACE_LACKS_SOCKETPAIR - -// Platform limits the maximum socket message size. -#define ACE_HAS_SOCK_BUF_SIZE_MAX - -// hrtime_t is a basic type that doesn't require ACE_U64_TO_U32 conversion -#define ACE_HRTIME_T_IS_BASIC_TYPE - -// printf format specifiers for 64 bit integers -# define ACE_UINT64_FORMAT_SPECIFIER_ASCII "%Ld" -# define ACE_INT64_FORMAT_SPECIFIER_ASCII "%Ld" - -// Use larger default buffer size for ease of interoperability -#define ACE_DEFAULT_CDR_BUFSIZE 4096 - -// Size of a wchar -#define ACE_SIZEOF_WCHAR 2 - -// Platform lacks time typedefs -#define ACE_LACKS_SUSECONDS_T -#define ACE_LACKS_USECONDS_T - -// Platform lacks setegid() and seteuid() -#define ACE_LACKS_SETEGID -#define ACE_LACKS_SETEUID - -// Platform lacks vsnprintf() -#define ACE_LACKS_VSNPRINTF - -// Platform lacks log2() -#define ACE_LACKS_LOG2 - -// Platform lacks alphasort() -#define ACE_LACKS_ALPHASORT - -#define ACE_LACKS_FD_MASK -#define ACE_LACKS_NFDBITS - -//========================================================================= -// Threads specific parts -//========================================================================= - -// Platform supports threads -#define ACE_HAS_THREADS - -// Platform supports POSIX Pthreads, of one form or another. This -// macro says the platform has a pthreads variety - should also define -// one of the below to say which one. Also may need some -// ACE_HAS_... thing for extensions. -#define ACE_HAS_PTHREADS - -// Standard pthreads supports only SCHED_FIFO -#define ACE_HAS_ONLY_SCHED_FIFO - -// Compiler/platform has thread-specific storage -#define ACE_HAS_THREAD_SPECIFIC_STORAGE - -// Platform has no implementation of pthread_condattr_setpshared(), -// even though it supports pthreads! -#define ACE_LACKS_CONDATTR_PSHARED - -// pthread_cond_timedwait does *not* reset the time argument when the -// lock is acquired. -#define ACE_LACKS_COND_TIMEDWAIT_RESET - -// Platform lacks pthread_attr_setsched() -#define ACE_LACKS_SETSCHED - -// Platform has pthread_getschedparam and pthread_setschedparam -// even when ACE_LACKS_SETSCHED is defined. -#define ACE_HAS_PTHREAD_SCHEDPARAM - -// Platform has pthread_mutexattr_setkind_np(). -#define ACE_HAS_PTHREAD_MUTEXATTR_SETKIND_NP - -// Platform lacks pthread_mutexattr_setpshared(). -#define ACE_LACKS_MUTEXATTR_PSHARED - -// Platform lacks pthread_attr_setscope() -#define ACE_LACKS_THREAD_PROCESS_SCOPING - -// Platform lacks pthread_attr_setstackaddr -#define ACE_LACKS_PTHREAD_ATTR_SETSTACKADDR - -// Platform lacks pthread_attr_setstack -#define ACE_LACKS_PTHREAD_ATTR_SETSTACK - -// Defining ACE_HAS_UCONTEXT_T since G06.21 version of spthreads has -// a definition for it. -#ifdef ACE_TANDEM_T1248_PTHREADS -#define ACE_HAS_UCONTEXT_T -#endif - -//========================================================================= -// Include file characteristics -//========================================================================= - -// Compiler/platform contains the file. -#define ACE_HAS_SYS_SYSCALL_H - -// Platform lacks malloc.h -#define ACE_LACKS_MALLOC_H - -// Platform lacks the siginfo.h include file -#define ACE_LACKS_SIGINFO_H - -// Platform doesn't define struct strrecvfd. -#define ACE_LACKS_STRRECVFD - -// Platform lacks the ucontext.h file -#define ACE_LACKS_UCONTEXT_H - -// Prototypes for both signal() and struct sigaction are consistent. -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES - -// Platform supports the POSIX struct timespec type -#define ACE_HAS_POSIX_TIME - -// Platform/compiler supports timezone * as second parameter to gettimeofday() -#define ACE_HAS_TIMEZONE_GETTIMEOFDAY - -// Platform has (which contains bzero() prototype) -#define ACE_HAS_STRINGS 1 - - -// OS/compiler omits the const from the iovec parameter in the -// writev() prototype. -#define ACE_HAS_NONCONST_WRITEV - -// Platform lacks -#define ACE_LACKS_STDINT_H - -// Platform lacks -#define ACE_LACKS_INTTYPES_H - -// Platform lacks -#define ACE_LACKS_SYS_SELECT_H - -// Platform lacks -#define ACE_LACKS_DLFCN_H - -// Platform lacks -#define ACE_LACKS_SEMAPHORE_H - -// Platform lacks -#define ACE_LACKS_POLL_H - -// Platform lacks -#define ACE_LACKS_SYS_SYSCTL_H - -//========================================================================= -// Compiler specific parts -//========================================================================= - -// Compiler supports C++ exception handling -#define ACE_HAS_EXCEPTIONS 1 - -// Compiler/platform has correctly prototyped header files -#define ACE_HAS_CPLUSPLUS_HEADERS - -// Compiler/platform does not support the unsigned long long datatype. -#define ACE_LACKS_UNSIGNEDLONGLONG_T - -// Compiler supports the ssize_t typedef -#define ACE_HAS_SSIZE_T - -// Platform/compiler supports Standard C++ Library -#define ACE_HAS_STANDARD_CPP_LIBRARY 1 - -// Compiler's template mechanism must see source code (i.e., -// .cpp files). -#define ACE_TEMPLATES_REQUIRE_SOURCE - -// Compiler implements templates that support typedefs inside -// of classes used as formal arguments to a template class. -#define ACE_HAS_TEMPLATE_TYPEDEFS - -// Platform/Compiler supports a String class -#define ACE_HAS_STRING_CLASS -#define ACE_HAS_STDCPP_STL_INCLUDES - -// Platform has its standard c++ library in the namespace std. -#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 - -// Compiler doesn't support static data member templates -#define ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES - -// Platform lacks "signed char" type (broken!) -// Following will not be needed if use standard c library (G06.20 and later) -#define ACE_LACKS_SIGNED_CHAR - -// Compiler can handle any operators in namespace -#define ACE_ANY_OPS_USE_NAMESPACE - -// Platform lacks intptr_t typedef -#define ACE_LACKS_INTPTR_T - -//========================================================================= -// C++ version3 import/export macros -//========================================================================= - -// Define the export macros needed to export symbols outside a DLL -// The ACE_IMPORT_SINGLETON_DECLARE macro has been modified to not explicitly -// instantiate the class template. -#if defined(USE_EXPLICIT_EXPORT) -#define ACE_LACKS_INLINE_FUNCTIONS - -#define ACE_HAS_CUSTOM_EXPORT_MACROS -#define ACE_Proper_Export_Flag export$ -#define ACE_Proper_Import_Flag import$ -#define ACE_EXPORT_SINGLETON_DECLARATION(T) template class export$ T -#define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) template class export$ SINGLETON_TYPE; -#define ACE_IMPORT_SINGLETON_DECLARATION(T) template class import$ T -#define ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) template class import$ SINGLETON_TYPE ; -#endif - - -//========================================================================= -// Build options -//========================================================================= - -// Disable the inclusion of RCS ids in the generated code. -#define ACE_USE_RCSID 0 - -// For debugging problems in os calls (but this doesn't work too well -// since output is not interleaved properly with output from ACE_TRACE -//# define ACE_OS_TRACE(X) ::printf(X) - -// Uncomment the following if timed message blocks are needed (e.g. -// for Dynamic_Priority_Test. Otherwise leave this disabled because -// enabling it adds overhead to message blocks and timed message blocks -// are "rarely used." -//#define ACE_HAS_TIMED_MESSAGE_BLOCKS - -// Uncomment the following if tokens library is needed. -//#define ACE_HAS_TOKENS_LIBRARY - -// NonStop CORBA uses the XML Service Configurator -#define ACE_HAS_XML_SVC_CONF - -#define ACE_LD_SEARCH_PATH "_RLD_LIB_PATH" - -#include /**/ "ace/post.h" - -#endif /* ACE_CONFIG_NSK_H */ diff --git a/externals/ace/config-tandem.h b/externals/ace/config-tandem.h deleted file mode 100644 index 145c20abdaf..00000000000 --- a/externals/ace/config-tandem.h +++ /dev/null @@ -1,191 +0,0 @@ -/* -*- C++ -*- */ -// Testing TANDEM -// $Id: config-tandem.h 87167 2009-10-19 19:33:53Z olli $ - -// The following configuration file is designed to work for Tandems NonStop-UX -// 4.2MP platforms using the NCC 3.20 compiler. - -// Note this is a test version it might include several errors I -// have done a test and set/unset until I errors disappered. -// Some of the options that should be set aren't because of the simple fact -// that i haven't the time to check what is wrong. -// e.g. widecharacter are supported but a wcstok which only take 2 parameters -// are included by the compiler, to get the correct wcstok that takes 3 params -// we must set _XOPEN_SOURCE and we get ALOT of errors and warnings. -// So this config is done to get things to start to work it isn't finished. -// Janne (Jan.Perman@osd.Ericsson.se) - -#ifndef ACE_CONFIG_H -#define ACE_CONFIG_H -#include /**/ "ace/pre.h" - -#if ! defined (__ACE_INLINE__) -# define __ACE_INLINE__ -#endif /* ! __ACE_INLINE__ */ - -#define ACE_HAS_IDTYPE_T -// Optimize ACE_Handle_Set for select(). -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT - -// Tandem doesn't include this although they are defined -// in sys/time.h and sys/resource.h -#define ACE_LACKS_RLIMIT_PROTOTYPE // jjpp -// Tandem has a function to set t_errno (set_t_errno) -#define ACE_HAS_SET_T_ERRNO // jjpp - -//Platform supports System V IPC (most versions of UNIX, but not Win32) -#define ACE_HAS_SYSV_IPC - -// OS/compiler omits the const from the sendmsg() prototype. -#define ACE_HAS_NONCONST_SENDMSG - -//Platform supports system configuration information -#define ACE_HAS_SYS_SYSTEMINFO_H -#define ACE_HAS_SYSV_SYSINFO - -//Platform supports the POSIX regular expression library -#define ACE_HAS_REGEX - -// Platform supports recvmsg and sendmsg -#define ACE_HAS_MSG - -//Compiler/platform contains the file. -#define ACE_HAS_SYS_SYSCALL_H - -//Platform provides header -#define ACE_HAS_SYSENT_H - -// Platform has POSIX terminal interface. -#define ACE_HAS_TERMIOS - -//Platform supports POSIX O_NONBLOCK semantics -#define ACE_HAS_POSIX_NONBLOCK - -// Compiler/platform has correctly prototyped header files -#define ACE_HAS_CPLUSPLUS_HEADERS - -//Compiler/platform supports alloca() -// Although ACE does have alloca() on this compiler/platform combination, it is -// disabled by default since it can be dangerous. Uncomment the following line -// if you ACE to use it. -//#define ACE_HAS_ALLOCA - -//Compiler/platform has -#define ACE_HAS_ALLOCA_H - -//Platform contains -#define ACE_HAS_POLL - -// Platform supports the POSIX struct timespec type -#define ACE_HAS_POSIX_TIME // As i understand it, but i'm in deep water -//Platform supports the SVR4 timestruc_t type - -// To get this to work a patch in sys/signal must be made -// typedef void SIG_FUNC_TYPE(int); -//#if defined (__cplusplus) -// void (*sa_handler)(int); -//#else -// ... -//#endif -//#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES -#define ACE_HAS_TANDEM_SIGNALS -//Compiler/platform defines the sig_atomic_t typedef -#define ACE_HAS_SIG_ATOMIC_T -//Platform supports SVR4 extended signals -#define ACE_HAS_SIGINFO_T -//Platform supports ucontext_t (which is used in the extended signal API). -#define ACE_HAS_UCONTEXT_T - -// Platform/compiler has the sigwait(2) prototype -#define ACE_HAS_SIGWAIT - -//Compiler/platform provides the sockio.h file -#define ACE_HAS_SYS_SOCKIO_H - -// Compiler supports the ssize_t typedef -#define ACE_HAS_SSIZE_T // Limits.h must be included - -//Platform supports STREAMS -#define ACE_HAS_STREAMS - -#define ACE_HAS_STREAM_PIPES -//Platform supports STREAM pipes - -//Compiler/platform supports struct strbuf -#define ACE_HAS_STRBUF_T - -//Compiler/platform supports SVR4 dynamic linking semantics -#define ACE_HAS_SVR4_DYNAMIC_LINKING - -//Compiler/platform supports SVR4 TLI (in particular, T_GETNAME stuff)... -#define ACE_HAS_SVR4_TLI - -//Platform provides header -#define ACE_HAS_SYS_FILIO_H - -//Platform supports TLI timod STREAMS module -#define ACE_HAS_TIMOD_H -//Platform supports TLI tiuser header -#define ACE_HAS_TIUSER_H - -//Platform supports TLI -#define ACE_HAS_TLI -//Platform provides TLI function prototypes -#define ACE_HAS_TLI_PROTOTYPES - -//Platform lacks streambuf "linebuffered ()". -#define ACE_LACKS_LINEBUFFERED_STREAMBUF - -// Platform lacks "signed char" type (broken!) -#define ACE_LACKS_SIGNED_CHAR - - -#define ACE_PAGE_SIZE 4096 -// Defines the page size of the system (not used on Win32 or -// with ACE_HAS_GETPAGESIZE). - -/****** THREAD SPECIFIC **********/ -/* If you want to remove threading then comment out the following four #defines .*/ -#if !defined (ACE_MT_SAFE) - #define ACE_MT_SAFE 1 //Compile using multi-thread libraries -#endif -#define ACE_HAS_THREADS //Platform supports threads -#define ACE_HAS_STHREADS //Platform supports Solaris threads - -// Compiler/platform has threadspecific storage -#define ACE_HAS_THREAD_SPECIFIC_STORAGE -//Platform supports thr_keydelete (e.g,. UNIXWARE) - -#define ACE_HAS_THR_MINSTACK // Tandem uses thr_minstack instead of thr_min_stack -#define ACE_LACKS_PRI_T // Tandem lacks pri_t -#define ACE_HAS_THR_KEYDELETE - -//************************************* - -/*********************************/ - -/******* SIGNAL STUFF *******/ - -//Platform uses non-const char * in calls to gethostbyaddr, gethostbyname, -// getservbyname -#define ACE_HAS_NONCONST_GETBY -#define ACE_HAS_NONCONST_INET_ADDR -// Platform's select() uses non-const timeval* (only found on Linux right now) -#define ACE_HAS_NONCONST_SELECT_TIMEVAL -// And on Tandem :-) -//Uses ctime_r & asctime_r with only two parameters vs. three. -#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R -//Platform has special header for select(). -#define ACE_HAS_SELECT_H -// Platform/compiler supports Standard C++ Library -#define ACE_HAS_STANDARD_CPP_LIBRARY -//Platform lacks madvise() (e.g., Linux) -#define ACE_LACKS_MADVISE -//Compiler/platform lacks strcasecmp() (e.g., DG/UX, UNIXWARE, VXWORKS) -#define ACE_LACKS_STRCASECMP - -// Defines the page size of the system. -#define ACE_PAGE_SIZE 4096 - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_H */ diff --git a/externals/ace/config-tru64.h b/externals/ace/config-tru64.h deleted file mode 100644 index 45a7aa6bd53..00000000000 --- a/externals/ace/config-tru64.h +++ /dev/null @@ -1,151 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-tru64.h 87270 2009-10-29 21:47:47Z olli $ - -// The following configuration file is designed to work for the -// Digital UNIX V4.0a and later platforms. It relies on -// config-osf1-4.0.h, and adds deltas for newer platforms. - -#ifndef ACE_CONFIG_TRU64_H -#define ACE_CONFIG_TRU64_H -#include /**/ "ace/pre.h" - -#if !defined (__ACE_INLINE__) -# define __ACE_INLINE__ -#endif /* ! __ACE_INLINE__ */ - -// Compile using multi-thread libraries. -#if !defined (ACE_MT_SAFE) -# define ACE_MT_SAFE 1 -#endif /* ! ACE_MT_SAFE */ - -/*clearerr is not defined when _REENTRANT is not defined*/ -#if ACE_MT_SAFE == 0 -#define ACE_LACKS_CLEARERR -#endif /* ACE_MT_SAFE == 0 */ - -#include "ace/config-posix.h" - -// Configuration-specific #defines: -// 1) g++ or cxx -// 2) pthreads or DCE threads -#if defined (__GNUG__) - // g++ with pthreads - - // config-g++-common.h undef's ACE_HAS_STRING_CLASS with -frepo, so - // this must appear before its #include. -# define ACE_HAS_STRING_CLASS - -# include "ace/config-g++-common.h" - -# define ACE_HAS_REENTRANT_FUNCTIONS -#elif defined (__DECCXX) - -# define ACE_CONFIG_INCLUDE_CXX_COMMON -# include "ace/config-cxx-common.h" - -#elif defined (__rational__) -# define ACE_HAS_REENTRANT_FUNCTIONS -# define ACE_HAS_STRING_CLASS -# define ACE_LACKS_LINEBUFFERED_STREAMBUF -# define ACE_LACKS_SIGNED_CHAR - - // Exceptions are enabled by platform_osf1_4.0_rcc.GNU. -# define ACE_HAS_STDCPP_STL_INCLUDES -#else -# ifdef __cplusplus /* Let it slide for C compilers. */ -# error unsupported compiler on Digital Unix -# endif /* __cplusplus */ -#endif /* ! __GNUG__ && ! __DECCXX && ! __rational__ */ - -#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R -#define ACE_HAS_BROKEN_IF_HEADER -#if (ACE_MT_SAFE != 0) -# define ACE_HAS_PTHREADS -# define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS -#endif /* ACE_MT_SAFE != 0 */ -#define ACE_LACKS_T_ERRNO -#if !defined (DIGITAL_UNIX) -# define DIGITAL_UNIX 0x400 -#endif /* ! DIGITAL_UNIX */ - -#define ACE_SIZEOF_LONG 8 - -#define ACE_DEFAULT_BASE_ADDR ((char *) 0x80000000) -#define ACE_HAS_AUTOMATIC_INIT_FINI -#define ACE_HAS_NONCONST_SETRLIMIT -#define ACE_HAS_BROKEN_T_ERROR -#define ACE_HAS_NONCONST_WRITEV -#define ACE_HAS_CLOCK_GETTIME -#define ACE_HAS_CLOCK_SETTIME -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES -#define ACE_HAS_CPLUSPLUS_HEADERS -#define ACE_HAS_DIRENT -#define ACE_HAS_GETRUSAGE -#define ACE_HAS_GPERF -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT -#define ACE_HAS_IP_MULTICAST -#define ACE_HAS_LLSEEK -#define ACE_HAS_LONG_MAP_FAILED -#define ACE_HAS_MSG -#define ACE_HAS_NONCONST_SELECT_TIMEVAL -#define ACE_HAS_NONCONST_SENDMSG -#define ACE_HAS_OSF1_GETTIMEOFDAY -#define ACE_HAS_OSF_TIMOD_H -#define ACE_HAS_POLL -#define ACE_HAS_POSIX_NONBLOCK -#define ACE_HAS_POSIX_TIME -#define ACE_HAS_PRIOCNTL -#define ACE_HAS_SIGINFO_T -#define ACE_HAS_SIG_ATOMIC_T -#define ACE_HAS_SSIZE_T -#define ACE_HAS_STRBUF_T -#define ACE_HAS_STREAMS -#define ACE_HAS_STRPTIME -#define ACE_HAS_SVR4_DYNAMIC_LINKING -#define ACE_HAS_SVR4_SIGNAL_T -#define ACE_HAS_SYS_SYSCALL_H -#define ACE_HAS_SYSV_IPC -#if (ACE_MT_SAFE == 0) -// clearerr is not defined when _REENTRANT is not defined -#define ACE_LACKS_CLEARERR -#else /* ACE_MT_SAFE != 0 */ -#define ACE_HAS_THREADS -#define ACE_HAS_THREAD_SPECIFIC_STORAGE -#define ACE_LACKS_PTHREAD_ATTR_SETSTACKADDR -#endif /* ACE_MT_SAFE != 0 */ -#define ACE_HAS_TIUSER_H -#define ACE_HAS_XTI -#define ACE_HAS_TLI_PROTOTYPES -#define ACE_HAS_UALARM -#define ACE_HAS_UCONTEXT_T -#define ACE_LACKS_PRI_T -#define ACE_LACKS_RWLOCK_T -#define ACE_PAGE_SIZE 8192 -#define ACE_HAS_SIGTIMEDWAIT -#define ACE_HAS_SIGSUSPEND - -// DJT 6/10/96 All these broken macro's can now be removed with the -// approporiate ordering of the include files. The Platinum release -// now temporarily supports both forms. Platform's implementation of -// sendmsg() has a non-const msgheader parameter. -#define ACE_HAS_NONCONST_SENDMSG -#define ACE_HAS_IDTYPE_T -#define ACE_HAS_NONSTATIC_OBJECT_MANAGER - -#if DIGITAL_UNIX >= 0x500 -# define ACE_HAS_XPG4_MULTIBYTE_CHAR 1 -#endif /* DIGITAL_UNIX >= 0x500 */ - -#if DIGITAL_UNIX >= 0x40E -# define ACE_LACKS_STDINT_H -#endif /* DIGITAL_UNIX >= 0x40E */ - -#if (DIGITAL_UNIX >= 0x400) && (DIGITAL_UNIX < 0x500) -#define ACE_LACKS_PREAD_PROTOTYPE -#endif /* (DIGITAL_UNIX >= 0x400) && (DIGITAL_UNIX < 0x500) */ - -// gethostbyaddr does not handle IPv6-mapped-IPv4 addresses -#define ACE_HAS_BROKEN_GETHOSTBYADDR_V4MAPPED - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_TRU64_H */ diff --git a/externals/ace/config-unixware-7.1.0.h b/externals/ace/config-unixware-7.1.0.h deleted file mode 100644 index 820e7fb763a..00000000000 --- a/externals/ace/config-unixware-7.1.0.h +++ /dev/null @@ -1,406 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-unixware-7.1.0.h 87268 2009-10-29 21:06:06Z olli $ - -#ifndef ACE_CONFIG_H -#define ACE_CONFIG_H - -/* ACE configuration header file */ - -/* Include the commong gnu config file */ -#include "config-g++-common.h" - -/* For unixware 7.1 && g++ 2.91.57, see if this fixes my problem */ -#ifndef UNIXWARE_7_1 -#define UNIXWARE_7_1 -#endif - -/* Define if you have alloca, as a function or macro. */ -#define HAVE_ALLOCA 1 - -/* Define if you have the strftime function. */ -#define HAVE_STRFTIME 1 - -/* Define if you have that is POSIX.1 compatible. */ -#define HAVE_SYS_WAIT_H 1 - -/* Define if you have the ANSI C header files. */ -#define STDC_HEADERS 1 - -/* Define if lex declares yytext as a char * by default, not a char[]. */ -#define YYTEXT_POINTER 1 - -/* Define _REENTRANT if reentrant functions should be used. */ -#ifndef _REENTRANT -# define _REENTRANT 1 -#endif - -#define ACE_HAS_NEW_NO_H 1 -#define ACE_HAS_STDEXCEPT_NO_H 1 - -#define ACE_THREAD_MIN_PRIORITY 0 -#if defined (ACE_THREAD_MIN_PRIORITY) -# define PTHREAD_MIN_PRIORITY ACE_THREAD_MIN_PRIORITY -#endif /* #if defined (ACE_THREAD_MIN_PRIORITY) */ - -#define ACE_THREAD_MAX_PRIORITY 99 -#if defined (ACE_THREAD_MAX_PRIORITY) -# define PTHREAD_MAX_PRIORITY ACE_THREAD_MAX_PRIORITY -#endif /* #if defined (ACE_THREAD_MAX_PRIORITY) */ - -/* Specify sizes of given built-in types. If a size isn't defined here, - then ace/Basic_Types.h will attempt to deduce the size. */ -/* #undef ACE_SIZEOF_CHAR */ -#define ACE_SIZEOF_SHORT 2 -#define ACE_SIZEOF_INT 4 -#define ACE_SIZEOF_LONG 4 -#define ACE_SIZEOF_LONG_LONG 8 -#define ACE_SIZEOF_VOID_P 4 -#define ACE_SIZEOF_FLOAT 4 -#define ACE_SIZEOF_DOUBLE 8 -#define ACE_SIZEOF_LONG_DOUBLE 12 - -/* Enable ACE inlining */ -#define __ACE_INLINE__ 1 - -/* OS has priocntl (2) */ -#define ACE_HAS_PRIOCNTL 1 - -/* Platform has pread() and pwrite() support */ -#define ACE_HAS_P_READ_WRITE 1 - -/* Compiler/platform supports alloca() */ -// Although ACE does have alloca() on this compiler/platform combination, it is -// disabled by default since it can be dangerous. Uncomment the following line -// if you ACE to use it. -//#define ACE_HAS_ALLOCA 1 - -/* Compiler/platform correctly calls init()/fini() for shared libraries */ -#define ACE_HAS_AUTOMATIC_INIT_FINI 1 - -/* Platform doesn't cast MAP_FAILED to a (void *). */ -/* #undef ACE_HAS_BROKEN_MAP_FAILED */ -/* Staller: oh yes, let's do this! */ -#define ACE_HAS_BROKEN_MAP_FAILED - -/* Prototypes for both signal() and struct sigaction are consistent. */ -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES 1 - -/* Platform supports operations on directories via struct dirent, - readdir_r, etc. */ -#define ACE_HAS_DIRENT 1 - -/* Compiler supports C++ exception handling */ -// MM-Graz if ! defined inserted, to prevent warnings, because it is already -// defined in config-g++common.h -# if !defined (ACE_HAS_EXCEPTIONS) -#define ACE_HAS_EXCEPTIONS 1 -# endif - -/* Platform supports getpagesize() call (otherwise, ACE_PAGE_SIZE must be - defined, except on Win32) */ -#define ACE_HAS_GETPAGESIZE 1 - -/* Platform supports the getrusage() system call. */ -#define ACE_HAS_GETRUSAGE 1 - -/* Platform has a getrusage () prototype in sys/resource.h that differs from - the one in ace/OS.i. */ -#define ACE_HAS_GETRUSAGE_PROTOTYPE 1 - -/* The GPERF utility is compiled for this platform */ -#define ACE_HAS_GPERF 1 - -/* Optimize ACE_Handle_Set::count_bits for select() operations (common case) */ -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT 1 - -/* Compiler/platform supports idtype_t. */ -#define ACE_HAS_IDTYPE_T 1 - -/* Platform supports IP multicast */ -#define ACE_HAS_IP_MULTICAST 1 - -/* Platform supports thr_keydelete (e.g,. UNIXWARE) */ -#define ACE_HAS_THR_KEYDELETE 1 - -/* Platform calls thr_minstack() rather than thr_min_stack() (e.g., Tandem). */ -#define ACE_HAS_THR_MINSTACK 1 - -/* Platform supports recvmsg and sendmsg */ -#define ACE_HAS_MSG 1 - -/* Platform's select() uses non-const timeval* (only found on Linux right - now) */ -#define ACE_HAS_NONCONST_SELECT_TIMEVAL 1 - -/* Uses ctime_r & asctime_r with only two parameters vs. three. */ -#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R 1 - -/* Platform is an Intel Pentium microprocessor. */ -/* There is a problem with the gethrtime() because of (apparently) a problem - with the inline assembly instruction. Hopefully there is a way to resolve - that with an improvement to the assembler -*/ -#ifdef ACE_HAS_PENTIUM -#undef ACE_HAS_PENTIUM -#endif /* ACE_HAS_PENTIUM */ - - -/* Platform contains */ -#define ACE_HAS_POLL 1 - -/* Platform supports POSIX O_NONBLOCK semantics */ -#define ACE_HAS_POSIX_NONBLOCK 1 - -/* Platform supports the POSIX struct timespec type */ -#define ACE_HAS_POSIX_TIME 1 - -/* Platform supports the /proc file system and defines tid_t - in */ -#define ACE_HAS_PROC_FS 1 - -/* Platform supports POSIX Threads */ -#define ACE_HAS_PTHREADS 1 - -/* pthread.h declares an enum with PTHREAD_PROCESS_PRIVATE and - PTHREAD_PROCESS_SHARED values */ -#define ACE_HAS_PTHREAD_PROCESS_ENUM 1 - -/* Platform will recurse infinitely on thread exits from TSS cleanup routines - (e.g., AIX) */ -#define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS 1 - -/* Platform supports reentrant functions (i.e., all the POSIX *_r - functions). */ -#define ACE_HAS_REENTRANT_FUNCTIONS 1 - -/* Platform has support for multi-byte character support compliant with the - XPG4 Worldwide Portability Interface wide-character classification. */ -#define ACE_HAS_XPG4_MULTIBYTE_CHAR 1 - -/* Platform does not support reentrant netdb functions (getprotobyname_r, - getprotobynumber_r, gethostbyaddr_r, gethostbyname_r, getservbyname_r). */ -#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS 1 - -/* Platform supports the POSIX regular expression library */ -#define ACE_HAS_REGEX 1 - -/* Platform has special header for select(). */ -#define ACE_HAS_SELECT_H 1 - -/* Platform has a function to set t_errno (e.g., Tandem). */ -#define ACE_HAS_SET_T_ERRNO 1 - -/* Platform supports SVR4 extended signals */ -#define ACE_HAS_SIGINFO_T 1 - -/* Platform/compiler has the sigwait(2) prototype */ -#define ACE_HAS_SIGWAIT 1 - -/* Compiler/platform defines the sig_atomic_t typedef */ -#define ACE_HAS_SIG_ATOMIC_T 1 - -/* Platform supports new BSD inet_addr len field. */ -#define ACE_HAS_SOCKADDR_IN_SIN_LEN 1 - -/* OS/compiler uses size_t * rather than int * for socket lengths */ -#define ACE_HAS_SIZET_SOCKET_LEN 1 - -/* Compiler/platform provides the sys/sockio.h file */ -#define ACE_HAS_SYS_SOCKIO_H 1 - -/* Compiler supports the ssize_t typedef */ -#define ACE_HAS_SSIZE_T 1 - -/* Platform supports UNIX International Threads */ -#define ACE_HAS_STHREADS 1 - -/* Platform has thr_yield() */ -#define ACE_HAS_THR_YIELD 1 - -/* Compiler/platform supports struct strbuf */ -#define ACE_HAS_STRBUF_T 1 - -/* Platform supports STREAMS */ -#define ACE_HAS_STREAMS 1 - -/* Platform supports STREAM pipes */ -#define ACE_HAS_STREAM_PIPES 1 - -/* Platform/Compiler supports a String class (e.g., GNU or Win32). */ -#define ACE_HAS_STRING_CLASS 1 - -/* Platform has (which contains bzero() prototype) */ -#define ACE_HAS_STRINGS 1 - -/* Platform/compiler supports void * as second parameter to gettimeofday(). */ -#define ACE_HAS_VOIDPTR_GETTIMEOFDAY 1 - -/* Compiler/platform supports SVR4 dynamic linking semantics */ -#define ACE_HAS_SVR4_DYNAMIC_LINKING 1 - -/* Compiler/platform supports SVR4 TLI (in particular, T_GETNAME stuff)... */ -#define ACE_HAS_SVR4_TLI 1 - -/* Compiler/platform contains the file. */ -#define ACE_HAS_SYS_SYSCALL_H 1 - -/* Platform supports system configuration information */ -#define ACE_HAS_SYS_SYSTEMINFO_H -#define ACE_HAS_SYSV_SYSINFO 1 - -/* Platform supports System V IPC (most versions of UNIX, but not Win32) */ -#define ACE_HAS_SYSV_IPC 1 - -/* Platform provides header */ -#define ACE_HAS_SYS_FILIO_H 1 - -/* Platform provides header */ -#define ACE_HAS_SYS_XTI_H 1 - -/* Platform has POSIX terminal interface. */ -#define ACE_HAS_TERMIOS 1 - -/* Platform supports threads */ -#define ACE_HAS_THREADS 1 - -/* Compiler/platform has thread-specific storage */ -#define ACE_HAS_THREAD_SPECIFIC_STORAGE 1 - -/* Platform supports TLI timod STREAMS module */ -#define ACE_HAS_TIMOD_H 1 - -/* Platform supports TLI tiuser header */ -#define ACE_HAS_TIUSER_H 1 - -/* Platform supports TLI. Also see ACE_TLI_TCP_DEVICE. */ -#define ACE_HAS_TLI 1 - -/* Platform provides TLI function prototypes */ -#define ACE_HAS_TLI_PROTOTYPES 1 - -/* Platform supports ualarm() */ -#define ACE_HAS_UALARM 1 - -/* Platform supports ucontext_t (which is used in the extended signal API). */ -#define ACE_HAS_UCONTEXT_T 1 - -/* Platform has header file */ -#define ACE_HAS_UTIME 1 - -/* Platform requires void * for mmap(). */ -#define ACE_HAS_VOIDPTR_MMAP 1 - -/* Platform has XTI (X/Open-standardized superset of TLI). Implies - ACE_HAS_TLI but uses a different header file. */ -#define ACE_HAS_XTI 1 - -/* Platform can not build ace/IOStream{,_T}.cpp. This does not necessarily - mean that the platform does not support iostreams. */ -#define ACE_LACKS_ACE_IOSTREAM 1 - -/* Platform does not have u_longlong_t typedef */ -#define ACE_LACKS_U_LONGLONG_T 1 - -/* Platform lacks madvise() (e.g., Linux) */ -#define ACE_LACKS_MADVISE 1 - -/* Platform lacks pri_t (e.g., Tandem NonStop UNIX). */ -#define ACE_LACKS_PRI_T 1 - -/* Platform lacks pthread_thr_sigsetmask (e.g., MVS, HP/UX, and OSF/1 3.2) */ -#define ACE_LACKS_PTHREAD_THR_SIGSETMASK 1 - -/* Platfrom lack pthread_yield() support. */ -#define ACE_LACKS_PTHREAD_YIELD 1 - -/* Platform lacks readers/writer locks. */ -#define ACE_LACKS_RWLOCK_T 1 - -/* MIT pthreads platform lacks the timedwait prototypes */ -#define ACE_LACKS_TIMEDWAIT_PROTOTYPES 1 - -/* Platform does not define timepec_t as a typedef for struct timespec. */ -#define ACE_LACKS_TIMESPEC_T 1 - -/* Compile using multi-thread libraries */ -#define ACE_MT_SAFE 1 - -/* Platform needs to #include to get thread scheduling defs. */ -#define ACE_NEEDS_SCHED_H 1 - -/*********************************************************************/ -/* Compiler's template mechanim must see source code (i.e., .cpp files). This - is used for GNU G++. */ -/* Staller -> make 0 */ -// #undef ACE_TEMPLATES_REQUIRE_SOURCE - -/*********************************************************************/ - -/* The OS/platform supports the poll() event demultiplexor */ -#define ACE_USE_POLL 1 - -/* Platform has its standard c++ library in the namespace std. */ -#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 - -/* The number of bytes in a double. */ -#define SIZEOF_DOUBLE 8 - -/* The number of bytes in a float. */ -#define SIZEOF_FLOAT 4 - -/* The number of bytes in a int. */ -#define SIZEOF_INT 4 - -/* The number of bytes in a long. */ -#define SIZEOF_LONG 4 - -/* The number of bytes in a long double. */ -#define SIZEOF_LONG_DOUBLE 12 - -/* The number of bytes in a long long. */ -#define SIZEOF_LONG_LONG 8 - -/* The number of bytes in a short. */ -#define SIZEOF_SHORT 2 - -/* The number of bytes in a signed char. */ -#define SIZEOF_SIGNED_CHAR 1 - -/* The number of bytes in a void *. */ -#define SIZEOF_VOID_P 4 - -/* Define if you have the execv function. */ -#define HAVE_EXECV 1 - -/* Define if you have the execve function. */ -#define HAVE_EXECVE 1 - -/* Define if you have the execvp function. */ -#define HAVE_EXECVP 1 - -/* Define if you have the header file. */ -#define HAVE_DIRENT_H 1 - -/* Define if you have the header file. */ -#define HAVE_FSTREAM 1 - -/* Define if you have the header file. */ -#define HAVE_IOMANIP 1 - -/* Define if you have the header file. */ -#define HAVE_IOSTREAM 1 - -/* Define if you have the header file. */ -#define HAVE_PWD_H 1 - -/* Name of package */ -#define PACKAGE "ace" - -/* Added by Staller */ -#define ENUM_BOOLEAN // See file /usr/local/lib/gcc-lib/i486-pc-sysv5/egcs-2.91.60/include/sys/types.h -#define howmany(x, y) (((x)+((y)-1))/(y)) -#define ACE_HAS_BROKEN_T_ERROR // make a nasty warning disappear in OS.i -#define __USLC__ 1 -#define __IOCTL_VERSIONED__ // By Carlo! - -#endif /* ACE_CONFIG_H */ diff --git a/externals/ace/config-unixware-7.1.0.udk.h b/externals/ace/config-unixware-7.1.0.udk.h deleted file mode 100644 index ec668c19581..00000000000 --- a/externals/ace/config-unixware-7.1.0.udk.h +++ /dev/null @@ -1,457 +0,0 @@ -/* -*- C++ -*- */ -#ifndef ACE_CONFIG_UNIXWARE_UDK_H -#define ACE_CONFIG_UNIXWARE_UDK_H - -// $Id: config-unixware-7.1.0.udk.h 87167 2009-10-19 19:33:53Z olli $ - -// Configuration for the unixware UDK compiler. derived from the unixware/g++ config -// which was itself derived from an autoconfig run. - -/* ACE configuration header file */ - -#define ACE_TEMPLATES_REQUIRE_SOURCE - -#ifndef UNIXWARE_7_1 -#define UNIXWARE_7_1 -#endif - -#define ACE_LACKS_PLACEMENT_OPERATOR_DELETE - -/* Define if you have the strftime function. */ -#define HAVE_STRFTIME 1 - -/* Define if you have that is POSIX.1 compatible. */ -#define HAVE_SYS_WAIT_H 1 - -/* Define if you have the ANSI C header files. */ -#define STDC_HEADERS 1 - -/* Define if lex declares yytext as a char * by default, not a char[]. */ -#define YYTEXT_POINTER 1 - -/* Define _REENTRANT if reentrant functions should be used. */ -#ifndef _REENTRANT -# define _REENTRANT 1 -#endif - -#define ACE_HAS_NEW_NO_H 1 -#define ACE_HAS_STDEXCEPT_NO_H 1 - -/* - * TODO: These two next #defines have an #undef before them, in - * case the variable being defined already had a value. - * The #undefs are being picked up by configure, and are commented out! - */ -#define ACE_THREAD_MIN_PRIORITY 0 -#if defined (ACE_THREAD_MIN_PRIORITY) -/* # undef PTHREAD_MIN_PRIORITY */ -# define PTHREAD_MIN_PRIORITY ACE_THREAD_MIN_PRIORITY -#endif /* #if defined (ACE_THREAD_MIN_PRIORITY) */ - -#define ACE_THREAD_MAX_PRIORITY 99 -#if defined (ACE_THREAD_MAX_PRIORITY) -/* # undef PTHREAD_MAX_PRIORITY */ -# define PTHREAD_MAX_PRIORITY ACE_THREAD_MAX_PRIORITY -#endif /* #if defined (ACE_THREAD_MAX_PRIORITY) */ - - - -/* UnixWare specific configuration parameters */ -/* #undef UNIXWARE */ -/* #undef UNIXWARE_2_0 */ -/* #undef UNIXWARE_2_1 */ - -/* Specify sizes of given built-in types. If a size isn't defined here, - then ace/Basic_Types.h will attempt to deduce the size. */ -/* #undef ACE_SIZEOF_CHAR */ -#define ACE_SIZEOF_SHORT 2 -#define ACE_SIZEOF_INT 4 -#define ACE_SIZEOF_LONG 4 -#define ACE_SIZEOF_LONG_LONG 8 -#define ACE_SIZEOF_VOID_P 4 -#define ACE_SIZEOF_FLOAT 4 -#define ACE_SIZEOF_DOUBLE 8 -#define ACE_SIZEOF_LONG_DOUBLE 12 - -/* Enable ACE inlining */ -#define __ACE_INLINE__ 1 - -/* Platform supports Asynchronous IO calls */ -/* #define ACE_HAS_AIO_CALLS */ - -/* Specify this if you don't want threads to inherit parent thread's - ACE_Log_Msg properties. */ -/* #undef ACE_THREADS_DONT_INHERIT_LOG_MSG */ - -/* OS has priocntl (2) */ -#define ACE_HAS_PRIOCNTL 1 - -/* Platform has pread() and pwrite() support */ -#define ACE_HAS_P_READ_WRITE 1 - -/* Compiler/platform correctly calls init()/fini() for shared libraries */ -#define ACE_HAS_AUTOMATIC_INIT_FINI 1 - -/* Compiler handles explicit calling of template destructor correctly. - See "ace/OS.h" for details. */ -/* Staller: already defined by config-g++-common.h -#define ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR 1 -*/ - -/* Platform doesn't cast MAP_FAILED to a (void *). */ -/* #undef ACE_HAS_BROKEN_MAP_FAILED */ -/* Staller: oh yes, let's do this! */ -#define ACE_HAS_BROKEN_MAP_FAILED - - -/* Prototypes for both signal() and struct sigaction are consistent. */ -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES 1 - -/* Compiler/platform has correctly prototyped header files */ -#define ACE_HAS_CPLUSPLUS_HEADERS - -/* Platform supports operations on directories via struct dirent, - readdir_r, etc. */ -#define ACE_HAS_DIRENT - -/* Compiler supports C++ exception handling */ -# if !defined (ACE_HAS_EXCEPTIONS) -#define ACE_HAS_EXCEPTIONS -# endif - -/* Platform supports getpagesize() call (otherwise, ACE_PAGE_SIZE must be - defined, except on Win32) */ -#define ACE_HAS_GETPAGESIZE - -/* Platform supports the getrusage() system call. */ -#define ACE_HAS_GETRUSAGE - -/* Platform has a getrusage () prototype in sys/resource.h that differs from - the one in ace/OS.i. */ -#define ACE_HAS_GETRUSAGE_PROTOTYPE - -/* The GPERF utility is compiled for this platform */ -#define ACE_HAS_GPERF - -/* Optimize ACE_Handle_Set::count_bits for select() operations (common case) */ -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT 1 - -/* Compiler/platform supports SunOS high resolution timers */ -/* #undef ACE_HAS_HI_RES_TIMER */ - -/* Compiler/platform supports idtype_t. */ -#define ACE_HAS_IDTYPE_T - -/* Inline all the static class OS methods to remove call overhead */ -/* Note: This gets defined by OS.h if __ACE_INLINE__ is defined */ -/* #undef ACE_HAS_INLINED_OSCALLS */ - -/* Platform supports IP multicast */ -#define ACE_HAS_IP_MULTICAST - -/* Platform supports thr_keydelete (e.g,. UNIXWARE) */ -#define ACE_HAS_THR_KEYDELETE - -/* Platform calls thr_minstack() rather than thr_min_stack() (e.g., Tandem). */ -#define ACE_HAS_THR_MINSTACK - -/* Some files, such as ace/streams.h, want to include new style C++ stream - headers. These headers are iomanip, ios, iostream, istream, ostream, - fstream and streambuf. If _all_ of these headers aren't available, then - assume that only iostream.h and fstream.h are available. */ -/* #define ACE_USES_OLD_IOSTREAMS */ - -/* Platform supports recvmsg and sendmsg */ -#define ACE_HAS_MSG - -/* Platform's select() uses non-const timeval* (only found on Linux right - now) */ -#define ACE_HAS_NONCONST_SELECT_TIMEVAL - -/* Uses ctime_r & asctime_r with only two parameters vs. three. */ -#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R - - -/* Platform is an Intel Pentium microprocessor. */ -/* There is a problem with the gethrtime() because of (apparently) a problem - with the inline assembly instruction. Hopefully there is a way to resolve - that with an improvement to the assembler -*/ -#ifdef ACE_HAS_PENTIUM -//#undef ACE_HAS_PENTIUM -#endif /* ACE_HAS_PENTIUM */ - - -/* Platform contains */ -#define ACE_HAS_POLL - -/* Platform supports POSIX O_NONBLOCK semantics */ -#define ACE_HAS_POSIX_NONBLOCK - -/* Platform supports the POSIX struct timespec type */ -#define ACE_HAS_POSIX_TIME - -/* Platform supports the /proc file system and defines tid_t - in */ -#define ACE_HAS_PROC_FS - -/* Platform supports POSIX Threads */ -#define ACE_HAS_PTHREADS - -/* pthread.h declares an enum with PTHREAD_PROCESS_PRIVATE and - PTHREAD_PROCESS_SHARED values */ -#define ACE_HAS_PTHREAD_PROCESS_ENUM - -/* Platform will recurse infinitely on thread exits from TSS cleanup routines - (e.g., AIX) */ -#define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS - -/* Platform supports reentrant functions (i.e., all the POSIX *_r - functions). */ -#define ACE_HAS_REENTRANT_FUNCTIONS - -/* Platform has support for multi-byte character support compliant with the - XPG4 Worldwide Portability Interface wide-character classification. */ -#define ACE_HAS_XPG4_MULTIBYTE_CHAR - -/* Platform does not support reentrant netdb functions (getprotobyname_r, - getprotobynumber_r, gethostbyaddr_r, gethostbyname_r, getservbyname_r). */ -#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS - -/* Platform supports the POSIX regular expression library */ -#define ACE_HAS_REGEX - -/* Platform has special header for select(). */ -#define ACE_HAS_SELECT_H - -/* Platform has a function to set t_errno (e.g., Tandem). */ -#define ACE_HAS_SET_T_ERRNO - -/* Platform supports SVR4 extended signals */ -#define ACE_HAS_SIGINFO_T - -/* Platform/compiler has the sigwait(2) prototype */ -#define ACE_HAS_SIGWAIT - -/* Compiler/platform defines the sig_atomic_t typedef */ -#define ACE_HAS_SIG_ATOMIC_T - -/* Platform supports new BSD inet_addr len field. */ -#define ACE_HAS_SOCKADDR_IN_SIN_LEN - -/* OS/compiler uses size_t * rather than int * for socket lengths */ -#define ACE_HAS_SIZET_SOCKET_LEN - -/* Compiler/platform provides the sys/sockio.h file */ -#define ACE_HAS_SYS_SOCKIO_H - -/* Compiler supports the ssize_t typedef */ -#define ACE_HAS_SSIZE_T - -/* Platform supports UNIX International Threads */ -#define ACE_HAS_STHREADS - -/* Platform has thr_yield() */ -#define ACE_HAS_THR_YIELD - -/* Platform/compiler supports Standard C++ Library */ -/* It seems that UDK provides std-like declarations for only portions - such as -*/ -#define ACE_HAS_STANDARD_CPP_LIBRARY 0 - -/* Compiler/platform supports struct strbuf */ -#define ACE_HAS_STRBUF_T - -/* Platform supports STREAMS */ -#define ACE_HAS_STREAMS - -/* Platform supports STREAM pipes */ -#define ACE_HAS_STREAM_PIPES - -/* Platform/Compiler supports a String class (e.g., GNU or Win32). */ -#define ACE_HAS_STRING_CLASS - -/* Platform has (which contains bzero() prototype) */ -#define ACE_HAS_STRINGS - -/* Platform/compiler supports void * as second parameter to gettimeofday(). */ -#define ACE_HAS_VOIDPTR_GETTIMEOFDAY - -/* Compiler/platform supports SVR4 dynamic linking semantics */ -#define ACE_HAS_SVR4_DYNAMIC_LINKING - -/* Compiler/platform supports SVR4 TLI (in particular, T_GETNAME stuff)... */ -#define ACE_HAS_SVR4_TLI - -/* Compiler/platform contains the file. */ -#define ACE_HAS_SYS_SYSCALL_H - -/* Platform supports system configuration information */ -#define ACE_HAS_SYS_SYSTEMINFO_H -#define ACE_HAS_SYSV_SYSINFO 1 - -/* Platform supports System V IPC (most versions of UNIX, but not Win32) */ -#define ACE_HAS_SYSV_IPC 1 - -/* Platform provides header */ -#define ACE_HAS_SYS_FILIO_H 1 - -/* Platform provides header */ -#define ACE_HAS_SYS_XTI_H 1 - -/* Compiler implements templates that support typedefs inside of classes used - as formal arguments to a template class. */ -#define ACE_HAS_TEMPLATE_TYPEDEFS 1 - -/* Platform has POSIX terminal interface. */ -#define ACE_HAS_TERMIOS 1 - -/* Platform supports threads */ -#define ACE_HAS_THREADS 1 - -/* Compiler/platform has thread-specific storage */ -#define ACE_HAS_THREAD_SPECIFIC_STORAGE 1 - -/* Platform supports TLI timod STREAMS module */ -#define ACE_HAS_TIMOD_H 1 - -/* Platform supports TLI tiuser header */ -#define ACE_HAS_TIUSER_H 1 - -/* Platform supports TLI. Also see ACE_TLI_TCP_DEVICE. */ -#define ACE_HAS_TLI 1 - -/* Platform provides TLI function prototypes */ -#define ACE_HAS_TLI_PROTOTYPES 1 - -/* Platform supports ualarm() */ -#define ACE_HAS_UALARM 1 - -/* Platform supports ucontext_t (which is used in the extended signal API). */ -#define ACE_HAS_UCONTEXT_T 1 - -/* Platform has header file */ -#define ACE_HAS_UTIME 1 - -/* Prints out console message in ACE_NOTSUP. Useful for tracking down origin - of ACE_NOTSUP. */ -/* #undef ACE_HAS_VERBOSE_NOTSUP */ - -/* Platform requires void * for mmap(). */ -#define ACE_HAS_VOIDPTR_MMAP 1 - -/* Platform has XTI (X/Open-standardized superset of TLI). Implies - ACE_HAS_TLI but uses a different header file. */ -#define ACE_HAS_XTI 1 - -/* Platform can not build ace/IOStream{,_T}.cpp. This does not necessarily - mean that the platform does not support iostreams. */ -#define ACE_LACKS_ACE_IOSTREAM 1 - -/* Platform does not have u_longlong_t typedef */ -#define ACE_LACKS_U_LONGLONG_T 1 - -/* Platform lacks madvise() (e.g., Linux) */ -#define ACE_LACKS_MADVISE 1 - -/* Platform lacks pri_t (e.g., Tandem NonStop UNIX). */ -#define ACE_LACKS_PRI_T 1 - -/* Platform lacks pthread_thr_sigsetmask (e.g., MVS, HP/UX, and OSF/1 3.2) */ -#define ACE_LACKS_PTHREAD_THR_SIGSETMASK 1 - -/* Platfrom lack pthread_yield() support. */ -#define ACE_LACKS_PTHREAD_YIELD 1 - -/* Platform lacks readers/writer locks. */ -#define ACE_LACKS_RWLOCK_T 1 - -/* MIT pthreads platform lacks the timedwait prototypes */ -#define ACE_LACKS_TIMEDWAIT_PROTOTYPES 1 - -/* Platform does not define timepec_t as a typedef for struct timespec. */ -#define ACE_LACKS_TIMESPEC_T 1 - -/* Compile using multi-thread libraries */ -#define ACE_MT_SAFE 1 - -/* Platform needs to #include to get thread scheduling defs. */ -#define ACE_NEEDS_SCHED_H 1 - -/* The OS/platform supports the poll() event demultiplexor */ -#define ACE_USE_POLL 1 - -/* Platform has its standard c++ library in the namespace std. */ -#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 - -/* The number of bytes in a double. */ -#define SIZEOF_DOUBLE 8 - -/* The number of bytes in a float. */ -#define SIZEOF_FLOAT 4 - -/* The number of bytes in a int. */ -#define SIZEOF_INT 4 - -/* The number of bytes in a long. */ -#define SIZEOF_LONG 4 - -/* The number of bytes in a long double. */ -#define SIZEOF_LONG_DOUBLE 12 - -/* The number of bytes in a long long. */ -#define SIZEOF_LONG_LONG 8 - -/* The number of bytes in a short. */ -#define SIZEOF_SHORT 2 - -/* The number of bytes in a signed char. */ -#define SIZEOF_SIGNED_CHAR 1 - -/* The number of bytes in a void *. */ -#define SIZEOF_VOID_P 4 - -/* Define if you have the execv function. */ -#define HAVE_EXECV 1 - -/* Define if you have the execve function. */ -#define HAVE_EXECVE 1 - -/* Define if you have the execvp function. */ -#define HAVE_EXECVP 1 - -/* Define if you have the header file. */ -#define HAVE_DIRENT_H 1 - -/* Define if you have the header file. */ -#define HAVE_FSTREAM 1 - -/* Define if you have the header file. */ -#define HAVE_IOMANIP 1 - -/* Define if you have the header file. */ -#define HAVE_IOSTREAM 1 - -/* Define if you have the header file. */ -#define HAVE_PWD_H 1 - -/* Name of package */ -#define PACKAGE "ace" - -/* Version number of package */ -#define VERSION "4.6.37" - -/* Added by Staller */ -#define ENUM_BOOLEAN // See file /usr/local/lib/gcc-lib/i486-pc-sysv5/egcs-2.91.60/include/sys/types.h -/* Hat nix gebracht -#define ACE_DEFAULT_SELECT_REACTOR_SIZE 256 // this is like in linux config fileto avoid another error -*/ -#define howmany(x, y) (((x)+((y)-1))/(y)) -#define ACE_HAS_BROKEN_T_ERROR // let disappear a nasty warning from OS.i -#if !defined (__USLC__) -# define __USLC__ 1 -#endif - -#define __IOCTL_VERSIONED__ // By Carlo! -#endif /* ACE_UNIXWARE_UDK_H */ diff --git a/externals/ace/config-visualage.h b/externals/ace/config-visualage.h deleted file mode 100644 index 4cef8108bc5..00000000000 --- a/externals/ace/config-visualage.h +++ /dev/null @@ -1,20 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-visualage.h 80826 2008-03-04 14:51:23Z wotte $ - -// This configuration file automatically includes the proper -// configurations for IBM's VisualAge C++ compiler on Win32 and AIX. - -#ifndef CONFIG_VISUALAGE_H -#define CONFIG_VISUALAGE_H -#include /**/ "ace/pre.h" - -#ifdef __TOS_WIN__ - #include "ace/config-win32.h" -#elif __TOS_AIX__ - #include "ace/config-aix-4.x.h" -#else - #include "PLATFORM NOT SPECIFIED" -#endif /* __TOS_WIN__ */ - -#include /**/ "ace/post.h" -#endif //CONFIG_VISUALAGE_H diff --git a/externals/ace/config-vxworks.h b/externals/ace/config-vxworks.h deleted file mode 100644 index fd4e04193c0..00000000000 --- a/externals/ace/config-vxworks.h +++ /dev/null @@ -1,57 +0,0 @@ -//* -*- C++ -*- */ -// $Id: config-vxworks.h 87036 2009-10-10 18:21:39Z johnnyw $ - -// The following configuration file is designed to work for VxWorks -// Based on ACE_VXWORKS it will select the correct config file - -#ifndef ACE_CONFIG_VXWORKS_H -#define ACE_CONFIG_VXWORKS_H -#include /**/ "ace/pre.h" - -// If ACE_VXWORKS is not defined try to figure out the VxWorks version -#if !defined (ACE_VXWORKS) -# include "vxWorks.h" -# if !defined (_WRS_VXWORKS_MAJOR) && !defined (_WRS_VXWORKS_MINOR) -# error You must define ACE_VXWORKS -# else -# if (_WRS_VXWORKS_MAJOR == 6) -# if (_WRS_VXWORKS_MINOR == 0) -# define ACE_VXWORKS 0x600 -# elif (_WRS_VXWORKS_MINOR == 1) -# define ACE_VXWORKS 0x610 -# elif (_WRS_VXWORKS_MINOR == 2) -# define ACE_VXWORKS 0x620 -# elif (_WRS_VXWORKS_MINOR == 3) -# define ACE_VXWORKS 0x630 -# elif (_WRS_VXWORKS_MINOR == 4) -# define ACE_VXWORKS 0x640 -# elif (_WRS_VXWORKS_MINOR == 5) -# define ACE_VXWORKS 0x650 -# elif (_WRS_VXWORKS_MINOR == 6) -# define ACE_VXWORKS 0x660 -# elif (_WRS_VXWORKS_MINOR == 7) -# define ACE_VXWORKS 0x670 -# elif (_WRS_VXWORKS_MINOR == 8) -# define ACE_VXWORKS 0x680 -# endif -# endif -# endif -#endif /* ! ACE_VXWORKS */ - -#if (ACE_VXWORKS == 0x640) -# include "ace/config-vxworks6.4.h" -#elif (ACE_VXWORKS == 0x650) -# include "ace/config-vxworks6.5.h" -#elif (ACE_VXWORKS == 0x660) -# include "ace/config-vxworks6.6.h" -#elif (ACE_VXWORKS == 0x670) -# include "ace/config-vxworks6.7.h" -#elif (ACE_VXWORKS == 0x680) -# include "ace/config-vxworks6.8.h" -#else -#error Unknown or unsupported VxWorks version -#endif - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_VXWORKS_H */ - diff --git a/externals/ace/config-vxworks6.4.h b/externals/ace/config-vxworks6.4.h deleted file mode 100644 index d1fad781985..00000000000 --- a/externals/ace/config-vxworks6.4.h +++ /dev/null @@ -1,350 +0,0 @@ -//* -*- C++ -*- */ -// $Id: config-vxworks6.4.h 89494 2010-03-15 20:11:18Z olli $ - -// The following configuration file is designed to work for VxWorks -// 6.4 platforms using one of these compilers: -// 1) The GNU g++ compiler that is shipped with VxWorks 6.4 -// 2) The Diab compiler that is shipped with VxWorks 6.4 - -#ifndef ACE_CONFIG_VXWORKS_6_4_H -#define ACE_CONFIG_VXWORKS_6_4_H -#include /**/ "ace/pre.h" - -#if ! defined (VXWORKS) -# define VXWORKS -#endif /* ! VXWORKS */ - -#if ! defined (ACE_VXWORKS) -# define ACE_VXWORKS 0x640 -#endif /* ! ACE_VXWORKS */ - -#if !defined (__RTP__) - // Fix for wrong typedef of time_t in kernel mode - #ifndef _TIME_T - #define _TIME_T - typedef long time_t; - #endif -#endif - -#if ! defined (__ACE_INLINE__) -# define __ACE_INLINE__ -#endif /* ! __ACE_INLINE__ */ - -// Compiler-specific configuration. -#if defined (__GNUG__) -# include "ace/config-g++-common.h" - -# define ACE_LACKS_IOSTREAM_FX -# define ACE_LACKS_LINEBUFFERED_STREAMBUF - -# if defined (__RTP__) && !defined (_HAS_C9X) -// Workaround for the fact that under RTP the log2 method can't be used -// without this define set, see TSR560446 -# if !defined (_C99) -# define _C99 -# endif -# endif - -#elif defined (__DCC__) -# define ACE_HAS_STANDARD_CPP_LIBRARY 1 -# define ACE_TEMPLATES_REQUIRE_SOURCE -#else /* ! __GNUG__ && ! ghs && !__DCC__ */ -# ifdef __cplusplus /* Let it slide for C compilers. */ -# error unsupported compiler on VxWorks -# endif /* __cplusplus */ -#endif /* ! __GNUG__ && ! ghs */ - -// Needed include to get all VxWorks CPU types -#include "types/vxCpu.h" -#if defined __RTP__ - #if defined (_VX_CPU) && (_VX_CPU == _VX_PENTIUM || _VX_CPU == _VX_PENTIUM2 || _VX_CPU == _VX_PENTIUM3 || _VX_CPU == _VX_PENTIUM4) - // If running an Intel Pentium the - // ACE_OS::gethrtime () can use the RDTSC instruction. - # define ACE_HAS_PENTIUM - #endif -#else - #if defined (CPU) && (CPU == PENTIUM || CPU == PENTIUM2 || CPU == PENTIUM3 || CPU == PENTIUM4) - // If running an Intel Pentium the - // ACE_OS::gethrtime () can use the RDTSC instruction. - # define ACE_HAS_PENTIUM - #endif -#endif - -#if !defined __RTP__ -# if defined (TOOL) && (TOOL == gnu) -# if defined (CPU) && (CPU == PPC85XX || CPU == PPC604 || CPU == PPC603 || CPU == PPC32) -// These PPC's do lack log2 in kernel mode -# define ACE_LACKS_LOG2 -# endif -# endif -#endif - -// OS-specific configuration -#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG -#define ACE_HAS_3_PARAM_READDIR_R -#define ACE_HAS_NONCONST_GETBY -#define ACE_HAS_NONCONST_INET_ADDR -#define ACE_HAS_NONCONST_SWAB -#define ACE_USES_INETLIB_H -#define ACE_USES_SELECTLIB_H -#define ACE_LACKS_UNIX_SYSLOG -#define ACE_DEFAULT_MAX_SOCKET_BUFSIZ 32768 -#define ACE_DEFAULT_THREAD_KEYS 16 -#define ACE_HAS_BROKEN_ACCEPT_ADDR -#define ACE_HAS_NONCONST_SENDMSG -#define ACE_HAS_NONCONST_WRITEV -#define ACE_HAS_CHARPTR_DL -#define ACE_HAS_CLOCK_GETTIME -#define ACE_HAS_CLOCK_SETTIME -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES -#define ACE_HAS_CPLUSPLUS_HEADERS -#define ACE_HAS_DIRENT -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT -#define ACE_HAS_MSG -#define ACE_HAS_NONCONST_READV -#define ACE_HAS_NONCONST_SELECT_TIMEVAL -#define ACE_HAS_NONSTATIC_OBJECT_MANAGER -#define ACE_HAS_POSIX_NONBLOCK -#define ACE_HAS_POSIX_TIME -#define ACE_HAS_REENTRANT_FUNCTIONS -#define ACE_HAS_SIGACTION_CONSTP2 -#define ACE_HAS_SIGINFO_T -#define ACE_HAS_SIGWAIT -#define ACE_HAS_SIG_ATOMIC_T -#define ACE_HAS_SOCKADDR_IN_SIN_LEN -#define ACE_HAS_SOCKADDR_IN6_SIN6_LEN -#define ACE_HAS_THREADS -#define ACE_HAS_SYSCTL -#define ACE_LACKS_ALPHASORT -#define ACE_LACKS_EXEC -#define ACE_LACKS_RLIMIT -#define ACE_LACKS_FILELOCKS -#define ACE_LACKS_FORK -#define ACE_LACKS_GETHOSTENT -#define ACE_LACKS_GETSERVBYNAME -#define ACE_LACKS_GETPROTOBYNAME -#define ACE_LACKS_GETPROTOBYNUMBER -#define ACE_LACKS_GETIPNODEBYADDR -#define ACE_LACKS_GETIPNODEBYNAME_IPV6 -#define ACE_LACKS_LSTAT -#define ACE_LACKS_MADVISE -#define ACE_LACKS_MALLOC_H -#define ACE_LACKS_MEMORY_H -#define ACE_LACKS_MKFIFO -#define ACE_LACKS_MKSTEMP -#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS -#define ACE_LACKS_SYS_PARAM_H -#define ACE_LACKS_PWD_FUNCTIONS -#define ACE_LACKS_READLINK -#define ACE_LACKS_REALPATH -#define ACE_LACKS_PIPE -#define ACE_LACKS_RWLOCK_T -#define ACE_LACKS_SBRK -#define ACE_LACKS_SEEKDIR -#define ACE_LACKS_SEMBUF_T -#define ACE_LACKS_SIGINFO_H -#define ACE_LACKS_SI_ADDR -#define ACE_LACKS_SOCKETPAIR -#define ACE_LACKS_STRRECVFD -#define ACE_LACKS_SYSV_SHMEM -#define ACE_LACKS_TELLDIR -#define ACE_LACKS_TIMESPEC_T -#define ACE_LACKS_TRUNCATE -#define ACE_LACKS_UCONTEXT_H -#define ACE_LACKS_USECONDS_T -#define ACE_LACKS_UMASK -#define ACE_LACKS_STRPTIME -#define ACE_LACKS_MKTEMP -#define ACE_LACKS_TEMPNAM -#define ACE_PAGE_SIZE 4096 -#define ACE_THR_PRI_FIFO_DEF 101 -#define ACE_THR_PRI_OTHER_DEF ACE_THR_PRI_FIFO_DEF -#define ACE_HAS_SIGTIMEDWAIT -#define ACE_HAS_SIGSUSPEND -#define ACE_HAS_GETIFADDRS - -#define ACE_LACKS_SETEGID -#define ACE_LACKS_SETPGID -#define ACE_LACKS_SETREGID -#define ACE_LACKS_SETREUID -#define ACE_LACKS_SETSID -#define ACE_LACKS_SETUID -#define ACE_LACKS_SETEUID -#define ACE_LACKS_GETEUID -#define ACE_LACKS_GETUID -#define ACE_LACKS_GETPGID -#define ACE_LACKS_GETEGID -#define ACE_LACKS_GETGID -#define ACE_LACKS_SETGID - -#define ACE_LACKS_SYS_UIO_H -#define ACE_LACKS_SYS_IPC_H -#define ACE_LACKS_SYS_SEM_H -#define ACE_LACKS_STROPTS_H -#define ACE_LACKS_SYS_MSG_H -#define ACE_LACKS_PWD_H -#define ACE_LACKS_SYS_SHM_H -#define ACE_LACKS_TERMIOS_H -#define ACE_LACKS_POLL_H -#define ACE_LACKS_FCNTL - -// Some string things -#define ACE_LACKS_ITOW -#define ACE_LACKS_WCSDUP -#define ACE_LACKS_WCSICMP -#define ACE_LACKS_WCSNICMP -#define ACE_LACKS_STRTOLL -#define ACE_LACKS_WCSTOLL -#define ACE_LACKS_STRTOULL -#define ACE_LACKS_WCSTOULL - -#define ACE_HAS_CHARPTR_SOCKOPT -#define ACE_LACKS_SYMLINKS -#define ACE_LACKS_ISCTYPE - -#if defined __RTP__ - // We are building for RTP mode - #if !defined (ACE_AS_STATIC_LIBS) - # define ACE_HAS_SVR4_DYNAMIC_LINKING - #endif - #define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R - #define ACE_LACKS_REGEX_H - #if defined ACE_HAS_PENTIUM - // Bug to workaround VxWorks 6.4 x86 - # define ACE_LACKS_PUTENV - #endif - #define ACE_HAS_SETENV - #define ACE_LACKS_STRCASECMP - #define ACE_HAS_3_PARAM_WCSTOK - #define ACE_HAS_WCHAR - #define ACE_HAS_VFWPRINTF - #define ACE_SIZEOF_WCHAR 2 - #define ACE_HAS_SHM_OPEN - #if defined (ACE_AS_STATIC_LIBS) - # define ACE_HAS_AIO_CALLS - #endif - // VxWorks seems to either not define this or define as zero up till now - #if !defined (IOV_MAX) || (IOV_MAX == 0) - #define ACE_IOV_MAX 16 - #endif - #define ACE_LACKS_ISASCII -#else - // We are building for kernel mode - #define ACE_LACKS_SETENV - #define ACE_LACKS_UNSETENV - #define ACE_LACKS_SUSECONDS_T - #define ACE_LACKS_INTPTR_T - #define ACE_LACKS_INTTYPES_H - #define ACE_LACKS_STDINT_H - #define ACE_LACKS_UNAME - #define ACE_LACKS_UTSNAME_T - #define ACE_LACKS_RAND_REENTRANT_FUNCTIONS - #define ACE_LACKS_DLFCN_H - #define ACE_LACKS_WAIT - #define ACE_LACKS_WAITPID - #define ACE_LACKS_SYS_TIME_H - #define ACE_LACKS_SYS_SELECT_H - #define ACE_MKDIR_LACKS_MODE - #define ACE_HAS_SIZET_PTR_ASCTIME_R_AND_CTIME_R - #define ACE_LACKS_SEARCH_H - #define ACE_LACKS_SYSCONF - #define ACE_LACKS_GETPPID - #define ACE_LACKS_WCHAR_H - #define ACE_LACKS_WCTYPE_H - #define ACE_LACKS_WCSCAT - #define ACE_LACKS_WCSCHR - #define ACE_LACKS_WCSCMP - #define ACE_LACKS_WCSCPY - #define ACE_LACKS_WCSCSPN - #define ACE_LACKS_WCSLEN - #define ACE_LACKS_WCSNCAT - #define ACE_LACKS_WCSNCMP - #define ACE_LACKS_WCSNCPY - #define ACE_LACKS_WCSPBRK - #define ACE_LACKS_WCSRCHR - #define ACE_LACKS_WCSSPN - #define ACE_LACKS_WCSSTR - #define ACE_LACKS_WCSTOK - #define ACE_LACKS_TOWLOWER - #define ACE_LACKS_TOWUPPER - #define ACE_LACKS_WCSTOD - #define ACE_LACKS_WCSTOL - #define ACE_LACKS_WCSTOUL - #define ACE_LACKS_FGETWC - #define ACE_LACKS_FGETWS - #define ACE_LACKS_FPUTWS - #define ACE_HAS_IOCTL_INT_3_PARAM - #define ACE_LACKS_MMAP - #define ACE_LACKS_MSYNC - #define ACE_LACKS_MPROTECT - #if !defined (ACE_MAIN) - # define ACE_MAIN ace_main - #endif /* ! ACE_MAIN */ - #define ACE_LACKS_TZSET - #define ACE_LACKS_ISWCTYPE - #define ACE_LACKS_ISBLANK -#endif - -// It is possible to enable pthread support with VxWorks, when the user decides -// to use this, we need some more defines -#if defined ACE_HAS_PTHREADS -# define ACE_HAS_THREAD_SPECIFIC_STORAGE -# if !defined __RTP__ -# define ACE_LACKS_PTHREAD_ATTR_SETSTACK -# endif -# define ACE_HAS_PTHREAD_ATTR_SETNAME -# define ACE_HAS_POSIX_SEM -# define ACE_LACKS_MUTEXATTR_PSHARED -# define ACE_LACKS_CONDATTR_PSHARED -// Include this file, the sys/stat.h file shipped with VxWorks has old types -// and without this include we get a lot of compile errors. A TSR has been filed -// so that hopefully in the future we can zap this include -#include "types/vxTypesOld.h" -#else -# define ACE_LACKS_PTHREAD_H -# define ACE_HAS_VXTHREADS -# if !defined __RTP__ -// Only when building for kernel mode we can use TSS emulation, in rtp mode -// we can't use the WIND_TCB struct anymore -# define ACE_HAS_TSS_EMULATION -# if !defined (ACE_VXWORKS_SPARE) -# define ACE_VXWORKS_SPARE spare4 -# endif /* ! ACE_VXWORKS_SPARE */ -# endif -// VxWorks has no recursive mutexes. This was set in the past but it doesn't -// work with the pthread support, so only set it for the time being when pthread -// is disabled -# define ACE_HAS_RECURSIVE_MUTEXES -# define ACE_LACKS_COND_T -# define ACE_HAS_MUTEX_TIMEOUTS -#endif - -#if !defined (ACE_MT_SAFE) -# define ACE_MT_SAFE 1 -#endif - -// VxWorks defines the CPU define MAP, undef it to prevent problems with -// application code -#if defined (MAP) -#undef MAP -#endif /* MAP */ - -#if !defined (ACE_NEEDS_HUGE_THREAD_STACKSIZE) -# define ACE_NEEDS_HUGE_THREAD_STACKSIZE 65536 -#endif /* ACE_NEEDS_HUGE_THREAD_STACKSIZE */ - -#if !defined (ACE_NTRACE) -# define ACE_NTRACE 1 -#endif /* ACE_NTRACE */ - -// By default, don't include RCS Id strings in object code. -#if !defined (ACE_USE_RCSID) -#define ACE_USE_RCSID 0 -#endif /* !ACE_USE_RCSID */ - -#if defined (ACE_HAS_IP_MULTICAST) -# define ACE_LACKS_PERFECT_MULTICAST_FILTERING 1 -#endif /* ACE_HAS_IP_MULTICAST */ - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_VXWORKS_6_4_H */ diff --git a/externals/ace/config-vxworks6.5.h b/externals/ace/config-vxworks6.5.h deleted file mode 100644 index 19273e6cad4..00000000000 --- a/externals/ace/config-vxworks6.5.h +++ /dev/null @@ -1,25 +0,0 @@ -//* -*- C++ -*- */ -// $Id: config-vxworks6.5.h 80826 2008-03-04 14:51:23Z wotte $ - -// The following configuration file is designed to work for VxWorks -// 6.5 platforms using one of these compilers: -// 1) The GNU g++ compiler that is shipped with VxWorks 6.5 -// 2) The Diab compiler that is shipped with VxWorks 6.5 - -#ifndef ACE_CONFIG_VXWORKS_6_5_H -#define ACE_CONFIG_VXWORKS_6_5_H -#include /**/ "ace/pre.h" - -#if !defined (ACE_VXWORKS) -# define ACE_VXWORKS 0x650 -#endif /* ! ACE_VXWORKS */ - -#include "ace/config-vxworks6.4.h" - -#if defined (__RTP__) -# undef ACE_HAS_GETIFADDRS -#endif - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_VXWORKS_6_5_H */ - diff --git a/externals/ace/config-vxworks6.6.h b/externals/ace/config-vxworks6.6.h deleted file mode 100644 index eebce4432b6..00000000000 --- a/externals/ace/config-vxworks6.6.h +++ /dev/null @@ -1,34 +0,0 @@ -//* -*- C++ -*- */ -// $Id: config-vxworks6.6.h 85143 2009-04-22 09:15:08Z johnnyw $ - -// The following configuration file is designed to work for VxWorks -// 6.6 platforms using one of these compilers: -// 1) The GNU g++ compiler that is shipped with VxWorks 6.6 -// 2) The Diab compiler that is shipped with VxWorks 6.6 - -#ifndef ACE_CONFIG_VXWORKS_6_6_H -#define ACE_CONFIG_VXWORKS_6_6_H -#include /**/ "ace/pre.h" - -#if !defined (ACE_VXWORKS) -# define ACE_VXWORKS 0x660 -#endif /* ! ACE_VXWORKS */ - -#include "ace/config-vxworks6.5.h" - -#if defined (ACE_HAS_PENTIUM) -# define ACE_LACKS_LOG2 -#endif - -#if !defined (__RTP__) -# undef ACE_HAS_IOCTL_INT_3_PARAM -# define ACE_HAS_TASKCPUAFFINITYSET -#endif - -#define ACE_HAS_VXATOMICLIB -#define ACE_HAS_CPUSET_T -#define ACE_HAS_VXCPULIB - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_VXWORKS_6_6_H */ - diff --git a/externals/ace/config-vxworks6.7.h b/externals/ace/config-vxworks6.7.h deleted file mode 100644 index eab429a2e94..00000000000 --- a/externals/ace/config-vxworks6.7.h +++ /dev/null @@ -1,23 +0,0 @@ -//* -*- C++ -*- */ -// $Id: config-vxworks6.7.h 84971 2009-03-25 13:03:44Z johnnyw $ - -// The following configuration file is designed to work for VxWorks -// 6.7 platforms using one of these compilers: -// 1) The GNU g++ compiler that is shipped with VxWorks 6.7 -// 2) The Diab compiler that is shipped with VxWorks 6.7 - -#ifndef ACE_CONFIG_VXWORKS_6_7_H -#define ACE_CONFIG_VXWORKS_6_7_H -#include /**/ "ace/pre.h" - -#if !defined (ACE_VXWORKS) -# define ACE_VXWORKS 0x670 -#endif /* ! ACE_VXWORKS */ - -#include "ace/config-vxworks6.6.h" - -#undef ACE_HAS_NONCONST_INET_ADDR - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_VXWORKS_6_7_H */ - diff --git a/externals/ace/config-vxworks6.8.h b/externals/ace/config-vxworks6.8.h deleted file mode 100644 index ecad4752d95..00000000000 --- a/externals/ace/config-vxworks6.8.h +++ /dev/null @@ -1,21 +0,0 @@ -//* -*- C++ -*- */ -// $Id: config-vxworks6.8.h 87036 2009-10-10 18:21:39Z johnnyw $ - -// The following configuration file is designed to work for VxWorks -// 6.8 platforms using one of these compilers: -// 1) The GNU g++ compiler that is shipped with VxWorks 6.8 -// 2) The Diab compiler that is shipped with VxWorks 6.8 - -#ifndef ACE_CONFIG_VXWORKS_6_8_H -#define ACE_CONFIG_VXWORKS_6_8_H -#include /**/ "ace/pre.h" - -#if !defined (ACE_VXWORKS) -# define ACE_VXWORKS 0x680 -#endif /* ! ACE_VXWORKS */ - -#include "ace/config-vxworks6.7.h" - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_VXWORKS_6_8_H */ - diff --git a/externals/ace/config-win32-borland.h b/externals/ace/config-win32-borland.h deleted file mode 100644 index c3ae460482b..00000000000 --- a/externals/ace/config-win32-borland.h +++ /dev/null @@ -1,174 +0,0 @@ -// -*- C++ -*- -//$Id: config-win32-borland.h 89292 2010-03-04 08:06:15Z johnnyw $ - -// The following configuration file contains defines for Borland compilers. - -#ifndef ACE_CONFIG_WIN32_BORLAND_H -#define ACE_CONFIG_WIN32_BORLAND_H -#include /**/ "ace/pre.h" - -#ifndef ACE_CONFIG_WIN32_H -#error Use config-win32.h in config.h instead of this header -#endif /* ACE_CONFIG_WIN32_H */ - -#define ACE_HAS_CUSTOM_EXPORT_MACROS -#define ACE_Proper_Export_Flag __declspec (dllexport) -#define ACE_Proper_Import_Flag __declspec (dllimport) -#define ACE_EXPORT_SINGLETON_DECLARATION(T) template class __declspec (dllexport) T -#define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) template class __declspec (dllexport) SINGLETON_TYPE; -#define ACE_IMPORT_SINGLETON_DECLARATION(T) template class __declspec (dllimport) T -#define ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) template class __declspec (dllimport) SINGLETON_TYPE ; - -// In later versions of C++Builder we will prefer inline functions by -// default. The debug configuration of ACE is built with functions -// out-of-line, so when linking your application against a debug ACE -// build, you can choose to use the out-of-line functions by adding -// ACE_NO_INLINE=1 to your project settings. -# if !defined (__ACE_INLINE__) -# define __ACE_INLINE__ 1 -# endif /* __ACE_INLINE__ */ - -# define ACE_CC_NAME ACE_TEXT ("Embarcadero C++ Builder") -# define ACE_CC_MAJOR_VERSION (__BORLANDC__ / 0x100) -# define ACE_CC_MINOR_VERSION (__BORLANDC__ % 0x100) -# define ACE_CC_BETA_VERSION (0) - -#ifndef ACE_USING_MCPP_PREPROCESSOR -# if (__BORLANDC__ >= 0x620) -# define ACE_CC_PREPROCESSOR_ARGS "-q -Sl -o%s" -# else -# define ACE_CC_PREPROCESSOR_ARGS "-q -P- -o%s" -# endif -#endif - -// Automatically define WIN32 macro if the compiler tells us it is our -// target platform. -# if defined (__WIN32__) && !defined (WIN32) -# define WIN32 1 -# endif - -// When building a VCL application, the main VCL header file should be -// included before anything else. You can define ACE_HAS_VCL=1 in your -// project settings to have this file included for you automatically. -# if defined (ACE_HAS_VCL) && (ACE_HAS_VCL != 0) -# include /**/ -# endif - -# define ACE_CC_PREPROCESSOR "CPP32.EXE" - -# include "ace/config-win32-common.h" - -# define ACE_WSTRING_HAS_USHORT_SUPPORT 1 -# define ACE_HAS_DIRENT - -#define ACE_USES_STD_NAMESPACE_FOR_STDC_LIB 1 - -#define ACE_NEEDS_DL_UNDERSCORE - -#define ACE_LACKS_TERMIOS_H -#define ACE_LACKS_NETINET_TCP_H -#define ACE_LACKS_REGEX_H -#define ACE_LACKS_SYS_MSG_H -#define ACE_LACKS_PWD_H -#define ACE_LACKS_POLL_H -#define ACE_LACKS_SYS_SHM_H -#define ACE_LACKS_STRINGS_H -#define ACE_LACKS_SEMAPHORE_H -#define ACE_LACKS_INTTYPES_H -#define ACE_LACKS_UCONTEXT_H -#define ACE_LACKS_SYS_SELECT_H -#define ACE_LACKS_SYS_TIME_H -#define ACE_LACKS_SYS_RESOURCE_H -#define ACE_LACKS_SYS_WAIT_H -#define ACE_LACKS_DLFCN_H -#define ACE_LACKS_SYS_MMAN_H -#define ACE_LACKS_SYS_UIO_H -#define ACE_LACKS_SYS_SOCKET_H -#define ACE_LACKS_NETINET_IN_H -#define ACE_LACKS_NETDB_H -#define ACE_LACKS_NET_IF_H -#define ACE_LACKS_SYS_IPC_H -#define ACE_LACKS_SYS_SEM_H -#define ACE_LACKS_SYS_IOCTL_H -#define ACE_LACKS_STROPTS_H - -#undef ACE_LACKS_STRUCT_DIR -#undef ACE_LACKS_CLOSEDIR -#undef ACE_LACKS_OPENDIR -#undef ACE_LACKS_READDIR -#undef ACE_LACKS_REWINDDIR - -#define ACE_HAS_WOPENDIR -#define ACE_HAS_WCLOSEDIR -#define ACE_HAS_WREADDIR -#define ACE_HAS_WREWINDDIR - -#define ACE_LACKS_STRRECVFD -#define ACE_USES_EXPLICIT_STD_NAMESPACE - -#define ACE_HAS_TIME_T_LONG_MISMATCH - -#define ACE_EXPORT_NESTED_CLASSES 1 -#define ACE_HAS_CPLUSPLUS_HEADERS 1 -#define ACE_HAS_EXCEPTIONS -#define ACE_HAS_NONCONST_SELECT_TIMEVAL -#define ACE_HAS_SIG_ATOMIC_T -#define ACE_HAS_STANDARD_CPP_LIBRARY 1 -#define ACE_HAS_STDCPP_STL_INCLUDES 1 -#define ACE_HAS_STRING_CLASS 1 -#define ACE_HAS_TEMPLATE_TYPEDEFS 1 -#define ACE_HAS_USER_MODE_MASKS 1 -#define ACE_LACKS_ACE_IOSTREAM 1 -#define ACE_LACKS_LINEBUFFERED_STREAMBUF 1 -#define ACE_HAS_NEW_NOTHROW -#define ACE_TEMPLATES_REQUIRE_SOURCE 1 -#define ACE_SIZEOF_LONG_DOUBLE 10 -#define ACE_UINT64_FORMAT_SPECIFIER_ASCII "%Lu" -#define ACE_INT64_FORMAT_SPECIFIER_ASCII "%Ld" -#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 -#define ACE_USES_STD_NAMESPACE_FOR_ABS 1 -#define ACE_ENDTHREADEX(STATUS) ::_endthreadex ((DWORD) STATUS) - -#if defined(ACE_MT_SAFE) && (ACE_MT_SAFE != 0) -// must have _MT defined to include multithreading -// features from win32 headers -# if !defined(__MT__) -// *** DO NOT *** defeat this error message by defining __MT__ yourself. -// You must link with the multi threaded libraries. Add -tWM to your -// compiler options -# error You must link against multi-threaded libraries when using ACE (check your project settings) -# endif /* !_MT && !ACE_HAS_WINCE */ -#endif /* ACE_MT_SAFE && ACE_MT_SAFE != 0 */ - -#if (__BORLANDC__ < 0x620) -# define ACE_LACKS_ISBLANK -# define ACE_LACKS_ISWBLANK -# define ACE_LACKS_PRAGMA_ONCE 1 -#endif - -#define ACE_LACKS_ISWCTYPE -#define ACE_LACKS_ISCTYPE - -#if (__BORLANDC__ < 0x620) -// Older Borland compilers can't handle assembly in inline methods or -// templates (E2211). When we build for pentium optimized and we are inlining -// then we disable inline assembly -# if defined (ACE_HAS_PENTIUM) && defined(__ACE_INLINE__) -# define ACE_LACKS_INLINE_ASSEMBLY -# endif -#endif - -#if (__BORLANDC__ == 0x621) -// C++ Builder 2010 wcsncat seems broken -# define ACE_LACKS_WCSNCAT -#endif - -#define ACE_WCSDUP_EQUIVALENT ::_wcsdup -#define ACE_STRCASECMP_EQUIVALENT ::stricmp -#define ACE_STRNCASECMP_EQUIVALENT ::strnicmp -#define ACE_WTOF_EQUIVALENT ::_wtof -#define ACE_FILENO_EQUIVALENT(X) (_get_osfhandle (::_fileno (X))) -#define ACE_HAS_ITOA 1 - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_WIN32_BORLAND_H */ diff --git a/externals/ace/config-win32-cegcc.h b/externals/ace/config-win32-cegcc.h deleted file mode 100644 index c29290d713f..00000000000 --- a/externals/ace/config-win32-cegcc.h +++ /dev/null @@ -1,113 +0,0 @@ -// -*- C++ -*- -// $Id: config-win32-cegcc.h 87167 2009-10-19 19:33:53Z olli $ - -// -// The following configuration file is designed to work for win32 -// platforms using gcc/g++ with mingw32 (http://www.mingw.org). -// - -#ifndef ACE_CONFIG_WIN32_CEGCC_H -#define ACE_CONFIG_WIN32_CEGCC_H -#include /**/ "ace/pre.h" - -#ifndef ACE_CONFIG_WIN32_H -# error Use config-win32.h in config.h instead of this header -#endif /* ACE_CONFIG_WIN32_H */ - -#define ACE_CC_NAME ACE_TEXT ("g++") -#define ACE_CC_PREPROCESSOR "cpp" -#define ACE_CC_PREPROCESOR_ARGS "" - -// Why all this is not in config-g++-common.h? -#define ACE_CC_MAJOR_VERSION __GNUC__ -#define ACE_CC_MINOR_VERSION __GNUC_MINOR__ -#define ACE_CC_BETA_VERSION (0) - -#if !defined (ACE_HAS_CEGCC) -# error You do not seem to be using cegcc -#endif - -// We trust the user: He must have used -mpentiumpro or -mpentium -// if that is what he wants. -#if defined(pentiumpro) || defined(pentium) -# define ACE_HAS_PENTIUM -#endif - -#include "ace/config-g++-common.h" - -#include /**/ -#include /**/ -#include /**/ <_mingw.h> - -#if (__MINGW32_MAJOR_VERSION > 3) || ((__MINGW32_MAJOR_VERSION == 3) && (__MINGW32_MINOR_VERSION >= 15)) -# undef ACE_LACKS_USECONDS_T -#endif - -#define ACE_HAS_USER_MODE_MASKS - -#define ACE_HAS_SSIZE_T -#undef ACE_LACKS_STRUCT_DIR -#undef ACE_LACKS_OPENDIR -#undef ACE_LACKS_CLOSEDIR -#undef ACE_LACKS_READDIR -#undef ACE_LACKS_TELLDIR -#undef ACE_LACKS_SEEKDIR -#undef ACE_LACKS_REWINDDIR - -#undef ACE_HAS_WTOF - -#define ACE_LACKS_SYS_SHM_H -#define ACE_LACKS_TERMIOS_H -#define ACE_LACKS_NETINET_TCP_H -#define ACE_LACKS_STRRECVFD -#define ACE_LACKS_STRPTIME -#define ACE_LACKS_POLL_H -#define ACE_LACKS_REGEX_H -#define ACE_LACKS_SYS_MSG_H -#define ACE_LACKS_PWD_H -#define ACE_LACKS_SEMAPHORE_H -#define ACE_LACKS_UCONTEXT_H -#define ACE_LACKS_SYS_SELECT_H -#define ACE_LACKS_SYS_RESOURCE_H -#define ACE_LACKS_SYS_WAIT_H -#define ACE_LACKS_DLFCN_H -#define ACE_LACKS_SYS_MMAN_H -#define ACE_LACKS_SYS_UIO_H -#define ACE_LACKS_SYS_SOCKET_H -#define ACE_LACKS_NETINET_IN_H -#define ACE_LACKS_NETDB_H -#define ACE_LACKS_NET_IF_H -#define ACE_LACKS_SYS_IPC_H -#define ACE_LACKS_SYS_SEM_H -#define ACE_LACKS_STROPTS_H -#define ACE_LACKS_SYS_IOCTL_H -#define ACE_LACKS_PDH_H -#define ACE_LACKS_PDHMSG_H -#define ACE_HAS_NONCONST_WCSDUP -#define ACE_HAS_WINSOCK2_GQOS -#define ACE_LACKS_CORRECT_ISWPRINT_TAB - -//Changes to compile on CE gcc. -#undef ACE_HAS_TYPES_H -#define ACE_LACKS_ERRNO_H -#undef ACE_LACKS_DEV_T -#define ACE_LACKS_ISCTYPE -#define ACE_HAS_NONCONST_WFDOPEN -#undef ACE_HAS_WTOI -#undef ACE_HAS_WTOL - -#define ACE_INT64_FORMAT_SPECIFIER_ASCII "%I64d" -#define ACE_UINT64_FORMAT_SPECIFIER_ASCII "%I64u" -#define ACE_ENDTHREADEX(STATUS) ExitThread ((DWORD) STATUS) - -#define ACE_Proper_Export_Flag __declspec (dllexport) -#define ACE_Proper_Import_Flag __declspec (dllimport) -#define ACE_EXPORT_SINGLETON_DECLARATION(T) template class __declspec (dllexport) T -#define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) template class __declspec (dllexport) SINGLETON_TYPE; -#define ACE_IMPORT_SINGLETON_DECLARATION(T) extern template class T -#define ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) extern template class SINGLETON_TYPE ; - -#define ACE_DLL_PREFIX ACE_TEXT ("lib") - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_WIN32_CEGCC_H */ diff --git a/externals/ace/config-win32-common.h b/externals/ace/config-win32-common.h deleted file mode 100644 index 0160a3742a1..00000000000 --- a/externals/ace/config-win32-common.h +++ /dev/null @@ -1,701 +0,0 @@ -/* -*- C++ -*- */ -// $Id: config-win32-common.h 88567 2010-01-15 10:21:49Z olli $ - - -#ifndef ACE_CONFIG_WIN32_COMMON_H -#define ACE_CONFIG_WIN32_COMMON_H -#include /**/ "ace/pre.h" - -#ifndef ACE_CONFIG_WIN32_H -#error Use config-win32.h in config.h instead of this header -#endif /* ACE_CONFIG_WIN32_H */ - - -// Windows Mobile (CE) stuff is primarily further restrictions to what's -// in the rest of this file. Also, it defined ACE_HAS_WINCE, which is used -// in this file. -#if defined (_WIN32_WCE) -# include "ace/config-WinCE.h" -#endif /* _WIN32_WCE */ - -// Complain if WIN32 is not already defined. -#if !defined (WIN32) && !defined (ACE_HAS_WINCE) -# error Please define WIN32 in your project settings. -#endif - -#define ACE_WIN32 -#if defined (_WIN64) || defined (WIN64) -# define ACE_WIN64 - -// Use 64-bit file offsets by default in the WIN64 case, similar to -// what 64-bit UNIX systems do. -// -// Note that _FILE_OFFSET_BITS is not recognized by Windows. It is, -// however, recognized by ACE. -# ifndef _FILE_OFFSET_BITS -# define _FILE_OFFSET_BITS 64 -# endif /* !_FILE_OFFSET_BITS */ -#endif /* _WIN64 || WIN64 */ - -#if !defined (_WIN32_WINNT) -# define _WIN32_WINNT 0x0501 // pretend it's at least Windows XP or Win2003 -#endif - -// If the invoking procedure turned off debugging by setting NDEBUG, then -// also set ACE_NDEBUG, unless the user has already set it. -#if defined (NDEBUG) -# if !defined (ACE_NDEBUG) -# define ACE_NDEBUG -# endif /* ACE_NDEBUG */ -#endif /* NDEBUG */ - -// Define ACE_HAS_MFC to 1, if you want ACE to use CWinThread. This should -// be defined, if your application uses MFC. -// Setting applies to : building ACE -// Runtime restrictions: MFC DLLs must be installed -// Additonal notes : If both ACE_HAS_MFC and ACE_MT_SAFE are -// defined, the MFC DLL (not the static lib) -// will be used from ACE. -#if !defined (ACE_HAS_MFC) -# define ACE_HAS_MFC 0 -#endif - -// ACE_USES_STATIC_MFC always implies ACE_HAS_MFC -#if defined (ACE_USES_STATIC_MFC) -# if defined (ACE_HAS_MFC) -# undef ACE_HAS_MFC -# endif -# define ACE_HAS_MFC 1 -#endif /* ACE_USES_STATIC_MFC */ - -// Define ACE_HAS_STRICT to 1 in your config.h file if you want to use -// STRICT type checking. It is disabled by default because it will -// break existing application code. However, if ACE_HAS_MFC is turned on, -// ACE_HAS_STRICT is required by MFC. -// Setting applies to : building ACE, linking with ACE -// Runtime restrictions: - -#if !defined (ACE_HAS_STRICT) -# define ACE_HAS_STRICT 0 -#endif - -// MFC itself defines STRICT. -#if defined (ACE_HAS_MFC) && (ACE_HAS_MFC != 0) -# undef ACE_HAS_STRICT -# define ACE_HAS_STRICT 1 -#endif - -// Turn off the following define if you want to disable threading. -// Compile using multi-thread libraries. -// Setting applies to : building ACE, linking with ACE -// Runtime restrictions: multithreaded runtime DLL must be installed -#if !defined (ACE_MT_SAFE) -# define ACE_MT_SAFE 1 -#endif - -// On winCE these classes do not exist. If they are -// introduced in the future, no changes need to be made -#if defined (ABOVE_NORMAL_PRIORITY_CLASS) && \ - defined (BELOW_NORMAL_PRIORITY_CLASS) && \ - defined (HIGH_PRIORITY_CLASS) && \ - defined (IDLE_PRIORITY_CLASS) && \ - defined (NORMAL_PRIORITY_CLASS) && \ - defined (REALTIME_PRIORITY_CLASS) -#define ACE_HAS_WIN32_PRIORITY_CLASS -#endif - -// Build ACE services as DLLs. If you write a library and want it to -// use ACE_Svc_Export, this will cause those macros to build dlls. If -// you want your ACE service to be a static library, comment out this -// line. As far as I know, the only reason to have a library be an -// ACE "service" is to leverage the ACE_Svc_Export macros. It's just -// as easy to define your own export macros. -// #if !defined (ACE_SVC_HAS_DLL) -// # define ACE_SVC_HAS_DLL 1 -// #endif - -// Define the special export macros needed to export symbols outside a dll -#if !defined(__BORLANDC__) && !defined (ACE_HAS_CUSTOM_EXPORT_MACROS) -#define ACE_HAS_CUSTOM_EXPORT_MACROS 1 -#define ACE_Proper_Export_Flag __declspec (dllexport) -#define ACE_Proper_Import_Flag __declspec (dllimport) -#define ACE_EXPORT_SINGLETON_DECLARATION(T) template class __declspec (dllexport) T -#define ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) template class __declspec (dllexport) SINGLETON_TYPE; -#define ACE_IMPORT_SINGLETON_DECLARATION(T) extern template class T -#define ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) extern template class SINGLETON_TYPE ; -#endif /* !__BORLANDC__ */ - -// Define ACE_HAS_WINSOCK2 to 0 in your config.h file if you do *not* -// want to compile with WinSock 2.0. -// Setting applies to : building ACE -// Runtime restrictions: winsock2 must be installed. -// #define ACE_HAS_WINSOCK2 0 - -// By default, we use non-static object manager on Win32. That is, -// the object manager is allocated in main's stack memory. If this -// does not suit your need, i.e., if your programs depend on the use -// of static object manager, you neet to disable the behavior by adding -// -// #undef ACE_HAS_NONSTATIC_OBJECT_MANAGER -// -// in the config.h after including config-win32.h -// -// MFC users: the main function is defined within a MFC library and -// therefore, ACE won't be able to meddle with main function and -// instantiate the non-static object manager for you. To solve the -// problem, you'll need to instantiate the ACE_Object_Manager by -// either: -// -// 1. Using static object manager (as described above), however, using -// the non-static object manager is prefered, therefore, -// 2. Instantiate the non-static object manager yourself by either 1) -// call ACE::init () at the beginning and ACE::fini () at the end, -// _or_ 2) instantiate the ACE_Object_Manager in your CWinApp -// derived class. -// -// Optionally, you can #define -// ACE_DOESNT_INSTANTIATE_NONSTATIC_OBJECT_MANAGER in your -// ace/config.h and always take care of the business by yourself. -// ACE_DOESNT_INSTANTIATE_NONSTATIC_OBJECT_MANAGER has no effect when -// using static object managers. -#if !defined (ACE_HAS_NONSTATIC_OBJECT_MANAGER) -# define ACE_HAS_NONSTATIC_OBJECT_MANAGER -#endif /* ACE_HAS_NONSTATIC_OBJECT_MANAGER */ - -#define ACE_HAS_GPERF - -// By default, don't include RCS Id strings in object code. -#if !defined (ACE_USE_RCSID) -# define ACE_USE_RCSID 0 -#endif /* ! ACE_USE_RCSID */ - -// ---------------- platform features or lack of them ------------- - -// By default WIN32 has FD_SETSIZE of 64, which places the limit -// between 61 and 64 on the number of clients a server using the -// Select Reactor can support at the same time (i.e., 64 - standard in, -// out, error). Here we raise the limit to 1024. Adjust the definition -// below if you need to raise or lower it. - -#if !defined (FD_SETSIZE) -#define FD_SETSIZE 1024 -#endif /* FD_SETSIZE */ - - -// Windows doesn't like 65536 ;-) If 65536 is specified, it is -// silently ignored by the OS, i.e., setsockopt does not fail, and you -// get stuck with the default size of 8k. -#define ACE_DEFAULT_MAX_SOCKET_BUFSIZ 65535 - -// It seems like Win32 does not have a limit on the number of buffers -// that can be transferred by the scatter/gather type of I/O -// functions, e.g., WSASend and WSARecv. We are setting this to be 64 -// for now. The typically use case is to create an I/O vector array -// of size ACE_IOV_MAX on the stack and then filled in. Note that we -// probably don't want too big a value for ACE_IOV_MAX since it may -// mostly go to waste or the size of the activation record may become -// excessively large. -#if !defined (ACE_IOV_MAX) -# define ACE_IOV_MAX 64 -#endif /* ACE_IOV_MAX */ - -#if !defined (ACE_HAS_WINCE) -// Platform supports pread() and pwrite() -# define ACE_HAS_WTOF -#endif /* ! ACE_HAS_WINCE */ - -#define ACE_HAS_P_READ_WRITE - -#if !defined (ACE_HAS_WINCE) -# define ACE_HAS_DIRECT_H -# define ACE_HAS_PROCESS_H -# define ACE_HAS_IO_H -#endif /* ! ACE_HAS_WINCE */ - -#if !defined (__MINGW32__) -# define ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS -#endif /* __MINGW32__ */ - -#define ACE_DEFAULT_THREAD_PRIORITY 0 - -#define ACE_HAS_DIRENT -#define ACE_HAS_MSG -#define ACE_HAS_RECURSIVE_MUTEXES -#define ACE_HAS_SOCKADDR_MSG_NAME -#define ACE_HAS_THREAD_SAFE_ACCEPT - -/* LACKS dir-related facilities */ -#define ACE_LACKS_READDIR_R -#define ACE_LACKS_REWINDDIR -#define ACE_LACKS_SEEKDIR -#define ACE_LACKS_TELLDIR - -/* LACKS gid/pid/sid/uid facilities */ -#define ACE_LACKS_GETPGID -#define ACE_LACKS_GETPPID -#define ACE_LACKS_SETPGID -#define ACE_LACKS_SETREGID -#define ACE_LACKS_SETREUID -#define ACE_LACKS_SETSID -#define ACE_LACKS_SETEGID -#define ACE_LACKS_SETUID -#define ACE_LACKS_SETEUID -#define ACE_LACKS_GETGID -#define ACE_LACKS_GETEGID -#define ACE_LACKS_GETUID -#define ACE_LACKS_GETEUID -#define ACE_LACKS_SETGID - -/* LACKS miscellaneous */ -#define ACE_LACKS_ALARM -#define ACE_LACKS_ARPA_INET_H -#define ACE_LACKS_DUP2 -#define ACE_LACKS_FORK -#define ACE_LACKS_GETHOSTENT -#define ACE_LACKS_GETOPT -#define ACE_LACKS_GETIPNODEBYNAME_IPV6 -#define ACE_LACKS_KILL -#define ACE_LACKS_INET_ATON -#define ACE_LACKS_MADVISE -#define ACE_LACKS_MKFIFO -#define ACE_LACKS_MODE_MASKS -#define ACE_LACKS_PTHREAD_H -#define ACE_LACKS_PWD_FUNCTIONS -#define ACE_LACKS_READLINK -#define ACE_LACKS_RLIMIT -#define ACE_LACKS_SBRK -#define ACE_LACKS_SCHED_H -#define ACE_LACKS_SEMBUF_T -#define ACE_LACKS_SIGACTION -#define ACE_LACKS_SIGSET -#define ACE_LACKS_SOCKETPAIR -#define ACE_LACKS_SUSECONDS_T -#define ACE_LACKS_USECONDS_T -#define ACE_LACKS_SYS_PARAM_H -#define ACE_LACKS_SYS_SYSCTL_H -#define ACE_LACKS_SYSCONF -#define ACE_LACKS_SYSV_SHMEM -#define ACE_LACKS_UNISTD_H -#define ACE_LACKS_UNIX_SIGNALS -#define ACE_LACKS_UNIX_SYSLOG -#define ACE_LACKS_UTSNAME_T -#define ACE_LACKS_UNAME -#define ACE_LACKS_WAIT -#define ACE_LACKS_IOVEC -#define ACE_LACKS_LOG2 -#define ACE_LACKS_CADDR_T -#if !defined(__MINGW32__) && !defined (__BORLANDC__) -# define ACE_LACKS_MODE_T -#endif -#if !defined (__BORLANDC__) -# define ACE_LACKS_NLINK_T -# define ACE_LACKS_UID_T -# define ACE_LACKS_GID_T -#endif -#define ACE_LACKS_SETENV -#define ACE_LACKS_UNSETENV - -#define ACE_HAS_PDH_H -#define ACE_HAS_PDHMSG_H - -#define ACE_HAS_VFWPRINTF - -#define ACE_MKDIR_LACKS_MODE - -#define ACE_SIZEOF_LONG_LONG 8 -// Green Hills Native x86 does not support __int64 keyword -// Neither does mingw32. -#if !defined (ACE_LACKS_LONGLONG_T) && !defined (__MINGW32__) -#define ACE_INT64_TYPE signed __int64 -#define ACE_UINT64_TYPE unsigned __int64 -#endif /* (ghs) */ - -#if defined (__MINGW32__) -#define ACE_INT64_TYPE signed long long -#define ACE_UINT64_TYPE unsigned long long -#endif - -// Optimize ACE_Handle_Set for select(). -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT - -// Win32 has wide-char support. Use of the compiler-defined wchar_t type -// is controlled in compiler configs since it's a compiler switch. -#define ACE_HAS_WCHAR -#define ACE_HAS_WTOI -#define ACE_HAS_WTOL - -// Compiler/platform correctly calls init()/fini() for shared -// libraries. - applied for DLLs ? -//define ACE_HAS_AUTOMATIC_INIT_FINI - -// Platform supports POSIX O_NONBLOCK semantics. -//define ACE_HAS_POSIX_NONBLOCK - -// Platform contains . -//define ACE_HAS_POLL - -// Platform supports the /proc file system. -//define ACE_HAS_PROC_FS - -// Platform supports the rusage struct. -#define ACE_HAS_GETRUSAGE - -// Compiler/platform supports SVR4 signal typedef. -//define ACE_HAS_SVR4_SIGNAL_T - -// Platform provides header. -//define ACE_HAS_SYS_FILIO_H - -// Platform supports ACE_TLI timod STREAMS module. -//define ACE_HAS_TIMOD_H - -// Platform supports ACE_TLI tiuser header. -//define ACE_HAS_TIUSER_H - -// Platform provides ACE_TLI function prototypes. -// For Win32, this is not really true, but saves a lot of hassle! -#define ACE_HAS_TLI_PROTOTYPES - -// Platform supports ACE_TLI. -//define ACE_HAS_TLI - -// I'm pretty sure NT lacks these -#define ACE_LACKS_UNIX_DOMAIN_SOCKETS - -// Windows NT needs readv() and writev() -#define ACE_LACKS_WRITEV -#define ACE_LACKS_READV - -#if !defined (ACE_HAS_WTHREADS_CONDITION_VARIABLE) -# define ACE_LACKS_COND_T -#endif - -#define ACE_LACKS_RWLOCK_T - -#define ACE_LACKS_KEY_T - -// No system support for replacing any previous mappings. -#define ACE_LACKS_AUTO_MMAP_REPLACEMENT - -// ACE_HAS_PENTIUM is used to optimize some CDR operations; it's used for -// some other time-related things using g++, but not for VC. Current VC -// compilers set _M_IX86 > 400 by default so if you're not using a Pentium -// class CPU, set the project code generation options appropriately. -#if !defined(ACE_HAS_PENTIUM) && (_M_IX86 > 400) -# define ACE_HAS_PENTIUM -#endif - -#if defined(ACE_MT_SAFE) && (ACE_MT_SAFE != 0) -// Platform supports threads. -# define ACE_HAS_THREADS - -// Platform supports Windows32 threads. -# define ACE_HAS_WTHREADS - -// Compiler/platform has thread-specific storage -# define ACE_HAS_THREAD_SPECIFIC_STORAGE - -// Win32 doesn't have fcntl -#define ACE_LACKS_FCNTL - -#endif /* ACE_MT_SAFE && ACE_MT_SAFE != 0 */ - -#if !defined(_DEBUG) -// If we are making a release, and the user has not specified -// inline directives, we will default to inline -# if ! defined (__ACE_INLINE__) -# define __ACE_INLINE__ 1 -# endif /* __ACE_INLINE__ */ -#endif - -// If __ACE_INLINE__ is defined to be 0, we will undefine it -#if defined (__ACE_INLINE__) && (__ACE_INLINE__ == 0) -# undef __ACE_INLINE__ -#endif /* __ACE_INLINE__ */ - -// We are build ACE and want to use MFC (multithreaded) -#if defined(ACE_HAS_MFC) && (ACE_HAS_MFC != 0) && defined (_MT) -# if (ACE_HAS_DLL != 0) && defined(ACE_BUILD_DLL) && !defined (_WINDLL) -// force multithreaded MFC DLL -# define _WINDLL -# endif /* _AFXDLL */ -# if !defined (_AFXDLL) && !defined (ACE_USES_STATIC_MFC) -# define _AFXDLL -# endif /* _AFXDLL */ -#endif - -// and MFC's are mutually -// incompatible. is brain-dead about MFC; it doesn't check -// to see whether MFC stuff is anticipated or already in progress -// before doing its thing. ACE needs (practically always) , -// and winsock in turn needs support either from windows.h or from -// afxwin.h. One or the other, not both. -// -// The MSVC++ V4.0 environment defines preprocessor macros that -// indicate the programmer has chosen something from the -// Build-->Settings-->General-->MFC combo-box. defines a -// macro itself to protect against double inclusion. We'll take -// advantage of all this to select the proper support for winsock. - -// trl 26-July-1996 - -// This is necessary since MFC users apparently can't #include -// directly. -#if defined (ACE_HAS_MFC) && (ACE_HAS_MFC != 0) -# include /**/ /* He is doing MFC */ -// Windows.h will be included via afxwin.h->afx.h->afx_ver_.h->afxv_w32.h -// #define _INC_WINDOWS // Prevent winsock.h from including windows.h -#elif defined (ACE_HAS_WINCE) -# include /**/ -#endif - -#if !defined (_INC_WINDOWS) /* Already include windows.h ? */ -// Must define strict before including windows.h ! -# if defined (ACE_HAS_STRICT) && (ACE_HAS_STRICT != 0) && !defined (STRICT) -# define STRICT 1 -# endif /* ACE_HAS_STRICT */ - -# if !defined (WIN32_LEAN_AND_MEAN) && !defined (ACE_NO_WIN32_LEAN_AND_MEAN) -# define WIN32_LEAN_AND_MEAN -# endif /* WIN32_LEAN_AND_MEAN */ - -#endif /* !defined (_INC_WINDOWS) */ - -// Always use WS2 when available -#if !defined(ACE_HAS_WINSOCK2) -# define ACE_HAS_WINSOCK2 1 -#endif /* !defined(ACE_HAS_WINSOCK2) */ -// Not use WS1 by default -#if !defined(ACE_HAS_WINSOCK1) -# define ACE_HAS_WINSOCK1 0 -#endif /* !defined(ACE_HAS_WINSOCK1) */ - - -#if defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0) -# define ACE_HAS_ICMP_SUPPORT 1 -# if !defined (_WINSOCK2API_) -// will also include windows.h, if not present -# include /**/ -// WinCE 4 doesn't define the Exxx values without the WSA prefix, so do that -// here. This is all lifted from the #if 0'd out part of winsock2.h. -# if defined (_WIN32_WCE) && (_WIN32_WCE < 0x600) -# define EWOULDBLOCK WSAEWOULDBLOCK -# define EINPROGRESS WSAEINPROGRESS -# define EALREADY WSAEALREADY -# define ENOTSOCK WSAENOTSOCK -# define EDESTADDRREQ WSAEDESTADDRREQ -# define EMSGSIZE WSAEMSGSIZE -# define EPROTOTYPE WSAEPROTOTYPE -# define ENOPROTOOPT WSAENOPROTOOPT -# define EPROTONOSUPPORT WSAEPROTONOSUPPORT -# define ESOCKTNOSUPPORT WSAESOCKTNOSUPPORT -# define EOPNOTSUPP WSAEOPNOTSUPP -# define EPFNOSUPPORT WSAEPFNOSUPPORT -# define EAFNOSUPPORT WSAEAFNOSUPPORT -# define EADDRINUSE WSAEADDRINUSE -# define EADDRNOTAVAIL WSAEADDRNOTAVAIL -# define ENETDOWN WSAENETDOWN -# define ENETUNREACH WSAENETUNREACH -# define ENETRESET WSAENETRESET -# define ECONNABORTED WSAECONNABORTED -# define ECONNRESET WSAECONNRESET -# define ENOBUFS WSAENOBUFS -# define EISCONN WSAEISCONN -# define ENOTCONN WSAENOTCONN -# define ESHUTDOWN WSAESHUTDOWN -# define ETOOMANYREFS WSAETOOMANYREFS -# define ETIMEDOUT WSAETIMEDOUT -# define ECONNREFUSED WSAECONNREFUSED -# define ELOOP WSAELOOP -# define ENAMETOOLONG WSAENAMETOOLONG -# define EHOSTDOWN WSAEHOSTDOWN -# define EHOSTUNREACH WSAEHOSTUNREACH -# define ENOTEMPTY WSAENOTEMPTY -# define EPROCLIM WSAEPROCLIM -# define EUSERS WSAEUSERS -# define EDQUOT WSAEDQUOT -# define ESTALE WSAESTALE -# define EREMOTE WSAEREMOTE -# endif /* (_WIN32_WCE) && (_WIN32_WCE < 0x600) */ -# endif /* _WINSOCK2API */ - -# if defined (ACE_HAS_FORE_ATM_WS2) -# include /**/ -# endif /*ACE_HAS_FORE_ATM_WS2 */ - -// CE doesn't have Microsoft Winsock 2 extensions -# if !defined _MSWSOCK_ && !defined (ACE_HAS_WINCE) -# include /**/ -# endif /* _MSWSOCK_ */ - -# if defined (_MSC_VER) -# if defined (ACE_HAS_WINCE) -# pragma comment(lib, "ws2.lib") -# else -# pragma comment(lib, "ws2_32.lib") -# pragma comment(lib, "mswsock.lib") -# if defined (ACE_HAS_IPV6) -# pragma comment(lib, "iphlpapi.lib") -# endif -# endif /* ACE_HAS_WINCE */ -# endif /* _MSC_VER */ - -# define ACE_WSOCK_VERSION 2, 0 -#else -# if !defined (_WINSOCKAPI_) - // will also include windows.h, if not present -# include /**/ -# endif /* _WINSOCKAPI */ - -// PharLap ETS has its own winsock lib, so don't grab the one -// supplied with the OS. -# if defined (_MSC_VER) && !defined (_WIN32_WCE) && !defined (ACE_HAS_PHARLAP) -# pragma comment(lib, "wsock32.lib") -# endif /* _MSC_VER */ - -// We can't use recvmsg and sendmsg unless WinSock 2 is available -# define ACE_LACKS_RECVMSG -# define ACE_LACKS_SENDMSG - -// Version 1.1 of WinSock -# define ACE_WSOCK_VERSION 1, 1 -#endif /* ACE_HAS_WINSOCK2 */ - -// Platform supports IP multicast on Winsock 2 -#if defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0) -# define ACE_HAS_IP_MULTICAST -#endif /* ACE_HAS_WINSOCK2 */ - -#if !defined (ACE_HAS_WINCE) -# define ACE_HAS_INTERLOCKED_EXCHANGEADD -#endif -#define ACE_HAS_WIN32_TRYLOCK - -#if !defined (ACE_HAS_WINCE) && !defined (ACE_HAS_PHARLAP) -# define ACE_HAS_SIGNAL_OBJECT_AND_WAIT - -// If CancelIO is undefined get the updated sp2-sdk from MS -# define ACE_HAS_CANCEL_IO -# define ACE_HAS_WIN32_OVERLAPPED_IO -# define ACE_HAS_WIN32_NAMED_PIPES -#endif /* !defined (ACE_HAS_WINCE) && !ACE_HAS_PHARLAP */ - -#if !defined (ACE_SEH_DEFAULT_EXCEPTION_HANDLING_ACTION) -# define ACE_SEH_DEFAULT_EXCEPTION_HANDLING_ACTION EXCEPTION_CONTINUE_SEARCH -#endif /* ACE_SEH_DEFAULT_EXCEPTION_HANDLING_ACTION */ - -// ACE_HAS_QOS is defined in the qos.mpb base project. -// If qos=1 in default.features, then this macro will be defined. -#if defined (ACE_HAS_QOS) && !defined (ACE_HAS_WINSOCK2_GQOS) -# if defined (WINSOCK_VERSION) -# define ACE_HAS_WINSOCK2_GQOS 1 -# endif /* WINSOCK_VERSION */ -#endif /* ACE_HAS_WINSOCK2_GQOS */ - -// These are the defaults and can be overridden by a user's config.h -#if !defined (ACE_DEFAULT_FILE_PERMS) -# define ACE_DEFAULT_FILE_PERMS (FILE_SHARE_READ | FILE_SHARE_WRITE | \ - FILE_SHARE_DELETE) -// This alternate used to be used for pre-NT4 systems; may still be needed -// by knock-offs such as CE and Pharlap. -//# define ACE_DEFAULT_FILE_PERMS (FILE_SHARE_READ | FILE_SHARE_WRITE) -#endif /* !defined (ACE_DEFAULT_FILE_PERMS) */ - -#define ACE_SIZEOF_WCHAR 2 -#define ACE_HAS_MUTEX_TIMEOUTS -#define ACE_LACKS_STRUCT_DIR -#define ACE_LACKS_OPENDIR -#define ACE_LACKS_CLOSEDIR -#define ACE_LACKS_READDIR -#define ACE_LACKS_ALPHASORT -#define ACE_LACKS_MKSTEMP -#define ACE_LACKS_LSTAT -// Looks like Win32 has a non-const swab function -#define ACE_HAS_NONCONST_SWAB - -// If we are using winsock2 then the SO_REUSEADDR feature is broken -// SO_REUSEADDR=1 behaves like SO_REUSEPORT=1. (SO_REUSEPORT is an -// extension to sockets on some platforms) -// We define SO_REUSEPORT here so that ACE_OS::setsockopt() can still -// allow the user to specify that a socketaddr can *always* be reused. -#if defined (ACE_HAS_WINSOCK2) && ACE_HAS_WINSOCK2 != 0 && ! defined(SO_REUSEPORT) -#define SO_REUSEPORT 0x0400 // We just have to pick a value that won't conflict -#endif - -#if defined (ACE_WIN64) -// Data must be aligned on 8-byte boundaries, at a minimum. -# define ACE_MALLOC_ALIGN 8 -// Void pointers are 8 bytes -# define ACE_SIZEOF_VOID_P 8 -#endif /* ACE_WIN64 */ - -#if !defined (ACE_DISABLES_THREAD_LIBRARY_CALLS) -# define ACE_DISABLES_THREAD_LIBRARY_CALLS 0 -#endif /* ACE_DISABLES_THREAD_LIBRARY_CALLS */ - -#if !defined (ACE_HAS_WINCE) && !defined (ACE_HAS_PHARLAP) -# define ACE_HAS_LOG_MSG_NT_EVENT_LOG -#endif /* !ACE_HAS_WINCE && !ACE_HAS_PHARLAP */ - -#if !defined (ACE_HAS_WINCE) -# define ACE_HAS_LLSEEK -#endif /* !ACE_HAS_WINCE */ - -// Needed for obtaining the MAC address -// I dont believe this will work under CE, notice the -// check for ACE_HAS_WINCE. -# if !defined (ACE_HAS_WINCE) -# include -# if defined (_MSC_VER) -# pragma comment(lib, "netapi32.lib") // needed for obtaing MACaddress -# endif -# endif /* !ACE_HAS_WINCE */ - -#if !defined (WINVER) -# define WINVER 0x0400 // pretend it's at least WinNT 4.0 -#endif - -/////////////////////////////////////// -// windows version-specific definitions -// see: http://msdn2.microsoft.com/en-us/library/aa383745.aspx -// -// For TSS information -// see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/thread_local_storage.asp - -#if (WINVER>=0x0600) -// Windows Server 2008 definitions go here -// Windows Vista defintions go here -# if ! defined(ACE_DEFAULT_THREAD_KEYS) -# define ACE_DEFAULT_THREAD_KEYS 1088 -# endif // ! defined(ACE_DEFAULT_THREAD_KEYS) -#elif (WINVER>=0x0502) - // Windows Server 2003 SP1 definitions go here -# if ! defined(ACE_DEFAULT_THREAD_KEYS) -# define ACE_DEFAULT_THREAD_KEYS 1088 -# endif // ! defined(ACE_DEFAULT_THREAD_KEYS) -#elif (WINVER>=0x0501) -// Windows XP definitions go here -# if ! defined(ACE_DEFAULT_THREAD_KEYS) -# define ACE_DEFAULT_THREAD_KEYS 1088 -# endif // ! defined(ACE_DEFAULT_THREAD_KEYS) -#elif (WINVER>=0x0500) -// Windows 2000 definitions go here -# if ! defined(ACE_DEFAULT_THREAD_KEYS) -# define ACE_DEFAULT_THREAD_KEYS 1088 -# endif // ! defined(ACE_DEFAULT_THREAD_KEYS) -#elif (WINVER>=0x0410) -// Windows 98 definitions go here -# if ! defined(ACE_DEFAULT_THREAD_KEYS) -# define ACE_DEFAULT_THREAD_KEYS 80 -# endif // ! defined(ACE_DEFAULT_THREAD_KEYS) -#else -// antique windows -# if ! defined(ACE_DEFAULT_THREAD_KEYS) -# define ACE_DEFAULT_THREAD_KEYS 64 -# endif // ! defined(ACE_DEFAULT_THREAD_KEYS) -#endif - -#if !defined (ACE_DEFAULT_BACKLOG) -# define ACE_DEFAULT_BACKLOG SOMAXCONN -#endif /* ACE_DEFAULT_BACKLOG */ - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_WIN32_COMMON_H */ diff --git a/externals/ace/config-win32-dmc.h b/externals/ace/config-win32-dmc.h deleted file mode 100644 index db6c7e9c8dc..00000000000 --- a/externals/ace/config-win32-dmc.h +++ /dev/null @@ -1,108 +0,0 @@ -// -*- C++ -*- -// $Id: config-win32-dmc.h 87268 2009-10-29 21:06:06Z olli $ - -// The following configuration file contains defines for Digital Mars compilers. - -#ifndef ACE_CONFIG_WIN32_DMC_H -#define ACE_CONFIG_WIN32_DMC_H -#include /**/ "ace/pre.h" - -#ifndef ACE_CONFIG_WIN32_H -#error Use config-win32.h in config.h instead of this header -#endif /* ACE_CONFIG_WIN32_H */ - -#ifndef WIN32 -# define WIN32 -#endif /* WIN32 */ - -#undef _M_IX86 -// This turns on ACE_HAS_PENTIUM -#define _M_IX86 500 - -#if defined ACE_LACKS_STRUCT_DIR -# undef ACE_LACKS_STRUCT_DIR -#endif - -// Changed ACE_TEXT to ACE_TEXT in the following line -# define ACE_CC_NAME ACE_TEXT ("Digital Mars") -# define ACE_CC_MAJOR_VERSION (1) -# define ACE_CC_MINOR_VERSION (8) -# define ACE_CC_BETA_VERSION (9) -# ifndef ACE_USING_MCPP_PREPROCESSOR -# define ACE_CC_PREPROCESSOR "DMC.EXE" -# define ACE_CC_PREPROCESSOR_ARGS "-E" -# endif - -// Microsoft's standard cpp library auto_ptr doesn't have reset (). -# define ACE_AUTO_PTR_LACKS_RESET - -#define ACE_ENDTHREADEX(STATUS) ::_endthreadex ((DWORD) STATUS) - -// This section below was extracted from config-win32-msvc -#define ACE_HAS_ITOA -#define ACE_ITOA_EQUIVALENT ::_itoa -#define ACE_STRCASECMP_EQUIVALENT ::_stricmp -#define ACE_STRNCASECMP_EQUIVALENT ::_strnicmp -#define ACE_WCSDUP_EQUIVALENT ::_wcsdup -// This section above was extracted from config-win32-msvc - -# define ACE_EXPORT_NESTED_CLASSES 1 -# define ACE_HAS_CPLUSPLUS_HEADERS 1 -//# define ACE_HAS_EXCEPTIONS 1 -# define ACE_HAS_NONCONST_SELECT_TIMEVAL 1 -# define ACE_HAS_SIG_ATOMIC_T 1 -# define ACE_HAS_STANDARD_CPP_LIBRARY 0 -# define ACE_HAS_STDCPP_STL_INCLUDES 1 -# define ACE_HAS_STRING_CLASS 1 -# define ACE_HAS_TEMPLATE_TYPEDEFS 1 -# define ACE_HAS_USER_MODE_MASKS 1 -//# define ACE_LACKS_LINEBUFFERED_STREAMBUF 1 -# define ACE_LACKS_STRPTIME 1 -//# define ACE_LACKS_PRAGMA_ONCE 1 -//# define ACE_NEW_THROWS_EXCEPTIONS 1 -# define ACE_SIZEOF_LONG_DOUBLE 10 -# define ACE_TEMPLATES_REQUIRE_SOURCE 1 -// Changed ACE_TEXT to ACE_TEXT in the following two lines -# define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 -# define ACE_HAS_STRBUF_T -#define ACE_HAS_3_PARAM_WCSTOK -#define ACE_USES_OLD_IOSTREAMS -#define ACE_LACKS_UCONTEXT_H -#define ACE_LACKS_SYS_RESOURCE_H -#define ACE_LACKS_SYS_WAIT_H -#define ACE_LACKS_STRINGS_H -#define ACE_LACKS_SYS_IPC_H -#define ACE_LACKS_SYS_SEM_H -#define ACE_LACKS_SEMAPHORE_H -#define ACE_LACKS_SYS_MMAN_H -#define ACE_LACKS_SYS_UIO_H -#define ACE_LACKS_SYS_SOCKET_H -#define ACE_LACKS_NETINET_IN_H -#define ACE_LACKS_SYS_IOCTL_H -#define ACE_LACKS_SYS_SELECT_H -#define ACE_LACKS_NET_IF_H -#define ACE_LACKS_DLFCN_H -#define ACE_LACKS_NETDB_H -#define ACE_LACKS_SYS_SHM_H -#define ACE_LACKS_REGEX_H -#define ACE_LACKS_SYS_MSG_H -#define ACE_LACKS_NETINET_TCP_H -#define ACE_LACKS_UNISTD_H -#define ACE_LACKS_TERMIOS_H -#define ACE_LACKS_ACE_IOSTREAM -#define ACE_HAS_NONCONST_TEMPNAM - -// Typedefs which we expect DMC to do, but they don't do that -typedef long o_uid_t; -typedef long o_gid_t; - -#include "io.h" -#undef umask; -#undef tell; - -# if !defined (ACE_LD_DECORATOR_STR) && defined (_DEBUG) -# define ACE_LD_DECORATOR_STR ACE_TEXT ("d") -# endif - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_WIN32_DMC_H */ diff --git a/externals/ace/config-win32-ghs.h b/externals/ace/config-win32-ghs.h deleted file mode 100644 index 0ac80bfbd11..00000000000 --- a/externals/ace/config-win32-ghs.h +++ /dev/null @@ -1,93 +0,0 @@ -// -*- C++ -*- -// $Id: config-win32-ghs.h 87268 2009-10-29 21:06:06Z olli $ - -// The following configuration file contains defines for Green Hills compilers. - -#ifndef ACE_CONFIG_WIN32_GHS_H -#define ACE_CONFIG_WIN32_GHS_H -#include /**/ "ace/pre.h" - -#ifndef ACE_CONFIG_WIN32_H -#error Use config-win32.h in config.h instead of this header -#endif /* ACE_CONFIG_WIN32_H */ - -#ifndef WIN32 -# define WIN32 -#endif /* WIN32 */ - -#undef _M_IX86 -// This turns on ACE_HAS_PENTIUM -#define _M_IX86 500 -// GHS does not provide DLL support -#define ACE_HAS_DLL 0 -#define TAO_HAS_DLL 0 -#undef _DLL - -//Green Hills Native x86 does not support structural exceptions -# undef ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS -# undef ACE_HAS_WCHAR -# define ACE_CONFIG_INCLUDE_GHS_COMMON -# include "ace/config-ghs-common.h" - -// Changed ACE_TEXT to ACE_TEXT in the following line -# define ACE_CC_NAME ACE_TEXT ("Green Hills C++") -# define ACE_CC_MAJOR_VERSION (1) -# define ACE_CC_MINOR_VERSION (8) -# define ACE_CC_BETA_VERSION (9) -# ifndef ACE_USING_MCPP_PREPROCESSOR -# define ACE_CC_PREPROCESSOR "GCX.EXE" -# define ACE_CC_PREPROCESSOR_ARGS "-E" -# endif - -// GHS uses Microsoft's standard cpp library, which has auto_ptr. -# undef ACE_LACKS_AUTO_PTR -// Microsoft's standard cpp library auto_ptr doesn't have reset (). -# define ACE_AUTO_PTR_LACKS_RESET - -#define ACE_ENDTHREADEX(STATUS) ::_endthreadex ((DWORD) STATUS) - -// This section below was extracted from config-win32-msvc -#define ACE_HAS_ITOA -#define ACE_ITOA_EQUIVALENT ::_itoa -#define ACE_STRCASECMP_EQUIVALENT ::_stricmp -#define ACE_STRNCASECMP_EQUIVALENT ::_strnicmp -#define ACE_WCSDUP_EQUIVALENT ::_wcsdup -// This section above was extracted from config-win32-msvc - -# define ACE_EXPORT_NESTED_CLASSES 1 -# define ACE_HAS_CPLUSPLUS_HEADERS 1 -//# define ACE_HAS_EXCEPTIONS 1 -# define ACE_HAS_NONCONST_SELECT_TIMEVAL 1 -# define ACE_HAS_SIG_ATOMIC_T 1 -# define ACE_HAS_STANDARD_CPP_LIBRARY 1 -# define ACE_HAS_STDCPP_STL_INCLUDES 1 -# define ACE_HAS_STRING_CLASS 1 -# define ACE_HAS_TEMPLATE_TYPEDEFS 1 -# define ACE_HAS_USER_MODE_MASKS 1 -# define ACE_LACKS_ACE_IOSTREAM 1 -//# define ACE_LACKS_LINEBUFFERED_STREAMBUF 1 -# define ACE_LACKS_STRPTIME 1 -//# define ACE_LACKS_PRAGMA_ONCE 1 -# define ACE_LACKS_STRRECVFD 1 -//# define ACE_NEW_THROWS_EXCEPTIONS 1 -# define ACE_SIZEOF_LONG_DOUBLE 10 -# define ACE_TEMPLATES_REQUIRE_SOURCE 1 -# define ACE_UINT64_FORMAT_SPECIFIER_ASCII "%I64u" -# define ACE_INT64_FORMAT_SPECIFIER_ASCII "%I64d" -# define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 -// Set the following to zero to placate SString.h ACE_WString CTOR -# undef ACE_WSTRING_HAS_USHORT_SUPPORT - -// Green Hills Native x86 does not support __int64 keyword -# define ACE_LACKS_LONGLONG_T - -/* need to ensure these are included before */ -# include -# include - -# if !defined (ACE_LD_DECORATOR_STR) && defined (_DEBUG) -# define ACE_LD_DECORATOR_STR ACE_TEXT ("d") -# endif - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_WIN32_GHS_H */ diff --git a/externals/ace/config-win32-interix.h b/externals/ace/config-win32-interix.h deleted file mode 100644 index d0365ac0399..00000000000 --- a/externals/ace/config-win32-interix.h +++ /dev/null @@ -1,127 +0,0 @@ -// -*- C++ -*- -// $Id: config-win32-interix.h 87578 2009-11-16 14:41:47Z olli $ - -// The following configuration file is designed to work for Interix -// platforms using GNU g++ (Interix == Microsoft's Services for Unix) - -#ifndef ACE_CONFIG_WIN32_INTERIX_H -#define ACE_CONFIG_WIN32_INTERIX_H - -#include /**/ "ace/pre.h" - -#include "ace/config-g++-common.h" - -#define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R -#define ACE_HAS_3_PARAM_READDIR_R -#define ACE_HAS_4_4BSD_SENDMSG_RECVMSG -#define ACE_HAS_AUTOMATIC_INIT_FINI -#define ACE_HAS_BROKEN_T_ERROR -#define ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES -#define ACE_HAS_DIRENT -#define ACE_HAS_EXCEPTIONS -#define ACE_HAS_GETPAGESIZE -#define ACE_HAS_GETRUSAGE -#define ACE_HAS_GETRUSAGE_PROTOTYPE -#define ACE_HAS_GPERF -#define ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT -#define ACE_HAS_ICMP_SUPPORT 1 -#define ACE_HAS_IP_MULTICAST -#define ACE_HAS_MEMCHR -#define ACE_HAS_MKDIR -#define ACE_HAS_MSG -#define ACE_HAS_NEW_NOTHROW -#define ACE_HAS_NEW_NO_H -#define ACE_HAS_NONCONST_SELECT_TIMEVAL -#define ACE_HAS_POLL -#define ACE_HAS_POSITION_INDEPENDENT_POINTERS 1 -#define ACE_HAS_POSIX_GETPWNAM_R -#define ACE_HAS_POSIX_NONBLOCK -#define ACE_HAS_POSIX_TIME -#define ACE_HAS_PTHREADS_STD -#define ACE_HAS_PTHREADS_UNIX98_EXT -#define ACE_HAS_PTHREAD_GETCONCURRENCY -#define ACE_HAS_PTHREAD_SETCONCURRENCY -#define ACE_HAS_PTHREAD_SIGMASK_PROTOTYPE -#define ACE_HAS_P_READ_WRITE -#define ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS -#define ACE_HAS_REENTRANT_FUNCTIONS -#define ACE_HAS_RTLD_LAZY_V -#define ACE_HAS_SEMUN -#define ACE_HAS_SIGINFO_T -#define ACE_HAS_SIGSUSPEND -#define ACE_HAS_SIGWAIT -#define ACE_HAS_SIG_ATOMIC_T -#define ACE_HAS_SIG_C_FUNC -#define ACE_HAS_SOCKADDR_MSG_NAME -#define ACE_HAS_SOCKLEN_T -#define ACE_HAS_SSIZE_T -#define ACE_HAS_STANDARD_CPP_LIBRARY 1 -#define ACE_HAS_STDCPP_STL_INCLUDES -#define ACE_HAS_STREAMS -#define ACE_HAS_STRING_CLASS -#define ACE_HAS_STRSIGNAL -#define ACE_HAS_SVR4_DYNAMIC_LINKING -#define ACE_HAS_SVR4_GETTIMEOFDAY -#define ACE_HAS_SVR4_SIGNAL_T -#define ACE_HAS_SYSV_IPC -#define ACE_HAS_SYS_SYSCALL_H -#define ACE_HAS_TERMIOS -#define ACE_HAS_UALARM -#define ACE_HAS_UCONTEXT_T -#define ACE_HAS_VOIDPTR_GETTIMEOFDAY -#define ACE_HAS_NONSTATIC_OBJECT_MANAGER - -#define ACE_LACKS_GETPGID -#define ACE_LACKS_ISCTYPE -#define ACE_LACKS_LOG2 -#define ACE_LACKS_NETDB_REENTRANT_FUNCTIONS -#define ACE_LACKS_NET_IF_H -#define ACE_LACKS_PRAGMA_ONCE -#define ACE_LACKS_SETSCHED -#define ACE_LACKS_STRRECVFD -#define ACE_LACKS_SYS_SYSCTL_H -#define ACE_LACKS_TIMESPEC_T -#define ACE_LACKS_WCSTOK -#define ACE_LACKS_WCSTOLL -#define ACE_LACKS_WCSTOULL - -// These are probably not needed with gcc 4.x -#define ACE_LACKS_UNSETENV -#define ACE_LACKS_STRTOLL -#define ACE_LACKS_STRTOULL -#define ACE_LACKS_SETEGID -#define ACE_LACKS_SETEUID - - -#define ACE_PAGE_SIZE 4096 -#define ACE_SIZEOF_LONG_LONG 8 -#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 - -#if defined (ACE_HAS_THREADS) -# define ACE_HAS_MUTEX_TIMEOUTS -# define ACE_HAS_PTHREADS -# define ACE_MT_SAFE 1 -#else -# error "You need to enable threads for this Interix port." -#endif /* ACE_HAS_THREADS */ - -// Turns off the tracing feature. -#if !defined (ACE_NTRACE) -#define ACE_NTRACE 1 -#endif /* ACE_NTRACE */ - -// NOTE: In debugging some of the test apps they would all memory fault in using -// ACE_Errno_Guard. Upon inspection of that code it uses TSS to save ERRNO in -// a TSS pointer. Access to that pointer caused the fault. The work around here -// is to tell ACE we have TSS and use emulation. More investigation is needed to -// determine whether Interix TSS is broken or the correct semantics for usage under -// Interix simply need to be ported. -// To get around the issue ACE_HAS_TSS_EMULATION is defined to use TSS emulation -// however while many test programs that use TSS pass the TSS_Test program fails. -#define ACE_HAS_THREAD_SPECIFIC_STORAGE // We need thread specific storage even though... -#define ACE_HAS_TSS_EMULATION // It would appear to be broken in Interix! - - -#include /**/ "ace/post.h" - -#endif /* ACE_CONFIG_WIN32_INTERIX_H */ diff --git a/externals/ace/config-win32-mingw.h b/externals/ace/config-win32-mingw.h deleted file mode 100644 index 0a0ff292f8c..00000000000 --- a/externals/ace/config-win32-mingw.h +++ /dev/null @@ -1,105 +0,0 @@ -// -*- C++ -*- -// $Id: config-win32-mingw.h 87167 2009-10-19 19:33:53Z olli $ - -// -// The following configuration file is designed to work for win32 -// platforms using gcc/g++ with mingw32 (http://www.mingw.org). -// - -#ifndef ACE_CONFIG_WIN32_MINGW_H -#define ACE_CONFIG_WIN32_MINGW_H -#include /**/ "ace/pre.h" - -#ifndef ACE_CONFIG_WIN32_H -# error Use config-win32.h in config.h instead of this header -#endif /* ACE_CONFIG_WIN32_H */ - -#define ACE_CC_NAME ACE_TEXT ("g++") -#define ACE_CC_PREPROCESSOR "cpp" -#define ACE_CC_PREPROCESOR_ARGS "" - -// Why all this is not in config-g++-common.h? -#define ACE_CC_MAJOR_VERSION __GNUC__ -#define ACE_CC_MINOR_VERSION __GNUC_MINOR__ -#define ACE_CC_BETA_VERSION (0) - -#if !defined(__MINGW32__) -# error You do not seem to be using mingw32 -#endif - -#include "ace/config-g++-common.h" - -#include /**/ <_mingw.h> -#include /**/ - -#define ACE_HAS_USER_MODE_MASKS - -#if (__MINGW32_MAJOR_VERSION < 2) -# error You need a newer version (>= 2.0) of mingw32/w32api -#endif - -#if (__MINGW32_MAJOR_VERSION >= 3) -# define ACE_HAS_SSIZE_T -# undef ACE_LACKS_STRUCT_DIR -# undef ACE_LACKS_OPENDIR -# undef ACE_LACKS_CLOSEDIR -# undef ACE_LACKS_READDIR -# undef ACE_LACKS_TELLDIR -# undef ACE_LACKS_SEEKDIR -# undef ACE_LACKS_REWINDDIR -#else -# define ACE_LACKS_DIRENT_H -#endif - -#if (__MINGW32_MAJOR_VERSION > 3) || ((__MINGW32_MAJOR_VERSION == 3) && (__MINGW32_MINOR_VERSION >= 15)) -# undef ACE_LACKS_USECONDS_T -#endif - -#undef ACE_HAS_WTOF - -#define ACE_LACKS_SYS_SHM_H -#define ACE_LACKS_TERMIOS_H -#define ACE_LACKS_NETINET_TCP_H -#define ACE_LACKS_STRRECVFD -#define ACE_LACKS_STRPTIME -#define ACE_LACKS_POLL_H -#define ACE_LACKS_REGEX_H -#define ACE_LACKS_SYS_MSG_H -#define ACE_LACKS_PWD_H -#define ACE_LACKS_SEMAPHORE_H -#define ACE_LACKS_UCONTEXT_H -#define ACE_LACKS_SYS_SELECT_H -#define ACE_LACKS_SYS_RESOURCE_H -#define ACE_LACKS_SYS_WAIT_H -#define ACE_LACKS_DLFCN_H -#define ACE_LACKS_SYS_MMAN_H -#define ACE_LACKS_SYS_UIO_H -#define ACE_LACKS_SYS_SOCKET_H -#define ACE_LACKS_NETINET_IN_H -#define ACE_LACKS_NETDB_H -#define ACE_LACKS_NET_IF_H -#define ACE_LACKS_SYS_IPC_H -#define ACE_LACKS_SYS_SEM_H -#define ACE_LACKS_STROPTS_H -#define ACE_LACKS_SYS_IOCTL_H -#define ACE_LACKS_PDH_H -#define ACE_LACKS_PDHMSG_H -#define ACE_HAS_NONCONST_WCSDUP -#define ACE_HAS_WINSOCK2_GQOS -#define ACE_ISCTYPE_EQUIVALENT ::_isctype - -// We trust the user: He must have used -mpentiumpro or -mpentium -// if that is what he wants. -#if defined(pentiumpro) || defined(pentium) -# define ACE_HAS_PENTIUM -#endif - -#define ACE_INT64_FORMAT_SPECIFIER_ASCII "%I64d" -#define ACE_UINT64_FORMAT_SPECIFIER_ASCII "%I64u" - -#define ACE_ENDTHREADEX(STATUS) ::_endthreadex ((DWORD) (STATUS)) - -#define ACE_DLL_PREFIX ACE_TEXT ("lib") - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_WIN32_MINGW_H */ diff --git a/externals/ace/config-win32-msvc-10.h b/externals/ace/config-win32-msvc-10.h deleted file mode 100644 index 1867aa010f2..00000000000 --- a/externals/ace/config-win32-msvc-10.h +++ /dev/null @@ -1,153 +0,0 @@ -/* -*- C++ -*- */ -//============================================================================= -/** - * @file config-win32-msvc-10.h - * - * $Id: config-win32-msvc-10.h 87224 2009-10-26 07:49:31Z olli $ - * - * @brief Microsoft Visual C++ 10.0 configuration file. - * - * This file is the ACE configuration file for Microsoft Visual C++ version 10. - * - * @note Do not include this file directly, include config-win32.h instead. - */ -//============================================================================= - -#ifndef ACE_CONFIG_WIN32_MSVC_10_H -#define ACE_CONFIG_WIN32_MSVC_10_H -#include /**/ "ace/pre.h" - -#ifndef ACE_CONFIG_WIN32_H -#error Use config-win32.h in config.h instead of this header -#endif /* ACE_CONFIG_WIN32_H */ - -#ifndef ACE_WIN32_VC10 -# define ACE_WIN32_VC10 -#endif - -// Visual C++ 9.0 (.NET) deprecated the old iostreams -#if !defined (ACE_HAS_STANDARD_CPP_LIBRARY) -#define ACE_HAS_STANDARD_CPP_LIBRARY 1 -#endif - -#if !defined (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB) -#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 -#endif - -// Windows' timeval is non-conformant (defined in terms of long instead of -// time_t) and VC9 (on desktop, not CE) changed time_t to a 64-bit value -// even when compiling a 32-bit application. Therefore, ace/Time_Value -// needs to rearrange a few things for this compiler. See Time_Value.h -// for complete details. -#if !defined (ACE_HAS_WINCE) -# define ACE_HAS_TIME_T_LONG_MISMATCH -#endif - -#define ACE_HAS_ITOA -#define ACE_HAS_HEADER_ALLOCATED_CLASS_STATIC_CONST_INT_STOREAGE -#define ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR - -#define ACE_ITOA_EQUIVALENT ::_itoa -#define ACE_STRCASECMP_EQUIVALENT ::_stricmp -#define ACE_STRNCASECMP_EQUIVALENT ::_strnicmp -#define ACE_WCSDUP_EQUIVALENT ::_wcsdup -#if defined (ACE_HAS_WINCE) -# define ACE_FILENO_EQUIVALENT ::_fileno -#else -# define ACE_FILENO_EQUIVALENT(X) (_get_osfhandle (::_fileno (X))) -#endif - -#ifndef ACE_HAS_EXCEPTIONS -# define ACE_HAS_EXCEPTIONS -#endif - -// Windows Mobile 6 doesn't do sig_atomic_t, but maybe future versions will. -# if !defined (_WIN32_WCE) || (_WIN32_WCE > 0x601) -# define ACE_HAS_SIG_ATOMIC_T -# endif /* !Win CE 6.0 or less */ - -#define ACE_LACKS_STRPTIME - -// Evaluate this with a WinCE build; maybe things have improved since VC8. -//#if !defined (ACE_HAS_WINCE) -# define ACE_HAS_INTRIN_H -# define ACE_HAS_INTRINSIC_INTERLOCKED -//#endif - -#if !defined (_WIN32_WCE) || (_WIN32_WCE >= 0x501) -# define ACE_HAS_INTRINSIC_BYTESWAP -#endif - -#define ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES -#define ACE_LACKS_STRRECVFD -#define ACE_HAS_CPLUSPLUS_HEADERS - -#define ACE_HAS_TEMPLATE_TYPEDEFS -#define ACE_TEMPLATES_REQUIRE_SOURCE - -// Platform provides ACE_TLI function prototypes. -// For Win32, this is not really true, but saves a lot of hassle! -#define ACE_HAS_TLI_PROTOTYPES - -// Platform support linebuffered streaming is broken -#define ACE_LACKS_LINEBUFFERED_STREAMBUF - -#if defined (ACE_HAS_STANDARD_CPP_LIBRARY) && (ACE_HAS_STANDARD_CPP_LIBRARY != 0) - -// Platform has its Standard C++ library in the namespace std -# if !defined (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB) -# define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 -# endif /* ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB */ - -// ace/iostream.h does not work with the standard cpp library (yet). -# if !defined (ACE_USES_OLD_IOSTREAMS) -# define ACE_LACKS_ACE_IOSTREAM -# endif /* ! ACE_USES_OLD_IOSTREAMS */ - -// Starting with MSVC 7.1, std::new throws std::bad_alloc on out-of-memory. -#define ACE_NEW_THROWS_EXCEPTIONS -#define ACE_HAS_NEW_NOTHROW - -#else - -// iostream header lacks ipfx (), isfx (), etc., declarations -# define ACE_LACKS_IOSTREAM_FX - -#endif - -// There are too many instances of this warning to fix it right now. -// Maybe in the future. - -// Disable warning of using Microsoft Extension. -# pragma warning(disable:4231) - -// 'class1' : inherits 'class2::member' via dominance -#pragma warning(disable:4250) - -// CE (at least thru Windows Mobile 5) doesn't have the new, secure CRT. -#if !defined (ACE_HAS_WINCE) && !defined (ACE_HAS_TR24731_2005_CRT) -# define ACE_HAS_TR24731_2005_CRT -#endif - -// On CE w/o MFC config-WinCE.h needs to declare a placement new. This -// triggers a warning that there's no placement delete, which can be ignored. -#if defined (ACE_HAS_WINCE) && !defined (ACE_HAS_MFC) -# pragma warning(disable:4291) -#endif - -// A template can not be exported. Only an instantiation may be exported. -#define ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION_EXPORT - -// At least for ACE_UNIMPLEMENTED_FUNC in class templates, this is needed to -// explicitly instantiate a template that has ACE_UNIMPLEMENTED_FUNC. -# define ACE_NEEDS_FUNC_DEFINITIONS - -// Windows Vista and Windows Server 2008 and newer do have native condition -// variables -#if defined (WIN32_WINNT) && (WIN32_WINNT >= 0x0600) -# define ACE_HAS_WTHREADS_CONDITION_VARIABLE -# undef ACE_LACKS_COND_T -#endif - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_WIN32_MSVC_10_H */ diff --git a/externals/ace/config-win32-msvc-7.h b/externals/ace/config-win32-msvc-7.h deleted file mode 100644 index 30965d6772f..00000000000 --- a/externals/ace/config-win32-msvc-7.h +++ /dev/null @@ -1,124 +0,0 @@ -/* -*- C++ -*- */ -//============================================================================= -/** - * @file config-win32-msvc-7.h - * - * $Id: config-win32-msvc-7.h 87251 2009-10-28 12:00:12Z olli $ - * - * @brief Microsoft Visual C++ 7.0 configuration file. - * - * This file is the ACE configuration file for Microsoft Visual C++ version 7. - * - * @note Do not include this file directly, include config-win32.h instead. - * - * @author Darrell Brunsch - */ -//============================================================================= - -#ifndef ACE_CONFIG_WIN32_MSVC_7_H -#define ACE_CONFIG_WIN32_MSVC_7_H -#include /**/ "ace/pre.h" - -#ifndef ACE_CONFIG_WIN32_H -#error Use config-win32.h in config.h instead of this header -#endif /* ACE_CONFIG_WIN32_H */ - -// Visual C++ 7.0 (.NET) deprecated the old iostreams -#if !defined (ACE_HAS_STANDARD_CPP_LIBRARY) -#define ACE_HAS_STANDARD_CPP_LIBRARY 1 -#endif - -#if !defined (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB) -#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 -#endif - -// Win64 SDK compiler claims std::auto_ptr<>::reset not available. -#if defined (_WIN64) || defined (WIN64) -#define ACE_AUTO_PTR_LACKS_RESET -#endif - -#define ACE_HAS_ITOA -#define ACE_HAS_HEADER_ALLOCATED_CLASS_STATIC_CONST_INT_STOREAGE -#define ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR - -#define ACE_ITOA_EQUIVALENT ::_itoa -#define ACE_STRCASECMP_EQUIVALENT ::_stricmp -#define ACE_STRNCASECMP_EQUIVALENT ::_strnicmp -#define ACE_WCSDUP_EQUIVALENT ::_wcsdup - -#if !defined (ACE_HAS_WINCE) && !defined (ACE_HAS_EXCEPTIONS) -#define ACE_HAS_EXCEPTIONS -#endif /* ACE_HAS_WINCE */ - -#define ACE_LACKS_STRPTIME - -#define ACE_HAS_SIG_ATOMIC_T -#define ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES -#define ACE_LACKS_STRRECVFD -#define ACE_HAS_CPLUSPLUS_HEADERS - -#define ACE_HAS_TEMPLATE_TYPEDEFS -#define ACE_TEMPLATES_REQUIRE_SOURCE - -// Platform provides ACE_TLI function prototypes. -// For Win32, this is not really true, but saves a lot of hassle! -#define ACE_HAS_TLI_PROTOTYPES - -// Platform support linebuffered streaming is broken -#define ACE_LACKS_LINEBUFFERED_STREAMBUF - -#if !defined (ACE_HAS_WINCE) && !(defined (__INTEL_COMPILER) && (__INTEL_COMPILER == 900)) -# define ACE_HAS_INTRINSIC_INTERLOCKED -# define ACE_HAS_INTRINSIC_BYTESWAP -#endif - -#if defined (ACE_HAS_STANDARD_CPP_LIBRARY) && (ACE_HAS_STANDARD_CPP_LIBRARY != 0) - -// Platform has its Standard C++ library in the namespace std -# if !defined (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB) -# define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 -# endif /* ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB */ - -// ace/iostream.h does not work with the standard cpp library (yet). -# if !defined (ACE_USES_OLD_IOSTREAMS) -# define ACE_LACKS_ACE_IOSTREAM -# endif /* ! ACE_USES_OLD_IOSTREAMS */ - -// Starting with MSVC 7.1, std::new throws std::bad_alloc on out-of-memory. -// Since we don't support MSVC 7.0, don't test for it. -# define ACE_NEW_THROWS_EXCEPTIONS -# define ACE_HAS_NEW_NOTHROW - -#else - -// iostream header lacks ipfx (), isfx (), etc., declarations -# define ACE_LACKS_IOSTREAM_FX - -#endif - -// There are too many instances of this warning to fix it right now. -// Maybe in the future. -// 'this' : used in base member initializer list -#pragma warning(disable:4355) - -// 'class1' : inherits 'class2::member' via dominance -#pragma warning(disable:4250) - -// C++ Exception Specification ignored -#pragma warning(disable:4290) - -// Disable warning of using Microsoft Extension. -#pragma warning(disable:4231) - -// 'function' : unreferenced local function has been removed -#pragma warning(disable:4505) - -// A template can not be exported. Only an instantiation may be exported. -#define ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION_EXPORT - -// At least for ACE_UNIMPLEMENTED_FUNC in class templates, this is needed to -// explicitly instantiate a template that has ACE_UNIMPLEMENTED_FUNC. -# define ACE_NEEDS_FUNC_DEFINITIONS - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_WIN32_MSVC_7_H */ diff --git a/externals/ace/config-win32-msvc-8.h b/externals/ace/config-win32-msvc-8.h deleted file mode 100644 index fafdd62d422..00000000000 --- a/externals/ace/config-win32-msvc-8.h +++ /dev/null @@ -1,163 +0,0 @@ -/* -*- C++ -*- */ -//============================================================================= -/** - * @file config-win32-msvc-8.h - * - * $Id: config-win32-msvc-8.h 87224 2009-10-26 07:49:31Z olli $ - * - * @brief Microsoft Visual C++ 8.0 configuration file. - * - * This file is the ACE configuration file for Microsoft Visual C++ version 8. - * - * @note Do not include this file directly, include config-win32.h instead. - * - * @author Darrell Brunsch - */ -//============================================================================= - -#ifndef ACE_CONFIG_WIN32_MSVC_8_H -#define ACE_CONFIG_WIN32_MSVC_8_H -#include /**/ "ace/pre.h" - -#ifndef ACE_CONFIG_WIN32_H -#error Use config-win32.h in config.h instead of this header -#endif /* ACE_CONFIG_WIN32_H */ - -#ifndef ACE_WIN32_VC8 -# define ACE_WIN32_VC8 -#endif - -// Visual C++ 8.0 (.NET) deprecated the old iostreams -#if !defined (ACE_HAS_STANDARD_CPP_LIBRARY) -#define ACE_HAS_STANDARD_CPP_LIBRARY 1 -#endif - -#if !defined (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB) -#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 -#endif - -// Windows' timeval is non-conformant (defined in terms of long instead of -// time_t) and VC8 (on desktop, not CE) changed time_t to a 64-bit value -// even when compiling a 32-bit application. Therefore, ace/Time_Value -// needs to rearrange a few things for this compiler. See Time_Value.h -// for complete details. -#if !defined (ACE_HAS_WINCE) -# define ACE_HAS_TIME_T_LONG_MISMATCH -#endif - -#define ACE_HAS_ITOA -#define ACE_HAS_HEADER_ALLOCATED_CLASS_STATIC_CONST_INT_STOREAGE -#define ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR - -#define ACE_ITOA_EQUIVALENT ::_itoa -#define ACE_STRCASECMP_EQUIVALENT ::_stricmp -#define ACE_STRNCASECMP_EQUIVALENT ::_strnicmp -#define ACE_WCSDUP_EQUIVALENT ::_wcsdup -#if defined (ACE_HAS_WINCE) -# define ACE_FILENO_EQUIVALENT ::_fileno -#else -# define ACE_FILENO_EQUIVALENT(X) (_get_osfhandle (::_fileno (X))) -#endif - -#ifndef ACE_HAS_EXCEPTIONS -# define ACE_HAS_EXCEPTIONS -#endif - -// Windows Mobile 6 doesn't do sig_atomic_t, but maybe future versions will. -// This has been true up thrugh the versions. We don't have any indication -// that this might be supported in the future, but it is an easy enough fix -// to bump the wince revision number when a new version is released. -# if !defined (_WIN32_WCE) || (_WIN32_WCE > 0x601) -# define ACE_HAS_SIG_ATOMIC_T -# endif /* !Win CE 6.0 or less */ - -#define ACE_LACKS_STRPTIME - -#if !defined (ACE_HAS_WINCE) -# define ACE_HAS_INTRIN_H -# define ACE_HAS_INTRINSIC_INTERLOCKED -#endif - -#if !defined (_WIN32_WCE) || (_WIN32_WCE >= 0x501) -# define ACE_HAS_INTRINSIC_BYTESWAP -#endif - -#define ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES -#define ACE_LACKS_STRRECVFD -#define ACE_HAS_CPLUSPLUS_HEADERS - -#define ACE_HAS_TEMPLATE_TYPEDEFS -#define ACE_TEMPLATES_REQUIRE_SOURCE - -// Platform provides ACE_TLI function prototypes. -// For Win32, this is not really true, but saves a lot of hassle! -#define ACE_HAS_TLI_PROTOTYPES - -// Platform support linebuffered streaming is broken -#define ACE_LACKS_LINEBUFFERED_STREAMBUF - -#if defined (ACE_HAS_STANDARD_CPP_LIBRARY) && (ACE_HAS_STANDARD_CPP_LIBRARY != 0) - -// Platform has its Standard C++ library in the namespace std -# if !defined (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB) -# define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 -# endif /* ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB */ - -// ace/iostream.h does not work with the standard cpp library (yet). -# if !defined (ACE_USES_OLD_IOSTREAMS) -# define ACE_LACKS_ACE_IOSTREAM -# endif /* ! ACE_USES_OLD_IOSTREAMS */ - -// Starting with MSVC 7.1, std::new throws std::bad_alloc on out-of-memory. -#define ACE_NEW_THROWS_EXCEPTIONS -#define ACE_HAS_NEW_NOTHROW - -#else - -// iostream header lacks ipfx (), isfx (), etc., declarations -# define ACE_LACKS_IOSTREAM_FX - -#endif - -// There are too many instances of this warning to fix it right now. -// Maybe in the future. - -// Disable warning of using Microsoft Extension. -#pragma warning(disable:4231) - -// 'class1' : inherits 'class2::member' via dominance -#pragma warning(disable:4250) - -// 'this' : used in base member initializer list -#pragma warning(disable:4355) - -// CE (at least thru Windows Mobile 5) doesn't have the new, secure CRT. -#if !defined (ACE_HAS_WINCE) && !defined (ACE_HAS_TR24731_2005_CRT) -# define ACE_HAS_TR24731_2005_CRT -#endif - -//Detect Platform SDK 64-bit (AMD64) compiler using _MSC_FULL_VER -#if (defined (_WIN64) || defined (WIN64)) && _MSC_FULL_VER < 140050000 -# define ACE_AUTO_PTR_LACKS_RESET -# define ACE_MSVC_USES_DOUBLE_UNDERSCORE_STAT64 -# define ACE_HAS_BROKEN_STD_REVERSE_ITERATOR -# define ACE_LACKS_NUMERIC_LIMITS_64_BIT_TYPES -# undef ACE_HAS_TR24731_2005_CRT -# undef ACE_HAS_INTRIN_H -#endif - -// On CE w/o MFC config-WinCE.h needs to declare a placement new. This -// triggers a warning that there's no placement delete, which can be ignored. -#if defined (ACE_HAS_WINCE) && !defined (ACE_HAS_MFC) -# pragma warning(disable:4291) -#endif - -// A template can not be exported. Only an instantiation may be exported. -#define ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION_EXPORT - -// At least for ACE_UNIMPLEMENTED_FUNC in class templates, this is needed to -// explicitly instantiate a template that has ACE_UNIMPLEMENTED_FUNC. -# define ACE_NEEDS_FUNC_DEFINITIONS - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_WIN32_MSVC_8_H */ diff --git a/externals/ace/config-win32-msvc-9.h b/externals/ace/config-win32-msvc-9.h deleted file mode 100644 index bd6bcf60fc4..00000000000 --- a/externals/ace/config-win32-msvc-9.h +++ /dev/null @@ -1,153 +0,0 @@ -/* -*- C++ -*- */ -//============================================================================= -/** - * @file config-win32-msvc-9.h - * - * $Id: config-win32-msvc-9.h 87224 2009-10-26 07:49:31Z olli $ - * - * @brief Microsoft Visual C++ 9.0 configuration file. - * - * This file is the ACE configuration file for Microsoft Visual C++ version 9. - * - * @note Do not include this file directly, include config-win32.h instead. - */ -//============================================================================= - -#ifndef ACE_CONFIG_WIN32_MSVC_9_H -#define ACE_CONFIG_WIN32_MSVC_9_H -#include /**/ "ace/pre.h" - -#ifndef ACE_CONFIG_WIN32_H -#error Use config-win32.h in config.h instead of this header -#endif /* ACE_CONFIG_WIN32_H */ - -#ifndef ACE_WIN32_VC9 -# define ACE_WIN32_VC9 -#endif - -// Visual C++ 9.0 (.NET) deprecated the old iostreams -#if !defined (ACE_HAS_STANDARD_CPP_LIBRARY) -#define ACE_HAS_STANDARD_CPP_LIBRARY 1 -#endif - -#if !defined (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB) -#define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 -#endif - -// Windows' timeval is non-conformant (defined in terms of long instead of -// time_t) and VC9 (on desktop, not CE) changed time_t to a 64-bit value -// even when compiling a 32-bit application. Therefore, ace/Time_Value -// needs to rearrange a few things for this compiler. See Time_Value.h -// for complete details. -#if !defined (ACE_HAS_WINCE) -# define ACE_HAS_TIME_T_LONG_MISMATCH -#endif - -#define ACE_HAS_ITOA -#define ACE_HAS_HEADER_ALLOCATED_CLASS_STATIC_CONST_INT_STOREAGE -#define ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR - -#define ACE_ITOA_EQUIVALENT ::_itoa -#define ACE_STRCASECMP_EQUIVALENT ::_stricmp -#define ACE_STRNCASECMP_EQUIVALENT ::_strnicmp -#define ACE_WCSDUP_EQUIVALENT ::_wcsdup -#if defined (ACE_HAS_WINCE) -# define ACE_FILENO_EQUIVALENT ::_fileno -#else -# define ACE_FILENO_EQUIVALENT(X) (_get_osfhandle (::_fileno (X))) -#endif - -#ifndef ACE_HAS_EXCEPTIONS -# define ACE_HAS_EXCEPTIONS -#endif - -// Windows Mobile 6 doesn't do sig_atomic_t, but maybe future versions will. -# if !defined (_WIN32_WCE) || (_WIN32_WCE > 0x601) -# define ACE_HAS_SIG_ATOMIC_T -# endif /* !Win CE 6.0 or less */ - -#define ACE_LACKS_STRPTIME - -// Evaluate this with a WinCE build; maybe things have improved since VC8. -#if !defined (ACE_HAS_WINCE) -# define ACE_HAS_INTRIN_H -# define ACE_HAS_INTRINSIC_INTERLOCKED -#endif - -#if !defined (_WIN32_WCE) || (_WIN32_WCE >= 0x501) -# define ACE_HAS_INTRINSIC_BYTESWAP -#endif - -#define ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES -#define ACE_LACKS_STRRECVFD -#define ACE_HAS_CPLUSPLUS_HEADERS - -#define ACE_HAS_TEMPLATE_TYPEDEFS -#define ACE_TEMPLATES_REQUIRE_SOURCE - -// Platform provides ACE_TLI function prototypes. -// For Win32, this is not really true, but saves a lot of hassle! -#define ACE_HAS_TLI_PROTOTYPES - -// Platform support linebuffered streaming is broken -#define ACE_LACKS_LINEBUFFERED_STREAMBUF - -#if defined (ACE_HAS_STANDARD_CPP_LIBRARY) && (ACE_HAS_STANDARD_CPP_LIBRARY != 0) - -// Platform has its Standard C++ library in the namespace std -# if !defined (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB) -# define ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB 1 -# endif /* ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB */ - -// ace/iostream.h does not work with the standard cpp library (yet). -# if !defined (ACE_USES_OLD_IOSTREAMS) -# define ACE_LACKS_ACE_IOSTREAM -# endif /* ! ACE_USES_OLD_IOSTREAMS */ - -// Starting with MSVC 7.1, std::new throws std::bad_alloc on out-of-memory. -#define ACE_NEW_THROWS_EXCEPTIONS -#define ACE_HAS_NEW_NOTHROW - -#else - -// iostream header lacks ipfx (), isfx (), etc., declarations -# define ACE_LACKS_IOSTREAM_FX - -#endif - -// There are too many instances of this warning to fix it right now. -// Maybe in the future. - -// Disable warning of using Microsoft Extension. -# pragma warning(disable:4231) - -// 'class1' : inherits 'class2::member' via dominance -#pragma warning(disable:4250) - -// CE (at least thru Windows Mobile 5) doesn't have the new, secure CRT. -#if !defined (ACE_HAS_WINCE) && !defined (ACE_HAS_TR24731_2005_CRT) -# define ACE_HAS_TR24731_2005_CRT -#endif - -// On CE w/o MFC config-WinCE.h needs to declare a placement new. This -// triggers a warning that there's no placement delete, which can be ignored. -#if defined (ACE_HAS_WINCE) && !defined (ACE_HAS_MFC) -# pragma warning(disable:4291) -#endif - -// A template can not be exported. Only an instantiation may be exported. -#define ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION_EXPORT - -// At least for ACE_UNIMPLEMENTED_FUNC in class templates, this is needed to -// explicitly instantiate a template that has ACE_UNIMPLEMENTED_FUNC. -# define ACE_NEEDS_FUNC_DEFINITIONS - -// Windows Vista and Windows Server 2008 and newer do have native condition -// variables -#if defined (WIN32_WINNT) && (WIN32_WINNT >= 0x0600) -# define ACE_HAS_WTHREADS_CONDITION_VARIABLE -# undef ACE_LACKS_COND_T -#endif - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_WIN32_MSVC_9_H */ diff --git a/externals/ace/config-win32-msvc.h b/externals/ace/config-win32-msvc.h deleted file mode 100644 index 6f62477b9dd..00000000000 --- a/externals/ace/config-win32-msvc.h +++ /dev/null @@ -1,175 +0,0 @@ -//============================================================================= -/** - * @file config-win32-msvc.h - * - * $Id: config-win32-msvc.h 85785 2009-06-24 18:20:42Z mitza $ - * - * @brief Microsoft Visual C++ configuration file. - * - * This file is the ACE configuration file for Microsoft Visual C++ versions - * 5.0, 6.0, and 7.0 (.NET) - * - * @author Darrell Brunsch - */ -//============================================================================= - -#ifndef ACE_CONFIG_WIN32_MSVC_H -#define ACE_CONFIG_WIN32_MSVC_H -#include /**/ "ace/pre.h" - -#ifndef ACE_CONFIG_WIN32_H -#error Use config-win32.h in config.h instead of this header -#endif /* ACE_CONFIG_WIN32_H */ - -#define ACE_CC_NAME ACE_TEXT ("Visual C++") -#ifndef ACE_USING_MCPP_PREPROCESSOR -# define ACE_CC_PREPROCESSOR "CL.EXE" -# define ACE_CC_PREPROCESSOR_ARGS "-nologo -E" -#endif - -#define ACE_CC_MAJOR_VERSION (_MSC_VER / 100 - 6) -#define ACE_CC_MINOR_VERSION (_MSC_VER % 100) -#define ACE_CC_BETA_VERSION (0) - -#if !defined(_NATIVE_WCHAR_T_DEFINED) - #define ACE_LACKS_NATIVE_WCHAR_T -#endif - -// Win Mobile still does thread exits differently than PC Windows. -#if defined (_WIN32_WCE) -# define ACE_ENDTHREADEX(STATUS) ExitThread ((DWORD) STATUS) -#else -# define ACE_ENDTHREADEX(STATUS) ::_endthreadex ((DWORD) STATUS) -#endif /* _WIN32_WCE */ - -//FUZZ: disable check_for_msc_ver -#if (_MSC_VER >= 1600) -# include "ace/config-win32-msvc-10.h" -#elif (_MSC_VER >= 1500) -# include "ace/config-win32-msvc-9.h" -#elif (_MSC_VER >= 1400) -# include "ace/config-win32-msvc-8.h" -#elif (_MSC_VER >= 1310) -# include "ace/config-win32-msvc-7.h" -#else -# error This version of Microsoft Visual C++ is not supported. -#endif -//FUZZ: enable check_for_msc_ver - -// MFC changes the behavior of operator new at all MSVC versions from 6 up -// by throwing a static CMemoryException* instead of std::bad_alloc -// (see ace/OS_Memory.h). This MFC exception object needs to be cleaned up -// by calling its Delete() method. -#if defined (ACE_HAS_MFC) && (ACE_HAS_MFC == 1) -# if !defined (ACE_NEW_THROWS_EXCEPTIONS) -# define ACE_NEW_THROWS_EXCEPTIONS -# endif -# if defined (ACE_bad_alloc) -# undef ACE_bad_alloc -# endif -# define ACE_bad_alloc CMemoryException *e -# if defined (ACE_del_bad_alloc) -# undef ACE_del_bad_alloc -# endif -# define ACE_del_bad_alloc e->Delete(); -#endif /* ACE_HAS_MFC && ACE_HAS_MFC==1 */ - -#if defined(ACE_MT_SAFE) && (ACE_MT_SAFE != 0) -// must have _MT defined to include multithreading -// features from win32 headers -# if !defined(_MT) && !defined (ACE_HAS_WINCE) -// *** DO NOT *** defeat this error message by defining _MT yourself. -// On MSVC, this is changed by selecting the Multithreaded -// DLL or Debug Multithreaded DLL in the Project Settings -// under C++ Code Generation. -# error You must link against multi-threaded libraries when using ACE (check your project settings) -# endif /* !_MT && !ACE_HAS_WINCE */ -#endif /* ACE_MT_SAFE && ACE_MT_SAFE != 0 */ - -#include -// Although ACE does have alloca() on this compiler/platform combination, it is -// disabled by default since it can be dangerous. Uncomment the following line -// if you ACE to use it. -//#define ACE_HAS_ALLOCA 1 - -#define ACE_LACKS_DIRENT_H -#define ACE_LACKS_DLFCN_H -#define ACE_LACKS_INTTYPES_H -#define ACE_LACKS_NETDB_H -#define ACE_LACKS_NET_IF_H -#define ACE_LACKS_NETINET_IN_H -#define ACE_LACKS_STDINT_H -#define ACE_LACKS_STROPTS_H -#define ACE_LACKS_SYS_IOCTL_H -#define ACE_LACKS_SYS_IPC_H -#define ACE_LACKS_SYS_MMAN_H -#define ACE_LACKS_SYS_RESOURCE_H -#define ACE_LACKS_SYS_SELECT_H -#define ACE_LACKS_SYS_SEM_H -#define ACE_LACKS_SYS_SOCKET_H -#define ACE_LACKS_SYS_TIME_H -#define ACE_LACKS_SYS_UIO_H -#define ACE_LACKS_SYS_WAIT_H -#define ACE_LACKS_UCONTEXT_H - -#define ACE_LACKS_SEMAPHORE_H -#define ACE_LACKS_STRINGS_H -#define ACE_LACKS_PWD_H -#define ACE_LACKS_POLL_H -#define ACE_LACKS_SYS_SHM_H -#define ACE_LACKS_SYS_MSG_H -#define ACE_LACKS_NETINET_TCP_H -#define ACE_LACKS_TERMIOS_H -#define ACE_LACKS_REGEX_H - -#define ACE_INT64_FORMAT_SPECIFIER_ASCII "%I64d" -#define ACE_UINT64_FORMAT_SPECIFIER_ASCII "%I64u" - -#define ACE_STRTOLL_EQUIVALENT ::_strtoi64 -#define ACE_WCSTOLL_EQUIVALENT ::_wcstoi64 -#define ACE_STRTOULL_EQUIVALENT ::_strtoui64 -#define ACE_WCSTOULL_EQUIVALENT ::_wcstoui64 -#define ACE_WTOF_EQUIVALENT ::_wtof - -#define ACE_LACKS_ISBLANK -#define ACE_LACKS_ISWBLANK -#define ACE_LACKS_CORRECT_ISWPRINT_TAB -#define ACE_ISCTYPE_EQUIVALENT ::_isctype - -// Turn off warnings for /W4 -// To resume any of these warning: #pragma warning(default: 4xxx) -// which should be placed after these defines - -#if !defined (ALL_WARNINGS) && defined(_MSC_VER) && !defined(ghs) && !defined(__MINGW32__) -# pragma warning(disable: 4127) /* constant expression for TRACE/ASSERT */ -# pragma warning(disable: 4134) /* message map member fxn casts */ -# pragma warning(disable: 4511) /* private copy constructors are good to have */ -# pragma warning(disable: 4512) /* private operator= are good to have */ -# pragma warning(disable: 4514) /* unreferenced inlines are common */ -# pragma warning(disable: 4710) /* private constructors are disallowed */ -# pragma warning(disable: 4705) /* statement has no effect in optimized code */ -# pragma warning(disable: 4791) /* loss of debugging info in retail version */ -# pragma warning(disable: 4275) /* deriving exported class from non-exported */ -# pragma warning(disable: 4251) /* using non-exported as public in exported */ -# pragma warning(disable: 4786) /* identifier was truncated to '255' characters in the browser information */ -# pragma warning(disable: 4097) /* typedef-name used as synonym for class-name */ -# pragma warning(disable: 4800) /* converting int to boolean */ -# if defined (__INTEL_COMPILER) -# pragma warning(disable: 1744) /* field of class type without a DLL interface used in a class with a DLL interface */ -# pragma warning(disable: 1738) -# endif -#endif /* !ALL_WARNINGS && _MSV_VER && !ghs && !__MINGW32__ */ - -// STRICT type checking in WINDOWS.H enhances type safety for Windows -// programs by using distinct types to represent all the different -// HANDLES in Windows. So for example, STRICT prevents you from -// mistakenly passing an HPEN to a routine expecting an HBITMAP. -// Note that we only use this if we -# if defined (ACE_HAS_STRICT) && (ACE_HAS_STRICT != 0) -# if !defined (STRICT) /* may already be defined */ -# define STRICT -# endif /* !STRICT */ -# endif /* ACE_HAS_STRICT */ - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_WIN32_MSVC_H */ diff --git a/externals/ace/config-win32.h b/externals/ace/config-win32.h deleted file mode 100644 index af946518cae..00000000000 --- a/externals/ace/config-win32.h +++ /dev/null @@ -1,55 +0,0 @@ -/* -*- C++ -*- */ -//============================================================================= -/** - * @file config-win32.h - * - * $Id: config-win32.h 85057 2009-04-08 10:59:58Z msmit $ - * - * @brief Microsoft Windows configuration file. - * - * This file is the ACE configuration file for all of Microsoft Windows - * platforms that ACE runs on. Based on preprocessor definitions, it - * includes other more specific configuration files. - * - * @author Darrell Brunsch - */ -//============================================================================= - -#ifndef ACE_CONFIG_WIN32_H -#define ACE_CONFIG_WIN32_H -#include /**/ "ace/pre.h" - -// NOTE: Please do not add anything besides #include's here. Put other stuff -// (definitions, etc.) in the included headers - -// We need to ensure that for Borland vcl.h can be included before -// windows.h. So we will not include config-win32-common.h from here, -// but instead let it be included at the appropriate place in -// config-win32-borland.h. -#if !defined (__BORLANDC__) -# include "ace/config-win32-common.h" -#endif /* !__BORLANDC__ */ - -// Include the config-win32-* file specific to the compiler -#if defined (__BORLANDC__) -# include "ace/config-win32-borland.h" -#elif defined (_MSC_VER) -# include "ace/config-win32-msvc.h" -#elif defined (ghs) -# include "ace/config-win32-ghs.h" -#elif defined (ACE_HAS_CEGCC) //need to be prior to MINGW32 -# include "ace/config-win32-cegcc.h" -#elif defined (__MINGW32__) -# include "ace/config-win32-mingw.h" -#elif defined (__DMC__) -# include "ace/config-win32-dmc.h" -#else -# error Compiler is not supported -#endif - -// gethostbyaddr does not handle IPv6-mapped-IPv4 addresses -#define ACE_HAS_BROKEN_GETHOSTBYADDR_V4MAPPED - -#include /**/ "ace/post.h" -#endif /* ACE_CONFIG_WIN32_H */ - diff --git a/externals/ace/config.h.in b/externals/ace/config.h.in deleted file mode 100644 index aa09aa48bf6..00000000000 --- a/externals/ace/config.h.in +++ /dev/null @@ -1,2204 +0,0 @@ -/* ace/config.h.in. Generated from configure.ac by autoheader. */ - - -#ifndef ACE_CONFIG_H -#define ACE_CONFIG_H - -// ACE configuration header file - - - - -/* Compiler/platform standard C++ auto_ptr implementation lacks reset() method - */ -#undef ACE_AUTO_PTR_LACKS_RESET - -/* Enable ACE_Timeprobes */ -#undef ACE_COMPILE_TIMEPROBES - -/* */ -#undef ACE_DEFAULT_BASE_ADDR - -/* */ -#undef ACE_DEFAULT_BASE_ADDRL - -/* */ -#undef ACE_DEFAULT_CLOSE_ALL_HANDLES - -/* */ -#undef ACE_DEFAULT_MAX_SOCKET_BUFSIZ - -/* The default number of handles the select()-based reactor should handle */ -#undef ACE_DEFAULT_SELECT_REACTOR_SIZE - -/* Number of TSS keys, with ACE_HAS_TSS_EMULATION _only_. Defaults to 64. */ -#undef ACE_DEFAULT_THREAD_KEYS - -/* Define this if you don't want debug version ACE search for debug version - DLLs first before looking for the DLL names specified. */ -#undef ACE_DISABLE_DEBUG_DLL_CHECK - -/* Do not include emulation for timed semaphore acquisitions. */ -#undef ACE_DISABLE_POSIX_SEM_TIMEOUT_EMULATION - -/* Define to 1 to disable swapping swapping CDR on read */ -#undef ACE_DISABLE_SWAP_ON_READ - -/* Define to DLL file suffix */ -#undef ACE_DLL_SUFFIX - -/* Define to 1 to enable swapping swapping CDR on write */ -#undef ACE_ENABLE_SWAP_ON_WRITE - -/* Compiler requires template args when explicitly calling template - destructor. */ -#undef ACE_EXPLICIT_TEMPLATE_DESTRUCTOR_TAKES_ARGS - -/* Define to 1 if the getsockname() and getpeername() return random values in - the sockaddr_in.sin_zero field. */ -#undef ACE_GETNAME_RETURNS_RANDOM_SIN_ZERO - -/* Uses ctime_r & asctime_r with only two parameters vs. three. */ -#undef ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R - -/* Define to 1 if platform has 2 parameter sched_getaffinity() */ -#undef ACE_HAS_2_PARAM_SCHED_GETAFFINITY - -/* Define to 1 if platform has 2 parameter sched_setaffinity() */ -#undef ACE_HAS_2_PARAM_SCHED_SETAFFINITY - -/* Define to 1 if platform has 3 parameter readdir_r() */ -#undef ACE_HAS_3_PARAM_READDIR_R - -/* Define to 1 if platform has 3 parameter wcstok() */ -#undef ACE_HAS_3_PARAM_WCSTOK - -/* Platform has BSD 4.4 sendmsg()/recvmsg() APIs. */ -#undef ACE_HAS_4_4BSD_SENDMSG_RECVMSG - -/* Platform supports Asynchronous IO calls */ -#undef ACE_HAS_AIO_CALLS - -/* Platform has AIX4 ::read_real_time() */ -#undef ACE_HAS_AIX_HI_RES_TIMER - -/* Compiler/platform supports alloca(). */ -#undef ACE_HAS_ALLOCA - -/* Compiler/platform has */ -#undef ACE_HAS_ALLOCA_H - -/* Define to 1 if system should use Alpha's cycle counter */ -#undef ACE_HAS_ALPHA_TIMER - -/* Use ACE's alternate cuserid() implementation since a system cuserid() may - not exist, or it is not desirable to use it. The implementation requires - ACE_LACKS_PWD_FUNCTIONS to be undefined and that the geteuid() system call - exists. */ -#undef ACE_HAS_ALT_CUSERID - -/* Compiler/platform correctly calls init()/fini() for shared libraries. */ -#undef ACE_HAS_AUTOMATIC_INIT_FINI - -/* Compiler/platform has "big" fd_set, i.e. large number of bits set in fd_set - passed back from select(). */ -#undef ACE_HAS_BIG_FD_SET - -/* Platform sendv() does not work properly with datagrams, i.e. it fails when - the iovec size is IOV_MAX. */ -#undef ACE_HAS_BROKEN_DGRAM_SENDV - -/* Platform doesn't cast MAP_FAILED to a (void *). */ -#undef ACE_HAS_BROKEN_MAP_FAILED - -/* HP/UX does not wrap the mmap(2) header files with extern "C". */ -#undef ACE_HAS_BROKEN_MMAP_H - -/* Platform headers don't support prototypes */ -#undef ACE_HAS_BROKEN_MSG_H - -/* Platform defines struct timespec in */ -#undef ACE_HAS_BROKEN_POSIX_TIME - -/* OS/compiler's header files are inconsistent with libC definition of - rand_r(). */ -#undef ACE_HAS_BROKEN_RANDR - -/* Compiler/platform has the wrong prototype for t_error(), i.e., t_error(char - *) rather than t_error(const char *). */ -#undef ACE_HAS_BROKEN_T_ERROR - -/* Platform has (which contains bzero() prototype) */ -#undef ACE_HAS_BSTRING - -/* Define to 1 if platform has bswap16(). */ -#undef ACE_HAS_BSWAP16 - -/* Define to 1 if platform has bswap32(). */ -#undef ACE_HAS_BSWAP32 - -/* Define to 1 if platform has bswap64(). */ -#undef ACE_HAS_BSWAP64 - -/* Define to 1 if platform has bswap_16(). */ -#undef ACE_HAS_BSWAP_16 - -/* Define to 1 if platform has bswap_32(). */ -#undef ACE_HAS_BSWAP_32 - -/* Define to 1 if platform has bswap_64(). */ -#undef ACE_HAS_BSWAP_64 - -/* Define to 1 if platform has the header file. */ -#undef ACE_HAS_BYTESEX_H - -/* Define to 1 if platform has the header file. */ -#undef ACE_HAS_BYTESWAP_H - -/* Platform supports the Win32 CancelIO() function. (WinNT 4.0 and beyond) */ -#undef ACE_HAS_CANCEL_IO - -/* OS/platform uses char * for dlopen/dlsym args, rather than const char *. */ -#undef ACE_HAS_CHARPTR_DL - -/* Define to 1 if arg 2 of 'shmat' is char *' */ -#undef ACE_HAS_CHARPTR_SHMAT - -/* Define to 1 if arg 1 of 'shmdt' is char *' */ -#undef ACE_HAS_CHARPTR_SHMDT - -/* OS/platform uses char * for sockopt, rather than const char * */ -#undef ACE_HAS_CHARPTR_SOCKOPT - -/* Define to 1 if platform has clock_gettime(). */ -#undef ACE_HAS_CLOCK_GETTIME - -/* Define to 1 if platform has clock_settime(). */ -#undef ACE_HAS_CLOCK_SETTIME - -/* OS header files have some problems with XTI (HP/UX 11). */ -#undef ACE_HAS_CONFLICTING_XTI_MACROS - -/* Prototypes for both signal() and struct sigaction are consistent. */ -#undef ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES - -/* Platform has swab(const char*, char*, ssize_t) variant. */ -#undef ACE_HAS_CONST_CHAR_SWAB - -/* Compiler/platform has correctly prototyped header files. */ -#undef ACE_HAS_CPLUSPLUS_HEADERS - -/* Define to 1 if the system has the type `cpu_set_t'. */ -#undef ACE_HAS_CPU_SET_T - -/* Platform defines custom DSO/DLL symbol export macros. */ -#undef ACE_HAS_CUSTOM_EXPORT_MACROS - -/* Platform supports /dev/poll character device. */ -#undef ACE_HAS_DEV_POLL - -/* Platform supports operations on directories via struct dirent, readdir_r, - etc. */ -#undef ACE_HAS_DIRENT - -/* Build ACE using the frigging PC DLL nonsense... */ -#undef ACE_HAS_DLL - -/* Define to 1 if the dlsym() call segfaults when passed an invalid handle. */ -#undef ACE_HAS_DLSYM_SEGFAULT_ON_INVALID_HANDLE - -/* Platform (Linux) supports event poll interface. */ -#undef ACE_HAS_EVENT_POLL - -/* Compiler supports C++ exception handling. */ -#undef ACE_HAS_EXCEPTIONS - -/* Platform has Fast-Light (FL) toolkit installed. */ -#undef ACE_HAS_FL - -/* Define to 1 if compiler has builtin atomic support */ -#undef ACE_HAS_GCC_ATOMIC_BUILTINS - -/* Define to 1 if platform has getifaddrs(). */ -#undef ACE_HAS_GETIFADDRS - -/* Platform supports getpagesize() call (otherwise, ACE_PAGE_SIZE must be - defined, except on Win32). */ -#undef ACE_HAS_GETPAGESIZE - -/* Define to 1 if platform has getprogname(). */ -#undef ACE_HAS_GETPROGNAME - -/* Define to 1 if platform has getrusage(). */ -#undef ACE_HAS_GETRUSAGE - -/* Define to 1 if platform has the declaration of getrusage(). */ -#undef ACE_HAS_GETRUSAGE_PROTOTYPE - -/* Enable use of GNU template repositories. GNU C++ w/repo patch and EGCS only - */ -#undef ACE_HAS_GNU_REPO - -/* The GPERF utility is compiled for this platform */ -#undef ACE_HAS_GPERF - -/* Optimize ACE_Handle_Set::count_bits for select() operations (common case) - */ -#undef ACE_HAS_HANDLE_SET_OPTIMIZED_FOR_SELECT - -/* Define to 1 if system has SunOS high resolution timer. */ -#undef ACE_HAS_HI_RES_TIMER - -/* Define to 1 if platform has the header file. */ -#undef ACE_HAS_IA32INTRIN_H - -/* Define to 1 if platform has the header file. */ -#undef ACE_HAS_IA64INTRIN_H - -/* Defined to 1 if platform supports ICMP over raw sockets */ -#undef ACE_HAS_ICMP_SUPPORT - -/* Define to 1 if the system has the type `idtype_t'. */ -#undef ACE_HAS_IDTYPE_T - -/* Inline all the static class OS methods to remove call overhead Note: This - gets defined by OS.h if __ACE_INLINE__ is defined */ -#undef ACE_HAS_INLINED_OSCALLS - -/* Define to 1 if the system has the type `int16_t'. */ -#undef ACE_HAS_INT16_T - -/* Define to 1 if the system has the type `int32_t'. */ -#undef ACE_HAS_INT32_T - -/* Define to 1 if the system has the type `int64_t'. */ -#undef ACE_HAS_INT64_T - -/* Define to 1 if the system has the type `int8_t'. */ -#undef ACE_HAS_INT8_T - -/* Define to 1 if the system supports x86/x86_64 inline assembly */ -#undef ACE_HAS_INTEL_ASSEMBLY - -/* Platform supports the intrinsic interlocked optimizations. */ -#undef ACE_HAS_INTRINSIC_INTERLOCKED - -/* Define to 1 if platform has the header file. */ -#undef ACE_HAS_INTRIN_H - -/* Platform supports IPv6 */ -#undef ACE_HAS_IPV6 - -/* Platform supports IP multicast */ -#undef ACE_HAS_IP_MULTICAST - -/* Platform supports the very odd IRIX 6.2 threads... */ -#undef ACE_HAS_IRIX62_THREADS - -/* Define to 1 if platform has the declaration of isastream(). */ -#undef ACE_HAS_ISASTREAM_PROTOTYPE - -/* Define to 1 if platform has itoa(). */ -#undef ACE_HAS_ITOA - -/* The rusage_t structure has only two fields. */ -#undef ACE_HAS_LIMITED_RUSAGE_T - -/* Define to 1 if system has Linux version of sysinfo(). */ -#undef ACE_HAS_LINUX_SYSINFO - -/* Platform supports llseek(). This should not be defined if ACE_HAS_LSEEK64 - is defined. */ -#undef ACE_HAS_LLSEEK - -/* Platform defines MAP_FAILED as a long constant. */ -#undef ACE_HAS_LONG_MAP_FAILED - -/* Platform supports lseek64(). This should not be defined if ACE_HAS_LLSEEK - is defined. */ -#undef ACE_HAS_LSEEK64 - -/* */ -#undef ACE_HAS_LYNXOS4_SIGNALS - -/* Enabled malloc statistics collection. */ -#undef ACE_HAS_MALLOC_STATS - -/* Define to 1 if platform has memchr(). */ -#undef ACE_HAS_MEMCHR - -/* Define to 1 if unrolled ACE_OS::fast_memcpy() is faster than system - memcpy() */ -#undef ACE_HAS_MEMCPY_LOOP_UNROLL - -/* Platform supports Microsoft Foundation Classes */ -#undef ACE_HAS_MFC - -/* Define to 1 if platform has mkdir(). */ -#undef ACE_HAS_MKDIR - -/* Platform supports recvmsg and sendmsg */ -#undef ACE_HAS_MSG - -/* Platform supports MT safe mktime() call (do any of them?) */ -#undef ACE_HAS_MT_SAFE_MKTIME - -/* Sockets may be called in multi-threaded programs */ -#undef ACE_HAS_MT_SAFE_SOCKETS - -/* Compiler supports timed mutex acquisitions (e.g. - pthread_mutex_timedlock()). */ -#undef ACE_HAS_MUTEX_TIMEOUTS - -/* Define to 1 if platform has nanosleep(). */ -#undef ACE_HAS_NANOSLEEP - -/* Define to 1 if platform has the header file. */ -#undef ACE_HAS_NEW_H - -/* Compiler supports new (std::nothrow) */ -#undef ACE_HAS_NEW_NOTHROW - -/* Platform provides new style C++ header */ -#undef ACE_HAS_NEW_NO_H - -/* Define to 1 if system has nonconst FD_ISSET() macro. */ -#undef ACE_HAS_NONCONST_FD_ISSET - -/* Platform uses non-const char * in calls to gethostbyaddr, gethostbyname, - getservbyname */ -#undef ACE_HAS_NONCONST_GETBY - -/* Platform has a non-const parameter to msgsnd() (e.g., SCO). */ -#undef ACE_HAS_NONCONST_MSGSND - -/* Platform omits const qualifier from iovec parameter in readv() prototype. - */ -#undef ACE_HAS_NONCONST_READV - -/* Platform's select() uses non-const timeval* (only found on Linux right now) - */ -#undef ACE_HAS_NONCONST_SELECT_TIMEVAL - -/* Platform omits const qualifier from msghdr parameter in sendmsg() - prototype. */ -#undef ACE_HAS_NONCONST_SENDMSG - -/* Platform omits const qualifier from rlimit parameter in setrlimit() - prototype. */ -#undef ACE_HAS_NONCONST_SETRLIMIT - -/* Platform has swab(char*, char*, ssize_t) variant. */ -#undef ACE_HAS_NONCONST_SWAB - -/* Platform omits const qualifier from iovec parameter in writev() prototype. - */ -#undef ACE_HAS_NONCONST_WRITEV - -/* Causes the ACE_Object_Manager instance to be created in main (int, char - *[]), instead of as a static (global) instance. */ -#undef ACE_HAS_NONSTATIC_OBJECT_MANAGER - -/* Compiler/platform uses old malloc()/free() prototypes (ugh) */ -#undef ACE_HAS_OLD_MALLOC - -/* Platform, e.g., Solaris 2.5, only supports SCHED_OTHER POSIX scheduling - policy. */ -#undef ACE_HAS_ONLY_SCHED_OTHER - -/* Use the semaphore implementation of ACE_Message_Queue rather than the - emulated condition variable (NT and VxWorks). */ -#undef ACE_HAS_OPTIMIZED_MESSAGE_QUEUE - -/* timezone* 2nd parameter & no prototype */ -#undef ACE_HAS_OSF1_GETTIMEOFDAY - -/* Platform supports the OSF TLI timod STREAMS module */ -#undef ACE_HAS_OSF_TIMOD_H - -/* Define to 1 if platform has the header file. */ -#undef ACE_HAS_PDH_H - -/* Define to 1 if system is using Intel Pentium(tm) processor */ -#undef ACE_HAS_PENTIUM - -/* Platform contains */ -#undef ACE_HAS_POLL - -/* Platform supports "position-independent" features provided by - ACE_Based_Pointer<>. */ -#undef ACE_HAS_POSITION_INDEPENDENT_POINTERS - -/* Platform supports POSIX getpwnam_r() function */ -#undef ACE_HAS_POSIX_GETPWNAM_R - -/* Platform supports POSIX O_NONBLOCK semantics */ -#undef ACE_HAS_POSIX_NONBLOCK - -/* Platform supports POSIX realtime signals */ -#undef ACE_HAS_POSIX_REALTIME_SIGNALS - -/* Platform supports POSIX real-time semaphores (e.g., VxWorks and Solaris) */ -#undef ACE_HAS_POSIX_SEM - -/* Platform supports timed POSIX semaphore acquisitions (sem_timedwait()). */ -#undef ACE_HAS_POSIX_SEM_TIMEOUT - -/* Platform supports the POSIX struct timespec type */ -#undef ACE_HAS_POSIX_TIME - -/* Define to 1 if system should use PowerPC's cycle counter */ -#undef ACE_HAS_POWERPC_TIMER - -/* OS has priocntl (2) */ -#undef ACE_HAS_PRIOCNTL - -/* Platform supports the /proc file system and defines tid_t in - */ -#undef ACE_HAS_PROC_FS - -/* Define to 1 if the system has the type `prusage_t'. */ -#undef ACE_HAS_PRUSAGE_T - -/* Define to 1 if platform has POSIX threads */ -#undef ACE_HAS_PTHREADS - -/* Platform supports POSIX Threads .4a Draft 4 */ -#undef ACE_HAS_PTHREADS_DRAFT4 - -/* Platform supports POSIX Threads .4a Draft 6 */ -#undef ACE_HAS_PTHREADS_DRAFT6 - -/* Platform supports POSIX Threads .1c Draft 7 */ -#undef ACE_HAS_PTHREADS_DRAFT7 - -/* Platform supports POSIX.1c-1995 threads */ -#undef ACE_HAS_PTHREADS_STD - -/* Platform has the UNIX98 extensions to Pthreads (rwlocks) */ -#undef ACE_HAS_PTHREADS_UNIX98_EXT - -/* Define to 1 if platform has pthread_attr_setcreatesuspend_np(). */ -#undef ACE_HAS_PTHREAD_ATTR_SETCREATESUSPEND_NP - -/* Define to 1 if platform has pthread_condattr_setkind_np(). */ -#undef ACE_HAS_PTHREAD_CONDATTR_SETKIND_NP - -/* Define to 1 if platform has pthread_continue(). */ -#undef ACE_HAS_PTHREAD_CONTINUE - -/* Define to 1 if platform has pthread_continue_np(). */ -#undef ACE_HAS_PTHREAD_CONTINUE_NP - -/* Define to 1 if platform has pthread_getaffinity_np(). */ -#undef ACE_HAS_PTHREAD_GETAFFINITY_NP - -/* Define to 1 if platform has pthread_getconcurrency(). */ -#undef ACE_HAS_PTHREAD_GETCONCURRENCY - -/* Define to 1 if platform has pthread_mutexattr_setkind_np(). */ -#undef ACE_HAS_PTHREAD_MUTEXATTR_SETKIND_NP - -/* Define to 1 if platform has the header file. */ -#undef ACE_HAS_PTHREAD_NP_H - -/* pthread.h declares an enum with PTHREAD_PROCESS_PRIVATE and - PTHREAD_PROCESS_SHARED values */ -#undef ACE_HAS_PTHREAD_PROCESS_ENUM - -/* Define to 1 if platform has pthread_resume_np(). */ -#undef ACE_HAS_PTHREAD_RESUME_NP - -/* Define to 1 if platform has pthread_setaffinity_np(). */ -#undef ACE_HAS_PTHREAD_SETAFFINITY_NP - -/* Define to 1 if platform has pthread_setconcurrency(). */ -#undef ACE_HAS_PTHREAD_SETCONCURRENCY - -/* Define to 1 if platform has the declaration of pthread_sigmask(). */ -#undef ACE_HAS_PTHREAD_SIGMASK_PROTOTYPE - -/* Define to 1 if platform has pthread_suspend(). */ -#undef ACE_HAS_PTHREAD_SUSPEND - -/* Define to 1 if platform has pthread_suspend_np(). */ -#undef ACE_HAS_PTHREAD_SUSPEND_NP - -/* Purify'ing. Defined on command line. */ -#undef ACE_HAS_PURIFY - -/* Platform has pread() and pwrite() support. */ -#undef ACE_HAS_P_READ_WRITE - -/* Quantify'ing. Defined on command line. */ -#undef ACE_HAS_QUANTIFY - -/* Define to 1 to configure Reactor to use a user-space queue for - notifications */ -#undef ACE_HAS_REACTOR_NOTIFICATION_QUEUE - -/* Mutexes are inherently recursive (e.g., Win32) */ -#undef ACE_HAS_RECURSIVE_MUTEXES - -/* Platform will recurse infinitely on thread exits from TSS cleanup routines - (e.g., AIX) */ -#undef ACE_HAS_RECURSIVE_THR_EXIT_SEMANTICS - -/* Platform supports reentrant functions (i.e., all the POSIX *_r functions). - */ -#undef ACE_HAS_REENTRANT_FUNCTIONS - -/* Platform supports the POSIX regular expression library */ -#undef ACE_HAS_REGEX - -/* Platform has enum instead of int for first argument to ::{get,set}rlimit - (). The value of this macro is the enum definition, e.g., enum - __rlimit_resource, for Linux glibc 2.0. */ -#undef ACE_HAS_RLIMIT_RESOURCE_ENUM - -/* Platform has enum instead of int for first argument to ::getrusage (). The - value of this macro is the enum definition, e.g., enum __rusage_who, for - Linux glibc 2.0. */ -#undef ACE_HAS_RUSAGE_WHO_ENUM - -/* Define to 1 if platform has sched_getaffinity(). */ -#undef ACE_HAS_SCHED_GETAFFINITY - -/* Define to 1 if platform has sched_setaffinity(). */ -#undef ACE_HAS_SCHED_SETAFFINITY - -/* Define to 1 if platform has the header file. */ -#undef ACE_HAS_SELECT_H - -/* Compiler/platform defines a union semun for SysV shared memory */ -#undef ACE_HAS_SEMUN - -/* Define to 1 if platform has setprogname(). */ -#undef ACE_HAS_SETPROGNAME - -/* Define to 1 if platform has set_t_errno(). */ -#undef ACE_HAS_SET_T_ERRNO - -/* Platform has shm_open() */ -#undef ACE_HAS_SHM_OPEN - -/* Platform's sigaction() function takes const sigaction* as 2nd parameter */ -#undef ACE_HAS_SIGACTION_CONSTP2 - -/* Define to 1 if the system has the type `siginfo_t'. */ -#undef ACE_HAS_SIGINFO_T - -/* Platform has bug with sigismember() (HP/UX 11). */ -#undef ACE_HAS_SIGISMEMBER_BUG - -/* Platform supports the Win32 SignalObjectAndWait() function (WinNT 4.0 and - beyond). */ -#undef ACE_HAS_SIGNAL_OBJECT_AND_WAIT - -/* Define to 1 if platform has sigsuspend(). */ -#undef ACE_HAS_SIGSUSPEND - -/* Define to 1 if platform has sigtimedwait(). */ -#undef ACE_HAS_SIGTIMEDWAIT - -/* Define to 1 if `sigval_int' is a member of `union sigval'. */ -#undef ACE_HAS_SIGVAL_SIGVAL_INT - -/* Define to 1 if `sigval_ptr' is a member of `union sigval'. */ -#undef ACE_HAS_SIGVAL_SIGVAL_PTR - -/* Define to 1 if platform has sigwait(). */ -#undef ACE_HAS_SIGWAIT - -/* Define to 1 if the system has the type 'sig_atomic_t'. */ -#undef ACE_HAS_SIG_ATOMIC_T - -/* Compiler requires extern "C" functions for signals. */ -#undef ACE_HAS_SIG_C_FUNC - -/* OS/compiler uses size_t * rather than int * for socket lengths */ -#undef ACE_HAS_SIZET_SOCKET_LEN - -/* Define to 1 if `sin6_len' is a member of `sockaddr_in6'. */ -#undef ACE_HAS_SOCKADDR_IN6_SIN6_LEN - -/* Define to 1 if `sin_len' is a member of `sockaddr_in'. */ -#undef ACE_HAS_SOCKADDR_IN_SIN_LEN - -/* Platform requires (struct sockaddr *) for msg_name field of struct msghdr. - */ -#undef ACE_HAS_SOCKADDR_MSG_NAME - -/* Define to 1 if the system has the type `socklen_t'. */ -#undef ACE_HAS_SOCKLEN_T - -/* Define to 1 if the system has the type `ssize_t'. */ -#undef ACE_HAS_SSIZE_T - -/* Platform/compiler supports Standard C++ Library */ -#undef ACE_HAS_STANDARD_CPP_LIBRARY - -/* Platform has void (*)(...) prototype for pthread_key_create() destructor - (e.g., LynxOS). */ -#undef ACE_HAS_STDARG_THR_DEST - -/* */ -#undef ACE_HAS_STDCPP_STL_INCLUDES - -/* Platform provides C++ header */ -#undef ACE_HAS_STDEXCEPT_NO_H - -/* Define to 1 if platform has UNIX International Threads */ -#undef ACE_HAS_STHREADS - -/* Define to 1 if the system has the type `struct strbuf'. */ -#undef ACE_HAS_STRBUF_T - -/* Define to 1 use ACE's strdup() emulation */ -#undef ACE_HAS_STRDUP_EMULATION - -/* Platform supports STREAMS */ -#undef ACE_HAS_STREAMS - -/* Platform supports STREAM pipes */ -#undef ACE_HAS_STREAM_PIPES - -/* Use the STRICT compilation mode on Win32. */ -#undef ACE_HAS_STRICT - -/* Platform has (which contains bzero() prototype) */ -#undef ACE_HAS_STRINGS - -/* Platform/Compiler supports a String class (e.g., GNU or Win32). */ -#undef ACE_HAS_STRING_CLASS - -/* Define to 1 if platform has strnlen(). */ -#undef ACE_HAS_STRNLEN - -/* Define to 1 if platform has strsignal(). */ -#undef ACE_HAS_STRSIGNAL - -/* Compiler/platform has strange hostent API for socket *_r() calls */ -#undef ACE_HAS_STRUCT_NETDB_DATA - -/* Compiler/platform supports SVR4 dynamic linking semantics */ -#undef ACE_HAS_SVR4_DYNAMIC_LINKING - -/* Compiler/platform supports SVR4 gettimeofday() prototype but doesn't have a - prototype */ -#undef ACE_HAS_SVR4_GETTIMEOFDAY - -/* Compiler/platform supports SVR4 signal typedef. */ -#undef ACE_HAS_SVR4_SIGNAL_T - -/* Compiler/platform supports SVR4 TLI (in particular, T_GETNAME stuff). */ -#undef ACE_HAS_SVR4_TLI - -/* Define to 1 if platform has sysctl(). */ -#undef ACE_HAS_SYSCTL - -/* Define to 1 if platform has the header file. */ -#undef ACE_HAS_SYSENT_H - -/* Platform supports System V IPC (most versions of UNIX, but not Win32) */ -#undef ACE_HAS_SYSV_IPC - -/* Define to 1 if system has SysV version of sysinfo(). */ -#undef ACE_HAS_SYSV_SYSINFO - -/* Define to 1 if platform has the header file. */ -#undef ACE_HAS_SYS_FILIO_H - -/* Define to 1 if platform has the header file. */ -#undef ACE_HAS_SYS_LOADAVG_H - -/* Define to 1 if platform has the header file. */ -#undef ACE_HAS_SYS_PSTAT_H - -/* Compiler/platform supports _sys_siglist array */ -#undef ACE_HAS_SYS_SIGLIST - -/* Define to 1 if platform has the header file. */ -#undef ACE_HAS_SYS_SOCKIO_H - -/* Define to 1 if platform has the header file. */ -#undef ACE_HAS_SYS_SYSCALL_H - -/* Define to 1 if platform has the header file. */ -#undef ACE_HAS_SYS_SYSINFO_H - -/* Define to 1 if platform has the header file. */ -#undef ACE_HAS_SYS_SYSTEMINFO_H - -/* Platform provides header */ -#undef ACE_HAS_SYS_XTI_H - -/* */ -#undef ACE_HAS_TANDEM_SIGNALS - -/* Compiler implements templates that support typedefs inside of classes used - as formal arguments to a template class. */ -#undef ACE_HAS_TEMPLATE_TYPEDEFS - -/* Define to 1 if system supports SysV tty API. */ -#undef ACE_HAS_TERMIO - -/* Define to 1 if system supports POSIX tty API. */ -#undef ACE_HAS_TERMIOS - -/* Platform supports threads. */ -#undef ACE_HAS_THREADS - -/* Platform allows multiple threads to call accept() on the same port (e.g., - WinNT). */ -#undef ACE_HAS_THREAD_SAFE_ACCEPT - -/* Platform has thread_self() rather than pthread_self() (e.g., DCETHREADS and - AIX) */ -#undef ACE_HAS_THREAD_SELF - -/* Compiler/platform has thread-specific storage */ -#undef ACE_HAS_THREAD_SPECIFIC_STORAGE - -/* The pthread_keycreate() routine *must* take extern C functions. */ -#undef ACE_HAS_THR_C_DEST - -/* The pthread_create() routine *must* take extern C functions. */ -#undef ACE_HAS_THR_C_FUNC - -/* Platform supports thr_keydelete (e.g,. UNIXWARE) */ -#undef ACE_HAS_THR_KEYDELETE - -/* Platform calls thr_minstack() rather than thr_min_stack() (e.g., Tandem). - */ -#undef ACE_HAS_THR_MINSTACK - -/* Platform has thr_yield() */ -#undef ACE_HAS_THR_YIELD - -/* Define to 1 if platform has global timezone variable */ -#undef ACE_HAS_TIMEZONE - -/* Platform/compiler supports timezone * as second parameter to gettimeofday() - and has a prototype. */ -#undef ACE_HAS_TIMEZONE_GETTIMEOFDAY - -/* Platform supports TLI timod STREAMS module */ -#undef ACE_HAS_TIMOD_H - -/* Platform supports TLI tiuser header */ -#undef ACE_HAS_TIUSER_H - -/* Platform does not protect with extern "C" */ -#undef ACE_HAS_TIUSER_H_BROKEN_EXTERN_C - -/* Platform supports TLI. Also see ACE_TLI_TCP_DEVICE. */ -#undef ACE_HAS_TLI - -/* Platform provides TLI function prototypes */ -#undef ACE_HAS_TLI_PROTOTYPES - -/* ACE provides TSS emulation. See also ACE_DEFAULT_THREAD_KEYS. */ -#undef ACE_HAS_TSS_EMULATION - -/* Define to 1 if platform has ualarm(). */ -#undef ACE_HAS_UALARM - -/* Define to 1 if the system has the type `ucontext_t'. */ -#undef ACE_HAS_UCONTEXT_T - -/* Define to 1 if the system has the type `uint16_t'. */ -#undef ACE_HAS_UINT16_T - -/* Define to 1 if the system has the type `uint32_t'. */ -#undef ACE_HAS_UINT32_T - -/* Define to 1 if the system has the type `uint64_t'. */ -#undef ACE_HAS_UINT64_T - -/* Define to 1 if the system has the type `uint8_t'. */ -#undef ACE_HAS_UINT8_T - -/* Has inconsistent SVR4 signal stuff, but not the same as the other platforms - */ -#undef ACE_HAS_UNIXWARE_SVR4_SIGNAL_T - -/* Define to 1 if platform has vasprintf(). */ -#undef ACE_HAS_VASPRINTF - -/* Define to 1 if platform has vaswprintf(). */ -#undef ACE_HAS_VASWPRINTF - -/* Prints out console message in ACE_NOTSUP. Useful for tracking down origin - of ACE_NOTSUP. */ -#undef ACE_HAS_VERBOSE_NOTSUP - -/* Define to 1 if platform has vfwprintf(). */ -#undef ACE_HAS_VFWPRINTF - -/* Platform/compiler supports void * as second parameter to gettimeofday() and - has a prototype. */ -#undef ACE_HAS_VOIDPTR_GETTIMEOFDAY - -/* Platform requires void * for mmap(). */ -#undef ACE_HAS_VOIDPTR_MMAP - -/* OS/compiler uses void * arg 4 setsockopt() rather than const char * */ -#undef ACE_HAS_VOIDPTR_SOCKOPT - -/* Define to 1 if platform has vswprintf(). */ -#undef ACE_HAS_VSWPRINTF - -/* Platform/compiler supports wchar_t */ -#undef ACE_HAS_WCHAR - -/* Define to 1 use ACE's wcsdup() emulation */ -#undef ACE_HAS_WCSDUP_EMULATION - -/* Define to 1 if platform has wcsnlen(). */ -#undef ACE_HAS_WCSNLEN - -/* Platform/compiler supports Win32 structural exceptions. */ -#undef ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS - -/* The Win32 platform support TryEnterCriticalSection(). (WinNT 4.0 and - beyond) */ -#undef ACE_HAS_WIN32_TRYLOCK - -/* The Win32 platform supports WinSock 2.0. */ -#undef ACE_HAS_WINSOCK2 - -/* Compiler handles explicit calling of template destructor correctly. */ -#undef ACE_HAS_WORKING_EXPLICIT_TEMPLATE_DESTRUCTOR - -/* Solaris for intel uses macros for fstat() and stat(), these are wrappers - for _fxstat() and _xstat() uses of the macros. Causes compile and runtime - problems. */ -#undef ACE_HAS_X86_STAT_MACROS - -/* Platform has the XLI version of TLI */ -#undef ACE_HAS_XLI - -/* Platform has support for multi-byte character support compliant with the - XPG4 Worldwide Portability Interface wide-character classification. */ -#undef ACE_HAS_XPG4_MULTIBYTE_CHAR - -/* Platform has Xt Intrinsics Toolkit */ -#undef ACE_HAS_XT - -/* Platform has XTI (X/Open-standardized superset of TLI). Implies ACE_HAS_TLI - but uses a different header file. */ -#undef ACE_HAS_XTI - -/* Define to 1 if platform has _InterlockedDecrement(). */ -#undef ACE_HAS__INTERLOCKEDDECREMENT - -/* Define to 1 if platform has _InterlockedExchangeAdd(). */ -#undef ACE_HAS__INTERLOCKEDEXCHANGEADD - -/* Define to 1 if platform has _InterlockedIncrement(). */ -#undef ACE_HAS__INTERLOCKEDINCREMENT - -/* Define to the *printf format specifier (e.g. "%lld") for ACE_INT64 */ -#undef ACE_INT64_FORMAT_SPECIFIER - -/* Define to signed 64 bit integer type */ -#undef ACE_INT64_TYPE - -/* Define to the type of arg 2 for `ioctl'. */ -#undef ACE_IOCTL_TYPE_ARG2 - -/* Define to 1 if platform lacks access(). */ -#undef ACE_LACKS_ACCESS - -/* Do not compile support for the "Codecs" ACE features. */ -#undef ACE_LACKS_ACE_CODECS - -/* Platform can not build ace/IOStream{,_T}.cpp. This does not necessarily - mean that the platform does not support iostreams. */ -#undef ACE_LACKS_ACE_IOSTREAM - -/* Do not compile support for the "other" ACE features, such as CORBA - handling, name services, and QoS. */ -#undef ACE_LACKS_ACE_OTHER - -/* Do not compile support for the ACE Service Configurator. */ -#undef ACE_LACKS_ACE_SVCCONF - -/* Do not compile support for the ACE Token feature. */ -#undef ACE_LACKS_ACE_TOKEN - -/* Do not compile support for the ACE UUID feature. */ -#undef ACE_LACKS_ACE_UUID - -/* Define to 1 if platform lacks alarm(). */ -#undef ACE_LACKS_ALARM - -/* Define to 1 if platform lacks alphasort(). */ -#undef ACE_LACKS_ALPHASORT - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_ARPA_INET_H - -/* Define to 1 if platform lacks asctime(). */ -#undef ACE_LACKS_ASCTIME - -/* Define to 1 if platform lacks asctime_r(). */ -#undef ACE_LACKS_ASCTIME_R - -/* No system support for replacing any previous mappings. */ -#undef ACE_LACKS_AUTO_MMAP_REPLACEMENT - -/* Platform lacks support for the standard C++ auto_ptr class */ -#undef ACE_LACKS_AUTO_PTR - -/* Define to 1 if platform lacks bsearch(). */ -#undef ACE_LACKS_BSEARCH - -/* Define to 1 to support unaligned CDR */ -#undef ACE_LACKS_CDR_ALIGNMENT - -/* Compiler does not have any istream operator>> for chars, u_chars, or signed - chars. */ -#undef ACE_LACKS_CHAR_RIGHT_SHIFTS - -/* Compiler does not have operator>> (istream &, u_char *) or operator>> - (istream &, signed char *) */ -#undef ACE_LACKS_CHAR_STAR_RIGHT_SHIFTS - -/* Define to 1 if platform lacks chdir(). */ -#undef ACE_LACKS_CHDIR - -/* Define to 1 if system lacks pthread_condattr_setpshared() */ -#undef ACE_LACKS_CONDATTR_PSHARED - -/* Platform lacks condition variables (e.g., Win32 and VxWorks) */ -#undef ACE_LACKS_COND_T - -/* pthread_cond_timedwait does *not* reset the time argument when the lock is - acquired. */ -#undef ACE_LACKS_COND_TIMEDWAIT_RESET - -/* Platform uses struct strbuf * rather than const struct strbuf * (e.g., - HP/UX 10.x) */ -#undef ACE_LACKS_CONST_STRBUF_PTR - -/* Platform forgot const in cond_timewait (e.g., HP/UX). */ -#undef ACE_LACKS_CONST_TIMESPEC_PTR - -/* Define to 1 if platform lacks difftime(). */ -#undef ACE_LACKS_DIFFTIME - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_DIRENT_H - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_DLFCN_H - -/* Define to 1 if platform lacks dup(). */ -#undef ACE_LACKS_DUP - -/* Define to 1 if platform lacks dup2(). */ -#undef ACE_LACKS_DUP2 - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_ERRNO_H - -/* Platform lacks the exec() family of system calls (e.g., Win32, VxWorks, - Chorus) */ -#undef ACE_LACKS_EXEC - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_EXECINFO_H - -/* Define to 1 if platform lacks fcntl(). */ -#undef ACE_LACKS_FCNTL - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_FCNTL_H - -/* Define to 1 if platform lacks fgetwc(). */ -#undef ACE_LACKS_FGETWC - -/* Define to 1 if platform lacks fgetws(). */ -#undef ACE_LACKS_FGETWS - -/* Define to 1 if the system lacks the type `struct flock'. */ -#undef ACE_LACKS_FILELOCKS - -/* Define to 1 if platform lacks fork(). */ -#undef ACE_LACKS_FORK - -/* Define to 1 if platform lacks fputws(). */ -#undef ACE_LACKS_FPUTWS - -/* Define to 1 if platform lacks fsync(). */ -#undef ACE_LACKS_FSYNC - -/* Define to 1 if platform lacks getcwd(). */ -#undef ACE_LACKS_GETCWD - -/* Define to 1 if platform lacks getegid(). */ -#undef ACE_LACKS_GETEGID - -/* Define to 1 if platform lacks geteuid(). */ -#undef ACE_LACKS_GETEUID - -/* Define to 1 if platform lacks getgid(). */ -#undef ACE_LACKS_GETGID - -/* Define to 1 if platform lacks gethostent(). */ -#undef ACE_LACKS_GETHOSTENT - -/* Define to 1 if platform lacks getipnodebyaddr(). */ -#undef ACE_LACKS_GETIPNODEBYADDR - -/* Define to 1 if platform lacks getipnodebyname(). */ -#undef ACE_LACKS_GETIPNODEBYNAME - -/* Define to 1 if platform lacks getopt(). */ -#undef ACE_LACKS_GETOPT - -/* Define to 1 if platform lacks the declaration of getopt(). */ -#undef ACE_LACKS_GETOPT_PROTOTYPE - -/* Define to 1 if platform lacks getpgid(). */ -#undef ACE_LACKS_GETPGID - -/* Define to 1 if platform lacks getpgid() declaration in . */ -#undef ACE_LACKS_GETPGID_PROTOTYPE - -/* Define to 1 if platform lacks getpid(). */ -#undef ACE_LACKS_GETPID - -/* Define to 1 if platform lacks getppid(). */ -#undef ACE_LACKS_GETPPID - -/* Platforms lacks getservbyname() (e.g., VxWorks and Chorus). */ -#undef ACE_LACKS_GETSERVBYNAME - -/* Define to 1 if platform lacks getuid(). */ -#undef ACE_LACKS_GETUID - -/* Define to 1 if platform lacks gmtime(). */ -#undef ACE_LACKS_GMTIME - -/* Define to 1 if platform lacks gmtime_r(). */ -#undef ACE_LACKS_GMTIME_R - -/* Define to 1 if platform lacks inet_aton(). */ -#undef ACE_LACKS_INET_ATON - -/* Platform can't handle "inline" keyword correctly. */ -#undef ACE_LACKS_INLINE_FUNCTIONS - -/* Define to 1 if the system lacks the type `intmax_t'. */ -#undef ACE_LACKS_INTMAX_T - -/* Define to 1 if the system lacks the type `intptr_t'. */ -#undef ACE_LACKS_INTPTR_T - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_INTTYPES_H - -/* iostream header does not declare ipfx (), opfx (), etc. */ -#undef ACE_LACKS_IOSTREAM_FX - -/* iostreams are not supported adequately on the given platform. */ -#undef ACE_LACKS_IOSTREAM_TOTALLY - -/* Define to 1 if platform lacks isatty(). */ -#undef ACE_LACKS_ISATTY - -/* Define to 1 if platform lacks isblank(). */ -#undef ACE_LACKS_ISBLANK - -/* Define to 1 if platform lacks isctype(). */ -#undef ACE_LACKS_ISCTYPE - -/* Define to 1 if platform lacks iswblank(). */ -#undef ACE_LACKS_ISWBLANK - -/* Define to 1 if platform lacks iswctype(). */ -#undef ACE_LACKS_ISWCTYPE - -/* Define to 1 if platform lacks itow(). */ -#undef ACE_LACKS_ITOW - -/* Define to 1 if the system lacks the type `key_t'. */ -#undef ACE_LACKS_KEY_T - -/* Define to 1 if platform lacks kill(). */ -#undef ACE_LACKS_KILL - -/* Platform lacks streambuf "linebuffered ()". */ -#undef ACE_LACKS_LINEBUFFERED_STREAMBUF - -/* Platform/compiler lacks the llseek() prototype. This should not be defined - if ACE_LACKS_LSEEK64_PROTOTYPE is defined. */ -#undef ACE_LACKS_LLSEEK_PROTOTYPE - -/* Define to 1 if platform lacks localtime(). */ -#undef ACE_LACKS_LOCALTIME - -/* Define to 1 if platform lacks log2(). */ -#undef ACE_LACKS_LOG2 - -/* Compiler/platform does not support the unsigned long long datatype. */ -#undef ACE_LACKS_LONGLONG_T - -/* Platform/compiler lacks the lseek64() prototype. This should not be defined - if ACE_LACKS_LLSEEK_PROTOTYPE is defined. */ -#undef ACE_LACKS_LSEEK64_PROTOTYPE - -/* Define to 1 if platform lacks lstat(). */ -#undef ACE_LACKS_LSTAT - -/* Define to 1 if platform lacks madvise(). */ -#undef ACE_LACKS_MADVISE - -/* Define to 1 if platform lacks the declaration of madvise(). */ -#undef ACE_LACKS_MADVISE_PROTOTYPE - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_MALLOC_H - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_MEMORY_H - -/* Define to 1 if platform lacks mkfifo(). */ -#undef ACE_LACKS_MKFIFO - -/* Define to 1 if platform lacks mkstemp(). */ -#undef ACE_LACKS_MKSTEMP - -/* Define to 1 if platform lacks the declaration of mkstemp(). */ -#undef ACE_LACKS_MKSTEMP_PROTOTYPE - -/* Define to 1 if platform lacks mktemp(). */ -#undef ACE_LACKS_MKTEMP - -/* Define to 1 if platform lacks the declaration of mktemp(). */ -#undef ACE_LACKS_MKTEMP_PROTOTYPE - -/* The platform doesn't have mmap(2) (e.g., SCO UNIX). */ -#undef ACE_LACKS_MMAP - -/* Platform/compiler doesn't have open() mode masks. */ -#undef ACE_LACKS_MODE_MASKS - -/* Platform does not have Motif X toolkit available */ -#undef ACE_LACKS_MOTIF - -/* Define to 1 if platform lacks mprotect(). */ -#undef ACE_LACKS_MPROTECT - -/* Platform defines ACE_HAS_MSG, but lacks msg_accrights{len}. */ -#undef ACE_LACKS_MSG_ACCRIGHTS - -/* Define to 1 if platform lacks msync(). */ -#undef ACE_LACKS_MSYNC - -/* Define to 1 if system lacks pthread_mutexattr_setpshared(). */ -#undef ACE_LACKS_MUTEXATTR_PSHARED - -/* Platform lacks named POSIX semaphores (e.g., Chorus) */ -#undef ACE_LACKS_NAMED_POSIX_SEM - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_NETDB_H - -/* Platform does not support reentrant netdb functions (getprotobyname_r, - getprotobynumber_r, gethostbyaddr_r, gethostbyname_r, getservbyname_r). */ -#undef ACE_LACKS_NETDB_REENTRANT_FUNCTIONS - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_NETINET_IN_H - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_NETINET_TCP_H - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_NET_IF_H - -/* OS requires non-null status pointer for pthread_join () */ -#undef ACE_LACKS_NULL_PTHREAD_STATUS - -/* Platform lacks std::numeric_limits<> */ -#undef ACE_LACKS_NUMERIC_LIMITS - -/* Define to 1 if platform lacks IGMPv3 "perfect" filtering of multicast - datagrams at the socket level. If defined, ACE_SOCK_Dgram_Mcast will bind - the first joined multicast group to the socket, and all future joins on - that socket will fail with an error. */ -#undef ACE_LACKS_PERFECT_MULTICAST_FILTERING - -/* Define to 1 if platform lacks pipe(). */ -#undef ACE_LACKS_PIPE - -/* Compiler doesn't support placement operator delete(void *, void *). */ -#undef ACE_LACKS_PLACEMENT_OPERATOR_DELETE - -/* Compiler complains about use of obsolete "pragma once" */ -#undef ACE_LACKS_PRAGMA_ONCE - -/* Platform/compiler lacks the pread() and pwrite() prototypes */ -#undef ACE_LACKS_PREAD_PROTOTYPE - -/* Define to 1 if the system lacks the type 'pri_t'. */ -#undef ACE_LACKS_PRI_T - -/* Define to 1 if platform lacks pthread_attr_setstack() */ -#undef ACE_LACKS_PTHREAD_ATTR_SETSTACK - -/* Define to 1 if platform lacks pthread_attr_setstackaddr(). */ -#undef ACE_LACKS_PTHREAD_ATTR_SETSTACKADDR - -/* Define to 1 if platform lacks pthread_attr_setstacksize(). */ -#undef ACE_LACKS_PTHREAD_ATTR_SETSTACKSIZE - -/* Platform lacks pthread_cancel() */ -#undef ACE_LACKS_PTHREAD_CANCEL - -/* Define to 1 if platform lacks pthread_sigmask(). */ -#undef ACE_LACKS_PTHREAD_SIGMASK - -/* Define to 1 if platform lacks pthread_thr_sigsetmask(). */ -#undef ACE_LACKS_PTHREAD_THR_SIGSETMASK - -/* Define to 1 if platform lacks pthread_yield(). */ -#undef ACE_LACKS_PTHREAD_YIELD - -/* Platform lacks, getpwnam(), etc. */ -#undef ACE_LACKS_PWD_FUNCTIONS - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_PWD_H - -/* Platform lacks getpwnam_r() methods (e.g., SGI 6.2). */ -#undef ACE_LACKS_PWD_REENTRANT_FUNCTIONS - -/* Define to 1 if platform lacks qsort(). */ -#undef ACE_LACKS_QSORT - -/* Define to 1 if platform lacks readdir_r(). */ -#undef ACE_LACKS_READDIR_R - -/* Define to 1 if platform lacks readlink(). */ -#undef ACE_LACKS_READLINK - -/* Define to 1 if platform lacks readv(). */ -#undef ACE_LACKS_READV - -/* Define to 1 if platform lacks realpath(). */ -#undef ACE_LACKS_REALPATH - -/* Define to 1 if platform lacks recvmsg(). */ -#undef ACE_LACKS_RECVMSG - -/* Define to 1 if platform lacks rename(). */ -#undef ACE_LACKS_RENAME - -/* Platform/compiler lacks {get,set}rlimit() function (e.g., VxWorks, Chorus, - and SCO UNIX) */ -#undef ACE_LACKS_RLIMIT - -/* Define to 1 if platform lacks the declaration of {get,set}rlimit(). */ -#undef ACE_LACKS_RLIMIT_PROTOTYPE - -/* Define to 1 if system lacks pthread_rwlockattr_setpshared(). */ -#undef ACE_LACKS_RWLOCKATTR_PSHARED - -/* Define to 1 if the system lacks the type `rwlock_t'. */ -#undef ACE_LACKS_RWLOCK_T - -/* Define to 1 if platform lacks sbrk(). */ -#undef ACE_LACKS_SBRK - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_SCHED_H - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_SEARCH_H - -/* Define to 1 if platform lacks seekdir(). */ -#undef ACE_LACKS_SEEKDIR - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_SEMAPHORE_H - -/* Define to 1 if the system lacks the type `struct sembuf'. */ -#undef ACE_LACKS_SEMBUF_T - -/* Define to 1 if platform lacks sendmsg(). */ -#undef ACE_LACKS_SENDMSG - -/* Platform lacks pthread_attr_setdetachstate() (e.g., HP/UX 10.x) */ -#undef ACE_LACKS_SETDETACH - -/* Define to 1 if platform lacks setegid(). */ -#undef ACE_LACKS_SETEGID - -/* Define to 1 if platform lacks setenv(). */ -#undef ACE_LACKS_SETENV - -/* Define to 1 if platform lacks seteuid(). */ -#undef ACE_LACKS_SETEUID - -/* Define to 1 if platform lacks setgid(). */ -#undef ACE_LACKS_SETGID - -/* Define to 1 if platform lacks setpgid(). */ -#undef ACE_LACKS_SETPGID - -/* Define to 1 if platform lacks setpgid() declaration in . */ -#undef ACE_LACKS_SETPGID_PROTOTYPE - -/* Define to 1 if platform lacks setregid(). */ -#undef ACE_LACKS_SETREGID - -/* Define to 1 if platform lacks setregid() declaration in . */ -#undef ACE_LACKS_SETREGID_PROTOTYPE - -/* Define to 1 if platform lacks setreuid(). */ -#undef ACE_LACKS_SETREUID - -/* Define to 1 if platform lacks setreuid() declaration in . */ -#undef ACE_LACKS_SETREUID_PROTOTYPE - -/* Platform lacks pthread_attr_setsched() (e.g. MVS) */ -#undef ACE_LACKS_SETSCHED - -/* Define to 1 if platform lacks setsid(). */ -#undef ACE_LACKS_SETSID - -/* Define to 1 if platform lacks setuid(). */ -#undef ACE_LACKS_SETUID - -/* Define to 1 if platform lacks sigaction(). */ -#undef ACE_LACKS_SIGACTION - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_SIGINFO_H - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_SIGNAL_H - -/* Platform lacks "signed char" type (broken!) */ -#undef ACE_LACKS_SIGNED_CHAR - -/* Define to 1 if the system lacks the type `sigset_t'. */ -#undef ACE_LACKS_SIGSET - -/* Define to 1 if `si_addr' is not a member of `siginfo_t'. */ -#undef ACE_LACKS_SI_ADDR - -/* Define to 1 if platform lacks socketpair(). */ -#undef ACE_LACKS_SOCKETPAIR - -/* Platform doesn't support SO_SNDBUF/SO_RCVBUF (used in TAO) */ -#undef ACE_LACKS_SOCKET_BUFSIZ - -/* Compiler doesn't support static data member templates */ -#undef ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_STDINT_H - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_STDLIB_H - -/* Define to 1 if platform lacks strcasecmp(). */ -#undef ACE_LACKS_STRCASECMP - -/* Define to 1 if platform lacks a declaration for strcasecmp() */ -#undef ACE_LACKS_STRCASECMP_PROTOTYPE - -/* Define to 1 if platform lacks strchr(). */ -#undef ACE_LACKS_STRCHR - -/* Define to 1 if platform lacks strdup(). */ -#undef ACE_LACKS_STRDUP - -/* Define to 1 if platform lacks strerror(). */ -#undef ACE_LACKS_STRERROR - -/* Define to 1 if platform lacks strftime(). */ -#undef ACE_LACKS_STRFTIME - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_STRINGS_H - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_STRING_H - -/* Define to 1 if platform lacks strncasecmp(). */ -#undef ACE_LACKS_STRNCASECMP - -/* Define to 1 if platform lacks a declaration for strncasecmp() */ -#undef ACE_LACKS_STRNCASECMP_PROTOTYPE - -/* Define to 1 if platform lacks the declaration of strnlen(). */ -#undef ACE_LACKS_STRNLEN_PROTOTYPE - -/* Platform lacks stropts.h */ -#undef ACE_LACKS_STROPTS_H - -/* Define to 1 if platform lacks strpbrk(). */ -#undef ACE_LACKS_STRPBRK - -/* Define to 1 if platform lacks strptime(). */ -#undef ACE_LACKS_STRPTIME - -/* Define to 1 if platform lacks the declaration of strptime(). */ -#undef ACE_LACKS_STRPTIME_PROTOTYPE - -/* Define to 1 if platform lacks strrchr(). */ -#undef ACE_LACKS_STRRCHR - -/* Define to 1 if the system lacks the type `struct strrecvfd'. */ -#undef ACE_LACKS_STRRECVFD - -/* Define to 1 if platform lacks strspn(). */ -#undef ACE_LACKS_STRSPN - -/* Define to 1 if platform lacks strtod(). */ -#undef ACE_LACKS_STRTOD - -/* Platform/compiler lacks the strtok_r() prototype */ -#undef ACE_LACKS_STRTOK_R_PROTOTYPE - -/* Define to 1 if platform lacks strtol(). */ -#undef ACE_LACKS_STRTOL - -/* Define to 1 if platform lacks strtoll(). */ -#undef ACE_LACKS_STRTOLL - -/* Define to 1 if platform lacks a declaration for strtoll() */ -#undef ACE_LACKS_STRTOLL_PROTOTYPE - -/* Define to 1 if platform lacks strtoul(). */ -#undef ACE_LACKS_STRTOUL - -/* Define to 1 if platform lacks strtoull(). */ -#undef ACE_LACKS_STRTOULL - -/* Define to 1 if platform lacks a declaration for strtoull() */ -#undef ACE_LACKS_STRTOULL_PROTOTYPE - -/* Define to 1 if the system lacks the type `struct dirent'. */ -#undef ACE_LACKS_STRUCT_DIR - -/* Define to 1 if the system lacks the type 'suseconds_t'. */ -#undef ACE_LACKS_SUSECONDS_T - -/* Define to 1 if platform lacks swab(). */ -#undef ACE_LACKS_SWAB - -/* Define to 1 if platform lacks syscall(). */ -#undef ACE_LACKS_SYSCALL - -/* Define to 1 if platform lacks sysconf(). */ -#undef ACE_LACKS_SYSCONF - -/* Define to 1 if platform lacks system(). */ -#undef ACE_LACKS_SYSTEM - -/* Platform lacks SYSV message queue prototypes */ -#undef ACE_LACKS_SYSV_MSQ_PROTOS - -/* Platform lacks System V shared memory (e.g., Win32 and VxWorks) */ -#undef ACE_LACKS_SYSV_SHMEM - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_SYS_IOCTL_H - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_SYS_IPC_H - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_SYS_MMAN_H - -/* Platform lacks sys/msg.h (e.g., Chorus and VxWorks) */ -#undef ACE_LACKS_SYS_MSG_H - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_SYS_PARAM_H - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_SYS_RESOURCE_H - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_SYS_SELECT_H - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_SYS_SEM_H - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_SYS_SHM_H - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_SYS_SOCKET_H - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_SYS_STAT_H - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_SYS_SYSCTL_H - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_SYS_TIME_H - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_SYS_TYPES_H - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_SYS_UIO_H - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_SYS_UN_H - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_SYS_WAIT_H - -/* OS does not support TCP_NODELAY */ -#undef ACE_LACKS_TCP_NODELAY - -/* Define to 1 if platform lacks telldir(). */ -#undef ACE_LACKS_TELLDIR - -/* Define to 1 if platform lacks tempnam(). */ -#undef ACE_LACKS_TEMPNAM - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_TERMIOS_H - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_TERMIO_H - -/* Platform lacks pthread_attr_setscope() */ -#undef ACE_LACKS_THREAD_PROCESS_SCOPING - -/* Define to 1 if platform lacks the declarations of recv_timedwait, - send_timedwait, etc. */ -#undef ACE_LACKS_TIMEDWAIT_PROTOTYPES - -/* Platform does not define timepec_t as a typedef for struct timespec. */ -#undef ACE_LACKS_TIMESPEC_T - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_TIME_H - -/* Define to 1 if platform lacks towlower(). */ -#undef ACE_LACKS_TOWLOWER - -/* Define to 1 if platform lacks towupper(). */ -#undef ACE_LACKS_TOWUPPER - -/* Define to 1 if platform lacks truncate(). */ -#undef ACE_LACKS_TRUNCATE - -/* Header files lack t_errno for TLI */ -#undef ACE_LACKS_T_ERRNO - -/* Define to 1 if platform lacks the declaration of ualarm(). */ -#undef ACE_LACKS_UALARM_PROTOTYPE - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_UCONTEXT_H - -/* Define to 1 if the system lacks the type `uintmax_t'. */ -#undef ACE_LACKS_UINTMAX_T - -/* Define to 1 if the system lacks the type `uintptr_t'. */ -#undef ACE_LACKS_UINTPTR_T - -/* Define to 1 if platform lacks umask(). */ -#undef ACE_LACKS_UMASK - -/* Define to 1 if platform lacks uname(). */ -#undef ACE_LACKS_UNAME - -/* */ -#undef ACE_LACKS_UNBUFFERED_STREAMBUF - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_UNISTD_H - -/* ACE platform has no UNIX domain sockets */ -#undef ACE_LACKS_UNIX_DOMAIN_SOCKETS - -/* Platform lacks full signal support (e.g., Win32 and Chorus). */ -#undef ACE_LACKS_UNIX_SIGNALS - -/* Define to 1 if platform lacks unlink(). */ -#undef ACE_LACKS_UNLINK - -/* Define to 1 if platform lacks unsetenv(). */ -#undef ACE_LACKS_UNSETENV - -/* Define to 1 if the system lacks the type 'useconds_t'. */ -#undef ACE_LACKS_USECONDS_T - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_UTIME_H - -/* Define to 1 if the system lacks the type `struct utsname'. */ -#undef ACE_LACKS_UTSNAME_T - -/* Define to 1 if the system lacks the type `u_long_long_t'. */ -#undef ACE_LACKS_U_LONGLONG_T - -/* Define to 1 if platform lacks vsnprintf(). */ -#undef ACE_LACKS_VSNPRINTF - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_WCHAR_H - -/* Define to 1 if the system lacks the type `wchar_t'. */ -#undef ACE_LACKS_WCHAR_T - -/* Define to 1 if platform lacks wcscasecmp(). */ -#undef ACE_LACKS_WCSCASECMP - -/* Define to 1 if platform lacks wcscat(). */ -#undef ACE_LACKS_WCSCAT - -/* Define to 1 if platform lacks wcschr(). */ -#undef ACE_LACKS_WCSCHR - -/* Define to 1 if platform lacks wcscmp(). */ -#undef ACE_LACKS_WCSCMP - -/* Define to 1 if platform lacks wcscpy(). */ -#undef ACE_LACKS_WCSCPY - -/* Define to 1 if platform lacks wcscspn(). */ -#undef ACE_LACKS_WCSCSPN - -/* Define to 1 if platform lacks wcsdup(). */ -#undef ACE_LACKS_WCSDUP - -/* Define to 1 if platform lacks wcslen(). */ -#undef ACE_LACKS_WCSLEN - -/* Define to 1 if platform lacks wcsncasecmp(). */ -#undef ACE_LACKS_WCSNCASECMP - -/* Define to 1 if platform lacks wcsncat(). */ -#undef ACE_LACKS_WCSNCAT - -/* Define to 1 if platform lacks wcsncmp(). */ -#undef ACE_LACKS_WCSNCMP - -/* Define to 1 if platform lacks wcsncpy(). */ -#undef ACE_LACKS_WCSNCPY - -/* Define to 1 if platform lacks wcsnicmp(). */ -#undef ACE_LACKS_WCSNICMP - -/* Define to 1 if platform lacks wcspbrk(). */ -#undef ACE_LACKS_WCSPBRK - -/* Define to 1 if platform lacks wcsrchr(). */ -#undef ACE_LACKS_WCSRCHR - -/* Define to 1 if platform lacks wcsspn(). */ -#undef ACE_LACKS_WCSSPN - -/* Define to 1 if platform lacks wcsstr(). */ -#undef ACE_LACKS_WCSSTR - -/* Define to 1 if platform lacks wcstod(). */ -#undef ACE_LACKS_WCSTOD - -/* Define to 1 if platform lacks wcstok(). */ -#undef ACE_LACKS_WCSTOK - -/* Define to 1 if platform lacks wcstol(). */ -#undef ACE_LACKS_WCSTOL - -/* Define to 1 if platform lacks wcstoll(). */ -#undef ACE_LACKS_WCSTOLL - -/* Define to 1 if platform lacks a declaration for wcstoll() */ -#undef ACE_LACKS_WCSTOLL_PROTOTYPE - -/* Define to 1 if platform lacks wcstoul(). */ -#undef ACE_LACKS_WCSTOUL - -/* Define to 1 if platform lacks wcstoull(). */ -#undef ACE_LACKS_WCSTOULL - -/* Define to 1 if platform lacks a declaration for wcstoull() */ -#undef ACE_LACKS_WCSTOULL_PROTOTYPE - -/* Define to 1 if platform lacks the header file. */ -#undef ACE_LACKS_WCTYPE_H - -/* Define to 1 if platform lacks writev(). */ -#undef ACE_LACKS_WRITEV - -/* Define to environment variable used for DLL search path */ -#undef ACE_LD_SEARCH_PATH - -/* typedef for ACE_LOFF_T */ -#undef ACE_LOFF_T_TYPEDEF - -/* Renames "main (int, char *[])", for platforms such as g++/VxWorks that - don't allow main. Requires the use of ACE_HAS_NONSTATIC_OBJECT_MANAGER. */ -#undef ACE_MAIN - -/* */ -#undef ACE_MALLOC_ALIGN - -/* */ -#undef ACE_MAP_PRIVATE - -/* Define to 1 if platform has 1 parameter mkdir() */ -#undef ACE_MKDIR_LACKS_MODE - -/* Compile using multi-thread libraries */ -#undef ACE_MT_SAFE - -/* Turns off debugging features */ -#undef ACE_NDEBUG - -/* Necessary with some compilers to pass ACE_TTY_IO as parameter to - DEV_Connector. */ -#undef ACE_NEEDS_DEV_IO_CONVERSION - -/* Compiler requires a definition for a "hidden" function, e.g., a private, - unimplemented copy constructor or assignment operator. The SGI C++ compiler - needs this, in template classes, with - ACE_HAS_TEMPLATE_INSTANTIATION_PRAGMA. */ -#undef ACE_NEEDS_FUNC_DEFINITIONS - -/* Required by platforms with small default stacks. */ -#undef ACE_NEEDS_HUGE_THREAD_STACKSIZE - -/* OS has LWPs, and when the priority of a bound thread is set, then the LWP - priority must be set also. */ -#undef ACE_NEEDS_LWP_PRIO_SET - -/* Platform needs to #include to get thread scheduling defs. */ -#undef ACE_NEEDS_SCHED_H - -/* Compiler's 'new' throws exception on failure (ANSI C++ behavior). */ -#undef ACE_NEW_THROWS_EXCEPTIONS - -/* Turns off the LM_DEBUG and LM_ERROR logging macros... */ -#undef ACE_NLOGGING - -/* Explicitly disable ACE inlining */ -#undef ACE_NO_INLINE - -/* Turns off the tracing feature. */ -#undef ACE_NTRACE - -/* Defines the page size of the system (not used on Win32 or with - ACE_HAS_GETPAGESIZE). */ -#undef ACE_PAGE_SIZE - -/* Flag that denotes the symbol should be exported from the DSO/DLL. */ -#undef ACE_Proper_Export_Flag - -/* Flag that denotes the symbol should be imported from the DSO/DLL. */ -#undef ACE_Proper_Import_Flag - -/* Platform redefines the t_... names (UnixWare) */ -#undef ACE_REDEFINES_XTI_FUNCTIONS - -/* shm_open() requires a leading slash in name */ -#undef ACE_SHM_OPEN_REQUIRES_ONE_SLASH - -/* Size of the native "double" type */ -#undef ACE_SIZEOF_DOUBLE - -/* Size of the native "float" type */ -#undef ACE_SIZEOF_FLOAT - -/* Size of the native "int" type */ -#undef ACE_SIZEOF_INT - -/* Size of the native "long" type */ -#undef ACE_SIZEOF_LONG - -/* Size of the native "long double" type */ -#undef ACE_SIZEOF_LONG_DOUBLE - -/* Size of the native "long long" type */ -#undef ACE_SIZEOF_LONG_LONG - -/* Size of the native "short" type */ -#undef ACE_SIZEOF_SHORT - -/* Size of the native "pointer to void" type */ -#undef ACE_SIZEOF_VOID_P - -/* Size of the native "wchar_t" type */ -#undef ACE_SIZEOF_WCHAR - -/* Define to the *printf format specifier (e.g. "%u") for size_t */ -#undef ACE_SIZE_T_FORMAT_SPECIFIER - -/* Define to the *printf format specifier (e.g. "%d") for ssize_t */ -#undef ACE_SSIZE_T_FORMAT_SPECIFIER - -/* Define to function that is equivalent to strcasecmp() */ -#undef ACE_STRCASECMP_EQUIVALENT - -/* Define to function that is equivalent to strdup() */ -#undef ACE_STRDUP_EQUIVALENT - -/* Define to function that is equivalent to strncasecmp() */ -#undef ACE_STRNCASECMP_EQUIVALENT - -/* Define to function that is equivalent to strtoll() */ -#undef ACE_STRTOLL_EQUIVALENT - -/* Define to function that is equivalent to strtoull() */ -#undef ACE_STRTOULL_EQUIVALENT - -/* Compiler's template mechanism must use a pragma. This is used for AIX's C++ - compiler. */ -#undef ACE_TEMPLATES_REQUIRE_PRAGMA - -/* Compiler's template mechanim must see source code (i.e., .cpp files). This - is used for GNU G++. */ -#undef ACE_TEMPLATES_REQUIRE_SOURCE - -/* Specify this if you don't want threads to inherit parent thread's - ACE_Log_Msg properties. */ -#undef ACE_THREADS_DONT_INHERIT_LOG_MSG - -/* */ -#undef ACE_THR_PRI_FIFO_DEF - -/* */ -#undef ACE_TIMER_SKEW - -/* Device the platform uses for TCP on TLI. Only needed if not /dev/tcp. */ -#undef ACE_TLI_TCP_DEVICE - -/* Define to the *printf format specifier (e.g. "%llu") for ACE_UINT64 */ -#undef ACE_UINT64_FORMAT_SPECIFIER - -/* Define to unsigned 64 bit integer type */ -#undef ACE_UINT64_TYPE - -/* Platform uses assembly symbols instead of C symbols in dlsym() */ -#undef ACE_USES_ASM_SYMBOL_IN_DLSYM - -/* Enable IPv6 support on platforms that don't have IPv6 turned on by default - */ -#undef ACE_USES_IPV4_IPV6_MIGRATION - -/* Some files, such as ace/streams.h, want to include new style C++ stream - headers. These headers are iomanip, ios, iostream, istream, ostream, - fstream and streambuf. If _all_ of these headers aren't available, then - assume that only iostream.h and fstream.h are available. */ -#undef ACE_USES_OLD_IOSTREAMS - -/* When linking MFC as a static library is desired */ -#undef ACE_USES_STATIC_MFC - -/* Platform has its standard C++ library in the namespace std. */ -#undef ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB - -/* ACE is built to use wide characters internally */ -#undef ACE_USES_WCHAR - -/* The OS/platform supports the poll() event demultiplexor */ -#undef ACE_USE_POLL - -/* Define to 1 to embed RCS ID strings into compiled object files. */ -#undef ACE_USE_RCSID - -/* For Win32: Use Select_Reactor as default implementation of Reactor instead - of WFMO_Reactor. */ -#undef ACE_USE_SELECT_REACTOR_FOR_REACTOR_IMPL - -/* Define to function that is equivalent to wcscasecmp() */ -#undef ACE_WCSCASECMP_EQUIVALENT - -/* Define to function that is equivalent to wcsdup() */ -#undef ACE_WCSDUP_EQUIVALENT - -/* Define to function that is equivalent to wcsncasecmp() */ -#undef ACE_WCSNCASECMP_EQUIVALENT - -/* Define to function that is equivalent to wcstoll() */ -#undef ACE_WCSTOLL_EQUIVALENT - -/* Define to function that is equivalent to wcstoull() */ -#undef ACE_WCSTOULL_EQUIVALENT - -/* Configure for use on Win32 */ -#undef ACE_WIN32 - -/* A parameter list indicating the version of WinSock (e.g., "1, 1" is version - 1.1). */ -#undef ACE_WSOCK_VERSION - -/* Define if building universal (internal helper macro) */ -#undef AC_APPLE_UNIVERSAL_BUILD - -/* Configure for use on AIX */ -#undef AIX - -/* Define to 1 if the `closedir' function returns void instead of `int'. */ -#undef CLOSEDIR_VOID - -/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP - systems. This function is required for `alloca.c' support on those systems. - */ -#undef CRAY_STACKSEG_END - -/* GNU Win32 environement */ -#undef CYGWIN32 - -/* Define to 1 if using `alloca.c'. */ -#undef C_ALLOCA - -/* */ -#undef DEC_CXX - -/* Configure for use on Digital Unix */ -#undef DIGITAL_UNIX - -/* Define to 1 if you have `alloca', as a function or macro. */ -#undef HAVE_ALLOCA - -/* Define to 1 if you have and it should be used (not on Ultrix). - */ -#undef HAVE_ALLOCA_H - -/* Define to 1 if you have the header file, and it defines `DIR'. - */ -#undef HAVE_DIRENT_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_DLFCN_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_FSTREAM - -/* Define to 1 if you have the header file. */ -#undef HAVE_FSTREAM_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_INTTYPES_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_IOMANIP - -/* Define to 1 if you have the header file. */ -#undef HAVE_IOS - -/* Define to 1 if you have the header file. */ -#undef HAVE_IOSTREAM - -/* Define to 1 if you have the header file. */ -#undef HAVE_IOSTREAM_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_ISTREAM - -/* Define to 1 if you have the `dld' library (-ldld). */ -#undef HAVE_LIBDLD - -/* Define to 1 if you have the header file. */ -#undef HAVE_MEMORY_H - -/* Define to 1 if you have the header file, and it defines `DIR'. */ -#undef HAVE_NDIR_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_OSTREAM - -/* Define to 1 if you have the header file. */ -#undef HAVE_STDINT_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_STDLIB_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_STREAMBUF - -/* Define to 1 if you have the `strftime' function. */ -#undef HAVE_STRFTIME - -/* Define to 1 if you have the header file. */ -#undef HAVE_STRINGS_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_STRING_H - -/* Define to 1 if you have the header file, and it defines `DIR'. - */ -#undef HAVE_SYS_DIR_H - -/* Define to 1 if you have the header file, and it defines `DIR'. - */ -#undef HAVE_SYS_NDIR_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_STAT_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_TYPES_H - -/* Define to 1 if you have that is POSIX.1 compatible. */ -#undef HAVE_SYS_WAIT_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_UNISTD_H - -/* Configure for use on HP-UX */ -#undef HPUX - -/* Configure for use on HP-UX 10 */ -#undef HPUX_10 - -/* Configure for use on HP-UX 11 */ -#undef HPUX_11 - -/* */ -#undef IP_ADD_MEMBERSHIP - -/* */ -#undef IP_DROP_MEMBERSHIP - -/* Configure for use on Irix 5 */ -#undef IRIX5 - -/* Configure for use on Irix 6 */ -#undef IRIX6 - -/* Define to the sub-directory in which libtool stores uninstalled libraries. - */ -#undef LT_OBJDIR - -/* Define to the address where bug reports for this package should be sent. */ -#undef PACKAGE_BUGREPORT - -/* Define to the full name of this package. */ -#undef PACKAGE_NAME - -/* Define to the full name and version of this package. */ -#undef PACKAGE_STRING - -/* Define to the one symbol short name of this package. */ -#undef PACKAGE_TARNAME - -/* Define to the version of this package. */ -#undef PACKAGE_VERSION - -/* Maximum thread priority */ -#undef PTHREAD_MAX_PRIORITY - -/* Minimum thread priority */ -#undef PTHREAD_MIN_PRIORITY - -/* */ -#undef PTHREAD_STACK_MIN - -/* */ -#undef SCO - -/* The size of `double', as computed by sizeof. */ -#undef SIZEOF_DOUBLE - -/* The size of `float', as computed by sizeof. */ -#undef SIZEOF_FLOAT - -/* The size of `int', as computed by sizeof. */ -#undef SIZEOF_INT - -/* The size of `long', as computed by sizeof. */ -#undef SIZEOF_LONG - -/* The size of `long double', as computed by sizeof. */ -#undef SIZEOF_LONG_DOUBLE - -/* The size of `long long', as computed by sizeof. */ -#undef SIZEOF_LONG_LONG - -/* The size of `short', as computed by sizeof. */ -#undef SIZEOF_SHORT - -/* The size of `signed char', as computed by sizeof. */ -#undef SIZEOF_SIGNED_CHAR - -/* The size of `void *', as computed by sizeof. */ -#undef SIZEOF_VOID_P - -/* The size of `wchar_t', as computed by sizeof. */ -#undef SIZEOF_WCHAR_T - -/* If using the C implementation of alloca, define if you know the - direction of stack growth for your system; otherwise it will be - automatically deduced at runtime. - STACK_DIRECTION > 0 => grows toward higher addresses - STACK_DIRECTION < 0 => grows toward lower addresses - STACK_DIRECTION = 0 => direction of growth unknown */ -#undef STACK_DIRECTION - -/* Define to 1 if you have the ANSI C header files. */ -#undef STDC_HEADERS - -/* Configure for use on UnixWare */ -#undef UNIXWARE - -/* */ -#undef UNIXWARE_2_0 - -/* */ -#undef UNIXWARE_2_1 - -/* */ -#undef UNIXWARE_7_1 - -/* Configure for use on VxWorks */ -#undef VXWORKS - -/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most - significant byte first (like Motorola and SPARC, unlike Intel). */ -#if defined AC_APPLE_UNIVERSAL_BUILD -# if defined __BIG_ENDIAN__ -# define WORDS_BIGENDIAN 1 -# endif -#else -# ifndef WORDS_BIGENDIAN -# undef WORDS_BIGENDIAN -# endif -#endif - -/* Define to 1 if the X Window System is missing or not being used. */ -#undef X_DISPLAY_MISSING - -/* Define to 1 if `lex' declares `yytext' as a `char *' by default, not a - `char[]'. */ -#undef YYTEXT_POINTER - -/* Enable ACE inlining */ -#undef __ACE_INLINE__ - -/* */ -#undef __IOCTL_VERSIONED__ - -/* */ -#undef __NO_INCLUDE_WARN__ - - - - -#endif /* ACE_CONFIG_H */ - - -// Local Variables: -// mode:C++ -// End: - - diff --git a/externals/ace/gethrtime.cpp b/externals/ace/gethrtime.cpp deleted file mode 100644 index 69de03153a1..00000000000 --- a/externals/ace/gethrtime.cpp +++ /dev/null @@ -1,60 +0,0 @@ -// $Id: gethrtime.cpp 80826 2008-03-04 14:51:23Z wotte $ -// -// Build this file with g++. It can be linked in to a ACE application -// that was compiled with GreenHills. It wouldn't be necessary if I -// knew a way to correctly move values from registers to a 64-bit -// variable in GHS asm code. That's easy with g++ asm. - -#include "ace/config-all.h" - -ACE_RCSID(ace, gethrtime, "$Id: gethrtime.cpp 80826 2008-03-04 14:51:23Z wotte $") - -#if defined (ghs) && (defined (i386) || defined(__i386__)) - -#include "ace/OS_NS_time.h" - -extern "C" -ACE_hrtime_t -ACE_GETHRTIME_NAME (void) -{ -#if defined (ACE_HAS_PENTIUM) - // ACE_TRACE ("ACE_GETHRTIME_NAME"); - -#if defined (ACE_LACKS_LONGLONG_T) - double now; -#else /* ! ACE_LACKS_LONGLONG_T */ - ACE_hrtime_t now; -#endif /* ! ACE_LACKS_LONGLONG_T */ - - // Read the high-res tick counter directly into memory variable - // "now". The A constraint signifies a 64-bit int. -#if defined (__GNUG__) - asm volatile ("rdtsc" : "=A" (now) : : "memory"); -// #elif defined (ghs) -// The following doesn't work. For now, this file must be compile with g++. -// asm ("rdtsc"); -// asm ("movl %edx,-16(%ebp)"); -// asm ("movl %eax,-12(%ebp)"); -#else -# error unsupported compiler -#endif - -#if defined (ACE_LACKS_LONGLONG_T) - // ACE_U_LongLong doesn't have the same layout as now, so construct - // it "properly". - ACE_UINT32 least, most; - ACE_OS::memcpy (&least, &now, sizeof (ACE_UINT32)); - ACE_OS::memcpy (&most, (unsigned char *) &now + sizeof (ACE_UINT32), - sizeof (ACE_UINT32)); - - const ACE_hrtime_t ret (least, most); - return ret; -#else /* ! ACE_LACKS_LONGLONG_T */ - return now; -#endif /* ! ACE_LACKS_LONGLONG_T */ - -#else /* ! ACE_HAS_PENTIUM */ -# error This file can _only_ be compiled with ACE_HAS_PENTIUM. -#endif /* ! ACE_HAS_PENTIUM */ -} -#endif /* ghs */ diff --git a/externals/ace/iosfwd.h b/externals/ace/iosfwd.h deleted file mode 100644 index b9576ebae97..00000000000 --- a/externals/ace/iosfwd.h +++ /dev/null @@ -1,100 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file iosfwd.h - * - * $Id: iosfwd.h 89098 2010-02-21 21:51:41Z schmidt $ - * - * @author Irfan Pyarali - * - * This file contains the portability ugliness for the Standard C++ - * Library. As implementations of the "standard" emerge, this file - * will need to be updated. - * - * This files deals with forward declaration for the stream - * classes. Remember that since the new Standard C++ Library code - * for streams uses templates, simple forward declaration will not - * work. - */ -//============================================================================= - - -#ifndef ACE_IOSFWD_H -#define ACE_IOSFWD_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_IOSTREAM_TOTALLY) - -#if defined (__APPLE_CC__) -// Should this really be here? dhinton -// FUZZ: disable check_for_streams_include -# include "ace/streams.h" -#endif - -#if defined (ACE_HAS_STANDARD_CPP_LIBRARY) && \ - (ACE_HAS_STANDARD_CPP_LIBRARY != 0) - -# if !defined (ACE_USES_OLD_IOSTREAMS) -# include /**/ -#define ACE_HAS_CPP98_IOSTREAMS 1 -# else - // @note If these forward declarations don't work (e.g. aren't - // portable), we may have to include "ace/streams.h" as a last - // resort. Doing so would defeat the purpose of this header, - // unfortunately. - class ios; - class streambuf; - class istream; - class ostream; - class iostream; - class filebuf; - class ifstream; - class ofstream; - class fstream; -# endif /* ! ACE_USES_OLD_IOSTREAMS */ - -# if defined (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB) && \ - (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB != 0) - -# if !defined (ACE_USES_OLD_IOSTREAMS) - // Make these available in the global name space - using std::ios; - using std::streambuf; - using std::istream; - using std::ostream; - using std::iostream; - using std::filebuf; - using std::ifstream; - using std::ofstream; - using std::fstream; -# endif /* ! ACE_USES_OLD_IOSTREAMS */ - -# endif /* ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB */ - -#else /* ! ACE_HAS_STANDARD_CPP_LIBRARY */ - - class ios; - class streambuf; - class istream; - class ostream; - class iostream; - class filebuf; - class ifstream; - class ofstream; - class fstream; - -# endif /* ! ACE_HAS_STANDARD_CPP_LIBRARY */ - -#include /**/ "ace/post.h" - -#endif /* ACE_LACKS_IOSTREAM_TOTALLY */ - -#endif /* ACE_IOSFWD_H */ diff --git a/externals/ace/os_include/arpa/os_inet.h b/externals/ace/os_include/arpa/os_inet.h deleted file mode 100644 index b97f7c6e419..00000000000 --- a/externals/ace/os_include/arpa/os_inet.h +++ /dev/null @@ -1,74 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_inet.h - * - * definitions for internet operations - * - * $Id: os_inet.h 85015 2009-04-03 12:27:59Z johnnyw $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_ARPA_OS_INET_H -#define ACE_OS_INCLUDE_ARPA_OS_INET_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/netinet/os_in.h" - -#if !defined (ACE_LACKS_ARPA_INET_H) - extern "C" { -# include /**/ - } -#endif /* !ACE_LACKS_ARPA_INET_H */ - -#if defined (ACE_USES_INETLIB_H) -# include /**/ -#endif /* ACE_USES_INETLIB_H */ - -/** - * In some environments it is useful to swap the bytes on write, for - * instance: a fast server can be feeding a lot of slow clients that - * happen to have the wrong byte order. - * Because this is a rarely used feature we disable it by default to - * minimize footprint. - * This macro enables the functionality, but we still need a way to - * activate it on a per-connection basis. - */ -// #define ACE_ENABLE_SWAP_ON_WRITE - -/** - * In some environements we never need to swap bytes when reading, for - * instance embebbed systems (such as avionics) or homogenous - * networks. - * Setting this macro disables the capabilities to demarshall streams - * in the wrong byte order. - */ -// #define ACE_DISABLE_SWAP_ON_READ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#if defined (ACE_LACKS_INET_ATON_PROTOTYPE) - int inet_aton (const char *, struct in_addr *); -#endif /* ACE_LACKS_INET_ATON_PROTOTYPE */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_ARPA_OS_INET_H */ diff --git a/externals/ace/os_include/net/os_if.h b/externals/ace/os_include/net/os_if.h deleted file mode 100644 index 3dcf5918f8c..00000000000 --- a/externals/ace/os_include/net/os_if.h +++ /dev/null @@ -1,112 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_if.h - * - * sockets local interfaces - * - * $Id: os_if.h 88719 2010-01-26 12:55:03Z sowayaa $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_NET_OS_IF_H -#define ACE_OS_INCLUDE_NET_OS_IF_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_NET_IF_H) -# include /**/ -# if defined (ACE_HAS_NET_IF_DL_H) -# include /**/ -# endif /* ACE_HAS_NET_IF_DL_H */ -# if defined (HPUX) && defined (IOR) - /* HP-UX 11.11 defines IOR in /usr/include/pa/inline.h - and we don't want that definition. See IOP_IORC.h. - Thanks to Torsten Kopper for this patch.*/ -# undef IOR -# endif /* HPUX && IOR */ -#endif /* !ACE_LACKS_NET_IF_H */ - -#if defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0) -# include /**/ -#endif /* ACE_HAS_WINSOCK2 */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#if defined (ACE_HAS_BROKEN_IF_HEADER) - struct ifafilt; -#endif /* ACE_HAS_BROKEN_IF_HEADER */ - -#if defined (ACE_LACKS_IFREQ) -struct ifreq { -#define IFNAMSIZ 16 - char ifr_name[IFNAMSIZ]; /* if name, e.g. "en0" */ - union { - struct sockaddr ifru_addr; - struct sockaddr ifru_dstaddr; - struct sockaddr ifru_broadaddr; - short ifru_flags; - int ifru_metric; - int ifru_mtu; - int ifru_phys; - int ifru_media; - caddr_t ifru_data; - int (*ifru_tap)(struct ifnet *, struct ether_header *, struct mbuf *); - } ifr_ifru; -#define ifr_addr ifr_ifru.ifru_addr /* address */ -#define ifr_dstaddr ifr_ifru.ifru_dstaddr /* other end of p-to-p link */ -#define ifr_broadaddr ifr_ifru.ifru_broadaddr /* broadcast address */ -#define ifr_flags ifr_ifru.ifru_flags /* flags */ -#define ifr_metric ifr_ifru.ifru_metric /* metric */ -#define ifr_mtu ifr_ifru.ifru_mtu /* mtu */ -#define ifr_phys ifr_ifru.ifru_phys /* physical wire */ -#define ifr_media ifr_ifru.ifru_media /* physical media */ -#define ifr_data ifr_ifru.ifru_data /* for use by interface */ -#define ifr_tap ifr_ifru.ifru_tap /* tap function */ -}; -#endif /* ACE_LACKS_IFREQ */ - -#if defined (ACE_LACKS_IFCONF) -struct ifconf { - int ifc_len; - union { - caddr_t ifcu_buf; - struct ifreq *ifcu_req; - } ifc_ifcu; -#define ifc_buf ifc_ifcu.ifcu_buf /* buffer address */ -#define ifc_req ifc_ifcu.ifcu_req /* array of structures returned */ - }; -#endif /* ACE_LACKS_IFCONF */ - -#if !defined (IFF_UP) -# define IFF_UP 0x1 -#endif /* IFF_UP */ - -#if !defined (IFF_LOOPBACK) -# define IFF_LOOPBACK 0x8 -#endif /* IFF_LOOPBACK */ - -#if !defined (IFF_BROADCAST) -# define IFF_BROADCAST 0x2 -#endif /* IFF_BROADCAST */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_NET_OS_IF_H */ diff --git a/externals/ace/os_include/netinet/os_in.h b/externals/ace/os_include/netinet/os_in.h deleted file mode 100644 index dff894aadce..00000000000 --- a/externals/ace/os_include/netinet/os_in.h +++ /dev/null @@ -1,179 +0,0 @@ - -// -*- C++ -*- - -//============================================================================= -/** - * @file os_in.h - * - * Internet address family - * - * $Id: os_in.h 85438 2009-05-26 06:56:46Z johnnyw $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_NETINET_OS_IN_H -#define ACE_OS_INCLUDE_NETINET_OS_IN_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/os_inttypes.h" -#include "ace/os_include/sys/os_socket.h" - -#if defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0) -# include /**/ -#endif /* ACE_HAS_WINSOCK2 */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#if !defined (ACE_LACKS_NETINET_IN_H) -# include /**/ -#endif /* !ACE_LACKS_NETINET_IN_H */ - - -# if defined (ACE_HAS_PHARLAP_RT) -# define ACE_IPPROTO_TCP SOL_SOCKET -# else -# define ACE_IPPROTO_TCP IPPROTO_TCP -# endif /* ACE_HAS_PHARLAP_RT */ - -# if !defined (ACE_HAS_IP_MULTICAST) && defined (ACE_LACKS_IP_ADD_MEMBERSHIP) - // Even if ACE_HAS_IP_MULTICAST is not defined, if IP_ADD_MEMBERSHIP - // is defined, assume that the ip_mreq struct is also defined - // (presumably in netinet/in.h). - struct ip_mreq - { - /// IP multicast address of group - struct in_addr imr_multiaddr; - /// Local IP address of interface - struct in_addr imr_interface; - }; -# endif /* ! ACE_HAS_IP_MULTICAST && ACE_LACKS_IP_ADD_MEMBERSHIP */ - -# if defined (ACE_LACKS_IN_ADDR) - struct in_addr - { - u_long s_addr; - }; -# endif /* ACE_LACKS_IN_ADDR */ - -# if defined (ACE_LACKS_SOCKADDR_IN) - struct sockaddr_in - { - short sin_family; // e.g. AF_INET - unsigned short sin_port; // e.g. htons(3490) - struct in_addr sin_addr; // see struct in_addr, below - char sin_zero[8]; // zero this if you want to - }; -# endif /* ACE_LACKS_SOCKADDR_IN */ - -# if defined (ACE_LACKS_SOCKADDR_UN) - struct sockaddr_un { - u_char sun_len; /* sockaddr len including null */ - u_char sun_family; /* AF_UNIX */ - char sun_path[104]; /* path name (gag) */ - }; -#endif /* ACE_LACKS_SOCKADDR_UN */ - -# if defined (ACE_LACKS_IP_MREQ) - struct ip_mreq - { - struct in_addr imr_multiaddr; /* IP multicast address of group */ - struct in_addr imr_interface; /* local IP address of interface */ - }; -# endif /* ACE_LACKS_IP_MREQ */ - -#if !defined (IPPORT_RESERVED) -# define IPPORT_RESERVED 1024 -#endif /* !IPPORT_RESERVED */ - -#if !defined (IPPORT_USERRESERVED) -# define IPPORT_USERRESERVED 5000 -#endif /* !IPPORT_USERRESERVED */ - -// Define INET loopback address constant if it hasn't been defined -// Dotted Decimal 127.0.0.1 == Hexidecimal 0x7f000001 -#if !defined (INADDR_LOOPBACK) -# define INADDR_LOOPBACK ((ACE_UINT32) 0x7f000001) -#endif /* INADDR_LOOPBACK */ - -// The INADDR_NONE address is generally 255.255.255.255. -#if !defined (INADDR_NONE) -# define INADDR_NONE ((ACE_UINT32) 0xffffffff) -#endif /* INADDR_NONE */ - -// Define INET string length constants if they haven't been defined -// -// for IPv4 dotted-decimal -#if !defined (INET_ADDRSTRLEN) -# define INET_ADDRSTRLEN 16 -#endif /* INET_ADDRSTRLEN */ -// -// for IPv6 hex string -#if !defined (INET6_ADDRSTRLEN) -# define INET6_ADDRSTRLEN 46 -#endif /* INET6_ADDRSTRLEN */ - -# if !defined (IP_DROP_MEMBERSHIP) -# define IP_DROP_MEMBERSHIP 0 -# endif /* IP_DROP_MEMBERSHIP */ - -# if !defined (IP_ADD_MEMBERSHIP) -# define IP_ADD_MEMBERSHIP 0 -# define ACE_LACKS_IP_ADD_MEMBERSHIP -# endif /* IP_ADD_MEMBERSHIP */ - -# if !defined (IP_DEFAULT_MULTICAST_TTL) -# define IP_DEFAULT_MULTICAST_TTL 0 -# endif /* IP_DEFAULT_MULTICAST_TTL */ - -# if !defined (IP_DEFAULT_MULTICAST_LOOP) -# define IP_DEFAULT_MULTICAST_LOOP 0 -# endif /* IP_DEFAULT_MULTICAST_LOOP */ - -# if !defined (IP_MULTICAST_IF) -# define IP_MULTICAST_IF 0 -# endif /* IP_MULTICAST_IF */ - -# if !defined (IP_MULTICAST_TTL) -# define IP_MULTICAST_TTL 1 -# endif /* IP_MULTICAST_TTL */ - -# if !defined (IP_MULTICAST_LOOP) -# define IP_MULTICAST_LOOP 2 -# endif /* IP_MULTICAST_LOOP */ - -# if !defined (IP_MAX_MEMBERSHIPS) -# define IP_MAX_MEMBERSHIPS 0 -# endif /* IP_MAX_MEMBERSHIP */ - -# if !defined (IPPROTO_IP) -# define IPPROTO_IP 0 -# endif /* IPPROTO_IP */ - -# if !defined (IPPROTO_TCP) -# define IPPROTO_TCP 6 -# endif /* IPPROTO_TCP */ - -# if !defined (INADDR_ANY) -# define INADDR_ANY (u_long)0x00000000 -# endif /* INADDR_ANY */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_NETINET_OS_IN_H */ diff --git a/externals/ace/os_include/netinet/os_tcp.h b/externals/ace/os_include/netinet/os_tcp.h deleted file mode 100644 index aca6590bc94..00000000000 --- a/externals/ace/os_include/netinet/os_tcp.h +++ /dev/null @@ -1,46 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_tcp.h - * - * definitions for the Internet Transmission Control Protocol (TCP) - * - * $Id: os_tcp.h 88499 2010-01-12 19:34:34Z olli $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_NETINET_OS_TCP_H -#define ACE_OS_INCLUDE_NETINET_OS_TCP_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_NETINET_TCP_H) -# include /**/ -#endif /* !ACE_LACKS_NETINET_TCP_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -# if !defined (TCP_NODELAY) -# define TCP_NODELAY 0x01 -# endif /* TCP_NODELAY */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_NETINET_OS_TCP_H */ diff --git a/externals/ace/os_include/os_aio.h b/externals/ace/os_include/os_aio.h deleted file mode 100644 index 4ec9fe9d127..00000000000 --- a/externals/ace/os_include/os_aio.h +++ /dev/null @@ -1,47 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_aio.h - * - * asynchronous input and output (REALTIME) - * - * $Id: os_aio.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_AIO_H -#define ACE_OS_INCLUDE_OS_AIO_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -// Inclusion of the header may make visible symbols defined in -// the headers , , , and . - -#include "ace/os_include/os_signal.h" // for sigevent - -#if !defined (ACE_LACKS_AIO_H) -# include /**/ -#endif /* !ACE_LACKS_AIO_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_AIO_H */ diff --git a/externals/ace/os_include/os_assert.h b/externals/ace/os_include/os_assert.h deleted file mode 100644 index fdca573fe8e..00000000000 --- a/externals/ace/os_include/os_assert.h +++ /dev/null @@ -1,46 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_assert.h - * - * verify program assertion - * - * $Id: os_assert.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_ASSERT_H -#define ACE_OS_INCLUDE_OS_ASSERT_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_ASSERT_H) -# include /**/ -#endif /* !ACE_LACKS_ASSERT_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#if defined (ACE_LACKS_ASSERT_MACRO) -# define assert(expr) -#endif - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_ASSERT_H */ diff --git a/externals/ace/os_include/os_byteswap.h b/externals/ace/os_include/os_byteswap.h deleted file mode 100644 index b55754ee810..00000000000 --- a/externals/ace/os_include/os_byteswap.h +++ /dev/null @@ -1,41 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_byteswap.h - * - * Byteswap methods - * - * $Id: os_byteswap.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Johnny Willemsen - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_BYTESWAP_H -#define ACE_OS_INCLUDE_OS_BYTESWAP_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_BYTESWAP_H) -# include /**/ -#endif /* !ACE_HAS_INTRIN_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_BYTESWAP_H */ diff --git a/externals/ace/os_include/os_complex.h b/externals/ace/os_include/os_complex.h deleted file mode 100644 index 5e6546f82df..00000000000 --- a/externals/ace/os_include/os_complex.h +++ /dev/null @@ -1,42 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_complex.h - * - * complex arithmetic - * - * $Id: os_complex.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_COMPLEX_H -#define ACE_OS_INCLUDE_OS_COMPLEX_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_COMPLEX_H) -# include /**/ -#endif /* !ACE_LACKS_COMPLEX_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_COMPLEX_H */ diff --git a/externals/ace/os_include/os_cpio.h b/externals/ace/os_include/os_cpio.h deleted file mode 100644 index 2c06e8eb2f5..00000000000 --- a/externals/ace/os_include/os_cpio.h +++ /dev/null @@ -1,42 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_cpio.h - * - * cpio archive values - * - * $Id: os_cpio.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_CPIO_H -#define ACE_OS_INCLUDE_OS_CPIO_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_CPIO_H) -# include /**/ -#endif /* !ACE_LACKS_CPIO_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_CPIO_H */ diff --git a/externals/ace/os_include/os_ctype.h b/externals/ace/os_include/os_ctype.h deleted file mode 100644 index 4b5b65120c5..00000000000 --- a/externals/ace/os_include/os_ctype.h +++ /dev/null @@ -1,48 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_ctype.h - * - * character types - * - * $Id: os_ctype.h 83520 2008-11-03 08:54:08Z johnnyw $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_CTYPE_H -#define ACE_OS_INCLUDE_OS_CTYPE_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_CTYPE_H) -# include /**/ -#endif /* !ACE_LACKS_CTYPE_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -// @todo move the is* and is* emulation methods in ACE_OS here -// and let ACE_OS just call them. -#if !defined (ACE_HAS_CTYPE_T) -typedef int ctype_t; -#endif - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_CTYPE_H */ diff --git a/externals/ace/os_include/os_dirent.h b/externals/ace/os_include/os_dirent.h deleted file mode 100644 index 034bacd006d..00000000000 --- a/externals/ace/os_include/os_dirent.h +++ /dev/null @@ -1,110 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_dirent.h - * - * format of directory entries - * - * $Id: os_dirent.h 82985 2008-10-08 18:15:30Z johnnyw $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_DIRENT_H -#define ACE_OS_INCLUDE_OS_DIRENT_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_types.h" -#include "ace/os_include/os_limits.h" - -#if defined (ACE_VXWORKS) && (ACE_VXWORKS < 0x620) -# include "ace/os_include/os_unistd.h" // VxWorks needs this to compile -#endif /* ACE_VXWORKS */ - -#if !defined (ACE_LACKS_DIRENT_H) -# include /**/ -#endif /* !ACE_LACKS_DIRENT_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#if !defined (MAXNAMLEN) -# define MAXNAMLEN NAME_MAX -#endif /* !MAXNAMLEN */ - -// At least compile on some of the platforms without info yet. -#if !defined (ACE_HAS_DIRENT) -typedef int ACE_DIR; -struct dirent { -}; -#endif /* ACE_HAS_DIRENT */ - -#if defined (ACE_LACKS_STRUCT_DIR) -struct dirent { - unsigned short d_ino; - unsigned short d_off; - unsigned short d_reclen; - // This must be a ACE_TCHAR * and not a one element - // ACE_TCHAR array. It causes problems on wide - // character builds with Visual C++ 6.0. - ACE_TCHAR *d_name; -}; - -#define ACE_DIRENT dirent -#define ACE_HAS_TCHAR_DIRENT - -struct ACE_DIR { - /// The name of the directory we are looking into - ACE_TCHAR *directory_name_; - - /// Remember the handle between calls. - HANDLE current_handle_; - - /// The struct for the results - ACE_DIRENT *dirent_; - - /// The struct for intermediate results. - ACE_TEXT_WIN32_FIND_DATA fdata_; - - /// A flag to remember if we started reading already. - int started_reading_; -}; -#elif defined (ACE_WIN32) && (__BORLANDC__) && defined (ACE_USES_WCHAR) -#define ACE_HAS_TCHAR_DIRENT -#define ACE_DIRENT wdirent -typedef wDIR ACE_DIR; -#else -#define ACE_DIRENT dirent -typedef DIR ACE_DIR; -#endif /* ACE_LACKS_STRUCT_DIR */ - -#if defined (ACE_LACKS_SCANDIR_PROTOTYPE) -int scandir (const char *, - struct dirent ***, - int (*) (const struct dirent *), - int (*) (const void *, const void *)); -#endif /* ACE_LACKS_SCANDIR_PROTOTYPE */ - -#if defined (ACE_LACKS_ALPHASORT_PROTOTYPE) -int alphasort (const void *, const void *); -#endif /* ACE_LACKS_ALPHASORT_PROTOTYPE */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_DIRENT_H */ diff --git a/externals/ace/os_include/os_dlfcn.h b/externals/ace/os_include/os_dlfcn.h deleted file mode 100644 index 0f74437fb80..00000000000 --- a/externals/ace/os_include/os_dlfcn.h +++ /dev/null @@ -1,101 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_dlfcn.h - * - * dynamic linking - * - * $Id: os_dlfcn.h 82273 2008-07-09 14:21:45Z jtc $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_DLFCN_H -#define ACE_OS_INCLUDE_OS_DLFCN_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_DLFCN_H) -# include /**/ -#endif /* !ACE_LACKS_DLFCN_H */ - -#if defined (__hpux) -# if defined(__GNUC__) || __cplusplus >= 199707L -# include /**/ -# else -# include /**/ -# endif /* (g++ || HP aC++) vs. HP C++ */ -#endif /* __hpux */ - -#if defined (ACE_VXWORKS) && !defined (__RTP__) -# include /**/ /* for module load */ -# include /**/ /* for module unload */ -# include /**/ /* for findSymbol */ -# include /**/ /* for global symbol table */ -#endif /* ACE_VXWORKS */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#if defined (_M_UNIX) - int _dlclose (void *); - char *_dlerror (void); - void *_dlopen (const char *, int); - void * _dlsym (void *, const char *); -#endif /* _M_UNIX */ - -/* Set the proper handle type for dynamically-loaded libraries. */ -/* Also define a default 'mode' for loading a library - the names and values */ -/* differ between OSes, so if you write code that uses the mode, be careful */ -/* of the platform differences. */ -#if defined (ACE_WIN32) - // Dynamic loading-related types - used for dlopen and family. - typedef HINSTANCE ACE_SHLIB_HANDLE; -# define ACE_SHLIB_INVALID_HANDLE 0 -# define ACE_DEFAULT_SHLIB_MODE 0 -#elif defined (ACE_HAS_SVR4_DYNAMIC_LINKING) - typedef void *ACE_SHLIB_HANDLE; -# define ACE_SHLIB_INVALID_HANDLE 0 - // This is needed to for dynamic_cast to work properly on objects passed to - // libraries. -# define ACE_DEFAULT_SHLIB_MODE RTLD_LAZY | RTLD_GLOBAL -#elif defined (__hpux) - typedef shl_t ACE_SHLIB_HANDLE; -# define ACE_SHLIB_INVALID_HANDLE 0 -# define ACE_DEFAULT_SHLIB_MODE BIND_DEFERRED | DYNAMIC_PATH -#else /* !ACE_WIN32 && !ACE_HAS_SVR4_DYNAMIC_LINKING && !__hpux */ - typedef void *ACE_SHLIB_HANDLE; -# define ACE_SHLIB_INVALID_HANDLE 0 -# define ACE_DEFAULT_SHLIB_MODE RTLD_LAZY -#endif /* ACE_WIN32 */ - -#if !defined (RTLD_LAZY) -#define RTLD_LAZY 1 -#endif /* !RTLD_LAZY */ - -#if !defined (RTLD_NOW) -#define RTLD_NOW 2 -#endif /* !RTLD_NOW */ - -#if !defined (RTLD_GLOBAL) -#define RTLD_GLOBAL 3 -#endif /* !RTLD_GLOBAL */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_DLFCN_H */ diff --git a/externals/ace/os_include/os_errno.h b/externals/ace/os_include/os_errno.h deleted file mode 100644 index 4f5cfe6954c..00000000000 --- a/externals/ace/os_include/os_errno.h +++ /dev/null @@ -1,458 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_errno.h - * - * system error numbers - * - * $Id: os_errno.h 91076 2010-07-13 14:20:35Z johnnyw $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_ERRNO_H -#define ACE_OS_INCLUDE_OS_ERRNO_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_ERRNO_H) -# include /**/ -#endif /* !ACE_LACKS_ERRNO_H */ - -#if defined (ACE_VXWORKS) -// Needed for VxWorks to pickup errnoSet() -#include /**/ -#endif /* ACE_VXWORKS */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#if defined (ACE_WIN32) - // error code mapping for windows - - // VC++ 10 has these error codes defined in errno.h, - // this will cause different errors in ACE. - // So we undef these error codes if they are wrongly defined -# if defined (EWOULDBLOCK) && (EWOULDBLOCK != WSAEWOULDBLOCK) -# undef EWOULDBLOCK -# endif /* EWOULDBLOCK */ -# if defined (EINPROGRESS) && (EINPROGRESS != WSAEINPROGRESS) -# undef EINPROGRESS -# endif /* EINPROGRESS */ -# if defined (EALREADY) && (EALREADY != WSAEALREADY) -# undef EALREADY -# endif /* EALREADY */ -# if defined (ENOTSOCK) && (ENOTSOCK != WSAENOTSOCK) -# undef ENOTSOCK -# endif /* ENOTSOCK */ -# if defined (EDESTADDRREQ) && (EDESTADDRREQ != WSAEDESTADDRREQ) -# undef EDESTADDRREQ -# endif /* EDESTADDRREQ */ -# if defined (EMSGSIZE) && (EMSGSIZE != WSAEMSGSIZE) -# undef EMSGSIZE -# endif /* EMSGSIZE */ -# if defined (EPROTOTYPE) && (EPROTOTYPE != WSAEPROTOTYPE) -# undef EPROTOTYPE -# endif /* EPROTOTYPE */ -# if defined (ENOPROTOOPT) && (ENOPROTOOPT != WSAENOPROTOOPT) -# undef ENOPROTOOPT -# endif /* ENOPROTOOPT */ -# if defined (EPROTONOSUPPORT) && (EPROTONOSUPPORT != WSAEPROTONOSUPPORT) -# undef EPROTONOSUPPORT -# endif /* EPROTONOSUPPORT */ -# if defined (ESOCKTNOSUPPORT) && (ESOCKTNOSUPPORT != WSAESOCKTNOSUPPORT) -# undef ESOCKTNOSUPPORT -# endif /* ESOCKTNOSUPPORT */ -# if defined (EOPNOTSUPP) && (EOPNOTSUPP != WSAEOPNOTSUPP) -# undef EOPNOTSUPP -# endif /* EOPNOTSUPP */ -# if defined (EPFNOSUPPORT) && (EPFNOSUPPORT != WSAEPFNOSUPPORT) -# undef EPFNOSUPPORT -# endif /* EPFNOSUPPORT */ -# if defined (EAFNOSUPPORT) && (EAFNOSUPPORT != WSAEAFNOSUPPORT) -# undef EAFNOSUPPORT -# endif /* EAFNOSUPPORT */ -# if defined (EADDRINUSE) && (EADDRINUSE != WSAEADDRINUSE) -# undef EADDRINUSE -# endif /* EADDRINUSE */ -# if defined (EADDRNOTAVAIL) && (EADDRNOTAVAIL != WSAEADDRNOTAVAIL) -# undef EADDRNOTAVAIL -# endif /* EADDRNOTAVAIL */ -# if defined (ENETDOWN) && (ENETDOWN != WSAENETDOWN) -# undef ENETDOWN -# endif /* ENETDOWN */ -# if defined (ENETUNREACH) && (ENETUNREACH != WSAENETUNREACH) -# undef ENETUNREACH -# endif /* ENETUNREACH */ -# if defined (ENETRESET) && (ENETRESET != WSAENETRESET) -# undef ENETRESET -# endif /* ENETRESET */ -# if defined (ECONNABORTED) && (ECONNABORTED != WSAECONNABORTED) -# undef ECONNABORTED -# endif /* ECONNABORTED */ -# if defined (ECONNRESET) && (ECONNRESET != WSAECONNRESET) -# undef ECONNRESET -# endif /* ECONNRESET */ -# if defined (ENOBUFS) && (ENOBUFS != WSAENOBUFS) -# undef ENOBUFS -# endif /* ENOBUFS */ -# if defined (EISCONN) && (EISCONN != WSAEISCONN) -# undef EISCONN -# endif /* EISCONN */ -# if defined (ENOTCONN) && (ENOTCONN != WSAENOTCONN) -# undef ENOTCONN -# endif /* ENOTCONN */ -# if defined (ESHUTDOWN) && (ESHUTDOWN != WSAESHUTDOWN) -# undef ESHUTDOWN -# endif /* ESHUTDOWN */ -# if defined (ETOOMANYREFS) && (ETOOMANYREFS != WSAETOOMANYREFS) -# undef ETOOMANYREFS -# endif /* ETOOMANYREFS */ -# if defined (ETIMEDOUT) && (ETIMEDOUT != WSAETIMEDOUT) -# undef ETIMEDOUT -# endif /* ETIMEDOUT */ -# if defined (ECONNREFUSED) && (ECONNREFUSED != WSAECONNREFUSED) -# undef ECONNREFUSED -# endif /* ECONNREFUSED */ -# if defined (ELOOP) && (ELOOP != WSAELOOP) -# undef ELOOP -# endif /* ELOOP */ -//# if defined (ENAMETOOLONG) && (ENAMETOOLONG != WSAENAMETOOLONG) -//# undef ENAMETOOLONG -//# endif /* ENAMETOOLONG */ -# if defined (EHOSTDOWN) && (EHOSTDOWN != WSAEHOSTDOWN) -# undef EHOSTDOWN -# endif /* EHOSTDOWN */ -# if defined (EHOSTUNREACH) && (EHOSTUNREACH != WSAEHOSTUNREACH) -# undef EHOSTUNREACH -# endif /* EHOSTUNREACH */ -//# if defined (ENOTEMPTY) && (ENOTEMPTY != WSAENOTEMPTY) -//# undef ENOTEMPTY -//# endif /* ENOTEMPTY */ -# if defined (EPROCLIM) && (EPROCLIM != WSAEPROCLIM) -# undef EPROCLIM -# endif /* EPROCLIM */ -# if defined (EUSERS) && (EUSERS != WSAEUSERS) -# undef EUSERS -# endif /* EUSERS */ -# if defined (EDQUOT) && (EDQUOT != WSAEDQUOT) -# undef EDQUOT -# endif /* EDQUOT */ -# if defined (ESTALE) && (ESTALE != WSAESTALE) -# undef ESTALE -# endif /* ESTALE */ -# if defined (EREMOTE) && (EREMOTE != WSAEREMOTE) -# undef EREMOTE -# endif /* EREMOTE */ - -# if !defined (ETIME) -# define ETIME ERROR_SEM_TIMEOUT -# endif /* !ETIME */ -# if !defined (EWOULDBLOCK) -# define EWOULDBLOCK WSAEWOULDBLOCK -# endif /* !EWOULDBLOCK */ -# if !defined (EINPROGRESS) -# define EINPROGRESS WSAEINPROGRESS -# endif /* !EINPROGRESS */ -# if !defined (EALREADY) -# define EALREADY WSAEALREADY -# endif /* !EALREADY */ -# if !defined (ENOTSOCK) -# define ENOTSOCK WSAENOTSOCK -# endif /* !ENOTSOCK */ -# if !defined (EDESTADDRREQ) -# define EDESTADDRREQ WSAEDESTADDRREQ -# endif /* !EDESTADDRREQ */ -# if !defined (EMSGSIZE) -# define EMSGSIZE WSAEMSGSIZE -# endif /* !EMSGSIZE */ -# if !defined (EPROTOTYPE) -# define EPROTOTYPE WSAEPROTOTYPE -# endif /* !EPROTOTYPE */ -# if !defined (ENOPROTOOPT) -# define ENOPROTOOPT WSAENOPROTOOPT -# endif /* !ENOPROTOOPT */ -# if !defined (EPROTONOSUPPORT) -# define EPROTONOSUPPORT WSAEPROTONOSUPPORT -# endif /* !EPROTONOSUPPORT */ -# if !defined (ESOCKTNOSUPPORT) -# define ESOCKTNOSUPPORT WSAESOCKTNOSUPPORT -# endif /* !ESOCKTNOSUPPORT */ -# if !defined (EOPNOTSUPP) -# define EOPNOTSUPP WSAEOPNOTSUPP -# endif /* !EOPNOTSUPP */ -# if !defined (EPFNOSUPPORT) -# define EPFNOSUPPORT WSAEPFNOSUPPORT -# endif /* !EPFNOSUPPORT */ -# if !defined (EAFNOSUPPORT) -# define EAFNOSUPPORT WSAEAFNOSUPPORT -# endif /* !EAFNOSUPPORT */ -# if !defined (EADDRINUSE) -# define EADDRINUSE WSAEADDRINUSE -# endif /* !EADDRINUSE */ -# if !defined (EADDRNOTAVAIL) -# define EADDRNOTAVAIL WSAEADDRNOTAVAIL -# endif /* !EADDRNOTAVAIL */ -# if !defined (ENETDOWN) -# define ENETDOWN WSAENETDOWN -# endif /* !ENETDOWN */ -# if !defined (ENETUNREACH) -# define ENETUNREACH WSAENETUNREACH -# endif /* !ENETUNREACH */ -# if !defined (ENETRESET) -# define ENETRESET WSAENETRESET -# endif /* !ENETRESET */ -# if !defined (ECONNABORTED) -# define ECONNABORTED WSAECONNABORTED -# endif /* !ECONNABORTED */ -# if !defined (ECONNRESET) -# define ECONNRESET WSAECONNRESET -# endif /* !ECONNRESET */ -# if !defined (ENOBUFS) -# define ENOBUFS WSAENOBUFS -# endif /* !ENOBUFS */ -# if !defined (EISCONN) -# define EISCONN WSAEISCONN -# endif /* !EISCONN */ -# if !defined (ENOTCONN) -# define ENOTCONN WSAENOTCONN -# endif /* !ENOTCONN */ -# if !defined (ESHUTDOWN) -# define ESHUTDOWN WSAESHUTDOWN -# endif /* !ESHUTDOWN */ -# if !defined (ETOOMANYREFS) -# define ETOOMANYREFS WSAETOOMANYREFS -# endif /* !ETOOMANYREFS */ -# if !defined (ETIMEDOUT) -# define ETIMEDOUT WSAETIMEDOUT -# endif /* !ETIMEDOUT */ -# if !defined (ECONNREFUSED) -# define ECONNREFUSED WSAECONNREFUSED -# endif /* !ECONNREFUSED */ -# if !defined (ELOOP) -# define ELOOP WSAELOOP -# endif /* !ELOOP */ -# if !defined (EHOSTDOWN) -# define EHOSTDOWN WSAEHOSTDOWN -# endif /* !EHOSTDOWN */ -# if !defined (EHOSTUNREACH) -# define EHOSTUNREACH WSAEHOSTUNREACH -# endif /* !EHOSTUNREACH */ -# if !defined (EPROCLIM) -# define EPROCLIM WSAEPROCLIM -# endif /* !EPROCLIM */ -# if !defined (EUSERS) -# define EUSERS WSAEUSERS -# endif /* !EUSERS */ -# if !defined (EDQUOT) -# define EDQUOT WSAEDQUOT -# endif /* !EDQUOT */ -# if !defined (ESTALE) -# define ESTALE WSAESTALE -# endif /* !ESTALE */ -# if !defined (EREMOTE) -# define EREMOTE WSAEREMOTE -# endif /* !EREMOTE */ - - // Grrr! ENAMETOOLONG and ENOTEMPTY are already defined by the horrible - // 'standard' library. - // #define ENAMETOOLONG WSAENAMETOOLONG -# if !defined (EADDRINUSE) -# define EADDRINUSE WSAEADDRINUSE -# endif /* EADDRINUSE*/ - - // CE needs this... -# if !defined (EPERM) -# define EPERM ERROR_ACCESS_DENIED -# endif -#endif /* ACE_WIN32 */ - -#if defined (ACE_HAS_H_ERRNO) -void herror (const char *str); -#endif /* ACE_HAS_H_ERRNO */ - -#if defined (ACE_LACKS_ERRNO_H) -# if !defined (EPERM) -# define EPERM 1 -# endif /* EPERM */ -# if !defined (ENOENT) -# define ENOENT 2 -# endif /* ENOENT */ -# if !defined (ESRCH) -# define ESRCH 3 -# endif /* ESRCH */ -# if !defined (EINTR) -# define EINTR 4 -# endif /* EINTR */ -# if !defined (EIO) -# define EIO 5 -# endif /* EIO */ -# if !defined (ENXIO) -# define ENXIO 6 -# endif /* ENXIO */ -# if !defined (E2BIG) -# define E2BIG 7 -# endif /* E2BIG */ -# if !defined (ENOEXEC) -# define ENOEXEC 8 -# endif /* ENOEXEC */ -# if !defined (EBADF) -# define EBADF 9 -# endif /* EBADF */ -# if !defined (ECHILD) -# define ECHILD 10 -# endif /* ECHILD */ -# if !defined (EAGAIN) -# define EAGAIN 11 -# endif /* EAGAIN */ -# if !defined (ENOMEM) -# define ENOMEM 12 -# endif /* ENOMEM */ -# if !defined (EACCES) -# define EACCES 13 -# endif /* EACCES */ -# if !defined (EFAULT) -# define EFAULT 14 -# endif /* EFAULT */ -# if !defined (EBUSY) -# define EBUSY 16 -# endif /* EBUSY */ -# if !defined (EEXIST) -# define EEXIST 17 -# endif /* EEXIST */ -# if !defined (EXDEV) -# define EXDEV 18 -# endif /* EXDEV */ -# if !defined (ENODEV) -# define ENODEV 19 -# endif /* ENODEV */ -# if !defined (ENOTDIR) -# define ENOTDIR 20 -# endif /* ENOTDIR */ -# if !defined (EISDIR) -# define EISDIR 21 -# endif /* EISDIR */ -# if !defined (EINVAL) -# define EINVAL 22 -# endif /* EINVAL */ -# if !defined (ENFILE) -# define ENFILE 23 -# endif /* ENFILE */ -# if !defined (EMFILE) -# define EMFILE 24 -# endif /* EMFILE */ -# if !defined (ENOTTY) -# define ENOTTY 25 -# endif /* ENOTTY */ -# if !defined (EFBIG) -# define EFBIG 27 -# endif /* EFBIG */ -# if !defined (ENOSPC) -# define ENOSPC 28 -# endif /* ENOSPC */ -# if !defined (ESPIPE) -# define ESPIPE 29 -# endif /* ESPIPE */ -# if !defined (EROFS) -# define EROFS 30 -# endif /* EROFS */ -# if !defined (EMLINK) -# define EMLINK 31 -# endif /* EMLINK */ -# if !defined (EPIPE) -# define EPIPE 32 -# endif /* EPIPE */ -# if !defined (EDOM) -# define EDOM 33 -# endif /* EDOM */ -# if !defined (ERANGE) -# define ERANGE 34 -# endif /* ERANGE */ -# if !defined (EDEADLK) -# define EDEADLK 36 -# endif /* EDEADLK */ -# if !defined (ENAMETOOLONG) -# define ENAMETOOLONG 38 -# endif /* ENAMETOOLONG */ -# if !defined (ENOLCK) -# define ENOLCK 39 -# endif /* ENOLCK */ -# if !defined (ENOSYS) -# define ENOSYS 40 -# endif /* ENOSYS */ -# if !defined (ENOTEMPTY) -# define ENOTEMPTY 41 -# endif /* ENOTEMPTY */ -#endif /* ACE_LACKS_ERRNO_H */ - -#if defined (ACE_LACKS_T_ERRNO) -extern int t_errno; -#endif /* ACE_LACKS_T_ERRNO */ - -#if !defined (ENOSYS) -# define ENOSYS EFAULT /* Operation not supported or unknown error. */ -#endif /* !ENOSYS */ - -#if !defined (ENOTSUP) -# define ENOTSUP ENOSYS /* Operation not supported. */ -#endif /* !ENOTSUP */ - -#if !defined (ESUCCESS) -# define ESUCCESS 0 -#endif /* !ESUCCESS */ - -#if !defined (EIDRM) -# define EIDRM 0 -#endif /* !EIDRM */ - -#if !defined (ENFILE) -# define ENFILE EMFILE /* No more socket descriptors are available. */ -#endif /* !ENFILE */ - -#if !defined (ECOMM) - // Not the same, but ECONNABORTED is provided on NT. -# define ECOMM ECONNABORTED -#endif /* ECOMM */ - -#if !defined (EDEADLK) -# define EDEADLK 1000 /* Some large number.... */ -#endif /* !EDEADLK */ - -#if !defined (ENXIO) /* Needed in SOCK_Dgram_Mcast */ -# define ENXIO 6 -#endif /* ENXIO */ - -#if !defined (ETIMEDOUT) && defined (ETIME) -# define ETIMEDOUT ETIME -#endif /* ETIMEDOUT */ - -#if !defined (ETIME) && defined (ETIMEDOUT) -# define ETIME ETIMEDOUT -#endif /* ETIMED */ - -#if !defined (EBUSY) -# define EBUSY ETIME -#endif /* EBUSY */ - -#if !defined (ECANCELED) -# define ECANCELED 125 -#endif /* ECANCELED */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_ERRNO_H */ diff --git a/externals/ace/os_include/os_fcntl.h b/externals/ace/os_include/os_fcntl.h deleted file mode 100644 index 048ff62ae6e..00000000000 --- a/externals/ace/os_include/os_fcntl.h +++ /dev/null @@ -1,106 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_fcntl.h - * - * file control options - * - * $Id: os_fcntl.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_FCNTL_H -#define ACE_OS_INCLUDE_OS_FCNTL_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_stat.h" -#include "ace/os_include/sys/os_types.h" - -#if !defined (ACE_LACKS_FCNTL_H) -# include /**/ -#endif /* !ACE_LACKS_FCNTL_H */ - -#if defined (ACE_VXWORKS) && (ACE_VXWORKS < 0x620) -// for creat(), open() -# include /**/ -#endif /* ACE_VXWORKS */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#if defined (__BORLANDC__) -# define _O_CREAT O_CREAT -# define _O_EXCL O_EXCL -# define _O_TRUNC O_TRUNC - // 0x0800 is used for O_APPEND. 0x08 looks free. -# define _O_TEMPORARY 0x08 /* see fcntl.h */ -# define _O_RDWR O_RDWR -# define _O_WRONLY O_WRONLY -# define _O_RDONLY O_RDONLY -# define _O_APPEND O_APPEND -# define _O_BINARY O_BINARY -# define _O_TEXT O_TEXT -#endif /* __BORLANDC__ */ - -#if defined (__DMC__) -# define _O_TEMPORARY 0x08 /* see fcntl.h */ -#endif /* __DMC__ */ - -// defined Win32 specific macros for UNIX platforms -#if !defined (O_BINARY) -# define O_BINARY 0 -#endif /* O_BINARY */ -#if !defined (_O_BINARY) -# define _O_BINARY O_BINARY -#endif /* _O_BINARY */ -#if !defined (O_TEXT) -# define O_TEXT 0 -#endif /* O_TEXT */ -#if !defined (_O_TEXT) -# define _O_TEXT O_TEXT -#endif /* _O_TEXT */ -#if !defined (O_RAW) -# define O_RAW 0 -#endif /* O_RAW */ -#if !defined (_O_RAW) -# define _O_RAW O_RAW -#endif /* _O_RAW */ - -#if defined (ACE_WIN32) -# define O_NDELAY 1 -#endif /* ACE_WIN32 */ - -# if !defined (O_NONBLOCK) -# define O_NONBLOCK 1 -# endif /* O_NONBLOCK */ - -#if defined (ACE_HAS_POSIX_NONBLOCK) -# define ACE_NONBLOCK O_NONBLOCK -#else -# define ACE_NONBLOCK O_NDELAY -#endif /* ACE_HAS_POSIX_NONBLOCK */ - -# if !defined (F_GETFL) -# define F_GETFL 0 -# endif /* F_GETFL */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_FCNTL_H */ diff --git a/externals/ace/os_include/os_fenv.h b/externals/ace/os_include/os_fenv.h deleted file mode 100644 index cbf5ab41100..00000000000 --- a/externals/ace/os_include/os_fenv.h +++ /dev/null @@ -1,42 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_fenv.h - * - * floating-point environment - * - * $Id: os_fenv.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_FENV_H -#define ACE_OS_INCLUDE_OS_FENV_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_FENV_H) -# include /**/ -#endif /* !ACE_LACKS_FENV_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_FENV_H */ diff --git a/externals/ace/os_include/os_float.h b/externals/ace/os_include/os_float.h deleted file mode 100644 index ac4b2f8f961..00000000000 --- a/externals/ace/os_include/os_float.h +++ /dev/null @@ -1,42 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_float.h - * - * floating types - * - * $Id: os_float.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_FLOAT_H -#define ACE_OS_INCLUDE_OS_FLOAT_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_FLOAT_H) -# include /**/ -#endif /* !ACE_LACKS_FLOAT_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_FLOAT_H */ diff --git a/externals/ace/os_include/os_fmtmsg.h b/externals/ace/os_include/os_fmtmsg.h deleted file mode 100644 index 74251a950d6..00000000000 --- a/externals/ace/os_include/os_fmtmsg.h +++ /dev/null @@ -1,42 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_fmtmsg.h - * - * message display structures - * - * $Id: os_fmtmsg.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_FMTMSG_H -#define ACE_OS_INCLUDE_OS_FMTMSG_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_FMTMSG_H) -# include /**/ -#endif /* !ACE_LACKS_FMTMSG_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_FMTMSG_H */ diff --git a/externals/ace/os_include/os_fnmatch.h b/externals/ace/os_include/os_fnmatch.h deleted file mode 100644 index 36726e293ae..00000000000 --- a/externals/ace/os_include/os_fnmatch.h +++ /dev/null @@ -1,42 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_fnmatch.h - * - * filename-matching types - * - * $Id: os_fnmatch.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_FNMATCH_H -#define ACE_OS_INCLUDE_OS_FNMATCH_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_FNMATCH_H) -# include /**/ -#endif /* !ACE_LACKS_FNMATCH_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_FNMATCH_H */ diff --git a/externals/ace/os_include/os_ftw.h b/externals/ace/os_include/os_ftw.h deleted file mode 100644 index 225d3251339..00000000000 --- a/externals/ace/os_include/os_ftw.h +++ /dev/null @@ -1,44 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_ftw.h - * - * file tree traversal - * - * $Id: os_ftw.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_FTW_H -#define ACE_OS_INCLUDE_OS_FTW_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_stat.h" - -#if !defined (ACE_LACKS_FTW_H) -# include /**/ -#endif /* !ACE_LACKS_FTW_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_FTW_H */ diff --git a/externals/ace/os_include/os_glob.h b/externals/ace/os_include/os_glob.h deleted file mode 100644 index 0ced3a36234..00000000000 --- a/externals/ace/os_include/os_glob.h +++ /dev/null @@ -1,42 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_glob.h - * - * pathname pattern-matching types - * - * $Id: os_glob.h 81692 2008-05-14 12:25:02Z johnnyw $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_GLOB_H -#define ACE_OS_INCLUDE_OS_GLOB_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_GLOB_H) -# include /**/ -#endif /* !ACE_LACKS_GLOB_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_GLOB_H */ diff --git a/externals/ace/os_include/os_grp.h b/externals/ace/os_include/os_grp.h deleted file mode 100644 index 74bb6e64737..00000000000 --- a/externals/ace/os_include/os_grp.h +++ /dev/null @@ -1,44 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_grp.h - * - * group structure - * - * $Id: os_grp.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_GRP_H -#define ACE_OS_INCLUDE_OS_GRP_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_types.h" // for gid_t - -#if !defined (ACE_LACKS_GRP_H) -# include /**/ -#endif /* !ACE_LACKS_GRP_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_GRP_H */ diff --git a/externals/ace/os_include/os_iconv.h b/externals/ace/os_include/os_iconv.h deleted file mode 100644 index 33b061cd789..00000000000 --- a/externals/ace/os_include/os_iconv.h +++ /dev/null @@ -1,44 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_iconv.h - * - * codeset conversion facility - * - * $Id: os_iconv.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_ICONV_H -#define ACE_OS_INCLUDE_OS_ICONV_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_types.h" - -#if !defined (ACE_LACKS_ICONV_H) -# include /**/ -#endif /* !ACE_LACKS_ICONV_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_ICONV_H */ diff --git a/externals/ace/os_include/os_intrin.h b/externals/ace/os_include/os_intrin.h deleted file mode 100644 index 37b669500e2..00000000000 --- a/externals/ace/os_include/os_intrin.h +++ /dev/null @@ -1,57 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_intrin.h - * - * Intrinsic methods - * - * $Id: os_intrin.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Johnny Willemsen - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_INTRIN_H -#define ACE_OS_INCLUDE_OS_INTRIN_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_INTRIN_H) -# include /**/ -#endif /* !ACE_HAS_INTRIN_H */ - -#if defined (ACE_HAS_IA64INTRIN_H) -# include /**/ -#endif /* !ACE_HAS_IA64INTRIN_H */ - -#if defined (ACE_HAS_IA32INTRIN_H) -# include /**/ -#endif /* !ACE_HAS_IA32INTRIN_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#if defined (_MSC_VER) && (_MSC_VER < 1400) && !(defined (__INTEL_COMPILER) && (__INTEL_COMPILER == 900)) -// See http://msdn2.microsoft.com/en-us/library/f24ya7ct(VS.71).aspx -LONG __cdecl _InterlockedIncrement (LONG volatile *Addend); -LONG __cdecl _InterlockedDecrement (LONG volatile *Addend); -LONG __cdecl _InterlockedExchange (LONG volatile *Target, LONG Value); -LONG __cdecl _InterlockedExchangeAdd (LONG volatile *Addend, LONG Value); -#endif //_MSC_VER - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_INTRIN_H */ diff --git a/externals/ace/os_include/os_inttypes.h b/externals/ace/os_include/os_inttypes.h deleted file mode 100644 index 2f0c188699e..00000000000 --- a/externals/ace/os_include/os_inttypes.h +++ /dev/null @@ -1,46 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_inttypes.h - * - * fixed size integer types - * - * $Id: os_inttypes.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_INTTYPES_H -#define ACE_OS_INCLUDE_OS_INTTYPES_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/os_stdint.h" - -#if !defined (ACE_LACKS_INTTYPES_H) -# include /**/ -#endif /* !ACE_LACKS_INTTYPES_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -// @todo if needbe, we can define the macros if they aren't available. - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_INTTYPES_H */ diff --git a/externals/ace/os_include/os_iso646.h b/externals/ace/os_include/os_iso646.h deleted file mode 100644 index 0c5ab2ae4aa..00000000000 --- a/externals/ace/os_include/os_iso646.h +++ /dev/null @@ -1,42 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_iso646.h - * - * alternative spellings - * - * $Id: os_iso646.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_ISO646_H -#define ACE_OS_INCLUDE_OS_ISO646_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_ISO646_H) -# include /**/ -#endif /* !ACE_LACKS_ISO646_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_ISO646_H */ diff --git a/externals/ace/os_include/os_kstat.h b/externals/ace/os_include/os_kstat.h deleted file mode 100644 index 31836cd27d0..00000000000 --- a/externals/ace/os_include/os_kstat.h +++ /dev/null @@ -1,43 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_kstat.h - * - * $Id: os_kstat.h 81692 2008-05-14 12:25:02Z johnnyw $ - * - * @author Johnny Willemsen - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_KSTAT_H -#define ACE_OS_INCLUDE_OS_KSTAT_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_KSTAT) -# define ACE_HAS_KSTAT_H -#endif /* ACE_HAS_KSTAT */ - -#if defined (ACE_HAS_KSTAT_H) -# include -#endif /* ACE_HAS_KSTAT_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_KSTAT_H */ diff --git a/externals/ace/os_include/os_langinfo.h b/externals/ace/os_include/os_langinfo.h deleted file mode 100644 index bfcd67cc2dc..00000000000 --- a/externals/ace/os_include/os_langinfo.h +++ /dev/null @@ -1,44 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_langinfo.h - * - * language information constants - * - * $Id: os_langinfo.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_LANGINFO_H -#define ACE_OS_INCLUDE_OS_LANGINFO_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/os_nl_types.h" - -#if !defined (ACE_LACKS_LANGINFO_H) -# include /**/ -#endif /* !ACE_LACKS_LANGINFO_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_LANGINFO_H */ diff --git a/externals/ace/os_include/os_libgen.h b/externals/ace/os_include/os_libgen.h deleted file mode 100644 index ca24a4d7f9b..00000000000 --- a/externals/ace/os_include/os_libgen.h +++ /dev/null @@ -1,42 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_libgen.h - * - * definitions for pattern matching functions - * - * $Id: os_libgen.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_LIBGEN_H -#define ACE_OS_INCLUDE_OS_LIBGEN_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_LIBGEN_H) -# include /**/ -#endif /* !ACE_LACKS_LIBGEN_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_LIBGEN_H */ diff --git a/externals/ace/os_include/os_limits.h b/externals/ace/os_include/os_limits.h deleted file mode 100644 index a128efcc060..00000000000 --- a/externals/ace/os_include/os_limits.h +++ /dev/null @@ -1,143 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_limits.h - * - * implementation-defined constants - * - * $Id: os_limits.h 84972 2009-03-25 19:09:06Z johnnyw $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_LIMITS_H -#define ACE_OS_INCLUDE_OS_LIMITS_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/os_unistd.h" -#include "ace/os_include/os_stdio.h" // for FILENAME_MAX on Windows - -#if !defined (ACE_LACKS_LIMITS_H) -# include /**/ -#endif /* !ACE_LACKS_LIMITS_H */ - -#if !defined (ACE_LACKS_SYS_PARAM_H) -# include /**/ -#endif /* ACE_LACKS_SYS_PARAM_H */ - -// On VxWorks 5.5.1 _POSIX_TIMER_MAX is defined in time.h -#if defined (ACE_VXWORKS) && (ACE_VXWORKS < 0x620) -# include /**/ -#endif /* ACE_VXWORKS */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#if ! defined (howmany) -# define howmany(x, y) (((x)+((y)-1))/(y)) -#endif /* howmany */ - -#if !defined (NAME_MAX) -# if defined (MAXNAMLEN) -# define NAME_MAX MAXNAMLEN -# elif defined (MAXNAMELEN) -# define NAME_MAX MAXNAMELEN -# elif defined (FILENAME_MAX) -# define NAME_MAX FILENAME_MAX -# elif defined (_MAX_FNAME) -# define NAME_MAX _MAX_FNAME -# else /* _MAX_FNAME */ -# define NAME_MAX 256 -# endif /* MAXNAMLEN */ -#endif /* !NAME_MAX */ - -#if !defined (MAXNAMELEN) -# define MAXNAMELEN NAME_MAX -#endif /* MAXNAMELEN */ - -#if !defined (HOST_NAME_MAX) -# define HOST_NAME_MAX 256 -#endif /* !HOST_NAME_MAX */ - -// Note that we are using PATH_MAX instead of _POSIX_PATH_MAX, since -// _POSIX_PATH_MAX is the *minimun* maximum value for PATH_MAX and is -// defined by POSIX as 256. -#if !defined (PATH_MAX) -# if defined (_MAX_PATH) -# define PATH_MAX _MAX_PATH -# elif defined (MAX_PATH) -# define PATH_MAX MAX_PATH -# else /* !_MAX_PATH */ -# define PATH_MAX 1024 -# endif /* _MAX_PATH */ -#endif /* !PATH_MAX */ - -// Leaving this for backward compatibility, but PATH_MAX should always be -// used directly. -#if !defined (MAXPATHLEN) -# define MAXPATHLEN PATH_MAX -#endif /* !MAXPATHLEN */ - -// This is defined by XOPEN to be a minimum of 16. POSIX.1g -// also defines this value. platform-specific config.h can -// override this if need be. -#if !defined (IOV_MAX) -# define IOV_MAX 16 -#endif /* IOV_MAX */ - -#if !defined (ACE_IOV_MAX) -# define ACE_IOV_MAX IOV_MAX -#endif /* ACE_IOV_MAX */ - -#if defined (ACE_VXWORKS) && ((ACE_VXWORKS >= 0x620) && (ACE_VXWORKS <= 0x670)) && !defined (__RTP__) -# if defined (PIPE_BUF) && (PIPE_BUF == -1) -# undef PIPE_BUF -# endif -#endif /* ACE_VXWORKS */ - -#if !defined (PIPE_BUF) -# define PIPE_BUF 5120 -#endif /* PIPE_BUF */ - -#if defined (ACE_HAS_POSIX_REALTIME_SIGNALS) - // = Giving unique ACE scoped names for some important - // RTSignal-Related constants. Becuase sometimes, different - // platforms use different names for these constants. - - // Number of realtime signals provided in the system. - // _POSIX_RTSIG_MAX is the upper limit on the number of real time - // signals supported in a posix-4 compliant system. -# if defined (_POSIX_RTSIG_MAX) -# define ACE_RTSIG_MAX _POSIX_RTSIG_MAX -# else /* not _POSIX_RTSIG_MAX */ - // POSIX-4 compilant system has to provide atleast 8 RT signals. - // @@ Make sure the platform does *not* define this constant with - // some other name. If yes, use that instead of 8. -# define ACE_RTSIG_MAX 8 -# endif /* _POSIX_RTSIG_MAX */ -#endif /* ACE_HAS_POSIX_REALTIME_SIGNALS */ - - // The maximum number of concurrent timers per process. -# if !defined (_POSIX_TIMER_MAX) -# define _POSIX_TIMER_MAX 44 -# endif /* _POSIX_TIMER_MAX */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_LIMITS_H */ diff --git a/externals/ace/os_include/os_local.h b/externals/ace/os_include/os_local.h deleted file mode 100644 index b5752f9ab95..00000000000 --- a/externals/ace/os_include/os_local.h +++ /dev/null @@ -1,44 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_local.h - * - * category macros - * - * $Id: os_local.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_LOCAL_H -#define ACE_OS_INCLUDE_OS_LOCAL_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/os_stddef.h" - -#if !defined (ACE_LACKS_LOCAL_H) -# include /**/ -#endif /* !ACE_LACKS_LOCAL_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_LOCAL_H */ diff --git a/externals/ace/os_include/os_math.h b/externals/ace/os_include/os_math.h deleted file mode 100644 index 6fb53cb1576..00000000000 --- a/externals/ace/os_include/os_math.h +++ /dev/null @@ -1,44 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_math.h - * - * mathematical declarations - * - * $Id: os_math.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_MATH_H -#define ACE_OS_INCLUDE_OS_MATH_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -// FUZZ: disable check_for_math_include - -#if !defined (ACE_LACKS_MATH_H) -# include /**/ -#endif /* !ACE_LACKS_MATH_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_MATH_H */ diff --git a/externals/ace/os_include/os_monetary.h b/externals/ace/os_include/os_monetary.h deleted file mode 100644 index 6e956885ad6..00000000000 --- a/externals/ace/os_include/os_monetary.h +++ /dev/null @@ -1,44 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_monetary.h - * - * monetary types - * - * $Id: os_monetary.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_MONETARY_H -#define ACE_OS_INCLUDE_OS_MONETARY_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_types.h" - -#if !defined (ACE_LACKS_MONETARY_H) -# include /**/ -#endif /* !ACE_LACKS_MONETARY_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_MONETARY_H */ diff --git a/externals/ace/os_include/os_mqueue.h b/externals/ace/os_include/os_mqueue.h deleted file mode 100644 index 7b3cbb9209a..00000000000 --- a/externals/ace/os_include/os_mqueue.h +++ /dev/null @@ -1,44 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_mqueue.h - * - * message queues (REALTIME) - * - * $Id: os_mqueue.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_MQUEUE_H -#define ACE_OS_INCLUDE_OS_MQUEUE_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/os_signal.h" - -#if !defined (ACE_LACKS_MQUEUE_H) -# include /**/ -#endif /* !ACE_LACKS_MQUEUE_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_MQUEUE_H */ diff --git a/externals/ace/os_include/os_ndbm.h b/externals/ace/os_include/os_ndbm.h deleted file mode 100644 index 042dcebf2ff..00000000000 --- a/externals/ace/os_include/os_ndbm.h +++ /dev/null @@ -1,44 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_ndbm.h - * - * definitions for ndbm database operations - * - * $Id: os_ndbm.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_NDBM_H -#define ACE_OS_INCLUDE_OS_NDBM_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_types.h" - -#if !defined (ACE_LACKS_NDBM_H) -# include /**/ -#endif /* !ACE_LACKS_NDBM_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_NDBM_H */ diff --git a/externals/ace/os_include/os_netdb.h b/externals/ace/os_include/os_netdb.h deleted file mode 100644 index 798bf9b7a2b..00000000000 --- a/externals/ace/os_include/os_netdb.h +++ /dev/null @@ -1,100 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_netdb.h - * - * definitions for network database operations - * - * $Id: os_netdb.h 84660 2009-03-01 20:22:37Z olli $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_NETDB_H -#define ACE_OS_INCLUDE_OS_NETDB_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/netinet/os_in.h" -#include "ace/os_include/os_limits.h" - -#if defined (ACE_VXWORKS) && (ACE_VXWORKS < 0x620) -# include /**/ -#endif /* ACE_VXWORKS */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#if !defined (ACE_LACKS_NETDB_H) -# include /**/ -#endif /* !ACE_LACKS_NETDB_H */ - -#if defined (ACE_LACKS_HOSTENT) -struct hostent { - char *h_name; /* official name of host */ - char **h_aliases; /* alias list */ - int h_addrtype; /* host address type */ - int h_length; /* length of address */ - char **h_addr_list; /* list of addresses from name server */ -#define h_addr h_addr_list[0] /* address, for backward compatibility */ -}; -#endif /* ACE_LACKS_HOSTENT */ - -#if defined (ACE_LACKS_PROTOENT) -struct protoent { - char *p_name; /* official protocol name */ - char **p_aliases; /* alias list */ - int p_proto; /* protocol # */ -}; -#endif /* ACE_LACKS_PROTOENT */ - -#if defined (ACE_LACKS_SERVENT) -struct servent { - char *s_name; /* official service name */ - char **s_aliases; /* alias list */ - int s_port; /* port # */ - char *s_proto; /* protocol to use */ -}; -#endif /* ACE_LACKS_SERVENT */ - -#if defined (ACE_HAS_STRUCT_NETDB_DATA) - typedef char ACE_HOSTENT_DATA[sizeof(struct hostent_data)]; - typedef char ACE_SERVENT_DATA[sizeof(struct servent_data)]; - typedef char ACE_PROTOENT_DATA[sizeof(struct protoent_data)]; -#else -# if !defined ACE_HOSTENT_DATA_SIZE -# define ACE_HOSTENT_DATA_SIZE (4*1024) -# endif /*ACE_HOSTENT_DATA_SIZE */ -# if !defined ACE_SERVENT_DATA_SIZE -# define ACE_SERVENT_DATA_SIZE (4*1024) -# endif /*ACE_SERVENT_DATA_SIZE */ -# if !defined ACE_PROTOENT_DATA_SIZE -# define ACE_PROTOENT_DATA_SIZE (2*1024) -# endif /*ACE_PROTOENT_DATA_SIZE */ - typedef char ACE_HOSTENT_DATA[ACE_HOSTENT_DATA_SIZE]; - typedef char ACE_SERVENT_DATA[ACE_SERVENT_DATA_SIZE]; - typedef char ACE_PROTOENT_DATA[ACE_PROTOENT_DATA_SIZE]; -#endif /* ACE_HAS_STRUCT_NETDB_DATA */ - -# if !defined(MAXHOSTNAMELEN) -# define MAXHOSTNAMELEN HOST_NAME_MAX -# endif /* MAXHOSTNAMELEN */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_NETDB_H */ diff --git a/externals/ace/os_include/os_nl_types.h b/externals/ace/os_include/os_nl_types.h deleted file mode 100644 index e043f6ae6d3..00000000000 --- a/externals/ace/os_include/os_nl_types.h +++ /dev/null @@ -1,42 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_nl_types.h - * - * data types - * - * $Id: os_nl_types.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_NL_TYPES_H -#define ACE_OS_INCLUDE_OS_NL_TYPES_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_NL_TYPES_H) -# include /**/ -#endif /* !ACE_LACKS_nl_types_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_NL_TYPES_H */ diff --git a/externals/ace/os_include/os_pdh.h b/externals/ace/os_include/os_pdh.h deleted file mode 100644 index 5c60c60d10e..00000000000 --- a/externals/ace/os_include/os_pdh.h +++ /dev/null @@ -1,45 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_pdh.h - * - * definitions for the windows pdh API - * - * $Id: os_pdh.h 81614 2008-05-05 14:04:25Z johnnyw $ - * - * @author Johnny Willemsen - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_PDH_H -#define ACE_OS_INCLUDE_OS_PDH_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_PDH_H) && !defined (ACE_LACKS_PDH_H) -# include /**/ -#endif /* ACE_HAS_PDH_H && !ACE_LACKS_PDH_H */ - -#if defined (ACE_HAS_PDH_H) && !defined (ACE_LACKS_PDH_H) -# define ACE_HAS_WIN32_PDH -#endif - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_PDH_H */ diff --git a/externals/ace/os_include/os_pdhmsg.h b/externals/ace/os_include/os_pdhmsg.h deleted file mode 100644 index 2156236e07c..00000000000 --- a/externals/ace/os_include/os_pdhmsg.h +++ /dev/null @@ -1,41 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_pdhmsg.h - * - * definitions for the windows pdh API - * - * $Id: os_pdhmsg.h 81693 2008-05-14 12:35:01Z johnnyw $ - * - * @author Johnny Willemsen - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_PDHMSG_H -#define ACE_OS_INCLUDE_OS_PDHMSG_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_PDHMSG_H) && !defined (ACE_LACKS_PDHMSG_H) -# include /**/ -#endif /* ACE_HAS_PDH_H && !ACE_LACKS_PDH_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_PDHMSG_H */ diff --git a/externals/ace/os_include/os_poll.h b/externals/ace/os_include/os_poll.h deleted file mode 100644 index 646c1bb853c..00000000000 --- a/externals/ace/os_include/os_poll.h +++ /dev/null @@ -1,42 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_poll.h - * - * definitions for the poll() function - * - * $Id: os_poll.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_POLL_H -#define ACE_OS_INCLUDE_OS_POLL_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_POLL_H) -# include /**/ -#endif /* !ACE_LACKS_POLL_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_POLL_H */ diff --git a/externals/ace/os_include/os_pthread.h b/externals/ace/os_include/os_pthread.h deleted file mode 100644 index 368f4254a34..00000000000 --- a/externals/ace/os_include/os_pthread.h +++ /dev/null @@ -1,424 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_pthread.h - * - * threads - * - * $Id: os_pthread.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_PTHREAD_H -#define ACE_OS_INCLUDE_OS_PTHREAD_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_PRIOCNTL) - // Need to #include thread.h before #defining THR_BOUND, etc., - // when building without threads on SunOS 5.x. -# if defined (sun) -# include /**/ -# endif /* sun */ - - // Need to #include these before #defining USYNC_PROCESS on SunOS 5.x. -# include /**/ -# include /**/ -#endif /* ACE_HAS_PRIOCNTL */ - -#include "ace/os_include/sys/os_types.h" - -// This needs to go here *first* to avoid problems with AIX. -# if defined (ACE_HAS_PTHREADS) -# define ACE_DONT_INCLUDE_ACE_SIGNAL_H -# include "ace/os_include/os_signal.h" -# undef ACE_DONT_INCLUDE_ACE_SIGNAL_H -# if defined (DIGITAL_UNIX) -# define pthread_self __pthread_self -extern "C" pthread_t pthread_self (void); -# endif /* DIGITAL_UNIX */ -# endif /* ACE_HAS_PTHREADS */ - - -#if !defined (ACE_LACKS_PTHREAD_H) - extern "C" { -# if defined (ACE_TANDEM_T1248_PTHREADS) -# include /**/ -# else -# include /**/ -# endif - } -#endif /* !ACE_LACKS_PTHREAD_H */ - -#if defined (ACE_HAS_PTHREAD_NP_H) -// FreeBSD declares _np (non-portable) pthread extensions in -# include /**/ -#endif - -// @todo: need to reoganize to put includes at the top and the rest of the -// code at the bottom. Also, move the classes out of this file. -#if defined (ACE_HAS_PTHREADS) -# define ACE_SCHED_OTHER SCHED_OTHER -# define ACE_SCHED_FIFO SCHED_FIFO -# define ACE_SCHED_RR SCHED_RR - -// Definitions for THREAD- and PROCESS-LEVEL priorities...some -// implementations define these while others don't. In order to -// further complicate matters, we don't redefine the default (*_DEF) -// values if they've already been defined, which allows individual -// programs to have their own ACE-wide "default". - -// PROCESS-level values -# if (defined (_POSIX_PRIORITY_SCHEDULING) || defined (ACE_TANDEM_T1248_PTHREADS)) \ - && !defined(_UNICOS) && !defined(UNIXWARE_7_1) -# define ACE_PROC_PRI_FIFO_MIN (sched_get_priority_min(SCHED_FIFO)) -# define ACE_PROC_PRI_RR_MIN (sched_get_priority_min(SCHED_RR)) -# if defined (HPUX) - // HP-UX's other is the SCHED_HPUX class, which uses historical - // values that have reverse semantics from POSIX (low value is - // more important priority). To use these in pthreads calls, - // the values need to be converted. The other scheduling classes - // don't need this special treatment. -# define ACE_PROC_PRI_OTHER_MIN \ - (sched_get_priority_min(SCHED_OTHER)) -# else -# define ACE_PROC_PRI_OTHER_MIN (sched_get_priority_min(SCHED_OTHER)) -# endif /* HPUX */ -# else /* UNICOS is missing a sched_get_priority_min() implementation, - SCO too */ -# define ACE_PROC_PRI_FIFO_MIN 0 -# define ACE_PROC_PRI_RR_MIN 0 -# define ACE_PROC_PRI_OTHER_MIN 0 -# endif - -# if defined (_POSIX_PRIORITY_SCHEDULING) && !defined(UNIXWARE_7_1) -# define ACE_PROC_PRI_FIFO_MAX (sched_get_priority_max(SCHED_FIFO)) -# define ACE_PROC_PRI_RR_MAX (sched_get_priority_max(SCHED_RR)) -# if defined (HPUX) -# define ACE_PROC_PRI_OTHER_MAX \ - (sched_get_priority_max(SCHED_OTHER)) -# else -# define ACE_PROC_PRI_OTHER_MAX (sched_get_priority_max(SCHED_OTHER)) -# endif /* HPUX */ -# else /* SCO missing sched_get_priority_max() implementation */ -# define ACE_PROC_PRI_FIFO_MAX 59 -# define ACE_PROC_PRI_RR_MAX 59 -# define ACE_PROC_PRI_OTHER_MAX 59 -# endif - -# if !defined(ACE_PROC_PRI_FIFO_DEF) -# define ACE_PROC_PRI_FIFO_DEF (ACE_PROC_PRI_FIFO_MIN + (ACE_PROC_PRI_FIFO_MAX - ACE_PROC_PRI_FIFO_MIN)/2) -# endif -# if !defined(ACE_PROC_PRI_RR_DEF) -# define ACE_PROC_PRI_RR_DEF (ACE_PROC_PRI_RR_MIN + (ACE_PROC_PRI_RR_MAX - ACE_PROC_PRI_RR_MIN)/2) -# endif -# if !defined(ACE_PROC_PRI_OTHER_DEF) -# define ACE_PROC_PRI_OTHER_DEF (ACE_PROC_PRI_OTHER_MIN + (ACE_PROC_PRI_OTHER_MAX - ACE_PROC_PRI_OTHER_MIN)/2) -# endif - -// THREAD-level values -# if defined(PRI_FIFO_MIN) && defined(PRI_FIFO_MAX) && defined(PRI_RR_MIN) && defined(PRI_RR_MAX) && defined(PRI_OTHER_MIN) && defined(PRI_OTHER_MAX) -# if !defined (ACE_THR_PRI_FIFO_MIN) -# define ACE_THR_PRI_FIFO_MIN (long) PRI_FIFO_MIN -# endif /* !ACE_THR_PRI_FIFO_MIN */ -# if !defined (ACE_THR_PRI_FIFO_MAX) -# define ACE_THR_PRI_FIFO_MAX (long) PRI_FIFO_MAX -# endif /* !ACE_THR_PRI_FIFO_MAX */ -# if !defined (ACE_THR_PRI_RR_MIN) -# define ACE_THR_PRI_RR_MIN (long) PRI_RR_MIN -# endif /* !ACE_THR_PRI_RR_MIN */ -# if !defined (ACE_THR_PRI_RR_MAX) -# define ACE_THR_PRI_RR_MAX (long) PRI_RR_MAX -# endif /* !ACE_THR_PRI_RR_MAX */ -# if !defined (ACE_THR_PRI_OTHER_MIN) -# define ACE_THR_PRI_OTHER_MIN (long) PRI_OTHER_MIN -# endif /* !ACE_THR_PRI_OTHER_MIN */ -# if !defined (ACE_THR_PRI_OTHER_MAX) -# define ACE_THR_PRI_OTHER_MAX (long) PRI_OTHER_MAX -# endif /* !ACE_THR_PRI_OTHER_MAX */ -# elif defined (AIX) - // AIX's priority range is 1 (low) to 127 (high). There aren't - // any preprocessor macros I can find. PRIORITY_MIN is for - // process priorities, as far as I can see, and does not apply - // to thread priority. The 1 to 127 range is from the - // pthread_attr_setschedparam man page (Steve Huston, 18-May-2001). -# if !defined (ACE_THR_PRI_FIFO_MIN) -# define ACE_THR_PRI_FIFO_MIN (long) 1 -# endif /* !ACE_THR_PRI_FIFO_MIN */ -# if !defined (ACE_THR_PRI_FIFO_MAX) -# define ACE_THR_PRI_FIFO_MAX (long) 127 -# endif /* !ACE_THR_PRI_FIFO_MAX */ -# if !defined (ACE_THR_PRI_RR_MIN) -# define ACE_THR_PRI_RR_MIN (long) 1 -# endif /* !ACE_THR_PRI_RR_MIN */ -# if !defined (ACE_THR_PRI_RR_MAX) -# define ACE_THR_PRI_RR_MAX (long) 127 -# endif /* !ACE_THR_PRI_RR_MAX */ -# if !defined (ACE_THR_PRI_OTHER_MIN) -# define ACE_THR_PRI_OTHER_MIN (long) 1 -# endif /* !ACE_THR_PRI_OTHER_MIN */ -# if !defined (ACE_THR_PRI_OTHER_MAX) -# define ACE_THR_PRI_OTHER_MAX (long) 127 -# endif /* !ACE_THR_PRI_OTHER_MAX */ -# elif defined (sun) -# if !defined (ACE_THR_PRI_FIFO_MIN) -# define ACE_THR_PRI_FIFO_MIN (long) 0 -# endif /* !ACE_THR_PRI_FIFO_MIN */ -# if !defined (ACE_THR_PRI_FIFO_MAX) -# define ACE_THR_PRI_FIFO_MAX (long) 59 -# endif /* !ACE_THR_PRI_FIFO_MAX */ -# if !defined (ACE_THR_PRI_RR_MIN) -# define ACE_THR_PRI_RR_MIN (long) 0 -# endif /* !ACE_THR_PRI_RR_MIN */ -# if !defined (ACE_THR_PRI_RR_MAX) -# define ACE_THR_PRI_RR_MAX (long) 59 -# endif /* !ACE_THR_PRI_RR_MAX */ -# if !defined (ACE_THR_PRI_OTHER_MIN) -# define ACE_THR_PRI_OTHER_MIN (long) 0 -# endif /* !ACE_THR_PRI_OTHER_MIN */ -# if !defined (ACE_THR_PRI_OTHER_MAX) -# define ACE_THR_PRI_OTHER_MAX (long) 127 -# endif /* !ACE_THR_PRI_OTHER_MAX */ -# else -# if !defined (ACE_THR_PRI_FIFO_MIN) -# define ACE_THR_PRI_FIFO_MIN (long) ACE_PROC_PRI_FIFO_MIN -# endif /* !ACE_THR_PRI_FIFO_MIN */ -# if !defined (ACE_THR_PRI_FIFO_MAX) -# define ACE_THR_PRI_FIFO_MAX (long) ACE_PROC_PRI_FIFO_MAX -# endif /* !ACE_THR_PRI_FIFO_MAX */ -# if !defined (ACE_THR_PRI_RR_MIN) -# define ACE_THR_PRI_RR_MIN (long) ACE_PROC_PRI_RR_MIN -# endif /* !ACE_THR_PRI_RR_MIN */ -# if !defined (ACE_THR_PRI_RR_MAX) -# define ACE_THR_PRI_RR_MAX (long) ACE_PROC_PRI_RR_MAX -# endif /* !ACE_THR_PRI_RR_MAX */ -# if !defined (ACE_THR_PRI_OTHER_MIN) -# define ACE_THR_PRI_OTHER_MIN (long) ACE_PROC_PRI_OTHER_MIN -# endif /* !ACE_THR_PRI_OTHER_MIN */ -# if !defined (ACE_THR_PRI_OTHER_MAX) -# define ACE_THR_PRI_OTHER_MAX (long) ACE_PROC_PRI_OTHER_MAX -# endif /* !ACE_THR_PRI_OTHER_MAX */ -# endif -# if !defined(ACE_THR_PRI_FIFO_DEF) -# define ACE_THR_PRI_FIFO_DEF ((ACE_THR_PRI_FIFO_MIN + ACE_THR_PRI_FIFO_MAX)/2) -# endif -# if !defined(ACE_THR_PRI_RR_DEF) -# define ACE_THR_PRI_RR_DEF ((ACE_THR_PRI_RR_MIN + ACE_THR_PRI_RR_MAX)/2) -# endif -# if !defined(ACE_THR_PRI_OTHER_DEF) -# define ACE_THR_PRI_OTHER_DEF ((ACE_THR_PRI_OTHER_MIN + ACE_THR_PRI_OTHER_MAX)/2) -# endif - // Typedefs to help compatibility with Windows NT and Pthreads. - typedef pthread_t ACE_hthread_t; - typedef pthread_t ACE_thread_t; - - // native TSS key type - typedef pthread_key_t ACE_OS_thread_key_t; - // TSS key type to be used by application -# if defined (ACE_HAS_TSS_EMULATION) - typedef u_int ACE_thread_key_t; -# else /* ! ACE_HAS_TSS_EMULATION */ - typedef ACE_OS_thread_key_t ACE_thread_key_t; -# endif /* ! ACE_HAS_TSS_EMULATION */ - -# if !defined (ACE_LACKS_COND_T) - typedef pthread_mutex_t ACE_mutex_t; - typedef pthread_cond_t ACE_cond_t; - typedef pthread_condattr_t ACE_condattr_t; - typedef pthread_mutexattr_t ACE_mutexattr_t; -# endif /* ! ACE_LACKS_COND_T */ - typedef pthread_mutex_t ACE_thread_mutex_t; - -# if !defined (PTHREAD_CANCEL_DISABLE) -# define PTHREAD_CANCEL_DISABLE 0 -# endif /* PTHREAD_CANCEL_DISABLE */ - -# if !defined (PTHREAD_CANCEL_ENABLE) -# define PTHREAD_CANCEL_ENABLE 0 -# endif /* PTHREAD_CANCEL_ENABLE */ - -# if !defined (PTHREAD_CANCEL_DEFERRED) -# define PTHREAD_CANCEL_DEFERRED 0 -# endif /* PTHREAD_CANCEL_DEFERRED */ - -# if !defined (PTHREAD_CANCEL_ASYNCHRONOUS) -# define PTHREAD_CANCEL_ASYNCHRONOUS 0 -# endif /* PTHREAD_CANCEL_ASYNCHRONOUS */ - -# define THR_CANCEL_DISABLE PTHREAD_CANCEL_DISABLE -# define THR_CANCEL_ENABLE PTHREAD_CANCEL_ENABLE -# define THR_CANCEL_DEFERRED PTHREAD_CANCEL_DEFERRED -# define THR_CANCEL_ASYNCHRONOUS PTHREAD_CANCEL_ASYNCHRONOUS - -# if !defined (PTHREAD_CREATE_JOINABLE) -# if defined (PTHREAD_CREATE_UNDETACHED) -# define PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED -# else -# define PTHREAD_CREATE_JOINABLE 0 -# endif /* PTHREAD_CREATE_UNDETACHED */ -# endif /* PTHREAD_CREATE_JOINABLE */ - -# if !defined (PTHREAD_CREATE_DETACHED) -# define PTHREAD_CREATE_DETACHED 1 -# endif /* PTHREAD_CREATE_DETACHED */ - -# if !defined (PTHREAD_PROCESS_PRIVATE) && !defined (ACE_HAS_PTHREAD_PROCESS_ENUM) -# if defined (PTHREAD_MUTEXTYPE_FAST) -# define PTHREAD_PROCESS_PRIVATE PTHREAD_MUTEXTYPE_FAST -# else -# define PTHREAD_PROCESS_PRIVATE 0 -# endif /* PTHREAD_MUTEXTYPE_FAST */ -# endif /* PTHREAD_PROCESS_PRIVATE */ - -# if !defined (PTHREAD_PROCESS_SHARED) && !defined (ACE_HAS_PTHREAD_PROCESS_ENUM) -# if defined (PTHREAD_MUTEXTYPE_FAST) -# define PTHREAD_PROCESS_SHARED PTHREAD_MUTEXTYPE_FAST -# else -# define PTHREAD_PROCESS_SHARED 1 -# endif /* PTHREAD_MUTEXTYPE_FAST */ -# endif /* PTHREAD_PROCESS_SHARED */ - -# if !defined (ACE_HAS_STHREADS) -# if !defined (USYNC_THREAD) -# define USYNC_THREAD PTHREAD_PROCESS_PRIVATE -# endif /* ! USYNC_THREAD */ -# if !defined (USYNC_PROCESS) -# define USYNC_PROCESS PTHREAD_PROCESS_SHARED -# endif /* ! USYNC_PROCESS */ -# endif /* ACE_HAS_STHREADS */ - - /* MM-Graz: prevent warnings */ -# if !defined (UNIXWARE_7_1) -# undef THR_BOUND -# undef THR_NEW_LWP -# undef THR_DETACHED -# undef THR_SUSPENDED -# undef THR_DAEMON - -# define THR_BOUND 0x00000001 -# define THR_NEW_LWP 0x00000002 -# define THR_DETACHED 0x00000040 -# define THR_SUSPENDED 0x00000080 -# define THR_DAEMON 0x00000100 -# define THR_SCHED_FIFO 0x00020000 -# define THR_SCHED_RR 0x00040000 -# define THR_SCHED_DEFAULT 0x00080000 -# endif /* UNIXWARE_7_1 */ - -# define THR_JOINABLE 0x00010000 - -# if defined (ACE_HAS_IRIX62_THREADS) -# define THR_SCOPE_SYSTEM 0x00100000 -# else -# define THR_SCOPE_SYSTEM THR_BOUND -# endif /*ACE_HAS_IRIX62_THREADS*/ - -# define THR_SCOPE_PROCESS 0x00200000 -# define THR_INHERIT_SCHED 0x00400000 -# define THR_EXPLICIT_SCHED 0x00800000 -# define THR_SCHED_IO 0x01000000 - -# if !defined (ACE_HAS_STHREADS) -# if !defined (ACE_HAS_POSIX_SEM) && !defined (ACE_USES_FIFO_SEM) - -// This needs to be moved out of here. -#include /**/ "ace/ACE_export.h" -/** - * @class ACE_sema_t - * - * @brief This is used to implement semaphores for platforms that support - * POSIX pthreads, but do *not* support POSIX semaphores, i.e., - * it's a different type than the POSIX . - */ -class ACE_Export ACE_sema_t -{ -public: - /// Serialize access to internal state. - ACE_mutex_t lock_; - - /// Block until there are no waiters. - ACE_cond_t count_nonzero_; - - /// Count of the semaphore. - u_long count_; - - /// Number of threads that have called . - u_long waiters_; -}; -# endif /* !ACE_HAS_POSIX_SEM */ - -# if defined (ACE_LACKS_PTHREAD_YIELD) && defined (ACE_HAS_THR_YIELD) - // If we are on Solaris we can just reuse the existing - // implementations of these synchronization types. -# if !defined (ACE_LACKS_RWLOCK_T) && !defined (ACE_HAS_PTHREADS_UNIX98_EXT) -# include /**/ - typedef rwlock_t ACE_rwlock_t; -# endif /* !ACE_LACKS_RWLOCK_T */ -# include /**/ -# endif /* (ACE_LACKS_PTHREAD_YIELD) && defined (ACE_HAS_THR_YIELD) */ - -# else -# if !defined (ACE_HAS_POSIX_SEM) - typedef sema_t ACE_sema_t; -# endif /* !ACE_HAS_POSIX_SEM */ -# endif /* !ACE_HAS_STHREADS */ - -# if defined (ACE_HAS_PTHREADS_UNIX98_EXT) - typedef pthread_rwlock_t ACE_rwlock_t; -# endif /* ACE_HAS_PTHREADS_UNIX98_EXT */ - -# if defined (__GLIBC__) && ((__GLIBC__ > 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2)) - - // glibc 2.2.x or better has pthread_mutex_timedlock() -# ifndef ACE_HAS_MUTEX_TIMEOUTS -# define ACE_HAS_MUTEX_TIMEOUTS -# endif /* ACE_HAS_MUTEX_TIMEOUTS */ - - // Use new pthread_attr_setstack if XPG6 support is enabled. -# if defined (_XOPEN_SOURCE) && (_XOPEN_SOURCE - 0) < 600 -# define ACE_LACKS_PTHREAD_ATTR_SETSTACK -# endif /* (_XOPEN_SOURCE - 0) < 600 */ - -# if !defined (_XOPEN_SOURCE) \ - || (defined (_XOPEN_SOURCE) && (_XOPEN_SOURCE - 0) < 600) - // pthread_mutex_timedlock() prototype is not visible if _XOPEN_SOURCE - // is not >= 600 (i.e. for XPG6). - extern "C" int pthread_mutex_timedlock (pthread_mutex_t *mutex, - const struct timespec * abstime); -# endif /* _XOPEN_SOURCE && _XOPEN_SOURCE < 600 */ - -# endif /* linux && ((__GLIBC__ > 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2)) */ - -#elif defined (ACE_HAS_STHREADS) -# if !defined (ACE_THR_PRI_FIFO_MIN) -# define ACE_THR_PRI_FIFO_MIN (long) 0 -# endif /* !ACE_THR_PRI_FIFO_MIN */ -# if !defined (ACE_THR_PRI_FIFO_MAX) -# define ACE_THR_PRI_FIFO_MAX (long) 59 -# endif /* !ACE_THR_PRI_FIFO_MAX */ -# if !defined (ACE_THR_PRI_RR_MIN) -# define ACE_THR_PRI_RR_MIN (long) 0 -# endif /* !ACE_THR_PRI_RR_MIN */ -# if !defined (ACE_THR_PRI_RR_MAX) -# define ACE_THR_PRI_RR_MAX (long) 59 -# endif /* !ACE_THR_PRI_RR_MAX */ -# if !defined (ACE_THR_PRI_OTHER_MIN) -# define ACE_THR_PRI_OTHER_MIN (long) 0 -# endif /* !ACE_THR_PRI_OTHER_MIN */ -# if !defined (ACE_THR_PRI_OTHER_MAX) -# define ACE_THR_PRI_OTHER_MAX (long) 127 -# endif /* !ACE_THR_PRI_OTHER_MAX */ -#endif /* ACE_HAS_PTHREADS */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_PTHREAD_H */ diff --git a/externals/ace/os_include/os_pwd.h b/externals/ace/os_include/os_pwd.h deleted file mode 100644 index b1bc94af381..00000000000 --- a/externals/ace/os_include/os_pwd.h +++ /dev/null @@ -1,58 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_pwd.h - * - * password structure - * - * $Id: os_pwd.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_PWD_H -#define ACE_OS_INCLUDE_OS_PWD_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_types.h" - -#if !defined (ACE_LACKS_PWD_H) -# include /**/ -#endif /* !ACE_LACKS_PWD_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#if !defined (ACE_WIN32) -// VAC++ doesn't correctly grok the ::getpwnam_r - the function is redefined -// in pwd.h, and that redefinition is used here -# if defined (_AIX) && defined (__IBMCPP__) && (__IBMCPP__ >= 400) - extern int _posix_getpwnam_r(const char *, struct passwd *, char *, - int, struct passwd **); -# endif /* AIX and VAC++ 4 */ -#endif /* !ACE_WIN32 */ - -#if defined (DIGITAL_UNIX) - extern int _Pgetpwnam_r (const char *, struct passwd *, - char *, size_t, struct passwd **); -#endif /* DIGITAL_UNIX */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_PWD_H */ diff --git a/externals/ace/os_include/os_regex.h b/externals/ace/os_include/os_regex.h deleted file mode 100644 index 1c856da26f0..00000000000 --- a/externals/ace/os_include/os_regex.h +++ /dev/null @@ -1,48 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_regex.h - * - * regular expression matching types - * - * $Id: os_regex.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_REGEX_H -#define ACE_OS_INCLUDE_OS_REGEX_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_types.h" - -#if !defined (ACE_LACKS_REGEX_H) -# include /**/ -#endif /* !ACE_LACKS_REGEX_H */ - -#if defined (ACE_HAS_REGEX) -# include /**/ -#endif /* ACE_HAS_REGEX */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_REGEX_H */ diff --git a/externals/ace/os_include/os_sched.h b/externals/ace/os_include/os_sched.h deleted file mode 100644 index f06541b8ca8..00000000000 --- a/externals/ace/os_include/os_sched.h +++ /dev/null @@ -1,56 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_sched.h - * - * execution scheduling (REALTIME) - * - * $Id: os_sched.h 85102 2009-04-17 14:04:36Z johnnyw $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_SCHED_H -#define ACE_OS_INCLUDE_OS_SCHED_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/os_time.h" - -#if !defined (ACE_LACKS_SCHED_H) -# include /**/ -#endif /* !ACE_LACKS_SCHED_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#if !defined (__cpu_set_t_defined) || !defined (ACE_HAS_CPU_SET_T) -#if defined (ACE_HAS_CPUSET_T) - typedef cpuset_t cpu_set_t; -#else -# define ACE_CPU_SETSIZE 1024 - typedef struct - { - ACE_UINT32 bit_array_[ACE_CPU_SETSIZE / (8 * sizeof (ACE_UINT32))]; - } cpu_set_t; -#endif -#endif /* !ACE_HAS_CPU_SET_T || !__cpu_set_t_defined */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_SCHED_H */ diff --git a/externals/ace/os_include/os_search.h b/externals/ace/os_include/os_search.h deleted file mode 100644 index 605fd365c09..00000000000 --- a/externals/ace/os_include/os_search.h +++ /dev/null @@ -1,44 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_search.h - * - * search tables - * - * $Id: os_search.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_SEARCH_H -#define ACE_OS_INCLUDE_OS_SEARCH_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_types.h" - -#if !defined (ACE_LACKS_SEARCH_H) -# include /**/ -#endif /* !ACE_LACKS_SEARCH_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_SEARCH_H */ diff --git a/externals/ace/os_include/os_semaphore.h b/externals/ace/os_include/os_semaphore.h deleted file mode 100644 index 7fad7dafb4e..00000000000 --- a/externals/ace/os_include/os_semaphore.h +++ /dev/null @@ -1,77 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_semaphore.h - * - * semaphores (REALTIME) - * - * $Id: os_semaphore.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_SEMAPHORE_H -#define ACE_OS_INCLUDE_OS_SEMAPHORE_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/os_time.h" - -#if !defined (ACE_LACKS_SEMAPHORE_H) -# include /**/ -#endif /* !ACE_LACKS_SEMAPHORE_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#if defined (ACE_HAS_POSIX_SEM) -# if !defined (SEM_FAILED) && !defined (ACE_LACKS_NAMED_POSIX_SEM) -# define SEM_FAILED ((sem_t *) -1) -# endif /* !SEM_FAILED */ - - typedef struct - { - /// Pointer to semaphore handle. This is allocated by ACE if we are - /// working with an unnamed POSIX semaphore or by the OS if we are - /// working with a named POSIX semaphore. - sem_t *sema_; - - /// Name of the semaphore (if this is non-NULL then this is a named - /// POSIX semaphore, else its an unnamed POSIX semaphore). - char *name_; - -# if defined (ACE_LACKS_NAMED_POSIX_SEM) - /// this->sema_ doesn't always get created dynamically if a platform - /// doesn't support named posix semaphores. We use this flag to - /// remember if we need to delete or not. - bool new_sema_; -# endif /* ACE_LACKS_NAMED_POSIX_SEM */ - -# if !defined (ACE_HAS_POSIX_SEM_TIMEOUT) && !defined (ACE_DISABLE_POSIX_SEM_TIMEOUT_EMULATION) - /// Serialize access to internal state. - ACE_mutex_t lock_; - - /// Block until there are no waiters. - ACE_cond_t count_nonzero_; -# endif /* !ACE_HAS_POSIX_SEM_TIMEOUT && !ACE_DISABLE_POSIX_SEM_TIMEOUT_EMULATION */ - } ACE_sema_t; -#endif /* ACE_HAS_POSIX_SEM */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_SEMAPHORE_H */ diff --git a/externals/ace/os_include/os_setjmp.h b/externals/ace/os_include/os_setjmp.h deleted file mode 100644 index 2ab4a18a9f9..00000000000 --- a/externals/ace/os_include/os_setjmp.h +++ /dev/null @@ -1,42 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_setjmp.h - * - * stack environment declarations - * - * $Id: os_setjmp.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_SETJMP_H -#define ACE_OS_INCLUDE_OS_SETJMP_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_SETJMP_H) -# include /**/ -#endif /* !ACE_LACKS_SETJMP_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_SETJMP_H */ diff --git a/externals/ace/os_include/os_signal.h b/externals/ace/os_include/os_signal.h deleted file mode 100644 index dbda2a67b4e..00000000000 --- a/externals/ace/os_include/os_signal.h +++ /dev/null @@ -1,249 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_signal.h - * - * signals - * - * $Id: os_signal.h 87480 2009-11-11 11:38:15Z olli $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_SIGNAL_H -#define ACE_OS_INCLUDE_OS_SIGNAL_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_types.h" - -#if !defined (ACE_LACKS_SIGNAL_H) - extern "C" { -# include /**/ - } -#endif /* !ACE_LACKS_SIGNAL_H */ - -// This must come after signal.h is #included. -#if defined (SCO) -# define SIGIO SIGPOLL -# include /**/ -#endif /* SCO */ - -#if defined (ACE_HAS_SIGINFO_T) -# if !defined (ACE_LACKS_SIGINFO_H) -# if defined (__QNX__) || defined (__OpenBSD__) || defined (__INTERIX) -# include /**/ -# else /* __QNX__ || __OpenBSD__ */ -# include /**/ -# endif /* __QNX__ || __OpenBSD__ */ -# endif /* ACE_LACKS_SIGINFO_H */ -#endif /* ACE_HAS_SIGINFO_T */ - -#if defined (ACE_VXWORKS) && (ACE_VXWORKS < 0x620) && !defined (__RTP__) -# include /**/ -#endif /* ACE_VXWORKS */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#if defined (ACE_LACKS_SIGSET) && !defined (__MINGW32__) - typedef u_int sigset_t; -#endif /* ACE_LACKS_SIGSET && !sigset_t */ - -#if !defined (ACE_HAS_SIG_ATOMIC_T) - typedef int sig_atomic_t; -#endif /* !ACE_HAS_SIG_ATOMIC_T */ - -# if !defined (SA_SIGINFO) -# define SA_SIGINFO 0 -# endif /* SA_SIGINFO */ - -# if !defined (SA_RESTART) -# define SA_RESTART 0 -# endif /* SA_RESTART */ - -#if !defined (SIGHUP) -# define SIGHUP 0 -#endif /* SIGHUP */ - -#if !defined (SIGINT) -# define SIGINT 0 -#endif /* SIGINT */ - -#if !defined (SIGSEGV) -# define SIGSEGV 0 -#endif /* SIGSEGV */ - -#if !defined (SIGIO) -# define SIGIO 0 -#endif /* SIGSEGV */ - -#if !defined (SIGUSR1) -# define SIGUSR1 0 -#endif /* SIGUSR1 */ - -#if !defined (SIGUSR2) -# define SIGUSR2 0 -#endif /* SIGUSR2 */ - -#if !defined (SIGCHLD) -# define SIGCHLD 0 -#endif /* SIGCHLD */ - -#if !defined (SIGCLD) -# define SIGCLD SIGCHLD -#endif /* SIGCLD */ - -#if !defined (SIGQUIT) -# define SIGQUIT 0 -#endif /* SIGQUIT */ - -#if !defined (SIGPIPE) -# define SIGPIPE 0 -#endif /* SIGPIPE */ - -#if !defined (SIGALRM) -# define SIGALRM 0 -#endif /* SIGALRM */ - -#if !defined (SIGABRT) -# define SIGABRT 0 -#endif /* SIGABRT */ - -#if !defined (SIGTERM) -# define SIGTERM 0 -#endif /* SIGTERM */ - -#if !defined (SIG_DFL) -# define SIG_DFL ((__sighandler_t) 0) -#endif /* SIG_DFL */ - -#if !defined (SIG_IGN) -# define SIG_IGN ((__sighandler_t) 1) /* ignore signal */ -#endif /* SIG_IGN */ - -#if !defined (SIG_ERR) -# define SIG_ERR ((__sighandler_t) -1) /* error return from signal */ -#endif /* SIG_ERR */ - -// These are used by the and -// methods. They must be unique and cannot -// conflict with the value of . We make the numbers -// negative here so they won't conflict with other values like SIGIO, -// etc. -# define ACE_SIGIO -1 -# define ACE_SIGURG -2 -# define ACE_CLOEXEC -3 - -#if defined (ACE_VXWORKS) -# define ACE_NSIG (_NSIGS + 1) -#elif defined (__Lynx__) || defined (ACE_HAS_RTEMS) -# define ACE_NSIG (NSIG + 1) -#else - // All other platforms set NSIG to one greater than the - // highest-numbered signal. -# define ACE_NSIG NSIG -#endif /* ACE_VXWORKS */ - -#if defined (ACE_HAS_WINCE) - typedef void (__cdecl * __sighandler_t)(int); -#endif - -#if defined (ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES) - // Prototypes for both signal() and struct sigaction are consistent.. - typedef void (*ACE_SignalHandler)(int); - typedef void (*ACE_SignalHandlerV)(int); -#elif defined (ACE_HAS_LYNXOS4_SIGNALS) || defined (ACE_HAS_TANDEM_SIGNALS) - typedef void (*ACE_SignalHandler)(...); - typedef void (*ACE_SignalHandlerV)(...); -#elif defined (ACE_HAS_SVR4_SIGNAL_T) - // SVR4 Signals are inconsistent (e.g., see struct sigaction).. - typedef void (*ACE_SignalHandler)(int); - typedef void (*ACE_SignalHandlerV)(void); -#elif defined (ACE_WIN32) - typedef void (__cdecl *ACE_SignalHandler)(int); - typedef void (__cdecl *ACE_SignalHandlerV)(int); -#elif defined (ACE_HAS_UNIXWARE_SVR4_SIGNAL_T) - typedef void (*ACE_SignalHandler)(int); - typedef void (*ACE_SignalHandlerV)(...); -#elif defined (INTEGRITY) - typedef void (*ACE_SignalHandler)(); - typedef void (*ACE_SignalHandlerV)(int); -#elif defined (ACE_HAS_RTEMS) - typedef void (*ACE_SignalHandler)(); - typedef void (*ACE_SignalHandlerV)(); -#else /* This is necessary for some older broken version of cfront */ -# if defined (SIG_PF) -# define ACE_SignalHandler SIG_PF -# else - typedef void (*ACE_SignalHandler)(int); -# endif /* SIG_PF */ - typedef void (*ACE_SignalHandlerV)(...); -#endif /* ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES */ - -#if defined (ACE_LACKS_SIGACTION) - struct sigaction - { - int sa_flags; - ACE_SignalHandlerV sa_handler; - sigset_t sa_mask; - }; -#endif /* ACE_LACKS_SIGACTION */ - -// Defining POSIX4 real-time signal range. -#if defined(ACE_HAS_POSIX_REALTIME_SIGNALS) -# define ACE_SIGRTMIN SIGRTMIN -# define ACE_SIGRTMAX SIGRTMAX -#else /* !ACE_HAS_POSIX_REALTIME_SIGNALS */ -# ifndef ACE_SIGRTMIN -# define ACE_SIGRTMIN 0 -# endif /* ACE_SIGRTMIN */ -# ifndef ACE_SIGRTMAX -# define ACE_SIGRTMAX 0 -# endif /* ACE_SIGRTMAX */ -#endif /* ACE_HAS_POSIX_REALTIME_SIGNALS */ - -#if defined (DIGITAL_UNIX) - // sigwait is yet another macro on Digital UNIX 4.0, just causing - // trouble when introducing member functions with the same name. - // Thanks to Thilo Kielmann" for - // this fix. -# if defined (__DECCXX_VER) -# undef sigwait - // cxx on Digital Unix 4.0 needs this declaration. With it, - // <::_Psigwait> works with cxx -pthread. g++ does _not_ need - // it. - int _Psigwait __((const sigset_t *set, int *sig)); -# endif /* __DECCXX_VER */ -#elif !defined (ACE_HAS_SIGWAIT) -# if defined(ACE_HAS_RTEMS) - int sigwait (const sigset_t *set, int *sig); -# else - int sigwait (sigset_t *set); -# endif /* ACE_HAS_RTEMS */ -#endif /* ! DIGITAL_UNIX && ! ACE_HAS_SIGWAIT */ - -#if !defined (ACE_HAS_PTHREAD_SIGMASK_PROTOTYPE) - int pthread_sigmask(int, const sigset_t *, sigset_t *); -#endif /*!ACE_HAS_PTHREAD_SIGMASK_PROTOTYPE */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include "ace/os_include/os_ucontext.h" - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_SIGNAL_H */ diff --git a/externals/ace/os_include/os_spawn.h b/externals/ace/os_include/os_spawn.h deleted file mode 100644 index 0f825640ff9..00000000000 --- a/externals/ace/os_include/os_spawn.h +++ /dev/null @@ -1,46 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_spawn.h - * - * spawn (ADVANCED REALTIME) - * - * $Id: os_spawn.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_SPAWN_H -#define ACE_OS_INCLUDE_OS_SPAWN_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/os_signal.h" -#include "ace/os_include/sys/os_types.h" -#include "ace/os_include/os_sched.h" - -#if !defined (ACE_LACKS_SPAWN_H) -# include /**/ -#endif /* !ACE_LACKS_SPAWN_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_SPAWN_H */ diff --git a/externals/ace/os_include/os_stdarg.h b/externals/ace/os_include/os_stdarg.h deleted file mode 100644 index 0e9d234b55e..00000000000 --- a/externals/ace/os_include/os_stdarg.h +++ /dev/null @@ -1,50 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_stdarg.h - * - * handle variable argument list - * - * $Id: os_stdarg.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_STDARG_H -#define ACE_OS_INCLUDE_OS_STDARG_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_STDARG_H) -# include /**/ -#endif /* !ACE_LACKS_STDARG_H */ - -#if !defined (va_copy) -#if defined (__va_copy) -#define va_copy(d, s) __va_copy((d),(s)) -#else -#define va_copy(d, s) memcpy((void *)&(d),(void *)&(s),sizeof(va_list)) -#endif -#endif - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_STDARG_H */ diff --git a/externals/ace/os_include/os_stdbool.h b/externals/ace/os_include/os_stdbool.h deleted file mode 100644 index ddb3f8e0ddb..00000000000 --- a/externals/ace/os_include/os_stdbool.h +++ /dev/null @@ -1,42 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_stdbool.h - * - * boolean type and values - * - * $Id: os_stdbool.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_STDBOOL_H -#define ACE_OS_INCLUDE_OS_STDBOOL_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_STDBOOL_H) -# include /**/ -#endif /* !ACE_LACKS_STDBOOL_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_STDBOOL_H */ diff --git a/externals/ace/os_include/os_stddef.h b/externals/ace/os_include/os_stddef.h deleted file mode 100644 index 55ec501921d..00000000000 --- a/externals/ace/os_include/os_stddef.h +++ /dev/null @@ -1,75 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_stddef.h - * - * standard type definitions - * - * $Id: os_stddef.h 89759 2010-04-06 06:07:24Z johnnyw $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -// From http://www.UNIX-systems.org/single_unix_specification/ - -#ifndef ACE_OS_INCLUDE_OS_STDDEF_H -#define ACE_OS_INCLUDE_OS_STDDEF_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_STDDEF_H) -# include /**/ -#endif /* !ACE_LACKS_STDDEF_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -// Signed integer type of the result of subtracting two pointers. -#if defined (ACE_LACKS_PTRDIFF_T) -# if !defined (ACE_PTRDIFF_T_TYPE) -# define ACE_PTRDIFF_T_TYPE unsigned long -# endif /* !ACE_PTRDIFF_T_TYPE */ - typedef ACE_PTRDIFF_T_TYPE ptrdiff_t; -#endif /* ACE_LACKS_PTRDIFF_T */ - -/* - Integer type whose range of values can represent distinct wide-character - codes for all members of the largest character set specified among the - locales supported by the compilation environment: the null character has - the code value 0 and each member of the portable character set has a code - value equal to its value when used as the lone character in an integer - character constant. -*/ -#if defined (ACE_LACKS_WCHAR_T) -# if !defined (ACE_WCHAR_T_TYPE) -# define ACE_WCHAR_T_TYPE long -# endif /* !ACE_WCHAR_T_TYPE */ - typedef ACE_WCHAR_T_TYPE wchar_t; -#endif /* ACE_LACKS_WCHAR_T */ - -// Unsigned integer type of the result of the sizeof operator. -#if defined (ACE_LACKS_SIZE_T) -# if !defined (ACE_SIZE_T_TYPE) -# define ACE_SIZE_T_TYPE unsigned int -# endif /* !ACE_SIZE_T_TYPE */ - typedef ACE_SIZE_T_TYPE size_t; -#endif /* ACE_LACKS_SIZE_T */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_STDDEF_H */ diff --git a/externals/ace/os_include/os_stdint.h b/externals/ace/os_include/os_stdint.h deleted file mode 100644 index ac6fec664c5..00000000000 --- a/externals/ace/os_include/os_stdint.h +++ /dev/null @@ -1,141 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_stdint.h - * - * integer types - * - * $Id: os_stdint.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_STDINT_H -#define ACE_OS_INCLUDE_OS_STDINT_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_STDINT_H) -# include /**/ -#endif /* !ACE_LACKS_STDINT_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -// BSD style types -#if defined (ACE_LACKS_SYS_TYPES_H) \ - || (defined (__GLIBC__) && !defined (_BSD_SOURCE)) - typedef unsigned char u_char; - typedef unsigned short u_short; - typedef unsigned int u_int; - typedef unsigned long u_long; - - typedef unsigned char uchar_t; - typedef unsigned short ushort_t; - typedef unsigned int uint_t; - typedef unsigned long ulong_t; -#endif /* ACE_LACKS_SYS_TYPES_H */ - -/* Define required types if missing */ - -#if defined (ACE_LACKS_INT8_T) -# if !defined (ACE_INT8_T_TYPE) -# define ACE_INT8_T_TYPE char -# endif /* !ACE_INT8_T_TYPE */ - typedef ACE_INT8_T_TYPE int8_t; -#endif /* ACE_LACKS_INT8_T */ - -#if defined (ACE_LACKS_UINT8_T) -# if !defined (ACE_UINT8_T_TYPE) -# define ACE_UINT8_T_TYPE unsigned char -# endif /* !ACE_UINT8_T_TYPE */ - typedef ACE_UINT8_T_TYPE int8_t; -#endif /* ACE_LACKS_UINT8_T */ - -#if defined (ACE_LACKS_INT16_T) -# if !defined (ACE_INT16_T_TYPE) -# define ACE_INT16_T_TYPE short -# endif /* !ACE_INT16_T_TYPE */ - typedef ACE_INT16_T_TYPE int16_t; -#endif /* ACE_LACKS_INT16_T */ - -#if defined (ACE_LACKS_UINT16_T) -# if !defined (ACE_UINT16_T_TYPE) -# define ACE_UINT16_T_TYPE unsigned short -# endif /* !ACE_UINT16_T_TYPE */ - typedef ACE_UINT16_T_TYPE int16_t; -#endif /* ACE_LACKS_UINT16_T */ - -#if defined (ACE_LACKS_INT32_T) -# if !defined (ACE_INT32_T_TYPE) -# define ACE_INT32_T_TYPE long -# endif /* !ACE_INT32_T_TYPE */ - typedef ACE_INT32_T_TYPE int32_t; -#endif /* ACE_LACKS_INT32_T */ - -#if defined (ACE_LACKS_UINT32_T) -# if !defined (ACE_UINT32_T_TYPE) -# define ACE_UINT32_T_TYPE unsigned long -# endif /* !ACE_UINT32_T_TYPE */ - typedef ACE_UINT32_T_TYPE int32_t; -#endif /* ACE_LACKS_UIN32_T */ - -// @todo pull in ACE class here -// 64 bit will be a problem, but stub it out for now -/* -If an implementation provides integer types with width 64 that meet -these requirements, then the following types are required: int64_t uint64_t - -In particular, this will be the case if any of the following are true: - -The implementation supports the _POSIX_V6_ILP32_OFFBIG programming -environment and the application is being built in the -_POSIX_V6_ILP32_OFFBIG programming environment (see the Shell and -Utilities volume of IEEE Std 1003.1-2001, c99, Programming Environments). - -The implementation supports the _POSIX_V6_LP64_OFF64 programming -environment and the application is being built in the -_POSIX_V6_LP64_OFF64 programming environment. - -The implementation supports the _POSIX_V6_LPBIG_OFFBIG programming -environment and the application is being built in the -_POSIX_V6_LPBIG_OFFBIG programming environment. -*/ -#if defined (ACE_LACKS_INT64_T) -# if !defined (ACE_INT64_T_TYPE) -# define ACE_INT64_T_TYPE long -# endif /* !ACE_INT64_T_TYPE */ - typedef ACE_INT64_T_TYPE int64_t; -#endif /* ACE_LACKS_INT64_T */ - -#if defined (ACE_LACKS_UINT64_T) -# if !defined (ACE_UINT64_T_TYPE) -# define ACE_UINT64_T_TYPE unsigned long -# endif /* !ACE_UINT64_T_TYPE */ - typedef ACE_UINT64_T_TYPE int64_t; -#endif /* ACE_LACKS_UIN64_T */ - -// @todo move the ACE_INT## typedefs here so that ACE_INT64 will -// always be available. - - -// @todo perhaps add macros - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_STDINT_H */ diff --git a/externals/ace/os_include/os_stdio.h b/externals/ace/os_include/os_stdio.h deleted file mode 100644 index e9f452024ff..00000000000 --- a/externals/ace/os_include/os_stdio.h +++ /dev/null @@ -1,87 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_stdio.h - * - * standard buffered input/output - * - * $Id: os_stdio.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_STDIO_H -#define ACE_OS_INCLUDE_OS_STDIO_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -// NOTE: stdarg.h must be #included before stdio.h on LynxOS. -#include "ace/os_include/os_stdarg.h" -#include "ace/os_include/os_stddef.h" - -#if !defined (ACE_LACKS_STDIO_H) -# include /**/ -#endif /* !ACE_LACKS_STDIO_H */ - -#if defined (ACE_VXWORKS) -// for remove(), rename() -# include /**/ -// for remCurIdGet() -# include /**/ -# if defined (__RTP__) && ((ACE_VXWORKS >= 0x620) && (ACE_VXWORKS <= 0x650)) -# define L_cuserid _PARM_L_cuserid -# endif -#endif /* ACE_VXWORKS */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -# if defined (INTEGRITY) -# define ACE_MAX_USERID 32 -# elif defined (ACE_WIN32) -# define ACE_MAX_USERID 32 -# else -# if defined (_POSIX_SOURCE) && defined (L_cuserid) -# define ACE_MAX_USERID L_cuserid -# else -# define ACE_MAX_USERID 9 -# endif -# endif /* INTEGRITY */ - -#if defined (BUFSIZ) -# define ACE_STREAMBUF_SIZE BUFSIZ -#else -# define ACE_STREAMBUF_SIZE 1024 -#endif /* BUFSIZ */ - -#if defined (ACE_WIN32) - typedef OVERLAPPED ACE_OVERLAPPED; -#else - struct ACE_OVERLAPPED - { - unsigned long Internal; - unsigned long InternalHigh; - unsigned long Offset; - unsigned long OffsetHigh; - ACE_HANDLE hEvent; - }; -#endif /* ACE_WIN32 */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_STDIO_H */ diff --git a/externals/ace/os_include/os_stdlib.h b/externals/ace/os_include/os_stdlib.h deleted file mode 100644 index 6a675d54e29..00000000000 --- a/externals/ace/os_include/os_stdlib.h +++ /dev/null @@ -1,85 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_stdlib.h - * - * standard library definitions - * - * $Id: os_stdlib.h 83948 2008-12-02 13:55:34Z jtc $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_STDLIB_H -#define ACE_OS_INCLUDE_OS_STDLIB_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/os_stddef.h" -#include "ace/os_include/sys/os_wait.h" - -#if defined (ACE_HAS_ALLOCA_H) -# include /**/ -#endif /* ACE_HAS_ALLOCA_H */ - -#if !defined (ACE_LACKS_STDLIB_H) -# include /**/ -#endif /* !ACE_LACKS_STDLIB_H */ - -#if defined (ACE_VXWORKS) && !defined (__RTP__) -# include /**/ -#endif /* ACE_VXWORKS */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - - typedef u_int ACE_RANDR_TYPE; -#if defined (ACE_HAS_BROKEN_RANDR) - // The SunOS 5.4.X version of rand_r is inconsistent with the header - // files... - int rand_r (ACE_RANDR_TYPE seed); -#else -#endif /* ACE_HAS_BROKEN_RANDR */ - -#if defined (DIGITAL_UNIX) - extern int _Prand_r (unsigned int *seedptr); -#endif /* DIGITAL_UNIX */ - -#if defined (ACE_LACKS_PUTENV_PROTOTYPE) - int putenv (char *); -#endif /* ACE_LACKS_PUTENV_PROTOTYPE */ - -#if defined (ACE_LACKS_MKTEMP_PROTOTYPE) - char *mktemp (char *); -#endif /* ACE_LACKS_MKTEMP_PROTOTYPE */ - -#if defined (ACE_LACKS_MKSTEMP_PROTOTYPE) - int mkstemp (char *); -#endif /* ACE_LACKS_MKSTEMP_PROTOTYPE */ - -#if defined (ACE_LACKS_STRTOLL_PROTOTYPE) - long long strtoll (const char *, char **, int); -#endif /* ACE_LACKS_STRTOLL_PROTOTYPE */ - -#if defined (ACE_LACKS_STRTOULL_PROTOTYPE) - unsigned long long strtoull (const char *, char **, int); -#endif /* ACE_LACKS_STRTOULL_PROTOTYPE */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_STDLIB_H */ diff --git a/externals/ace/os_include/os_string.h b/externals/ace/os_include/os_string.h deleted file mode 100644 index 0aa2f7de7cc..00000000000 --- a/externals/ace/os_include/os_string.h +++ /dev/null @@ -1,53 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_string.h - * - * string operations - * - * $Id: os_string.h 87216 2009-10-23 20:26:16Z olli $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_STRING_H -#define ACE_OS_INCLUDE_OS_STRING_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/os_stddef.h" - -#if !defined (ACE_LACKS_STRING_H) -# include /**/ -#endif /* !ACE_LACKS_STRING_H */ - - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#if defined (ACE_LACKS_STRTOK_R_PROTOTYPE) && !defined (_POSIX_SOURCE) - char *strtok_r (char *s, const char *delim, char **save_ptr); -#endif /* ACE_LACKS_STRTOK_R_PROTOTYPE */ - -#if defined (ACE_LACKS_STRNLEN_PROTOTYPE) - size_t strnlen(const char *s, size_t maxlen); -#endif /* ACE_LACKS_STRNLEN_PROTOTYPE */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_STRING_H */ diff --git a/externals/ace/os_include/os_strings.h b/externals/ace/os_include/os_strings.h deleted file mode 100644 index ba258b08cb9..00000000000 --- a/externals/ace/os_include/os_strings.h +++ /dev/null @@ -1,52 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_strings.h - * - * string operations - * - * $Id: os_strings.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_STRINGS_H -#define ACE_OS_INCLUDE_OS_STRINGS_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/os_stddef.h" - -#if !defined (ACE_LACKS_STRINGS_H) -# include /**/ -#endif /* !ACE_LACKS_STRINGS_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#if defined (ACE_LACKS_STRCASECMP_PROTOTYPE) - int strcasecmp(const char *, const char *); -#endif /* ACE_LACKS_STRCASECMP_PROTOTYPE */ - -#if defined (ACE_LACKS_STRNCASECMP_PROTOTYPE) - int strncasecmp(const char *, const char *, size_t); -#endif /* ACE_LACKS_STRNCASECMP_PROTOTYPE */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_STRINGS_H */ diff --git a/externals/ace/os_include/os_stropts.h b/externals/ace/os_include/os_stropts.h deleted file mode 100644 index e64717a9551..00000000000 --- a/externals/ace/os_include/os_stropts.h +++ /dev/null @@ -1,114 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_stropts.h - * - * STREAMS interface (STREAMS) - * - * $Id: os_stropts.h 84660 2009-03-01 20:22:37Z olli $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_STROPTS_H -#define ACE_OS_INCLUDE_OS_STROPTS_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/os_unistd.h" - -#if defined (ACE_HAS_TIMOD_H) -# include /**/ -#elif defined (ACE_HAS_OSF_TIMOD_H) -# include /**/ -#endif /* ACE_HAS_TIMOD_H */ - -#if !defined (ACE_LACKS_SYS_IOCTL_H) -# include /**/ -#endif /* !ACE_LACKS_IOCTL_H */ - -#if defined (ACE_HAS_SYS_FILIO_H) -# include /**/ -#endif /* ACE_HAS_SYS_FILIO_H */ - -#if defined (ACE_HAS_SYS_SOCKIO_H) -# include /**/ -#endif /* ACE_HAS_SOCKIO_H */ - -// This is sorta counter intuitive, but this is how it was done in OS.h -// @todo: fix this... dhinton -#if defined (ACE_HAS_STREAMS) -# if defined (AIX) -# if !defined (_XOPEN_EXTENDED_SOURCE) -# define _XOPEN_EXTENDED_SOURCE -# endif /* !_XOPEN_EXTENDED_SOURCE */ -# endif /* AIX */ -#endif /* ACE_HAS_STREAMS */ - -#if !defined (ACE_LACKS_STROPTS_H) -# include /**/ -#endif /* !ACE_LACKS_STROPTS_H */ - -// This is sorta counter intuitive, but this is how it was done in OS.h -// @todo: fix this... dhinton -#if defined (ACE_HAS_STREAMS) -# if defined (AIX) -# undef _XOPEN_EXTENDED_SOURCE -# endif /* AIX */ -#endif /* ACE_HAS_STREAMS */ - -#if defined (ACE_VXWORKS) -// for ioctl() -# include /**/ -#endif /* ACE_VXWORKS */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#if defined (ACE_LACKS_STRRECVFD) - struct strrecvfd {}; -#endif /* ACE_LACKS_STRRECVFD */ - -# if !defined (SIOCGIFBRDADDR) -# define SIOCGIFBRDADDR 0 -# endif /* SIOCGIFBRDADDR */ - -# if !defined (SIOCGIFADDR) -# define SIOCGIFADDR 0 -# endif /* SIOCGIFADDR */ - -# if !defined (ACE_HAS_STRBUF_T) -struct strbuf -{ - /// No. of bytes in buffer. - int maxlen; - /// No. of bytes returned. - int len; - /// Pointer to data. - void *buf; -}; -# endif /* ACE_HAS_STRBUF_T */ - -// These prototypes are chronically lacking from many versions of UNIX. -#if !defined (ACE_WIN32) && !defined (ACE_HAS_ISASTREAM_PROTOTYPE) - int isastream (int); -#endif /* !ACE_WIN32 && ACE_HAS_ISASTREAM_PROTOTYPE */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_STROPTS_H */ diff --git a/externals/ace/os_include/os_syslog.h b/externals/ace/os_include/os_syslog.h deleted file mode 100644 index d448b7491e5..00000000000 --- a/externals/ace/os_include/os_syslog.h +++ /dev/null @@ -1,42 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_syslog.h - * - * definitions for system error logging - * - * $Id: os_syslog.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_SYSLOG_H -#define ACE_OS_INCLUDE_OS_SYSLOG_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_SYSLOG_H) -# include /**/ -#endif /* !ACE_LACKS_SYSLOG_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_SYSLOG_H */ diff --git a/externals/ace/os_include/os_tar.h b/externals/ace/os_include/os_tar.h deleted file mode 100644 index 007925022e8..00000000000 --- a/externals/ace/os_include/os_tar.h +++ /dev/null @@ -1,42 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_tar.h - * - * extended tar definitions - * - * $Id: os_tar.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_TAR_H -#define ACE_OS_INCLUDE_OS_TAR_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_TAR_H) -# include /**/ -#endif /* !ACE_LACKS_TAR_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_TAR_H */ diff --git a/externals/ace/os_include/os_termios.h b/externals/ace/os_include/os_termios.h deleted file mode 100644 index 9dfd3862276..00000000000 --- a/externals/ace/os_include/os_termios.h +++ /dev/null @@ -1,46 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_termios.h - * - * define values for termios - * - * $Id: os_termios.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_TERMIOS_H -#define ACE_OS_INCLUDE_OS_TERMIOS_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_TERMIOS_H) -# include /**/ -#endif /* !ACE_LACKS_TERMIOS_H */ - -#if defined (HPUX) -# include /**/ -#endif /* HPUX */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_TERMIOS_H */ diff --git a/externals/ace/os_include/os_tgmath.h b/externals/ace/os_include/os_tgmath.h deleted file mode 100644 index 6d9f2c2db23..00000000000 --- a/externals/ace/os_include/os_tgmath.h +++ /dev/null @@ -1,45 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_tgmath.h - * - * type-generic macros - * - * $Id: os_tgmath.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_TGMATH_H -#define ACE_OS_INCLUDE_OS_TGMATH_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/os_math.h" -#include "ace/os_include/os_complex.h" - -#if !defined (ACE_LACKS_TGMATH_H) -# include /**/ -#endif /* !ACE_LACKS_TGMATH_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_TGMATH_H */ diff --git a/externals/ace/os_include/os_time.h b/externals/ace/os_include/os_time.h deleted file mode 100644 index e10a3b3164b..00000000000 --- a/externals/ace/os_include/os_time.h +++ /dev/null @@ -1,119 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_time.h - * - * time types - * - * $Id: os_time.h 87270 2009-10-29 21:47:47Z olli $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_TIME_H -#define ACE_OS_INCLUDE_OS_TIME_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -// @todo should we include anything from signal.h? -#include "ace/os_include/sys/os_types.h" - -// To get the proper select() signature, this is required for HP-UX, and -// maybe other platforms that offer both int and fdset forms of select(). -// For HP-UX, sys/time.h must be included before time.h, or -// _XOPEN_SOURCE_EXTENDED must be defined. It's not nice to require -// the preprocessor macro, so we force our select() preference this way. -#if !defined (ACE_LACKS_SYS_TIME_H) -# include /**/ -#endif /* !ACE_LACKS_SYS_TIME_H */ - -#if !defined (ACE_LACKS_TIME_H) -# include /**/ -#endif /* !ACE_LACKS_TIME_H */ - -# if defined (ACE_USES_STD_NAMESPACE_FOR_STDC_LIB) && \ - (ACE_USES_STD_NAMESPACE_FOR_STDC_LIB != 0) -using std::tm; -# if !defined (ACE_HAS_DINKUM_STL) -# if defined (ACE_WIN32) -using std::_timezone; -# else -using std::timezone; -# endif -# endif -using std::difftime; -# endif /* ACE_USES_STD_NAMESPACE_FOR_STDC_LIB */ - -# if !defined (ACE_HAS_POSIX_TIME) -// Definition per POSIX. -typedef struct timespec -{ - /// Seconds - time_t tv_sec; - /// Nanoseconds - long tv_nsec; -} timespec_t; -# elif defined (ACE_HAS_BROKEN_POSIX_TIME) -# if defined (ACE_OPENVMS) -# include /**/ -# else -// OSF/1 defines struct timespec in - Tom Marrs -# include /**/ -# endif -# endif /* !ACE_HAS_POSIX_TIME */ - -# if defined(ACE_LACKS_TIMESPEC_T) -typedef struct timespec timespec_t; -# endif /* ACE_LACKS_TIMESPEC_T */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -// There are a lot of threads-related macro definitions in the config files. -// They came in at different times and from different places and platform -// requirements as threads evolved. They are probably not all needed - some -// overlap or are otherwise confused. This is an attempt to start -// straightening them out. -#if defined (ACE_HAS_PTHREADS) /* POSIX.1c threads (pthreads) */ - // ... and 2-parameter asctime_r and ctime_r -# if !defined (ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R) && \ - !defined (ACE_HAS_STHREADS) && !defined (ACE_VXWORKS) -# define ACE_HAS_2_PARAM_ASCTIME_R_AND_CTIME_R -# endif -#endif /* ACE_HAS_PTHREADS */ - -#if defined (ACE_LACKS_STRPTIME_PROTOTYPE) && !defined (_XOPEN_SOURCE) - extern char *strptime (const char *s, const char *fmt, struct tm *tp); -#endif /* ACE_LACKS_STRPTIME_PROTOTYPE */ - -#if defined (ACE_LACKS_CONST_TIMESPEC_PTR) -typedef struct timespec * ACE_TIMESPEC_PTR; -#else -typedef const struct timespec * ACE_TIMESPEC_PTR; -#endif /* ACE_LACKS_CONST_TIMESPEC_PTR */ - -#if defined (DIGITAL_UNIX) - extern char *_Pctime_r (const time_t *, char *); - extern struct tm *_Plocaltime_r (const time_t *, struct tm *); - extern struct tm *_Pgmtime_r (const time_t *, struct tm *); - extern char *_Pasctime_r (const struct tm *, char *); -#endif /* DIGITAL_UNIX */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_TIME_H */ diff --git a/externals/ace/os_include/os_trace.h b/externals/ace/os_include/os_trace.h deleted file mode 100644 index fd89d54b23b..00000000000 --- a/externals/ace/os_include/os_trace.h +++ /dev/null @@ -1,44 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_trace.h - * - * tracing - * - * $Id: os_trace.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_TRACE_H -#define ACE_OS_INCLUDE_OS_TRACE_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_types.h" - -#if !defined (ACE_LACKS_TRACE_H) -# include /**/ -#endif /* !ACE_LACKS_TRACE_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_TRACE_H */ diff --git a/externals/ace/os_include/os_typeinfo.h b/externals/ace/os_include/os_typeinfo.h deleted file mode 100644 index 3ad1b16ef77..00000000000 --- a/externals/ace/os_include/os_typeinfo.h +++ /dev/null @@ -1,39 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_typeinfo.h - * - * definitions for the typeinfo file - * - * $Id: os_typeinfo.h 84160 2009-01-14 14:13:58Z johnnyw $ - * - * @author Don Hinton Johnny Willemsen - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_TYPEINFO_H -#define ACE_OS_INCLUDE_OS_TYPEINFO_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -# include /**/ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_TYPEINFO_H */ diff --git a/externals/ace/os_include/os_ucontext.h b/externals/ace/os_include/os_ucontext.h deleted file mode 100644 index f62be80e5fc..00000000000 --- a/externals/ace/os_include/os_ucontext.h +++ /dev/null @@ -1,48 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_ucontext.h - * - * user context - * - * $Id: os_ucontext.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_UCONTEXT_H -#define ACE_OS_INCLUDE_OS_UCONTEXT_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/os_signal.h" - -#if !defined (ACE_LACKS_UCONTEXT_H) -# include /**/ -#endif /* !ACE_LACKS_ucontext_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -# if !defined (ACE_HAS_UCONTEXT_T) -typedef int ucontext_t; -# endif /* ACE_HAS_UCONTEXT_T */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_UCONTEXT_H */ diff --git a/externals/ace/os_include/os_ulimit.h b/externals/ace/os_include/os_ulimit.h deleted file mode 100644 index 8593c0d95a5..00000000000 --- a/externals/ace/os_include/os_ulimit.h +++ /dev/null @@ -1,42 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_ulimit.h - * - * ulimit commands - * - * $Id: os_ulimit.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_ULIMIT_H -#define ACE_OS_INCLUDE_OS_ULIMIT_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_ULIMIT_H) -# include /**/ -#endif /* !ACE_LACKS_ULIMIT_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_ULIMIT_H */ diff --git a/externals/ace/os_include/os_unistd.h b/externals/ace/os_include/os_unistd.h deleted file mode 100644 index ee685d26222..00000000000 --- a/externals/ace/os_include/os_unistd.h +++ /dev/null @@ -1,196 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_unistd.h - * - * standard symbolic constants and types - * - * $Id: os_unistd.h 87125 2009-10-15 17:34:25Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_UNISTD_H -#define ACE_OS_INCLUDE_OS_UNISTD_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_types.h" -#include "ace/os_include/os_inttypes.h" - -#if defined (ACE_HAS_PROCESS_H) -# include /**/ -#endif /* ACE_HAS_PROCESS_H */ - -#if defined (ACE_HAS_IO_H) -# include /**/ -#endif /* ACE_HAS_IO_H */ - -#if defined (ACE_HAS_SYS_SYSTEMINFO_H) -# include /**/ -#endif /* ACE_HAS_SYS_SYSTEMINFO_H */ - -#if !defined (ACE_LACKS_UNISTD_H) -# include /**/ -#endif /* !ACE_LACKS_UNISTD_H */ - -#if defined (ACE_VXWORKS) -# if !defined (__RTP__) - // for unlink(), close(), read(), write(), lseek(), chdir(), getcwd(), - // getwd(), and isatty() - # include /**/ -# endif -// for gethostname() -# include /**/ -#endif /* ACE_VXWORKS */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#if defined (ACE_WIN32) -// The following are #defines and #includes that are specific to -// WIN32. -# if defined (ACE_HAS_WINCE) -# define ACE_STDIN _fileno (stdin) -# define ACE_STDOUT _fileno (stdout) -# define ACE_STDERR _fileno (stderr) -# else -# define ACE_STDIN GetStdHandle (STD_INPUT_HANDLE) -# define ACE_STDOUT GetStdHandle (STD_OUTPUT_HANDLE) -# define ACE_STDERR GetStdHandle (STD_ERROR_HANDLE) -# endif // ACE_HAS_WINCE -// The following are #defines and #includes that are specific to UNIX. -#else /* !ACE_WIN32 */ -# if defined (STDIN_FILENO) -# define ACE_STDIN STDIN_FILENO -# else -# define ACE_STDIN 0 -# endif -# if defined (STDOUT_FILENO) -# define ACE_STDOUT STDOUT_FILENO -# else -# define ACE_STDOUT 1 -# endif -# if defined (STDERR_FILENO) -# define ACE_STDERR STDERR_FILENO -# else -# define ACE_STDERR 2 -# endif -#endif /* ACE_WIN32 */ - -#if (!defined (_BSD_SOURCE) && \ - !defined (_XOPEN_SOURCE) && !defined (_XOPEN_SOURCE_EXTENDED)) \ - || (defined (_XOPEN_SOURCE) && defined (__GNUC__)) - -# if defined (ACE_LACKS_SETREUID_PROTOTYPE) - extern int setreuid (uid_t ruid, uid_t euid); -# endif /* ACE_LACKS_SETREUID_PROTOTYPE */ - -# if defined (ACE_LACKS_SETREGID_PROTOTYPE) - extern int setregid (gid_t rgid, gid_t egid); -# endif /* ACE_LACKS_SETREGID_PROTOTYPE */ -#endif /* !_BSD_SOURCE && !_XOPEN_SOURCE && !_XOPEN_SOURCE_EXTENDED - || _XOPEN_SOURCE && __GNUC__ */ - - // for use by access() -# if !defined (R_OK) -# define R_OK 04 /* Test for Read permission. */ -# endif /* R_OK */ - -# if !defined (W_OK) -# define W_OK 02 /* Test for Write permission. */ -# endif /* W_OK */ - -# if !defined (X_OK) -# if defined (ACE_WIN32) - /* Windows has no test for X_OK - use R_OK instead */ -# define X_OK R_OK /* Test for eXecute permission. */ -# else /* ACE_WIN32 */ -# define X_OK 01 /* Test for eXecute permission. */ -# endif /* ACE_WIN32 */ -# endif /* X_OK */ - -# if !defined (F_OK) -# define F_OK 0 /* Test for existence of File. */ -# endif /* F_OK */ - -#if defined (ACE_LACKS_UALARM_PROTOTYPE) - u_int ualarm (u_int usecs, u_int interval); -#endif /* ACE_LACKS_UALARM_PROTOTYPE */ - -#if defined (ACE_LACKS_PREAD_PROTOTYPE) && (_XOPEN_SOURCE - 0) < 500 - // _XOPEN_SOURCE == 500 Single Unix conformance - // It seems that _XOPEN_SOURCE == 500 means that the prototypes are - // already defined in the system headers. - ssize_t pread (int fd, - void *buf, - size_t nbytes, - ACE_OFF_T offset); - - ssize_t pwrite (int fd, - const void *buf, - size_t n, - ACE_OFF_T offset); -#endif /* ACE_LACKS_PREAD_PROTOTYPE && (_XOPEN_SOURCE - 0) < 500 */ - -#if defined (ACE_LACKS_GETPGID_PROTOTYPE) && \ - !defined (_XOPEN_SOURCE) && !defined (_XOPEN_SOURCE_EXTENDED) - pid_t getpgid (pid_t pid); -#endif /* ACE_LACKS_GETPGID_PROTOTYPE && - !_XOPEN_SOURCE && !_XOPEN_SOURCE_EXTENDED */ - -#if !defined (_LARGEFILE64_SOURCE) -# if defined (ACE_LACKS_LSEEK64_PROTOTYPE) && \ - defined (ACE_LACKS_LLSEEK_PROTOTYPE) -# error Define either ACE_LACKS_LSEEK64_PROTOTYPE or ACE_LACKS_LLSEEK_PROTOTYPE, not both! -# elif defined (ACE_LACKS_LSEEK64_PROTOTYPE) - ACE_LOFF_T lseek64 (int fd, ACE_LOFF_T offset, int whence); -# elif defined (ACE_LACKS_LLSEEK_PROTOTYPE) - ACE_LOFF_T llseek (int fd, ACE_LOFF_T offset, int whence); -# endif -#endif /* _LARGEFILE64_SOURCE */ - -#if defined (__BORLANDC__) -# define _isatty isatty -#endif /* __BORLANDC__ */ - -# if defined (ACE_LACKS_TIMEDWAIT_PROTOTYPES) - - ssize_t read_timedwait (ACE_HANDLE handle, - char *buf, - size_t n, - struct timespec *timeout); - - ssize_t write_timedwait (ACE_HANDLE handle, - const void *buf, - size_t n, - struct timespec *timeout); - -# endif /* ACE_LACKS_TIMEDWAIT_PROTOTYPES */ - -#if defined (ACE_LACKS_SWAB_PROTOTYPE) - void swab(const void *, void *, ssize_t); -#endif /* ACE_LACKS_SWAB_PROTOTYPE */ - -#if defined (ACE_LACKS_GETOPT_PROTOTYPE) - int getopt(int, char * const [], const char *); -#endif /* ACE_LACKS_GETOPT_PROTOTYPE */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_UNISTD_H */ diff --git a/externals/ace/os_include/os_utime.h b/externals/ace/os_include/os_utime.h deleted file mode 100644 index 703da8b1424..00000000000 --- a/externals/ace/os_include/os_utime.h +++ /dev/null @@ -1,44 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_utime.h - * - * access and modification times structure - * - * $Id: os_utime.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_UTIME_H -#define ACE_OS_INCLUDE_OS_UTIME_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_types.h" - -#if !defined (ACE_LACKS_UTIME_H) -# include /**/ -#endif /* !ACE_LACKS_UTIME_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_UTIME_H */ diff --git a/externals/ace/os_include/os_utmpx.h b/externals/ace/os_include/os_utmpx.h deleted file mode 100644 index 74ef305d4c1..00000000000 --- a/externals/ace/os_include/os_utmpx.h +++ /dev/null @@ -1,44 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_utmpx.h - * - * user accounting database definitions - * - * $Id: os_utmpx.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_UTMPX_H -#define ACE_OS_INCLUDE_OS_UTMPX_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_time.h" - -#if !defined (ACE_LACKS_UTMPX_H) -# include /**/ -#endif /* !ACE_LACKS_UTMPX_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_UTMPX_H */ diff --git a/externals/ace/os_include/os_wchar.h b/externals/ace/os_include/os_wchar.h deleted file mode 100644 index 37eab2e4ee0..00000000000 --- a/externals/ace/os_include/os_wchar.h +++ /dev/null @@ -1,57 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_wchar.h - * - * wide-character handling - * - * $Id: os_wchar.h 83948 2008-12-02 13:55:34Z jtc $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_WCHAR_H -#define ACE_OS_INCLUDE_OS_WCHAR_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -// ctype.h, string.h, stdarg.h, stdio.h, stdlib.h, time.h -#include "ace/os_include/os_stdio.h" -#include "ace/os_include/os_stdlib.h" -#include "ace/os_include/os_time.h" -#include "ace/os_include/os_string.h" -#include "ace/os_include/os_ctype.h" - -#if !defined (ACE_LACKS_WCHAR_H) -# include /**/ -#endif /* !ACE_LACKS_WCHAR_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#if defined (ACE_LACKS_WCSTOLL_PROTOTYPE) - long long wcstoll (const wchar_t *, wchar_t **, int); -#endif /* ACE_LACKS_WCSTOLL_PROTOTYPE */ - -#if defined (ACE_LACKS_WCSTOULL_PROTOTYPE) - unsigned long long wcstoull (const wchar_t *, wchar_t **, int); -#endif /* ACE_LACKS_WCSTOULL_PROTOTYPE */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_WCHAR_H */ diff --git a/externals/ace/os_include/os_wctype.h b/externals/ace/os_include/os_wctype.h deleted file mode 100644 index 15aa295a677..00000000000 --- a/externals/ace/os_include/os_wctype.h +++ /dev/null @@ -1,45 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_wctype.h - * - * wide-character classification and mapping utilities - * - * $Id: os_wctype.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_WCTYPE_H -#define ACE_OS_INCLUDE_OS_WCTYPE_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -// ctype.h, string.h, stdarg.h, stdio.h, stdlib.h, time.h -#include "ace/os_include/os_wchar.h" - -#if !defined (ACE_LACKS_WCTYPE_H) -# include /**/ -#endif /* !ACE_LACKS_WCTYPE_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_WCTYPE_H */ diff --git a/externals/ace/os_include/os_wordexp.h b/externals/ace/os_include/os_wordexp.h deleted file mode 100644 index 76960076df6..00000000000 --- a/externals/ace/os_include/os_wordexp.h +++ /dev/null @@ -1,44 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_wordexp.h - * - * word-expansion types - * - * $Id: os_wordexp.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_OS_WORDEXP_H -#define ACE_OS_INCLUDE_OS_WORDEXP_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/os_stddef.h" // size_t - -#if !defined (ACE_LACKS_WORDEXP_H) -# include /**/ -#endif /* !ACE_LACKS_WORDEXP_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_OS_WORDEXP_H */ diff --git a/externals/ace/os_include/sys/os_ipc.h b/externals/ace/os_include/sys/os_ipc.h deleted file mode 100644 index bea65e5e7d9..00000000000 --- a/externals/ace/os_include/sys/os_ipc.h +++ /dev/null @@ -1,74 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_ipc.h - * - * XSI interprocess communication access structure - * - * $Id: os_ipc.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_SYS_OS_IPC_H -#define ACE_OS_INCLUDE_SYS_OS_IPC_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_types.h" - -#if !defined (ACE_LACKS_SYS_IPC_H) -# include /**/ -#endif /* !ACE_LACKS_SYS_IPC_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#if defined (ACE_WIN32) -# define ACE_INVALID_SEM_KEY 0 -#else /* !ACE_WIN32 */ -# define ACE_INVALID_SEM_KEY -1 -#endif /* ACE_WIN32 */ - -#if !defined (IPC_PRIVATE) -# define IPC_PRIVATE ACE_INVALID_SEM_KEY -#endif /* IPC_PRIVATE */ - -#if !defined (IPC_STAT) -# define IPC_STAT 0 -#endif /* IPC_STAT */ - -#if !defined (IPC_CREAT) -# define IPC_CREAT 0 -#endif /* IPC_CREAT */ - -#if !defined (IPC_NOWAIT) -# define IPC_NOWAIT 0 -#endif /* IPC_NOWAIT */ - -#if !defined (IPC_RMID) -# define IPC_RMID 0 -#endif /* IPC_RMID */ - -#if !defined (IPC_EXCL) -# define IPC_EXCL 0 -#endif /* IPC_EXCL */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_SYS_OS_IPC_H */ diff --git a/externals/ace/os_include/sys/os_loadavg.h b/externals/ace/os_include/sys/os_loadavg.h deleted file mode 100644 index 6eeeb69be0a..00000000000 --- a/externals/ace/os_include/sys/os_loadavg.h +++ /dev/null @@ -1,41 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_loadavg.h - * - * loadavg functions - * - * $Id: os_loadavg.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Johnny Willemsen - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_SYS_OS_LOADAVG_H -#define ACE_OS_INCLUDE_SYS_OS_LOADAVG_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_SYS_LOADAVG_H) -# include /**/ -#endif /* ACE_HAS_SYS_LOADAVG_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_SYS_OS_LOADAVG_H */ diff --git a/externals/ace/os_include/sys/os_mman.h b/externals/ace/os_include/sys/os_mman.h deleted file mode 100644 index b39fc48cbc4..00000000000 --- a/externals/ace/os_include/sys/os_mman.h +++ /dev/null @@ -1,122 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_mman.h - * - * memory management declarations - * - * $Id: os_mman.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_SYS_OS_MMAN_H -#define ACE_OS_INCLUDE_SYS_OS_MMAN_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_types.h" - -#if defined (ACE_LACKS_MMAP) -# define ACE_LACKS_SYS_MMAN_H -#endif /* ACE_LACKS_MMAP */ - -#if !defined (ACE_LACKS_SYS_MMAN_H) - // Fixes a problem with HP/UX. -# if defined (ACE_HAS_BROKEN_MMAP_H) - extern "C" { -# endif /* ACE_HAS_BROKEN_MMAP_H */ -# include /**/ -# if defined (ACE_HAS_BROKEN_MMAP_H) - } -# endif /* ACE_HAS_BROKEN_MMAP_H */ -#endif /* ACE_LACKS_SYS_MMAN_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#if defined (ACE_LACKS_SYS_MMAN_H) && !defined (ACE_WIN32) -# define PROT_READ 0 -# define PROT_WRITE 0 -# define PROT_EXEC 0 -# define PROT_NONE 0 -# define PROT_RDWR 0 -# define MAP_PRIVATE 0 -# define MAP_SHARED 0 -# define MAP_FIXED 0 -#elif defined (ACE_WIN32) - // These two may be used for internal flags soon: -# define MAP_PRIVATE 1 -# define MAP_SHARED 2 -# define MAP_FIXED 4 - // MMAP flags -# define PROT_READ PAGE_READONLY -# define PROT_WRITE PAGE_READWRITE -# define PROT_RDWR PAGE_READWRITE -/* If we can find suitable use for these flags, here they are: -PAGE_WRITECOPY -PAGE_EXECUTE -PAGE_EXECUTE_READ -PAGE_EXECUTE_READWRITE -PAGE_EXECUTE_WRITECOPY -PAGE_GUARD -PAGE_NOACCESS -PAGE_NOCACHE */ -#endif /* !ACE_LACKS_SYS_MMAN_H && !ACE_WIN32*/ - -# if !defined (ACE_MAP_PRIVATE) -# define ACE_MAP_PRIVATE MAP_PRIVATE -# endif /* ! ACE_MAP_PRIVATE */ - -# if !defined (ACE_MAP_SHARED) -# define ACE_MAP_SHARED MAP_SHARED -# endif /* ! ACE_MAP_SHARED */ - -# if !defined (ACE_MAP_FIXED) -# define ACE_MAP_FIXED MAP_FIXED -# endif /* ! ACE_MAP_FIXED */ - -# if !defined (MAP_FAILED) || defined (ACE_HAS_BROKEN_MAP_FAILED) -# undef MAP_FAILED -# define MAP_FAILED ((void *) -1) -# elif defined (ACE_HAS_LONG_MAP_FAILED) -# undef MAP_FAILED -# define MAP_FAILED ((void *) -1L) -# endif /* !MAP_FAILED || ACE_HAS_BROKEN_MAP_FAILED */ - -#if !defined (PROT_RDWR) -# define PROT_RDWR (PROT_READ|PROT_WRITE) -#endif /* PROT_RDWR */ - -# if defined (ACE_WIN32) - // Needed to map calls to NT transparently. -# define MS_ASYNC 0 -# define MS_INVALIDATE 0 -# endif /* ACE_WIN32 */ - -# if !defined (MS_SYNC) -# define MS_SYNC 0x0 -# endif /* !MS_SYNC */ - -#if !defined (ACE_LACKS_MADVISE) && defined (ACE_LACKS_MADVISE_PROTOTYPE) - extern "C" int madvise(caddr_t, size_t, int); -#endif /* !ACE_LACKS_MADVISE && ACE_LACKS_MADVISE_PROTOTYPE */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_SYS_OS_MMAN_H */ diff --git a/externals/ace/os_include/sys/os_msg.h b/externals/ace/os_include/sys/os_msg.h deleted file mode 100644 index fa7edad1eb1..00000000000 --- a/externals/ace/os_include/sys/os_msg.h +++ /dev/null @@ -1,55 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_msg.h - * - * XSI message queue structures - * - * $Id: os_msg.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_SYS_OS_MSG_H -#define ACE_OS_INCLUDE_SYS_OS_MSG_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_ipc.h" - -#if !defined (ACE_LACKS_SYS_MSG_H) -# include /**/ -#endif /* !ACE_LACKS_SYS_MSG_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - - // Declare opaque type. Needed for ACE_OS wrappers on systems - // without SysV IPC. - struct msqid_ds; - -#if defined (ACE_LACKS_SYSV_MSQ_PROTOS) - int msgget (key_t, int); - int msgrcv (int, void *, size_t, long, int); - int msgsnd (int, const void *, size_t, int); - int msgctl (int, int, struct msqid_ds *); -#endif /* ACE_LACKS_SYSV_MSQ_PROTOS */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_SYS_OS_MSG_H */ diff --git a/externals/ace/os_include/sys/os_pstat.h b/externals/ace/os_include/sys/os_pstat.h deleted file mode 100644 index dcb3467b623..00000000000 --- a/externals/ace/os_include/sys/os_pstat.h +++ /dev/null @@ -1,42 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_pstat.h - * - * pstat functions - * - * $Id: os_pstat.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Johnny Willemsen - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_SYS_OS_PSTAT_H -#define ACE_OS_INCLUDE_SYS_OS_PSTAT_H - -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_SYS_PSTAT_H) -# include /**/ -# include /**/ -#endif /* ACE_HAS_SYS_PSTAT_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_SYS_OS_PSTAT_H */ diff --git a/externals/ace/os_include/sys/os_resource.h b/externals/ace/os_include/sys/os_resource.h deleted file mode 100644 index 23486b616e2..00000000000 --- a/externals/ace/os_include/sys/os_resource.h +++ /dev/null @@ -1,104 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_resource.h - * - * definitions for XSI resource operations - * - * $Id: os_resource.h 81697 2008-05-14 18:33:11Z johnnyw $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_SYS_OS_RESOURCE_H -#define ACE_OS_INCLUDE_SYS_OS_RESOURCE_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_time.h" -#include "ace/os_include/sys/os_types.h" - -#if !defined (ACE_LACKS_SYS_RESOURCE_H) -# include /**/ -#endif /* !ACE_LACKS_SYS_RESOURCE_H */ - -#if defined (ACE_HAS_SYS_SYSTEMINFO_H) -# include /**/ -#endif /* ACE_HAS_SYS_SYSTEMINFO_H */ - -#if defined (ACE_HAS_SYS_SYSCALL_H) -# include /**/ -#endif /* ACE_HAS_SYS_SYSCALL_H */ - -// prusage_t is defined in -#if defined (ACE_HAS_PROC_FS) -# include /**/ -#endif /* ACE_HAS_PROC_FS */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -// There must be a better way to do this... -#if !defined (RLIMIT_NOFILE) && !defined (ACE_LACKS_RLIMIT_NOFILE) -# if defined (linux) || defined (AIX) || defined (SCO) -# if defined (RLIMIT_OFILE) -# define RLIMIT_NOFILE RLIMIT_OFILE -# else -# define RLIMIT_NOFILE 200 -# endif /* RLIMIT_OFILE */ -# endif /* defined (linux) || defined (AIX) || defined (SCO) */ -#endif /* RLIMIT_NOFILE */ - -#if defined (ACE_WIN32) -# define RUSAGE_SELF 1 - /// Fake the UNIX rusage structure. Perhaps we can add more to this - /// later on? - struct rusage - { - FILETIME ru_utime; - FILETIME ru_stime; - }; -#endif /* ACE_WIN32 */ - -#if defined (ACE_LACKS_RLIMIT_PROTOTYPE) - int getrlimit (int resource, struct rlimit *rlp); - int setrlimit (int resource, const struct rlimit *rlp); -#endif /* ACE_LACKS_RLIMIT_PROTOTYPE */ - -#if defined (ACE_HAS_PRUSAGE_T) - typedef prusage_t ACE_Rusage; -#elif defined (ACE_HAS_GETRUSAGE) - typedef rusage ACE_Rusage; -#else - typedef int ACE_Rusage; -#endif /* ACE_HAS_PRUSAGE_T */ - -#if !defined (ACE_WIN32) -// These prototypes are chronically lacking from many versions of UNIX. -# if !defined (ACE_HAS_GETRUSAGE_PROTOTYPE) - int getrusage (int who, struct rusage *rusage); -# endif /* ! ACE_HAS_GETRUSAGE_PROTOTYPE */ - -# if defined (ACE_LACKS_SYSCALL) - int syscall (int, ACE_HANDLE, struct rusage *); -# endif /* ACE_LACKS_SYSCALL */ -#endif /* !ACE_WIN32 */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_SYS_OS_RESOURCE_H */ diff --git a/externals/ace/os_include/sys/os_select.h b/externals/ace/os_include/sys/os_select.h deleted file mode 100644 index 59473aff398..00000000000 --- a/externals/ace/os_include/sys/os_select.h +++ /dev/null @@ -1,61 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_select.h - * - * select types - * - * $Id: os_select.h 85015 2009-04-03 12:27:59Z johnnyw $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_SYS_OS_SELECT_H -#define ACE_OS_INCLUDE_SYS_OS_SELECT_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_time.h" -#include "ace/os_include/os_signal.h" -#include "ace/os_include/os_unistd.h" - -#if !defined (ACE_LACKS_SYS_SELECT_H) -# include /**/ -#endif /* !ACE_LACKS_SYS_SELECT_H */ - -#if defined (ACE_USES_SELECTLIB_H) && defined (ACE_LACKS_SYS_SELECT_H) -# include /**/ -#endif /* ACE_USES_SELECTLIB_H && ACE_LACKS_SYS_SELECT_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#if defined (ACE_LACKS_FD_MASK) - typedef long fd_mask; -#endif /* __QNX__ */ - -#if defined (ACE_WIN32) - // This will help until we figure out everything: -# define NFDBITS 32 /* only used in unused functions... */ -#elif defined (ACE_LACKS_NFDBITS) -# define NFDBITS (sizeof(fd_mask) * NBBY) /* bits per mask */ -#endif /* ACE_WIN32 */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_SYS_OS_SELECT_H */ diff --git a/externals/ace/os_include/sys/os_sem.h b/externals/ace/os_include/sys/os_sem.h deleted file mode 100644 index 926092b7d06..00000000000 --- a/externals/ace/os_include/sys/os_sem.h +++ /dev/null @@ -1,90 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_sem.h - * - * XSI semaphore facility - * - * $Id: os_sem.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_SYS_OS_SEM_H -#define ACE_OS_INCLUDE_SYS_OS_SEM_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_ipc.h" - -#if !defined (ACE_LACKS_SYS_SEM_H) -# include /**/ -#endif /* !ACE_LACKS_SYS_SEM_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -# if !defined (GETVAL) -# define GETVAL 0 -# endif /* GETVAL */ - -# if !defined (SETVAL) -# define SETVAL 0 -# endif /* SETVAL */ - -# if !defined (GETALL) -# define GETALL 0 -# endif /* GETALL */ - -# if !defined (SETALL) -# define SETALL 0 -# endif /* SETALL */ - -# if !defined (SEM_UNDO) -# define SEM_UNDO 0 -# endif /* SEM_UNDO */ - -#if defined (ACE_LACKS_SEMBUF_T) - struct sembuf - { - /// semaphore # - unsigned short sem_num; - - /// semaphore operation - short sem_op; - - /// operation flags - short sem_flg; - }; -#endif /* ACE_LACKS_SEMBUF_T */ - -#if !defined (ACE_HAS_SEMUN) || (defined (__GLIBC__) && defined (_SEM_SEMUN_UNDEFINED)) - union semun - { - /// value for SETVAL - int val; - /// buffer for IPC_STAT & IPC_SET - struct semid_ds *buf; - /// array for GETALL & SETALL - u_short *array; - }; -#endif /* !ACE_HAS_SEMUN || (defined (__GLIBC__) && defined (_SEM_SEMUN_UNDEFINED)) */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_SYS_OS_SEM_H */ diff --git a/externals/ace/os_include/sys/os_shm.h b/externals/ace/os_include/sys/os_shm.h deleted file mode 100644 index 79d502fec0d..00000000000 --- a/externals/ace/os_include/sys/os_shm.h +++ /dev/null @@ -1,48 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_shm.h - * - * XSI shared memory facility - * - * $Id: os_shm.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_SYS_OS_SHM_H -#define ACE_OS_INCLUDE_SYS_OS_SHM_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_ipc.h" - -#if !defined (ACE_LACKS_SYS_SHM_H) -# include /**/ -#endif /* !ACE_LACKS_SYS_SHM_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - - // Declare opaque type. Needed for ACE_OS wrappers on systems - // without SysV IPC. - struct shmid_ds; - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_SYS_OS_SHM_H */ diff --git a/externals/ace/os_include/sys/os_socket.h b/externals/ace/os_include/sys/os_socket.h deleted file mode 100644 index 676041747ba..00000000000 --- a/externals/ace/os_include/sys/os_socket.h +++ /dev/null @@ -1,307 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_socket.h - * - * main sockets header - * - * $Id: os_socket.h 85015 2009-04-03 12:27:59Z johnnyw $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_SYS_OS_SOCKET_H -#define ACE_OS_INCLUDE_SYS_OS_SOCKET_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_uio.h" - -#if !defined (ACE_LACKS_SYS_SOCKET_H) -# include /**/ -#endif /* !ACE_LACKS_SYS_SOCKET_H */ - -#if defined (ACE_USES_SOCKLIB_H) -# include /**/ -#endif /* ACE_USES_SOCKLIB_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#if !defined (ACE_HAS_MSG) && !defined (SCO) - struct msghdr {}; -#endif /* ACE_HAS_MSG */ - -#if defined (ACE_HAS_MSG) && defined (ACE_LACKS_MSG_ACCRIGHTS) -# if !defined (msg_accrights) -# undef msg_control -# define msg_accrights msg_control -# endif /* ! msg_accrights */ - -# if !defined (msg_accrightslen) -# undef msg_controllen -# define msg_accrightslen msg_controllen -# endif /* ! msg_accrightslen */ -#endif /* ACE_HAS_MSG && ACE_LACKS_MSG_ACCRIGHTS */ - -# if defined (ACE_LACKS_SOCKADDR) - struct sockaddr { - u_char sa_len; /* total length */ - u_char sa_family; /* address family */ - char sa_data[14]; /* actually longer; address value */ - }; -# endif /* ACE_LACKS_SOCKADDR */ - -# if defined (ACE_LACKS_LINGER) - struct linger { - int l_onoff; /* option on/off */ - int l_linger; /* linger time */ - }; -# endif /* ACE_LACKS_LINGER */ - -#if defined (ACE_WIN32) - struct msghdr - { - /// Optional address - sockaddr * msg_name; - - /// Size of address - int msg_namelen; - - /// Scatter/gather array - iovec *msg_iov; - - /// # elements in msg_iov - int msg_iovlen; - - /// Access rights sent/received - caddr_t msg_accrights; - - int msg_accrightslen; - }; -#endif /* ACE_WIN32 */ - -#if defined (ACE_HAS_4_4BSD_SENDMSG_RECVMSG) - // Control message size to pass a file descriptor. -# define ACE_BSD_CONTROL_MSG_LEN sizeof (struct cmsghdr) + sizeof (ACE_HANDLE) -#endif /* ACE_HAS_4_4BSD_SENDMSG_RECVMSG */ - -// Increase the range of "address families". Please note that this -// must appear _after_ the include of sys/socket.h, for the AF_FILE -// definition on Linux/glibc2. -#if !defined (AF_ANY) -# define AF_ANY (-1) -#endif /* AF_ANY */ - -#if !defined (AF_UNSPEC) -# define AF_UNSPEC 0 -#endif /* AF_UNSPEC */ - -#if !defined (AF_LOCAL) -# define AF_LOCAL 1 -#endif /* AF_LOCAL */ - -#if !defined (AF_UNIX) -# define AF_UNIX AF_LOCAL -#endif /* AF_UNIX */ - -#if !defined (AF_INET) -# define AF_INET 2 -#endif /* AF_INET */ - -#if !defined (PF_INET) -# define PF_INET AF_INET -#endif /* PF_INET */ - -#if !defined (PF_LOCAL) -# define PF_LOCAL AF_LOCAL -#endif /* PF_LOCAL */ - -#if !defined (PF_UNIX) -# define PF_UNIX PF_LOCAL -#endif /* PF_UNIX */ - -#if !defined (AF_MAX) -# define AF_MAX 29 -#endif /* AF_MAX */ - -#if !defined (PF_UNSPEC) -# define PF_UNSPEC 0 -#endif /* PF_UNSPEC */ - -#define AF_SPIPE (AF_MAX + 1) -#if !defined (AF_FILE) -# define AF_FILE (AF_MAX + 2) -#endif /* ! AF_FILE */ -#define AF_DEV (AF_MAX + 3) -#define AF_UPIPE (AF_SPIPE) - -#if !defined (MSG_OOB) -# define MSG_OOB 0x1 -#endif /* MSG_OOB */ - -#if !defined (MSG_PEEK) -# define MSG_PEEK 0x2 -#endif /* MSG_PEEK */ - -#if !defined (SOCK_STREAM) -# define SOCK_STREAM 1 -#endif /* SOCK_STREAM */ - -#if !defined (SOCK_DGRAM) -# define SOCK_DGRAM 2 -#endif /* SOCK_DGRAM */ - -#if !defined (SOCK_SEQPACKET) -# define SOCK_SEQPACKET 5 -#endif /* SOCK_SEQPACKET */ - -#if !defined (SOL_SOCKET) -# define SOL_SOCKET 0xffff -#endif /* SOL_SOCKET */ - -#if !defined (SO_REUSEADDR) -# define SO_REUSEADDR 0x0004 -#endif /* SO_REUSEADDR */ - -#if !defined (SO_LINGER) -# define SO_LINGER 0x0080 -#endif /* SO_LINGER */ - -#if !defined (SO_SNDBUF) -# define SO_SNDBUF 0x1001 -#endif /* SO_SNDBUF */ - -#if !defined (SO_RCVBUF) -# define SO_RCVBUF 0x1002 -#endif /* SO_RCVBUF */ - -#if !defined (SO_BROADCAST) -# define SO_BROADCAST 0x0020 -#endif /* SO_BROADCAST */ - -#if !defined (SO_ERROR) -# define SO_ERROR 0x1007 -#endif /* SO_ERROR */ - -#if !defined (SCM_RIGHTS) -# define SCM_RIGHTS 0x01 -#endif /* SCM_RIGHTS */ - -#if defined (ACE_HAS_IPV6) -# if defined (ACE_USES_IPV4_IPV6_MIGRATION) -# define ACE_ADDRESS_FAMILY_INET AF_UNSPEC -# define ACE_PROTOCOL_FAMILY_INET PF_UNSPEC -# else -# define ACE_ADDRESS_FAMILY_INET AF_INET6 -# define ACE_PROTOCOL_FAMILY_INET PF_INET6 -# endif /* ACE_USES_IPV4_IPV6_MIGRATION */ -#else /* !ACE_HAS_IPV6 */ -# define ACE_ADDRESS_FAMILY_INET AF_INET -# define ACE_PROTOCOL_FAMILY_INET PF_INET -#endif /* ACE_HAS_IPV6 */ - -#if !defined (ACE_HAS_SOCK_BUF_SIZE_MAX_VALUE) -#define ACE_HAS_SOCK_BUF_SIZE_MAX_VALUE SSIZE_MAX -#endif /* ACE_HAS_SOCK_BUF_SIZE_MAX_VALUE */ - -#if defined (ACE_HAS_SOCKLEN_T) -# if defined (__hpux) - /* - ** HP-UX supplies the socklen_t type unless some feature set less than - ** _XOPEN_SOURCE_EXTENDED is specifically requested. However, it only - ** actually uses the socklen_t type in supplied socket functions if - ** _XOPEN_SOURCE_EXTENDED is specifically requested. So, for example, - ** the compile options ACE usually uses (includes -mt) cause _HPUX_SOURCE - ** to be set, which sets _INCLUDE_XOPEN_SOURCE_EXTENDED (causing socklen_t - ** to be defined) but _not_ _XOPEN_SOURCE_EXTENDED (causing socket functions - ** to use int, not socklen_t). React to this situation here... - */ -# if defined (_XOPEN_SOURCE_EXTENDED) -typedef socklen_t ACE_SOCKET_LEN; -# else -typedef int ACE_SOCKET_LEN; -# endif /* _XOPEN_SOURCE_EXTENDED */ -# else -typedef socklen_t ACE_SOCKET_LEN; -# endif /* __hpux */ -#elif defined (ACE_HAS_SIZET_SOCKET_LEN) -typedef size_t ACE_SOCKET_LEN; -#else -typedef int ACE_SOCKET_LEN; -#endif /* ACE_HAS_SIZET_SOCKET_LEN */ - -#if defined (ACE_HAS_NETLINK) -# include /**/ -# include /**/ -# define ACE_PROTOCOL_FAMILY_NETLINK AF_NETLINK -#endif - -#if defined (ACE_HAS_LKSCTP) -extern "C" -{ -#include /**/ -#include /**/ -} -#endif /* ACE_HAS_LKSCTP */ - -# if defined (ACE_LACKS_TIMEDWAIT_PROTOTYPES) - - ssize_t recv_timedwait (ACE_HANDLE handle, - char *buf, - int len, - int flags, - struct timespec *timeout); - - ssize_t recvmsg_timedwait (ACE_HANDLE handle, - struct msghdr *msg, - int flags, - struct timespec *timeout); - - ssize_t recvfrom_timedwait (ACE_HANDLE handle, - char *buf, - int len, - int flags, - struct sockaddr *addr, - int *addrlen, - struct timespec *timeout); - - ssize_t send_timedwait (ACE_HANDLE handle, - const char *buf, - int len, - int flags, - struct timespec *timeout); - - ssize_t sendmsg_timedwait (ACE_HANDLE handle, - const struct msghdr *msg, - int flags, - struct timespec *timeout); - - ssize_t sendto_timedwait (ACE_HANDLE handle, - const char *buf, - int len, - int flags, - const struct sockaddr *addr, - int addrlen, - struct timespec *timeout); - -# endif /* ACE_LACKS_TIMEDWAIT_PROTOTYPES */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_SYS_OS_SOCKET_H */ diff --git a/externals/ace/os_include/sys/os_stat.h b/externals/ace/os_include/sys/os_stat.h deleted file mode 100644 index 19b126500c1..00000000000 --- a/externals/ace/os_include/sys/os_stat.h +++ /dev/null @@ -1,157 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_stat.h - * - * data returned by the stat() function - * - * $Id: os_stat.h 85057 2009-04-08 10:59:58Z msmit $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_SYS_OS_STAT_H -#define ACE_OS_INCLUDE_SYS_OS_STAT_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_types.h" - -#if defined (ACE_HAS_DIRECT_H) -# include /**/ -#endif /* ACE_HAS_DIRECT_H */ - -#if !defined (ACE_LACKS_SYS_STAT_H) -# include /**/ -#endif /* !ACE_LACKS_SYS_STAT_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#if defined (ACE_LACKS_MODE_MASKS) -// MODE MASKS - -// the following macros are for POSIX conformance. - -# if !defined (ACE_HAS_USER_MODE_MASKS) -# if !defined (S_IRWXU) -# define S_IRWXU 00700 /* read, write, execute: owner. */ -# endif /* !S_IRWXU */ -# if !defined (S_IRUSR) -# define S_IRUSR 00400 /* read permission: owner. */ -# endif /* !S_IRUSR */ -# if !defined (S_IWUSR) -# define S_IWUSR 00200 /* write permission: owner. */ -# endif /* !S_IWUSR */ -# if !defined (S_IXUSR) -# define S_IXUSR 00100 /* execute permission: owner. */ -# endif /* !S_IXUSR */ -# endif /* ACE_HAS_USER_MODE_MASKS */ - -# if !defined (S_IRWXG) -# define S_IRWXG 00070 -# endif /* S_IRWXG */ -# if !defined (S_IRGRP) -# define S_IRGRP 00040 -# endif /* S_IRGRP */ -# if !defined (S_IWGRP) -# define S_IWGRP 00020 -# endif /* S_IWGRP */ -# if !defined (S_IXGRP) -# define S_IXGRP 00010 -# endif /* S_IXGRP */ -# if !defined (S_IRWXO) -# define S_IRWXO 00007 -# endif /* S_IRWXO */ -# if !defined (S_IROTH) -# define S_IROTH 00004 -# endif /* S_IROTH */ -# if !defined (S_IWOTH) -# define S_IWOTH 00002 -# endif /* S_IWOTH */ -# if !defined (S_IXOTH) -# define S_IXOTH 00001 -# endif /* S_IXOTH */ - -// WinCE's S_IFLNK is defined with the other bits, below. -#if !defined (S_IFLNK) && !defined (ACE_HAS_WINCE) -#define S_IFLNK 0200000 -#endif /* S_IFLNK && !ACE_HAS_WINCE */ - -#endif /* ACE_LACKS_MODE_MASKS */ - -// Some systems (VxWorks) don't define S_ISLNK -#if !defined (S_ISLNK) -# if defined (S_IFLNK) -# define S_ISLNK(mode) (((mode)&S_IFLNK) == S_IFLNK) -# else -# define S_ISLNK(mode) 0 -# endif /* S_IFLNK */ -#endif /* S_ISLNK */ - -#if defined (ACE_HAS_WINCE) - -// Translate the WinCE bits into names expected by our callers. -// The dwFileAttributes parameter doesn't have protection info, so -// S_IFMT is the whole thing. Since there are no symbolic links, S_IFLNK is 0. -# define S_IFMT 0xFFFF -# define S_IFDIR FILE_ATTRIBUTE_DIRECTORY -# define S_IFREG FILE_ATTRIBUTE_NORMAL -# define S_IFLNK 0 - -# if !defined (__MINGW32__) - // Since CE does not have _stat by default as NT/2000 does, the 'stat' - // struct defined here will be used. Also note that CE file system - // struct is only for the CE 3.0 or later. - // Refer to the WCHAR.H from Visual C++ and WIBASE.H from eVC 3.0. - struct stat - { - /// always 0 on Windows platforms - dev_t st_dev; - - /// always 0 on Windows platforms - dev_t st_rdev; - - /// file attribute - mode_t st_mode; - - /// number of hard links - nlink_t st_nlink; - - /// time of last access - time_t st_atime; - - /// time of last data modification - time_t st_mtime; - - /// time of creation - time_t st_ctime; - - /// file size, in bytes - ACE_OFF_T st_size; - - // Following members do not have direct conversion in Window platforms. - //u_long st_blksize; // optimal blocksize for I/O - //u_long st_flags; // user defined flags for file - }; - #endif -#endif /* ACE_HAS_WINCE */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_SYS_OS_STAT_H */ diff --git a/externals/ace/os_include/sys/os_statvfs.h b/externals/ace/os_include/sys/os_statvfs.h deleted file mode 100644 index 7988c4f5060..00000000000 --- a/externals/ace/os_include/sys/os_statvfs.h +++ /dev/null @@ -1,42 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_statvfs.h - * - * VFS File System information structure - * - * $Id: os_statvfs.h 81692 2008-05-14 12:25:02Z johnnyw $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_SYS_OS_STATVFS_H -#define ACE_OS_INCLUDE_SYS_OS_STATVFS_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_SYS_STATVFS_H) -# include /**/ -#endif /* !ACE_LACKS_SYS_STATVFS_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_SYS_OS_STATVFS_H */ diff --git a/externals/ace/os_include/sys/os_sysctl.h b/externals/ace/os_include/sys/os_sysctl.h deleted file mode 100644 index ee51cd7db65..00000000000 --- a/externals/ace/os_include/sys/os_sysctl.h +++ /dev/null @@ -1,41 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_sysctl.h - * - * declarations for sysctl - * - * $Id: os_sysctl.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Johnny Willemsen - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_SYS_OS_SYSCTL_H -#define ACE_OS_INCLUDE_SYS_OS_SYSCTL_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_SYS_SYSCTL_H) -# include /**/ -#endif /* !ACE_LACKS_SYS_SYSCTL_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_SYS_OS_SYSCTL_H */ diff --git a/externals/ace/os_include/sys/os_sysinfo.h b/externals/ace/os_include/sys/os_sysinfo.h deleted file mode 100644 index 7aca1f44d1f..00000000000 --- a/externals/ace/os_include/sys/os_sysinfo.h +++ /dev/null @@ -1,39 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_sysinfo.h - * - * $Id: os_sysinfo.h 81692 2008-05-14 12:25:02Z johnnyw $ - * - * @author Johnny Willemsen - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_SYS_OS_SYSINFO_H -#define ACE_OS_INCLUDE_SYS_OS_SYSINFO_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if defined (ACE_HAS_SYS_SYSINFO_H) -# include /**/ -#endif /* ACE_HAS_SYS_SYSINFO_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_SYS_OS_SYSINFO_H */ diff --git a/externals/ace/os_include/sys/os_time.h b/externals/ace/os_include/sys/os_time.h deleted file mode 100644 index 937ceebaa13..00000000000 --- a/externals/ace/os_include/sys/os_time.h +++ /dev/null @@ -1,56 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_time.h - * - * time types - * - * $Id: os_time.h 85365 2009-05-18 08:27:42Z johnnyw $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_SYS_OS_TIME_H -#define ACE_OS_INCLUDE_SYS_OS_TIME_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_types.h" - -#if !defined (ACE_LACKS_SYS_TIME_H) -# include /**/ -#endif /* !ACE_LACKS_SYS_TIME_H */ - -#if defined (ACE_VXWORKS) && (ACE_VXWORKS == 0x620) -# include /**/ // VxWorks 6.2 defined timeval in time.h -#endif - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#if defined (ACE_HAS_SVR4_GETTIMEOFDAY) - int gettimeofday (struct timeval *tp, void * = 0); -#elif defined (ACE_HAS_OSF1_GETTIMEOFDAY) - int gettimeofday (struct timeval *tp, struct timezone * = 0); -#elif defined (ACE_HAS_VOIDPTR_GETTIMEOFDAY) -# define ACE_HAS_SVR4_GETTIMEOFDAY -#endif /* ACE_HAS_SVR4_GETTIMEOFDAY */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_SYS_OS_TIME_H */ diff --git a/externals/ace/os_include/sys/os_timeb.h b/externals/ace/os_include/sys/os_timeb.h deleted file mode 100644 index cf10566ed99..00000000000 --- a/externals/ace/os_include/sys/os_timeb.h +++ /dev/null @@ -1,44 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_timeb.h - * - * additional definitions for date and time - * - * $Id: os_timeb.h 83306 2008-10-17 12:19:53Z johnnyw $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_SYS_OS_TIMEB_H -#define ACE_OS_INCLUDE_SYS_OS_TIMEB_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_types.h" - -#if !defined (ACE_LACKS_SYS_TIMEB_H) -# include /**/ -#endif /* !ACE_LACKS_SYS_TIMEB_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_SYS_OS_TIMEB_H */ diff --git a/externals/ace/os_include/sys/os_times.h b/externals/ace/os_include/sys/os_times.h deleted file mode 100644 index 617b416ec56..00000000000 --- a/externals/ace/os_include/sys/os_times.h +++ /dev/null @@ -1,44 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_times.h - * - * file access and modification times structure - * - * $Id: os_times.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_SYS_OS_TIMES_H -#define ACE_OS_INCLUDE_SYS_OS_TIMES_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_types.h" - -#if !defined (ACE_LACKS_SYS_TIMES_H) -# include /**/ -#endif /* !ACE_LACKS_SYS_TIMES_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_SYS_OS_TIMES_H */ diff --git a/externals/ace/os_include/sys/os_types.h b/externals/ace/os_include/sys/os_types.h deleted file mode 100644 index 9638265378d..00000000000 --- a/externals/ace/os_include/sys/os_types.h +++ /dev/null @@ -1,157 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_types.h - * - * data types - * - * $Id: os_types.h 88515 2010-01-13 08:47:38Z johnnyw $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_SYS_OS_TYPES_H -#define ACE_OS_INCLUDE_SYS_OS_TYPES_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/os_stddef.h" - -#if !defined (ACE_LACKS_SYS_TYPES_H) -# include /**/ -#endif /* !ACE_LACKS_SYS_TYPES_H */ - -#if defined (ACE_HAS_TYPES_H) -# include /**/ -#endif /* ACE_HAS_TYPES_H */ - -# if defined (ACE_USES_STD_NAMESPACE_FOR_STDC_LIB) && \ - (ACE_USES_STD_NAMESPACE_FOR_STDC_LIB != 0) -using std::time_t; -# endif /* ACE_USES_STD_NAMESPACE_FOR_STDC_LIB */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -typedef double ACE_timer_t; - -// todo: don't forget to clean this up! ;-) -#if !defined (ACE_HAS_CLOCK_GETTIME) && !(defined (_CLOCKID_T_) || defined (_CLOCKID_T)) - typedef int clockid_t; -# if !defined (CLOCK_REALTIME) -# define CLOCK_REALTIME 0 -# endif /* CLOCK_REALTIME */ -#endif /* ! ACE_HAS_CLOCK_GETTIME && ! _CLOCKID_T_ */ - -#if defined (ACE_LACKS_DEV_T) - typedef unsigned int dev_t; -#endif /* ACE_LACKS_DEV_T */ - -#if defined (ACE_HAS_WINCE) - typedef long off_t; -#endif - -#if defined(ACE_WIN32) && defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS==64) - typedef __int64 ACE_OFF_T; -#else - typedef off_t ACE_OFF_T; -#endif - -#if defined (ACE_SIZEOF_LONG) && ACE_SIZEOF_LONG == 8 - typedef off_t ACE_LOFF_T; -#elif defined (ACE_HAS_RTEMS) || defined (__FreeBSD__) || defined (__NetBSD__) || defined (__OpenBSD__) || defined (__APPLE__) || defined(ACE_MVS) || defined(__INTERIX) || \ - (defined (ACE_OPENVMS) && defined (_LARGEFILE)) - typedef off_t ACE_LOFF_T; -#elif defined (__sgi) || defined (AIX) || defined (HPUX) || defined (__QNX__) - typedef off64_t ACE_LOFF_T; -#elif defined (__sun) - typedef offset_t ACE_LOFF_T; -#elif defined (WIN32) - typedef __int64 ACE_LOFF_T; -#elif (defined (ACE_VXWORKS) && (ACE_VXWORKS <= 0x680)) || \ - defined (ACE_LYNXOS_MAJOR) || \ - (defined (ACE_OPENVMS) && !defined (_LARGEFILE)) || \ - defined (__TANDEM) - typedef long long ACE_LOFF_T; -#else - typedef loff_t ACE_LOFF_T; -#endif - -#if defined (ACE_LACKS_UID_T) -typedef long uid_t; -#endif /* ACE_LACKS_UID_T */ - -#if defined (ACE_LACKS_GID_T) -typedef long gid_t; -#endif /* ACE_LACKS_GID_T */ - -#if defined (ACE_LACKS_CADDR_T) -typedef char *caddr_t; -#endif /* ACE_LACKS_CADDR_T */ - -#if defined (ACE_LACKS_MODE_T) -typedef u_short mode_t; -#endif /* ACE_LACKS_MODE_T */ - -#if defined (ACE_LACKS_NLINK_T) -typedef DWORD nlink_t; -#endif /* ACE_LACKS_NLINK_T */ - -#if defined (ACE_LACKS_KEY_T) -# if defined (ACE_WIN32) - // Win32 doesn't use numeric values to name its semaphores, it uses - // strings! - typedef char *key_t; -# else - typedef int key_t; -# endif /* ACE_WIN32 */ -#endif /* ACE_LACKS_KEY_T */ - -#if !defined (ACE_HAS_SSIZE_T) -# if defined (ACE_WIN64) - typedef SSIZE_T ssize_t; -# else - typedef int ssize_t; -# endif /* ACE_WIN64 */ -#endif /* ACE_HAS_SSIZE_T */ - -#if defined (ACE_WIN32) - typedef DWORD ACE_exitcode; -#else - typedef int ACE_exitcode; -#endif /* ACE_WIN32 */ - -#if defined (ACE_LACKS_SUSECONDS_T) - typedef long suseconds_t; -#endif - -#if defined (ACE_LACKS_USECONDS_T) - typedef unsigned long useconds_t; -#endif - -#if defined (ACE_WIN32) && !defined(__MINGW32__) - typedef int pid_t; -#endif /* ACE_WIN32 */ - -# if !defined (ACE_INVALID_PID) -# define ACE_INVALID_PID ((pid_t) -1) -# endif /* ACE_INVALID_PID */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_SYS_OS_TYPES_H */ diff --git a/externals/ace/os_include/sys/os_uio.h b/externals/ace/os_include/sys/os_uio.h deleted file mode 100644 index 7baaec57e75..00000000000 --- a/externals/ace/os_include/sys/os_uio.h +++ /dev/null @@ -1,77 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_uio.h - * - * definitions for vector I/O operations - * - * $Id: os_uio.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_SYS_OS_UIO_H -#define ACE_OS_INCLUDE_SYS_OS_UIO_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_types.h" -#include "ace/os_include/os_limits.h" - -#if !defined (ACE_LACKS_SYS_UIO_H) -# include /**/ -#endif /* !ACE_LACKS_SYS_UIO_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#if defined (ACE_LACKS_IOVEC) - /// The ordering of the fields in this struct is important. It has to - /// match those in WSABUF. - struct iovec - { - /// byte count to read/write - u_long iov_len; - /// data to be read/written - char *iov_base; - - // WSABUF is a Winsock2-only type. -# if defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0) - operator WSABUF &(void) { return *((WSABUF *) this); } -# endif /* defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0) */ - }; -#endif /* ACE_LACKS_IOVEC */ - - -# if defined (ACE_LACKS_TIMEDWAIT_PROTOTYPES) - - ssize_t readv_timedwait (ACE_HANDLE handle, - const iovec *iov, - int iovcnt, - struct timespec* timeout); - - ssize_t writev_timedwait (ACE_HANDLE handle, - const iovec *iov, - int iovcnt, - struct timespec *timeout); - -# endif /* ACE_LACKS_TIMEDWAIT_PROTOTYPES */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_SYS_OS_UIO_H */ diff --git a/externals/ace/os_include/sys/os_un.h b/externals/ace/os_include/sys/os_un.h deleted file mode 100644 index 04a4da0bda9..00000000000 --- a/externals/ace/os_include/sys/os_un.h +++ /dev/null @@ -1,52 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_un.h - * - * definitions for UNIX domain sockets - * - * $Id: os_un.h 85015 2009-04-03 12:27:59Z johnnyw $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_SYS_OS_UN_H -#define ACE_OS_INCLUDE_SYS_OS_UN_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/sys/os_socket.h" - -#if !defined (ACE_LACKS_SYS_UN_H) -# include /**/ -#endif /* !ACE_LACKS_SYS_UN_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#if defined (ACE_LACKS_SOCKADDR_UN) -struct sockaddr_un { - short sun_family; // AF_UNIX. - char sun_path[108]; // path name. -}; -#endif /* ACE_LACKS_SOCKADDR_UN */ - - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_SYS_OS_UN_H */ diff --git a/externals/ace/os_include/sys/os_utsname.h b/externals/ace/os_include/sys/os_utsname.h deleted file mode 100644 index d78d1e3463a..00000000000 --- a/externals/ace/os_include/sys/os_utsname.h +++ /dev/null @@ -1,42 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_utsname.h - * - * system name structure - * - * $Id: os_utsname.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_SYS_OS_UTSNAME_H -#define ACE_OS_INCLUDE_SYS_OS_UTSNAME_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#if !defined (ACE_LACKS_SYS_UTSNAME_H) -# include /**/ -#endif /* !ACE_LACKS_SYS_UTSNAME_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_SYS_OS_UTSNAME_H */ diff --git a/externals/ace/os_include/sys/os_wait.h b/externals/ace/os_include/sys/os_wait.h deleted file mode 100644 index b7a219ac82e..00000000000 --- a/externals/ace/os_include/sys/os_wait.h +++ /dev/null @@ -1,97 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file os_wait.h - * - * declarations for waiting - * - * $Id: os_wait.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Don Hinton - * @author This code was originally in various places including ace/OS.h. - */ -//============================================================================= - -#ifndef ACE_OS_INCLUDE_SYS_OS_WAIT_H -#define ACE_OS_INCLUDE_SYS_OS_WAIT_H - -#include /**/ "ace/pre.h" - -#include "ace/config-lite.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -#include "ace/os_include/os_signal.h" -#include "ace/os_include/sys/os_resource.h" - -#if !defined (ACE_LACKS_SYS_WAIT_H) -# include /**/ -#endif /* !ACE_LACKS_SYS_WAIT_H */ - -// Place all additions (especially function declarations) within extern "C" {} -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - - // Wrapping around wait status macros for platforms that - // lack them. - -# if !defined (WCOREDUMP) -# define WCOREDUMP(stat) 0 -# endif /* WCOREDUMP */ - -# if !defined (WNOHANG) -# define WNOHANG 0100 -# endif /* !WNOHANG */ - - // If the value of WIFEXITED(stat) is non-zero, this macro evaluates - // to the exit code that the child process exit(3C), or the value - // that the child process returned from main. Peaceful exit code is - // 0. -# if !defined (WEXITSTATUS) -# define WEXITSTATUS(stat) stat -# endif /* WEXITSTATUS */ - -# if !defined (WIFCONTINUED) -# define WIFCONTINUED(stat) 0 -# endif /* WIFCONTINUED */ - - // Evaluates to a non-zero value if status was returned for a child - // process that terminated normally. 0 means status wasn't - // returned. -# if !defined (WIFEXITED) -# define WIFEXITED(stat) 1 -# endif /* WIFEXITED */ - - // Evaluates to a non-zero value if status was returned for a child - // process that terminated due to the receipt of a signal. 0 means - // status wasnt returned. -# if !defined (WIFSIGNALED) -# define WIFSIGNALED(stat) 0 -# endif /* WIFSIGNALED */ - -# if !defined (WIFSTOPPED) -# define WIFSTOPPED(stat) 0 -# endif /* WIFSTOPPED */ - -# if !defined (WSTOPSIG) -# define WSTOPSIG(stat) 0 -# endif /* WSTOPSIG */ - - // If the value of WIFSIGNALED(stat) is non-zero, this macro - // evaluates to the number of the signal that caused the - // termination of the child process. -# if !defined (WTERMSIG) -# define WTERMSIG(stat) 0 -# endif /* WTERMSIG */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#include /**/ "ace/post.h" -#endif /* ACE_OS_INCLUDE_SYS_OS_WAIT_H */ diff --git a/externals/ace/post.h b/externals/ace/post.h deleted file mode 100644 index c393dfe50aa..00000000000 --- a/externals/ace/post.h +++ /dev/null @@ -1,22 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file post.h - * - * $Id: post.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Christopher Kohlhoff - * - * This file restores the original alignment rules. - */ -//============================================================================= - -// No header guard -#if defined (_MSC_VER) -# pragma pack (pop) -#elif defined (__BORLANDC__) -# pragma option pop -# pragma nopushoptwarn -# pragma nopackwarning -#endif diff --git a/externals/ace/pre.h b/externals/ace/pre.h deleted file mode 100644 index 7cc32d8ff30..00000000000 --- a/externals/ace/pre.h +++ /dev/null @@ -1,24 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file pre.h - * - * $Id: pre.h 80826 2008-03-04 14:51:23Z wotte $ - * - * @author Christopher Kohlhoff - * - * This file saves the original alignment rules and changes the alignment - * boundary to ACE's default. - */ -//============================================================================= - -// No header guard -#if defined (_MSC_VER) -# pragma warning (disable:4103) -# pragma pack (push, 8) -#elif defined (__BORLANDC__) -# pragma option push -a8 -b -Ve- -Vx- -w-rvl -w-rch -w-ccc -w-obs -w-aus -w-pia -w-inl -w-sig -# pragma nopushoptwarn -# pragma nopackwarning -#endif diff --git a/externals/ace/streams.h b/externals/ace/streams.h deleted file mode 100644 index 396a67c712e..00000000000 --- a/externals/ace/streams.h +++ /dev/null @@ -1,138 +0,0 @@ -// -*- C++ -*- - -//============================================================================= -/** - * @file streams.h - * - * $Id: streams.h 82445 2008-07-28 13:40:01Z johnnyw $ - * - * @author Irfan Pyarali - * - * This file contains the portability ugliness for the Standard C++ - * Library. As implementations of the "standard" emerge, this file - * will need to be updated. - * - * This files deals with the streams includes. - * - * - */ -//============================================================================= - - -#ifndef ACE_STREAMS_H -#define ACE_STREAMS_H -#include /**/ "ace/pre.h" - -#include /**/ "ace/config-all.h" - -#if !defined (ACE_LACKS_PRAGMA_ONCE) -# pragma once -#endif /* ACE_LACKS_PRAGMA_ONCE */ - -// Do this so the #pragma warning in the MSVC headers do not -// affect our #pragma warning settings -#if defined (_MSC_VER) -#pragma warning(push) -#endif /* _MSC_VER*/ - - -#if !defined (ACE_LACKS_IOSTREAM_TOTALLY) - -# if defined (ACE_HAS_STANDARD_CPP_LIBRARY) && \ - (ACE_HAS_STANDARD_CPP_LIBRARY != 0) - -# if defined (_MSC_VER) -# pragma warning(disable: 4018 4114 4146 4245) -# pragma warning(disable: 4663 4664 4665 4511 4512) -# endif /* _MSC_VER */ - -# if defined (ACE_USES_OLD_IOSTREAMS) -# include /**/ -# include /**/ - // This has been commented as it is not needed and causes problems with Qt. - // (brunsch) But has been uncommented since it should be included. Qt - // probably should have some sort of macro that will prevent including this - // when it is used. -# include /**/ -# else -# include /**/ -# include /**/ -# include /**/ -# include /**/ -# include /**/ -# include /**/ -# include /**/ -# endif /* ACE_USES_OLD_IOSTREAMS */ - -# if defined (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB) && \ - (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB != 0) - -# if !defined (ACE_USES_OLD_IOSTREAMS) - // Make these available in the global name space - using std::ios; - using std::ios_base; - using std::streambuf; - using std::istream; - using std::ostream; - using std::iostream; - using std::filebuf; - using std::ifstream; - using std::ofstream; - using std::fstream; - - using std::cin; - using std::cout; - using std::cerr; - using std::clog; - - using std::endl; - using std::ends; - using std::flush; - - using std::ws; - - using std::resetiosflags; - using std::setfill; - using std::setiosflags; - using std::setprecision; - using std::setw; - - using std::dec; - using std::hex; - using std::oct; -# endif /* ! ACE_USES_OLD_IOSTREAMS */ - -# endif /* ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB */ - -# if defined (_MSC_VER) -# pragma warning(4: 4018 4114 4146 4245) -# pragma warning(4: 4663 4664 4665 4512 4511) -# endif /* _MSC_VER */ - -# else /* ! ACE_HAS_STANDARD_CPP_LIBRARY */ - -# include /**/ -# include /**/ -# include /**/ - -# if defined (ACE_WIN32) && !defined(__MINGW32__) -# if defined(_MSC_VER) // VSB -# include /**/ -# include /**/ -# include /**/ -# include /**/ -# endif /* _MSC_VER */ -# endif /* ACE_WIN32 && !__MINGW32__ */ - -# endif /* ! ACE_HAS_STANDARD_CPP_LIBRARY */ - -#endif /* ! ACE_LACKS_IOSTREAM_TOTALLY */ - -// Do this so the #pragma warning in the MSVC headers do not -// affect our #pragma warning settings -#if defined (_MSC_VER) -#pragma warning(pop) -#endif /* _MSC_VER */ - -#include /**/ "ace/post.h" -#endif /* ACE_STREAMS_H */ diff --git a/externals/ace/svc_export.h b/externals/ace/svc_export.h deleted file mode 100644 index 18cf3a24c35..00000000000 --- a/externals/ace/svc_export.h +++ /dev/null @@ -1,44 +0,0 @@ -// -*- C++ -*- -// $Id: svc_export.h 84495 2009-02-17 17:44:31Z johnnyw $ -// Definition for Win32 Export directives. - -// This file was generated by generate_export_file.pl -// but needed to be altered to support ACE_BUILD_SVC_DLL -// instead of ACE_SVC_BUILD_DLL which was already being -// used. - -// ------------------------------ -#if !defined (ACE_SVC_EXPORT_H) -#define ACE_SVC_EXPORT_H - -#include /**/ "ace/config-all.h" - -#if defined (ACE_AS_STATIC_LIBS) && !defined (ACE_SVC_HAS_DLL) -# define ACE_SVC_HAS_DLL 0 -#endif /* ACE_AS_STATIC_LIBS && ACE_SVC_HAS_DLL */ - -#if !defined (ACE_SVC_HAS_DLL) -#define ACE_SVC_HAS_DLL 1 -#endif /* ! ACE_SVC_HAS_DLL */ - -#if defined (ACE_SVC_HAS_DLL) -# if (ACE_SVC_HAS_DLL == 1) -# if defined (ACE_BUILD_SVC_DLL) || defined (ACE_SVC_BUILD_DLL) -# define ACE_Svc_Export ACE_Proper_Export_Flag -# define ACE_SVC_SINGLETON_DECLARATION(T) ACE_EXPORT_SINGLETON_DECLARATION (T) -# else -# define ACE_Svc_Export ACE_Proper_Import_Flag -# define ACE_SVC_SINGLETON_DECLARATION(T) ACE_IMPORT_SINGLETON_DECLARATION (T) -# endif /* ACE_BUILD_SVC_DLL */ -# else -# define ACE_Svc_Export -# define ACE_SVC_SINGLETON_DECLARATION(T) -# endif /* ! ACE_SVC_HAS_DLL == 1 */ -#else -# define ACE_Svc_Export -# define ACE_SVC_SINGLETON_DECLARATION(T) -#endif /* ACE_SVC_HAS_DLL */ - -#endif /* ACE_SVC_EXPORT_H */ - -// End of auto generated file. diff --git a/externals/bzip2/CMakeLists.txt b/externals/bzip2/CMakeLists.txt deleted file mode 100644 index 3de5475610a..00000000000 --- a/externals/bzip2/CMakeLists.txt +++ /dev/null @@ -1,22 +0,0 @@ -# Copyright (C) 2008-2010 Trinity -# -# This file is free software; as a special exception the author gives -# unlimited permission to copy and/or distribute it, with or without -# modifications, as long as this notice is preserved. -# -# This program is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the -# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -file(GLOB sources *.c) - -set(bzip2_STAT_SRCS - ${sources} -) - -include_directories( - ${CMAKE_SOURCE_DIR}/externals/zlib - ${CMAKE_CURRENT_SOURCE_DIR} -) - -add_library(bzip2 STATIC ${bzip2_STAT_SRCS}) diff --git a/externals/bzip2/blocksort.c b/externals/bzip2/blocksort.c deleted file mode 100644 index bd2dec157fa..00000000000 --- a/externals/bzip2/blocksort.c +++ /dev/null @@ -1,1094 +0,0 @@ - -/*-------------------------------------------------------------*/ -/*--- Block sorting machinery ---*/ -/*--- blocksort.c ---*/ -/*-------------------------------------------------------------*/ - -/* ------------------------------------------------------------------ - This file is part of bzip2/libbzip2, a program and library for - lossless, block-sorting data compression. - - bzip2/libbzip2 version 1.0.5 of 10 December 2007 - Copyright (C) 1996-2007 Julian Seward - - Please read the WARNING, DISCLAIMER and PATENTS sections in the - README file. - - This program is released under the terms of the license contained - in the file LICENSE. - ------------------------------------------------------------------ */ - - -#include "bzlib_private.h" - -/*---------------------------------------------*/ -/*--- Fallback O(N log(N)^2) sorting ---*/ -/*--- algorithm, for repetitive blocks ---*/ -/*---------------------------------------------*/ - -/*---------------------------------------------*/ -static -__inline__ -void fallbackSimpleSort ( UInt32* fmap, - UInt32* eclass, - Int32 lo, - Int32 hi ) -{ - Int32 i, j, tmp; - UInt32 ec_tmp; - - if (lo == hi) return; - - if (hi - lo > 3) { - for ( i = hi-4; i >= lo; i-- ) { - tmp = fmap[i]; - ec_tmp = eclass[tmp]; - for ( j = i+4; j <= hi && ec_tmp > eclass[fmap[j]]; j += 4 ) - fmap[j-4] = fmap[j]; - fmap[j-4] = tmp; - } - } - - for ( i = hi-1; i >= lo; i-- ) { - tmp = fmap[i]; - ec_tmp = eclass[tmp]; - for ( j = i+1; j <= hi && ec_tmp > eclass[fmap[j]]; j++ ) - fmap[j-1] = fmap[j]; - fmap[j-1] = tmp; - } -} - - -/*---------------------------------------------*/ -#define fswap(zz1, zz2) \ - { Int32 zztmp = zz1; zz1 = zz2; zz2 = zztmp; } - -#define fvswap(zzp1, zzp2, zzn) \ -{ \ - Int32 yyp1 = (zzp1); \ - Int32 yyp2 = (zzp2); \ - Int32 yyn = (zzn); \ - while (yyn > 0) { \ - fswap(fmap[yyp1], fmap[yyp2]); \ - yyp1++; yyp2++; yyn--; \ - } \ -} - - -#define fmin(a,b) ((a) < (b)) ? (a) : (b) - -#define fpush(lz,hz) { stackLo[sp] = lz; \ - stackHi[sp] = hz; \ - sp++; } - -#define fpop(lz,hz) { sp--; \ - lz = stackLo[sp]; \ - hz = stackHi[sp]; } - -#define FALLBACK_QSORT_SMALL_THRESH 10 -#define FALLBACK_QSORT_STACK_SIZE 100 - - -static -void fallbackQSort3 ( UInt32* fmap, - UInt32* eclass, - Int32 loSt, - Int32 hiSt ) -{ - Int32 unLo, unHi, ltLo, gtHi, n, m; - Int32 sp, lo, hi; - UInt32 med, r, r3; - Int32 stackLo[FALLBACK_QSORT_STACK_SIZE]; - Int32 stackHi[FALLBACK_QSORT_STACK_SIZE]; - - r = 0; - - sp = 0; - fpush ( loSt, hiSt ); - - while (sp > 0) { - - AssertH ( sp < FALLBACK_QSORT_STACK_SIZE - 1, 1004 ); - - fpop ( lo, hi ); - if (hi - lo < FALLBACK_QSORT_SMALL_THRESH) { - fallbackSimpleSort ( fmap, eclass, lo, hi ); - continue; - } - - /* Random partitioning. Median of 3 sometimes fails to - avoid bad cases. Median of 9 seems to help but - looks rather expensive. This too seems to work but - is cheaper. Guidance for the magic constants - 7621 and 32768 is taken from Sedgewick's algorithms - book, chapter 35. - */ - r = ((r * 7621) + 1) % 32768; - r3 = r % 3; - if (r3 == 0) med = eclass[fmap[lo]]; else - if (r3 == 1) med = eclass[fmap[(lo+hi)>>1]]; else - med = eclass[fmap[hi]]; - - unLo = ltLo = lo; - unHi = gtHi = hi; - - while (1) { - while (1) { - if (unLo > unHi) break; - n = (Int32)eclass[fmap[unLo]] - (Int32)med; - if (n == 0) { - fswap(fmap[unLo], fmap[ltLo]); - ltLo++; unLo++; - continue; - }; - if (n > 0) break; - unLo++; - } - while (1) { - if (unLo > unHi) break; - n = (Int32)eclass[fmap[unHi]] - (Int32)med; - if (n == 0) { - fswap(fmap[unHi], fmap[gtHi]); - gtHi--; unHi--; - continue; - }; - if (n < 0) break; - unHi--; - } - if (unLo > unHi) break; - fswap(fmap[unLo], fmap[unHi]); unLo++; unHi--; - } - - AssertD ( unHi == unLo-1, "fallbackQSort3(2)" ); - - if (gtHi < ltLo) continue; - - n = fmin(ltLo-lo, unLo-ltLo); fvswap(lo, unLo-n, n); - m = fmin(hi-gtHi, gtHi-unHi); fvswap(unLo, hi-m+1, m); - - n = lo + unLo - ltLo - 1; - m = hi - (gtHi - unHi) + 1; - - if (n - lo > hi - m) { - fpush ( lo, n ); - fpush ( m, hi ); - } else { - fpush ( m, hi ); - fpush ( lo, n ); - } - } -} - -#undef fmin -#undef fpush -#undef fpop -#undef fswap -#undef fvswap -#undef FALLBACK_QSORT_SMALL_THRESH -#undef FALLBACK_QSORT_STACK_SIZE - - -/*---------------------------------------------*/ -/* Pre: - nblock > 0 - eclass exists for [0 .. nblock-1] - ((UChar*)eclass) [0 .. nblock-1] holds block - ptr exists for [0 .. nblock-1] - - Post: - ((UChar*)eclass) [0 .. nblock-1] holds block - All other areas of eclass destroyed - fmap [0 .. nblock-1] holds sorted order - bhtab [ 0 .. 2+(nblock/32) ] destroyed -*/ - -#define SET_BH(zz) bhtab[(zz) >> 5] |= (1 << ((zz) & 31)) -#define CLEAR_BH(zz) bhtab[(zz) >> 5] &= ~(1 << ((zz) & 31)) -#define ISSET_BH(zz) (bhtab[(zz) >> 5] & (1 << ((zz) & 31))) -#define WORD_BH(zz) bhtab[(zz) >> 5] -#define UNALIGNED_BH(zz) ((zz) & 0x01f) - -static -void fallbackSort ( UInt32* fmap, - UInt32* eclass, - UInt32* bhtab, - Int32 nblock, - Int32 verb ) -{ - Int32 ftab[257]; - Int32 ftabCopy[256]; - Int32 H, i, j, k, l, r, cc, cc1; - Int32 nNotDone; - Int32 nBhtab; - UChar* eclass8 = (UChar*)eclass; - - /*-- - Initial 1-char radix sort to generate - initial fmap and initial BH bits. - --*/ - if (verb >= 4) - VPrintf0 ( " bucket sorting ...\n" ); - for (i = 0; i < 257; i++) ftab[i] = 0; - for (i = 0; i < nblock; i++) ftab[eclass8[i]]++; - for (i = 0; i < 256; i++) ftabCopy[i] = ftab[i]; - for (i = 1; i < 257; i++) ftab[i] += ftab[i-1]; - - for (i = 0; i < nblock; i++) { - j = eclass8[i]; - k = ftab[j] - 1; - ftab[j] = k; - fmap[k] = i; - } - - nBhtab = 2 + (nblock / 32); - for (i = 0; i < nBhtab; i++) bhtab[i] = 0; - for (i = 0; i < 256; i++) SET_BH(ftab[i]); - - /*-- - Inductively refine the buckets. Kind-of an - "exponential radix sort" (!), inspired by the - Manber-Myers suffix array construction algorithm. - --*/ - - /*-- set sentinel bits for block-end detection --*/ - for (i = 0; i < 32; i++) { - SET_BH(nblock + 2*i); - CLEAR_BH(nblock + 2*i + 1); - } - - /*-- the log(N) loop --*/ - H = 1; - while (1) { - - if (verb >= 4) - VPrintf1 ( " depth %6d has ", H ); - - j = 0; - for (i = 0; i < nblock; i++) { - if (ISSET_BH(i)) j = i; - k = fmap[i] - H; if (k < 0) k += nblock; - eclass[k] = j; - } - - nNotDone = 0; - r = -1; - while (1) { - - /*-- find the next non-singleton bucket --*/ - k = r + 1; - while (ISSET_BH(k) && UNALIGNED_BH(k)) k++; - if (ISSET_BH(k)) { - while (WORD_BH(k) == 0xffffffff) k += 32; - while (ISSET_BH(k)) k++; - } - l = k - 1; - if (l >= nblock) break; - while (!ISSET_BH(k) && UNALIGNED_BH(k)) k++; - if (!ISSET_BH(k)) { - while (WORD_BH(k) == 0x00000000) k += 32; - while (!ISSET_BH(k)) k++; - } - r = k - 1; - if (r >= nblock) break; - - /*-- now [l, r] bracket current bucket --*/ - if (r > l) { - nNotDone += (r - l + 1); - fallbackQSort3 ( fmap, eclass, l, r ); - - /*-- scan bucket and generate header bits-- */ - cc = -1; - for (i = l; i <= r; i++) { - cc1 = eclass[fmap[i]]; - if (cc != cc1) { SET_BH(i); cc = cc1; }; - } - } - } - - if (verb >= 4) - VPrintf1 ( "%6d unresolved strings\n", nNotDone ); - - H *= 2; - if (H > nblock || nNotDone == 0) break; - } - - /*-- - Reconstruct the original block in - eclass8 [0 .. nblock-1], since the - previous phase destroyed it. - --*/ - if (verb >= 4) - VPrintf0 ( " reconstructing block ...\n" ); - j = 0; - for (i = 0; i < nblock; i++) { - while (ftabCopy[j] == 0) j++; - ftabCopy[j]--; - eclass8[fmap[i]] = (UChar)j; - } - AssertH ( j < 256, 1005 ); -} - -#undef SET_BH -#undef CLEAR_BH -#undef ISSET_BH -#undef WORD_BH -#undef UNALIGNED_BH - - -/*---------------------------------------------*/ -/*--- The main, O(N^2 log(N)) sorting ---*/ -/*--- algorithm. Faster for "normal" ---*/ -/*--- non-repetitive blocks. ---*/ -/*---------------------------------------------*/ - -/*---------------------------------------------*/ -static -__inline__ -Bool mainGtU ( UInt32 i1, - UInt32 i2, - UChar* block, - UInt16* quadrant, - UInt32 nblock, - Int32* budget ) -{ - Int32 k; - UChar c1, c2; - UInt16 s1, s2; - - AssertD ( i1 != i2, "mainGtU" ); - /* 1 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - i1++; i2++; - /* 2 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - i1++; i2++; - /* 3 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - i1++; i2++; - /* 4 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - i1++; i2++; - /* 5 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - i1++; i2++; - /* 6 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - i1++; i2++; - /* 7 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - i1++; i2++; - /* 8 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - i1++; i2++; - /* 9 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - i1++; i2++; - /* 10 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - i1++; i2++; - /* 11 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - i1++; i2++; - /* 12 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - i1++; i2++; - - k = nblock + 8; - - do { - /* 1 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - s1 = quadrant[i1]; s2 = quadrant[i2]; - if (s1 != s2) return (s1 > s2); - i1++; i2++; - /* 2 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - s1 = quadrant[i1]; s2 = quadrant[i2]; - if (s1 != s2) return (s1 > s2); - i1++; i2++; - /* 3 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - s1 = quadrant[i1]; s2 = quadrant[i2]; - if (s1 != s2) return (s1 > s2); - i1++; i2++; - /* 4 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - s1 = quadrant[i1]; s2 = quadrant[i2]; - if (s1 != s2) return (s1 > s2); - i1++; i2++; - /* 5 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - s1 = quadrant[i1]; s2 = quadrant[i2]; - if (s1 != s2) return (s1 > s2); - i1++; i2++; - /* 6 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - s1 = quadrant[i1]; s2 = quadrant[i2]; - if (s1 != s2) return (s1 > s2); - i1++; i2++; - /* 7 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - s1 = quadrant[i1]; s2 = quadrant[i2]; - if (s1 != s2) return (s1 > s2); - i1++; i2++; - /* 8 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - s1 = quadrant[i1]; s2 = quadrant[i2]; - if (s1 != s2) return (s1 > s2); - i1++; i2++; - - if (i1 >= nblock) i1 -= nblock; - if (i2 >= nblock) i2 -= nblock; - - k -= 8; - (*budget)--; - } - while (k >= 0); - - return False; -} - - -/*---------------------------------------------*/ -/*-- - Knuth's increments seem to work better - than Incerpi-Sedgewick here. Possibly - because the number of elems to sort is - usually small, typically <= 20. ---*/ -static -Int32 incs[14] = { 1, 4, 13, 40, 121, 364, 1093, 3280, - 9841, 29524, 88573, 265720, - 797161, 2391484 }; - -static -void mainSimpleSort ( UInt32* ptr, - UChar* block, - UInt16* quadrant, - Int32 nblock, - Int32 lo, - Int32 hi, - Int32 d, - Int32* budget ) -{ - Int32 i, j, h, bigN, hp; - UInt32 v; - - bigN = hi - lo + 1; - if (bigN < 2) return; - - hp = 0; - while (incs[hp] < bigN) hp++; - hp--; - - for (; hp >= 0; hp--) { - h = incs[hp]; - - i = lo + h; - while (True) { - - /*-- copy 1 --*/ - if (i > hi) break; - v = ptr[i]; - j = i; - while ( mainGtU ( - ptr[j-h]+d, v+d, block, quadrant, nblock, budget - ) ) { - ptr[j] = ptr[j-h]; - j = j - h; - if (j <= (lo + h - 1)) break; - } - ptr[j] = v; - i++; - - /*-- copy 2 --*/ - if (i > hi) break; - v = ptr[i]; - j = i; - while ( mainGtU ( - ptr[j-h]+d, v+d, block, quadrant, nblock, budget - ) ) { - ptr[j] = ptr[j-h]; - j = j - h; - if (j <= (lo + h - 1)) break; - } - ptr[j] = v; - i++; - - /*-- copy 3 --*/ - if (i > hi) break; - v = ptr[i]; - j = i; - while ( mainGtU ( - ptr[j-h]+d, v+d, block, quadrant, nblock, budget - ) ) { - ptr[j] = ptr[j-h]; - j = j - h; - if (j <= (lo + h - 1)) break; - } - ptr[j] = v; - i++; - - if (*budget < 0) return; - } - } -} - - -/*---------------------------------------------*/ -/*-- - The following is an implementation of - an elegant 3-way quicksort for strings, - described in a paper "Fast Algorithms for - Sorting and Searching Strings", by Robert - Sedgewick and Jon L. Bentley. ---*/ - -#define mswap(zz1, zz2) \ - { Int32 zztmp = zz1; zz1 = zz2; zz2 = zztmp; } - -#define mvswap(zzp1, zzp2, zzn) \ -{ \ - Int32 yyp1 = (zzp1); \ - Int32 yyp2 = (zzp2); \ - Int32 yyn = (zzn); \ - while (yyn > 0) { \ - mswap(ptr[yyp1], ptr[yyp2]); \ - yyp1++; yyp2++; yyn--; \ - } \ -} - -static -__inline__ -UChar mmed3 ( UChar a, UChar b, UChar c ) -{ - UChar t; - if (a > b) { t = a; a = b; b = t; }; - if (b > c) { - b = c; - if (a > b) b = a; - } - return b; -} - -#define mmin(a,b) ((a) < (b)) ? (a) : (b) - -#define mpush(lz,hz,dz) { stackLo[sp] = lz; \ - stackHi[sp] = hz; \ - stackD [sp] = dz; \ - sp++; } - -#define mpop(lz,hz,dz) { sp--; \ - lz = stackLo[sp]; \ - hz = stackHi[sp]; \ - dz = stackD [sp]; } - - -#define mnextsize(az) (nextHi[az]-nextLo[az]) - -#define mnextswap(az,bz) \ - { Int32 tz; \ - tz = nextLo[az]; nextLo[az] = nextLo[bz]; nextLo[bz] = tz; \ - tz = nextHi[az]; nextHi[az] = nextHi[bz]; nextHi[bz] = tz; \ - tz = nextD [az]; nextD [az] = nextD [bz]; nextD [bz] = tz; } - - -#define MAIN_QSORT_SMALL_THRESH 20 -#define MAIN_QSORT_DEPTH_THRESH (BZ_N_RADIX + BZ_N_QSORT) -#define MAIN_QSORT_STACK_SIZE 100 - -static -void mainQSort3 ( UInt32* ptr, - UChar* block, - UInt16* quadrant, - Int32 nblock, - Int32 loSt, - Int32 hiSt, - Int32 dSt, - Int32* budget ) -{ - Int32 unLo, unHi, ltLo, gtHi, n, m, med; - Int32 sp, lo, hi, d; - - Int32 stackLo[MAIN_QSORT_STACK_SIZE]; - Int32 stackHi[MAIN_QSORT_STACK_SIZE]; - Int32 stackD [MAIN_QSORT_STACK_SIZE]; - - Int32 nextLo[3]; - Int32 nextHi[3]; - Int32 nextD [3]; - - sp = 0; - mpush ( loSt, hiSt, dSt ); - - while (sp > 0) { - - AssertH ( sp < MAIN_QSORT_STACK_SIZE - 2, 1001 ); - - mpop ( lo, hi, d ); - if (hi - lo < MAIN_QSORT_SMALL_THRESH || - d > MAIN_QSORT_DEPTH_THRESH) { - mainSimpleSort ( ptr, block, quadrant, nblock, lo, hi, d, budget ); - if (*budget < 0) return; - continue; - } - - med = (Int32) - mmed3 ( block[ptr[ lo ]+d], - block[ptr[ hi ]+d], - block[ptr[ (lo+hi)>>1 ]+d] ); - - unLo = ltLo = lo; - unHi = gtHi = hi; - - while (True) { - while (True) { - if (unLo > unHi) break; - n = ((Int32)block[ptr[unLo]+d]) - med; - if (n == 0) { - mswap(ptr[unLo], ptr[ltLo]); - ltLo++; unLo++; continue; - }; - if (n > 0) break; - unLo++; - } - while (True) { - if (unLo > unHi) break; - n = ((Int32)block[ptr[unHi]+d]) - med; - if (n == 0) { - mswap(ptr[unHi], ptr[gtHi]); - gtHi--; unHi--; continue; - }; - if (n < 0) break; - unHi--; - } - if (unLo > unHi) break; - mswap(ptr[unLo], ptr[unHi]); unLo++; unHi--; - } - - AssertD ( unHi == unLo-1, "mainQSort3(2)" ); - - if (gtHi < ltLo) { - mpush(lo, hi, d+1 ); - continue; - } - - n = mmin(ltLo-lo, unLo-ltLo); mvswap(lo, unLo-n, n); - m = mmin(hi-gtHi, gtHi-unHi); mvswap(unLo, hi-m+1, m); - - n = lo + unLo - ltLo - 1; - m = hi - (gtHi - unHi) + 1; - - nextLo[0] = lo; nextHi[0] = n; nextD[0] = d; - nextLo[1] = m; nextHi[1] = hi; nextD[1] = d; - nextLo[2] = n+1; nextHi[2] = m-1; nextD[2] = d+1; - - if (mnextsize(0) < mnextsize(1)) mnextswap(0,1); - if (mnextsize(1) < mnextsize(2)) mnextswap(1,2); - if (mnextsize(0) < mnextsize(1)) mnextswap(0,1); - - AssertD (mnextsize(0) >= mnextsize(1), "mainQSort3(8)" ); - AssertD (mnextsize(1) >= mnextsize(2), "mainQSort3(9)" ); - - mpush (nextLo[0], nextHi[0], nextD[0]); - mpush (nextLo[1], nextHi[1], nextD[1]); - mpush (nextLo[2], nextHi[2], nextD[2]); - } -} - -#undef mswap -#undef mvswap -#undef mpush -#undef mpop -#undef mmin -#undef mnextsize -#undef mnextswap -#undef MAIN_QSORT_SMALL_THRESH -#undef MAIN_QSORT_DEPTH_THRESH -#undef MAIN_QSORT_STACK_SIZE - - -/*---------------------------------------------*/ -/* Pre: - nblock > N_OVERSHOOT - block32 exists for [0 .. nblock-1 +N_OVERSHOOT] - ((UChar*)block32) [0 .. nblock-1] holds block - ptr exists for [0 .. nblock-1] - - Post: - ((UChar*)block32) [0 .. nblock-1] holds block - All other areas of block32 destroyed - ftab [0 .. 65536 ] destroyed - ptr [0 .. nblock-1] holds sorted order - if (*budget < 0), sorting was abandoned -*/ - -#define BIGFREQ(b) (ftab[((b)+1) << 8] - ftab[(b) << 8]) -#define SETMASK (1 << 21) -#define CLEARMASK (~(SETMASK)) - -static -void mainSort ( UInt32* ptr, - UChar* block, - UInt16* quadrant, - UInt32* ftab, - Int32 nblock, - Int32 verb, - Int32* budget ) -{ - Int32 i, j, k, ss, sb; - Int32 runningOrder[256]; - Bool bigDone[256]; - Int32 copyStart[256]; - Int32 copyEnd [256]; - UChar c1; - Int32 numQSorted; - UInt16 s; - if (verb >= 4) VPrintf0 ( " main sort initialise ...\n" ); - - /*-- set up the 2-byte frequency table --*/ - for (i = 65536; i >= 0; i--) ftab[i] = 0; - - j = block[0] << 8; - i = nblock-1; - for (; i >= 3; i -= 4) { - quadrant[i] = 0; - j = (j >> 8) | ( ((UInt16)block[i]) << 8); - ftab[j]++; - quadrant[i-1] = 0; - j = (j >> 8) | ( ((UInt16)block[i-1]) << 8); - ftab[j]++; - quadrant[i-2] = 0; - j = (j >> 8) | ( ((UInt16)block[i-2]) << 8); - ftab[j]++; - quadrant[i-3] = 0; - j = (j >> 8) | ( ((UInt16)block[i-3]) << 8); - ftab[j]++; - } - for (; i >= 0; i--) { - quadrant[i] = 0; - j = (j >> 8) | ( ((UInt16)block[i]) << 8); - ftab[j]++; - } - - /*-- (emphasises close relationship of block & quadrant) --*/ - for (i = 0; i < BZ_N_OVERSHOOT; i++) { - block [nblock+i] = block[i]; - quadrant[nblock+i] = 0; - } - - if (verb >= 4) VPrintf0 ( " bucket sorting ...\n" ); - - /*-- Complete the initial radix sort --*/ - for (i = 1; i <= 65536; i++) ftab[i] += ftab[i-1]; - - s = block[0] << 8; - i = nblock-1; - for (; i >= 3; i -= 4) { - s = (s >> 8) | (block[i] << 8); - j = ftab[s] -1; - ftab[s] = j; - ptr[j] = i; - s = (s >> 8) | (block[i-1] << 8); - j = ftab[s] -1; - ftab[s] = j; - ptr[j] = i-1; - s = (s >> 8) | (block[i-2] << 8); - j = ftab[s] -1; - ftab[s] = j; - ptr[j] = i-2; - s = (s >> 8) | (block[i-3] << 8); - j = ftab[s] -1; - ftab[s] = j; - ptr[j] = i-3; - } - for (; i >= 0; i--) { - s = (s >> 8) | (block[i] << 8); - j = ftab[s] -1; - ftab[s] = j; - ptr[j] = i; - } - - /*-- - Now ftab contains the first loc of every small bucket. - Calculate the running order, from smallest to largest - big bucket. - --*/ - for (i = 0; i <= 255; i++) { - bigDone [i] = False; - runningOrder[i] = i; - } - - { - Int32 vv; - Int32 h = 1; - do h = 3 * h + 1; while (h <= 256); - do { - h = h / 3; - for (i = h; i <= 255; i++) { - vv = runningOrder[i]; - j = i; - while ( BIGFREQ(runningOrder[j-h]) > BIGFREQ(vv) ) { - runningOrder[j] = runningOrder[j-h]; - j = j - h; - if (j <= (h - 1)) goto zero; - } - zero: - runningOrder[j] = vv; - } - } while (h != 1); - } - - /*-- - The main sorting loop. - --*/ - - numQSorted = 0; - - for (i = 0; i <= 255; i++) { - - /*-- - Process big buckets, starting with the least full. - Basically this is a 3-step process in which we call - mainQSort3 to sort the small buckets [ss, j], but - also make a big effort to avoid the calls if we can. - --*/ - ss = runningOrder[i]; - - /*-- - Step 1: - Complete the big bucket [ss] by quicksorting - any unsorted small buckets [ss, j], for j != ss. - Hopefully previous pointer-scanning phases have already - completed many of the small buckets [ss, j], so - we don't have to sort them at all. - --*/ - for (j = 0; j <= 255; j++) { - if (j != ss) { - sb = (ss << 8) + j; - if ( ! (ftab[sb] & SETMASK) ) { - Int32 lo = ftab[sb] & CLEARMASK; - Int32 hi = (ftab[sb+1] & CLEARMASK) - 1; - if (hi > lo) { - if (verb >= 4) - VPrintf4 ( " qsort [0x%x, 0x%x] " - "done %d this %d\n", - ss, j, numQSorted, hi - lo + 1 ); - mainQSort3 ( - ptr, block, quadrant, nblock, - lo, hi, BZ_N_RADIX, budget - ); - numQSorted += (hi - lo + 1); - if (*budget < 0) return; - } - } - ftab[sb] |= SETMASK; - } - } - - AssertH ( !bigDone[ss], 1006 ); - - /*-- - Step 2: - Now scan this big bucket [ss] so as to synthesise the - sorted order for small buckets [t, ss] for all t, - including, magically, the bucket [ss,ss] too. - This will avoid doing Real Work in subsequent Step 1's. - --*/ - { - for (j = 0; j <= 255; j++) { - copyStart[j] = ftab[(j << 8) + ss] & CLEARMASK; - copyEnd [j] = (ftab[(j << 8) + ss + 1] & CLEARMASK) - 1; - } - for (j = ftab[ss << 8] & CLEARMASK; j < copyStart[ss]; j++) { - k = ptr[j]-1; if (k < 0) k += nblock; - c1 = block[k]; - if (!bigDone[c1]) - ptr[ copyStart[c1]++ ] = k; - } - for (j = (ftab[(ss+1) << 8] & CLEARMASK) - 1; j > copyEnd[ss]; j--) { - k = ptr[j]-1; if (k < 0) k += nblock; - c1 = block[k]; - if (!bigDone[c1]) - ptr[ copyEnd[c1]-- ] = k; - } - } - - AssertH ( (copyStart[ss]-1 == copyEnd[ss]) - || - /* Extremely rare case missing in bzip2-1.0.0 and 1.0.1. - Necessity for this case is demonstrated by compressing - a sequence of approximately 48.5 million of character - 251; 1.0.0/1.0.1 will then die here. */ - (copyStart[ss] == 0 && copyEnd[ss] == nblock-1), - 1007 ) - - for (j = 0; j <= 255; j++) ftab[(j << 8) + ss] |= SETMASK; - - /*-- - Step 3: - The [ss] big bucket is now done. Record this fact, - and update the quadrant descriptors. Remember to - update quadrants in the overshoot area too, if - necessary. The "if (i < 255)" test merely skips - this updating for the last bucket processed, since - updating for the last bucket is pointless. - - The quadrant array provides a way to incrementally - cache sort orderings, as they appear, so as to - make subsequent comparisons in fullGtU() complete - faster. For repetitive blocks this makes a big - difference (but not big enough to be able to avoid - the fallback sorting mechanism, exponential radix sort). - - The precise meaning is: at all times: - - for 0 <= i < nblock and 0 <= j <= nblock - - if block[i] != block[j], - - then the relative values of quadrant[i] and - quadrant[j] are meaningless. - - else { - if quadrant[i] < quadrant[j] - then the string starting at i lexicographically - precedes the string starting at j - - else if quadrant[i] > quadrant[j] - then the string starting at j lexicographically - precedes the string starting at i - - else - the relative ordering of the strings starting - at i and j has not yet been determined. - } - --*/ - bigDone[ss] = True; - - if (i < 255) { - Int32 bbStart = ftab[ss << 8] & CLEARMASK; - Int32 bbSize = (ftab[(ss+1) << 8] & CLEARMASK) - bbStart; - Int32 shifts = 0; - - while ((bbSize >> shifts) > 65534) shifts++; - - for (j = bbSize-1; j >= 0; j--) { - Int32 a2update = ptr[bbStart + j]; - UInt16 qVal = (UInt16)(j >> shifts); - quadrant[a2update] = qVal; - if (a2update < BZ_N_OVERSHOOT) - quadrant[a2update + nblock] = qVal; - } - AssertH ( ((bbSize-1) >> shifts) <= 65535, 1002 ); - } - - } - - if (verb >= 4) - VPrintf3 ( " %d pointers, %d sorted, %d scanned\n", - nblock, numQSorted, nblock - numQSorted ); -} - -#undef BIGFREQ -#undef SETMASK -#undef CLEARMASK - - -/*---------------------------------------------*/ -/* Pre: - nblock > 0 - arr2 exists for [0 .. nblock-1 +N_OVERSHOOT] - ((UChar*)arr2) [0 .. nblock-1] holds block - arr1 exists for [0 .. nblock-1] - - Post: - ((UChar*)arr2) [0 .. nblock-1] holds block - All other areas of block destroyed - ftab [ 0 .. 65536 ] destroyed - arr1 [0 .. nblock-1] holds sorted order -*/ -void BZ2_blockSort ( EState* s ) -{ - UInt32* ptr = s->ptr; - UChar* block = s->block; - UInt32* ftab = s->ftab; - Int32 nblock = s->nblock; - Int32 verb = s->verbosity; - Int32 wfact = s->workFactor; - UInt16* quadrant; - Int32 budget; - Int32 budgetInit; - Int32 i; - - if (nblock < 10000) { - fallbackSort ( s->arr1, s->arr2, ftab, nblock, verb ); - } else { - /* Calculate the location for quadrant, remembering to get - the alignment right. Assumes that &(block[0]) is at least - 2-byte aligned -- this should be ok since block is really - the first section of arr2. - */ - i = nblock+BZ_N_OVERSHOOT; - if (i & 1) i++; - quadrant = (UInt16*)(&(block[i])); - - /* (wfact-1) / 3 puts the default-factor-30 - transition point at very roughly the same place as - with v0.1 and v0.9.0. - Not that it particularly matters any more, since the - resulting compressed stream is now the same regardless - of whether or not we use the main sort or fallback sort. - */ - if (wfact < 1 ) wfact = 1; - if (wfact > 100) wfact = 100; - budgetInit = nblock * ((wfact-1) / 3); - budget = budgetInit; - - mainSort ( ptr, block, quadrant, ftab, nblock, verb, &budget ); - if (verb >= 3) - VPrintf3 ( " %d work, %d block, ratio %5.2f\n", - budgetInit - budget, - nblock, - (float)(budgetInit - budget) / - (float)(nblock==0 ? 1 : nblock) ); - if (budget < 0) { - if (verb >= 2) - VPrintf0 ( " too repetitive; using fallback" - " sorting algorithm\n" ); - fallbackSort ( s->arr1, s->arr2, ftab, nblock, verb ); - } - } - - s->origPtr = -1; - for (i = 0; i < s->nblock; i++) - if (ptr[i] == 0) - { s->origPtr = i; break; }; - - AssertH( s->origPtr != -1, 1003 ); -} - - -/*-------------------------------------------------------------*/ -/*--- end blocksort.c ---*/ -/*-------------------------------------------------------------*/ diff --git a/externals/bzip2/bzlib.c b/externals/bzip2/bzlib.c deleted file mode 100644 index ef86c91e695..00000000000 --- a/externals/bzip2/bzlib.c +++ /dev/null @@ -1,1572 +0,0 @@ - -/*-------------------------------------------------------------*/ -/*--- Library top-level functions. ---*/ -/*--- bzlib.c ---*/ -/*-------------------------------------------------------------*/ - -/* ------------------------------------------------------------------ - This file is part of bzip2/libbzip2, a program and library for - lossless, block-sorting data compression. - - bzip2/libbzip2 version 1.0.5 of 10 December 2007 - Copyright (C) 1996-2007 Julian Seward - - Please read the WARNING, DISCLAIMER and PATENTS sections in the - README file. - - This program is released under the terms of the license contained - in the file LICENSE. - ------------------------------------------------------------------ */ - -/* CHANGES - 0.9.0 -- original version. - 0.9.0a/b -- no changes in this file. - 0.9.0c -- made zero-length BZ_FLUSH work correctly in bzCompress(). - fixed bzWrite/bzRead to ignore zero-length requests. - fixed bzread to correctly handle read requests after EOF. - wrong parameter order in call to bzDecompressInit in - bzBuffToBuffDecompress. Fixed. -*/ - -#include "bzlib_private.h" - - -/*---------------------------------------------------*/ -/*--- Compression stuff ---*/ -/*---------------------------------------------------*/ - - -/*---------------------------------------------------*/ -#ifndef BZ_NO_STDIO -void BZ2_bz__AssertH__fail ( int errcode ) -{ - fprintf(stderr, - "\n\nbzip2/libbzip2: internal error number %d.\n" - "This is a bug in bzip2/libbzip2, %s.\n" - "Please report it to me at: jseward@bzip.org. If this happened\n" - "when you were using some program which uses libbzip2 as a\n" - "component, you should also report this bug to the author(s)\n" - "of that program. Please make an effort to report this bug;\n" - "timely and accurate bug reports eventually lead to higher\n" - "quality software. Thanks. Julian Seward, 10 December 2007.\n\n", - errcode, - BZ2_bzlibVersion() - ); - - if (errcode == 1007) { - fprintf(stderr, - "\n*** A special note about internal error number 1007 ***\n" - "\n" - "Experience suggests that a common cause of i.e. 1007\n" - "is unreliable memory or other hardware. The 1007 assertion\n" - "just happens to cross-check the results of huge numbers of\n" - "memory reads/writes, and so acts (unintendedly) as a stress\n" - "test of your memory system.\n" - "\n" - "I suggest the following: try compressing the file again,\n" - "possibly monitoring progress in detail with the -vv flag.\n" - "\n" - "* If the error cannot be reproduced, and/or happens at different\n" - " points in compression, you may have a flaky memory system.\n" - " Try a memory-test program. I have used Memtest86\n" - " (www.memtest86.com). At the time of writing it is free (GPLd).\n" - " Memtest86 tests memory much more thorougly than your BIOSs\n" - " power-on test, and may find failures that the BIOS doesn't.\n" - "\n" - "* If the error can be repeatably reproduced, this is a bug in\n" - " bzip2, and I would very much like to hear about it. Please\n" - " let me know, and, ideally, save a copy of the file causing the\n" - " problem -- without which I will be unable to investigate it.\n" - "\n" - ); - } - - exit(3); -} -#endif - - -/*---------------------------------------------------*/ -static -int bz_config_ok ( void ) -{ - if (sizeof(int) != 4) return 0; - if (sizeof(short) != 2) return 0; - if (sizeof(char) != 1) return 0; - return 1; -} - - -/*---------------------------------------------------*/ -static -void* default_bzalloc ( void* opaque, Int32 items, Int32 size ) -{ - void* v = malloc ( items * size ); - return v; -} - -static -void default_bzfree ( void* opaque, void* addr ) -{ - if (addr != NULL) free ( addr ); -} - - -/*---------------------------------------------------*/ -static -void prepare_new_block ( EState* s ) -{ - Int32 i; - s->nblock = 0; - s->numZ = 0; - s->state_out_pos = 0; - BZ_INITIALISE_CRC ( s->blockCRC ); - for (i = 0; i < 256; i++) s->inUse[i] = False; - s->blockNo++; -} - - -/*---------------------------------------------------*/ -static -void init_RL ( EState* s ) -{ - s->state_in_ch = 256; - s->state_in_len = 0; -} - - -static -Bool isempty_RL ( EState* s ) -{ - if (s->state_in_ch < 256 && s->state_in_len > 0) - return False; else - return True; -} - - -/*---------------------------------------------------*/ -int BZ_API(BZ2_bzCompressInit) - ( bz_stream* strm, - int blockSize100k, - int verbosity, - int workFactor ) -{ - Int32 n; - EState* s; - - if (!bz_config_ok()) return BZ_CONFIG_ERROR; - - if (strm == NULL || - blockSize100k < 1 || blockSize100k > 9 || - workFactor < 0 || workFactor > 250) - return BZ_PARAM_ERROR; - - if (workFactor == 0) workFactor = 30; - if (strm->bzalloc == NULL) strm->bzalloc = default_bzalloc; - if (strm->bzfree == NULL) strm->bzfree = default_bzfree; - - s = BZALLOC( sizeof(EState) ); - if (s == NULL) return BZ_MEM_ERROR; - s->strm = strm; - - s->arr1 = NULL; - s->arr2 = NULL; - s->ftab = NULL; - - n = 100000 * blockSize100k; - s->arr1 = BZALLOC( n * sizeof(UInt32) ); - s->arr2 = BZALLOC( (n+BZ_N_OVERSHOOT) * sizeof(UInt32) ); - s->ftab = BZALLOC( 65537 * sizeof(UInt32) ); - - if (s->arr1 == NULL || s->arr2 == NULL || s->ftab == NULL) { - if (s->arr1 != NULL) BZFREE(s->arr1); - if (s->arr2 != NULL) BZFREE(s->arr2); - if (s->ftab != NULL) BZFREE(s->ftab); - if (s != NULL) BZFREE(s); - return BZ_MEM_ERROR; - } - - s->blockNo = 0; - s->state = BZ_S_INPUT; - s->mode = BZ_M_RUNNING; - s->combinedCRC = 0; - s->blockSize100k = blockSize100k; - s->nblockMAX = 100000 * blockSize100k - 19; - s->verbosity = verbosity; - s->workFactor = workFactor; - - s->block = (UChar*)s->arr2; - s->mtfv = (UInt16*)s->arr1; - s->zbits = NULL; - s->ptr = (UInt32*)s->arr1; - - strm->state = s; - strm->total_in_lo32 = 0; - strm->total_in_hi32 = 0; - strm->total_out_lo32 = 0; - strm->total_out_hi32 = 0; - init_RL ( s ); - prepare_new_block ( s ); - return BZ_OK; -} - - -/*---------------------------------------------------*/ -static -void add_pair_to_block ( EState* s ) -{ - Int32 i; - UChar ch = (UChar)(s->state_in_ch); - for (i = 0; i < s->state_in_len; i++) { - BZ_UPDATE_CRC( s->blockCRC, ch ); - } - s->inUse[s->state_in_ch] = True; - switch (s->state_in_len) { - case 1: - s->block[s->nblock] = (UChar)ch; s->nblock++; - break; - case 2: - s->block[s->nblock] = (UChar)ch; s->nblock++; - s->block[s->nblock] = (UChar)ch; s->nblock++; - break; - case 3: - s->block[s->nblock] = (UChar)ch; s->nblock++; - s->block[s->nblock] = (UChar)ch; s->nblock++; - s->block[s->nblock] = (UChar)ch; s->nblock++; - break; - default: - s->inUse[s->state_in_len-4] = True; - s->block[s->nblock] = (UChar)ch; s->nblock++; - s->block[s->nblock] = (UChar)ch; s->nblock++; - s->block[s->nblock] = (UChar)ch; s->nblock++; - s->block[s->nblock] = (UChar)ch; s->nblock++; - s->block[s->nblock] = ((UChar)(s->state_in_len-4)); - s->nblock++; - break; - } -} - - -/*---------------------------------------------------*/ -static -void flush_RL ( EState* s ) -{ - if (s->state_in_ch < 256) add_pair_to_block ( s ); - init_RL ( s ); -} - - -/*---------------------------------------------------*/ -#define ADD_CHAR_TO_BLOCK(zs,zchh0) \ -{ \ - UInt32 zchh = (UInt32)(zchh0); \ - /*-- fast track the common case --*/ \ - if (zchh != zs->state_in_ch && \ - zs->state_in_len == 1) { \ - UChar ch = (UChar)(zs->state_in_ch); \ - BZ_UPDATE_CRC( zs->blockCRC, ch ); \ - zs->inUse[zs->state_in_ch] = True; \ - zs->block[zs->nblock] = (UChar)ch; \ - zs->nblock++; \ - zs->state_in_ch = zchh; \ - } \ - else \ - /*-- general, uncommon cases --*/ \ - if (zchh != zs->state_in_ch || \ - zs->state_in_len == 255) { \ - if (zs->state_in_ch < 256) \ - add_pair_to_block ( zs ); \ - zs->state_in_ch = zchh; \ - zs->state_in_len = 1; \ - } else { \ - zs->state_in_len++; \ - } \ -} - - -/*---------------------------------------------------*/ -static -Bool copy_input_until_stop ( EState* s ) -{ - Bool progress_in = False; - - if (s->mode == BZ_M_RUNNING) { - - /*-- fast track the common case --*/ - while (True) { - /*-- block full? --*/ - if (s->nblock >= s->nblockMAX) break; - /*-- no input? --*/ - if (s->strm->avail_in == 0) break; - progress_in = True; - ADD_CHAR_TO_BLOCK ( s, (UInt32)(*((UChar*)(s->strm->next_in))) ); - s->strm->next_in++; - s->strm->avail_in--; - s->strm->total_in_lo32++; - if (s->strm->total_in_lo32 == 0) s->strm->total_in_hi32++; - } - - } else { - - /*-- general, uncommon case --*/ - while (True) { - /*-- block full? --*/ - if (s->nblock >= s->nblockMAX) break; - /*-- no input? --*/ - if (s->strm->avail_in == 0) break; - /*-- flush/finish end? --*/ - if (s->avail_in_expect == 0) break; - progress_in = True; - ADD_CHAR_TO_BLOCK ( s, (UInt32)(*((UChar*)(s->strm->next_in))) ); - s->strm->next_in++; - s->strm->avail_in--; - s->strm->total_in_lo32++; - if (s->strm->total_in_lo32 == 0) s->strm->total_in_hi32++; - s->avail_in_expect--; - } - } - return progress_in; -} - - -/*---------------------------------------------------*/ -static -Bool copy_output_until_stop ( EState* s ) -{ - Bool progress_out = False; - - while (True) { - - /*-- no output space? --*/ - if (s->strm->avail_out == 0) break; - - /*-- block done? --*/ - if (s->state_out_pos >= s->numZ) break; - - progress_out = True; - *(s->strm->next_out) = s->zbits[s->state_out_pos]; - s->state_out_pos++; - s->strm->avail_out--; - s->strm->next_out++; - s->strm->total_out_lo32++; - if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++; - } - - return progress_out; -} - - -/*---------------------------------------------------*/ -static -Bool handle_compress ( bz_stream* strm ) -{ - Bool progress_in = False; - Bool progress_out = False; - EState* s = strm->state; - - while (True) { - - if (s->state == BZ_S_OUTPUT) { - progress_out |= copy_output_until_stop ( s ); - if (s->state_out_pos < s->numZ) break; - if (s->mode == BZ_M_FINISHING && - s->avail_in_expect == 0 && - isempty_RL(s)) break; - prepare_new_block ( s ); - s->state = BZ_S_INPUT; - if (s->mode == BZ_M_FLUSHING && - s->avail_in_expect == 0 && - isempty_RL(s)) break; - } - - if (s->state == BZ_S_INPUT) { - progress_in |= copy_input_until_stop ( s ); - if (s->mode != BZ_M_RUNNING && s->avail_in_expect == 0) { - flush_RL ( s ); - BZ2_compressBlock ( s, (Bool)(s->mode == BZ_M_FINISHING) ); - s->state = BZ_S_OUTPUT; - } - else - if (s->nblock >= s->nblockMAX) { - BZ2_compressBlock ( s, False ); - s->state = BZ_S_OUTPUT; - } - else - if (s->strm->avail_in == 0) { - break; - } - } - - } - - return progress_in || progress_out; -} - - -/*---------------------------------------------------*/ -int BZ_API(BZ2_bzCompress) ( bz_stream *strm, int action ) -{ - Bool progress; - EState* s; - if (strm == NULL) return BZ_PARAM_ERROR; - s = strm->state; - if (s == NULL) return BZ_PARAM_ERROR; - if (s->strm != strm) return BZ_PARAM_ERROR; - - preswitch: - switch (s->mode) { - - case BZ_M_IDLE: - return BZ_SEQUENCE_ERROR; - - case BZ_M_RUNNING: - if (action == BZ_RUN) { - progress = handle_compress ( strm ); - return progress ? BZ_RUN_OK : BZ_PARAM_ERROR; - } - else - if (action == BZ_FLUSH) { - s->avail_in_expect = strm->avail_in; - s->mode = BZ_M_FLUSHING; - goto preswitch; - } - else - if (action == BZ_FINISH) { - s->avail_in_expect = strm->avail_in; - s->mode = BZ_M_FINISHING; - goto preswitch; - } - else - return BZ_PARAM_ERROR; - - case BZ_M_FLUSHING: - if (action != BZ_FLUSH) return BZ_SEQUENCE_ERROR; - if (s->avail_in_expect != s->strm->avail_in) - return BZ_SEQUENCE_ERROR; - progress = handle_compress ( strm ); - if (s->avail_in_expect > 0 || !isempty_RL(s) || - s->state_out_pos < s->numZ) return BZ_FLUSH_OK; - s->mode = BZ_M_RUNNING; - return BZ_RUN_OK; - - case BZ_M_FINISHING: - if (action != BZ_FINISH) return BZ_SEQUENCE_ERROR; - if (s->avail_in_expect != s->strm->avail_in) - return BZ_SEQUENCE_ERROR; - progress = handle_compress ( strm ); - if (!progress) return BZ_SEQUENCE_ERROR; - if (s->avail_in_expect > 0 || !isempty_RL(s) || - s->state_out_pos < s->numZ) return BZ_FINISH_OK; - s->mode = BZ_M_IDLE; - return BZ_STREAM_END; - } - return BZ_OK; /*--not reached--*/ -} - - -/*---------------------------------------------------*/ -int BZ_API(BZ2_bzCompressEnd) ( bz_stream *strm ) -{ - EState* s; - if (strm == NULL) return BZ_PARAM_ERROR; - s = strm->state; - if (s == NULL) return BZ_PARAM_ERROR; - if (s->strm != strm) return BZ_PARAM_ERROR; - - if (s->arr1 != NULL) BZFREE(s->arr1); - if (s->arr2 != NULL) BZFREE(s->arr2); - if (s->ftab != NULL) BZFREE(s->ftab); - BZFREE(strm->state); - - strm->state = NULL; - - return BZ_OK; -} - - -/*---------------------------------------------------*/ -/*--- Decompression stuff ---*/ -/*---------------------------------------------------*/ - -/*---------------------------------------------------*/ -int BZ_API(BZ2_bzDecompressInit) - ( bz_stream* strm, - int verbosity, - int small ) -{ - DState* s; - - if (!bz_config_ok()) return BZ_CONFIG_ERROR; - - if (strm == NULL) return BZ_PARAM_ERROR; - if (small != 0 && small != 1) return BZ_PARAM_ERROR; - if (verbosity < 0 || verbosity > 4) return BZ_PARAM_ERROR; - - if (strm->bzalloc == NULL) strm->bzalloc = default_bzalloc; - if (strm->bzfree == NULL) strm->bzfree = default_bzfree; - - s = BZALLOC( sizeof(DState) ); - if (s == NULL) return BZ_MEM_ERROR; - s->strm = strm; - strm->state = s; - s->state = BZ_X_MAGIC_1; - s->bsLive = 0; - s->bsBuff = 0; - s->calculatedCombinedCRC = 0; - strm->total_in_lo32 = 0; - strm->total_in_hi32 = 0; - strm->total_out_lo32 = 0; - strm->total_out_hi32 = 0; - s->smallDecompress = (Bool)small; - s->ll4 = NULL; - s->ll16 = NULL; - s->tt = NULL; - s->currBlockNo = 0; - s->verbosity = verbosity; - - return BZ_OK; -} - - -/*---------------------------------------------------*/ -/* Return True iff data corruption is discovered. - Returns False if there is no problem. -*/ -static -Bool unRLE_obuf_to_output_FAST ( DState* s ) -{ - UChar k1; - - if (s->blockRandomised) { - - while (True) { - /* try to finish existing run */ - while (True) { - if (s->strm->avail_out == 0) return False; - if (s->state_out_len == 0) break; - *( (UChar*)(s->strm->next_out) ) = s->state_out_ch; - BZ_UPDATE_CRC ( s->calculatedBlockCRC, s->state_out_ch ); - s->state_out_len--; - s->strm->next_out++; - s->strm->avail_out--; - s->strm->total_out_lo32++; - if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++; - } - - /* can a new run be started? */ - if (s->nblock_used == s->save_nblock+1) return False; - - /* Only caused by corrupt data stream? */ - if (s->nblock_used > s->save_nblock+1) - return True; - - s->state_out_len = 1; - s->state_out_ch = s->k0; - BZ_GET_FAST(k1); BZ_RAND_UPD_MASK; - k1 ^= BZ_RAND_MASK; s->nblock_used++; - if (s->nblock_used == s->save_nblock+1) continue; - if (k1 != s->k0) { s->k0 = k1; continue; }; - - s->state_out_len = 2; - BZ_GET_FAST(k1); BZ_RAND_UPD_MASK; - k1 ^= BZ_RAND_MASK; s->nblock_used++; - if (s->nblock_used == s->save_nblock+1) continue; - if (k1 != s->k0) { s->k0 = k1; continue; }; - - s->state_out_len = 3; - BZ_GET_FAST(k1); BZ_RAND_UPD_MASK; - k1 ^= BZ_RAND_MASK; s->nblock_used++; - if (s->nblock_used == s->save_nblock+1) continue; - if (k1 != s->k0) { s->k0 = k1; continue; }; - - BZ_GET_FAST(k1); BZ_RAND_UPD_MASK; - k1 ^= BZ_RAND_MASK; s->nblock_used++; - s->state_out_len = ((Int32)k1) + 4; - BZ_GET_FAST(s->k0); BZ_RAND_UPD_MASK; - s->k0 ^= BZ_RAND_MASK; s->nblock_used++; - } - - } else { - - /* restore */ - UInt32 c_calculatedBlockCRC = s->calculatedBlockCRC; - UChar c_state_out_ch = s->state_out_ch; - Int32 c_state_out_len = s->state_out_len; - Int32 c_nblock_used = s->nblock_used; - Int32 c_k0 = s->k0; - UInt32* c_tt = s->tt; - UInt32 c_tPos = s->tPos; - char* cs_next_out = s->strm->next_out; - unsigned int cs_avail_out = s->strm->avail_out; - Int32 ro_blockSize100k = s->blockSize100k; - /* end restore */ - - UInt32 avail_out_INIT = cs_avail_out; - Int32 s_save_nblockPP = s->save_nblock+1; - unsigned int total_out_lo32_old; - - while (True) { - - /* try to finish existing run */ - if (c_state_out_len > 0) { - while (True) { - if (cs_avail_out == 0) goto return_notr; - if (c_state_out_len == 1) break; - *( (UChar*)(cs_next_out) ) = c_state_out_ch; - BZ_UPDATE_CRC ( c_calculatedBlockCRC, c_state_out_ch ); - c_state_out_len--; - cs_next_out++; - cs_avail_out--; - } - s_state_out_len_eq_one: - { - if (cs_avail_out == 0) { - c_state_out_len = 1; goto return_notr; - }; - *( (UChar*)(cs_next_out) ) = c_state_out_ch; - BZ_UPDATE_CRC ( c_calculatedBlockCRC, c_state_out_ch ); - cs_next_out++; - cs_avail_out--; - } - } - /* Only caused by corrupt data stream? */ - if (c_nblock_used > s_save_nblockPP) - return True; - - /* can a new run be started? */ - if (c_nblock_used == s_save_nblockPP) { - c_state_out_len = 0; goto return_notr; - }; - c_state_out_ch = c_k0; - BZ_GET_FAST_C(k1); c_nblock_used++; - if (k1 != c_k0) { - c_k0 = k1; goto s_state_out_len_eq_one; - }; - if (c_nblock_used == s_save_nblockPP) - goto s_state_out_len_eq_one; - - c_state_out_len = 2; - BZ_GET_FAST_C(k1); c_nblock_used++; - if (c_nblock_used == s_save_nblockPP) continue; - if (k1 != c_k0) { c_k0 = k1; continue; }; - - c_state_out_len = 3; - BZ_GET_FAST_C(k1); c_nblock_used++; - if (c_nblock_used == s_save_nblockPP) continue; - if (k1 != c_k0) { c_k0 = k1; continue; }; - - BZ_GET_FAST_C(k1); c_nblock_used++; - c_state_out_len = ((Int32)k1) + 4; - BZ_GET_FAST_C(c_k0); c_nblock_used++; - } - - return_notr: - total_out_lo32_old = s->strm->total_out_lo32; - s->strm->total_out_lo32 += (avail_out_INIT - cs_avail_out); - if (s->strm->total_out_lo32 < total_out_lo32_old) - s->strm->total_out_hi32++; - - /* save */ - s->calculatedBlockCRC = c_calculatedBlockCRC; - s->state_out_ch = c_state_out_ch; - s->state_out_len = c_state_out_len; - s->nblock_used = c_nblock_used; - s->k0 = c_k0; - s->tt = c_tt; - s->tPos = c_tPos; - s->strm->next_out = cs_next_out; - s->strm->avail_out = cs_avail_out; - /* end save */ - } - return False; -} - - - -/*---------------------------------------------------*/ -__inline__ Int32 BZ2_indexIntoF ( Int32 indx, Int32 *cftab ) -{ - Int32 nb, na, mid; - nb = 0; - na = 256; - do { - mid = (nb + na) >> 1; - if (indx >= cftab[mid]) nb = mid; else na = mid; - } - while (na - nb != 1); - return nb; -} - - -/*---------------------------------------------------*/ -/* Return True iff data corruption is discovered. - Returns False if there is no problem. -*/ -static -Bool unRLE_obuf_to_output_SMALL ( DState* s ) -{ - UChar k1; - - if (s->blockRandomised) { - - while (True) { - /* try to finish existing run */ - while (True) { - if (s->strm->avail_out == 0) return False; - if (s->state_out_len == 0) break; - *( (UChar*)(s->strm->next_out) ) = s->state_out_ch; - BZ_UPDATE_CRC ( s->calculatedBlockCRC, s->state_out_ch ); - s->state_out_len--; - s->strm->next_out++; - s->strm->avail_out--; - s->strm->total_out_lo32++; - if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++; - } - - /* can a new run be started? */ - if (s->nblock_used == s->save_nblock+1) return False; - - /* Only caused by corrupt data stream? */ - if (s->nblock_used > s->save_nblock+1) - return True; - - s->state_out_len = 1; - s->state_out_ch = s->k0; - BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK; - k1 ^= BZ_RAND_MASK; s->nblock_used++; - if (s->nblock_used == s->save_nblock+1) continue; - if (k1 != s->k0) { s->k0 = k1; continue; }; - - s->state_out_len = 2; - BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK; - k1 ^= BZ_RAND_MASK; s->nblock_used++; - if (s->nblock_used == s->save_nblock+1) continue; - if (k1 != s->k0) { s->k0 = k1; continue; }; - - s->state_out_len = 3; - BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK; - k1 ^= BZ_RAND_MASK; s->nblock_used++; - if (s->nblock_used == s->save_nblock+1) continue; - if (k1 != s->k0) { s->k0 = k1; continue; }; - - BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK; - k1 ^= BZ_RAND_MASK; s->nblock_used++; - s->state_out_len = ((Int32)k1) + 4; - BZ_GET_SMALL(s->k0); BZ_RAND_UPD_MASK; - s->k0 ^= BZ_RAND_MASK; s->nblock_used++; - } - - } else { - - while (True) { - /* try to finish existing run */ - while (True) { - if (s->strm->avail_out == 0) return False; - if (s->state_out_len == 0) break; - *( (UChar*)(s->strm->next_out) ) = s->state_out_ch; - BZ_UPDATE_CRC ( s->calculatedBlockCRC, s->state_out_ch ); - s->state_out_len--; - s->strm->next_out++; - s->strm->avail_out--; - s->strm->total_out_lo32++; - if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++; - } - - /* can a new run be started? */ - if (s->nblock_used == s->save_nblock+1) return False; - - /* Only caused by corrupt data stream? */ - if (s->nblock_used > s->save_nblock+1) - return True; - - s->state_out_len = 1; - s->state_out_ch = s->k0; - BZ_GET_SMALL(k1); s->nblock_used++; - if (s->nblock_used == s->save_nblock+1) continue; - if (k1 != s->k0) { s->k0 = k1; continue; }; - - s->state_out_len = 2; - BZ_GET_SMALL(k1); s->nblock_used++; - if (s->nblock_used == s->save_nblock+1) continue; - if (k1 != s->k0) { s->k0 = k1; continue; }; - - s->state_out_len = 3; - BZ_GET_SMALL(k1); s->nblock_used++; - if (s->nblock_used == s->save_nblock+1) continue; - if (k1 != s->k0) { s->k0 = k1; continue; }; - - BZ_GET_SMALL(k1); s->nblock_used++; - s->state_out_len = ((Int32)k1) + 4; - BZ_GET_SMALL(s->k0); s->nblock_used++; - } - - } -} - - -/*---------------------------------------------------*/ -int BZ_API(BZ2_bzDecompress) ( bz_stream *strm ) -{ - Bool corrupt; - DState* s; - if (strm == NULL) return BZ_PARAM_ERROR; - s = strm->state; - if (s == NULL) return BZ_PARAM_ERROR; - if (s->strm != strm) return BZ_PARAM_ERROR; - - while (True) { - if (s->state == BZ_X_IDLE) return BZ_SEQUENCE_ERROR; - if (s->state == BZ_X_OUTPUT) { - if (s->smallDecompress) - corrupt = unRLE_obuf_to_output_SMALL ( s ); else - corrupt = unRLE_obuf_to_output_FAST ( s ); - if (corrupt) return BZ_DATA_ERROR; - if (s->nblock_used == s->save_nblock+1 && s->state_out_len == 0) { - BZ_FINALISE_CRC ( s->calculatedBlockCRC ); - if (s->verbosity >= 3) - VPrintf2 ( " {0x%08x, 0x%08x}", s->storedBlockCRC, - s->calculatedBlockCRC ); - if (s->verbosity >= 2) VPrintf0 ( "]" ); - if (s->calculatedBlockCRC != s->storedBlockCRC) - return BZ_DATA_ERROR; - s->calculatedCombinedCRC - = (s->calculatedCombinedCRC << 1) | - (s->calculatedCombinedCRC >> 31); - s->calculatedCombinedCRC ^= s->calculatedBlockCRC; - s->state = BZ_X_BLKHDR_1; - } else { - return BZ_OK; - } - } - if (s->state >= BZ_X_MAGIC_1) { - Int32 r = BZ2_decompress ( s ); - if (r == BZ_STREAM_END) { - if (s->verbosity >= 3) - VPrintf2 ( "\n combined CRCs: stored = 0x%08x, computed = 0x%08x", - s->storedCombinedCRC, s->calculatedCombinedCRC ); - if (s->calculatedCombinedCRC != s->storedCombinedCRC) - return BZ_DATA_ERROR; - return r; - } - if (s->state != BZ_X_OUTPUT) return r; - } - } - - AssertH ( 0, 6001 ); - - return 0; /*NOTREACHED*/ -} - - -/*---------------------------------------------------*/ -int BZ_API(BZ2_bzDecompressEnd) ( bz_stream *strm ) -{ - DState* s; - if (strm == NULL) return BZ_PARAM_ERROR; - s = strm->state; - if (s == NULL) return BZ_PARAM_ERROR; - if (s->strm != strm) return BZ_PARAM_ERROR; - - if (s->tt != NULL) BZFREE(s->tt); - if (s->ll16 != NULL) BZFREE(s->ll16); - if (s->ll4 != NULL) BZFREE(s->ll4); - - BZFREE(strm->state); - strm->state = NULL; - - return BZ_OK; -} - - -#ifndef BZ_NO_STDIO -/*---------------------------------------------------*/ -/*--- File I/O stuff ---*/ -/*---------------------------------------------------*/ - -#define BZ_SETERR(eee) \ -{ \ - if (bzerror != NULL) *bzerror = eee; \ - if (bzf != NULL) bzf->lastErr = eee; \ -} - -typedef - struct { - FILE* handle; - Char buf[BZ_MAX_UNUSED]; - Int32 bufN; - Bool writing; - bz_stream strm; - Int32 lastErr; - Bool initialisedOk; - } - bzFile; - - -/*---------------------------------------------*/ -static Bool myfeof ( FILE* f ) -{ - Int32 c = fgetc ( f ); - if (c == EOF) return True; - ungetc ( c, f ); - return False; -} - - -/*---------------------------------------------------*/ -BZFILE* BZ_API(BZ2_bzWriteOpen) - ( int* bzerror, - FILE* f, - int blockSize100k, - int verbosity, - int workFactor ) -{ - Int32 ret; - bzFile* bzf = NULL; - - BZ_SETERR(BZ_OK); - - if (f == NULL || - (blockSize100k < 1 || blockSize100k > 9) || - (workFactor < 0 || workFactor > 250) || - (verbosity < 0 || verbosity > 4)) - { BZ_SETERR(BZ_PARAM_ERROR); return NULL; }; - - if (ferror(f)) - { BZ_SETERR(BZ_IO_ERROR); return NULL; }; - - bzf = malloc ( sizeof(bzFile) ); - if (bzf == NULL) - { BZ_SETERR(BZ_MEM_ERROR); return NULL; }; - - BZ_SETERR(BZ_OK); - bzf->initialisedOk = False; - bzf->bufN = 0; - bzf->handle = f; - bzf->writing = True; - bzf->strm.bzalloc = NULL; - bzf->strm.bzfree = NULL; - bzf->strm.opaque = NULL; - - if (workFactor == 0) workFactor = 30; - ret = BZ2_bzCompressInit ( &(bzf->strm), blockSize100k, - verbosity, workFactor ); - if (ret != BZ_OK) - { BZ_SETERR(ret); free(bzf); return NULL; }; - - bzf->strm.avail_in = 0; - bzf->initialisedOk = True; - return bzf; -} - - - -/*---------------------------------------------------*/ -void BZ_API(BZ2_bzWrite) - ( int* bzerror, - BZFILE* b, - void* buf, - int len ) -{ - Int32 n, n2, ret; - bzFile* bzf = (bzFile*)b; - - BZ_SETERR(BZ_OK); - if (bzf == NULL || buf == NULL || len < 0) - { BZ_SETERR(BZ_PARAM_ERROR); return; }; - if (!(bzf->writing)) - { BZ_SETERR(BZ_SEQUENCE_ERROR); return; }; - if (ferror(bzf->handle)) - { BZ_SETERR(BZ_IO_ERROR); return; }; - - if (len == 0) - { BZ_SETERR(BZ_OK); return; }; - - bzf->strm.avail_in = len; - bzf->strm.next_in = buf; - - while (True) { - bzf->strm.avail_out = BZ_MAX_UNUSED; - bzf->strm.next_out = bzf->buf; - ret = BZ2_bzCompress ( &(bzf->strm), BZ_RUN ); - if (ret != BZ_RUN_OK) - { BZ_SETERR(ret); return; }; - - if (bzf->strm.avail_out < BZ_MAX_UNUSED) { - n = BZ_MAX_UNUSED - bzf->strm.avail_out; - n2 = fwrite ( (void*)(bzf->buf), sizeof(UChar), - n, bzf->handle ); - if (n != n2 || ferror(bzf->handle)) - { BZ_SETERR(BZ_IO_ERROR); return; }; - } - - if (bzf->strm.avail_in == 0) - { BZ_SETERR(BZ_OK); return; }; - } -} - - -/*---------------------------------------------------*/ -void BZ_API(BZ2_bzWriteClose) - ( int* bzerror, - BZFILE* b, - int abandon, - unsigned int* nbytes_in, - unsigned int* nbytes_out ) -{ - BZ2_bzWriteClose64 ( bzerror, b, abandon, - nbytes_in, NULL, nbytes_out, NULL ); -} - - -void BZ_API(BZ2_bzWriteClose64) - ( int* bzerror, - BZFILE* b, - int abandon, - unsigned int* nbytes_in_lo32, - unsigned int* nbytes_in_hi32, - unsigned int* nbytes_out_lo32, - unsigned int* nbytes_out_hi32 ) -{ - Int32 n, n2, ret; - bzFile* bzf = (bzFile*)b; - - if (bzf == NULL) - { BZ_SETERR(BZ_OK); return; }; - if (!(bzf->writing)) - { BZ_SETERR(BZ_SEQUENCE_ERROR); return; }; - if (ferror(bzf->handle)) - { BZ_SETERR(BZ_IO_ERROR); return; }; - - if (nbytes_in_lo32 != NULL) *nbytes_in_lo32 = 0; - if (nbytes_in_hi32 != NULL) *nbytes_in_hi32 = 0; - if (nbytes_out_lo32 != NULL) *nbytes_out_lo32 = 0; - if (nbytes_out_hi32 != NULL) *nbytes_out_hi32 = 0; - - if ((!abandon) && bzf->lastErr == BZ_OK) { - while (True) { - bzf->strm.avail_out = BZ_MAX_UNUSED; - bzf->strm.next_out = bzf->buf; - ret = BZ2_bzCompress ( &(bzf->strm), BZ_FINISH ); - if (ret != BZ_FINISH_OK && ret != BZ_STREAM_END) - { BZ_SETERR(ret); return; }; - - if (bzf->strm.avail_out < BZ_MAX_UNUSED) { - n = BZ_MAX_UNUSED - bzf->strm.avail_out; - n2 = fwrite ( (void*)(bzf->buf), sizeof(UChar), - n, bzf->handle ); - if (n != n2 || ferror(bzf->handle)) - { BZ_SETERR(BZ_IO_ERROR); return; }; - } - - if (ret == BZ_STREAM_END) break; - } - } - - if ( !abandon && !ferror ( bzf->handle ) ) { - fflush ( bzf->handle ); - if (ferror(bzf->handle)) - { BZ_SETERR(BZ_IO_ERROR); return; }; - } - - if (nbytes_in_lo32 != NULL) - *nbytes_in_lo32 = bzf->strm.total_in_lo32; - if (nbytes_in_hi32 != NULL) - *nbytes_in_hi32 = bzf->strm.total_in_hi32; - if (nbytes_out_lo32 != NULL) - *nbytes_out_lo32 = bzf->strm.total_out_lo32; - if (nbytes_out_hi32 != NULL) - *nbytes_out_hi32 = bzf->strm.total_out_hi32; - - BZ_SETERR(BZ_OK); - BZ2_bzCompressEnd ( &(bzf->strm) ); - free ( bzf ); -} - - -/*---------------------------------------------------*/ -BZFILE* BZ_API(BZ2_bzReadOpen) - ( int* bzerror, - FILE* f, - int verbosity, - int small, - void* unused, - int nUnused ) -{ - bzFile* bzf = NULL; - int ret; - - BZ_SETERR(BZ_OK); - - if (f == NULL || - (small != 0 && small != 1) || - (verbosity < 0 || verbosity > 4) || - (unused == NULL && nUnused != 0) || - (unused != NULL && (nUnused < 0 || nUnused > BZ_MAX_UNUSED))) - { BZ_SETERR(BZ_PARAM_ERROR); return NULL; }; - - if (ferror(f)) - { BZ_SETERR(BZ_IO_ERROR); return NULL; }; - - bzf = malloc ( sizeof(bzFile) ); - if (bzf == NULL) - { BZ_SETERR(BZ_MEM_ERROR); return NULL; }; - - BZ_SETERR(BZ_OK); - - bzf->initialisedOk = False; - bzf->handle = f; - bzf->bufN = 0; - bzf->writing = False; - bzf->strm.bzalloc = NULL; - bzf->strm.bzfree = NULL; - bzf->strm.opaque = NULL; - - while (nUnused > 0) { - bzf->buf[bzf->bufN] = *((UChar*)(unused)); bzf->bufN++; - unused = ((void*)( 1 + ((UChar*)(unused)) )); - nUnused--; - } - - ret = BZ2_bzDecompressInit ( &(bzf->strm), verbosity, small ); - if (ret != BZ_OK) - { BZ_SETERR(ret); free(bzf); return NULL; }; - - bzf->strm.avail_in = bzf->bufN; - bzf->strm.next_in = bzf->buf; - - bzf->initialisedOk = True; - return bzf; -} - - -/*---------------------------------------------------*/ -void BZ_API(BZ2_bzReadClose) ( int *bzerror, BZFILE *b ) -{ - bzFile* bzf = (bzFile*)b; - - BZ_SETERR(BZ_OK); - if (bzf == NULL) - { BZ_SETERR(BZ_OK); return; }; - - if (bzf->writing) - { BZ_SETERR(BZ_SEQUENCE_ERROR); return; }; - - if (bzf->initialisedOk) - (void)BZ2_bzDecompressEnd ( &(bzf->strm) ); - free ( bzf ); -} - - -/*---------------------------------------------------*/ -int BZ_API(BZ2_bzRead) - ( int* bzerror, - BZFILE* b, - void* buf, - int len ) -{ - Int32 n, ret; - bzFile* bzf = (bzFile*)b; - - BZ_SETERR(BZ_OK); - - if (bzf == NULL || buf == NULL || len < 0) - { BZ_SETERR(BZ_PARAM_ERROR); return 0; }; - - if (bzf->writing) - { BZ_SETERR(BZ_SEQUENCE_ERROR); return 0; }; - - if (len == 0) - { BZ_SETERR(BZ_OK); return 0; }; - - bzf->strm.avail_out = len; - bzf->strm.next_out = buf; - - while (True) { - - if (ferror(bzf->handle)) - { BZ_SETERR(BZ_IO_ERROR); return 0; }; - - if (bzf->strm.avail_in == 0 && !myfeof(bzf->handle)) { - n = fread ( bzf->buf, sizeof(UChar), - BZ_MAX_UNUSED, bzf->handle ); - if (ferror(bzf->handle)) - { BZ_SETERR(BZ_IO_ERROR); return 0; }; - bzf->bufN = n; - bzf->strm.avail_in = bzf->bufN; - bzf->strm.next_in = bzf->buf; - } - - ret = BZ2_bzDecompress ( &(bzf->strm) ); - - if (ret != BZ_OK && ret != BZ_STREAM_END) - { BZ_SETERR(ret); return 0; }; - - if (ret == BZ_OK && myfeof(bzf->handle) && - bzf->strm.avail_in == 0 && bzf->strm.avail_out > 0) - { BZ_SETERR(BZ_UNEXPECTED_EOF); return 0; }; - - if (ret == BZ_STREAM_END) - { BZ_SETERR(BZ_STREAM_END); - return len - bzf->strm.avail_out; }; - if (bzf->strm.avail_out == 0) - { BZ_SETERR(BZ_OK); return len; }; - - } - - return 0; /*not reached*/ -} - - -/*---------------------------------------------------*/ -void BZ_API(BZ2_bzReadGetUnused) - ( int* bzerror, - BZFILE* b, - void** unused, - int* nUnused ) -{ - bzFile* bzf = (bzFile*)b; - if (bzf == NULL) - { BZ_SETERR(BZ_PARAM_ERROR); return; }; - if (bzf->lastErr != BZ_STREAM_END) - { BZ_SETERR(BZ_SEQUENCE_ERROR); return; }; - if (unused == NULL || nUnused == NULL) - { BZ_SETERR(BZ_PARAM_ERROR); return; }; - - BZ_SETERR(BZ_OK); - *nUnused = bzf->strm.avail_in; - *unused = bzf->strm.next_in; -} -#endif - - -/*---------------------------------------------------*/ -/*--- Misc convenience stuff ---*/ -/*---------------------------------------------------*/ - -/*---------------------------------------------------*/ -int BZ_API(BZ2_bzBuffToBuffCompress) - ( char* dest, - unsigned int* destLen, - char* source, - unsigned int sourceLen, - int blockSize100k, - int verbosity, - int workFactor ) -{ - bz_stream strm; - int ret; - - if (dest == NULL || destLen == NULL || - source == NULL || - blockSize100k < 1 || blockSize100k > 9 || - verbosity < 0 || verbosity > 4 || - workFactor < 0 || workFactor > 250) - return BZ_PARAM_ERROR; - - if (workFactor == 0) workFactor = 30; - strm.bzalloc = NULL; - strm.bzfree = NULL; - strm.opaque = NULL; - ret = BZ2_bzCompressInit ( &strm, blockSize100k, - verbosity, workFactor ); - if (ret != BZ_OK) return ret; - - strm.next_in = source; - strm.next_out = dest; - strm.avail_in = sourceLen; - strm.avail_out = *destLen; - - ret = BZ2_bzCompress ( &strm, BZ_FINISH ); - if (ret == BZ_FINISH_OK) goto output_overflow; - if (ret != BZ_STREAM_END) goto errhandler; - - /* normal termination */ - *destLen -= strm.avail_out; - BZ2_bzCompressEnd ( &strm ); - return BZ_OK; - - output_overflow: - BZ2_bzCompressEnd ( &strm ); - return BZ_OUTBUFF_FULL; - - errhandler: - BZ2_bzCompressEnd ( &strm ); - return ret; -} - - -/*---------------------------------------------------*/ -int BZ_API(BZ2_bzBuffToBuffDecompress) - ( char* dest, - unsigned int* destLen, - char* source, - unsigned int sourceLen, - int small, - int verbosity ) -{ - bz_stream strm; - int ret; - - if (dest == NULL || destLen == NULL || - source == NULL || - (small != 0 && small != 1) || - verbosity < 0 || verbosity > 4) - return BZ_PARAM_ERROR; - - strm.bzalloc = NULL; - strm.bzfree = NULL; - strm.opaque = NULL; - ret = BZ2_bzDecompressInit ( &strm, verbosity, small ); - if (ret != BZ_OK) return ret; - - strm.next_in = source; - strm.next_out = dest; - strm.avail_in = sourceLen; - strm.avail_out = *destLen; - - ret = BZ2_bzDecompress ( &strm ); - if (ret == BZ_OK) goto output_overflow_or_eof; - if (ret != BZ_STREAM_END) goto errhandler; - - /* normal termination */ - *destLen -= strm.avail_out; - BZ2_bzDecompressEnd ( &strm ); - return BZ_OK; - - output_overflow_or_eof: - if (strm.avail_out > 0) { - BZ2_bzDecompressEnd ( &strm ); - return BZ_UNEXPECTED_EOF; - } else { - BZ2_bzDecompressEnd ( &strm ); - return BZ_OUTBUFF_FULL; - }; - - errhandler: - BZ2_bzDecompressEnd ( &strm ); - return ret; -} - - -/*---------------------------------------------------*/ -/*-- - Code contributed by Yoshioka Tsuneo (tsuneo@rr.iij4u.or.jp) - to support better zlib compatibility. - This code is not _officially_ part of libbzip2 (yet); - I haven't tested it, documented it, or considered the - threading-safeness of it. - If this code breaks, please contact both Yoshioka and me. ---*/ -/*---------------------------------------------------*/ - -/*---------------------------------------------------*/ -/*-- - return version like "0.9.5d, 4-Sept-1999". ---*/ -const char * BZ_API(BZ2_bzlibVersion)(void) -{ - return BZ_VERSION; -} - - -#ifndef BZ_NO_STDIO -/*---------------------------------------------------*/ - -#if defined(_WIN32) || defined(OS2) || defined(MSDOS) -# include -# include -# define SET_BINARY_MODE(file) setmode(fileno(file),O_BINARY) -#else -# define SET_BINARY_MODE(file) -#endif -static -BZFILE * bzopen_or_bzdopen - ( const char *path, /* no use when bzdopen */ - int fd, /* no use when bzdopen */ - const char *mode, - int open_mode) /* bzopen: 0, bzdopen:1 */ -{ - int bzerr; - char unused[BZ_MAX_UNUSED]; - int blockSize100k = 9; - int writing = 0; - char mode2[10] = ""; - FILE *fp = NULL; - BZFILE *bzfp = NULL; - int verbosity = 0; - int workFactor = 30; - int smallMode = 0; - int nUnused = 0; - - if (mode == NULL) return NULL; - while (*mode) { - switch (*mode) { - case 'r': - writing = 0; break; - case 'w': - writing = 1; break; - case 's': - smallMode = 1; break; - default: - if (isdigit((int)(*mode))) { - blockSize100k = *mode-BZ_HDR_0; - } - } - mode++; - } - strcat(mode2, writing ? "w" : "r" ); - strcat(mode2,"b"); /* binary mode */ - - if (open_mode==0) { - if (path==NULL || strcmp(path,"")==0) { - fp = (writing ? stdout : stdin); - SET_BINARY_MODE(fp); - } else { - fp = fopen(path,mode2); - } - } else { -#ifdef BZ_STRICT_ANSI - fp = NULL; -#else - fp = fdopen(fd,mode2); -#endif - } - if (fp == NULL) return NULL; - - if (writing) { - /* Guard against total chaos and anarchy -- JRS */ - if (blockSize100k < 1) blockSize100k = 1; - if (blockSize100k > 9) blockSize100k = 9; - bzfp = BZ2_bzWriteOpen(&bzerr,fp,blockSize100k, - verbosity,workFactor); - } else { - bzfp = BZ2_bzReadOpen(&bzerr,fp,verbosity,smallMode, - unused,nUnused); - } - if (bzfp == NULL) { - if (fp != stdin && fp != stdout) fclose(fp); - return NULL; - } - return bzfp; -} - - -/*---------------------------------------------------*/ -/*-- - open file for read or write. - ex) bzopen("file","w9") - case path="" or NULL => use stdin or stdout. ---*/ -BZFILE * BZ_API(BZ2_bzopen) - ( const char *path, - const char *mode ) -{ - return bzopen_or_bzdopen(path,-1,mode,/*bzopen*/0); -} - - -/*---------------------------------------------------*/ -BZFILE * BZ_API(BZ2_bzdopen) - ( int fd, - const char *mode ) -{ - return bzopen_or_bzdopen(NULL,fd,mode,/*bzdopen*/1); -} - - -/*---------------------------------------------------*/ -int BZ_API(BZ2_bzread) (BZFILE* b, void* buf, int len ) -{ - int bzerr, nread; - if (((bzFile*)b)->lastErr == BZ_STREAM_END) return 0; - nread = BZ2_bzRead(&bzerr,b,buf,len); - if (bzerr == BZ_OK || bzerr == BZ_STREAM_END) { - return nread; - } else { - return -1; - } -} - - -/*---------------------------------------------------*/ -int BZ_API(BZ2_bzwrite) (BZFILE* b, void* buf, int len ) -{ - int bzerr; - - BZ2_bzWrite(&bzerr,b,buf,len); - if(bzerr == BZ_OK){ - return len; - }else{ - return -1; - } -} - - -/*---------------------------------------------------*/ -int BZ_API(BZ2_bzflush) (BZFILE *b) -{ - /* do nothing now... */ - return 0; -} - - -/*---------------------------------------------------*/ -void BZ_API(BZ2_bzclose) (BZFILE* b) -{ - int bzerr; - FILE *fp; - - if (b==NULL) {return;} - fp = ((bzFile *)b)->handle; - if(((bzFile*)b)->writing){ - BZ2_bzWriteClose(&bzerr,b,0,NULL,NULL); - if(bzerr != BZ_OK){ - BZ2_bzWriteClose(NULL,b,1,NULL,NULL); - } - }else{ - BZ2_bzReadClose(&bzerr,b); - } - if(fp!=stdin && fp!=stdout){ - fclose(fp); - } -} - - -/*---------------------------------------------------*/ -/*-- - return last error code ---*/ -static const char *bzerrorstrings[] = { - "OK" - ,"SEQUENCE_ERROR" - ,"PARAM_ERROR" - ,"MEM_ERROR" - ,"DATA_ERROR" - ,"DATA_ERROR_MAGIC" - ,"IO_ERROR" - ,"UNEXPECTED_EOF" - ,"OUTBUFF_FULL" - ,"CONFIG_ERROR" - ,"???" /* for future */ - ,"???" /* for future */ - ,"???" /* for future */ - ,"???" /* for future */ - ,"???" /* for future */ - ,"???" /* for future */ -}; - - -const char * BZ_API(BZ2_bzerror) (BZFILE *b, int *errnum) -{ - int err = ((bzFile *)b)->lastErr; - - if(err>0) err = 0; - *errnum = err; - return bzerrorstrings[err*-1]; -} -#endif - - -/*-------------------------------------------------------------*/ -/*--- end bzlib.c ---*/ -/*-------------------------------------------------------------*/ diff --git a/externals/bzip2/bzlib.h b/externals/bzip2/bzlib.h deleted file mode 100644 index c5b75d6d8ff..00000000000 --- a/externals/bzip2/bzlib.h +++ /dev/null @@ -1,282 +0,0 @@ - -/*-------------------------------------------------------------*/ -/*--- Public header file for the library. ---*/ -/*--- bzlib.h ---*/ -/*-------------------------------------------------------------*/ - -/* ------------------------------------------------------------------ - This file is part of bzip2/libbzip2, a program and library for - lossless, block-sorting data compression. - - bzip2/libbzip2 version 1.0.5 of 10 December 2007 - Copyright (C) 1996-2007 Julian Seward - - Please read the WARNING, DISCLAIMER and PATENTS sections in the - README file. - - This program is released under the terms of the license contained - in the file LICENSE. - ------------------------------------------------------------------ */ - - -#ifndef _BZLIB_H -#define _BZLIB_H - -#ifdef __cplusplus -extern "C" { -#endif - -#define BZ_RUN 0 -#define BZ_FLUSH 1 -#define BZ_FINISH 2 - -#define BZ_OK 0 -#define BZ_RUN_OK 1 -#define BZ_FLUSH_OK 2 -#define BZ_FINISH_OK 3 -#define BZ_STREAM_END 4 -#define BZ_SEQUENCE_ERROR (-1) -#define BZ_PARAM_ERROR (-2) -#define BZ_MEM_ERROR (-3) -#define BZ_DATA_ERROR (-4) -#define BZ_DATA_ERROR_MAGIC (-5) -#define BZ_IO_ERROR (-6) -#define BZ_UNEXPECTED_EOF (-7) -#define BZ_OUTBUFF_FULL (-8) -#define BZ_CONFIG_ERROR (-9) - -typedef - struct { - char *next_in; - unsigned int avail_in; - unsigned int total_in_lo32; - unsigned int total_in_hi32; - - char *next_out; - unsigned int avail_out; - unsigned int total_out_lo32; - unsigned int total_out_hi32; - - void *state; - - void *(*bzalloc)(void *,int,int); - void (*bzfree)(void *,void *); - void *opaque; - } - bz_stream; - - -#ifndef BZ_IMPORT -#define BZ_EXPORT -#endif - -#ifndef BZ_NO_STDIO -/* Need a definitition for FILE */ -#include -#endif - -#ifdef _WIN32 -# include -# ifdef small - /* windows.h define small to char */ -# undef small -# endif -# ifdef BZ_EXPORT -# define BZ_API(func) WINAPI func -# define BZ_EXTERN extern -# else - /* import windows dll dynamically */ -# define BZ_API(func) (WINAPI * func) -# define BZ_EXTERN -# endif -#else -# define BZ_API(func) func -# define BZ_EXTERN extern -#endif - - -/*-- Core (low-level) library functions --*/ - -BZ_EXTERN int BZ_API(BZ2_bzCompressInit) ( - bz_stream* strm, - int blockSize100k, - int verbosity, - int workFactor - ); - -BZ_EXTERN int BZ_API(BZ2_bzCompress) ( - bz_stream* strm, - int action - ); - -BZ_EXTERN int BZ_API(BZ2_bzCompressEnd) ( - bz_stream* strm - ); - -BZ_EXTERN int BZ_API(BZ2_bzDecompressInit) ( - bz_stream *strm, - int verbosity, - int small - ); - -BZ_EXTERN int BZ_API(BZ2_bzDecompress) ( - bz_stream* strm - ); - -BZ_EXTERN int BZ_API(BZ2_bzDecompressEnd) ( - bz_stream *strm - ); - - - -/*-- High(er) level library functions --*/ - -#ifndef BZ_NO_STDIO -#define BZ_MAX_UNUSED 5000 - -typedef void BZFILE; - -BZ_EXTERN BZFILE* BZ_API(BZ2_bzReadOpen) ( - int* bzerror, - FILE* f, - int verbosity, - int small, - void* unused, - int nUnused - ); - -BZ_EXTERN void BZ_API(BZ2_bzReadClose) ( - int* bzerror, - BZFILE* b - ); - -BZ_EXTERN void BZ_API(BZ2_bzReadGetUnused) ( - int* bzerror, - BZFILE* b, - void** unused, - int* nUnused - ); - -BZ_EXTERN int BZ_API(BZ2_bzRead) ( - int* bzerror, - BZFILE* b, - void* buf, - int len - ); - -BZ_EXTERN BZFILE* BZ_API(BZ2_bzWriteOpen) ( - int* bzerror, - FILE* f, - int blockSize100k, - int verbosity, - int workFactor - ); - -BZ_EXTERN void BZ_API(BZ2_bzWrite) ( - int* bzerror, - BZFILE* b, - void* buf, - int len - ); - -BZ_EXTERN void BZ_API(BZ2_bzWriteClose) ( - int* bzerror, - BZFILE* b, - int abandon, - unsigned int* nbytes_in, - unsigned int* nbytes_out - ); - -BZ_EXTERN void BZ_API(BZ2_bzWriteClose64) ( - int* bzerror, - BZFILE* b, - int abandon, - unsigned int* nbytes_in_lo32, - unsigned int* nbytes_in_hi32, - unsigned int* nbytes_out_lo32, - unsigned int* nbytes_out_hi32 - ); -#endif - - -/*-- Utility functions --*/ - -BZ_EXTERN int BZ_API(BZ2_bzBuffToBuffCompress) ( - char* dest, - unsigned int* destLen, - char* source, - unsigned int sourceLen, - int blockSize100k, - int verbosity, - int workFactor - ); - -BZ_EXTERN int BZ_API(BZ2_bzBuffToBuffDecompress) ( - char* dest, - unsigned int* destLen, - char* source, - unsigned int sourceLen, - int small, - int verbosity - ); - - -/*-- - Code contributed by Yoshioka Tsuneo (tsuneo@rr.iij4u.or.jp) - to support better zlib compatibility. - This code is not _officially_ part of libbzip2 (yet); - I haven't tested it, documented it, or considered the - threading-safeness of it. - If this code breaks, please contact both Yoshioka and me. ---*/ - -BZ_EXTERN const char * BZ_API(BZ2_bzlibVersion) ( - void - ); - -#ifndef BZ_NO_STDIO -BZ_EXTERN BZFILE * BZ_API(BZ2_bzopen) ( - const char *path, - const char *mode - ); - -BZ_EXTERN BZFILE * BZ_API(BZ2_bzdopen) ( - int fd, - const char *mode - ); - -BZ_EXTERN int BZ_API(BZ2_bzread) ( - BZFILE* b, - void* buf, - int len - ); - -BZ_EXTERN int BZ_API(BZ2_bzwrite) ( - BZFILE* b, - void* buf, - int len - ); - -BZ_EXTERN int BZ_API(BZ2_bzflush) ( - BZFILE* b - ); - -BZ_EXTERN void BZ_API(BZ2_bzclose) ( - BZFILE* b - ); - -BZ_EXTERN const char * BZ_API(BZ2_bzerror) ( - BZFILE *b, - int *errnum - ); -#endif - -#ifdef __cplusplus -} -#endif - -#endif - -/*-------------------------------------------------------------*/ -/*--- end bzlib.h ---*/ -/*-------------------------------------------------------------*/ diff --git a/externals/bzip2/bzlib_private.h b/externals/bzip2/bzlib_private.h deleted file mode 100644 index 23427879b18..00000000000 --- a/externals/bzip2/bzlib_private.h +++ /dev/null @@ -1,509 +0,0 @@ - -/*-------------------------------------------------------------*/ -/*--- Private header file for the library. ---*/ -/*--- bzlib_private.h ---*/ -/*-------------------------------------------------------------*/ - -/* ------------------------------------------------------------------ - This file is part of bzip2/libbzip2, a program and library for - lossless, block-sorting data compression. - - bzip2/libbzip2 version 1.0.5 of 10 December 2007 - Copyright (C) 1996-2007 Julian Seward - - Please read the WARNING, DISCLAIMER and PATENTS sections in the - README file. - - This program is released under the terms of the license contained - in the file LICENSE. - ------------------------------------------------------------------ */ - - -#ifndef _BZLIB_PRIVATE_H -#define _BZLIB_PRIVATE_H - -#include - -#ifndef BZ_NO_STDIO -#include -#include -#include -#endif - -#include "bzlib.h" - - - -/*-- General stuff. --*/ - -#define BZ_VERSION "1.0.5, 10-Dec-2007" - -typedef char Char; -typedef unsigned char Bool; -typedef unsigned char UChar; -typedef int Int32; -typedef unsigned int UInt32; -typedef short Int16; -typedef unsigned short UInt16; - -#define True ((Bool)1) -#define False ((Bool)0) - -#ifndef __GNUC__ -#define __inline__ /* */ -#endif - -#ifndef BZ_NO_STDIO - -extern void BZ2_bz__AssertH__fail ( int errcode ); -#define AssertH(cond,errcode) \ - { if (!(cond)) BZ2_bz__AssertH__fail ( errcode ); } - -#if BZ_DEBUG -#define AssertD(cond,msg) \ - { if (!(cond)) { \ - fprintf ( stderr, \ - "\n\nlibbzip2(debug build): internal error\n\t%s\n", msg );\ - exit(1); \ - }} -#else -#define AssertD(cond,msg) /* */ -#endif - -#define VPrintf0(zf) \ - fprintf(stderr,zf) -#define VPrintf1(zf,za1) \ - fprintf(stderr,zf,za1) -#define VPrintf2(zf,za1,za2) \ - fprintf(stderr,zf,za1,za2) -#define VPrintf3(zf,za1,za2,za3) \ - fprintf(stderr,zf,za1,za2,za3) -#define VPrintf4(zf,za1,za2,za3,za4) \ - fprintf(stderr,zf,za1,za2,za3,za4) -#define VPrintf5(zf,za1,za2,za3,za4,za5) \ - fprintf(stderr,zf,za1,za2,za3,za4,za5) - -#else - -extern void bz_internal_error ( int errcode ); -#define AssertH(cond,errcode) \ - { if (!(cond)) bz_internal_error ( errcode ); } -#define AssertD(cond,msg) do { } while (0) -#define VPrintf0(zf) do { } while (0) -#define VPrintf1(zf,za1) do { } while (0) -#define VPrintf2(zf,za1,za2) do { } while (0) -#define VPrintf3(zf,za1,za2,za3) do { } while (0) -#define VPrintf4(zf,za1,za2,za3,za4) do { } while (0) -#define VPrintf5(zf,za1,za2,za3,za4,za5) do { } while (0) - -#endif - - -#define BZALLOC(nnn) (strm->bzalloc)(strm->opaque,(nnn),1) -#define BZFREE(ppp) (strm->bzfree)(strm->opaque,(ppp)) - - -/*-- Header bytes. --*/ - -#define BZ_HDR_B 0x42 /* 'B' */ -#define BZ_HDR_Z 0x5a /* 'Z' */ -#define BZ_HDR_h 0x68 /* 'h' */ -#define BZ_HDR_0 0x30 /* '0' */ - -/*-- Constants for the back end. --*/ - -#define BZ_MAX_ALPHA_SIZE 258 -#define BZ_MAX_CODE_LEN 23 - -#define BZ_RUNA 0 -#define BZ_RUNB 1 - -#define BZ_N_GROUPS 6 -#define BZ_G_SIZE 50 -#define BZ_N_ITERS 4 - -#define BZ_MAX_SELECTORS (2 + (900000 / BZ_G_SIZE)) - - - -/*-- Stuff for randomising repetitive blocks. --*/ - -extern Int32 BZ2_rNums[512]; - -#define BZ_RAND_DECLS \ - Int32 rNToGo; \ - Int32 rTPos \ - -#define BZ_RAND_INIT_MASK \ - s->rNToGo = 0; \ - s->rTPos = 0 \ - -#define BZ_RAND_MASK ((s->rNToGo == 1) ? 1 : 0) - -#define BZ_RAND_UPD_MASK \ - if (s->rNToGo == 0) { \ - s->rNToGo = BZ2_rNums[s->rTPos]; \ - s->rTPos++; \ - if (s->rTPos == 512) s->rTPos = 0; \ - } \ - s->rNToGo--; - - - -/*-- Stuff for doing CRCs. --*/ - -extern UInt32 BZ2_crc32Table[256]; - -#define BZ_INITIALISE_CRC(crcVar) \ -{ \ - crcVar = 0xffffffffL; \ -} - -#define BZ_FINALISE_CRC(crcVar) \ -{ \ - crcVar = ~(crcVar); \ -} - -#define BZ_UPDATE_CRC(crcVar,cha) \ -{ \ - crcVar = (crcVar << 8) ^ \ - BZ2_crc32Table[(crcVar >> 24) ^ \ - ((UChar)cha)]; \ -} - - - -/*-- States and modes for compression. --*/ - -#define BZ_M_IDLE 1 -#define BZ_M_RUNNING 2 -#define BZ_M_FLUSHING 3 -#define BZ_M_FINISHING 4 - -#define BZ_S_OUTPUT 1 -#define BZ_S_INPUT 2 - -#define BZ_N_RADIX 2 -#define BZ_N_QSORT 12 -#define BZ_N_SHELL 18 -#define BZ_N_OVERSHOOT (BZ_N_RADIX + BZ_N_QSORT + BZ_N_SHELL + 2) - - - - -/*-- Structure holding all the compression-side stuff. --*/ - -typedef - struct { - /* pointer back to the struct bz_stream */ - bz_stream* strm; - - /* mode this stream is in, and whether inputting */ - /* or outputting data */ - Int32 mode; - Int32 state; - - /* remembers avail_in when flush/finish requested */ - UInt32 avail_in_expect; - - /* for doing the block sorting */ - UInt32* arr1; - UInt32* arr2; - UInt32* ftab; - Int32 origPtr; - - /* aliases for arr1 and arr2 */ - UInt32* ptr; - UChar* block; - UInt16* mtfv; - UChar* zbits; - - /* for deciding when to use the fallback sorting algorithm */ - Int32 workFactor; - - /* run-length-encoding of the input */ - UInt32 state_in_ch; - Int32 state_in_len; - BZ_RAND_DECLS; - - /* input and output limits and current posns */ - Int32 nblock; - Int32 nblockMAX; - Int32 numZ; - Int32 state_out_pos; - - /* map of bytes used in block */ - Int32 nInUse; - Bool inUse[256]; - UChar unseqToSeq[256]; - - /* the buffer for bit stream creation */ - UInt32 bsBuff; - Int32 bsLive; - - /* block and combined CRCs */ - UInt32 blockCRC; - UInt32 combinedCRC; - - /* misc administratium */ - Int32 verbosity; - Int32 blockNo; - Int32 blockSize100k; - - /* stuff for coding the MTF values */ - Int32 nMTF; - Int32 mtfFreq [BZ_MAX_ALPHA_SIZE]; - UChar selector [BZ_MAX_SELECTORS]; - UChar selectorMtf[BZ_MAX_SELECTORS]; - - UChar len [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; - Int32 code [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; - Int32 rfreq [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; - /* second dimension: only 3 needed; 4 makes index calculations faster */ - UInt32 len_pack[BZ_MAX_ALPHA_SIZE][4]; - - } - EState; - - - -/*-- externs for compression. --*/ - -extern void -BZ2_blockSort ( EState* ); - -extern void -BZ2_compressBlock ( EState*, Bool ); - -extern void -BZ2_bsInitWrite ( EState* ); - -extern void -BZ2_hbAssignCodes ( Int32*, UChar*, Int32, Int32, Int32 ); - -extern void -BZ2_hbMakeCodeLengths ( UChar*, Int32*, Int32, Int32 ); - - - -/*-- states for decompression. --*/ - -#define BZ_X_IDLE 1 -#define BZ_X_OUTPUT 2 - -#define BZ_X_MAGIC_1 10 -#define BZ_X_MAGIC_2 11 -#define BZ_X_MAGIC_3 12 -#define BZ_X_MAGIC_4 13 -#define BZ_X_BLKHDR_1 14 -#define BZ_X_BLKHDR_2 15 -#define BZ_X_BLKHDR_3 16 -#define BZ_X_BLKHDR_4 17 -#define BZ_X_BLKHDR_5 18 -#define BZ_X_BLKHDR_6 19 -#define BZ_X_BCRC_1 20 -#define BZ_X_BCRC_2 21 -#define BZ_X_BCRC_3 22 -#define BZ_X_BCRC_4 23 -#define BZ_X_RANDBIT 24 -#define BZ_X_ORIGPTR_1 25 -#define BZ_X_ORIGPTR_2 26 -#define BZ_X_ORIGPTR_3 27 -#define BZ_X_MAPPING_1 28 -#define BZ_X_MAPPING_2 29 -#define BZ_X_SELECTOR_1 30 -#define BZ_X_SELECTOR_2 31 -#define BZ_X_SELECTOR_3 32 -#define BZ_X_CODING_1 33 -#define BZ_X_CODING_2 34 -#define BZ_X_CODING_3 35 -#define BZ_X_MTF_1 36 -#define BZ_X_MTF_2 37 -#define BZ_X_MTF_3 38 -#define BZ_X_MTF_4 39 -#define BZ_X_MTF_5 40 -#define BZ_X_MTF_6 41 -#define BZ_X_ENDHDR_2 42 -#define BZ_X_ENDHDR_3 43 -#define BZ_X_ENDHDR_4 44 -#define BZ_X_ENDHDR_5 45 -#define BZ_X_ENDHDR_6 46 -#define BZ_X_CCRC_1 47 -#define BZ_X_CCRC_2 48 -#define BZ_X_CCRC_3 49 -#define BZ_X_CCRC_4 50 - - - -/*-- Constants for the fast MTF decoder. --*/ - -#define MTFA_SIZE 4096 -#define MTFL_SIZE 16 - - - -/*-- Structure holding all the decompression-side stuff. --*/ - -typedef - struct { - /* pointer back to the struct bz_stream */ - bz_stream* strm; - - /* state indicator for this stream */ - Int32 state; - - /* for doing the final run-length decoding */ - UChar state_out_ch; - Int32 state_out_len; - Bool blockRandomised; - BZ_RAND_DECLS; - - /* the buffer for bit stream reading */ - UInt32 bsBuff; - Int32 bsLive; - - /* misc administratium */ - Int32 blockSize100k; - Bool smallDecompress; - Int32 currBlockNo; - Int32 verbosity; - - /* for undoing the Burrows-Wheeler transform */ - Int32 origPtr; - UInt32 tPos; - Int32 k0; - Int32 unzftab[256]; - Int32 nblock_used; - Int32 cftab[257]; - Int32 cftabCopy[257]; - - /* for undoing the Burrows-Wheeler transform (FAST) */ - UInt32 *tt; - - /* for undoing the Burrows-Wheeler transform (SMALL) */ - UInt16 *ll16; - UChar *ll4; - - /* stored and calculated CRCs */ - UInt32 storedBlockCRC; - UInt32 storedCombinedCRC; - UInt32 calculatedBlockCRC; - UInt32 calculatedCombinedCRC; - - /* map of bytes used in block */ - Int32 nInUse; - Bool inUse[256]; - Bool inUse16[16]; - UChar seqToUnseq[256]; - - /* for decoding the MTF values */ - UChar mtfa [MTFA_SIZE]; - Int32 mtfbase[256 / MTFL_SIZE]; - UChar selector [BZ_MAX_SELECTORS]; - UChar selectorMtf[BZ_MAX_SELECTORS]; - UChar len [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; - - Int32 limit [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; - Int32 base [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; - Int32 perm [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; - Int32 minLens[BZ_N_GROUPS]; - - /* save area for scalars in the main decompress code */ - Int32 save_i; - Int32 save_j; - Int32 save_t; - Int32 save_alphaSize; - Int32 save_nGroups; - Int32 save_nSelectors; - Int32 save_EOB; - Int32 save_groupNo; - Int32 save_groupPos; - Int32 save_nextSym; - Int32 save_nblockMAX; - Int32 save_nblock; - Int32 save_es; - Int32 save_N; - Int32 save_curr; - Int32 save_zt; - Int32 save_zn; - Int32 save_zvec; - Int32 save_zj; - Int32 save_gSel; - Int32 save_gMinlen; - Int32* save_gLimit; - Int32* save_gBase; - Int32* save_gPerm; - - } - DState; - - - -/*-- Macros for decompression. --*/ - -#define BZ_GET_FAST(cccc) \ - /* c_tPos is unsigned, hence test < 0 is pointless. */ \ - if (s->tPos >= (UInt32)100000 * (UInt32)s->blockSize100k) return True; \ - s->tPos = s->tt[s->tPos]; \ - cccc = (UChar)(s->tPos & 0xff); \ - s->tPos >>= 8; - -#define BZ_GET_FAST_C(cccc) \ - /* c_tPos is unsigned, hence test < 0 is pointless. */ \ - if (c_tPos >= (UInt32)100000 * (UInt32)ro_blockSize100k) return True; \ - c_tPos = c_tt[c_tPos]; \ - cccc = (UChar)(c_tPos & 0xff); \ - c_tPos >>= 8; - -#define SET_LL4(i,n) \ - { if (((i) & 0x1) == 0) \ - s->ll4[(i) >> 1] = (s->ll4[(i) >> 1] & 0xf0) | (n); else \ - s->ll4[(i) >> 1] = (s->ll4[(i) >> 1] & 0x0f) | ((n) << 4); \ - } - -#define GET_LL4(i) \ - ((((UInt32)(s->ll4[(i) >> 1])) >> (((i) << 2) & 0x4)) & 0xF) - -#define SET_LL(i,n) \ - { s->ll16[i] = (UInt16)(n & 0x0000ffff); \ - SET_LL4(i, n >> 16); \ - } - -#define GET_LL(i) \ - (((UInt32)s->ll16[i]) | (GET_LL4(i) << 16)) - -#define BZ_GET_SMALL(cccc) \ - /* c_tPos is unsigned, hence test < 0 is pointless. */ \ - if (s->tPos >= (UInt32)100000 * (UInt32)s->blockSize100k) return True; \ - cccc = BZ2_indexIntoF ( s->tPos, s->cftab ); \ - s->tPos = GET_LL(s->tPos); - - -/*-- externs for decompression. --*/ - -extern Int32 -BZ2_indexIntoF ( Int32, Int32* ); - -extern Int32 -BZ2_decompress ( DState* ); - -extern void -BZ2_hbCreateDecodeTables ( Int32*, Int32*, Int32*, UChar*, - Int32, Int32, Int32 ); - - -#endif - - -/*-- BZ_NO_STDIO seems to make NULL disappear on some platforms. --*/ - -#ifdef BZ_NO_STDIO -#ifndef NULL -#define NULL 0 -#endif -#endif - - -/*-------------------------------------------------------------*/ -/*--- end bzlib_private.h ---*/ -/*-------------------------------------------------------------*/ diff --git a/externals/bzip2/compress.c b/externals/bzip2/compress.c deleted file mode 100644 index 8c80a079700..00000000000 --- a/externals/bzip2/compress.c +++ /dev/null @@ -1,672 +0,0 @@ - -/*-------------------------------------------------------------*/ -/*--- Compression machinery (not incl block sorting) ---*/ -/*--- compress.c ---*/ -/*-------------------------------------------------------------*/ - -/* ------------------------------------------------------------------ - This file is part of bzip2/libbzip2, a program and library for - lossless, block-sorting data compression. - - bzip2/libbzip2 version 1.0.5 of 10 December 2007 - Copyright (C) 1996-2007 Julian Seward - - Please read the WARNING, DISCLAIMER and PATENTS sections in the - README file. - - This program is released under the terms of the license contained - in the file LICENSE. - ------------------------------------------------------------------ */ - - -/* CHANGES - 0.9.0 -- original version. - 0.9.0a/b -- no changes in this file. - 0.9.0c -- changed setting of nGroups in sendMTFValues() - so as to do a bit better on small files -*/ - -#include "bzlib_private.h" - - -/*---------------------------------------------------*/ -/*--- Bit stream I/O ---*/ -/*---------------------------------------------------*/ - -/*---------------------------------------------------*/ -void BZ2_bsInitWrite ( EState* s ) -{ - s->bsLive = 0; - s->bsBuff = 0; -} - - -/*---------------------------------------------------*/ -static -void bsFinishWrite ( EState* s ) -{ - while (s->bsLive > 0) { - s->zbits[s->numZ] = (UChar)(s->bsBuff >> 24); - s->numZ++; - s->bsBuff <<= 8; - s->bsLive -= 8; - } -} - - -/*---------------------------------------------------*/ -#define bsNEEDW(nz) \ -{ \ - while (s->bsLive >= 8) { \ - s->zbits[s->numZ] \ - = (UChar)(s->bsBuff >> 24); \ - s->numZ++; \ - s->bsBuff <<= 8; \ - s->bsLive -= 8; \ - } \ -} - - -/*---------------------------------------------------*/ -static -__inline__ -void bsW ( EState* s, Int32 n, UInt32 v ) -{ - bsNEEDW ( n ); - s->bsBuff |= (v << (32 - s->bsLive - n)); - s->bsLive += n; -} - - -/*---------------------------------------------------*/ -static -void bsPutUInt32 ( EState* s, UInt32 u ) -{ - bsW ( s, 8, (u >> 24) & 0xffL ); - bsW ( s, 8, (u >> 16) & 0xffL ); - bsW ( s, 8, (u >> 8) & 0xffL ); - bsW ( s, 8, u & 0xffL ); -} - - -/*---------------------------------------------------*/ -static -void bsPutUChar ( EState* s, UChar c ) -{ - bsW( s, 8, (UInt32)c ); -} - - -/*---------------------------------------------------*/ -/*--- The back end proper ---*/ -/*---------------------------------------------------*/ - -/*---------------------------------------------------*/ -static -void makeMaps_e ( EState* s ) -{ - Int32 i; - s->nInUse = 0; - for (i = 0; i < 256; i++) - if (s->inUse[i]) { - s->unseqToSeq[i] = s->nInUse; - s->nInUse++; - } -} - - -/*---------------------------------------------------*/ -static -void generateMTFValues ( EState* s ) -{ - UChar yy[256]; - Int32 i, j; - Int32 zPend; - Int32 wr; - Int32 EOB; - - /* - After sorting (eg, here), - s->arr1 [ 0 .. s->nblock-1 ] holds sorted order, - and - ((UChar*)s->arr2) [ 0 .. s->nblock-1 ] - holds the original block data. - - The first thing to do is generate the MTF values, - and put them in - ((UInt16*)s->arr1) [ 0 .. s->nblock-1 ]. - Because there are strictly fewer or equal MTF values - than block values, ptr values in this area are overwritten - with MTF values only when they are no longer needed. - - The final compressed bitstream is generated into the - area starting at - (UChar*) (&((UChar*)s->arr2)[s->nblock]) - - These storage aliases are set up in bzCompressInit(), - except for the last one, which is arranged in - compressBlock(). - */ - UInt32* ptr = s->ptr; - UChar* block = s->block; - UInt16* mtfv = s->mtfv; - - makeMaps_e ( s ); - EOB = s->nInUse+1; - - for (i = 0; i <= EOB; i++) s->mtfFreq[i] = 0; - - wr = 0; - zPend = 0; - for (i = 0; i < s->nInUse; i++) yy[i] = (UChar) i; - - for (i = 0; i < s->nblock; i++) { - UChar ll_i; - AssertD ( wr <= i, "generateMTFValues(1)" ); - j = ptr[i]-1; if (j < 0) j += s->nblock; - ll_i = s->unseqToSeq[block[j]]; - AssertD ( ll_i < s->nInUse, "generateMTFValues(2a)" ); - - if (yy[0] == ll_i) { - zPend++; - } else { - - if (zPend > 0) { - zPend--; - while (True) { - if (zPend & 1) { - mtfv[wr] = BZ_RUNB; wr++; - s->mtfFreq[BZ_RUNB]++; - } else { - mtfv[wr] = BZ_RUNA; wr++; - s->mtfFreq[BZ_RUNA]++; - } - if (zPend < 2) break; - zPend = (zPend - 2) / 2; - }; - zPend = 0; - } - { - register UChar rtmp; - register UChar* ryy_j; - register UChar rll_i; - rtmp = yy[1]; - yy[1] = yy[0]; - ryy_j = &(yy[1]); - rll_i = ll_i; - while ( rll_i != rtmp ) { - register UChar rtmp2; - ryy_j++; - rtmp2 = rtmp; - rtmp = *ryy_j; - *ryy_j = rtmp2; - }; - yy[0] = rtmp; - j = ryy_j - &(yy[0]); - mtfv[wr] = j+1; wr++; s->mtfFreq[j+1]++; - } - - } - } - - if (zPend > 0) { - zPend--; - while (True) { - if (zPend & 1) { - mtfv[wr] = BZ_RUNB; wr++; - s->mtfFreq[BZ_RUNB]++; - } else { - mtfv[wr] = BZ_RUNA; wr++; - s->mtfFreq[BZ_RUNA]++; - } - if (zPend < 2) break; - zPend = (zPend - 2) / 2; - }; - zPend = 0; - } - - mtfv[wr] = EOB; wr++; s->mtfFreq[EOB]++; - - s->nMTF = wr; -} - - -/*---------------------------------------------------*/ -#define BZ_LESSER_ICOST 0 -#define BZ_GREATER_ICOST 15 - -static -void sendMTFValues ( EState* s ) -{ - Int32 v, t, i, j, gs, ge, totc, bt, bc, iter; - Int32 nSelectors, alphaSize, minLen, maxLen, selCtr; - Int32 nGroups, nBytes; - - /*-- - UChar len [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; - is a global since the decoder also needs it. - - Int32 code[BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; - Int32 rfreq[BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; - are also globals only used in this proc. - Made global to keep stack frame size small. - --*/ - - - UInt16 cost[BZ_N_GROUPS]; - Int32 fave[BZ_N_GROUPS]; - - UInt16* mtfv = s->mtfv; - - if (s->verbosity >= 3) - VPrintf3( " %d in block, %d after MTF & 1-2 coding, " - "%d+2 syms in use\n", - s->nblock, s->nMTF, s->nInUse ); - - alphaSize = s->nInUse+2; - for (t = 0; t < BZ_N_GROUPS; t++) - for (v = 0; v < alphaSize; v++) - s->len[t][v] = BZ_GREATER_ICOST; - - /*--- Decide how many coding tables to use ---*/ - AssertH ( s->nMTF > 0, 3001 ); - if (s->nMTF < 200) nGroups = 2; else - if (s->nMTF < 600) nGroups = 3; else - if (s->nMTF < 1200) nGroups = 4; else - if (s->nMTF < 2400) nGroups = 5; else - nGroups = 6; - - /*--- Generate an initial set of coding tables ---*/ - { - Int32 nPart, remF, tFreq, aFreq; - - nPart = nGroups; - remF = s->nMTF; - gs = 0; - while (nPart > 0) { - tFreq = remF / nPart; - ge = gs-1; - aFreq = 0; - while (aFreq < tFreq && ge < alphaSize-1) { - ge++; - aFreq += s->mtfFreq[ge]; - } - - if (ge > gs - && nPart != nGroups && nPart != 1 - && ((nGroups-nPart) % 2 == 1)) { - aFreq -= s->mtfFreq[ge]; - ge--; - } - - if (s->verbosity >= 3) - VPrintf5( " initial group %d, [%d .. %d], " - "has %d syms (%4.1f%%)\n", - nPart, gs, ge, aFreq, - (100.0 * (float)aFreq) / (float)(s->nMTF) ); - - for (v = 0; v < alphaSize; v++) - if (v >= gs && v <= ge) - s->len[nPart-1][v] = BZ_LESSER_ICOST; else - s->len[nPart-1][v] = BZ_GREATER_ICOST; - - nPart--; - gs = ge+1; - remF -= aFreq; - } - } - - /*--- - Iterate up to BZ_N_ITERS times to improve the tables. - ---*/ - for (iter = 0; iter < BZ_N_ITERS; iter++) { - - for (t = 0; t < nGroups; t++) fave[t] = 0; - - for (t = 0; t < nGroups; t++) - for (v = 0; v < alphaSize; v++) - s->rfreq[t][v] = 0; - - /*--- - Set up an auxiliary length table which is used to fast-track - the common case (nGroups == 6). - ---*/ - if (nGroups == 6) { - for (v = 0; v < alphaSize; v++) { - s->len_pack[v][0] = (s->len[1][v] << 16) | s->len[0][v]; - s->len_pack[v][1] = (s->len[3][v] << 16) | s->len[2][v]; - s->len_pack[v][2] = (s->len[5][v] << 16) | s->len[4][v]; - } - } - - nSelectors = 0; - totc = 0; - gs = 0; - while (True) { - - /*--- Set group start & end marks. --*/ - if (gs >= s->nMTF) break; - ge = gs + BZ_G_SIZE - 1; - if (ge >= s->nMTF) ge = s->nMTF-1; - - /*-- - Calculate the cost of this group as coded - by each of the coding tables. - --*/ - for (t = 0; t < nGroups; t++) cost[t] = 0; - - if (nGroups == 6 && 50 == ge-gs+1) { - /*--- fast track the common case ---*/ - register UInt32 cost01, cost23, cost45; - register UInt16 icv; - cost01 = cost23 = cost45 = 0; - -# define BZ_ITER(nn) \ - icv = mtfv[gs+(nn)]; \ - cost01 += s->len_pack[icv][0]; \ - cost23 += s->len_pack[icv][1]; \ - cost45 += s->len_pack[icv][2]; \ - - BZ_ITER(0); BZ_ITER(1); BZ_ITER(2); BZ_ITER(3); BZ_ITER(4); - BZ_ITER(5); BZ_ITER(6); BZ_ITER(7); BZ_ITER(8); BZ_ITER(9); - BZ_ITER(10); BZ_ITER(11); BZ_ITER(12); BZ_ITER(13); BZ_ITER(14); - BZ_ITER(15); BZ_ITER(16); BZ_ITER(17); BZ_ITER(18); BZ_ITER(19); - BZ_ITER(20); BZ_ITER(21); BZ_ITER(22); BZ_ITER(23); BZ_ITER(24); - BZ_ITER(25); BZ_ITER(26); BZ_ITER(27); BZ_ITER(28); BZ_ITER(29); - BZ_ITER(30); BZ_ITER(31); BZ_ITER(32); BZ_ITER(33); BZ_ITER(34); - BZ_ITER(35); BZ_ITER(36); BZ_ITER(37); BZ_ITER(38); BZ_ITER(39); - BZ_ITER(40); BZ_ITER(41); BZ_ITER(42); BZ_ITER(43); BZ_ITER(44); - BZ_ITER(45); BZ_ITER(46); BZ_ITER(47); BZ_ITER(48); BZ_ITER(49); - -# undef BZ_ITER - - cost[0] = cost01 & 0xffff; cost[1] = cost01 >> 16; - cost[2] = cost23 & 0xffff; cost[3] = cost23 >> 16; - cost[4] = cost45 & 0xffff; cost[5] = cost45 >> 16; - - } else { - /*--- slow version which correctly handles all situations ---*/ - for (i = gs; i <= ge; i++) { - UInt16 icv = mtfv[i]; - for (t = 0; t < nGroups; t++) cost[t] += s->len[t][icv]; - } - } - - /*-- - Find the coding table which is best for this group, - and record its identity in the selector table. - --*/ - bc = 999999999; bt = -1; - for (t = 0; t < nGroups; t++) - if (cost[t] < bc) { bc = cost[t]; bt = t; }; - totc += bc; - fave[bt]++; - s->selector[nSelectors] = bt; - nSelectors++; - - /*-- - Increment the symbol frequencies for the selected table. - --*/ - if (nGroups == 6 && 50 == ge-gs+1) { - /*--- fast track the common case ---*/ - -# define BZ_ITUR(nn) s->rfreq[bt][ mtfv[gs+(nn)] ]++ - - BZ_ITUR(0); BZ_ITUR(1); BZ_ITUR(2); BZ_ITUR(3); BZ_ITUR(4); - BZ_ITUR(5); BZ_ITUR(6); BZ_ITUR(7); BZ_ITUR(8); BZ_ITUR(9); - BZ_ITUR(10); BZ_ITUR(11); BZ_ITUR(12); BZ_ITUR(13); BZ_ITUR(14); - BZ_ITUR(15); BZ_ITUR(16); BZ_ITUR(17); BZ_ITUR(18); BZ_ITUR(19); - BZ_ITUR(20); BZ_ITUR(21); BZ_ITUR(22); BZ_ITUR(23); BZ_ITUR(24); - BZ_ITUR(25); BZ_ITUR(26); BZ_ITUR(27); BZ_ITUR(28); BZ_ITUR(29); - BZ_ITUR(30); BZ_ITUR(31); BZ_ITUR(32); BZ_ITUR(33); BZ_ITUR(34); - BZ_ITUR(35); BZ_ITUR(36); BZ_ITUR(37); BZ_ITUR(38); BZ_ITUR(39); - BZ_ITUR(40); BZ_ITUR(41); BZ_ITUR(42); BZ_ITUR(43); BZ_ITUR(44); - BZ_ITUR(45); BZ_ITUR(46); BZ_ITUR(47); BZ_ITUR(48); BZ_ITUR(49); - -# undef BZ_ITUR - - } else { - /*--- slow version which correctly handles all situations ---*/ - for (i = gs; i <= ge; i++) - s->rfreq[bt][ mtfv[i] ]++; - } - - gs = ge+1; - } - if (s->verbosity >= 3) { - VPrintf2 ( " pass %d: size is %d, grp uses are ", - iter+1, totc/8 ); - for (t = 0; t < nGroups; t++) - VPrintf1 ( "%d ", fave[t] ); - VPrintf0 ( "\n" ); - } - - /*-- - Recompute the tables based on the accumulated frequencies. - --*/ - /* maxLen was changed from 20 to 17 in bzip2-1.0.3. See - comment in huffman.c for details. */ - for (t = 0; t < nGroups; t++) - BZ2_hbMakeCodeLengths ( &(s->len[t][0]), &(s->rfreq[t][0]), - alphaSize, 17 /*20*/ ); - } - - - AssertH( nGroups < 8, 3002 ); - AssertH( nSelectors < 32768 && - nSelectors <= (2 + (900000 / BZ_G_SIZE)), - 3003 ); - - - /*--- Compute MTF values for the selectors. ---*/ - { - UChar pos[BZ_N_GROUPS], ll_i, tmp2, tmp; - for (i = 0; i < nGroups; i++) pos[i] = i; - for (i = 0; i < nSelectors; i++) { - ll_i = s->selector[i]; - j = 0; - tmp = pos[j]; - while ( ll_i != tmp ) { - j++; - tmp2 = tmp; - tmp = pos[j]; - pos[j] = tmp2; - }; - pos[0] = tmp; - s->selectorMtf[i] = j; - } - }; - - /*--- Assign actual codes for the tables. --*/ - for (t = 0; t < nGroups; t++) { - minLen = 32; - maxLen = 0; - for (i = 0; i < alphaSize; i++) { - if (s->len[t][i] > maxLen) maxLen = s->len[t][i]; - if (s->len[t][i] < minLen) minLen = s->len[t][i]; - } - AssertH ( !(maxLen > 17 /*20*/ ), 3004 ); - AssertH ( !(minLen < 1), 3005 ); - BZ2_hbAssignCodes ( &(s->code[t][0]), &(s->len[t][0]), - minLen, maxLen, alphaSize ); - } - - /*--- Transmit the mapping table. ---*/ - { - Bool inUse16[16]; - for (i = 0; i < 16; i++) { - inUse16[i] = False; - for (j = 0; j < 16; j++) - if (s->inUse[i * 16 + j]) inUse16[i] = True; - } - - nBytes = s->numZ; - for (i = 0; i < 16; i++) - if (inUse16[i]) bsW(s,1,1); else bsW(s,1,0); - - for (i = 0; i < 16; i++) - if (inUse16[i]) - for (j = 0; j < 16; j++) { - if (s->inUse[i * 16 + j]) bsW(s,1,1); else bsW(s,1,0); - } - - if (s->verbosity >= 3) - VPrintf1( " bytes: mapping %d, ", s->numZ-nBytes ); - } - - /*--- Now the selectors. ---*/ - nBytes = s->numZ; - bsW ( s, 3, nGroups ); - bsW ( s, 15, nSelectors ); - for (i = 0; i < nSelectors; i++) { - for (j = 0; j < s->selectorMtf[i]; j++) bsW(s,1,1); - bsW(s,1,0); - } - if (s->verbosity >= 3) - VPrintf1( "selectors %d, ", s->numZ-nBytes ); - - /*--- Now the coding tables. ---*/ - nBytes = s->numZ; - - for (t = 0; t < nGroups; t++) { - Int32 curr = s->len[t][0]; - bsW ( s, 5, curr ); - for (i = 0; i < alphaSize; i++) { - while (curr < s->len[t][i]) { bsW(s,2,2); curr++; /* 10 */ }; - while (curr > s->len[t][i]) { bsW(s,2,3); curr--; /* 11 */ }; - bsW ( s, 1, 0 ); - } - } - - if (s->verbosity >= 3) - VPrintf1 ( "code lengths %d, ", s->numZ-nBytes ); - - /*--- And finally, the block data proper ---*/ - nBytes = s->numZ; - selCtr = 0; - gs = 0; - while (True) { - if (gs >= s->nMTF) break; - ge = gs + BZ_G_SIZE - 1; - if (ge >= s->nMTF) ge = s->nMTF-1; - AssertH ( s->selector[selCtr] < nGroups, 3006 ); - - if (nGroups == 6 && 50 == ge-gs+1) { - /*--- fast track the common case ---*/ - UInt16 mtfv_i; - UChar* s_len_sel_selCtr - = &(s->len[s->selector[selCtr]][0]); - Int32* s_code_sel_selCtr - = &(s->code[s->selector[selCtr]][0]); - -# define BZ_ITAH(nn) \ - mtfv_i = mtfv[gs+(nn)]; \ - bsW ( s, \ - s_len_sel_selCtr[mtfv_i], \ - s_code_sel_selCtr[mtfv_i] ) - - BZ_ITAH(0); BZ_ITAH(1); BZ_ITAH(2); BZ_ITAH(3); BZ_ITAH(4); - BZ_ITAH(5); BZ_ITAH(6); BZ_ITAH(7); BZ_ITAH(8); BZ_ITAH(9); - BZ_ITAH(10); BZ_ITAH(11); BZ_ITAH(12); BZ_ITAH(13); BZ_ITAH(14); - BZ_ITAH(15); BZ_ITAH(16); BZ_ITAH(17); BZ_ITAH(18); BZ_ITAH(19); - BZ_ITAH(20); BZ_ITAH(21); BZ_ITAH(22); BZ_ITAH(23); BZ_ITAH(24); - BZ_ITAH(25); BZ_ITAH(26); BZ_ITAH(27); BZ_ITAH(28); BZ_ITAH(29); - BZ_ITAH(30); BZ_ITAH(31); BZ_ITAH(32); BZ_ITAH(33); BZ_ITAH(34); - BZ_ITAH(35); BZ_ITAH(36); BZ_ITAH(37); BZ_ITAH(38); BZ_ITAH(39); - BZ_ITAH(40); BZ_ITAH(41); BZ_ITAH(42); BZ_ITAH(43); BZ_ITAH(44); - BZ_ITAH(45); BZ_ITAH(46); BZ_ITAH(47); BZ_ITAH(48); BZ_ITAH(49); - -# undef BZ_ITAH - - } else { - /*--- slow version which correctly handles all situations ---*/ - for (i = gs; i <= ge; i++) { - bsW ( s, - s->len [s->selector[selCtr]] [mtfv[i]], - s->code [s->selector[selCtr]] [mtfv[i]] ); - } - } - - - gs = ge+1; - selCtr++; - } - AssertH( selCtr == nSelectors, 3007 ); - - if (s->verbosity >= 3) - VPrintf1( "codes %d\n", s->numZ-nBytes ); -} - - -/*---------------------------------------------------*/ -void BZ2_compressBlock ( EState* s, Bool is_last_block ) -{ - if (s->nblock > 0) { - - BZ_FINALISE_CRC ( s->blockCRC ); - s->combinedCRC = (s->combinedCRC << 1) | (s->combinedCRC >> 31); - s->combinedCRC ^= s->blockCRC; - if (s->blockNo > 1) s->numZ = 0; - - if (s->verbosity >= 2) - VPrintf4( " block %d: crc = 0x%08x, " - "combined CRC = 0x%08x, size = %d\n", - s->blockNo, s->blockCRC, s->combinedCRC, s->nblock ); - - BZ2_blockSort ( s ); - } - - s->zbits = (UChar*) (&((UChar*)s->arr2)[s->nblock]); - - /*-- If this is the first block, create the stream header. --*/ - if (s->blockNo == 1) { - BZ2_bsInitWrite ( s ); - bsPutUChar ( s, BZ_HDR_B ); - bsPutUChar ( s, BZ_HDR_Z ); - bsPutUChar ( s, BZ_HDR_h ); - bsPutUChar ( s, (UChar)(BZ_HDR_0 + s->blockSize100k) ); - } - - if (s->nblock > 0) { - - bsPutUChar ( s, 0x31 ); bsPutUChar ( s, 0x41 ); - bsPutUChar ( s, 0x59 ); bsPutUChar ( s, 0x26 ); - bsPutUChar ( s, 0x53 ); bsPutUChar ( s, 0x59 ); - - /*-- Now the block's CRC, so it is in a known place. --*/ - bsPutUInt32 ( s, s->blockCRC ); - - /*-- - Now a single bit indicating (non-)randomisation. - As of version 0.9.5, we use a better sorting algorithm - which makes randomisation unnecessary. So always set - the randomised bit to 'no'. Of course, the decoder - still needs to be able to handle randomised blocks - so as to maintain backwards compatibility with - older versions of bzip2. - --*/ - bsW(s,1,0); - - bsW ( s, 24, s->origPtr ); - generateMTFValues ( s ); - sendMTFValues ( s ); - } - - - /*-- If this is the last block, add the stream trailer. --*/ - if (is_last_block) { - - bsPutUChar ( s, 0x17 ); bsPutUChar ( s, 0x72 ); - bsPutUChar ( s, 0x45 ); bsPutUChar ( s, 0x38 ); - bsPutUChar ( s, 0x50 ); bsPutUChar ( s, 0x90 ); - bsPutUInt32 ( s, s->combinedCRC ); - if (s->verbosity >= 2) - VPrintf1( " final combined CRC = 0x%08x\n ", s->combinedCRC ); - bsFinishWrite ( s ); - } -} - - -/*-------------------------------------------------------------*/ -/*--- end compress.c ---*/ -/*-------------------------------------------------------------*/ diff --git a/externals/bzip2/crctable.c b/externals/bzip2/crctable.c deleted file mode 100644 index 215687b2c05..00000000000 --- a/externals/bzip2/crctable.c +++ /dev/null @@ -1,104 +0,0 @@ - -/*-------------------------------------------------------------*/ -/*--- Table for doing CRCs ---*/ -/*--- crctable.c ---*/ -/*-------------------------------------------------------------*/ - -/* ------------------------------------------------------------------ - This file is part of bzip2/libbzip2, a program and library for - lossless, block-sorting data compression. - - bzip2/libbzip2 version 1.0.5 of 10 December 2007 - Copyright (C) 1996-2007 Julian Seward - - Please read the WARNING, DISCLAIMER and PATENTS sections in the - README file. - - This program is released under the terms of the license contained - in the file LICENSE. - ------------------------------------------------------------------ */ - - -#include "bzlib_private.h" - -/*-- - I think this is an implementation of the AUTODIN-II, - Ethernet & FDDI 32-bit CRC standard. Vaguely derived - from code by Rob Warnock, in Section 51 of the - comp.compression FAQ. ---*/ - -UInt32 BZ2_crc32Table[256] = { - - /*-- Ugly, innit? --*/ - - 0x00000000L, 0x04c11db7L, 0x09823b6eL, 0x0d4326d9L, - 0x130476dcL, 0x17c56b6bL, 0x1a864db2L, 0x1e475005L, - 0x2608edb8L, 0x22c9f00fL, 0x2f8ad6d6L, 0x2b4bcb61L, - 0x350c9b64L, 0x31cd86d3L, 0x3c8ea00aL, 0x384fbdbdL, - 0x4c11db70L, 0x48d0c6c7L, 0x4593e01eL, 0x4152fda9L, - 0x5f15adacL, 0x5bd4b01bL, 0x569796c2L, 0x52568b75L, - 0x6a1936c8L, 0x6ed82b7fL, 0x639b0da6L, 0x675a1011L, - 0x791d4014L, 0x7ddc5da3L, 0x709f7b7aL, 0x745e66cdL, - 0x9823b6e0L, 0x9ce2ab57L, 0x91a18d8eL, 0x95609039L, - 0x8b27c03cL, 0x8fe6dd8bL, 0x82a5fb52L, 0x8664e6e5L, - 0xbe2b5b58L, 0xbaea46efL, 0xb7a96036L, 0xb3687d81L, - 0xad2f2d84L, 0xa9ee3033L, 0xa4ad16eaL, 0xa06c0b5dL, - 0xd4326d90L, 0xd0f37027L, 0xddb056feL, 0xd9714b49L, - 0xc7361b4cL, 0xc3f706fbL, 0xceb42022L, 0xca753d95L, - 0xf23a8028L, 0xf6fb9d9fL, 0xfbb8bb46L, 0xff79a6f1L, - 0xe13ef6f4L, 0xe5ffeb43L, 0xe8bccd9aL, 0xec7dd02dL, - 0x34867077L, 0x30476dc0L, 0x3d044b19L, 0x39c556aeL, - 0x278206abL, 0x23431b1cL, 0x2e003dc5L, 0x2ac12072L, - 0x128e9dcfL, 0x164f8078L, 0x1b0ca6a1L, 0x1fcdbb16L, - 0x018aeb13L, 0x054bf6a4L, 0x0808d07dL, 0x0cc9cdcaL, - 0x7897ab07L, 0x7c56b6b0L, 0x71159069L, 0x75d48ddeL, - 0x6b93dddbL, 0x6f52c06cL, 0x6211e6b5L, 0x66d0fb02L, - 0x5e9f46bfL, 0x5a5e5b08L, 0x571d7dd1L, 0x53dc6066L, - 0x4d9b3063L, 0x495a2dd4L, 0x44190b0dL, 0x40d816baL, - 0xaca5c697L, 0xa864db20L, 0xa527fdf9L, 0xa1e6e04eL, - 0xbfa1b04bL, 0xbb60adfcL, 0xb6238b25L, 0xb2e29692L, - 0x8aad2b2fL, 0x8e6c3698L, 0x832f1041L, 0x87ee0df6L, - 0x99a95df3L, 0x9d684044L, 0x902b669dL, 0x94ea7b2aL, - 0xe0b41de7L, 0xe4750050L, 0xe9362689L, 0xedf73b3eL, - 0xf3b06b3bL, 0xf771768cL, 0xfa325055L, 0xfef34de2L, - 0xc6bcf05fL, 0xc27dede8L, 0xcf3ecb31L, 0xcbffd686L, - 0xd5b88683L, 0xd1799b34L, 0xdc3abdedL, 0xd8fba05aL, - 0x690ce0eeL, 0x6dcdfd59L, 0x608edb80L, 0x644fc637L, - 0x7a089632L, 0x7ec98b85L, 0x738aad5cL, 0x774bb0ebL, - 0x4f040d56L, 0x4bc510e1L, 0x46863638L, 0x42472b8fL, - 0x5c007b8aL, 0x58c1663dL, 0x558240e4L, 0x51435d53L, - 0x251d3b9eL, 0x21dc2629L, 0x2c9f00f0L, 0x285e1d47L, - 0x36194d42L, 0x32d850f5L, 0x3f9b762cL, 0x3b5a6b9bL, - 0x0315d626L, 0x07d4cb91L, 0x0a97ed48L, 0x0e56f0ffL, - 0x1011a0faL, 0x14d0bd4dL, 0x19939b94L, 0x1d528623L, - 0xf12f560eL, 0xf5ee4bb9L, 0xf8ad6d60L, 0xfc6c70d7L, - 0xe22b20d2L, 0xe6ea3d65L, 0xeba91bbcL, 0xef68060bL, - 0xd727bbb6L, 0xd3e6a601L, 0xdea580d8L, 0xda649d6fL, - 0xc423cd6aL, 0xc0e2d0ddL, 0xcda1f604L, 0xc960ebb3L, - 0xbd3e8d7eL, 0xb9ff90c9L, 0xb4bcb610L, 0xb07daba7L, - 0xae3afba2L, 0xaafbe615L, 0xa7b8c0ccL, 0xa379dd7bL, - 0x9b3660c6L, 0x9ff77d71L, 0x92b45ba8L, 0x9675461fL, - 0x8832161aL, 0x8cf30badL, 0x81b02d74L, 0x857130c3L, - 0x5d8a9099L, 0x594b8d2eL, 0x5408abf7L, 0x50c9b640L, - 0x4e8ee645L, 0x4a4ffbf2L, 0x470cdd2bL, 0x43cdc09cL, - 0x7b827d21L, 0x7f436096L, 0x7200464fL, 0x76c15bf8L, - 0x68860bfdL, 0x6c47164aL, 0x61043093L, 0x65c52d24L, - 0x119b4be9L, 0x155a565eL, 0x18197087L, 0x1cd86d30L, - 0x029f3d35L, 0x065e2082L, 0x0b1d065bL, 0x0fdc1becL, - 0x3793a651L, 0x3352bbe6L, 0x3e119d3fL, 0x3ad08088L, - 0x2497d08dL, 0x2056cd3aL, 0x2d15ebe3L, 0x29d4f654L, - 0xc5a92679L, 0xc1683bceL, 0xcc2b1d17L, 0xc8ea00a0L, - 0xd6ad50a5L, 0xd26c4d12L, 0xdf2f6bcbL, 0xdbee767cL, - 0xe3a1cbc1L, 0xe760d676L, 0xea23f0afL, 0xeee2ed18L, - 0xf0a5bd1dL, 0xf464a0aaL, 0xf9278673L, 0xfde69bc4L, - 0x89b8fd09L, 0x8d79e0beL, 0x803ac667L, 0x84fbdbd0L, - 0x9abc8bd5L, 0x9e7d9662L, 0x933eb0bbL, 0x97ffad0cL, - 0xafb010b1L, 0xab710d06L, 0xa6322bdfL, 0xa2f33668L, - 0xbcb4666dL, 0xb8757bdaL, 0xb5365d03L, 0xb1f740b4L -}; - - -/*-------------------------------------------------------------*/ -/*--- end crctable.c ---*/ -/*-------------------------------------------------------------*/ diff --git a/externals/bzip2/decompress.c b/externals/bzip2/decompress.c deleted file mode 100644 index bba5e0fa36d..00000000000 --- a/externals/bzip2/decompress.c +++ /dev/null @@ -1,626 +0,0 @@ - -/*-------------------------------------------------------------*/ -/*--- Decompression machinery ---*/ -/*--- decompress.c ---*/ -/*-------------------------------------------------------------*/ - -/* ------------------------------------------------------------------ - This file is part of bzip2/libbzip2, a program and library for - lossless, block-sorting data compression. - - bzip2/libbzip2 version 1.0.5 of 10 December 2007 - Copyright (C) 1996-2007 Julian Seward - - Please read the WARNING, DISCLAIMER and PATENTS sections in the - README file. - - This program is released under the terms of the license contained - in the file LICENSE. - ------------------------------------------------------------------ */ - - -#include "bzlib_private.h" - - -/*---------------------------------------------------*/ -static -void makeMaps_d ( DState* s ) -{ - Int32 i; - s->nInUse = 0; - for (i = 0; i < 256; i++) - if (s->inUse[i]) { - s->seqToUnseq[s->nInUse] = i; - s->nInUse++; - } -} - - -/*---------------------------------------------------*/ -#define RETURN(rrr) \ - { retVal = rrr; goto save_state_and_return; }; - -#define GET_BITS(lll,vvv,nnn) \ - case lll: s->state = lll; \ - while (True) { \ - if (s->bsLive >= nnn) { \ - UInt32 v; \ - v = (s->bsBuff >> \ - (s->bsLive-nnn)) & ((1 << nnn)-1); \ - s->bsLive -= nnn; \ - vvv = v; \ - break; \ - } \ - if (s->strm->avail_in == 0) RETURN(BZ_OK); \ - s->bsBuff \ - = (s->bsBuff << 8) | \ - ((UInt32) \ - (*((UChar*)(s->strm->next_in)))); \ - s->bsLive += 8; \ - s->strm->next_in++; \ - s->strm->avail_in--; \ - s->strm->total_in_lo32++; \ - if (s->strm->total_in_lo32 == 0) \ - s->strm->total_in_hi32++; \ - } - -#define GET_UCHAR(lll,uuu) \ - GET_BITS(lll,uuu,8) - -#define GET_BIT(lll,uuu) \ - GET_BITS(lll,uuu,1) - -/*---------------------------------------------------*/ -#define GET_MTF_VAL(label1,label2,lval) \ -{ \ - if (groupPos == 0) { \ - groupNo++; \ - if (groupNo >= nSelectors) \ - RETURN(BZ_DATA_ERROR); \ - groupPos = BZ_G_SIZE; \ - gSel = s->selector[groupNo]; \ - gMinlen = s->minLens[gSel]; \ - gLimit = &(s->limit[gSel][0]); \ - gPerm = &(s->perm[gSel][0]); \ - gBase = &(s->base[gSel][0]); \ - } \ - groupPos--; \ - zn = gMinlen; \ - GET_BITS(label1, zvec, zn); \ - while (1) { \ - if (zn > 20 /* the longest code */) \ - RETURN(BZ_DATA_ERROR); \ - if (zvec <= gLimit[zn]) break; \ - zn++; \ - GET_BIT(label2, zj); \ - zvec = (zvec << 1) | zj; \ - }; \ - if (zvec - gBase[zn] < 0 \ - || zvec - gBase[zn] >= BZ_MAX_ALPHA_SIZE) \ - RETURN(BZ_DATA_ERROR); \ - lval = gPerm[zvec - gBase[zn]]; \ -} - - -/*---------------------------------------------------*/ -Int32 BZ2_decompress ( DState* s ) -{ - UChar uc; - Int32 retVal; - Int32 minLen, maxLen; - bz_stream* strm = s->strm; - - /* stuff that needs to be saved/restored */ - Int32 i; - Int32 j; - Int32 t; - Int32 alphaSize; - Int32 nGroups; - Int32 nSelectors; - Int32 EOB; - Int32 groupNo; - Int32 groupPos; - Int32 nextSym; - Int32 nblockMAX; - Int32 nblock; - Int32 es; - Int32 N; - Int32 curr; - Int32 zt; - Int32 zn; - Int32 zvec; - Int32 zj; - Int32 gSel; - Int32 gMinlen; - Int32* gLimit; - Int32* gBase; - Int32* gPerm; - - if (s->state == BZ_X_MAGIC_1) { - /*initialise the save area*/ - s->save_i = 0; - s->save_j = 0; - s->save_t = 0; - s->save_alphaSize = 0; - s->save_nGroups = 0; - s->save_nSelectors = 0; - s->save_EOB = 0; - s->save_groupNo = 0; - s->save_groupPos = 0; - s->save_nextSym = 0; - s->save_nblockMAX = 0; - s->save_nblock = 0; - s->save_es = 0; - s->save_N = 0; - s->save_curr = 0; - s->save_zt = 0; - s->save_zn = 0; - s->save_zvec = 0; - s->save_zj = 0; - s->save_gSel = 0; - s->save_gMinlen = 0; - s->save_gLimit = NULL; - s->save_gBase = NULL; - s->save_gPerm = NULL; - } - - /*restore from the save area*/ - i = s->save_i; - j = s->save_j; - t = s->save_t; - alphaSize = s->save_alphaSize; - nGroups = s->save_nGroups; - nSelectors = s->save_nSelectors; - EOB = s->save_EOB; - groupNo = s->save_groupNo; - groupPos = s->save_groupPos; - nextSym = s->save_nextSym; - nblockMAX = s->save_nblockMAX; - nblock = s->save_nblock; - es = s->save_es; - N = s->save_N; - curr = s->save_curr; - zt = s->save_zt; - zn = s->save_zn; - zvec = s->save_zvec; - zj = s->save_zj; - gSel = s->save_gSel; - gMinlen = s->save_gMinlen; - gLimit = s->save_gLimit; - gBase = s->save_gBase; - gPerm = s->save_gPerm; - - retVal = BZ_OK; - - switch (s->state) { - - GET_UCHAR(BZ_X_MAGIC_1, uc); - if (uc != BZ_HDR_B) RETURN(BZ_DATA_ERROR_MAGIC); - - GET_UCHAR(BZ_X_MAGIC_2, uc); - if (uc != BZ_HDR_Z) RETURN(BZ_DATA_ERROR_MAGIC); - - GET_UCHAR(BZ_X_MAGIC_3, uc) - if (uc != BZ_HDR_h) RETURN(BZ_DATA_ERROR_MAGIC); - - GET_BITS(BZ_X_MAGIC_4, s->blockSize100k, 8) - if (s->blockSize100k < (BZ_HDR_0 + 1) || - s->blockSize100k > (BZ_HDR_0 + 9)) RETURN(BZ_DATA_ERROR_MAGIC); - s->blockSize100k -= BZ_HDR_0; - - if (s->smallDecompress) { - s->ll16 = BZALLOC( s->blockSize100k * 100000 * sizeof(UInt16) ); - s->ll4 = BZALLOC( - ((1 + s->blockSize100k * 100000) >> 1) * sizeof(UChar) - ); - if (s->ll16 == NULL || s->ll4 == NULL) RETURN(BZ_MEM_ERROR); - } else { - s->tt = BZALLOC( s->blockSize100k * 100000 * sizeof(Int32) ); - if (s->tt == NULL) RETURN(BZ_MEM_ERROR); - } - - GET_UCHAR(BZ_X_BLKHDR_1, uc); - - if (uc == 0x17) goto endhdr_2; - if (uc != 0x31) RETURN(BZ_DATA_ERROR); - GET_UCHAR(BZ_X_BLKHDR_2, uc); - if (uc != 0x41) RETURN(BZ_DATA_ERROR); - GET_UCHAR(BZ_X_BLKHDR_3, uc); - if (uc != 0x59) RETURN(BZ_DATA_ERROR); - GET_UCHAR(BZ_X_BLKHDR_4, uc); - if (uc != 0x26) RETURN(BZ_DATA_ERROR); - GET_UCHAR(BZ_X_BLKHDR_5, uc); - if (uc != 0x53) RETURN(BZ_DATA_ERROR); - GET_UCHAR(BZ_X_BLKHDR_6, uc); - if (uc != 0x59) RETURN(BZ_DATA_ERROR); - - s->currBlockNo++; - if (s->verbosity >= 2) - VPrintf1 ( "\n [%d: huff+mtf ", s->currBlockNo ); - - s->storedBlockCRC = 0; - GET_UCHAR(BZ_X_BCRC_1, uc); - s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); - GET_UCHAR(BZ_X_BCRC_2, uc); - s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); - GET_UCHAR(BZ_X_BCRC_3, uc); - s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); - GET_UCHAR(BZ_X_BCRC_4, uc); - s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); - - GET_BITS(BZ_X_RANDBIT, s->blockRandomised, 1); - - s->origPtr = 0; - GET_UCHAR(BZ_X_ORIGPTR_1, uc); - s->origPtr = (s->origPtr << 8) | ((Int32)uc); - GET_UCHAR(BZ_X_ORIGPTR_2, uc); - s->origPtr = (s->origPtr << 8) | ((Int32)uc); - GET_UCHAR(BZ_X_ORIGPTR_3, uc); - s->origPtr = (s->origPtr << 8) | ((Int32)uc); - - if (s->origPtr < 0) - RETURN(BZ_DATA_ERROR); - if (s->origPtr > 10 + 100000*s->blockSize100k) - RETURN(BZ_DATA_ERROR); - - /*--- Receive the mapping table ---*/ - for (i = 0; i < 16; i++) { - GET_BIT(BZ_X_MAPPING_1, uc); - if (uc == 1) - s->inUse16[i] = True; else - s->inUse16[i] = False; - } - - for (i = 0; i < 256; i++) s->inUse[i] = False; - - for (i = 0; i < 16; i++) - if (s->inUse16[i]) - for (j = 0; j < 16; j++) { - GET_BIT(BZ_X_MAPPING_2, uc); - if (uc == 1) s->inUse[i * 16 + j] = True; - } - makeMaps_d ( s ); - if (s->nInUse == 0) RETURN(BZ_DATA_ERROR); - alphaSize = s->nInUse+2; - - /*--- Now the selectors ---*/ - GET_BITS(BZ_X_SELECTOR_1, nGroups, 3); - if (nGroups < 2 || nGroups > 6) RETURN(BZ_DATA_ERROR); - GET_BITS(BZ_X_SELECTOR_2, nSelectors, 15); - if (nSelectors < 1) RETURN(BZ_DATA_ERROR); - for (i = 0; i < nSelectors; i++) { - j = 0; - while (True) { - GET_BIT(BZ_X_SELECTOR_3, uc); - if (uc == 0) break; - j++; - if (j >= nGroups) RETURN(BZ_DATA_ERROR); - } - s->selectorMtf[i] = j; - } - - /*--- Undo the MTF values for the selectors. ---*/ - { - UChar pos[BZ_N_GROUPS], tmp, v; - for (v = 0; v < nGroups; v++) pos[v] = v; - - for (i = 0; i < nSelectors; i++) { - v = s->selectorMtf[i]; - tmp = pos[v]; - while (v > 0) { pos[v] = pos[v-1]; v--; } - pos[0] = tmp; - s->selector[i] = tmp; - } - } - - /*--- Now the coding tables ---*/ - for (t = 0; t < nGroups; t++) { - GET_BITS(BZ_X_CODING_1, curr, 5); - for (i = 0; i < alphaSize; i++) { - while (True) { - if (curr < 1 || curr > 20) RETURN(BZ_DATA_ERROR); - GET_BIT(BZ_X_CODING_2, uc); - if (uc == 0) break; - GET_BIT(BZ_X_CODING_3, uc); - if (uc == 0) curr++; else curr--; - } - s->len[t][i] = curr; - } - } - - /*--- Create the Huffman decoding tables ---*/ - for (t = 0; t < nGroups; t++) { - minLen = 32; - maxLen = 0; - for (i = 0; i < alphaSize; i++) { - if (s->len[t][i] > maxLen) maxLen = s->len[t][i]; - if (s->len[t][i] < minLen) minLen = s->len[t][i]; - } - BZ2_hbCreateDecodeTables ( - &(s->limit[t][0]), - &(s->base[t][0]), - &(s->perm[t][0]), - &(s->len[t][0]), - minLen, maxLen, alphaSize - ); - s->minLens[t] = minLen; - } - - /*--- Now the MTF values ---*/ - - EOB = s->nInUse+1; - nblockMAX = 100000 * s->blockSize100k; - groupNo = -1; - groupPos = 0; - - for (i = 0; i <= 255; i++) s->unzftab[i] = 0; - - /*-- MTF init --*/ - { - Int32 ii, jj, kk; - kk = MTFA_SIZE-1; - for (ii = 256 / MTFL_SIZE - 1; ii >= 0; ii--) { - for (jj = MTFL_SIZE-1; jj >= 0; jj--) { - s->mtfa[kk] = (UChar)(ii * MTFL_SIZE + jj); - kk--; - } - s->mtfbase[ii] = kk + 1; - } - } - /*-- end MTF init --*/ - - nblock = 0; - GET_MTF_VAL(BZ_X_MTF_1, BZ_X_MTF_2, nextSym); - - while (True) { - - if (nextSym == EOB) break; - - if (nextSym == BZ_RUNA || nextSym == BZ_RUNB) { - - es = -1; - N = 1; - do { - if (nextSym == BZ_RUNA) es = es + (0+1) * N; else - if (nextSym == BZ_RUNB) es = es + (1+1) * N; - N = N * 2; - GET_MTF_VAL(BZ_X_MTF_3, BZ_X_MTF_4, nextSym); - } - while (nextSym == BZ_RUNA || nextSym == BZ_RUNB); - - es++; - uc = s->seqToUnseq[ s->mtfa[s->mtfbase[0]] ]; - s->unzftab[uc] += es; - - if (s->smallDecompress) - while (es > 0) { - if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); - s->ll16[nblock] = (UInt16)uc; - nblock++; - es--; - } - else - while (es > 0) { - if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); - s->tt[nblock] = (UInt32)uc; - nblock++; - es--; - }; - - continue; - - } else { - - if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); - - /*-- uc = MTF ( nextSym-1 ) --*/ - { - Int32 ii, jj, kk, pp, lno, off; - UInt32 nn; - nn = (UInt32)(nextSym - 1); - - if (nn < MTFL_SIZE) { - /* avoid general-case expense */ - pp = s->mtfbase[0]; - uc = s->mtfa[pp+nn]; - while (nn > 3) { - Int32 z = pp+nn; - s->mtfa[(z) ] = s->mtfa[(z)-1]; - s->mtfa[(z)-1] = s->mtfa[(z)-2]; - s->mtfa[(z)-2] = s->mtfa[(z)-3]; - s->mtfa[(z)-3] = s->mtfa[(z)-4]; - nn -= 4; - } - while (nn > 0) { - s->mtfa[(pp+nn)] = s->mtfa[(pp+nn)-1]; nn--; - }; - s->mtfa[pp] = uc; - } else { - /* general case */ - lno = nn / MTFL_SIZE; - off = nn % MTFL_SIZE; - pp = s->mtfbase[lno] + off; - uc = s->mtfa[pp]; - while (pp > s->mtfbase[lno]) { - s->mtfa[pp] = s->mtfa[pp-1]; pp--; - }; - s->mtfbase[lno]++; - while (lno > 0) { - s->mtfbase[lno]--; - s->mtfa[s->mtfbase[lno]] - = s->mtfa[s->mtfbase[lno-1] + MTFL_SIZE - 1]; - lno--; - } - s->mtfbase[0]--; - s->mtfa[s->mtfbase[0]] = uc; - if (s->mtfbase[0] == 0) { - kk = MTFA_SIZE-1; - for (ii = 256 / MTFL_SIZE-1; ii >= 0; ii--) { - for (jj = MTFL_SIZE-1; jj >= 0; jj--) { - s->mtfa[kk] = s->mtfa[s->mtfbase[ii] + jj]; - kk--; - } - s->mtfbase[ii] = kk + 1; - } - } - } - } - /*-- end uc = MTF ( nextSym-1 ) --*/ - - s->unzftab[s->seqToUnseq[uc]]++; - if (s->smallDecompress) - s->ll16[nblock] = (UInt16)(s->seqToUnseq[uc]); else - s->tt[nblock] = (UInt32)(s->seqToUnseq[uc]); - nblock++; - - GET_MTF_VAL(BZ_X_MTF_5, BZ_X_MTF_6, nextSym); - continue; - } - } - - /* Now we know what nblock is, we can do a better sanity - check on s->origPtr. - */ - if (s->origPtr < 0 || s->origPtr >= nblock) - RETURN(BZ_DATA_ERROR); - - /*-- Set up cftab to facilitate generation of T^(-1) --*/ - s->cftab[0] = 0; - for (i = 1; i <= 256; i++) s->cftab[i] = s->unzftab[i-1]; - for (i = 1; i <= 256; i++) s->cftab[i] += s->cftab[i-1]; - for (i = 0; i <= 256; i++) { - if (s->cftab[i] < 0 || s->cftab[i] > nblock) { - /* s->cftab[i] can legitimately be == nblock */ - RETURN(BZ_DATA_ERROR); - } - } - - s->state_out_len = 0; - s->state_out_ch = 0; - BZ_INITIALISE_CRC ( s->calculatedBlockCRC ); - s->state = BZ_X_OUTPUT; - if (s->verbosity >= 2) VPrintf0 ( "rt+rld" ); - - if (s->smallDecompress) { - - /*-- Make a copy of cftab, used in generation of T --*/ - for (i = 0; i <= 256; i++) s->cftabCopy[i] = s->cftab[i]; - - /*-- compute the T vector --*/ - for (i = 0; i < nblock; i++) { - uc = (UChar)(s->ll16[i]); - SET_LL(i, s->cftabCopy[uc]); - s->cftabCopy[uc]++; - } - - /*-- Compute T^(-1) by pointer reversal on T --*/ - i = s->origPtr; - j = GET_LL(i); - do { - Int32 tmp = GET_LL(j); - SET_LL(j, i); - i = j; - j = tmp; - } - while (i != s->origPtr); - - s->tPos = s->origPtr; - s->nblock_used = 0; - if (s->blockRandomised) { - BZ_RAND_INIT_MASK; - BZ_GET_SMALL(s->k0); s->nblock_used++; - BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; - } else { - BZ_GET_SMALL(s->k0); s->nblock_used++; - } - - } else { - - /*-- compute the T^(-1) vector --*/ - for (i = 0; i < nblock; i++) { - uc = (UChar)(s->tt[i] & 0xff); - s->tt[s->cftab[uc]] |= (i << 8); - s->cftab[uc]++; - } - - s->tPos = s->tt[s->origPtr] >> 8; - s->nblock_used = 0; - if (s->blockRandomised) { - BZ_RAND_INIT_MASK; - BZ_GET_FAST(s->k0); s->nblock_used++; - BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; - } else { - BZ_GET_FAST(s->k0); s->nblock_used++; - } - - } - - RETURN(BZ_OK); - - - - endhdr_2: - - GET_UCHAR(BZ_X_ENDHDR_2, uc); - if (uc != 0x72) RETURN(BZ_DATA_ERROR); - GET_UCHAR(BZ_X_ENDHDR_3, uc); - if (uc != 0x45) RETURN(BZ_DATA_ERROR); - GET_UCHAR(BZ_X_ENDHDR_4, uc); - if (uc != 0x38) RETURN(BZ_DATA_ERROR); - GET_UCHAR(BZ_X_ENDHDR_5, uc); - if (uc != 0x50) RETURN(BZ_DATA_ERROR); - GET_UCHAR(BZ_X_ENDHDR_6, uc); - if (uc != 0x90) RETURN(BZ_DATA_ERROR); - - s->storedCombinedCRC = 0; - GET_UCHAR(BZ_X_CCRC_1, uc); - s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); - GET_UCHAR(BZ_X_CCRC_2, uc); - s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); - GET_UCHAR(BZ_X_CCRC_3, uc); - s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); - GET_UCHAR(BZ_X_CCRC_4, uc); - s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); - - s->state = BZ_X_IDLE; - RETURN(BZ_STREAM_END); - - default: AssertH ( False, 4001 ); - } - - AssertH ( False, 4002 ); - - save_state_and_return: - - s->save_i = i; - s->save_j = j; - s->save_t = t; - s->save_alphaSize = alphaSize; - s->save_nGroups = nGroups; - s->save_nSelectors = nSelectors; - s->save_EOB = EOB; - s->save_groupNo = groupNo; - s->save_groupPos = groupPos; - s->save_nextSym = nextSym; - s->save_nblockMAX = nblockMAX; - s->save_nblock = nblock; - s->save_es = es; - s->save_N = N; - s->save_curr = curr; - s->save_zt = zt; - s->save_zn = zn; - s->save_zvec = zvec; - s->save_zj = zj; - s->save_gSel = gSel; - s->save_gMinlen = gMinlen; - s->save_gLimit = gLimit; - s->save_gBase = gBase; - s->save_gPerm = gPerm; - - return retVal; -} - - -/*-------------------------------------------------------------*/ -/*--- end decompress.c ---*/ -/*-------------------------------------------------------------*/ diff --git a/externals/bzip2/huffman.c b/externals/bzip2/huffman.c deleted file mode 100644 index 87e79e38af0..00000000000 --- a/externals/bzip2/huffman.c +++ /dev/null @@ -1,205 +0,0 @@ - -/*-------------------------------------------------------------*/ -/*--- Huffman coding low-level stuff ---*/ -/*--- huffman.c ---*/ -/*-------------------------------------------------------------*/ - -/* ------------------------------------------------------------------ - This file is part of bzip2/libbzip2, a program and library for - lossless, block-sorting data compression. - - bzip2/libbzip2 version 1.0.5 of 10 December 2007 - Copyright (C) 1996-2007 Julian Seward - - Please read the WARNING, DISCLAIMER and PATENTS sections in the - README file. - - This program is released under the terms of the license contained - in the file LICENSE. - ------------------------------------------------------------------ */ - - -#include "bzlib_private.h" - -/*---------------------------------------------------*/ -#define WEIGHTOF(zz0) ((zz0) & 0xffffff00) -#define DEPTHOF(zz1) ((zz1) & 0x000000ff) -#define MYMAX(zz2,zz3) ((zz2) > (zz3) ? (zz2) : (zz3)) - -#define ADDWEIGHTS(zw1,zw2) \ - (WEIGHTOF(zw1)+WEIGHTOF(zw2)) | \ - (1 + MYMAX(DEPTHOF(zw1),DEPTHOF(zw2))) - -#define UPHEAP(z) \ -{ \ - Int32 zz, tmp; \ - zz = z; tmp = heap[zz]; \ - while (weight[tmp] < weight[heap[zz >> 1]]) { \ - heap[zz] = heap[zz >> 1]; \ - zz >>= 1; \ - } \ - heap[zz] = tmp; \ -} - -#define DOWNHEAP(z) \ -{ \ - Int32 zz, yy, tmp; \ - zz = z; tmp = heap[zz]; \ - while (True) { \ - yy = zz << 1; \ - if (yy > nHeap) break; \ - if (yy < nHeap && \ - weight[heap[yy+1]] < weight[heap[yy]]) \ - yy++; \ - if (weight[tmp] < weight[heap[yy]]) break; \ - heap[zz] = heap[yy]; \ - zz = yy; \ - } \ - heap[zz] = tmp; \ -} - - -/*---------------------------------------------------*/ -void BZ2_hbMakeCodeLengths ( UChar *len, - Int32 *freq, - Int32 alphaSize, - Int32 maxLen ) -{ - /*-- - Nodes and heap entries run from 1. Entry 0 - for both the heap and nodes is a sentinel. - --*/ - Int32 nNodes, nHeap, n1, n2, i, j, k; - Bool tooLong; - - Int32 heap [ BZ_MAX_ALPHA_SIZE + 2 ]; - Int32 weight [ BZ_MAX_ALPHA_SIZE * 2 ]; - Int32 parent [ BZ_MAX_ALPHA_SIZE * 2 ]; - - for (i = 0; i < alphaSize; i++) - weight[i+1] = (freq[i] == 0 ? 1 : freq[i]) << 8; - - while (True) { - - nNodes = alphaSize; - nHeap = 0; - - heap[0] = 0; - weight[0] = 0; - parent[0] = -2; - - for (i = 1; i <= alphaSize; i++) { - parent[i] = -1; - nHeap++; - heap[nHeap] = i; - UPHEAP(nHeap); - } - - AssertH( nHeap < (BZ_MAX_ALPHA_SIZE+2), 2001 ); - - while (nHeap > 1) { - n1 = heap[1]; heap[1] = heap[nHeap]; nHeap--; DOWNHEAP(1); - n2 = heap[1]; heap[1] = heap[nHeap]; nHeap--; DOWNHEAP(1); - nNodes++; - parent[n1] = parent[n2] = nNodes; - weight[nNodes] = ADDWEIGHTS(weight[n1], weight[n2]); - parent[nNodes] = -1; - nHeap++; - heap[nHeap] = nNodes; - UPHEAP(nHeap); - } - - AssertH( nNodes < (BZ_MAX_ALPHA_SIZE * 2), 2002 ); - - tooLong = False; - for (i = 1; i <= alphaSize; i++) { - j = 0; - k = i; - while (parent[k] >= 0) { k = parent[k]; j++; } - len[i-1] = j; - if (j > maxLen) tooLong = True; - } - - if (! tooLong) break; - - /* 17 Oct 04: keep-going condition for the following loop used - to be 'i < alphaSize', which missed the last element, - theoretically leading to the possibility of the compressor - looping. However, this count-scaling step is only needed if - one of the generated Huffman code words is longer than - maxLen, which up to and including version 1.0.2 was 20 bits, - which is extremely unlikely. In version 1.0.3 maxLen was - changed to 17 bits, which has minimal effect on compression - ratio, but does mean this scaling step is used from time to - time, enough to verify that it works. - - This means that bzip2-1.0.3 and later will only produce - Huffman codes with a maximum length of 17 bits. However, in - order to preserve backwards compatibility with bitstreams - produced by versions pre-1.0.3, the decompressor must still - handle lengths of up to 20. */ - - for (i = 1; i <= alphaSize; i++) { - j = weight[i] >> 8; - j = 1 + (j / 2); - weight[i] = j << 8; - } - } -} - - -/*---------------------------------------------------*/ -void BZ2_hbAssignCodes ( Int32 *code, - UChar *length, - Int32 minLen, - Int32 maxLen, - Int32 alphaSize ) -{ - Int32 n, vec, i; - - vec = 0; - for (n = minLen; n <= maxLen; n++) { - for (i = 0; i < alphaSize; i++) - if (length[i] == n) { code[i] = vec; vec++; }; - vec <<= 1; - } -} - - -/*---------------------------------------------------*/ -void BZ2_hbCreateDecodeTables ( Int32 *limit, - Int32 *base, - Int32 *perm, - UChar *length, - Int32 minLen, - Int32 maxLen, - Int32 alphaSize ) -{ - Int32 pp, i, j, vec; - - pp = 0; - for (i = minLen; i <= maxLen; i++) - for (j = 0; j < alphaSize; j++) - if (length[j] == i) { perm[pp] = j; pp++; }; - - for (i = 0; i < BZ_MAX_CODE_LEN; i++) base[i] = 0; - for (i = 0; i < alphaSize; i++) base[length[i]+1]++; - - for (i = 1; i < BZ_MAX_CODE_LEN; i++) base[i] += base[i-1]; - - for (i = 0; i < BZ_MAX_CODE_LEN; i++) limit[i] = 0; - vec = 0; - - for (i = minLen; i <= maxLen; i++) { - vec += (base[i+1] - base[i]); - limit[i] = vec-1; - vec <<= 1; - } - for (i = minLen + 1; i <= maxLen; i++) - base[i] = ((limit[i-1] + 1) << 1) - base[i]; -} - - -/*-------------------------------------------------------------*/ -/*--- end huffman.c ---*/ -/*-------------------------------------------------------------*/ diff --git a/externals/bzip2/randtable.c b/externals/bzip2/randtable.c deleted file mode 100644 index 068b76367bc..00000000000 --- a/externals/bzip2/randtable.c +++ /dev/null @@ -1,84 +0,0 @@ - -/*-------------------------------------------------------------*/ -/*--- Table for randomising repetitive blocks ---*/ -/*--- randtable.c ---*/ -/*-------------------------------------------------------------*/ - -/* ------------------------------------------------------------------ - This file is part of bzip2/libbzip2, a program and library for - lossless, block-sorting data compression. - - bzip2/libbzip2 version 1.0.5 of 10 December 2007 - Copyright (C) 1996-2007 Julian Seward - - Please read the WARNING, DISCLAIMER and PATENTS sections in the - README file. - - This program is released under the terms of the license contained - in the file LICENSE. - ------------------------------------------------------------------ */ - - -#include "bzlib_private.h" - - -/*---------------------------------------------*/ -Int32 BZ2_rNums[512] = { - 619, 720, 127, 481, 931, 816, 813, 233, 566, 247, - 985, 724, 205, 454, 863, 491, 741, 242, 949, 214, - 733, 859, 335, 708, 621, 574, 73, 654, 730, 472, - 419, 436, 278, 496, 867, 210, 399, 680, 480, 51, - 878, 465, 811, 169, 869, 675, 611, 697, 867, 561, - 862, 687, 507, 283, 482, 129, 807, 591, 733, 623, - 150, 238, 59, 379, 684, 877, 625, 169, 643, 105, - 170, 607, 520, 932, 727, 476, 693, 425, 174, 647, - 73, 122, 335, 530, 442, 853, 695, 249, 445, 515, - 909, 545, 703, 919, 874, 474, 882, 500, 594, 612, - 641, 801, 220, 162, 819, 984, 589, 513, 495, 799, - 161, 604, 958, 533, 221, 400, 386, 867, 600, 782, - 382, 596, 414, 171, 516, 375, 682, 485, 911, 276, - 98, 553, 163, 354, 666, 933, 424, 341, 533, 870, - 227, 730, 475, 186, 263, 647, 537, 686, 600, 224, - 469, 68, 770, 919, 190, 373, 294, 822, 808, 206, - 184, 943, 795, 384, 383, 461, 404, 758, 839, 887, - 715, 67, 618, 276, 204, 918, 873, 777, 604, 560, - 951, 160, 578, 722, 79, 804, 96, 409, 713, 940, - 652, 934, 970, 447, 318, 353, 859, 672, 112, 785, - 645, 863, 803, 350, 139, 93, 354, 99, 820, 908, - 609, 772, 154, 274, 580, 184, 79, 626, 630, 742, - 653, 282, 762, 623, 680, 81, 927, 626, 789, 125, - 411, 521, 938, 300, 821, 78, 343, 175, 128, 250, - 170, 774, 972, 275, 999, 639, 495, 78, 352, 126, - 857, 956, 358, 619, 580, 124, 737, 594, 701, 612, - 669, 112, 134, 694, 363, 992, 809, 743, 168, 974, - 944, 375, 748, 52, 600, 747, 642, 182, 862, 81, - 344, 805, 988, 739, 511, 655, 814, 334, 249, 515, - 897, 955, 664, 981, 649, 113, 974, 459, 893, 228, - 433, 837, 553, 268, 926, 240, 102, 654, 459, 51, - 686, 754, 806, 760, 493, 403, 415, 394, 687, 700, - 946, 670, 656, 610, 738, 392, 760, 799, 887, 653, - 978, 321, 576, 617, 626, 502, 894, 679, 243, 440, - 680, 879, 194, 572, 640, 724, 926, 56, 204, 700, - 707, 151, 457, 449, 797, 195, 791, 558, 945, 679, - 297, 59, 87, 824, 713, 663, 412, 693, 342, 606, - 134, 108, 571, 364, 631, 212, 174, 643, 304, 329, - 343, 97, 430, 751, 497, 314, 983, 374, 822, 928, - 140, 206, 73, 263, 980, 736, 876, 478, 430, 305, - 170, 514, 364, 692, 829, 82, 855, 953, 676, 246, - 369, 970, 294, 750, 807, 827, 150, 790, 288, 923, - 804, 378, 215, 828, 592, 281, 565, 555, 710, 82, - 896, 831, 547, 261, 524, 462, 293, 465, 502, 56, - 661, 821, 976, 991, 658, 869, 905, 758, 745, 193, - 768, 550, 608, 933, 378, 286, 215, 979, 792, 961, - 61, 688, 793, 644, 986, 403, 106, 366, 905, 644, - 372, 567, 466, 434, 645, 210, 389, 550, 919, 135, - 780, 773, 635, 389, 707, 100, 626, 958, 165, 504, - 920, 176, 193, 713, 857, 265, 203, 50, 668, 108, - 645, 990, 626, 197, 510, 357, 358, 850, 858, 364, - 936, 638 -}; - - -/*-------------------------------------------------------------*/ -/*--- end randtable.c ---*/ -/*-------------------------------------------------------------*/ diff --git a/externals/g3dlite/AABox.cpp b/externals/g3dlite/AABox.cpp deleted file mode 100644 index 035497aa3c4..00000000000 --- a/externals/g3dlite/AABox.cpp +++ /dev/null @@ -1,366 +0,0 @@ -/** - @file AABox.cpp - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2004-01-10 - @edited 2006-01-11 -*/ - -#include "G3D/platform.h" -#include "G3D/AABox.h" -#include "G3D/Box.h" -#include "G3D/Plane.h" -#include "G3D/Sphere.h" -#include "G3D/BinaryInput.h" -#include "G3D/BinaryOutput.h" - - -namespace G3D { - -const AABox& AABox::maxFinite() { - static const AABox b = AABox(Vector3::minFinite(), - Vector3::maxFinite()); - return b; -} - - -const AABox& AABox::large() { - static const AABox b = AABox(Vector3::minFinite() * 0.5f, - Vector3::maxFinite() * 0.5f); - return b; -} - - -const AABox& AABox::inf() { - static const AABox b = AABox(-Vector3::inf(), Vector3::inf()); - return b; -} - - -const AABox& AABox::zero() { - static const AABox b = AABox(Vector3::zero(), Vector3::zero()); - return b; -} - - -void AABox::serialize(class BinaryOutput& b) const { - b.writeVector3(lo); - b.writeVector3(hi); -} - - -void AABox::deserialize(class BinaryInput& b) { - lo = b.readVector3(); - hi = b.readVector3(); -} - - -void AABox::split(const Vector3::Axis& axis, float location, AABox& low, AABox& high) const { - // Low, medium, and high along the chosen axis - float L = G3D::min(location, lo[axis]); - float M = G3D::min(G3D::max(location, lo[axis]), hi[axis]); - float H = G3D::max(location, hi[axis]); - - // Copy over this box. - high = low = *this; - - // Now move the split points along the special axis - low.lo[axis] = L; - low.hi[axis] = M; - high.lo[axis] = M; - high.hi[axis] = H; -} - - -Vector3 AABox::randomSurfacePoint() const { - Vector3 extent = hi - lo; - float aXY = extent.x * extent.y; - float aYZ = extent.y * extent.z; - float aZX = extent.z * extent.x; - - float r = (float)uniformRandom(0.0f, aXY + aYZ + aZX); - - // Choose evenly between positive and negative face planes - float d = ((float)uniformRandom(0, 1) < 0.5f) ? 0.0f : 1.0f; - - // The probability of choosing a given face is proportional to - // its area. - if (r < aXY) { - return - lo + - Vector3( - (float)uniformRandom(0.0f, extent.x), - (float)uniformRandom(0.0f, extent.y), - d * extent.z); - } else if (r < aYZ) { - return - lo + - Vector3( - d * extent.x, - (float)uniformRandom(0, extent.y), - (float)uniformRandom(0, extent.z)); - } else { - return - lo + - Vector3( - (float)uniformRandom(0, extent.x), - d * extent.y, - (float)uniformRandom(0, extent.z)); - } -} - - -Vector3 AABox::randomInteriorPoint() const { - return Vector3( - (float)uniformRandom(lo.x, hi.x), - (float)uniformRandom(lo.y, hi.y), - (float)uniformRandom(lo.z, hi.z)); -} - - -bool AABox::intersects(const AABox& other) const { - // Must be overlap along all three axes. - // Try to find a separating axis. - - for (int a = 0; a < 3; ++a) { - - // |--------| - // |------| - - if ((lo[a] > other.hi[a]) || - (hi[a] < other.lo[a])) { - return false; - } - } - - return true; -} - -int AABox::dummy = 0; - -bool AABox::culledBy( - const Array& plane, - int& cullingPlane, - const uint32 _inMask, - uint32& childMask) const { - - uint32 inMask = _inMask; - assert(plane.size() < 31); - - childMask = 0; - - const bool finite = - (abs(lo.x) < G3D::finf()) && - (abs(hi.x) < G3D::finf()) && - (abs(lo.y) < G3D::finf()) && - (abs(hi.y) < G3D::finf()) && - (abs(lo.z) < G3D::finf()) && - (abs(hi.z) < G3D::finf()); - - // See if there is one plane for which all of the - // vertices are in the negative half space. - for (int p = 0; p < plane.size(); ++p) { - - // Only test planes that are not masked - if ((inMask & 1) != 0) { - - Vector3 corner; - - int numContained = 0; - int v = 0; - - // We can early-out only if we have found one point on each - // side of the plane (i.e. if we are straddling). That - // occurs when (numContained < v) && (numContained > 0) - for (v = 0; (v < 8) && ((numContained == v) || (numContained == 0)); ++v) { - // Unrolling these 3 if's into a switch decreases performance - // by about 2x - corner.x = (v & 1) ? hi.x : lo.x; - corner.y = (v & 2) ? hi.y : lo.y; - corner.z = (v & 4) ? hi.z : lo.z; - - if (finite) { // this branch is highly predictable - if (plane[p].halfSpaceContainsFinite(corner)) { - ++numContained; - } - } else { - if (plane[p].halfSpaceContains(corner)) { - ++numContained; - } - } - } - - if (numContained == 0) { - // Plane p culled the box - cullingPlane = p; - - // The caller should not recurse into the children, - // since the parent is culled. If they do recurse, - // make them only test against this one plane, which - // will immediately cull the volume. - childMask = 1 << p; - return true; - - } else if (numContained < v) { - // The bounding volume straddled the plane; we have - // to keep testing against this plane - childMask |= (1 << p); - } - } - - // Move on to the next bit. - inMask = inMask >> 1; - } - - // None of the planes could cull this box - cullingPlane = -1; - return false; -} - - -bool AABox::culledBy( - const Array& plane, - int& cullingPlane, - const uint32 _inMask) const { - - uint32 inMask = _inMask; - assert(plane.size() < 31); - - const bool finite = - (abs(lo.x) < G3D::finf()) && - (abs(hi.x) < G3D::finf()) && - (abs(lo.y) < G3D::finf()) && - (abs(hi.y) < G3D::finf()) && - (abs(lo.z) < G3D::finf()) && - (abs(hi.z) < G3D::finf()); - - // See if there is one plane for which all of the - // vertices are in the negative half space. - for (int p = 0; p < plane.size(); ++p) { - - // Only test planes that are not masked - if ((inMask & 1) != 0) { - - bool culled = true; - Vector3 corner; - - int v; - - // Assume this plane culls all points. See if there is a point - // not culled by the plane... early out when at least one point - // is in the positive half space. - for (v = 0; (v < 8) && culled; ++v) { - - // Unrolling these 3 if's into a switch decreases performance - // by about 2x - corner.x = (v & 1) ? hi.x : lo.x; - corner.y = (v & 2) ? hi.y : lo.y; - corner.z = (v & 4) ? hi.z : lo.z; - - if (finite) { // this branch is highly predictable - culled = ! plane[p].halfSpaceContainsFinite(corner); - } else { - culled = ! plane[p].halfSpaceContains(corner); - } - } - - if (culled) { - // Plane p culled the box - cullingPlane = p; - - return true; - } - } - - // Move on to the next bit. - inMask = inMask >> 1; - } - - // None of the planes could cull this box - cullingPlane = -1; - return false; -} - - -bool AABox::intersects(const class Sphere& sphere) const { - double d = 0; - - //find the square of the distance - //from the sphere to the box - for (int i = 0; i < 3; ++i) { - if (sphere.center[i] < lo[i]) { - d += square(sphere.center[i] - lo[i]); - } else if (sphere.center[i] > hi[i]) { - d += square(sphere.center[i] - hi[i]); - } - } - - return d <= square(sphere.radius); -} - -Vector3 AABox::corner(int index) const { - - // default constructor inits all components to 0 - Vector3 v; - - switch (index) - { - case 0: - v.x = lo.x; - v.y = lo.y; - v.z = hi.z; - break; - - case 1: - v.x = hi.x; - v.y = lo.y; - v.z = hi.z; - break; - - case 2: - v.x = hi.x; - v.y = hi.y; - v.z = hi.z; - break; - - case 3: - v.x = lo.x; - v.y = hi.y; - v.z = hi.z; - break; - - case 4: - v.x = lo.x; - v.y = lo.y; - v.z = lo.z; - break; - - case 5: - v.x = hi.x; - v.y = lo.y; - v.z = lo.z; - break; - - case 6: - v.x = hi.x; - v.y = hi.y; - v.z = lo.z; - break; - - case 7: - v.x = lo.x; - v.y = hi.y; - v.z = lo.z; - break; - - default: - debugAssertM(false, "Invalid corner index"); - break; - } - - return v; -} - - -} diff --git a/externals/g3dlite/Any.cpp b/externals/g3dlite/Any.cpp deleted file mode 100644 index de4d32e83ea..00000000000 --- a/externals/g3dlite/Any.cpp +++ /dev/null @@ -1,1237 +0,0 @@ -/** - @file Any.cpp - - @author Morgan McGuire - @author Shawn Yarbrough - - @created 2006-06-11 - @edited 2009-11-15 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ - -#include "G3D/Any.h" -#include "G3D/TextOutput.h" -#include "G3D/TextInput.h" -#include "G3D/stringutils.h" -#include -#include - -namespace G3D { - -void Any::beforeRead() const { - if (isPlaceholder()) { - // Tried to read from a placeholder--throw an exception as if - // the original operator[] had failed. - KeyNotFound e; - alwaysAssertM(m_data, "Corrupt placeholder"); - - e.filename = m_data->source.filename; - e.line = m_data->source.line; - e.character = m_data->source.character; - e.key = m_placeholderName; - e.message = - "This exception may have been thrown later than " - "the actual operator[] invocation."; - - throw e; - } -} - - -Any::Data* Any::Data::create(const Data* d) { - Data* p = create(d->type); - - p->comment = d->comment; - p->name = d->name; - - switch (d->type) { - case NONE: - case BOOLEAN: - case NUMBER: - // No clone needed - break; - - case STRING: - *(p->value.s) = *(d->value.s); - break; - - case ARRAY: - *(p->value.a) = *(d->value.a); - break; - - case TABLE: - *(p->value.t) = *(d->value.t); - // Note that placeholders may be copied; that is ok--they are still - // just placeholders. - break; - } - - return p; -} - - -Any::Data* Any::Data::create(Any::Type t) { - size_t s = sizeof(Data); - - switch (t) { - case NONE: - case BOOLEAN: - case NUMBER: - // No extra space needed - break; - - case STRING: - s += sizeof(std::string); - break; - - case ARRAY: - s += sizeof(AnyArray); - break; - - case TABLE: - s += sizeof(AnyTable); - break; - } - - // Allocate the data object - Data* p = new (MemoryManager::create()->alloc(s)) Data(t); - - // Create the (empyt) value object at the end of the Data object - switch (t) { - case NONE: - case BOOLEAN: - case NUMBER: - // No value - break; - - case STRING: - p->value.s = new (p + 1) std::string(); - break; - - case ARRAY: - p->value.a = new (p + 1) AnyArray(); - break; - - case TABLE: - p->value.t = new (p + 1) AnyTable(); - break; - } - - return p; -} - - -void Any::Data::destroy(Data* d) { - if (d != NULL) { - d->~Data(); - MemoryManager::create()->free(d); - } -} - - -Any::Data::~Data() { - debugAssertM(referenceCount.value() <= 0, "Deleted while still referenced."); - - // Destruct but do not deallocate children - switch (type) { - case STRING: - debugAssert(value.s != NULL); - value.s->~basic_string(); - break; - - case ARRAY: - debugAssert(value.a != NULL); - value.a->~Array(); - break; - - case TABLE: - debugAssert(value.t != NULL); - value.t->~Table(); - break; - - default: - // All other types should have a NULL value pointer (i.e., they were used just for name and comment fields) - debugAssertM(value.s == NULL, "Corrupt Any::Data::Value"); - } - - value.s = NULL; -} - - -////////////////////////////////////////////////////////////// - -bool Any::containsKey(const std::string& x) const { - beforeRead(); - verifyType(TABLE); - - Any* a = m_data->value.t->getPointer(x); - - // Don't return true for placeholder objects - return (a != NULL) && (! a->isPlaceholder()); -} - - -void Any::dropReference() { - if (m_data && m_data->referenceCount.decrement() <= 0) { - // This was the last reference to the shared data - Data::destroy(m_data); - } - m_data = NULL; -} - - -void Any::ensureMutable() { - if (m_data && (m_data->referenceCount.value() >= 1)) { - // Copy the data. We must do this before dropping the reference - // to avoid a race condition - Data* d = Data::create(m_data); - dropReference(); - m_data = d; - } -} - - -Any::Any() : m_type(NONE), m_data(NULL) { -} - - -Any::Any(TextInput& t) : m_type(NONE), m_data(NULL) { - deserialize(t); -} - - -Any::Any(const Any& x) : m_type(NONE), m_data(NULL) { - x.beforeRead(); - *this = x; -} - - -Any::Any(double x) : m_type(NUMBER), m_simpleValue(x), m_data(NULL) { -} - - -#ifdef G3D_32BIT -Any::Any(int64 x) : m_type(NUMBER), m_simpleValue((double)x), m_data(NULL) { -} -#endif // G3D_32BIT - - -Any::Any(long x) : m_type(NUMBER), m_simpleValue((double)x), m_data(NULL) { -} - - -Any::Any(int x) : m_type(NUMBER), m_simpleValue((double)x), m_data(NULL) { -} - - -Any::Any(short x) : m_type(NUMBER), m_simpleValue((double)x), m_data(NULL) { -} - - -Any::Any(bool x) : m_type(BOOLEAN), m_simpleValue(x), m_data(NULL) { -} - - -Any::Any(const std::string& s) : m_type(STRING), m_data(Data::create(STRING)) { - *(m_data->value.s) = s; -} - - -Any::Any(const char* s) : m_type(STRING), m_data(NULL) { - if (s == NULL) { - m_type = NONE; - } else { - ensureData(); - *(m_data->value.s) = s; - } -} - - -Any::Any(Type t, const std::string& name) : m_type(t), m_data(NULL) { - alwaysAssertM(t == ARRAY || t == TABLE, "Can only create ARRAY or TABLE from Type enum."); - - ensureData(); - if (name != "") { - m_data->name = name; - } -} - - -Any::~Any() { - dropReference(); -} - - -void Any::beforeWrite() { - if (isPlaceholder()) { - // This is no longer a placeholder - m_placeholderName = ""; - } -} - -Any& Any::operator=(const Any& x) { - x.beforeRead(); - - if (this == &x) { - return *this; - } - - beforeWrite(); - - dropReference(); - - m_type = x.m_type; - m_simpleValue = x.m_simpleValue; - - if (x.m_data != NULL) { - x.m_data->referenceCount.increment(); - m_data = x.m_data; - } - - return *this; -} - - -Any& Any::operator=(double x) { - *this = Any(x); - return *this; -} - - -Any& Any::operator=(int x) { - return (*this = Any(x)); -} - - -Any& Any::operator=(bool x) { - *this = Any(x); - return *this; -} - - -Any& Any::operator=(const std::string& x) { - *this = Any(x); - return *this; -} - - -Any& Any::operator=(const char* x) { - *this = Any(x); - return *this; -} - - -Any& Any::operator=(Type t) { - switch (t) { - case NONE: - *this = Any(); - break; - - case TABLE: - case ARRAY: - *this = Any(t); - break; - - default: - alwaysAssertM(false, "Can only assign NONE, TABLE, or ARRAY Type enum."); - } - - return *this; -} - - -Any::Type Any::type() const { - beforeRead(); - return m_type; -} - - -const std::string& Any::comment() const { - beforeRead(); - - static const std::string blank; - if (m_data != NULL) { - return m_data->comment; - } else { - return blank; - } -} - - -void Any::setComment(const std::string& c) { - beforeRead(); - ensureData(); - m_data->comment = c; -} - - -bool Any::isNone() const { - beforeRead(); - return (m_type == NONE); -} - - -double Any::number() const { - beforeRead(); - verifyType(NUMBER); - return m_simpleValue.n; -} - - -const std::string& Any::string() const { - beforeRead(); - verifyType(STRING); - return *(m_data->value.s); -} - - -bool Any::boolean() const { - beforeRead(); - verifyType(BOOLEAN); - return m_simpleValue.b; -} - - -const std::string& Any::name() const { - beforeRead(); - static const std::string blank; - if (m_data != NULL) { - return m_data->name; - } else { - return blank; - } -} - - -void Any::setName(const std::string& n) { - beforeRead(); - ensureData(); - m_data->name = n; -} - - -int Any::size() const { - beforeRead(); - verifyType(ARRAY, TABLE); - switch (m_type) { - case TABLE: - return m_data->value.t->size(); - - case ARRAY: - return m_data->value.a->size(); - - default:; - return 0; - } // switch (m_type) -} - - -int Any::length() const { - beforeRead(); - return size(); -} - - -void Any::resize(int n) { - beforeRead(); - alwaysAssertM(n >= 0, "Cannot resize less than 0."); - verifyType(ARRAY); - m_data->value.a->resize(n); -} - - -void Any::clear() { - beforeRead(); - verifyType(ARRAY, TABLE); - switch (m_type) { - case ARRAY: - m_data->value.a->clear(); - break; - - case TABLE: - m_data->value.t->clear(); - break; - - default:; - } -} - - -const Any& Any::operator[](int i) const { - beforeRead(); - verifyType(ARRAY); - debugAssert(m_data != NULL); - Array& array = *(m_data->value.a); - return array[i]; -} - - -Any& Any::next() { - beforeRead(); - verifyType(ARRAY); - int n = size(); - resize(n + 1); - return (*this)[n]; -} - - -Any& Any::operator[](int i) { - beforeRead(); - verifyType(ARRAY); - debugAssert(m_data != NULL); - Array& array = *(m_data->value.a); - return array[i]; -} - - -const Array& Any::array() const { - beforeRead(); - verifyType(ARRAY); - debugAssert(m_data != NULL); - return *(m_data->value.a); -} - - -void Any::append(const Any& x0) { - beforeRead(); - verifyType(ARRAY); - debugAssert(m_data != NULL); - m_data->value.a->append(x0); -} - - -void Any::append(const Any& x0, const Any& x1) { - beforeRead(); - append(x0); - append(x1); -} - - -void Any::append(const Any& x0, const Any& x1, const Any& x2) { - beforeRead(); - append(x0); - append(x1); - append(x2); -} - - -void Any::append(const Any& x0, const Any& x1, const Any& x2, const Any& x3) { - beforeRead(); - append(x0); - append(x1); - append(x2); - append(x3); -} - - -const Table& Any::table() const { - beforeRead(); - verifyType(TABLE); - debugAssert(m_data != NULL); - return *(m_data->value.t); -} - - -const Any& Any::operator[](const std::string& x) const { - beforeRead(); - verifyType(TABLE); - debugAssert(m_data != NULL); - const Table& table = *(m_data->value.t); - Any* value = table.getPointer(x); - if (value == NULL) { - KeyNotFound e; - if (m_data) { - e.filename = m_data->source.filename; - e.line = m_data->source.line; - e.character = m_data->source.character; - } - e.key = x; - throw e; - } - return *value; -} - - -Any& Any::operator[](const std::string& key) { - beforeRead(); - verifyType(TABLE); - - bool created = false; - Any& value = m_data->value.t->getCreate(key, created); - - if (created) { - // The entry was created by this method; do not allow it to be - // read before it is written. - value.m_placeholderName = key; - - // Write source data for the value - value.ensureData(); - value.m_data->source = source(); - } - - return value; -} - - -void Any::set(const std::string& k, const Any& v) { - beforeRead(); - v.beforeRead(); - verifyType(TABLE); - debugAssert(m_data != NULL); - Table& table = *(m_data->value.t); - table.set(k, v); -} - - -const Any& Any::get(const std::string& x, const Any& defaultVal) const { - beforeRead(); - defaultVal.beforeRead(); - try { - return operator[](x); - } catch(KeyNotFound) { - return defaultVal; - } -} - - -bool Any::operator==(const Any& x) const { - beforeRead(); - x.beforeRead(); - if (m_type != x.m_type) { - return false; - } - - switch (m_type) { - case NONE: - return true; - - case BOOLEAN: - return (m_simpleValue.b == x.m_simpleValue.b); - - case NUMBER: - return (m_simpleValue.n == x.m_simpleValue.n); - - case STRING: - debugAssert(m_data != NULL); - return (*(m_data->value.s) == *(x.m_data->value.s)); - - case TABLE: { - if (size() != x.size()) { - return false; - } - debugAssert(m_data != NULL); - if (m_data->name != x.m_data->name) { - return false; - } - Table& cmptable = *( m_data->value.t); - Table& xcmptable = *(x.m_data->value.t); - for (Table::Iterator it1 = cmptable.begin(), it2 = xcmptable.begin(); - it1 != cmptable.end() && it2 != xcmptable.end(); - ++it1, ++it2) { - if (*it1 != *it2) { - return false; - } - } - return true; - } - - case ARRAY: { - if (size() != x.size()) { - return false; - } - debugAssert(m_data != NULL); - if (m_data->name != x.m_data->name) { - return false; - } - - Array& cmparray = *( m_data->value.a); - Array& xcmparray = *(x.m_data->value.a); - - for (int ii = 0; ii < size(); ++ii) { - if (cmparray[ii] != xcmparray[ii]) { - return false; - } - } - return true; - } - - default: - alwaysAssertM(false, "Unknown type."); - return false; - } // switch (m_type) - -} - - -bool Any::operator!=(const Any& x) const { - beforeRead(); - x.beforeRead(); - return !operator==(x); -} - - -static void getDeserializeSettings(TextInput::Settings& settings) { - settings.cppBlockComments = true; - settings.cppLineComments = true; - settings.otherLineComments = true; - settings.otherCommentCharacter = '#'; - settings.generateCommentTokens = true; - settings.singleQuotedStrings = false; - settings.msvcSpecials = false; - settings.caseSensitive = false; -} - - -std::string Any::unparse() const { - beforeRead(); - TextOutput::Settings settings; - TextOutput to(settings); - serialize(to); - return to.commitString(); -} - - -void Any::parse(const std::string& src) { - beforeRead(); - TextInput::Settings settings; - getDeserializeSettings(settings); - - TextInput ti(TextInput::FROM_STRING, src, settings); - deserialize(ti); -} - - -void Any::load(const std::string& filename) { - beforeRead(); - TextInput::Settings settings; - getDeserializeSettings(settings); - - TextInput ti(filename, settings); - deserialize(ti); -} - - -void Any::save(const std::string& filename) const { - beforeRead(); - TextOutput::Settings settings; - settings.wordWrap = TextOutput::Settings::WRAP_NONE; - - TextOutput to(filename,settings); - serialize(to); - to.commit(); -} - - -static bool needsQuotes(const std::string& s) { - if (! isLetter(s[0]) && (s[0] != '_')) { - return true; - } - - for (int i = 0; i < (int)s.length(); ++i) { - char c = s[i]; - - // peek character - char p = (i == (int)s.length() - 1) ? '_' : s[i + 1]; - - // Identify separators - if ((c == '-' && p == '>') || - (c == ':' && p == ':')) { - // Skip over this symbol - ++i; - continue; - } - - if (! isDigit(c) && ! isLetter(c) & (c != '.')) { - // This is an illegal character for an identifier, so we need quotes - return true; - } - } - - return false; -} - - -// TODO: if the output will fit on one line, compress tables and arrays into a single line -void Any::serialize(TextOutput& to) const { - beforeRead(); - if (m_data && ! m_data->comment.empty()) { - to.printf("\n/* %s */\n", m_data->comment.c_str()); - } - - switch (m_type) { - case NONE: - to.writeSymbol("NONE"); - break; - - case BOOLEAN: - to.writeBoolean(m_simpleValue.b); - break; - - case NUMBER: - to.writeNumber(m_simpleValue.n); - break; - - case STRING: - debugAssert(m_data != NULL); - to.writeString(*(m_data->value.s)); - break; - - case TABLE: { - debugAssert(m_data != NULL); - if (! m_data->name.empty()) { - if (needsQuotes(m_data->name)) { - to.writeString(m_data->name); - } else { - to.writeSymbol(m_data->name); - } - } - to.writeSymbol("{"); - to.writeNewline(); - to.pushIndent(); - AnyTable& table = *(m_data->value.t); - Array keys; - table.getKeys(keys); - keys.sort(); - - for (int i = 0; i < keys.size(); ++i) { - - to.writeSymbol(keys[i]); - to.writeSymbol("="); - table[keys[i]].serialize(to); - - if (i < keys.size() - 1) { - to.writeSymbol(","); - } - to.writeNewline(); - - // Skip a line between table entries - to.writeNewline(); - } - - to.popIndent(); - to.writeSymbol("}"); - break; - } - - case ARRAY: { - debugAssert(m_data != NULL); - if (! m_data->name.empty()) { - // For arrays, leave no trailing space between the name and the paren - to.writeSymbol(format("%s(", m_data->name.c_str())); - } else { - to.writeSymbol("("); - } - to.writeNewline(); - to.pushIndent(); - Array& array = *(m_data->value.a); - for (int ii = 0; ii < size(); ++ii) { - array[ii].serialize(to); - if (ii < size() - 1) { - to.writeSymbol(","); - to.writeNewline(); - } - - // Put the close paren on an array right behind the last element - } - to.popIndent(); - to.writeSymbol(")"); - break; - } - } -} - - -void Any::deserializeComment(TextInput& ti, Token& token, std::string& comment) { - // Parse comments - while (token.type() == Token::COMMENT) { - comment += trimWhitespace(token.string()) + "\n"; - - // Allow comments to contain newlines. - do { - token = ti.read(); - comment += "\n"; - } while (token.type() == Token::NEWLINE); - } - - comment = trimWhitespace(comment); -} - -/** True if \a c is an open paren of some form */ -static bool isOpen(const char c) { - return c == '(' || c == '[' || c == '{'; -} - - -/** True if \a c is an open paren of some form */ -static bool isClose(const char c) { - return c == ')' || c == ']' || c == '}'; -} - - -/** True if \a s is a C++ name operator */ -static bool isNameOperator(const std::string& s) { - return s == "." || s == "::" || s == "->"; -} - - -void Any::deserializeName(TextInput& ti, Token& token, std::string& name) { - debugAssert(token.type() == Token::SYMBOL); - std::string s = token.string(); - while (! isOpen(s[0])) { - name += s; - - // Skip newlines and comments - token = ti.readSignificant(); - - if (token.type() != Token::SYMBOL) { - throw ParseError(ti.filename(), token.line(), token.character(), - "Expected symbol while parsing Any"); - } - s = token.string(); - } -} - - -void Any::deserialize(TextInput& ti) { - beforeRead(); - Token token = ti.read(); - deserialize(ti, token); - // Restore the last token - ti.push(token); -} - - -void Any::deserialize(TextInput& ti, Token& token) { - // Deallocate old data - dropReference(); - m_type = NONE; - m_simpleValue.b = false; - - // Skip leading newlines - while (token.type() == Token::NEWLINE) { - token = ti.read(); - } - - std::string comment; - if (token.type() == Token::COMMENT) { - deserializeComment(ti, token, comment); - } - - if (token.type() == Token::END) { - // There should never be a comment without an Any following it; even - // if the file ends with some commented out stuff, - // that should not happen after a comma, so we'd never read that - // far in a proper file. - throw ParseError(ti.filename(), token.line(), token.character(), - "File ended without a properly formed Any"); - } - - switch (token.type()) { - case Token::STRING: - m_type = STRING; - ensureData(); - *(m_data->value.s) = token.string(); - m_data->source.set(ti, token); - break; - - case Token::NUMBER: - m_type = NUMBER; - m_simpleValue.n = token.number(); - ensureData(); - m_data->source.set(ti, token); - break; - - case Token::BOOLEAN: - m_type = BOOLEAN; - m_simpleValue.b = token.boolean(); - ensureData(); - m_data->source.set(ti, token); - break; - - case Token::SYMBOL: - // Named Array, Named Table, Array, Table, or NONE - if (toUpper(token.string()) == "NONE") { - // Nothing left to do; we initialized to NONE originally - ensureData(); - m_data->source.set(ti, token); - } else { - // Array or Table - - // Parse the name - - // s must have at least one element or this would not have - // been parsed as a symbol - std::string name; - deserializeName(ti, token, name); - if (token.type() != Token::SYMBOL) { - throw ParseError(ti.filename(), token.line(), token.character(), - "Malformed Any TABLE or ARRAY; must start with [, (, or {"); - } - - if (isOpen(token.string()[0])) { - // Array or table - deserializeBody(ti, token); - } else { - throw ParseError(ti.filename(), token.line(), token.character(), - "Malformed Any TABLE or ARRAY; must start with [, (, or {"); - } - - if (! name.empty()) { - ensureData(); - m_data->name = name; - } - } // if NONE - break; - - default: - throw ParseError(ti.filename(), token.line(), token.character(), - "Unexpected token"); - - } // switch - - if (! comment.empty()) { - ensureData(); - m_data->comment = comment; - } - - if (m_type != ARRAY && m_type != TABLE) { - // Array and table already consumed their last token - token = ti.read(); - } -} - - -void Any::ensureData() { - if (m_data == NULL) { - m_data = Data::create(m_type); - } -} - - -static bool isSeparator(char c) { - return c == ',' || c == ';'; -} - - -void Any::readUntilCommaOrClose(TextInput& ti, Token& token) { - while (! ((token.type() == Token::SYMBOL) && - (isClose(token.string()[0])) || - isSeparator(token.string()[0]))) { - switch (token.type()) { - case Token::NEWLINE: - case Token::COMMENT: - // Consume - token = ti.read(); - break; - - default: - throw ParseError(ti.filename(), token.line(), token.character(), - "Expected a comma or close paren"); - } - } -} - - -void Any::deserializeBody(TextInput& ti, Token& token) { - char closeSymbol = '}'; - m_type = TABLE; - - const char c = token.string()[0]; - - if (c != '{') { - m_type = ARRAY; - // Chose the appropriate close symbol - closeSymbol = (c == '(') ? ')' : ']'; - } - - // Allocate the underlying data structure - ensureData(); - m_data->source.set(ti, token); - - // Consume the open token - token = ti.read(); - - while (! ((token.type() == Token::SYMBOL) && (token.string()[0] == closeSymbol))) { - - // Read any leading comment. This must be done here (and not in the recursive deserialize - // call) in case the body contains only a comment. - std::string comment; - deserializeComment(ti, token, comment); - - if ((token.type() == Token::SYMBOL) && (token.string()[0] == closeSymbol)) { - // We're done; this catches the case where the array is empty - break; - } - - // Pointer the value being read - Any a = NULL; - std::string key; - - if (m_type == TABLE) { - // Read the key - if (token.type() != Token::SYMBOL && token.type() != Token::STRING) { - throw ParseError(ti.filename(), token.line(), token.character(), "Expected a name"); - } - - key = token.string(); - // Consume everything up to the = sign - token = ti.readSignificant(); - - if ((token.type() != Token::SYMBOL) || (token.string() != "=")) { - throw ParseError(ti.filename(), token.line(), token.character(), "Expected ="); - } else { - // Consume (don't consume comments--we want the value pointed to by a to get those). - token = ti.read(); - } - } - a.deserialize(ti, token); - - if (! comment.empty()) { - // Prepend the comment we read earlier - a.ensureData(); - a.m_data->comment = trimWhitespace(comment + "\n" + a.m_data->comment); - } - - if (m_type == TABLE) { - set(key, a); - } else { - append(a); - } - - // Read until the comma or close paren, discarding trailing comments and newlines - readUntilCommaOrClose(ti, token); - - // Consume the comma - if (isSeparator(token.string()[0])) { - token = ti.read(); - } - } - - // Consume the close paren (to match other deserialize methods) - token = ti.read(); -} - - -Any::operator int() const { - beforeRead(); - return iRound(number()); -} - - -Any::operator float() const { - beforeRead(); - return float(number()); -} - - -Any::operator double() const { - beforeRead(); - return number(); -} - - -Any::operator bool() const { - beforeRead(); - return boolean(); -} - - -Any::operator std::string() const { - beforeRead(); - return string(); -} - - -const Any::Source& Any::source() const { - static Source s; - if (m_data) { - return m_data->source; - } else { - return s; - } -} - - -void Any::verify(bool value, const std::string& message) const { - beforeRead(); - if (! value) { - ParseError p; - if (m_data) { - p.filename = m_data->source.filename; - p.line = m_data->source.line; - p.character = m_data->source.character; - } - - if (name().empty()) { - p.message = "Parse error"; - } else { - p.message = "Parse error while reading the contents of " + name(); - } - - if (! message.empty()) { - p.message = p.message + ": " + message; - } - - throw p; - } -} - - -void Any::verifyName(const std::string& n) const { - beforeRead(); - verify(beginsWith(toUpper(name()), toUpper(n)), "Name must begin with " + n); -} - - -void Any::verifyType(Type t) const { - beforeRead(); - if (type() != t) { - verify(false, "Must have type " + toString(t)); - } -} - - -void Any::verifyType(Type t0, Type t1) const { - beforeRead(); - if (type() != t0 && type() != t1) { - verify(false, "Must have type " + toString(t0) + " or " + toString(t1)); - } -} - - -void Any::verifySize(int low, int high) const { - beforeRead(); - verifyType(ARRAY, TABLE); - if (size() < low || size() > high) { - verify(false, format("Size must be between %d and %d", low, high)); - } -} - - -void Any::verifySize(int s) const { - beforeRead(); - verifyType(ARRAY, TABLE); - if (size() != s) { - verify(false, format("Size must be %d", s)); - } -} - - -std::string Any::toString(Type t) { - switch(t) { - case NONE: return "NONE"; - case BOOLEAN: return "BOOLEAN"; - case NUMBER: return "NUMBER"; - case STRING: return "STRING"; - case ARRAY: return "ARRAY"; - case TABLE: return "TABLE"; - default: - alwaysAssertM(false, "Illegal Any::Type"); - return ""; - } -} - -} // namespace G3D - diff --git a/externals/g3dlite/BinaryFormat.cpp b/externals/g3dlite/BinaryFormat.cpp deleted file mode 100644 index d3991378f45..00000000000 --- a/externals/g3dlite/BinaryFormat.cpp +++ /dev/null @@ -1,81 +0,0 @@ -/** - @file BinaryFormat.cpp - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2005-06-10 - @edited 2005-06-10 - */ - -#include "G3D/BinaryFormat.h" - -namespace G3D { - -int32 byteSize(BinaryFormat f) { - switch (f) { - case BOOL8_BINFMT: - case UINT8_BINFMT: - case INT8_BINFMT: - return 1; - - case UINT16_BINFMT: - case INT16_BINFMT: - return 2; - - case FLOAT16_BINFMT: - return 2; - - case UINT32_BINFMT: - case INT32_BINFMT: - case FLOAT32_BINFMT: - return 4; - - case FLOAT64_BINFMT: - case UINT64_BINFMT: - case INT64_BINFMT: - return 8; - - case INT128_BINFMT: - case UINT128_BINFMT: - return 16; - - case VECTOR2_BINFMT: - return 2 * 4; - - case VECTOR2INT16_BINFMT: - return 2 * 2; - - case VECTOR3_BINFMT: - return 3 * 4; - - case VECTOR3INT16_BINFMT: - return 3 * 2; - - case VECTOR4_BINFMT: - return 4 * 4; - - case VECTOR4INT16_BINFMT: - return 4 * 4; - - case COLOR3_BINFMT: - return 3 * 4; - - case COLOR3UINT8_BINFMT: - return 3 * 1; - - case COLOR3INT16_BINFMT: - return 3 * 2; - - case COLOR4_BINFMT: - return 4 * 4; - - case COLOR4UINT8_BINFMT: - return 4 * 1; - - case COLOR4INT16_BINFMT: - return 4 * 2; - - default: - return -1; - } -} -} diff --git a/externals/g3dlite/BinaryInput.cpp b/externals/g3dlite/BinaryInput.cpp deleted file mode 100644 index 65a9976fe04..00000000000 --- a/externals/g3dlite/BinaryInput.cpp +++ /dev/null @@ -1,568 +0,0 @@ -/** - @file BinaryInput.cpp - - @author Morgan McGuire, graphics3d.com - Copyright 2001-2007, Morgan McGuire. All rights reserved. - - @created 2001-08-09 - @edited 2005-02-24 - - -
-    {    
-    BinaryOutput b("c:/tmp/test.b", BinaryOutput::LITTLE_ENDIAN);
-
-    float f = 3.1415926;
-    int i = 1027221;
-    std::string s = "Hello World!";
-
-    b.writeFloat32(f);
-    b.writeInt32(i);
-    b.writeString(s);
-    b.commit();
-    
-
-    BinaryInput in("c:/tmp/test.b", BinaryInput::LITTLE_ENDIAN);
-
-    debugAssert(f == in.readFloat32());
-    int ii = in.readInt32();
-    debugAssert(i == ii);
-    debugAssert(s == in.readString());
-    }
-  
- */ - -#include "G3D/platform.h" -#include "G3D/BinaryInput.h" -#include "G3D/Array.h" -#include "G3D/fileutils.h" -#include "G3D/Log.h" -#include - -#include - -namespace G3D { - -void BinaryInput::readBool8(std::vector& out, int64 n) { - out.resize((int)n); - // std::vector optimizes bool in a way that prevents fast reading - for (int64 i = 0; i < n ; ++i) { - out[i] = readBool8(); - } -} - - -void BinaryInput::readBool8(Array& out, int64 n) { - out.resize(n); - readBool8(out.begin(), n); -} - - -#define IMPLEMENT_READER(ucase, lcase)\ -void BinaryInput::read##ucase(std::vector& out, int64 n) {\ - out.resize(n);\ - read##ucase(&out[0], n);\ -}\ -\ -\ -void BinaryInput::read##ucase(Array& out, int64 n) {\ - out.resize(n);\ - read##ucase(out.begin(), n);\ -} - - -IMPLEMENT_READER(UInt8, uint8) -IMPLEMENT_READER(Int8, int8) -IMPLEMENT_READER(UInt16, uint16) -IMPLEMENT_READER(Int16, int16) -IMPLEMENT_READER(UInt32, uint32) -IMPLEMENT_READER(Int32, int32) -IMPLEMENT_READER(UInt64, uint64) -IMPLEMENT_READER(Int64, int64) -IMPLEMENT_READER(Float32, float32) -IMPLEMENT_READER(Float64, float64) - -#undef IMPLEMENT_READER - -// Data structures that are one byte per element can be -// directly copied, regardles of endian-ness. -#define IMPLEMENT_READER(ucase, lcase)\ -void BinaryInput::read##ucase(lcase* out, int64 n) {\ - if (sizeof(lcase) == 1) {\ - readBytes(out, n);\ - } else {\ - for (int64 i = 0; i < n ; ++i) {\ - out[i] = read##ucase();\ - }\ - }\ -} - -IMPLEMENT_READER(Bool8, bool) -IMPLEMENT_READER(UInt8, uint8) -IMPLEMENT_READER(Int8, int8) - -#undef IMPLEMENT_READER - - -#define IMPLEMENT_READER(ucase, lcase)\ -void BinaryInput::read##ucase(lcase* out, int64 n) {\ - if (m_swapBytes) {\ - for (int64 i = 0; i < n; ++i) {\ - out[i] = read##ucase();\ - }\ - } else {\ - readBytes(out, sizeof(lcase) * n);\ - }\ -} - - -IMPLEMENT_READER(UInt16, uint16) -IMPLEMENT_READER(Int16, int16) -IMPLEMENT_READER(UInt32, uint32) -IMPLEMENT_READER(Int32, int32) -IMPLEMENT_READER(UInt64, uint64) -IMPLEMENT_READER(Int64, int64) -IMPLEMENT_READER(Float32, float32) -IMPLEMENT_READER(Float64, float64) - -#undef IMPLEMENT_READER - -void BinaryInput::loadIntoMemory(int64 startPosition, int64 minLength) { - // Load the next section of the file - debugAssertM(m_filename != "", "Read past end of file."); - - int64 absPos = m_alreadyRead + m_pos; - - if (m_bufferLength < minLength) { - // The current buffer isn't big enough to hold the chunk we want to read. - // This happens if there was little memory available during the initial constructor - // read but more memory has since been freed. - m_bufferLength = minLength; - debugAssert(m_freeBuffer); - m_buffer = (uint8*)System::realloc(m_buffer, m_bufferLength); - if (m_buffer == NULL) { - throw "Tried to read a larger memory chunk than could fit in memory. (2)"; - } - } - - m_alreadyRead = startPosition; - -# ifdef G3D_WIN32 - FILE* file = fopen(m_filename.c_str(), "rb"); - debugAssert(file); - int ret = fseek(file, (off_t)m_alreadyRead, SEEK_SET); - debugAssert(ret == 0); - size_t toRead = (size_t)G3D::min(m_bufferLength, m_length - m_alreadyRead); - ret = fread(m_buffer, 1, toRead, file); - debugAssert(ret == toRead); - fclose(file); - file = NULL; - -# else - FILE* file = fopen(m_filename.c_str(), "rb"); - debugAssert(file); - int ret = fseeko(file, (off_t)m_alreadyRead, SEEK_SET); - debugAssert(ret == 0); - size_t toRead = (size_t)G3D::min(m_bufferLength, m_length - m_alreadyRead); - ret = fread(m_buffer, 1, toRead, file); - debugAssert((size_t)ret == (size_t)toRead); - fclose(file); - file = NULL; -# endif - - m_pos = absPos - m_alreadyRead; - debugAssert(m_pos >= 0); -} - - - -const bool BinaryInput::NO_COPY = false; - -static bool needSwapBytes(G3DEndian fileEndian) { - return (fileEndian != System::machineEndian()); -} - - -/** Helper used by the constructors for decompression */ -static uint32 readUInt32(const uint8* data, bool swapBytes) { - if (swapBytes) { - uint8 out[4]; - out[0] = data[3]; - out[1] = data[2]; - out[2] = data[1]; - out[3] = data[0]; - return *((uint32*)out); - } else { - return *((uint32*)data); - } -} - - -void BinaryInput::setEndian(G3DEndian e) { - m_fileEndian = e; - m_swapBytes = needSwapBytes(m_fileEndian); -} - - -BinaryInput::BinaryInput( - const uint8* data, - int64 dataLen, - G3DEndian dataEndian, - bool compressed, - bool copyMemory) : - m_filename(""), - m_bitPos(0), - m_bitString(0), - m_beginEndBits(0), - m_alreadyRead(0), - m_bufferLength(0), - m_pos(0) { - - m_freeBuffer = copyMemory || compressed; - - setEndian(dataEndian); - - if (compressed) { - // Read the decompressed size from the first 4 bytes - m_length = G3D::readUInt32(data, m_swapBytes); - - debugAssert(m_freeBuffer); - m_buffer = (uint8*)System::alignedMalloc(m_length, 16); - - unsigned long L = m_length; - // Decompress with zlib - int64 result = uncompress(m_buffer, (unsigned long*)&L, data + 4, dataLen - 4); - m_length = L; - m_bufferLength = L; - debugAssert(result == Z_OK); (void)result; - - } else { - m_length = dataLen; - m_bufferLength = m_length; - if (! copyMemory) { - debugAssert(!m_freeBuffer); - m_buffer = const_cast(data); - } else { - debugAssert(m_freeBuffer); - m_buffer = (uint8*)System::alignedMalloc(m_length, 16); - System::memcpy(m_buffer, data, dataLen); - } - } -} - - -BinaryInput::BinaryInput( - const std::string& filename, - G3DEndian fileEndian, - bool compressed) : - m_filename(filename), - m_bitPos(0), - m_bitString(0), - m_beginEndBits(0), - m_alreadyRead(0), - m_length(0), - m_bufferLength(0), - m_buffer(NULL), - m_pos(0), - m_freeBuffer(true) { - - setEndian(fileEndian); - - // Update global file tracker - _internal::currentFilesUsed.insert(m_filename); - - - if (! fileExists(m_filename, false)) { - std::string zipfile; - std::string internalfile; - if (zipfileExists(m_filename, zipfile, internalfile)) { - // Load from zipfile - void* v; - size_t s; - zipRead(filename, v, s); - m_buffer = reinterpret_cast(v); - m_bufferLength = m_length = s; - if (compressed) { - decompress(); - } - m_freeBuffer = true; - } else { - Log::common()->printf("Warning: File not found: %s\n", m_filename.c_str()); - } - return; - } - - // Figure out how big the file is and verify that it exists. - m_length = fileLength(m_filename); - - // Read the file into memory - FILE* file = fopen(m_filename.c_str(), "rb"); - - if (! file || (m_length == -1)) { - throw format("File not found: \"%s\"", m_filename.c_str()); - return; - } - - if (! compressed && (m_length > INITIAL_BUFFER_LENGTH)) { - // Read only a subset of the file so we don't consume - // all available memory. - m_bufferLength = INITIAL_BUFFER_LENGTH; - } else { - // Either the length is fine or the file is compressed - // and requires us to read the whole thing for zlib. - m_bufferLength = m_length; - } - - debugAssert(m_freeBuffer); - m_buffer = (uint8*)System::alignedMalloc(m_bufferLength, 16); - if (m_buffer == NULL) { - if (compressed) { - throw "Not enough memory to load compressed file. (1)"; - } - - // Try to allocate a small array; not much memory is available. - // Give up if we can't allocate even 1k. - while ((m_buffer == NULL) && (m_bufferLength > 1024)) { - m_bufferLength /= 2; - m_buffer = (uint8*)System::alignedMalloc(m_bufferLength, 16); - } - } - debugAssert(m_buffer); - - fread(m_buffer, m_bufferLength, sizeof(int8), file); - fclose(file); - file = NULL; - - if (compressed) { - if (m_bufferLength != m_length) { - throw "Not enough memory to load compressed file. (2)"; - } - - decompress(); - } -} - -void BinaryInput::decompress() { - // Decompress - // Use the existing buffer as the source, allocate - // a new buffer to use as the destination. - - int64 tempLength = m_length; - m_length = G3D::readUInt32(m_buffer, m_swapBytes); - - // The file couldn't have better than 500:1 compression - alwaysAssertM(m_length < m_bufferLength * 500, "Compressed file header is corrupted"); - - uint8* tempBuffer = m_buffer; - m_buffer = (uint8*)System::alignedMalloc(m_length, 16); - - debugAssert(m_buffer); - debugAssert(isValidHeapPointer(tempBuffer)); - debugAssert(isValidHeapPointer(m_buffer)); - - unsigned long L = m_length; - int64 result = uncompress(m_buffer, &L, tempBuffer + 4, tempLength - 4); - m_length = L; - m_bufferLength = m_length; - - debugAssertM(result == Z_OK, "BinaryInput/zlib detected corruption in " + m_filename); - (void)result; - - System::alignedFree(tempBuffer); -} - - -void BinaryInput::readBytes(void* bytes, int64 n) { - prepareToRead(n); - debugAssert(isValidPointer(bytes)); - - memcpy(bytes, m_buffer + m_pos, n); - m_pos += n; -} - - -BinaryInput::~BinaryInput() { - - if (m_freeBuffer) { - System::alignedFree(m_buffer); - } - m_buffer = NULL; -} - - -uint64 BinaryInput::readUInt64() { - prepareToRead(8); - uint8 out[8]; - - if (m_swapBytes) { - out[0] = m_buffer[m_pos + 7]; - out[1] = m_buffer[m_pos + 6]; - out[2] = m_buffer[m_pos + 5]; - out[3] = m_buffer[m_pos + 4]; - out[4] = m_buffer[m_pos + 3]; - out[5] = m_buffer[m_pos + 2]; - out[6] = m_buffer[m_pos + 1]; - out[7] = m_buffer[m_pos + 0]; - } else { - *(uint64*)out = *(uint64*)(m_buffer + m_pos); - } - - m_pos += 8; - return *(uint64*)out; -} - - -std::string BinaryInput::readString(int64 n) { - prepareToRead(n); - debugAssertM((m_pos + n) <= m_length, "Read past end of file"); - - char *s = (char*)System::alignedMalloc(n + 1, 16); - assert(s != NULL); - - memcpy(s, m_buffer + m_pos, n); - // There may not be a null, so make sure - // we add one. - s[n] = '\0'; - - std::string out = s; - System::alignedFree(s); - s = NULL; - - m_pos += n; - - return out; - -} - - -std::string BinaryInput::readString() { - int64 n = 0; - - if ((m_pos + m_alreadyRead + n) < (m_length - 1)) { - prepareToRead(1); - } - - if ( ((m_pos + m_alreadyRead + n) < (m_length - 1)) && - (m_buffer[m_pos + n] != '\0')) { - - ++n; - while ( ((m_pos + m_alreadyRead + n) < (m_length - 1)) && - (m_buffer[m_pos + n] != '\0')) { - - prepareToRead(1); - ++n; - } - } - - // Consume NULL - ++n; - - return readString(n); -} - - -std::string BinaryInput::readStringEven() { - std::string x = readString(); - if (hasMore() && (G3D::isOdd(x.length() + 1))) { - skip(1); - } - return x; -} - - -std::string BinaryInput::readString32() { - int len = readUInt32(); - return readString(len); -} - - -Vector4 BinaryInput::readVector4() { - float x = readFloat32(); - float y = readFloat32(); - float z = readFloat32(); - float w = readFloat32(); - return Vector4(x, y, z, w); -} - - -Vector3 BinaryInput::readVector3() { - float x = readFloat32(); - float y = readFloat32(); - float z = readFloat32(); - return Vector3(x, y, z); -} - - -Vector2 BinaryInput::readVector2() { - float x = readFloat32(); - float y = readFloat32(); - return Vector2(x, y); -} - - -Color4 BinaryInput::readColor4() { - float r = readFloat32(); - float g = readFloat32(); - float b = readFloat32(); - float a = readFloat32(); - return Color4(r, g, b, a); -} - - -Color3 BinaryInput::readColor3() { - float r = readFloat32(); - float g = readFloat32(); - float b = readFloat32(); - return Color3(r, g, b); -} - - -void BinaryInput::beginBits() { - debugAssert(m_beginEndBits == 0); - m_beginEndBits = 1; - m_bitPos = 0; - - debugAssertM(hasMore(), "Can't call beginBits when at the end of a file"); - m_bitString = readUInt8(); -} - - -uint32 BinaryInput::readBits(int numBits) { - debugAssert(m_beginEndBits == 1); - - uint32 out = 0; - - const int total = numBits; - while (numBits > 0) { - if (m_bitPos > 7) { - // Consume a new byte for reading. We do this at the beginning - // of the loop so that we don't try to read past the end of the file. - m_bitPos = 0; - m_bitString = readUInt8(); - } - - // Slide the lowest bit of the bitString into - // the correct position. - out |= (m_bitString & 1) << (total - numBits); - - // Shift over to the next bit - m_bitString = m_bitString >> 1; - ++m_bitPos; - --numBits; - } - - return out; -} - - -void BinaryInput::endBits() { - debugAssert(m_beginEndBits == 1); - if (m_bitPos == 0) { - // Put back the last byte we read - --m_pos; - } - m_beginEndBits = 0; - m_bitPos = 0; -} - -} diff --git a/externals/g3dlite/BinaryOutput.cpp b/externals/g3dlite/BinaryOutput.cpp deleted file mode 100644 index 2de46c6d4bb..00000000000 --- a/externals/g3dlite/BinaryOutput.cpp +++ /dev/null @@ -1,522 +0,0 @@ -/** - @file BinaryOutput.cpp - - @author Morgan McGuire, graphics3d.com - Copyright 2002-2007, Morgan McGuire, All rights reserved. - - @created 2002-02-20 - @edited 2008-01-07 - */ - -#include "G3D/platform.h" -#include "G3D/BinaryOutput.h" -#include "G3D/fileutils.h" -#include "G3D/stringutils.h" -#include "G3D/Array.h" -#include - -#include - -// Largest memory buffer that the system will use for writing to -// disk. After this (or if the system runs out of memory) -// chunks of the file will be dumped to disk. -// -// Currently 400 MB -#define MAX_BINARYOUTPUT_BUFFER_SIZE 400000000 - -namespace G3D { - -void BinaryOutput::writeBool8(const std::vector& out, int n) { - for (int i = 0; i < n; ++i) { - writeBool8(out[i]); - } -} - - -void BinaryOutput::writeBool8(const Array& out, int n) { - writeBool8(out.getCArray(), n); -} - -#define IMPLEMENT_WRITER(ucase, lcase)\ -void BinaryOutput::write##ucase(const std::vector& out, int n) {\ - write##ucase(&out[0], n);\ -}\ -\ -\ -void BinaryOutput::write##ucase(const Array& out, int n) {\ - write##ucase(out.getCArray(), n);\ -} - - -IMPLEMENT_WRITER(UInt8, uint8) -IMPLEMENT_WRITER(Int8, int8) -IMPLEMENT_WRITER(UInt16, uint16) -IMPLEMENT_WRITER(Int16, int16) -IMPLEMENT_WRITER(UInt32, uint32) -IMPLEMENT_WRITER(Int32, int32) -IMPLEMENT_WRITER(UInt64, uint64) -IMPLEMENT_WRITER(Int64, int64) -IMPLEMENT_WRITER(Float32, float32) -IMPLEMENT_WRITER(Float64, float64) - -#undef IMPLEMENT_WRITER - -// Data structures that are one byte per element can be -// directly copied, regardles of endian-ness. -#define IMPLEMENT_WRITER(ucase, lcase)\ -void BinaryOutput::write##ucase(const lcase* out, int n) {\ - if (sizeof(lcase) == 1) {\ - writeBytes((void*)out, n);\ - } else {\ - for (int i = 0; i < n ; ++i) {\ - write##ucase(out[i]);\ - }\ - }\ -} - -IMPLEMENT_WRITER(Bool8, bool) -IMPLEMENT_WRITER(UInt8, uint8) -IMPLEMENT_WRITER(Int8, int8) - -#undef IMPLEMENT_WRITER - - -#define IMPLEMENT_WRITER(ucase, lcase)\ -void BinaryOutput::write##ucase(const lcase* out, int n) {\ - if (m_swapBytes) {\ - for (int i = 0; i < n; ++i) {\ - write##ucase(out[i]);\ - }\ - } else {\ - writeBytes((const void*)out, sizeof(lcase) * n);\ - }\ -} - - -IMPLEMENT_WRITER(UInt16, uint16) -IMPLEMENT_WRITER(Int16, int16) -IMPLEMENT_WRITER(UInt32, uint32) -IMPLEMENT_WRITER(Int32, int32) -IMPLEMENT_WRITER(UInt64, uint64) -IMPLEMENT_WRITER(Int64, int64) -IMPLEMENT_WRITER(Float32, float32) -IMPLEMENT_WRITER(Float64, float64) - -#undef IMPLEMENT_WRITER - - -void BinaryOutput::reallocBuffer(size_t bytes, size_t oldBufferLen) { - //debugPrintf("reallocBuffer(%d, %d)\n", bytes, oldBufferLen); - - size_t newBufferLen = (int)(m_bufferLen * 1.5) + 100; - uint8* newBuffer = NULL; - - if ((m_filename == "") || (newBufferLen < MAX_BINARYOUTPUT_BUFFER_SIZE)) { - // We're either writing to memory (in which case we *have* to try and allocate) - // or we've been asked to allocate a reasonable size buffer. - - //debugPrintf(" realloc(%d)\n", newBufferLen); - newBuffer = (uint8*)System::realloc(m_buffer, newBufferLen); - if (newBuffer != NULL) { - m_maxBufferLen = newBufferLen; - } - } - - if ((newBuffer == NULL) && (bytes > 0)) { - // Realloc failed; we're probably out of memory. Back out - // the entire call and try to dump some data to disk. - m_bufferLen = oldBufferLen; - reserveBytesWhenOutOfMemory(bytes); - } else { - m_buffer = newBuffer; - debugAssert(isValidHeapPointer(m_buffer)); - } -} - - -void BinaryOutput::reserveBytesWhenOutOfMemory(size_t bytes) { - if (m_filename == "") { - throw "Out of memory while writing to memory in BinaryOutput (no RAM left)."; - } else if ((int)bytes > (int)m_maxBufferLen) { - throw "Out of memory while writing to disk in BinaryOutput (could not create a large enough buffer)."; - } else { - - // Dump the contents to disk. In order to enable seeking backwards, - // we keep the last 10 MB in memory. - int writeBytes = m_bufferLen - 10 * 1024 * 1024; - - if (writeBytes < m_bufferLen / 3) { - // We're going to write less than 1/3 of the file; - // give up and just write the whole thing. - writeBytes = m_bufferLen; - } - debugAssert(writeBytes > 0); - - //debugPrintf("Writing %d bytes to disk\n", writeBytes); - - const char* mode = (m_alreadyWritten > 0) ? "ab" : "wb"; - FILE* file = fopen(m_filename.c_str(), mode); - debugAssert(file); - - size_t count = fwrite(m_buffer, 1, writeBytes, file); - debugAssert((int)count == writeBytes); (void)count; - - fclose(file); - file = NULL; - - // Record that we saved this data. - m_alreadyWritten += writeBytes; - m_bufferLen -= writeBytes; - m_pos -= writeBytes; - - debugAssert(m_bufferLen < m_maxBufferLen); - debugAssert(m_bufferLen >= 0); - debugAssert(m_pos >= 0); - debugAssert(m_pos <= m_bufferLen); - - // Shift the unwritten data back appropriately in the buffer. - debugAssert(isValidHeapPointer(m_buffer)); - System::memcpy(m_buffer, m_buffer + writeBytes, m_bufferLen); - debugAssert(isValidHeapPointer(m_buffer)); - - // *now* we allocate bytes (there should presumably be enough - // space in the buffer; if not, we'll come back through this - // code and dump the last 10MB to disk as well. Note that the - // bytes > maxBufferLen case above would already have triggered - // if this call couldn't succeed. - reserveBytes(bytes); - } -} - - -BinaryOutput::BinaryOutput() { - m_alreadyWritten = 0; - m_swapBytes = false; - m_pos = 0; - m_filename = ""; - m_buffer = NULL; - m_bufferLen = 0; - m_maxBufferLen = 0; - m_beginEndBits = 0; - m_bitString = 0; - m_bitPos = 0; - m_ok = true; - m_committed = false; -} - - -BinaryOutput::BinaryOutput( - const std::string& filename, - G3DEndian fileEndian) { - - m_pos = 0; - m_alreadyWritten = 0; - setEndian(fileEndian); - m_filename = filename; - m_buffer = NULL; - m_bufferLen = 0; - m_maxBufferLen = 0; - m_beginEndBits = 0; - m_bitString = 0; - m_bitPos = 0; - m_committed = false; - - m_ok = true; - /** Verify ability to write to disk */ - commit(false); - m_committed = false; -} - - -void BinaryOutput::reset() { - debugAssert(m_beginEndBits == 0); - alwaysAssertM(m_filename == "", - "Can only reset a BinaryOutput that writes to memory."); - - // Do not reallocate, just clear the size of the buffer. - m_pos = 0; - m_alreadyWritten = 0; - m_bufferLen = 0; - m_beginEndBits = 0; - m_bitString = 0; - m_bitPos = 0; - m_committed = false; -} - - -BinaryOutput::~BinaryOutput() { - debugAssert((m_buffer == NULL) || isValidHeapPointer(m_buffer)); - System::free(m_buffer); - m_buffer = NULL; - m_bufferLen = 0; - m_maxBufferLen = 0; -} - - -void BinaryOutput::setEndian(G3DEndian fileEndian) { - m_fileEndian = fileEndian; - m_swapBytes = (fileEndian != System::machineEndian()); -} - - -bool BinaryOutput::ok() const { - return m_ok; -} - - -void BinaryOutput::compress() { - if (m_alreadyWritten > 0) { - throw "Cannot compress huge files (part of this file has already been written to disk)."; - } - - // Old buffer size - int L = m_bufferLen; - uint8* convert = (uint8*)&L; - - // Zlib requires the output buffer to be this big - unsigned long newSize = iCeil(m_bufferLen * 1.01) + 12; - uint8* temp = (uint8*)System::malloc(newSize); - int result = compress2(temp, &newSize, m_buffer, m_bufferLen, 9); - - debugAssert(result == Z_OK); (void)result; - - // Write the header - if (m_swapBytes) { - m_buffer[0] = convert[3]; - m_buffer[1] = convert[2]; - m_buffer[2] = convert[1]; - m_buffer[3] = convert[0]; - } else { - m_buffer[0] = convert[0]; - m_buffer[1] = convert[1]; - m_buffer[2] = convert[2]; - m_buffer[3] = convert[3]; - } - - // Write the data - if ((int64)newSize + 4 > (int64)m_maxBufferLen) { - m_maxBufferLen = newSize + 4; - m_buffer = (uint8*)System::realloc(m_buffer, m_maxBufferLen); - } - m_bufferLen = newSize + 4; - System::memcpy(m_buffer + 4, temp, newSize); - m_pos = m_bufferLen; - - System::free(temp); -} - - -void BinaryOutput::commit(bool flush) { - debugAssertM(! m_committed, "Cannot commit twice"); - m_committed = true; - debugAssertM(m_beginEndBits == 0, "Missing endBits before commit"); - - // Make sure the directory exists. - std::string root, base, ext, path; - Array pathArray; - parseFilename(m_filename, root, pathArray, base, ext); - - path = root + stringJoin(pathArray, '/'); - if (! fileExists(path, false)) { - createDirectory(path); - } - - const char* mode = (m_alreadyWritten > 0) ? "ab" : "wb"; - - FILE* file = fopen(m_filename.c_str(), mode); - - m_ok = (file != NULL) && m_ok; - - if (m_ok) { - debugAssertM(file, std::string("Could not open '") + m_filename + "'"); - - if (m_buffer != NULL) { - m_alreadyWritten += m_bufferLen; - - int success = fwrite(m_buffer, m_bufferLen, 1, file); - (void)success; - debugAssertM(success == 1, std::string("Could not write to '") + m_filename + "'"); - } - if (flush) { - fflush(file); - } - fclose(file); - file = NULL; - } -} - - -void BinaryOutput::commit( - uint8* out) { - debugAssertM(! m_committed, "Cannot commit twice"); - m_committed = true; - - System::memcpy(out, m_buffer, m_bufferLen); -} - - -void BinaryOutput::writeUInt16(uint16 u) { - reserveBytes(2); - - uint8* convert = (uint8*)&u; - - if (m_swapBytes) { - m_buffer[m_pos] = convert[1]; - m_buffer[m_pos + 1] = convert[0]; - } else { - *(uint16*)(m_buffer + m_pos) = u; - } - - m_pos += 2; -} - - -void BinaryOutput::writeUInt32(uint32 u) { - reserveBytes(4); - - uint8* convert = (uint8*)&u; - - debugAssert(m_beginEndBits == 0); - - if (m_swapBytes) { - m_buffer[m_pos] = convert[3]; - m_buffer[m_pos + 1] = convert[2]; - m_buffer[m_pos + 2] = convert[1]; - m_buffer[m_pos + 3] = convert[0]; - } else { - *(uint32*)(m_buffer + m_pos) = u; - } - - m_pos += 4; -} - - -void BinaryOutput::writeUInt64(uint64 u) { - reserveBytes(8); - - uint8* convert = (uint8*)&u; - - if (m_swapBytes) { - m_buffer[m_pos] = convert[7]; - m_buffer[m_pos + 1] = convert[6]; - m_buffer[m_pos + 2] = convert[5]; - m_buffer[m_pos + 3] = convert[4]; - m_buffer[m_pos + 4] = convert[3]; - m_buffer[m_pos + 5] = convert[2]; - m_buffer[m_pos + 6] = convert[1]; - m_buffer[m_pos + 7] = convert[0]; - } else { - *(uint64*)(m_buffer + m_pos) = u; - } - - m_pos += 8; -} - - -void BinaryOutput::writeString(const char* s) { - // +1 is because strlen doesn't count the null - int len = strlen(s) + 1; - - debugAssert(m_beginEndBits == 0); - reserveBytes(len); - System::memcpy(m_buffer + m_pos, s, len); - m_pos += len; -} - - -void BinaryOutput::writeStringEven(const char* s) { - // +1 is because strlen doesn't count the null - int len = strlen(s) + 1; - - reserveBytes(len); - System::memcpy(m_buffer + m_pos, s, len); - m_pos += len; - - // Pad with another NULL - if ((len % 2) == 1) { - writeUInt8(0); - } -} - - -void BinaryOutput::writeString32(const char* s) { - writeUInt32(strlen(s) + 1); - writeString(s); -} - - -void BinaryOutput::writeVector4(const Vector4& v) { - writeFloat32(v.x); - writeFloat32(v.y); - writeFloat32(v.z); - writeFloat32(v.w); -} - - -void BinaryOutput::writeVector3(const Vector3& v) { - writeFloat32(v.x); - writeFloat32(v.y); - writeFloat32(v.z); -} - - -void BinaryOutput::writeVector2(const Vector2& v) { - writeFloat32(v.x); - writeFloat32(v.y); -} - - -void BinaryOutput::writeColor4(const Color4& v) { - writeFloat32(v.r); - writeFloat32(v.g); - writeFloat32(v.b); - writeFloat32(v.a); -} - - -void BinaryOutput::writeColor3(const Color3& v) { - writeFloat32(v.r); - writeFloat32(v.g); - writeFloat32(v.b); -} - - -void BinaryOutput::beginBits() { - debugAssertM(m_beginEndBits == 0, "Already in beginBits...endBits"); - m_bitString = 0x00; - m_bitPos = 0; - m_beginEndBits = 1; -} - - -void BinaryOutput::writeBits(uint32 value, int numBits) { - - while (numBits > 0) { - // Extract the current bit of value and - // insert it into the current byte - m_bitString |= (value & 1) << m_bitPos; - ++m_bitPos; - value = value >> 1; - --numBits; - - if (m_bitPos > 7) { - // We've reached the end of this byte - writeUInt8(m_bitString); - m_bitString = 0x00; - m_bitPos = 0; - } - } -} - - -void BinaryOutput::endBits() { - debugAssertM(m_beginEndBits == 1, "Not in beginBits...endBits"); - if (m_bitPos > 0) { - writeUInt8(m_bitString); - } - m_bitString = 0; - m_bitPos = 0; - m_beginEndBits = 0; -} - -} diff --git a/externals/g3dlite/Box.cpp b/externals/g3dlite/Box.cpp deleted file mode 100644 index f7c112ae3a5..00000000000 --- a/externals/g3dlite/Box.cpp +++ /dev/null @@ -1,393 +0,0 @@ -/** - @file Box.cpp - Box class - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2001-06-02 - @edited 2006-02-05 -*/ - -#include "G3D/Box.h" -#include "G3D/debug.h" -#include "G3D/Plane.h" -#include "G3D/AABox.h" -#include "G3D/CoordinateFrame.h" - -namespace G3D { - -/** - Sets a field on four vertices. Used by the constructor. - */ -#define setMany(i0, i1, i2, i3, field, extreme) \ - _corner[i0].field = _corner[i1].field = \ - _corner[i2].field = _corner[i3].field = \ - (extreme).field - -Box::Box() { -} - - -Box::Box(const AABox& b) { - init(b.low(), b.high()); -} - -Box::Box(class BinaryInput& b) { - deserialize(b); -} - - -void Box::serialize(class BinaryOutput& b) const { - int i; - for (i = 0; i < 8; ++i) { - _corner[i].serialize(b); - } - - // Other state can be reconstructed -} - - -void Box::deserialize(class BinaryInput& b) { - int i; - - _center = Vector3::zero(); - for (i = 0; i < 8; ++i) { - _corner[i].deserialize(b); - _center += _corner[i]; - } - - _center = _center / 8; - - // Reconstruct other state from the corners - _axis[0] = _corner[5] - _corner[4]; - _axis[1] = _corner[7] - _corner[4]; - _axis[2] = _corner[0] - _corner[4]; - - for (i = 0; i < 3; ++i) { - _extent[i] = _axis[i].magnitude(); - _axis[i] /= _extent[i]; - } - - _volume = _extent.x * _extent.y * _extent.z; - - _area = 2 * - (_extent.x * _extent.y + - _extent.y * _extent.z + - _extent.z * _extent.x); -} - - -Box::Box( - const Vector3& min, - const Vector3& max) { - - init(min.min(max), min.max(max)); - -} - -void Box::init( - const Vector3& min, - const Vector3& max) { - - debugAssert( - (min.x <= max.x) && - (min.y <= max.y) && - (min.z <= max.z)); - - setMany(0, 1, 2, 3, z, max); - setMany(4, 5, 6, 7, z, min); - - setMany(1, 2, 5, 6, x, max); - setMany(0, 3, 4, 7, x, min); - - setMany(3, 2, 6, 7, y, max); - setMany(0, 1, 5, 4, y, min); - - _extent = max - min; - - _axis[0] = Vector3::unitX(); - _axis[1] = Vector3::unitY(); - _axis[2] = Vector3::unitZ(); - - if (_extent.isFinite()) { - _volume = _extent.x * _extent.y * _extent.z; - } else { - _volume = G3D::finf(); - } - - debugAssert(! isNaN(_extent.x)); - - _area = 2 * - (_extent.x * _extent.y + - _extent.y * _extent.z + - _extent.z * _extent.x); - - _center = (max + min) * 0.5f; - - // If the extent is infinite along an axis, make the center zero to avoid NaNs - for (int i = 0; i < 3; ++i) { - if (! G3D::isFinite(_extent[i])) { - _center[i] = 0.0f; - } - } -} - - -float Box::volume() const { - return _volume; -} - - -float Box::area() const { - return _area; -} - - -void Box::getLocalFrame(CoordinateFrame& frame) const { - - frame.rotation = Matrix3( - _axis[0][0], _axis[1][0], _axis[2][0], - _axis[0][1], _axis[1][1], _axis[2][1], - _axis[0][2], _axis[1][2], _axis[2][2]); - - frame.translation = _center; -} - - -CoordinateFrame Box::localFrame() const { - CoordinateFrame out; - getLocalFrame(out); - return out; -} - - -void Box::getFaceCorners(int f, Vector3& v0, Vector3& v1, Vector3& v2, Vector3& v3) const { - switch (f) { - case 0: - v0 = _corner[0]; v1 = _corner[1]; v2 = _corner[2]; v3 = _corner[3]; - break; - - case 1: - v0 = _corner[1]; v1 = _corner[5]; v2 = _corner[6]; v3 = _corner[2]; - break; - - case 2: - v0 = _corner[7]; v1 = _corner[6]; v2 = _corner[5]; v3 = _corner[4]; - break; - - case 3: - v0 = _corner[2]; v1 = _corner[6]; v2 = _corner[7]; v3 = _corner[3]; - break; - - case 4: - v0 = _corner[3]; v1 = _corner[7]; v2 = _corner[4]; v3 = _corner[0]; - break; - - case 5: - v0 = _corner[1]; v1 = _corner[0]; v2 = _corner[4]; v3 = _corner[5]; - break; - - default: - debugAssert((f >= 0) && (f < 6)); - } -} - - - -int Box::dummy = 0; - -bool Box::culledBy( - const Array& plane, - int& cullingPlane, - const uint32 _inMask, - uint32& childMask) const { - - uint32 inMask = _inMask; - assert(plane.size() < 31); - - childMask = 0; - - // See if there is one plane for which all of the - // vertices are in the negative half space. - for (int p = 0; p < plane.size(); ++p) { - - // Only test planes that are not masked - if ((inMask & 1) != 0) { - - Vector3 corner; - - int numContained = 0; - int v = 0; - - // We can early-out only if we have found one point on each - // side of the plane (i.e. if we are straddling). That - // occurs when (numContained < v) && (numContained > 0) - for (v = 0; (v < 8) && ((numContained == v) || (numContained == 0)); ++v) { - if (plane[p].halfSpaceContains(_corner[v])) { - ++numContained; - } - } - - if (numContained == 0) { - // Plane p culled the box - cullingPlane = p; - - // The caller should not recurse into the children, - // since the parent is culled. If they do recurse, - // make them only test against this one plane, which - // will immediately cull the volume. - childMask = 1 << p; - return true; - - } else if (numContained < v) { - // The bounding volume straddled the plane; we have - // to keep testing against this plane - childMask |= (1 << p); - } - } - - // Move on to the next bit. - inMask = inMask >> 1; - } - - // None of the planes could cull this box - cullingPlane = -1; - return false; -} - - -bool Box::culledBy( - const Array& plane, - int& cullingPlane, - const uint32 _inMask) const { - - uint32 inMask = _inMask; - assert(plane.size() < 31); - - // See if there is one plane for which all of the - // vertices are in the negative half space. - for (int p = 0; p < plane.size(); ++p) { - - // Only test planes that are not masked - if ((inMask & 1) != 0) { - - bool culled = true; - - int v; - - // Assume this plane culls all points. See if there is a point - // not culled by the plane... early out when at least one point - // is in the positive half space. - for (v = 0; (v < 8) && culled; ++v) { - culled = ! plane[p].halfSpaceContains(corner(v)); - } - - if (culled) { - // Plane p culled the box - cullingPlane = p; - - return true; - } - } - - // Move on to the next bit. - inMask = inMask >> 1; - } - - // None of the planes could cull this box - cullingPlane = -1; - return false; -} - - -bool Box::contains( - const Vector3& point) const { - - // Form axes from three edges, transform the point into that - // space, and perform 3 interval tests - - Vector3 u = _corner[4] - _corner[0]; - Vector3 v = _corner[3] - _corner[0]; - Vector3 w = _corner[1] - _corner[0]; - - Matrix3 M = Matrix3(u.x, v.x, w.x, - u.y, v.y, w.y, - u.z, v.z, w.z); - - // M^-1 * (point - _corner[0]) = point in unit cube's object space - // compute the inverse of M - Vector3 osPoint = M.inverse() * (point - _corner[0]); - - return - (osPoint.x >= 0) && - (osPoint.y >= 0) && - (osPoint.z >= 0) && - (osPoint.x <= 1) && - (osPoint.y <= 1) && - (osPoint.z <= 1); -} - -#undef setMany - - -void Box::getRandomSurfacePoint(Vector3& P, Vector3& N) const { - float aXY = _extent.x * _extent.y; - float aYZ = _extent.y * _extent.z; - float aZX = _extent.z * _extent.x; - - float r = (float)uniformRandom(0, aXY + aYZ + aZX); - - // Choose evenly between positive and negative face planes - float d = (uniformRandom(0, 1) < 0.5f) ? -1.0f : 1.0f; - - // The probability of choosing a given face is proportional to - // its area. - if (r < aXY) { - P = _axis[0] * (float)uniformRandom(-0.5, 0.5) * _extent.x + - _axis[1] * (float)uniformRandom(-0.5, 0.5) * _extent.y + - _center + _axis[2] * d * _extent.z * 0.5f; - N = _axis[2] * d; - } else if (r < aYZ) { - P = _axis[1] * (float)uniformRandom(-0.5, 0.5) * _extent.y + - _axis[2] * (float)uniformRandom(-0.5, 0.5) * _extent.z + - _center + _axis[0] * d * _extent.x * 0.5f; - N = _axis[0] * d; - } else { - P = _axis[2] * (float)uniformRandom(-0.5, 0.5) * _extent.z + - _axis[0] *(float) uniformRandom(-0.5, 0.5) * _extent.x + - _center + _axis[1] * d * _extent.y * 0.5f; - N = _axis[1] * d; - } -} - - -Vector3 Box::randomInteriorPoint() const { - Vector3 sum = _center; - - for (int a = 0; a < 3; ++a) { - sum += _axis[a] * (float)uniformRandom(-0.5, 0.5) * _extent[a]; - } - - return sum; -} - -Box Box::inf() { - return Box(-Vector3::inf(), Vector3::inf()); -} - -void Box::getBounds(class AABox& aabb) const { - - Vector3 lo = _corner[0]; - Vector3 hi = lo; - - for (int v = 1; v < 8; ++v) { - const Vector3& C = _corner[v]; - lo = lo.min(C); - hi = hi.max(C); - } - - aabb = AABox(lo, hi); -} - - -} // namespace diff --git a/externals/g3dlite/CMakeLists.txt b/externals/g3dlite/CMakeLists.txt deleted file mode 100644 index da5c89ec143..00000000000 --- a/externals/g3dlite/CMakeLists.txt +++ /dev/null @@ -1,37 +0,0 @@ -# Copyright (C) 2008-2010 Trinity -# -# This file is free software; as a special exception the author gives -# unlimited permission to copy and/or distribute it, with or without -# modifications, as long as this notice is preserved. -# -# This program is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the -# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -file(GLOB sources *.cpp) - -set(g3dlib_STAT_SRCS - ${sources} -) -if(WIN32) - include_directories( - ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_SOURCE_DIR}/externals/zlib - ) -else() - include_directories( - ${CMAKE_CURRENT_SOURCE_DIR} - ) -endif() - -add_library(g3dlib STATIC ${g3dlib_STAT_SRCS}) - -if(WIN32) - target_link_libraries(g3dlib - zlib - ) -else() - target_link_libraries(g3dlib - ${ZLIB_LIBRARIES} - ) -endif() diff --git a/externals/g3dlite/Capsule.cpp b/externals/g3dlite/Capsule.cpp deleted file mode 100644 index 2ad3891c960..00000000000 --- a/externals/g3dlite/Capsule.cpp +++ /dev/null @@ -1,179 +0,0 @@ -/** - @file Capsule.cpp - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2003-02-07 - @edited 2005-08-18 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ - -#include "G3D/Capsule.h" -#include "G3D/BinaryInput.h" -#include "G3D/BinaryOutput.h" -#include "G3D/LineSegment.h" -#include "G3D/Sphere.h" -#include "G3D/CoordinateFrame.h" -#include "G3D/Line.h" -#include "G3D/AABox.h" - -namespace G3D { - -Capsule::Capsule(class BinaryInput& b) { - deserialize(b); -} - - -Capsule::Capsule() { -} - - -Capsule::Capsule(const Vector3& _p1, const Vector3& _p2, float _r) - : p1(_p1), p2(_p2), _radius(_r) { -} - - -void Capsule::serialize(class BinaryOutput& b) const { - p1.serialize(b); - p2.serialize(b); - b.writeFloat64(_radius); -} - - -void Capsule::deserialize(class BinaryInput& b) { - p1.deserialize(b); - p2.deserialize(b); - _radius = b.readFloat64(); -} - - -Line Capsule::axis() const { - return Line::fromTwoPoints(p1, p2); -} - - -float Capsule::volume() const { - return - // Sphere volume - pow(_radius, 3) * pi() * 4 / 3 + - - // Cylinder volume - pow(_radius, 2) * (p1 - p2).magnitude(); -} - - -float Capsule::area() const { - - return - // Sphere area - pow(_radius, 2) * 4 * pi() + - - // Cylinder area - twoPi() * _radius * (p1 - p2).magnitude(); -} - - -void Capsule::getBounds(AABox& out) const { - Vector3 min = p1.min(p2) - (Vector3(1, 1, 1) * _radius); - Vector3 max = p1.max(p2) + (Vector3(1, 1, 1) * _radius); - - out = AABox(min, max); -} - - -bool Capsule::contains(const Vector3& p) const { - return LineSegment::fromTwoPoints(p1, p2).distanceSquared(p) <= square(radius()); -} - - -void Capsule::getRandomSurfacePoint(Vector3& p, Vector3& N) const { - float h = height(); - float r = radius(); - - // Create a random point on a standard capsule and then rotate to the global frame. - - // Relative areas - float capRelArea = sqrt(r) / 2.0f; - float sideRelArea = r * h; - - float r1 = uniformRandom(0, capRelArea * 2 + sideRelArea); - - if (r1 < capRelArea * 2) { - - // Select a point uniformly at random on a sphere - N = Sphere(Vector3::zero(), 1).randomSurfacePoint(); - p = N * r; - p.y += sign(p.y) * h / 2.0f; - } else { - // Side - float a = uniformRandom(0, (float)twoPi()); - N.x = cos(a); - N.y = 0; - N.z = sin(a); - p.x = N.x * r; - p.z = N.y * r; - p.y = uniformRandom(-h / 2.0f, h / 2.0f); - } - - // Transform to world space - CoordinateFrame cframe; - getReferenceFrame(cframe); - - p = cframe.pointToWorldSpace(p); - N = cframe.normalToWorldSpace(N); -} - - -void Capsule::getReferenceFrame(CoordinateFrame& cframe) const { - cframe.translation = center(); - - Vector3 Y = (p1 - p2).direction(); - Vector3 X = (abs(Y.dot(Vector3::unitX())) > 0.9) ? Vector3::unitY() : Vector3::unitX(); - Vector3 Z = X.cross(Y).direction(); - X = Y.cross(Z); - cframe.rotation.setColumn(0, X); - cframe.rotation.setColumn(1, Y); - cframe.rotation.setColumn(2, Z); -} - - -Vector3 Capsule::randomInteriorPoint() const { - float h = height(); - float r = radius(); - - // Create a random point in a standard capsule and then rotate to the global frame. - - Vector3 p; - - float hemiVolume = pi() * (r*r*r) * 4 / 6.0; - float cylVolume = pi() * square(r) * h; - - float r1 = uniformRandom(0, 2.0 * hemiVolume + cylVolume); - - if (r1 < 2.0 * hemiVolume) { - - p = Sphere(Vector3::zero(), r).randomInteriorPoint(); - - p.y += sign(p.y) * h / 2.0f; - - } else { - - // Select a point uniformly at random on a disk - float a = uniformRandom(0, (float)twoPi()); - float r2 = sqrt(uniformRandom(0, 1)) * r; - - p = Vector3(cos(a) * r2, - uniformRandom(-h / 2.0f, h / 2.0f), - sin(a) * r2); - } - - // Transform to world space - CoordinateFrame cframe; - getReferenceFrame(cframe); - - return cframe.pointToWorldSpace(p); -} - -} // namespace diff --git a/externals/g3dlite/CollisionDetection.cpp b/externals/g3dlite/CollisionDetection.cpp deleted file mode 100644 index 77eef0a5500..00000000000 --- a/externals/g3dlite/CollisionDetection.cpp +++ /dev/null @@ -1,2455 +0,0 @@ -/** - @file CollisionDetection.cpp - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @cite Bounce direction based on Paul Nettle's ftp://ftp.3dmaileffects.com/pub/FluidStudios/CollisionDetection/Fluid_Studios_Generic_Collision_Detection_for_Games_Using_Ellipsoids.pdf and comments by Max McGuire. Ray-sphere code by Eric Haines. - - @created 2001-11-24 - @edited 2008-12-29 - */ - -#include "G3D/CoordinateFrame.h" -#include "G3D/platform.h" -#include "G3D/CollisionDetection.h" -#include "G3D/debugAssert.h" -#include "G3D/vectorMath.h" -#include "G3D/Capsule.h" -#include "G3D/Plane.h" -#include "G3D/Line.h" -#include "G3D/LineSegment.h" -#include "G3D/Sphere.h" -#include "G3D/Box.h" -#include "G3D/Triangle.h" -#include "G3D/Vector3.h" -#include "G3D/AABox.h" - -#ifdef _MSC_VER -// Turn on fast floating-point optimizations -#pragma float_control( push ) -#pragma fp_contract( on ) -#pragma fenv_access( off ) -#pragma float_control( except, off ) -#pragma float_control( precise, off ) -#endif - - -namespace G3D { - -bool CollisionDetection::ignoreBool; -Vector3 CollisionDetection::ignore; -Array CollisionDetection::ignoreArray; - - - -Vector3 CollisionDetection::separatingAxisForSolidBoxSolidBox( - const int separatingAxisIndex, - const Box & box1, - const Box & box2) { - debugAssert(separatingAxisIndex >= 0); - debugAssert(separatingAxisIndex < 15); - Vector3 axis; - if (separatingAxisIndex < 3) { - axis = box1.axis(separatingAxisIndex); - } else if (separatingAxisIndex < 6) { - axis = box2.axis(separatingAxisIndex - 3); - } else { - int box1Index = (separatingAxisIndex - 6) / 3; - int box2Index = (separatingAxisIndex - 6) % 3; - axis = cross(box1.axis(box1Index), box2.axis(box2Index)); - } - return axis; -} - -#ifdef _MSC_VER -# pragma warning (push) -# pragma warning (disable : 4244) -#endif - -float CollisionDetection::projectedDistanceForSolidBoxSolidBox( - const int separatingAxisIndex, - const Vector3 & a, - const Vector3 & b, - const Vector3 & D, - const double* c, - const double* ca, - const double* ad, - const double* bd) -{ - (void)D; - - float R0 = 0.0f; - float R1 = 0.0f; - float R = 0.0f; - switch (separatingAxisIndex) { - case 0: - // A0 - R0 = a[0]; - R1 = b[0] * ca[0] + b[1] * ca[1] + b[2] * ca[2]; - R = fabs(ad[0]); - break; - case 1: - // A1 - R0 = a[1]; - R1 = b[0] * ca[3] + b[1] * ca[4] + b[2] * ca[5]; - R = fabs(ad[1]); - break; - case 2: - // A2 - R0 = a[2]; - R1 = b[0] * ca[6] + b[1] * ca[7] + b[2] * ca[8]; - R = fabs(ad[2]); - break; - case 3: - // B0 - R0 = a[0] * ca[0] + a[1] * ca[3] + a[2] * ca[6]; - R1 = b[0]; - R = fabs(bd[0]); - break; - case 4: - // B1 - R0 = a[0] * ca[1] + a[1] * ca[4] + a[2] * ca[7]; - R1 = b[1]; - R = fabs(bd[1]); - break; - case 5: - // B2 - R0 = a[0] * ca[2] + a[1] * ca[5] + a[2] * ca[8]; - R1 = b[2]; - R = fabs(bd[2]); - break; - case 6: - // A0 x B0 - R0 = a[1] * ca[6] + a[2] * ca[3]; - R1 = b[1] * ca[2] + b[2] * ca[1]; - R = fabs(c[3] * ad[2] - c[6] * ad[1]); - break; - case 7: - // A0 x B1 - R0 = a[1] * ca[7] + a[2] * ca[4]; - R1 = b[0] * ca[2] + b[2] * ca[0]; - R = fabs(c[4] * ad[2] - c[7] * ad[1]); - break; - case 8: - // A0 x B2 - R0 = a[1] * ca[8] + a[2] * ca[5]; - R1 = b[0] * ca[1] + b[1] * ca[0]; - R = fabs(c[5] * ad[2] - c[8] * ad[1]); - break; - case 9: - // A1 x B0 - R0 = a[0] * ca[6] + a[2] * ca[0]; - R1 = b[1] * ca[5] + b[2] * ca[4]; - R = fabs(c[6] * ad[0] - c[0] * ad[2]); - break; - case 10: - // A1 x B1 - R0 = a[0] * ca[7] + a[2] * ca[1]; - R1 = b[0] * ca[5] + b[2] * ca[3]; - R = fabs(c[7] * ad[0] - c[1] * ad[2]); - break; - case 11: - // A1 x B2 - R0 = a[0] * ca[8] + a[2] * ca[2]; - R1 = b[0] * ca[4] + b[1] * ca[3]; - R = fabs(c[8] * ad[0] - c[2] * ad[2]); - break; - case 12: - // A2 x B0 - R0 = a[0] * ca[3] + a[1] * ca[0]; - R1 = b[1] * ca[8] + b[2] * ca[7]; - R = fabs(c[0] * ad[1] - c[3] * ad[0]); - break; - case 13: - // A2 x B1 - R0 = a[0] * ca[4] + a[1] * ca[1]; - R1 = b[0] * ca[8] + b[2] * ca[6]; - R = fabs(c[1] * ad[1] - c[4] * ad[0]); - break; - case 14: - // A2 x B2 - R0 = a[0] * ca[5] + a[1] * ca[2]; - R1 = b[0] * ca[7] + b[1] * ca[6]; - R = fabs(c[2] * ad[1] - c[5] * ad[0]); - break; - default: - debugAssertM(false, "fell through switch statement"); - } - - return (R - (R0 + R1)); -} - - -bool CollisionDetection::parallelAxisForSolidBoxSolidBox( - const double* ca, - const double epsilon, - int & axis1, - int & axis2) { - const double parallelDot = 1.0 - epsilon; - for (int i = 0; i < 9; i++) { - if (ca[i] >= parallelDot) { - axis1 = i / 3; - axis2 = i % 3; - return true; - } - } - return false; -} - - - - -void CollisionDetection::fillSolidBoxSolidBoxInfo( - const Box & box1, - const Box & box2, - Vector3 & a, - Vector3 & b, - Vector3 & D, - double* c, - double* ca, - double* ad, - double* bd) { - // length between center and each side of box1 and box2 - a = box1.extent() * 0.5; - b = box2.extent() * 0.5; - - // difference between centers of box1 and box2 - D = box2.center() - box1.center(); - - // store the value of all possible dot products between the - // axes of box1 and box2, c_{row, col} in the Eberly paper - // corresponds to c[row * 3 + col] for this 9 element array. - // - // c[] holds signed values, ca[] hold absolute values - for (int i = 0; i < 9; i++) { - c[i] = dot(box1.axis(i / 3), box2.axis(i % 3)); - ca[i] = fabs(c[i]); - } - - // store all possible dot products between the axes of box1 and D, - // as well as the axes of box2 and D - for (int i = 0; i < 3; i++) { - ad[i] = dot(box1.axis(i), D); - bd[i] = dot(box2.axis(i), D); - } -} - - - -bool CollisionDetection::conservativeBoxBoxTest( - const Vector3 & a, const Vector3 & b, const Vector3 & D) { - // do a quick bounding sphere test because it is relatively - // cheap, (three dot products, two sqrts, and a few others) - double boxRadius1 = a.magnitude(); - double boxRadius2 = b.magnitude(); - return (D.squaredMagnitude() < square(boxRadius1 + boxRadius2)); -} - - - - -bool CollisionDetection::fixedSolidBoxIntersectsFixedSolidBox( - const Box& box1, - const Box& box2, - const int lastSeparatingAxis) { - // for explanations of the variable please refer to the - // paper and fillSolidBoxSolidBoxInfo() - Vector3 a; - Vector3 b; - Vector3 D; - double c[9]; - double ca[9]; - double ad[3]; - double bd[3]; - - fillSolidBoxSolidBoxInfo(box1, box2, a, b, D, c, ca, ad, bd); - - int dummy1, dummy2; - bool parallelAxes = parallelAxisForSolidBoxSolidBox(ca, 0.00001, - dummy1, dummy2); - - // check the separating axis from the last time step - if (lastSeparatingAxis != -1 && - (lastSeparatingAxis < 6 || !parallelAxes)) { - double projectedDistance = projectedDistanceForSolidBoxSolidBox( - lastSeparatingAxis, a, b, D, c, ca, ad, bd); - - // the separating axis from the last time step is still - // valid, the boxes do not intersect - if (projectedDistance > 0.0) { - return false; - } - } - - // test if the boxes can be separated by a plane normal to - // any of the three axes of box1, any of the three axes of box2, - // or any of the 9 possible cross products of axes from box1 - // and box2 - for (int i = 0; i < 15; i++) { - // do not need to check edge-edge cases if any two of - // the axes are parallel - if (parallelAxes && i == 6) { - return true; - } - - double projectedDistance = - projectedDistanceForSolidBoxSolidBox(i, a, b, D, c, ca, ad, bd); - - // found a separating axis, the boxes do not intersect - if (projectedDistance > 0.0) { - return false; - } - } - - return true; -} - - - -void CollisionDetection::closestPointsBetweenLineAndLine( - const Line & line1, - const Line & line2, - Vector3 & closest1, - Vector3 & closest2) { - // TODO make accessors for Line that don't make a copy of data - Vector3 P0 = line1.point(); - Vector3 u = line1.direction(); - Vector3 Q0 = line2.point(); - Vector3 v = line2.direction(); - Vector3 w0 = P0 - Q0; - - // a = 1.0, c = 1.0 - double b = dot(u, v); - double d = dot(u, w0); - double e = dot(v, w0); - double D = 1.0 - b * b; - double sc, tc; - - static const double epsilon = 0.00001; - - if (D < epsilon) { - // lines are parallel, choose P0 as one point, find the point - // on line2 that is closest to P0 - sc = 0.0; - tc = (b > 1.0) ? (d / b) : (e / 1.0); - } else { - // lines are not parallel - sc = (b * e - 1.0 * d) / D; - tc = (1.0 * e - b * d) / D; - } - - closest1 = P0 + (sc * u); - closest2 = Q0 + (tc * v); -} - - - -float CollisionDetection::penetrationDepthForFixedBoxFixedBox( - const Box& box1, - const Box& box2, - Array& contactPoints, - Array& contactNormals, - const int lastSeparatingAxis) { - - contactPoints.resize(0, DONT_SHRINK_UNDERLYING_ARRAY); - contactNormals.resize(0, DONT_SHRINK_UNDERLYING_ARRAY); - - Vector3 a; - Vector3 b; - Vector3 D; - double c[9]; - double ca[9]; - double ad[3]; - double bd[3]; - - debugAssert(lastSeparatingAxis >= -1); - debugAssert(lastSeparatingAxis < 15); - - fillSolidBoxSolidBoxInfo(box1, box2, a, b, D, c, ca, ad, bd); - - int axis1, axis2; - bool parallelAxes = parallelAxisForSolidBoxSolidBox(ca, 0.00001, - axis1, axis2); - - - // check the separating axis from the last time step - if (lastSeparatingAxis != -1 && - (lastSeparatingAxis < 6 || !parallelAxes)) { - float projectedDistance = projectedDistanceForSolidBoxSolidBox( - lastSeparatingAxis, a, b, D, c, ca, ad, bd); - - // the separating axis from the last time step is still - // valid, the boxes do not intersect - if (projectedDistance > 0.0) { - return -projectedDistance; - } - } - - // test if the boxes can be separated by a plane normal to - // any of the three axes of box1, any of the three axes of box2, - // (test 9 possible cross products later) - float penetration = -finf(); - int penetrationAxisIndex = -1; - - for (int i = 0; i < 6; i++) { - float projectedDistance = - projectedDistanceForSolidBoxSolidBox(i, a, b, D, c, ca, ad, bd); - - // found a separating axis, the boxes do not intersect - if (projectedDistance > 0.0) { - return -projectedDistance; - } - - // keep track of the axis that is least violated - if (projectedDistance > penetration) { - penetration = projectedDistance; - penetrationAxisIndex = i; - } - } - - - // for each edge-edge case we have to adjust the magnitude of - // penetration since we did not include the dot(L, L) denominator - // that can be smaller than 1.0 for the edge-edge cases. - if (!parallelAxes) { - double edgeDistances[9]; - - // run through edge-edge cases to see if we can find a separating axis - for (int i = 6; i < 15; i++) { - float projectedDistance = - projectedDistanceForSolidBoxSolidBox(i, a, b, D, c, ca, ad, bd); - - // found a separating axis, the boxes do not intersect, - // correct magnitude and return projected distance - if (projectedDistance > 0.0) { - Vector3 L = separatingAxisForSolidBoxSolidBox(i, box1, box2); - projectedDistance /= dot(L, L); - return -projectedDistance; - } - - edgeDistances[i - 6] = projectedDistance; - } - - // no separating axis found, the boxes do intersect, - // correct the magnitudes of the projectedDistance values - for (int i = 6; i < 15; i++) { - // find the negative penetration value with the smallest magnitude, - // the adjustment done for the edge-edge cases only increases - // magnitude by dividing by a number smaller than 1 and greater than 0 - float projectedDistance = (float)edgeDistances[i - 6]; - if (projectedDistance > penetration) { - Vector3 L = separatingAxisForSolidBoxSolidBox(i, box1, box2); - projectedDistance /= dot(L, L); - if (projectedDistance > penetration) { - penetration = projectedDistance; - penetrationAxisIndex = i; - } - } - } - } - - // get final separating axis vector - Vector3 L = separatingAxisForSolidBoxSolidBox(penetrationAxisIndex, - box1, box2); - - // set L to be the normal that faces away from box1 - if (dot(L, D) < 0) { - L = -L; - } - - Vector3 contactPoint; - - if (penetrationAxisIndex < 6) { - // vertex to face collision, find deepest colliding vertex - const Box* vertexBox; - const Box* faceBox; - Vector3 faceNormal = L; - - // L will be the outward facing normal for the faceBox - if (penetrationAxisIndex < 3) { - faceBox = & box1; - vertexBox = & box2; - if (dot(L, D) < 0) { - faceNormal = -L; - } - } else { - faceBox = & box2; - vertexBox = & box1; - if (dot(L, D) > 0) { - faceNormal = -L; - } - } - - // find the vertex that is farthest away in the direction - // face normal direction - int deepestPointIndex = 0; - float deepestPointDot = dot(faceNormal, vertexBox->corner(0)); - for (int i = 1; i < 8; i++) { - float dotProduct = dot(faceNormal, vertexBox->corner(i)); - if (dotProduct < deepestPointDot) { - deepestPointDot = dotProduct; - deepestPointIndex = i; - } - } - - // return the point half way between the deepest point and the - // contacting face - contactPoint = vertexBox->corner(deepestPointIndex) + - (-penetration * 0.5 * faceNormal); - } else { - // edge-edge case, find the two ege lines - int edge1 = (penetrationAxisIndex - 6) / 3; - int edge2 = (penetrationAxisIndex - 6) % 3; - Vector3 linePoint1 = box1.center(); - Vector3 linePoint2 = box2.center(); - Vector3 lineDir1; - Vector3 lineDir2; - - // find edge line by finding the edge axis, and the - // other two axes that are closest to the other box - for (int i = 0; i < 3; i++ ) { - if (i == edge1) { - lineDir1 = box1.axis(i); - } else { - Vector3 axis = box1.axis(i); - if (dot(axis, L) < 0) { - axis = -axis; - } - linePoint1 += axis * a[i]; - } - - if (i == edge2) { - lineDir2 = box2.axis(i); - } else { - Vector3 axis = box2.axis(i); - if (dot(axis, L) > 0) { - axis = -axis; - } - linePoint2 += axis * b[i]; - } - } - - // make lines from the two closest edges, and find - // the points that on each line that are closest to the other - Line line1 = Line::fromPointAndDirection(linePoint1, lineDir1); - Line line2 = Line::fromPointAndDirection(linePoint2, lineDir2); - Vector3 closest1; - Vector3 closest2; - - closestPointsBetweenLineAndLine(line1, line2, closest1, closest2); - - // take the average of the two closest edge points for the final - // contact point - contactPoint = (closest1 + closest2) * 0.5; - } - - contactPoints.push(contactPoint); - contactNormals.push(L); - - return -penetration; - -} - - - - -float CollisionDetection::penetrationDepthForFixedSphereFixedBox( - const Sphere& sphere, - const Box& box, - Array& contactPoints, - Array& contactNormals) { - - contactPoints.resize(0, DONT_SHRINK_UNDERLYING_ARRAY); - contactNormals.resize(0, DONT_SHRINK_UNDERLYING_ARRAY); - - // In its local coordinate frame, the box measures - // 2 * halfExtent[a] along dimesion a. - Vector3 halfExtent(box.extent(0), box.extent(1), box.extent(2)); - halfExtent *= 0.5f; - - CoordinateFrame boxFrame; - box.getLocalFrame(boxFrame); - - // Transform the sphere to the box's coordinate frame. - Vector3 center = boxFrame.pointToObjectSpace(sphere.center); - - // Find the square of the distance from the sphere to the box - - - // Distance along each axis from the closest side of the box - // to the sphere center. Negative values are *inside* the box. - Vector3 distOutsideBox; - - // Divide space up into the 27 regions corresponding - // to {+|-|0}X, {+|-|0}Y, {+|-|0}Z and classify the - // sphere center into one of them. - Vector3 centerRegion; - - // In the edge collision case, the edge is between vertices - // (constant + variable) and (constant - variable). - Vector3 constant, variable; - - int numNonZero = 0; - - // Iterate over axes - for (int a = 0; a < 3; ++a) { - // For each (box side), see which direction the sphere - // is outside the box (positive or negative). Add the - // square of that distance to the total distance from - // the box. - - float distanceFromLow = -halfExtent[a] - center[a]; - float distanceFromHigh = center[a] - halfExtent[a]; - - if (fabsf(distanceFromLow) < fabsf(distanceFromHigh)) { - distOutsideBox[a] = distanceFromLow; - } else { - distOutsideBox[a] = distanceFromHigh; - } - - if (distanceFromLow < 0.0) { - if (distanceFromHigh < 0.0) { - // Inside the box - centerRegion[a] = 0.0; - variable[a] = 1.0; - } else { - // Off the high side - centerRegion[a] = 1.0; - constant[a] = halfExtent[a]; - ++numNonZero; - } - } else if (distanceFromHigh < 0.0) { - // Off the low side - centerRegion[a] = -1.0; - constant[a] = -halfExtent[a]; - ++numNonZero; - } else { - debugAssertM(false, - "distanceFromLow and distanceFromHigh cannot both be positive"); - } - } - - // Squared distance between the outside of the box and the - // sphere center. - float d2 = Vector3::zero().max(distOutsideBox).squaredMagnitude(); - - if (d2 > square(sphere.radius)) { - // There is no penetration because the distance is greater - // than the radius of the sphere. This is the common case - // and we quickly exit. - return -1; - } - - // We know there is some penetration but need to classify it. - // - // Examine the region that contains the center of the sphere. If - // there is exactly one non-zero axis, the collision is with a - // plane. If there are exactly two non-zero axes, the collision - // is with an edge. If all three axes are non-zero, the collision is - // with a vertex. If there are no non-zero axes, the center is inside - // the box. - - double depth = -1; - switch (numNonZero) { - case 3: // Vertex collision - // The collision point is the vertex at constant, the normal - // is the vector from there to the sphere center. - contactNormals.append(boxFrame.normalToWorldSpace(constant - center)); - contactPoints.append(boxFrame.pointToWorldSpace(constant)); - depth = sphere.radius - sqrt(d2); - break; - - case 2: // Edge collision - { - // TODO: unwrapping the edge constructor and closest point - // code will probably make it faster. - - // Determine the edge - Line line = Line::fromPointAndDirection(constant, variable); - - // Penetration depth: - depth = sphere.radius - sqrt(d2); - - // The contact point is the closes point to the sphere on the line - Vector3 X = line.closestPoint(center); - contactNormals.append(boxFrame.normalToWorldSpace(X - center).direction()); - contactPoints.append(boxFrame.pointToWorldSpace(X)); - } - break; - - case 1: // Plane collision - { - // The plane normal is the centerRegion vector, - // so the sphere normal is the negative. Take - // it to world space from box-space. - - // Center region doesn't need to be normalized because - // it is known to contain only one non-zero value - // and that value is +/- 1. - Vector3 N = boxFrame.normalToWorldSpace(-centerRegion); - contactNormals.append(N); - - // Penetration depth: - depth = sphere.radius - sqrtf(d2); - - // Compute the contact point from the penetration depth - contactPoints.append(sphere.center + N * (sphere.radius - depth)); - } - break; - - case 0: // Volume collision - - // The sphere center is inside the box. This is an easy case - // to handle. Note that all axes of distOutsideBox must - // be negative. - - // Arbitratily choose the sphere center as a contact point - contactPoints.append(sphere.center); - - // Find the least-negative penetration axis. - // - // We could have computed this during the loop over the axes, - // but since volume collisions are rare (they only occur with - // large time steps), this case will seldom be executed and - // should not be optimized at the expense of the others. - if (distOutsideBox.x > distOutsideBox.y) { - if (distOutsideBox.x > distOutsideBox.z) { - // Smallest penetration on x-axis - // Chose normal based on which side we're closest to. - // Keep in mind that this is a normal to the sphere, - // so it is the inverse of the box normal. - if (center.x > 0) { - contactNormals.append(boxFrame.normalToWorldSpace(-Vector3::unitX())); - } else { - contactNormals.append(boxFrame.normalToWorldSpace(Vector3::unitX())); - } - depth = -distOutsideBox.x; - } else { - // Smallest penetration on z-axis - goto ZAXIS; - } - } else if (distOutsideBox.y > distOutsideBox.z) { - // Smallest penetration on y-axis - // Chose normal based on which side we're closest to. - // Keep in mind that this is a normal to the sphere, - // so it is the inverse of the box normal. - if (center.y > 0) { - contactNormals.append(boxFrame.normalToWorldSpace(-Vector3::unitY())); - } else { - contactNormals.append(boxFrame.normalToWorldSpace(Vector3::unitY())); - } - depth = -distOutsideBox.y; - } else { - // Smallest on z-axis -ZAXIS: - // Chose normal based on which side we're closest to. - // Keep in mind that this is a normal to the sphere, - // so it is the inverse of the box normal. - if (center.z > 0) { - contactNormals.append(boxFrame.normalToWorldSpace(-Vector3::unitZ())); - } else { - contactNormals.append(boxFrame.normalToWorldSpace(Vector3::unitZ())); - } - depth = -distOutsideBox.z; - } - break; - - default: - debugAssertM(false, "Fell through switch"); - break; - } - - return depth; -} - - -float CollisionDetection::penetrationDepthForFixedSphereFixedSphere( - const Sphere& sphereA, - const Sphere& sphereB, - Array& contactPoints, - Array& contactNormals) { - - Vector3 axis = sphereB.center - sphereA.center; - double radius = sphereA.radius + sphereB.radius; - double mag = axis.magnitude(); - axis /= mag; - double depth = -(mag - radius); - - contactPoints.resize(0, DONT_SHRINK_UNDERLYING_ARRAY); - contactNormals.resize(0, DONT_SHRINK_UNDERLYING_ARRAY); - - if (depth >= 0) { - contactPoints.append(sphereA.center + axis * (sphereA.radius - depth / 2)); - contactNormals.append(axis); - } - - return depth; -} - - -float CollisionDetection::penetrationDepthForFixedSphereFixedPlane( - const Sphere& sphereA, - const Plane& planeB, - Array& contactPoints, - Array& contactNormals) { - - Vector3 N; - double d; - - planeB.getEquation(N, d); - - double depth = -(sphereA.center.dot(N) + d - sphereA.radius); - - contactPoints.resize(0, DONT_SHRINK_UNDERLYING_ARRAY); - contactNormals.resize(0, DONT_SHRINK_UNDERLYING_ARRAY); - - if (depth >= 0) { - contactPoints.append(N * (depth - sphereA.radius) + sphereA.center); - contactNormals.append(N); - } - - return depth; -} - - -float CollisionDetection::penetrationDepthForFixedBoxFixedPlane( - const Box& box, - const Plane& plane, - Array& contactPoints, - Array& contactNormals) { - - Vector3 N; - double d; - - plane.getEquation(N, d); - - contactPoints.resize(0, DONT_SHRINK_UNDERLYING_ARRAY); - contactNormals.resize(0, DONT_SHRINK_UNDERLYING_ARRAY); - - float lowest = finf(); - for (int i = 0; i < 8; ++i) { - const Vector3 vertex = box.corner(i); - - float x = vertex.dot(N) + (float)d; - - if (x <= 0) { - // All vertices below the plane should be contact points. - contactPoints.append(vertex); - contactNormals.append(-N); - } - - lowest = min(lowest, x); - } - - // Depth should be a positive number - return -lowest; -} - - -float CollisionDetection::collisionTimeForMovingPointFixedPlane( - const Vector3& point, - const Vector3& velocity, - const Plane& plane, - Vector3& location, - Vector3& outNormal) { - - // Solve for the time at which normal.dot(point + velocity) + d == 0. - double d; - Vector3 normal; - plane.getEquation(normal, d); - - float vdotN = velocity.dot(normal); - float pdotN = point.dot(normal); - - if (fuzzyEq(pdotN + d, 0)) { - // The point is *in* the plane. - location = point; - outNormal = normal; - return 0; - } - - if (vdotN >= 0) { - // no collision will occur - location = Vector3::inf(); - return finf(); - } - - float t = -(pdotN + d) / vdotN; - if (t < 0) { - location = Vector3::inf(); - return finf(); - } else { - location = point + velocity * t; - outNormal = normal; - return t; - } -} - -bool __fastcall CollisionDetection::rayAABox( - const Ray& ray, - const Vector3& invDir, - const AABox& box, - const Vector3& boxCenter, - float boundingRadiusSquared, - Vector3& location, - bool& inside) { - - debugAssertM(fabs(ray.direction().squaredLength() - 1.0f) < 0.01f, format("Length = %f", ray.direction().length())); - { - // Pre-emptive partial bounding sphere test - const Vector3 L(boxCenter - ray.origin()); - float d = L.dot(ray.direction()); - - float L2 = L.dot(L); - float D2 = square(d); - float M2 = L2 - D2; - - if (((d < 0) && (L2 > boundingRadiusSquared)) || (M2 > boundingRadiusSquared)) { - inside = false; - return false; - } - // Passing here does not mean that the ray hits the bounding sphere; - // we would still have to perform more expensive tests to determine - // that. - } - - inside = true; - const Vector3& MinB = box.low(); - const Vector3& MaxB = box.high(); - Vector3 MaxT(-1.0f, -1.0f, -1.0f); - - // Find candidate planes. - for (int i = 0; i < 3; ++i) { - if (ray.origin()[i] < MinB[i]) { - location[i] = MinB[i]; - inside = false; - - // Calculate T distances to candidate planes - if (ray.direction()[i] != 0) { - MaxT[i] = (MinB[i] - ray.origin()[i]) * invDir[i]; - } - } else if (ray.origin()[i] > MaxB[i]) { - location[i] = MaxB[i]; - inside = false; - - // Calculate T distances to candidate planes - if (ray.direction()[i] != 0) { - MaxT[i] = (MaxB[i] - ray.origin()[i]) * invDir[i]; - } - } - } - - if (inside) { - // Ray origin inside bounding box - location = ray.origin(); - return true; - } - - // Get largest of the maxT's for final choice of intersection - int WhichPlane = 0; - if (MaxT[1] > MaxT[WhichPlane]) { - WhichPlane = 1; - } - - if (MaxT[2] > MaxT[WhichPlane]) { - WhichPlane = 2; - } - - // Check final candidate actually inside box - if (MaxT[WhichPlane] < 0.0f) { - // Miss the box - return false; - } - - for (int i = 0; i < 3; ++i) { - if (i != WhichPlane) { - location[i] = ray.origin()[i] + MaxT[WhichPlane] * ray.direction()[i]; - if ((location[i] < MinB[i]) || - (location[i] > MaxB[i])) { - // On this plane we're outside the box extents, so - // we miss the box - return false; - } - } - } - - return true; -} - -float CollisionDetection::collisionTimeForMovingPointFixedSphere( - const Vector3& point, - const Vector3& velocity, - const Sphere& sphere, - Vector3& location, - Vector3& outNormal, - bool solid) { - - if (solid && sphere.contains(point)) { - location = point; - outNormal = (point - sphere.center).direction(); - return 0.0f; - } - - float speed = velocity.magnitude(); - const Vector3& direction = velocity / speed; - - // length of the axis between the start and the sphere - const Vector3& L = sphere.center - point; - float d = L.dot(direction); - - float L2 = L.dot(L); - float R2 = square(sphere.radius); - float D2 = square(d); - - if ((d < 0.0f) && (L2 > R2)) { - location = Vector3::inf(); - return finf(); - } - - const float M2 = L2 - D2; - - if (M2 > R2) { - location = Vector3::inf(); - return finf(); - } - - float q = sqrt(R2 - M2); - float time; - - if (L2 > R2) { - time = d - q; - } else { - time = d + q; - } - - time /= speed; - - location = point + velocity * time; - outNormal = (location - sphere.center).direction(); - - return time; -} - - -float CollisionDetection::collisionTimeForMovingSphereFixedSphere( - const Sphere& movingSphere, - const Vector3& velocity, - const Sphere& fixedSphere, - Vector3& location, - Vector3& outNormal) { - - const Vector3& sep = (fixedSphere.center - movingSphere.center); - float sepLen = sep.squaredLength(); - if (sepLen < square(movingSphere.radius + fixedSphere.radius)) { - // Interpenetrating - outNormal = sep.directionOrZero(); - location = fixedSphere.center - outNormal * fixedSphere.radius; - return 0; - } - - float time = collisionTimeForMovingPointFixedSphere - (movingSphere.center, velocity, - Sphere(fixedSphere.center, fixedSphere.radius + movingSphere.radius), - location, outNormal); - - if (time < finf()) { - // Location is now the center of the moving sphere at the collision time. - // Adjust for the size of the moving sphere. Two spheres always collide - // along a line between their centers. - location += (location - fixedSphere.center) * movingSphere.radius / fixedSphere.radius; - } - - return time; -} - - -/* -float CollisionDetection::collisionTimeForMovingPointFixedTriangle( - const Vector3& point, - const Vector3& velocity, - const Triangle& triangle, - Vector3& outLocation, - Vector3& outNormal) { - - double time = collisionTimeForMovingPointFixedPlane(point, velocity, triangle.plane(), outLocation, outNormal); - - if (time == finf()) { - // No collision with the plane of the triangle. - return finf(); - } - - if (isPointInsideTriangle(triangle.vertex(0), triangle.vertex(1), triangle.vertex(2), triangle.normal(), outLocation, triangle.primaryAxis())) { - // Collision occured inside the triangle - return time; - } else { - // Missed the triangle - outLocation = Vector3::inf(); - return finf(); - } -}*/ - -/* -float CollisionDetection::collisionTimeForMovingPointFixedTriangle( - const Vector3& orig, - const Vector3& dir, - const Vector3& vert0, - const Vector3& vert1, - const Vector3& vert2) { - - // Barycenteric coords - double u, v; - #define EPSILON 0.000001 - #define CROSS(dest,v1,v2) \ - dest[0]=v1[1]*v2[2]-v1[2]*v2[1]; \ - dest[1]=v1[2]*v2[0]-v1[0]*v2[2]; \ - dest[2]=v1[0]*v2[1]-v1[1]*v2[0]; - - #define DOT(v1,v2) (v1[0]*v2[0]+v1[1]*v2[1]+v1[2]*v2[2]) - - #define SUB(dest,v1,v2) \ - dest[0]=v1[0]-v2[0]; \ - dest[1]=v1[1]-v2[1]; \ - dest[2]=v1[2]-v2[2]; - - double edge1[3], edge2[3], tvec[3], pvec[3], qvec[3]; - - // find vectors for two edges sharing vert0 - SUB(edge1, vert1, vert0); - SUB(edge2, vert2, vert0); - - // begin calculating determinant - also used to calculate U parameter - CROSS(pvec, dir, edge2); - - // if determinant is near zero, ray lies in plane of triangle - const double det = DOT(edge1, pvec); - - if (det < EPSILON) { - return finf(); - } - - // calculate distance from vert0 to ray origin - SUB(tvec, orig, vert0); - - // calculate U parameter and test bounds - u = DOT(tvec, pvec); - if ((u < 0.0) || (u > det)) { - // Hit the plane outside the triangle - return finf(); - } - - // prepare to test V parameter - CROSS(qvec, tvec, edge1); - - // calculate V parameter and test bounds - v = DOT(dir, qvec); - if ((v < 0.0) || (u + v > det)) { - // Hit the plane outside the triangle - return finf(); - } - - // calculate t, scale parameters, ray intersects triangle - // If we want u,v, we can compute this - // double t = DOT(edge2, qvec); - //const double inv_det = 1.0 / det; - //t *= inv_det; - //u *= inv_det; - //v *= inv_det; - // return t; - - // Case where we don't need correct (u, v): - - const double t = DOT(edge2, qvec); - - if (t >= 0) { - // Note that det must be positive - return t / det; - } else { - // We had to travel backwards in time to intersect - return finf(); - } - - #undef EPSILON - #undef CROSS - #undef DOT - #undef SUB -} -*/ - -float CollisionDetection::collisionTimeForMovingPointFixedBox( - const Vector3& point, - const Vector3& velocity, - const Box& box, - Vector3& location, - Vector3& outNormal) { - - double bestTime; - - Vector3 normal; - Vector3 v[4]; - - // Prime the loop - int f = 0; - box.getFaceCorners(f, v[0], v[1], v[2], v[3]); - bestTime = collisionTimeForMovingPointFixedRectangle(point, velocity, v[0], v[1], v[2], v[3], location, normal); - outNormal = normal; - - // Check other faces - for (f = 1; f < 6; ++f) { - Vector3 pos; - box.getFaceCorners(f, v[0], v[1], v[2], v[3]); - float time = collisionTimeForMovingPointFixedRectangle(point, velocity, v[0], v[1], v[2], v[3], pos, normal); - if (time < bestTime) { - bestTime = time; - outNormal = normal; - location = pos; - } - } - - return bestTime; -} - - -float CollisionDetection::collisionTimeForMovingPointFixedAABox( - const Vector3& origin, - const Vector3& dir, - const AABox& box, - Vector3& location, - bool& Inside, - Vector3& normal) { - - if (collisionLocationForMovingPointFixedAABox(origin, dir, box, location, Inside, normal)) { - return (location - origin).magnitude(); - } else { - return (float)finf(); - } -} - - -bool CollisionDetection::collisionLocationForMovingPointFixedAABox( - const Vector3& origin, - const Vector3& dir, - const AABox& box, - Vector3& location, - bool& Inside, - Vector3& normal) { - - // Integer representation of a floating-point value. - #define IR(x) ((uint32&)x) - - Inside = true; - const Vector3& MinB = box.low(); - const Vector3& MaxB = box.high(); - Vector3 MaxT(-1.0f, -1.0f, -1.0f); - - // Find candidate planes. - for (int i = 0; i < 3; ++i) { - if (origin[i] < MinB[i]) { - location[i] = MinB[i]; - Inside = false; - - // Calculate T distances to candidate planes - if (IR(dir[i])) { - MaxT[i] = (MinB[i] - origin[i]) / dir[i]; - } - } else if (origin[i] > MaxB[i]) { - location[i] = MaxB[i]; - Inside = false; - - // Calculate T distances to candidate planes - if (IR(dir[i])) { - MaxT[i] = (MaxB[i] - origin[i]) / dir[i]; - } - } - } - - if (Inside) { - // Ray origin inside bounding box - location = origin; - return false; - } - - // Get largest of the maxT's for final choice of intersection - int WhichPlane = 0; - if (MaxT[1] > MaxT[WhichPlane]) { - WhichPlane = 1; - } - - if (MaxT[2] > MaxT[WhichPlane]) { - WhichPlane = 2; - } - - // Check final candidate actually inside box - if (IR(MaxT[WhichPlane]) & 0x80000000) { - // Miss the box - return false; - } - - for (int i = 0; i < 3; ++i) { - if (i != WhichPlane) { - location[i] = origin[i] + MaxT[WhichPlane] * dir[i]; - if ((location[i] < MinB[i]) || - (location[i] > MaxB[i])) { - // On this plane we're outside the box extents, so - // we miss the box - return false; - } - } - } - - // Choose the normal to be the plane normal facing into the ray - normal = Vector3::zero(); - normal[WhichPlane] = (dir[WhichPlane] > 0) ? -1.0 : 1.0; - - return true; - - #undef IR -} - - - -float CollisionDetection::collisionTimeForMovingPointFixedRectangle( - const Vector3& point, - const Vector3& velocity, - const Vector3& v0, - const Vector3& v1, - const Vector3& v2, - const Vector3& v3, - Vector3& location, - Vector3& outNormal) { - - Plane plane = Plane(v0, v1, v2); - - float time = collisionTimeForMovingPointFixedPlane(point, velocity, plane, location, outNormal); - - if (time == finf()) { - // No collision is ever going to happen - return time; - } - - if (isPointInsideRectangle(v0, v1, v2, v3, plane.normal(), location)) { - // The intersection point is inside the rectangle; that is the location where - // the point hits the rectangle. - return time; - } else { - return finf(); - } -} - -/** Used by findRayCapsuleIntersection. - @cite From magic software http://www.magic-software.com/Source/Intersection3D/MgcIntr3DLinCap.cpp */ -static int findRayCapsuleIntersectionAux( - const Vector3& rkOrigin, - const Vector3& rkDirection, - const Capsule& rkCapsule, - double afT[2]) { - - Vector3 capsuleDirection = rkCapsule.point(1) - rkCapsule.point(0); - - // set up quadratic Q(t) = a*t^2 + 2*b*t + c - Vector3 kU, kV, kW = capsuleDirection; - float fWLength = kW.unitize(); - Vector3::generateOrthonormalBasis(kU, kV, kW); - Vector3 kD(kU.dot(rkDirection), kV.dot(rkDirection), kW.dot(rkDirection)); - float fDLength = kD.unitize(); - - float fEpsilon = 1e-6f; - - float fInvDLength = 1.0f/fDLength; - Vector3 kDiff = rkOrigin - rkCapsule.point(0); - Vector3 kP(kU.dot(kDiff),kV.dot(kDiff),kW.dot(kDiff)); - float fRadiusSqr = square(rkCapsule.radius()); - - float fInv, fA, fB, fC, fDiscr, fRoot, fT, fTmp; - - // Is the velocity parallel to the capsule direction? (or zero) - if ((abs(kD.z) >= 1.0f - fEpsilon) || (fDLength < fEpsilon)) { - - float fAxisDir = rkDirection.dot(capsuleDirection); - - fDiscr = fRadiusSqr - kP.x*kP.x - kP.y*kP.y; - if ((fAxisDir < 0) && (fDiscr >= 0.0f)) { - // Velocity anti-parallel to the capsule direction - fRoot = sqrt(fDiscr); - afT[0] = (kP.z + fRoot)*fInvDLength; - afT[1] = -(fWLength - kP.z + fRoot)*fInvDLength; - return 2; - } else if ((fAxisDir > 0) && (fDiscr >= 0.0f)) { - // Velocity parallel to the capsule direction - fRoot = sqrt(fDiscr); - afT[0] = -(kP.z + fRoot)*fInvDLength; - afT[1] = (fWLength - kP.z + fRoot)*fInvDLength; - return 2; - } else { - // sphere heading wrong direction, or no velocity at all - return 0; - } - } - - // test intersection with infinite cylinder - fA = kD.x*kD.x + kD.y*kD.y; - fB = kP.x*kD.x + kP.y*kD.y; - fC = kP.x*kP.x + kP.y*kP.y - fRadiusSqr; - fDiscr = fB*fB - fA*fC; - if (fDiscr < 0.0f) { - // line does not intersect infinite cylinder - return 0; - } - - int iQuantity = 0; - - if (fDiscr > 0.0f) { - // line intersects infinite cylinder in two places - fRoot = sqrt(fDiscr); - fInv = 1.0f/fA; - fT = (-fB - fRoot)*fInv; - fTmp = kP.z + fT*kD.z; - if ((0.0f <= fTmp) && (fTmp <= fWLength)) { - afT[iQuantity] = fT * fInvDLength; - iQuantity++; - } - - fT = (-fB + fRoot)*fInv; - fTmp = kP.z + fT*kD.z; - - if ((0.0f <= fTmp) && (fTmp <= fWLength)) { - afT[iQuantity++] = fT*fInvDLength; - } - - if (iQuantity == 2) { - // line intersects capsule wall in two places - return 2; - } - } else { - // line is tangent to infinite cylinder - fT = -fB/fA; - fTmp = kP.z + fT*kD.z; - if ((0.0f <= fTmp) && (fTmp <= fWLength)) { - afT[0] = fT*fInvDLength; - return 1; - } - } - - // test intersection with bottom hemisphere - // fA = 1 - fB += kP.z*kD.z; - fC += kP.z*kP.z; - fDiscr = fB*fB - fC; - if (fDiscr > 0.0f) { - fRoot = sqrt(fDiscr); - fT = -fB - fRoot; - fTmp = kP.z + fT*kD.z; - if (fTmp <= 0.0f) { - afT[iQuantity++] = fT*fInvDLength; - if (iQuantity == 2) { - return 2; - } - } - - fT = -fB + fRoot; - fTmp = kP.z + fT*kD.z; - if (fTmp <= 0.0f) { - afT[iQuantity++] = fT*fInvDLength; - if (iQuantity == 2) { - return 2; - } - } - } else if (fDiscr == 0.0f) { - fT = -fB; - fTmp = kP.z + fT*kD.z; - if (fTmp <= 0.0f) { - afT[iQuantity++] = fT*fInvDLength; - if (iQuantity == 2) { - return 2; - } - } - } - - // test intersection with top hemisphere - // fA = 1 - fB -= kD.z*fWLength; - fC += fWLength*(fWLength - 2.0f*kP.z); - - fDiscr = fB*fB - fC; - if (fDiscr > 0.0f) { - fRoot = sqrt(fDiscr); - fT = -fB - fRoot; - fTmp = kP.z + fT*kD.z; - if (fTmp >= fWLength) { - afT[iQuantity++] = fT*fInvDLength; - if (iQuantity == 2) { - return 2; - } - } - - fT = -fB + fRoot; - fTmp = kP.z + fT*kD.z; - if (fTmp >= fWLength) { - afT[iQuantity++] = fT*fInvDLength; - if (iQuantity == 2) { - return 2; - } - } - } else if (fDiscr == 0.0f) { - fT = -fB; - fTmp = kP.z + fT*kD.z; - if (fTmp >= fWLength) { - afT[iQuantity++] = fT*fInvDLength; - if (iQuantity == 2) { - return 2; - } - } - } - - return iQuantity; -} - - -/** Used by collisionTimeForMovingPointFixedCapsule. - @cite From magic software http://www.magic-software.com/Source/Intersection3D/MgcIntr3DLinCap.cpp - - @param rkRay The ray - @param rkCapsule The capsule - @param riQuantity The number of intersections found - @param akPoint The intersections found - @return True if there is at least one intersection - */ -static bool findRayCapsuleIntersection( - const Ray& rkRay, - const Capsule& rkCapsule, - int& riQuantity, - Vector3 akPoint[2]) { - - double afT[2]; - riQuantity = findRayCapsuleIntersectionAux(rkRay.origin(), rkRay.direction(), rkCapsule, afT); - - // Only return intersections that occur in the future - int iClipQuantity = 0; - int i; - for (i = 0; i < riQuantity; ++i) { - if (afT[i] >= 0.0f) { - akPoint[iClipQuantity] = rkRay.origin() + afT[i] * rkRay.direction(); - ++iClipQuantity; - } - } - - riQuantity = iClipQuantity; - return (riQuantity > 0); -} - -float CollisionDetection::collisionTimeForMovingPointFixedCapsule( - const Vector3& _point, - const Vector3& velocity, - const Capsule& capsule, - Vector3& location, - Vector3& outNormal) { - - float timeScale = velocity.magnitude(); - - if (timeScale == 0.0f) { - timeScale = 1; - } - - Vector3 direction = velocity / timeScale; - int numIntersections; - Vector3 intersection[2]; - findRayCapsuleIntersection(Ray::fromOriginAndDirection(_point, direction), capsule, numIntersections, intersection); - - if (numIntersections == 2) { - // A collision can only occur if there are two intersections. If there is one - // intersection, that one is exiting the capsule. - - // Find the entering intersection (the first one that occurs). - float d0 = (intersection[0] - _point).squaredMagnitude(); - float d1 = (intersection[1] - _point).squaredMagnitude(); - - // Compute the surface normal (if we aren't ignoring the result) - if (&outNormal != &ignore) { - Vector3 p2 = LineSegment::fromTwoPoints(capsule.point(0), capsule.point(1)).closestPoint(_point); - outNormal = (_point - p2).direction(); - } - - if (d0 > d1) { - location = intersection[1]; - return sqrt(d1) / timeScale; - } else { - location = intersection[0]; - return sqrt(d0) / timeScale; - } - } else { - // No entering intersection discovered; return no intersection. - location = Vector3::inf(); - return finf(); - } -} - - -float CollisionDetection::collisionTimeForMovingSphereFixedPlane( - const Sphere& sphere, - const Vector3& velocity, - const Plane& plane, - Vector3& location, - Vector3& outNormal) { - - if (sphere.radius == 0) { - // Optimization for zero radius sphere - return collisionTimeForMovingPointFixedPlane(sphere.center, velocity, plane, location, outNormal); - } - - // The collision point on the sphere will be the point at - // center - (radius * normal). Collisions only occur when - // the sphere is travelling into the plane. - - double d; - plane.getEquation(outNormal, d); - - double vdotN = velocity.dot(outNormal); - - if (fuzzyGt(vdotN, 0)) { - // No collision when the sphere is moving towards a backface. - location = Vector3::inf(); - return (float)finf(); - } - - float cdotN = sphere.center.dot(outNormal); - - // Distance from the center to the plane - float distance = cdotN + (float)d; - - // Where is the collision on the sphere? - Vector3 point = sphere.center - (sphere.radius * outNormal); - - if (fuzzyLe(G3D::abs(distance), sphere.radius)) { - // Already interpenetrating - location = sphere.center - distance * outNormal; - return 0; - } else { - return collisionTimeForMovingPointFixedPlane(point, velocity, plane, location, outNormal); - } - -} - - -float CollisionDetection::collisionTimeForMovingSphereFixedTriangle( - const class Sphere& sphere, - const Vector3& velocity, - const Triangle& triangle, - Vector3& outLocation, - float b[3]) { - - Vector3 dummy; - float time = collisionTimeForMovingSphereFixedPlane(sphere, velocity, triangle.plane(), - outLocation, dummy); - - if (time == finf()) { - // No collision is ever going to happen - return time; - } - - // We will hit the plane of the triangle at *time*. See if - // the intersection point actually is within the triangle. - - if (isPointInsideTriangle(triangle.vertex(0), triangle.vertex(1), triangle.vertex(2), triangle.normal(), - outLocation, b, triangle.primaryAxis())) { - - // The intersection point is inside the triangle; that is the location where - // the sphere hits the triangle. - -# ifdef G3D_DEBUG - { - // Internal consistency checks - debugAssertM(b[0] >= 0.0 && b[0] <= 1.0f, "Intersection is outside triangle."); - debugAssertM(b[1] >= 0.0 && b[1] <= 1.0f, "Intersection is outside triangle."); - debugAssertM(b[2] >= 0.0 && b[2] <= 1.0f, "Intersection is outside triangle."); - Vector3 blend = - b[0] * triangle.vertex(0) + - b[1] * triangle.vertex(1) + - b[2] * triangle.vertex(2); - debugAssertM(blend.fuzzyEq(outLocation), "Barycentric coords don't match intersection."); - // Call again so that we can debug the problem - // isPointInsideTriangle(triangle.vertex(0), triangle.vertex(1), triangle.vertex(2), triangle.normal(), - // outLocation, b, triangle.primaryAxis()); - } -# endif - - return time; - } - - // The collision (if it exists) is with a point on the triangle perimeter. - // Switch over to moving the triangle towards a fixed sphere and see at what time - // they will hit. - - // Closest point on the triangle to the sphere intersection with the plane. - int edgeIndex; - const Vector3& point = closestPointOnTrianglePerimeter(triangle._vertex, triangle.edgeDirection, - triangle.edgeMagnitude, outLocation, edgeIndex); - - float t = 0; - if (! sphere.contains(point)) { - // The point is outside the sphere--see when it will hit - t = collisionTimeForMovingPointFixedSphere(point, -velocity, sphere, dummy, dummy); - } - - if (t < finf()) { - outLocation = point; - // Compute Barycentric coords - - // Index of the next vertex - static const int next[] = {1, 2, 0}; - - // Project along the edge in question. - // Avoid sqrt by taking advantage of the existing edgeDirection unit vector. - b[next[edgeIndex]] = (outLocation - triangle._vertex[edgeIndex]).dot - (triangle.edgeDirection[edgeIndex]) / triangle.edgeMagnitude[edgeIndex]; - - b[edgeIndex] = 1.0f - b[next[edgeIndex]]; - - b[next[next[edgeIndex]]] = 0.0f; - -# ifdef G3D_DEBUG - { - // Internal consistency checks - for (int i = 0; i < 3; ++i) { - debugAssertM(fuzzyGe(b[i], 0.0f) && fuzzyLe(b[i], 1.0f), "Intersection is outside triangle."); - } - Vector3 blend = - b[0] * triangle.vertex(0) + - b[1] * triangle.vertex(1) + - b[2] * triangle.vertex(2); - debugAssertM(blend.fuzzyEq(outLocation), - format("Barycentric coords don't match intersection. %s != %s", - blend.toString().c_str(), - outLocation.toString().c_str())); - - // Call again so that we can debug the problem - collisionTimeForMovingPointFixedSphere(point, -velocity, sphere, dummy, dummy); - } -# endif - - // Due to tiny roundoffs, these values might be slightly out of bounds. - // Ensure that they are legal. Note that the above debugging code - // verifies that we are not clamping truly illegal values. - for (int i = 0; i < 3; ++i) { - b[i] = clamp(b[i], 0.0f, 1.0f); - } - } - - // The collision occured at the point, if it occured. The normal - // was the plane normal, computed above. - - return t; -} - - -float CollisionDetection::collisionTimeForMovingSphereFixedRectangle( - const Sphere& sphere, - const Vector3& velocity, - const Vector3& v0, - const Vector3& v1, - const Vector3& v2, - const Vector3& v3, - Vector3& location, - Vector3& outNormal) { - - Plane plane(v0, v1, v2); - - float time = collisionTimeForMovingSphereFixedPlane(sphere, velocity, plane, location, outNormal); - - if (time == finf()) { - // No collision is ever going to happen - return time; - } - - if (isPointInsideRectangle(v0, v1, v2, v3, plane.normal(), location)) { - // The intersection point is inside the rectangle; that is the location where - // the sphere hits the rectangle. - return time; - } - - // Switch over to moving the rectangle towards a fixed sphere and see at what time - // they will hit. - - Vector3 point = closestPointToRectanglePerimeter(v0, v1, v2, v3, sphere.center); - - Vector3 dummy; - double t = collisionTimeForMovingPointFixedSphere(point, -velocity, sphere, location, dummy); - - // Normal is the plane normal, location is the original location of the point. - location = point; - - return t; -} - - -float CollisionDetection::collisionTimeForMovingSphereFixedBox( - const Sphere& sphere, - const Vector3& velocity, - const Box& box, - Vector3& location, - Vector3& outNormal) { - - if (fixedSolidSphereIntersectsFixedSolidBox(sphere, box)) { - // TODO: Compute more useful location and normal? - location = sphere.center; - outNormal = Vector3::zero(); - return 0; - } - - float bestTime; - - Vector3 v[4]; - int f = 0; - box.getFaceCorners(f, v[0], v[1], v[2], v[3]); - bestTime = collisionTimeForMovingSphereFixedRectangle(sphere, velocity, v[0], v[1], v[2], v[3], location, outNormal); - - for (f = 1; f < 6; ++f) { - Vector3 pos, normal; - box.getFaceCorners(f, v[0], v[1], v[2], v[3]); - float time = collisionTimeForMovingSphereFixedRectangle(sphere, velocity, v[0], v[1], v[2], v[3], pos, normal); - if (time < bestTime) { - bestTime = time; - location = pos; - outNormal = normal; - } - } - - return bestTime; -} - - -float CollisionDetection::collisionTimeForMovingSphereFixedCapsule( - const Sphere& sphere, - const Vector3& velocity, - const Capsule& capsule, - Vector3& location, - Vector3& outNormal) { - - (void)outNormal; - - Capsule _capsule(capsule.point(0), capsule.point(1), capsule.radius() + sphere.radius); - - Vector3 normal; - double time = collisionTimeForMovingPointFixedCapsule(sphere.center, velocity, _capsule, location, normal); - - if (time < finf()) { - // Location is now the position of the center of the sphere at the time of collision. - // We have to adjust the collision location for the size of the sphere. - location -= sphere.radius * normal; - } - - return time; -} - - -Vector3 CollisionDetection::bounceDirection( - const Sphere& sphere, - const Vector3& velocity, - const float collisionTime, - const Vector3& collisionLocation, - const Vector3& collisionNormal) { - - // Location when the collision occurs - Vector3 sphereLocation = sphere.center + velocity * collisionTime; - - Vector3 normal = (sphereLocation - collisionLocation); - if (fuzzyEq(normal.squaredMagnitude(), 0)) { - normal = collisionNormal; - } else { - normal.unitize(); - } - - Vector3 direction = velocity.direction(); - - // Reflect direction about the normal - return direction - 2.0 * normal * normal.dot(direction); -} - - -Vector3 CollisionDetection::slideDirection( - const Sphere& sphere, - const Vector3& velocity, - const float collisionTime, - const Vector3& collisionLocation) { - - Vector3 sphereLocation = sphere.center + velocity * collisionTime; - Vector3 normal = (sphereLocation - collisionLocation).direction(); - Vector3 direction = velocity.direction(); - - // subtract off the part in the direction away from the normal. - return direction - normal * normal.dot(direction); -} - - -Vector3 CollisionDetection::closestPointOnLineSegment( - const Vector3& v0, - const Vector3& v1, - const Vector3& point) { - - const Vector3& edge = (v1 - v0); - float edgeLength = edge.magnitude(); - - if (edgeLength == 0) { - // The line segment is a point - return v0; - } - - return closestPointOnLineSegment(v0, v1, edge / edgeLength, edgeLength, point); -} - - -Vector3 CollisionDetection::closestPointOnLineSegment( - const Vector3& v0, - const Vector3& v1, - const Vector3& edgeDirection, - const float edgeLength, - const Vector3& point) { - - debugAssert((v1 - v0).direction().fuzzyEq(edgeDirection)); - debugAssert(fuzzyEq((v1 - v0).magnitude(), edgeLength)); - - // Vector towards the point - const Vector3& c = point - v0; - - // Projected onto the edge itself - float t = edgeDirection.dot(c); - - if (t <= 0) { - // Before the start - return v0; - } else if (t >= edgeLength) { - // After the end - return v1; - } else { - // At distance t along the edge - return v0 + edgeDirection * t; - } -} - - -Vector3 CollisionDetection::closestPointOnTrianglePerimeter( - const Vector3& v0, - const Vector3& v1, - const Vector3& v2, - const Vector3& point) { - - Vector3 v[3] = {v0, v1, v2}; - Vector3 edgeDirection[3] = {(v1 - v0), (v2 - v1), (v0 - v2)}; - float edgeLength[3]; - - for (int i = 0; i < 3; ++i) { - edgeLength[i] = edgeDirection[i].magnitude(); - edgeDirection[i] /= edgeLength[i]; - } - - int edgeIndex; - return closestPointOnTrianglePerimeter(v, edgeDirection, edgeLength, point, edgeIndex); -} - - -Vector3 CollisionDetection::closestPointOnTrianglePerimeter( - const Vector3 v[3], - const Vector3 edgeDirection[3], - const float edgeLength[3], - const Vector3& point, - int& edgeIndex) { - - // Closest point on segment from v[i] to v[i + 1] - Vector3 r[3]; - - // Distance squared from r[i] to point - float d[3]; - - // Index of the next point - static const int next[] = {1, 2, 0}; - - for (int i = 0; i < 3; ++i) { - r[i] = closestPointOnLineSegment(v[i], v[next[i]], edgeDirection[i], edgeLength[i], point); - d[i] = (r[i] - point).squaredMagnitude(); - } - - if (d[0] < d[1]) { - if (d[0] < d[2]) { - // Between v0 and v1 - edgeIndex = 0; - } else { - // Between v2 and v0 - edgeIndex = 2; - } - } else { - if (d[1] < d[2]) { - // Between v1 and v2 - edgeIndex = 1; - } else { - // Between v2 and v0 - edgeIndex = 2; - } - } - -# ifdef G3D_DEBUG - { - Vector3 diff = r[edgeIndex] - v[edgeIndex]; - debugAssertM(fuzzyEq(diff.direction().dot(edgeDirection[edgeIndex]), 1.0f) || - diff.fuzzyEq(Vector3::zero()), "Point not on correct triangle edge"); - float frac = diff.dot(edgeDirection[edgeIndex])/edgeLength[edgeIndex]; - debugAssertM(frac >= -0.000001, "Point off low side of edge."); - debugAssertM(frac <= 1.000001, "Point off high side of edge."); - } -# endif - - return r[edgeIndex]; -} - - -bool CollisionDetection::isPointInsideTriangle( - const Vector3& v0, - const Vector3& v1, - const Vector3& v2, - const Vector3& normal, - const Vector3& point, - float b[3], - Vector3::Axis primaryAxis) { - - if (primaryAxis == Vector3::DETECT_AXIS) { - primaryAxis = normal.primaryAxis(); - } - - // Check that the point is within the triangle using a Barycentric - // coordinate test on a two dimensional plane. - int i, j; - - switch (primaryAxis) { - case Vector3::X_AXIS: - i = Vector3::Y_AXIS; - j = Vector3::Z_AXIS; - break; - - case Vector3::Y_AXIS: - i = Vector3::Z_AXIS; - j = Vector3::X_AXIS; - break; - - case Vector3::Z_AXIS: - i = Vector3::X_AXIS; - j = Vector3::Y_AXIS; - break; - - default: - // This case is here to supress a warning on Linux - i = j = 0; - debugAssertM(false, "Should not get here."); - break; - } - - // See if all barycentric coordinates are non-negative - - // 2D area via cross product -# define AREA2(d, e, f) (((e)[i] - (d)[i]) * ((f)[j] - (d)[j]) - ((f)[i] - (d)[i]) * ((e)[j] - (d)[j])) - - // Area of the polygon - float area = AREA2(v0, v1, v2); - if (area == 0) { - // This triangle has zero area, so the point must not - // be in it unless the triangle point is the test point. - return (v0 == point); - } - - debugAssert(area != 0); - - float invArea = 1.0f / area; - - // (avoid normalization until absolutely necessary) - b[0] = AREA2(point, v1, v2) * invArea; - - if ((b[0] < 0.0f) || (b[0] > 1.0f)) { - return false; - } - - b[1] = AREA2(v0, point, v2) * invArea; - if ((b[1] < 0.0f) || (b[1] > 1.0f)) { - return false; - } - - b[2] = 1.0f - b[0] - b[1]; - -# undef AREA2 - - return (b[2] >= 0.0f) && (b[2] <= 1.0f); -} - - -bool CollisionDetection::isPointInsideRectangle( - const Vector3& v0, - const Vector3& v1, - const Vector3& v2, - const Vector3& v3, - const Vector3& normal, - const Vector3& point) { - - return isPointInsideTriangle(v0, v1, v2, normal, point) || - isPointInsideTriangle(v2, v3, v0, normal, point); -} - - -Vector3 CollisionDetection::closestPointToRectanglePerimeter( - const Vector3& v0, - const Vector3& v1, - const Vector3& v2, - const Vector3& v3, - const Vector3& point) { - - Vector3 r0 = closestPointOnLineSegment(v0, v1, point); - Vector3 r1 = closestPointOnLineSegment(v1, v2, point); - Vector3 r2 = closestPointOnLineSegment(v2, v3, point); - Vector3 r3 = closestPointOnLineSegment(v3, v0, point); - - double d0 = (r0 - point).squaredMagnitude(); - double d1 = (r1 - point).squaredMagnitude(); - double d2 = (r2 - point).squaredMagnitude(); - double d3 = (r3 - point).squaredMagnitude(); - - if (d0 < d1) { - if (d0 < d2) { - if (d0 < d3) { - return r0; - } else { - return r3; - } - } else { - if (d2 < d3) { - return r2; - } else { - return r3; - } - } - } else { - if (d1 < d2) { - if (d1 < d3) { - return r1; - } else { - return r3; - } - } else { - if (d2 < d3) { - return r2; - } else { - return r3; - } - } - } -} - - -Vector3 CollisionDetection::closestPointToRectangle( - const Vector3& v0, - const Vector3& v1, - const Vector3& v2, - const Vector3& v3, - const Vector3& point) { - - Plane plane(v0, v1, v2); - - // Project the point into the plane - double a, b, c, d; - plane.getEquation(a, b, c, d); - - double distance = a*point.x + b*point.y + c*point.z + d; - Vector3 planePoint = point - distance * plane.normal(); - - if (isPointInsideRectangle(v0, v1, v2, v3, plane.normal(), planePoint)) { - return planePoint; - } else { - return closestPointToRectanglePerimeter(v0, v1, v2, v3, planePoint); - } -} - - -bool CollisionDetection::fixedSolidSphereIntersectsFixedSolidSphere( - const Sphere& sphere1, - const Sphere& sphere2) { - - return (sphere1.center - sphere2.center).squaredMagnitude() < square(sphere1.radius + sphere2.radius); -} - - -bool CollisionDetection::fixedSolidSphereIntersectsFixedSolidBox( - const Sphere& sphere, - const Box& box) { - - // If the center of the sphere is within the box, the whole - // sphere is within the box. - if (box.contains(sphere.center)) { - return true; - } - - float r2 = square(sphere.radius); - - // Find the closest point on the surface of the box to the sphere. If - // this point is within the sphere's radius, they intersect. - int f; - for (f = 0; f < 6; ++f) { - Vector3 v0, v1, v2, v3; - box.getFaceCorners(f, v0, v1, v2, v3); - if ((closestPointToRectangle(v0, v1, v2, v3, sphere.center) - sphere.center).squaredMagnitude() <= r2) { - return true; - } - } - - return false; -} - - -bool CollisionDetection::movingSpherePassesThroughFixedBox( - const Sphere& sphere, - const Vector3& velocity, - const Box& box, - double timeLimit) { - - // If they intersect originally, they definitely pass through each other. - if (fixedSolidSphereIntersectsFixedSolidBox(sphere, box)) { - return true; - } - - // See if the sphere hits the box during the time period. - Vector3 dummy1, dummy2; - - return (collisionTimeForMovingSphereFixedBox(sphere, velocity, box, dummy1, dummy2) < timeLimit); -} - - -bool CollisionDetection::movingSpherePassesThroughFixedSphere( - const Sphere& sphere, - const Vector3& velocity, - const Sphere& fixedSphere, - double timeLimit) { - - if (fixedSolidSphereIntersectsFixedSolidSphere(sphere, fixedSphere)) { - return true; - } - - // Extend the fixed sphere by the radius of the moving sphere - Sphere bigFixed(fixedSphere.center, fixedSphere.radius + sphere.radius); - Vector3 dummy1, dummy2; - - // If the sphere collides with the other sphere during the time limit, it passes through - return (collisionTimeForMovingPointFixedSphere(sphere.center, velocity, bigFixed, dummy1, dummy2) < timeLimit); -} - - - -bool CollisionDetection::fixedSolidSphereIntersectsFixedTriangle( - const Sphere& sphere, - const Triangle& triangle) { - - // How far is the sphere from the plane of the triangle - const Plane& plane = triangle.plane(); - - // Does the closest point to the sphere center lie within the triangle? - Vector3 v = plane.closestPoint(sphere.center); - - // Is the closest point to the plane within the sphere? - if ((v - sphere.center).squaredLength() <= square(sphere.radius)) { - // Is it also within the triangle? - float b[3]; - if (isPointInsideTriangle(triangle.vertex(0), triangle.vertex(1), triangle.vertex(2), triangle.normal(), - v, b, triangle.primaryAxis())){ - // The closest point is inside the triangle - return true; - } - } - - // ignored - int edgeIndex; - - v = closestPointOnTrianglePerimeter(triangle._vertex, triangle.edgeDirection, triangle.edgeMagnitude, sphere.center, edgeIndex); - - // Is the closest point within the sphere? - return ((v - sphere.center).squaredLength() <= square(sphere.radius)); -} - - -//////////////////////////////////////////////////////////////////////////////// -// AABB-triangle overlap test code based on Tomas Akenine-Möller's -// http://www.cs.lth.se/home/Tomas_Akenine_Moller/code/tribox3.txt -// Ported 2008-12-28 - -#define X 0 -#define Y 1 -#define Z 2 - -#define FINDMINMAX(x0, x1, x2, min, max) \ - min = max = x0; \ - if(x1max) max=x1;\ - if(x2max) max=x2; - -static bool planeBoxOverlap(const Vector3& normal, const Vector3& vert, const Vector3& maxbox) { - Vector3 vmin, vmax; - float v; - - // for each axis - for(int a = 0; a < 3; ++a) { - v = vert[a]; - - if (normal[a] > 0.0f) { - vmin[a] = -maxbox[a] - v; - vmax[a] = maxbox[a] - v; - } else { - vmin[a] = maxbox[a] - v; - vmax[a] = -maxbox[a] - v; - } - } - - if (normal.dot(vmin) > 0.0f) { - return false; - } else if (normal.dot(vmax) >= 0.0f) { - return true; - } else { - return false; - } -} - -/*======================== X-tests ========================*/ - -#define AXISTEST_X01(a, b, fa, fb) \ - p0 = a*v0[Y] - b*v0[Z]; \ - p2 = a*v2[Y] - b*v2[Z]; \ - if(p0rad || max<-rad) return false; - - -#define AXISTEST_X2(a, b, fa, fb) \ - p0 = a*v0[Y] - b*v0[Z]; \ - p1 = a*v1[Y] - b*v1[Z]; \ - if(p0rad || max<-rad) return false; - -/*======================== Y-tests ========================*/ - -#define AXISTEST_Y02(a, b, fa, fb) \ - p0 = -a*v0[X] + b*v0[Z]; \ - p2 = -a*v2[X] + b*v2[Z]; \ - if(p0rad || max<-rad) return false; - -#define AXISTEST_Y1(a, b, fa, fb) \ - p0 = -a*v0[X] + b*v0[Z]; \ - p1 = -a*v1[X] + b*v1[Z]; \ - if(p0rad || max<-rad) return false; - -/*======================== Z-tests ========================*/ - -#define AXISTEST_Z12(a, b, fa, fb) \ - p1 = a*v1[X] - b*v1[Y]; \ - p2 = a*v2[X] - b*v2[Y]; \ - if(p2rad || max<-rad) return false; - -#define AXISTEST_Z0(a, b, fa, fb) \ - p0 = a*v0[X] - b*v0[Y]; \ - p1 = a*v1[X] - b*v1[Y]; \ - if(p0rad || max<-rad) return false; - -bool CollisionDetection::fixedSolidBoxIntersectsFixedTriangle( - const AABox& box, const Triangle& tri) { - - // use separating axis theorem to test overlap between triangle and box - // need to test for overlap in these directions: - // 1) the {x,y,z}-directions (actually, since we use the AABB of the triangle - // we do not even need to test these) - // 2) normal of the triangle - // 3) crossproduct(edge from tri, {x,y,z}-direction) - // this gives 3x3=9 more tests - - // This is the fastest branch (on Sun). - // Move the triangle to the object space of the box - // Triangle vertices in box object space - - const Vector3& boxcenter = box.center(); - const Vector3& boxhalfsize = box.extent() * 0.5f; - - const Vector3& v0 = tri.vertex(0) - boxcenter; - const Vector3& v1 = tri.vertex(1) - boxcenter; - const Vector3& v2 = tri.vertex(2) - boxcenter; - - // Compute triangle edges in object space - const Vector3& e0 = v1 - v0; - const Vector3& e1 = v2 - v1; - const Vector3& e2 = v0 - v2; - - // Bullet 3: - // test the 9 tests first (this was faster) - float min,max,p0,p1,p2,rad; - Vector3 fe; - - fe = abs(e0); - AXISTEST_X01(e0[Z], e0[Y], fe[Z], fe[Y]); - AXISTEST_Y02(e0[Z], e0[X], fe[Z], fe[X]); - AXISTEST_Z12(e0[Y], e0[X], fe[Y], fe[X]); - - fe = abs(e1); - AXISTEST_X01(e1[Z], e1[Y], fe[Z], fe[Y]); - AXISTEST_Y02(e1[Z], e1[X], fe[Z], fe[X]); - AXISTEST_Z0 (e1[Y], e1[X], fe[Y], fe[X]); - - fe = abs(e2); - AXISTEST_X2 (e2[Z], e2[Y], fe[Z], fe[Y]); - AXISTEST_Y1 (e2[Z], e2[X], fe[Z], fe[X]); - AXISTEST_Z12(e2[Y], e2[X], fe[Y], fe[X]); - - // Bullet 1: - // first test overlap in the {x,y,z}-directions - // find min, max of the triangle each direction, and test for overlap in - // that direction -- this is equivalent to testing a minimal AABB around - // the triangle against the AABB - - // test in X-direction - FINDMINMAX(v0[X],v1[X],v2[X],min,max); - if (min > boxhalfsize[X] || max < -boxhalfsize[X]) { - return false; - } - - // test in Y-direction - FINDMINMAX(v0[Y],v1[Y],v2[Y],min,max); - if (min > boxhalfsize[Y] || max < -boxhalfsize[Y]) { - return false; - } - - // test in Z-direction - FINDMINMAX(v0[Z],v1[Z],v2[Z],min,max); - if (min > boxhalfsize[Z] || max < -boxhalfsize[Z]) { - return false; - } - - // Bullet 2: - // test if the box intersects the plane of the triangle - // compute plane equation of triangle: normal*x+d=0 - - if (! planeBoxOverlap(tri.normal(), v0, boxhalfsize)) { - return false; - } - - // box and triangle overlap - return true; -} -#undef X -#undef Y -#undef Z - -//////////////////////////////////////////////////////////////////////////////// - - -} // namespace - -#ifdef _MSC_VER -// Turn off fast floating-point optimizations -#pragma float_control( pop ) -#pragma warning (pop) -#endif diff --git a/externals/g3dlite/CoordinateFrame.cpp b/externals/g3dlite/CoordinateFrame.cpp deleted file mode 100644 index 9b639b62082..00000000000 --- a/externals/g3dlite/CoordinateFrame.cpp +++ /dev/null @@ -1,436 +0,0 @@ -/** - @file CoordinateFrame.cpp - - Coordinate frame class - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2001-06-02 - @edited 2009-11-13 - - Copyright 2000-2010, Morgan McGuire. - All rights reserved. -*/ - -#include "G3D/platform.h" -#include "G3D/CoordinateFrame.h" -#include "G3D/Quat.h" -#include "G3D/Matrix4.h" -#include "G3D/Box.h" -#include "G3D/AABox.h" -#include "G3D/Sphere.h" -#include "G3D/Triangle.h" -#include "G3D/Ray.h" -#include "G3D/Capsule.h" -#include "G3D/Cylinder.h" -#include "G3D/UprightFrame.h" -#include "G3D/Any.h" -#include "G3D/stringutils.h" - -namespace G3D { - -CoordinateFrame::CoordinateFrame(const Any& any) { - any.verifyName("CFrame"); - if (toUpper(any.name()) == "CFRAME") { - any.verifyType(Any::TABLE, Any::ARRAY); - if (any.type() == Any::TABLE) { - rotation = any["rotation"]; - translation = any["translation"]; - } else { - any.verifySize(2); - rotation = any[0]; - translation = any[1]; - } - } else { - any.verifyName("CFrame::fromXYZYPRDegrees"); - any.verifyType(Any::ARRAY); - any.verifySize(3, 6); - - int s = any.size(); - - *this = fromXYZYPRDegrees(any[0], any[1], any[2], - (s > 3) ? any[3].number() : 0.0f, - (s > 4) ? any[4].number() : 0.0f, - (s > 5) ? any[5].number() : 0.0f); - } -} - - -CoordinateFrame::operator Any() const { - float x, y, z, yaw, pitch, roll; - getXYZYPRDegrees(x, y, z, yaw, pitch, roll); - Any a(Any::ARRAY, "CFrame::fromXYZYPRDegrees"); - a.append(x, y, z, yaw); - if ( ! G3D::fuzzyEq(yaw, 0.0f) || ! G3D::fuzzyEq(pitch, 0.0f) || ! G3D::fuzzyEq(roll, 0.0f)) { - a.append(yaw); - if (! G3D::fuzzyEq(pitch, 0.0f) || ! G3D::fuzzyEq(roll, 0.0f)) { - a.append(pitch); - if (! G3D::fuzzyEq(roll, 0.0f)) { - a.append(roll); - } - } - } - return a; -} - - -CoordinateFrame::CoordinateFrame(const class UprightFrame& f) { - *this = f.toCoordinateFrame(); -} - - -CoordinateFrame::CoordinateFrame() : - rotation(Matrix3::identity()), translation(Vector3::zero()) { -} - -CoordinateFrame CoordinateFrame::fromXYZYPRRadians(float x, float y, float z, float yaw, - float pitch, float roll) { - Matrix3 rotation = Matrix3::fromAxisAngle(Vector3::unitY(), yaw); - - rotation = Matrix3::fromAxisAngle(rotation.column(0), pitch) * rotation; - rotation = Matrix3::fromAxisAngle(rotation.column(2), roll) * rotation; - - const Vector3 translation(x, y, z); - - return CoordinateFrame(rotation, translation); -} - - -void CoordinateFrame::getXYZYPRRadians(float& x, float& y, float& z, - float& yaw, float& pitch, float& roll) const { - x = translation.x; - y = translation.y; - z = translation.z; - - const Vector3& look = lookVector(); - - if (abs(look.y) > 0.99f) { - // Looking nearly straight up or down - - yaw = G3D::pi() + atan2(look.x, look.z); - pitch = asin(look.y); - roll = 0.0f; - - } else { - - // Yaw cannot be affected by others, so pull it first - yaw = G3D::pi() + atan2(look.x, look.z); - - // Pitch is the elevation of the yaw vector - pitch = asin(look.y); - - Vector3 actualRight = rightVector(); - Vector3 expectedRight = look.cross(Vector3::unitY()); - - roll = 0;//acos(actualRight.dot(expectedRight)); TODO - } -} - - -void CoordinateFrame::getXYZYPRDegrees(float& x, float& y, float& z, - float& yaw, float& pitch, float& roll) const { - getXYZYPRRadians(x, y, z, yaw, pitch, roll); - yaw = toDegrees(yaw); - pitch = toDegrees(pitch); - roll = toDegrees(roll); -} - - -CoordinateFrame CoordinateFrame::fromXYZYPRDegrees(float x, float y, float z, - float yaw, float pitch, float roll) { - return fromXYZYPRRadians(x, y, z, toRadians(yaw), toRadians(pitch), toRadians(roll)); -} - - -Ray CoordinateFrame::lookRay() const { - return Ray::fromOriginAndDirection(translation, lookVector()); -} - - -bool CoordinateFrame::fuzzyEq(const CoordinateFrame& other) const { - - for (int c = 0; c < 3; ++c) { - for (int r = 0; r < 3; ++r) { - if (! G3D::fuzzyEq(other.rotation[r][c], rotation[r][c])) { - return false; - } - } - if (! G3D::fuzzyEq(translation[c], other.translation[c])) { - return false; - } - } - - return true; -} - - -bool CoordinateFrame::fuzzyIsIdentity() const { - const Matrix3& I = Matrix3::identity(); - - for (int c = 0; c < 3; ++c) { - for (int r = 0; r < 3; ++r) { - if (fuzzyNe(I[r][c], rotation[r][c])) { - return false; - } - } - if (fuzzyNe(translation[c], 0)) { - return false; - } - } - - return true; -} - - -bool CoordinateFrame::isIdentity() const { - return - (translation == Vector3::zero()) && - (rotation == Matrix3::identity()); -} - - -Matrix4 CoordinateFrame::toMatrix4() const { - return Matrix4(*this); -} - - -std::string CoordinateFrame::toXML() const { - return G3D::format( - "\n %lf,%lf,%lf,%lf,\n %lf,%lf,%lf,%lf,\n %lf,%lf,%lf,%lf,\n %lf,%lf,%lf,%lf\n\n", - rotation[0][0], rotation[0][1], rotation[0][2], translation.x, - rotation[1][0], rotation[1][1], rotation[1][2], translation.y, - rotation[2][0], rotation[2][1], rotation[2][2], translation.z, - 0.0, 0.0, 0.0, 1.0); -} - - -Plane CoordinateFrame::toObjectSpace(const Plane& p) const { - Vector3 N, P; - double d; - p.getEquation(N, d); - P = N * (float)d; - P = pointToObjectSpace(P); - N = normalToObjectSpace(N); - return Plane(N, P); -} - - -Plane CoordinateFrame::toWorldSpace(const Plane& p) const { - Vector3 N, P; - double d; - p.getEquation(N, d); - P = N * (float)d; - P = pointToWorldSpace(P); - N = normalToWorldSpace(N); - return Plane(N, P); -} - - -Triangle CoordinateFrame::toObjectSpace(const Triangle& t) const { - return Triangle(pointToObjectSpace(t.vertex(0)), - pointToObjectSpace(t.vertex(1)), - pointToObjectSpace(t.vertex(2))); -} - - -Triangle CoordinateFrame::toWorldSpace(const Triangle& t) const { - return Triangle(pointToWorldSpace(t.vertex(0)), - pointToWorldSpace(t.vertex(1)), - pointToWorldSpace(t.vertex(2))); -} - - -Cylinder CoordinateFrame::toWorldSpace(const Cylinder& c) const { - return Cylinder( - pointToWorldSpace(c.point(0)), - pointToWorldSpace(c.point(1)), - c.radius()); -} - - -Capsule CoordinateFrame::toWorldSpace(const Capsule& c) const { - return Capsule( - pointToWorldSpace(c.point(0)), - pointToWorldSpace(c.point(1)), - c.radius()); -} - - -Box CoordinateFrame::toWorldSpace(const AABox& b) const { - Box b2(b); - return toWorldSpace(b2); -} - - -Box CoordinateFrame::toWorldSpace(const Box& b) const { - Box out(b); - - for (int i = 0; i < 8; ++i) { - out._corner[i] = pointToWorldSpace(b._corner[i]); - debugAssert(! isNaN(out._corner[i].x)); - } - - for (int i = 0; i < 3; ++i) { - out._axis[i] = vectorToWorldSpace(b._axis[i]); - } - - out._center = pointToWorldSpace(b._center); - - return out; -} - - -Box CoordinateFrame::toObjectSpace(const Box &b) const { - return inverse().toWorldSpace(b); -} - - -Box CoordinateFrame::toObjectSpace(const AABox& b) const { - return toObjectSpace(Box(b)); -} - - -CoordinateFrame::CoordinateFrame(class BinaryInput& b) : rotation(Matrix3::zero()) { - deserialize(b); -} - - -void CoordinateFrame::deserialize(class BinaryInput& b) { - rotation.deserialize(b); - translation.deserialize(b); -} - - -void CoordinateFrame::serialize(class BinaryOutput& b) const { - rotation.serialize(b); - translation.serialize(b); -} - - -Sphere CoordinateFrame::toWorldSpace(const Sphere &b) const { - return Sphere(pointToWorldSpace(b.center), b.radius); -} - - -Sphere CoordinateFrame::toObjectSpace(const Sphere &b) const { - return Sphere(pointToObjectSpace(b.center), b.radius); -} - - -Ray CoordinateFrame::toWorldSpace(const Ray& r) const { - return Ray::fromOriginAndDirection(pointToWorldSpace(r.origin()), vectorToWorldSpace(r.direction())); -} - - -Ray CoordinateFrame::toObjectSpace(const Ray& r) const { - return Ray::fromOriginAndDirection(pointToObjectSpace(r.origin()), vectorToObjectSpace(r.direction())); -} - - -void CoordinateFrame::lookAt(const Vector3 &target) { - lookAt(target, Vector3::unitY()); -} - - -void CoordinateFrame::lookAt( - const Vector3& target, - Vector3 up) { - - up = up.direction(); - - Vector3 look = (target - translation).direction(); - if (fabs(look.dot(up)) > .99f) { - up = Vector3::unitX(); - if (fabs(look.dot(up)) > .99f) { - up = Vector3::unitY(); - } - } - - up -= look * look.dot(up); - up.unitize(); - - Vector3 z = -look; - Vector3 x = -z.cross(up); - x.unitize(); - - Vector3 y = z.cross(x); - - rotation.setColumn(0, x); - rotation.setColumn(1, y); - rotation.setColumn(2, z); -} - - -CoordinateFrame CoordinateFrame::lerp( - const CoordinateFrame& other, - float alpha) const { - - if (alpha == 1.0f) { - return other; - } else if (alpha == 0.0f) { - return *this; - } else { - Quat q1 = Quat(this->rotation); - Quat q2 = Quat(other.rotation); - - return CoordinateFrame( - q1.slerp(q2, alpha).toRotationMatrix(), - this->translation * (1 - alpha) + other.translation * alpha); - } -} - - -void CoordinateFrame::pointToWorldSpace(const Array& v, Array& vout) const { - vout.resize(v.size()); - - for (int i = v.size() - 1; i >= 0; --i) { - vout[i] = pointToWorldSpace(v[i]); - } -} - - -void CoordinateFrame::normalToWorldSpace(const Array& v, Array& vout) const { - vout.resize(v.size()); - - for (int i = v.size() - 1; i >= 0; --i) { - vout[i] = normalToWorldSpace(v[i]); - } -} - - -void CoordinateFrame::vectorToWorldSpace(const Array& v, Array& vout) const { - vout.resize(v.size()); - - for (int i = v.size() - 1; i >= 0; --i) { - vout[i] = vectorToWorldSpace(v[i]); - } -} - - -void CoordinateFrame::pointToObjectSpace(const Array& v, Array& vout) const { - vout.resize(v.size()); - - for (int i = v.size() - 1; i >= 0; --i) { - vout[i] = pointToObjectSpace(v[i]); - } -} - - -void CoordinateFrame::normalToObjectSpace(const Array& v, Array& vout) const { - vout.resize(v.size()); - - for (int i = v.size() - 1; i >= 0; --i) { - vout[i] = normalToObjectSpace(v[i]); - } -} - - -void CoordinateFrame::vectorToObjectSpace(const Array& v, Array& vout) const { - vout.resize(v.size()); - - for (int i = v.size() - 1; i >= 0; --i) { - vout[i] = vectorToObjectSpace(v[i]); - } -} - -} // namespace diff --git a/externals/g3dlite/Crypto.cpp b/externals/g3dlite/Crypto.cpp deleted file mode 100644 index c69b23375ce..00000000000 --- a/externals/g3dlite/Crypto.cpp +++ /dev/null @@ -1,70 +0,0 @@ -/** - @file Crypto.cpp - - @author Morgan McGuire, http://graphics.cs.williams.edu - - - @created 2006-03-28 - @edited 2006-04-06 - */ - -#include "G3D/platform.h" -#include "G3D/Crypto.h" -#include "G3D/g3dmath.h" -#include - -namespace G3D { - - -int Crypto::smallPrime(int n) { - debugAssert(n < numSmallPrimes() && n >= 0); - - // From: - // http://primes.utm.edu/lists/small/1000.txt - - static const int table[] = { - 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, - 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, - 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, - 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, - 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, - 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, - 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, - 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, - 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, - 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, - 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, - 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, - 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, - 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, - 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, - 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, - 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, - 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, - 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, - 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, - 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, - 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, - 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, - 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, - 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, - 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, - 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, - 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, - 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, - 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, - 1993, 1997, 1999}; - - return table[n]; -} - - -int Crypto::numSmallPrimes() { - return 303; -} - -uint32 Crypto::crc32(const void* byte, size_t numBytes) { - return ::crc32(::crc32(0, Z_NULL, 0), static_cast(byte), numBytes); -} - -} // G3D diff --git a/externals/g3dlite/Cylinder.cpp b/externals/g3dlite/Cylinder.cpp deleted file mode 100644 index 7a7b9f9440d..00000000000 --- a/externals/g3dlite/Cylinder.cpp +++ /dev/null @@ -1,176 +0,0 @@ -/** - @file Cylinder.cpp - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2003-02-07 - @edited 2006-02-18 - - Copyright 2000-2006, Morgan McGuire. - All rights reserved. - */ - -#include "G3D/platform.h" -#include "G3D/Cylinder.h" -#include "G3D/BinaryInput.h" -#include "G3D/BinaryOutput.h" -#include "G3D/LineSegment.h" -#include "G3D/CoordinateFrame.h" -#include "G3D/Line.h" -#include "G3D/AABox.h" - -namespace G3D { - -Cylinder::Cylinder(class BinaryInput& b) { - deserialize(b); -} - - -Cylinder::Cylinder() { -} - - -Cylinder::Cylinder(const Vector3& _p1, const Vector3& _p2, float _r) - : p1(_p1), p2(_p2), mRadius(_r) { -} - - -void Cylinder::serialize(class BinaryOutput& b) const { - p1.serialize(b); - p2.serialize(b); - b.writeFloat64(mRadius); -} - - -void Cylinder::deserialize(class BinaryInput& b) { - p1.deserialize(b); - p2.deserialize(b); - mRadius = b.readFloat64(); -} - - -Line Cylinder::axis() const { - return Line::fromTwoPoints(p1, p2); -} - - - -float Cylinder::radius() const { - return mRadius; -} - - -float Cylinder::volume() const { - return - (float)pi() * square(mRadius) * (p1 - p2).magnitude(); -} - - -float Cylinder::area() const { - return - // Sides - (twoPi() * mRadius) * height() + - - // Caps - twoPi() * square(mRadius); -} - -void Cylinder::getBounds(AABox& out) const { - Vector3 min = p1.min(p2) - (Vector3(1, 1, 1) * mRadius); - Vector3 max = p1.max(p2) + (Vector3(1, 1, 1) * mRadius); - out = AABox(min, max); -} - -bool Cylinder::contains(const Vector3& p) const { - return LineSegment::fromTwoPoints(p1, p2).distanceSquared(p) <= square(mRadius); -} - - -void Cylinder::getReferenceFrame(CoordinateFrame& cframe) const { - cframe.translation = center(); - - Vector3 Y = (p1 - p2).direction(); - Vector3 X = (abs(Y.dot(Vector3::unitX())) > 0.9) ? Vector3::unitY() : Vector3::unitX(); - Vector3 Z = X.cross(Y).direction(); - X = Y.cross(Z); - cframe.rotation.setColumn(0, X); - cframe.rotation.setColumn(1, Y); - cframe.rotation.setColumn(2, Z); -} - - -void Cylinder::getRandomSurfacePoint(Vector3& p, Vector3& N) const { - float h = height(); - float r = radius(); - - // Create a random point on a standard cylinder and then rotate to the global frame. - - // Relative areas (factor of 2PI already taken out) - float capRelArea = square(r) / 2.0f; - float sideRelArea = r * h; - - float r1 = uniformRandom(0, capRelArea * 2 + sideRelArea); - - if (r1 < capRelArea * 2) { - - // Select a point uniformly at random on a disk - // @cite http://mathworld.wolfram.com/DiskPointPicking.html - float a = uniformRandom(0, (float)twoPi()); - float r2 = sqrt(uniformRandom(0, 1)) * r; - p.x = cos(a) * r2; - p.z = sin(a) * r2; - - N.x = 0; - N.z = 0; - if (r1 < capRelArea) { - // Top - p.y = h / 2.0f; - N.y = 1; - } else { - // Bottom - p.y = -h / 2.0f; - N.y = -1; - } - } else { - // Side - float a = uniformRandom(0, (float)twoPi()); - N.x = cos(a); - N.y = 0; - N.z = sin(a); - p.x = N.x * r; - p.z = N.y * r; - p.y = uniformRandom(-h / 2.0f, h / 2.0f); - } - - // Transform to world space - CoordinateFrame cframe; - getReferenceFrame(cframe); - - p = cframe.pointToWorldSpace(p); - N = cframe.normalToWorldSpace(N); -} - - -Vector3 Cylinder::randomInteriorPoint() const { - float h = height(); - float r = radius(); - - // Create a random point in a standard cylinder and then rotate to the global frame. - - // Select a point uniformly at random on a disk - // @cite http://mathworld.wolfram.com/DiskPointPicking.html - float a = uniformRandom(0, (float)twoPi()); - float r2 = sqrt(uniformRandom(0, 1)) * r; - - Vector3 p( cos(a) * r2, - uniformRandom(-h / 2.0f, h / 2.0f), - sin(a) * r2); - - // Transform to world space - CoordinateFrame cframe; - getReferenceFrame(cframe); - - return cframe.pointToWorldSpace(p); -} - -} // namespace diff --git a/externals/g3dlite/G3D/AABox.h b/externals/g3dlite/G3D/AABox.h deleted file mode 100644 index 2e8da1f6098..00000000000 --- a/externals/g3dlite/G3D/AABox.h +++ /dev/null @@ -1,272 +0,0 @@ -/** - @file AABox.h - - Axis-aligned box class - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2004-01-10 - @edited 2009-02-10 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_AABOX_H -#define G3D_AABOX_H - -#include "G3D/platform.h" -#include "G3D/Vector3.h" -#include "G3D/debug.h" -#include "G3D/Array.h" -#include "G3D/Plane.h" - -namespace G3D { - -/** - An axis-aligned box. - */ -class AABox { -private: - friend class Intersect; - - /** Optional argument placeholder */ - static int dummy; - - Vector3 lo; - Vector3 hi; - -public: - - /** Does not initialize the fields */ - inline AABox() {} - - /** - Constructs a zero-area AABox at v. - */ - inline explicit AABox(const Vector3& v) { - lo = hi = v; - } - - /** Assumes that low is less than or equal to high along each dimension. - To have this automatically enforced, use - AABox(low.min(high), low.max(high)); - */ - inline AABox(const Vector3& low, const Vector3& high) { - set(low, high); - } - - /** Assumes that low is less than or equal to high along each dimension. - */ - inline void set(const Vector3& low, const Vector3& high) { - debugAssert( - (low.x <= high.x) && - (low.y <= high.y) && - (low.z <= high.z)); - lo = low; - hi = high; - } - - /** - Grows to include the bounds of a - */ - inline void merge(const AABox& a) { - lo = lo.min(a.lo); - hi = hi.max(a.hi); - } - - inline void merge(const Vector3& a) { - lo = lo.min(a); - hi = hi.max(a); - } - - void serialize(class BinaryOutput& b) const; - - void deserialize(class BinaryInput& b); - - inline bool isFinite() const { - return lo.isFinite() && hi.isFinite(); - } - - inline const Vector3& low() const { - return lo; - } - - inline const Vector3& high() const { - return hi; - } - - /** - The largest possible finite box. - */ - static const AABox& maxFinite(); - - /** A large finite box. This is smaller than FLT_MAX - because it leaves room to add boxes together. */ - static const AABox& large(); - - static const AABox& inf(); - - static const AABox& zero(); - - /** - Returns the centroid of the box. - */ - inline Vector3 center() const { - return (lo + hi) * 0.5; - } - - Vector3 corner(int index) const; - - /** - Distance from corner(0) to the next corner along axis a. - */ - inline float extent(int a) const { - debugAssert(a < 3); - return hi[a] - lo[a]; - } - - - inline Vector3 extent() const { - return hi - lo; - } - - - /** - Splits the box into two AABoxes along the specified axis. low contains - the part that was closer to negative infinity along axis, high contains - the other part. Either may have zero volume. - */ - void split(const Vector3::Axis& axis, float location, AABox& low, AABox& high) const; - - /** - Conservative culling test for up to 32 planes. - Returns true if there exists a plane[p] for - which the entire object is in the negative half space - (opposite the plane normal). - - testMask and childMask - are used for optimizing bounding volume hierarchies. - The version of this method that produces childMask - is slower than the version without; it should only - be used for parent nodes. - - @param cullingPlaneIndex The index of the first plane for which - the entire object is in the negative half-space. The function - exits early when one plane is found. -1 when the function - returns false (i.e. when no plane culls the whole object). - - @param testMask If bit p is 0, the - bounding volume automatically passes the culling test for - plane[p] (i.e. it is known that the volume - is entirely within the positive half space). The function - must return false if testMask is 0 and test all planes - when testMask is -1 (0xFFFFFFFF). - - @param childMask Test mask for the children of this volume. - - */ - bool culledBy( - const Array& plane, - int32& cullingPlaneIndex, - const uint32 testMask, - uint32& childMask) const; - - /** - Conservative culling test that does not produce a mask for children. - */ - bool culledBy( - const Array& plane, - int32& cullingPlaneIndex = dummy, - const uint32 testMask = 0xFFFFFFFF) const; - - /** less than or equal to containment */ - inline bool contains(const AABox& other) const { - return - (other.hi.x <= hi.x) && - (other.hi.y <= hi.y) && - (other.hi.z <= hi.z) && - (other.lo.x >= lo.x) && - (other.lo.y >= lo.y) && - (other.lo.z >= lo.z); - } - - inline bool contains( - const Vector3& point) const { - return - (point.x >= lo.x) && - (point.y >= lo.y) && - (point.z >= lo.z) && - (point.x <= hi.x) && - (point.y <= hi.y) && - (point.z <= hi.z); - } - - inline float area() const { - Vector3 diag = hi - lo; - return 2.0f * (diag.x * diag.y + diag.y * diag.z + diag.x * diag.z); - } - - inline float volume() const { - Vector3 diag = hi - lo; - return diag.x * diag.y * diag.z; - } - - Vector3 randomInteriorPoint() const; - - Vector3 randomSurfacePoint() const; - - /** Returns true if there is any overlap */ - bool intersects(const AABox& other) const; - - /** Returns true if there is any overlap. - @cite Jim Arvo's algorithm from Graphics Gems II*/ - bool intersects(const class Sphere& other) const; - - /** Return the intersection of the two boxes */ - AABox intersect(const AABox& other) const { - Vector3 H = hi.min(other.hi); - Vector3 L = lo.max(other.lo).min(H); - return AABox(L, H); - } - - inline size_t hashCode() const { - return lo.hashCode() + hi.hashCode(); - } - - inline bool operator==(const AABox& b) const { - return (lo == b.lo) && (hi == b.hi); - } - - inline bool operator!=(const AABox& b) const { - return !((lo == b.lo) && (hi == b.hi)); - } - - inline AABox operator+(const Vector3& v) const { - AABox out; - out.lo = lo + v; - out.hi = hi + v; - return out; - } - - inline AABox operator-(const Vector3& v) const { - AABox out; - out.lo = lo - v; - out.hi = hi - v; - return out; - } - - void getBounds(AABox& out) const { - out = *this; - } -}; - -} - -template <> struct HashTrait { - static size_t hashCode(const G3D::AABox& key) { return key.hashCode(); } -}; - - - -#endif diff --git a/externals/g3dlite/G3D/Any.h b/externals/g3dlite/G3D/Any.h deleted file mode 100644 index 49701202ca9..00000000000 --- a/externals/g3dlite/G3D/Any.h +++ /dev/null @@ -1,570 +0,0 @@ -/** - @file Any.h - - @author Morgan McGuire, Shawn Yarbrough, and Corey Taylor - @maintainer Morgan McGuire - - @created 2006-06-11 - @edited 2009-12-16 - - Copyright 2000-2010, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_Any_h -#define G3D_Any_h - -#include "G3D/platform.h" -#include "G3D/Table.h" -#include "G3D/Array.h" -#include "G3D/AtomicInt32.h" -#include - -// needed for Token -#include "G3D/TextInput.h" - -#ifdef verify -#undef verify -#endif - -namespace G3D { - -class TextOutput; - -/** -\brief Easy loading and saving of human-readable configuration files. - -Encodes typed, structured data and can serialize it to a human -readable format that is very similar to the Python language's data -syntax. Well-suited for quickly creating human-readable file formats, -especially since deserialization and serialization preserve comments and -an Any can tell you what file and line it came from. - -The class is designed so that copying Anys generally is fast, even if -it is a large array or table. This is because data is shared between -copies until it is mutated, at which point an actual copy occurs. - -\section Example -Sample File: -
-{
-   shape = "round",
-
-   # in meters
-   radius = 3.7,
-
-   position = Vector3(1.0, -1.0, 0.0),
-   texture = { format = "RGB8", size = (320, 200)}
-}
-
- -Sample code using: -
-Any x;
-x.load("ball.txt");
-if (x["shape"].string() == "round") {
-    x["density"] = 3;
-}
-x.save("ball.txt");
-
- -The custom serialization format was chosen to be terse, easy for -humans to read, and easy for machines to parse. It was specifically -chosen over formats like XML, YAML, JSON, S-expressions, and Protocol -Buffers, although there is no reason you could not write readers and -writers for G3D::Any that support those. - -G3D::Any assumes that structures do not contain cycles; it is an -error to create a structure like: - -
-Any x(Any::ARRAY);
-x.array().append(x);    // don't do this!
-
- -although no exception will be thrown at runtime during that append. - - -\section Parsing - -The primary use of Any is to create your own text file formats. -The Vector3 constructor is a good example of how to use the Any::verify -methods to provide good error checking while parsing such formats: - -
-Vector3::Vector3(const Any& any) {
-    any.verifyName("Vector3");
-    any.verifyType(Any::TABLE, Any::ARRAY);
-    any.verifySize(3);
-
-    if (any.type() == Any::ARRAY) {
-        x = any[0];
-        y = any[1];
-        z = any[2];
-    } else {
-        // Table
-        x = any["x"];
-        y = any["y"];
-        z = any["z"];
-    }
-}
-
- -\section BNF -Serialized format BNF: - -
-identifier  ::= (letter | "_") (letter | digit | "_")*
-identifier-op ::= "::" | "->" | "."
-
-identifier-exp ::= [identifier-op] identifier (identifier-op identifier)*
-
-comment     ::= "#"  "\n"
-separator   ::= "," | ";"
-
-number      ::= 
-string      ::= 
-boolean     ::= "True" | "False"
-none        ::= "None"
-array       ::= "(" [value ("," value)*] ")"
-pair        ::= (identifier | string) "=" value
-table       ::= "{" [pair (separator pair)*] "}"
-named-array ::= identifier-exp tuple
-named-table ::= identifier-exp dict
-
-value       ::= [comment] (none | number | boolean | string | array | table | named-array | named-table)
-
- -Except for single-line comments, whitespace is not significant. -All parsing is case-insensitive. - -The deserializer allows the substitution of [] for () when writing -tuples and ";" for ",". - -The serializer indents four spaces for each level of nesting. -Tables are written with the keys in alphabetic order. -*/ -class Any { -public: - - enum Type {NONE, BOOLEAN, NUMBER, STRING, ARRAY, TABLE}; - - static std::string toString(Type t); - - /** Where an Any came from in a file. Useful for throwing parsing errors */ - class Source { - public: - std::string filename; - int line; - int character; - - Source() : line(0), character(0) {} - - void set(const TextInput& ti, const Token& t) { - filename = ti.filename(); - line = t.line(); - character = t.character(); - } - }; - - typedef Array AnyArray; - typedef Table AnyTable; - -private: - - /** Called from deserialize() */ - static void deserializeComment(TextInput& ti, Token& token, std::string& comment); - - /** NONE, BOOLEAN, and NUMBER are stored directly in the Any */ - union SimpleValue { - bool b; - double n; - - inline SimpleValue() : n(0.0) {} - inline SimpleValue(bool x) : b(x) {} - inline SimpleValue(double x) : n(x) {} - }; - - class Data { - public: - /** ARRAY, TABLE, or STRING value only. NULL otherwise. */ - union Value { - std::string* s; - Array* a; - AnyTable* t; - inline Value() : s(NULL) {} - }; - - // Needed so that the destructor knows what is in Value - // and can call its destructor. - Type type; - - /** Always points to memory that is allocated with the Data, so - the destructor does not delete this. */ - Value value; - - std::string comment; - - std::string name; - - /** For STRING, ARRAY and TABLE types, m_value is shared between - multiple instances. Mutation is allowed only if the reference - count is exactly 1, otherwise the mutating instance must copy - the value. This is not used for other types. - */ - AtomicInt32 referenceCount; - - Source source; - - private: - - /** Called by create() */ - inline Data(Type t) : type(t), referenceCount(1) {} - - /** Called by destroy */ - ~Data(); - - public: - - /** Clones the argument */ - static Data* create(const Data* d); - static Data* create(Type t); - - /** Free d, invoking its destructor and freeing the memory for - the value. */ - static void destroy(Data* d); - - }; - - /** If not empty, this Any was created from operator[] on a table - and perhaps was not intended to exist. The name is needed to - format the error message if it is read from before it is - written to. - - The source of a placeholder object is that of the parent - object until it is written. - */ - std::string m_placeholderName; - - Type m_type; - SimpleValue m_simpleValue; - mutable Data* m_data; - - /** Called before every read operation to ensure that this object - is not a placeholder. */ - void beforeRead() const; - - /** Called before every write operation to wipe the placeholder - status. */ - void beforeWrite(); - - /** Decrements the reference count (if there is one). If the - reference count is zero after decrement, calls delete on @a m_data - and sets it to NULL. - */ - void dropReference(); - - /** Allocate the Data object if it does not exist */ - void ensureData(); - - /** If m_data is not NULL, ensure that it has a unique reference - and contains a valid m_data. This has a race condition if two - threads are both trying to modify the same Any - simultaneously.*/ - void ensureMutable(); - - /** Read an unnamed a TABLE or ARRAY. Token should be the open - paren token; it is the next token after the close on - return. Called from deserialize().*/ - void deserializeBody(TextInput& ti, Token& token); - - void deserialize(TextInput& ti, Token& token); - - /** Read the name of a named Array or Table. */ - static void deserializeName(TextInput& ti, Token& token, std::string& name); - - /** Read until a comma is consumed or a close paren is hit, and - return that token. Considers the passed in token to be the first - value read. */ - static void readUntilCommaOrClose(TextInput& ti, Token& token); - - /** Construct an Any that is a proxy for a table fetch from \a data. - This proxy can be copied exactly once on return from operator[].*/ - Any(const std::string& key, Data* data); - - inline bool isPlaceholder() const { - return ! m_placeholderName.empty(); - } - -public: - - /** Base class for all Any exceptions.*/ - class Exception { - public: - virtual ~Exception() {} - }; - - /** Thrown by operator[] when a key is not present in a const table. */ - class KeyNotFound : public ParseError { - public: - std::string key; - }; - - /** Thrown by operator[] when an array index is not present. */ - class IndexOutOfBounds : public Exception { - public: - int index; - int size; - inline IndexOutOfBounds() : index(0), size(0) {} - inline IndexOutOfBounds(int i, int s) : index(i), size(s) {} - }; - - /** NONE constructor */ - Any(); - - /** Deserialize */ - explicit Any(TextInput& t); - - Any(const Any& x); - - /** NUMBER constructor */ - Any(double x); - -#ifdef G3D_32BIT - /** NUMBER constructor */ - Any(int64 x); -#endif // G3D_32BIT - -#if 0 - /** NUMBER constructor */ - Any(int32 x); -#endif // 0 - - /** NUMBER constructor */ - Any(long x); - - /** NUMBER constructor */ - Any(int x); - - /** NUMBER constructor */ - Any(short x); - - /** BOOLEAN constructor */ - Any(bool x); - - /** STRING constructor */ - Any(const std::string& x); - - /** STRING constructor */ - Any(const char* x); - - /** \a t must be ARRAY or TABLE */ - Any(Type t, const std::string& name = ""); - - ~Any(); - - /** Removes the comment and name */ - Any& operator=(const Any& x); - - /** Removes the comment and name */ - Any& operator=(double x); - - /** Removes the comment and name */ - Any& operator=(int x); - - /** Removes the comment and name */ - Any& operator=(bool x); - - /** Removes the comment and name */ - Any& operator=(const std::string& x); - - /** Removes the comment and name */ - Any& operator=(const char* x); - - /** \a t must be ARRAY, TABLE, or NONE. Removes the comment and name */ - Any& operator=(Type t); - - Type type() const; - - /** Same as deserialize or load, but operates on a string instead - of a stream or file. - - \sa deserialize, load - */ - void parse(const std::string& src); - - std::string unparse() const; - - /** Comments appear before values when they are in serialized form.*/ - const std::string& comment() const; - void setComment(const std::string& c); - - /** True if this is the NONE value */ - bool isNone() const; - - /** Throws a ParseError exception if this is not a number */ - double number() const; - const std::string& string() const; - bool boolean() const; - - /** If this is named ARRAY or TABLE, returns the name. */ - const std::string& name() const; - - /** \brief Set the name used when serializing an ARRAY or TABLE. - - Only legal for ARRAY or TABLE. The \a name must begin with a letter - and contain only letters, numbers, underscores and scope operators. - -
-        a2z
-        hello
-        Foo::bar
-        color.red
-        this->that
-        __x
-        
- - - The scope operators "::", "->", and - ".", may have spaces around them. The name may not - contain parentheses. - */ - void setName(const std::string& name); - - /** Number of elements if this is an ARRAY or TABLE */ - int size() const; - int length() const; - - /** For an array, returns the ith element */ - const Any& operator[](int i) const; - Any& operator[](int i); - - /** Directly exposes the underlying data structure for an ARRAY. */ - const Array& array() const; - void append(const Any& v0); - void append(const Any& v0, const Any& v1); - void append(const Any& v0, const Any& v1, const Any& v2); - void append(const Any& v0, const Any& v1, const Any& v2, const Any& v3); - - /** Directly exposes the underlying data structure for table.*/ - const Table& table() const; - - /** For a table, returns the element for \a key. Throws KeyNotFound - exception if the element does not exist. - */ - const Any& operator[](const std::string& key) const; - - // Needed to prevent the operator[](int) overload from catching - // string literals - inline const Any& operator[](const char* key) const { - return operator[](std::string(key)); - } - - /** - Fetch an element from a table. This can be used as: - -
-        a["key"] = value;  (create the key if it did not exist)
-        
- - or - -
-        value = a["key"];  (throw an error if the key did not exist)
-        
- - Note: - In order to cause elements to be correctly created in the - first case while still providing "key not found" errors in the - second case, the Any returned is a special object that delays - the actual fetch until the following assignment or method - call. This means that in the event of an error, the exception - may be thrown from a line other than the actual fetch. Use - the Any::get() or the const Any::operator[]() methods to avoid - this behavior and ensure error-checking at fetch time. - */ - Any& operator[](const std::string& key); - - /** \copydoc Any::operator[](const std::string&) */ - inline Any& operator[](const char* key) { - return operator[](std::string(key)); - } - - /** For a table, returns the element for key \a x and \a - defaultVal if it does not exist. */ - const Any& get(const std::string& key, const Any& defaultVal) const; - - /** Returns true if this key is in the TABLE. Illegal to call on an object that is not a TABLE. */ - bool containsKey(const std::string& key) const; - - /** For a table, assigns the element for key k. */ - void set(const std::string& key, const Any& val); - - /** for an ARRAY, resizes and returns the last element */ - Any& next(); - - - /** True if the Anys are exactly equal, ignoring comments. Applies deeply on arrays and tables. */ - bool operator==(const Any& x) const; - bool operator!=(const Any& x) const; - - operator int() const; - operator float() const; - operator double() const; - operator bool() const; - operator std::string() const; - - /** Resize to \a n elements, where new elements are NIL - It is an error to call this method if this is not an Any::ARRAY */ - void resize(int n); - - /** - Clears all entries. - This must be a TABLE or ARRAY */ - void clear(); - - /** Parse from a file. - \sa deserialize, parse */ - void load(const std::string& filename); - - /** Uses the serialize method. */ - void save(const std::string& filename) const; - - void serialize(TextOutput& to) const; - /** Parse from a stream. - \sa load, parse */ - void deserialize(TextInput& ti); - - const Source& source() const; - - /** Throws a ParseError if \a value is false. Useful for quickly - creating parse rules in classes that deserialize from Any. - */ - void verify(bool value, const std::string& message = "") const; - - /** Verifies that the name begins with identifier \a n. It may contain - identifier operators after this */ - void verifyName(const std::string& n) const; - - /** Verifies that the type is \a t. */ - void verifyType(Type t) const; - - /** Throws an exception if the type is not \a t0 or \a t1. */ - void verifyType(Type t0, Type t1) const; - - /** Verifies that the size is between \a low and \a high, inclusive */ - void verifySize(int low, int high) const; - - /** Verifies that the size is exactly \a s */ - void verifySize(int s) const; - -private: - - void deserializeTable(TextInput& ti); - void deserializeArray(TextInput& ti,const std::string& term); - -}; // class Any - -} // namespace G3D - -#endif diff --git a/externals/g3dlite/G3D/AnyVal.h b/externals/g3dlite/G3D/AnyVal.h deleted file mode 100644 index 8c1bc72f206..00000000000 --- a/externals/g3dlite/G3D/AnyVal.h +++ /dev/null @@ -1,512 +0,0 @@ -/** - @file AnyVal.h - @author Morgan McGuire - @created 2006-06-11 - @edited 2008-07-14 - */ - -#ifndef G3D_ANYVAL_H -#define G3D_ANYVAL_H - -#include "G3D/platform.h" -#include -#include "G3D/Array.h" -#include "G3D/TextInput.h" - -namespace G3D { -// Forward declarations for G3D types -class Vector2; -class Vector3; -class Vector4; -class Color1; -class Color3; -class Color4; -class Quat; -class Matrix2; -class Matrix3; -class Matrix4; -class CoordinateFrame; -class TextInput; -class TextOutput; -class BinaryInput; -class BinaryOutput; -class Rect2D; -class AABox; - -/** - \deprecated - Use the G3D::Any class instead. This is only provided for - backwards compatibility to G3D 7.xx. - - A generic value, useful for defining property trees that can - be loaded from and saved to disk. The values are intentionally - restricted to a small set. - - When written to files, the syntax is as follows. Note that you can - nest arrays and tables in order to create full tree (i.e., XML-like) - structures as configuration files: - - - - - - - - - - - - - - - - - - - - - - - -
NULLNil
doubleThe number in printf double format
booltrue or false
std::stringThe string in double-quotes (")
Rect2DR(x0,y0,x1,y1)
Color1C1(value)
Color3C3(r,g,b)
Color4C4(r,g,b,a)
Vector2V2(x,y)
Vector3V3(x,y,z)
Vector4V4(x,y,z,w)
QuatV(x,y,z,w)
AABoxAAB(low Vector3, high Vector3)
Matrix2M2(r0c0, r0c1, -
   
r1c0, r1c1)
Matrix3M3(r0c0, r0c1, r0c2, -
   
r1c0, r1c1, r1c2, -
   
r2c0, r2c1, r2c2)
Matrix4M4(r0c0, r0c1, r0c2, r0c3, -
   
r1c0, r1c1, r1c2, r1c3, -
   
r2c0, r2c1, r2c2, r2c3, -
   
r3c0, r3c1, r3c2, r3c3)
CoordinateFrameCF(r0c0, r0c1, r0c2, r0c3, -
   
r1c0, r1c1, r1c2, r1c3, -
   
r2c0, r2c1, r2c2, r2c3)
CoordinateFrameCF(V3(x, y, z), yaw deg, pitch deg, optional roll deg)
Array[element0, element1, ... , elementn-1]
Table{symbol0 = value0 -
 symbol1 = value1 -
 ... -
 symboln-1 = valuen-1}
- - See also boost::any for a more general purpose but slightly harder to use - "any" for C++. - - The semantics of operator[] and the get() methods are slightly different; - operator[] acts more like a scripting language that automatically extends - arrays and tables instead of generating errors. get() has more strict semantics, - like a C++ class. - - AnyVal uses copy-on-mutate, so that AnyVal a = b semantically copies b (like int a = b would), although in practice - it delays the copy until one is mutated so that it is still fast to "copy" large arrays and tables. - - Reading example: -
-    AnyVal property = AnyVal::fromFile("c:/tmp/test.txt"));
-
-    Vector3 vel = property["angular velocity"]
-
-    Using defaults to handle errors:
-       If there was no "enabled" value, this will return the default instead of failing
-    bool enabled = property["enabled"].boolean(true);
-
- 
- - Writing to a file: -
-    AnyVal dict(AnyVal::TABLE);
-
-    dict["enabled"] = AnyVal(true);
-    dict["weight"] = 100;
-    dict["angular velocity"] = Vector3(1, -3, 4.5);
-
-    TextOutput t("c:/tmp/test.txt");
-    dict.serialize(t);
-    t.commit();
-  
- - Example of a data file: -
-   {
-      heights = [1, 17, 32]
-      model = 
-        {
-           color = C3(1, 1, 1)
-           filename = "foo.md2"
-        }
-      position = V3(23, 14, 0)
-      name = "Elmer"
-   }
-  
- -

- What's the difference from boost::any? -
I think that AnyVal will be easier for novice C++ users. It addresses the problem that - even though G3D::TextInput makes reading configuration files extremely simple, many people - still don't use it. So AnyVal makes it ridiculously simple to read and write a tree of G3D - types to a file. - - AnyVal: -

-{
-AnyVal tree(TextInput("config.txt"));
-
-bool enabled = tree.get("enabled", false);
-Vector3 direction = tree.get("direction", Vector3::zero());
-...
-}
-
- -boost: -
-{
-bool enabled = false;
-Vector3 direction;
-Table tree;
-
- ...write lots of file parsing code...
-
-   if (tree.containsKey("enabled")) {
-      const boost::any& val = tree["enabled"];
-      try {
-        enabled = any_cast(val);
-      } catch(const boost::bad_any_cast &) {
-      }
-    }
-
-   if (tree.containsKey("direction")) {
-      const boost::any& val = tree["direction"];
-      try {
-        direction = any_cast(val);
-      } catch(const boost::bad_any_cast &) {
-      }
-    }
-   ...
-}
-
- -\deprecated - */ -class AnyVal { -public: - - /** Array and table values are all Any.*/ - enum Type { - NIL, - NUMBER, - BOOLEAN, - STRING, - VECTOR2, - VECTOR3, - VECTOR4, - MATRIX2, - MATRIX3, - MATRIX4, - QUAT, - COORDINATEFRAME, - COORDINATEFRAME2D, - CFRAME = COORDINATEFRAME, - CFRAME2D = COORDINATEFRAME2D, - COLOR1, - COLOR3, - COLOR4, - RECT2D, - AABOX2D = RECT2D, - AABOX, - ARRAY, - TABLE}; - - /** Base class for all AnyVal exceptions.*/ - class Exception { - public: - virtual ~Exception() {} - }; - - /** Thrown when an inappropriate operation is performed (e.g., operator[] on a number) */ - class WrongType : public Exception { - public: - Type expected; - Type actual; - WrongType() : expected(NIL), actual(NIL) {} - WrongType(Type e, Type a) : expected(e), actual(a) {} - }; - - /** Thrown by operator[] when a key is not present. */ - class KeyNotFound : public Exception { - public: - std::string key; - KeyNotFound() {} - KeyNotFound(const std::string& k) : key(k) {} - }; - - class IndexOutOfBounds : public Exception { - public: - int index; - int size; - IndexOutOfBounds() : index(0), size(0) {} - IndexOutOfBounds(int i, int s) : index(i), size(s) {} - }; - - /** Thrown when deserialize() when the input is incorrectly formatted. */ - class CorruptText : public Exception { - public: - std::string message; - - /** Token where the problem occurred.*/ - G3D::Token token; - - CorruptText() {} - CorruptText(const std::string& s, const G3D::Token& t) : message(s), token(t) {} - }; - -private: - - Type m_type; - void* m_value; - - /** For table and array types, *m_value is shared between multiple - instances. Mutation is allowed only if the reference count is - exactly 1, otherwise the mutating instance must copy the - value. This is not used for other types. - */ - int* m_referenceCount; - - /** Decrements the reference count (if there is one). If the - reference count is zero or does not exist. Calls delete on @a - m_value and sets it to NULL. - */ - void deleteValue(); - - /** Returns a copy of the value. */ - void* copyValue() const; - - /** Assumes isSharedType. Ensures that this has a unique reference */ - void makeMutable(); - - /** True if this is a shared value between multiple instances. */ - inline bool isShared() const { - return m_referenceCount && (*m_referenceCount > 1); - } - - /** True when m_value is a double pointer */ - inline bool isSharedType() const { - return (m_type == TABLE) || (m_type == ARRAY); - } - -public: - - AnyVal(); - - /** Deserialize */ - explicit AnyVal(G3D::TextInput& t); - - static AnyVal fromFile(const std::string& filename); - - void load(const std::string& filename); - - void save(const std::string& filename) const; - - ///** Deserialize */ - //explicit AnyVal(G3D::BinaryInput& t); - - /** Construct a number */ - AnyVal(double); - AnyVal(int); - - // Explicit to avoid ambiguity with the 'double' constructor - // when an integer type is constructed - AnyVal(bool); - AnyVal(const G3D::Vector2&); - AnyVal(const G3D::Vector3&); - AnyVal(const G3D::Vector4&); - - AnyVal(const G3D::Color1&); - AnyVal(const G3D::Color3&); - AnyVal(const G3D::Color4&); - - AnyVal(const std::string&); - AnyVal(const char*); - - AnyVal(const G3D::Quat&); - - AnyVal(const G3D::Rect2D&); - AnyVal(const G3D::AABox&); - - AnyVal(const G3D::CoordinateFrame&); - AnyVal(const G3D::Matrix2&); - AnyVal(const G3D::Matrix3&); - AnyVal(const G3D::Matrix4&); - - AnyVal(const AnyVal&); - - AnyVal(Type arrayOrTable); - - AnyVal& operator=(const AnyVal&); - - /** Frees the underlying storage */ - ~AnyVal(); - - Type type() const; - - bool isNil() const { - return type() == NIL; - } - - void serialize(G3D::TextOutput& t) const; - //void serialize(G3D::BinaryOutput& t) const; - void deserialize(G3D::TextInput& t); - //void deserialize(G3D::BinaryInput& t); - - /** Array dereference. If the index is out of bounds, IndexOutOfBounds is thrown */ - const AnyVal& operator[](int) const; - - /** Extend this array by one element. */ - void append(const AnyVal&); - - /** If the index is out of bounds, the array is resized. If the index is negative, - IndexOutOfBounds is thrown.*/ - AnyVal& operator[](int); - - /** If @a i is out of bounds or this is not an ARRAY, defaultVal is returned.*/ - const AnyVal& get(int i, const AnyVal& defaultVal) const; - - /** If out of bounds, IndexOutOfBounds is thrown. */ - const AnyVal& get(int i) const; - - /** Returns defaultVal if this is not a TABLE or the key is not found. */ - const AnyVal& get(const std::string& key, const AnyVal& defaultVal) const; - - /** Throws KeyNotFound exception if the key is not present.*/ - const AnyVal& get(const std::string& key) const; - - /** Table reference */ - const AnyVal& operator[](const std::string&) const; - - /** Table reference. If the element does not exist, it is created. */ - AnyVal& operator[](const std::string&); - - /** Table reference */ - const AnyVal& operator[](const char*) const; - - /** Table reference. If the element does not exist, it is created. */ - AnyVal& operator[](const char*); - - /** If this value is not a number throws a WrongType exception. */ - double number() const; - - /** If this value is not a number, returns defaultVal. */ - double number(double defaultVal) const; - - operator double () const { - return number(); - } - - operator float () const { - return (float)number(); - } - - bool boolean() const; - bool boolean(bool b) const; - - operator bool() const { - return boolean(); - } - - const std::string& string() const; - const std::string& string(const std::string& defaultVal) const; - - operator const std::string& () const { - return string(); - } - - const G3D::Rect2D& rect2D() const; - const G3D::Rect2D& rect2D(const G3D::Rect2D& defaultVal) const; - - operator const Rect2D& () const { - return rect2D(); - } - - const G3D::AABox& aabox() const; - const G3D::AABox& aabox(const G3D::AABox& defaultVal) const; - - operator const AABox& () const { - return aabox(); - } - - const G3D::Vector2& vector2() const; - const G3D::Vector2& vector2(const G3D::Vector2& defaultVal) const; - - operator const Vector2& () const { - return vector2(); - } - - const G3D::Vector3& vector3() const; - const G3D::Vector3& vector3(const G3D::Vector3& defaultVal) const; - - operator const Vector3& () { - return vector3(); - } - - const G3D::Vector4& vector4() const; - const G3D::Vector4& vector4(const G3D::Vector4& defaultVal) const; - - operator const Vector4& () const { - return vector4(); - } - - const G3D::Color1& color1() const; - const G3D::Color1& color1(const G3D::Color1& defaultVal) const; - - const G3D::Color3& color3() const; - const G3D::Color3& color3(const G3D::Color3& defaultVal) const; - - operator const Color3& () const { - return color3(); - } - - const G3D::Color4& color4() const; - const G3D::Color4& color4(const G3D::Color4& defaultVal) const; - - operator const Color4& () const { - return color4(); - } - - const G3D::CoordinateFrame& coordinateFrame() const; - const G3D::CoordinateFrame& coordinateFrame(const G3D::CoordinateFrame& defaultVal) const; - - operator const CoordinateFrame& () const { - return coordinateFrame(); - } - - const G3D::Matrix2& matrix2() const; - const G3D::Matrix2& matrix2(const G3D::Matrix2& defaultVal) const; - - operator const Matrix2& () const { - return matrix2(); - } - - const G3D::Matrix3& matrix3() const; - const G3D::Matrix3& matrix3(const G3D::Matrix3& defaultVal) const; - - operator const Matrix3& () const { - return matrix3(); - } - - const G3D::Matrix4& matrix4() const; - const G3D::Matrix4& matrix4(const G3D::Matrix4& defaultVal) const; - - operator const Matrix4& () const { - return matrix4(); - } - - const G3D::Quat& quat() const; - const G3D::Quat& quat(const G3D::Quat& defaultVal) const; - - operator const Quat& () const { - return quat(); - } - - std::string toString() const; - - /** Number of elements for an array or table.*/ - int size() const; - - /** For a table, returns the keys. */ - void getKeys(G3D::Array&) const; -}; - -} - -#endif diff --git a/externals/g3dlite/G3D/AreaMemoryManager.h b/externals/g3dlite/G3D/AreaMemoryManager.h deleted file mode 100644 index d8d8f710359..00000000000 --- a/externals/g3dlite/G3D/AreaMemoryManager.h +++ /dev/null @@ -1,93 +0,0 @@ -/** - @file AreaMemoryManager.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2009-01-20 - @edited 2009-05-29 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ - - -#ifndef G3D_AreaMemoryManager_h -#define G3D_AreaMemoryManager_h - -#include "G3D/platform.h" -#include "G3D/g3dmath.h" -#include "G3D/Array.h" -#include "G3D/MemoryManager.h" - -namespace G3D { - -/** - \brief Allocates memory in large blocks and then frees it as an area. - - Useful for ensuring cache coherence and for reducing the time cost of - multiple allocations and deallocations. - - Not threadsafe - */ -class AreaMemoryManager : public MemoryManager { -private: - - class Buffer { - private: - uint8* m_first; - size_t m_size; - size_t m_used; - - public: - - Buffer(size_t size); - - ~Buffer(); - - /** Returns NULL if out of space */ - void* alloc(size_t s); - }; - - size_t m_sizeHint; - - /** The underlying array is stored in regular MemoryManager heap memory */ - Array m_bufferArray; - - AreaMemoryManager(size_t sizeHint); - -public: - - typedef ReferenceCountedPointer Ref; - - /** - \param sizeHint Total amount of memory expected to be allocated. - The allocator will allocate memory from the system in increments - of this size. - */ - static AreaMemoryManager::Ref create(size_t sizeHint = 10 * 1024 * 1024); - - /** Invokes deallocateAll. */ - ~AreaMemoryManager(); - - size_t bytesAllocated() const; - - /** Allocates memory out of the buffer pool. - @param s must be no larger than sizeHint */ - virtual void* alloc(size_t s); - - /** Ignored. */ - virtual void free(void* x); - - virtual bool isThreadsafe() const; - - /** Deletes all previously allocated memory. Because delete is not - invoked on objects in this memory, it is not safe to simply - free memory containing C++ objects that expect their destructors - to be called. */ - void deallocateAll(); -}; - -typedef AreaMemoryManager CoherentAllocator; -} - -#endif diff --git a/externals/g3dlite/G3D/Array.h b/externals/g3dlite/G3D/Array.h deleted file mode 100644 index cc9e1d9dd01..00000000000 --- a/externals/g3dlite/G3D/Array.h +++ /dev/null @@ -1,1274 +0,0 @@ -/** - @file Array.h - - @maintainer Morgan McGuire, graphics3d.com - @cite Portions written by Aaron Orenstein, a@orenstein.name - - @created 2001-03-11 - @edited 2009-05-29 - - Copyright 2000-2009, Morgan McGuire, http://graphics.cs.williams.edu - All rights reserved. - */ - -#ifndef G3D_Array_h -#define G3D_Array_h - -#include "G3D/platform.h" -#include "G3D/debug.h" -#include "G3D/System.h" -#include "G3D/MemoryManager.h" -#ifdef G3D_DEBUG -// For formatting error messages -# include "G3D/format.h" -#endif -#include -#include - -#ifdef _MSC_VER -# include - -# pragma warning (push) - // debug information too long -# pragma warning( disable : 4312) -# pragma warning( disable : 4786) -#endif - - -namespace G3D { - -/** - Constant for passing to Array::resize - */ -const bool DONT_SHRINK_UNDERLYING_ARRAY = false; - -/** Constant for Array::sort */ -const int SORT_INCREASING = 1; -/** Constant for Array::sort */ -const int SORT_DECREASING = -1; - -/** - \brief Dynamic 1D array tuned for performance. - - Objects must have a default constructor (constructor that - takes no arguments) in order to be used with this template. - You will get the error "no appropriate default constructor found" - if they do not. - - Do not use with objects that overload placement operator new, - since the speed of Array is partly due to pooled allocation. - - Array is highly optimized compared to std::vector. - Array operations are less expensive than on std::vector and for large - amounts of data, Array consumes only 1.5x the total size of the - data, while std::vector consumes 2.0x. The default - array takes up zero heap space. The first resize (or append) - operation grows it to a reasonable internal size so it is efficient - to append to small arrays. - - Then Array needs to copy - data internally on a resize operation it correctly invokes copy - constructors of the elements (the MSVC6 implementation of - std::vector uses realloc, which can create memory leaks for classes - containing references and pointers). Array provides a guaranteed - safe way to access the underlying data as a flat C array -- - Array::getCArray. Although (T*)std::vector::begin() can be used for - this purpose, it is not guaranteed to succeed on all platforms. - - To serialize an array, see G3D::serialize. - - The template parameter MIN_ELEMENTS indicates the smallest number of - elements that will be allocated. The default of 10 is designed to avoid - the overhead of repeatedly allocating the array as it grows from 1, to 2, and so on. - If you are creating a lot of small Arrays, however, you may want to set this smaller - to reduce the memory cost. Once the array has been allocated, it will never - deallocate the underlying array unless MIN_ELEMENTS is set to 0, MIN_BYTES is 0, and the array - is empty. - - Do not subclass an Array. - - \sa G3D::SmallArray - */ -template -class Array { -private: - /** 0...num-1 are initialized elements, num...numAllocated-1 are not */ - T* data; - - int num; - int numAllocated; - - MemoryManager::Ref m_memoryManager; - - /** \param n Number of elements - */ - void init(int n, const MemoryManager::Ref& m) { - m_memoryManager = m; - debugAssert(n >= 0); - this->num = 0; - this->numAllocated = 0; - data = NULL; - if (n > 0) { - resize(n); - } else { - data = NULL; - } - } - - void _copy(const Array &other) { - init(other.num, MemoryManager::create()); - for (int i = 0; i < num; i++) { - data[i] = other.data[i]; - } - } - - /** - Returns true iff address points to an element of this array. - Used by append. - */ - inline bool inArray(const T* address) { - return (address >= data) && (address < data + num); - } - - - /** Only compiled if you use the sort procedure. */ - static bool __cdecl compareGT(const T& a, const T& b) { - return a > b; - } - - - /** - Allocates a new array of size numAllocated (not a parameter to the method) - and then copies at most oldNum elements from the old array to it. Destructors are - called for oldNum elements of the old array. - */ - void realloc(int oldNum) { - T* oldData = data; - - // The allocation is separate from the constructor invocation because we don't want - // to pay for the cost of constructors until the newly allocated - // elements are actually revealed to the application. They - // will be constructed in the resize() method. - - data = (T*)m_memoryManager->alloc(sizeof(T) * numAllocated); - alwaysAssertM(data, "Memory manager returned NULL: out of memory?"); - - // Call the copy constructors - {const int N = G3D::min(oldNum, numAllocated); - const T* end = data + N; - T* oldPtr = oldData; - for (T* ptr = data; ptr < end; ++ptr, ++oldPtr) { - - // Use placement new to invoke the constructor at the location - // that we determined. Use the copy constructor to make the assignment. - const T* constructed = new (ptr) T(*oldPtr); - - (void)constructed; - debugAssertM(constructed == ptr, - "new returned a different address than the one provided by Array."); - }} - - // Call destructors on the old array (if there is no destructor, this will compile away) - {const T* end = oldData + oldNum; - for (T* ptr = oldData; ptr < end; ++ptr) { - ptr->~T(); - }} - - m_memoryManager->free(oldData); - } - -public: - - /** - G3D C++ STL style iterator variable. Call begin() to get - the first iterator, pre-increment (++i) the iterator to get to - the next value. Use dereference (*i) to access the element. - */ - typedef T* Iterator; - /** G3D C++ STL style const iterator in same style as Iterator. */ - typedef const T* ConstIterator; - - /** stl porting compatibility helper */ - typedef Iterator iterator; - /** stl porting compatibility helper */ - typedef ConstIterator const_iterator; - /** stl porting compatibility helper */ - typedef T value_type; - /** stl porting compatibility helper */ - typedef int size_type; - /** stl porting compatibility helper */ - typedef int difference_type; - - /** - C++ STL style iterator method. Returns the first iterator element. - Do not change the size of the array while iterating. - */ - Iterator begin() { - return data; - } - - ConstIterator begin() const { - return data; - } - /** - C++ STL style iterator method. Returns one after the last iterator - element. - */ - ConstIterator end() const { - return data + num; - } - - Iterator end() { - return data + num; - } - - /** - The array returned is only valid until the next append() or resize call, or - the Array is deallocated. - */ - T* getCArray() { - return data; - } - - /** - The array returned is only valid until the next append() or resize call, or - the Array is deallocated. - */ - const T* getCArray() const { - return data; - } - - /** Creates a zero length array (no heap allocation occurs until resize). */ - Array() : num(0) { - init(0, MemoryManager::create()); - debugAssert(num >= 0); - } - - - /** Creates an array containing v0. */ - Array(const T& v0) { - init(1, MemoryManager::create()); - (*this)[0] = v0; - } - - /** Creates an array containing v0 and v1. */ - Array(const T& v0, const T& v1) { - init(2, MemoryManager::create()); - (*this)[0] = v0; - (*this)[1] = v1; - } - - /** Creates an array containing v0...v2. */ - Array(const T& v0, const T& v1, const T& v2) { - init(3, MemoryManager::create()); - (*this)[0] = v0; - (*this)[1] = v1; - (*this)[2] = v2; - } - - /** Creates an array containing v0...v3. */ - Array(const T& v0, const T& v1, const T& v2, const T& v3) { - init(4, MemoryManager::create()); - (*this)[0] = v0; - (*this)[1] = v1; - (*this)[2] = v2; - (*this)[3] = v3; - } - - /** Creates an array containing v0...v4. */ - Array(const T& v0, const T& v1, const T& v2, const T& v3, const T& v4) { - init(5, MemoryManager::create()); - (*this)[0] = v0; - (*this)[1] = v1; - (*this)[2] = v2; - (*this)[3] = v3; - (*this)[4] = v4; - } - - - /** - Copy constructor - */ - Array(const Array& other) : num(0) { - _copy(other); - debugAssert(num >= 0); - } - - /** - Destructor does not delete() the objects if T is a pointer type - (e.g. T = int*) instead, it deletes the pointers themselves and - leaves the objects. Call deleteAll if you want to dealocate - the objects referenced. Do not call deleteAll if T is not a pointer - type (e.g. do call Array::deleteAll, do not call Array::deleteAll). - */ - ~Array() { - // Invoke the destructors on the elements - for (int i = 0; i < num; i++) { - (data + i)->~T(); - } - - m_memoryManager->free(data); - // Set to 0 in case this Array is global and gets referenced during app exit - data = NULL; - num = 0; - numAllocated = 0; - } - - /** - Removes all elements. Use resize(0, false) or fastClear if you want to - remove all elements without deallocating the underlying array - so that future append() calls will be faster. - */ - void clear(bool shrink = true) { - resize(0, shrink); - } - - void clearAndSetMemoryManager(const MemoryManager::Ref& m) { - clear(); - debugAssert(data == NULL); - m_memoryManager = m; - } - - /** resize(0, false) - @deprecated*/ - void fastClear() { - clear(false); - } - - /** - Assignment operator. - */ - Array& operator=(const Array& other) { - debugAssert(num >= 0); - resize(other.num); for (int i = 0; i < num; ++i) { - data[i] = other[i]; - } - debugAssert(num >= 0); - return *this; - } - - Array& operator=(const std::vector& other) { - resize((int)other.size()); - for (int i = 0; i < num; ++i) { - data[i] = other[i]; - } - return *this; - } - - inline MemoryManager::Ref memoryManager() const { - return m_memoryManager; - } - - /** - Number of elements in the array. - */ - inline int size() const { - return num; - } - - /** - Number of elements in the array. (Same as size; this is just - here for convenience). - */ - inline int length() const { - return size(); - } - - /** - Swaps element index with the last element in the array then - shrinks the array by one. - */ - void fastRemove(int index, bool shrinkIfNecessary = false) { - debugAssert(index >= 0); - debugAssert(index < num); - data[index] = data[num - 1]; - resize(size() - 1, shrinkIfNecessary); - } - - - /** - Inserts at the specified index and shifts all other elements up by one. - */ - void insert(int n, const T& value) { - // Add space for the extra element - resize(num + 1, false); - - for (int i = num - 1; i > n; --i) { - data[i] = data[i - 1]; - } - data[n] = value; - } - - /** @param shrinkIfNecessary if false, memory will never be - reallocated when the array shrinks. This makes resizing much - faster but can waste memory. - */ - void resize(int n, bool shrinkIfNecessary = true) { - debugAssert(n >= 0); - if (num == n) { - return; - } - - int oldNum = num; - num = n; - - // Call the destructors on newly hidden elements if there are any - for (int i = num; i < oldNum; ++i) { - (data + i)->~T(); - } - - // Once allocated, always maintain MIN_ELEMENTS elements or 32 bytes, whichever is higher. - const int minSize = std::max(MIN_ELEMENTS, (int)(MIN_BYTES / sizeof(T))); - - if ((MIN_ELEMENTS == 0) && (MIN_BYTES == 0) && (n == 0) && shrinkIfNecessary) { - // Deallocate the array completely - numAllocated = 0; - m_memoryManager->free(data); - data = NULL; - return; - } - - if (num > numAllocated) { - // Grow the underlying array - - if (numAllocated == 0) { - // First allocation; grow to exactly the size requested to avoid wasting space. - numAllocated = n; - debugAssert(oldNum == 0); - realloc(oldNum); - } else { - - if (num < minSize) { - // Grow to at least the minimum size - numAllocated = minSize; - - } else { - - // Increase the underlying size of the array. Grow aggressively - // up to 64k, less aggressively up to 400k, and then grow relatively - // slowly (1.5x per resize) to avoid excessive space consumption. - // - // These numbers are tweaked according to performance tests. - - float growFactor = 3.0; - - int oldSizeBytes = numAllocated * sizeof(T); - if (oldSizeBytes > 400000) { - // Avoid bloat - growFactor = 1.5; - } else if (oldSizeBytes > 64000) { - // This is what std:: uses at all times - growFactor = 2.0; - } - - numAllocated = (num - numAllocated) + (int)(numAllocated * growFactor); - - if (numAllocated < minSize) { - numAllocated = minSize; - } - } - - realloc(oldNum); - } - - } else if ((num <= numAllocated / 3) && shrinkIfNecessary && (num > minSize)) { - // Shrink the underlying array - - // Only copy over old elements that still remain after resizing - // (destructors were called for others if we're shrinking) - realloc(iMin(num, oldNum)); - - } - - // Call the constructors on newly revealed elements. - // Do not use parens because we don't want the intializer - // invoked for POD types. - for (int i = oldNum; i < num; ++i) { - new (data + i) T; - } - } - - /** - Add an element to the end of the array. Will not shrink the underlying array - under any circumstances. It is safe to append an element that is already - in the array. - */ - inline void append(const T& value) { - - if (num < numAllocated) { - // This is a simple situation; just stick it in the next free slot using - // the copy constructor. - new (data + num) T(value); - ++num; - } else if (inArray(&value)) { - // The value was in the original array; resizing - // is dangerous because it may move the value - // we have a reference to. - T tmp = value; - append(tmp); - } else { - // Here we run the empty initializer where we don't have to, but - // this simplifies the computation. - resize(num + 1, DONT_SHRINK_UNDERLYING_ARRAY); - data[num - 1] = value; - } - } - - - inline void append(const T& v1, const T& v2) { - if (inArray(&v1) || inArray(&v2)) { - // Copy into temporaries so that the references won't break when - // the array resizes. - T t1 = v1; - T t2 = v2; - append(t1, t2); - } else if (num + 1 < numAllocated) { - // This is a simple situation; just stick it in the next free slot using - // the copy constructor. - new (data + num) T(v1); - new (data + num + 1) T(v2); - num += 2; - } else { - // Resize the array. Note that neither value is already in the array. - resize(num + 2, DONT_SHRINK_UNDERLYING_ARRAY); - data[num - 2] = v1; - data[num - 1] = v2; - } - } - - - inline void append(const T& v1, const T& v2, const T& v3) { - if (inArray(&v1) || inArray(&v2) || inArray(&v3)) { - T t1 = v1; - T t2 = v2; - T t3 = v3; - append(t1, t2, t3); - } else if (num + 2 < numAllocated) { - // This is a simple situation; just stick it in the next free slot using - // the copy constructor. - new (data + num) T(v1); - new (data + num + 1) T(v2); - new (data + num + 2) T(v3); - num += 3; - } else { - resize(num + 3, DONT_SHRINK_UNDERLYING_ARRAY); - data[num - 3] = v1; - data[num - 2] = v2; - data[num - 1] = v3; - } - } - - - inline void append(const T& v1, const T& v2, const T& v3, const T& v4) { - if (inArray(&v1) || inArray(&v2) || inArray(&v3) || inArray(&v4)) { - T t1 = v1; - T t2 = v2; - T t3 = v3; - T t4 = v4; - append(t1, t2, t3, t4); - } else if (num + 3 < numAllocated) { - // This is a simple situation; just stick it in the next free slot using - // the copy constructor. - new (data + num) T(v1); - new (data + num + 1) T(v2); - new (data + num + 2) T(v3); - new (data + num + 3) T(v4); - num += 4; - } else { - resize(num + 4, DONT_SHRINK_UNDERLYING_ARRAY); - data[num - 4] = v1; - data[num - 3] = v2; - data[num - 2] = v3; - data[num - 1] = v4; - } - } - - /** - Returns true if the given element is in the array. - */ - bool contains(const T& e) const { - for (int i = 0; i < size(); ++i) { - if ((*this)[i] == e) { - return true; - } - } - - return false; - } - - /** - Append the elements of array. Cannot be called with this array - as an argument. - */ - void append(const Array& array) { - debugAssert(this != &array); - int oldNum = num; - int arrayLength = array.length(); - - resize(num + arrayLength, false); - - for (int i = 0; i < arrayLength; i++) { - data[oldNum + i] = array.data[i]; - } - } - - /** - Pushes a new element onto the end and returns its address. - This is the same as A.resize(A.size() + 1, false); A.last() - */ - inline T& next() { - resize(num + 1, false); - return last(); - } - - /** - Pushes an element onto the end (appends) - */ - inline void push(const T& value) { - append(value); - } - - inline void push(const Array& array) { - append(array); - } - - /** Alias to provide std::vector compatibility */ - inline void push_back(const T& v) { - push(v); - } - - /** "The member function removes the last element of the controlled sequence, which must be non-empty." - For compatibility with std::vector. */ - inline void pop_back() { - pop(); - } - - /** - "The member function returns the storage currently allocated to hold the controlled - sequence, a value at least as large as size()" - For compatibility with std::vector. - */ - int capacity() const { - return numAllocated; - } - - /** - "The member function returns a reference to the first element of the controlled sequence, - which must be non-empty." - For compatibility with std::vector. - */ - T& front() { - return (*this)[0]; - } - - /** - "The member function returns a reference to the first element of the controlled sequence, - which must be non-empty." - For compatibility with std::vector. - */ - const T& front() const { - return (*this)[0]; - } - - /** - "The member function returns a reference to the last element of the controlled sequence, - which must be non-empty." - For compatibility with std::vector. - */ - T& back() { - return (*this)[size()-1]; - } - - /** - "The member function returns a reference to the last element of the controlled sequence, - which must be non-empty." - For compatibility with std::vector. - */ - const T& back() const { - return (*this)[size()-1]; - } - - /** - Removes the last element and returns it. By default, shrinks the underlying array. - */ - inline T pop(bool shrinkUnderlyingArrayIfNecessary = true) { - debugAssert(num > 0); - T temp = data[num - 1]; - resize(num - 1, shrinkUnderlyingArrayIfNecessary); - return temp; - } - - /** Pops the last element and discards it without returning anything. Faster than pop. - By default, does not shrink the underlying array.*/ - inline void popDiscard(bool shrinkUnderlyingArrayIfNecessary = false) { - debugAssert(num > 0); - resize(num - 1, shrinkUnderlyingArrayIfNecessary); - } - - - /** - "The member function swaps the controlled sequences between *this and str." - Note that this is slower than the optimal std implementation. - - For compatibility with std::vector. - */ - void swap(Array& str) { - Array temp = str; - str = *this; - *this = temp; - } - - - /** - Performs bounds checks in debug mode - */ - inline T& operator[](int n) { - debugAssertM((n >= 0) && (n < num), format("Array index out of bounds. n = %d, size() = %d", n, num)); - debugAssert(data!=NULL); - return data[n]; - } - - inline T& operator[](unsigned int n) { - debugAssertM(n < (unsigned int)num, format("Array index out of bounds. n = %d, size() = %d", n, num)); - return data[n]; - } - - /** - Performs bounds checks in debug mode - */ - inline const T& operator[](int n) const { - debugAssert((n >= 0) && (n < num)); - debugAssert(data!=NULL); - return data[n]; - } - - inline const T& operator[](unsigned int n) const { - debugAssert((n < (unsigned int)num)); - debugAssert(data!=NULL); - return data[n]; - } - - inline T& randomElement() { - debugAssert(num > 0); - debugAssert(data!=NULL); - return data[iRandom(0, num - 1)]; - } - - inline const T& randomElement() const { - debugAssert(num > 0); - debugAssert(data!=NULL); - return data[iRandom(0, num - 1)]; - } - - /** - Returns the last element, performing a check in - debug mode that there is at least one element. - */ - inline const T& last() const { - debugAssert(num > 0); - debugAssert(data!=NULL); - return data[num - 1]; - } - - /** Returns element lastIndex() */ - inline T& last() { - debugAssert(num > 0); - debugAssert(data!=NULL); - return data[num - 1]; - } - - /** Returns size() - 1 */ - inline int lastIndex() const { - debugAssertM(num > 0, "Array is empty"); - return num - 1; - } - - inline int firstIndex() const { - debugAssertM(num > 0, "Array is empty"); - return 0; - } - - /** Returns element firstIndex(), performing a check in debug mode to ensure that there is at least one */ - inline T& first() { - debugAssertM(num > 0, "Array is empty"); - return data[0]; - } - - inline const T& first() const { - debugAssertM(num > 0, "Array is empty"); - return data[0]; - } - - /** Returns iFloor(size() / 2), throws an assertion in debug mode if the array is empty */ - inline int middleIndex() const { - debugAssertM(num > 0, "Array is empty"); - return num >> 1; - } - - /** Returns element middleIndex() */ - inline const T& middle() const { - debugAssertM(num > 0, "Array is empty"); - return data[num >> 1]; - } - - /** Returns element middleIndex() */ - inline T& middle() { - debugAssertM(num > 0, "Array is empty"); - return data[num >> 1]; - } - - /** - Calls delete on all objects[0...size-1] - and sets the size to zero. - */ - void deleteAll() { - for (int i = 0; i < num; i++) { - delete data[i]; - } - resize(0); - } - - /** - Returns the index of (the first occurance of) an index or -1 if - not found. Searches from the right. - */ - int rfindIndex(const T& value) const { - for (int i = num -1 ; i >= 0; --i) { - if (data[i] == value) { - return i; - } - } - return -1; - } - - /** - Returns the index of (the first occurance of) an index or -1 if - not found. - */ - int findIndex(const T& value) const { - for (int i = 0; i < num; ++i) { - if (data[i] == value) { - return i; - } - } - return -1; - } - - /** - Finds an element and returns the iterator to it. If the element - isn't found then returns end(). - */ - Iterator find(const T& value) { - for (int i = 0; i < num; ++i) { - if (data[i] == value) { - return data + i; - } - } - return end(); - } - - ConstIterator find(const T& value) const { - for (int i = 0; i < num; ++i) { - if (data[i] == value) { - return data + i; - } - } - return end(); - } - - /** - Removes count elements from the array - referenced either by index or Iterator. - */ - void remove(Iterator element, int count = 1) { - debugAssert((element >= begin()) && (element < end())); - debugAssert((count > 0) && (element + count) <= end()); - Iterator last = end() - count; - - while(element < last) { - element[0] = element[count]; - ++element; - } - - resize(num - count); - } - - void remove(int index, int count = 1) { - debugAssert((index >= 0) && (index < num)); - debugAssert((count > 0) && (index + count <= num)); - - remove(begin() + index, count); - } - - /** - Reverse the elements of the array in place. - */ - void reverse() { - T temp; - - int n2 = num / 2; - for (int i = 0; i < n2; ++i) { - temp = data[num - 1 - i]; - data[num - 1 - i] = data[i]; - data[i] = temp; - } - } - - /** - Sort using a specific less-than function, e.g.: - -
-    bool __cdecl myLT(const MyClass& elem1, const MyClass& elem2) {
-        return elem1.x < elem2.x;
-    }
-    
- - Note that for pointer arrays, the const must come - after the class name, e.g., Array uses: - -
-    bool __cdecl myLT(MyClass*const& elem1, MyClass*const& elem2) {
-        return elem1->x < elem2->x;
-    }
-    
- - or a functor, e.g., -
-bool
-less_than_functor::operator()( const double& lhs, const double& rhs ) const
-{
-return( lhs < rhs? true : false );
-}
-
- */ - // void sort(bool (__cdecl *lessThan)(const T& elem1, const T& elem2)) { - // std::sort(data, data + num, lessThan); - //} - template - void sort(const LessThan& lessThan) { - // Using std::sort, which according to http://www.open-std.org/JTC1/SC22/WG21/docs/D_4.cpp - // was 2x faster than qsort for arrays around size 2000 on intel core2 with gcc - std::sort(data, data + num, lessThan); - } - - /** - Sorts the array in increasing order using the > or < operator. To - invoke this method on Array, T must override those operator. - You can overide these operators as follows: - - bool T::operator>(const T& other) const { - return ...; - } - bool T::operator<(const T& other) const { - return ...; - } - - */ - void sort(int direction = SORT_INCREASING) { - if (direction == SORT_INCREASING) { - std::sort(data, data + num); - } else { - std::sort(data, data + num, compareGT); - } - } - - /** - Sorts elements beginIndex through and including endIndex. - */ - void sortSubArray(int beginIndex, int endIndex, int direction = SORT_INCREASING) { - if (direction == SORT_INCREASING) { - std::sort(data + beginIndex, data + endIndex + 1); - } else { - std::sort(data + beginIndex, data + endIndex + 1, compareGT); - } - } - - void sortSubArray(int beginIndex, int endIndex, bool (__cdecl *lessThan)(const T& elem1, const T& elem2)) { - std::sort(data + beginIndex, data + endIndex + 1, lessThan); - } - - /** - The StrictWeakOrdering can be either a class that overloads the function call operator() or - a function pointer of the form bool (__cdecl *lessThan)(const T& elem1, const T& elem2) - */ - template - void sortSubArray(int beginIndex, int endIndex, StrictWeakOrdering& lessThan) { - std::sort(data + beginIndex, data + endIndex + 1, lessThan); - } - - /** Uses < and == to evaluate operator(); this is the default comparator for Array::partition. */ - class DefaultComparator { - public: - inline int operator()(const T& A, const T& B) const { - if (A < B) { - return 1; - } else if (A == B) { - return 0; - } else { - return -1; - } - } - }; - - /** The output arrays are resized with fastClear() so that if they are already of the same size - as this array no memory is allocated during partitioning. - - @param comparator A function, or class instance with an overloaded operator() that compares - two elements of type T and returns 0 if they are equal, -1 if the second is smaller, - and 1 if the first is smaller (i.e., following the conventions of std::string::compare). For example: - -
-        int compare(int A, int B) {
-            if (A < B) {
-                return 1;
-            } else if (A == B) {
-                return 0;
-            } else {
-                return -1;
-            }
-        }
-        
- */ - template - void partition( - const T& partitionElement, - Array& ltArray, - Array& eqArray, - Array& gtArray, - const Comparator& comparator) const { - - // Make sure all arrays are independent - debugAssert(<Array != this); - debugAssert(&eqArray != this); - debugAssert(>Array != this); - debugAssert(<Array != &eqArray); - debugAssert(<Array != >Array); - debugAssert(&eqArray != >Array); - - // Clear the arrays - ltArray.fastClear(); - eqArray.fastClear(); - gtArray.fastClear(); - - // Form a table of buckets for lt, eq, and gt - Array* bucket[3] = {<Array, &eqArray, >Array}; - - for (int i = 0; i < num; ++i) { - int c = comparator(partitionElement, data[i]); - debugAssertM(c >= -1 && c <= 1, "Comparator returned an illegal value."); - - // Insert into the correct bucket, 0, 1, or 2 - bucket[c + 1]->append(data[i]); - } - } - - /** - Uses < and == on elements to perform a partition. See partition(). - */ - void partition( - const T& partitionElement, - Array& ltArray, - Array& eqArray, - Array& gtArray) const { - - partition(partitionElement, ltArray, eqArray, gtArray, typename Array::DefaultComparator()); - } - - /** - Paritions the array into those below the median, those above the median, and those elements - equal to the median in expected O(n) time using quickselect. If the array has an even - number of different elements, the median for partition purposes is the largest value - less than the median. - - @param tempArray used for working scratch space - @param comparator see parition() for a discussion.*/ - template - void medianPartition( - Array& ltMedian, - Array& eqMedian, - Array& gtMedian, - Array& tempArray, - const Comparator& comparator) const { - - ltMedian.fastClear(); - eqMedian.fastClear(); - gtMedian.fastClear(); - - // Handle trivial cases first - switch (size()) { - case 0: - // Array is empty; no parition is possible - return; - - case 1: - // One element - eqMedian.append(first()); - return; - - case 2: - { - // Two element array; median is the smaller - int c = comparator(first(), last()); - - switch (c) { - case -1: - // first was bigger - eqMedian.append(last()); - gtMedian.append(first()); - break; - - case 0: - // Both equal to the median - eqMedian.append(first(), last()); - break; - - case 1: - // Last was bigger - eqMedian.append(first()); - gtMedian.append(last()); - break; - } - } - return; - } - - // All other cases use a recursive randomized median - - // Number of values less than all in the current arrays - int ltBoost = 0; - - // Number of values greater than all in the current arrays - int gtBoost = 0; - - // For even length arrays, force the gt array to be one larger than the - // lt array: - // [1 2 3] size = 3, choose half = (s + 1) /2 - // - int lowerHalfSize, upperHalfSize; - if (isEven(size())) { - lowerHalfSize = size() / 2; - upperHalfSize = lowerHalfSize + 1; - } else { - lowerHalfSize = upperHalfSize = (size() + 1) / 2; - } - const T* xPtr = NULL; - - // Maintain pointers to the arrays; we'll switch these around during sorting - // to avoid copies. - const Array* source = this; - Array* lt = <Median; - Array* eq = &eqMedian; - Array* gt = >Median; - Array* extra = &tempArray; - - while (true) { - // Choose a random element -- choose the middle element; this is theoretically - // suboptimal, but for loosly sorted array is actually the best strategy - - xPtr = &(source->middle()); - if (source->size() == 1) { - // Done; there's only one element left - break; - } - const T& x = *xPtr; - - // Note: partition (fast) clears the arrays for us - source->partition(x, *lt, *eq, *gt, comparator); - - int L = lt->size() + ltBoost + eq->size(); - int U = gt->size() + gtBoost + eq->size(); - if ((L >= lowerHalfSize) && - (U >= upperHalfSize)) { - - // x must be the partition median - break; - - } else if (L < lowerHalfSize) { - - // x must be smaller than the median. Recurse into the 'gt' array. - ltBoost += lt->size() + eq->size(); - - // The new gt array will be the old source array, unless - // that was the this pointer (i.e., unless we are on the - // first iteration) - Array* newGt = (source == this) ? extra : const_cast*>(source); - - // Now set up the gt array as the new source - source = gt; - gt = newGt; - - } else { - - // x must be bigger than the median. Recurse into the 'lt' array. - gtBoost += gt->size() + eq->size(); - - // The new lt array will be the old source array, unless - // that was the this pointer (i.e., unless we are on the - // first iteration) - Array* newLt = (source == this) ? extra : const_cast*>(source); - - // Now set up the lt array as the new source - source = lt; - lt = newLt; - } - } - - // Now that we know the median, make a copy of it (since we're about to destroy the array that it - // points into). - T median = *xPtr; - xPtr = NULL; - - // Partition the original array (note that this fast clears for us) - partition(median, ltMedian, eqMedian, gtMedian, comparator); - } - - /** - Computes a median partition using the default comparator and a dynamically allocated temporary - working array. If the median is not in the array, it is chosen to be the largest value smaller - than the true median. - */ - void medianPartition( - Array& ltMedian, - Array& eqMedian, - Array& gtMedian) const { - - Array temp; - medianPartition(ltMedian, eqMedian, gtMedian, temp, DefaultComparator()); - } - - - /** Redistributes the elements so that the new order is statistically independent - of the original order. O(n) time.*/ - void randomize() { - T temp; - - for (int i = size() - 1; i >= 0; --i) { - int x = iRandom(0, i); - - temp = data[i]; - data[i] = data[x]; - data[x] = temp; - } - } - - -}; - - -/** Array::contains for C-arrays */ -template bool contains(const T* array, int len, const T& e) { - for (int i = len - 1; i >= 0; --i) { - if (array[i] == e) { - return true; - } - } - return false; -} - -} // namespace - -#ifdef _MSC_VER -# pragma warning (pop) -#endif - -#endif diff --git a/externals/g3dlite/G3D/AtomicInt32.h b/externals/g3dlite/G3D/AtomicInt32.h deleted file mode 100644 index 2d63f998355..00000000000 --- a/externals/g3dlite/G3D/AtomicInt32.h +++ /dev/null @@ -1,164 +0,0 @@ -/** - @file AtomicInt32.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2005-09-01 - @edited 2006-06-21 - */ -#ifndef G3D_ATOMICINT32_H -#define G3D_ATOMICINT32_H - -#include "G3D/platform.h" -#include "G3D/g3dmath.h" - -#if defined(G3D_OSX) -# include -#endif - -namespace G3D { - -/** - An integer that may safely be used on different threads without - external locking. - - On Win32, Linux, FreeBSD, and Mac OS X this is implemented without locks. - - BETA API This is unsupported and may change - */ -class AtomicInt32 { -private: -# if defined(G3D_WIN32) - volatile long m_value; -# elif defined(G3D_OSX) - int32_t m_value; -# else - volatile int32 m_value; -# endif - - -public: - - /** Initial value is undefined. */ - AtomicInt32() {} - - /** Atomic set */ - explicit AtomicInt32(const int32 x) { - m_value = x; - } - - /** Atomic set */ - AtomicInt32(const AtomicInt32& x) { - m_value = x.m_value; - } - - /** Atomic set */ - const AtomicInt32& operator=(const int32 x) { - m_value = x; - return *this; - } - - /** Atomic set */ - void operator=(const AtomicInt32& x) { - m_value = x.m_value; - } - - /** Returns the current value */ - int32 value() const { - return m_value; - } - - /** Returns the old value, before the add. */ - int32 add(const int32 x) { -# if defined(G3D_WIN32) - - return InterlockedExchangeAdd(&m_value, x); - -# elif defined(G3D_LINUX) || defined(G3D_FREEBSD) - - int32 old; - asm volatile ("lock; xaddl %0,%1" - : "=r"(old), "=m"(m_value) /* outputs */ - : "0"(x), "m"(m_value) /* inputs */ - : "memory", "cc"); - return old; - -# elif defined(G3D_OSX) - - int32 old = m_value; - OSAtomicAdd32(x, &m_value); - return old; - -# endif - } - - /** Returns old value. */ - int32 sub(const int32 x) { - return add(-x); - } - - void increment() { -# if defined(G3D_WIN32) - // Note: returns the newly incremented value - InterlockedIncrement(&m_value); -# elif defined(G3D_LINUX) || defined(G3D_FREEBSD) - add(1); -# elif defined(G3D_OSX) - // Note: returns the newly incremented value - OSAtomicIncrement32(&m_value); -# endif - } - - /** Returns zero if the result is zero after decrement, non-zero otherwise.*/ - int32 decrement() { -# if defined(G3D_WIN32) - // Note: returns the newly decremented value - return InterlockedDecrement(&m_value); -# elif defined(G3D_LINUX) || defined(G3D_FREEBSD) - unsigned char nz; - - asm volatile ("lock; decl %1;\n\t" - "setnz %%al" - : "=a" (nz) - : "m" (m_value) - : "memory", "cc"); - return nz; -# elif defined(G3D_OSX) - // Note: returns the newly decremented value - return OSAtomicDecrement32(&m_value); -# endif - } - - - /** Atomic test-and-set: if *this == comperand then *this := exchange else do nothing. - In both cases, returns the old value of *this. - - Performs an atomic comparison of this with the Comperand value. - If this is equal to the Comperand value, the Exchange value is stored in this. - Otherwise, no operation is performed. - - Under VC6 the sign bit may be lost. - */ - int32 compareAndSet(const int32 comperand, const int32 exchange) { -# if defined(G3D_WIN32) - return InterlockedCompareExchange(&m_value, exchange, comperand); -# elif defined(G3D_LINUX) || defined(G3D_FREEBSD) || defined(G3D_OSX) - // Based on Apache Portable Runtime - // http://koders.com/c/fid3B6631EE94542CDBAA03E822CA780CBA1B024822.aspx - int32 ret; - asm volatile ("lock; cmpxchgl %1, %2" - : "=a" (ret) - : "r" (exchange), "m" (m_value), "0"(comperand) - : "memory", "cc"); - return ret; - - // Note that OSAtomicCompareAndSwap32 does not return a useful value for us - // so it can't satisfy the cmpxchgl contract. -# endif - } - -}; - -} // namespace - -#endif diff --git a/externals/g3dlite/G3D/BinaryFormat.h b/externals/g3dlite/G3D/BinaryFormat.h deleted file mode 100644 index f6719a1c540..00000000000 --- a/externals/g3dlite/G3D/BinaryFormat.h +++ /dev/null @@ -1,140 +0,0 @@ -/** - @file BinaryFormat.h - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @author 2005-06-03 - @edited 2005-06-03 - - Copyright 2000-2005, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_BINARYFORMAT_H -#define G3D_BINARYFORMAT_H - -#include "G3D/platform.h" -#include "G3D/g3dmath.h" - -namespace G3D { - -class Vector2; -class Vector2int16; -class Vector3; -class Vector3int16; -class Vector4; -class Vector4int16; -class Color3; -class Color3uint8; -class Color4; -class Color4uint8; - -/** - Some values like float16 and int128 have no current CPU data structure that implements them but are useful - for file formats and for GPUs. - - CHUNK_BINFMT data follows the protocol. - */ -// Must be packed int 16 bits for the chunk reader -// We can't name these just "INT8" etc. because some libraries #define names like that -enum BinaryFormat { - FIRST_BINFMT = 1000, - - BOOL8_BINFMT, - UINT8_BINFMT, INT8_BINFMT, UINT16_BINFMT, INT16_BINFMT, UINT32_BINFMT, INT32_BINFMT, UINT64_BINFMT, INT64_BINFMT, UINT128_BINFMT, INT128_BINFMT, - FLOAT16_BINFMT, FLOAT32_BINFMT, FLOAT64_BINFMT, - VECTOR2_BINFMT, VECTOR2INT16_BINFMT, - VECTOR3_BINFMT, VECTOR3INT16_BINFMT, - VECTOR4_BINFMT, VECTOR4INT16_BINFMT, - COLOR3_BINFMT, COLOR3UINT8_BINFMT, COLOR3INT16_BINFMT, - COLOR4_BINFMT, COLOR4UINT8_BINFMT, COLOR4INT16_BINFMT, - STRING_BINFMT, STRINGEVEN_BINFMT, STRING8_BINFMT, STRING16_BINFMT, STRING32_BINFMT, - - CHUNK_BINFMT, - - CUSTOM_BINFMT, - - LAST_BINFMT -}; - -} - -/** A macro that maps G3D types to format constants. - (e.g. binaryFormatOf(Vector3) == VECTOR3_BINFMT). -*/ -// This implementation is designed to meet the following constraints: -// 1. Work around the many MSVC++ partial template bugs -// 2. Work for primitive types (e.g. int) -#define binaryFormatOf(T) (G3D::_internal::_BinaryFormat::x()) - -namespace G3D { -namespace _internal { - - -template class _BinaryFormat { -public: - static BinaryFormat x() { - return CUSTOM_BINFMT; - } -}; -}} - - -/** - Macro to declare the underlying format (as will be returned by glFormatOf) - of a type. For example, - -
-    DECLARE_BINARYFORMATOF(Vector4, VECTOR4_BINFMT)
-  
- - Use this so you can make vertex arrays of your own classes and not just - the standard ones. - */ -#define DECLARE_BINARYFORMATOF(CType, EnumType) \ -namespace G3D { \ - namespace _internal { \ - template<> class _BinaryFormat { \ - public: \ - static BinaryFormat x() { \ - return EnumType; \ - } \ - }; \ - } \ -} - -DECLARE_BINARYFORMATOF( bool, BOOL8_BINFMT ) - -DECLARE_BINARYFORMATOF( uint8, UINT8_BINFMT ) -DECLARE_BINARYFORMATOF( int8, INT8_BINFMT ) -DECLARE_BINARYFORMATOF( uint16, UINT16_BINFMT ) -DECLARE_BINARYFORMATOF( int16, INT16_BINFMT ) -DECLARE_BINARYFORMATOF( uint32, UINT32_BINFMT ) -DECLARE_BINARYFORMATOF( int32, INT32_BINFMT ) -DECLARE_BINARYFORMATOF( uint64, UINT64_BINFMT ) -DECLARE_BINARYFORMATOF( int64, INT64_BINFMT ) - -DECLARE_BINARYFORMATOF( float32, FLOAT32_BINFMT ) -DECLARE_BINARYFORMATOF( float64, FLOAT64_BINFMT ) - -DECLARE_BINARYFORMATOF( Vector2, VECTOR2_BINFMT ) -DECLARE_BINARYFORMATOF( Vector2int16, VECTOR2INT16_BINFMT ) -DECLARE_BINARYFORMATOF( Vector3, VECTOR3_BINFMT ) -DECLARE_BINARYFORMATOF( Vector3int16, VECTOR3INT16_BINFMT ) -DECLARE_BINARYFORMATOF( Vector4, VECTOR4_BINFMT ) -DECLARE_BINARYFORMATOF( Vector4int16, VECTOR4INT16_BINFMT ) - -DECLARE_BINARYFORMATOF( Color3, COLOR3_BINFMT ) -DECLARE_BINARYFORMATOF( Color3uint8, COLOR3UINT8_BINFMT ) -DECLARE_BINARYFORMATOF( Color4, COLOR4_BINFMT ) -DECLARE_BINARYFORMATOF( Color4uint8, COLOR4UINT8_BINFMT ) - -namespace G3D { - -/** Returns -1 if the format is custom, otherwise the byte size - of a single element in this format.*/ -int32 byteSize(BinaryFormat f); - - -} //G3D - -#endif diff --git a/externals/g3dlite/G3D/BinaryInput.h b/externals/g3dlite/G3D/BinaryInput.h deleted file mode 100644 index 1dac93ea55e..00000000000 --- a/externals/g3dlite/G3D/BinaryInput.h +++ /dev/null @@ -1,441 +0,0 @@ -/** - @file BinaryInput.h - - @maintainer Morgan McGuire, graphics3d.com - - @created 2001-08-09 - @edited 2006-07-19 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_BinaryInput_h -#define G3D_BinaryInput_h - -#ifdef _MSC_VER -// Disable conditional expression is constant, which occurs incorrectly on inlined functions -# pragma warning(push) -# pragma warning( disable : 4127 ) -#endif - -#include -#include -#include -#include -#include -#include -#include "G3D/platform.h" -#include "G3D/Array.h" -#include "G3D/Color4.h" -#include "G3D/Color3.h" -#include "G3D/Vector4.h" -#include "G3D/Vector3.h" -#include "G3D/Vector2.h" -#include "G3D/g3dmath.h" -#include "G3D/debug.h" -#include "G3D/System.h" - - -namespace G3D { - -#if defined(G3D_WIN32) || defined(G3D_LINUX) - // Allow writing of integers to non-word aligned locations. - // This is legal on x86, but not on other platforms. - #define G3D_ALLOW_UNALIGNED_WRITES -#endif - -/** - Sequential or random access byte-order independent binary file access. - Files compressed with zlib and beginning with an unsigned 32-bit int - size are transparently decompressed when the compressed = true flag is - specified to the constructor. - - For every readX method there are also versions that operate on a whole - Array, std::vector, or C-array. e.g. readFloat32(Array& array, n) - These methods resize the array or std::vector to the appropriate size - before reading. For a C-array, they require the pointer to reference - a memory block at least large enough to hold n elements. - - Most classes define serialize/deserialize methods that use BinaryInput, - BinaryOutput, TextInput, and TextOutput. There are text serializer - functions for primitive types (e.g. int, std::string, float, double) but not - binary serializers-- you must call the BinaryInput::readInt32 or - other appropriate function. This is because it would be very hard to - debug the error sequence: serialize(1.0, bo); ... float f; deserialize(f, bi); - in which a double is serialized and then deserialized as a float. - */ -class BinaryInput { -private: - - // The initial buffer will be no larger than this, but - // may grow if a large memory read occurs. 50 MB - enum {INITIAL_BUFFER_LENGTH = 50000000}; - - /** - is the file big or little endian - */ - G3DEndian m_fileEndian; - std::string m_filename; - - bool m_swapBytes; - - /** Next position to read from in bitString during readBits. */ - int m_bitPos; - - /** Bits currently being read by readBits. - Contains at most 8 (low) bits. Note that - beginBits/readBits actually consumes one extra byte, which - will be restored by writeBits.*/ - uint32 m_bitString; - - /** 1 when between beginBits and endBits, 0 otherwise. */ - int m_beginEndBits; - - /** When operating on huge files, we cannot load the whole file into memory. - This is the file position to which buffer[0] corresponds. - */ - int64 m_alreadyRead; - - /** - Length of the entire file, in bytes. - For the length of the buffer, see bufferLength - */ - int64 m_length; - - /** Length of the array referenced by buffer. May go past the end of the file!*/ - int64 m_bufferLength; - uint8* m_buffer; - - /** - Next byte in file, relative to buffer. - */ - int64 m_pos; - - /** - When true, the buffer is freed in the destructor. - */ - bool m_freeBuffer; - - /** Ensures that we are able to read at least minLength from startPosition (relative - to start of file). */ - void loadIntoMemory(int64 startPosition, int64 minLength = 0); - - /** Verifies that at least this number of bytes can be read.*/ - inline void prepareToRead(int64 nbytes) { - debugAssertM(m_length > 0, m_filename + " not found or corrupt."); - debugAssertM(m_pos + nbytes + m_alreadyRead <= m_length, "Read past end of file."); - - if (m_pos + nbytes > m_bufferLength) { - loadIntoMemory(m_pos + m_alreadyRead, nbytes); - } - } - - // Not implemented on purpose, don't use - BinaryInput(const BinaryInput&); - BinaryInput& operator=(const BinaryInput&); - bool operator==(const BinaryInput&); - - /** Buffer is compressed; replace it with a decompressed version */ - void decompress(); -public: - - /** false, constant to use with the copyMemory option */ - static const bool NO_COPY; - - /** - If the file cannot be opened, a zero length buffer is presented. - Automatically opens files that are inside zipfiles. - - @param compressed Set to true if and only if the file was - compressed using BinaryOutput's zlib compression. This has - nothing to do with whether the input is in a zipfile. - */ - BinaryInput( - const std::string& filename, - G3DEndian fileEndian, - bool compressed = false); - - /** - Creates input stream from an in memory source. - Unless you specify copyMemory = false, the data is copied - from the pointer, so you may deallocate it as soon as the - object is constructed. It is an error to specify copyMemory = false - and compressed = true. - - To decompress part of a file, you can follow the following paradigm: - -
-        BinaryInput master(...);
-
-        // read from master to point where compressed data exists.
-
-        BinaryInput subset(master.getCArray() + master.getPosition(), 
-                           master.length() - master.getPosition(),
-                           master.endian(), true, true);
-
-        // Now read from subset (it is ok for master to go out of scope)
-     
- */ - BinaryInput( - const uint8* data, - int64 dataLen, - G3DEndian dataEndian, - bool compressed = false, - bool copyMemory = true); - - virtual ~BinaryInput(); - - /** Change the endian-ness of the file. This only changes the - interpretation of the file for future read calls; the - underlying data is unmodified.*/ - void setEndian(G3DEndian endian); - - G3DEndian endian() const { - return m_fileEndian; - } - - std::string getFilename() const { - return m_filename; - } - - /** - Returns a pointer to the internal memory buffer. - May throw an exception for huge files. - */ - const uint8* getCArray() const { - if (m_alreadyRead > 0) { - throw "Cannot getCArray for a huge file"; - } - return m_buffer; - } - - /** - Performs bounds checks in debug mode. [] are relative to - the start of the file, not the current position. - Seeks to the new position before reading (and leaves - that as the current position) - */ - inline uint8 operator[](int64 n) { - setPosition(n); - return readUInt8(); - } - - /** - Returns the length of the file in bytes. - */ - inline int64 getLength() const { - return m_length; - } - - inline int64 size() const { - return getLength(); - } - - /** - Returns the current byte position in the file, - where 0 is the beginning and getLength() - 1 is the end. - */ - inline int64 getPosition() const { - return m_pos + m_alreadyRead; - } - - /** - Sets the position. Cannot set past length. - May throw a char* when seeking backwards more than 10 MB on a huge file. - */ - inline void setPosition(int64 p) { - debugAssertM(p <= m_length, "Read past end of file"); - m_pos = p - m_alreadyRead; - if ((m_pos < 0) || (m_pos > m_bufferLength)) { - loadIntoMemory(m_pos + m_alreadyRead); - } - } - - /** - Goes back to the beginning of the file. - */ - inline void reset() { - setPosition(0); - } - - inline int8 readInt8() { - prepareToRead(1); - return m_buffer[m_pos++]; - } - - inline bool readBool8() { - return (readInt8() != 0); - } - - inline uint8 readUInt8() { - prepareToRead(1); - return ((uint8*)m_buffer)[m_pos++]; - } - - uint16 inline readUInt16() { - prepareToRead(2); - - m_pos += 2; - if (m_swapBytes) { - uint8 out[2]; - out[0] = m_buffer[m_pos - 1]; - out[1] = m_buffer[m_pos - 2]; - return *(uint16*)out; - } else { - #ifdef G3D_ALLOW_UNALIGNED_WRITES - return *(uint16*)(&m_buffer[m_pos - 2]); - #else - uint8 out[2]; - out[0] = m_buffer[m_pos - 2]; - out[1] = m_buffer[m_pos - 1]; - return *(uint16*)out; - #endif - } - - } - - inline int16 readInt16() { - uint16 a = readUInt16(); - return *(int16*)&a; - } - - inline uint32 readUInt32() { - prepareToRead(4); - - m_pos += 4; - if (m_swapBytes) { - uint8 out[4]; - out[0] = m_buffer[m_pos - 1]; - out[1] = m_buffer[m_pos - 2]; - out[2] = m_buffer[m_pos - 3]; - out[3] = m_buffer[m_pos - 4]; - return *(uint32*)out; - } else { - #ifdef G3D_ALLOW_UNALIGNED_WRITES - return *(uint32*)(&m_buffer[m_pos - 4]); - #else - uint8 out[4]; - out[0] = m_buffer[m_pos - 4]; - out[1] = m_buffer[m_pos - 3]; - out[2] = m_buffer[m_pos - 2]; - out[3] = m_buffer[m_pos - 1]; - return *(uint32*)out; - #endif - } - } - - - inline int32 readInt32() { - uint32 a = readUInt32(); - return *(int32*)&a; - } - - uint64 readUInt64(); - - inline int64 readInt64() { - uint64 a = readUInt64(); - return *(int64*)&a; - } - - inline float32 readFloat32() { - union { - uint32 a; - float32 b; - }; - a = readUInt32(); - return b; - } - - inline float64 readFloat64() { - union { - uint64 a; - float64 b; - }; - a = readUInt64(); - return b; - } - - void readBytes(void* bytes, int64 n); - - /** - Reads an n character string. The string is not - required to end in NULL in the file but will - always be a proper std::string when returned. - */ - std::string readString(int64 n); - - /** - Reads until NULL or the end of the file is encountered. - */ - std::string readString(); - - /** - Reads until NULL or the end of the file is encountered. - If the string has odd length (including NULL), reads - another byte. - */ - std::string readStringEven(); - - - std::string readString32(); - - Vector4 readVector4(); - Vector3 readVector3(); - Vector2 readVector2(); - - Color4 readColor4(); - Color3 readColor3(); - - /** - Skips ahead n bytes. - */ - inline void skip(int64 n) { - setPosition(m_pos + m_alreadyRead + n); - } - - /** - Returns true if the position is not at the end of the file - */ - inline bool hasMore() const { - return m_pos + m_alreadyRead < m_length; - } - - /** Prepares for bit reading via readBits. Only readBits can be - called between beginBits and endBits without corrupting the - data stream. */ - void beginBits(); - - /** Can only be called between beginBits and endBits */ - uint32 readBits(int numBits); - - /** Ends bit-reading. */ - void endBits(); - -# define DECLARE_READER(ucase, lcase)\ - void read##ucase(lcase* out, int64 n);\ - void read##ucase(std::vector& out, int64 n);\ - void read##ucase(Array& out, int64 n); - - DECLARE_READER(Bool8, bool) - DECLARE_READER(UInt8, uint8) - DECLARE_READER(Int8, int8) - DECLARE_READER(UInt16, uint16) - DECLARE_READER(Int16, int16) - DECLARE_READER(UInt32, uint32) - DECLARE_READER(Int32, int32) - DECLARE_READER(UInt64, uint64) - DECLARE_READER(Int64, int64) - DECLARE_READER(Float32, float32) - DECLARE_READER(Float64, float64) -# undef DECLARE_READER -}; - - -} - -#ifdef _MSC_VER -# pragma warning(pop) -#endif - -#endif diff --git a/externals/g3dlite/G3D/BinaryOutput.h b/externals/g3dlite/G3D/BinaryOutput.h deleted file mode 100644 index d81ec56a67b..00000000000 --- a/externals/g3dlite/G3D/BinaryOutput.h +++ /dev/null @@ -1,421 +0,0 @@ -/** - @file BinaryOutput.h - - @maintainer Morgan McGuire, graphics3d.com - - @created 2001-08-09 - @edited 2008-01-24 - - Copyright 2000-2006, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_BINARYOUTPUT_H -#define G3D_BINARYOUTPUT_H - -#include "G3D/platform.h" -#include -#include -#include -#include -#include -#include "G3D/Color4.h" -#include "G3D/Color3.h" -#include "G3D/Vector4.h" -#include "G3D/Vector3.h" -#include "G3D/Vector2.h" -#include "G3D/g3dmath.h" -#include "G3D/debug.h" -#include "G3D/BinaryInput.h" -#include "G3D/System.h" - -#ifdef _MSC_VER -# pragma warning (push) -// Conditional is constant (wrong in inline) -# pragma warning (disable : 4127) -#endif -namespace G3D { - -/** - Sequential or random access byte-order independent binary file access. - - The compress() call can be used to compress with zlib. - - Any method call can trigger an out of memory error (thrown as char*) - when writing to "" instead of a file. - - Compressed writing and seeking backwards is not supported for huge files - (i.e., BinaryOutput may have to dump the contents to disk if they - exceed available RAM). - */ -class BinaryOutput { -private: - std::string m_filename; - - bool m_committed; - - /** 0 outside of beginBits...endBits, 1 inside */ - int m_beginEndBits; - - /** The current string of bits being built up by beginBits...endBits. - This string is treated semantically, as if the lowest bit was - on the left and the highest was on the right.*/ - int8 m_bitString; - - /** Position (from the lowest bit) currently used in bitString.*/ - int m_bitPos; - - // True if the file endianess does not match the machine endian - bool m_swapBytes; - - G3DEndian m_fileEndian; - - uint8* m_buffer; - - /** Size of the elements used */ - int m_bufferLen; - - /** Underlying size of memory allocaded */ - int m_maxBufferLen; - - /** Next byte in file */ - int m_pos; - - /** is this initialized? */ - bool m_init; - - /** Number of bytes already written to the file.*/ - size_t m_alreadyWritten; - - bool m_ok; - - void reserveBytesWhenOutOfMemory(size_t bytes); - - void reallocBuffer(size_t bytes, size_t oldBufferLen); - - /** - Make sure at least bytes can be written, resizing if - necessary. - */ - inline void reserveBytes(int bytes) { - debugAssert(bytes > 0); - size_t oldBufferLen = (size_t)m_bufferLen; - - m_bufferLen = iMax(m_bufferLen, (m_pos + bytes)); - if (m_bufferLen > m_maxBufferLen) { - reallocBuffer(bytes, oldBufferLen); - } - } - - // Not implemented on purpose, don't use - BinaryOutput(const BinaryOutput&); - BinaryOutput& operator=(const BinaryOutput&); - bool operator==(const BinaryOutput&); - -public: - - /** - You must call setEndian() if you use this (memory) constructor. - */ - BinaryOutput(); - - /** - Doesn't actually open the file; commit() does that. - Use "" as the filename if you're going to commit - to memory. - */ - BinaryOutput( - const std::string& filename, - G3DEndian fileEndian); - - ~BinaryOutput(); - - /** Compresses the data in the buffer in place, - preceeding it with a little-endian uint32 indicating - the uncompressed size. - - Call immediately before commit(). - - Cannot be used for huge files (ones where the data - was already written to disk)-- will throw char*. - */ - void compress(); - - /** True if no errors have been encountered.*/ - bool ok() const; - - /** - Returns a pointer to the internal memory buffer. - */ - inline const uint8* getCArray() const { - return m_buffer; - } - - void setEndian(G3DEndian fileEndian); - - G3DEndian endian() const { - return m_fileEndian; - } - - std::string getFilename() const { - return m_filename; - } - - /** - Write the bytes to disk. It is ok to call this - multiple times; it will just overwrite the previous file. - - Parent directories are created as needed if they do - not exist. - - Not called from the destructor; you must call - it yourself. - - @param flush If true (default) the file is ready for reading when the method returns, otherwise - the method returns immediately and writes the file in the background. - */ - void commit(bool flush = true); - - /** - Write the bytes to memory (which must be of - at least size() bytes). - */ - void commit(uint8*); - - /** - A memory BinaryOutput may be reset so that it can be written to again - without allocating new memory. The underlying array will not be deallocated, - but the reset structure will act like a newly intialized one. - */ - void reset(); - - - inline int length() const { - return (int)m_bufferLen + (int)m_alreadyWritten; - } - - inline int size() const { - return length(); - } - - /** - Sets the length of the file to n, padding - with 0's past the current end. Does not - change the position of the next byte to be - written unless n < size(). - - Throws char* when resetting a huge file to be shorter - than its current length. - */ - inline void setLength(int n) { - n = n - (int)m_alreadyWritten; - - if (n < 0) { - throw "Cannot resize huge files to be shorter."; - } - - if (n < m_bufferLen) { - m_pos = n; - } - if (n > m_bufferLen) { - reserveBytes(n - m_bufferLen); - } - } - - /** - Returns the current byte position in the file, - where 0 is the beginning and getLength() - 1 is the end. - */ - inline int64 position() const { - return (int64)m_pos + (int64)m_alreadyWritten; - } - - - /** - Sets the position. Can set past length, in which case - the file is padded with zeros up to one byte before the - next to be written. - - May throw a char* exception when seeking backwards on a huge file. - */ - inline void setPosition(int64 p) { - p = p - (int64)m_alreadyWritten; - - if (p > m_bufferLen) { - setLength((int)(p + (int64)m_alreadyWritten)); - } - - if (p < 0) { - throw "Cannot seek more than 10 MB backwards on huge files."; - } - - m_pos = (int)p; - } - - - void writeBytes( - const void* b, - int count) { - - reserveBytes(count); - debugAssert(m_pos >= 0); - debugAssert(m_bufferLen >= count); - System::memcpy(m_buffer + m_pos, b, count); - m_pos += count; - } - - /** - Writes a signed 8-bit integer to the current position. - */ - inline void writeInt8(int8 i) { - reserveBytes(1); - m_buffer[m_pos] = *(uint8*)&i; - m_pos++; - } - - inline void writeBool8(bool b) { - writeInt8(b ? 1 : 0); - } - - inline void writeUInt8(uint8 i) { - reserveBytes(1); - m_buffer[m_pos] = i; - m_pos++; - } - - void writeUInt16(uint16 u); - - inline void writeInt16(int16 i) { - writeUInt16(*(uint16*)&i); - } - - void writeUInt32(uint32 u); - - inline void writeInt32(int32 i) { - debugAssert(m_beginEndBits == 0); - writeUInt32(*(uint32*)&i); - } - - void writeUInt64(uint64 u); - - inline void writeInt64(int64 i) { - writeUInt64(*(uint64*)&i); - } - - inline void writeFloat32(float32 f) { - debugAssert(m_beginEndBits == 0); - union { - float32 a; - uint32 b; - }; - a = f; - writeUInt32(b); - } - - inline void writeFloat64(float64 f) { - union { - float64 a; - uint64 b; - }; - a = f; - writeUInt64(b); - } - - /** - Write a string with NULL termination. - */ - inline void writeString(const std::string& s) { - writeString(s.c_str()); - } - - void writeString(const char* s); - - /** - Write a string, ensuring that the total length - including NULL is even. - */ - void writeStringEven(const std::string& s) { - writeStringEven(s.c_str()); - } - - void writeStringEven(const char* s); - - - void writeString32(const char* s); - - /** - Write a string with a 32-bit length field in front - of it. - */ - void writeString32(const std::string& s) { - writeString32(s.c_str()); - } - - void writeVector4(const Vector4& v); - - void writeVector3(const Vector3& v); - - void writeVector2(const Vector2& v); - - void writeColor4(const Color4& v); - - void writeColor3(const Color3& v); - - /** - Skips ahead n bytes. - */ - inline void skip(int n) { - if (m_pos + n > m_bufferLen) { - setLength((int)m_pos + (int)m_alreadyWritten + n); - } - m_pos += n; - } - - /** Call before a series of BinaryOutput::writeBits calls. Only writeBits - can be called between beginBits and endBits without corrupting the stream.*/ - void beginBits(); - - /** Write numBits from bitString to the output stream. Bits are numbered from - low to high. - - Can only be - called between beginBits and endBits. Bits written are semantically - little-endian, regardless of the actual endian-ness of the system. That is, - writeBits(0xABCD, 16) writes 0xCD to the first byte and - 0xAB to the second byte. However, if used with BinaryInput::readBits, the ordering - is transparent to the caller. - */ - void writeBits(uint32 bitString, int numBits); - - /** Call after a series of BinaryOutput::writeBits calls. This will - finish out with zeros the last byte into which bits were written.*/ - void endBits(); - - -# define DECLARE_WRITER(ucase, lcase)\ - void write##ucase(const lcase* out, int n);\ - void write##ucase(const std::vector& out, int n);\ - void write##ucase(const Array& out, int n); - - DECLARE_WRITER(Bool8, bool) - DECLARE_WRITER(UInt8, uint8) - DECLARE_WRITER(Int8, int8) - DECLARE_WRITER(UInt16, uint16) - DECLARE_WRITER(Int16, int16) - DECLARE_WRITER(UInt32, uint32) - DECLARE_WRITER(Int32, int32) - DECLARE_WRITER(UInt64, uint64) - DECLARE_WRITER(Int64, int64) - DECLARE_WRITER(Float32, float32) - DECLARE_WRITER(Float64, float64) -# undef DECLARE_WRITER - -}; - -} - -#ifdef _MSC_VER -# pragma warning (pop) -#endif - -#endif diff --git a/externals/g3dlite/G3D/BoundsTrait.h b/externals/g3dlite/G3D/BoundsTrait.h deleted file mode 100644 index 15e1418010c..00000000000 --- a/externals/g3dlite/G3D/BoundsTrait.h +++ /dev/null @@ -1,20 +0,0 @@ -/** - @file BoundsTrait.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - @created 2008-10-01 - @edited 2008-10-01 - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_BOUNDSTRAIT_H -#define G3D_BOUNDSTRAIT_H - -#include "G3D/platform.h" - -template -struct BoundsTrait{}; - -#endif - diff --git a/externals/g3dlite/G3D/Box.h b/externals/g3dlite/G3D/Box.h deleted file mode 100644 index 82af9125b05..00000000000 --- a/externals/g3dlite/G3D/Box.h +++ /dev/null @@ -1,195 +0,0 @@ -/** - @file Box.h - - Box class - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @cite Portions based on Dave Eberly's Magic Software Library at http://www.magic-software.com - @created 2001-06-02 - @edited 2007-06-05 - - Copyright 2000-2006, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_BOX_H -#define G3D_BOX_H - -#include "G3D/platform.h" -#include "G3D/Vector3.h" -#include "G3D/Array.h" -#include "G3D/Plane.h" - -namespace G3D { - -class CoordinateFrame; - -/** - An arbitrary 3D box, useful as a bounding box. - - - To construct a box from a coordinate frame, center and extent, use the idiom: - - Box box = cframe.toObjectSpace(Box(center - extent/2, center + extent/2)); - */ -class Box { -private: - - static int32 dummy; - - friend class CoordinateFrame; - - /** -
-       3    2       7    6
-    
-       0    1       4    5
-
-       front    back (seen through front)
-      
- */ - Vector3 _corner[8]; - - /** - Unit axes. - */ - Vector3 _axis[3]; - - Vector3 _center; - - /** - Extent along each axis. - */ - Vector3 _extent; - - float _area; - float _volume; - - void init( - const Vector3& min, - const Vector3& max); - -public: - - /** - Does not initialize the fields. - */ - Box(); - - /** - Constructs a box from two opposite corners. - */ - Box( - const Vector3& min, - const Vector3& max); - - static Box inf(); - - Box(class BinaryInput& b); - - Box(const class AABox& b); - - void serialize(class BinaryOutput& b) const; - void deserialize(class BinaryInput& b); - - /** - Returns the object to world transformation for - this box. localFrame().worldToObject(...) takes - objects into the space where the box axes are - (1,0,0), (0,1,0), (0,0,1). Note that there - is no scaling in this transformation. - */ - CoordinateFrame localFrame() const; - - void getLocalFrame(CoordinateFrame& frame) const; - - /** - Returns the centroid of the box. - */ - inline Vector3 center() const { - return _center; - } - - - inline Vector3 corner(int i) const { - debugAssert(i < 8); - return _corner[i]; - } - - /** - Unit length. - */ - inline Vector3 axis(int a) const { - debugAssert(a < 3); - return _axis[a]; - } - - /** - Distance from corner(0) to the next corner - along the box's local axis a. - */ - inline float extent(int a) const { - debugAssert(a < 3); - return (float)_extent[a]; - } - - inline Vector3 extent() const { - return _extent; - } - - /** - Returns the four corners of a face (0 <= f < 6). - The corners are returned to form a counter clockwise quad facing outwards. - */ - void getFaceCorners( - int f, - Vector3& v0, - Vector3& v1, - Vector3& v2, - Vector3& v3) const; - - - /** - See AABox::culledBy - */ - bool culledBy - ( - const Array& plane, - int32& cullingPlaneIndex, - const uint32 testMask, - uint32& childMask) const; - - /** - Conservative culling test that does not produce a mask for children. - */ - bool culledBy - ( - const Array& plane, - int32& cullingPlaneIndex = dummy, - const uint32 testMask = -1) const; - - bool contains( - const Vector3& point) const; - - float area() const; - - float volume() const; - - void getRandomSurfacePoint(Vector3& P, Vector3& N = Vector3::ignore()) const; - - /** - Uniformly distributed on the interior (includes surface) - */ - Vector3 randomInteriorPoint() const; - - void getBounds(class AABox&) const; - - bool isFinite() const { - return G3D::isFinite(_volume); - } -}; - -} - -#endif diff --git a/externals/g3dlite/G3D/Box2D.h b/externals/g3dlite/G3D/Box2D.h deleted file mode 100644 index 80accad89dd..00000000000 --- a/externals/g3dlite/G3D/Box2D.h +++ /dev/null @@ -1,121 +0,0 @@ -/** - @file Box2D.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2001-06-02 - @edited 2008-12-27 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_Box2D_h -#define G3D_Box2D_h - -#include "G3D/platform.h" -#include "G3D/Vector2.h" - -namespace G3D { - -class CoordinateFrame; -typedef class CoordinateFrame CFrame; -class Rect2D; -typedef class Rect2D AABox2D; - -/** - 2D oriented box - @cite http://www.flipcode.com/archives/2D_OBB_Intersection.shtml - */ -class Box2D { -private: - /** Corners of the box, where 0 is the lower left. */ - Vector2 m_corner[4]; - - /** Two edges of the box extended away from corner[0], with length - = 1 / extentSquared */ - Vector2 m_axisin[2]; - - /** Two edges of the box extended away from corner[0], with unit length */ - Vector2 m_axis[2]; - - /** Centroid of the box */ - Vector2 m_center; - - /** origin[a] = m_corner[0].dot(m_axisin[a]); */ - float origin[2]; - - /** Surface area */ - float m_area; - - Vector2 m_extent; - - /** Returns true if other overlaps one dimension of this. */ - bool overlaps1Way(const Box2D& other) const; - - - /** Updates the axes after the m_corners move. Assumes the - m_corners actually form a rectangle. */ - void computeAxes(); - -public: - - /** - @param center World-space center - @param w Width along object-space x-axis - @param h Height along object-space y-axis - @param angle Counter-clockwise angle from object-space x-axis in radians - */ - Box2D(const Vector2& center = Vector2(0, 0), float w = 0, float h = 0, float angle = 0); - - Box2D(const AABox2D& b); - - Box2D(const Vector2& min, const Vector2& max); - - /** Transform @a b by @a frame, discarding the Z components, and - compute the new box.*/ - Box2D(const CFrame& frame, Box2D& b); - - inline bool contains(const Vector2& v) const { - // Take to object space: - const Vector2& p = v - m_center; - float x = p.dot(m_axisin[0]); - float y = p.dot(m_axisin[1]); - - // Must be within extent/2 on both axes in object space - return (abs(x) <= 0.5f) && (abs(y) <= 0.5f); - } - - /** @brief Distance from corner(0) to the next corner along the box's local axis a. */ - inline const Vector2& extent() const { - return m_extent; - } - - /** @brief Unit length vector along axis @a a */ - inline const Vector2& axis(int a) const { - debugAssert(a == 0 || a == 1); - return m_axis[a]; - } - - /** @brief Surface area */ - inline float area() const { - return m_area; - } - - inline const Vector2& corner(int i) const { - debugAssert(i >=0 && i <= 3); - return m_corner[i]; - } - - inline const Vector2& center() const { - return m_center; - } - - /** Returns true if the intersection of the boxes is non-empty. */ - inline bool overlaps(const Box2D& other) const { - return overlaps1Way(other) && other.overlaps1Way(*this); - } -}; - -} // G3D -#endif diff --git a/externals/g3dlite/G3D/BumpMapPreprocess.h b/externals/g3dlite/G3D/BumpMapPreprocess.h deleted file mode 100644 index 955f99e61b2..00000000000 --- a/externals/g3dlite/G3D/BumpMapPreprocess.h +++ /dev/null @@ -1,61 +0,0 @@ -/** - \file BumpMapPreprocess.h - - \maintainer Morgan McGuire, http://graphics.cs.williams.edu - - \created 2010-01-28 - \edited 2010-01-28 - - Copyright 2000-2010, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_BumpMapPreprocess_h -#define G3D_BumpMapPreprocess_h - -#include "G3D/platform.h" - -namespace G3D { -class Any; - -/** -Not in the BumpMap class to avoid a circular dependency between Texture and BumpMap. -G3D::GImage::computeNormalMap(). -*/ -class BumpMapPreprocess { -public: - - /** If true, the elevations are box filtered after computing normals - and before uploading, which produces better results for parallax offset mapping - Defaults to false. */ - bool lowPassFilter; - - /** Height of the maximum ("white") value, in pixels, for the purpose of computing normals. - A value of 255 means that a 255 x 255 bump image with a full black-to-white gradient - will produce a 45-degree ramp (this also results in "cubic" voxels). - A negative value means to set zExtentPixels to -zExtentPixels * max(width, height). - The default is -0.02. - */ - float zExtentPixels; - - /** After computing normals, scale the height by |N.z|, a trick that reduces texture swim in steep areas for parallax offset - mapping. Defaults to false.*/ - bool scaleZByNz; - - BumpMapPreprocess() : lowPassFilter(false), zExtentPixels(-0.02f), scaleZByNz(false) {} - - BumpMapPreprocess(const Any& any); - - operator Any() const; - - bool operator==(const BumpMapPreprocess& other) const { - return - (lowPassFilter == other.lowPassFilter) && - (zExtentPixels == other.zExtentPixels) && - (scaleZByNz == other.scaleZByNz); - } -}; - -} - -#endif diff --git a/externals/g3dlite/G3D/Capsule.h b/externals/g3dlite/G3D/Capsule.h deleted file mode 100644 index baeea3aa82b..00000000000 --- a/externals/g3dlite/G3D/Capsule.h +++ /dev/null @@ -1,90 +0,0 @@ -/** - @file Capsule.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2003-02-07 - @edited 2005-08-20 - - Copyright 2000-2006, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_CAPSULE_H -#define G3D_CAPSULE_H - -#include "G3D/platform.h" -#include "G3D/g3dmath.h" -#include "G3D/Vector3.h" - -namespace G3D { - -class Line; -class AABox; -/** - A shape formed by extruding a sphere along a line segment. - */ -class Capsule { -private: - Vector3 p1; - Vector3 p2; - - float _radius; -public: - - - /** Uninitialized */ - Capsule(); - Capsule(class BinaryInput& b); - Capsule(const Vector3& _p1, const Vector3& _p2, float _r); - void serialize(class BinaryOutput& b) const; - void deserialize(class BinaryInput& b); - - /** The line down the center of the capsule */ - Line axis() const; - - inline float radius() const { - return _radius; - } - - /** Argument may be 0 or 1 */ - inline Vector3 point(int i) const { - debugAssert(i == 0 || i == 1); - return (i == 0) ? p1 : p2; - } - - /** Distance between the sphere centers. The total extent of the cylinder is - 2r + h. */ - inline float height() const { - return (p1 - p2).magnitude(); - } - - inline Vector3 center() const { - return (p1 + p2) / 2.0; - } - - /** Get a reference frame in which the center of mass is the origin and Y is the axis of the capsule.*/ - void getReferenceFrame(class CoordinateFrame& cframe) const; - - /** - Returns true if the point is inside the capsule or on its surface. - */ - bool contains(const Vector3& p) const; - - float volume() const; - - float area() const; - - /** Get axis aligned bounding box */ - void getBounds(AABox& out) const; - - /** Random world space point with outward facing normal. */ - void getRandomSurfacePoint(Vector3& P, Vector3& N) const; - - /** Point selected uniformly at random over the volume. */ - Vector3 randomInteriorPoint() const; -}; - -} // namespace - -#endif diff --git a/externals/g3dlite/G3D/CollisionDetection.h b/externals/g3dlite/G3D/CollisionDetection.h deleted file mode 100644 index c8fcf5534c2..00000000000 --- a/externals/g3dlite/G3D/CollisionDetection.h +++ /dev/null @@ -1,1205 +0,0 @@ -/** - @file CollisionDetection.h - - - Moving collision detection for simple primitives. - - @author Morgan McGuire, http://graphics.cs.williams.edu - @cite Spherical collision based on Paul Nettle's - ftp://ftp.3dmaileffects.com/pub/FluidStudios/CollisionDetection/Fluid_Studios_Generic_Collision_Detection_for_Games_Using_Ellipsoids.pdf - and comments by Max McGuire. Ray-sphere intersection by Eric Haines. - Box-Box intersection written by Kevin Egan. - Thanks to Max McGuire of Iron Lore for various bug fixes. - Box-Triangle by Tomas Akenine-Moller - - @created 2001-11-19 - @edited 2008-12-19 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_COLLISIONDETECTION_H -#define G3D_COLLISIONDETECTION_H - -#include "G3D/platform.h" -#include "G3D/Vector3.h" -#include "G3D/Plane.h" -#include "G3D/Box.h" -#include "G3D/Triangle.h" -#include "G3D/Array.h" -#include "G3D/Ray.h" -#include "G3D/Line.h" - -namespace G3D { - - -/** - Collision detection primitives and tools for building - higher order collision detection schemes. - - These routines provide moving and static collision detection. - Moving collision detection allows the calculation of collisions that - occur during a period of time -- as opposed to the intersection of - two static bodies. - - Moving collision detection routines detect collisions between - only static primitives and moving spheres or points. Since the - reference frame can be user defined, these functions can be used to - detect the collision between two moving bodies by subtracting - the velocity vector of one object from the velocity vector of the - sphere or point the detection is to occur with. This unified - velocity vector will act as if both objects are moving simultaneously. - - Collisions are detected for single-sided objects only. That is, - no collision is detected when leaving a primitive or passing - through a plane or triangle opposite the normal... except for the - point-sphere calculation or when otherwise noted. - - For a sphere, the collision location returned is the point in world - space where the surface of the sphere and the fixed object meet. - It is not the position of the center of the sphere at - the time of the collision. - - The collision normal returned is the surface normal to the fixed - object at the collision location. - -

- Static Collision Detection: (Neither object is moving) - - - - - - - - - - - - - - -
Vector3LineSegmentRay *LinePlaneTriangleSphereCylinderCapsuleAABoxBox
Vector3\link Vector3::operator== V3::==\endlink \link Vector3::fuzzyEq V3::fuzzy \endlink \link G3D::distance distance \endlink
LineSegment\link LineSegment::closestPoint LS::closestPoint\endlink \link LineSegment::distance LS::distance\endlink \link CollisionDetection::closestPointOnLineSegment CD\endlink
Ray *Ray::closestPoint Ray::distance
LineLine::closestPoint Line::distance\link CollisionDetection::closestPointsBetweenLineAndLine CD\endlink
Plane
Triangle
SphereSphere::contains\link CollisionDetection::collisionTimeForMovingPointFixedSphere CD \endlink, \link Ray::intersectionTime R::time\endlink
CylinderCylinder::contains
CapsuleCapsule::contains
AABoxAABox::contains\link CollisionDetection::fixedSolidBoxIntersectsFixedTriangle CD\endlink
BoxBox::contains(treat as Ray)\link CollisionDetection::collisionTimeForMovingPointFixedBox CD\endlink(treat as Ray)\link CollisionDetection::penetrationDepthForFixedBoxFixedPlane CD \endlink\link CollisionDetection::penetrationDepthForFixedBoxFixedPlane CD\endlink\link CollisionDetection::penetrationDepthForFixedSphereFixedBox CD\endlinkNone (use OPCODE)\link CollisionDetection::movingSpherePassesThroughFixedBox CD \endlink\link CollisionDetection::penetrationDepthForFixedBoxFixedBox CD\endlink\link CollisionDetection::penetrationDepthForFixedBoxFixedBox CD\endlink
- -

- Moving Collision Detection: - - * Note: Moving collision detection against certain primitives is equivalent to static collision - detection against a bigger primitive. Ray, Line Segment == ``moving Point''; Capsule ==``moving Sphere''; Plane == ``moving Line'' - - @deprecated Routines moving to the G3D::Intersect class in G3D 8.0 - */ -class CollisionDetection { -private: - - /** - Default parameter if value passed to a function as reference is - not to be calculated. Must be explicitly supported by function. - */ - static Vector3 ignore; - - /** - Default parameter if value passed to a function as reference is - not to be calculated. Must be explicitly supported by function. - */ - static bool ignoreBool; - - /** - Default parameter if value passed to a function as reference is - not to be calculated. Must be explicitly supported by function. - */ - static Array ignoreArray; - - - // Static class! - CollisionDetection() {} - virtual ~CollisionDetection() {} - -public: - - /** - Converts an index [0, 15] to the corresponding separating axis. - Does not return normalized vector in the edge-edge case - (indices 6 through 15). - - @param separatingAxisIndex Separating axis. - @param box1 Box 1. - @param box2 Box 2. - - @return Axis that separates the two boxes. - */ - static Vector3 separatingAxisForSolidBoxSolidBox( - const int separatingAxisIndex, - const Box & box1, - const Box & box2); - - /** - Tests whether two boxes have axes that are parallel to - each other. If they are, axis1 and axis2 are set to be - the parallel axes for both box1 and box2 respectively. - - @param ca Dot products of each of the boxes axes - @param epsilon Fudge factor (small unit by which the dot - products may vary and still be considered - zero). - @param axis1 Parallel Axis 1. [Post Condition] - @param axis2 Parallel Axis 2. [Post Condition] - - @return true - If boxes have a parallel axis - @return false - otherwise. - */ - static bool parallelAxisForSolidBoxSolidBox( - const double* ca, - const double epsilon, - int & axis1, - int & axis2); - - /** - Calculates the projected distance between the two boxes along - the specified separating axis, negative distances correspond - to an overlap along that separating axis. The distance is not - divided by denominator dot(L, L), see - penetrationDepthForFixedSphereFixedBox() for more details - - @param separatingAxisIndex - @param a Box 1's bounding sphere vector - @param b Box 2's bounding sphere vector - @param D Vector between Box 1 and Box 2's center points - @param c Pointer to array of dot products of the axes of Box 1 - and Box 2. - @param ca Pointer to array of unsigned dot products of the axes - of Box 1 and Box 2. - @param ad Pointer to array of dot products of Box 1 axes and D. - @param bd Pointer to array of dot products of Box 2 axes and D. - - @return Projected distance between the two boxes along the - specified separating axis. - */ - static float projectedDistanceForSolidBoxSolidBox( - const int separatingAxisIndex, - const Vector3 & a, - const Vector3 & b, - const Vector3 & D, - const double* c, - const double* ca, - const double* ad, - const double* bd); - - - /** - Creates a set of standard information about two boxes in order to - solve for their collision. This information includes a vector to - the radius of the bounding sphere for each box, the vector between - each boxes' center and a series of dot products between differing - important vectors. These dot products include those between the axes - of both boxes (signed and unsigned values), and the dot products - between all the axes of box1 and the boxes' center vector and box2 - and the boxes' center vector. - - @pre The following space requirements must be met: - - c[] 9 elements - - ca[] 9 elements - - ad[] 3 elements - - bd[] 3 elements - - @cite dobted from David Eberly's papers, variables used in this function - correspond to variables used in pages 6 and 7 in the pdf - http://www.magic-software.com/Intersection.html - http://www.magic-software.com/Documentation/DynamicCollisionDetection.pdf - - @note Links are out-dated. (Kept to preserve origin and authorship) - - @param box1 Box 1 - @param box2 Box 2 - @param a Box 1's bounding sphere vector - @param b Box 2's bounding sphere vector - @param D Vector between Box 1 and Box 2's center points - @param c Pointer to array of dot products of the axes of Box 1 - and Box 2. - @param ca Pointer to array of unsigned dot products of the axes - of Box 1 and Box 2. - @param ad Pointer to array of dot products of Box 1 axes and D. - @param bd Pointer to array of dot products of Box 2 axes and D. - */ - static void fillSolidBoxSolidBoxInfo( - const Box & box1, - const Box & box2, - Vector3 & a, - Vector3 & b, - Vector3 & D, - double* c, - double* ca, - double* ad, - double* bd); - - /** - Performs a simple bounding sphere check between two boxes to determine - whether these boxes could possibly intersect. This is a very - cheap operation (three dot products, two sqrts and a few others). If - it returns true, an intersection is possible, but not necessarily - guaranteed. - - @param a Vector from box A's center to an outer vertex - @param b Vector from box B's center to an outer vertex - @param D Distance between the centers of the two boxes - - @return true - if possible intersection - @return false - otherwise (This does not guarantee an intersection) - */ - static bool conservativeBoxBoxTest( - const Vector3 & a, - const Vector3 & b, - const Vector3 & D); - - /** - Determines whether two fixed solid boxes intersect. - - @note To speed up collision detection, the lastSeparatingAxis from - the previous time step can be passed in and that plane can be - checked first. If the separating axis was not saved, or if the - two boxes intersected then lastSeparatingAxis should equal -1. - - @cite Adobted from David Eberly's papers, variables used in this function - correspond to variables used in pages 6 and 7 in the pdf - http://www.magic-software.com/Intersection.html - http://www.magic-software.com/Documentation/DynamicCollisionDetection.pdf - - @param box1 Box 1. - @param box2 Box 2. - @param lastSeparatingAxis Last separating axis. - (optimization - see note) - - @return true - Intersection. - @return false - otherwise. - */ - static bool fixedSolidBoxIntersectsFixedSolidBox( - const Box& box1, - const Box& box2, - const int lastSeparatingAxis = -1); - - /** - Calculates the closest points on two lines with each other. If the - lines are parallel then using the starting point, else calculate the - closest point on each line to the other. - - @note This is very similiar to calculating the intersection of two lines. - Logically then, the two points calculated would be identical if calculated - with inifinite precision, but with the finite precision of floating point - calculations, these values could (will) differ as the line slope approaches - zero or inifinity. - - @cite variables and algorithm based on derivation at the following website: - http://softsurfer.com/Archive/algorithm_0106/algorithm_0106.htm - - @param line1 Line 1. - @param line2 Line 2. - @param closest1 Closest point on line 1. - @param closest2 Closest point on line 2. - */ - static void closestPointsBetweenLineAndLine( - const Line & line1, - const Line & line2, - Vector3 & closest1, - Vector3 & closest2); - - /** - Calculates the depth of penetration between two fixed boxes. - Contact normal faces away from box1 and into box2. If there is - contact, only one contact point is returned. The minimally - violated separating plane is computed - - if the separating axis corresponds to a face - the contact point is half way between the deepest vertex - and the face - - if the separating axis corresponds to two edges - the contact point is the midpoint of the smallest line - segment between the two edge lines - - @note This is very similiar to calculating the intersection of two lines. - Logically then, the two points calculated would be identical if calculated - with inifinite precision, but with the finite precision of floating point - calculations, these values could (will) differ as the line slope approaches - zero or inifinity. - - @cite adobted from David Eberly's papers, variables used in this function - correspond to variables used in pages 6 and 7 in the pdf - http://www.magic-software.com/Intersection.html - http://www.magic-software.com/Documentation/DynamicCollisionDetection.pdf - - @param box1 Box 1 - @param box2 Box 2 - @param contactPoints Contact point between boxes. [Post Condition] - @param contactNormals Surface normal at contact point. [Post Condition] - @param lastSeparatingAxis Last separating axis. (Used for optimization) - - @return Depth of penetration between the two boxes. If there is no - intersection between the boxes, then a negative value is returned. - */ - static float penetrationDepthForFixedBoxFixedBox( - const Box& box1, - const Box& box2, - Array& contactPoints, - Array& contactNormals, - const int lastSeparatingAxis = -1); - - /** - Calculates the depth of penetration between two fixed spheres as well - as the deepest point of Sphere A that penetrates Sphere B. The normal - returned points away from the object A, although it may - represent a perpendicular to either the faces of object B or object A - depending on their relative orientations. - - @param sphereA Fixed Sphere A. - @param sphereB Fixed Sphere B. - @param contactPoints Sphere A's deepest point that penetrates Sphere B. - [Post Condition] - @param contactNormals Normal at penetration point. [Post Condition] - - @return Depth of penetration. If there is no intersection between the - objects then the depth will be a negative value. - */ - static float penetrationDepthForFixedSphereFixedSphere( - const class Sphere& sphereA, - const Sphere& sphereB, - Array& contactPoints, - Array& contactNormals = ignoreArray); - - /** - Calculates the depth of penetration between a fixed sphere and a fixed - box as well as the deepest point of the sphere that penetrates the box - and the normal at that intersection. - - @note There are three possible intersections between a sphere and box. - - Sphere completely contained in the box - - Sphere intersects one edge - - Sphere intersects one vertex - - The contact point and contact normal vary for each of these situations. - - Sphere contained in Box: - - Normal is based on side of least penetration (as is the depth calculation). - - Point is based on center of sphere - - Sphere intersects one edge - - Normal is based on vector from the box center to the point of depth. - - Point is closest point to the sphere on the line - - Sphere intersects one vertex - - Normal is based on vector from the box center to the vertex of penetration. - - Point is vertex of penetration. - - @cite Adapted from Jim Arvo's method in Graphics Gems - See also http://www.win.tue.nl/~gino/solid/gdc2001depth.pdf - - @param sphere Fixed Sphere. - @param box Fixed Box. - @param contactPoints Sphere point that penetrates the box. [Post Condition] - @param contactNormals Normal at the penetration point. [Post Condition] - - @return Depth of penetration. If there is no intersection between the - objects then the depth will be a negative value. - */ - static float penetrationDepthForFixedSphereFixedBox( - const Sphere& sphere, - const Box& box, - Array& contactPoints, - Array& contactNormals = ignoreArray); - - /** - Calculates the depth of penetration between a Fixed Sphere and a Fixed - Plane as well as the deepest point of the sphere that penetrates the plane - and the plane normal at that intersection. - - @param sphereA Fixed Sphere. - @param planeB Fixed Plane. - @param contactPoints Sphere point that penetrates the plane. - [Post Condition] - @param contactNormals Normal at penetration point. [Post Condition] - - @return Depth of penetration. If there is no intersection between the - objects then the depth will be a negative value. - */ - static float penetrationDepthForFixedSphereFixedPlane( - const Sphere& sphereA, - const class Plane& planeB, - Array& contactPoints, - Array& contactNormals = ignoreArray); - - /** - Calculates the depth of penetration between a fixed box and a fixed - plane as well as the vertexes of the box that penetrate the plane - and the plane normals at those intersections. - - @param box Fixed Box. - @param plane Fixed Plane. - @param contactPoints Box points that penetrate the plane. - [Post Condition] - @param contactNormals Normals at penetration points [Post Condition] - - @return Depth of penetration. If there is no intersection between the - objects then the depth will be a negative value. - */ - static float penetrationDepthForFixedBoxFixedPlane( - const Box& box, - const Plane& plane, - Array& contactPoints, - Array& contactNormals = ignoreArray); - - /** - Calculates time between the intersection of a moving point and a fixed - plane. - - @note This is only a one sided collision test. The side defined by - the plane's surface normal is the only one tested. For a two sided - collision, call the function once for each side's surface normal. - - @param point Moving point. - @param velocity Point's velocity. - @param plane Fixed plane. - @param location Location of collision. [Post Condition] - (Infinite vector on no collision) - @param outNormal Plane's surface normal. [Post Condition] - - @return Time til collision. If there is no collision then the return - value will be inf(). - */ - static float collisionTimeForMovingPointFixedPlane( - const Vector3& point, - const Vector3& velocity, - const class Plane& plane, - Vector3& outLocation, - Vector3& outNormal = ignore); - - /** - Calculates time between the intersection of a moving point and a fixed - triangle. - - @note This is only a one sided collision test. The side defined by - the triangle's surface normal is the only one tested. For a two sided - collision, call the function once for each side's surface normal. - - @param orig Moving point. - @param dir Point's velocity. - @param v0 Triangle vertex 1. - @param v1 Triangle vertex 2. - @param v2 Triangle vertex 3 - - @return Time til collision. If there is no collision then the return - value will be inf(). - */ - inline static float collisionTimeForMovingPointFixedTriangle( - const Vector3& orig, - const Vector3& dir, - const Vector3& v0, - const Vector3& v1, - const Vector3& v2) { - return Ray::fromOriginAndDirection(orig, dir).intersectionTime(v0, v1, v2); - } - - /** - Calculates time between the intersection of a moving point and a fixed - triangle. - - @note This is only a one sided collision test. The side defined by - the triangle's surface normal is the only one tested. For a two sided - collision, call the function once for each side's surface normal. - - @param orig Moving point. - @param dir Point's velocity. - @param v0 Triangle vertex 1. - @param v1 Triangle vertex 2. - @param v2 Triangle vertex 3 - @param location Location of collision. [Post Condition] - (Infinite vector on no collision) - - @return Time til collision. If there is no collision then the return - value will be inf(). - */ - inline static float collisionTimeForMovingPointFixedTriangle( - const Vector3& orig, - const Vector3& dir, - const Vector3& v0, - const Vector3& v1, - const Vector3& v2, - Vector3& location) { - float t = collisionTimeForMovingPointFixedTriangle(orig, dir, v0, v1, v2); - if (t < finf()) { - location = orig + dir * t; - } - return t; - } - - /** - Calculates time between the intersection of a moving point and a fixed - triangle. - - @note This is only a one sided collision test. The side defined by - the triangle's surface normal is the only one tested. For a two sided - collision, call the function once for each side's surface normal. - - @param orig Moving point. - @param dir Point's velocity. - @param tri Fixed triangle. - @param location Location of collision. [Post Condition] - (Infinite vector on no collision) - @param normal Triangle's surface normal. [Post Condition] - - @return Time til collision. If there is no collision then the return - value will be inf(). - */ - inline static float collisionTimeForMovingPointFixedTriangle( - const Vector3& orig, - const Vector3& dir, - const Triangle& tri, - Vector3& location = ignore, - Vector3& normal = ignore) { - - float t = collisionTimeForMovingPointFixedTriangle( - orig, dir, tri.vertex(0), tri.vertex(1), tri.vertex(2)); - - if ((t < finf()) && (&location != &ignore)) { - location = orig + dir * t; - normal = tri.normal(); - } - return t; - } - - /** - Calculates time between the intersection of a moving point and a fixed - triangle. - - @note This is only a one sided collision test. The side defined by - the triangle's surface normal is the only one tested. For a two sided - collision, call the function once for each side's surface normal. - - @param orig Moving point. - @param dir Point's velocity. - @param v0 Triangle vertex 1. - @param v1 Triangle vertex 2. - @param v2 Triangle vertex 3 - @param location Location of collision. [Post Condition] - (Infinite vector on no collision) - @param normal Triangle's surface normal. [Post Condition] - - @return Time til collision. If there is no collision then the return - value will be inf(). - */ - inline static float collisionTimeForMovingPointFixedTriangle( - const Vector3& orig, - const Vector3& dir, - const Vector3& v0, - const Vector3& v1, - const Vector3& v2, - Vector3& location, - Vector3& normal) { - float t = collisionTimeForMovingPointFixedTriangle(orig, dir, v0, v1, v2); - if (t < finf()) { - location = orig + dir * t; - normal = (v1 - v0).cross(v2 - v0).direction(); - } - return t; - } - - /** - If the ray origin is inside the box, returns inf() but inside - is set to true. - Beta API - - @cite Andrew Woo, from "Graphics Gems", Academic Press, 1990 - @cite Optimized code by Pierre Terdiman, 2000 (~20-30% faster on Celeron 500) - @cite Epsilon value added by Klaus Hartmann - @cite http://www.codercorner.com/RayAABB.cpp - */ - static float collisionTimeForMovingPointFixedAABox( - const Vector3& point, - const Vector3& velocity, - const class AABox& box, - Vector3& outLocation, - bool& inside = ignoreBool, - Vector3& outNormal = ignore); - - /** - Calculates time between the intersection of a moving point and a fixed - Axis-Aligned Box (AABox). - - @note Avoids the sqrt from collisionTimeForMovingPointFixedAABox. - - @param point Moving point. - @param velocity Sphere's velocity. - @param box Fixed AAbox. - @param location Location of collision. [Post Condition] - @param Inside Does the ray originate inside the box? [Post Condition] - @param normal Box's surface normal to collision [Post Condition] - - @return Time til collision. If there is no collision then the return - value will be inf(). - */ - static bool collisionLocationForMovingPointFixedAABox( - const Vector3& point, - const Vector3& velocity, - const class AABox& box, - Vector3& outLocation, - bool& inside = ignoreBool, - Vector3& normal = ignore); - - - /** - @brief Calculates intersection of a ray and a static - Axis-Aligned Box (AABox). - - @note Avoids the sqrt from collisionTimeForMovingPointFixedAABox; - early-out branches and operations optimized for Intel Core2 architecture. - - @param invDir 1/dir - @param location Location of collision. [Post Condition] - @param inside Does the ray originate inside the box? [Post Condition] - - @return True if the ray hits the box - */ - static bool __fastcall rayAABox( - const Ray& ray, - const Vector3& invDir, - const AABox& box, - const Vector3& boxCenter, - float boundingRadiusSquared, - Vector3& location, - bool& inside); - - /** - Calculates time between the intersection of a moving point and a fixed - sphere. - - @note When ray is starts inside the rectangle, the exiting intersection - is detected. - - @param point Moving point. - @param velocity Point's velocity. - @param sphere Fixed Sphere. - @param outLocation Location of collision. [Post Condition] - @param outNormal Sphere's surface normal to collision [Post Condition] - \param solid If true, rays inside the sphere immediately intersect (good for collision detection). If false, they hit the opposite side of the sphere (good for ray tracing). - - @return Time until collision. If there is no collision then the return - value will be inf(). - */ - static float collisionTimeForMovingPointFixedSphere( - const Vector3& point, - const Vector3& velocity, - const class Sphere& sphere, - Vector3& outLocation, - Vector3& outNormal = ignore, - bool solid = false); - - /** - Calculates time between the intersection of a moving point and a fixed - box. - - @note If the point is already inside the box, no collision: inf is returned. - - @param point Moving point. - @param velocity Sphere's velocity. - @param box Fixed box. - @param location Position of collision. [Post Condition] - @param outNormal Box's surface normal to collision [Post Condition] - - @return Time til collision. If there is no collision then the return - value will be inf(). - */ - static float collisionTimeForMovingPointFixedBox( - const Vector3& point, - const Vector3& velocity, - const class Box& box, - Vector3& outLocation, - Vector3& outNormal = ignore); - - /** - Calculates time between the intersection of a moving point and a fixed - rectangle defined by the points v0, v1, v2, & v3. - - @note This is only a one sided collision test. The side defined by - the rectangle's surface normal is the only one tested. For a two sided - collision, call the function once for each side's surface normal. - - @param point Moving point. - @param velocity Sphere's velocity. - @param v0 Rectangle vertex 1. - @param v1 Rectangle vertex 2. - @param v2 Rectangle vertex 3 - @param v3 Rectangle vertex 4. - @param location Location of collision [Post Condition] - @param outNormal Rectangle's surface normal. [Post Condition] - - @return Time til collision. If there is no collision then the return - value will be inf(). - */ - static float collisionTimeForMovingPointFixedRectangle( - const Vector3& point, - const Vector3& velocity, - const Vector3& v0, - const Vector3& v1, - const Vector3& v2, - const Vector3& v3, - Vector3& outLocation, - Vector3& outNormal = ignore); - - /** - Calculates time between the intersection of a moving point and a fixed - capsule. - - @param point Moving point. - @param velocity Point's velocity. - @param capsule Fixed capsule. - @param outLocation Location of collision. [Post Condition] - @param outNormal Capsule's surface normal to collision [Post Condition] - - @return Time til collision. If there is no collision then the return - value will be inf(). - */ - static float collisionTimeForMovingPointFixedCapsule( - const Vector3& point, - const Vector3& velocity, - const class Capsule& capsule, - Vector3& outLocation, - Vector3& outNormal = ignore); - - /** - Calculates time between the intersection of a moving sphere and a fixed - triangle. - - @param sphere Moving sphere. - @param velocity Sphere's velocity. - @param plane Fixed Plane. - @param outLocation Location of collision -- not center position of sphere - at the collision time. [Post Condition] - @param outNormal Box's surface normal to collision [Post Condition] - - @return Time til collision. If there is no collision then the return - value will be inf(). - */ - static float collisionTimeForMovingSphereFixedPlane( - const class Sphere& sphere, - const Vector3& velocity, - const class Plane& plane, - Vector3& outLocation, - Vector3& outNormal = ignore); - - /** - Calculates time between the intersection of a moving sphere and a fixed - triangle. - - @param sphere Moving sphere. - @param velocity Sphere's velocity. - @param triangle Fixed Triangle. (collisions can happen on the back side of the triangle) - @param outLocation Location of collision, if collision occurs -- not center position of sphere - at the collision time. If there is interpenetration at the start, this point may be inside - the sphere. - @param b Barycentric coordinates. These are not valid unless collision occurs. - - @return Time til collision. If there is no collision then the return - value will be inf(). - */ - static float collisionTimeForMovingSphereFixedTriangle( - const class Sphere& sphere, - const Vector3& velocity, - const Triangle& triangle, - Vector3& outLocation, - float b[3] = (float*)&ignore); - - /** - Calculates time between the intersection of a moving sphere and a fixed - rectangle defined by the points v0, v1, v2, & v3. - - @param sphere Moving sphere. - @param velocity Sphere's velocity. - @param v0 Rectangle vertex 1. - @param v1 Rectangle vertex 2. - @param v2 Rectangle vertex 3 - @param v3 Rectangle vertex 4. - @param outLocation Location of collision -- not center position of sphere - at the collision time. [Post Condition] - @param outNormal Box's surface normal to collision [Post Condition] - - @return Time til collision. If there is no collision then the return - value will be inf(). - */ - static float collisionTimeForMovingSphereFixedRectangle( - const class Sphere& sphere, - const Vector3& velocity, - const Vector3& v0, - const Vector3& v1, - const Vector3& v2, - const Vector3& v3, - Vector3& outLocation, - Vector3& outNormal = ignore); - - /** - Calculates time between the intersection of a moving sphere and a fixed - box. - - @note This function will not detect an intersection between a moving object - that is already interpenetrating the fixed object. - - @param sphere Moving sphere. - @param velocity Sphere's velocity. - @param box Fixed box. - @param location Location of collision -- not center position of sphere - at the collision time. [Post Condition] - @param outNormal Box's surface normal to collision [Post Condition] - - @return Time til collision. If there is no collision then the return - value will be inf(). - */ - static float collisionTimeForMovingSphereFixedBox( - const class Sphere& sphere, - const Vector3& velocity, - const class Box& box, - Vector3& outLocation, - Vector3& outNormal = ignore); - - /** Calculates time between the intersection of a moving sphere - and a fixed sphere. - - If they are already interpenetrating, returns 0 and @a - location is the closest point on the surface of the fixed sphere - to the center of the moving sphere. - - @param sphere Moving sphere. - @param velocity Sphere's velocity. - @param fixedSphere Fixed Sphere. - @param outLocation Location of collision -- not center position of sphere - at the collision time. [Post Condition] - @param outNormal Moving sphere's surface normal to collision [Post Condition] - - @return Time until collision. If there is no collision then the return - value will be inf(). - */ - static float collisionTimeForMovingSphereFixedSphere( - const Sphere& sphere, - const Vector3& velocity, - const Sphere& fixedSphere, - Vector3& outLocation, - Vector3& outNormal = ignore); - - /** - Calculates time between the intersection of a moving sphere and a fixed - capsule. - - @note This won't detect a collision if the sphere is already - interpenetrating the capsule. - - @param sphere Moving sphere. - @param velocity Sphere's velocity. - @param capsule Fixed capsule. - @param location Location of collision -- not center position of sphere - at the collision time. [Post Condition] - @param outNormal Capsule's surface normal to the collision [Post Condition] - - @return Time til collision. If there is no collision then the return - value will be inf(). - */ - static float collisionTimeForMovingSphereFixedCapsule( - const class Sphere& sphere, - const Vector3& velocity, - const class Capsule& capsule, - Vector3& outLocation, - Vector3& outNormal = ignore); - - /** - Finds the direction of bounce that a sphere would have when it - intersects an object with the given time of collision, the - collision location and the collision normal. - - @note This function works like a pong style ball bounce. - - @param sphere Moving sphere. - @param velocity Sphere's velocity. - @param collisionTime Time of collision. - @param collisionLocation Collision location. - @param collisionNormal Surface collision normal. - - @return Direction of bounce. - */ - static Vector3 bounceDirection( - const class Sphere& sphere, - const Vector3& velocity, - const float collisionTime, - const Vector3& collisionLocation, - const Vector3& collisionNormal); - - /** - Finds the direction of slide given a moving sphere, its velocity, the - time of collision and the collision location. This function works as - if the sphere intersects the surface and continues to hug it. - - @note The result will work well for calculating the movement of a player - who collides with an object and continues moving along the object instead - of just bouncing off it. - - @param sphere Moving sphere. - @param velocity Sphere's velocity. - @param collisionTime Time of collision - @param collisionLocation Collision location. - - @return Direction of slide. - */ - static Vector3 slideDirection( - const class Sphere& sphere, - const Vector3& velocity, - const float collisionTime, - const Vector3& collisionLocation); - - /** - Finds the closest point on a line segment to a given point. - - @param v0 line vertex 1. - @param v1 line vertex 2. - @param point External point. - - @return Closests point to point on the line segment. - */ - static Vector3 closestPointOnLineSegment( - const Vector3& v0, - const Vector3& v1, - const Vector3& point); - - /** - Finds the closest point on a line segment to a given point. - - @note This is an optimization to closestPointOnLineSegment. Edge length - and direction can be used in this function if already pre-calculated. This - prevents doing the same work twice. - - @param v0 line vertex 0. - @param v1 line vertex 1. - @param edgeDirection The direction of the segment (unit length). - @param edgeLength The length of the segment. - @param point External point. - - @return Closests point to point on the line segment. - */ - static Vector3 closestPointOnLineSegment( - const Vector3& v0, - const Vector3& v1, - const Vector3& edgeDirection, - float edgeLength, - const Vector3& point); - - /** - Finds the closest point on the perimeter of the triangle to an external point; - given a triangle defined by three points v0, v1, & v2, and the external point. - - @param v0 Triangle vertex 0. - @param v1 Triangle vertex 1. - @param v2 Triangle vertex 2. - @param point External point. - - @return Closests point to point on the perimeter of the - triangle. - */ - static Vector3 closestPointOnTrianglePerimeter( - const Vector3& v0, - const Vector3& v1, - const Vector3& v2, - const Vector3& point); - - /** - Finds the closest point on the perimeter of the triangle to an external point; - given a triangle defined by the array of points v, its edge directions and - their lengths, as well as the external point. - - @note This is an optimization to closestPointToTrianglePerimeter. Edge length - and direction can be used in this function if already pre-calculated. This - prevents doing the same work twice. - - @param v Triangle vertices. - @param point External point. - @param edgeIndex The point lies on the edge between v[edgeIndex] and v[(edgeIndex + 1) % 3] - - @return Closest point to point on the perimeter of the - triangle. - */ - static Vector3 closestPointOnTrianglePerimeter( - const Vector3 v[3], - const Vector3 edgeDirection[3], - const float edgeLength[3], - const Vector3& point, - int& edgeIndex); - - /** - Tests whether a point is contained within the triangle defined by - v0, v1, and v2 and its plane's normal. - - @param v0 Triangle vertex 0. - @param v1 Triangle vertex 1. - @param v2 Triangle vertex 2. - @param normal Normal to triangle's plane. - @param point The point in question. - @param primaryAxis Primary axis of triangle. This will be detected - if not given. This parameter is provided as an optimization. - @param b Barycentric coordinates; b[i] is the weight on v[i] - - @return true - if point is inside the triangle. - @return false - otherwise - */ - static bool isPointInsideTriangle( - const Vector3& v0, - const Vector3& v1, - const Vector3& v2, - const Vector3& normal, - const Vector3& point, - float b[3], - Vector3::Axis primaryAxis = Vector3::DETECT_AXIS); - - inline static bool isPointInsideTriangle( - const Vector3& v0, - const Vector3& v1, - const Vector3& v2, - const Vector3& normal, - const Vector3& point, - Vector3::Axis primaryAxis = Vector3::DETECT_AXIS) { - - float b[3]; - return isPointInsideTriangle(v0, v1, v2, normal, point, b, primaryAxis); - } - - /** - Tests for the intersection of a moving sphere and a fixed box in a - given time limit. - - @note Returns true if any part of the sphere is inside the box - during the time period (inf means "ever"). Useful for - performing bounding-box collision detection. - - @param sphere Moving sphere. - @param velocity Velocity of moving sphere. - @param box Fixed box. - @param timeLimit Time limit for intersection test. - - @return true - if the two objects will touch. - @return false - if there is no intersection. - */ - static bool movingSpherePassesThroughFixedBox( - const Sphere& sphere, - const Vector3& velocity, - const Box& box, - double timeLimit = inf()); - - /** - Tests for the intersection of a moving sphere and a fixed sphere in a - given time limit. - - @note This function will not detect an intersection between a moving object - that is already interpenetrating the fixed object. - - @param sphere Moving sphere. - @param velocity Velocity of moving sphere. - @param fixedSphere Fixed sphere. - @param timeLimit Time limit for intersection test. - - @return true - if the two spheres will touch. - @return false - if there is no intersection. - */ - static bool movingSpherePassesThroughFixedSphere( - const Sphere& sphere, - const Vector3& velocity, - const Sphere& fixedSphere, - double timeLimit = inf()); - - /** - Tests for the intersection of two fixed spheres. - - @param sphere1 Fixed sphere 1. - @param sphere2 Fixed sphere 2. - - @return true - if the two spheres touch. - @return false - if there is no intersection. - */ - static bool fixedSolidSphereIntersectsFixedSolidSphere( - const Sphere& sphere1, - const Sphere& sphere2); - - /** - Tests for the intersection of a fixed sphere and a fixed box. - - @param sphere Fixed sphere. - @param box Fixed box. - - @return true - if the two objects touch. - @return false - if there is no intersection. - */ - static bool fixedSolidSphereIntersectsFixedSolidBox( - const Sphere& sphere, - const Box& box); - - static bool fixedSolidSphereIntersectsFixedTriangle( - const Sphere& sphere, - const Triangle& triangle); - - static bool fixedSolidBoxIntersectsFixedTriangle( - const AABox& box, - const Triangle& triangle); - - /** - Tests whether a point is inside a rectangle defined by the vertexes - v0, v1, v2, & v3, and the rectangle's plane normal. - - @param v0 Rectangle vertex 1. - @param v1 Rectangle vertex 2. - @param v2 Rectangle vertex 3. - @param v3 Rectangle vertex 4. - @param normal Normal to rectangle's plane. - @param point The point in question. - - @return true - if point is inside the rectangle. - @return false - otherwise - */ - static bool isPointInsideRectangle( - const Vector3& v0, - const Vector3& v1, - const Vector3& v2, - const Vector3& v3, - const Vector3& normal, - const Vector3& point); - - /** - Finds the closest point on the perimeter of the rectangle to an - external point; given a rectangle defined by four points v0, v1, - v2, & v3, and the external point. - - @param v0 Rectangle vertex 1. - @param v1 Rectangle vertex 2. - @param v2 Rectangle vertex 3. - @param v3 Rectangle vertex 4. - @param point External point. - - @return Closests point to point on the perimeter of the - rectangle. - */ - static Vector3 closestPointToRectanglePerimeter( - const Vector3& v0, - const Vector3& v1, - const Vector3& v2, - const Vector3& v3, - const Vector3& point); - - /** - Finds the closest point in the rectangle to an external point; Given - a rectangle defined by four points v0, v1, v2, & v3, and the external - point. - - @param v0 Rectangle vertex 1. - @param v1 Rectangle vertex 2. - @param v2 Rectangle vertex 3 - @param v3 Rectangle vertex 4. - @param point External point. - - @return Closet point in the rectangle to the external point. - */ - static Vector3 closestPointToRectangle( - const Vector3& v0, - const Vector3& v1, - const Vector3& v2, - const Vector3& v3, - const Vector3& point); -}; - -} // namespace - -#endif // G3D_COLLISIONDETECTION_H diff --git a/externals/g3dlite/G3D/Color1.h b/externals/g3dlite/G3D/Color1.h deleted file mode 100644 index 0f68c84b363..00000000000 --- a/externals/g3dlite/G3D/Color1.h +++ /dev/null @@ -1,144 +0,0 @@ -/** - @file Color1.h - - Monochrome Color class - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - @created 2007-01-31 - @edited 2009-03-20 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_COLOR1_H -#define G3D_COLOR1_H - -#include "G3D/platform.h" -#include "G3D/g3dmath.h" -#include "G3D/HashTrait.h" -#include - -namespace G3D { - -/** - Monochrome color. This is just a float, but it has nice semantics - because a scaling by 255 automatically occurs when switching between - fixed point (Color1uint8) and floating point (Color1) formats. - */ -class Color1 { -private: - // Hidden operators - bool operator<(const Color1&) const; - bool operator>(const Color1&) const; - bool operator<=(const Color1&) const; - bool operator>=(const Color1&) const; - -public: - float value; - - /** - Initializes to 0 - */ - inline Color1() : value(0) {} - - Color1(class BinaryInput& bi); - - inline explicit Color1(float v) : value(v) { - } - - inline bool isZero() const { - return value == 0.0f; - } - - inline bool isOne() const { - return value == 1.0f; - } - - static const Color1& one(); - - static const Color1& zero(); - - /** Returns the value three times */ - class Color3 rgb() const; - - Color1 (const class Color1uint8& other); - - void serialize(class BinaryOutput& bo) const; - void deserialize(class BinaryInput& bi); - - Color1 operator+ (const Color1& other) const { - return Color1(value + other.value); - } - - Color1 operator+ (const float other) const { - return Color1(value + other); - } - - Color1& operator+= (const Color1 other) { - value += other.value; - return *this; - } - - Color1& operator-= (const Color1 other) { - value -= other.value; - return *this; - } - - Color1 operator- (const Color1& other) const { - return Color1(value - other.value); - } - - Color1 operator- (const float other) const { - return Color1(value - other); - } - - Color1 operator- () const { - return Color1(-value); - } - - Color1 operator* (const Color1& other) const { - return Color1(value * other.value); - } - - Color1 operator* (const float other) const { - return Color1(value * other); - } - - Color1 operator/ (const Color1& other) const { - return Color1(value / other.value); - } - - Color1 operator/ (const float other) const { - return Color1(value / other); - } - - inline Color1 max(const Color1& other) const { - return Color1(G3D::max(value, other.value)); - } - - inline Color1 min(const Color1& other) const { - return Color1(G3D::min(value, other.value)); - } - - inline Color1 lerp(const Color1& other, float a) const { - return Color1(value + (other.value - value) * a); - - } - - inline size_t hashCode() const { - return (size_t)(value * 0xFFFFFF); - } -}; - -} - -template <> -struct HashTrait { - static size_t hashCode(const G3D::Color1& key) { - return key.hashCode(); - } -}; - - -#endif diff --git a/externals/g3dlite/G3D/Color1uint8.h b/externals/g3dlite/G3D/Color1uint8.h deleted file mode 100644 index 092099d0d17..00000000000 --- a/externals/g3dlite/G3D/Color1uint8.h +++ /dev/null @@ -1,91 +0,0 @@ -/** - @file Color1uint8.h - - @maintainer Morgan McGuire, graphics3d.com - - @created 2007-01-30 - @edited 2007-01-30 - - Copyright 2000-2007, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_COLOR1UINT8_H -#define G3D_COLOR1UINT8_H - -#include "G3D/platform.h" -#include "G3D/g3dmath.h" - -namespace G3D { - -/** - Represents a Color1 as a packed integer. Convenient - for creating unsigned int vertex arrays. - - WARNING: Integer color formats are different than - integer vertex formats. The color channels are automatically - scaled by 255 (because OpenGL automatically scales integer - colors back by this factor). So Color3(1,1,1) == Color3uint8(255,255,255) - but Vector3(1,1,1) == Vector3int16(1,1,1). - - Note: - Conversion of a float32 to uint8 is accomplished by min(iFloor(f * 256)) and - back to float32 by u / 255.0f. This gives equal size intervals. -Consider a number line from 0 to 1 and a corresponding one from 0 to 255. If we use iRound(x * 255), then the mapping for three critical intervals are: - -

-let s = 0.5/255
-  float             int       size
-[0, s)           -> 0          s
-[s, s * 3)       -> 1         2*s
-(1 - s, 1]       -> 255        s
-
- -If we use max(floor(x * 256), 255), then we get: - -
-let s = 1/256
-  float             int           size
-[0, s)           -> 0               s
-[s, 2 * s)       -> 1               s
-(1 - s, 1]       -> 255             s
-
-and the intervals are all the same size, thus giving equal precision to all values. - */ -G3D_BEGIN_PACKED_CLASS(1) -class Color1uint8 { -private: - // Hidden operators - bool operator<(const Color1uint8&) const; - bool operator>(const Color1uint8&) const; - bool operator<=(const Color1uint8&) const; - bool operator>=(const Color1uint8&) const; - -public: - - uint8 value; - - Color1uint8() : value(0) {} - - explicit Color1uint8(const uint8 _v) : value(_v) {} - - Color1uint8(const class Color1& c); - - Color1uint8(class BinaryInput& bi); - - void serialize(class BinaryOutput& bo) const; - - void deserialize(class BinaryInput& bi); - - inline bool operator==(const Color1uint8& other) const { - return value == other.value; - } - - inline bool operator!=(const Color1uint8& other) const { - return value != other.value; - } - -} -G3D_END_PACKED_CLASS(1) -} -#endif diff --git a/externals/g3dlite/G3D/Color3.h b/externals/g3dlite/G3D/Color3.h deleted file mode 100644 index bffe434fc27..00000000000 --- a/externals/g3dlite/G3D/Color3.h +++ /dev/null @@ -1,432 +0,0 @@ -/** - @file Color3.h - - Color class - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - @cite Portions based on Dave Eberly's Magic Software Library - at http://www.magic-software.com - - @created 2001-06-02 - @edited 2009-04-28 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_Color3_h -#define G3D_Color3_h - -#include "G3D/platform.h" -#include "G3D/g3dmath.h" -#include "G3D/HashTrait.h" -#include "G3D/Color1.h" -#include - -namespace G3D { -class Any; - -/** - Do not subclass-- this implementation makes assumptions about the - memory layout. - */ -class Color3 { -private: - // Hidden operators - bool operator<(const Color3&) const; - bool operator>(const Color3&) const; - bool operator<=(const Color3&) const; - bool operator>=(const Color3&) const; - -public: - /** - Does not initialize fields. - */ - Color3(); - - /** \param any Must be in one of the following forms: - - Color3(#, #, #) - - Color3::fromARGB(#) - - Color3{r = #, g = #, b = #) - - Color3::one() - - Color3::zero() - */ - Color3(const Any& any); - - /** Converts the Color3 to an Any. */ - operator Any() const; - - explicit Color3(class BinaryInput& bi); - - Color3(float r, float g, float b); - Color3(float v) : r(v), g(v), b(v) {} - - explicit Color3(const class Vector3& v); - - explicit Color3(const float value[3]); - - /** Returns this color */ - const Color3& rgb() const { - return *this; - } - - /** - Initialize from another color. - */ - Color3 (const Color3& other); - - Color3 (const class Color3uint8& other); - - inline bool isZero() const { - return (r == 0.0f) && (g == 0.0f) && (b == 0.0f); - } - - inline bool isOne() const { - return (r == 1.0f) && (g == 1.0f) && (b == 1.0f); - } - - bool isFinite() const; - - /** - Initialize from an HTML-style color (e.g. 0xFF0000 == RED) - */ - static Color3 fromARGB(uint32); - - /** Returns one of the color wheel colors (e.g. RED, GREEN, CYAN). - Does not include white, black, or gray. */ - static const Color3& wheelRandom(); - - /** Generate colors according to the ANSI color set, mod 16. - \sa pastelMap */ - static Color3 ansiMap(uint32 i); - - /** - Generate colors using a hash such that adjacent values - are unlikely to have similar colors. - - Useful for rendering with - stable but arbitrary colors, e.g., when debugging a mesh - algorithm. - - \sa ansiMap - */ - static Color3 pastelMap(uint32 i); - - /** - * Channel value. - */ - float r, g, b; - - void serialize(class BinaryOutput& bo) const; - void deserialize(class BinaryInput& bi); - - // access vector V as V[0] = V.r, V[1] = V.g, V[2] = V.b - // - // WARNING. These member functions rely on - // (1) Color3 not having virtual functions - // (2) the data packed in a 3*sizeof(float) memory block - const float& operator[] (int i) const; - float& operator[] (int i); - - // assignment and comparison - Color3& operator= (const Color3& rkVector); - bool operator== (const Color3& rkVector) const; - bool operator!= (const Color3& rkVector) const; - size_t hashCode() const; - - // arithmetic operations - Color3 operator+ (const Color3& rkVector) const; - Color3 operator- (const Color3& rkVector) const; - inline Color3 operator* (float s) const { - return Color3(r * s, g * s, b * s); - } - Color3 operator* (const Color3& rkVector) const; - inline Color3 operator/ (float fScalar) const { - return (*this) * (1.0f / fScalar); - } - Color3 operator- () const; - - // arithmetic updates - Color3& operator+= (const Color3& rkVector); - Color3& operator-= (const Color3& rkVector); - Color3& operator*= (const Color3& rkVector); - Color3& operator*= (float fScalar); - Color3& operator/= (float fScalar); - - bool fuzzyEq(const Color3& other) const; - bool fuzzyNe(const Color3& other) const; - - // vector operations - float length () const; - Color3 direction() const; - float squaredLength () const; - float dot (const Color3& rkVector) const; - float unitize (float fTolerance = 1e-06); - Color3 cross (const Color3& rkVector) const; - Color3 unitCross (const Color3& rkVector) const; - - inline Color3 pow(const Color3& other) const { - return Color3(::pow(r, other.r), ::pow(g, other.g), ::pow(b, other.b)); - } - - inline Color3 pow(float other) const { - return Color3(::pow(r, other), ::pow(g, other), ::pow(b, other)); - } - - inline Color3 max(const Color3& other) const { - return Color3(G3D::max(r, other.r), G3D::max(g, other.g), G3D::max(b, other.b)); - } - - inline Color3 min(const Color3& other) const { - return Color3(G3D::min(r, other.r), G3D::min(g, other.g), G3D::min(b, other.b)); - } - - /** Smallest element */ - inline float min() const { - return G3D::min(G3D::min(r, g), b); - } - - /** Largest element */ - inline float max() const { - return G3D::max(G3D::max(r, g), b); - } - - inline Color3 lerp(const Color3& other, float a) const { - return (*this) + (other - *this) * a; - - } - - inline float sum() const { - return r + g + b; - } - - inline float average() const { - return sum() / 3.0f; - } - - - /** - * Converts from HSV to RGB , note: toHSV(fromHSV(_hsv)) may not be _hsv, if it is at a grey point or black point. - * The components of _hsv should lie in the unit interval. - * @cite Alvy Ray Smith SIGGRAPH 1978 "Color Gamut Transform Pairs" - **/ - static Color3 fromHSV(const Vector3& _hsv); - static Vector3 toHSV(const Color3& _rgb); - - /** Duplicates the matlab jet colormap maps [0,1] --> (r,g,b) where blue is close to 0 and red is close to 1. */ - static Color3 jetColorMap(const float& val); - - /** Returns colors with maximum saturation and value @param hue [0, 1]*/ - static Color3 rainbowColorMap(float hue); - - std::string toString() const; - - /** Random unit vector */ - static Color3 random(); - - // Special values. - // Intentionally not inlined: see Matrix3::identity() for details. - static const Color3& red(); - static const Color3& green(); - static const Color3& blue(); - static const Color3& purple(); - static const Color3& cyan(); - static const Color3& yellow(); - static const Color3& brown(); - static const Color3& orange(); - static const Color3& black(); - static const Color3& gray(); - static const Color3& white(); - - static const Color3& zero(); - static const Color3& one(); - - inline Color3 bgr() const { - return Color3(b, g, r); - } -}; - -inline G3D::Color3 operator* (float s, const G3D::Color3& c) { - return c * s; -} - -inline G3D::Color3 operator* (G3D::Color1& s, const G3D::Color3& c) { - return c * s.value; -} - -inline G3D::Color3 operator* (const G3D::Color3& c, G3D::Color1& s) { - return c * s.value; -} - - -//---------------------------------------------------------------------------- -inline Color3::Color3 () { -} - -//---------------------------------------------------------------------------- - -inline Color3::Color3(float fX, float fY, float fZ) { - r = fX; - g = fY; - b = fZ; -} - -//---------------------------------------------------------------------------- -inline Color3::Color3(const float afCoordinate[3]) { - r = afCoordinate[0]; - g = afCoordinate[1]; - b = afCoordinate[2]; -} - -//---------------------------------------------------------------------------- -inline Color3::Color3 (const Color3& rkVector) { - r = rkVector.r; - g = rkVector.g; - b = rkVector.b; -} - -//---------------------------------------------------------------------------- -inline float& Color3::operator[] (int i) { - return ((float*)this)[i]; -} - -//---------------------------------------------------------------------------- - -inline const float& Color3::operator[] (int i) const { - return ((float*)this)[i]; -} - -//---------------------------------------------------------------------------- - -inline bool Color3::fuzzyEq(const Color3& other) const { - return G3D::fuzzyEq((*this - other).squaredLength(), 0); -} - -//---------------------------------------------------------------------------- - -inline bool Color3::fuzzyNe(const Color3& other) const { - return G3D::fuzzyNe((*this - other).squaredLength(), 0); -} - - -//---------------------------------------------------------------------------- -inline Color3& Color3::operator= (const Color3& rkVector) { - r = rkVector.r; - g = rkVector.g; - b = rkVector.b; - return *this; -} - -//---------------------------------------------------------------------------- -inline bool Color3::operator== (const Color3& rkVector) const { - return ( r == rkVector.r && g == rkVector.g && b == rkVector.b ); -} - -//---------------------------------------------------------------------------- -inline bool Color3::operator!= (const Color3& rkVector) const { - return ( r != rkVector.r || g != rkVector.g || b != rkVector.b ); -} - -//---------------------------------------------------------------------------- -inline Color3 Color3::operator+ (const Color3& rkVector) const { - return Color3(r + rkVector.r, g + rkVector.g, b + rkVector.b); -} - -//---------------------------------------------------------------------------- -inline Color3 Color3::operator- (const Color3& rkVector) const { - return Color3(r -rkVector.r, g - rkVector.g, b - rkVector.b); -} - -//---------------------------------------------------------------------------- -inline Color3 Color3::operator* (const Color3& rkVector) const { - return Color3(r * rkVector.r, g * rkVector.g, b * rkVector.b); -} - -//---------------------------------------------------------------------------- -inline Color3 Color3::operator- () const { - return Color3( -r, -g, -b); -} - -//---------------------------------------------------------------------------- -inline Color3& Color3::operator+= (const Color3& rkVector) { - r += rkVector.r; - g += rkVector.g; - b += rkVector.b; - return *this; -} - -//---------------------------------------------------------------------------- -inline Color3& Color3::operator-= (const Color3& rkVector) { - r -= rkVector.r; - g -= rkVector.g; - b -= rkVector.b; - return *this; -} - -//---------------------------------------------------------------------------- -inline Color3& Color3::operator*= (float fScalar) { - r *= fScalar; - g *= fScalar; - b *= fScalar; - return *this; -} - -//---------------------------------------------------------------------------- -inline Color3& Color3::operator*= (const Color3& rkVector) { - r *= rkVector.r; - g *= rkVector.g; - b *= rkVector.b; - return *this; -} -//---------------------------------------------------------------------------- -inline float Color3::squaredLength () const { - return r*r + g*g + b*b; -} - -//---------------------------------------------------------------------------- -inline float Color3::length () const { - return sqrtf(r*r + g*g + b*b); -} - -//---------------------------------------------------------------------------- -inline Color3 Color3::direction () const { - float lenSquared = r * r + g * g + b * b; - - if (lenSquared != 1.0f) { - return *this / sqrtf(lenSquared); - } else { - return *this; - } -} - -//---------------------------------------------------------------------------- -inline float Color3::dot (const Color3& rkVector) const { - return r*rkVector.r + g*rkVector.g + b*rkVector.b; -} - -//---------------------------------------------------------------------------- -inline Color3 Color3::cross (const Color3& rkVector) const { - return Color3(g*rkVector.b - b*rkVector.g, b*rkVector.r - r*rkVector.b, - r*rkVector.g - g*rkVector.r); -} - -//---------------------------------------------------------------------------- -inline Color3 Color3::unitCross (const Color3& rkVector) const { - Color3 kCross(g*rkVector.b - b*rkVector.g, b*rkVector.r - r*rkVector.b, - r*rkVector.g - g*rkVector.r); - kCross.unitize(); - return kCross; -} - - -} // namespace - - -template <> struct HashTrait { - static size_t hashCode(const G3D::Color3& key) { - return key.hashCode(); - } -}; - - -#endif diff --git a/externals/g3dlite/G3D/Color3uint8.h b/externals/g3dlite/G3D/Color3uint8.h deleted file mode 100644 index bd4b00d7fd6..00000000000 --- a/externals/g3dlite/G3D/Color3uint8.h +++ /dev/null @@ -1,110 +0,0 @@ -/** - @file Color3uint8.h - - @maintainer Morgan McGuire, graphics3d.com - - @created 2003-04-07 - @edited 2006-06-24 - - Copyright 2000-2006, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_COLOR3UINT8_H -#define G3D_COLOR3UINT8_H - -#include "G3D/platform.h" -#include "G3D/g3dmath.h" - -namespace G3D { - -/** - Represents a Color3 as a packed integer. Convenient - for creating unsigned int vertex arrays. Used by - G3D::GImage as the underlying format. - - WARNING: Integer color formats are different than - integer vertex formats. The color channels are automatically - scaled by 255 (because OpenGL automatically scales integer - colors back by this factor). So Color3(1,1,1) == Color3uint8(255,255,255) - but Vector3(1,1,1) == Vector3int16(1,1,1). - */ - -G3D_BEGIN_PACKED_CLASS(1) - -class Color3uint8 { -private: - // Hidden operators - bool operator<(const Color3uint8&) const; - bool operator>(const Color3uint8&) const; - bool operator<=(const Color3uint8&) const; - bool operator>=(const Color3uint8&) const; - -public: - uint8 r; - uint8 g; - uint8 b; - - Color3uint8() : r(0), g(0), b(0) {} - - Color3uint8(const uint8 _r, const uint8 _g, const uint8 _b) : r(_r), g(_g), b(_b) {} - - Color3uint8(const class Color3& c); - - Color3uint8(class BinaryInput& bi); - - inline static Color3uint8 fromARGB(uint32 i) { - Color3uint8 c; - c.r = (i >> 16) & 0xFF; - c.g = (i >> 8) & 0xFF; - c.b = i & 0xFF; - return c; - } - - inline Color3uint8 bgr() const { - return Color3uint8(b, g, r); - } - - /** - Returns the color packed into a uint32 - (the upper byte is 0xFF) - */ - inline uint32 asUInt32() const { - return (0xFF << 24) + ((uint32)r << 16) + ((uint32)g << 8) + b; - } - - void serialize(class BinaryOutput& bo) const; - - void deserialize(class BinaryInput& bi); - - // access vector V as V[0] = V.r, V[1] = V.g, V[2] = V.b - // - // WARNING. These member functions rely on - // (1) Color3 not having virtual functions - // (2) the data packed in a 3*sizeof(uint8) memory block - uint8& operator[] (int i) const { - debugAssert((unsigned int)i < 3); - return ((uint8*)this)[i]; - } - - operator uint8* () { - return (G3D::uint8*)this; - } - - operator const uint8* () const { - return (uint8*)this; - } - - bool operator==(const Color3uint8& other) const { - return (other.r == r) && (other.g == g) && (other.b == b); - } - - bool operator!=(const Color3uint8& other) const { - return (other.r != r) && (other.g != g) && (other.b != b); - } -} -G3D_END_PACKED_CLASS(1) - -} // namespace G3D - -#endif diff --git a/externals/g3dlite/G3D/Color4.h b/externals/g3dlite/G3D/Color4.h deleted file mode 100644 index d8858abbce2..00000000000 --- a/externals/g3dlite/G3D/Color4.h +++ /dev/null @@ -1,338 +0,0 @@ -/** - @file Color4.h - - Color class - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - @cite Portions based on Dave Eberly's Magic Software Library - at http://www.magic-software.com - - @created 2002-06-25 - @edited 2009-11-15 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_Color4_h -#define G3D_Color4_h - -#include "G3D/platform.h" -#include "G3D/g3dmath.h" -#include "G3D/Color3.h" -#include - -namespace G3D { - -class Any; - -/** - Do not subclass-- this implementation makes assumptions about the - memory layout. - */ -class Color4 { -private: - // Hidden operators - bool operator<(const Color4&) const; - bool operator>(const Color4&) const; - bool operator<=(const Color4&) const; - bool operator>=(const Color4&) const; - -public: - - /** \param any Must be in one of the following forms: - - Color4(#, #, #, #) - - Color4::fromARGB(#) - - Color4{r = #, g = #, b = #, a = #) - */ - Color4(const Any& any); - - /** Converts the Color4 to an Any. */ - operator Any() const; - - /** - * Does not initialize fields. - */ - Color4 (); - - Color4(const Color3& c3, float a = 1.0); - - Color4(const class Color4uint8& c); - - Color4(class BinaryInput& bi); - - Color4(const class Vector4& v); - - Color4(float r, float g, float b, float a = 1.0); - - static const Color4& one(); - - Color4(float value[4]); - - /** - * Initialize from another color. - */ - Color4(const Color4& other); - - - inline bool isZero() const { - return (r == 0.0f) && (g == 0.0f) && (b == 0.0f) && (a == 0.0f); - } - - inline bool isOne() const { - return (r == 1.0f) && (g == 1.0f) && (b == 1.0f) && (a == 1.0f); - } - - void serialize(class BinaryOutput& bo) const; - void deserialize(class BinaryInput& bi); - - /** - Initialize from an HTML-style color (e.g. 0xFFFF0000 == RED) - */ - static Color4 fromARGB(uint32); - - /** - * Channel values. - */ - float r, g, b, a; - - inline Color3 rgb() const { - return Color3(r, g, b); - } - - // access vector V as V[0] = V.r, V[1] = V.g, V[2] = V.b, v[3] = V.a - // - // WARNING. These member functions rely on - // (1) Color4 not having virtual functions - // (2) the data packed in a 3*sizeof(float) memory block - float& operator[] (int i) const; - - // assignment and comparison - Color4& operator= (const Color4& rkVector); - bool operator== (const Color4& rkVector) const; - bool operator!= (const Color4& rkVector) const; - size_t hashCode() const; - - // arithmetic operations - Color4 operator+ (const Color4& rkVector) const; - Color4 operator- (const Color4& rkVector) const; - Color4 operator* (float fScalar) const; - inline Color4 operator* (const Color4& k) const { - return Color4(r*k.r, g*k.g, b*k.b, a * k.a); - } - Color4 operator/ (float fScalar) const; - Color4 operator- () const; - friend Color4 operator* (double fScalar, const Color4& rkVector); - - // arithmetic updates - Color4& operator+= (const Color4& rkVector); - Color4& operator-= (const Color4& rkVector); - Color4& operator*= (float fScalar); - Color4& operator/= (float fScalar); - - bool fuzzyEq(const Color4& other) const; - bool fuzzyNe(const Color4& other) const; - - std::string toString() const; - - inline Color4 max(const Color4& other) const { - return Color4(G3D::max(r, other.r), G3D::max(g, other.g), G3D::max(b, other.b), G3D::max(a, other.a)); - } - - inline Color4 min(const Color4& other) const { - return Color4(G3D::min(r, other.r), G3D::min(g, other.g), G3D::min(b, other.b), G3D::min(a, other.a)); - } - - /** r + g + b + a */ - inline float sum() const { - return r + g + b + a; - } - - inline Color4 lerp(const Color4& other, float a) const { - return (*this) + (other - *this) * a; - - } - - // Special values. - // Intentionally not inlined: see Matrix3::identity() for details. - static const Color4& zero(); - static const Color4& clear(); - - static const Color4& inf(); - static const Color4& nan(); - - inline bool isFinite() const { - return G3D::isFinite(r) && G3D::isFinite(g) && G3D::isFinite(b) && G3D::isFinite(a); - } - - inline Color3 bgr() const { - return Color3(b, g, r); - } -}; - -/** - Extends the c3 with alpha = 1.0 - */ -Color4 operator*(const Color3& c3, const Color4& c4); - - -inline Color4 operator*(const Color3& c3, const Color4& c4) { - return Color4(c3.r * c4.r, c3.g * c4.g, c3.b * c4.b, c4.a); -} - -//---------------------------------------------------------------------------- - -inline Color4::Color4 () { - // For efficiency in construction of large arrays of vectors, the - // default constructor does not initialize the vector. -} - -//---------------------------------------------------------------------------- - -inline Color4::Color4(const Color3& c3, float a) { - r = c3.r; - g = c3.g; - b = c3.b; - this->a = a; -} - -//---------------------------------------------------------------------------- - -inline Color4::Color4( - float r, - float g, - float b, - float a) : - r(r), g(g), b(b), a(a) { -} - -//---------------------------------------------------------------------------- -inline Color4::Color4 (float afCoordinate[4]) { - r = afCoordinate[0]; - g = afCoordinate[1]; - b = afCoordinate[2]; - a = afCoordinate[3]; -} - -//---------------------------------------------------------------------------- - -inline Color4::Color4( - const Color4& other) { - - r = other.r; - g = other.g; - b = other.b; - a = other.a; -} - -//---------------------------------------------------------------------------- - -inline float& Color4::operator[] (int i) const { - return ((float*)this)[i]; -} - -//---------------------------------------------------------------------------- - -inline bool Color4::fuzzyEq(const Color4& other) const { - Color4 dif = (*this - other); - return G3D::fuzzyEq(dif.r * dif.r + dif.g * dif.g + dif.b * dif.b + dif.a * dif.a, 0); -} - -//---------------------------------------------------------------------------- - -inline bool Color4::fuzzyNe(const Color4& other) const { - Color4 dif = (*this - other); - return G3D::fuzzyNe(dif.r * dif.r + dif.g * dif.g + dif.b * dif.b + dif.a * dif.a, 0); -} - - -//---------------------------------------------------------------------------- -inline Color4& Color4::operator= (const Color4& other) { - r = other.r; - g = other.g; - b = other.b; - a = other.a; - return *this; -} - -//---------------------------------------------------------------------------- - -inline bool Color4::operator== (const Color4& other) const { - return ( r == other.r && g == other.g && b == other.b && a == other.a); -} - -//---------------------------------------------------------------------------- - -inline bool Color4::operator!= (const Color4& other) const { - return ( r != other.r || g != other.g || b != other.b || a != other.a); -} - -//---------------------------------------------------------------------------- -inline Color4 Color4::operator+ (const Color4& other) const { - return Color4(r + other.r, g + other.g, b + other.b, a + other.a); -} - -//---------------------------------------------------------------------------- -inline Color4 Color4::operator- (const Color4& other) const { - return Color4(r - other.r, g - other.g, b - other.b, a - other.a); -} - -//---------------------------------------------------------------------------- - -inline Color4 Color4::operator* (float fScalar) const { - return Color4(fScalar * r, fScalar * g, fScalar * b, fScalar * a); -} - -//---------------------------------------------------------------------------- - -inline Color4 Color4::operator- () const { - return Color4(-r, -g, -b, -a); -} - -//---------------------------------------------------------------------------- - -inline Color4 operator* (float fScalar, const Color4& other) { - return Color4(fScalar * other.r, fScalar * other.g, - fScalar * other.b, fScalar * other.a); -} - -//---------------------------------------------------------------------------- - -inline Color4& Color4::operator+= (const Color4& other) { - r += other.r; - g += other.g; - b += other.b; - a += other.a; - return *this; -} - -//---------------------------------------------------------------------------- - -inline Color4& Color4::operator-= (const Color4& other) { - r -= other.r; - g -= other.g; - b -= other.b; - a -= other.a; - return *this; -} - -//---------------------------------------------------------------------------- - -inline Color4& Color4::operator*= (float fScalar) { - r *= fScalar; - g *= fScalar; - b *= fScalar; - a *= fScalar; - return *this; -} - -} // namespace - -template <> -struct HashTrait { - static size_t hashCode(const G3D::Color4& key) { - return key.hashCode(); - } -}; - -#endif diff --git a/externals/g3dlite/G3D/Color4uint8.h b/externals/g3dlite/G3D/Color4uint8.h deleted file mode 100644 index ab8c0729276..00000000000 --- a/externals/g3dlite/G3D/Color4uint8.h +++ /dev/null @@ -1,115 +0,0 @@ -/** - @file Color4uint8.h - - @maintainer Morgan McGuire, graphics3d.com - - @created 2003-04-07 - @edited 2006-03-24 - - Copyright 2000-2006, Morgan McGuire. - All rights reserved. - */ - -#ifndef COLOR4UINT8_H -#define COLOR4UINT8_H - -#include "G3D/g3dmath.h" -#include "G3D/platform.h" -#include "G3D/Color3uint8.h" - -namespace G3D { - -/** - Represents a Color4 as a packed integer. Convenient - for creating unsigned int vertex arrays. Used by - G3D::GImage as the underlying format. - - WARNING: Integer color formats are different than - integer vertex formats. The color channels are automatically - scaled by 255 (because OpenGL automatically scales integer - colors back by this factor). So Color4(1,1,1) == Color4uint8(255,255,255) - but Vector3(1,1,1) == Vector3int16(1,1,1). - - */ -G3D_BEGIN_PACKED_CLASS(1) -class Color4uint8 { -private: - // Hidden operators - bool operator<(const Color4uint8&) const; - bool operator>(const Color4uint8&) const; - bool operator<=(const Color4uint8&) const; - bool operator>=(const Color4uint8&) const; - -public: - uint8 r; - uint8 g; - uint8 b; - uint8 a; - - Color4uint8() : r(0), g(0), b(0), a(0) {} - - Color4uint8(const class Color4& c); - - Color4uint8(const uint8 _r, const uint8 _g, const uint8 _b, const uint8 _a) : r(_r), g(_g), b(_b), a(_a) {} - - Color4uint8(const Color3uint8& c, const uint8 _a) : r(c.r), g(c.g), b(c.b), a(_a) {} - - Color4uint8(class BinaryInput& bi); - - inline static Color4uint8 fromARGB(uint32 i) { - Color4uint8 c; - c.a = (i >> 24) & 0xFF; - c.r = (i >> 16) & 0xFF; - c.g = (i >> 8) & 0xFF; - c.b = i & 0xFF; - return c; - } - - inline uint32 asUInt32() const { - return ((uint32)a << 24) + ((uint32)r << 16) + ((uint32)g << 8) + b; - } - - // access vector V as V[0] = V.r, V[1] = V.g, V[2] = V.b - // - // WARNING. These member functions rely on - // (1) Color4uint8 not having virtual functions - // (2) the data packed in a 3*sizeof(uint8) memory block - uint8& operator[] (int i) const { - return ((uint8*)this)[i]; - } - - operator uint8* () { - return (uint8*)this; - } - - operator const uint8* () const { - return (uint8*)this; - } - - - inline Color3uint8 bgr() const { - return Color3uint8(b, g, r); - } - - void serialize(class BinaryOutput& bo) const; - - void deserialize(class BinaryInput& bi); - - inline Color3uint8 rgb() const { - return Color3uint8(r, g, b); - } - - bool operator==(const Color4uint8& other) const { - return *reinterpret_cast(this) == *reinterpret_cast(&other); - } - - bool operator!=(const Color4uint8& other) const { - return *reinterpret_cast(this) != *reinterpret_cast(&other); - } - -} -G3D_END_PACKED_CLASS(1) - -} // namespace G3D - -#endif diff --git a/externals/g3dlite/G3D/Cone.h b/externals/g3dlite/G3D/Cone.h deleted file mode 100644 index d801a9b348f..00000000000 --- a/externals/g3dlite/G3D/Cone.h +++ /dev/null @@ -1,68 +0,0 @@ -/** - @file Cone.h - - Cone class - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - @cite Portions based on Dave Eberly's Magic Software Library at http://www.magic-software.com - - @created 2001-06-02 - @edited 2006-02-23 - - Copyright 2000-2006, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_CONE_H -#define G3D_CONE_H - -#include "G3D/platform.h" -#include "G3D/g3dmath.h" -#include "G3D/Vector3.h" - -namespace G3D { - -/** - An infinite cone. - */ -class Cone { - -private: - Vector3 tip; - Vector3 direction; - - /** Angle from the center line to the edge. */ - float angle; - -public: - - /** - @param angle Angle from the center line to the edge, in radians - */ - Cone(const Vector3& tip, const Vector3& direction, float angle); - - /** - Forms the smallest cone that contains the box. Undefined if - the tip is inside or on the box. - */ - Cone(const Vector3& tip, const class Box& box); - - virtual ~Cone() {} - - /** - Returns true if the cone touches, intersects, or contains b. - - If c.intersects(s) and c.intersects(Sphere(s.center, s.radius * 2) - then the sphere s is entirely within cone c. - */ - bool intersects(const class Sphere& s) const; - - /** - True if v is a point inside the cone. - */ - bool contains(const class Vector3& v) const; -}; - -} // namespace - -#endif diff --git a/externals/g3dlite/G3D/ConvexPolyhedron.h b/externals/g3dlite/G3D/ConvexPolyhedron.h deleted file mode 100644 index a6fdd62cf90..00000000000 --- a/externals/g3dlite/G3D/ConvexPolyhedron.h +++ /dev/null @@ -1,180 +0,0 @@ -/** - @file ConvexPolyhedron.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2001-11-11 - @edited 2006-04-10 - - Copyright 2000-2006, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_CONVEXPOLYHEDRON_H -#define G3D_CONVEXPOLYHEDRON_H - -#include "G3D/platform.h" -#include "G3D/Vector3.h" -#include "G3D/Vector2.h" -#include "G3D/CoordinateFrame.h" -#include "G3D/Plane.h" -#include "G3D/Line.h" -#include "G3D/Array.h" - -namespace G3D { - -class DirectedEdge { -public: - Vector3 start; - Vector3 stop; -}; - -class ConvexPolygon { -private: - - friend class ConvexPolyhedron; - - Array _vertex; - -public: - - ConvexPolygon() {} - ConvexPolygon(const Vector3& v0, const Vector3& v1, const Vector3& v2); - ConvexPolygon(const Array& __vertex); - virtual ~ConvexPolygon() {} - - /** - Counter clockwise winding order. - */ - inline const Vector3& vertex(int i) const { - return _vertex[i]; - } - - inline void setVertex(int i, const Vector3& v) { - _vertex[i] = v; - } - - /** - Zero vertices indicates an empty polygon (zero area). - */ - inline int numVertices() const { - return _vertex.size(); - } - - inline void setNumVertices(int n) { - _vertex.resize(n); - } - - /** - O(n) in the number of edges - */ - bool isEmpty() const; - - /** - Cuts the polygon at the plane. If the polygon is entirely above or below - the plane, one of the returned polygons will be empty. - - @param above The part of the polygon above (on the side the - normal points to or in the plane) the plane - @param below The part of the polygon below the plane. - @param newEdge If a new edge was introduced, this is that edge (on the above portion; the below portion is the opposite winding. - */ - void cut(const Plane& plane, ConvexPolygon &above, ConvexPolygon &below, DirectedEdge& newEdge); - void cut(const Plane& plane, ConvexPolygon &above, ConvexPolygon &below); - - /** - When a cut plane grazes a vertex in the polygon, two near-identical vertices may be created. - The closeness of these two points can cause a number of problems, such as ConvexPolygon::normal() - returning an infinite vector. It should be noted, however, that not all applications are - sensitive to near-identical vertices. - - removeDuplicateVertices() detects and eliminates redundant vertices. - */ - void removeDuplicateVertices(); - - /** - O(n) in the number of edges - */ - float getArea() const; - - inline Vector3 normal() const { - debugAssert(_vertex.length() >= 3); - return (_vertex[1] - _vertex[0]).cross(_vertex[2] - _vertex[0]).direction(); - } - - /** - Returns the same polygon with inverse winding. - */ - ConvexPolygon inverse() const; -}; - - - -class ConvexPolyhedron { -public: - /** - Zero faces indicates an empty polyhedron - */ - Array face; - - ConvexPolyhedron() {} - ConvexPolyhedron(const Array& _face); - - /** - O(n) in the number of edges - */ - bool isEmpty() const; - - /** - O(n) in the number of edges - */ - float getVolume() const; - - /** - Cuts the polyhedron at the plane. If the polyhedron is entirely above or below - the plane, one of the returned polyhedra will be empty. - - @param above The part of the polyhedron above (on the side the - normal points to or in the plane) the plane - @param below The part of the polyhedron below the plane. - */ - void cut(const Plane& plane, ConvexPolyhedron &above, ConvexPolyhedron &below); -}; - -/** - - */ -class ConvexPolygon2D { -private: - - Array m_vertex; - -public: - - ConvexPolygon2D() {} - - /** - Points are counter-clockwise in a Y = down, X = right coordinate - system. - - @param reverse If true, the points are reversed (i.e. winding direction is changed) - before the polygon is created. - */ - ConvexPolygon2D(const Array& pts, bool reverse = false); - - inline int numVertices() const { - return m_vertex.size(); - } - - inline const Vector2& vertex(int index) const { - debugAssert((index >= 0) && (index <= m_vertex.size())); - return m_vertex[index]; - } - - /** @param reverseWinding If true, the winding direction of the polygon is reversed for this test.*/ - bool contains(const Vector2& p, bool reverseWinding = false) const; -}; - - -} // namespace -#endif diff --git a/externals/g3dlite/G3D/CoordinateFrame.h b/externals/g3dlite/G3D/CoordinateFrame.h deleted file mode 100644 index 7ed4d0acc65..00000000000 --- a/externals/g3dlite/G3D/CoordinateFrame.h +++ /dev/null @@ -1,331 +0,0 @@ -/** - @file CoordinateFrame.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2001-03-04 - @edited 2009-04-29 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. -*/ - -#ifndef G3D_CFrame_h -#define G3D_CFrame_h - -#include "G3D/platform.h" -#include "G3D/Vector3.h" -#include "G3D/Vector4.h" -#include "G3D/Matrix3.h" -#include "G3D/Array.h" -#include -#include -#include -#include -#include - -#ifdef _MSC_VER -// Turn off "conditional expression is constant" warning; MSVC generates this -// for debug assertions in inlined methods. -# pragma warning (disable : 4127) -#endif - - -namespace G3D { -class Any; - -/** - A rigid body RT (rotation-translation) transformation. - -CoordinateFrame abstracts a 4x4 matrix that maps object space to world space: - - v_world = C * v_object - -CoordinateFrame::rotation is the upper 3x3 submatrix, CoordinateFrame::translation -is the right 3x1 column. The 4th row is always [0 0 0 1], so it isn't stored. -So you don't have to remember which way the multiplication and transformation work, -it provides explicit toWorldSpace and toObjectSpace methods. Also, points, vectors -(directions), and surface normals transform differently, so they have separate methods. - -Some helper functions transform whole primitives like boxes in and out of object space. - -Convert to Matrix4 using CoordinateFrame::toMatrix4. You can construct a CoordinateFrame -from a Matrix4 using Matrix4::approxCoordinateFrame, however, because a Matrix4 is more -general than a CoordinateFrame, some information may be lost. - -@sa G3D::UprightFrame, G3D::PhysicsFrame, G3D::Matrix4, G3D::Quat -*/ -class CoordinateFrame { -public: - - /** Takes object space points to world space. */ - Matrix3 rotation; - - /** Takes object space points to world space. */ - Vector3 translation; - - /** \param any Must be in one of the following forms: - - CFrame((matrix3 expr), (vector3 expr)) - - CFrame::fromXYZYPRDegrees(#, #, #, #, #, #) - - CFrame { rotation = (matrix3 expr), translation = (vector3 expr) } - */ - CoordinateFrame(const Any& any); - - /** Converts the CFrame to an Any. */ - operator Any() const; - - inline bool operator==(const CoordinateFrame& other) const { - return (translation == other.translation) && (rotation == other.rotation); - } - - inline bool operator!=(const CoordinateFrame& other) const { - return !(*this == other); - } - - bool fuzzyEq(const CoordinateFrame& other) const; - - bool fuzzyIsIdentity() const; - - bool isIdentity() const; - - /** - Initializes to the identity coordinate frame. - */ - CoordinateFrame(); - - CoordinateFrame(const Vector3& _translation) : - rotation(Matrix3::identity()), translation(_translation) { - } - - CoordinateFrame(const Matrix3 &rotation, const Vector3 &translation) : - rotation(rotation), translation(translation) { - } - - CoordinateFrame(const Matrix3 &rotation) : - rotation(rotation), translation(Vector3::zero()) { - } - - CoordinateFrame(const class UprightFrame& f); - - static CoordinateFrame fromXYZYPRRadians(float x, float y, float z, float yaw = 0.0f, float pitch = 0.0f, float roll = 0.0f); - - /** Construct a coordinate frame from translation = (x,y,z) and - rotations (in that order) about Y, object space X, object space - Z. Note that because object-space axes are used, these are not - equivalent to Euler angles; they are known as Tait-Bryan - rotations and are more convenient for intuitive positioning.*/ - static CoordinateFrame fromXYZYPRDegrees(float x, float y, float z, float yaw = 0.0f, float pitch = 0.0f, float roll = 0.0f); - - CoordinateFrame(class BinaryInput& b); - - void deserialize(class BinaryInput& b); - - void serialize(class BinaryOutput& b) const; - - CoordinateFrame(const CoordinateFrame &other) : - rotation(other.rotation), translation(other.translation) {} - - /** - Computes the inverse of this coordinate frame. - */ - inline CoordinateFrame inverse() const { - CoordinateFrame out; - out.rotation = rotation.transpose(); - out.translation = -out.rotation * translation; - return out; - } - - inline ~CoordinateFrame() {} - - /** See also Matrix4::approxCoordinateFrame */ - class Matrix4 toMatrix4() const; - - void getXYZYPRRadians(float& x, float& y, float& z, float& yaw, float& pitch, float& roll) const; - void getXYZYPRDegrees(float& x, float& y, float& z, float& yaw, float& pitch, float& roll) const; - - - /** - Produces an XML serialization of this coordinate frame. - @deprecated - */ - std::string toXML() const; - - /** - Returns the heading of the lookVector as an angle in radians relative to - the world -z axis. That is, a counter-clockwise heading where north (-z) - is 0 and west (-x) is PI/2. - - Note that the heading ignores the Y axis, so an inverted - object has an inverted heading. - */ - inline float getHeading() const { - Vector3 look = rotation.column(2); - float angle = -(float) atan2(-look.x, look.z); - return angle; - } - - /** - Takes the coordinate frame into object space. - this->inverse() * c - */ - inline CoordinateFrame toObjectSpace(const CoordinateFrame& c) const { - return this->inverse() * c; - } - - inline Vector4 toObjectSpace(const Vector4& v) const { - return this->inverse().toWorldSpace(v); - } - - inline Vector4 toWorldSpace(const Vector4& v) const { - return Vector4(rotation * Vector3(v.x, v.y, v.z) + translation * v.w, v.w); - } - - /** - Transforms the point into world space. - */ - inline Vector3 pointToWorldSpace(const Vector3& v) const { - return Vector3( - rotation[0][0] * v[0] + rotation[0][1] * v[1] + rotation[0][2] * v[2] + translation[0], - rotation[1][0] * v[0] + rotation[1][1] * v[1] + rotation[1][2] * v[2] + translation[1], - rotation[2][0] * v[0] + rotation[2][1] * v[1] + rotation[2][2] * v[2] + translation[2]); - } - - /** - Transforms the point into object space. Assumes that the rotation matrix is orthonormal. - */ - inline Vector3 pointToObjectSpace(const Vector3& v) const { - float p[3]; - p[0] = v[0] - translation[0]; - p[1] = v[1] - translation[1]; - p[2] = v[2] - translation[2]; - debugAssert(G3D::fuzzyEq(rotation.determinant(), 1.0f)); - return Vector3( - rotation[0][0] * p[0] + rotation[1][0] * p[1] + rotation[2][0] * p[2], - rotation[0][1] * p[0] + rotation[1][1] * p[1] + rotation[2][1] * p[2], - rotation[0][2] * p[0] + rotation[1][2] * p[1] + rotation[2][2] * p[2]); - } - - /** - Transforms the vector into world space (no translation). - */ - inline Vector3 vectorToWorldSpace(const Vector3& v) const { - return rotation * v; - } - - inline Vector3 normalToWorldSpace(const Vector3& v) const { - return rotation * v; - } - - class Ray toObjectSpace(const Ray& r) const; - - Ray toWorldSpace(const Ray& r) const; - - /** - Transforms the vector into object space (no translation). - */ - inline Vector3 vectorToObjectSpace(const Vector3 &v) const { - // Multiply on the left (same as rotation.transpose() * v) - return v * rotation; - } - - inline Vector3 normalToObjectSpace(const Vector3 &v) const { - // Multiply on the left (same as rotation.transpose() * v) - return v * rotation; - } - - void pointToWorldSpace(const Array& v, Array& vout) const; - - void normalToWorldSpace(const Array& v, Array& vout) const; - - void vectorToWorldSpace(const Array& v, Array& vout) const; - - void pointToObjectSpace(const Array& v, Array& vout) const; - - void normalToObjectSpace(const Array& v, Array& vout) const; - - void vectorToObjectSpace(const Array& v, Array& vout) const; - - class Box toWorldSpace(const class AABox& b) const; - - class Box toWorldSpace(const class Box& b) const; - - class Cylinder toWorldSpace(const class Cylinder& b) const; - - class Capsule toWorldSpace(const class Capsule& b) const; - - class Plane toWorldSpace(const class Plane& p) const; - - class Sphere toWorldSpace(const class Sphere& b) const; - - class Triangle toWorldSpace(const class Triangle& t) const; - - class Box toObjectSpace(const AABox& b) const; - - class Box toObjectSpace(const Box& b) const; - - class Plane toObjectSpace(const Plane& p) const; - - class Sphere toObjectSpace(const Sphere& b) const; - - Triangle toObjectSpace(const Triangle& t) const; - - /** Compose: create the transformation that is other followed by this.*/ - CoordinateFrame operator*(const CoordinateFrame &other) const { - return CoordinateFrame(rotation * other.rotation, - pointToWorldSpace(other.translation)); - } - - CoordinateFrame operator+(const Vector3& v) const { - return CoordinateFrame(rotation, translation + v); - } - - CoordinateFrame operator-(const Vector3& v) const { - return CoordinateFrame(rotation, translation - v); - } - - void lookAt(const Vector3& target); - - void lookAt( - const Vector3& target, - Vector3 up); - - /** The direction this camera is looking (its negative z axis)*/ - inline Vector3 lookVector() const { - return -rotation.column(2); - } - - /** Returns the ray starting at the camera origin travelling in direction CoordinateFrame::lookVector. */ - class Ray lookRay() const; - - /** Up direction for this camera (its y axis). */ - inline Vector3 upVector() const { - return rotation.column(1); - } - - inline Vector3 rightVector() const { - return rotation.column(0); - } - - /** - If a viewer looks along the look vector, this is the viewer's "left". - Useful for strafing motions and building alternative coordinate frames. - */ - inline Vector3 leftVector() const { - return -rotation.column(0); - } - - /** - Linearly interpolates between two coordinate frames, using - Quat::slerp for the rotations. - */ - CoordinateFrame lerp( - const CoordinateFrame& other, - float alpha) const; - -}; - -typedef CoordinateFrame CFrame; - -} // namespace - -#endif diff --git a/externals/g3dlite/G3D/Crypto.h b/externals/g3dlite/G3D/Crypto.h deleted file mode 100644 index 56c816a4977..00000000000 --- a/externals/g3dlite/G3D/Crypto.h +++ /dev/null @@ -1,96 +0,0 @@ -/** - @file Crypto.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - - @created 2006-03-29 - @edited 2006-04-06 - */ - -#ifndef G3D_CRYPTO_H -#define G3D_CRYPTO_H - -#include "G3D/platform.h" -#include "G3D/g3dmath.h" -#include - -namespace G3D { - -/** See G3D::Crypto::md5 */ -class MD5Hash { -private: - - uint8 value[16]; - -public: - - MD5Hash() { - for (int i = 0; i < 16; ++i) { - value[i] = 0; - } - } - - explicit MD5Hash(class BinaryInput& b); - - uint8& operator[](int i) { - return value[i]; - } - - const uint8& operator[](int i) const { - return value[i]; - } - - bool operator==(const MD5Hash& other) const { - bool match = true; - for (int i = 0; i < 16; ++i) { - match = match && (other.value[i] == value[i]); - } - return match; - } - - inline bool operator!=(const MD5Hash& other) const { - return !(*this == other); - } - - void deserialize(class BinaryInput& b); - - void serialize(class BinaryOutput& b) const; -}; - - -/** Cryptography and hashing helper functions */ -class Crypto { -public: - - /** - Computes the CRC32 value of a byte array. CRC32 is designed to be a hash - function that produces different values for similar strings. - - This implementation is compatible with PKZIP and GZIP. - - Based on http://www.gamedev.net/reference/programming/features/crc32/ - */ - static uint32 crc32(const void* bytes, size_t numBytes); - - /** - Computes the MD5 hash (message digest) of a byte stream, as defined by - http://www.ietf.org/rfc/rfc1321.txt. - - @cite Based on implementation by L. Peter Deutsch, ghost@aladdin.com - */ - MD5Hash md5(const void* bytes, size_t numBytes); - - /** - Returns the nth prime less than 2000 in constant time. The first prime has index - 0 and is the number 2. - */ - static int smallPrime(int n); - - /** Returns 1 + the largest value that can be passed to smallPrime. */ - static int numSmallPrimes(); -}; - -} - -#endif diff --git a/externals/g3dlite/G3D/Cylinder.h b/externals/g3dlite/G3D/Cylinder.h deleted file mode 100644 index 85eba77b794..00000000000 --- a/externals/g3dlite/G3D/Cylinder.h +++ /dev/null @@ -1,92 +0,0 @@ -/** - @file Cylinder.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2003-02-07 - @edited 2005-09-26 - - Copyright 2000-2005, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_Cylinder_H -#define G3D_Cylinder_H - -#include "G3D/platform.h" -#include "G3D/g3dmath.h" -#include "G3D/Vector3.h" - -namespace G3D { - -class Line; -class AABox; -/** - Right cylinder - */ -class Cylinder { -private: - Vector3 p1; - Vector3 p2; - - float mRadius; - -public: - - /** Uninitialized */ - Cylinder(); - Cylinder(class BinaryInput& b); - Cylinder(const Vector3& _p1, const Vector3& _p2, float _r); - void serialize(class BinaryOutput& b) const; - void deserialize(class BinaryInput& b); - - /** The line down the center of the Cylinder */ - Line axis() const; - - /** - A reference frame in which the center of mass is at the origin and - the Y-axis is the cylinder's axis. If the cylinder is transformed, this reference frame - may freely rotate around its axis.*/ - void getReferenceFrame(class CoordinateFrame& cframe) const; - - /** Returns point 0 or 1 */ - inline const Vector3& point(int i) const { - debugAssert(i >= 0 && i <= 1); - return (i == 0) ? p1 : p2; - } - - /** - Returns true if the point is inside the Cylinder or on its surface. - */ - bool contains(const Vector3& p) const; - - float area() const; - - float volume() const; - - float radius() const; - - /** Center of mass */ - inline Vector3 center() const { - return (p1 + p2) / 2.0f; - } - - inline float height() const { - return (p1 - p2).magnitude(); - } - - /** - Get close axis aligned bounding box. - With vertical world orientation, the top and bottom might not be very tight. */ - void getBounds(AABox& out) const; - - /** Random world space point with outward facing normal. */ - void getRandomSurfacePoint(Vector3& P, Vector3& N) const; - - /** Point selected uniformly at random over the volume. */ - Vector3 randomInteriorPoint() const; -}; - -} // namespace - -#endif diff --git a/externals/g3dlite/G3D/EqualsTrait.h b/externals/g3dlite/G3D/EqualsTrait.h deleted file mode 100644 index 349cb5088fb..00000000000 --- a/externals/g3dlite/G3D/EqualsTrait.h +++ /dev/null @@ -1,26 +0,0 @@ -/** - @file EqualsTrait.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - @created 2008-10-01 - @edited 2008-10-01 - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_EQUALSTRAIT_H -#define G3D_EQUALSTRAIT_H - -#include "G3D/platform.h" - -/** Default implementation of EqualsTrait. - @see G3D::Table for specialization requirements. -*/ -template struct EqualsTrait { - static bool equals(const Key& a, const Key& b) { - return a == b; - } -}; - -#endif - diff --git a/externals/g3dlite/G3D/G3D.h b/externals/g3dlite/G3D/G3D.h deleted file mode 100644 index 5b56b9c71dc..00000000000 --- a/externals/g3dlite/G3D/G3D.h +++ /dev/null @@ -1,162 +0,0 @@ -/** - @file G3D.h - - This header includes all of the G3D libraries in - appropriate namespaces. - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2001-08-25 - @edited 2010-01-30 - - Copyright 2000-2010, Morgan McGuire. - All rights reserved. -*/ - -#ifndef G3D_G3D_h -#define G3D_G3D_h - -#define NOMINMAX 1 -#ifdef min - #undef min -#endif -#ifdef max - #undef max -#endif - -#include "G3D/platform.h" -#include "G3D/units.h" -#include "G3D/ParseError.h" -#include "G3D/Random.h" -#include "G3D/Array.h" -#include "G3D/SmallArray.h" -#include "G3D/Queue.h" -#include "G3D/Crypto.h" -#include "G3D/format.h" -#include "G3D/Vector2.h" -#include "G3D/Vector3.h" -#include "G3D/Vector4.h" -#include "G3D/Color1.h" -#include "G3D/Color3.h" -#include "G3D/Color4.h" -#include "G3D/Matrix2.h" -#include "G3D/Matrix3.h" -#include "G3D/Matrix4.h" -#include "G3D/CoordinateFrame.h" -#include "G3D/PhysicsFrame.h" -#include "G3D/Plane.h" -#include "G3D/Line.h" -#include "G3D/Ray.h" -#include "G3D/Sphere.h" -#include "G3D/Box.h" -#include "G3D/Box2D.h" -#include "G3D/AABox.h" -#include "G3D/WrapMode.h" -#include "G3D/Cone.h" -#include "G3D/Quat.h" -#include "G3D/stringutils.h" -#include "G3D/prompt.h" -#include "G3D/Table.h" -#include "G3D/Set.h" -#include "G3D/GUniqueID.h" -#include "G3D/BinaryFormat.h" -#include "G3D/BinaryInput.h" -#include "G3D/BinaryOutput.h" -#include "G3D/debug.h" -#include "G3D/g3dfnmatch.h" -#include "G3D/G3DGameUnits.h" -#include "G3D/g3dmath.h" -#include "G3D/uint128.h" -#include "G3D/fileutils.h" -#include "G3D/ReferenceCount.h" -#include "G3D/Welder.h" -#include "G3D/GMutex.h" -#include "G3D/PrecomputedRandom.h" -#include "G3D/MemoryManager.h" -#include "G3D/AreaMemoryManager.h" -#include "G3D/BumpMapPreprocess.h" - -template struct HashTrait< G3D::ReferenceCountedPointer > { - static size_t hashCode(G3D::ReferenceCountedPointer key) { return reinterpret_cast( key.pointer() ); } -}; - -#include "G3D/GImage.h" -#include "G3D/CollisionDetection.h" -#include "G3D/Intersect.h" -#include "G3D/Log.h" -#include "G3D/serialize.h" -#include "G3D/TextInput.h" -#include "G3D/NetAddress.h" -#include "G3D/NetworkDevice.h" -#include "G3D/System.h" -#include "G3D/splinefunc.h" -#include "G3D/Spline.h" -#include "G3D/UprightFrame.h" -#include "G3D/LineSegment.h" -#include "G3D/Capsule.h" -#include "G3D/Cylinder.h" -#include "G3D/Triangle.h" -#include "G3D/Color3uint8.h" -#include "G3D/Color4uint8.h" -#include "G3D/Vector2int16.h" -#include "G3D/Vector3int16.h" -#include "G3D/Vector3int32.h" -#include "G3D/Vector4int8.h" -#include "G3D/ConvexPolyhedron.h" -#include "G3D/MeshAlg.h" -#include "G3D/vectorMath.h" -#include "G3D/Rect2D.h" -#include "G3D/GCamera.h" -#include "G3D/GLight.h" -#include "G3D/KDTree.h" -#include "G3D/PointKDTree.h" -#include "G3D/TextOutput.h" -#include "G3D/MeshBuilder.h" -#include "G3D/Stopwatch.h" -#include "G3D/AtomicInt32.h" -#include "G3D/GThread.h" -#include "G3D/ThreadSet.h" -#include "G3D/RegistryUtil.h" -#include "G3D/Any.h" -#include "G3D/PointHashGrid.h" -#include "G3D/Map2D.h" -#include "G3D/Image1.h" -#include "G3D/Image1uint8.h" -#include "G3D/Image3.h" -#include "G3D/Image3uint8.h" -#include "G3D/Image4.h" -#include "G3D/Image4uint8.h" -#include "G3D/filter.h" -#include "G3D/WeakCache.h" -#include "G3D/Pointer.h" -#include "G3D/Matrix.h" -#include "G3D/ImageFormat.h" - -#ifdef _MSC_VER -# pragma comment(lib, "zlib") -# pragma comment(lib, "ws2_32") -# pragma comment(lib, "winmm") -# pragma comment(lib, "imagehlp") -# pragma comment(lib, "gdi32") -# pragma comment(lib, "user32") -# pragma comment(lib, "kernel32") -# pragma comment(lib, "version") -# pragma comment(lib, "advapi32") -# pragma comment(lib, "png") -# pragma comment(lib, "jpeg") -# pragma comment(lib, "zip") -# ifdef _DEBUG - // Don't link against G3D when building G3D itself. -# ifndef G3D_BUILDING_LIBRARY_DLL -# pragma comment(lib, "G3Dd.lib") -# endif -# else - // Don't link against G3D when building G3D itself. -# ifndef G3D_BUILDING_LIBRARY_DLL -# pragma comment(lib, "G3D.lib") -# endif -# endif -#endif - -#endif - diff --git a/externals/g3dlite/G3D/G3DAll.h b/externals/g3dlite/G3D/G3DAll.h deleted file mode 100644 index 1176fe742e7..00000000000 --- a/externals/g3dlite/G3D/G3DAll.h +++ /dev/null @@ -1,26 +0,0 @@ -/** - @file G3DAll.h - - Includes all G3D and GLG3D files and uses the G3D namespace. - - This requires OpenGL and SDL headers. If you don't want all of this, - \#include separately. - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2002-01-01 - @edited 2006-08-13 - - Copyright 2000-2006, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_G3DALL_H -#define G3D_G3DALL_H - -#include "G3D/G3D.h" -#include "GLG3D/GLG3D.h" - -using namespace G3D; - -#endif diff --git a/externals/g3dlite/G3D/G3DGameUnits.h b/externals/g3dlite/G3D/G3DGameUnits.h deleted file mode 100644 index e2bc2c811e8..00000000000 --- a/externals/g3dlite/G3D/G3DGameUnits.h +++ /dev/null @@ -1,42 +0,0 @@ -/** - @file G3DGameUnits.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - @created 2002-10-05 - @edited 2006-11-10 - */ - -#ifndef G3D_GAMEUNITS_H -#define G3D_GAMEUNITS_H - -#include "G3D/platform.h" - -namespace G3D { -/** - Time, in seconds. - */ -typedef double GameTime; -typedef double SimTime; - -/** - Actual wall clock time in seconds. - */ -typedef double RealTime; - -enum AMPM {AM, PM}; - -/** \deprecated */ -enum {SECOND=1, MINUTE=60, HOUR = 60*60, DAY=24*60*60, SUNRISE=24*60*60/4, SUNSET=24*60*60*3/4, MIDNIGHT=0, METER=1, KILOMETER=1000}; - -/** - Converts a 12 hour clock time into the number of seconds since - midnight. Note that 12:00 PM is noon and 12:00 AM is midnight. - - Example: toSeconds(10, 00, AM) - */ -SimTime toSeconds(int hour, int minute, double seconds, AMPM ap); -SimTime toSeconds(int hour, int minute, AMPM ap); - -} - -#endif diff --git a/externals/g3dlite/G3D/GCamera.h b/externals/g3dlite/G3D/GCamera.h deleted file mode 100644 index 018fbc85d59..00000000000 --- a/externals/g3dlite/G3D/GCamera.h +++ /dev/null @@ -1,337 +0,0 @@ -/** - @file GCamera.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2005-07-20 - @edited 2009-04-20 -*/ - -#ifndef G3D_GCamera_H -#define G3D_GCamera_H - -#include "G3D/platform.h" -#include "G3D/CoordinateFrame.h" -#include "G3D/Vector3.h" -#include "G3D/Plane.h" -#include "G3D/debugAssert.h" - -namespace G3D { - -class Matrix4; -class Rect2D; -class Any; - -/** - Abstraction of a pinhole camera. - - The area a camera sees is called a frustum. It is bounded by the - near plane, the far plane, and the sides of the view frame projected - into the scene. It has the shape of a pyramid with the top cut off. - - Cameras can project points from 3D to 2D. The "unit" projection - matches OpenGL. It maps the entire view frustum to a cube of unit - radius (i.e., edges of length 2) centered at the origin. The - non-unit projection then maps that cube to the specified pixel - viewport in X and Y and the range [0, 1] in Z. The projection is - reversable as long as the projected Z value is known. - - All viewport arguments are the pixel bounds of the viewport-- e.g., - RenderDevice::viewport(). - */ -class GCamera { - -public: - /** - Stores the direction of the field of view - */ - enum FOVDirection {HORIZONTAL, VERTICAL}; - -private: - - /** Full field of view (in radians) */ - float m_fieldOfView; - - /** Clipping plane, *not* imaging plane. Negative numbers. */ - float m_nearPlaneZ; - - /** Negative */ - float m_farPlaneZ; - - /** Stores the camera's location and orientation */ - CoordinateFrame m_cframe; - - /** Horizontal or Vertical */ - FOVDirection m_direction; - -public: - - /** Must be of the format produced by the Any cast, e.g., - -
-        GCamera {
-            coordinateFrame = CFrame::fromXYZYPRDegrees(-13.3f, 8.0f, -1.9f, 246.6f, -3),
-            nearPlaneZ = -0.5,
-            farPlaneZ = -50,
-            fovDirection = "HORIZONTAL",
-            fovAngleDegrees = 90
-        }
- - Missing fields are filled from the default GCamera constructor. - */ - GCamera(const Any& any); - - operator Any() const; - - class Frustum { - public: - class Face { - public: - /** Counter clockwise indices into vertexPos */ - int vertexIndex[4]; - - /** The plane containing the face. */ - Plane plane; - }; - - /** The vertices, in homogeneous space. If w == 0, - a vertex is at infinity. */ - Array vertexPos; - - /** The faces in the frustum. When the - far plane is at infinity, there are 5 faces, - otherwise there are 6. The faces are in the order - N,R,L,B,T,[F]. - */ - Array faceArray; - }; - - GCamera(); - - GCamera(const Matrix4& proj, const CFrame& frame); - - virtual ~GCamera(); - - /** Returns the current coordinate frame */ - const CoordinateFrame& coordinateFrame() const { - return m_cframe; - } - - /** Sets c to the camera's coordinate frame */ - void getCoordinateFrame(CoordinateFrame& c) const; - - /** Sets a new coordinate frame for the camera */ - void setCoordinateFrame(const CoordinateFrame& c); - - /** Sets \a P equal to the camera's projection matrix. This is the - matrix that maps points to the homogeneous clip cube that - varies from -1 to 1 on all axes. The projection matrix does - not include the camera transform. - - This is the matrix that a RenderDevice (or OpenGL) uses as the projection matrix. - @sa RenderDevice::setProjectionAndCameraMatrix, RenderDevice::setProjectionMatrix, Matrix4::perspectiveProjection - */ - void getProjectUnitMatrix(const Rect2D& viewport, Matrix4& P) const; - - /** Sets \a P equal to the matrix that transforms points to pixel - coordinates on the given viewport. A point correspoinding to - the top-left corner of the viewport in camera space will - transform to viewport.x0y0() and the bottom-right to viewport.x1y1(). */ - void getProjectPixelMatrix(const Rect2D& viewport, Matrix4& P) const; - - /** Converts projected points from OpenGL standards - (-1, 1) to normal 3D coordinate standards (0, 1) - - \deprecated - */ // TODO: Remove - Vector3 convertFromUnitToNormal(const Vector3& in, const Rect2D& viewport) const; - - /** - Sets the field of view, in radians. The - initial angle is toRadians(55). Must specify - the direction of the angle. - - This is the full angle, i.e., from the left side of the - viewport to the right side. - */ - void setFieldOfView(float angle, FOVDirection direction); - - /** Returns the current full field of view angle (from the left side of the - viewport to the right side) and direction */ - inline void getFieldOfView(float& angle, FOVDirection& direction) const { - angle = m_fieldOfView; - direction = m_direction; - } - - /** - Projects a world space point onto a width x height screen. The - returned coordinate uses pixmap addressing: x = right and y = - down. The resulting z value is 0 at the near plane, 1 at the far plane, - and is a linear compression of unit cube projection. - - If the point is behind the camera, Vector3::inf() is returned. - */ - Vector3 project(const G3D::Vector3& point, - const class Rect2D& viewport) const; - - /** - Projects a world space point onto a unit cube. The resulting - x,y,z values range between -1 and 1, where z is -1 - at the near plane and 1 at the far plane and varies hyperbolically in between. - - If the point is behind the camera, Vector3::inf() is returned. - */ - Vector3 projectUnit(const G3D::Vector3& point, - const class Rect2D& viewport) const; - - /** - Gives the world-space coordinates of screen space point v, where - v.x is in pixels from the left, v.y is in pixels from - the top, and v.z is on the range 0 (near plane) to 1 (far plane). - */ - Vector3 unproject(const Vector3& v, const Rect2D& viewport) const; - - /** - Gives the world-space coordinates of unit cube point v, where - v varies from -1 to 1 on all axes. The unproject first - transforms the point into a pixel location for the viewport, then calls unproject - */ - Vector3 unprojectUnit(const Vector3& v, const Rect2D& viewport) const; - - /** - Returns the pixel area covered by a shape of the given - world space area at the given z value (z must be negative). - */ - float worldToScreenSpaceArea(float area, float z, const class Rect2D& viewport) const; - - /** - Returns the world space 3D viewport corners. These - are at the near clipping plane. The corners are constructed - from the nearPlaneZ, viewportWidth, and viewportHeight. - "left" and "right" are from the GCamera's perspective. - */ - void getNearViewportCorners(const class Rect2D& viewport, - Vector3& outUR, Vector3& outUL, - Vector3& outLL, Vector3& outLR) const; - - /** - Returns the world space 3D viewport corners. These - are at the Far clipping plane. The corners are constructed - from the nearPlaneZ, farPlaneZ, viewportWidth, and viewportHeight. - "left" and "right" are from the GCamera's perspective. - */ - void getFarViewportCorners(const class Rect2D& viewport, - Vector3& outUR, Vector3& outUL, - Vector3& outLL, Vector3& outLR) const; - - /** - Returns the image plane depth, assumes imagePlane - is the same as the near clipping plane. - returns a positive number. - */ - float imagePlaneDepth() const; - - /** - Returns the world space ray passing through the center of pixel - (x, y) on the image plane. The pixel x and y axes are opposite - the 3D object space axes: (0,0) is the upper left corner of the screen. - They are in viewport coordinates, not screen coordinates. - - The ray origin is at the origin. To start it at the image plane, - move it forward by imagePlaneDepth/ray.direction.z - - Integer (x, y) values correspond to - the upper left corners of pixels. If you want to cast rays - through pixel centers, add 0.5 to x and y. - */ - Ray worldRay( - float x, - float y, - const class Rect2D& viewport) const; - - /** - Returns a negative z-value. - */ - inline float nearPlaneZ() const { - return m_nearPlaneZ; - } - - /** - Returns a negative z-value. - */ - inline float farPlaneZ() const { - return m_farPlaneZ; - } - - /** - Sets a new value for the far clipping plane - Expects a negative value - */ - inline void setFarPlaneZ(float z) { - debugAssert(z < 0); - m_farPlaneZ = z; - } - - /** - Sets a new value for the near clipping plane - Expects a negative value - */ - inline void setNearPlaneZ(float z) { - debugAssert(z < 0); - m_nearPlaneZ = z; - } - - /** - Returns the camera space width of the viewport at the near plane. - */ - float viewportWidth(const class Rect2D& viewport) const; - - /** - Returns the camera space height of the viewport at the near plane. - */ - float viewportHeight(const class Rect2D& viewport) const; - - void setPosition(const Vector3& t); - - /** Rotate the camera in place to look at the target. Does not - persistently look at that location when the camera moves; - i.e., if you move the camera and still want it to look at the - old target, you must call lookAt again after moving the - camera.)*/ - void lookAt(const Vector3& position, const Vector3& up = Vector3::unitY()); - - /** - Returns the clipping planes of the frustum, in world space. - The planes have normals facing into the view frustum. - - The plane order is guaranteed to be: - Near, Right, Left, Top, Bottom, [Far] - - If the far plane is at infinity, the resulting array will have - 5 planes, otherwise there will be 6. - - The viewport is used only to determine the aspect ratio of the screen; the - absolute dimensions and xy values don't matter. - */ - void getClipPlanes - ( - const Rect2D& viewport, - Array& outClip) const; - - /** - Returns the world space view frustum, which is a truncated pyramid describing - the volume of space seen by this camera. - */ - void frustum(const Rect2D& viewport, GCamera::Frustum& f) const; - - GCamera::Frustum frustum(const Rect2D& viewport) const; - - /** Read and Write camera parameters */ - void serialize(class BinaryOutput& bo) const; - void deserialize(class BinaryInput& bi); - -}; - -} // namespace G3D - -#endif diff --git a/externals/g3dlite/G3D/GImage.h b/externals/g3dlite/G3D/GImage.h deleted file mode 100644 index 8ae11134fc9..00000000000 --- a/externals/g3dlite/G3D/GImage.h +++ /dev/null @@ -1,607 +0,0 @@ -/** - \file GImage.h - - See G3D::GImage for details. - - @cite JPEG compress/decompressor is the IJG library, used in accordance with their license. - @cite JPG code by John Chisholm, using the IJG Library - @cite TGA code by Morgan McGuire - @cite BMP code by John Chisholm, based on code by Edward "CGameProgrammer" Resnick mailto:cgp@gdnmail.net at ftp://ftp.flipcode.com/cotd/LoadPicture.txt - @cite PCX format described in the ZSOFT PCX manual http://www.nist.fss.ru/hr/doc/spec/pcx.htm#2 - @cite PNG compress/decompressor is the libpng library, used in accordance with their license. - @cite PPM code by Morgan McGuire based on http://netpbm.sourceforge.net/doc/ppm.html - - \maintainer Morgan McGuire, http://graphics.cs.williams.edu - - \created 2002-05-27 - \edited 2010-01-04 - - Copyright 2000-2010, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_GImage_h -#define G3D_GImage_h - -#include "G3D/platform.h" -#include -#include "G3D/Array.h" -#include "G3D/g3dmath.h" -#include "G3D/stringutils.h" -#include "G3D/Color1uint8.h" -#include "G3D/Color3uint8.h" -#include "G3D/Color4uint8.h" -#include "G3D/MemoryManager.h" -#include "G3D/BumpMapPreprocess.h" - -namespace G3D { -class BinaryInput; -class BinaryOutput; - - -/** - Interface to image compression & file formats. - - Supported formats (decode and encode): Color JPEG, PNG, - (Uncompressed)TGA 24, (Uncompressed)TGA 32, BMP 1, BMP 4, BMP 8, BMP - 24, PPM (P6), and PPM ASCII (P1, P2, P3), which includes PPM, PGM, - and PBM. 8-bit paletted PCX, 24-bit PCX, and ICO are supported for - decoding only. - - Sample usage: - - \verbatim - // Loading from disk: - G3D::GImage im1("test.jpg"); - - // Loading from memory: - G3D::GImage im2(data, length); - - // im.pixel is a pointer to RGB color data. If you want - // an alpha channel, call RGBtoRGBA or RGBtoARGB for - // conversion. - - // Saving to memory: - G3D::GImage im3(width, height); - // (Set the pixels of im3...) - uint8* data2; - int len2; - im3.encode(G3D::GImage::JPEG, data2, len2); - - // Saving to disk - im3.save("out.jpg"); - \endverbatim - - The free Image Magick Magick Wand API - (http://www.imagemagick.org/www/api/magick_wand.html) provides a more powerful - API for image manipulation and wider set of image load/save formats. It is - recommended over GImage (we don't include it directly in G3D because their license - is more restrictive than the BSD one). - - */ -class GImage { -private: - - /** Used exclusively for allocating m_byte; this may be an - implementation that allocates directly on a GPU.*/ - MemoryManager::Ref m_memMan; - uint8* m_byte; - - int m_channels; - int m_width; - int m_height; - -public: - - class Error { - public: - Error( - const std::string& reason, - const std::string& filename = "") : - reason(reason), filename(filename) {} - - std::string reason; - std::string filename; - }; - - /** PGM, PPM, and PBM all come in two versions and are classified as PPM_* files */ - enum Format {JPEG, BMP, TGA, PCX, ICO, PNG, - PPM_BINARY, PGM_BINARY = PPM_BINARY, - PPM_ASCII, PGM_ASCII = PPM_ASCII, - AUTODETECT, UNKNOWN}; - - - /** - The number of channels; either 3 (RGB) or 4 (RGBA) - */ - inline int channels() const { - return m_channels; - } - - inline int width() const { - return m_width; - } - - inline int height() const { - return m_height; - } - - inline const uint8* byte() const { - return m_byte; - } - - /** Returns a pointer to the underlying data, which is stored - in row-major order without row padding. - e.g., uint8* ptr = image.rawData(); - */ - template - inline const Type* rawData() const { - return (Type*)m_byte; - } - - /** \copybrief GImage::rawData() const */ - template - inline Type* rawData() { - return (Type*)m_byte; - } - - inline const Color1uint8* pixel1() const { - debugAssertM(m_channels == 1, format("Tried to call GImage::pixel1 on an image with %d channels", m_channels)); - return (Color1uint8*)m_byte; - } - - inline Color1uint8* pixel1() { - debugAssertM(m_channels == 1, format("Tried to call GImage::pixel1 on an image with %d channels", m_channels)); - return (Color1uint8*)m_byte; - } - - /** Returns a pointer to the upper left pixel - as Color4uint8. - */ - inline const Color4uint8* pixel4() const { - debugAssertM(m_channels == 4, format("Tried to call GImage::pixel4 on an image with %d channels", m_channels)); - return (Color4uint8*)m_byte; - } - - inline Color4uint8* pixel4() { - debugAssert(m_channels == 4); - return (Color4uint8*)m_byte; - } - - /** Returns a pointer to the upper left pixel - as Color3uint8. - */ - inline const Color3uint8* pixel3() const { - debugAssertM(m_channels == 3, format("Tried to call GImage::pixel3 on an image with %d channels", m_channels)); - return (Color3uint8*)m_byte; - } - - inline Color3uint8* pixel3() { - debugAssert(m_channels == 3); - return (Color3uint8*)m_byte; - } - - /** Returns the pixel at (x, y), where (0,0) is the upper left. */ - inline const Color1uint8& pixel1(int x, int y) const { - debugAssert(x >= 0 && x < m_width); - debugAssert(y >= 0 && y < m_height); - return pixel1()[x + y * m_width]; - } - - /** Returns the pixel at (x, y), where (0,0) is the upper left. */ - inline Color1uint8& pixel1(int x, int y) { - debugAssert(x >= 0 && x < m_width); - debugAssert(y >= 0 && y < m_height); - return pixel1()[x + y * m_width]; - } - - /** Returns the pixel at (x, y), where (0,0) is the upper left. */ - inline const Color3uint8& pixel3(int x, int y) const { - debugAssert(x >= 0 && x < m_width); - debugAssert(y >= 0 && y < m_height); - return pixel3()[x + y * m_width]; - } - - inline Color3uint8& pixel3(int x, int y) { - debugAssert(x >= 0 && x < m_width); - debugAssert(y >= 0 && y < m_height); - return pixel3()[x + y * m_width]; - } - - /** Returns the pixel at (x, y), where (0,0) is the upper left. */ - inline const Color4uint8& pixel4(int x, int y) const { - debugAssert(x >= 0 && x < m_width); - debugAssert(y >= 0 && y < m_height); - return pixel4()[x + y * m_width]; - } - - inline Color4uint8& pixel4(int x, int y) { - debugAssert(x >= 0 && x < m_width); - debugAssert(y >= 0 && y < m_height); - return pixel4()[x + y * m_width]; - } - - inline uint8* byte() { - return m_byte; - } - -private: - - void encodeBMP( - BinaryOutput& out) const; - - /** - The TGA file will be either 24- or 32-bit depending - on the number of channels. - */ - void encodeTGA( - BinaryOutput& out) const; - - /** - Converts this image into a JPEG - */ - void encodeJPEG( - BinaryOutput& out) const; - - /** - Converts this image into a JPEG - */ - void encodePNG( - BinaryOutput& out) const; - - void encodePPM( - BinaryOutput& out) const; - - void encodePPMASCII( - BinaryOutput& out) const; - - void decodeTGA( - BinaryInput& input); - - void decodeBMP( - BinaryInput& input); - - void decodeJPEG( - BinaryInput& input); - - void decodePCX( - BinaryInput& input); - - void decodeICO( - BinaryInput& input); - - void decodePNG( - BinaryInput& input); - - void decodePPM( - BinaryInput& input); - - void decodePPMASCII( - BinaryInput& input); - - /** - Given [maybe] a filename, memory buffer, and [maybe] a format, - returns the most likely format of this file. - */ - static Format resolveFormat( - const std::string& filename, - const uint8* data, - int dataLen, - Format maybeFormat); - - void _copy( - const GImage& other); - -public: - - /** Predicts the image file format of \a filename */ - static Format resolveFormat(const std::string& filename); - - void flipHorizontal(); - void flipVertical(); - void rotate90CW(int numTimes = 1); - - /** - Create an empty image of the given size. - \sa load() - */ - GImage( - int width = 0, - int height = 0, - int channels = 3, - const MemoryManager::Ref& m = MemoryManager::create()); - - /** - Load an encoded image from disk and decode it. - Throws GImage::Error if something goes wrong. - */ - GImage( - const std::string& filename, - Format format = AUTODETECT, - const MemoryManager::Ref& m = MemoryManager::create()); - - /** - Decodes an image stored in a buffer. - */ - GImage( - const unsigned char*data, - int length, - Format format = AUTODETECT, - const MemoryManager::Ref& m = MemoryManager::create()); - - GImage( - const GImage& other, - const MemoryManager::Ref& m = MemoryManager::create()); - - GImage& operator=(const GImage& other); - - /** - Returns a new GImage that has 4 channels. RGB is - taken from this GImage and the alpha from the red - channel of the supplied image. The new GImage is passed - as a reference parameter for speed. - */ - void insertRedAsAlpha(const GImage& alpha, GImage& output) const; - - /** - Returns a new GImage with 3 channels, removing - the alpha channel if there is one. The new GImage - is passed as a reference parameter for speed. - */ - void stripAlpha(GImage& output) const; - - /** - Loads an image from disk (clearing the old one first), - using the existing memory manager. - */ - void load( - const std::string& filename, - Format format = AUTODETECT); - - /** - Frees memory and resets to a 0x0 image. - */ - void clear(); - - /** - Deallocates the pixels. - */ - virtual ~GImage(); - - /** - Resizes the internal buffer to (\a width x \a height) with the - number of \a channels specified. - - \param zero If true, all data is set to 0 (black). - */ - void resize(int width, int height, int channels, bool zero = true); - - /** - Copies src sub-image data into dest at a certain offset. - The dest variable must already contain an image that is large - enough to contain the src sub-image at the specified offset. - Returns true on success and false if the src sub-image cannot - completely fit within dest at the specified offset. Both - src and dest must have the same number of channels. - */ - static bool pasteSubImage( - GImage& dest, - const GImage& src, - int destX, - int destY, - int srcX, - int srcY, - int srcWidth, - int srcHeight); - - /** - creates dest from src sub-image data. - Returns true on success and false if the src sub-image - is not within src. - */ - static bool copySubImage(GImage & dest, const GImage & src, - int srcX, int srcY, int srcWidth, int srcHeight); - - void convertToRGBA(); - - void convertToRGB(); - - /** Averages color channels if they exist */ - void convertToL8(); - - /** - Returns true if format is supported. Format - should be an extension string (e.g. "BMP"). - */ - static bool supportedFormat( - const std::string& format); - - /** - Converts a string to an enum, returns UNKNOWN if not recognized. - */ - static Format stringToFormat( - const std::string& format); - - /** - Encode and save to disk. - */ - void save( - const std::string& filename, - Format format = AUTODETECT) const; - - /** - The caller must delete the returned buffer. - TODO: provide a memory manager - */ - void encode( - Format format, - uint8*& outData, - int& outLength) const; - - /** - Does not commit the BinaryOutput when done. - */ - void encode( - Format format, - BinaryOutput& out) const; - - /** - Decodes the buffer into this image. - @param format Must be the correct format. - */ - void decode( - BinaryInput& input, - Format format); - - /** Returns the size of this object in bytes */ - int sizeInMemory() const; - - /** Ok for in == out */ - static void R8G8B8_to_Y8U8V8(int width, int height, const uint8* in, uint8* out); - - /** Ok for in == out */ - static void Y8U8V8_to_R8G8B8(int width, int height, const uint8* in, uint8* out); - - /** - @param in RGB buffer of numPixels * 3 bytes - @param out Buffer of numPixels * 4 bytes - @param numPixels Number of RGB pixels to convert - */ - static void RGBtoRGBA( - const uint8* in, - uint8* out, - int numPixels); - - static void RGBtoARGB( - const uint8* in, - uint8* out, - int numPixels); - - static void LtoRGB - (const uint8* in, - uint8* out, - int numPixels); - - static void LtoRGBA - (const uint8* in, - uint8* out, - int numPixels); - - /** Safe for in == out */ - static void RGBtoBGR( - const uint8* in, - uint8* out, - int numPixels); - - /** - Win32 32-bit HDC format. - */ - static void RGBtoBGRA( - const uint8* in, - uint8* out, - int numPixels); - - static void RGBAtoRGB( - const uint8* in, - uint8* out, - int numPixels); - /** - Uses the red channel of the second image as an alpha channel. - */ - static void RGBxRGBtoRGBA( - const uint8* colorRGB, - const uint8* alphaRGB, - uint8* out, - int numPixels); - - /** - Flips the image along the vertical axis. - Safe for in == out. - */ - static void flipRGBVertical( - const uint8* in, - uint8* out, - int width, - int height); - - static void flipRGBAVertical( - const uint8* in, - uint8* out, - int width, - int height); - - /** - Given a tangent space bump map, computes a new image where the - RGB channels are a tangent space normal map and the alpha channel - is the original bump map. Assumes the input image is tileable. - - In the resulting image, x = red = tangent, y = green = binormal, and z = blue = normal. - - Particularly useful as part of the idiom: -
- 	    GImage normal;
-	    computeNormalMap(GImage(filename), normal);
-	    return Texture::fromGImage(filename, normal);
-    
- - */ - static void computeNormalMap( - const class GImage& bump, - class GImage& normal, - const BumpMapPreprocess& preprocess = BumpMapPreprocess()); - - static void computeNormalMap - (int width, - int height, - int channels, - const uint8* src, - GImage& normal, - const BumpMapPreprocess& preprocess = BumpMapPreprocess()); - - /** - Bayer demosaicing using the filter proposed in - - HIGH-QUALITY LINEAR INTERPOLATION FOR DEMOSAICING OF BAYER-PATTERNED COLOR IMAGES - Henrique S. Malvar, Li-wei He, and Ross Cutler - - The filter wraps at the image boundaries. - - Assumes in != out. - */ - static void BAYER_G8B8_R8G8_to_R8G8B8_MHC(int w, int h, const uint8* in, uint8* _out); - static void BAYER_G8R8_B8G8_to_R8G8B8_MHC(int w, int h, const uint8* in, uint8* _out); - static void BAYER_R8G8_G8B8_to_R8G8B8_MHC(int w, int h, const uint8* in, uint8* _out); - static void BAYER_B8G8_G8R8_to_R8G8B8_MHC(int w, int h, const uint8* in, uint8* _out); - - /** Fast conversion; the output has 1/2 the size of the input in each direction. Assumes in != out. - See G3D::BAYER_G8B8_R8G8_to_R8G8B8_MHC for a much better result. */ - static void BAYER_G8B8_R8G8_to_Quarter_R8G8B8 - (int inWidth, - int inHeight, - const uint8* in, - uint8* out); - - /** Attempt to undo fast conversion of G3D::BAYER_G8B8_R8G8_to_Quarter_R8G8B8; - the green channel will lose data. Assumes in != out - The input should have size 3 * inWidth * inHeight. The output should have size - 2 * inWidth * 2 * inHeight. - */ - static void Quarter_R8G8B8_to_BAYER_G8B8_R8G8 - (int inWidth, - int inHeight, - const uint8* in, - uint8* out); - - /** Overwrites every pixel with one of the two colors in a checkerboard pattern. - The fields used from the two colors depend on the current number of channels in @a im. - */ - static void makeCheckerboard - (GImage& im, - int checkerSize = 1, - const Color4uint8& color1 = Color4uint8(255,255,255,255), - const Color4uint8& color2 = Color4uint8(0,0,0,255)); -}; - -} - -#endif diff --git a/externals/g3dlite/G3D/GLight.h b/externals/g3dlite/G3D/GLight.h deleted file mode 100644 index 3a95f1a8114..00000000000 --- a/externals/g3dlite/G3D/GLight.h +++ /dev/null @@ -1,106 +0,0 @@ -/** - @file GLight.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2003-11-12 - @edited 2009-11-08 -*/ - -#ifndef G3D_GLight_h -#define G3D_GLight_h - -#include "G3D/platform.h" -#include "G3D/Vector4.h" -#include "G3D/Vector3.h" -#include "G3D/Color4.h" - -namespace G3D { -class Any; - -/** - A light representation that closely follows the OpenGL light format. - */ -class GLight { -public: - /** World space position (for a directional light, w = 0 */ - Vector4 position; - - /** For a spot or directional light, this is the "right vector" that will be used when constructing - a reference frame(). */ - Vector3 rightDirection; - - /** Direction in which the light faces, if a spot light. This is the "look vector" of the light source. */ - Vector3 spotDirection; - - /** In degrees. 180 = no cutoff (point/dir). Values less than 90 = spot light */ - float spotCutoff; - - /** If true, G3D::SuperShader will render a cone of light large - enough to encompass the entire square that bounds the cutoff - angle. This produces a square prism instead of a cone of light - when used with a G3D::ShadowMap. for an unshadowed light this - has no effect.*/ - bool spotSquare; - - /** Constant, linear, quadratic */ - float attenuation[3]; - - /** May be outside the range [0, 1] */ - Color3 color; - - /** If false, this light is ignored */ - bool enabled; - - /** If false, this light does not create specular highlights - (useful when using negative lights). */ - bool specular; - - /** If false, this light does not create diffuse illumination - (useful when rendering a specular-only pass). */ - bool diffuse; - - GLight(); - - /** Accepted forms: - - GLight::directional( vector3, color3, [bool, [bool]]) - - GLight::spot(vector3, vector3, #, color3, [#, [#, [#, [#, [bool, [bool]]]]) - - GLight::point(vector3, color3, [#, [#, [#, [#, [bool, [bool]]]]) - - GLight { [all fields] } - */ - GLight(const Any& any); - - /** Converts the Color3 to an Any. */ - operator Any() const; - - /** @param toLight will be normalized */ - static GLight directional(const Vector3& toLight, const Color3& color, bool specular = true, bool diffuse = true); - - static GLight point(const Vector3& pos, const Color3& color, float constAtt = 1, float linAtt = 0, float quadAtt = 0.5f, bool specular = true, bool diffuse = true); - - /** @param pointDirection Will be normalized. Points in the - direction that light propagates. - - @param cutOffAngleDegrees Must be on the range [0, 90]. This - is the angle from the point direction to the edge of the light - cone. I.e., a value of 45 produces a light with a 90-degree - cone of view. - */ - static GLight spot(const Vector3& pos, const Vector3& pointDirection, float cutOffAngleDegrees, - const Color3& color, float constAtt = 1, float linAtt = 0, float quadAtt = 0, - bool specular = true, bool diffuse = true); - - /** Returns the sphere within which this light has some noticable effect. May be infinite. - @param cutoff The value at which the light intensity is considered negligible. */ - class Sphere effectSphere(float cutoff = 30.0f / 255) const; - - /** Computes a reference frame (e.g., for use with G3D::ShadowMap */ - class CoordinateFrame frame() const; - - bool operator==(const GLight& other) const; - bool operator!=(const GLight& other) const; -}; - -} // namespace -#endif - diff --git a/externals/g3dlite/G3D/GMutex.h b/externals/g3dlite/G3D/GMutex.h deleted file mode 100644 index 3469b812736..00000000000 --- a/externals/g3dlite/G3D/GMutex.h +++ /dev/null @@ -1,123 +0,0 @@ -/** - @file GMutex.h - - @created 2005-09-22 - @edited 2009-03-25 - */ - -#ifndef G3D_GMutex_h -#define G3D_GMutex_h - -#include "G3D/platform.h" -#include "G3D/AtomicInt32.h" -#include "G3D/debugAssert.h" -#include - -#ifndef G3D_WIN32 -# include -# include -#endif - - -namespace G3D { - -/** - \brief A mutual exclusion lock that busy-waits when locking. - - On a machine with one (significant) thread per processor core, - a spinlock may be substantially faster than a mutex. - - \sa G3D::GThread, G3D::GMutex, G3D::AtomicInt32 - */ -class Spinlock { -private: - - AtomicInt32 x; - -public: - - inline Spinlock() : x(0) {} - - /** Busy waits until the lock is unlocked, then locks it - exclusively. Returns true if the lock succeeded on the first - try (indicating no contention). */ - inline bool lock() { - bool first = true; - while (x.compareAndSet(0, 1) == 1) { - first = false; -# ifdef G3D_WIN32 - Sleep(0); -# else - usleep(0); -# endif - } - return first; - } - - inline void unlock() { - x.compareAndSet(1, 0); - } - -}; - -/** - \brief Mutual exclusion lock used for synchronization. - - @sa G3D::GThread, G3D::AtomicInt32, G3D::Spinlock -*/ -class GMutex { -private: -# ifdef G3D_WIN32 - CRITICAL_SECTION m_handle; -# else - pthread_mutex_t m_handle; - pthread_mutexattr_t m_attr; -# endif - - // Not implemented on purpose, don't use - GMutex(const GMutex &mlock); - GMutex &operator=(const GMutex &); - bool operator==(const GMutex&); - -public: - GMutex(); - ~GMutex(); - - /** Locks the mutex or blocks until available. */ - void lock(); - - /** Locks the mutex if it not already locked. - Returns true if lock successful, false otherwise. */ - bool tryLock(); - - /** Unlocks the mutex. */ - void unlock(); -}; - - -/** - Automatically locks while in scope. -*/ -class GMutexLock { -private: - GMutex* m; - - // Not implemented on purpose, don't use - GMutexLock(const GMutexLock &mlock); - GMutexLock &operator=(const GMutexLock &); - bool operator==(const GMutexLock&); - -public: - GMutexLock(GMutex* mutex) { - m = mutex; - m->lock(); - } - - ~GMutexLock() { - m->unlock(); - } -}; - -} // G3D - -#endif diff --git a/externals/g3dlite/G3D/GThread.h b/externals/g3dlite/G3D/GThread.h deleted file mode 100644 index 58437efc3fb..00000000000 --- a/externals/g3dlite/G3D/GThread.h +++ /dev/null @@ -1,121 +0,0 @@ -/** - @file GThread.h - - @created 2005-09-22 - @edited 2007-01-31 - - */ - -#ifndef G3D_GTHREAD_H -#define G3D_GTHREAD_H - -#include "G3D/platform.h" -#include "G3D/ReferenceCount.h" -#include - -#ifndef G3D_WIN32 -# include -# include -#endif - - -namespace G3D { - -typedef ReferenceCountedPointer GThreadRef; - -/** - Platform independent thread implementation. You can either subclass and - override GThread::threadMain or call the create method with a method. - - Beware of reference counting and threads. If circular references exist between - GThread subclasses then neither class will ever be deallocated. Also, - dropping all pointers (and causing deallocation) of a GThread does NOT - stop the underlying process. - - @sa G3D::GMutex, G3D::Spinlock, G3D::AtomicInt32 -*/ -class GThread : public ReferenceCountedObject { -private: - // "Status" is a reserved work on FreeBSD - enum GStatus {STATUS_CREATED, STATUS_STARTED, STATUS_RUNNING, STATUS_COMPLETED}; - - // Not implemented on purpose, don't use - GThread(const GThread &); - GThread& operator=(const GThread&); - bool operator==(const GThread&); - -#ifdef G3D_WIN32 - static DWORD WINAPI internalThreadProc(LPVOID param); -#else - static void* internalThreadProc(void* param); -#endif //G3D_WIN32 - - volatile GStatus m_status; - - // Thread handle to hold HANDLE and pthread_t -#ifdef G3D_WIN32 - HANDLE m_handle; - HANDLE m_event; -#else - pthread_t m_handle; -#endif //G3D_WIN32 - - std::string m_name; - -protected: - - /** Overriden by the thread implementor */ - virtual void threadMain() = 0; - -public: - typedef ReferenceCountedPointer Ref; - enum SpawnBehavior {USE_NEW_THREAD, USE_CURRENT_THREAD}; - - GThread(const std::string& name); - - virtual ~GThread(); - - /** Constructs a basic GThread without requiring a subclass. - - @param proc The global or static function for the threadMain() */ - static GThreadRef create(const std::string& name, void (*proc)(void*), void* param = NULL); - - /** Starts the thread and executes threadMain(). Returns false if - the thread failed to start (either because it was already started - or because the OS refused). - - @param behavior If USE_CURRENT_THREAD, rather than spawning a new thread, this routine - runs threadMain on the current thread. - */ - bool start(SpawnBehavior behavior = USE_NEW_THREAD); - - /** Terminates the thread without notifying or - waiting for a cancelation point. */ - void terminate(); - - /** - Returns true if threadMain is currently executing. This will - only be set when the thread is actually running and might not - be set when start() returns. */ - bool running() const; - - /** True after start() has been called, even through the thread - may have already completed(), or be currently running().*/ - bool started() const; - - /** Returns true if the thread has exited. */ - bool completed() const; - - /** Waits for the thread to finish executing. */ - void waitForCompletion(); - - /** Returns thread name */ - inline const std::string& name() { - return m_name; - } -}; - - -} // namespace G3D - -#endif //G3D_GTHREAD_H diff --git a/externals/g3dlite/G3D/GUniqueID.h b/externals/g3dlite/G3D/GUniqueID.h deleted file mode 100644 index c8b775c2e66..00000000000 --- a/externals/g3dlite/G3D/GUniqueID.h +++ /dev/null @@ -1,69 +0,0 @@ -/** - @file GUniqueID.h - @author Morgan McGuire, http://graphics.cs.williams.edu - */ -#ifndef G3D_GUNIQUEID_H -#define G3D_GUNIQUEID_H - -#include "G3D/platform.h" -#include "G3D/g3dmath.h" -#include "G3D/Table.h" - -namespace G3D { - -/** Globally unique identifiers. The probability of two different - programs generating the same value from UniqueID::create is - vanishingly small. - - UniqueIDs optionally contain a 10-bit application specific tag - that distinguishes their type. -*/ -class GUniqueID { -private: - - uint64 id; - -public: - - GUniqueID() : id(0) {} - - bool uninitialized() const { - return id == 0; - } - - uint16 tag() const { - return id >> 54; - } - - operator uint64() const { - return id; - } - - bool operator==(const GUniqueID& other) const { - return id == other.id; - } - - bool operator!=(const GUniqueID& other) const { - return id != other.id; - } - - void serialize(class BinaryOutput& b) const; - - void deserialize(class BinaryInput& b); - - void serialize(class TextOutput& t) const; - - void deserialize(class TextInput& t); - - /** Create a new ID */ - static GUniqueID create(uint16 tag = 0); -}; - -} // G3D - -/** For Table and Set */ -template<> struct HashTrait { - static size_t hashCode(G3D::GUniqueID id) { return (size_t)(G3D::uint64)id; } -}; - -#endif diff --git a/externals/g3dlite/G3D/HashTrait.h b/externals/g3dlite/G3D/HashTrait.h deleted file mode 100644 index ca35da48643..00000000000 --- a/externals/g3dlite/G3D/HashTrait.h +++ /dev/null @@ -1,92 +0,0 @@ -/** - @file HashTrait.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - @created 2008-10-01 - @edited 2009-11-01 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_HashTrait_h -#define G3D_HashTrait_h - -#include "G3D/platform.h" -#include "G3D/Crypto.h" -#include "G3D/g3dmath.h" -#include "G3D/uint128.h" - -/** Must be specialized for custom types. - @see G3D::Table for specialization requirements. -*/ -template struct HashTrait{}; - -template struct HashTrait { - static size_t hashCode(const void* k) { return reinterpret_cast(k); } -}; - -#if 0 -template <> struct HashTrait { - static size_t hashCode(int k) { return static_cast(k); } -}; -#endif - -template <> struct HashTrait { - static size_t hashCode(G3D::int16 k) { return static_cast(k); } -}; - -template <> struct HashTrait { - static size_t hashCode(G3D::uint16 k) { return static_cast(k); } -}; - -//template <> struct HashTrait { -// static size_t hashCode(int k) { return static_cast(k); } -//}; - -template <> struct HashTrait { - static size_t hashCode(G3D::int32 k) { return static_cast(k); } -}; - -template <> struct HashTrait { - static size_t hashCode(G3D::uint32 k) { return static_cast(k); } -}; - -#if 0 -template <> struct HashTrait { - static size_t hashCode(G3D::uint32 k) { return static_cast(k); } -}; -#endif - -template <> struct HashTrait { - static size_t hashCode(G3D::int64 k) { return static_cast(k); } -}; - -template <> struct HashTrait { - static size_t hashCode(G3D::uint64 k) { return static_cast(k); } -}; - -template <> struct HashTrait { - static size_t hashCode(const std::string& k) { return static_cast(G3D::Crypto::crc32(k.c_str(), k.size())); } -}; - -template <> struct HashTrait { - // Use the FNV-1 hash (http://isthe.com/chongo/tech/comp/fnv/#FNV-1). - static size_t hashCode(G3D::uint128 key) { - static const G3D::uint128 FNV_PRIME_128(1 << 24, 0x159); - static const G3D::uint128 FNV_OFFSET_128(0xCF470AAC6CB293D2ULL, 0xF52F88BF32307F8FULL); - - G3D::uint128 hash = FNV_OFFSET_128; - G3D::uint128 mask(0, 0xFF); - for (int i = 0; i < 16; ++i) { - hash *= FNV_PRIME_128; - hash ^= (mask & key); - key >>= 8; - } - - G3D::uint64 foldedHash = hash.hi ^ hash.lo; - return static_cast((foldedHash >> 32) ^ (foldedHash & 0xFFFFFFFF)); - } -}; - -#endif diff --git a/externals/g3dlite/G3D/Image1.h b/externals/g3dlite/G3D/Image1.h deleted file mode 100644 index 711e83f2079..00000000000 --- a/externals/g3dlite/G3D/Image1.h +++ /dev/null @@ -1,81 +0,0 @@ -/** - @file Image1.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2007-01-31 - @edited 2007-01-31 -*/ - - -#ifndef G3D_IMAGE1_H -#define G3D_IMAGE1_H - -#include "G3D/platform.h" -#include "G3D/Map2D.h" -#include "G3D/Color1.h" -#include "G3D/GImage.h" - -namespace G3D { - -typedef ReferenceCountedPointer Image1Ref; - -/** - Luminance image with 32-bit floating point storage. - - See also G3D::Image1uint8, G3D::GImage. - */ -class Image1 : public Map2D { -public: - - typedef Image1 Type; - typedef ReferenceCountedPointer Ref; - typedef Color1 Storage; - typedef Color1 Compute; - -protected: - - Image1(int w, int h, WrapMode wrap); - - void copyGImage(const class GImage& im); - void copyArray(const Color1* src, int w, int h); - void copyArray(const Color3* src, int w, int h); - void copyArray(const Color4* src, int w, int h); - void copyArray(const Color1uint8* src, int w, int h); - void copyArray(const Color3uint8* src, int w, int h); - void copyArray(const Color4uint8* src, int w, int h); - -public: - - const class ImageFormat* format() const; - - /** Creates an all-zero width x height image. */ - static Ref createEmpty(int width, int height, WrapMode wrap = WrapMode::ERROR); - - /** Creates a 0 x 0 image. */ - static Ref createEmpty(WrapMode wrap = WrapMode::ERROR); - - static Ref fromFile(const std::string& filename, WrapMode wrap = WrapMode::ERROR, GImage::Format fmt = GImage::AUTODETECT); - - static Ref fromArray(const class Color1uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color3uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color4uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color1* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color3* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color4* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - - static Ref fromImage1uint8(const ReferenceCountedPointer& im); - - static Ref fromGImage(const class GImage& im, WrapMode wrap = WrapMode::ERROR); - - /** Loads from any of the file formats supported by G3D::GImage. If there is an alpha channel on the input, - it is stripped. */ - void load(const std::string& filename, GImage::Format fmt = GImage::AUTODETECT); - - /** Saves in any of the formats supported by G3D::GImage. */ - void save(const std::string& filename, GImage::Format fmt = GImage::AUTODETECT); -}; - -} // G3D - -#endif diff --git a/externals/g3dlite/G3D/Image1uint8.h b/externals/g3dlite/G3D/Image1uint8.h deleted file mode 100644 index f32e022e92a..00000000000 --- a/externals/g3dlite/G3D/Image1uint8.h +++ /dev/null @@ -1,80 +0,0 @@ -/** - @file Image1uint8.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2007-01-31 - @edited 2007-01-31 -*/ - -#ifndef G3D_IMAGE1UINT8_H -#define G3D_IMAGE1UINT8_H - -#include "G3D/platform.h" -#include "G3D/Map2D.h" -#include "G3D/Color1uint8.h" -#include "G3D/Color1.h" -#include "G3D/GImage.h" - -namespace G3D { - -typedef ReferenceCountedPointer Image1uint8Ref; - -/** - Compact storage for luminance 8-bit images. - - See also G3D::Image3, G3D::GImage - */ -class Image1uint8 : public Map2D { -public: - - typedef Image1uint8 Type; - typedef Image1uint8Ref Ref; - -protected: - - Image1uint8(int w, int h, WrapMode wrap); - - void copyGImage(const class GImage& im); - void copyArray(const Color1* src, int w, int h); - void copyArray(const Color3* src, int w, int h); - void copyArray(const Color4* src, int w, int h); - void copyArray(const Color1uint8* src, int w, int h); - void copyArray(const Color3uint8* src, int w, int h); - void copyArray(const Color4uint8* src, int w, int h); - -public: - - const class ImageFormat* format() const; - - /** Creates an all-zero width x height image. */ - static Ref createEmpty(int width, int height, WrapMode wrap = WrapMode::ERROR); - - /** Creates a 0 x 0 image. */ - static Ref createEmpty(WrapMode wrap = WrapMode::ERROR); - - static Ref fromFile(const std::string& filename, WrapMode wrap = WrapMode::ERROR, GImage::Format fmt = GImage::AUTODETECT); - - static Ref fromGImage(const class GImage& im, WrapMode wrap = WrapMode::ERROR); - - static Ref fromArray(const class Color1uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color3uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color4uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color1* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color3* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color4* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - - static Ref fromImage1(const ReferenceCountedPointer& im); - static Ref fromImage3uint8(const ReferenceCountedPointer& im); - - /** Loads from any of the file formats supported by G3D::GImage. If there is an alpha channel on the input, - it is stripped. */ - void load(const std::string& filename, GImage::Format fmt = GImage::AUTODETECT); - - /** Saves in any of the formats supported by G3D::GImage. */ - void save(const std::string& filename, GImage::Format fmt = GImage::AUTODETECT); -}; - -} // G3D - -#endif diff --git a/externals/g3dlite/G3D/Image3.h b/externals/g3dlite/G3D/Image3.h deleted file mode 100644 index 13cb8fa7faf..00000000000 --- a/externals/g3dlite/G3D/Image3.h +++ /dev/null @@ -1,81 +0,0 @@ -/** - @file Image3.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2007-01-31 - @edited 2007-01-31 -*/ - - -#ifndef G3D_IMAGE3_H -#define G3D_IMAGE3_H - -#include "G3D/platform.h" -#include "G3D/Map2D.h" -#include "G3D/Color3.h" -#include "G3D/GImage.h" - -namespace G3D { - -typedef ReferenceCountedPointer Image3Ref; - -/** - RGB image with 32-bit floating point storage for each channel. - - See also G3D::Image3uint8, G3D::GImage. - */ -class Image3 : public Map2D { -public: - - typedef Image3 Type; - typedef ReferenceCountedPointer Ref; - typedef Color3 Storage; - typedef Color3 Compute; - -protected: - - Image3(int w, int h, WrapMode wrap); - - void copyGImage(const class GImage& im); - void copyArray(const Color1* src, int w, int h); - void copyArray(const Color3* src, int w, int h); - void copyArray(const Color4* src, int w, int h); - void copyArray(const Color1uint8* src, int w, int h); - void copyArray(const Color3uint8* src, int w, int h); - void copyArray(const Color4uint8* src, int w, int h); - -public: - - const class ImageFormat* format() const; - - /** Creates an all-zero width x height image. */ - static Ref createEmpty(int width, int height, WrapMode wrap = WrapMode::ERROR); - - /** Creates a 0 x 0 image. */ - static Ref createEmpty(WrapMode wrap = WrapMode::ERROR); - - static Ref fromFile(const std::string& filename, WrapMode wrap = WrapMode::ERROR, GImage::Format fmt = GImage::AUTODETECT); - - static Ref fromArray(const class Color1uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color3uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color4uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color1* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color3* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color4* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - - static Ref fromImage3uint8(const ReferenceCountedPointer& im); - - static Ref fromGImage(const class GImage& im, WrapMode wrap = WrapMode::ERROR); - - /** Loads from any of the file formats supported by G3D::GImage. If there is an alpha channel on the input, - it is stripped. */ - void load(const std::string& filename, GImage::Format fmt = GImage::AUTODETECT); - - /** Saves in any of the formats supported by G3D::GImage. */ - void save(const std::string& filename, GImage::Format fmt = GImage::AUTODETECT); -}; - -} // G3D - -#endif diff --git a/externals/g3dlite/G3D/Image3uint8.h b/externals/g3dlite/G3D/Image3uint8.h deleted file mode 100644 index d4fdbc169ca..00000000000 --- a/externals/g3dlite/G3D/Image3uint8.h +++ /dev/null @@ -1,85 +0,0 @@ -/** - @file Image3uint8.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2007-01-31 - @edited 2007-01-31 -*/ - -#ifndef G3D_IMAGE3UINT8_H -#define G3D_IMAGE3UINT8_H - -#include "G3D/platform.h" -#include "G3D/Map2D.h" -#include "G3D/Color3uint8.h" -#include "G3D/Color3.h" -#include "G3D/GImage.h" - -namespace G3D { - -typedef ReferenceCountedPointer Image3uint8Ref; - -/** - Compact storage for RGB 8-bit per channel images. - - See also G3D::Image3, G3D::GImage - */ -class Image3uint8 : public Map2D { -public: - - typedef Image3uint8 Type; - typedef Image3uint8Ref Ref; - -protected: - - Image3uint8(int w, int h, WrapMode wrap); - - void copyGImage(const class GImage& im); - void copyArray(const Color1* src, int w, int h); - void copyArray(const Color3* src, int w, int h); - void copyArray(const Color4* src, int w, int h); - void copyArray(const Color1uint8* src, int w, int h); - void copyArray(const Color3uint8* src, int w, int h); - void copyArray(const Color4uint8* src, int w, int h); - -public: - - const class ImageFormat* format() const; - - /** Creates an all-zero width x height image. */ - static Ref createEmpty(int width, int height, WrapMode wrap = WrapMode::ERROR); - - - /** Creates a 0 x 0 image. */ - static Ref createEmpty(WrapMode wrap = WrapMode::ERROR); - - - static Ref fromFile(const std::string& filename, WrapMode wrap = WrapMode::ERROR, GImage::Format fmt = GImage::AUTODETECT); - - static Ref fromGImage(const class GImage& im, WrapMode wrap = WrapMode::ERROR); - - static Ref fromArray(const class Color1uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color3uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color4uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color1* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color3* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color4* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - - static Ref fromImage3(const ReferenceCountedPointer& im); - static Ref fromImage1uint8(const ReferenceCountedPointer& im); - - /** Loads from any of the file formats supported by G3D::GImage. If there is an alpha channel on the input, - it is stripped. */ - void load(const std::string& filename, GImage::Format fmt = GImage::AUTODETECT); - - /** Saves in any of the formats supported by G3D::GImage. */ - void save(const std::string& filename, GImage::Format fmt = GImage::AUTODETECT); - - /** Extracts color channel 0 <= c <= 2 and returns it as a new monochrome image. */ - ReferenceCountedPointer getChannel(int c) const; -}; - -} // G3D - -#endif diff --git a/externals/g3dlite/G3D/Image4.h b/externals/g3dlite/G3D/Image4.h deleted file mode 100644 index 21d7f1e79b1..00000000000 --- a/externals/g3dlite/G3D/Image4.h +++ /dev/null @@ -1,86 +0,0 @@ -/** - @file Image4.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2007-01-31 - @edited 2007-01-31 -*/ - - -#ifndef G3D_IMAGE4_H -#define G3D_IMAGE4_H - -#include "G3D/platform.h" -#include "G3D/Map2D.h" -#include "G3D/Color4.h" -#include "G3D/GImage.h" - -namespace G3D { - -typedef ReferenceCountedPointer Image4Ref; - -/** - RGBA image with 32-bit floating point storage for each channel. - - Whenever a method needs to convert from RGB to RGBA, A=1 is assumed. - - Bilinear interpolation on Image4 is about 8x faster than on - Image4uint8 due to the large cost of converting int->float on modern - machines. - - @sa G3D::Image4uint8, G3D::GImage. - */ -class Image4 : public Map2D { -public: - - typedef Image4 Type; - typedef ReferenceCountedPointer Ref; - typedef Color4 Storage; - typedef Color4 Compute; - -protected: - - Image4(int w, int h, WrapMode wrap); - - void copyGImage(const class GImage& im); - void copyArray(const Color1* src, int w, int h); - void copyArray(const Color3* src, int w, int h); - void copyArray(const Color4* src, int w, int h); - void copyArray(const Color1uint8* src, int w, int h); - void copyArray(const Color3uint8* src, int w, int h); - void copyArray(const Color4uint8* src, int w, int h); - -public: - - const class ImageFormat* format() const; - - /** Creates an all-zero width x height image. */ - static Ref createEmpty(int width, int height, WrapMode wrap = WrapMode::ERROR); - - /** Creates a 0 x 0 image. */ - static Ref createEmpty(WrapMode wrap = WrapMode::ERROR); - - static Ref fromFile(const std::string& filename, WrapMode wrap = WrapMode::ERROR, GImage::Format fmt = GImage::AUTODETECT); - - static Ref fromArray(const class Color1uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color3uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color4uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color1* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color3* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color4* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - - static Ref fromImage4uint8(const ReferenceCountedPointer& im); - - static Ref fromGImage(const class GImage& im, WrapMode wrap = WrapMode::ERROR); - - /** Loads from any of the file formats supported by G3D::GImage. */ - void load(const std::string& filename, GImage::Format fmt = GImage::AUTODETECT); - - /** Saves in any of the formats supported by G3D::GImage. */ - void save(const std::string& filename, GImage::Format fmt = GImage::AUTODETECT); -}; - -} // G3D - -#endif diff --git a/externals/g3dlite/G3D/Image4uint8.h b/externals/g3dlite/G3D/Image4uint8.h deleted file mode 100644 index 46df6b490b4..00000000000 --- a/externals/g3dlite/G3D/Image4uint8.h +++ /dev/null @@ -1,85 +0,0 @@ -/** - @file Image4uint8.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2007-01-31 - @edited 2007-01-31 -*/ - -#ifndef G3D_IMAGE4UINT8_H -#define G3D_IMAGE4UINT8_H - -#include "G3D/platform.h" -#include "G3D/Map2D.h" -#include "G3D/Color4uint8.h" -#include "G3D/Color4.h" -#include "G3D/GImage.h" -#include "G3D/Image1uint8.h" - -namespace G3D { - -typedef ReferenceCountedPointer Image4uint8Ref; - -/** - Compact storage for RGBA 8-bit per channel images. - - See also G3D::Image4, G3D::GImage - */ -class Image4uint8 : public Map2D { -public: - - typedef Image4uint8 Type; - typedef Image4uint8Ref Ref; - -protected: - - Image4uint8(int w, int h, WrapMode wrap); - - void copyGImage(const class GImage& im); - void copyArray(const Color1* src, int w, int h); - void copyArray(const Color3* src, int w, int h); - void copyArray(const Color4* src, int w, int h); - void copyArray(const Color1uint8* src, int w, int h); - void copyArray(const Color3uint8* src, int w, int h); - void copyArray(const Color4uint8* src, int w, int h); - -public: - - const class ImageFormat* format() const; - - /** Creates an all-zero width x height image. */ - static Ref createEmpty(int width, int height, WrapMode wrap = WrapMode::ERROR); - - - /** Creates a 0 x 0 image. */ - static Ref createEmpty(WrapMode wrap = WrapMode::ERROR); - - - static Ref fromFile(const std::string& filename, WrapMode wrap = WrapMode::ERROR, GImage::Format fmt = GImage::AUTODETECT); - - static Ref fromGImage(const class GImage& im, WrapMode wrap = WrapMode::ERROR); - - static Ref fromArray(const class Color1uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color3uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color4uint8* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color1* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color3* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - static Ref fromArray(const class Color4* ptr, int width, int height, WrapMode wrap = WrapMode::ERROR); - - static Ref fromImage4(const ReferenceCountedPointer& im); - - /** Loads from any of the file formats supported by G3D::GImage. If there is an alpha channel on the input, - it is stripped. */ - void load(const std::string& filename, GImage::Format fmt = GImage::AUTODETECT); - - /** Saves in any of the formats supported by G3D::GImage. */ - void save(const std::string& filename, GImage::Format fmt = GImage::AUTODETECT); - - /** Extracts color channel 0 <= c <= 3 and returns it as a new monochrome image. */ - ReferenceCountedPointer getChannel(int c) const; -}; - -} // G3D - -#endif diff --git a/externals/g3dlite/G3D/ImageFormat.h b/externals/g3dlite/G3D/ImageFormat.h deleted file mode 100644 index 7f098322d26..00000000000 --- a/externals/g3dlite/G3D/ImageFormat.h +++ /dev/null @@ -1,419 +0,0 @@ -/** - @file ImageFormat.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2003-05-23 - @edited 2010-01-01 -*/ - -#ifndef GLG3D_ImageFormat_H -#define GLG3D_ImageFormat_H - -#include "G3D/platform.h" -#include "G3D/Table.h" -#include "G3D/enumclass.h" - -namespace G3D { - -/** Information about common image formats. - Don't construct these; use the methods provided. - - For most formats, the number indicates the number of bits per channel and a suffix of "F" indicates - floating point. This does not hold for the YUV and DXT formats.*/ -class ImageFormat { -public: - - // Must update ImageFormat::name() when this enum changes. - enum Code { - CODE_NONE = -1, - CODE_L8, - CODE_L16, - CODE_L16F, - CODE_L32F, - - CODE_A8, - CODE_A16, - CODE_A16F, - CODE_A32F, - - CODE_LA4, - CODE_LA8, - CODE_LA16, - CODE_LA16F, - CODE_LA32F, - - CODE_RGB5, - CODE_RGB5A1, - CODE_RGB8, - CODE_RGB10, - CODE_RGB10A2, - CODE_RGB16, - CODE_RGB16F, - CODE_RGB32F, - CODE_R11G11B10F, - CODE_RGB9E5F, - - CODE_RGB8I, - CODE_RGB8UI, - - CODE_ARGB8, - CODE_BGR8, - - CODE_RG8, - CODE_RG8I, - CODE_RG8UI, - - CODE_RGBA8, - CODE_RGBA16, - CODE_RGBA16F, - CODE_RGBA32F, - - CODE_RGBA32UI, - - CODE_BAYER_RGGB8, - CODE_BAYER_GRBG8, - CODE_BAYER_GBRG8, - CODE_BAYER_BGGR8, - CODE_BAYER_RGGB32F, - CODE_BAYER_GRBG32F, - CODE_BAYER_GBRG32F, - CODE_BAYER_BGGR32F, - - CODE_HSV8, - CODE_HSV32F, - - CODE_YUV420_PLANAR, - CODE_YUV422, - CODE_YUV444, - - CODE_RGB_DXT1, - CODE_RGBA_DXT1, - CODE_RGBA_DXT3, - CODE_RGBA_DXT5, - - CODE_SRGB8, - CODE_SRGBA8, - - CODE_SL8, - CODE_SLA8, - - CODE_SRGB_DXT1, - CODE_SRGBA_DXT1, - CODE_SRGBA_DXT3, - CODE_SRGBA_DXT5, - - CODE_DEPTH16, - CODE_DEPTH24, - CODE_DEPTH32, - CODE_DEPTH32F, - - CODE_STENCIL1, - CODE_STENCIL4, - CODE_STENCIL8, - CODE_STENCIL16, - - CODE_DEPTH24_STENCIL8, - - CODE_NUM - }; - - enum ColorSpace { - COLOR_SPACE_NONE, - COLOR_SPACE_RGB, - COLOR_SPACE_HSV, - COLOR_SPACE_YUV, - COLOR_SPACE_SRGB - }; - - enum BayerPattern { - BAYER_PATTERN_NONE, - BAYER_PATTERN_RGGB, - BAYER_PATTERN_GRBG, - BAYER_PATTERN_GBRG, - BAYER_PATTERN_BGGR - }; - - /** Number of channels (1 for a depth texture). */ - int numComponents; - bool compressed; - - /** Useful for serializing. */ - Code code; - - ColorSpace colorSpace; - - /** If this is a Bayer format, what is the pattern. */ - BayerPattern bayerPattern; - - /** The OpenGL format equivalent to this one, e.g, GL_RGB8 Zero if there is no equivalent. This is actually a GLenum */ - int openGLFormat; - - /** The OpenGL base format equivalent to this one (e.g., GL_RGB, GL_ALPHA). Zero if there is no equivalent. */ - int openGLBaseFormat; - - int luminanceBits; - - /** Number of bits per pixel storage for alpha values; Zero for compressed textures and non-RGB. */ - int alphaBits; - - /** Number of bits per pixel storage for red values; Zero for compressed textures and non-RGB. */ - int redBits; - - /** Number of bits per pixel storage for green values; Zero for compressed textures and non-RGB. */ - int greenBits; - - /** Number of bits per pixel storage for blue values; Zero for compressed textures and non-RGB. */ - int blueBits; - - /** Number of bits per pixel */ - int stencilBits; - - /** Number of depth bits (for depth textures; e.g. shadow maps) */ - int depthBits; - - /** Amount of CPU memory per pixel when packed into an array, discounting any end-of-row padding. */ - int cpuBitsPerPixel; - - /** Amount of CPU memory per pixel when packed into an array, discounting any end-of-row padding. - @deprecated Use cpuBitsPerPixel*/ - int packedBitsPerTexel; - - /** - Amount of GPU memory per pixel on most graphics cards, for formats supported by OpenGL. This is - only an estimate--the actual amount of memory may be different on your actual card. - - This may be greater than the sum of the per-channel bits - because graphics cards need to pad to the nearest 1, 2, or - 4 bytes. - */ - int openGLBitsPerPixel; - - /** @deprecated Use openGLBitsPerPixel */ - int hardwareBitsPerTexel; - - /** The OpenGL bytes (type) format of the data buffer used with this texture format, e.g., GL_UNSIGNED_BYTE */ - int openGLDataFormat; - - /** True if there is no alpha channel for this texture. */ - bool opaque; - - /** True if the bit depths specified are for float formats. */ - bool floatingPoint; - - /** Human readable name of this format.*/ - const std::string& name() const; - - /** Takes the same values that name() returns */ - static const ImageFormat* fromString(const std::string& s); - -private: - - ImageFormat - (int numComponents, - bool compressed, - int glFormat, - int glBaseFormat, - int luminanceBits, - int alphaBits, - int redBits, - int greenBits, - int blueBits, - int depthBits, - int stencilBits, - int hardwareBitsPerTexel, - int packedBitsPerTexel, - int glDataFormat, - bool opaque, - bool floatingPoint, - Code code, - ColorSpace colorSpace, - BayerPattern bayerPattern = BAYER_PATTERN_NONE); - -public: - - static const ImageFormat* L8(); - - static const ImageFormat* L16(); - - static const ImageFormat* L16F(); - - static const ImageFormat* L32F(); - - static const ImageFormat* A8(); - - static const ImageFormat* A16(); - - static const ImageFormat* A16F(); - - static const ImageFormat* A32F(); - - static const ImageFormat* LA4(); - - static const ImageFormat* LA8(); - - static const ImageFormat* LA16(); - - static const ImageFormat* LA16F(); - - static const ImageFormat* LA32F(); - - static const ImageFormat* BGR8(); - - static const ImageFormat* RG8(); - static const ImageFormat* RG8I(); - static const ImageFormat* RG8UI(); - - static const ImageFormat* RGB5(); - - static const ImageFormat* RGB5A1(); - - static const ImageFormat* RGB8(); - - static const ImageFormat* RGB10(); - - static const ImageFormat* RGB10A2(); - - static const ImageFormat* RGB16(); - - static const ImageFormat* RGB16F(); - - static const ImageFormat* RGB32F(); - - static const ImageFormat* RGBA8(); - - static const ImageFormat* RGBA16(); - - static const ImageFormat* RGBA16F(); - - static const ImageFormat* RGBA32F(); - - static const ImageFormat* RGBA32UI(); - - static const ImageFormat* R11G11B10F(); - - static const ImageFormat* RGB9E5F(); - - static const ImageFormat* RGB8I(); - - static const ImageFormat* RGB8UI(); - - static const ImageFormat* RGB_DXT1(); - - static const ImageFormat* RGBA_DXT1(); - - static const ImageFormat* RGBA_DXT3(); - - static const ImageFormat* RGBA_DXT5(); - - static const ImageFormat* SRGB8(); - - static const ImageFormat* SRGBA8(); - - static const ImageFormat* SL8(); - - static const ImageFormat* SLA8(); - - static const ImageFormat* SRGB_DXT1(); - - static const ImageFormat* SRGBA_DXT1(); - - static const ImageFormat* SRGBA_DXT3(); - - static const ImageFormat* SRGBA_DXT5(); - - static const ImageFormat* DEPTH16(); - - static const ImageFormat* DEPTH24(); - - static const ImageFormat* DEPTH32(); - - static const ImageFormat* DEPTH32F(); - - static const ImageFormat* STENCIL1(); - - static const ImageFormat* STENCIL4(); - - static const ImageFormat* STENCIL8(); - - static const ImageFormat* STENCIL16(); - - static const ImageFormat* DEPTH24_STENCIL8(); - - static const ImageFormat* YUV420_PLANAR(); - - static const ImageFormat* YUV422(); - - static const ImageFormat* YUV444(); - - /** - NULL pointer; indicates that the G3D::Texture class should choose - either RGBA8 or RGB8 depending on the presence of an alpha channel - in the input. - */ - static const ImageFormat* AUTO() { return NULL; } - - /** Returns DEPTH16, DEPTH24, or DEPTH32 according to the bits - specified. You can use "glGetInteger(GL_DEPTH_BITS)" to match - the screen's format.*/ - static const ImageFormat* depth(int depthBits = 24); - - /** Returns STENCIL1, STENCIL4, STENCIL8 or STENCIL16 according to the bits - specified. You can use "glGetInteger(GL_STENCIL_BITS)" to match - the screen's format.*/ - static const ImageFormat* stencil(int bits = 8); - - /** Returns the matching ImageFormat* identified by the Code. May return NULL - if this format's code is reserved but not yet implemented by G3D. */ - static const ImageFormat* fromCode(ImageFormat::Code code); - - - - /** For use with ImageFormat::convert. */ - class BayerAlgorithm { - public: - enum Value { - NEAREST, - BILINEAR, - MHC, - HIGH_QUALITY = MHC - }; - private: - - Value value; - - public: - - G3D_DECLARE_ENUM_CLASS_METHODS(BayerAlgorithm); - }; - - /** Converts between arbitrary formats on the CPU. Not all format conversions are supported or directly supported. - Formats without direct conversions will attempt to convert through RGBA first. - - A conversion routine might only support source or destination padding or y inversion or none. - If support is needed and not available in any of the direct conversion routines, then no conversion is done. - - YUV422 expects data in YUY2 format (Y, U, Y2, v). Most YUV formats require width and heights that are multiples of 2. - - Returns true if a conversion was available, false if none occurred. - */ - static bool convert(const Array& srcBytes, int srcWidth, int srcHeight, const ImageFormat* srcFormat, int srcRowPadBits, - const Array& dstBytes, const ImageFormat* dstFormat, int dstRowPadBits, - bool invertY = false, BayerAlgorithm bayerAlg = BayerAlgorithm::HIGH_QUALITY); - - /* Checks if a conversion between two formats is available. */ - static bool conversionAvailable(const ImageFormat* srcFormat, int srcRowPadBits, const ImageFormat* dstFormat, int dstRowPadBits, bool invertY = false); -}; - -typedef ImageFormat TextureFormat; - -} - -template <> -struct HashTrait { - static size_t hashCode(const G3D::ImageFormat* key) { return reinterpret_cast(key); } -}; - - - -#endif diff --git a/externals/g3dlite/G3D/Intersect.h b/externals/g3dlite/G3D/Intersect.h deleted file mode 100644 index 4a3c8fb4540..00000000000 --- a/externals/g3dlite/G3D/Intersect.h +++ /dev/null @@ -1,55 +0,0 @@ -/** - @file Intersect.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2009-06-29 - @edited 2009-06-29 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - - From the G3D Innovation Engine - http://g3d.sf.net - */ -#ifndef G3D_Intersect -#define G3D_Intersect - -#include "G3D/platform.h" -#include "G3D/Ray.h" -#include "G3D/AABox.h" - -namespace G3D { - -/** - @beta - */ -class Intersect { -public: - - /** \brief Returns true if the intersection of the ray and the solid box is non-empty. - - \cite "Fast Ray / Axis-Aligned Bounding Box Overlap Tests using Ray Slopes" - by Martin Eisemann, Thorsten Grosch, Stefan Müller and Marcus Magnor - Computer Graphics Lab, TU Braunschweig, Germany and - University of Koblenz-Landau, Germany - */ - static bool __fastcall rayAABox(const Ray& ray, const AABox& box); - - /** \brief Returns true if the intersection of the ray and the solid box is non-empty. - - \param time If there is an intersection, set to the time to that intersection. If the ray origin is inside the box, - this is a negative value indicating the distance backwards from the ray origin to the first intersection. - \a time is not set if there is no intersection. - - \cite Slope-Mul method from "Fast Ray / Axis-Aligned Bounding Box Overlap Tests using Ray Slopes" - by Martin Eisemann, Thorsten Grosch, Stefan Müller and Marcus Magnor - Computer Graphics Lab, TU Braunschweig, Germany and - University of Koblenz-Landau, Germany - */ - static bool __fastcall rayAABox(const Ray& ray, const AABox& box, float& time); -}; - -} - -#endif diff --git a/externals/g3dlite/G3D/KDTree.h b/externals/g3dlite/G3D/KDTree.h deleted file mode 100644 index 4785ef2baea..00000000000 --- a/externals/g3dlite/G3D/KDTree.h +++ /dev/null @@ -1,1667 +0,0 @@ -/** - @file KDTree.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2004-01-11 - @edited 2009-12-28 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_KDTREE_H -#define G3D_KDTREE_H - -#include "G3D/platform.h" -#include "G3D/Array.h" -#include "G3D/Table.h" -#include "G3D/Vector2.h" -#include "G3D/Vector3.h" -#include "G3D/Vector4.h" -#include "G3D/AABox.h" -#include "G3D/Sphere.h" -#include "G3D/Box.h" -#include "G3D/Triangle.h" -#include "G3D/Ray.h" -#include "G3D/GCamera.h" -#include "G3D/BinaryInput.h" -#include "G3D/BinaryOutput.h" -#include "G3D/CollisionDetection.h" -#include "G3D/GCamera.h" -#include "G3D/BoundsTrait.h" -#include - -// If defined, in debug mode the tree is checked for consistency -// as a way of detecting corruption due to implementation bugs -// #define VERIFY_TREE - -template<> struct BoundsTrait { - static void getBounds(const G3D::Vector2& v, G3D::AABox& out) { out = G3D::AABox(G3D::Vector3(v, 0)); } -}; - -template<> struct BoundsTrait { - static void getBounds(const G3D::Vector3& v, G3D::AABox& out) { out = G3D::AABox(v); } -}; - -template<> struct BoundsTrait { - static void getBounds(const G3D::Vector4& v, G3D::AABox& out) { out = G3D::AABox(v.xyz()); } -}; - -template<> struct BoundsTrait { - static void getBounds(const G3D::AABox& v, G3D::AABox& out) { out = v; } -}; - -template<> struct BoundsTrait { - static void getBounds(const G3D::Sphere& s, G3D::AABox& out) { s.getBounds(out); } -}; - -template<> struct BoundsTrait { - static void getBounds(const G3D::Box& b, G3D::AABox& out) { b.getBounds(out); } -}; - -template<> struct BoundsTrait { - static void getBounds(const G3D::Vector2*& v, G3D::AABox& out) { out = G3D::AABox(G3D::Vector3(*v, 0)); } -}; - -template<> struct BoundsTrait { - static void getBounds(const G3D::Vector3*& v, G3D::AABox& out) { out = G3D::AABox(*v); } -}; - -template<> struct BoundsTrait { - static void getBounds(const G3D::Vector4*& v, G3D::AABox& out) { out = G3D::AABox(v->xyz()); } -}; - -template<> struct BoundsTrait { - static void getBounds(const G3D::AABox*& v, G3D::AABox& out) { out = *v; } -}; - -template<> struct BoundsTrait { - static void getBounds(const G3D::Sphere*& s, G3D::AABox& out) { s->getBounds(out); } -}; - -template<> struct BoundsTrait { - static void getBounds(const G3D::Box*& b, G3D::AABox& out) { b->getBounds(out); } -}; - - -template<> struct BoundsTrait { - static void getBounds(const G3D::Triangle*& t, G3D::AABox& out) { t->getBounds(out); } -}; - -namespace G3D { - namespace _internal { - - /** - Wraps a pointer value so that it can be treated as the instance itself; - convenient for inserting pointers into a Table but using the - object equality instead of pointer equality. - */ - template - class Indirector { - public: - Type* handle; - - inline Indirector(Type* h) : handle(h) {} - - inline Indirector() : handle(NULL) {} - - /** Returns true iff the values referenced by the handles are equivalent. */ - inline bool operator==(const Indirector& m) const { - return *handle == *(m.handle); - } - - inline bool operator==(const Type& m) const { - return *handle == m; - } - - inline size_t hashCode() const { - return handle->hashCode(); - } - }; - } // namespace internal -} // namespace G3D - -template struct HashTrait > { - static size_t hashCode(const G3D::_internal::Indirector& key) { return key.hashCode(); } -}; - -namespace G3D { - -/** - A set that supports spatial queries using a KD tree (axis-aligned - BSP tree) for speed. - - KDTree allows you to quickly find objects in 3D that lie within - a box or along a ray. For large sets of objects it is much faster - than testing each object for a collision. - - KDTree is as powerful as but more general than a Quad Tree, Oct - Tree, or regular KD tree that cycles through axes, but less general than an unconstrained BSP tree - (which is much slower to create). - - Internally, objects - are arranged into a tree according to their - axis-aligned bounds. This increases the cost of insertion to - O(log n) but allows fast overlap queries. - - Template Parameters -
The template parameter T must be one for which - the following functions are all overloaded: - -
-  T::T(); // public constructor of no arguments
-  template <> struct HashTrait { static size_t hashCode(int key); };
-  template<> struct BoundsTrait { static void getBounds(const T& obj, G3D::AABox& out); };
- 
- - G3D provides these for common classes like G3D::Vector3 and G3D::Sphere. - If you use a custom class, or a pointer to a custom class, you will need - to define those functions. - - Moving %Set Members -
It is important that objects do not move without updating the - KDTree. If the axis-aligned bounds of an object are about - to change, KDTree::remove it before they change and - KDTree::insert it again afterward. For objects - where the hashCode and == operator are invariant with respect - to the 3D position, - you can use the KDTree::update method as a shortcut to - insert/remove an object in one step after it has moved. - - - Note: Do not mutate any value once it has been inserted into KDTree. Values - are copied interally. All KDTree iterators convert to pointers to constant - values to reinforce this. - - If you want to mutate the objects you intend to store in a KDTree - simply insert pointers to your objects instead of the objects - themselves, and ensure that the above operations are defined. (And - actually, because values are copied, if your values are large you may - want to insert pointers anyway, to save space and make the balance - operation faster.) - - Dimensions - Although designed as a 3D-data structure, you can use the KDTree - for data distributed along 2 or 1 axes by simply returning bounds - that are always zero along one or more dimensions. - -*/ -template< class T, - class BoundsFunc = BoundsTrait, - class HashFunc = HashTrait, - class EqualsFunc = EqualsTrait > -class KDTree { -protected: -#define TreeType KDTree - - /** Wrapper for a value that includes a cache of its bounds. - Except for the test value used in a set-query operation, there - is only ever one instance of the handle associated with any - value and the memberTable and Nodes maintain pointers to that - heap-allocated value. - */ - class Handle { - public: - /** The bounds of each object are constrained to AABox::large */ - AABox bounds; - - /** Center of bounds. We cache this value to avoid recomputing it - during the median sort, and because MSVC 6 std::sort goes into - an infinite loop if we compute the midpoint on the fly (possibly - a floating point roundoff issue, where B& point, - int beginIndex, - int endIndex) { - - Vector3 lo = Vector3::inf(); - Vector3 hi = -lo; - - debugAssertM(beginIndex <= endIndex, "No points"); - for (int p = beginIndex; p <= endIndex; ++p) { - // This code is written with the vector min and max expanded - // because otherwise it compiles incorrectly with -O3 on - // gcc 3.4 - - const Vector3& pLo = point[p]->bounds.low(); - const Vector3& pHi = point[p]->bounds.high(); - for (int a = 0; a < 3; ++a) { - lo[a] = G3D::min(lo[a], pLo[a]); - hi[a] = G3D::max(hi[a], pHi[a]); - } - } - - return AABox(lo, hi); - } - - /** Compares centers */ - class CenterComparator { - public: - Vector3::Axis sortAxis; - - CenterComparator(Vector3::Axis a) : sortAxis(a) {} - - inline int operator()(Handle* A, const Handle* B) const { - float a = A->center[sortAxis]; - float b = B->center[sortAxis]; - - if (a < b) { - return 1; - } else if (a > b) { - return -1; - } else { - return 0; - } - } - }; - - - /** Compares bounds for strict >, <, or overlap*/ - class BoundsComparator { - public: - Vector3::Axis sortAxis; - - BoundsComparator(Vector3::Axis a) : sortAxis(a) {} - - inline int operator()(Handle* A, const Handle* B) const { - const AABox& a = A->bounds; - const AABox& b = B->bounds; - - if (a.high()[sortAxis] < b.low()[sortAxis]) { - return 1; - } else if (a.low()[sortAxis] > b.high()[sortAxis]) { - return -1; - } else { - return 0; - } - } - }; - - - /** Compares bounds to the sort location */ - class Comparator { - public: - Vector3::Axis sortAxis; - float sortLocation; - - Comparator(Vector3::Axis a, float l) : sortAxis(a), sortLocation(l) {} - - inline int operator()(Handle* ignore, const Handle* handle) const { - (void)ignore; - const AABox& box = handle->bounds; - debugAssert(ignore == NULL); - - if (box.high()[sortAxis] < sortLocation) { - // Box is strictly below the sort location - return -1; - } else if (box.low()[sortAxis] > sortLocation) { - // Box is strictly above the sort location - return 1; - } else { - // Box overlaps the sort location - return 0; - } - } - }; - - // Using System::malloc with this class provided no speed improvement. - class Node { - public: - - /** Spatial bounds on all values at this node and its children, based purely on - the parent's splitting planes. May be infinite. */ - AABox splitBounds; - - Vector3::Axis splitAxis; - - /** Location along the specified axis */ - float splitLocation; - - /** child[0] contains all values strictly - smaller than splitLocation along splitAxis. - - child[1] contains all values strictly - larger. - - Both may be NULL if there are not enough - values to bother recursing. - */ - Node* child[2]; - - /** Array of values at this node (i.e., values - straddling the split plane + all values if - this is a leaf node). - - This is an array of pointers because that minimizes - data movement during tree building, which accounts - for about 15% of the time cost of tree building. - */ - Array valueArray; - - /** For each object in the value array, a copy of its bounds. - Packing these into an array at the node level - instead putting them in the valueArray improves - cache coherence, which is about a 3x performance - increase when performing intersection computations. - */ - Array boundsArray; - - /** Creates node with NULL children */ - Node() { - splitAxis = Vector3::X_AXIS; - splitLocation = 0; - splitBounds = AABox(-Vector3::inf(), Vector3::inf()); - for (int i = 0; i < 2; ++i) { - child[i] = NULL; - } - } - - /** - Doesn't clone children. - */ - Node(const Node& other) : valueArray(other.valueArray), boundsArray(other.boundsArray) { - splitAxis = other.splitAxis; - splitLocation = other.splitLocation; - splitBounds = other.splitBounds; - for (int i = 0; i < 2; ++i) { - child[i] = NULL; - } - } - - /** Copies the specified subarray of pt into point, NULLs the children. - Assumes a second pass will set splitBounds. */ - Node(const Array& pt) : valueArray(pt) { - splitAxis = Vector3::X_AXIS; - splitLocation = 0; - for (int i = 0; i < 2; ++i) { - child[i] = NULL; - } - - boundsArray.resize(valueArray.size()); - for (int i = 0; i < valueArray.size(); ++i) { - boundsArray[i] = valueArray[i]->bounds; - } - } - - /** Deletes the children (but not the values) */ - ~Node() { - for (int i = 0; i < 2; ++i) { - delete child[i]; - } - } - - /** Returns true if this node is a leaf (no children) */ - inline bool isLeaf() const { - return (child[0] == NULL) && (child[1] == NULL); - } - - - /** - Recursively appends all handles and children's handles - to the array. - */ - void getHandles(Array& handleArray) const { - handleArray.append(valueArray); - for (int i = 0; i < 2; ++i) { - if (child[i] != NULL) { - child[i]->getHandles(handleArray); - } - } - } - - void verifyNode(const Vector3& lo, const Vector3& hi) { - // debugPrintf("Verifying: split %d @ %f [%f, %f, %f], [%f, %f, %f]\n", - // splitAxis, splitLocation, lo.x, lo.y, lo.z, hi.x, hi.y, hi.z); - - debugAssertM(lo == splitBounds.low(), - format("lo = %s, splitBounds.lo = %s", - lo.toString().c_str(), splitBounds.low().toString().c_str())); - debugAssert(hi == splitBounds.high()); - - for (int i = 0; i < valueArray.length(); ++i) { - const AABox& b = valueArray[i]->bounds; - debugAssert(b == boundsArray[i]); - - for(int axis = 0; axis < 3; ++axis) { - debugAssert(b.low()[axis] <= b.high()[axis]); - debugAssert(b.low()[axis] >= lo[axis]); - debugAssert(b.high()[axis] <= hi[axis]); - } - } - - if (child[0] || child[1]) { - debugAssert(lo[splitAxis] < splitLocation); - debugAssert(hi[splitAxis] > splitLocation); - } - - Vector3 newLo = lo; - newLo[splitAxis] = splitLocation; - Vector3 newHi = hi; - newHi[splitAxis] = splitLocation; - - if (child[0] != NULL) { - child[0]->verifyNode(lo, newHi); - } - - if (child[1] != NULL) { - child[1]->verifyNode(newLo, hi); - } - } - - - /** - Stores the locations of the splitting planes (the structure but not the content) - so that the tree can be quickly rebuilt from a previous configuration without - calling balance. - */ - static void serializeStructure(const Node* n, BinaryOutput& bo) { - if (n == NULL) { - bo.writeUInt8(0); - } else { - bo.writeUInt8(1); - n->splitBounds.serialize(bo); - serialize(n->splitAxis, bo); - bo.writeFloat32(n->splitLocation); - for (int c = 0; c < 2; ++c) { - serializeStructure(n->child[c], bo); - } - } - } - - /** Clears the member table */ - static Node* deserializeStructure(BinaryInput& bi) { - if (bi.readUInt8() == 0) { - return NULL; - } else { - Node* n = new Node(); - n->splitBounds.deserialize(bi); - deserialize(n->splitAxis, bi); - n->splitLocation = bi.readFloat32(); - for (int c = 0; c < 2; ++c) { - n->child[c] = deserializeStructure(bi); - } - return n; - } - } - - /** Returns the deepest node that completely contains bounds. */ - Node* findDeepestContainingNode(const AABox& bounds) { - - // See which side of the splitting plane the bounds are on - if (bounds.high()[splitAxis] < splitLocation) { - // Bounds are on the low side. Recurse into the child - // if it exists. - if (child[0] != NULL) { - return child[0]->findDeepestContainingNode(bounds); - } - } else if (bounds.low()[splitAxis] > splitLocation) { - // Bounds are on the high side, recurse into the child - // if it exists. - if (child[1] != NULL) { - return child[1]->findDeepestContainingNode(bounds); - } - } - - // There was no containing child, so this node is the - // deepest containing node. - return this; - } - - - /** Appends all members that intersect the box. - If useSphere is true, members that pass the box test - face a second test against the sphere. */ - void getIntersectingMembers( - const AABox& box, - const Sphere& sphere, - Array& members, - bool useSphere) const { - - // Test all values at this node - for (int v = 0; v < boundsArray.size(); ++v) { - const AABox& bounds = boundsArray[v]; - if (bounds.intersects(box) && - (! useSphere || bounds.intersects(sphere))) { - members.append(& (valueArray[v]->value)); - } - } - - // If the left child overlaps the box, recurse into it - if ((child[0] != NULL) && (box.low()[splitAxis] < splitLocation)) { - child[0]->getIntersectingMembers(box, sphere, members, useSphere); - } - - // If the right child overlaps the box, recurse into it - if ((child[1] != NULL) && (box.high()[splitAxis] > splitLocation)) { - child[1]->getIntersectingMembers(box, sphere, members, useSphere); - } - } - - /** - Recurse through the tree, assigning splitBounds fields. - */ - void assignSplitBounds(const AABox& myBounds) { - splitBounds = myBounds; - - AABox childBounds[2]; - myBounds.split(splitAxis, splitLocation, childBounds[0], childBounds[1]); - -# if defined(G3D_DEBUG) && defined(VERIFY_TREE) - // Verify the split - for (int v = 0; v < boundsArray.size(); ++v) { - const AABox& bounds = boundsArray[v]; - debugAssert(myBounds.contains(bounds)); - } -# endif - - for (int c = 0; c < 2; ++c) { - if (child[c]) { - child[c]->assignSplitBounds(childBounds[c]); - } - } - } - - /** Returns true if the ray intersects this node */ - bool intersects(const Ray& ray, float distance) const { - // See if the ray will ever hit this node or its children - Vector3 location; - bool alreadyInsideBounds = false; - bool rayWillHitBounds = - CollisionDetection::collisionLocationForMovingPointFixedAABox( - ray.origin(), ray.direction(), splitBounds, location, alreadyInsideBounds); - - bool canHitThisNode = (alreadyInsideBounds || - (rayWillHitBounds && ((location - ray.origin()).squaredLength() < square(distance)))); - - return canHitThisNode; - } - - template - void intersectRay( - const Ray& ray, - RayCallback& intersectCallback, - float& distance, - bool intersectCallbackIsFast) const { - - if (! intersects(ray, distance)) { - // The ray doesn't hit this node, so it can't hit the children of the node. - return; - } - - // Test for intersection against every object at this node. - for (int v = 0; v < valueArray.size(); ++v) { - bool canHitThisObject = true; - - if (! intersectCallbackIsFast) { - // See if - Vector3 location; - const AABox& bounds = boundsArray[v]; - bool alreadyInsideBounds = false; - bool rayWillHitBounds = - CollisionDetection::collisionLocationForMovingPointFixedAABox( - ray.origin(), ray.direction(), bounds, location, alreadyInsideBounds); - - canHitThisObject = (alreadyInsideBounds || - (rayWillHitBounds && ((location - ray.origin()).squaredLength() < square(distance)))); - } - - if (canHitThisObject) { - // It is possible that this ray hits this object. Look for the intersection using the - // callback. - const T& value = valueArray[v]->value; - intersectCallback(ray, value, distance); - } - } - - // There are three cases to consider next: - // - // 1. the ray can start on one side of the splitting plane and never enter the other, - // 2. the ray can start on one side and enter the other, and - // 3. the ray can travel exactly down the splitting plane - - enum {NONE = -1}; - int firstChild = NONE; - int secondChild = NONE; - - if (ray.origin()[splitAxis] < splitLocation) { - - // The ray starts on the small side - firstChild = 0; - - if (ray.direction()[splitAxis] > 0) { - // The ray will eventually reach the other side - secondChild = 1; - } - - } else if (ray.origin()[splitAxis] > splitLocation) { - - // The ray starts on the large side - firstChild = 1; - - if (ray.direction()[splitAxis] < 0) { - secondChild = 0; - } - } else { - // The ray starts on the splitting plane - if (ray.direction()[splitAxis] < 0) { - // ...and goes to the small side - firstChild = 0; - } else if (ray.direction()[splitAxis] > 0) { - // ...and goes to the large side - firstChild = 1; - } - } - - // Test on the side closer to the ray origin. - if ((firstChild != NONE) && child[firstChild]) { - child[firstChild]->intersectRay(ray, intersectCallback, distance, intersectCallbackIsFast); - } - - if (ray.direction()[splitAxis] != 0) { - // See if there was an intersection before hitting the splitting plane. - // If so, there is no need to look on the far side and recursion terminates. - float distanceToSplittingPlane = (splitLocation - ray.origin()[splitAxis]) / ray.direction()[splitAxis]; - if (distanceToSplittingPlane > distance) { - // We aren't going to hit anything else before hitting the splitting plane, - // so don't bother looking on the far side of the splitting plane at the other - // child. - return; - } - } - - // Test on the side farther from the ray origin. - if ((secondChild != NONE) && child[secondChild]) { - child[secondChild]->intersectRay(ray, intersectCallback, distance, intersectCallbackIsFast); - } - - } - }; - - - /** - Recursively subdivides the subarray. - - Clears the source array as soon as it is no longer needed. - - Call assignSplitBounds() on the root node after making a tree. - */ - Node* makeNode( - Array& source, - int valuesPerNode, - int numMeanSplits, - Array& temp) { - - Node* node = NULL; - - if (source.size() <= valuesPerNode) { - // Make a new leaf node - node = new Node(source); - - // Set the pointers in the memberTable - for (int i = 0; i < source.size(); ++i) { - memberTable.set(Member(source[i]), node); - } - source.clear(); - - } else { - // Make a new internal node - node = new Node(); - - const AABox& bounds = computeBounds(source, 0, source.size() - 1); - const Vector3& extent = bounds.high() - bounds.low(); - - Vector3::Axis splitAxis = extent.primaryAxis(); - - float splitLocation; - - // Arrays for holding the children - Array lt, gt; - - if (numMeanSplits <= 0) { - - source.medianPartition(lt, node->valueArray, gt, temp, CenterComparator(splitAxis)); - - // Choose the split location to be the center of whatever fell in the center - splitLocation = node->valueArray[0]->center[splitAxis]; - - // Some of the elements in the lt or gt array might really overlap the split location. - // Move them as needed. - for (int i = 0; i < lt.size(); ++i) { - const AABox& bounds = lt[i]->bounds; - if ((bounds.low()[splitAxis] <= splitLocation) && (bounds.high()[splitAxis] >= splitLocation)) { - node->valueArray.append(lt[i]); - // Remove this element and process the new one that - // is swapped in in its place. - lt.fastRemove(i); --i; - } - } - - for (int i = 0; i < gt.size(); ++i) { - const AABox& bounds = gt[i]->bounds; - if ((bounds.low()[splitAxis] <= splitLocation) && (bounds.high()[splitAxis] >= splitLocation)) { - node->valueArray.append(gt[i]); - // Remove this element and process the new one that - // is swapped in in its place. - gt.fastRemove(i); --i; - } - } - - if ((node->valueArray.size() > (source.size() / 2)) && - (source.size() > 6)) { - // This was a bad partition; we ended up putting the splitting plane right in the middle of most of the - // objects. We could try to split on a different axis, or use a different partition (e.g., the extents mean, - // or geometric mean). This implementation falls back on the extents mean, since that case is already handled - // below. - numMeanSplits = 1; - } - } - - // Note: numMeanSplits may have been increased by the code in the previous case above in order to - // force a re-partition. - - if (numMeanSplits > 0) { - // Split along the mean - splitLocation = - bounds.high()[splitAxis] * 0.5f + - bounds.low()[splitAxis] * 0.5f; - - debugAssertM(isFinite(splitLocation), - "Internal error: split location must be finite."); - - source.partition(NULL, lt, node->valueArray, gt, Comparator(splitAxis, splitLocation)); - - // The Comparator ensures that elements are strictly on the correct side of the split - } - - -# if defined(G3D_DEBUG) && defined(VERIFY_TREE) - debugAssert(lt.size() + node->valueArray.size() + gt.size() == source.size()); - // Verify that all objects ended up on the correct side of the split. - // (i.e., make sure that the Array partition was correct) - for (int i = 0; i < lt.size(); ++i) { - const AABox& bounds = lt[i]->bounds; - debugAssert(bounds.high()[splitAxis] < splitLocation); - } - - for (int i = 0; i < gt.size(); ++i) { - const AABox& bounds = gt[i]->bounds; - debugAssert(bounds.low()[splitAxis] > splitLocation); - } - - for (int i = 0; i < node->valueArray.size(); ++i) { - const AABox& bounds = node->valueArray[i]->bounds; - debugAssert(bounds.high()[splitAxis] >= splitLocation); - debugAssert(bounds.low()[splitAxis] <= splitLocation); - } -# endif - - // The source array is no longer needed - source.clear(); - - node->splitAxis = splitAxis; - node->splitLocation = splitLocation; - - // Update the bounds array and member table - node->boundsArray.resize(node->valueArray.size()); - for (int i = 0; i < node->valueArray.size(); ++i) { - Handle* v = node->valueArray[i]; - node->boundsArray[i] = v->bounds; - memberTable.set(Member(v), node); - } - - if (lt.size() > 0) { - node->child[0] = makeNode(lt, valuesPerNode, numMeanSplits - 1, temp); - } - - if (gt.size() > 0) { - node->child[1] = makeNode(gt, valuesPerNode, numMeanSplits - 1, temp); - } - - } - - return node; - } - - /** - Recursively clone the passed in node tree, setting - pointers for members in the memberTable as appropriate. - called by the assignment operator. - */ - Node* cloneTree(Node* src) { - Node* dst = new Node(*src); - - // Make back pointers - for (int i = 0; i < dst->valueArray.size(); ++i) { - memberTable.set(Member(dst->valueArray[i]), dst); - } - - // Clone children - for (int i = 0; i < 2; ++i) { - if (src->child[i] != NULL) { - dst->child[i] = cloneTree(src->child[i]); - } - } - - return dst; - } - - /** - Wrapper for a Handle; used to create a memberTable that acts like Table but - stores only Handle* internally to avoid memory copies. - */ - typedef _internal::Indirector Member; - - typedef Table MemberTable; - - /** Maps members to the node containing them */ - MemberTable memberTable; - - Node* root; - -public: - - /** To construct a balanced tree, insert the elements and then call - KDTree::balance(). */ - KDTree() : root(NULL) {} - - - KDTree(const KDTree& src) : root(NULL) { - *this = src; - } - - - KDTree& operator=(const KDTree& src) { - delete root; - // Clone tree takes care of filling out the memberTable. - root = cloneTree(src.root); - return *this; - } - - - ~KDTree() { - clear(); - } - - /** - Throws out all elements of the set. - */ - void clear() { - typedef typename Table<_internal::Indirector, Node*>::Iterator It; - - // Delete all handles stored in the member table - It cur = memberTable.begin(); - It end = memberTable.end(); - while (cur != end) { - delete cur->key.handle; - cur->key.handle = NULL; - ++cur; - } - memberTable.clear(); - - // Delete the tree structure itself - delete root; - root = NULL; - } - - int size() const { - return memberTable.size(); - } - - /** - Inserts an object into the set if it is not - already present. O(log n) time. Does not - cause the tree to be balanced. - */ - void insert(const T& value) { - if (contains(value)) { - // Already in the set - return; - } - - Handle* h = new Handle(value); - - if (root == NULL) { - // This is the first node; create a root node - root = new Node(); - } - - Node* node = root->findDeepestContainingNode(h->bounds); - - // Insert into the node - node->valueArray.append(h); - node->boundsArray.append(h->bounds); - - // Insert into the node table - Member m(h); - memberTable.set(m, node); - } - - /** Inserts each elements in the array in turn. If the tree - begins empty (no structure and no elements), this is faster - than inserting each element in turn. You still need to balance - the tree at the end.*/ - void insert(const Array& valueArray) { - if (root == NULL) { - // Optimized case for an empty tree; don't bother - // searching or reallocating the root node's valueArray - // as we incrementally insert. - root = new Node(); - root->valueArray.resize(valueArray.size()); - root->boundsArray.resize(root->valueArray.size()); - for (int i = 0; i < valueArray.size(); ++i) { - // Insert in opposite order so that we have the exact same - // data structure as if we inserted each (i.e., order is reversed - // from array). - Handle* h = new Handle(valueArray[i]); - int j = valueArray.size() - i - 1; - root->valueArray[j] = h; - root->boundsArray[j] = h->bounds; - memberTable.set(Member(h), root); - } - - } else { - // Insert at appropriate tree depth. - for (int i = 0; i < valueArray.size(); ++i) { - insert(valueArray[i]); - } - } - } - - - /** - Returns true if this object is in the set, otherwise - returns false. O(1) time. - */ - bool contains(const T& value) { - // Temporarily create a handle and member - Handle h(value); - return memberTable.containsKey(Member(&h)); - } - - - /** - Removes an object from the set in O(1) time. - It is an error to remove members that are not already - present. May unbalance the tree. - - Removing an element never causes a node (split plane) to be removed... - nodes are only changed when the tree is rebalanced. This behavior - is desirable because it allows the split planes to be serialized, - and then deserialized into an empty tree which can be repopulated. - */ - void remove(const T& value) { - debugAssertM(contains(value), - "Tried to remove an element from a " - "KDTree that was not present"); - - // Get the list of elements at the node - Handle h(value); - Member m(&h); - - Array& list = memberTable[m]->valueArray; - - Handle* ptr = NULL; - - // Find the element and remove it - for (int i = list.length() - 1; i >= 0; --i) { - if (list[i]->value == value) { - // This was the element. Grab the pointer so that - // we can delete it below - ptr = list[i]; - - // Remove the handle from the node - list.fastRemove(i); - - // Remove the corresponding bounds - memberTable[m]->boundsArray.fastRemove(i); - break; - } - } - - // Remove the member - memberTable.remove(m); - - // Delete the handle data structure - delete ptr; - ptr = NULL; - } - - - /** - If the element is in the set, it is removed. - The element is then inserted. - - This is useful when the == and hashCode methods - on T are independent of the bounds. In - that case, you may call update(v) to insert an - element for the first time and call update(v) - again every time it moves to keep the tree - up to date. - */ - void update(const T& value) { - if (contains(value)) { - remove(value); - } - insert(value); - } - - - /** - Rebalances the tree (slow). Call when objects - have moved substantially from their original positions - (which unbalances the tree and causes the spatial - queries to be slow). - - @param valuesPerNode Maximum number of elements to put at - a node. - - @param numMeanSplits numMeanSplits = 0 gives a - fully axis aligned BSP-tree, where the balance operation attempts to balance - the tree so that every splitting plane has an equal number of left - and right children (i.e. it is a median split along that axis). - This tends to maximize average performance. - - You can override this behavior by - setting a number of mean (average) splits. numMeanSplits = MAX_INT - creates a full oct-tree, which tends to optimize peak performance at the expense of - average performance. It tends to have better clustering behavior when - members are not uniformly distributed. - */ - void balance(int valuesPerNode = 5, int numMeanSplits = 3) { - if (root == NULL) { - // Tree is empty - return; - } - - // Get all handles and delete the old tree structure - Node* oldRoot = root; - for (int c = 0; c < 2; ++c) { - if (root->child[c] != NULL) { - root->child[c]->getHandles(root->valueArray); - - // Delete the child; this will delete all structure below it - delete root->child[c]; - root->child[c] = NULL; - } - } - - Array temp; - // Make a new root. Work with a copy of the value array because - // makeNode clears the source array as it progresses - Array copy(oldRoot->valueArray); - root = makeNode(copy, valuesPerNode, numMeanSplits, temp); - - // Throw away the old root node - delete oldRoot; - oldRoot = NULL; - - // Walk the tree, assigning splitBounds. We start with unbounded - // space. This will override the current member table. - const AABox& LARGE = AABox::large(); - root->assignSplitBounds(LARGE); - -# ifdef _DEBUG - { - // Ensure that the balanced tree is still correct - root->verifyNode(LARGE.low(), LARGE.high()); - } -# endif - } - - - /** Clear, set the contents to the values in the array, and then balance */ - void setContents(const Array& array, int valuesPerNode = 5, int numMeanSplits = 3) { - clear(); - insert(array); - balance(valuesPerNode, numMeanSplits); - } - - -protected: - - /** - @param parentMask The mask that this node returned from culledBy. - */ - static void getIntersectingMembers( - const Array& plane, - Array& members, - Node* node, - uint32 parentMask) { - - int dummy; - - if (parentMask == 0) { - // None of these planes can cull anything - for (int v = node->valueArray.size() - 1; v >= 0; --v) { - members.append(& (node->valueArray[v]->value)); - } - - // Iterate through child nodes - for (int c = 0; c < 2; ++c) { - if (node->child[c]) { - getIntersectingMembers(plane, members, node->child[c], 0); - } - } - } else { - - // Test values at this node against remaining planes - for (int v = node->boundsArray.size() - 1; v >= 0; --v) { - if (! node->boundsArray[v].culledBy(plane, dummy, parentMask)) { - members.append(&(node->valueArray[v]->value)); - } - } - - uint32 childMask = 0xFFFFFF; - - // Iterate through child nodes - for (int c = 0; c < 2; ++c) { - if (node->child[c] && - ! node->child[c]->splitBounds.culledBy(plane, dummy, parentMask, childMask)) { - // This node was not culled - getIntersectingMembers(plane, members, node->child[c], childMask); - } - } - } - } - -public: - - /** - Returns all members inside the set of planes. - @param members The results are appended to this array. - */ - void getIntersectingMembers(const Array& plane, Array& members) const { - if (root == NULL) { - return; - } - - getIntersectingMembers(plane, members, root, 0xFFFFFF); - } - - void getIntersectingMembers(const Array& plane, Array& members) const { - Array temp; - getIntersectingMembers(plane, temp, root, 0xFFFFFF); - for (int i = 0; i < temp.size(); ++i) { - members.append(*temp[i]); - } - } - - /** - Typically used to find all visible - objects inside the view frustum (see also GCamera::getClipPlanes)... i.e. all objects - not culled by frustum. - - Example: -
-        Array  visible;
-        tree.getIntersectingMembers(camera.frustum(), visible);
-        // ... Draw all objects in the visible array.
-      
- @param members The results are appended to this array. - */ - void getIntersectingMembers(const GCamera::Frustum& frustum, Array& members) const { - Array plane; - - for (int i = 0; i < frustum.faceArray.size(); ++i) { - plane.append(frustum.faceArray[i].plane); - } - - getIntersectingMembers(plane, members); - } - - void getIntersectingMembers(const GCamera::Frustum& frustum, Array& members) const { - Array temp; - getIntersectingMembers(frustum, temp); - for (int i = 0; i < temp.size(); ++i) { - members.append(*temp[i]); - } - } - - /** - C++ STL style iterator variable. See beginBoxIntersection(). - The iterator overloads the -> (dereference) operator, so this - acts like a pointer to the current member. - */ - // This iterator turns Node::getIntersectingMembers into a - // coroutine. It first translates that method from recursive to - // stack based, then captures the system state (analogous to a Scheme - // continuation) after each element is appended to the member array, - // and allowing the computation to be restarted. - class BoxIntersectionIterator { - private: - friend class TreeType; - - /** True if this is the "end" iterator instance */ - bool isEnd; - - /** The box that we're testing against. */ - AABox box; - - /** Node that we're currently looking at. Undefined if isEnd - is true. */ - Node* node; - - /** Nodes waiting to be processed */ - // We could use backpointers within the tree and careful - // state management to avoid ever storing the stack-- but - // it is much easier this way and only inefficient if the - // caller uses post increment (which they shouldn't!). - Array stack; - - /** The next index of current->valueArray to return. - Undefined when isEnd is true.*/ - int nextValueArrayIndex; - - BoxIntersectionIterator() : isEnd(true) {} - - BoxIntersectionIterator(const AABox& b, const Node* root) : - isEnd(root == NULL), box(b), - node(const_cast(root)), nextValueArrayIndex(-1) { - - // We intentionally start at the "-1" index of the current - // node so we can use the preincrement operator to move - // ourselves to element 0 instead of repeating all of the - // code from the preincrement method. Note that this might - // cause us to become the "end" instance. - ++(*this); - } - - public: - - inline bool operator!=(const BoxIntersectionIterator& other) const { - return ! (*this == other); - } - - bool operator==(const BoxIntersectionIterator& other) const { - if (isEnd) { - return other.isEnd; - } else if (other.isEnd) { - return false; - } else { - // Two non-end iterators; see if they match. This is kind of - // silly; users shouldn't call == on iterators in general unless - // one of them is the end iterator. - if ((box != other.box) || (node != other.node) || - (nextValueArrayIndex != other.nextValueArrayIndex) || - (stack.length() != other.stack.length())) { - return false; - } - - // See if the stacks are the same - for (int i = 0; i < stack.length(); ++i) { - if (stack[i] != other.stack[i]) { - return false; - } - } - - // We failed to find a difference; they must be the same - return true; - } - } - - /** - Pre increment. - */ - BoxIntersectionIterator& operator++() { - ++nextValueArrayIndex; - - bool foundIntersection = false; - while (! isEnd && ! foundIntersection) { - - // Search for the next node if we've exhausted this one - while ((! isEnd) && (nextValueArrayIndex >= node->valueArray.length())) { - // If we entered this loop, then the iterator has exhausted the elements at - // node (possibly because it just switched to a child node with no members). - // This loop continues until it finds a node with members or reaches - // the end of the whole intersection search. - - // If the right child overlaps the box, push it onto the stack for - // processing. - if ((node->child[1] != NULL) && - (box.high()[node->splitAxis] > node->splitLocation)) { - stack.push(node->child[1]); - } - - // If the left child overlaps the box, push it onto the stack for - // processing. - if ((node->child[0] != NULL) && - (box.low()[node->splitAxis] < node->splitLocation)) { - stack.push(node->child[0]); - } - - if (stack.length() > 0) { - // Go on to the next node (which may be either one of the ones we - // just pushed, or one from farther back the tree). - node = stack.pop(); - nextValueArrayIndex = 0; - } else { - // That was the last node; we're done iterating - isEnd = true; - } - } - - // Search for the next intersection at this node until we run out of children - while (! isEnd && ! foundIntersection && (nextValueArrayIndex < node->valueArray.length())) { - if (box.intersects(node->boundsArray[nextValueArrayIndex])) { - foundIntersection = true; - } else { - ++nextValueArrayIndex; - // If we exhaust this node, we'll loop around the master loop - // to find a new node. - } - } - } - - return *this; - } - - private: - /** - Post increment (much slower than preincrement!). - Intentionally overloaded to preclude accidentally slow code. - */ - BoxIntersectionIterator operator++(int); - /*{ - BoxIntersectionIterator old = *this; - ++this; - return old; - }*/ - - public: - - /** Overloaded dereference operator so the iterator can masquerade as a pointer - to a member */ - const T& operator*() const { - alwaysAssertM(! isEnd, "Can't dereference the end element of an iterator"); - return node->valueArray[nextValueArrayIndex]->value; - } - - /** Overloaded dereference operator so the iterator can masquerade as a pointer - to a member */ - T const * operator->() const { - alwaysAssertM(! isEnd, "Can't dereference the end element of an iterator"); - return &(stack.last()->valueArray[nextValueArrayIndex]->value); - } - - /** Overloaded cast operator so the iterator can masquerade as a pointer - to a member */ - operator T*() const { - alwaysAssertM(! isEnd, "Can't dereference the end element of an iterator"); - return &(stack.last()->valueArray[nextValueArrayIndex]->value); - } - }; - - - /** - Iterates through the members that intersect the box - */ - BoxIntersectionIterator beginBoxIntersection(const AABox& box) const { - return BoxIntersectionIterator(box, root); - } - - BoxIntersectionIterator endBoxIntersection() const { - // The "end" iterator instance - return BoxIntersectionIterator(); - } - - /** - Appends all members whose bounds intersect the box. - See also KDTree::beginBoxIntersection. - */ - void getIntersectingMembers(const AABox& box, Array& members) const { - if (root == NULL) { - return; - } - root->getIntersectingMembers(box, Sphere(Vector3::zero(), 0), members, false); - } - - void getIntersectingMembers(const AABox& box, Array& members) const { - Array temp; - getIntersectingMembers(box, temp); - for (int i = 0; i < temp.size(); ++i) { - members.append(*temp[i]); - } - } - - - /** - Invoke a callback for every member along a ray until the closest intersection is found. - - @param callback either a function or an instance of a class with an overloaded operator() of the form: - - void callback(const Ray& ray, const T& object, float& distance). If the ray hits the object - before travelling distance distance, updates distance with the new distance to - the intersection, otherwise leaves it unmodified. A common example is: - -
-     class Entity {
-     public:
-
-                void intersect(const Ray& ray, float& maxDist, Vector3& outLocation, Vector3& outNormal) {
-                    float d = maxDist;
-
-                    // ... search for intersection distance d
-
-                    if ((d > 0) && (d < maxDist)) {
-                        // Intersection occured
-                        maxDist = d;
-                        outLocation = ...;
-                        outNormal = ...;
-                    }
-                }
-            };
-
-            // Finds the surface normal and location of the first intersection with the scene
-            class Intersection {
-            public:
-                Entity*     closestEntity;
-                Vector3     hitLocation;
-                Vector3     hitNormal;
-
-                void operator()(const Ray& ray, const Entity* entity, float& distance) {
-                    entity->intersect(ray, distance, hitLocation, hitNormal);
-                }
-            };
-
-            KDTree scene;
-
-            Intersection intersection;
-            float distance = finf();
-            scene.intersectRay(camera.worldRay(x, y), intersection, distance);
-          
- - - @param distance When the method is invoked, this is the maximum - distance that the tree should search for an intersection. On - return, this is set to the distance to the first intersection - encountered. - - @param intersectCallbackIsFast If false, each object's bounds are - tested before the intersectCallback is invoked. If the - intersect callback runs at the same speed or faster than - AABox-ray intersection, set this to true. - */ - template - void intersectRay( - const Ray& ray, - RayCallback& intersectCallback, - float& distance, - bool intersectCallbackIsFast = false) const { - - root->intersectRay(ray, intersectCallback, distance, intersectCallbackIsFast); - } - - - /** - @brief Finds all members whose bounding boxes intersect the sphere. The actual - elements may not intersect the sphere. - - @param members The results are appended to this array. - */ - void getIntersectingMembers(const Sphere& sphere, Array& members) const { - if (root == NULL) { - return; - } - - AABox box; - sphere.getBounds(box); - root->getIntersectingMembers(box, sphere, members, true); - } - - void getIntersectingMembers(const Sphere& sphere, Array& members) const { - Array temp; - getIntersectingMembers(sphere, temp); - for (int i = 0; i < temp.size(); ++i) { - members.append(*temp[i]); - } - } - - /** - Stores the locations of the splitting planes (the structure but not the content) - so that the tree can be quickly rebuilt from a previous configuration without - calling balance. - */ - void serializeStructure(BinaryOutput& bo) const { - Node::serializeStructure(root, bo); - } - - /** Clears the member table */ - void deserializeStructure(BinaryInput& bi) { - clear(); - root = Node::deserializeStructure(bi); - } - - /** - Returns an array of all members of the set. See also KDTree::begin. - */ - void getMembers(Array& members) const { - Array temp; - memberTable.getKeys(temp); - for (int i = 0; i < temp.size(); ++i) { - members.append(*(temp.handle)); - } - } - - - /** If a value that is EqualsFunc to @a value is present, returns a pointer to the - version stored in the data structure, otherwise returns NULL. - */ - const T* getPointer(const T& value) const { - // Temporarily create a handle and member - Handle h(value); - const Member* member = memberTable.getKeyPointer(Member(&h)); - if (member == NULL) { - // Not found - return NULL; - } else { - return &(member->handle->value); - } - } - - - /** - C++ STL style iterator variable. See begin(). - Overloads the -> (dereference) operator, so this acts like a pointer - to the current member. - */ - class Iterator { - private: - friend class TreeType; - - // Note: this is a Table iterator, we are currently defining - // Set iterator - typename Table::Iterator it; - - Iterator(const typename Table::Iterator& it) : it(it) {} - - public: - - inline bool operator!=(const Iterator& other) const { - return !(*this == other); - } - - bool operator==(const Iterator& other) const { - return it == other.it; - } - - /** - Pre increment. - */ - Iterator& operator++() { - ++it; - return *this; - } - - private: - /** - Post increment (slower than preincrement). Intentionally unimplemented to prevent slow code. - */ - Iterator operator++(int);/* { - Iterator old = *this; - ++(*this); - return old; - }*/ - public: - - const T& operator*() const { - return it->key.handle->value; - } - - T* operator->() const { - return &(it->key.handle->value); - } - - operator T*() const { - return &(it->key.handle->value); - } - }; - - - /** - C++ STL style iterator method. Returns the first member. - Use preincrement (++entry) to get to the next element (iteration - order is arbitrary). - Do not modify the set while iterating. - */ - Iterator begin() const { - return Iterator(memberTable.begin()); - } - - - /** - C++ STL style iterator method. Returns one after the last iterator - element. - */ - Iterator end() const { - return Iterator(memberTable.end()); - } -#undef TreeType -}; - - -} - -#endif diff --git a/externals/g3dlite/G3D/Line.h b/externals/g3dlite/G3D/Line.h deleted file mode 100644 index 3579a6becec..00000000000 --- a/externals/g3dlite/G3D/Line.h +++ /dev/null @@ -1,105 +0,0 @@ -/** - @file Line.h - - Line class - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2001-06-02 - @edited 2006-02-28 - */ - -#ifndef G3D_LINE_H -#define G3D_LINE_H - -#include "G3D/platform.h" -#include "G3D/Vector3.h" - -namespace G3D { - -class Plane; - -/** - An infinite 3D line. - */ -class Line { -protected: - - Vector3 _point; - Vector3 _direction; - - Line(const Vector3& point, const Vector3& direction) { - _point = point; - _direction = direction.direction(); - } - -public: - - /** Undefined (provided for creating Array only) */ - inline Line() {} - - Line(class BinaryInput& b); - - void serialize(class BinaryOutput& b) const; - - void deserialize(class BinaryInput& b); - - virtual ~Line() {} - - /** - Constructs a line from two (not equal) points. - */ - static Line fromTwoPoints(const Vector3 &point1, const Vector3 &point2) { - return Line(point1, point2 - point1); - } - - /** - Creates a line from a point and a (nonzero) direction. - */ - static Line fromPointAndDirection(const Vector3& point, const Vector3& direction) { - return Line(point, direction); - } - - /** - Returns the closest point on the line to point. - */ - Vector3 closestPoint(const Vector3& pt) const; - - /** - Returns the distance between point and the line - */ - double distance(const Vector3& point) const { - return (closestPoint(point) - point).magnitude(); - } - - /** Returns a point on the line */ - Vector3 point() const; - - /** Returns the direction (or negative direction) of the line */ - Vector3 direction() const; - - /** - Returns the point where the line and plane intersect. If there - is no intersection, returns a point at infinity. - */ - Vector3 intersection(const Plane &plane) const; - - - /** Finds the closest point to the two lines. - - @param minDist Returns the minimum distance between the lines. - - @cite http://objectmix.com/graphics/133793-coordinates-closest-points-pair-skew-lines.html - */ - Vector3 closestPoint(const Line& B, float& minDist) const; - - inline Vector3 closestPoint(const Line& B) const { - float m; - return closestPoint(B, m); - } -}; - -};// namespace - - -#endif diff --git a/externals/g3dlite/G3D/LineSegment.h b/externals/g3dlite/G3D/LineSegment.h deleted file mode 100644 index 70210ec7e00..00000000000 --- a/externals/g3dlite/G3D/LineSegment.h +++ /dev/null @@ -1,115 +0,0 @@ -/** - @file LineSegment.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2003-02-08 - @edited 2008-02-02 - */ - -#ifndef G3D_LINESEGMENT_H -#define G3D_LINESEGMENT_H - -#include "G3D/platform.h" -#include "G3D/Vector3.h" - -namespace G3D { - -/** - An finite segment of an infinite 3D line. - */ -class LineSegment { -protected: - - Vector3 _point; - - /** Not normalized */ - Vector3 direction; - - LineSegment(const Vector3& __point, const Vector3& _direction) : _point(__point), direction(_direction) { - } - -public: - - inline LineSegment() : _point(Vector3::zero()), direction(Vector3::zero()) {} - - LineSegment(class BinaryInput& b); - - void serialize(class BinaryOutput& b) const; - - void deserialize(class BinaryInput& b); - - virtual ~LineSegment() {} - - /** - * Constructs a line from two (not equal) points. - */ - static LineSegment fromTwoPoints(const Vector3 &point1, const Vector3 &point2) { - return LineSegment(point1, point2 - point1); - } - - /** Call with 0 or 1 */ - Vector3 point(int i) const; - - inline float length() const { - return direction.magnitude(); - } - - /** - * Returns the closest point on the line segment to point. - */ - Vector3 closestPoint(const Vector3 &point) const; - - /** - Returns the distance between point and the line - */ - double distance(const Vector3& p) const { - return (closestPoint(p) - p).magnitude(); - } - - double distanceSquared(const Vector3& p) const { - return (closestPoint(p) - p).squaredMagnitude(); - } - - /** Returns true if some part of this segment is inside the sphere */ - bool intersectsSolidSphere(const class Sphere& s) const; - - Vector3 randomPoint() const; - -}; - - -class LineSegment2D { -private: - - Vector2 m_origin; - - /** Not normalized */ - Vector2 m_direction; - - /** Length of m_direction */ - float m_length; - -public: - - LineSegment2D() {} - - static LineSegment2D fromTwoPoints(const Vector2& p0, const Vector2& p1); - - /** Returns the intersection of these segements (including - testing endpoints), or Vector2::inf() if they do not intersect. */ - Vector2 intersection(const LineSegment2D& other) const; - - Vector2 point(int i) const; - - Vector2 closestPoint(const Vector2& Q) const; - - float distance(const Vector2& p) const; - - float length() const; -}; - -} // namespace - - -#endif diff --git a/externals/g3dlite/G3D/Log.h b/externals/g3dlite/G3D/Log.h deleted file mode 100644 index d252d0c1a17..00000000000 --- a/externals/g3dlite/G3D/Log.h +++ /dev/null @@ -1,109 +0,0 @@ -/** - @file Log.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - @cite Backtrace by Aaron Orenstein - @created 2001-08-04 - @edited 2005-11-04 - */ - -#ifndef G3D_LOG_H -#define G3D_LOG_H - -#include -#include -#include "G3D/platform.h" - -#ifndef G3D_WIN32 - #include -#endif - -namespace G3D { - -/** Prints to the common system log, log.txt, which is usually - in the working directory of the program. If your disk is - not writable or is slow, it will attempt to write to "c:/tmp/log.txt" or - "c:/temp/log.txt" on Windows systems instead. - - Unlike printf or debugPrintf, - this function guarantees that all output is committed before it returns. - This is very useful for debugging a crash, which might hide the last few - buffered print statements otherwise. - - Many G3D routines write useful warnings and debugging information to the - system log, which makes it a good first place to go when tracking down - a problem. - */ -void logPrintf(const char* fmt, ...); - -/** Does not flush the buffer; follow up with a logPrintf to force the flush. */ -void logLazyPrintf(const char* fmt, ...); - -/** - System log for debugging purposes. The first log opened - is the "common log" and can be accessed with the static - method common(). If you access common() and a common log - does not yet exist, one is created for you. - */ -class Log { -private: - - /** - Log messages go here. - */ - FILE* logFile; - - std::string filename; - - static Log* commonLog; - - int stripFromStackBottom; - -public: - - /** - @param stripFromStackBottom Number of call stacks to strip from the - bottom of the stack when printing a trace. Useful for hiding - routines like "main" and "WinMain". If the specified file cannot - be opened for some reason, tries to open "c:/tmp/log.txt" or - "c:/temp/log.txt" instead. - */ - Log(const std::string& filename = "log.txt", - int stripFromStackBottom = 0); - - virtual ~Log(); - - /** - Returns the handle to the file log. - */ - FILE* getFile() const; - - /** - Marks the beginning of a logfile section. - */ - void section(const std::string& s); - - /** - Given arguments like printf, writes characters to the debug text overlay. - */ - // We want G3D_CHECK_PRINTF_ARGS here, but that conflicts with the - // overload. - void __cdecl printf(const char* fmt, ...) G3D_CHECK_PRINTF_METHOD_ARGS; - - void __cdecl vprintf(const char*, va_list argPtr) G3D_CHECK_VPRINTF_METHOD_ARGS; - /** Does not flush */ - void __cdecl lazyvprintf(const char*, va_list argPtr) G3D_CHECK_VPRINTF_METHOD_ARGS; - - static Log* common(); - - static std::string getCommonLogFilename(); - - void print(const std::string& s); - - - void println(const std::string& s); -}; - -} - -#endif diff --git a/externals/g3dlite/G3D/Map2D.h b/externals/g3dlite/G3D/Map2D.h deleted file mode 100644 index 9af9f7242c1..00000000000 --- a/externals/g3dlite/G3D/Map2D.h +++ /dev/null @@ -1,667 +0,0 @@ -/** - @file Map2D.h - - More flexible support than provided by G3D::GImage. - - @maintainer Morgan McGuire, morgan@cs.brown.edu - @created 2004-10-10 - @edited 2009-03-24 - */ -#ifndef G3D_Map2D_h -#define G3D_Map2D_h - -#include "G3D/platform.h" -#include "G3D/g3dmath.h" -#include "G3D/Array.h" -#include "G3D/vectorMath.h" -#include "G3D/Vector2int16.h" -#include "G3D/ReferenceCount.h" -#include "G3D/AtomicInt32.h" -#include "G3D/GThread.h" -#include "G3D/Rect2D.h" -#include "G3D/WrapMode.h" - -#include - -namespace G3D { -namespace _internal { - -/** The default compute type for a type is the type itself. */ -template class _GetComputeType { -public: - typedef Storage Type; -}; - -} // _internal -} // G3D - -// This weird syntax is needed to support VC6, which doesn't -// properly implement template overloading. -#define DECLARE_COMPUTE_TYPE(StorageType, ComputeType) \ -namespace G3D { \ - namespace _internal { \ - template<> class _GetComputeType < StorageType > { \ - public: \ - typedef ComputeType Type; \ - }; \ - } \ -} - -DECLARE_COMPUTE_TYPE( float32, float64) -DECLARE_COMPUTE_TYPE( float64, float64) - -DECLARE_COMPUTE_TYPE( int8, float32) -DECLARE_COMPUTE_TYPE( int16, float32) -DECLARE_COMPUTE_TYPE( int32, float64) -DECLARE_COMPUTE_TYPE( int64, float64) - -DECLARE_COMPUTE_TYPE( uint8, float32) -DECLARE_COMPUTE_TYPE( uint16, float32) -DECLARE_COMPUTE_TYPE( uint32, float64) -DECLARE_COMPUTE_TYPE( uint64, float64) - -DECLARE_COMPUTE_TYPE( Vector2, Vector2) -DECLARE_COMPUTE_TYPE( Vector2int16, Vector2) - -DECLARE_COMPUTE_TYPE( Vector3, Vector3) -DECLARE_COMPUTE_TYPE( Vector3int16, Vector3) - -DECLARE_COMPUTE_TYPE( Vector4, Vector4) - -DECLARE_COMPUTE_TYPE( Color3, Color3) -DECLARE_COMPUTE_TYPE( Color3uint8, Color3) - -DECLARE_COMPUTE_TYPE( Color4, Color4) -DECLARE_COMPUTE_TYPE( Color4uint8, Color4) -#undef DECLARE_COMPUTE_TYPE - -namespace G3D { - -/** - Map of values across a discrete 2D plane. Can be thought of as a generic class for 2D images, - allowing flexibility as to pixel format and convenient methods. - In fact, the "pixels" can be any values - on a grid that can be sensibly interpolated--RGB colors, scalars, 4D vectors, and so on. - - Other "image" classes in G3D: - - G3D::GImage - Supports file formats, fast, Color3uint8 and Color4uint8 formats. No interpolation. - - G3D::Texture::Ref - Represents image on the graphics card (not directly readable on the CPU). Supports 2D, 3D, and a variety of interpolation methods, loads file formats. - - G3D::Image3 - A subclass of Map2D that supports image loading and saving and conversion to Texture. - - G3D::Image4 - A subclass of Map2D that supports image loading and saving and conversion to Texture. - - G3D::Image3uint8 - A subclass of Map2D that supports image loading and saving and conversion to Texture. - - G3D::Image4uint8 - A subclass of Map2D that supports image loading and saving and conversion to Texture. - - There are two type parameters-- the first (@ Storage) is the type - used to store the "pixel" values efficiently and - the second (@a Compute) is - the type operated on by computation. The Compute::Compute(Storage&) constructor - is used to convert between storage and computation types. - @a Storage is often an integer version of @a Compute, for example - Map2D. By default, the computation type is: - -
-     Storage       Computation
-
-     uint8          float32
-     uint16         float32
-     uint32         float64
-     uint64         float64
-
-     int8           float32
-     int16          float32
-     int32          float64
-     int64          float64
-
-     float32        float64
-     float64        float64
-
-     Vector2        Vector2
-     Vector2int16   Vector2
-
-     Vector3        Vector3
-     Vector3int16   Vector3
-
-     Vector4        Vector4
-
-     Color3         Color3
-     Color3uint8    Color3
-
-     Color4         Color4
-     Color4uint8    Color4
-    
- Any other storage type defaults to itself as the computation type. - - The computation type can be any that - supports lerp, +, -, *, /, and an empty constructor. - - Assign value: - - im->set(x, y, 7); or - im->get(x, y) = 7; - - Read value: - - int c = im(x, y); - - Can also sample with nearest neighbor, bilinear, and bicubic - interpolation. - - Sampling follows OpenGL conventions, where - pixel values represent grid points and (0.5, 0.5) is half-way - between two vertical and two horizontal grid points. - To draw an image of dimensions w x h with nearest neighbor - sampling, render pixels from [0, 0] to [w - 1, h - 1]. - - Under the WrapMode::CLAMP wrap mode, the value of bilinear interpolation - becomes constant outside [1, w - 2] horizontally. Nearest neighbor - interpolation is constant outside [0, w - 1] and bicubic outside - [3, w - 4]. The class does not offer quadratic interpolation because - the interpolation filter could not center over a pixel. - - @author Morgan McGuire, http://graphics.cs.williams.edu - */ -template< typename Storage, -typename Compute = typename G3D::_internal::_GetComputeType::Type> -class Map2D : public ReferenceCountedObject { - -// -// It doesn't make sense to automatically convert from Compute back to Storage -// because the rounding rule (and scaling) is application dependent. -// Thus the interpolation methods all return type Compute. -// - -public: - - typedef Storage StorageType; - typedef Compute ComputeType; - typedef Map2D Type; - typedef ReferenceCountedPointer Ref; - -protected: - - Storage ZERO; - - /** Width, in pixels. */ - uint32 w; - - /** Height, in pixels. */ - uint32 h; - - WrapMode _wrapMode; - - /** 0 if no mutating method has been invoked - since the last call to setChanged(); */ - AtomicInt32 m_changed; - - Array data; - - /** Handles the exceptional cases from get */ - const Storage& slowGet(int x, int y, WrapMode wrap) { - switch (wrap) { - case WrapMode::CLAMP: - return fastGet(iClamp(x, 0, w - 1), iClamp(y, 0, h - 1)); - - case WrapMode::TILE: - return fastGet(iWrap(x, w), iWrap(y, h)); - - case WrapMode::ZERO: - return ZERO; - - case WrapMode::ERROR: - alwaysAssertM(((uint32)x < w) && ((uint32)y < h), - format("Index out of bounds: (%d, %d), w = %d, h = %d", - x, y, w, h)); - - // intentionally fall through - case WrapMode::IGNORE: - // intentionally fall through - default: - { - static Storage temp; - return temp; - } - } - } - -public: - - /** Unsafe access to the underlying data structure with no wrapping support; requires that (x, y) is in bounds. */ - inline const Storage& fastGet(int x, int y) const { - debugAssert(((uint32)x < w) && ((uint32)y < h)); - return data[x + y * w]; - } - - /** Unsafe access to the underlying data structure with no wrapping support; requires that (x, y) is in bounds. */ - inline void fastSet(int x, int y, const Storage& v) { - debugAssert(((uint32)x < w) && ((uint32)y < h)); - data[x + y * w] = v; - } - -protected: - - /** Given four control points and a value on the range [0, 1) - evaluates the Catmull-rom spline between the times of the - middle two control points */ - Compute bicubic(const Compute* ctrl, double s) const { - - // f = B * S * ctrl' - - // B matrix: Catmull-Rom spline basis - static const double B[4][4] = { - { 0.0, -0.5, 1.0, -0.5}, - { 1.0, 0.0, -2.5, 1.5}, - { 0.0, 0.5, 2.0, -1.5}, - { 0.0, 0.0, -0.5, 0.5}}; - - // S: Powers of the fraction - double S[4]; - double s2 = s * s; - S[0] = 1.0; - S[1] = s; - S[2] = s2; - S[3] = s2 * s; - - Compute sum(ZERO); - - for (int c = 0; c < 4; ++c) { - double coeff = 0.0; - for (int power = 0; power < 4; ++power) { - coeff += B[c][power] * S[power]; - } - sum += ctrl[c] * coeff; - } - - return sum; - } - - - Map2D(int w, int h, WrapMode wrap) : w(0), h(0), _wrapMode(wrap), m_changed(1) { - ZERO = Storage(Compute(Storage()) * 0); - resize(w, h); - } - -public: - - /** - Although Map2D is not threadsafe (except for the setChanged() method), - you can use this mutex to create your own threadsafe access to a Map2D. - Not used by the default implementation. - */ - GMutex mutex; - - static Ref create(int w = 0, int h = 0, WrapMode wrap = WrapMode::ERROR) { - return new Map2D(w, h, wrap); - } - - /** Resizes without clearing, leaving garbage. - */ - void resize(uint32 newW, uint32 newH) { - if ((newW != w) || (newH != h)) { - w = newW; - h = newH; - data.resize(w * h); - setChanged(true); - } - } - - /** - Returns true if this map has been written to since the last call to setChanged(false). - This is useful if you are caching a texture map other value that must be recomputed - whenever this changes. - */ - bool changed() { - return m_changed.value() != 0; - } - - /** Set/unset the changed flag. */ - void setChanged(bool c) { - m_changed = c ? 1 : 0; - } - - /** Returns a pointer to the underlying row-major data. There is no padding at the end of the row. - Be careful--this will be reallocated during a resize. You should call setChanged(true) if you mutate the array.*/ - Storage* getCArray() { - return data.getCArray(); - } - - - const Storage* getCArray() const { - return data.getCArray(); - } - - - /** Row-major array. You should call setChanged(true) if you mutate the array. */ - Array& getArray() { - return data; - } - - - const Array& getArray() const { - return data; - } - - /** is (x, y) strictly within the image bounds, or will it trigger some kind of wrap mode */ - inline bool inBounds(int x, int y) const { - return (((uint32)x < w) && ((uint32)y < h)); - } - - /** is (x, y) strictly within the image bounds, or will it trigger some kind of wrap mode */ - inline bool inBounds(const Vector2int16& v) const { - return inBounds(v.x, v.y); - } - - /** Get the value at (x, y). - - Note that the type of image->get(x, y) is - the storage type, not the computation - type. If the constructor promoting Storage to Compute rescales values - (as, for example Color3(Color3uint8&) does), this will not match the value - returned by Map2D::nearest. - */ - inline const Storage& get(int x, int y, WrapMode wrap) const { - if (((uint32)x < w) && ((uint32)y < h)) { - return data[x + y * w]; - } else { - // Remove the const to allow a slowGet on this object - // (we're returning a const reference so this is ok) - return const_cast(this)->slowGet(x, y, wrap); - } -# ifndef G3D_WIN32 - // gcc gives a useless warning that the above code might reach the end of the function; - // we use this line to supress the warning. - return ZERO; -# endif - } - - inline const Storage& get(int x, int y) const { - return get(x, y, _wrapMode); - } - - inline const Storage& get(const Vector2int16& p) const { - return get(p.x, p.y, _wrapMode); - } - - inline const Storage& get(const Vector2int16& p, WrapMode wrap) const { - return get(p.x, p.y, wrap); - } - - inline Storage& get(int x, int y, WrapMode wrap) { - return const_cast(const_cast(this)->get(x, y, wrap)); -# ifndef G3D_WIN32 - // gcc gives a useless warning that the above code might reach the end of the function; - // we use this line to supress the warning. - return ZERO; -# endif - } - - inline Storage& get(int x, int y) { - return const_cast(const_cast(this)->get(x, y)); -# ifndef G3D_WIN32 - // gcc gives a useless warning that the above code might reach the end of the function; - // we use this line to supress the warning. - return ZERO; -# endif - } - - inline Storage& get(const Vector2int16& p) { - return get(p.x, p.y); - } - - /** Sets the changed flag to true */ - inline void set(const Vector2int16& p, const Storage& v) { - set(p.x, p.y, v); - } - - /** Sets the changed flag to true */ - void set(int x, int y, const Storage& v, WrapMode wrap) { - setChanged(true); - if (((uint32)x < w) && ((uint32)y < h)) { - // In bounds, wrapping isn't an issue. - data[x + y * w] = v; - } else { - const_cast(slowGet(x, y, wrap)) = v; - } - } - - void set(int x, int y, const Storage& v) { - set(x, y, v, _wrapMode); - } - - - void setAll(const Storage& v) { - for(int i = 0; i < data.size(); ++i) { - data[i] = v; - } - setChanged(true); - } - - /** flips if @a flip is true*/ - void maybeFlipVertical(bool flip) { - if (flip) { - flipVertical(); - } - } - - virtual void flipVertical() { - int halfHeight = h/2; - Storage* d = data.getCArray(); - for (int y = 0; y < halfHeight; ++y) { - int o1 = y * w; - int o2 = (h - y - 1) * w; - for (int x = 0; x < (int)w; ++x) { - int i1 = o1 + x; - int i2 = o2 + x; - Storage temp = d[i1]; - d[i1] = d[i2]; - d[i2] = temp; - } - } - setChanged(true); - } - - virtual void flipHorizontal() { - int halfWidth = w / 2; - Storage* d = data.getCArray(); - for (int x = 0; x < halfWidth; ++x) { - for (int y = 0; y < (int)h; ++y) { - int i1 = y * w + x; - int i2 = y * w + (w - x - 1); - Storage temp = d[i1]; - d[i1] = d[i2]; - d[i2] = temp; - } - } - setChanged(true); - } - - /** - Crops this map so that it only contains pixels between (x, y) and (x + w - 1, y + h - 1) inclusive. - */ - virtual void crop(int newX, int newY, int newW, int newH) { - alwaysAssertM(newX + newW <= (int)w, "Cannot grow when cropping"); - alwaysAssertM(newY + newH <= (int)h, "Cannot grow when cropping"); - alwaysAssertM(newX >= 0 && newY >= 0, "Origin out of bounds."); - - // Always safe to copy towards the upper left, provided - // that we're iterating towards the lower right. This lets us avoid - // reallocating the underlying array. - for (int y = 0; y < newH; ++y) { - for (int x = 0; x < newW; ++x) { - data[x + y * newW] = data[(x + newX) + (y + newY) * w]; - } - } - - resize(newW, newH); - } - - /** iRounds to the nearest x0 and y0. */ - virtual void crop(const Rect2D& rect) { - crop(iRound(rect.x0()), iRound(rect.y0()), iRound(rect.x1()) - iRound(rect.x0()), iRound(rect.y1()) - iRound(rect.y0())); - } - - /** Returns the nearest neighbor. Pixel values are considered - to be at the upper left corner, so image->nearest(x, y) == image(x, y) - */ - inline Compute nearest(float x, float y, WrapMode wrap) const { - int ix = iRound(x); - int iy = iRound(y); - return Compute(get(ix, iy, wrap)); - } - - inline Compute nearest(float x, float y) const { - return nearest(x, y, _wrapMode); - } - - inline Compute nearest(const Vector2& p) const { - return nearest(p.x, p.y); - } - - /** Returns the average value of all elements of the map */ - Compute average() const { - if ((w == 0) || (h == 0)) { - return ZERO; - } - - // To avoid overflows, compute the average of row averages - - Compute rowSum = ZERO; - for (unsigned int y = 0; y < h; ++y) { - Compute sum = ZERO; - int offset = y * w; - for (unsigned int x = 0; x < w; ++x) { - sum += Compute(data[offset + x]); - } - rowSum += sum * (1.0f / w); - } - - return rowSum * (1.0f / h); - } - - /** - Needs to access elements from (floor(x), floor(y)) - to (floor(x) + 1, floor(y) + 1) and will use - the wrap mode appropriately (possibly generating - out of bounds errors). - - Guaranteed to match nearest(x, y) at integers. */ - Compute bilinear(float x, float y, WrapMode wrap) const { - const int i = iFloor(x); - const int j = iFloor(y); - - const float fX = x - i; - const float fY = y - j; - - // Horizontal interpolation, first row - const Compute& t0 = get(i, j, wrap); - const Compute& t1 = get(i + 1, j, wrap); - - // Horizontal interpolation, second row - const Compute& t2 = get(i, j + 1, wrap); - const Compute& t3 = get(i + 1, j + 1, wrap); - - const Compute& A = lerp(t0, t1, fX); - const Compute& B = lerp(t2, t3, fX); - - // Vertical interpolation - return lerp(A, B, fY); - } - - Compute bilinear(float x, float y) const { - return bilinear(x, y, _wrapMode); - } - - inline Compute bilinear(const Vector2& p) const { - return bilinear(p.x, p.y, _wrapMode); - } - - inline Compute bilinear(const Vector2& p, WrapMode wrap) const { - return bilinear(p.x, p.y, wrap); - } - - /** - Uses Catmull-Rom splines to interpolate between grid - values. Guaranteed to match nearest(x, y) at integers. - */ - Compute bicubic(float x, float y, WrapMode wrap) const { - int i = iFloor(x); - int j = iFloor(y); - float fX = x - i; - float fY = y - j; - - Compute vsample[4]; - for (int v = 0; v < 4; ++v) { - - // Horizontal interpolation - Compute hsample[4]; - for (int u = 0; u < 4; ++u) { - hsample[u] = Compute(get(i + u - 1, j + v - 1, wrap)); - } - - vsample[v] = bicubic(hsample, fX); - } - - // Vertical interpolation - return bicubic(vsample, fY); - } - - Compute bicubic(float x, float y) const { - return bicubic(x, y, _wrapMode); - } - - inline Compute bicubic(const Vector2& p, WrapMode wrap) const { - return bicubic(p.x, p.y, wrap); - } - - inline Compute bicubic(const Vector2& p) const { - return bicubic(p.x, p.y, _wrapMode); - } - - /** Pixel width */ - inline int32 width() const { - return (int32)w; - } - - - /** Pixel height */ - inline int32 height() const { - return (int32)h; - } - - - /** Dimensions in pixels */ - Vector2int16 size() const { - return Vector2int16(w, h); - } - - /** Rectangle from (0, 0) to (w, h) */ - Rect2D rect2DBounds() const { - return Rect2D::xywh(0, 0, w, h); - } - - /** Number of bytes occupied by the image data and this structure */ - size_t sizeInMemory() const { - return data.size() * sizeof(Storage) + sizeof(*this); - } - - - WrapMode wrapMode() const { - return _wrapMode; - } - - - void setWrapMode(WrapMode m) { - _wrapMode = m; - } -}; - - - -} - -#endif // G3D_IMAGE_H diff --git a/externals/g3dlite/G3D/Matrix.h b/externals/g3dlite/G3D/Matrix.h deleted file mode 100644 index 3c5394d9a76..00000000000 --- a/externals/g3dlite/G3D/Matrix.h +++ /dev/null @@ -1,634 +0,0 @@ -/** - @file Matrix.h - @author Morgan McGuire, http://graphics.cs.williams.edu - - @created 2005-10-23 - @edited 2007-07-18 - */ - -#ifndef G3D_MATRIX_H -#define G3D_MATRIX_H - -#include "G3D/g3dmath.h" -#include "G3D/Vector3.h" -#include "G3D/Vector4.h" -#include "G3D/Matrix3.h" -#include "G3D/Matrix4.h" -#include "G3D/ReferenceCount.h" - -namespace G3D { - -/** - N x M matrix. - - The actual data is tracked internally by a reference counted pointer; - it is efficient to pass and assign Matrix objects because no data is actually copied. - This avoids the headache of pointers and allows natural math notation: - -
-    Matrix A, B, C;
-    // ...
-
-    C = A * f(B);
-    C = C.inverse();
-
-    A = Matrix::identity(4);
-    C = A;
-    C.set(0, 0, 2.0); // Triggers a copy of the data so that A remains unchanged.
-
-    // etc.
-
-  
- - The Matrix::debugNumCopyOps and Matrix::debugNumAllocOps counters - increment every time an operation forces the copy and allocation of matrices. You - can use these to detect slow operations when efficiency is a major concern. - - Some methods accept an output argument instead of returning a value. For example, - A = B.transpose() can also be invoked as B.transpose(A). - The latter may be more efficient, since Matrix may be able to re-use the storage of - A (if it has approximatly the right size and isn't currently shared with another matrix). - - @sa G3D::Matrix3, G3D::Matrix4, G3D::Vector2, G3D::Vector3, G3D::Vector4, G3D::CoordinateFrame - - @beta - */ -class Matrix { -public: - /** - Internal precision. Currently float, but this may become a templated class in the future - to allow operations like Matrix and Matrix. - - Not necessarily a plain-old-data type (e.g., could ComplexFloat), but must be something - with no constructor, that can be safely memcpyd, and that has a bit pattern of all zeros - when zero.*/ - typedef float T; - - /** Incremented every time the elements of a matrix are copied. Useful for profiling your - own code that uses Matrix to determine when it is slow due to copying.*/ - static int debugNumCopyOps; - - /** Incremented every time a new matrix object is allocated. Useful for profiling your - own code that uses Matrix to determine when it is slow due to allocation.*/ - static int debugNumAllocOps; - -private: -public: - - /** Used internally by Matrix. - - Does not throw exceptions-- assumes the caller has taken care of - argument checking. */ - class Impl : public ReferenceCountedObject { - public: - - static void* operator new(size_t size) { - return System::malloc(size); - } - - static void operator delete(void* p) { - System::free(p); - } - - ~Impl(); - - private: - friend class Matrix; - - /** elt[r][c] = the element. Pointers into data.*/ - T** elt; - - /** Row major data for the entire matrix. */ - T* data; - - /** The number of rows */ - int R; - - /** The number of columns */ - int C; - - int dataSize; - - /** If R*C is much larger or smaller than the current, deletes all previous data - and resets to random data. Otherwise re-uses existing memory and just resets - R, C, and the row pointers. */ - void setSize(int newRows, int newCols); - - inline Impl() : elt(NULL), data(NULL), R(0), C(0), dataSize(0) {} - - Impl(const Matrix3& M); - - Impl(const Matrix4& M); - - inline Impl(int r, int c) : elt(NULL), data(NULL), R(0), C(0), dataSize(0) { - setSize(r, c); - } - - Impl& operator=(const Impl& m); - - inline Impl(const Impl& B) : elt(NULL), data(NULL), R(0), C(0), dataSize(0) { - // Use the assignment operator - *this = B; - } - - void setZero(); - - inline void set(int r, int c, T v) { - debugAssert(r < R); - debugAssert(c < C); - elt[r][c] = v; - } - - inline const T& get(int r, int c) const { - debugAssert(r < R); - debugAssert(c < C); - return elt[r][c]; - } - - /** Multiplies this by B and puts the result in out. */ - void mul(const Impl& B, Impl& out) const; - - /** Ok if out == this or out == B */ - void add(const Impl& B, Impl& out) const; - - /** Ok if out == this or out == B */ - void add(T B, Impl& out) const; - - /** Ok if out == this or out == B */ - void sub(const Impl& B, Impl& out) const; - - /** Ok if out == this or out == B */ - void sub(T B, Impl& out) const; - - /** B - this */ - void lsub(T B, Impl& out) const; - - /** Ok if out == this or out == B */ - void arrayMul(const Impl& B, Impl& out) const; - - /** Ok if out == this or out == B */ - void mul(T B, Impl& out) const; - - /** Ok if out == this or out == B */ - void arrayDiv(const Impl& B, Impl& out) const; - - /** Ok if out == this or out == B */ - void div(T B, Impl& out) const; - - void negate(Impl& out) const; - - /** Slow way of computing an inverse; for reference */ - void inverseViaAdjoint(Impl& out) const; - - /** Use Gaussian elimination with pivots to solve for the inverse destructively in place. */ - void inverseInPlaceGaussJordan(); - - void adjoint(Impl& out) const; - - /** Matrix of all cofactors */ - void cofactor(Impl& out) const; - - /** - Cofactor [r][c] is defined as C[r][c] = -1 ^(r+c) * det(A[r][c]), - where A[r][c] is the (R-1)x(C-1) matrix formed by removing row r and - column c from the original matrix. - */ - T cofactor(int r, int c) const; - - /** Ok if out == this or out == B */ - void transpose(Impl& out) const; - - T determinant() const; - - /** Determinant computed without the given row and column */ - T determinant(int r, int c) const; - - void arrayLog(Impl& out) const; - - void arrayExp(Impl& out) const; - - void arraySqrt(Impl& out) const; - - void arrayCos(Impl& out) const; - - void arraySin(Impl& out) const; - - void swapRows(int r0, int r1); - - void swapAndNegateCols(int c0, int c1); - - void mulRow(int r, const T& v); - - void abs(Impl& out) const; - - /** Makes a (R-1)x(C-1) copy of this matrix */ - void withoutRowAndCol(int excludeRow, int excludeCol, Impl& out) const; - - bool anyNonZero() const; - - bool allNonZero() const; - - void setRow(int r, const T* vals); - - void setCol(int c, const T* vals); - }; -private: - - typedef ReferenceCountedPointer ImplRef; - - ImplRef impl; - - inline Matrix(ImplRef i) : impl(i) {} - inline Matrix(Impl* i) : impl(ImplRef(i)) {} - - /** Used by SVD */ - class SortRank { - public: - T value; - int col; - - inline bool operator>(const SortRank& x) const { - return x.value > value; - } - - inline bool operator<(const SortRank& x) const { - return x.value < value; - } - - inline bool operator>=(const SortRank& x) const { - return x.value >= value; - } - - inline bool operator<=(const SortRank& x) const { - return x.value <= value; - } - - inline bool operator==(const SortRank& x) const { - return x.value == value; - } - - inline bool operator!=(const SortRank& x) const { - return x.value != value; - } - }; - - Matrix vectorPseudoInverse() const; - Matrix partitionPseudoInverse() const; - Matrix colPartPseudoInverse() const; - Matrix rowPartPseudoInverse() const; - - Matrix col2PseudoInverse(const Matrix& B) const; - Matrix col3PseudoInverse(const Matrix& B) const; - Matrix col4PseudoInverse(const Matrix& B) const; - Matrix row2PseudoInverse(const Matrix& B) const; - Matrix row3PseudoInverse(const Matrix& B) const; - Matrix row4PseudoInverse(const Matrix& B) const; - -public: - - Matrix() : impl(new Impl(0, 0)) {} - - Matrix(const Matrix3& M) : impl(new Impl(M)) {} - - Matrix(const Matrix4& M) : impl(new Impl(M)) {} - - template - static Matrix fromDiagonal(const Array& d) { - Matrix D = zero(d.length(), d.length()); - for (int i = 0; i < d.length(); ++i) { - D.set(i, i, d[i]); - } - return D; - } - - static Matrix fromDiagonal(const Matrix& d); - - /** Returns a new matrix that is all zero. */ - Matrix(int R, int C) : impl(new Impl(R, C)) { - impl->setZero(); - } - - /** Returns a new matrix that is all zero. */ - static Matrix zero(int R, int C); - - /** Returns a new matrix that is all one. */ - static Matrix one(int R, int C); - - /** Returns a new identity matrix */ - static Matrix identity(int N); - - /** Uniformly distributed values between zero and one. */ - static Matrix random(int R, int C); - - /** The number of rows */ - inline int rows() const { - return impl->R; - } - - /** Number of columns */ - inline int cols() const { - return impl->C; - } - - /** Generally more efficient than A * B */ - Matrix& operator*=(const T& B); - - /** Generally more efficient than A / B */ - Matrix& operator/=(const T& B); - - /** Generally more efficient than A + B */ - Matrix& operator+=(const T& B); - - /** Generally more efficient than A - B */ - Matrix& operator-=(const T& B); - - /** No performance advantage over A * B because - matrix multiplication requires intermediate - storage. */ - Matrix& operator*=(const Matrix& B); - - /** Generally more efficient than A + B */ - Matrix& operator+=(const Matrix& B); - - /** Generally more efficient than A - B */ - Matrix& operator-=(const Matrix& B); - - /** Returns a new matrix that is a subset of this one, - from r1:r2 to c1:c2, inclusive.*/ - Matrix subMatrix(int r1, int r2, int c1, int c2) const; - - /** Matrix multiplication. To perform element-by-element multiplication, - see arrayMul. */ - inline Matrix operator*(const Matrix& B) const { - Matrix C(impl->R, B.impl->C); - impl->mul(*B.impl, *C.impl); - return C; - } - - /** See also A *= B, which is more efficient in many cases */ - inline Matrix operator*(const T& B) const { - Matrix C(impl->R, impl->C); - impl->mul(B, *C.impl); - return C; - } - - /** See also A += B, which is more efficient in many cases */ - inline Matrix operator+(const Matrix& B) const { - Matrix C(impl->R, impl->C); - impl->add(*B.impl, *C.impl); - return C; - } - - /** See also A -= B, which is more efficient in many cases */ - inline Matrix operator-(const Matrix& B) const { - Matrix C(impl->R, impl->C); - impl->sub(*B.impl, *C.impl); - return C; - } - - /** See also A += B, which is more efficient in many cases */ - inline Matrix operator+(const T& v) const { - Matrix C(impl->R, impl->C); - impl->add(v, *C.impl); - return C; - } - - /** See also A -= B, which is more efficient in many cases */ - inline Matrix operator-(const T& v) const { - Matrix C(impl->R, impl->C); - impl->sub(v, *C.impl); - return C; - } - - - Matrix operator>(const T& scalar) const; - - Matrix operator<(const T& scalar) const; - - Matrix operator>=(const T& scalar) const; - - Matrix operator<=(const T& scalar) const; - - Matrix operator==(const T& scalar) const; - - Matrix operator!=(const T& scalar) const; - - /** scalar B - this */ - inline Matrix lsub(const T& B) const { - Matrix C(impl->R, impl->C); - impl->lsub(B, *C.impl); - return C; - } - - inline Matrix arrayMul(const Matrix& B) const { - Matrix C(impl->R, impl->C); - impl->arrayMul(*B.impl, *C.impl); - return C; - } - - Matrix3 toMatrix3() const; - - Matrix4 toMatrix4() const; - - Vector2 toVector2() const; - - Vector3 toVector3() const; - - Vector4 toVector4() const; - - /** Mutates this */ - void arrayMulInPlace(const Matrix& B); - - /** Mutates this */ - void arrayDivInPlace(const Matrix& B); - - // Declares an array unary method and its explicit-argument counterpart -# define DECLARE_METHODS_1(method)\ - inline Matrix method() const {\ - Matrix C(impl->R, impl->C);\ - impl->method(*C.impl);\ - return C;\ - }\ - void method(Matrix& out) const; - - - DECLARE_METHODS_1(abs) - DECLARE_METHODS_1(arrayLog) - DECLARE_METHODS_1(arrayExp) - DECLARE_METHODS_1(arraySqrt) - DECLARE_METHODS_1(arrayCos) - DECLARE_METHODS_1(arraySin) - DECLARE_METHODS_1(negate) - -# undef DECLARE_METHODS_1 - - inline Matrix operator-() const { - return negate(); - } - - /** - A-1 computed using the Gauss-Jordan algorithm, - for square matrices. - Run time is O(R3), where R is the - number of rows. - */ - inline Matrix inverse() const { - Impl* A = new Impl(*impl); - A->inverseInPlaceGaussJordan(); - return Matrix(A); - } - - inline T determinant() const { - return impl->determinant(); - } - - /** - AT - */ - inline Matrix transpose() const { - Impl* A = new Impl(cols(), rows()); - impl->transpose(*A); - return Matrix(A); - } - - /** Transpose in place; more efficient than transpose */ - void transpose(Matrix& out) const; - - inline Matrix adjoint() const { - Impl* A = new Impl(cols(), rows()); - impl->adjoint(*A); - return Matrix(A); - } - - /** - (ATA)-1AT) computed - using SVD. - - @param tolerance Use -1 for automatic tolerance. - */ - Matrix pseudoInverse(float tolerance = -1) const; - - /** Called from pseudoInverse when the matrix has size > 4 along some dimension.*/ - Matrix svdPseudoInverse(float tolerance = -1) const; - - /** - (ATA)-1AT) computed - using Gauss-Jordan elimination. - */ - inline Matrix gaussJordanPseudoInverse() const { - Matrix trans = transpose(); - return (trans * (*this)).inverse() * trans; - } - - /** Singular value decomposition. Factors into three matrices - such that @a this = @a U * fromDiagonal(@a d) * @a V.transpose(). - - The matrix must have at least as many rows as columns. - - Run time is O(C2*R). - - @param sort If true (default), the singular values - are arranged so that D is sorted from largest to smallest. - */ - void svd(Matrix& U, Array& d, Matrix& V, bool sort = true) const; - - void set(int r, int c, T v); - - void setCol(int c, const Matrix& vec); - - void setRow(int r, const Matrix& vec); - - Matrix col(int c) const; - - Matrix row(int r) const; - - T get(int r, int c) const; - - Vector2int16 size() const { - return Vector2int16(rows(), cols()); - } - - int numElements() const { - return rows() * cols(); - } - - void swapRows(int r0, int r1); - - /** Swaps columns c0 and c1 and negates both */ - void swapAndNegateCols(int c0, int c1); - - void mulRow(int r, const T& v); - - /** Returns true if any element is non-zero */ - bool anyNonZero() const; - - /** Returns true if all elements are non-zero */ - bool allNonZero() const; - - inline bool allZero() const { - return !anyNonZero(); - } - - inline bool anyZero() const { - return !allNonZero(); - } - - /** Serializes in Matlab source format */ - void serialize(TextOutput& t) const; - - std::string toString(const std::string& name) const; - - std::string toString() const { - static const std::string name = ""; - return toString(name); - } - - /** 2-norm squared: sum(squares). (i.e., dot product with itself) */ - double normSquared() const; - - /** 2-norm (sqrt(sum(squares)) */ - double norm() const; - - /** - Low-level SVD functionality. Useful for applications that do not want - to construct a Matrix but need to perform the SVD operation. - - this = U * D * V' - - Assumes that rows >= cols - - @return NULL on success, a string describing the error on failure. - @param U rows x cols matrix to be decomposed, gets overwritten with U, a rows x cols matrix with orthogonal columns. - @param D vector of singular values of a (diagonal of the D matrix). Length cols. - @param V returns the right orthonormal transformation matrix, size cols x cols - - @cite Based on Dianne Cook's implementation, which is adapted from - svdecomp.c in XLISP-STAT 2.1, which is code from Numerical Recipes - adapted by Luke Tierney and David Betz. The Numerical Recipes code - is adapted from Forsythe et al, who based their code on Golub and - Reinsch's original implementation. - */ - static const char* svdCore(float** U, int rows, int cols, float* D, float** V); - -}; - -} - -inline G3D::Matrix operator-(const G3D::Matrix::T& v, const G3D::Matrix& M) { - return M.lsub(v); -} - -inline G3D::Matrix operator*(const G3D::Matrix::T& v, const G3D::Matrix& M) { - return M * v; -} - -inline G3D::Matrix operator+(const G3D::Matrix::T& v, const G3D::Matrix& M) { - return M + v; -} - -inline G3D::Matrix abs(const G3D::Matrix& M) { - return M.abs(); -} - -#endif - diff --git a/externals/g3dlite/G3D/Matrix2.h b/externals/g3dlite/G3D/Matrix2.h deleted file mode 100644 index eaf4aefa220..00000000000 --- a/externals/g3dlite/G3D/Matrix2.h +++ /dev/null @@ -1,69 +0,0 @@ -#ifndef G3D_MATRIX2_H -#define G3D_MATRIX2_H - -#include "G3D/platform.h" -#include "G3D/Vector2.h" - -namespace G3D { - -/** @beta */ -class Matrix2 { -private: - - float data[2][2]; - -public: - - inline Matrix2() { - data[0][0] = 1.0f; data[0][1] = 0.0f; - data[1][0] = 0.0f; data[1][1] = 1.0f; - } - - inline Matrix2(float v00, float v01, float v10, float v11) { - data[0][0] = v00; data[0][1] = v01; - data[1][0] = v10; data[1][1] = v11; - } - - inline Vector2 operator*(const Vector2& v) const { - return Vector2(data[0][0] * v[0] + data[0][1] * v[1], - data[1][0] * v[0] + data[1][1] * v[1]); - } - - inline Matrix2 inverse() const { - return Matrix2(data[0][0], data[1][0], - data[0][1], data[1][1]) * (1.0f / determinant()); - } - - inline Matrix2 transpose() const { - return Matrix2(data[0][0], data[1][0], - data[0][1], data[1][1]); - } - - inline float determinant() const { - return data[0][0] * data[1][1] - data[0][1] * data[1][0]; - } - - inline Matrix2 operator*(float f) const { - return Matrix2(data[0][0] * f, data[0][1] * f, - data[1][0] * f, data[1][1] * f); - } - - inline Matrix2 operator/(float f) const { - return Matrix2(data[0][0] / f, data[0][1] / f, - data[1][0] / f, data[1][1] / f); - } - - inline float* operator[](int i) { - debugAssert(i >= 0 && i <= 2); - return data[i]; - } - - inline const float* operator[](int i) const { - debugAssert(i >= 0 && i <= 1); - return data[i]; - } -}; - -} - -#endif diff --git a/externals/g3dlite/G3D/Matrix3.h b/externals/g3dlite/G3D/Matrix3.h deleted file mode 100644 index 06ec7e67474..00000000000 --- a/externals/g3dlite/G3D/Matrix3.h +++ /dev/null @@ -1,366 +0,0 @@ -/** - @file Matrix3.h - - 3x3 matrix class - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @cite Portions based on Dave Eberly's Magic Software Library at
http://www.magic-software.com - - @created 2001-06-02 - @edited 2006-04-05 - */ - -#ifndef G3D_Matrix3_h -#define G3D_Matrix3_h - -#include "G3D/platform.h" -#include "G3D/Vector3.h" -#include "G3D/Vector4.h" -#include "G3D/debugAssert.h" - -#include - -namespace G3D { - -#ifdef _MSC_VER -// Turn off "conditional expression is constant" warning; MSVC generates this -// for debug assertions in inlined methods. -# pragma warning (disable : 4127) -#endif - -class Any; - -/** - 3x3 matrix. Do not subclass. - */ -class Matrix3 { -private: - - float elt[3][3]; - - // Hidden operators - bool operator<(const Matrix3&) const; - bool operator>(const Matrix3&) const; - bool operator<=(const Matrix3&) const; - bool operator>=(const Matrix3&) const; - -public: - - Matrix3(const Any& any); - - operator Any() const; - - /** Initial values are undefined for performance. See also - Matrix3::zero(), Matrix3::identity(), Matrix3::fromAxisAngle, etc.*/ - inline Matrix3() {} - - Matrix3 (class BinaryInput& b); - Matrix3 (const float aafEntry[3][3]); - Matrix3 (const Matrix3& rkMatrix); - Matrix3 (float fEntry00, float fEntry01, float fEntry02, - float fEntry10, float fEntry11, float fEntry12, - float fEntry20, float fEntry21, float fEntry22); - - bool fuzzyEq(const Matrix3& b) const; - - /** Constructs a matrix from a quaternion. - @cite Graphics Gems II, p. 351--354 - @cite Implementation from Watt and Watt, pg 362*/ - Matrix3(const class Quat& q); - - void serialize(class BinaryOutput& b) const; - void deserialize(class BinaryInput& b); - - /** Returns true if column(0).cross(column(1)).dot(column(2)) > 0. */ - bool isRightHanded() const; - - /** - Sets all elements. - */ - void set(float fEntry00, float fEntry01, float fEntry02, - float fEntry10, float fEntry11, float fEntry12, - float fEntry20, float fEntry21, float fEntry22); - - /** - * member access, allows use of construct mat[r][c] - */ - inline float* operator[] (int iRow) { - debugAssert(iRow >= 0); - debugAssert(iRow < 3); - return (float*)&elt[iRow][0]; - } - - inline const float* operator[] (int iRow) const { - debugAssert(iRow >= 0); - debugAssert(iRow < 3); - return (const float*)&elt[iRow][0]; - } - - inline operator float* () { - return (float*)&elt[0][0]; - } - - inline operator const float* () const{ - return (const float*)&elt[0][0]; - } - - Vector3 column(int c) const; - const Vector3& row(int r) const; - - void setColumn(int iCol, const Vector3 &vector); - void setRow(int iRow, const Vector3 &vector); - - // assignment and comparison - inline Matrix3& operator= (const Matrix3& rkMatrix) { - memcpy(elt, rkMatrix.elt, 9 * sizeof(float)); - return *this; - } - - bool operator== (const Matrix3& rkMatrix) const; - bool operator!= (const Matrix3& rkMatrix) const; - - // arithmetic operations - Matrix3 operator+ (const Matrix3& rkMatrix) const; - Matrix3 operator- (const Matrix3& rkMatrix) const; - /** Matrix-matrix multiply */ - Matrix3 operator* (const Matrix3& rkMatrix) const; - Matrix3 operator- () const; - - Matrix3& operator+= (const Matrix3& rkMatrix); - Matrix3& operator-= (const Matrix3& rkMatrix); - Matrix3& operator*= (const Matrix3& rkMatrix); - - /** - * matrix * vector [3x3 * 3x1 = 3x1] - */ - inline Vector3 operator* (const Vector3& v) const { - Vector3 kProd; - - for (int r = 0; r < 3; ++r) { - kProd[r] = - elt[r][0] * v[0] + - elt[r][1] * v[1] + - elt[r][2] * v[2]; - } - - return kProd; - } - - - /** - * vector * matrix [1x3 * 3x3 = 1x3] - */ - friend Vector3 operator* (const Vector3& rkVector, - const Matrix3& rkMatrix); - - /** - * matrix * scalar - */ - Matrix3 operator* (float fScalar) const; - - /** scalar * matrix */ - friend Matrix3 operator* (double fScalar, const Matrix3& rkMatrix); - friend Matrix3 operator* (float fScalar, const Matrix3& rkMatrix); - friend Matrix3 operator* (int fScalar, const Matrix3& rkMatrix); - - Matrix3& operator*= (float k); - Matrix3& operator/= (float k); - - -private: - /** Multiplication where out != A and out != B */ - static void _mul(const Matrix3& A, const Matrix3& B, Matrix3& out); -public: - - /** Optimized implementation of out = A * B. It is safe (but slow) to call - with A, B, and out possibly pointer equal to one another.*/ - // This is a static method so that it is not ambiguous whether "this" - // is an input or output argument. - inline static void mul(const Matrix3& A, const Matrix3& B, Matrix3& out) { - if ((&out == &A) || (&out == &B)) { - // We need a temporary anyway, so revert to the stack method. - out = A * B; - } else { - // Optimized in-place multiplication. - _mul(A, B, out); - } - } - -private: - static void _transpose(const Matrix3& A, Matrix3& out); -public: - - /** Optimized implementation of out = A.transpose(). It is safe (but slow) to call - with A and out possibly pointer equal to one another. - - Note that A.transpose() * v can be computed - more efficiently as v * A. - */ - inline static void transpose(const Matrix3& A, Matrix3& out) { - if (&A == &out) { - out = A.transpose(); - } else { - _transpose(A, out); - } - } - - /** Returns true if the rows and column L2 norms are 1.0 and the rows are orthogonal. */ - bool isOrthonormal() const; - - Matrix3 transpose () const; - bool inverse (Matrix3& rkInverse, float fTolerance = 1e-06) const; - Matrix3 inverse (float fTolerance = 1e-06) const; - float determinant () const; - - /** singular value decomposition */ - void singularValueDecomposition (Matrix3& rkL, Vector3& rkS, - Matrix3& rkR) const; - /** singular value decomposition */ - void singularValueComposition (const Matrix3& rkL, - const Vector3& rkS, const Matrix3& rkR); - - /** Gram-Schmidt orthonormalization (applied to columns of rotation matrix) */ - void orthonormalize(); - - /** orthogonal Q, diagonal D, upper triangular U stored as (u01,u02,u12) */ - void qDUDecomposition (Matrix3& rkQ, Vector3& rkD, - Vector3& rkU) const; - - /** - Polar decomposition of a matrix. Based on pseudocode from Nicholas J - Higham, "Computing the Polar Decomposition -- with Applications Siam - Journal of Science and Statistical Computing, Vol 7, No. 4, October - 1986. - - Decomposes A into R*S, where R is orthogonal and S is symmetric. - - Ken Shoemake's "Matrix animation and polar decomposition" - in Proceedings of the conference on Graphics interface '92 - seems to be better known in the world of graphics, but Higham's version - uses a scaling constant that can lead to faster convergence than - Shoemake's when the initial matrix is far from orthogonal. - */ - void polarDecomposition(Matrix3 &R, Matrix3 &S) const; - - /** - * Matrix norms. - */ - float spectralNorm () const; - - float squaredFrobeniusNorm() const; - - float frobeniusNorm() const; - - float l1Norm() const; - - float lInfNorm() const; - - float diffOneNorm(const Matrix3 &y) const; - - /** matrix must be orthonormal */ - void toAxisAngle(Vector3& rkAxis, float& rfRadians) const; - - static Matrix3 fromDiagonal(const Vector3& d) { - return Matrix3(d.x, 0, 0, - 0, d.y, 0, - 0, 0, d.z); - } - - static Matrix3 fromAxisAngle(const Vector3& rkAxis, float fRadians); - - /** - * The matrix must be orthonormal. The decomposition is yaw*pitch*roll - * where yaw is rotation about the Up vector, pitch is rotation about the - * right axis, and roll is rotation about the Direction axis. - */ - bool toEulerAnglesXYZ (float& rfYAngle, float& rfPAngle, - float& rfRAngle) const; - bool toEulerAnglesXZY (float& rfYAngle, float& rfPAngle, - float& rfRAngle) const; - bool toEulerAnglesYXZ (float& rfYAngle, float& rfPAngle, - float& rfRAngle) const; - bool toEulerAnglesYZX (float& rfYAngle, float& rfPAngle, - float& rfRAngle) const; - bool toEulerAnglesZXY (float& rfYAngle, float& rfPAngle, - float& rfRAngle) const; - bool toEulerAnglesZYX (float& rfYAngle, float& rfPAngle, - float& rfRAngle) const; - static Matrix3 fromEulerAnglesXYZ (float fYAngle, float fPAngle, float fRAngle); - static Matrix3 fromEulerAnglesXZY (float fYAngle, float fPAngle, float fRAngle); - static Matrix3 fromEulerAnglesYXZ (float fYAngle, float fPAngle, float fRAngle); - static Matrix3 fromEulerAnglesYZX (float fYAngle, float fPAngle, float fRAngle); - static Matrix3 fromEulerAnglesZXY (float fYAngle, float fPAngle, float fRAngle); - static Matrix3 fromEulerAnglesZYX (float fYAngle, float fPAngle, float fRAngle); - - /** eigensolver, matrix must be symmetric */ - void eigenSolveSymmetric (float afEigenvalue[3], - Vector3 akEigenvector[3]) const; - - static void tensorProduct (const Vector3& rkU, const Vector3& rkV, - Matrix3& rkProduct); - std::string toString() const; - - static const float EPSILON; - - // Special values. - // The unguaranteed order of initialization of static variables across - // translation units can be a source of annoying bugs, so now the static - // special values (like Vector3::ZERO, Color3::WHITE, ...) are wrapped - // inside static functions that return references to them. - // These functions are intentionally not inlined, because: - // "You might be tempted to write [...] them as inline functions - // inside their respective header files, but this is something you - // must definitely not do. An inline function can be duplicated - // in every file in which it appears œóõ½ and this duplication - // includes the static object definition. Because inline functions - // automatically default to internal linkage, this would result in - // having multiple static objects across the various translation - // units, which would certainly cause problems. So you must - // ensure that there is only one definition of each wrapping - // function, and this means not making the wrapping functions inline", - // according to Chapter 10 of "Thinking in C++, 2nd ed. Volume 1" by Bruce Eckel, - // http://www.mindview.net/ - static const Matrix3& zero(); - static const Matrix3& identity(); - -protected: - - // support for eigensolver - void tridiagonal (float afDiag[3], float afSubDiag[3]); - bool qLAlgorithm (float afDiag[3], float afSubDiag[3]); - - // support for singular value decomposition - static const float ms_fSvdEpsilon; - static const int ms_iSvdMaxIterations; - static void bidiagonalize (Matrix3& kA, Matrix3& kL, - Matrix3& kR); - static void golubKahanStep (Matrix3& kA, Matrix3& kL, - Matrix3& kR); - - // support for spectral norm - static float maxCubicRoot (float afCoeff[3]); - -}; - - -//---------------------------------------------------------------------------- -/** v * M == M.transpose() * v */ -inline Vector3 operator* (const Vector3& rkPoint, const Matrix3& rkMatrix) { - Vector3 kProd; - - for (int r = 0; r < 3; ++r) { - kProd[r] = - rkPoint[0] * rkMatrix.elt[0][r] + - rkPoint[1] * rkMatrix.elt[1][r] + - rkPoint[2] * rkMatrix.elt[2][r]; - } - - return kProd; -} - - -} // namespace - -#endif - diff --git a/externals/g3dlite/G3D/Matrix4.h b/externals/g3dlite/G3D/Matrix4.h deleted file mode 100644 index 9ce87d875b8..00000000000 --- a/externals/g3dlite/G3D/Matrix4.h +++ /dev/null @@ -1,249 +0,0 @@ -/** - @file Matrix4.h - - 4x4 matrix class - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2003-10-02 - @edited 2009-10-20 - */ - -#ifndef G3D_Matrix4_h -#define G3D_Matrix4_h - -#ifdef _MSC_VER -// Disable conditional expression is constant, which occurs incorrectly on inlined functions -# pragma warning (push) -# pragma warning( disable : 4127 ) -#endif - -#include "G3D/platform.h" -#include "G3D/debugAssert.h" -#include "G3D/Matrix3.h" -#include "G3D/Vector3.h" - -namespace G3D { - -class Any; - -/** - A 4x4 matrix. - - See also G3D::CoordinateFrame, G3D::Matrix3, G3D::Quat - */ -class Matrix4 { -private: - - float elt[4][4]; - - /** - Computes the determinant of the 3x3 matrix that lacks excludeRow - and excludeCol. - */ - float subDeterminant(int excludeRow, int excludeCol) const; - - // Hidden operators - bool operator<(const Matrix4&) const; - bool operator>(const Matrix4&) const; - bool operator<=(const Matrix4&) const; - bool operator>=(const Matrix4&) const; - -public: - /** Must be of the form: Matrix4(#, #, # .... #)*/ - Matrix4(const Any& any); - - operator Any() const; - - Matrix4( - float r1c1, float r1c2, float r1c3, float r1c4, - float r2c1, float r2c2, float r2c3, float r2c4, - float r3c1, float r3c2, float r3c3, float r3c4, - float r4c1, float r4c2, float r4c3, float r4c4); - - /** - init should be row major. - */ - Matrix4(const float* init); - - /** - a is the upper left 3x3 submatrix and b is the upper right 3x1 submatrix. The last row of the created matrix is (0,0,0,1). - */ - Matrix4(const class Matrix3& upper3x3, const class Vector3& lastCol = Vector3::zero()); - - Matrix4(const class CoordinateFrame& c); - - Matrix4(const double* init); - - Matrix4(); - - /** Produces an RT transformation that nearly matches this Matrix4. - Because a Matrix4 may not be precisely a rotation and translation, - this may introduce error. */ - class CoordinateFrame approxCoordinateFrame() const; - - // Special values. - // Intentionally not inlined: see Matrix3::identity() for details. - static const Matrix4& identity(); - static const Matrix4& zero(); - - /** If this is a perspective projection matrix created by - Matrix4::perspectiveProjection, extract its parameters. */ - void getPerspectiveProjectionParameters - (float& left, - float& right, - float& bottom, - float& top, - float& nearval, - float& farval, - float updirection = -1.0f) const; - - inline float* operator[](int r) { - debugAssert(r >= 0); - debugAssert(r < 4); - return (float*)&elt[r]; - } - - inline const float* operator[](int r) const { - debugAssert(r >= 0); - debugAssert(r < 4); - return (const float*)&elt[r]; - } - - inline operator float* () { - return (float*)&elt[0][0]; - } - - inline operator const float* () const { - return (const float*)&elt[0][0]; - } - - Matrix4 operator*(const Matrix4& other) const; - - class Matrix3 upper3x3() const; - - /** Homogeneous multiplication. Let k = M * [v w]^T. result = k.xyz() / k.w */ - class Vector3 homoMul(const class Vector3& v, float w) const; - - /** - Constructs an orthogonal projection matrix from the given parameters. - Near and far are the NEGATIVE of the near and far plane Z values - (to follow OpenGL conventions). - - \param upDirection Use -1.0 for 2D Y increasing downwards (the G3D 8.x default convention), - 1.0 for 2D Y increasing upwards (the G3D 7.x default and OpenGL convention) - */ - static Matrix4 orthogonalProjection( - float left, - float right, - float bottom, - float top, - float nearval, - float farval, - float upDirection = -1.0f); - - - /** \param upDirection Use -1.0 for 2D Y increasing downwards (the G3D 8.x default convention), - 1.0 for 2D Y increasing upwards (the G3D 7.x default and OpenGL convention) - */ - static Matrix4 orthogonalProjection( - const class Rect2D& rect, - float nearval, - float farval, - float upDirection = -1.0f); - - /** \param upDirection Use -1.0 for 2D Y increasing downwards (the G3D 8.x default convention), - 1.0 for 2D Y increasing upwards (the G3D 7.x default and OpenGL convention) - */ - static Matrix4 perspectiveProjection( - float left, - float right, - float bottom, - float top, - float nearval, - float farval, - float upDirection = -1.0f); - - void setRow(int r, const class Vector4& v); - void setColumn(int c, const Vector4& v); - - const Vector4& row(int r) const; - Vector4 column(int c) const; - - Matrix4 operator*(const float s) const; - Vector4 operator*(const Vector4& vector) const; - - Matrix4 transpose() const; - - bool operator!=(const Matrix4& other) const; - bool operator==(const Matrix4& other) const; - - float determinant() const; - Matrix4 inverse() const; - - /** - Transpose of the cofactor matrix (used in computing the inverse). - Note: This is in fact only one type of adjoint. More generally, - an adjoint of a matrix is any mapping of a matrix which possesses - certain properties. This returns the so-called adjugate - or classical adjoint. - */ - Matrix4 adjoint() const; - Matrix4 cofactor() const; - - /** Serializes row-major */ - void serialize(class BinaryOutput& b) const; - void deserialize(class BinaryInput& b); - - std::string toString() const; - - /** 3D scale matrix */ - inline static Matrix4 scale(const Vector3& v) { - return Matrix4(v.x, 0, 0, 0, - 0, v.y, 0, 0, - 0, 0, v.z, 0, - 0, 0, 0, 1); - } - - /** 3D scale matrix */ - inline static Matrix4 scale(float x, float y, float z) { - return scale(Vector3(x, y, z)); - } - - /** 3D scale matrix */ - inline static Matrix4 scale(float s) { - return scale(s,s,s); - } - - /** 3D translation matrix */ - inline static Matrix4 translation(const Vector3& v) { - return Matrix4(Matrix3::identity(), v); - } - - inline static Matrix4 translation(float x, float y, float z) { - return Matrix4(Matrix3::identity(), Vector3(x, y, z)); - } - - /** Create a rotation matrix that rotates \a deg degrees around the Y axis */ - inline static Matrix4 yawDegrees(float deg) { - return Matrix4(Matrix3::fromAxisAngle(Vector3::unitY(), toRadians(deg))); - } - - inline static Matrix4 pitchDegrees(float deg) { - return Matrix4(Matrix3::fromAxisAngle(Vector3::unitX(), toRadians(deg))); - } - - inline static Matrix4 rollDegrees(float deg) { - return Matrix4(Matrix3::fromAxisAngle(Vector3::unitZ(), toRadians(deg))); - } -}; - - - -} // namespace - -#ifdef _MSC_VER -# pragma warning (pop) -#endif - -#endif diff --git a/externals/g3dlite/G3D/MemoryManager.h b/externals/g3dlite/G3D/MemoryManager.h deleted file mode 100644 index 15bf6d8be43..00000000000 --- a/externals/g3dlite/G3D/MemoryManager.h +++ /dev/null @@ -1,93 +0,0 @@ -/** - @file MemoryManager.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - @created 2009-04-20 - @edited 2009-04-20 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ -#ifndef G3D_MemoryManager_h -#define G3D_MemoryManager_h - -#include "G3D/platform.h" -#include "G3D/ReferenceCount.h" - -namespace G3D { - -/** - Abstraction of memory management. - Default implementation uses G3D::System::malloc and is threadsafe. - - \sa CRTMemoryManager, AlignedMemoryManager, AreaMemoryManager */ -class MemoryManager : public ReferenceCountedObject { -protected: - - MemoryManager(); - -public: - - typedef ReferenceCountedPointer Ref; - - /** Return a pointer to \a s bytes of memory that are unused by - the rest of the program. The contents of the memory are - undefined */ - virtual void* alloc(size_t s); - - /** Invoke to declare that this memory will no longer be used by - the program. The memory manager is not required to actually - reuse or release this memory. */ - virtual void free(void* ptr); - - /** Returns true if this memory manager is threadsafe (i.e., alloc - and free can be called asychronously) */ - virtual bool isThreadsafe() const; - - /** Return the instance. There's only one instance of the default - MemoryManager; it is cached after the first creation. */ - static MemoryManager::Ref create(); -}; - -/** - Allocates memory on 16-byte boundaries. - \sa MemoryManager, CRTMemoryManager, AreaMemoryManager */ -class AlignedMemoryManager : public MemoryManager { -protected: - - AlignedMemoryManager(); - -public: - - typedef ReferenceCountedPointer Ref; - - - virtual void* alloc(size_t s); - - virtual void free(void* ptr); - - virtual bool isThreadsafe() const; - - static AlignedMemoryManager::Ref create(); -}; - - -/** MemoryManager implemented using the C runtime. */ -class CRTMemoryManager : public MemoryManager { -protected: - CRTMemoryManager(); - -public: - typedef ReferenceCountedPointer Ref; - virtual void* alloc(size_t s); - virtual void free(void* ptr); - virtual bool isThreadsafe() const; - - /** There's only one instance of this memory manager; it is - cached after the first creation. */ - static CRTMemoryManager::Ref create(); -}; - -} - -#endif diff --git a/externals/g3dlite/G3D/MeshAlg.h b/externals/g3dlite/G3D/MeshAlg.h deleted file mode 100644 index 1decea10105..00000000000 --- a/externals/g3dlite/G3D/MeshAlg.h +++ /dev/null @@ -1,683 +0,0 @@ -/** - @file MeshAlg.h - - Indexed Mesh algorithms. - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2003-09-14 - @edited 2010-01-18 -*/ - -#ifndef G3D_MeshAlg_h -#define G3D_MeshAlg_h - -#include "G3D/platform.h" -#include "G3D/Array.h" -#include "G3D/Vector3.h" -#include "G3D/CoordinateFrame.h" -#include "G3D/SmallArray.h" -#include "G3D/constants.h" -#include "G3D/Image1.h" - -#ifdef G3D_WIN32 -// Turn off "conditional expression is constant" warning; MSVC generates this -// for debug assertions in inlined methods. -#pragma warning (disable : 4127) -#endif - -namespace G3D { - -/** - Indexed mesh algorithms. You have to build your own mesh class. -

- No mesh class is provided with G3D because there isn't an "ideal" - mesh format-- one application needs keyframed animation, another - skeletal animation, a third texture coordinates, a fourth - cannot precompute information, etc. Instead of compromising, this - class implements the hard parts of mesh computation and you can write - your own ideal mesh class on top of it. - - \sa G3D::ArticulatedModel, G3D::IFSModel - */ -class MeshAlg { -public: - - /** \deprecated */ - typedef PrimitiveType Primitive; - - /** Adjacency information for a vertex. - Does not contain the vertex position or normal, - which are stored in the MeshAlg::Geometry object. - Vertexs must be stored in an array - parallel to (indexed in the same way as) - MeshAlg::Geometry::vertexArray. - */ - class Vertex { - public: - Vertex() {} - - /** - Array of edges adjacent to this vertex. - Let e = edgeIndex[i]. - edge[(e >= 0) ? e : ~e].vertexIndex[0] == this - vertex index. - - Edges may be listed multiple times if they are - degenerate. - */ - SmallArray edgeIndex; - - /** - Returns true if e or ~e is in the edgeIndex list. - */ - inline bool inEdge(int e) const { - return edgeIndex.contains(~e) || edgeIndex.contains(e); - } - - /** - Array of faces containing this vertex. Faces - may be listed multiple times if they are degenerate. - */ - SmallArray faceIndex; - - inline bool inFace(int f) const { - debugAssert(f >= 0); - return faceIndex.contains(f); - } - }; - - - /** - Oriented, indexed triangle. - */ - class Face { - public: - Face(); - - /** - Used by Edge::faceIndex to indicate a missing face. - This is a large negative value. - */ - static const int NONE; - - - /** - Vertices in the face in counter-clockwise order. - Degenerate faces may include the same vertex multiple times. - */ - int vertexIndex[3]; - - inline bool containsVertex(int v) const { - return contains(vertexIndex, 3, v); - } - - /** - Edge indices in counter-clockwise order. Edges are - undirected, so it is important to know which way - each edge is pointing in a face. This is encoded - using negative indices. - - If edgeIndex[i] >= 0 then this face - contains the directed edge - between vertex indices - edgeArray[face.edgeIndex[i]].vertexIndex[0] - and - edgeArray[face.edgeIndex[i]].vertexIndex[1]. - - If edgeIndex[i] < 0 then - ~edgeIndex[i] (i.e. the two's - complement of) is used and this face contains the directed - edge between vertex indices - edgeArray[~face.edgeIndex[i]].vertexIndex[0] - and - edgeArray[~face.edgeIndex[i]].vertexIndex[1]. - - Degenerate faces may include the same edge multiple times. - */ - // Temporarily takes on the value Face::NONE during adjacency - // computation to indicate an edge that has not yet been assigned. - int edgeIndex[3]; - - inline bool containsEdge(int e) const { - if (e < 0) { - e = ~e; - } - return contains(edgeIndex, 3, e) || contains(edgeIndex, 3, ~e); - } - - /** Contains the forward edge e if e >= 0 and the backward edge - ~e otherwise. */ - inline bool containsDirectedEdge(int e) const { - return contains(edgeIndex, 3, e); - } - }; - - - /** Oriented, indexed edge */ - class Edge { - public: - Edge(); - - /** Degenerate edges may include the same vertex times. */ - int vertexIndex[2]; - - inline bool containsVertex(int v) const { - return contains(vertexIndex, 2, v); - } - - /** - The edge is directed forward in face 0 - backward in face 1. Face index of MeshAlg::Face::NONE - indicates a boundary (a.k.a. crack, broken) edge. - */ - int faceIndex[2]; - - /** Returns true if f is contained in the faceIndex array in either slot. - To see if it is forward in that face, just check edge.faceIndex[0] == f.*/ - inline bool inFace(int f) const { - return contains(faceIndex, 2, f); - } - - /** - Returns true if either faceIndex is NONE. - */ - inline bool boundary() const { - return (faceIndex[0] == Face::NONE) || - (faceIndex[1] == Face::NONE); - } - - /** - Returns the reversed edge. - */ - inline Edge reverse() const { - Edge e; - e.vertexIndex[0] = vertexIndex[1]; - e.vertexIndex[1] = vertexIndex[0]; - e.faceIndex[0] = faceIndex[1]; - e.faceIndex[1] = faceIndex[0]; - return e; - } - }; - - - /** - Convenient for passing around the per-vertex data that changes under - animation. The faces and edges are needed to interpret - these values. - */ - class Geometry { - public: - /** Vertex positions */ - Array vertexArray; - - /** Vertex normals */ - Array normalArray; - - /** - Assignment is optimized using SSE. - */ - Geometry& operator=(const Geometry& src); - - void clear() { - vertexArray.clear(); - normalArray.clear(); - } - }; - - /** - Given a set of vertices and a set of indices for traversing them - to create triangles, computes other mesh properties. - - Colocated vertices are treated as separate. To have - colocated vertices collapsed (necessary for many algorithms, - like shadowing), weld the mesh before computing adjacency. - - Recent change: In version 6.00, colocated vertices were automatically - welded by this routine and degenerate faces and edges were removed. That - is no longer the case. - - Where two faces meet, there are two opposite directed edges. These - are collapsed into a single bidirectional edge in the edgeArray. - If four faces meet exactly at the same edge, that edge will appear - twice in the array, and so on. If an edge is a boundary of the mesh - (i.e. if the edge has only one adjacent face) it will appear in the - array with one face index set to MeshAlg::Face::NONE. - - @param vertexGeometry %Vertex positions to use when deciding colocation. - @param indexArray Order to traverse vertices to make triangles - @param faceArray Output - @param edgeArray Output. Sorted so that boundary edges are at the end of the array. - @param vertexArray Output - */ - static void computeAdjacency( - const Array& vertexGeometry, - const Array& indexArray, - Array& faceArray, - Array& edgeArray, - Array& vertexArray); - - /** - @deprecated Use the other version of computeAdjacency, which takes Array. - @param facesAdjacentToVertex Output adjacentFaceArray[v] is an array of - indices for faces touching vertex index v - */ - static void computeAdjacency( - const Array& vertexArray, - const Array& indexArray, - Array& faceArray, - Array& edgeArray, - Array< Array >& facesAdjacentToVertex); - - /** - Computes some basic mesh statistics including: min, max mean and median, - edge lengths; and min, mean, median, and max face area. - - @param vertexArray %Vertex positions to use when deciding colocation. - @param indexArray Order to traverse vertices to make triangles - @param minEdgeLength Minimum edge length - @param meanEdgeLength Mean edge length - @param medianEdgeLength Median edge length - @param maxEdgeLength Max edge length - @param minFaceArea Minimum face area - @param meanFaceArea Mean face area - @param medianFaceArea Median face area - @param maxFaceArea Max face area - */ - static void computeAreaStatistics( - const Array& vertexArray, - const Array& indexArray, - double& minEdgeLength, - double& meanEdgeLength, - double& medianEdgeLength, - double& maxEdgeLength, - double& minFaceArea, - double& meanFaceArea, - double& medianFaceArea, - double& maxFaceArea); - -private: - - /** Helper for weldAdjacency */ - static void weldBoundaryEdges( - Array& faceArray, - Array& edgeArray, - Array& vertexArray); - -public: - - /** - Computes tangent and binormal vectors, - which provide a (mostly) consistent - parameterization over the surface for - effects like bump mapping. In the resulting coordinate frame, - T = x (varies with texture s coordinate), B = y (varies with negative texture t coordinate), - and N = z for a right-handed coordinate frame. If a billboard is vertical on the screen - in view of the camera, the tangent space matches the camera's coordinate frame. - - The vertex, texCoord, tangent, and binormal - arrays are parallel arrays. - - The resulting tangent and binormal might not be exactly - perpendicular to each other. They are guaranteed to - be perpendicular to the normal. - - @cite Max McGuire - */ - static void computeTangentSpaceBasis( - const Array& vertexArray, - const Array& texCoordArray, - const Array& vertexNormalArray, - const Array& faceArray, - Array& tangent, - Array& binormal); - - /** @deprecated */ - static void computeNormals( - const Array& vertexArray, - const Array& faceArray, - const Array< Array >& adjacentFaceArray, - Array& vertexNormalArray, - Array& faceNormalArray); - - /** - Vertex normals are weighted by the area of adjacent faces. - Nelson Max showed this is superior to uniform weighting for - general meshes in jgt. - - @param vertexNormalArray Output. Unit length - @param faceNormalArray Output. Degenerate faces produce zero magnitude normals. Unit length - @see weld - */ - static void computeNormals( - const Array& vertexGeometry, - const Array& faceArray, - const Array& vertexArray, - Array& vertexNormalArray, - Array& faceNormalArray); - - /** Computes unit length normals in place using the other computeNormals methods. - If you already have a face array use another method; it will be faster. - @see weld*/ - static void computeNormals( - Geometry& geometry, - const Array& indexArray); - - /** - Computes face normals only. Significantly faster (especially if - normalize is false) than computeNormals. - @see weld - */ - static void computeFaceNormals( - const Array& vertexArray, - const Array& faceArray, - Array& faceNormals, - bool normalize = true); - - /** - Classifies each face as a backface or a front face relative - to the observer point P (which is at infinity when P.w = 0). - A face with normal exactly perpendicular to the observer vector - may be classified as either a front or a back face arbitrarily. - */ - static void identifyBackfaces( - const Array& vertexArray, - const Array& faceArray, - const Vector4& P, - Array& backface); - - /** A faster version of identifyBackfaces for the case where - face normals have already been computed */ - static void identifyBackfaces( - const Array& vertexArray, - const Array& faceArray, - const Vector4& P, - Array& backface, - const Array& faceNormals); - - /** - Welds nearby and colocated elements of the oldVertexArray together so that - newVertexArray contains no vertices within radius of one another. - Every vertex in newVertexPositions also appears in oldVertexPositions. - This is useful for downsampling meshes and welding cracks created by artist errors - or numerical imprecision. - - The two integer arrays map indices back and forth between the arrays according to: -

-     oldVertexArray[toOld[ni]] == newVertexArray[ni]
-     oldVertexArray[oi] == newVertexArray[toNew[ni]]
-     
- - Note that newVertexPositions is never longer than oldVertexPositions - and is shorter when vertices are welded. - - Welding with a large radius will effectively compute a lower level of detail for - the mesh. - - The welding method runs in roughly linear time in the length of oldVertexArray-- - a uniform spatial grid is used to achieve nearly constant time vertex collapses - for uniformly distributed vertices. - - It is sometimes desirable to keep the original vertex ordering but - identify the unique vertices. The following code computes - array canonical s.t. canonical[v] = first occurance of - a vertex near oldVertexPositions[v] in oldVertexPositions. - -
-        Array canonical(oldVertexPositions.size()), toNew, toOld;
-        computeWeld(oldVertexPositions, Array(), toNew, toOld, radius);
-        for (int v = 0; v < canonical.size(); ++v) {
-            canonical[v] = toOld[toNew[v]];
-        }
-     
- - See also G3D::MeshAlg::weldAdjacency. - - @cite The method is that described as the 'Grouper' in Baum, Mann, Smith, and Winget, - Making Radiosity Usable: Automatic Preprocessing and Meshing Techniques for - the Generation of Accurate Radiosity Solutions, Computer Graphics vol 25, no 4, July 1991. - - @deprecated Use weld. - */ - static void computeWeld( - const Array& oldVertexPositions, - Array& newVertexPositions, - Array& toNew, - Array& toOld, - double radius = fuzzyEpsilon); - - /** - Modifies the face, edge, and vertex arrays in place so that - colocated (within radius) vertices are treated as identical. - Note that the vertexArray and corresponding geometry will - contain elements that are no longer used. In the vertexArray, - these elements are initialized to MeshAlg::Vertex() but not - removed (because removal would change the indexing). - - This is a good preprocessing step for algorithms that are only - concerned with the shape of a mesh (e.g. cartoon rendering, fur, shadows) - and not the indexing of the vertices. - - Use this method when you have already computed adjacency information - and want to collapse colocated vertices within that data without - disturbing the actual mesh vertices or indexing scheme. - - If you have not computed adjacency already, use MeshAlg::computeWeld - instead and compute adjacency information after welding. - - @deprecated Use weld. - - @param faceArray Mutated in place. Size is maintained (degenerate - faces are not removed). - @param edgeArray Mutated in place. May shrink if boundary edges - are welded together. - @param vertexArray Mutated in place. Size is maintained (duplicate - vertices contain no adjacency info). - */ - static void weldAdjacency( - const Array& originalGeometry, - Array& faceArray, - Array& edgeArray, - Array& vertexArray, - double radius = fuzzyEpsilon); - - - /** - Counts the number of edges (in an edge array returned from - MeshAlg::computeAdjacency) that have only one adjacent face. - */ - static int countBoundaryEdges(const Array& edgeArray); - - - /** - Generates an array of integers from start to start + n - 1 that have run numbers - in series then omit the next skip before the next run. Useful for turning - a triangle list into an indexed face set. - - Example: -
-       createIndexArray(10, x);
-       // x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
-
-       createIndexArray(5, x, 2);
-       // x = [2, 3, 4, 5, 6, 7] 
-
-       createIndexArray(6, x, 0, 2, 1);
-       // x = [0, 1, 3, 4, 6, 7]
-     
- */ - static void createIndexArray( - int n, - Array& array, - int start = 0, - int run = 1, - int skip = 0); - - /** - Computes a conservative, near-optimal axis aligned bounding box and sphere. - - @cite The bounding sphere uses the method from J. Ritter. An effcient bounding sphere. In Andrew S. Glassner, editor, Graphics Gems. Academic Press, Boston, MA, 1990. - - */ - static void computeBounds(const Array& vertex, class AABox& box, class Sphere& sphere); - - /** Computes bounds for a subset of the vertices. It is ok if vertices appear more than once in the index array. */ - static void computeBounds(const Array& vertex, const Array& index, class AABox& box, class Sphere& sphere); - - /** - In debug mode, asserts that the adjacency references between the - face, edge, and vertex array are consistent. - */ - static void debugCheckConsistency( - const Array& faceArray, - const Array& edgeArray, - const Array& vertexArray); - - /** - Generates a unit square in the X-Z plane composed of a grid of wCells x hCells - squares and then transforms it by xform. - - @param vertex Output vertices - @param texCoord Output texture coordinates - @param index Output triangle list indices - @param textureScale Lower-right texture coordinate - @param spaceCentered If true, the coordinates generated are centered at the origin before the transformation. - @param twoSided If true, matching top and bottom planes are generated. - \param elevation If non-NULL, values from this image are used as elevations. Apply an \a xform to adjust the scale - */ - static void generateGrid( - Array& vertex, - Array& texCoord, - Array& index, - int wCells = 10, - int hCells = 10, - const Vector2& textureScale = Vector2(1,1), - bool spaceCentered = true, - bool twoSided = true, - const CoordinateFrame& xform = CoordinateFrame(), - const Image1::Ref& elevation = NULL); - - /** Converts quadlist (QUADS), - triangle fan (TRIANGLE_FAN), - tristrip(TRIANGLE_STRIP), and quadstrip (QUAD_STRIP) indices into - triangle list (TRIANGLES) indices and appends them to outIndices. */ - template - static void toIndexedTriList( - const Array& inIndices, - MeshAlg::Primitive inType, - Array& outIndices) { - - debugAssert( - inType == PrimitiveType::TRIANGLE_STRIP || - inType == PrimitiveType::TRIANGLE_FAN || - inType == PrimitiveType::QUADS || - inType == PrimitiveType::QUAD_STRIP); - - const int inSize = inIndices.size(); - - switch(inType) { - case PrimitiveType::TRIANGLE_FAN: - { - debugAssert(inSize >= 3); - - int N = outIndices.size(); - outIndices.resize(N + (inSize - 2) * 3); - - for (IndexType i = 1, outIndex = N; i <= (inSize - 2); ++i, outIndex += 3) { - outIndices[outIndex] = inIndices[0]; - outIndices[outIndex + 1] = inIndices[i]; - outIndices[outIndex + 2] = inIndices[i + 1]; - } - - break; - } - - case PrimitiveType::TRIANGLE_STRIP: - { - debugAssert(inSize >= 3); - - int N = outIndices.size(); - outIndices.resize(N + (inSize - 2) * 3); - - bool atEven = false; - for (IndexType i = 0, outIndex = N; i <= (inSize - 2); ++i, outIndex += 3) { - if (atEven) { - outIndices[outIndex] = inIndices[i + 1]; - outIndices[outIndex + 1] = inIndices[i]; - outIndices[outIndex + 2] = inIndices[i + 2]; - atEven = false; - } else { - outIndices[outIndex] = inIndices[i]; - outIndices[outIndex + 1] = inIndices[i + 1]; - outIndices[outIndex + 2] = inIndices[i + 2]; - atEven = true; - } - } - - break; - } - - case PrimitiveType::QUADS: - { - debugAssert(inIndices.size() >= 4); - - int N = outIndices.size(); - outIndices.resize(N + (inSize / 4) * 3); - - for (IndexType i = 0, outIndex = N; i <= (inSize - 4); i += 4, outIndex += 6) { - outIndices[outIndex] = inIndices[i]; - outIndices[outIndex + 1] = inIndices[i + 1]; - outIndices[outIndex + 2] = inIndices[i + 3]; - outIndices[outIndex + 3] = inIndices[i + 1]; - outIndices[outIndex + 4] = inIndices[i + 2]; - outIndices[outIndex + 5] = inIndices[i + 3]; - } - - break; - } - - case PrimitiveType::QUAD_STRIP: - { - debugAssert(inIndices.size() >= 4); - - int N = outIndices.size(); - outIndices.resize(N + (inSize - 2) * 3); - - for (IndexType i = 0, outIndex = N; i <= (inSize - 2); i += 2, outIndex += 6) { - outIndices[outIndex] = inIndices[i]; - outIndices[outIndex + 1] = inIndices[i + 1]; - outIndices[outIndex + 2] = inIndices[i + 2]; - outIndices[outIndex + 3] = inIndices[i + 2]; - outIndices[outIndex + 4] = inIndices[i + 1]; - outIndices[outIndex + 5] = inIndices[i + 3]; - } - break; - } - default: - alwaysAssertM(false, "Illegal argument"); - } - } - -protected: - - /** - Helper for computeAdjacency. If a directed edge with index e already - exists from i0 to i1 then e is returned. If a directed edge with index e - already exists from i1 to i0, ~e is returned (the complement) and - edgeArray[e] is set to f. Otherwise, a new edge is created from i0 to i1 - with first face index f and its index is returned. - - @param vertexArray Vertex positions to use when deciding colocation. - - @param area Area of face f. When multiple edges of the same direction - are found between the same vertices (usually because of degenerate edges) - the face with larger area is kept in the edge table. - */ - static int findEdgeIndex( - const Array& vertexArray, - Array& geometricEdgeArray, - int i0, int i1, int f, double area); -}; -} -#endif - diff --git a/externals/g3dlite/G3D/MeshBuilder.h b/externals/g3dlite/G3D/MeshBuilder.h deleted file mode 100644 index 9920d59d7d3..00000000000 --- a/externals/g3dlite/G3D/MeshBuilder.h +++ /dev/null @@ -1,82 +0,0 @@ -/** - @file MeshBuilder.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2002-02-27 - @edited 2004-10-04 - */ -#ifndef G3D_MESHBUILDER_H -#define G3D_MESHBUILDER_H - -#include "G3D/platform.h" -#include "G3D/Array.h" -#include "G3D/Vector3.h" -#include "G3D/Triangle.h" - -namespace G3D { - -/** - Allows creation of optimized watertight meshes from unoptimized polygon soups. - See also G3D::MeshAlg for algorithms that operate on the output. - */ -class MeshBuilder { -public: - - /** - Set setWeldRadius to AUTO_WELD to weld vertices closer than 1/2 - the smallest edge length in a model. - */ - enum {AUTO_WELD = -100}; - -private: - /** Indices of vertices in or near a grid cell. */ - typedef Array List; - - std::string name; - - /** - All of the triangles, as a long triangle list. - */ - Array triList; - - void centerTriList(); - void computeBounds(Vector3& min, Vector3& max); - - bool _twoSided; - - /** Collapse radius */ - double close; - -public: - - inline MeshBuilder(bool twoSided = false) : _twoSided(twoSided), close(AUTO_WELD) {} - - /** Writes the model to the arrays, which can then be used with - G3D::IFSModel::save and G3D::MeshAlg */ - void commit(std::string& name, Array& indexArray, Array& vertexArray); - - /** - Adds a new triangle to the model. (Counter clockwise) - */ - void addTriangle(const Vector3& a, const Vector3& b, const Vector3& c); - - /** - Adds two new triangles to the model. (Counter clockwise) - */ - void addQuad(const Vector3& a, const Vector3& b, const Vector3& c, const Vector3& d); - - void addTriangle(const Triangle& t); - - void setName(const std::string& n); - - /** Vertices within this distance are considered identical. - Use AUTO_WELD (the default) to have the distance be a function of the model size.*/ - void setWeldRadius(double r) { - close = r; - } -}; - -} // namespace - -#endif diff --git a/externals/g3dlite/G3D/NetAddress.h b/externals/g3dlite/G3D/NetAddress.h deleted file mode 100644 index 8ed20a06690..00000000000 --- a/externals/g3dlite/G3D/NetAddress.h +++ /dev/null @@ -1,132 +0,0 @@ -#ifndef G3D_NETADDRESS_H -#define G3D_NETADDRESS_H - -#include "G3D/platform.h" -#include "G3D/Table.h" - -/** These control the version of Winsock used by G3D. - Version 2.0 is standard for G3D 6.09 and later. - Version 1.1 is standard for G3D 6.08 and earlier. - */ -#define G3D_WINSOCK_MAJOR_VERSION 2 -#define G3D_WINSOCK_MINOR_VERSION 0 - -#ifdef G3D_WIN32 -# if (G3D_WINSOCK_MAJOR_VERSION == 2) -# include -# elif (G3D_WINSOCK_MAJOR_VERSION == 1) -# include -# endif -#else -# include -# include -# include -# ifndef SOCKADDR_IN -# define SOCKADDR_IN struct sockaddr_in -# endif -# ifndef SOCKET -# define SOCKET int -# endif -#endif - -#include "G3D/g3dmath.h" - -namespace G3D { - -class NetAddress { -private: - friend class NetworkDevice; - friend class LightweightConduit; - friend class ReliableConduit; - - /** Host byte order */ - void init(uint32 host, uint16 port); - void init(const std::string& hostname, uint16 port); - NetAddress(const SOCKADDR_IN& a); - NetAddress(const struct in_addr& addr, uint16 port = 0); - - SOCKADDR_IN addr; - -public: - /** - In host byte order - */ - NetAddress(uint32 host, uint16 port = 0); - - /** - @param port Specified in host byte order (i.e., don't worry about endian issues) - */ - NetAddress(const std::string& hostname, uint16 port); - - /** - @param hostnameAndPort in the form "hostname:port" or "ip:port" - */ - NetAddress(const std::string& hostnameAndPort); - - /** - @deprecated Use G3D::NetworkDevice::broadcastAddressArray() - - @brief Creates a UDP broadcast address for use with a - G3D::LightweightConduit. - - UDP broadcast allows one machine to send a packet to all machines - on the same local network. The IP portion of the address is - 0xFFFFFFFF, which indicates "broadcast" to the underlying socket - API. This feature is not available with the connection-based TCP - protocol abstracted by G3D::ReliableConduit; use multisend - instead. - */ - static NetAddress broadcastAddress(uint16 port); - - NetAddress(); - - void serialize(class BinaryOutput& b) const; - void deserialize(class BinaryInput& b); - - /** @brief Returns true if this is not an illegal address. */ - bool ok() const; - - /** @brief Returns a value in host format (i.e., don't worry about - endian issues) */ - inline uint32 ip() const { - return ntohl(addr.sin_addr.s_addr); - //return ntohl(addr.sin_addr.S_un.S_addr); - } - - inline uint16 port() const { - return ntohs(addr.sin_port); - } - - std::string ipString() const; - std::string toString() const; - -}; - -std::ostream& operator<<(std::ostream& os, const NetAddress&); - -} // namespace G3D - -template <> struct HashTrait { - static size_t hashCode(const G3D::NetAddress& key) { - return static_cast(key.ip() + (static_cast(key.port()) << 16)); - } -}; - -namespace G3D { - -/** - Two addresses may point to the same computer but be != because - they have different IP's. - */ -inline bool operator==(const NetAddress& a, const NetAddress& b) { - return (a.ip() == b.ip()) && (a.port() == b.port()); -} - - -inline bool operator!=(const NetAddress& a, const NetAddress& b) { - return !(a == b); -} - -} // namespace G3D - -#endif diff --git a/externals/g3dlite/G3D/NetworkDevice.h b/externals/g3dlite/G3D/NetworkDevice.h deleted file mode 100644 index ea3290cbc09..00000000000 --- a/externals/g3dlite/G3D/NetworkDevice.h +++ /dev/null @@ -1,738 +0,0 @@ -/** - @file NetworkDevice.h - - These classes abstract networking from the socket level to a - serialized messaging style that is more appropriate for games. The - performance has been tuned for sending many small messages. The - message protocol contains a header that prevents them from being used - with raw UDP/TCP (e.g. connecting to an HTTP server). - - LightweightConduit and ReliableConduits have different interfaces - because they have different semantics. You would never want to - interchange them without rewriting the surrounding code. - - NetworkDevice creates conduits because they need access to a global - log pointer and because I don't want non-reference counted conduits - being created. - - Be careful with threads and reference counting. The reference - counters are not threadsafe, and are also not updated correctly if a - thread is explicitly killed. Since the conduits will be passed by - const XConduitRef& most of the time this doesn't appear as a major - problem. With non-blocking conduits, you should need few threads - anyway. - - LightweightConduits preceed each message with a 4-byte host order - unsigned integer that is the message type. This does not appear in - the message serialization/deserialization. - - ReliableConduits preceed each message with two 4-byte host order - unsigned integers. The first is the message type and the second - indicates the length of the rest of the data. The size does not - include the size of the header itself. The minimum message is 9 - bytes:a 4-byte type, a 4-byte header equal to "1", and one byte of data. - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - @created 2002-11-22 - @edited 2006-11-25 - */ - -#ifndef G3D_NETWORKDEVICE_H -#define G3D_NETWORKDEVICE_H - -#include "G3D/platform.h" -#include "G3D/NetAddress.h" - -#include -#include -#include "G3D/g3dmath.h" - -#include "G3D/ReferenceCount.h" -#include "G3D/Array.h" -#include "G3D/BinaryOutput.h" - -namespace G3D { - -class TextOutput; - -class Conduit : public ReferenceCountedObject { -protected: - friend class NetworkDevice; - friend class NetListener; - - uint64 mSent; - uint64 mReceived; - uint64 bSent; - uint64 bReceived; - - SOCKET sock; - - /** - Used for serialization. One per socket - to make this threadsafe. - */ - BinaryOutput binaryOutput; - - Conduit(); - -public: - - virtual ~Conduit(); - uint64 bytesSent() const; - uint64 messagesSent() const; - uint64 bytesReceived() const; - uint64 messagesReceived() const; - - /** - If true, receive will return true. - */ - virtual bool messageWaiting(); - - /** - Returns the type of the waiting message (i.e. the type supplied - with send). The return value is zero when there is no message - waiting. - - One way to use this is to have a Table mapping message types to - pre-allocated subclasses so receiving looks like: - -
-         // My base class for messages.
-         class Message {
-             virtual void serialize(BinaryOutput&) const;
-             virtual void deserialize(BinaryInput&);
-             virtual void process() = 0;
-         };
-
-         Message* m = table[conduit->waitingMessageType()];
-         conduit->receive(m);
-         m->process();
-     
- - Another is to simply switch on the message type: - -
-         switch (conduit->waitingMessageType()) {
-         case 0:
-            // No message
-            break;
-
-         case ENTITY_SPAWN_MSG:
-            {
-               EntitySpawnMsg m;
-               condiut->receive(m);
-               spawnEntity(m.id, m.position, m.modelID);
-            }
-            break;
-            ...
-         }
-      
- */ - virtual uint32 waitingMessageType() = 0; - - /** Returns true if the connection is ok. */ - bool ok() const; -}; - -typedef ReferenceCountedPointer ReliableConduitRef; - -#ifdef __GNUC__ -// Workaround for a known bug in gcc 4.x where htonl produces -// a spurrious warning. -// http://gcc.gnu.org/ml/gcc-bugs/2005-10/msg03270.html -uint32 gcchtonl(uint32); -#endif - -// Messaging and stream APIs must be supported on a single class because -// sometimes an application will switch modes on a single socket. For -// example, when transferring 3D level geometry during handshaking with -// a game server. -/** - A conduit that guarantees messages will arrive, intact and in order. - Create on the client using NetworkDevice::createReliableConduit and - on the server using NetListener::waitForConnection. Set the reference - counted pointer to NULL to disconnect. - - To construct a ReliableConduit: -
    -
  1. Create a G3D::NetworkDevice (if you are using G3D::GApp, it creates - one for you) on the client and on the server. -
  2. On the server, create a G3D::NetListener using - G3D::NetworkDevice::createListener -
  3. On the server, invoke G3D::NetListener::waitForConnection. -
  4. On the client, call G3D::NetworkDevice::createReliableConduit. - You will need the server's G3D::NetAddress. Consider using - G3D::Discovery::Client to find it via broadcasting. -
- - */ -class ReliableConduit : public Conduit { -private: - friend class NetworkDevice; - friend class NetListener; - - enum State {RECEIVING, HOLDING, NO_MESSAGE} state; - - NetAddress addr; - - /** - Type of the incoming message. - */ - uint32 messageType; - - /** - Total size of the incoming message (read from the header). - */ - uint32 messageSize; - - /** Shared buffer for receiving messages. */ - void* receiveBuffer; - - /** Total size of the receiveBuffer. */ - size_t receiveBufferTotalSize; - - /** Size occupied by the current message... so far. This will be - equal to messageSize when the whole message has arrived. - */ - size_t receiveBufferUsedSize; - - ReliableConduit(const NetAddress& addr); - - ReliableConduit(const SOCKET& sock, - const NetAddress& addr); - - template static void serializeMessage - (uint32 t, const T& m, BinaryOutput& b) { - - b.writeUInt32(t); - - // Reserve space for the 4 byte size header - b.writeUInt32(0); - - size_t L = b.length(); - m.serialize(b); - if ((size_t)b.length() == L) { - // No data was created by serialization. - // We need to send at least one byte because receive assumes that - // a zero length message is an error. - b.writeUInt8(0xFF); - } - - uint32 len = b.size() - 8; - - // We send the length first to tell recv how much data to read. - // Here we abuse BinaryOutput a bit and write directly into - // its buffer, violating the abstraction. - // Note that we write to the second set of 4 bytes, which is - // the size field. - uint32* lenPtr = ((uint32*)b.getCArray()) + 1; - #if defined(__GNUC__) - *lenPtr = gcchtonl(len); - #else - *lenPtr = htonl(len); - #endif - } - - - void sendBuffer(const BinaryOutput& b); - - /** Accumulates whatever part of the message (not the header) is - still waiting on the socket into the receiveBuffer during - state = RECEIVING mode. Closes the socket if anything goes - wrong. When receiveBufferUsedSize == messageSize, the entire - message has arrived. */ - void receiveIntoBuffer(); - - /** Receives the messageType and messageSize from the socket. */ - void receiveHeader(); - -public: - - /** - Client invokes this to connect to a server. The call blocks until the - conduit is opened. The conduit will not be ok() if it fails. - */ - static ReliableConduitRef create(const NetAddress& address); - - /** Closes the socket. */ - ~ReliableConduit(); - - - // The message is actually copied from the socket to an internal buffer during - // this call. Receive only deserializes. - virtual bool messageWaiting(); - - /** - Serializes the message and schedules it to be sent as soon as possible, - and then returns immediately. The message can be any class with - a serialize and deserialize method. On the receiving side, - use G3D::ReliableConduit::waitingMessageType() to detect the incoming - message and then invoke G3D::ReliableConduit::receive(msg) where msg - is of the same class as the message that was sent. - - The actual data sent across the network is preceeded by the - message type and the size of the serialized message as a 32-bit - integer. The size is sent because TCP is a stream protocol and - doesn't have a concept of discrete messages. - */ - template inline void send(uint32 type, const T& message) { - binaryOutput.reset(); - serializeMessage(type, message, binaryOutput); - sendBuffer(binaryOutput); - } - - /** Sends an empty message with the given type. Useful for sending - commands that have no parameters. */ - void send(uint32 type); - - /** Send the same message to a number of conduits. Useful for sending - data from a server to many clients (only serializes once). */ - template - inline static void multisend( - const Array& array, - uint32 type, - const T& m) { - - if (array.size() > 0) { - array[0]->binaryOutput.reset(); - serializeMessage(type, m, array[0]->binaryOutput); - - for (int i = 0; i < array.size(); ++i) { - array[i]->sendBuffer(array[0]->binaryOutput); - } - } - } - - virtual uint32 waitingMessageType(); - - /** - If a message is waiting, deserializes the waiting message into - message and returns true, otherwise returns false. You can - determine the type of the message (and therefore, the class - of message) using G3D::ReliableConduit::waitingMessageType(). - */ - template inline bool receive(T& message) { - if (! messageWaiting()) { - return false; - } - - debugAssert(state == HOLDING); - // Deserialize - BinaryInput b((uint8*)receiveBuffer, receiveBufferUsedSize, G3D_LITTLE_ENDIAN, BinaryInput::NO_COPY); - message.deserialize(b); - - // Don't let anyone read this message again. We leave the buffer - // allocated for the next caller, however. - receiveBufferUsedSize = 0; - state = NO_MESSAGE; - messageType = 0; - messageSize = 0; - - // Potentially read the next message. - messageWaiting(); - - return true; - } - - /** Removes the current message from the queue. */ - inline void receive() { - if (! messageWaiting()) { - return; - } - receiveBufferUsedSize = 0; - state = NO_MESSAGE; - messageType = 0; - messageSize = 0; - - // Potentially read the next message. - messageWaiting(); - } - - NetAddress address() const; -}; - - -typedef ReferenceCountedPointer LightweightConduitRef; - -/** - Provides fast but unreliable transfer of messages. On a LAN, - LightweightConduit will probably never drop messages but you - might get your messages out of order. On an internet - connection it might drop messages altogether. Messages are never - corrupted, however. LightweightConduit requires a little less setup - and overhead than ReliableConduit. ReliableConduit guarantees - message delivery and order but requires a persistent connection. - - To set up a LightweightConduit (assuming you have already made - subclasses of G3D::NetMessage based on your application's - pcommunication protocol): - -[Server Side] -
    -
  1. Call LightweightConduit::create(port, true, false), -where port is the port on which you will receive messages. - -
  2. Poll LightweightConduit::messageWaiting from your main loop. When -it is true (or, equivalently, when LightweightConduit::waitingMessageType -is non-zero) there is an incoming message. - -
  3. To read the incoming message, call LightweightConduit::receive with -the appropriate class type, which mist have a deserialize method. -LightweightConduit::waitingMessageType tells you what class is -needed (you make up your own message constants for your program; numbers -under 1000 are reserved for G3D's internal use). - -
  4. When done, simply set the G3D::LightweightConduitRef to NULL or let -it go out of scope and the conduit cleans itself up automatically. -
- -[Client Side] -
    -
  1. Call G3D::LightweightConduit::create(). If you will -broadcast to all servers on a LAN, set the third optional argument to -true (the default is false for no broadcast). You can also set up the -receive port as if it was a server to send and receive from a single -LightweightConduit. - -
  2. To send, call G3D::LightweightConduit::send with the target address -and a pointer to an instance of the message you want to send. - -
  3. When done, simply set the G3D::LightweightConduitRef to NULL or let -it go out of scope and the conduit cleans itself up automatically. - -
- */ -class LightweightConduit : public Conduit { -private: - friend class NetworkDevice; - - /** - True when waitingForMessageType has read the message - from the network into messageType/messageStream. - */ - bool alreadyReadMessage; - - /** - Origin of the received message. - */ - NetAddress messageSender; - - /** - The type of the last message received. - */ - uint32 messageType; - - /** - The message received (the type has already been read off). - */ - Array messageBuffer; - - LightweightConduit(uint16 receivePort, bool enableReceive, bool enableBroadcast); - - void sendBuffer(const NetAddress& a, BinaryOutput& b); - - /** Maximum transmission unit (packet size in bytes) for this socket. - May vary between sockets. */ - int MTU; - - - template - void serializeMessage( - uint32 type, - const T& m, - BinaryOutput& b) const { - - debugAssert(type != 0); - b.writeUInt32(type); - m.serialize(b); - b.writeUInt32(1); - - debugAssertM(b.size() < MTU, - format("This LightweightConduit is limited to messages of " - "%d bytes (Ethernet hardware limit; this is the " - "'UDP MTU')", maxMessageSize())); - - if (b.size() >= MTU) { - throw LightweightConduit::PacketSizeException( - format("This LightweightConduit is limited to messages of " - "%d bytes (Ethernet hardware limit; this is the " - "'UDP MTU')", maxMessageSize()), - b.size() - 4, // Don't count the type header - maxMessageSize()); - } - } - -public: - - static LightweightConduitRef create(uint16 receivePort, bool enableReceive, bool enableBroadcast); - - class PacketSizeException { - public: - std::string message; - int serializedPacketSize; - int maxMessageSize; - - inline PacketSizeException(const std::string& m, int s, int b) : - message(m), - serializedPacketSize(s), - maxMessageSize(b) {} - }; - - /** Closes the socket. */ - ~LightweightConduit(); - - /** The maximum length of a message that can be sent - (G3D places a small header at the front of each UDP packet; - this is already taken into account by the value returned). - */ - inline int maxMessageSize() const { - return MTU - 4; - } - - - template inline void send(const NetAddress& a, uint32 type, const T& msg) { - binaryOutput.reset(); - serializeMessage(type, msg, binaryOutput); - sendBuffer(a, binaryOutput); - } - - /** Send the same message to multiple addresses (only serializes once). - Useful when server needs to send to a known list of addresses - (unlike direct UDP broadcast to all addresses on the subnet) */ - template inline void send(const Array& a, uint32 type, const T& m) { - binaryOutput.reset(); - serializeMessage(type, m, binaryOutput); - - for (int i = 0; i < a.size(); ++i) { - sendBuffer(a[i], binaryOutput); - } - } - - bool receive(NetAddress& sender); - - template inline bool receive(NetAddress& sender, T& message) { - bool r = receive(sender); - if (r) { - BinaryInput b((messageBuffer.getCArray() + 4), - messageBuffer.size() - 4, - G3D_LITTLE_ENDIAN, BinaryInput::NO_COPY); - message.deserialize(b); - } - - return r; - } - - inline bool receive() { - static NetAddress ignore; - return receive(ignore); - } - - virtual uint32 waitingMessageType(); - - - virtual bool messageWaiting(); -}; - -/////////////////////////////////////////////////////////////////////////////// - -typedef ReferenceCountedPointer NetListenerRef; - -/** - Runs on the server listening for clients trying to make reliable connections. - */ -class NetListener : public ReferenceCountedObject { -private: - - friend class NetworkDevice; - - SOCKET sock; - - /** Port is in host byte order. */ - NetListener(uint16 port); - -public: - - static NetListenerRef create(const uint16 port); - - ~NetListener(); - - /** Block until a connection is received. Returns NULL if - something went wrong. */ - ReliableConduitRef waitForConnection(); - - /** True if a client is waiting (i.e. waitForConnection will - return immediately). */ - bool clientWaiting() const; - - bool ok() const; -}; - - -/////////////////////////////////////////////////////////////////////////////// - -/** - @brief Abstraction of network (socket) functionality. - - An abstraction over sockets that provides a message-based network - infrastructure optimized for sending many small (~500 bytes) messages. - All functions always return immediately. - - Create only one NetworkDevice per process (a WinSock restriction). - - NetworkDevice is technically not thread safe. However, as long as - you use different conduits on different threads (or lock conduits - before sending), you will encounter no problems sharing the single - NetworkDevice across multiple threads. That is, do not invoke the same - Conduit's send or receive method on two threads at once. - - This assumes that the underlying WinSock/BSD sockets implementation - is thread safe. That is not guaranteed, but in practice seems - to always be true (see - http://tangentsoft.net/wskfaq/intermediate.html#threadsafety) - -
- - IP networks use "network byte order" (big-endian) for - communicating integers. "Host byte order" is the endian-ness of - the local machine (typically little-endian; see - System::endian). The C functions htonl() and ntohl() convert 32-bit - values between these formats. G3D only ever exposes host byte order, - so programmers rarely need to be aware of the distinction. - - */ -class NetworkDevice { -public: - - /** @brief Description of an ethernet or wireless ethernet adapter.*/ - class EthernetAdapter { - public: - /** Reverse-DNS of the ip address.*/ - std::string hostname; - - /** Name of the adapter */ - std::string name; - - /** IP address in host byte order.*/ - uint32 ip; - - /** Subnet mask in host byte order.*/ - uint32 subnet; - - /** UDP broadcast address in host byte order.*/ - uint32 broadcast; - - /** MAC (hardware) address, if known */ - uint8 mac[6]; - - EthernetAdapter(); - - /** Produces a text description of this adapter */ - void describe(TextOutput& t) const; - }; - -private: - - friend class Conduit; - friend class LightweightConduit; - friend class ReliableConduit; - friend class NetListener; - - bool initialized; - - Array m_adapterArray; - - /** Broadcast addresses available on this machine, - extracted from m_adapterArray.*/ - Array m_broadcastAddresses; - - /** Utility method. */ - void closesocket(SOCKET& sock) const; - - /** Utility method. Returns true on success.*/ - bool bind(SOCKET sock, const NetAddress& addr) const; - - /** The global instance */ - static NetworkDevice* s_instance; - - NetworkDevice(); - - bool init(); - - void _cleanup(); - - /** Called from init to update m_adapterArray and - m_broadcastAddresses. */ - void addAdapter(const EthernetAdapter& a); - -public: - - /** Prints an IP address to a string. - @param ip In host byte order.*/ - static std::string formatIP(uint32 ip); - - /** Prints a MAC address to a string. */ - static std::string formatMAC(const uint8 mac[6]); - - ~NetworkDevice(); - - /** Returns the available ethernet adapters for the current - machine that are online. Does not include the loopback adapter - for localhost.*/ - inline const Array& adapterArray() const { - return m_adapterArray; - } - - /** Returns the (unique) IP addresses for UDP broadcasting - extracted from adapterArray(). All are in host byte order. */ - inline const Array& broadcastAddressArray() const { - return m_broadcastAddresses; - } - - /** - Returns NULL if there was a problem initializing the network. - */ - static NetworkDevice* instance(); - - /** - Shuts down the network device (destroying the global instance). - */ - static void cleanup(); - - /** - Prints a human-readable description of this machine - to the text output stream. - */ - void describeSystem( - TextOutput& t); - - void describeSystem( - std::string& s); - - /** Returns the name (or one of the names) of this computer */ - std::string localHostName() const; - - /** There is often more than one address for the local host. This - returns all of them. - @deprecated Use adapterArray() - */ - void localHostAddresses(Array& array) const; -}; - - -#ifdef __GNUC__ -inline uint32 gcchtonl(uint32 x) { - // This pragma fools gcc into surpressing all error messages, - // including the bogus one that it creates for htonl -# pragma GCC system_header - return htonl(x); -} -#endif - -} // G3D namespace - -#ifndef _WIN32 -#undef SOCKADDR_IN -#undef SOCKET -#endif - -#endif diff --git a/externals/g3dlite/G3D/ParseError.h b/externals/g3dlite/G3D/ParseError.h deleted file mode 100644 index f02948e3d29..00000000000 --- a/externals/g3dlite/G3D/ParseError.h +++ /dev/null @@ -1,59 +0,0 @@ -/** - @file ParseError.h - - @maintainer Morgan McGuire - - @created 2009-11-15 - @edited 2009-11-15 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ -#ifndef G3D_ParseError_h -#define G3D_ParseError_h - -#include "G3D/platform.h" -#include "G3D/g3dmath.h" -#include - -namespace G3D { - -/** Thrown by TextInput, Any, and other parsers on unexpected input. */ -class ParseError { -public: - enum {UNKNOWN = -1}; - - /** Empty means unknown */ - std::string filename; - - /** For a binary file, the location of the parse error. -1 if unknown.*/ - int64 byte; - - /** For a text file, the line number is the line number of start of token which caused the exception. 1 is - the first line of the file. -1 means unknown. Note that you can use - TextInput::Settings::startingLineNumberOffset to shift the effective line - number that is reported by that class. - */ - int line; - - /** Character number (in the line) of the start of the token which caused the - exception. 1 is the character in the line. May be -1 if unknown. - */ - int character; - - std::string message; - - ParseError() : byte(UNKNOWN), line(UNKNOWN), character(UNKNOWN) {} - - virtual ~ParseError() {} - - ParseError(const std::string& f, int l, int c, const std::string& m) : - filename (f), byte(UNKNOWN), line(l), character(c), message(m) {} - - ParseError(const std::string& f, int64 b, const std::string& m) : - filename (f), byte(b), line(UNKNOWN), character(UNKNOWN), message(m) {} -}; - -} - -#endif diff --git a/externals/g3dlite/G3D/PhysicsFrame.h b/externals/g3dlite/G3D/PhysicsFrame.h deleted file mode 100644 index a5a9305b83e..00000000000 --- a/externals/g3dlite/G3D/PhysicsFrame.h +++ /dev/null @@ -1,74 +0,0 @@ -/** - @file PhysicsFrame.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2002-07-08 - @edited 2006-01-10 -*/ - -#ifndef G3D_PHYSICSFRAME_H -#define G3D_PHYSICSFRAME_H - -#include "G3D/platform.h" -#include "G3D/Vector3.h" -#include "G3D/Matrix3.h" -#include "G3D/Quat.h" -#include "G3D/CoordinateFrame.h" -#include -#include - - -namespace G3D { - -/** - An RT transformation using a quaternion; suitable for - physics integration. - - This interface is in "Beta" and will change in the next release. - */ -class PhysicsFrame { -public: - - Quat rotation; - - /** - Takes object space points to world space. - */ - Vector3 translation; - - /** - Initializes to the identity frame. - */ - PhysicsFrame(); - - /** - Purely translational force - */ - PhysicsFrame(const Vector3& translation) : translation(translation) {} - - PhysicsFrame(const CoordinateFrame& coordinateFrame); - - /** Compose: create the transformation that is other followed by this.*/ - PhysicsFrame operator*(const PhysicsFrame& other) const; - - virtual ~PhysicsFrame() {} - - CoordinateFrame toCoordinateFrame() const; - - /** - Linear interpolation (spherical linear for the rotations). - */ - PhysicsFrame lerp( - const PhysicsFrame& other, - float alpha) const; - - void deserialize(class BinaryInput& b); - - void serialize(class BinaryOutput& b) const; - -}; - -} // namespace - -#endif diff --git a/externals/g3dlite/G3D/Plane.h b/externals/g3dlite/G3D/Plane.h deleted file mode 100644 index 360bcd2bc75..00000000000 --- a/externals/g3dlite/G3D/Plane.h +++ /dev/null @@ -1,161 +0,0 @@ -/** - @file Plane.h - - Plane class - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2001-06-02 - @edited 2004-07-18 -*/ - -#ifndef G3D_PLANE_H -#define G3D_PLANE_H - -#include "G3D/platform.h" -#include "G3D/Vector3.h" -#include "G3D/Vector4.h" -#include "G3D/debugAssert.h" - -namespace G3D { - -/** - An infinite 2D plane in 3D space. - */ -class Plane { -private: - - /** normal.Dot(x,y,z) = distance */ - Vector3 _normal; - float _distance; - - /** - Assumes the normal has unit length. - */ - Plane(const Vector3& n, float d) : _normal(n), _distance(d) { - } - -public: - - Plane() : _normal(Vector3::unitY()), _distance(0) { - } - - /** - Constructs a plane from three points. - */ - Plane( - const Vector3& point0, - const Vector3& point1, - const Vector3& point2); - - /** - Constructs a plane from three points, where at most two are - at infinity (w = 0, not xyz = inf). - */ - Plane( - Vector4 point0, - Vector4 point1, - Vector4 point2); - - /** - The normal will be unitized. - */ - Plane( - const Vector3& __normal, - const Vector3& point); - - static Plane fromEquation(float a, float b, float c, float d); - - Plane(class BinaryInput& b); - void serialize(class BinaryOutput& b) const; - void deserialize(class BinaryInput& b); - - virtual ~Plane() {} - - /** - Returns true if point is on the side the normal points to or - is in the plane. - */ - inline bool halfSpaceContains(Vector3 point) const { - // Clamp to a finite range for testing - point = point.clamp(Vector3::minFinite(), Vector3::maxFinite()); - - // We can get away with putting values *at* the limits of the float32 range into - // a dot product, since the dot product is carried out on float64. - return _normal.dot(point) >= _distance; - } - - /** - Returns true if point is on the side the normal points to or - is in the plane. - */ - inline bool halfSpaceContains(const Vector4& point) const { - if (point.w == 0) { - return _normal.dot(point.xyz()) > 0; - } else { - return halfSpaceContains(point.xyz() / point.w); - } - } - - /** - Returns true if point is on the side the normal points to or - is in the plane. Only call on finite points. Faster than halfSpaceContains. - */ - inline bool halfSpaceContainsFinite(const Vector3& point) const { - debugAssert(point.isFinite()); - return _normal.dot(point) >= _distance; - } - - /** - Returns true if the point is nearly in the plane. - */ - inline bool fuzzyContains(const Vector3 &point) const { - return fuzzyEq(point.dot(_normal), _distance); - } - - inline const Vector3& normal() const { - return _normal; - } - - /** - Returns distance from point to plane. Distance is negative if point is behind (not in plane in direction opposite normal) the plane. - */ - inline float distance(const Vector3& x) const { - return (_normal.dot(x) - _distance); - } - - inline Vector3 closestPoint(const Vector3& x) const { - return x + (_normal * (-distance(x))); - } - - /** Returns normal * distance from origin */ - Vector3 center() const { - return _normal * _distance; - } - - /** - Inverts the facing direction of the plane so the new normal - is the inverse of the old normal. - */ - void flip(); - - /** - Returns the equation in the form: - - normal.Dot(Vector3(x, y, z)) + d = 0 - */ - void getEquation(Vector3 &normal, double& d) const; - void getEquation(Vector3 &normal, float& d) const; - - /** - ax + by + cz + d = 0 - */ - void getEquation(double& a, double& b, double& c, double& d) const; - void getEquation(float& a, float& b, float& c, float& d) const; - - std::string toString() const; -}; - -} // namespace - -#endif diff --git a/externals/g3dlite/G3D/PointHashGrid.h b/externals/g3dlite/G3D/PointHashGrid.h deleted file mode 100644 index 0db9e677321..00000000000 --- a/externals/g3dlite/G3D/PointHashGrid.h +++ /dev/null @@ -1,917 +0,0 @@ -/** - @file PointHashGrid.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - @created 2008-07-01 - @edited 2009-05-28 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. -*/ -#ifndef G3D_PointHashGrid_h -#define G3D_PointHashGrid_h - -#include "G3D/platform.h" -#include "G3D/EqualsTrait.h" -#include "G3D/HashTrait.h" -#include "G3D/Vector3.h" -#include "G3D/Vector3int32.h" -#include "G3D/Array.h" -#include "G3D/Table.h" -#include "G3D/AABox.h" -#include "G3D/Sphere.h" -#include "G3D/SmallArray.h" - -namespace G3D { - -/** - Storage of data in a sparse 3D grid of point-based data. The - space cost for n elements is O(n). For data with - approximately uniform density (with respect to the radius hint), - the time cost of searching for neighbors is O(1). - - Value must be supported by a G3D::PositionTrait, - G3D::EqualsTrait, and G3D::HashFunc. overrides are provided for - common G3D classes like G3D::Vector3. -*/ -template, - class EqualsFunc = EqualsTrait, - class HashFunc = HashTrait > -class PointHashGrid { -private: - -#define ThisType PointHashGrid - - /** A value annotated with precomputed position and hash code.*/ - class Entry { - public: - Vector3 position; - Value value; - }; - - /** One cell of the grid. */ - typedef Array Cell; - typedef Table CellTable; - - /** The cube of +/-1 along each dimension. Initialized by initOffsetArray.*/ - Vector3int32 m_offsetArray[3*3*3]; - - /** Incremented every time the data structure is mutated. - Used by the iterators to determine if the data structure - has changed since iteration began. */ - int m_epoch; - - /** Extent of a cell along one dimension. */ - float m_cellWidth; - - /** 1.0 / cell width */ - float m_invCellWidth; - - /** Conservative bounds; the actual data may be smaller. */ - AABox m_bounds; - - /** Number of elements. */ - int m_size; - - /** Non-empty cells indexed by grid position. Actual 3D position is - position * m_cellWidth*/ - CellTable m_data; - - MemoryManager::Ref m_memoryManager; - - /** Intentionally unimplemented: prevent copy construction. */ - PointHashGrid(const ThisType&); - - - /** Intentionally unimplemented: prevent assignment. */ - PointHashGrid& operator=(const ThisType&); - - - /** Locate the cell and index within that cell containing v. Called by - remove() and contains(). */ - bool find(const Value& v, - Vector3int32& foundCellCoord, - Cell*& foundCell, - int& index) { - - Vector3 pos; - PosFunc::getPosition(v, pos); - - Vector3int32 cellCoord; - getCellCoord(pos, cellCoord); - for (int i = 0; i < 27; ++i) { - Vector3int32 c = cellCoord + m_offsetArray[i]; - Cell* cell = m_data.getPointer(c); - if (cell != NULL) { - // The cell exists - for (int j = 0; j < cell->size(); ++j) { - if (EqualsFunc::equals((*cell)[j].value, v)) { - foundCell = cell; - index = j; - foundCellCoord = c; - return true; - } - } - } - } - - // Not found - return false; - } - - /** Given a real-space position, returns the cell coord - containing it.*/ - inline void getCellCoord(const Vector3& pos, Vector3int32& cellCoord) const { - for (int a = 0; a < 3; ++a) { - cellCoord[a] = iFloor(pos[a] * m_invCellWidth); - } - } - - /** Initializes m_offsetArray. */ - void initOffsetArray() { - int i = 0; - Vector3int32 d; - for (d.x = -1; d.x <= +1; ++d.x) { - for (d.y = -1; d.y <= +1; ++d.y) { - for (d.z = -1; d.z <= +1; ++d.z) { - m_offsetArray[i] = d; - ++i; - } - } - } - - // Put (0, 0, 0) first, so that contains() is most likely to find - // the value quickly. - i = (1 * 3 + 1) * 3 + 1; - debugAssert(m_offsetArray[i] == Vector3int32(0,0,0)); - Vector3int32 temp = m_offsetArray[0]; - m_offsetArray[0] = m_offsetArray[i]; - m_offsetArray[i] = temp; - } - -public: - - /** - @param radiusHint the radius that will typically be used with - beginSphereIntersection and beginBoxIntersection. If two Values are equal, - their positions must be within this radius as well. - */ - PointHashGrid(float radiusHint, const MemoryManager::Ref& m = MemoryManager::create()) : m_size(0), m_memoryManager(m) { - initOffsetArray(); - m_data.clearAndSetMemoryManager(m_memoryManager); - - debugAssertM(radiusHint > 0, "Cell radius must be positive"); - m_cellWidth = radiusHint; - m_invCellWidth = 1.0f / m_cellWidth; - } - - /** - If radiusHint is negative, it is automatically chosen to put - about 5 values in each grid cell (which means about 27 * 5 - values for each beginIntersection call). - */ - PointHashGrid(const Array& init, float radiusHint = -1.0f, const MemoryManager::Ref& m = MemoryManager::create()) : m_size(0), m_memoryManager(m) { - initOffsetArray(); - m_data.clearAndSetMemoryManager(m_memoryManager); - - Vector3 lo(Vector3::inf()); - Vector3 hi(-lo); - - // Compute bounds - Array entry(init.size()); - for (int i = 0; i < entry.size(); ++i) { - const Value& value = init[i]; - Vector3 pos = m_posFunc(value); - - entry[i].value = value; - entry[i].hashCode = m_hashFunc(value); - entry[i].position = pos; - - lo = lo.min(pos); - hi = hi.max(pos); - } - - m_bounds = AABox(lo, hi); - - if (radiusHint <= 0) { - // Compute a good cell width based on the bounds. - // - // N numPerCell - // ----- = --------- - // volume r^3 - - float numPerCell = 5; - radiusHint = - (float)pow(numPerCell * m_bounds.volume() / init.size(), 1.0 / 3.0); - - if (radiusHint == 0) { - // Volume must have been zero because all points were colocated. - radiusHint = 0.1f; - } - } - - insert(init); - } - - /** Returns the number of elements. */ - inline int size() const { - return m_size; - } - - /** Returns a conservative bounding box around the contents. This is - conservative because it is not updated when elements are removed. */ - const AABox& conservativeBoxBounds() const { - return m_bounds; - } - - /** Insert @a v at position @a p given by getPosition(v, p). - Multiple elements that are equal may be inserted; all copies will be - in the data structure. */ - void insert(const Value& v) { - Vector3 pos; - PosFunc::getPosition(v, pos); - Vector3int32 cellCoord; - getCellCoord(pos, cellCoord); - - // See if the cell already exists - Cell& cell = m_data.getCreate(cellCoord); - - if (cell.size() == 0) { - // Use the same memory manager as for the whole class - cell.clearAndSetMemoryManager(m_memoryManager); - } - - Entry& entry = cell.next(); - entry.value = v; - entry.position = pos; - - // Update the bounds - if (size() == 0) { - m_bounds = AABox(pos); - } else { - m_bounds.merge(pos); - } - - ++m_size; - ++m_epoch; - } - - - /** Inserts all elements of the array. */ - void insert(const Array& v) { - for (int i = 0; i < v.size(); ++i) { - insert(v[i]); - } - } - - - /** If there are multiple copies of an element, you must - delete them multiple times. - - @param shrinkIfNecessary If true, deallocate underlying data - structures as they are emptied. False increases performace at - the cost of memory overhead for dynamic structures. - - @return true if the element was found. - */ - bool remove(const Value& v, bool shrinkIfNecessary = true) { - Cell* cell = NULL; - int index = 0; - Vector3int32 cellCoord; - - if (find(v, cellCoord, cell, index)) { - cell->fastRemove(index, shrinkIfNecessary); - --m_size; - ++m_epoch; - - if ((cell->size() == 0) && shrinkIfNecessary) { - // Remove the cell itself - - // Drop our pointer, which is about to dangle - cell = NULL; - bool success = m_data.remove(cellCoord); - debugAssertM(success, "Data structure corrupt: " - "tried to remove a cell that doesn't exist."); - } - - return true; - - } else { - return false; - } - } - - /** Removes all elements of @v. */ - void remove(const Array& v, bool shrink = true) { - for (int i = 0; i < v.size(); ++i) { - remove(v[i], shrink); - } - } - - /////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////// - - class Iterator { - private: - friend class ThisType; - - bool m_isEnd; - - const ThisType* m_grid; - - typename CellTable::Iterator m_tableIterator; - - /** Index within m_tableIterator->value of the current value. */ - int m_arrayIndex; - - const int m_epoch; - - /** End iterator. Note that the m_tableIterator is initialized to the end iterator - of a temporary value! This is ok because we'll never look at the value of the - m_tableIterator, since we're initializing the "end" Iterator.*/ - Iterator() : m_isEnd(true), m_grid(NULL), m_tableIterator(CellTable().end()), - m_arrayIndex(0), m_epoch(0) {} - - Iterator(const ThisType* grid) : - m_isEnd(false), - m_grid(grid), - m_tableIterator( grid->m_data.begin() ), - m_arrayIndex(0), - m_epoch(grid->m_epoch) { } - - private: - - const Value& value() const { - debugAssert(! m_isEnd); - debugAssertM(m_tableIterator->value.size() > m_arrayIndex, - "No more elements"); - return m_tableIterator->value[m_arrayIndex].value; - } - - public: - - inline bool operator!=(const Iterator& other) const { - if (other.m_isEnd && m_isEnd) { - return false; - } else { - return (m_isEnd != other.m_isEnd) || - (m_tableIterator != other.m_tableIterator) || - (m_arrayIndex != other.m_arrayIndex); - } - } - - bool operator==(const Iterator& other) const { - return !(*this != other); - } - - /** Preincrement */ - Iterator& operator++() { - debugAssert(! m_isEnd); - debugAssertM(m_epoch == m_grid->m_epoch, - "It is illegal to mutate the HashGrid " - "while iterating through it."); - - ++m_arrayIndex; - - if (m_arrayIndex >= m_tableIterator->value.size()) { - // Move on to the next cell - ++m_tableIterator; - m_arrayIndex = 0; - - // Check to see if we're at the end - m_isEnd = (m_tableIterator == m_grid->m_data.end()); - } - - return *this; - } - - /** Post increment (slower) */ - Iterator operator++(int) { - debugAssert(! m_isEnd); - Iterator old = *this; - ++(*this); - return old; - } - - const Value& operator*() const { return value(); } - const Value* operator->() const { return &value(); } - operator Value*() const { return &value(); } - }; // Iterator - - - /** Iterate through all members. It is an error to mutate the HashGrid - while iterating through it. Each member can be accessed by "dereferencing" - the iterator: - -
-        for (Grid::Iterator i = grid.begin(); i != grid.end(), ++i) {
-        const Value& = *i;
-        ...
-        }
-        
- */ - Iterator begin() const { - return Iterator(this); - } - - const Iterator& end() const { - static const Iterator it; - return it; - } - - /////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////// - - // Forward declaration required by older gcc versions for friend declaration in BoxIterator - class SphereIterator; - class BoxIterator { - private: - friend class ThisType; - friend class SphereIterator; - - bool m_isEnd; - - const ThisType* m_grid; - - /** Lower bound on the boxes covered, inclusive. */ - Vector3int32 m_lo; - - /** Upper bound on the boxes covered, inclusive.*/ - Vector3int32 m_hi; - - /** If true, test values against m_box before returning them.*/ - bool m_exact; - - /** The underlying box in 3D space */ - AABox m_box; - - /** The iterator winds through the 3D grid between m_lo and (m_lo + m_extent) in - Z,Y,X-major order. This is the index keeping track of how - far it has come */ - Vector3int32 m_current; - - /** The current cell. */ - Cell* m_cell; - - /** Index within m_cell of the current value */ - int m_arrayIndex; - - const int m_epoch; - - - /** Called from advance() */ - void advanceCell() { - do { - ++m_current.x; - if (m_current.x > m_hi.x) { - m_current.x = m_lo.x; - ++m_current.y; - if (m_current.y > m_hi.y) { - m_current.y = m_lo.y; - ++m_current.z; - if (m_current.z > m_hi.z) { - m_isEnd = true; - return; - } - } - } - - // Pick up the new cell - m_cell = m_grid->m_data.getPointer(m_current); - // Keep advancing if the cell does not exist - } while ((m_cell == NULL) || (m_cell->size() == 0)); - } - - /** Advance to the next value */ - void advance() { - debugAssert(! m_isEnd); - - do { - ++m_arrayIndex; - bool inConstructor = (m_cell == NULL); - if (inConstructor || m_arrayIndex >= m_cell->size()) { - advanceCell(); - m_arrayIndex = 0; - - if (m_isEnd) { - // Ran out of values - return; - } - debugAssert(m_cell != NULL); - } - - // Advance until we have a value that can be returned, either - // because we don't care about exactness or because it is - // guaranteed to be within the box. - } while (m_exact && ! m_box.contains(position())); - } - - - /** End iterator */ - BoxIterator() : m_isEnd(true), m_grid(NULL), m_exact(true), m_current(0,0,0), m_cell(NULL), m_arrayIndex(0), m_epoch(0) {} - - /** Begin iterator */ - BoxIterator(const ThisType* grid, bool exact, const AABox& box) : - m_isEnd(false), - m_grid(grid), - m_exact(exact), - m_box(box), - m_current(-1, 0 ,0), - m_cell(NULL), - m_arrayIndex(0), - m_epoch(grid->m_epoch) { - - m_grid->getCellCoord(box.low(), m_lo); - m_grid->getCellCoord(box.high(), m_hi); - - // Get to the first value - m_current = m_lo; - // Back up one so that advancing takes us to the first - --m_current.x; - advance(); - } - - const Value& value() const { - debugAssert(! m_isEnd); - return (*m_cell)[m_arrayIndex].value; - } - - /** Used by SphereIterator::advance() */ - const Vector3& position() const { - debugAssert(! m_isEnd); - return (*m_cell)[m_arrayIndex].position; - } - - // Intentionally unimplemented - BoxIterator& operator=(const BoxIterator&); - - public: - - inline bool operator!=(const BoxIterator& other) const { - if (other.m_isEnd && m_isEnd) { - return false; - } else { - return (m_isEnd != other.m_isEnd) || - (m_cell != other.m_cell) || - (m_arrayIndex != other.m_arrayIndex); - } - } - - bool operator==(const BoxIterator& other) const { - return !(*this != other); - } - - /** Preincrement */ - BoxIterator& operator++() { - debugAssert(! m_isEnd); - debugAssertM(m_epoch == m_grid->m_epoch, - "It is illegal to mutate the HashGrid " - "while iterating through it."); - - advance(); - - return *this; - } - - /** Post increment (slower) */ - BoxIterator operator++(int) { - Iterator old = *this; - ++(*this); - return old; - } - - const Value& operator*() const { return value(); } - const Value* operator->() const { return &value(); } - operator Value*() const { return &value(); } - - bool hasMore() const { - return ! m_isEnd; - } - }; // BoxIterator - - /** - Finds all values whose positions are within @a box. It is an error to - mutate the PointHashGrid while iterating through it. - - @param exact If false, the iterator will execute more quickly but will likely return some - values that lie outside the box. Set exact = false if you are going to test the - results against the yourself box anyway. - */ - BoxIterator beginBoxIntersection(const AABox& box, bool exact = true) const { - return BoxIterator(this, exact, box); - } - - const BoxIterator& endBoxIntersection() const { - static const BoxIterator it; - return it; - } - - /////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////// - - class SphereIterator { - private: - - friend class ThisType; - - bool m_isEnd; - Sphere m_sphere; - BoxIterator m_boxIterator; - - SphereIterator() : m_isEnd(true) {} - - void advance() { - if (! m_boxIterator.hasMore()) { - m_isEnd = true; - return; - } - - while (! m_sphere.contains(m_boxIterator.position())) { - ++m_boxIterator; - - if (! m_boxIterator.hasMore()) { - m_isEnd = true; - return; - } - } - } - - static AABox getBoundingBox(const Sphere& s) { - AABox box; - s.getBounds(box); - return box; - } - - SphereIterator(const ThisType* grid, const Sphere& sphere) : - m_isEnd(false), - m_sphere(sphere), - m_boxIterator(grid, false, getBoundingBox(sphere)) { - - // Find the first element that is actually in the sphere, - // not just the box. - advance(); - } - - const Value& value() const { - return *m_boxIterator; - } - - // TODO: if the sphere is very big compared to radius, check each - // cell's box to see if the cell itself is actually inside the sphere - // before iterating through it, since there may be many boxes outside the sphere. - - // Intentionally unimplemented - SphereIterator& operator=(const SphereIterator&); - public: - - inline bool operator!=(const SphereIterator& other) const { - if (other.m_isEnd && m_isEnd) { - return false; - } else { - return - (m_isEnd != other.m_isEnd) || - (m_sphere != other.m_sphere) || - (m_boxIterator != other.m_boxIterator); - } - } - - bool operator==(const SphereIterator& other) const { - return !(*this != other); - } - - - - /** Preincrement */ - SphereIterator& operator++() { - debugAssert(! m_isEnd); - - ++m_boxIterator; - advance(); - - return *this; - } - - /** Post increment (slower) */ - SphereIterator operator++(int) { - Iterator old = *this; - ++(*this); - return old; - } - - const Value& operator*() const { return value(); } - const Value* operator->() const { return &value(); } - operator Value*() const { return &value(); } - - bool hasMore() const { - return ! m_isEnd; - } - }; // SphereIterator - - /** - Finds all values whose positions are within @a sphere. It is an error - to mutate the HashGrid while iterating through it. - */ - SphereIterator beginSphereIntersection(const Sphere& sphere) const { - return SphereIterator(this, sphere); - } - - const SphereIterator& endSphereIntersection() const { - static const SphereIterator it; - return it; - } - - /////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////// - - /** - Dereference to access the bounds() and size() [element count] of the underlying - cell objet. - - Example: -
-       for(PointHashGrid::CellIterator iter = grid.beginCells(); iter != grid.endCells(); ++iter) {	
-       entriesFound += iter->size();
-       }
-       
- */ - class CellIterator { - private: - friend class ThisType; - - bool m_isEnd; - const ThisType* m_grid; - typename CellTable::Iterator m_tableIterator; - const int m_epoch; - - - Cell& cell() { - return m_tableIterator->value; - } - - public: - - class CellObject { - friend class CellIterator; - private: - const CellIterator* m_parent; - - CellObject() : m_parent(NULL) {} - - public: - - /** Returns the bounds on this cell */ - AABox bounds() const { - const Vector3int32& k = m_parent->m_tableIterator->key; - return AABox(Vector3(k) * m_parent->m_cellWidth, - Vector3(k + Vector3int32(1, 1, 1)) * m_parent->m_cellWidth); - } - - /** Number of elements inside this cell */ - int size() const { - debugAssert(! m_parent->m_isEnd); - return m_parent->m_tableIterator->value.size(); - } - }; - - private: - /** Used to make the indirection work.*/ - CellObject m_indirection; - - /** End iterator. Note that the m_tableIterator is initialized to the end iterator - of a temporary value! This is ok because we'll never look at the value of the - m_tableIterator, since we're initializing the "end" Iterator.*/ - CellIterator() : - m_isEnd(true), - m_grid(NULL), - m_tableIterator( CellTable().end() ), - m_epoch(0) {} - - CellIterator(const ThisType* grid) : - m_isEnd(false), - m_grid(grid), - m_tableIterator( grid->m_data.begin()), - m_epoch(grid->m_epoch) { - m_indirection.m_parent = this; - m_isEnd = ! m_tableIterator.hasMore(); - } - - // Intentionally unimplemented - CellIterator& operator=(const CellIterator&); - - public: - - const CellObject& operator*() const { return m_indirection; } - const CellObject* operator->() const { return &m_indirection; } - operator CellObject*() const { return &m_indirection; } - - inline bool operator!=(const CellIterator& other) const { - // != is called more often than == during iteration - return !( - (m_isEnd && other.m_isEnd) || - ((m_isEnd == other.m_isEnd) && - (m_tableIterator != other.m_tableIterator))); - } - - bool operator==(const CellIterator& other) const { - return !(*this != other); - } - - /** Preincrement */ - CellIterator& operator++() { - debugAssertM(m_epoch == m_grid->m_epoch, - "It is illegal to mutate the HashGrid while " - "iterating through it."); - ++m_tableIterator; - m_isEnd = ! m_tableIterator.hasMore(); - return *this; - } - - /** Post increment (slower) */ - CellIterator operator++(int) { - Iterator old = *this; - ++(*this); - return old; - } - - bool hasMore() const { - return ! m_isEnd; - } - }; // CellIterator - - /** Iterates through the non-empty cells. This is intended primarily for - debugging and visualizing the data structure.*/ - CellIterator beginCells() const { - return CellIterator(this); - } - - const CellIterator& endCells() const { - static const CellIterator it; - return it; - } - - /////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////// - - /** Returns true if there is a value that is exactly equal to @a v. This will - check all neighboring cells to avoid roundoff error at cell boundaries. - */ - bool contains(const Value& v) const { - Cell* cell = NULL; - int index = 0; - Vector3int32 cellCoord; - return const_cast(this)->find(v, cellCoord, cell, index); - } - - /** Calls delete on all of the values, which are assumed to be pointers. - This is a helper to avoid requiring you to iterate through the data - structure, removing and deleting each one. Clears the PointHashGrid at the - end. - - Using objects (instead of pointers) or reference counted pointers is - recommended over using pointers and this deleteAll method.*/ - void deleteAll() { - for (Iterator it = begin(); it.hasMore(); ++it) { - delete *it; - } - clear(); - } - - void clearAndSetMemoryManager(const MemoryManager::Ref& m) { - ++m_epoch; - m_size = 0; - m_bounds = AABox(); - - m_data.clearAndSetMemoryManager(m); - m_memoryManager = m; - } - - /** Removes all data. - @param shrink If true, underlying structures are deallocated as - they are freed.*/ - void clear(bool shrink = true) { - m_size = 0; - m_bounds = AABox(); - if (! shrink) { - // Remove all data - for (CellIterator it = beginCells(); it.hasMore(); ++it) { - it.cell().clear(true); - } - } else { - m_data.clear(); - } - ++m_epoch; - } - - int debugGetDeepestBucketSize() const { - return m_data.debugGetDeepestBucketSize(); - } - - float debugGetAverageBucketSize() const { - return m_data.debugGetAverageBucketSize(); - } -#undef ThisType -}; - -} // G3D -#endif diff --git a/externals/g3dlite/G3D/PointKDTree.h b/externals/g3dlite/G3D/PointKDTree.h deleted file mode 100644 index 151cbd5f2f3..00000000000 --- a/externals/g3dlite/G3D/PointKDTree.h +++ /dev/null @@ -1,1185 +0,0 @@ -/** - @file PointKDTree.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2004-01-11 - @edited 2008-11-02 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - - */ - -#ifndef X_PointKDTree_H -#define X_PointKDTree_H - -#include "G3D/platform.h" -#include "G3D/Array.h" -#include "G3D/Table.h" -#include "G3D/Vector2.h" -#include "G3D/Vector3.h" -#include "G3D/Vector4.h" -#include "G3D/AABox.h" -#include "G3D/Sphere.h" -#include "G3D/Box.h" -#include "G3D/BinaryInput.h" -#include "G3D/BinaryOutput.h" -#include "G3D/CollisionDetection.h" -#include "G3D/GCamera.h" -#include "G3D/PositionTrait.h" -#include - -namespace G3D { - -/** - A set data structure that supports spatial queries using an axis-aligned - BSP tree for speed. - - PointKDTree allows you to quickly find points in 3D that lie within - a box or sphere. For large sets of objects it is much faster - than testing each object for a collision. See also G3D::KDTree; this class - is optimized for point sets, e.g.,for use in photon mapping and mesh processing. - - Template Parameters - -
- -
The template parameter T must be one for which - the following functions are overloaded: - -
-      T::T(); (public constructor of no arguments)
-
-       template<> struct PositionTrait {
-         static void getPosition(const T& v, G3D::Vector3& p);};
-
-       template <> struct HashTrait {
-         static size_t hashCode(const T& key);};
-
-       template<> struct EqualsTrait {
-           static bool equals(const T& a, const T& b); };
-    
- -

- - G3D provides these for the Vector2, Vector3, and Vector4 classes. - If you use a custom class, or a pointer to a custom class, you will need - to define those functions. - - Moving %Set Members -

It is important that objects do not move without updating the - PointKDTree. If the position of an object is about - to change, PointKDTree::remove it before they change and - PointKDTree::insert it again afterward. For objects - where the hashCode and == operator are invariant with respect - to the 3D position, - you can use the PointKDTree::update method as a shortcut to - insert/remove an object in one step after it has moved. - - - Note: Do not mutate any value once it has been inserted into PointKDTree. Values - are copied interally. All PointKDTree iterators convert to pointers to constant - values to reinforce this. - - If you want to mutate the objects you intend to store in a PointKDTree - simply insert pointers to your objects instead of the objects - themselves, and ensure that the above operations are defined. (And - actually, because values are copied, if your values are large you may - want to insert pointers anyway, to save space and make the balance - operation faster.) - - Dimensions - Although designed as a 3D-data structure, you can use the PointKDTree - for data distributed along 2 or 1 axes by simply returning bounds - that are always zero along one or more dimensions. - -*/ -template, - class HashFunc = HashTrait, - class EqualsFunc = EqualsTrait > -class PointKDTree { -protected: -#define TreeType PointKDTree - - // Unlike the KDTree, the PointKDTree assumes that T elements are - // small and keeps the handle and cached position together instead of - // placing them in separate bounds arrays. Also note that a copy of T - // is kept in the member table and that there is no indirection. - class Handle { - private: - Vector3 m_position; - - public: - T value; - - inline Handle() {} - inline Handle(const T& v) : value(v) { - PositionFunc::getPosition(v, m_position); - } - - /** Used by makeNode to create fake handles for partitioning. */ - void setPosition(const Vector3& v) { - m_position = v; - } - - inline const Vector3& position() const { - return m_position; - } - }; - - /** Returns the bounds of the sub array. Used by makeNode. */ - static AABox computeBounds( - const Array& point) { - - if (point.size() == 0) { - return AABox(Vector3::inf(), Vector3::inf()); - } - - AABox bounds(point[0].position()); - - for (int p = 0; p < point.size(); ++p) { - bounds.merge(point[p].position()); - } - - return bounds; - } - - class Node { - public: - - /** Spatial bounds on all values at this node and its children, based purely on - the parent's splitting planes. May be infinite */ - AABox splitBounds; - - Vector3::Axis splitAxis; - - /** Location along the specified axis */ - float splitLocation; - - /** child[0] contains all values strictly - smaller than splitLocation along splitAxis. - - child[1] contains all values strictly - larger. - - Both may be NULL if there are not enough - values to bother recursing. - */ - Node* child[2]; - - /** Values if this is a leaf node). */ - Array valueArray; - - /** Creates node with NULL children */ - Node() { - splitAxis = Vector3::X_AXIS; - splitLocation = 0; - splitBounds = AABox(-Vector3::inf(), Vector3::inf()); - for (int i = 0; i < 2; ++i) { - child[i] = NULL; - } - } - - /** - Doesn't clone children. - */ - Node(const Node& other) : valueArray(other.valueArray) { - splitAxis = other.splitAxis; - splitLocation = other.splitLocation; - splitBounds = other.splitBounds; - for (int i = 0; i < 2; ++i) { - child[i] = NULL; - } - } - - /** Copies the specified subarray of pt into point, NULLs the children. - Assumes a second pass will set splitBounds. */ - Node(const Array& pt) { - splitAxis = Vector3::X_AXIS; - splitLocation = 0; - for (int i = 0; i < 2; ++i) { - child[i] = NULL; - } - valueArray = pt; - } - - - /** Deletes the children (but not the values) */ - ~Node() { - for (int i = 0; i < 2; ++i) { - delete child[i]; - } - } - - - /** Returns true if this node is a leaf (no children) */ - inline bool isLeaf() const { - return (child[0] == NULL) && (child[1] == NULL); - } - - - /** - Recursively appends all handles and children's handles - to the array. - */ - void getHandles(Array& handleArray) const { - handleArray.append(valueArray); - for (int i = 0; i < 2; ++i) { - if (child[i] != NULL) { - child[i]->getHandles(handleArray); - } - } - } - - - void verifyNode(const Vector3& lo, const Vector3& hi) { - // debugPrintf("Verifying: split %d @ %f [%f, %f, %f], [%f, %f, %f]\n", - // splitAxis, splitLocation, lo.x, lo.y, lo.z, hi.x, hi.y, hi.z); - - debugAssert(lo == splitBounds.low()); - debugAssert(hi == splitBounds.high()); - - for (int i = 0; i < valueArray.length(); ++i) { - const Vector3& b = valueArray[i].position(); - debugAssert(splitBounds.contains(b)); - } - - if (child[0] || child[1]) { - debugAssert(lo[splitAxis] < splitLocation); - debugAssert(hi[splitAxis] > splitLocation); - } - - Vector3 newLo = lo; - newLo[splitAxis] = splitLocation; - Vector3 newHi = hi; - newHi[splitAxis] = splitLocation; - - if (child[0] != NULL) { - child[0]->verifyNode(lo, newHi); - } - - if (child[1] != NULL) { - child[1]->verifyNode(newLo, hi); - } - } - - - /** - Stores the locations of the splitting planes (the structure but not the content) - so that the tree can be quickly rebuilt from a previous configuration without - calling balance. - */ - static void serializeStructure(const Node* n, BinaryOutput& bo) { - if (n == NULL) { - bo.writeUInt8(0); - } else { - bo.writeUInt8(1); - n->splitBounds.serialize(bo); - serialize(n->splitAxis, bo); - bo.writeFloat32(n->splitLocation); - for (int c = 0; c < 2; ++c) { - serializeStructure(n->child[c], bo); - } - } - } - - /** Clears the member table */ - static Node* deserializeStructure(BinaryInput& bi) { - if (bi.readUInt8() == 0) { - return NULL; - } else { - Node* n = new Node(); - n->splitBounds.deserialize(bi); - deserialize(n->splitAxis, bi); - n->splitLocation = bi.readFloat32(); - for (int c = 0; c < 2; ++c) { - n->child[c] = deserializeStructure(bi); - } - } - } - - /** Returns the deepest node that completely contains bounds. */ - Node* findDeepestContainingNode(const Vector3& point) { - - // See which side of the splitting plane the bounds are on - if (point[splitAxis] < splitLocation) { - // Point is on the low side. Recurse into the child - // if it exists. - if (child[0] != NULL) { - return child[0]->findDeepestContainingNode(point); - } - } else if (point[splitAxis] > splitLocation) { - // Point is on the high side, recurse into the child - // if it exists. - if (child[1] != NULL) { - return child[1]->findDeepestContainingNode(point); - } - } - - // There was no containing child, so this node is the - // deepest containing node. - return this; - } - - /** Appends all members that intersect the box. - If useSphere is true, members are tested against the sphere instead. */ - void getIntersectingMembers( - const AABox& sphereBounds, - const Sphere& sphere, - Array& members) const { - - // Test all values at this node. Extract the - // underlying C array for speed - const int N = valueArray.size(); - const Handle* handleArray = valueArray.getCArray(); - - const float r2 = square(sphere.radius); - - // Copy the sphere center so that it is on the stack near the radius - const Vector3 center = sphere.center; - for (int v = 0; v < N; ++v) { - if ((center - handleArray[v].position()).squaredLength() <= r2) { - members.append(handleArray[v].value); - } - } - - // If the left child overlaps the box, recurse into it - if (child[0] && (sphereBounds.low()[splitAxis] < splitLocation)) { - child[0]->getIntersectingMembers(sphereBounds, sphere, members); - } - - // If the right child overlaps the box, recurse into it - if (child[1] && (sphereBounds.high()[splitAxis] > splitLocation)) { - child[1]->getIntersectingMembers(sphereBounds, sphere, members); - } - } - - /** Appends all members that intersect the box. - If useSphere is true, members are tested against the sphere instead. - - Implemented using both box and sphere tests to simplify the implementation - of a future beginSphereInteresection iterator using the same underlying - BoxIterator class. - */ - void getIntersectingMembers( - const AABox& box, - const Sphere& sphere, - Array& members, - bool useSphere) const { - - // Test all values at this node - for (int v = 0; v < valueArray.size(); ++v) { - if ((useSphere && sphere.contains(valueArray[v].position())) || - (! useSphere && box.contains(valueArray[v].position()))) { - members.append(valueArray[v].value); - } - } - - // If the left child overlaps the box, recurse into it - if ((child[0] != NULL) && (box.low()[splitAxis] < splitLocation)) { - child[0]->getIntersectingMembers(box, sphere, members, useSphere); - } - - // If the right child overlaps the box, recurse into it - if ((child[1] != NULL) && (box.high()[splitAxis] > splitLocation)) { - child[1]->getIntersectingMembers(box, sphere, members, useSphere); - } - } - - /** - Recurse through the tree, assigning splitBounds fields. - */ - void assignSplitBounds(const AABox& myBounds) { - splitBounds = myBounds; - -# ifdef G3D_DEBUG - if (child[0] || child[1]) { - debugAssert(splitBounds.high()[splitAxis] > splitLocation); - debugAssert(splitBounds.low()[splitAxis] < splitLocation); - } -# endif - - AABox childBounds[2]; - myBounds.split(splitAxis, splitLocation, childBounds[0], childBounds[1]); - - for (int c = 0; c < 2; ++c) { - if (child[c]) { - child[c]->assignSplitBounds(childBounds[c]); - } - } - } - }; - - class AxisComparator { - private: - Vector3::Axis sortAxis; - - public: - - AxisComparator(Vector3::Axis s) : sortAxis(s) {} - - inline int operator()(const Handle& A, const Handle& B) const { - if (A.position()[sortAxis] > B.position()[sortAxis]) { - return -1; - } else if (A.position()[sortAxis] < B.position()[sortAxis]) { - return 1; - } else { - return 0; - } - } - }; - - /** - Recursively subdivides the subarray. - - The source array will be cleared after it is used - - Call assignSplitBounds() on the root node after making a tree. - */ - Node* makeNode( - Array& source, - Array& temp, - int valuesPerNode, - int numMeanSplits) { - - Node* node = NULL; - - if (source.size() <= valuesPerNode) { - // Make a new leaf node - node = new Node(source); - - // Set the pointers in the memberTable - for (int i = 0; i < source.size(); ++i) { - memberTable.set(source[i].value, node); - } - - } else { - // Make a new internal node - node = new Node(); - - const AABox bounds = computeBounds(source); - const Vector3 extent = bounds.high() - bounds.low(); - - Vector3::Axis splitAxis = extent.primaryAxis(); - - float splitLocation; - - Array lt, gt; - - if (numMeanSplits <= 0) { - source.medianPartition(lt, node->valueArray, gt, temp, AxisComparator(splitAxis)); - splitLocation = node->valueArray[0].position()[splitAxis]; - - if ((node->valueArray.size() > source.size() / 2) && - (source.size() > 10)) { - // Our median split put an awful lot of points on the splitting plane. Try a mean - // split instead - numMeanSplits = 1; - } - } - - if (numMeanSplits > 0) { - // Compute the mean along the axis - - splitLocation = (bounds.high()[splitAxis] + - bounds.low()[splitAxis]) / 2.0; - - Handle splitHandle; - Vector3 v; - v[splitAxis] = splitLocation; - splitHandle.setPosition(v); - - source.partition(splitHandle, lt, node->valueArray, gt, AxisComparator(splitAxis)); - } - -# if defined(G3D_DEBUG) && defined(VERIFY_TREE) - for (int i = 0; i < lt.size(); ++i) { - const Vector3& v = lt[i].position(); - debugAssert(v[splitAxis] < splitLocation); - } - for (int i = 0; i < gt.size(); ++i) { - debugAssert(gt[i].position()[splitAxis] > splitLocation); - } - for (int i = 0; i < node->valueArray.size(); ++i) { - debugAssert(node->valueArray[i].position()[splitAxis] == splitLocation); - } -# endif - - node->splitAxis = splitAxis; - node->splitLocation = splitLocation; - - // Throw away the source array to save memory - source.fastClear(); - - if (lt.size() > 0) { - node->child[0] = makeNode(lt, temp, valuesPerNode, numMeanSplits - 1); - } - - if (gt.size() > 0) { - node->child[1] = makeNode(gt, temp, valuesPerNode, numMeanSplits - 1); - } - - // Add the values stored at this interior node to the member table - for(int i = 0; i < node->valueArray.size(); ++i) { - memberTable.set(node->valueArray[i].value, node); - } - - } - - return node; - } - - /** - Recursively clone the passed in node tree, setting - pointers for members in the memberTable as appropriate. - called by the assignment operator. - */ - Node* cloneTree(Node* src) { - Node* dst = new Node(*src); - - // Make back pointers - for (int i = 0; i < dst->valueArray.size(); ++i) { - memberTable.set(dst->valueArray[i].value, dst); - } - - // Clone children - for (int i = 0; i < 2; ++i) { - if (src->child[i] != NULL) { - dst->child[i] = cloneTree(src->child[i]); - } - } - - return dst; - } - - /** Maps members to the node containing them */ - typedef Table MemberTable; - MemberTable memberTable; - - Node* root; - -public: - - /** To construct a balanced tree, insert the elements and then call - PointKDTree::balance(). */ - PointKDTree() : root(NULL) {} - - - PointKDTree(const PointKDTree& src) : root(NULL) { - *this = src; - } - - - PointKDTree& operator=(const PointKDTree& src) { - delete root; - // Clone tree takes care of filling out the memberTable. - root = cloneTree(src.root); - return *this; - } - - - ~PointKDTree() { - clear(); - } - - /** - Throws out all elements of the set and erases the structure of the tree. - */ - void clear() { - memberTable.clear(); - delete root; - root = NULL; - } - - /** Removes all elements of the set while maintaining the structure of the tree */ - void clearData() { - memberTable.clear(); - Array stack; - stack.push(root); - while (stack.size() > 0) { - Node* node = stack.pop(); - node->valueArray.fastClear(); - - for (int i = 0; i < 2; ++i) { - if (node->child[i] != NULL) { - stack.push(node->child[i]); - } - } - } - } - - - int size() const { - return memberTable.size(); - } - - /** - Inserts an object into the set if it is not - already present. O(log n) time. Does not - cause the tree to be balanced. - */ - void insert(const T& value) { - if (contains(value)) { - // Already in the set - return; - } - - Handle h(value); - - if (root == NULL) { - // This is the first node; create a root node - root = new Node(); - } - - Node* node = root->findDeepestContainingNode(h.position()); - - // Insert into the node - node->valueArray.append(h); - - // Insert into the node table - memberTable.set(value, node); - } - - /** Inserts each elements in the array in turn. If the tree - begins empty (no structure and no elements), this is faster - than inserting each element in turn. You still need to balance - the tree at the end.*/ - void insert(const Array& valueArray) { - // Pre-size the member table to avoid multiple allocations - memberTable.setSizeHint(valueArray.size() + size()); - - if (root == NULL) { - // Optimized case for an empty tree; don't bother - // searching or reallocating the root node's valueArray - // as we incrementally insert. - root = new Node(); - root->valueArray.resize(valueArray.size()); - for (int i = 0; i < valueArray.size(); ++i) { - // Insert in opposite order so that we have the exact same - // data structure as if we inserted each (i.e., order is reversed - // from array). - root->valueArray[valueArray.size() - i - 1] = Handle(valueArray[i]); - memberTable.set(valueArray[i], root); - } - } else { - // Insert at appropriate tree depth. - for (int i = 0; i < valueArray.size(); ++i) { - insert(valueArray[i]); - } - } - } - - - /** - Returns true if this object is in the set, otherwise - returns false. O(1) time. - */ - bool contains(const T& value) { - return memberTable.containsKey(value); - } - - - /** - Removes an object from the set in O(1) time. - It is an error to remove members that are not already - present. May unbalance the tree. - - Removing an element never causes a node (split plane) to be removed... - nodes are only changed when the tree is rebalanced. This behavior - is desirable because it allows the split planes to be serialized, - and then deserialized into an empty tree which can be repopulated. - */ - void remove(const T& value) { - debugAssertM(contains(value), - "Tried to remove an element from a " - "PointKDTree that was not present"); - - Array& list = memberTable[value]->valueArray; - - // Find the element and remove it - for (int i = list.length() - 1; i >= 0; --i) { - if (list[i].value == value) { - list.fastRemove(i); - break; - } - } - memberTable.remove(value); - } - - - /** - If the element is in the set, it is removed. - The element is then inserted. - - This is useful when the == and hashCode methods - on T are independent of the bounds. In - that case, you may call update(v) to insert an - element for the first time and call update(v) - again every time it moves to keep the tree - up to date. - */ - void update(const T& value) { - if (contains(value)) { - remove(value); - } - insert(value); - } - - - /** - Rebalances the tree (slow). Call when objects - have moved substantially from their original positions - (which unbalances the tree and causes the spatial - queries to be slow). - - @param valuesPerNode Maximum number of elements to put at - a node. - - @param numMeanSplits numMeanSplits = 0 gives a - fully axis aligned BSP-tree, where the balance operation attempts to balance - the tree so that every splitting plane has an equal number of left - and right children (i.e. it is a median split along that axis). - This tends to maximize average performance; all querries will return in the same amount of time. - - You can override this behavior by - setting a number of mean (average) splits. numMeanSplits = MAX_INT - creates a full oct-tree, which tends to optimize peak performance (some areas of the scene will terminate after few recursive splits) at the expense of - peak performance. - */ - void balance(int valuesPerNode = 40, int numMeanSplits = 3) { - if (root == NULL) { - // Tree is empty - return; - } - - Array handleArray; - root->getHandles(handleArray); - - // Delete the old tree - clear(); - - Array temp; - root = makeNode(handleArray, temp, valuesPerNode, numMeanSplits); - temp.fastClear(); - - // Walk the tree, assigning splitBounds. We start with unbounded - // space. - root->assignSplitBounds(AABox::maxFinite()); - -# ifdef _DEBUG - root->verifyNode(Vector3::minFinite(), Vector3::maxFinite()); -# endif - } - -private: - - /** - Returns the elements - - @param parentMask The mask that this node returned from culledBy. - */ - static void getIntersectingMembers( - const Array& plane, - Array& members, - Node* node, - uint32 parentMask) { - - int dummy; - - if (parentMask == 0) { - // None of these planes can cull anything - for (int v = node->valueArray.size() - 1; v >= 0; --v) { - members.append(node->valueArray[v].value); - } - - // Iterate through child nodes - for (int c = 0; c < 2; ++c) { - if (node->child[c]) { - getIntersectingMembers(plane, members, node->child[c], 0); - } - } - } else { - - if (node->valueArray.size() > 0) { - // This is a leaf; check the points - debugAssertM(node->child[0] == NULL, "Malformed Point tree"); - debugAssertM(node->child[1] == NULL, "Malformed Point tree"); - - // Test values at this node against remaining planes - for (int p = 0; p < plane.size(); ++p) { - if ((parentMask >> p) & 1 != 0) { - // Test against this plane - const Plane& curPlane = plane[p]; - for (int v = node->valueArray.size() - 1; v >= 0; --v) { - if (curPlane.halfSpaceContains(node->valueArray[v].position())) { - members.append(node->valueArray[v].value); - } - } - } - } - } else { - - uint32 childMask = 0xFFFFFF; - - // Iterate through child nodes - for (int c = 0; c < 2; ++c) { - if (node->child[c] && - ! node->child[c]->splitBounds.culledBy(plane, dummy, parentMask, childMask)) { - // This node was not culled - getIntersectingMembers(plane, members, node->child[c], childMask); - } - } - } - } - } - -public: - - /** - Returns all members inside the set of planes. - @param members The results are appended to this array. - */ - void getIntersectingMembers(const Array& plane, Array& members) const { - if (root == NULL) { - return; - } - - getIntersectingMembers(plane, members, root, 0xFFFFFF); - } - - /** - Typically used to find all visible - objects inside the view frustum (see also GCamera::getClipPlanes)... i.e. all objects - not culled by frustum. - - Example: -
-        Array  visible;
-        tree.getIntersectingMembers(camera.frustum(), visible);
-        // ... Draw all objects in the visible array.
-      
- @param members The results are appended to this array. - */ - void getIntersectingMembers(const GCamera::Frustum& frustum, Array& members) const { - Array plane; - - for (int i = 0; i < frustum.faceArray.size(); ++i) { - plane.append(frustum.faceArray[i].plane); - } - - getIntersectingMembers(plane, members); - } - - /** - C++ STL style iterator variable. See beginBoxIntersection(). - The iterator overloads the -> (dereference) operator, so this - acts like a pointer to the current member. - */ - // This iterator turns Node::getIntersectingMembers into a - // coroutine. It first translates that method from recursive to - // stack based, then captures the system state (analogous to a Scheme - // continuation) after each element is appended to the member array, - // and allowing the computation to be restarted. - class BoxIntersectionIterator { - private: - friend class TreeType; - - /** True if this is the "end" iterator instance */ - bool isEnd; - - /** The box that we're testing against. */ - AABox box; - - /** Node that we're currently looking at. Undefined if isEnd - is true. */ - Node* node; - - /** Nodes waiting to be processed */ - // We could use backpointers within the tree and careful - // state management to avoid ever storing the stack-- but - // it is much easier this way and only inefficient if the - // caller uses post increment (which they shouldn't!). - Array stack; - - /** The next index of current->valueArray to return. - Undefined when isEnd is true.*/ - int nextValueArrayIndex; - - BoxIntersectionIterator() : isEnd(true) {} - - BoxIntersectionIterator(const AABox& b, const Node* root) : - isEnd(root == NULL), box(b), - node(const_cast(root)), nextValueArrayIndex(-1) { - - // We intentionally start at the "-1" index of the current - // node so we can use the preincrement operator to move - // ourselves to element 0 instead of repeating all of the - // code from the preincrement method. Note that this might - // cause us to become the "end" instance. - ++(*this); - } - - public: - - inline bool operator!=(const BoxIntersectionIterator& other) const { - return ! (*this == other); - } - - bool operator==(const BoxIntersectionIterator& other) const { - if (isEnd) { - return other.isEnd; - } else if (other.isEnd) { - return false; - } else { - // Two non-end iterators; see if they match. This is kind of - // silly; users shouldn't call == on iterators in general unless - // one of them is the end iterator. - if ((box != other.box) || (node != other.node) || - (nextValueArrayIndex != other.nextValueArrayIndex) || - (stack.length() != other.stack.length())) { - return false; - } - - // See if the stacks are the same - for (int i = 0; i < stack.length(); ++i) { - if (stack[i] != other.stack[i]) { - return false; - } - } - - // We failed to find a difference; they must be the same - return true; - } - } - - /** - Pre increment. - */ - BoxIntersectionIterator& operator++() { - ++nextValueArrayIndex; - - bool foundIntersection = false; - while (! isEnd && ! foundIntersection) { - - // Search for the next node if we've exhausted this one - while ((! isEnd) && (nextValueArrayIndex >= node->valueArray.length())) { - // If we entered this loop, then the iterator has exhausted the elements at - // node (possibly because it just switched to a child node with no members). - // This loop continues until it finds a node with members or reaches - // the end of the whole intersection search. - - // If the right child overlaps the box, push it onto the stack for - // processing. - if ((node->child[1] != NULL) && - (box.high()[node->splitAxis] > node->splitLocation)) { - stack.push(node->child[1]); - } - - // If the left child overlaps the box, push it onto the stack for - // processing. - if ((node->child[0] != NULL) && - (box.low()[node->splitAxis] < node->splitLocation)) { - stack.push(node->child[0]); - } - - if (stack.length() > 0) { - // Go on to the next node (which may be either one of the ones we - // just pushed, or one from farther back the tree). - node = stack.pop(); - nextValueArrayIndex = 0; - } else { - // That was the last node; we're done iterating - isEnd = true; - } - } - - // Search for the next intersection at this node until we run out of children - while (! isEnd && ! foundIntersection && (nextValueArrayIndex < node->valueArray.length())) { - if (box.intersects(node->valueArray[nextValueArrayIndex].bounds)) { - foundIntersection = true; - } else { - ++nextValueArrayIndex; - // If we exhaust this node, we'll loop around the master loop - // to find a new node. - } - } - } - - return *this; - } - - /** - Post increment (much slower than preincrement!). - */ - BoxIntersectionIterator operator++(int) { - BoxIntersectionIterator old = *this; - ++this; - return old; - } - - /** Overloaded dereference operator so the iterator can masquerade as a pointer - to a member */ - const T& operator*() const { - alwaysAssertM(! isEnd, "Can't dereference the end element of an iterator"); - return node->valueArray[nextValueArrayIndex].value; - } - - /** Overloaded dereference operator so the iterator can masquerade as a pointer - to a member */ - T const * operator->() const { - alwaysAssertM(! isEnd, "Can't dereference the end element of an iterator"); - return &(stack.last()->valueArray[nextValueArrayIndex].value); - } - - /** Overloaded cast operator so the iterator can masquerade as a pointer - to a member */ - operator T*() const { - alwaysAssertM(! isEnd, "Can't dereference the end element of an iterator"); - return &(stack.last()->valueArray[nextValueArrayIndex].value); - } - }; - - - /** - Iterates through the members that intersect the box - */ - BoxIntersectionIterator beginBoxIntersection(const AABox& box) const { - return BoxIntersectionIterator(box, root); - } - - BoxIntersectionIterator endBoxIntersection() const { - // The "end" iterator instance - return BoxIntersectionIterator(); - } - - /** - Appends all members whose bounds intersect the box. - See also PointKDTree::beginBoxIntersection. - */ - void getIntersectingMembers(const AABox& box, Array& members) const { - if (root == NULL) { - return; - } - root->getIntersectingMembers(box, Sphere(Vector3::zero(), 0), members, false); - } - - - /** - @param members The results are appended to this array. - */ - void getIntersectingMembers(const Sphere& sphere, Array& members) const { - if (root == NULL) { - return; - } - - AABox box; - sphere.getBounds(box); - root->getIntersectingMembers(box, sphere, members); - - } - - - /** - Stores the locations of the splitting planes (the structure but not the content) - so that the tree can be quickly rebuilt from a previous configuration without - calling balance. - */ - void serializeStructure(BinaryOutput& bo) const { - Node::serializeStructure(root, bo); - } - - /** Clears the member table */ - void deserializeStructure(BinaryInput& bi) { - clear(); - root = Node::deserializeStructure(bi); - } - - /** - Returns an array of all members of the set. See also PointKDTree::begin. - */ - void getMembers(Array& members) const { - memberTable.getKeys(members); - } - - - /** - C++ STL style iterator variable. See begin(). - Overloads the -> (dereference) operator, so this acts like a pointer - to the current member. - */ - class Iterator { - private: - friend class TreeType; - - // Note: this is a Table iterator, we are currently defining - // Set iterator - typename MemberTable::Iterator it; - - Iterator(const typename MemberTable::Iterator& it) : it(it) {} - - public: - inline bool operator!=(const Iterator& other) const { - return !(*this == other); - } - - bool operator==(const Iterator& other) const { - return it == other.it; - } - - /** - Pre increment. - */ - Iterator& operator++() { - ++it; - return *this; - } - - /** - Post increment (slower than preincrement). - */ - Iterator operator++(int) { - Iterator old = *this; - ++(*this); - return old; - } - - const T& operator*() const { - return it->key; - } - - T* operator->() const { - return &(it->key); - } - - operator T*() const { - return &(it->key); - } - }; - - - /** - C++ STL style iterator method. Returns the first member. - Use preincrement (++entry) to get to the next element (iteration - order is arbitrary). - Do not modify the set while iterating. - */ - Iterator begin() const { - return Iterator(memberTable.begin()); - } - - - /** - C++ STL style iterator method. Returns one after the last iterator - element. - */ - Iterator end() const { - return Iterator(memberTable.end()); - } -#undef TreeType -}; - -} - -#endif diff --git a/externals/g3dlite/G3D/Pointer.h b/externals/g3dlite/G3D/Pointer.h deleted file mode 100644 index 6e35062a746..00000000000 --- a/externals/g3dlite/G3D/Pointer.h +++ /dev/null @@ -1,292 +0,0 @@ -/** - @file Pointer.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2007-05-16 - @edited 2009-03-26 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ -#ifndef G3D_Pointer_h -#define G3D_Pointer_h - -#include "G3D/debugAssert.h" -#include "G3D/ReferenceCount.h" - -namespace G3D { - -/** - Acts like a pointer to a value of type ValueType (i.e., - ValueType*), but can operate through accessor methods as well as on - a value in memory. This is useful for implementing scripting - languages and other applications that need to connect existing APIs - by reference. - - Because the accessors require values to be passed by value (instead of by reference) - this is primarily useful for objects whose memory size is small. - -
-   class Foo {
-   public:
-      void setEnabled(bool b);
-      bool getEnabled() const;
-   };
-
-   Foo  f;
-   bool b;
-   
-   Pointer p1(&b);
-   Pointer p2(&f, &Foo::getEnabled, &Foo::setEnabled);
-
-   *p1 = true;
-   *p2 = false;
-   *p2 = *p1; \/\/ Value assignment
-   p2 = p1; \/\/ Pointer aliasing
-
-   \/\/ Or, equivalently:
-   p1.setValue(true);
-   p2.setValue(false);
-
-   p2.setValue(p1.getValue());
-   p2 = p1;
-   
- - Note: Because of the way that dereference is implemented, you cannot pass *p through a function - that takes varargs (...), e.g., printf("%d", *p) will produce a compile-time error. Instead use - printf("%d",(bool)*p) or printf("%d", p.getValue()). - - */ -template -class Pointer { -private: - - class Interface { - public: - virtual ~Interface() {}; - virtual void set(ValueType b) = 0; - virtual ValueType get() const = 0; - virtual Interface* clone() const = 0; - virtual bool isNull() const = 0; - }; - - class Memory : public Interface { - private: - - ValueType* value; - - public: - - Memory(ValueType* value) : value(value) { - //debugAssert(value != NULL); - } - - virtual void set(ValueType v) { - *value = v; - } - - virtual ValueType get() const { - return *value; - } - - virtual Interface* clone() const { - return new Memory(value); - } - - virtual bool isNull() const { - return value == NULL; - } - }; - - template - class Accessor : public Interface { - private: - - T* object; - GetMethod getMethod; - SetMethod setMethod; - - public: - - Accessor(T* object, - GetMethod getMethod, - SetMethod setMethod) : object(object), getMethod(getMethod), setMethod(setMethod) { - debugAssert(object != NULL); - } - - virtual void set(ValueType v) { - (object->*setMethod)(v); - } - - virtual ValueType get() const { - return (object->*getMethod)(); - } - - virtual Interface* clone() const { - return new Accessor(object, getMethod, setMethod); - } - - virtual bool isNull() const { - return object == NULL; - } - }; - - - template - class RefAccessor : public Interface { - private: - - ReferenceCountedPointer object; - GetMethod getMethod; - SetMethod setMethod; - - public: - - RefAccessor( - const ReferenceCountedPointer& object, - GetMethod getMethod, - SetMethod setMethod) : object(object), getMethod(getMethod), setMethod(setMethod) { - - debugAssert(object != NULL); - } - - virtual void set(ValueType v) { - (object.pointer()->*setMethod)(v); - } - - virtual ValueType get() const { - return (object.pointer()->*getMethod)(); - } - - virtual Interface* clone() const { - return new RefAccessor(object, getMethod, setMethod); - } - - virtual bool isNull() const { - return object.isNull(); - } - }; - - - Interface* m_interface; - -public: - - Pointer() : m_interface(NULL) {}; - - /** Allows implicit cast from real pointer */ - Pointer(ValueType* v) : m_interface(new Memory(v)) {} - - inline bool isNull() const { - return (m_interface == NULL) || m_interface->isNull(); - } - - // Assignment - inline Pointer& operator=(const Pointer& r) { - delete m_interface; - if (r.m_interface != NULL) { - m_interface = r.m_interface->clone(); - } else { - m_interface = NULL; - } - return this[0]; - } - - Pointer(const Pointer& p) : m_interface(NULL) { - this[0] = p; - } - - template - Pointer(const ReferenceCountedPointer& object, - ValueType (Class::*getMethod)() const, - void (Class::*setMethod)(ValueType)) : - m_interface(new RefAccessor(object, getMethod, setMethod)) {} - - template - Pointer(const ReferenceCountedPointer& object, - const ValueType& (Class::*getMethod)() const, - void (Class::*setMethod)(ValueType)) : - m_interface(new RefAccessor(object, getMethod, setMethod)) {} - - template - Pointer(const ReferenceCountedPointer& object, - ValueType (Class::*getMethod)() const, - void (Class::*setMethod)(const ValueType&)) : - m_interface(new RefAccessor(object, getMethod, setMethod)) {} - - template - Pointer(const ReferenceCountedPointer& object, - const ValueType& (Class::*getMethod)() const, - void (Class::*setMethod)(const ValueType&)) : - m_interface(new RefAccessor(object, getMethod, setMethod)) {} - - template - Pointer(Class* object, - const ValueType& (Class::*getMethod)() const, - void (Class::*setMethod)(const ValueType&)) : - m_interface(new Accessor(object, getMethod, setMethod)) {} - - template - Pointer(Class* object, - ValueType (Class::*getMethod)() const, - void (Class::*setMethod)(const ValueType&)) : - m_interface(new Accessor(object, getMethod, setMethod)) {} - - template - Pointer(Class* object, - const ValueType& (Class::*getMethod)() const, - void (Class::*setMethod)(ValueType)) : - m_interface(new Accessor(object, getMethod, setMethod)) {} - - template - Pointer(Class* object, - ValueType (Class::*getMethod)() const, - void (Class::*setMethod)(ValueType)) : - m_interface(new Accessor(object, getMethod, setMethod)) {} - - ~Pointer() { - delete m_interface; - } - - inline const ValueType getValue() const { - debugAssert(m_interface != NULL); - return m_interface->get(); - } - - inline void setValue(const ValueType& v) { - debugAssert(m_interface != NULL); - m_interface->set(v); - } - - class IndirectValue { - private: - - friend class Pointer; - Pointer* pointer; - IndirectValue(Pointer* p) : pointer(p) {} - - public: - - void operator=(const ValueType& v) { - pointer->setValue(v); - } - - operator ValueType() const { - return pointer->getValue(); - } - - }; - - inline IndirectValue operator*() { - return IndirectValue(this); - } - - inline const ValueType operator*() const { - return getValue(); - } -}; - -} - -#endif diff --git a/externals/g3dlite/G3D/PositionTrait.h b/externals/g3dlite/G3D/PositionTrait.h deleted file mode 100644 index 67a4f64138a..00000000000 --- a/externals/g3dlite/G3D/PositionTrait.h +++ /dev/null @@ -1,7 +0,0 @@ -#ifndef G3D_POSITIONTRAIT_H -#define G3D_POSITIONTRAIT_H - -template -struct PositionTrait{}; - -#endif diff --git a/externals/g3dlite/G3D/PrecomputedRandom.h b/externals/g3dlite/G3D/PrecomputedRandom.h deleted file mode 100644 index 411d128c582..00000000000 --- a/externals/g3dlite/G3D/PrecomputedRandom.h +++ /dev/null @@ -1,110 +0,0 @@ -/** - @file PrecomputedRandom.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2009-03-31 - @edited 2009-03-31 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ -#ifndef G3D_PrecomputedRandom_h -#define G3D_PrecomputedRandom_h - -#include "G3D/platform.h" -#include "G3D/Random.h" - -namespace G3D { - -/** Fast random numbers using a precomputed data table. - - e.g., generates cosHemi about 13x faster than Random. - This is useful for quickly generating seeded random - numbers for reproducibility. G3D::Random takes a long - time to seed; this is instantaneous (providing the - precomputed data is already available.) - - Not threadsafe.*/ -class PrecomputedRandom : public Random { -public: - /** Put the cosHemi and the uniform together so that when - alternating between them we stay in cache. This is also packed - into a good size for SIMD and GPU operations.*/ - class HemiUniformData { - public: - float cosHemiX; - float cosHemiY; - float cosHemiZ; - float uniform; - }; - - class SphereBitsData { - public: - float sphereX; - float sphereY; - float sphereZ; - uint32 bits; - }; - -protected: - - /** Array of 2^n elements. */ - const HemiUniformData* m_hemiUniform; - const SphereBitsData* m_sphereBits; - - /** 2^n - 1; the AND mask for computing a fast modulo */ - int m_modMask; - - int m_index; - - /** If true, free m_hemiUniform and m_sphereBits in destructor */ - bool m_freeData; - -public: - - /* - \param dataSize Must be a power of 2 - \param data Will NOT be deleted by the destructor. - */ - PrecomputedRandom(const HemiUniformData* data1, const SphereBitsData* data2, int dataSize, uint32 seed = 0xF018A4D2); - - /** - \param dataSize Number of random numbers that can be requested before periodicity. Must be a power of 2. - */ - PrecomputedRandom(int dataSize, uint32 seed = 0xF018A4D2); - - ~PrecomputedRandom(); - - /** Each bit is random. Subclasses can choose to override just - this method and the other methods will all work automatically. */ - virtual uint32 bits(); - - // integer is inherited - - /** Uniform random float on the range [min, max] */ - virtual float uniform(float low, float high); - - /** Uniform random float on the range [0, 1] */ - virtual float uniform(); - - // gaussian is inherited - - /** Returns 3D unit vectors distributed according to - a cosine distribution about the z axis. */ - virtual void cosHemi(float& x, float& y, float& z); - - /** Returns 3D unit vectors distributed according to a cosine - power distribution (\f$ \mbox{cos}^k \theta \f$) about - the z-axis. */ - virtual void cosPowHemi(const float k, float& x, float& y, float& z); - - // hemi is inherited - - /** Returns 3D unit vectors uniformly distributed on the sphere */ - virtual void sphere(float& x, float& y, float& z); -}; - -} - -#endif diff --git a/externals/g3dlite/G3D/Quat.h b/externals/g3dlite/G3D/Quat.h deleted file mode 100644 index 9ef3d57b301..00000000000 --- a/externals/g3dlite/G3D/Quat.h +++ /dev/null @@ -1,725 +0,0 @@ -/** - @file Quat.h - - Quaternion - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2002-01-23 - @edited 2009-05-10 - */ - -#ifndef G3D_Quat_h -#define G3D_Quat_h - -#include "G3D/platform.h" -#include "G3D/g3dmath.h" -#include "G3D/Vector3.h" -#include "G3D/Matrix3.h" -#include - -namespace G3D { - -/** - Unit quaternions are used in computer graphics to represent - rotation about an axis. Any 3x3 rotation matrix can - be stored as a quaternion. - - A quaternion represents the sum of a real scalar and - an imaginary vector: ix + jy + kz + w. A unit quaternion - representing a rotation by A about axis v has the form - [sin(A/2)*v, cos(A/2)]. For a unit quaternion, q.conj() == q.inverse() - is a rotation by -A about v. -q is the same rotation as q - (negate both the axis and angle). - - A non-unit quaterion q represents the same rotation as - q.unitize() (Dam98 pg 28). - - Although quaternion-vector operations (eg. Quat + Vector3) are - well defined, they are not supported by this class because - they typically are bugs when they appear in code. - - Do not subclass. - - BETA API -- subject to change - @cite Erik B. Dam, Martin Koch, Martin Lillholm, Quaternions, Interpolation and Animation. Technical Report DIKU-TR-98/5, Department of Computer Science, University of Copenhagen, Denmark. 1998. - */ -class Quat { -private: - // Hidden operators - bool operator<(const Quat&) const; - bool operator>(const Quat&) const; - bool operator<=(const Quat&) const; - bool operator>=(const Quat&) const; - -public: - - /** - q = [sin(angle / 2) * axis, cos(angle / 2)] - - In Watt & Watt's notation, s = w, v = (x, y, z) - In the Real-Time Rendering notation, u = (x, y, z), w = w - */ - float x, y, z, w; - - /** - Initializes to a zero degree rotation. - */ - inline Quat() : x(0), y(0), z(0), w(1) {} - - Quat( - const Matrix3& rot); - - inline Quat(float _x, float _y, float _z, float _w) : - x(_x), y(_y), z(_z), w(_w) {} - - /** Defaults to a pure vector quaternion */ - inline Quat(const Vector3& v, float _w = 0) : x(v.x), y(v.y), z(v.z), w(_w) { - } - - /** - The real part of the quaternion. - */ - inline const float& real() const { - return w; - } - - inline float& real() { - return w; - } - - /** Note: two quats can represent the Quat::sameRotation and not be equal. */ - bool fuzzyEq(const Quat& q) { - return G3D::fuzzyEq(x, q.x) && G3D::fuzzyEq(y, q.y) && G3D::fuzzyEq(z, q.z) && G3D::fuzzyEq(w, q.w); - } - - /** True if these quaternions represent the same rotation (note that every rotation is - represented by two values; q and -q). - */ - bool sameRotation(const Quat& q) { - return fuzzyEq(q) || fuzzyEq(-q); - } - - inline Quat operator-() const { - return Quat(-x, -y, -z, -w); - } - - /** - Returns the imaginary part (x, y, z) - */ - inline const Vector3& imag() const { - return *(reinterpret_cast(this)); - } - - inline Vector3& imag() { - return *(reinterpret_cast(this)); - } - - /** q = [sin(angle/2)*axis, cos(angle/2)] */ - static Quat fromAxisAngleRotation( - const Vector3& axis, - float angle); - - /** Returns the axis and angle of rotation represented - by this quaternion (i.e. q = [sin(angle/2)*axis, cos(angle/2)]) */ - void toAxisAngleRotation( - Vector3& axis, - double& angle) const; - - void toAxisAngleRotation( - Vector3& axis, - float& angle) const { - double d; - toAxisAngleRotation(axis, d); - angle = (float)d; - } - - Matrix3 toRotationMatrix() const; - - void toRotationMatrix( - Matrix3& rot) const; - - /** - Spherical linear interpolation: linear interpolation along the - shortest (3D) great-circle route between two quaternions. - - Note: Correct rotations are expected between 0 and PI in the right order. - - @cite Based on Game Physics -- David Eberly pg 538-540 - @param threshold Critical angle between between rotations at which - the algorithm switches to normalized lerp, which is more - numerically stable in those situations. 0.0 will always slerp. - */ - Quat slerp( - const Quat& other, - float alpha, - float threshold = 0.05f) const; - - /** Normalized linear interpolation of quaternion components. */ - Quat nlerp(const Quat& other, float alpha) const; - - /** - Negates the imaginary part. - */ - inline Quat conj() const { - return Quat(-x, -y, -z, w); - } - - inline float sum() const { - return x + y + z + w; - } - - inline float average() const { - return sum() / 4.0f; - } - - inline Quat operator*(float s) const { - return Quat(x * s, y * s, z * s, w * s); - } - - inline Quat& operator*=(float s) { - x *= s; - y *= s; - z *= s; - w *= s; - return *this; - } - - /** @cite Based on Watt & Watt, page 360 */ - friend Quat operator* (float s, const Quat& q); - - inline Quat operator/(float s) const { - return Quat(x / s, y / s, z / s, w / s); - } - - inline float dot(const Quat& other) const { - return (x * other.x) + (y * other.y) + (z * other.z) + (w * other.w); - } - - /** Note that q-1 = q.conj() for a unit quaternion. - @cite Dam99 page 13 */ - inline Quat inverse() const { - return conj() / dot(*this); - } - - Quat operator-(const Quat& other) const; - - Quat operator+(const Quat& other) const; - - /** - Quaternion multiplication (composition of rotations). - Note that this does not commute. - */ - Quat operator*(const Quat& other) const; - - /* (*this) * other.inverse() */ - Quat operator/(const Quat& other) const { - return (*this) * other.inverse(); - } - - - /** Is the magnitude nearly 1.0? */ - inline bool isUnit(float tolerance = 1e-5) const { - return abs(dot(*this) - 1.0f) < tolerance; - } - - - inline float magnitude() const { - return sqrtf(dot(*this)); - } - - inline Quat log() const { - if ((x == 0) && (y == 0) && (z == 0)) { - if (w > 0) { - return Quat(0, 0, 0, ::logf(w)); - } else if (w < 0) { - // Log of a negative number. Multivalued, any number of the form - // (PI * v, ln(-q.w)) - return Quat((float)pi(), 0, 0, ::logf(-w)); - } else { - // log of zero! - return Quat((float)nan(), (float)nan(), (float)nan(), (float)nan()); - } - } else { - // Partly imaginary. - float imagLen = sqrtf(x * x + y * y + z * z); - float len = sqrtf(imagLen * imagLen + w * w); - float theta = atan2f(imagLen, (float)w); - float t = theta / imagLen; - return Quat(t * x, t * y, t * z, ::logf(len)); - } - } - /** log q = [Av, 0] where q = [sin(A) * v, cos(A)]. - Only for unit quaternions - debugAssertM(isUnit(), "Log only defined for unit quaternions"); - // Solve for A in q = [sin(A)*v, cos(A)] - Vector3 u(x, y, z); - double len = u.magnitude(); - - if (len == 0.0) { - return - } - double A = atan2((double)w, len); - Vector3 v = u / len; - - return Quat(v * A, 0); - } - */ - - /** exp q = [sin(A) * v, cos(A)] where q = [Av, 0]. - Only defined for pure-vector quaternions */ - inline Quat exp() const { - debugAssertM(w == 0, "exp only defined for vector quaternions"); - Vector3 u(x, y, z); - float A = u.magnitude(); - Vector3 v = u / A; - return Quat(sinf(A) * v, cosf(A)); - } - - - /** - Raise this quaternion to a power. For a rotation, this is - the effect of rotating x times as much as the original - quaterion. - - Note that q.pow(a).pow(b) == q.pow(a + b) - @cite Dam98 pg 21 - */ - inline Quat pow(float x) const { - return (log() * x).exp(); - } - - inline void unitize() { - float mag2 = dot(*this); - if (! G3D::fuzzyEq(mag2, 1.0f)) { - *this *= rsq(mag2); - } - } - - /** - Returns a unit quaterion obtained by dividing through by - the magnitude. - */ - inline Quat toUnit() const { - Quat x = *this; - x.unitize(); - return x; - } - - /** - The linear algebra 2-norm, sqrt(q dot q). This matches - the value used in Dam's 1998 tech report but differs from the - n(q) value used in Eberly's 1999 paper, which is the square of the - norm. - */ - inline float norm() const { - return magnitude(); - } - - // access quaternion as q[0] = q.x, q[1] = q.y, q[2] = q.z, q[3] = q.w - // - // WARNING. These member functions rely on - // (1) Quat not having virtual functions - // (2) the data packed in a 4*sizeof(float) memory block - const float& operator[] (int i) const; - float& operator[] (int i); - - /** Generate uniform random unit quaternion (i.e. random "direction") - @cite From "Uniform Random Rotations", Ken Shoemake, Graphics Gems III. - */ - static Quat unitRandom(); - - void deserialize(class BinaryInput& b); - void serialize(class BinaryOutput& b) const; - - // 2-char swizzles - - Vector2 xx() const; - Vector2 yx() const; - Vector2 zx() const; - Vector2 wx() const; - Vector2 xy() const; - Vector2 yy() const; - Vector2 zy() const; - Vector2 wy() const; - Vector2 xz() const; - Vector2 yz() const; - Vector2 zz() const; - Vector2 wz() const; - Vector2 xw() const; - Vector2 yw() const; - Vector2 zw() const; - Vector2 ww() const; - - // 3-char swizzles - - Vector3 xxx() const; - Vector3 yxx() const; - Vector3 zxx() const; - Vector3 wxx() const; - Vector3 xyx() const; - Vector3 yyx() const; - Vector3 zyx() const; - Vector3 wyx() const; - Vector3 xzx() const; - Vector3 yzx() const; - Vector3 zzx() const; - Vector3 wzx() const; - Vector3 xwx() const; - Vector3 ywx() const; - Vector3 zwx() const; - Vector3 wwx() const; - Vector3 xxy() const; - Vector3 yxy() const; - Vector3 zxy() const; - Vector3 wxy() const; - Vector3 xyy() const; - Vector3 yyy() const; - Vector3 zyy() const; - Vector3 wyy() const; - Vector3 xzy() const; - Vector3 yzy() const; - Vector3 zzy() const; - Vector3 wzy() const; - Vector3 xwy() const; - Vector3 ywy() const; - Vector3 zwy() const; - Vector3 wwy() const; - Vector3 xxz() const; - Vector3 yxz() const; - Vector3 zxz() const; - Vector3 wxz() const; - Vector3 xyz() const; - Vector3 yyz() const; - Vector3 zyz() const; - Vector3 wyz() const; - Vector3 xzz() const; - Vector3 yzz() const; - Vector3 zzz() const; - Vector3 wzz() const; - Vector3 xwz() const; - Vector3 ywz() const; - Vector3 zwz() const; - Vector3 wwz() const; - Vector3 xxw() const; - Vector3 yxw() const; - Vector3 zxw() const; - Vector3 wxw() const; - Vector3 xyw() const; - Vector3 yyw() const; - Vector3 zyw() const; - Vector3 wyw() const; - Vector3 xzw() const; - Vector3 yzw() const; - Vector3 zzw() const; - Vector3 wzw() const; - Vector3 xww() const; - Vector3 yww() const; - Vector3 zww() const; - Vector3 www() const; - - // 4-char swizzles - - Vector4 xxxx() const; - Vector4 yxxx() const; - Vector4 zxxx() const; - Vector4 wxxx() const; - Vector4 xyxx() const; - Vector4 yyxx() const; - Vector4 zyxx() const; - Vector4 wyxx() const; - Vector4 xzxx() const; - Vector4 yzxx() const; - Vector4 zzxx() const; - Vector4 wzxx() const; - Vector4 xwxx() const; - Vector4 ywxx() const; - Vector4 zwxx() const; - Vector4 wwxx() const; - Vector4 xxyx() const; - Vector4 yxyx() const; - Vector4 zxyx() const; - Vector4 wxyx() const; - Vector4 xyyx() const; - Vector4 yyyx() const; - Vector4 zyyx() const; - Vector4 wyyx() const; - Vector4 xzyx() const; - Vector4 yzyx() const; - Vector4 zzyx() const; - Vector4 wzyx() const; - Vector4 xwyx() const; - Vector4 ywyx() const; - Vector4 zwyx() const; - Vector4 wwyx() const; - Vector4 xxzx() const; - Vector4 yxzx() const; - Vector4 zxzx() const; - Vector4 wxzx() const; - Vector4 xyzx() const; - Vector4 yyzx() const; - Vector4 zyzx() const; - Vector4 wyzx() const; - Vector4 xzzx() const; - Vector4 yzzx() const; - Vector4 zzzx() const; - Vector4 wzzx() const; - Vector4 xwzx() const; - Vector4 ywzx() const; - Vector4 zwzx() const; - Vector4 wwzx() const; - Vector4 xxwx() const; - Vector4 yxwx() const; - Vector4 zxwx() const; - Vector4 wxwx() const; - Vector4 xywx() const; - Vector4 yywx() const; - Vector4 zywx() const; - Vector4 wywx() const; - Vector4 xzwx() const; - Vector4 yzwx() const; - Vector4 zzwx() const; - Vector4 wzwx() const; - Vector4 xwwx() const; - Vector4 ywwx() const; - Vector4 zwwx() const; - Vector4 wwwx() const; - Vector4 xxxy() const; - Vector4 yxxy() const; - Vector4 zxxy() const; - Vector4 wxxy() const; - Vector4 xyxy() const; - Vector4 yyxy() const; - Vector4 zyxy() const; - Vector4 wyxy() const; - Vector4 xzxy() const; - Vector4 yzxy() const; - Vector4 zzxy() const; - Vector4 wzxy() const; - Vector4 xwxy() const; - Vector4 ywxy() const; - Vector4 zwxy() const; - Vector4 wwxy() const; - Vector4 xxyy() const; - Vector4 yxyy() const; - Vector4 zxyy() const; - Vector4 wxyy() const; - Vector4 xyyy() const; - Vector4 yyyy() const; - Vector4 zyyy() const; - Vector4 wyyy() const; - Vector4 xzyy() const; - Vector4 yzyy() const; - Vector4 zzyy() const; - Vector4 wzyy() const; - Vector4 xwyy() const; - Vector4 ywyy() const; - Vector4 zwyy() const; - Vector4 wwyy() const; - Vector4 xxzy() const; - Vector4 yxzy() const; - Vector4 zxzy() const; - Vector4 wxzy() const; - Vector4 xyzy() const; - Vector4 yyzy() const; - Vector4 zyzy() const; - Vector4 wyzy() const; - Vector4 xzzy() const; - Vector4 yzzy() const; - Vector4 zzzy() const; - Vector4 wzzy() const; - Vector4 xwzy() const; - Vector4 ywzy() const; - Vector4 zwzy() const; - Vector4 wwzy() const; - Vector4 xxwy() const; - Vector4 yxwy() const; - Vector4 zxwy() const; - Vector4 wxwy() const; - Vector4 xywy() const; - Vector4 yywy() const; - Vector4 zywy() const; - Vector4 wywy() const; - Vector4 xzwy() const; - Vector4 yzwy() const; - Vector4 zzwy() const; - Vector4 wzwy() const; - Vector4 xwwy() const; - Vector4 ywwy() const; - Vector4 zwwy() const; - Vector4 wwwy() const; - Vector4 xxxz() const; - Vector4 yxxz() const; - Vector4 zxxz() const; - Vector4 wxxz() const; - Vector4 xyxz() const; - Vector4 yyxz() const; - Vector4 zyxz() const; - Vector4 wyxz() const; - Vector4 xzxz() const; - Vector4 yzxz() const; - Vector4 zzxz() const; - Vector4 wzxz() const; - Vector4 xwxz() const; - Vector4 ywxz() const; - Vector4 zwxz() const; - Vector4 wwxz() const; - Vector4 xxyz() const; - Vector4 yxyz() const; - Vector4 zxyz() const; - Vector4 wxyz() const; - Vector4 xyyz() const; - Vector4 yyyz() const; - Vector4 zyyz() const; - Vector4 wyyz() const; - Vector4 xzyz() const; - Vector4 yzyz() const; - Vector4 zzyz() const; - Vector4 wzyz() const; - Vector4 xwyz() const; - Vector4 ywyz() const; - Vector4 zwyz() const; - Vector4 wwyz() const; - Vector4 xxzz() const; - Vector4 yxzz() const; - Vector4 zxzz() const; - Vector4 wxzz() const; - Vector4 xyzz() const; - Vector4 yyzz() const; - Vector4 zyzz() const; - Vector4 wyzz() const; - Vector4 xzzz() const; - Vector4 yzzz() const; - Vector4 zzzz() const; - Vector4 wzzz() const; - Vector4 xwzz() const; - Vector4 ywzz() const; - Vector4 zwzz() const; - Vector4 wwzz() const; - Vector4 xxwz() const; - Vector4 yxwz() const; - Vector4 zxwz() const; - Vector4 wxwz() const; - Vector4 xywz() const; - Vector4 yywz() const; - Vector4 zywz() const; - Vector4 wywz() const; - Vector4 xzwz() const; - Vector4 yzwz() const; - Vector4 zzwz() const; - Vector4 wzwz() const; - Vector4 xwwz() const; - Vector4 ywwz() const; - Vector4 zwwz() const; - Vector4 wwwz() const; - Vector4 xxxw() const; - Vector4 yxxw() const; - Vector4 zxxw() const; - Vector4 wxxw() const; - Vector4 xyxw() const; - Vector4 yyxw() const; - Vector4 zyxw() const; - Vector4 wyxw() const; - Vector4 xzxw() const; - Vector4 yzxw() const; - Vector4 zzxw() const; - Vector4 wzxw() const; - Vector4 xwxw() const; - Vector4 ywxw() const; - Vector4 zwxw() const; - Vector4 wwxw() const; - Vector4 xxyw() const; - Vector4 yxyw() const; - Vector4 zxyw() const; - Vector4 wxyw() const; - Vector4 xyyw() const; - Vector4 yyyw() const; - Vector4 zyyw() const; - Vector4 wyyw() const; - Vector4 xzyw() const; - Vector4 yzyw() const; - Vector4 zzyw() const; - Vector4 wzyw() const; - Vector4 xwyw() const; - Vector4 ywyw() const; - Vector4 zwyw() const; - Vector4 wwyw() const; - Vector4 xxzw() const; - Vector4 yxzw() const; - Vector4 zxzw() const; - Vector4 wxzw() const; - Vector4 xyzw() const; - Vector4 yyzw() const; - Vector4 zyzw() const; - Vector4 wyzw() const; - Vector4 xzzw() const; - Vector4 yzzw() const; - Vector4 zzzw() const; - Vector4 wzzw() const; - Vector4 xwzw() const; - Vector4 ywzw() const; - Vector4 zwzw() const; - Vector4 wwzw() const; - Vector4 xxww() const; - Vector4 yxww() const; - Vector4 zxww() const; - Vector4 wxww() const; - Vector4 xyww() const; - Vector4 yyww() const; - Vector4 zyww() const; - Vector4 wyww() const; - Vector4 xzww() const; - Vector4 yzww() const; - Vector4 zzww() const; - Vector4 wzww() const; - Vector4 xwww() const; - Vector4 ywww() const; - Vector4 zwww() const; - Vector4 wwww() const; -}; - -inline Quat exp(const Quat& q) { - return q.exp(); -} - -inline Quat log(const Quat& q) { - return q.log(); -} - -inline G3D::Quat operator*(double s, const G3D::Quat& q) { - return q * (float)s; -} - -inline G3D::Quat operator*(float s, const G3D::Quat& q) { - return q * s; -} - -inline float& Quat::operator[] (int i) { - debugAssert(i >= 0); - debugAssert(i < 4); - return ((float*)this)[i]; -} - -inline const float& Quat::operator[] (int i) const { - debugAssert(i >= 0); - debugAssert(i < 4); - return ((float*)this)[i]; -} - -inline Quat Quat::operator-(const Quat& other) const { - return Quat(x - other.x, y - other.y, z - other.z, w - other.w); -} - -inline Quat Quat::operator+(const Quat& other) const { - return Quat(x + other.x, y + other.y, z + other.z, w + other.w); -} - -} // Namespace G3D - -// Outside the namespace to avoid overloading confusion for C++ -inline G3D::Quat pow(const G3D::Quat& q, double x) { - return q.pow((float)x); -} - - -#endif diff --git a/externals/g3dlite/G3D/Quat.inl b/externals/g3dlite/G3D/Quat.inl deleted file mode 100644 index 9e4c861d93b..00000000000 --- a/externals/g3dlite/G3D/Quat.inl +++ /dev/null @@ -1,36 +0,0 @@ -/** - Quat.inl - - @cite Quaternion implementation based on Watt & Watt page 363. - Thanks to Max McGuire for slerp optimizations. - - @maintainer Morgan McGuire, matrix@graphics3d.com - - @created 2002-01-23 - @edited 2004-03-04 - */ - -namespace G3D { - -inline float& Quat::operator[] (int i) { - debugAssert(i >= 0); - debugAssert(i < 4); - return ((float*)this)[i]; -} - -inline const float& Quat::operator[] (int i) const { - debugAssert(i >= 0); - debugAssert(i < 4); - return ((float*)this)[i]; -} - -inline Quat Quat::operator-(const Quat& other) const { - return Quat(x - other.x, y - other.y, z - other.z, w - other.w); -} - -inline Quat Quat::operator+(const Quat& other) const { - return Quat(x + other.x, y + other.y, z + other.z, w + other.w); -} - -} - diff --git a/externals/g3dlite/G3D/Queue.h b/externals/g3dlite/G3D/Queue.h deleted file mode 100644 index 36573265d1a..00000000000 --- a/externals/g3dlite/G3D/Queue.h +++ /dev/null @@ -1,364 +0,0 @@ -/** - @file Queue.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2002-07-09 - @edited 2008-12-20 - */ - -#ifndef G3D_QUEUE_H -#define G3D_QUEUE_H - -#include "G3D/platform.h" -#include "G3D/System.h" -#include "G3D/debug.h" - -namespace G3D { - -/** - Locate the indices of the break between of the two - sections of the circular queue. These are used to - construct two for loops that iterate over the whole - sequence without using the modulo operator. - - [0 ... secondEnd) [head .... firstEnd) - */ -#define FIND_ENDS \ - int firstEnd = head + num;\ - int secondEnd = 0;\ - if (firstEnd > numAllocated) {\ - secondEnd = firstEnd - numAllocated;\ - firstEnd = numAllocated;\ - } - - -/** - Dynamic queue that uses a circular buffer for performance. - - Faster than std::deque for objects with constructors. - */ -template -class Queue { -private: - // - // |<---- num ---->| - // [ | | | | | | | | | | | | | ] - // ^ - // | - // head - // - // - - /** - Only num elements are initialized. - */ - T* data; - - /** - Index of the next element to be dequeue-d in data. - */ - int head; - - /** - Number of elements (including head) that are visible and initialized. - */ - int num; - - /** - Size of data array in elements. - */ - int numAllocated; - - /** If a clear was needed, assumes it already occured */ - void _copy(const Queue& other) { - debugAssert(data == NULL); - data = (T*)System::malloc(sizeof(T) * other.numAllocated); - debugAssert(data); - head = other.head; - num = other.num; - numAllocated = other.numAllocated; - - FIND_ENDS; - - for (int i = head; i < firstEnd; ++i) { - new (data + i)T(other.data[i]); - } - - for (int i = 0; i < secondEnd; ++i) { - new (data + i)T(other.data[i]); - } - } - - - /** - Computes a data array index from a queue position. The queue position - may be negative. - */ - inline int index(int i) const { - return (head + i + numAllocated) % numAllocated; - } - - /** - Allocates newSize elements and repacks the array. - */ - void repackAndRealloc(int newSize) { - // TODO: shrink queue - T* old = data; - data = (T*)System::malloc(newSize * sizeof(T)); - debugAssert(data != NULL); - - FIND_ENDS; - - int j = 0; - for (int i = head; i < firstEnd; ++i, ++j) { - new (data + j)T(old[i]); - (old + i)->~T(); - } - - for (int i = 0; i < secondEnd; ++i, ++j) { - new (data + j)T(old[i]); - (old + i)->~T(); - } - - head = 0; - System::free(old); - numAllocated = newSize; - } - - /** - Ensure that there is at least one element between - the tail and head, wrapping around in the circular - buffer. - */ - inline void reserveSpace() { - if (num == numAllocated) { - repackAndRealloc(numAllocated * 3 + 20); - } - } - -public: - - Queue() : - data(NULL), - head(0), - num(0), - numAllocated(0) { - } - - - /** - Copy constructor - */ - Queue(const Queue& other) : data(NULL) { - _copy(other); - } - - - /** - Destructor does not delete() the objects if T is a pointer type - (e.g. T = int*) instead, it deletes the pointers themselves and - leaves the objects. Call deleteAll if you want to dealocate - the objects referenced. - */ - virtual ~Queue() { - clear(); - } - - /** - Insert a new element into the front of the queue - (a traditional queue only uses pushBack). - */ - inline void pushFront(const T& e) { - reserveSpace(); - - // Get the index of head-1 - int i = index(-1); - - // Call the constructor on the newly exposed element. - new (data + i)T(e); - - // Reassign the head to point to this index - head = i; - ++num; - } - - /** - Insert a new element at the end of the queue. - */ - inline void pushBack(const T& e) { - reserveSpace(); - - // Get the index of 1+tail - int i = index(num); - - // Initialize that element - new (data + i)T(e); - ++num; - } - - /** - pushBack - */ - inline void enqueue(const T& e) { - pushBack(e); - } - - - /** - Remove the last element from the queue. The queue will never - shrink in size. (A typical queue only uses popFront). - */ - inline T popBack() { - int tail = index(num - 1); - T result(data[tail]); - - // Call the destructor - (data + tail)->~T(); - --num; - - return result; - } - - /** - Remove the next element from the head of the queue. The queue will never - shrink in size. */ - inline T popFront() { - T result(data[head]); - // Call the destructor - (data + head)->~T(); - head = (head + 1) % numAllocated; - --num; - return result; - } - - - /** - popFront - */ - inline T dequeue() { - return popFront(); - } - - /** - Removes all elements (invoking their destructors). - - @param freeStorage If false, the underlying array is not deallocated - (allowing fast push in the future), however, the size of the Queue - is reported as zero. - - */ - void clear(bool freeStorage = true) { - - FIND_ENDS; - - // Invoke the destructors on the elements - int i; - for (i = head; i < firstEnd; ++i) { - (data + i)->~T(); - } - - for (i = 0; i < secondEnd; ++i) { - (data + i)->~T(); - } - - num = 0; - head = 0; - if (freeStorage) { - numAllocated = 0; - System::free(data); - data = NULL; - } - } - - /** Clear without freeing the underlying array. */ - void fastClear() { - clear(false); - } - - /** - Assignment operator. - */ - Queue& operator=(const Queue& other) { - clear(); - _copy(other); - return *this; - } - - /** - Number of elements in the queue. - */ - inline int size() const { - return num; - } - - /** - Number of elements in the queue. - */ - inline int length() const { - return size(); - } - - /** - Performs bounds checks in debug mode - */ - inline T& operator[](int n) { - debugAssert((n >= 0) && (n < num)); - return data[index(n)]; - } - - /** - Performs bounds checks in debug mode - */ - inline const T& operator[](int n) const { - debugAssert((n >= 0) && (n < num)); - return data[index(n)]; - } - - - /** Returns the back element */ - inline const T& last() const { - return (*this)[size() - 1]; - } - - inline T& last() { - return (*this)[size() - 1]; - } - - /** - Returns true if the given element is in the queue. - */ - bool contains(const T& e) const { - for (int i = 0; i < size(); ++i) { - if ((*this)[i] == e) { - return true; - } - } - - return false; - } - - /** - Calls delete on all objects[0...size-1] - and sets the queue size to zero. - */ - void deleteAll() { - FIND_ENDS; - - int i; - for (i = 0; i < secondEnd; ++i) { - delete data[i]; - } - - for (i = head; i < firstEnd; ++i) { - delete data[i]; - } - clear(); - } -}; - -#undef FIND_ENDS - -}; // namespace - -#endif diff --git a/externals/g3dlite/G3D/Random.h b/externals/g3dlite/G3D/Random.h deleted file mode 100644 index 54491d06f1b..00000000000 --- a/externals/g3dlite/G3D/Random.h +++ /dev/null @@ -1,139 +0,0 @@ -/** - @file Random.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2009-01-02 - @edited 2009-03-20 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ -#ifndef G3D_Random_h -#define G3D_Random_h - -#include "G3D/platform.h" -#include "G3D/g3dmath.h" -#include "G3D/GMutex.h" - -namespace G3D { - -/** Random number generator. - - Threadsafe. - - Useful for generating consistent random numbers across platforms - and when multiple threads are involved. - - Uses the Fast Mersenne Twister (FMT-19937) algorithm. - - On average, uniform() runs about 2x-3x faster than rand(). - - @cite http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/index.html - - On OS X, Random is about 10x faster than drand48() (which is - threadsafe) and 4x faster than rand() (which is not threadsafe). - */ -class Random { -protected: - - /** Constants (important for the algorithm; do not modify) */ - enum { - N = 624, - M = 397, - R = 31, - U = 11, - S = 7, - T = 15, - L = 18, - A = 0x9908B0DF, - B = 0x9D2C5680, - C = 0xEFC60000}; - - /** - Prevents multiple overlapping calls to generate(). - */ - Spinlock lock; - - /** State vector (these are the next N values that will be returned) */ - uint32* state; - - /** Index into state */ - int index; - - bool m_threadsafe; - - /** Generate the next N ints, and store them for readback later. - Called from bits() */ - virtual void generate(); - - /** For subclasses. The void* parameter is just to distinguish this from the - public constructor.*/ - Random(void*); - -public: - - /** \param threadsafe Set to false if you know that this random - will only be used on a single thread. This eliminates the - lock and improves performance on some platforms. - */ - Random(uint32 seed = 0xF018A4D2, bool threadsafe = true); - - virtual ~Random(); - - /** Each bit is random. Subclasses can choose to override just - this method and the other methods will all work automatically. */ - virtual uint32 bits(); - - /** Uniform random integer on the range [min, max] */ - virtual int integer(int min, int max); - - /** Uniform random float on the range [min, max] */ - virtual inline float uniform(float low, float high) { - // We could compute the ratio in double precision here for - // about 1.5x slower performance and slightly better - // precision. - return low + (high - low) * ((float)bits() / (float)0xFFFFFFFFUL); - } - - /** Uniform random float on the range [0, 1] */ - virtual inline float uniform() { - // We could compute the ratio in double precision here for - // about 1.5x slower performance and slightly better - // precision. - const float norm = 1.0f / (float)0xFFFFFFFFUL; - return (float)bits() * norm; - } - - /** Normally distributed reals. */ - virtual float gaussian(float mean, float stdev); - - /** Returns 3D unit vectors distributed according to - a cosine distribution about the z-axis. */ - virtual void cosHemi(float& x, float& y, float& z); - - /** Returns 3D unit vectors distributed according to a cosine - power distribution (\f$ \cos^k \theta \f$) about - the z-axis. */ - virtual void cosPowHemi(const float k, float& x, float& y, float& z); - - /** Returns 3D unit vectors uniformly distributed on the - hemisphere about the z-axis. */ - virtual void hemi(float& x, float& y, float& z); - - /** Returns 3D unit vectors uniformly distributed on the sphere */ - virtual void sphere(float& x, float& y, float& z); - - /** - A shared instance for when the performance and features but not - consistency of the class are desired. It is slightly (10%) - faster to use a distinct instance than to use the common one. - - Threadsafe. - */ - static Random& common(); -}; - -} - -#endif diff --git a/externals/g3dlite/G3D/Ray.h b/externals/g3dlite/G3D/Ray.h deleted file mode 100644 index bfee9243343..00000000000 --- a/externals/g3dlite/G3D/Ray.h +++ /dev/null @@ -1,371 +0,0 @@ -/** - @file Ray.h - - Ray class - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2002-07-12 - @edited 2009-06-29 - */ - -#ifndef G3D_Ray_h -#define G3D_Ray_h - -#include "G3D/platform.h" -#include "G3D/Vector3.h" -#include "G3D/Triangle.h" - -namespace G3D { - -/** - A 3D Ray. - */ -class Ray { -private: - friend class Intersect; - - Vector3 m_origin; - - /** Unit length */ - Vector3 m_direction; - - /** 1.0 / direction */ - Vector3 m_invDirection; - - - // The following are for the "ray slope" optimization from - // "Fast Ray / Axis-Aligned Bounding Box Overlap Tests using Ray Slopes" - // by Martin Eisemann, Thorsten Grosch, Stefan Müller and Marcus Magnor - // Computer Graphics Lab, TU Braunschweig, Germany and - // University of Koblenz-Landau, Germany*/ - enum Classification {MMM, MMP, MPM, MPP, PMM, PMP, PPM, PPP, POO, MOO, OPO, OMO, OOP, OOM, OMM, OMP, OPM, OPP, MOM, MOP, POM, POP, MMO, MPO, PMO, PPO}; Classification classification; - // ray slope - float ibyj, jbyi, kbyj, jbyk, ibyk, kbyi; - // Precomputed components - float c_xy, c_xz, c_yx, c_yz, c_zx, c_zy; - -public: - - void set(const Vector3& origin, const Vector3& direction); - - inline const Vector3& origin() const { - return m_origin; - } - - /** Unit direction vector. */ - inline const Vector3& direction() const { - return m_direction; - } - - /** Component-wise inverse of direction vector. May have inf() components */ - inline const Vector3& invDirection() const { - return m_invDirection; - } - - inline Ray() { - set(Vector3::zero(), Vector3::unitX()); - } - - inline Ray(const Vector3& origin, const Vector3& direction) { - set(origin, direction); - } - - Ray(class BinaryInput& b); - - void serialize(class BinaryOutput& b) const; - void deserialize(class BinaryInput& b); - - /** - Creates a Ray from a origin and a (nonzero) unit direction. - */ - static Ray fromOriginAndDirection(const Vector3& point, const Vector3& direction) { - return Ray(point, direction); - } - - /** Advances the origin along the direction by @a distance */ - inline Ray bump(float distance) const { - return Ray(m_origin + m_direction * distance, m_direction); - } - - /** Advances the origin along the @a bumpDirection by @a distance and returns the new ray*/ - inline Ray bump(float distance, const Vector3& bumpDirection) const { - return Ray(m_origin + bumpDirection * distance, m_direction); - } - - /** - Returns the closest point on the Ray to point. - */ - Vector3 closestPoint(const Vector3& point) const { - float t = m_direction.dot(point - m_origin); - if (t < 0) { - return m_origin; - } else { - return m_origin + m_direction * t; - } - } - - /** - Returns the closest distance between point and the Ray - */ - float distance(const Vector3& point) const { - return (closestPoint(point) - point).magnitude(); - } - - /** - Returns the point where the Ray and plane intersect. If there - is no intersection, returns a point at infinity. - - Planes are considered one-sided, so the ray will not intersect - a plane where the normal faces in the traveling direction. - */ - Vector3 intersection(const class Plane& plane) const; - - /** - Returns the distance until intersection with the sphere or the (solid) ball bounded by the sphere. - Will be 0 if inside the sphere, inf if there is no intersection. - - The ray direction is not normalized. If the ray direction - has unit length, the distance from the origin to intersection - is equal to the time. If the direction does not have unit length, - the distance = time * direction.length(). - - See also the G3D::CollisionDetection "movingPoint" methods, - which give more information about the intersection. - - \param solid If true, rays inside the sphere immediately intersect (good for collision detection). If false, they hit the opposite side of the sphere (good for ray tracing). - */ - float intersectionTime(const class Sphere& sphere, bool solid = false) const; - - float intersectionTime(const class Plane& plane) const; - - float intersectionTime(const class Box& box) const; - - float intersectionTime(const class AABox& box) const; - - /** - The three extra arguments are the weights of vertices 0, 1, and 2 - at the intersection point; they are useful for texture mapping - and interpolated normals. - */ - float intersectionTime( - const Vector3& v0, const Vector3& v1, const Vector3& v2, - const Vector3& edge01, const Vector3& edge02, - double& w0, double& w1, double& w2) const; - - /** - Ray-triangle intersection for a 1-sided triangle. Fastest version. - @cite http://www.acm.org/jgt/papers/MollerTrumbore97/ - http://www.graphics.cornell.edu/pubs/1997/MT97.html - */ - inline float intersectionTime( - const Vector3& vert0, - const Vector3& vert1, - const Vector3& vert2, - const Vector3& edge01, - const Vector3& edge02) const; - - - inline float intersectionTime( - const Vector3& vert0, - const Vector3& vert1, - const Vector3& vert2) const { - - return intersectionTime(vert0, vert1, vert2, vert1 - vert0, vert2 - vert0); - } - - - inline float intersectionTime( - const Vector3& vert0, - const Vector3& vert1, - const Vector3& vert2, - double& w0, - double& w1, - double& w2) const { - - return intersectionTime(vert0, vert1, vert2, vert1 - vert0, vert2 - vert0, w0, w1, w2); - } - - /* One-sided triangle - */ - inline float intersectionTime(const Triangle& triangle) const { - return intersectionTime( - triangle.vertex(0), triangle.vertex(1), triangle.vertex(2), - triangle.edge01(), triangle.edge02()); - } - - inline float intersectionTime( - const Triangle& triangle, - double& w0, - double& w1, - double& w2) const { - return intersectionTime(triangle.vertex(0), triangle.vertex(1), triangle.vertex(2), - triangle.edge01(), triangle.edge02(), w0, w1, w2); - } - - /** Refracts about the normal - using G3D::Vector3::refractionDirection - and bumps the ray slightly from the newOrigin. */ - Ray refract( - const Vector3& newOrigin, - const Vector3& normal, - float iInside, - float iOutside) const; - - /** Reflects about the normal - using G3D::Vector3::reflectionDirection - and bumps the ray slightly from - the newOrigin. */ - Ray reflect( - const Vector3& newOrigin, - const Vector3& normal) const; -}; - - -#define EPSILON 0.000001 -#define CROSS(dest,v1,v2) \ - dest[0]=v1[1]*v2[2]-v1[2]*v2[1]; \ - dest[1]=v1[2]*v2[0]-v1[0]*v2[2]; \ - dest[2]=v1[0]*v2[1]-v1[1]*v2[0]; - -#define DOT(v1,v2) (v1[0]*v2[0]+v1[1]*v2[1]+v1[2]*v2[2]) - -#define SUB(dest,v1,v2) \ - dest[0]=v1[0]-v2[0]; \ - dest[1]=v1[1]-v2[1]; \ - dest[2]=v1[2]-v2[2]; - -inline float Ray::intersectionTime( - const Vector3& vert0, - const Vector3& vert1, - const Vector3& vert2, - const Vector3& edge1, - const Vector3& edge2) const { - - (void)vert1; - (void)vert2; - - // Barycenteric coords - float u, v; - - float tvec[3], pvec[3], qvec[3]; - - // begin calculating determinant - also used to calculate U parameter - CROSS(pvec, m_direction, edge2); - - // if determinant is near zero, ray lies in plane of triangle - const float det = DOT(edge1, pvec); - - if (det < EPSILON) { - return finf(); - } - - // calculate distance from vert0 to ray origin - SUB(tvec, m_origin, vert0); - - // calculate U parameter and test bounds - u = DOT(tvec, pvec); - if ((u < 0.0f) || (u > det)) { - // Hit the plane outside the triangle - return finf(); - } - - // prepare to test V parameter - CROSS(qvec, tvec, edge1); - - // calculate V parameter and test bounds - v = DOT(m_direction, qvec); - if ((v < 0.0f) || (u + v > det)) { - // Hit the plane outside the triangle - return finf(); - } - - - // Case where we don't need correct (u, v): - const float t = DOT(edge2, qvec); - - if (t >= 0.0f) { - // Note that det must be positive - return t / det; - } else { - // We had to travel backwards in time to intersect - return finf(); - } -} - - -inline float Ray::intersectionTime( - const Vector3& vert0, - const Vector3& vert1, - const Vector3& vert2, - const Vector3& edge1, - const Vector3& edge2, - double& w0, - double& w1, - double& w2) const { - - (void)vert1; - (void)vert2; - - // Barycenteric coords - float u, v; - - float tvec[3], pvec[3], qvec[3]; - - // begin calculating determinant - also used to calculate U parameter - CROSS(pvec, m_direction, edge2); - - // if determinant is near zero, ray lies in plane of triangle - const float det = DOT(edge1, pvec); - - if (det < EPSILON) { - return finf(); - } - - // calculate distance from vert0 to ray origin - SUB(tvec, m_origin, vert0); - - // calculate U parameter and test bounds - u = DOT(tvec, pvec); - if ((u < 0.0f) || (u > det)) { - // Hit the plane outside the triangle - return finf(); - } - - // prepare to test V parameter - CROSS(qvec, tvec, edge1); - - // calculate V parameter and test bounds - v = DOT(m_direction, qvec); - if ((v < 0.0f) || (u + v > det)) { - // Hit the plane outside the triangle - return finf(); - } - - float t = DOT(edge2, qvec); - - if (t >= 0) { - const float inv_det = 1.0f / det; - t *= inv_det; - u *= inv_det; - v *= inv_det; - - w0 = (1.0f - u - v); - w1 = u; - w2 = v; - - return t; - } else { - // We had to travel backwards in time to intersect - return finf(); - } -} - -#undef EPSILON -#undef CROSS -#undef DOT -#undef SUB - -}// namespace - -#endif diff --git a/externals/g3dlite/G3D/Rect2D.h b/externals/g3dlite/G3D/Rect2D.h deleted file mode 100644 index 2fb58c50465..00000000000 --- a/externals/g3dlite/G3D/Rect2D.h +++ /dev/null @@ -1,417 +0,0 @@ -/** - @file Rect2D.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2003-11-13 - @created 2009-11-16 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_Rect2D_h -#define G3D_Rect2D_h - -// Linux defines this as a macro -#ifdef border -#undef border -#endif - -#include "G3D/platform.h" -#include "G3D/Array.h" -#include "G3D/Vector2.h" - -#ifdef _MSC_VER -// Turn off "conditional expression is constant" warning; MSVC generates this -// for debug assertions in inlined methods. -# pragma warning (disable : 4127) -#endif - - -namespace G3D { - -class Any; - -/** - If you are using this class for pixel rectangles, keep in mind that the last - pixel you can draw to is at x0() + width() - 1. - */ -class Rect2D { -private: - Vector2 min, max; - - /** - Returns true if the whole polygon is clipped. - @param p Value of the point - @param axis Index [0 or 1] of the axis to clip along? - @param clipGreater Are we clipping greater than or less than the line? - @param inPoly Polygon being clipped - @param outPoly The clipped polygon - */ - template - static bool clipSide2D( - const float p, bool clipGreater, int axis, - const Array& inPoly, Array& outPoly) { - - outPoly.clear(); - int i0 = -1; - - Vector2 pt1; - bool c1 = true; - - float negate = clipGreater ? -1 : 1; - - // Find a point that is not clipped - for (i0 = 0; (i0 < inPoly.length()) && c1; ++i0) { - pt1 = inPoly[i0]; - c1 = (negate * pt1[axis]) < (negate * p); - } - - // We incremented i0 one time to many - --i0; - - if (c1) { - // We could not find an unclipped point - return true; - } - - outPoly.append(pt1); - - // for each point in inPoly, - // if the point is outside the side and the previous one was also outside, continue - // if the point is outside the side and the previous one was inside, cut the line - // if the point is inside the side and the previous one was also inside, append the points - // if the point is inside the side and the previous one was outside, cut the line - for (int i = 1; i <= inPoly.length(); ++i) { - T pt2 = inPoly[(i + i0) % inPoly.length()]; - bool c2 = (negate * pt2[axis]) < (negate * p); - - if (c1 ^ c2) { - - if (!c1 && c2 && (i > 1)) { - // Unclipped to clipped trasition and not the first iteration - outPoly.append(pt1); - } - - // only one point is clipped, find where the line crosses the clipping plane - - - float alpha; - if (pt2[axis] == pt1[axis]) { - alpha = 0; - } else { - alpha = (p - pt1[axis]) / (pt2[axis] - pt1[axis]); - } - outPoly.append(pt1.lerp(pt2, alpha)); - } else if (! (c1 || c2) && (i != 1)) { - // neither point is clipped (don't do this the first time - // because we appended the first pt before the loop) - outPoly.append(pt1); - } - - pt1 = pt2; - c1 = c2; - } - - return false; - } - -public: - - /** \param any Must either Rect2D::xywh(#, #, #, #) or Rect2D::xyxy(#, #, #, #)*/ - Rect2D(const Any& any); - - /** Converts the Rect2D to an Any. */ - operator Any() const; - - Rect2D() : min(0, 0), max(0, 0) {} - - /** Creates a rectangle at 0,0 with the given width and height*/ - Rect2D(const Vector2& wh) : min(0, 0), max(wh.x, wh.y) {} - - /** Computes a rectangle that contains both @a a and @a b. - Note that even if @a or @b has zero area, its origin will be included.*/ - Rect2D(const Rect2D& a, const Rect2D& b) { - min = a.min.min(b.min); - max = a.max.max(b.max); - } - - /** @brief Uniformly random point on the interior */ - Vector2 randomPoint() const { - return Vector2(uniformRandom(0, max.x - min.x) + min.x, - uniformRandom(0, max.y - min.y) + min.y); - } - - float width() const { - return max.x - min.x; - } - - float height() const { - return max.y - min.y; - } - - float x0() const { - return min.x; - } - - float x1() const { - return max.x; - } - - float y0() const { - return min.y; - } - - float y1() const { - return max.y; - } - - /** Min, min corner */ - Vector2 x0y0() const { - return min; - } - - Vector2 x1y0() const { - return Vector2(max.x, min.y); - } - - Vector2 x0y1() const { - return Vector2(min.x, max.y); - } - - /** Max,max corner */ - Vector2 x1y1() const { - return max; - } - - /** Width and height */ - Vector2 wh() const { - return max - min; - } - - Vector2 center() const { - return (max + min) * 0.5; - } - - float area() const { - return width() * height(); - } - - bool isFinite() const { - return (min.isFinite() && max.isFinite()); - } - - Rect2D lerp(const Rect2D& other, float alpha) const { - Rect2D out; - - out.min = min.lerp(other.min, alpha); - out.max = max.lerp(other.max, alpha); - - return out; - } - - static Rect2D xyxy(float x0, float y0, float x1, float y1) { - Rect2D r; - - r.min.x = G3D::min(x0, x1); - r.min.y = G3D::min(y0, y1); - r.max.x = G3D::max(x0, x1); - r.max.y = G3D::max(y0, y1); - - return r; - } - - static Rect2D xyxy(const Vector2& v0, const Vector2& v1) { - Rect2D r; - - r.min = v0.min(v1); - r.max = v0.max(v1); - - return r; - } - - static Rect2D xywh(float x, float y, float w, float h) { - return xyxy(x, y, x + w, y + h); - } - - static Rect2D xywh(const Vector2& v, const Vector2& w) { - return xyxy(v.x, v.y, v.x + w.x, v.y + w.y); - } - - /** Constructs a Rect2D with infinite boundaries. - Use isFinite() to test either min or max. - */ - static Rect2D inf() { - return xyxy(Vector2::inf(), Vector2::inf()); - } - - bool contains(const Vector2& v) const { - return (v.x >= min.x) && (v.y >= min.y) && (v.x <= max.x) && (v.y <= max.y); - } - - bool contains(const Rect2D& r) const { - return (min.x <= r.min.x) && (min.y <= r.min.y) && - (max.x >= r.max.x) && (max.y >= r.max.y); - } - - /** True if there is non-zero area to the intersection between @a this and @a r. - Note that two rectangles that are adjacent do not intersect because there is - zero area to the overlap, even though one of them "contains" the corners of the other.*/ - bool intersects(const Rect2D& r) const { - return (min.x < r.max.x) && (min.y < r.max.y) && - (max.x > r.min.x) && (max.y > r.min.y); - } - - /** Like intersection, but counts the adjacent case as touching. */ - bool intersectsOrTouches(const Rect2D& r) const { - return (min.x <= r.max.x) && (min.y <= r.max.y) && - (max.x >= r.min.x) && (max.y >= r.min.y); - } - - Rect2D operator*(float s) const { - return xyxy(min.x * s, min.y * s, max.x * s, max.y * s); - } - - Rect2D operator/(float s) const { - return xyxy(min / s, max / s); - } - - Rect2D operator/(const Vector2& s) const { - return xyxy(min / s, max / s); - } - - Rect2D operator+(const Vector2& v) const { - return xyxy(min + v, max + v); - } - - Rect2D operator-(const Vector2& v) const { - return xyxy(min - v, max - v); - } - - bool operator==(const Rect2D& other) const { - return (min == other.min) && (max == other.max); - } - - bool operator!=(const Rect2D& other) const { - return (min != other.min) || (max != other.max); - } - - /** Returns the corners in the order: (min,min), (max,min), (max,max), (min,max). */ - Vector2 corner(int i) const { - debugAssert(i >= 0 && i < 4); - switch (i & 3) { - case 0: - return Vector2(min.x, min.y); - case 1: - return Vector2(max.x, min.y); - case 2: - return Vector2(max.x, max.y); - case 3: - return Vector2(min.x, max.y); - default: - // Should never get here - return Vector2(0, 0); - } - } - - - /** @deprecated - @sa expand() */ - Rect2D border(float delta) const { - return Rect2D::xywh(x0() + delta, - y0() + delta, - width() - 2.0f * delta, - height() - 2.0f * delta); - } - - /** Returns a new Rect2D that is bigger/smaller by the specified amount - (negative is shrink.) */ - Rect2D expand(float delta) const { - float newX = x0() - delta; - float newY = y0() - delta; - float newW = width() + 2.0f * delta; - float newH = height() + 2.0f * delta; - - if (newW < 0.0f) { - newX = (x0() + width()) / 2.0f; - newW = 0.0f; - } - - if (newH < 0.0f) { - newY = (y0() + height()) / 2.0f; - newH = 0.0f; - } - return Rect2D::xywh(newX, newY, newW, newH); - } - - /** - Clips so that the rightmost point of the outPoly is at rect.x1 (e.g. a 800x600 window produces - rightmost point 799, not 800). The results are suitable for pixel rendering if iRounded. - Templated so that it will work for Vector2,3,4 (the z and w components are interpolated linearly). - The template parameter must define T.lerp and contain x and y components. - - If the entire polygon is clipped by a single side, the result will be empty. - The result might also have zero area but not be empty. - */ - template - void clip(const Array& inPoly, Array& outPoly) const { - - const bool greaterThan = true; - const bool lessThan = false; - const int X = 0; - const int Y = 1; - - Array temp; - - bool entirelyClipped = - clipSide2D(x0(), lessThan, X, inPoly, temp) || - clipSide2D(x1(), greaterThan, X, temp, outPoly) || - clipSide2D(y0(), lessThan, Y, outPoly, temp) || - clipSide2D(y1(), greaterThan, Y, temp, outPoly); - - if (entirelyClipped) { - outPoly.clear(); - } - } - - - /** Returns the largest, centered Rect2D that can fit inside this - while maintaining the aspect ratio of x:y. Convenient for - displaying images in odd-shaped windows. - */ - Rect2D largestCenteredSubRect(float ww, float hh) const { - float textureAspect = hh / ww; - float viewAspect = height() / width(); - - if (viewAspect > textureAspect) { - // The view is too tall - float h = width() * textureAspect; - float y = (height() - h) / 2; - return Rect2D::xywh(0, y, width(), h) + corner(0); - } else { - // The view is too wide - float w = height() / textureAspect; - float x = (width() - w) / 2; - return Rect2D::xywh(x, 0, w, height()) + corner(0); - } - } - - /** - Returns the overlap region between the two rectangles. This may have zero area - if they do not intersect. See the two-Rect2D constructor for a way to compute - a union-like rectangle. - */ - Rect2D intersect(const Rect2D& other) const { - if (intersects(other)) { - return Rect2D::xyxy(min.max(other.min), max.min(other.max)); - }else{ - return Rect2D::xywh(0, 0, 0, 0); - } - } -}; - -typedef Rect2D AABox2D; -} - -#endif diff --git a/externals/g3dlite/G3D/ReferenceCount.h b/externals/g3dlite/G3D/ReferenceCount.h deleted file mode 100644 index 84591c6d8e5..00000000000 --- a/externals/g3dlite/G3D/ReferenceCount.h +++ /dev/null @@ -1,570 +0,0 @@ -/** - @file ReferenceCount.h - - Reference Counting Garbage Collector for C++ - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - @cite Adapted and extended from Justin Miller's "RGC" class that appeared in BYTE magazine. - @cite See also http://www.jelovic.com/articles/cpp_without_memory_errors_slides.htm - - @created 2001-10-23 - @edited 2009-04-25 -*/ -#ifndef G3D_ReferenceCount_h -#define G3D_ReferenceCount_h - -#include "G3D/platform.h" -#include "G3D/debug.h" -#include "G3D/AtomicInt32.h" - -namespace G3D { - -#ifdef _MSC_VER -// Turn off "conditional expression is constant" warning; MSVC generates this -// for debug assertions in inlined methods. -# pragma warning (disable : 4127) -#endif - -/** Base class for WeakReferenceCountedPointer */ -class _WeakPtr { -public: - inline virtual ~_WeakPtr() {} - -protected: - friend class ReferenceCountedObject; - - /** Called by ReferenceCountedObject to tell a weak pointer that its underlying object was collected. */ - virtual void objectCollected() = 0; -}; - -/** Used internally by ReferenceCountedObject */ -class _WeakPtrLinkedList { -public: - _WeakPtr* weakPtr; - _WeakPtrLinkedList* next; - - inline _WeakPtrLinkedList() : weakPtr(NULL), next(NULL) {} - - /** Inserts this node into the head of the list that previously had n as its head. */ - inline _WeakPtrLinkedList(_WeakPtr* p, _WeakPtrLinkedList* n) : weakPtr(p), next(n) {} -}; - -/** - Objects that are reference counted inherit from this. Subclasses - must have a public destructor (the default destructor is fine) - and publicly inherit ReferenceCountedObject. - - Multiple inheritance from a reference counted object is dangerous-- use - at your own risk. - - ReferenceCountedPointer and ReferenceCountedObject are threadsafe. - You can create and drop references on multiple threads without - violating integrity. WeakReferenceCountedPointer is not - threadsafe. Introducing a weak pointer destroys all thread safety, - even for strong pointers to the same object (this is inherent in the - design of the class; we cannot fix it without slowing down the - performance of reference counted objects.) - - Usage Example - -
-
-class Foo : public G3D::ReferenceCountedObject {
-public:
-    int x;
-};
-
-class Bar : public Foo {};
-
-typedef G3D::ReferenceCountedPointer FooRef;
-typedef G3D::WeakReferenceCountedPointer WeakFooRef;
-typedef G3D::ReferenceCountedPointer BarRef;
-
-
-int main(int argc, char *argv[]) {
-
-    WeakFooRef x;
-
-    {
-        FooRef a = new Foo();
-
-        // Reference count == 1
-
-        x = a;
-        // Weak references do not increase count
-
-        {
-            FooRef b = a;
-            // Reference count == 2
-        }
-
-        // Reference count == 1
-    }
-    // No more strong references; object automatically deleted.
-    // x is set to NULL automatically.
-
-    // Example of using dynamic cast on reference counted objects
-    BarRef b = new Bar();
-
-    // No cast needed to go down the heirarchy.
-    FooRef f = b;
-
-    // We can't cast the reference object because it is a class.
-    // Instead we must extract the pointer and cast that:
-    b = dynamic_cast(&*f);
-
-    return 0;
-}
-
- */ -class ReferenceCountedObject { -public: - - /** - The long name is to keep this from accidentally conflicting with - a subclass's variable name. Do not use or explicitly manipulate - this value--its type may change in the future and is not part - of the supported API. - */ - AtomicInt32 ReferenceCountedObject_refCount; - - /** - Linked list of all weak pointers that reference this (some may be - on the stack!). Do not use or explicitly manipulate this value. - */ - _WeakPtrLinkedList* ReferenceCountedObject_weakPointer; - -protected: - - ReferenceCountedObject(); - -public: - - /** Automatically called immediately before the object is deleted. - This is not called from the destructor because it needs to be invoked - before the subclass destructor. - */ - void ReferenceCountedObject_zeroWeakPointers(); - - virtual ~ReferenceCountedObject(); - - - /** - Note: copies will initially start out with 0 - references and 0 weak references like any other object. - */ - ReferenceCountedObject(const ReferenceCountedObject& notUsed); - - ReferenceCountedObject& operator=(const ReferenceCountedObject& other); -}; - - - -/** - Use ReferenceCountedPointer in place of T* in your program. - T must subclass ReferenceCountedObject. -@deprecated To be replaced by boost::shared_ptr in 7.0 - */ -template -class ReferenceCountedPointer { -private: - - T* m_pointer; - -public: - typedef T element_type; - - inline T* pointer() const { - return m_pointer; - } - -private: - - /** Nulls out the pointer and drops a reference. If the reference - count hits zero. */ - void zeroPointer() { - if (m_pointer != NULL) { - - ReferenceCountedObject* pointer = ((ReferenceCountedObject*)m_pointer); - debugAssert(G3D::isValidHeapPointer(m_pointer)); - debugAssertM(pointer->ReferenceCountedObject_refCount.value() > 0, - "Dangling reference detected."); - - // Only delete if this instance caused the count to hit - // exactly zero. If there is a race condition, the value - // may be zero after decrement returns, but only one of - // the instances will get a zero return value. - if (pointer->ReferenceCountedObject_refCount.decrement() == 0) { - // We held the last reference, so delete the object. - // This test is threadsafe because there is no way for - // the reference count to increase after the last - // reference was dropped (assuming the application does - // not voilate the class abstraction). - //debugPrintf(" delete 0x%x\n", m_pointer); - - // We must zero the weak pointers *before* deletion in case there - // are cycles of weak references. - // Note that since there are no strong references at this point, - // it is perfectly fair to zero the weak pointers anyway. - pointer->ReferenceCountedObject_zeroWeakPointers(); - delete pointer; - } - - m_pointer = NULL; - } - } - - /** Non-atomic (except for the referencec increment). Can only be - called in contexts like the copy constructor or initial - constructor where it is known that the reference count will - not hit zero on some other thread. */ - void setPointer(T* x) { - if (x != m_pointer) { - zeroPointer(); - - if (x != NULL) { - debugAssert(G3D::isValidHeapPointer(x)); - - m_pointer = x; - - // Note that the ref count can be zero if this is the - // first pointer to it - ReferenceCountedObject* pointer = (ReferenceCountedObject*)m_pointer; - debugAssertM(pointer->ReferenceCountedObject_refCount.value() >= 0, - "Negative reference count detected."); - pointer->ReferenceCountedObject_refCount.increment(); - } - } - } - -public: - - inline ReferenceCountedPointer() : m_pointer(NULL) {} - - /** - Allow silent cast to the base class. - -
-        SubRef  s = new Sub();
-        BaseRef b = s;
-      
- - i.e., compile-time subtyping rule - RCP<T> <: RCP<S> if T <: S - */ - template - inline ReferenceCountedPointer(const ReferenceCountedPointer& p) : - m_pointer(NULL) { - setPointer(p.pointer()); - } - -# if (! defined(MSC_VER) || (MSC_VER >= 1300)) - /** - Explicit cast to a subclass. Acts like dynamic cast; the result will be NULL if - the cast cannot succeed. Not supported on VC6. -
-        SubRef  s = new Sub();
-        BaseRef b = s;
-        s = b.downcast();   // Note that the template argument is the object type, not the pointer type.
-      
- */ - template - ReferenceCountedPointer downcast() { - return ReferenceCountedPointer(dynamic_cast(m_pointer)); - } - - template - const ReferenceCountedPointer downcast() const { - return ReferenceCountedPointer(dynamic_cast(m_pointer)); - } -# endif - - // We need an explicit version of the copy constructor as well or - // the default copy constructor will be used. - inline ReferenceCountedPointer(const ReferenceCountedPointer& p) : m_pointer(NULL) { - setPointer(p.m_pointer); - } - - /** Allows construction from a raw pointer. That object will thereafter be - reference counted -- do not call delete on it. - - Use of const allows downcast on const references */ - inline ReferenceCountedPointer(const T* p) : m_pointer(NULL) { - // only const constructor is defined to remove ambiguity using NULL - setPointer(const_cast(p)); - } - - - inline ~ReferenceCountedPointer() { - zeroPointer(); - } - - inline size_t hashCode() const { - return reinterpret_cast(m_pointer);; - } - - inline const ReferenceCountedPointer& operator=(const ReferenceCountedPointer& p) { - setPointer(p.m_pointer); - return *this; - } - - inline ReferenceCountedPointer& operator=(T* p) { - setPointer(p); - return *this; - } - - inline bool operator==(const ReferenceCountedPointer& y) const { - return (m_pointer == y.m_pointer); - } - - inline bool operator!=(const ReferenceCountedPointer& y) const { - return (m_pointer != y.m_pointer); - } - - bool operator < (const ReferenceCountedPointer& y) const { - return (m_pointer < y.m_pointer); - } - - bool operator > (const ReferenceCountedPointer& y) const { - return (m_pointer > y.m_pointer); - } - - bool operator <= (const ReferenceCountedPointer& y) const { - return (m_pointer <= y.m_pointer); - } - - bool operator >= (const ReferenceCountedPointer& y) const { - return (m_pointer >= y.m_pointer); - } - - inline T& operator*() const { - debugAssertM(m_pointer != NULL, "Dereferenced a NULL ReferenceCountedPointer"); - return (*m_pointer); - } - - inline T* operator->() const { - debugAssertM(m_pointer != NULL, "Dereferenced a NULL ReferenceCountedPointer"); - return m_pointer; - } - - inline bool isNull() const { - return (m_pointer == NULL); - } - - inline bool notNull() const { - return (m_pointer != NULL); - } - - // TODO: distinguish between last strong and last any pointer - /** - Returns true if this is the last reference to an object. - Useful for flushing memoization caches-- a cache that holds the last - reference is unnecessarily keeping an object alive. - - Not threadsafe. - - @deprecated Use WeakReferenceCountedPointer for caches - */ - inline int isLastReference() const { - return (m_pointer->ReferenceCountedObject_refCount.value() == 1); - } -}; - - -/** - A weak pointer allows the object it references to be garbage collected. - Weak pointers are commonly used in caches, where it is important to hold - a pointer to an object without keeping that object alive solely for the - cache's benefit (i.e., the object can be collected as soon as all - pointers to it outside the cache are gone). They are also convenient - for adding back-pointers in tree and list structures. - - Weak pointers may become NULL at any point (when their target is collected). - Therefore the only way to reference the target is to convert to a strong - pointer and then check that it is not NULL. - -@deprecated To be replaced by boost::weak_ptr in 7.0 - */ -template -class WeakReferenceCountedPointer : public _WeakPtr { -private: - - /** NULL if the object has been collected. */ - T* pointer; - -public: - /** - Creates a strong pointer, which prevents the object from being - garbage collected. The strong pointer may be NULL, which means - that the underlying. - */ - // There is intentionally no way to check if the - // WeakReferenceCountedPointer has a null reference without - // creating a strong pointer since there is no safe way to use - // that information-- the pointer could be collected by a - // subsequent statement. - ReferenceCountedPointer createStrongPtr() const { - // TODO: What if the object's destructor is called while we - // are in this method? - return ReferenceCountedPointer(pointer); - } - -private: - - /** Thread issues: safe because this is only called when another - object is guaranteed to keep p alive for the duration of this - call. */ - void setPointer(T* p) { - // TODO: must prevent the object from being collected while in - // this method - - zeroPointer(); - pointer = p; - - if (pointer != NULL) { - // TODO: threadsafe: must update the list atomically - - // Add myself to the head of my target's list of weak pointers - _WeakPtrLinkedList* head = - new _WeakPtrLinkedList - (this, - pointer->ReferenceCountedObject_weakPointer); - - pointer->ReferenceCountedObject_weakPointer = head; - } else { - - } - } - - - /** - Removes this from its target's list of weak pointers. Called - when the weak pointer goes out of scope. - - Thread issues: depends on the thread safety of createStrongPtr. - */ - void zeroPointer() { - // Grab a strong reference to prevent the object from being collected while we - // are traversing its list. - ReferenceCountedPointer strong = createStrongPtr(); - - // If the following test fails then the object was collected before we - // reached it. - if (strong.notNull()) { - debugAssertM(((ReferenceCountedObject*)pointer)->ReferenceCountedObject_weakPointer != NULL, - "Weak pointer exists without a backpointer from the object."); - - // Remove myself from my target's list of weak pointers - _WeakPtrLinkedList** node = &((ReferenceCountedObject*)pointer)->ReferenceCountedObject_weakPointer; - while ((*node)->weakPtr != this) { - node = &((*node)->next); - debugAssertM(*node != NULL, - "Weak pointer exists without a backpointer from the object (2)."); - } - - // Node must now point at the node for me. Remove node and - // close the linked list behind it. - _WeakPtrLinkedList* temp = *node; - *node = temp->next; - - // Now delete the node corresponding to me - delete temp; - } - - pointer = NULL; - } - -public: - - WeakReferenceCountedPointer() : pointer(0) {} - - /** - Allow compile time subtyping rule - RCP<T> <: RCP<S> if T <: S - */ - template - inline WeakReferenceCountedPointer(const WeakReferenceCountedPointer& p) : pointer(0) { - // Threadsafe: the object cannot be collected while the other pointer exists. - setPointer(p.pointer); - } - - template - inline WeakReferenceCountedPointer(const ReferenceCountedPointer& p) : pointer(0) { - // Threadsafe: the object cannot be collected while the other - // pointer exists. - setPointer(p.pointer()); - } - - // Gets called a *lot* when weak pointers are on the stack - WeakReferenceCountedPointer( - const WeakReferenceCountedPointer& weakPtr) : pointer(0) { - setPointer(weakPtr.pointer); - } - - WeakReferenceCountedPointer( - const ReferenceCountedPointer& strongPtr) : pointer(0) { - setPointer(strongPtr.pointer()); - } - - ~WeakReferenceCountedPointer() { - zeroPointer(); - } - - WeakReferenceCountedPointer& operator=(const WeakReferenceCountedPointer& other) { - // Threadsafe: the object cannot be collected while the other pointer exists. - - // I now point at other's target - setPointer(other.pointer); - - return *this; - } - - WeakReferenceCountedPointer& operator=(const ReferenceCountedPointer& other) { - - // Threadsafe: the object cannot be collected while the other pointer exists. - - // I now point at other's target - setPointer(other.pointer()); - - return *this; - } - - bool operator==(const WeakReferenceCountedPointer& other) const { - return pointer == other.pointer; - } - - bool operator!=(const WeakReferenceCountedPointer& other) const { - return pointer != other.pointer; - } - - bool operator < (const WeakReferenceCountedPointer& y) const { - return (pointer < y.pointer); - } - - bool operator > (const WeakReferenceCountedPointer& y) const { - return (pointer > y.pointer); - } - - bool operator <= (const WeakReferenceCountedPointer& y) const { - return (pointer <= y.pointer); - } - - bool operator >= (const ReferenceCountedPointer& y) const { - return (pointer >= y.pointer); - } - -protected: - - /** Invoked by the destructor on ReferenceCountedPointer. */ - void objectCollected() { - debugAssertM(pointer != NULL, - "Removed a weak pointer twice."); - pointer = NULL; - } - -}; - -} // namespace - -#endif - diff --git a/externals/g3dlite/G3D/RegistryUtil.h b/externals/g3dlite/G3D/RegistryUtil.h deleted file mode 100644 index 4b47be5f4bd..00000000000 --- a/externals/g3dlite/G3D/RegistryUtil.h +++ /dev/null @@ -1,97 +0,0 @@ -/** - @file RegistryUtil.h - - @created 2006-04-06 - @edited 2006-04-06 - - Copyright 2000-2006, Morgan McGuire. - All rights reserved. -*/ - -#ifndef G3D_REGISTRYUTIL_H -#define G3D_REGISTRYUTIL_H - -#include "G3D/platform.h" -#include "G3D/g3dmath.h" - -// This file is only used on Windows -#ifdef G3D_WIN32 - -#include - -namespace G3D { - -/** - Provides generalized Windows registry querying. - - All key names are one string in the format: - "[base key]\[sub-keys]" - - A value must now be provided for every query. - An empty value string will use the (Default) value. - - [base key] can be any of the following: - HKEY_CLASSES_ROOT - HKEY_CURRENT_CONFIG - HKEY_CURRENT_USER - HKEY_LOCAL_MACHINE - HKEY_PERFORMANCE_DATA - HKEY_PERFORMANCE_NLSTEXT - HKEY_PERFORMANCE_TEXT - HKEY_USERS - - valueExists() should be used to validate a key+value before reading or writing - to ensure that a debug assert or false return is for a different error during - reads and writes. - - All read and write calls will assert when a key will not open for reasons other - that it does not exist. All read and write calls will assert when the value cannot - be read or written for any reason. -*/ -class RegistryUtil { - -public: - /** returns true if the key exists and the current user has permission to read */ - static bool keyExists(const std::string& key); - - /** returns true if the key exists and the current user has permission to read */ - static bool valueExists(const std::string& key, const std::string& value); - - /** returns false if the key could not be read for any reason. */ - static bool readInt32(const std::string& key, const std::string& value, int32& data); - - /** - Reads an arbitrary amount of data from a binary registry key. - returns false if the key could not be read for any reason. - - @beta - @param data pointer to the output buffer of sufficient size. Pass NULL as data in order to have available data size returned in dataSize. - @param dataSize size of the output buffer. When NULL is passed for data, contains the size of available data on successful return. - */ - static bool readBytes(const std::string& key, const std::string& value, uint8* data, uint32& dataSize); - - /** returns false if the key could not be read for any reason. */ - static bool readString(const std::string& key, const std::string& value, std::string& data); - - /** returns false if the key could not be written for any reason. */ - static bool writeInt32(const std::string& key, const std::string& value, int32 data); - - /** - Writes an arbitrary amount of data to a binary registry key. - returns false if the key could not be written for any reason. - - @param data pointer to the input buffer - @param dataSize size of the input buffer that should be written - */ - static bool writeBytes(const std::string& key, const std::string& value, const uint8* data, uint32 dataSize); - - /** returns false if the key could not be written for any reason. */ - static bool writeString(const std::string& key, const std::string& value, const std::string& data); - -}; - -} // namespace G3D - -#endif // G3D_WIN32 - -#endif // G3D_REGISTRYTUIL_H diff --git a/externals/g3dlite/G3D/Set.h b/externals/g3dlite/G3D/Set.h deleted file mode 100644 index 9a8e1b619bb..00000000000 --- a/externals/g3dlite/G3D/Set.h +++ /dev/null @@ -1,186 +0,0 @@ -/** - @file Set.h - - Hash set - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2001-12-09 - @edited 2009-06-10 - */ - -#ifndef G3D_Set_h -#define G3D_Set_h - -#include "G3D/platform.h" -#include "G3D/Table.h" -#include "G3D/MemoryManager.h" -#include -#include - -namespace G3D { - -/** - An unordered data structure that has at most one of each element. - Provides O(1) time insert, remove, and member test (contains). - - Set uses G3D::Table internally, which means that the template type T - must define a hashCode and operator== function. See G3D::Table for - a discussion of these functions. - */ -// There is not copy constructor or assignment operator defined because -// the default ones are correct for Set. -template, class EqualsFunc = EqualsTrait > -class Set { - - /** - If an object is a member, it is contained in - this table. - */ - Table memberTable; - -public: - - void clearAndSetMemoryManager(const MemoryManager::Ref& m) { - memberTable.clearAndSetMemoryManager(m); - } - - virtual ~Set() {} - - int size() const { - return (int)memberTable.size(); - } - - bool contains(const T& member) const { - return memberTable.containsKey(member); - } - - /** - Inserts into the table if not already present. - */ - void insert(const T& member) { - memberTable.set(member, true); - } - - /** - Returns true if the element was present and removed. Returns false - if the element was not present. - */ - bool remove(const T& member) { - return memberTable.remove(member); - } - - /** If @a member is present, sets @a removed to the element - being removed and returns true. Otherwise returns false - and does not write to @a removed. This is useful when building - efficient hashed data structures that wrap Set. - */ - bool getRemove(const T& member, T& removed) { - bool ignore; - return memberTable.getRemove(member, removed, ignore); - } - - /** If a value that is EqualsFunc to @a member is present, returns a pointer to the - version stored in the data structure, otherwise returns NULL. - */ - const T* getPointer(const T& member) const { - return memberTable.getKeyPointer(member); - } - - Array getMembers() const { - return memberTable.getKeys(); - } - - void getMembers(Array& keyArray) const { - memberTable.getKeys(keyArray); - } - - void clear() { - memberTable.clear(); - } - - void deleteAll() { - getMembers().deleteAll(); - clear(); - } - - /** - C++ STL style iterator variable. See begin(). - */ - class Iterator { - private: - friend class Set; - - // Note: this is a Table iterator, we are currently defining - // Set iterator - typename Table::Iterator it; - - Iterator(const typename Table::Iterator& it) : it(it) {} - - public: - inline bool operator!=(const Iterator& other) const { - return !(*this == other); - } - - bool hasMore() const { - return it.hasMore(); - } - - bool operator==(const Iterator& other) const { - return it == other.it; - } - - /** - Pre increment. - */ - Iterator& operator++() { - ++it; - return *this; - } - - /** - Post increment (slower than preincrement). - */ - Iterator operator++(int) { - Iterator old = *this; - ++(*this); - return old; - } - - const T& operator*() const { - return it->key; - } - - T* operator->() const { - return &(it->key); - } - - operator T*() const { - return &(it->key); - } - }; - - - /** - C++ STL style iterator method. Returns the first member. - Use preincrement (++entry) to get to the next element. - Do not modify the set while iterating. - */ - Iterator begin() const { - return Iterator(memberTable.begin()); - } - - - /** - C++ STL style iterator method. Returns one after the last iterator - element. - */ - const Iterator end() const { - return Iterator(memberTable.end()); - } -}; - -} - -#endif - diff --git a/externals/g3dlite/G3D/SmallArray.h b/externals/g3dlite/G3D/SmallArray.h deleted file mode 100644 index 41f9959e264..00000000000 --- a/externals/g3dlite/G3D/SmallArray.h +++ /dev/null @@ -1,155 +0,0 @@ -/** - @file SmallArray.h - - @created 2009-04-26 - @edited 2009-04-26 - - Copyright 2000-2009, Morgan McGuire, http://graphics.cs.williams.edu - All rights reserved. - */ -#ifndef G3D_SmallArray_h -#define G3D_SmallArray_h - -#include "G3D/platform.h" -#include "G3D/Array.h" - -namespace G3D { - -/** Embeds \a N elements to reduce allocation time and increase - memory coherence when working with arrays of arrays. - Offers a limited subset of the functionality of G3D::Array.*/ -template -class SmallArray { -private: - int m_size; - - /** First N elements */ - T m_embedded[N]; - - /** Remaining elements */ - Array m_rest; - -public: - - SmallArray() : m_size(0) {} - - inline int size() const { - return m_size; - } - - void resize(int n, bool shrinkIfNecessary = true) { - m_rest.resize(std::max(0, n - N), shrinkIfNecessary); - m_size = n; - } - - void clear(bool shrinkIfNecessary = true) { - resize(0, shrinkIfNecessary); - } - - inline T& operator[](int i) { - debugAssert(i < m_size && i >= 0); - if (i < N) { - return m_embedded[i]; - } else { - return m_rest[i - N]; - } - } - - inline const T& operator[](int i) const { - debugAssert(i < m_size && i >= 0); - if (i < N) { - return m_embedded[i]; - } else { - return m_rest[i - N]; - } - } - - inline void push(const T& v) { - ++m_size; - if (m_size <= N) { - m_embedded[m_size - 1] = v; - } else { - m_rest.append(v); - } - } - - inline void append(const T& v) { - push(v); - } - - void fastRemove(int i) { - debugAssert(i < m_size && i >= 0); - if (i < N) { - if (m_size <= N) { - // Exclusively embedded - m_embedded[i] = m_embedded[m_size - 1]; - } else { - // Move one down from the rest array - m_embedded[i] = m_rest.pop(); - } - } else { - // Removing from the rest array - m_rest.fastRemove(i - N); - } - --m_size; - } - - T pop() { - debugAssert(m_size > 0); - if (m_size <= N) { - // Popping from embedded, don't need a temporary - --m_size; - return m_embedded[m_size]; - } else { - // Popping from rest - --m_size; - return m_rest.pop(); - } - } - - inline void popDiscard() { - debugAssert(m_size > 0); - if (m_size > N) { - m_rest.popDiscard(); - } - --m_size; - } - - inline T& next() { - ++m_size; - if (m_size <= N) { - return m_embedded[m_size - 1]; - } else { - return m_rest.next(); - } - } - - bool contains(const T& value) const { - for (int i = std::min(m_size, N) - 1; i >= 0; --i) { - if (m_embedded[i] == value) { - return true; - } - } - return m_rest.contains(value); - } - - template - SmallArray& operator=(const Array& src) { - resize(src.size()); - for (int i = 0; i < src.size(); ++i) { - (*this)[i] = src[i]; - } - return *this; - } - - inline const T& last() const { - return (*this)[size() - 1]; - } - - inline T& last() { - return (*this)[size() - 1]; - } -}; - -} -#endif diff --git a/externals/g3dlite/G3D/Sphere.h b/externals/g3dlite/G3D/Sphere.h deleted file mode 100644 index 595b61c4bf1..00000000000 --- a/externals/g3dlite/G3D/Sphere.h +++ /dev/null @@ -1,148 +0,0 @@ -/** - @file Sphere.h - - Sphere class - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2001-06-02 - @edited 2008-10-07 - */ - -#ifndef G3D_SPHERE_H -#define G3D_SPHERE_H - -#include "G3D/platform.h" -#include "G3D/Vector3.h" -#include "G3D/Array.h" -#include "G3D/Sphere.h" - -namespace G3D { - -/** - Sphere. - */ -class Sphere { -private: - - static int32 dummy; - -public: - Vector3 center; - float radius; - - Sphere() { - center = Vector3::zero(); - radius = 0; - } - - Sphere(class BinaryInput& b); - void serialize(class BinaryOutput& b) const; - void deserialize(class BinaryInput& b); - - Sphere( - const Vector3& center, - float radius) { - - this->center = center; - this->radius = radius; - } - - virtual ~Sphere() {} - - bool operator==(const Sphere& other) const { - return (center == other.center) && (radius == other.radius); - } - - bool operator!=(const Sphere& other) const { - return !((center == other.center) && (radius == other.radius)); - } - - /** - Returns true if point is less than or equal to radius away from - the center. - */ - bool contains(const Vector3& point) const; - - bool contains(const Sphere& other) const; - - /** - @deprecated Use culledBy(Array&) - */ - bool culledBy( - const class Plane* plane, - int numPlanes, - int32& cullingPlaneIndex, - const uint32 testMask, - uint32& childMask) const; - - /** - @deprecated Use culledBy(Array&) - */ - bool culledBy( - const class Plane* plane, - int numPlanes, - int32& cullingPlaneIndex = dummy, - const uint32 testMask = 0xFFFFFFFF) const; - - /** - See AABox::culledBy - */ - bool culledBy( - const Array& plane, - int32& cullingPlaneIndex, - const uint32 testMask, - uint32& childMask) const; - - /** - Conservative culling test that does not produce a mask for children. - */ - bool culledBy( - const Array& plane, - int32& cullingPlaneIndex = dummy, - const uint32 testMask = 0xFFFFFFFF) const; - - virtual std::string toString() const; - - float volume() const; - - float area() const; - - /** - Uniformly distributed on the surface. - */ - Vector3 randomSurfacePoint() const; - - /** - Uniformly distributed on the interior (includes surface) - */ - Vector3 randomInteriorPoint() const; - - void getBounds(class AABox& out) const; - - bool intersects(const Sphere& other) const; - - /** Translates the sphere */ - Sphere operator+(const Vector3& v) const { - return Sphere(center + v, radius); - } - - /** Translates the sphere */ - Sphere operator-(const Vector3& v) const { - return Sphere(center - v, radius); - } - - /** Sets this to the smallest sphere that encapsulates both */ - void merge(const Sphere& s); -}; - -} - -template <> struct HashTrait { - static size_t hashCode(const G3D::Sphere& key) { - return static_cast(key.center.hashCode() + (key.radius * 13)); - } -}; - - -#endif diff --git a/externals/g3dlite/G3D/Spline.h b/externals/g3dlite/G3D/Spline.h deleted file mode 100644 index fdd29e69ce9..00000000000 --- a/externals/g3dlite/G3D/Spline.h +++ /dev/null @@ -1,367 +0,0 @@ -/** - @file Spline.h - - @author Morgan McGuire, http://graphics.cs.williams.edu - */ - -#ifndef G3D_SPLINE_H -#define G3D_SPLINE_H - -#include "G3D/platform.h" -#include "G3D/Array.h" -#include "G3D/g3dmath.h" -#include "G3D/Matrix4.h" -#include "G3D/Vector4.h" - -namespace G3D { - -/** Common implementation code for all G3D::Spline template parameters */ -class SplineBase { -public: - - /** Times at which control points occur. Must have the same - number of elements as Spline::control. */ - Array time; - - /** If cyclic, then the control points will be assumed to wrap around. - If not cyclic, then the tangents at the ends of the spline - point to the final control points.*/ - bool cyclic; - - /** For a cyclic spline, this is the time elapsed between the last - control point and the first. If less than or equal to zero this is - assumed to be: - - (time[0] - time[1] + . - time[time.size() - 1] - time[time.size() - 2]) / 2. - */ - float finalInterval; - - SplineBase() : cyclic(true), finalInterval(-1) {} - - virtual ~SplineBase() {} - - /** See specification for Spline::finalInterval; this handles the - non-positive case. Returns 0 if not cyclic. */ - float getFinalInterval() const; - - /** Returns the amount of time covered by this spline in one - period. For a cyclic spline, this contains the final - interval.*/ - float duration() const; - - /** Computes the derivative spline basis from the control point version. */ - static Matrix4 computeBasis(); - -protected: - - /** Assumes that t0 <= s < tn. called by computeIndex. */ - void computeIndexInBounds(float s, int& i, float& u) const; - -public: - - /** - Given a time @a s, finds @a i and 0 <= @a u < 1 such that - @a s = time[@a i] * @a u + time[@a i + 1] * (1 - @a u). Note that - @a i may be outside the bounds of the time and control arrays; - use getControl to handle wraparound and extrapolation issues. - - This function takes expected O(1) time for control points with - uniform time sampled control points or for uniformly - distributed random time samples, but may take O( log time.size() ) time - in the worst case. - - Called from evaluate(). - */ - void computeIndex(float s, int& i, float& u) const; -}; - - -/** - Smooth parameteric curve implemented using a piecewise 3rd-order - Catmull-Rom spline curve. The spline is considered infinite and may - either continue linearly from the specified control points or cycle - through them. Control points are spaced uniformly in time at unit - intervals by default, but irregular spacing may be explicitly - specified. - - The dimension of the spline can be set by varying the Control - template parameter. For a 1D function, use Spline. For a - curve in the plane, Spline. Note that any template - parameter that supports operator+(Control) and operator*(float) can - be used; you can make splines out of G3D::Vector4, G3D::Matrix3, or - your own classes. - - To provide shortest-path interpolation, subclass G3D::Spline and - override ensureShortestPath(). To provide normalization of - interpolated points (e.g., projecting Quats onto the unit - hypersphere) override correct(). - - See Real Time Rendering, 2nd edition, ch 12 for a general discussion - of splines and their properties. - - @sa G3D::UprightSpline, G3D::QuatSpline - */ -template -class Spline : public SplineBase { -protected: - /** The additive identity control point. */ - Control zero; - -public: - - /** Control points. Must have the same number of elements as - Spline::time.*/ - Array control; - - Spline() { - static Control x; - // Hide the fact from C++ that we are using an - // uninitialized variable here by pointer arithmetic. - // This is ok because any type that is a legal control - // point also supports multiplication by float. - zero = *(&x) * 0.0f; - } - - /** Appends a control point at a specific time that must be - greater than that of the previous point. */ - void append(float t, const Control& c) { - debugAssertM((time.size() == 0) || (t > time.last()), - "Control points must have monotonically increasing times."); - time.append(t); - control.append(c); - debugAssert(control.size() == time.size()); - } - - - /** Appends control point spaced in time based on the previous - control point, or spaced at unit intervals if this is the - first control point. */ - void append(const Control& c) { - switch (time.size()) { - case 0: - append(0, c); - break; - - case 1: - if (time[0] == 0) { - append(1, c); - } else { - append(time[0], c); - } - break; - - default: - append(2 * time[time.size() - 1] - time[time.size() - 2], c); - } - debugAssert(control.size() == time.size()); - } - - /** Erases all control points and times, but retains the state of - cyclic and finalInterval. - */ - void clear() { - control.clear(); - time.clear(); - } - - - /** Number of control points */ - int size() const { - debugAssert(time.size() == control.size()); - return control.size(); - } - - - /** Returns the requested control point and time sample based on - array index. If the array index is out of bounds, wraps (for - a cyclic spline) or linearly extrapolates (for a non-cyclic - spline), assuming time intervals follow the first or last - sample recorded. - - Calls correct() on the control point if it was extrapolated. - - Returns 0 if there are no control points. - - @sa Spline::control and Spline::time for the underlying - control point array; Spline::computeIndex to find the index - given a time. - */ - void getControl(int i, float& t, Control& c) const { - int N = control.size(); - if (N == 0) { - c = zero; - t = 0; - } else if (cyclic) { - c = control[iWrap(i, N)]; - - if (i < 0) { - // Wrapped around bottom - - // Number of times we wrapped around the cyclic array - int wraps = (N + 1 - i) / N; - int j = (i + wraps * N) % N; - t = time[j] - wraps * duration(); - - } else if (i < N) { - - t = time[i]; - - } else { - // Wrapped around top - - // Number of times we wrapped around the cyclic array - int wraps = i / N; - int j = i % N; - t = time[j] + wraps * duration(); - } - - } else if (i < 0) { - // Are there enough points to extrapolate? - if (N >= 2) { - // Step away from control point 0 - float dt = time[1] - time[0]; - - // Extrapolate (note; i is negative) - c = control[1] * float(i) + control[0] * float(1 - i); - correct(c); - t = dt * i + time[0]; - - } else { - // Just clamp - c = control[0]; - - // Only 1 time; assume 1s intervals - t = time[0] + i; - } - - } else if (i >= N) { - if (N >= 2) { - float dt = time[N - 1] - time[N - 2]; - - // Extrapolate - c = control[N - 1] * float(i - N + 2) + control[N - 2] * -float(i - N + 1); - correct(c); - t = time[N - 1] + dt * (i - N + 1); - - } else { - // Return the last, clamping - c = control.last(); - // Only 1 time; assume 1s intervals - t = time[0] + i; - } - } else { - // In bounds - c = control[i]; - t = time[i]; - } - } - -protected: - - /** Returns a series of N control points and times, fixing - boundary issues. The indices may be assumed to be treated - cyclically. */ - void getControls(int i, float* T, Control* A, int N) const { - for (int j = 0; j < N; ++j) { - getControl(i + j, T[j], A[j]); - } - ensureShortestPath(A, N); - } - - /** - Mutates the array of N control points. It is useful to override this - method by one that wraps the values if they are angles or quaternions - for which "shortest path" interpolation is significant. - */ - virtual void ensureShortestPath(Control* A, int N) const { (void)A; (void) N;} - - /** Normalize or otherwise adjust this interpolated Control. */ - virtual void correct(Control& A) const { (void)A; } - -public: - - - /** - Return the position at time s. The spline is defined outside - of the time samples by extrapolation or cycling. - */ - Control evaluate(float s) const { - debugAssertM(control.size() == time.size(), "Corrupt spline: wrong number of control points."); - - /* - @cite http://www.gamedev.net/reference/articles/article1497.asp - Derivation of basis matrix follows. - - Given control points with positions p[i] at times t[i], 0 <= i <= 3, find the position - at time t[1] <= s <= t[2]. - - Let u = s - t[0] - Let U = [u^0 u^1 u^2 u^3] = [1 u u^2 u^3] - Let dt0 = t[0] - t[-1] - Let dt1 = t[1] - t[0] - Let dt2 = t[2] - t[1] - */ - - // Index of the first control point (i.e., the u = 0 point) - int i = 0; - // Fractional part of the time - float u = 0; - - computeIndex(s, i, u); - - Control p[4]; - float t[4]; - getControls(i - 1, t, p, 4); - float dt0 = t[1] - t[0]; - float dt1 = t[2] - t[1]; - float dt2 = t[3] - t[2]; - - static const Matrix4 basis = computeBasis(); - - // Powers of u - Vector4 uvec((float)(u*u*u), (float)(u*u), (float)u, 1.0f); - - // Compute the weights on each of the control points. - const Vector4& weights = uvec * basis; - - // Compute the weighted sum of the neighboring control points. - Control sum; - - const Control& p0 = p[0]; - const Control& p1 = p[1]; - const Control& p2 = p[2]; - const Control& p3 = p[3]; - - const Control& dp0 = p1 + (p0*-1.0f); - const Control& dp1 = p2 + (p1*-1.0f); - const Control& dp2 = p3 + (p2*-1.0f); - - // The factor of 1/2 from averaging two time intervals is - // already factored into the basis - - // tan1 = (dp0 / dt0 + dp1 / dt1) * ((dt0 + dt1) * 0.5); - // The last term normalizes for unequal time intervals - float x = (dt0 + dt1) * 0.5f; - float n0 = x / dt0; - float n1 = x / dt1; - float n2 = x / dt2; - const Control& dp1n1 = dp1 * n1; - const Control& tan1 = dp0 * n0 + dp1n1; - const Control& tan2 = dp1n1 + dp2 * n2; - - sum = - tan1 * weights[0]+ - p1 * weights[1] + - p2 * weights[2] + - tan2 * weights[3]; - - - correct(sum); - return sum; - } -}; - -} - -#endif diff --git a/externals/g3dlite/G3D/Stopwatch.h b/externals/g3dlite/G3D/Stopwatch.h deleted file mode 100644 index 3f2aa9c8d86..00000000000 --- a/externals/g3dlite/G3D/Stopwatch.h +++ /dev/null @@ -1,144 +0,0 @@ -/** - @file Stopwatch.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2005-10-05 - @edited 2009-05-10 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_Stopwatch_h -#define G3D_Stopwatch_h - -#include "G3D/platform.h" -#include "G3D/Queue.h" -#include "G3D/G3DGameUnits.h" -#include "G3D/g3dmath.h" - -namespace G3D { - -/** - \brief Accurately measure durations and framerates. - - Example 1: For profiling code in the context of a rendering loop: -
-      sw.tick();
-      ...timed code...
-      sw.tock();
-
-      screenPrintf("%f\n", sw.smoothFPS());
-    
- - - Example 2: For profiling pieces of a sequence: -
-    Stopwatch sw;
-    slowOperation();
-    sw.after("slowOperation");
-    kdTree.balance();
-    sw.after("Balance tree");
-   
- */ -class Stopwatch { -private: - - std::string myName; - double startTime; - std::string prevMark; - double prevTime; - - /** True between tick and tock */ - bool inBetween; - - /** The initial cycle count. */ - uint64 cycleStart; - - /** The time at which tick was called. */ - RealTime timeStart; - - /** The time at which the previous tock was called, -1 if never. */ - RealTime lastTockTime; - - RealTime lastDuration; - int64 lastCycleCount; - - /** Frames per second. */ - double m_fps; - - /** Weighted fps */ - double emwaFPS; - double m_smoothFPS; - - /** Weighted duration */ - RealTime emwaDuration; - - /** The overhead for calling into the class. */ - int64 cycleOverhead; - - /** Called from the constructor. */ - void computeOverhead(); - -public: - - Stopwatch(const std::string& name = "Stopwatch"); - - /** Returns the number of times that tick was called per wall-clock second; - e.g. frames-per-second. */ - double FPS() const { - return m_fps; - } - - /** Amount of time between the most recent tick and tock calls. 0 if tick has - never been called. */ - RealTime elapsedTime() const { - return lastDuration; - } - - /** Time-smoothed value that is stable to the nearest 1%. - This is useful if you are displaying elapsed time in real-time - and want a stable number.*/ - RealTime smoothElapsedTime() const { - return emwaDuration; - } - - /** Time-smoothed value of fps that is stable to the nearest integer for fps > 10 and - to the first decimal place for fps <= 10. - This is useful if you - are displaying the frame rate in real-time and want a stable (readable) number.*/ - double smoothFPS() const { - return m_smoothFPS; - } - - /** The elapsed cycle time between tick and tock. An attempt is made to factor out all - tick/tock overhead, so that back-to-back calls should return zero. - Unreliable on non-x86 platforms.*/ - uint64 elapsedCycles() const { - return lastCycleCount; - } - - /** Call at the beginning of the period that you want timed. */ - void tick(); - - /** Call at the end of the period that you want timed. */ - void tock(); - - - /** Reset the start time used by after() and the emwa value.*/ - void reset(); - - /** Call after an operation has completed, with the name of the operation, to - print a debug message listing the time since the previous after() call. */ - void after(const std::string& s = ""); - -}; - -/** Because it is hard to remember the proper capitalization. */ -typedef Stopwatch StopWatch; - -} - -#endif - diff --git a/externals/g3dlite/G3D/System.h b/externals/g3dlite/G3D/System.h deleted file mode 100644 index 56ef9c8e3dc..00000000000 --- a/externals/g3dlite/G3D/System.h +++ /dev/null @@ -1,507 +0,0 @@ -/** - @file System.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @cite Rob Wyatt http://www.gamasutra.com/features/wyatts_world/19990709/processor_detection_01.htm - @cite Benjamin Jurke http://www.flipcode.com/cgi-bin/msg.cgi?showThread=COTD-ProcessorDetectionClass&forum=cotd&id=-1 - @cite Michael Herf http://www.stereopsis.com/memcpy.html - - @created 2003-01-25 - @edited 2008-10-14 - */ - -#ifndef G3D_System_h -#define G3D_System_h - -#include "G3D/platform.h" -#include "G3D/g3dmath.h" -#include "G3D/G3DGameUnits.h" -#include "G3D/BinaryFormat.h" -#include - -#ifdef G3D_OSX -# include -#endif - -namespace G3D { - -/** - Routine used by the demos to find the data. Searches in - ../data, ../../data, etc. up to 5 levels back. Checks - common locations like \verbatim c:\libraries\g3d-\data \endverbatim - and some hard-coded paths on the Brown University file - system. - - @deprecated - */ -std::string demoFindData(bool errorIfNotFound = true); - -/** G3D, SDL, and IJG libraries require license documentation - to be distributed with your program. This generates the - string that must appear in your documentation. - Your program can be commercial, closed-source under - any license you want. - @deprecated Use System::license -*/ -std::string license(); - -/** -@brief The order in which the bytes of an integer are stored on a -machine. - -Intel/AMD chips tend to be G3D_LITTLE_ENDIAN, Mac PPC's and Suns are -G3D_BIG_ENDIAN. However, this is primarily used to specify the byte -order of file formats, which are fixed. -*/ -enum G3DEndian { - G3D_BIG_ENDIAN, - G3D_LITTLE_ENDIAN -}; - -/** - @brief OS and processor abstraction. - - The first time any method is called the processor will be analyzed. - Future calls are then fast. - - Timing function overview: - System::getCycleCount - - actual cycle count - - System::getTick - - High-resolution time in seconds since program started - - System::getLocalTime - - High-resolution time in seconds since Jan 1, 1970 - (because it is stored in a double, this may be less - accurate than getTick) - */ -class System { -public: - /** - @param size Size of memory that the system was trying to allocate - - @param recoverable If true, the system will attempt to allocate again - if the callback returns true. If false, malloc is going to return - NULL and this invocation is just to notify the application. - - @return Return true to force malloc to attempt allocation again if the - error was recoverable. - */ - typedef bool (*OutOfMemoryCallback)(size_t size, bool recoverable); - -private: - - bool m_initialized; - int m_cpuSpeed; - bool m_hasCPUID; - bool m_hasRDTSC; - bool m_hasMMX; - bool m_hasSSE; - bool m_hasSSE2; - bool m_hasSSE3; - bool m_has3DNOW; - bool m_has3DNOW2; - bool m_hasAMDMMX; - std::string m_cpuVendor; - int m_numCores; - - /** this holds the data directory set by the application (currently - GApp) for use by findDataFile */ - std::string m_appDataDir; - - G3DEndian m_machineEndian; - std::string m_cpuArch; - std::string m_operatingSystem; - -# ifdef G3D_WIN32 - /** Used by getTick() for timing */ - LARGE_INTEGER m_start; - LARGE_INTEGER m_counterFrequency; -#else - struct timeval m_start; -#endif - - std::string m_version; - OutOfMemoryCallback m_outOfMemoryCallback; - -#ifdef G3D_OSX - /** In Cycles/Second */ - SInt32 m_OSXCPUSpeed; - double m_secondsPerNS; -#endif - - /** The Real-World time of System::getTick() time 0. Set by initTime */ - RealTime m_realWorldGetTickTime0; - - uint32 m_highestCPUIDFunction; - - /** @brief Used for the singleton instance only. */ - System(); - - /** @brief The singleton instance. - - Used instead of a global variable to ensure that the order of - intialization is correct, which is critical because other - globals may allocate memory using System::malloc. - */ - static System& instance(); - - enum CPUIDFunction { - CPUID_VENDOR_ID = 0x00000000, - CPUID_PROCESSOR_FEATURES = 0x00000001, - CPUID_NUM_CORES = 0x00000004, - CPUID_GET_HIGHEST_FUNCTION = 0x80000000, - CPUID_EXTENDED_FEATURES = 0x80000001}; - - /** Helper macro to call cpuid functions and return all values - - See http://software.intel.com/en-us/articles/intel-64-architecture-processor-topology-enumeration/ - or http://www.amd.com/us-en/assets/content_type/white_papers_and_tech_docs/25481.pdf - - for description of the arguments. - */ - static void cpuid(CPUIDFunction func, uint32& areg, uint32& breg, uint32& creg, uint32& dreg); - - void init(); - - /** Called from init() */ - void getStandardProcessorExtensions(); - - /** Called from init() */ - void initTime(); - -public: - - /** Returns the speed of processor 0 in MHz. - Always returns 0 on linux.*/ - inline static int cpuSpeedMHz() { - return instance().m_cpuSpeed; - } - - /** Returns the number of logical processor cores (i.e., the - number of execution units for threads) */ - inline static int numCores() { - return instance().m_numCores; - } - - inline static bool hasCPUID() { - return instance().m_hasCPUID; - } - - inline static bool hasRDTSC() { - return instance().m_hasRDTSC; - } - - inline static bool hasSSE() { - return instance().m_hasSSE; - } - - inline static bool hasSSE2() { - return instance().m_hasSSE2; - } - - inline static bool hasSSE3() { - return instance().m_hasSSE3; - } - - inline static bool hasMMX() { - return instance().m_hasMMX; - } - - inline static bool has3DNow() { - return instance().m_has3DNOW; - } - - inline static const std::string& cpuVendor() { - return instance().m_cpuVendor; - } - - /** - Returns the endianness of this machine. - */ - inline static G3DEndian machineEndian() { - return instance().m_machineEndian; - } - - /** e.g., "Windows", "GNU/Linux" */ - inline static const std::string& operatingSystem() { - return instance().m_operatingSystem; - } - - /** e.g., 80686 */ - inline static const std::string& cpuArchitecture() { - return instance().m_cpuArch; - } - - /** - Returns the current date as a string in the form YYYY-MM-DD - */ - static std::string currentDateString(); - - /** - Guarantees that the start of the array is aligned to the - specified number of bytes. - */ - static void* alignedMalloc(size_t bytes, size_t alignment); - - /** - Uses pooled storage to optimize small allocations (1 byte to 5 - kilobytes). Can be 10x to 100x faster than calling ::malloc or - new. - - The result must be freed with free. - - Threadsafe on Win32. - - @sa calloc realloc OutOfMemoryCallback free - */ - static void* malloc(size_t bytes); - - static void* calloc(size_t n, size_t x); - - /** - Version of realloc that works with System::malloc. - */ - static void* realloc(void* block, size_t bytes); - - /** Returns a string describing how well System::malloc is using - its internal pooled storage. "heap" memory was slow to - allocate; the other data sizes are comparatively fast.*/ - static std::string mallocPerformance(); - static void resetMallocPerformanceCounters(); - - /** - Returns a string describing the current usage of the buffer pools used for - optimizing System::malloc. - */ - static std::string mallocStatus(); - - /** - Free data allocated with System::malloc. - - Threadsafe on Win32. - */ - static void free(void* p); - - /** - Frees memory allocated with alignedMalloc. - */ - static void alignedFree(void* ptr); - - /** An implementation of memcpy that may be up to 2x as fast as the C library - one on some processors. Guaranteed to have the same behavior as memcpy - in all cases. */ - static void memcpy(void* dst, const void* src, size_t numBytes); - - /** An implementation of memset that may be up to 2x as fast as the C library - one on some processors. Guaranteed to have the same behavior as memset - in all cases. */ - static void memset(void* dst, uint8 value, size_t numBytes); - - /** - Returns the fully qualified filename for the currently running executable. - - This is more reliable than arg[0], which may be intentionally set - to an incorrect value by a calling program, relative to a now - non-current directory, or obfuscated by sym-links. - - @cite Linux version written by Nicolai Haehnle , http://www.flipcode.com/cgi-bin/msg.cgi?showThread=COTD-getexename&forum=cotd&id=-1 - */ - static std::string currentProgramFilename(); - - /** Name of this program. Note that you can mutate this string to - set your app name explicitly.*/ - static std::string& appName(); - - /** G3D Version string */ - inline static const std::string& version() { - return instance().m_version; - } - - /** - @brief The optimization status of the G3D library (not the program compiled against it) - - Either "Debug" or "Release", depending on whether _DEBUG was - defined at compile-time for the library. - */ - static const std::string& build(); - - /** - Causes the current thread to yield for the specified duration - and consume almost no CPU. - The sleep will be extremely precise; it uses System::time() - to calibrate the exact yeild time. - */ - static void sleep(RealTime t); - - /** - Clears the console. - Console programs only. - */ - static void consoleClearScreen(); - - /** - Returns true if a key is waiting. - Console programs only. - */ - static bool consoleKeyPressed(); - - /** - Blocks until a key is read (use consoleKeyPressed to determine if - a key is waiting to be read) then returns the character code for - that key. - */ - static int consoleReadKey(); - - /** - The actual time (measured in seconds since - Jan 1 1970 midnight). - - Adjusted for local timezone and daylight savings - time. This is as accurate and fast as getCycleCount(). - */ - static RealTime time(); - - /** - To count the number of cycles a given operation takes: - -
-     unsigned long count;
-     System::beginCycleCount(count);
-     ...
-     System::endCycleCount(count);
-     // count now contains the cycle count for the intervening operation.
-     
- */ - /* static void beginCycleCount(uint64& cycleCount); - static void endCycleCount(uint64& cycleCount); - - static uint64 getCycleCount(); */ - - inline static void setOutOfMemoryCallback(OutOfMemoryCallback c) { - instance().m_outOfMemoryCallback = c; - } - - /** - When System::malloc fails to allocate memory because the system is - out of memory, it invokes this handler (if it is not NULL). - The argument to the callback is the amount of memory that malloc - was trying to allocate when it ran out. If the callback returns - true, System::malloc will attempt to allocate the memory again. - If the callback returns false, then System::malloc will return NULL. - - You can use outOfMemoryCallback to free data structures or to - register the failure. - */ - inline static OutOfMemoryCallback outOfMemoryCallback() { - return instance().m_outOfMemoryCallback; - } - - /** Set an environment variable for the current process */ - static void setEnv(const std::string& name, const std::string& value); - - /** Get an environment variable for the current process. Returns NULL if the variable doesn't exist. */ - static const char* getEnv(const std::string& name); - - /** - Prints a human-readable description of this machine - to the text output stream. Either argument may be NULL. - */ - static void describeSystem( - class TextOutput& t); - - static void describeSystem( - std::string& s); - - /** On Win32, returns the clipboard text contents. Does nothing on other - platforms (yet) */ - static std::string getClipboardText(); - - /** Copies the text to the clipboard on Win32. */ - static void setClipboardText(const std::string& s); - - /** - Tries to locate the resource by looking in related directories. - If found, returns the full path to the resource, otherwise - returns the empty string. - */ - static std::string findDataFile(const std::string& full, bool errorIfNotFound = true); - - /** - Sets the path that the application is using as its data directory. - Used by findDataDir as an initial search location. GApp sets this - upon constrution. - */ - static void setAppDataDir(const std::string& path); - -}; - -/* don't need that for MaNGOS, not portable to Win64... -#ifdef _MSC_VER - inline uint64 System::getCycleCount() { - uint32 timehi, timelo; - - // Use the assembly instruction rdtsc, which gets the current - // cycle count (since the process started) and puts it in edx:eax. - __asm - { - rdtsc; - mov timehi, edx; - mov timelo, eax; - } - - return ((uint64)timehi << 32) + (uint64)timelo; - } - -#elif defined(G3D_LINUX) - - inline uint64 System::getCycleCount() { - uint32 timehi, timelo; - - __asm__ __volatile__ ( - "rdtsc " - : "=a" (timelo), - "=d" (timehi) - : ); - - return ((uint64)timehi << 32) + (uint64)timelo; - } - -#elif defined(G3D_OSX) - - inline uint64 System::getCycleCount() { - //Note: To put off extra processing until the end, this does not - //return the actual clock cycle count. It is a bus cycle count. - //When endCycleCount() is called, it converts the two into a difference - //of clock cycles - - return (uint64) UnsignedWideToUInt64(UpTime()); - //return (uint64) mach_absolute_time(); - } - -#endif - -inline void System::beginCycleCount(uint64& cycleCount) { - cycleCount = getCycleCount(); -} - - -inline void System::endCycleCount(uint64& cycleCount) { -#ifndef G3D_OSX - cycleCount = getCycleCount() - cycleCount; -#else - AbsoluteTime end = UpTime(); - Nanoseconds diffNS = - AbsoluteDeltaToNanoseconds(end, UInt64ToUnsignedWide(cycleCount)); - cycleCount = - (uint64) ((double) (instance().m_OSXCPUSpeed) * - (double) UnsignedWideToUInt64(diffNS) * instance().m_secondsPerNS); -#endif -} - */ - -} // namespace - -#endif diff --git a/externals/g3dlite/G3D/Table.h b/externals/g3dlite/G3D/Table.h deleted file mode 100644 index 287efa94d97..00000000000 --- a/externals/g3dlite/G3D/Table.h +++ /dev/null @@ -1,924 +0,0 @@ -/** - @file Table.h - - Templated hash table class. - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - @created 2001-04-22 - @edited 2010-01-28 - Copyright 2000-2010, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_Table_h -#define G3D_Table_h - -#include -#include - -#include "G3D/platform.h" -#include "G3D/Array.h" -#include "G3D/debug.h" -#include "G3D/System.h" -#include "G3D/g3dmath.h" -#include "G3D/EqualsTrait.h" -#include "G3D/HashTrait.h" -#include "G3D/MemoryManager.h" - -#ifdef _MSC_VER -# pragma warning (push) - // Debug name too long warning -# pragma warning (disable : 4786) -#endif - -namespace G3D { - -/** - An unordered data structure mapping keys to values. - - There are two ways of definining custom hash functions (G3D provides built-in ones for most classes): - -
- class Foo {
- public:
-     std::string     name;
-     int             index;
-     static size_t hashCode(const Foo& key) {
-          return HashTrait::hashCode(key.name) + key.index;
-     }
-  };
-
-  template<> struct HashTrait {
-       static size_t hashCode(const Foo& key) { return HashTrait::hashCode(key.name) + key.index; }
-  }; 
-
-
-  // Use Foo::hashCode
-  Table fooTable1;
-
-  // Use HashTrait
-  Table      fooTable2;
-  
- - - Key must be a pointer, an int, a std::string or provide overloads for: - -
-    template<> struct HashTrait {
-        static size_t hashCode(const Key& key) { return reinterpret_cast( ... ); }
-    }; 
-  
- - and one of - -
-    template<> struct EqualsTrait{
-         static bool equals(const Key& a, const Key& b) { return ... ; }
-    };
-
-
-    bool operator==(const Key&, const Key&);
-  
- - G3D pre-defines HashTrait specializations for common types (like int and std::string). - If you use a Table with a different type you must write those functions yourself. For example, - an enum would use: - -
-    template<> struct HashTrait {
-        static size_t equals(const MyEnum& key) const { return reinterpret_cast( key ); }
-    };
-  
- - And rely on the default enum operator==. - - - Periodically check that debugGetLoad() is low (> 0.1). When it gets near - 1.0 your hash function is badly designed and maps too many inputs to - the same output. - */ -template, class EqualsFunc = EqualsTrait > -class Table { -public: - - /** - The pairs returned by iterator. - */ - class Entry { - public: - Key key; - Value value; - Entry() {} - Entry(const Key& k) : key(k) {} - Entry(const Key& k, const Value& v) : key(k), value(v) {} - bool operator==(const Entry &peer) const { return (key == peer.key && value == peer.value); } - bool operator!=(const Entry &peer) const { return !operator==(peer); } - }; - -private: - - typedef Table ThisType; - - /** - Linked list nodes used internally by HashTable. - */ - class Node { - public: - Entry entry; - size_t hashCode; - Node* next; - - private: - - // Private to require use of the allocator - Node(const Key& k, const Value& v, size_t h, Node* n) - : entry(k, v), hashCode(h), next(n) { - } - - Node(const Key& k, size_t h, Node* n) - : entry(k), hashCode(h), next(n) { - } - - public: - - static Node* create(const Key& k, const Value& v, size_t h, Node* n, MemoryManager::Ref& mm) { - Node* node = (Node*)mm->alloc(sizeof(Node)); - return new (node) Node(k, v, h, n); - } - - static Node* create(const Key& k, size_t hashCode, Node* n, MemoryManager::Ref& mm) { - Node* node = (Node*)mm->alloc(sizeof(Node)); - return new (node) Node(k, hashCode, n); - } - - static void destroy(Node* n, MemoryManager::Ref& mm) { - n->~Node(); - mm->free(n); - } - - /** - Clones a whole chain; - */ - Node* clone(MemoryManager::Ref& mm) { - return create(this->entry.key, this->entry.value, hashCode, (next == NULL) ? NULL : next->clone(mm), mm); - } - }; - - void checkIntegrity() const { -# ifdef G3D_DEBUG - debugAssert(m_bucket == NULL || isValidHeapPointer(m_bucket)); - for (size_t b = 0; b < m_numBuckets; ++b) { - Node* node = m_bucket[b]; - debugAssert(node == NULL || isValidHeapPointer(node)); - while (node != NULL) { - debugAssert(node == NULL || isValidHeapPointer(node)); - node = node->next; - } - } -# endif - } - - /** Number of elements in the table.*/ - size_t m_size; - - /** - Array of Node*. - - We don't use Array because Table is lower-level than Array. - Some elements may be NULL. - */ - Node** m_bucket; - - /** - Length of the m_bucket array. - */ - size_t m_numBuckets; - - MemoryManager::Ref m_memoryManager; - - void* alloc(size_t s) const { - return m_memoryManager->alloc(s); - } - - void free(void* p) const { - return m_memoryManager->free(p); - } - - /** - Re-hashes for a larger m_bucket size. - */ - void resize(size_t newSize) { - - // Hang onto the old m_bucket array - Node** oldBucket = m_bucket; - - // Allocate a new m_bucket array with the new size - m_bucket = (Node**)alloc(sizeof(Node*) * newSize); - // Set all pointers to NULL - System::memset(m_bucket, 0, newSize * sizeof(Node*)); - debugAssertM(m_bucket != NULL, "MemoryManager::alloc returned NULL. Out of memory."); - // Move each node to its new hash location - for (size_t b = 0; b < m_numBuckets; ++b) { - Node* node = oldBucket[b]; - - // There is a linked list of nodes at this m_bucket - while (node != NULL) { - // Hang onto the old next pointer - Node* nextNode = node->next; - - // Insert at the head of the list for m_bucket[i] - size_t i = node->hashCode % newSize; - node->next = m_bucket[i]; - m_bucket[i] = node; - - // Move on to the next node - node = nextNode; - } - - // Drop the old pointer for cleanliness when debugging - oldBucket[b] = NULL; - } - - // Delete the old storage - free(oldBucket); - this->m_numBuckets = newSize; - - checkIntegrity(); - } - - - void copyFrom(const ThisType& h) { - if (&h == this) { - return; - } - - debugAssert(m_bucket == NULL); - m_size = h.m_size; - m_numBuckets = h.m_numBuckets; - m_bucket = (Node**)alloc(sizeof(Node*) * m_numBuckets); - // No need to NULL elements since we're about to overwrite them - - for (size_t b = 0; b < m_numBuckets; ++b) { - if (h.m_bucket[b] != NULL) { - m_bucket[b] = h.m_bucket[b]->clone(m_memoryManager); - } else { - m_bucket[b] = NULL; - } - } - - checkIntegrity(); - } - - /** - Frees the heap structures for the nodes. - */ - void freeMemory() { - checkIntegrity(); - - for (size_t b = 0; b < m_numBuckets; b++) { - Node* node = m_bucket[b]; - while (node != NULL) { - Node* next = node->next; - Node::destroy(node, m_memoryManager); - node = next; - } - m_bucket[b] = NULL; - } - free(m_bucket); - m_bucket = NULL; - m_numBuckets = 0; - m_size = 0; - } - -public: - - /** - Creates an empty hash table using the default MemoryManager. - */ - Table() : m_bucket(NULL) { - m_memoryManager = MemoryManager::create(); - m_numBuckets = 0; - m_size = 0; - m_bucket = NULL; - checkIntegrity(); - } - - /** Changes the internal memory manager to m */ - void clearAndSetMemoryManager(const MemoryManager::Ref& m) { - clear(); - debugAssert(m_bucket == NULL); - m_memoryManager = m; - } - - /** - Recommends that the table resize to anticipate at least this number of elements. - */ - void setSizeHint(size_t n) { - size_t s = n * 3; - if (s > m_numBuckets) { - resize(s); - } - } - - /** - Destroys all of the memory allocated by the table, but does not - call delete on keys or values if they are pointers. If you want to - deallocate things that the table points at, use getKeys() and Array::deleteAll() - to delete them. - */ - virtual ~Table() { - freeMemory(); - } - - /** Uses the default memory manager */ - Table(const ThisType& h) { - m_memoryManager = MemoryManager::create(); - m_numBuckets = 0; - m_size = 0; - m_bucket = NULL; - this->copyFrom(h); - checkIntegrity(); - } - - - Table& operator=(const ThisType& h) { - // No need to copy if the argument is this - if (this != &h) { - // Free the existing nodes - freeMemory(); - this->copyFrom(h); - checkIntegrity(); - } - return *this; - } - - /** - Returns the length of the deepest m_bucket. - */ - size_t debugGetDeepestBucketSize() const { - size_t deepest = 0; - - for (size_t b = 0; b < m_numBuckets; b++) { - size_t count = 0; - Node* node = m_bucket[b]; - while (node != NULL) { - node = node->next; - ++count; - } - - if (count > deepest) { - deepest = count; - } - } - - return deepest; - } - - /** - Returns the average size of non-empty buckets. - */ - float debugGetAverageBucketSize() const { - size_t num = 0; - size_t count = 0; - - for (size_t b = 0; b < m_numBuckets; b++) { - Node* node = m_bucket[b]; - if (node != NULL) { - ++num; - while (node != NULL) { - node = node->next; - ++count; - } - } - } - - return (float)((double)count / num); - } - - /** - A small load (close to zero) means the hash table is acting very - efficiently most of the time. A large load (close to 1) means - the hash table is acting poorly-- all operations will be very slow. - A large load will result from a bad hash function that maps too - many keys to the same code. - */ - double debugGetLoad() const { - return debugGetDeepestBucketSize() / (double)size(); - } - - /** - Returns the number of buckets. - */ - size_t debugGetNumBuckets() const { - return m_numBuckets; - } - - /** - C++ STL style iterator variable. See begin(). - */ - class Iterator { - private: - friend class Table; - - /** - Bucket index. - */ - size_t index; - - /** - Linked list node. - */ - Node* node; - ThisType* table; - size_t m_numBuckets; - Node** m_bucket; - bool isDone; - - /** - Creates the end iterator. - */ - Iterator(const ThisType* table) : table(const_cast(table)) { - isDone = true; - } - - Iterator(const ThisType* table, size_t m_numBuckets, Node** m_bucket) : - table(const_cast(table)), - m_numBuckets(m_numBuckets), - m_bucket(m_bucket) { - - if (m_numBuckets == 0) { - // Empty table - isDone = true; - return; - } - - index = 0; - node = m_bucket[index]; - isDone = false; - findNext(); - } - - /** - Finds the next element, setting isDone if one can't be found. - Looks at the current element first. - */ - void findNext() { - while (node == NULL) { - index++; - if (index >= m_numBuckets) { - isDone = true; - break; - } else { - node = m_bucket[index]; - } - } - } - - public: - inline bool operator!=(const Iterator& other) const { - return !(*this == other); - } - - bool operator==(const Iterator& other) const { - if (other.isDone || isDone) { - // Common case; check against isDone. - return (isDone == other.isDone) && (other.table == table); - } else { - return - (table == other.table) && - (node == other.node) && - (index == other.index); - } - } - - /** - Pre increment. - */ - Iterator& operator++() { - node = node->next; - findNext(); - return *this; - } - - /** - Post increment (slower than preincrement). - */ - Iterator operator++(int) { - Iterator old = *this; - ++(*this); - return old; - } - - const Entry& operator*() const { - return node->entry; - } - - Entry* operator->() const { - return &(node->entry); - } - - operator Entry*() const { - return &(node->entry); - } - - bool hasMore() const { - return ! isDone; - } - }; - - - /** - C++ STL style iterator method. Returns the first Entry, which - contains a key and value. Use preincrement (++entry) to get to - the next element. Do not modify the table while iterating. - */ - Iterator begin() const { - return Iterator(this, m_numBuckets, m_bucket); - } - - /** - C++ STL style iterator method. Returns one after the last iterator - element. - */ - const Iterator end() const { - return Iterator(this); - } - - /** - Removes all elements - */ - void clear() { - freeMemory(); - m_numBuckets = 0; - m_size = 0; - m_bucket = NULL; - } - - - /** - Returns the number of keys. - */ - size_t size() const { - return m_size; - } - - - /** - If you insert a pointer into the key or value of a table, you are - responsible for deallocating the object eventually. Inserting - key into a table is O(1), but may cause a potentially slow rehashing. - */ - void set(const Key& key, const Value& value) { - getCreateEntry(key).value = value; - } - -private: - - /** Helper for remove() and getRemove() */ - bool remove(const Key& key, Key& removedKey, Value& removedValue, bool updateRemoved) { - if (m_numBuckets == 0) { - return false; - } - size_t code = HashFunc::hashCode(key); - size_t b = code % m_numBuckets; - - // Go to the m_bucket - Node* n = m_bucket[b]; - - if (n == NULL) { - return false; - } - - Node* previous = NULL; - - // Try to find the node - do { - if ((code == n->hashCode) && EqualsFunc::equals(n->entry.key, key)) { - // This is the node; remove it - - // Replace the previous's next pointer - if (previous == NULL) { - m_bucket[b] = n->next; - } else { - previous->next = n->next; - } - - if (updateRemoved) { - removedKey = n->entry.key; - removedValue = n->entry.value; - } - // Delete the node - Node::destroy(n, m_memoryManager); - --m_size; - return true; - } - - previous = n; - n = n->next; - } while (n != NULL); - - return false; - //alwaysAssertM(false, "Tried to remove a key that was not in the table."); - } - -public: - - /** If @a member is present, sets @a removed to the element - being removed and returns true. Otherwise returns false - and does not write to @a removed. */ - bool getRemove(const Key& key, Key& removedKey, Value& removedValue) { - return remove(key, removedKey, removedValue, true); - } - - /** - Removes an element from the table if it is present. - @return true if the element was found and removed, otherwise false - */ - bool remove(const Key& key) { - Key x; - Value v; - return remove(key, x, v, false); - } - -private: - - Entry* getEntryPointer(const Key& key) const { - if (m_numBuckets == 0) { - return NULL; - } - - size_t code = HashFunc::hashCode(key); - size_t b = code % m_numBuckets; - - Node* node = m_bucket[b]; - - while (node != NULL) { - if ((node->hashCode == code) && EqualsFunc::equals(node->entry.key, key)) { - return &(node->entry); - } - node = node->next; - } - - return NULL; - } - -public: - - /** If a value that is EqualsFunc to @a member is present, returns a pointer to the - version stored in the data structure, otherwise returns NULL. - */ - const Key* getKeyPointer(const Key& key) const { - const Entry* e = getEntryPointer(key); - if (e == NULL) { - return NULL; - } else { - return &(e->key); - } - } - - /** - Returns the value associated with key. - @deprecated Use get(key, val) or getPointer(key) - */ - Value& get(const Key& key) const { - Entry* e = getEntryPointer(key); - debugAssertM(e != NULL, "Key not found"); - return e->value; - } - - - /** Returns a pointer to the element if it exists, or NULL if it does not. - Note that if your value type is a pointer, the return value is - a pointer to a pointer. Do not remove the element while holding this - pointer. - - It is easy to accidentally mis-use this method. Consider making - a Table and using get(key, val) instead, which makes you manage - the memory for the values yourself and is less likely to result in - pointer errors. - */ - Value* getPointer(const Key& key) const { - if (m_numBuckets == 0) { - return NULL; - } - - size_t code = HashFunc::hashCode(key); - size_t b = code % m_numBuckets; - - Node* node = m_bucket[b]; - - while (node != NULL) { - if ((node->hashCode == code) && EqualsFunc::equals(node->entry.key, key)) { - // found key - return &(node->entry.value); - } - node = node->next; - } - - // Failed to find key - return NULL; - } - - /** - If the key is present in the table, val is set to the associated value and returns true. - If the key is not present, returns false. - */ - bool get(const Key& key, Value& val) const { - Value* v = getPointer(key); - if (v != NULL) { - val = *v; - return true; - } else { - return false; - } - } - - - - /** Called by getCreate() and set() - - \param created Set to true if the entry was created by this method. - */ - Entry& getCreateEntry(const Key& key, bool& created) { - created = false; - - if (m_numBuckets == 0) { - resize(10); - } - - size_t code = HashFunc::hashCode(key); - size_t b = code % m_numBuckets; - - // Go to the m_bucket - Node* n = m_bucket[b]; - - // No m_bucket, so this must be the first - if (n == NULL) { - m_bucket[b] = Node::create(key, code, NULL, m_memoryManager); - ++m_size; - created = true; - return m_bucket[b]->entry; - } - - size_t bucketLength = 1; - - // Sometimes a bad hash code will cause all elements - // to collide. Detect this case and don't rehash when - // it occurs; nothing good will come from the rehashing. - bool allSameCode = true; - - // Try to find the node - do { - allSameCode = allSameCode && (code == n->hashCode); - - if ((code == n->hashCode) && EqualsFunc::equals(n->entry.key, key)) { - // This is the a pre-existing node - return n->entry; - } - - n = n->next; - ++bucketLength; - } while (n != NULL); - - const size_t maxBucketLength = 3; - // (Don't bother changing the size of the table if all entries - // have the same hashcode--they'll still collide) - if ((bucketLength > maxBucketLength) && - ! allSameCode && - (m_numBuckets < m_size * 15)) { - - // This m_bucket was really large; rehash if all elements - // don't have the same hashcode the number of buckets is - // reasonable. - - // Back off the scale factor as the number of buckets gets - // large - float f = 3.0f; - if (m_numBuckets > 1000000) { - f = 1.5f; - } else if (m_numBuckets > 100000) { - f = 2.0f; - } - int newSize = iMax((int)(m_numBuckets * f) + 1, (int)(m_size * f)); - resize(newSize); - } - - // Not found; insert at the head. - b = code % m_numBuckets; - m_bucket[b] = Node::create(key, code, m_bucket[b], m_memoryManager); - ++m_size; - created = true; - return m_bucket[b]->entry; - } - - Entry& getCreateEntry(const Key& key) { - bool ignore; - return getCreateEntry(key, ignore); - } - - - /** Returns the current value that key maps to, creating it if necessary.*/ - Value& getCreate(const Key& key) { - return getCreateEntry(key).value; - } - - /** \param created True if the element was created. */ - Value& getCreate(const Key& key, bool& created) { - return getCreateEntry(key, created).value; - } - - - /** - Returns true if key is in the table. - */ - bool containsKey(const Key& key) const { - if (m_numBuckets == 0) { - return false; - } - - size_t code = HashFunc::hashCode(key); - size_t b = code % m_numBuckets; - - Node* node = m_bucket[b]; - - while (node != NULL) { - if ((node->hashCode == code) && EqualsFunc::equals(node->entry.key, key)) { - return true; - } - node = node->next; - } while (node != NULL); - - return false; - } - - - /** - Short syntax for get. - */ - inline Value& operator[](const Key &key) const { - return get(key); - } - - /** - Returns an array of all of the keys in the table. - You can iterate over the keys to get the values. - @deprecated - */ - Array getKeys() const { - Array keyArray; - getKeys(keyArray); - return keyArray; - } - - void getKeys(Array& keyArray) const { - keyArray.resize(0, DONT_SHRINK_UNDERLYING_ARRAY); - for (size_t i = 0; i < m_numBuckets; i++) { - Node* node = m_bucket[i]; - while (node != NULL) { - keyArray.append(node->entry.key); - node = node->next; - } - } - } - - /** - Calls delete on all of the keys and then clears the table. - */ - void deleteKeys() { - for (size_t i = 0; i < m_numBuckets; i++) { - Node* node = m_bucket[i]; - while (node != NULL) { - delete node->entry.key; - node = node->next; - } - } - clear(); - } - - /** - Calls delete on all of the values. This is unsafe-- - do not call unless you know that each value appears - at most once. - - Does not clear the table, so you are left with a table - of NULL pointers. - */ - void deleteValues() { - for (size_t i = 0; i < m_numBuckets; ++i) { - Node* node = m_bucket[i]; - while (node != NULL) { - delete node->entry.value; - node->entry.value = NULL; - node = node->next; - } - } - } -}; - -} // namespace - -#ifdef _MSC_VER -# pragma warning (pop) -#endif - -#endif diff --git a/externals/g3dlite/G3D/TextInput.h b/externals/g3dlite/G3D/TextInput.h deleted file mode 100644 index 33eb8c48e53..00000000000 --- a/externals/g3dlite/G3D/TextInput.h +++ /dev/null @@ -1,801 +0,0 @@ -/** - @file TextInput.h - - Simple text lexer/tokenizer. - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @cite Based on a lexer written by Aaron Orenstein. - - @created 2002-11-27 - @edited 2009-11-24 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_TextInput_h -#define G3D_TextInput_h - -#include "G3D/platform.h" -#include "G3D/Array.h" -#include "G3D/Set.h" -#include "G3D/ParseError.h" -#include -#include -#include -#include - -namespace G3D { - -/** - For use with TextInput. - */ -class Token { -public: - - /** - More detailed type information than Type. - */ - enum ExtendedType { - DOUBLE_QUOTED_TYPE, - SINGLE_QUOTED_TYPE, - SYMBOL_TYPE, - FLOATING_POINT_TYPE, - INTEGER_TYPE, - BOOLEAN_TYPE, - LINE_COMMENT_TYPE, - BLOCK_COMMENT_TYPE, - NEWLINE_TYPE, - END_TYPE - }; - - /** - Strings are enclosed in quotes, symbols are not. - */ - enum Type { - STRING = DOUBLE_QUOTED_TYPE, - SYMBOL = SYMBOL_TYPE, - NUMBER = FLOATING_POINT_TYPE, - BOOLEAN = BOOLEAN_TYPE, - COMMENT = LINE_COMMENT_TYPE, - NEWLINE = NEWLINE_TYPE, - END = END_TYPE - }; - -private: - - friend class TextInput; - - /** - Holds the actual value, which might be any type. If a number, it will be - parsed at runtime. - */ - std::string _string; - - bool _bool; - int _line; - int _character; - Type _type; - ExtendedType _extendedType; - -public: - - Token() : - _string(""), - _bool(false), - _line(0), - _character(0), - _type(END), - _extendedType(END_TYPE) {} - - Token(Type t, ExtendedType e, const std::string& s, int L, int c) - : _string(s), _bool(false), _line(L), _character(c), _type(t), _extendedType(e) {} - - Token(Type t, ExtendedType e, const std::string& s, bool b, int L, int c) - : _string(s), _bool(b), _line(L), _character(c), _type(t), _extendedType(e) {} - - Type type() const { - return _type; - } - - ExtendedType extendedType() const { - return _extendedType; - } - - /** - The value of a single or double quote string (not including the quotes), - the name of a symbol, or the exact textual representation of a number as - parsed from the input. - */ - const std::string& string() const { - return _string; - } - - bool boolean() const { - return _bool; - } - - /** - Starting line of the input from which this token was parsed. Starts - at 1. - */ - int line() const { - return _line; - } - - /** - Starting character position in the input line from which this token was - parsed. Starts at 1. - */ - int character() const { - return _character; - } - - /** Return the numeric value for a number type, or zero if this is - not a number type. - */ - double number() const; -}; - - -/** - A simple style tokenizer for reading text files. TextInput handles a - superset of C++,Java, Matlab, and Bash code text including single - line comments, block comments, quoted strings with escape sequences, - and operators. TextInput recognizes several categories of tokens, - which are separated by white space, quotation marks, or the end of a - recognized operator: - -
    -
  • Token::SINGLE_QUOTED_TYPE string of characters surrounded by single quotes, e.g., 'x', '\\0', 'foo'. -
  • Token::DOUBLE_QUOTED_TYPE string of characters surrounded by double quotes, e.g., "x", "abc\txyz", "b o b". -
  • Token::SYMBOL_TYPE legal C++ operators, keywords, and identifiers. e.g., >=, Foo, _X, class, { -
  • Token::INTEGER_TYPE numbers without decimal places or exponential notation. e.g., 10, 0x17F, 32, 0, -155 -
  • Token::FLOATING_POINT_TYPE numbers with decimal places or exponential notation. e.g., 1e3, -1.2, .4, 0.5 -
  • Token::BOOLEAN_TYPE special symbols like "true" and "false"; the exact details can be configured in TextInput::Settings -
  • Token::LINE_COMMENT_TYPE (disabled by default); generated for line comments as specified by TextInput::Settings -
  • Token::BLOCK_COMMENT_TYPE (disabled by default); generated for c-style block comments as specified by TextInput::Settings -
  • Token::NEWLINE_TYPE (disabled by default); generated for any of "\\r", "\\n" or "\\r\\n" -
- -

The special ".." and "..." tokens are always recognized in - addition to normal C++ operators. Additional tokens can be made - available by changing the Settings. - - Negative numbers are handled specially because of the ambiguity between unary minus and negative numbers-- - see the note on TextInput::read. - - TextInput does not have helper functions for types with non-obvious - formatting, or helpers that would be redundant. Use the serialize - methods instead for parsing specific types like int, Vector3, and - Color3. - - Inside quoted strings escape sequences are converted. Thus the - string token for ["a\\nb"] is 'a', followed by a newline, followed by - 'b'. Outside of quoted strings, escape sequences are not converted, - so the token sequence for [a\\nb] is symbol 'a', symbol '\\', symbol - 'nb' (this matches what a C++ parser would do). The exception is - that a specified TextInput::Settings::otherCommentCharacter preceeded - by a backslash is assumed to be an escaped comment character and is - returned as a symbol token instead of being parsed as a comment - (this is what a LaTex or VRML parser would do). - - Examples - -

-  TextInput ti(TextInput::FROM_STRING, "name = \"Max\", height = 6");
-
-  Token t;
-
-  t = ti.read(); 
-  debugAssert(t.type == Token::SYMBOL);
-  debugAssert(t.sval == "name");
-
-  ti.read();
-  debugAssert(t.type == Token::SYMBOL);
-  debugAssert(t.sval == "=");
-
-  std::string name = ti.read().sval;
-  ti.read();
-  
- -
-  TextInput ti(TextInput::FROM_STRING, "name = \"Max\", height = 6");
-  ti.readSymbols("name", "=");
-  std::string name = ti.readString();
-  ti.readSymbols(",", "height", "=");
-  double height = ti. readNumber();
-  
- - Assumes that the file is not modified once opened. - */ -class TextInput { -public: - - /** Tokenizer configuration options. */ - class Settings { - public: - /** If true, C-style slash-star marks a multi-line comment. - - See generateCommentTokens for rules on how this is applied. - - Default is true. - */ - bool cppBlockComments; - - /** If true, // begins a single line comment. - - See generateCommentTokens for rules on how this is applied. - - Default is true. - */ - bool cppLineComments; - - /** If true, otherCommentCharacter and otherCommentCharacter2 - are used to begin single line comments in the same way - cppLineComments is. - - See generateCommentTokens for rules on how this is applied. - - Default is true. - */ - bool otherLineComments; - - /** If true, \\r, \\n, \\t, \\0, \\\\ and other escape sequences inside - strings are converted to the equivalent C++ escaped character. - If false, backslashes are treated literally. It is convenient to - set to false if reading Windows paths, for example, like - c:\\foo\\bar. - - Default is true. - */ - bool escapeSequencesInStrings; - - /** If not '\\0', specifies a character that begins single line - comments ('#' and '%' are popular choices). This is independent - of the cppLineComments flag. If the character appears in text with - a backslash in front of it, it is considered escaped and is not - treated as a comment character. - - Default is '\\0'. - */ - char otherCommentCharacter; - - /** Another (optional) 1-comment character. Useful for files that - support multiple comment syntaxes. Default is '\\0'. - */ - char otherCommentCharacter2; - - /** If true, comments enabled by cppBlockComments, cppLineComments - and otherLineComments will generate their respective tokens. - If false, the same settings will enable parsing and ignoring - comments - - Default is false. - */ - bool generateCommentTokens; - - /** If true, newlines will generate tokens. - If false, newlines will be discarded as whitespace when parsed - outside of other tokens. - - Default is false. - */ - bool generateNewlineTokens; - - /** If true, "-1" parses as the number -1 instead of the - symbol "-" followed by the number 1. Default is true.*/ - bool signedNumbers; - - /** If true, strings can be marked with single quotes (e.g., - 'aaa'). If false, the quote character is parsed as a - symbol. Default is true. Backquote (`) is always parsed - as a symbol. */ - bool singleQuotedStrings; - - /** The character to use as a single quote. Defaults to "'" (backquote), - occasionally useful to set to "`" (forward quote) or to "," (comma) for - reading CSV files. */ - char singleQuoteCharacter; - - /** If set to a non-empty string, that string will be used in - place of the real file name (or in place of a pseudonym - constructed from the buffer if given FROM_STRING) in - tokens and exceptions. - - Default is empty. - */ - std::string sourceFileName; - - - /** Added to the line number reported by peekLineNumber and in - exceptions. Useful for concatenating files that are - parsed separately. Default is zero. */ - int startingLineNumberOffset; - - /** - Parse -1.#IND00 as the floating point number returned by - nan(), -1.#INF00 as -inf(), and 1.#INF00 as inf(). Note - that the C99 standard specifies that a variety of formats - like "NaN" and "nan" are to be used; these are easier to - parse yourself and not currently supported by readNumber. - - An alternative to specifying msvcSpecials is to read numbers as: -
-            Token x = t.read();
-            Token y = t.peek();
-            if ((x.string() == "-1.") && 
-                (y.string() == "#INF00") && 
-                (y.character() == x.character() + 3) &&
-                (y.line() == x.line()) {
-                t.read();
-                return nan();
-            }
-            // ... similar cases for inf
-          
- - If the single-comment character was #, the floating point - special format overrides the comment and will be parsed - instead. - - If signedNumbers is false msvcSpecials will not be parsed. - - Default is true. */ - bool msvcSpecials; - - /** - Parse the following set of useful proof symbols: - - => - ::> - <:: - :> - <: - |- - ::= - := - <- - - Default is false. - */ - bool proofSymbols; - - /** - When parsing booleans and msvcSpecials, is case significant? - Default is {true} - */ - bool caseSensitive; - - /** All symbols that will become the 'true' boolean token. See also caseSensitive. - Clear this value to disable parsing of true booleans. - - Default is {true}. - */ - Set trueSymbols; - - /** See trueSymbols. Default is {false}*/ - Set falseSymbols; - - Settings(); - }; - -private: - - std::deque stack; - - /** - Characters to be tokenized. - */ - Array buffer; - - /** - Offset of current character (the next character to consumed) in - input buffer. - */ - int currentCharOffset; - - /** - Line number of next character to be consumed from the input buffer. (1 - indicates first line of input.) - - Note that this is the line number of the @e next character to be - consumed from the input, not the line number of the @e last character - consumed! - */ - int lineNumber; - - /** - Character number (within the line) of the next character to be consumed - from the input buffer. (1 indicates first character of the line). - - Note that this is the character number of the @e next character to be - consumed from the input, not the character number of the @e last - character consumed! - */ - int charNumber; - - /** Configuration options. This includes the file name that will be - reported in tokens and exceptions. */ - Settings options; - - void init(); - - /** - Consumes the next character from the input buffer, and returns that - character. Updates lineNumber and charNumber to reflect the location of - the next character in the input buffer. - - Note: you shouldn't be using the return value of this function in most - cases. In general, you should peekInputChar() to get the next - character, determine what to do with it, then consume it with this - function (or with eatAndPeekInputChar()). Given that usage, in most - instances you already know what this function would return! - */ - int eatInputChar(); - - /** - Returns the next character from the input buffer, without consuming any - characters. Can also be used to look deeper into the input buffer. - Does not modify lineNumber or charNumber. - - @param distance Index of the character in the input buffer to peek at, - relative to the next character. Default is 0, for the next character in - the input buffer. - */ - int peekInputChar(int distance = 0); - - /** - Helper function to consume the next character in the input buffer and - peek at the one following (without consuming it). - */ - inline int eatAndPeekInputChar() { - eatInputChar(); - return peekInputChar(0); - } - - /** - Read the next token, returning an END token if no more input is - available. - */ - Token nextToken(); - - /** - Helper for nextToken. Appends characters to t._string until the end - delimiter is reached. - - When called, the next character in the input buffer should be first the - first character after the opening delimiter character. - */ - void parseQuotedString(unsigned char delimiter, Token& t); - -public: - - class TokenException : public ParseError { - public: - /** Name of file being parsed when exception occurred. - \deprecated Use filename - */ - std::string sourceFile; - - virtual ~TokenException() {} - - protected: - - TokenException( - const std::string& src, - int ln, - int ch); - - }; - - /** While parsing a number of the form 1.\#IN?00, ? was - not 'D' or 'F'. */ - class BadMSVCSpecial : public TokenException { - public: - - BadMSVCSpecial( - const std::string& src, - int ln, - int ch); - }; - - /** Thrown by the read methods. */ - class WrongTokenType : public TokenException { - public: - Token::Type expected; - Token::Type actual; - - WrongTokenType( - const std::string& src, - int ln, - int ch, - Token::Type e, - Token::Type a); - }; - - class WrongSymbol : public TokenException { - public: - std::string expected; - std::string actual; - - WrongSymbol( - const std::string& src, - int ln, - int ch, - const std::string& e, - const std::string& a); - }; - - - /** String read from input did not match expected string. */ - class WrongString : public TokenException { - public: - std::string expected; - std::string actual; - - WrongString( - const std::string& src, - int ln, - int ch, - const std::string& e, - const std::string& a); - }; - - TextInput(const std::string& filename, const Settings& settings = Settings()); - - enum FS {FROM_STRING}; - /** Creates input directly from a string. The first argument must be - TextInput::FROM_STRING. - */ - TextInput(FS fs, const std::string& str, const Settings& settings = Settings()); - - /** Returns true while there are tokens remaining. */ - bool hasMore(); - - /** Read the next token (which will be the END token if ! hasMore()). - - Signed numbers can be handled in one of two modes. If the option - TextInput::Settings::signedNumbers is true, - A '+' or '-' immediately before a number is prepended onto that number and - if there is intervening whitespace, it is read as a separate symbol. - - If TextInput::Settings::signedNumbers is false, - read() does not distinguish between a plus or minus symbol next - to a number and a positive/negative number itself. For example, "x - 1" and "x -1" - will be parsed the same way by read(). - - In both cases, readNumber() will contract a leading "-" or "+" onto - a number. - */ - Token read(); - - /** Calls read() until the result is not a newline or comment */ - Token readSignificant(); - - /** Read one token (or possibly two) as a number or throws - WrongTokenType, and returns the number. - - If the first token in the input is a number, it is returned directly. - - If TextInput::Settings::signedNumbers is false and the input stream - contains a '+' or '-' symbol token immediately followed by a number - token, both tokens will be consumed and a single token will be - returned by this method. - - WrongTokenType will be thrown if one of the input conditions - described above is not satisfied. When an exception is thrown, no - tokens are consumed. - */ - double readNumber(); - - bool readBoolean(); - - /** Reads a string token or throws WrongTokenType, and returns the token. - - Use this method (rather than readString) if you want the token's - location as well as its value. - - WrongTokenType will be thrown if the next token in the input stream - is not a string. When an exception is thrown, no tokens are - consumed. - */ - Token readStringToken(); - - /** Like readStringToken, but returns the token's string. - - Use this method (rather than readStringToken) if you want the token's - value but don't really care about its location in the input. Use of - readStringToken is encouraged for better error reporting. - */ - std::string readString(); - - /** Reads a specific string token or throws either WrongTokenType or - WrongString. If the next token in the input is a string matching @p - s, it will be consumed. - - Use this method if you want to match a specific string from the - input. In that case, typically error reporting related to the token - is only going to occur because of a mismatch, so no location - information is needed by the caller. - - WrongTokenType will be thrown if the next token in the input stream - is not a string. WrongString will be thrown if the next token in the - input stream is a string but does not match the @p s parameter. When - an exception is thrown, no tokens are consumed. - */ - void readString(const std::string& s); - - /** Reads a comment token or throws WrongTokenType, and returns the token. - - Use this method (rather than readComment) if you want the token's - location as well as its value. - - WrongTokenType will be thrown if the next token in the input stream - is not a comment. When an exception is thrown, no tokens are - consumed. - */ - Token readCommentToken(); - - /** Like readCommentToken, but returns the token's string. - - Use this method (rather than readCommentToken) if you want the token's - value but don't really care about its location in the input. Use of - readCommentToken is encouraged for better error reporting. - */ - std::string readComment(); - - /** Reads a specific comment token or throws either WrongTokenType or - WrongString. If the next token in the input is a comment matching @p - s, it will be consumed. - - Use this method if you want to match a specific comment from the - input. In that case, typically error reporting related to the token - is only going to occur because of a mismatch, so no location - information is needed by the caller. - - WrongTokenType will be thrown if the next token in the input stream - is not a comment. WrongString will be thrown if the next token in the - input stream is a comment but does not match the @p s parameter. When - an exception is thrown, no tokens are consumed. - */ - void readComment(const std::string& s); - - /** Reads a newline token or throws WrongTokenType, and returns the token. - - Use this method (rather than readNewline) if you want the token's - location as well as its value. - - WrongTokenType will be thrown if the next token in the input stream - is not a newline. When an exception is thrown, no tokens are - consumed. - */ - Token readNewlineToken(); - - /** Like readNewlineToken, but returns the token's string. - - Use this method (rather than readNewlineToken) if you want the token's - value but don't really care about its location in the input. Use of - readNewlineToken is encouraged for better error reporting. - */ - std::string readNewline(); - - /** Reads a specific newline token or throws either WrongTokenType or - WrongString. If the next token in the input is a newline matching @p - s, it will be consumed. - - Use this method if you want to match a specific newline from the - input. In that case, typically error reporting related to the token - is only going to occur because of a mismatch, so no location - information is needed by the caller. - - WrongTokenType will be thrown if the next token in the input stream - is not a newline. WrongString will be thrown if the next token in the - input stream is a newlin but does not match the @p s parameter. When - an exception is thrown, no tokens are consumed. - */ - void readNewline(const std::string& s); - - /** Reads a symbol token or throws WrongTokenType, and returns the token. - - Use this method (rather than readSymbol) if you want the token's - location as well as its value. - - WrongTokenType will be thrown if the next token in the input stream - is not a symbol. When an exception is thrown, no tokens are - consumed. - */ - Token readSymbolToken(); - - /** Like readSymbolToken, but returns the token's string. - - Use this method (rather than readSymbolToken) if you want the token's - value but don't really care about its location in the input. Use of - readSymbolToken is encouraged for better error reporting. - */ - std::string readSymbol(); - - /** Reads a specific symbol token or throws either WrongTokenType or - WrongSymbol. If the next token in the input is a symbol matching @p - symbol, it will be consumed. - - Use this method if you want to match a specific symbol from the - input. In that case, typically error reporting related to the token - is only going to occur because of a mismatch, so no location - information is needed by the caller. - - WrongTokenType will be thrown if the next token in the input stream - is not a symbol. WrongSymbol will be thrown if the next token in the - input stream is a symbol but does not match the @p symbol parameter. - When an exception is thrown, no tokens are consumed. - */ - void readSymbol(const std::string& symbol); - - - /** Read a series of two specific symbols. See readSymbol. */ - inline void readSymbols(const std::string& s1, const std::string& s2) { - readSymbol(s1); - readSymbol(s2); - } - - /** Read a series of three specific symbols. See readSymbol. */ - inline void readSymbols( - const std::string& s1, - const std::string& s2, - const std::string& s3) { - readSymbol(s1); - readSymbol(s2); - readSymbol(s3); - } - - /** Read a series of four specific symbols. See readSymbol. */ - inline void readSymbols( - const std::string& s1, - const std::string& s2, - const std::string& s3, - const std::string& s4) { - readSymbol(s1); - readSymbol(s2); - readSymbol(s3); - readSymbol(s4); - } - - /** Return a copy of the next token in the input stream, but don't remove - it from the input stream. - */ - Token peek(); - - /** Returns the line number for the @e next token. See also peek. */ - int peekLineNumber(); - - /** Returns the character number (relative to the line) for the @e next - token in the input stream. See also peek. - */ - int peekCharacterNumber(); - - /** Take a previously read token and push it back at the front of the - input stream. - - Can be used in the case where more than one token of read-ahead is - needed (i.e., when peek doesn't suffice). - */ - void push(const Token& t); - - /** Returns the filename from which this input is drawn, or the first few - characters of the string if created from a string. - If settings::filename is non-empty that will replace the - true filename.*/ - const std::string& filename() const; -}; - -void deserialize(bool& b, TextInput& ti); -void deserialize(int& b, TextInput& ti); -void deserialize(uint8& b, TextInput& ti); -void deserialize(double& b, TextInput& ti); -void deserialize(float& b, TextInput& ti); -void deserialize(std::string& b, TextInput& ti); - -} // namespace - -#endif - diff --git a/externals/g3dlite/G3D/TextOutput.h b/externals/g3dlite/G3D/TextOutput.h deleted file mode 100644 index 4c22b7d5653..00000000000 --- a/externals/g3dlite/G3D/TextOutput.h +++ /dev/null @@ -1,249 +0,0 @@ -/** - @file TextOutput.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - @created 2004-06-21 - @edited 2006-10-24 - - Copyright 2000-2007, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_TEXTOUTPUT_H -#define G3D_TEXTOUTPUT_H - -#include "G3D/platform.h" -#include "G3D/Array.h" -#include - -namespace G3D { - -/** - Convenient formatting of ASCII text written to a file. -

- - The core writeString, writeNumber, and writeSymbol methods map to TextInput's - methods. Number and Symbol each print an additional space that is used to - separate adjacent tokens. - - TextOutput::printf allows arbitrary text to be conveniently dumped - en-masse. Use [de]serialize(bool, TextOutput) and other overloads to read/write - primitive types in a standardized manner and - -

- When a word-wrap line break occurs, all whitespace between words is replaced - with a single newline (the newline may be two characters-- see - G3D::TextOutput::Options::NewlineStyle). Word wrapping occurs against - the number of columns specified by Options::numColumns, minus the current - indent level. - - Indenting adds the specified number of spaces immediately after a newline. - If a newline was followed by spaces in the original string, these are added - to the indent spaces. Indenting will indent blank lines and will leave - indents after the last newline of a file (if the indent level is non-zero at the end). - -

Serialization/Marshalling -

Text serialization is accomplished using TextOutput by defining the pair of - methods: - -
-  void serialize(TextOutput& to) const;
-  void deserialize(TextInput& ti);
-  
- - See also G3D::TextInput. - -

- BETA API -

This API is subject to change in future versions. - */ -class TextOutput { -public: - - class Settings { - public: - /** - WRAP_NONE Word wrapping is disabled - WRAP_WITHOUT_BREAKING Word-wrap, but don't break continuous lines that - are longer than numColumns (default) - WRAP_ALWAYS Wrap even if it means breaking a continuous line or - a quoted string. - - Word wrapping is only allowed at whitespaces ('\\n', '\\r', '\\t', ' '); it - will not occur after commas, punctuation, minus signs, or any other characters - */ - enum WordWrapMode {WRAP_NONE, WRAP_WITHOUT_BREAKING, WRAP_ALWAYS}; - - /** Defaults to WRAP_WITHOUT_BREAKING */ - WordWrapMode wordWrap; - - /** Is word-wrapping allowed to insert newlines inside double quotes? - Default: false */ - bool allowWordWrapInsideDoubleQuotes; - - /** Number of columns for word wrapping. Default: 8 */ - int numColumns; - - /** Number of spaces in each indent. Default: 4 */ - int spacesPerIndent; - - /** Style of newline used by word wrapping and by (optional) conversion. - default: Windows: NEWLINE_WINDOWS, Linux, OS X: NEWLINE_UNIX. - */ - enum NewlineStyle {NEWLINE_WINDOWS, NEWLINE_UNIX}; - - NewlineStyle newlineStyle; - - /** If true, all newlines are converted to NewlineStyle regardless of - how they start out. Default: true. */ - bool convertNewlines; - - /** Used by writeBoolean */ - std::string trueSymbol; - - /** Used by writeBoolean */ - std::string falseSymbol; - - Settings() : - wordWrap(WRAP_WITHOUT_BREAKING), - allowWordWrapInsideDoubleQuotes(false), - numColumns(80), - spacesPerIndent(4), - convertNewlines(true), - trueSymbol("true"), - falseSymbol("false") { - #ifdef G3D_WIN32 - newlineStyle = NEWLINE_WINDOWS; - #else - newlineStyle = NEWLINE_UNIX; - #endif - } - }; - -private: - - /** Used by indentAndAppend to tell when we are writing the - first character of a new line. - - So that push/popIndent work correctly, we cannot indent - immediately after writing a newline. Instead we must - indent on writing the first character after that - newline. - */ - bool startingNewLine; - - /** Number of characters at the end of the buffer since the last newline */ - int currentColumn; - - /** True if we have seen an open " and no close ".*/ - bool inDQuote; - - /** Empty if there is none */ - std::string filename; - - Array data; - - Settings option; - - /** Number of indents to prepend before each line. Always set using setIndentLevel.*/ - int indentLevel; - - void setIndentLevel(int i); - - /** Actual number of spaces to indent. */ - int indentSpaces; - - /** the newline character(s) */ - std::string newline; - - void setOptions(const Settings& _opt); - - /** Converts to the desired newlines. Called from vprintf */ - void convertNewlines(const std::string& in, std::string& out); - - /** Called from vprintf */ - void wordWrapIndentAppend(const std::string& str); - - /** Appends the character to data, indenting whenever a newline is encountered. - Called from wordWrapIndentAppend */ - void indentAppend(char c); - -public: - - explicit TextOutput(const std::string& filename, const Settings& options = Settings()); - - /** Constructs a text output that can later be commited to a string instead of a file.*/ - explicit TextOutput(const Settings& options = Settings()); - - /** Commit to the filename specified on the constructor. - Not called from the destructor; you must call - it yourself. - @param flush If true (default) the file is ready for reading when the method returns, otherwise - the method returns immediately and writes the file in the background.*/ - void commit(bool flush = true); - - /** Commits to this string */ - void commitString(std::string& string); - - /** Increase indent level by 1 */ - void pushIndent(); - - void popIndent(); - - /** Produces a new string that contains the output */ - std::string commitString(); - - /** Writes a quoted string. Special characters in the string (e.g., \\, \\t, \\n) are escaped so that - TextInput will produce the identical string on reading.*/ - void writeString(const std::string& string); - - void writeBoolean(bool b); - - void writeNumber(double n); - - void writeNumber(int n); - - void writeNewline(); - void writeNewlines(int numLines); - - /** The symbol is written without quotes. Symbols are required to begin with a - letter or underscore and contain only letters, underscores, and numbers - or be a C++ symbol (e.g. "{", "(", "++", etc.) - so that they may be properly parsed by TextInput::readSymbol. Symbols are - printed with a trailing space.*/ - void writeSymbol(const std::string& string); - - /** Convenient idiom for writing multiple symbols in a row, e.g. - writeSymbols("name", "="); The empty symbols are not written. - */ - void writeSymbols( - const std::string& a, - const std::string& b = "", - const std::string& c = "", - const std::string& d = "", - const std::string& e = "", - const std::string& f = ""); - - /** Normal printf conventions. Note that the output will be reformatted - for word-wrapping and newlines */ - void __cdecl printf(const char* fmt, ...) - G3D_CHECK_PRINTF_METHOD_ARGS; - - // Can't pass by reference because that confuses va_start - void __cdecl printf(const std::string fmt, ...); - void __cdecl vprintf(const char* fmt, va_list argPtr) - G3D_CHECK_VPRINTF_METHOD_ARGS; -}; - -// Primitive serializers -void serialize(const bool& b, TextOutput& to); -void serialize(const int& b, TextOutput& to); -void serialize(const uint8& b, TextOutput& to); -void serialize(const double& b, TextOutput& to); -void serialize(const float& b, TextOutput& to); -void serialize(const std::string& b, TextOutput& to); -void serialize(const char* b, TextOutput& to); - -} - -#endif diff --git a/externals/g3dlite/G3D/ThreadSet.h b/externals/g3dlite/G3D/ThreadSet.h deleted file mode 100644 index 121f1415a1d..00000000000 --- a/externals/g3dlite/G3D/ThreadSet.h +++ /dev/null @@ -1,87 +0,0 @@ -#ifndef G3D_THREADSET_H -#define G3D_THREADSET_H - -#include "G3D/platform.h" -#include "G3D/Array.h" -#include "G3D/ReferenceCount.h" -#include "G3D/GThread.h" -#include "G3D/GMutex.h" - -namespace G3D { - -/** Manages a set of threads. All methods are threadsafe except for - the iterator begin/end. - - @beta*/ -class ThreadSet : public ReferenceCountedObject { -public: - /** Intended to allow future use with a template parameter.*/ - typedef GThread Thread; - - typedef ReferenceCountedPointer ThreadRef; - typedef ReferenceCountedPointer Ref; - typedef Array::Iterator Iterator; - typedef Array::ConstIterator ConstIterator; - -private: - - /** Protects m_thread */ - GMutex m_lock; - - /** Threads in the set */ - Array m_thread; - -public: - - /** Total number of threads (some of which may be completed). */ - int size() const; - - /** Number of threads that have been started */ - int numStarted() const; - - /** Start all threads that are not currently started. - - @param lastThreadBehavior If USE_CURRENT_THREAD, takes the last unstarted thread and executes it manually on - the current thread. This helps to take full advantage of the machine when - running a large number of jobs and avoids the overhead of a thread start for single-thread groups. - Note that this forces start() to block until - that thread is complete. - */ - void start(GThread::SpawnBehavior lastThreadBehavior = GThread::USE_NEW_THREAD) const; - - /** Terminate all threads that are currently started */ - void terminate() const; - - /** Waits until all started threads have completed. */ - void waitForCompletion() const; - - /** Remove all (not stopping them) */ - void clear(); - - /** Removes completed threads and returns the new size.*/ - int removeCompleted(); - - /** Inserts a new thread, if it is not already present, and - returns the new number of threads.*/ - int insert(const ThreadRef& t); - - /** Removes a thread. Returns true if the thread was present and - removed. */ - bool remove(const ThreadRef& t); - - bool contains(const ThreadRef& t) const; - - /** It is an error to mutate the ThreadSet while iterating through it. */ - Iterator begin(); - - Iterator end(); - - ConstIterator begin() const; - - ConstIterator end() const; -}; - - -} // namespace G3D - -#endif diff --git a/externals/g3dlite/G3D/Triangle.h b/externals/g3dlite/G3D/Triangle.h deleted file mode 100644 index 590dbaad946..00000000000 --- a/externals/g3dlite/G3D/Triangle.h +++ /dev/null @@ -1,160 +0,0 @@ -/** - @file Triangle.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2003-04-05 - @edited 2008-10-06 - - @cite Random point method by Greg Turk, Generating random points in triangles. In A. S. Glassner, ed., Graphics Gems, pp. 24-28. Academic Press, 1990 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_TRIANGLE_H -#define G3D_TRIANGLE_H - -#include "G3D/platform.h" -#include "G3D/g3dmath.h" -#include "G3D/Vector3.h" -#include "G3D/Plane.h" -#include "G3D/BoundsTrait.h" -#include "G3D/debugAssert.h" -#include - -namespace G3D { - -/** - A generic triangle representation. This should not be used - as the underlying triangle for creating models; it is intended - for providing fast property queries but requires a lot of - storage and is mostly immutable. - */ -class Triangle { -private: - friend class CollisionDetection; - friend class Ray; - - Vector3 _vertex[3]; - - /** edgeDirection[i] is the normalized vector v[i+1] - v[i] */ - Vector3 edgeDirection[3]; - float edgeMagnitude[3]; - Plane _plane; - Vector3::Axis _primaryAxis; - - /** vertex[1] - vertex[0] */ - Vector3 _edge01; - - /** vertex[2] - vertex[0] */ - Vector3 _edge02; - - float _area; - - void init(const Vector3& v0, const Vector3& v1, const Vector3& v2); - -public: - - Triangle(class BinaryInput& b); - void serialize(class BinaryOutput& b); - void deserialize(class BinaryInput& b); - - Triangle(); - - Triangle(const Vector3& v0, const Vector3& v1, const Vector3& v2); - - ~Triangle(); - - /** 0, 1, or 2 */ - inline const Vector3& vertex(int n) const { - debugAssert((n >= 0) && (n < 3)); - return _vertex[n]; - } - - /** vertex[1] - vertex[0] */ - inline const Vector3& edge01() const { - return _edge01; - } - - /** vertex[2] - vertex[0] */ - inline const Vector3& edge02() const { - return _edge02; - } - - float area() const; - - Vector3::Axis primaryAxis() const { - return _primaryAxis; - } - - const Vector3& normal() const; - - /** Barycenter */ - Vector3 center() const; - - const Plane& plane() const; - - /** Returns a random point in the triangle. */ - Vector3 randomPoint() const; - - inline void getRandomSurfacePoint - (Vector3& P, - Vector3& N = Vector3::ignore()) const { - P = randomPoint(); - N = normal(); - } - - /** - For two triangles to be equal they must have - the same vertices in the same order. - That is, vertex[0] == vertex[0], etc. - */ - inline bool operator==(const Triangle& other) const { - for (int i = 0; i < 3; ++i) { - if (_vertex[i] != other._vertex[i]) { - return false; - } - } - - return true; - } - - inline size_t hashCode() const { - return - _vertex[0].hashCode() + - (_vertex[1].hashCode() >> 2) + - (_vertex[2].hashCode() >> 3); - } - - void getBounds(class AABox&) const; - - /** - @brief Intersect the ray at distance less than @a distance. - - @param distance Set to the maximum distance (can be G3D::inf()) - to search for an intersection. On return, this is the smaller - of the distance to the intersection, if one exists, and the original - value. - - @param baryCoord If a triangle is hit before @a distance, a - the barycentric coordinates of the hit location on the triangle. - Otherwise, unmodified. - - @return True if there was an intersection before the original distance. - */ - bool intersect(const class Ray& ray, float& distance, float baryCoord[3]) const; -}; - -} // namespace G3D - -template <> struct HashTrait { - static size_t hashCode(const G3D::Triangle& key) { return key.hashCode(); } -}; - - -template<> struct BoundsTrait { - static void getBounds(const G3D::Triangle& t, G3D::AABox& out) { t.getBounds(out); } -}; - -#endif diff --git a/externals/g3dlite/G3D/UprightFrame.h b/externals/g3dlite/G3D/UprightFrame.h deleted file mode 100644 index ad5157cb14b..00000000000 --- a/externals/g3dlite/G3D/UprightFrame.h +++ /dev/null @@ -1,83 +0,0 @@ -/** - @file UprightFrame.h - - @author Morgan McGuire, http://graphics.cs.williams.edu - */ - -#ifndef G3D_UPRIGHTFRAME_H -#define G3D_UPRIGHTFRAME_H - -#include "G3D/platform.h" -#include "G3D/Spline.h" -#include "G3D/Vector3.h" -#include "G3D/CoordinateFrame.h" - -namespace G3D { - -/** - Coordinate frame expressed in Euler angles. - Unlike a G3D::Quat, UprightFrame always keeps the reference frame from rolling about its own z axis. - Particularly useful for cameras. - - @sa G3D::CoordinateFrame, G3D::Matrix4, G3D::PhysicsFrame, G3D::UprightSpline, G3D::UprightSplineManipulator - */ -class UprightFrame { -public: - - Vector3 translation; - - /** -pi/2 < pitch < pi/2 in radians about the X-axis */ - float pitch; - - /** In radians about the Y-axis */ - float yaw; - - inline UprightFrame(const Vector3& t = Vector3::zero(), float p = 0, float y = 0) - : translation(t), pitch(p), yaw(y) {} - - UprightFrame(const CoordinateFrame& cframe); - - CoordinateFrame toCoordinateFrame() const; - - /** Supports implicit cast to CoordinateFrame */ - inline operator CoordinateFrame() const { - return toCoordinateFrame(); - } - - /** Required for use with spline */ - UprightFrame operator+(const UprightFrame& other) const; - - /** Required for use with spline */ - UprightFrame operator*(const float k) const; - - /** - Unwraps the yaw values in the elements of the array such that - they still represent the same angles but strictly increase/decrease - without wrapping about zero. For use with Spline - */ - static void unwrapYaw(UprightFrame* a, int N); - - void serialize(class BinaryOutput& b) const; - void deserialize(class BinaryInput& b); -}; - -/** Shortest-path linear velocity spline for camera positions. Always keeps the camera from rolling. -@sa G3D::UprightSplineManipulator, G3D::UprightFrame -*/ -class UprightSpline : public Spline { -protected: - - virtual void ensureShortestPath(UprightFrame* A, int N) const { - UprightFrame::unwrapYaw(A, N); - } - -public: - - void serialize(class BinaryOutput& b) const; - void deserialize(class BinaryInput& b); - -}; - -} - -#endif diff --git a/externals/g3dlite/G3D/Vector2.h b/externals/g3dlite/G3D/Vector2.h deleted file mode 100644 index dba7353785e..00000000000 --- a/externals/g3dlite/G3D/Vector2.h +++ /dev/null @@ -1,454 +0,0 @@ -/** - @file Vector2.h - - 2D vector class - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2001-06-02 - @edited 2008-11-30 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. -*/ - -#ifndef G3D_VECTOR2_H -#define G3D_VECTOR2_H - -#include - -#include "G3D/platform.h" -#include "G3D/g3dmath.h" -#include "G3D/Table.h" -#include "G3D/HashTrait.h" -#include "G3D/Vector2int16.h" -#include "G3D/Random.h" - -namespace G3D { - -class Vector2; -class Vector3; -class Vector4; -class Any; - -/** - Do not subclass-- this implementation makes assumptions about the - memory layout. - */ -class Vector2 { -private: - // Hidden operators - bool operator<(const Vector2&) const; - bool operator>(const Vector2&) const; - bool operator<=(const Vector2&) const; - bool operator>=(const Vector2&) const; - -public: - float x; - float y; - - /** \param any Must either Vector2(#, #) or Vector2 {x = #, y = #}*/ - Vector2(const Any& any); - - /** Converts the Vector2 to an Any. */ - operator Any() const; - - /** Creates the zero vector */ - Vector2(); - Vector2(class TextInput& t); - Vector2(class BinaryInput& b); - Vector2(float x, float y); - Vector2(float coordinate[2]); - Vector2(double coordinate[2]); - Vector2(const Vector2& other); - Vector2(const Vector2int16& other); - - void serialize(class BinaryOutput& b) const; - void deserialize(class BinaryInput& b); - - void serialize(class TextOutput& t) const; - void deserialize(class TextInput& t); - - float& operator[](int i); - const float& operator[](int i) const; - - // assignment and comparison - Vector2& operator=(const Vector2& other); - bool operator==(const Vector2& other) const; - bool operator!=(const Vector2& other) const; - size_t hashCode() const; - bool fuzzyEq(const Vector2& other) const; - bool fuzzyNe(const Vector2& other) const; - - /** Returns true if this vector has finite length */ - bool isFinite() const; - - /** Returns true if this vector has length == 0 */ - bool isZero() const; - - /** Returns true if this vector has length == 1 */ - bool isUnit() const; - - // arithmetic operations - Vector2 operator+(const Vector2& v) const; - Vector2 operator-(const Vector2& v) const; - Vector2 operator*(float s) const; - - /** Array (pointwise) multiplication */ - Vector2 operator*(const Vector2& v) const; - - /** Array division */ - Vector2 operator/(const Vector2& v) const; - Vector2 operator/(float s) const; - - /** Unary minus */ - Vector2 operator-() const; - - /** x + y */ - inline float sum() const { - return x + y; - } - - /** - Linear interpolation - */ - inline Vector2 lerp(const Vector2& v, float alpha) const { - return (*this) + (v - *this) * alpha; - } - - inline Vector2 clamp(const Vector2& low, const Vector2& high) const { - return Vector2( - G3D::clamp(x, low.x, high.x), - G3D::clamp(y, low.y, high.y)); - } - - inline Vector2 clamp(float low, float high) const { - return Vector2( - (float)G3D::clamp(x, low, high), - (float)G3D::clamp(y, low, high)); - } - - // arithmetic updates - Vector2& operator+=(const Vector2&); - Vector2& operator-=(const Vector2&); - Vector2& operator*=(float); - Vector2& operator/=(float); - Vector2& operator*=(const Vector2&); - Vector2& operator/=(const Vector2&); - - // vector operations - - /** */ - float length() const; - - /** Returns a unit-length vector */ - Vector2 direction() const; - - /** - Potentially less accurate but faster than direction(). - Only works if System::hasSSE is true. - */ - Vector2 fastDirection() const { - return direction(); - } - - float squaredLength() const; - float dot(const Vector2& s) const; - - /** - Make this vector have unit length and return the old length. - If the vector length was less than tolerance, do not normalize. - */ - float unitize(float fTolerance = 1e-06); - - Vector2 min(const Vector2& v) const; - Vector2 max(const Vector2& v) const; - - /** Uniformly distributed random vector on the unit sphere */ - static Vector2 random(Random& r = Random::common()); - - // Special values. - // Intentionally not inlined: see Matrix3::identity() for details. - static const Vector2& zero(); - static const Vector2& one(); - static const Vector2& unitX(); - static const Vector2& unitY(); - static const Vector2& inf(); - static const Vector2& nan(); - /** smallest (most negative) representable vector */ - static const Vector2& minFinite(); - /** Largest representable vector */ - static const Vector2& maxFinite(); - - std::string toString() const; - - // 2-char swizzles - - Vector2 xx() const; - Vector2 yx() const; - Vector2 xy() const; - Vector2 yy() const; - - // 3-char swizzles - - Vector3 xxx() const; - Vector3 yxx() const; - Vector3 xyx() const; - Vector3 yyx() const; - Vector3 xxy() const; - Vector3 yxy() const; - Vector3 xyy() const; - Vector3 yyy() const; - - // 4-char swizzles - - Vector4 xxxx() const; - Vector4 yxxx() const; - Vector4 xyxx() const; - Vector4 yyxx() const; - Vector4 xxyx() const; - Vector4 yxyx() const; - Vector4 xyyx() const; - Vector4 yyyx() const; - Vector4 xxxy() const; - Vector4 yxxy() const; - Vector4 xyxy() const; - Vector4 yyxy() const; - Vector4 xxyy() const; - Vector4 yxyy() const; - Vector4 xyyy() const; - Vector4 yyyy() const; - -}; - -inline Vector2 operator*(double s, const Vector2& v) { - return v * (float)s; -} - -inline Vector2 operator*(float s, const Vector2& v) { - return v * s; -} - -inline Vector2 operator*(int s, const Vector2& v) { - return v * (float)s; -} - - -inline Vector2::Vector2 () : x(0.0f), y(0.0f) { -} - - -inline Vector2::Vector2(float _x, float _y) : x(_x), y(_y) { -} - - -inline Vector2::Vector2 (float afCoordinate[2]) { - x = afCoordinate[0]; - y = afCoordinate[1]; -} - - - -inline Vector2::Vector2 (double afCoordinate[2]) { - x = (float)afCoordinate[0]; - y = (float)afCoordinate[1]; -} - - -inline Vector2::Vector2 (const Vector2& rkVector) { - x = rkVector.x; - y = rkVector.y; -} - - -inline Vector2::Vector2 (const Vector2int16& v) : x(v.x), y(v.y) { -} - - -inline float& Vector2::operator[] (int i) { - return ((float*)this)[i]; -} - - -inline const float& Vector2::operator[] (int i) const { - return ((float*)this)[i]; -} - - -inline Vector2& Vector2::operator= (const Vector2& rkVector) { - x = rkVector.x; - y = rkVector.y; - return *this; -} - - -inline bool Vector2::operator== (const Vector2& rkVector) const { - return ( x == rkVector.x && y == rkVector.y); -} - - -inline bool Vector2::operator!= (const Vector2& rkVector) const { - return ( x != rkVector.x || y != rkVector.y); -} - - -inline Vector2 Vector2::operator+ (const Vector2& rkVector) const { - return Vector2(x + rkVector.x, y + rkVector.y); -} - - -inline Vector2 Vector2::operator- (const Vector2& rkVector) const { - return Vector2(x - rkVector.x, y - rkVector.y); -} - - -inline Vector2 Vector2::operator* (float fScalar) const { - return Vector2(fScalar*x, fScalar*y); -} - - - -inline Vector2 Vector2::operator- () const { - return Vector2( -x, -y); -} - - - -inline Vector2& Vector2::operator+= (const Vector2& rkVector) { - x += rkVector.x; - y += rkVector.y; - return *this; -} - - - -inline Vector2& Vector2::operator-= (const Vector2& rkVector) { - x -= rkVector.x; - y -= rkVector.y; - return *this; -} - - - -inline Vector2& Vector2::operator*= (float fScalar) { - x *= fScalar; - y *= fScalar; - return *this; -} - - - - -inline Vector2& Vector2::operator*= (const Vector2& rkVector) { - x *= rkVector.x; - y *= rkVector.y; - return *this; -} - - - -inline Vector2& Vector2::operator/= (const Vector2& rkVector) { - x /= rkVector.x; - y /= rkVector.y; - return *this; -} - - -inline Vector2 Vector2::operator* (const Vector2& rkVector) const { - return Vector2(x * rkVector.x, y * rkVector.y); -} - - - -inline Vector2 Vector2::operator/ (const Vector2& rkVector) const { - return Vector2(x / rkVector.x, y / rkVector.y); -} - - -inline float Vector2::squaredLength () const { - return x*x + y*y; -} - - -inline float Vector2::length () const { - return sqrtf(x*x + y*y); -} - - -inline Vector2 Vector2::direction () const { - float lenSquared = x * x + y * y; - - if (lenSquared != 1.0f) { - return *this / sqrtf(lenSquared); - } else { - return *this; - } -} - - - -inline float Vector2::dot (const Vector2& rkVector) const { - return x*rkVector.x + y*rkVector.y; -} - - - -inline Vector2 Vector2::min(const Vector2 &v) const { - return Vector2(G3D::min(v.x, x), G3D::min(v.y, y)); -} - - - -inline Vector2 Vector2::max(const Vector2 &v) const { - return Vector2(G3D::max(v.x, x), G3D::max(v.y, y)); -} - - - -inline bool Vector2::fuzzyEq(const Vector2& other) const { - return G3D::fuzzyEq((*this - other).squaredLength(), 0); -} - - - -inline bool Vector2::fuzzyNe(const Vector2& other) const { - return G3D::fuzzyNe((*this - other).squaredLength(), 0); -} - - - -inline bool Vector2::isFinite() const { - return G3D::isFinite(x) && G3D::isFinite(y); -} - - - -inline bool Vector2::isZero() const { - return (x == 0.0f) && (y == 0.0f); -} - - - -inline bool Vector2::isUnit() const { - return squaredLength() == 1.0f; -} - -} // namespace G3D - -template <> -struct HashTrait { - static size_t hashCode(const G3D::Vector2& key) { - return key.hashCode(); - } -}; - - -// Intentionally outside namespace to avoid operator overloading confusion -inline G3D::Vector2 operator*(double s, const G3D::Vector2& v) { - return v * (float)s; -} -inline G3D::Vector2 operator*(int s, const G3D::Vector2& v) { - return v * (float)s; -} - -#endif diff --git a/externals/g3dlite/G3D/Vector2.inl b/externals/g3dlite/G3D/Vector2.inl deleted file mode 100644 index 4f7c55a39cf..00000000000 --- a/externals/g3dlite/G3D/Vector2.inl +++ /dev/null @@ -1,18 +0,0 @@ -/** - @file Vector2.inl - - @maintainer Morgan McGuire, matrix@graphics3d.com - @cite Portions by Laura Wollstadt, graphics3d.com - - @cite Portions based on Dave Eberly'x Magic Software Library - at http://www.magic-software.com - - @created 2001-06-02 - @edited 2006-01-14 - - Copyright 2000-2006, Morgan McGuire. - All rights reserved. - */ - -} - diff --git a/externals/g3dlite/G3D/Vector2int16.h b/externals/g3dlite/G3D/Vector2int16.h deleted file mode 100644 index ba72266d75a..00000000000 --- a/externals/g3dlite/G3D/Vector2int16.h +++ /dev/null @@ -1,127 +0,0 @@ -/** - @file Vector2int16.h - - @maintainer Morgan McGuire, matrix@brown.edu - - @created 2003-08-09 - @edited 2004-01-03 - - Copyright 2000-2006, Morgan McGuire. - All rights reserved. - */ - -#ifndef VECTOR2INT16_H -#define VECTOR2INT16_H - -#include "G3D/platform.h" -#include "G3D/g3dmath.h" -#include "G3D/HashTrait.h" - -namespace G3D { - -/** - \class Vector2int16 - A Vector2 that packs its fields into uint16s. - */ -G3D_BEGIN_PACKED_CLASS(2) -class Vector2int16 { -private: - // Hidden operators - bool operator<(const Vector2int16&) const; - bool operator>(const Vector2int16&) const; - bool operator<=(const Vector2int16&) const; - bool operator>=(const Vector2int16&) const; - -public: - G3D::int16 x; - G3D::int16 y; - - Vector2int16() : x(0), y(0) {} - Vector2int16(G3D::int16 _x, G3D::int16 _y) : x(_x), y(_y){} - Vector2int16(const class Vector2& v); - Vector2int16(class BinaryInput& bi); - - inline G3D::int16& operator[] (int i) { - debugAssert(((unsigned int)i) <= 1); - return ((G3D::int16*)this)[i]; - } - - inline const G3D::int16& operator[] (int i) const { - debugAssert(((unsigned int)i) <= 1); - return ((G3D::int16*)this)[i]; - } - - inline Vector2int16 operator+(const Vector2int16& other) const { - return Vector2int16(x + other.x, y + other.y); - } - - inline Vector2int16 operator-(const Vector2int16& other) const { - return Vector2int16(x - other.x, y - other.y); - } - - inline Vector2int16 operator*(const Vector2int16& other) const { - return Vector2int16(x * other.x, y * other.y); - } - - inline Vector2int16 operator*(const int s) const { - return Vector2int16(x * s, y * s); - } - - inline Vector2int16& operator+=(const Vector2int16& other) { - x += other.x; - y += other.y; - return *this; - } - - /** Shifts both x and y */ - inline Vector2int16 operator>>(const int s) const { - return Vector2int16(x >> s, y >> s); - } - - /** Shifts both x and y */ - inline Vector2int16 operator<<(const int s) const { - return Vector2int16(x << s, y << s); - } - - inline Vector2int16& operator-=(const Vector2int16& other) { - x -= other.x; - y -= other.y; - return *this; - } - - inline Vector2int16& operator*=(const Vector2int16& other) { - x *= other.x; - y *= other.y; - return *this; - } - - Vector2int16 clamp(const Vector2int16& lo, const Vector2int16& hi); - - inline bool operator== (const Vector2int16& rkVector) const { - return ((int32*)this)[0] == ((int32*)&rkVector)[0]; - } - - inline bool operator!= (const Vector2int16& rkVector) const { - return ((int32*)this)[0] != ((int32*)&rkVector)[0]; - } - - Vector2int16 max(const Vector2int16& v) const { - return Vector2int16(iMax(x, v.x), iMax(y, v.y)); - } - - Vector2int16 min(const Vector2int16& v) const { - return Vector2int16(iMin(x, v.x), iMin(y, v.y)); - } - - void serialize(class BinaryOutput& bo) const; - void deserialize(class BinaryInput& bi); -} -G3D_END_PACKED_CLASS(2) - -} - -template<> struct HashTrait { - static size_t hashCode(const G3D::Vector2int16& key) { return static_cast(key.x + ((int)key.y << 16)); } -}; - -#endif diff --git a/externals/g3dlite/G3D/Vector3.h b/externals/g3dlite/G3D/Vector3.h deleted file mode 100644 index 4825efb9985..00000000000 --- a/externals/g3dlite/G3D/Vector3.h +++ /dev/null @@ -1,798 +0,0 @@ -/** - @file Vector3.h - - 3D vector class - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2001-06-02 - @edited 2009-11-01 - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_Vector3_h -#define G3D_Vector3_h - -#include "G3D/platform.h" -#include "G3D/g3dmath.h" -#include "G3D/Random.h" -#include "G3D/Vector2.h" -#include "G3D/Table.h" -#include "G3D/HashTrait.h" -#include "G3D/PositionTrait.h" -#include "G3D/Vector2.h" -#include -#include - -namespace G3D { - -class Vector2; -class Vector4; -class Vector4int8; -class Vector3int32; -class Any; - -/** - Swizzles - Vector classes have swizzle operators, e.g. v.xy(), that - allow selection of arbitrary sub-fields. These cannot be used as write - masks. Examples - -
-Vector3 v(1, 2, 3);
-Vector3 j;
-Vector2 b;
-
-b = v.xz();
-j = b.xx();
-
- - - Warning - - Do not subclass-- this implementation makes assumptions about the - memory layout. - */ -class Vector3 { -public: - - // coordinates - float x, y, z; - -private: - - // Hidden operators - bool operator<(const Vector3&) const; - bool operator>(const Vector3&) const; - bool operator<=(const Vector3&) const; - bool operator>=(const Vector3&) const; - -public: - /** Initializes to zero */ - Vector3(); - - /** \param any Must either Vector3(#, #, #) or Vector3 {x = #, y = #, z = #}*/ - Vector3(const Any& any); - - /** Converts the Vector3 to an Any. */ - operator Any() const; - - /** Divides by 127 */ - Vector3(const Vector4int8&); - Vector3(const class Vector3int32& v); - explicit Vector3(class BinaryInput& b); - Vector3(float _x, float _y, float _z); - explicit Vector3(const class Vector2& v, float _z); - explicit Vector3(float coordinate[3]); - explicit Vector3(double coordinate[3]); - Vector3(const class Vector3int16& v); - explicit Vector3(class TextInput& t); - explicit Vector3(const class Color3& c); - - /** Format is three float32's */ - void serialize(class BinaryOutput& b) const; - void deserialize(class BinaryInput& b); - - /** Format is "(%f, %f, %f)" */ - void serialize(class TextOutput& t) const; - void deserialize(class TextInput& t); - - // access vector V as V[0] = V.x, V[1] = V.y, V[2] = V.z - // - // WARNING. These member functions rely on - // (1) Vector3 not having virtual functions - // (2) the data packed in a 3*sizeof(float) memory block - const float& __fastcall operator[] (int i) const; - float& operator[] (int i); - - enum Axis {X_AXIS=0, Y_AXIS=1, Z_AXIS=2, DETECT_AXIS=-1}; - - /** - Returns the largest dimension. Particularly convenient for determining - which plane to project a triangle onto for point-in-polygon tests. - */ - Axis primaryAxis() const; - - // assignment and comparison - Vector3& __fastcall operator= (const Vector3& rkVector); - bool operator== (const Vector3& rkVector) const; - bool operator!= (const Vector3& rkVector) const; - size_t hashCode() const; - bool fuzzyEq(const Vector3& other) const; - bool fuzzyNe(const Vector3& other) const; - - /** Returns true if this vector has finite length. */ - bool isFinite() const; - - /** Returns true if this vector has length ~= 0 */ - bool isZero() const; - - /** Returns true if this vector has length ~= 1 */ - bool isUnit() const; - - // arithmetic operations - Vector3 __fastcall operator+ (const Vector3& v) const; - Vector3 __fastcall operator- (const Vector3& v) const; - Vector3 __fastcall operator* (float s) const; - inline Vector3 __fastcall operator/ (float s) const { - return *this * (1.0f / s); - } - Vector3 __fastcall operator* (const Vector3& v) const; - Vector3 __fastcall operator/ (const Vector3& v) const; - Vector3 __fastcall operator- () const; - - // arithmetic updates - Vector3& __fastcall operator+= (const Vector3& v); - Vector3& __fastcall operator-= (const Vector3& v); - Vector3& __fastcall operator*= (float s); - inline Vector3& __fastcall operator/= (float s) { - return (*this *= (1.0f / s)); - } - Vector3& __fastcall operator*= (const Vector3& v); - Vector3& __fastcall operator/= (const Vector3& v); - - /** Same as magnitude */ - float length() const; - - float magnitude() const; - - /** - The result is a nan vector if the length is almost zero. - */ - Vector3 direction() const; - - /** - Potentially less accurate but faster than direction(). - Only works if System::hasSSE is true. - */ - Vector3 fastDirection() const; - - /** - Reflect this vector about the (not necessarily unit) normal. - Assumes that both the before and after vectors point away from - the base of the normal. - - Note that if used for a collision or ray reflection you - must negate the resulting vector to get a direction pointing - away from the collision. - -
-       V'    N      V
-                 
-         r   ^   -,
-          \  |  /
-            \|/
-     
- - See also Vector3::reflectionDirection - */ - Vector3 reflectAbout(const Vector3& normal) const; - - /** - See also G3D::Ray::reflect. - The length is 1. -
-       V'    N       V
-                 
-         r   ^    /
-          \  |  /
-            \|'-
-     
- */ - Vector3 reflectionDirection(const Vector3& normal) const; - - - /** - Returns Vector3::zero() if the length is nearly zero, otherwise - returns a unit vector. - */ - inline Vector3 directionOrZero() const { - float mag = magnitude(); - if (G3D::fuzzyEq(mag, 0.0f)) { - return Vector3::zero(); - } else if (G3D::fuzzyEq(mag, 1.0f)) { - return *this; - } else { - return *this * (1.0f / mag); - } - } - - /** - Returns the direction of a refracted ray, - where iExit is the index of refraction for the - previous material and iEnter is the index of refraction - for the new material. Like Vector3::reflectionDirection, - the result has length 1 and is - pointed away from the intersection. - - Returns Vector3::zero() in the case of total internal refraction. - - @param iOutside The index of refraction (eta) outside - (on the positive normal side) of the surface. - - @param iInside The index of refraction (eta) inside - (on the negative normal side) of the surface. - - See also G3D::Ray::refract. -
-              N      V
-                  
-              ^    /
-              |  /
-              |'-
-          __--
-     V'<--
-     
- */ - Vector3 refractionDirection( - const Vector3& normal, - float iInside, - float iOutside) const; - - /** Synonym for direction */ - inline Vector3 unit() const { - return direction(); - } - - /** Returns a normalized vector. May be computed with lower - precision than unit */ - inline Vector3 fastUnit() const { - return fastDirection(); - } - - /** Same as squaredMagnitude */ - float squaredLength() const; - - float squaredMagnitude () const; - - float __fastcall dot(const Vector3& rkVector) const; - - float unitize(float tolerance = 1e-06); - - /** Cross product. Note that two cross products in a row - can be computed more cheaply: v1 x (v2 x v3) = (v1 dot v3) v2 - (v1 dot v2) v3. - */ - Vector3 __fastcall cross(const Vector3& rkVector) const; - Vector3 unitCross(const Vector3& rkVector) const; - - /** - Returns a matrix such that v.cross() * w = v.cross(w). -
-     [ 0  -v.z  v.y ]
-     [ v.z  0  -v.x ]
-     [ -v.y v.x  0  ]
-     
- */ - class Matrix3 cross() const; - - Vector3 __fastcall min(const Vector3 &v) const; - Vector3 __fastcall max(const Vector3 &v) const; - - /** Smallest element */ - inline float min() const { - return G3D::min(G3D::min(x, y), z); - } - - /** Largest element */ - inline float max() const { - return G3D::max(G3D::max(x, y), z); - } - - std::string toString() const; - - inline Vector3 clamp(const Vector3& low, const Vector3& high) const { - return Vector3( - G3D::clamp(x, low.x, high.x), - G3D::clamp(y, low.y, high.y), - G3D::clamp(z, low.z, high.z)); - } - - inline Vector3 clamp(float low, float high) const { - return Vector3( - G3D::clamp(x, low, high), - G3D::clamp(y, low, high), - G3D::clamp(z, low, high)); - } - - /** - Linear interpolation - */ - inline Vector3 lerp(const Vector3& v, float alpha) const { - return (*this) + (v - *this) * alpha; - } - - /** Gram-Schmidt orthonormalization. */ - static void orthonormalize (Vector3 akVector[3]); - - /** \brief Random unit vector, uniformly distributed on the sphere. - - Distribution rendered by G3D::DirectionHistogram: - \image html vector3-random.png - */ - static Vector3 random(Random& r = Random::common()); - - /** \brief Random unit vector, distributed according to \f$\max(\cos \theta,0)\f$. - - That is, so that the probability of \f$\vec{V}\f$ is proportional - to \f$\max(\vec{v} \cdot \vec{n}, 0)\f$. Useful in photon mapping for - Lambertian scattering. - - Distribution rendered by G3D::DirectionHistogram: - \image html vector3-coshemirandom.png - - \param n Unit vector at the center of the distribution. - - @cite Henrik Wann Jensen, Realistic Image Synthesis using Photon Mapping eqn 2.24 - */ - static Vector3 cosHemiRandom(const Vector3& n, Random& r = Random::common()); - - /** \brief Random unit vector, distributed according to \f$\max(\cos^k \theta,0)\f$. - - That is, so that the probability of \f$\vec{V}\f$ is - proportional to \f$\max((\vec{v} \cdot \vec{n})^k, 0)\f$. - Useful in photon mapping for glossy scattering. - - Distribution rendered by G3D::DirectionHistogram: - \image html vector3-cospowhemirandom.png - - \param n Unit vector at the center of the distribution. - - @cite Ashikhmin and Shirley, An anisotropic Phong BRDF model, Journal of Graphics Tools, 2002 - */ - static Vector3 cosPowHemiRandom(const Vector3& n, const float k, Random& r = Random::common()); - - /** - \brief Random vector distributed over the hemisphere about normal. - - Distribution rendered by G3D::DirectionHistogram: - \image html vector3-hemirandom.png - */ - static Vector3 hemiRandom(const Vector3& normal, Random& r = Random::common()); - - /** Input W must be initialize to a nonzero vector, output is {U,V,W} - an orthonormal basis. A hint is provided about whether or not W - is already unit length. - @deprecated Use getTangents - */ - static void generateOrthonormalBasis (Vector3& rkU, Vector3& rkV, - Vector3& rkW, bool bUnitLengthW = true); - - inline float sum() const { - return x + y + z; - } - - inline float average() const { - return sum() / 3.0f; - } - - // Special values. - static const Vector3& zero(); - static const Vector3& one(); - static const Vector3& unitX(); - static const Vector3& unitY(); - static const Vector3& unitZ(); - static const Vector3& inf(); - static const Vector3& nan(); - - /** Smallest (most negative) representable vector */ - static const Vector3& minFinite(); - - /** Largest representable vector */ - static const Vector3& maxFinite(); - - - /** Creates two orthonormal tangent vectors X and Y such that - if Z = this, X x Y = Z.*/ - inline void getTangents(Vector3& X, Vector3& Y) const { - debugAssertM(G3D::fuzzyEq(length(), 1.0f), - "makeAxes requires Z to have unit length"); - - // Choose another vector not perpendicular - X = (abs(x) < 0.9f) ? Vector3::unitX() : Vector3::unitY(); - - // Remove the part that is parallel to Z - X -= *this * this->dot(X); - X /= X.length(); - - Y = this->cross(X); - } - - - // 2-char swizzles - - Vector2 xx() const; - Vector2 yx() const; - Vector2 zx() const; - Vector2 xy() const; - Vector2 yy() const; - Vector2 zy() const; - Vector2 xz() const; - Vector2 yz() const; - Vector2 zz() const; - - // 3-char swizzles - - Vector3 xxx() const; - Vector3 yxx() const; - Vector3 zxx() const; - Vector3 xyx() const; - Vector3 yyx() const; - Vector3 zyx() const; - Vector3 xzx() const; - Vector3 yzx() const; - Vector3 zzx() const; - Vector3 xxy() const; - Vector3 yxy() const; - Vector3 zxy() const; - Vector3 xyy() const; - Vector3 yyy() const; - Vector3 zyy() const; - Vector3 xzy() const; - Vector3 yzy() const; - Vector3 zzy() const; - Vector3 xxz() const; - Vector3 yxz() const; - Vector3 zxz() const; - Vector3 xyz() const; - Vector3 yyz() const; - Vector3 zyz() const; - Vector3 xzz() const; - Vector3 yzz() const; - Vector3 zzz() const; - - // 4-char swizzles - - Vector4 xxxx() const; - Vector4 yxxx() const; - Vector4 zxxx() const; - Vector4 xyxx() const; - Vector4 yyxx() const; - Vector4 zyxx() const; - Vector4 xzxx() const; - Vector4 yzxx() const; - Vector4 zzxx() const; - Vector4 xxyx() const; - Vector4 yxyx() const; - Vector4 zxyx() const; - Vector4 xyyx() const; - Vector4 yyyx() const; - Vector4 zyyx() const; - Vector4 xzyx() const; - Vector4 yzyx() const; - Vector4 zzyx() const; - Vector4 xxzx() const; - Vector4 yxzx() const; - Vector4 zxzx() const; - Vector4 xyzx() const; - Vector4 yyzx() const; - Vector4 zyzx() const; - Vector4 xzzx() const; - Vector4 yzzx() const; - Vector4 zzzx() const; - Vector4 xxxy() const; - Vector4 yxxy() const; - Vector4 zxxy() const; - Vector4 xyxy() const; - Vector4 yyxy() const; - Vector4 zyxy() const; - Vector4 xzxy() const; - Vector4 yzxy() const; - Vector4 zzxy() const; - Vector4 xxyy() const; - Vector4 yxyy() const; - Vector4 zxyy() const; - Vector4 xyyy() const; - Vector4 yyyy() const; - Vector4 zyyy() const; - Vector4 xzyy() const; - Vector4 yzyy() const; - Vector4 zzyy() const; - Vector4 xxzy() const; - Vector4 yxzy() const; - Vector4 zxzy() const; - Vector4 xyzy() const; - Vector4 yyzy() const; - Vector4 zyzy() const; - Vector4 xzzy() const; - Vector4 yzzy() const; - Vector4 zzzy() const; - Vector4 xxxz() const; - Vector4 yxxz() const; - Vector4 zxxz() const; - Vector4 xyxz() const; - Vector4 yyxz() const; - Vector4 zyxz() const; - Vector4 xzxz() const; - Vector4 yzxz() const; - Vector4 zzxz() const; - Vector4 xxyz() const; - Vector4 yxyz() const; - Vector4 zxyz() const; - Vector4 xyyz() const; - Vector4 yyyz() const; - Vector4 zyyz() const; - Vector4 xzyz() const; - Vector4 yzyz() const; - Vector4 zzyz() const; - Vector4 xxzz() const; - Vector4 yxzz() const; - Vector4 zxzz() const; - Vector4 xyzz() const; - Vector4 yyzz() const; - Vector4 zyzz() const; - Vector4 xzzz() const; - Vector4 yzzz() const; - Vector4 zzzz() const; - - /** Can be passed to ignore a vector3 parameter */ - static Vector3& ignore(); -}; - -inline G3D::Vector3 operator*(float s, const G3D::Vector3& v) { - return v * s; -} - -inline G3D::Vector3 operator*(double s, const G3D::Vector3& v) { - return v * (float)s; -} - -inline G3D::Vector3 operator*(int s, const G3D::Vector3& v) { - return v * (float)s; -} - -std::ostream& operator<<(std::ostream& os, const Vector3&); - - -void serialize(const Vector3::Axis& a, class BinaryOutput& bo); -void deserialize(Vector3::Axis& a, class BinaryInput& bo); - - -//---------------------------------------------------------------------------- -inline Vector3::Vector3() : x(0.0f), y(0.0f), z(0.0f) { -} - -//---------------------------------------------------------------------------- - -inline Vector3::Vector3 (float fX, float fY, float fZ) : x(fX), y(fY), z(fZ) { -} - -//---------------------------------------------------------------------------- -inline Vector3::Vector3 (float V[3]) : x(V[0]), y(V[1]), z(V[2]){ -} - -//---------------------------------------------------------------------------- -inline Vector3::Vector3 (double V[3]) : x((float)V[0]), y((float)V[1]), z((float)V[2]){ -} - -//---------------------------------------------------------------------------- -inline const float& Vector3::operator[] (int i) const { - return ((float*)this)[i]; -} - -inline float& Vector3::operator[] (int i) { - return ((float*)this)[i]; -} - - -//---------------------------------------------------------------------------- -inline Vector3& Vector3::operator= (const Vector3& rkVector) { - x = rkVector.x; - y = rkVector.y; - z = rkVector.z; - return *this; -} - -//---------------------------------------------------------------------------- - -inline bool Vector3::fuzzyEq(const Vector3& other) const { - return G3D::fuzzyEq((*this - other).squaredMagnitude(), 0); -} - -//---------------------------------------------------------------------------- - -inline bool Vector3::fuzzyNe(const Vector3& other) const { - return G3D::fuzzyNe((*this - other).squaredMagnitude(), 0); -} - -//---------------------------------------------------------------------------- - -inline bool Vector3::isFinite() const { - return G3D::isFinite(x) && G3D::isFinite(y) && G3D::isFinite(z); -} - -//---------------------------------------------------------------------------- -inline bool Vector3::operator== (const Vector3& rkVector) const { - return ( x == rkVector.x && y == rkVector.y && z == rkVector.z ); -} - -//---------------------------------------------------------------------------- -inline bool Vector3::operator!= (const Vector3& rkVector) const { - return ( x != rkVector.x || y != rkVector.y || z != rkVector.z ); -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::operator+ (const Vector3& rkVector) const { - return Vector3(x + rkVector.x, y + rkVector.y, z + rkVector.z); -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::operator- (const Vector3& rkVector) const { - return Vector3(x - rkVector.x, y - rkVector.y, z - rkVector.z); -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::operator* (const Vector3& rkVector) const { - return Vector3(x * rkVector.x, y * rkVector.y, z * rkVector.z); -} - -inline Vector3 Vector3::operator*(float f) const { - return Vector3(x * f, y * f, z * f); -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::operator/ (const Vector3& rkVector) const { - return Vector3(x / rkVector.x, y / rkVector.y, z / rkVector.z); -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::operator- () const { - return Vector3(-x, -y, -z); -} - -//---------------------------------------------------------------------------- -inline Vector3& Vector3::operator+= (const Vector3& rkVector) { - x += rkVector.x; - y += rkVector.y; - z += rkVector.z; - return *this; -} - -//---------------------------------------------------------------------------- -inline Vector3& Vector3::operator-= (const Vector3& rkVector) { - x -= rkVector.x; - y -= rkVector.y; - z -= rkVector.z; - return *this; -} - -//---------------------------------------------------------------------------- -inline Vector3& Vector3::operator*= (float fScalar) { - x *= fScalar; - y *= fScalar; - z *= fScalar; - return *this; -} - -//---------------------------------------------------------------------------- -inline Vector3& Vector3::operator*= (const Vector3& rkVector) { - x *= rkVector.x; - y *= rkVector.y; - z *= rkVector.z; - return *this; -} - -//---------------------------------------------------------------------------- -inline Vector3& Vector3::operator/= (const Vector3& rkVector) { - x /= rkVector.x; - y /= rkVector.y; - z /= rkVector.z; - return *this; -} - -//---------------------------------------------------------------------------- -inline float Vector3::squaredMagnitude () const { - return x*x + y*y + z*z; -} - -//---------------------------------------------------------------------------- -inline float Vector3::squaredLength () const { - return squaredMagnitude(); -} - -//---------------------------------------------------------------------------- -inline float Vector3::magnitude() const { - return ::sqrtf(x*x + y*y + z*z); -} - -//---------------------------------------------------------------------------- -inline float Vector3::length() const { - return magnitude(); -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::direction () const { - const float lenSquared = squaredMagnitude(); - const float invSqrt = 1.0f / sqrtf(lenSquared); - return Vector3(x * invSqrt, y * invSqrt, z * invSqrt); -} - -//---------------------------------------------------------------------------- - -inline Vector3 Vector3::fastDirection () const { - float lenSquared = x * x + y * y + z * z; - float invSqrt = rsq(lenSquared); - return Vector3(x * invSqrt, y * invSqrt, z * invSqrt); -} - -//---------------------------------------------------------------------------- -inline float Vector3::dot (const Vector3& rkVector) const { - return x*rkVector.x + y*rkVector.y + z*rkVector.z; -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::cross (const Vector3& rkVector) const { - return Vector3(y*rkVector.z - z*rkVector.y, z*rkVector.x - x*rkVector.z, - x*rkVector.y - y*rkVector.x); -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::unitCross (const Vector3& rkVector) const { - Vector3 kCross(y*rkVector.z - z*rkVector.y, z*rkVector.x - x*rkVector.z, - x*rkVector.y - y*rkVector.x); - kCross.unitize(); - return kCross; -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::min(const Vector3 &v) const { - return Vector3(G3D::min(v.x, x), G3D::min(v.y, y), G3D::min(v.z, z)); -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::max(const Vector3 &v) const { - return Vector3(G3D::max(v.x, x), G3D::max(v.y, y), G3D::max(v.z, z)); -} - -//---------------------------------------------------------------------------- -inline bool Vector3::isZero() const { - return G3D::fuzzyEq(squaredMagnitude(), 0.0f); -} - -//---------------------------------------------------------------------------- - -inline bool Vector3::isUnit() const { - return G3D::fuzzyEq(squaredMagnitude(), 1.0f); -} - -} // namespace G3D - - -template <> -struct HashTrait { - static size_t hashCode(const G3D::Vector3& key) { - return key.hashCode(); - } -}; - - -template<> struct PositionTrait { - static void getPosition(const G3D::Vector2& v, G3D::Vector3& p) { p = G3D::Vector3(v, 0); } -}; - -template<> struct PositionTrait { - static void getPosition(const G3D::Vector3& v, G3D::Vector3& p) { p = v; } -}; - - -#endif diff --git a/externals/g3dlite/G3D/Vector3.inl b/externals/g3dlite/G3D/Vector3.inl deleted file mode 100644 index 9211c2a70fd..00000000000 --- a/externals/g3dlite/G3D/Vector3.inl +++ /dev/null @@ -1,249 +0,0 @@ -/** - @file Vector3.inl - - @maintainer Morgan McGuire, matrix@graphics3d.com - - @cite Portions based on Dave Eberly's Magic Software Library at http://www.magic-software.com - - @created 2001-06-02 - @edited 2004-05-21 - Copyright 2000-2004, Morgan McGuire. - All rights reserved. - */ - -//---------------------------------------------------------------------------- -#ifdef SSE - // If you receive an error on this line, it is because you do not have the file - // xmmintrin.h needed for MMX & SSE extensions. Download and install - // - // http://download.microsoft.com/download/vstudio60ent/SP5/Wideband-Full/WIN98Me/EN-US/vs6sp5.exe - // and - // http://download.microsoft.com/download/vb60ent/Update/6/W9X2KXP/EN-US/vcpp5.exe - // - // to get this file. -# include -#endif - -inline unsigned int hashCode(const G3D::Vector3& v) { - return v.hashCode(); -} - -namespace G3D { - -//---------------------------------------------------------------------------- -inline Vector3::Vector3() : x(0.0f), y(0.0f), z(0.0f) { -} - -//---------------------------------------------------------------------------- - -inline Vector3::Vector3 (float fX, float fY, float fZ) : x(fX), y(fY), z(fZ) { -} - -//---------------------------------------------------------------------------- -inline Vector3::Vector3 (float V[3]) : x(V[0]), y(V[1]), z(V[2]){ -} -//---------------------------------------------------------------------------- -inline Vector3::Vector3 (double V[3]) : x((float)V[0]), y((float)V[1]), z((float)V[2]){ -} - -//---------------------------------------------------------------------------- -inline Vector3::Vector3 (const Vector3& V) : x(V.x), y(V.y), z(V.z) { -} - -//---------------------------------------------------------------------------- - -//inline Vector3::Vector3 (const __m128& m) { - // Cast from SSE packed floats -// *this = *(Vector3*)&m; -//} - -//---------------------------------------------------------------------------- -inline const float& Vector3::operator[] (int i) const { - return ((float*)this)[i]; -} - -inline float& Vector3::operator[] (int i) { - return ((float*)this)[i]; -} - -//---------------------------------------------------------------------------- -inline Vector3& Vector3::operator= (const Vector3& rkVector) { - x = rkVector.x; - y = rkVector.y; - z = rkVector.z; - return *this; -} - -//---------------------------------------------------------------------------- - -inline bool Vector3::fuzzyEq(const Vector3& other) const { - return G3D::fuzzyEq((*this - other).squaredMagnitude(), 0); -} - -//---------------------------------------------------------------------------- - -inline bool Vector3::fuzzyNe(const Vector3& other) const { - return G3D::fuzzyNe((*this - other).squaredMagnitude(), 0); -} - -//---------------------------------------------------------------------------- - -inline bool Vector3::isFinite() const { - return G3D::isFinite(x) && G3D::isFinite(y) && G3D::isFinite(z); -} - -//---------------------------------------------------------------------------- -inline bool Vector3::operator== (const Vector3& rkVector) const { - return ( x == rkVector.x && y == rkVector.y && z == rkVector.z ); -} - -//---------------------------------------------------------------------------- -inline bool Vector3::operator!= (const Vector3& rkVector) const { - return ( x != rkVector.x || y != rkVector.y || z != rkVector.z ); -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::operator+ (const Vector3& rkVector) const { - return Vector3(x + rkVector.x, y + rkVector.y, z + rkVector.z); -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::operator- (const Vector3& rkVector) const { - return Vector3(x - rkVector.x, y - rkVector.y, z - rkVector.z); -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::operator* (const Vector3& rkVector) const { - return Vector3(x * rkVector.x, y * rkVector.y, z * rkVector.z); -} - -inline Vector3 Vector3::operator*(float f) const { - return Vector3(x * f, y * f, z * f); -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::operator/ (const Vector3& rkVector) const { - return Vector3(x / rkVector.x, y / rkVector.y, z / rkVector.z); -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::operator- () const { - return Vector3(-x, -y, -z); -} - -//---------------------------------------------------------------------------- -inline Vector3& Vector3::operator+= (const Vector3& rkVector) { - x += rkVector.x; - y += rkVector.y; - z += rkVector.z; - return *this; -} - -//---------------------------------------------------------------------------- -inline Vector3& Vector3::operator-= (const Vector3& rkVector) { - x -= rkVector.x; - y -= rkVector.y; - z -= rkVector.z; - return *this; -} - -//---------------------------------------------------------------------------- -inline Vector3& Vector3::operator*= (float fScalar) { - x *= fScalar; - y *= fScalar; - z *= fScalar; - return *this; -} - -//---------------------------------------------------------------------------- -inline Vector3& Vector3::operator*= (const Vector3& rkVector) { - x *= rkVector.x; - y *= rkVector.y; - z *= rkVector.z; - return *this; -} - -//---------------------------------------------------------------------------- -inline Vector3& Vector3::operator/= (const Vector3& rkVector) { - x /= rkVector.x; - y /= rkVector.y; - z /= rkVector.z; - return *this; -} - -//---------------------------------------------------------------------------- -inline float Vector3::squaredMagnitude () const { - return x*x + y*y + z*z; -} - -//---------------------------------------------------------------------------- -inline float Vector3::squaredLength () const { - return squaredMagnitude(); -} - -//---------------------------------------------------------------------------- -inline float Vector3::magnitude() const { - return sqrtf(x*x + y*y + z*z); -} - -//---------------------------------------------------------------------------- -inline float Vector3::length() const { - return magnitude(); -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::direction () const { - float lenSquared = squaredMagnitude(); - float invSqrt = 1.0f / sqrtf(lenSquared); - return Vector3(x * invSqrt, y * invSqrt, z * invSqrt); -} - -//---------------------------------------------------------------------------- - -inline Vector3 Vector3::fastDirection () const { - float lenSquared = x * x + y * y + z * z; - float invSqrt = rsq(lenSquared); - return Vector3(x * invSqrt, y * invSqrt, z * invSqrt); -} - -//---------------------------------------------------------------------------- -inline float Vector3::dot (const Vector3& rkVector) const { - return x*rkVector.x + y*rkVector.y + z*rkVector.z; -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::cross (const Vector3& rkVector) const { - return Vector3(y*rkVector.z - z*rkVector.y, z*rkVector.x - x*rkVector.z, - x*rkVector.y - y*rkVector.x); -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::unitCross (const Vector3& rkVector) const { - Vector3 kCross(y*rkVector.z - z*rkVector.y, z*rkVector.x - x*rkVector.z, - x*rkVector.y - y*rkVector.x); - kCross.unitize(); - return kCross; -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::min(const Vector3 &v) const { - return Vector3(G3D::min(v.x, x), G3D::min(v.y, y), G3D::min(v.z, z)); -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::max(const Vector3 &v) const { - return Vector3(G3D::max(v.x, x), G3D::max(v.y, y), G3D::max(v.z, z)); -} - -//---------------------------------------------------------------------------- -inline bool Vector3::isZero() const { - return G3D::fuzzyEq(squaredMagnitude(), 0.0f); -} - -//---------------------------------------------------------------------------- - -inline bool Vector3::isUnit() const { - return G3D::fuzzyEq(squaredMagnitude(), 1.0f); -} - -} // namespace diff --git a/externals/g3dlite/G3D/Vector3int16.h b/externals/g3dlite/G3D/Vector3int16.h deleted file mode 100644 index 3197ea49d1a..00000000000 --- a/externals/g3dlite/G3D/Vector3int16.h +++ /dev/null @@ -1,127 +0,0 @@ -/** - @file Vector3int16.h - - @maintainer Morgan McGuire, matrix@brown.edu - - @created 2003-04-07 - @edited 2003-06-24 - Copyright 2000-2004, Morgan McGuire. - All rights reserved. - */ - -#ifndef VECTOR3INT16_H -#define VECTOR3INT16_H - -#include "G3D/platform.h" -#include "G3D/g3dmath.h" -#include "G3D/HashTrait.h" - -#ifdef _MSC_VER -// Turn off "conditional expression is constant" warning; MSVC generates this -// for debug assertions in inlined methods. -#pragma warning (disable : 4127) -#endif - - -namespace G3D { - -/** - \class Vector3int16 - A Vector3 that packs its fields into uint16s. - */ -G3D_BEGIN_PACKED_CLASS(2) -class Vector3int16 { -private: - // Hidden operators - bool operator<(const Vector3int16&) const; - bool operator>(const Vector3int16&) const; - bool operator<=(const Vector3int16&) const; - bool operator>=(const Vector3int16&) const; - -public: - G3D::int16 x; - G3D::int16 y; - G3D::int16 z; - - Vector3int16() : x(0), y(0), z(0) {} - Vector3int16(G3D::int16 _x, G3D::int16 _y, G3D::int16 _z) : x(_x), y(_y), z(_z) {} - Vector3int16(const class Vector3& v); - Vector3int16(class BinaryInput& bi); - - void serialize(class BinaryOutput& bo) const; - void deserialize(class BinaryInput& bi); - - inline G3D::int16& operator[] (int i) { - debugAssert(i <= 2); - return ((G3D::int16*)this)[i]; - } - - inline const G3D::int16& operator[] (int i) const { - debugAssert(i <= 2); - return ((G3D::int16*)this)[i]; - } - - inline Vector3int16 operator+(const Vector3int16& other) const { - return Vector3int16(x + other.x, y + other.y, z + other.z); - } - - inline Vector3int16 operator-(const Vector3int16& other) const { - return Vector3int16(x - other.x, y - other.y, z - other.z); - } - - inline Vector3int16 operator*(const Vector3int16& other) const { - return Vector3int16(x * other.x, y * other.y, z * other.z); - } - - inline Vector3int16 operator*(const int s) const { - return Vector3int16(int16(x * s), int16(y * s), int16(z * s)); - } - - inline Vector3int16& operator+=(const Vector3int16& other) { - x += other.x; - y += other.y; - z += other.y; - return *this; - } - - inline Vector3int16& operator-=(const Vector3int16& other) { - x -= other.x; - y -= other.y; - z -= other.z; - return *this; - } - - inline Vector3int16& operator*=(const Vector3int16& other) { - x *= other.x; - y *= other.y; - z *= other.z; - return *this; - } - - inline bool operator== (const Vector3int16& rkVector) const { - return ( x == rkVector.x && y == rkVector.y && z == rkVector.z ); - } - - inline bool operator!= (const Vector3int16& rkVector) const { - return ( x != rkVector.x || y != rkVector.y || z != rkVector.z ); - } - - Vector3int16 max(const Vector3int16& v) const { - return Vector3int16(std::max(x, v.x), std::max(y, v.y), std::max(z, v.z)); - } - - Vector3int16 min(const Vector3int16& v) const { - return Vector3int16(std::min(x, v.x), std::min(y, v.y), std::min(z, v.z)); - } - - std::string toString() const; -} -G3D_END_PACKED_CLASS(2) - -} - -template <> struct HashTrait { - static size_t hashCode(const G3D::Vector3int16& key) { return static_cast(key.x + ((int)key.y << 5) + ((int)key.z << 10)); } -}; - -#endif diff --git a/externals/g3dlite/G3D/Vector3int32.h b/externals/g3dlite/G3D/Vector3int32.h deleted file mode 100644 index 2f256ea0300..00000000000 --- a/externals/g3dlite/G3D/Vector3int32.h +++ /dev/null @@ -1,128 +0,0 @@ -/** - @file Vector3int32.h - - @maintainer Morgan McGuire, matrix@brown.edu - - @created 2008-07-01 - @edited 2008-07-01 - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ - -#ifndef VECTOR3INT32_H -#define VECTOR3INT32_H - -#include "G3D/platform.h" -#include "G3D/g3dmath.h" -#include "G3D/HashTrait.h" - -namespace G3D { - -/** - \ Vector3int32 - A Vector3 that packs its fields into uint32s. - */ -G3D_BEGIN_PACKED_CLASS(4) -class Vector3int32 { -private: - // Hidden operators - bool operator<(const Vector3int32&) const; - bool operator>(const Vector3int32&) const; - bool operator<=(const Vector3int32&) const; - bool operator>=(const Vector3int32&) const; - -public: - G3D::int32 x; - G3D::int32 y; - G3D::int32 z; - - Vector3int32() : x(0), y(0), z(0) {} - Vector3int32(int _x, int _y, int _z) : x(_x), y(_y), z(_z) {} - Vector3int32(const class Vector3int16& v); - Vector3int32(const class Vector3& v); - Vector3int32(class BinaryInput& bi); - - void serialize(class BinaryOutput& bo) const; - void deserialize(class BinaryInput& bi); - - inline G3D::int32& operator[] (int i) { - debugAssert(i <= 2); - return ((G3D::int32*)this)[i]; - } - - inline const G3D::int32& operator[] (int i) const { - debugAssert(i <= 2); - return ((G3D::int32*)this)[i]; - } - - inline Vector3int32 operator+(const Vector3int32& other) const { - return Vector3int32(x + other.x, y + other.y, z + other.z); - } - - inline Vector3int32 operator-(const Vector3int32& other) const { - return Vector3int32(x - other.x, y - other.y, z - other.z); - } - - inline Vector3int32 operator*(const Vector3int32& other) const { - return Vector3int32(x * other.x, y * other.y, z * other.z); - } - - inline Vector3int32 operator*(const int s) const { - return Vector3int32(x * s, y * s, z * s); - } - - inline Vector3int32& operator+=(const Vector3int32& other) { - x += other.x; - y += other.y; - z += other.y; - return *this; - } - - inline Vector3int32& operator-=(const Vector3int32& other) { - x -= other.x; - y -= other.y; - z -= other.z; - return *this; - } - - inline Vector3int32& operator*=(const Vector3int32& other) { - x *= other.x; - y *= other.y; - z *= other.z; - return *this; - } - - inline bool operator== (const Vector3int32& rkVector) const { - return ( x == rkVector.x && y == rkVector.y && z == rkVector.z ); - } - - inline bool operator!= (const Vector3int32& rkVector) const { - return ( x != rkVector.x || y != rkVector.y || z != rkVector.z ); - } - - Vector3int32 max(const Vector3int32& v) const { - return Vector3int32(iMax(x, v.x), iMax(y, v.y), iMax(z, v.z)); - } - - Vector3int32 min(const Vector3int32& v) const { - return Vector3int32(iMin(x, v.x), iMin(y, v.y), iMin(z, v.z)); - } - - std::string toString() const; -} -G3D_END_PACKED_CLASS(4) - -} - -template <> struct HashTrait { - static size_t hashCode(const G3D::Vector3int32& key) { - // Mask for the top bit of a uint32 - const G3D::uint32 top = (1UL << 31); - // Mask for the bottom 10 bits of a uint32 - const G3D::uint32 bot = 0x000003FF; - return static_cast(((key.x & top) | ((key.y & top) >> 1) | ((key.z & top) >> 2)) | - (((key.x & bot) << 19) ^ ((key.y & bot) << 10) ^ (key.z & bot))); - } -}; - -#endif diff --git a/externals/g3dlite/G3D/Vector4.h b/externals/g3dlite/G3D/Vector4.h deleted file mode 100644 index 5e511451f86..00000000000 --- a/externals/g3dlite/G3D/Vector4.h +++ /dev/null @@ -1,716 +0,0 @@ -/** - @file Vector4.h - - Homogeneous vector class. - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2002-07-09 - @edited 2008-11-01 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_Vector4_h -#define G3D_Vector4_h - -#include "G3D/platform.h" -#include "G3D/g3dmath.h" -#include "G3D/Vector3.h" -#include "G3D/Vector2.h" -#include "G3D/Table.h" -#include "G3D/HashTrait.h" -#include "G3D/PositionTrait.h" -#include - -namespace G3D { - -class Vector2; -class Vector3; -class Vector4; -class Vector4int8; -class Any; - -/** - Do not subclass-- this implementation makes assumptions about the - memory layout. - */ -class Vector4 { -private: - // Hidden operators - bool operator<(const Vector4&) const; - bool operator>(const Vector4&) const; - bool operator<=(const Vector4&) const; - bool operator>=(const Vector4&) const; - -public: - - /** \param any Must either Vector4(#, #, #, #) or Vector3 {x = #, y = #, z = #, w =#}*/ - Vector4(const Any& any); - - /** Converts the Vector4 to an Any. */ - operator Any() const; - - // construction - Vector4(); - Vector4(float fX, float fY, float fZ, float fW); - Vector4(float afCoordinate[4]); - Vector4(const Vector4& rkVector); - Vector4(const class Color4& c); - Vector4(const Vector3& rkVector, float fW); - Vector4(const Vector2& v1, const Vector2& v2); - Vector4(const Vector2& v1, float fz, float fw); - - /** Divides by 127 when converting */ - Vector4(const Vector4int8&); - - Vector4(class BinaryInput& b); - void serialize(class BinaryOutput& b) const; - void deserialize(class BinaryInput& b); - - // coordinates - float x, y, z, w; - - // access vector V as V[0] = V.x, V[1] = V.y, V[2] = V.z, etc. - // - // WARNING. These member functions rely on - // (1) Vector4 not having virtual functions - // (2) the data packed in a 4*sizeof(float) memory block - float& operator[] (int i); - const float& operator[] (int i) const; - - // assignment and comparison - Vector4& operator= (const Vector4& rkVector); - bool operator== (const Vector4& rkVector) const; - bool operator!= (const Vector4& rkVector) const; - - static const Vector4& zero(); - - inline void set(float _x, float _y, float _z, float _w) { - x = _x; - y = _y; - z = _z; - w = _w; - } - - inline void set(const Vector3& v, float _w) { - x = v.x; - y = v.y; - z = v.z; - w = _w; - } - - inline void set(const Vector2& v, float _z, float _w) { - x = v.x; - y = v.y; - z = _z; - w = _w; - } - - size_t hashCode() const; - bool fuzzyEq(const Vector4& other) const; - bool fuzzyNe(const Vector4& other) const; - - static const Vector4& inf(); - static const Vector4& nan(); - - /** sqrt(this->dot(*this)) */ - float length() const; - float squaredLength() const; - - inline float sum() const { - return x + y + z + w; - } - - /** Returns true if this vector has finite length */ - bool isFinite() const; - - /** Returns true if this vector has length == 0 */ - bool isZero() const; - - /** Returns true if this vector has length == 1 */ - bool isUnit() const; - - // arithmetic operations - Vector4 operator+ (const Vector4& rkVector) const; - Vector4 operator- (const Vector4& rkVector) const; - - inline Vector4 operator*(const Vector4& rkVector) const { - return Vector4(x * rkVector.x, y * rkVector.y, z * rkVector.z, w * rkVector.w); - } - - inline Vector4 operator/(const Vector4& rkVector) const { - return Vector4(x / rkVector.x, y / rkVector.y, z / rkVector.z, w / rkVector.w); - } - - Vector4 operator*(const class Matrix4& M) const; - - Vector4 operator* (float fScalar) const; - Vector4 operator/ (float fScalar) const; - Vector4 operator- () const; - friend Vector4 operator* (float, const Vector4& rkVector); - - // arithmetic updates - Vector4& operator+= (const Vector4& rkVector); - Vector4& operator-= (const Vector4& rkVector); - Vector4& operator*= (float fScalar); - Vector4& operator/= (float fScalar); - - inline Vector4 clamp(const Vector4& low, const Vector4& high) const { - return Vector4( - G3D::clamp(x, low.x, high.x), - G3D::clamp(y, low.y, high.y), - G3D::clamp(z, low.z, high.z), - G3D::clamp(w, low.w, high.w)); - } - - inline Vector4 clamp(float low, float high) const { - return Vector4( - G3D::clamp(x, low, high), - G3D::clamp(y, low, high), - G3D::clamp(z, low, high), - G3D::clamp(w, low, high)); - } - - float dot (const Vector4& rkVector) const; - - Vector4 min(const Vector4& v) const; - Vector4 max(const Vector4& v) const; - - std::string toString() const; - - /** - Linear interpolation - */ - Vector4 lerp(const Vector4& v, float alpha) const; - - // 2-char swizzles - - Vector2 xx() const; - Vector2 yx() const; - Vector2 zx() const; - Vector2 wx() const; - Vector2 xy() const; - Vector2 yy() const; - Vector2 zy() const; - Vector2 wy() const; - Vector2 xz() const; - Vector2 yz() const; - Vector2 zz() const; - Vector2 wz() const; - Vector2 xw() const; - Vector2 yw() const; - Vector2 zw() const; - Vector2 ww() const; - - // 3-char swizzles - - Vector3 xxx() const; - Vector3 yxx() const; - Vector3 zxx() const; - Vector3 wxx() const; - Vector3 xyx() const; - Vector3 yyx() const; - Vector3 zyx() const; - Vector3 wyx() const; - Vector3 xzx() const; - Vector3 yzx() const; - Vector3 zzx() const; - Vector3 wzx() const; - Vector3 xwx() const; - Vector3 ywx() const; - Vector3 zwx() const; - Vector3 wwx() const; - Vector3 xxy() const; - Vector3 yxy() const; - Vector3 zxy() const; - Vector3 wxy() const; - Vector3 xyy() const; - Vector3 yyy() const; - Vector3 zyy() const; - Vector3 wyy() const; - Vector3 xzy() const; - Vector3 yzy() const; - Vector3 zzy() const; - Vector3 wzy() const; - Vector3 xwy() const; - Vector3 ywy() const; - Vector3 zwy() const; - Vector3 wwy() const; - Vector3 xxz() const; - Vector3 yxz() const; - Vector3 zxz() const; - Vector3 wxz() const; - Vector3 xyz() const; - Vector3 yyz() const; - Vector3 zyz() const; - Vector3 wyz() const; - Vector3 xzz() const; - Vector3 yzz() const; - Vector3 zzz() const; - Vector3 wzz() const; - Vector3 xwz() const; - Vector3 ywz() const; - Vector3 zwz() const; - Vector3 wwz() const; - Vector3 xxw() const; - Vector3 yxw() const; - Vector3 zxw() const; - Vector3 wxw() const; - Vector3 xyw() const; - Vector3 yyw() const; - Vector3 zyw() const; - Vector3 wyw() const; - Vector3 xzw() const; - Vector3 yzw() const; - Vector3 zzw() const; - Vector3 wzw() const; - Vector3 xww() const; - Vector3 yww() const; - Vector3 zww() const; - Vector3 www() const; - - // 4-char swizzles - - Vector4 xxxx() const; - Vector4 yxxx() const; - Vector4 zxxx() const; - Vector4 wxxx() const; - Vector4 xyxx() const; - Vector4 yyxx() const; - Vector4 zyxx() const; - Vector4 wyxx() const; - Vector4 xzxx() const; - Vector4 yzxx() const; - Vector4 zzxx() const; - Vector4 wzxx() const; - Vector4 xwxx() const; - Vector4 ywxx() const; - Vector4 zwxx() const; - Vector4 wwxx() const; - Vector4 xxyx() const; - Vector4 yxyx() const; - Vector4 zxyx() const; - Vector4 wxyx() const; - Vector4 xyyx() const; - Vector4 yyyx() const; - Vector4 zyyx() const; - Vector4 wyyx() const; - Vector4 xzyx() const; - Vector4 yzyx() const; - Vector4 zzyx() const; - Vector4 wzyx() const; - Vector4 xwyx() const; - Vector4 ywyx() const; - Vector4 zwyx() const; - Vector4 wwyx() const; - Vector4 xxzx() const; - Vector4 yxzx() const; - Vector4 zxzx() const; - Vector4 wxzx() const; - Vector4 xyzx() const; - Vector4 yyzx() const; - Vector4 zyzx() const; - Vector4 wyzx() const; - Vector4 xzzx() const; - Vector4 yzzx() const; - Vector4 zzzx() const; - Vector4 wzzx() const; - Vector4 xwzx() const; - Vector4 ywzx() const; - Vector4 zwzx() const; - Vector4 wwzx() const; - Vector4 xxwx() const; - Vector4 yxwx() const; - Vector4 zxwx() const; - Vector4 wxwx() const; - Vector4 xywx() const; - Vector4 yywx() const; - Vector4 zywx() const; - Vector4 wywx() const; - Vector4 xzwx() const; - Vector4 yzwx() const; - Vector4 zzwx() const; - Vector4 wzwx() const; - Vector4 xwwx() const; - Vector4 ywwx() const; - Vector4 zwwx() const; - Vector4 wwwx() const; - Vector4 xxxy() const; - Vector4 yxxy() const; - Vector4 zxxy() const; - Vector4 wxxy() const; - Vector4 xyxy() const; - Vector4 yyxy() const; - Vector4 zyxy() const; - Vector4 wyxy() const; - Vector4 xzxy() const; - Vector4 yzxy() const; - Vector4 zzxy() const; - Vector4 wzxy() const; - Vector4 xwxy() const; - Vector4 ywxy() const; - Vector4 zwxy() const; - Vector4 wwxy() const; - Vector4 xxyy() const; - Vector4 yxyy() const; - Vector4 zxyy() const; - Vector4 wxyy() const; - Vector4 xyyy() const; - Vector4 yyyy() const; - Vector4 zyyy() const; - Vector4 wyyy() const; - Vector4 xzyy() const; - Vector4 yzyy() const; - Vector4 zzyy() const; - Vector4 wzyy() const; - Vector4 xwyy() const; - Vector4 ywyy() const; - Vector4 zwyy() const; - Vector4 wwyy() const; - Vector4 xxzy() const; - Vector4 yxzy() const; - Vector4 zxzy() const; - Vector4 wxzy() const; - Vector4 xyzy() const; - Vector4 yyzy() const; - Vector4 zyzy() const; - Vector4 wyzy() const; - Vector4 xzzy() const; - Vector4 yzzy() const; - Vector4 zzzy() const; - Vector4 wzzy() const; - Vector4 xwzy() const; - Vector4 ywzy() const; - Vector4 zwzy() const; - Vector4 wwzy() const; - Vector4 xxwy() const; - Vector4 yxwy() const; - Vector4 zxwy() const; - Vector4 wxwy() const; - Vector4 xywy() const; - Vector4 yywy() const; - Vector4 zywy() const; - Vector4 wywy() const; - Vector4 xzwy() const; - Vector4 yzwy() const; - Vector4 zzwy() const; - Vector4 wzwy() const; - Vector4 xwwy() const; - Vector4 ywwy() const; - Vector4 zwwy() const; - Vector4 wwwy() const; - Vector4 xxxz() const; - Vector4 yxxz() const; - Vector4 zxxz() const; - Vector4 wxxz() const; - Vector4 xyxz() const; - Vector4 yyxz() const; - Vector4 zyxz() const; - Vector4 wyxz() const; - Vector4 xzxz() const; - Vector4 yzxz() const; - Vector4 zzxz() const; - Vector4 wzxz() const; - Vector4 xwxz() const; - Vector4 ywxz() const; - Vector4 zwxz() const; - Vector4 wwxz() const; - Vector4 xxyz() const; - Vector4 yxyz() const; - Vector4 zxyz() const; - Vector4 wxyz() const; - Vector4 xyyz() const; - Vector4 yyyz() const; - Vector4 zyyz() const; - Vector4 wyyz() const; - Vector4 xzyz() const; - Vector4 yzyz() const; - Vector4 zzyz() const; - Vector4 wzyz() const; - Vector4 xwyz() const; - Vector4 ywyz() const; - Vector4 zwyz() const; - Vector4 wwyz() const; - Vector4 xxzz() const; - Vector4 yxzz() const; - Vector4 zxzz() const; - Vector4 wxzz() const; - Vector4 xyzz() const; - Vector4 yyzz() const; - Vector4 zyzz() const; - Vector4 wyzz() const; - Vector4 xzzz() const; - Vector4 yzzz() const; - Vector4 zzzz() const; - Vector4 wzzz() const; - Vector4 xwzz() const; - Vector4 ywzz() const; - Vector4 zwzz() const; - Vector4 wwzz() const; - Vector4 xxwz() const; - Vector4 yxwz() const; - Vector4 zxwz() const; - Vector4 wxwz() const; - Vector4 xywz() const; - Vector4 yywz() const; - Vector4 zywz() const; - Vector4 wywz() const; - Vector4 xzwz() const; - Vector4 yzwz() const; - Vector4 zzwz() const; - Vector4 wzwz() const; - Vector4 xwwz() const; - Vector4 ywwz() const; - Vector4 zwwz() const; - Vector4 wwwz() const; - Vector4 xxxw() const; - Vector4 yxxw() const; - Vector4 zxxw() const; - Vector4 wxxw() const; - Vector4 xyxw() const; - Vector4 yyxw() const; - Vector4 zyxw() const; - Vector4 wyxw() const; - Vector4 xzxw() const; - Vector4 yzxw() const; - Vector4 zzxw() const; - Vector4 wzxw() const; - Vector4 xwxw() const; - Vector4 ywxw() const; - Vector4 zwxw() const; - Vector4 wwxw() const; - Vector4 xxyw() const; - Vector4 yxyw() const; - Vector4 zxyw() const; - Vector4 wxyw() const; - Vector4 xyyw() const; - Vector4 yyyw() const; - Vector4 zyyw() const; - Vector4 wyyw() const; - Vector4 xzyw() const; - Vector4 yzyw() const; - Vector4 zzyw() const; - Vector4 wzyw() const; - Vector4 xwyw() const; - Vector4 ywyw() const; - Vector4 zwyw() const; - Vector4 wwyw() const; - Vector4 xxzw() const; - Vector4 yxzw() const; - Vector4 zxzw() const; - Vector4 wxzw() const; - Vector4 xyzw() const; - Vector4 yyzw() const; - Vector4 zyzw() const; - Vector4 wyzw() const; - Vector4 xzzw() const; - Vector4 yzzw() const; - Vector4 zzzw() const; - Vector4 wzzw() const; - Vector4 xwzw() const; - Vector4 ywzw() const; - Vector4 zwzw() const; - Vector4 wwzw() const; - Vector4 xxww() const; - Vector4 yxww() const; - Vector4 zxww() const; - Vector4 wxww() const; - Vector4 xyww() const; - Vector4 yyww() const; - Vector4 zyww() const; - Vector4 wyww() const; - Vector4 xzww() const; - Vector4 yzww() const; - Vector4 zzww() const; - Vector4 wzww() const; - Vector4 xwww() const; - Vector4 ywww() const; - Vector4 zwww() const; - Vector4 wwww() const; - -}; - - -//---------------------------------------------------------------------------- -inline Vector4::Vector4() { - x = y = z = w = 0; -} - -//---------------------------------------------------------------------------- - -inline Vector4::Vector4 (float fX, float fY, float fZ, float fW) { - x = fX; - y = fY; - z = fZ; - w = fW; -} - -//---------------------------------------------------------------------------- -inline Vector4::Vector4 (float afCoordinate[4]) { - x = afCoordinate[0]; - y = afCoordinate[1]; - z = afCoordinate[2]; - w = afCoordinate[3]; -} - -//---------------------------------------------------------------------------- -inline Vector4::Vector4(const Vector4& rkVector) { - x = rkVector.x; - y = rkVector.y; - z = rkVector.z; - w = rkVector.w; -} -//---------------------------------------------------------------------------- -inline Vector4::Vector4(const Vector3& rkVector, float fW) { - x = rkVector.x; - y = rkVector.y; - z = rkVector.z; - w = fW; -} - -//---------------------------------------------------------------------------- -inline float& Vector4::operator[] (int i) { - return ((float*)this)[i]; -} - -//---------------------------------------------------------------------------- -inline const float& Vector4::operator[] (int i) const { - return ((float*)this)[i]; -} - -//---------------------------------------------------------------------------- -inline Vector4& Vector4::operator= (const Vector4& rkVector) { - x = rkVector.x; - y = rkVector.y; - z = rkVector.z; - w = rkVector.w; - return *this; -} - -//---------------------------------------------------------------------------- -inline bool Vector4::operator== (const Vector4& rkVector) const { - return ( (x == rkVector.x) && (y == rkVector.y) && (z == rkVector.z) && (w == rkVector.w)); -} - -//---------------------------------------------------------------------------- -inline bool Vector4::operator!= (const Vector4& rkVector) const { - return ( x != rkVector.x || y != rkVector.y || z != rkVector.z || w != rkVector.w); -} - -//---------------------------------------------------------------------------- -inline Vector4 Vector4::operator+ (const Vector4& rkVector) const { - return Vector4(x + rkVector.x, y + rkVector.y, z + rkVector.z, w + rkVector.w); -} - -//---------------------------------------------------------------------------- -inline Vector4 Vector4::operator- (const Vector4& rkVector) const { - return Vector4(x - rkVector.x, y - rkVector.y, z - rkVector.z, w - rkVector.w); -} - -//---------------------------------------------------------------------------- -inline Vector4 Vector4::operator* (float fScalar) const { - return Vector4(fScalar*x, fScalar*y, fScalar*z, fScalar*w); -} - -//---------------------------------------------------------------------------- -inline Vector4 Vector4::operator- () const { - return Vector4( -x, -y, -z, -w); -} - -//---------------------------------------------------------------------------- -inline Vector4& Vector4::operator+= (const Vector4& rkVector) { - x += rkVector.x; - y += rkVector.y; - z += rkVector.z; - w += rkVector.w; - return *this; -} - -//---------------------------------------------------------------------------- -inline Vector4& Vector4::operator-= (const Vector4& rkVector) { - x -= rkVector.x; - y -= rkVector.y; - z -= rkVector.z; - w -= rkVector.w; - return *this; -} - -//---------------------------------------------------------------------------- - -inline Vector4 Vector4::lerp(const Vector4& v, float alpha) const { - return (*this) + (v - *this) * alpha; -} - - -//---------------------------------------------------------------------------- -inline Vector4& Vector4::operator*= (float fScalar) { - x *= fScalar; - y *= fScalar; - z *= fScalar; - w *= fScalar; - return *this; -} - - -//---------------------------------------------------------------------------- -inline float Vector4::dot(const Vector4& rkVector) const { - return x*rkVector.x + y*rkVector.y + z*rkVector.z + w*rkVector.w; -} - -//---------------------------------------------------------------------------- -inline Vector4 Vector4::min(const Vector4 &v) const { - return Vector4(G3D::min(v.x, x), G3D::min(v.y, y), G3D::min(v.z, z), G3D::min(v.w, w)); -} - -//---------------------------------------------------------------------------- -inline Vector4 Vector4::max(const Vector4 &v) const { - return Vector4(G3D::max(v.x, x), G3D::max(v.y, y), G3D::max(v.z, z), G3D::max(v.w, w)); -} - -//---------------------------------------------------------------------------- -inline bool Vector4::isZero() const { - return (x == 0.0f) && (y == 0.0f) && (z == 0.0f) && (w == 0.0f); -} - -//---------------------------------------------------------------------------- - -inline bool Vector4::isFinite() const { - return G3D::isFinite(x) && G3D::isFinite(y) && G3D::isFinite(z) && G3D::isFinite(w); -} - -//---------------------------------------------------------------------------- - -inline bool Vector4::isUnit() const { - return squaredLength() == 1.0; -} - -//---------------------------------------------------------------------------- - -inline float Vector4::length() const { - return sqrtf(squaredLength()); -} - -//---------------------------------------------------------------------------- - -inline float Vector4::squaredLength() const { - return x * x + y * y + z * z + w * w; -} - -} - -template <> struct HashTrait { - static size_t hashCode(const G3D::Vector4& key) { return key.hashCode(); } -}; - - -template<> struct PositionTrait { - static void getPosition(const G3D::Vector4& v, G3D::Vector3& p) { p = v.xyz(); } -}; - -inline G3D::Vector4 operator* (float s, const G3D::Vector4& v) { - return v * s; -} - -#endif diff --git a/externals/g3dlite/G3D/Vector4.inl b/externals/g3dlite/G3D/Vector4.inl deleted file mode 100644 index 576cca83b56..00000000000 --- a/externals/g3dlite/G3D/Vector4.inl +++ /dev/null @@ -1,191 +0,0 @@ -/** - @file Vector4.inl - - @maintainer Morgan McGuire, matrix@graphics3d.com - - @created 2002-07-09 - @edited 2003-02-10 - */ - -//---------------------------------------------------------------------------- - -inline unsigned int hashCode(const G3D::Vector4& v) { - return v.hashCode(); -} - -namespace G3D { - -//---------------------------------------------------------------------------- -inline Vector4::Vector4() { - x = y = z = w = 0; -} - -//---------------------------------------------------------------------------- - -inline Vector4::Vector4 (float fX, float fY, float fZ, float fW) { - x = fX; - y = fY; - z = fZ; - w = fW; -} - -//---------------------------------------------------------------------------- -inline Vector4::Vector4 (float afCoordinate[4]) { - x = afCoordinate[0]; - y = afCoordinate[1]; - z = afCoordinate[2]; - w = afCoordinate[3]; -} - -//---------------------------------------------------------------------------- -inline Vector4::Vector4(const Vector4& rkVector) { - x = rkVector.x; - y = rkVector.y; - z = rkVector.z; - w = rkVector.w; -} -//---------------------------------------------------------------------------- -inline Vector4::Vector4(const Vector3& rkVector, float fW) { - x = rkVector.x; - y = rkVector.y; - z = rkVector.z; - w = fW; -} - -//---------------------------------------------------------------------------- -inline float& Vector4::operator[] (int i) { - return ((float*)this)[i]; -} - -//---------------------------------------------------------------------------- -inline const float& Vector4::operator[] (int i) const { - return ((float*)this)[i]; -} - -//---------------------------------------------------------------------------- -inline Vector4::operator float* () { - return (float*)this; -} - -inline Vector4::operator const float* () const { - return (float*)this; -} - -//---------------------------------------------------------------------------- -inline Vector4& Vector4::operator= (const Vector4& rkVector) { - x = rkVector.x; - y = rkVector.y; - z = rkVector.z; - w = rkVector.w; - return *this; -} - -//---------------------------------------------------------------------------- -inline bool Vector4::operator== (const Vector4& rkVector) const { - return ( (x == rkVector.x) && (y == rkVector.y) && (z == rkVector.z) && (w == rkVector.w)); -} - -//---------------------------------------------------------------------------- -inline bool Vector4::operator!= (const Vector4& rkVector) const { - return ( x != rkVector.x || y != rkVector.y || z != rkVector.z || w != rkVector.w); -} - -//---------------------------------------------------------------------------- -inline Vector4 Vector4::operator+ (const Vector4& rkVector) const { - return Vector4(x + rkVector.x, y + rkVector.y, z + rkVector.z, w + rkVector.w); -} - -//---------------------------------------------------------------------------- -inline Vector4 Vector4::operator- (const Vector4& rkVector) const { - return Vector4(x - rkVector.x, y - rkVector.y, z - rkVector.z, w - rkVector.w); -} - -//---------------------------------------------------------------------------- -inline Vector4 Vector4::operator* (float fScalar) const { - return Vector4(fScalar*x, fScalar*y, fScalar*z, fScalar*w); -} - -//---------------------------------------------------------------------------- -inline Vector4 Vector4::operator- () const { - return Vector4( -x, -y, -z, -w); -} - -//---------------------------------------------------------------------------- -inline Vector4& Vector4::operator+= (const Vector4& rkVector) { - x += rkVector.x; - y += rkVector.y; - z += rkVector.z; - w += rkVector.w; - return *this; -} - -//---------------------------------------------------------------------------- -inline Vector4& Vector4::operator-= (const Vector4& rkVector) { - x -= rkVector.x; - y -= rkVector.y; - z -= rkVector.z; - w -= rkVector.w; - return *this; -} - -//---------------------------------------------------------------------------- - -inline Vector4 Vector4::lerp(const Vector4& v, float alpha) const { - return (*this) + (v - *this) * alpha; -} - -//---------------------------------------------------------------------------- -inline Vector4& Vector4::operator*= (float fScalar) { - x *= fScalar; - y *= fScalar; - z *= fScalar; - w *= fScalar; - return *this; -} - -//---------------------------------------------------------------------------- -inline float Vector4::dot(const Vector4& rkVector) const { - return x*rkVector.x + y*rkVector.y + z*rkVector.z + w*rkVector.w; -} - -//---------------------------------------------------------------------------- -inline Vector4 Vector4::min(const Vector4 &v) const { - return Vector4(G3D::min(v.x, x), G3D::min(v.y, y), G3D::min(v.z, z), G3D::min(v.w, w)); -} - -//---------------------------------------------------------------------------- -inline Vector4 Vector4::max(const Vector4 &v) const { - return Vector4(G3D::max(v.x, x), G3D::max(v.y, y), G3D::max(v.z, z), G3D::max(v.w, w)); -} - -//---------------------------------------------------------------------------- -inline bool Vector4::isZero() const { - return (x == 0.0f) && (y == 0.0f) && (z == 0.0f) && (w == 0.0f); -} - -//---------------------------------------------------------------------------- - -inline bool Vector4::isFinite() const { - return G3D::isFinite(x) && G3D::isFinite(y) && G3D::isFinite(z) && G3D::isFinite(w); -} - -//---------------------------------------------------------------------------- - -inline bool Vector4::isUnit() const { - return squaredLength() == 1.0; -} - -//---------------------------------------------------------------------------- - -inline float Vector4::length() const { - return sqrtf(squaredLength()); -} - -//---------------------------------------------------------------------------- - -inline float Vector4::squaredLength() const { - return x * x + y * y + z * z + w * w; -} - -} - diff --git a/externals/g3dlite/G3D/Vector4int8.h b/externals/g3dlite/G3D/Vector4int8.h deleted file mode 100644 index 544b693e8b3..00000000000 --- a/externals/g3dlite/G3D/Vector4int8.h +++ /dev/null @@ -1,113 +0,0 @@ -/** - @file Vector4int8.h - - Homogeneous vector class. - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2007-02-09 - @edited 2007-02-09 - - Copyright 2000-2007, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_VECTOR4INT8_H -#define G3D_VECTOR4INT8_H - -#include "G3D/platform.h" -#include "G3D/g3dmath.h" - -namespace G3D { - -class Vector3; -class Vector4; - -/** - Homogeneous vector stored efficiently in four signed int8s. - - */ -class Vector4int8 { -private: - // Hidden operators - bool operator<(const Vector4int8&) const; - bool operator>(const Vector4int8&) const; - bool operator<=(const Vector4int8&) const; - bool operator>=(const Vector4int8&) const; - - - /** For fast operations, treat this packed data structure as - an int32 */ - inline uint32& asInt32() { - return *reinterpret_cast(this); - } - - inline const uint32& asInt32() const { - return *reinterpret_cast(this); - } - -public: - // construction - inline Vector4int8() : x(0), y(0), z(0), w(0) {} - - /** Multiplies the source by 127 and clamps to (-128, 127) when converting */ - Vector4int8(const Vector4& source); - - /** Multiplies the source by 127 and clamps to (-128, 127) when converting */ - Vector4int8(const Vector3& source, int8 w); - - inline Vector4int8(int8 x, int8 y, int8 z, int8 w) : x(x), y(y), z(z), w(w) {} - - Vector4int8(class BinaryInput& b); - void serialize(class BinaryOutput& b) const; - void deserialize(class BinaryInput& b); - - // coordinates - int8 x, y, z, w; - - inline operator int8* () { - return reinterpret_cast(this); - } - - inline operator const int8* () const { - return reinterpret_cast(this); - } - - // access vector V as V[0] = V.x, V[1] = V.y, V[2] = V.z, etc. - // - // WARNING. These member functions rely on - // (1) Vector4int8 not having virtual functions - // (2) the data packed in a 4*sizeof(int8) memory block - inline int8& operator[] (int i) { - debugAssert(i >= 0 && i <= 4); - return ((int8*)this)[i]; - } - - const int8& operator[] (int i) const { - debugAssert(i >= 0 && i <= 4); - return ((const int8*)this)[i]; - } - - // assignment and comparison - Vector4int8& operator= (const Vector4int8& other) { - asInt32() = other.asInt32(); - return *this; - } - - inline bool operator== (const Vector4int8& other) const { - return asInt32() == other.asInt32(); - } - - inline bool operator!= (const Vector4int8& other) const { - return ! (*this == other); - } - - inline unsigned int hashCode() const { - return asInt32(); - } -}; - -} // namespace G3D - - -#endif diff --git a/externals/g3dlite/G3D/WeakCache.h b/externals/g3dlite/G3D/WeakCache.h deleted file mode 100644 index f9fdc4bbd5b..00000000000 --- a/externals/g3dlite/G3D/WeakCache.h +++ /dev/null @@ -1,122 +0,0 @@ -/** - @file WeakCache.h - - @maintainer Morgan McGuire, graphics3d.com - - @created 2007-05-16 - @edited 2007-05-16 - - Copyright 2000-2007, Morgan McGuire. - All rights reserved. - */ -#ifndef G3D_WEAKCACHE_H -#define G3D_WEAKCACHE_H - -#include "G3D/ReferenceCount.h" -#include "G3D/Table.h" - -namespace G3D { - -/** - A cache that does not prevent its members from being garbage collected. - Useful to avoid loading or computing an expression twice. Useful - for memoization and dynamic programming. - - Maintains a table of weak pointers. Weak pointers do not prevent - an object from being garbage collected. If the object is garbage - collected, the cache removes its reference. - - There are no "contains" or "iterate" methods because elements can be - flushed from the cache at any time if they are garbage collected. - - Example: -
-      WeakCache textureCache;
-
-      TextureRef loadTexture(std::string s) {
-          TextureRef t = textureCache[s];
-
-          if (t.isNull()) {
-              t = Texture::fromFile(s);
-              textureCache.set(s, t);
-          }
-
-          return t;
-      }
-      
-      
-    
- */ -template -class WeakCache { - typedef WeakReferenceCountedPointer ValueWeakRef; - -private: - - Table table; - -public: - /** - Returns NULL if the object is not in the cache - */ - ValueRef operator[](const Key& k) { - if (table.containsKey(k)) { - ValueWeakRef w = table[k]; - ValueRef s = w.createStrongPtr(); - if (s.isNull()) { - // This object has been collected; clean out its key - table.remove(k); - } - return s; - } else { - return NULL; - } - } - - void set(const Key& k, ValueRef v) { - table.set(k, v); - } - - /** Removes k from the cache or does nothing if it is not currently in the cache.*/ - void remove(const Key& k) { - if (table.containsKey(k)) { - table.remove(k); - } - } -}; - -#if 0 // To turn off all WeakCaching -template -class WeakCache { -private: - - Table table; - -public: - /** - Returns NULL if the object is not in the cache - */ - ValueRef operator[](const Key& k) { - if (table.containsKey(k)) { - return table[k]; - } else { - return NULL; - } - } - - void set(const Key& k, ValueRef v) { - table.set(k, v); - } - - /** Removes k from the cache or does nothing if it is not currently in the cache.*/ - void remove(const Key& k) { - if (table.containsKey(k)) { - table.remove(k); - } - } -}; -#endif - -} -#endif - diff --git a/externals/g3dlite/G3D/Welder.h b/externals/g3dlite/G3D/Welder.h deleted file mode 100644 index 2c2554da7b6..00000000000 --- a/externals/g3dlite/G3D/Welder.h +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef G3D_Welder_h -#define G3D_Welder_h - -#include "G3D/platform.h" -#include "G3D/Array.h" -#include "G3D/Vector3.h" -#include "G3D/Vector2.h" - -namespace G3D { - -class Any; - -class Welder { -private: - - Welder() {} - -public: - - class Settings { - public: - /** Surfaces with normals that are within this angle of each - other are considered to be curved. Default value is toRadians(70.0f).*/ - float normalSmoothingAngle; - float vertexWeldRadius; - float textureWeldRadius; - float normalWeldRadius; - - inline Settings(float normalSmoothAngle = toRadians(70.0f)) : - normalSmoothingAngle(normalSmoothAngle), - vertexWeldRadius(0.0001f), - textureWeldRadius(0.0001f), - normalWeldRadius(0.01f) {} - - - Settings(const Any& any); - operator Any() const; - }; - -/** - Mutates geometry, texCoord, and indexArray so that the output has collocated vertices collapsed (welded). - - @param vertices Input and output - @param textureCoords Input and output - @param normals Output only - @param indices Input and output. This is an array of trilist indices. - @param oldToNewIndex Output argument - @param normalSmoothingAngle Varies from 0 (flat shading) to toRadians(180) for extremely smooth shading. Default is toRadians(70) - */ - static void weld( - Array& vertices, - Array& textureCoords, - Array& normals, - Array*>& indices, - const Settings& settings); - - /** - Mutates geometry, texCoord, and indexArray so that the output has collocated vertices collapsed (welded). - - @param vertices Input and output - @param textureCoords Input and output - @param normals Output only - @param indices Input and output. This is an array of trilist indices. - @param oldToNewIndex Output argument - @param normalSmoothingAngle Varies from 0 (flat shading) to toRadians(180) for extremely smooth shading. Default is toRadians(70) - */ - inline static void weld( - Array& vertices, - Array& textureCoords, - Array& normals, - Array& indices, - const Settings& settings) { - - Array*> meta; - meta.append(&indices); - weld(vertices, textureCoords, normals, meta, settings); - } -}; - -} - -#endif diff --git a/externals/g3dlite/G3D/WrapMode.h b/externals/g3dlite/G3D/WrapMode.h deleted file mode 100644 index 8ef38a77c23..00000000000 --- a/externals/g3dlite/G3D/WrapMode.h +++ /dev/null @@ -1,93 +0,0 @@ -/** - @file WrapMode.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2007-04-17 - @edited 2007-04-17 - - Copyright 2000-2010, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_WrapMode_h -#define G3D_WrapMode_h - -#include "G3D/platform.h" -#include "G3D/enumclass.h" - -#ifdef IGNORE -# undef IGNORE -#endif -#ifdef ZERO -# undef ZERO -#endif -#ifdef ERROR -# undef ERROR -#endif - -namespace G3D { - -/** - Describes the behavior of G3D::Texture, G3D::Map2D, G3D::Image3, - etc. when accessing an out-of-bounds pixel. Not all classes support - all modes. - - Refer to these as scoped enums, e.g., WrapMode m = WrapMode::CLAMP;. - - WrapMode::IGNORE silently discards attempts to write to out - of bounds locations and returns an undefined value for reading - from out of bounds locations. - - WrapMode::ERROR generates an error when the - pixel indices are out of bounds - - WrapMode::CLAMP makes out of bounds pixels equal to the last in-range pixel along that dimension. - - WrapMode::TILE computes out of bounds pixels modulo the dimension - - WrapMode::ZERO treats out of bounds values as the zero value, which varies in definition - according to the class used. For example, with a G3D::Texture, ZERO = Color4(0,0,0,0). - - Uses the "Intelligent Enum" design pattern - http://www.codeguru.com/cpp/cpp/cpp_mfc/article.php/c4001/ - */ -class WrapMode { -public: - /** Don't use this enum; use WrapMode instances instead. */ - enum Value { - CLAMP, - TILE, - ZERO, - IGNORE, - ERROR - }; - -private: - - Value value; - -public: - - G3D_DECLARE_ENUM_CLASS_METHODS(WrapMode); - - inline const char* toString() const { - static const char* s[] = {"CLAMP", "TILE", "ZERO", "IGNORE", "ERROR"}; - return s[value]; - } - - inline explicit WrapMode(const std::string& x) : value(ERROR) { - static const char* s[] = {"CLAMP", "TILE", "ZERO", "IGNORE", "ERROR"}; - for (int i = 0; i < 5; ++i) { - if (x == s[i]) { - value = (Value)i; - } - } - } -}; - -} // namespace G3D - -G3D_DECLARE_ENUM_CLASS_HASHCODE(G3D::WrapMode); - -#endif diff --git a/externals/g3dlite/G3D/constants.h b/externals/g3dlite/G3D/constants.h deleted file mode 100644 index dd5cb3649e5..00000000000 --- a/externals/g3dlite/G3D/constants.h +++ /dev/null @@ -1,129 +0,0 @@ -/** - @file G3D/constants.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - @created 2009-05-20 - @edited 2009-05-20 -*/ -#ifndef G3D_constants_h -#define G3D_constants_h - -#include "G3D/platform.h" -#include "G3D/enumclass.h" - -namespace G3D { - -/** These are defined to have the same value as the equivalent OpenGL - constant. */ -class PrimitiveType { -public: - enum Value { - POINTS = 0x0000, - LINES = 0x0001, - LINE_STRIP = 0x0003, - TRIANGLES = 0x0004, - TRIANGLE_STRIP = 0x0005, - TRIANGLE_FAN = 0x0006, - QUADS = 0x0007, - QUAD_STRIP = 0x0008 - }; - -private: - - Value value; - -public: - - G3D_DECLARE_ENUM_CLASS_METHODS(PrimitiveType); -}; - - -/** Values for SuperSurface::GPUGeom::refractionHint. */ -class RefractionQuality { -public: - enum Value { - /** No refraction; a translucent object will appear as if it had the same index of refraction - as the surrounding medium and objects will be undistorted in the background. */ - NONE = 0, - - /** Use a static environment map (cube or paraboloid) for computing transmissivity.*/ - STATIC_ENV = 25, - - /** Use a dynamically rendered 2D environment map; distort the background. This looks good for many scenes - but avoids the cost of rendering a cube map for DYNAMIC_ENV. */ - DYNAMIC_FLAT = 50, - - /** Use a dynamically rendered 2D environment map that is re-captured per transparent object. This works well - for transparent objects that are separated by a significant camera space z distance but overlap in screen space.*/ - DYNAMIC_FLAT_MULTILAYER = 55, - - /** Render a dynamic environment map */ - DYNAMIC_ENV = 75, - - /** Use the best method available, ideally true ray tracing. */ - BEST = 100 - }; - -private: - - /** Used for to/from string conversion. Last is the emtpy string as a sentinel */ - static const std::string str[7]; - static const Value enm[6]; - Value value; - -public: - G3D_DECLARE_ENUM_CLASS_METHODS(RefractionQuality); - - RefractionQuality(const class Any&); - RefractionQuality& operator=(const Any&); - operator Any() const; - const std::string& toString() const; -}; - - -/** Values for SuperSurface::GPUGeom::mirrorHint. */ -class MirrorQuality { -public: - - enum Value { - /** Reflections are black */ - NONE = 0, - - /** Use a static environment map. This is what most games use */ - STATIC_ENV = 25, - - /** Planar reflection, typically for water or glass windows. This assumes that the mirror is flat; - it is distinct from RefractionQuality::DYNAMIC_FLAT, which assumes the background is flat.*/ - DYNAMIC_PLANAR = 50, - - /** Render a dynamic environment map. */ - DYNAMIC_ENV = 75, - - /** Use the best method available, ideally true ray tracing. */ - BEST = 100 - }; - -private: - - /** Used for to/from string conversion. Last is the emtpy string as a sentinel */ - static const std::string str[6]; - static const Value enm[5]; - - Value value; - -public: - G3D_DECLARE_ENUM_CLASS_METHODS(MirrorQuality); - MirrorQuality(const class Any&); - MirrorQuality& operator=(const Any&); - operator Any() const; - const std::string& toString() const; -}; - -} // namespace G3D - -G3D_DECLARE_ENUM_CLASS_HASHCODE(G3D::PrimitiveType) -G3D_DECLARE_ENUM_CLASS_HASHCODE(G3D::RefractionQuality) -G3D_DECLARE_ENUM_CLASS_HASHCODE(G3D::MirrorQuality) - -#endif - diff --git a/externals/g3dlite/G3D/debug.h b/externals/g3dlite/G3D/debug.h deleted file mode 100644 index a7697fe9c01..00000000000 --- a/externals/g3dlite/G3D/debug.h +++ /dev/null @@ -1,66 +0,0 @@ -/** - @file debug.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2001-08-26 - @edited 2006-02-16 - - Copyright 2000-2006, Morgan McGuire. - All rights reserved. -*/ - -#ifndef G3D_DEBUG_H -#define G3D_DEBUG_H - -#include "G3D/platform.h" -#ifdef _MSC_VER - #include -#endif - -#include "G3D/debugPrintf.h" -#include "G3D/debugAssert.h" - -namespace G3D { - -#ifdef _MSC_VER - // Turn off 64-bit warnings -# pragma warning(push) -# pragma warning( disable : 4312) -# pragma warning( disable : 4267) -# pragma warning( disable : 4311) -#endif - - -/** - Useful for debugging purposes. - */ -inline bool isValidHeapPointer(const void* x) { - #ifdef _MSC_VER - return - (x != (void*)0xcccccccc) && (x != (void*)0xdeadbeef) && (x != (void*)0xfeeefeee); - #else - return x != NULL; - #endif -} - -/** - Returns true if the pointer is likely to be - a valid pointer (instead of an arbitrary number). - Useful for debugging purposes. - */ -inline bool isValidPointer(const void* x) { - #ifdef _MSC_VER - return x != ((void*)0xcccccccc) && (x != (void*)0xdeadbeef) && (x != (void*)0xfeeefeee); - #else - return x != NULL; - #endif -} - -#ifdef _MSC_VER -# pragma warning(pop) -#endif - -} - -#endif diff --git a/externals/g3dlite/G3D/debugAssert.h b/externals/g3dlite/G3D/debugAssert.h deleted file mode 100644 index 432e97e679d..00000000000 --- a/externals/g3dlite/G3D/debugAssert.h +++ /dev/null @@ -1,233 +0,0 @@ -/** - @file debugAssert.h - - debugAssert(expression); - debugAssertM(expression, message); - - @cite - John Robbins, Microsoft Systems Journal Bugslayer Column, Feb 1999. - - http://msdn.microsoft.com/library/periodic/period99/feb99_BUGSLAYE_BUGSLAYE.htm - - @cite - Douglas Cox, An assert() Replacement, Code of The Day, flipcode, Sept 19, 2000 - - http://www.flipcode.com/cgi-bin/msg.cgi?showThread=COTD-AssertReplace&forum=cotd&id=-1 - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2001-08-26 - @edited 2006-01-12 - - Copyright 2000-2006, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_DEBUGASSERT_H -#define G3D_DEBUGASSERT_H - -#include -#include "G3D/platform.h" - -#include - -#ifdef _MSC_VER -// conditional expression is constant -# pragma warning (disable : 4127) -#endif - -#ifdef G3D_LINUX - // Needed so we can define a global display - // pointer for debugAssert. -#if SOMEONE_MADE_THIS_USEFUL - #include - #include - #include -#endif -#endif - - -/** - @def debugBreak() - - Break at the current location (i.e. don't push a procedure stack frame - before breaking). - */ - -/** - @def debugAssert(exp) - Breaks if the expression is false. If G3D_DEBUG_NOGUI is defined, prompts at - the console, otherwise pops up a dialog. The user may then break (debug), - ignore, or halt the program. - - The assertion is also posted to the clipboard under Win32. - */ - -/** - @def debugAssertM(exp, msg) - Breaks if the expression is false and displays a message. If G3D_DEBUG_NOGUI - is defined, prompts at the console, otherwise pops up a dialog. The user may - then break (debug), ignore, or halt the program. - - The assertion is also posted to the clipboard under Win32. - */ - -/** - @def alwaysAssertM(exp, msg) - Same as debugAssertM except that it asserts in release builds as well. - */ - -namespace G3D { -typedef bool (*AssertionHook)( - const char* _expression, - const std::string& message, - const char* filename, - int lineNumber, - bool useGuiPrompt); - -/** - Allows customization of the global function invoked when a debugAssert fails. - The initial value is G3D::_internal::_handleDebugAssert_. G3D will invoke - rawBreak if the hook returns true. If NULL, assertions are not handled. -*/ -void setAssertionHook(AssertionHook hook); - -AssertionHook assertionHook(); - -/** - Called by alwaysAssertM in case of failure in release mode. If returns - true then the program exits with -1 (you can replace this with your own - version that throws an exception or has other failure modes). - */ -void setFailureHook(AssertionHook hook); -AssertionHook failureHook(); - -namespace _internal { - extern AssertionHook _debugHook; - extern AssertionHook _failureHook; -} // internal -} // G3D - -/** - @def __debugPromptShowDialog__ - @internal - */ - -#ifdef G3D_DEBUG - -# if defined(_MSC_VER) -# define rawBreak() ::DebugBreak(); -# elif defined(__i386__) - // gcc on intel -# define rawBreak() __asm__ __volatile__ ( "int $3" ); -# else - // some other gcc -# define rawBreak() ::abort() -# endif - - -# define debugBreak() G3D::_internal::_releaseInputGrab_(); rawBreak(); G3D::_internal::_restoreInputGrab_(); -# define debugAssert(exp) debugAssertM(exp, "Debug assertion failure") - - #ifdef G3D_DEBUG_NOGUI - #define __debugPromptShowDialog__ false - #else - #define __debugPromptShowDialog__ true - #endif - - #define debugAssertM(exp, message) do { \ - if (!(exp)) { \ - G3D::_internal::_releaseInputGrab_(); \ - if ((G3D::_internal::_debugHook != NULL) && \ - G3D::_internal::_debugHook((const char*)(#exp), message, __FILE__, __LINE__, __debugPromptShowDialog__)) { \ - rawBreak(); \ - } \ - G3D::_internal::_restoreInputGrab_(); \ - } \ - } while (0) - - #define alwaysAssertM debugAssertM - -#else // Release - #ifdef G3D_DEBUG_NOGUI - #define __debugPromptShowDialog__ false - #else - #define __debugPromptShowDialog__ true - #endif - - // In the release build, just define away assertions. - #define rawBreak() do {} while (0) - #define debugAssert(exp) do {} while (0) - #define debugAssertM(exp, message) do {} while (0) - #define debugBreak() do {} while (0) - - // But keep the 'always' assertions - #define alwaysAssertM(exp, message) { \ - if (!(exp)) { \ - G3D::_internal::_releaseInputGrab_(); \ - if ((G3D::_internal::_failureHook != NULL) && \ - G3D::_internal::_failureHook(#exp, message, __FILE__, __LINE__, __debugPromptShowDialog__)) { \ - ::exit(-1); \ - } \ - G3D::_internal::_restoreInputGrab_(); \ - } \ - } - -#endif // if debug - - - -namespace G3D { namespace _internal { - -#ifdef G3D_LINUX -#if SOMEONE_MADE_THIS_USEFUL - /** - A pointer to the X11 display. Initially NULL. If set to a - non-null value (e.g. by SDLWindow), debugAssert attempts to use - this display to release the mouse/input grab when an assertion - fails. - */ - extern Display* x11Display; - - /** - A pointer to the X11 window. Initially NULL. If set to a - non-null value (e.g. by SDLWindow), debugAssert attempts to use - this window to release the mouse/input grab when an assertion - fails. - */ - extern Window x11Window; -#endif -#endif - -/** - Pops up an assertion dialog or prints an assertion - - ignoreAlways - return result of pressing the ignore button. - useGuiPrompt - if true, shows a dialog - */ -bool _handleDebugAssert_( - const char* expression, - const std::string& message, - const char* filename, - int lineNumber, - bool useGuiPrompt); - -bool _handleErrorCheck_( - const char* expression, - const std::string& message, - const char* filename, - int lineNumber, - bool useGuiPrompt); - -/** Attempts to give the user back their mouse and keyboard if they - were locked to the current window. - @internal*/ -void _releaseInputGrab_(); - -/** Attempts to restore the state before _releaseInputGrab_. - @internal*/ -void _restoreInputGrab_(); - -}; }; // namespace - -#endif diff --git a/externals/g3dlite/G3D/debugPrintf.h b/externals/g3dlite/G3D/debugPrintf.h deleted file mode 100644 index b42151cae9e..00000000000 --- a/externals/g3dlite/G3D/debugPrintf.h +++ /dev/null @@ -1,62 +0,0 @@ -/** - @file debugPrintf.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2001-08-26 - @edited 2007-07-20 - - Copyright 2000-2007, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_DEBUGPRINTF_H -#define G3D_DEBUGPRINTF_H - -#include "G3D/platform.h" -#include -#include -#include "G3D/format.h" -#include - -namespace G3D { - -typedef void (*ConsolePrintHook)(const std::string&); - -namespace _internal { - extern ConsolePrintHook _consolePrintHook; -} - -/** Called by consolePrintf after the log and terminal have been written to. - Used by GConsole to intercept printing routines.*/ -void setConsolePrintHook(ConsolePrintHook h); - -ConsolePrintHook consolePrintHook(); - -/** - Sends output to the log and to the last GConsole instantiated. - - Guarantees that the output has been flushed by the time the routine - returns. - @sa G3D::logPrintf, G3D::screenPrintf - @return The string that was printed - */ -std::string __cdecl consolePrintf(const char* fmt ...) G3D_CHECK_PRINTF_ARGS; -std::string consolePrint(const std::string&); - -/** - Under visual studio, appears in the VS debug pane. - On unix-based operating systems the output is sent to stderr. - - Also sends output to the console (G3D::consolePrintf) if there is a consolePrintHook, - and log (G3D::logPrintf), and flushes before returning. - - @return The string that was printed -*/ -std::string __cdecl debugPrintf(const char* fmt ...) G3D_CHECK_PRINTF_ARGS; -std::string debugPrint(const std::string&); - -} // namespace G3D - -#endif - diff --git a/externals/g3dlite/G3D/enumclass.h b/externals/g3dlite/G3D/enumclass.h deleted file mode 100644 index c7dfe45f14f..00000000000 --- a/externals/g3dlite/G3D/enumclass.h +++ /dev/null @@ -1,147 +0,0 @@ -/** - @file G3D/enumclass.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - @created 2007-01-27 - @edited 2007-07-20 -*/ -#ifndef G3D_enumclass_h -#define G3D_enumclass_h - -#include "G3D/HashTrait.h" -#include "G3D/BinaryInput.h" -#include "G3D/BinaryOutput.h" - -/** -\def G3D_DECLARE_ENUM_CLASS_METHODS - - \brief Creates a series of methods that turn a class into a scoped enumeration. - - Uses the "Intelligent Enum" design pattern - http://www.codeguru.com/cpp/cpp/cpp_mfc/article.php/c4001/ - - Enum classes are initialized to their zero value by default. - - See GLG3D/GKey.h for an example. - \sa G3D_DECLARE_ENUM_CLASS_HASHCODE - */ -#define G3D_DECLARE_ENUM_CLASS_METHODS(Classname)\ - inline Classname(char v) : value((Value)v) {}\ -\ - inline Classname() : value((Value)0) {}\ -\ - inline Classname(const Value v) : value(v) {}\ -\ - explicit inline Classname(int v) : value((Value)v) {}\ -\ - /** Support cast back to the Value type, which is needed to allow implicit assignment inside unions. */\ - /*inline operator Value() const { - return value; - }*/\ -\ - inline operator int() const {\ - return (int)value;\ - }\ -\ - inline bool operator== (const Classname other) const {\ - return value == other.value;\ - }\ -\ - inline bool operator== (const Classname::Value other) const {\ - return value == other;\ - }\ -\ - inline bool operator!= (const Classname other) const {\ - return value != other.value;\ - }\ -\ - inline bool operator!= (const Classname::Value other) const {\ - return value != other;\ - }\ -\ - inline bool operator< (const Classname other) const {\ - return value < other.value;\ - }\ -\ - inline bool operator> (const Classname other) const {\ - return value > other.value;\ - }\ -\ - inline bool operator>= (const Classname other) const {\ - return value >= other.value;\ - }\ -\ - inline bool operator<= (const Classname other) const {\ - return value <= other.value;\ - }\ -\ - inline bool operator< (const Value other) const {\ - return value < other;\ - }\ -\ - inline bool operator> (const Value other) const {\ - return value > other;\ - }\ -\ - inline bool operator<= (const Value other) const {\ - return value <= other;\ - }\ -\ - inline bool operator>= (const Value other) const {\ - return value >= other;\ - }\ -\ - inline Classname& operator-- () {\ - value = (Value)((int)value - 1);\ - return *this;\ - }\ -\ - inline Classname& operator++ () {\ - value = (Value)((int)value + 1);\ - return *this;\ - }\ -\ - inline Classname& operator+= (const int x) {\ - value = (Value)((int)value + x);\ - return *this;\ - }\ -\ - inline Classname& operator-= (const int x) {\ - value = (Value)((int)value - x);\ - return *this;\ - }\ -\ - inline Classname operator+ (const int x) const {\ - return Classname((int)value + x);\ - }\ -\ - inline Classname operator- (const int x) const {\ - return Classname((int)value - x);\ - }\ -\ - inline unsigned int hashCode() const {\ - return (unsigned int)value;\ - }\ -\ - inline void serialize(BinaryOutput& b) const {\ - b.writeInt32(value);\ - }\ -\ - inline void deserialize(BinaryInput& b) {\ - value = (Value)b.readInt32();\ - } - -/** \def G3D_DECLARE_ENUM_CLASS_HASHCODE -*/ -#define G3D_DECLARE_ENUM_CLASS_HASHCODE(Classname)\ -template <> struct HashTrait \ -{ \ - static size_t hashCode(Classname::Value key) { return static_cast(key); } \ -}; \ - \ -template <> struct HashTrait \ -{ \ - static size_t hashCode(Classname key) { return static_cast(key.hashCode()); } \ -}; - -#endif diff --git a/externals/g3dlite/G3D/fileutils.h b/externals/g3dlite/G3D/fileutils.h deleted file mode 100644 index 9e49777d93a..00000000000 --- a/externals/g3dlite/G3D/fileutils.h +++ /dev/null @@ -1,254 +0,0 @@ -/** - @file fileutils.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @author 2002-06-06 - @edited 2010-02-06 - - Copyright 2000-2010, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_fileUtils_h -#define G3D_fileUtils_h - -#include "G3D/platform.h" -#include -#include -#include "G3D/Array.h" -#include "G3D/Set.h" -#include "G3D/g3dmath.h" - -#ifdef G3D_WIN32 -// For chdir, mkdir, etc. -# include -#endif - -namespace G3D { - - namespace _internal { - extern Set currentFilesUsed; - } - -/** Returns all the files used by G3D and GLG3D during the current execution. */ -Array filesUsed(); - -std::string readWholeFile( - const std::string& filename); - - -/** Reads from a zip file and decompresses the desired contents - into memory. Does not support recursive zip calls (i.e. a .zip - stored within another .zip) - - @param file the path, of the format C:\\...\\something.zip\\...\\desiredfile.ext - @param data a pointer to the memory where the file will be stored - @param length the size of the file decompressed to memory */ -void zipRead(const std::string& file, - void*& data, - size_t& length); - - -/** Closes the contents of a zip file that had been decompressed to - memory. Must be called in tandem with zipRead() to avoid memory - leaks. - - @param data the pointer to the decompressed file in memory */ -void zipClose(void* data); - - -/** - @param flush If true (default), the file is ready for reading as soon - as the function returns. If false, the function returns immediately and - writes the file in the background. - */ -void writeWholeFile( - const std::string& filename, - const std::string& str, - bool flush = true); - -/** - Creates the directory (which may optionally end in a /) - and any parents needed to reach it. - */ -void createDirectory( - const std::string& dir); - -/** - Fully qualifies a filename. The filename may contain wildcards, - in which case the wildcards will be preserved in the returned value. - */ -std::string resolveFilename(const std::string& filename); - -/** - Appends all files matching filespec to the files array. The names - will not contain paths unless includePath == true. These may be - relative to the current directory unless the filespec is fully qualified - (can be done with resolveFilename). - Wildcards can only appear to the right of the last slash in filespec. - Works with .zip files used as paths, if filespec is passed in the form - C:\\...\\something.zip\\* Does not work recursively with zipfiles (a - .zip within a .zip will not work) - */ -void getFiles( - const std::string& filespec, - Array& files, - bool includePath = false); - -/** - Appends all directories matching filespec to the files array. The names - will not contain paths unless includePath == true. These may be - relative to the current directory unless the filespec is fully qualified - (can be done with resolveFilename). - Does not append special directories "." or "..". - Works with .zip files used as paths, if filespec is passed in the form - C:\\...\\something.zip\\* Does not work recursively with zipfiles (a - .zip within a .zip will not work) - */ -void getDirs( - const std::string& filespec, - Array& files, - bool includePath = false); - - -/** Returns true if the specified path exists and is a directory */ -bool isDirectory(const std::string& filespec); - - -/** Returns true if the specified filename exists and is a zipfile */ -bool isZipfile(const std::string& filename); - - -/** Returns the length of the file. If - filename specifies a path that contains a zipfile, but the - contents within are specified correctly, returns the - uncompressed size of the requested file. Returns -1 if - the file does not exist. - - @param filename the path to test, may contain .zip -*/ -int64 fileLength(const std::string& filename); - -/** - Copies the file - */ -void copyFile( - const std::string& source, - const std::string& dest); - -/** Returns a temporary file that is open for read/write access. This - tries harder than the ANSI tmpfile, so it may succeed when that fails. */ -FILE* createTempFile(); - -/** - Returns true if the given file (or directory) exists. - - \param filename the path to test. must not end in a trailing slash. - \param lookInZipfiles if the path does not exist, calls zipfileExists() - \param trustCache If true and \a lookInZipfiles is true, cache directory and zipfile contents - so that subsequent calls to the same directory are fast. - - \sa G3D::clearFileSystemCache, G3D::zipfileExists - */ -bool fileExists -(const std::string& filename, - bool lookInZipfiles = true, - bool trustCache = true); - - -/** Clears the cache used by fileExists */ -void clearFileSystemCache(); - -/** - Returns true if the given file (or directory) exists - within a zipfile. Called if fileExists initially - returns false and the lookInZipfiles flag has been set. - Must not end in a trailing slash. Does not work for recursive - zipfiles (.zips within another .zip) - - @param filename the path to test - @param outZipfile the path to the .zip file - @param outInternalFile the path (within the .zip) where the desired file is located, if valid - - */ -bool zipfileExists -(const std::string& filename, - std::string& outZipfile, - std::string& outInternalFile); - -bool zipfileExists(const std::string& filename); - -/** - Parses a filename into four useful pieces. - - Examples: - - c:\\a\\b\\d.e - root = "c:\\" - path = "a" "b" - base = "d" - ext = "e" - - /a/b/d.e - root = "/" - path = "a" "b" - base = "d" - ext = "e" - - /a/b - root = "/" - path = "a" - base = "b" - ext = "e" - - */ -void parseFilename( - const std::string& filename, - std::string& drive, - Array& path, - std::string& base, - std::string& ext); - - -/** - Returns the part of the filename that includes the base and ext from - parseFilename (i.e. everything to the right of the path). - */ -std::string filenameBaseExt(const std::string& filename); - -/** - Returns the extension on a filename. - */ -std::string filenameExt(const std::string& filename); - - -/** Returns the portion of a filename to the left of the last period - and to the right of the last slash or colon. - */ -std::string filenameBase(const std::string& filename); - -/** Creates a unique filename base in the current directory using the - specified prefix and suffix.*/ -std::string generateFilenameBase(const std::string& prefix = "", const std::string& suffix = ""); - -/** - Returns the drive (if Win32) and path from a filename, including - a slash if there was one. - filenamePath(f) + filenameBaseExt(f) == f - */ -std::string filenamePath(const std::string& filename); - -/** Returns true if '*' or '?' appears in the string */ -bool filenameContainsWildcards(const std::string& filename); - -/** Returns true if dst does not exist or src is newer than dst. Works on both files and directories. */ -bool fileIsNewer(const std::string& src, const std::string& dst); - -/** Appends file onto dirname, ensuring a / if needed. */ -std::string pathConcat(const std::string& dirname, const std::string& file); - -} // namespace - -#endif - diff --git a/externals/g3dlite/G3D/filter.h b/externals/g3dlite/G3D/filter.h deleted file mode 100644 index 609477b79c9..00000000000 --- a/externals/g3dlite/G3D/filter.h +++ /dev/null @@ -1,29 +0,0 @@ -/** - @file G3D/filter.h - - @author Morgan McGuire, http://graphics.cs.williams.edu - @created 2007-03-01 - @edited 2007-03-01 - - Copyright 2000-2007, Morgan McGuire. - All rights reserved. - */ -#ifndef G3D_FILTER_H -#define G3D_FILTER_H - -#include "G3D/platform.h" -#include "G3D/Array.h" -#include "G3D/g3dmath.h" - -namespace G3D { -/** - Generates a set of 1D gaussian filter coefficients of size N. The coefficients - are centered on element (N-1)/2 and have standard deviation given by std. The coefficients - are normalized such that the sum across coeff is 1.0. - - Matches the results returned by Matlab fspecial('gaussian', [1, N], std) - */ -void gaussian1D(Array& coeff, int N = 5, float std = 0.5f); -} - -#endif diff --git a/externals/g3dlite/G3D/format.h b/externals/g3dlite/G3D/format.h deleted file mode 100644 index 3c7f0678876..00000000000 --- a/externals/g3dlite/G3D/format.h +++ /dev/null @@ -1,44 +0,0 @@ -/** - @file format.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @author 2000-09-09 - @edited 2005-11-03 - - Copyright 2000-2005, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_FORMAT_H -#define G3D_FORMAT_H - -#include "G3D/platform.h" -#include -#include -#include - -namespace G3D { - -/** - Produces a string from arguments of the style of printf. This avoids - problems with buffer overflows when using sprintf and makes it easy - to use the result functionally. This function is fast when the resulting - string is under 160 characters (not including terminator) and slower - when the string is longer. - */ -std::string __cdecl format( - const char* fmt - ...) G3D_CHECK_PRINTF_ARGS; - -/** - Like format, but can be called with the argument list from a ... function. - */ -std::string vformat( - const char* fmt, - va_list argPtr) G3D_CHECK_VPRINTF_ARGS; - - -} // namespace - -#endif diff --git a/externals/g3dlite/G3D/g3dfnmatch.h b/externals/g3dlite/G3D/g3dfnmatch.h deleted file mode 100644 index 464b3927eee..00000000000 --- a/externals/g3dlite/G3D/g3dfnmatch.h +++ /dev/null @@ -1,83 +0,0 @@ -/*- - * Copyright (c) 1992, 1993 - *The Regents of the University of California. 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. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - *This product includes software developed by the University of - *California, Berkeley and its contributors. - * 4. Neither the name of the University 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 REGENTS 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 REGENTS 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. - * - *@(#)fnmatch.h8.1 (Berkeley) 6/2/93 - * - * From FreeBSD fnmatch.h 1.7 - * $Id: g3dfnmatch.h,v 1.1 2010/02/06 06:51:28 morgan3d Exp $ - */ -#ifndef G3D_g3dfnmatch_h -#define G3D_g3dfnmatch_h - -#include "G3D/platform.h" - -namespace G3D { - -#if defined(G3D_WIN32) - -# if ! defined(FNM_NOMATCH) -# define FNM_NOMATCH 1 /* Match failed. */ -# define FNM_NOESCAPE 0x01 /* Disable backslash escaping. */ -# define FNM_PATHNAME 0x02 /* Slash must be matched by slash. */ -# define FNM_PERIOD 0x04 /* Period must be matched by period. */ -# define FNM_LEADING_DIR 0x08 /* Ignore / after Imatch. */ -# define FNM_CASEFOLD 0x10 /* Case insensitive search. */ -# define FNM_PREFIX_DIRS 0x20 /* Directory prefixes of pattern match too. */ -# endif - -#else - - // On non-windows systems, include fnmatch directly -# include -#endif - - -/** - Function fnmatch() as specified in POSIX 1003.2-1992, section B.6. - Compares a filename or pathname to a pattern. - -The fnmatch() function checks whether the string argument matches the pattern argument, which is a shell wildcard pattern. -The flags argument modifies the behaviour; it is the bitwise OR of zero or more of the following flags: - -- FNM_NOESCAPE If this flag is set, treat backslash as an ordinary character, instead of an escape character. -- FNM_PATHNAME If this flag is set, match a slash in string only with a slash in pattern and not by an asterisk (*) or a question mark (?) metacharacter, nor by a bracket expression ([]) containing a slash. -- FNM_PERIOD If this flag is set, a leading period in string has to be matched exactly by a period in pattern. A period is considered to be leading if it is the first character in string, or if both FNM_PATHNAME is set and the period immediately follows a slash. -- FNM_FILE_NAME This is a GNU synonym for FNM_PATHNAME. -- FNM_LEADING_DIR If this flag (a GNU extension) is set, the pattern is considered to be matched if it matches an initial segment of string which is followed by a slash. This flag is mainly for the internal use of glibc and is only implemented in certain cases. -- FNM_CASEFOLD If this flag (a GNU extension) is set, the pattern is matched case-insensitively. - -\return Zero if \a string matches \a pattern, FNM_NOMATCH if there is no match or another non-zero value if there is an error - - */ -int g3dfnmatch(const char *pattern, const char *string, int flags); -} -#endif diff --git a/externals/g3dlite/G3D/g3dmath.h b/externals/g3dlite/G3D/g3dmath.h deleted file mode 100644 index d16214ebb37..00000000000 --- a/externals/g3dlite/G3D/g3dmath.h +++ /dev/null @@ -1,845 +0,0 @@ -/** - @file g3dmath.h - - Math util class. - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - @cite highestBit by Jukka Liimatta - - @created 2001-06-02 - @edited 2009-04-07 - - Copyright 2000-2006, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_g3dmath_h -#define G3D_g3dmath_h - -#ifdef _MSC_VER -// Disable conditional expression is constant, which occurs incorrectly on inlined functions -# pragma warning (push) -# pragma warning (disable : 4127) -// disable: "C++ exception handler used" -# pragma warning (disable : 4530) -#endif - -#include "G3D/platform.h" -#include -#include -#include -#include - -#ifdef _MSC_VER - // Visual Studio is missing inttypes.h -# ifndef PRId64 -# define PRId64 "I64d" -# endif -#else -#include -#endif - -/*These defines enable functionality introduced with the 1999 ISO C -**standard. They must be defined before the inclusion of math.h to -**engage them. If optimisation is enabled, these functions will be -**inlined. With optimisation switched off, you have to link in the -**maths library using -lm. -*/ - -#define _ISOC9X_SOURCE1 -#define _ISOC99_SOURCE1 -#define __USE_ISOC9X1 -#define __USE_ISOC991 - -#include - -#include "G3D/debug.h" - -#undef min -#undef max - -namespace G3D { - -#ifdef _MSC_VER -inline double __fastcall drand48() { - return ::rand() / double(RAND_MAX); -} - -#if !defined(_WIN64) - -/** - Win32 implementation of the C99 fast rounding routines. - - @cite routines are - Copyright (C) 2001 Erik de Castro Lopo - - Permission to use, copy, modify, distribute, and sell this file for any - purpose is hereby granted without fee, provided that the above copyright - and this permission notice appear in all copies. No representations are - made about the suitability of this software for any purpose. It is - provided "as is" without express or implied warranty. -*/ - -__inline long int lrint (double flt) { - int intgr; - - _asm { - fld flt - fistp intgr - }; - - return intgr; -} - -__inline long int lrintf(float flt) { - int intgr; - - _asm { - fld flt - fistp intgr - }; - - return intgr; -} - -#else - - __inline long int lrint (double flt) { - return (long int)floor(flt+0.5f); - } - - __inline long int lrintf(float flt) { - return (long int)floorf(flt+0.5f); - } - -#endif - -#endif - - -#define fuzzyEpsilon (0.00001f) -/** - This value should not be tested against directly, instead - G3D::isNan() and G3D::isFinite() will return reliable results. */ -double inf(); - -/** This value should not be tested against directly, instead - G3D::isNan() and G3D::isFinite() will return reliable results. */ -double nan(); - -float finf(); - -float fnan(); - -inline double pi() { - return 3.1415926535898; -} - -inline double halfPi() { - return 1.57079633; -} - -inline double twoPi() { - return 6.28318531; -} - -typedef signed char int8; -typedef unsigned char uint8; -typedef short int16; -typedef unsigned short uint16; -typedef int int32; -typedef unsigned int uint32; - -#ifdef _MSC_EXTENSIONS - typedef __int64 int64; - typedef unsigned __int64 uint64; -#elif ! defined(_MSC_VER) - typedef int64_t int64; - typedef uint64_t uint64; -#else - typedef long long int64; - typedef unsigned long long uint64; -#endif - -typedef float float32; -typedef double float64; - -int iAbs(int iValue); -int iCeil(double fValue); - -/** - Clamps the value to the range [low, hi] (inclusive) - */ -int iClamp(int val, int low, int hi); -int16 iClamp(int16 val, int16 low, int16 hi); -double clamp(double val, double low, double hi); -float clamp(float val, float low, float hi); - -/** - Returns a + (b - a) * f; - */ -inline double lerp(double a, double b, double f) { - return a + (b - a) * f; -} - -inline float lerp(float a, float b, float f) { - return a + (b - a) * f; -} - -/** - Wraps the value to the range [0, hi) (exclusive - on the high end). This is like the clock arithmetic - produced by % (modulo) except the result is guaranteed - to be positive. - */ -int iWrap(int val, int hi); - -int iFloor(double fValue); - -int iSign(int iValue); -int iSign(double fValue); - -inline int iSign(float f) { - return iSign((double)f); -} - - -/** - Fast round to integer using the lrint routine. - Typically 6x faster than casting to integer. - */ -inline int iRound(double fValue) { - return lrint(fValue); -} - -/** - Fast round to integer using the lrint routine. - Typically 6x faster than casting to integer. - */ -inline int iRound(float f) { - return lrintf(f); -} - -/** - Returns a random number uniformly at random between low and hi - (inclusive). - @deprecated Use Random::integer - */ -int iRandom(int low, int hi); - -double abs (double fValue); -double aCos (double fValue); -double aSin (double fValue); -double aTan (double fValue); -double aTan2 (double fY, double fX); -double sign (double fValue); -double square (double fValue); - -/** - Returns true if the argument is a finite real number. - */ -bool isFinite(double x); - -/** - Returns true if the argument is NaN (not a number). - You can't use x == nan to test this because all - comparisons against nan return false. - */ -bool isNaN(double x); -bool isNaN(float x); -inline bool isNaN(int x) { - (void)x; - return false; -} - -/** - Computes x % 3. - */ -int iMod3(int x); - -/** - Uniform random number between low and hi, inclusive. [low, hi] - @deprecated - @sa Random::uniform - */ -float uniformRandom(float low = 0.0f, float hi = 1.0f); - -/** - Normally distributed random number. - - @deprecated - @sa Random::gaussian - */ -float gaussRandom(float mean = 0.0f, float stdev = 1.0f); - - -/** Returns x5 */ -template -inline T pow5(T x) { - const T y = x * x; - return y * y * x; -} - - -template -inline T min(const T& x, const T& y) { - return std::min(x, y); -} - -template -inline T min(const T& x, const T& y, const T& z) { - return std::min(std::min(x, y), z); -} - -template -inline T min(const T& x, const T& y, const T& z, const T& w) { - return std::min(std::min(x, y), std::min(z, w)); -} - -template -inline T max(const T& x, const T& y) { - return std::max(x, y); -} - -template -inline T max(const T& x, const T& y, const T& z) { - return std::max(std::max(x, y), z); -} - -template -inline T max(const T& x, const T& y, const T& z, const T& w) { - return std::max(std::max(x, y), std::max(z, w)); -} - -int iMin(int x, int y); -int iMax(int x, int y); - -double square(double x); -double sumSquares(double x, double y); -double sumSquares(double x, double y, double z); -double distance(double x, double y); -double distance(double x, double y, double z); - -/** - Returnes the 0-based index of the highest 1 bit from - the left. -1 means the number was 0. - - @cite Based on code by jukka@liimatta.org - */ -int highestBit(uint32 x); - -/** - Note that fuzzyEq(a, b) && fuzzyEq(b, c) does not imply - fuzzyEq(a, c), although that will be the case on some - occasions. - */ -bool fuzzyEq(double a, double b); - -/** True if a is definitely not equal to b. - Guaranteed false if a == b. - Possibly false when a != b.*/ -bool fuzzyNe(double a, double b); - -/** Is a strictly greater than b? (Guaranteed false if a <= b). - (Possibly false if a > b) */ -bool fuzzyGt(double a, double b); - -/** Is a near or greater than b? */ -bool fuzzyGe(double a, double b); - -/** Is a strictly less than b? (Guaranteed false if a >= b)*/ -bool fuzzyLt(double a, double b); - -/** Is a near or less than b? */ -bool fuzzyLe(double a, double b); - -/** - Computes 1 / sqrt(x). - */ -inline float rsq(float x) { - return 1.0f / sqrtf(x); -} - -/** - Return the next power of 2 higher than the input - If the input is already a power of 2, the output will be the same - as the input. - */ -int ceilPow2(unsigned int in); - -/** Returns 2^x */ -inline int pow2(unsigned int x) { - return 1 << x; -} - -inline double log2(double x) { - return ::log(x) * 1.442695; -} - -inline float log2(float x) { - return ::logf(x) * 1.442695f; -} - -inline double log2(int x) { - return log2((double)x); -} - - -/** - * True if num is a power of two. - */ -bool isPow2(int num); - -bool isOdd(int num); -bool isEven(int num); - -double toRadians(double deg); -double toDegrees(double rad); - -/** - Returns true if x is not exactly equal to 0.0f. - */ -inline bool any(float x) { - return x != 0; -} - -/** - Returns true if x is not exactly equal to 0.0f. - */ -inline bool all(float x) { - return x != 0; -} - -/** - v / v (for DirectX/Cg support) - */ -inline float normalize(float v) { - return v / v; -} - -/** - a * b (for DirectX/Cg support) - */ -inline float dot(float a, float b) { - return a * b; -} - - -/** - a * b (for DirectX/Cg support) - */ -inline float mul(float a, float b) { - return a * b; -} - -/** - 2^x - */ -inline double exp2(double x) { - return pow(2.0, x); -} - -inline float exp2(float x) { - return powf(2.0f, x); -} - -/** @deprecated Use rsq */ -inline double rsqrt(double x) { - return 1.0 / sqrt(x); -} - -/** @deprecated Use rsq */ -inline float rsqrt(float x) { - // TODO: default this to using the SSE2 instruction - return 1.0 / sqrtf(x); -} - -/** - sin(x)/x - */ -inline double sinc(double x) { - double r = sin(x) / x; - - if (isNaN(r)) { - return 1.0; - } else { - return r; - } -} - -/** - Computes a floating point modulo; the result is t wrapped to the range [lo, hi). - */ -inline float wrap(float t, float lo, float hi) { - if ((t >= lo) && (t < hi)) { - return t; - } - - debugAssert(hi > lo); - - float interval = hi - lo; - - return t - interval * iFloor((t - lo) / interval); -} - - -inline double wrap(double t, double lo, double hi) { - if ((t >= lo) && (t < hi)) { - return t; - } - - debugAssert(hi > lo); - - double interval = hi - lo; - - return t - interval * iFloor((t - lo) / interval); -} - -inline double wrap(double t, double hi) { - return wrap(t, 0.0, hi); -} - - -inline bool isFinite(double x) { - return ! isNaN(x) && (x < G3D::inf()) && (x > -G3D::inf()); -} - -inline bool isFinite(float x) { - return ! isNaN(x) && (x < G3D::finf()) && (x > -G3D::finf()); -} - -//---------------------------------------------------------------------------- -inline int iAbs (int iValue) { - return ( iValue >= 0 ? iValue : -iValue ); -} - -//---------------------------------------------------------------------------- -inline int iCeil (double fValue) { - return int(::ceil(fValue)); -} - -//---------------------------------------------------------------------------- - -inline int iClamp(int val, int low, int hi) { - debugAssert(low <= hi); - if (val <= low) { - return low; - } else if (val >= hi) { - return hi; - } else { - return val; - } -} - -//---------------------------------------------------------------------------- - -inline int16 iClamp(int16 val, int16 low, int16 hi) { - debugAssert(low <= hi); - if (val <= low) { - return low; - } else if (val >= hi) { - return hi; - } else { - return val; - } -} - -//---------------------------------------------------------------------------- - -inline double clamp(double val, double low, double hi) { - debugAssert(low <= hi); - if (val <= low) { - return low; - } else if (val >= hi) { - return hi; - } else { - return val; - } -} - -inline float clamp(float val, float low, float hi) { - debugAssert(low <= hi); - if (val <= low) { - return low; - } else if (val >= hi) { - return hi; - } else { - return val; - } -} -//---------------------------------------------------------------------------- - -inline int iWrap(int val, int hi) { - if (val < 0) { - return ((val % hi) + hi) % hi; - } else { - return val % hi; - } -} - -//---------------------------------------------------------------------------- -inline int iFloor (double fValue) { - return int(::floor(fValue)); -} - -//---------------------------------------------------------------------------- -inline int iSign (int iValue) { - return ( iValue > 0 ? + 1 : ( iValue < 0 ? -1 : 0 ) ); -} - -inline int iSign (double fValue) { - return ( fValue > 0.0 ? + 1 : ( fValue < 0.0 ? -1 : 0 ) ); -} - -//---------------------------------------------------------------------------- -inline double abs (double fValue) { - return double(::fabs(fValue)); -} - -//---------------------------------------------------------------------------- -inline double aCos (double fValue) { - if ( -1.0 < fValue ) { - if ( fValue < 1.0 ) - return double(::acos(fValue)); - else - return 0.0; - } else { - return pi(); - } -} - -//---------------------------------------------------------------------------- -inline double aSin (double fValue) { - if ( -1.0 < fValue ) { - if ( fValue < 1.0 ) { - return double(::asin(fValue)); - } else { - return -halfPi(); - } - } else { - return halfPi(); - } -} - -//---------------------------------------------------------------------------- -inline double aTan (double fValue) { - return double(::atan(fValue)); -} - -//---------------------------------------------------------------------------- -inline double aTan2 (double fY, double fX) { - return double(::atan2(fY, fX)); -} - -//---------------------------------------------------------------------------- -inline double sign (double fValue) { - if (fValue > 0.0) { - return 1.0; - } - - if (fValue < 0.0) { - return -1.0; - } - - return 0.0; -} - -inline float sign (float fValue) { - if (fValue > 0.0f) { - return 1.0f; - } - - if (fValue < 0.0f) { - return -1.0f; - } - - return 0.0f; -} - - -inline float uniformRandom(float low, float hi) { - return (hi - low) * float(::rand()) / float(RAND_MAX) + low; -} - -inline double square(double x) { - return x * x; -} - -inline float square(float x) { - return x * x; -} - -inline int square(int x) { - return x * x; -} - -//---------------------------------------------------------------------------- -inline double sumSquares(double x, double y) { - return x*x + y*y; -} - -//---------------------------------------------------------------------------- -inline float sumSquares(float x, float y) { - return x*x + y*y; -} - -//---------------------------------------------------------------------------- -inline double sumSquares(double x, double y, double z) { - return x*x + y*y + z*z; -} - -//---------------------------------------------------------------------------- -inline float sumSquares(float x, float y, float z) { - return x*x + y*y + z*z; -} - -//---------------------------------------------------------------------------- -inline double distance(double x, double y) { - return sqrt(sumSquares(x, y)); -} - -//---------------------------------------------------------------------------- -inline float distance(float x, float y) { - return sqrt(sumSquares(x, y)); -} - -//---------------------------------------------------------------------------- -inline double distance(double x, double y, double z) { - return sqrt(sumSquares(x, y, z)); -} - -//---------------------------------------------------------------------------- -inline float distance(float x, float y, float z) { - return sqrt(sumSquares(x, y, z)); -} - -//---------------------------------------------------------------------------- - -/** @deprecated use G3D::min */ -inline int iMin(int x, int y) { - return (x >= y) ? y : x; -} - -//---------------------------------------------------------------------------- -/** @deprecated use G3D::min */ -inline int iMax(int x, int y) { - return (x >= y) ? x : y; -} - -//---------------------------------------------------------------------------- -inline int ceilPow2(unsigned int in) { - in -= 1; - - in |= in >> 16; - in |= in >> 8; - in |= in >> 4; - in |= in >> 2; - in |= in >> 1; - - return in + 1; -} - -inline bool isPow2(int num) { - return ((num & -num) == num); -} - -inline bool isOdd(int num) { - return (num & 1) == 1; -} - -inline bool isEven(int num) { - return (num & 1) == 0; -} - -inline double toRadians(double deg) { - return deg * pi() / 180.0; -} - -inline double toDegrees(double rad) { - return rad * 180.0 / pi(); -} - -inline float toRadians(float deg) { - return deg * (float)pi() / 180.0f; -} - -inline float toDegrees(float rad) { - return rad * 180.0f / (float)pi(); -} - -inline float toRadians(int deg) { - return deg * (float)pi() / 180.0f; -} - -inline float toDegrees(int rad) { - return rad * 180.0f / (float)pi(); -} -/** - Computes an appropriate epsilon for comparing a and b. - */ -inline double eps(double a, double b) { - // For a and b to be nearly equal, they must have nearly - // the same magnitude. This means that we can ignore b - // since it either has the same magnitude or the comparison - // will fail anyway. - (void)b; - const double aa = abs(a) + 1.0; - if (aa == inf()) { - return fuzzyEpsilon; - } else { - return fuzzyEpsilon * aa; - } -} - -inline bool fuzzyEq(double a, double b) { - return (a == b) || (abs(a - b) <= eps(a, b)); -} - -inline bool fuzzyNe(double a, double b) { - return ! fuzzyEq(a, b); -} - -inline bool fuzzyGt(double a, double b) { - return a > b + eps(a, b); -} - -inline bool fuzzyGe(double a, double b) { - return a > b - eps(a, b); -} - -inline bool fuzzyLt(double a, double b) { - return a < b - eps(a, b); -} - -inline bool fuzzyLe(double a, double b) { - return a < b + eps(a, b); -} - -inline int iMod3(int x) { - return x % 3; -} - -/** - Given a 32-bit integer, returns the integer with the bytes in the opposite order. - */ -inline uint32 flipEndian32(const uint32 x) { - return (x << 24) | ((x & 0xFF00) << 8) | - ((x & 0xFF0000) >> 8) | ((x & 0xFF000000) >> 24); -} - -/** - Given a 16-bit integer, returns the integer with the bytes in the opposite order. - */ -inline uint16 flipEndian16(const uint16 x) { - return (x << 8) | ((x & 0xFF00) >> 8); -} - - -} // namespace - -#ifdef _MSC_VER -# pragma warning (pop) -#endif - -#endif - diff --git a/externals/g3dlite/G3D/g3dmath.inl b/externals/g3dlite/G3D/g3dmath.inl deleted file mode 100644 index 9bf661a7ebc..00000000000 --- a/externals/g3dlite/G3D/g3dmath.inl +++ /dev/null @@ -1,288 +0,0 @@ -/** - @file g3dmath.inl - - @maintainer Morgan McGuire, matrix@graphics3d.com - - @created 2001-06-02 - @edited 2006-01-14 - */ - -#include - -#ifdef _MSC_VER -// Disable conditional expression is constant, which occurs incorrectly on inlined functions -# pragma warning (push) -# pragma warning( disable : 4127 ) -#endif - -namespace G3D { - -inline bool isNaN(double x) { - bool b1 = (x < 0.0); - bool b2 = (x >= 0.0); - bool b3 = !(b1 || b2); - return b3; -} - -inline bool isFinite(double x) { - return ! isNaN(x) && (x < G3D::inf()) && (x > -G3D::inf()); -} - -//---------------------------------------------------------------------------- -inline int iAbs (int iValue) { - return ( iValue >= 0 ? iValue : -iValue ); -} - -//---------------------------------------------------------------------------- -inline int iCeil (double fValue) { - return int(::ceil(fValue)); -} - -//---------------------------------------------------------------------------- - -inline int iClamp(int val, int low, int hi) { - debugAssert(low <= hi); - if (val <= low) { - return low; - } else if (val >= hi) { - return hi; - } else { - return val; - } -} - -//---------------------------------------------------------------------------- - -inline double clamp(double val, double low, double hi) { - debugAssert(low <= hi); - if (val <= low) { - return low; - } else if (val >= hi) { - return hi; - } else { - return val; - } -} - -inline float clamp(float val, float low, float hi) { - debugAssert(low <= hi); - if (val <= low) { - return low; - } else if (val >= hi) { - return hi; - } else { - return val; - } -} -//---------------------------------------------------------------------------- - -inline int iWrap(int val, int hi) { - if (val < 0) { - return ((val % hi) + hi) % hi; - } else { - return val % hi; - } -} - -//---------------------------------------------------------------------------- -inline int iFloor (double fValue) { - return int(::floor(fValue)); -} - -//---------------------------------------------------------------------------- -inline int iSign (int iValue) { - return ( iValue > 0 ? + 1 : ( iValue < 0 ? -1 : 0 ) ); -} - -inline int iSign (double fValue) { - return ( fValue > 0.0 ? + 1 : ( fValue < 0.0 ? -1 : 0 ) ); -} - -//---------------------------------------------------------------------------- -inline double abs (double fValue) { - return double(::fabs(fValue)); -} - -//---------------------------------------------------------------------------- -inline double aCos (double fValue) { - if ( -1.0 < fValue ) { - if ( fValue < 1.0 ) - return double(::acos(fValue)); - else - return 0.0; - } else { - return G3D_PI; - } -} - -//---------------------------------------------------------------------------- -inline double aSin (double fValue) { - if ( -1.0 < fValue ) { - if ( fValue < 1.0 ) { - return double(::asin(fValue)); - } else { - return -G3D_HALF_PI; - } - } else { - return G3D_HALF_PI; - } -} - -//---------------------------------------------------------------------------- -inline double aTan (double fValue) { - return double(::atan(fValue)); -} - -//---------------------------------------------------------------------------- -inline double aTan2 (double fY, double fX) { - return double(::atan2(fY, fX)); -} - -//---------------------------------------------------------------------------- -inline double sign (double fValue) { - if (fValue > 0.0) { - return 1.0; - } - - if (fValue < 0.0) { - return -1.0; - } - - return 0.0; -} - -inline double G3D_DEPRECATED unitRandom () { - return double(::rand()) / double(RAND_MAX); -} - -inline float uniformRandom(float low, float hi) { - return (hi - low) * float(::rand()) / float(RAND_MAX) + low; -} - -//---------------------------------------------------------------------------- -inline double G3D_DEPRECATED symmetricRandom () { - return 2.0 * double(::rand()) / double(RAND_MAX) - 1.0; -} - -//---------------------------------------------------------------------------- -inline double square(double x) { - return x * x; -} - -//---------------------------------------------------------------------------- -inline double sumSquares(double x, double y) { - return x*x + y*y; -} - -//---------------------------------------------------------------------------- -inline double sumSquares(double x, double y, double z) { - return x*x + y*y + z*z; -} - -//---------------------------------------------------------------------------- -inline double distance(double x, double y) { - return sqrt(sumSquares(x, y)); -} - -//---------------------------------------------------------------------------- -inline double distance(double x, double y, double z) { - return sqrt(sumSquares(x, y, z)); -} - -//---------------------------------------------------------------------------- - -/** @deprecated use G3D::min */ -inline int iMin(int x, int y) { - return (x >= y) ? y : x; -} - -//---------------------------------------------------------------------------- -/** @deprecated use G3D::min */ -inline int iMax(int x, int y) { - return (x >= y) ? x : y; -} - -//---------------------------------------------------------------------------- -inline int ceilPow2(unsigned int in) { - in -= 1; - - in |= in >> 16; - in |= in >> 8; - in |= in >> 4; - in |= in >> 2; - in |= in >> 1; - - return in + 1; -} - -inline bool isPow2(int num) { - return ((num & -num) == num); -} - -inline bool isOdd(int num) { - return (num & 1) == 1; -} - -inline bool isEven(int num) { - return (num & 1) == 0; -} - -inline double toRadians(double deg) { - return deg * G3D_PI / 180.0; -} - -inline double toDegrees(double rad) { - return rad * 180.0 / G3D_PI; -} - -/** - Computes an appropriate epsilon for comparing a and b. - */ -inline double eps(double a, double b) { - // For a and b to be nearly equal, they must have nearly - // the same magnitude. This means that we can ignore b - // since it either has the same magnitude or the comparison - // will fail anyway. - (void)b; - const double aa = abs(a) + 1; - if (aa == inf()) { - return fuzzyEpsilon; - } else { - return fuzzyEpsilon * aa; - } -} - -inline bool fuzzyEq(double a, double b) { - return (a == b) || (abs(a - b) <= eps(a, b)); -} - -inline bool fuzzyNe(double a, double b) { - return ! fuzzyEq(a, b); -} - -inline bool fuzzyGt(double a, double b) { - return a > b + eps(a, b); -} - -inline bool fuzzyGe(double a, double b) { - return a > b - eps(a, b); -} - -inline bool fuzzyLt(double a, double b) { - return a < b - eps(a, b); -} - -inline bool fuzzyLe(double a, double b) { - return a < b + eps(a, b); -} - -inline int iMod3(int x) { - return x % 3; -} - -} // namespace G3D - -#ifdef _MSC_VER -// Disable conditional expression is constant, which occurs incorrectly on inlined functions -# pragma warning (pop) -#endif diff --git a/externals/g3dlite/G3D/platform.h b/externals/g3dlite/G3D/platform.h deleted file mode 100644 index 11ba0127a16..00000000000 --- a/externals/g3dlite/G3D/platform.h +++ /dev/null @@ -1,331 +0,0 @@ -/** - @file platform.h - - \#defines for platform specific issues. - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2003-06-09 - @edited 2010-01-11 - */ - -#ifndef G3D_platform_h -#define G3D_platform_h - -/** - The version number of G3D in the form: MmmBB -> - version M.mm [beta BB] - */ -#define G3D_VER 80004 - -// fatal error for unsupported architectures -#if defined(__powerpc__) -# error PowerPC is not supported by G3D! -#endif - -#if defined(G3D_RELEASEDEBUG) -# define G3D_DEBUGRELEASE -#endif - -#if defined(G3D_DEBUGRELEASE) && defined(_DEBUG) -# undef _DEBUG -#endif - -/** @def G3D_DEBUG() - Defined if G3D is built in debug mode. */ -#if !defined(G3D_DEBUG) && (defined(_DEBUG) || defined(G3D_DEBUGRELEASE)) -# define G3D_DEBUG -#endif - -#ifndef _MSC_VER -/// Fast call is a register-based optimized calling convention supported only by Visual C++ -#define __fastcall - -#endif - -#ifdef _MSC_VER - #define G3D_WIN32 -#elif defined(__FreeBSD__) || defined(__OpenBSD__) - #define G3D_FREEBSD - #define G3D_LINUX -#elif defined(__linux__) - #define G3D_LINUX -#elif defined(__APPLE__) - #define G3D_OSX - - // Prevent OS X fp.h header from being included; it defines - // pi as a constant, which creates a conflict with G3D -#define __FP__ -#else - #error Unknown platform -#endif - -// Detect 64-bit under various compilers -#if (defined(_M_X64) || defined(_WIN64) || defined(__LP64__) || defined(_LP64)) -# define G3D_64BIT - #if defined(WIN32) - #include - #endif -#else -# define G3D_32BIT -#endif - -// Strongly encourage inlining on gcc -#ifdef __GNUC__ -#define inline __inline__ -#endif - - -// Verify that the supported compilers are being used and that this is a known -// processor. - -#ifdef G3D_LINUX -# ifndef __GNUC__ -# error G3D only supports the gcc compiler on Linux. -# endif -#endif - -#ifdef G3D_OSX -# ifndef __GNUC__ -# error G3D only supports the gcc compiler on OS X. -# endif - -# if defined(__i386__) -# define G3D_OSX_INTEL -# elif defined(__PPC__) -# define G3D_OSX_PPC -# else -# define G3D_OSX_UNKNOWN -# endif - -#endif - - -#ifdef _MSC_VER -// Microsoft Visual C++ 8.0 ("Express") = 1400 -// Microsoft Visual C++ 7.1 ("2003") _MSC_VER = 1310 -// Microsoft Visual C++ 7.0 ("2002") _MSC_VER = 1300 -// Microsoft Visual C++ 6.0 _MSC_VER = 1200 -// Microsoft Visual C++ 5.0 _MSC_VER = 1100 - -// Turn off warnings about deprecated C routines -# pragma warning (disable : 4996) - -// Turn off "conditional expression is constant" warning; MSVC generates this -// for debug assertions in inlined methods. -# pragma warning (disable : 4127) - -/** @def G3D_DEPRECATED() - Creates deprecated warning. */ -# define G3D_DEPRECATED __declspec(deprecated) - -// Prevent Winsock conflicts by hiding the winsock API -# ifndef _WINSOCKAPI_ -# define _G3D_INTERNAL_HIDE_WINSOCK_ -# define _WINSOCKAPI_ -# endif - -// Disable 'name too long for browse information' warning -# pragma warning (disable : 4786) -// TODO: remove -# pragma warning (disable : 4244) - -# define restrict - -/** @def G3D_CHECK_PRINTF_METHOD_ARGS() - Enables printf parameter validation on gcc. */ -# define G3D_CHECK_PRINTF_ARGS - -/** @def G3D_CHECK_PRINTF_METHOD_ARGS() - Enables printf parameter validation on gcc. */ -# define G3D_CHECK_VPRINTF_ARGS - -/** @def G3D_CHECK_PRINTF_METHOD_ARGS() - Enables printf parameter validation on gcc. */ -# define G3D_CHECK_PRINTF_METHOD_ARGS - -/** @def G3D_CHECK_PRINTF_METHOD_ARGS() - Enables printf parameter validation on gcc. */ -# define G3D_CHECK_VPRINTF_METHOD_ARGS - - // On MSVC, we need to link against the multithreaded DLL version of - // the C++ runtime because that is what SDL and ZLIB are compiled - // against. This is not the default for MSVC, so we set the following - // defines to force correct linking. - // - // For documentation on compiler options, see: - // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccore/html/_core_.2f.md.2c_2f.ml.2c_2f.mt.2c_2f.ld.asp - // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccore98/HTML/_core_Compiler_Reference.asp - // - - // DLL runtime - #ifndef _DLL - #define _DLL - #endif - - // Multithreaded runtime - #ifndef _MT - #define _MT 1 - #endif - - // Ensure that we aren't forced into the static lib - #ifdef _STATIC_CPPLIB - #undef _STATIC_CPPLIB - #endif - - #ifdef _DEBUG - #pragma comment (linker, "/NODEFAULTLIB:LIBCMTD.LIB") - #pragma comment (linker, "/NODEFAULTLIB:LIBCPMTD.LIB") - #pragma comment (linker, "/NODEFAULTLIB:LIBCPD.LIB") - #pragma comment (linker, "/DEFAULTLIB:MSVCPRTD.LIB") - #pragma comment(linker, "/NODEFAULTLIB:LIBCD.LIB") - #pragma comment(linker, "/DEFAULTLIB:MSVCRTD.LIB") - #else - #pragma comment(linker, "/NODEFAULTLIB:LIBC.LIB") - #pragma comment(linker, "/DEFAULTLIB:MSVCRT.LIB") - #pragma comment (linker, "/NODEFAULTLIB:LIBCMT.LIB") - #pragma comment (linker, "/NODEFAULTLIB:LIBCPMT.LIB") - #pragma comment(linker, "/NODEFAULTLIB:LIBCP.LIB") - #pragma comment (linker, "/DEFAULTLIB:MSVCPRT.LIB") - #endif - - // Now set up external linking - -# ifdef _DEBUG - // zlib was linked against the release MSVCRT; force - // the debug version. -# pragma comment(linker, "/NODEFAULTLIB:MSVCRT.LIB") -# endif - - -# ifndef WIN32_LEAN_AND_MEAN -# define WIN32_LEAN_AND_MEAN 1 -# endif - - -# define NOMINMAX 1 -# ifndef _WIN32_WINNT -# define _WIN32_WINNT 0x0500 -# endif -# include -# undef WIN32_LEAN_AND_MEAN -# undef NOMINMAX - -# ifdef _G3D_INTERNAL_HIDE_WINSOCK_ -# undef _G3D_INTERNAL_HIDE_WINSOCK_ -# undef _WINSOCKAPI_ -# endif - - -/** @def G3D_START_AT_MAIN() - Defines necessary wrapper around WinMain on Windows to allow transfer of execution to main(). */ -# define G3D_START_AT_MAIN()\ -int WINAPI G3D_WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int sw);\ -int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int sw) {\ - return G3D_WinMain(hInst, hPrev, szCmdLine, sw);\ -} - -#else - -/** @def G3D_START_AT_MAIN() - Defines necessary wrapper around WinMain on Windows to allow transfer of execution to main(). */ -# define G3D_START_AT_MAIN() - -#endif // win32 - -#ifdef __GNUC__ - -# include - -# if __STDC_VERSION__ < 199901 -# define restrict __restrict__ -# endif - -/** @def G3D_DEPRECATED() - Creates deprecated warning. */ -# define G3D_DEPRECATED __attribute__((__deprecated__)) - -// setup function calling conventions -# if defined(__i386__) && ! defined(__x86_64__) - -# ifndef __cdecl -# define __cdecl __attribute__((cdecl)) -# endif - -# ifndef __stdcall -# define __stdcall __attribute__((stdcall)) -# endif - -# elif defined(__x86_64__) - -# ifndef __cdecl -# define __cdecl -# endif - -# ifndef __stdcall -# define __stdcall -# endif -# endif // calling conventions - -/** @def G3D_CHECK_PRINTF_METHOD_ARGS() - Enables printf parameter validation on gcc. */ -# define G3D_CHECK_PRINTF_METHOD_ARGS __attribute__((__format__(__printf__, 2, 3))) - -/** @def G3D_CHECK_PRINTF_METHOD_ARGS() - Enables printf parameter validation on gcc. */ -# define G3D_CHECK_VPRINTF_METHOD_ARGS __attribute__((__format__(__printf__, 2, 0))) - -/** @def G3D_CHECK_PRINTF_METHOD_ARGS() - Enables printf parameter validation on gcc. */ -# define G3D_CHECK_PRINTF_ARGS __attribute__((__format__(__printf__, 1, 2))) - -/** @def G3D_CHECK_PRINTF_METHOD_ARGS() - Enables printf parameter validation on gcc. */ -# define G3D_CHECK_VPRINTF_ARGS __attribute__((__format__(__printf__, 1, 0))) -#endif - - -/** - @def STR(expression) - - Creates a string from the expression. Frequently used with G3D::Shader - to express shading programs inline. - - STR(this becomes a string)\verbatim
\endverbatim evaluates the same as \verbatim\endverbatim"this becomes a string"
- */
-#define STR(x) #x
-
-/** @def PRAGMA(expression)
-    \#pragma may not appear inside a macro, so this uses the pragma operator
-    to create an equivalent statement.*/
-#ifdef _MSC_VER
-// Microsoft's version http://msdn.microsoft.com/en-us/library/d9x1s805.aspx
-#    define PRAGMA(x) __pragma(x)
-#else
-// C99 standard http://www.delorie.com/gnu/docs/gcc/cpp_45.html
-#    define PRAGMA(x) _Pragma(#x)
-#endif
-
-/** @def G3D_BEGIN_PACKED_CLASS(byteAlign)
-    Switch to tight alignment
-    See G3D::Color3uint8 for an example.*/
-#ifdef _MSC_VER
-#    define G3D_BEGIN_PACKED_CLASS(byteAlign)  PRAGMA( pack(push, byteAlign) )
-#else
-#    define G3D_BEGIN_PACKED_CLASS(byteAlign)
-#endif
-
-/** @def G3D_END_PACKED_CLASS(byteAlign)
-    End switch to tight alignment
-    See G3D::Color3uint8 for an example.*/
-#ifdef _MSC_VER
-#    define G3D_END_PACKED_CLASS(byteAlign)  ; PRAGMA( pack(pop) )
-#elif defined(__GNUC__)
-#    define G3D_END_PACKED_CLASS(byteAlign)  __attribute((aligned(byteAlign))) ;
-#else
-#    define G3D_END_PACKED_CLASS(byteAlign)  ;
-#endif
-
-
-// Header guard
-#endif
diff --git a/externals/g3dlite/G3D/prompt.h b/externals/g3dlite/G3D/prompt.h
deleted file mode 100644
index c6df628099e..00000000000
--- a/externals/g3dlite/G3D/prompt.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/** 
- @file prompt.h
- 
- @maintainer Morgan McGuire, http://graphics.cs.williams.edu
- @cite   Windows GUI code by Max McGuire
-
- @created 2001-08-26
- @edited  2006-08-13
- */
-
-#ifndef G3D_PROMPT_H
-#define G3D_PROMPT_H
-
-#include "platform.h"
-#include 
-
-namespace G3D {
-
-/**
-  Prints a prompt to stdout and waits for user input.  The return value is
-  the number of the user's choice (the first is 0, if there are no
-  choices, returns 0). 
- 
-  @param useGui Under Win32, use a GUI, not stdout prompt.
-  @param windowTitle The title for the prompt window
-  @param promptx The text string to prompt the user with
-  @param choice  An array of strings that are the choices the user may make
-  @param numChoices The length of choice.
-
-  @cite Windows dialog interface by Max McGuire, mmcguire@ironlore.com
-  @cite Font setting code by Kurt Miller, kurt@flipcode.com
- */
-int prompt(
-    const char*     windowTitle,
-    const char*     promptx,
-    const char**    choice,
-    int             numChoices,
-    bool            useGui);
-
-/**
-  Prints a prompt and waits for user input.  The return value is
-  the number of the user's choice (the first is 0, if there are no
-  choices, returns 0).
-  

Uses GUI under Win32, stdout prompt otherwise. - */ -inline int prompt( - const char* windowTitle, - const char* promptx, - const char** choice, - int numChoices) { - - return prompt(windowTitle, promptx, choice, numChoices, true); -} - - -/** - Displays a GUI prompt with "Ok" as the only choice. - */ -void msgBox( - const std::string& message, - const std::string& title = "Message"); - - -}; // namespace - -#endif - diff --git a/externals/g3dlite/G3D/serialize.h b/externals/g3dlite/G3D/serialize.h deleted file mode 100644 index 2382c0ee0fd..00000000000 --- a/externals/g3dlite/G3D/serialize.h +++ /dev/null @@ -1,30 +0,0 @@ -#ifndef G3D_SERIALIZE_H -#define G3D_SERIALIZE_H - -#include "G3D/BinaryInput.h" -#include "G3D/BinaryOutput.h" -#include "G3D/Array.h" - -namespace G3D { - - -template -void serialize(const Array& array, BinaryOutput& b) { - b.writeInt32(array.size()); - for (int i = 0; i < array.size(); ++i) { - serialize(array[i], b); - } -} - -template -void deserialize(Array& array, BinaryInput& b) { - int N = b.readInt32(); - array.resize(N); - for (int i = 0; i < array.size(); ++i) { - deserialize(array[i], b); - } -} - -} - -#endif diff --git a/externals/g3dlite/G3D/splinefunc.h b/externals/g3dlite/G3D/splinefunc.h deleted file mode 100644 index 3f3a018c292..00000000000 --- a/externals/g3dlite/G3D/splinefunc.h +++ /dev/null @@ -1,118 +0,0 @@ -/** - @file spline.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2004-07-25 - @edited 2007-05-05 - */ - -#ifndef G3D_SPLINEFUNC_H -#define G3D_SPLINEFUNC_H - -#include "G3D/platform.h" -#include "G3D/debug.h" -#include "G3D/Array.h" -#include "G3D/g3dmath.h" - -namespace G3D { - -/** - Interpolates a property according to a piecewise linear spline. This provides - C0 continuity but the derivatives are not smooth. -

- Example: - - const double times[] = {MIDNIGHT, SUNRISE - HOUR, SUNRISE, SUNRISE + sunRiseAndSetTime / 4, SUNRISE + sunRiseAndSetTime, SUNSET - sunRiseAndSetTime, SUNSET - sunRiseAndSetTime / 2, SUNSET, SUNSET + HOUR/2, DAY}; - const Color3 color[] = {Color3(0, .0, .1), Color3(0, .0, .1), Color3::black(), Color3::black(), Color3::white() * .25, Color3::white() * .25, Color3(.5, .2, .2), Color3(.05, .05, .1), Color3(0, .0, .1), Color3(0, .0, .1)}; - ambient = linearSpline(time, times, color, 10); - - - See also G3D::Spline - - @param x The spline is a function of x; this is the sample to choose. - @param controlX controlX[i], controlY[i] is a control points. It is assumed - that controlX are strictly increasing. XType must support - the "<" operator and a subtraction operator that returns - a number. - @param controlY YType must support multiplication and addition. - @param numControl The number of control points. - */ -template -YType linearSpline(double x, const XType* controlX, const YType* controlY, int numControl) { - debugAssert(numControl >= 1); - - // Off the beginning - if ((numControl == 1) || (x < controlX[0])) { - return controlY[0]; - } - - for (int i = 1; i < numControl; ++i) { - if (x < controlX[i]) { - const double alpha = (double)(controlX[i] - x) / (controlX[i] - controlX[i - 1]); - return controlY[i] * (1 - alpha) + controlY[i - 1] * alpha; - } - } - - // Off the end - return controlY[numControl - 1]; -} - - - /** See also G3D::Spline*/ -template YType cyclicCatmullRomSpline( - double t, - const YType* controlY, - int numPoints) { - - debugAssert(numPoints >= 3); - - t = wrap(t, numPoints); - - // Find the indices of adjacent control points - int i = iFloor(t); - - // Compute the distance from the control point - t = t - i; - - // Shift back one point for correct indexing - i += numPoints - 1; - - // Pick up four control points - const YType& P0 = controlY[(i + 0) % numPoints]; - const YType& P1 = controlY[(i + 1) % numPoints]; - const YType& P2 = controlY[(i + 2) % numPoints]; - const YType& P3 = controlY[(i + 3) % numPoints]; - - return 0.5 * ((2 * P1) + - (-P0 + P2) * t + - (2*P0 - 5*P1 + 4*P2 - P3) * t*t + - (-P0 + 3*P1- 3*P2 + P3) * t*t*t); -} - -/** - A cubic spline with regularly spaced - control points. The spline interpolates - the control points. The spline - will wrap from the last point back to the first. - - The t parameter is on the range [0, controlY.size()], - where integers correspond to control points exactly. - - See also G3D::Spline - - @cite http://www.mvps.org/directx/articles/catmull/ -*/ -template YType cyclicCatmullRomSpline( - double t, - const Array& controlY) { - - int numPoints = controlY.size(); - return cyclicCatmullRomSpline(t, controlY.getCArray(), numPoints); -} - -} - -#endif - - diff --git a/externals/g3dlite/G3D/stringutils.h b/externals/g3dlite/G3D/stringutils.h deleted file mode 100644 index e15a757a7a6..00000000000 --- a/externals/g3dlite/G3D/stringutils.h +++ /dev/null @@ -1,140 +0,0 @@ -/** - @file stringutils.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @author 2000-09-09 - @edited 2008-08-05 - */ - -#ifndef G3D_STRINGUTILS_H -#define G3D_STRINGUTILS_H - -#include "G3D/platform.h" -#include "G3D/Array.h" -#include - -namespace G3D { - -extern const char* NEWLINE; - -/** Separates a comma-separated line, properly escaping commas within - double quotes (") and super quotes ("""). This matches Microsoft Excel's - CSV output. - - \param stripQuotes If true, strips leading and trailing " and """ - - \sa G3D::stringSplit, G3D::TextInput, G3D::readWholeFile -*/ -void parseCommaSeparated(const std::string s, Array& array, bool stripQuotes = true); - -/** - Returns true if the test string begins with the pattern string. - */ -bool beginsWith( - const std::string& test, - const std::string& pattern); - -/** - Returns true if the test string ends with the pattern string. - */ -bool endsWith( - const std::string& test, - const std::string& pattern); - -/** - Produces a new string that is the input string - wrapped at a certain number of columns (where - the line is broken at the latest space before the - column limit.) Platform specific NEWLINEs - are inserted to wrap. - */ -std::string wordWrap( - const std::string& input, - int numCols); - -/** - A comparison function for passing to Array::sort. - */ -int stringCompare( - const std::string& s1, - const std::string& s2); - -int stringPtrCompare( - const std::string* s1, - const std::string* s2); - -/** - Returns a new string that is an uppercase version of x. - */ -std::string toUpper( - const std::string& x); - -std::string toLower( - const std::string& x); - -/** - Splits x at each occurance of splitChar. - */ -G3D::Array stringSplit( - const std::string& x, - char splitChar); - -/** - joinChar is not inserted at the beginning or end, just in between - elements. - */ -std::string stringJoin( - const G3D::Array& a, - char joinChar); - -std::string stringJoin( - const G3D::Array& a, - const std::string& joinStr); - -/** - Strips whitespace from both ends of the string. - */ -std::string trimWhitespace( - const std::string& s); - -/** These standard C functions are renamed for clarity/naming - conventions and to return bool, not int. - */ -inline bool isWhiteSpace(const unsigned char c) { - return isspace(c) != 0; -} - -/** These standard C functions are renamed for clarity/naming - conventions and to return bool, not int. - */ -inline bool isNewline(const unsigned char c) { - return (c == '\n') || (c == '\r'); -} - -/** These standard C functions are renamed for clarity/naming - conventions and to return bool, not int. - */ -inline bool isDigit(const unsigned char c) { - return isdigit(c) != 0; -} - -/** These standard C functions are renamed for clarity/naming - conventions and to return bool, not int. - */ -inline bool isLetter(const unsigned char c) { - return isalpha(c) != 0; -} - -inline bool isSlash(const unsigned char c) { - return (c == '\\') || (c == '/'); -} - -inline bool isQuote(const unsigned char c) { - return (c == '\'') || (c == '\"'); -} - -}; // namespace - -#endif - diff --git a/externals/g3dlite/G3D/uint128.h b/externals/g3dlite/G3D/uint128.h deleted file mode 100644 index da1af3ec272..00000000000 --- a/externals/g3dlite/G3D/uint128.h +++ /dev/null @@ -1,51 +0,0 @@ -/** - @file uint128.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - @author Kyle Whitson - - @created 2008-07-17 - @edited 2008-07-17 - */ - -#ifndef G3D_UINT128_H -#define G3D_UINT128_H - -#include "G3D/g3dmath.h" - -namespace G3D { - -/** Limited functionality 128-bit unsigned integer. This is primarily to support FNV hashing and other - cryptography applications. See the GMP library for high-precision C++ math support. */ -class uint128 { -public: - - G3D::uint64 hi; - G3D::uint64 lo; - - uint128(const uint64& lo); - - uint128(const uint64& hi, const uint64& lo); - - uint128& operator+=(const uint128& x); - - uint128& operator*=(const uint128& x); - - uint128& operator^=(const uint128& x); - - uint128& operator&=(const uint128& x); - - uint128& operator|=(const uint128& x); - - bool operator==(const uint128& x); - - uint128& operator>>=(const int x); - - uint128& operator<<=(const int x); - - uint128 operator&(const uint128& x); - -}; -} - -#endif diff --git a/externals/g3dlite/G3D/units.h b/externals/g3dlite/G3D/units.h deleted file mode 100644 index 2e30304dc62..00000000000 --- a/externals/g3dlite/G3D/units.h +++ /dev/null @@ -1,126 +0,0 @@ -/** - @file units.h - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2009-08-21 - @edited 2009-08-21 - */ -#ifndef G3D_units_h -#define G3D_units_h - -#include "G3D/platform.h" - -namespace G3D { -/** Use using namespace G3D::units; to include all units - into your program. The units system is specifically designed not to - be general but to support commonly used units efficiently and - clearly. See http://en.wikipedia.org/wiki/SI_prefix for interesting facts - about SI/metric units and full definitions.*/ -namespace units { - -/** 1e-9 m */ -inline float nanometers() { - return 1e-9f; -} - -/** 1e-6 m */ -inline float micrometers() { - return 1e-6f; -} - -/** 0.001 m */ -inline float millimeters() { - return 0.001f; -} - -/** 0.01 m */ -inline float centimeters() { - return 0.01f; -} - -/** SI base unit of distance measure. */ -inline float meters() { - return 1.0f; -} - -/** 1000 m */ -inline float kilometers() { - return 100.0f; -} - -/** 0.0254 m */ -inline float inches() { - return 0.0254f; -} - -/** 0.3048 m */ -inline float feet() { - return 0.3048f; -} - -/** 0.9144 m */ -inline float yards() { - return 0.9144f; -} - -/** 1609.344 m */ -inline float miles() { - return 1609.344f; -} - -///////////////////////////////////////////////////////////// - -/** SI base unit of angular measure. */ -inline float radians() { - return 1.0f; -} - -/** pi/180 */ -inline float degrees() { - return 0.0174532925f; -} - -////////////////////////////////////////////////////////////// - -/** 1e-9 s */ -inline float nanoseconds() { - return 1e-9f; -} - -/** 1e-3 s */ -inline float milliseconds() { - return 1e-3f; -} - -/** Base unit of time */ -inline float seconds() { - return 1.0; -} - -/** 60 s */ -inline float minutes() { - return 60.0f; -} - -/** 3600 s */ -inline float hours() { - return 3600.0f; -} - -/** 86400 s */ -inline float days() { - return 86400.0f; -} - -/** 31556926 s */ -inline float years() { - return 31556926.0f; -} - -/////////////////////////////////////////// - -} -} - -#endif diff --git a/externals/g3dlite/G3D/vectorMath.h b/externals/g3dlite/G3D/vectorMath.h deleted file mode 100644 index ac6d2b32e9d..00000000000 --- a/externals/g3dlite/G3D/vectorMath.h +++ /dev/null @@ -1,235 +0,0 @@ -/** - @file vectorMath.h - - Function aliases for popular vector methods. - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created: 2001-06-02 - @edited: 2004-02-02 - Copyright 2000-2004, Morgan McGuire. - All rights reserved. - */ - -#ifndef G3D_VECTORMATH_H -#define G3D_VECTORMATH_H - -#include "G3D/platform.h" -#include "G3D/g3dmath.h" -#include "G3D/Vector2.h" -#include "G3D/Vector3.h" -#include "G3D/Vector4.h" -#include "G3D/Matrix3.h" -#include "G3D/Matrix4.h" -#include "G3D/Color1.h" -#include "G3D/Color3.h" -#include "G3D/Color4.h" - - -namespace G3D { - - -inline Matrix4 mul(const Matrix4& a, const Matrix4& b) { - return a * b; -} - -inline Vector4 mul(const Matrix4& m, const Vector4& v) { - return m * v; -} - -inline Vector3 mul(const Matrix3& m, const Vector3& v) { - return m * v; -} - -inline Matrix3 mul(const Matrix3& a, const Matrix3& b) { - return a * b; -} - -inline float dot(const Vector2& a, const Vector2& b) { - return a.dot(b); -} - -inline float dot(const Vector3& a, const Vector3& b) { - return a.dot(b); -} - -inline float dot(const Vector4& a, const Vector4& b) { - return a.dot(b); -} - -inline Vector2 normalize(const Vector2& v) { - return v / v.length(); -} - -inline Vector3 normalize(const Vector3& v) { - return v / v.magnitude(); -} - -inline Vector4 normalize(const Vector4& v) { - return v / v.length(); -} - -inline Vector2 abs(const Vector2& v) { - return Vector2(::fabsf(v.x), ::fabsf(v.y)); -} - -inline Vector3 abs(const Vector3& v) { - return Vector3(::fabsf(v.x), ::fabsf(v.y), ::fabsf(v.z)); -} - -inline Vector4 abs(const Vector4& v) { - return Vector4(::fabsf(v.x), ::fabsf(v.y), ::fabsf(v.z), ::fabsf(v.w)); -} - -inline bool all(const Vector2& v) { - return (v.x != 0) && (v.y != 0); -} - -inline bool all(const Vector3& v) { - return (v.x != 0) && (v.y != 0) && (v.z != 0); -} - -inline bool all(const Vector4& v) { - return (v.x != 0) && (v.y != 0) && (v.z != 0) && (v.w != 0); -} - -inline bool any(const Vector2& v) { - return (v.x != 0) || (v.y != 0); -} - -inline bool any(const Vector3& v) { - return (v.x != 0) || (v.y != 0) || (v.z != 0); -} - -inline bool any(const Vector4& v) { - return (v.x != 0) || (v.y != 0) || (v.z != 0) || (v.w != 0); -} - -inline Vector2 clamp(const Vector2& v, const Vector2& a, const Vector2& b) { - return v.clamp(a, b); -} - -inline Vector3 clamp(const Vector3& v, const Vector3& a, const Vector3& b) { - return v.clamp(a, b); -} - -inline Vector4 clamp(const Vector4& v, const Vector4& a, const Vector4& b) { - return v.clamp(a, b); -} - -inline Vector2 lerp(const Vector2& v1, const Vector2& v2, float f) { - return v1.lerp(v2, f); -} - -inline Vector3 lerp(const Vector3& v1, const Vector3& v2, float f) { - return v1.lerp(v2, f); -} - -inline Vector4 lerp(const Vector4& v1, const Vector4& v2, float f) { - return v1.lerp(v2, f); -} - -inline Color1 lerp(const Color1& v1, const Color1& v2, float f) { - return v1.lerp(v2, f); -} - -inline Color3 lerp(const Color3& v1, const Color3& v2, float f) { - return v1.lerp(v2, f); -} - -inline Color4 lerp(const Color4& v1, const Color4& v2, float f) { - return v1.lerp(v2, f); -} - -inline Vector3 cross(const Vector3& v1, const Vector3& v2) { - return v1.cross(v2); -} - -inline double determinant(const Matrix3& m) { - return m.determinant(); -} - -inline double determinant(const Matrix4& m) { - return m.determinant(); -} - -inline Vector2 min(const Vector2& v1, const Vector2& v2) { - return v1.min(v2); -} - -inline Vector3 min(const Vector3& v1, const Vector3& v2) { - return v1.min(v2); -} - -inline Vector4 min(const Vector4& v1, const Vector4& v2) { - return v1.min(v2); -} - -inline Color3 min(const Color3& v1, const Color3& v2) { - return v1.min(v2); -} - -inline Color4 min(const Color4& v1, const Color4& v2) { - return v1.min(v2); -} - -inline Vector2 max(const Vector2& v1, const Vector2& v2) { - return v1.max(v2); -} - -inline Vector3 max(const Vector3& v1, const Vector3& v2) { - return v1.max(v2); -} - -inline Vector4 max(const Vector4& v1, const Vector4& v2) { - return v1.max(v2); -} - -inline Color3 max(const Color3& v1, const Color3& v2) { - return v1.max(v2); -} - -inline Color4 max(const Color4& v1, const Color4& v2) { - return v1.max(v2); -} - -inline Vector2 sign(const Vector2& v) { - return Vector2((float)sign(v.x), (float)sign(v.y)); -} - -inline Vector3 sign(const Vector3& v) { - return Vector3((float)sign(v.x), (float)sign(v.y), (float)sign(v.z)); -} - -inline Vector4 sign(const Vector4& v) { - return Vector4((float)sign(v.x), (float)sign(v.y), (float)sign(v.z), (float)sign(v.w)); -} - -inline float length(float v) { - return ::fabsf(v); -} - -inline float length(const Vector2& v) { - return v.length(); -} - -inline float length(const Vector3& v) { - return v.magnitude(); -} - -inline float length(const Vector4& v) { - return v.length(); -} - -/** - Computes the log of each component. Useful for - inverting the monitor gamma function or simulating - perceptual response. - */ -inline Color3 log(const Color3& c) { - return Color3(::logf(c.r), ::logf(c.g), ::logf(c.b)); -} - -} - -#endif diff --git a/externals/g3dlite/Line.cpp b/externals/g3dlite/Line.cpp deleted file mode 100644 index 195ae7197f2..00000000000 --- a/externals/g3dlite/Line.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/** - @file Line.cpp - - Line class - - @maintainer Morgan McGuire, graphics3d.com - - @created 2001-06-02 - @edited 2006-01-28 - */ - -#include "G3D/Line.h" -#include "G3D/Plane.h" - -namespace G3D { - -Vector3 Line::intersection(const Plane& plane) const { - float d; - Vector3 normal = plane.normal(); - plane.getEquation(normal, d); - float rate = _direction.dot(normal); - - if (rate == 0) { - - return Vector3::inf(); - - } else { - float t = -(d + _point.dot(normal)) / rate; - - return _point + _direction * t; - } -} - - -Line::Line(class BinaryInput& b) { - deserialize(b); -} - - -void Line::serialize(class BinaryOutput& b) const { - _point.serialize(b); - _direction.serialize(b); -} - - -void Line::deserialize(class BinaryInput& b) { - _point.deserialize(b); - _direction.deserialize(b); -} - - -Vector3 Line::closestPoint(const Vector3& pt) const { - float t = _direction.dot(pt - _point); - return _point + _direction * t; -} - - -Vector3 Line::point() const { - return _point; -} - - -Vector3 Line::direction() const { - return _direction; -} - - -Vector3 Line::closestPoint(const Line& B, float& minDist) const { - const Vector3& P1 = _point; - const Vector3& U1 = _direction; - - Vector3 P2 = B.point(); - Vector3 U2 = B.direction(); - - const Vector3& P21 = P2 - P1; - const Vector3& M = U2.cross(U1); - float m2 = M.length(); - - Vector3 R = P21.cross(M) / m2; - - float t1 = R.dot(U2); - - minDist = abs(P21.dot(M)) / sqrt(m2); - - return P1 + t1 * U1; -} - -} - diff --git a/externals/g3dlite/LineSegment.cpp b/externals/g3dlite/LineSegment.cpp deleted file mode 100644 index 754600ad554..00000000000 --- a/externals/g3dlite/LineSegment.cpp +++ /dev/null @@ -1,236 +0,0 @@ -/** - @file LineSegment.cpp - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2003-02-08 - @edited 2008-02-02 - */ - -#include "G3D/platform.h" -#include "G3D/LineSegment.h" -#include "G3D/Sphere.h" -#include "G3D/debug.h" - -namespace G3D { - - -Vector3 LineSegment::closestPoint(const Vector3& p) const { - - // The vector from the end of the capsule to the point in question. - Vector3 v(p - _point); - - // Projection of v onto the line segment scaled by - // the length of direction. - float t = direction.dot(v); - - // Avoid some square roots. Derivation: - // t/direction.length() <= direction.length() - // t <= direction.squaredLength() - - if ((t >= 0) && (t <= direction.squaredMagnitude())) { - - // The point falls within the segment. Normalize direction, - // divide t by the length of direction. - return _point + direction * t / direction.squaredMagnitude(); - - } else { - - // The point does not fall within the segment; see which end is closer. - - // Distance from 0, squared - float d0Squared = v.squaredMagnitude(); - - // Distance from 1, squared - float d1Squared = (v - direction).squaredMagnitude(); - - if (d0Squared < d1Squared) { - - // Point 0 is closer - return _point; - - } else { - - // Point 1 is closer - return _point + direction; - - } - } - -} - -Vector3 LineSegment::point(int i) const { - switch (i) { - case 0: - return _point; - - case 1: - return _point + direction; - - default: - debugAssertM(i == 0 || i == 1, "Argument to point must be 0 or 1"); - return _point; - } -} - - -bool LineSegment::intersectsSolidSphere(const class Sphere& s) const { - return distanceSquared(s.center) <= square(s.radius); -} - - -LineSegment::LineSegment(class BinaryInput& b) { - deserialize(b); -} - - -void LineSegment::serialize(class BinaryOutput& b) const { - _point.serialize(b); - direction.serialize(b); -} - - -void LineSegment::deserialize(class BinaryInput& b) { - _point.deserialize(b); - direction.deserialize(b); -} - - -Vector3 LineSegment::randomPoint() const { - return _point + uniformRandom(0, 1) * direction; -} - - -///////////////////////////////////////////////////////////////////////////////////// - -LineSegment2D LineSegment2D::fromTwoPoints(const Vector2& p0, const Vector2& p1) { - LineSegment2D s; - s.m_origin = p0; - s.m_direction = p1 - p0; - s.m_length = s.m_direction.length(); - return s; -} - - -Vector2 LineSegment2D::point(int i) const { - debugAssert(i == 0 || i == 1); - if (i == 0) { - return m_origin; - } else { - return m_direction + m_origin; - } -} - - -Vector2 LineSegment2D::closestPoint(const Vector2& Q) const { - // Two constants that appear in the result - const Vector2 k1(m_origin - Q); - const Vector2& k2 = m_direction; - - if (fuzzyEq(m_length, 0)) { - // This line segment has no length - return m_origin; - } - - // Time [0, 1] at which we hit the closest point travelling from p0 to p1. - // Derivation can be obtained by minimizing the expression - // ||P0 + (P1 - P0)t - Q||. - const float t = -k1.dot(k2) / (m_length * m_length); - - if (t < 0) { - // Clipped to low end point - return m_origin; - } else if (t > 1) { - // Clipped to high end point - return m_origin + m_direction; - } else { - // Subsitute into the line equation to find - // the point on the segment. - return m_origin + k2 * t; - } -} - - -float LineSegment2D::distance(const Vector2& p) const { - Vector2 closest = closestPoint(p); - return (closest - p).length(); -} - - -float LineSegment2D::length() const { - return m_length; -} - - -Vector2 LineSegment2D::intersection(const LineSegment2D& other) const { - - if ((m_origin == other.m_origin) || - (m_origin == other.m_origin + other.m_direction)) { - return m_origin; - } - - if (m_origin + m_direction == other.m_origin) { - return other.m_origin; - } - - // Note: Now that we've checked the endpoints, all other parallel lines can now be assumed - // to not intersect (within numerical precision) - - Vector2 dir1 = m_direction; - Vector2 dir2 = other.m_direction; - Vector2 origin1 = m_origin; - Vector2 origin2 = other.m_origin; - - if (dir1.x == 0) { - // Avoid an upcoming divide by zero - dir1 = dir1.yx(); - dir2 = dir2.yx(); - origin1 = origin1.yx(); - origin2 = origin2.yx(); - } - - // t1 = ((other.m_origin.x - m_origin.x) + other.m_direction.x * t2) / m_direction.x - // - // ((other.m_origin.x - m_origin.x) + other.m_direction.x * t2) * m_direction.y / m_direction.x = - // (other.m_origin.y - m_origin.y) + other.m_direction.y * t2 - // - // m = m_direction.y / m_direction.x - // d = other.m_origin - m_origin - // - // (d.x + other.m_direction.x * t2) * m = d.y + other.m_direction.y * t2 - // - // d.x * m + other.m_direction.x * m * t2 = d.y + other.m_direction.y * t2 - // - // d.x * m - d.y = (other.m_direction.y - other.m_direction.x * m) * t2 - // - // (d.x * m - d.y) / (other.m_direction.y - other.m_direction.x * m) = t2 - // - - Vector2 d = origin2 - origin1; - float m = dir1.y / dir1.x; - - float t2 = (d.x * m - d.y) / (dir2.y - dir2.x * m); - if (! isFinite(t2)) { - // Parallel lines: no intersection - return Vector2::inf(); - } - - if ((t2 < 0.0f) || (t2 > 1.0f)) { - // Intersection occurs past the end of the line segments - return Vector2::inf(); - } - - float t1 = (d.x + dir2.x * t2) / dir1.x; - if ((t1 < 0.0f) || (t1 > 1.0f)) { - // Intersection occurs past the end of the line segments - return Vector2::inf(); - } - - // Return the intersection point (computed from non-transposed - // variables even if we flipped above) - return m_origin + m_direction * t1; - -} - -} - diff --git a/externals/g3dlite/Log.cpp b/externals/g3dlite/Log.cpp deleted file mode 100644 index 07614fcf563..00000000000 --- a/externals/g3dlite/Log.cpp +++ /dev/null @@ -1,146 +0,0 @@ -/** - @file Log.cpp - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - @created 2001-08-04 - @edited 2009-01-15 - */ - -#include "G3D/platform.h" -#include "G3D/Log.h" -#include "G3D/format.h" -#include "G3D/Array.h" -#include "G3D/fileutils.h" -#include - -#ifdef G3D_WIN32 - #include -#else - #include -#endif - -namespace G3D { - -void logPrintf(const char* fmt, ...) { - va_list arg_list; - va_start(arg_list, fmt); - Log::common()->vprintf(fmt, arg_list); - va_end(arg_list); -} - - -void logLazyPrintf(const char* fmt, ...) { - va_list arg_list; - va_start(arg_list, fmt); - Log::common()->lazyvprintf(fmt, arg_list); - va_end(arg_list); -} - -Log* Log::commonLog = NULL; - -Log::Log(const std::string& filename, int stripFromStackBottom) : - stripFromStackBottom(stripFromStackBottom) { - - this->filename = filename; - - logFile = fopen(filename.c_str(), "w"); - - if (logFile == NULL) { - std::string drive, base, ext; - Array path; - parseFilename(filename, drive, path, base, ext); - std::string logName = base + ((ext != "") ? ("." + ext) : ""); - - // Write time is greater than 1ms. This may be a network drive.... try another file. - #ifdef G3D_WIN32 - logName = std::string(std::getenv("TEMP")) + logName; - #else - logName = std::string("/tmp/") + logName; - #endif - - logFile = fopen(logName.c_str(), "w"); - } - - // Use a large buffer (although we flush in logPrintf) - setvbuf(logFile, NULL, _IOFBF, 2048); - - fprintf(logFile, "Application Log\n"); - time_t t; - time(&t); - fprintf(logFile, "Start: %s\n", ctime(&t)); - fflush(logFile); - - if (commonLog == NULL) { - commonLog = this; - } -} - - -Log::~Log() { - section("Shutdown"); - println("Closing log file"); - - // Make sure we don't leave a dangling pointer - if (Log::commonLog == this) { - Log::commonLog = NULL; - } - - fclose(logFile); -} - - -FILE* Log::getFile() const { - return logFile; -} - - -Log* Log::common() { - if (commonLog == NULL) { - commonLog = new Log(); - } - return commonLog; -} - - -std::string Log::getCommonLogFilename() { - return common()->filename; -} - - -void Log::section(const std::string& s) { - fprintf(logFile, "_____________________________________________________\n"); - fprintf(logFile, "\n ### %s ###\n\n", s.c_str()); -} - - -void __cdecl Log::printf(const char* fmt, ...) { - va_list arg_list; - va_start(arg_list, fmt); - print(vformat(fmt, arg_list)); - va_end(arg_list); -} - - -void __cdecl Log::vprintf(const char* fmt, va_list argPtr) { - vfprintf(logFile, fmt, argPtr); - fflush(logFile); -} - - -void __cdecl Log::lazyvprintf(const char* fmt, va_list argPtr) { - vfprintf(logFile, fmt, argPtr); -} - - -void Log::print(const std::string& s) { - fprintf(logFile, "%s", s.c_str()); - fflush(logFile); -} - - -void Log::println(const std::string& s) { - fprintf(logFile, "%s\n", s.c_str()); - fflush(logFile); -} - -} diff --git a/externals/g3dlite/Matrix3.cpp b/externals/g3dlite/Matrix3.cpp deleted file mode 100644 index b32d938f0f9..00000000000 --- a/externals/g3dlite/Matrix3.cpp +++ /dev/null @@ -1,1927 +0,0 @@ -/** - @file Matrix3.cpp - - 3x3 matrix class - - @author Morgan McGuire, graphics3d.com - - @created 2001-06-02 - @edited 2009-11-15 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. -*/ - -#include "G3D/platform.h" -#include -#include -#include "G3D/Matrix3.h" -#include "G3D/g3dmath.h" -#include "G3D/BinaryInput.h" -#include "G3D/BinaryOutput.h" -#include "G3D/Quat.h" -#include "G3D/Any.h" - -namespace G3D { - -const float Matrix3::EPSILON = 1e-06f; - -Matrix3::Matrix3(const Any& any) { - any.verifyName("Matrix3"); - any.verifyType(Any::ARRAY); - any.verifySize(9); - - for (int r = 0; r < 3; ++r) { - for (int c = 0; c < 3; ++c) { - elt[r][c] = any[r * 3 + c]; - } - } -} - - -Matrix3::operator Any() const { - Any any(Any::ARRAY, "Matrix3"); - any.resize(9); - for (int r = 0; r < 3; ++r) { - for (int c = 0; c < 3; ++c) { - any[r * 3 + c] = elt[r][c]; - } - } - - return any; -} - -const Matrix3& Matrix3::zero() { - static Matrix3 m(0, 0, 0, 0, 0, 0, 0, 0, 0); - return m; -} - -const Matrix3& Matrix3::identity() { - static Matrix3 m(1, 0, 0, 0, 1, 0, 0, 0, 1); - return m; -} - - -const float Matrix3::ms_fSvdEpsilon = 1e-04f; -const int Matrix3::ms_iSvdMaxIterations = 32; - -Matrix3::Matrix3(BinaryInput& b) { - deserialize(b); -} - -bool Matrix3::fuzzyEq(const Matrix3& b) const { - for (int r = 0; r < 3; ++r) { - for (int c = 0; c < 3; ++c) { - if (! G3D::fuzzyEq(elt[r][c], b[r][c])) { - return false; - } - } - } - return true; -} - - -bool Matrix3::isRightHanded() const{ - - const Vector3& X = column(0); - const Vector3& Y = column(1); - const Vector3& Z = column(2); - - const Vector3& W = X.cross(Y); - - return W.dot(Z) > 0.0f; -} - - -bool Matrix3::isOrthonormal() const { - const Vector3& X = column(0); - const Vector3& Y = column(1); - const Vector3& Z = column(2); - - return - (G3D::fuzzyEq(X.dot(Y), 0.0f) && - G3D::fuzzyEq(Y.dot(Z), 0.0f) && - G3D::fuzzyEq(X.dot(Z), 0.0f) && - G3D::fuzzyEq(X.squaredMagnitude(), 1.0f) && - G3D::fuzzyEq(Y.squaredMagnitude(), 1.0f) && - G3D::fuzzyEq(Z.squaredMagnitude(), 1.0f)); -} - -//---------------------------------------------------------------------------- -Matrix3::Matrix3(const Quat& _q) { - // Implementation from Watt and Watt, pg 362 - // See also http://www.flipcode.com/documents/matrfaq.html#Q54 - Quat q = _q; - q.unitize(); - float xx = 2.0f * q.x * q.x; - float xy = 2.0f * q.x * q.y; - float xz = 2.0f * q.x * q.z; - float xw = 2.0f * q.x * q.w; - - float yy = 2.0f * q.y * q.y; - float yz = 2.0f * q.y * q.z; - float yw = 2.0f * q.y * q.w; - - float zz = 2.0f * q.z * q.z; - float zw = 2.0f * q.z * q.w; - - set(1.0f - yy - zz, xy - zw, xz + yw, - xy + zw, 1.0f - xx - zz, yz - xw, - xz - yw, yz + xw, 1.0f - xx - yy); -} - -//---------------------------------------------------------------------------- - -Matrix3::Matrix3 (const float aafEntry[3][3]) { - memcpy(elt, aafEntry, 9*sizeof(float)); -} - -//---------------------------------------------------------------------------- -Matrix3::Matrix3 (const Matrix3& rkMatrix) { - memcpy(elt, rkMatrix.elt, 9*sizeof(float)); -} - -//---------------------------------------------------------------------------- -Matrix3::Matrix3( - float fEntry00, float fEntry01, float fEntry02, - float fEntry10, float fEntry11, float fEntry12, - float fEntry20, float fEntry21, float fEntry22) { - set(fEntry00, fEntry01, fEntry02, - fEntry10, fEntry11, fEntry12, - fEntry20, fEntry21, fEntry22); -} - -void Matrix3::set( - float fEntry00, float fEntry01, float fEntry02, - float fEntry10, float fEntry11, float fEntry12, - float fEntry20, float fEntry21, float fEntry22) { - - elt[0][0] = fEntry00; - elt[0][1] = fEntry01; - elt[0][2] = fEntry02; - elt[1][0] = fEntry10; - elt[1][1] = fEntry11; - elt[1][2] = fEntry12; - elt[2][0] = fEntry20; - elt[2][1] = fEntry21; - elt[2][2] = fEntry22; -} - - -void Matrix3::deserialize(BinaryInput& b) { - int r,c; - for (c = 0; c < 3; ++c) { - for (r = 0; r < 3; ++r) { - elt[r][c] = b.readFloat32(); - } - } -} - - -void Matrix3::serialize(BinaryOutput& b) const { - int r,c; - for (c = 0; c < 3; ++c) { - for (r = 0; r < 3; ++r) { - b.writeFloat32(elt[r][c]); - } - } -} - - -//---------------------------------------------------------------------------- -Vector3 Matrix3::column (int iCol) const { - assert((0 <= iCol) && (iCol < 3)); - return Vector3(elt[0][iCol], elt[1][iCol], - elt[2][iCol]); -} - - -const Vector3& Matrix3::row (int iRow) const { - assert((0 <= iRow) && (iRow < 3)); - return *reinterpret_cast(elt[iRow]); -} - - -void Matrix3::setColumn(int iCol, const Vector3 &vector) { - debugAssert((iCol >= 0) && (iCol < 3)); - elt[0][iCol] = vector.x; - elt[1][iCol] = vector.y; - elt[2][iCol] = vector.z; -} - - -void Matrix3::setRow(int iRow, const Vector3 &vector) { - debugAssert((iRow >= 0) && (iRow < 3)); - elt[iRow][0] = vector.x; - elt[iRow][1] = vector.y; - elt[iRow][2] = vector.z; -} - - -//---------------------------------------------------------------------------- -bool Matrix3::operator== (const Matrix3& rkMatrix) const { - for (int iRow = 0; iRow < 3; iRow++) { - for (int iCol = 0; iCol < 3; iCol++) { - if ( elt[iRow][iCol] != rkMatrix.elt[iRow][iCol] ) - return false; - } - } - - return true; -} - -//---------------------------------------------------------------------------- -bool Matrix3::operator!= (const Matrix3& rkMatrix) const { - return !operator==(rkMatrix); -} - -//---------------------------------------------------------------------------- -Matrix3 Matrix3::operator+ (const Matrix3& rkMatrix) const { - Matrix3 kSum; - - for (int iRow = 0; iRow < 3; iRow++) { - for (int iCol = 0; iCol < 3; iCol++) { - kSum.elt[iRow][iCol] = elt[iRow][iCol] + - rkMatrix.elt[iRow][iCol]; - } - } - - return kSum; -} - -//---------------------------------------------------------------------------- -Matrix3 Matrix3::operator- (const Matrix3& rkMatrix) const { - Matrix3 kDiff; - - for (int iRow = 0; iRow < 3; iRow++) { - for (int iCol = 0; iCol < 3; iCol++) { - kDiff.elt[iRow][iCol] = elt[iRow][iCol] - - rkMatrix.elt[iRow][iCol]; - } - } - - return kDiff; -} - -//---------------------------------------------------------------------------- -Matrix3 Matrix3::operator* (const Matrix3& rkMatrix) const { - Matrix3 kProd; - - for (int iRow = 0; iRow < 3; iRow++) { - for (int iCol = 0; iCol < 3; iCol++) { - kProd.elt[iRow][iCol] = - elt[iRow][0] * rkMatrix.elt[0][iCol] + - elt[iRow][1] * rkMatrix.elt[1][iCol] + - elt[iRow][2] * rkMatrix.elt[2][iCol]; - } - } - - return kProd; -} - -Matrix3& Matrix3::operator+= (const Matrix3& rkMatrix) { - for (int iRow = 0; iRow < 3; iRow++) { - for (int iCol = 0; iCol < 3; iCol++) { - elt[iRow][iCol] = elt[iRow][iCol] + rkMatrix.elt[iRow][iCol]; - } - } - - return *this; -} - -Matrix3& Matrix3::operator-= (const Matrix3& rkMatrix) { - for (int iRow = 0; iRow < 3; iRow++) { - for (int iCol = 0; iCol < 3; iCol++) { - elt[iRow][iCol] = elt[iRow][iCol] - rkMatrix.elt[iRow][iCol]; - } - } - - return *this; -} - -Matrix3& Matrix3::operator*= (const Matrix3& rkMatrix) { - Matrix3 mulMat; - for (int iRow = 0; iRow < 3; iRow++) { - for (int iCol = 0; iCol < 3; iCol++) { - mulMat.elt[iRow][iCol] = - elt[iRow][0] * rkMatrix.elt[0][iCol] + - elt[iRow][1] * rkMatrix.elt[1][iCol] + - elt[iRow][2] * rkMatrix.elt[2][iCol]; - } - } - - *this = mulMat; - return *this; -} - -//---------------------------------------------------------------------------- -Matrix3 Matrix3::operator- () const { - Matrix3 kNeg; - - for (int iRow = 0; iRow < 3; iRow++) { - for (int iCol = 0; iCol < 3; iCol++) { - kNeg[iRow][iCol] = -elt[iRow][iCol]; - } - } - - return kNeg; -} - -//---------------------------------------------------------------------------- -Matrix3 Matrix3::operator* (float fScalar) const { - Matrix3 kProd; - - for (int iRow = 0; iRow < 3; iRow++) { - for (int iCol = 0; iCol < 3; iCol++) { - kProd[iRow][iCol] = fScalar * elt[iRow][iCol]; - } - } - - return kProd; -} - -Matrix3& Matrix3::operator/= (float fScalar) { - return *this *= (1.0f / fScalar); -} - -Matrix3& Matrix3::operator*= (float fScalar) { - - for (int iRow = 0; iRow < 3; iRow++) { - for (int iCol = 0; iCol < 3; iCol++) { - elt[iRow][iCol] *= fScalar; - } - } - - return *this; -} - -//---------------------------------------------------------------------------- -Matrix3 operator* (double fScalar, const Matrix3& rkMatrix) { - Matrix3 kProd; - - for (int iRow = 0; iRow < 3; iRow++) { - for (int iCol = 0; iCol < 3; iCol++) { - kProd[iRow][iCol] = fScalar * rkMatrix.elt[iRow][iCol]; - } - } - - return kProd; -} - -Matrix3 operator* (float fScalar, const Matrix3& rkMatrix) { - return (double)fScalar * rkMatrix; -} - - -Matrix3 operator* (int fScalar, const Matrix3& rkMatrix) { - return (double)fScalar * rkMatrix; -} -//---------------------------------------------------------------------------- -Matrix3 Matrix3::transpose () const { - Matrix3 kTranspose; - - for (int iRow = 0; iRow < 3; iRow++) { - for (int iCol = 0; iCol < 3; iCol++) { - kTranspose[iRow][iCol] = elt[iCol][iRow]; - } - } - - return kTranspose; -} - -//---------------------------------------------------------------------------- -bool Matrix3::inverse (Matrix3& rkInverse, float fTolerance) const { - // Invert a 3x3 using cofactors. This is about 8 times faster than - // the Numerical Recipes code which uses Gaussian elimination. - - rkInverse[0][0] = elt[1][1] * elt[2][2] - - elt[1][2] * elt[2][1]; - rkInverse[0][1] = elt[0][2] * elt[2][1] - - elt[0][1] * elt[2][2]; - rkInverse[0][2] = elt[0][1] * elt[1][2] - - elt[0][2] * elt[1][1]; - rkInverse[1][0] = elt[1][2] * elt[2][0] - - elt[1][0] * elt[2][2]; - rkInverse[1][1] = elt[0][0] * elt[2][2] - - elt[0][2] * elt[2][0]; - rkInverse[1][2] = elt[0][2] * elt[1][0] - - elt[0][0] * elt[1][2]; - rkInverse[2][0] = elt[1][0] * elt[2][1] - - elt[1][1] * elt[2][0]; - rkInverse[2][1] = elt[0][1] * elt[2][0] - - elt[0][0] * elt[2][1]; - rkInverse[2][2] = elt[0][0] * elt[1][1] - - elt[0][1] * elt[1][0]; - - float fDet = - elt[0][0] * rkInverse[0][0] + - elt[0][1] * rkInverse[1][0] + - elt[0][2] * rkInverse[2][0]; - - if ( G3D::abs(fDet) <= fTolerance ) - return false; - - float fInvDet = 1.0 / fDet; - - for (int iRow = 0; iRow < 3; iRow++) { - for (int iCol = 0; iCol < 3; iCol++) - rkInverse[iRow][iCol] *= fInvDet; - } - - return true; -} - -//---------------------------------------------------------------------------- -Matrix3 Matrix3::inverse (float fTolerance) const { - Matrix3 kInverse = Matrix3::zero(); - inverse(kInverse, fTolerance); - return kInverse; -} - -//---------------------------------------------------------------------------- -float Matrix3::determinant () const { - float fCofactor00 = elt[1][1] * elt[2][2] - - elt[1][2] * elt[2][1]; - float fCofactor10 = elt[1][2] * elt[2][0] - - elt[1][0] * elt[2][2]; - float fCofactor20 = elt[1][0] * elt[2][1] - - elt[1][1] * elt[2][0]; - - float fDet = - elt[0][0] * fCofactor00 + - elt[0][1] * fCofactor10 + - elt[0][2] * fCofactor20; - - return fDet; -} - -//---------------------------------------------------------------------------- -void Matrix3::bidiagonalize (Matrix3& kA, Matrix3& kL, - Matrix3& kR) { - float afV[3], afW[3]; - float fLength, fSign, fT1, fInvT1, fT2; - bool bIdentity; - - // map first column to (*,0,0) - fLength = sqrt(kA[0][0] * kA[0][0] + kA[1][0] * kA[1][0] + - kA[2][0] * kA[2][0]); - - if ( fLength > 0.0 ) { - fSign = (kA[0][0] > 0.0 ? 1.0 : -1.0); - fT1 = kA[0][0] + fSign * fLength; - fInvT1 = 1.0 / fT1; - afV[1] = kA[1][0] * fInvT1; - afV[2] = kA[2][0] * fInvT1; - - fT2 = -2.0 / (1.0 + afV[1] * afV[1] + afV[2] * afV[2]); - afW[0] = fT2 * (kA[0][0] + kA[1][0] * afV[1] + kA[2][0] * afV[2]); - afW[1] = fT2 * (kA[0][1] + kA[1][1] * afV[1] + kA[2][1] * afV[2]); - afW[2] = fT2 * (kA[0][2] + kA[1][2] * afV[1] + kA[2][2] * afV[2]); - kA[0][0] += afW[0]; - kA[0][1] += afW[1]; - kA[0][2] += afW[2]; - kA[1][1] += afV[1] * afW[1]; - kA[1][2] += afV[1] * afW[2]; - kA[2][1] += afV[2] * afW[1]; - kA[2][2] += afV[2] * afW[2]; - - kL[0][0] = 1.0 + fT2; - kL[0][1] = kL[1][0] = fT2 * afV[1]; - kL[0][2] = kL[2][0] = fT2 * afV[2]; - kL[1][1] = 1.0 + fT2 * afV[1] * afV[1]; - kL[1][2] = kL[2][1] = fT2 * afV[1] * afV[2]; - kL[2][2] = 1.0 + fT2 * afV[2] * afV[2]; - bIdentity = false; - } else { - kL = Matrix3::identity(); - bIdentity = true; - } - - // map first row to (*,*,0) - fLength = sqrt(kA[0][1] * kA[0][1] + kA[0][2] * kA[0][2]); - - if ( fLength > 0.0 ) { - fSign = (kA[0][1] > 0.0 ? 1.0 : -1.0); - fT1 = kA[0][1] + fSign * fLength; - afV[2] = kA[0][2] / fT1; - - fT2 = -2.0 / (1.0 + afV[2] * afV[2]); - afW[0] = fT2 * (kA[0][1] + kA[0][2] * afV[2]); - afW[1] = fT2 * (kA[1][1] + kA[1][2] * afV[2]); - afW[2] = fT2 * (kA[2][1] + kA[2][2] * afV[2]); - kA[0][1] += afW[0]; - kA[1][1] += afW[1]; - kA[1][2] += afW[1] * afV[2]; - kA[2][1] += afW[2]; - kA[2][2] += afW[2] * afV[2]; - - kR[0][0] = 1.0; - kR[0][1] = kR[1][0] = 0.0; - kR[0][2] = kR[2][0] = 0.0; - kR[1][1] = 1.0 + fT2; - kR[1][2] = kR[2][1] = fT2 * afV[2]; - kR[2][2] = 1.0 + fT2 * afV[2] * afV[2]; - } else { - kR = Matrix3::identity(); - } - - // map second column to (*,*,0) - fLength = sqrt(kA[1][1] * kA[1][1] + kA[2][1] * kA[2][1]); - - if ( fLength > 0.0 ) { - fSign = (kA[1][1] > 0.0 ? 1.0 : -1.0); - fT1 = kA[1][1] + fSign * fLength; - afV[2] = kA[2][1] / fT1; - - fT2 = -2.0 / (1.0 + afV[2] * afV[2]); - afW[1] = fT2 * (kA[1][1] + kA[2][1] * afV[2]); - afW[2] = fT2 * (kA[1][2] + kA[2][2] * afV[2]); - kA[1][1] += afW[1]; - kA[1][2] += afW[2]; - kA[2][2] += afV[2] * afW[2]; - - float fA = 1.0 + fT2; - float fB = fT2 * afV[2]; - float fC = 1.0 + fB * afV[2]; - - if ( bIdentity ) { - kL[0][0] = 1.0; - kL[0][1] = kL[1][0] = 0.0; - kL[0][2] = kL[2][0] = 0.0; - kL[1][1] = fA; - kL[1][2] = kL[2][1] = fB; - kL[2][2] = fC; - } else { - for (int iRow = 0; iRow < 3; iRow++) { - float fTmp0 = kL[iRow][1]; - float fTmp1 = kL[iRow][2]; - kL[iRow][1] = fA * fTmp0 + fB * fTmp1; - kL[iRow][2] = fB * fTmp0 + fC * fTmp1; - } - } - } -} - -//---------------------------------------------------------------------------- -void Matrix3::golubKahanStep (Matrix3& kA, Matrix3& kL, - Matrix3& kR) { - float fT11 = kA[0][1] * kA[0][1] + kA[1][1] * kA[1][1]; - float fT22 = kA[1][2] * kA[1][2] + kA[2][2] * kA[2][2]; - float fT12 = kA[1][1] * kA[1][2]; - float fTrace = fT11 + fT22; - float fDiff = fT11 - fT22; - float fDiscr = sqrt(fDiff * fDiff + 4.0 * fT12 * fT12); - float fRoot1 = 0.5 * (fTrace + fDiscr); - float fRoot2 = 0.5 * (fTrace - fDiscr); - - // adjust right - float fY = kA[0][0] - (G3D::abs(fRoot1 - fT22) <= - G3D::abs(fRoot2 - fT22) ? fRoot1 : fRoot2); - float fZ = kA[0][1]; - float fInvLength = 1.0 / sqrt(fY * fY + fZ * fZ); - float fSin = fZ * fInvLength; - float fCos = -fY * fInvLength; - - float fTmp0 = kA[0][0]; - float fTmp1 = kA[0][1]; - kA[0][0] = fCos * fTmp0 - fSin * fTmp1; - kA[0][1] = fSin * fTmp0 + fCos * fTmp1; - kA[1][0] = -fSin * kA[1][1]; - kA[1][1] *= fCos; - - int iRow; - - for (iRow = 0; iRow < 3; iRow++) { - fTmp0 = kR[0][iRow]; - fTmp1 = kR[1][iRow]; - kR[0][iRow] = fCos * fTmp0 - fSin * fTmp1; - kR[1][iRow] = fSin * fTmp0 + fCos * fTmp1; - } - - // adjust left - fY = kA[0][0]; - - fZ = kA[1][0]; - - fInvLength = 1.0 / sqrt(fY * fY + fZ * fZ); - - fSin = fZ * fInvLength; - - fCos = -fY * fInvLength; - - kA[0][0] = fCos * kA[0][0] - fSin * kA[1][0]; - - fTmp0 = kA[0][1]; - - fTmp1 = kA[1][1]; - - kA[0][1] = fCos * fTmp0 - fSin * fTmp1; - - kA[1][1] = fSin * fTmp0 + fCos * fTmp1; - - kA[0][2] = -fSin * kA[1][2]; - - kA[1][2] *= fCos; - - int iCol; - - for (iCol = 0; iCol < 3; iCol++) { - fTmp0 = kL[iCol][0]; - fTmp1 = kL[iCol][1]; - kL[iCol][0] = fCos * fTmp0 - fSin * fTmp1; - kL[iCol][1] = fSin * fTmp0 + fCos * fTmp1; - } - - // adjust right - fY = kA[0][1]; - - fZ = kA[0][2]; - - fInvLength = 1.0 / sqrt(fY * fY + fZ * fZ); - - fSin = fZ * fInvLength; - - fCos = -fY * fInvLength; - - kA[0][1] = fCos * kA[0][1] - fSin * kA[0][2]; - - fTmp0 = kA[1][1]; - - fTmp1 = kA[1][2]; - - kA[1][1] = fCos * fTmp0 - fSin * fTmp1; - - kA[1][2] = fSin * fTmp0 + fCos * fTmp1; - - kA[2][1] = -fSin * kA[2][2]; - - kA[2][2] *= fCos; - - for (iRow = 0; iRow < 3; iRow++) { - fTmp0 = kR[1][iRow]; - fTmp1 = kR[2][iRow]; - kR[1][iRow] = fCos * fTmp0 - fSin * fTmp1; - kR[2][iRow] = fSin * fTmp0 + fCos * fTmp1; - } - - // adjust left - fY = kA[1][1]; - - fZ = kA[2][1]; - - fInvLength = 1.0 / sqrt(fY * fY + fZ * fZ); - - fSin = fZ * fInvLength; - - fCos = -fY * fInvLength; - - kA[1][1] = fCos * kA[1][1] - fSin * kA[2][1]; - - fTmp0 = kA[1][2]; - - fTmp1 = kA[2][2]; - - kA[1][2] = fCos * fTmp0 - fSin * fTmp1; - - kA[2][2] = fSin * fTmp0 + fCos * fTmp1; - - for (iCol = 0; iCol < 3; iCol++) { - fTmp0 = kL[iCol][1]; - fTmp1 = kL[iCol][2]; - kL[iCol][1] = fCos * fTmp0 - fSin * fTmp1; - kL[iCol][2] = fSin * fTmp0 + fCos * fTmp1; - } -} - -//---------------------------------------------------------------------------- -void Matrix3::singularValueDecomposition (Matrix3& kL, Vector3& kS, - Matrix3& kR) const { - int iRow, iCol; - - Matrix3 kA = *this; - bidiagonalize(kA, kL, kR); - - for (int i = 0; i < ms_iSvdMaxIterations; i++) { - float fTmp, fTmp0, fTmp1; - float fSin0, fCos0, fTan0; - float fSin1, fCos1, fTan1; - - bool bTest1 = (G3D::abs(kA[0][1]) <= - ms_fSvdEpsilon * (G3D::abs(kA[0][0]) + G3D::abs(kA[1][1]))); - bool bTest2 = (G3D::abs(kA[1][2]) <= - ms_fSvdEpsilon * (G3D::abs(kA[1][1]) + G3D::abs(kA[2][2]))); - - if ( bTest1 ) { - if ( bTest2 ) { - kS[0] = kA[0][0]; - kS[1] = kA[1][1]; - kS[2] = kA[2][2]; - break; - } else { - // 2x2 closed form factorization - fTmp = (kA[1][1] * kA[1][1] - kA[2][2] * kA[2][2] + - kA[1][2] * kA[1][2]) / (kA[1][2] * kA[2][2]); - fTan0 = 0.5 * (fTmp + sqrt(fTmp * fTmp + 4.0)); - fCos0 = 1.0 / sqrt(1.0 + fTan0 * fTan0); - fSin0 = fTan0 * fCos0; - - for (iCol = 0; iCol < 3; iCol++) { - fTmp0 = kL[iCol][1]; - fTmp1 = kL[iCol][2]; - kL[iCol][1] = fCos0 * fTmp0 - fSin0 * fTmp1; - kL[iCol][2] = fSin0 * fTmp0 + fCos0 * fTmp1; - } - - fTan1 = (kA[1][2] - kA[2][2] * fTan0) / kA[1][1]; - fCos1 = 1.0 / sqrt(1.0 + fTan1 * fTan1); - fSin1 = -fTan1 * fCos1; - - for (iRow = 0; iRow < 3; iRow++) { - fTmp0 = kR[1][iRow]; - fTmp1 = kR[2][iRow]; - kR[1][iRow] = fCos1 * fTmp0 - fSin1 * fTmp1; - kR[2][iRow] = fSin1 * fTmp0 + fCos1 * fTmp1; - } - - kS[0] = kA[0][0]; - kS[1] = fCos0 * fCos1 * kA[1][1] - - fSin1 * (fCos0 * kA[1][2] - fSin0 * kA[2][2]); - kS[2] = fSin0 * fSin1 * kA[1][1] + - fCos1 * (fSin0 * kA[1][2] + fCos0 * kA[2][2]); - break; - } - } else { - if ( bTest2 ) { - // 2x2 closed form factorization - fTmp = (kA[0][0] * kA[0][0] + kA[1][1] * kA[1][1] - - kA[0][1] * kA[0][1]) / (kA[0][1] * kA[1][1]); - fTan0 = 0.5 * ( -fTmp + sqrt(fTmp * fTmp + 4.0)); - fCos0 = 1.0 / sqrt(1.0 + fTan0 * fTan0); - fSin0 = fTan0 * fCos0; - - for (iCol = 0; iCol < 3; iCol++) { - fTmp0 = kL[iCol][0]; - fTmp1 = kL[iCol][1]; - kL[iCol][0] = fCos0 * fTmp0 - fSin0 * fTmp1; - kL[iCol][1] = fSin0 * fTmp0 + fCos0 * fTmp1; - } - - fTan1 = (kA[0][1] - kA[1][1] * fTan0) / kA[0][0]; - fCos1 = 1.0 / sqrt(1.0 + fTan1 * fTan1); - fSin1 = -fTan1 * fCos1; - - for (iRow = 0; iRow < 3; iRow++) { - fTmp0 = kR[0][iRow]; - fTmp1 = kR[1][iRow]; - kR[0][iRow] = fCos1 * fTmp0 - fSin1 * fTmp1; - kR[1][iRow] = fSin1 * fTmp0 + fCos1 * fTmp1; - } - - kS[0] = fCos0 * fCos1 * kA[0][0] - - fSin1 * (fCos0 * kA[0][1] - fSin0 * kA[1][1]); - kS[1] = fSin0 * fSin1 * kA[0][0] + - fCos1 * (fSin0 * kA[0][1] + fCos0 * kA[1][1]); - kS[2] = kA[2][2]; - break; - } else { - golubKahanStep(kA, kL, kR); - } - } - } - - // positize diagonal - for (iRow = 0; iRow < 3; iRow++) { - if ( kS[iRow] < 0.0 ) { - kS[iRow] = -kS[iRow]; - - for (iCol = 0; iCol < 3; iCol++) - kR[iRow][iCol] = -kR[iRow][iCol]; - } - } -} - -//---------------------------------------------------------------------------- -void Matrix3::singularValueComposition (const Matrix3& kL, - const Vector3& kS, const Matrix3& kR) { - int iRow, iCol; - Matrix3 kTmp; - - // product S*R - for (iRow = 0; iRow < 3; iRow++) { - for (iCol = 0; iCol < 3; iCol++) - kTmp[iRow][iCol] = kS[iRow] * kR[iRow][iCol]; - } - - // product L*S*R - for (iRow = 0; iRow < 3; iRow++) { - for (iCol = 0; iCol < 3; iCol++) { - elt[iRow][iCol] = 0.0; - - for (int iMid = 0; iMid < 3; iMid++) - elt[iRow][iCol] += kL[iRow][iMid] * kTmp[iMid][iCol]; - } - } -} - -//---------------------------------------------------------------------------- -void Matrix3::orthonormalize () { - // Algorithm uses Gram-Schmidt orthogonalization. If 'this' matrix is - // M = [m0|m1|m2], then orthonormal output matrix is Q = [q0|q1|q2], - // - // q0 = m0/|m0| - // q1 = (m1-(q0*m1)q0)/|m1-(q0*m1)q0| - // q2 = (m2-(q0*m2)q0-(q1*m2)q1)/|m2-(q0*m2)q0-(q1*m2)q1| - // - // where |V| indicates length of vector V and A*B indicates dot - // product of vectors A and B. - - // compute q0 - float fInvLength = 1.0 / sqrt(elt[0][0] * elt[0][0] - + elt[1][0] * elt[1][0] + - elt[2][0] * elt[2][0]); - - elt[0][0] *= fInvLength; - elt[1][0] *= fInvLength; - elt[2][0] *= fInvLength; - - // compute q1 - float fDot0 = - elt[0][0] * elt[0][1] + - elt[1][0] * elt[1][1] + - elt[2][0] * elt[2][1]; - - elt[0][1] -= fDot0 * elt[0][0]; - elt[1][1] -= fDot0 * elt[1][0]; - elt[2][1] -= fDot0 * elt[2][0]; - - fInvLength = 1.0 / sqrt(elt[0][1] * elt[0][1] + - elt[1][1] * elt[1][1] + - elt[2][1] * elt[2][1]); - - elt[0][1] *= fInvLength; - elt[1][1] *= fInvLength; - elt[2][1] *= fInvLength; - - // compute q2 - float fDot1 = - elt[0][1] * elt[0][2] + - elt[1][1] * elt[1][2] + - elt[2][1] * elt[2][2]; - - fDot0 = - elt[0][0] * elt[0][2] + - elt[1][0] * elt[1][2] + - elt[2][0] * elt[2][2]; - - elt[0][2] -= fDot0 * elt[0][0] + fDot1 * elt[0][1]; - elt[1][2] -= fDot0 * elt[1][0] + fDot1 * elt[1][1]; - elt[2][2] -= fDot0 * elt[2][0] + fDot1 * elt[2][1]; - - fInvLength = 1.0 / sqrt(elt[0][2] * elt[0][2] + - elt[1][2] * elt[1][2] + - elt[2][2] * elt[2][2]); - - elt[0][2] *= fInvLength; - elt[1][2] *= fInvLength; - elt[2][2] *= fInvLength; -} - -//---------------------------------------------------------------------------- -void Matrix3::qDUDecomposition (Matrix3& kQ, - Vector3& kD, Vector3& kU) const { - // Factor M = QR = QDU where Q is orthogonal, D is diagonal, - // and U is upper triangular with ones on its diagonal. Algorithm uses - // Gram-Schmidt orthogonalization (the QR algorithm). - // - // If M = [ m0 | m1 | m2 ] and Q = [ q0 | q1 | q2 ], then - // - // q0 = m0/|m0| - // q1 = (m1-(q0*m1)q0)/|m1-(q0*m1)q0| - // q2 = (m2-(q0*m2)q0-(q1*m2)q1)/|m2-(q0*m2)q0-(q1*m2)q1| - // - // where |V| indicates length of vector V and A*B indicates dot - // product of vectors A and B. The matrix R has entries - // - // r00 = q0*m0 r01 = q0*m1 r02 = q0*m2 - // r10 = 0 r11 = q1*m1 r12 = q1*m2 - // r20 = 0 r21 = 0 r22 = q2*m2 - // - // so D = diag(r00,r11,r22) and U has entries u01 = r01/r00, - // u02 = r02/r00, and u12 = r12/r11. - - // Q = rotation - // D = scaling - // U = shear - - // D stores the three diagonal entries r00, r11, r22 - // U stores the entries U[0] = u01, U[1] = u02, U[2] = u12 - - // build orthogonal matrix Q - float fInvLength = 1.0 / sqrt(elt[0][0] * elt[0][0] - + elt[1][0] * elt[1][0] + - elt[2][0] * elt[2][0]); - kQ[0][0] = elt[0][0] * fInvLength; - kQ[1][0] = elt[1][0] * fInvLength; - kQ[2][0] = elt[2][0] * fInvLength; - - float fDot = kQ[0][0] * elt[0][1] + kQ[1][0] * elt[1][1] + - kQ[2][0] * elt[2][1]; - kQ[0][1] = elt[0][1] - fDot * kQ[0][0]; - kQ[1][1] = elt[1][1] - fDot * kQ[1][0]; - kQ[2][1] = elt[2][1] - fDot * kQ[2][0]; - fInvLength = 1.0 / sqrt(kQ[0][1] * kQ[0][1] + kQ[1][1] * kQ[1][1] + - kQ[2][1] * kQ[2][1]); - kQ[0][1] *= fInvLength; - kQ[1][1] *= fInvLength; - kQ[2][1] *= fInvLength; - - fDot = kQ[0][0] * elt[0][2] + kQ[1][0] * elt[1][2] + - kQ[2][0] * elt[2][2]; - kQ[0][2] = elt[0][2] - fDot * kQ[0][0]; - kQ[1][2] = elt[1][2] - fDot * kQ[1][0]; - kQ[2][2] = elt[2][2] - fDot * kQ[2][0]; - fDot = kQ[0][1] * elt[0][2] + kQ[1][1] * elt[1][2] + - kQ[2][1] * elt[2][2]; - kQ[0][2] -= fDot * kQ[0][1]; - kQ[1][2] -= fDot * kQ[1][1]; - kQ[2][2] -= fDot * kQ[2][1]; - fInvLength = 1.0 / sqrt(kQ[0][2] * kQ[0][2] + kQ[1][2] * kQ[1][2] + - kQ[2][2] * kQ[2][2]); - kQ[0][2] *= fInvLength; - kQ[1][2] *= fInvLength; - kQ[2][2] *= fInvLength; - - // guarantee that orthogonal matrix has determinant 1 (no reflections) - float fDet = kQ[0][0] * kQ[1][1] * kQ[2][2] + kQ[0][1] * kQ[1][2] * kQ[2][0] + - kQ[0][2] * kQ[1][0] * kQ[2][1] - kQ[0][2] * kQ[1][1] * kQ[2][0] - - kQ[0][1] * kQ[1][0] * kQ[2][2] - kQ[0][0] * kQ[1][2] * kQ[2][1]; - - if ( fDet < 0.0 ) { - for (int iRow = 0; iRow < 3; iRow++) - for (int iCol = 0; iCol < 3; iCol++) - kQ[iRow][iCol] = -kQ[iRow][iCol]; - } - - // build "right" matrix R - Matrix3 kR; - - kR[0][0] = kQ[0][0] * elt[0][0] + kQ[1][0] * elt[1][0] + - kQ[2][0] * elt[2][0]; - - kR[0][1] = kQ[0][0] * elt[0][1] + kQ[1][0] * elt[1][1] + - kQ[2][0] * elt[2][1]; - - kR[1][1] = kQ[0][1] * elt[0][1] + kQ[1][1] * elt[1][1] + - kQ[2][1] * elt[2][1]; - - kR[0][2] = kQ[0][0] * elt[0][2] + kQ[1][0] * elt[1][2] + - kQ[2][0] * elt[2][2]; - - kR[1][2] = kQ[0][1] * elt[0][2] + kQ[1][1] * elt[1][2] + - kQ[2][1] * elt[2][2]; - - kR[2][2] = kQ[0][2] * elt[0][2] + kQ[1][2] * elt[1][2] + - kQ[2][2] * elt[2][2]; - - // the scaling component - kD[0] = kR[0][0]; - - kD[1] = kR[1][1]; - - kD[2] = kR[2][2]; - - // the shear component - float fInvD0 = 1.0 / kD[0]; - - kU[0] = kR[0][1] * fInvD0; - - kU[1] = kR[0][2] * fInvD0; - - kU[2] = kR[1][2] / kD[1]; -} - -//---------------------------------------------------------------------------- -void Matrix3::polarDecomposition(Matrix3 &R, Matrix3 &S) const{ - /* - Polar decomposition of a matrix. Based on pseudocode from - Nicholas J Higham, "Computing the Polar Decomposition -- with - Applications Siam Journal of Science and Statistical Computing, Vol 7, No. 4, - October 1986. - - Decomposes A into R*S, where R is orthogonal and S is symmetric. - - Ken Shoemake's "Matrix animation and polar decomposition" - in Proceedings of the conference on Graphics interface '92 - seems to be better known in the world of graphics, but Higham's version - uses a scaling constant that can lead to faster convergence than - Shoemake's when the initial matrix is far from orthogonal. - */ - - Matrix3 X = *this; - Matrix3 tmp = X.inverse(); - Matrix3 Xit = tmp.transpose(); - int iter = 0; - - const int MAX_ITERS = 100; - - const double eps = 50 * std::numeric_limits::epsilon(); - const float BigEps = 50 * eps; - - /* Higham suggests using OneNorm(Xit-X) < eps * OneNorm(X) - * as the convergence criterion, but OneNorm(X) should quickly - * settle down to something between 1 and 1.7, so just comparing - * with eps seems sufficient. - *--------------------------------------------------------------- */ - - double resid = X.diffOneNorm(Xit); - while (resid > eps && iter < MAX_ITERS) { - - tmp = X.inverse(); - Xit = tmp.transpose(); - - if (resid < BigEps) { - // close enough use simple iteration - X += Xit; - X *= 0.5f; - } - else { - // not close to convergence, compute acceleration factor - float gamma = sqrt( sqrt( - (Xit.l1Norm()* Xit.lInfNorm())/(X.l1Norm()*X.lInfNorm()) ) ); - - X *= 0.5f * gamma; - tmp = Xit; - tmp *= 0.5f / gamma; - X += tmp; - } - - resid = X.diffOneNorm(Xit); - iter++; - } - - R = X; - tmp = R.transpose(); - - S = tmp * (*this); - - // S := (S + S^t)/2 one more time to make sure it is symmetric - tmp = S.transpose(); - - S += tmp; - S *= 0.5f; - -#ifdef G3D_DEBUG - // Check iter limit - assert(iter < MAX_ITERS); - - // Check A = R*S - tmp = R*S; - resid = tmp.diffOneNorm(*this); - assert(resid < eps); - - // Check R is orthogonal - tmp = R*R.transpose(); - resid = tmp.diffOneNorm(Matrix3::identity()); - assert(resid < eps); - - // Check that S is symmetric - tmp = S.transpose(); - resid = tmp.diffOneNorm(S); - assert(resid < eps); -#endif -} - -//---------------------------------------------------------------------------- -float Matrix3::maxCubicRoot (float afCoeff[3]) { - // Spectral norm is for A^T*A, so characteristic polynomial - // P(x) = c[0]+c[1]*x+c[2]*x^2+x^3 has three positive float roots. - // This yields the assertions c[0] < 0 and c[2]*c[2] >= 3*c[1]. - - // quick out for uniform scale (triple root) - const float fOneThird = 1.0f / 3.0f; - const float fEpsilon = 1e-06f; - float fDiscr = afCoeff[2] * afCoeff[2] - 3.0f * afCoeff[1]; - - if ( fDiscr <= fEpsilon ) - return -fOneThird*afCoeff[2]; - - // Compute an upper bound on roots of P(x). This assumes that A^T*A - // has been scaled by its largest entry. - float fX = 1.0f; - - float fPoly = afCoeff[0] + fX * (afCoeff[1] + fX * (afCoeff[2] + fX)); - - if ( fPoly < 0.0f ) { - // uses a matrix norm to find an upper bound on maximum root - fX = G3D::abs(afCoeff[0]); - float fTmp = 1.0 + G3D::abs(afCoeff[1]); - - if ( fTmp > fX ) - fX = fTmp; - - fTmp = 1.0 + G3D::abs(afCoeff[2]); - - if ( fTmp > fX ) - fX = fTmp; - } - - // Newton's method to find root - float fTwoC2 = 2.0f * afCoeff[2]; - - for (int i = 0; i < 16; i++) { - fPoly = afCoeff[0] + fX * (afCoeff[1] + fX * (afCoeff[2] + fX)); - - if ( G3D::abs(fPoly) <= fEpsilon ) - return fX; - - float fDeriv = afCoeff[1] + fX * (fTwoC2 + 3.0f * fX); - - fX -= fPoly / fDeriv; - } - - return fX; -} - -//---------------------------------------------------------------------------- -float Matrix3::spectralNorm () const { - Matrix3 kP; - int iRow, iCol; - float fPmax = 0.0; - - for (iRow = 0; iRow < 3; iRow++) { - for (iCol = 0; iCol < 3; iCol++) { - kP[iRow][iCol] = 0.0; - - for (int iMid = 0; iMid < 3; iMid++) { - kP[iRow][iCol] += - elt[iMid][iRow] * elt[iMid][iCol]; - } - - if ( kP[iRow][iCol] > fPmax ) - fPmax = kP[iRow][iCol]; - } - } - - float fInvPmax = 1.0 / fPmax; - - for (iRow = 0; iRow < 3; iRow++) { - for (iCol = 0; iCol < 3; iCol++) - kP[iRow][iCol] *= fInvPmax; - } - - float afCoeff[3]; - afCoeff[0] = -(kP[0][0] * (kP[1][1] * kP[2][2] - kP[1][2] * kP[2][1]) + - kP[0][1] * (kP[2][0] * kP[1][2] - kP[1][0] * kP[2][2]) + - kP[0][2] * (kP[1][0] * kP[2][1] - kP[2][0] * kP[1][1])); - afCoeff[1] = kP[0][0] * kP[1][1] - kP[0][1] * kP[1][0] + - kP[0][0] * kP[2][2] - kP[0][2] * kP[2][0] + - kP[1][1] * kP[2][2] - kP[1][2] * kP[2][1]; - afCoeff[2] = -(kP[0][0] + kP[1][1] + kP[2][2]); - - float fRoot = maxCubicRoot(afCoeff); - float fNorm = sqrt(fPmax * fRoot); - return fNorm; -} - -//---------------------------------------------------------------------------- -float Matrix3::squaredFrobeniusNorm() const { - float norm2 = 0; - const float* e = &elt[0][0]; - - for (int i = 0; i < 9; ++i){ - norm2 += (*e) * (*e); - } - - return norm2; -} - -//---------------------------------------------------------------------------- -float Matrix3::frobeniusNorm() const { - return sqrtf(squaredFrobeniusNorm()); -} - -//---------------------------------------------------------------------------- -float Matrix3::l1Norm() const { - // The one norm of a matrix is the max column sum in absolute value. - float oneNorm = 0; - for (int c = 0; c < 3; ++c) { - - float f = fabs(elt[0][c])+ fabs(elt[1][c]) + fabs(elt[2][c]); - - if (f > oneNorm) { - oneNorm = f; - } - } - return oneNorm; -} - -//---------------------------------------------------------------------------- -float Matrix3::lInfNorm() const { - // The infinity norm of a matrix is the max row sum in absolute value. - float infNorm = 0; - - for (int r = 0; r < 3; ++r) { - - float f = fabs(elt[r][0]) + fabs(elt[r][1])+ fabs(elt[r][2]); - - if (f > infNorm) { - infNorm = f; - } - } - return infNorm; -} - -//---------------------------------------------------------------------------- -float Matrix3::diffOneNorm(const Matrix3 &y) const{ - float oneNorm = 0; - - for (int c = 0; c < 3; ++c){ - - float f = fabs(elt[0][c] - y[0][c]) + fabs(elt[1][c] - y[1][c]) - + fabs(elt[2][c] - y[2][c]); - - if (f > oneNorm) { - oneNorm = f; - } - } - return oneNorm; -} - -//---------------------------------------------------------------------------- -void Matrix3::toAxisAngle (Vector3& rkAxis, float& rfRadians) const { - // - // Let (x,y,z) be the unit-length axis and let A be an angle of rotation. - // The rotation matrix is R = I + sin(A)*P + (1-cos(A))*P^2 (Rodrigues' formula) where - // I is the identity and - // - // +- -+ - // P = | 0 -z +y | - // | +z 0 -x | - // | -y +x 0 | - // +- -+ - // - // If A > 0, R represents a counterclockwise rotation about the axis in - // the sense of looking from the tip of the axis vector towards the - // origin. Some algebra will show that - // - // cos(A) = (trace(R)-1)/2 and R - R^t = 2*sin(A)*P - // - // In the event that A = pi, R-R^t = 0 which prevents us from extracting - // the axis through P. Instead note that R = I+2*P^2 when A = pi, so - // P^2 = (R-I)/2. The diagonal entries of P^2 are x^2-1, y^2-1, and - // z^2-1. We can solve these for axis (x,y,z). Because the angle is pi, - // it does not matter which sign you choose on the square roots. - - float fTrace = elt[0][0] + elt[1][1] + elt[2][2]; - float fCos = 0.5f * (fTrace - 1.0f); - rfRadians = G3D::aCos(fCos); // in [0,PI] - - if ( rfRadians > 0.0 ) { - if ( rfRadians < pi() ) { - rkAxis.x = elt[2][1] - elt[1][2]; - rkAxis.y = elt[0][2] - elt[2][0]; - rkAxis.z = elt[1][0] - elt[0][1]; - rkAxis.unitize(); - } else { - // angle is PI - float fHalfInverse; - - if ( elt[0][0] >= elt[1][1] ) { - // r00 >= r11 - if ( elt[0][0] >= elt[2][2] ) { - // r00 is maximum diagonal term - rkAxis.x = 0.5 * sqrt(elt[0][0] - - elt[1][1] - elt[2][2] + 1.0); - fHalfInverse = 0.5 / rkAxis.x; - rkAxis.y = fHalfInverse * elt[0][1]; - rkAxis.z = fHalfInverse * elt[0][2]; - } else { - // r22 is maximum diagonal term - rkAxis.z = 0.5 * sqrt(elt[2][2] - - elt[0][0] - elt[1][1] + 1.0); - fHalfInverse = 0.5 / rkAxis.z; - rkAxis.x = fHalfInverse * elt[0][2]; - rkAxis.y = fHalfInverse * elt[1][2]; - } - } else { - // r11 > r00 - if ( elt[1][1] >= elt[2][2] ) { - // r11 is maximum diagonal term - rkAxis.y = 0.5 * sqrt(elt[1][1] - - elt[0][0] - elt[2][2] + 1.0); - fHalfInverse = 0.5 / rkAxis.y; - rkAxis.x = fHalfInverse * elt[0][1]; - rkAxis.z = fHalfInverse * elt[1][2]; - } else { - // r22 is maximum diagonal term - rkAxis.z = 0.5 * sqrt(elt[2][2] - - elt[0][0] - elt[1][1] + 1.0); - fHalfInverse = 0.5 / rkAxis.z; - rkAxis.x = fHalfInverse * elt[0][2]; - rkAxis.y = fHalfInverse * elt[1][2]; - } - } - } - } else { - // The angle is 0 and the matrix is the identity. Any axis will - // work, so just use the x-axis. - rkAxis.x = 1.0; - rkAxis.y = 0.0; - rkAxis.z = 0.0; - } -} - -//---------------------------------------------------------------------------- -Matrix3 Matrix3::fromAxisAngle (const Vector3& _axis, float fRadians) { - Vector3 axis = _axis.direction(); - - Matrix3 m; - float fCos = cos(fRadians); - float fSin = sin(fRadians); - float fOneMinusCos = 1.0 - fCos; - float fX2 = square(axis.x); - float fY2 = square(axis.y); - float fZ2 = square(axis.z); - float fXYM = axis.x * axis.y * fOneMinusCos; - float fXZM = axis.x * axis.z * fOneMinusCos; - float fYZM = axis.y * axis.z * fOneMinusCos; - float fXSin = axis.x * fSin; - float fYSin = axis.y * fSin; - float fZSin = axis.z * fSin; - - m.elt[0][0] = fX2 * fOneMinusCos + fCos; - m.elt[0][1] = fXYM - fZSin; - m.elt[0][2] = fXZM + fYSin; - - m.elt[1][0] = fXYM + fZSin; - m.elt[1][1] = fY2 * fOneMinusCos + fCos; - m.elt[1][2] = fYZM - fXSin; - - m.elt[2][0] = fXZM - fYSin; - m.elt[2][1] = fYZM + fXSin; - m.elt[2][2] = fZ2 * fOneMinusCos + fCos; - - return m; -} - -//---------------------------------------------------------------------------- -bool Matrix3::toEulerAnglesXYZ (float& rfXAngle, float& rfYAngle, - float& rfZAngle) const { - // rot = cy*cz -cy*sz sy - // cz*sx*sy+cx*sz cx*cz-sx*sy*sz -cy*sx - // -cx*cz*sy+sx*sz cz*sx+cx*sy*sz cx*cy - - if ( elt[0][2] < 1.0f ) { - if ( elt[0][2] > -1.0f ) { - rfXAngle = G3D::aTan2( -elt[1][2], elt[2][2]); - rfYAngle = (float) G3D::aSin(elt[0][2]); - rfZAngle = G3D::aTan2( -elt[0][1], elt[0][0]); - return true; - } else { - // WARNING. Not unique. XA - ZA = -atan2(r10,r11) - rfXAngle = -G3D::aTan2(elt[1][0], elt[1][1]); - rfYAngle = -(float)halfPi(); - rfZAngle = 0.0f; - return false; - } - } else { - // WARNING. Not unique. XAngle + ZAngle = atan2(r10,r11) - rfXAngle = G3D::aTan2(elt[1][0], elt[1][1]); - rfYAngle = (float)halfPi(); - rfZAngle = 0.0f; - return false; - } -} - -//---------------------------------------------------------------------------- -bool Matrix3::toEulerAnglesXZY (float& rfXAngle, float& rfZAngle, - float& rfYAngle) const { - // rot = cy*cz -sz cz*sy - // sx*sy+cx*cy*sz cx*cz -cy*sx+cx*sy*sz - // -cx*sy+cy*sx*sz cz*sx cx*cy+sx*sy*sz - - if ( elt[0][1] < 1.0f ) { - if ( elt[0][1] > -1.0f ) { - rfXAngle = G3D::aTan2(elt[2][1], elt[1][1]); - rfZAngle = (float) asin( -elt[0][1]); - rfYAngle = G3D::aTan2(elt[0][2], elt[0][0]); - return true; - } else { - // WARNING. Not unique. XA - YA = atan2(r20,r22) - rfXAngle = G3D::aTan2(elt[2][0], elt[2][2]); - rfZAngle = (float)halfPi(); - rfYAngle = 0.0; - return false; - } - } else { - // WARNING. Not unique. XA + YA = atan2(-r20,r22) - rfXAngle = G3D::aTan2( -elt[2][0], elt[2][2]); - rfZAngle = -(float)halfPi(); - rfYAngle = 0.0f; - return false; - } -} - -//---------------------------------------------------------------------------- -bool Matrix3::toEulerAnglesYXZ (float& rfYAngle, float& rfXAngle, - float& rfZAngle) const { - // rot = cy*cz+sx*sy*sz cz*sx*sy-cy*sz cx*sy - // cx*sz cx*cz -sx - // -cz*sy+cy*sx*sz cy*cz*sx+sy*sz cx*cy - - if ( elt[1][2] < 1.0 ) { - if ( elt[1][2] > -1.0 ) { - rfYAngle = G3D::aTan2(elt[0][2], elt[2][2]); - rfXAngle = (float) asin( -elt[1][2]); - rfZAngle = G3D::aTan2(elt[1][0], elt[1][1]); - return true; - } else { - // WARNING. Not unique. YA - ZA = atan2(r01,r00) - rfYAngle = G3D::aTan2(elt[0][1], elt[0][0]); - rfXAngle = (float)halfPi(); - rfZAngle = 0.0; - return false; - } - } else { - // WARNING. Not unique. YA + ZA = atan2(-r01,r00) - rfYAngle = G3D::aTan2( -elt[0][1], elt[0][0]); - rfXAngle = -(float)halfPi(); - rfZAngle = 0.0f; - return false; - } -} - -//---------------------------------------------------------------------------- -bool Matrix3::toEulerAnglesYZX (float& rfYAngle, float& rfZAngle, - float& rfXAngle) const { - // rot = cy*cz sx*sy-cx*cy*sz cx*sy+cy*sx*sz - // sz cx*cz -cz*sx - // -cz*sy cy*sx+cx*sy*sz cx*cy-sx*sy*sz - - if ( elt[1][0] < 1.0 ) { - if ( elt[1][0] > -1.0 ) { - rfYAngle = G3D::aTan2( -elt[2][0], elt[0][0]); - rfZAngle = (float) asin(elt[1][0]); - rfXAngle = G3D::aTan2( -elt[1][2], elt[1][1]); - return true; - } else { - // WARNING. Not unique. YA - XA = -atan2(r21,r22); - rfYAngle = -G3D::aTan2(elt[2][1], elt[2][2]); - rfZAngle = -(float)halfPi(); - rfXAngle = 0.0; - return false; - } - } else { - // WARNING. Not unique. YA + XA = atan2(r21,r22) - rfYAngle = G3D::aTan2(elt[2][1], elt[2][2]); - rfZAngle = (float)halfPi(); - rfXAngle = 0.0f; - return false; - } -} - -//---------------------------------------------------------------------------- -bool Matrix3::toEulerAnglesZXY (float& rfZAngle, float& rfXAngle, - float& rfYAngle) const { - // rot = cy*cz-sx*sy*sz -cx*sz cz*sy+cy*sx*sz - // cz*sx*sy+cy*sz cx*cz -cy*cz*sx+sy*sz - // -cx*sy sx cx*cy - - if ( elt[2][1] < 1.0 ) { - if ( elt[2][1] > -1.0 ) { - rfZAngle = G3D::aTan2( -elt[0][1], elt[1][1]); - rfXAngle = (float) asin(elt[2][1]); - rfYAngle = G3D::aTan2( -elt[2][0], elt[2][2]); - return true; - } else { - // WARNING. Not unique. ZA - YA = -atan(r02,r00) - rfZAngle = -G3D::aTan2(elt[0][2], elt[0][0]); - rfXAngle = -(float)halfPi(); - rfYAngle = 0.0f; - return false; - } - } else { - // WARNING. Not unique. ZA + YA = atan2(r02,r00) - rfZAngle = G3D::aTan2(elt[0][2], elt[0][0]); - rfXAngle = (float)halfPi(); - rfYAngle = 0.0f; - return false; - } -} - -//---------------------------------------------------------------------------- -bool Matrix3::toEulerAnglesZYX (float& rfZAngle, float& rfYAngle, - float& rfXAngle) const { - // rot = cy*cz cz*sx*sy-cx*sz cx*cz*sy+sx*sz - // cy*sz cx*cz+sx*sy*sz -cz*sx+cx*sy*sz - // -sy cy*sx cx*cy - - if ( elt[2][0] < 1.0 ) { - if ( elt[2][0] > -1.0 ) { - rfZAngle = atan2f(elt[1][0], elt[0][0]); - rfYAngle = asinf(-(double)elt[2][1]); - rfXAngle = atan2f(elt[2][1], elt[2][2]); - return true; - } else { - // WARNING. Not unique. ZA - XA = -atan2(r01,r02) - rfZAngle = -G3D::aTan2(elt[0][1], elt[0][2]); - rfYAngle = (float)halfPi(); - rfXAngle = 0.0f; - return false; - } - } else { - // WARNING. Not unique. ZA + XA = atan2(-r01,-r02) - rfZAngle = G3D::aTan2( -elt[0][1], -elt[0][2]); - rfYAngle = -(float)halfPi(); - rfXAngle = 0.0f; - return false; - } -} - -//---------------------------------------------------------------------------- -Matrix3 Matrix3::fromEulerAnglesXYZ (float fYAngle, float fPAngle, - float fRAngle) { - float fCos, fSin; - - fCos = cosf(fYAngle); - fSin = sinf(fYAngle); - Matrix3 kXMat(1.0f, 0.0f, 0.0f, 0.0f, fCos, -fSin, 0.0, fSin, fCos); - - fCos = cosf(fPAngle); - fSin = sinf(fPAngle); - Matrix3 kYMat(fCos, 0.0f, fSin, 0.0f, 1.0f, 0.0f, -fSin, 0.0f, fCos); - - fCos = cosf(fRAngle); - fSin = sinf(fRAngle); - Matrix3 kZMat(fCos, -fSin, 0.0f, fSin, fCos, 0.0f, 0.0f, 0.0f, 1.0f); - - return kXMat * (kYMat * kZMat); -} - -//---------------------------------------------------------------------------- -Matrix3 Matrix3::fromEulerAnglesXZY (float fYAngle, float fPAngle, - float fRAngle) { - - float fCos, fSin; - - fCos = cosf(fYAngle); - fSin = sinf(fYAngle); - Matrix3 kXMat(1.0, 0.0, 0.0, 0.0, fCos, -fSin, 0.0, fSin, fCos); - - fCos = cosf(fPAngle); - fSin = sinf(fPAngle); - Matrix3 kZMat(fCos, -fSin, 0.0, fSin, fCos, 0.0, 0.0, 0.0, 1.0); - - fCos = cosf(fRAngle); - fSin = sinf(fRAngle); - Matrix3 kYMat(fCos, 0.0, fSin, 0.0, 1.0, 0.0, -fSin, 0.0, fCos); - - return kXMat * (kZMat * kYMat); -} - -//---------------------------------------------------------------------------- -Matrix3 Matrix3::fromEulerAnglesYXZ( - float fYAngle, - float fPAngle, - float fRAngle) { - - float fCos, fSin; - - fCos = cos(fYAngle); - fSin = sin(fYAngle); - Matrix3 kYMat(fCos, 0.0f, fSin, 0.0f, 1.0f, 0.0f, -fSin, 0.0f, fCos); - - fCos = cos(fPAngle); - fSin = sin(fPAngle); - Matrix3 kXMat(1.0f, 0.0f, 0.0f, 0.0f, fCos, -fSin, 0.0f, fSin, fCos); - - fCos = cos(fRAngle); - fSin = sin(fRAngle); - Matrix3 kZMat(fCos, -fSin, 0.0f, fSin, fCos, 0.0f, 0.0f, 0.0f, 1.0f); - - return kYMat * (kXMat * kZMat); -} - -//---------------------------------------------------------------------------- -Matrix3 Matrix3::fromEulerAnglesYZX( - float fYAngle, - float fPAngle, - float fRAngle) { - - float fCos, fSin; - - fCos = cos(fYAngle); - fSin = sin(fYAngle); - Matrix3 kYMat(fCos, 0.0f, fSin, 0.0f, 1.0f, 0.0f, -fSin, 0.0f, fCos); - - fCos = cos(fPAngle); - fSin = sin(fPAngle); - Matrix3 kZMat(fCos, -fSin, 0.0f, fSin, fCos, 0.0f, 0.0f, 0.0f, 1.0f); - - fCos = cos(fRAngle); - fSin = sin(fRAngle); - Matrix3 kXMat(1.0f, 0.0f, 0.0f, 0.0f, fCos, -fSin, 0.0f, fSin, fCos); - - return kYMat * (kZMat * kXMat); -} - -//---------------------------------------------------------------------------- -Matrix3 Matrix3::fromEulerAnglesZXY (float fYAngle, float fPAngle, - float fRAngle) { - float fCos, fSin; - - fCos = cos(fYAngle); - fSin = sin(fYAngle); - Matrix3 kZMat(fCos, -fSin, 0.0, fSin, fCos, 0.0, 0.0, 0.0, 1.0); - - fCos = cos(fPAngle); - fSin = sin(fPAngle); - Matrix3 kXMat(1.0, 0.0, 0.0, 0.0, fCos, -fSin, 0.0, fSin, fCos); - - fCos = cos(fRAngle); - fSin = sin(fRAngle); - Matrix3 kYMat(fCos, 0.0, fSin, 0.0, 1.0, 0.0, -fSin, 0.0, fCos); - - return kZMat * (kXMat * kYMat); -} - -//---------------------------------------------------------------------------- -Matrix3 Matrix3::fromEulerAnglesZYX (float fYAngle, float fPAngle, - float fRAngle) { - float fCos, fSin; - - fCos = cos(fYAngle); - fSin = sin(fYAngle); - Matrix3 kZMat(fCos, -fSin, 0.0, fSin, fCos, 0.0, 0.0, 0.0, 1.0); - - fCos = cos(fPAngle); - fSin = sin(fPAngle); - Matrix3 kYMat(fCos, 0.0, fSin, 0.0, 1.0, 0.0, -fSin, 0.0, fCos); - - fCos = cos(fRAngle); - fSin = sin(fRAngle); - Matrix3 kXMat(1.0, 0.0, 0.0, 0.0, fCos, -fSin, 0.0, fSin, fCos); - - return kZMat * (kYMat * kXMat); -} - -//---------------------------------------------------------------------------- -void Matrix3::tridiagonal (float afDiag[3], float afSubDiag[3]) { - // Householder reduction T = Q^t M Q - // Input: - // mat, symmetric 3x3 matrix M - // Output: - // mat, orthogonal matrix Q - // diag, diagonal entries of T - // subd, subdiagonal entries of T (T is symmetric) - - float fA = elt[0][0]; - float fB = elt[0][1]; - float fC = elt[0][2]; - float fD = elt[1][1]; - float fE = elt[1][2]; - float fF = elt[2][2]; - - afDiag[0] = fA; - afSubDiag[2] = 0.0; - - if ( G3D::abs(fC) >= EPSILON ) { - float fLength = sqrt(fB * fB + fC * fC); - float fInvLength = 1.0 / fLength; - fB *= fInvLength; - fC *= fInvLength; - float fQ = 2.0 * fB * fE + fC * (fF - fD); - afDiag[1] = fD + fC * fQ; - afDiag[2] = fF - fC * fQ; - afSubDiag[0] = fLength; - afSubDiag[1] = fE - fB * fQ; - elt[0][0] = 1.0; - elt[0][1] = 0.0; - elt[0][2] = 0.0; - elt[1][0] = 0.0; - elt[1][1] = fB; - elt[1][2] = fC; - elt[2][0] = 0.0; - elt[2][1] = fC; - elt[2][2] = -fB; - } else { - afDiag[1] = fD; - afDiag[2] = fF; - afSubDiag[0] = fB; - afSubDiag[1] = fE; - elt[0][0] = 1.0; - elt[0][1] = 0.0; - elt[0][2] = 0.0; - elt[1][0] = 0.0; - elt[1][1] = 1.0; - elt[1][2] = 0.0; - elt[2][0] = 0.0; - elt[2][1] = 0.0; - elt[2][2] = 1.0; - } -} - -//---------------------------------------------------------------------------- -bool Matrix3::qLAlgorithm (float afDiag[3], float afSubDiag[3]) { - // QL iteration with implicit shifting to reduce matrix from tridiagonal - // to diagonal - - for (int i0 = 0; i0 < 3; i0++) { - const int iMaxIter = 32; - int iIter; - - for (iIter = 0; iIter < iMaxIter; iIter++) { - int i1; - - for (i1 = i0; i1 <= 1; i1++) { - float fSum = G3D::abs(afDiag[i1]) + - G3D::abs(afDiag[i1 + 1]); - - if ( G3D::abs(afSubDiag[i1]) + fSum == fSum ) - break; - } - - if ( i1 == i0 ) - break; - - float fTmp0 = (afDiag[i0 + 1] - afDiag[i0]) / (2.0 * afSubDiag[i0]); - - float fTmp1 = sqrt(fTmp0 * fTmp0 + 1.0); - - if ( fTmp0 < 0.0 ) - fTmp0 = afDiag[i1] - afDiag[i0] + afSubDiag[i0] / (fTmp0 - fTmp1); - else - fTmp0 = afDiag[i1] - afDiag[i0] + afSubDiag[i0] / (fTmp0 + fTmp1); - - float fSin = 1.0; - - float fCos = 1.0; - - float fTmp2 = 0.0; - - for (int i2 = i1 - 1; i2 >= i0; i2--) { - float fTmp3 = fSin * afSubDiag[i2]; - float fTmp4 = fCos * afSubDiag[i2]; - - if (G3D::abs(fTmp3) >= G3D::abs(fTmp0)) { - fCos = fTmp0 / fTmp3; - fTmp1 = sqrt(fCos * fCos + 1.0); - afSubDiag[i2 + 1] = fTmp3 * fTmp1; - fSin = 1.0 / fTmp1; - fCos *= fSin; - } else { - fSin = fTmp3 / fTmp0; - fTmp1 = sqrt(fSin * fSin + 1.0); - afSubDiag[i2 + 1] = fTmp0 * fTmp1; - fCos = 1.0 / fTmp1; - fSin *= fCos; - } - - fTmp0 = afDiag[i2 + 1] - fTmp2; - fTmp1 = (afDiag[i2] - fTmp0) * fSin + 2.0 * fTmp4 * fCos; - fTmp2 = fSin * fTmp1; - afDiag[i2 + 1] = fTmp0 + fTmp2; - fTmp0 = fCos * fTmp1 - fTmp4; - - for (int iRow = 0; iRow < 3; iRow++) { - fTmp3 = elt[iRow][i2 + 1]; - elt[iRow][i2 + 1] = fSin * elt[iRow][i2] + - fCos * fTmp3; - elt[iRow][i2] = fCos * elt[iRow][i2] - - fSin * fTmp3; - } - } - - afDiag[i0] -= fTmp2; - afSubDiag[i0] = fTmp0; - afSubDiag[i1] = 0.0; - } - - if ( iIter == iMaxIter ) { - // should not get here under normal circumstances - return false; - } - } - - return true; -} - -//---------------------------------------------------------------------------- -void Matrix3::eigenSolveSymmetric (float afEigenvalue[3], - Vector3 akEigenvector[3]) const { - Matrix3 kMatrix = *this; - float afSubDiag[3]; - kMatrix.tridiagonal(afEigenvalue, afSubDiag); - kMatrix.qLAlgorithm(afEigenvalue, afSubDiag); - - for (int i = 0; i < 3; i++) { - akEigenvector[i][0] = kMatrix[0][i]; - akEigenvector[i][1] = kMatrix[1][i]; - akEigenvector[i][2] = kMatrix[2][i]; - } - - // make eigenvectors form a right--handed system - Vector3 kCross = akEigenvector[1].cross(akEigenvector[2]); - - float fDet = akEigenvector[0].dot(kCross); - - if ( fDet < 0.0 ) { - akEigenvector[2][0] = - akEigenvector[2][0]; - akEigenvector[2][1] = - akEigenvector[2][1]; - akEigenvector[2][2] = - akEigenvector[2][2]; - } -} - -//---------------------------------------------------------------------------- -void Matrix3::tensorProduct (const Vector3& rkU, const Vector3& rkV, - Matrix3& rkProduct) { - for (int iRow = 0; iRow < 3; iRow++) { - for (int iCol = 0; iCol < 3; iCol++) { - rkProduct[iRow][iCol] = rkU[iRow] * rkV[iCol]; - } - } -} - -//---------------------------------------------------------------------------- - -// Runs in 52 cycles on AMD, 76 cycles on Intel Centrino -// -// The loop unrolling is necessary for performance. -// I was unable to improve performance further by flattening the matrices -// into float*'s instead of 2D arrays. -// -// -morgan -void Matrix3::_mul(const Matrix3& A, const Matrix3& B, Matrix3& out) { - const float* ARowPtr = A.elt[0]; - float* outRowPtr = out.elt[0]; - outRowPtr[0] = - ARowPtr[0] * B.elt[0][0] + - ARowPtr[1] * B.elt[1][0] + - ARowPtr[2] * B.elt[2][0]; - outRowPtr[1] = - ARowPtr[0] * B.elt[0][1] + - ARowPtr[1] * B.elt[1][1] + - ARowPtr[2] * B.elt[2][1]; - outRowPtr[2] = - ARowPtr[0] * B.elt[0][2] + - ARowPtr[1] * B.elt[1][2] + - ARowPtr[2] * B.elt[2][2]; - - ARowPtr = A.elt[1]; - outRowPtr = out.elt[1]; - - outRowPtr[0] = - ARowPtr[0] * B.elt[0][0] + - ARowPtr[1] * B.elt[1][0] + - ARowPtr[2] * B.elt[2][0]; - outRowPtr[1] = - ARowPtr[0] * B.elt[0][1] + - ARowPtr[1] * B.elt[1][1] + - ARowPtr[2] * B.elt[2][1]; - outRowPtr[2] = - ARowPtr[0] * B.elt[0][2] + - ARowPtr[1] * B.elt[1][2] + - ARowPtr[2] * B.elt[2][2]; - - ARowPtr = A.elt[2]; - outRowPtr = out.elt[2]; - - outRowPtr[0] = - ARowPtr[0] * B.elt[0][0] + - ARowPtr[1] * B.elt[1][0] + - ARowPtr[2] * B.elt[2][0]; - outRowPtr[1] = - ARowPtr[0] * B.elt[0][1] + - ARowPtr[1] * B.elt[1][1] + - ARowPtr[2] * B.elt[2][1]; - outRowPtr[2] = - ARowPtr[0] * B.elt[0][2] + - ARowPtr[1] * B.elt[1][2] + - ARowPtr[2] * B.elt[2][2]; -} - -//---------------------------------------------------------------------------- -void Matrix3::_transpose(const Matrix3& A, Matrix3& out) { - out[0][0] = A.elt[0][0]; - out[0][1] = A.elt[1][0]; - out[0][2] = A.elt[2][0]; - out[1][0] = A.elt[0][1]; - out[1][1] = A.elt[1][1]; - out[1][2] = A.elt[2][1]; - out[2][0] = A.elt[0][2]; - out[2][1] = A.elt[1][2]; - out[2][2] = A.elt[2][2]; -} - -//----------------------------------------------------------------------------- -std::string Matrix3::toString() const { - return G3D::format("[%g, %g, %g; %g, %g, %g; %g, %g, %g]", - elt[0][0], elt[0][1], elt[0][2], - elt[1][0], elt[1][1], elt[1][2], - elt[2][0], elt[2][1], elt[2][2]); -} - - - -} // namespace - diff --git a/externals/g3dlite/Matrix4.cpp b/externals/g3dlite/Matrix4.cpp deleted file mode 100644 index cd38a1a3602..00000000000 --- a/externals/g3dlite/Matrix4.cpp +++ /dev/null @@ -1,523 +0,0 @@ -/** - @file Matrix4.cpp - - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2003-10-02 - @edited 2010-01-29 - */ - -#include "G3D/platform.h" -#include "G3D/Matrix4.h" -#include "G3D/Matrix3.h" -#include "G3D/Vector4.h" -#include "G3D/Vector3.h" -#include "G3D/BinaryInput.h" -#include "G3D/BinaryOutput.h" -#include "G3D/CoordinateFrame.h" -#include "G3D/Rect2D.h" -#include "G3D/Any.h" -#include "G3D/stringutils.h" - -namespace G3D { - - -Matrix4::Matrix4(const Any& any) { - any.verifyName("Matrix4"); - any.verifyType(Any::ARRAY); - - const std::string& name = toLower(any.name()); - if (name == "matrix4") { - any.verifySize(16); - - for (int r = 0; r < 4; ++r) { - for (int c = 0; c < 4; ++c) { - elt[r][c] = any[r * 4 + c]; - } - } - } else if (name == "matrix4::scale") { - if (any.size() == 1) { - *this = scale(any[0].number()); - } else if (any.size() == 3) { - *this = scale(any[0], any[1], any[2]); - } else { - any.verify(false, "Matrix4::scale() takes either 1 or 3 arguments"); - } - } else { - any.verify(false, "Expected Matrix4 constructor"); - } -} - - -Matrix4::operator Any() const { - Any any(Any::ARRAY, "Matrix4"); - any.resize(16); - for (int r = 0; r < 4; ++r) { - for (int c = 0; c < 4; ++c) { - any[r * 4 + c] = elt[r][c]; - } - } - - return any; -} - -const Matrix4& Matrix4::identity() { - static Matrix4 m( - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1); - return m; -} - - -const Matrix4& Matrix4::zero() { - static Matrix4 m( - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0); - return m; -} - - -Matrix4::Matrix4(const class CoordinateFrame& cframe) { - for (int r = 0; r < 3; ++r) { - for (int c = 0; c < 3; ++c) { - elt[r][c] = cframe.rotation[r][c]; - } - elt[r][3] = cframe.translation[r]; - } - elt[3][0] = 0.0f; - elt[3][1] = 0.0f; - elt[3][2] = 0.0f; - elt[3][3] = 1.0f; -} - -Matrix4::Matrix4(const Matrix3& upper3x3, const Vector3& lastCol) { - for (int r = 0; r < 3; ++r) { - for (int c = 0; c < 3; ++c) { - elt[r][c] = upper3x3[r][c]; - } - elt[r][3] = lastCol[r]; - } - elt[3][0] = 0.0f; - elt[3][1] = 0.0f; - elt[3][2] = 0.0f; - elt[3][3] = 1.0f; -} - - -Matrix3 Matrix4::upper3x3() const { - return Matrix3(elt[0][0], elt[0][1], elt[0][2], - elt[1][0], elt[1][1], elt[1][2], - elt[2][0], elt[2][1], elt[2][2]); -} - - -Matrix4 Matrix4::orthogonalProjection( - const class Rect2D& rect, - float nearval, - float farval, - float upDirection) { - return Matrix4::orthogonalProjection(rect.x0(), rect.x1(), rect.y1(), rect.y0(), nearval, farval, upDirection); -} - - -Matrix4 Matrix4::orthogonalProjection( - float left, - float right, - float bottom, - float top, - float nearval, - float farval, - float upDirection) { - - // Adapted from Mesa. Note that Microsoft (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/opengl/glfunc03_8qnj.asp) - // and Linux (http://www.xfree86.org/current/glOrtho.3.html) have different matrices shown in their documentation. - - float x, y, z; - float tx, ty, tz; - - x = 2.0f / (right-left); - y = 2.0f / (top-bottom); - z = -2.0f / (farval-nearval); - tx = -(right+left) / (right-left); - ty = -(top+bottom) / (top-bottom); - tz = -(farval+nearval) / (farval-nearval); - - y *= upDirection; - ty *= upDirection; - - return - Matrix4( x , 0.0f, 0.0f, tx, - 0.0f, y , 0.0f, ty, - 0.0f, 0.0f, z , tz, - 0.0f, 0.0f, 0.0f, 1.0f); -} - - -Matrix4 Matrix4::perspectiveProjection( - float left, - float right, - float bottom, - float top, - float nearval, - float farval, - float upDirection) { - - float x, y, a, b, c, d; - - x = (2.0f*nearval) / (right-left); - y = (2.0f*nearval) / (top-bottom); - a = (right+left) / (right-left); - b = (top+bottom) / (top-bottom); - - if (farval >= finf()) { - // Infinite view frustum - c = -1.0f; - d = -2.0f * nearval; - } else { - c = -(farval+nearval) / (farval-nearval); - d = -(2.0f*farval*nearval) / (farval-nearval); - } - - debugAssertM(abs(upDirection) == 1.0f, "upDirection must be -1 or +1"); - y *= upDirection; - b *= upDirection; - - return Matrix4( - x, 0, a, 0, - 0, y, b, 0, - 0, 0, c, d, - 0, 0, -1, 0); -} - - -void Matrix4::getPerspectiveProjectionParameters( - float& left, - float& right, - float& bottom, - float& top, - float& nearval, - float& farval, - float upDirection) const { - - debugAssertM(abs(upDirection) == 1.0f, "upDirection must be -1 or +1"); - - float x = elt[0][0]; - float y = elt[1][1] * upDirection; - float a = elt[0][2]; - float b = elt[1][2] * upDirection; - float c = elt[2][2]; - float d = elt[2][3]; - - // Verify that this really is a projection matrix - debugAssertM(elt[3][2] == -1, "Not a projection matrix"); - debugAssertM(elt[0][1] == 0, "Not a projection matrix"); - debugAssertM(elt[0][3] == 0, "Not a projection matrix"); - debugAssertM(elt[1][3] == 0, "Not a projection matrix"); - debugAssertM(elt[3][3] == 0, "Not a projection matrix"); - debugAssertM(elt[1][0] == 0, "Not a projection matrix"); - debugAssertM(elt[2][0] == 0, "Not a projection matrix"); - debugAssertM(elt[2][1] == 0, "Not a projection matrix"); - debugAssertM(elt[3][0] == 0, "Not a projection matrix"); - debugAssertM(elt[3][1] == 0, "Not a projection matrix"); - - if (c == -1) { - farval = finf(); - nearval = -d / 2.0f; - } else { - nearval = d * ((c - 1.0f) / (c + 1.0f) - 1.0f) / (-2.0f * (c - 1.0f) / (c + 1.0f)); - farval = nearval * ((c - 1.0f) / (c + 1.0f)); - } - - - left = (a - 1.0f) * nearval / x; - right = 2.0f * nearval / x + left; - - bottom = (b - 1.0f) * nearval / y; - top = 2.0f * nearval / y + bottom; -} - - -Matrix4::Matrix4( - float r1c1, float r1c2, float r1c3, float r1c4, - float r2c1, float r2c2, float r2c3, float r2c4, - float r3c1, float r3c2, float r3c3, float r3c4, - float r4c1, float r4c2, float r4c3, float r4c4) { - elt[0][0] = r1c1; elt[0][1] = r1c2; elt[0][2] = r1c3; elt[0][3] = r1c4; - elt[1][0] = r2c1; elt[1][1] = r2c2; elt[1][2] = r2c3; elt[1][3] = r2c4; - elt[2][0] = r3c1; elt[2][1] = r3c2; elt[2][2] = r3c3; elt[2][3] = r3c4; - elt[3][0] = r4c1; elt[3][1] = r4c2; elt[3][2] = r4c3; elt[3][3] = r4c4; -} - -/** - init should be row major. - */ -Matrix4::Matrix4(const float* init) { - for (int r = 0; r < 4; ++r) { - for (int c = 0; c < 4; ++c) { - elt[r][c] = init[r * 4 + c]; - } - } -} - - -Matrix4::Matrix4(const double* init) { - for (int r = 0; r < 4; ++r) { - for (int c = 0; c < 4; ++c) { - elt[r][c] = (float)init[r * 4 + c]; - } - } -} - - -Matrix4::Matrix4() { - for (int r = 0; r < 4; ++r) { - for (int c = 0; c < 4; ++c) { - elt[r][c] = 0; - } - } -} - - -void Matrix4::setRow(int r, const Vector4& v) { - for (int c = 0; c < 4; ++c) { - elt[r][c] = v[c]; - } -} - - -void Matrix4::setColumn(int c, const Vector4& v) { - for (int r = 0; r < 4; ++r) { - elt[r][c] = v[r]; - } -} - - -const Vector4& Matrix4::row(int r) const { - return reinterpret_cast(elt[r])[0]; -} - - -Vector4 Matrix4::column(int c) const { - Vector4 v; - for (int r = 0; r < 4; ++r) { - v[r] = elt[r][c]; - } - return v; -} - - -Matrix4 Matrix4::operator*(const Matrix4& other) const { - Matrix4 result; - for (int r = 0; r < 4; ++r) { - for (int c = 0; c < 4; ++c) { - for (int i = 0; i < 4; ++i) { - result.elt[r][c] += elt[r][i] * other.elt[i][c]; - } - } - } - - return result; -} - - -Matrix4 Matrix4::operator*(const float s) const { - Matrix4 result; - for (int r = 0; r < 4; ++r) { - for (int c = 0; c < 4; ++c) { - result.elt[r][c] = elt[r][c] * s; - } - } - - return result; -} - - -Vector3 Matrix4::homoMul(const class Vector3& v, float w) const { - Vector4 r = (*this) * Vector4(v, w); - return r.xyz() * (1.0f / r.w); -} - - -Vector4 Matrix4::operator*(const Vector4& vector) const { - Vector4 result(0,0,0,0); - for (int r = 0; r < 4; ++r) { - for (int c = 0; c < 4; ++c) { - result[r] += elt[r][c] * vector[c]; - } - } - - return result; -} - - -Matrix4 Matrix4::transpose() const { - Matrix4 result; - for (int r = 0; r < 4; ++r) { - for (int c = 0; c < 4; ++c) { - result.elt[c][r] = elt[r][c]; - } - } - - return result; -} - - -bool Matrix4::operator!=(const Matrix4& other) const { - return ! (*this == other); -} - - -bool Matrix4::operator==(const Matrix4& other) const { - - // If the bit patterns are identical, they must be - // the same matrix. If not, they *might* still have - // equal elements due to floating point weirdness. - if (memcmp(this, &other, sizeof(Matrix4) == 0)) { - return true; - } - - for (int r = 0; r < 4; ++r) { - for (int c = 0; c < 4; ++c) { - if (elt[r][c] != other.elt[r][c]) { - return false; - } - } - } - - return true; -} - - -float Matrix4::determinant() const { - // Determinant is the dot product of the first row and the first row - // of cofactors (i.e. the first col of the adjoint matrix) - return cofactor().row(0).dot(row(0)); -} - - -Matrix4 Matrix4::adjoint() const { - return cofactor().transpose(); -} - - -Matrix4 Matrix4::inverse() const { - // Inverse = adjoint / determinant - - Matrix4 A = adjoint(); - - // Determinant is the dot product of the first row and the first row - // of cofactors (i.e. the first col of the adjoint matrix) - float det = A.column(0).dot(row(0)); - - return A * (1.0f / det); -} - - -Matrix4 Matrix4::cofactor() const { - Matrix4 out; - - // We'll use i to incrementally compute -1 ^ (r+c) - int i = 1; - - for (int r = 0; r < 4; ++r) { - for (int c = 0; c < 4; ++c) { - // Compute the determinant of the 3x3 submatrix - float det = subDeterminant(r, c); - out.elt[r][c] = i * det; - i = -i; - } - i = -i; - } - - return out; -} - - -float Matrix4::subDeterminant(int excludeRow, int excludeCol) const { - // Compute non-excluded row and column indices - int row[3]; - int col[3]; - - for (int i = 0; i < 3; ++i) { - row[i] = i; - col[i] = i; - - if (i >= excludeRow) { - ++row[i]; - } - if (i >= excludeCol) { - ++col[i]; - } - } - - // Compute the first row of cofactors - float cofactor00 = - elt[row[1]][col[1]] * elt[row[2]][col[2]] - - elt[row[1]][col[2]] * elt[row[2]][col[1]]; - - float cofactor10 = - elt[row[1]][col[2]] * elt[row[2]][col[0]] - - elt[row[1]][col[0]] * elt[row[2]][col[2]]; - - float cofactor20 = - elt[row[1]][col[0]] * elt[row[2]][col[1]] - - elt[row[1]][col[1]] * elt[row[2]][col[0]]; - - // Product of the first row and the cofactors along the first row - return - elt[row[0]][col[0]] * cofactor00 + - elt[row[0]][col[1]] * cofactor10 + - elt[row[0]][col[2]] * cofactor20; -} - - -CoordinateFrame Matrix4::approxCoordinateFrame() const { - CoordinateFrame cframe; - - for (int r = 0; r < 3; ++r) { - for (int c = 0; c < 3; ++c) { - cframe.rotation[r][c] = elt[r][c]; - } - cframe.translation[r] = elt[r][3]; - } - - // Ensure that the rotation matrix is orthonormal - cframe.rotation.orthonormalize(); - - return cframe; -} - - -void Matrix4::serialize(class BinaryOutput& b) const { - for (int r = 0; r < 4; ++r) { - for (int c = 0; c < 4; ++c) { - b.writeFloat32(elt[r][c]); - } - } -} - - -void Matrix4::deserialize(class BinaryInput& b) { - for (int r = 0; r < 4; ++r) { - for (int c = 0; c < 4; ++c) { - elt[r][c] = b.readFloat32(); - } - } -} - -std::string Matrix4::toString() const { - return G3D::format("[%g, %g, %g, %g; %g, %g, %g, %g; %g, %g, %g, %g; %g, %g, %g, %g]", - elt[0][0], elt[0][1], elt[0][2], elt[0][3], - elt[1][0], elt[1][1], elt[1][2], elt[1][3], - elt[2][0], elt[2][1], elt[2][2], elt[2][3], - elt[3][0], elt[3][1], elt[3][2], elt[3][3]); -} - -} // namespace - - diff --git a/externals/g3dlite/MemoryManager.cpp b/externals/g3dlite/MemoryManager.cpp deleted file mode 100644 index 240188a1f0e..00000000000 --- a/externals/g3dlite/MemoryManager.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/** - @file MemoryManager.cpp - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - @created 2009-04-20 - @edited 2009-05-29 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ - -#include "G3D/MemoryManager.h" -#include "G3D/System.h" - -namespace G3D { - -MemoryManager::MemoryManager() {} - - -void* MemoryManager::alloc(size_t s) { - return System::malloc(s); -} - - -void MemoryManager::free(void* ptr) { - System::free(ptr); -} - - -bool MemoryManager::isThreadsafe() const { - return true; -} - - -MemoryManager::Ref MemoryManager::create() { - static MemoryManager::Ref m = new MemoryManager(); - return m; -} - - -/////////////////////////////////////////////////// - -AlignedMemoryManager::AlignedMemoryManager() {} - - -void* AlignedMemoryManager::alloc(size_t s) { - return System::alignedMalloc(s, 16); -} - - -void AlignedMemoryManager::free(void* ptr) { - System::alignedFree(ptr); -} - - -bool AlignedMemoryManager::isThreadsafe() const { - return true; -} - - -AlignedMemoryManager::Ref AlignedMemoryManager::create() { - static AlignedMemoryManager::Ref m = new AlignedMemoryManager(); - return m; -} - - -/////////////////////////////////////////////////// - -CRTMemoryManager::CRTMemoryManager() {} - - -void* CRTMemoryManager::alloc(size_t s) { - return ::malloc(s); -} - - -void CRTMemoryManager::free(void* ptr) { - return ::free(ptr); -} - - -bool CRTMemoryManager::isThreadsafe() const { - return true; -} - - -CRTMemoryManager::Ref CRTMemoryManager::create() { - static CRTMemoryManager::Ref m = new CRTMemoryManager(); - return m; -} -} diff --git a/externals/g3dlite/Plane.cpp b/externals/g3dlite/Plane.cpp deleted file mode 100644 index 9b7991c0333..00000000000 --- a/externals/g3dlite/Plane.cpp +++ /dev/null @@ -1,149 +0,0 @@ -/** - @file Plane.cpp - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2003-02-06 - @edited 2006-01-29 - */ - -#include "G3D/platform.h" -#include "G3D/Plane.h" -#include "G3D/BinaryOutput.h" -#include "G3D/BinaryInput.h" -#include "G3D/stringutils.h" - -namespace G3D { - -Plane::Plane(class BinaryInput& b) { - deserialize(b); -} - - -void Plane::serialize(class BinaryOutput& b) const { - _normal.serialize(b); - b.writeFloat64(_distance); -} - - -void Plane::deserialize(class BinaryInput& b) { - _normal.deserialize(b); - _distance = (float)b.readFloat64(); -} - - -Plane::Plane( - Vector4 point0, - Vector4 point1, - Vector4 point2) { - - debugAssertM( - point0.w != 0 || - point1.w != 0 || - point2.w != 0, - "At least one point must be finite."); - - // Rotate the points around so that the finite points come first. - - while ((point0.w == 0) && - ((point1.w == 0) || (point2.w != 0))) { - Vector4 temp = point0; - point0 = point1; - point1 = point2; - point2 = temp; - } - - Vector3 dir1; - Vector3 dir2; - - if (point1.w == 0) { - // 1 finite, 2 infinite points; the plane must contain - // the direction of the two direcitons - dir1 = point1.xyz(); - dir2 = point2.xyz(); - } else if (point2.w != 0) { - // 3 finite points, the plane must contain the directions - // betwseen the points. - dir1 = point1.xyz() - point0.xyz(); - dir2 = point2.xyz() - point0.xyz(); - } else { - // 2 finite, 1 infinite point; the plane must contain - // the direction between the first two points and the - // direction of the third point. - dir1 = point1.xyz() - point0.xyz(); - dir2 = point2.xyz(); - } - - _normal = dir1.cross(dir2).direction(); - _distance = _normal.dot(point0.xyz()); -} - - -Plane::Plane( - const Vector3& point0, - const Vector3& point1, - const Vector3& point2) { - - _normal = (point1 - point0).cross(point2 - point0).direction(); - _distance = _normal.dot(point0); -} - - -Plane::Plane( - const Vector3& __normal, - const Vector3& point) { - - _normal = __normal.direction(); - _distance = _normal.dot(point); -} - - -Plane Plane::fromEquation(float a, float b, float c, float d) { - Vector3 n(a, b, c); - float magnitude = n.magnitude(); - d /= magnitude; - n /= magnitude; - return Plane(n, -d); -} - - -void Plane::flip() { - _normal = -_normal; - _distance = -_distance; -} - - -void Plane::getEquation(Vector3& n, float& d) const { - double _d; - getEquation(n, _d); - d = (float)_d; -} - -void Plane::getEquation(Vector3& n, double& d) const { - n = _normal; - d = -_distance; -} - - -void Plane::getEquation(float& a, float& b, float& c, float& d) const { - double _a, _b, _c, _d; - getEquation(_a, _b, _c, _d); - a = (float)_a; - b = (float)_b; - c = (float)_c; - d = (float)_d; -} - -void Plane::getEquation(double& a, double& b, double& c, double& d) const { - a = _normal.x; - b = _normal.y; - c = _normal.z; - d = -_distance; -} - - -std::string Plane::toString() const { - return format("Plane(%g, %g, %g, %g)", _normal.x, _normal.y, _normal.z, _distance); -} - -} diff --git a/externals/g3dlite/Quat.cpp b/externals/g3dlite/Quat.cpp deleted file mode 100644 index 225c5b51acc..00000000000 --- a/externals/g3dlite/Quat.cpp +++ /dev/null @@ -1,583 +0,0 @@ -/** - @file Quat.cpp - - Quaternion implementation based on Watt & Watt page 363 - - @author Morgan McGuire, graphics3d.com - - @created 2002-01-23 - @edited 2006-01-31 - */ - -#include "G3D/Quat.h" -#include "G3D/BinaryInput.h" -#include "G3D/BinaryOutput.h" - -namespace G3D { - -Quat Quat::fromAxisAngleRotation( - const Vector3& axis, - float angle) { - - Quat q; - - q.w = cos(angle / 2.0f); - q.imag() = axis.direction() * sin(angle / 2.0f); - - return q; -} - - -Quat::Quat( - const Matrix3& rot) { - - static const int plus1mod3[] = {1, 2, 0}; - - // Find the index of the largest diagonal component - // These ? operations hopefully compile to conditional - // move instructions instead of branches. - int i = (rot[1][1] > rot[0][0]) ? 1 : 0; - i = (rot[2][2] > rot[i][i]) ? 2 : i; - - // Find the indices of the other elements - int j = plus1mod3[i]; - int k = plus1mod3[j]; - - // Index the elements of the vector part of the quaternion as a float* - float* v = (float*)(this); - - // If we attempted to pre-normalize and trusted the matrix to be - // perfectly orthonormal, the result would be: - // - // double c = sqrt((rot[i][i] - (rot[j][j] + rot[k][k])) + 1.0) - // v[i] = -c * 0.5 - // v[j] = -(rot[i][j] + rot[j][i]) * 0.5 / c - // v[k] = -(rot[i][k] + rot[k][i]) * 0.5 / c - // w = (rot[j][k] - rot[k][j]) * 0.5 / c - // - // Since we're going to pay the sqrt anyway, we perform a post normalization, which also - // fixes any poorly normalized input. Multiply all elements by 2*c in the above, giving: - - // nc2 = -c^2 - double nc2 = ((rot[j][j] + rot[k][k]) - rot[i][i]) - 1.0; - v[i] = nc2; - w = (rot[j][k] - rot[k][j]); - v[j] = -(rot[i][j] + rot[j][i]); - v[k] = -(rot[i][k] + rot[k][i]); - - // We now have the correct result with the wrong magnitude, so normalize it: - float s = sqrt(x*x + y*y + z*z + w*w); - if (s > 0.00001f) { - s = 1.0f / s; - x *= s; - y *= s; - z *= s; - w *= s; - } else { - // The quaternion is nearly zero. Make it 0 0 0 1 - x = 0.0f; - y = 0.0f; - z = 0.0f; - w = 1.0f; - } -} - - -void Quat::toAxisAngleRotation( - Vector3& axis, - double& angle) const { - - // Decompose the quaternion into an angle and an axis. - - axis = Vector3(x, y, z); - angle = 2 * acos(w); - - float len = sqrt(1.0f - w * w); - - if (fuzzyGt(abs(len), 0.0f)) { - axis /= len; - } - - // Reduce the range of the angle. - - if (angle < 0) { - angle = -angle; - axis = -axis; - } - - while (angle > twoPi()) { - angle -= twoPi(); - } - - if (abs(angle) > pi()) { - angle -= twoPi(); - } - - // Make the angle positive. - - if (angle < 0.0f) { - angle = -angle; - axis = -axis; - } -} - - -Matrix3 Quat::toRotationMatrix() const { - Matrix3 out = Matrix3::zero(); - - toRotationMatrix(out); - - return out; -} - - -void Quat::toRotationMatrix( - Matrix3& rot) const { - - rot = Matrix3(*this); -} - - -Quat Quat::slerp( - const Quat& _quat1, - float alpha, - float threshold) const { - - // From: Game Physics -- David Eberly pg 538-540 - // Modified to include lerp for small angles, which - // is a common practice. - - // See also: - // http://number-none.com/product/Understanding%20Slerp,%20Then%20Not%20Using%20It/index.html - - const Quat& quat0 = *this; - Quat quat1 = _quat1; - - // angle between quaternion rotations - float phi; - float cosphi = quat0.dot(quat1); - - - if (cosphi < 0) { - // Change the sign and fix the dot product; we need to - // loop the other way to get the shortest path - quat1 = -quat1; - cosphi = -cosphi; - } - - // Using G3D::aCos will clamp the angle to 0 and pi - phi = static_cast(G3D::aCos(cosphi)); - - if (phi >= threshold) { - // For large angles, slerp - float scale0, scale1; - - scale0 = sin((1.0f - alpha) * phi); - scale1 = sin(alpha * phi); - - return ( (quat0 * scale0) + (quat1 * scale1) ) / sin(phi); - } else { - // For small angles, linear interpolate - return quat0.nlerp(quat1, alpha); - } -} - - -Quat Quat::nlerp( - const Quat& quat1, - float alpha) const { - - Quat result = (*this) * (1.0f - alpha) + quat1 * alpha; - return result / result.magnitude(); -} - - -Quat Quat::operator*(const Quat& other) const { - - // Following Watt & Watt, page 360 - const Vector3& v1 = imag(); - const Vector3& v2 = other.imag(); - float s1 = w; - float s2 = other.w; - - return Quat(s1*v2 + s2*v1 + v1.cross(v2), s1*s2 - v1.dot(v2)); -} - - -// From "Uniform Random Rotations", Ken Shoemake, Graphics Gems III. -Quat Quat::unitRandom() { - float x0 = uniformRandom(); - float r1 = sqrtf(1 - x0), - r2 = sqrtf(x0); - float t1 = (float)G3D::twoPi() * uniformRandom(); - float t2 = (float)G3D::twoPi() * uniformRandom(); - float c1 = cosf(t1), - s1 = sinf(t1); - float c2 = cosf(t2), - s2 = sinf(t2); - return Quat(s1 * r1, c1 * r1, s2 * r2, c2 * r2); -} - - -void Quat::deserialize(class BinaryInput& b) { - x = b.readFloat32(); - y = b.readFloat32(); - z = b.readFloat32(); - w = b.readFloat32(); -} - - -void Quat::serialize(class BinaryOutput& b) const { - b.writeFloat32(x); - b.writeFloat32(y); - b.writeFloat32(z); - b.writeFloat32(w); -} - - -// 2-char swizzles - -Vector2 Quat::xx() const { return Vector2 (x, x); } -Vector2 Quat::yx() const { return Vector2 (y, x); } -Vector2 Quat::zx() const { return Vector2 (z, x); } -Vector2 Quat::wx() const { return Vector2 (w, x); } -Vector2 Quat::xy() const { return Vector2 (x, y); } -Vector2 Quat::yy() const { return Vector2 (y, y); } -Vector2 Quat::zy() const { return Vector2 (z, y); } -Vector2 Quat::wy() const { return Vector2 (w, y); } -Vector2 Quat::xz() const { return Vector2 (x, z); } -Vector2 Quat::yz() const { return Vector2 (y, z); } -Vector2 Quat::zz() const { return Vector2 (z, z); } -Vector2 Quat::wz() const { return Vector2 (w, z); } -Vector2 Quat::xw() const { return Vector2 (x, w); } -Vector2 Quat::yw() const { return Vector2 (y, w); } -Vector2 Quat::zw() const { return Vector2 (z, w); } -Vector2 Quat::ww() const { return Vector2 (w, w); } - -// 3-char swizzles - -Vector3 Quat::xxx() const { return Vector3 (x, x, x); } -Vector3 Quat::yxx() const { return Vector3 (y, x, x); } -Vector3 Quat::zxx() const { return Vector3 (z, x, x); } -Vector3 Quat::wxx() const { return Vector3 (w, x, x); } -Vector3 Quat::xyx() const { return Vector3 (x, y, x); } -Vector3 Quat::yyx() const { return Vector3 (y, y, x); } -Vector3 Quat::zyx() const { return Vector3 (z, y, x); } -Vector3 Quat::wyx() const { return Vector3 (w, y, x); } -Vector3 Quat::xzx() const { return Vector3 (x, z, x); } -Vector3 Quat::yzx() const { return Vector3 (y, z, x); } -Vector3 Quat::zzx() const { return Vector3 (z, z, x); } -Vector3 Quat::wzx() const { return Vector3 (w, z, x); } -Vector3 Quat::xwx() const { return Vector3 (x, w, x); } -Vector3 Quat::ywx() const { return Vector3 (y, w, x); } -Vector3 Quat::zwx() const { return Vector3 (z, w, x); } -Vector3 Quat::wwx() const { return Vector3 (w, w, x); } -Vector3 Quat::xxy() const { return Vector3 (x, x, y); } -Vector3 Quat::yxy() const { return Vector3 (y, x, y); } -Vector3 Quat::zxy() const { return Vector3 (z, x, y); } -Vector3 Quat::wxy() const { return Vector3 (w, x, y); } -Vector3 Quat::xyy() const { return Vector3 (x, y, y); } -Vector3 Quat::yyy() const { return Vector3 (y, y, y); } -Vector3 Quat::zyy() const { return Vector3 (z, y, y); } -Vector3 Quat::wyy() const { return Vector3 (w, y, y); } -Vector3 Quat::xzy() const { return Vector3 (x, z, y); } -Vector3 Quat::yzy() const { return Vector3 (y, z, y); } -Vector3 Quat::zzy() const { return Vector3 (z, z, y); } -Vector3 Quat::wzy() const { return Vector3 (w, z, y); } -Vector3 Quat::xwy() const { return Vector3 (x, w, y); } -Vector3 Quat::ywy() const { return Vector3 (y, w, y); } -Vector3 Quat::zwy() const { return Vector3 (z, w, y); } -Vector3 Quat::wwy() const { return Vector3 (w, w, y); } -Vector3 Quat::xxz() const { return Vector3 (x, x, z); } -Vector3 Quat::yxz() const { return Vector3 (y, x, z); } -Vector3 Quat::zxz() const { return Vector3 (z, x, z); } -Vector3 Quat::wxz() const { return Vector3 (w, x, z); } -Vector3 Quat::xyz() const { return Vector3 (x, y, z); } -Vector3 Quat::yyz() const { return Vector3 (y, y, z); } -Vector3 Quat::zyz() const { return Vector3 (z, y, z); } -Vector3 Quat::wyz() const { return Vector3 (w, y, z); } -Vector3 Quat::xzz() const { return Vector3 (x, z, z); } -Vector3 Quat::yzz() const { return Vector3 (y, z, z); } -Vector3 Quat::zzz() const { return Vector3 (z, z, z); } -Vector3 Quat::wzz() const { return Vector3 (w, z, z); } -Vector3 Quat::xwz() const { return Vector3 (x, w, z); } -Vector3 Quat::ywz() const { return Vector3 (y, w, z); } -Vector3 Quat::zwz() const { return Vector3 (z, w, z); } -Vector3 Quat::wwz() const { return Vector3 (w, w, z); } -Vector3 Quat::xxw() const { return Vector3 (x, x, w); } -Vector3 Quat::yxw() const { return Vector3 (y, x, w); } -Vector3 Quat::zxw() const { return Vector3 (z, x, w); } -Vector3 Quat::wxw() const { return Vector3 (w, x, w); } -Vector3 Quat::xyw() const { return Vector3 (x, y, w); } -Vector3 Quat::yyw() const { return Vector3 (y, y, w); } -Vector3 Quat::zyw() const { return Vector3 (z, y, w); } -Vector3 Quat::wyw() const { return Vector3 (w, y, w); } -Vector3 Quat::xzw() const { return Vector3 (x, z, w); } -Vector3 Quat::yzw() const { return Vector3 (y, z, w); } -Vector3 Quat::zzw() const { return Vector3 (z, z, w); } -Vector3 Quat::wzw() const { return Vector3 (w, z, w); } -Vector3 Quat::xww() const { return Vector3 (x, w, w); } -Vector3 Quat::yww() const { return Vector3 (y, w, w); } -Vector3 Quat::zww() const { return Vector3 (z, w, w); } -Vector3 Quat::www() const { return Vector3 (w, w, w); } - -// 4-char swizzles - -Vector4 Quat::xxxx() const { return Vector4 (x, x, x, x); } -Vector4 Quat::yxxx() const { return Vector4 (y, x, x, x); } -Vector4 Quat::zxxx() const { return Vector4 (z, x, x, x); } -Vector4 Quat::wxxx() const { return Vector4 (w, x, x, x); } -Vector4 Quat::xyxx() const { return Vector4 (x, y, x, x); } -Vector4 Quat::yyxx() const { return Vector4 (y, y, x, x); } -Vector4 Quat::zyxx() const { return Vector4 (z, y, x, x); } -Vector4 Quat::wyxx() const { return Vector4 (w, y, x, x); } -Vector4 Quat::xzxx() const { return Vector4 (x, z, x, x); } -Vector4 Quat::yzxx() const { return Vector4 (y, z, x, x); } -Vector4 Quat::zzxx() const { return Vector4 (z, z, x, x); } -Vector4 Quat::wzxx() const { return Vector4 (w, z, x, x); } -Vector4 Quat::xwxx() const { return Vector4 (x, w, x, x); } -Vector4 Quat::ywxx() const { return Vector4 (y, w, x, x); } -Vector4 Quat::zwxx() const { return Vector4 (z, w, x, x); } -Vector4 Quat::wwxx() const { return Vector4 (w, w, x, x); } -Vector4 Quat::xxyx() const { return Vector4 (x, x, y, x); } -Vector4 Quat::yxyx() const { return Vector4 (y, x, y, x); } -Vector4 Quat::zxyx() const { return Vector4 (z, x, y, x); } -Vector4 Quat::wxyx() const { return Vector4 (w, x, y, x); } -Vector4 Quat::xyyx() const { return Vector4 (x, y, y, x); } -Vector4 Quat::yyyx() const { return Vector4 (y, y, y, x); } -Vector4 Quat::zyyx() const { return Vector4 (z, y, y, x); } -Vector4 Quat::wyyx() const { return Vector4 (w, y, y, x); } -Vector4 Quat::xzyx() const { return Vector4 (x, z, y, x); } -Vector4 Quat::yzyx() const { return Vector4 (y, z, y, x); } -Vector4 Quat::zzyx() const { return Vector4 (z, z, y, x); } -Vector4 Quat::wzyx() const { return Vector4 (w, z, y, x); } -Vector4 Quat::xwyx() const { return Vector4 (x, w, y, x); } -Vector4 Quat::ywyx() const { return Vector4 (y, w, y, x); } -Vector4 Quat::zwyx() const { return Vector4 (z, w, y, x); } -Vector4 Quat::wwyx() const { return Vector4 (w, w, y, x); } -Vector4 Quat::xxzx() const { return Vector4 (x, x, z, x); } -Vector4 Quat::yxzx() const { return Vector4 (y, x, z, x); } -Vector4 Quat::zxzx() const { return Vector4 (z, x, z, x); } -Vector4 Quat::wxzx() const { return Vector4 (w, x, z, x); } -Vector4 Quat::xyzx() const { return Vector4 (x, y, z, x); } -Vector4 Quat::yyzx() const { return Vector4 (y, y, z, x); } -Vector4 Quat::zyzx() const { return Vector4 (z, y, z, x); } -Vector4 Quat::wyzx() const { return Vector4 (w, y, z, x); } -Vector4 Quat::xzzx() const { return Vector4 (x, z, z, x); } -Vector4 Quat::yzzx() const { return Vector4 (y, z, z, x); } -Vector4 Quat::zzzx() const { return Vector4 (z, z, z, x); } -Vector4 Quat::wzzx() const { return Vector4 (w, z, z, x); } -Vector4 Quat::xwzx() const { return Vector4 (x, w, z, x); } -Vector4 Quat::ywzx() const { return Vector4 (y, w, z, x); } -Vector4 Quat::zwzx() const { return Vector4 (z, w, z, x); } -Vector4 Quat::wwzx() const { return Vector4 (w, w, z, x); } -Vector4 Quat::xxwx() const { return Vector4 (x, x, w, x); } -Vector4 Quat::yxwx() const { return Vector4 (y, x, w, x); } -Vector4 Quat::zxwx() const { return Vector4 (z, x, w, x); } -Vector4 Quat::wxwx() const { return Vector4 (w, x, w, x); } -Vector4 Quat::xywx() const { return Vector4 (x, y, w, x); } -Vector4 Quat::yywx() const { return Vector4 (y, y, w, x); } -Vector4 Quat::zywx() const { return Vector4 (z, y, w, x); } -Vector4 Quat::wywx() const { return Vector4 (w, y, w, x); } -Vector4 Quat::xzwx() const { return Vector4 (x, z, w, x); } -Vector4 Quat::yzwx() const { return Vector4 (y, z, w, x); } -Vector4 Quat::zzwx() const { return Vector4 (z, z, w, x); } -Vector4 Quat::wzwx() const { return Vector4 (w, z, w, x); } -Vector4 Quat::xwwx() const { return Vector4 (x, w, w, x); } -Vector4 Quat::ywwx() const { return Vector4 (y, w, w, x); } -Vector4 Quat::zwwx() const { return Vector4 (z, w, w, x); } -Vector4 Quat::wwwx() const { return Vector4 (w, w, w, x); } -Vector4 Quat::xxxy() const { return Vector4 (x, x, x, y); } -Vector4 Quat::yxxy() const { return Vector4 (y, x, x, y); } -Vector4 Quat::zxxy() const { return Vector4 (z, x, x, y); } -Vector4 Quat::wxxy() const { return Vector4 (w, x, x, y); } -Vector4 Quat::xyxy() const { return Vector4 (x, y, x, y); } -Vector4 Quat::yyxy() const { return Vector4 (y, y, x, y); } -Vector4 Quat::zyxy() const { return Vector4 (z, y, x, y); } -Vector4 Quat::wyxy() const { return Vector4 (w, y, x, y); } -Vector4 Quat::xzxy() const { return Vector4 (x, z, x, y); } -Vector4 Quat::yzxy() const { return Vector4 (y, z, x, y); } -Vector4 Quat::zzxy() const { return Vector4 (z, z, x, y); } -Vector4 Quat::wzxy() const { return Vector4 (w, z, x, y); } -Vector4 Quat::xwxy() const { return Vector4 (x, w, x, y); } -Vector4 Quat::ywxy() const { return Vector4 (y, w, x, y); } -Vector4 Quat::zwxy() const { return Vector4 (z, w, x, y); } -Vector4 Quat::wwxy() const { return Vector4 (w, w, x, y); } -Vector4 Quat::xxyy() const { return Vector4 (x, x, y, y); } -Vector4 Quat::yxyy() const { return Vector4 (y, x, y, y); } -Vector4 Quat::zxyy() const { return Vector4 (z, x, y, y); } -Vector4 Quat::wxyy() const { return Vector4 (w, x, y, y); } -Vector4 Quat::xyyy() const { return Vector4 (x, y, y, y); } -Vector4 Quat::yyyy() const { return Vector4 (y, y, y, y); } -Vector4 Quat::zyyy() const { return Vector4 (z, y, y, y); } -Vector4 Quat::wyyy() const { return Vector4 (w, y, y, y); } -Vector4 Quat::xzyy() const { return Vector4 (x, z, y, y); } -Vector4 Quat::yzyy() const { return Vector4 (y, z, y, y); } -Vector4 Quat::zzyy() const { return Vector4 (z, z, y, y); } -Vector4 Quat::wzyy() const { return Vector4 (w, z, y, y); } -Vector4 Quat::xwyy() const { return Vector4 (x, w, y, y); } -Vector4 Quat::ywyy() const { return Vector4 (y, w, y, y); } -Vector4 Quat::zwyy() const { return Vector4 (z, w, y, y); } -Vector4 Quat::wwyy() const { return Vector4 (w, w, y, y); } -Vector4 Quat::xxzy() const { return Vector4 (x, x, z, y); } -Vector4 Quat::yxzy() const { return Vector4 (y, x, z, y); } -Vector4 Quat::zxzy() const { return Vector4 (z, x, z, y); } -Vector4 Quat::wxzy() const { return Vector4 (w, x, z, y); } -Vector4 Quat::xyzy() const { return Vector4 (x, y, z, y); } -Vector4 Quat::yyzy() const { return Vector4 (y, y, z, y); } -Vector4 Quat::zyzy() const { return Vector4 (z, y, z, y); } -Vector4 Quat::wyzy() const { return Vector4 (w, y, z, y); } -Vector4 Quat::xzzy() const { return Vector4 (x, z, z, y); } -Vector4 Quat::yzzy() const { return Vector4 (y, z, z, y); } -Vector4 Quat::zzzy() const { return Vector4 (z, z, z, y); } -Vector4 Quat::wzzy() const { return Vector4 (w, z, z, y); } -Vector4 Quat::xwzy() const { return Vector4 (x, w, z, y); } -Vector4 Quat::ywzy() const { return Vector4 (y, w, z, y); } -Vector4 Quat::zwzy() const { return Vector4 (z, w, z, y); } -Vector4 Quat::wwzy() const { return Vector4 (w, w, z, y); } -Vector4 Quat::xxwy() const { return Vector4 (x, x, w, y); } -Vector4 Quat::yxwy() const { return Vector4 (y, x, w, y); } -Vector4 Quat::zxwy() const { return Vector4 (z, x, w, y); } -Vector4 Quat::wxwy() const { return Vector4 (w, x, w, y); } -Vector4 Quat::xywy() const { return Vector4 (x, y, w, y); } -Vector4 Quat::yywy() const { return Vector4 (y, y, w, y); } -Vector4 Quat::zywy() const { return Vector4 (z, y, w, y); } -Vector4 Quat::wywy() const { return Vector4 (w, y, w, y); } -Vector4 Quat::xzwy() const { return Vector4 (x, z, w, y); } -Vector4 Quat::yzwy() const { return Vector4 (y, z, w, y); } -Vector4 Quat::zzwy() const { return Vector4 (z, z, w, y); } -Vector4 Quat::wzwy() const { return Vector4 (w, z, w, y); } -Vector4 Quat::xwwy() const { return Vector4 (x, w, w, y); } -Vector4 Quat::ywwy() const { return Vector4 (y, w, w, y); } -Vector4 Quat::zwwy() const { return Vector4 (z, w, w, y); } -Vector4 Quat::wwwy() const { return Vector4 (w, w, w, y); } -Vector4 Quat::xxxz() const { return Vector4 (x, x, x, z); } -Vector4 Quat::yxxz() const { return Vector4 (y, x, x, z); } -Vector4 Quat::zxxz() const { return Vector4 (z, x, x, z); } -Vector4 Quat::wxxz() const { return Vector4 (w, x, x, z); } -Vector4 Quat::xyxz() const { return Vector4 (x, y, x, z); } -Vector4 Quat::yyxz() const { return Vector4 (y, y, x, z); } -Vector4 Quat::zyxz() const { return Vector4 (z, y, x, z); } -Vector4 Quat::wyxz() const { return Vector4 (w, y, x, z); } -Vector4 Quat::xzxz() const { return Vector4 (x, z, x, z); } -Vector4 Quat::yzxz() const { return Vector4 (y, z, x, z); } -Vector4 Quat::zzxz() const { return Vector4 (z, z, x, z); } -Vector4 Quat::wzxz() const { return Vector4 (w, z, x, z); } -Vector4 Quat::xwxz() const { return Vector4 (x, w, x, z); } -Vector4 Quat::ywxz() const { return Vector4 (y, w, x, z); } -Vector4 Quat::zwxz() const { return Vector4 (z, w, x, z); } -Vector4 Quat::wwxz() const { return Vector4 (w, w, x, z); } -Vector4 Quat::xxyz() const { return Vector4 (x, x, y, z); } -Vector4 Quat::yxyz() const { return Vector4 (y, x, y, z); } -Vector4 Quat::zxyz() const { return Vector4 (z, x, y, z); } -Vector4 Quat::wxyz() const { return Vector4 (w, x, y, z); } -Vector4 Quat::xyyz() const { return Vector4 (x, y, y, z); } -Vector4 Quat::yyyz() const { return Vector4 (y, y, y, z); } -Vector4 Quat::zyyz() const { return Vector4 (z, y, y, z); } -Vector4 Quat::wyyz() const { return Vector4 (w, y, y, z); } -Vector4 Quat::xzyz() const { return Vector4 (x, z, y, z); } -Vector4 Quat::yzyz() const { return Vector4 (y, z, y, z); } -Vector4 Quat::zzyz() const { return Vector4 (z, z, y, z); } -Vector4 Quat::wzyz() const { return Vector4 (w, z, y, z); } -Vector4 Quat::xwyz() const { return Vector4 (x, w, y, z); } -Vector4 Quat::ywyz() const { return Vector4 (y, w, y, z); } -Vector4 Quat::zwyz() const { return Vector4 (z, w, y, z); } -Vector4 Quat::wwyz() const { return Vector4 (w, w, y, z); } -Vector4 Quat::xxzz() const { return Vector4 (x, x, z, z); } -Vector4 Quat::yxzz() const { return Vector4 (y, x, z, z); } -Vector4 Quat::zxzz() const { return Vector4 (z, x, z, z); } -Vector4 Quat::wxzz() const { return Vector4 (w, x, z, z); } -Vector4 Quat::xyzz() const { return Vector4 (x, y, z, z); } -Vector4 Quat::yyzz() const { return Vector4 (y, y, z, z); } -Vector4 Quat::zyzz() const { return Vector4 (z, y, z, z); } -Vector4 Quat::wyzz() const { return Vector4 (w, y, z, z); } -Vector4 Quat::xzzz() const { return Vector4 (x, z, z, z); } -Vector4 Quat::yzzz() const { return Vector4 (y, z, z, z); } -Vector4 Quat::zzzz() const { return Vector4 (z, z, z, z); } -Vector4 Quat::wzzz() const { return Vector4 (w, z, z, z); } -Vector4 Quat::xwzz() const { return Vector4 (x, w, z, z); } -Vector4 Quat::ywzz() const { return Vector4 (y, w, z, z); } -Vector4 Quat::zwzz() const { return Vector4 (z, w, z, z); } -Vector4 Quat::wwzz() const { return Vector4 (w, w, z, z); } -Vector4 Quat::xxwz() const { return Vector4 (x, x, w, z); } -Vector4 Quat::yxwz() const { return Vector4 (y, x, w, z); } -Vector4 Quat::zxwz() const { return Vector4 (z, x, w, z); } -Vector4 Quat::wxwz() const { return Vector4 (w, x, w, z); } -Vector4 Quat::xywz() const { return Vector4 (x, y, w, z); } -Vector4 Quat::yywz() const { return Vector4 (y, y, w, z); } -Vector4 Quat::zywz() const { return Vector4 (z, y, w, z); } -Vector4 Quat::wywz() const { return Vector4 (w, y, w, z); } -Vector4 Quat::xzwz() const { return Vector4 (x, z, w, z); } -Vector4 Quat::yzwz() const { return Vector4 (y, z, w, z); } -Vector4 Quat::zzwz() const { return Vector4 (z, z, w, z); } -Vector4 Quat::wzwz() const { return Vector4 (w, z, w, z); } -Vector4 Quat::xwwz() const { return Vector4 (x, w, w, z); } -Vector4 Quat::ywwz() const { return Vector4 (y, w, w, z); } -Vector4 Quat::zwwz() const { return Vector4 (z, w, w, z); } -Vector4 Quat::wwwz() const { return Vector4 (w, w, w, z); } -Vector4 Quat::xxxw() const { return Vector4 (x, x, x, w); } -Vector4 Quat::yxxw() const { return Vector4 (y, x, x, w); } -Vector4 Quat::zxxw() const { return Vector4 (z, x, x, w); } -Vector4 Quat::wxxw() const { return Vector4 (w, x, x, w); } -Vector4 Quat::xyxw() const { return Vector4 (x, y, x, w); } -Vector4 Quat::yyxw() const { return Vector4 (y, y, x, w); } -Vector4 Quat::zyxw() const { return Vector4 (z, y, x, w); } -Vector4 Quat::wyxw() const { return Vector4 (w, y, x, w); } -Vector4 Quat::xzxw() const { return Vector4 (x, z, x, w); } -Vector4 Quat::yzxw() const { return Vector4 (y, z, x, w); } -Vector4 Quat::zzxw() const { return Vector4 (z, z, x, w); } -Vector4 Quat::wzxw() const { return Vector4 (w, z, x, w); } -Vector4 Quat::xwxw() const { return Vector4 (x, w, x, w); } -Vector4 Quat::ywxw() const { return Vector4 (y, w, x, w); } -Vector4 Quat::zwxw() const { return Vector4 (z, w, x, w); } -Vector4 Quat::wwxw() const { return Vector4 (w, w, x, w); } -Vector4 Quat::xxyw() const { return Vector4 (x, x, y, w); } -Vector4 Quat::yxyw() const { return Vector4 (y, x, y, w); } -Vector4 Quat::zxyw() const { return Vector4 (z, x, y, w); } -Vector4 Quat::wxyw() const { return Vector4 (w, x, y, w); } -Vector4 Quat::xyyw() const { return Vector4 (x, y, y, w); } -Vector4 Quat::yyyw() const { return Vector4 (y, y, y, w); } -Vector4 Quat::zyyw() const { return Vector4 (z, y, y, w); } -Vector4 Quat::wyyw() const { return Vector4 (w, y, y, w); } -Vector4 Quat::xzyw() const { return Vector4 (x, z, y, w); } -Vector4 Quat::yzyw() const { return Vector4 (y, z, y, w); } -Vector4 Quat::zzyw() const { return Vector4 (z, z, y, w); } -Vector4 Quat::wzyw() const { return Vector4 (w, z, y, w); } -Vector4 Quat::xwyw() const { return Vector4 (x, w, y, w); } -Vector4 Quat::ywyw() const { return Vector4 (y, w, y, w); } -Vector4 Quat::zwyw() const { return Vector4 (z, w, y, w); } -Vector4 Quat::wwyw() const { return Vector4 (w, w, y, w); } -Vector4 Quat::xxzw() const { return Vector4 (x, x, z, w); } -Vector4 Quat::yxzw() const { return Vector4 (y, x, z, w); } -Vector4 Quat::zxzw() const { return Vector4 (z, x, z, w); } -Vector4 Quat::wxzw() const { return Vector4 (w, x, z, w); } -Vector4 Quat::xyzw() const { return Vector4 (x, y, z, w); } -Vector4 Quat::yyzw() const { return Vector4 (y, y, z, w); } -Vector4 Quat::zyzw() const { return Vector4 (z, y, z, w); } -Vector4 Quat::wyzw() const { return Vector4 (w, y, z, w); } -Vector4 Quat::xzzw() const { return Vector4 (x, z, z, w); } -Vector4 Quat::yzzw() const { return Vector4 (y, z, z, w); } -Vector4 Quat::zzzw() const { return Vector4 (z, z, z, w); } -Vector4 Quat::wzzw() const { return Vector4 (w, z, z, w); } -Vector4 Quat::xwzw() const { return Vector4 (x, w, z, w); } -Vector4 Quat::ywzw() const { return Vector4 (y, w, z, w); } -Vector4 Quat::zwzw() const { return Vector4 (z, w, z, w); } -Vector4 Quat::wwzw() const { return Vector4 (w, w, z, w); } -Vector4 Quat::xxww() const { return Vector4 (x, x, w, w); } -Vector4 Quat::yxww() const { return Vector4 (y, x, w, w); } -Vector4 Quat::zxww() const { return Vector4 (z, x, w, w); } -Vector4 Quat::wxww() const { return Vector4 (w, x, w, w); } -Vector4 Quat::xyww() const { return Vector4 (x, y, w, w); } -Vector4 Quat::yyww() const { return Vector4 (y, y, w, w); } -Vector4 Quat::zyww() const { return Vector4 (z, y, w, w); } -Vector4 Quat::wyww() const { return Vector4 (w, y, w, w); } -Vector4 Quat::xzww() const { return Vector4 (x, z, w, w); } -Vector4 Quat::yzww() const { return Vector4 (y, z, w, w); } -Vector4 Quat::zzww() const { return Vector4 (z, z, w, w); } -Vector4 Quat::wzww() const { return Vector4 (w, z, w, w); } -Vector4 Quat::xwww() const { return Vector4 (x, w, w, w); } -Vector4 Quat::ywww() const { return Vector4 (y, w, w, w); } -Vector4 Quat::zwww() const { return Vector4 (z, w, w, w); } -Vector4 Quat::wwww() const { return Vector4 (w, w, w, w); } -} - diff --git a/externals/g3dlite/Random.cpp b/externals/g3dlite/Random.cpp deleted file mode 100644 index 2dda744a1ac..00000000000 --- a/externals/g3dlite/Random.cpp +++ /dev/null @@ -1,212 +0,0 @@ -/** - @file Random.cpp - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2009-01-02 - @edited 2009-03-29 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ -#include "G3D/Random.h" - -namespace G3D { - -Random& Random::common() { - static Random r; - return r; -} - -Random::Random(void* x) : state(NULL), m_threadsafe(false) { - (void)x; -} - - -Random::Random(uint32 seed, bool threadsafe) : m_threadsafe(threadsafe) { - const uint32 X = 1812433253UL; - - state = new uint32[N]; - state[0] = seed; - for (index = 1; index < (int)N; ++index) { - state[index] = X * (state[index - 1] ^ (state[index - 1] >> 30)) + index; - } -} - - -Random::~Random() { - delete[] state; - state = NULL; -} - - -uint32 Random::bits() { - // See http://en.wikipedia.org/wiki/Mersenne_twister - - // Make a local copy of the index variable to ensure that it - // is not out of bounds - int localIndex = index; - - // Automatically checks for index < 0 if corrupted - // by unsynchronized threads. - if ((unsigned int)localIndex >= (unsigned int)N) { - generate(); - localIndex = 0; - } - // Increment the global index. It may go out of bounds on - // multiple threads, but the above check ensures that the - // array index actually used never goes out of bounds. - // It doesn't matter if we grab the same array index twice - // on two threads, since the distribution of random numbers - // will still be uniform. - ++index; - // Return the next random in the sequence - uint32 r = state[localIndex]; - - // Temper the result - r ^= r >> U; - r ^= (r << S) & B; - r ^= (r << T) & C; - r ^= r >> L; - - return r; -} - - -/** Generate the next N ints, and store them for readback later */ -void Random::generate() { - // Lower R bits - static const uint32 LOWER_MASK = (1LU << R) - 1; - - // Upper (32 - R) bits - static const uint32 UPPER_MASK = 0xFFFFFFFF << R; - static const uint32 mag01[2] = {0UL, (uint32)A}; - - if (m_threadsafe) { - bool contention = ! lock.lock(); - if (contention) { - // Another thread just generated a set of numbers; no need for - // this thread to do it too - lock.unlock(); - return; - } - } - - // First N - M - for (unsigned int i = 0; i < N - M; ++i) { - uint32 x = (state[i] & UPPER_MASK) | (state[i + 1] & LOWER_MASK); - state[i] = state[i + M] ^ (x >> 1) ^ mag01[x & 1]; - } - - // Rest - for (unsigned int i = N - M + 1; i < N - 1; ++i) { - uint32 x = (state[i] & UPPER_MASK) | (state[i + 1] & LOWER_MASK); - state[i] = state[i + (M - N)] ^ (x >> 1) ^ mag01[x & 1]; - } - - uint32 y = (state[N - 1] & UPPER_MASK) | (state[0] & LOWER_MASK); - state[N - 1] = state[M - 1] ^ (y >> 1) ^ mag01[y & 1]; - index = 0; - - if (m_threadsafe) { - lock.unlock(); - } -} - - -int Random::integer(int low, int high) { - int r = iFloor(low + (high - low + 1) * (double)bits() / 0xFFFFFFFFUL); - - // There is a *very small* chance of generating - // a number larger than high. - if (r > high) { - return high; - } else { - return r; - } -} - - -float Random::gaussian(float mean, float stdev) { - - // Using Box-Mueller method from http://www.taygeta.com/random/gaussian.html - // Modified to specify standard deviation and mean of distribution - float w, x1, x2; - - // Loop until w is less than 1 so that log(w) is negative - do { - x1 = uniform(-1.0, 1.0); - x2 = uniform(-1.0, 1.0); - - w = float(square(x1) + square(x2)); - } while (w > 1.0f); - - // Transform to gassian distribution - // Multiply by sigma (stdev ^ 2) and add mean. - return x2 * (float)square(stdev) * sqrtf((-2.0f * logf(w) ) / w) + mean; -} - - -void Random::cosHemi(float& x, float& y, float& z) { - const float e1 = uniform(); - const float e2 = uniform(); - - // Jensen's method - const float sin_theta = sqrtf(1.0f - e1); - const float cos_theta = sqrtf(e1); - const float phi = 6.28318531f * e2; - - x = cos(phi) * sin_theta; - y = sin(phi) * sin_theta; - z = cos_theta; - - // We could also use Malley's method (pbrt p.657), since they are the same cost: - // - // r = sqrt(e1); - // t = 2*pi*e2; - // x = cos(t)*r; - // y = sin(t)*r; - // z = sqrt(1.0 - x*x + y*y); -} - - -void Random::cosPowHemi(const float k, float& x, float& y, float& z) { - const float e1 = uniform(); - const float e2 = uniform(); - - const float cos_theta = pow(e1, 1.0f / (k + 1.0f)); - const float sin_theta = sqrtf(1.0f - square(cos_theta)); - const float phi = 6.28318531f * e2; - - x = cos(phi) * sin_theta; - y = sin(phi) * sin_theta; - z = cos_theta; -} - - -void Random::hemi(float& x, float& y, float& z) { - sphere(x, y, z); - z = fabsf(z); -} - - -void Random::sphere(float& x, float& y, float& z) { - // Squared magnitude - float m2; - - // Rejection sample - do { - x = uniform() * 2.0f - 1.0f, - y = uniform() * 2.0f - 1.0f, - z = uniform() * 2.0f - 1.0f; - m2 = x*x + y*y + z*z; - } while (m2 >= 1.0f); - - // Divide by magnitude to produce a unit vector - float s = rsqrt(m2); - x *= s; - y *= s; - z *= s; -} - -} // G3D diff --git a/externals/g3dlite/Ray.cpp b/externals/g3dlite/Ray.cpp deleted file mode 100644 index 0436ef0b323..00000000000 --- a/externals/g3dlite/Ray.cpp +++ /dev/null @@ -1,218 +0,0 @@ -/** - @file Ray.cpp - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2002-07-12 - @edited 2004-03-19 - */ - -#include "G3D/platform.h" -#include "G3D/Ray.h" -#include "G3D/Plane.h" -#include "G3D/Sphere.h" -#include "G3D/CollisionDetection.h" - -namespace G3D { - -void Ray::set(const Vector3& origin, const Vector3& direction) { - m_origin = origin; - m_direction = direction; - debugAssert(direction.isUnit()); - - m_invDirection = Vector3::one() / direction; - - // ray slope - ibyj = m_direction.x * m_invDirection.y; - jbyi = m_direction.y * m_invDirection.x; - jbyk = m_direction.y * m_invDirection.z; - kbyj = m_direction.z * m_invDirection.y; - ibyk = m_direction.x * m_invDirection.z; - kbyi = m_direction.z * m_invDirection.x; - - // precomputed terms - c_xy = m_origin.y - jbyi * m_origin.x; - c_xz = m_origin.z - kbyi * m_origin.x; - c_yx = m_origin.x - ibyj * m_origin.y; - c_yz = m_origin.z - kbyj * m_origin.y; - c_zx = m_origin.x - ibyk * m_origin.z; - c_zy = m_origin.y - jbyk * m_origin.z; - - //ray slope classification - if (m_direction.x < 0) { - if (m_direction.y < 0) { - if (m_direction.z < 0) { - classification = MMM; - } else if (m_direction.z > 0) { - classification = MMP; - } else { //(m_direction.z >= 0) - classification = MMO; - } - } else { //(m_direction.y >= 0) - if (m_direction.z < 0) { - if (m_direction.y == 0) { - classification = MOM; - } else { - classification = MPM; - } - } else { //(m_direction.z >= 0) - if ((m_direction.y == 0) && (m_direction.z == 0)) { - classification = MOO; - } else if (m_direction.z == 0) { - classification = MPO; - } else if (m_direction.y == 0) { - classification = MOP; - } else { - classification = MPP; - } - } - } - } else { //(m_direction.x >= 0) - if (m_direction.y < 0) { - if (m_direction.z < 0) { - if (m_direction.x == 0) { - classification = OMM; - } else { - classification = PMM; - } - } else { //(m_direction.z >= 0) - if ((m_direction.x == 0) && (m_direction.z == 0)) { - classification = OMO; - } else if (m_direction.z == 0) { - classification = PMO; - } else if (m_direction.x == 0) { - classification = OMP; - } else { - classification = PMP; - } - } - } else { //(m_direction.y >= 0) - if (m_direction.z < 0) { - if ((m_direction.x == 0) && (m_direction.y == 0)) { - classification = OOM; - } else if (m_direction.x == 0) { - classification = OPM; - } else if (m_direction.y == 0) { - classification = POM; - } else { - classification = PPM; - } - } else { //(m_direction.z > 0) - if (m_direction.x == 0) { - if (m_direction.y == 0) { - classification = OOP; - } else if (m_direction.z == 0) { - classification = OPO; - } else { - classification = OPP; - } - } else { - if ((m_direction.y == 0) && (m_direction.z == 0)) { - classification = POO; - } else if (m_direction.y == 0) { - classification = POP; - } else if (m_direction.z == 0) { - classification = PPO; - } else { - classification = PPP; - } - } - } - } - } -} - -Ray::Ray(class BinaryInput& b) { - deserialize(b); -} - - -void Ray::serialize(class BinaryOutput& b) const { - m_origin.serialize(b); - m_direction.serialize(b); -} - - -void Ray::deserialize(class BinaryInput& b) { - m_origin.deserialize(b); - m_direction.deserialize(b); - set(m_origin, m_direction); -} - - -Ray Ray::refract( - const Vector3& newOrigin, - const Vector3& normal, - float iInside, - float iOutside) const { - - Vector3 D = m_direction.refractionDirection(normal, iInside, iOutside); - return Ray(newOrigin + (m_direction + normal * (float)sign(m_direction.dot(normal))) * 0.001f, D); -} - - -Ray Ray::reflect( - const Vector3& newOrigin, - const Vector3& normal) const { - - Vector3 D = m_direction.reflectionDirection(normal); - return Ray(newOrigin + (D + normal) * 0.001f, D); -} - - -Vector3 Ray::intersection(const Plane& plane) const { - float d; - Vector3 normal = plane.normal(); - plane.getEquation(normal, d); - float rate = m_direction.dot(normal); - - if (rate >= 0.0f) { - return Vector3::inf(); - } else { - float t = -(d + m_origin.dot(normal)) / rate; - return m_origin + m_direction * t; - } -} - - -float Ray::intersectionTime(const class Sphere& sphere, bool solid) const { - Vector3 dummy; - return CollisionDetection::collisionTimeForMovingPointFixedSphere( - m_origin, m_direction, sphere, dummy, dummy, solid); -} - - -float Ray::intersectionTime(const class Plane& plane) const { - Vector3 dummy; - return CollisionDetection::collisionTimeForMovingPointFixedPlane( - m_origin, m_direction, plane, dummy); -} - - -float Ray::intersectionTime(const class Box& box) const { - Vector3 dummy; - float time = CollisionDetection::collisionTimeForMovingPointFixedBox( - m_origin, m_direction, box, dummy); - - if ((time == finf()) && (box.contains(m_origin))) { - return 0.0f; - } else { - return time; - } -} - - -float Ray::intersectionTime(const class AABox& box) const { - Vector3 dummy; - bool inside; - float time = CollisionDetection::collisionTimeForMovingPointFixedAABox( - m_origin, m_direction, box, dummy, inside); - - if ((time == finf()) && inside) { - return 0.0f; - } else { - return time; - } -} - -} diff --git a/externals/g3dlite/ReferenceCount.cpp b/externals/g3dlite/ReferenceCount.cpp deleted file mode 100644 index 2e1f117e0d9..00000000000 --- a/externals/g3dlite/ReferenceCount.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/** - @file ReferenceCount.cpp - - Reference Counting Garbage Collector for C++ - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - @cite Adapted and extended from Justin Miller's "RGC" class that appeared in BYTE magazine. - @cite See also http://www.jelovic.com/articles/cpp_without_memory_errors_slides.htm - - @created 2001-10-23 - @edited 2009-04-25 -*/ -#include "G3D/platform.h" -#include "G3D/ReferenceCount.h" - -namespace G3D { - -ReferenceCountedObject::ReferenceCountedObject() : - ReferenceCountedObject_refCount(0), - ReferenceCountedObject_weakPointer(0) { - - debugAssertM(isValidHeapPointer(this), - "Reference counted objects must be allocated on the heap."); -} - -void ReferenceCountedObject::ReferenceCountedObject_zeroWeakPointers() { - // Tell all of my weak pointers that I'm gone. - - _WeakPtrLinkedList* node = ReferenceCountedObject_weakPointer; - - while (node != NULL) { - // Notify the weak pointer that it is going away - node->weakPtr->objectCollected(); - - // Free the node and advance - _WeakPtrLinkedList* tmp = node; - node = node->next; - delete tmp; - } -} - -ReferenceCountedObject::~ReferenceCountedObject() {} - - -ReferenceCountedObject::ReferenceCountedObject(const ReferenceCountedObject& notUsed) : - ReferenceCountedObject_refCount(0), - ReferenceCountedObject_weakPointer(0) { - (void)notUsed; - debugAssertM(G3D::isValidHeapPointer(this), - "Reference counted objects must be allocated on the heap."); -} - -ReferenceCountedObject& ReferenceCountedObject::operator=(const ReferenceCountedObject& other) { - (void)other; - // Nothing changes when I am assigned; the reference count on - // both objects is the same (although my super-class probably - // changes). - return *this; -} - -} // G3D diff --git a/externals/g3dlite/RegistryUtil.cpp b/externals/g3dlite/RegistryUtil.cpp deleted file mode 100644 index fc4cebc2ee5..00000000000 --- a/externals/g3dlite/RegistryUtil.cpp +++ /dev/null @@ -1,290 +0,0 @@ -/** - @file RegistryUtil.cpp - - @created 2006-04-06 - @edited 2006-04-24 - - Copyright 2000-2006, Morgan McGuire. - All rights reserved. -*/ - -#include "G3D/platform.h" - -// This file is only used on Windows -#ifdef G3D_WIN32 - -#include "G3D/RegistryUtil.h" -#include "G3D/System.h" - -namespace G3D { - -// static helpers -static HKEY getRootKeyFromString(const char* str, size_t length); - - -bool RegistryUtil::keyExists(const std::string& key) { - size_t pos = key.find('\\', 0); - if (pos == std::string::npos) { - return false; - } - - HKEY hkey = getRootKeyFromString(key.c_str(), pos); - - if (hkey == NULL) { - return false; - } - - HKEY openKey; - int32 result = RegOpenKeyExA(hkey, (key.c_str() + pos + 1), 0, KEY_READ, &openKey); - - debugAssert(result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND); - - if (result == ERROR_SUCCESS) { - RegCloseKey(openKey); - return true; - } else { - return false; - } -} - -bool RegistryUtil::valueExists(const std::string& key, const std::string& value) { - size_t pos = key.find('\\', 0); - if (pos == std::string::npos) { - return false; - } - - HKEY hkey = getRootKeyFromString(key.c_str(), pos); - - if ( hkey == NULL ) { - return false; - } - - HKEY openKey; - int32 result = RegOpenKeyExA(hkey, (key.c_str() + pos + 1), 0, KEY_READ, &openKey); - debugAssert(result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND); - - if (result == ERROR_SUCCESS) { - uint32 dataSize = 0; - result = RegQueryValueExA(openKey, value.c_str(), NULL, NULL, NULL, reinterpret_cast(&dataSize)); - - debugAssert(result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND); - RegCloseKey(openKey); - } - return (result == ERROR_SUCCESS); -} - - -bool RegistryUtil::readInt32(const std::string& key, const std::string& value, int32& data) { - size_t pos = key.find('\\', 0); - if (pos == std::string::npos) { - return false; - } - - HKEY hkey = getRootKeyFromString(key.c_str(), pos); - - if ( hkey == NULL ) { - return false; - } - - HKEY openKey; - int32 result = RegOpenKeyExA(hkey, (key.c_str() + pos + 1), 0, KEY_READ, &openKey); - debugAssert(result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND); - - if (result == ERROR_SUCCESS) { - uint32 dataSize = sizeof(int32); - result = RegQueryValueExA(openKey, value.c_str(), NULL, NULL, reinterpret_cast(&data), reinterpret_cast(&dataSize)); - - debugAssertM(result == ERROR_SUCCESS, "Could not read registry key value."); - - RegCloseKey(openKey); - } - return (result == ERROR_SUCCESS); -} - -bool RegistryUtil::readBytes(const std::string& key, const std::string& value, uint8* data, uint32& dataSize) { - size_t pos = key.find('\\', 0); - if (pos == std::string::npos) { - return false; - } - - HKEY hkey = getRootKeyFromString(key.c_str(), pos); - - if (hkey == NULL) { - return false; - } - - HKEY openKey; - int32 result = RegOpenKeyExA(hkey, (key.c_str() + pos + 1), 0, KEY_READ, &openKey); - debugAssert(result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND); - - if (result == ERROR_SUCCESS) { - if (data == NULL) { - result = RegQueryValueExA(openKey, value.c_str(), NULL, NULL, NULL, reinterpret_cast(&dataSize)); - } else { - result = RegQueryValueExA(openKey, value.c_str(), NULL, NULL, reinterpret_cast(&data), reinterpret_cast(&dataSize)); - } - - debugAssertM(result == ERROR_SUCCESS, "Could not read registry key value."); - - RegCloseKey(openKey); - } - return (result == ERROR_SUCCESS); -} - -bool RegistryUtil::readString(const std::string& key, const std::string& value, std::string& data) { - size_t pos = key.find('\\', 0); - if (pos == std::string::npos) { - return false; - } - - HKEY hkey = getRootKeyFromString(key.c_str(), pos); - - if (hkey == NULL) { - return false; - } - - HKEY openKey; - int32 result = RegOpenKeyExA(hkey, (key.c_str() + pos + 1), 0, KEY_READ, &openKey); - debugAssert(result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND); - - if (result == ERROR_SUCCESS) { - uint32 dataSize = 0; - - result = RegQueryValueExA(openKey, value.c_str(), NULL, NULL, NULL, reinterpret_cast(&dataSize)); - debugAssertM(result == ERROR_SUCCESS, "Could not read registry key value."); - - // increment datasize to allow for non null-terminated strings in registry - dataSize += 1; - - if (result == ERROR_SUCCESS) { - char* tmpStr = static_cast(System::malloc(dataSize)); - System::memset(tmpStr, 0, dataSize); - - result = RegQueryValueExA(openKey, value.c_str(), NULL, NULL, reinterpret_cast(tmpStr), reinterpret_cast(&dataSize)); - debugAssertM(result == ERROR_SUCCESS, "Could not read registry key value."); - - if (result == ERROR_SUCCESS) { - data = tmpStr; - } - - RegCloseKey(openKey); - System::free(tmpStr); - } - } - return (result == ERROR_SUCCESS); -} - -bool RegistryUtil::writeInt32(const std::string& key, const std::string& value, int32 data) { - size_t pos = key.find('\\', 0); - if (pos == std::string::npos) { - return false; - } - - HKEY hkey = getRootKeyFromString(key.c_str(), pos); - - if (hkey == NULL) { - return false; - } - - HKEY openKey; - int32 result = RegOpenKeyExA(hkey, (key.c_str() + pos + 1), 0, KEY_WRITE, &openKey); - debugAssert(result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND); - - if (result == ERROR_SUCCESS) { - result = RegSetValueExA(openKey, value.c_str(), 0, REG_DWORD, reinterpret_cast(&data), sizeof(int32)); - - debugAssertM(result == ERROR_SUCCESS, "Could not write registry key value."); - - RegCloseKey(openKey); - } - return (result == ERROR_SUCCESS); -} - -bool RegistryUtil::writeBytes(const std::string& key, const std::string& value, const uint8* data, uint32 dataSize) { - debugAssert(data); - - size_t pos = key.find('\\', 0); - if (pos == std::string::npos) { - return false; - } - - HKEY hkey = getRootKeyFromString(key.c_str(), pos); - - if (hkey == NULL) { - return false; - } - - HKEY openKey; - int32 result = RegOpenKeyExA(hkey, (key.c_str() + pos + 1), 0, KEY_WRITE, &openKey); - debugAssert(result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND); - - if (result == ERROR_SUCCESS) { - if (data) { - result = RegSetValueExA(openKey, value.c_str(), 0, REG_BINARY, reinterpret_cast(data), dataSize); - } - - debugAssertM(result == ERROR_SUCCESS, "Could not write registry key value."); - - RegCloseKey(openKey); - } - return (result == ERROR_SUCCESS); -} - -bool RegistryUtil::writeString(const std::string& key, const std::string& value, const std::string& data) { - size_t pos = key.find('\\', 0); - if (pos == std::string::npos) { - return false; - } - - HKEY hkey = getRootKeyFromString(key.c_str(), pos); - - if (hkey == NULL) { - return false; - } - - HKEY openKey; - int32 result = RegOpenKeyExA(hkey, (key.c_str() + pos + 1), 0, KEY_WRITE, &openKey); - debugAssert(result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND); - - if (result == ERROR_SUCCESS) { - result = RegSetValueExA(openKey, value.c_str(), 0, REG_SZ, reinterpret_cast(data.c_str()), (data.size() + 1)); - debugAssertM(result == ERROR_SUCCESS, "Could not write registry key value."); - - RegCloseKey(openKey); - } - return (result == ERROR_SUCCESS); -} - - -// static helpers -static HKEY getRootKeyFromString(const char* str, size_t length) { - debugAssert(str); - - if (str) { - if ( strncmp(str, "HKEY_CLASSES_ROOT", length) == 0 ) { - return HKEY_CLASSES_ROOT; - } else if ( strncmp(str, "HKEY_CURRENT_CONFIG", length) == 0 ) { - return HKEY_CURRENT_CONFIG; - } else if ( strncmp(str, "HKEY_CURRENT_USER", length) == 0 ) { - return HKEY_CURRENT_USER; - } else if ( strncmp(str, "HKEY_LOCAL_MACHINE", length) == 0 ) { - return HKEY_LOCAL_MACHINE; - } else if ( strncmp(str, "HKEY_PERFORMANCE_DATA", length) == 0 ) { - return HKEY_PERFORMANCE_DATA; - } else if ( strncmp(str, "HKEY_PERFORMANCE_NLSTEXT", length) == 0 ) { - return HKEY_PERFORMANCE_NLSTEXT; - } else if ( strncmp(str, "HKEY_PERFORMANCE_TEXT", length) == 0 ) { - return HKEY_PERFORMANCE_TEXT; - } else if ( strncmp(str, "HKEY_CLASSES_ROOT", length) == 0 ) { - return HKEY_CLASSES_ROOT; - } else { - return NULL; - } - } else { - return NULL; - } -} - -} // namespace G3D - -#endif // G3D_WIN32 diff --git a/externals/g3dlite/Sphere.cpp b/externals/g3dlite/Sphere.cpp deleted file mode 100644 index 4ed0811cb29..00000000000 --- a/externals/g3dlite/Sphere.cpp +++ /dev/null @@ -1,223 +0,0 @@ -/** - @file Sphere.cpp - - Sphere class - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2001-04-17 - @edited 2009-01-20 - */ - -#include "G3D/platform.h" -#include "G3D/Sphere.h" -#include "G3D/stringutils.h" -#include "G3D/BinaryOutput.h" -#include "G3D/BinaryInput.h" -#include "G3D/AABox.h" -#include "G3D/Plane.h" - -namespace G3D { - -int32 Sphere::dummy; - -Sphere::Sphere(class BinaryInput& b) { - deserialize(b); -} - - -void Sphere::serialize(class BinaryOutput& b) const { - center.serialize(b); - b.writeFloat64(radius); -} - - -void Sphere::deserialize(class BinaryInput& b) { - center.deserialize(b); - radius = (float)b.readFloat64(); -} - - -std::string Sphere::toString() const { - return format("Sphere(<%g, %g, %g>, %g)", - center.x, center.y, center.z, radius); -} - - -bool Sphere::contains(const Vector3& point) const { - float distance = (center - point).squaredMagnitude(); - return distance <= square(radius); -} - - -bool Sphere::contains(const Sphere& other) const { - float distance = (center - other.center).squaredMagnitude(); - return (radius >= other.radius) && (distance <= square(radius - other.radius)); -} - - -bool Sphere::intersects(const Sphere& other) const { - return (other.center - center).length() <= (radius + other.radius); -} - - -void Sphere::merge(const Sphere& other) { - if (other.contains(*this)) { - *this = other; - } else if (! contains(other)) { - // The farthest distance is along the axis between the centers, which - // must not be colocated since neither contains the other. - Vector3 toMe = center - other.center; - // Get a point on the axis from each - toMe = toMe.direction(); - const Vector3& A = center + toMe * radius; - const Vector3& B = other.center - toMe * other.radius; - - // Now just bound the A->B segment - center = (A + B) * 0.5f; - radius = (A - B).length(); - } - // (if this contains other, we're done) -} - - -bool Sphere::culledBy( - const Array& plane, - int& cullingPlaneIndex, - const uint32 inMask, - uint32& outMask) const { - - return culledBy(plane.getCArray(), plane.size(), cullingPlaneIndex, inMask, outMask); -} - - -bool Sphere::culledBy( - const Array& plane, - int& cullingPlaneIndex, - const uint32 inMask) const { - - return culledBy(plane.getCArray(), plane.size(), cullingPlaneIndex, inMask); -} - - -bool Sphere::culledBy( - const class Plane* plane, - int numPlanes, - int& cullingPlane, - const uint32 _inMask, - uint32& childMask) const { - - if (radius == finf()) { - // No plane can cull the infinite box - return false; - } - - uint32 inMask = _inMask; - assert(numPlanes < 31); - - childMask = 0; - - // See if there is one plane for which all of the - // vertices are in the negative half space. - for (int p = 0; p < numPlanes; p++) { - - // Only test planes that are not masked - if ((inMask & 1) != 0) { - - bool culledLow = ! plane[p].halfSpaceContainsFinite(center + plane[p].normal() * radius); - bool culledHigh = ! plane[p].halfSpaceContainsFinite(center - plane[p].normal() * radius); - - if (culledLow) { - // Plane p culled the sphere - cullingPlane = p; - - // The caller should not recurse into the children, - // since the parent is culled. If they do recurse, - // make them only test against this one plane, which - // will immediately cull the volume. - childMask = 1 << p; - return true; - - } else if (culledHigh) { - // The bounding volume straddled the plane; we have - // to keep testing against this plane - childMask |= (1 << p); - } - } - - // Move on to the next bit. - inMask = inMask >> 1; - } - - // None of the planes could cull this box - cullingPlane = -1; - return false; -} - - -bool Sphere::culledBy( - const class Plane* plane, - int numPlanes, - int& cullingPlane, - const uint32 _inMask) const { - - uint32 inMask = _inMask; - assert(numPlanes < 31); - - // See if there is one plane for which all of the - // vertices are in the negative half space. - for (int p = 0; p < numPlanes; p++) { - - // Only test planes that are not masked - if ((inMask & 1) != 0) { - bool culled = ! plane[p].halfSpaceContains(center + plane[p].normal() * radius); - if (culled) { - // Plane p culled the sphere - cullingPlane = p; - return true; - } - } - - // Move on to the next bit. - inMask = inMask >> 1; - } - - // None of the planes could cull this box - cullingPlane = -1; - return false; -} - - -Vector3 Sphere::randomSurfacePoint() const { - return Vector3::random() * radius + center; -} - - -Vector3 Sphere::randomInteriorPoint() const { - Vector3 result; - do { - result = Vector3(uniformRandom(-1, 1), - uniformRandom(-1, 1), - uniformRandom(-1, 1)); - } while (result.squaredMagnitude() >= 1.0f); - - return result * radius + center; -} - - -float Sphere::volume() const { - return (float)pi() * (4.0f / 3.0f) * powf((float)radius, 3.0f); -} - - -float Sphere::area() const { - return (float)pi() * 4.0f * powf((float)radius, 2.0f); -} - - -void Sphere::getBounds(AABox& out) const { - Vector3 extent(radius, radius, radius); - out = AABox(center - extent, center + extent); -} - -} // namespace diff --git a/externals/g3dlite/System.cpp b/externals/g3dlite/System.cpp deleted file mode 100644 index e03c4e8c6fa..00000000000 --- a/externals/g3dlite/System.cpp +++ /dev/null @@ -1,1746 +0,0 @@ -/** - @file System.cpp - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - Note: every routine must call init() first. - - There are two kinds of detection used in this file. At compile - time, the _MSC_VER #define is used to determine whether x86 assembly - can be used at all. At runtime, processor detection is used to - determine if we can safely call the routines that use that assembly. - - @created 2003-01-25 - @edited 2010-01-03 - */ - -#include "G3D/platform.h" -#include "G3D/System.h" -#include "G3D/debug.h" -#include "G3D/fileutils.h" -#include "G3D/TextOutput.h" -#include "G3D/G3DGameUnits.h" -#include "G3D/Crypto.h" -#include "G3D/prompt.h" -#include "G3D/stringutils.h" -#include "G3D/Log.h" -#include "G3D/Table.h" -#include "G3D/GMutex.h" -#include "G3D/units.h" -#include - -#include -#include - -// Uncomment the following line to turn off G3D::System memory -// allocation and use the operating system's malloc. -//#define NO_BUFFERPOOL - -#if defined(__i386__) || defined(__x86_64__) || defined(G3D_WIN32) -# define G3D_NOT_OSX_PPC -#endif - -#include - -#ifdef G3D_WIN32 - -# include -# include -# include "G3D/RegistryUtil.h" - -#elif defined(G3D_LINUX) - -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include - -#elif defined(G3D_OSX) - - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - - #include - #include -#endif - -// SIMM include -#ifdef __SSE__ -#include -#endif - -namespace G3D { - - -/** Checks if the CPUID command is available on the processor (called from init) */ -static bool checkForCPUID(); - -/** Called from init */ -static void getG3DVersion(std::string& s); - -/** Called from init */ -static G3DEndian checkEndian(); - - -System& System::instance() { - static System thesystem; - return thesystem; -} - - -System::System() : - m_initialized(false), - m_cpuSpeed(0), - m_hasCPUID(false), - m_hasRDTSC(false), - m_hasMMX(false), - m_hasSSE(false), - m_hasSSE2(false), - m_hasSSE3(false), - m_has3DNOW(false), - m_has3DNOW2(false), - m_hasAMDMMX(false), - m_cpuVendor("Uninitialized"), - m_numCores(1), - m_machineEndian(G3D_LITTLE_ENDIAN), - m_cpuArch("Uninitialized"), - m_operatingSystem("Uninitialized"), - m_version("Uninitialized"), - m_outOfMemoryCallback(NULL), - m_realWorldGetTickTime0(0), - m_highestCPUIDFunction(0) { - - init(); -} - - -void System::init() { - // NOTE: Cannot use most G3D data structures or utility functions - // in here because they are not initialized. - - if (m_initialized) { - return; - } else { - m_initialized = true; - } - - getG3DVersion(m_version); - - m_machineEndian = checkEndian(); - - m_hasCPUID = checkForCPUID(); - // Process the CPUID information - if (m_hasCPUID) { - // We read the standard CPUID level 0x00000000 which should - // be available on every x86 processor. This fills out - // a string with the processor vendor tag. - unsigned int eaxreg = 0, ebxreg = 0, ecxreg = 0, edxreg = 0; - - cpuid(CPUID_VENDOR_ID, eaxreg, ebxreg, ecxreg, edxreg); - - { - char c[100]; - // Then we connect the single register values to the vendor string - *((unsigned int*) c) = ebxreg; - *((unsigned int*) (c + 4)) = edxreg; - *((unsigned int*) (c + 8)) = ecxreg; - c[12] = '\0'; - m_cpuVendor = c; - } - - switch (ebxreg) { - case 0x756E6547: // GenuineIntel - m_cpuArch = "Intel Processor"; - break; - - case 0x68747541: // AuthenticAMD - m_cpuArch = "AMD Processor"; - break; - - case 0x69727943: // CyrixInstead - m_cpuArch = "Cyrix Processor"; - break; - - default: - m_cpuArch = "Unknown Processor Vendor"; - break; - } - - - unsigned int highestFunction = eaxreg; - if (highestFunction >= CPUID_NUM_CORES) { - cpuid(CPUID_NUM_CORES, eaxreg, ebxreg, ecxreg, edxreg); - // Number of cores is in (eax>>26) + 1 - m_numCores = (eaxreg >> 26) + 1; - } - - cpuid(CPUID_GET_HIGHEST_FUNCTION, m_highestCPUIDFunction, ebxreg, ecxreg, edxreg); - } - - - // Get the operating system name (also happens to read some other information) -# ifdef G3D_WIN32 - // Note that this overrides some of the values computed above - bool success = RegistryUtil::readInt32 - ("HKEY_LOCAL_MACHINE\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", - "~MHz", m_cpuSpeed); - - SYSTEM_INFO systemInfo; - GetSystemInfo(&systemInfo); - const char* arch = NULL; - switch (systemInfo.wProcessorArchitecture) { - case PROCESSOR_ARCHITECTURE_INTEL: - arch = "Intel"; - break; - - case PROCESSOR_ARCHITECTURE_MIPS: - arch = "MIPS"; - break; - - case PROCESSOR_ARCHITECTURE_ALPHA: - arch = "Alpha"; - break; - - case PROCESSOR_ARCHITECTURE_PPC: - arch = "Power PC"; - break; - - default: - arch = "Unknown"; - } - - m_numCores = systemInfo.dwNumberOfProcessors; - uint32 maxAddr = (uint32)systemInfo.lpMaximumApplicationAddress; - { - char c[1024]; - sprintf(c, "%d x %d-bit %s processor", - systemInfo.dwNumberOfProcessors, - (int)(::log((double)maxAddr) / ::log(2.0) + 2.0), - arch); - m_cpuArch = c; - } - - OSVERSIONINFO osVersionInfo; - osVersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); - success = GetVersionEx(&osVersionInfo) != 0; - - if (success) { - char c[1000]; - sprintf(c, "Windows %d.%d build %d Platform %d %s", - osVersionInfo.dwMajorVersion, - osVersionInfo.dwMinorVersion, - osVersionInfo.dwBuildNumber, - osVersionInfo.dwPlatformId, - osVersionInfo.szCSDVersion); - m_operatingSystem = c; - } else { - m_operatingSystem = "Windows"; - } - -# elif defined(G3D_LINUX) || defined(G3D_FREEBSD) - - { - // Find the operating system using the 'uname' command - FILE* f = popen("uname -a", "r"); - - int len = 100; - char* r = (char*)::malloc(len * sizeof(char)); - fgets(r, len, f); - // Remove trailing newline - if (r[strlen(r) - 1] == '\n') { - r[strlen(r) - 1] = '\0'; - } - fclose(f); - - m_operatingSystem = r; - ::free(r); - } - -# elif defined(G3D_OSX) - - // Operating System: - SInt32 macVersion; - Gestalt(gestaltSystemVersion, &macVersion); - - int major = (macVersion >> 8) & 0xFF; - int minor = (macVersion >> 4) & 0xF; - int revision = macVersion & 0xF; - - { - char c[1000]; - sprintf(c, "OS X %x.%x.%x", major, minor, revision); - m_operatingSystem = c; - } - - // Clock Cycle Timing Information: - Gestalt('pclk', &m_OSXCPUSpeed); - m_cpuSpeed = iRound((double)m_OSXCPUSpeed / (1024 * 1024)); - m_secondsPerNS = 1.0 / 1.0e9; - - // System Architecture: - const NXArchInfo* pInfo = NXGetLocalArchInfo(); - - if (pInfo) { - m_cpuArch = pInfo->description; - - switch (pInfo->cputype) { - case CPU_TYPE_POWERPC: - switch(pInfo->cpusubtype){ - case CPU_SUBTYPE_POWERPC_750: - case CPU_SUBTYPE_POWERPC_7400: - case CPU_SUBTYPE_POWERPC_7450: - m_cpuVendor = "Motorola"; - break; - case CPU_SUBTYPE_POWERPC_970: - m_cpuVendor = "IBM"; - break; - } - break; - - case CPU_TYPE_I386: - m_cpuVendor = "Intel"; - break; - } - } -# endif - - initTime(); - - getStandardProcessorExtensions(); -} - - -void getG3DVersion(std::string& s) { - char cstr[100]; - if ((G3D_VER % 100) != 0) { - sprintf(cstr, "G3D %d.%02d beta %d", - G3D_VER / 10000, - (G3D_VER / 100) % 100, - G3D_VER % 100); - } else { - sprintf(cstr, "G3D %d.%02d", - G3D_VER / 10000, - (G3D_VER / 100) % 100); - } - s = cstr; -} - -#if 0 // TODO: delete -struct Directory { - std::string path; - Array contents; -}; - -static bool maybeAddDirectory(const std::string& newPath, Array& directoryArray, bool recurse = true) { - if (fileExists(newPath)) { - Directory& d = directoryArray.next(); - d.path = newPath; - getFiles(pathConcat(newPath, "*"), d.contents); - Array dirs; - getDirs(pathConcat(newPath, "*"), dirs); - d.contents.append(dirs); - - if (recurse) { - // Look for subdirectories - static const std::string subdirs[] = - {"font", "gui", "SuperShader", "cubemap", "icon", "material", "image", "md2", "md3", "ifs", "3ds", "sky", ""}; - - for (int j = 0; j < dirs.size(); ++j) { - for (int i = 0; ! subdirs[i].empty(); ++i) { - if (dirs[j] == subdirs[i]) { - maybeAddDirectory(pathConcat(newPath, dirs[j]), directoryArray, false); - } - } - } - } - return true; - } else { - return false; - } -} -#endif - -std::string System::findDataFile -(const std::string& full, - bool errorIfNotFound) { - - // Places where specific files were most recently found. This is - // used to cache seeking of common files. - static Table lastFound; - - // First check if the file exists as requested. This will go - // through the FileSystemCache, so most calls do not touch disk. - if (fileExists(full)) { - return full; - } - - // Now check where we previously found this file. - std::string* last = lastFound.getPointer(full); - if (last != NULL) { - if (fileExists(*last)) { - // Even if cwd has changed the file is still present. - // We won't notice if it has been deleted, however. - return *last; - } else { - // Remove this from the cache it is invalid - lastFound.remove(full); - } - } - - // Places to look - static Array directoryArray; - - if (directoryArray.size() == 0) { - // Initialize the directory array - RealTime t0 = System::time(); - - Array baseDirArray; - - std::string initialAppDataDir(instance().m_appDataDir); - - baseDirArray.append(""); - if (! initialAppDataDir.empty()) { - baseDirArray.append(initialAppDataDir); - } - - const char* g3dPath = getenv("G3DDATA"); - - if (g3dPath && (initialAppDataDir != g3dPath)) { - baseDirArray.append(g3dPath); - } - - static const std::string subdirs[] = - {"font", "gui", "SuperShader", "cubemap", "icon", "material", "image", "md2", "md3", "ifs", "3ds", "sky", ""}; - for (int j = 0; j < baseDirArray.size(); ++j) { - std::string d = baseDirArray[j]; - if (fileExists(d)) { - directoryArray.append(d); - for (int i = 0; ! subdirs[i].empty(); ++i) { - const std::string& p = pathConcat(d, subdirs[i]); - if (fileExists(p)) { - directoryArray.append(p); - } - } - } - } - - logLazyPrintf("Initializing System::findDataFile took %fs\n", System::time() - t0); - } - - for (int i = 0; i < directoryArray.size(); ++i) { - const std::string& p = pathConcat(directoryArray[i], full); - if (fileExists(p)) { - lastFound.set(full, p); - return p; - } - } - - if (errorIfNotFound) { - // Generate an error message - std::string locations; - for (int i = 0; i < directoryArray.size(); ++i) { - locations += pathConcat(directoryArray[i], full) + "\n"; - } - alwaysAssertM(false, "Could not find '" + full + "' in:\n" + locations); - } - - // Not found - return ""; -} - - -void System::setAppDataDir(const std::string& path) { - instance().m_appDataDir = path; -} - - -std::string demoFindData(bool errorIfNotFound) { - static const char* g3dPath = getenv("G3DDATA"); - if (g3dPath) { - return g3dPath; -# ifdef G3D_WIN32 - } else if (fileExists("../data")) { - // G3D install on Windows - return "../data"; - } else if (fileExists("../data-files")) { - // G3D source on Windows - return "../data-files"; -# else - } else if (fileExists("../../../../data")) { - // G3D install on Unix - return "../../../../data"; - } else if (fileExists("../../../../data-files")) { - // G3D source on Unix - return "../../../../data-files"; -# endif - } else { - return ""; - } -} - - -const std::string& System::build() { - const static std::string b = -# ifdef _DEBUG - "Debug"; -# else - "Release"; -# endif - - return b; -} - - -static G3DEndian checkEndian() { - int32 a = 1; - if (*(uint8*)&a == 1) { - return G3D_LITTLE_ENDIAN; - } else { - return G3D_BIG_ENDIAN; - } -} - - -static bool checkForCPUID() { - // all known supported architectures have cpuid - // add cases for incompatible architectures if they are added - // e.g., if we ever support __powerpc__ being defined again - - return true; -} - - -void System::getStandardProcessorExtensions() { -#if ! defined(G3D_OSX) || defined(G3D_OSX_INTEL) - if (! m_hasCPUID) { - return; - } - - uint32 eaxreg = 0, ebxreg = 0, ecxreg = 0, features = 0; - - cpuid(CPUID_PROCESSOR_FEATURES, eaxreg, ebxreg, ecxreg, features); - -# define checkBit(var, bit) ((var & (1 << bit)) ? true : false) - - m_hasRDTSC = checkBit(features, 4); - m_hasMMX = checkBit(features, 23); - m_hasSSE = checkBit(features, 25); - m_hasSSE2 = checkBit(features, 26); - // Bit 28 is HTT; not checked by G3D - - m_hasSSE3 = checkBit(ecxreg, 0); - - if (m_highestCPUIDFunction >= CPUID_EXTENDED_FEATURES) { - cpuid(CPUID_EXTENDED_FEATURES, eaxreg, ebxreg, ecxreg, features); - m_hasAMDMMX = checkBit(features, 22); // Only on AMD - m_has3DNOW = checkBit(features, 31); // Only on AMD - m_has3DNOW2 = checkBit(features, 30); // Only on AMD - } else { - m_hasAMDMMX = false; - m_has3DNOW = false; - m_has3DNOW2 = false; - } - -# undef checkBit -#endif -} - -#if defined(G3D_WIN32) && !defined(G3D_64BIT) - #pragma message("Port System::memcpy SIMD to all platforms") -/** Michael Herf's fast memcpy */ -void memcpyMMX(void* dst, const void* src, int nbytes) { - int remainingBytes = nbytes; - - if (nbytes > 64) { - _asm { - mov esi, src - mov edi, dst - mov ecx, nbytes - shr ecx, 6 // 64 bytes per iteration - - loop1: - movq mm1, 0[ESI] // Read in source data - movq mm2, 8[ESI] - movq mm3, 16[ESI] - movq mm4, 24[ESI] - movq mm5, 32[ESI] - movq mm6, 40[ESI] - movq mm7, 48[ESI] - movq mm0, 56[ESI] - - movntq 0[EDI], mm1 // Non-temporal stores - movntq 8[EDI], mm2 - movntq 16[EDI], mm3 - movntq 24[EDI], mm4 - movntq 32[EDI], mm5 - movntq 40[EDI], mm6 - movntq 48[EDI], mm7 - movntq 56[EDI], mm0 - - add esi, 64 - add edi, 64 - dec ecx - jnz loop1 - - emms - } - remainingBytes -= ((nbytes >> 6) << 6); - } - - if (remainingBytes > 0) { - // Memcpy the rest - memcpy((uint8*)dst + (nbytes - remainingBytes), - (const uint8*)src + (nbytes - remainingBytes), remainingBytes); - } -} -#endif - -void System::memcpy(void* dst, const void* src, size_t numBytes) { -#if defined(G3D_WIN32) && !defined(G3D_64BIT) - memcpyMMX(dst, src, numBytes); -#else - ::memcpy(dst, src, numBytes); -#endif -} - - -/** Michael Herf's fastest memset. n32 must be filled with the same - character repeated. */ -#if defined(G3D_WIN32) && !defined(G3D_64BIT) - #pragma message("Port System::memfill SIMD to all platforms") - -// On x86 processors, use MMX -void memfill(void *dst, int n32, unsigned long i) { - - int originalSize = i; - int bytesRemaining = i; - - if (i > 16) { - - bytesRemaining = i % 16; - i -= bytesRemaining; - __asm { - movq mm0, n32 - punpckldq mm0, mm0 - mov edi, dst - - loopwrite: - - movntq 0[edi], mm0 - movntq 8[edi], mm0 - - add edi, 16 - sub i, 16 - jg loopwrite - - emms - } - } - - if (bytesRemaining > 0) { - ::memset((uint8*)dst + (originalSize - bytesRemaining), n32, bytesRemaining); - } -} -#endif - - -void System::memset(void* dst, uint8 value, size_t numBytes) { -#if defined(G3D_WIN32) && !defined(G3D_64BIT) - uint32 v = value; - v = v + (v << 8) + (v << 16) + (v << 24); - G3D::memfill(dst, v, numBytes); -#else - ::memset(dst, value, numBytes); -#endif -} - - -/** Removes the 'd' that icompile / Morgan's VC convention appends. */ -static std::string computeAppName(const std::string& start) { - if (start.size() < 2) { - return start; - } - - if (start[start.size() - 1] == 'd') { - // Maybe remove the 'd'; see if ../ or ../../ has the same name - char tmp[1024]; - getcwd(tmp, sizeof(tmp)); - std::string drive, base, ext; - Array path; - parseFilename(tmp, drive, path, base, ext); - - std::string shortName = start.substr(0, start.size() - 1); - - if ((path.size() > 1) && (toLower(path.last()) == toLower(shortName))) { - return shortName; - } - - if ((path.size() > 2) && (toLower(path[path.size() - 2]) == toLower(shortName))) { - return shortName; - } - } - - return start; -} - - -std::string& System::appName() { - static std::string n = computeAppName(filenameBase(currentProgramFilename())); - return n; -} - - -std::string System::currentProgramFilename() { - char filename[2048]; - -# ifdef G3D_WIN32 - { - GetModuleFileNameA(NULL, filename, sizeof(filename)); - } -# elif defined(G3D_OSX) - { - // Run the 'ps' program to extract the program name - // from the process ID. - int pid; - FILE* fd; - char cmd[80]; - pid = getpid(); - sprintf(cmd, "ps -p %d -o comm=\"\"", pid); - - fd = popen(cmd, "r"); - int s = fread(filename, 1, sizeof(filename), fd); - // filename will contain a newline. Overwrite it: - filename[s - 1] = '\0'; - } -# else - { - int ret = readlink("/proc/self/exe", filename, sizeof(filename)); - - // In case of an error, leave the handling up to the caller - if (ret == -1) { - return ""; - } - - debugAssert((int)sizeof(filename) > ret); - - // Ensure proper NULL termination - filename[ret] = 0; - } - #endif - - return filename; -} - - -void System::sleep(RealTime t) { - - // Overhead of calling this function, measured from a previous run. - static const RealTime OVERHEAD = 0.00006f; - - RealTime now = time(); - RealTime wakeupTime = now + t - OVERHEAD; - - RealTime remainingTime = wakeupTime - now; - RealTime sleepTime = 0; - - // On Windows, a "time slice" is measured in quanta of 3-5 ms (http://support.microsoft.com/kb/259025) - // Sleep(0) yields the remainder of the time slice, which could be a long time. - // A 1 ms minimum time experimentally kept the "Empty GApp" at nearly no CPU load at 100 fps, - // yet nailed the frame timing perfectly. - static RealTime minRealSleepTime = 3 * units::milliseconds(); - - while (remainingTime > 0) { - - if (remainingTime > minRealSleepTime * 2.5) { - // Safe to use Sleep with a time... sleep for half the remaining time - sleepTime = max(remainingTime * 0.5, 0.0005); - } else if (remainingTime > minRealSleepTime) { - // Safe to use Sleep with a zero time; - // causes the program to yield only - // the current time slice, and then return. - sleepTime = 0; - } else { - // Not safe to use Sleep; busy wait - sleepTime = -1; - } - - if (sleepTime >= 0) { - #ifdef G3D_WIN32 - // Translate to milliseconds - Sleep((int)(sleepTime * 1e3)); - #else - // Translate to microseconds - usleep((int)(sleepTime * 1e6)); - #endif - } - - now = time(); - remainingTime = wakeupTime - now; - } -} - - -void System::consoleClearScreen() { -# ifdef G3D_WIN32 - system("cls"); -# else - system("clear"); -# endif -} - - -bool System::consoleKeyPressed() { - #ifdef G3D_WIN32 - - return _kbhit() != 0; - - #else - - static const int STDIN = 0; - static bool initialized = false; - - if (! initialized) { - // Use termios to turn off line buffering - termios term; - tcgetattr(STDIN, &term); - term.c_lflag &= ~ICANON; - tcsetattr(STDIN, TCSANOW, &term); - setbuf(stdin, NULL); - initialized = true; - } - - #ifdef G3D_LINUX - - int bytesWaiting; - ioctl(STDIN, FIONREAD, &bytesWaiting); - return bytesWaiting; - - #else - - timeval timeout; - fd_set rdset; - - FD_ZERO(&rdset); - FD_SET(STDIN, &rdset); - timeout.tv_sec = 0; - timeout.tv_usec = 0; - - return select(STDIN + 1, &rdset, NULL, NULL, &timeout); - #endif - #endif -} - - -int System::consoleReadKey() { -# ifdef G3D_WIN32 - return _getch(); -# else - char c; - read(0, &c, 1); - return c; -# endif -} - - -void System::initTime() { - #ifdef G3D_WIN32 - if (QueryPerformanceFrequency(&m_counterFrequency)) { - QueryPerformanceCounter(&m_start); - } - - struct _timeb t; - _ftime(&t); - - m_realWorldGetTickTime0 = (RealTime)t.time - t.timezone * G3D::MINUTE + (t.dstflag ? G3D::HOUR : 0); - - #else - gettimeofday(&m_start, NULL); - // "sse" = "seconds since epoch". The time - // function returns the seconds since the epoch - // GMT (perhaps more correctly called UTC). - time_t gmt = ::time(NULL); - - // No call to free or delete is needed, but subsequent - // calls to asctime, ctime, mktime, etc. might overwrite - // local_time_vals. - tm* localTimeVals = localtime(&gmt); - - time_t local = gmt; - - if (localTimeVals) { - // tm_gmtoff is already corrected for daylight savings. - local = local + localTimeVals->tm_gmtoff; - } - - m_realWorldGetTickTime0 = local; - #endif -} - - -RealTime System::time() { -# ifdef G3D_WIN32 - LARGE_INTEGER now; - QueryPerformanceCounter(&now); - - return ((RealTime)(now.QuadPart - instance().m_start.QuadPart) / - instance().m_counterFrequency.QuadPart) + instance().m_realWorldGetTickTime0; -# else - // Linux resolution defaults to 100Hz. - // There is no need to do a separate RDTSC call as gettimeofday - // actually uses RDTSC when on systems that support it, otherwise - // it uses the system clock. - struct timeval now; - gettimeofday(&now, NULL); - - return (now.tv_sec - instance().m_start.tv_sec) + - (now.tv_usec - instance().m_start.tv_usec) / 1e6 - + instance().m_realWorldGetTickTime0; -# endif -} - - -//////////////////////////////////////////////////////////////// - -#define REALPTR_TO_USERPTR(x) ((uint8*)(x) + sizeof (void *)) -#define USERPTR_TO_REALPTR(x) ((uint8*)(x) - sizeof (void *)) -#define REALBLOCK_SIZE(x) ((x) + sizeof (void *)) - -class BufferPool { -public: - - /** Only store buffers up to these sizes (in bytes) in each pool-> - Different pools have different management strategies. - - A large block is preallocated for tiny buffers; they are used with - tremendous frequency. Other buffers are allocated as demanded. - Tiny buffers are 128 bytes long because that seems to align well with - cache sizes on many machines. - */ - enum {tinyBufferSize = 128, smallBufferSize = 1024, medBufferSize = 4096}; - - /** - Most buffers we're allowed to store. - 250000 * 128 = 32 MB (preallocated) - 10000 * 1024 = 10 MB (allocated on demand) - 1024 * 4096 = 4 MB (allocated on demand) - */ - enum {maxTinyBuffers = 250000, maxSmallBuffers = 10000, maxMedBuffers = 1024}; - -private: - - class MemBlock { - public: - void* ptr; - size_t bytes; - - inline MemBlock() : ptr(NULL), bytes(0) {} - inline MemBlock(void* p, size_t b) : ptr(p), bytes(b) {} - }; - - MemBlock smallPool[maxSmallBuffers]; - int smallPoolSize; - - MemBlock medPool[maxMedBuffers]; - int medPoolSize; - - /** The tiny pool is a single block of storage into which all tiny - objects are allocated. This provides better locality for - small objects and avoids the search time, since all tiny - blocks are exactly the same size. */ - void* tinyPool[maxTinyBuffers]; - int tinyPoolSize; - - /** Pointer to the data in the tiny pool */ - void* tinyHeap; - - Spinlock m_lock; - - void lock() { - m_lock.lock(); - } - - void unlock() { - m_lock.unlock(); - } - -#if 0 //-----------------------------------------------old mutex -# ifdef G3D_WIN32 - CRITICAL_SECTION mutex; -# else - pthread_mutex_t mutex; -# endif - - /** Provide synchronization between threads */ - void lock() { -# ifdef G3D_WIN32 - EnterCriticalSection(&mutex); -# else - pthread_mutex_lock(&mutex); -# endif - } - - void unlock() { -# ifdef G3D_WIN32 - LeaveCriticalSection(&mutex); -# else - pthread_mutex_unlock(&mutex); -# endif - } -#endif //-------------------------------------------old mutex - - /** - Malloc out of the tiny heap. Returns NULL if allocation failed. - */ - inline void* tinyMalloc(size_t bytes) { - // Note that we ignore the actual byte size - // and create a constant size block. - (void)bytes; - assert(tinyBufferSize >= bytes); - - void* ptr = NULL; - - if (tinyPoolSize > 0) { - --tinyPoolSize; - - // Return the old last pointer from the freelist - ptr = tinyPool[tinyPoolSize]; - -# ifdef G3D_DEBUG - if (tinyPoolSize > 0) { - assert(tinyPool[tinyPoolSize - 1] != ptr); - // "System::malloc heap corruption detected: " - // "the last two pointers on the freelist are identical (during tinyMalloc)."); - } -# endif - - // NULL out the entry to help detect corruption - tinyPool[tinyPoolSize] = NULL; - } - - return ptr; - } - - /** Returns true if this is a pointer into the tiny heap. */ - bool inTinyHeap(void* ptr) { - return - (ptr >= tinyHeap) && - (ptr < (uint8*)tinyHeap + maxTinyBuffers * tinyBufferSize); - } - - void tinyFree(void* ptr) { - assert(ptr); - assert(tinyPoolSize < maxTinyBuffers); - // "Tried to free a tiny pool buffer when the tiny pool freelist is full."); - -# ifdef G3D_DEBUG - if (tinyPoolSize > 0) { - void* prevOnHeap = tinyPool[tinyPoolSize - 1]; - assert(prevOnHeap != ptr); -// "System::malloc heap corruption detected: " -// "the last two pointers on the freelist are identical (during tinyFree)."); - } -# endif - - assert(tinyPool[tinyPoolSize] == NULL); - - // Put the pointer back into the free list - tinyPool[tinyPoolSize] = ptr; - ++tinyPoolSize; - - } - - void flushPool(MemBlock* pool, int& poolSize) { - for (int i = 0; i < poolSize; ++i) { - ::free(pool[i].ptr); - pool[i].ptr = NULL; - pool[i].bytes = 0; - } - poolSize = 0; - } - - - /** Allocate out of a specific pool-> Return NULL if no suitable - memory was found. - - */ - void* malloc(MemBlock* pool, int& poolSize, size_t bytes) { - - // OPT: find the smallest block that satisfies the request. - - // See if there's something we can use in the buffer pool-> - // Search backwards since usually we'll re-use the last one. - for (int i = (int)poolSize - 1; i >= 0; --i) { - if (pool[i].bytes >= bytes) { - // We found a suitable entry in the pool-> - - // No need to offset the pointer; it is already offset - void* ptr = pool[i].ptr; - - // Remove this element from the pool - --poolSize; - pool[i] = pool[poolSize]; - - return ptr; - } - } - - return NULL; - } - -public: - - /** Count of memory allocations that have occurred. */ - int totalMallocs; - int mallocsFromTinyPool; - int mallocsFromSmallPool; - int mallocsFromMedPool; - - /** Amount of memory currently allocated (according to the application). - This does not count the memory still remaining in the buffer pool, - but does count extra memory required for rounding off to the size - of a buffer. - Primarily useful for detecting leaks.*/ - // TODO: make me an atomic int! - volatile int bytesAllocated; - - BufferPool() { - totalMallocs = 0; - - mallocsFromTinyPool = 0; - mallocsFromSmallPool = 0; - mallocsFromMedPool = 0; - - bytesAllocated = true; - - tinyPoolSize = 0; - tinyHeap = NULL; - - smallPoolSize = 0; - - medPoolSize = 0; - - - // Initialize the tiny heap as a bunch of pointers into one - // pre-allocated buffer. - tinyHeap = ::malloc(maxTinyBuffers * tinyBufferSize); - for (int i = 0; i < maxTinyBuffers; ++i) { - tinyPool[i] = (uint8*)tinyHeap + (tinyBufferSize * i); - } - tinyPoolSize = maxTinyBuffers; - -#if 0 ///---------------------------------- old mutex -# ifdef G3D_WIN32 - InitializeCriticalSection(&mutex); -# else - pthread_mutex_init(&mutex, NULL); -# endif -#endif ///---------------------------------- old mutex - } - - - ~BufferPool() { - ::free(tinyHeap); -#if 0 //-------------------------------- old mutex -# ifdef G3D_WIN32 - DeleteCriticalSection(&mutex); -# else - // No destruction on pthreads -# endif -#endif //--------------------------------old mutex - } - - - void* realloc(void* ptr, size_t bytes) { - if (ptr == NULL) { - return malloc(bytes); - } - - if (inTinyHeap(ptr)) { - if (bytes <= tinyBufferSize) { - // The old pointer actually had enough space. - return ptr; - } else { - // Free the old pointer and malloc - - void* newPtr = malloc(bytes); - System::memcpy(newPtr, ptr, tinyBufferSize); - tinyFree(ptr); - return newPtr; - - } - } else { - // In one of our heaps. - - // See how big the block really was - size_t realSize = *(uint32*)USERPTR_TO_REALPTR(ptr); - if (bytes <= realSize) { - // The old block was big enough. - return ptr; - } - - // Need to reallocate - void* newPtr = malloc(bytes); - System::memcpy(newPtr, ptr, realSize); - free(ptr); - return newPtr; - } - } - - - void* malloc(size_t bytes) { - lock(); - ++totalMallocs; - - if (bytes <= tinyBufferSize) { - - void* ptr = tinyMalloc(bytes); - - if (ptr) { - ++mallocsFromTinyPool; - unlock(); - return ptr; - } - - } - - // Failure to allocate a tiny buffer is allowed to flow - // through to a small buffer - if (bytes <= smallBufferSize) { - - void* ptr = malloc(smallPool, smallPoolSize, bytes); - - if (ptr) { - ++mallocsFromSmallPool; - unlock(); - return ptr; - } - - } else if (bytes <= medBufferSize) { - // Note that a small allocation failure does *not* fall - // through into a medium allocation because that would - // waste the medium buffer's resources. - - void* ptr = malloc(medPool, medPoolSize, bytes); - - if (ptr) { - ++mallocsFromMedPool; - unlock(); - debugAssertM(ptr != NULL, "BufferPool::malloc returned NULL"); - return ptr; - } - } - - bytesAllocated += REALBLOCK_SIZE(bytes); - unlock(); - - // Heap allocate - - // Allocate 4 extra bytes for our size header (unfortunate, - // since malloc already added its own header). - void* ptr = ::malloc(REALBLOCK_SIZE(bytes)); - - if (ptr == NULL) { - // Flush memory pools to try and recover space - flushPool(smallPool, smallPoolSize); - flushPool(medPool, medPoolSize); - ptr = ::malloc(REALBLOCK_SIZE(bytes)); - } - - if (ptr == NULL) { - if ((System::outOfMemoryCallback() != NULL) && - (System::outOfMemoryCallback()(REALBLOCK_SIZE(bytes), true) == true)) { - // Re-attempt the malloc - ptr = ::malloc(REALBLOCK_SIZE(bytes)); - } - } - - if (ptr == NULL) { - if (System::outOfMemoryCallback() != NULL) { - // Notify the application - System::outOfMemoryCallback()(REALBLOCK_SIZE(bytes), false); - } -# ifdef G3D_DEBUG - debugPrintf("::malloc(%d) returned NULL\n", (int)REALBLOCK_SIZE(bytes)); -# endif - debugAssertM(ptr != NULL, - "::malloc returned NULL. Either the " - "operating system is out of memory or the " - "heap is corrupt."); - return NULL; - } - - *(uint32*)ptr = bytes; - - return REALPTR_TO_USERPTR(ptr); - } - - - void free(void* ptr) { - if (ptr == NULL) { - // Free does nothing on null pointers - return; - } - - assert(isValidPointer(ptr)); - - if (inTinyHeap(ptr)) { - lock(); - tinyFree(ptr); - unlock(); - return; - } - - uint32 bytes = *(uint32*)USERPTR_TO_REALPTR(ptr); - - lock(); - if (bytes <= smallBufferSize) { - if (smallPoolSize < maxSmallBuffers) { - smallPool[smallPoolSize] = MemBlock(ptr, bytes); - ++smallPoolSize; - unlock(); - return; - } - } else if (bytes <= medBufferSize) { - if (medPoolSize < maxMedBuffers) { - medPool[medPoolSize] = MemBlock(ptr, bytes); - ++medPoolSize; - unlock(); - return; - } - } - bytesAllocated -= REALBLOCK_SIZE(bytes); - unlock(); - - // Free; the buffer pools are full or this is too big to store. - ::free(USERPTR_TO_REALPTR(ptr)); - } - - std::string performance() const { - if (totalMallocs > 0) { - int pooled = mallocsFromTinyPool + - mallocsFromSmallPool + - mallocsFromMedPool; - - int total = totalMallocs; - - return format("malloc performance: %5.1f%% <= %db, %5.1f%% <= %db, " - "%5.1f%% <= %db, %5.1f%% > %db", - 100.0 * mallocsFromTinyPool / total, - BufferPool::tinyBufferSize, - 100.0 * mallocsFromSmallPool / total, - BufferPool::smallBufferSize, - 100.0 * mallocsFromMedPool / total, - BufferPool::medBufferSize, - 100.0 * (1.0 - (double)pooled / total), - BufferPool::medBufferSize); - } else { - return "No System::malloc calls made yet."; - } - } - - std::string status() const { - return format("preallocated shared buffers: %5d/%d x %db", - maxTinyBuffers - tinyPoolSize, maxTinyBuffers, tinyBufferSize); - } -}; - -// Dynamically allocated because we need to ensure that -// the buffer pool is still around when the last global variable -// is deallocated. -static BufferPool* bufferpool = NULL; - -std::string System::mallocPerformance() { -#ifndef NO_BUFFERPOOL - return bufferpool->performance(); -#else - return "NO_BUFFERPOOL"; -#endif -} - -std::string System::mallocStatus() { -#ifndef NO_BUFFERPOOL - return bufferpool->status(); -#else - return "NO_BUFFERPOOL"; -#endif -} - - -void System::resetMallocPerformanceCounters() { -#ifndef NO_BUFFERPOOL - bufferpool->totalMallocs = 0; - bufferpool->mallocsFromMedPool = 0; - bufferpool->mallocsFromSmallPool = 0; - bufferpool->mallocsFromTinyPool = 0; -#endif -} - - -#ifndef NO_BUFFERPOOL -inline void initMem() { - // Putting the test here ensures that the system is always - // initialized, even when globals are being allocated. - static bool initialized = false; - if (! initialized) { - bufferpool = new BufferPool(); - initialized = true; - } -} -#endif - - -void* System::malloc(size_t bytes) { -#ifndef NO_BUFFERPOOL - initMem(); - return bufferpool->malloc(bytes); -#else - return ::malloc(bytes); -#endif -} - -void* System::calloc(size_t n, size_t x) { -#ifndef NO_BUFFERPOOL - void* b = System::malloc(n * x); - debugAssertM(b != NULL, "System::malloc returned NULL"); - debugAssertM(isValidHeapPointer(b), "System::malloc returned an invalid pointer"); - System::memset(b, 0, n * x); - return b; -#else - return ::calloc(n, x); -#endif -} - - -void* System::realloc(void* block, size_t bytes) { -#ifndef NO_BUFFERPOOL - initMem(); - return bufferpool->realloc(block, bytes); -#else - return ::realloc(block, bytes); -#endif -} - - -void System::free(void* p) { -#ifndef NO_BUFFERPOOL - bufferpool->free(p); -#else - return ::free(p); -#endif -} - - -void* System::alignedMalloc(size_t bytes, size_t alignment) { - - alwaysAssertM(isPow2(alignment), "alignment must be a power of 2"); - - // We must align to at least a word boundary. - alignment = iMax(alignment, sizeof(void *)); - - // Pad the allocation size with the alignment size and the - // size of the redirect pointer. - size_t totalBytes = bytes + alignment + sizeof(void*); - - size_t truePtr = (size_t)System::malloc(totalBytes); - - if (truePtr == 0) { - // malloc returned NULL - return NULL; - } - - debugAssert(isValidHeapPointer((void*)truePtr)); - #ifdef G3D_WIN32 - // The blocks we return will not be valid Win32 debug heap - // pointers because they are offset - // debugAssert(_CrtIsValidPointer((void*)truePtr, totalBytes, TRUE) ); - #endif - - // The return pointer will be the next aligned location (we must at least - // leave space for the redirect pointer, however). - size_t alignedPtr = truePtr + sizeof(void*); - - // 2^n - 1 has the form 1111... in binary. - uint32 bitMask = (alignment - 1); - - // Advance forward until we reach an aligned location. - while ((alignedPtr & bitMask) != 0) { - alignedPtr += sizeof(void*); - } - - debugAssert(alignedPtr - truePtr + bytes <= totalBytes); - - // Immediately before the aligned location, write the true array location - // so that we can free it correctly. - size_t* redirectPtr = (size_t *)(alignedPtr - sizeof(void *)); - redirectPtr[0] = truePtr; - - debugAssert(isValidHeapPointer((void*)truePtr)); - - #ifdef G3D_WIN32 - debugAssert( _CrtIsValidPointer((void*)alignedPtr, bytes, TRUE) ); - #endif - return (void *)alignedPtr; -} - - -void System::alignedFree(void* _ptr) { - if (_ptr == NULL) { - return; - } - - size_t alignedPtr = (size_t)_ptr; - - // Back up one word from the pointer the user passed in. - // We now have a pointer to a pointer to the true start - // of the memory block. - size_t* redirectPtr = (size_t*)(alignedPtr - sizeof(void *)); - - // Dereference that pointer so that ptr = true start - void* truePtr = (void*)redirectPtr[0]; - - debugAssert(isValidHeapPointer((void*)truePtr)); - System::free(truePtr); -} - - -void System::setEnv(const std::string& name, const std::string& value) { - std::string cmd = name + "=" + value; -# ifdef G3D_WIN32 - _putenv(cmd.c_str()); -# else - // Many linux implementations of putenv expect char* - putenv(const_cast(cmd.c_str())); -# endif -} - - -const char* System::getEnv(const std::string& name) { - return getenv(name.c_str()); -} - - -static void var(TextOutput& t, const std::string& name, const std::string& val) { - t.writeSymbols(name,"="); - t.writeString(val); - t.writeNewline(); -} - - -static void var(TextOutput& t, const std::string& name, const bool val) { - t.writeSymbols(name, "=", val ? "Yes" : "No"); - t.writeNewline(); -} - - -static void var(TextOutput& t, const std::string& name, const int val) { - t.writeSymbols(name,"="); - t.writeNumber(val); - t.writeNewline(); -} - - -void System::describeSystem( - std::string& s) { - - TextOutput t; - describeSystem(t); - t.commitString(s); -} - -void System::describeSystem( - TextOutput& t) { - - t.writeSymbols("App", "{"); - t.writeNewline(); - t.pushIndent(); - { - var(t, "Name", System::currentProgramFilename()); - char cwd[1024]; - getcwd(cwd, 1024); - var(t, "cwd", std::string(cwd)); - } - t.popIndent(); - t.writeSymbols("}"); - t.writeNewline(); - t.writeNewline(); - - t.writeSymbols("OS", "{"); - t.writeNewline(); - t.pushIndent(); - { - var(t, "Name", System::operatingSystem()); - } - t.popIndent(); - t.writeSymbols("}"); - t.writeNewline(); - t.writeNewline(); - - t.writeSymbols("CPU", "{"); - t.writeNewline(); - t.pushIndent(); - { - var(t, "Vendor", System::cpuVendor()); - var(t, "Architecture", System::cpuArchitecture()); - var(t, "hasCPUID", System::hasCPUID()); - var(t, "hasMMX", System::hasMMX()); - var(t, "hasSSE", System::hasSSE()); - var(t, "hasSSE2", System::hasSSE2()); - var(t, "hasSSE3", System::hasSSE3()); - var(t, "has3DNow", System::has3DNow()); - var(t, "hasRDTSC", System::hasRDTSC()); - var(t, "numCores", System::numCores()); - } - t.popIndent(); - t.writeSymbols("}"); - t.writeNewline(); - t.writeNewline(); - - t.writeSymbols("G3D", "{"); - t.writeNewline(); - t.pushIndent(); - { - var(t, "Link version", G3D_VER); - var(t, "Compile version", System::version()); - } - t.popIndent(); - t.writeSymbols("}"); - t.writeNewline(); - t.writeNewline(); -} - - -void System::setClipboardText(const std::string& s) { -# ifdef G3D_WIN32 - if (OpenClipboard(NULL)) { - HGLOBAL hMem = GlobalAlloc(GHND | GMEM_DDESHARE, s.size() + 1); - if (hMem) { - char *pMem = (char*)GlobalLock(hMem); - strcpy(pMem, s.c_str()); - GlobalUnlock(hMem); - - EmptyClipboard(); - SetClipboardData(CF_TEXT, hMem); - } - - CloseClipboard(); - GlobalFree(hMem); - } -# endif -} - - -std::string System::getClipboardText() { - std::string s; - -# ifdef G3D_WIN32 - if (OpenClipboard(NULL)) { - HANDLE h = GetClipboardData(CF_TEXT); - - if (h) { - char* temp = (char*)GlobalLock(h); - if (temp) { - s = temp; - } - temp = NULL; - GlobalUnlock(h); - } - CloseClipboard(); - } -# endif - return s; -} - - -std::string System::currentDateString() { - time_t t1; - ::time(&t1); - tm* t = localtime(&t1); - return format("%d-%02d-%02d", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday); -} - -#ifdef _MSC_VER - -// VC on Intel -void System::cpuid(CPUIDFunction func, uint32& areg, uint32& breg, uint32& creg, uint32& dreg) { -#if !defined(G3D_64BIT) - // Can't copy from assembler direct to a function argument (which is on the stack) in VC. - uint32 a,b,c,d; - - // Intel assembler syntax - __asm { - mov eax, func // eax <- func - mov ecx, 0 - cpuid - mov a, eax - mov b, ebx - mov c, ecx - mov d, edx - } - areg = a; - breg = b; - creg = c; - dreg = d; -#else - int CPUInfo[4]; - __cpuid(CPUInfo, func); - memcpy(&areg, &CPUInfo[0], 4); - memcpy(&breg, &CPUInfo[1], 4); - memcpy(&creg, &CPUInfo[2], 4); - memcpy(&dreg, &CPUInfo[3], 4); -#endif -} - -#elif defined(G3D_OSX) && ! defined(G3D_OSX_INTEL) - -// non-intel OS X; no CPUID -void System::cpuid(CPUIDFunction func, uint32& eax, uint32& ebx, uint32& ecx, uint32& edx) { - eax = 0; - ebx = 0; - ecx = 0; - edx = 0; -} - -#else - -// See http://sam.zoy.org/blog/2007-04-13-shlib-with-non-pic-code-have-inline-assembly-and-pic-mix-well -// for a discussion of why the second version saves ebx; it allows 32-bit code to compile with the -fPIC option. -// On 64-bit x86, PIC code has a dedicated rip register for PIC so there is no ebx conflict. -void System::cpuid(CPUIDFunction func, uint32& eax, uint32& ebx, uint32& ecx, uint32& edx) { -#if ! defined(__PIC__) || defined(__x86_64__) - // AT&T assembler syntax - asm volatile( - "movl $0, %%ecx \n\n" /* Wipe ecx */ - "cpuid \n\t" - : "=a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx) - : "a"(func)); -#else - // AT&T assembler syntax - asm volatile( - "pushl %%ebx \n\t" /* save ebx */ - "movl $0, %%ecx \n\n" /* Wipe ecx */ - "cpuid \n\t" - "movl %%ebx, %1 \n\t" /* save what cpuid just put in %ebx */ - "popl %%ebx \n\t" /* restore the old ebx */ - : "=a"(eax), "=r"(ebx), "=c"(ecx), "=d"(edx) - : "a"(func)); -#endif -} - -#endif - -} // namespace diff --git a/externals/g3dlite/TextInput.cpp b/externals/g3dlite/TextInput.cpp deleted file mode 100644 index 7276d8c66b2..00000000000 --- a/externals/g3dlite/TextInput.cpp +++ /dev/null @@ -1,1136 +0,0 @@ -/** - @file TextInput.cpp - - @author Morgan McGuire, graphics3d.com - - @cite Based on a lexer written by Aaron Orenstein. - - @created 2001-11-27 - @edited 2008-07-14 - */ - -#include "G3D/fileutils.h" -#include "G3D/TextInput.h" -#include "G3D/BinaryInput.h" -#include "G3D/stringutils.h" - -#ifdef _MSC_VER -# pragma warning (push) -// conversion from 'int' to 'char', possible loss of data (TODO: fix underlying problems) -# pragma warning (disable: 4244) -#endif - -namespace G3D { - -Token TextInput::readSignificant() { - Token t; - do { - t = read(); - } while ((t.type() == Token::COMMENT) || (t.type() == Token::NEWLINE)); - return t; -} - - -double Token::number() const { - if (_type == NUMBER) { - std::string s = toLower(_string); - if (s == "-1.#ind00") { - return nan(); - } - - if (s == "1.#inf00") { - return inf(); - } - - if (s == "-1.#inf00") { - return -inf(); - } - - double n; - if ((_string.length() > 2) && - (_string[0] == '0') && - (_string[1] == 'x')) { - // Hex - uint32 i; - sscanf(_string.c_str(), "%x", &i); - n = i; - } else { - sscanf(_string.c_str(), "%lg", &n); - } - return n; - } else { - return 0.0; - } -} - - -TextInput::Settings::Settings () : - cppBlockComments(true), - cppLineComments(true), - otherLineComments(true), - escapeSequencesInStrings(true), - otherCommentCharacter('\0'), - otherCommentCharacter2('\0'), - generateCommentTokens(false), - generateNewlineTokens(false), - signedNumbers(true), - singleQuotedStrings(true), - singleQuoteCharacter('\''), - sourceFileName(), - startingLineNumberOffset(0), - msvcSpecials(true), - proofSymbols(false), - caseSensitive(true) -{ - trueSymbols.insert("true"); - falseSymbols.insert("false"); -} - - -Token TextInput::peek() { - if (stack.size() == 0) { - Token t = nextToken(); - push(t); - } - - return stack.front(); -} - - -int TextInput::peekLineNumber() { - return peek().line(); -} - - -int TextInput::peekCharacterNumber() { - return peek().character(); -} - - -Token TextInput::read() { - if (stack.size() > 0) { - Token t = stack.front(); - stack.pop_front(); - return t; - } else { - return nextToken(); - } -} - -static void toUpper(Set& set) { - Array symbols; - set.getMembers(symbols); - set.clear(); - for (int i = 0; i < symbols.size(); ++i) { - set.insert(toUpper(symbols[i])); - } -} - -void TextInput::init() { - currentCharOffset = 0; - charNumber = 1; - lineNumber = 1 + options.startingLineNumberOffset; - - if (! options.caseSensitive) { - // Convert true and false symbols to all uppercase for fast comparisons - toUpper(options.trueSymbols); - toUpper(options.falseSymbols); - } -} - - -void TextInput::push(const Token& t) { - stack.push_front(t); -} - - -bool TextInput::hasMore() { - return (peek()._type != Token::END); -} - - -int TextInput::eatInputChar() { - // Don't go off the end - if (currentCharOffset >= buffer.length()) { - return EOF; - } - - unsigned char c = buffer[currentCharOffset]; - ++currentCharOffset; - - // update lineNumber and charNumber to reflect the location of the *next* - // character which will be read. - - // increment line number for \r, \n and \r\n which matches Token::NEWLINE parsing - if (c == '\r') { - ++lineNumber; - charNumber = 1; - - // check for \r\n - if (currentCharOffset < buffer.length()) { - unsigned char c2 = buffer[currentCharOffset]; - if (c2 == '\n') { - c = c2; - ++currentCharOffset; - } - } - } else if (c == '\n') { - ++lineNumber; - charNumber = 1; - } else { - ++charNumber; - } - - return c; -} - -int TextInput::peekInputChar(int distance) { - // Don't go off the end - if ((currentCharOffset + distance) >= buffer.length()) { - return EOF; - } - - unsigned char c = buffer[currentCharOffset + distance]; - return c; -} - - -Token TextInput::nextToken() { - Token t; - - t._line = lineNumber; - t._character = charNumber; - t._type = Token::END; - t._extendedType = Token::END_TYPE; - - int c = peekInputChar(); - if (c == EOF) { - return t; - } - - // loop through white space, newlines and comments - // found before other tokens - bool whitespaceDone = false; - while (! whitespaceDone) { - whitespaceDone = true; - - // generate newlines tokens for '\n' and '\r' and '\r\n' - if (options.generateNewlineTokens && isNewline(c)) { - t._type = Token::NEWLINE; - t._extendedType = Token::NEWLINE_TYPE; - t._string = c; - - int c2 = peekInputChar(1); - if (c == '\r' && c2 == '\n') { - t._string += c2; - } - - eatInputChar(); - return t; - } else { - // Consume whitespace - while (isWhiteSpace(c)) { - c = eatAndPeekInputChar(); - } - } - - // update line and character number to include discarded whitespace - t._line = lineNumber; - t._character = charNumber; - - int c2 = peekInputChar(1); - - // parse comments and generate tokens if enabled - std::string commentString; - - // check for line comments first - bool isLineComment = false; - if (options.cppLineComments && (c == '/' && c2 == '/')) { - // set start of line comment and eat markers - isLineComment = true; - eatInputChar(); - eatInputChar(); - } else if ( options.otherCommentCharacter && - (options.otherCommentCharacter != '\0' && c == options.otherCommentCharacter) ) { - // set start of line comment and eat markers - isLineComment = true; - eatInputChar(); - } else if ( options.otherCommentCharacter && - (options.otherCommentCharacter2 != '\0' && c == options.otherCommentCharacter2) ) { - // set start of line comment and eat markers - isLineComment = true; - eatInputChar(); - } - - if (isLineComment) { - - // consume line comment to newline or EOF - c = peekInputChar(); - while (! isNewline(c) && c != EOF) { - // build comment string for token - commentString += c; - - c = eatAndPeekInputChar(); - } - - if (options.generateCommentTokens) { - t._type = Token::COMMENT; - t._extendedType = Token::LINE_COMMENT_TYPE; - t._string = commentString; - return t; - } else { - // There is whitespace after the comment (in particular, the - // newline that terminates the comment). There might also be - // whitespace at the start of the next line. - whitespaceDone = false; - } - - } else if (options.cppBlockComments && (c == '/' && c2 == '*')) { - // consume block comment to end-marker or EOF - - // consume both start-comment chars, can't let the trailing one - // help close the comment. - eatInputChar(); - eatInputChar(); - - c = peekInputChar(); - c2 = peekInputChar(1); - while (! ((c == '*') && (c2 == '/')) && (c != EOF)) { - commentString += c; - - eatInputChar(); - c = c2; - c2 = peekInputChar(1); - } - eatInputChar(); // eat closing '*' - eatInputChar(); // eat closing '/' - - c = peekInputChar(); - - if (options.generateCommentTokens) { - t._type = Token::COMMENT; - t._extendedType = Token::BLOCK_COMMENT_TYPE; - t._string = commentString; - return t; - } else { - // There is whitespace after the comment (in particular, the - // newline that terminates the comment). There might also be - // whitespace at the start of the next line. - whitespaceDone = false; - } - } - - } // while (! whitespaceDone) - - t._line = lineNumber; - t._character = charNumber; - - // handle EOF - if (c == EOF) { - return t; - } - - // Extended ASCII parses as itself, except for EOF - if (c > 127 && c < 255) { - t._type = Token::SYMBOL; - t._extendedType = Token::SYMBOL_TYPE; - t._string = c; - c = eatAndPeekInputChar(); - } - - - // Perform appropriate setup for a symbol (including setting up the token - // string to start with c), eat the input character, and overwrite - // 'c' with the peeked next input character. -#define SETUP_SYMBOL(c) \ - { \ - t._type = Token::SYMBOL; \ - t._extendedType = Token::SYMBOL_TYPE; \ - t._string = c; \ - c = eatAndPeekInputChar(); \ - } - - switch (c) { - - case '@': // Simple symbols -> just themselves. - case '(': - case ')': - case ',': - case ';': - case '{': - case '}': - case '[': - case ']': - case '#': - case '$': - case '?': - case '%': - SETUP_SYMBOL(c); - return t; - - case '-': // negative number, -, --, -=, or -> - SETUP_SYMBOL(c); - - switch (c) { - case '>': // -> - case '-': // -- - case '=': // -= - t._string += c; - eatInputChar(); - return t; - } - - if (options.signedNumbers - && (isDigit(c) || (c == '.' && isDigit(peekInputChar(1))))) { - - // Negative number. 'c' is still the first digit, and is - // the next input char. - - goto numLabel; - } - - // plain - - return t; - - case '+': // positive number, +, ++, or += - SETUP_SYMBOL(c); - - switch (c) { - case '+': // ++ - case '=': // += - t._string += c; - eatInputChar(); - return t; - } - - if (options.signedNumbers - && (isDigit(c) || (c == '.' && isDigit(peekInputChar(1))))) { - - // Positive number. 'c' is still the first digit, and is - // the next input char. - - goto numLabel; - } - - return t; - - case ':': // : or :: or ::> or ::= or := or :> - SETUP_SYMBOL(c); - - if (c == ':') { - t._string += c; - eatInputChar(); - - if (options.proofSymbols) { - c = peekInputChar(0); - - if ((c == '>') || (c == '=')) { - t._string += c; - eatInputChar(); - } - } - } - else if (options.proofSymbols && (c == '=' || c == '>')) { - t._string += c; - eatInputChar(); - } - return t; - - case '=': // = or == or => - SETUP_SYMBOL(c); - - if (c == '=') { - t._string += c; - eatInputChar(); - return t; - } else if (options.proofSymbols && (c == '>')) { - t._string += c; - eatInputChar(); - return t; - } - return t; - - case '*': // * or *= - case '/': // / or /= - case '!': // ! or != - case '~': // ~ or ~= - case '^': // ^ or ^= - SETUP_SYMBOL(c); - - if (c == '=') { - t._string += c; - eatInputChar(); - return t; - } - return t; - - case '>': // >, >>,or >= - case '<': // <<, <<, or <= or <- or <: - case '|': // ||, ||, or |= or |- - case '&': // &, &&, or &= - { - int orig_c = c; - SETUP_SYMBOL(c); - - if ((c == '=') || (orig_c == c)) { - t._string += c; - eatInputChar(); - return t; - } else if (options.proofSymbols) { - if ((orig_c == '<') && (c == '-')) { - t._string += c; - eatInputChar(); - } else if ((orig_c == '|') && (c == '-')) { - t._string += c; - eatInputChar(); - } else if ((orig_c == '<') && (c == ':')) { - t._string += c; - - c = eatAndPeekInputChar(); - - if (c == ':') { - t._string += c; - eatInputChar(); - } - } - } - } - return t; - - case '\\': // backslash or escaped comment char. - SETUP_SYMBOL(c); - - if ((options.otherCommentCharacter != '\0' - && c == options.otherCommentCharacter) - || (options.otherCommentCharacter2 != '\0' - && c == options.otherCommentCharacter2)) { - - // escaped comment character. Return the raw comment - // char (no backslash). - - t._string = c; - eatInputChar(); - return t; - } - return t; - - case '.': // number, ., .., or ... - if (isDigit(peekInputChar(1))) { - // We're parsing a float that began without a leading zero - goto numLabel; - } - - SETUP_SYMBOL(c); - - if (c == '.') { // .. or ... - t._string += c; - c = eatAndPeekInputChar(); - - if (c == '.') { // ... - t._string += c; - eatInputChar(); - } - return t; - } - - return t; - - } // switch (c) - -#undef SETUP_SYMBOL - -numLabel: - if (isDigit(c) || (c == '.')) { - - // A number. Note-- single dots have been - // parsed already, so a . indicates a number - // less than 1 in floating point form. - - // [0-9]*(\.[0-9][f]) or [0-9]+ or 0x[0-9,A-F]+ - - if (t._string != "-") { - // If we picked up a leading "-" sign above, keep it, - // otherwise drop the string parsed thus far - t._string = ""; - } - t._type = Token::NUMBER; - if (c == '.') { - t._extendedType = Token::FLOATING_POINT_TYPE; - } else { - t._extendedType = Token::INTEGER_TYPE; - } - - if ((c == '0') && (peekInputChar(1) == 'x')) { - // Hex number - t._string += "0x"; - - // skip the 0x - eatInputChar(); - eatInputChar(); - - c = peekInputChar(); - while (isDigit(c) || ((c >= 'A') && (c <= 'F')) || ((c >= 'a') && (c <= 'f'))) { - t._string += c; - c = eatAndPeekInputChar(); - } - - } else { - // Non-hex number - - // Read the part before the decimal. - while (isDigit(c)) { - t._string += c; - c = eatAndPeekInputChar(); - } - - // True if we are reading a floating-point special type - bool isSpecial = false; - - // Read the decimal, if one exists - if (c == '.') { - t._extendedType = Token::FLOATING_POINT_TYPE; - - // The '.' character was a decimal point, not the start of a - // method or range operator - t._string += c; - c = eatAndPeekInputChar(); - - // Floating point specials (msvc format only) - if (options.msvcSpecials && (c == '#')) { - isSpecial = true; - // We are reading a floating point special value - // of the form -1.#IND00, -1.#INF00, or 1.#INF00 - c = eatAndPeekInputChar(); - char test = c; - if (! options.caseSensitive) { - test = toupper(c); - } - if (test != 'I') { - throw BadMSVCSpecial - ( - "Incorrect floating-point special (inf or nan) " - "format.", - t.line(), charNumber); - } - c = eatAndPeekInputChar(); - test = c; - if (! options.caseSensitive) { - test = toupper(c); - } - if (test != 'N') { - throw BadMSVCSpecial - ( - "Incorrect floating-point special (inf or nan) " - "format.", - t.line(), charNumber); - } - t._string += "#IN"; - c = eatAndPeekInputChar(); - test = c; - if (! options.caseSensitive) { - test = toupper(c); - } - if ((test != 'F') && (test != 'D')) { - throw BadMSVCSpecial - ( - "Incorrect floating-point special (inf or nan) " - "format.", - t.line(), charNumber); - } - t._string += c; - for (int j = 0; j < 2; ++j) { - c = eatAndPeekInputChar(); - if (c != '0') { - throw BadMSVCSpecial - ( - "Incorrect floating-point special (inf or" - "nan) format.", - t.line(), charNumber); - } - t._string += (char)c; - } - - } else { - - // Read the part after the decimal - while (isDigit((char)c)) { - t._string += (char)c; - c = eatAndPeekInputChar(); - } - } - } - - if (! isSpecial && ((c == 'e') || (c == 'E'))) { - // Read exponent - t._extendedType = Token::FLOATING_POINT_TYPE; - t._string += c; - - c = eatAndPeekInputChar(); - if ((c == '-') || (c == '+')) { - t._string += c; - c = eatAndPeekInputChar(); - } - - while (isDigit(c)) { - t._string += c; - c = eatAndPeekInputChar(); - } - } - - if (! isSpecial && (t._extendedType == Token::FLOATING_POINT_TYPE) && (c == 'f')) { - // Trailing f on a float - t._string += c; - c = eatAndPeekInputChar(); - } - } - return t; - - } else if (isLetter(c) || (c == '_')) { - // Identifier or keyword - // [A-Za-z_][A-Za-z_0-9]* - - t._type = Token::SYMBOL; - t._extendedType = Token::SYMBOL_TYPE; - t._string = ""; - do { - t._string += c; - c = eatAndPeekInputChar(); - } while (isLetter(c) || isDigit(c) || (c == '_')); - - // See if this symbol is actually a boolean - if ((options.trueSymbols.size() > 0) || (options.falseSymbols.size() > 0)) { - std::string str = t._string; - if (! options.caseSensitive) { - str = toUpper(str); - } - if (options.trueSymbols.contains(str)) { - t._type = Token::BOOLEAN; - t._extendedType = Token::BOOLEAN_TYPE; - t._bool = true; - } else if (options.falseSymbols.contains(str)) { - t._type = Token::BOOLEAN; - t._extendedType = Token::BOOLEAN_TYPE; - t._bool = false; - } - } - - return t; - - } else if (c == '\"') { - - // Discard the double-quote. - eatInputChar(); - - // Double quoted string - parseQuotedString('\"', t); - return t; - - } else if (c == options.singleQuoteCharacter) { - - // Discard the single-quote. - eatInputChar(); - - if (options.singleQuotedStrings) { - // Single quoted string - parseQuotedString(options.singleQuoteCharacter, t); - } else { - t._string = c; - t._type = Token::SYMBOL; - t._extendedType = Token::SYMBOL_TYPE; - } - return t; - - } // end of special case tokens - - if (c == EOF) { - t._type = Token::END; - t._extendedType = Token::END_TYPE; - t._string = ""; - return t; - } - - // Some unknown token - debugAssertM(false, - format("Unrecognized token type beginning with character '%c' (ASCII %d)", - c, c)); - return t; -} - - -void TextInput::parseQuotedString(unsigned char delimiter, Token& t) { - - t._type = Token::STRING; - - if (delimiter == options.singleQuoteCharacter) { - t._extendedType = Token::SINGLE_QUOTED_TYPE; - } else { - t._extendedType = Token::DOUBLE_QUOTED_TYPE; - } - - while (true) { - // We're definitely going to consume the next input char, so we get - // it right now. This makes the condition handling below a bit easier. - int c = eatInputChar(); - - if (c == EOF) { - // END inside a quoted string. (We finish the string.) - break; - } - - if (options.escapeSequencesInStrings && (c == '\\')) { - // An escaped character. We're definitely going to consume it, - // so we get it (and consume it) now. - - c = eatInputChar(); - - switch (c) { - case 'r': - t._string += '\r'; - break; - case 'n': - t._string += '\n'; - break; - case 't': - t._string += '\t'; - break; - case '0': - t._string += '\0'; - break; - - case '\\': - case '\"': - t._string += (char)c; - break; - - default: - if (c == options.singleQuoteCharacter) { - t._string += (char)c; - break; - } - - if (((c == options.otherCommentCharacter) && - (options.otherCommentCharacter != '\0')) || - ((c == options.otherCommentCharacter2) && - (options.otherCommentCharacter2 != '\0'))) { - t._string += c; - } - // otherwise, some illegal escape sequence; skip it. - break; - - } // switch - - } else if (c == delimiter) { - // End of the string. Already consumed the character. - break; - } else { - // All other chars, go on to the string. Already consumed the - // character. - t._string += (char)c; - } - - } -} - -bool TextInput::readBoolean() { - Token t(read()); - - if (t._type == Token::BOOLEAN) { - return t.boolean(); - } - - // Push initial token back, and throw an error. We intentionally - // indicate that the wrong type is the type of the initial token. - // Logically, the number started there. - push(t); - throw WrongTokenType(options.sourceFileName, t.line(), t.character(), - Token::BOOLEAN, t._type); -} - -double TextInput::readNumber() { - Token t(read()); - - if (t._type == Token::NUMBER) { - return t.number(); - } - - // Even if signedNumbers is disabled, readNumber attempts to - // read a signed number, so we handle that case here. - if (! options.signedNumbers - && (t._type == Token::SYMBOL) - && ((t._string == "-") - || (t._string == "+"))) { - - Token t2(read()); - - if ((t2._type == Token::NUMBER) - && (t2._character == t._character + 1)) { - - if (t._string == "-") { - return -t2.number(); - } else { - return t2.number(); - } - } - - // push back the second token. - push(t2); - } - - // Push initial token back, and throw an error. We intentionally - // indicate that the wrong type is the type of the initial token. - // Logically, the number started there. - push(t); - throw WrongTokenType(options.sourceFileName, t.line(), t.character(), - Token::NUMBER, t._type); -} - - -Token TextInput::readStringToken() { - Token t(read()); - - if (t._type == Token::STRING) { // fast path - return t; - } - - push(t); - throw WrongTokenType(options.sourceFileName, t.line(), t.character(), - Token::STRING, t._type); -} - -std::string TextInput::readString() { - return readStringToken()._string; -} - -void TextInput::readString(const std::string& s) { - Token t(readStringToken()); - - if (t._string == s) { // fast path - return; - } - - push(t); - throw WrongString(options.sourceFileName, t.line(), t.character(), - s, t._string); -} - -Token TextInput::readCommentToken() { - Token t(read()); - - if (t._type == Token::COMMENT) { // fast path - return t; - } - - push(t); - throw WrongTokenType(options.sourceFileName, t.line(), t.character(), - Token::COMMENT, t._type); -} - -std::string TextInput::readComment() { - return readCommentToken()._string; -} - -void TextInput::readComment(const std::string& s) { - Token t(readCommentToken()); - - if (t._string == s) { // fast path - return; - } - - push(t); - throw WrongString(options.sourceFileName, t.line(), t.character(), - s, t._string); -} - -Token TextInput::readNewlineToken() { - Token t(read()); - - if (t._type == Token::NEWLINE) { // fast path - return t; - } - - push(t); - throw WrongTokenType(options.sourceFileName, t.line(), t.character(), - Token::NEWLINE, t._type); -} - -std::string TextInput::readNewline() { - return readNewlineToken()._string; -} - -void TextInput::readNewline(const std::string& s) { - Token t(readNewlineToken()); - - if (t._string == s) { // fast path - return; - } - - push(t); - throw WrongString(options.sourceFileName, t.line(), t.character(), - s, t._string); -} - -Token TextInput::readSymbolToken() { - Token t(read()); - - if (t._type == Token::SYMBOL) { // fast path - return t; - } - - push(t); - throw WrongTokenType(options.sourceFileName, t.line(), t.character(), - Token::SYMBOL, t._type); -} - - -std::string TextInput::readSymbol() { - return readSymbolToken()._string; -} - -void TextInput::readSymbol(const std::string& symbol) { - Token t(readSymbolToken()); - - if (t._string == symbol) { // fast path - return; - } - - push(t); - throw WrongSymbol(options.sourceFileName, t.line(), t.character(), - symbol, t._string); -} - - -TextInput::TextInput(const std::string& filename, const Settings& opt) : options(opt) { - init(); - std::string input = readWholeFile(filename); - - if (options.sourceFileName.empty()) { - options.sourceFileName = filename; - } - int n = input.size(); - buffer.resize(n); - System::memcpy(buffer.getCArray(), input.c_str(), n); -} - - -TextInput::TextInput(FS fs, const std::string& str, const Settings& opt) : options(opt) { - (void)fs; - init(); - if (options.sourceFileName.empty()) { - if (str.length() < 14) { - options.sourceFileName = std::string("\"") + str + "\""; - } else { - options.sourceFileName = std::string("\"") + str.substr(0, 10) + "...\""; - } - } - buffer.resize(str.length()); // we don't bother copying trailing NUL. - System::memcpy(buffer.getCArray(), str.c_str(), buffer.size()); -} - - -const std::string& TextInput::filename() const { - return options.sourceFileName; -} - -/////////////////////////////////////////////////////////////////////////////////// - -TextInput::TokenException::TokenException( - const std::string& src, - int ln, - int ch) : ParseError(src, ln, ch, format("%s(%d) : ", src.c_str(), ln)), - sourceFile(src) { -} - -/////////////////////////////////////////////////////////////////////////////////// - -static const char* tokenTypeToString(Token::Type t) { - switch (t) { - case Token::SYMBOL: - return "Token::SYMBOL"; - case Token::STRING: - return "Token::STRING"; - case Token::NUMBER: - return "Token::NUMBER"; - case Token::END: - return "Token::END"; - default: - debugAssertM(false, "Fell through switch"); - return "?"; - } -} - -TextInput::WrongTokenType::WrongTokenType( - const std::string& src, - int ln, - int ch, - Token::Type e, - Token::Type a) : - TokenException(src, ln, ch), expected(e), actual(a) { - - message += format("Expected token of type %s, found type %s.", - tokenTypeToString(e), tokenTypeToString(a)); -} - - -TextInput::BadMSVCSpecial::BadMSVCSpecial( - const std::string& src, - int ln, - int ch) : - TokenException(src, ln, ch) { -} - - -TextInput::WrongSymbol::WrongSymbol( - const std::string& src, - int ln, - int ch, - const std::string& e, - const std::string& a) : - TokenException(src, ln, ch), expected(e), actual(a) { - - message += format("Expected symbol '%s', found symbol '%s'.", - e.c_str(), a.c_str()); -} - - -TextInput::WrongString::WrongString( - const std::string& src, - int ln, - int ch, - const std::string& e, - const std::string& a) : - TokenException(src, ln, ch), expected(e), actual(a) { - - message += format("Expected string '%s', found string '%s'.", - e.c_str(), a.c_str()); -} - - -void deserialize(bool& b, TextInput& ti) { - b = ti.readSymbol() == "true"; -} - - -void deserialize(int& b, TextInput& ti) { - b = iRound(ti.readNumber()); -} - - -void deserialize(uint8& b, TextInput& ti) { - b = (uint8)iRound(ti.readNumber()); -} - - -void deserialize(double& b, TextInput& ti) { - b = ti.readNumber(); -} - - -void deserialize(float& b, TextInput& ti) { - b = (float)ti.readNumber(); -} - -} // namespace - -#ifdef _MSC_VER -# pragma warning (pop) -#endif diff --git a/externals/g3dlite/TextOutput.cpp b/externals/g3dlite/TextOutput.cpp deleted file mode 100644 index 11347252eba..00000000000 --- a/externals/g3dlite/TextOutput.cpp +++ /dev/null @@ -1,452 +0,0 @@ -/** - @file TextOutput.cpp - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - @created 2004-06-21 - @edited 2006-08-14 - - Copyright 2000-2006, Morgan McGuire. - All rights reserved. - */ - -#include "G3D/TextOutput.h" -#include "G3D/Log.h" -#include "G3D/fileutils.h" - -namespace G3D { - -TextOutput::TextOutput(const TextOutput::Settings& opt) : - startingNewLine(true), - currentColumn(0), - inDQuote(false), - filename(""), - indentLevel(0) -{ - setOptions(opt); -} - - -TextOutput::TextOutput(const std::string& fil, const TextOutput::Settings& opt) : - startingNewLine(true), - currentColumn(0), - inDQuote(false), - filename(fil), - indentLevel(0) -{ - - setOptions(opt); -} - - -void TextOutput::setIndentLevel(int i) { - indentLevel = i; - - // If there were more pops than pushes, don't let that take us below 0 indent. - // Don't ever indent more than the number of columns. - indentSpaces = - iClamp(option.spacesPerIndent * indentLevel, - 0, - option.numColumns - 1); -} - - -void TextOutput::setOptions(const Settings& _opt) { - option = _opt; - - debugAssert(option.numColumns > 1); - - setIndentLevel(indentLevel); - - newline = (option.newlineStyle == Settings::NEWLINE_WINDOWS) ? "\r\n" : "\n"; -} - - -void TextOutput::pushIndent() { - setIndentLevel(indentLevel + 1); -} - - -void TextOutput::popIndent() { - setIndentLevel(indentLevel - 1); -} - - -static std::string escape(const std::string& string) { - std::string result = ""; - - for (std::string::size_type i = 0; i < string.length(); ++i) { - char c = string.at(i); - switch (c) { - case '\0': - result += "\\0"; - break; - - case '\r': - result += "\\r"; - break; - - case '\n': - result += "\\n"; - break; - - case '\t': - result += "\\t"; - break; - - case '\\': - result += "\\\\"; - break; - - default: - result += c; - } - } - - return result; -} - -void TextOutput::writeString(const std::string& string) { - // Convert special characters to escape sequences - this->printf("\"%s\"", escape(string).c_str()); -} - - -void TextOutput::writeBoolean(bool b) { - this->printf("%s ", b ? option.trueSymbol.c_str() : option.falseSymbol.c_str()); -} - -void TextOutput::writeNumber(double n) { - this->printf("%f ", n); -} - - -void TextOutput::writeNumber(int n) { - this->printf("%d ", n); -} - - -void TextOutput::writeSymbol(const std::string& string) { - if (string.size() > 0) { - // TODO: check for legal symbols? - this->printf("%s ", string.c_str()); - } -} - -void TextOutput::writeSymbols( - const std::string& a, - const std::string& b, - const std::string& c, - const std::string& d, - const std::string& e, - const std::string& f) { - - writeSymbol(a); - writeSymbol(b); - writeSymbol(c); - writeSymbol(d); - writeSymbol(e); - writeSymbol(f); -} - - -void TextOutput::printf(const std::string formatString, ...) { - va_list argList; - va_start(argList, formatString); - this->vprintf(formatString.c_str(), argList); - va_end(argList); -} - - -void TextOutput::printf(const char* formatString, ...) { - va_list argList; - va_start(argList, formatString); - this->vprintf(formatString, argList); - va_end(argList); -} - - -void TextOutput::convertNewlines(const std::string& in, std::string& out) { - // TODO: can be significantly optimized in cases where - // single characters are copied in order by walking through - // the array and copying substrings as needed. - - if (option.convertNewlines) { - out = ""; - for (uint32 i = 0; i < in.size(); ++i) { - if (in[i] == '\n') { - // Unix newline - out += newline; - } else if ((in[i] == '\r') && (i + 1 < in.size()) && (in[i + 1] == '\n')) { - // Windows newline - out += newline; - ++i; - } else { - out += in[i]; - } - } - } else { - out = in; - } -} - - -void TextOutput::writeNewline() { - for (uint32 i = 0; i < newline.size(); ++i) { - indentAppend(newline[i]); - } -} - - -void TextOutput::writeNewlines(int numLines) { - for (int i = 0; i < numLines; ++i) { - writeNewline(); - } -} - - -void TextOutput::wordWrapIndentAppend(const std::string& str) { - // TODO: keep track of the last space character we saw so we don't - // have to always search. - - if ((option.wordWrap == Settings::WRAP_NONE) || - (currentColumn + (int)str.size() <= option.numColumns)) { - // No word-wrapping is needed - - // Add one character at a time. - // TODO: optimize for strings without newlines to add multiple - // characters. - for (uint32 i = 0; i < str.size(); ++i) { - indentAppend(str[i]); - } - return; - } - - // Number of columns to wrap against - int cols = option.numColumns - indentSpaces; - - // Copy forward until we exceed the column size, - // and then back up and try to insert newlines as needed. - for (uint32 i = 0; i < str.size(); ++i) { - - indentAppend(str[i]); - if ((str[i] == '\r') && (i + 1 < str.size()) && (str[i + 1] == '\n')) { - // \r\n, we need to hit the \n to enter word wrapping. - ++i; - indentAppend(str[i]); - } - - if (currentColumn >= cols) { - debugAssertM(str[i] != '\n' && str[i] != '\r', - "Should never enter word-wrapping on a newline character"); - - // True when we're allowed to treat a space as a space. - bool unquotedSpace = option.allowWordWrapInsideDoubleQuotes || ! inDQuote; - - // Cases: - // - // 1. Currently in a series of spaces that ends with a newline - // strip all spaces and let the newline - // flow through. - // - // 2. Currently in a series of spaces that does not end with a newline - // strip all spaces and replace them with single newline - // - // 3. Not in a series of spaces - // search backwards for a space, then execute case 2. - - // Index of most recent space - uint32 lastSpace = data.size() - 1; - - // How far back we had to look for a space - uint32 k = 0; - uint32 maxLookBackward = currentColumn - indentSpaces; - - // Search backwards (from current character), looking for a space. - while ((k < maxLookBackward) && - (lastSpace > 0) && - (! ((data[lastSpace] == ' ') && unquotedSpace))) { - --lastSpace; - ++k; - - if ((data[lastSpace] == '\"') && !option.allowWordWrapInsideDoubleQuotes) { - unquotedSpace = ! unquotedSpace; - } - } - - if (k == maxLookBackward) { - // We couldn't find a series of spaces - - if (option.wordWrap == Settings::WRAP_ALWAYS) { - // Strip the last character we wrote, force a newline, - // and replace the last character; - data.pop(); - writeNewline(); - indentAppend(str[i]); - } else { - // Must be Settings::WRAP_WITHOUT_BREAKING - // - // Don't write the newline; we'll come back to - // the word wrap code after writing another character - } - } else { - // We found a series of spaces. If they continue - // to the new string, strip spaces off both. Otherwise - // strip spaces from data only and insert a newline. - - // Find the start of the spaces. firstSpace is the index of the - // first non-space, looking backwards from lastSpace. - uint32 firstSpace = lastSpace; - while ((k < maxLookBackward) && - (firstSpace > 0) && - (data[firstSpace] == ' ')) { - --firstSpace; - ++k; - } - - if (k == maxLookBackward) { - ++firstSpace; - } - - if (lastSpace == (uint32)data.size() - 1) { - // Spaces continued up to the new string - data.resize(firstSpace + 1); - writeNewline(); - - // Delete the spaces from the new string - while ((i < str.size() - 1) && (str[i + 1] == ' ')) { - ++i; - } - } else { - // Spaces were somewhere in the middle of the old string. - // replace them with a newline. - - // Copy over the characters that should be saved - Array temp; - for (uint32 j = lastSpace + 1; j < (uint32)data.size(); ++j) { - char c = data[j]; - - if (c == '\"') { - // Undo changes to quoting (they will be re-done - // when we paste these characters back on). - inDQuote = !inDQuote; - } - temp.append(c); - } - - // Remove those characters and replace with a newline. - data.resize(firstSpace + 1); - writeNewline(); - - // Write them back - for (uint32 j = 0; j < (uint32)temp.size(); ++j) { - indentAppend(temp[j]); - } - - // We are now free to continue adding from the - // new string, which may or may not begin with spaces. - - } // if spaces included new string - } // if hit indent - } // if line exceeded - } // iterate over str -} - - -void TextOutput::indentAppend(char c) { - - if (startingNewLine) { - for (int j = 0; j < indentSpaces; ++j) { - data.push(' '); - } - startingNewLine = false; - currentColumn = indentSpaces; - } - - data.push(c); - - // Don't increment the column count on return character - // newline is taken care of below. - if (c != '\r') { - ++currentColumn; - } - - if (c == '\"') { - inDQuote = ! inDQuote; - } - - startingNewLine = (c == '\n'); - if (startingNewLine) { - currentColumn = 0; - } -} - - -void TextOutput::vprintf(const char* formatString, va_list argPtr) { - std::string str = vformat(formatString, argPtr); - - std::string clean; - convertNewlines(str, clean); - wordWrapIndentAppend(clean); -} - - -void TextOutput::commit(bool flush) { - std::string p = filenamePath(filename); - if (! fileExists(p, false)) { - createDirectory(p); - } - - FILE* f = fopen(filename.c_str(), "wb"); - debugAssertM(f, "Could not open \"" + filename + "\""); - fwrite(data.getCArray(), 1, data.size(), f); - if (flush) { - fflush(f); - } - fclose(f); -} - - -void TextOutput::commitString(std::string& out) { - // Null terminate - data.push('\0'); - out = data.getCArray(); - data.pop(); -} - - -std::string TextOutput::commitString() { - std::string str; - commitString(str); - return str; -} - - - -///////////////////////////////////////////////////////////////////// - -void serialize(const float& b, TextOutput& to) { - to.writeNumber(b); -} - - -void serialize(const bool& b, TextOutput& to) { - to.writeSymbol(b ? "true" : "false"); -} - - -void serialize(const int& b, TextOutput& to) { - to.writeNumber(b); -} - - -void serialize(const uint8& b, TextOutput& to) { - to.writeNumber(b); -} - - -void serialize(const double& b, TextOutput& to) { - to.writeNumber(b); -} - - -} diff --git a/externals/g3dlite/Triangle.cpp b/externals/g3dlite/Triangle.cpp deleted file mode 100644 index 253438ad5fb..00000000000 --- a/externals/g3dlite/Triangle.cpp +++ /dev/null @@ -1,186 +0,0 @@ -/** - @file Triangle.cpp - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2001-04-06 - @edited 2008-12-28 - - Copyright 2000-2009, Morgan McGuire. - All rights reserved. - */ - -#include "G3D/platform.h" -#include "G3D/Triangle.h" -#include "G3D/Plane.h" -#include "G3D/BinaryInput.h" -#include "G3D/BinaryOutput.h" -#include "G3D/debugAssert.h" -#include "G3D/AABox.h" -#include "G3D/Ray.h" - -namespace G3D { - - -void Triangle::init(const Vector3& v0, const Vector3& v1, const Vector3& v2) { - - _plane = Plane(v0, v1, v2); - _vertex[0] = v0; - _vertex[1] = v1; - _vertex[2] = v2; - - static int next[] = {1,2,0}; - - for (int i = 0; i < 3; ++i) { - const Vector3& e = _vertex[next[i]] - _vertex[i]; - edgeMagnitude[i] = e.magnitude(); - - if (edgeMagnitude[i] == 0) { - edgeDirection[i] = Vector3::zero(); - } else { - edgeDirection[i] = e / (float)edgeMagnitude[i]; - } - } - - _edge01 = _vertex[1] - _vertex[0]; - _edge02 = _vertex[2] - _vertex[0]; - - _primaryAxis = _plane.normal().primaryAxis(); - _area = 0.5f * edgeDirection[0].cross(edgeDirection[2]).magnitude() * (edgeMagnitude[0] * edgeMagnitude[2]); - //0.5f * (_vertex[1] - _vertex[0]).cross(_vertex[2] - _vertex[0]).dot(_plane.normal()); -} - - -Triangle::Triangle() { - init(Vector3::zero(), Vector3::zero(), Vector3::zero()); -} - - -Triangle::Triangle(const Vector3& v0, const Vector3& v1, const Vector3& v2) { - init(v0, v1, v2); -} - - -Triangle::~Triangle() { -} - - -Triangle::Triangle(class BinaryInput& b) { - deserialize(b); -} - - -void Triangle::serialize(class BinaryOutput& b) { - _vertex[0].serialize(b); - _vertex[1].serialize(b); - _vertex[2].serialize(b); -} - - -void Triangle::deserialize(class BinaryInput& b) { - _vertex[0].deserialize(b); - _vertex[1].deserialize(b); - _vertex[2].deserialize(b); - init(_vertex[0], _vertex[1], _vertex[2]); -} - - -float Triangle::area() const { - return _area; -} - - -const Vector3& Triangle::normal() const { - return _plane.normal(); -} - - -const Plane& Triangle::plane() const { - return _plane; -} - - -Vector3 Triangle::center() const { - return (_vertex[0] + _vertex[1] + _vertex[2]) / 3.0; -} - -Vector3 Triangle::randomPoint() const { - // Choose a random point in the parallelogram - - float s = uniformRandom(); - float t = uniformRandom(); - - if (t > 1.0f - s) { - // Outside the triangle; reflect about the - // diagonal of the parallelogram - t = 1.0f - t; - s = 1.0f - s; - } - - return _edge01 * s + _edge02 * t + _vertex[0]; -} - - -void Triangle::getBounds(AABox& out) const { - Vector3 lo = _vertex[0]; - Vector3 hi = lo; - - for (int i = 1; i < 3; ++i) { - lo = lo.min(_vertex[i]); - hi = hi.max(_vertex[i]); - } - - out = AABox(lo, hi); -} - - -bool Triangle::intersect(const Ray& ray, float& distance, float baryCoord[3]) const { - static const float EPS = 1e-5f; - - // See RTR2 ch. 13.7 for the algorithm. - - const Vector3& e1 = edge01(); - const Vector3& e2 = edge02(); - const Vector3 p(ray.direction().cross(e2)); - const float a = e1.dot(p); - - if (abs(a) < EPS) { - // Determinant is ill-conditioned; abort early - return false; - } - - const float f = 1.0f / a; - const Vector3 s(ray.origin() - vertex(0)); - const float u = f * s.dot(p); - - if ((u < 0.0f) || (u > 1.0f)) { - // We hit the plane of the m_geometry, but outside the m_geometry - return false; - } - - const Vector3 q(s.cross(e1)); - const float v = f * ray.direction().dot(q); - - if ((v < 0.0f) || ((u + v) > 1.0f)) { - // We hit the plane of the triangle, but outside the triangle - return false; - } - - const float t = f * e2.dot(q); - - if ((t > 0.0f) && (t < distance)) { - // This is a new hit, closer than the previous one - distance = t; - - baryCoord[0] = 1.0 - u - v; - baryCoord[1] = u; - baryCoord[2] = v; - - return true; - } else { - // This hit is after the previous hit, so ignore it - return false; - } -} - -} // G3D diff --git a/externals/g3dlite/UprightFrame.cpp b/externals/g3dlite/UprightFrame.cpp deleted file mode 100644 index c80264bf4e8..00000000000 --- a/externals/g3dlite/UprightFrame.cpp +++ /dev/null @@ -1,132 +0,0 @@ -/** - @file UprightFrame.cpp - Box class - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2007-05-02 - @edited 2007-05-05 -*/ - -#include "G3D/UprightFrame.h" -#include "G3D/BinaryInput.h" -#include "G3D/BinaryOutput.h" - -namespace G3D { - -UprightFrame::UprightFrame(const CoordinateFrame& cframe) { - Vector3 look = cframe.lookVector(); - - yaw = G3D::pi() + atan2(look.x, look.z); - pitch = asin(look.y); - - translation = cframe.translation; -} - - -CoordinateFrame UprightFrame::toCoordinateFrame() const { - CoordinateFrame cframe; - - Matrix3 P(Matrix3::fromAxisAngle(Vector3::unitX(), pitch)); - Matrix3 Y(Matrix3::fromAxisAngle(Vector3::unitY(), yaw)); - - cframe.rotation = Y * P; - cframe.translation = translation; - - return cframe; -} - - -UprightFrame UprightFrame::operator+(const UprightFrame& other) const { - return UprightFrame(translation + other.translation, pitch + other.pitch, yaw + other.yaw); -} - - -UprightFrame UprightFrame::operator*(const float k) const { - return UprightFrame(translation * k, pitch * k, yaw * k); -} - - -void UprightFrame::unwrapYaw(UprightFrame* a, int N) { - // Use the first point to establish the wrapping convention - for (int i = 1; i < N; ++i) { - const float prev = a[i - 1].yaw; - float& cur = a[i].yaw; - - // No two angles should be more than pi (i.e., 180-degrees) apart. - if (abs(cur - prev) > G3D::pi()) { - // These angles must have wrapped at zero, causing them - // to be interpolated the long way. - - // Find canonical [0, 2pi] versions of these numbers - float p = wrap(prev, twoPi()); - float c = wrap(cur, twoPi()); - - // Find the difference -pi < diff < pi between the current and previous values - float diff = c - p; - if (diff < -G3D::pi()) { - diff += twoPi(); - } else if (diff > G3D::pi()) { - diff -= twoPi(); - } - - // Offset the current from the previous by the difference - // between them. - cur = prev + diff; - } - } -} - - -void UprightFrame::serialize(class BinaryOutput& b) const { - translation.serialize(b); - b.writeFloat32(pitch); - b.writeFloat32(yaw); -} - - -void UprightFrame::deserialize(class BinaryInput& b) { - translation.deserialize(b); - pitch = b.readFloat32(); - yaw = b.readFloat32(); -} - - -void UprightSpline::serialize(class BinaryOutput& b) const { - b.writeBool8(cyclic); - - b.writeInt32(control.size()); - for (int i = 0; i < control.size(); ++i) { - control[i].serialize(b); - } - b.writeInt32(time.size()); - for (int i = 0; i < time.size(); ++i) { - b.writeFloat32(time[i]); - } -} - - -void UprightSpline::deserialize(class BinaryInput& b) { - cyclic = b.readBool8(); - - control.resize(b.readInt32()); - for (int i = 0; i < control.size(); ++i) { - control[i].deserialize(b); - } - - if (b.hasMore()) { - time.resize(b.readInt32()); - for (int i = 0; i < time.size(); ++i) { - time[i] = b.readFloat32(); - } - debugAssert(time.size() == control.size()); - } else { - // Import legacy path - time.resize(control.size()); - for (int i = 0; i < time.size(); ++i) { - time[i] = i; - } - } -} - -} diff --git a/externals/g3dlite/Vector2.cpp b/externals/g3dlite/Vector2.cpp deleted file mode 100644 index ec0737c3755..00000000000 --- a/externals/g3dlite/Vector2.cpp +++ /dev/null @@ -1,224 +0,0 @@ -/** - @file Vector2.cpp - - 2D vector class, used for texture coordinates primarily. - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @cite Portions based on Dave Eberly'x Magic Software Library - at http://www.magic-software.com - - @created 2001-06-02 - @edited 2009-11-16 - */ - -#include "G3D/platform.h" -#include -#include "G3D/Vector2.h" -#include "G3D/g3dmath.h" -#include "G3D/format.h" -#include "G3D/BinaryInput.h" -#include "G3D/BinaryOutput.h" -#include "G3D/TextInput.h" -#include "G3D/TextOutput.h" -#include "G3D/Any.h" - -namespace G3D { - - -Vector2::Vector2(const Any& any) { - any.verifyName("Vector2"); - any.verifyType(Any::TABLE, Any::ARRAY); - any.verifySize(2); - - if (any.type() == Any::ARRAY) { - x = any[0]; - y = any[1]; - } else { - // Table - x = any["x"]; - y = any["y"]; - } -} - - -Vector2::operator Any() const { - Any any(Any::ARRAY, "Vector2"); - any.append(x, y); - return any; -} - - -const Vector2& Vector2::one() { - static const Vector2 v(1, 1); return v; -} - - -const Vector2& Vector2::zero() { - static Vector2 v(0, 0); - return v; -} - -const Vector2& Vector2::unitX() { - static Vector2 v(1, 0); - return v; -} - -const Vector2& Vector2::unitY() { - static Vector2 v(0, 1); - return v; -} - -const Vector2& Vector2::inf() { - static Vector2 v((float)G3D::finf(), (float)G3D::finf()); - return v; -} - - -const Vector2& Vector2::nan() { - static Vector2 v((float)G3D::fnan(), (float)G3D::fnan()); - return v; -} - - -const Vector2& Vector2::minFinite() { - static Vector2 v(-FLT_MAX, -FLT_MAX); - return v; -} - - -const Vector2& Vector2::maxFinite() { - static Vector2 v(FLT_MAX, FLT_MAX); - return v; -} - - -size_t Vector2::hashCode() const { - unsigned int xhash = (*(int*)(void*)(&x)); - unsigned int yhash = (*(int*)(void*)(&y)); - - return xhash + (yhash * 37); -} - - -Vector2::Vector2(BinaryInput& b) { - deserialize(b); -} - - -void Vector2::deserialize(BinaryInput& b) { - x = b.readFloat32(); - y = b.readFloat32(); -} - - -void Vector2::serialize(BinaryOutput& b) const { - b.writeFloat32(x); - b.writeFloat32(y); -} - - -void Vector2::deserialize(TextInput& t) { - t.readSymbol("("); - x = (float)t.readNumber(); - t.readSymbol(","); - y = (float)t.readNumber(); - t.readSymbol(")"); -} - - -void Vector2::serialize(TextOutput& t) const { - t.writeSymbol("("); - t.writeNumber(x); - t.writeSymbol(","); - t.writeNumber(y); - t.writeSymbol(")"); -} - -//---------------------------------------------------------------------------- - -Vector2 Vector2::random(G3D::Random& r) { - Vector2 result; - - do { - result = Vector2(r.uniform(-1, 1), r.uniform(-1, 1)); - - } while (result.squaredLength() >= 1.0f); - - result.unitize(); - - return result; -} - - -Vector2 Vector2::operator/ (float k) const { - return *this * (1.0f / k); -} - -Vector2& Vector2::operator/= (float k) { - this->x /= k; - this->y /= k; - return *this; -} - -//---------------------------------------------------------------------------- -float Vector2::unitize (float fTolerance) { - float fLength = length(); - - if (fLength > fTolerance) { - float fInvLength = 1.0f / fLength; - x *= fInvLength; - y *= fInvLength; - } else { - fLength = 0.0; - } - - return fLength; -} - -//---------------------------------------------------------------------------- - -std::string Vector2::toString() const { - return G3D::format("(%g, %g)", x, y); -} - -// 2-char swizzles - -Vector2 Vector2::xx() const { return Vector2 (x, x); } -Vector2 Vector2::yx() const { return Vector2 (y, x); } -Vector2 Vector2::xy() const { return Vector2 (x, y); } -Vector2 Vector2::yy() const { return Vector2 (y, y); } - -// 3-char swizzles - -Vector3 Vector2::xxx() const { return Vector3 (x, x, x); } -Vector3 Vector2::yxx() const { return Vector3 (y, x, x); } -Vector3 Vector2::xyx() const { return Vector3 (x, y, x); } -Vector3 Vector2::yyx() const { return Vector3 (y, y, x); } -Vector3 Vector2::xxy() const { return Vector3 (x, x, y); } -Vector3 Vector2::yxy() const { return Vector3 (y, x, y); } -Vector3 Vector2::xyy() const { return Vector3 (x, y, y); } -Vector3 Vector2::yyy() const { return Vector3 (y, y, y); } - -// 4-char swizzles - -Vector4 Vector2::xxxx() const { return Vector4 (x, x, x, x); } -Vector4 Vector2::yxxx() const { return Vector4 (y, x, x, x); } -Vector4 Vector2::xyxx() const { return Vector4 (x, y, x, x); } -Vector4 Vector2::yyxx() const { return Vector4 (y, y, x, x); } -Vector4 Vector2::xxyx() const { return Vector4 (x, x, y, x); } -Vector4 Vector2::yxyx() const { return Vector4 (y, x, y, x); } -Vector4 Vector2::xyyx() const { return Vector4 (x, y, y, x); } -Vector4 Vector2::yyyx() const { return Vector4 (y, y, y, x); } -Vector4 Vector2::xxxy() const { return Vector4 (x, x, x, y); } -Vector4 Vector2::yxxy() const { return Vector4 (y, x, x, y); } -Vector4 Vector2::xyxy() const { return Vector4 (x, y, x, y); } -Vector4 Vector2::yyxy() const { return Vector4 (y, y, x, y); } -Vector4 Vector2::xxyy() const { return Vector4 (x, x, y, y); } -Vector4 Vector2::yxyy() const { return Vector4 (y, x, y, y); } -Vector4 Vector2::xyyy() const { return Vector4 (x, y, y, y); } -Vector4 Vector2::yyyy() const { return Vector4 (y, y, y, y); } - - - -} // namespace diff --git a/externals/g3dlite/Vector3.cpp b/externals/g3dlite/Vector3.cpp deleted file mode 100644 index a53fa8269b7..00000000000 --- a/externals/g3dlite/Vector3.cpp +++ /dev/null @@ -1,507 +0,0 @@ -/** - @file Vector3.cpp - - 3D vector class - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @cite Portions based on Dave Eberly's Magic Software Library at http://www.magic-software.com - - @created 2001-06-02 - @edited 2009-11-27 - */ - -#include -#include -#include "G3D/Vector3.h" -#include "G3D/g3dmath.h" -#include "G3D/stringutils.h" -#include "G3D/BinaryInput.h" -#include "G3D/BinaryOutput.h" -#include "G3D/TextInput.h" -#include "G3D/TextOutput.h" -#include "G3D/Vector3int16.h" -#include "G3D/Matrix3.h" -#include "G3D/Vector2.h" -#include "G3D/Color3.h" -#include "G3D/Vector4int8.h" -#include "G3D/Vector3int32.h" -#include "G3D/Any.h" - -namespace G3D { - -Vector3::Vector3(const Any& any) { - any.verifyName("Vector3"); - any.verifyType(Any::TABLE, Any::ARRAY); - any.verifySize(3); - - if (any.type() == Any::ARRAY) { - x = any[0]; - y = any[1]; - z = any[2]; - } else { - // Table - x = any["x"]; - y = any["y"]; - z = any["z"]; - } -} - -Vector3::operator Any() const { - Any any(Any::ARRAY, "Vector3"); - any.append(x, y, z); - return any; -} - -Vector3::Vector3(const class Color3& v) : x(v.r), y(v.g), z(v.b) {} - -Vector3::Vector3(const class Vector3int32& v) : x((float)v.x), y((float)v.y), z((float)v.z) {} - -Vector3::Vector3(const Vector4int8& v) : x(v.x / 127.0f), y(v.y / 127.0f), z(v.z / 127.0f) {} - -Vector3::Vector3(const class Vector2& v, float _z) : x(v.x), y(v.y), z(_z) { -} - -Vector3& Vector3::ignore() { - static Vector3 v; - return v; -} - -const Vector3& Vector3::zero() { static const Vector3 v(0, 0, 0); return v; } -const Vector3& Vector3::one() { static const Vector3 v(1, 1, 1); return v; } -const Vector3& Vector3::unitX() { static const Vector3 v(1, 0, 0); return v; } -const Vector3& Vector3::unitY() { static const Vector3 v(0, 1, 0); return v; } -const Vector3& Vector3::unitZ() { static const Vector3 v(0, 0, 1); return v; } -const Vector3& Vector3::inf() { static const Vector3 v((float)G3D::finf(), (float)G3D::finf(), (float)G3D::finf()); return v; } -const Vector3& Vector3::nan() { static const Vector3 v((float)G3D::fnan(), (float)G3D::fnan(), (float)G3D::fnan()); return v; } -const Vector3& Vector3::minFinite(){ static const Vector3 v(-FLT_MAX, -FLT_MAX, -FLT_MAX); return v; } -const Vector3& Vector3::maxFinite(){ static const Vector3 v(FLT_MAX, FLT_MAX, FLT_MAX); return v; } - -Vector3::Axis Vector3::primaryAxis() const { - - Axis a = X_AXIS; - - double nx = abs(x); - double ny = abs(y); - double nz = abs(z); - - if (nx > ny) { - if (nx > nz) { - a = X_AXIS; - } else { - a = Z_AXIS; - } - } else { - if (ny > nz) { - a = Y_AXIS; - } else { - a = Z_AXIS; - } - } - - return a; -} - - -size_t Vector3::hashCode() const { - unsigned int xhash = (*(int*)(void*)(&x)); - unsigned int yhash = (*(int*)(void*)(&y)); - unsigned int zhash = (*(int*)(void*)(&z)); - - return xhash + (yhash * 37) + (zhash * 101); -} - -std::ostream& operator<<(std::ostream& os, const Vector3& v) { - return os << v.toString(); -} - - -//---------------------------------------------------------------------------- - -double frand() { - return rand() / (double) RAND_MAX; -} - -Vector3::Vector3(TextInput& t) { - deserialize(t); -} - -Vector3::Vector3(BinaryInput& b) { - deserialize(b); -} - - -Vector3::Vector3(const class Vector3int16& v) { - x = v.x; - y = v.y; - z = v.z; -} - - -void Vector3::deserialize(BinaryInput& b) { - x = b.readFloat32(); - y = b.readFloat32(); - z = b.readFloat32(); -} - - -void Vector3::deserialize(TextInput& t) { - t.readSymbol("("); - x = (float)t.readNumber(); - t.readSymbol(","); - y = (float)t.readNumber(); - t.readSymbol(","); - z = (float)t.readNumber(); - t.readSymbol(")"); -} - - -void Vector3::serialize(TextOutput& t) const { - t.writeSymbol("("); - t.writeNumber(x); - t.writeSymbol(","); - t.writeNumber(y); - t.writeSymbol(","); - t.writeNumber(z); - t.writeSymbol(")"); -} - - -void Vector3::serialize(BinaryOutput& b) const { - b.writeFloat32(x); - b.writeFloat32(y); - b.writeFloat32(z); -} - - -Vector3 Vector3::random(Random& r) { - Vector3 result; - r.sphere(result.x, result.y, result.z); - return result; -} - - -float Vector3::unitize(float fTolerance) { - float fMagnitude = magnitude(); - - if (fMagnitude > fTolerance) { - float fInvMagnitude = 1.0f / fMagnitude; - x *= fInvMagnitude; - y *= fInvMagnitude; - z *= fInvMagnitude; - } else { - fMagnitude = 0.0f; - } - - return fMagnitude; -} - - -Vector3 Vector3::reflectAbout(const Vector3& normal) const { - Vector3 out; - - Vector3 N = normal.direction(); - - // 2 * normal.dot(this) * normal - this - return N * 2 * this->dot(N) - *this; -} - - -Vector3 Vector3::cosHemiRandom(const Vector3& normal, Random& r) { - debugAssertM(G3D::fuzzyEq(normal.length(), 1.0f), - "cosHemiRandom requires its argument to have unit length"); - - float x, y, z; - r.cosHemi(x, y, z); - - // Make a coordinate system - const Vector3& Z = normal; - - Vector3 X, Y; - normal.getTangents(X, Y); - - return - x * X + - y * Y + - z * Z; -} - - -Vector3 Vector3::cosPowHemiRandom(const Vector3& normal, const float k, Random& r) { - debugAssertM(G3D::fuzzyEq(normal.length(), 1.0f), - "cosPowHemiRandom requires its argument to have unit length"); - - float x, y, z; - r.cosPowHemi(k, x, y, z); - - // Make a coordinate system - const Vector3& Z = normal; - - Vector3 X, Y; - normal.getTangents(X, Y); - - return - x * X + - y * Y + - z * Z; -} - - -Vector3 Vector3::hemiRandom(const Vector3& normal, Random& r) { - const Vector3& V = Vector3::random(r); - - if (V.dot(normal) < 0) { - return -V; - } else { - return V; - } -} - -//---------------------------------------------------------------------------- - -Vector3 Vector3::reflectionDirection(const Vector3& normal) const { - return -reflectAbout(normal).direction(); -} - -//---------------------------------------------------------------------------- - -Vector3 Vector3::refractionDirection( - const Vector3& normal, - float iInside, - float iOutside) const { - - // From pg. 24 of Henrik Wann Jensen. Realistic Image Synthesis - // Using Photon Mapping. AK Peters. ISBN: 1568811470. July 2001. - - // Invert the directions from Wann Jensen's formulation - // and normalize the vectors. - const Vector3 W = -direction(); - Vector3 N = normal.direction(); - - float h1 = iOutside; - float h2 = iInside; - - if (normal.dot(*this) > 0.0f) { - h1 = iInside; - h2 = iOutside; - N = -N; - } - - const float hRatio = h1 / h2; - const float WdotN = W.dot(N); - - float det = 1.0f - (float)square(hRatio) * (1.0f - (float)square(WdotN)); - - if (det < 0) { - // Total internal reflection - return Vector3::zero(); - } else { - return -hRatio * (W - WdotN * N) - N * sqrt(det); - } -} - -//---------------------------------------------------------------------------- -void Vector3::orthonormalize (Vector3 akVector[3]) { - // If the input vectors are v0, v1, and v2, then the Gram-Schmidt - // orthonormalization produces vectors u0, u1, and u2 as follows, - // - // u0 = v0/|v0| - // u1 = (v1-(u0*v1)u0)/|v1-(u0*v1)u0| - // u2 = (v2-(u0*v2)u0-(u1*v2)u1)/|v2-(u0*v2)u0-(u1*v2)u1| - // - // where |A| indicates length of vector A and A*B indicates dot - // product of vectors A and B. - - // compute u0 - akVector[0].unitize(); - - // compute u1 - float fDot0 = akVector[0].dot(akVector[1]); - akVector[1] -= akVector[0] * fDot0; - akVector[1].unitize(); - - // compute u2 - float fDot1 = akVector[1].dot(akVector[2]); - fDot0 = akVector[0].dot(akVector[2]); - akVector[2] -= akVector[0] * fDot0 + akVector[1] * fDot1; - akVector[2].unitize(); -} - -//---------------------------------------------------------------------------- -void Vector3::generateOrthonormalBasis (Vector3& rkU, Vector3& rkV, - Vector3& rkW, bool bUnitLengthW) { - if ( !bUnitLengthW ) - rkW.unitize(); - - if ( G3D::abs(rkW.x) >= G3D::abs(rkW.y) - && G3D::abs(rkW.x) >= G3D::abs(rkW.z) ) { - rkU.x = -rkW.y; - rkU.y = + rkW.x; - rkU.z = 0.0; - } else { - rkU.x = 0.0; - rkU.y = + rkW.z; - rkU.z = -rkW.y; - } - - rkU.unitize(); - rkV = rkW.cross(rkU); -} - -//---------------------------------------------------------------------------- - -std::string Vector3::toString() const { - return G3D::format("(%g, %g, %g)", x, y, z); -} - - -//---------------------------------------------------------------------------- - -Matrix3 Vector3::cross() const { - return Matrix3( 0, -z, y, - z, 0, -x, - -y, x, 0); -} - - -void serialize(const Vector3::Axis& a, class BinaryOutput& bo) { - bo.writeUInt8((uint8)a); -} - -void deserialize(Vector3::Axis& a, class BinaryInput& bi) { - a = (Vector3::Axis)bi.readUInt8(); -} - -//---------------------------------------------------------------------------- -// 2-char swizzles - -Vector2 Vector3::xx() const { return Vector2 (x, x); } -Vector2 Vector3::yx() const { return Vector2 (y, x); } -Vector2 Vector3::zx() const { return Vector2 (z, x); } -Vector2 Vector3::xy() const { return Vector2 (x, y); } -Vector2 Vector3::yy() const { return Vector2 (y, y); } -Vector2 Vector3::zy() const { return Vector2 (z, y); } -Vector2 Vector3::xz() const { return Vector2 (x, z); } -Vector2 Vector3::yz() const { return Vector2 (y, z); } -Vector2 Vector3::zz() const { return Vector2 (z, z); } - -// 3-char swizzles - -Vector3 Vector3::xxx() const { return Vector3 (x, x, x); } -Vector3 Vector3::yxx() const { return Vector3 (y, x, x); } -Vector3 Vector3::zxx() const { return Vector3 (z, x, x); } -Vector3 Vector3::xyx() const { return Vector3 (x, y, x); } -Vector3 Vector3::yyx() const { return Vector3 (y, y, x); } -Vector3 Vector3::zyx() const { return Vector3 (z, y, x); } -Vector3 Vector3::xzx() const { return Vector3 (x, z, x); } -Vector3 Vector3::yzx() const { return Vector3 (y, z, x); } -Vector3 Vector3::zzx() const { return Vector3 (z, z, x); } -Vector3 Vector3::xxy() const { return Vector3 (x, x, y); } -Vector3 Vector3::yxy() const { return Vector3 (y, x, y); } -Vector3 Vector3::zxy() const { return Vector3 (z, x, y); } -Vector3 Vector3::xyy() const { return Vector3 (x, y, y); } -Vector3 Vector3::yyy() const { return Vector3 (y, y, y); } -Vector3 Vector3::zyy() const { return Vector3 (z, y, y); } -Vector3 Vector3::xzy() const { return Vector3 (x, z, y); } -Vector3 Vector3::yzy() const { return Vector3 (y, z, y); } -Vector3 Vector3::zzy() const { return Vector3 (z, z, y); } -Vector3 Vector3::xxz() const { return Vector3 (x, x, z); } -Vector3 Vector3::yxz() const { return Vector3 (y, x, z); } -Vector3 Vector3::zxz() const { return Vector3 (z, x, z); } -Vector3 Vector3::xyz() const { return Vector3 (x, y, z); } -Vector3 Vector3::yyz() const { return Vector3 (y, y, z); } -Vector3 Vector3::zyz() const { return Vector3 (z, y, z); } -Vector3 Vector3::xzz() const { return Vector3 (x, z, z); } -Vector3 Vector3::yzz() const { return Vector3 (y, z, z); } -Vector3 Vector3::zzz() const { return Vector3 (z, z, z); } - -// 4-char swizzles - -Vector4 Vector3::xxxx() const { return Vector4 (x, x, x, x); } -Vector4 Vector3::yxxx() const { return Vector4 (y, x, x, x); } -Vector4 Vector3::zxxx() const { return Vector4 (z, x, x, x); } -Vector4 Vector3::xyxx() const { return Vector4 (x, y, x, x); } -Vector4 Vector3::yyxx() const { return Vector4 (y, y, x, x); } -Vector4 Vector3::zyxx() const { return Vector4 (z, y, x, x); } -Vector4 Vector3::xzxx() const { return Vector4 (x, z, x, x); } -Vector4 Vector3::yzxx() const { return Vector4 (y, z, x, x); } -Vector4 Vector3::zzxx() const { return Vector4 (z, z, x, x); } -Vector4 Vector3::xxyx() const { return Vector4 (x, x, y, x); } -Vector4 Vector3::yxyx() const { return Vector4 (y, x, y, x); } -Vector4 Vector3::zxyx() const { return Vector4 (z, x, y, x); } -Vector4 Vector3::xyyx() const { return Vector4 (x, y, y, x); } -Vector4 Vector3::yyyx() const { return Vector4 (y, y, y, x); } -Vector4 Vector3::zyyx() const { return Vector4 (z, y, y, x); } -Vector4 Vector3::xzyx() const { return Vector4 (x, z, y, x); } -Vector4 Vector3::yzyx() const { return Vector4 (y, z, y, x); } -Vector4 Vector3::zzyx() const { return Vector4 (z, z, y, x); } -Vector4 Vector3::xxzx() const { return Vector4 (x, x, z, x); } -Vector4 Vector3::yxzx() const { return Vector4 (y, x, z, x); } -Vector4 Vector3::zxzx() const { return Vector4 (z, x, z, x); } -Vector4 Vector3::xyzx() const { return Vector4 (x, y, z, x); } -Vector4 Vector3::yyzx() const { return Vector4 (y, y, z, x); } -Vector4 Vector3::zyzx() const { return Vector4 (z, y, z, x); } -Vector4 Vector3::xzzx() const { return Vector4 (x, z, z, x); } -Vector4 Vector3::yzzx() const { return Vector4 (y, z, z, x); } -Vector4 Vector3::zzzx() const { return Vector4 (z, z, z, x); } -Vector4 Vector3::xxxy() const { return Vector4 (x, x, x, y); } -Vector4 Vector3::yxxy() const { return Vector4 (y, x, x, y); } -Vector4 Vector3::zxxy() const { return Vector4 (z, x, x, y); } -Vector4 Vector3::xyxy() const { return Vector4 (x, y, x, y); } -Vector4 Vector3::yyxy() const { return Vector4 (y, y, x, y); } -Vector4 Vector3::zyxy() const { return Vector4 (z, y, x, y); } -Vector4 Vector3::xzxy() const { return Vector4 (x, z, x, y); } -Vector4 Vector3::yzxy() const { return Vector4 (y, z, x, y); } -Vector4 Vector3::zzxy() const { return Vector4 (z, z, x, y); } -Vector4 Vector3::xxyy() const { return Vector4 (x, x, y, y); } -Vector4 Vector3::yxyy() const { return Vector4 (y, x, y, y); } -Vector4 Vector3::zxyy() const { return Vector4 (z, x, y, y); } -Vector4 Vector3::xyyy() const { return Vector4 (x, y, y, y); } -Vector4 Vector3::yyyy() const { return Vector4 (y, y, y, y); } -Vector4 Vector3::zyyy() const { return Vector4 (z, y, y, y); } -Vector4 Vector3::xzyy() const { return Vector4 (x, z, y, y); } -Vector4 Vector3::yzyy() const { return Vector4 (y, z, y, y); } -Vector4 Vector3::zzyy() const { return Vector4 (z, z, y, y); } -Vector4 Vector3::xxzy() const { return Vector4 (x, x, z, y); } -Vector4 Vector3::yxzy() const { return Vector4 (y, x, z, y); } -Vector4 Vector3::zxzy() const { return Vector4 (z, x, z, y); } -Vector4 Vector3::xyzy() const { return Vector4 (x, y, z, y); } -Vector4 Vector3::yyzy() const { return Vector4 (y, y, z, y); } -Vector4 Vector3::zyzy() const { return Vector4 (z, y, z, y); } -Vector4 Vector3::xzzy() const { return Vector4 (x, z, z, y); } -Vector4 Vector3::yzzy() const { return Vector4 (y, z, z, y); } -Vector4 Vector3::zzzy() const { return Vector4 (z, z, z, y); } -Vector4 Vector3::xxxz() const { return Vector4 (x, x, x, z); } -Vector4 Vector3::yxxz() const { return Vector4 (y, x, x, z); } -Vector4 Vector3::zxxz() const { return Vector4 (z, x, x, z); } -Vector4 Vector3::xyxz() const { return Vector4 (x, y, x, z); } -Vector4 Vector3::yyxz() const { return Vector4 (y, y, x, z); } -Vector4 Vector3::zyxz() const { return Vector4 (z, y, x, z); } -Vector4 Vector3::xzxz() const { return Vector4 (x, z, x, z); } -Vector4 Vector3::yzxz() const { return Vector4 (y, z, x, z); } -Vector4 Vector3::zzxz() const { return Vector4 (z, z, x, z); } -Vector4 Vector3::xxyz() const { return Vector4 (x, x, y, z); } -Vector4 Vector3::yxyz() const { return Vector4 (y, x, y, z); } -Vector4 Vector3::zxyz() const { return Vector4 (z, x, y, z); } -Vector4 Vector3::xyyz() const { return Vector4 (x, y, y, z); } -Vector4 Vector3::yyyz() const { return Vector4 (y, y, y, z); } -Vector4 Vector3::zyyz() const { return Vector4 (z, y, y, z); } -Vector4 Vector3::xzyz() const { return Vector4 (x, z, y, z); } -Vector4 Vector3::yzyz() const { return Vector4 (y, z, y, z); } -Vector4 Vector3::zzyz() const { return Vector4 (z, z, y, z); } -Vector4 Vector3::xxzz() const { return Vector4 (x, x, z, z); } -Vector4 Vector3::yxzz() const { return Vector4 (y, x, z, z); } -Vector4 Vector3::zxzz() const { return Vector4 (z, x, z, z); } -Vector4 Vector3::xyzz() const { return Vector4 (x, y, z, z); } -Vector4 Vector3::yyzz() const { return Vector4 (y, y, z, z); } -Vector4 Vector3::zyzz() const { return Vector4 (z, y, z, z); } -Vector4 Vector3::xzzz() const { return Vector4 (x, z, z, z); } -Vector4 Vector3::yzzz() const { return Vector4 (y, z, z, z); } -Vector4 Vector3::zzzz() const { return Vector4 (z, z, z, z); } - - - - - - -} // namespace diff --git a/externals/g3dlite/Vector4.cpp b/externals/g3dlite/Vector4.cpp deleted file mode 100644 index f6abc1a6e0c..00000000000 --- a/externals/g3dlite/Vector4.cpp +++ /dev/null @@ -1,520 +0,0 @@ -/** - @file Vector4.cpp - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2001-07-09 - @edited 2009-11-29 - */ - -#include -#include -#include "G3D/Vector4.h" -#include "G3D/Color4.h" -#include "G3D/g3dmath.h" -#include "G3D/stringutils.h" -#include "G3D/BinaryInput.h" -#include "G3D/BinaryOutput.h" -#include "G3D/Vector4int8.h" -#include "G3D/Matrix4.h" -#include "G3D/Any.h" - -namespace G3D { - -Vector4::Vector4(const Any& any) { - any.verifyName("Vector4"); - any.verifyType(Any::TABLE, Any::ARRAY); - any.verifySize(4); - - if (any.type() == Any::ARRAY) { - x = any[0]; - y = any[1]; - z = any[2]; - w = any[3]; - } else { - // Table - x = any["x"]; - y = any["y"]; - z = any["z"]; - w = any["w"]; - } -} - -Vector4::operator Any() const { - Any any(Any::ARRAY, "Vector4"); - any.append(x, y, z, w); - return any; -} - - -Vector4::Vector4(const Vector4int8& v) : x(v.x / 127.0f), y(v.y / 127.0f), z(v.z / 127.0f), w(v.w / 127.0f) { -} - - -const Vector4& Vector4::inf() { - static const Vector4 v((float)G3D::finf(), (float)G3D::finf(), (float)G3D::finf(), (float)G3D::finf()); - return v; -} - - -const Vector4& Vector4::zero() { - static const Vector4 v(0,0,0,0); - return v; -} - -const Vector4& Vector4::nan() { - static Vector4 v((float)G3D::fnan(), (float)G3D::fnan(), (float)G3D::fnan(), (float)G3D::fnan()); - return v; -} - - -size_t Vector4::hashCode() const { - unsigned int xhash = (*(int*)(void*)(&x)); - unsigned int yhash = (*(int*)(void*)(&y)); - unsigned int zhash = (*(int*)(void*)(&z)); - unsigned int whash = (*(int*)(void*)(&w)); - - return xhash + (yhash * 37) + (zhash * 101) + (whash * 241); -} - - -Vector4::Vector4(const class Color4& c) { - x = c.r; - y = c.g; - z = c.b; - w = c.a; -} - - -Vector4::Vector4(const Vector2& v1, const Vector2& v2) { - x = v1.x; - y = v1.y; - z = v2.x; - w = v2.y; -} - - -Vector4::Vector4(const Vector2& v1, float fz, float fw) { - x = v1.x; - y = v1.y; - z = fz; - w = fw; -} - -Vector4::Vector4(BinaryInput& b) { - deserialize(b); -} - - -void Vector4::deserialize(BinaryInput& b) { - x = b.readFloat32(); - y = b.readFloat32(); - z = b.readFloat32(); - w = b.readFloat32(); -} - - -void Vector4::serialize(BinaryOutput& b) const { - b.writeFloat32(x); - b.writeFloat32(y); - b.writeFloat32(z); - b.writeFloat32(w); -} - -//---------------------------------------------------------------------------- - -Vector4 Vector4::operator*(const Matrix4& M) const { - Vector4 result; - for (int i = 0; i < 4; ++i) { - result[i] = 0.0f; - for (int j = 0; j < 4; ++j) { - result[i] += (*this)[j] * M[j][i]; - } - } - return result; -} - - -Vector4 Vector4::operator/ (float fScalar) const { - Vector4 kQuot; - - if ( fScalar != 0.0 ) { - float fInvScalar = 1.0f / fScalar; - kQuot.x = fInvScalar * x; - kQuot.y = fInvScalar * y; - kQuot.z = fInvScalar * z; - kQuot.w = fInvScalar * w; - return kQuot; - } else { - return Vector4::inf(); - } -} - -//---------------------------------------------------------------------------- -Vector4& Vector4::operator/= (float fScalar) { - if (fScalar != 0.0f) { - float fInvScalar = 1.0f / fScalar; - x *= fInvScalar; - y *= fInvScalar; - z *= fInvScalar; - w *= fInvScalar; - } else { - *this = Vector4::inf(); - } - - return *this; -} - - -//---------------------------------------------------------------------------- - -std::string Vector4::toString() const { - return G3D::format("(%g, %g, %g, %g)", x, y, z, w); -} -// 2-char swizzles - -Vector2 Vector4::xx() const { return Vector2 (x, x); } -Vector2 Vector4::yx() const { return Vector2 (y, x); } -Vector2 Vector4::zx() const { return Vector2 (z, x); } -Vector2 Vector4::wx() const { return Vector2 (w, x); } -Vector2 Vector4::xy() const { return Vector2 (x, y); } -Vector2 Vector4::yy() const { return Vector2 (y, y); } -Vector2 Vector4::zy() const { return Vector2 (z, y); } -Vector2 Vector4::wy() const { return Vector2 (w, y); } -Vector2 Vector4::xz() const { return Vector2 (x, z); } -Vector2 Vector4::yz() const { return Vector2 (y, z); } -Vector2 Vector4::zz() const { return Vector2 (z, z); } -Vector2 Vector4::wz() const { return Vector2 (w, z); } -Vector2 Vector4::xw() const { return Vector2 (x, w); } -Vector2 Vector4::yw() const { return Vector2 (y, w); } -Vector2 Vector4::zw() const { return Vector2 (z, w); } -Vector2 Vector4::ww() const { return Vector2 (w, w); } - -// 3-char swizzles - -Vector3 Vector4::xxx() const { return Vector3 (x, x, x); } -Vector3 Vector4::yxx() const { return Vector3 (y, x, x); } -Vector3 Vector4::zxx() const { return Vector3 (z, x, x); } -Vector3 Vector4::wxx() const { return Vector3 (w, x, x); } -Vector3 Vector4::xyx() const { return Vector3 (x, y, x); } -Vector3 Vector4::yyx() const { return Vector3 (y, y, x); } -Vector3 Vector4::zyx() const { return Vector3 (z, y, x); } -Vector3 Vector4::wyx() const { return Vector3 (w, y, x); } -Vector3 Vector4::xzx() const { return Vector3 (x, z, x); } -Vector3 Vector4::yzx() const { return Vector3 (y, z, x); } -Vector3 Vector4::zzx() const { return Vector3 (z, z, x); } -Vector3 Vector4::wzx() const { return Vector3 (w, z, x); } -Vector3 Vector4::xwx() const { return Vector3 (x, w, x); } -Vector3 Vector4::ywx() const { return Vector3 (y, w, x); } -Vector3 Vector4::zwx() const { return Vector3 (z, w, x); } -Vector3 Vector4::wwx() const { return Vector3 (w, w, x); } -Vector3 Vector4::xxy() const { return Vector3 (x, x, y); } -Vector3 Vector4::yxy() const { return Vector3 (y, x, y); } -Vector3 Vector4::zxy() const { return Vector3 (z, x, y); } -Vector3 Vector4::wxy() const { return Vector3 (w, x, y); } -Vector3 Vector4::xyy() const { return Vector3 (x, y, y); } -Vector3 Vector4::yyy() const { return Vector3 (y, y, y); } -Vector3 Vector4::zyy() const { return Vector3 (z, y, y); } -Vector3 Vector4::wyy() const { return Vector3 (w, y, y); } -Vector3 Vector4::xzy() const { return Vector3 (x, z, y); } -Vector3 Vector4::yzy() const { return Vector3 (y, z, y); } -Vector3 Vector4::zzy() const { return Vector3 (z, z, y); } -Vector3 Vector4::wzy() const { return Vector3 (w, z, y); } -Vector3 Vector4::xwy() const { return Vector3 (x, w, y); } -Vector3 Vector4::ywy() const { return Vector3 (y, w, y); } -Vector3 Vector4::zwy() const { return Vector3 (z, w, y); } -Vector3 Vector4::wwy() const { return Vector3 (w, w, y); } -Vector3 Vector4::xxz() const { return Vector3 (x, x, z); } -Vector3 Vector4::yxz() const { return Vector3 (y, x, z); } -Vector3 Vector4::zxz() const { return Vector3 (z, x, z); } -Vector3 Vector4::wxz() const { return Vector3 (w, x, z); } -Vector3 Vector4::xyz() const { return Vector3 (x, y, z); } -Vector3 Vector4::yyz() const { return Vector3 (y, y, z); } -Vector3 Vector4::zyz() const { return Vector3 (z, y, z); } -Vector3 Vector4::wyz() const { return Vector3 (w, y, z); } -Vector3 Vector4::xzz() const { return Vector3 (x, z, z); } -Vector3 Vector4::yzz() const { return Vector3 (y, z, z); } -Vector3 Vector4::zzz() const { return Vector3 (z, z, z); } -Vector3 Vector4::wzz() const { return Vector3 (w, z, z); } -Vector3 Vector4::xwz() const { return Vector3 (x, w, z); } -Vector3 Vector4::ywz() const { return Vector3 (y, w, z); } -Vector3 Vector4::zwz() const { return Vector3 (z, w, z); } -Vector3 Vector4::wwz() const { return Vector3 (w, w, z); } -Vector3 Vector4::xxw() const { return Vector3 (x, x, w); } -Vector3 Vector4::yxw() const { return Vector3 (y, x, w); } -Vector3 Vector4::zxw() const { return Vector3 (z, x, w); } -Vector3 Vector4::wxw() const { return Vector3 (w, x, w); } -Vector3 Vector4::xyw() const { return Vector3 (x, y, w); } -Vector3 Vector4::yyw() const { return Vector3 (y, y, w); } -Vector3 Vector4::zyw() const { return Vector3 (z, y, w); } -Vector3 Vector4::wyw() const { return Vector3 (w, y, w); } -Vector3 Vector4::xzw() const { return Vector3 (x, z, w); } -Vector3 Vector4::yzw() const { return Vector3 (y, z, w); } -Vector3 Vector4::zzw() const { return Vector3 (z, z, w); } -Vector3 Vector4::wzw() const { return Vector3 (w, z, w); } -Vector3 Vector4::xww() const { return Vector3 (x, w, w); } -Vector3 Vector4::yww() const { return Vector3 (y, w, w); } -Vector3 Vector4::zww() const { return Vector3 (z, w, w); } -Vector3 Vector4::www() const { return Vector3 (w, w, w); } - -// 4-char swizzles - -Vector4 Vector4::xxxx() const { return Vector4 (x, x, x, x); } -Vector4 Vector4::yxxx() const { return Vector4 (y, x, x, x); } -Vector4 Vector4::zxxx() const { return Vector4 (z, x, x, x); } -Vector4 Vector4::wxxx() const { return Vector4 (w, x, x, x); } -Vector4 Vector4::xyxx() const { return Vector4 (x, y, x, x); } -Vector4 Vector4::yyxx() const { return Vector4 (y, y, x, x); } -Vector4 Vector4::zyxx() const { return Vector4 (z, y, x, x); } -Vector4 Vector4::wyxx() const { return Vector4 (w, y, x, x); } -Vector4 Vector4::xzxx() const { return Vector4 (x, z, x, x); } -Vector4 Vector4::yzxx() const { return Vector4 (y, z, x, x); } -Vector4 Vector4::zzxx() const { return Vector4 (z, z, x, x); } -Vector4 Vector4::wzxx() const { return Vector4 (w, z, x, x); } -Vector4 Vector4::xwxx() const { return Vector4 (x, w, x, x); } -Vector4 Vector4::ywxx() const { return Vector4 (y, w, x, x); } -Vector4 Vector4::zwxx() const { return Vector4 (z, w, x, x); } -Vector4 Vector4::wwxx() const { return Vector4 (w, w, x, x); } -Vector4 Vector4::xxyx() const { return Vector4 (x, x, y, x); } -Vector4 Vector4::yxyx() const { return Vector4 (y, x, y, x); } -Vector4 Vector4::zxyx() const { return Vector4 (z, x, y, x); } -Vector4 Vector4::wxyx() const { return Vector4 (w, x, y, x); } -Vector4 Vector4::xyyx() const { return Vector4 (x, y, y, x); } -Vector4 Vector4::yyyx() const { return Vector4 (y, y, y, x); } -Vector4 Vector4::zyyx() const { return Vector4 (z, y, y, x); } -Vector4 Vector4::wyyx() const { return Vector4 (w, y, y, x); } -Vector4 Vector4::xzyx() const { return Vector4 (x, z, y, x); } -Vector4 Vector4::yzyx() const { return Vector4 (y, z, y, x); } -Vector4 Vector4::zzyx() const { return Vector4 (z, z, y, x); } -Vector4 Vector4::wzyx() const { return Vector4 (w, z, y, x); } -Vector4 Vector4::xwyx() const { return Vector4 (x, w, y, x); } -Vector4 Vector4::ywyx() const { return Vector4 (y, w, y, x); } -Vector4 Vector4::zwyx() const { return Vector4 (z, w, y, x); } -Vector4 Vector4::wwyx() const { return Vector4 (w, w, y, x); } -Vector4 Vector4::xxzx() const { return Vector4 (x, x, z, x); } -Vector4 Vector4::yxzx() const { return Vector4 (y, x, z, x); } -Vector4 Vector4::zxzx() const { return Vector4 (z, x, z, x); } -Vector4 Vector4::wxzx() const { return Vector4 (w, x, z, x); } -Vector4 Vector4::xyzx() const { return Vector4 (x, y, z, x); } -Vector4 Vector4::yyzx() const { return Vector4 (y, y, z, x); } -Vector4 Vector4::zyzx() const { return Vector4 (z, y, z, x); } -Vector4 Vector4::wyzx() const { return Vector4 (w, y, z, x); } -Vector4 Vector4::xzzx() const { return Vector4 (x, z, z, x); } -Vector4 Vector4::yzzx() const { return Vector4 (y, z, z, x); } -Vector4 Vector4::zzzx() const { return Vector4 (z, z, z, x); } -Vector4 Vector4::wzzx() const { return Vector4 (w, z, z, x); } -Vector4 Vector4::xwzx() const { return Vector4 (x, w, z, x); } -Vector4 Vector4::ywzx() const { return Vector4 (y, w, z, x); } -Vector4 Vector4::zwzx() const { return Vector4 (z, w, z, x); } -Vector4 Vector4::wwzx() const { return Vector4 (w, w, z, x); } -Vector4 Vector4::xxwx() const { return Vector4 (x, x, w, x); } -Vector4 Vector4::yxwx() const { return Vector4 (y, x, w, x); } -Vector4 Vector4::zxwx() const { return Vector4 (z, x, w, x); } -Vector4 Vector4::wxwx() const { return Vector4 (w, x, w, x); } -Vector4 Vector4::xywx() const { return Vector4 (x, y, w, x); } -Vector4 Vector4::yywx() const { return Vector4 (y, y, w, x); } -Vector4 Vector4::zywx() const { return Vector4 (z, y, w, x); } -Vector4 Vector4::wywx() const { return Vector4 (w, y, w, x); } -Vector4 Vector4::xzwx() const { return Vector4 (x, z, w, x); } -Vector4 Vector4::yzwx() const { return Vector4 (y, z, w, x); } -Vector4 Vector4::zzwx() const { return Vector4 (z, z, w, x); } -Vector4 Vector4::wzwx() const { return Vector4 (w, z, w, x); } -Vector4 Vector4::xwwx() const { return Vector4 (x, w, w, x); } -Vector4 Vector4::ywwx() const { return Vector4 (y, w, w, x); } -Vector4 Vector4::zwwx() const { return Vector4 (z, w, w, x); } -Vector4 Vector4::wwwx() const { return Vector4 (w, w, w, x); } -Vector4 Vector4::xxxy() const { return Vector4 (x, x, x, y); } -Vector4 Vector4::yxxy() const { return Vector4 (y, x, x, y); } -Vector4 Vector4::zxxy() const { return Vector4 (z, x, x, y); } -Vector4 Vector4::wxxy() const { return Vector4 (w, x, x, y); } -Vector4 Vector4::xyxy() const { return Vector4 (x, y, x, y); } -Vector4 Vector4::yyxy() const { return Vector4 (y, y, x, y); } -Vector4 Vector4::zyxy() const { return Vector4 (z, y, x, y); } -Vector4 Vector4::wyxy() const { return Vector4 (w, y, x, y); } -Vector4 Vector4::xzxy() const { return Vector4 (x, z, x, y); } -Vector4 Vector4::yzxy() const { return Vector4 (y, z, x, y); } -Vector4 Vector4::zzxy() const { return Vector4 (z, z, x, y); } -Vector4 Vector4::wzxy() const { return Vector4 (w, z, x, y); } -Vector4 Vector4::xwxy() const { return Vector4 (x, w, x, y); } -Vector4 Vector4::ywxy() const { return Vector4 (y, w, x, y); } -Vector4 Vector4::zwxy() const { return Vector4 (z, w, x, y); } -Vector4 Vector4::wwxy() const { return Vector4 (w, w, x, y); } -Vector4 Vector4::xxyy() const { return Vector4 (x, x, y, y); } -Vector4 Vector4::yxyy() const { return Vector4 (y, x, y, y); } -Vector4 Vector4::zxyy() const { return Vector4 (z, x, y, y); } -Vector4 Vector4::wxyy() const { return Vector4 (w, x, y, y); } -Vector4 Vector4::xyyy() const { return Vector4 (x, y, y, y); } -Vector4 Vector4::yyyy() const { return Vector4 (y, y, y, y); } -Vector4 Vector4::zyyy() const { return Vector4 (z, y, y, y); } -Vector4 Vector4::wyyy() const { return Vector4 (w, y, y, y); } -Vector4 Vector4::xzyy() const { return Vector4 (x, z, y, y); } -Vector4 Vector4::yzyy() const { return Vector4 (y, z, y, y); } -Vector4 Vector4::zzyy() const { return Vector4 (z, z, y, y); } -Vector4 Vector4::wzyy() const { return Vector4 (w, z, y, y); } -Vector4 Vector4::xwyy() const { return Vector4 (x, w, y, y); } -Vector4 Vector4::ywyy() const { return Vector4 (y, w, y, y); } -Vector4 Vector4::zwyy() const { return Vector4 (z, w, y, y); } -Vector4 Vector4::wwyy() const { return Vector4 (w, w, y, y); } -Vector4 Vector4::xxzy() const { return Vector4 (x, x, z, y); } -Vector4 Vector4::yxzy() const { return Vector4 (y, x, z, y); } -Vector4 Vector4::zxzy() const { return Vector4 (z, x, z, y); } -Vector4 Vector4::wxzy() const { return Vector4 (w, x, z, y); } -Vector4 Vector4::xyzy() const { return Vector4 (x, y, z, y); } -Vector4 Vector4::yyzy() const { return Vector4 (y, y, z, y); } -Vector4 Vector4::zyzy() const { return Vector4 (z, y, z, y); } -Vector4 Vector4::wyzy() const { return Vector4 (w, y, z, y); } -Vector4 Vector4::xzzy() const { return Vector4 (x, z, z, y); } -Vector4 Vector4::yzzy() const { return Vector4 (y, z, z, y); } -Vector4 Vector4::zzzy() const { return Vector4 (z, z, z, y); } -Vector4 Vector4::wzzy() const { return Vector4 (w, z, z, y); } -Vector4 Vector4::xwzy() const { return Vector4 (x, w, z, y); } -Vector4 Vector4::ywzy() const { return Vector4 (y, w, z, y); } -Vector4 Vector4::zwzy() const { return Vector4 (z, w, z, y); } -Vector4 Vector4::wwzy() const { return Vector4 (w, w, z, y); } -Vector4 Vector4::xxwy() const { return Vector4 (x, x, w, y); } -Vector4 Vector4::yxwy() const { return Vector4 (y, x, w, y); } -Vector4 Vector4::zxwy() const { return Vector4 (z, x, w, y); } -Vector4 Vector4::wxwy() const { return Vector4 (w, x, w, y); } -Vector4 Vector4::xywy() const { return Vector4 (x, y, w, y); } -Vector4 Vector4::yywy() const { return Vector4 (y, y, w, y); } -Vector4 Vector4::zywy() const { return Vector4 (z, y, w, y); } -Vector4 Vector4::wywy() const { return Vector4 (w, y, w, y); } -Vector4 Vector4::xzwy() const { return Vector4 (x, z, w, y); } -Vector4 Vector4::yzwy() const { return Vector4 (y, z, w, y); } -Vector4 Vector4::zzwy() const { return Vector4 (z, z, w, y); } -Vector4 Vector4::wzwy() const { return Vector4 (w, z, w, y); } -Vector4 Vector4::xwwy() const { return Vector4 (x, w, w, y); } -Vector4 Vector4::ywwy() const { return Vector4 (y, w, w, y); } -Vector4 Vector4::zwwy() const { return Vector4 (z, w, w, y); } -Vector4 Vector4::wwwy() const { return Vector4 (w, w, w, y); } -Vector4 Vector4::xxxz() const { return Vector4 (x, x, x, z); } -Vector4 Vector4::yxxz() const { return Vector4 (y, x, x, z); } -Vector4 Vector4::zxxz() const { return Vector4 (z, x, x, z); } -Vector4 Vector4::wxxz() const { return Vector4 (w, x, x, z); } -Vector4 Vector4::xyxz() const { return Vector4 (x, y, x, z); } -Vector4 Vector4::yyxz() const { return Vector4 (y, y, x, z); } -Vector4 Vector4::zyxz() const { return Vector4 (z, y, x, z); } -Vector4 Vector4::wyxz() const { return Vector4 (w, y, x, z); } -Vector4 Vector4::xzxz() const { return Vector4 (x, z, x, z); } -Vector4 Vector4::yzxz() const { return Vector4 (y, z, x, z); } -Vector4 Vector4::zzxz() const { return Vector4 (z, z, x, z); } -Vector4 Vector4::wzxz() const { return Vector4 (w, z, x, z); } -Vector4 Vector4::xwxz() const { return Vector4 (x, w, x, z); } -Vector4 Vector4::ywxz() const { return Vector4 (y, w, x, z); } -Vector4 Vector4::zwxz() const { return Vector4 (z, w, x, z); } -Vector4 Vector4::wwxz() const { return Vector4 (w, w, x, z); } -Vector4 Vector4::xxyz() const { return Vector4 (x, x, y, z); } -Vector4 Vector4::yxyz() const { return Vector4 (y, x, y, z); } -Vector4 Vector4::zxyz() const { return Vector4 (z, x, y, z); } -Vector4 Vector4::wxyz() const { return Vector4 (w, x, y, z); } -Vector4 Vector4::xyyz() const { return Vector4 (x, y, y, z); } -Vector4 Vector4::yyyz() const { return Vector4 (y, y, y, z); } -Vector4 Vector4::zyyz() const { return Vector4 (z, y, y, z); } -Vector4 Vector4::wyyz() const { return Vector4 (w, y, y, z); } -Vector4 Vector4::xzyz() const { return Vector4 (x, z, y, z); } -Vector4 Vector4::yzyz() const { return Vector4 (y, z, y, z); } -Vector4 Vector4::zzyz() const { return Vector4 (z, z, y, z); } -Vector4 Vector4::wzyz() const { return Vector4 (w, z, y, z); } -Vector4 Vector4::xwyz() const { return Vector4 (x, w, y, z); } -Vector4 Vector4::ywyz() const { return Vector4 (y, w, y, z); } -Vector4 Vector4::zwyz() const { return Vector4 (z, w, y, z); } -Vector4 Vector4::wwyz() const { return Vector4 (w, w, y, z); } -Vector4 Vector4::xxzz() const { return Vector4 (x, x, z, z); } -Vector4 Vector4::yxzz() const { return Vector4 (y, x, z, z); } -Vector4 Vector4::zxzz() const { return Vector4 (z, x, z, z); } -Vector4 Vector4::wxzz() const { return Vector4 (w, x, z, z); } -Vector4 Vector4::xyzz() const { return Vector4 (x, y, z, z); } -Vector4 Vector4::yyzz() const { return Vector4 (y, y, z, z); } -Vector4 Vector4::zyzz() const { return Vector4 (z, y, z, z); } -Vector4 Vector4::wyzz() const { return Vector4 (w, y, z, z); } -Vector4 Vector4::xzzz() const { return Vector4 (x, z, z, z); } -Vector4 Vector4::yzzz() const { return Vector4 (y, z, z, z); } -Vector4 Vector4::zzzz() const { return Vector4 (z, z, z, z); } -Vector4 Vector4::wzzz() const { return Vector4 (w, z, z, z); } -Vector4 Vector4::xwzz() const { return Vector4 (x, w, z, z); } -Vector4 Vector4::ywzz() const { return Vector4 (y, w, z, z); } -Vector4 Vector4::zwzz() const { return Vector4 (z, w, z, z); } -Vector4 Vector4::wwzz() const { return Vector4 (w, w, z, z); } -Vector4 Vector4::xxwz() const { return Vector4 (x, x, w, z); } -Vector4 Vector4::yxwz() const { return Vector4 (y, x, w, z); } -Vector4 Vector4::zxwz() const { return Vector4 (z, x, w, z); } -Vector4 Vector4::wxwz() const { return Vector4 (w, x, w, z); } -Vector4 Vector4::xywz() const { return Vector4 (x, y, w, z); } -Vector4 Vector4::yywz() const { return Vector4 (y, y, w, z); } -Vector4 Vector4::zywz() const { return Vector4 (z, y, w, z); } -Vector4 Vector4::wywz() const { return Vector4 (w, y, w, z); } -Vector4 Vector4::xzwz() const { return Vector4 (x, z, w, z); } -Vector4 Vector4::yzwz() const { return Vector4 (y, z, w, z); } -Vector4 Vector4::zzwz() const { return Vector4 (z, z, w, z); } -Vector4 Vector4::wzwz() const { return Vector4 (w, z, w, z); } -Vector4 Vector4::xwwz() const { return Vector4 (x, w, w, z); } -Vector4 Vector4::ywwz() const { return Vector4 (y, w, w, z); } -Vector4 Vector4::zwwz() const { return Vector4 (z, w, w, z); } -Vector4 Vector4::wwwz() const { return Vector4 (w, w, w, z); } -Vector4 Vector4::xxxw() const { return Vector4 (x, x, x, w); } -Vector4 Vector4::yxxw() const { return Vector4 (y, x, x, w); } -Vector4 Vector4::zxxw() const { return Vector4 (z, x, x, w); } -Vector4 Vector4::wxxw() const { return Vector4 (w, x, x, w); } -Vector4 Vector4::xyxw() const { return Vector4 (x, y, x, w); } -Vector4 Vector4::yyxw() const { return Vector4 (y, y, x, w); } -Vector4 Vector4::zyxw() const { return Vector4 (z, y, x, w); } -Vector4 Vector4::wyxw() const { return Vector4 (w, y, x, w); } -Vector4 Vector4::xzxw() const { return Vector4 (x, z, x, w); } -Vector4 Vector4::yzxw() const { return Vector4 (y, z, x, w); } -Vector4 Vector4::zzxw() const { return Vector4 (z, z, x, w); } -Vector4 Vector4::wzxw() const { return Vector4 (w, z, x, w); } -Vector4 Vector4::xwxw() const { return Vector4 (x, w, x, w); } -Vector4 Vector4::ywxw() const { return Vector4 (y, w, x, w); } -Vector4 Vector4::zwxw() const { return Vector4 (z, w, x, w); } -Vector4 Vector4::wwxw() const { return Vector4 (w, w, x, w); } -Vector4 Vector4::xxyw() const { return Vector4 (x, x, y, w); } -Vector4 Vector4::yxyw() const { return Vector4 (y, x, y, w); } -Vector4 Vector4::zxyw() const { return Vector4 (z, x, y, w); } -Vector4 Vector4::wxyw() const { return Vector4 (w, x, y, w); } -Vector4 Vector4::xyyw() const { return Vector4 (x, y, y, w); } -Vector4 Vector4::yyyw() const { return Vector4 (y, y, y, w); } -Vector4 Vector4::zyyw() const { return Vector4 (z, y, y, w); } -Vector4 Vector4::wyyw() const { return Vector4 (w, y, y, w); } -Vector4 Vector4::xzyw() const { return Vector4 (x, z, y, w); } -Vector4 Vector4::yzyw() const { return Vector4 (y, z, y, w); } -Vector4 Vector4::zzyw() const { return Vector4 (z, z, y, w); } -Vector4 Vector4::wzyw() const { return Vector4 (w, z, y, w); } -Vector4 Vector4::xwyw() const { return Vector4 (x, w, y, w); } -Vector4 Vector4::ywyw() const { return Vector4 (y, w, y, w); } -Vector4 Vector4::zwyw() const { return Vector4 (z, w, y, w); } -Vector4 Vector4::wwyw() const { return Vector4 (w, w, y, w); } -Vector4 Vector4::xxzw() const { return Vector4 (x, x, z, w); } -Vector4 Vector4::yxzw() const { return Vector4 (y, x, z, w); } -Vector4 Vector4::zxzw() const { return Vector4 (z, x, z, w); } -Vector4 Vector4::wxzw() const { return Vector4 (w, x, z, w); } -Vector4 Vector4::xyzw() const { return Vector4 (x, y, z, w); } -Vector4 Vector4::yyzw() const { return Vector4 (y, y, z, w); } -Vector4 Vector4::zyzw() const { return Vector4 (z, y, z, w); } -Vector4 Vector4::wyzw() const { return Vector4 (w, y, z, w); } -Vector4 Vector4::xzzw() const { return Vector4 (x, z, z, w); } -Vector4 Vector4::yzzw() const { return Vector4 (y, z, z, w); } -Vector4 Vector4::zzzw() const { return Vector4 (z, z, z, w); } -Vector4 Vector4::wzzw() const { return Vector4 (w, z, z, w); } -Vector4 Vector4::xwzw() const { return Vector4 (x, w, z, w); } -Vector4 Vector4::ywzw() const { return Vector4 (y, w, z, w); } -Vector4 Vector4::zwzw() const { return Vector4 (z, w, z, w); } -Vector4 Vector4::wwzw() const { return Vector4 (w, w, z, w); } -Vector4 Vector4::xxww() const { return Vector4 (x, x, w, w); } -Vector4 Vector4::yxww() const { return Vector4 (y, x, w, w); } -Vector4 Vector4::zxww() const { return Vector4 (z, x, w, w); } -Vector4 Vector4::wxww() const { return Vector4 (w, x, w, w); } -Vector4 Vector4::xyww() const { return Vector4 (x, y, w, w); } -Vector4 Vector4::yyww() const { return Vector4 (y, y, w, w); } -Vector4 Vector4::zyww() const { return Vector4 (z, y, w, w); } -Vector4 Vector4::wyww() const { return Vector4 (w, y, w, w); } -Vector4 Vector4::xzww() const { return Vector4 (x, z, w, w); } -Vector4 Vector4::yzww() const { return Vector4 (y, z, w, w); } -Vector4 Vector4::zzww() const { return Vector4 (z, z, w, w); } -Vector4 Vector4::wzww() const { return Vector4 (w, z, w, w); } -Vector4 Vector4::xwww() const { return Vector4 (x, w, w, w); } -Vector4 Vector4::ywww() const { return Vector4 (y, w, w, w); } -Vector4 Vector4::zwww() const { return Vector4 (z, w, w, w); } -Vector4 Vector4::wwww() const { return Vector4 (w, w, w, w); } - - -}; // namespace diff --git a/externals/g3dlite/debugAssert.cpp b/externals/g3dlite/debugAssert.cpp deleted file mode 100644 index a87161b261f..00000000000 --- a/externals/g3dlite/debugAssert.cpp +++ /dev/null @@ -1,389 +0,0 @@ -/** - @file debugAssert.cpp - - Windows implementation of assertion routines. - - @maintainer Morgan McGuire, graphics3d.com - - @created 2001-08-26 - @edited 2009-06-02 - */ - -#include "G3D/debugAssert.h" -#include "G3D/platform.h" -#ifdef G3D_WIN32 - #include -#endif -#include "G3D/format.h" -#include "G3D/prompt.h" -#include -#include "G3D/debugPrintf.h" -#include "G3D/Log.h" - -#include - -#ifdef _MSC_VER - // disable: "C++ exception handler used" -# pragma warning (push) -# pragma warning (disable : 4530) -#endif - -using namespace std; - -namespace G3D { namespace _internal { - -ConsolePrintHook _consolePrintHook; -AssertionHook _debugHook = _handleDebugAssert_; -AssertionHook _failureHook = _handleErrorCheck_; - -#ifdef G3D_LINUX -#if SOMEONE_MADE_THIS_USEFUL - Display* x11Display = NULL; - Window x11Window = 0; -#endif -#endif - - -#ifdef G3D_WIN32 -static void postToClipboard(const char *text) { - if (OpenClipboard(NULL)) { - HGLOBAL hMem = GlobalAlloc(GHND | GMEM_DDESHARE, strlen(text) + 1); - if (hMem) { - char *pMem = (char*)GlobalLock(hMem); - strcpy(pMem, text); - GlobalUnlock(hMem); - - EmptyClipboard(); - SetClipboardData(CF_TEXT, hMem); - } - - CloseClipboard(); - GlobalFree(hMem); - } -} -#endif - -/** - outTitle should be set before the call - */ -static void createErrorMessage( - const char* expression, - const std::string& message, - const char* filename, - int lineNumber, - std::string& outTitle, - std::string& outMessage) { - - std::string le = ""; - const char* newline = "\n"; - - #ifdef G3D_WIN32 - newline = "\r\n"; - - // The last error value. (Which is preserved across the call). - DWORD lastErr = GetLastError(); - - // The decoded message from FormatMessage - LPTSTR formatMsg = NULL; - - if (NULL == formatMsg) { - FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_IGNORE_INSERTS | - FORMAT_MESSAGE_FROM_SYSTEM, - NULL, - lastErr, - 0, - (LPTSTR)&formatMsg, - 0, - NULL); - } - - // Make sure the message got translated into something. - LPTSTR realLastErr; - if (NULL != formatMsg) { - realLastErr = formatMsg; - } else { - realLastErr = _T("Last error code does not exist."); - } - - if (lastErr != 0) { - le = G3D::format("Last Error (0x%08X): %s\r\n\r\n", lastErr, (LPCSTR)realLastErr); - } - - // Get rid of the allocated memory from FormatMessage. - if (NULL != formatMsg) { - LocalFree((LPVOID)formatMsg); - } - - char modulePath[MAX_PATH]; - GetModuleFileNameA(NULL, modulePath, MAX_PATH); - - const char* moduleName = strrchr(modulePath, '\\'); - outTitle = outTitle + string(" - ") + string(moduleName ? (moduleName + 1) : modulePath); - - #endif - - // Build the message. - outMessage = - G3D::format("%s%s%sExpression: %s%s%s:%d%s%s%s", - message.c_str(), newline, newline, expression, newline, - filename, lineNumber, newline, newline, le.c_str()); -} - - -bool _handleDebugAssert_( - const char* expression, - const std::string& message, - const char* filename, - int lineNumber, - bool useGuiPrompt) { - - std::string dialogTitle = "Assertion Failure"; - std::string dialogText = ""; - createErrorMessage(expression, message, filename, lineNumber, dialogTitle, dialogText); - - #ifdef G3D_WIN32 - DWORD lastErr = GetLastError(); - postToClipboard(dialogText.c_str()); - debugPrintf("\n%s\n", dialogText.c_str()); - #endif - - const int cBreak = 0; - const int cIgnore = 1; - const int cAbort = 2; - - static const char* choices[] = {"Debug", "Ignore", "Exit"}; - - // Log the error - Log::common()->print(std::string("\n**************************\n\n") + dialogTitle + "\n" + dialogText); - - int result = G3D::prompt(dialogTitle.c_str(), dialogText.c_str(), (const char**)choices, 3, useGuiPrompt); - -# ifdef G3D_WIN32 - // Put the incoming last error back. - SetLastError(lastErr); -# endif - - switch (result) { - // -1 shouldn't actually occur because it means - // that we're in release mode. - case -1: - case cBreak: - return true; - break; - - case cIgnore: - return false; - break; - - case cAbort: - exit(-1); - break; - } - - // Should never get here - return false; -} - - -bool _handleErrorCheck_( - const char* expression, - const std::string& message, - const char* filename, - int lineNumber, - bool useGuiPrompt) { - - std::string dialogTitle = "Critical Error"; - std::string dialogText = ""; - - createErrorMessage(expression, message, filename, lineNumber, dialogTitle, dialogText); - - // Log the error - Log::common()->print(std::string("\n**************************\n\n") + dialogTitle + "\n" + dialogText); - #ifdef G3D_WIN32 - DWORD lastErr = GetLastError(); - (void)lastErr; - postToClipboard(dialogText.c_str()); - debugPrintf("\n%s\n", dialogText.c_str()); - #endif - - static const char* choices[] = {"Ok"}; - - const std::string& m = - std::string("An internal error has occured in this program and it will now close. " - "The specific error is below. More information has been saved in \"") + - Log::getCommonLogFilename() + "\".\n" + dialogText; - - int result = G3D::prompt("Error", m.c_str(), (const char**)choices, 1, useGuiPrompt); - (void)result; - - return true; -} - - -#ifdef G3D_WIN32 -static HCURSOR oldCursor; -static RECT oldCursorRect; -static POINT oldCursorPos; -static int oldShowCursorCount; -#endif - -void _releaseInputGrab_() { - #ifdef G3D_WIN32 - - GetCursorPos(&oldCursorPos); - - // Stop hiding the cursor if the application hid it. - oldShowCursorCount = ShowCursor(true) - 1; - - if (oldShowCursorCount < -1) { - for (int c = oldShowCursorCount; c < -1; ++c) { - ShowCursor(true); - } - } - - // Set the default cursor in case the application - // set the cursor to NULL. - oldCursor = GetCursor(); - SetCursor(LoadCursor(NULL, IDC_ARROW)); - - // Allow the cursor full access to the screen - GetClipCursor(&oldCursorRect); - ClipCursor(NULL); - - #elif defined(G3D_LINUX) -#if SOMEONE_MADE_THIS_USEFUL - if (x11Display != NULL) { - XUngrabPointer(x11Display, CurrentTime); - XUngrabKeyboard(x11Display, CurrentTime); - if (x11Window != 0) { - //XUndefineCursor(x11Display, x11Window); - // TODO: Note that we leak this cursor; it should be - // freed in the restore code. - Cursor c = XCreateFontCursor(x11Display, 68); - XDefineCursor(x11Display, x11Window, c); - } - XSync(x11Display, false); - XAllowEvents(x11Display, AsyncPointer, CurrentTime); - XFlush(x11Display); - } -#endif - #elif defined(G3D_OSX) - // TODO: OS X - #endif -} - - -void _restoreInputGrab_() { - #ifdef G3D_WIN32 - - // Restore the old clipping region - ClipCursor(&oldCursorRect); - - SetCursorPos(oldCursorPos.x, oldCursorPos.y); - - // Restore the old cursor - SetCursor(oldCursor); - - // Restore old visibility count - if (oldShowCursorCount < 0) { - for (int c = 0; c > oldShowCursorCount; --c) { - ShowCursor(false); - } - } - - #elif defined(G3D_LINUX) - // TODO: Linux - #elif defined(G3D_OSX) - // TODO: OS X - #endif -} - - -}; // internal namespace - -void setAssertionHook(AssertionHook hook) { - G3D::_internal::_debugHook = hook; -} - -AssertionHook assertionHook() { - return G3D::_internal::_debugHook; -} - -void setFailureHook(AssertionHook hook) { - G3D::_internal::_failureHook = hook; -} - -AssertionHook failureHook() { - return G3D::_internal::_failureHook; -} - - -void setConsolePrintHook(ConsolePrintHook h) { - G3D::_internal::_consolePrintHook = h; -} - -ConsolePrintHook consolePrintHook() { - return G3D::_internal::_consolePrintHook; -} - - -std::string __cdecl debugPrint(const std::string& s) { -# ifdef G3D_WIN32 - const int MAX_STRING_LEN = 1024; - - // Windows can't handle really long strings sent to - // the console, so we break the string. - if (s.size() < MAX_STRING_LEN) { - OutputDebugStringA(s.c_str()); - } else { - for (unsigned int i = 0; i < s.size(); i += MAX_STRING_LEN) { - std::string sub = s.substr(i, MAX_STRING_LEN); - OutputDebugStringA(sub.c_str()); - } - } -# else - fprintf(stderr, "%s", s.c_str()); - fflush(stderr); -# endif - - return s; -} - -std::string __cdecl debugPrintf(const char* fmt ...) { - va_list argList; - va_start(argList, fmt); - std::string s = G3D::vformat(fmt, argList); - va_end(argList); - - return debugPrint(s); -// return debugPrint(consolePrint(s)); -} - -std::string consolePrint(const std::string& s) { - FILE* L = Log::common()->getFile(); - fprintf(L, "%s", s.c_str()); - - if (consolePrintHook()) { - consolePrintHook()(s); - } - - fflush(L); - return s; -} - - -std::string __cdecl consolePrintf(const char* fmt ...) { - va_list argList; - va_start(argList, fmt); - std::string s = G3D::vformat(fmt, argList); - va_end(argList); - - return consolePrint(s); -} - -} // namespace - -#ifdef _MSC_VER -# pragma warning (pop) -#endif diff --git a/externals/g3dlite/fileutils.cpp b/externals/g3dlite/fileutils.cpp deleted file mode 100644 index 3f5eb579ba9..00000000000 --- a/externals/g3dlite/fileutils.cpp +++ /dev/null @@ -1,1165 +0,0 @@ -/** - @file fileutils.cpp - - @author Morgan McGuire, graphics3d.com - - @author 2002-06-06 - @edited 2010-02-05 - */ - -#include -#include -#include "G3D/platform.h" -#include "G3D/fileutils.h" -#include "G3D/BinaryInput.h" -#include "G3D/BinaryOutput.h" -#include "G3D/g3dmath.h" -#include "G3D/stringutils.h" -#include "G3D/Set.h" -#include "G3D/g3dfnmatch.h" - -#include -#include -#if _HAVE_ZIP - #include "zip.h" -#endif - -#ifdef G3D_WIN32 - // Needed for _getcwd - #include - #include -#else - #include - #include - #include - #define _getcwd getcwd - #define _stat stat -#endif - - -namespace G3D { - -namespace _internal { - Set currentFilesUsed; -} - -std::string pathConcat(const std::string& dirname, const std::string& file) { - // Ensure that the directory ends in a slash - if ((dirname.size() != 0) && - (dirname[dirname.size() - 1] != '/') && - (dirname[dirname.size() - 1] != '\\') && - (dirname[dirname.size() - 1] != ':')) { - return dirname + '/' + file; - } else { - return dirname + file; - } -} - -std::string resolveFilename(const std::string& filename) { - if (filename.size() >= 1) { - if ((filename[0] == '/') || (filename[0] == '\\')) { - // Already resolved - return filename; - } else { - - #ifdef G3D_WIN32 - if ((filename.size() >= 2) && (filename[1] == ':')) { - // There is a drive spec on the front. - if ((filename.size() >= 3) && ((filename[2] == '\\') || - (filename[2] == '/'))) { - // Already fully qualified - return filename; - } else { - // The drive spec is relative to the - // working directory on that drive. - debugAssertM(false, "Files of the form d:path are" - " not supported (use a fully qualified" - " name)."); - return filename; - } - } - #endif - } - } - - char buffer[1024]; - - // Prepend the working directory. - _getcwd(buffer, 1024); - - return format("%s/%s", buffer, filename.c_str()); -} - -bool zipfileExists(const std::string& filename) { - std::string outZipfile; - std::string outInternalFile; - return zipfileExists(filename, outZipfile, outInternalFile); -} - -std::string readWholeFile( - const std::string& filename) { - - _internal::currentFilesUsed.insert(filename); - - std::string s; - - debugAssert(filename != ""); - if (fileExists(filename, false)) { - - int64 length = fileLength(filename); - - char* buffer = (char*)System::alignedMalloc(length + 1, 16); - debugAssert(buffer); - FILE* f = fopen(filename.c_str(), "rb"); - debugAssert(f); - int ret = fread(buffer, 1, length, f); - debugAssert(ret == length);(void)ret; - fclose(f); - - buffer[length] = '\0'; - s = std::string(buffer); - - System::alignedFree(buffer); - - } else if (zipfileExists(filename)) { - - void* zipBuffer; - size_t length; - zipRead(filename, zipBuffer, length); - - char* buffer = (char*)System::alignedMalloc(length + 1, 16); - System::memcpy(buffer,zipBuffer, length + 1); - zipClose(zipBuffer); - - buffer[length] = '\0'; - s = std::string(buffer); - System::alignedFree(buffer); - } else { - debugAssertM(false, filename + " not found"); - } - - return s; -} - - -void zipRead(const std::string& file, - void*& data, - size_t& length) { - std::string zip, desiredFile; -#if _HAVE_ZIP - if (zipfileExists(file, zip, desiredFile)) { - struct zip *z = zip_open( zip.c_str(), ZIP_CHECKCONS, NULL ); - { - struct zip_stat info; - zip_stat_init( &info ); // TODO: Docs unclear if zip_stat_init is required. - zip_stat( z, desiredFile.c_str(), ZIP_FL_NOCASE, &info ); - length = info.size; - // sets machines up to use MMX, if they want - data = System::alignedMalloc(length, 16); - struct zip_file *zf = zip_fopen( z, desiredFile.c_str(), ZIP_FL_NOCASE ); - { - int test = zip_fread( zf, data, length ); - debugAssertM((size_t)test == length, - desiredFile + " was corrupt because it unzipped to the wrong size."); - (void)test; - } - zip_fclose( zf ); - } - zip_close( z ); - } else { - data = NULL; - } -#else - data = NULL; -#endif -} - - -void zipClose(void* data) { - System::alignedFree(data); -} - - -int64 fileLength(const std::string& filename) { - struct _stat st; - int result = _stat(filename.c_str(), &st); - - if (result == -1) { -#if _HAVE_ZIP - std::string zip, contents; - if(zipfileExists(filename, zip, contents)){ - int64 requiredMem; - - struct zip *z = zip_open( zip.c_str(), ZIP_CHECKCONS, NULL ); - debugAssertM(z != NULL, zip + ": zip open failed."); - { - struct zip_stat info; - zip_stat_init( &info ); // TODO: Docs unclear if zip_stat_init is required. - int success = zip_stat( z, contents.c_str(), ZIP_FL_NOCASE, &info ); - debugAssertM(success == 0, zip + ": " + contents + ": zip stat failed."); - requiredMem = info.size; - } - zip_close( z ); - return requiredMem; - } else { - return -1; - } -#else - return -1; -#endif - } - - return st.st_size; -} - -/** Used by robustTmpfile. Returns nonzero if fread, fwrite, and fseek all -succeed on the file. - @author Morgan McGuire, http://graphics.cs.williams.edu */ -static int isFileGood(FILE* f) { - - int x, n, result; - - /* Must be a valid file handle */ - if (f == NULL) { - return 0; - } - - /* Try to write */ - x = 1234; - n = fwrite(&x, sizeof(int), 1, f); - - if (n != 1) { - return 0; - } - - /* Seek back to the beginning */ - result = fseek(f, 0, SEEK_SET); - if (result != 0) { - return 0; - } - - /* Read */ - n = fread(&x, sizeof(int), 1, f); - if (n != 1) { - return 0; - } - - /* Seek back to the beginning again */ - fseek(f, 0, SEEK_SET); - - return 1; -} - -FILE* createTempFile() { - FILE* t = NULL; - -//# ifdef G3D_WIN32 - t = tmpfile(); -//# else -// // On Unix, tmpfile generates a warning for any code that links against it. -// const char* tempfilename = "/tmp/g3dtemp.XXXXXXXX"; -// mktemp(tempfilename); -// t = fopen(tempfilename, "w"); -//# endif - -# ifdef _WIN32 - char* n = NULL; -# endif - char name[256]; - - if (isFileGood(t)) { - return t; - } - -# ifdef G3D_WIN32 - /* tmpfile failed; try the tmpnam routine */ - t = fopen(tmpnam(NULL), "w+"); - if (isFileGood(t)) { - return t; - } - - n = _tempnam("c:/tmp/", "t"); - /* Try to create something in C:\tmp */ - t = fopen(n, "w+"); - if (isFileGood(t)) { - return t; - } - - /* Try c:\temp */ - n = _tempnam("c:/temp/", "t"); - t = fopen(n, "w+"); - if (isFileGood(t)) { - return t; - } - - /* try the current directory */ - n = _tempnam("./", "t"); - t = fopen(n, "w+"); - if (isFileGood(t)) { - return t; - } - - sprintf(name, "%s/tmp%d", "c:/temp", rand()); - t = fopen(name, "w+"); - if (isFileGood(t)) { - return t; - } - - /* Try some hardcoded paths */ - sprintf(name, "%s/tmp%d", "c:/tmp", rand()); - t = fopen(name, "w+"); - if (isFileGood(t)) { - return t; - } -# else - sprintf(name, "%s/tmp%d", "/tmp", rand()); - t = fopen(name, "w+"); - if (isFileGood(t)) { - return t; - } -#endif - - sprintf(name, "tmp%d", rand()); - t = fopen(name, "w+"); - if (isFileGood(t)) { - return t; - } - - fprintf(stderr, "Unable to create a temporary file; robustTmpfile returning NULL\n"); - - return NULL; -} - -/////////////////////////////////////////////////////////////////////////////// -void writeWholeFile( - const std::string& filename, - const std::string& str, - bool flush) { - - // Make sure the directory exists. - std::string root, base, ext, path; - Array pathArray; - parseFilename(filename, root, pathArray, base, ext); - - path = root + stringJoin(pathArray, '/'); - if (! fileExists(path, false)) { - createDirectory(path); - } - - FILE* file = fopen(filename.c_str(), "wb"); - - debugAssert(file); - - fwrite(str.c_str(), str.size(), 1, file); - - if (flush) { - fflush(file); - } - fclose(file); -} - -/////////////////////////////////////////////////////////////////////////////// - -/** - Creates the directory (which may optionally end in a /) - and any parents needed to reach it. - */ -void createDirectory( - const std::string& dir) { - - if (dir == "") { - return; - } - - std::string d; - - // Add a trailing / if there isn't one. - switch (dir[dir.size() - 1]) { - case '/': - case '\\': - d = dir; - break; - - default: - d = dir + "/"; - } - - // If it already exists, do nothing - if (fileExists(d.substr(0, d.size() - 1)), false) { - return; - } - - // Parse the name apart - std::string root, base, ext; - Array path; - - std::string lead; - parseFilename(d, root, path, base, ext); - debugAssert(base == ""); - debugAssert(ext == ""); - - // Begin with an extra period so "c:\" becomes "c:\.\" after - // appending a path and "c:" becomes "c:.\", not root: "c:\" - std::string p = root + "."; - - // Create any intermediate that doesn't exist - for (int i = 0; i < path.size(); ++i) { - p += "/" + path[i]; - if (! fileExists(p, false)) { - // Windows only requires one argument to mkdir, - // where as unix also requires the permissions. -# ifndef G3D_WIN32 - mkdir(p.c_str(), 0777); -# else - _mkdir(p.c_str()); -# endif - } - } -} - -/////////////////////////////////////////////////////////////////////////////// - -class FileSystemCache { -private: - - Table > m_files; - -public: - - bool fileExists(const std::string& filename) { - const std::string& path = resolveFilename(filenamePath(filename)); - const std::string& name = filenameBaseExt(filename); - - bool neverBeforeSeen = false; - Array& fileList = m_files.getCreate(path, neverBeforeSeen); - if (neverBeforeSeen) { - if (! G3D::fileExists(path, true, false)) { - // The path itself doesn't exist... back out our insertion (which makes fileList& invalid) - m_files.remove(path); - return false; - } - - std::string spec = pathConcat(path, "*"); - - // Will automatically recurse into zipfiles - getFiles(spec, fileList); - getDirs(spec, fileList); - -# ifdef G3D_WIN32 - { - // Case insensitive - for (int i = 0; i < fileList.size(); ++i) { - fileList[i] = toLower(fileList[i]); - } - } -# endif - } - - if (filenameContainsWildcards(name)) { - // See if anything matches - for (int i = 0; i < fileList.size(); ++i) { - if (g3dfnmatch(name.c_str(), fileList[i].c_str(), 0) == 0) { - return true; - } - } - return false; - } else { - // On windows, this is a lower-lower comparison, so it is case insensitive - return fileList.contains(name); - } - } - - void clear() { - m_files.clear(); - } - - static FileSystemCache& instance() { - static FileSystemCache i; - return i; - } -}; - - -void clearFileSystemCache() { - FileSystemCache::instance().clear(); -} - -bool fileExists -(const std::string& _filename, - bool lookInZipfiles, - bool trustCache) { - - if (_filename.empty()) { - return false; - } - - // Remove trailing slash from directories - const std::string& filename = (endsWith(_filename, "/") || endsWith(_filename, "\\")) ? _filename.substr(0, _filename.length() - 1) : _filename; - - if (trustCache && lookInZipfiles) { -# ifdef G3D_WIN32 - // Case insensitive - return FileSystemCache::instance().fileExists(toLower(filename)); -# else - return FileSystemCache::instance().fileExists(filename); -# endif - } - - // Useful for debugging - //char curdir[1024]; _getcwd(curdir, 1024); - - struct _stat st; - int ret = _stat(filename.c_str(), &st); - - // _stat returns zero on success - bool exists = (ret == 0); - - if (! exists && lookInZipfiles) { - // Does not exist standalone, but might exist in a zipfile - - // These output arguments will be ignored - std::string zipDir, internalPath; - return zipfileExists(filename, zipDir, internalPath); - } else { - return exists; - } -} - -/////////////////////////////////////////////////////////////////////////////// - -#if _HAVE_ZIP -/* Helper methods for zipfileExists()*/ -// Given a string (the drive) and an array (the path), computes the directory -static void _zip_resolveDirectory(std::string& completeDir, const std::string& drive, const Array& path, const int length){ - completeDir = drive; - int tempLength; - // if the given length is longer than the array, we correct it - if(length > path.length()){ - tempLength = path.length(); - } else{ - tempLength = length; - } - - for(int t = 0; t < tempLength; ++t){ - if(t > 0){ - completeDir += "/"; - } - completeDir += path[t]; - } -} - - -// assumes that zipDir references a .zip file -static bool _zip_zipContains(const std::string& zipDir, const std::string& desiredFile){ - struct zip *z = zip_open( zipDir.c_str(), ZIP_CHECKCONS, NULL ); - //the last parameter, an int, determines case sensitivity: - //1 is sensitive, 2 is not, 0 is default - int test = zip_name_locate( z, desiredFile.c_str(), ZIP_FL_NOCASE ); - zip_close( z ); - if(test == -1){ - return false; - } - return true; -} -#endif - -// If no zipfile exists, outZipfile and outInternalFile are unchanged -bool zipfileExists(const std::string& filename, std::string& outZipfile, - std::string& outInternalFile){ -#if _HAVE_ZIP - Array path; - std::string drive, base, ext, zipfile, infile; - parseFilename(filename, drive, path, base, ext); - - // Put the filename back together - if ((base != "") && (ext != "")) { - infile = base + "." + ext; - } else { - infile = base + ext; - } - - // Remove "." from path - for (int i = 0; i < path.length(); ++i) { - if (path[i] == ".") { - path.remove(i); - --i; - } - } - - // Remove ".." from path - for (int i = 1; i < path.length(); ++i) { - if ((path[i] == "..") && (i > 0) && (path[i - 1] != "..")) { - // Remove both i and i - 1 - path.remove(i - 1, 2); - i -= 2; - } - } - - // Walk the path backwards, accumulating pieces onto the infile until - // we find a zipfile that contains it - for (int t = 0; t < path.length(); ++t){ - _zip_resolveDirectory(zipfile, drive, path, path.length() - t); - if (t > 0) { - infile = path[path.length() - t] + "/" + infile; - } - - if (endsWith(zipfile, "..")) { - return false; - } - - if (fileExists(zipfile, false)) { - // test if it actually is a zipfile - // if not, return false, a bad - // directory structure has been given, - // not a .zip - if (isZipfile(zipfile)){ - - if (_zip_zipContains(zipfile, infile)){ - outZipfile = zipfile; - outInternalFile = infile; - return true; - } else { - return false; - } - } else { - // the directory structure was valid but did not point to a .zip - return false; - } - } - - } -#endif - // not a valid directory structure ever, - // obviously no .zip was found within the path - return false; -} - -/////////////////////////////////////////////////////////////////////////////// - -std::string generateFilenameBase(const std::string& prefix, const std::string& suffix) { - Array exist; - - // Note "template" is a reserved word in C++ - std::string templat = prefix + System::currentDateString() + "_"; - getFiles(templat + "*", exist); - - // Remove extensions - for (int i = 0; i < exist.size(); ++i) { - exist[i] = filenameBase(exist[i]); - } - - int num = 0; - std::string result; - templat += "%03d" + suffix; - do { - result = format(templat.c_str(), num); - ++num; - } while (exist.contains(result)); - - return result; -} - -/////////////////////////////////////////////////////////////////////////////// - -void copyFile( - const std::string& source, - const std::string& dest) { - - #ifdef G3D_WIN32 - CopyFileA(source.c_str(), dest.c_str(), FALSE); - #else - // TODO: don't use BinaryInput and BinaryOutput - // Read it all in, then dump it out - BinaryInput in(source, G3D_LITTLE_ENDIAN); - BinaryOutput out(dest, G3D_LITTLE_ENDIAN); - out.writeBytes(in.getCArray(), in.size()); - out.commit(false); - #endif -} - -////////////////////////////////////////////////////////////////////////////// - -void parseFilename( - const std::string& filename, - std::string& root, - Array& path, - std::string& base, - std::string& ext) { - - std::string f = filename; - - root = ""; - path.clear(); - base = ""; - ext = ""; - - if (f == "") { - // Empty filename - return; - } - - // See if there is a root/drive spec. - if ((f.size() >= 2) && (f[1] == ':')) { - - if ((f.size() > 2) && isSlash(f[2])) { - - // e.g. c:\foo - root = f.substr(0, 3); - f = f.substr(3, f.size() - 3); - - } else { - - // e.g. c:foo - root = f.substr(2); - f = f.substr(2, f.size() - 2); - - } - - } else if ((f.size() >= 2) & isSlash(f[0]) && isSlash(f[1])) { - - // e.g. //foo - root = f.substr(0, 2); - f = f.substr(2, f.size() - 2); - - } else if (isSlash(f[0])) { - - root = f.substr(0, 1); - f = f.substr(1, f.size() - 1); - - } - - // Pull the extension off - { - // Find the period - size_t i = f.rfind('.'); - - if (i != std::string::npos) { - // Make sure it is after the last slash! - size_t j = iMax(f.rfind('/'), f.rfind('\\')); - if ((j == std::string::npos) || (i > j)) { - ext = f.substr(i + 1, f.size() - i - 1); - f = f.substr(0, i); - } - } - } - - // Pull the basename off - { - // Find the last slash - size_t i = iMax(f.rfind('/'), f.rfind('\\')); - - if (i == std::string::npos) { - - // There is no slash; the basename is the whole thing - base = f; - f = ""; - - } else if ((i != std::string::npos) && (i < f.size() - 1)) { - - base = f.substr(i + 1, f.size() - i - 1); - f = f.substr(0, i); - - } - } - - // Parse what remains into path. - size_t prev, cur = 0; - - while (cur < f.size()) { - prev = cur; - - // Allow either slash - size_t i = f.find('/', prev + 1); - size_t j = f.find('\\', prev + 1); - if (i == std::string::npos) { - i = f.size(); - } - - if (j == std::string::npos) { - j = f.size(); - } - - cur = iMin(i, j); - - if (cur == std::string::npos) { - cur = f.size(); - } - - path.append(f.substr(prev, cur - prev)); - ++cur; - } -} - - -/** - Helper for getFileList and getDirectoryList. - - @param wantFiles If false, returns the directories, otherwise - returns the files. - @param includePath If true, the names include paths - */ -static void getFileOrDirListNormal -(const std::string& filespec, - Array& files, - bool wantFiles, - bool includePath) { - - bool test = wantFiles ? true : false; - - std::string path = ""; - - // Find the place where the path ends and the file-spec begins - size_t i = filespec.rfind('/'); - size_t j = filespec.rfind('\\'); - - // Drive letters on Windows can separate a path - size_t k = filespec.rfind(':'); - - if (((j != std::string::npos) && (j > i)) || - (i == std::string::npos)) { - i = j; - } - - if (((k != std::string::npos) && (k > i)) || - (i == std::string::npos)) { - i = k; - } - - // If there is a path, pull it off - if (i != std::string::npos) { - path = filespec.substr(0, i + 1); - } - - std::string prefix = path; - - if (path.size() > 0) { - // Strip the trailing character - path = path.substr(0, path.size() - 1); - } - -# ifdef G3D_WIN32 - { - struct _finddata_t fileinfo; - - long handle = _findfirst(filespec.c_str(), &fileinfo); - int result = handle; - - while (result != -1) { - if ((((fileinfo.attrib & _A_SUBDIR) == 0) == test) && - strcmp(fileinfo.name, ".") && - strcmp(fileinfo.name, "..")) { - - if (includePath) { - files.append(prefix + fileinfo.name); - } else { - files.append(fileinfo.name); - } - } - - result = _findnext(handle, &fileinfo); - } - } -# else - { - if (path == "") { - // Empty paths don't work on Unix - path = "."; - } - - // Unix implementation - DIR* dir = opendir(path.c_str()); - - if (dir != NULL) { - struct dirent* entry = readdir(dir); - - while (entry != NULL) { - - // Exclude '.' and '..' - if ((strcmp(entry->d_name, ".") != 0) && - (strcmp(entry->d_name, "..") != 0)) { - - // Form a name with a path - std::string filename = prefix + entry->d_name; - // See if this is a file or a directory - struct _stat st; - bool exists = _stat(filename.c_str(), &st) != -1; - - if (exists && - - // Make sure it has the correct type - (((st.st_mode & S_IFDIR) == 0) == test) && - - // Make sure it matches the wildcard - (fnmatch(filespec.c_str(), - filename.c_str(), - FNM_PATHNAME) == 0)) { - - if (includePath) { - files.append(filename); - } else { - files.append(entry->d_name); - } - } - } - - entry = readdir(dir); - } - closedir(dir); - } - } -# endif -} - -#if _HAVE_ZIP -/** - @param path The zipfile name (no trailing slash) - @param prefix Directory inside the zipfile. No leading slash, must have trailing slash if non-empty. - @param file Name inside the zipfile that we are testing to see if it matches prefix + "*" - */ -static void _zip_addEntry(const std::string& path, - const std::string& prefix, - const std::string& file, - Set& files, - bool wantFiles, - bool includePath) { - - // Make certain we are within the desired parent folder (prefix) - if (beginsWith(file, prefix)) { - // validityTest was prefix/file - - // Extract everything to the right of the prefix - std::string s = file.substr(prefix.length()); - - if (s == "") { - // This was the name of the prefix - return; - } - - // See if there are any slashes - size_t slashPos = s.find('/'); - - bool add = false; - - if (slashPos == std::string::npos) { - // No slashes, so s must be a file - add = wantFiles; - } else if (! wantFiles) { - // Not all zipfiles list directories as explicit entries. - // Because of this, if we're looking for directories and see - // any path longer than prefix, we must add the subdirectory. - // The Set will fix duplicates for us. - s = s.substr(0, slashPos); - add = true; - } - - if (add) { - if (includePath) { - files.insert(path + "/" + prefix + s); - } else { - files.insert(s); - } - } - } -} -#endif - -static void getFileOrDirListZip(const std::string& path, - const std::string& prefix, - Array& files, - bool wantFiles, - bool includePath){ -#if _HAVE_ZIP - struct zip *z = zip_open( path.c_str(), ZIP_CHECKCONS, NULL ); - - Set fileSet; - - int count = zip_get_num_files( z ); - for( int i = 0; i < count; ++i ) { - struct zip_stat info; - zip_stat_init( &info ); // TODO: Docs unclear if zip_stat_init is required. - zip_stat_index( z, i, ZIP_FL_NOCASE, &info ); - _zip_addEntry(path, prefix, info.name, fileSet, wantFiles, includePath); - } - - zip_close( z ); - - fileSet.getMembers(files); -#endif -} - - -static void determineFileOrDirList( - const std::string& filespec, - Array& files, - bool wantFiles, - bool includePath) { - - // if it is a .zip, prefix will specify the folder within - // whose contents we want to see - std::string prefix = ""; - std::string path = filenamePath(filespec); - - if ((path.size() > 0) && isSlash(path[path.size() - 1])) { - // Strip the trailing slash - path = path.substr(0, path.length() -1); - } - - if ((path == "") || fileExists(path, false)) { - if ((path != "") && isZipfile(path)) { - // .zip should only work if * is specified as the Base + Ext - // Here, we have been asked for the root's contents - debugAssertM(filenameBaseExt(filespec) == "*", "Can only call getFiles/getDirs on zipfiles using '*' wildcard"); - getFileOrDirListZip(path, prefix, files, wantFiles, includePath); - } else { - // It is a normal directory - getFileOrDirListNormal(filespec, files, wantFiles, includePath); - } - } else if (zipfileExists(filenamePath(filespec), path, prefix)) { - // .zip should only work if * is specified as the Base + Ext - // Here, we have been asked for the contents of a folder within the .zip - debugAssertM(filenameBaseExt(filespec) == "*", "Can only call getFiles/getDirs on zipfiles using '*' wildcard"); - getFileOrDirListZip(path, prefix, files, wantFiles, includePath); - } -} - - -void getFiles(const std::string& filespec, - Array& files, - bool includePath) { - - determineFileOrDirList(filespec, files, true, includePath); -} - - -void getDirs( - const std::string& filespec, - Array& files, - bool includePath) { - - determineFileOrDirList(filespec, files, false, includePath); -} - - -std::string filenameBaseExt(const std::string& filename) { - int i = filename.rfind("/"); - int j = filename.rfind("\\"); - - if ((j > i) && (j >= 0)) { - i = j; - } - -# ifdef G3D_WIN32 - j = filename.rfind(":"); - if ((i == -1) && (j >= 0)) { - i = j; - } -# endif - - if (i == -1) { - return filename; - } else { - return filename.substr(i + 1, filename.length() - i); - } -} - - -std::string filenameBase(const std::string& s) { - std::string drive; - std::string base; - std::string ext; - Array path; - - parseFilename(s, drive, path, base, ext); - return base; -} - - -std::string filenameExt(const std::string& filename) { - int i = filename.rfind("."); - if (i >= 0) { - return filename.substr(i + 1, filename.length() - i); - } else { - return ""; - } -} - - -std::string filenamePath(const std::string& filename) { - int i = filename.rfind("/"); - int j = filename.rfind("\\"); - - if ((j > i) && (j >= 0)) { - i = j; - } - -# ifdef G3D_WIN32 - j = filename.rfind(":"); - if ((i == -1) && (j >= 0)) { - i = j; - } -# endif - - if (i == -1) { - return ""; - } else { - return filename.substr(0, i+1); - } -} - - -bool isZipfile(const std::string& filename) { - - FILE* f = fopen(filename.c_str(), "r"); - if (f == NULL) { - return false; - } - uint8 header[4]; - fread(header, 4, 1, f); - - const uint8 zipHeader[4] = {0x50, 0x4b, 0x03, 0x04}; - for (int i = 0; i < 4; ++i) { - if (header[i] != zipHeader[i]) { - fclose(f); - return false; - } - } - - fclose(f); - return true; -} - - -bool isDirectory(const std::string& filename) { - struct _stat st; - bool exists = _stat(filename.c_str(), &st) != -1; - return exists && ((st.st_mode & S_IFDIR) != 0); -} - - -bool filenameContainsWildcards(const std::string& filename) { - return (filename.find('*') != std::string::npos) || (filename.find('?') != std::string::npos); -} - - -bool fileIsNewer(const std::string& src, const std::string& dst) { - struct _stat sts; - bool sexists = _stat(src.c_str(), &sts) != -1; - - struct _stat dts; - bool dexists = _stat(dst.c_str(), &dts) != -1; - - return sexists && ((! dexists) || (sts.st_mtime > dts.st_mtime)); -} - - -Array filesUsed() { - Array f; - _internal::currentFilesUsed.getMembers(f); - return f; -} - -} - -#ifndef G3D_WIN32 - #undef _stat -#endif diff --git a/externals/g3dlite/format.cpp b/externals/g3dlite/format.cpp deleted file mode 100644 index d9d1b516393..00000000000 --- a/externals/g3dlite/format.cpp +++ /dev/null @@ -1,164 +0,0 @@ -/** - @file format.cpp - - @author Morgan McGuire, graphics3d.com - - @created 2000-09-09 - @edited 2006-08-14 -*/ - -#include "G3D/format.h" -#include "G3D/platform.h" -#include "G3D/System.h" - -#ifdef _MSC_VER - // disable: "C++ exception handler used" -# pragma warning (push) -# pragma warning (disable : 4530) -#endif // _MSC_VER - -// If your platform does not have vsnprintf, you can find a -// implementation at http://www.ijs.si/software/snprintf/ - -namespace G3D { - -std::string __cdecl format(const char* fmt,...) { - va_list argList; - va_start(argList,fmt); - std::string result = vformat(fmt, argList); - va_end(argList); - - return result; -} - -#if defined(_MSC_VER) && (_MSC_VER >= 1300) -// Both MSVC seems to use the non-standard vsnprintf -// so we are using vscprintf to determine buffer size, however -// only MSVC7 and up headers include vscprintf for some reason. -std::string vformat(const char *fmt, va_list argPtr) { - // We draw the line at a 1MB string. - const int maxSize = 1000000; - - // If the string is less than 161 characters, - // allocate it on the stack because this saves - // the malloc/free time. - const int bufSize = 161; - char stackBuffer[bufSize]; - - // MSVC does not support va_copy - int actualSize = _vscprintf(fmt, argPtr) + 1; - - if (actualSize > bufSize) { - - // Now use the heap. - char* heapBuffer = NULL; - - if (actualSize < maxSize) { - - heapBuffer = (char*)System::malloc(maxSize + 1); - _vsnprintf(heapBuffer, maxSize, fmt, argPtr); - heapBuffer[maxSize] = '\0'; - } else { - heapBuffer = (char*)System::malloc(actualSize); - vsprintf(heapBuffer, fmt, argPtr); - } - - std::string formattedString(heapBuffer); - System::free(heapBuffer); - return formattedString; - } else { - - vsprintf(stackBuffer, fmt, argPtr); - return std::string(stackBuffer); - } -} - -#elif defined(_MSC_VER) && (_MSC_VER < 1300) - -std::string vformat(const char *fmt, va_list argPtr) { - // We draw the line at a 1MB string. - const int maxSize = 1000000; - - // If the string is less than 161 characters, - // allocate it on the stack because this saves - // the malloc/free time. - const int bufSize = 161; - char stackBuffer[bufSize]; - - // MSVC6 doesn't support va_copy, however it also seems to compile - // correctly if we just pass our argument list along. Note that - // this whole code block is only compiled if we're on MSVC6 anyway - int actualWritten = _vsnprintf(stackBuffer, bufSize, fmt, argPtr); - - // Not a big enough buffer, bufSize characters written - if (actualWritten == -1) { - - int heapSize = 512; - double powSize = 1.0; - char* heapBuffer = (char*)System::malloc(heapSize); - - while ((_vsnprintf(heapBuffer, heapSize, fmt, argPtr) == -1) && - (heapSize < maxSize)) { - - heapSize = iCeil(heapSize * ::pow((double)2.0, powSize++)); - heapBuffer = (char*)System::realloc(heapBuffer, heapSize); - } - - heapBuffer[heapSize-1] = '\0'; - - std::string heapString(heapBuffer); - System::free(heapBuffer); - - return heapString; - } else { - - return std::string(stackBuffer); - } -} - -#else - -// glibc 2.1 has been updated to the C99 standard -std::string vformat(const char* fmt, va_list argPtr) { - // If the string is less than 161 characters, - // allocate it on the stack because this saves - // the malloc/free time. The number 161 is chosen - // to support two lines of text on an 80 character - // console (plus the null terminator). - const int bufSize = 161; - char stackBuffer[bufSize]; - - va_list argPtrCopy; - va_copy(argPtrCopy, argPtr); - int numChars = vsnprintf(stackBuffer, bufSize, fmt, argPtrCopy); - va_end(argPtrCopy); - - if (numChars >= bufSize) { - // We didn't allocate a big enough string. - char* heapBuffer = (char*)System::malloc((numChars + 1) * sizeof(char)); - - debugAssert(heapBuffer); - int numChars2 = vsnprintf(heapBuffer, numChars + 1, fmt, argPtr); - debugAssert(numChars2 == numChars); - (void)numChars2; - - std::string result(heapBuffer); - - System::free(heapBuffer); - - return result; - - } else { - - return std::string(stackBuffer); - - } -} - -#endif - -} // namespace - -#ifdef _MSC_VER -# pragma warning (pop) -#endif diff --git a/externals/g3dlite/g3dfnmatch.cpp b/externals/g3dlite/g3dfnmatch.cpp deleted file mode 100644 index 39ef7b31914..00000000000 --- a/externals/g3dlite/g3dfnmatch.cpp +++ /dev/null @@ -1,204 +0,0 @@ -/*- -* Copyright (c) 1992, 1993 -*The Regents of the University of California. 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. All advertising materials mentioning features or use of this software -* must display the following acknowledgement: -*This product includes software developed by the University of -*California, Berkeley and its contributors. -* 4. Neither the name of the University 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 REGENTS 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 REGENTS 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. -* -*@(#)fnmatch.h8.1 (Berkeley) 6/2/93 -* -* From FreeBSD fnmatch.h 1.7 -* $Id: g3dfnmatch.cpp,v 1.2 2010/02/06 10:03:24 corey_taylor Exp $ -*/ -#include "G3D/g3dfnmatch.h" - -#ifdef G3D_WIN32 - -#include -#include -#include - -namespace G3D { - -#define EOS '\0' - -static const char *rangematch(const char *, char, int); - -int g3dfnmatch(const char *pattern, const char *string, int flags) -{ - const char *stringstart; - char c, test; - - for (stringstart = string;;) - switch (c = *pattern++) { - case EOS: - if ((flags & FNM_LEADING_DIR) && *string == '/') - return (0); - return (*string == EOS ? 0 : FNM_NOMATCH); - case '?': - if (*string == EOS) - return (FNM_NOMATCH); - if (*string == '/' && (flags & FNM_PATHNAME)) - return (FNM_NOMATCH); - if (*string == '.' && (flags & FNM_PERIOD) && - (string == stringstart || - ((flags & FNM_PATHNAME) && *(string - 1) == '/'))) - return (FNM_NOMATCH); - ++string; - break; - case '*': - c = *pattern; - /* Collapse multiple stars. */ - while (c == '*') - c = *++pattern; - - if (*string == '.' && (flags & FNM_PERIOD) && - (string == stringstart || - ((flags & FNM_PATHNAME) && *(string - 1) == '/'))) - return (FNM_NOMATCH); - - /* Optimize for pattern with * at end or before /. */ - if (c == EOS) - if (flags & FNM_PATHNAME) - return ((flags & FNM_LEADING_DIR) || - strchr(string, '/') == NULL ? - 0 : FNM_NOMATCH); - else - return (0); - else if (c == '/' && flags & FNM_PATHNAME) { - if ((string = strchr(string, '/')) == NULL) - return (FNM_NOMATCH); - break; - } - - /* General case, use recursion. */ - while ((test = *string) != EOS) { - if (!rangematch(pattern, *string, flags & ~FNM_PERIOD)) - return (0); - if (test == '/' && flags & FNM_PATHNAME) - break; - ++string; - } - return (FNM_NOMATCH); - case '[': - if (*string == EOS) - return (FNM_NOMATCH); - if (*string == '/' && flags & FNM_PATHNAME) - return (FNM_NOMATCH); - if ((pattern = - rangematch(pattern, *string, flags)) == NULL) - return (FNM_NOMATCH); - ++string; - break; - case '\\': - if (!(flags & FNM_NOESCAPE)) { - if ((c = *pattern++) == EOS) { - c = '\\'; - --pattern; - } - } - /* FALLTHROUGH */ - default: - if (c == *string) - ; - else if ((flags & FNM_CASEFOLD) && - (tolower((unsigned char)c) == - tolower((unsigned char)*string))) - ; - else if ((flags & FNM_PREFIX_DIRS) && *string == EOS && - ((c == '/' && string != stringstart) || - (string == stringstart+1 && *stringstart == '/'))) - return (0); - else - return (FNM_NOMATCH); - string++; - break; - } - /* NOTREACHED */ -} - -static const char * -rangematch(const char *pattern, char test, int flags) -{ - int negate, ok; - char c, c2; - - /* - * A bracket expression starting with an unquoted circumflex - * character produces unspecified results (IEEE 1003.2-1992, - * 3.13.2). This implementation treats it like '!', for - * consistency with the regular expression syntax. - * J.T. Conklin (conklin@ngai.kaleida.com) - */ - if ( (negate = (*pattern == '!' || *pattern == '^')) ) - ++pattern; - - if (flags & FNM_CASEFOLD) - test = tolower((unsigned char)test); - - for (ok = 0; (c = *pattern++) != ']';) { - if (c == '\\' && !(flags & FNM_NOESCAPE)) - c = *pattern++; - if (c == EOS) - return (NULL); - - if (flags & FNM_CASEFOLD) - c = tolower((unsigned char)c); - - if (*pattern == '-' - && (c2 = *(pattern+1)) != EOS && c2 != ']') { - pattern += 2; - if (c2 == '\\' && !(flags & FNM_NOESCAPE)) - c2 = *pattern++; - if (c2 == EOS) - return (NULL); - - if (flags & FNM_CASEFOLD) - c2 = tolower((unsigned char)c2); - - if ((unsigned char)c <= (unsigned char)test && - (unsigned char)test <= (unsigned char)c2) - ok = 1; - } else if (c == test) - ok = 1; - } - return (ok == negate ? NULL : pattern); -} - -} - -#else - -namespace G3D { -int g3dfnmatch(const char * a, const char *b, int c) { - return fnmatch(a, b, c); -} -} - -#endif - diff --git a/externals/g3dlite/g3dmath.cpp b/externals/g3dlite/g3dmath.cpp deleted file mode 100644 index ad85e9efb9b..00000000000 --- a/externals/g3dlite/g3dmath.cpp +++ /dev/null @@ -1,108 +0,0 @@ -/** - @file g3dmath.cpp - - @author Morgan McGuire, graphics3d.com - - @created 2001-06-02 - @edited 2004-02-24 - */ - -#include "G3D/g3dmath.h" -#include -#include - -namespace G3D { - -float gaussRandom(float mean, float stdev) { - - // Using Box-Mueller method from http://www.taygeta.com/random/gaussian.html - // Modified to specify standard deviation and mean of distribution - float w, x1, x2; - - // Loop until w is less than 1 so that log(w) is negative - do { - x1 = uniformRandom(-1.0, 1.0); - x2 = uniformRandom(-1.0, 1.0); - - w = float(square(x1) + square(x2)); - } while (w > 1.0f); - - // Transform to gassian distribution - // Multiply by sigma (stdev ^ 2) and add mean. - return x2 * (float)square(stdev) * sqrtf((-2.0f * logf(w) ) / w) + mean; -} - -/** - This value should not be tested against directly, instead - G3D::isNan() and G3D::isFinite() will return reliable results. */ -double inf() { - return std::numeric_limits::infinity(); -} - -bool isNaN(float x) { - static const float n = nan(); - return memcmp(&x, &n, sizeof(float)) == 0; -} - -bool isNaN(double x) { - static const double n = nan(); - return memcmp(&x, &n, sizeof(double)) == 0; -} - - -/** - This value should not be tested against directly, instead - G3D::isNan() and G3D::isFinite() will return reliable results. */ -float finf() { - return std::numeric_limits::infinity(); -} - -/** This value should not be tested against directly, instead - G3D::isNan() and G3D::isFinite() will return reliable results. */ -double nan() { - // double is a standard type and should have quiet NaN - return std::numeric_limits::quiet_NaN(); -} - -float fnan() { - // double is a standard type and should have quiet NaN - return std::numeric_limits::quiet_NaN(); -} - - -int highestBit(uint32 x) { - // Binary search. - int base = 0; - - if (x & 0xffff0000) { - base = 16; - x >>= 16; - } - if (x & 0x0000ff00) { - base += 8; - x >>= 8; - } - if (x & 0x000000f0) { - base += 4; - x >>= 4; - } - - static const int lut[] = {-1,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3}; - return base + lut[x]; -} - - -int iRandom(int low, int high) { - int r = iFloor(low + (high - low + 1) * (double)rand() / RAND_MAX); - - // There is a *very small* chance of generating - // a number larger than high. - if (r > high) { - return high; - } else { - return r; - } -} - - -} diff --git a/externals/g3dlite/prompt.cpp b/externals/g3dlite/prompt.cpp deleted file mode 100644 index 6a28e6462b4..00000000000 --- a/externals/g3dlite/prompt.cpp +++ /dev/null @@ -1,729 +0,0 @@ -/** - @file prompt.cpp - - @author Morgan McGuire, http://graphics.cs.williams.edu - @cite Windows dialog interface by Max McGuire, mmcguire@ironlore.com - @cite Font setting code by Kurt Miller, kurt@flipcode.com - - @created 2000-08-26 - @edited 2005-01-14 - */ - -#include "G3D/prompt.h" -#include "G3D/platform.h" - -#include - -#ifdef G3D_WIN32 -# include -# include -#else -# define _getch getchar -#endif - -#ifdef G3D_OSX - -/*#ifdef __LP64__ -# undef __LP64__ -#endif -*/ - -# include - -/* -#ifdef G3D_64BIT -# define __LP64__ -#endif -*/ - -#endif - -namespace G3D { - -#ifdef G3D_WIN32 - -namespace _internal { -/** - Generic Win32 dialog facility. - @author Max McGuire - */ -class DialogTemplate { -public: - - DialogTemplate(LPCSTR caption, DWORD style, - int x, int y, int w, int h, - LPCSTR font = NULL, WORD fontSize = 8) { - - usedBufferLength = sizeof(DLGTEMPLATE); - totalBufferLength = usedBufferLength; - - dialogTemplate = (DLGTEMPLATE*)malloc(totalBufferLength); - - dialogTemplate->style = style; - - if (font != NULL) { - dialogTemplate->style |= DS_SETFONT; - } - - dialogTemplate->x = (short)x; - dialogTemplate->y = (short)y; - dialogTemplate->cx = (short)w; - dialogTemplate->cy = (short)h; - dialogTemplate->cdit = 0; - - dialogTemplate->dwExtendedStyle = 0; - - // The dialog box doesn't have a menu or a special class - AppendData("\0", 2); - AppendData("\0", 2); - - // Add the dialog's caption to the template - - AppendString(caption); - - if (font != NULL) { - AppendData(&fontSize, sizeof(WORD)); - AppendString(font); - } - } - - void AddComponent(LPCSTR type, LPCSTR caption, DWORD style, DWORD exStyle, int x, int y, int w, int h, WORD id) { - - DLGITEMTEMPLATE item; - - item.style = style; - item.x = (short)x; - item.y = (short)y; - item.cx = (short)w; - item.cy = (short)h; - item.id = id; - - item.dwExtendedStyle = exStyle; - - AppendData(&item, sizeof(DLGITEMTEMPLATE)); - - AppendString(type); - AppendString(caption); - - WORD creationDataLength = 0; - AppendData(&creationDataLength, sizeof(WORD)); - - // Increment the component count - dialogTemplate->cdit++; - - } - - - void AddButton(LPCSTR caption, DWORD style, DWORD exStyle, int x, int y, int w, int h, WORD id) { - - AddStandardComponent(0x0080, caption, style, exStyle, x, y, w, h, id); - - WORD creationDataLength = 0; - AppendData(&creationDataLength, sizeof(WORD)); - - } - - - void AddEditBox(LPCSTR caption, DWORD style, DWORD exStyle, int x, int y, int w, int h, WORD id) { - - AddStandardComponent(0x0081, caption, style, exStyle, x, y, w, h, id); - - WORD creationDataLength = 0; - AppendData(&creationDataLength, sizeof(WORD)); - - } - - - void AddStatic(LPCSTR caption, DWORD style, DWORD exStyle, int x, int y, int w, int h, WORD id) { - - AddStandardComponent(0x0082, caption, style, exStyle, x, y, w, h, id); - - WORD creationDataLength = 0; - AppendData(&creationDataLength, sizeof(WORD)); - - } - - - void AddListBox(LPCSTR caption, DWORD style, DWORD exStyle, int x, int y, int w, int h, WORD id) { - - AddStandardComponent(0x0083, caption, style, exStyle, x, y, w, h, id); - - WORD creationDataLength = sizeof(WORD) + 5 * sizeof(WCHAR); - AppendData(&creationDataLength, sizeof(WORD)); - - AppendString("TEST"); - - } - - - void AddScrollBar(LPCSTR caption, DWORD style, DWORD exStyle, int x, int y, int w, int h, WORD id) { - - AddStandardComponent(0x0084, caption, style, exStyle, x, y, w, h, id); - - WORD creationDataLength = 0; - AppendData(&creationDataLength, sizeof(WORD)); - - } - - - void AddComboBox(LPCSTR caption, DWORD style, DWORD exStyle, int x, int y, int w, int h, WORD id) { - - AddStandardComponent(0x0085, caption, style, exStyle, x, y, w, h, id); - - WORD creationDataLength = 0; - AppendData(&creationDataLength, sizeof(WORD)); - - } - - - /** - * - * Returns a pointer to the Win32 dialog template which the object - * represents. This pointer may become invalid if additional components - * are added to the template. - * - */ - operator const DLGTEMPLATE*() const { - return dialogTemplate; - } - - virtual ~DialogTemplate() { - free(dialogTemplate); - } - -protected: - - void AddStandardComponent(WORD type, LPCSTR caption, DWORD style, DWORD exStyle, - int x, int y, int w, int h, WORD id, LPSTR font = NULL, WORD fontSize = 8) { - - DLGITEMTEMPLATE item; - - // DWORD align the beginning of the component data - - AlignData(sizeof(DWORD)); - - item.style = style; - if (font != NULL) { - item.style |= DS_SETFONT; - } - item.x = (short)x; - item.y = (short)y; - item.cx = (short)w; - item.cy = (short)h; - item.id = id; - - item.dwExtendedStyle = exStyle; - - AppendData(&item, sizeof(DLGITEMTEMPLATE)); - - WORD preType = 0xFFFF; - - AppendData(&preType, sizeof(WORD)); - AppendData(&type, sizeof(WORD)); - - AppendString(caption); - - if (font != NULL) { - AppendData(&fontSize, sizeof(WORD)); - AppendString(font); - } - - // Increment the component count - dialogTemplate->cdit++; - } - - - void AlignData(int size) { - - int paddingSize = usedBufferLength % size; - - if (paddingSize != 0) { - EnsureSpace(paddingSize); - usedBufferLength += paddingSize; - } - - } - - void AppendString(LPCSTR string) { - - int length = MultiByteToWideChar(CP_ACP, 0, string, -1, NULL, 0); - - WCHAR* wideString = (WCHAR*)malloc(sizeof(WCHAR) * length); - MultiByteToWideChar(CP_ACP, 0, string, -1, wideString, length); - - AppendData(wideString, length * sizeof(WCHAR)); - free(wideString); - - } - - void AppendData(const void* data, int dataLength) { - - EnsureSpace(dataLength); - - memcpy((char*)dialogTemplate + usedBufferLength, data, dataLength); - usedBufferLength += dataLength; - - } - - void EnsureSpace(int length) { - if (length + usedBufferLength > totalBufferLength) { - totalBufferLength += length * 2; - - void* newBuffer = malloc(totalBufferLength); - memcpy(newBuffer, dialogTemplate, usedBufferLength); - - free(dialogTemplate); - dialogTemplate = (DLGTEMPLATE*)newBuffer; - } - } - -private: - - DLGTEMPLATE* dialogTemplate; - - int totalBufferLength; - int usedBufferLength; - -}; - - -struct PromptParams { - const char* message; - const char* title; -}; - -/** - * Constants for controls. - */ -#define IDC_MESSAGE 1000 -#define IDC_BUTTON0 2000 - -INT_PTR CALLBACK PromptDlgProc(HWND hDlg, UINT msg, - WPARAM wParam, LPARAM lParam) { - switch(msg) { - case WM_INITDIALOG: - { - PromptParams *params = (PromptParams*)lParam; - ::SetWindowTextA(::GetDlgItem(hDlg, IDC_MESSAGE), params->message); - - ::SetFocus(::GetDlgItem(hDlg, IDC_BUTTON0)); - - SetWindowTextA(hDlg, params->title); - - HFONT hfont = - CreateFontA(16, 0, 0, 0, FW_NORMAL, - FALSE, FALSE, FALSE, - ANSI_CHARSET,OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS, - PROOF_QUALITY, FIXED_PITCH | FF_MODERN, "Courier New"); - - SendDlgItemMessage(hDlg, IDC_MESSAGE, WM_SETFONT, (WPARAM)hfont, MAKELPARAM(TRUE,0)); - - - break; - } - case WM_COMMAND: - { - int choiceNumber = LOWORD(wParam) - IDC_BUTTON0; - if ((choiceNumber >= 0) && (choiceNumber < 10)) { - EndDialog(hDlg, choiceNumber); - return TRUE; - } - } - - break; - - case WM_NCDESTROY: - // Under SDL 1.2.6 we get a NCDESTROY message for no reason and the - // window is immediately closed. This is here to debug the problem. - (void)0; - break; - - } - - return FALSE; -} - -}; // namespace _internal - - -using namespace _internal; - -/** - * Show a dialog prompt. - */ -static int guiPrompt( - const char* windowTitle, - const char* prompt, - const char** choice, - int numChoices) { - - int width = 280; - int height = 128; - - const int buttonSpacing = 2; - const int buttonWidth = - (width - buttonSpacing * 2 - - buttonSpacing * (numChoices - 1)) / numChoices; - const int buttonHeight = 13; - - - DialogTemplate dialogTemplate( - windowTitle, - WS_CAPTION | DS_CENTER | WS_SYSMENU, - 10, 10, width, height, - "Tahoma"); - - dialogTemplate.AddEditBox( - "Edit", WS_VISIBLE | ES_READONLY | ES_OEMCONVERT | ES_MULTILINE | WS_TABSTOP, WS_EX_STATICEDGE, - 2, 2, width - 4, height - buttonHeight - 7, IDC_MESSAGE); - - int i; - for (i = 0; i < numChoices; i++) { - - int x = buttonSpacing + i * (buttonWidth + buttonSpacing); - int y = height - buttonHeight - buttonSpacing; - - dialogTemplate.AddButton(choice[i], WS_VISIBLE | WS_TABSTOP, 0, - x, y, buttonWidth, buttonHeight, IDC_BUTTON0 + (WORD)i); - - } - - // Convert all single \n characters to \r\n for proper printing - int strLen = 0; - const char* pStr = prompt; - - while (*pStr != '\0') { - if ((*pStr == '\n') && (pStr != prompt)) { - if (*(pStr - 1) != '\r') { - ++strLen; - } - } - ++strLen; - ++pStr; - } - - char* newStr = (char*)malloc(strLen + 1); - - const char* pStr2 = prompt; - char* pNew = newStr; - - while (*pStr2 != '\0') { - if ((*pStr2 == '\n') && (pStr2 != prompt)) { - if (*(pStr2 - 1) != '\r') { - *pNew = '\r'; - ++pNew; - } - } - *pNew = *pStr2; - ++pNew; - ++pStr2; - } - - *pNew = '\0'; - - PromptParams params; - params.message = newStr;; - params.title = windowTitle; - - HMODULE module = GetModuleHandle(0); - int ret = DialogBoxIndirectParam(module, dialogTemplate, NULL, (DLGPROC) PromptDlgProc, (DWORD)¶ms); - - free(newStr); - - /* - For debugging when DialogBoxIndirectParam fails: - - // The last error value. (Which is preserved across the call). - DWORD lastErr = GetLastError(); - - // The decoded message from FormatMessage - LPTSTR formatMsg = NULL; - - if (NULL == formatMsg) { - FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_IGNORE_INSERTS | - FORMAT_MESSAGE_FROM_SYSTEM, - NULL, - lastErr, - 0, - (LPTSTR)&formatMsg, - 0, - NULL); - } - - // Make sure the message got translated into something. - LPTSTR realLastErr; - if (NULL != formatMsg) { - realLastErr = formatMsg; - } else { - realLastErr = "Last error code does not exist."; - } - - // Get rid of the allocated memory from FormatMessage. - if (NULL != formatMsg) { - LocalFree((LPVOID)formatMsg); - } - */ - - return ret; -} - -#endif - - -/** - * Show a prompt on stdout - */ -static int textPrompt( - const char* windowTitle, - const char* prompt, - const char** choice, - int numChoices) { - - printf("\n___________________________________________________\n"); - printf("%s\n", windowTitle); - printf("%s", prompt); - - if (numChoices > 10) { - numChoices = 10; - } - - int c = -1; - if (numChoices > 1) { - printf("\n"); - printf("Choose an option by number:"); - - while ((c < 0) || (c >= numChoices)) { - printf("\n"); - - for (int i = 0; i < numChoices; i++) { - if (numChoices <= 3) { - printf(" (%d) %s ", i, choice[i]); - } else { - printf(" (%d) %s\n", i, choice[i]); - } - } - - printf("\n> "); - c = _getch() - '0'; - - if ((c < 0) || (c >= numChoices)) { - printf("'%d' is not a valid choice.", c); - } else { - printf("%d", c); - } - } - - } else if (numChoices == 1) { - - printf("\nPress any key for '%s'...", choice[0]); - _getch(); - c = 0; - - } else { - - printf("\nPress any key..."); - _getch(); - c = 0; - } - - printf("\n___________________________________________________\n"); - return c; -} - -#ifdef G3D_OSX - -// See http://developer.apple.com/documentation/Carbon/Reference/Carbon_Event_Manager_Ref/index.html - -#define CARBON_COMMANDID_START 128 -#define CARBON_BUTTON_SPACING 12 -#define CARBON_BUTTON_HEIGHT 20 -#define CARBON_BUTTON_MINWIDTH 69 -#define CARBON_WINDOW_PADDING 20 - -struct CallbackData { - WindowRef refWindow; - - /** Index of this particular button */ - int myIndex; - - /** Buttons store their index into here when pressed. */ - int* whichButton; -}; - -/** - Assumes that userData is a pointer to a carbon_evt_data_t. - - */ -static pascal OSStatus DoCommandEvent(EventHandlerCallRef handlerRef, EventRef event, void* userData) { - // See http://developer.apple.com/documentation/Carbon/Conceptual/HandlingWindowsControls/index.html - - CallbackData& callbackData = *(CallbackData*)userData; - -# pragma unused(handlerRef) - - callbackData.whichButton[0] = callbackData.myIndex; - - // If we get here we can close the window - ::QuitAppModalLoopForWindow(callbackData.refWindow); - - // Return noErr to indicate that we handled the event - return noErr; -} - -static int guiPrompt -(const char* windowTitle, - const char* prompt, - const char** choice, - int numChoices) { - - WindowRef window; - - int iNumButtonRows = 0; - int iButtonWidth = -1; - OSStatus err = noErr; - - // Determine number of rows of buttons - while (iButtonWidth < CARBON_BUTTON_MINWIDTH) { - ++iNumButtonRows; - iButtonWidth = - (550 - (CARBON_WINDOW_PADDING*2 + - (CARBON_BUTTON_SPACING*numChoices))) / - (numChoices/iNumButtonRows); - } - - // Window Variables - Rect rectWin = {0, 0, 200 + ((iNumButtonRows-1) * (CARBON_BUTTON_HEIGHT+CARBON_BUTTON_SPACING)), 550}; // top, left, bottom, right - CFStringRef szWindowTitle = CFStringCreateWithCString(kCFAllocatorDefault, windowTitle, kCFStringEncodingUTF8); - - window = NULL; - - err = CreateNewWindow(kMovableAlertWindowClass, kWindowStandardHandlerAttribute|kWindowCompositingAttribute, &rectWin, &window); - err = SetWindowTitleWithCFString(window, szWindowTitle); - err = SetThemeWindowBackground(window, kThemeBrushAlertBackgroundActive, false); - assert(err == noErr); - - // Event Handler Variables - EventTypeSpec buttonSpec[] = {{ kEventClassControl, kEventControlHit }, { kEventClassCommand, kEventCommandProcess }}; - EventHandlerUPP buttonHandler = NewEventHandlerUPP(DoCommandEvent); - - // Static Text Variables - Rect rectStatic = {20, 20, 152, 530}; - CFStringRef szStaticText = CFStringCreateWithCString(kCFAllocatorDefault, prompt, kCFStringEncodingUTF8); - ControlRef refStaticText = NULL; - err = CreateStaticTextControl(window, &rectStatic, szStaticText, NULL, &refStaticText); - - // Button Variables - Rect bounds[numChoices]; - CFStringRef caption[numChoices]; - ControlRef button[numChoices]; - - int whichButton=-1; - CallbackData callbackData[numChoices]; - - // Create the Buttons and assign event handlers - for (int i = 0; i < numChoices; ++i) { - bounds[i].top = 160 + ((CARBON_BUTTON_HEIGHT+CARBON_BUTTON_SPACING)*(i%iNumButtonRows)); - bounds[i].right = 530 - ((iButtonWidth+CARBON_BUTTON_SPACING)*(i/iNumButtonRows)); - bounds[i].left = bounds[i].right - iButtonWidth; - bounds[i].bottom = bounds[i].top + CARBON_BUTTON_HEIGHT; - - // Convert the button captions to Apple strings - caption[i] = CFStringCreateWithCString(kCFAllocatorDefault, choice[i], kCFStringEncodingUTF8); - - err = CreatePushButtonControl(window, &bounds[i], caption[i], &button[i]); - assert(err == noErr); - - err = SetControlCommandID(button[i], CARBON_COMMANDID_START + i); - assert(err == noErr); - - callbackData[i].refWindow = window; - callbackData[i].myIndex = i; - callbackData[i].whichButton = &whichButton; - - err = InstallControlEventHandler(button[i], buttonHandler, - GetEventTypeCount(buttonSpec), buttonSpec, - &callbackData[i], NULL); - assert(err == noErr); - } - - // Show Dialog - err = RepositionWindow(window, NULL, kWindowCenterOnMainScreen); - ShowWindow(window); - BringToFront(window); - err = ActivateWindow(window, true); - - // Hack to get our window/process to the front... - ProcessSerialNumber psn = { 0, kCurrentProcess}; - TransformProcessType(&psn, kProcessTransformToForegroundApplication); - SetFrontProcess (&psn); - - // Run in Modal State - err = RunAppModalLoopForWindow(window); - - // Dispose of Button Related Data - for (int i = 0; i < numChoices; ++i) { - // Dispose of controls - DisposeControl(button[i]); - - // Release CFStrings - CFRelease(caption[i]); - } - - // Dispose of Other Controls - DisposeControl(refStaticText); - - // Dispose of Event Handlers - DisposeEventHandlerUPP(buttonHandler); - - // Dispose of Window - DisposeWindow(window); - - // Release CFStrings - CFRelease(szWindowTitle); - CFRelease(szStaticText); - - // Return Selection - return whichButton; -} - -#endif - -int prompt( - const char* windowTitle, - const char* prompt, - const char** choice, - int numChoices, - bool useGui) { - - #ifdef G3D_WIN32 - if (useGui) { - // Build the message box - return guiPrompt(windowTitle, prompt, choice, numChoices); - } - #endif - - #ifdef G3D_OSX - if (useGui){ - //Will default to text prompt if numChoices > 4 - return guiPrompt(windowTitle, prompt, choice, numChoices); - } - #endif - return textPrompt(windowTitle, prompt, choice, numChoices); -} - - -void msgBox( - const std::string& message, - const std::string& title) { - - const char *choice[] = {"Ok"}; - prompt(title.c_str(), message.c_str(), choice, 1, true); -} - -#ifndef G3D_WIN32 - #undef _getch -#endif - -};// namespace - diff --git a/externals/g3dlite/stringutils.cpp b/externals/g3dlite/stringutils.cpp deleted file mode 100644 index c3876ebb6a4..00000000000 --- a/externals/g3dlite/stringutils.cpp +++ /dev/null @@ -1,275 +0,0 @@ -/** - @file stringutils.cpp - - @maintainer Morgan McGuire, http://graphics.cs.williams.edu - - @created 2000-09-09 - @edited 2008-01-10 -*/ - -#include "G3D/platform.h" -#include "G3D/stringutils.h" -#include "G3D/BinaryInput.h" -#include - -namespace G3D { - -#ifdef _MSC_VER - // disable: "C++ exception handler used" -# pragma warning (push) -# pragma warning (disable : 4530) -#endif -#ifdef G3D_WIN32 - const char* NEWLINE = "\r\n"; -#else - const char* NEWLINE = "\n"; - static bool iswspace(int ch) { return (ch==' ' || ch=='\t' || ch=='\n' || ch=='\r'); } -#endif - -void parseCommaSeparated(const std::string s, Array& array, bool stripQuotes) { - array.fastClear(); - if (s == "") { - return; - } - - size_t begin = 0; - const char delimiter = ','; - const char quote = '\"'; - do { - size_t end = begin; - // Find the next comma, or the end of the string - bool inQuotes = false; - while ((end < s.length()) && (inQuotes || (s[end] != delimiter))) { - if (s[end] == quote) { - if ((end < s.length() - 2) && (s[end + 1] == quote) && (s[end + 2]) == quote) { - // Skip over the superquote - end += 2; - } - inQuotes = ! inQuotes; - } - ++end; - } - array.append(s.substr(begin, end - begin)); - begin = end + 1; - } while (begin < s.length()); - - if (stripQuotes) { - for (int i = 0; i < array.length(); ++i) { - std::string& t = array[i]; - int L = t.length(); - if ((L > 1) && (t[0] == quote) && (t[L - 1] == quote)) { - if ((L > 6) && (t[1] == quote) && (t[2] == quote) && (t[L - 3] == quote) && (t[L - 2] == quote)) { - // Triple-quote - t = t.substr(3, L - 6); - } else { - // Double-quote - t = t.substr(1, L - 2); - } - } - } - } -} - -bool beginsWith( - const std::string& test, - const std::string& pattern) { - - if (test.size() >= pattern.size()) { - for (int i = 0; i < (int)pattern.size(); ++i) { - if (pattern[i] != test[i]) { - return false; - } - } - return true; - } else { - return false; - } -} - - -bool endsWith( - const std::string& test, - const std::string& pattern) { - - if (test.size() >= pattern.size()) { - int te = test.size() - 1; - int pe = pattern.size() - 1; - for (int i = pattern.size() - 1; i >= 0; --i) { - if (pattern[pe - i] != test[te - i]) { - return false; - } - } - return true; - } else { - return false; - } -} - - -std::string wordWrap( - const std::string& input, - int numCols) { - - std::string output; - size_t c = 0; - int len; - - // Don't make lines less than this length - int minLength = numCols / 4; - size_t inLen = input.size(); - - bool first = true; - while (c < inLen) { - if (first) { - first = false; - } else { - output += NEWLINE; - } - - if ((int)inLen - (int)c - 1 < numCols) { - // The end - output += input.substr(c, inLen - c); - break; - } - - len = numCols; - - // Look at character c + numCols, see if it is a space. - while ((len > minLength) && - (input[c + len] != ' ')) { - len--; - } - - if (len == minLength) { - // Just crop - len = numCols; - - } - - output += input.substr(c, len); - c += len; - if (c < input.size()) { - // Collapse multiple spaces. - while ((input[c] == ' ') && (c < input.size())) { - c++; - } - } - } - - return output; -} - - -int stringCompare( - const std::string& s1, - const std::string& s2) { - - return stringPtrCompare(&s1, &s2); -} - - -int stringPtrCompare( - const std::string* s1, - const std::string* s2) { - - return s1->compare(*s2); -} - - -std::string toUpper(const std::string& x) { - std::string result = x; - std::transform(result.begin(), result.end(), result.begin(), toupper); - return result; -} - - -std::string toLower(const std::string& x) { - std::string result = x; - std::transform(result.begin(), result.end(), result.begin(), tolower); - return result; -} - - -Array stringSplit( - const std::string& x, - char splitChar) { - - Array out; - - // Pointers to the beginning and end of the substring - const char* start = x.c_str(); - const char* stop = start; - - while ((stop = strchr(start, splitChar))) { - out.append(std::string(start, stop - start)); - start = stop + 1; - } - - // Append the last one - out.append(std::string(start)); - - return out; -} - - -std::string stringJoin( - const Array& a, - char joinChar) { - - std::string out; - - for (int i = 0; i < (int)a.size() - 1; ++i) { - out += a[i] + joinChar; - } - - if (a.size() > 0) { - return out + a.last(); - } else { - return out; - } -} - - -std::string stringJoin( - const Array& a, - const std::string& joinStr) { - - std::string out; - - for (int i = 0; i < (int)a.size() - 1; ++i) { - out += a[i] + joinStr; - } - - if (a.size() > 0) { - return out + a.last(); - } else { - return out; - } -} - - -std::string trimWhitespace( - const std::string& s) { - - size_t left = 0; - - // Trim from left - while ((left < s.length()) && iswspace(s[left])) { - ++left; - } - - int right = s.length() - 1; - // Trim from right - while ((right > (int)left) && iswspace(s[right])) { - --right; - } - - return s.substr(left, right - left + 1); -} - -}; // namespace - -#undef NEWLINE -#ifdef _MSC_VER -# pragma warning (pop) -#endif diff --git a/externals/gsoap/CMakeLists.txt b/externals/gsoap/CMakeLists.txt deleted file mode 100644 index 915eeed9b21..00000000000 --- a/externals/gsoap/CMakeLists.txt +++ /dev/null @@ -1,11 +0,0 @@ -file(GLOB sources *.cpp *.h) - -set(gsoap_STAT_SRCS - ${sources} -) - -include_directories( - ${CMAKE_CURRENT_SOURCE_DIR} -) - -add_library(gsoap STATIC ${gsoap_STAT_SRCS}) diff --git a/externals/gsoap/soapC.cpp b/externals/gsoap/soapC.cpp deleted file mode 100644 index 7b964aff6a9..00000000000 --- a/externals/gsoap/soapC.cpp +++ /dev/null @@ -1,1645 +0,0 @@ -/* soapC.cpp - Generated by gSOAP 2.7.10 from stub.h - Copyright(C) 2000-2008, Robert van Engelen, Genivia Inc. All Rights Reserved. - This part of the software is released under one of the following licenses: - GPL, the gSOAP public license, or Genivia's license for commercial use. -*/ - -#include "soapH.h" - -SOAP_SOURCE_STAMP("@(#) soapC.cpp ver 2.7.10 2010-02-18 18:41:56 GMT") - - -#ifndef WITH_NOGLOBAL - -SOAP_FMAC3 void SOAP_FMAC4 soap_serializeheader(struct soap *soap) -{ - if (soap->header) - soap_serialize_SOAP_ENV__Header(soap, soap->header); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_putheader(struct soap *soap) -{ - if (soap->header) - { soap->part = SOAP_IN_HEADER; - if (soap_out_SOAP_ENV__Header(soap, "SOAP-ENV:Header", 0, soap->header, NULL)) - return soap->error; - soap->part = SOAP_END_HEADER; - } - return SOAP_OK; -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_getheader(struct soap *soap) -{ - soap->part = SOAP_IN_HEADER; - soap->header = soap_in_SOAP_ENV__Header(soap, "SOAP-ENV:Header", NULL, NULL); - soap->part = SOAP_END_HEADER; - return soap->header == NULL; -} - -SOAP_FMAC3 void SOAP_FMAC4 soap_header(struct soap *soap) -{ - if (!soap->header) - { soap->header = soap_new_SOAP_ENV__Header(soap, -1); - soap_default_SOAP_ENV__Header(soap, soap->header); - } -} - -SOAP_FMAC3 void SOAP_FMAC4 soap_fault(struct soap *soap) -{ - if (!soap->fault) - { soap->fault = soap_new_SOAP_ENV__Fault(soap, -1); - soap_default_SOAP_ENV__Fault(soap, soap->fault); - } - if (soap->version == 2 && !soap->fault->SOAP_ENV__Code) - { soap->fault->SOAP_ENV__Code = soap_new_SOAP_ENV__Code(soap, -1); - soap_default_SOAP_ENV__Code(soap, soap->fault->SOAP_ENV__Code); - } - if (soap->version == 2 && !soap->fault->SOAP_ENV__Reason) - { soap->fault->SOAP_ENV__Reason = soap_new_SOAP_ENV__Reason(soap, -1); - soap_default_SOAP_ENV__Reason(soap, soap->fault->SOAP_ENV__Reason); - } -} - -SOAP_FMAC3 void SOAP_FMAC4 soap_serializefault(struct soap *soap) -{ - soap_fault(soap); - if (soap->fault) - soap_serialize_SOAP_ENV__Fault(soap, soap->fault); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_putfault(struct soap *soap) -{ - if (soap->fault) - return soap_put_SOAP_ENV__Fault(soap, soap->fault, "SOAP-ENV:Fault", NULL); - return SOAP_OK; -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_getfault(struct soap *soap) -{ - return (soap->fault = soap_get_SOAP_ENV__Fault(soap, NULL, "SOAP-ENV:Fault", NULL)) == NULL; -} - -SOAP_FMAC3 const char ** SOAP_FMAC4 soap_faultcode(struct soap *soap) -{ - soap_fault(soap); - if (soap->version == 2) - return (const char**)&soap->fault->SOAP_ENV__Code->SOAP_ENV__Value; - return (const char**)&soap->fault->faultcode; -} - -SOAP_FMAC3 const char ** SOAP_FMAC4 soap_faultsubcode(struct soap *soap) -{ - soap_fault(soap); - if (soap->version == 2) - { if (!soap->fault->SOAP_ENV__Code->SOAP_ENV__Subcode) - { soap->fault->SOAP_ENV__Code->SOAP_ENV__Subcode = soap_new_SOAP_ENV__Code(soap, -1); - soap_default_SOAP_ENV__Code(soap, soap->fault->SOAP_ENV__Code->SOAP_ENV__Subcode); - } - return (const char**)&soap->fault->SOAP_ENV__Code->SOAP_ENV__Subcode->SOAP_ENV__Value; - } - return (const char**)&soap->fault->faultcode; -} - -SOAP_FMAC3 const char ** SOAP_FMAC4 soap_faultstring(struct soap *soap) -{ - soap_fault(soap); - if (soap->version == 2) - return (const char**)&soap->fault->SOAP_ENV__Reason->SOAP_ENV__Text; - return (const char**)&soap->fault->faultstring; -} - -SOAP_FMAC3 const char ** SOAP_FMAC4 soap_faultdetail(struct soap *soap) -{ - soap_fault(soap); - if (soap->version == 1) - { if (!soap->fault->detail) - { soap->fault->detail = (struct SOAP_ENV__Detail*)soap_malloc(soap, sizeof(struct SOAP_ENV__Detail)); - soap_default_SOAP_ENV__Detail(soap, soap->fault->detail); - } - return (const char**)&soap->fault->detail->__any; - } - if (!soap->fault->SOAP_ENV__Detail) - { soap->fault->SOAP_ENV__Detail = soap_new_SOAP_ENV__Detail(soap, -1); - soap_default_SOAP_ENV__Detail(soap, soap->fault->SOAP_ENV__Detail); - } - return (const char**)&soap->fault->SOAP_ENV__Detail->__any; -} - -#endif - -#ifndef WITH_NOIDREF -SOAP_FMAC3 int SOAP_FMAC4 soap_getindependent(struct soap *soap) -{ - int t; - for (;;) - if (!soap_getelement(soap, &t)) - if (soap->error || soap_ignore_element(soap)) - break; - if (soap->error == SOAP_NO_TAG || soap->error == SOAP_EOF) - soap->error = SOAP_OK; - return soap->error; -} -#endif - -#ifndef WITH_NOIDREF - -#ifdef __cplusplus -extern "C" { -#endif -SOAP_FMAC3 void * SOAP_FMAC4 soap_getelement(struct soap *soap, int *type) -{ - if (soap_peek_element(soap)) - return NULL; - if (!*soap->id || !(*type = soap_lookup_type(soap, soap->id))) - *type = soap_lookup_type(soap, soap->href); - switch (*type) - { - case SOAP_TYPE_byte: - return soap_in_byte(soap, NULL, NULL, "xsd:byte"); - case SOAP_TYPE_int: - return soap_in_int(soap, NULL, NULL, "xsd:int"); - case SOAP_TYPE_ns1__executeCommand: - return soap_in_ns1__executeCommand(soap, NULL, NULL, "ns1:executeCommand"); - case SOAP_TYPE_ns1__executeCommandResponse: - return soap_in_ns1__executeCommandResponse(soap, NULL, NULL, "ns1:executeCommandResponse"); - case SOAP_TYPE_PointerTostring: - return soap_in_PointerTostring(soap, NULL, NULL, "xsd:string"); - case SOAP_TYPE_string: - { char **s; - s = soap_in_string(soap, NULL, NULL, "xsd:string"); - return s ? *s : NULL; - } - default: - { const char *t = soap->type; - if (!*t) - t = soap->tag; - if (!soap_match_tag(soap, t, "xsd:byte")) - { *type = SOAP_TYPE_byte; - return soap_in_byte(soap, NULL, NULL, NULL); - } - if (!soap_match_tag(soap, t, "xsd:int")) - { *type = SOAP_TYPE_int; - return soap_in_int(soap, NULL, NULL, NULL); - } - if (!soap_match_tag(soap, t, "ns1:executeCommand")) - { *type = SOAP_TYPE_ns1__executeCommand; - return soap_in_ns1__executeCommand(soap, NULL, NULL, NULL); - } - if (!soap_match_tag(soap, t, "ns1:executeCommandResponse")) - { *type = SOAP_TYPE_ns1__executeCommandResponse; - return soap_in_ns1__executeCommandResponse(soap, NULL, NULL, NULL); - } - if (!soap_match_tag(soap, t, "xsd:string")) - { char **s; - *type = SOAP_TYPE_string; - s = soap_in_string(soap, NULL, NULL, NULL); - return s ? *s : NULL; - } - t = soap->tag; - if (!soap_match_tag(soap, t, "xsd:QName")) - { char **s; - *type = SOAP_TYPE__QName; - s = soap_in__QName(soap, NULL, NULL, NULL); - return s ? *s : NULL; - } - } - } - soap->error = SOAP_TAG_MISMATCH; - return NULL; -} - -#ifdef __cplusplus -} -#endif -#endif - -SOAP_FMAC3 int SOAP_FMAC4 soap_ignore_element(struct soap *soap) -{ - if (!soap_peek_element(soap)) - { int t; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unexpected element '%s' in input (level=%u, %d)\n", soap->tag, soap->level, soap->body)); - if (soap->mustUnderstand && !soap->other) - return soap->error = SOAP_MUSTUNDERSTAND; - if (((soap->mode & SOAP_XML_STRICT) && soap->part != SOAP_IN_HEADER) || !soap_match_tag(soap, soap->tag, "SOAP-ENV:")) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "REJECTING element '%s'\n", soap->tag)); - return soap->error = SOAP_TAG_MISMATCH; - } - if (!*soap->id || !soap_getelement(soap, &t)) - { soap->peeked = 0; - if (soap->fignore) - soap->error = soap->fignore(soap, soap->tag); - else - soap->error = SOAP_OK; - DBGLOG(TEST, if (!soap->error) SOAP_MESSAGE(fdebug, "IGNORING element '%s'\n", soap->tag)); - if (!soap->error && soap->body) - { soap->level++; - while (!soap_ignore_element(soap)) - ; - if (soap->error == SOAP_NO_TAG) - soap->error = soap_element_end_in(soap, NULL); - } - } - } - return soap->error; -} - -#ifndef WITH_NOIDREF -SOAP_FMAC3 int SOAP_FMAC4 soap_putindependent(struct soap *soap) -{ - int i; - struct soap_plist *pp; - if (soap->version == 1 && soap->encodingStyle && !(soap->mode & (SOAP_XML_TREE | SOAP_XML_GRAPH))) - for (i = 0; i < SOAP_PTRHASH; i++) - for (pp = soap->pht[i]; pp; pp = pp->next) - if (pp->mark1 == 2 || pp->mark2 == 2) - if (soap_putelement(soap, pp->ptr, "id", pp->id, pp->type)) - return soap->error; - return SOAP_OK; -} -#endif - -#ifndef WITH_NOIDREF - -#ifdef __cplusplus -extern "C" { -#endif -SOAP_FMAC3 int SOAP_FMAC4 soap_putelement(struct soap *soap, const void *ptr, const char *tag, int id, int type) -{ - switch (type) - { - case SOAP_TYPE_byte: - return soap_out_byte(soap, tag, id, (const char *)ptr, "xsd:byte"); - case SOAP_TYPE_int: - return soap_out_int(soap, tag, id, (const int *)ptr, "xsd:int"); - case SOAP_TYPE_ns1__executeCommand: - return soap_out_ns1__executeCommand(soap, tag, id, (const struct ns1__executeCommand *)ptr, "ns1:executeCommand"); - case SOAP_TYPE_ns1__executeCommandResponse: - return soap_out_ns1__executeCommandResponse(soap, tag, id, (const struct ns1__executeCommandResponse *)ptr, "ns1:executeCommandResponse"); - case SOAP_TYPE_PointerTostring: - return soap_out_PointerTostring(soap, tag, id, (char **const*)ptr, "xsd:string"); - case SOAP_TYPE__QName: - return soap_out_string(soap, "xsd:QName", id, (char*const*)&ptr, NULL); - case SOAP_TYPE_string: - return soap_out_string(soap, tag, id, (char*const*)&ptr, "xsd:string"); - } - return SOAP_OK; -} - -#ifdef __cplusplus -} -#endif -#endif - -#ifndef WITH_NOIDREF - -#ifdef __cplusplus -extern "C" { -#endif -SOAP_FMAC3 void SOAP_FMAC4 soap_markelement(struct soap *soap, const void *ptr, int type) -{ - (void)soap; (void)ptr; (void)type; /* appease -Wall -Werror */ - switch (type) - { - case SOAP_TYPE_ns1__executeCommand: - soap_serialize_ns1__executeCommand(soap, (const struct ns1__executeCommand *)ptr); - break; - case SOAP_TYPE_ns1__executeCommandResponse: - soap_serialize_ns1__executeCommandResponse(soap, (const struct ns1__executeCommandResponse *)ptr); - break; - case SOAP_TYPE_PointerTostring: - soap_serialize_PointerTostring(soap, (char **const*)ptr); - break; - case SOAP_TYPE__QName: - soap_serialize_string(soap, (char*const*)&ptr); - break; - case SOAP_TYPE_string: - soap_serialize_string(soap, (char*const*)&ptr); - break; - } -} - -#ifdef __cplusplus -} -#endif -#endif - -SOAP_FMAC3 void * SOAP_FMAC4 soap_instantiate(struct soap *soap, int t, const char *type, const char *arrayType, size_t *n) -{ - switch (t) - { - case SOAP_TYPE_ns1__executeCommandResponse: - return (void*)soap_instantiate_ns1__executeCommandResponse(soap, -1, type, arrayType, n); - case SOAP_TYPE_ns1__executeCommand: - return (void*)soap_instantiate_ns1__executeCommand(soap, -1, type, arrayType, n); -#ifndef WITH_NOGLOBAL - case SOAP_TYPE_SOAP_ENV__Header: - return (void*)soap_instantiate_SOAP_ENV__Header(soap, -1, type, arrayType, n); -#endif -#ifndef WITH_NOGLOBAL - case SOAP_TYPE_SOAP_ENV__Code: - return (void*)soap_instantiate_SOAP_ENV__Code(soap, -1, type, arrayType, n); -#endif -#ifndef WITH_NOGLOBAL - case SOAP_TYPE_SOAP_ENV__Detail: - return (void*)soap_instantiate_SOAP_ENV__Detail(soap, -1, type, arrayType, n); -#endif -#ifndef WITH_NOGLOBAL - case SOAP_TYPE_SOAP_ENV__Reason: - return (void*)soap_instantiate_SOAP_ENV__Reason(soap, -1, type, arrayType, n); -#endif -#ifndef WITH_NOGLOBAL - case SOAP_TYPE_SOAP_ENV__Fault: - return (void*)soap_instantiate_SOAP_ENV__Fault(soap, -1, type, arrayType, n); -#endif - } - return NULL; -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_fdelete(struct soap_clist *p) -{ switch (p->type) - { - case SOAP_TYPE_ns1__executeCommandResponse: - if (p->size < 0) - delete (struct ns1__executeCommandResponse*)p->ptr; - else - delete[] (struct ns1__executeCommandResponse*)p->ptr; - break; - case SOAP_TYPE_ns1__executeCommand: - if (p->size < 0) - delete (struct ns1__executeCommand*)p->ptr; - else - delete[] (struct ns1__executeCommand*)p->ptr; - break; - case SOAP_TYPE_SOAP_ENV__Header: - if (p->size < 0) - delete (struct SOAP_ENV__Header*)p->ptr; - else - delete[] (struct SOAP_ENV__Header*)p->ptr; - break; - case SOAP_TYPE_SOAP_ENV__Code: - if (p->size < 0) - delete (struct SOAP_ENV__Code*)p->ptr; - else - delete[] (struct SOAP_ENV__Code*)p->ptr; - break; - case SOAP_TYPE_SOAP_ENV__Detail: - if (p->size < 0) - delete (struct SOAP_ENV__Detail*)p->ptr; - else - delete[] (struct SOAP_ENV__Detail*)p->ptr; - break; - case SOAP_TYPE_SOAP_ENV__Reason: - if (p->size < 0) - delete (struct SOAP_ENV__Reason*)p->ptr; - else - delete[] (struct SOAP_ENV__Reason*)p->ptr; - break; - case SOAP_TYPE_SOAP_ENV__Fault: - if (p->size < 0) - delete (struct SOAP_ENV__Fault*)p->ptr; - else - delete[] (struct SOAP_ENV__Fault*)p->ptr; - break; - default: return SOAP_ERR; - } - return SOAP_OK; -} - -SOAP_FMAC3 void* SOAP_FMAC4 soap_class_id_enter(struct soap *soap, const char *id, void *p, int t, size_t n, const char *type, const char *arrayType) -{ return soap_id_enter(soap, id, p, t, n, 0, type, arrayType, soap_instantiate); -} - -SOAP_FMAC3 void SOAP_FMAC4 soap_default_byte(struct soap *soap, char *a) -{ (void)soap; /* appease -Wall -Werror */ -#ifdef SOAP_DEFAULT_byte - *a = SOAP_DEFAULT_byte; -#else - *a = (char)0; -#endif -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_put_byte(struct soap *soap, const char *a, const char *tag, const char *type) -{ - register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_byte); - if (soap_out_byte(soap, tag, id, a, type)) - return soap->error; - return soap_putindependent(soap); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_out_byte(struct soap *soap, const char *tag, int id, const char *a, const char *type) -{ - return soap_outbyte(soap, tag, id, a, type, SOAP_TYPE_byte); -} - -SOAP_FMAC3 char * SOAP_FMAC4 soap_get_byte(struct soap *soap, char *p, const char *tag, const char *type) -{ - if ((p = soap_in_byte(soap, tag, p, type))) - if (soap_getindependent(soap)) - return NULL; - return p; -} - -SOAP_FMAC3 char * SOAP_FMAC4 soap_in_byte(struct soap *soap, const char *tag, char *a, const char *type) -{ - return soap_inbyte(soap, tag, a, type, SOAP_TYPE_byte); -} - -SOAP_FMAC3 void SOAP_FMAC4 soap_default_int(struct soap *soap, int *a) -{ (void)soap; /* appease -Wall -Werror */ -#ifdef SOAP_DEFAULT_int - *a = SOAP_DEFAULT_int; -#else - *a = (int)0; -#endif -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_put_int(struct soap *soap, const int *a, const char *tag, const char *type) -{ - register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_int); - if (soap_out_int(soap, tag, id, a, type)) - return soap->error; - return soap_putindependent(soap); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_out_int(struct soap *soap, const char *tag, int id, const int *a, const char *type) -{ - return soap_outint(soap, tag, id, a, type, SOAP_TYPE_int); -} - -SOAP_FMAC3 int * SOAP_FMAC4 soap_get_int(struct soap *soap, int *p, const char *tag, const char *type) -{ - if ((p = soap_in_int(soap, tag, p, type))) - if (soap_getindependent(soap)) - return NULL; - return p; -} - -SOAP_FMAC3 int * SOAP_FMAC4 soap_in_int(struct soap *soap, const char *tag, int *a, const char *type) -{ - return soap_inint(soap, tag, a, type, SOAP_TYPE_int); -} - -#ifndef WITH_NOGLOBAL - -SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Fault(struct soap *soap, struct SOAP_ENV__Fault *a) -{ - (void)soap; (void)a; /* appease -Wall -Werror */ - soap_default__QName(soap, &a->faultcode); - soap_default_string(soap, &a->faultstring); - soap_default_string(soap, &a->faultactor); - a->detail = NULL; - a->SOAP_ENV__Code = NULL; - a->SOAP_ENV__Reason = NULL; - soap_default_string(soap, &a->SOAP_ENV__Node); - soap_default_string(soap, &a->SOAP_ENV__Role); - a->SOAP_ENV__Detail = NULL; -} - -SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Fault(struct soap *soap, const struct SOAP_ENV__Fault *a) -{ - (void)soap; (void)a; /* appease -Wall -Werror */ - soap_serialize__QName(soap, &a->faultcode); - soap_serialize_string(soap, &a->faultstring); - soap_serialize_string(soap, &a->faultactor); - soap_serialize_PointerToSOAP_ENV__Detail(soap, &a->detail); - soap_serialize_PointerToSOAP_ENV__Code(soap, &a->SOAP_ENV__Code); - soap_serialize_PointerToSOAP_ENV__Reason(soap, &a->SOAP_ENV__Reason); - soap_serialize_string(soap, &a->SOAP_ENV__Node); - soap_serialize_string(soap, &a->SOAP_ENV__Role); - soap_serialize_PointerToSOAP_ENV__Detail(soap, &a->SOAP_ENV__Detail); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Fault(struct soap *soap, const struct SOAP_ENV__Fault *a, const char *tag, const char *type) -{ - register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_SOAP_ENV__Fault); - if (soap_out_SOAP_ENV__Fault(soap, tag, id, a, type)) - return soap->error; - return soap_putindependent(soap); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Fault(struct soap *soap, const char *tag, int id, const struct SOAP_ENV__Fault *a, const char *type) -{ - const char *soap_tmp_faultcode = soap_QName2s(soap, a->faultcode); - if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_SOAP_ENV__Fault), type)) - return soap->error; - if (soap_out__QName(soap, "faultcode", -1, (char*const*)&soap_tmp_faultcode, "")) - return soap->error; - if (soap_out_string(soap, "faultstring", -1, &a->faultstring, "")) - return soap->error; - if (soap_out_string(soap, "faultactor", -1, &a->faultactor, "")) - return soap->error; - if (soap_out_PointerToSOAP_ENV__Detail(soap, "detail", -1, &a->detail, "")) - return soap->error; - if (soap_out_PointerToSOAP_ENV__Code(soap, "SOAP-ENV:Code", -1, &a->SOAP_ENV__Code, "")) - return soap->error; - if (soap_out_PointerToSOAP_ENV__Reason(soap, "SOAP-ENV:Reason", -1, &a->SOAP_ENV__Reason, "")) - return soap->error; - if (soap_out_string(soap, "SOAP-ENV:Node", -1, &a->SOAP_ENV__Node, "")) - return soap->error; - if (soap_out_string(soap, "SOAP-ENV:Role", -1, &a->SOAP_ENV__Role, "")) - return soap->error; - if (soap_out_PointerToSOAP_ENV__Detail(soap, "SOAP-ENV:Detail", -1, &a->SOAP_ENV__Detail, "")) - return soap->error; - return soap_element_end_out(soap, tag); -} - -SOAP_FMAC3 struct SOAP_ENV__Fault * SOAP_FMAC4 soap_get_SOAP_ENV__Fault(struct soap *soap, struct SOAP_ENV__Fault *p, const char *tag, const char *type) -{ - if ((p = soap_in_SOAP_ENV__Fault(soap, tag, p, type))) - if (soap_getindependent(soap)) - return NULL; - return p; -} - -SOAP_FMAC3 struct SOAP_ENV__Fault * SOAP_FMAC4 soap_in_SOAP_ENV__Fault(struct soap *soap, const char *tag, struct SOAP_ENV__Fault *a, const char *type) -{ - short soap_flag_faultcode = 1, soap_flag_faultstring = 1, soap_flag_faultactor = 1, soap_flag_detail = 1, soap_flag_SOAP_ENV__Code = 1, soap_flag_SOAP_ENV__Reason = 1, soap_flag_SOAP_ENV__Node = 1, soap_flag_SOAP_ENV__Role = 1, soap_flag_SOAP_ENV__Detail = 1; - if (soap_element_begin_in(soap, tag, 0, type)) - return NULL; - a = (struct SOAP_ENV__Fault *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_SOAP_ENV__Fault, sizeof(struct SOAP_ENV__Fault), 0, NULL, NULL, NULL); - if (!a) - return NULL; - soap_default_SOAP_ENV__Fault(soap, a); - if (soap->body && !*soap->href) - { - for (;;) - { soap->error = SOAP_TAG_MISMATCH; - if (soap_flag_faultcode && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) - if (soap_in__QName(soap, "faultcode", &a->faultcode, "")) - { soap_flag_faultcode--; - continue; - } - if (soap_flag_faultstring && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) - if (soap_in_string(soap, "faultstring", &a->faultstring, "xsd:string")) - { soap_flag_faultstring--; - continue; - } - if (soap_flag_faultactor && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) - if (soap_in_string(soap, "faultactor", &a->faultactor, "xsd:string")) - { soap_flag_faultactor--; - continue; - } - if (soap_flag_detail && soap->error == SOAP_TAG_MISMATCH) - if (soap_in_PointerToSOAP_ENV__Detail(soap, "detail", &a->detail, "")) - { soap_flag_detail--; - continue; - } - if (soap_flag_SOAP_ENV__Code && soap->error == SOAP_TAG_MISMATCH) - if (soap_in_PointerToSOAP_ENV__Code(soap, "SOAP-ENV:Code", &a->SOAP_ENV__Code, "")) - { soap_flag_SOAP_ENV__Code--; - continue; - } - if (soap_flag_SOAP_ENV__Reason && soap->error == SOAP_TAG_MISMATCH) - if (soap_in_PointerToSOAP_ENV__Reason(soap, "SOAP-ENV:Reason", &a->SOAP_ENV__Reason, "")) - { soap_flag_SOAP_ENV__Reason--; - continue; - } - if (soap_flag_SOAP_ENV__Node && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) - if (soap_in_string(soap, "SOAP-ENV:Node", &a->SOAP_ENV__Node, "xsd:string")) - { soap_flag_SOAP_ENV__Node--; - continue; - } - if (soap_flag_SOAP_ENV__Role && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) - if (soap_in_string(soap, "SOAP-ENV:Role", &a->SOAP_ENV__Role, "xsd:string")) - { soap_flag_SOAP_ENV__Role--; - continue; - } - if (soap_flag_SOAP_ENV__Detail && soap->error == SOAP_TAG_MISMATCH) - if (soap_in_PointerToSOAP_ENV__Detail(soap, "SOAP-ENV:Detail", &a->SOAP_ENV__Detail, "")) - { soap_flag_SOAP_ENV__Detail--; - continue; - } - if (soap->error == SOAP_TAG_MISMATCH) - soap->error = soap_ignore_element(soap); - if (soap->error == SOAP_NO_TAG) - break; - if (soap->error) - return NULL; - } - if (soap_element_end_in(soap, tag)) - return NULL; - } - else - { a = (struct SOAP_ENV__Fault *)soap_id_forward(soap, soap->href, (void*)a, 0, SOAP_TYPE_SOAP_ENV__Fault, 0, sizeof(struct SOAP_ENV__Fault), 0, NULL); - if (soap->body && soap_element_end_in(soap, tag)) - return NULL; - } - return a; -} - -SOAP_FMAC5 struct SOAP_ENV__Fault * SOAP_FMAC6 soap_new_SOAP_ENV__Fault(struct soap *soap, int n) -{ return soap_instantiate_SOAP_ENV__Fault(soap, n, NULL, NULL, NULL); -} - -SOAP_FMAC5 void SOAP_FMAC6 soap_delete_SOAP_ENV__Fault(struct soap *soap, struct SOAP_ENV__Fault *p) -{ soap_delete(soap, p); -} - -SOAP_FMAC3 struct SOAP_ENV__Fault * SOAP_FMAC4 soap_instantiate_SOAP_ENV__Fault(struct soap *soap, int n, const char *type, const char *arrayType, size_t *size) -{ - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "soap_instantiate_SOAP_ENV__Fault(%d, %s, %s)\n", n, type?type:"", arrayType?arrayType:"")); - struct soap_clist *cp = soap_link(soap, NULL, SOAP_TYPE_SOAP_ENV__Fault, n, soap_fdelete); - if (!cp) - return NULL; - if (n < 0) - { cp->ptr = (void*)new struct SOAP_ENV__Fault; - if (size) - *size = sizeof(struct SOAP_ENV__Fault); - } - else - { cp->ptr = (void*)new struct SOAP_ENV__Fault[n]; - if (!cp->ptr) - { soap->error = SOAP_EOM; - return NULL; - } - if (size) - *size = n * sizeof(struct SOAP_ENV__Fault); - } - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Instantiated location=%p\n", cp->ptr)); - return (struct SOAP_ENV__Fault*)cp->ptr; -} -SOAP_FMAC3 void SOAP_FMAC4 soap_copy_SOAP_ENV__Fault(struct soap *soap, int st, int tt, void *p, size_t len, const void *q, size_t n) -{ - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copying struct SOAP_ENV__Fault %p -> %p\n", q, p)); - *(struct SOAP_ENV__Fault*)p = *(struct SOAP_ENV__Fault*)q; -} - -#endif - -#ifndef WITH_NOGLOBAL - -SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Reason(struct soap *soap, struct SOAP_ENV__Reason *a) -{ - (void)soap; (void)a; /* appease -Wall -Werror */ - soap_default_string(soap, &a->SOAP_ENV__Text); -} - -SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Reason(struct soap *soap, const struct SOAP_ENV__Reason *a) -{ - (void)soap; (void)a; /* appease -Wall -Werror */ - soap_serialize_string(soap, &a->SOAP_ENV__Text); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Reason(struct soap *soap, const struct SOAP_ENV__Reason *a, const char *tag, const char *type) -{ - register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_SOAP_ENV__Reason); - if (soap_out_SOAP_ENV__Reason(soap, tag, id, a, type)) - return soap->error; - return soap_putindependent(soap); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Reason(struct soap *soap, const char *tag, int id, const struct SOAP_ENV__Reason *a, const char *type) -{ - if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_SOAP_ENV__Reason), type)) - return soap->error; - if (soap_out_string(soap, "SOAP-ENV:Text", -1, &a->SOAP_ENV__Text, "")) - return soap->error; - return soap_element_end_out(soap, tag); -} - -SOAP_FMAC3 struct SOAP_ENV__Reason * SOAP_FMAC4 soap_get_SOAP_ENV__Reason(struct soap *soap, struct SOAP_ENV__Reason *p, const char *tag, const char *type) -{ - if ((p = soap_in_SOAP_ENV__Reason(soap, tag, p, type))) - if (soap_getindependent(soap)) - return NULL; - return p; -} - -SOAP_FMAC3 struct SOAP_ENV__Reason * SOAP_FMAC4 soap_in_SOAP_ENV__Reason(struct soap *soap, const char *tag, struct SOAP_ENV__Reason *a, const char *type) -{ - short soap_flag_SOAP_ENV__Text = 1; - if (soap_element_begin_in(soap, tag, 0, type)) - return NULL; - a = (struct SOAP_ENV__Reason *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_SOAP_ENV__Reason, sizeof(struct SOAP_ENV__Reason), 0, NULL, NULL, NULL); - if (!a) - return NULL; - soap_default_SOAP_ENV__Reason(soap, a); - if (soap->body && !*soap->href) - { - for (;;) - { soap->error = SOAP_TAG_MISMATCH; - if (soap_flag_SOAP_ENV__Text && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) - if (soap_in_string(soap, "SOAP-ENV:Text", &a->SOAP_ENV__Text, "xsd:string")) - { soap_flag_SOAP_ENV__Text--; - continue; - } - if (soap->error == SOAP_TAG_MISMATCH) - soap->error = soap_ignore_element(soap); - if (soap->error == SOAP_NO_TAG) - break; - if (soap->error) - return NULL; - } - if (soap_element_end_in(soap, tag)) - return NULL; - } - else - { a = (struct SOAP_ENV__Reason *)soap_id_forward(soap, soap->href, (void*)a, 0, SOAP_TYPE_SOAP_ENV__Reason, 0, sizeof(struct SOAP_ENV__Reason), 0, NULL); - if (soap->body && soap_element_end_in(soap, tag)) - return NULL; - } - return a; -} - -SOAP_FMAC5 struct SOAP_ENV__Reason * SOAP_FMAC6 soap_new_SOAP_ENV__Reason(struct soap *soap, int n) -{ return soap_instantiate_SOAP_ENV__Reason(soap, n, NULL, NULL, NULL); -} - -SOAP_FMAC5 void SOAP_FMAC6 soap_delete_SOAP_ENV__Reason(struct soap *soap, struct SOAP_ENV__Reason *p) -{ soap_delete(soap, p); -} - -SOAP_FMAC3 struct SOAP_ENV__Reason * SOAP_FMAC4 soap_instantiate_SOAP_ENV__Reason(struct soap *soap, int n, const char *type, const char *arrayType, size_t *size) -{ - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "soap_instantiate_SOAP_ENV__Reason(%d, %s, %s)\n", n, type?type:"", arrayType?arrayType:"")); - struct soap_clist *cp = soap_link(soap, NULL, SOAP_TYPE_SOAP_ENV__Reason, n, soap_fdelete); - if (!cp) - return NULL; - if (n < 0) - { cp->ptr = (void*)new struct SOAP_ENV__Reason; - if (size) - *size = sizeof(struct SOAP_ENV__Reason); - } - else - { cp->ptr = (void*)new struct SOAP_ENV__Reason[n]; - if (!cp->ptr) - { soap->error = SOAP_EOM; - return NULL; - } - if (size) - *size = n * sizeof(struct SOAP_ENV__Reason); - } - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Instantiated location=%p\n", cp->ptr)); - return (struct SOAP_ENV__Reason*)cp->ptr; -} -SOAP_FMAC3 void SOAP_FMAC4 soap_copy_SOAP_ENV__Reason(struct soap *soap, int st, int tt, void *p, size_t len, const void *q, size_t n) -{ - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copying struct SOAP_ENV__Reason %p -> %p\n", q, p)); - *(struct SOAP_ENV__Reason*)p = *(struct SOAP_ENV__Reason*)q; -} - -#endif - -#ifndef WITH_NOGLOBAL - -SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Detail(struct soap *soap, struct SOAP_ENV__Detail *a) -{ - (void)soap; (void)a; /* appease -Wall -Werror */ - a->__type = 0; - a->fault = NULL; - a->__any = NULL; -} - -SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Detail(struct soap *soap, const struct SOAP_ENV__Detail *a) -{ - (void)soap; (void)a; /* appease -Wall -Werror */ - soap_markelement(soap, a->fault, a->__type); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Detail(struct soap *soap, const struct SOAP_ENV__Detail *a, const char *tag, const char *type) -{ - register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_SOAP_ENV__Detail); - if (soap_out_SOAP_ENV__Detail(soap, tag, id, a, type)) - return soap->error; - return soap_putindependent(soap); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Detail(struct soap *soap, const char *tag, int id, const struct SOAP_ENV__Detail *a, const char *type) -{ - if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_SOAP_ENV__Detail), type)) - return soap->error; - if (soap_putelement(soap, a->fault, "fault", -1, a->__type)) - return soap->error; - soap_outliteral(soap, "-any", &a->__any, NULL); - return soap_element_end_out(soap, tag); -} - -SOAP_FMAC3 struct SOAP_ENV__Detail * SOAP_FMAC4 soap_get_SOAP_ENV__Detail(struct soap *soap, struct SOAP_ENV__Detail *p, const char *tag, const char *type) -{ - if ((p = soap_in_SOAP_ENV__Detail(soap, tag, p, type))) - if (soap_getindependent(soap)) - return NULL; - return p; -} - -SOAP_FMAC3 struct SOAP_ENV__Detail * SOAP_FMAC4 soap_in_SOAP_ENV__Detail(struct soap *soap, const char *tag, struct SOAP_ENV__Detail *a, const char *type) -{ - short soap_flag_fault = 1, soap_flag___any = 1; - if (soap_element_begin_in(soap, tag, 0, type)) - return NULL; - a = (struct SOAP_ENV__Detail *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_SOAP_ENV__Detail, sizeof(struct SOAP_ENV__Detail), 0, NULL, NULL, NULL); - if (!a) - return NULL; - soap_default_SOAP_ENV__Detail(soap, a); - if (soap->body && !*soap->href) - { - for (;;) - { soap->error = SOAP_TAG_MISMATCH; - if (soap_flag_fault && soap->error == SOAP_TAG_MISMATCH) - if ((a->fault = soap_getelement(soap, &a->__type))) - { soap_flag_fault = 0; - continue; - } - if (soap_flag___any && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) - if (soap_inliteral(soap, "-any", &a->__any)) - { soap_flag___any--; - continue; - } - if (soap->error == SOAP_TAG_MISMATCH) - soap->error = soap_ignore_element(soap); - if (soap->error == SOAP_NO_TAG) - break; - if (soap->error) - return NULL; - } - if (soap_element_end_in(soap, tag)) - return NULL; - } - else - { a = (struct SOAP_ENV__Detail *)soap_id_forward(soap, soap->href, (void*)a, 0, SOAP_TYPE_SOAP_ENV__Detail, 0, sizeof(struct SOAP_ENV__Detail), 0, NULL); - if (soap->body && soap_element_end_in(soap, tag)) - return NULL; - } - return a; -} - -SOAP_FMAC5 struct SOAP_ENV__Detail * SOAP_FMAC6 soap_new_SOAP_ENV__Detail(struct soap *soap, int n) -{ return soap_instantiate_SOAP_ENV__Detail(soap, n, NULL, NULL, NULL); -} - -SOAP_FMAC5 void SOAP_FMAC6 soap_delete_SOAP_ENV__Detail(struct soap *soap, struct SOAP_ENV__Detail *p) -{ soap_delete(soap, p); -} - -SOAP_FMAC3 struct SOAP_ENV__Detail * SOAP_FMAC4 soap_instantiate_SOAP_ENV__Detail(struct soap *soap, int n, const char *type, const char *arrayType, size_t *size) -{ - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "soap_instantiate_SOAP_ENV__Detail(%d, %s, %s)\n", n, type?type:"", arrayType?arrayType:"")); - struct soap_clist *cp = soap_link(soap, NULL, SOAP_TYPE_SOAP_ENV__Detail, n, soap_fdelete); - if (!cp) - return NULL; - if (n < 0) - { cp->ptr = (void*)new struct SOAP_ENV__Detail; - if (size) - *size = sizeof(struct SOAP_ENV__Detail); - } - else - { cp->ptr = (void*)new struct SOAP_ENV__Detail[n]; - if (!cp->ptr) - { soap->error = SOAP_EOM; - return NULL; - } - if (size) - *size = n * sizeof(struct SOAP_ENV__Detail); - } - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Instantiated location=%p\n", cp->ptr)); - return (struct SOAP_ENV__Detail*)cp->ptr; -} -SOAP_FMAC3 void SOAP_FMAC4 soap_copy_SOAP_ENV__Detail(struct soap *soap, int st, int tt, void *p, size_t len, const void *q, size_t n) -{ - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copying struct SOAP_ENV__Detail %p -> %p\n", q, p)); - *(struct SOAP_ENV__Detail*)p = *(struct SOAP_ENV__Detail*)q; -} - -#endif - -#ifndef WITH_NOGLOBAL - -SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Code(struct soap *soap, struct SOAP_ENV__Code *a) -{ - (void)soap; (void)a; /* appease -Wall -Werror */ - soap_default__QName(soap, &a->SOAP_ENV__Value); - a->SOAP_ENV__Subcode = NULL; -} - -SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Code(struct soap *soap, const struct SOAP_ENV__Code *a) -{ - (void)soap; (void)a; /* appease -Wall -Werror */ - soap_serialize__QName(soap, &a->SOAP_ENV__Value); - soap_serialize_PointerToSOAP_ENV__Code(soap, &a->SOAP_ENV__Subcode); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Code(struct soap *soap, const struct SOAP_ENV__Code *a, const char *tag, const char *type) -{ - register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_SOAP_ENV__Code); - if (soap_out_SOAP_ENV__Code(soap, tag, id, a, type)) - return soap->error; - return soap_putindependent(soap); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Code(struct soap *soap, const char *tag, int id, const struct SOAP_ENV__Code *a, const char *type) -{ - const char *soap_tmp_SOAP_ENV__Value = soap_QName2s(soap, a->SOAP_ENV__Value); - if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_SOAP_ENV__Code), type)) - return soap->error; - if (soap_out__QName(soap, "SOAP-ENV:Value", -1, (char*const*)&soap_tmp_SOAP_ENV__Value, "")) - return soap->error; - if (soap_out_PointerToSOAP_ENV__Code(soap, "SOAP-ENV:Subcode", -1, &a->SOAP_ENV__Subcode, "")) - return soap->error; - return soap_element_end_out(soap, tag); -} - -SOAP_FMAC3 struct SOAP_ENV__Code * SOAP_FMAC4 soap_get_SOAP_ENV__Code(struct soap *soap, struct SOAP_ENV__Code *p, const char *tag, const char *type) -{ - if ((p = soap_in_SOAP_ENV__Code(soap, tag, p, type))) - if (soap_getindependent(soap)) - return NULL; - return p; -} - -SOAP_FMAC3 struct SOAP_ENV__Code * SOAP_FMAC4 soap_in_SOAP_ENV__Code(struct soap *soap, const char *tag, struct SOAP_ENV__Code *a, const char *type) -{ - short soap_flag_SOAP_ENV__Value = 1, soap_flag_SOAP_ENV__Subcode = 1; - if (soap_element_begin_in(soap, tag, 0, type)) - return NULL; - a = (struct SOAP_ENV__Code *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_SOAP_ENV__Code, sizeof(struct SOAP_ENV__Code), 0, NULL, NULL, NULL); - if (!a) - return NULL; - soap_default_SOAP_ENV__Code(soap, a); - if (soap->body && !*soap->href) - { - for (;;) - { soap->error = SOAP_TAG_MISMATCH; - if (soap_flag_SOAP_ENV__Value && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) - if (soap_in__QName(soap, "SOAP-ENV:Value", &a->SOAP_ENV__Value, "")) - { soap_flag_SOAP_ENV__Value--; - continue; - } - if (soap_flag_SOAP_ENV__Subcode && soap->error == SOAP_TAG_MISMATCH) - if (soap_in_PointerToSOAP_ENV__Code(soap, "SOAP-ENV:Subcode", &a->SOAP_ENV__Subcode, "")) - { soap_flag_SOAP_ENV__Subcode--; - continue; - } - if (soap->error == SOAP_TAG_MISMATCH) - soap->error = soap_ignore_element(soap); - if (soap->error == SOAP_NO_TAG) - break; - if (soap->error) - return NULL; - } - if (soap_element_end_in(soap, tag)) - return NULL; - } - else - { a = (struct SOAP_ENV__Code *)soap_id_forward(soap, soap->href, (void*)a, 0, SOAP_TYPE_SOAP_ENV__Code, 0, sizeof(struct SOAP_ENV__Code), 0, NULL); - if (soap->body && soap_element_end_in(soap, tag)) - return NULL; - } - return a; -} - -SOAP_FMAC5 struct SOAP_ENV__Code * SOAP_FMAC6 soap_new_SOAP_ENV__Code(struct soap *soap, int n) -{ return soap_instantiate_SOAP_ENV__Code(soap, n, NULL, NULL, NULL); -} - -SOAP_FMAC5 void SOAP_FMAC6 soap_delete_SOAP_ENV__Code(struct soap *soap, struct SOAP_ENV__Code *p) -{ soap_delete(soap, p); -} - -SOAP_FMAC3 struct SOAP_ENV__Code * SOAP_FMAC4 soap_instantiate_SOAP_ENV__Code(struct soap *soap, int n, const char *type, const char *arrayType, size_t *size) -{ - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "soap_instantiate_SOAP_ENV__Code(%d, %s, %s)\n", n, type?type:"", arrayType?arrayType:"")); - struct soap_clist *cp = soap_link(soap, NULL, SOAP_TYPE_SOAP_ENV__Code, n, soap_fdelete); - if (!cp) - return NULL; - if (n < 0) - { cp->ptr = (void*)new struct SOAP_ENV__Code; - if (size) - *size = sizeof(struct SOAP_ENV__Code); - } - else - { cp->ptr = (void*)new struct SOAP_ENV__Code[n]; - if (!cp->ptr) - { soap->error = SOAP_EOM; - return NULL; - } - if (size) - *size = n * sizeof(struct SOAP_ENV__Code); - } - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Instantiated location=%p\n", cp->ptr)); - return (struct SOAP_ENV__Code*)cp->ptr; -} -SOAP_FMAC3 void SOAP_FMAC4 soap_copy_SOAP_ENV__Code(struct soap *soap, int st, int tt, void *p, size_t len, const void *q, size_t n) -{ - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copying struct SOAP_ENV__Code %p -> %p\n", q, p)); - *(struct SOAP_ENV__Code*)p = *(struct SOAP_ENV__Code*)q; -} - -#endif - -#ifndef WITH_NOGLOBAL - -SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Header(struct soap *soap, struct SOAP_ENV__Header *a) -{ - (void)soap; (void)a; /* appease -Wall -Werror */ -} - -SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Header(struct soap *soap, const struct SOAP_ENV__Header *a) -{ - (void)soap; (void)a; /* appease -Wall -Werror */ -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Header(struct soap *soap, const struct SOAP_ENV__Header *a, const char *tag, const char *type) -{ - register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_SOAP_ENV__Header); - if (soap_out_SOAP_ENV__Header(soap, tag, id, a, type)) - return soap->error; - return soap_putindependent(soap); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Header(struct soap *soap, const char *tag, int id, const struct SOAP_ENV__Header *a, const char *type) -{ - if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_SOAP_ENV__Header), type)) - return soap->error; - return soap_element_end_out(soap, tag); -} - -SOAP_FMAC3 struct SOAP_ENV__Header * SOAP_FMAC4 soap_get_SOAP_ENV__Header(struct soap *soap, struct SOAP_ENV__Header *p, const char *tag, const char *type) -{ - if ((p = soap_in_SOAP_ENV__Header(soap, tag, p, type))) - if (soap_getindependent(soap)) - return NULL; - return p; -} - -SOAP_FMAC3 struct SOAP_ENV__Header * SOAP_FMAC4 soap_in_SOAP_ENV__Header(struct soap *soap, const char *tag, struct SOAP_ENV__Header *a, const char *type) -{ - if (soap_element_begin_in(soap, tag, 0, type)) - return NULL; - a = (struct SOAP_ENV__Header *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_SOAP_ENV__Header, sizeof(struct SOAP_ENV__Header), 0, NULL, NULL, NULL); - if (!a) - return NULL; - soap_default_SOAP_ENV__Header(soap, a); - if (soap->body && !*soap->href) - { - for (;;) - { soap->error = SOAP_TAG_MISMATCH; - if (soap->error == SOAP_TAG_MISMATCH) - soap->error = soap_ignore_element(soap); - if (soap->error == SOAP_NO_TAG) - break; - if (soap->error) - return NULL; - } - if (soap_element_end_in(soap, tag)) - return NULL; - } - else - { a = (struct SOAP_ENV__Header *)soap_id_forward(soap, soap->href, (void*)a, 0, SOAP_TYPE_SOAP_ENV__Header, 0, sizeof(struct SOAP_ENV__Header), 0, NULL); - if (soap->body && soap_element_end_in(soap, tag)) - return NULL; - } - return a; -} - -SOAP_FMAC5 struct SOAP_ENV__Header * SOAP_FMAC6 soap_new_SOAP_ENV__Header(struct soap *soap, int n) -{ return soap_instantiate_SOAP_ENV__Header(soap, n, NULL, NULL, NULL); -} - -SOAP_FMAC5 void SOAP_FMAC6 soap_delete_SOAP_ENV__Header(struct soap *soap, struct SOAP_ENV__Header *p) -{ soap_delete(soap, p); -} - -SOAP_FMAC3 struct SOAP_ENV__Header * SOAP_FMAC4 soap_instantiate_SOAP_ENV__Header(struct soap *soap, int n, const char *type, const char *arrayType, size_t *size) -{ - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "soap_instantiate_SOAP_ENV__Header(%d, %s, %s)\n", n, type?type:"", arrayType?arrayType:"")); - struct soap_clist *cp = soap_link(soap, NULL, SOAP_TYPE_SOAP_ENV__Header, n, soap_fdelete); - if (!cp) - return NULL; - if (n < 0) - { cp->ptr = (void*)new struct SOAP_ENV__Header; - if (size) - *size = sizeof(struct SOAP_ENV__Header); - } - else - { cp->ptr = (void*)new struct SOAP_ENV__Header[n]; - if (!cp->ptr) - { soap->error = SOAP_EOM; - return NULL; - } - if (size) - *size = n * sizeof(struct SOAP_ENV__Header); - } - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Instantiated location=%p\n", cp->ptr)); - return (struct SOAP_ENV__Header*)cp->ptr; -} -SOAP_FMAC3 void SOAP_FMAC4 soap_copy_SOAP_ENV__Header(struct soap *soap, int st, int tt, void *p, size_t len, const void *q, size_t n) -{ - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copying struct SOAP_ENV__Header %p -> %p\n", q, p)); - *(struct SOAP_ENV__Header*)p = *(struct SOAP_ENV__Header*)q; -} - -#endif - -SOAP_FMAC3 void SOAP_FMAC4 soap_default_ns1__executeCommand(struct soap *soap, struct ns1__executeCommand *a) -{ - (void)soap; (void)a; /* appease -Wall -Werror */ - soap_default_string(soap, &a->command); -} - -SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_ns1__executeCommand(struct soap *soap, const struct ns1__executeCommand *a) -{ - (void)soap; (void)a; /* appease -Wall -Werror */ - soap_serialize_string(soap, &a->command); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_put_ns1__executeCommand(struct soap *soap, const struct ns1__executeCommand *a, const char *tag, const char *type) -{ - register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_ns1__executeCommand); - if (soap_out_ns1__executeCommand(soap, tag, id, a, type)) - return soap->error; - return soap_putindependent(soap); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_out_ns1__executeCommand(struct soap *soap, const char *tag, int id, const struct ns1__executeCommand *a, const char *type) -{ - if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_ns1__executeCommand), type)) - return soap->error; - if (soap_out_string(soap, "command", -1, &a->command, "")) - return soap->error; - return soap_element_end_out(soap, tag); -} - -SOAP_FMAC3 struct ns1__executeCommand * SOAP_FMAC4 soap_get_ns1__executeCommand(struct soap *soap, struct ns1__executeCommand *p, const char *tag, const char *type) -{ - if ((p = soap_in_ns1__executeCommand(soap, tag, p, type))) - if (soap_getindependent(soap)) - return NULL; - return p; -} - -SOAP_FMAC3 struct ns1__executeCommand * SOAP_FMAC4 soap_in_ns1__executeCommand(struct soap *soap, const char *tag, struct ns1__executeCommand *a, const char *type) -{ - short soap_flag_command = 1; - if (soap_element_begin_in(soap, tag, 0, type)) - return NULL; - a = (struct ns1__executeCommand *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_ns1__executeCommand, sizeof(struct ns1__executeCommand), 0, NULL, NULL, NULL); - if (!a) - return NULL; - soap_default_ns1__executeCommand(soap, a); - if (soap->body && !*soap->href) - { - for (;;) - { soap->error = SOAP_TAG_MISMATCH; - if (soap_flag_command && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG)) - if (soap_in_string(soap, "command", &a->command, "xsd:string")) - { soap_flag_command--; - continue; - } - if (soap->error == SOAP_TAG_MISMATCH) - soap->error = soap_ignore_element(soap); - if (soap->error == SOAP_NO_TAG) - break; - if (soap->error) - return NULL; - } - if (soap_element_end_in(soap, tag)) - return NULL; - } - else - { a = (struct ns1__executeCommand *)soap_id_forward(soap, soap->href, (void*)a, 0, SOAP_TYPE_ns1__executeCommand, 0, sizeof(struct ns1__executeCommand), 0, NULL); - if (soap->body && soap_element_end_in(soap, tag)) - return NULL; - } - return a; -} - -SOAP_FMAC5 struct ns1__executeCommand * SOAP_FMAC6 soap_new_ns1__executeCommand(struct soap *soap, int n) -{ return soap_instantiate_ns1__executeCommand(soap, n, NULL, NULL, NULL); -} - -SOAP_FMAC5 void SOAP_FMAC6 soap_delete_ns1__executeCommand(struct soap *soap, struct ns1__executeCommand *p) -{ soap_delete(soap, p); -} - -SOAP_FMAC3 struct ns1__executeCommand * SOAP_FMAC4 soap_instantiate_ns1__executeCommand(struct soap *soap, int n, const char *type, const char *arrayType, size_t *size) -{ - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "soap_instantiate_ns1__executeCommand(%d, %s, %s)\n", n, type?type:"", arrayType?arrayType:"")); - struct soap_clist *cp = soap_link(soap, NULL, SOAP_TYPE_ns1__executeCommand, n, soap_fdelete); - if (!cp) - return NULL; - if (n < 0) - { cp->ptr = (void*)new struct ns1__executeCommand; - if (size) - *size = sizeof(struct ns1__executeCommand); - } - else - { cp->ptr = (void*)new struct ns1__executeCommand[n]; - if (!cp->ptr) - { soap->error = SOAP_EOM; - return NULL; - } - if (size) - *size = n * sizeof(struct ns1__executeCommand); - } - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Instantiated location=%p\n", cp->ptr)); - return (struct ns1__executeCommand*)cp->ptr; -} -SOAP_FMAC3 void SOAP_FMAC4 soap_copy_ns1__executeCommand(struct soap *soap, int st, int tt, void *p, size_t len, const void *q, size_t n) -{ - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copying struct ns1__executeCommand %p -> %p\n", q, p)); - *(struct ns1__executeCommand*)p = *(struct ns1__executeCommand*)q; -} - -SOAP_FMAC3 void SOAP_FMAC4 soap_default_ns1__executeCommandResponse(struct soap *soap, struct ns1__executeCommandResponse *a) -{ - (void)soap; (void)a; /* appease -Wall -Werror */ - a->result = NULL; -} - -SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_ns1__executeCommandResponse(struct soap *soap, const struct ns1__executeCommandResponse *a) -{ - (void)soap; (void)a; /* appease -Wall -Werror */ - soap_serialize_PointerTostring(soap, &a->result); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_put_ns1__executeCommandResponse(struct soap *soap, const struct ns1__executeCommandResponse *a, const char *tag, const char *type) -{ - register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_ns1__executeCommandResponse); - if (soap_out_ns1__executeCommandResponse(soap, tag, id, a, type)) - return soap->error; - return soap_putindependent(soap); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_out_ns1__executeCommandResponse(struct soap *soap, const char *tag, int id, const struct ns1__executeCommandResponse *a, const char *type) -{ - if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_ns1__executeCommandResponse), type)) - return soap->error; - if (soap_out_PointerTostring(soap, "result", -1, &a->result, "")) - return soap->error; - return soap_element_end_out(soap, tag); -} - -SOAP_FMAC3 struct ns1__executeCommandResponse * SOAP_FMAC4 soap_get_ns1__executeCommandResponse(struct soap *soap, struct ns1__executeCommandResponse *p, const char *tag, const char *type) -{ - if ((p = soap_in_ns1__executeCommandResponse(soap, tag, p, type))) - if (soap_getindependent(soap)) - return NULL; - return p; -} - -SOAP_FMAC3 struct ns1__executeCommandResponse * SOAP_FMAC4 soap_in_ns1__executeCommandResponse(struct soap *soap, const char *tag, struct ns1__executeCommandResponse *a, const char *type) -{ - short soap_flag_result = 1; - if (soap_element_begin_in(soap, tag, 0, type)) - return NULL; - a = (struct ns1__executeCommandResponse *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_ns1__executeCommandResponse, sizeof(struct ns1__executeCommandResponse), 0, NULL, NULL, NULL); - if (!a) - return NULL; - soap_default_ns1__executeCommandResponse(soap, a); - if (soap->body && !*soap->href) - { - for (;;) - { soap->error = SOAP_TAG_MISMATCH; - if (soap_flag_result && soap->error == SOAP_TAG_MISMATCH) - if (soap_in_PointerTostring(soap, "result", &a->result, "xsd:string")) - { soap_flag_result--; - continue; - } - if (soap->error == SOAP_TAG_MISMATCH) - soap->error = soap_ignore_element(soap); - if (soap->error == SOAP_NO_TAG) - break; - if (soap->error) - return NULL; - } - if (soap_element_end_in(soap, tag)) - return NULL; - } - else - { a = (struct ns1__executeCommandResponse *)soap_id_forward(soap, soap->href, (void*)a, 0, SOAP_TYPE_ns1__executeCommandResponse, 0, sizeof(struct ns1__executeCommandResponse), 0, NULL); - if (soap->body && soap_element_end_in(soap, tag)) - return NULL; - } - return a; -} - -SOAP_FMAC5 struct ns1__executeCommandResponse * SOAP_FMAC6 soap_new_ns1__executeCommandResponse(struct soap *soap, int n) -{ return soap_instantiate_ns1__executeCommandResponse(soap, n, NULL, NULL, NULL); -} - -SOAP_FMAC5 void SOAP_FMAC6 soap_delete_ns1__executeCommandResponse(struct soap *soap, struct ns1__executeCommandResponse *p) -{ soap_delete(soap, p); -} - -SOAP_FMAC3 struct ns1__executeCommandResponse * SOAP_FMAC4 soap_instantiate_ns1__executeCommandResponse(struct soap *soap, int n, const char *type, const char *arrayType, size_t *size) -{ - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "soap_instantiate_ns1__executeCommandResponse(%d, %s, %s)\n", n, type?type:"", arrayType?arrayType:"")); - struct soap_clist *cp = soap_link(soap, NULL, SOAP_TYPE_ns1__executeCommandResponse, n, soap_fdelete); - if (!cp) - return NULL; - if (n < 0) - { cp->ptr = (void*)new struct ns1__executeCommandResponse; - if (size) - *size = sizeof(struct ns1__executeCommandResponse); - } - else - { cp->ptr = (void*)new struct ns1__executeCommandResponse[n]; - if (!cp->ptr) - { soap->error = SOAP_EOM; - return NULL; - } - if (size) - *size = n * sizeof(struct ns1__executeCommandResponse); - } - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Instantiated location=%p\n", cp->ptr)); - return (struct ns1__executeCommandResponse*)cp->ptr; -} -SOAP_FMAC3 void SOAP_FMAC4 soap_copy_ns1__executeCommandResponse(struct soap *soap, int st, int tt, void *p, size_t len, const void *q, size_t n) -{ - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copying struct ns1__executeCommandResponse %p -> %p\n", q, p)); - *(struct ns1__executeCommandResponse*)p = *(struct ns1__executeCommandResponse*)q; -} - -#ifndef WITH_NOGLOBAL - -SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerToSOAP_ENV__Reason(struct soap *soap, struct SOAP_ENV__Reason *const*a) -{ - if (!soap_reference(soap, *a, SOAP_TYPE_SOAP_ENV__Reason)) - soap_serialize_SOAP_ENV__Reason(soap, *a); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerToSOAP_ENV__Reason(struct soap *soap, struct SOAP_ENV__Reason *const*a, const char *tag, const char *type) -{ - register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_PointerToSOAP_ENV__Reason); - if (soap_out_PointerToSOAP_ENV__Reason(soap, tag, id, a, type)) - return soap->error; - return soap_putindependent(soap); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerToSOAP_ENV__Reason(struct soap *soap, const char *tag, int id, struct SOAP_ENV__Reason *const*a, const char *type) -{ - id = soap_element_id(soap, tag, id, *a, NULL, 0, type, SOAP_TYPE_SOAP_ENV__Reason); - if (id < 0) - return soap->error; - return soap_out_SOAP_ENV__Reason(soap, tag, id, *a, type); -} - -SOAP_FMAC3 struct SOAP_ENV__Reason ** SOAP_FMAC4 soap_get_PointerToSOAP_ENV__Reason(struct soap *soap, struct SOAP_ENV__Reason **p, const char *tag, const char *type) -{ - if ((p = soap_in_PointerToSOAP_ENV__Reason(soap, tag, p, type))) - if (soap_getindependent(soap)) - return NULL; - return p; -} - -SOAP_FMAC3 struct SOAP_ENV__Reason ** SOAP_FMAC4 soap_in_PointerToSOAP_ENV__Reason(struct soap *soap, const char *tag, struct SOAP_ENV__Reason **a, const char *type) -{ - if (soap_element_begin_in(soap, tag, 1, NULL)) - return NULL; - if (!a) - if (!(a = (struct SOAP_ENV__Reason **)soap_malloc(soap, sizeof(struct SOAP_ENV__Reason *)))) - return NULL; - *a = NULL; - if (!soap->null && *soap->href != '#') - { soap_revert(soap); - if (!(*a = soap_in_SOAP_ENV__Reason(soap, tag, *a, type))) - return NULL; - } - else - { a = (struct SOAP_ENV__Reason **)soap_id_lookup(soap, soap->href, (void**)a, SOAP_TYPE_SOAP_ENV__Reason, sizeof(struct SOAP_ENV__Reason), 0); - if (soap->body && soap_element_end_in(soap, tag)) - return NULL; - } - return a; -} - -#endif - -#ifndef WITH_NOGLOBAL - -SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerToSOAP_ENV__Detail(struct soap *soap, struct SOAP_ENV__Detail *const*a) -{ - if (!soap_reference(soap, *a, SOAP_TYPE_SOAP_ENV__Detail)) - soap_serialize_SOAP_ENV__Detail(soap, *a); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerToSOAP_ENV__Detail(struct soap *soap, struct SOAP_ENV__Detail *const*a, const char *tag, const char *type) -{ - register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_PointerToSOAP_ENV__Detail); - if (soap_out_PointerToSOAP_ENV__Detail(soap, tag, id, a, type)) - return soap->error; - return soap_putindependent(soap); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerToSOAP_ENV__Detail(struct soap *soap, const char *tag, int id, struct SOAP_ENV__Detail *const*a, const char *type) -{ - id = soap_element_id(soap, tag, id, *a, NULL, 0, type, SOAP_TYPE_SOAP_ENV__Detail); - if (id < 0) - return soap->error; - return soap_out_SOAP_ENV__Detail(soap, tag, id, *a, type); -} - -SOAP_FMAC3 struct SOAP_ENV__Detail ** SOAP_FMAC4 soap_get_PointerToSOAP_ENV__Detail(struct soap *soap, struct SOAP_ENV__Detail **p, const char *tag, const char *type) -{ - if ((p = soap_in_PointerToSOAP_ENV__Detail(soap, tag, p, type))) - if (soap_getindependent(soap)) - return NULL; - return p; -} - -SOAP_FMAC3 struct SOAP_ENV__Detail ** SOAP_FMAC4 soap_in_PointerToSOAP_ENV__Detail(struct soap *soap, const char *tag, struct SOAP_ENV__Detail **a, const char *type) -{ - if (soap_element_begin_in(soap, tag, 1, NULL)) - return NULL; - if (!a) - if (!(a = (struct SOAP_ENV__Detail **)soap_malloc(soap, sizeof(struct SOAP_ENV__Detail *)))) - return NULL; - *a = NULL; - if (!soap->null && *soap->href != '#') - { soap_revert(soap); - if (!(*a = soap_in_SOAP_ENV__Detail(soap, tag, *a, type))) - return NULL; - } - else - { a = (struct SOAP_ENV__Detail **)soap_id_lookup(soap, soap->href, (void**)a, SOAP_TYPE_SOAP_ENV__Detail, sizeof(struct SOAP_ENV__Detail), 0); - if (soap->body && soap_element_end_in(soap, tag)) - return NULL; - } - return a; -} - -#endif - -#ifndef WITH_NOGLOBAL - -SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerToSOAP_ENV__Code(struct soap *soap, struct SOAP_ENV__Code *const*a) -{ - if (!soap_reference(soap, *a, SOAP_TYPE_SOAP_ENV__Code)) - soap_serialize_SOAP_ENV__Code(soap, *a); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerToSOAP_ENV__Code(struct soap *soap, struct SOAP_ENV__Code *const*a, const char *tag, const char *type) -{ - register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_PointerToSOAP_ENV__Code); - if (soap_out_PointerToSOAP_ENV__Code(soap, tag, id, a, type)) - return soap->error; - return soap_putindependent(soap); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerToSOAP_ENV__Code(struct soap *soap, const char *tag, int id, struct SOAP_ENV__Code *const*a, const char *type) -{ - id = soap_element_id(soap, tag, id, *a, NULL, 0, type, SOAP_TYPE_SOAP_ENV__Code); - if (id < 0) - return soap->error; - return soap_out_SOAP_ENV__Code(soap, tag, id, *a, type); -} - -SOAP_FMAC3 struct SOAP_ENV__Code ** SOAP_FMAC4 soap_get_PointerToSOAP_ENV__Code(struct soap *soap, struct SOAP_ENV__Code **p, const char *tag, const char *type) -{ - if ((p = soap_in_PointerToSOAP_ENV__Code(soap, tag, p, type))) - if (soap_getindependent(soap)) - return NULL; - return p; -} - -SOAP_FMAC3 struct SOAP_ENV__Code ** SOAP_FMAC4 soap_in_PointerToSOAP_ENV__Code(struct soap *soap, const char *tag, struct SOAP_ENV__Code **a, const char *type) -{ - if (soap_element_begin_in(soap, tag, 1, NULL)) - return NULL; - if (!a) - if (!(a = (struct SOAP_ENV__Code **)soap_malloc(soap, sizeof(struct SOAP_ENV__Code *)))) - return NULL; - *a = NULL; - if (!soap->null && *soap->href != '#') - { soap_revert(soap); - if (!(*a = soap_in_SOAP_ENV__Code(soap, tag, *a, type))) - return NULL; - } - else - { a = (struct SOAP_ENV__Code **)soap_id_lookup(soap, soap->href, (void**)a, SOAP_TYPE_SOAP_ENV__Code, sizeof(struct SOAP_ENV__Code), 0); - if (soap->body && soap_element_end_in(soap, tag)) - return NULL; - } - return a; -} - -#endif - -SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerTostring(struct soap *soap, char **const*a) -{ - if (!soap_reference(soap, *a, SOAP_TYPE_string)) - soap_serialize_string(soap, *a); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerTostring(struct soap *soap, char **const*a, const char *tag, const char *type) -{ - register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_PointerTostring); - if (soap_out_PointerTostring(soap, tag, id, a, type)) - return soap->error; - return soap_putindependent(soap); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerTostring(struct soap *soap, const char *tag, int id, char **const*a, const char *type) -{ - id = soap_element_id(soap, tag, id, *a, NULL, 0, type, SOAP_TYPE_string); - if (id < 0) - return soap->error; - return soap_out_string(soap, tag, id, *a, type); -} - -SOAP_FMAC3 char *** SOAP_FMAC4 soap_get_PointerTostring(struct soap *soap, char ***p, const char *tag, const char *type) -{ - if ((p = soap_in_PointerTostring(soap, tag, p, type))) - if (soap_getindependent(soap)) - return NULL; - return p; -} - -SOAP_FMAC3 char *** SOAP_FMAC4 soap_in_PointerTostring(struct soap *soap, const char *tag, char ***a, const char *type) -{ - if (soap_element_begin_in(soap, tag, 1, NULL)) - return NULL; - if (!a) - if (!(a = (char ***)soap_malloc(soap, sizeof(char **)))) - return NULL; - *a = NULL; - if (!soap->null && *soap->href != '#') - { soap_revert(soap); - if (!(*a = soap_in_string(soap, tag, *a, type))) - return NULL; - } - else - { a = (char ***)soap_id_lookup(soap, soap->href, (void**)a, SOAP_TYPE_string, sizeof(char *), 1); - if (soap->body && soap_element_end_in(soap, tag)) - return NULL; - } - return a; -} - -SOAP_FMAC3 void SOAP_FMAC4 soap_default__QName(struct soap *soap, char **a) -{ soap_default_string(soap, a); -} - -SOAP_FMAC3 void SOAP_FMAC4 soap_serialize__QName(struct soap *soap, char *const*a) -{ soap_serialize_string(soap, a); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_put__QName(struct soap *soap, char *const*a, const char *tag, const char *type) -{ - register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE__QName); - if (soap_out__QName(soap, tag, id, a, type)) - return soap->error; - return soap_putindependent(soap); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_out__QName(struct soap *soap, const char *tag, int id, char *const*a, const char *type) -{ - return soap_outstring(soap, tag, id, a, type, SOAP_TYPE__QName); -} - -SOAP_FMAC3 char ** SOAP_FMAC4 soap_get__QName(struct soap *soap, char **p, const char *tag, const char *type) -{ - if ((p = soap_in__QName(soap, tag, p, type))) - if (soap_getindependent(soap)) - return NULL; - return p; -} - -SOAP_FMAC3 char * * SOAP_FMAC4 soap_in__QName(struct soap *soap, const char *tag, char **a, const char *type) -{ - return soap_instring(soap, tag, a, type, SOAP_TYPE__QName, 2, -1, -1); -} - -SOAP_FMAC3 void SOAP_FMAC4 soap_default_string(struct soap *soap, char **a) -{ (void)soap; /* appease -Wall -Werror */ -#ifdef SOAP_DEFAULT_string - *a = SOAP_DEFAULT_string; -#else - *a = (char *)0; -#endif -} - -SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_string(struct soap *soap, char *const*a) -{ - soap_reference(soap, *a, SOAP_TYPE_string); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_put_string(struct soap *soap, char *const*a, const char *tag, const char *type) -{ - register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_string); - if (soap_out_string(soap, tag, id, a, type)) - return soap->error; - return soap_putindependent(soap); -} - -SOAP_FMAC3 int SOAP_FMAC4 soap_out_string(struct soap *soap, const char *tag, int id, char *const*a, const char *type) -{ - return soap_outstring(soap, tag, id, a, type, SOAP_TYPE_string); -} - -SOAP_FMAC3 char ** SOAP_FMAC4 soap_get_string(struct soap *soap, char **p, const char *tag, const char *type) -{ - if ((p = soap_in_string(soap, tag, p, type))) - if (soap_getindependent(soap)) - return NULL; - return p; -} - -SOAP_FMAC3 char * * SOAP_FMAC4 soap_in_string(struct soap *soap, const char *tag, char **a, const char *type) -{ - return soap_instring(soap, tag, a, type, SOAP_TYPE_string, 1, -1, -1); -} - -/* End of soapC.cpp */ - diff --git a/externals/gsoap/soapH.h b/externals/gsoap/soapH.h deleted file mode 100644 index ae135516be7..00000000000 --- a/externals/gsoap/soapH.h +++ /dev/null @@ -1,239 +0,0 @@ -/* soapH.h - Generated by gSOAP 2.7.10 from stub.h - Copyright(C) 2000-2008, Robert van Engelen, Genivia Inc. All Rights Reserved. - This part of the software is released under one of the following licenses: - GPL, the gSOAP public license, or Genivia's license for commercial use. -*/ - -#ifndef soapH_H -#define soapH_H -#include "soapStub.h" -#ifndef WITH_NOIDREF - -#ifdef __cplusplus -extern "C" { -#endif -SOAP_FMAC3 void SOAP_FMAC4 soap_markelement(struct soap*, const void*, int); -SOAP_FMAC3 int SOAP_FMAC4 soap_putelement(struct soap*, const void*, const char*, int, int); -SOAP_FMAC3 void *SOAP_FMAC4 soap_getelement(struct soap*, int*); - -#ifdef __cplusplus -} -#endif -SOAP_FMAC3 int SOAP_FMAC4 soap_putindependent(struct soap*); -SOAP_FMAC3 int SOAP_FMAC4 soap_getindependent(struct soap*); -#endif -SOAP_FMAC3 int SOAP_FMAC4 soap_ignore_element(struct soap*); - -SOAP_FMAC3 void * SOAP_FMAC4 soap_instantiate(struct soap*, int, const char*, const char*, size_t*); -SOAP_FMAC3 int SOAP_FMAC4 soap_fdelete(struct soap_clist*); -SOAP_FMAC3 void* SOAP_FMAC4 soap_class_id_enter(struct soap*, const char*, void*, int, size_t, const char*, const char*); - -#ifndef SOAP_TYPE_byte -#define SOAP_TYPE_byte (3) -#endif -SOAP_FMAC3 void SOAP_FMAC4 soap_default_byte(struct soap*, char *); -SOAP_FMAC3 int SOAP_FMAC4 soap_put_byte(struct soap*, const char *, const char*, const char*); -SOAP_FMAC3 int SOAP_FMAC4 soap_out_byte(struct soap*, const char*, int, const char *, const char*); -SOAP_FMAC3 char * SOAP_FMAC4 soap_get_byte(struct soap*, char *, const char*, const char*); -SOAP_FMAC3 char * SOAP_FMAC4 soap_in_byte(struct soap*, const char*, char *, const char*); - -#ifndef SOAP_TYPE_int -#define SOAP_TYPE_int (1) -#endif -SOAP_FMAC3 void SOAP_FMAC4 soap_default_int(struct soap*, int *); -SOAP_FMAC3 int SOAP_FMAC4 soap_put_int(struct soap*, const int *, const char*, const char*); -SOAP_FMAC3 int SOAP_FMAC4 soap_out_int(struct soap*, const char*, int, const int *, const char*); -SOAP_FMAC3 int * SOAP_FMAC4 soap_get_int(struct soap*, int *, const char*, const char*); -SOAP_FMAC3 int * SOAP_FMAC4 soap_in_int(struct soap*, const char*, int *, const char*); - -#ifndef WITH_NOGLOBAL - -#ifndef SOAP_TYPE_SOAP_ENV__Fault -#define SOAP_TYPE_SOAP_ENV__Fault (18) -#endif -SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Fault(struct soap*, struct SOAP_ENV__Fault *); -SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Fault(struct soap*, const struct SOAP_ENV__Fault *); -SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Fault(struct soap*, const struct SOAP_ENV__Fault *, const char*, const char*); -SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Fault(struct soap*, const char*, int, const struct SOAP_ENV__Fault *, const char*); -SOAP_FMAC3 struct SOAP_ENV__Fault * SOAP_FMAC4 soap_get_SOAP_ENV__Fault(struct soap*, struct SOAP_ENV__Fault *, const char*, const char*); -SOAP_FMAC3 struct SOAP_ENV__Fault * SOAP_FMAC4 soap_in_SOAP_ENV__Fault(struct soap*, const char*, struct SOAP_ENV__Fault *, const char*); -SOAP_FMAC5 struct SOAP_ENV__Fault * SOAP_FMAC6 soap_new_SOAP_ENV__Fault(struct soap*, int); -SOAP_FMAC5 void SOAP_FMAC6 soap_delete_SOAP_ENV__Fault(struct soap*, struct SOAP_ENV__Fault*); -SOAP_FMAC3 struct SOAP_ENV__Fault * SOAP_FMAC4 soap_instantiate_SOAP_ENV__Fault(struct soap*, int, const char*, const char*, size_t*); -SOAP_FMAC3 void SOAP_FMAC4 soap_copy_SOAP_ENV__Fault(struct soap*, int, int, void*, size_t, const void*, size_t); - -#endif - -#ifndef WITH_NOGLOBAL - -#ifndef SOAP_TYPE_SOAP_ENV__Reason -#define SOAP_TYPE_SOAP_ENV__Reason (17) -#endif -SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Reason(struct soap*, struct SOAP_ENV__Reason *); -SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Reason(struct soap*, const struct SOAP_ENV__Reason *); -SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Reason(struct soap*, const struct SOAP_ENV__Reason *, const char*, const char*); -SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Reason(struct soap*, const char*, int, const struct SOAP_ENV__Reason *, const char*); -SOAP_FMAC3 struct SOAP_ENV__Reason * SOAP_FMAC4 soap_get_SOAP_ENV__Reason(struct soap*, struct SOAP_ENV__Reason *, const char*, const char*); -SOAP_FMAC3 struct SOAP_ENV__Reason * SOAP_FMAC4 soap_in_SOAP_ENV__Reason(struct soap*, const char*, struct SOAP_ENV__Reason *, const char*); -SOAP_FMAC5 struct SOAP_ENV__Reason * SOAP_FMAC6 soap_new_SOAP_ENV__Reason(struct soap*, int); -SOAP_FMAC5 void SOAP_FMAC6 soap_delete_SOAP_ENV__Reason(struct soap*, struct SOAP_ENV__Reason*); -SOAP_FMAC3 struct SOAP_ENV__Reason * SOAP_FMAC4 soap_instantiate_SOAP_ENV__Reason(struct soap*, int, const char*, const char*, size_t*); -SOAP_FMAC3 void SOAP_FMAC4 soap_copy_SOAP_ENV__Reason(struct soap*, int, int, void*, size_t, const void*, size_t); - -#endif - -#ifndef WITH_NOGLOBAL - -#ifndef SOAP_TYPE_SOAP_ENV__Detail -#define SOAP_TYPE_SOAP_ENV__Detail (14) -#endif -SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Detail(struct soap*, struct SOAP_ENV__Detail *); -SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Detail(struct soap*, const struct SOAP_ENV__Detail *); -SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Detail(struct soap*, const struct SOAP_ENV__Detail *, const char*, const char*); -SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Detail(struct soap*, const char*, int, const struct SOAP_ENV__Detail *, const char*); -SOAP_FMAC3 struct SOAP_ENV__Detail * SOAP_FMAC4 soap_get_SOAP_ENV__Detail(struct soap*, struct SOAP_ENV__Detail *, const char*, const char*); -SOAP_FMAC3 struct SOAP_ENV__Detail * SOAP_FMAC4 soap_in_SOAP_ENV__Detail(struct soap*, const char*, struct SOAP_ENV__Detail *, const char*); -SOAP_FMAC5 struct SOAP_ENV__Detail * SOAP_FMAC6 soap_new_SOAP_ENV__Detail(struct soap*, int); -SOAP_FMAC5 void SOAP_FMAC6 soap_delete_SOAP_ENV__Detail(struct soap*, struct SOAP_ENV__Detail*); -SOAP_FMAC3 struct SOAP_ENV__Detail * SOAP_FMAC4 soap_instantiate_SOAP_ENV__Detail(struct soap*, int, const char*, const char*, size_t*); -SOAP_FMAC3 void SOAP_FMAC4 soap_copy_SOAP_ENV__Detail(struct soap*, int, int, void*, size_t, const void*, size_t); - -#endif - -#ifndef WITH_NOGLOBAL - -#ifndef SOAP_TYPE_SOAP_ENV__Code -#define SOAP_TYPE_SOAP_ENV__Code (12) -#endif -SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Code(struct soap*, struct SOAP_ENV__Code *); -SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Code(struct soap*, const struct SOAP_ENV__Code *); -SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Code(struct soap*, const struct SOAP_ENV__Code *, const char*, const char*); -SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Code(struct soap*, const char*, int, const struct SOAP_ENV__Code *, const char*); -SOAP_FMAC3 struct SOAP_ENV__Code * SOAP_FMAC4 soap_get_SOAP_ENV__Code(struct soap*, struct SOAP_ENV__Code *, const char*, const char*); -SOAP_FMAC3 struct SOAP_ENV__Code * SOAP_FMAC4 soap_in_SOAP_ENV__Code(struct soap*, const char*, struct SOAP_ENV__Code *, const char*); -SOAP_FMAC5 struct SOAP_ENV__Code * SOAP_FMAC6 soap_new_SOAP_ENV__Code(struct soap*, int); -SOAP_FMAC5 void SOAP_FMAC6 soap_delete_SOAP_ENV__Code(struct soap*, struct SOAP_ENV__Code*); -SOAP_FMAC3 struct SOAP_ENV__Code * SOAP_FMAC4 soap_instantiate_SOAP_ENV__Code(struct soap*, int, const char*, const char*, size_t*); -SOAP_FMAC3 void SOAP_FMAC4 soap_copy_SOAP_ENV__Code(struct soap*, int, int, void*, size_t, const void*, size_t); - -#endif - -#ifndef WITH_NOGLOBAL - -#ifndef SOAP_TYPE_SOAP_ENV__Header -#define SOAP_TYPE_SOAP_ENV__Header (11) -#endif -SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Header(struct soap*, struct SOAP_ENV__Header *); -SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Header(struct soap*, const struct SOAP_ENV__Header *); -SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Header(struct soap*, const struct SOAP_ENV__Header *, const char*, const char*); -SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Header(struct soap*, const char*, int, const struct SOAP_ENV__Header *, const char*); -SOAP_FMAC3 struct SOAP_ENV__Header * SOAP_FMAC4 soap_get_SOAP_ENV__Header(struct soap*, struct SOAP_ENV__Header *, const char*, const char*); -SOAP_FMAC3 struct SOAP_ENV__Header * SOAP_FMAC4 soap_in_SOAP_ENV__Header(struct soap*, const char*, struct SOAP_ENV__Header *, const char*); -SOAP_FMAC5 struct SOAP_ENV__Header * SOAP_FMAC6 soap_new_SOAP_ENV__Header(struct soap*, int); -SOAP_FMAC5 void SOAP_FMAC6 soap_delete_SOAP_ENV__Header(struct soap*, struct SOAP_ENV__Header*); -SOAP_FMAC3 struct SOAP_ENV__Header * SOAP_FMAC4 soap_instantiate_SOAP_ENV__Header(struct soap*, int, const char*, const char*, size_t*); -SOAP_FMAC3 void SOAP_FMAC4 soap_copy_SOAP_ENV__Header(struct soap*, int, int, void*, size_t, const void*, size_t); - -#endif - -#ifndef SOAP_TYPE_ns1__executeCommand -#define SOAP_TYPE_ns1__executeCommand (10) -#endif -SOAP_FMAC3 void SOAP_FMAC4 soap_default_ns1__executeCommand(struct soap*, struct ns1__executeCommand *); -SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_ns1__executeCommand(struct soap*, const struct ns1__executeCommand *); -SOAP_FMAC3 int SOAP_FMAC4 soap_put_ns1__executeCommand(struct soap*, const struct ns1__executeCommand *, const char*, const char*); -SOAP_FMAC3 int SOAP_FMAC4 soap_out_ns1__executeCommand(struct soap*, const char*, int, const struct ns1__executeCommand *, const char*); -SOAP_FMAC3 struct ns1__executeCommand * SOAP_FMAC4 soap_get_ns1__executeCommand(struct soap*, struct ns1__executeCommand *, const char*, const char*); -SOAP_FMAC3 struct ns1__executeCommand * SOAP_FMAC4 soap_in_ns1__executeCommand(struct soap*, const char*, struct ns1__executeCommand *, const char*); -SOAP_FMAC5 struct ns1__executeCommand * SOAP_FMAC6 soap_new_ns1__executeCommand(struct soap*, int); -SOAP_FMAC5 void SOAP_FMAC6 soap_delete_ns1__executeCommand(struct soap*, struct ns1__executeCommand*); -SOAP_FMAC3 struct ns1__executeCommand * SOAP_FMAC4 soap_instantiate_ns1__executeCommand(struct soap*, int, const char*, const char*, size_t*); -SOAP_FMAC3 void SOAP_FMAC4 soap_copy_ns1__executeCommand(struct soap*, int, int, void*, size_t, const void*, size_t); - -#ifndef SOAP_TYPE_ns1__executeCommandResponse -#define SOAP_TYPE_ns1__executeCommandResponse (9) -#endif -SOAP_FMAC3 void SOAP_FMAC4 soap_default_ns1__executeCommandResponse(struct soap*, struct ns1__executeCommandResponse *); -SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_ns1__executeCommandResponse(struct soap*, const struct ns1__executeCommandResponse *); -SOAP_FMAC3 int SOAP_FMAC4 soap_put_ns1__executeCommandResponse(struct soap*, const struct ns1__executeCommandResponse *, const char*, const char*); -SOAP_FMAC3 int SOAP_FMAC4 soap_out_ns1__executeCommandResponse(struct soap*, const char*, int, const struct ns1__executeCommandResponse *, const char*); -SOAP_FMAC3 struct ns1__executeCommandResponse * SOAP_FMAC4 soap_get_ns1__executeCommandResponse(struct soap*, struct ns1__executeCommandResponse *, const char*, const char*); -SOAP_FMAC3 struct ns1__executeCommandResponse * SOAP_FMAC4 soap_in_ns1__executeCommandResponse(struct soap*, const char*, struct ns1__executeCommandResponse *, const char*); -SOAP_FMAC5 struct ns1__executeCommandResponse * SOAP_FMAC6 soap_new_ns1__executeCommandResponse(struct soap*, int); -SOAP_FMAC5 void SOAP_FMAC6 soap_delete_ns1__executeCommandResponse(struct soap*, struct ns1__executeCommandResponse*); -SOAP_FMAC3 struct ns1__executeCommandResponse * SOAP_FMAC4 soap_instantiate_ns1__executeCommandResponse(struct soap*, int, const char*, const char*, size_t*); -SOAP_FMAC3 void SOAP_FMAC4 soap_copy_ns1__executeCommandResponse(struct soap*, int, int, void*, size_t, const void*, size_t); - -#ifndef WITH_NOGLOBAL - -#ifndef SOAP_TYPE_PointerToSOAP_ENV__Reason -#define SOAP_TYPE_PointerToSOAP_ENV__Reason (20) -#endif -SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerToSOAP_ENV__Reason(struct soap*, struct SOAP_ENV__Reason *const*); -SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerToSOAP_ENV__Reason(struct soap*, struct SOAP_ENV__Reason *const*, const char*, const char*); -SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerToSOAP_ENV__Reason(struct soap*, const char *, int, struct SOAP_ENV__Reason *const*, const char *); -SOAP_FMAC3 struct SOAP_ENV__Reason ** SOAP_FMAC4 soap_get_PointerToSOAP_ENV__Reason(struct soap*, struct SOAP_ENV__Reason **, const char*, const char*); -SOAP_FMAC3 struct SOAP_ENV__Reason ** SOAP_FMAC4 soap_in_PointerToSOAP_ENV__Reason(struct soap*, const char*, struct SOAP_ENV__Reason **, const char*); - -#endif - -#ifndef WITH_NOGLOBAL - -#ifndef SOAP_TYPE_PointerToSOAP_ENV__Detail -#define SOAP_TYPE_PointerToSOAP_ENV__Detail (19) -#endif -SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerToSOAP_ENV__Detail(struct soap*, struct SOAP_ENV__Detail *const*); -SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerToSOAP_ENV__Detail(struct soap*, struct SOAP_ENV__Detail *const*, const char*, const char*); -SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerToSOAP_ENV__Detail(struct soap*, const char *, int, struct SOAP_ENV__Detail *const*, const char *); -SOAP_FMAC3 struct SOAP_ENV__Detail ** SOAP_FMAC4 soap_get_PointerToSOAP_ENV__Detail(struct soap*, struct SOAP_ENV__Detail **, const char*, const char*); -SOAP_FMAC3 struct SOAP_ENV__Detail ** SOAP_FMAC4 soap_in_PointerToSOAP_ENV__Detail(struct soap*, const char*, struct SOAP_ENV__Detail **, const char*); - -#endif - -#ifndef WITH_NOGLOBAL - -#ifndef SOAP_TYPE_PointerToSOAP_ENV__Code -#define SOAP_TYPE_PointerToSOAP_ENV__Code (13) -#endif -SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerToSOAP_ENV__Code(struct soap*, struct SOAP_ENV__Code *const*); -SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerToSOAP_ENV__Code(struct soap*, struct SOAP_ENV__Code *const*, const char*, const char*); -SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerToSOAP_ENV__Code(struct soap*, const char *, int, struct SOAP_ENV__Code *const*, const char *); -SOAP_FMAC3 struct SOAP_ENV__Code ** SOAP_FMAC4 soap_get_PointerToSOAP_ENV__Code(struct soap*, struct SOAP_ENV__Code **, const char*, const char*); -SOAP_FMAC3 struct SOAP_ENV__Code ** SOAP_FMAC4 soap_in_PointerToSOAP_ENV__Code(struct soap*, const char*, struct SOAP_ENV__Code **, const char*); - -#endif - -#ifndef SOAP_TYPE_PointerTostring -#define SOAP_TYPE_PointerTostring (7) -#endif -SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerTostring(struct soap*, char **const*); -SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerTostring(struct soap*, char **const*, const char*, const char*); -SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerTostring(struct soap*, const char *, int, char **const*, const char *); -SOAP_FMAC3 char *** SOAP_FMAC4 soap_get_PointerTostring(struct soap*, char ***, const char*, const char*); -SOAP_FMAC3 char *** SOAP_FMAC4 soap_in_PointerTostring(struct soap*, const char*, char ***, const char*); - -#ifndef SOAP_TYPE__QName -#define SOAP_TYPE__QName (5) -#endif -SOAP_FMAC3 void SOAP_FMAC4 soap_default__QName(struct soap*, char **); -SOAP_FMAC3 void SOAP_FMAC4 soap_serialize__QName(struct soap*, char *const*); -SOAP_FMAC3 int SOAP_FMAC4 soap_put__QName(struct soap*, char *const*, const char*, const char*); -SOAP_FMAC3 int SOAP_FMAC4 soap_out__QName(struct soap*, const char*, int, char*const*, const char*); -SOAP_FMAC3 char ** SOAP_FMAC4 soap_get__QName(struct soap*, char **, const char*, const char*); -SOAP_FMAC3 char * * SOAP_FMAC4 soap_in__QName(struct soap*, const char*, char **, const char*); - -#ifndef SOAP_TYPE_string -#define SOAP_TYPE_string (4) -#endif -SOAP_FMAC3 void SOAP_FMAC4 soap_default_string(struct soap*, char **); -SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_string(struct soap*, char *const*); -SOAP_FMAC3 int SOAP_FMAC4 soap_put_string(struct soap*, char *const*, const char*, const char*); -SOAP_FMAC3 int SOAP_FMAC4 soap_out_string(struct soap*, const char*, int, char*const*, const char*); -SOAP_FMAC3 char ** SOAP_FMAC4 soap_get_string(struct soap*, char **, const char*, const char*); -SOAP_FMAC3 char * * SOAP_FMAC4 soap_in_string(struct soap*, const char*, char **, const char*); - -#endif - -/* End of soapH.h */ - diff --git a/externals/gsoap/soapServer.cpp b/externals/gsoap/soapServer.cpp deleted file mode 100644 index e3eeb8fb3d7..00000000000 --- a/externals/gsoap/soapServer.cpp +++ /dev/null @@ -1,127 +0,0 @@ -/* soapServer.cpp - Generated by gSOAP 2.7.10 from stub.h - Copyright(C) 2000-2008, Robert van Engelen, Genivia Inc. All Rights Reserved. - This part of the software is released under one of the following licenses: - GPL, the gSOAP public license, or Genivia's license for commercial use. -*/ -#include "soapH.h" - -SOAP_SOURCE_STAMP("@(#) soapServer.cpp ver 2.7.10 2010-02-18 18:41:56 GMT") - - -SOAP_FMAC5 int SOAP_FMAC6 soap_serve(struct soap *soap) -{ -#ifndef WITH_FASTCGI - unsigned int k = soap->max_keep_alive; -#endif - - do - { -#ifdef WITH_FASTCGI - if (FCGI_Accept() < 0) - { - soap->error = SOAP_EOF; - return soap_send_fault(soap); - } -#endif - - soap_begin(soap); - -#ifndef WITH_FASTCGI - if (soap->max_keep_alive > 0 && !--k) - soap->keep_alive = 0; -#endif - - if (soap_begin_recv(soap)) - { if (soap->error < SOAP_STOP) - { -#ifdef WITH_FASTCGI - soap_send_fault(soap); -#else - return soap_send_fault(soap); -#endif - } - soap_closesock(soap); - - continue; - } - - if (soap_envelope_begin_in(soap) - || soap_recv_header(soap) - || soap_body_begin_in(soap) - || soap_serve_request(soap) - || (soap->fserveloop && soap->fserveloop(soap))) - { -#ifdef WITH_FASTCGI - soap_send_fault(soap); -#else - return soap_send_fault(soap); -#endif - } - -#ifdef WITH_FASTCGI - soap_destroy(soap); - soap_end(soap); - } while (1); -#else - } while (soap->keep_alive); -#endif - return SOAP_OK; -} - -#ifndef WITH_NOSERVEREQUEST -SOAP_FMAC5 int SOAP_FMAC6 soap_serve_request(struct soap *soap) -{ - soap_peek_element(soap); - if (!soap_match_tag(soap, soap->tag, "ns1:executeCommand")) - return soap_serve_ns1__executeCommand(soap); - return soap->error = SOAP_NO_METHOD; -} -#endif - -SOAP_FMAC5 int SOAP_FMAC6 soap_serve_ns1__executeCommand(struct soap *soap) -{ struct ns1__executeCommand soap_tmp_ns1__executeCommand; - struct ns1__executeCommandResponse soap_tmp_ns1__executeCommandResponse; - char * soap_tmp_string; - soap_default_ns1__executeCommandResponse(soap, &soap_tmp_ns1__executeCommandResponse); - soap_tmp_string = NULL; - soap_tmp_ns1__executeCommandResponse.result = &soap_tmp_string; - soap_default_ns1__executeCommand(soap, &soap_tmp_ns1__executeCommand); - soap->encodingStyle = NULL; - if (!soap_get_ns1__executeCommand(soap, &soap_tmp_ns1__executeCommand, "ns1:executeCommand", NULL)) - return soap->error; - if (soap_body_end_in(soap) - || soap_envelope_end_in(soap) - || soap_end_recv(soap)) - return soap->error; - soap->error = ns1__executeCommand(soap, soap_tmp_ns1__executeCommand.command, &soap_tmp_string); - if (soap->error) - return soap->error; - soap_serializeheader(soap); - soap_serialize_ns1__executeCommandResponse(soap, &soap_tmp_ns1__executeCommandResponse); - if (soap_begin_count(soap)) - return soap->error; - if (soap->mode & SOAP_IO_LENGTH) - { if (soap_envelope_begin_out(soap) - || soap_putheader(soap) - || soap_body_begin_out(soap) - || soap_put_ns1__executeCommandResponse(soap, &soap_tmp_ns1__executeCommandResponse, "ns1:executeCommandResponse", "") - || soap_body_end_out(soap) - || soap_envelope_end_out(soap)) - return soap->error; - }; - if (soap_end_count(soap) - || soap_response(soap, SOAP_OK) - || soap_envelope_begin_out(soap) - || soap_putheader(soap) - || soap_body_begin_out(soap) - || soap_put_ns1__executeCommandResponse(soap, &soap_tmp_ns1__executeCommandResponse, "ns1:executeCommandResponse", "") - || soap_body_end_out(soap) - || soap_envelope_end_out(soap) - || soap_end_send(soap)) - return soap->error; - return soap_closesock(soap); -} - -/* End of soapServer.cpp */ - diff --git a/externals/gsoap/soapStub.h b/externals/gsoap/soapStub.h deleted file mode 100644 index eaa35c247bc..00000000000 --- a/externals/gsoap/soapStub.h +++ /dev/null @@ -1,184 +0,0 @@ -/* soapStub.h - Generated by gSOAP 2.7.10 from stub.h - Copyright(C) 2000-2008, Robert van Engelen, Genivia Inc. All Rights Reserved. - This part of the software is released under one of the following licenses: - GPL, the gSOAP public license, or Genivia's license for commercial use. -*/ - -#ifndef soapStub_H -#define soapStub_H -#include "stdsoap2.h" - -/******************************************************************************\ - * * - * Enumerations * - * * -\******************************************************************************/ - - -/******************************************************************************\ - * * - * Classes and Structs * - * * -\******************************************************************************/ - - -#if 0 /* volatile type: do not redeclare here */ - -#endif - -#ifndef SOAP_TYPE_ns1__executeCommandResponse -#define SOAP_TYPE_ns1__executeCommandResponse (9) -/* ns1:executeCommandResponse */ -struct ns1__executeCommandResponse -{ -public: - char **result; /* SOAP 1.2 RPC return element (when namespace qualified) */ /* optional element of type xsd:string */ -}; -#endif - -#ifndef SOAP_TYPE_ns1__executeCommand -#define SOAP_TYPE_ns1__executeCommand (10) -/* ns1:executeCommand */ -struct ns1__executeCommand -{ -public: - char *command; /* optional element of type xsd:string */ -}; -#endif - -#ifndef SOAP_TYPE_SOAP_ENV__Header -#define SOAP_TYPE_SOAP_ENV__Header (11) -/* SOAP Header: */ -struct SOAP_ENV__Header -{ -#ifdef WITH_NOEMPTYSTRUCT -private: - char dummy; /* dummy member to enable compilation */ -#endif -}; -#endif - -#ifndef SOAP_TYPE_SOAP_ENV__Code -#define SOAP_TYPE_SOAP_ENV__Code (12) -/* SOAP Fault Code: */ -struct SOAP_ENV__Code -{ -public: - char *SOAP_ENV__Value; /* optional element of type xsd:QName */ - struct SOAP_ENV__Code *SOAP_ENV__Subcode; /* optional element of type SOAP-ENV:Code */ -}; -#endif - -#ifndef SOAP_TYPE_SOAP_ENV__Detail -#define SOAP_TYPE_SOAP_ENV__Detail (14) -/* SOAP-ENV:Detail */ -struct SOAP_ENV__Detail -{ -public: - int __type; /* any type of element (defined below) */ - void *fault; /* transient */ - char *__any; -}; -#endif - -#ifndef SOAP_TYPE_SOAP_ENV__Reason -#define SOAP_TYPE_SOAP_ENV__Reason (17) -/* SOAP-ENV:Reason */ -struct SOAP_ENV__Reason -{ -public: - char *SOAP_ENV__Text; /* optional element of type xsd:string */ -}; -#endif - -#ifndef SOAP_TYPE_SOAP_ENV__Fault -#define SOAP_TYPE_SOAP_ENV__Fault (18) -/* SOAP Fault: */ -struct SOAP_ENV__Fault -{ -public: - char *faultcode; /* optional element of type xsd:QName */ - char *faultstring; /* optional element of type xsd:string */ - char *faultactor; /* optional element of type xsd:string */ - struct SOAP_ENV__Detail *detail; /* optional element of type SOAP-ENV:Detail */ - struct SOAP_ENV__Code *SOAP_ENV__Code; /* optional element of type SOAP-ENV:Code */ - struct SOAP_ENV__Reason *SOAP_ENV__Reason; /* optional element of type SOAP-ENV:Reason */ - char *SOAP_ENV__Node; /* optional element of type xsd:string */ - char *SOAP_ENV__Role; /* optional element of type xsd:string */ - struct SOAP_ENV__Detail *SOAP_ENV__Detail; /* optional element of type SOAP-ENV:Detail */ -}; -#endif - -/******************************************************************************\ - * * - * Types with Custom Serializers * - * * -\******************************************************************************/ - - -/******************************************************************************\ - * * - * Typedefs * - * * -\******************************************************************************/ - -#ifndef SOAP_TYPE__QName -#define SOAP_TYPE__QName (5) -typedef char *_QName; -#endif - -#ifndef SOAP_TYPE__XML -#define SOAP_TYPE__XML (6) -typedef char *_XML; -#endif - - -/******************************************************************************\ - * * - * Typedef Synonyms * - * * -\******************************************************************************/ - - -/******************************************************************************\ - * * - * Externals * - * * -\******************************************************************************/ - - -/******************************************************************************\ - * * - * Service Operations * - * * -\******************************************************************************/ - - -SOAP_FMAC5 int SOAP_FMAC6 ns1__executeCommand(struct soap*, char *command, char **result); - -/******************************************************************************\ - * * - * Stubs * - * * -\******************************************************************************/ - - -SOAP_FMAC5 int SOAP_FMAC6 soap_call_ns1__executeCommand(struct soap *soap, const char *soap_endpoint, const char *soap_action, char *command, char **result); - -/******************************************************************************\ - * * - * Skeletons * - * * -\******************************************************************************/ - -SOAP_FMAC5 int SOAP_FMAC6 soap_serve(struct soap*); - -SOAP_FMAC5 int SOAP_FMAC6 soap_serve_request(struct soap*); - -SOAP_FMAC5 int SOAP_FMAC6 soap_serve_ns1__executeCommand(struct soap*); - -#endif - -/* End of soapStub.h */ - diff --git a/externals/gsoap/stdsoap2.cpp b/externals/gsoap/stdsoap2.cpp deleted file mode 100644 index 199d3118f23..00000000000 --- a/externals/gsoap/stdsoap2.cpp +++ /dev/null @@ -1,15198 +0,0 @@ -/* - stdsoap2.c[pp] 2.7.15 - - gSOAP runtime engine - -gSOAP XML Web services tools -Copyright (C) 2000-2009, Robert van Engelen, Genivia Inc., All Rights Reserved. -This part of the software is released under ONE of the following licenses: -GPL, or the gSOAP public license, or Genivia's license for commercial use. --------------------------------------------------------------------------------- -Contributors: - -Wind River Systems Inc., for the following additions under gSOAP public license: - - vxWorks compatible --------------------------------------------------------------------------------- -gSOAP public license. - -The contents of this file are subject to the gSOAP Public License Version 1.3 -(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.cs.fsu.edu/~engelen/soaplicense.html -Software distributed under the License is distributed on an "AS IS" basis, -WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License -for the specific language governing rights and limitations under the License. - -The Initial Developer of the Original Code is Robert A. van Engelen. -Copyright (C) 2000-2009, Robert van Engelen, Genivia Inc., All Rights Reserved. --------------------------------------------------------------------------------- -GPL license. - -This program is free software; you can redistribute it and/or modify it under -the terms of the GNU General Public License as published by the Free Software -Foundation; either version 2 of the License, or (at your option) any later -version. - -This program is distributed in the hope that it will be useful, but WITHOUT ANY -WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A -PARTICULAR PURPOSE. See the GNU General Public License for more details. - -You should have received a copy of the GNU General Public License along with -this program; if not, write to the Free Software Foundation, Inc., 59 Temple -Place, Suite 330, Boston, MA 02111-1307 USA - -Author contact information: -engelen@genivia.com / engelen@acm.org - -This program is released under the GPL with the additional exemption that -compiling, linking, and/or using OpenSSL is allowed. --------------------------------------------------------------------------------- -A commercial use license is available from Genivia, Inc., contact@genivia.com --------------------------------------------------------------------------------- - -Installation note: - -Win32 build needs winsock.dll (Visual C++ "wsock32.lib") -To do this in Visual C++ 6.0, go to "Project", "settings", select the "Link" -tab (the project file needs to be selected in the file view) and add -"wsock32.lib" to the "Object/library modules" entry - -On Mac OS X with gcc (GCC) 3.1 20020420 (prerelease) you MUST compile with --fstack_check when using -O2 because gcc 3.1 has a bug that smashes the stack -when locally allocated data exceeds 64K. - -*/ - -#ifdef AS400 -# pragma convert(819) /* EBCDIC to ASCII */ -#endif - -#include "stdsoap2.h" - -#ifdef __BORLANDC__ -# pragma warn -8060 -#else -# ifdef WIN32 -# ifdef UNDER_CE -# pragma comment(lib, "winsock.lib") -# else -# pragma comment(lib, "wsock32.lib") -# endif -# pragma warning(disable : 4996) /* disable deprecation warnings */ -# endif -#endif - -#ifdef __cplusplus -SOAP_SOURCE_STAMP("@(#) stdsoap2.cpp ver 2.7.15 2009-11-07 00:00:00 GMT") -extern "C" { -#else -SOAP_SOURCE_STAMP("@(#) stdsoap2.c ver 2.7.15 2009-11-07 00:00:00 GMT") -#endif - -/* 8bit character representing unknown/nonrepresentable character data (e.g. not supported by current locale with multibyte support enabled) */ -#ifndef SOAP_UNKNOWN_CHAR -#define SOAP_UNKNOWN_CHAR (127) -#endif - -/* EOF=-1 */ -#define SOAP_LT (soap_wchar)(-2) /* XML character '<' */ -#define SOAP_TT (soap_wchar)(-3) /* XML character '' */ -#define SOAP_QT (soap_wchar)(-5) /* XML character '"' */ -#define SOAP_AP (soap_wchar)(-6) /* XML character ''' */ - -#define soap_blank(c) ((c) >= 0 && (c) <= 32) -#define soap_notblank(c) ((c) > 32) - -#if defined(WIN32) && !defined(UNDER_CE) -#define soap_hash_ptr(p) ((PtrToUlong(p) >> 3) & (SOAP_PTRHASH - 1)) -#else -#define soap_hash_ptr(p) ((size_t)(((unsigned long)(p) >> 3) & (SOAP_PTRHASH-1))) -#endif - -#ifndef PALM_1 -static void soap_init_logs(struct soap*); -#endif -#ifdef SOAP_DEBUG -static void soap_close_logfile(struct soap*, int); -static void soap_set_logfile(struct soap*, int, const char*); -#endif - -#ifdef SOAP_MEM_DEBUG -static void soap_init_mht(struct soap*); -static void soap_free_mht(struct soap*); -static void soap_track_unlink(struct soap*, const void*); -#endif - -#ifndef PALM_2 -static int soap_set_error(struct soap*, const char*, const char*, const char*, const char*, int); -static int soap_copy_fault(struct soap*, const char*, const char*, const char*, const char*); -static int soap_getattrval(struct soap*, char*, size_t, soap_wchar); -#endif - -#ifndef PALM_1 -static void soap_free_ns(struct soap *soap); -static soap_wchar soap_char(struct soap*); -static soap_wchar soap_get_pi(struct soap*); -static int soap_isxdigit(int); -static void *fplugin(struct soap*, const char*); -static char *soap_get_http_body(struct soap*); -static size_t soap_count_attachments(struct soap *soap); -static int soap_try_connect_command(struct soap*, int http_command, const char *endpoint, const char *action); -#ifndef WITH_NOIDREF -static void soap_update_ptrs(struct soap*, char*, char*, char*, char*); -static int soap_has_copies(struct soap*, const char*, const char*); -static void soap_init_iht(struct soap*); -static void soap_free_iht(struct soap*); -static void soap_init_pht(struct soap*); -static void soap_free_pht(struct soap*); -#endif -#endif - -#ifndef WITH_LEAN -static const char *soap_set_validation_fault(struct soap*, const char*, const char*); -static int soap_isnumeric(struct soap*, const char*); -static struct soap_nlist *soap_push_ns(struct soap *soap, const char *id, const char *ns, short utilized); -static void soap_utilize_ns(struct soap *soap, const char *tag, size_t n); -#endif - -#ifndef WITH_LEANER -#ifndef PALM_1 -static struct soap_multipart *soap_new_multipart(struct soap*, struct soap_multipart**, struct soap_multipart**, char*, size_t); -static int soap_putdimefield(struct soap*, const char*, size_t); -static char *soap_getdimefield(struct soap*, size_t); -static void soap_select_mime_boundary(struct soap*); -static int soap_valid_mime_boundary(struct soap*); -static void soap_resolve_attachment(struct soap*, struct soap_multipart*); -#endif -#endif - -#ifdef WITH_GZIP -static int soap_getgziphdr(struct soap*); -#endif - -#ifdef WITH_OPENSSL -int soap_ssl_init_done = 0; - -static int ssl_auth_init(struct soap*); -static int ssl_verify_callback(int, X509_STORE_CTX*); -static int ssl_verify_callback_allow_expired_certificate(int, X509_STORE_CTX*); -static int ssl_password(char*, int, int, void *); -/* The callback below is included for future references: -static DH *ssl_tmp_dh(SSL*, int, int); -*/ -#endif - -#if !defined(WITH_NOHTTP) || !defined(WITH_LEANER) -#ifndef PALM_1 -static const char *soap_decode(char*, size_t, const char*, const char*); -#endif -#endif - -#ifndef WITH_NOHTTP -#ifndef PALM_1 -static soap_wchar soap_getchunkchar(struct soap*); -static const char *http_error(struct soap*, int); -static int http_get(struct soap*); -static int http_405(struct soap*); -static int http_post(struct soap*, const char*, const char*, int, const char*, const char*, size_t); -static int http_send_header(struct soap*, const char*); -static int http_post_header(struct soap*, const char*, const char*); -static int http_response(struct soap*, int, size_t); -static int http_parse(struct soap*); -static int http_parse_header(struct soap*, const char*, const char*); -#endif -#endif - -#ifndef WITH_NOIO - -#ifndef PALM_1 -static int fsend(struct soap*, const char*, size_t); -static size_t frecv(struct soap*, char*, size_t); -static int tcp_init(struct soap*); -static const char *tcp_error(struct soap*); -#ifndef WITH_IPV6 -static int tcp_gethost(struct soap*, const char *addr, struct in_addr *inaddr); -#endif -static SOAP_SOCKET tcp_connect(struct soap*, const char *endpoint, const char *host, int port); -static SOAP_SOCKET tcp_accept(struct soap*, SOAP_SOCKET, struct sockaddr*, int*); -static int tcp_select(struct soap*, SOAP_SOCKET, int, int); -static int tcp_disconnect(struct soap*); -static int tcp_closesocket(struct soap*, SOAP_SOCKET); -static int tcp_shutdownsocket(struct soap*, SOAP_SOCKET, int); -static const char *soap_strerror(struct soap*); -#endif - -#define SOAP_TCP_SELECT_RCV 0x1 -#define SOAP_TCP_SELECT_SND 0x2 -#define SOAP_TCP_SELECT_ERR 0x4 -#define SOAP_TCP_SELECT_ALL 0x7 - -#if defined(WIN32) - #define SOAP_SOCKBLOCK(fd) \ - { u_long blocking = 0; \ - ioctlsocket(fd, FIONBIO, &blocking); \ - } - #define SOAP_SOCKNONBLOCK(fd) \ - { u_long nonblocking = 1; \ - ioctlsocket(fd, FIONBIO, &nonblocking); \ - } -#elif defined(VXWORKS) - #define SOAP_SOCKBLOCK(fd) \ - { u_long blocking = 0; \ - ioctl(fd, FIONBIO, (int)(&blocking)); \ - } - #define SOAP_SOCKNONBLOCK(fd) \ - { u_long nonblocking = 1; \ - ioctl(fd, FIONBIO, (int)(&nonblocking)); \ - } -#elif defined(PALM) - #define SOAP_SOCKBLOCK(fd) fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0)&~O_NONBLOCK); - #define SOAP_SOCKNONBLOCK(fd) fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0)|O_NONBLOCK); -#elif defined(SYMBIAN) - #define SOAP_SOCKBLOCK(fd) \ - { long blocking = 0; \ - ioctl(fd, 0/*FIONBIO*/, &blocking); \ - } - #define SOAP_SOCKNONBLOCK(fd) \ - { long nonblocking = 1; \ - ioctl(fd, 0/*FIONBIO*/, &nonblocking); \ - } -#else - #define SOAP_SOCKBLOCK(fd) fcntl(fd, F_SETFL, fcntl(fd, F_GETFL)&~O_NONBLOCK); - #define SOAP_SOCKNONBLOCK(fd) fcntl(fd, F_SETFL, fcntl(fd, F_GETFL)|O_NONBLOCK); -#endif - -#endif - -#if defined(PALM) && !defined(PALM_2) -unsigned short errno; -#endif - -#ifndef PALM_1 -static const char soap_env1[42] = "http://schemas.xmlsoap.org/soap/envelope/"; -static const char soap_enc1[42] = "http://schemas.xmlsoap.org/soap/encoding/"; -static const char soap_env2[40] = "http://www.w3.org/2003/05/soap-envelope"; -static const char soap_enc2[40] = "http://www.w3.org/2003/05/soap-encoding"; -static const char soap_rpc[35] = "http://www.w3.org/2003/05/soap-rpc"; -#endif - -#ifndef PALM_1 -const struct soap_double_nan soap_double_nan = {0xFFFFFFFF, 0xFFFFFFFF}; -static const char soap_base64o[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -static const char soap_base64i[81] = "\76XXX\77\64\65\66\67\70\71\72\73\74\75XXXXXXX\00\01\02\03\04\05\06\07\10\11\12\13\14\15\16\17\20\21\22\23\24\25\26\27\30\31XXXXXX\32\33\34\35\36\37\40\41\42\43\44\45\46\47\50\51\52\53\54\55\56\57\60\61\62\63"; -#endif - -#ifndef WITH_LEAN -static const char soap_indent[11] = "\n\t\t\t\t\t\t\t\t\t"; -/* Alternative indentation form for SOAP_XML_INDENT: -static const char soap_indent[21] = "\n "; -*/ -#endif - -#ifndef SOAP_CANARY -# define SOAP_CANARY (0xC0DE) -#endif - -static const char soap_padding[4] = "\0\0\0"; -#define SOAP_STR_PADDING (soap_padding) -#define SOAP_STR_EOS (soap_padding) -#define SOAP_NON_NULL (soap_padding) - -#ifndef WITH_LEAN -static const struct soap_code_map html_entity_codes[] = /* entities for XHTML parsing */ -{ { 160, "nbsp" }, - { 161, "iexcl" }, - { 162, "cent" }, - { 163, "pound" }, - { 164, "curren" }, - { 165, "yen" }, - { 166, "brvbar" }, - { 167, "sect" }, - { 168, "uml" }, - { 169, "copy" }, - { 170, "ordf" }, - { 171, "laquo" }, - { 172, "not" }, - { 173, "shy" }, - { 174, "reg" }, - { 175, "macr" }, - { 176, "deg" }, - { 177, "plusmn" }, - { 178, "sup2" }, - { 179, "sup3" }, - { 180, "acute" }, - { 181, "micro" }, - { 182, "para" }, - { 183, "middot" }, - { 184, "cedil" }, - { 185, "sup1" }, - { 186, "ordm" }, - { 187, "raquo" }, - { 188, "frac14" }, - { 189, "frac12" }, - { 190, "frac34" }, - { 191, "iquest" }, - { 192, "Agrave" }, - { 193, "Aacute" }, - { 194, "Acirc" }, - { 195, "Atilde" }, - { 196, "Auml" }, - { 197, "Aring" }, - { 198, "AElig" }, - { 199, "Ccedil" }, - { 200, "Egrave" }, - { 201, "Eacute" }, - { 202, "Ecirc" }, - { 203, "Euml" }, - { 204, "Igrave" }, - { 205, "Iacute" }, - { 206, "Icirc" }, - { 207, "Iuml" }, - { 208, "ETH" }, - { 209, "Ntilde" }, - { 210, "Ograve" }, - { 211, "Oacute" }, - { 212, "Ocirc" }, - { 213, "Otilde" }, - { 214, "Ouml" }, - { 215, "times" }, - { 216, "Oslash" }, - { 217, "Ugrave" }, - { 218, "Uacute" }, - { 219, "Ucirc" }, - { 220, "Uuml" }, - { 221, "Yacute" }, - { 222, "THORN" }, - { 223, "szlig" }, - { 224, "agrave" }, - { 225, "aacute" }, - { 226, "acirc" }, - { 227, "atilde" }, - { 228, "auml" }, - { 229, "aring" }, - { 230, "aelig" }, - { 231, "ccedil" }, - { 232, "egrave" }, - { 233, "eacute" }, - { 234, "ecirc" }, - { 235, "euml" }, - { 236, "igrave" }, - { 237, "iacute" }, - { 238, "icirc" }, - { 239, "iuml" }, - { 240, "eth" }, - { 241, "ntilde" }, - { 242, "ograve" }, - { 243, "oacute" }, - { 244, "ocirc" }, - { 245, "otilde" }, - { 246, "ouml" }, - { 247, "divide" }, - { 248, "oslash" }, - { 249, "ugrave" }, - { 250, "uacute" }, - { 251, "ucirc" }, - { 252, "uuml" }, - { 253, "yacute" }, - { 254, "thorn" }, - { 255, "yuml" }, - { 0, NULL } -}; -#endif - -#ifndef WITH_NOIO -#ifndef WITH_LEAN -static const struct soap_code_map h_error_codes[] = -{ -#ifdef HOST_NOT_FOUND - { HOST_NOT_FOUND, "Host not found" }, -#endif -#ifdef TRY_AGAIN - { TRY_AGAIN, "Try Again" }, -#endif -#ifdef NO_RECOVERY - { NO_RECOVERY, "No Recovery" }, -#endif -#ifdef NO_DATA - { NO_DATA, "No Data" }, -#endif -#ifdef NO_ADDRESS - { NO_ADDRESS, "No Address" }, -#endif - { 0, NULL } -}; -#endif -#endif - -#ifndef WITH_NOHTTP -#ifndef WITH_LEAN -static const struct soap_code_map h_http_error_codes[] = -{ { 200, "OK" }, - { 201, "Created" }, - { 202, "Accepted" }, - { 203, "Non-Authoritative Information" }, - { 204, "No Content" }, - { 205, "Reset Content" }, - { 206, "Partial Content" }, - { 300, "Multiple Choices" }, - { 301, "Moved Permanently" }, - { 302, "Found" }, - { 303, "See Other" }, - { 304, "Not Modified" }, - { 305, "Use Proxy" }, - { 307, "Temporary Redirect" }, - { 400, "Bad Request" }, - { 401, "Unauthorized" }, - { 402, "Payment Required" }, - { 403, "Forbidden" }, - { 404, "Not Found" }, - { 405, "Method Not Allowed" }, - { 406, "Not Acceptable" }, - { 407, "Proxy Authentication Required" }, - { 408, "Request Time-out" }, - { 409, "Conflict" }, - { 410, "Gone" }, - { 411, "Length Required" }, - { 412, "Precondition Failed" }, - { 413, "Request Entity Too Large" }, - { 414, "Request-URI Too Large" }, - { 415, "Unsupported Media Type" }, - { 416, "Requested range not satisfiable" }, - { 417, "Expectation Failed" }, - { 500, "Internal Server Error" }, - { 501, "Not Implemented" }, - { 502, "Bad Gateway" }, - { 503, "Service Unavailable" }, - { 504, "Gateway Time-out" }, - { 505, "HTTP Version not supported" }, - { 0, NULL } -}; -#endif -#endif - -#ifdef WITH_OPENSSL -static const struct soap_code_map h_ssl_error_codes[] = -{ -#define _SSL_ERROR(e) { e, #e } - _SSL_ERROR(SSL_ERROR_SSL), - _SSL_ERROR(SSL_ERROR_ZERO_RETURN), - _SSL_ERROR(SSL_ERROR_WANT_READ), - _SSL_ERROR(SSL_ERROR_WANT_WRITE), - _SSL_ERROR(SSL_ERROR_WANT_CONNECT), - _SSL_ERROR(SSL_ERROR_WANT_X509_LOOKUP), - _SSL_ERROR(SSL_ERROR_SYSCALL), - { 0, NULL } -}; -#endif - -#ifndef WITH_LEANER -static const struct soap_code_map mime_codes[] = -{ { SOAP_MIME_7BIT, "7bit" }, - { SOAP_MIME_8BIT, "8bit" }, - { SOAP_MIME_BINARY, "binary" }, - { SOAP_MIME_QUOTED_PRINTABLE, "quoted-printable" }, - { SOAP_MIME_BASE64, "base64" }, - { SOAP_MIME_IETF_TOKEN, "ietf-token" }, - { SOAP_MIME_X_TOKEN, "x-token" }, - { 0, NULL } -}; -#endif - -#ifdef WIN32 -static int tcp_done = 0; -#endif - -#if defined(HP_UX) && defined(HAVE_GETHOSTBYNAME_R) -extern int h_errno; -#endif - -/******************************************************************************/ -#ifndef WITH_NOIO -#ifndef PALM_1 -static int -fsend(struct soap *soap, const char *s, size_t n) -{ register int nwritten, err; -#if defined(__cplusplus) && !defined(WITH_LEAN) && !defined(WITH_COMPAT) - if (soap->os) - { soap->os->write(s, (std::streamsize)n); - if (soap->os->good()) - return SOAP_OK; - soap->errnum = 0; - return SOAP_EOF; - } -#endif - while (n) - { if (soap_valid_socket(soap->socket)) - { -#ifndef WITH_LEAN - if (soap->send_timeout) - { for (;;) - { register int r; -#ifdef WITH_OPENSSL - if (soap->ssl) - r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_ALL, soap->send_timeout); - else -#endif - r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_SND | SOAP_TCP_SELECT_ERR, soap->send_timeout); - if (r > 0) - break; - if (!r) - return SOAP_EOF; - err = soap->errnum; - if (!err) - return soap->error; - if (err != SOAP_EINTR && err != SOAP_EAGAIN && err != SOAP_EWOULDBLOCK) - return SOAP_EOF; - } - } -#endif -#ifdef WITH_OPENSSL - if (soap->ssl) - nwritten = SSL_write(soap->ssl, s, (int)n); - else if (soap->bio) - nwritten = BIO_write(soap->bio, s, (int)n); - else -#endif -#ifndef WITH_LEAN - if ((soap->omode & SOAP_IO_UDP)) - { if (soap->peerlen) - nwritten = sendto(soap->socket, (char*)s, (SOAP_WINSOCKINT)n, soap->socket_flags, (struct sockaddr*)&soap->peer, (SOAP_WINSOCKINT)soap->peerlen); - else - nwritten = send(soap->socket, s, (SOAP_WINSOCKINT)n, soap->socket_flags); - /* retry and back-off algorithm */ - /* TODO: this is not very clear from specs so verify and limit conditions under which we should loop (e.g. ENOBUFS) */ - if (nwritten < 0) - { int udp_repeat; - int udp_delay; - if ((soap->connect_flags & SO_BROADCAST)) - udp_repeat = 3; /* SOAP-over-UDP MULTICAST_UDP_REPEAT - 1 */ - else - udp_repeat = 1; /* SOAP-over-UDP UNICAST_UDP_REPEAT - 1 */ - udp_delay = (soap_random % 201) + 50; /* UDP_MIN_DELAY .. UDP_MAX_DELAY */ - do - { tcp_select(soap, soap->socket, SOAP_TCP_SELECT_ERR, -1000 * udp_delay); - if (soap->peerlen) - nwritten = sendto(soap->socket, s, (SOAP_WINSOCKINT)n, soap->socket_flags, (struct sockaddr*)&soap->peer, (SOAP_WINSOCKINT)soap->peerlen); - else - nwritten = send(soap->socket, s, (SOAP_WINSOCKINT)n, soap->socket_flags); - udp_delay <<= 1; - if (udp_delay > 500) /* UDP_UPPER_DELAY */ - udp_delay = 500; - } - while (nwritten < 0 && --udp_repeat > 0); - } - } - else -#endif -#if !defined(PALM) && !defined(AS400) - nwritten = send(soap->socket, s, (int)n, soap->socket_flags); -#else - nwritten = send(soap->socket, (void*)s, n, soap->socket_flags); -#endif - if (nwritten <= 0) - { -#if defined(WITH_OPENSSL) || !defined(WITH_LEAN) - register int r = 0; -#endif - err = soap_socket_errno(soap->socket); -#ifdef WITH_OPENSSL - if (soap->ssl && (r = SSL_get_error(soap->ssl, nwritten)) != SSL_ERROR_NONE && r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE) - { soap->errnum = err; - return SOAP_EOF; - } -#endif - if (err == SOAP_EWOULDBLOCK || err == SOAP_EAGAIN) - { -#ifndef WITH_LEAN -#ifdef WITH_OPENSSL - if (soap->ssl && r == SSL_ERROR_WANT_READ) - r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, soap->send_timeout ? soap->send_timeout : -10000); - else - r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_SND | SOAP_TCP_SELECT_ERR, soap->send_timeout ? soap->send_timeout : -10000); -#else - r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_SND | SOAP_TCP_SELECT_ERR, soap->send_timeout ? soap->send_timeout : -10000); -#endif - if (!r && soap->send_timeout) - return SOAP_EOF; - if (r < 0 && soap->errnum != SOAP_EINTR) - return SOAP_EOF; -#endif - } - else if (err && err != SOAP_EINTR) - { soap->errnum = err; - return SOAP_EOF; - } - nwritten = 0; /* and call write() again */ - } - } - else - { -#ifdef WITH_FASTCGI - nwritten = fwrite((void*)s, 1, n, stdout); - fflush(stdout); -#else -#ifdef UNDER_CE - nwritten = fwrite(s, 1, n, soap->sendfd); -#else -#ifdef VXWORKS -#ifdef WMW_RPM_IO - if (soap->rpmreqid) - nwritten = (httpBlockPut(soap->rpmreqid, s, n) == 0) ? n : -1; - else -#endif - nwritten = fwrite(s, sizeof(char), n, fdopen(soap->sendfd, "w")); -#else -#ifdef WIN32 - nwritten = _write(soap->sendfd, s, (unsigned int)n); -#else - nwritten = write(soap->sendfd, s, (unsigned int)n); -#endif -#endif -#endif -#endif - if (nwritten <= 0) - { -#ifndef WITH_FASTCGI - err = soap_errno; -#else - err = EOF; -#endif - if (err && err != SOAP_EINTR && err != SOAP_EWOULDBLOCK && err != SOAP_EAGAIN) - { soap->errnum = err; - return SOAP_EOF; - } - nwritten = 0; /* and call write() again */ - } - } - n -= nwritten; - s += nwritten; - } - return SOAP_OK; -} -#endif -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_send_raw(struct soap *soap, const char *s, size_t n) -{ if (!n) - return SOAP_OK; - if (soap->mode & SOAP_IO_LENGTH) - { soap->count += n; -#ifndef WITH_LEANER - if (soap->fpreparesend && (soap->mode & SOAP_IO) != SOAP_IO_STORE) - return soap->error = soap->fpreparesend(soap, s, n); -#endif - return SOAP_OK; - } - if (soap->mode & SOAP_IO) - { register size_t i = SOAP_BUFLEN - soap->bufidx; - while (n >= i) - { memcpy(soap->buf + soap->bufidx, s, i); - soap->bufidx = SOAP_BUFLEN; - if (soap_flush(soap)) - return soap->error; - s += i; - n -= i; - i = SOAP_BUFLEN; - } - memcpy(soap->buf + soap->bufidx, s, n); - soap->bufidx += n; - return SOAP_OK; - } - return soap_flush_raw(soap, s, n); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_flush(struct soap *soap) -{ register size_t n = soap->bufidx; - if (n) - { soap->bufidx = 0; -#ifdef WITH_ZLIB - if (soap->mode & SOAP_ENC_ZLIB) - { soap->d_stream->next_in = (Byte*)soap->buf; - soap->d_stream->avail_in = (unsigned int)n; -#ifdef WITH_GZIP - soap->z_crc = crc32(soap->z_crc, (Byte*)soap->buf, (unsigned int)n); -#endif - do - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Deflating %u bytes\n", soap->d_stream->avail_in)); - if (deflate(soap->d_stream, Z_NO_FLUSH) != Z_OK) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unable to deflate: %s\n", soap->d_stream->msg?soap->d_stream->msg:SOAP_STR_EOS)); - return soap->error = SOAP_ZLIB_ERROR; - } - if (!soap->d_stream->avail_out) - { if (soap_flush_raw(soap, soap->z_buf, SOAP_BUFLEN)) - return soap->error; - soap->d_stream->next_out = (Byte*)soap->z_buf; - soap->d_stream->avail_out = SOAP_BUFLEN; - } - } while (soap->d_stream->avail_in); - } - else -#endif - return soap_flush_raw(soap, soap->buf, n); - } - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_flush_raw(struct soap *soap, const char *s, size_t n) -{ if ((soap->mode & SOAP_IO) == SOAP_IO_STORE) - { register char *t; - if (!(t = (char*)soap_push_block(soap, NULL, n))) - return soap->error = SOAP_EOM; - memcpy(t, s, n); -#ifndef WITH_LEANER - if (soap->fpreparesend) - return soap->error = soap->fpreparesend(soap, s, n); -#endif - return SOAP_OK; - } -#ifndef WITH_LEANER - if ((soap->mode & SOAP_IO) == SOAP_IO_CHUNK) - { char t[16]; - sprintf(t, "\r\n%lX\r\n" + (soap->chunksize ? 0 : 2), (unsigned long)n); - DBGMSG(SENT, t, strlen(t)); - if ((soap->error = soap->fsend(soap, t, strlen(t)))) - return soap->error; - soap->chunksize += n; - } - DBGMSG(SENT, s, n); -#endif - return soap->error = soap->fsend(soap, s, n); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_send(struct soap *soap, const char *s) -{ if (s) - return soap_send_raw(soap, s, strlen(s)); - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_send2(struct soap *soap, const char *s1, const char *s2) -{ if (soap_send(soap, s1)) - return soap->error; - return soap_send(soap, s2); -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_send3(struct soap *soap, const char *s1, const char *s2, const char *s3) -{ if (soap_send(soap, s1) - || soap_send(soap, s2)) - return soap->error; - return soap_send(soap, s3); -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIO -#ifndef PALM_1 -static size_t -frecv(struct soap *soap, char *s, size_t n) -{ register int r; -#ifndef WITH_LEAN - register int retries = 100; /* max 100 retries with non-blocking sockets */ -#endif - soap->errnum = 0; -#if defined(__cplusplus) && !defined(WITH_LEAN) && !defined(WITH_COMPAT) - if (soap->is) - { if (soap->is->good()) - return soap->is->read(s, (std::streamsize)n).gcount(); - return 0; - } -#endif - if (soap_valid_socket(soap->socket)) - { for (;;) - { -#ifdef WITH_OPENSSL - register int err = 0; -#endif -#ifndef WITH_LEAN -#ifdef WITH_OPENSSL - if (soap->recv_timeout && !soap->ssl) /* SSL: sockets are nonblocking */ -#else - if (soap->recv_timeout) -#endif - { for (;;) - { r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, soap->recv_timeout); - if (r > 0) - break; - if (!r) - return 0; - r = soap->errnum; - if (r != SOAP_EINTR && r != SOAP_EAGAIN && r != SOAP_EWOULDBLOCK) - return 0; - } - } -#endif -#ifdef WITH_OPENSSL - if (soap->ssl) - { r = SSL_read(soap->ssl, s, (int)n); - if (r > 0) - return (size_t)r; - err = SSL_get_error(soap->ssl, r); - if (err != SSL_ERROR_NONE && err != SSL_ERROR_WANT_READ && err != SSL_ERROR_WANT_WRITE) - return 0; - } - else if (soap->bio) - { r = BIO_read(soap->bio, s, (int)n); - if (r > 0) - return (size_t)r; - return 0; - } - else -#endif - { -#ifndef WITH_LEAN - if ((soap->omode & SOAP_IO_UDP)) - { SOAP_SOCKLEN_T k = (SOAP_SOCKLEN_T)sizeof(soap->peer); - memset((void*)&soap->peer, 0, sizeof(soap->peer)); - r = recvfrom(soap->socket, s, (SOAP_WINSOCKINT)n, soap->socket_flags, (struct sockaddr*)&soap->peer, &k); /* portability note: see SOAP_SOCKLEN_T definition in stdsoap2.h */ - soap->peerlen = (size_t)k; -#ifndef WITH_IPV6 - soap->ip = ntohl(soap->peer.sin_addr.s_addr); -#endif - } - else -#endif - r = recv(soap->socket, s, (int)n, soap->socket_flags); -#ifdef PALM - /* CycleSyncDisplay(curStatusMsg); */ -#endif - if (r >= 0) - return (size_t)r; - r = soap_socket_errno(soap->socket); - if (r != SOAP_EINTR && r != SOAP_EAGAIN && r != SOAP_EWOULDBLOCK) - { soap->errnum = r; - return 0; - } - } -#ifndef WITH_LEAN - { -#ifdef WITH_OPENSSL - if (soap->ssl && err == SSL_ERROR_WANT_WRITE) - r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_SND | SOAP_TCP_SELECT_ERR, soap->recv_timeout ? soap->recv_timeout : 5); - else - r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, soap->recv_timeout ? soap->recv_timeout : 5); -#else - r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, soap->recv_timeout ? soap->recv_timeout : 5); -#endif - if (!r && soap->recv_timeout) - return 0; - if (r < 0) - { r = soap->errnum; - if (r != SOAP_EINTR && r != SOAP_EAGAIN && r != SOAP_EWOULDBLOCK) - return 0; - } - if (retries-- <= 0) - return 0; - } -#endif -#ifdef PALM - r = soap_socket_errno(soap->socket); - if (r != SOAP_EINTR && retries-- <= 0) - { soap->errnum = r; - return 0; - } -#endif - } - } -#ifdef WITH_FASTCGI - return fread(s, 1, n, stdin); -#else -#ifdef UNDER_CE - return fread(s, 1, n, soap->recvfd); -#else -#ifdef WMW_RPM_IO - if (soap->rpmreqid) - r = httpBlockRead(soap->rpmreqid, s, n); - else -#endif -#ifdef WIN32 - r = _read(soap->recvfd, s, (unsigned int)n); -#else - r = read(soap->recvfd, s, (unsigned int)n); -#endif - if (r >= 0) - return (size_t)r; - soap->errnum = soap_errno; - return 0; -#endif -#endif -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOHTTP -#ifndef PALM_1 -static soap_wchar -soap_getchunkchar(struct soap *soap) -{ if (soap->bufidx < soap->buflen) - return soap->buf[soap->bufidx++]; - soap->bufidx = 0; - soap->buflen = soap->chunkbuflen = soap->frecv(soap, soap->buf, SOAP_BUFLEN); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Read %u bytes from socket %d\n", (unsigned int)soap->buflen, soap->socket)); - DBGMSG(RECV, soap->buf, soap->buflen); - if (soap->buflen) - return soap->buf[soap->bufidx++]; - return EOF; -} -#endif -#endif - -/******************************************************************************/ -#ifndef PALM_1 -static int -soap_isxdigit(int c) -{ return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_recv_raw(struct soap *soap) -{ register size_t ret; -#if !defined(WITH_LEANER) || defined(WITH_ZLIB) - register int r; -#endif -#ifdef WITH_ZLIB - if (soap->mode & SOAP_ENC_ZLIB) - { if (soap->d_stream->next_out == Z_NULL) - return EOF; - if (soap->d_stream->avail_in || !soap->d_stream->avail_out) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Inflating\n")); - soap->d_stream->next_out = (Byte*)soap->buf; - soap->d_stream->avail_out = SOAP_BUFLEN; - r = inflate(soap->d_stream, Z_NO_FLUSH); - if (r == Z_NEED_DICT && soap->z_dict) - r = inflateSetDictionary(soap->d_stream, (const Bytef*)soap->z_dict, soap->z_dict_len); - if (r == Z_OK || r == Z_STREAM_END) - { soap->bufidx = 0; - ret = soap->buflen = SOAP_BUFLEN - soap->d_stream->avail_out; - if (soap->zlib_in == SOAP_ZLIB_GZIP) - soap->z_crc = crc32(soap->z_crc, (Byte*)soap->buf, (unsigned int)ret); - if (r == Z_STREAM_END) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Inflated %lu->%lu bytes\n", soap->d_stream->total_in, soap->d_stream->total_out)); - soap->z_ratio_in = (float)soap->d_stream->total_in / (float)soap->d_stream->total_out; - soap->d_stream->next_out = Z_NULL; - } - if (ret) - { soap->count += ret; - DBGLOG(RECV, SOAP_MESSAGE(fdebug, "\n---- decompressed ----\n")); - DBGMSG(RECV, soap->buf, ret); - DBGLOG(RECV, SOAP_MESSAGE(fdebug, "\n----\n")); - return SOAP_OK; - } - } - else if (r != Z_BUF_ERROR) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Inflate error: %s\n", soap->d_stream->msg?soap->d_stream->msg:SOAP_STR_EOS)); - soap->d_stream->next_out = Z_NULL; - soap->error = SOAP_ZLIB_ERROR; - return EOF; - } - } -zlib_again: - if ((soap->mode & SOAP_IO) == SOAP_IO_CHUNK && !soap->chunksize) - { memcpy(soap->buf, soap->z_buf, SOAP_BUFLEN); - soap->buflen = soap->z_buflen; - } - DBGLOG(RECV, SOAP_MESSAGE(fdebug, "\n---- compressed ----\n")); - } -#endif -#ifndef WITH_NOHTTP - if ((soap->mode & SOAP_IO) == SOAP_IO_CHUNK) /* read HTTP chunked transfer */ - { for (;;) - { register soap_wchar c; - char *t, tmp[8]; - if (soap->chunksize) - { soap->buflen = ret = soap->frecv(soap, soap->buf, soap->chunksize > SOAP_BUFLEN ? SOAP_BUFLEN : soap->chunksize); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Getting chunk: read %u bytes\n", (unsigned int)ret)); - DBGMSG(RECV, soap->buf, ret); - soap->bufidx = 0; - soap->chunksize -= ret; - break; - } - t = tmp; - if (!soap->chunkbuflen) - { soap->chunkbuflen = ret = soap->frecv(soap, soap->buf, SOAP_BUFLEN); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Read %u bytes (chunked) from socket %d\n", (unsigned int)ret, soap->socket)); - DBGMSG(RECV, soap->buf, ret); - soap->bufidx = 0; - if (!ret) - return soap->ahead = EOF; - } - else - soap->bufidx = soap->buflen; - soap->buflen = soap->chunkbuflen; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Getting chunk size (idx=%u len=%u)\n", (unsigned int)soap->bufidx, (unsigned int)soap->buflen)); - while (!soap_isxdigit((int)(c = soap_getchunkchar(soap)))) - { if ((int)c == EOF) - return soap->ahead = EOF; - } - do - *t++ = (char)c; - while (soap_isxdigit((int)(c = soap_getchunkchar(soap))) && t - tmp < 7); - while ((int)c != EOF && c != '\n') - c = soap_getchunkchar(soap); - if ((int)c == EOF) - return soap->ahead = EOF; - *t = '\0'; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Chunk size = %s (hex)\n", tmp)); - soap->chunksize = soap_strtoul(tmp, &t, 16); - if (!soap->chunksize) - { soap->chunkbuflen = 0; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "End of chunked message\n")); - while ((int)c != EOF && c != '\n') - c = soap_getchunkchar(soap); - ret = 0; - soap->ahead = EOF; - break; - } - soap->buflen = soap->bufidx + soap->chunksize; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Moving buf len to idx=%u len=%u (%s)\n", (unsigned int)soap->bufidx, (unsigned int)soap->buflen, tmp)); - if (soap->buflen > soap->chunkbuflen) - { soap->buflen = soap->chunkbuflen; - soap->chunksize -= soap->buflen - soap->bufidx; - soap->chunkbuflen = 0; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Passed end of buffer for chunked HTTP (%u bytes left)\n", (unsigned int)(soap->buflen - soap->bufidx))); - } - else if (soap->chunkbuflen) - soap->chunksize = 0; - ret = soap->buflen - soap->bufidx; - if (ret) - break; - } - } - else -#endif - { soap->bufidx = 0; - soap->buflen = ret = soap->frecv(soap, soap->buf, SOAP_BUFLEN); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Read %u bytes from socket %d\n", (unsigned int)ret, soap->socket)); - DBGMSG(RECV, soap->buf, ret); - } -#ifndef WITH_LEANER - if (soap->fpreparerecv && (r = soap->fpreparerecv(soap, soap->buf, ret))) - return soap->error = r; -#endif -#ifdef WITH_ZLIB - if (soap->mode & SOAP_ENC_ZLIB) - { memcpy(soap->z_buf, soap->buf, SOAP_BUFLEN); - soap->d_stream->next_in = (Byte*)(soap->z_buf + soap->bufidx); - soap->d_stream->avail_in = (unsigned int)ret; - soap->d_stream->next_out = (Byte*)soap->buf; - soap->d_stream->avail_out = SOAP_BUFLEN; - r = inflate(soap->d_stream, Z_NO_FLUSH); - if (r == Z_NEED_DICT && soap->z_dict) - r = inflateSetDictionary(soap->d_stream, (const Bytef*)soap->z_dict, soap->z_dict_len); - if (r == Z_OK || r == Z_STREAM_END) - { soap->bufidx = 0; - soap->z_buflen = soap->buflen; - soap->buflen = SOAP_BUFLEN - soap->d_stream->avail_out; - if (soap->zlib_in == SOAP_ZLIB_GZIP) - soap->z_crc = crc32(soap->z_crc, (Byte*)soap->buf, (unsigned int)soap->buflen); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Inflated %u bytes\n", (unsigned int)soap->buflen)); - if (ret && !soap->buflen && r != Z_STREAM_END) - goto zlib_again; - ret = soap->buflen; - if (r == Z_STREAM_END) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Inflated total %lu->%lu bytes\n", soap->d_stream->total_in, soap->d_stream->total_out)); - soap->z_ratio_in = (float)soap->d_stream->total_in / (float)soap->d_stream->total_out; - soap->d_stream->next_out = Z_NULL; - } - DBGLOG(RECV, SOAP_MESSAGE(fdebug, "\n---- decompressed ----\n")); - DBGMSG(RECV, soap->buf, ret); - } - else - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unable to inflate: (%d) %s\n", r, soap->d_stream->msg?soap->d_stream->msg:SOAP_STR_EOS)); - soap->d_stream->next_out = Z_NULL; - soap->error = SOAP_ZLIB_ERROR; - return EOF; - } - } -#endif - soap->count += ret; - return !ret; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_recv(struct soap *soap) -{ -#ifndef WITH_LEANER - if (soap->mode & SOAP_ENC_DIME) - { if (soap->dime.buflen) - { char *s; - int i; - unsigned char tmp[12]; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "DIME hdr for chunked DIME is in buffer\n")); - soap->count += soap->dime.buflen - soap->buflen; - soap->buflen = soap->dime.buflen; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Skip padding (%ld bytes)\n", -(long)soap->dime.size&3)); - for (i = -(long)soap->dime.size&3; i > 0; i--) - { soap->bufidx++; - if (soap->bufidx >= soap->buflen) - if (soap_recv_raw(soap)) - return EOF; - } - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Get DIME hdr for next chunk\n")); - s = (char*)tmp; - for (i = 12; i > 0; i--) - { *s++ = soap->buf[soap->bufidx++]; - if (soap->bufidx >= soap->buflen) - if (soap_recv_raw(soap)) - return EOF; - } - soap->dime.flags = tmp[0] & 0x7; - soap->dime.size = ((size_t)tmp[8] << 24) | ((size_t)tmp[9] << 16) | ((size_t)tmp[10] << 8) | ((size_t)tmp[11]); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Get DIME chunk (%u bytes)\n", (unsigned int)soap->dime.size)); - if (soap->dime.flags & SOAP_DIME_CF) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "More chunking\n")); - soap->dime.chunksize = soap->dime.size; - if (soap->buflen - soap->bufidx >= soap->dime.size) - { soap->dime.buflen = soap->buflen; - soap->buflen = soap->bufidx + soap->dime.chunksize; - } - else - soap->dime.chunksize -= soap->buflen - soap->bufidx; - } - else - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Last chunk\n")); - soap->dime.buflen = 0; - soap->dime.chunksize = 0; - } - soap->count = soap->buflen - soap->bufidx; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "%u bytes remaining\n", (unsigned int)soap->count)); - return SOAP_OK; - } - if (soap->dime.chunksize) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Get next DIME hdr for chunked DIME (%u bytes chunk)\n", (unsigned int)soap->dime.chunksize)); - if (soap_recv_raw(soap)) - return EOF; - if (soap->buflen - soap->bufidx >= soap->dime.chunksize) - { soap->dime.buflen = soap->buflen; - soap->count -= soap->buflen - soap->bufidx - soap->dime.chunksize; - soap->buflen = soap->bufidx + soap->dime.chunksize; - } - else - soap->dime.chunksize -= soap->buflen - soap->bufidx; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "%lu bytes remaining, count=%u\n", (unsigned long)(soap->buflen-soap->bufidx), (unsigned int)soap->count)); - return SOAP_OK; - } - } -#endif - return soap_recv_raw(soap); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -soap_wchar -SOAP_FMAC2 -soap_getchar(struct soap *soap) -{ register soap_wchar c; - c = soap->ahead; - if (c) - { if (c != EOF) - soap->ahead = 0; - return c; - } - return soap_get1(soap); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -const struct soap_code_map* -SOAP_FMAC2 -soap_code(const struct soap_code_map *code_map, const char *str) -{ if (code_map && str) - { while (code_map->string) - { if (!strcmp(str, code_map->string)) /* case sensitive */ - return code_map; - code_map++; - } - } - return NULL; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -long -SOAP_FMAC2 -soap_code_int(const struct soap_code_map *code_map, const char *str, long other) -{ if (code_map) - { while (code_map->string) - { if (!soap_tag_cmp(str, code_map->string)) /* case insensitive */ - return code_map->code; - code_map++; - } - } - return other; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -const char* -SOAP_FMAC2 -soap_code_str(const struct soap_code_map *code_map, long code) -{ if (!code_map) - return NULL; - while (code_map->code != code && code_map->string) - code_map++; - return code_map->string; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -long -SOAP_FMAC2 -soap_code_bits(const struct soap_code_map *code_map, const char *str) -{ register long bits = 0; - if (code_map) - { while (str && *str) - { const struct soap_code_map *p; - for (p = code_map; p->string; p++) - { register size_t n = strlen(p->string); - if (!strncmp(p->string, str, n) && soap_blank(str[n])) - { bits |= p->code; - str += n; - while (*str > 0 && *str <= 32) - str++; - break; - } - } - if (!p->string) - return 0; - } - } - return bits; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -const char* -SOAP_FMAC2 -soap_code_list(struct soap *soap, const struct soap_code_map *code_map, long code) -{ register char *t = soap->tmpbuf; - if (code_map) - { while (code_map->string) - { if (code_map->code & code) - { register const char *s = code_map->string; - if (t != soap->tmpbuf) - *t++ = ' '; - while (*s && t < soap->tmpbuf + sizeof(soap->tmpbuf) - 1) - *t++ = *s++; - if (t == soap->tmpbuf + sizeof(soap->tmpbuf) - 1) - break; - } - code_map++; - } - } - *t = '\0'; - return soap->tmpbuf; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -static soap_wchar -soap_char(struct soap *soap) -{ char tmp[8]; - register int i; - register soap_wchar c; - register char *s = tmp; - for (i = 0; i < 7; i++) - { c = soap_get1(soap); - if (c == ';' || (int)c == EOF) - break; - *s++ = (char)c; - } - *s = '\0'; - if (*tmp == '#') - { if (tmp[1] == 'x' || tmp[1] == 'X') - return soap_strtol(tmp + 2, NULL, 16); - return atol(tmp + 1); - } - if (!strcmp(tmp, "lt")) - return '<'; - if (!strcmp(tmp, "gt")) - return '>'; - if (!strcmp(tmp, "amp")) - return '&'; - if (!strcmp(tmp, "quot")) - return '"'; - if (!strcmp(tmp, "apos")) - return '\''; -#ifndef WITH_LEAN - return (soap_wchar)soap_code_int(html_entity_codes, tmp, SOAP_UNKNOWN_CHAR); -#else - return SOAP_UNKNOWN_CHAR; /* use this to represent unknown code */ -#endif -} -#endif - -/******************************************************************************/ -#ifdef WITH_LEAN -#ifndef PALM_1 -soap_wchar -soap_get0(struct soap *soap) -{ if (soap->bufidx >= soap->buflen && soap_recv(soap)) - return EOF; - return (unsigned char)soap->buf[soap->bufidx]; -} -#endif -#endif - -/******************************************************************************/ -#ifdef WITH_LEAN -#ifndef PALM_1 -soap_wchar -soap_get1(struct soap *soap) -{ if (soap->bufidx >= soap->buflen && soap_recv(soap)) - return EOF; - return (unsigned char)soap->buf[soap->bufidx++]; -} -#endif -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -soap_wchar -SOAP_FMAC2 -soap_get(struct soap *soap) -{ register soap_wchar c; - c = soap->ahead; - if (c) - { if ((int)c != EOF) - soap->ahead = 0; - } - else - c = soap_get1(soap); - while ((int)c != EOF) - { if (soap->cdata) - { if (c == ']') - { c = soap_get1(soap); - if (c == ']') - { c = soap_get0(soap); - if (c == '>') - { soap->cdata = 0; - soap_get1(soap); - c = soap_get1(soap); - } - else - { soap_unget(soap, ']'); - return ']'; - } - } - else - { soap_revget1(soap); - return ']'; - } - } - else - return c; - } - switch (c) - { case '<': - do c = soap_get1(soap); - while (soap_blank(c)); - if (c == '!' || c == '?' || c == '%') - { register int k = 1; - if (c == '!') - { c = soap_get1(soap); - if (c == '[') - { do c = soap_get1(soap); - while ((int)c != EOF && c != '['); - if ((int)c == EOF) - break; - soap->cdata = 1; - c = soap_get1(soap); - continue; - } - if (c == '-' && (c = soap_get1(soap)) == '-') - { do - { c = soap_get1(soap); - if (c == '-' && (c = soap_get1(soap)) == '-') - break; - } while ((int)c != EOF); - } - } - else if (c == '?') - c = soap_get_pi(soap); - while ((int)c != EOF) - { if (c == '<') - k++; - else if (c == '>') - { if (--k <= 0) - break; - } - c = soap_get1(soap); - } - if ((int)c == EOF) - break; - c = soap_get1(soap); - continue; - } - if (c == '/') - return SOAP_TT; - soap_revget1(soap); - return SOAP_LT; - case '>': - return SOAP_GT; - case '"': - return SOAP_QT; - case '\'': - return SOAP_AP; - case '&': - return soap_char(soap) | 0x80000000; - } - break; - } - return c; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -static soap_wchar -soap_get_pi(struct soap *soap) -{ char buf[64]; - register char *s = buf; - register int i = sizeof(buf); - register soap_wchar c = soap_getchar(soap); - /* This is a quick way to parse XML PI and we could use a callback instead to - * enable applications to intercept processing instructions */ - while ((int)c != EOF && c != '?') - { if (--i > 0) - { if (soap_blank(c)) - c = ' '; - *s++ = (char)c; - } - c = soap_getchar(soap); - } - *s = '\0'; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "XML PI \n", buf)); - if (!strncmp(buf, "xml ", 4)) - { s = strstr(buf, " encoding="); - if (s && s[10]) - { if (!soap_tag_cmp(s + 11, "iso-8859-1*") - || !soap_tag_cmp(s + 11, "latin1*")) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Switching to latin1 encoding\n")); - soap->mode |= SOAP_ENC_LATIN; - } - else if (!soap_tag_cmp(s + 11, "utf-8*")) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Switching to utf-8 encoding\n")); - soap->mode &= ~SOAP_ENC_LATIN; - } - } - } - if ((int)c != EOF) - c = soap_getchar(soap); - return c; -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_move(struct soap *soap, long n) -{ DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Moving %ld bytes forward\n", (long)n)); - for (; n > 0; n--) - if ((int)soap_getchar(soap) == EOF) - return SOAP_EOF; - return SOAP_OK; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -SOAP_FMAC1 -size_t -SOAP_FMAC2 -soap_tell(struct soap *soap) -{ return soap->count - soap->buflen + soap->bufidx - (soap->ahead != 0); -} -#endif -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_pututf8(struct soap *soap, register unsigned long c) -{ char tmp[16]; - if (c < 0x80 && c > 0) - { *tmp = (char)c; - return soap_send_raw(soap, tmp, 1); - } -#ifndef WITH_LEAN - if (c >= 0x80) - { register char *t = tmp; - if (c < 0x0800) - *t++ = (char)(0xC0 | ((c >> 6) & 0x1F)); - else - { if (c < 0x010000) - *t++ = (char)(0xE0 | ((c >> 12) & 0x0F)); - else - { if (c < 0x200000) - *t++ = (char)(0xF0 | ((c >> 18) & 0x07)); - else - { if (c < 0x04000000) - *t++ = (char)(0xF8 | ((c >> 24) & 0x03)); - else - { *t++ = (char)(0xFC | ((c >> 30) & 0x01)); - *t++ = (char)(0x80 | ((c >> 24) & 0x3F)); - } - *t++ = (char)(0x80 | ((c >> 18) & 0x3F)); - } - *t++ = (char)(0x80 | ((c >> 12) & 0x3F)); - } - *t++ = (char)(0x80 | ((c >> 6) & 0x3F)); - } - *t++ = (char)(0x80 | (c & 0x3F)); - *t = '\0'; - } -#else - sprintf(tmp, "&#%lu;", c); -#endif - return soap_send(soap, tmp); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -soap_wchar -SOAP_FMAC2 -soap_getutf8(struct soap *soap) -{ register soap_wchar c, c1, c2, c3, c4; - c = soap->ahead; - if (c > 0x7F) - { soap->ahead = 0; - return c; - } - c = soap_get(soap); - if (c < 0x80 || (soap->mode & SOAP_ENC_LATIN)) - return c; - c1 = soap_get1(soap); - if (c1 < 0x80) - { soap_revget1(soap); /* doesn't look like this is UTF8 */ - return c; - } - c1 &= 0x3F; - if (c < 0xE0) - return ((soap_wchar)(c & 0x1F) << 6) | c1; - c2 = (soap_wchar)soap_get1(soap) & 0x3F; - if (c < 0xF0) - return ((soap_wchar)(c & 0x0F) << 12) | (c1 << 6) | c2; - c3 = (soap_wchar)soap_get1(soap) & 0x3F; - if (c < 0xF8) - return ((soap_wchar)(c & 0x07) << 18) | (c1 << 12) | (c2 << 6) | c3; - c4 = (soap_wchar)soap_get1(soap) & 0x3F; - if (c < 0xFC) - return ((soap_wchar)(c & 0x03) << 24) | (c1 << 18) | (c2 << 12) | (c3 << 6) | c4; - return ((soap_wchar)(c & 0x01) << 30) | (c1 << 24) | (c2 << 18) | (c3 << 12) | (c4 << 6) | (soap_wchar)(soap_get1(soap) & 0x3F); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_puthex(struct soap *soap, const unsigned char *s, int n) -{ char d[2]; - register int i; -#ifdef WITH_DOM - if ((soap->mode & SOAP_XML_DOM) && soap->dom) - { if (!(soap->dom->data = soap_s2hex(soap, s, NULL, n))) - return soap->error; - return SOAP_OK; - } -#endif - for (i = 0; i < n; i++) - { register int m = *s++; - d[0] = (char)((m >> 4) + (m > 159 ? '7' : '0')); - m &= 0x0F; - d[1] = (char)(m + (m > 9 ? '7' : '0')); - if (soap_send_raw(soap, d, 2)) - return soap->error; - } - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -unsigned char* -SOAP_FMAC2 -soap_gethex(struct soap *soap, int *n) -{ -#ifdef WITH_DOM - if ((soap->mode & SOAP_XML_DOM) && soap->dom) - { soap->dom->data = soap_string_in(soap, 0, -1, -1); - return (unsigned char*)soap_hex2s(soap, soap->dom->data, NULL, 0, n); - } -#endif -#ifdef WITH_FAST - soap->labidx = 0; - for (;;) - { register char *s; - register size_t i, k; - if (soap_append_lab(soap, NULL, 0)) - return NULL; - s = soap->labbuf + soap->labidx; - k = soap->lablen - soap->labidx; - soap->labidx = soap->lablen; - for (i = 0; i < k; i++) - { register char d1, d2; - register soap_wchar c; - c = soap_get(soap); - if (soap_isxdigit(c)) - { d1 = (char)c; - c = soap_get(soap); - if (soap_isxdigit(c)) - d2 = (char)c; - else - { soap->error = SOAP_TYPE; - return NULL; - } - } - else - { unsigned char *p; - soap_unget(soap, c); - if (n) - *n = (int)(soap->lablen + i - k); - p = (unsigned char*)soap_malloc(soap, soap->lablen + i - k); - if (p) - memcpy(p, soap->labbuf, soap->lablen + i - k); - return p; - } - *s++ = ((d1 >= 'A' ? (d1 & 0x7) + 9 : d1 - '0') << 4) + (d2 >= 'A' ? (d2 & 0x7) + 9 : d2 - '0'); - } - } -#else - if (soap_new_block(soap) == NULL) - return NULL; - for (;;) - { register int i; - register char *s = (char*)soap_push_block(soap, NULL, SOAP_BLKLEN); - if (!s) - { soap_end_block(soap, NULL); - return NULL; - } - for (i = 0; i < SOAP_BLKLEN; i++) - { register char d1, d2; - register soap_wchar c = soap_get(soap); - if (soap_isxdigit(c)) - { d1 = (char)c; - c = soap_get(soap); - if (soap_isxdigit(c)) - d2 = (char)c; - else - { soap_end_block(soap, NULL); - soap->error = SOAP_TYPE; - return NULL; - } - } - else - { unsigned char *p; - soap_unget(soap, c); - if (n) - *n = (int)soap_size_block(soap, NULL, i); - p = (unsigned char*)soap_save_block(soap, NULL, 0); - return p; - } - *s++ = ((d1 >= 'A' ? (d1 & 0x7) + 9 : d1 - '0') << 4) + (d2 >= 'A' ? (d2 & 0x7) + 9 : d2 - '0'); - } - } -#endif -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_putbase64(struct soap *soap, const unsigned char *s, int n) -{ register int i; - register unsigned long m; - char d[4]; - if (!s) - return SOAP_OK; -#ifdef WITH_DOM - if ((soap->mode & SOAP_XML_DOM) && soap->dom) - { if (!(soap->dom->data = soap_s2base64(soap, s, NULL, n))) - return soap->error; - return SOAP_OK; - } -#endif - for (; n > 2; n -= 3, s += 3) - { m = s[0]; - m = (m << 8) | s[1]; - m = (m << 8) | s[2]; - for (i = 4; i > 0; m >>= 6) - d[--i] = soap_base64o[m & 0x3F]; - if (soap_send_raw(soap, d, 4)) - return soap->error; - } - if (n > 0) - { m = 0; - for (i = 0; i < n; i++) - m = (m << 8) | *s++; - for (; i < 3; i++) - m <<= 8; - for (i++; i > 0; m >>= 6) - d[--i] = soap_base64o[m & 0x3F]; - for (i = 3; i > n; i--) - d[i] = '='; - if (soap_send_raw(soap, d, 4)) - return soap->error; - } - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -unsigned char* -SOAP_FMAC2 -soap_getbase64(struct soap *soap, int *n, int malloc_flag) -{ -#ifdef WITH_DOM - if ((soap->mode & SOAP_XML_DOM) && soap->dom) - { soap->dom->data = soap_string_in(soap, 0, -1, -1); - return (unsigned char*)soap_base642s(soap, soap->dom->data, NULL, 0, n); - } -#endif -#ifdef WITH_FAST - soap->labidx = 0; - for (;;) - { register size_t i, k; - register char *s; - if (soap_append_lab(soap, NULL, 2)) - return NULL; - s = soap->labbuf + soap->labidx; - k = soap->lablen - soap->labidx; - soap->labidx = 3 * (soap->lablen / 3); - if (!s) - return NULL; - if (k > 2) - { for (i = 0; i < k - 2; i += 3) - { register unsigned long m = 0; - register int j = 0; - do - { register soap_wchar c = soap_get(soap); - if (c == '=' || c < 0) - { unsigned char *p; - switch (j) - { case 2: - *s++ = (char)((m >> 4) & 0xFF); - i++; - break; - case 3: - *s++ = (char)((m >> 10) & 0xFF); - *s++ = (char)((m >> 2) & 0xFF); - i += 2; - } - if (n) - *n = (int)(soap->lablen + i - k); - p = (unsigned char*)soap_malloc(soap, soap->lablen + i - k); - if (p) - memcpy(p, soap->labbuf, soap->lablen + i - k); - if (c >= 0) - { while ((int)((c = soap_get(soap)) != EOF) && c != SOAP_LT && c != SOAP_TT) - ; - } - soap_unget(soap, c); - return p; - } - c -= '+'; - if (c >= 0 && c <= 79) - { register int b = soap_base64i[c]; - if (b >= 64) - { soap->error = SOAP_TYPE; - return NULL; - } - m = (m << 6) + b; - j++; - } - else if (!soap_blank(c + '+')) - { soap->error = SOAP_TYPE; - return NULL; - } - } while (j < 4); - *s++ = (char)((m >> 16) & 0xFF); - *s++ = (char)((m >> 8) & 0xFF); - *s++ = (char)(m & 0xFF); - } - } - } -#else - if (soap_new_block(soap) == NULL) - return NULL; - for (;;) - { register int i; - register char *s = (char*)soap_push_block(soap, NULL, 3 * SOAP_BLKLEN); /* must be multiple of 3 */ - if (!s) - { soap_end_block(soap, NULL); - return NULL; - } - for (i = 0; i < SOAP_BLKLEN; i++) - { register unsigned long m = 0; - register int j = 0; - do - { register soap_wchar c = soap_get(soap); - if (c == '=' || c < 0) - { unsigned char *p; - i *= 3; - switch (j) - { case 2: - *s++ = (char)((m >> 4) & 0xFF); - i++; - break; - case 3: - *s++ = (char)((m >> 10) & 0xFF); - *s++ = (char)((m >> 2) & 0xFF); - i += 2; - } - if (n) - *n = (int)soap_size_block(soap, NULL, i); - p = (unsigned char*)soap_save_block(soap, NULL, 0); - if (c >= 0) - { while ((int)((c = soap_get(soap)) != EOF) && c != SOAP_LT && c != SOAP_TT) - ; - } - soap_unget(soap, c); - return p; - } - c -= '+'; - if (c >= 0 && c <= 79) - { int b = soap_base64i[c]; - if (b >= 64) - { soap->error = SOAP_TYPE; - return NULL; - } - m = (m << 6) + b; - j++; - } - else if (!soap_blank(c)) - { soap->error = SOAP_TYPE; - return NULL; - } - } while (j < 4); - *s++ = (char)((m >> 16) & 0xFF); - *s++ = (char)((m >> 8) & 0xFF); - *s++ = (char)(m & 0xFF); - } - } -#endif -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_xop_forward(struct soap *soap, unsigned char **ptr, int *size, char **id, char **type, char **options) -{ /* Check MTOM xop:Include element (within hex/base64Binary) */ - /* TODO: this code to be obsoleted with new import/xop.h conventions */ - int body = soap->body; /* should save type too? */ - if (!soap_peek_element(soap)) - { if (!soap_element_begin_in(soap, "xop:Include", 0, NULL) && *soap->href) - { if (soap_dime_forward(soap, ptr, size, id, type, options)) - return soap->error; - } - if (soap->body && soap_element_end_in(soap, NULL)) - return soap->error; - } - soap->body = body; - return SOAP_OK; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_dime_forward(struct soap *soap, unsigned char **ptr, int *size, char **id, char **type, char **options) -{ struct soap_xlist *xp; - *ptr = NULL; - *size = 0; - *id = NULL; - *type = NULL; - *options = NULL; - if (!*soap->href) - return SOAP_OK; - *id = soap_strdup(soap, soap->href); - xp = (struct soap_xlist*)SOAP_MALLOC(soap, sizeof(struct soap_xlist)); - if (!xp) - return soap->error = SOAP_EOM; - xp->next = soap->xlist; - xp->ptr = ptr; - xp->size = size; - xp->id = *id; - xp->type = type; - xp->options = options; - soap->xlist = xp; - return SOAP_OK; -} -#endif -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -char * -SOAP_FMAC2 -soap_strdup(struct soap *soap, const char *s) -{ char *t = NULL; - if (s && (t = (char*)soap_malloc(soap, strlen(s) + 1))) - strcpy(t, s); - return t; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -wchar_t * -SOAP_FMAC2 -soap_wstrdup(struct soap *soap, const wchar_t *s) -{ wchar_t *t = NULL; - if (s) - { size_t n = 0; - while (s[n]) - n++; - if ((t = (wchar_t*)soap_malloc(soap, sizeof(wchar_t)*(n+1)))) - memcpy(t, s, sizeof(wchar_t)*(n+1)); - } - return t; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -struct soap_blist* -SOAP_FMAC2 -soap_new_block(struct soap *soap) -{ struct soap_blist *p; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "New block sequence (prev=%p)\n", soap->blist)); - if (!(p = (struct soap_blist*)SOAP_MALLOC(soap, sizeof(struct soap_blist)))) - { soap->error = SOAP_EOM; - return NULL; - } - p->next = soap->blist; - p->ptr = NULL; - p->size = 0; - soap->blist = p; - return p; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -void* -SOAP_FMAC2 -soap_push_block(struct soap *soap, struct soap_blist *b, size_t n) -{ char *p; - if (!b) - b = soap->blist; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Push block of %u bytes (%u bytes total)\n", (unsigned int)n, (unsigned int)b->size + (unsigned int)n)); - if (!(p = (char*)SOAP_MALLOC(soap, n + sizeof(char*) + sizeof(size_t)))) - { soap->error = SOAP_EOM; - return NULL; - } - *(char**)p = b->ptr; - *(size_t*)(p + sizeof(char*)) = n; - b->ptr = p; - b->size += n; - return p + sizeof(char*) + sizeof(size_t); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_pop_block(struct soap *soap, struct soap_blist *b) -{ char *p; - if (!b) - b = soap->blist; - if (!b->ptr) - return; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Pop block\n")); - p = b->ptr; - b->size -= *(size_t*)(p + sizeof(char*)); - b->ptr = *(char**)p; - SOAP_FREE(soap, p); -} -#endif - -/******************************************************************************/ -#ifndef WITH_NOIDREF -#ifndef PALM_1 -static void -soap_update_ptrs(struct soap *soap, char *start, char *end, char *p1, char *p2) -{ int i; - register struct soap_ilist *ip = NULL; - register struct soap_flist *fp = NULL; -#ifndef WITH_LEANER - register struct soap_xlist *xp = NULL; -#endif - register void *p, **q; - for (i = 0; i < SOAP_IDHASH; i++) - { for (ip = soap->iht[i]; ip; ip = ip->next) - { if (ip->ptr && (char*)ip->ptr >= start && (char*)ip->ptr < end) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Update id='%s' %p -> %p\n", ip->id, ip->ptr, (char*)ip->ptr + (p1-p2))); - ip->ptr = (char*)ip->ptr + (p1-p2); - } - for (q = &ip->link; q; q = (void**)p) - { p = *q; - if (p && (char*)p >= start && (char*)p < end) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Link update id='%s' %p\n", ip->id, p)); - *q = (char*)p + (p1-p2); - } - } - for (q = &ip->copy; q; q = (void**)p) - { p = *q; - if (p && (char*)p >= start && (char*)p < end) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copy chain update id='%s' %p\n", ip->id, p)); - *q = (char*)p + (p1-p2); - } - } - for (fp = ip->flist; fp; fp = fp->next) - { if ((char*)fp->ptr >= start && (char*)fp->ptr < end) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copy list update id='%s' %p\n", ip->id, fp)); - fp->ptr = (char*)fp->ptr + (p1-p2); - } - } - } - } -#ifndef WITH_LEANER - for (xp = soap->xlist; xp; xp = xp->next) - { if (xp->ptr && (char*)xp->ptr >= start && (char*)xp->ptr < end) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Update id='%s' %p -> %p\n", xp->id?xp->id:SOAP_STR_EOS, xp->ptr, (char*)xp->ptr + (p1-p2))); - xp->ptr = (unsigned char**)((char*)xp->ptr + (p1-p2)); - xp->size = (int*)((char*)xp->size + (p1-p2)); - xp->type = (char**)((char*)xp->type + (p1-p2)); - xp->options = (char**)((char*)xp->options + (p1-p2)); - } - } -#endif -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIDREF -#ifndef PALM_1 -static int -soap_has_copies(struct soap *soap, register const char *start, register const char *end) -{ register int i; - register struct soap_ilist *ip = NULL; - register struct soap_flist *fp = NULL; - register const char *p; - for (i = 0; i < SOAP_IDHASH; i++) - { for (ip = soap->iht[i]; ip; ip = ip->next) - { for (p = (const char*)ip->copy; p; p = *(const char**)p) - if (p >= start && p < end) - return SOAP_ERR; - for (fp = ip->flist; fp; fp = fp->next) - if ((const char*)fp->ptr >= start && (const char*)fp->ptr < end) - return SOAP_ERR; - } - } - return SOAP_OK; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIDREF -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_resolve(struct soap *soap) -{ register int i; - register struct soap_ilist *ip = NULL; - register struct soap_flist *fp = NULL; - short flag; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Resolving forwarded data\n")); - for (i = 0; i < SOAP_IDHASH; i++) - { for (ip = soap->iht[i]; ip; ip = ip->next) - { if (ip->ptr) - { register void *p, **q, *r; - q = (void**)ip->link; - ip->link = NULL; - r = ip->ptr; - DBGLOG(TEST, if (q) SOAP_MESSAGE(fdebug, "Traversing link chain to resolve id='%s'\n", ip->id)); - while (q) - { p = *q; - *q = r; - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "... link %p -> %p\n", q, r)); - q = (void**)p; - } - } - else if (*ip->id == '#') - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Missing data for id='%s'\n", ip->id)); - strcpy(soap->id, ip->id + 1); - return soap->error = SOAP_MISSING_ID; - } - } - } - do - { flag = 0; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Resolution phase\n")); - for (i = 0; i < SOAP_IDHASH; i++) - { for (ip = soap->iht[i]; ip; ip = ip->next) - { if (ip->ptr && !soap_has_copies(soap, (const char*)ip->ptr, (const char*)ip->ptr + ip->size)) - { if (ip->copy) - { register void *p, **q = (void**)ip->copy; - DBGLOG(TEST, if (q) SOAP_MESSAGE(fdebug, "Traversing copy chain to resolve id='%s'\n", ip->id)); - ip->copy = NULL; - do - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "... copy %p -> %p (%u bytes)\n", ip->ptr, q, (unsigned int)ip->size)); - p = *q; - memcpy(q, ip->ptr, ip->size); - q = (void**)p; - } while (q); - flag = 1; - } - for (fp = ip->flist; fp; fp = ip->flist) - { register unsigned int k = fp->level; - register void *p = ip->ptr; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Resolving forwarded data type=%d location=%p level=%u,%u id='%s'\n", ip->type, p, ip->level, fp->level, ip->id)); - while (ip->level < k) - { register void **q = (void**)soap_malloc(soap, sizeof(void*)); - if (!q) - return soap->error; - *q = p; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Descending one level, new location=%p holds=%p...\n", q, *q)); - p = (void*)q; - k--; - } - if (fp->fcopy) - fp->fcopy(soap, ip->type, fp->type, fp->ptr, fp->len, p, ip->size); - else - soap_fcopy(soap, ip->type, fp->type, fp->ptr, fp->len, p, ip->size); - ip->flist = fp->next; - SOAP_FREE(soap, fp); - flag = 1; - } - } - } - } - } while (flag); -#ifdef SOAP_DEBUG - for (i = 0; i < SOAP_IDHASH; i++) - { for (ip = soap->iht[i]; ip; ip = ip->next) - { if (ip->copy || ip->flist) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Resolution error: forwarded data for id='%s' could not be propagated, please report this problem to the developers\n", ip->id)); - } - } - } -#endif - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Resolution done\n")); - return SOAP_OK; -} -#endif -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -size_t -SOAP_FMAC2 -soap_size_block(struct soap *soap, struct soap_blist *b, size_t n) -{ if (!b) - b = soap->blist; - if (b->ptr) - { b->size -= *(size_t*)(b->ptr + sizeof(char*)) - n; - *(size_t*)(b->ptr + sizeof(char*)) = n; - } - return b->size; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -char* -SOAP_FMAC2 -soap_first_block(struct soap *soap, struct soap_blist *b) -{ char *p, *q, *r; - if (!b) - b = soap->blist; - p = b->ptr; - if (!p) - return NULL; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "First block\n")); - r = NULL; - do - { q = *(char**)p; - *(char**)p = r; - r = p; - p = q; - } while (p); - b->ptr = r; - return r + sizeof(char*) + sizeof(size_t); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -char* -SOAP_FMAC2 -soap_next_block(struct soap *soap, struct soap_blist *b) -{ char *p; - if (!b) - b = soap->blist; - p = b->ptr; - if (p) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Next block\n")); - b->ptr = *(char**)p; - SOAP_FREE(soap, p); - if (b->ptr) - return b->ptr + sizeof(char*) + sizeof(size_t); - } - return NULL; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -size_t -SOAP_FMAC2 -soap_block_size(struct soap *soap, struct soap_blist *b) -{ if (!b) - b = soap->blist; - return *(size_t*)(b->ptr + sizeof(char*)); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_end_block(struct soap *soap, struct soap_blist *b) -{ char *p, *q; - if (!b) - b = soap->blist; - if (b) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "End of block sequence, free all remaining blocks\n")); - for (p = b->ptr; p; p = q) - { q = *(char**)p; - SOAP_FREE(soap, p); - } - if (soap->blist == b) - soap->blist = b->next; - else - { struct soap_blist *bp; - for (bp = soap->blist; bp; bp = bp->next) - { if (bp->next == b) - { bp->next = b->next; - break; - } - } - } - SOAP_FREE(soap, b); - } - DBGLOG(TEST, if (soap->blist) SOAP_MESSAGE(fdebug, "Restore previous block sequence\n")); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -char* -SOAP_FMAC2 -soap_save_block(struct soap *soap, struct soap_blist *b, char *p, int flag) -{ register size_t n; - register char *q, *s; - if (!b) - b = soap->blist; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Save all blocks in contiguous memory space of %u bytes (%p->%p)\n", (unsigned int)b->size, b->ptr, p)); - if (b->size) - { if (!p) - p = (char*)soap_malloc(soap, b->size); - if (p) - { for (s = p, q = soap_first_block(soap, b); q; q = soap_next_block(soap, b)) - { n = soap_block_size(soap, b); -#ifndef WITH_NOIDREF - if (flag) - soap_update_ptrs(soap, q, q + n, s, q); -#endif - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copy %u bytes from %p to %p\n", (unsigned int)n, q, s)); - memcpy(s, q, n); - s += n; - } - } - else - soap->error = SOAP_EOM; - } - soap_end_block(soap, b); - return p; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -char * -SOAP_FMAC2 -soap_putsize(struct soap *soap, const char *type, int size) -{ return soap_putsizes(soap, type, &size, 1); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -char * -SOAP_FMAC2 -soap_putsizes(struct soap *soap, const char *type, const int *size, int dim) -{ return soap_putsizesoffsets(soap, type, size, NULL, dim); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -char * -SOAP_FMAC2 -soap_putsizesoffsets(struct soap *soap, const char *type, const int *size, const int *offset, int dim) -{ int i; - if (!type) - return NULL; - if (soap->version == 2) - { sprintf(soap->type, "%s[%d", type, size[0]); - for (i = 1; i < dim; i++) - sprintf(soap->type + strlen(soap->type), " %d", size[i]); - } - else - { if (offset) - { sprintf(soap->type, "%s[%d", type, size[0] + offset[0]); - for (i = 1; i < dim; i++) - sprintf(soap->type + strlen(soap->type), ",%d", size[i] + offset[i]); - } - else - { sprintf(soap->type, "%s[%d", type, size[0]); - for (i = 1; i < dim; i++) - sprintf(soap->type + strlen(soap->type), ",%d", size[i]); - } - strcat(soap->type, "]"); - } - return soap->type; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -char * -SOAP_FMAC2 -soap_putoffset(struct soap *soap, int offset) -{ return soap_putoffsets(soap, &offset, 1); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -char * -SOAP_FMAC2 -soap_putoffsets(struct soap *soap, const int *offset, int dim) -{ register int i; - sprintf(soap->arrayOffset, "[%d", offset[0]); - for (i = 1; i < dim; i++) - sprintf(soap->arrayOffset + strlen(soap->arrayOffset), ",%d", offset[i]); - strcat(soap->arrayOffset, "]"); - return soap->arrayOffset; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_size(const int *size, int dim) -{ register int i, n = size[0]; - for (i = 1; i < dim; i++) - n *= size[i]; - return n; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_getoffsets(const char *attr, const int *size, int *offset, int dim) -{ register int i, j = 0; - if (offset) - for (i = 0; i < dim && attr && *attr; i++) - { attr++; - j *= size[i]; - j += offset[i] = (int)atol(attr); - attr = strchr(attr, ','); - } - else - for (i = 0; i < dim && attr && *attr; i++) - { attr++; - j *= size[i]; - j += (int)atol(attr); - attr = strchr(attr, ','); - } - return j; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_getsize(const char *attr1, const char *attr2, int *j) -{ register int n, k; - char *s; - *j = 0; - if (!*attr1) - return -1; - if (*attr1 == '[') - attr1++; - n = 1; - for (;;) - { k = (int)soap_strtol(attr1, &s, 10); - n *= k; - if (k < 0 || n > SOAP_MAXARRAYSIZE || s == attr1) - return -1; - attr1 = strchr(s, ','); - if (!attr1) - attr1 = strchr(s, ' '); - if (attr2 && *attr2) - { attr2++; - *j *= k; - k = (int)soap_strtol(attr2, &s, 10); - *j += k; - if (k < 0) - return -1; - attr2 = s; - } - if (!attr1) - break; - attr1++; - } - return n - *j; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_getsizes(const char *attr, int *size, int dim) -{ register int i, k, n; - if (!*attr) - return -1; - i = (int)strlen(attr); - n = 1; - do - { for (i = i-1; i >= 0; i--) - if (attr[i] == '[' || attr[i] == ',' || attr[i] == ' ') - break; - k = (int)atol(attr + i + 1); - n *= size[--dim] = k; - if (k < 0 || n > SOAP_MAXARRAYSIZE) - return -1; - } while (i >= 0 && attr[i] != '['); - return n; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_getposition(const char *attr, int *pos) -{ register int i, n; - if (!*attr) - return -1; - n = 0; - i = 1; - do - { pos[n++] = (int)atol(attr + i); - while (attr[i] && attr[i] != ',' && attr[i] != ']') - i++; - if (attr[i] == ',') - i++; - } while (n < SOAP_MAXDIMS && attr[i] && attr[i] != ']'); - return n; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -struct soap_nlist * -SOAP_FMAC2 -soap_push_namespace(struct soap *soap, const char *id, const char *ns) -{ register struct soap_nlist *np; - register struct Namespace *p; - register short i = -1; - register size_t n, k; - n = strlen(id); - k = strlen(ns) + 1; - p = soap->local_namespaces; - if (p) - { for (i = 0; p->id; p++, i++) - { if (p->ns && !strcmp(ns, p->ns)) - { if (p->out) - { SOAP_FREE(soap, p->out); - p->out = NULL; - } - break; - } - if (p->out) - { if (!strcmp(ns, p->out)) - break; - } - else if (p->in) - { if (!soap_tag_cmp(ns, p->in)) - { if ((p->out = (char*)SOAP_MALLOC(soap, k))) - strcpy(p->out, ns); - break; - } - } - } - if (!p || !p->id) - i = -1; - } - if (i >= 0) - k = 0; - np = (struct soap_nlist*)SOAP_MALLOC(soap, sizeof(struct soap_nlist) + n + k); - if (!np) - { soap->error = SOAP_EOM; - return NULL; - } - np->next = soap->nlist; - soap->nlist = np; - np->level = soap->level; - np->index = i; - strcpy(np->id, id); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Push namespace binding (level=%u) '%s' '%s'\n", soap->level, id, ns)); - if (i < 0) - { np->ns = strcpy(np->id + n + 1, ns); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Push NOT OK: no match found for '%s' in namespace mapping table (added to stack anyway)\n", ns)); - } - else - { np->ns = NULL; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Push OK ('%s' matches '%s' in namespace table)\n", id, p->id)); - } - return np; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_pop_namespace(struct soap *soap) -{ register struct soap_nlist *np, *nq; - for (np = soap->nlist; np && np->level >= soap->level; np = nq) - { nq = np->next; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Pop namespace binding (level=%u) '%s'\n", soap->level, np->id)); - SOAP_FREE(soap, np); - } - soap->nlist = np; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_match_namespace(struct soap *soap, const char *id1, const char *id2, size_t n1, size_t n2) -{ register struct soap_nlist *np = soap->nlist; - while (np && (strncmp(np->id, id1, n1) || np->id[n1])) - np = np->next; - if (np) - { if (np->index < 0 - || (soap->local_namespaces[np->index].id - && (strncmp(soap->local_namespaces[np->index].id, id2, n2) - || soap->local_namespaces[np->index].id[n2]))) - return SOAP_NAMESPACE; - return SOAP_OK; - } - if (n1 == 3 && n1 == n2 && !strncmp(id1, "xml", 3) && !strncmp(id1, id2, 3)) - return SOAP_OK; - return soap->error = SOAP_SYNTAX_ERROR; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -const char* -SOAP_FMAC2 -soap_current_namespace(struct soap *soap, const char *tag) -{ register struct soap_nlist *np; - register const char *s; - if (!tag || !strncmp(tag, "xml", 3)) - return NULL; - np = soap->nlist; - if (!(s = strchr(tag, ':'))) - { while (np && *np->id) /* find default namespace, if present */ - np = np->next; - } - else - { while (np && (strncmp(np->id, tag, s - tag) || np->id[s - tag])) - np = np->next; - if (!np) - soap->error = SOAP_NAMESPACE; - } - if (np) - { if (np->index >= 0) - return soap->namespaces[np->index].ns; - if (np->ns) - return soap_strdup(soap, np->ns); - } - return NULL; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_tag_cmp(const char *s, const char *t) -{ for (;;) - { register int c1 = *s; - register int c2 = *t; - if (!c1 || c1 == '"') - break; - if (c2 != '-') - { if (c1 != c2) - { if (c1 >= 'A' && c1 <= 'Z') - c1 += 'a' - 'A'; - if (c2 >= 'A' && c2 <= 'Z') - c2 += 'a' - 'A'; - } - if (c1 != c2) - { if (c2 != '*') - return 1; - c2 = *++t; - if (!c2) - return 0; - if (c2 >= 'A' && c2 <= 'Z') - c2 += 'a' - 'A'; - for (;;) - { c1 = *s; - if (!c1 || c1 == '"') - break; - if (c1 >= 'A' && c1 <= 'Z') - c1 += 'a' - 'A'; - if (c1 == c2 && !soap_tag_cmp(s + 1, t + 1)) - return 0; - s++; - } - break; - } - } - s++; - t++; - } - if (*t == '*' && !t[1]) - return 0; - return *t; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_match_tag(struct soap *soap, const char *tag1, const char *tag2) -{ register const char *s, *t; - register int err; - if (!tag1 || !tag2 || !*tag2) - return SOAP_OK; - s = strchr(tag1, ':'); - t = strchr(tag2, ':'); - if (t) - { if (s) - { if (t[1] && SOAP_STRCMP(s + 1, t + 1)) - return SOAP_TAG_MISMATCH; - if (t != tag2 && (err = soap_match_namespace(soap, tag1, tag2, s - tag1, t - tag2))) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Tags '%s' and '%s' match but namespaces differ\n", tag1, tag2)); - if (err == SOAP_NAMESPACE) - return SOAP_TAG_MISMATCH; - return err; - } - } - else if (SOAP_STRCMP(tag1, t + 1)) - { return SOAP_TAG_MISMATCH; - } - else if (t != tag2 && (err = soap_match_namespace(soap, tag1, tag2, 0, t - tag2))) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Tags '%s' and '%s' match but namespaces differ\n", tag1, tag2)); - if (err == SOAP_NAMESPACE) - return SOAP_TAG_MISMATCH; - return err; - } - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Tags and (default) namespaces match: '%s' '%s'\n", tag1, tag2)); - return SOAP_OK; - } - if (s) - { if (SOAP_STRCMP(s + 1, tag2)) - return SOAP_TAG_MISMATCH; - } - else if (SOAP_STRCMP(tag1, tag2)) - return SOAP_TAG_MISMATCH; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Tags match: '%s' '%s'\n", tag1, tag2)); - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_match_array(struct soap *soap, const char *type) -{ if (*soap->arrayType) - if (soap_match_tag(soap, soap->arrayType, type) - && soap_match_tag(soap, soap->arrayType, "xsd:anyType") - && soap_match_tag(soap, soap->arrayType, "xsd:ur-type") - ) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Array type mismatch: '%s' '%s'\n", soap->arrayType, type)); - return SOAP_TAG_MISMATCH; - } - return SOAP_OK; -} -#endif - -/******************************************************************************\ - * - * SSL - * -\******************************************************************************/ - -#ifdef WITH_OPENSSL -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_rand() -{ unsigned char buf[4]; - if (!soap_ssl_init_done) - soap_ssl_init(); - RAND_pseudo_bytes(buf, 4); - return *(int*)buf; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_ssl_server_context(struct soap *soap, unsigned short flags, const char *keyfile, const char *password, const char *cafile, const char *capath, const char *dhfile, const char *randfile, const char *sid) -{ int err; - soap->keyfile = keyfile; - soap->password = password; - soap->cafile = cafile; - soap->capath = capath; - soap->dhfile = dhfile; - soap->randfile = randfile; - soap->ssl_flags = flags | (dhfile == NULL ? SOAP_SSL_RSA : 0); - if (!(err = soap->fsslauth(soap))) - { if (sid) - SSL_CTX_set_session_id_context(soap->ctx, (unsigned char*)sid, (unsigned int)strlen(sid)); - } - return err; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_ssl_client_context(struct soap *soap, unsigned short flags, const char *keyfile, const char *password, const char *cafile, const char *capath, const char *randfile) -{ soap->keyfile = keyfile; - soap->password = password; - soap->cafile = cafile; - soap->capath = capath; - soap->dhfile = NULL; - soap->ssl_flags = flags; - soap->randfile = randfile; - soap->fsslverify = (flags & SOAP_SSL_ALLOW_EXPIRED_CERTIFICATE) == 0 ? ssl_verify_callback : ssl_verify_callback_allow_expired_certificate; - return soap->fsslauth(soap); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_ssl_init() -{ /* Note: for MT systems, the main program MUST call soap_ssl_init() before any threads are started */ - if (!soap_ssl_init_done) - { soap_ssl_init_done = 1; - SSL_library_init(); -#ifndef WITH_LEAN - SSL_load_error_strings(); -#endif - if (!RAND_load_file("/dev/urandom", 1024)) - { char buf[1024]; - RAND_seed(buf, sizeof(buf)); - while (!RAND_status()) - { int r = rand(); - RAND_seed(&r, sizeof(int)); - } - } - } -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -const char * -SOAP_FMAC2 -soap_ssl_error(struct soap *soap, int ret) -{ int err = SSL_get_error(soap->ssl, ret); - const char *msg = soap_code_str(h_ssl_error_codes, err); - if (msg) - strcpy(soap->msgbuf, msg); - else - return ERR_error_string(err, soap->msgbuf); - if (ERR_peek_error()) - { unsigned long r; - strcat(soap->msgbuf, "\n"); - while ((r = ERR_get_error())) - ERR_error_string_n(r, soap->msgbuf + strlen(soap->msgbuf), sizeof(soap->msgbuf) - strlen(soap->msgbuf)); - } - else - { switch (ret) - { case 0: - strcpy(soap->msgbuf, "EOF was observed that violates the protocol. The client probably provided invalid authentication information."); - break; - case -1: - sprintf(soap->msgbuf, "Error observed by underlying BIO: %s", strerror(errno)); - break; - } - } - return soap->msgbuf; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -static int -ssl_password(char *buf, int num, int rwflag, void *userdata) -{ if (num < (int)strlen((char*)userdata) + 1) - return 0; - return (int)strlen(strcpy(buf, (char*)userdata)); -} -#endif - -/******************************************************************************/ -/* This callback is included for future references. It should not be deleted -#ifndef PALM_2 -static DH * -ssl_tmp_dh(SSL *ssl, int is_export, int keylength) -{ static DH *dh512 = NULL; - static DH *dh1024 = NULL; - DH *dh; - switch (keylength) - { case 512: - if (!dh512) - { BIO *bio = BIO_new_file("dh512.pem", "r"); - if (bio) - { dh512 = PEM_read_bio_DHparams(bio, NULL, NULL, NULL); - BIO_free(bio); - return dh512; - } - } - else - return dh512; - default: - if (!dh1024) - { BIO *bio = BIO_new_file("dh1024.pem", "r"); - if (bio) - { dh1024 = PEM_read_bio_DHparams(bio, NULL, NULL, NULL); - BIO_free(bio); - } - } - dh = dh1024; - } - return dh; -} -#endif -*/ - -/******************************************************************************/ -#ifndef PALM_1 -static int -ssl_auth_init(struct soap *soap) -{ long flags; - int mode; - if (!soap_ssl_init_done) - soap_ssl_init(); - ERR_clear_error(); - if (!soap->ctx) - { if (!(soap->ctx = SSL_CTX_new(SSLv23_method()))) - return soap_set_receiver_error(soap, "SSL error", "Can't setup context", SOAP_SSL_ERROR); - /* Alters the behavior of SSL read/write: - SSL_CTX_set_mode(soap->ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_AUTO_RETRY); - */ - } - if (soap->randfile) - { if (!RAND_load_file(soap->randfile, -1)) - return soap_set_receiver_error(soap, "SSL error", "Can't load randomness", SOAP_SSL_ERROR); - } - if (soap->cafile || soap->capath) - { if (!SSL_CTX_load_verify_locations(soap->ctx, soap->cafile, soap->capath)) - return soap_set_receiver_error(soap, "SSL error", "Can't read CA file and directory", SOAP_SSL_ERROR); - if (soap->cafile && (soap->ssl_flags & SOAP_SSL_REQUIRE_CLIENT_AUTHENTICATION)) - SSL_CTX_set_client_CA_list(soap->ctx, SSL_load_client_CA_file(soap->cafile)); - } - if (!(soap->ssl_flags & SOAP_SSL_NO_DEFAULT_CA_PATH)) - { if (!SSL_CTX_set_default_verify_paths(soap->ctx)) - return soap_set_receiver_error(soap, "SSL error", "Can't read default CA file and/or directory", SOAP_SSL_ERROR); - } -/* This code assumes a typical scenario, see alternative code below */ - if (soap->keyfile) - { if (!SSL_CTX_use_certificate_chain_file(soap->ctx, soap->keyfile)) - return soap_set_receiver_error(soap, "SSL error", "Can't read certificate key file", SOAP_SSL_ERROR); - if (soap->password) - { SSL_CTX_set_default_passwd_cb_userdata(soap->ctx, (void*)soap->password); - SSL_CTX_set_default_passwd_cb(soap->ctx, ssl_password); - } - if (!SSL_CTX_use_PrivateKey_file(soap->ctx, soap->keyfile, SSL_FILETYPE_PEM)) - return soap_set_receiver_error(soap, "SSL error", "Can't read key file", SOAP_SSL_ERROR); - } -/* Suggested alternative approach to check the key file for certs (cafile=NULL): - if (soap->password) - { SSL_CTX_set_default_passwd_cb_userdata(soap->ctx, (void*)soap->password); - SSL_CTX_set_default_passwd_cb(soap->ctx, ssl_password); - } - if (!soap->cafile || !SSL_CTX_use_certificate_chain_file(soap->ctx, soap->cafile)) - { if (soap->keyfile) - { if (!SSL_CTX_use_certificate_chain_file(soap->ctx, soap->keyfile)) - return soap_set_receiver_error(soap, "SSL error", "Can't read certificate or key file", SOAP_SSL_ERROR); - if (!SSL_CTX_use_PrivateKey_file(soap->ctx, soap->keyfile, SSL_FILETYPE_PEM)) - return soap_set_receiver_error(soap, "SSL error", "Can't read key file", SOAP_SSL_ERROR); - } - } -*/ - if ((soap->ssl_flags & SOAP_SSL_RSA)) - { RSA *rsa = RSA_generate_key(1024, RSA_F4, NULL, NULL); - if (!SSL_CTX_set_tmp_rsa(soap->ctx, rsa)) - { if (rsa) - RSA_free(rsa); - return soap_set_receiver_error(soap, "SSL error", "Can't set RSA key", SOAP_SSL_ERROR); - } - RSA_free(rsa); - } - else if (soap->dhfile) - { DH *dh = 0; - BIO *bio; - bio = BIO_new_file(soap->dhfile, "r"); - if (!bio) - return soap_set_receiver_error(soap, "SSL error", "Can't read DH file", SOAP_SSL_ERROR); - dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL); - BIO_free(bio); - if (SSL_CTX_set_tmp_dh(soap->ctx, dh) < 0) - { if (dh) - DH_free(dh); - return soap_set_receiver_error(soap, "SSL error", "Can't set DH parameters", SOAP_SSL_ERROR); - } - DH_free(dh); - } - flags = (SSL_OP_ALL | SSL_OP_NO_SSLv2); - if ((soap->ssl_flags & SOAP_SSLv3)) - flags |= SSL_OP_NO_TLSv1; - if ((soap->ssl_flags & SOAP_TLSv1)) - flags |= SSL_OP_NO_SSLv3; -#ifdef SSL_OP_NO_TICKET - /* TLS extension is enabled by default in OPENSSL v0.9.8k - Disable it by adding SSL_OP_NO_TICKET */ - flags |= SSL_OP_NO_TICKET; -#endif - SSL_CTX_set_options(soap->ctx, flags); - if ((soap->ssl_flags & SOAP_SSL_REQUIRE_CLIENT_AUTHENTICATION)) - mode = (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT); - else if ((soap->ssl_flags & SOAP_SSL_REQUIRE_SERVER_AUTHENTICATION)) - mode = SSL_VERIFY_PEER; - else - mode = SSL_VERIFY_NONE; - SSL_CTX_set_verify(soap->ctx, mode, soap->fsslverify); -#if (OPENSSL_VERSION_NUMBER < 0x00905100L) - SSL_CTX_set_verify_depth(soap->ctx, 1); -#else - SSL_CTX_set_verify_depth(soap->ctx, 9); -#endif - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -static int -ssl_verify_callback(int ok, X509_STORE_CTX *store) -{ -#ifdef SOAP_DEBUG - if (!ok) - { char data[256]; - X509 *cert = X509_STORE_CTX_get_current_cert(store); - fprintf(stderr, "SSL verify error or warning with certificate at depth %d: %s\n", X509_STORE_CTX_get_error_depth(store), X509_verify_cert_error_string(X509_STORE_CTX_get_error(store))); - X509_NAME_oneline(X509_get_issuer_name(cert), data, sizeof(data)); - fprintf(stderr, "certificate issuer %s\n", data); - X509_NAME_oneline(X509_get_subject_name(cert), data, sizeof(data)); - fprintf(stderr, "certificate subject %s\n", data); - } -#endif - /* Note: return 1 to continue, but unsafe progress will be terminated by SSL */ - return ok; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -static int -ssl_verify_callback_allow_expired_certificate(int ok, X509_STORE_CTX *store) -{ ok = ssl_verify_callback(ok, store); - if (ok == 0 && X509_STORE_CTX_get_error(store) == X509_V_ERR_CERT_HAS_EXPIRED) - { -#ifdef SOAP_DEBUG - fprintf(stderr, "ignoring certificate expiration\n"); -#endif - X509_STORE_CTX_set_error(store, X509_V_OK); - ok = 1; - } - /* Note: return 1 to continue, but unsafe progress will be terminated by SSL */ - return ok; -} -#endif - -/******************************************************************************/ -#ifndef WITH_NOIO -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_ssl_accept(struct soap *soap) -{ BIO *bio; - int retries, r, s; - if (!soap_valid_socket(soap->socket)) - return soap_set_receiver_error(soap, "SSL error", "No socket in soap_ssl_accept()", SOAP_SSL_ERROR); - if (!soap->ctx && (soap->error = soap->fsslauth(soap))) - return SOAP_SSL_ERROR; - if (!soap->ssl) - { soap->ssl = SSL_new(soap->ctx); - if (!soap->ssl) - return soap_set_receiver_error(soap, "SSL error", "SSL_new() failed in soap_ssl_accept()", SOAP_SSL_ERROR); - } - else - SSL_clear(soap->ssl); - soap->imode |= SOAP_ENC_SSL; - soap->omode |= SOAP_ENC_SSL; - /* Set SSL sockets to non-blocking */ - SOAP_SOCKNONBLOCK(soap->socket) - bio = BIO_new_socket((int)soap->socket, BIO_NOCLOSE); - SSL_set_bio(soap->ssl, bio, bio); - retries = 100; /* SSL_accept timeout: 10 sec retries, 100 times 0.1 sec */ - while ((r = SSL_accept(soap->ssl)) <= 0) - { int err = SSL_get_error(soap->ssl, r); - if (err == SSL_ERROR_WANT_ACCEPT || err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) - { if (err == SSL_ERROR_WANT_READ) - s = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, -100000); - else - s = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_SND | SOAP_TCP_SELECT_ERR, -100000); - if (s < 0 && soap->errnum != SOAP_EINTR) - break; - } - else - { soap->errnum = soap_socket_errno(soap->socket); - break; - } - if (retries-- <= 0) - break; - } - if (r <= 0) - { soap_set_receiver_error(soap, soap_ssl_error(soap, r), "SSL_accept() failed in soap_ssl_accept()", SOAP_SSL_ERROR); - soap_closesock(soap); - return SOAP_SSL_ERROR; - } - if ((soap->ssl_flags & SOAP_SSL_REQUIRE_CLIENT_AUTHENTICATION)) - { X509 *peer; - int err; - if ((err = SSL_get_verify_result(soap->ssl)) != X509_V_OK) - { soap_closesock(soap); - return soap_set_sender_error(soap, X509_verify_cert_error_string(err), "SSL certificate presented by peer cannot be verified in soap_ssl_accept()", SOAP_SSL_ERROR); - } - peer = SSL_get_peer_certificate(soap->ssl); - if (!peer) - { soap_closesock(soap); - return soap_set_sender_error(soap, "SSL error", "No SSL certificate was presented by the peer in soap_ssl_accept()", SOAP_SSL_ERROR); - } - X509_free(peer); - } - return SOAP_OK; -} -#endif -#endif - -/******************************************************************************/ -#endif /* WITH_OPENSSL */ - -/******************************************************************************/ -#ifndef WITH_NOIO -#ifndef PALM_1 -static int -tcp_init(struct soap *soap) -{ soap->errmode = 1; -#ifdef WIN32 - if (tcp_done) - return 0; - else - { WSADATA w; - if (WSAStartup(MAKEWORD(1, 1), &w)) - return -1; - tcp_done = 1; - } -#endif - return 0; -} -#endif -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_done(struct soap *soap) -{ -#ifdef SOAP_DEBUG - int i; -#endif - if (soap_check_state(soap)) - return; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Done with context\n")); - soap_free_temp(soap); - while (soap->clist) - { struct soap_clist *p = soap->clist->next; - SOAP_FREE(soap, soap->clist); - soap->clist = p; - } - if (soap->state == SOAP_INIT) - soap->omode &= ~SOAP_IO_UDP; /* to force close the socket */ - soap->keep_alive = 0; /* to force close the socket */ - soap_closesock(soap); -#ifdef WITH_COOKIES - soap_free_cookies(soap); -#endif - while (soap->plugins) - { register struct soap_plugin *p = soap->plugins->next; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Removing plugin '%s'\n", soap->plugins->id)); - if (soap->plugins->fcopy || soap->state == SOAP_INIT) - soap->plugins->fdelete(soap, soap->plugins); - SOAP_FREE(soap, soap->plugins); - soap->plugins = p; - } - soap->fplugin = fplugin; - soap->fmalloc = NULL; -#ifndef WITH_NOHTTP - soap->fpost = http_post; - soap->fget = http_get; - soap->fput = http_405; - soap->fdel = http_405; - soap->fhead = http_405; - soap->fform = NULL; - soap->fposthdr = http_post_header; - soap->fresponse = http_response; - soap->fparse = http_parse; - soap->fparsehdr = http_parse_header; -#endif - soap->fheader = NULL; -#ifndef WITH_NOIO -#ifndef WITH_IPV6 - soap->fresolve = tcp_gethost; -#else - soap->fresolve = NULL; -#endif - soap->faccept = tcp_accept; - soap->fopen = tcp_connect; - soap->fclose = tcp_disconnect; - soap->fclosesocket = tcp_closesocket; - soap->fshutdownsocket = tcp_shutdownsocket; - soap->fsend = fsend; - soap->frecv = frecv; - soap->fpoll = soap_poll; -#else - soap->fopen = NULL; - soap->fclose = NULL; - soap->fpoll = NULL; -#endif -#ifndef WITH_LEANER - soap->fprepareinit = NULL; - soap->fpreparesend = NULL; - soap->fpreparerecv = NULL; - soap->fpreparefinal = NULL; -#endif - soap->fseterror = NULL; - soap->fignore = NULL; - soap->fserveloop = NULL; -#ifdef WITH_OPENSSL - if (soap->session) - { SSL_SESSION_free(soap->session); - soap->session = NULL; - } -#endif - if (soap->state == SOAP_INIT) - { if (soap_valid_socket(soap->master)) - { soap->fclosesocket(soap, soap->master); - soap->master = SOAP_INVALID_SOCKET; - } - } -#ifdef WITH_OPENSSL - if (soap->ssl) - { SSL_free(soap->ssl); - soap->ssl = NULL; - } - if (soap->state == SOAP_INIT) - { if (soap->ctx) - { SSL_CTX_free(soap->ctx); - soap->ctx = NULL; - } - } -#endif -#ifdef WITH_OPENSSL - ERR_remove_state(0); -#endif -#ifdef WITH_C_LOCALE - freelocale(soap->c_locale); -#endif -#ifdef WITH_ZLIB - if (soap->d_stream) - { SOAP_FREE(soap, (void*)soap->d_stream); - soap->d_stream = NULL; - } - if (soap->z_buf) - { SOAP_FREE(soap, (void*)soap->z_buf); - soap->z_buf = NULL; - } -#endif -#ifdef SOAP_DEBUG - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Free logfiles\n")); - for (i = 0; i < SOAP_MAXLOGS; i++) - { if (soap->logfile[i]) - { SOAP_FREE(soap, (void*)soap->logfile[i]); - soap->logfile[i] = NULL; - } - soap_close_logfile(soap, i); - } - soap->state = SOAP_NONE; -#endif -#ifdef SOAP_MEM_DEBUG - soap_free_mht(soap); -#endif -} -#endif - -/******************************************************************************/ -#ifndef WITH_NOIO -#ifndef PALM_2 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_cleanup(struct soap *soap) -{ soap_done(soap); -#ifdef WIN32 - if (!tcp_done) - return; - tcp_done = 0; - WSACleanup(); -#endif -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIO -#ifndef PALM_1 -static const char* -tcp_error(struct soap *soap) -{ register const char *msg = NULL; - switch (soap->errmode) - { case 0: - msg = soap_strerror(soap); - break; - case 1: - msg = "WSAStartup failed"; - break; - case 2: - { -#ifndef WITH_LEAN - msg = soap_code_str(h_error_codes, soap->errnum); - if (!msg) -#endif - { sprintf(soap->msgbuf, "TCP/UDP IP error %d", soap->errnum); - msg = soap->msgbuf; - } - } - } - return msg; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOHTTP -#ifndef PALM_1 -static const char* -http_error(struct soap *soap, int status) -{ register const char *msg = SOAP_STR_EOS; -#ifndef WITH_LEAN - msg = soap_code_str(h_http_error_codes, status); - if (!msg) - msg = SOAP_STR_EOS; -#endif - return msg; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_IPV6 -#ifndef WITH_NOIO -#ifndef PALM_1 -static int -tcp_gethost(struct soap *soap, const char *addr, struct in_addr *inaddr) -{ soap_int32 iadd = -1; - struct hostent hostent, *host = &hostent; -#ifdef VXWORKS - int hostint; - /* inet_addr(), and hostGetByName() expect "char *"; addr is a "const char *". */ - iadd = inet_addr((char*)addr); -#else -#if defined(_AIX43) || ((defined(TRU64) || defined(HP_UX)) && defined(HAVE_GETHOSTBYNAME_R)) - struct hostent_data ht_data; -#endif -#ifdef AS400 - iadd = inet_addr((void*)addr); -#else - iadd = inet_addr(addr); -#endif -#endif - if (iadd != -1) - { memcpy(inaddr, &iadd, sizeof(iadd)); - return SOAP_OK; - } -#if defined(__GLIBC__) || (defined(HAVE_GETHOSTBYNAME_R) && (defined(FREEBSD) || defined(__FreeBSD__))) - if (gethostbyname_r(addr, &hostent, soap->buf, SOAP_BUFLEN, &host, &soap->errnum) < 0) - host = NULL; -#elif defined(_AIX43) || ((defined(TRU64) || defined(HP_UX)) && defined(HAVE_GETHOSTBYNAME_R)) - memset((void*)&ht_data, 0, sizeof(ht_data)); - if (gethostbyname_r(addr, &hostent, &ht_data) < 0) - { host = NULL; - soap->errnum = h_errno; - } -#elif defined(HAVE_GETHOSTBYNAME_R) - host = gethostbyname_r(addr, &hostent, soap->buf, SOAP_BUFLEN, &soap->errnum); -#elif defined(VXWORKS) - /* If the DNS resolver library resolvLib has been configured in the vxWorks - * image, a query for the host IP address is sent to the DNS server, if the - * name was not found in the local host table. */ - hostint = hostGetByName((char*)addr); - if (hostint == ERROR) - { host = NULL; - soap->errnum = soap_errno; - } -#else -#ifdef AS400 - if (!(host = gethostbyname((void*)addr))) - soap->errnum = h_errno; -#else - if (!(host = gethostbyname(addr))) - soap->errnum = h_errno; -#endif -#endif - if (!host) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Host name not found\n")); - return SOAP_ERR; - } -#ifdef VXWORKS - inaddr->s_addr = hostint; -#else - memcpy(inaddr, host->h_addr, host->h_length); -#endif - return SOAP_OK; -} -#endif -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIO -#ifndef PALM_1 -static SOAP_SOCKET -tcp_connect(struct soap *soap, const char *endpoint, const char *host, int port) -{ -#ifdef WITH_IPV6 - struct addrinfo hints, *res, *ressave; -#endif - SOAP_SOCKET fd; - int err = 0; -#ifndef WITH_LEAN - int len = SOAP_BUFLEN; - int set = 1; - int retries; -#endif - if (soap_valid_socket(soap->socket)) - soap->fclosesocket(soap, soap->socket); - soap->socket = SOAP_INVALID_SOCKET; - if (tcp_init(soap)) - { soap->errnum = 0; - soap_set_sender_error(soap, tcp_error(soap), "TCP init failed in tcp_connect()", SOAP_TCP_ERROR); - return SOAP_INVALID_SOCKET; - } - soap->errmode = 0; -#ifdef WITH_IPV6 - memset((void*)&hints, 0, sizeof(hints)); - hints.ai_family = PF_UNSPEC; -#ifndef WITH_LEAN - if ((soap->omode & SOAP_IO_UDP)) - hints.ai_socktype = SOCK_DGRAM; - else -#endif - hints.ai_socktype = SOCK_STREAM; - soap->errmode = 2; - if (soap->proxy_host) - err = getaddrinfo(soap->proxy_host, soap_int2s(soap, soap->proxy_port), &hints, &res); - else - err = getaddrinfo(host, soap_int2s(soap, port), &hints, &res); - if (err) - { soap_set_sender_error(soap, SOAP_GAI_STRERROR(err), "getaddrinfo failed in tcp_connect()", SOAP_TCP_ERROR); - return SOAP_INVALID_SOCKET; - } - ressave = res; -again: - fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); - soap->errmode = 0; -#else -#ifndef WITH_LEAN -again: -#endif -#ifndef WITH_LEAN - if ((soap->omode & SOAP_IO_UDP)) - fd = socket(AF_INET, SOCK_DGRAM, 0); - else -#endif - fd = socket(AF_INET, SOCK_STREAM, 0); -#endif - if (!soap_valid_socket(fd)) - { -#ifdef WITH_IPV6 - if (res->ai_next) - { res = res->ai_next; - goto again; - } -#endif - soap->errnum = soap_socket_errno(fd); - soap_set_sender_error(soap, tcp_error(soap), "socket failed in tcp_connect()", SOAP_TCP_ERROR); -#ifdef WITH_IPV6 - freeaddrinfo(ressave); -#endif - return SOAP_INVALID_SOCKET; - } -#ifdef SOCKET_CLOSE_ON_EXEC -#ifdef WIN32 -#ifndef UNDER_CE - SetHandleInformation((HANDLE)fd, HANDLE_FLAG_INHERIT, 0); -#endif -#else - fcntl(fd, F_SETFD, 1); -#endif -#endif -#ifndef WITH_LEAN - if (soap->connect_flags == SO_LINGER) - { struct linger linger; - memset((void*)&linger, 0, sizeof(linger)); - linger.l_onoff = 1; - linger.l_linger = soap->linger_time; - if (setsockopt(fd, SOL_SOCKET, SO_LINGER, (char*)&linger, sizeof(struct linger))) - { soap->errnum = soap_socket_errno(fd); - soap_set_sender_error(soap, tcp_error(soap), "setsockopt SO_LINGER failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); -#ifdef WITH_IPV6 - freeaddrinfo(ressave); -#endif - return SOAP_INVALID_SOCKET; - } - } - else if (soap->connect_flags && setsockopt(fd, SOL_SOCKET, soap->connect_flags, (char*)&set, sizeof(int))) - { soap->errnum = soap_socket_errno(fd); - soap_set_sender_error(soap, tcp_error(soap), "setsockopt failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); -#ifdef WITH_IPV6 - freeaddrinfo(ressave); -#endif - return SOAP_INVALID_SOCKET; - } - if ((soap->keep_alive || soap->tcp_keep_alive) && setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (char*)&set, sizeof(int))) - { soap->errnum = soap_socket_errno(fd); - soap_set_sender_error(soap, tcp_error(soap), "setsockopt SO_KEEPALIVE failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); -#ifdef WITH_IPV6 - freeaddrinfo(ressave); -#endif - return SOAP_INVALID_SOCKET; - } - if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char*)&len, sizeof(int))) - { soap->errnum = soap_socket_errno(fd); - soap_set_sender_error(soap, tcp_error(soap), "setsockopt SO_SNDBUF failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); -#ifdef WITH_IPV6 - freeaddrinfo(ressave); -#endif - return SOAP_INVALID_SOCKET; - } - if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char*)&len, sizeof(int))) - { soap->errnum = soap_socket_errno(fd); - soap_set_sender_error(soap, tcp_error(soap), "setsockopt SO_RCVBUF failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); -#ifdef WITH_IPV6 - freeaddrinfo(ressave); -#endif - return SOAP_INVALID_SOCKET; - } -#ifdef TCP_KEEPIDLE - if (soap->tcp_keep_idle && setsockopt((SOAP_SOCKET)fd, IPPROTO_TCP, TCP_KEEPIDLE, (char*)&(soap->tcp_keep_idle), sizeof(int))) - { soap->errnum = soap_socket_errno(fd); - soap_set_sender_error(soap, tcp_error(soap), "setsockopt TCP_KEEPIDLE failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, (SOAP_SOCKET)fd); -#ifdef WITH_IPV6 - freeaddrinfo(ressave); -#endif - return SOAP_INVALID_SOCKET; - } -#endif -#ifdef TCP_KEEPINTVL - if (soap->tcp_keep_intvl && setsockopt((SOAP_SOCKET)fd, IPPROTO_TCP, TCP_KEEPINTVL, (char*)&(soap->tcp_keep_intvl), sizeof(int))) - { soap->errnum = soap_socket_errno(fd); - soap_set_sender_error(soap, tcp_error(soap), "setsockopt TCP_KEEPINTVL failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, (SOAP_SOCKET)fd); -#ifdef WITH_IPV6 - freeaddrinfo(ressave); -#endif - return SOAP_INVALID_SOCKET; - } -#endif -#ifdef TCP_KEEPCNT - if (soap->tcp_keep_cnt && setsockopt((SOAP_SOCKET)fd, IPPROTO_TCP, TCP_KEEPCNT, (char*)&(soap->tcp_keep_cnt), sizeof(int))) - { soap->errnum = soap_socket_errno(fd); - soap_set_sender_error(soap, tcp_error(soap), "setsockopt TCP_KEEPCNT failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, (SOAP_SOCKET)fd); -#ifdef WITH_IPV6 - freeaddrinfo(ressave); -#endif - return SOAP_INVALID_SOCKET; - } -#endif -#ifdef TCP_NODELAY - if (!(soap->omode & SOAP_IO_UDP) && setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char*)&set, sizeof(int))) - { soap->errnum = soap_socket_errno(fd); - soap_set_sender_error(soap, tcp_error(soap), "setsockopt TCP_NODELAY failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); -#ifdef WITH_IPV6 - freeaddrinfo(ressave); -#endif - return SOAP_INVALID_SOCKET; - } -#endif -#ifdef WITH_IPV6 - if ((soap->omode & SOAP_IO_UDP) && soap->ipv6_multicast_if) - { struct sockaddr_in6 *in6addr = (struct sockaddr_in6*)res->ai_addr; - in6addr->sin6_scope_id = soap->ipv6_multicast_if; - } -#endif -#ifdef IP_MULTICAST_TTL - if ((soap->omode & SOAP_IO_UDP) && soap->ipv4_multicast_if && !soap->ipv6_multicast_if) - { if (soap->ipv4_multicast_ttl > 0) - { char ttl = (char)(soap->ipv4_multicast_ttl); - if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, (char*)&ttl, sizeof(ttl))) - { soap->errnum = soap_socket_errno(fd); - soap_set_sender_error(soap, tcp_error(soap), "setsockopt IP_MULTICAST_TTL failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); - return SOAP_INVALID_SOCKET; - } - } -#ifndef WINDOWS - if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, (char*)soap->ipv4_multicast_if, sizeof(struct in_addr))) - { soap->errnum = soap_socket_errno(fd); - soap_set_sender_error(soap, tcp_error(soap), "setsockopt IP_MULTICAST_IF failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); - return SOAP_INVALID_SOCKET; - } -#else -#ifndef IP_MULTICAST_IF -#define IP_MULTICAST_IF 2 -#endif - if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, (char*)soap->ipv4_multicast_if, sizeof(struct in_addr))) - { soap->errnum = soap_socket_errno(fd); - soap_set_sender_error(soap, tcp_error(soap), "setsockopt IP_MULTICAST_IF failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); - return SOAP_INVALID_SOCKET; - } -#endif - } -#endif -#endif - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Opening socket %d to host='%s' port=%d\n", fd, host, port)); -#ifndef WITH_IPV6 - soap->peerlen = sizeof(soap->peer); - memset((void*)&soap->peer, 0, sizeof(soap->peer)); - soap->peer.sin_family = AF_INET; - soap->errmode = 2; - if (soap->proxy_host) - { if (soap->fresolve(soap, soap->proxy_host, &soap->peer.sin_addr)) - { soap_set_sender_error(soap, tcp_error(soap), "get proxy host by name failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); - return SOAP_INVALID_SOCKET; - } - soap->peer.sin_port = htons((short)soap->proxy_port); - } - else - { if (soap->fresolve(soap, host, &soap->peer.sin_addr)) - { soap_set_sender_error(soap, tcp_error(soap), "get host by name failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); - return SOAP_INVALID_SOCKET; - } - soap->peer.sin_port = htons((short)port); - } - soap->errmode = 0; -#ifndef WITH_LEAN - if ((soap->omode & SOAP_IO_UDP)) - return fd; -#endif -#else - if ((soap->omode & SOAP_IO_UDP)) - { memcpy(&soap->peer, res->ai_addr, res->ai_addrlen); - soap->peerlen = res->ai_addrlen; - freeaddrinfo(ressave); - return fd; - } -#endif -#ifndef WITH_LEAN - if (soap->connect_timeout) - SOAP_SOCKNONBLOCK(fd) - else - SOAP_SOCKBLOCK(fd) - retries = 10; -#endif - for (;;) - { -#ifdef WITH_IPV6 - if (connect(fd, res->ai_addr, (int)res->ai_addrlen)) -#else - if (connect(fd, (struct sockaddr*)&soap->peer, sizeof(soap->peer))) -#endif - { err = soap_socket_errno(fd); -#ifndef WITH_LEAN - if (err == SOAP_EADDRINUSE) - { soap->fclosesocket(soap, fd); - if (retries-- > 0) - goto again; - } - else if (soap->connect_timeout && (err == SOAP_EINPROGRESS || err == SOAP_EAGAIN || err == SOAP_EWOULDBLOCK)) - { - SOAP_SOCKLEN_T k; - for (;;) - { register int r; - r = tcp_select(soap, fd, SOAP_TCP_SELECT_SND, soap->connect_timeout); - if (r > 0) - break; - if (!r) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Connect timeout\n")); - soap_set_sender_error(soap, "Timeout", "connect failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); -#ifdef WITH_IPV6 - freeaddrinfo(ressave); -#endif - return SOAP_INVALID_SOCKET; - } - r = soap->errnum; - if (r != SOAP_EINTR) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not connect to host\n")); - soap_set_sender_error(soap, tcp_error(soap), "connect failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); -#ifdef WITH_IPV6 - freeaddrinfo(ressave); -#endif - return SOAP_INVALID_SOCKET; - } - } - k = (SOAP_SOCKLEN_T)sizeof(soap->errnum); - if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, (char*)&soap->errnum, &k) && !soap->errnum) /* portability note: see SOAP_SOCKLEN_T definition in stdsoap2.h */ - break; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not connect to host\n")); - if (!soap->errnum) - soap->errnum = soap_socket_errno(fd); - soap_set_sender_error(soap, tcp_error(soap), "connect failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); -#ifdef WITH_IPV6 - freeaddrinfo(ressave); -#endif - return SOAP_INVALID_SOCKET; - } -#endif -#ifdef WITH_IPV6 - if (res->ai_next) - { res = res->ai_next; - soap->fclosesocket(soap, fd); - goto again; - } -#endif - if (err && err != SOAP_EINTR) - { soap->errnum = err; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not connect to host\n")); - soap_set_sender_error(soap, tcp_error(soap), "connect failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); -#ifdef WITH_IPV6 - freeaddrinfo(ressave); -#endif - return SOAP_INVALID_SOCKET; - } - } - else - break; - } -#ifdef WITH_IPV6 - soap->peerlen = 0; /* IPv6: already connected so use send() */ - freeaddrinfo(ressave); -#endif -#ifndef WITH_LEAN - if (soap->recv_timeout || soap->send_timeout) - SOAP_SOCKNONBLOCK(fd) - else - SOAP_SOCKBLOCK(fd) -#endif - soap->socket = fd; - soap->imode &= ~SOAP_ENC_SSL; - soap->omode &= ~SOAP_ENC_SSL; - if (!soap_tag_cmp(endpoint, "https:*")) - { -#ifdef WITH_OPENSSL - BIO *bio; - int r; - if (soap->proxy_host) - { soap_mode m = soap->mode; /* preserve settings */ - soap_mode om = soap->omode; /* make sure we only parse HTTP */ - size_t n = soap->count; /* save the content length */ - const char *userid, *passwd; - soap->omode &= ~SOAP_ENC; /* mask IO and ENC */ - soap->omode |= SOAP_IO_BUFFER; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Connecting to %s proxy server\n", soap->proxy_http_version)); - sprintf(soap->tmpbuf, "CONNECT %s:%d HTTP/%s", host, port, soap->proxy_http_version); - if (soap_begin_send(soap) - || (soap->error = soap->fposthdr(soap, soap->tmpbuf, NULL))) - { soap->fclosesocket(soap, fd); - return SOAP_INVALID_SOCKET; - } -#ifndef WITH_LEAN - if (soap->proxy_userid && soap->proxy_passwd && strlen(soap->proxy_userid) + strlen(soap->proxy_passwd) < 761) - { sprintf(soap->tmpbuf + 262, "%s:%s", soap->proxy_userid, soap->proxy_passwd); - strcpy(soap->tmpbuf, "Basic "); - soap_s2base64(soap, (const unsigned char*)(soap->tmpbuf + 262), soap->tmpbuf + 6, (int)strlen(soap->tmpbuf + 262)); - if ((soap->error = soap->fposthdr(soap, "Proxy-Authorization", soap->tmpbuf))) - { soap->fclosesocket(soap, fd); - return soap->error; - } - } -#endif - if ((soap->error = soap->fposthdr(soap, NULL, NULL)) - || soap_flush(soap)) - { soap->fclosesocket(soap, fd); - return SOAP_INVALID_SOCKET; - } - soap->omode = om; - om = soap->imode; - soap->imode &= ~SOAP_ENC; /* mask IO and ENC */ - userid = soap->userid; /* preserve */ - passwd = soap->passwd; /* preserve */ - if ((soap->error = soap->fparse(soap))) - { soap->fclosesocket(soap, fd); - return SOAP_INVALID_SOCKET; - } - soap->userid = userid; /* restore */ - soap->passwd = passwd; /* restore */ - soap->imode = om; /* restore */ - soap->count = n; /* restore */ - if (soap_begin_send(soap)) - { soap->fclosesocket(soap, fd); - return SOAP_INVALID_SOCKET; - } - if (endpoint) - strncpy(soap->endpoint, endpoint, sizeof(soap->endpoint)-1); /* restore */ - soap->mode = m; - } - if (!soap->ctx && (soap->error = soap->fsslauth(soap))) - { soap_set_sender_error(soap, "SSL error", "SSL authentication failed in tcp_connect(): check password, key file, and ca file.", SOAP_SSL_ERROR); - soap->fclosesocket(soap, fd); - return SOAP_INVALID_SOCKET; - } - if (!soap->ssl) - { soap->ssl = SSL_new(soap->ctx); - if (!soap->ssl) - { soap->fclosesocket(soap, fd); - soap->error = SOAP_SSL_ERROR; - return SOAP_INVALID_SOCKET; - } - } - else - SSL_clear(soap->ssl); - if (soap->session) - { if (!strcmp(soap->session_host, host) && soap->session_port == port) - SSL_set_session(soap->ssl, soap->session); - SSL_SESSION_free(soap->session); - soap->session = NULL; - } - soap->imode |= SOAP_ENC_SSL; - soap->omode |= SOAP_ENC_SSL; - bio = BIO_new_socket((int)fd, BIO_NOCLOSE); - SSL_set_bio(soap->ssl, bio, bio); -#ifndef WITH_LEAN - /* Connect timeout: set SSL sockets to non-blocking */ - if (soap->connect_timeout) - SOAP_SOCKNONBLOCK(fd) - else - SOAP_SOCKBLOCK(fd) - retries = 100; /* SSL connect timeout: 10 sec retries, 100 times 0.1 sec */ -#endif - /* Try connecting until success or timeout (when nonblocking) */ - do - { if ((r = SSL_connect(soap->ssl)) <= 0) - { int err = SSL_get_error(soap->ssl, r); - if (err == SSL_ERROR_WANT_CONNECT || err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) - { register int s; - if (err == SSL_ERROR_WANT_READ) - s = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, -100000); - else - s = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_SND | SOAP_TCP_SELECT_ERR, -100000); - if (s < 0 && soap->errnum != SOAP_EINTR) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "SSL_connect/select error in tcp_connect\n")); - soap_set_sender_error(soap, soap_ssl_error(soap, r), "SSL_connect failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); - return SOAP_INVALID_SOCKET; - } - if (s == 0 && retries-- <= 0) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "SSL connect timeout\n")); - soap_set_sender_error(soap, "Timeout", "SSL connect failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); - return SOAP_INVALID_SOCKET; - } - } - else - { soap_set_sender_error(soap, soap_ssl_error(soap, r), "SSL_connect error in tcp_connect()", SOAP_SSL_ERROR); - soap->fclosesocket(soap, fd); - return SOAP_INVALID_SOCKET; - } - } - } while (!SSL_is_init_finished(soap->ssl)); -#ifndef WITH_LEAN - /* Set SSL sockets to nonblocking */ - SOAP_SOCKNONBLOCK(fd) -#endif - /* Check server credentials when required */ - if ((soap->ssl_flags & SOAP_SSL_REQUIRE_SERVER_AUTHENTICATION)) - { int err; - if ((err = SSL_get_verify_result(soap->ssl)) != X509_V_OK) - { soap_set_sender_error(soap, X509_verify_cert_error_string(err), "SSL certificate presented by peer cannot be verified in tcp_connect()", SOAP_SSL_ERROR); - soap->fclosesocket(soap, fd); - return SOAP_INVALID_SOCKET; - } - if (!(soap->ssl_flags & SOAP_SSL_SKIP_HOST_CHECK)) - { X509_NAME *subj; - int ext_count; - int ok = 0; - X509 *peer; - peer = SSL_get_peer_certificate(soap->ssl); - if (!peer) - { soap_set_sender_error(soap, "SSL error", "No SSL certificate was presented by the peer in tcp_connect()", SOAP_SSL_ERROR); - soap->fclosesocket(soap, fd); - return SOAP_INVALID_SOCKET; - } - ext_count = X509_get_ext_count(peer); - if (ext_count > 0) - { int i; - for (i = 0; i < ext_count; i++) - { X509_EXTENSION *ext = X509_get_ext(peer, i); - const char *ext_str = OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(ext))); - if (ext_str && !strcmp(ext_str, "subjectAltName")) - { X509V3_EXT_METHOD *meth = X509V3_EXT_get(ext); - void *ext_data; -#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) - const unsigned char *data; -#else - unsigned char *data; -#endif - STACK_OF(CONF_VALUE) *val; - int j; - if (!meth) - break; - data = ext->value->data; -#if (OPENSSL_VERSION_NUMBER > 0x00907000L) - if (meth->it) - ext_data = ASN1_item_d2i(NULL, &data, ext->value->length, ASN1_ITEM_ptr(meth->it)); - else - { /* OpenSSL not perfectly portable at this point (?): - Some compilers appear to prefer - meth->d2i(NULL, (const unsigned char**)&data, ... - and others prefer - meth->d2i(NULL, &data, ext->value->length); - */ - ext_data = meth->d2i(NULL, &data, ext->value->length); - } -#else - ext_data = meth->d2i(NULL, &data, ext->value->length); -#endif - if (ext_data) - { val = meth->i2v(meth, ext_data, NULL); - if (val) - { for (j = 0; j < sk_CONF_VALUE_num(val); j++) - { CONF_VALUE *nval = sk_CONF_VALUE_value(val, j); - if (nval && !strcmp(nval->name, "DNS") && !strcmp(nval->value, host)) - { ok = 1; - break; - } - } - sk_CONF_VALUE_pop_free(val, X509V3_conf_free); - } -#if (OPENSSL_VERSION_NUMBER > 0x00907000L) - if (meth->it) - ASN1_item_free((ASN1_VALUE*)ext_data, ASN1_ITEM_ptr(meth->it)); - else - meth->ext_free(ext_data); -#else - meth->ext_free(ext_data); -#endif - } - } - if (ok) - break; - } - } - if (!ok && (subj = X509_get_subject_name(peer))) - { int i = -1; - do - { ASN1_STRING *name; - i = X509_NAME_get_index_by_NID(subj, NID_commonName, i); - if (i == -1) - break; - name = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subj, i)); - if (name) - { if (!soap_tag_cmp(host, (const char*)name)) - ok = 1; - else - { unsigned char *tmp = NULL; - ASN1_STRING_to_UTF8(&tmp, name); - if (tmp) - { if (!soap_tag_cmp(host, (const char*)tmp)) - ok = 1; - OPENSSL_free(tmp); - } - } - } - } while (!ok); - } - X509_free(peer); - if (!ok) - { soap_set_sender_error(soap, "SSL error", "SSL certificate host name mismatch in tcp_connect()", SOAP_SSL_ERROR); - soap->fclosesocket(soap, fd); - return SOAP_INVALID_SOCKET; - } - } - } -#else - soap->fclosesocket(soap, fd); - soap->error = SOAP_SSL_ERROR; - return SOAP_INVALID_SOCKET; -#endif - } - return fd; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIO -#ifndef PALM_1 -SOAP_FMAC1 -SOAP_SOCKET -SOAP_FMAC2 -soap_bind(struct soap *soap, const char *host, int port, int backlog) -{ -#ifdef WITH_IPV6 - struct addrinfo *addrinfo = NULL; - struct addrinfo hints; - struct addrinfo res; - int err; -#ifdef IPV6_V6ONLY - int unset = 0; -#ifdef SOL_IP - int level = SOL_IP; -#else - int level = IPPROTO_IPV6; -#endif -#endif -#endif -#ifndef WITH_LEAN - int len = SOAP_BUFLEN; - int set = 1; -#endif - if (soap_valid_socket(soap->master)) - { soap->fclosesocket(soap, soap->master); - soap->master = SOAP_INVALID_SOCKET; - } - soap->socket = SOAP_INVALID_SOCKET; - soap->errmode = 1; - if (tcp_init(soap)) - { soap_set_receiver_error(soap, tcp_error(soap), "TCP init failed in soap_bind()", SOAP_TCP_ERROR); - return SOAP_INVALID_SOCKET; - } -#ifdef WITH_IPV6 - memset((void*)&hints, 0, sizeof(hints)); - hints.ai_family = PF_UNSPEC; -#ifndef WITH_LEAN - if ((soap->omode & SOAP_IO_UDP)) - hints.ai_socktype = SOCK_DGRAM; - else -#endif - hints.ai_socktype = SOCK_STREAM; - hints.ai_flags = AI_PASSIVE; - soap->errmode = 2; - err = getaddrinfo(host, soap_int2s(soap, port), &hints, &addrinfo); - if (addrinfo) - { res = *addrinfo; - memcpy(&soap->peer, addrinfo->ai_addr, addrinfo->ai_addrlen); - soap->peerlen = addrinfo->ai_addrlen; - res.ai_addr = (struct sockaddr*)&soap->peer; - res.ai_addrlen = soap->peerlen; - freeaddrinfo(addrinfo); - } - if (err || !addrinfo) - { soap_set_receiver_error(soap, SOAP_GAI_STRERROR(err), "getaddrinfo failed in soap_bind()", SOAP_TCP_ERROR); - return SOAP_INVALID_SOCKET; - } - soap->master = (int)socket(res.ai_family, res.ai_socktype, res.ai_protocol); -#else -#ifndef WITH_LEAN - if ((soap->omode & SOAP_IO_UDP)) - soap->master = (int)socket(AF_INET, SOCK_DGRAM, 0); - else -#endif - soap->master = (int)socket(AF_INET, SOCK_STREAM, 0); -#endif - soap->errmode = 0; - if (!soap_valid_socket(soap->master)) - { soap->errnum = soap_socket_errno(soap->master); - soap_set_receiver_error(soap, tcp_error(soap), "socket failed in soap_bind()", SOAP_TCP_ERROR); - return SOAP_INVALID_SOCKET; - } -#ifndef WITH_LEAN - if ((soap->omode & SOAP_IO_UDP)) - soap->socket = soap->master; -#endif -#ifdef SOCKET_CLOSE_ON_EXEC -#ifdef WIN32 -#ifndef UNDER_CE - SetHandleInformation((HANDLE)soap->master, HANDLE_FLAG_INHERIT, 0); -#endif -#else - fcntl(soap->master, F_SETFD, 1); -#endif -#endif -#ifndef WITH_LEAN - if (soap->bind_flags && setsockopt(soap->master, SOL_SOCKET, soap->bind_flags, (char*)&set, sizeof(int))) - { soap->errnum = soap_socket_errno(soap->master); - soap_set_receiver_error(soap, tcp_error(soap), "setsockopt failed in soap_bind()", SOAP_TCP_ERROR); - return SOAP_INVALID_SOCKET; - } - if (((soap->imode | soap->omode) & SOAP_IO_KEEPALIVE) && setsockopt(soap->master, SOL_SOCKET, SO_KEEPALIVE, (char*)&set, sizeof(int))) - { soap->errnum = soap_socket_errno(soap->master); - soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_KEEPALIVE failed in soap_bind()", SOAP_TCP_ERROR); - return SOAP_INVALID_SOCKET; - } - if (setsockopt(soap->master, SOL_SOCKET, SO_SNDBUF, (char*)&len, sizeof(int))) - { soap->errnum = soap_socket_errno(soap->master); - soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_SNDBUF failed in soap_bind()", SOAP_TCP_ERROR); - return SOAP_INVALID_SOCKET; - } - if (setsockopt(soap->master, SOL_SOCKET, SO_RCVBUF, (char*)&len, sizeof(int))) - { soap->errnum = soap_socket_errno(soap->master); - soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_RCVBUF failed in soap_bind()", SOAP_TCP_ERROR); - return SOAP_INVALID_SOCKET; - } -#ifdef TCP_NODELAY - if (!(soap->omode & SOAP_IO_UDP) && setsockopt(soap->master, IPPROTO_TCP, TCP_NODELAY, (char*)&set, sizeof(int))) - { soap->errnum = soap_socket_errno(soap->master); - soap_set_receiver_error(soap, tcp_error(soap), "setsockopt TCP_NODELAY failed in soap_bind()", SOAP_TCP_ERROR); - return SOAP_INVALID_SOCKET; - } -#endif -#endif -#ifdef WITH_IPV6 -#ifdef IPV6_V6ONLY - if (setsockopt(soap->master, level, IPV6_V6ONLY, (char*)&unset, sizeof(int))) - { soap->errnum = soap_socket_errno(soap->master); - soap_set_receiver_error(soap, tcp_error(soap), "setsockopt IPV6_V6ONLY failed in soap_bind()", SOAP_TCP_ERROR); - return SOAP_INVALID_SOCKET; - } -#endif - soap->errmode = 0; - if (bind(soap->master, res.ai_addr, (int)res.ai_addrlen)) - { soap->errnum = soap_socket_errno(soap->master); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not bind to host\n")); - soap_closesock(soap); - soap_set_receiver_error(soap, tcp_error(soap), "bind failed in soap_bind()", SOAP_TCP_ERROR); - return SOAP_INVALID_SOCKET; - } -#else - soap->peerlen = sizeof(soap->peer); - memset((void*)&soap->peer, 0, sizeof(soap->peer)); - soap->peer.sin_family = AF_INET; - soap->errmode = 2; - if (host) - { if (soap->fresolve(soap, host, &soap->peer.sin_addr)) - { soap_set_receiver_error(soap, tcp_error(soap), "get host by name failed in soap_bind()", SOAP_TCP_ERROR); - return SOAP_INVALID_SOCKET; - } - } - else - soap->peer.sin_addr.s_addr = htonl(INADDR_ANY); - soap->peer.sin_port = htons((short)port); - soap->errmode = 0; - if (bind(soap->master, (struct sockaddr*)&soap->peer, (int)soap->peerlen)) - { soap->errnum = soap_socket_errno(soap->master); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not bind to host\n")); - soap_closesock(soap); - soap_set_receiver_error(soap, tcp_error(soap), "bind failed in soap_bind()", SOAP_TCP_ERROR); - return SOAP_INVALID_SOCKET; - } -#endif - if (!(soap->omode & SOAP_IO_UDP) && listen(soap->master, backlog)) - { soap->errnum = soap_socket_errno(soap->master); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not bind to host\n")); - soap_closesock(soap); - soap_set_receiver_error(soap, tcp_error(soap), "listen failed in soap_bind()", SOAP_TCP_ERROR); - return SOAP_INVALID_SOCKET; - } - return soap->master; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIO -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_poll(struct soap *soap) -{ -#ifndef WITH_LEAN - register int r; - if (soap_valid_socket(soap->socket)) - { r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_ALL, 0); - if (r > 0 && (r & SOAP_TCP_SELECT_ERR)) - r = -1; - } - else if (soap_valid_socket(soap->master)) - r = tcp_select(soap, soap->master, SOAP_TCP_SELECT_SND, 0); - else - return SOAP_OK; - if (r > 0) - { -#ifdef WITH_OPENSSL - if (soap->imode & SOAP_ENC_SSL) - { - if (soap_valid_socket(soap->socket) - && (r & SOAP_TCP_SELECT_SND) - && (!(r & SOAP_TCP_SELECT_RCV) - || SSL_peek(soap->ssl, soap->tmpbuf, 1) > 0)) - return SOAP_OK; - } - else -#endif - if (soap_valid_socket(soap->socket) - && (r & SOAP_TCP_SELECT_SND) - && (!(r & SOAP_TCP_SELECT_RCV) - || recv(soap->socket, soap->tmpbuf, 1, MSG_PEEK) > 0)) - return SOAP_OK; - } - else if (r < 0) - { if ((soap_valid_socket(soap->master) || soap_valid_socket(soap->socket)) && soap_socket_errno(soap->master) != SOAP_EINTR) - { soap_set_receiver_error(soap, tcp_error(soap), "select failed in soap_poll()", SOAP_TCP_ERROR); - return soap->error = SOAP_TCP_ERROR; - } - } - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Polling: other end down on socket=%d select=%d\n", soap->socket, r)); - return SOAP_EOF; -#else - return SOAP_OK; -#endif -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEAN -#ifndef WITH_NOIO -#ifndef PALM_1 -static int -tcp_select(struct soap *soap, SOAP_SOCKET s, int flags, int timeout) -{ register int r; - struct timeval tv; - fd_set fd[3], *rfd, *sfd, *efd; - soap->errnum = 0; -#ifndef WIN32 - /* if fd max set size exceeded, use poll() when available */ -#if defined(__QNX__) || defined(QNX) /* select() is not MT safe on some QNX */ - if (1) -#else - if ((int)s >= (int)FD_SETSIZE) -#endif -#ifdef HAVE_POLL - { struct pollfd pollfd; - int retries = 0; - pollfd.fd = (int)s; - pollfd.events = 0; - if (flags & SOAP_TCP_SELECT_RCV) - pollfd.events |= POLLIN; - if (flags & SOAP_TCP_SELECT_SND) - pollfd.events |= POLLOUT; - if (flags & SOAP_TCP_SELECT_ERR) - pollfd.events |= POLLERR; - if (timeout < 0) - timeout /= -1000; /* -usec -> ms */ - else if (timeout <= 1000000) /* avoid overflow */ - timeout *= 1000; /* sec -> ms */ - else - { retries = timeout / 1000000; - timeout = 1000000000; - } - do r = poll(&pollfd, 1, timeout); - while (r == 0 && retries--); - if (r > 0) - { r = 0; - if ((flags & SOAP_TCP_SELECT_RCV) && (pollfd.revents & POLLIN)) - r |= SOAP_TCP_SELECT_RCV; - if ((flags & SOAP_TCP_SELECT_SND) && (pollfd.revents & POLLOUT)) - r |= SOAP_TCP_SELECT_SND; - if ((flags & SOAP_TCP_SELECT_ERR) && (pollfd.revents & POLLERR)) - r |= SOAP_TCP_SELECT_ERR; - } - else if (r < 0) - soap->errnum = soap_socket_errno(s); - return r; - } -#else - { soap->error = SOAP_FD_EXCEEDED; - return -1; - } -#endif -#endif - rfd = sfd = efd = NULL; - if (flags & SOAP_TCP_SELECT_RCV) - { rfd = &fd[0]; - FD_ZERO(rfd); - FD_SET(s, rfd); - } - if (flags & SOAP_TCP_SELECT_SND) - { sfd = &fd[1]; - FD_ZERO(sfd); - FD_SET(s, sfd); - } - if (flags & SOAP_TCP_SELECT_ERR) - { efd = &fd[2]; - FD_ZERO(efd); - FD_SET(s, efd); - } - if (timeout >= 0) - { tv.tv_sec = timeout; - tv.tv_usec = 0; - } - else - { tv.tv_sec = -timeout / 1000000; - tv.tv_usec = -timeout % 1000000; - } - r = select((int)s + 1, rfd, sfd, efd, &tv); - if (r > 0) - { r = 0; - if ((flags & SOAP_TCP_SELECT_RCV) && FD_ISSET(s, rfd)) - r |= SOAP_TCP_SELECT_RCV; - if ((flags & SOAP_TCP_SELECT_SND) && FD_ISSET(s, sfd)) - r |= SOAP_TCP_SELECT_SND; - if ((flags & SOAP_TCP_SELECT_ERR) && FD_ISSET(s, efd)) - r |= SOAP_TCP_SELECT_ERR; - } - else if (r < 0) - soap->errnum = soap_socket_errno(s); - return r; -} -#endif -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIO -#ifndef PALM_1 -static SOAP_SOCKET -tcp_accept(struct soap *soap, SOAP_SOCKET s, struct sockaddr *a, int *n) -{ SOAP_SOCKET fd; - fd = accept(s, a, (SOAP_SOCKLEN_T*)n); /* portability note: see SOAP_SOCKLEN_T definition in stdsoap2.h */ -#ifdef SOCKET_CLOSE_ON_EXEC -#ifdef WIN32 -#ifndef UNDER_CE - SetHandleInformation((HANDLE)fd, HANDLE_FLAG_INHERIT, 0); -#endif -#else - fcntl(fd, F_SETFD, FD_CLOEXEC); -#endif -#endif - return fd; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIO -#ifndef PALM_1 -SOAP_FMAC1 -SOAP_SOCKET -SOAP_FMAC2 -soap_accept(struct soap *soap) -{ int n = (int)sizeof(soap->peer); -#ifndef WITH_LEAN - int len = SOAP_BUFLEN; - int set = 1; -#endif - soap->error = SOAP_OK; -#ifndef WITH_LEAN - if ((soap->omode & SOAP_IO_UDP)) - return soap->socket = soap->master; -#endif - memset((void*)&soap->peer, 0, sizeof(soap->peer)); - soap->socket = SOAP_INVALID_SOCKET; - soap->errmode = 0; - soap->keep_alive = 0; - if (soap_valid_socket(soap->master)) - { register int err; - for (;;) - { -#ifndef WITH_LEAN - if (soap->accept_timeout || soap->send_timeout || soap->recv_timeout) - { for (;;) - { register int r; - r = tcp_select(soap, soap->master, SOAP_TCP_SELECT_ALL, soap->accept_timeout ? soap->accept_timeout : 60); - if (r > 0) - break; - if (!r && soap->accept_timeout) - { soap_set_receiver_error(soap, "Timeout", "accept failed in soap_accept()", SOAP_TCP_ERROR); - return SOAP_INVALID_SOCKET; - } - if (r < 0) - { r = soap->errnum; - if (r != SOAP_EINTR) - { soap_closesock(soap); - soap_set_sender_error(soap, tcp_error(soap), "accept failed in soap_accept()", SOAP_TCP_ERROR); - return SOAP_INVALID_SOCKET; - } - } - } - } - if (soap->accept_timeout || soap->send_timeout || soap->recv_timeout) - SOAP_SOCKNONBLOCK(soap->master) - else - SOAP_SOCKBLOCK(soap->master) -#endif - soap->socket = soap->faccept(soap, soap->master, (struct sockaddr*)&soap->peer, &n); - soap->peerlen = (size_t)n; - if (soap_valid_socket(soap->socket)) - { -#ifdef WITH_IPV6 -/* Use soap->host to store the numeric form of the remote host */ - getnameinfo((struct sockaddr*)&soap->peer, n, soap->host, sizeof(soap->host), NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV); - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Accept socket %d from %s\n", soap->socket, soap->host)); - soap->ip = 0; /* info stored in soap->peer and soap->host */ - soap->port = 0; /* info stored in soap->peer and soap->host */ -#else - soap->ip = ntohl(soap->peer.sin_addr.s_addr); - soap->port = (int)ntohs(soap->peer.sin_port); /* does not return port number on some systems */ - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Accept socket %d at port %d from IP %d.%d.%d.%d\n", soap->socket, soap->port, (int)(soap->ip>>24)&0xFF, (int)(soap->ip>>16)&0xFF, (int)(soap->ip>>8)&0xFF, (int)soap->ip&0xFF)); -#endif -#ifndef WITH_LEAN - if (soap->accept_flags == SO_LINGER) - { struct linger linger; - memset((void*)&linger, 0, sizeof(linger)); - linger.l_onoff = 1; - linger.l_linger = soap->linger_time; - if (setsockopt(soap->socket, SOL_SOCKET, SO_LINGER, (char*)&linger, sizeof(struct linger))) - { soap->errnum = soap_socket_errno(soap->socket); - soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_LINGER failed in soap_accept()", SOAP_TCP_ERROR); - soap_closesock(soap); - return SOAP_INVALID_SOCKET; - } - } - else if (soap->accept_flags && setsockopt(soap->socket, SOL_SOCKET, soap->accept_flags, (char*)&set, sizeof(int))) - { soap->errnum = soap_socket_errno(soap->socket); - soap_set_receiver_error(soap, tcp_error(soap), "setsockopt failed in soap_accept()", SOAP_TCP_ERROR); - soap_closesock(soap); - return SOAP_INVALID_SOCKET; - } - if (((soap->imode | soap->omode) & SOAP_IO_KEEPALIVE) && setsockopt(soap->socket, SOL_SOCKET, SO_KEEPALIVE, (char*)&set, sizeof(int))) - { soap->errnum = soap_socket_errno(soap->socket); - soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_KEEPALIVE failed in soap_accept()", SOAP_TCP_ERROR); - soap_closesock(soap); - return SOAP_INVALID_SOCKET; - } - if (setsockopt(soap->socket, SOL_SOCKET, SO_SNDBUF, (char*)&len, sizeof(int))) - { soap->errnum = soap_socket_errno(soap->socket); - soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_SNDBUF failed in soap_accept()", SOAP_TCP_ERROR); - soap_closesock(soap); - return SOAP_INVALID_SOCKET; - } - if (setsockopt(soap->socket, SOL_SOCKET, SO_RCVBUF, (char*)&len, sizeof(int))) - { soap->errnum = soap_socket_errno(soap->socket); - soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_RCVBUF failed in soap_accept()", SOAP_TCP_ERROR); - soap_closesock(soap); - return SOAP_INVALID_SOCKET; - } -#ifdef TCP_NODELAY - if (!(soap->omode & SOAP_IO_UDP) && setsockopt(soap->socket, IPPROTO_TCP, TCP_NODELAY, (char*)&set, sizeof(int))) - { soap->errnum = soap_socket_errno(soap->socket); - soap_set_receiver_error(soap, tcp_error(soap), "setsockopt TCP_NODELAY failed in soap_accept()", SOAP_TCP_ERROR); - soap_closesock(soap); - return SOAP_INVALID_SOCKET; - } -#endif -#endif - soap->keep_alive = (((soap->imode | soap->omode) & SOAP_IO_KEEPALIVE) != 0); - return soap->socket; - } - err = soap_socket_errno(soap->socket); - if (err != 0 && err != SOAP_EINTR && err != SOAP_EAGAIN && err != SOAP_EWOULDBLOCK) - { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Accept failed from %s\n", soap->host)); - soap->errnum = err; - soap_set_receiver_error(soap, tcp_error(soap), "accept failed in soap_accept()", SOAP_TCP_ERROR); - soap_closesock(soap); - return SOAP_INVALID_SOCKET; - } - } - } - else - { soap->errnum = 0; - soap_set_receiver_error(soap, tcp_error(soap), "no master socket in soap_accept()", SOAP_TCP_ERROR); - return SOAP_INVALID_SOCKET; - } -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIO -#ifndef PALM_1 -static int -tcp_disconnect(struct soap *soap) -{ -#ifdef WITH_OPENSSL - if (soap->ssl) - { int r, s = 0; - if (soap->session) - { SSL_SESSION_free(soap->session); - soap->session = NULL; - } - if (*soap->host) - { soap->session = SSL_get1_session(soap->ssl); - if (soap->session) - { strcpy(soap->session_host, soap->host); - soap->session_port = soap->port; - } - } - r = SSL_shutdown(soap->ssl); - /* SSL shutdown does not work when reads are pending */ - while (SSL_want_read(soap->ssl)) - { SSL_read(soap->ssl, NULL, 0); - if (soap_socket_errno(soap->socket) != SOAP_EAGAIN) - { r = SSL_shutdown(soap->ssl); - break; - } - } - if (r == 0) - { if (soap_valid_socket(soap->socket)) - { if (!soap->fshutdownsocket(soap, soap->socket, 1)) - { /* - wait up to 10 seconds for close_notify to be sent by peer (if peer not - present, this avoids calling SSL_shutdown() which has a lengthy return - timeout) - */ - r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, 10); - if (r <= 0 && soap->errnum != SOAP_EINTR) - { soap->errnum = 0; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Connection lost...\n")); - soap->fclosesocket(soap, soap->socket); - soap->socket = SOAP_INVALID_SOCKET; - ERR_remove_state(0); - return SOAP_OK; - } - } - } - } - if (r != 1) - { s = ERR_get_error(); - if (s) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Shutdown failed: %d\n", SSL_get_error(soap->ssl, r))); - if (soap_valid_socket(soap->socket) && !(soap->omode & SOAP_IO_UDP)) - { soap->fclosesocket(soap, soap->socket); - soap->socket = SOAP_INVALID_SOCKET; - } - } - } - SSL_free(soap->ssl); - soap->ssl = NULL; - if (s) - return SOAP_SSL_ERROR; - ERR_remove_state(0); - } -#endif - if (soap_valid_socket(soap->socket) && !(soap->omode & SOAP_IO_UDP)) - { soap->fshutdownsocket(soap, soap->socket, 2); - soap->fclosesocket(soap, soap->socket); - soap->socket = SOAP_INVALID_SOCKET; - } - return SOAP_OK; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIO -#ifndef PALM_1 -static int -tcp_closesocket(struct soap *soap, SOAP_SOCKET fd) -{ DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Close socket %d\n", (int)fd)); - return soap_closesocket(fd); -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIO -#ifndef PALM_1 -static int -tcp_shutdownsocket(struct soap *soap, SOAP_SOCKET fd, int how) -{ DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Shutdown socket %d how=%d\n", (int)fd, how)); - return shutdown(fd, how); -} -#endif -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_closesock(struct soap *soap) -{ register int status = soap->error; - if (status == SOAP_EOF || status == SOAP_TCP_ERROR || status == SOAP_SSL_ERROR || !soap->keep_alive) - { if (soap->fclose && (soap->error = soap->fclose(soap))) - return soap->error; - soap->keep_alive = 0; - } -#ifdef WITH_ZLIB - if (soap->zlib_state == SOAP_ZLIB_DEFLATE) - deflateEnd(soap->d_stream); - else if (soap->zlib_state == SOAP_ZLIB_INFLATE) - inflateEnd(soap->d_stream); - soap->zlib_state = SOAP_ZLIB_NONE; -#endif - return soap->error = status; -} -#endif - -/******************************************************************************/ -#ifndef WITH_NOIDREF -#ifndef PALM_2 -SOAP_FMAC1 -size_t -SOAP_FMAC2 -soap_hash(register const char *s) -{ register size_t h = 0; - while (*s) - h = 65599*h + *s++; - return h % SOAP_IDHASH; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIDREF -#ifndef PALM_1 -static void -soap_init_pht(struct soap *soap) -{ register int i; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Initializing pointer hashtable\n")); - soap->pblk = NULL; - soap->pidx = 0; - for (i = 0; i < (int)SOAP_PTRHASH; i++) - soap->pht[i] = NULL; -} -#endif -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -struct soap* -SOAP_FMAC2 -soap_new1(soap_mode mode) -{ return soap_new2(mode, mode); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -struct soap* -SOAP_FMAC2 -soap_new() -{ return soap_new2(SOAP_IO_DEFAULT, SOAP_IO_DEFAULT); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -struct soap* -SOAP_FMAC2 -soap_new2(soap_mode imode, soap_mode omode) -{ struct soap *soap = (struct soap*)malloc(sizeof(struct soap)); - if (soap) - soap_init2(soap, imode, omode); - return soap; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_free(struct soap *soap) -{ soap_done(soap); - free(soap); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_del(struct soap *soap) -{ free(soap); -} -#endif - -/******************************************************************************/ -#ifndef WITH_NOIDREF -#ifndef PALM_1 -static void -soap_free_pht(struct soap *soap) -{ register struct soap_pblk *pb, *next; - register int i; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Free pointer hashtable\n")); - for (pb = soap->pblk; pb; pb = next) - { next = pb->next; - SOAP_FREE(soap, pb); - } - soap->pblk = NULL; - soap->pidx = 0; - for (i = 0; i < (int)SOAP_PTRHASH; i++) - soap->pht[i] = NULL; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIDREF -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_embed(struct soap *soap, const void *p, const struct soap_array *a, int n, const char *tag, int type) -{ register int i; - struct soap_plist *pp; - if (soap->version == 2) - soap->encoding = 1; - if (a) - i = soap_array_pointer_lookup(soap, p, a, n, type, &pp); - else - i = soap_pointer_lookup(soap, p, type, &pp); - if (i) - { if (soap_is_embedded(soap, pp) - || soap_is_single(soap, pp)) - return 0; - soap_set_embedded(soap, pp); - } - return i; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIDREF -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_pointer_lookup(struct soap *soap, const void *p, int type, struct soap_plist **ppp) -{ register struct soap_plist *pp; - *ppp = NULL; - if (p) - { for (pp = soap->pht[soap_hash_ptr(p)]; pp; pp = pp->next) - { if (pp->ptr == p && pp->type == type) - { *ppp = pp; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Lookup location=%p type=%d id=%d\n", p, type, pp->id)); - return pp->id; - } - } - } - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Lookup location=%p type=%d: not found\n", p, type)); - return 0; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIDREF -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_pointer_enter(struct soap *soap, const void *p, const struct soap_array *a, int n, int type, struct soap_plist **ppp) -{ register size_t h; - register struct soap_plist *pp; - if (!soap->pblk || soap->pidx >= SOAP_PTRBLK) - { register struct soap_pblk *pb = (struct soap_pblk*)SOAP_MALLOC(soap, sizeof(struct soap_pblk)); - if (!pb) - { soap->error = SOAP_EOM; - return 0; - } - pb->next = soap->pblk; - soap->pblk = pb; - soap->pidx = 0; - } - *ppp = pp = &soap->pblk->plist[soap->pidx++]; - if (a) - h = soap_hash_ptr(a->__ptr); - else - h = soap_hash_ptr(p); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Pointer enter location=%p array=%p size=%d dim=%d type=%d id=%d\n", p, a?a->__ptr:NULL, a?a->__size:0, n, type, soap->idnum+1)); - pp->next = soap->pht[h]; - pp->type = type; - pp->mark1 = 0; - pp->mark2 = 0; - pp->ptr = p; - pp->array = a; - soap->pht[h] = pp; - pp->id = ++soap->idnum; - return pp->id; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIDREF -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_array_pointer_lookup(struct soap *soap, const void *p, const struct soap_array *a, int n, int type, struct soap_plist **ppp) -{ register struct soap_plist *pp; - *ppp = NULL; - if (!p || !a->__ptr) - return 0; - for (pp = soap->pht[soap_hash_ptr(a->__ptr)]; pp; pp = pp->next) - { if (pp->type == type && pp->array && pp->array->__ptr == a->__ptr) - { register int i; - for (i = 0; i < n; i++) - if (((const int*)&pp->array->__size)[i] != ((const int*)&a->__size)[i]) - break; - if (i == n) - { *ppp = pp; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Array lookup location=%p type=%d id=%d\n", a->__ptr, type, pp->id)); - return pp->id; - } - } - } - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Array lookup location=%p type=%d: not found\n", a->__ptr, type)); - return 0; -} -#endif -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_begin_count(struct soap *soap) -{ soap_free_ns(soap); -#ifndef WITH_LEANER - if ((soap->mode & SOAP_ENC_DIME) || (soap->omode & SOAP_ENC_DIME)) - soap->mode = soap->omode | SOAP_IO_LENGTH | SOAP_ENC_DIME; - else -#endif - { soap->mode = soap->omode; - if ((soap->mode & SOAP_IO) == SOAP_IO_STORE - || (((soap->mode & SOAP_IO) == SOAP_IO_CHUNK || (soap->mode & SOAP_ENC_XML)) -#ifndef WITH_LEANER - && !soap->fpreparesend -#endif - )) - soap->mode &= ~SOAP_IO_LENGTH; - else - soap->mode |= SOAP_IO_LENGTH; - } -#ifdef WITH_ZLIB - if ((soap->mode & SOAP_ENC_ZLIB) && (soap->mode & SOAP_IO) == SOAP_IO_FLUSH) - { if (!(soap->mode & SOAP_ENC_DIME)) - soap->mode &= ~SOAP_IO_LENGTH; - if (soap->mode & SOAP_ENC_XML) - soap->mode |= SOAP_IO_BUFFER; - else - soap->mode |= SOAP_IO_STORE; - } -#endif - if (!soap->encodingStyle && !(soap->mode & SOAP_XML_GRAPH)) - soap->mode |= SOAP_XML_TREE; -#ifndef WITH_LEANER - if ((soap->mode & SOAP_ENC_MTOM) && (soap->mode & SOAP_ENC_DIME)) - soap->mode |= SOAP_ENC_MIME; - else if (!(soap->mode & SOAP_ENC_MIME)) - soap->mode &= ~SOAP_ENC_MTOM; - if (soap->mode & SOAP_ENC_MIME) - soap_select_mime_boundary(soap); - soap->dime.list = soap->dime.last; /* keep track of last DIME attachment */ -#endif - soap->count = 0; - soap->ns = 0; - soap->null = 0; - soap->position = 0; - soap->mustUnderstand = 0; - soap->encoding = 0; - soap->part = SOAP_BEGIN; - soap->idnum = 0; - soap_clr_attr(soap); - soap_set_local_namespaces(soap); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Begin count phase (socket=%d mode=0x%x count=%lu)\n", soap->socket, soap->mode, (unsigned long)soap->count)); -#ifndef WITH_LEANER - soap->dime.count = 0; /* count # of attachments */ - soap->dime.size = 0; /* accumulate total size of attachments */ - if (soap->fprepareinit && (soap->mode & SOAP_IO) != SOAP_IO_STORE) - return soap->error = soap->fprepareinit(soap); -#endif - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_end_count(struct soap *soap) -{ -#ifndef WITH_LEANER - if (soap->fpreparefinal) - return soap->error = soap->fpreparefinal(soap); -#endif - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "End of count phase\n")); - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_begin_send(struct soap *soap) -{ DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Initializing for output\n")); - soap_free_ns(soap); - soap->error = SOAP_OK; - soap->mode = soap->omode | (soap->mode & (SOAP_IO_LENGTH | SOAP_ENC_DIME)); -#ifdef WITH_ZLIB - if ((soap->mode & SOAP_ENC_ZLIB) && (soap->mode & SOAP_IO) == SOAP_IO_FLUSH) - { if (soap->mode & SOAP_ENC_XML) - soap->mode |= SOAP_IO_BUFFER; - else - soap->mode |= SOAP_IO_STORE; - } -#endif -#ifndef WITH_LEAN - if ((soap->mode & SOAP_IO_UDP)) - { soap->mode |= SOAP_ENC_XML; - if (soap->count > SOAP_BUFLEN) - return soap->error = SOAP_UDP_ERROR; - } -#endif - if ((soap->mode & SOAP_IO) == SOAP_IO_FLUSH && soap_valid_socket(soap->socket)) - { if (soap->count || (soap->mode & SOAP_IO_LENGTH) || (soap->mode & SOAP_ENC_XML)) - soap->mode |= SOAP_IO_BUFFER; - else - soap->mode |= SOAP_IO_STORE; - } - soap->mode &= ~SOAP_IO_LENGTH; - if ((soap->mode & SOAP_IO) == SOAP_IO_STORE) - if (soap_new_block(soap) == NULL) - return soap->error; - if (!(soap->mode & SOAP_IO_KEEPALIVE)) - soap->keep_alive = 0; - if (!soap->encodingStyle && !(soap->mode & SOAP_XML_GRAPH)) - soap->mode |= SOAP_XML_TREE; -#ifndef WITH_LEANER - if ((soap->mode & SOAP_ENC_MTOM) && (soap->mode & SOAP_ENC_DIME)) - { soap->mode |= SOAP_ENC_MIME; - soap->mode &= ~SOAP_ENC_DIME; - } - else if (!(soap->mode & SOAP_ENC_MIME)) - soap->mode &= ~SOAP_ENC_MTOM; - if (soap->mode & SOAP_ENC_MIME) - soap_select_mime_boundary(soap); -#ifdef WIN32 -#ifndef UNDER_CE -#ifndef WITH_FASTCGI - if (!soap_valid_socket(soap->socket)) /* Set win32 stdout or soap->sendfd to BINARY, e.g. to support DIME */ -#ifdef __BORLANDC__ - setmode(soap->sendfd, _O_BINARY); -#else - _setmode(soap->sendfd, _O_BINARY); -#endif -#endif -#endif -#endif -#endif - if (soap->mode & SOAP_IO) - { soap->bufidx = 0; - soap->buflen = 0; - } - soap->chunksize = 0; - soap->ns = 0; - soap->null = 0; - soap->position = 0; - soap->mustUnderstand = 0; - soap->encoding = 0; - soap->idnum = 0; - soap->level = 0; - soap_clr_attr(soap); - soap_set_local_namespaces(soap); -#ifdef WITH_ZLIB - soap->z_ratio_out = 1.0; - if ((soap->mode & SOAP_ENC_ZLIB) && soap->zlib_state != SOAP_ZLIB_DEFLATE) - { if (!soap->z_buf) - soap->z_buf = (char*)SOAP_MALLOC(soap, SOAP_BUFLEN); - soap->d_stream->next_out = (Byte*)soap->z_buf; - soap->d_stream->avail_out = SOAP_BUFLEN; -#ifdef WITH_GZIP - if (soap->zlib_out != SOAP_ZLIB_DEFLATE) - { memcpy(soap->z_buf, "\37\213\10\0\0\0\0\0\0\377", 10); - soap->d_stream->next_out = (Byte*)soap->z_buf + 10; - soap->d_stream->avail_out = SOAP_BUFLEN - 10; - soap->z_crc = crc32(0L, NULL, 0); - soap->zlib_out = SOAP_ZLIB_GZIP; - if (soap->z_dict) - *((Byte*)soap->z_buf + 2) = 0xff; - if (deflateInit2(soap->d_stream, soap->z_level, Z_DEFLATED, -MAX_WBITS, 8, Z_DEFAULT_STRATEGY) != Z_OK) - return soap->error = SOAP_ZLIB_ERROR; - } - else -#endif - if (deflateInit(soap->d_stream, soap->z_level) != Z_OK) - return soap->error = SOAP_ZLIB_ERROR; - if (soap->z_dict) - { if (deflateSetDictionary(soap->d_stream, (const Bytef*)soap->z_dict, soap->z_dict_len) != Z_OK) - return soap->error = SOAP_ZLIB_ERROR; - } - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Deflate initialized\n")); - soap->zlib_state = SOAP_ZLIB_DEFLATE; - } -#endif -#ifdef WITH_OPENSSL - if (soap->ssl) - ERR_clear_error(); -#endif - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Begin send phase (socket=%d mode=0x%x count=%lu)\n", soap->socket, soap->mode, (unsigned long)soap->count)); - soap->part = SOAP_BEGIN; -#ifndef WITH_LEANER - if (soap->fprepareinit && (soap->mode & SOAP_IO) == SOAP_IO_STORE) - soap->fprepareinit(soap); -#endif - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef WITH_NOIDREF -#ifndef PALM_2 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_embedded(struct soap *soap, const void *p, int t) -{ struct soap_plist *pp; - if (soap_pointer_lookup(soap, p, t, &pp)) - { pp->mark1 = 1; - pp->mark2 = 1; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Embedded %p type=%d mark set to 1\n", p, t)); - } -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIDREF -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_reference(struct soap *soap, const void *p, int t) -{ struct soap_plist *pp; - if (!p || (soap->mode & SOAP_XML_TREE)) - return 1; - if (soap_pointer_lookup(soap, p, t, &pp)) - { if (pp->mark1 == 0) - { pp->mark1 = 2; - pp->mark2 = 2; - } - } - else if (soap_pointer_enter(soap, p, NULL, 0, t, &pp)) - { pp->mark1 = 0; - pp->mark2 = 0; - } - else - return 1; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Reference %p type=%d (%d %d)\n", p, t, (int)pp->mark1, (int)pp->mark2)); - return pp->mark1; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIDREF -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_array_reference(struct soap *soap, const void *p, const struct soap_array *a, int n, int t) -{ register int i; - struct soap_plist *pp; - if (!p || !a->__ptr) - return 1; - i = soap_array_pointer_lookup(soap, p, a, n, t, &pp); - if (i) - { if (pp->mark1 == 0) - { pp->mark1 = 2; - pp->mark2 = 2; - } - } - else if (!soap_pointer_enter(soap, p, a, n, t, &pp)) - return 1; - else - { pp->mark1 = 0; - pp->mark2 = 0; - } - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Array reference %p ptr=%p dim=%d type=%d (%d %d)\n", p, a->__ptr, n, t, (int)pp->mark1, (int)pp->mark2)); - return pp->mark1; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIDREF -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_embedded_id(struct soap *soap, int id, const void *p, int t) -{ struct soap_plist *pp = NULL; - if (soap->mode & SOAP_XML_TREE) - return id; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Embedded_id %p type=%d id=%d\n", p, t, id)); - if (soap->version == 1 && soap->encodingStyle && !(soap->mode & SOAP_XML_GRAPH) && soap->part != SOAP_IN_HEADER) - { if (id < 0) - { id = soap_pointer_lookup(soap, p, t, &pp); - if (id) - { if (soap->mode & SOAP_IO_LENGTH) - pp->mark1 = 2; - else - pp->mark2 = 2; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Embedded_id multiref id=%d %p type=%d = (%d %d)\n", id, p, t, (int)pp->mark1, (int)pp->mark2)); - } - return -1; - } - return id; - } - if (id < 0) - id = soap_pointer_lookup(soap, p, t, &pp); - else if (id && !soap_pointer_lookup(soap, p, t, &pp)) - return 0; - if (id && pp) - { if (soap->mode & SOAP_IO_LENGTH) - pp->mark1 = 1; - else - pp->mark2 = 1; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Embedded_id embedded ref id=%d %p type=%d = (%d %d)\n", id, p, t, (int)pp->mark1, (int)pp->mark2)); - } - return id; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIDREF -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_is_embedded(struct soap *soap, struct soap_plist *pp) -{ if (!pp) - return 0; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Is embedded? %d %d\n", (int)pp->mark1, (int)pp->mark2)); - if (soap->version == 1 && soap->encodingStyle && !(soap->mode & SOAP_XML_GRAPH) && soap->part != SOAP_IN_HEADER) - { if (soap->mode & SOAP_IO_LENGTH) - return pp->mark1 != 0; - return pp->mark2 != 0; - } - if (soap->mode & SOAP_IO_LENGTH) - return pp->mark1 == 1; - return pp->mark2 == 1; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIDREF -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_is_single(struct soap *soap, struct soap_plist *pp) -{ if (soap->part == SOAP_IN_HEADER) - return 1; - if (!pp) - return 0; - if (soap->mode & SOAP_IO_LENGTH) - return pp->mark1 == 0; - return pp->mark2 == 0; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIDREF -#ifndef PALM_2 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_set_embedded(struct soap *soap, struct soap_plist *pp) -{ if (!pp) - return; - if (soap->mode & SOAP_IO_LENGTH) - pp->mark1 = 1; - else - pp->mark2 = 1; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_attachment(struct soap *soap, const char *tag, int id, const void *p, const struct soap_array *a, const char *aid, const char *atype, const char *aoptions, int n, const char *type, int t) -{ -#ifndef WITH_NOIDREF - struct soap_plist *pp; - int i; - if (!p || !a->__ptr || (!aid && !atype)) - return soap_element_id(soap, tag, id, p, a, n, type, t); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Attachment tag='%s' id='%s' (%d) type='%s'\n", tag, aid?aid:SOAP_STR_EOS, id, atype?atype:SOAP_STR_EOS)); - i = soap_array_pointer_lookup(soap, p, a, n, t, &pp); - if (!i) - { i = soap_pointer_enter(soap, p, a, n, t, &pp); - if (!i) - { soap->error = SOAP_EOM; - return -1; - } - } - if (id <= 0) - id = i; - if (!aid) - { sprintf(soap->tmpbuf, soap->dime_id_format, id); - aid = soap_strdup(soap, soap->tmpbuf); - } - /* Add MTOM xop:Include element when necessary */ - /* TODO: this code to be obsoleted with new import/xop.h conventions */ - if ((soap->mode & SOAP_ENC_MTOM) && strcmp(tag, "xop:Include")) - { if (soap_element_begin_out(soap, tag, 0, type) - || soap_element_href(soap, "xop:Include", 0, "href", aid) - || soap_element_end_out(soap, tag)) - return soap->error; - } - else if (soap_element_href(soap, tag, 0, "href", aid)) - return soap->error; - if (soap->mode & SOAP_IO_LENGTH) - { if (pp->mark1 != 3) - { struct soap_multipart *content; - if (soap->mode & SOAP_ENC_MTOM) - content = soap_new_multipart(soap, &soap->mime.first, &soap->mime.last, (char*)a->__ptr, a->__size); - else - content = soap_new_multipart(soap, &soap->dime.first, &soap->dime.last, (char*)a->__ptr, a->__size); - if (!content) - { soap->error = SOAP_EOM; - return -1; - } - if (!strncmp(aid, "cid:", 4)) /* RFC 2111 */ - { if (soap->mode & SOAP_ENC_MTOM) - { char *s = (char*)soap_malloc(soap, strlen(aid) - 1); - if (s) - { *s = '<'; - strcpy(s + 1, aid + 4); - strcat(s, ">"); - content->id = s; - } - } - else - content->id = aid + 4; - } - else - content->id = aid; - content->type = atype; - content->options = aoptions; - content->encoding = SOAP_MIME_BINARY; - pp->mark1 = 3; - } - } - else - pp->mark2 = 3; -#endif - return -1; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIDREF -#ifndef PALM_1 -static void -soap_init_iht(struct soap *soap) -{ register int i; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Initializing ID hashtable\n")); - for (i = 0; i < SOAP_IDHASH; i++) - soap->iht[i] = NULL; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIDREF -#ifndef PALM_1 -static void -soap_free_iht(struct soap *soap) -{ register int i; - register struct soap_ilist *ip = NULL, *p = NULL; - register struct soap_flist *fp = NULL, *fq = NULL; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Free ID hashtable\n")); - for (i = 0; i < SOAP_IDHASH; i++) - { for (ip = soap->iht[i]; ip; ip = p) - { for (fp = ip->flist; fp; fp = fq) - { fq = fp->next; - SOAP_FREE(soap, fp); - } - p = ip->next; - SOAP_FREE(soap, ip); - } - soap->iht[i] = NULL; - } -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIDREF -#ifndef PALM_2 -SOAP_FMAC1 -struct soap_ilist * -SOAP_FMAC2 -soap_lookup(struct soap *soap, const char *id) -{ register struct soap_ilist *ip = NULL; - for (ip = soap->iht[soap_hash(id)]; ip; ip = ip->next) - if (!strcmp(ip->id, id)) - return ip; - return NULL; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIDREF -#ifndef PALM_2 -SOAP_FMAC1 -struct soap_ilist * -SOAP_FMAC2 -soap_enter(struct soap *soap, const char *id) -{ register size_t h; - register struct soap_ilist *ip; - ip = (struct soap_ilist*)SOAP_MALLOC(soap, sizeof(struct soap_ilist) + strlen(id)); - if (ip) - { h = soap_hash(id); - strcpy(ip->id, id); - ip->next = soap->iht[h]; - soap->iht[h] = ip; - } - return ip; -} -#endif -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -void* -SOAP_FMAC2 -soap_malloc(struct soap *soap, size_t n) -{ register char *p; - if (!n) - return (void*)SOAP_NON_NULL; - if (!soap) - return SOAP_MALLOC(soap, n); - if (soap->fmalloc) - p = (char*)soap->fmalloc(soap, n); - else - { n += sizeof(short); - n += (-(long)n) & (sizeof(void*)-1); /* align at 4-, 8- or 16-byte boundary */ - if (!(p = (char*)SOAP_MALLOC(soap, n + sizeof(void*) + sizeof(size_t)))) - { soap->error = SOAP_EOM; - return NULL; - } - /* set the canary to detect corruption */ - *(short*)(p + n - sizeof(short)) = (short)SOAP_CANARY; - /* keep chain of alloced cells for destruction */ - *(void**)(p + n) = soap->alist; - *(size_t*)(p + n + sizeof(void*)) = n; - soap->alist = p + n; - } - soap->alloced = 1; - return p; -} -#endif - -/******************************************************************************/ -#ifdef SOAP_MEM_DEBUG -static void -soap_init_mht(struct soap *soap) -{ register int i; - for (i = 0; i < (int)SOAP_PTRHASH; i++) - soap->mht[i] = NULL; -} -#endif - -/******************************************************************************/ -#ifdef SOAP_MEM_DEBUG -static void -soap_free_mht(struct soap *soap) -{ register int i; - register struct soap_mlist *mp, *mq; - for (i = 0; i < (int)SOAP_PTRHASH; i++) - { for (mp = soap->mht[i]; mp; mp = mq) - { mq = mp->next; - if (mp->live) - fprintf(stderr, "%s(%d): malloc() = %p not freed (memory leak or forgot to call soap_end()?)\n", mp->file, mp->line, mp->ptr); - free(mp); - } - soap->mht[i] = NULL; - } -} -#endif - -/******************************************************************************/ -#ifdef SOAP_MEM_DEBUG -SOAP_FMAC1 -void* -SOAP_FMAC2 -soap_track_malloc(struct soap *soap, const char *file, int line, size_t size) -{ register void *p = malloc(size); - if (soap) - { register size_t h = soap_hash_ptr(p); - register struct soap_mlist *mp = (struct soap_mlist*)malloc(sizeof(struct soap_mlist)); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "%s(%d): malloc(%lu) = %p\n", file, line, (unsigned long)size, p)); - mp->next = soap->mht[h]; - mp->ptr = p; - mp->file = file; - mp->line = line; - mp->live = 1; - soap->mht[h] = mp; - } - return p; -} -#endif - -/******************************************************************************/ -#ifdef SOAP_MEM_DEBUG -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_track_free(struct soap *soap, const char *file, int line, void *p) -{ register size_t h = soap_hash_ptr(p); - register struct soap_mlist *mp; - for (mp = soap->mht[h]; mp; mp = mp->next) - if (mp->ptr == p) - break; - if (mp) - { if (mp->live) - { free(p); - if (soap->fdebug[SOAP_INDEX_TEST]) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "%s(%d): free(%p)\n", file, line, p)); - } - mp->live = 0; - } - else - fprintf(stderr, "%s(%d): free(%p) double free of pointer malloced at %s(%d)\n", file, line, p, mp->file, mp->line); - } - else - fprintf(stderr, "%s(%d): free(%p) pointer not malloced\n", file, line, p); -} -#endif - -/******************************************************************************/ -#ifdef SOAP_MEM_DEBUG -static void -soap_track_unlink(struct soap *soap, const void *p) -{ register size_t h = soap_hash_ptr(p); - register struct soap_mlist *mp; - for (mp = soap->mht[h]; mp; mp = mp->next) - if (mp->ptr == p) - break; - if (mp) - mp->live = 0; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_dealloc(struct soap *soap, void *p) -{ if (soap_check_state(soap)) - return; - if (p) - { register char **q; - for (q = (char**)&soap->alist; *q; q = *(char***)q) - { - if (*(short*)(char*)(*q - sizeof(short)) != (short)SOAP_CANARY) - { -#ifdef SOAP_MEM_DEBUG - fprintf(stderr, "Data corruption in dynamic allocation (see logs)\n"); -#endif - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Data corruption:\n")); - DBGHEX(TEST, *q - 200, 200); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "\n")); - soap->error = SOAP_MOE; - return; - } - if (p == (void*)(*q - *(size_t*)(*q + sizeof(void*)))) - { *q = **(char***)q; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Freed data at %p\n", p)); - SOAP_FREE(soap, p); - return; - } - } - soap_delete(soap, p); - } - else - { register char *q; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Free all soap_malloc() data\n")); - while (soap->alist) - { q = (char*)soap->alist; - if (*(short*)(char*)(q - sizeof(short)) != (short)SOAP_CANARY) - { -#ifdef SOAP_MEM_DEBUG - fprintf(stderr, "Data corruption in dynamic allocation (see logs)\n"); -#endif - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Data corruption:\n")); - DBGHEX(TEST, q - 200, 200); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "\n")); - soap->error = SOAP_MOE; - return; - } - soap->alist = *(void**)q; - q -= *(size_t*)(q + sizeof(void*)); - SOAP_FREE(soap, q); - } - /* we must assume these were deallocated: */ - soap->action = NULL; - soap->fault = NULL; - soap->header = NULL; - soap->userid = NULL; - soap->passwd = NULL; - soap->authrealm = NULL; - soap->http_content = NULL; -#ifndef WITH_LEANER - soap_clr_mime(soap); -#endif - } -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_delete(struct soap *soap, void *p) -{ register struct soap_clist **cp; - if (soap_check_state(soap)) - return; - cp = &soap->clist; - if (p) - { while (*cp) - { if (p == (*cp)->ptr) - { register struct soap_clist *q = *cp; - *cp = q->next; - if (q->fdelete(q)) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not dealloc data %p: deletion callback failed for object type %d\n", q->ptr, q->type)); -#ifdef SOAP_MEM_DEBUG - fprintf(stderr, "new(object type = %d) = %p not freed: deletion callback failed\n", q->type, q->ptr); -#endif - } - SOAP_FREE(soap, q); - return; - } - cp = &(*cp)->next; - } - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not dealloc data %p: address not in list\n", p)); - } - else - { while (*cp) - { register struct soap_clist *q = *cp; - *cp = q->next; - if (q->fdelete(q)) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not dealloc data %p: deletion callback failed for object type %d\n", q->ptr, q->type)); -#ifdef SOAP_MEM_DEBUG - fprintf(stderr, "new(object type = %d) = %p not freed: deletion callback failed\n", q->type, q->ptr); -#endif - } - SOAP_FREE(soap, q); - } - } - soap->fault = NULL; /* this was possibly deallocated */ - soap->header = NULL; /* this was possibly deallocated */ -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_delegate_deletion(struct soap *soap, struct soap *soap_to) -{ register struct soap_clist *cp; - register char **q; -#ifdef SOAP_MEM_DEBUG - register void *p; - register struct soap_mlist **mp, *mq; - size_t h; -#endif - for (q = (char**)&soap->alist; *q; q = *(char***)q) - { - if (*(short*)(char*)(*q - sizeof(short)) != (short)SOAP_CANARY) - { -#ifdef SOAP_MEM_DEBUG - fprintf(stderr, "Data corruption in dynamic allocation (see logs)\n"); -#endif - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Data corruption:\n")); - DBGHEX(TEST, *q - 200, 200); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "\n")); - soap->error = SOAP_MOE; - return; - } -#ifdef SOAP_MEM_DEBUG - p = (void*)(*q - *(size_t*)(*q + sizeof(void*))); - h = soap_hash_ptr(p); - for (mp = &soap->mht[h]; *mp; mp = &(*mp)->next) - { if ((*mp)->ptr == p) - { mq = *mp; - *mp = mq->next; - mq->next = soap_to->mht[h]; - soap_to->mht[h] = mq; - break; - } - } -#endif - } - *q = (char*)soap_to->alist; - soap_to->alist = soap->alist; - soap->alist = NULL; - cp = soap_to->clist; - if (cp) - { while (cp->next) - cp = cp->next; - cp->next = soap->clist; - } - else - soap_to->clist = soap->clist; - soap->clist = NULL; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -struct soap_clist * -SOAP_FMAC2 -soap_link(struct soap *soap, void *p, int t, int n, int (*fdelete)(struct soap_clist*)) -{ register struct soap_clist *cp; - if ((cp = (struct soap_clist*)SOAP_MALLOC(soap, sizeof(struct soap_clist)))) - { cp->next = soap->clist; - cp->type = t; - cp->size = n; - cp->ptr = p; - cp->fdelete = fdelete; - soap->clist = cp; - } - return cp; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_unlink(struct soap *soap, const void *p) -{ register char **q; - register struct soap_clist **cp; - if (!soap || !p) - return; - for (q = (char**)&soap->alist; *q; q = *(char***)q) - { if (p == (void*)(*q - *(size_t*)(*q + sizeof(void*)))) - { *q = **(char***)q; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unlinked data %p\n", p)); -#ifdef SOAP_MEM_DEBUG - soap_track_unlink(soap, p); -#endif - return; - } - } - for (cp = &soap->clist; *cp; cp = &(*cp)->next) - { if (p == (*cp)->ptr) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unlinked class instance %p\n", p)); - q = (char**)*cp; - *cp = (*cp)->next; - SOAP_FREE(soap, q); - return; - } - } -} -#endif - -/******************************************************************************/ -#ifndef WITH_NOIDREF -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_lookup_type(struct soap *soap, const char *id) -{ register struct soap_ilist *ip; - if (id && *id) - { ip = soap_lookup(soap, id); - if (ip) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Lookup id='%s' type=%d\n", id, ip->type)); - return ip->type; - } - } - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "lookup type id='%s' NOT FOUND! Need to get it from xsi:type\n", id)); - return 0; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIDREF -#ifndef PALM_2 -SOAP_FMAC1 -void* -SOAP_FMAC2 -soap_id_lookup(struct soap *soap, const char *id, void **p, int t, size_t n, unsigned int k) -{ struct soap_ilist *ip; - void **q; - if (!p || !id || !*id) - return p; - ip = soap_lookup(soap, id); /* lookup pointer to hash table entry for string id */ - if (!ip) - { if (!(ip = soap_enter(soap, id))) /* new hash table entry for string id */ - return NULL; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Forwarding first href='%s' type=%d %p (%u bytes)\n", id, t, p, (unsigned int)n)); - ip->type = t; - ip->size = n; - ip->link = p; - ip->copy = NULL; - ip->flist = NULL; - ip->ptr = NULL; - ip->level = k; - *p = NULL; - } - else if (ip->ptr) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Resolved href='%s' type=%d location=%p (%u bytes)\n", id, t, ip->ptr, (unsigned int)n)); - if (ip->type != t) - { strcpy(soap->id, id); - soap->error = SOAP_HREF; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Type incompatibility: href='%s' id-type=%d href-type=%d\n", id, ip->type, t)); - return NULL; - } - while (ip->level < k) - { q = (void**)soap_malloc(soap, sizeof(void*)); - if (!q) - return NULL; - *p = (void*)q; - p = q; - k--; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Descending one level...\n")); - } - *p = ip->ptr; - } - else if (ip->level > k) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Resolving level %u pointers to href='%s'\n", ip->level, id)); - while (ip->level > k) - { void *s, **r = &ip->link; - q = (void**)ip->link; - while (q) - { *r = (void*)soap_malloc(soap, sizeof(void*)); - if (!*r) - return NULL; - s = *q; - *q = *r; - r = (void**)*r; - q = (void**)s; - } - *r = NULL; - ip->size = n; - ip->copy = NULL; - ip->level = ip->level - 1; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Descending one level...\n")); - } - q = (void**)ip->link; - ip->link = p; - *p = (void*)q; - } - else - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Forwarded href='%s' type=%d location=%p (%u bytes)\n", id, t, p, (unsigned int)n)); - while (ip->level < k) - { q = (void**)soap_malloc(soap, sizeof(void*)); - if (!q) - return NULL; - *p = q; - p = q; - k--; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Descending one level...\n")); - } - q = (void**)ip->link; - ip->link = p; - *p = (void*)q; - } - return p; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIDREF -#ifndef PALM_2 -SOAP_FMAC1 -void* -SOAP_FMAC2 -soap_id_forward(struct soap *soap, const char *href, void *p, size_t len, int st, int tt, size_t n, unsigned int k, void (*fcopy)(struct soap*, int, int, void*, size_t, const void*, size_t)) -{ struct soap_ilist *ip; - if (!p || !href || !*href) - return p; - ip = soap_lookup(soap, href); /* lookup pointer to hash table entry for string id */ - if (!ip) - { if (!(ip = soap_enter(soap, href))) /* new hash table entry for string id */ - return NULL; - ip->type = st; - ip->size = n; - ip->link = NULL; - ip->copy = NULL; - ip->ptr = NULL; - ip->level = 0; - ip->flist = NULL; - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "New entry href='%s' type=%d size=%lu level=%d location=%p\n", href, st, (unsigned long)n, k, p)); - } - else if (ip->type != st || (ip->level == k && ip->size != n)) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Type incompatibility id='%s' expect type=%d size=%lu level=%u got type=%d size=%lu\n", href, ip->type, (unsigned long)ip->size, k, st, (unsigned long)n)); - strcpy(soap->id, href); - soap->error = SOAP_HREF; - return NULL; - } - if (fcopy || n < sizeof(void*) || *href != '#') - { register struct soap_flist *fp = (struct soap_flist*)SOAP_MALLOC(soap, sizeof(struct soap_flist)); - if (!fp) - { soap->error = SOAP_EOM; - return NULL; - } - fp->next = ip->flist; - fp->type = tt; - fp->ptr = p; - fp->level = k; - fp->len = len; - if (fcopy) - fp->fcopy = fcopy; - else - fp->fcopy = soap_fcopy; - ip->flist = fp; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Forwarding type=%d (target type=%d) size=%lu location=%p level=%u len=%lu href='%s'\n", st, tt, (unsigned long)n, p, k, (unsigned long)len, href)); - } - else - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Forwarding copying address %p for type=%d href='%s'\n", p, st, href)); - *(void**)p = ip->copy; - ip->copy = p; - } - return p; -} -#endif -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -void* -SOAP_FMAC2 -soap_id_enter(struct soap *soap, const char *id, void *p, int t, size_t n, unsigned int k, const char *type, const char *arrayType, void *(*finstantiate)(struct soap*, int, const char*, const char*, size_t*)) -{ -#ifndef WITH_NOIDREF - struct soap_ilist *ip; -#endif - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Enter id='%s' type=%d loc=%p size=%lu level=%u\n", id, t, p, (unsigned long)n, k)); - soap->alloced = 0; - if (!p) - { if (finstantiate) - p = finstantiate(soap, t, type, arrayType, &n); - else - p = soap_malloc(soap, n); - if (p) - soap->alloced = 1; - } -#ifndef WITH_NOIDREF - if (!id || !*id) -#endif - return p; -#ifndef WITH_NOIDREF - ip = soap_lookup(soap, id); /* lookup pointer to hash table entry for string id */ - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Lookup entry id='%s for location=%p'\n", id, p)); - if (!ip) - { if (!(ip = soap_enter(soap, id))) /* new hash table entry for string id */ - return NULL; - ip->type = t; - ip->link = NULL; - ip->copy = NULL; - ip->flist = NULL; - ip->size = n; - ip->ptr = p; - ip->level = k; - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "New entry id='%s' type=%d size=%lu level=%u location=%p\n", id, t, (unsigned long)n, k, p)); - } - else if ((ip->type != t || (ip->level == k && ip->size != n)) && (ip->copy || ip->flist)) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Type incompatibility id='%s' expect type=%d size=%lu level=%u got type=%d size=%lu\n", id, ip->type, (unsigned long)ip->size, k, t, (unsigned long)n)); - strcpy(soap->id, id); - soap->error = SOAP_HREF; - return NULL; - } - else if (ip->ptr) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Multiply defined id='%s'\n", id)); - strcpy(soap->id, id); - soap->error = SOAP_DUPLICATE_ID; - return NULL; - } - else - { ip->size = n; - ip->ptr = p; - ip->level = k; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Update entry id='%s' type=%d location=%p size=%lu level=%u\n", id, t, p, (unsigned long)n, k)); - } - return ip->ptr; -#endif -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_fcopy(struct soap *soap, int st, int tt, void *p, size_t len, const void *q, size_t n) -{ DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Copying data type=%d (target type=%d) %p -> %p (%lu bytes)\n", st, tt, q, p, (unsigned long)n)); - memcpy(p, q, n); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_end_send(struct soap *soap) -{ -#ifndef WITH_LEANER - if (soap->dime.list) - { /* SOAP body referenced attachments must appear first */ - soap->dime.last->next = soap->dime.first; - soap->dime.first = soap->dime.list->next; - soap->dime.list->next = NULL; - soap->dime.last = soap->dime.list; - } - if (soap_putdime(soap) || soap_putmime(soap)) - return soap->error; - soap->mime.list = NULL; - soap->mime.first = NULL; - soap->mime.last = NULL; - soap->dime.list = NULL; - soap->dime.first = NULL; - soap->dime.last = NULL; -#endif - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "End send\n")); - if (soap->mode & SOAP_IO) /* need to flush the remaining data in buffer */ - { if (soap_flush(soap)) -#ifdef WITH_ZLIB - { if (soap->mode & SOAP_ENC_ZLIB && soap->zlib_state == SOAP_ZLIB_DEFLATE) - { soap->zlib_state = SOAP_ZLIB_NONE; - deflateEnd(soap->d_stream); - } - return soap->error; - } -#else - return soap->error; -#endif -#ifdef WITH_ZLIB - if (soap->mode & SOAP_ENC_ZLIB) - { int r; - soap->d_stream->avail_in = 0; - do - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Deflating remainder\n")); - r = deflate(soap->d_stream, Z_FINISH); - if (soap->d_stream->avail_out != SOAP_BUFLEN) - { if (soap_flush_raw(soap, soap->z_buf, SOAP_BUFLEN - soap->d_stream->avail_out)) - { soap->zlib_state = SOAP_ZLIB_NONE; - deflateEnd(soap->d_stream); - return soap->error; - } - soap->d_stream->next_out = (Byte*)soap->z_buf; - soap->d_stream->avail_out = SOAP_BUFLEN; - } - } while (r == Z_OK); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Deflated total %lu->%lu bytes\n", soap->d_stream->total_in, soap->d_stream->total_out)); - soap->z_ratio_out = (float)soap->d_stream->total_out / (float)soap->d_stream->total_in; - soap->mode &= ~SOAP_ENC_ZLIB; - soap->zlib_state = SOAP_ZLIB_NONE; - if (deflateEnd(soap->d_stream) != Z_OK || r != Z_STREAM_END) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unable to end deflate: %s\n", soap->d_stream->msg?soap->d_stream->msg:SOAP_STR_EOS)); - return soap->error = SOAP_ZLIB_ERROR; - } -#ifdef WITH_GZIP - if (soap->zlib_out != SOAP_ZLIB_DEFLATE) - { soap->z_buf[0] = soap->z_crc & 0xFF; - soap->z_buf[1] = (soap->z_crc >> 8) & 0xFF; - soap->z_buf[2] = (soap->z_crc >> 16) & 0xFF; - soap->z_buf[3] = (soap->z_crc >> 24) & 0xFF; - soap->z_buf[4] = soap->d_stream->total_in & 0xFF; - soap->z_buf[5] = (soap->d_stream->total_in >> 8) & 0xFF; - soap->z_buf[6] = (soap->d_stream->total_in >> 16) & 0xFF; - soap->z_buf[7] = (soap->d_stream->total_in >> 24) & 0xFF; - if (soap_flush_raw(soap, soap->z_buf, 8)) - return soap->error; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "gzip crc32=%lu\n", (unsigned long)soap->z_crc)); - } -#endif - } -#endif - if ((soap->mode & SOAP_IO) == SOAP_IO_STORE) - { char *p; -#ifndef WITH_NOHTTP - if (!(soap->mode & SOAP_ENC_XML)) - { soap->mode--; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Sending buffered message of length %u\n", (unsigned int)soap->blist->size)); - if (soap->status >= SOAP_POST) - soap->error = soap->fpost(soap, soap->endpoint, soap->host, soap->port, soap->path, soap->action, soap->blist->size); - else if (soap->status != SOAP_STOP) - soap->error = soap->fresponse(soap, soap->status, soap->blist->size); - if (soap->error || soap_flush(soap)) - return soap->error; - soap->mode++; - } -#endif - for (p = soap_first_block(soap, NULL); p; p = soap_next_block(soap, NULL)) - { DBGMSG(SENT, p, soap_block_size(soap, NULL)); - if ((soap->error = soap->fsend(soap, p, soap_block_size(soap, NULL)))) - { soap_end_block(soap, NULL); - return soap->error; - } - } - soap_end_block(soap, NULL); - } -#ifndef WITH_LEANER - else if ((soap->mode & SOAP_IO) == SOAP_IO_CHUNK) - { DBGMSG(SENT, "\r\n0\r\n\r\n", 7); - if ((soap->error = soap->fsend(soap, "\r\n0\r\n\r\n", 7))) - return soap->error; - } -#endif - } -#ifdef WITH_TCPFIN -#ifdef WITH_OPENSSL - if (!soap->ssl && soap_valid_socket(soap->socket) && !soap->keep_alive && !(soap->omode & SOAP_IO_UDP)) - soap->fshutdownsocket(soap, soap->socket, 1); /* Send TCP FIN */ -#else - if (soap_valid_socket(soap->socket) && !soap->keep_alive && !(soap->omode & SOAP_IO_UDP)) - soap->fshutdownsocket(soap, soap->socket, 1); /* Send TCP FIN */ -#endif -#endif - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "End of send phase\n")); - soap->omode &= ~SOAP_XML_SEC; - soap->count = 0; - soap->part = SOAP_END; - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_end_recv(struct soap *soap) -{ soap->part = SOAP_END; -#ifndef WITH_LEANER - if ((soap->mode & SOAP_ENC_DIME) && soap_getdime(soap)) - { soap->dime.first = NULL; - soap->dime.last = NULL; - return soap->error; - } - soap->dime.list = soap->dime.first; - soap->dime.first = NULL; - soap->dime.last = NULL; - /* Check if MIME attachments and mime-post-check flag is set, if set call soap_resolve() and return */ - if (soap->mode & SOAP_ENC_MIME) - { -#ifndef WITH_NOIDREF - if (soap->mode & SOAP_MIME_POSTCHECK) - { soap_resolve(soap); - return SOAP_OK; - } -#endif - if (soap_getmime(soap)) - return soap->error; - } - soap->mime.list = soap->mime.first; - soap->mime.first = NULL; - soap->mime.last = NULL; - soap->mime.boundary = NULL; - if (soap->xlist) - { struct soap_multipart *content; - for (content = soap->mime.list; content; content = content->next) - soap_resolve_attachment(soap, content); - } -#endif - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "End of receive message ok\n")); -#ifdef WITH_ZLIB - if (soap->mode & SOAP_ENC_ZLIB) - { /* Make sure end of compressed content is reached */ - while (soap->d_stream->next_out != Z_NULL) - if ((int)soap_get1(soap) == EOF) - break; - soap->mode &= ~SOAP_ENC_ZLIB; - memcpy(soap->buf, soap->z_buf, SOAP_BUFLEN); - soap->bufidx = (char*)soap->d_stream->next_in - soap->z_buf; - soap->buflen = soap->z_buflen; - soap->zlib_state = SOAP_ZLIB_NONE; - if (inflateEnd(soap->d_stream) != Z_OK) - return soap->error = SOAP_ZLIB_ERROR; - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Inflate end ok\n")); -#ifdef WITH_GZIP - if (soap->zlib_in == SOAP_ZLIB_GZIP) - { soap_wchar c; - short i; - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Inflate gzip crc check\n")); - for (i = 0; i < 8; i++) - { if ((int)(c = soap_get1(soap)) == EOF) - return soap->error = SOAP_EOF; - soap->z_buf[i] = (char)c; - } - if (soap->z_crc != ((uLong)(unsigned char)soap->z_buf[0] | ((uLong)(unsigned char)soap->z_buf[1] << 8) | ((uLong)(unsigned char)soap->z_buf[2] << 16) | ((uLong)(unsigned char)soap->z_buf[3] << 24))) - { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Gzip error: crc check failed, message corrupted? (crc32=%lu)\n", (unsigned long)soap->z_crc)); - return soap->error = SOAP_ZLIB_ERROR; - } - if (soap->d_stream->total_out != ((uLong)(unsigned char)soap->z_buf[4] | ((uLong)(unsigned char)soap->z_buf[5] << 8) | ((uLong)(unsigned char)soap->z_buf[6] << 16) | ((uLong)(unsigned char)soap->z_buf[7] << 24))) - { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Gzip error: incorrect message length\n")); - return soap->error = SOAP_ZLIB_ERROR; - } - } - soap->zlib_in = SOAP_ZLIB_NONE; -#endif - } -#endif - if ((soap->mode & SOAP_IO) == SOAP_IO_CHUNK) - while ((int)soap_getchar(soap) != EOF) /* advance to last chunk */ - ; - if (soap->fdisconnect && (soap->error = soap->fdisconnect(soap))) - return soap->error; -#ifndef WITH_NOIDREF - if (soap_resolve(soap)) - return soap->error; -#endif -#ifndef WITH_LEANER - if (soap->xlist) - { if (soap->mode & SOAP_ENC_MTOM) - return soap->error = SOAP_MIME_HREF; - return soap->error = SOAP_DIME_HREF; - } -#endif - soap_free_ns(soap); - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_free_temp(struct soap *soap) -{ register struct soap_attribute *tp, *tq; - register struct Namespace *ns; - soap_free_ns(soap); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Free any remaining temp blocks\n")); - while (soap->blist) - soap_end_block(soap, NULL); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Free attribute storage\n")); - for (tp = soap->attributes; tp; tp = tq) - { tq = tp->next; - if (tp->value) - SOAP_FREE(soap, tp->value); - SOAP_FREE(soap, tp); - } - soap->attributes = NULL; -#ifdef WITH_FAST - if (soap->labbuf) - SOAP_FREE(soap, soap->labbuf); - soap->labbuf = NULL; - soap->lablen = 0; - soap->labidx = 0; -#endif - ns = soap->local_namespaces; - if (ns) - { for (; ns->id; ns++) - { if (ns->out) - { if (soap->encodingStyle == ns->out) - soap->encodingStyle = SOAP_STR_EOS; - SOAP_FREE(soap, ns->out); - ns->out = NULL; - } - if (soap->encodingStyle == ns->ns) - soap->encodingStyle = SOAP_STR_EOS; - } - SOAP_FREE(soap, soap->local_namespaces); - soap->local_namespaces = NULL; - } -#ifndef WITH_LEANER - while (soap->xlist) - { struct soap_xlist *xp = soap->xlist->next; - SOAP_FREE(soap, soap->xlist); - soap->xlist = xp; - } -#endif -#ifndef WITH_NOIDREF - soap_free_pht(soap); - soap_free_iht(soap); -#endif -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -static void -soap_free_ns(struct soap *soap) -{ register struct soap_nlist *np, *nq; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Free namespace stack\n")); - for (np = soap->nlist; np; np = nq) - { nq = np->next; - SOAP_FREE(soap, np); - } - soap->nlist = NULL; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -#if !defined(WITH_LEAN) || defined(SOAP_DEBUG) -static void -soap_init_logs(struct soap *soap) -{ int i; - for (i = 0; i < SOAP_MAXLOGS; i++) - { soap->logfile[i] = NULL; - soap->fdebug[i] = NULL; - } -} -#endif -#endif - -/******************************************************************************/ -#if !defined(WITH_LEAN) || defined(SOAP_DEBUG) -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_open_logfile(struct soap *soap, int i) -{ if (soap->logfile[i]) - soap->fdebug[i] = fopen(soap->logfile[i], i < 2 ? "ab" : "a"); -} -#endif - -/******************************************************************************/ -#ifdef SOAP_DEBUG -static void -soap_close_logfile(struct soap *soap, int i) -{ if (soap->fdebug[i]) - { fclose(soap->fdebug[i]); - soap->fdebug[i] = NULL; - } -} -#endif - -/******************************************************************************/ -#ifdef SOAP_DEBUG -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_close_logfiles(struct soap *soap) -{ int i; - for (i = 0; i < SOAP_MAXLOGS; i++) - soap_close_logfile(soap, i); -} -#endif - -/******************************************************************************/ -#ifdef SOAP_DEBUG -static void -soap_set_logfile(struct soap *soap, int i, const char *logfile) -{ const char *s; - char *t = NULL; - soap_close_logfile(soap, i); - s = soap->logfile[i]; - soap->logfile[i] = logfile; - if (s) - SOAP_FREE(soap, (void*)s); - if (logfile) - if ((t = (char*)SOAP_MALLOC(soap, strlen(logfile) + 1))) - strcpy(t, logfile); - soap->logfile[i] = t; -} -#endif - -/******************************************************************************/ -#ifdef SOAP_DEBUG -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_set_recv_logfile(struct soap *soap, const char *logfile) -{ soap_set_logfile(soap, SOAP_INDEX_RECV, logfile); -} -#endif - -/******************************************************************************/ -#ifdef SOAP_DEBUG -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_set_sent_logfile(struct soap *soap, const char *logfile) -{ soap_set_logfile(soap, SOAP_INDEX_SENT, logfile); -} -#endif - -/******************************************************************************/ -#ifdef SOAP_DEBUG -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_set_test_logfile(struct soap *soap, const char *logfile) -{ soap_set_logfile(soap, SOAP_INDEX_TEST, logfile); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -struct soap* -SOAP_FMAC2 -soap_copy(const struct soap *soap) -{ return soap_copy_context((struct soap*)malloc(sizeof(struct soap)), soap); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -struct soap* -SOAP_FMAC2 -soap_copy_context(struct soap *copy, const struct soap *soap) -{ if (soap_check_state(soap)) - return NULL; - if (copy) - { register struct soap_plugin *p = NULL; -#ifdef __cplusplus - *copy = *soap; -#else - memcpy(copy, soap, sizeof(struct soap)); -#endif - copy->state = SOAP_COPY; - copy->error = SOAP_OK; - copy->userid = NULL; - copy->passwd = NULL; - copy->nlist = NULL; - copy->blist = NULL; - copy->clist = NULL; - copy->alist = NULL; - copy->attributes = NULL; - copy->labbuf = NULL; - copy->lablen = 0; - copy->labidx = 0; -#ifdef SOAP_MEM_DEBUG - soap_init_mht(copy); -#endif -#if !defined(WITH_LEAN) || defined(SOAP_DEBUG) - soap_init_logs(copy); -#endif -#ifdef SOAP_DEBUG - soap_set_test_logfile(copy, soap->logfile[SOAP_INDEX_TEST]); - soap_set_sent_logfile(copy, soap->logfile[SOAP_INDEX_SENT]); - soap_set_recv_logfile(copy, soap->logfile[SOAP_INDEX_RECV]); -#endif -#ifdef WITH_C_LOCALE - copy->c_locale = duplocale(soap->c_locale); -#else - copy->c_locale = NULL; -#endif -#ifdef WITH_OPENSSL - copy->bio = NULL; - copy->ssl = NULL; - copy->session = NULL; -#endif -#ifdef WITH_ZLIB - copy->d_stream = (z_stream*)SOAP_MALLOC(copy, sizeof(z_stream)); - copy->d_stream->zalloc = Z_NULL; - copy->d_stream->zfree = Z_NULL; - copy->d_stream->opaque = Z_NULL; - copy->z_buf = NULL; -#endif - copy->local_namespaces = NULL; -#ifndef WITH_NOIDREF - soap_init_iht(copy); - soap_init_pht(copy); -#endif - copy->header = NULL; - copy->fault = NULL; - copy->action = NULL; -#ifndef WITH_LEAN -#ifdef WITH_COOKIES - copy->cookies = soap_copy_cookies(copy, soap); -#else - copy->cookies = NULL; -#endif -#endif - copy->plugins = NULL; - for (p = soap->plugins; p; p = p->next) - { register struct soap_plugin *q = (struct soap_plugin*)SOAP_MALLOC(copy, sizeof(struct soap_plugin)); - if (!q) - return NULL; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copying plugin '%s'\n", p->id)); - *q = *p; - if (p->fcopy && p->fcopy(copy, q, p)) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not copy plugin '%s'\n", p->id)); - SOAP_FREE(copy, q); - return NULL; - } - q->next = copy->plugins; - copy->plugins = q; - } - } - return copy; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_copy_stream(struct soap *copy, struct soap *soap) -{ copy->mode = soap->mode; - copy->imode = soap->imode; - copy->omode = soap->omode; - copy->socket = soap->socket; - copy->recv_timeout = soap->recv_timeout; - copy->send_timeout = soap->send_timeout; -#if defined(__cplusplus) && !defined(WITH_LEAN) - copy->os = soap->os; - copy->is = soap->is; -#endif - copy->sendfd = soap->sendfd; - copy->recvfd = soap->recvfd; - copy->bufidx = soap->bufidx; - copy->buflen = soap->buflen; - copy->ahead = soap->ahead; - copy->cdata = soap->cdata; - copy->chunksize = soap->chunksize; - copy->chunkbuflen = soap->chunkbuflen; - copy->keep_alive = soap->keep_alive; - copy->tcp_keep_alive = soap->tcp_keep_alive; - copy->tcp_keep_idle = soap->tcp_keep_idle; - copy->tcp_keep_intvl = soap->tcp_keep_intvl; - copy->tcp_keep_cnt = soap->tcp_keep_cnt; - copy->max_keep_alive = soap->max_keep_alive; -#ifndef WITH_NOIO - copy->peer = soap->peer; - copy->peerlen = soap->peerlen; -#endif -#ifdef WITH_OPENSSL - copy->bio = soap->bio; - copy->ssl = soap->ssl; - copy->ctx = soap->ctx; -#endif -#ifdef WITH_ZLIB - copy->zlib_state = soap->zlib_state; - copy->zlib_in = soap->zlib_in; - copy->zlib_out = soap->zlib_out; - copy->d_stream = (z_stream*)SOAP_MALLOC(copy, sizeof(z_stream)); - memcpy(copy->d_stream, soap->d_stream, sizeof(z_stream)); - copy->z_crc = soap->z_crc; - copy->z_ratio_in = soap->z_ratio_in; - copy->z_ratio_out = soap->z_ratio_out; - copy->z_buf = NULL; - copy->z_buflen = soap->z_buflen; - copy->z_level = soap->z_level; - if (soap->z_buf && soap->zlib_state != SOAP_ZLIB_NONE) - { copy->z_buf = (char*)SOAP_MALLOC(copy, SOAP_BUFLEN); - memcpy(copy->z_buf, soap->z_buf, sizeof(soap->z_buf)); - } - copy->z_dict = soap->z_dict; - copy->z_dict_len = soap->z_dict_len; -#endif - memcpy(copy->buf, soap->buf, sizeof(soap->buf)); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_init(struct soap *soap) -{ soap->state = SOAP_INIT; -#ifdef SOAP_MEM_DEBUG - soap_init_mht(soap); -#endif -#if !defined(WITH_LEAN) || defined(SOAP_DEBUG) - soap_init_logs(soap); -#endif -#ifdef SOAP_DEBUG - soap_set_test_logfile(soap, "TEST.log"); - soap_set_sent_logfile(soap, "SENT.log"); - soap_set_recv_logfile(soap, "RECV.log"); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Initializing context\n")); -#endif - soap->version = 0; - soap_imode(soap, SOAP_IO_DEFAULT); - soap_omode(soap, SOAP_IO_DEFAULT); - soap->plugins = NULL; - soap->user = NULL; - soap->userid = NULL; - soap->passwd = NULL; -#ifndef WITH_NOHTTP - soap->fpost = http_post; - soap->fget = http_get; - soap->fput = http_405; - soap->fdel = http_405; - soap->fhead = http_405; - soap->fform = NULL; - soap->fposthdr = http_post_header; - soap->fresponse = http_response; - soap->fparse = http_parse; - soap->fparsehdr = http_parse_header; -#endif - soap->fheader = NULL; - soap->fconnect = NULL; - soap->fdisconnect = NULL; -#ifndef WITH_NOIO - soap->ipv6_multicast_if = 0; - soap->ipv4_multicast_if = NULL; -#ifndef WITH_IPV6 - soap->fresolve = tcp_gethost; -#else - soap->fresolve = NULL; -#endif - soap->faccept = tcp_accept; - soap->fopen = tcp_connect; - soap->fclose = tcp_disconnect; - soap->fclosesocket = tcp_closesocket; - soap->fshutdownsocket = tcp_shutdownsocket; - soap->fsend = fsend; - soap->frecv = frecv; - soap->fpoll = soap_poll; -#else - soap->fopen = NULL; - soap->fclose = NULL; - soap->fpoll = NULL; -#endif - soap->fseterror = NULL; - soap->fignore = NULL; - soap->fserveloop = NULL; - soap->fplugin = fplugin; - soap->fmalloc = NULL; -#ifndef WITH_LEANER - soap->fprepareinit = NULL; - soap->fpreparesend = NULL; - soap->fpreparerecv = NULL; - soap->fpreparefinal = NULL; - soap->fdimereadopen = NULL; - soap->fdimewriteopen = NULL; - soap->fdimereadclose = NULL; - soap->fdimewriteclose = NULL; - soap->fdimeread = NULL; - soap->fdimewrite = NULL; - soap->fmimereadopen = NULL; - soap->fmimewriteopen = NULL; - soap->fmimereadclose = NULL; - soap->fmimewriteclose = NULL; - soap->fmimeread = NULL; - soap->fmimewrite = NULL; -#endif - soap->float_format = "%.9G"; /* Alternative: use "%G" */ - soap->double_format = "%.17lG"; /* Alternative: use "%lG" */ - soap->dime_id_format = "cid:id%d"; /* default DIME id format */ - soap->http_version = "1.1"; - soap->proxy_http_version = "1.0"; - soap->http_content = NULL; - soap->actor = NULL; - soap->lang = "en"; - soap->keep_alive = 0; - soap->tcp_keep_alive = 0; - soap->tcp_keep_idle = 0; - soap->tcp_keep_intvl = 0; - soap->tcp_keep_cnt = 0; - soap->max_keep_alive = SOAP_MAXKEEPALIVE; - soap->recv_timeout = 0; - soap->send_timeout = 0; - soap->connect_timeout = 0; - soap->accept_timeout = 0; - soap->socket_flags = 0; - soap->connect_flags = 0; - soap->bind_flags = 0; - soap->accept_flags = 0; - soap->linger_time = 0; - soap->ip = 0; - soap->labbuf = NULL; - soap->lablen = 0; - soap->labidx = 0; - soap->encodingStyle = SOAP_STR_EOS; -#ifndef WITH_NONAMESPACES - soap->namespaces = namespaces; -#else - soap->namespaces = NULL; -#endif - soap->local_namespaces = NULL; - soap->nlist = NULL; - soap->blist = NULL; - soap->clist = NULL; - soap->alist = NULL; - soap->attributes = NULL; - soap->header = NULL; - soap->fault = NULL; - soap->master = SOAP_INVALID_SOCKET; - soap->socket = SOAP_INVALID_SOCKET; - soap->os = NULL; - soap->is = NULL; -#ifndef WITH_LEANER - soap->dom = NULL; - soap->dime.list = NULL; - soap->dime.first = NULL; - soap->dime.last = NULL; - soap->mime.list = NULL; - soap->mime.first = NULL; - soap->mime.last = NULL; - soap->mime.boundary = NULL; - soap->mime.start = NULL; - soap->xlist = NULL; -#endif -#ifndef UNDER_CE - soap->recvfd = 0; - soap->sendfd = 1; -#else - soap->recvfd = stdin; - soap->sendfd = stdout; -#endif - soap->host[0] = '\0'; - soap->port = 0; - soap->action = NULL; - soap->proxy_host = NULL; - soap->proxy_port = 8080; - soap->proxy_userid = NULL; - soap->proxy_passwd = NULL; - soap->authrealm = NULL; - soap->prolog = NULL; -#ifdef WITH_ZLIB - soap->zlib_state = SOAP_ZLIB_NONE; - soap->zlib_in = SOAP_ZLIB_NONE; - soap->zlib_out = SOAP_ZLIB_NONE; - soap->d_stream = (z_stream*)SOAP_MALLOC(soap, sizeof(z_stream)); - soap->d_stream->zalloc = Z_NULL; - soap->d_stream->zfree = Z_NULL; - soap->d_stream->opaque = Z_NULL; - soap->z_buf = NULL; - soap->z_level = 6; - soap->z_dict = NULL; - soap->z_dict_len = 0; -#endif -#ifndef WITH_LEAN - soap->c14ninclude = NULL; - soap->c14nexclude = NULL; - soap->cookies = NULL; - soap->cookie_domain = NULL; - soap->cookie_path = NULL; - soap->cookie_max = 32; -#endif -#ifdef WMW_RPM_IO - soap->rpmreqid = NULL; -#endif -#ifdef PALM - palmNetLibOpen(); -#endif -#ifndef WITH_NOIDREF - soap_init_iht(soap); - soap_init_pht(soap); -#endif -#ifdef WITH_OPENSSL - if (!soap_ssl_init_done) - { soap_ssl_init(); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Initializing OpenSSL, version=%ld\n", (long)OPENSSL_VERSION_NUMBER)); - } - soap->fsslauth = ssl_auth_init; - soap->fsslverify = ssl_verify_callback; - soap->bio = NULL; - soap->ssl = NULL; - soap->ctx = NULL; - soap->ssl_flags = SOAP_SSL_DEFAULT; - soap->keyfile = NULL; - soap->password = NULL; - soap->dhfile = NULL; - soap->cafile = NULL; - soap->capath = NULL; - soap->crlfile = NULL; - soap->randfile = NULL; - soap->session = NULL; -#endif -#ifdef WITH_C_LOCALE - soap->c_locale = newlocale(LC_ALL_MASK, "C", NULL); -#else - soap->c_locale = NULL; -#endif - soap_begin(soap); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_init1(struct soap *soap, soap_mode mode) -{ soap_init2(soap, mode, mode); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_init2(struct soap *soap, soap_mode imode, soap_mode omode) -{ soap_init(soap); - soap_imode(soap, imode); - soap_omode(soap, omode); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_begin(struct soap *soap) -{ DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Reinitializing context\n")); - if (!soap->keep_alive) - { soap->buflen = 0; - soap->bufidx = 0; - } - soap->keep_alive = (((soap->imode | soap->omode) & SOAP_IO_KEEPALIVE) != 0); - soap->null = 0; - soap->position = 0; - soap->encoding = 0; - soap->mustUnderstand = 0; - soap->mode = 0; - soap->ns = 0; - soap->part = SOAP_END; - soap->alloced = 0; - soap->count = 0; - soap->length = 0; - soap->cdata = 0; - soap->error = SOAP_OK; - soap->peeked = 0; - soap->ahead = 0; - soap->idnum = 0; - soap->level = 0; - soap->endpoint[0] = '\0'; -#ifndef WITH_LEANER - soap->dime.chunksize = 0; - soap->dime.buflen = 0; -#endif - soap_free_temp(soap); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_end(struct soap *soap) -{ if (soap_check_state(soap)) - return; - soap_free_temp(soap); - soap_dealloc(soap, NULL); - while (soap->clist) - { register struct soap_clist *cp = soap->clist->next; - SOAP_FREE(soap, soap->clist); - soap->clist = cp; - } - soap_closesock(soap); -#ifdef SOAP_DEBUG - soap_close_logfiles(soap); -#endif -#ifdef PALM - palmNetLibClose(); -#endif -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_set_namespaces(struct soap *soap, const struct Namespace *p) -{ register struct Namespace *ns = soap->local_namespaces; - register struct soap_nlist *np, *nq, *nr; - register unsigned int level = soap->level; - soap->namespaces = p; - soap->local_namespaces = NULL; - soap_set_local_namespaces(soap); - /* reverse the namespace list */ - np = soap->nlist; - soap->nlist = NULL; - if (np) - { nq = np->next; - np->next = NULL; - while (nq) - { nr = nq->next; - nq->next = np; - np = nq; - nq = nr; - } - } - /* then push on new stack */ - while (np) - { register const char *s; - soap->level = np->level; /* preserve element nesting level */ - s = np->ns; - if (!s && np->index >= 0 && ns) - { s = ns[np->index].out; - if (!s) - s = ns[np->index].ns; - } - if (s && soap_push_namespace(soap, np->id, s) == NULL) - return soap->error; - nq = np; - np = np->next; - SOAP_FREE(soap, nq); - } - if (ns) - { register int i; - for (i = 0; ns[i].id; i++) - { if (ns[i].out) - { SOAP_FREE(soap, ns[i].out); - ns[i].out = NULL; - } - } - SOAP_FREE(soap, ns); - } - soap->level = level; /* restore level */ - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_set_local_namespaces(struct soap *soap) -{ if (soap->namespaces && !soap->local_namespaces) - { register const struct Namespace *ns1; - register struct Namespace *ns2; - register size_t n = 1; - for (ns1 = soap->namespaces; ns1->id; ns1++) - n++; - n *= sizeof(struct Namespace); - ns2 = (struct Namespace*)SOAP_MALLOC(soap, n); - if (ns2) - { memcpy(ns2, soap->namespaces, n); - if (ns2[0].ns) - { if (!strcmp(ns2[0].ns, soap_env1)) - soap->version = 1; - else - soap->version = 2; - } - soap->local_namespaces = ns2; - } - } -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEAN -#ifndef PALM_1 -SOAP_FMAC1 -const char * -SOAP_FMAC2 -soap_strsearch(const char *big, const char *little) -{ register size_t n = strlen(little); - register const char *s = big; - while (s) - { if (!strncmp(s, little, n) && (s[n] == '\0' || s[n] == ' ')) - return s; - s = strchr(s, ' '); - if (s) - s++; - } - return NULL; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEAN -#ifndef PALM_1 -SOAP_FMAC1 -struct soap_nlist * -SOAP_FMAC2 -soap_lookup_ns(struct soap *soap, const char *tag, size_t n) -{ register struct soap_nlist *np; - for (np = soap->nlist; np; np = np->next) - { if (!strncmp(np->id, tag, n) && !np->id[n]) - return np; - } - return NULL; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEAN -static struct soap_nlist * -soap_push_ns(struct soap *soap, const char *id, const char *ns, short utilized) -{ register struct soap_nlist *np; - size_t n, k; - if (soap_strsearch(soap->c14nexclude, id)) - return NULL; - if (!utilized) - { for (np = soap->nlist; np; np = np->next) - { if (!strcmp(np->id, id) && (!np->ns || !strcmp(np->ns, ns))) - break; - } - if (np) - { if ((np->level < soap->level || !np->ns) && np->index == 1) - utilized = 1; - else - return NULL; - } - } - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Adding namespace binding (level=%u) '%s' '%s' utilized=%d\n", soap->level, id, ns?ns:"(null)", utilized)); - n = strlen(id); - if (ns) - k = strlen(ns); - else - k = 0; - np = (struct soap_nlist*)SOAP_MALLOC(soap, sizeof(struct soap_nlist) + n + k + 1); - if (!np) - { soap->error = SOAP_EOM; - return NULL; - } - np->next = soap->nlist; - soap->nlist = np; - strcpy(np->id, id); - if (ns) - np->ns = strcpy(np->id + n + 1, ns); - else - np->ns = NULL; - np->level = soap->level; - np->index = utilized; - return np; -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEAN -static void -soap_utilize_ns(struct soap *soap, const char *tag, size_t n) -{ register struct soap_nlist *np = soap_lookup_ns(soap, tag, n); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Utilizing namespace of '%s'\n", tag)); - if (np) - { if (np->index == 0) - soap_push_ns(soap, np->id, np->ns, 1); - } - else if (strncmp(tag, "xml", 3)) - { strncpy(soap->tmpbuf, tag, n); - soap->tmpbuf[n] = '\0'; - soap_push_ns(soap, soap->tmpbuf, NULL, 1); - } -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_element(struct soap *soap, const char *tag, int id, const char *type) -{ - register const char *s; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Element begin tag='%s' id='%d' type='%s'\n", tag, id, type?type:SOAP_STR_EOS)); -#ifdef WITH_DOM - if (soap->part == SOAP_BEGIN_SECURITY && (soap->mode & SOAP_XML_CANONICAL) && !(soap->mode & SOAP_DOM_ASIS)) - { register struct soap_nlist *np; - /* wsu:Id found: clear xmlns renderings, so re-emit them for exc-c14n */ - for (np = soap->nlist; np; np = np->next) - { if (np->index == 2) - np->index = 0; - } - } - if (soap->mode & SOAP_XML_DOM) - { register struct soap_dom_element *elt = (struct soap_dom_element*)soap_malloc(soap, sizeof(struct soap_dom_element)); - if (!elt) - return soap->error; - elt->soap = soap; - elt->next = NULL; - elt->prnt = soap->dom; - elt->name = soap_strdup(soap, tag); - elt->elts = NULL; - elt->atts = NULL; - elt->nstr = NULL; - elt->data = NULL; - elt->wide = NULL; - elt->node = NULL; - elt->type = 0; - elt->head = NULL; - elt->tail = NULL; - if (soap->dom) - { struct soap_dom_element *p = soap->dom->elts; - if (p) - { while (p->next) - p = p->next; - p->next = elt; - } - else - soap->dom->elts = elt; - } - soap->dom = elt; - } - else - { -#endif - soap->level++; -#ifndef WITH_LEAN - if (!soap->ns) - { if (!(soap->mode & SOAP_XML_CANONICAL) - && soap_send(soap, soap->prolog ? soap->prolog : "\n")) - return soap->error; - } - else if (soap->mode & SOAP_XML_INDENT) - { if (soap->ns == 1 && soap_send_raw(soap, soap_indent, soap->level < sizeof(soap_indent) ? soap->level : sizeof(soap_indent) - 1)) - return soap->error; - soap->body = 1; - } - if ((soap->mode & SOAP_XML_DEFAULTNS) && (s = strchr(tag, ':'))) - { struct Namespace *ns = soap->local_namespaces; - size_t n = s - tag; - if (soap_send_raw(soap, "<", 1) - || soap_send(soap, s + 1)) - return soap->error; - if (soap->nlist && !strncmp(soap->nlist->id, tag, n) && !soap->nlist->id[n]) - ns = NULL; - for (; ns && ns->id; ns++) - { if (*ns->id && (ns->out || ns->ns) && !strncmp(ns->id, tag, n) && !ns->id[n]) - { soap_push_ns(soap, ns->id, ns->out ? ns->out : ns->ns, 0); - if (soap_attribute(soap, "xmlns", ns->out ? ns->out : ns->ns)) - return soap->error; - break; - } - } - } - else -#endif - if (soap_send_raw(soap, "<", 1) - || soap_send(soap, tag)) - return soap->error; -#ifdef WITH_DOM - } -#endif - if (!soap->ns) - { struct Namespace *ns; - int k = -1; -#ifndef WITH_LEAN - if ((soap->mode & SOAP_XML_DEFAULTNS)) - k = 4; /* only produce the first four required entries */ -#endif - for (ns = soap->local_namespaces; ns && ns->id && k; ns++, k--) - { if (*ns->id && (ns->out || ns->ns)) - { sprintf(soap->tmpbuf, "xmlns:%s", ns->id); - if (soap_attribute(soap, soap->tmpbuf, ns->out ? ns->out : ns->ns)) - return soap->error; - } - } - } - soap->ns = 1; /* namespace table control: ns = 0 or 2 to start, then 1 to stop dumping the table */ -#ifndef WITH_LEAN - if (soap->mode & SOAP_XML_CANONICAL) - { const char *t = strchr(tag, ':'); - if (t) - soap_utilize_ns(soap, tag, t - tag); - } -#endif - if (id > 0) - { sprintf(soap->tmpbuf, "_%d", id); - if (soap_attribute(soap, "id", soap->tmpbuf)) - return soap->error; - } - if (type && *type && (!(soap->mode & SOAP_XML_SEC) || soap->part == SOAP_IN_BODY)) - { if (soap_attribute(soap, "xsi:type", type)) - return soap->error; -#ifndef WITH_LEAN - if (soap->mode & SOAP_XML_CANONICAL) - { const char *t = strchr(type, ':'); - if (t) - soap_utilize_ns(soap, type, t - type); - } -#endif - } - if (soap->null && soap->position > 0) - { register int i; - sprintf(soap->tmpbuf, "[%d", soap->positions[0]); - for (i = 1; i < soap->position; i++) - sprintf(soap->tmpbuf + strlen(soap->tmpbuf), ",%d", soap->positions[i]); - strcat(soap->tmpbuf, "]"); - if (soap_attribute(soap, "SOAP-ENC:position", soap->tmpbuf)) - return soap->error; - } - if (soap->mustUnderstand) - { if (soap->actor && *soap->actor) - { if (soap_attribute(soap, soap->version == 2 ? "SOAP-ENV:role" : "SOAP-ENV:actor", soap->actor)) - return soap->error; - } - if (soap_attribute(soap, "SOAP-ENV:mustUnderstand", soap->version == 2 ? "true" : "1")) - return soap->error; - soap->mustUnderstand = 0; - } - if (soap->encoding) - { if (soap->encodingStyle && soap->local_namespaces) - { if (!*soap->encodingStyle) - { if (soap->local_namespaces[1].out) - soap->encodingStyle = soap->local_namespaces[1].out; - else - soap->encodingStyle = soap->local_namespaces[1].ns; - } - if (soap->encodingStyle && soap_attribute(soap, "SOAP-ENV:encodingStyle", soap->encodingStyle)) - return soap->error; - } - soap->encoding = 0; - } - soap->null = 0; - soap->position = 0; - if (soap->part == SOAP_BEGIN_SECURITY && (soap->mode & SOAP_XML_CANONICAL)) - soap->part = SOAP_IN_SECURITY; - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_element_begin_out(struct soap *soap, const char *tag, int id, const char *type) -{ if (*tag == '-') - return SOAP_OK; - if (soap_element(soap, tag, id, type)) - return soap->error; - return soap_element_start_end_out(soap, NULL); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -#ifndef HAVE_STRRCHR -SOAP_FMAC1 -char* -SOAP_FMAC2 -soap_strrchr(const char *s, int t) -{ register char *r = NULL; - while (*s) - if (*s++ == t) - r = (char*)s - 1; - return r; -} -#endif -#endif - -/******************************************************************************/ -#ifndef PALM_2 -#ifndef HAVE_STRTOL -SOAP_FMAC1 -long -SOAP_FMAC2 -soap_strtol(const char *s, char **t, int b) -{ register long n = 0; - register int c; - while (*s > 0 && *s <= 32) - s++; - if (b == 10) - { short neg = 0; - if (*s == '-') - { s++; - neg = 1; - } - else if (*s == '+') - s++; - while ((c = *s) && c >= '0' && c <= '9') - { if (n >= 214748364 && (n > 214748364 || c >= '8')) - break; - n *= 10; - n += c - '0'; - s++; - } - if (neg) - n = -n; - } - else /* b == 16 and value is always positive */ - { while ((c = *s)) - { if (c >= '0' && c <= '9') - c -= '0'; - else if (c >= 'A' && c <= 'F') - c -= 'A' - 10; - else if (c >= 'a' && c <= 'f') - c -= 'a' - 10; - if (n > 0x07FFFFFF) - break; - n <<= 4; - n += c; - s++; - } - } - if (t) - *t = (char*)s; - return n; -} -#endif -#endif - -/******************************************************************************/ -#ifndef PALM_2 -#ifndef HAVE_STRTOUL -SOAP_FMAC1 -unsigned long -SOAP_FMAC2 -soap_strtoul(const char *s, char **t, int b) -{ unsigned long n = 0; - register int c; - while (*s > 0 && *s <= 32) - s++; - if (b == 10) - { if (*s == '+') - s++; - while ((c = *s) && c >= '0' && c <= '9') - { if (n >= 429496729 && (n > 429496729 || c >= '6')) - break; - n *= 10; - n += c - '0'; - s++; - } - } - else /* b == 16 */ - { while ((c = *s)) - { if (c >= '0' && c <= '9') - c -= '0'; - else if (c >= 'A' && c <= 'F') - c -= 'A' - 10; - else if (c >= 'a' && c <= 'f') - c -= 'a' - 10; - if (n > 0x0FFFFFFF) - break; - n <<= 4; - n += c; - s++; - } - } - if (t) - *t = (char*)s; - return n; -} -#endif -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_array_begin_out(struct soap *soap, const char *tag, int id, const char *type, const char *offset) -{ if (!type || !*type) - return soap_element_begin_out(soap, tag, id, NULL); - if (soap_element(soap, tag, id, "SOAP-ENC:Array")) - return soap->error; - if (soap->version == 2) - { const char *s; - s = soap_strrchr(type, '['); - if ((size_t)(s - type) < sizeof(soap->tmpbuf)) - { strncpy(soap->tmpbuf, type, s - type); - soap->tmpbuf[s - type] = '\0'; - if (soap_attribute(soap, "SOAP-ENC:itemType", soap->tmpbuf)) - return soap->error; - if (s && (soap_attribute(soap, "SOAP-ENC:arraySize", s + 1))) - return soap->error; - } - } - else - { if (offset && soap_attribute(soap, "SOAP-ENC:offset", offset)) - return soap->error; - if (soap_attribute(soap, "SOAP-ENC:arrayType", type)) - return soap->error; - } -#ifndef WITH_LEAN - if ((soap->mode & SOAP_XML_CANONICAL)) - { const char *s = strchr(type, ':'); - if (s) - soap_utilize_ns(soap, type, s - type); - } -#endif - return soap_element_start_end_out(soap, NULL); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_element_start_end_out(struct soap *soap, const char *tag) -{ register struct soap_attribute *tp; -#ifndef WITH_LEAN - if (soap->mode & SOAP_XML_CANONICAL) - { struct soap_nlist *np; - for (tp = soap->attributes; tp; tp = tp->next) - { if (tp->visible && tp->name) - { const char *s = strchr(tp->name, ':'); - if (s) - soap_utilize_ns(soap, tp->name, s - tp->name); - } - } - for (np = soap->nlist; np; np = np->next) - { if (np->index == 1 && np->ns) - { sprintf(soap->tmpbuf, "xmlns:%s", np->id); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Enabling utilized binding (level=%u) %s='%s'\n", np->level, soap->tmpbuf, np->ns)); - soap_set_attr(soap, soap->tmpbuf, np->ns); - np->index = 2; - } - } - } -#endif -#ifdef WITH_DOM - if ((soap->mode & SOAP_XML_DOM) && soap->dom) - { register struct soap_dom_attribute **att; - att = &soap->dom->atts; - for (tp = soap->attributes; tp; tp = tp->next) - { if (tp->visible) - { *att = (struct soap_dom_attribute*)soap_malloc(soap, sizeof(struct soap_dom_attribute)); - if (!*att) - return soap->error; - (*att)->next = NULL; - (*att)->nstr = NULL; - (*att)->name = soap_strdup(soap, tp->name); - (*att)->data = soap_strdup(soap, tp->value); - (*att)->wide = NULL; - (*att)->soap = soap; - att = &(*att)->next; - tp->visible = 0; - } - } - return SOAP_OK; - } -#endif - for (tp = soap->attributes; tp; tp = tp->next) - { if (tp->visible) - { const char *s; -#ifndef WITH_LEAN - if ((soap->mode & SOAP_XML_DEFAULTNS) && (s = strchr(tp->name, ':'))) - { size_t n = s - tp->name; - if (soap->nlist && !strncmp(soap->nlist->id, tp->name, n) && !soap->nlist->id[n]) - s++; - else - s = tp->name; - if (soap_send(soap, " ") || soap_send(soap, s)) - return soap->error; - } - else -#endif - if (soap_send(soap, " ") || soap_send(soap, tp->name)) - return soap->error; - if (tp->visible == 2 && tp->value) - if (soap_send_raw(soap, "=\"", 2) - || soap_string_out(soap, tp->value, 1) - || soap_send_raw(soap, "\"", 1)) - return soap->error; - tp->visible = 0; - } - } - if (tag) - { -#ifndef WITH_LEAN - if (soap->mode & SOAP_XML_CANONICAL) - { if (soap_send_raw(soap, ">", 1) - || soap_element_end_out(soap, tag)) - return soap->error; - return SOAP_OK; - } -#endif - soap->level--; /* decrement level just before /> */ - if (soap_send_raw(soap, "/>", 2)) - return soap->error; - return SOAP_OK; - } - return soap_send_raw(soap, ">", 1); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_element_end_out(struct soap *soap, const char *tag) -{ const char *s; - if (*tag == '-') - return SOAP_OK; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Element ending tag='%s'\n", tag)); -#ifdef WITH_DOM - if ((soap->mode & SOAP_XML_DOM) && soap->dom) - { if (soap->dom->prnt) - soap->dom = soap->dom->prnt; - return SOAP_OK; - } -#endif -#ifndef WITH_LEAN - if (soap->mode & SOAP_XML_CANONICAL) - soap_pop_namespace(soap); - if (soap->mode & SOAP_XML_INDENT) - { if (!soap->body) - { if (soap_send_raw(soap, soap_indent, soap->level < sizeof(soap_indent) ? soap->level : sizeof(soap_indent) - 1)) - return soap->error; - } - soap->body = 0; - } - if ((soap->mode & SOAP_XML_DEFAULTNS) && (s = strchr(tag, ':'))) - { soap_pop_namespace(soap); - tag = s + 1; - } -#endif - if (soap_send_raw(soap, "error; - soap->level--; /* decrement level just before > */ - return soap_send_raw(soap, ">", 1); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_element_ref(struct soap *soap, const char *tag, int id, int href) -{ register int n = 0; - const char *s = "href"; - if (soap->version == 2) - { s = "SOAP-ENC:ref"; - n = 1; - } - sprintf(soap->href, "#_%d", href); - return soap_element_href(soap, tag, id, s, soap->href + n); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_element_href(struct soap *soap, const char *tag, int id, const char *ref, const char *val) -{ DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Element '%s' reference %s='%s'\n", tag, ref, val)); - if (soap_element(soap, tag, id, NULL) - || soap_attribute(soap, ref, val) - || soap_element_start_end_out(soap, tag)) - return soap->error; - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_element_null(struct soap *soap, const char *tag, int id, const char *type) -{ struct soap_attribute *tp; - for (tp = soap->attributes; tp; tp = tp->next) - if (tp->visible) - break; - if (tp || (soap->version == 2 && soap->position > 0) || id > 0 || (soap->mode & SOAP_XML_NIL)) - { if (soap_element(soap, tag, id, type)) - return soap->error; - if (!tp && soap_attribute(soap, "xsi:nil", "true")) - return soap->error; - return soap_element_start_end_out(soap, tag); - } - soap->null = 1; - soap->position = 0; - soap->mustUnderstand = 0; - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_element_id(struct soap *soap, const char *tag, int id, const void *p, const struct soap_array *a, int n, const char *type, int t) -{ if (!p) - { soap_element_null(soap, tag, id, type); - return -1; - } -#ifndef WITH_NOIDREF - if (soap->mode & SOAP_XML_TREE) - return 0; - if (id < 0) - { struct soap_plist *pp; - if (a) - id = soap_array_pointer_lookup(soap, p, a, n, t, &pp); - else - id = soap_pointer_lookup(soap, p, t, &pp); - if (id) - { if (soap_is_embedded(soap, pp)) - { soap_element_ref(soap, tag, 0, id); - return -1; - } - if (soap_is_single(soap, pp)) - return 0; - soap_set_embedded(soap, pp); - } - } - return id; -#else - return 0; -#endif -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_element_result(struct soap *soap, const char *tag) -{ if (soap->version == 2 && soap->encodingStyle) - { if (soap_element(soap, "SOAP-RPC:result", 0, NULL) - || soap_attribute(soap, "xmlns:SOAP-RPC", soap_rpc) - || soap_element_start_end_out(soap, NULL) - || soap_string_out(soap, tag, 0) - || soap_element_end_out(soap, "SOAP-RPC:result")) - return soap->error; - } - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_check_result(struct soap *soap, const char *tag) -{ if (soap->version == 2 && soap->encodingStyle) - { soap_instring(soap, ":result", NULL, NULL, 0, 2, -1, -1); - /* just ignore content for compliance reasons, but should compare tag to element's QName value? */ - } -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_attribute(struct soap *soap, const char *name, const char *value) -{ - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Attribute '%s'='%s'\n", name, value)); -#ifdef WITH_DOM - if ((soap->mode & SOAP_XML_DOM) && !(soap->mode & SOAP_XML_CANONICAL) && soap->dom) - { register struct soap_dom_attribute *a = (struct soap_dom_attribute*)soap_malloc(soap, sizeof(struct soap_dom_attribute)); - if (!a) - return soap->error; - a->next = soap->dom->atts; - a->nstr = NULL; - a->name = soap_strdup(soap, name); - a->data = soap_strdup(soap, value); - a->wide = NULL; - a->soap = soap; - soap->dom->atts = a; - return SOAP_OK; - } -#endif -#ifndef WITH_LEAN - if (soap->mode & SOAP_XML_CANONICAL) - { /* TODO: consider using this code to handle default namespace bindings - if (!strncmp(name, "xmlns", 5) && (name[5] == ':' || name[5] == '\0')) - { if (name[5] == ':') - soap_push_ns(soap, name + 6, value, 0); - else - soap_push_ns(soap, "", value, 0); - } - */ - if (!strncmp(name, "xmlns:", 6)) - soap_push_ns(soap, name + 6, value, 0); - else if (soap_set_attr(soap, name, value)) - return soap->error; - } - else -#endif - { if (soap_send(soap, " ") || soap_send(soap, name)) - return soap->error; - if (value) - if (soap_send_raw(soap, "=\"", 2) - || soap_string_out(soap, value, 1) - || soap_send_raw(soap, "\"", 1)) - return soap->error; - } - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_element_begin_in(struct soap *soap, const char *tag, int nillable, const char *type) -{ if (!soap_peek_element(soap)) - { if (soap->other) - return soap->error = SOAP_TAG_MISMATCH; - if (tag && *tag == '-') - return SOAP_OK; - if (!(soap->error = soap_match_tag(soap, soap->tag, tag))) - { soap->peeked = 0; - if (type && *soap->type && soap_match_tag(soap, soap->type, type)) - return soap->error = SOAP_TYPE; - if (!nillable && soap->null && (soap->mode & SOAP_XML_STRICT)) - return soap->error = SOAP_NULL; - if (soap->body) - soap->level++; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Begin element found (level=%u) '%s'='%s'\n", soap->level, soap->tag, tag?tag:SOAP_STR_EOS )); - } - } - else if (soap->error == SOAP_NO_TAG && tag && *tag == '-') - soap->error = SOAP_OK; - return soap->error; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_element_end_in(struct soap *soap, const char *tag) -{ register soap_wchar c; - register char *s; - register int n = 0; - if (tag && *tag == '-') - return SOAP_OK; - if (soap->error == SOAP_NO_TAG) - soap->error = SOAP_OK; -#ifdef WITH_DOM - /* this whitespace or mixed content is not insignificant for DOM */ - if ((soap->mode & SOAP_XML_DOM) && soap->dom) - { if (!soap->peeked && !soap_string_in(soap, 3, -1, -1)) - return soap->error; - if (soap->dom->prnt) - soap->dom = soap->dom->prnt; - } -#endif - if (soap->peeked) - { if (*soap->tag) - n++; - soap->peeked = 0; - } - do - { while (((c = soap_get(soap)) != SOAP_TT)) - { if ((int)c == EOF) - return soap->error = SOAP_EOF; - if (c == SOAP_LT) - n++; - else if (c == '/') - { c = soap_get(soap); - if (c == SOAP_GT) - n--; - else - soap_unget(soap, c); - } - } - } while (n--); - s = soap->tag; - n = sizeof(soap->tag); - while (soap_notblank(c = soap_get(soap))) - { if (--n > 0) - *s++ = (char)c; - } - *s = '\0'; - if ((int)c == EOF) - return soap->error = SOAP_EOF; - while (soap_blank(c)) - c = soap_get(soap); - if (c != SOAP_GT) - return soap->error = SOAP_SYNTAX_ERROR; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "End element found (level=%u) '%s'='%s'\n", soap->level, soap->tag, tag?tag:SOAP_STR_EOS)); -#ifndef WITH_LEAN - if (tag && (soap->mode & SOAP_XML_STRICT)) - { soap_pop_namespace(soap); - if (soap_match_tag(soap, soap->tag, tag)) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "End element tag name does not match\n")); - return soap->error = SOAP_SYNTAX_ERROR; - } - } -#endif - soap->level--; - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -const char * -SOAP_FMAC2 -soap_attr_value(struct soap *soap, const char *name, int flag) -{ register struct soap_attribute *tp; - if (*name == '-') - return SOAP_STR_EOS; - for (tp = soap->attributes; tp; tp = tp->next) - { if (tp->visible && !soap_match_tag(soap, tp->name, name)) - break; - } - if (tp) - { if (flag == 2 && (soap->mode & SOAP_XML_STRICT)) - soap->error = SOAP_PROHIBITED; - else - return tp->value; - } - else if (flag == 1 && (soap->mode & SOAP_XML_STRICT)) - soap->error = SOAP_REQUIRED; - else - soap->error = SOAP_OK; - return NULL; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_set_attr(struct soap *soap, const char *name, const char *value) -{ register struct soap_attribute *tp; - if (*name == '-') - return SOAP_OK; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Set attribute %s='%s'\n", name, value?value:SOAP_STR_EOS)); - for (tp = soap->attributes; tp; tp = tp->next) - { if (!strcmp(tp->name, name)) - break; - } - if (!tp) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Allocate attribute %s\n", name)); - if (!(tp = (struct soap_attribute*)SOAP_MALLOC(soap, sizeof(struct soap_attribute) + strlen(name)))) - return soap->error = SOAP_EOM; - tp->ns = NULL; -#ifndef WITH_LEAN - if (soap->mode & SOAP_XML_CANONICAL) - { struct soap_attribute **tpp = &soap->attributes; - const char *s = strchr(name, ':'); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Inserting attribute %s for c14n\n", name)) - if (!strncmp(name, "xmlns", 5)) - { for (; *tpp; tpp = &(*tpp)->next) - if (strncmp((*tpp)->name, "xmlns", 5) || strcmp((*tpp)->name + 5, name + 5) > 0) - break; - } - else if (!s) - { for (; *tpp; tpp = &(*tpp)->next) - if (strncmp((*tpp)->name, "xmlns", 5) && ((*tpp)->ns || strcmp((*tpp)->name, name) > 0)) - break; - } - else - { int k; - for (; *tpp; tpp = &(*tpp)->next) - { if (!strncmp((*tpp)->name, "xmlns:", 6) && !strncmp((*tpp)->name + 6, name, s - name) && !(*tpp)->name[6 + s - name]) - { if (!tp->ns) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Canonicalization: prefix %s=%p (%s)\n", name, (*tpp)->ns, (*tpp)->ns)); - tp->ns = (*tpp)->ns; - } - } - else if (strncmp((*tpp)->name, "xmlns", 5) && (*tpp)->ns && tp->ns && ((k = strcmp((*tpp)->ns, tp->ns)) > 0 || (!k && strcmp((*tpp)->name, name) > 0))) - break; - } - } - tp->next = *tpp; - *tpp = tp; - } - else -#endif - { tp->next = soap->attributes; - soap->attributes = tp; - } - strcpy(tp->name, name); - tp->value = NULL; - } - else if (tp->visible) - { return SOAP_OK; - } - else if (value && tp->value && tp->size <= strlen(value)) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Free attribute value of %s (free %p)\n", name, tp->value)); - SOAP_FREE(soap, tp->value); - tp->value = NULL; - tp->ns = NULL; - } - if (value) - { if (!tp->value) - { tp->size = strlen(value) + 1; - if (!(tp->value = (char*)SOAP_MALLOC(soap, tp->size))) - return soap->error = SOAP_EOM; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Allocate attribute value for %s (%p)\n", tp->name, tp->value)); - } - strcpy(tp->value, value); - if (!strncmp(tp->name, "xmlns:", 6)) - tp->ns = tp->value; - tp->visible = 2; -#ifndef WITH_LEAN - if (!strcmp(name, "wsu:Id")) - { soap->part = SOAP_BEGIN_SECURITY; - strncpy(soap->id, value, sizeof(soap->id)); - soap->id[sizeof(soap->id)-1] = '\0'; - } -#endif - } - else - tp->visible = 1; - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_clr_attr(struct soap *soap) -{ register struct soap_attribute *tp; -#ifndef WITH_LEAN - if ((soap->mode & SOAP_XML_CANONICAL)) - { while (soap->attributes) - { tp = soap->attributes->next; - if (soap->attributes->value) - SOAP_FREE(soap, soap->attributes->value); - SOAP_FREE(soap, soap->attributes); - soap->attributes = tp; - } - } - else -#endif - { for (tp = soap->attributes; tp; tp = tp->next) - tp->visible = 0; - } -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -static int -soap_getattrval(struct soap *soap, char *s, size_t n, soap_wchar d) -{ register size_t i; - for (i = 0; i < n; i++) - { register soap_wchar c = soap_get(soap); - switch (c) - { - case SOAP_TT: - *s++ = '<'; - soap_unget(soap, '/'); - break; - case SOAP_LT: - *s++ = '<'; - break; - case SOAP_GT: - if (d == ' ') - { soap_unget(soap, c); - *s = '\0'; - return SOAP_OK; - } - *s++ = '>'; - break; - case SOAP_QT: - if (c == d) - { *s = '\0'; - return SOAP_OK; - } - *s++ = '"'; - break; - case SOAP_AP: - if (c == d) - { *s = '\0'; - return SOAP_OK; - } - *s++ = '\''; - break; - case '\t': - case '\n': - case '\r': - case ' ': - case '/': - if (d == ' ') - { soap_unget(soap, c); - *s = '\0'; - return SOAP_OK; - } - default: - if ((int)c == EOF) - return soap->error = SOAP_EOF; - *s++ = (char)c; - } - } - return soap->error = SOAP_EOM; -} -#endif - -/******************************************************************************/ -#ifdef WITH_FAST -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_store_lab(struct soap *soap, const char *s, size_t n) -{ soap->labidx = 0; - return soap_append_lab(soap, s, n); -} -#endif -#endif - -/******************************************************************************/ -#ifdef WITH_FAST -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_append_lab(struct soap *soap, const char *s, size_t n) -{ if (soap->labidx + n >= soap->lablen) - { register char *t = soap->labbuf; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Enlarging look-aside buffer to append data, old size=%lu", (unsigned long)soap->lablen)); - if (soap->lablen == 0) - soap->lablen = SOAP_LABLEN; - while (soap->labidx + n >= soap->lablen) - soap->lablen <<= 1; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, ", new size=%lu\n", (unsigned long)soap->lablen)); - soap->labbuf = (char*)SOAP_MALLOC(soap, soap->lablen); - if (!soap->labbuf) - { if (t) - SOAP_FREE(soap, t); - return soap->error = SOAP_EOM; - } - if (t) - { memcpy(soap->labbuf, t, soap->labidx); - SOAP_FREE(soap, t); - } - } - if (s) - { memcpy(soap->labbuf + soap->labidx, s, n); - soap->labidx += n; - } - return SOAP_OK; -} -#endif -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_peek_element(struct soap *soap) -{ -#ifdef WITH_DOM - register struct soap_dom_attribute **att = NULL; - register char *lead = NULL; -#endif - register struct soap_attribute *tp, *tq = NULL; - register const char *t; - register char *s; - register soap_wchar c; - register int i; - if (soap->peeked) - { if (!*soap->tag) - return soap->error = SOAP_NO_TAG; - return SOAP_OK; - } - soap->peeked = 1; - soap->id[0] = '\0'; - soap->href[0] = '\0'; - soap->type[0] = '\0'; - soap->arrayType[0] = '\0'; - soap->arraySize[0] = '\0'; - soap->arrayOffset[0] = '\0'; - soap->other = 0; - soap->root = -1; - soap->position = 0; - soap->null = 0; - soap->mustUnderstand = 0; - /* skip BOM */ - if ((c = soap_getchar(soap)) != 0xEF || (c = soap_get1(soap)) != 0xBB || (c = soap_get1(soap)) != 0xBF) - soap_unget(soap, c); - c = soap_get(soap); -#ifdef WITH_DOM - /* whitespace leading to start tag is not insignificant for DOM */ - if (soap_blank(c)) - { soap->labidx = 0; - do - { if (soap_append_lab(soap, NULL, 0)) - return soap->error; - s = soap->labbuf + soap->labidx; - i = soap->lablen - soap->labidx; - soap->labidx = soap->lablen; - while (soap_blank(c) && i--) - { *s++ = c; - c = soap_get(soap); - } - } - while (soap_blank(c)); - *s = '\0'; - if (*soap->labbuf) - lead = soap->labbuf; - } -#else - /* skip space */ - while (soap_blank(c)) - c = soap_get(soap); -#endif - if (c != SOAP_LT) - { *soap->tag = '\0'; - if ((int)c == EOF) - return soap->error = SOAP_EOF; - soap_unget(soap, c); -#ifdef WITH_DOM - /* whitespace leading to end tag is not insignificant for DOM */ - if ((soap->mode & SOAP_XML_DOM) && soap->dom) - soap->dom->tail = soap_strdup(soap, lead); -#endif - return soap->error = SOAP_NO_TAG; - } - s = soap->tag; - do c = soap_get1(soap); - while (soap_blank(c)); - i = sizeof(soap->tag); - while (c != '>' && c != '/' && soap_notblank(c) && (int)c != EOF) - { if (--i > 0) - *s++ = (char)c; - c = soap_get1(soap); - } - while (soap_blank(c)) - c = soap_get1(soap); - *s = '\0'; -#ifdef WITH_DOM - if (soap->mode & SOAP_XML_DOM) - { register struct soap_dom_element *elt; - elt = (struct soap_dom_element*)soap_malloc(soap, sizeof(struct soap_dom_element)); - if (!elt) - return soap->error; - elt->next = NULL; - elt->nstr = NULL; - elt->name = soap_strdup(soap, soap->tag); - elt->prnt = soap->dom; - elt->elts = NULL; - elt->atts = NULL; - elt->data = NULL; - elt->wide = NULL; - elt->type = 0; - elt->node = NULL; - elt->head = soap_strdup(soap, lead); - elt->tail = NULL; - elt->soap = soap; - if (soap->dom) - { struct soap_dom_element *p = soap->dom->elts; - if (p) - { while (p->next) - p = p->next; - p->next = elt; - } - else - soap->dom->elts = elt; - } - soap->dom = elt; - att = &elt->atts; - } -#endif - soap_pop_namespace(soap); - for (tp = soap->attributes; tp; tp = tp->next) - tp->visible = 0; - while ((int)c != EOF && c != '>' && c != '/') - { s = soap->tmpbuf; - i = sizeof(soap->tmpbuf); - while (c != '=' && c != '>' && c != '/' && soap_notblank(c) && (int)c != EOF) - { if (--i > 0) - *s++ = (char)c; - c = soap_get1(soap); - } - *s = '\0'; - if (i == sizeof(soap->tmpbuf)) - return soap->error = SOAP_SYNTAX_ERROR; -#ifdef WITH_DOM - /* add attribute name to dom */ - if (att) - { *att = (struct soap_dom_attribute*)soap_malloc(soap, sizeof(struct soap_dom_attribute)); - if (!*att) - return soap->error; - (*att)->next = NULL; - (*att)->nstr = NULL; - (*att)->name = soap_strdup(soap, soap->tmpbuf); - (*att)->data = NULL; - (*att)->wide = NULL; - (*att)->soap = soap; - } -#endif - if (!strncmp(soap->tmpbuf, "xmlns", 5)) - { if (soap->tmpbuf[5] == ':') - t = soap->tmpbuf + 6; - else if (soap->tmpbuf[5]) - t = NULL; - else - t = SOAP_STR_EOS; - } - else - t = NULL; - tq = NULL; - for (tp = soap->attributes; tp; tq = tp, tp = tp->next) - { if (!SOAP_STRCMP(tp->name, soap->tmpbuf)) - break; - } - if (!tp) - { tp = (struct soap_attribute*)SOAP_MALLOC(soap, sizeof(struct soap_attribute) + strlen(soap->tmpbuf)); - if (!tp) - return soap->error = SOAP_EOM; - strcpy(tp->name, soap->tmpbuf); - tp->value = NULL; - tp->size = 0; - /* if attribute name is qualified, append it to the end of the list */ - if (tq && strchr(soap->tmpbuf, ':')) - { tq->next = tp; - tp->next = NULL; - } - else - { tp->next = soap->attributes; - soap->attributes = tp; - } - } - while (soap_blank(c)) - c = soap_get1(soap); - if (c == '=') - { do c = soap_getutf8(soap); - while (soap_blank(c)); - if (c != SOAP_QT && c != SOAP_AP) - { soap_unget(soap, c); - c = ' '; /* blank delimiter */ - } - if (soap_getattrval(soap, tp->value, tp->size, c)) - { -#ifdef WITH_FAST - if (soap->error != SOAP_EOM) - return soap->error; - soap->error = SOAP_OK; - if (soap_store_lab(soap, tp->value, tp->size)) - return soap->error; - if (tp->value) - SOAP_FREE(soap, tp->value); - for (;;) - { if (soap_getattrval(soap, soap->labbuf + soap->labidx, soap->lablen - soap->labidx, c)) - { if (soap->error != SOAP_EOM) - return soap->error; - soap->error = SOAP_OK; - soap->labidx = soap->lablen; - if (soap_append_lab(soap, NULL, 0)) - return soap->error; - } - else - break; - } - if (soap->labidx) - tp->size = soap->lablen; - else - { tp->size = strlen(soap->labbuf) + 1; - if (tp->size < SOAP_LABLEN) - tp->size = SOAP_LABLEN; - } - if (!(tp->value = (char*)SOAP_MALLOC(soap, tp->size))) - return soap->error = SOAP_EOM; - strcpy(tp->value, soap->labbuf); -#else - size_t n; - if (soap->error != SOAP_EOM) - return soap->error; - soap->error = SOAP_OK; - if (soap_new_block(soap) == NULL) - return soap->error; - for (;;) - { if (!(s = (char*)soap_push_block(soap, NULL, SOAP_BLKLEN))) - return soap->error; - if (soap_getattrval(soap, s, SOAP_BLKLEN, c)) - { if (soap->error != SOAP_EOM) - return soap->error; - soap->error = SOAP_OK; - } - else - break; - } - n = tp->size + soap->blist->size; - if (!(s = (char*)SOAP_MALLOC(soap, n))) - return soap->error = SOAP_EOM; - if (tp->value) - { memcpy(s, tp->value, tp->size); - SOAP_FREE(soap, tp->value); - } - soap_save_block(soap, NULL, s + tp->size, 0); - tp->value = s; - tp->size = n; -#endif - } - do c = soap_get1(soap); - while (soap_blank(c)); - tp->visible = 2; /* seen this attribute w/ value */ -#ifdef WITH_DOM - if (att) - (*att)->data = soap_strdup(soap, tp->value); -#endif - } - else - tp->visible = 1; /* seen this attribute w/o value */ -#ifdef WITH_DOM - if (att) - att = &(*att)->next; -#endif - if (t && tp->value) - { if (soap_push_namespace(soap, t, tp->value) == NULL) - return soap->error; - } - } -#ifdef WITH_DOM - if (att) - { soap->dom->nstr = soap_current_namespace(soap, soap->tag); - for (att = &soap->dom->atts; *att; att = &(*att)->next) - (*att)->nstr = soap_current_namespace(soap, (*att)->name); - } -#endif - if ((int)c == EOF) - return soap->error = SOAP_EOF; - if (!(soap->body = (c != '/'))) - do c = soap_get1(soap); - while (soap_blank(c)); -#ifdef WITH_DOM - if (soap->mode & SOAP_XML_DOM) - { if (!soap->body && soap->dom->prnt) - soap->dom = soap->dom->prnt; - } -#endif - for (tp = soap->attributes; tp; tp = tp->next) - { if (tp->visible && tp->value) - { -#ifndef WITH_NOIDREF - if (!strcmp(tp->name, "id")) - { if ((soap->version > 0 && !(soap->mode & SOAP_XML_TREE)) - || (soap->mode & SOAP_XML_GRAPH)) - { *soap->id = '#'; - strncpy(soap->id + 1, tp->value, sizeof(soap->id) - 2); - soap->id[sizeof(soap->id)-1] = '\0'; - } - } - else if (!strcmp(tp->name, "href")) - { if (soap->version == 1 - || (soap->mode & SOAP_XML_GRAPH) - || (soap->mode & SOAP_ENC_MTOM) - || (soap->mode & SOAP_ENC_DIME)) - { strncpy(soap->href, tp->value, sizeof(soap->href) - 1); - soap->href[sizeof(soap->href)-1] = '\0'; - } - } - else -#endif - if (!soap_match_tag(soap, tp->name, "xsi:type")) - { strncpy(soap->type, tp->value, sizeof(soap->type) - 1); - soap->type[sizeof(soap->type)-1] = '\0'; - } - else if ((!soap_match_tag(soap, tp->name, "xsi:null") - || !soap_match_tag(soap, tp->name, "xsi:nil")) - && (!strcmp(tp->value, "1") - || !strcmp(tp->value, "true"))) - { soap->null = 1; - } - else if (soap->version == 1) - { if (!soap_match_tag(soap, tp->name, "SOAP-ENC:arrayType")) - { s = soap_strrchr(tp->value, '['); - if (s && (size_t)(s - tp->value) < sizeof(soap->arrayType)) - { strncpy(soap->arrayType, tp->value, s - tp->value); - soap->arrayType[s - tp->value] = '\0'; - strncpy(soap->arraySize, s, sizeof(soap->arraySize) - 1); - } - else - strncpy(soap->arrayType, tp->value, sizeof(soap->arrayType) - 1); - soap->arraySize[sizeof(soap->arrayType)-1] = '\0'; - soap->arrayType[sizeof(soap->arrayType)-1] = '\0'; - } - else if (!soap_match_tag(soap, tp->name, "SOAP-ENC:offset")) - strncpy(soap->arrayOffset, tp->value, sizeof(soap->arrayOffset)); - else if (!soap_match_tag(soap, tp->name, "SOAP-ENC:position")) - soap->position = soap_getposition(tp->value, soap->positions); - else if (!soap_match_tag(soap, tp->name, "SOAP-ENC:root")) - soap->root = ((!strcmp(tp->value, "1") || !strcmp(tp->value, "true"))); - else if (!soap_match_tag(soap, tp->name, "SOAP-ENV:mustUnderstand") - && (!strcmp(tp->value, "1") || !strcmp(tp->value, "true"))) - soap->mustUnderstand = 1; - else if (!soap_match_tag(soap, tp->name, "SOAP-ENV:actor")) - { if ((!soap->actor || strcmp(soap->actor, tp->value)) - && strcmp(tp->value, "http://schemas.xmlsoap.org/soap/actor/next")) - soap->other = 1; - } - } - else if (soap->version == 2) - { -#ifndef WITH_NOIDREF - if (!strcmp(tp->name, "ref") - || !soap_match_tag(soap, tp->name, "SOAP-ENC:ref")) - { *soap->href = '#'; - strncpy(soap->href + 1, tp->value, sizeof(soap->href) - 2); - soap->href[sizeof(soap->href)-1] = '\0'; - } - else -#endif - if (!soap_match_tag(soap, tp->name, "SOAP-ENC:itemType")) - strncpy(soap->arrayType, tp->value, sizeof(soap->arrayType) - 1); - else if (!soap_match_tag(soap, tp->name, "SOAP-ENC:arraySize")) - strncpy(soap->arraySize, tp->value, sizeof(soap->arraySize) - 1); - else if (!soap_match_tag(soap, tp->name, "SOAP-ENV:mustUnderstand") - && (!strcmp(tp->value, "1") || !strcmp(tp->value, "true"))) - soap->mustUnderstand = 1; - else if (!soap_match_tag(soap, tp->name, "SOAP-ENV:role")) - { if ((!soap->actor || strcmp(soap->actor, tp->value)) - && strcmp(tp->value, "http://www.w3.org/2003/05/soap-envelope/role/next")) - soap->other = 1; - } - } - else - { if (!soap_match_tag(soap, tp->name, "wsdl:required") && !strcmp(tp->value, "true")) - soap->mustUnderstand = 1; - } - } - } - return soap->error = SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_retry(struct soap *soap) -{ soap->error = SOAP_OK; - soap_revert(soap); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_revert(struct soap *soap) -{ if (!soap->peeked) - { soap->peeked = 1; - if (soap->body) - soap->level--; - } - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Reverting last element (level=%u)\n", soap->level)); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_string_out(struct soap *soap, const char *s, int flag) -{ register const char *t; - register soap_wchar c; - register soap_wchar mask = (soap_wchar)0xFFFFFF80UL; -#ifdef WITH_DOM - if ((soap->mode & SOAP_XML_DOM) && soap->dom) - { soap->dom->data = soap_strdup(soap, s); - return SOAP_OK; - } -#endif - if (soap->mode & SOAP_C_UTFSTRING) - mask = 0; - t = s; - while ((c = *t++)) - { switch (c) - { - case 0x09: - if (flag) - { if (soap_send_raw(soap, s, t - s - 1) || soap_send_raw(soap, " ", 5)) - return soap->error; - s = t; - } - break; - case 0x0A: - if (flag || !(soap->mode & SOAP_XML_CANONICAL)) - { if (soap_send_raw(soap, s, t - s - 1) || soap_send_raw(soap, " ", 5)) - return soap->error; - s = t; - } - break; - case 0x0D: - if (soap_send_raw(soap, s, t - s - 1) || soap_send_raw(soap, " ", 5)) - return soap->error; - s = t; - break; - case '&': - if (soap_send_raw(soap, s, t - s - 1) || soap_send_raw(soap, "&", 5)) - return soap->error; - s = t; - break; - case '<': - if (soap_send_raw(soap, s, t - s - 1) || soap_send_raw(soap, "<", 4)) - return soap->error; - s = t; - break; - case '>': - if (!flag) - { if (soap_send_raw(soap, s, t - s - 1) || soap_send_raw(soap, ">", 4)) - return soap->error; - s = t; - } - break; - case '"': - if (flag) - { if (soap_send_raw(soap, s, t - s - 1) || soap_send_raw(soap, """, 6)) - return soap->error; - s = t; - } - break; - default: -#ifndef WITH_LEANER -#ifdef HAVE_MBTOWC - if (soap->mode & SOAP_C_MBSTRING) - { wchar_t wc; - register int m = mbtowc(&wc, t - 1, MB_CUR_MAX); - if (m > 0 && wc != c) - { if (soap_send_raw(soap, s, t - s - 1) || soap_pututf8(soap, wc)) - return soap->error; - s = t += m - 1; - continue; - } - } -#endif -#endif -#ifndef WITH_NOSTRINGTOUTF8 - if ((c & mask) || !(c & 0xFFFFFFE0UL)) - { if (soap_send_raw(soap, s, t - s - 1) || soap_pututf8(soap, (unsigned char)c)) - return soap->error; - s = t; - } -#endif - } - } - return soap_send_raw(soap, s, t - s - 1); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -char * -SOAP_FMAC2 -soap_string_in(struct soap *soap, int flag, long minlen, long maxlen) -{ register char *s; - char *t = NULL; - register size_t i; - register long l = 0; - register int n = 0, f = 0, m = 0; - register soap_wchar c; -#if !defined(WITH_LEANER) && defined(HAVE_WCTOMB) - char buf[MB_LEN_MAX > 8 ? MB_LEN_MAX : 8]; -#else - char buf[8]; -#endif - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Reading string content, flag=%d\n", flag)); - if (soap->peeked && *soap->tag) - { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "String content includes tag '%s' and attributes\n", soap->tag)); -#ifndef WITH_LEAN - struct soap_attribute *tp; - t = soap->tmpbuf; - *t = '<'; - t[sizeof(soap->tmpbuf)-1] = '\0'; - strncpy(t + 1, soap->tag, sizeof(soap->tmpbuf) - 2); - t += strlen(t); - for (tp = soap->attributes; tp; tp = tp->next) - { if (tp->visible) - { if (t >= soap->tmpbuf + sizeof(soap->tmpbuf) - 2) - break; - *t++ = ' '; - strcpy(t, tp->name); - t += strlen(t); - if (t >= soap->tmpbuf + sizeof(soap->tmpbuf) - 2) - break; /* too many or large attribute values */ - if (tp->value) - { *t++ = '='; - *t++ = '"'; - strcpy(t, tp->value); - t += strlen(t); - *t++ = '"'; - } - } - } - if (!soap->body) - *t++ = '/'; - *t++ = '>'; - *t = '\0'; - t = soap->tmpbuf; - m = (int)strlen(soap->tmpbuf); -#endif - if (soap->body) - n = 1; - f = 1; - soap->peeked = 0; - } -#ifdef WITH_CDATA - if (!flag) - { register int state = 0; -#ifdef WITH_FAST - soap->labidx = 0; /* use look-aside buffer */ -#else - if (soap_new_block(soap) == NULL) - return NULL; -#endif - for (;;) - { -#ifdef WITH_FAST - register size_t k; - if (soap_append_lab(soap, NULL, 0)) /* allocate more space in look-aside buffer if necessary */ - return NULL; - s = soap->labbuf + soap->labidx; /* space to populate */ - k = soap->lablen - soap->labidx; /* number of bytes available */ - soap->labidx = soap->lablen; /* claim this space */ -#else - register size_t k = SOAP_BLKLEN; - if (!(s = (char*)soap_push_block(soap, NULL, k))) - return NULL; -#endif - for (i = 0; i < k; i++) - { if (m > 0) - { *s++ = *t++; /* copy multibyte characters */ - m--; - continue; - } - c = soap_getchar(soap); - if ((int)c == EOF) - goto end; - if (c >= 0x80 && state != 1 && !(soap->mode & SOAP_ENC_LATIN)) - { soap_unget(soap, c); - c = soap_getutf8(soap); - if (soap->mode & SOAP_C_UTFSTRING) - { c &= 0x7FFFFFFF; - t = buf; - if (c < 0x0800) - *t++ = (char)(0xC0 | ((c >> 6) & 0x1F)); - else - { if (c < 0x010000) - *t++ = (char)(0xE0 | ((c >> 12) & 0x0F)); - else - { if (c < 0x200000) - *t++ = (char)(0xF0 | ((c >> 18) & 0x07)); - else - { if (c < 0x04000000) - *t++ = (char)(0xF8 | ((c >> 24) & 0x03)); - else - { *t++ = (char)(0xFC | ((c >> 30) & 0x01)); - *t++ = (char)(0x80 | ((c >> 24) & 0x3F)); - } - *t++ = (char)(0x80 | ((c >> 18) & 0x3F)); - } - *t++ = (char)(0x80 | ((c >> 12) & 0x3F)); - } - *t++ = (char)(0x80 | ((c >> 6) & 0x3F)); - } - *t++ = (char)(0x80 | (c & 0x3F)); - m = (int)(t - buf) - 1; - t = buf; - *s++ = *t++; - continue; - } - } - switch (state) - { case 1: - if (c == ']') - state = 4; - *s++ = c; - continue; - case 2: - if (c == '-') - state = 6; - *s++ = c; - continue; - case 3: - if (c == '?') - state = 8; - *s++ = c; - continue; - /* CDATA */ - case 4: - if (c == ']') - state = 5; - else - state = 1; - *s++ = c; - continue; - case 5: - if (c == '>') - state = 0; - else - state = 1; - *s++ = c; - continue; - /* comment */ - case 6: - if (c == '-') - state = 7; - else - state = 2; - *s++ = c; - continue; - case 7: - if (c == '>') - state = 0; - else - state = 2; - *s++ = c; - continue; - /* PI */ - case 8: - if (c == '>') - state = 0; - else - state = 3; - *s++ = c; - continue; - } - switch (c) - { - case SOAP_TT: - if (n == 0) - goto end; - n--; - *s++ = '<'; - t = (char*)"/"; - m = 1; - break; - case SOAP_LT: - if (f && n == 0) - goto end; - n++; - *s++ = '<'; - break; - case '/': - if (n > 0) - { c = soap_getchar(soap); - if (c == '>') - n--; - soap_unget(soap, c); - } - *s++ = '/'; - break; - case '<': - c = soap_getchar(soap); - if (c == '/') - { if (n == 0) - { c = SOAP_TT; - goto end; - } - n--; - } - else if (c == '!') - { c = soap_getchar(soap); - if (c == '[') - { do c = soap_getchar(soap); - while ((int)c != EOF && c != '['); - if ((int)c == EOF) - goto end; - t = (char*)"![CDATA["; - m = 8; - state = 1; - } - else if (c == '-') - { if ((c = soap_getchar(soap)) == '-') - state = 2; - t = (char*)"!-"; - m = 2; - soap_unget(soap, c); - } - else - { t = (char*)"!"; - m = 1; - soap_unget(soap, c); - } - *s++ = '<'; - break; - } - else if (c == '?') - state = 3; - else if (f && n == 0) - { soap_revget1(soap); - c = '<'; - goto end; - } - else - n++; - soap_unget(soap, c); - *s++ = '<'; - break; - case '>': - *s++ = '>'; - break; - case '"': - *s++ = '"'; - break; - default: -#ifndef WITH_LEANER -#ifdef HAVE_WCTOMB - if (soap->mode & SOAP_C_MBSTRING) - { m = wctomb(buf, c & 0x7FFFFFFF); - if (m >= 1 && m <= (int)MB_CUR_MAX) - { t = buf; - *s++ = *t++; - m--; - } - else - { *s++ = SOAP_UNKNOWN_CHAR; - m = 0; - } - } - else -#endif -#endif - *s++ = (char)(c & 0xFF); - } - l++; - if ((soap->mode & SOAP_XML_STRICT) && maxlen >= 0 && l > maxlen) - { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "String too long: maxlen=%ld\n", maxlen)); - soap->error = SOAP_LENGTH; - return NULL; - } - } - } - } -#endif -#ifdef WITH_FAST - soap->labidx = 0; /* use look-aside buffer */ -#else - if (soap_new_block(soap) == NULL) - return NULL; -#endif - for (;;) - { -#ifdef WITH_FAST - register size_t k; - if (soap_append_lab(soap, NULL, 0)) /* allocate more space in look-aside buffer if necessary */ - return NULL; - s = soap->labbuf + soap->labidx; /* space to populate */ - k = soap->lablen - soap->labidx; /* number of bytes available */ - soap->labidx = soap->lablen; /* claim this space */ -#else - register size_t k = SOAP_BLKLEN; - if (!(s = (char*)soap_push_block(soap, NULL, k))) - return NULL; -#endif - for (i = 0; i < k; i++) - { if (m > 0) - { *s++ = *t++; /* copy multibyte characters */ - m--; - continue; - } - if (soap->mode & SOAP_C_UTFSTRING) - { if (((c = soap_get(soap)) & 0x80000000) && c >= -0x7FFFFF80 && c < SOAP_AP) - { c &= 0x7FFFFFFF; - t = buf; - if (c < 0x0800) - *t++ = (char)(0xC0 | ((c >> 6) & 0x1F)); - else - { if (c < 0x010000) - *t++ = (char)(0xE0 | ((c >> 12) & 0x0F)); - else - { if (c < 0x200000) - *t++ = (char)(0xF0 | ((c >> 18) & 0x07)); - else - { if (c < 0x04000000) - *t++ = (char)(0xF8 | ((c >> 24) & 0x03)); - else - { *t++ = (char)(0xFC | ((c >> 30) & 0x01)); - *t++ = (char)(0x80 | ((c >> 24) & 0x3F)); - } - *t++ = (char)(0x80 | ((c >> 18) & 0x3F)); - } - *t++ = (char)(0x80 | ((c >> 12) & 0x3F)); - } - *t++ = (char)(0x80 | ((c >> 6) & 0x3F)); - } - *t++ = (char)(0x80 | (c & 0x3F)); - m = (int)(t - buf) - 1; - t = buf; - *s++ = *t++; - continue; - } - } - else - c = soap_getutf8(soap); - switch (c) - { - case SOAP_TT: - if (n == 0) - goto end; - n--; - *s++ = '<'; - t = (char*)"/"; - m = 1; - break; - case SOAP_LT: - if (f && n == 0) - goto end; - n++; - *s++ = '<'; - break; - case SOAP_GT: - *s++ = '>'; - break; - case SOAP_QT: - *s++ = '"'; - break; - case SOAP_AP: - *s++ = '\''; - break; - case '/': - if (n > 0) - { c = soap_get(soap); - if (c == SOAP_GT) - n--; - soap_unget(soap, c); - } - *s++ = '/'; - break; - case (soap_wchar)('<' | 0x80000000): - if (flag) - *s++ = '<'; - else - { *s++ = '&'; - t = (char*)"lt;"; - m = 3; - } - break; - case (soap_wchar)('>' | 0x80000000): - if (flag) - *s++ = '>'; - else - { *s++ = '&'; - t = (char*)"gt;"; - m = 3; - } - break; - case (soap_wchar)('&' | 0x80000000): - if (flag) - *s++ = '&'; - else - { *s++ = '&'; - t = (char*)"amp;"; - m = 4; - } - break; - case (soap_wchar)('"' | 0x80000000): - if (flag) - *s++ = '"'; - else - { *s++ = '&'; - t = (char*)"quot;"; - m = 5; - } - break; - case (soap_wchar)('\'' | 0x80000000): - if (flag) - *s++ = '\''; - else - { *s++ = '&'; - t = (char*)"apos;"; - m = 5; - } - break; - default: - if ((int)c == EOF) - goto end; -#ifndef WITH_LEANER -#ifdef HAVE_WCTOMB - if (soap->mode & SOAP_C_MBSTRING) - { m = wctomb(buf, c & 0x7FFFFFFF); - if (m >= 1 && m <= (int)MB_CUR_MAX) - { t = buf; - *s++ = *t++; - m--; - } - else - { *s++ = SOAP_UNKNOWN_CHAR; - m = 0; - } - } - else -#endif -#endif - *s++ = (char)(c & 0xFF); - } - l++; - if ((soap->mode & SOAP_XML_STRICT) && maxlen >= 0 && l > maxlen) - { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "String too long: maxlen=%ld\n", maxlen)); - soap->error = SOAP_LENGTH; - return NULL; - } - } - } -end: - soap_unget(soap, c); - *s = '\0'; -#ifdef WITH_FAST - t = soap_strdup(soap, soap->labbuf); -#else - soap_size_block(soap, NULL, i+1); - t = soap_save_block(soap, NULL, 0); -#endif - if ((soap->mode & SOAP_XML_STRICT) && l < minlen) - { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "String too short: %ld chars, minlen=%ld\n", l, minlen)); - soap->error = SOAP_LENGTH; - return NULL; - } -#ifdef WITH_DOM - if ((soap->mode & SOAP_XML_DOM) && soap->dom) - { if (flag == 3) - soap->dom->tail = t; - else - soap->dom->data = t; - } -#endif - if (flag == 2) - if (soap_s2QName(soap, t, &t, minlen, maxlen)) - return NULL; - return t; -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_wstring_out(struct soap *soap, const wchar_t *s, int flag) -{ const char *t; - char tmp; - register soap_wchar c; -#ifdef WITH_DOM - if ((soap->mode & SOAP_XML_DOM) && soap->dom) - { wchar_t *r = (wchar_t*)s; - int n = 1; - while (*r++) - n++; - soap->dom->wide = r = (wchar_t*)soap_malloc(soap, n * sizeof(wchar_t)); - while (n--) - *r++ = *s++; - return SOAP_OK; - } -#endif - while ((c = *s++)) - { switch (c) - { - case 0x09: - if (flag) - t = " "; - else - t = "\t"; - break; - case 0x0A: - if (flag || !(soap->mode & SOAP_XML_CANONICAL)) - t = " "; - else - t = "\n"; - break; - case 0x0D: - t = " "; - break; - case '&': - t = "&"; - break; - case '<': - t = "<"; - break; - case '>': - if (flag) - t = ">"; - else - t = ">"; - break; - case '"': - if (flag) - t = """; - else - t = "\""; - break; - default: - if (c >= 0x20 && c < 0x80) - { tmp = (char)c; - if (soap_send_raw(soap, &tmp, 1)) - return soap->error; - } - else if (soap_pututf8(soap, (unsigned long)c)) - return soap->error; - continue; - } - if (soap_send(soap, t)) - return soap->error; - } - return SOAP_OK; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_2 -SOAP_FMAC1 -wchar_t * -SOAP_FMAC2 -soap_wstring_in(struct soap *soap, int flag, long minlen, long maxlen) -{ wchar_t *s; - register int i, n = 0, f = 0; - register long l = 0; - register soap_wchar c; - char *t = NULL; - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Reading wide string content\n")); - if (soap->peeked) - { if (*soap->tag) - { -#ifndef WITH_LEAN - struct soap_attribute *tp; - t = soap->tmpbuf; - *t = '<'; - t[sizeof(soap->tmpbuf)-1] = '\0'; - strncpy(t + 1, soap->tag, sizeof(soap->tmpbuf) - 2); - t += strlen(t); - for (tp = soap->attributes; tp; tp = tp->next) - { if (tp->visible) - { if (t >= soap->tmpbuf + sizeof(soap->tmpbuf) - 2) - break; - *t++ = ' '; - strcpy(t, tp->name); - t += strlen(t); - if (t >= soap->tmpbuf + sizeof(soap->tmpbuf) - 2) - break; - if (tp->value) - { *t++ = '='; - *t++ = '"'; - strcpy(t, tp->value); - t += strlen(t); - *t++ = '"'; - } - } - } - if (!soap->body) - *t++ = '/'; - *t++ = '>'; - *t = '\0'; - t = soap->tmpbuf; -#endif - if (soap->body) - n = 1; - f = 1; - soap->peeked = 0; - } - } - if (soap_new_block(soap) == NULL) - return NULL; - for (;;) - { if (!(s = (wchar_t*)soap_push_block(soap, NULL, sizeof(wchar_t)*SOAP_BLKLEN))) - return NULL; - for (i = 0; i < SOAP_BLKLEN; i++) - { if (t) - { *s++ = (wchar_t)*t++; - if (!*t) - t = NULL; - continue; - } - c = soap_getutf8(soap); - switch (c) - { - case SOAP_TT: - if (n == 0) - goto end; - n--; - *s++ = '<'; - soap_unget(soap, '/'); - break; - case SOAP_LT: - if (f && n == 0) - goto end; - n++; - *s++ = '<'; - break; - case SOAP_GT: - *s++ = '>'; - break; - case SOAP_QT: - *s++ = '"'; - break; - case SOAP_AP: - *s++ = '\''; - break; - case '/': - if (n > 0) - { c = soap_getutf8(soap); - if (c == SOAP_GT) - n--; - soap_unget(soap, c); - } - *s++ = '/'; - break; - case '<': - if (flag) - *s++ = (soap_wchar)'<'; - else - { *s++ = (soap_wchar)'&'; - t = (char*)"lt;"; - } - break; - case '>': - if (flag) - *s++ = (soap_wchar)'>'; - else - { *s++ = (soap_wchar)'&'; - t = (char*)"gt;"; - } - break; - case '"': - if (flag) - *s++ = (soap_wchar)'"'; - else - { *s++ = (soap_wchar)'&'; - t = (char*)"quot;"; - } - break; - default: - if ((int)c == EOF) - goto end; - *s++ = (wchar_t)c & 0x7FFFFFFF; - } - l++; - if ((soap->mode & SOAP_XML_STRICT) && maxlen >= 0 && l > maxlen) - { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "String too long: maxlen=%ld\n", maxlen)); - soap->error = SOAP_LENGTH; - return NULL; - } - } - } -end: - soap_unget(soap, c); - *s = '\0'; - soap_size_block(soap, NULL, sizeof(wchar_t) * (i + 1)); - if ((soap->mode & SOAP_XML_STRICT) && l < minlen) - { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "String too short: %ld chars, minlen=%ld\n", l, minlen)); - soap->error = SOAP_LENGTH; - return NULL; - } - s = (wchar_t*)soap_save_block(soap, NULL, NULL, 0); -#ifdef WITH_DOM - if ((soap->mode & SOAP_XML_DOM) && soap->dom) - soap->dom->wide = s; -#endif - return s; -} -#endif -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -const char* -SOAP_FMAC2 -soap_int2s(struct soap *soap, int n) -{ return soap_long2s(soap, (long)n); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_outint(struct soap *soap, const char *tag, int id, const int *p, const char *type, int n) -{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type) - || soap_string_out(soap, soap_long2s(soap, (long)*p), 0)) - return soap->error; - return soap_element_end_out(soap, tag); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_s2int(struct soap *soap, const char *s, int *p) -{ if (s) - { char *r; -#ifndef WITH_NOIO -#ifndef WITH_LEAN - soap_reset_errno; -#endif -#endif - *p = (int)soap_strtol(s, &r, 10); - if ((s == r && (soap->mode & SOAP_XML_STRICT)) || *r -#ifndef WITH_NOIO -#ifndef WITH_LEAN - || soap_errno == SOAP_ERANGE -#endif -#endif - ) - soap->error = SOAP_TYPE; - } - return soap->error; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int * -SOAP_FMAC2 -soap_inint(struct soap *soap, const char *tag, int *p, const char *type, int t) -{ if (soap_element_begin_in(soap, tag, 0, NULL)) - return NULL; -#ifndef WITH_LEAN - if (*soap->type - && soap_match_tag(soap, soap->type, type) - && soap_match_tag(soap, soap->type, ":int") - && soap_match_tag(soap, soap->type, ":short") - && soap_match_tag(soap, soap->type, ":byte")) - { soap->error = SOAP_TYPE; - soap_revert(soap); - return NULL; - } -#endif - p = (int*)soap_id_enter(soap, soap->id, p, t, sizeof(int), 0, NULL, NULL, NULL); - if (*soap->href) - p = (int*)soap_id_forward(soap, soap->href, p, 0, t, 0, sizeof(int), 0, NULL); - else if (p) - { if (soap_s2int(soap, soap_value(soap), p)) - return NULL; - } - if (soap->body && soap_element_end_in(soap, tag)) - return NULL; - return p; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -const char* -SOAP_FMAC2 -soap_long2s(struct soap *soap, long n) -{ sprintf(soap->tmpbuf, "%ld", n); - return soap->tmpbuf; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_outlong(struct soap *soap, const char *tag, int id, const long *p, const char *type, int n) -{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type) - || soap_string_out(soap, soap_long2s(soap, *p), 0)) - return soap->error; - return soap_element_end_out(soap, tag); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_s2long(struct soap *soap, const char *s, long *p) -{ if (s) - { char *r; -#ifndef WITH_NOIO -#ifndef WITH_LEAN - soap_reset_errno; -#endif -#endif - *p = soap_strtol(s, &r, 10); - if ((s == r && (soap->mode & SOAP_XML_STRICT)) || *r -#ifndef WITH_NOIO -#ifndef WITH_LEAN - || soap_errno == SOAP_ERANGE -#endif -#endif - ) - soap->error = SOAP_TYPE; - } - return soap->error; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -long * -SOAP_FMAC2 -soap_inlong(struct soap *soap, const char *tag, long *p, const char *type, int t) -{ if (soap_element_begin_in(soap, tag, 0, NULL)) - return NULL; -#ifndef WITH_LEAN - if (*soap->type - && soap_match_tag(soap, soap->type, type) - && soap_match_tag(soap, soap->type, ":int") - && soap_match_tag(soap, soap->type, ":short") - && soap_match_tag(soap, soap->type, ":byte")) - { soap->error = SOAP_TYPE; - soap_revert(soap); - return NULL; - } -#endif - p = (long*)soap_id_enter(soap, soap->id, p, t, sizeof(long), 0, NULL, NULL, NULL); - if (*soap->href) - p = (long*)soap_id_forward(soap, soap->href, p, 0, t, 0, sizeof(long), 0, NULL); - else if (p) - { if (soap_s2long(soap, soap_value(soap), p)) - return NULL; - } - if (soap->body && soap_element_end_in(soap, tag)) - return NULL; - return p; -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEAN -SOAP_FMAC1 -const char* -SOAP_FMAC2 -soap_LONG642s(struct soap *soap, LONG64 n) -{ sprintf(soap->tmpbuf, SOAP_LONG_FORMAT, n); - return soap->tmpbuf; -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEAN -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_outLONG64(struct soap *soap, const char *tag, int id, const LONG64 *p, const char *type, int n) -{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type) - || soap_string_out(soap, soap_LONG642s(soap, *p), 0)) - return soap->error; - return soap_element_end_out(soap, tag); -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEAN -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_s2LONG64(struct soap *soap, const char *s, LONG64 *p) -{ if (s) - { -#ifdef HAVE_STRTOLL - char *r; -#ifndef WITH_NOIO -#ifndef WITH_LEAN - soap_reset_errno; -#endif -#endif - *p = strtoll(s, &r, 10); - if ((s == r && (soap->mode & SOAP_XML_STRICT)) || *r -#ifndef WITH_NOIO -#ifndef WITH_LEAN - || soap_errno == SOAP_ERANGE -#endif -#endif - ) -#else -# ifdef HAVE_SSCANF - if (sscanf(s, SOAP_LONG_FORMAT, p) != 1) -# endif -#endif - soap->error = SOAP_TYPE; - } - return soap->error; -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEAN -SOAP_FMAC1 -LONG64 * -SOAP_FMAC2 -soap_inLONG64(struct soap *soap, const char *tag, LONG64 *p, const char *type, int t) -{ if (soap_element_begin_in(soap, tag, 0, NULL)) - return NULL; -#ifndef WITH_LEAN - if (*soap->type - && soap_match_tag(soap, soap->type, type) - && soap_match_tag(soap, soap->type, ":integer") - && soap_match_tag(soap, soap->type, ":positiveInteger") - && soap_match_tag(soap, soap->type, ":negativeInteger") - && soap_match_tag(soap, soap->type, ":nonPositiveInteger") - && soap_match_tag(soap, soap->type, ":nonNegativeInteger") - && soap_match_tag(soap, soap->type, ":long") - && soap_match_tag(soap, soap->type, ":int") - && soap_match_tag(soap, soap->type, ":short") - && soap_match_tag(soap, soap->type, ":byte")) - { soap->error = SOAP_TYPE; - soap_revert(soap); - return NULL; - } -#endif - p = (LONG64*)soap_id_enter(soap, soap->id, p, t, sizeof(LONG64), 0, NULL, NULL, NULL); - if (*soap->href) - p = (LONG64*)soap_id_forward(soap, soap->href, p, 0, t, 0, sizeof(LONG64), 0, NULL); - else if (p) - { if (soap_s2LONG64(soap, soap_value(soap), p)) - return NULL; - } - if (soap->body && soap_element_end_in(soap, tag)) - return NULL; - return p; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -const char* -SOAP_FMAC2 -soap_byte2s(struct soap *soap, char n) -{ return soap_long2s(soap, (long)n); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_outbyte(struct soap *soap, const char *tag, int id, const char *p, const char *type, int n) -{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type) - || soap_string_out(soap, soap_long2s(soap, (long)*p), 0)) - return soap->error; - return soap_element_end_out(soap, tag); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_s2byte(struct soap *soap, const char *s, char *p) -{ if (s) - { long n; - char *r; - n = soap_strtol(s, &r, 10); - if (s == r || *r || n < -128 || n > 127) - soap->error = SOAP_TYPE; - *p = (char)n; - } - return soap->error; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -char * -SOAP_FMAC2 -soap_inbyte(struct soap *soap, const char *tag, char *p, const char *type, int t) -{ if (soap_element_begin_in(soap, tag, 0, NULL)) - return NULL; -#ifndef WITH_LEAN - if (*soap->type - && soap_match_tag(soap, soap->type, type) - && soap_match_tag(soap, soap->type, ":byte")) - { soap->error = SOAP_TYPE; - soap_revert(soap); - return NULL; - } -#endif - p = (char*)soap_id_enter(soap, soap->id, p, t, sizeof(char), 0, NULL, NULL, NULL); - if (*soap->href) - p = (char*)soap_id_forward(soap, soap->href, p, 0, t, 0, sizeof(char), 0, NULL); - else if (p) - { if (soap_s2byte(soap, soap_value(soap), p)) - return NULL; - } - if (soap->body && soap_element_end_in(soap, tag)) - return NULL; - return p; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -const char* -SOAP_FMAC2 -soap_short2s(struct soap *soap, short n) -{ return soap_long2s(soap, (long)n); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_outshort(struct soap *soap, const char *tag, int id, const short *p, const char *type, int n) -{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type) - || soap_string_out(soap, soap_long2s(soap, (long)*p), 0)) - return soap->error; - return soap_element_end_out(soap, tag); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_s2short(struct soap *soap, const char *s, short *p) -{ if (s) - { long n; - char *r; - n = soap_strtol(s, &r, 10); - if (s == r || *r || n < -32768 || n > 32767) - soap->error = SOAP_TYPE; - *p = (short)n; - } - return soap->error; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -short * -SOAP_FMAC2 -soap_inshort(struct soap *soap, const char *tag, short *p, const char *type, int t) -{ if (soap_element_begin_in(soap, tag, 0, NULL)) - return NULL; -#ifndef WITH_LEAN - if (*soap->type - && soap_match_tag(soap, soap->type, type) - && soap_match_tag(soap, soap->type, ":short") - && soap_match_tag(soap, soap->type, ":byte")) - { soap->error = SOAP_TYPE; - soap_revert(soap); - return NULL; - } -#endif - p = (short*)soap_id_enter(soap, soap->id, p, t, sizeof(short), 0, NULL, NULL, NULL); - if (*soap->href) - p = (short*)soap_id_forward(soap, soap->href, p, 0, t, 0, sizeof(short), 0, NULL); - else if (p) - { if (soap_s2short(soap, soap_value(soap), p)) - return NULL; - } - if (soap->body && soap_element_end_in(soap, tag)) - return NULL; - return p; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -const char* -SOAP_FMAC2 -soap_float2s(struct soap *soap, float n) -{ char *s; - if (soap_isnan((double)n)) - return "NaN"; - if (soap_ispinff(n)) - return "INF"; - if (soap_isninff(n)) - return "-INF"; - s = soap->tmpbuf; -#if defined(HAVE_SPRINTF_L) - sprintf_l(s, soap->c_locale, soap->float_format, n); -#else - sprintf(s, soap->float_format, n); - s = strchr(s, ','); /* convert decimal comma to DP */ - if (s) - *s = '.'; -#endif - return soap->tmpbuf; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_outfloat(struct soap *soap, const char *tag, int id, const float *p, const char *type, int n) -{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type) - || soap_string_out(soap, soap_float2s(soap, *p), 0)) - return soap->error; - return soap_element_end_out(soap, tag); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_s2float(struct soap *soap, const char *s, float *p) -{ if (s) - { if (!*s) - return soap->error = SOAP_TYPE; - if (!soap_tag_cmp(s, "INF")) - *p = FLT_PINFTY; - else if (!soap_tag_cmp(s, "+INF")) - *p = FLT_PINFTY; - else if (!soap_tag_cmp(s, "-INF")) - *p = FLT_NINFTY; - else if (!soap_tag_cmp(s, "NaN")) - *p = FLT_NAN; - else - { -/* On some systems strtof requires -std=c99 or does not even link: so we try to use strtod first */ -#if defined(HAVE_STRTOD_L) - char *r; - *p = (float)strtod_l(s, &r, soap->c_locale); - if (*r) -#elif defined(HAVE_STRTOD) - char *r; - *p = (float)strtod(s, &r); - if (*r) -#elif defined(HAVE_STRTOF_L) - char *r; - *p = strtof_l((char*)s, &r, soap->c_locale); - if (*r) -#elif defined(HAVE_STRTOF) - char *r; - *p = strtof((char*)s, &r); - if (*r) -#endif - { -#if defined(HAVE_SSCANF_L) && !defined(HAVE_STRTOF_L) && !defined(HAVE_STRTOD_L) - if (sscanf_l(s, soap->c_locale, "%g", p) != 1) - soap->error = SOAP_TYPE; -#elif defined(HAVE_SSCANF) - if (sscanf(s, "%g", p) != 1) - soap->error = SOAP_TYPE; -#else - soap->error = SOAP_TYPE; -#endif - } - } - } - return soap->error; -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEAN -static int soap_isnumeric(struct soap *soap, const char *type) -{ if (soap_match_tag(soap, soap->type, type) - && soap_match_tag(soap, soap->type, ":float") - && soap_match_tag(soap, soap->type, ":double") - && soap_match_tag(soap, soap->type, ":decimal") - && soap_match_tag(soap, soap->type, ":integer") - && soap_match_tag(soap, soap->type, ":positiveInteger") - && soap_match_tag(soap, soap->type, ":negativeInteger") - && soap_match_tag(soap, soap->type, ":nonPositiveInteger") - && soap_match_tag(soap, soap->type, ":nonNegativeInteger") - && soap_match_tag(soap, soap->type, ":long") - && soap_match_tag(soap, soap->type, ":int") - && soap_match_tag(soap, soap->type, ":short") - && soap_match_tag(soap, soap->type, ":byte") - && soap_match_tag(soap, soap->type, ":unsignedLong") - && soap_match_tag(soap, soap->type, ":unsignedInt") - && soap_match_tag(soap, soap->type, ":unsignedShort") - && soap_match_tag(soap, soap->type, ":unsignedByte")) - { soap->error = SOAP_TYPE; - soap_revert(soap); - return SOAP_ERR; - } - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -float * -SOAP_FMAC2 -soap_infloat(struct soap *soap, const char *tag, float *p, const char *type, int t) -{ if (soap_element_begin_in(soap, tag, 0, NULL)) - return NULL; -#ifndef WITH_LEAN - if (*soap->type != '\0' && soap_isnumeric(soap, type)) - return NULL; -#endif - p = (float*)soap_id_enter(soap, soap->id, p, t, sizeof(float), 0, NULL, NULL, NULL); - if (*soap->href) - p = (float*)soap_id_forward(soap, soap->href, p, 0, t, 0, sizeof(float), 0, NULL); - else if (p) - { if (soap_s2float(soap, soap_value(soap), p)) - return NULL; - } - if (soap->body && soap_element_end_in(soap, tag)) - return NULL; - return p; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -const char* -SOAP_FMAC2 -soap_double2s(struct soap *soap, double n) -{ char *s; - if (soap_isnan(n)) - return "NaN"; - if (soap_ispinfd(n)) - return "INF"; - if (soap_isninfd(n)) - return "-INF"; - s = soap->tmpbuf; -#if defined(HAVE_SPRINTF_L) - sprintf_l(s, soap->c_locale, soap->double_format, n); -#else - sprintf(s, soap->double_format, n); - s = strchr(s, ','); /* convert decimal comma to DP */ - if (s) - *s = '.'; -#endif - return soap->tmpbuf; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_outdouble(struct soap *soap, const char *tag, int id, const double *p, const char *type, int n) -{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type) - || soap_string_out(soap, soap_double2s(soap, *p), 0)) - return soap->error; - return soap_element_end_out(soap, tag); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_s2double(struct soap *soap, const char *s, double *p) -{ if (s) - { if (!*s) - return soap->error = SOAP_TYPE; - if (!soap_tag_cmp(s, "INF")) - *p = DBL_PINFTY; - else if (!soap_tag_cmp(s, "+INF")) - *p = DBL_PINFTY; - else if (!soap_tag_cmp(s, "-INF")) - *p = DBL_NINFTY; - else if (!soap_tag_cmp(s, "NaN")) - *p = DBL_NAN; - else - { -#if defined(HAVE_STRTOD_L) - char *r; - *p = strtod_l(s, &r, soap->c_locale); - if (*r) -#elif defined(HAVE_STRTOD) - char *r; - *p = strtod(s, &r); - if (*r) -#endif - { -#if defined(HAVE_SSCANF_L) && !defined(HAVE_STRTOF_L) && !defined(HAVE_STRTOD_L) - if (sscanf_l(s, soap->c_locale, "%lg", p) != 1) - soap->error = SOAP_TYPE; -#elif defined(HAVE_SSCANF) - if (sscanf(s, "%lg", p) != 1) - soap->error = SOAP_TYPE; -#else - soap->error = SOAP_TYPE; -#endif - } - } - } - return soap->error; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -double * -SOAP_FMAC2 -soap_indouble(struct soap *soap, const char *tag, double *p, const char *type, int t) -{ if (soap_element_begin_in(soap, tag, 0, NULL)) - return NULL; -#ifndef WITH_LEAN - if (*soap->type != '\0' && soap_isnumeric(soap, type)) - return NULL; -#endif - p = (double*)soap_id_enter(soap, soap->id, p, t, sizeof(double), 0, NULL, NULL, NULL); - if (*soap->href) - p = (double*)soap_id_forward(soap, soap->href, p, 0, t, 0, sizeof(double), 0, NULL); - else if (p) - { if (soap_s2double(soap, soap_value(soap), p)) - return NULL; - } - if (soap->body && soap_element_end_in(soap, tag)) - return NULL; - return p; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -const char* -SOAP_FMAC2 -soap_unsignedByte2s(struct soap *soap, unsigned char n) -{ return soap_unsignedLong2s(soap, (unsigned long)n); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_outunsignedByte(struct soap *soap, const char *tag, int id, const unsigned char *p, const char *type, int n) -{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type) - || soap_string_out(soap, soap_unsignedLong2s(soap, (unsigned long)*p), 0)) - return soap->error; - return soap_element_end_out(soap, tag); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_s2unsignedByte(struct soap *soap, const char *s, unsigned char *p) -{ if (s) - { unsigned long n; - char *r; - n = soap_strtoul(s, &r, 10); - if (s == r || *r || n > 255) - soap->error = SOAP_TYPE; - *p = (unsigned char)n; - } - return soap->error; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -unsigned char * -SOAP_FMAC2 -soap_inunsignedByte(struct soap *soap, const char *tag, unsigned char *p, const char *type, int t) -{ if (soap_element_begin_in(soap, tag, 0, NULL)) - return NULL; -#ifndef WITH_LEAN - if (*soap->type - && soap_match_tag(soap, soap->type, type) - && soap_match_tag(soap, soap->type, ":unsignedByte")) - { soap->error = SOAP_TYPE; - soap_revert(soap); - return NULL; - } -#endif - p = (unsigned char*)soap_id_enter(soap, soap->id, p, t, sizeof(unsigned char), 0, NULL, NULL, NULL); - if (*soap->href) - p = (unsigned char*)soap_id_forward(soap, soap->href, p, 0, t, 0, sizeof(unsigned char), 0, NULL); - else if (p) - { if (soap_s2unsignedByte(soap, soap_value(soap), p)) - return NULL; - } - if (soap->body && soap_element_end_in(soap, tag)) - return NULL; - return p; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -const char* -SOAP_FMAC2 -soap_unsignedShort2s(struct soap *soap, unsigned short n) -{ return soap_unsignedLong2s(soap, (unsigned long)n); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_outunsignedShort(struct soap *soap, const char *tag, int id, const unsigned short *p, const char *type, int n) -{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type) - || soap_string_out(soap, soap_unsignedLong2s(soap, (unsigned long)*p), 0)) - return soap->error; - return soap_element_end_out(soap, tag); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_s2unsignedShort(struct soap *soap, const char *s, unsigned short *p) -{ if (s) - { unsigned long n; - char *r; - n = soap_strtoul(s, &r, 10); - if (s == r || *r || n > 65535) - soap->error = SOAP_TYPE; - *p = (unsigned short)n; - } - return soap->error; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -unsigned short * -SOAP_FMAC2 -soap_inunsignedShort(struct soap *soap, const char *tag, unsigned short *p, const char *type, int t) -{ if (soap_element_begin_in(soap, tag, 0, NULL)) - return NULL; -#ifndef WITH_LEAN - if (*soap->type - && soap_match_tag(soap, soap->type, type) - && soap_match_tag(soap, soap->type, ":unsignedShort") - && soap_match_tag(soap, soap->type, ":unsignedByte")) - { soap->error = SOAP_TYPE; - soap_revert(soap); - return NULL; - } -#endif - p = (unsigned short*)soap_id_enter(soap, soap->id, p, t, sizeof(unsigned short), 0, NULL, NULL, NULL); - if (*soap->href) - p = (unsigned short*)soap_id_forward(soap, soap->href, p, 0, t, 0, sizeof(unsigned short), 0, NULL); - else if (p) - { if (soap_s2unsignedShort(soap, soap_value(soap), p)) - return NULL; - } - if (soap->body && soap_element_end_in(soap, tag)) - return NULL; - return p; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -const char* -SOAP_FMAC2 -soap_unsignedInt2s(struct soap *soap, unsigned int n) -{ return soap_unsignedLong2s(soap, (unsigned long)n); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_outunsignedInt(struct soap *soap, const char *tag, int id, const unsigned int *p, const char *type, int n) -{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type) - || soap_string_out(soap, soap_unsignedLong2s(soap, (unsigned long)*p), 0)) - return soap->error; - return soap_element_end_out(soap, tag); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_s2unsignedInt(struct soap *soap, const char *s, unsigned int *p) -{ if (s) - { char *r; -#ifndef WITH_NOIO -#ifndef WITH_LEAN - soap_reset_errno; -#endif -#endif - *p = (unsigned int)soap_strtoul(s, &r, 10); - if ((s == r && (soap->mode & SOAP_XML_STRICT)) || *r -#ifndef WITH_NOIO -#ifndef WITH_LEAN - || soap_errno == SOAP_ERANGE -#endif -#endif - ) - soap->error = SOAP_TYPE; - } - return soap->error; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -unsigned int * -SOAP_FMAC2 -soap_inunsignedInt(struct soap *soap, const char *tag, unsigned int *p, const char *type, int t) -{ if (soap_element_begin_in(soap, tag, 0, NULL)) - return NULL; -#ifndef WITH_LEAN - if (*soap->type - && soap_match_tag(soap, soap->type, type) - && soap_match_tag(soap, soap->type, ":unsignedInt") - && soap_match_tag(soap, soap->type, ":unsignedShort") - && soap_match_tag(soap, soap->type, ":unsignedByte")) - { soap->error = SOAP_TYPE; - soap_revert(soap); - return NULL; - } -#endif - p = (unsigned int*)soap_id_enter(soap, soap->id, p, t, sizeof(unsigned int), 0, NULL, NULL, NULL); - if (*soap->href) - p = (unsigned int*)soap_id_forward(soap, soap->href, p, 0, t, 0, sizeof(unsigned int), 0, NULL); - else if (p) - { if (soap_s2unsignedInt(soap, soap_value(soap), p)) - return NULL; - } - if (soap->body && soap_element_end_in(soap, tag)) - return NULL; - return p; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -const char* -SOAP_FMAC2 -soap_unsignedLong2s(struct soap *soap, unsigned long n) -{ sprintf(soap->tmpbuf, "%lu", n); - return soap->tmpbuf; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_outunsignedLong(struct soap *soap, const char *tag, int id, const unsigned long *p, const char *type, int n) -{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type) - || soap_string_out(soap, soap_unsignedLong2s(soap, *p), 0)) - return soap->error; - return soap_element_end_out(soap, tag); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_s2unsignedLong(struct soap *soap, const char *s, unsigned long *p) -{ if (s) - { char *r; -#ifndef WITH_NOIO -#ifndef WITH_LEAN - soap_reset_errno; -#endif -#endif - *p = soap_strtoul(s, &r, 10); - if ((s == r && (soap->mode & SOAP_XML_STRICT)) || *r -#ifndef WITH_NOIO -#ifndef WITH_LEAN - || soap_errno == SOAP_ERANGE -#endif -#endif - ) - soap->error = SOAP_TYPE; - } - return soap->error; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -unsigned long * -SOAP_FMAC2 -soap_inunsignedLong(struct soap *soap, const char *tag, unsigned long *p, const char *type, int t) -{ if (soap_element_begin_in(soap, tag, 0, NULL)) - return NULL; -#ifndef WITH_LEAN - if (*soap->type - && soap_match_tag(soap, soap->type, type) - && soap_match_tag(soap, soap->type, ":unsignedInt") - && soap_match_tag(soap, soap->type, ":unsignedShort") - && soap_match_tag(soap, soap->type, ":unsignedByte")) - { soap->error = SOAP_TYPE; - soap_revert(soap); - return NULL; - } -#endif - p = (unsigned long*)soap_id_enter(soap, soap->id, p, t, sizeof(unsigned long), 0, NULL, NULL, NULL); - if (*soap->href) - p = (unsigned long*)soap_id_forward(soap, soap->href, p, 0, t, 0, sizeof(unsigned long), 0, NULL); - else if (p) - { if (soap_s2unsignedLong(soap, soap_value(soap), p)) - return NULL; - } - if (soap->body && soap_element_end_in(soap, tag)) - return NULL; - return p; -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEAN -SOAP_FMAC1 -const char* -SOAP_FMAC2 -soap_ULONG642s(struct soap *soap, ULONG64 n) -{ sprintf(soap->tmpbuf, SOAP_ULONG_FORMAT, n); - return soap->tmpbuf; -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEAN -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_outULONG64(struct soap *soap, const char *tag, int id, const ULONG64 *p, const char *type, int n) -{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type) - || soap_string_out(soap, soap_ULONG642s(soap, *p), 0)) - return soap->error; - return soap_element_end_out(soap, tag); -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEAN -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_s2ULONG64(struct soap *soap, const char *s, ULONG64 *p) -{ if (s) - { -#ifdef HAVE_STRTOULL - char *r; -#ifndef WITH_NOIO -#ifndef WITH_LEAN - soap_reset_errno; -#endif -#endif - *p = strtoull(s, &r, 10); - if ((s == r && (soap->mode & SOAP_XML_STRICT)) || *r -#ifndef WITH_NOIO -#ifndef WITH_LEAN - || soap_errno == SOAP_ERANGE -#endif -#endif - ) -#else -#ifdef HAVE_SSCANF - if (sscanf(s, SOAP_ULONG_FORMAT, p) != 1) -#endif -#endif - soap->error = SOAP_TYPE; - } - return soap->error; -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEAN -SOAP_FMAC1 -ULONG64 * -SOAP_FMAC2 -soap_inULONG64(struct soap *soap, const char *tag, ULONG64 *p, const char *type, int t) -{ if (soap_element_begin_in(soap, tag, 0, NULL)) - return NULL; - if (*soap->type - && soap_match_tag(soap, soap->type, type) - && soap_match_tag(soap, soap->type, ":positiveInteger") - && soap_match_tag(soap, soap->type, ":nonNegativeInteger") - && soap_match_tag(soap, soap->type, ":unsignedLong") - && soap_match_tag(soap, soap->type, ":unsignedInt") - && soap_match_tag(soap, soap->type, ":unsignedShort") - && soap_match_tag(soap, soap->type, ":unsignedByte")) - { soap->error = SOAP_TYPE; - soap_revert(soap); - return NULL; - } - p = (ULONG64*)soap_id_enter(soap, soap->id, p, t, sizeof(ULONG64), 0, NULL, NULL, NULL); - if (*soap->href) - p = (ULONG64*)soap_id_forward(soap, soap->href, p, 0, t, 0, sizeof(ULONG64), 0, NULL); - else if (p) - { if (soap_s2ULONG64(soap, soap_value(soap), p)) - return NULL; - } - if (soap->body && soap_element_end_in(soap, tag)) - return NULL; - return p; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_s2string(struct soap *soap, const char *s, char **t, long minlen, long maxlen) -{ if (s) - { if (!(*t = soap_strdup(soap, s))) - return soap->error = SOAP_EOM; - if (!(soap->mode & (SOAP_ENC_LATIN | SOAP_C_UTFSTRING))) - { char *r = *t; - /* remove non-ASCII chars */ - for (s = *t; *s; s++) - if (!(*s & 0x80)) - *r++ = *s; - *r = '\0'; - } - if ((soap->mode & SOAP_XML_STRICT)) - { long l = (long)strlen(*t); - if ((maxlen >= 0 && l > maxlen) || l < minlen) - soap->error = SOAP_LENGTH; - } - } - return soap->error; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_s2QName(struct soap *soap, const char *s, char **t, long minlen, long maxlen) -{ if (s) - { soap->labidx = 0; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Normalized namespace(s) of QNames '%s'", s)); - /* convert (by prefix normalize prefix) all QNames in s */ - for (;;) - { size_t n; - struct soap_nlist *np; - register const char *p; - /* skip blanks */ - while (*s && soap_blank(*s)) - s++; - if (!*s) - break; - /* find next QName */ - n = 1; - while (s[n] && !soap_blank(s[n])) - n++; - np = soap->nlist; - /* if there is no namespace stack, or prefix is "xml" then copy string */ - if (!np || !strncmp(s, "xml:", 4)) - { soap_append_lab(soap, s, n); - } - else /* we normalize the QName by replacing its prefix */ - { for (p = s; *p && p < s + n; p++) - if (*p == ':') - break; - if (*p == ':') - { size_t k = p - s; - while (np && (strncmp(np->id, s, k) || np->id[k])) - np = np->next; - p++; - } - else - { while (np && *np->id) - np = np->next; - p = s; - } - /* replace prefix */ - if (np) - { if (np->index >= 0 && soap->local_namespaces) - { const char *q = soap->local_namespaces[np->index].id; - if (q) - soap_append_lab(soap, q, strlen(q)); - } - else if (np->ns) - { soap_append_lab(soap, "\"", 1); - soap_append_lab(soap, np->ns, strlen(np->ns)); - soap_append_lab(soap, "\"", 1); - } - else - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "\nNamespace prefix of '%s' not defined (index=%d, URI=%s)\n", s, np->index, np->ns?np->ns:SOAP_STR_EOS)); - return soap->error = SOAP_NAMESPACE; - } - } - else if (s[n]) /* no namespace, part of string */ - { soap_append_lab(soap, s, n); - } - else /* no namespace: assume "" namespace */ - { soap_append_lab(soap, "\"\"", 2); - } - soap_append_lab(soap, ":", 1); - soap_append_lab(soap, p, n - (p-s)); - } - /* advance to next and add spacing */ - s += n; - if (*s) - soap_append_lab(soap, " ", 1); - } - soap_append_lab(soap, SOAP_STR_EOS, 1); - *t = soap_strdup(soap, soap->labbuf); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, " into '%s'\n", *t)); - if ((soap->mode & SOAP_XML_STRICT)) - { long l = (long)soap->labidx - 1; - if ((maxlen >= 0 && l > maxlen) || l < minlen) - soap->error = SOAP_LENGTH; - } - } - return soap->error; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -const char* -SOAP_FMAC2 -soap_QName2s(struct soap *soap, const char *s) -{ const char *t = NULL; - if (s) - { soap->labidx = 0; - for (;;) - { size_t n; - /* skip blanks */ - while (*s && soap_blank(*s)) - s++; - if (!*s) - break; - /* find next QName */ - n = 1; - while (s[n] && !soap_blank(s[n])) - n++; - /* normal prefix: pass string as is */ - if (*s != '"') - { soap_append_lab(soap, s, n); -#ifndef WITH_LEAN - if ((soap->mode & SOAP_XML_CANONICAL)) - { const char *r = strchr(s, ':'); - if (r) - soap_utilize_ns(soap, s, r - s); - } -#endif - } - else /* URL-based string prefix */ - { const char *q; - s++; - q = strchr(s, '"'); - if (q) - { struct Namespace *p = soap->local_namespaces; - if (p) - { for (; p->id; p++) - { if (p->ns) - if (!soap_tag_cmp(s, p->ns)) - break; - if (p->in) - if (!soap_tag_cmp(s, p->in)) - break; - } - } - /* URL is in the namespace table? */ - if (p && p->id) - { soap_append_lab(soap, p->id, strlen(p->id)); - } - else /* not in namespace table: create xmlns binding */ - { char *r = soap_strdup(soap, s); - r[q-s] = '\0'; - sprintf(soap->tmpbuf, "xmlns:_%d", soap->idnum++); - soap_set_attr(soap, soap->tmpbuf, r); - soap_append_lab(soap, soap->tmpbuf + 6, strlen(soap->tmpbuf + 6)); - } - soap_append_lab(soap, q + 1, n - (q-s) - 1); - } - } - /* advance to next and add spacing */ - s += n; - if (*s) - soap_append_lab(soap, " ", 1); - } - soap_append_lab(soap, SOAP_STR_EOS, 1); - t = soap_strdup(soap, soap->labbuf); - } - return t; -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEAN -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_s2wchar(struct soap *soap, const char *s, wchar_t **t, long minlen, long maxlen) -{ if (s) - { wchar_t *r; - *t = r = (wchar_t*)soap_malloc(soap, sizeof(wchar_t) * (strlen(s) + 1)); - if (!r) - return soap->error; - if (soap->mode & SOAP_ENC_LATIN) - { while (*s) - *r++ = (wchar_t)*s++; - } - else - { /* Convert UTF8 to wchar */ - while (*s) - { register soap_wchar c, c1, c2, c3, c4; - c = (unsigned char)*s++; - if (c < 0x80) - *r++ = (wchar_t)c; - else - { c1 = (soap_wchar)*s++ & 0x3F; - if (c < 0xE0) - *r++ = (wchar_t)(((soap_wchar)(c & 0x1F) << 6) | c1); - else - { c2 = (soap_wchar)*s++ & 0x3F; - if (c < 0xF0) - *r++ = (wchar_t)(((soap_wchar)(c & 0x0F) << 12) | (c1 << 6) | c2); - else - { c3 = (soap_wchar)*s++ & 0x3F; - if (c < 0xF8) - *r++ = (wchar_t)(((soap_wchar)(c & 0x07) << 18) | (c1 << 12) | (c2 << 6) | c3); - else - { c4 = (soap_wchar)*s++ & 0x3F; - if (c < 0xFC) - *r++ = (wchar_t)(((soap_wchar)(c & 0x03) << 24) | (c1 << 18) | (c2 << 12) | (c3 << 6) | c4); - else - *r++ = (wchar_t)(((soap_wchar)(c & 0x01) << 30) | (c1 << 24) | (c2 << 18) | (c3 << 12) | (c4 << 6) | (soap_wchar)(*s++ & 0x3F)); - } - } - } - } - } - } - *r = L'\0'; - if ((soap->mode & SOAP_XML_STRICT)) - { long l = (long)(r - *t); - if ((maxlen >= 0 && l > maxlen) || l < minlen) - soap->error = SOAP_LENGTH; - } - } - return soap->error; -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEAN -SOAP_FMAC1 -const char* -SOAP_FMAC2 -soap_wchar2s(struct soap *soap, const wchar_t *s) -{ register soap_wchar c; - register char *r, *t; - const wchar_t *q = s; - size_t n = 0; - while ((c = *q++)) - { if (c > 0 && c < 0x80) - n++; - else - n += 6; - } - r = t = (char*)soap_malloc(soap, n + 1); - if (r) - { /* Convert wchar to UTF8 */ - while ((c = *s++)) - { if (c > 0 && c < 0x80) - *t++ = (char)c; - else - { if (c < 0x0800) - *t++ = (char)(0xC0 | ((c >> 6) & 0x1F)); - else - { if (c < 0x010000) - *t++ = (char)(0xE0 | ((c >> 12) & 0x0F)); - else - { if (c < 0x200000) - *t++ = (char)(0xF0 | ((c >> 18) & 0x07)); - else - { if (c < 0x04000000) - *t++ = (char)(0xF8 | ((c >> 24) & 0x03)); - else - { *t++ = (char)(0xFC | ((c >> 30) & 0x01)); - *t++ = (char)(0x80 | ((c >> 24) & 0x3F)); - } - *t++ = (char)(0x80 | ((c >> 18) & 0x3F)); - } - *t++ = (char)(0x80 | ((c >> 12) & 0x3F)); - } - *t++ = (char)(0x80 | ((c >> 6) & 0x3F)); - } - *t++ = (char)(0x80 | (c & 0x3F)); - } - } - *t = '\0'; - } - return r; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_outstring(struct soap *soap, const char *tag, int id, char *const*p, const char *type, int n) -{ id = soap_element_id(soap, tag, id, *p, NULL, 0, type, n); - if (id < 0) - return soap->error; - if (!**p && (soap->mode & SOAP_C_NILSTRING)) - return soap_element_null(soap, tag, id, type); - if (soap_element_begin_out(soap, tag, id, type) - || soap_string_out(soap, *p, 0) - || soap_element_end_out(soap, tag)) - return soap->error; - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -char ** -SOAP_FMAC2 -soap_instring(struct soap *soap, const char *tag, char **p, const char *type, int t, int flag, long minlen, long maxlen) -{ if (soap_element_begin_in(soap, tag, 1, NULL)) - { if (!tag || *tag != '-' || soap->error != SOAP_NO_TAG) - return NULL; - soap->error = SOAP_OK; - } - if (!p) - { if (!(p = (char**)soap_malloc(soap, sizeof(char*)))) - return NULL; - } - if (soap->null) - *p = NULL; - else if (soap->body) - { *p = soap_string_in(soap, flag, minlen, maxlen); - if (!*p || !(char*)soap_id_enter(soap, soap->id, *p, t, sizeof(char*), 0, NULL, NULL, NULL)) - return NULL; - if (!**p && tag && *tag == '-') - { soap->error = SOAP_NO_TAG; - return NULL; - } - } - else if (tag && *tag == '-') - { soap->error = SOAP_NO_TAG; - return NULL; - } - else - *p = soap_strdup(soap, SOAP_STR_EOS); - if (*soap->href) - p = (char**)soap_id_lookup(soap, soap->href, (void**)p, t, sizeof(char**), 0); - if (soap->body && soap_element_end_in(soap, tag)) - return NULL; - return p; -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_outwstring(struct soap *soap, const char *tag, int id, wchar_t *const*p, const char *type, int n) -{ id = soap_element_id(soap, tag, id, *p, NULL, 0, type, n); - if (id < 0) - return soap->error; - if (!**p && (soap->mode & SOAP_C_NILSTRING)) - return soap_element_null(soap, tag, id, type); - if (soap_element_begin_out(soap, tag, id, type) - || soap_wstring_out(soap, *p, 0) - || soap_element_end_out(soap, tag)) - return soap->error; - return SOAP_OK; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_2 -SOAP_FMAC1 -wchar_t ** -SOAP_FMAC2 -soap_inwstring(struct soap *soap, const char *tag, wchar_t **p, const char *type, int t, long minlen, long maxlen) -{ if (soap_element_begin_in(soap, tag, 1, NULL)) - { if (!tag || *tag != '-' || soap->error != SOAP_NO_TAG) - return NULL; - soap->error = SOAP_OK; - } - if (!p) - { if (!(p = (wchar_t**)soap_malloc(soap, sizeof(wchar_t*)))) - return NULL; - } - if (soap->body) - { *p = soap_wstring_in(soap, 1, minlen, maxlen); - if (!*p || !(wchar_t*)soap_id_enter(soap, soap->id, *p, t, sizeof(wchar_t*), 0, NULL, NULL, NULL)) - return NULL; - if (!**p && tag && *tag == '-') - { soap->error = SOAP_NO_TAG; - return NULL; - } - } - else if (tag && *tag == '-') - { soap->error = SOAP_NO_TAG; - return NULL; - } - else if (soap->null) - *p = NULL; - else - *p = soap_wstrdup(soap, (wchar_t*)SOAP_STR_EOS); - if (*soap->href) - p = (wchar_t**)soap_id_lookup(soap, soap->href, (void**)p, t, sizeof(wchar_t**), 0); - if (soap->body && soap_element_end_in(soap, tag)) - return NULL; - return p; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEAN -SOAP_FMAC1 -time_t -SOAP_FMAC2 -soap_timegm(struct tm *T) -{ -#if defined(HAVE_TIMEGM) - return timegm(T); -#else - time_t t, g, z; - struct tm tm; - t = mktime(T); - if (t == (time_t)-1) - return (time_t)-1; -#ifdef HAVE_GMTIME_R - gmtime_r(&t, &tm); -#else - tm = *gmtime(&t); -#endif - tm.tm_isdst = 0; - g = mktime(&tm); - if (g == (time_t)-1) - return (time_t)-1; - z = g - t; - return t - z; -#endif -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEAN -SOAP_FMAC1 -const char* -SOAP_FMAC2 -soap_dateTime2s(struct soap *soap, time_t n) -{ struct tm T, *pT = &T; -#if defined(HAVE_GMTIME_R) - if (gmtime_r(&n, pT)) - strftime(soap->tmpbuf, sizeof(soap->tmpbuf), "%Y-%m-%dT%H:%M:%SZ", pT); -#elif defined(HAVE_GMTIME) - if ((pT = gmtime(&n))) - strftime(soap->tmpbuf, sizeof(soap->tmpbuf), "%Y-%m-%dT%H:%M:%SZ", pT); -#elif defined(HAVE_GETTIMEOFDAY) - struct timezone tz; - memset((void*)&tz, 0, sizeof(tz)); -#if defined(HAVE_LOCALTIME_R) - if (localtime_r(&n, pT)) - { struct timeval tv; - gettimeofday(&tv, &tz); - strftime(soap->tmpbuf, sizeof(soap->tmpbuf), "%Y-%m-%dT%H:%M:%S", pT); - sprintf(soap->tmpbuf + strlen(soap->tmpbuf), "%+03d:%02d", -tz.tz_minuteswest/60+(pT->tm_isdst!=0), abs(tz.tz_minuteswest)%60); - } -#else - if ((pT = localtime(&n))) - { struct timeval tv; - gettimeofday(&tv, &tz); - strftime(soap->tmpbuf, sizeof(soap->tmpbuf), "%Y-%m-%dT%H:%M:%S", pT); - sprintf(soap->tmpbuf + strlen(soap->tmpbuf), "%+03d:%02d", -tz.tz_minuteswest/60+(pT->tm_isdst!=0), abs(tz.tz_minuteswest)%60); - } -#endif -#elif defined(HAVE_FTIME) - struct timeb t; - memset((void*)&t, 0, sizeof(t)); -#if defined(HAVE_LOCALTIME_R) - if (localtime_r(&n, pT)) - { -#ifdef __BORLANDC__ - ::ftime(&t); -#else - ftime(&t); -#endif - strftime(soap->tmpbuf, sizeof(soap->tmpbuf), "%Y-%m-%dT%H:%M:%S", pT); - sprintf(soap->tmpbuf + strlen(soap->tmpbuf), "%+03d:%02d", -t.timezone/60+(pT->tm_isdst!=0), abs(t.timezone)%60); - } -#else - if ((pT = localtime(&n))) - { -#ifdef __BORLANDC__ - ::ftime(&t); -#else - ftime(&t); -#endif - strftime(soap->tmpbuf, sizeof(soap->tmpbuf), "%Y-%m-%dT%H:%M:%S", pT); - sprintf(soap->tmpbuf + strlen(soap->tmpbuf), "%+03d:%02d", -t.timezone/60+(pT->tm_isdst!=0), abs(t.timezone)%60); - } -#endif -#elif defined(HAVE_LOCALTIME_R) - if (localtime_r(&n, pT)) - strftime(soap->tmpbuf, sizeof(soap->tmpbuf), "%Y-%m-%dT%H:%M:%S", pT); -#else - if ((pT = localtime(&n))) - strftime(soap->tmpbuf, sizeof(soap->tmpbuf), "%Y-%m-%dT%H:%M:%S", pT); -#endif - else - strcpy(soap->tmpbuf, "1969-12-31T23:59:59Z"); - return soap->tmpbuf; -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEAN -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_outdateTime(struct soap *soap, const char *tag, int id, const time_t *p, const char *type, int n) -{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type) - || soap_string_out(soap, soap_dateTime2s(soap, *p), 0)) - return soap->error; - return soap_element_end_out(soap, tag); -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEAN -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_s2dateTime(struct soap *soap, const char *s, time_t *p) -{ if (s) - { char zone[32]; - struct tm T; - const char *t; - *zone = '\0'; - memset((void*)&T, 0, sizeof(T)); - if (strchr(s, '-')) - t = "%d-%d-%dT%d:%d:%d%31s"; - else if (strchr(s, ':')) - t = "%4d%2d%2dT%d:%d:%d%31s"; - else /* parse non-XSD-standard alternative ISO 8601 format */ - t = "%4d%2d%2dT%2d%2d%2d%31s"; - if (sscanf(s, t, &T.tm_year, &T.tm_mon, &T.tm_mday, &T.tm_hour, &T.tm_min, &T.tm_sec, zone) < 6) - return soap->error = SOAP_TYPE; - if (T.tm_year == 1) - T.tm_year = 70; - else - T.tm_year -= 1900; - T.tm_mon--; - if (*zone == '.') - { for (s = zone + 1; *s; s++) - if (*s < '0' || *s > '9') - break; - } - else - s = zone; - if (*s) - { -#ifndef WITH_NOZONE - if (*s == '+' || *s == '-') - { int h = 0, m = 0; - if (s[3] == ':') - { /* +hh:mm */ - sscanf(s, "%d:%d", &h, &m); - if (h < 0) - m = -m; - } - else /* +hhmm */ - { m = (int)atol(s); - h = m / 100; - m = m % 100; - } - T.tm_min -= m; - T.tm_hour -= h; - /* put hour and min in range */ - T.tm_hour += T.tm_min / 60; - T.tm_min %= 60; - if (T.tm_min < 0) - { T.tm_min += 60; - T.tm_hour--; - } - T.tm_mday += T.tm_hour / 24; - T.tm_hour %= 24; - if (T.tm_hour < 0) - { T.tm_hour += 24; - T.tm_mday--; - } - /* note: day of the month may be out of range, timegm() handles it */ - } -#endif - *p = soap_timegm(&T); - } - else /* no UTC or timezone, so assume we got a localtime */ - { T.tm_isdst = -1; - *p = mktime(&T); - } - } - return soap->error; -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEAN -SOAP_FMAC1 -time_t * -SOAP_FMAC2 -soap_indateTime(struct soap *soap, const char *tag, time_t *p, const char *type, int t) -{ if (soap_element_begin_in(soap, tag, 0, NULL)) - return NULL; - if (*soap->type - && soap_match_tag(soap, soap->type, type) - && soap_match_tag(soap, soap->type, ":dateTime")) - { soap->error = SOAP_TYPE; - soap_revert(soap); - return NULL; - } - p = (time_t*)soap_id_enter(soap, soap->id, p, t, sizeof(time_t), 0, NULL, NULL, NULL); - if (*soap->href) - p = (time_t*)soap_id_forward(soap, soap->href, p, 0, t, 0, sizeof(time_t), 0, NULL); - else if (p) - { if (soap_s2dateTime(soap, soap_value(soap), p)) - return NULL; - } - if (soap->body && soap_element_end_in(soap, tag)) - return NULL; - return p; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_outliteral(struct soap *soap, const char *tag, char *const*p, const char *type) -{ int i; - const char *t = NULL; - if (tag && *tag != '-') - { if (soap->local_namespaces && (t = strchr(tag, ':'))) - { strncpy(soap->tmpbuf, tag, t-tag); - soap->tmpbuf[t-tag] = '\0'; - for (i = 0; soap->local_namespaces[i].id; i++) - if (!strcmp(soap->tmpbuf, soap->local_namespaces[i].id)) - break; - t++; - if (soap_element(soap, t, 0, type) - || soap_attribute(soap, "xmlns", soap->local_namespaces[i].ns ? soap->local_namespaces[i].ns : SOAP_STR_EOS) - || soap_element_start_end_out(soap, NULL)) - return soap->error; - } - else - { t = tag; - if (soap_element_begin_out(soap, t, 0, type)) - return soap->error; - } - } - if (p && *p) - { if (soap_send(soap, *p)) - return soap->error; - } - if (t) - return soap_element_end_out(soap, t); - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -char ** -SOAP_FMAC2 -soap_inliteral(struct soap *soap, const char *tag, char **p) -{ if (soap_element_begin_in(soap, tag, 1, NULL)) - { if (soap->error != SOAP_NO_TAG || soap_unget(soap, soap_get(soap)) == SOAP_TT) - return NULL; - soap->error = SOAP_OK; - } - if (!p) - { if (!(p = (char**)soap_malloc(soap, sizeof(char*)))) - return NULL; - } - if (soap->body || (tag && *tag == '-')) - { *p = soap_string_in(soap, 0, -1, -1); - if (!*p) - return NULL; - if (!**p && tag && *tag == '-') - { soap->error = SOAP_NO_TAG; - return NULL; - } - } - else if (soap->null) - *p = NULL; - else - *p = soap_strdup(soap, SOAP_STR_EOS); - if (soap->body && soap_element_end_in(soap, tag)) - return NULL; - return p; -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_outwliteral(struct soap *soap, const char *tag, wchar_t *const*p, const char *type) -{ int i; - const char *t = NULL; - if (tag && *tag != '-') - { if (soap->local_namespaces && (t = strchr(tag, ':'))) - { strncpy(soap->tmpbuf, tag, t-tag); - soap->tmpbuf[t-tag] = '\0'; - for (i = 0; soap->local_namespaces[i].id; i++) - if (!strcmp(soap->tmpbuf, soap->local_namespaces[i].id)) - break; - t++; - if (soap_element(soap, t, 0, type) - || soap_attribute(soap, "xmlns", soap->local_namespaces[i].ns ? soap->local_namespaces[i].ns : SOAP_STR_EOS) - || soap_element_start_end_out(soap, NULL)) - return soap->error; - } - else - { t = tag; - if (soap_element_begin_out(soap, t, 0, type)) - return soap->error; - } - if (soap_send(soap, soap->tmpbuf)) - return soap->error; - } - if (p) - { wchar_t c; - const wchar_t *s = *p; - while ((c = *s++)) - { if (soap_pututf8(soap, (unsigned long)c)) - return soap->error; - } - } - if (t) - return soap_element_end_out(soap, t); - return SOAP_OK; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_2 -SOAP_FMAC1 -wchar_t ** -SOAP_FMAC2 -soap_inwliteral(struct soap *soap, const char *tag, wchar_t **p) -{ if (soap_element_begin_in(soap, tag, 1, NULL)) - { if (soap->error != SOAP_NO_TAG || soap_unget(soap, soap_get(soap)) == SOAP_TT) - return NULL; - soap->error = SOAP_OK; - } - if (!p) - { if (!(p = (wchar_t**)soap_malloc(soap, sizeof(wchar_t*)))) - return NULL; - } - if (soap->body) - { *p = soap_wstring_in(soap, 0, -1, -1); - if (!*p) - return NULL; - if (!**p && tag && *tag == '-') - { soap->error = SOAP_NO_TAG; - return NULL; - } - } - else if (tag && *tag == '-') - { soap->error = SOAP_NO_TAG; - return NULL; - } - else if (soap->null) - *p = NULL; - else - *p = soap_wstrdup(soap, (wchar_t*)SOAP_STR_EOS); - if (soap->body && soap_element_end_in(soap, tag)) - return NULL; - return p; -} -#endif -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -const char * -SOAP_FMAC2 -soap_value(struct soap *soap) -{ register size_t i; - register soap_wchar c = 0; - register char *s = soap->tmpbuf; - if (!soap->body) - return SOAP_STR_EOS; - do c = soap_get(soap); - while (soap_blank(c)); - for (i = 0; i < sizeof(soap->tmpbuf) - 1; i++) - { if (c == SOAP_TT || (int)c == EOF) - break; - *s++ = (char)c; - c = soap_get(soap); - } - for (s--; i > 0; i--, s--) - { if (!soap_blank(*s)) - break; - } - s[1] = '\0'; - if ((int)c == EOF || c == SOAP_TT) - soap_unget(soap, c); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Element content value='%s'\n", soap->tmpbuf)); -#ifdef WITH_DOM - if ((soap->mode & SOAP_XML_DOM) && soap->dom) - soap->dom->data = soap_strdup(soap, soap->tmpbuf); -#endif - return soap->tmpbuf; /* return non-null pointer */ -} -#endif - -/******************************************************************************/ -#if !defined(WITH_LEANER) || !defined(WITH_NOHTTP) -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_getline(struct soap *soap, char *s, int len) -{ int i = len; - soap_wchar c = 0; - for (;;) - { while (--i > 0) - { c = soap_getchar(soap); - if (c == '\r' || c == '\n') - break; - if ((int)c == EOF) - return soap->error = SOAP_EOF; - *s++ = (char)c; - } - if (c != '\n') - c = soap_getchar(soap); /* got \r or something else, now get \n */ - if (c == '\n') - { *s = '\0'; - if (i+1 == len) /* empty line: end of HTTP/MIME header */ - break; - c = soap_get0(soap); - if (c != ' ' && c != '\t') /* HTTP line continuation? */ - break; - } - else if ((int)c == EOF) - return soap->error = SOAP_EOF; - if (i < 0) - return soap->error = SOAP_HDR; - } - return SOAP_OK; -} -#endif -#endif - -/******************************************************************************/ -#ifndef PALM_1 -static size_t -soap_count_attachments(struct soap *soap) -{ -#ifndef WITH_LEANER - register struct soap_multipart *content; - register size_t count = soap->count; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Calculating the message size with attachments, current count=%lu\n", (unsigned long)count)); - if ((soap->mode & SOAP_ENC_DIME) && !(soap->mode & SOAP_ENC_MTOM)) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Calculating the size of DIME attachments\n")); - for (content = soap->dime.first; content; content = content->next) - { count += 12 + ((content->size+3)&(~3)); - if (content->id) - count += ((strlen(content->id)+3)&(~3)); - if (content->type) - count += ((strlen(content->type)+3)&(~3)); - if (content->options) - count += ((((unsigned char)content->options[2] << 8) | ((unsigned char)content->options[3]))+7)&(~3); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Size of DIME attachment content is %lu bytes\n", (unsigned long)content->size)); - } - } - if ((soap->mode & SOAP_ENC_MIME) && soap->mime.boundary) - { register size_t n = strlen(soap->mime.boundary); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Calculating the size of MIME attachments\n")); - for (content = soap->mime.first; content; content = content->next) - { register const char *s; - /* count \r\n--boundary\r\n */ - count += 6 + n; - /* count Content-Type: ...\r\n */ - if (content->type) - count += 16 + strlen(content->type); - /* count Content-Transfer-Encoding: ...\r\n */ - s = soap_code_str(mime_codes, content->encoding); - if (s) - count += 29 + strlen(s); - /* count Content-ID: ...\r\n */ - if (content->id) - count += 14 + strlen(content->id); - /* count Content-Location: ...\r\n */ - if (content->location) - count += 20 + strlen(content->location); - /* count Content-Description: ...\r\n */ - if (content->description) - count += 23 + strlen(content->description); - /* count \r\n...content */ - count += 2 + content->size; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Size of MIME attachment content is %lu bytes\n", (unsigned long)content->size)); - } - /* count \r\n--boundary-- */ - count += 6 + n; - } - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "New count is %lu bytes\n", (unsigned long)count)); - return count; -#else - return soap->count; -#endif -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -static int -soap_putdimefield(struct soap *soap, const char *s, size_t n) -{ if (soap_send_raw(soap, s, n)) - return soap->error; - return soap_send_raw(soap, SOAP_STR_PADDING, -(long)n&3); -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -SOAP_FMAC1 -char * -SOAP_FMAC2 -soap_dime_option(struct soap *soap, unsigned short optype, const char *option) -{ size_t n; - char *s = NULL; - if (option) - { n = strlen(option); - s = (char*)soap_malloc(soap, n + 5); - if (s) - { s[0] = (char)(optype >> 8); - s[1] = (char)(optype & 0xFF); - s[2] = (char)(n >> 8); - s[3] = (char)(n & 0xFF); - strcpy(s + 4, option); - } - } - return s; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_putdimehdr(struct soap *soap) -{ unsigned char tmp[12]; - size_t optlen = 0, idlen = 0, typelen = 0; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Put DIME header id='%s'\n", soap->dime.id?soap->dime.id:SOAP_STR_EOS)); - if (soap->dime.options) - optlen = (((unsigned char)soap->dime.options[2] << 8) | ((unsigned char)soap->dime.options[3])) + 4; - if (soap->dime.id) - { idlen = strlen(soap->dime.id); - if (idlen > 0x0000FFFF) - idlen = 0x0000FFFF; - } - if (soap->dime.type) - { typelen = strlen(soap->dime.type); - if (typelen > 0x0000FFFF) - typelen = 0x0000FFFF; - } - tmp[0] = SOAP_DIME_VERSION | (soap->dime.flags & 0x7); - tmp[1] = soap->dime.flags & 0xF0; - tmp[2] = (char)(optlen >> 8); - tmp[3] = (char)(optlen & 0xFF); - tmp[4] = (char)(idlen >> 8); - tmp[5] = (char)(idlen & 0xFF); - tmp[6] = (char)(typelen >> 8); - tmp[7] = (char)(typelen & 0xFF); - tmp[8] = (char)(soap->dime.size >> 24); - tmp[9] = (char)((soap->dime.size >> 16) & 0xFF); - tmp[10] = (char)((soap->dime.size >> 8) & 0xFF); - tmp[11] = (char)(soap->dime.size & 0xFF); - if (soap_send_raw(soap, (char*)tmp, 12) - || soap_putdimefield(soap, soap->dime.options, optlen) - || soap_putdimefield(soap, soap->dime.id, idlen) - || soap_putdimefield(soap, soap->dime.type, typelen)) - return soap->error; - return SOAP_OK; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_putdime(struct soap *soap) -{ struct soap_multipart *content; - if (!(soap->mode & SOAP_ENC_DIME)) - return SOAP_OK; - for (content = soap->dime.first; content; content = content->next) - { void *handle; - soap->dime.size = content->size; - soap->dime.id = content->id; - soap->dime.type = content->type; - soap->dime.options = content->options; - soap->dime.flags = SOAP_DIME_VERSION | SOAP_DIME_MEDIA; - if (soap->fdimereadopen && ((handle = soap->fdimereadopen(soap, (void*)content->ptr, content->id, content->type, content->options)) || soap->error)) - { size_t size = content->size; - if (!handle) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "fdimereadopen failed\n")); - return soap->error; - } - if (!size && ((soap->mode & SOAP_ENC_XML) || (soap->mode & SOAP_IO) == SOAP_IO_CHUNK || (soap->mode & SOAP_IO) == SOAP_IO_STORE)) - { size_t chunksize = sizeof(soap->tmpbuf); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Chunked streaming DIME\n")); - do - { size = soap->fdimeread(soap, handle, soap->tmpbuf, chunksize); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "fdimeread returned %lu bytes\n", (unsigned long)size)); - if (size < chunksize) - { soap->dime.flags &= ~SOAP_DIME_CF; - if (!content->next) - soap->dime.flags |= SOAP_DIME_ME; - } - else - soap->dime.flags |= SOAP_DIME_CF; - soap->dime.size = size; - if (soap_putdimehdr(soap) - || soap_putdimefield(soap, soap->tmpbuf, size)) - break; - if (soap->dime.id) - { soap->dime.flags &= ~(SOAP_DIME_MB | SOAP_DIME_MEDIA); - soap->dime.id = NULL; - soap->dime.type = NULL; - soap->dime.options = NULL; - } - } while (size >= chunksize); - } - else - { if (!content->next) - soap->dime.flags |= SOAP_DIME_ME; - if (soap_putdimehdr(soap)) - return soap->error; - do - { size_t bufsize; - if (size < sizeof(soap->tmpbuf)) - bufsize = size; - else - bufsize = sizeof(soap->tmpbuf); - if (!(bufsize = soap->fdimeread(soap, handle, soap->tmpbuf, bufsize))) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "fdimeread failed: insufficient data (%lu bytes remaining from %lu bytes)\n", (unsigned long)size, (unsigned long)content->size)); - soap->error = SOAP_EOF; - break; - } - if (soap_send_raw(soap, soap->tmpbuf, bufsize)) - break; - size -= bufsize; - } while (size); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "fdimereadclose\n")); - soap_send_raw(soap, SOAP_STR_PADDING, -(long)soap->dime.size&3); - } - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "fdimereadclose\n")); - if (soap->fdimereadclose) - soap->fdimereadclose(soap, handle); - } - else - { if (!content->next) - soap->dime.flags |= SOAP_DIME_ME; - if (soap_putdimehdr(soap) - || soap_putdimefield(soap, (char*)content->ptr, content->size)) - return soap->error; - } - } - return SOAP_OK; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -static char * -soap_getdimefield(struct soap *soap, size_t n) -{ register soap_wchar c; - register size_t i; - register char *s; - register char *p = NULL; - if (n) - { p = (char*)soap_malloc(soap, n + 1); - if (p) - { s = p; - for (i = n; i > 0; i--) - { if ((int)(c = soap_get1(soap)) == EOF) - { soap->error = SOAP_EOF; - return NULL; - } - *s++ = (char)c; - } - *s = '\0'; - if ((soap->error = soap_move(soap, -(long)n&3))) - return NULL; - } - else - soap->error = SOAP_EOM; - } - return p; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_getdimehdr(struct soap *soap) -{ register soap_wchar c; - register char *s; - register int i; - unsigned char tmp[12]; - size_t optlen, idlen, typelen; - if (!(soap->mode & SOAP_ENC_DIME)) - return soap->error = SOAP_DIME_END; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Get DIME header\n")); - if (soap->dime.buflen || soap->dime.chunksize) - { if (soap_move(soap, (long)(soap->dime.size - soap_tell(soap)))) - return soap->error = SOAP_EOF; - soap_unget(soap, soap_getchar(soap)); /* skip padding and get hdr */ - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "... From chunked\n")); - return SOAP_OK; - } - s = (char*)tmp; - for (i = 12; i > 0; i--) - { if ((int)(c = soap_getchar(soap)) == EOF) - return soap->error = SOAP_EOF; - *s++ = (char)c; - } - if ((tmp[0] & 0xF8) != SOAP_DIME_VERSION) - return soap->error = SOAP_DIME_MISMATCH; - soap->dime.flags = (tmp[0] & 0x7) | (tmp[1] & 0xF0); - optlen = (tmp[2] << 8) | tmp[3]; - idlen = (tmp[4] << 8) | tmp[5]; - typelen = (tmp[6] << 8) | tmp[7]; - soap->dime.size = (tmp[8] << 24) | (tmp[9] << 16) | (tmp[10] << 8) | tmp[11]; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "DIME size=%lu flags=0x%X\n", (unsigned long)soap->dime.size, soap->dime.flags)); - if (!(soap->dime.options = soap_getdimefield(soap, optlen)) && soap->error) - return soap->error; - if (!(soap->dime.id = soap_getdimefield(soap, idlen)) && soap->error) - return soap->error; - if (!(soap->dime.type = soap_getdimefield(soap, typelen)) && soap->error) - return soap->error; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "DIME id=%s, type=%s, options=%s\n", soap->dime.id?soap->dime.id:SOAP_STR_EOS, soap->dime.type?soap->dime.type:"", soap->dime.options?soap->dime.options+4:SOAP_STR_EOS)); - if (soap->dime.flags & SOAP_DIME_ME) - soap->mode &= ~SOAP_ENC_DIME; - return SOAP_OK; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_getdime(struct soap *soap) -{ while (soap->dime.flags & SOAP_DIME_CF) - { if (soap_getdimehdr(soap)) - return soap->error; - if (soap_move(soap, (long)soap->dime.size)) - return soap->error = SOAP_EOF; - } - if (soap_move(soap, (long)(((soap->dime.size+3)&(~3))-soap_tell(soap)))) - return soap->error = SOAP_EOF; - for (;;) - { register struct soap_multipart *content; - if (soap_getdimehdr(soap)) - break; - if (soap->fdimewriteopen && ((soap->dime.ptr = (char*)soap->fdimewriteopen(soap, soap->dime.id, soap->dime.type, soap->dime.options)) || soap->error)) - { const char *id, *type, *options; - size_t size, n; - if (!soap->dime.ptr) - return soap->error; - id = soap->dime.id; - type = soap->dime.type; - options = soap->dime.options; - for (;;) - { size = soap->dime.size; - for (;;) - { n = soap->buflen - soap->bufidx; - if (size < n) - n = size; - if ((soap->error = soap->fdimewrite(soap, (void*)soap->dime.ptr, soap->buf + soap->bufidx, n))) - break; - size -= n; - if (!size) - { soap->bufidx += n; - break; - } - if (soap_recv(soap)) - { soap->error = SOAP_EOF; - goto end; - } - } - if (soap_move(soap, -(long)soap->dime.size&3)) - { soap->error = SOAP_EOF; - break; - } - if (!(soap->dime.flags & SOAP_DIME_CF)) - break; - if (soap_getdimehdr(soap)) - break; - } -end: - if (soap->fdimewriteclose) - soap->fdimewriteclose(soap, (void*)soap->dime.ptr); - soap->dime.size = 0; - soap->dime.id = id; - soap->dime.type = type; - soap->dime.options = options; - } - else if (soap->dime.flags & SOAP_DIME_CF) - { const char *id, *type, *options; - id = soap->dime.id; - type = soap->dime.type; - options = soap->dime.options; - if (soap_new_block(soap) == NULL) - return SOAP_EOM; - for (;;) - { register soap_wchar c; - register size_t i; - register char *s; - s = (char*)soap_push_block(soap, NULL, soap->dime.size); - if (!s) - return soap->error = SOAP_EOM; - for (i = soap->dime.size; i > 0; i--) - { if ((int)(c = soap_get1(soap)) == EOF) - return soap->error = SOAP_EOF; - *s++ = (char)c; - } - if (soap_move(soap, -(long)soap->dime.size&3)) - return soap->error = SOAP_EOF; - if (!(soap->dime.flags & SOAP_DIME_CF)) - break; - if (soap_getdimehdr(soap)) - return soap->error; - } - soap->dime.size = soap->blist->size++; /* allocate one more for '\0' */ - if (!(soap->dime.ptr = soap_save_block(soap, NULL, NULL, 0))) - return soap->error; - soap->dime.ptr[soap->dime.size] = '\0'; /* force 0-terminated */ - soap->dime.id = id; - soap->dime.type = type; - soap->dime.options = options; - } - else - soap->dime.ptr = soap_getdimefield(soap, soap->dime.size); - content = soap_new_multipart(soap, &soap->dime.first, &soap->dime.last, soap->dime.ptr, soap->dime.size); - if (!content) - return soap->error = SOAP_EOM; - content->id = soap->dime.id; - content->type = soap->dime.type; - content->options = soap->dime.options; - if (soap->error) - return soap->error; - soap_resolve_attachment(soap, content); - } - if (soap->error != SOAP_DIME_END) - return soap->error; - return soap->error = SOAP_OK; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_getmimehdr(struct soap *soap) -{ struct soap_multipart *content; - do - { if (soap_getline(soap, soap->msgbuf, sizeof(soap->msgbuf))) - return soap->error; - } - while (!*soap->msgbuf); - if (soap->msgbuf[0] == '-' && soap->msgbuf[1] == '-') - { char *s = soap->msgbuf + strlen(soap->msgbuf) - 1; - /* remove white space */ - while (soap_blank(*s)) - s--; - s[1] = '\0'; - if (soap->mime.boundary) - { if (strcmp(soap->msgbuf + 2, soap->mime.boundary)) - return soap->error = SOAP_MIME_ERROR; - } - else - soap->mime.boundary = soap_strdup(soap, soap->msgbuf + 2); - if (soap_getline(soap, soap->msgbuf, sizeof(soap->msgbuf))) - return soap->error; - } - if (soap_set_mime_attachment(soap, NULL, 0, SOAP_MIME_NONE, NULL, NULL, NULL, NULL)) - return soap->error = SOAP_EOM; - content = soap->mime.last; - for (;;) - { register char *key = soap->msgbuf; - register char *val; - if (!*key) - break; - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "MIME header: %s\n", key)); - val = strchr(soap->msgbuf, ':'); - if (val) - { *val = '\0'; - do val++; - while (*val && *val <= 32); - if (!soap_tag_cmp(key, "Content-ID")) - content->id = soap_strdup(soap, val); - else if (!soap_tag_cmp(key, "Content-Location")) - content->location = soap_strdup(soap, val); - else if (!soap_tag_cmp(key, "Content-Disposition")) - content->id = soap_strdup(soap, soap_get_header_attribute(soap, val, "name")); - else if (!soap_tag_cmp(key, "Content-Type")) - content->type = soap_strdup(soap, val); - else if (!soap_tag_cmp(key, "Content-Description")) - content->description = soap_strdup(soap, val); - else if (!soap_tag_cmp(key, "Content-Transfer-Encoding")) - content->encoding = (enum soap_mime_encoding)soap_code_int(mime_codes, val, (long)SOAP_MIME_NONE); - } - if (soap_getline(soap, key, sizeof(soap->msgbuf))) - return soap->error; - } - return SOAP_OK; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_getmime(struct soap *soap) -{ while (soap_get_mime_attachment(soap, NULL)) - ; - return soap->error; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_post_check_mime_attachments(struct soap *soap) -{ soap->imode |= SOAP_MIME_POSTCHECK; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_check_mime_attachments(struct soap *soap) -{ if (soap->mode & SOAP_MIME_POSTCHECK) - return soap_get_mime_attachment(soap, NULL) != NULL; - return 0; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -SOAP_FMAC1 -struct soap_multipart * -SOAP_FMAC2 -soap_get_mime_attachment(struct soap *soap, void *handle) -{ register soap_wchar c = 0; - register size_t i, m = 0; - register char *s, *t = NULL; - register struct soap_multipart *content; - register short flag = 0; - if (!(soap->mode & SOAP_ENC_MIME)) - return NULL; - content = soap->mime.last; - if (!content) - { if (soap_getmimehdr(soap)) - return NULL; - content = soap->mime.last; - } - else if (content != soap->mime.first) - { if (soap->fmimewriteopen && ((content->ptr = (char*)soap->fmimewriteopen(soap, (void*)handle, content->id, content->type, content->description, content->encoding)) || soap->error)) - { if (!content->ptr) - return NULL; - } - } - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Parsing MIME content id=%s type=%s\n", content->id?content->id:SOAP_STR_EOS, content->type?content->type:SOAP_STR_EOS)); - if (!content->ptr && soap_new_block(soap) == NULL) - { soap->error = SOAP_EOM; - return NULL; - } - for (;;) - { if (content->ptr) - s = soap->tmpbuf; - else if (!(s = (char*)soap_push_block(soap, NULL, sizeof(soap->tmpbuf)))) - { soap->error = SOAP_EOM; - return NULL; - } - for (i = 0; i < sizeof(soap->tmpbuf); i++) - { if (m > 0) - { *s++ = *t++; - m--; - } - else - { if (!flag) - { c = soap_get1(soap); - if ((int)c == EOF) - { soap->error = SOAP_EOF; - return NULL; - } - } - if (flag || c == '\r') - { t = soap->msgbuf; - memset(t, 0, sizeof(soap->msgbuf)); - strcpy(t, "\n--"); - if (soap->mime.boundary) - strncat(t, soap->mime.boundary, sizeof(soap->msgbuf)-4); - do c = soap_getchar(soap); - while (c == *t++); - if ((int)c == EOF) - { soap->error = SOAP_EOF; - return NULL; - } - if (!*--t) - goto end; - *t = (char)c; - flag = (c == '\r'); - m = t - soap->msgbuf + 1 - flag; - t = soap->msgbuf; - c = '\r'; - } - *s++ = (char)c; - } - } - if (content->ptr && soap->fmimewrite) - { if ((soap->error = soap->fmimewrite(soap, (void*)content->ptr, soap->tmpbuf, i))) - break; - } - } -end: - *s = '\0'; /* force 0-terminated */ - if (content->ptr) - { if (!soap->error && soap->fmimewrite) - soap->error = soap->fmimewrite(soap, (void*)content->ptr, soap->tmpbuf, i); - if (soap->fmimewriteclose) - soap->fmimewriteclose(soap, (void*)content->ptr); - if (soap->error) - return NULL; - } - else - { content->size = soap_size_block(soap, NULL, i+1)-1; - content->ptr = soap_save_block(soap, NULL, NULL, 0); - } - soap_resolve_attachment(soap, content); - if (c == '-' && soap_getchar(soap) == '-') - { soap->mode &= ~SOAP_ENC_MIME; - if ((soap->mode & SOAP_MIME_POSTCHECK) && soap_end_recv(soap)) - return NULL; - } - else - { while (c != '\r' && (int)c != EOF && soap_blank(c)) - c = soap_getchar(soap); - if (c != '\r' || soap_getchar(soap) != '\n') - { soap->error = SOAP_MIME_ERROR; - return NULL; - } - if (soap_getmimehdr(soap)) - return NULL; - } - return content; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_match_cid(struct soap *soap, const char *s, const char *t) -{ register size_t n; - if (!s) - return 1; - if (!strcmp(s, t)) - return 0; - if (!strncmp(s, "cid:", 4)) - s += 4; - n = strlen(t); - if (*t == '<') - { t++; - n -= 2; - } - if (!strncmp(s, t, n) && !s[n]) - return 0; - soap_decode(soap->tmpbuf, sizeof(soap->tmpbuf), s, SOAP_STR_EOS); - if (!strncmp(soap->tmpbuf, t, n) && !soap->tmpbuf[n]) - return 0; - return 1; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -static void -soap_resolve_attachment(struct soap *soap, struct soap_multipart *content) -{ if (content->id) - { register struct soap_xlist **xp = &soap->xlist; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Resolving attachment data for id=%s\n", content->id)); - while (*xp) - { register struct soap_xlist *xq = *xp; - if (!soap_match_cid(soap, xq->id, content->id)) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Found matching attachment %s for content id=%s\n", xq->id, content->id)); - *xp = xq->next; - *xq->ptr = (unsigned char*)content->ptr; - *xq->size = (int)content->size; - *xq->type = (char*)content->type; - if (content->options) - *xq->options = (char*)content->options; - else - *xq->options = (char*)content->description; - SOAP_FREE(soap, xq); - } - else - xp = &(*xp)->next; - } - } -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_putmimehdr(struct soap *soap, struct soap_multipart *content) -{ const char *s; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "MIME attachment type=%s\n", content->type?content->type:SOAP_STR_EOS)); - if (soap_send3(soap, "\r\n--", soap->mime.boundary, "\r\n")) - return soap->error; - if (content->type && soap_send3(soap, "Content-Type: ", content->type, "\r\n")) - return soap->error; - s = soap_code_str(mime_codes, content->encoding); - if (s && soap_send3(soap, "Content-Transfer-Encoding: ", s, "\r\n")) - return soap->error; - if (content->id && soap_send3(soap, "Content-ID: ", content->id, "\r\n")) - return soap->error; - if (content->location && soap_send3(soap, "Content-Location: ", content->location, "\r\n")) - return soap->error; - if (content->description && soap_send3(soap, "Content-Description: ", content->description, "\r\n")) - return soap->error; - return soap_send_raw(soap, "\r\n", 2); -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_putmime(struct soap *soap) -{ struct soap_multipart *content; - if (!(soap->mode & SOAP_ENC_MIME) || !soap->mime.boundary) - return SOAP_OK; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Sending MIME attachments\n")); - for (content = soap->mime.first; content; content = content->next) - { void *handle; - if (soap->fmimereadopen && ((handle = soap->fmimereadopen(soap, (void*)content->ptr, content->id, content->type, content->description)) || soap->error)) - { size_t size = content->size; - if (!handle) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "fmimereadopen failed\n")); - return soap->error; - } - if (soap_putmimehdr(soap, content)) - return soap->error; - if (!size) - { if ((soap->mode & SOAP_ENC_XML) || (soap->mode & SOAP_IO) == SOAP_IO_CHUNK || (soap->mode & SOAP_IO) == SOAP_IO_STORE) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Chunked streaming MIME\n")); - do - { size = soap->fmimeread(soap, handle, soap->tmpbuf, sizeof(soap->tmpbuf)); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "fmimeread returned %lu bytes\n", (unsigned long)size)); - if (soap_send_raw(soap, soap->tmpbuf, size)) - break; - } while (size); - } - else - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Error: cannot chunk streaming MIME (no HTTP chunking)\n")); - } - } - else - { do - { size_t bufsize; - if (size < sizeof(soap->tmpbuf)) - bufsize = size; - else - bufsize = sizeof(soap->tmpbuf); - if (!(bufsize = soap->fmimeread(soap, handle, soap->tmpbuf, bufsize))) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "fmimeread failed: insufficient data (%lu bytes remaining from %lu bytes)\n", (unsigned long)size, (unsigned long)content->size)); - soap->error = SOAP_EOF; - break; - } - if (soap_send_raw(soap, soap->tmpbuf, bufsize)) - break; - size -= bufsize; - } while (size); - } - if (soap->fmimereadclose) - soap->fmimereadclose(soap, handle); - } - else - { if (soap_putmimehdr(soap, content) - || soap_send_raw(soap, content->ptr, content->size)) - return soap->error; - } - } - return soap_send3(soap, "\r\n--", soap->mime.boundary, "--"); -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_set_dime(struct soap *soap) -{ soap->omode |= SOAP_ENC_DIME; - soap->dime.first = NULL; - soap->dime.last = NULL; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_set_mime(struct soap *soap, const char *boundary, const char *start) -{ soap->omode |= SOAP_ENC_MIME; - soap->mime.first = NULL; - soap->mime.last = NULL; - soap->mime.boundary = soap_strdup(soap, boundary); - soap->mime.start = soap_strdup(soap, start); -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_clr_dime(struct soap *soap) -{ soap->omode &= ~SOAP_ENC_DIME; - soap->dime.first = NULL; - soap->dime.last = NULL; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_clr_mime(struct soap *soap) -{ soap->omode &= ~SOAP_ENC_MIME; - soap->mime.first = NULL; - soap->mime.last = NULL; - soap->mime.boundary = NULL; - soap->mime.start = NULL; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -static struct soap_multipart* -soap_new_multipart(struct soap *soap, struct soap_multipart **first, struct soap_multipart **last, char *ptr, size_t size) -{ struct soap_multipart *content; - content = (struct soap_multipart*)soap_malloc(soap, sizeof(struct soap_multipart)); - if (content) - { content->next = NULL; - content->ptr = ptr; - content->size = size; - content->id = NULL; - content->type = NULL; - content->options = NULL; - content->encoding = SOAP_MIME_NONE; - content->location = NULL; - content->description = NULL; - if (!*first) - *first = content; - if (*last) - (*last)->next = content; - *last = content; - } - return content; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_set_dime_attachment(struct soap *soap, char *ptr, size_t size, const char *type, const char *id, unsigned short optype, const char *option) -{ struct soap_multipart *content = soap_new_multipart(soap, &soap->dime.first, &soap->dime.last, ptr, size); - if (!content) - return SOAP_EOM; - content->id = soap_strdup(soap, id); - content->type = soap_strdup(soap, type); - content->options = soap_dime_option(soap, optype, option); - return SOAP_OK; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_set_mime_attachment(struct soap *soap, char *ptr, size_t size, enum soap_mime_encoding encoding, const char *type, const char *id, const char *location, const char *description) -{ struct soap_multipart *content = soap_new_multipart(soap, &soap->mime.first, &soap->mime.last, ptr, size); - if (!content) - return SOAP_EOM; - content->id = soap_strdup(soap, id); - content->type = soap_strdup(soap, type); - content->encoding = encoding; - content->location = soap_strdup(soap, location); - content->description = soap_strdup(soap, description); - return SOAP_OK; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -SOAP_FMAC1 -struct soap_multipart* -SOAP_FMAC2 -soap_next_multipart(struct soap_multipart *content) -{ if (content) - return content->next; - return NULL; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -static void -soap_select_mime_boundary(struct soap *soap) -{ while (!soap->mime.boundary || soap_valid_mime_boundary(soap)) - { register char *s = soap->mime.boundary; - register size_t n = 0; - if (s) - n = strlen(s); - if (n < 16) - { n = 64; - s = soap->mime.boundary = (char*)soap_malloc(soap, n + 1); - if (!s) - return; - } - strcpy(s, "=="); - s += 2; - n -= 4; - while (n) - { *s++ = soap_base64o[soap_random & 0x3F]; - n--; - } - strcpy(s, "=="); - } - if (!soap->mime.start) - soap->mime.start = ""; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEANER -#ifndef PALM_1 -static int -soap_valid_mime_boundary(struct soap *soap) -{ register struct soap_multipart *content; - register size_t k; - if (soap->fmimeread) - return SOAP_OK; - k = strlen(soap->mime.boundary); - for (content = soap->mime.first; content; content = content->next) - { if (content->ptr && content->size >= k) - { register const char *p = (const char*)content->ptr; - register size_t i; - for (i = 0; i < content->size - k; i++, p++) - { if (!strncmp(p, soap->mime.boundary, k)) - return SOAP_ERR; - } - } - } - return SOAP_OK; -} -#endif -#endif - -/******************************************************************************\ - * - * HTTP cookie handling - * -\******************************************************************************/ - -#ifdef WITH_COOKIES -/******************************************************************************/ -SOAP_FMAC1 -size_t -SOAP_FMAC2 -soap_encode_cookie(const char *s, char *t, size_t len) -{ register int c; - register size_t n = len; - while ((c = *s++) && --n > 0) - { if (c > ' ' && c < 128 && !strchr("()<>@,;:\\\"/[]?={}#!$&'*+", c)) - *t++ = c; - else if (n > 2) - { *t++ = '%'; - *t++ = (c >> 4) + (c > 159 ? '7' : '0'); - c &= 0xF; - *t++ = c + (c > 9 ? '7' : '0'); - n -= 2; - } - else - break; - } - *t = '\0'; - return len - n; -} - -/******************************************************************************/ -SOAP_FMAC1 -struct soap_cookie* -SOAP_FMAC2 -soap_cookie(struct soap *soap, const char *name, const char *domain, const char *path) -{ struct soap_cookie *p; - if (!domain) - domain = soap->cookie_domain; - if (!path) - path = soap->cookie_path; - if (!path) - path = SOAP_STR_EOS; - else if (*path == '/') - path++; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Search cookie %s domain=%s path=%s\n", name, domain?domain:"(null)", path?path:"(null)")); - for (p = soap->cookies; p; p = p->next) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Cookie in database: %s=%s domain=%s path=%s env=%hd\n", p->name, p->value?p->value:"(null)", p->domain?p->domain:"(null)", p->path?p->path:"(null)", p->env)); - if (!strcmp(p->name, name) - && p->domain - && p->path - && !strcmp(p->domain, domain) - && (!*p->path || !strncmp(p->path, path, strlen(p->path)))) - break; - } - return p; -} - -/******************************************************************************/ -SOAP_FMAC1 -struct soap_cookie* -SOAP_FMAC2 -soap_set_cookie(struct soap *soap, const char *name, const char *value, const char *domain, const char *path) -{ struct soap_cookie **p, *q; - int n; - if (!domain) - domain = soap->cookie_domain; - if (!path) - path = soap->cookie_path; - if (!path) - path = SOAP_STR_EOS; - else if (*path == '/') - path++; - q = soap_cookie(soap, name, domain, path); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Set %scookie: %s=%s domain=%s path=%s\n", q ? SOAP_STR_EOS : "new ", name, value?value:"(null)", domain?domain:"(null)", path?path:"(null)")); - if (!q) - { if ((q = (struct soap_cookie*)SOAP_MALLOC(soap, sizeof(struct soap_cookie)))) - { if ((q->name = (char*)SOAP_MALLOC(soap, strlen(name)+1))) - strcpy(q->name, name); - q->value = NULL; - q->domain = NULL; - q->path = NULL; - q->expire = 0; - q->maxage = -1; - q->version = 1; - q->secure = 0; - q->modified = 0; - for (p = &soap->cookies, n = soap->cookie_max; *p && n; p = &(*p)->next, n--) - if (!strcmp((*p)->name, name) && (*p)->path && path && strcmp((*p)->path, path) < 0) - break; - if (n) - { q->next = *p; - *p = q; - } - else - { SOAP_FREE(soap, q->name); - SOAP_FREE(soap, q); - q = NULL; - } - } - } - else - q->modified = 1; - if (q) - { if (q->value) - { if (!value || strcmp(value, q->value)) - { SOAP_FREE(soap, q->value); - q->value = NULL; - } - } - if (value && *value && !q->value && (q->value = (char*)SOAP_MALLOC(soap, strlen(value)+1))) - strcpy(q->value, value); - if (q->domain) - { if (!domain || strcmp(domain, q->domain)) - { SOAP_FREE(soap, q->domain); - q->domain = NULL; - } - } - if (domain && !q->domain && (q->domain = (char*)SOAP_MALLOC(soap, strlen(domain)+1))) - strcpy(q->domain, domain); - if (q->path) - { if (!path || strncmp(path, q->path, strlen(q->path))) - { SOAP_FREE(soap, q->path); - q->path = NULL; - } - } - if (path && !q->path && (q->path = (char*)SOAP_MALLOC(soap, strlen(path)+1))) - strcpy(q->path, path); - q->session = 1; - q->env = 0; - } - return q; -} - -/******************************************************************************/ -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_clr_cookie(struct soap *soap, const char *name, const char *domain, const char *path) -{ struct soap_cookie **p, *q; - if (!domain) - domain = soap->cookie_domain; - if (!domain) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Error in clear cookie %s: cookie domain not set\n", name?name:"(null)")); - return; - } - if (!path) - path = soap->cookie_path; - if (!path) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Error in clear cookie %s: cookie path not set\n", name?name:"(null)")); - return; - } - if (*path == '/') - path++; - for (p = &soap->cookies, q = *p; q; q = *p) - { if (!strcmp(q->name, name) && !strcmp(q->domain, domain) && !strncmp(q->path, path, strlen(q->path))) - { if (q->value) - SOAP_FREE(soap, q->value); - if (q->domain) - SOAP_FREE(soap, q->domain); - if (q->path) - SOAP_FREE(soap, q->path); - *p = q->next; - SOAP_FREE(soap, q); - } - else - p = &q->next; - } -} - -/******************************************************************************/ -SOAP_FMAC1 -char * -SOAP_FMAC2 -soap_cookie_value(struct soap *soap, const char *name, const char *domain, const char *path) -{ struct soap_cookie *p; - if ((p = soap_cookie(soap, name, domain, path))) - return p->value; - return NULL; -} - -/******************************************************************************/ -SOAP_FMAC1 -char * -SOAP_FMAC2 -soap_env_cookie_value(struct soap *soap, const char *name, const char *domain, const char *path) -{ struct soap_cookie *p; - if ((p = soap_cookie(soap, name, domain, path)) && p->env) - return p->value; - return NULL; -} - -/******************************************************************************/ -SOAP_FMAC1 -time_t -SOAP_FMAC2 -soap_cookie_expire(struct soap *soap, const char *name, const char *domain, const char *path) -{ struct soap_cookie *p; - if ((p = soap_cookie(soap, name, domain, path))) - return p->expire; - return -1; -} - -/******************************************************************************/ -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_set_cookie_expire(struct soap *soap, const char *name, long expire, const char *domain, const char *path) -{ struct soap_cookie *p; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Set cookie expiration max-age %ld: %s domain=%s path=%s\n", expire, name, domain?domain:"(null)", path?path:"(null)")); - if ((p = soap_cookie(soap, name, domain, path))) - { p->maxage = expire; - p->modified = 1; - return SOAP_OK; - } - return SOAP_ERR; -} - -/******************************************************************************/ -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_set_cookie_session(struct soap *soap, const char *name, const char *domain, const char *path) -{ struct soap_cookie *p; - if ((p = soap_cookie(soap, name, domain, path))) - { p->session = 1; - p->modified = 1; - return SOAP_OK; - } - return SOAP_ERR; -} - -/******************************************************************************/ -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_clr_cookie_session(struct soap *soap, const char *name, const char *domain, const char *path) -{ struct soap_cookie *p; - if ((p = soap_cookie(soap, name, domain, path))) - { p->session = 0; - p->modified = 1; - return SOAP_OK; - } - return SOAP_ERR; -} - -/******************************************************************************/ -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_putsetcookies(struct soap *soap) -{ struct soap_cookie *p; - char *s, tmp[4096]; - const char *t; - for (p = soap->cookies; p; p = p->next) - { - if (p->modified -#ifdef WITH_OPENSSL - || (!p->env && !soap->ssl == !p->secure) -#endif - ) - { s = tmp; - if (p->name) - s += soap_encode_cookie(p->name, s, tmp-s+4064); - if (p->value && *p->value) - { *s++ = '='; - s += soap_encode_cookie(p->value, s, tmp-s+4064); - } - if (p->domain && (int)strlen(p->domain) < tmp-s+4064) - { strcpy(s, ";Domain="); - strcat(s, p->domain); - } - else if (soap->cookie_domain && (int)strlen(soap->cookie_domain) < tmp-s+4064) - { strcpy(s, ";Domain="); - strcat(s, soap->cookie_domain); - } - strcat(s, ";Path=/"); - s += strlen(s); - if (p->path) - t = p->path; - else - t = soap->cookie_path; - if (t) - { if (*t == '/') - t++; - if ((int)strlen(t) < tmp-s+4064) - { if (strchr(t, '%')) /* already URL encoded? */ - { strcpy(s, t); - s += strlen(s); - } - else - s += soap_encode_cookie(t, s, tmp-s+4064); - } - } - if (p->version > 0 && s-tmp < 4060) - { sprintf(s, ";Version=%u", p->version); - s += strlen(s); - } - if (p->maxage >= 0 && s-tmp < 4060) - { sprintf(s, ";Max-Age=%ld", p->maxage); - s += strlen(s); - } - if (s-tmp < 4073 - && (p->secure -#ifdef WITH_OPENSSL - || soap->ssl -#endif - )) - strcpy(s, ";Secure"); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Set-Cookie: %s\n", tmp)); - if ((soap->error = soap->fposthdr(soap, "Set-Cookie", tmp))) - return soap->error; - } - } - return SOAP_OK; -} - -/******************************************************************************/ -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_putcookies(struct soap *soap, const char *domain, const char *path, int secure) -{ struct soap_cookie **p, *q; - unsigned int version = 0; - time_t now = time(NULL); - char *s, tmp[4096]; - p = &soap->cookies; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Sending cookies for domain=%s path=%s\n", domain, path)); - if (*path == '/') - path++; - while ((q = *p)) - { if (q->expire && now > q->expire) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Cookie %s expired\n", q->name)); - SOAP_FREE(soap, q->name); - if (q->value) - SOAP_FREE(soap, q->value); - if (q->domain) - SOAP_FREE(soap, q->domain); - if (q->path) - SOAP_FREE(soap, q->path); - *p = q->next; - SOAP_FREE(soap, q); - } - else - { int flag; - char *t = q->domain; - size_t n = 0; - if (!t) - flag = 1; - else - { const char *r = strchr(t, ':'); - if (r) - n = r - t; - else - n = strlen(t); - flag = !strncmp(t, domain, n); - } - /* domain-level cookies, cannot compile when WITH_NOIO set */ -#ifndef WITH_NOIO - if (!flag) - { struct hostent *hostent = gethostbyname((char*)domain); - if (hostent) - { const char *r = strchr(hostent->h_name, '.'); - if (!r) - r = hostent->h_name; - flag = !strncmp(t, r, n); - } - } -#endif - if (flag - && (!q->path || !strncmp(q->path, path, strlen(q->path))) - && (!q->secure || secure)) - { s = tmp; - if (q->version != version) - { sprintf(s, "$Version=%u;", q->version); - version = q->version; - } - if (q->name) - s += soap_encode_cookie(q->name, s, tmp-s+4080); - if (q->value && *q->value) - { *s++ = '='; - s += soap_encode_cookie(q->value, s, tmp-s+4080); - } - if (q->path && *q->path && (int)strlen(q->path) < tmp-s+4080) - { sprintf(s, ";$Path=\"/%s\"", (*q->path == '/' ? q->path + 1 : q->path)); - s += strlen(s); - } - if (q->domain && (int)strlen(q->domain) < tmp-s+4080) - sprintf(s, ";$Domain=\"%s\"", q->domain); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Cookie: %s\n", tmp)); - if ((soap->error = soap->fposthdr(soap, "Cookie", tmp))) - return soap->error; - } - p = &q->next; - } - } - return SOAP_OK; -} - -/******************************************************************************/ -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_getcookies(struct soap *soap, const char *val) -{ struct soap_cookie *p = NULL, *q; - const char *s; - char *t, tmp[4096]; /* cookie size is up to 4096 bytes [RFC2109] */ - char *domain = NULL; - char *path = NULL; - unsigned int version = 0; - time_t now = time(NULL); - if (!val) - return; - s = val; - while (*s) - { s = soap_decode_key(tmp, sizeof(tmp), s); - if (!soap_tag_cmp(tmp, "$Version")) - { if ((s = soap_decode_val(tmp, sizeof(tmp), s))) - { if (p) - p->version = (int)atol(tmp); - else - version = (int)atol(tmp); - } - } - else if (!soap_tag_cmp(tmp, "$Path")) - { s = soap_decode_val(tmp, sizeof(tmp), s); - if (*tmp) - { if ((t = (char*)SOAP_MALLOC(soap, strlen(tmp)+1))) - strcpy(t, tmp); - } - else - t = NULL; - if (p) - { if (p->path) - SOAP_FREE(soap, p->path); - p->path = t; - } - else - { if (path) - SOAP_FREE(soap, path); - path = t; - } - } - else if (!soap_tag_cmp(tmp, "$Domain")) - { s = soap_decode_val(tmp, sizeof(tmp), s); - if (*tmp) - { if ((t = (char*)SOAP_MALLOC(soap, strlen(tmp)+1))) - strcpy(t, tmp); - } - else - t = NULL; - if (p) - { if (p->domain) - SOAP_FREE(soap, p->domain); - p->domain = t; - } - else - { if (domain) - SOAP_FREE(soap, domain); - domain = t; - } - } - else if (p && !soap_tag_cmp(tmp, "Path")) - { if (p->path) - SOAP_FREE(soap, p->path); - s = soap_decode_val(tmp, sizeof(tmp), s); - if (*tmp) - { if ((p->path = (char*)SOAP_MALLOC(soap, strlen(tmp)+1))) - strcpy(p->path, tmp); - } - else - p->path = NULL; - } - else if (p && !soap_tag_cmp(tmp, "Domain")) - { if (p->domain) - SOAP_FREE(soap, p->domain); - s = soap_decode_val(tmp, sizeof(tmp), s); - if (*tmp) - { if ((p->domain = (char*)SOAP_MALLOC(soap, strlen(tmp)+1))) - strcpy(p->domain, tmp); - } - else - p->domain = NULL; - } - else if (p && !soap_tag_cmp(tmp, "Version")) - { s = soap_decode_val(tmp, sizeof(tmp), s); - p->version = (unsigned int)atol(tmp); - } - else if (p && !soap_tag_cmp(tmp, "Max-Age")) - { s = soap_decode_val(tmp, sizeof(tmp), s); - p->expire = now + atol(tmp); - } - else if (p && !soap_tag_cmp(tmp, "Expires")) - { struct tm T; - char a[3]; - static const char mns[] = "anebarprayunulugepctovec"; - s = soap_decode_val(tmp, sizeof(tmp), s); - if (strlen(tmp) > 20) - { memset((void*)&T, 0, sizeof(T)); - a[0] = tmp[4]; - a[1] = tmp[5]; - a[2] = '\0'; - T.tm_mday = (int)atol(a); - a[0] = tmp[8]; - a[1] = tmp[9]; - T.tm_mon = (int)(strstr(mns, a) - mns) / 2; - a[0] = tmp[11]; - a[1] = tmp[12]; - T.tm_year = 100 + (int)atol(a); - a[0] = tmp[13]; - a[1] = tmp[14]; - T.tm_hour = (int)atol(a); - a[0] = tmp[16]; - a[1] = tmp[17]; - T.tm_min = (int)atol(a); - a[0] = tmp[19]; - a[1] = tmp[20]; - T.tm_sec = (int)atol(a); - p->expire = soap_timegm(&T); - } - } - else if (p && !soap_tag_cmp(tmp, "Secure")) - p->secure = 1; - else - { if (p) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Got environment cookie %s=%s domain=%s path=%s expire=%ld secure=%d\n", p->name, p->value?p->value:"(null)", p->domain?p->domain:"(null)", p->path?p->path:"(null)", p->expire, p->secure)); - if ((q = soap_set_cookie(soap, p->name, p->value, p->domain, p->path))) - { q->version = p->version; - q->expire = p->expire; - q->secure = p->secure; - q->env = 1; - } - if (p->name) - SOAP_FREE(soap, p->name); - if (p->value) - SOAP_FREE(soap, p->value); - if (p->domain) - SOAP_FREE(soap, p->domain); - if (p->path) - SOAP_FREE(soap, p->path); - SOAP_FREE(soap, p); - } - if ((p = (struct soap_cookie*)SOAP_MALLOC(soap, sizeof(struct soap_cookie)))) - { p->name = (char*)SOAP_MALLOC(soap, strlen(tmp)+1); - strcpy(p->name, tmp); - s = soap_decode_val(tmp, sizeof(tmp), s); - if (*tmp) - { p->value = (char*)SOAP_MALLOC(soap, strlen(tmp)+1); - strcpy(p->value, tmp); - } - else - p->value = NULL; - if (domain) - p->domain = domain; - else if (*soap->host) - { p->domain = (char*)SOAP_MALLOC(soap, strlen(soap->host)+1); - strcpy(p->domain, soap->host); - } - else - p->domain = NULL; - if (path) - p->path = path; - else if (soap->path && *soap->path) - { p->path = (char*)SOAP_MALLOC(soap, strlen(soap->path)+1); - strcpy(p->path, soap->path); - } - else - { p->path = (char*)SOAP_MALLOC(soap, 2); - strcpy(p->path, "/"); - } - p->expire = 0; - p->secure = 0; - p->version = version; - } - } - } - if (p) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Got environment cookie %s=%s domain=%s path=%s expire=%ld secure=%d\n", p->name, p->value?p->value:"(null)", p->domain?p->domain:"(null)", p->path?p->path:"(null)", p->expire, p->secure)); - if ((q = soap_set_cookie(soap, p->name, p->value, p->domain, p->path))) - { q->version = p->version; - q->expire = p->expire; - q->secure = p->secure; - q->env = 1; - } - if (p->name) - SOAP_FREE(soap, p->name); - if (p->value) - SOAP_FREE(soap, p->value); - if (p->domain) - SOAP_FREE(soap, p->domain); - if (p->path) - SOAP_FREE(soap, p->path); - SOAP_FREE(soap, p); - } - if (domain) - SOAP_FREE(soap, domain); - if (path) - SOAP_FREE(soap, path); -} - -/******************************************************************************/ -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_getenv_cookies(struct soap *soap) -{ struct soap_cookie *p; - const char *s; - char key[4096], val[4096]; /* cookie size is up to 4096 bytes [RFC2109] */ - if (!(s = getenv("HTTP_COOKIE"))) - return SOAP_ERR; - do - { s = soap_decode_key(key, sizeof(key), s); - s = soap_decode_val(val, sizeof(val), s); - p = soap_set_cookie(soap, key, val, NULL, NULL); - if (p) - p->env = 1; - } while (*s); - return SOAP_OK; -} - -/******************************************************************************/ -SOAP_FMAC1 -struct soap_cookie* -SOAP_FMAC2 -soap_copy_cookies(struct soap *copy, const struct soap *soap) -{ struct soap_cookie *p, **q, *r; - q = &r; - for (p = soap->cookies; p; p = p->next) - { if (!(*q = (struct soap_cookie*)SOAP_MALLOC(copy, sizeof(struct soap_cookie)))) - return r; - **q = *p; - if (p->name) - { if (((*q)->name = (char*)SOAP_MALLOC(copy, strlen(p->name)+1))) - strcpy((*q)->name, p->name); - } - if (p->value) - { if (((*q)->value = (char*)SOAP_MALLOC(copy, strlen(p->value)+1))) - strcpy((*q)->value, p->value); - } - if (p->domain) - { if (((*q)->domain = (char*)SOAP_MALLOC(copy, strlen(p->domain)+1))) - strcpy((*q)->domain, p->domain); - } - if (p->path) - { if (((*q)->path = (char*)SOAP_MALLOC(copy, strlen(p->path)+1))) - strcpy((*q)->path, p->path); - } - q = &(*q)->next; - } - *q = NULL; - return r; -} - -/******************************************************************************/ -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_free_cookies(struct soap *soap) -{ struct soap_cookie *p; - for (p = soap->cookies; p; p = soap->cookies) - { soap->cookies = p->next; - SOAP_FREE(soap, p->name); - if (p->value) - SOAP_FREE(soap, p->value); - if (p->domain) - SOAP_FREE(soap, p->domain); - if (p->path) - SOAP_FREE(soap, p->path); - SOAP_FREE(soap, p); - } -} - -/******************************************************************************/ -#endif /* WITH_COOKIES */ - -/******************************************************************************/ -#ifdef WITH_GZIP -#ifndef PALM_1 -static int -soap_getgziphdr(struct soap *soap) -{ int i; - soap_wchar c = 0, f = 0; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Get gzip header\n")); - for (i = 0; i < 9; i++) - { if ((int)(c = soap_get1(soap) == EOF)) - return soap->error = SOAP_EOF; - if (i == 1 && c == 8) - soap->z_dict = 0; - if (i == 2) - f = c; - } - if (f & 0x04) /* FEXTRA */ - { for (i = soap_get1(soap) | (soap_get1(soap) << 8); i; i--) - { if ((int)soap_get1(soap) == EOF) - return soap->error = SOAP_EOF; - } - } - if (f & 0x08) /* FNAME */ - { do - c = soap_get1(soap); - while (c && (int)c != EOF); - } - if ((int)c != EOF && (f & 0x10)) /* FCOMMENT */ - { do - c = soap_get1(soap); - while (c && (int)c != EOF); - } - if ((int)c != EOF && (f & 0x01)) /* FHCRC */ - { if ((int)(c = soap_get1(soap)) != EOF) - c = soap_get1(soap); - } - if ((int)c == EOF) - return soap->error = SOAP_EOF; - return SOAP_OK; -} -#endif -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_begin_recv(struct soap *soap) -{ soap_wchar c; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Initializing for input\n")); - soap->error = SOAP_OK; - soap_free_temp(soap); - soap_set_local_namespaces(soap); - soap->version = 0; /* don't assume we're parsing SOAP content by default */ -#ifndef WITH_NOIDREF - soap_free_iht(soap); -#endif - if ((soap->imode & SOAP_IO) == SOAP_IO_CHUNK) - soap->omode |= SOAP_IO_CHUNK; - soap->imode &= ~(SOAP_IO | SOAP_ENC_MIME); - soap->mode = soap->imode; - if (!soap->keep_alive) - { soap->buflen = 0; - soap->bufidx = 0; - } - if (!(soap->mode & SOAP_IO_KEEPALIVE)) - soap->keep_alive = 0; - soap->ahead = 0; - soap->peeked = 0; - soap->level = 0; - soap->part = SOAP_BEGIN; - soap->alloced = 0; - soap->count = 0; - soap->length = 0; - soap->cdata = 0; - *soap->endpoint = '\0'; - soap->action = NULL; - soap->header = NULL; - soap->fault = NULL; - soap->status = 0; -#ifndef WITH_LEANER - soap->dom = NULL; - soap->dime.chunksize = 0; - soap->dime.buflen = 0; - soap->dime.list = NULL; - soap->dime.first = NULL; - soap->dime.last = NULL; - soap->mime.list = NULL; - soap->mime.first = NULL; - soap->mime.last = NULL; - soap->mime.boundary = NULL; - soap->mime.start = NULL; -#endif -#ifdef WIN32 -#ifndef UNDER_CE -#ifndef WITH_FASTCGI - if (!soap_valid_socket(soap->socket)) -#ifdef __BORLANDC__ - setmode(soap->recvfd, _O_BINARY); -#else - _setmode(soap->recvfd, _O_BINARY); -#endif -#endif -#endif -#endif -#ifdef WITH_ZLIB - soap->mode &= ~SOAP_ENC_ZLIB; - soap->zlib_in = SOAP_ZLIB_NONE; - soap->zlib_out = SOAP_ZLIB_NONE; - soap->d_stream->next_in = Z_NULL; - soap->d_stream->avail_in = 0; - soap->d_stream->next_out = (Byte*)soap->buf; - soap->d_stream->avail_out = SOAP_BUFLEN; - soap->z_ratio_in = 1.0; -#endif -#ifdef WITH_OPENSSL - if (soap->ssl) - ERR_clear_error(); -#endif -#ifndef WITH_LEANER - if (soap->fprepareinit) - soap->fprepareinit(soap); -#endif - c = soap_getchar(soap); -#ifdef WITH_GZIP - if (c == 0x1F) - { if (soap_getgziphdr(soap)) - return soap->error; - if (inflateInit2(soap->d_stream, -MAX_WBITS) != Z_OK) - return soap->error = SOAP_ZLIB_ERROR; - if (soap->z_dict) - { if (inflateSetDictionary(soap->d_stream, (const Bytef*)soap->z_dict, soap->z_dict_len) != Z_OK) - return soap->error = SOAP_ZLIB_ERROR; - } - soap->zlib_state = SOAP_ZLIB_INFLATE; - soap->mode |= SOAP_ENC_ZLIB; - soap->zlib_in = SOAP_ZLIB_GZIP; - soap->z_crc = crc32(0L, NULL, 0); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "gzip initialized\n")); - if (!soap->z_buf) - soap->z_buf = (char*)SOAP_MALLOC(soap, SOAP_BUFLEN); - memcpy(soap->z_buf, soap->buf, SOAP_BUFLEN); - /* should not chunk over plain transport, so why bother to check? */ - /* if ((soap->mode & SOAP_IO) == SOAP_IO_CHUNK) */ - /* soap->z_buflen = soap->bufidx; */ - /* else */ - soap->d_stream->next_in = (Byte*)(soap->z_buf + soap->bufidx); - soap->d_stream->avail_in = soap->buflen - soap->bufidx; - soap->z_buflen = soap->buflen; - soap->buflen = soap->bufidx; - c = soap_getchar(soap); - } -#endif -#ifndef WITH_LEANER - if (c == '-' && soap_get0(soap) == '-') - soap->mode |= SOAP_ENC_MIME; - else if ((c & 0xFFFC) == (SOAP_DIME_VERSION | SOAP_DIME_MB) && (soap_get0(soap) & 0xFFF0) == 0x20) - soap->mode |= SOAP_ENC_DIME; - else -#endif - { /* skip BOM */ - if (c == 0xEF && (c = soap_getchar(soap)) == 0xBB && (c = soap_getchar(soap)) == 0xBF) - c = soap_getchar(soap); - /* skip space */ - while (soap_blank(c)) - c = soap_getchar(soap); - } - if ((int)c == EOF) - return soap->error = SOAP_EOF; - soap_unget(soap, c); -#ifndef WITH_NOHTTP - /* if not XML or MIME/DIME/ZLIB, assume HTTP header */ - if (c != '<' && !(soap->mode & (SOAP_ENC_MIME | SOAP_ENC_DIME | SOAP_ENC_ZLIB))) - { soap_mode m = soap->imode; - soap->mode &= ~SOAP_IO; - soap->error = soap->fparse(soap); - if (soap->error && soap->error < SOAP_STOP) - { soap->keep_alive = 0; /* force close later */ - return soap->error; - } - if (soap->error == SOAP_STOP) - return soap->error; - soap->mode = soap->imode; /* if imode is changed, effectuate */ - soap->imode = m; /* restore imode */ -#ifdef WITH_ZLIB - soap->mode &= ~SOAP_ENC_ZLIB; -#endif - if ((soap->mode & SOAP_IO) == SOAP_IO_CHUNK) - { soap->chunkbuflen = soap->buflen; - soap->buflen = soap->bufidx; - soap->chunksize = 0; - } -#ifndef WITH_LEANER - else if (soap->fpreparerecv && soap->buflen != soap->bufidx) - soap->fpreparerecv(soap, soap->buf + soap->bufidx, soap->buflen - soap->bufidx); -#endif - /* Note: fparse should not use soap_unget to push back last char */ - if (soap_get0(soap) == (int)EOF) - { if (soap->status == 200) - return soap->error = SOAP_NO_DATA; /* HTTP OK: always expect data */ - return soap->error = soap->status; - } -#ifdef WITH_ZLIB - if (soap->zlib_in != SOAP_ZLIB_NONE) - { -#ifdef WITH_GZIP - if (soap->zlib_in != SOAP_ZLIB_DEFLATE) - { c = soap_get1(soap); - if (c == 0x1F) - { if (soap_getgziphdr(soap)) - return soap->error; - if (inflateInit2(soap->d_stream, -MAX_WBITS) != Z_OK) - return soap->error = SOAP_ZLIB_ERROR; - soap->z_crc = crc32(0L, NULL, 0); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "gzip initialized\n")); - } - else - { soap_revget1(soap); - if (inflateInit(soap->d_stream) != Z_OK) - return soap->error = SOAP_ZLIB_ERROR; - soap->zlib_in = SOAP_ZLIB_DEFLATE; - } - } - else -#endif - if (inflateInit(soap->d_stream) != Z_OK) - return soap->error = SOAP_ZLIB_ERROR; - if (soap->z_dict) - { if (inflateSetDictionary(soap->d_stream, (const Bytef*)soap->z_dict, soap->z_dict_len) != Z_OK) - return soap->error = SOAP_ZLIB_ERROR; - } - soap->zlib_state = SOAP_ZLIB_INFLATE; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Inflate initialized\n")); - soap->mode |= SOAP_ENC_ZLIB; - if (!soap->z_buf) - soap->z_buf = (char*)SOAP_MALLOC(soap, SOAP_BUFLEN); - memcpy(soap->z_buf, soap->buf, SOAP_BUFLEN); - soap->d_stream->next_in = (Byte*)(soap->z_buf + soap->bufidx); - soap->d_stream->avail_in = soap->buflen - soap->bufidx; - soap->z_buflen = soap->buflen; - soap->buflen = soap->bufidx; - } -#endif - if (soap->error) - { if (soap->error == SOAP_FORM && soap->fform) - { soap->error = soap->fform(soap); - if (soap->error == SOAP_OK) - soap->error = SOAP_STOP; /* prevents further processing */ - } - return soap->error; - } - } -#endif -#ifndef WITH_LEANER - if (soap->mode & SOAP_ENC_MIME) - { if (soap_getmimehdr(soap)) - return soap->error; - if (soap->mime.start) - { do - { if (!soap->mime.last->id) - break; - if (!soap_match_cid(soap, soap->mime.start, soap->mime.last->id)) - break; - } while (soap_get_mime_attachment(soap, NULL)); - } - if (soap_get_header_attribute(soap, soap->mime.first->type, "application/dime")) - soap->mode |= SOAP_ENC_DIME; - } - if (soap->mode & SOAP_ENC_DIME) - { if (soap_getdimehdr(soap)) - return soap->error; - if (soap->dime.flags & SOAP_DIME_CF) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Chunked DIME SOAP message\n")); - soap->dime.chunksize = soap->dime.size; - if (soap->buflen - soap->bufidx >= soap->dime.chunksize) - { soap->dime.buflen = soap->buflen; - soap->buflen = soap->bufidx + soap->dime.chunksize; - } - else - soap->dime.chunksize -= soap->buflen - soap->bufidx; - } - soap->count = soap->buflen - soap->bufidx; - } -#endif - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef WITH_NOHTTP -#ifndef PALM_1 -static int -http_parse(struct soap *soap) -{ char header[SOAP_HDRLEN], *s; - unsigned short httpcmd = 0, status = 0; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Waiting for HTTP request/response...\n")); - *soap->endpoint = '\0'; - soap->length = 0; - soap->userid = NULL; - soap->passwd = NULL; - soap->action = NULL; - soap->authrealm = NULL; - soap->proxy_from = NULL; - soap->http_content = NULL; - soap->status = 0; - do - { if (soap_getline(soap, soap->msgbuf, sizeof(soap->msgbuf))) - { if (soap->error == SOAP_EOF) - return SOAP_EOF; - return soap->error = 414; - } - if ((s = strchr(soap->msgbuf, ' '))) - { soap->status = (unsigned short)soap_strtoul(s, &s, 10); - if (!soap_blank(*s)) - soap->status = 0; - } - else - soap->status = 0; - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "HTTP status: %s\n", soap->msgbuf)); - for (;;) - { if (soap_getline(soap, header, SOAP_HDRLEN)) - { if (soap->error == SOAP_EOF) - { soap->error = SOAP_OK; - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "EOF in HTTP header, continue anyway\n")); - break; - } - return soap->error; - } - if (!*header) - break; - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "HTTP header: %s\n", header)); - s = strchr(header, ':'); - if (s) - { char *t; - *s = '\0'; - do s++; - while (*s && *s <= 32); - if (*s == '"') - s++; - t = s + strlen(s) - 1; - while (t > s && *t <= 32) - t--; - if (t >= s && *t == '"') - t--; - t[1] = '\0'; - if ((soap->error = soap->fparsehdr(soap, header, s))) - { if (soap->error < SOAP_STOP) - return soap->error; - status = soap->error; - soap->error = SOAP_OK; - } - } - } - } while (soap->status == 100); - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Finished HTTP header parsing, status = %d\n", soap->status)); - s = strstr(soap->msgbuf, "HTTP/"); - if (s && s[7] != '1') - { if (soap->keep_alive == 1) - soap->keep_alive = 0; - if (soap->status == 0 && (soap->omode & SOAP_IO) == SOAP_IO_CHUNK) /* soap->status == 0 for HTTP request */ - { soap->imode |= SOAP_IO_CHUNK; - soap->omode = (soap->omode & ~SOAP_IO) | SOAP_IO_STORE; - } - } - if (soap->keep_alive < 0) - soap->keep_alive = 1; - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Keep alive connection = %d\n", soap->keep_alive)); - if (soap->status == 0) - { size_t l = 0; - if (s) - { if (!strncmp(soap->msgbuf, "POST ", l = 5)) - httpcmd = 1; - else if (!strncmp(soap->msgbuf, "GET ", l = 4)) - httpcmd = 2; - else if (!strncmp(soap->msgbuf, "PUT ", l = 4)) - httpcmd = 3; - else if (!strncmp(soap->msgbuf, "DELETE ", l = 7)) - httpcmd = 4; - else if (!strncmp(soap->msgbuf, "HEAD ", l = 5)) - httpcmd = 5; - } - if (s && httpcmd) - { size_t m = strlen(soap->endpoint); - size_t n = m + (s - soap->msgbuf) - l - 1; - if (m > n) - m = n; - if (n >= sizeof(soap->endpoint)) - n = sizeof(soap->endpoint) - 1; - strncpy(soap->path, soap->msgbuf + l, n - m); - soap->path[n - m] = '\0'; - strcat(soap->endpoint, soap->path); - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Target endpoint='%s'\n", soap->endpoint)); - if (httpcmd > 1) - { switch (httpcmd) - { case 2: soap->error = soap->fget(soap); break; - case 3: soap->error = soap->fput(soap); break; - case 4: soap->error = soap->fdel(soap); break; - case 5: soap->error = soap->fhead(soap); break; - default: soap->error = 405; break; - } - if (soap->error == SOAP_OK) - soap->error = SOAP_STOP; /* prevents further processing */ - return soap->error; - } - if (status) - return soap->error = status; - } - else if (status) - return soap->error = status; - else if (s) - return soap->error = 405; - } - /* Status OK (HTTP 200) */ - if (soap->status == 0 || soap->status == 200) - return SOAP_OK; - /* Status 201 (Created), 202 (Accepted), ... and HTTP 400 and 500 errors - may not have a body. When content length, content type, or chunking is - used assume there is a message to parse, either XML or HTTP. - */ - if (soap->length > 0 || soap->http_content || (soap->imode & SOAP_IO) == SOAP_IO_CHUNK) - { if (((soap->status > 200 && soap->status <= 299) || soap->status == 400 || soap->status == 500)) - return SOAP_OK; - /* force close afterwards in soap_closesock() */ - soap->keep_alive = 0; - /* read HTTP body for error details */ - s = soap_get_http_body(soap); - if (s) - return soap_set_receiver_error(soap, soap->msgbuf, s, soap->status); - } - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "HTTP error %d\n", soap->status)); - return soap_set_receiver_error(soap, "HTTP Error", soap->msgbuf, soap->status); -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOHTTP -#ifndef PALM_1 -static int -http_parse_header(struct soap *soap, const char *key, const char *val) -{ if (!soap_tag_cmp(key, "Host")) - { -#ifdef WITH_OPENSSL - if (soap->imode & SOAP_ENC_SSL) - strcpy(soap->endpoint, "https://"); - else -#endif - strcpy(soap->endpoint, "http://"); - strncat(soap->endpoint, val, sizeof(soap->endpoint) - 8); - soap->endpoint[sizeof(soap->endpoint) - 1] = '\0'; - } -#ifndef WITH_LEANER - else if (!soap_tag_cmp(key, "Content-Type")) - { const char *action; - soap->http_content = soap_strdup(soap, val); - if (soap_get_header_attribute(soap, val, "application/dime")) - soap->imode |= SOAP_ENC_DIME; - else if (soap_get_header_attribute(soap, val, "multipart/related") - || soap_get_header_attribute(soap, val, "multipart/form-data")) - { soap->mime.boundary = soap_strdup(soap, soap_get_header_attribute(soap, val, "boundary")); - soap->mime.start = soap_strdup(soap, soap_get_header_attribute(soap, val, "start")); - soap->imode |= SOAP_ENC_MIME; - } - action = soap_get_header_attribute(soap, val, "action"); - if (action) - { if (*action == '"') - { soap->action = soap_strdup(soap, action + 1); - soap->action[strlen(soap->action) - 1] = '\0'; - } - else - soap->action = soap_strdup(soap, action); - } - } -#endif - else if (!soap_tag_cmp(key, "Content-Length")) - { soap->length = soap_strtoul(val, NULL, 10); - } - else if (!soap_tag_cmp(key, "Content-Encoding")) - { if (!soap_tag_cmp(val, "deflate")) -#ifdef WITH_ZLIB - soap->zlib_in = SOAP_ZLIB_DEFLATE; -#else - return SOAP_ZLIB_ERROR; -#endif - else if (!soap_tag_cmp(val, "gzip")) -#ifdef WITH_GZIP - soap->zlib_in = SOAP_ZLIB_GZIP; -#else - return SOAP_ZLIB_ERROR; -#endif - } -#ifdef WITH_ZLIB - else if (!soap_tag_cmp(key, "Accept-Encoding")) - { -#ifdef WITH_GZIP - if (strchr(val, '*') || soap_get_header_attribute(soap, val, "gzip")) - soap->zlib_out = SOAP_ZLIB_GZIP; - else -#endif - if (strchr(val, '*') || soap_get_header_attribute(soap, val, "deflate")) - soap->zlib_out = SOAP_ZLIB_DEFLATE; - else - soap->zlib_out = SOAP_ZLIB_NONE; - } -#endif - else if (!soap_tag_cmp(key, "Transfer-Encoding")) - { soap->imode &= ~SOAP_IO; - if (!soap_tag_cmp(val, "chunked")) - soap->imode |= SOAP_IO_CHUNK; - } - else if (!soap_tag_cmp(key, "Connection")) - { if (!soap_tag_cmp(val, "keep-alive")) - soap->keep_alive = -soap->keep_alive; - else if (!soap_tag_cmp(val, "close")) - soap->keep_alive = 0; - } -#ifndef WITH_LEAN - else if (!soap_tag_cmp(key, "Authorization")) - { if (!soap_tag_cmp(val, "Basic *")) - { int n; - char *s; - soap_base642s(soap, val + 6, soap->tmpbuf, sizeof(soap->tmpbuf) - 1, &n); - soap->tmpbuf[n] = '\0'; - if ((s = strchr(soap->tmpbuf, ':'))) - { *s = '\0'; - soap->userid = soap_strdup(soap, soap->tmpbuf); - soap->passwd = soap_strdup(soap, s + 1); - } - } - } - else if (!soap_tag_cmp(key, "WWW-Authenticate")) - { soap->authrealm = soap_strdup(soap, soap_get_header_attribute(soap, val + 6, "realm")); - } - else if (!soap_tag_cmp(key, "Expect")) - { if (!soap_tag_cmp(val, "100-continue")) - { if ((soap->error = soap->fposthdr(soap, "HTTP/1.1 100 Continue", NULL)) - || (soap->error = soap->fposthdr(soap, NULL, NULL))) - return soap->error; - } - } -#endif - else if (!soap_tag_cmp(key, "SOAPAction")) - { if (*val == '"') - { soap->action = soap_strdup(soap, val + 1); - soap->action[strlen(soap->action) - 1] = '\0'; - } - else - soap->action = soap_strdup(soap, val); - } - else if (!soap_tag_cmp(key, "Location")) - { strncpy(soap->endpoint, val, sizeof(soap->endpoint)); - soap->endpoint[sizeof(soap->endpoint) - 1] = '\0'; - } - else if (!soap_tag_cmp(key, "X-Forwarded-For")) - { soap->proxy_from = soap_strdup(soap, val); - } -#ifdef WITH_COOKIES - else if (!soap_tag_cmp(key, "Cookie") - || !soap_tag_cmp(key, "Cookie2") - || !soap_tag_cmp(key, "Set-Cookie") - || !soap_tag_cmp(key, "Set-Cookie2")) - { soap_getcookies(soap, val); - } -#endif - return SOAP_OK; -} -#endif -#endif - -/******************************************************************************/ -#if !defined(WITH_NOHTTP) || !defined(WITH_LEANER) -#ifndef PALM_1 -SOAP_FMAC1 -const char* -SOAP_FMAC2 -soap_get_header_attribute(struct soap *soap, const char *line, const char *key) -{ register const char *s = line; - if (s) - { while (*s) - { register short flag; - s = soap_decode_key(soap->tmpbuf, sizeof(soap->tmpbuf), s); - flag = soap_tag_cmp(soap->tmpbuf, key); - s = soap_decode_val(soap->tmpbuf, sizeof(soap->tmpbuf), s); - if (!flag) - return soap->tmpbuf; - } - } - return NULL; -} -#endif -#endif - -/******************************************************************************/ -#if !defined(WITH_NOHTTP) || !defined(WITH_LEANER) -#ifndef PALM_1 -SOAP_FMAC1 -const char* -SOAP_FMAC2 -soap_decode_key(char *buf, size_t len, const char *val) -{ return soap_decode(buf, len, val, "=,;"); -} -#endif -#endif - -/******************************************************************************/ -#if !defined(WITH_NOHTTP) || !defined(WITH_LEANER) -#ifndef PALM_1 -SOAP_FMAC1 -const char* -SOAP_FMAC2 -soap_decode_val(char *buf, size_t len, const char *val) -{ if (*val != '=') - { *buf = '\0'; - return val; - } - return soap_decode(buf, len, val + 1, ",;"); -} -#endif -#endif - -/******************************************************************************/ -#if !defined(WITH_NOHTTP) || !defined(WITH_LEANER) -#ifndef PALM_1 -static const char* -soap_decode(char *buf, size_t len, const char *val, const char *sep) -{ const char *s; - char *t = buf; - for (s = val; *s; s++) - if (*s != ' ' && *s != '\t' && !strchr(sep, *s)) - break; - if (*s == '"') - { s++; - while (*s && *s != '"' && --len) - *t++ = *s++; - } - else - { while (*s && !soap_blank(*s) && !strchr(sep, *s) && --len) - { if (*s == '%') - { *t++ = ((s[1] >= 'A' ? (s[1] & 0x7) + 9 : s[1] - '0') << 4) - + (s[2] >= 'A' ? (s[2] & 0x7) + 9 : s[2] - '0'); - s += 3; - } - else - *t++ = *s++; - } - } - *t = '\0'; - while (*s && !strchr(sep, *s)) - s++; - return s; -} -#endif -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_envelope_begin_out(struct soap *soap) -{ -#ifndef WITH_LEANER - size_t n = 0; - if ((soap->mode & SOAP_ENC_MIME) && soap->mime.boundary && soap->mime.start && strlen(soap->mime.boundary) + strlen(soap->mime.start) < sizeof(soap->tmpbuf) - 80 ) - { const char *s; - if ((soap->mode & SOAP_ENC_DIME) && !(soap->mode & SOAP_ENC_MTOM)) - s = "application/dime"; - else if (soap->version == 2) - { if (soap->mode & SOAP_ENC_MTOM) - s = "application/xop+xml; charset=utf-8; type=\"application/soap+xml\""; - else - s = "application/soap+xml; charset=utf-8"; - } - else if (soap->mode & SOAP_ENC_MTOM) - s = "application/xop+xml; charset=utf-8; type=\"text/xml\""; - else - s = "text/xml; charset=utf-8"; - sprintf(soap->tmpbuf, "--%s\r\nContent-Type: %s\r\nContent-Transfer-Encoding: binary\r\nContent-ID: %s\r\n\r\n", soap->mime.boundary, s, soap->mime.start); - n = strlen(soap->tmpbuf); - if (soap_send_raw(soap, soap->tmpbuf, n)) - return soap->error; - } - if (soap->mode & SOAP_IO_LENGTH) - soap->dime.size = soap->count; /* DIME in MIME correction */ - if (!(soap->mode & SOAP_IO_LENGTH) && (soap->mode & SOAP_ENC_DIME)) - { if (soap_putdimehdr(soap)) - return soap->error; - } -#endif - soap->part = SOAP_IN_ENVELOPE; - return soap_element_begin_out(soap, "SOAP-ENV:Envelope", 0, NULL); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_envelope_end_out(struct soap *soap) -{ if (soap_element_end_out(soap, "SOAP-ENV:Envelope")) - return soap->error; -#ifndef WITH_LEANER - if ((soap->mode & SOAP_IO_LENGTH) && (soap->mode & SOAP_ENC_DIME) && !(soap->mode & SOAP_ENC_MTOM)) - { soap->dime.size = soap->count - soap->dime.size; /* DIME in MIME correction */ - sprintf(soap->id, soap->dime_id_format, 0); - soap->dime.id = soap->id; - if (soap->local_namespaces) - { if (soap->local_namespaces[0].out) - soap->dime.type = (char*)soap->local_namespaces[0].out; - else - soap->dime.type = (char*)soap->local_namespaces[0].ns; - } - soap->dime.options = NULL; - soap->dime.flags = SOAP_DIME_MB | SOAP_DIME_ABSURI; - if (!soap->dime.first) - soap->dime.flags |= SOAP_DIME_ME; - soap->count += 12 + ((strlen(soap->dime.id)+3)&(~3)) + (soap->dime.type ? ((strlen(soap->dime.type)+3)&(~3)) : 0); - } - if ((soap->mode & SOAP_ENC_DIME) && !(soap->mode & SOAP_ENC_MTOM)) - return soap_send_raw(soap, SOAP_STR_PADDING, -(long)soap->dime.size&3); -#endif - soap->part = SOAP_END_ENVELOPE; - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -static char* -soap_get_http_body(struct soap *soap) -{ -#ifndef WITH_LEAN - register size_t l = 0, n = 0; - register char *s; - /* get HTML body of HTTP error content */ - if (!(soap->mode & SOAP_ENC_ZLIB) && (soap->mode & SOAP_IO) != SOAP_IO_CHUNK) - { n = soap->length; - if (!n) - return NULL; - } -#ifdef WITH_FAST - soap->labidx = 0; /* use look-aside buffer */ -#else - if (soap_new_block(soap) == NULL) - return NULL; -#endif - for (;;) - { -#ifdef WITH_FAST - register size_t i, k; - if (soap_append_lab(soap, NULL, 0)) /* allocate more space in look-aside buffer if necessary */ - return NULL; - s = soap->labbuf + soap->labidx; /* space to populate */ - k = soap->lablen - soap->labidx; /* number of bytes available */ - soap->labidx = soap->lablen; /* claim this space */ -#else - register size_t i, k = SOAP_BLKLEN; - if (!(s = (char*)soap_push_block(soap, NULL, k))) - return NULL; -#endif - for (i = 0; i < k; i++) - { register soap_wchar c = soap_getchar(soap); - if ((int)c == EOF) - goto end; - *s++ = (char)(c & 0xFF); - l++; - if (n > 0 && l >= n) - goto end; - } - } -end: - *s = '\0'; -#ifdef WITH_FAST - s = soap_strdup(soap, soap->labbuf); -#else - soap_size_block(soap, NULL, i+1); - s = soap_save_block(soap, NULL, 0); -#endif - return s; -#else - return NULL; -#endif -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_envelope_begin_in(struct soap *soap) -{ register struct Namespace *p; - soap->part = SOAP_IN_ENVELOPE; - if (soap_element_begin_in(soap, "SOAP-ENV:Envelope", 0, NULL)) - { if (soap->error == SOAP_TAG_MISMATCH - && !soap_element_begin_in(soap, "Envelope", 0, NULL)) - soap->error = SOAP_VERSIONMISMATCH; - else if (soap->status) - soap->error = soap->status; - return soap->error; - } - p = soap->local_namespaces; - if (p) - { const char *ns = p[0].out; - if (!ns) - ns = p[0].ns; - if (!strcmp(ns, soap_env1)) - { soap->version = 1; /* make sure we use SOAP 1.1 */ - if (p[1].out) - SOAP_FREE(soap, p[1].out); - if ((p[1].out = (char*)SOAP_MALLOC(soap, sizeof(soap_enc1)))) - strcpy(p[1].out, soap_enc1); - } - else if (!strcmp(ns, soap_env2)) - { soap->version = 2; /* make sure we use SOAP 1.2 */ - if (p[1].out) - SOAP_FREE(soap, p[1].out); - if ((p[1].out = (char*)SOAP_MALLOC(soap, sizeof(soap_enc2)))) - strcpy(p[1].out, soap_enc2); - } - } - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_envelope_end_in(struct soap *soap) -{ soap->part = SOAP_END_ENVELOPE; - return soap_element_end_in(soap, "SOAP-ENV:Envelope"); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_body_begin_out(struct soap *soap) -{ soap->part = SOAP_IN_BODY; - if (soap->version == 1) - soap->encoding = 1; -#ifndef WITH_LEAN - if ((soap->mode & SOAP_XML_SEC) && soap_set_attr(soap, "wsu:Id", "Body")) - return soap->error; -#endif - if (soap_element(soap, "SOAP-ENV:Body", 0, NULL)) - return soap->error; - return soap_element_start_end_out(soap, NULL); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_body_end_out(struct soap *soap) -{ if (soap_element_end_out(soap, "SOAP-ENV:Body")) - return soap->error; - soap->part = SOAP_END_BODY; - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_body_begin_in(struct soap *soap) -{ soap->part = SOAP_IN_BODY; - if (soap_element_begin_in(soap, "SOAP-ENV:Body", 0, NULL)) - return soap->error; - if (!soap->body) - soap->part = SOAP_NO_BODY; - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_body_end_in(struct soap *soap) -{ if (soap->part == SOAP_NO_BODY) - return SOAP_OK; - soap->part = SOAP_END_BODY; - return soap_element_end_in(soap, "SOAP-ENV:Body"); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_recv_header(struct soap *soap) -{ if (soap_getheader(soap) && soap->error == SOAP_TAG_MISMATCH) - soap->error = SOAP_OK; - if (soap->error == SOAP_OK && soap->fheader) - soap->error = soap->fheader(soap); - return soap->error; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_set_endpoint(struct soap *soap, const char *endpoint) -{ register const char *s; - register size_t i, n; - soap->endpoint[0] = '\0'; - soap->host[0] = '\0'; - soap->path[0] = '/'; - soap->path[1] = '\0'; - soap->port = 80; - if (!endpoint || !*endpoint) - return; -#ifdef WITH_OPENSSL - if (!soap_tag_cmp(endpoint, "https:*")) - soap->port = 443; -#endif - strncpy(soap->endpoint, endpoint, sizeof(soap->endpoint) - 1); - soap->endpoint[sizeof(soap->endpoint) - 1] = '\0'; - s = strchr(endpoint, ':'); - if (s && s[1] == '/' && s[2] == '/') - s += 3; - else - s = endpoint; - n = strlen(s); - if (n >= sizeof(soap->host)) - n = sizeof(soap->host) - 1; -#ifdef WITH_IPV6 - if (s[0] == '[') - { s++; - for (i = 0; i < n; i++) - { if (s[i] == ']') - { s++; - --n; - break; - } - soap->host[i] = s[i]; - } - } - else - { for (i = 0; i < n; i++) - { soap->host[i] = s[i]; - if (s[i] == '/' || s[i] == ':') - break; - } - } -#else - for (i = 0; i < n; i++) - { soap->host[i] = s[i]; - if (s[i] == '/' || s[i] == ':') - break; - } -#endif - soap->host[i] = '\0'; - if (s[i] == ':') - { soap->port = (int)atol(s + i + 1); - for (i++; i < n; i++) - if (s[i] == '/') - break; - } - if (i < n && s[i]) - { strncpy(soap->path, s + i, sizeof(soap->path)); - soap->path[sizeof(soap->path) - 1] = '\0'; - } -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_connect(struct soap *soap, const char *endpoint, const char *action) -{ return soap_connect_command(soap, SOAP_POST, endpoint, action); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_connect_command(struct soap *soap, int http_command, const char *endpoints, const char *action) -{ char *endpoint; - const char *s; - if (endpoints && (s = strchr(endpoints, ' '))) - { endpoint = (char*)SOAP_MALLOC(soap, strlen(endpoints) + 1); - for (;;) - { strncpy(endpoint, endpoints, s - endpoints); - endpoint[s - endpoints] = '\0'; - if (soap_try_connect_command(soap, http_command, endpoint, action) != SOAP_TCP_ERROR) - break; - if (!*s) - break; - soap->error = SOAP_OK; - while (*s == ' ') - s++; - endpoints = s; - s = strchr(endpoints, ' '); - if (!s) - s = endpoints + strlen(endpoints); - } - SOAP_FREE(soap, endpoint); - } - else - soap_try_connect_command(soap, http_command, endpoints, action); - return soap->error; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -static int -soap_try_connect_command(struct soap *soap, int http_command, const char *endpoint, const char *action) -{ char host[sizeof(soap->host)]; - int port; - size_t count; - soap->error = SOAP_OK; - strcpy(host, soap->host); /* save previous host name: if != then reconnect */ - port = soap->port; /* save previous port to compare */ - soap->status = http_command; - soap_set_endpoint(soap, endpoint); -#ifndef WITH_LEANER - if (soap->fconnect) - { if ((soap->error = soap->fconnect(soap, endpoint, soap->host, soap->port))) - return soap->error; - } - else -#endif - if (soap->fopen && *soap->host) - { if (!soap->keep_alive || !soap_valid_socket(soap->socket) || strcmp(soap->host, host) || soap->port != port || !soap->fpoll || soap->fpoll(soap)) - { soap->keep_alive = 0; /* to force close */ - soap->omode &= ~SOAP_IO_UDP; /* to force close */ - soap_closesock(soap); - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Connect/reconnect to host='%s' path='%s' port=%d\n", soap->host, soap->path, soap->port)); -#ifndef WITH_LEAN - if (!strncmp(endpoint, "soap.udp:", 9)) - soap->omode |= SOAP_IO_UDP; -#endif - soap->socket = soap->fopen(soap, endpoint, soap->host, soap->port); - if (soap->error) - return soap->error; - soap->keep_alive = ((soap->omode & SOAP_IO_KEEPALIVE) != 0); - } - } - count = soap_count_attachments(soap); - if (soap_begin_send(soap)) - return soap->error; - if (http_command == SOAP_GET) - { soap->mode &= ~SOAP_IO; - soap->mode |= SOAP_IO_BUFFER; - } -#ifndef WITH_NOHTTP - soap->action = soap_strdup(soap, action); - if ((soap->mode & SOAP_IO) != SOAP_IO_STORE && !(soap->mode & SOAP_ENC_XML) && endpoint) - { unsigned int k = soap->mode; - soap->mode &= ~(SOAP_IO | SOAP_ENC_ZLIB); - if ((k & SOAP_IO) != SOAP_IO_FLUSH) - soap->mode |= SOAP_IO_BUFFER; - if ((soap->error = soap->fpost(soap, endpoint, soap->host, soap->port, soap->path, action, count))) - return soap->error; -#ifndef WITH_LEANER - if ((k & SOAP_IO) == SOAP_IO_CHUNK) - { if (soap_flush(soap)) - return soap->error; - } -#endif - soap->mode = k; - } - if (http_command == SOAP_GET) - return soap_end_send(soap); -#endif - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEAN -SOAP_FMAC1 -char* -SOAP_FMAC2 -soap_s2base64(struct soap *soap, const unsigned char *s, char *t, int n) -{ register int i; - register unsigned long m; - register char *p; - if (!t) - t = (char*)soap_malloc(soap, (n + 2) / 3 * 4 + 1); - if (!t) - return NULL; - p = t; - t[0] = '\0'; - if (!s) - return p; - for (; n > 2; n -= 3, s += 3) - { m = s[0]; - m = (m << 8) | s[1]; - m = (m << 8) | s[2]; - for (i = 4; i > 0; m >>= 6) - t[--i] = soap_base64o[m & 0x3F]; - t += 4; - } - t[0] = '\0'; - if (n > 0) - { m = 0; - for (i = 0; i < n; i++) - m = (m << 8) | *s++; - for (; i < 3; i++) - m <<= 8; - for (i++; i > 0; m >>= 6) - t[--i] = soap_base64o[m & 0x3F]; - for (i = 3; i > n; i--) - t[i] = '='; - t[4] = '\0'; - } - return p; -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEAN -SOAP_FMAC1 -const char* -SOAP_FMAC2 -soap_base642s(struct soap *soap, const char *s, char *t, size_t l, int *n) -{ register int i, j, c; - register unsigned long m; - register const char *p; - if (!s || !*s) - { if (n) - *n = 0; - if (soap->error) - return NULL; - return SOAP_NON_NULL; - } - if (!t) - { l = (strlen(s) + 3) / 4 * 3; - t = (char*)soap_malloc(soap, l); - } - if (!t) - return NULL; - p = t; - if (n) - *n = 0; - for (;;) - { for (i = 0; i < SOAP_BLKLEN; i++) - { m = 0; - j = 0; - while (j < 4) - { c = *s++; - if (c == '=' || !c) - { i *= 3; - switch (j) - { case 2: - *t++ = (char)((m >> 4) & 0xFF); - i++; - break; - case 3: - *t++ = (char)((m >> 10) & 0xFF); - *t++ = (char)((m >> 2) & 0xFF); - i += 2; - } - if (n) - *n += i; - return p; - } - c -= '+'; - if (c >= 0 && c <= 79) - { int b = soap_base64i[c]; - if (b >= 64) - { soap->error = SOAP_TYPE; - return NULL; - } - m = (m << 6) + b; - j++; - } - else if (!soap_blank(c + '+')) - { soap->error = SOAP_TYPE; - return NULL; - } - } - *t++ = (char)((m >> 16) & 0xFF); - *t++ = (char)((m >> 8) & 0xFF); - *t++ = (char)(m & 0xFF); - if (l < 3) - { if (n) - *n += i; - return p; - } - l -= 3; - } - if (n) - *n += 3 * SOAP_BLKLEN; - } -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEAN -SOAP_FMAC1 -char* -SOAP_FMAC2 -soap_s2hex(struct soap *soap, const unsigned char *s, char *t, int n) -{ register char *p; - if (!t) - t = (char*)soap_malloc(soap, 2 * n + 1); - if (!t) - return NULL; - p = t; - t[0] = '\0'; - if (s) - { for (; n > 0; n--) - { register int m = *s++; - *t++ = (char)((m >> 4) + (m > 159 ? 'a' - 10 : '0')); - m &= 0x0F; - *t++ = (char)(m + (m > 9 ? 'a' - 10 : '0')); - } - } - *t++ = '\0'; - return p; -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEAN -SOAP_FMAC1 -const char* -SOAP_FMAC2 -soap_hex2s(struct soap *soap, const char *s, char *t, size_t l, int *n) -{ register const char *p; - if (!s || !*s) - { if (n) - *n = 0; - if (soap->error) - return NULL; - return SOAP_NON_NULL; - } - if (!t) - { l = strlen(s) / 2; - t = (char*)soap_malloc(soap, l); - } - if (!t) - return NULL; - p = t; - while (l) - { register int d1, d2; - d1 = *s++; - if (!d1) - break; - d2 = *s++; - if (!d2) - break; - *t++ = ((d1 >= 'A' ? (d1 & 0x7) + 9 : d1 - '0') << 4) + (d2 >= 'A' ? (d2 & 0x7) + 9 : d2 - '0'); - l--; - } - if (n) - *n = (int)(t - p); - return p; -} -#endif - -/******************************************************************************/ -#ifndef WITH_NOHTTP -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_puthttphdr(struct soap *soap, int status, size_t count) -{ if (soap->status != SOAP_GET) - { register const char *s = "text/xml; charset=utf-8"; - register int err = SOAP_OK; -#ifndef WITH_LEANER - register const char *r = NULL; -#endif - if ((status == SOAP_FILE || soap->status == SOAP_POST_FILE) && soap->http_content) - s = soap->http_content; - else if (status == SOAP_HTML) - s = "text/html; charset=utf-8"; - else if (count || ((soap->omode & SOAP_IO) == SOAP_IO_CHUNK)) - { if (soap->version == 2) - s = "application/soap+xml; charset=utf-8"; - } -#ifndef WITH_LEANER - if (soap->mode & (SOAP_ENC_DIME | SOAP_ENC_MTOM)) - { if (soap->mode & SOAP_ENC_MTOM) - { if (soap->version == 2) - r = "application/soap+xml"; - else - r = "text/xml"; - s = "application/xop+xml"; - } - else - s = "application/dime"; - } - if ((soap->mode & SOAP_ENC_MIME) && soap->mime.boundary && strlen(soap->mime.boundary) + strlen(soap->mime.start ? soap->mime.start : SOAP_STR_EOS) < sizeof(soap->tmpbuf) - 80) - { register const char *t = strchr(s, ';'); - sprintf(soap->tmpbuf, "multipart/related; charset=utf-8; boundary=\"%s\"; type=\"", soap->mime.boundary); - if (t) - { strncat(soap->tmpbuf, s, t - s); - soap->tmpbuf[sizeof(soap->tmpbuf)-1] = '\0'; - } - else - strcat(soap->tmpbuf, s); - if (soap->mime.start) - { strcat(soap->tmpbuf, "\"; start=\""); - strcat(soap->tmpbuf, soap->mime.start); - } - strcat(soap->tmpbuf, "\""); - if (r) - { strcat(soap->tmpbuf, "; start-info=\""); - strcat(soap->tmpbuf, r); - strcat(soap->tmpbuf, "\""); - } - s = soap->tmpbuf; - } -#endif - if (s && (err = soap->fposthdr(soap, "Content-Type", s))) - return err; -#ifdef WITH_ZLIB - if ((soap->omode & SOAP_ENC_ZLIB)) - { -#ifdef WITH_GZIP - err = soap->fposthdr(soap, "Content-Encoding", soap->zlib_out == SOAP_ZLIB_DEFLATE ? "deflate" : "gzip"); -#else - err = soap->fposthdr(soap, "Content-Encoding", "deflate"); -#endif - if (err) - return err; - } -#endif -#ifndef WITH_LEANER - if ((soap->omode & SOAP_IO) == SOAP_IO_CHUNK) - err = soap->fposthdr(soap, "Transfer-Encoding", "chunked"); - else -#endif - if (s) - { sprintf(soap->tmpbuf, "%lu", (unsigned long)count); - err = soap->fposthdr(soap, "Content-Length", soap->tmpbuf); - } - if (err) - return err; - } - return soap->fposthdr(soap, "Connection", soap->keep_alive ? "keep-alive" : "close"); -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOHTTP -#ifndef PALM_1 -static int -http_get(struct soap *soap) -{ return SOAP_GET_METHOD; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOHTTP -#ifndef PALM_1 -static int -http_405(struct soap *soap) -{ return 405; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOHTTP -#ifndef PALM_1 -static int -http_post(struct soap *soap, const char *endpoint, const char *host, int port, const char *path, const char *action, size_t count) -{ register const char *s; - register int err; - if (soap->status == SOAP_GET) - s = "GET"; - else - s = "POST"; -#ifdef PALM - if (!endpoint || (soap_tag_cmp(endpoint, "http:*") && soap_tag_cmp(endpoint, "https:*") && strncmp(endpoint, "httpg:", 6)) && strncmp(endpoint, "_beam:", 6) && strncmp(endpoint, "_local:", 7) && strncmp(endpoint, "_btobex:", 8)) -#else - if (!endpoint || (soap_tag_cmp(endpoint, "http:*") && soap_tag_cmp(endpoint, "https:*") && strncmp(endpoint, "httpg:", 6))) -#endif - return SOAP_OK; - if (strlen(endpoint) + strlen(soap->http_version) > sizeof(soap->tmpbuf) - 80) - return soap->error = SOAP_EOM; - if (soap->proxy_host && soap_tag_cmp(endpoint, "https:*")) - sprintf(soap->tmpbuf, "%s %s HTTP/%s", s, endpoint, soap->http_version); - else - sprintf(soap->tmpbuf, "%s /%s HTTP/%s", s, (*path == '/' ? path + 1 : path), soap->http_version); - if ((err = soap->fposthdr(soap, soap->tmpbuf, NULL))) - return err; -#ifdef WITH_OPENSSL - if ((soap->ssl && soap->port != 443) || (!soap->ssl && soap->port != 80)) - sprintf(soap->tmpbuf, "%s:%d", host, port); - else - strcpy(soap->tmpbuf, host); -#else - if (port != 80) - sprintf(soap->tmpbuf, "%s:%d", host, port); - else - strcpy(soap->tmpbuf, host); -#endif - if ((err = soap->fposthdr(soap, "Host", soap->tmpbuf)) - || (err = soap->fposthdr(soap, "User-Agent", "gSOAP/2.7")) - || (err = soap_puthttphdr(soap, SOAP_OK, count))) - return err; -#ifdef WITH_ZLIB -#ifdef WITH_GZIP - if ((err = soap->fposthdr(soap, "Accept-Encoding", "gzip, deflate"))) -#else - if ((err = soap->fposthdr(soap, "Accept-Encoding", "deflate"))) -#endif - return err; -#endif -#ifndef WITH_LEAN - if (soap->userid && soap->passwd && strlen(soap->userid) + strlen(soap->passwd) < 761) - { sprintf(soap->tmpbuf + 262, "%s:%s", soap->userid, soap->passwd); - strcpy(soap->tmpbuf, "Basic "); - soap_s2base64(soap, (const unsigned char*)(soap->tmpbuf + 262), soap->tmpbuf + 6, (int)strlen(soap->tmpbuf + 262)); - if ((err = soap->fposthdr(soap, "Authorization", soap->tmpbuf))) - return err; - } - if (soap->proxy_userid && soap->proxy_passwd && strlen(soap->proxy_userid) + strlen(soap->proxy_passwd) < 761) - { sprintf(soap->tmpbuf + 262, "%s:%s", soap->proxy_userid, soap->proxy_passwd); - strcpy(soap->tmpbuf, "Basic "); - soap_s2base64(soap, (const unsigned char*)(soap->tmpbuf + 262), soap->tmpbuf + 6, (int)strlen(soap->tmpbuf + 262)); - if ((err = soap->fposthdr(soap, "Proxy-Authorization", soap->tmpbuf))) - return err; - } -#endif -#ifdef WITH_COOKIES -#ifdef WITH_OPENSSL - if (soap_putcookies(soap, host, path, soap->ssl != NULL)) - return soap->error; -#else - if (soap_putcookies(soap, host, path, 0)) - return soap->error; -#endif -#endif - if (soap->status != SOAP_GET && (soap->version == 1 || (action && *action))) - { sprintf(soap->tmpbuf, "\"%s\"", action && strlen(action) < sizeof(soap->tmpbuf) - 3 ? action : SOAP_STR_EOS); - if ((err = soap->fposthdr(soap, "SOAPAction", soap->tmpbuf))) - return err; - } - return soap->fposthdr(soap, NULL, NULL); -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOHTTP -#ifndef PALM_1 -static int -http_send_header(struct soap *soap, const char *s) -{ register const char *t; - do - { t = strchr(s, '\n'); /* disallow \n in HTTP headers */ - if (!t) - t = s + strlen(s); - if (soap_send_raw(soap, s, t - s)) - return soap->error; - s = t + 1; - } while (*t); - return SOAP_OK; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOHTTP -#ifndef PALM_1 -static int -http_post_header(struct soap *soap, const char *key, const char *val) -{ if (key) - { if (http_send_header(soap, key)) - return soap->error; - if (val && (soap_send_raw(soap, ": ", 2) || http_send_header(soap, val))) - return soap->error; - } - return soap_send_raw(soap, "\r\n", 2); -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOHTTP -#ifndef PALM_1 -static int -http_response(struct soap *soap, int status, size_t count) -{ register int err; -#ifdef WMW_RPM_IO - if (soap->rpmreqid) - httpOutputEnable(soap->rpmreqid); -#endif - if (strlen(soap->http_version) > 4) - return soap->error = SOAP_EOM; - if (!status || status == SOAP_HTML || status == SOAP_FILE) - { const char *s; - if (count || ((soap->omode & SOAP_IO) == SOAP_IO_CHUNK)) - s = "200 OK"; - else - s = "202 ACCEPTED"; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Status = %s\n", s)); -#ifdef WMW_RPM_IO - if (soap->rpmreqid || soap_valid_socket(soap->master) || soap_valid_socket(soap->socket)) /* RPM behaves as if standalone */ -#else - if (soap_valid_socket(soap->master) || soap_valid_socket(soap->socket)) /* standalone application (socket) or CGI (stdin/out)? */ -#endif - { sprintf(soap->tmpbuf, "HTTP/%s %s", soap->http_version, s); - if ((err = soap->fposthdr(soap, soap->tmpbuf, NULL))) - return err; - } - else if ((err = soap->fposthdr(soap, "Status", s))) /* CGI header */ - return err; - } - else if (status >= 200 && status < 600) - { sprintf(soap->tmpbuf, "HTTP/%s %d %s", soap->http_version, status, http_error(soap, status)); - if ((err = soap->fposthdr(soap, soap->tmpbuf, NULL))) - return err; -#ifndef WITH_LEAN - if (status == 401) - { sprintf(soap->tmpbuf, "Basic realm=\"%s\"", (soap->authrealm && strlen(soap->authrealm) < sizeof(soap->tmpbuf) - 14) ? soap->authrealm : "gSOAP Web Service"); - if ((err = soap->fposthdr(soap, "WWW-Authenticate", soap->tmpbuf))) - return err; - } - else if ((status >= 301 && status <= 303) || status == 307) - { if ((err = soap->fposthdr(soap, "Location", soap->endpoint))) - return err; - } -#endif - } - else - { const char *s = *soap_faultcode(soap); - if (status >= SOAP_GET_METHOD && status <= SOAP_HTTP_METHOD) - s = "405 Method Not Allowed"; - else if (soap->version == 2 && (!s || !strcmp(s, "SOAP-ENV:Sender"))) - s = "400 Bad Request"; - else - s = "500 Internal Server Error"; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Error %s (status=%d)\n", s, status)); -#ifdef WMW_RPM_IO - if (soap->rpmreqid || soap_valid_socket(soap->master) || soap_valid_socket(soap->socket)) /* RPM behaves as if standalone */ -#else - if (soap_valid_socket(soap->master) || soap_valid_socket(soap->socket)) /* standalone application */ -#endif - { sprintf(soap->tmpbuf, "HTTP/%s %s", soap->http_version, s); - if ((err = soap->fposthdr(soap, soap->tmpbuf, NULL))) - return err; - } - else if ((err = soap->fposthdr(soap, "Status", s))) /* CGI */ - return err; - } - if ((err = soap->fposthdr(soap, "Server", "gSOAP/2.7")) - || (err = soap_puthttphdr(soap, status, count))) - return err; -#ifdef WITH_COOKIES - if (soap_putsetcookies(soap)) - return soap->error; -#endif - return soap->fposthdr(soap, NULL, NULL); -} -#endif -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_response(struct soap *soap, int status) -{ register size_t count; - if (!(soap->omode & (SOAP_ENC_XML | SOAP_IO_STORE /* this tests for chunking too */)) - && (status == SOAP_HTML || status == SOAP_FILE)) - soap->omode = (soap->omode & ~SOAP_IO) | SOAP_IO_STORE; - soap->status = status; - count = soap_count_attachments(soap); - if (soap_begin_send(soap)) - return soap->error; -#ifndef WITH_NOHTTP - if ((soap->mode & SOAP_IO) != SOAP_IO_STORE && !(soap->mode & SOAP_ENC_XML)) - { register int n = soap->mode; - soap->mode &= ~(SOAP_IO | SOAP_ENC_ZLIB); - if ((n & SOAP_IO) != SOAP_IO_FLUSH) - soap->mode |= SOAP_IO_BUFFER; - if ((soap->error = soap->fresponse(soap, status, count))) - return soap->error; -#ifndef WITH_LEANER - if ((n & SOAP_IO) == SOAP_IO_CHUNK) - { if (soap_flush(soap)) - return soap->error; - } -#endif - soap->mode = n; - } -#endif - return SOAP_OK; -} -#endif - -/******************************************************************************/ -#ifndef WITH_LEAN -static const char* -soap_set_validation_fault(struct soap *soap, const char *s, const char *t) -{ if (*soap->tag) - sprintf(soap->msgbuf, "Validation constraint violation: %s%s in element '%s'", s, t?t:SOAP_STR_EOS, soap->tag); - else - sprintf(soap->msgbuf, "Validation constraint violation: %s%s", s, t?t:SOAP_STR_EOS); - return soap->msgbuf; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_set_fault(struct soap *soap) -{ const char **c = soap_faultcode(soap); - const char **s = soap_faultstring(soap); - if (soap->fseterror) - soap->fseterror(soap, c, s); - if (!*c) - { if (soap->version == 2) - *c = "SOAP-ENV:Sender"; - else - *c = "SOAP-ENV:Client"; - } - if (*s) - return; - switch (soap->error) - { -#ifndef WITH_LEAN - case SOAP_CLI_FAULT: - *s = "Client fault"; - break; - case SOAP_SVR_FAULT: - *s = "Server fault"; - break; - case SOAP_TAG_MISMATCH: - *s = soap_set_validation_fault(soap, "tag name or namespace mismatch", NULL); - break; - case SOAP_TYPE: - *s = soap_set_validation_fault(soap, "data type mismatch ", soap->type); - break; - case SOAP_SYNTAX_ERROR: - *s = "Well-formedness violation"; - break; - case SOAP_NO_TAG: - *s = "No XML element tag"; - break; - case SOAP_MUSTUNDERSTAND: - *c = "SOAP-ENV:MustUnderstand"; - sprintf(soap->msgbuf, "The data in element '%s' must be understood but cannot be handled", soap->tag); - *s = soap->msgbuf; - break; - case SOAP_VERSIONMISMATCH: - *c = "SOAP-ENV:VersionMismatch"; - *s = "Invalid SOAP message or SOAP version mismatch"; - break; - case SOAP_DATAENCODINGUNKNOWN: - *c = "SOAP-ENV:DataEncodingUnknown"; - *s = "Unsupported SOAP data encoding"; - break; - case SOAP_NAMESPACE: - *s = soap_set_validation_fault(soap, "namespace error", NULL); - break; - case SOAP_USER_ERROR: - *s = "User error"; - break; - case SOAP_FATAL_ERROR: - *s = "Fatal error"; - break; - case SOAP_NO_METHOD: - sprintf(soap->msgbuf, "Method '%s' not implemented: method name or namespace not recognized", soap->tag); - *s = soap->msgbuf; - break; - case SOAP_NO_DATA: - *s = "Data required for operation"; - break; - case SOAP_GET_METHOD: - *s = "HTTP GET method not implemented"; - break; - case SOAP_PUT_METHOD: - *s = "HTTP PUT method not implemented"; - break; - case SOAP_HEAD_METHOD: - *s = "HTTP HEAD method not implemented"; - break; - case SOAP_HTTP_METHOD: - *s = "HTTP method not implemented"; - break; - case SOAP_EOM: - *s = "Out of memory"; - break; - case SOAP_MOE: - *s = "Memory overflow or memory corruption error"; - break; - case SOAP_HDR: - *s = "Header line too long"; - break; - case SOAP_IOB: - *s = "Array index out of bounds"; - break; - case SOAP_NULL: - *s = soap_set_validation_fault(soap, "nil not allowed", NULL); - break; - case SOAP_DUPLICATE_ID: - *s = soap_set_validation_fault(soap, "multiple definitions of id ", soap->id); - if (soap->version == 2) - *soap_faultsubcode(soap) = "SOAP-ENC:DuplicateID"; - break; - case SOAP_MISSING_ID: - *s = soap_set_validation_fault(soap, "missing id for ref ", soap->id); - if (soap->version == 2) - *soap_faultsubcode(soap) = "SOAP-ENC:MissingID"; - break; - case SOAP_HREF: - *s = soap_set_validation_fault(soap, "incompatible object type ref/id pair ", soap->id); - break; - case SOAP_FAULT: - break; -#ifndef WITH_NOIO - case SOAP_UDP_ERROR: - *s = "Message too large for UDP packet"; - break; - case SOAP_TCP_ERROR: - *s = tcp_error(soap); - break; -#endif - case SOAP_HTTP_ERROR: - *s = "An HTTP processing error occurred"; - break; - case SOAP_SSL_ERROR: -#ifdef WITH_OPENSSL - *s = "SSL error"; -#else - *s = "OpenSSL not installed: recompile with -DWITH_OPENSSL"; -#endif - break; - case SOAP_PLUGIN_ERROR: - *s = "Plugin registry error"; - break; - case SOAP_DIME_ERROR: - *s = "DIME format error"; - break; - case SOAP_DIME_HREF: - *s = "DIME href to missing attachment"; - break; - case SOAP_DIME_MISMATCH: - *s = "DIME version/transmission error"; - break; - case SOAP_DIME_END: - *s = "End of DIME error"; - break; - case SOAP_MIME_ERROR: - *s = "MIME format error"; - break; - case SOAP_MIME_HREF: - *s = "MIME href to missing attachment"; - break; - case SOAP_MIME_END: - *s = "End of MIME error"; - break; - case SOAP_ZLIB_ERROR: -#ifdef WITH_ZLIB - sprintf(soap->msgbuf, "Zlib/gzip error: '%s'", soap->d_stream->msg?soap->d_stream->msg:SOAP_STR_EOS); - *s = soap->msgbuf; -#else - *s = "Zlib/gzip not installed for (de)compression: recompile with -DWITH_GZIP"; -#endif - break; - case SOAP_REQUIRED: - *s = soap_set_validation_fault(soap, "missing required attribute", NULL); - break; - case SOAP_PROHIBITED: - *s = soap_set_validation_fault(soap, "prohibited attribute present", NULL); - break; - case SOAP_OCCURS: - *s = soap_set_validation_fault(soap, "occurrence violation", NULL); - break; - case SOAP_LENGTH: - *s = soap_set_validation_fault(soap, "content range or length violation", NULL); - break; - case SOAP_FD_EXCEEDED: - *s = "Maximum number of open connections was reached (no define HAVE_POLL): increase FD_SETSIZE"; - break; - case SOAP_STOP: - *s = "Stopped: no response sent"; - break; -#endif - case SOAP_EOF: -#ifndef WITH_NOIO - strcpy(soap->msgbuf, soap_strerror(soap)); -#ifndef WITH_LEAN - if (strlen(soap->msgbuf) + 25 < sizeof(soap->msgbuf)) - { memmove(soap->msgbuf + 25, soap->msgbuf, strlen(soap->msgbuf) + 1); - memcpy(soap->msgbuf, "End of file or no input: ", 25); - } -#endif - *s = soap->msgbuf; - break; -#else - *s = "End of file or no input"; - break; -#endif - default: -#ifndef WITH_NOHTTP -#ifndef WITH_LEAN - if (soap->error > 200 && soap->error < 600) - { sprintf(soap->msgbuf, "HTTP Error: %d %s", soap->error, http_error(soap, soap->error)); - *s = soap->msgbuf; - } - else -#endif -#endif - { sprintf(soap->msgbuf, "Error %d", soap->error); - *s = soap->msgbuf; - } - } -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_send_fault(struct soap *soap) -{ register int status = soap->error; - if (status == SOAP_STOP) - return status; - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Sending back fault struct for error code %d\n", soap->error)); - soap->keep_alive = 0; /* to terminate connection */ - soap_set_fault(soap); - if (soap->error < 200 && soap->error != SOAP_FAULT) - soap->header = NULL; - if (status != SOAP_EOF || (!soap->recv_timeout && !soap->send_timeout)) - { int r = 1; -#ifndef WITH_NOIO - if (soap->fpoll && soap->fpoll(soap)) - r = 0; -#ifndef WITH_LEAN - else if (soap_valid_socket(soap->socket)) - { r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_SND, 0); - if (r > 0) - { if (!(r & SOAP_TCP_SELECT_SND) - || ((r & SOAP_TCP_SELECT_RCV) - && recv(soap->socket, soap->tmpbuf, 1, MSG_PEEK) < 0)) - r = 0; - } - } -#endif -#endif - if (r > 0) - { soap->error = SOAP_OK; - soap_serializeheader(soap); - soap_serializefault(soap); - soap_begin_count(soap); - if (soap->mode & SOAP_IO_LENGTH) - { soap_envelope_begin_out(soap); - soap_putheader(soap); - soap_body_begin_out(soap); - soap_putfault(soap); - soap_body_end_out(soap); - soap_envelope_end_out(soap); - } - soap_end_count(soap); - if (soap_response(soap, status) - || soap_envelope_begin_out(soap) - || soap_putheader(soap) - || soap_body_begin_out(soap) - || soap_putfault(soap) - || soap_body_end_out(soap) - || soap_envelope_end_out(soap)) - return soap_closesock(soap); - soap_end_send(soap); - } - } - soap->error = status; - return soap_closesock(soap); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_recv_fault(struct soap *soap) -{ register int status = soap->error; - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Receiving SOAP Fault\n")); - soap->error = SOAP_OK; - if (soap_getfault(soap)) - { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Error: soap_get_soapfault() failed. Is this a SOAP message at all?\n")); - *soap_faultcode(soap) = (soap->version == 2 ? "SOAP-ENV:Sender" : "SOAP-ENV:Client"); - soap->error = status; - soap_set_fault(soap); - } - else - { register const char *s = *soap_faultcode(soap); - if (!soap_match_tag(soap, s, "SOAP-ENV:Server") || !soap_match_tag(soap, s, "SOAP-ENV:Receiver")) - status = SOAP_SVR_FAULT; - else if (!soap_match_tag(soap, s, "SOAP-ENV:Client") || !soap_match_tag(soap, s, "SOAP-ENV:Sender")) - status = SOAP_CLI_FAULT; - else if (!soap_match_tag(soap, s, "SOAP-ENV:MustUnderstand")) - status = SOAP_MUSTUNDERSTAND; - else if (!soap_match_tag(soap, s, "SOAP-ENV:VersionMismatch")) - status = SOAP_VERSIONMISMATCH; - else - { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Fault code %s\n", s)); - status = SOAP_FAULT; - } - if (soap_body_end_in(soap) - || soap_envelope_end_in(soap) - || soap_end_recv(soap)) - return soap_closesock(soap); - soap->error = status; - } - return soap_closesock(soap); -} -#endif - -/******************************************************************************/ -#ifndef WITH_NOHTTP -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_send_empty_response(struct soap *soap, int httpstatuscode) -{ register soap_mode m = soap->omode; - soap->count = 0; - if ((m & SOAP_IO) == SOAP_IO_CHUNK) - soap->omode = (m & ~SOAP_IO) | SOAP_IO_BUFFER; - if (soap_response(soap, httpstatuscode) || soap_end_send(soap)) - { soap->omode = m; - return soap_closesock(soap); - } - soap->omode = m; - return SOAP_OK; -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOHTTP -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_recv_empty_response(struct soap *soap) -{ if (!soap_begin_recv(soap)) - soap_end_recv(soap); - else if (soap->error == SOAP_NO_DATA || soap->error == 202) - soap->error = SOAP_OK; - return soap_closesock(soap); -} -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_NOIO -#ifndef PALM_1 -static const char* -soap_strerror(struct soap *soap) -{ register int err = soap->errnum; - if (err) - { -#ifndef WIN32 - return strerror(err); -#else -#ifndef UNDER_CE - DWORD len; - *soap->msgbuf = '\0'; - len = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)soap->msgbuf, (DWORD)sizeof(soap->msgbuf), NULL); -#else - DWORD i, len; - *soap->msgbuf = '\0'; - len = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, 0, (LPTSTR)soap->msgbuf, (DWORD)(sizeof(soap->msgbuf)/sizeof(TCHAR)), NULL); - for (i = 0; i <= len; i++) - { if (((TCHAR*)soap->msgbuf)[i] < 0x80) - soap->msgbuf[i] = (char)((TCHAR*)soap->msgbuf)[i]; - else - soap->msgbuf[i] = '?'; - } -#endif - return soap->msgbuf; -#endif - } -#ifndef WITH_LEAN - if (soap->recv_timeout > 0) - { if (soap->send_timeout > 0) - sprintf(soap->msgbuf, "Operation interrupted or timed out after %ds send or %ds receive delay", soap->send_timeout, soap->recv_timeout); - else - sprintf(soap->msgbuf, "Operation interrupted or timed out after %ds receive delay", soap->recv_timeout); - return soap->msgbuf; - } -#endif - return "Operation interrupted or timed out"; -} -#endif -#endif - -/******************************************************************************/ -#ifndef PALM_2 -static int -soap_set_error(struct soap *soap, const char *faultcode, const char *faultsubcodeQName, const char *faultstring, const char *faultdetailXML, int soaperror) -{ *soap_faultcode(soap) = faultcode; - if (faultsubcodeQName) - *soap_faultsubcode(soap) = faultsubcodeQName; - *soap_faultstring(soap) = faultstring; - if (faultdetailXML && *faultdetailXML) - { register const char **s = soap_faultdetail(soap); - if (s) - *s = faultdetailXML; - } - return soap->error = soaperror; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_set_sender_error(struct soap *soap, const char *faultstring, const char *faultdetailXML, int soaperror) -{ return soap_set_error(soap, soap->version == 2 ? "SOAP-ENV:Sender" : "SOAP-ENV:Client", NULL, faultstring, faultdetailXML, soaperror); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_set_receiver_error(struct soap *soap, const char *faultstring, const char *faultdetailXML, int soaperror) -{ return soap_set_error(soap, soap->version == 2 ? "SOAP-ENV:Receiver" : "SOAP-ENV:Server", NULL, faultstring, faultdetailXML, soaperror); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -static int -soap_copy_fault(struct soap *soap, const char *faultcode, const char *faultsubcodeQName, const char *faultstring, const char *faultdetailXML) -{ char *r = NULL, *s = NULL, *t = NULL; - if (faultsubcodeQName) - r = soap_strdup(soap, faultsubcodeQName); - if (faultstring) - s = soap_strdup(soap, faultstring); - if (faultdetailXML) - t = soap_strdup(soap, faultdetailXML); - return soap_set_error(soap, faultcode, r, s, t, SOAP_FAULT); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_sender_fault(struct soap *soap, const char *faultstring, const char *faultdetailXML) -{ return soap_sender_fault_subcode(soap, NULL, faultstring, faultdetailXML); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_sender_fault_subcode(struct soap *soap, const char *faultsubcodeQName, const char *faultstring, const char *faultdetailXML) -{ return soap_copy_fault(soap, soap->version == 2 ? "SOAP-ENV:Sender" : "SOAP-ENV:Client", faultsubcodeQName, faultstring, faultdetailXML); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_receiver_fault(struct soap *soap, const char *faultstring, const char *faultdetailXML) -{ return soap_receiver_fault_subcode(soap, NULL, faultstring, faultdetailXML); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_receiver_fault_subcode(struct soap *soap, const char *faultsubcodeQName, const char *faultstring, const char *faultdetailXML) -{ return soap_copy_fault(soap, soap->version == 2 ? "SOAP-ENV:Receiver" : "SOAP-ENV:Server", faultsubcodeQName, faultstring, faultdetailXML); -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -#ifndef WITH_NOSTDLIB -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_print_fault(struct soap *soap, FILE *fd) -{ if (soap_check_state(soap)) - fprintf(fd, "Error: soap struct state not initialized\n"); - else if (soap->error) - { const char *c, *v = NULL, *s, **d; - d = soap_faultcode(soap); - if (!*d) - soap_set_fault(soap); - c = *d; - if (soap->version == 2) - v = *soap_faultsubcode(soap); - s = *soap_faultstring(soap); - d = soap_faultdetail(soap); - fprintf(fd, "%s%d fault: %s [%s]\n\"%s\"\nDetail: %s\n", soap->version ? "SOAP 1." : "Error ", soap->version ? (int)soap->version : soap->error, c, v ? v : "no subcode", s ? s : "[no reason]", d && *d ? *d : "[no detail]"); - } -} -#endif -#endif - -/******************************************************************************/ -#ifdef __cplusplus -#ifndef WITH_LEAN -#ifndef WITH_NOSTDLIB -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_stream_fault(struct soap *soap, std::ostream& os) -{ if (soap_check_state(soap)) - os << "Error: soap struct state not initialized\n"; - else if (soap->error) - { const char *c, *v = NULL, *s, **d; - d = soap_faultcode(soap); - if (!*d) - soap_set_fault(soap); - c = *d; - if (soap->version == 2) - v = *soap_faultsubcode(soap); - s = *soap_faultstring(soap); - d = soap_faultdetail(soap); - os << (soap->version ? "SOAP 1." : "Error ") - << (soap->version ? (int)soap->version : soap->error) - << " fault: " << c - << "[" << (v ? v : "no subcode") << "]" - << std::endl - << "\"" << (s ? s : "[no reason]") << "\"" - << std::endl - << "Detail: " << (d && *d ? *d : "[no detail]") - << std::endl; - } -} -#endif -#endif -#endif - -/******************************************************************************/ -#ifndef WITH_LEAN -#ifndef WITH_NOSTDLIB -SOAP_FMAC1 -char* -SOAP_FMAC2 -soap_sprint_fault(struct soap *soap, char *buf, size_t len) -{ if (soap_check_state(soap)) - strncpy(buf, "Error: soap struct not initialized", len); - else if (soap->error) - { const char *c, *v = NULL, *s, **d; - d = soap_faultcode(soap); - if (!*d) - soap_set_fault(soap); - c = *d; - if (soap->version == 2) - v = *soap_faultsubcode(soap); - s = *soap_faultstring(soap); - d = soap_faultdetail(soap); -#ifdef WIN32 - _snprintf -#else - snprintf -#endif - (buf, len, "%s%d fault: %s [%s]\n\"%s\"\nDetail: %s\n", soap->version ? "SOAP 1." : "Error ", soap->version ? (int)soap->version : soap->error, c, v ? v : "no subcode", s ? s : "[no reason]", d && *d ? *d : "[no detail]"); - } - return buf; -} -#endif -#endif - -/******************************************************************************/ -#ifndef PALM_1 -#ifndef WITH_NOSTDLIB -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_print_fault_location(struct soap *soap, FILE *fd) -{ -#ifndef WITH_LEAN - int i, j, c1, c2; - if (soap->error && soap->bufidx <= soap->buflen && soap->buflen > 0 && soap->buflen <= SOAP_BUFLEN) - { i = (int)soap->bufidx - 1; - if (i <= 0) - i = 0; - c1 = soap->buf[i]; - soap->buf[i] = '\0'; - if ((int)soap->buflen >= i + 1024) - j = i + 1023; - else - j = (int)soap->buflen - 1; - c2 = soap->buf[j]; - soap->buf[j] = '\0'; - fprintf(fd, "%s%c\n\n", soap->buf, c1); - if (soap->bufidx < soap->buflen) - fprintf(fd, "%s\n", soap->buf + soap->bufidx); - soap->buf[i] = c1; - soap->buf[j] = c2; - } -#endif -} -#endif -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -int -SOAP_FMAC2 -soap_register_plugin_arg(struct soap *soap, int (*fcreate)(struct soap*, struct soap_plugin*, void*), void *arg) -{ register struct soap_plugin *p; - register int r; - if (!(p = (struct soap_plugin*)SOAP_MALLOC(soap, sizeof(struct soap_plugin)))) - return soap->error = SOAP_EOM; - p->id = NULL; - p->data = NULL; - p->fcopy = NULL; - p->fdelete = NULL; - r = fcreate(soap, p, arg); - if (!r && p->fdelete) - { p->next = soap->plugins; - soap->plugins = p; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Registered '%s' plugin\n", p->id)); - return SOAP_OK; - } - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not register plugin '%s': plugin returned error %d (or fdelete callback not set)\n", p->id?p->id:"?", r)); - SOAP_FREE(soap, p); - return r; -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -static void * -fplugin(struct soap *soap, const char *id) -{ register struct soap_plugin *p; - for (p = soap->plugins; p; p = p->next) - if (p->id == id || !strcmp(p->id, id)) - return p->data; - return NULL; -} -#endif - -/******************************************************************************/ -#ifndef PALM_2 -SOAP_FMAC1 -void * -SOAP_FMAC2 -soap_lookup_plugin(struct soap *soap, const char *id) -{ return soap->fplugin(soap, id); -} -#endif - -/******************************************************************************/ -#ifdef __cplusplus -} -#endif - -/******************************************************************************\ - * - * C++ soap struct methods - * -\******************************************************************************/ - -#ifdef __cplusplus -soap::soap() -{ soap_init(this); -} -#endif - -/******************************************************************************/ -#ifdef __cplusplus -soap::soap(soap_mode m) -{ soap_init1(this, m); -} -#endif - -/******************************************************************************/ -#ifdef __cplusplus -soap::soap(soap_mode im, soap_mode om) -{ soap_init2(this, im, om); -} -#endif - -/******************************************************************************/ -#ifdef __cplusplus -soap::soap(const struct soap& soap) -{ soap_copy_context(this, &soap); -} -#endif - -/******************************************************************************/ -#ifdef __cplusplus -soap::~soap() -{ soap_destroy(this); - soap_end(this); - soap_done(this); -} -#endif - -/******************************************************************************/ diff --git a/externals/gsoap/stdsoap2.h b/externals/gsoap/stdsoap2.h deleted file mode 100644 index 0aa8e409578..00000000000 --- a/externals/gsoap/stdsoap2.h +++ /dev/null @@ -1,2360 +0,0 @@ -/* - stdsoap2.h 2.7.15 - - gSOAP runtime engine - -gSOAP XML Web services tools -Copyright (C) 2000-2009, Robert van Engelen, Genivia Inc., All Rights Reserved. -This part of the software is released under ONE of the following licenses: -GPL, or the gSOAP public license, or Genivia's license for commercial use. --------------------------------------------------------------------------------- -Contributors: - -Wind River Systems, Inc., for the following additions - - vxWorks compatible --------------------------------------------------------------------------------- -gSOAP public license. - -The contents of this file are subject to the gSOAP Public License Version 1.3 -(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.cs.fsu.edu/~engelen/soaplicense.html -Software distributed under the License is distributed on an "AS IS" basis, -WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License -for the specific language governing rights and limitations under the License. - -The Initial Developer of the Original Code is Robert A. van Engelen. -Copyright (C) 2000-2009, Robert van Engelen, Genivia Inc., All Rights Reserved. --------------------------------------------------------------------------------- -GPL license. - -This program is free software; you can redistribute it and/or modify it under -the terms of the GNU General Public License as published by the Free Software -Foundation; either version 2 of the License, or (at your option) any later -version. - -This program is distributed in the hope that it will be useful, but WITHOUT ANY -WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A -PARTICULAR PURPOSE. See the GNU General Public License for more details. - -You should have received a copy of the GNU General Public License along with -this program; if not, write to the Free Software Foundation, Inc., 59 Temple -Place, Suite 330, Boston, MA 02111-1307 USA - -Author contact information: -engelen@genivia.com / engelen@acm.org - -This program is released under the GPL with the additional exemption that -compiling, linking, and/or using OpenSSL is allowed. --------------------------------------------------------------------------------- -A commercial use license is available from Genivia, Inc., contact@genivia.com --------------------------------------------------------------------------------- -*/ - -#ifdef WITH_SOAPDEFS_H -# include "soapdefs.h" /* include user-defined stuff */ -#endif - -#ifndef _THREAD_SAFE -# define _THREAD_SAFE -#endif - -#ifndef OPENSERVER -# ifndef _REENTRANT -# define _REENTRANT -# endif -#endif - -#ifndef SOAP_FMAC1 /* stdsoap2.h declaration macro */ -# define SOAP_FMAC1 -#endif - -#ifndef SOAP_FMAC2 /* stdsoap2.h declaration macro */ -# define SOAP_FMAC2 -#endif - -#ifndef SOAP_FMAC3 /* (de)serializer declaration macro */ -# define SOAP_FMAC3 -#endif - -#ifndef SOAP_FMAC3S /* string converter for (de)serializer declaration macro */ -# define SOAP_FMAC3S SOAP_FMAC3 -#endif - -#ifndef SOAP_FMAC4 /* (de)serializer declaration macro */ -# define SOAP_FMAC4 -#endif - -#ifndef SOAP_FMAC4S /* string converter for (de)serializer declaration macro */ -# define SOAP_FMAC4S SOAP_FMAC4 -#endif - -#ifndef SOAP_FMAC5 /* stub/skeleton declaration macro */ -# define SOAP_FMAC5 -#endif - -#ifndef SOAP_FMAC6 /* stub/skeleton declaration macro */ -# define SOAP_FMAC6 -#endif - -#ifndef SOAP_CMAC /* class declaration macro */ -# define SOAP_CMAC -#endif - -#ifndef SOAP_NMAC /* namespace table declaration macro */ -# define SOAP_NMAC -#endif - -#ifndef SOAP_SOURCE_STAMP -# define SOAP_SOURCE_STAMP(str) -#endif - -/* gSOAP 2.7.4 and higher: fast look-aside buffering is stable */ -#ifndef WITH_FAST -# define WITH_FAST -#endif - -/* gSOAP 2.7.15 and higher: always retain CDATA in literal XML, unless WITH_LEAN or WITH_NOCDATA */ -#ifndef WITH_LEAN -# ifndef WITH_NOCDATA -# ifndef WITH_CDATA -# define WITH_CDATA -# endif -# endif -#endif - -#ifdef WITH_LEANER -# ifndef WITH_LEAN -# define WITH_LEAN -# endif -#endif - -#ifdef WITH_LEAN -# ifdef WITH_COOKIES -# error "Cannot build WITH_LEAN code WITH_COOKIES enabled" -# endif -#endif - -#ifndef STDSOAP_H -#define STDSOAP_H - -#if defined(__vxworks) || defined(__VXWORKS__) -# ifndef VXWORKS -# define VXWORKS -# endif -#endif - -#ifdef _WIN32 -# ifndef WIN32 -# define WIN32 -# endif -#endif - -#ifdef _WIN32_WCE -# ifndef UNDER_CE -# define UNDER_CE _WIN32_WCE -# endif -#endif - -#ifdef UNDER_CE -# ifndef WIN32 -# define WIN32 -# endif -#endif - -#ifdef __BORLANDC__ -# ifdef __WIN32__ -# ifndef WIN32 -# define WIN32 -# endif -# endif -#endif - -#ifdef __CYGWIN__ -# ifndef CYGWIN -# define CYGWIN -# endif -#endif - -#ifdef __SYMBIAN32__ -# define SYMBIAN -# undef WIN32 -#endif - -#if defined(__palmos__) || defined(PALM_GCC) || defined(__PALMOS_TRAPS__) -# ifndef PALM -# define PALM -# endif -#endif - -#if defined(__hpux) -# ifndef HP_UX -# define HP_UX -# endif -#endif - -#if defined(__digital__) && defined(__unix__) -# ifndef TRU64 -# define TRU64 -# endif -#endif - -#ifdef __MVS__ -# ifndef OS390 -# define OS390 -# endif -#endif - -#ifdef HAVE_CONFIG_H -# include "config.h" -# if defined(WITH_OPENSSL) -# ifndef HAVE_OPENSSL_SSL_H -# undef WITH_OPENSSL -# endif -# endif -# if defined(WITH_ZLIB) || defined(WITH_GZIP) -# ifndef HAVE_ZLIB_H -# undef WITH_ZLIB -# undef WITH_GZIP -# endif -# endif -#else -# if defined(UNDER_CE) -# define WITH_LEAN -# define HAVE_SSCANF -# elif defined(WIN32) -# define HAVE_STRRCHR -# define HAVE_STRTOD -# define HAVE_SSCANF -# define HAVE_STRTOL -# define HAVE_STRTOUL -# define HAVE_SYS_TIMEB_H -# define HAVE_FTIME -# define HAVE_GMTIME -# define HAVE_WCTOMB -# define HAVE_MBTOWC -# define SOAP_LONG_FORMAT "%I64d" -# define SOAP_ULONG_FORMAT "%I64u" -# elif defined(CYGWIN) -# define HAVE_POLL -# define HAVE_STRRCHR -# define HAVE_STRTOD -# define HAVE_SSCANF -# define HAVE_STRTOL -# define HAVE_STRTOUL -# define HAVE_SYS_TIMEB_H -# define HAVE_FTIME -# define HAVE_RAND_R -# define HAVE_GMTIME_R -# define HAVE_LOCALTIME_R -# define HAVE_WCTOMB -# define HAVE_MBTOWC -# elif defined(__APPLE__) -# define HAVE_POLL -# define HAVE_STRRCHR -# define HAVE_STRTOD -# define HAVE_SSCANF -# define HAVE_STRTOD_L -# define HAVE_SSCANF_L -# define HAVE_SPRINTF_L -# define HAVE_STRTOL -# define HAVE_STRTOUL -# define HAVE_RAND_R -# define HAVE_GMTIME_R -# define HAVE_LOCALTIME_R -# define HAVE_TIMEGM -# define HAVE_WCTOMB -# define HAVE_MBTOWC -# elif defined(_AIX43) -# define HAVE_STRRCHR -# define HAVE_STRTOD -# define HAVE_SSCANF -# define HAVE_STRTOL -# define HAVE_STRTOUL -# define HAVE_SYS_TIMEB_H -# define HAVE_FTIME -# define HAVE_RAND_R -# define HAVE_GMTIME_R -# define HAVE_LOCALTIME_R -# define HAVE_WCTOMB -# define HAVE_MBTOWC -# elif defined(_AIX41) -# define HAVE_STRRCHR -# define HAVE_STRTOD -# define HAVE_SSCANF -# define HAVE_STRTOL -# define HAVE_STRTOUL -# define HAVE_SYS_TIMEB_H -# define HAVE_WCTOMB -# define HAVE_MBTOWC -# elif defined(HP_UX) -# define HAVE_STRRCHR -# define HAVE_STRTOD -# define HAVE_SSCANF -# define HAVE_STRTOL -# define HAVE_STRTOUL -# define HAVE_SYS_TIMEB_H -# define HAVE_FTIME -# define HAVE_RAND_R -# define HAVE_GMTIME_R -# define HAVE_LOCALTIME_R -# define HAVE_WCTOMB -# define HAVE_MBTOWC -# elif defined(FREEBSD) || defined(__FreeBSD__) || defined(OPENBSD) -# define HAVE_POLL -# define HAVE_STRRCHR -# define HAVE_STRTOD -# define HAVE_SSCANF -# define HAVE_STRTOD_L -# define HAVE_SSCANF_L -# define HAVE_SPRINTF_L -# define HAVE_STRTOL -# define HAVE_STRTOUL -# define HAVE_STRTOLL -# define HAVE_STRTOULL -# define HAVE_GETTIMEOFDAY -# define HAVE_RAND_R -# define HAVE_GMTIME_R -# define HAVE_LOCALTIME_R -# define HAVE_WCTOMB -# define HAVE_MBTOWC -# define SOAP_LONG_FORMAT "%qd" -# define SOAP_ULONG_FORMAT "%qu" -# elif defined(__VMS) -# define HAVE_STRRCHR -# define HAVE_STRTOD -# define HAVE_SSCANF -# define HAVE_STRTOL -# define HAVE_STRTOUL -# define HAVE_SYS_TIMEB_H -# define HAVE_FTIME -# define HAVE_RAND_R -# define HAVE_GMTIME_R -# define HAVE_LOCALTIME_R -# define HAVE_WCTOMB -# define HAVE_MBTOWC -# elif defined(__GLIBC__) || defined(__GNU__) -# define HAVE_POLL -# define HAVE_STRRCHR -# define HAVE_STRTOD -# define HAVE_SSCANF -# define HAVE_STRTOD_L -# define HAVE_SSCANF_L -# define HAVE_SPRINTF_L -# define HAVE_STRTOL -# define HAVE_STRTOUL -# define HAVE_STRTOLL -# define HAVE_STRTOULL -# define HAVE_SYS_TIMEB_H -# define HAVE_FTIME -# define HAVE_RAND_R -# define HAVE_GMTIME_R -# define HAVE_LOCALTIME_R -# define HAVE_TIMEGM -# define HAVE_WCTOMB -# define HAVE_MBTOWC -# define HAVE_ISNAN -# elif defined(TRU64) -# define HAVE_STRRCHR -# define HAVE_STRTOD -# define HAVE_SSCANF -# define HAVE_STRTOL -# define HAVE_STRTOUL -# define HAVE_GETTIMEOFDAY -# define HAVE_SYS_TIMEB_H -# define HAVE_RAND_R -# define HAVE_GMTIME_R -# define HAVE_LOCALTIME_R -# define __USE_STD_IOSTREAM -# define HAVE_WCTOMB -# define HAVE_MBTOWC -# define SOAP_LONG_FORMAT "%ld" -# define SOAP_ULONG_FORMAT "%lu" -# elif defined(MAC_CARBON) -# define WITH_NOIO -# define HAVE_STRRCHR -# define HAVE_STRTOD -# define HAVE_SSCANF -# define HAVE_STRTOD_L -# define HAVE_SSCANF_L -# define HAVE_SPRINTF_L -# define HAVE_STRTOL -# define HAVE_STRTOUL -# define HAVE_FTIME -# define HAVE_RAND_R -# define HAVE_GETHOSTBYNAME_R -# define HAVE_GMTIME_R -# define HAVE_LOCALTIME_R -# define HAVE_WCTOMB -# define HAVE_MBTOWC -# elif defined(PALM) -# define WITH_LEAN -# define HAVE_STRTOD /* strtod() is defined in palmFunctions.h */ -# include /* Needs to be included before unix headers */ -# include -# define IGNORE_STDIO_STUBS -# include -# define O_NONBLOCK FNONBIO -# include -# include "palmFunctions.h" -# elif defined(SYMBIAN) -# define WITH_LEAN -# define WITH_NONAMESPACES -# define HAVE_STRTOD /* use STRTOD since sscanf doesn't seem to work */ -# include -# include -# elif defined(VXWORKS) -# ifdef _WRS_KERNEL -# define _POSIX_THREADS 1 -# endif -# define HAVE_STRRCHR -# define HAVE_STRTOD -# define HAVE_SSCANF -# define HAVE_STRTOL -# define HAVE_STRTOUL -# define HAVE_GMTIME -# define HAVE_LOCALTIME -# define HAVE_MKTIME -# elif defined(OS390) -# define HAVE_STRRCHR -# define HAVE_STRTOD -# define HAVE_SSCANF -# define HAVE_STRTOL -# define HAVE_STRTOUL -# define HAVE_SYS_TIMEB_H -# define HAVE_FTIME -# define HAVE_RAND_R -# define HAVE_GMTIME_R -# define HAVE_LOCALTIME_R -# define HAVE_WCTOMB -# define HAVE_MBTOWC -# elif defined(AS400) -# define HAVE_STRRCHR -# define HAVE_STRTOD -# define HAVE_SSCANF -# define HAVE_STRTOL -# define HAVE_STRTOUL -# define HAVE_SYS_TIMEB_H -# define HAVE_FTIME -# define HAVE_RAND_R -# define HAVE_GMTIME_R -# define HAVE_LOCALTIME_R -# define HAVE_WCTOMB -# define HAVE_MBTOWC -# elif defined(__QNX__) || defined(QNX) -/* QNX does not have a working version of strtof */ -# undef HAVE_STRTOF -# define HAVE_POLL -# define HAVE_STRRCHR -# define HAVE_STRTOD -# define HAVE_SSCANF -# define HAVE_STRTOL -# define HAVE_STRTOUL -# define HAVE_SYS_TIMEB_H -# define HAVE_FTIME -# define HAVE_RAND_R -# define HAVE_GETHOSTBYNAME_R -# define HAVE_GMTIME_R -# define HAVE_LOCALTIME_R -# define HAVE_WCTOMB -# define HAVE_MBTOWC -# define LONG64 long -# define ULONG64 unsigned LONG64 -# define SOAP_LONG_FORMAT "%ld" -# define SOAP_ULONG_FORMAT "%lu" -# else -/* Default asumptions on supported functions */ -# define HAVE_STRRCHR -# define HAVE_STRTOD -# define HAVE_SSCANF -# define HAVE_STRTOL -# define HAVE_STRTOUL -# define HAVE_SYS_TIMEB_H -# define HAVE_FTIME -# define HAVE_RAND_R -# define HAVE_GETHOSTBYNAME_R -# define HAVE_GMTIME_R -# define HAVE_LOCALTIME_R -# define HAVE_WCTOMB -# define HAVE_MBTOWC -# endif -#endif - -/* native Win and HP-UX compilers don't like empty structs */ -#if defined(WIN32) || defined(HP_UX) -# define WITH_NOEMPTYSTRUCT -#endif - -#ifdef HP_UX -# undef HAVE_STRTOLL -# undef HAVE_STRTOULL -#endif - -/* older OpenVMS TCP/IP stacks cannot handle 65536 bytes */ -#ifdef __VMS -# ifndef SOAP_BUFLEN -# define SOAP_BUFLEN (65535) -# endif -#endif - -#ifdef WITH_C_LOCALE -# include -#else -# undef HAVE_STRTOF_L -# undef HAVE_STRTOD_L -# undef HAVE_SSCANF_L -# undef HAVE_SPRINTF_L -#endif - -#ifndef WITH_NOSTDLIB -# include -# ifndef PALM -# include -# include -# endif -# include -# include -#endif - -#ifdef HAVE_POLL -# include -#endif - -#if defined(__cplusplus) && !defined(WITH_LEAN) && !defined(WITH_COMPAT) -# include -# include -#endif - -#ifdef WITH_NOHTTP -# ifndef WITH_NOIO -# define WITH_NOIO -# undef WITH_COOKIES -# endif -#endif - -/* Suggestion when SOAP_FD_EXCEEDED error occurs: - Some systems allow increasing FD_SETSIZE before including sys/types.h: -#define FD_SETSIZE (2048) -*/ - -#ifndef UNDER_CE -# ifndef PALM -# ifndef WITH_NOIO -# include -# include -# endif -# ifndef WITH_LEAN -# ifdef HAVE_SYS_TIMEB_H -# include /* for ftime() */ -# endif -# include -# endif -# endif -#endif - -#ifdef OPENSERVER -# include -# include -# include - extern int h_errno; -#endif - -#ifndef WITH_NOIO -# ifndef WIN32 -# ifndef PALM -# include -# ifdef VXWORKS -# include -# include -# ifndef _WRS_KERNEL -# include -# endif -# else -# ifndef SYMBIAN -# include -# endif -# endif -# ifdef SUN_OS -# include /* SUN */ -# include /* SUN < 2.8 (?) */ -# endif -# ifdef VXWORKS -# ifdef _WRS_KERNEL -# include -# endif -# else -# include -# endif -# include -# ifdef OS390 -# include -# else -# include /* TCP_NODELAY */ -# endif -# include -# endif -# endif -#endif - -#ifdef WIN32 -# define SOAP_WINSOCKINT int -#else -# define SOAP_WINSOCKINT size_t -#endif - -#ifdef WIN32 -# ifndef UNDER_CE -# include -# include -# endif -# ifdef WITH_IPV6 -# include /* Visual Studio 2005 users: you must install the Platform SDK (R2) */ -# include -# include -# define SOAP_GAI_STRERROR gai_strerrorA -# else -# ifndef __BORLANDC__ -# include /* Visual Studio 2005 users: you must install the Platform SDK (R2) */ -/* # include */ /* Alternative: use winsock2 (not available with eVC) */ -# else -# include /* Borland C */ -# endif -# endif -#else -# ifdef VXWORKS -# include -# include -# include -# endif -# ifndef WITH_NOIO -# ifndef PALM -# include -# include -# include -# include -# ifdef _AIX41 -# include -# endif -# endif -# endif -#endif - -#ifdef WITH_FASTCGI -# include -#endif - -#ifdef WITH_OPENSSL -# define OPENSSL_NO_KRB5 -# include -# include -# include -# include -# include -# ifndef ALLOW_OLD_VERSIONS -# if (OPENSSL_VERSION_NUMBER < 0x00905100L) -# error "Must use OpenSSL 0.9.6 or later" -# endif -# endif -#endif - -#ifdef WITH_GZIP -# ifndef WITH_ZLIB -# define WITH_ZLIB -# endif -#endif - -#ifdef WITH_CASEINSENSITIVETAGS -# define SOAP_STRCMP soap_tag_cmp /* case insensitve XML element/attribute names */ -#else -# define SOAP_STRCMP strcmp /* case sensitive XML element/attribute names */ -#endif - -#ifdef WITH_ZLIB -# include -#endif - -#ifndef WITH_NOSTDLIB -# ifndef PALM -# include /* for isnan() */ -# endif -#endif - -/* #define DEBUG */ /* Uncomment to debug sending (in file SENT.log) receiving (in file RECV.log) and messages (in file TEST.log) */ - -#ifdef __cplusplus -extern "C" { -#endif - -/* Portability: define SOAP_SOCKLEN_T */ -#if defined(_AIX) -# if defined(_AIX43) -# define SOAP_SOCKLEN_T socklen_t -# else -# define SOAP_SOCKLEN_T int -# endif -#elif defined(SOCKLEN_T) -# define SOAP_SOCKLEN_T SOCKLEN_T -#elif defined(__socklen_t_defined) || defined(_SOCKLEN_T) || defined(CYGWIN) || defined(FREEBSD) || defined(__FreeBSD__) || defined(OPENBSD) || defined(__QNX__) || defined(QNX) || defined(OS390) -# define SOAP_SOCKLEN_T socklen_t -#elif defined(IRIX) || defined(WIN32) || defined(__APPLE__) || defined(HP_UX) || defined(SUN_OS) || defined(OPENSERVER) || defined(TRU64) || defined(VXWORKS) -# define SOAP_SOCKLEN_T int -#else -# define SOAP_SOCKLEN_T size_t -#endif - -#ifndef SOAP_SOCKET -# ifdef WIN32 -# define SOAP_SOCKET SOCKET -# define soap_closesocket(n) closesocket(n) -# else -# define SOAP_SOCKET int -# define soap_closesocket(n) close(n) -# endif -#endif - -#define SOAP_INVALID_SOCKET ((SOAP_SOCKET)-1) -#define soap_valid_socket(n) ((n) != SOAP_INVALID_SOCKET) - -#ifndef SOAP_GAI_STRERROR -# define SOAP_GAI_STRERROR gai_strerror -#endif - -#ifndef FD_SETSIZE -# define FD_SETSIZE (1024) -#endif - -#if defined(SYMBIAN) -# define LONG64 long -# define ULONG64 unsigned LONG64 -#elif !defined(WIN32) || defined(CYGWIN) || defined(__GLIBC__) || defined(__GNU__) -# ifndef LONG64 -# if defined(HAVE_STDINT_H) -# include -# define LONG64 int64_t -# define ULONG64 uint64_t -# elif defined(__GLIBC__) -# include -# if (__WORDSIZE == 64) -# define LONG64 int64_t -# define ULONG64 uint64_t -# ifndef SOAP_LONG_FORMAT -# define SOAP_LONG_FORMAT "%ld" -# endif -# ifndef SOAP_ULONG_FORMAT -# define SOAP_ULONG_FORMAT "%lu" -# endif -# else -# define LONG64 long long -# define ULONG64 unsigned LONG64 -# endif -# else -# define LONG64 long long -# define ULONG64 unsigned LONG64 -# endif -# endif -#elif defined(UNDER_CE) -# define LONG64 __int64 -# define ULONG64 unsigned LONG64 -#elif defined(__BORLANDC__) -# define LONG64 __int64 -# define ULONG64 unsigned LONG64 -#endif - -#ifndef SOAP_LONG_FORMAT -# define SOAP_LONG_FORMAT "%lld" /* printf format for 64 bit ints */ -#endif - -#ifndef SOAP_ULONG_FORMAT -# define SOAP_ULONG_FORMAT "%llu" /* printf format for unsigned 64 bit ints */ -#endif - -#if defined(WIN32) && !defined(CYGWIN) -# define soap_int32 __int32 -#elif defined(SYMBIAN) -# define soap_int32 long -#elif defined(PALM) -# define soap_int32 Int32 -#elif defined(_AIX) -# if defined(_AIX43) -# define soap_int32 int32_t -# else -# define soap_int32 signed int -# endif -#else -# define soap_int32 int32_t -#endif - -#ifdef WIN32 -# define SOAP_ERANGE ERANGE -# define SOAP_EINTR WSAEINTR -# define SOAP_EAGAIN WSAEWOULDBLOCK -# define SOAP_EWOULDBLOCK WSAEWOULDBLOCK -# define SOAP_EINPROGRESS WSAEINPROGRESS -# define SOAP_EADDRINUSE WSAEADDRINUSE -#else -# define SOAP_ERANGE ERANGE -# define SOAP_EINTR EINTR -# define SOAP_EAGAIN EAGAIN -# define SOAP_EADDRINUSE EADDRINUSE -# ifdef SYMBIAN -# define SOAP_EWOULDBLOCK 9898 -# define SOAP_EINPROGRESS 9899 -# else -# define SOAP_EWOULDBLOCK EWOULDBLOCK -# define SOAP_EINPROGRESS EINPROGRESS -# endif -#endif - -#ifdef WIN32 -# ifdef UNDER_CE -# define soap_errno GetLastError() -# define soap_socket_errno(s) GetLastError() -# define soap_reset_errno SetLastError(0) -# else -# define soap_errno GetLastError() -# define soap_socket_errno(s) WSAGetLastError() -# define soap_reset_errno SetLastError(0) -# endif -#else -# ifndef WITH_NOIO -# define soap_errno errno -# define soap_socket_errno(s) errno -# define soap_reset_errno (errno = 0) -# else -# define soap_errno 0 -# define soap_socket_errno(s) 0 -# define soap_reset_errno -# endif -#endif - -#ifndef SOAP_BUFLEN -# if !defined(WITH_LEAN) || defined(WITH_UDP) -# define SOAP_BUFLEN (65536) /* buffer length for socket packets, also used by gethostbyname_r and UDP messages, so don't make this too small */ -# else -# define SOAP_BUFLEN (2048) /* lean size */ -# endif -#endif -#ifndef SOAP_LABLEN -# define SOAP_LABLEN (256) /* initial look-aside buffer length */ -#endif -#ifndef SOAP_PTRBLK -# define SOAP_PTRBLK (32) /* block allocation for pointer hash table chains */ -#endif -#ifndef SOAP_PTRHASH -# ifndef WITH_LEAN -# define SOAP_PTRHASH (1024) /* size of pointer analysis hash table (must be power of 2) */ -# else -# define SOAP_PTRHASH (32) -# endif -#endif -#ifndef SOAP_IDHASH -# ifndef WITH_LEAN -# define SOAP_IDHASH (1999) /* prime size of hash table for parsed id/ref */ -# else -# define SOAP_IDHASH (19) /* 19, 199 */ -# endif -#endif -#ifndef SOAP_BLKLEN -# ifndef WITH_LEAN -# define SOAP_BLKLEN (256) /* size of blocks to collect long strings and XML attributes */ -# else -# define SOAP_BLKLEN (32) -# endif -#endif -#ifndef SOAP_TAGLEN -# ifndef WITH_LEAN -# define SOAP_TAGLEN (1024) /* maximum length of XML element tag/attribute name or host/path name + 1 */ -# else -# define SOAP_TAGLEN (64) -# endif -#endif -#ifndef SOAP_HDRLEN -# ifndef WITH_LEAN -# define SOAP_HDRLEN (8192) /* maximum length of HTTP header line (must be >4096 to read cookies) */ -# else -# define SOAP_HDRLEN (1024) -# endif -#endif -#ifndef SOAP_MAXDIMS -# ifndef WITH_LEAN -# define SOAP_MAXDIMS (16) /* maximum array dimensions (array nestings) must be less than 64 to protect soap->tmpbuf */ -# else -# define SOAP_MAXDIMS (4) -# endif -#endif - -#ifndef SOAP_MAXLOGS -# define SOAP_MAXLOGS (3) /* max number of debug logs per struct soap environment */ -# define SOAP_INDEX_RECV (0) -# define SOAP_INDEX_SENT (1) -# define SOAP_INDEX_TEST (2) -#endif - -/* Max iterations in soap_serve() to keep server connection alive */ -#ifndef SOAP_MAXKEEPALIVE -# define SOAP_MAXKEEPALIVE (100) -#endif - -/* Trusted max size of inbound SOAP array for compound array allocation. - Increase if necessary to allow larger arrays. -*/ -#ifndef SOAP_MAXARRAYSIZE -# define SOAP_MAXARRAYSIZE (1000000) -#endif - -#ifdef VXWORKS -# ifdef __INCmathh -# include -# ifndef HAVE_ISNAN -# define HAVE_ISNAN -# endif -# define soap_isnan(num) isNan(num) -# endif -#endif - -#ifdef WIN32 -# include -# ifndef HAVE_ISNAN -# define HAVE_ISNAN -# endif -# define soap_isnan(num) _isnan(num) -#endif - -#ifdef SUN_OS -# define HAVE_ISNAN -#endif - -#ifdef __APPLE__ -# ifdef __cplusplus -# ifndef isnan -extern "C" int isnan(double); -# endif -# endif -# define HAVE_ISNAN -#endif - -#if !defined(HAVE_ISNAN) && (defined(_MATH_H) || defined(_MATH_INCLUDED)) -# define HAVE_ISNAN -#endif - -extern const struct soap_double_nan { unsigned int n1, n2; } soap_double_nan; - -#ifdef VXWORKS -# ifndef FLT_MAX -# define FLT_MAX _ARCH_FLT_MAX -# endif -# ifndef DBL_MAX -# define DBL_MAX _ARCH_DBL_MAX -# endif -#endif - -#ifndef FLT_NAN -# define FLT_NAN (*(float*)(void*)&soap_double_nan) -#endif - -#ifndef FLT_PINFTY -# if defined(FLT_MAX) -# define FLT_PINFTY FLT_MAX -# elif defined(HUGE_VALF) -# define FLT_PINFTY (float)HUGE_VALF -# elif defined(HUGE_VAL) -# define FLT_PINFTY (float)HUGE_VAL -# elif defined(FLOAT_MAX) -# define FLT_PINFTY FLOAT_MAX -# else -# define FLT_PINFTY (3.40282347e+38F) -# endif -#endif - -#ifndef FLT_NINFTY -# define FLT_NINFTY (-FLT_PINFTY) -#endif - -#ifndef DBL_NAN -# define DBL_NAN (*(double*)(void*)&soap_double_nan) -#endif - -#ifndef DBL_PINFTY -# if defined(DBL_MAX) -# define DBL_PINFTY DBL_MAX -# elif defined(HUGE_VALF) -# define DBL_PINFTY (double)HUGE_VALF -# elif defined(HUGE_VAL) -# define DBL_PINFTY (double)HUGE_VAL -# elif defined(DOUBLE_MAX) -# define DBL_PINFTY DOUBLE_MAX -# else -# define DBL_PINFTY (1.7976931348623157e+308) -# endif -#endif - -#ifndef DBL_NINFTY -# define DBL_NINFTY (-DBL_PINFTY) -#endif - -#ifndef soap_isnan -# ifdef HAVE_ISNAN -# define soap_isnan(n) isnan(n) -# else -# define soap_isnan(n) (0) -# endif -#endif - -#define soap_ispinfd(n) ((n) >= DBL_PINFTY) -#define soap_ispinff(n) ((n) >= FLT_PINFTY) -#define soap_isninfd(n) ((n) <= DBL_NINFTY) -#define soap_isninff(n) ((n) <= FLT_NINFTY) - -/* gSOAP error codes */ - -#define SOAP_EOF EOF -#define SOAP_ERR EOF -#define SOAP_OK 0 -#define SOAP_CLI_FAULT 1 -#define SOAP_SVR_FAULT 2 -#define SOAP_TAG_MISMATCH 3 -#define SOAP_TYPE 4 -#define SOAP_SYNTAX_ERROR 5 -#define SOAP_NO_TAG 6 -#define SOAP_IOB 7 -#define SOAP_MUSTUNDERSTAND 8 -#define SOAP_NAMESPACE 9 -#define SOAP_USER_ERROR 10 -#define SOAP_FATAL_ERROR 11 -#define SOAP_FAULT 12 -#define SOAP_NO_METHOD 13 -#define SOAP_NO_DATA 14 -#define SOAP_GET_METHOD 15 -#define SOAP_PUT_METHOD 16 -#define SOAP_DEL_METHOD 17 -#define SOAP_HEAD_METHOD 18 -#define SOAP_HTTP_METHOD 19 -#define SOAP_EOM 20 -#define SOAP_MOE 21 -#define SOAP_HDR 22 -#define SOAP_NULL 23 -#define SOAP_DUPLICATE_ID 24 -#define SOAP_MISSING_ID 25 -#define SOAP_HREF 26 -#define SOAP_UDP_ERROR 27 -#define SOAP_TCP_ERROR 28 -#define SOAP_HTTP_ERROR 29 -#define SOAP_SSL_ERROR 30 -#define SOAP_ZLIB_ERROR 31 -#define SOAP_DIME_ERROR 32 -#define SOAP_DIME_HREF 33 -#define SOAP_DIME_MISMATCH 34 -#define SOAP_DIME_END 35 -#define SOAP_MIME_ERROR 36 -#define SOAP_MIME_HREF 37 -#define SOAP_MIME_END 38 -#define SOAP_VERSIONMISMATCH 39 -#define SOAP_PLUGIN_ERROR 40 -#define SOAP_DATAENCODINGUNKNOWN 41 -#define SOAP_REQUIRED 42 -#define SOAP_PROHIBITED 43 -#define SOAP_OCCURS 44 -#define SOAP_LENGTH 45 -#define SOAP_FD_EXCEEDED 46 - -#define soap_xml_error_check(e) ((e) == SOAP_TAG_MISMATCH || (e) == SOAP_NO_TAG || (e) == SOAP_SYNTAX_ERROR || (e) == SOAP_NAMESPACE || (e) == SOAP_DUPLICATE_ID || (e) == SOAP_MISSING_ID || (e) == SOAP_REQUIRED || (e) == SOAP_PROHIBITED || (e) == SOAP_OCCURS || (e) == SOAP_LENGTH || (e) == SOAP_NULL || (e) == SOAP_HREF) -#define soap_soap_error_check(e) ((e) == SOAP_CLI_FAULT || (e) == SOAP_SVR_FAULT || (e) == SOAP_VERSIONMISMATCH || (e) == SOAP_MUSTUNDERSTAND || (e) == SOAP_FAULT || (e) == SOAP_NO_METHOD) -#define soap_tcp_error_check(e) ((e) == SOAP_EOF || (e) == SOAP_TCP_ERROR) -#define soap_ssl_error_check(e) ((e) == SOAP_SSL_ERROR) -#define soap_zlib_error_check(e) ((e) == SOAP_ZLIB_ERROR) -#define soap_http_error_check(e) ((e) == SOAP_HTTP_ERROR || (e) == SOAP_NO_DATA || ((e) >= SOAP_GET_METHOD && (e) <= SOAP_HTTP_METHOD) || ((e) >= 100 && (e) < 600)) - -/* gSOAP HTTP response status codes 100 to 599 are reserved */ - -/* Codes 600 to 999 are user definable */ - -/* Exceptional gSOAP HTTP server response status codes >= 1000 */ - -#define SOAP_STOP 1000 /* No HTTP response */ -#define SOAP_FORM 1001 /* Form request/response */ -#define SOAP_HTML 1002 /* Custom HTML response */ -#define SOAP_FILE 1003 /* Custom file-based response */ - -/* gSOAP HTTP method codes (client) */ - -#define SOAP_POST 2000 /* POST request */ -#define SOAP_POST_FILE 2001 /* Custom file-based POST request */ -#define SOAP_GET 2002 /* GET request */ - -/* gSOAP DIME */ - -#define SOAP_DIME_CF 0x01 -#define SOAP_DIME_ME 0x02 -#define SOAP_DIME_MB 0x04 -#define SOAP_DIME_VERSION 0x08 /* DIME version 1 */ -#define SOAP_DIME_MEDIA 0x10 -#define SOAP_DIME_ABSURI 0x20 - -/* gSOAP ZLIB */ - -#define SOAP_ZLIB_NONE 0x00 -#define SOAP_ZLIB_DEFLATE 0x01 -#define SOAP_ZLIB_INFLATE 0x02 -#define SOAP_ZLIB_GZIP 0x02 - -/* gSOAP transport, connection, and content encoding modes */ - -typedef soap_int32 soap_mode; - -#define SOAP_IO 0x00000003 /* IO mask */ -#define SOAP_IO_FLUSH 0x00000000 /* flush output immediately, no buffering */ -#define SOAP_IO_BUFFER 0x00000001 /* buffer output in packets of size SOAP_BUFLEN */ -#define SOAP_IO_STORE 0x00000002 /* store entire output to determine length for transport */ -#define SOAP_IO_CHUNK 0x00000003 /* use HTTP chunked transfer AND buffer packets */ - -#define SOAP_IO_UDP 0x00000004 /* TCP or UDP */ - -#define SOAP_IO_LENGTH 0x00000008 /* calc message length (internal) */ -#define SOAP_IO_KEEPALIVE 0x00000010 /* keep connection alive */ - -#define SOAP_ENC_LATIN 0x00000020 /* accept iso-8859-1 encoding */ -#define SOAP_ENC_XML 0x00000040 /* plain XML encoding, no HTTP header */ -#define SOAP_ENC_DIME 0x00000080 -#define SOAP_ENC_MIME 0x00000100 -#define SOAP_ENC_MTOM 0x00000200 -#define SOAP_ENC_ZLIB 0x00000400 -#define SOAP_ENC_SSL 0x00000800 - -#define SOAP_ENC 0x00000FFF /* IO and ENC mask */ - -#define SOAP_XML_STRICT 0x00001000 /* apply strict validation */ -#define SOAP_XML_INDENT 0x00002000 /* emit indented XML */ -#define SOAP_XML_DEFAULTNS 0x00004000 /* emit xmlns="..." namesp. */ -#define SOAP_XML_CANONICAL 0x00008000 /* EXC C14N canonical XML */ -#define SOAP_XML_TREE 0x00010000 /* emit XML tree (no id/ref) */ -#define SOAP_XML_GRAPH 0x00020000 /* see DOM manual */ -#define SOAP_XML_NIL 0x00040000 /* serialize NULLs as xsi:nil */ -#define SOAP_XML_DOM 0x00080000 - -#define SOAP_C_NOIOB 0x00100000 /* don't fault on array index out of bounds (just ignore) */ -#define SOAP_C_UTFSTRING 0x00200000 /* (de)serialize strings with UTF8 content */ -#define SOAP_C_MBSTRING 0x00400000 /* (de)serialize strings with multi-byte content */ -#define SOAP_C_NILSTRING 0x00800000 /* serialize empty strings as nil (omitted) */ - -#define SOAP_DOM_TREE 0x01000000 -#define SOAP_DOM_NODE 0x02000000 -#define SOAP_DOM_ASIS 0x04000000 - -#define SOAP_MIME_POSTCHECK 0x10000000 /* MIME flag (internal) */ - -#define SOAP_XML_SEC 0x80000000 /* reserved for WS security */ - -/* WITH_XMLNS backward compatibility: always use XML default namespaces */ -#ifdef WITH_XMLNS -# define SOAP_IO_DEFAULT (SOAP_IO_FLUSH | SOAP_XML_DEFAULTNS) -#else -# define SOAP_IO_DEFAULT SOAP_IO_FLUSH -#endif - -/* SSL client/server authentication settings */ - -#define SOAP_SSL_NO_AUTHENTICATION 0x00 /* for testing purposes */ -#define SOAP_SSL_REQUIRE_SERVER_AUTHENTICATION 0x01 /* client requires server to authenticate */ -#define SOAP_SSL_REQUIRE_CLIENT_AUTHENTICATION 0x02 /* server requires client to authenticate */ -#define SOAP_SSL_SKIP_HOST_CHECK 0x04 /* client does not check the common name of the host in certificate */ -#define SOAP_SSL_ALLOW_EXPIRED_CERTIFICATE 0x08 /* client does not check the expiration date of the host certificate */ -#define SOAP_SSL_NO_DEFAULT_CA_PATH 0x10 /* don't use default_verify_paths */ -#define SOAP_SSL_RSA 0x20 /* use RSA */ -#define SOAP_SSLv3 0x40 /* SSL v3 only */ -#define SOAP_TLSv1 0x80 /* TLS v1 only */ -#define SOAP_SSLv3_TLSv1 0x00 /* SSL v3 and TLS v1 support by default */ - -#define SOAP_SSL_DEFAULT (SOAP_SSL_REQUIRE_SERVER_AUTHENTICATION | SOAP_SSLv3_TLSv1) - -/* state */ - -#define SOAP_NONE 0 -#define SOAP_INIT 1 -#define SOAP_COPY 2 - -#define soap_check_state(soap) (!(soap) || ((soap)->state != SOAP_INIT && (soap)->state != SOAP_COPY)) - -/* part */ - -#define SOAP_BEGIN 0 -#define SOAP_IN_ENVELOPE 2 -#define SOAP_IN_HEADER 3 -#define SOAP_END_HEADER 4 -#define SOAP_NO_BODY 5 -#define SOAP_IN_BODY 6 -#define SOAP_END_BODY 7 -#define SOAP_END_ENVELOPE 8 -#define SOAP_END 9 -#define SOAP_BEGIN_SECURITY 10 -#define SOAP_IN_SECURITY 11 -#define SOAP_END_SECURITY 12 - -/* DEBUG macros */ - -#ifndef WITH_LEAN -# ifdef DEBUG -# ifndef SOAP_DEBUG -# define SOAP_DEBUG -# endif -# ifndef SOAP_MEM_DEBUG -# define SOAP_MEM_DEBUG -# endif -# endif -#endif - -#ifdef SOAP_MEM_DEBUG -# ifndef SOAP_MALLOC -# define SOAP_MALLOC(soap, size) soap_track_malloc(soap, __FILE__, __LINE__, size) -# endif -# ifndef SOAP_FREE -# define SOAP_FREE(soap, ptr) soap_track_free(soap, __FILE__, __LINE__, ptr) -# endif -#endif - -#ifndef SOAP_MALLOC /* use libc malloc */ -# define SOAP_MALLOC(soap, size) malloc(size) -#endif - -#ifndef SOAP_FREE /* use libc free */ -# define SOAP_FREE(soap, ptr) free(ptr) -#endif - -#ifdef SOAP_DEBUG -# ifndef SOAP_MESSAGE -# define SOAP_MESSAGE fprintf -# endif -# ifndef DBGLOG -# define DBGLOG(DBGFILE, CMD) \ -{ if (soap)\ - { if (!soap->fdebug[SOAP_INDEX_##DBGFILE])\ - soap_open_logfile((struct soap*)soap, SOAP_INDEX_##DBGFILE);\ - if (soap->fdebug[SOAP_INDEX_##DBGFILE])\ - { FILE *fdebug = soap->fdebug[SOAP_INDEX_##DBGFILE];\ - CMD;\ - fflush(fdebug);\ - }\ - }\ -} -# endif -# ifndef DBGMSG -# define DBGMSG(DBGFILE, MSG, LEN) \ -{ if (soap)\ - { if (!soap->fdebug[SOAP_INDEX_##DBGFILE])\ - soap_open_logfile((struct soap*)soap, SOAP_INDEX_##DBGFILE);\ - if (soap->fdebug[SOAP_INDEX_##DBGFILE])\ - { fwrite((MSG), 1, (LEN), soap->fdebug[SOAP_INDEX_##DBGFILE]);\ - fflush(soap->fdebug[SOAP_INDEX_##DBGFILE]);\ - }\ - }\ -} -# endif -# ifndef DBGFUN -# define DBGFUN(FNAME) DBGLOG(TEST, SOAP_MESSAGE(fdebug, "%s(%d): %s()\n", __FILE__, __LINE__, FNAME)) -# define DBGFUN1(FNAME, FMT, ARG) DBGLOG(TEST, SOAP_MESSAGE(fdebug, "%s(%d): %s("FMT")\n", __FILE__, __LINE__, FNAME, (ARG))) -# define DBGFUN2(FNAME, FMT1, ARG1, FMT2, ARG2) DBGLOG(TEST, SOAP_MESSAGE(fdebug, "%s(%d): %s("FMT1", "FMT2")\n", __FILE__, __LINE__, FNAME, (ARG1), (ARG2))) -# define DBGFUN3(FNAME, FMT1, ARG1, FMT2, ARG2, FMT3, ARG3) DBGLOG(TEST, SOAP_MESSAGE(fdebug, "%s(%d): %s("FMT1", "FMT2", "FMT3")\n", __FILE__, __LINE__, FNAME, (ARG1), (ARG2), (ARG3))) -# endif -# ifndef DBGHEX -# define DBGHEX(DBGFILE, MSG, LEN) \ -{ if (soap)\ - { if (!soap->fdebug[SOAP_INDEX_##DBGFILE])\ - soap_open_logfile(soap, SOAP_INDEX_##DBGFILE);\ - if (soap->fdebug[SOAP_INDEX_##DBGFILE])\ - { int i; char *s;\ - for (s = (char*)(MSG), i = (LEN); i; i--)\ - fprintf(soap->fdebug[SOAP_INDEX_##DBGFILE], "%2.2X ", (int)*s++&0xFF);\ - fflush(soap->fdebug[SOAP_INDEX_##DBGFILE]);\ - }\ - }\ -} -# endif -#else -# define DBGLOG(DBGFILE, CMD) -# define DBGMSG(DBGFILE, MSG, LEN) -# define DBGFUN(FNAME) -# define DBGFUN1(FNAME, FMT, ARG) -# define DBGFUN2(FNAME, FMT1, ARG1, FMT2, ARG2) -# define DBGFUN3(FNAME, FMT1, ARG1, FMT2, ARG2, FMT3, ARG3) -# define DBGHEX(DBGFILE, MSG, LEN) -#endif - -/* UCS-4 requires 32 bits (0-7FFFFFFF, the sign bit is used by gSOAP to distinguish XML entities) */ -typedef soap_int32 soap_wchar; - -/* namespace table row */ -struct Namespace -{ const char *id; - const char *ns; - const char *in; - char *out; -}; - -/* namespace stack */ -struct soap_nlist -{ struct soap_nlist *next; - unsigned int level; /* nesting depth level */ - short index; /* corresponding entry in ns mapping table */ - const char *ns; /* only set when parsed ns URI is not in the ns mapping table */ - char id[1]; /* the actual string value flows into the allocated region below this struct */ -}; - -/* block stack for nested block allocations */ -struct soap_blist -{ struct soap_blist *next; - char *ptr; - size_t size; -}; - -/* array layout */ -struct soap_array -{ void *__ptr; - int __size; -}; - -/* pointer serialization management */ -struct soap_plist -{ struct soap_plist *next; - const void *ptr; - const struct soap_array *array; - int type; - int id; - char mark1; - char mark2; -}; - -/* block allocation for pointer serialization management */ -struct soap_pblk -{ struct soap_pblk *next; - struct soap_plist plist[SOAP_PTRBLK]; -}; - -#ifdef SOAP_MEM_DEBUG -/* malloc/free tracking for debugging */ -struct soap_mlist -{ struct soap_mlist *next; - const void *ptr; - const char *file; - int line; - short live; -}; -#endif - -/* class allocation list */ -struct soap_clist -{ struct soap_clist *next; - void *ptr; - int type; - int size; - int (*fdelete)(struct soap_clist*); -}; - -/* attributes */ -struct soap_attribute -{ struct soap_attribute *next; - char *value; - size_t size; - char *ns; - short visible; - char name[1]; /* the actual name string flows into the allocated region below this struct */ -}; - -#ifndef WITH_LEAN -struct soap_cookie -{ struct soap_cookie *next; - char *name; - char *value; - char *domain; - char *path; - time_t expire; /* client-side: local time to expire */ - long maxage; /* server-side: seconds to expire */ - unsigned int version; - short secure; - short session; /* server-side */ - short env; /* server-side: got cookie from client and should not be (re)send */ - short modified; /* server-side: client cookie was modified and should be send */ -}; -#endif - -SOAP_FMAC1 struct soap_multipart* SOAP_FMAC2 soap_next_multipart(struct soap_multipart*); - -#ifdef __cplusplus - -class soap_multipart_iterator -{ public: - struct soap_multipart *content; - bool operator==(const soap_multipart_iterator& iter) const - { return (bool)(content == iter.content); } - bool operator!=(const soap_multipart_iterator& iter) const - { return (bool)(content != iter.content); } - struct soap_multipart &operator*() const - { return *content; } - soap_multipart_iterator &operator++() - { content = soap_next_multipart(content); return *this; } - soap_multipart_iterator() : content(NULL) - { } - soap_multipart_iterator(struct soap_multipart *p) : content(p) - { } -}; -#endif - -#ifndef WITH_LEANER -struct soap_dime -{ size_t count; - size_t size; - size_t chunksize; - size_t buflen; - char flags; - char *ptr; - const char *id; - const char *type; - const char *options; - struct soap_multipart *list; /* list of DIME attachments received */ - struct soap_multipart *first, *last; /* temporary in/out queue */ -#ifdef __cplusplus - soap_multipart_iterator begin() - { soap_multipart_iterator iter(list); return iter; }; - soap_multipart_iterator end() - { soap_multipart_iterator iter(NULL); return iter; }; -#endif -}; -#endif - -#ifndef WITH_LEANER -struct soap_mime -{ char *boundary; /* MIME boundary */ - const char *start; /* MIME start ID */ - struct soap_multipart *list; /* list of MIME attachments received */ - struct soap_multipart *first, *last; /* temporary in/out queue */ -#ifdef __cplusplus - soap_multipart_iterator begin() - { soap_multipart_iterator iter(list); return iter; }; - soap_multipart_iterator end() - { soap_multipart_iterator iter(NULL); return iter; }; -#endif -}; -#endif - -#ifndef WITH_LEANER -/* RFC2045 MIME content transfer encodings */ -enum soap_mime_encoding -{ SOAP_MIME_NONE, - SOAP_MIME_7BIT, - SOAP_MIME_8BIT, - SOAP_MIME_BINARY, - SOAP_MIME_QUOTED_PRINTABLE, - SOAP_MIME_BASE64, - SOAP_MIME_IETF_TOKEN, - SOAP_MIME_X_TOKEN -}; -#endif - -#ifndef WITH_LEANER -/* DIME/MIME multipart list */ -struct soap_multipart -{ struct soap_multipart *next; - char *ptr; /* points to raw data content */ - size_t size; /* size of data content */ - const char *id; /* DIME/MIME content ID or form data name */ - const char *type; /* DIME/MIME type (MIME type format) */ - const char *options; /* DIME options */ - enum soap_mime_encoding encoding; /* MIME Content-Transfer-Encoding */ - const char *location; /* MIME Content-Location (optional) */ - const char *description; /* MIME Content-Description (optional) */ -#ifdef __cplusplus - typedef soap_multipart_iterator iterator; -#endif -}; -#endif - -#ifndef WITH_LEANER -/* attachment DIME and MTOM XOP forwarding */ -struct soap_xlist -{ struct soap_xlist *next; - unsigned char **ptr; - int *size; - char *id; - char **type; - char **options; -}; -#endif - -/******************************************************************************/ - -#ifndef WITH_LEANER -#ifdef __cplusplus -class soap_dom_attribute_iterator -{ public: - struct soap_dom_attribute *att; - const char *nstr; - const char *name; - bool operator==(const soap_dom_attribute_iterator&) const; - bool operator!=(const soap_dom_attribute_iterator&) const; - struct soap_dom_attribute &operator*() const; - soap_dom_attribute_iterator &operator++(); - soap_dom_attribute_iterator(); - soap_dom_attribute_iterator(struct soap_dom_attribute*); - ~soap_dom_attribute_iterator(); -}; -#endif -#endif - -#ifndef WITH_LEANER -struct soap_dom_attribute -{ struct soap_dom_attribute *next; - const char *nstr; - char *name; - char *data; - wchar_t *wide; - struct soap *soap; -#ifdef __cplusplus - typedef soap_dom_attribute_iterator iterator; - struct soap_dom_attribute &set(const char *nstr, const char *name); /* set namespace and name */ - struct soap_dom_attribute &set(const char *data); /* set data */ - soap_dom_attribute_iterator begin(); - soap_dom_attribute_iterator end(); - soap_dom_attribute_iterator find(const char *nstr, const char *name); - void unlink(); - soap_dom_attribute(); - soap_dom_attribute(struct soap *soap); - soap_dom_attribute(struct soap *soap, const char *nstr, const char *name, const char *data); - ~soap_dom_attribute(); -#endif -}; -#endif - -#ifndef WITH_LEANER -#ifdef __cplusplus -class soap_dom_element_iterator -{ public: - struct soap_dom_element *elt; - const char *nstr; - const char *name; - int type; - bool operator==(const soap_dom_element_iterator&) const; - bool operator!=(const soap_dom_element_iterator&) const; - struct soap_dom_element &operator*() const; - soap_dom_element_iterator &operator++(); - soap_dom_element_iterator(); - soap_dom_element_iterator(struct soap_dom_element*); - ~soap_dom_element_iterator(); -}; -#endif -#endif - -#ifndef WITH_LEANER -struct soap_dom_element -{ struct soap_dom_element *next; /* next sibling */ - struct soap_dom_element *prnt; /* parent */ - struct soap_dom_element *elts; /* list of child elements */ - struct soap_dom_attribute *atts; /* list of attributes */ - const char *nstr; /* namespace string */ - char *name; /* element tag name */ - char *data; /* element content data (with SOAP_C_UTFSTRING flag set) */ - wchar_t *wide; /* element content data */ - int type; /* optional: serialized C/C++ data type */ - void *node; /* optional: pointer to serialized C/C++ data */ - char *head; /* leading content before start tag */ - char *tail; /* leading content before end tag */ - struct soap *soap; /* soap context that manages this node */ -#ifdef __cplusplus - typedef soap_dom_element_iterator iterator; - struct soap_dom_element &set(const char *nstr, const char *name); - struct soap_dom_element &set(const char *data); - struct soap_dom_element &set(void *node, int type); - struct soap_dom_element &add(struct soap_dom_element*); - struct soap_dom_element &add(struct soap_dom_element&); - struct soap_dom_element &add(struct soap_dom_attribute*); - struct soap_dom_element &add(struct soap_dom_attribute&); - soap_dom_element_iterator begin(); - soap_dom_element_iterator end(); - soap_dom_element_iterator find(const char *nstr, const char *name); - soap_dom_element_iterator find(int type); - void unlink(); - soap_dom_element(); - soap_dom_element(struct soap *soap); - soap_dom_element(struct soap *soap, const char *nstr, const char *name); - soap_dom_element(struct soap *soap, const char *nstr, const char *name, const char *data); - soap_dom_element(struct soap *soap, const char *nstr, const char *name, void *node, int type); - ~soap_dom_element(); -#endif -}; -SOAP_FMAC1 struct soap_dom_element * SOAP_FMAC2 soap_dom_next_element(struct soap_dom_element *elt); -SOAP_FMAC1 struct soap_dom_attribute * SOAP_FMAC2 soap_dom_next_attribute(struct soap_dom_attribute *att); -#endif - -#if defined(__cplusplus) && !defined(WITH_LEAN) && !defined(WITH_COMPAT) -} -extern std::ostream &operator<<(std::ostream&, const struct soap_dom_element&); -extern std::istream &operator>>(std::istream&, struct soap_dom_element&); -extern "C" { -#endif - -/******************************************************************************/ - -#ifdef WIN32 -# ifdef SOAP_STD_EXPORTS -# define SOAP_STD_API __declspec(dllexport) -# else -# define SOAP_STD_API -# endif -#else -# define SOAP_STD_API -#endif - -struct SOAP_STD_API soap -{ short state; /* 0 = uninitialized, 1 = initialized, 2 = copy of another soap struct */ - short version; /* 1 = SOAP1.1 and 2 = SOAP1.2 (set automatically from namespace URI in nsmap table) */ - soap_mode mode; - soap_mode imode; - soap_mode omode; - const char *float_format; /* user-definable format string for floats (<1024 chars) */ - const char *double_format; /* user-definable format string for doubles (<1024 chars) */ - const char *dime_id_format; /* user-definable format string for integer DIME id ( 0, gives socket recv timeout in seconds, < 0 in usec */ - int send_timeout; /* when > 0, gives socket send timeout in seconds, < 0 in usec */ - int connect_timeout; /* when > 0, gives socket connect() timeout in seconds, < 0 in usec */ - int accept_timeout; /* when > 0, gives socket accept() timeout in seconds, < 0 in usec */ - int socket_flags; /* socket recv() and send() flags, e.g. set to MSG_NOSIGNAL to disable sigpipe */ - int connect_flags; /* connect() SOL_SOCKET sockopt flags, e.g. set to SO_DEBUG to debug socket */ - int bind_flags; /* bind() SOL_SOCKET sockopt flags, e.g. set to SO_REUSEADDR to enable reuse */ - int accept_flags; /* accept() SOL_SOCKET sockopt flags */ - unsigned short linger_time; /* linger time for SO_LINGER option */ - const struct Namespace *namespaces; /* Pointer to global namespace mapping table */ - struct Namespace *local_namespaces; /* Local namespace mapping table */ - struct soap_nlist *nlist; /* namespace stack */ - struct soap_blist *blist; /* block allocation stack */ - struct soap_clist *clist; /* class instance allocation list */ - void *alist; /* memory allocation (malloc) list */ - struct soap_ilist *iht[SOAP_IDHASH]; - struct soap_plist *pht[SOAP_PTRHASH]; - struct soap_pblk *pblk; /* plist block allocation */ - short pidx; /* plist block allocation */ - struct SOAP_ENV__Header *header; - struct SOAP_ENV__Fault *fault; - int idnum; - void *user; /* to pass user-defined data */ - struct soap_plugin *plugins; /* linked list of plug-in data */ - const char *userid; /* HTTP Basic authorization userid */ - const char *passwd; /* HTTP Basic authorization passwd */ - int (*fpost)(struct soap*, const char*, const char*, int, const char*, const char*, size_t); - int (*fget)(struct soap*); - int (*fput)(struct soap*); - int (*fdel)(struct soap*); - int (*fhead)(struct soap*); - int (*fform)(struct soap*); - int (*fposthdr)(struct soap*, const char*, const char*); - int (*fresponse)(struct soap*, int, size_t); - int (*fparse)(struct soap*); - int (*fparsehdr)(struct soap*, const char*, const char*); - int (*fheader)(struct soap*); - int (*fresolve)(struct soap*, const char*, struct in_addr* inaddr); - int (*fconnect)(struct soap*, const char*, const char*, int); - int (*fdisconnect)(struct soap*); - int (*fclosesocket)(struct soap*, SOAP_SOCKET); - int (*fshutdownsocket)(struct soap*, SOAP_SOCKET, int); - SOAP_SOCKET (*fopen)(struct soap*, const char*, const char*, int); - SOAP_SOCKET (*faccept)(struct soap*, SOAP_SOCKET, struct sockaddr*, int *n); - int (*fclose)(struct soap*); - int (*fsend)(struct soap*, const char*, size_t); - size_t (*frecv)(struct soap*, char*, size_t); - int (*fpoll)(struct soap*); - void (*fseterror)(struct soap*, const char **c, const char **s); - int (*fignore)(struct soap*, const char*); - int (*fserveloop)(struct soap*); - void *(*fplugin)(struct soap*, const char*); - void *(*fmalloc)(struct soap*, size_t); -#ifndef WITH_LEANER - int (*fprepareinit)(struct soap*); - int (*fpreparesend)(struct soap*, const char*, size_t); - int (*fpreparerecv)(struct soap*, const char*, size_t); - int (*fpreparefinal)(struct soap*); - void *(*fdimereadopen)(struct soap*, void*, const char*, const char*, const char*); - void *(*fdimewriteopen)(struct soap*, const char*, const char*, const char*); - void (*fdimereadclose)(struct soap*, void*); - void (*fdimewriteclose)(struct soap*, void*); - size_t (*fdimeread)(struct soap*, void*, char*, size_t); - int (*fdimewrite)(struct soap*, void*, const char*, size_t); - void *(*fmimereadopen)(struct soap*, void*, const char*, const char*, const char*); - void *(*fmimewriteopen)(struct soap*, void*, const char*, const char*, const char*, enum soap_mime_encoding); - void (*fmimereadclose)(struct soap*, void*); - void (*fmimewriteclose)(struct soap*, void*); - size_t (*fmimeread)(struct soap*, void*, char*, size_t); - int (*fmimewrite)(struct soap*, void*, const char*, size_t); -#endif - SOAP_SOCKET master; - SOAP_SOCKET socket; -#if defined(__cplusplus) && !defined(WITH_LEAN) && !defined(WITH_COMPAT) - std::ostream *os; - std::istream *is; -#else - void *os; /* preserve struct size */ - void *is; /* preserve struct size */ -#endif -#ifndef UNDER_CE - int sendfd; - int recvfd; -#else - FILE *sendfd; - FILE *recvfd; -#endif - size_t bufidx; /* index in soap.buf[] */ - size_t buflen; /* length of soap.buf[] content */ - soap_wchar ahead; /* parser lookahead */ - short cdata; /* CDATA parser state */ - short body; /* parsed XML element has a body or not */ - unsigned int level; /* XML nesting level */ - size_t count; /* message length counter */ - size_t length; /* message length as set by HTTP header */ - char *labbuf; /* look-aside buffer */ - size_t lablen; /* look-aside buffer allocated length */ - size_t labidx; /* look-aside buffer index to available part */ - char buf[SOAP_BUFLEN];/* send and receive buffer */ - char msgbuf[1024]; /* in/out buffer for HTTP/MIME headers >=1024 bytes */ - char tmpbuf[1024]; /* in/out buffer for HTTP/MIME headers, simpleType values, element and attribute tag names, and DIME must be >=1024 bytes */ - char tag[SOAP_TAGLEN]; - char id[SOAP_TAGLEN]; - char href[SOAP_TAGLEN]; - char type[SOAP_TAGLEN]; - char arrayType[SOAP_TAGLEN]; - char arraySize[SOAP_TAGLEN]; - char arrayOffset[SOAP_TAGLEN]; - short other; - short position; - int positions[SOAP_MAXDIMS]; - short root; - struct soap_attribute *attributes; /* attribute list */ - short encoding; /* when set, output encodingStyle */ - short mustUnderstand; /* a mustUnderstand element was parsed or is output */ - short null; /* parsed XML is xsi:nil */ - short ns; /* when not set, output full xmlns bindings */ - short part; /* parsing state */ - short alloced; - short peeked; - size_t chunksize; - size_t chunkbuflen; - char endpoint[SOAP_TAGLEN]; - char path[SOAP_TAGLEN]; - char host[SOAP_TAGLEN]; - char *action; - char *authrealm; /* HTTP authentication realm */ - char *prolog; /* XML declaration prolog */ - unsigned long ip; /* IP number */ - int port; /* port number */ - short keep_alive; /* connection should be kept open */ - short tcp_keep_alive; /* enable SO_KEEPALIVE */ - unsigned int tcp_keep_idle; /* set TCP_KEEPIDLE */ - unsigned int tcp_keep_intvl; /* set TCP_KEEPINTVL */ - unsigned int tcp_keep_cnt; /* set TCP_KEEPCNT */ - unsigned int max_keep_alive; /* maximum keep-alive session (default=100) */ - const char *proxy_http_version;/* HTTP version of proxy "1.0" or "1.1" */ - const char *proxy_host; /* Proxy Server host name */ - int proxy_port; /* Proxy Server port (default = 8080) */ - const char *proxy_userid; /* Proxy Authorization user name */ - const char *proxy_passwd; /* Proxy Authorization password */ - const char *proxy_from; /* X-Forwarding-For header returned by proxy */ - int status; /* -1 when request, else error code to be returned by server */ - int error; - int errmode; - int errnum; -#ifndef WITH_LEANER - struct soap_dom_element *dom; - struct soap_dime dime; - struct soap_mime mime; - struct soap_xlist *xlist; -#endif -#if !defined(WITH_LEAN) || defined(SOAP_DEBUG) - const char *logfile[SOAP_MAXLOGS]; - FILE *fdebug[SOAP_MAXLOGS]; - struct soap_mlist *mht[SOAP_PTRHASH]; -#endif -#ifndef WITH_LEAN - const char *c14ninclude; - const char *c14nexclude; - struct soap_cookie *cookies; - const char *cookie_domain; - const char *cookie_path; - int cookie_max; -#endif -#ifndef WITH_NOIO - int ipv6_multicast_if; /* always include this to keep the soap struct size the same in v4 and v6 */ - char* ipv4_multicast_if; /* always include this to keep the soap struct size the same in v4 and v6 */ - int ipv4_multicast_ttl; /* multicast scope */ -#ifdef WITH_IPV6 - struct sockaddr_storage peer; /* IPv6: set by soap_accept and by UDP recv */ -#else - struct sockaddr_in peer; /* IPv4: set by soap_connect/soap_accept and by UDP recv */ -#endif -#endif - size_t peerlen; -#ifdef WITH_OPENSSL - int (*fsslauth)(struct soap*); - int (*fsslverify)(int, X509_STORE_CTX*); - BIO *bio; - SSL *ssl; - SSL_CTX *ctx; - SSL_SESSION *session; -#else - void *fsslauth; /* dummy members, to preserve struct size */ - void *fsslverify; - void *bio; - void *ssl; - void *ctx; - void *session; -#endif - unsigned short ssl_flags; - const char *keyfile; - const char *password; - const char *dhfile; - const char *cafile; - const char *capath; - const char *crlfile; - const char *randfile; - char session_host[SOAP_TAGLEN]; - int session_port; -#ifdef WITH_C_LOCALE - locale_t c_locale; /* set to C locale by default */ -#else - void *c_locale; -#endif -#ifdef WITH_ZLIB - z_stream *d_stream; /* decompression stream */ - uLong z_crc; /* internal gzip crc */ -#else - void *d_stream; /* dummy members, to preserve struct size */ - soap_int32 z_crc; -#endif - const char *z_dict; /* support for zlib static dictionaries */ - unsigned int z_dict_len; - short zlib_state; /* SOAP_ZLIB_NONE, SOAP_ZLIB_DEFLATE, or SOAP_ZLIB_INFLATE */ - short zlib_in; /* SOAP_ZLIB_NONE, SOAP_ZLIB_DEFLATE, or SOAP_ZLIB_GZIP */ - short zlib_out; /* SOAP_ZLIB_NONE, SOAP_ZLIB_DEFLATE, or SOAP_ZLIB_GZIP */ - char *z_buf; /* buffer */ - size_t z_buflen; - unsigned short z_level; /* compression level to be used (0=none, 1=fast to 9=best) */ - float z_ratio_in; /* detected compression ratio compressed_length/length of inbound message */ - float z_ratio_out; /* detected compression ratio compressed_length/length of outbound message */ -#ifdef WMW_RPM_IO - void *rpmreqid; -#endif -#ifdef __cplusplus - soap(); - soap(soap_mode); - soap(soap_mode, soap_mode); - soap(const struct soap&); - virtual ~soap(); -#else - void (*dummy)(); -#endif -}; - -struct soap_code_map -{ long code; - const char *string; -}; - -/* forwarding list */ -struct soap_flist -{ struct soap_flist *next; - int type; - void *ptr; - unsigned int level; - size_t len; - void (*fcopy)(struct soap*, int, int, void*, size_t, const void*, size_t); -}; - -/* id-ref forwarding list */ -struct soap_ilist -{ struct soap_ilist *next; - int type; - size_t size; - void *link; - void *copy; - struct soap_flist *flist; - void *ptr; - unsigned int level; - char id[1]; /* the actual id string value flows into the allocated region below this struct */ -}; - -struct soap_plugin -{ struct soap_plugin *next; - const char *id; - void *data; - int (*fcopy)(struct soap *soap, struct soap_plugin *dst, struct soap_plugin *src); - void (*fdelete)(struct soap *soap, struct soap_plugin *p); /* should delete fields of plugin only and not free(p) */ -}; - -#ifndef WITH_NONAMESPACES -extern SOAP_NMAC struct Namespace namespaces[]; -#endif - -#ifndef WITH_LEAN -# define soap_get0(soap) (((soap)->bufidx>=(soap)->buflen && soap_recv(soap)) ? EOF : (unsigned char)(soap)->buf[(soap)->bufidx]) -# define soap_get1(soap) (((soap)->bufidx>=(soap)->buflen && soap_recv(soap)) ? EOF : (unsigned char)(soap)->buf[(soap)->bufidx++]) -#else -soap_wchar soap_get0(struct soap*); -soap_wchar soap_get1(struct soap*); -#endif - -#define soap_revget1(soap) ((soap)->bufidx--) -#define soap_unget(soap, c) ((soap)->ahead = c) -#define soap_register_plugin(soap, plugin) soap_register_plugin_arg(soap, plugin, NULL) -#define soap_imode(soap, n) ((soap)->mode = (soap)->imode = (n)) -#define soap_set_imode(soap, n) ((soap)->imode |= (n)) -#define soap_clr_imode(soap, n) ((soap)->imode &= ~(n)) -#define soap_omode(soap, n) ((soap)->mode = (soap)->omode = (n)) -#define soap_set_omode(soap, n) ((soap)->omode |= (n)) -#define soap_clr_omode(soap, n) ((soap)->omode &= ~(n)) -#define soap_set_mode(soap, n) ((soap)->imode |= (n), (soap)->omode |= (n)) -#define soap_clr_mode(soap, n) ((soap)->imode &= ~(n), (soap)->omode &= ~(n)) -#define soap_destroy(soap) soap_delete((soap), NULL) - -#ifdef HAVE_STRRCHR -# define soap_strrchr(s, t) strrchr(s, t) -#else - SOAP_FMAC1 char* SOAP_FMAC2 soap_strrchr(const char *s, int t); -#endif - -#ifdef HAVE_STRTOL -# define soap_strtol(s, t, b) strtol(s, t, b) -#else - SOAP_FMAC1 long SOAP_FMAC2 soap_strtol(const char *s, char **t, int b); -#endif - -#ifdef HAVE_STRTOUL -# define soap_strtoul(s, t, b) strtoul(s, t, b) -#else - SOAP_FMAC1 unsigned long SOAP_FMAC2 soap_strtoul(const char *s, char **t, int b); -#endif - -#if defined(WITH_OPENSSL) -# define soap_random soap_rand() -SOAP_FMAC1 int SOAP_FMAC2 soap_rand(void); -#elif defined(HAVE_RANDOM) -# define soap_random (int)random() -#else -# define soap_random rand() -#endif - -#ifdef WITH_NOIDREF -# define soap_embedded(s, p, t) (0) -# define soap_id_lookup(s, i, p, t, n, k) (p) -# define soap_id_forward(s, h, p, len, st, tt, n, k, fc) (p) -# define soap_reference(s, a, t) (1) -# define soap_array_reference(s, p, a, n, t) (1) -# define soap_embed(s, p, a, n, t, pp) (0) -# define soap_embedded_id(s, i, p, t) (i) -# define soap_is_embedded(s, p) (0) -# define soap_is_single(s, p) (1) -# define soap_lookup_type(s, i) (0) -# define soap_getindependent(s) (0) -# define soap_putindependent(s) (0) -# define soap_getelement(s, n) (n) -# define soap_putelement(s, p, t, i, n) (0) -# define soap_markelement(s, p, n) (0) -#endif - -SOAP_FMAC1 void SOAP_FMAC2 soap_header(struct soap*); -SOAP_FMAC1 void SOAP_FMAC2 soap_fault(struct soap*); -SOAP_FMAC1 const char** SOAP_FMAC2 soap_faultcode(struct soap*); -SOAP_FMAC1 const char** SOAP_FMAC2 soap_faultsubcode(struct soap*); -SOAP_FMAC1 const char** SOAP_FMAC2 soap_faultstring(struct soap*); -SOAP_FMAC1 const char** SOAP_FMAC2 soap_faultdetail(struct soap*); -SOAP_FMAC1 void SOAP_FMAC2 soap_serializeheader(struct soap*); -SOAP_FMAC1 int SOAP_FMAC2 soap_putheader(struct soap*); -SOAP_FMAC1 int SOAP_FMAC2 soap_getheader(struct soap*); -SOAP_FMAC1 void SOAP_FMAC2 soap_serializefault(struct soap*); -SOAP_FMAC1 int SOAP_FMAC2 soap_putfault(struct soap*); -SOAP_FMAC1 int SOAP_FMAC2 soap_getfault(struct soap*); - -SOAP_FMAC1 void SOAP_FMAC2 soap_ssl_init(); -SOAP_FMAC1 int SOAP_FMAC2 soap_poll(struct soap*); -SOAP_FMAC1 int SOAP_FMAC2 soap_connect_command(struct soap*, int, const char*, const char*); -SOAP_FMAC1 int SOAP_FMAC2 soap_connect(struct soap*, const char*, const char*); -SOAP_FMAC1 SOAP_SOCKET SOAP_FMAC2 soap_bind(struct soap*, const char*, int, int); -SOAP_FMAC1 SOAP_SOCKET SOAP_FMAC2 soap_accept(struct soap*); -SOAP_FMAC1 int SOAP_FMAC2 soap_ssl_accept(struct soap*); -SOAP_FMAC1 const char * SOAP_FMAC2 soap_ssl_error(struct soap*, int); - -SOAP_FMAC1 int SOAP_FMAC2 soap_ssl_server_context(struct soap*, unsigned short, const char*, const char*, const char*, const char*, const char*, const char*, const char*); -SOAP_FMAC1 int SOAP_FMAC2 soap_ssl_client_context(struct soap*, unsigned short, const char*, const char*, const char*, const char*, const char*); - -SOAP_FMAC1 int SOAP_FMAC2 soap_puthttphdr(struct soap*, int status, size_t count); - -SOAP_FMAC1 const char* SOAP_FMAC2 soap_get_header_attribute(struct soap*, const char*, const char*); -SOAP_FMAC1 const char* SOAP_FMAC2 soap_decode_key(char*, size_t, const char*); -SOAP_FMAC1 const char* SOAP_FMAC2 soap_decode_val(char*, size_t, const char*); - -SOAP_FMAC1 size_t SOAP_FMAC2 soap_hash(const char*); -SOAP_FMAC1 void SOAP_FMAC2 soap_set_endpoint(struct soap*, const char*); -SOAP_FMAC1 int SOAP_FMAC2 soap_flush_raw(struct soap*, const char*, size_t); -SOAP_FMAC1 int SOAP_FMAC2 soap_flush(struct soap*); -SOAP_FMAC1 soap_wchar SOAP_FMAC2 soap_get(struct soap*); -SOAP_FMAC1 soap_wchar SOAP_FMAC2 soap_getchar(struct soap*); -SOAP_FMAC1 int SOAP_FMAC2 soap_tag_cmp(const char*, const char*); -SOAP_FMAC1 void SOAP_FMAC2 soap_set_fault(struct soap*); -SOAP_FMAC1 int SOAP_FMAC2 soap_sender_fault(struct soap*, const char*, const char*); -SOAP_FMAC1 int SOAP_FMAC2 soap_sender_fault_subcode(struct soap*, const char*, const char*, const char*); -SOAP_FMAC1 int SOAP_FMAC2 soap_receiver_fault(struct soap*, const char*, const char*); -SOAP_FMAC1 int SOAP_FMAC2 soap_receiver_fault_subcode(struct soap*, const char*, const char*, const char*); -SOAP_FMAC1 int SOAP_FMAC2 soap_set_sender_error(struct soap*, const char*, const char*, int); -SOAP_FMAC1 int SOAP_FMAC2 soap_set_receiver_error(struct soap*, const char*, const char*, int); - -SOAP_FMAC1 int SOAP_FMAC2 soap_send_raw(struct soap*, const char*, size_t); -SOAP_FMAC1 int SOAP_FMAC2 soap_recv_raw(struct soap*); -SOAP_FMAC1 int SOAP_FMAC2 soap_recv(struct soap*); -SOAP_FMAC1 int SOAP_FMAC2 soap_send(struct soap*, const char*); -SOAP_FMAC1 int SOAP_FMAC2 soap_send2(struct soap*, const char*, const char*); -SOAP_FMAC1 int SOAP_FMAC2 soap_send3(struct soap*, const char*, const char*, const char*); - -SOAP_FMAC1 int SOAP_FMAC2 soap_pututf8(struct soap*, unsigned long); -SOAP_FMAC1 soap_wchar SOAP_FMAC2 soap_getutf8(struct soap*); - -SOAP_FMAC1 int SOAP_FMAC2 soap_putbase64(struct soap*, const unsigned char*, int); -SOAP_FMAC1 unsigned char* SOAP_FMAC2 soap_getbase64(struct soap*, int*, int); -SOAP_FMAC1 int SOAP_FMAC2 soap_puthex(struct soap*, const unsigned char*, int); -SOAP_FMAC1 unsigned char* SOAP_FMAC2 soap_gethex(struct soap*, int*); - -#ifndef WITH_LEANER -SOAP_FMAC1 int SOAP_FMAC2 soap_xop_forward(struct soap*, unsigned char**, int*, char**, char**, char**); -SOAP_FMAC1 int SOAP_FMAC2 soap_dime_forward(struct soap*, unsigned char**, int*, char**, char**, char**); -#endif - -#ifndef WITH_NOIDREF -SOAP_FMAC1 int SOAP_FMAC2 soap_pointer_lookup_id(struct soap*, void *p, int t, struct soap_plist**); -SOAP_FMAC1 int SOAP_FMAC2 soap_pointer_lookup(struct soap*, const void *p, int t, struct soap_plist**); -SOAP_FMAC1 int SOAP_FMAC2 soap_pointer_enter(struct soap*, const void *p, const struct soap_array *a, int n, int t, struct soap_plist**); -SOAP_FMAC1 int SOAP_FMAC2 soap_array_pointer_lookup(struct soap*, const void *p, const struct soap_array *a, int n, int t, struct soap_plist**); -SOAP_FMAC1 int SOAP_FMAC2 soap_embed(struct soap *soap, const void *p, const struct soap_array *a, int n, const char *tag, int type); -SOAP_FMAC1 struct soap_ilist* SOAP_FMAC2 soap_lookup(struct soap*, const char*); -SOAP_FMAC1 struct soap_ilist* SOAP_FMAC2 soap_enter(struct soap*, const char*); -SOAP_FMAC1 int SOAP_FMAC2 soap_resolve(struct soap*); -SOAP_FMAC1 void SOAP_FMAC2 soap_embedded(struct soap*, const void *p, int t); -SOAP_FMAC1 int SOAP_FMAC2 soap_reference(struct soap*, const void *p, int t); -SOAP_FMAC1 int SOAP_FMAC2 soap_array_reference(struct soap*, const void *p, const struct soap_array *a, int n, int t); -SOAP_FMAC1 int SOAP_FMAC2 soap_embedded_id(struct soap*, int id, const void *p, int t); -SOAP_FMAC1 int SOAP_FMAC2 soap_is_embedded(struct soap*, struct soap_plist*); -SOAP_FMAC1 int SOAP_FMAC2 soap_is_single(struct soap*, struct soap_plist*); -SOAP_FMAC1 void SOAP_FMAC2 soap_set_embedded(struct soap*, struct soap_plist*); -#endif - -SOAP_FMAC1 int SOAP_FMAC2 soap_begin_count(struct soap*); -SOAP_FMAC1 int SOAP_FMAC2 soap_end_count(struct soap*); -SOAP_FMAC1 int SOAP_FMAC2 soap_begin_send(struct soap*); -SOAP_FMAC1 int SOAP_FMAC2 soap_end_send(struct soap*); - -SOAP_FMAC1 const struct soap_code_map* SOAP_FMAC2 soap_code(const struct soap_code_map*, const char*); -SOAP_FMAC1 long SOAP_FMAC2 soap_code_int(const struct soap_code_map*, const char*, long); -SOAP_FMAC1 const char* SOAP_FMAC2 soap_code_str(const struct soap_code_map*, long); -SOAP_FMAC1 long SOAP_FMAC2 soap_code_bits(const struct soap_code_map*, const char*); -SOAP_FMAC1 const char* SOAP_FMAC2 soap_code_list(struct soap*, const struct soap_code_map*, long); - -SOAP_FMAC1 int SOAP_FMAC2 soap_getline(struct soap*, char*, int); -SOAP_FMAC1 int SOAP_FMAC2 soap_begin_recv(struct soap*); -SOAP_FMAC1 int SOAP_FMAC2 soap_end_recv(struct soap*); - -SOAP_FMAC1 void* SOAP_FMAC2 soap_malloc(struct soap*, size_t); -SOAP_FMAC1 void SOAP_FMAC2 soap_dealloc(struct soap*, void*); -SOAP_FMAC1 struct soap_clist * SOAP_FMAC2 soap_link(struct soap*, void*, int, int, int (*fdelete)(struct soap_clist*)); -SOAP_FMAC1 void SOAP_FMAC2 soap_unlink(struct soap*, const void*); -SOAP_FMAC1 void SOAP_FMAC2 soap_free_temp(struct soap*); -SOAP_FMAC1 void SOAP_FMAC2 soap_del(struct soap*); - -SOAP_FMAC1 void* SOAP_FMAC2 soap_track_malloc(struct soap*, const char*, int, size_t); -SOAP_FMAC1 void SOAP_FMAC2 soap_track_free(struct soap*, const char*, int, void*); - -#ifndef WITH_NOIDREF -SOAP_FMAC1 int SOAP_FMAC2 soap_lookup_type(struct soap*, const char *id); -SOAP_FMAC1 void* SOAP_FMAC2 soap_id_lookup(struct soap*, const char *id, void **p, int t, size_t n, unsigned int k); -SOAP_FMAC1 void* SOAP_FMAC2 soap_id_forward(struct soap*, const char *id, void *p, size_t len, int st, int tt, size_t n, unsigned int k, void(*fcopy)(struct soap*, int, int, void*, size_t, const void*, size_t)); -#endif -SOAP_FMAC1 void* SOAP_FMAC2 soap_id_enter(struct soap*, const char *id, void *p, int t, size_t n, unsigned int k, const char *type, const char *arrayType, void *(*finstantiate)(struct soap*, int, const char*, const char*, size_t*)); -SOAP_FMAC1 void SOAP_FMAC2 soap_fcopy(struct soap *soap, int st, int tt, void *p, size_t, const void *q, size_t n); - -SOAP_FMAC1 int SOAP_FMAC2 soap_size(const int *, int); -SOAP_FMAC1 int SOAP_FMAC2 soap_getoffsets(const char *, const int *, int *, int); -SOAP_FMAC1 int SOAP_FMAC2 soap_getsize(const char *, const char *, int *); -SOAP_FMAC1 int SOAP_FMAC2 soap_getsizes(const char *, int *, int); -SOAP_FMAC1 int SOAP_FMAC2 soap_getposition(const char *, int *); - -SOAP_FMAC1 char* SOAP_FMAC2 soap_putsize(struct soap*, const char *, int); -SOAP_FMAC1 char* SOAP_FMAC2 soap_putsizesoffsets(struct soap*, const char *, const int *, const int *, int); -SOAP_FMAC1 char* SOAP_FMAC2 soap_putsizes(struct soap*, const char *, const int *, int); -SOAP_FMAC1 char* SOAP_FMAC2 soap_putoffset(struct soap*, int); -SOAP_FMAC1 char* SOAP_FMAC2 soap_putoffsets(struct soap*, const int *, int); - -SOAP_FMAC1 int SOAP_FMAC2 soap_closesock(struct soap*); - -SOAP_FMAC1 struct soap *SOAP_FMAC2 soap_new(void); -SOAP_FMAC1 struct soap *SOAP_FMAC2 soap_new1(soap_mode); -SOAP_FMAC1 struct soap *SOAP_FMAC2 soap_new2(soap_mode, soap_mode); -SOAP_FMAC1 void SOAP_FMAC2 soap_free(struct soap*); -SOAP_FMAC1 struct soap *SOAP_FMAC2 soap_copy(const struct soap*); -SOAP_FMAC1 struct soap *SOAP_FMAC2 soap_copy_context(struct soap*, const struct soap*); -SOAP_FMAC1 void SOAP_FMAC2 soap_copy_stream(struct soap*, struct soap*); -SOAP_FMAC1 void SOAP_FMAC2 soap_init(struct soap*); -SOAP_FMAC1 void SOAP_FMAC2 soap_init1(struct soap*, soap_mode); -SOAP_FMAC1 void SOAP_FMAC2 soap_init2(struct soap*, soap_mode, soap_mode); -SOAP_FMAC1 void SOAP_FMAC2 soap_done(struct soap*); -SOAP_FMAC1 void SOAP_FMAC2 soap_cleanup(struct soap*); -SOAP_FMAC1 void SOAP_FMAC2 soap_begin(struct soap*); -SOAP_FMAC1 void SOAP_FMAC2 soap_end(struct soap*); -SOAP_FMAC1 void SOAP_FMAC2 soap_delete(struct soap*, void*); -SOAP_FMAC1 void SOAP_FMAC2 soap_delegate_deletion(struct soap*, struct soap*); - -/* API functions available with DEBUG or SOAP_DEBUG defined: */ -SOAP_FMAC1 void SOAP_FMAC2 soap_set_recv_logfile(struct soap*, const char*); -SOAP_FMAC1 void SOAP_FMAC2 soap_set_sent_logfile(struct soap*, const char*); -SOAP_FMAC1 void SOAP_FMAC2 soap_set_test_logfile(struct soap*, const char*); -SOAP_FMAC1 void SOAP_FMAC2 soap_close_logfiles(struct soap*); -SOAP_FMAC1 void SOAP_FMAC2 soap_open_logfile(struct soap*, int); -/* */ - -SOAP_FMAC1 const char* SOAP_FMAC2 soap_value(struct soap*); - -SOAP_FMAC1 int SOAP_FMAC2 soap_match_tag(struct soap*, const char*, const char *); -SOAP_FMAC1 int SOAP_FMAC2 soap_match_array(struct soap*, const char*); - -SOAP_FMAC1 int SOAP_FMAC2 soap_element(struct soap*, const char*, int, const char*); -SOAP_FMAC1 int SOAP_FMAC2 soap_element_begin_out(struct soap*, const char *tag, int id, const char *type); -SOAP_FMAC1 int SOAP_FMAC2 soap_array_begin_out(struct soap*, const char *tag, int id, const char *type, const char *offset); -SOAP_FMAC1 int SOAP_FMAC2 soap_element_ref(struct soap*, const char *tag, int id, int href); -SOAP_FMAC1 int SOAP_FMAC2 soap_element_href(struct soap*, const char *tag, int id, const char *ref, const char *val); -SOAP_FMAC1 int SOAP_FMAC2 soap_element_null(struct soap*, const char *tag, int id, const char *type); -SOAP_FMAC1 int SOAP_FMAC2 soap_element_id(struct soap*, const char *tag, int id, const void *p, const struct soap_array *a, int d, const char *type, int n); -SOAP_FMAC1 int SOAP_FMAC2 soap_element_result(struct soap*, const char *tag); -SOAP_FMAC1 void SOAP_FMAC2 soap_check_result(struct soap*, const char *tag); -SOAP_FMAC1 int SOAP_FMAC2 soap_element_end_out(struct soap*, const char *tag); -SOAP_FMAC1 int SOAP_FMAC2 soap_element_start_end_out(struct soap*, const char *tag); - -SOAP_FMAC1 int SOAP_FMAC2 soap_attribute(struct soap*, const char*, const char*); - -SOAP_FMAC1 int SOAP_FMAC2 soap_element_begin_in(struct soap*, const char *tag, int nillable, const char *type); - -SOAP_FMAC1 int SOAP_FMAC2 soap_element_end_in(struct soap*, const char *tag); - -SOAP_FMAC1 int SOAP_FMAC2 soap_peek_element(struct soap*); - -SOAP_FMAC1 void SOAP_FMAC2 soap_retry(struct soap*); -SOAP_FMAC1 void SOAP_FMAC2 soap_revert(struct soap*); - -SOAP_FMAC1 char* SOAP_FMAC2 soap_strdup(struct soap*, const char*); -SOAP_FMAC1 wchar_t* SOAP_FMAC2 soap_wstrdup(struct soap*, const wchar_t*); -SOAP_FMAC1 const char * SOAP_FMAC2 soap_strsearch(const char *big, const char *little); - -SOAP_FMAC1 int SOAP_FMAC2 soap_string_out(struct soap*, const char *s, int flag); -SOAP_FMAC1 char* SOAP_FMAC2 soap_string_in(struct soap*, int, long, long); - -#ifndef WITH_LEANER -SOAP_FMAC1 int SOAP_FMAC2 soap_wstring_out(struct soap*, const wchar_t *s, int flag); -SOAP_FMAC1 wchar_t* SOAP_FMAC2 soap_wstring_in(struct soap*, int, long, long); -#endif - -SOAP_FMAC1 int SOAP_FMAC2 soap_match_namespace(struct soap*, const char *, const char*, size_t n1, size_t n2); - -SOAP_FMAC1 int SOAP_FMAC2 soap_set_namespaces(struct soap*, const struct Namespace*); -SOAP_FMAC1 void SOAP_FMAC2 soap_set_local_namespaces(struct soap*); - -SOAP_FMAC1 void SOAP_FMAC2 soap_pop_namespace(struct soap*); -SOAP_FMAC1 struct soap_nlist* SOAP_FMAC2 soap_push_namespace(struct soap*, const char *,const char *); -SOAP_FMAC1 const char* SOAP_FMAC2 soap_current_namespace(struct soap *soap, const char *tag); - -SOAP_FMAC1 struct soap_nlist* SOAP_FMAC2 soap_lookup_ns(struct soap *soap, const char *tag, size_t n); - -SOAP_FMAC1 int SOAP_FMAC2 soap_store_lab(struct soap*, const char*, size_t); -SOAP_FMAC1 int SOAP_FMAC2 soap_append_lab(struct soap*, const char*, size_t); - -SOAP_FMAC1 struct soap_blist* SOAP_FMAC2 soap_new_block(struct soap*); -SOAP_FMAC1 void* SOAP_FMAC2 soap_push_block(struct soap*, struct soap_blist*, size_t); -SOAP_FMAC1 void SOAP_FMAC2 soap_pop_block(struct soap*, struct soap_blist*); -SOAP_FMAC1 size_t SOAP_FMAC2 soap_size_block(struct soap*, struct soap_blist*, size_t); -SOAP_FMAC1 char* SOAP_FMAC2 soap_first_block(struct soap*, struct soap_blist*); -SOAP_FMAC1 char* SOAP_FMAC2 soap_next_block(struct soap*, struct soap_blist*); -SOAP_FMAC1 size_t SOAP_FMAC2 soap_block_size(struct soap*, struct soap_blist*); -SOAP_FMAC1 char* SOAP_FMAC2 soap_save_block(struct soap*, struct soap_blist*, char*, int); -SOAP_FMAC1 void SOAP_FMAC2 soap_end_block(struct soap*, struct soap_blist*); - -SOAP_FMAC1 int SOAP_FMAC2 soap_envelope_begin_out(struct soap*); -SOAP_FMAC1 int soap_envelope_end_out(struct soap*); - -SOAP_FMAC1 int SOAP_FMAC2 soap_envelope_begin_in(struct soap*); -SOAP_FMAC1 int SOAP_FMAC2 soap_envelope_end_in(struct soap*); - -SOAP_FMAC1 int SOAP_FMAC2 soap_body_begin_out(struct soap*); -SOAP_FMAC1 int SOAP_FMAC2 soap_body_end_out(struct soap*); - -SOAP_FMAC1 int SOAP_FMAC2 soap_body_begin_in(struct soap*); -SOAP_FMAC1 int SOAP_FMAC2 soap_body_end_in(struct soap*); - -SOAP_FMAC1 int SOAP_FMAC2 soap_recv_header(struct soap*); - -SOAP_FMAC1 int SOAP_FMAC2 soap_response(struct soap*, int); - -SOAP_FMAC1 int SOAP_FMAC2 soap_send_empty_response(struct soap*, int status); -SOAP_FMAC1 int SOAP_FMAC2 soap_recv_empty_response(struct soap*); - -SOAP_FMAC1 int SOAP_FMAC2 soap_send_fault(struct soap*); -SOAP_FMAC1 int SOAP_FMAC2 soap_recv_fault(struct soap*); - -#ifndef WITH_NOSTDLIB -SOAP_FMAC1 void SOAP_FMAC2 soap_print_fault(struct soap*, FILE*); -SOAP_FMAC1 void SOAP_FMAC2 soap_print_fault_location(struct soap*, FILE*); -# ifndef WITH_LEAN -# ifdef __cplusplus -SOAP_FMAC1 void SOAP_FMAC2 soap_stream_fault(struct soap*, std::ostream&); -# endif -SOAP_FMAC1 char* SOAP_FMAC2 soap_sprint_fault(struct soap*, char*, size_t); -# endif -#endif - -SOAP_FMAC1 int SOAP_FMAC2 soap_s2byte(struct soap*, const char*, char*); -SOAP_FMAC1 int SOAP_FMAC2 soap_s2short(struct soap*, const char*, short*); -SOAP_FMAC1 int SOAP_FMAC2 soap_s2int(struct soap*, const char*, int*); -SOAP_FMAC1 int SOAP_FMAC2 soap_s2long(struct soap*, const char*, long*); -SOAP_FMAC1 int SOAP_FMAC2 soap_s2LONG64(struct soap*, const char*, LONG64*); -SOAP_FMAC1 int SOAP_FMAC2 soap_s2float(struct soap*, const char*, float*); -SOAP_FMAC1 int SOAP_FMAC2 soap_s2double(struct soap*, const char*, double*); -SOAP_FMAC1 int SOAP_FMAC2 soap_s2unsignedByte(struct soap*, const char*, unsigned char*); -SOAP_FMAC1 int SOAP_FMAC2 soap_s2unsignedShort(struct soap*, const char*, unsigned short*); -SOAP_FMAC1 int SOAP_FMAC2 soap_s2unsignedInt(struct soap*, const char*, unsigned int*); -SOAP_FMAC1 int SOAP_FMAC2 soap_s2unsignedLong(struct soap*, const char*, unsigned long*); -SOAP_FMAC1 int SOAP_FMAC2 soap_s2ULONG64(struct soap*, const char*, ULONG64*); -SOAP_FMAC1 int SOAP_FMAC2 soap_s2string(struct soap*, const char*, char**, long minlen, long maxlen); -SOAP_FMAC1 int SOAP_FMAC2 soap_s2QName(struct soap*, const char*, char**, long minlen, long maxlen); - -#ifndef WITH_LEAN -SOAP_FMAC1 int SOAP_FMAC2 soap_s2wchar(struct soap*, const char*, wchar_t**, long minlen, long maxlen); -SOAP_FMAC1 int SOAP_FMAC2 soap_s2dateTime(struct soap*, const char*, time_t*); -SOAP_FMAC1 char* SOAP_FMAC2 soap_s2base64(struct soap*, const unsigned char*, char*, int); -SOAP_FMAC1 char* SOAP_FMAC2 soap_s2hex(struct soap*, const unsigned char*, char*, int); -#endif - -SOAP_FMAC1 const char* SOAP_FMAC2 soap_byte2s(struct soap*, char); -SOAP_FMAC1 const char* SOAP_FMAC2 soap_short2s(struct soap*, short); -SOAP_FMAC1 const char* SOAP_FMAC2 soap_int2s(struct soap*, int); -SOAP_FMAC1 const char* SOAP_FMAC2 soap_long2s(struct soap*, long); -SOAP_FMAC1 const char* SOAP_FMAC2 soap_LONG642s(struct soap*, LONG64); -SOAP_FMAC1 const char* SOAP_FMAC2 soap_float2s(struct soap*, float); -SOAP_FMAC1 const char* SOAP_FMAC2 soap_double2s(struct soap*, double); -SOAP_FMAC1 const char* SOAP_FMAC2 soap_unsignedByte2s(struct soap*, unsigned char); -SOAP_FMAC1 const char* SOAP_FMAC2 soap_unsignedShort2s(struct soap*, unsigned short); -SOAP_FMAC1 const char* SOAP_FMAC2 soap_unsignedInt2s(struct soap*, unsigned int); -SOAP_FMAC1 const char* SOAP_FMAC2 soap_unsignedLong2s(struct soap*, unsigned long); -SOAP_FMAC1 const char* SOAP_FMAC2 soap_ULONG642s(struct soap*, ULONG64); -SOAP_FMAC1 const char* SOAP_FMAC2 soap_QName2s(struct soap*, const char*); - -#ifndef WITH_LEAN -SOAP_FMAC1 const char* SOAP_FMAC2 soap_wchar2s(struct soap*, const wchar_t*); -SOAP_FMAC1 const char* SOAP_FMAC2 soap_dateTime2s(struct soap*, time_t); -SOAP_FMAC1 const char* SOAP_FMAC2 soap_base642s(struct soap*, const char*, char*, size_t, int*); -SOAP_FMAC1 const char* SOAP_FMAC2 soap_hex2s(struct soap*, const char*, char*, size_t, int*); -#endif - - -SOAP_FMAC1 int* SOAP_FMAC2 soap_inint(struct soap*, const char *tag, int *p, const char *, int); -SOAP_FMAC1 char* SOAP_FMAC2 soap_inbyte(struct soap*, const char *tag, char *p, const char *, int); -SOAP_FMAC1 long* SOAP_FMAC2 soap_inlong(struct soap*, const char *tag, long *p, const char *, int); -SOAP_FMAC1 LONG64* SOAP_FMAC2 soap_inLONG64(struct soap*, const char *tag, LONG64 *p, const char *, int); -SOAP_FMAC1 short* SOAP_FMAC2 soap_inshort(struct soap*, const char *tag, short *p, const char *, int); -SOAP_FMAC1 float* SOAP_FMAC2 soap_infloat(struct soap*, const char *tag, float *p, const char *, int); -SOAP_FMAC1 double* SOAP_FMAC2 soap_indouble(struct soap*, const char *tag, double *p, const char *, int); -SOAP_FMAC1 unsigned char* SOAP_FMAC2 soap_inunsignedByte(struct soap*, const char *tag, unsigned char *p, const char *, int); -SOAP_FMAC1 unsigned short* SOAP_FMAC2 soap_inunsignedShort(struct soap*, const char *tag, unsigned short *p, const char *, int); -SOAP_FMAC1 unsigned int* SOAP_FMAC2 soap_inunsignedInt(struct soap*, const char *tag, unsigned int *p, const char *, int); -SOAP_FMAC1 unsigned long* SOAP_FMAC2 soap_inunsignedLong(struct soap*, const char *tag, unsigned long *p, const char *, int); -SOAP_FMAC1 ULONG64* SOAP_FMAC2 soap_inULONG64(struct soap*, const char *tag, ULONG64 *p, const char *, int); -SOAP_FMAC1 char** SOAP_FMAC2 soap_instring(struct soap*, const char *tag, char **p, const char *, int, int, long, long); -SOAP_FMAC1 char** SOAP_FMAC2 soap_inliteral(struct soap*, const char *tag, char **p); - -#ifndef WITH_LEAN -SOAP_FMAC1 time_t* SOAP_FMAC2 soap_indateTime(struct soap*, const char *tag, time_t *p, const char *, int); -SOAP_FMAC1 time_t SOAP_FMAC2 soap_timegm(struct tm*); -#endif - -#ifndef WITH_LEANER -SOAP_FMAC1 wchar_t** SOAP_FMAC2 soap_inwstring(struct soap*, const char *tag, wchar_t **p, const char *, int, long, long); -SOAP_FMAC1 wchar_t** SOAP_FMAC2 soap_inwliteral(struct soap*, const char *tag, wchar_t **p); -#endif - -SOAP_FMAC1 int SOAP_FMAC2 soap_outbyte(struct soap*, const char *tag, int id, const char *p, const char *, int); -SOAP_FMAC1 int SOAP_FMAC2 soap_outshort(struct soap*, const char *tag, int id, const short *p, const char *, int); -SOAP_FMAC1 int SOAP_FMAC2 soap_outint(struct soap*, const char *tag, int id, const int *p, const char *, int); -SOAP_FMAC1 int SOAP_FMAC2 soap_outlong(struct soap*, const char *tag, int id, const long *p, const char *, int); -SOAP_FMAC1 int SOAP_FMAC2 soap_outLONG64(struct soap*, const char *tag, int id, const LONG64 *p, const char *, int); -SOAP_FMAC1 int SOAP_FMAC2 soap_outfloat(struct soap*, const char *tag, int id, const float *p, const char *, int); -SOAP_FMAC1 int SOAP_FMAC2 soap_outdouble(struct soap*, const char *tag, int id, const double *p, const char *, int); -SOAP_FMAC1 int SOAP_FMAC2 soap_outunsignedByte(struct soap*, const char *tag, int id, const unsigned char *p, const char *, int); -SOAP_FMAC1 int SOAP_FMAC2 soap_outunsignedShort(struct soap*, const char *tag, int id, const unsigned short *p, const char *, int); -SOAP_FMAC1 int SOAP_FMAC2 soap_outunsignedInt(struct soap*, const char *tag, int id, const unsigned int *p, const char *, int); -SOAP_FMAC1 int SOAP_FMAC2 soap_outunsignedLong(struct soap*, const char *tag, int id, const unsigned long *p, const char *, int); -SOAP_FMAC1 int SOAP_FMAC2 soap_outULONG64(struct soap*, const char *tag, int id, const ULONG64 *p, const char *, int); -SOAP_FMAC1 int SOAP_FMAC2 soap_outstring(struct soap*, const char *tag, int id, char *const*p, const char *, int); -SOAP_FMAC1 int SOAP_FMAC2 soap_outliteral(struct soap*, const char *tag, char *const*p, const char *type); - -#ifndef WITH_LEAN -SOAP_FMAC1 int SOAP_FMAC2 soap_outdateTime(struct soap*, const char *tag, int id, const time_t *p, const char *, int); -#endif - -#ifndef WITH_LEANER -SOAP_FMAC1 int SOAP_FMAC2 soap_outwstring(struct soap*, const char *tag, int id, wchar_t *const*p, const char *, int); -SOAP_FMAC1 int SOAP_FMAC2 soap_outwliteral(struct soap*, const char *tag, wchar_t *const*p, const char *type); -#endif - -#ifndef WITH_LEANER -SOAP_FMAC1 int SOAP_FMAC2 soap_attachment(struct soap *, const char*, int, const void*, const struct soap_array*, const char*, const char*, const char*, int, const char*, int); -SOAP_FMAC1 int SOAP_FMAC2 soap_move(struct soap*, long); -SOAP_FMAC1 size_t SOAP_FMAC2 soap_tell(struct soap*); -SOAP_FMAC1 char* SOAP_FMAC2 soap_dime_option(struct soap*, unsigned short, const char*); -SOAP_FMAC1 int SOAP_FMAC2 soap_getdimehdr(struct soap*); -SOAP_FMAC1 int SOAP_FMAC2 soap_getdime(struct soap*); -SOAP_FMAC1 int SOAP_FMAC2 soap_putdimehdr(struct soap*); -SOAP_FMAC1 int SOAP_FMAC2 soap_putdime(struct soap*); -SOAP_FMAC1 int SOAP_FMAC2 soap_getmimehdr(struct soap*); -SOAP_FMAC1 int SOAP_FMAC2 soap_getmime(struct soap*); -SOAP_FMAC1 int SOAP_FMAC2 soap_putmimehdr(struct soap*, struct soap_multipart*); -SOAP_FMAC1 int SOAP_FMAC2 soap_putmime(struct soap*); -SOAP_FMAC1 void SOAP_FMAC2 soap_set_dime(struct soap*); -SOAP_FMAC1 void SOAP_FMAC2 soap_set_mime(struct soap*, const char *boundary, const char *start); -SOAP_FMAC1 void SOAP_FMAC2 soap_clr_dime(struct soap*); -SOAP_FMAC1 void SOAP_FMAC2 soap_clr_mime(struct soap*); -SOAP_FMAC1 int SOAP_FMAC2 soap_set_dime_attachment(struct soap*, char *ptr, size_t size, const char *type, const char *id, unsigned short optype, const char *option); -SOAP_FMAC1 int SOAP_FMAC2 soap_set_mime_attachment(struct soap*, char *ptr, size_t size, enum soap_mime_encoding encoding, const char *type, const char *id, const char *location, const char *description); -SOAP_FMAC1 void SOAP_FMAC2 soap_post_check_mime_attachments(struct soap *soap); -SOAP_FMAC1 int SOAP_FMAC2 soap_check_mime_attachments(struct soap *soap); -SOAP_FMAC1 struct soap_multipart* SOAP_FMAC2 soap_get_mime_attachment(struct soap *soap, void *handle); -SOAP_FMAC1 int SOAP_FMAC2 soap_match_cid(struct soap*, const char*, const char*); -#endif - -SOAP_FMAC1 int SOAP_FMAC2 soap_register_plugin_arg(struct soap*, int (*fcreate)(struct soap*, struct soap_plugin*, void*), void*); -SOAP_FMAC1 void* SOAP_FMAC2 soap_lookup_plugin(struct soap*, const char*); - -SOAP_FMAC1 const char* SOAP_FMAC2 soap_attr_value(struct soap *soap, const char *name, int flag); -SOAP_FMAC1 int SOAP_FMAC2 soap_set_attr(struct soap *soap, const char *name, const char *value); -SOAP_FMAC1 void SOAP_FMAC2 soap_clr_attr(struct soap *soap); - -#ifdef WITH_COOKIES -SOAP_FMAC1 void SOAP_FMAC2 soap_getcookies(struct soap *soap, const char *val); -SOAP_FMAC1 size_t SOAP_FMAC2 soap_encode_cookie(const char*, char*, size_t); -SOAP_FMAC1 extern struct soap_cookie* SOAP_FMAC2 soap_set_cookie(struct soap*, const char*, const char*, const char*, const char*); -SOAP_FMAC1 extern struct soap_cookie* SOAP_FMAC2 soap_cookie(struct soap*, const char*, const char*, const char*); -SOAP_FMAC1 extern char* SOAP_FMAC2 soap_cookie_value(struct soap*, const char*, const char*, const char*); -SOAP_FMAC1 extern char* SOAP_FMAC2 soap_env_cookie_value(struct soap*, const char*, const char*, const char*); -SOAP_FMAC1 extern time_t SOAP_FMAC2 soap_cookie_expire(struct soap*, const char*, const char*, const char*); -SOAP_FMAC1 extern int SOAP_FMAC2 soap_set_cookie_expire(struct soap*, const char*, long, const char*, const char*); -SOAP_FMAC1 extern int SOAP_FMAC2 soap_set_cookie_session(struct soap*, const char*, const char*, const char*); -SOAP_FMAC1 extern int SOAP_FMAC2 soap_clr_cookie_session(struct soap*, const char*, const char*, const char*); -SOAP_FMAC1 extern void SOAP_FMAC2 soap_clr_cookie(struct soap*, const char*, const char*, const char*); -SOAP_FMAC1 extern int SOAP_FMAC2 soap_getenv_cookies(struct soap*); -SOAP_FMAC1 extern struct soap_cookie* SOAP_FMAC2 soap_copy_cookies(struct soap*, const struct soap*); -SOAP_FMAC1 extern void SOAP_FMAC2 soap_free_cookies(struct soap*); -#endif - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif diff --git a/externals/jemalloc/CMakeLists.txt b/externals/jemalloc/CMakeLists.txt deleted file mode 100644 index d560c6ba675..00000000000 --- a/externals/jemalloc/CMakeLists.txt +++ /dev/null @@ -1,25 +0,0 @@ -# Copyright (C) 2008-2010 Trinity -# -# This file is free software; as a special exception the author gives -# unlimited permission to copy and/or distribute it, with or without -# modifications, as long as this notice is preserved. -# -# This program is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the -# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -file(GLOB sources *.c) - -set(jemalloc_STAT_SRC - ${sources} -) - -include_directories( - ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_CURRENT_SOURCE_DIR}/include - ${CMAKE_CURRENT_SOURCE_DIR}/include/internal -) - -add_definitions(-D_GNU_SOURCE -D_REENTRANT) - -add_library(jemalloc STATIC ${sources}) diff --git a/externals/jemalloc/arena.c b/externals/jemalloc/arena.c deleted file mode 100644 index e74b4701907..00000000000 --- a/externals/jemalloc/arena.c +++ /dev/null @@ -1,2446 +0,0 @@ -#define JEMALLOC_ARENA_C_ -#include "jemalloc/internal/jemalloc_internal.h" - -/******************************************************************************/ -/* Data. */ - -size_t opt_lg_qspace_max = LG_QSPACE_MAX_DEFAULT; -size_t opt_lg_cspace_max = LG_CSPACE_MAX_DEFAULT; -ssize_t opt_lg_dirty_mult = LG_DIRTY_MULT_DEFAULT; -uint8_t const *small_size2bin; - -/* Various bin-related settings. */ -unsigned nqbins; -unsigned ncbins; -unsigned nsbins; -unsigned nbins; -size_t qspace_max; -size_t cspace_min; -size_t cspace_max; -size_t sspace_min; -size_t sspace_max; - -size_t lg_mspace; -size_t mspace_mask; - -/* - * const_small_size2bin is a static constant lookup table that in the common - * case can be used as-is for small_size2bin. For dynamically linked programs, - * this avoids a page of memory overhead per process. - */ -#define S2B_1(i) i, -#define S2B_2(i) S2B_1(i) S2B_1(i) -#define S2B_4(i) S2B_2(i) S2B_2(i) -#define S2B_8(i) S2B_4(i) S2B_4(i) -#define S2B_16(i) S2B_8(i) S2B_8(i) -#define S2B_32(i) S2B_16(i) S2B_16(i) -#define S2B_64(i) S2B_32(i) S2B_32(i) -#define S2B_128(i) S2B_64(i) S2B_64(i) -#define S2B_256(i) S2B_128(i) S2B_128(i) -/* - * The number of elements in const_small_size2bin is dependent on page size - * and on the definition for SUBPAGE. If SUBPAGE changes, the '- 255' must also - * change, along with the addition/removal of static lookup table element - * definitions. - */ -static const uint8_t const_small_size2bin[STATIC_PAGE_SIZE - 255] = { - S2B_1(0xffU) /* 0 */ -#if (LG_QUANTUM == 4) -/* 16-byte quantum **********************/ -# ifdef JEMALLOC_TINY -# if (LG_TINY_MIN == 2) - S2B_4(0) /* 4 */ - S2B_4(1) /* 8 */ - S2B_8(2) /* 16 */ -# define S2B_QMIN 2 -# elif (LG_TINY_MIN == 3) - S2B_8(0) /* 8 */ - S2B_8(1) /* 16 */ -# define S2B_QMIN 1 -# else -# error "Unsupported LG_TINY_MIN" -# endif -# else - S2B_16(0) /* 16 */ -# define S2B_QMIN 0 -# endif - S2B_16(S2B_QMIN + 1) /* 32 */ - S2B_16(S2B_QMIN + 2) /* 48 */ - S2B_16(S2B_QMIN + 3) /* 64 */ - S2B_16(S2B_QMIN + 4) /* 80 */ - S2B_16(S2B_QMIN + 5) /* 96 */ - S2B_16(S2B_QMIN + 6) /* 112 */ - S2B_16(S2B_QMIN + 7) /* 128 */ -# define S2B_CMIN (S2B_QMIN + 8) -#else -/* 8-byte quantum ***********************/ -# ifdef JEMALLOC_TINY -# if (LG_TINY_MIN == 2) - S2B_4(0) /* 4 */ - S2B_4(1) /* 8 */ -# define S2B_QMIN 1 -# else -# error "Unsupported LG_TINY_MIN" -# endif -# else - S2B_8(0) /* 8 */ -# define S2B_QMIN 0 -# endif - S2B_8(S2B_QMIN + 1) /* 16 */ - S2B_8(S2B_QMIN + 2) /* 24 */ - S2B_8(S2B_QMIN + 3) /* 32 */ - S2B_8(S2B_QMIN + 4) /* 40 */ - S2B_8(S2B_QMIN + 5) /* 48 */ - S2B_8(S2B_QMIN + 6) /* 56 */ - S2B_8(S2B_QMIN + 7) /* 64 */ - S2B_8(S2B_QMIN + 8) /* 72 */ - S2B_8(S2B_QMIN + 9) /* 80 */ - S2B_8(S2B_QMIN + 10) /* 88 */ - S2B_8(S2B_QMIN + 11) /* 96 */ - S2B_8(S2B_QMIN + 12) /* 104 */ - S2B_8(S2B_QMIN + 13) /* 112 */ - S2B_8(S2B_QMIN + 14) /* 120 */ - S2B_8(S2B_QMIN + 15) /* 128 */ -# define S2B_CMIN (S2B_QMIN + 16) -#endif -/****************************************/ - S2B_64(S2B_CMIN + 0) /* 192 */ - S2B_64(S2B_CMIN + 1) /* 256 */ - S2B_64(S2B_CMIN + 2) /* 320 */ - S2B_64(S2B_CMIN + 3) /* 384 */ - S2B_64(S2B_CMIN + 4) /* 448 */ - S2B_64(S2B_CMIN + 5) /* 512 */ -# define S2B_SMIN (S2B_CMIN + 6) - S2B_256(S2B_SMIN + 0) /* 768 */ - S2B_256(S2B_SMIN + 1) /* 1024 */ - S2B_256(S2B_SMIN + 2) /* 1280 */ - S2B_256(S2B_SMIN + 3) /* 1536 */ - S2B_256(S2B_SMIN + 4) /* 1792 */ - S2B_256(S2B_SMIN + 5) /* 2048 */ - S2B_256(S2B_SMIN + 6) /* 2304 */ - S2B_256(S2B_SMIN + 7) /* 2560 */ - S2B_256(S2B_SMIN + 8) /* 2816 */ - S2B_256(S2B_SMIN + 9) /* 3072 */ - S2B_256(S2B_SMIN + 10) /* 3328 */ - S2B_256(S2B_SMIN + 11) /* 3584 */ - S2B_256(S2B_SMIN + 12) /* 3840 */ -#if (STATIC_PAGE_SHIFT == 13) - S2B_256(S2B_SMIN + 13) /* 4096 */ - S2B_256(S2B_SMIN + 14) /* 4352 */ - S2B_256(S2B_SMIN + 15) /* 4608 */ - S2B_256(S2B_SMIN + 16) /* 4864 */ - S2B_256(S2B_SMIN + 17) /* 5120 */ - S2B_256(S2B_SMIN + 18) /* 5376 */ - S2B_256(S2B_SMIN + 19) /* 5632 */ - S2B_256(S2B_SMIN + 20) /* 5888 */ - S2B_256(S2B_SMIN + 21) /* 6144 */ - S2B_256(S2B_SMIN + 22) /* 6400 */ - S2B_256(S2B_SMIN + 23) /* 6656 */ - S2B_256(S2B_SMIN + 24) /* 6912 */ - S2B_256(S2B_SMIN + 25) /* 7168 */ - S2B_256(S2B_SMIN + 26) /* 7424 */ - S2B_256(S2B_SMIN + 27) /* 7680 */ - S2B_256(S2B_SMIN + 28) /* 7936 */ -#endif -}; -#undef S2B_1 -#undef S2B_2 -#undef S2B_4 -#undef S2B_8 -#undef S2B_16 -#undef S2B_32 -#undef S2B_64 -#undef S2B_128 -#undef S2B_256 -#undef S2B_QMIN -#undef S2B_CMIN -#undef S2B_SMIN - -/******************************************************************************/ -/* Function prototypes for non-inline static functions. */ - -static void arena_run_split(arena_t *arena, arena_run_t *run, size_t size, - bool large, bool zero); -static arena_chunk_t *arena_chunk_alloc(arena_t *arena); -static void arena_chunk_dealloc(arena_t *arena, arena_chunk_t *chunk); -static arena_run_t *arena_run_alloc(arena_t *arena, size_t size, bool large, - bool zero); -static void arena_purge(arena_t *arena); -static void arena_run_dalloc(arena_t *arena, arena_run_t *run, bool dirty); -static void arena_run_trim_head(arena_t *arena, arena_chunk_t *chunk, - arena_run_t *run, size_t oldsize, size_t newsize); -static void arena_run_trim_tail(arena_t *arena, arena_chunk_t *chunk, - arena_run_t *run, size_t oldsize, size_t newsize, bool dirty); -static arena_run_t *arena_bin_nonfull_run_get(arena_t *arena, arena_bin_t *bin); -static void *arena_bin_malloc_hard(arena_t *arena, arena_bin_t *bin); -static size_t arena_bin_run_size_calc(arena_bin_t *bin, size_t min_run_size); -static void arena_dalloc_bin_run(arena_t *arena, arena_chunk_t *chunk, - arena_run_t *run, arena_bin_t *bin); -static void arena_ralloc_large_shrink(arena_t *arena, arena_chunk_t *chunk, - void *ptr, size_t size, size_t oldsize); -static bool arena_ralloc_large_grow(arena_t *arena, arena_chunk_t *chunk, - void *ptr, size_t size, size_t oldsize); -static bool arena_ralloc_large(void *ptr, size_t size, size_t oldsize); -#ifdef JEMALLOC_TINY -static size_t pow2_ceil(size_t x); -#endif -static bool small_size2bin_init(void); -#ifdef JEMALLOC_DEBUG -static void small_size2bin_validate(void); -#endif -static bool small_size2bin_init_hard(void); - -/******************************************************************************/ - -static inline int -arena_run_comp(arena_chunk_map_t *a, arena_chunk_map_t *b) -{ - uintptr_t a_mapelm = (uintptr_t)a; - uintptr_t b_mapelm = (uintptr_t)b; - - assert(a != NULL); - assert(b != NULL); - - return ((a_mapelm > b_mapelm) - (a_mapelm < b_mapelm)); -} - -/* Generate red-black tree functions. */ -rb_gen(static JEMALLOC_ATTR(unused), arena_run_tree_, arena_run_tree_t, - arena_chunk_map_t, u.rb_link, arena_run_comp) - -static inline int -arena_avail_comp(arena_chunk_map_t *a, arena_chunk_map_t *b) -{ - int ret; - size_t a_size = a->bits & ~PAGE_MASK; - size_t b_size = b->bits & ~PAGE_MASK; - - assert((a->bits & CHUNK_MAP_KEY) == CHUNK_MAP_KEY || (a->bits & - CHUNK_MAP_DIRTY) == (b->bits & CHUNK_MAP_DIRTY)); - - ret = (a_size > b_size) - (a_size < b_size); - if (ret == 0) { - uintptr_t a_mapelm, b_mapelm; - - if ((a->bits & CHUNK_MAP_KEY) != CHUNK_MAP_KEY) - a_mapelm = (uintptr_t)a; - else { - /* - * Treat keys as though they are lower than anything - * else. - */ - a_mapelm = 0; - } - b_mapelm = (uintptr_t)b; - - ret = (a_mapelm > b_mapelm) - (a_mapelm < b_mapelm); - } - - return (ret); -} - -/* Generate red-black tree functions. */ -rb_gen(static JEMALLOC_ATTR(unused), arena_avail_tree_, arena_avail_tree_t, - arena_chunk_map_t, u.rb_link, arena_avail_comp) - -static inline void * -arena_run_reg_alloc(arena_run_t *run, arena_bin_t *bin) -{ - void *ret; - - assert(run->magic == ARENA_RUN_MAGIC); - assert(run->nfree > 0); - - run->nfree--; - ret = run->avail; - if (ret != NULL) { - run->avail = *(void **)ret; - /* Double free can cause assertion failure.*/ - assert(ret != NULL); - /* Write-after free can cause assertion failure. */ - assert((uintptr_t)ret >= (uintptr_t)run + - (uintptr_t)bin->reg0_offset); - assert((uintptr_t)ret < (uintptr_t)run->next); - assert(((uintptr_t)ret - ((uintptr_t)run + - (uintptr_t)bin->reg0_offset)) % (uintptr_t)bin->reg_size == - 0); - return (ret); - } - ret = run->next; - run->next = (void *)((uintptr_t)ret + (uintptr_t)bin->reg_size); - assert(ret != NULL); - return (ret); -} - -static inline void -arena_run_reg_dalloc(arena_run_t *run, void *ptr) -{ - - assert(run->nfree < run->bin->nregs); - /* Freeing an interior pointer can cause assertion failure. */ - assert(((uintptr_t)ptr - ((uintptr_t)run + - (uintptr_t)run->bin->reg0_offset)) % (uintptr_t)run->bin->reg_size - == 0); - - *(void **)ptr = run->avail; - run->avail = ptr; - run->nfree++; -} - -static void -arena_run_split(arena_t *arena, arena_run_t *run, size_t size, bool large, - bool zero) -{ - arena_chunk_t *chunk; - size_t old_ndirty, run_ind, total_pages, need_pages, rem_pages, i; - size_t flag_dirty; - arena_avail_tree_t *runs_avail; - - chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(run); - old_ndirty = chunk->ndirty; - run_ind = (unsigned)(((uintptr_t)run - (uintptr_t)chunk) - >> PAGE_SHIFT); - flag_dirty = chunk->map[run_ind].bits & CHUNK_MAP_DIRTY; - runs_avail = (flag_dirty != 0) ? &arena->runs_avail_dirty : - &arena->runs_avail_clean; - total_pages = (chunk->map[run_ind].bits & ~PAGE_MASK) >> - PAGE_SHIFT; - assert((chunk->map[run_ind+total_pages-1].bits & CHUNK_MAP_DIRTY) == - flag_dirty); - need_pages = (size >> PAGE_SHIFT); - assert(need_pages > 0); - assert(need_pages <= total_pages); - rem_pages = total_pages - need_pages; - - arena_avail_tree_remove(runs_avail, &chunk->map[run_ind]); - arena->nactive += need_pages; - - /* Keep track of trailing unused pages for later use. */ - if (rem_pages > 0) { - if (flag_dirty != 0) { - chunk->map[run_ind+need_pages].bits = (rem_pages << - PAGE_SHIFT) | CHUNK_MAP_DIRTY; - chunk->map[run_ind+total_pages-1].bits = (rem_pages << - PAGE_SHIFT) | CHUNK_MAP_DIRTY; - } else { - chunk->map[run_ind+need_pages].bits = (rem_pages << - PAGE_SHIFT) | (chunk->map[run_ind+need_pages].bits & - CHUNK_MAP_ZEROED); - chunk->map[run_ind+total_pages-1].bits = (rem_pages << - PAGE_SHIFT) | - (chunk->map[run_ind+total_pages-1].bits & - CHUNK_MAP_ZEROED); - } - arena_avail_tree_insert(runs_avail, - &chunk->map[run_ind+need_pages]); - } - - /* Update dirty page accounting. */ - if (flag_dirty != 0) { - chunk->ndirty -= need_pages; - arena->ndirty -= need_pages; - } - - /* - * Update the page map separately for large vs. small runs, since it is - * possible to avoid iteration for large mallocs. - */ - if (large) { - if (zero) { - if (flag_dirty == 0) { - /* - * The run is clean, so some pages may be - * zeroed (i.e. never before touched). - */ - for (i = 0; i < need_pages; i++) { - if ((chunk->map[run_ind + i].bits & - CHUNK_MAP_ZEROED) == 0) { - memset((void *)((uintptr_t) - chunk + ((run_ind + i) << - PAGE_SHIFT)), 0, - PAGE_SIZE); - } - } - } else { - /* - * The run is dirty, so all pages must be - * zeroed. - */ - memset((void *)((uintptr_t)chunk + (run_ind << - PAGE_SHIFT)), 0, (need_pages << - PAGE_SHIFT)); - } - } - - /* - * Set the last element first, in case the run only contains one - * page (i.e. both statements set the same element). - */ - chunk->map[run_ind+need_pages-1].bits = CHUNK_MAP_LARGE | - CHUNK_MAP_ALLOCATED | flag_dirty; - chunk->map[run_ind].bits = size | CHUNK_MAP_LARGE | -#ifdef JEMALLOC_PROF - CHUNK_MAP_CLASS_MASK | -#endif - CHUNK_MAP_ALLOCATED | flag_dirty; - } else { - assert(zero == false); - /* - * Propagate the dirty flag to the allocated small run, so that - * arena_dalloc_bin_run() has the ability to conditionally trim - * clean pages. - */ - chunk->map[run_ind].bits = CHUNK_MAP_ALLOCATED | flag_dirty; - for (i = 1; i < need_pages - 1; i++) { - chunk->map[run_ind + i].bits = (i << PAGE_SHIFT) - | CHUNK_MAP_ALLOCATED; - } - chunk->map[run_ind + need_pages - 1].bits = ((need_pages - 1) << - PAGE_SHIFT) | CHUNK_MAP_ALLOCATED | flag_dirty; - } -} - -static arena_chunk_t * -arena_chunk_alloc(arena_t *arena) -{ - arena_chunk_t *chunk; - size_t i; - - if (arena->spare != NULL) { - arena_avail_tree_t *runs_avail; - - chunk = arena->spare; - arena->spare = NULL; - - /* Insert the run into the appropriate runs_avail_* tree. */ - if ((chunk->map[arena_chunk_header_npages].bits & - CHUNK_MAP_DIRTY) == 0) - runs_avail = &arena->runs_avail_clean; - else - runs_avail = &arena->runs_avail_dirty; - arena_avail_tree_insert(runs_avail, - &chunk->map[arena_chunk_header_npages]); - } else { - bool zero; - size_t zeroed; - - zero = false; - malloc_mutex_unlock(&arena->lock); - chunk = (arena_chunk_t *)chunk_alloc(chunksize, &zero); - malloc_mutex_lock(&arena->lock); - if (chunk == NULL) - return (NULL); -#ifdef JEMALLOC_STATS - arena->stats.mapped += chunksize; -#endif - - chunk->arena = arena; - ql_elm_new(chunk, link_dirty); - chunk->dirtied = false; - - /* - * Claim that no pages are in use, since the header is merely - * overhead. - */ - chunk->ndirty = 0; - - /* - * Initialize the map to contain one maximal free untouched run. - * Mark the pages as zeroed iff chunk_alloc() returned a zeroed - * chunk. - */ - zeroed = zero ? CHUNK_MAP_ZEROED : 0; - for (i = 0; i < arena_chunk_header_npages; i++) - chunk->map[i].bits = 0; - chunk->map[i].bits = arena_maxclass | zeroed; - for (i++; i < chunk_npages-1; i++) - chunk->map[i].bits = zeroed; - chunk->map[chunk_npages-1].bits = arena_maxclass | zeroed; - - /* Insert the run into the runs_avail_clean tree. */ - arena_avail_tree_insert(&arena->runs_avail_clean, - &chunk->map[arena_chunk_header_npages]); - } - - return (chunk); -} - -static void -arena_chunk_dealloc(arena_t *arena, arena_chunk_t *chunk) -{ - arena_avail_tree_t *runs_avail; - - while (arena->spare != NULL) { - arena_chunk_t *spare = arena->spare; - - arena->spare = NULL; - if (spare->dirtied) { - ql_remove(&chunk->arena->chunks_dirty, spare, - link_dirty); - arena->ndirty -= spare->ndirty; - } - malloc_mutex_unlock(&arena->lock); - chunk_dealloc((void *)spare, chunksize); - malloc_mutex_lock(&arena->lock); -#ifdef JEMALLOC_STATS - arena->stats.mapped -= chunksize; -#endif - } - - /* - * Remove run from the appropriate runs_avail_* tree, so that the arena - * does not use it. - */ - if ((chunk->map[arena_chunk_header_npages].bits & - CHUNK_MAP_DIRTY) == 0) - runs_avail = &arena->runs_avail_clean; - else - runs_avail = &arena->runs_avail_dirty; - arena_avail_tree_remove(runs_avail, - &chunk->map[arena_chunk_header_npages]); - - arena->spare = chunk; -} - -static arena_run_t * -arena_run_alloc(arena_t *arena, size_t size, bool large, bool zero) -{ - arena_chunk_t *chunk; - arena_run_t *run; - arena_chunk_map_t *mapelm, key; - - assert(size <= arena_maxclass); - assert((size & PAGE_MASK) == 0); - - /* Search the arena's chunks for the lowest best fit. */ - key.bits = size | CHUNK_MAP_KEY; - mapelm = arena_avail_tree_nsearch(&arena->runs_avail_dirty, &key); - if (mapelm != NULL) { - arena_chunk_t *run_chunk = CHUNK_ADDR2BASE(mapelm); - size_t pageind = ((uintptr_t)mapelm - (uintptr_t)run_chunk->map) - / sizeof(arena_chunk_map_t); - - run = (arena_run_t *)((uintptr_t)run_chunk + (pageind << - PAGE_SHIFT)); - arena_run_split(arena, run, size, large, zero); - return (run); - } - mapelm = arena_avail_tree_nsearch(&arena->runs_avail_clean, &key); - if (mapelm != NULL) { - arena_chunk_t *run_chunk = CHUNK_ADDR2BASE(mapelm); - size_t pageind = ((uintptr_t)mapelm - (uintptr_t)run_chunk->map) - / sizeof(arena_chunk_map_t); - - run = (arena_run_t *)((uintptr_t)run_chunk + (pageind << - PAGE_SHIFT)); - arena_run_split(arena, run, size, large, zero); - return (run); - } - - /* - * No usable runs. Create a new chunk from which to allocate the run. - */ - chunk = arena_chunk_alloc(arena); - if (chunk != NULL) { - run = (arena_run_t *)((uintptr_t)chunk + - (arena_chunk_header_npages << PAGE_SHIFT)); - arena_run_split(arena, run, size, large, zero); - return (run); - } - - /* - * arena_chunk_alloc() failed, but another thread may have made - * sufficient memory available while this one dropped arena->lock in - * arena_chunk_alloc(), so search one more time. - */ - mapelm = arena_avail_tree_nsearch(&arena->runs_avail_dirty, &key); - if (mapelm != NULL) { - arena_chunk_t *run_chunk = CHUNK_ADDR2BASE(mapelm); - size_t pageind = ((uintptr_t)mapelm - (uintptr_t)run_chunk->map) - / sizeof(arena_chunk_map_t); - - run = (arena_run_t *)((uintptr_t)run_chunk + (pageind << - PAGE_SHIFT)); - arena_run_split(arena, run, size, large, zero); - return (run); - } - mapelm = arena_avail_tree_nsearch(&arena->runs_avail_clean, &key); - if (mapelm != NULL) { - arena_chunk_t *run_chunk = CHUNK_ADDR2BASE(mapelm); - size_t pageind = ((uintptr_t)mapelm - (uintptr_t)run_chunk->map) - / sizeof(arena_chunk_map_t); - - run = (arena_run_t *)((uintptr_t)run_chunk + (pageind << - PAGE_SHIFT)); - arena_run_split(arena, run, size, large, zero); - return (run); - } - - return (NULL); -} - -static inline void -arena_maybe_purge(arena_t *arena) -{ - - /* Enforce opt_lg_dirty_mult. */ - if (opt_lg_dirty_mult >= 0 && arena->ndirty > arena->npurgatory && - (arena->ndirty - arena->npurgatory) > chunk_npages && - (arena->nactive >> opt_lg_dirty_mult) < (arena->ndirty - - arena->npurgatory)) - arena_purge(arena); -} - -static inline void -arena_chunk_purge(arena_t *arena, arena_chunk_t *chunk) -{ - ql_head(arena_chunk_map_t) mapelms; - arena_chunk_map_t *mapelm; - size_t pageind, flag_zeroed; -#ifdef JEMALLOC_DEBUG - size_t ndirty; -#endif -#ifdef JEMALLOC_STATS - size_t nmadvise; -#endif - - ql_new(&mapelms); - - flag_zeroed = -#ifdef JEMALLOC_SWAP - swap_enabled ? 0 : -#endif - CHUNK_MAP_ZEROED; - - /* - * If chunk is the spare, temporarily re-allocate it, 1) so that its - * run is reinserted into runs_avail_dirty, and 2) so that it cannot be - * completely discarded by another thread while arena->lock is dropped - * by this thread. Note that the arena_run_dalloc() call will - * implicitly deallocate the chunk, so no explicit action is required - * in this function to deallocate the chunk. - * - * Note that once a chunk contains dirty pages, it cannot again contain - * a single run unless 1) it is a dirty run, or 2) this function purges - * dirty pages and causes the transition to a single clean run. Thus - * (chunk == arena->spare) is possible, but it is not possible for - * this function to be called on the spare unless it contains a dirty - * run. - */ - if (chunk == arena->spare) { - assert((chunk->map[arena_chunk_header_npages].bits & - CHUNK_MAP_DIRTY) != 0); - arena_chunk_alloc(arena); - } - - /* Temporarily allocate all free dirty runs within chunk. */ - for (pageind = arena_chunk_header_npages; pageind < chunk_npages;) { - mapelm = &chunk->map[pageind]; - if ((mapelm->bits & CHUNK_MAP_ALLOCATED) == 0) { - size_t npages; - - npages = mapelm->bits >> PAGE_SHIFT; - assert(pageind + npages <= chunk_npages); - if (mapelm->bits & CHUNK_MAP_DIRTY) { - size_t i; - - arena_avail_tree_remove( - &arena->runs_avail_dirty, mapelm); - - /* - * Update internal elements in the page map, so - * that CHUNK_MAP_ZEROED is properly set. - * madvise(..., MADV_DONTNEED) results in - * zero-filled pages for anonymous mappings, - * but not for file-backed mappings. - */ - mapelm->bits = (npages << PAGE_SHIFT) | - CHUNK_MAP_LARGE | CHUNK_MAP_ALLOCATED | - flag_zeroed; - for (i = 1; i < npages - 1; i++) { - chunk->map[pageind + i].bits = - flag_zeroed; - } - if (npages > 1) { - chunk->map[pageind + npages - 1].bits = - (npages << PAGE_SHIFT) | - CHUNK_MAP_LARGE | CHUNK_MAP_ALLOCATED | - flag_zeroed; - } - - arena->nactive += npages; - /* Append to list for later processing. */ - ql_elm_new(mapelm, u.ql_link); - ql_tail_insert(&mapelms, mapelm, u.ql_link); - } - - pageind += npages; - } else { - /* Skip allocated run. */ - if (mapelm->bits & CHUNK_MAP_LARGE) - pageind += mapelm->bits >> PAGE_SHIFT; - else { - arena_run_t *run = (arena_run_t *)((uintptr_t) - chunk + (uintptr_t)(pageind << PAGE_SHIFT)); - - assert((mapelm->bits >> PAGE_SHIFT) == 0); - assert(run->magic == ARENA_RUN_MAGIC); - pageind += run->bin->run_size >> PAGE_SHIFT; - } - } - } - assert(pageind == chunk_npages); - -#ifdef JEMALLOC_DEBUG - ndirty = chunk->ndirty; -#endif -#ifdef JEMALLOC_STATS - arena->stats.purged += chunk->ndirty; -#endif - arena->ndirty -= chunk->ndirty; - chunk->ndirty = 0; - ql_remove(&arena->chunks_dirty, chunk, link_dirty); - chunk->dirtied = false; - - malloc_mutex_unlock(&arena->lock); -#ifdef JEMALLOC_STATS - nmadvise = 0; -#endif - ql_foreach(mapelm, &mapelms, u.ql_link) { - size_t pageind = ((uintptr_t)mapelm - (uintptr_t)chunk->map) / - sizeof(arena_chunk_map_t); - size_t npages = mapelm->bits >> PAGE_SHIFT; - - assert(pageind + npages <= chunk_npages); -#ifdef JEMALLOC_DEBUG - assert(ndirty >= npages); - ndirty -= npages; -#endif - madvise((void *)((uintptr_t)chunk + (pageind << PAGE_SHIFT)), - (npages << PAGE_SHIFT), MADV_DONTNEED); -#ifdef JEMALLOC_STATS - nmadvise++; -#endif - } -#ifdef JEMALLOC_DEBUG - assert(ndirty == 0); -#endif - malloc_mutex_lock(&arena->lock); -#ifdef JEMALLOC_STATS - arena->stats.nmadvise += nmadvise; -#endif - - /* Deallocate runs. */ - for (mapelm = ql_first(&mapelms); mapelm != NULL; - mapelm = ql_first(&mapelms)) { - size_t pageind = ((uintptr_t)mapelm - (uintptr_t)chunk->map) / - sizeof(arena_chunk_map_t); - arena_run_t *run = (arena_run_t *)((uintptr_t)chunk + - (uintptr_t)(pageind << PAGE_SHIFT)); - - ql_remove(&mapelms, mapelm, u.ql_link); - arena_run_dalloc(arena, run, false); - } -} - -static void -arena_purge(arena_t *arena) -{ - arena_chunk_t *chunk; - size_t npurgatory; -#ifdef JEMALLOC_DEBUG - size_t ndirty = 0; - - ql_foreach(chunk, &arena->chunks_dirty, link_dirty) { - assert(chunk->dirtied); - ndirty += chunk->ndirty; - } - assert(ndirty == arena->ndirty); -#endif - assert(arena->ndirty > arena->npurgatory); - assert(arena->ndirty > chunk_npages); - assert((arena->nactive >> opt_lg_dirty_mult) < arena->ndirty); - -#ifdef JEMALLOC_STATS - arena->stats.npurge++; -#endif - - /* - * Compute the minimum number of pages that this thread should try to - * purge, and add the result to arena->npurgatory. This will keep - * multiple threads from racing to reduce ndirty below the threshold. - */ - npurgatory = (arena->ndirty - arena->npurgatory) - (arena->nactive >> - opt_lg_dirty_mult); - arena->npurgatory += npurgatory; - - while (npurgatory > 0) { - /* Get next chunk with dirty pages. */ - chunk = ql_first(&arena->chunks_dirty); - if (chunk == NULL) { - /* - * This thread was unable to purge as many pages as - * originally intended, due to races with other threads - * that either did some of the purging work, or re-used - * dirty pages. - */ - arena->npurgatory -= npurgatory; - return; - } - while (chunk->ndirty == 0) { - ql_remove(&arena->chunks_dirty, chunk, link_dirty); - chunk->dirtied = false; - chunk = ql_first(&arena->chunks_dirty); - if (chunk == NULL) { - /* Same logic as for above. */ - arena->npurgatory -= npurgatory; - return; - } - } - - if (chunk->ndirty > npurgatory) { - /* - * This thread will, at a minimum, purge all the dirty - * pages in chunk, so set npurgatory to reflect this - * thread's commitment to purge the pages. This tends - * to reduce the chances of the following scenario: - * - * 1) This thread sets arena->npurgatory such that - * (arena->ndirty - arena->npurgatory) is at the - * threshold. - * 2) This thread drops arena->lock. - * 3) Another thread causes one or more pages to be - * dirtied, and immediately determines that it must - * purge dirty pages. - * - * If this scenario *does* play out, that's okay, - * because all of the purging work being done really - * needs to happen. - */ - arena->npurgatory += chunk->ndirty - npurgatory; - npurgatory = chunk->ndirty; - } - - arena->npurgatory -= chunk->ndirty; - npurgatory -= chunk->ndirty; - arena_chunk_purge(arena, chunk); - } -} - -static void -arena_run_dalloc(arena_t *arena, arena_run_t *run, bool dirty) -{ - arena_chunk_t *chunk; - size_t size, run_ind, run_pages, flag_dirty; - arena_avail_tree_t *runs_avail; - - chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(run); - run_ind = (size_t)(((uintptr_t)run - (uintptr_t)chunk) - >> PAGE_SHIFT); - assert(run_ind >= arena_chunk_header_npages); - assert(run_ind < chunk_npages); - if ((chunk->map[run_ind].bits & CHUNK_MAP_LARGE) != 0) - size = chunk->map[run_ind].bits & ~PAGE_MASK; - else - size = run->bin->run_size; - run_pages = (size >> PAGE_SHIFT); - arena->nactive -= run_pages; - - /* - * The run is dirty if the caller claims to have dirtied it, as well as - * if it was already dirty before being allocated. - */ - if ((chunk->map[run_ind].bits & CHUNK_MAP_DIRTY) != 0) - dirty = true; - flag_dirty = dirty ? CHUNK_MAP_DIRTY : 0; - runs_avail = dirty ? &arena->runs_avail_dirty : - &arena->runs_avail_clean; - - /* Mark pages as unallocated in the chunk map. */ - if (dirty) { - chunk->map[run_ind].bits = size | flag_dirty; - chunk->map[run_ind+run_pages-1].bits = size | flag_dirty; - - chunk->ndirty += run_pages; - arena->ndirty += run_pages; - } else { - chunk->map[run_ind].bits = size | (chunk->map[run_ind].bits & - CHUNK_MAP_ZEROED); - chunk->map[run_ind+run_pages-1].bits = size | - (chunk->map[run_ind+run_pages-1].bits & CHUNK_MAP_ZEROED); - } - - /* Try to coalesce forward. */ - if (run_ind + run_pages < chunk_npages && - (chunk->map[run_ind+run_pages].bits & CHUNK_MAP_ALLOCATED) == 0 && - (chunk->map[run_ind+run_pages].bits & CHUNK_MAP_DIRTY) == - flag_dirty) { - size_t nrun_size = chunk->map[run_ind+run_pages].bits & - ~PAGE_MASK; - - /* - * Remove successor from runs_avail; the coalesced run is - * inserted later. - */ - arena_avail_tree_remove(runs_avail, - &chunk->map[run_ind+run_pages]); - - size += nrun_size; - run_pages = size >> PAGE_SHIFT; - - assert((chunk->map[run_ind+run_pages-1].bits & ~PAGE_MASK) - == nrun_size); - chunk->map[run_ind].bits = size | (chunk->map[run_ind].bits & - CHUNK_MAP_FLAGS_MASK); - chunk->map[run_ind+run_pages-1].bits = size | - (chunk->map[run_ind+run_pages-1].bits & - CHUNK_MAP_FLAGS_MASK); - } - - /* Try to coalesce backward. */ - if (run_ind > arena_chunk_header_npages && (chunk->map[run_ind-1].bits & - CHUNK_MAP_ALLOCATED) == 0 && (chunk->map[run_ind-1].bits & - CHUNK_MAP_DIRTY) == flag_dirty) { - size_t prun_size = chunk->map[run_ind-1].bits & ~PAGE_MASK; - - run_ind -= prun_size >> PAGE_SHIFT; - - /* - * Remove predecessor from runs_avail; the coalesced run is - * inserted later. - */ - arena_avail_tree_remove(runs_avail, &chunk->map[run_ind]); - - size += prun_size; - run_pages = size >> PAGE_SHIFT; - - assert((chunk->map[run_ind].bits & ~PAGE_MASK) == prun_size); - chunk->map[run_ind].bits = size | (chunk->map[run_ind].bits & - CHUNK_MAP_FLAGS_MASK); - chunk->map[run_ind+run_pages-1].bits = size | - (chunk->map[run_ind+run_pages-1].bits & - CHUNK_MAP_FLAGS_MASK); - } - - /* Insert into runs_avail, now that coalescing is complete. */ - arena_avail_tree_insert(runs_avail, &chunk->map[run_ind]); - - /* - * Deallocate chunk if it is now completely unused. The bit - * manipulation checks whether the first run is unallocated and extends - * to the end of the chunk. - */ - if ((chunk->map[arena_chunk_header_npages].bits & (~PAGE_MASK | - CHUNK_MAP_ALLOCATED)) == arena_maxclass) - arena_chunk_dealloc(arena, chunk); - - /* - * It is okay to do dirty page processing even if the chunk was - * deallocated above, since in that case it is the spare. Waiting - * until after possible chunk deallocation to do dirty processing - * allows for an old spare to be fully deallocated, thus decreasing the - * chances of spuriously crossing the dirty page purging threshold. - */ - if (dirty) { - if (chunk->dirtied == false) { - ql_tail_insert(&arena->chunks_dirty, chunk, link_dirty); - chunk->dirtied = true; - } - arena_maybe_purge(arena); - } -} - -static void -arena_run_trim_head(arena_t *arena, arena_chunk_t *chunk, arena_run_t *run, - size_t oldsize, size_t newsize) -{ - size_t pageind = ((uintptr_t)run - (uintptr_t)chunk) >> PAGE_SHIFT; - size_t head_npages = (oldsize - newsize) >> PAGE_SHIFT; - size_t flags = chunk->map[pageind].bits & CHUNK_MAP_FLAGS_MASK; - - assert(oldsize > newsize); - - /* - * Update the chunk map so that arena_run_dalloc() can treat the - * leading run as separately allocated. - */ - assert(chunk->map[pageind].bits & CHUNK_MAP_LARGE); - assert(chunk->map[pageind].bits & CHUNK_MAP_ALLOCATED); - chunk->map[pageind].bits = (oldsize - newsize) | flags; - chunk->map[pageind+head_npages].bits = newsize | flags; - - arena_run_dalloc(arena, run, false); -} - -static void -arena_run_trim_tail(arena_t *arena, arena_chunk_t *chunk, arena_run_t *run, - size_t oldsize, size_t newsize, bool dirty) -{ - size_t pageind = ((uintptr_t)run - (uintptr_t)chunk) >> PAGE_SHIFT; - size_t npages = newsize >> PAGE_SHIFT; - size_t flags = chunk->map[pageind].bits & CHUNK_MAP_FLAGS_MASK; - - assert(oldsize > newsize); - - /* - * Update the chunk map so that arena_run_dalloc() can treat the - * trailing run as separately allocated. - */ - assert(chunk->map[pageind].bits & CHUNK_MAP_LARGE); - assert(chunk->map[pageind].bits & CHUNK_MAP_ALLOCATED); - chunk->map[pageind].bits = newsize | flags; - chunk->map[pageind+npages-1].bits = newsize | flags; - chunk->map[pageind+npages].bits = (oldsize - newsize) | flags; - - arena_run_dalloc(arena, (arena_run_t *)((uintptr_t)run + newsize), - dirty); -} - -static arena_run_t * -arena_bin_nonfull_run_get(arena_t *arena, arena_bin_t *bin) -{ - arena_chunk_map_t *mapelm; - arena_run_t *run; - - /* Look for a usable run. */ - mapelm = arena_run_tree_first(&bin->runs); - if (mapelm != NULL) { - arena_chunk_t *chunk; - size_t pageind; - - /* run is guaranteed to have available space. */ - arena_run_tree_remove(&bin->runs, mapelm); - - chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(mapelm); - pageind = (((uintptr_t)mapelm - (uintptr_t)chunk->map) / - sizeof(arena_chunk_map_t)); - run = (arena_run_t *)((uintptr_t)chunk + (uintptr_t)((pageind - - (mapelm->bits >> PAGE_SHIFT)) - << PAGE_SHIFT)); -#ifdef JEMALLOC_STATS - bin->stats.reruns++; -#endif - return (run); - } - /* No existing runs have any space available. */ - - /* Allocate a new run. */ - malloc_mutex_unlock(&bin->lock); - /******************************/ - malloc_mutex_lock(&arena->lock); - run = arena_run_alloc(arena, bin->run_size, false, false); - if (run != NULL) { - /* Initialize run internals. */ - run->bin = bin; - run->avail = NULL; - run->next = (void *)(((uintptr_t)run) + - (uintptr_t)bin->reg0_offset); - run->nfree = bin->nregs; -#ifdef JEMALLOC_DEBUG - run->magic = ARENA_RUN_MAGIC; -#endif - } - malloc_mutex_unlock(&arena->lock); - /********************************/ - malloc_mutex_lock(&bin->lock); - if (run != NULL) { -#ifdef JEMALLOC_STATS - bin->stats.nruns++; - bin->stats.curruns++; - if (bin->stats.curruns > bin->stats.highruns) - bin->stats.highruns = bin->stats.curruns; -#endif - return (run); - } - - /* - * arena_run_alloc() failed, but another thread may have made - * sufficient memory available while this one dopped bin->lock above, - * so search one more time. - */ - mapelm = arena_run_tree_first(&bin->runs); - if (mapelm != NULL) { - arena_chunk_t *chunk; - size_t pageind; - - /* run is guaranteed to have available space. */ - arena_run_tree_remove(&bin->runs, mapelm); - - chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(mapelm); - pageind = (((uintptr_t)mapelm - (uintptr_t)chunk->map) / - sizeof(arena_chunk_map_t)); - run = (arena_run_t *)((uintptr_t)chunk + (uintptr_t)((pageind - - (mapelm->bits >> PAGE_SHIFT)) - << PAGE_SHIFT)); -#ifdef JEMALLOC_STATS - bin->stats.reruns++; -#endif - return (run); - } - - return (NULL); -} - -/* Re-fill bin->runcur, then call arena_run_reg_alloc(). */ -static void * -arena_bin_malloc_hard(arena_t *arena, arena_bin_t *bin) -{ - void *ret; - arena_run_t *run; - - bin->runcur = NULL; - run = arena_bin_nonfull_run_get(arena, bin); - if (bin->runcur != NULL && bin->runcur->nfree > 0) { - /* - * Another thread updated runcur while this one ran without the - * bin lock in arena_bin_nonfull_run_get(). - */ - assert(bin->runcur->magic == ARENA_RUN_MAGIC); - assert(bin->runcur->nfree > 0); - ret = arena_run_reg_alloc(bin->runcur, bin); - if (run != NULL) { - malloc_mutex_unlock(&bin->lock); - malloc_mutex_lock(&arena->lock); - arena_run_dalloc(arena, run, false); - malloc_mutex_unlock(&arena->lock); - malloc_mutex_lock(&bin->lock); - } - return (ret); - } - - if (run == NULL) - return (NULL); - - bin->runcur = run; - - assert(bin->runcur->magic == ARENA_RUN_MAGIC); - assert(bin->runcur->nfree > 0); - - return (arena_run_reg_alloc(bin->runcur, bin)); -} - -#ifdef JEMALLOC_PROF -void -arena_prof_accum(arena_t *arena, uint64_t accumbytes) -{ - - if (prof_interval != 0) { - arena->prof_accumbytes += accumbytes; - if (arena->prof_accumbytes >= prof_interval) { - prof_idump(); - arena->prof_accumbytes -= prof_interval; - } - } -} -#endif - -#ifdef JEMALLOC_TCACHE -void -arena_tcache_fill_small(arena_t *arena, tcache_bin_t *tbin, size_t binind -# ifdef JEMALLOC_PROF - , uint64_t prof_accumbytes -# endif - ) -{ - unsigned i, nfill; - arena_bin_t *bin; - arena_run_t *run; - void *ptr; - - assert(tbin->ncached == 0); - -#ifdef JEMALLOC_PROF - malloc_mutex_lock(&arena->lock); - arena_prof_accum(arena, prof_accumbytes); - malloc_mutex_unlock(&arena->lock); -#endif - bin = &arena->bins[binind]; - malloc_mutex_lock(&bin->lock); - for (i = 0, nfill = (tbin->ncached_max >> 1); i < nfill; i++) { - if ((run = bin->runcur) != NULL && run->nfree > 0) - ptr = arena_run_reg_alloc(run, bin); - else - ptr = arena_bin_malloc_hard(arena, bin); - if (ptr == NULL) - break; - *(void **)ptr = tbin->avail; - tbin->avail = ptr; - } -#ifdef JEMALLOC_STATS - bin->stats.allocated += (i - tbin->ncached) * bin->reg_size; - bin->stats.nmalloc += i; - bin->stats.nrequests += tbin->tstats.nrequests; - bin->stats.nfills++; - tbin->tstats.nrequests = 0; -#endif - malloc_mutex_unlock(&bin->lock); - tbin->ncached = i; - if (tbin->ncached > tbin->high_water) - tbin->high_water = tbin->ncached; -} -#endif - -/* - * Calculate bin->run_size such that it meets the following constraints: - * - * *) bin->run_size >= min_run_size - * *) bin->run_size <= arena_maxclass - * *) run header overhead <= RUN_MAX_OVRHD (or header overhead relaxed). - * *) run header size < PAGE_SIZE - * - * bin->nregs and bin->reg0_offset are also calculated here, since these - * settings are all interdependent. - */ -static size_t -arena_bin_run_size_calc(arena_bin_t *bin, size_t min_run_size) -{ - size_t try_run_size, good_run_size; - uint32_t try_nregs, good_nregs; - uint32_t try_hdr_size, good_hdr_size; -#ifdef JEMALLOC_PROF - uint32_t try_cnt0_offset, good_cnt0_offset; -#endif - uint32_t try_reg0_offset, good_reg0_offset; - - assert(min_run_size >= PAGE_SIZE); - assert(min_run_size <= arena_maxclass); - - /* - * Calculate known-valid settings before entering the run_size - * expansion loop, so that the first part of the loop always copies - * valid settings. - * - * The do..while loop iteratively reduces the number of regions until - * the run header and the regions no longer overlap. A closed formula - * would be quite messy, since there is an interdependency between the - * header's mask length and the number of regions. - */ - try_run_size = min_run_size; - try_nregs = ((try_run_size - sizeof(arena_run_t)) / bin->reg_size) - + 1; /* Counter-act try_nregs-- in loop. */ - do { - try_nregs--; - try_hdr_size = sizeof(arena_run_t); -#ifdef JEMALLOC_PROF - if (opt_prof && prof_promote == false) { - /* Pad to a quantum boundary. */ - try_hdr_size = QUANTUM_CEILING(try_hdr_size); - try_cnt0_offset = try_hdr_size; - /* Add space for one (prof_thr_cnt_t *) per region. */ - try_hdr_size += try_nregs * sizeof(prof_thr_cnt_t *); - } else - try_cnt0_offset = 0; -#endif - try_reg0_offset = try_run_size - (try_nregs * bin->reg_size); - } while (try_hdr_size > try_reg0_offset); - - /* run_size expansion loop. */ - do { - /* - * Copy valid settings before trying more aggressive settings. - */ - good_run_size = try_run_size; - good_nregs = try_nregs; - good_hdr_size = try_hdr_size; -#ifdef JEMALLOC_PROF - good_cnt0_offset = try_cnt0_offset; -#endif - good_reg0_offset = try_reg0_offset; - - /* Try more aggressive settings. */ - try_run_size += PAGE_SIZE; - try_nregs = ((try_run_size - sizeof(arena_run_t)) / - bin->reg_size) + 1; /* Counter-act try_nregs-- in loop. */ - do { - try_nregs--; - try_hdr_size = sizeof(arena_run_t); -#ifdef JEMALLOC_PROF - if (opt_prof && prof_promote == false) { - /* Pad to a quantum boundary. */ - try_hdr_size = QUANTUM_CEILING(try_hdr_size); - try_cnt0_offset = try_hdr_size; - /* - * Add space for one (prof_thr_cnt_t *) per - * region. - */ - try_hdr_size += try_nregs * - sizeof(prof_thr_cnt_t *); - } -#endif - try_reg0_offset = try_run_size - (try_nregs * - bin->reg_size); - } while (try_hdr_size > try_reg0_offset); - } while (try_run_size <= arena_maxclass - && try_run_size <= arena_maxclass - && RUN_MAX_OVRHD * (bin->reg_size << 3) > RUN_MAX_OVRHD_RELAX - && (try_reg0_offset << RUN_BFP) > RUN_MAX_OVRHD * try_run_size - && try_hdr_size < PAGE_SIZE); - - assert(good_hdr_size <= good_reg0_offset); - - /* Copy final settings. */ - bin->run_size = good_run_size; - bin->nregs = good_nregs; -#ifdef JEMALLOC_PROF - bin->cnt0_offset = good_cnt0_offset; -#endif - bin->reg0_offset = good_reg0_offset; - - return (good_run_size); -} - -void * -arena_malloc_small(arena_t *arena, size_t size, bool zero) -{ - void *ret; - arena_bin_t *bin; - arena_run_t *run; - size_t binind; - - binind = small_size2bin[size]; - assert(binind < nbins); - bin = &arena->bins[binind]; - size = bin->reg_size; - - malloc_mutex_lock(&bin->lock); - if ((run = bin->runcur) != NULL && run->nfree > 0) - ret = arena_run_reg_alloc(run, bin); - else - ret = arena_bin_malloc_hard(arena, bin); - - if (ret == NULL) { - malloc_mutex_unlock(&bin->lock); - return (NULL); - } - -#ifdef JEMALLOC_STATS - bin->stats.allocated += size; - bin->stats.nmalloc++; - bin->stats.nrequests++; -#endif - malloc_mutex_unlock(&bin->lock); -#ifdef JEMALLOC_PROF - if (isthreaded == false) { - malloc_mutex_lock(&arena->lock); - arena_prof_accum(arena, size); - malloc_mutex_unlock(&arena->lock); - } -#endif - - if (zero == false) { -#ifdef JEMALLOC_FILL - if (opt_junk) - memset(ret, 0xa5, size); - else if (opt_zero) - memset(ret, 0, size); -#endif - } else - memset(ret, 0, size); - - return (ret); -} - -void * -arena_malloc_large(arena_t *arena, size_t size, bool zero) -{ - void *ret; - - /* Large allocation. */ - size = PAGE_CEILING(size); - malloc_mutex_lock(&arena->lock); - ret = (void *)arena_run_alloc(arena, size, true, zero); - if (ret == NULL) { - malloc_mutex_unlock(&arena->lock); - return (NULL); - } -#ifdef JEMALLOC_STATS - arena->stats.nmalloc_large++; - arena->stats.nrequests_large++; - arena->stats.allocated_large += size; - arena->stats.lstats[(size >> PAGE_SHIFT) - 1].nmalloc++; - arena->stats.lstats[(size >> PAGE_SHIFT) - 1].nrequests++; - arena->stats.lstats[(size >> PAGE_SHIFT) - 1].curruns++; - if (arena->stats.lstats[(size >> PAGE_SHIFT) - 1].curruns > - arena->stats.lstats[(size >> PAGE_SHIFT) - 1].highruns) { - arena->stats.lstats[(size >> PAGE_SHIFT) - 1].highruns = - arena->stats.lstats[(size >> PAGE_SHIFT) - 1].curruns; - } -#endif -#ifdef JEMALLOC_PROF - arena_prof_accum(arena, size); -#endif - malloc_mutex_unlock(&arena->lock); - - if (zero == false) { -#ifdef JEMALLOC_FILL - if (opt_junk) - memset(ret, 0xa5, size); - else if (opt_zero) - memset(ret, 0, size); -#endif - } - - return (ret); -} - -void * -arena_malloc(size_t size, bool zero) -{ - - assert(size != 0); - assert(QUANTUM_CEILING(size) <= arena_maxclass); - - if (size <= small_maxclass) { -#ifdef JEMALLOC_TCACHE - tcache_t *tcache; - - if ((tcache = tcache_get()) != NULL) - return (tcache_alloc_small(tcache, size, zero)); - else - -#endif - return (arena_malloc_small(choose_arena(), size, zero)); - } else { -#ifdef JEMALLOC_TCACHE - if (size <= tcache_maxclass) { - tcache_t *tcache; - - if ((tcache = tcache_get()) != NULL) - return (tcache_alloc_large(tcache, size, zero)); - else { - return (arena_malloc_large(choose_arena(), - size, zero)); - } - } else -#endif - return (arena_malloc_large(choose_arena(), size, zero)); - } -} - -/* Only handles large allocations that require more than page alignment. */ -void * -arena_palloc(arena_t *arena, size_t alignment, size_t size, size_t alloc_size) -{ - void *ret; - size_t offset; - arena_chunk_t *chunk; - - assert((size & PAGE_MASK) == 0); - assert((alignment & PAGE_MASK) == 0); - - malloc_mutex_lock(&arena->lock); - ret = (void *)arena_run_alloc(arena, alloc_size, true, false); - if (ret == NULL) { - malloc_mutex_unlock(&arena->lock); - return (NULL); - } - - chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ret); - - offset = (uintptr_t)ret & (alignment - 1); - assert((offset & PAGE_MASK) == 0); - assert(offset < alloc_size); - if (offset == 0) - arena_run_trim_tail(arena, chunk, ret, alloc_size, size, false); - else { - size_t leadsize, trailsize; - - leadsize = alignment - offset; - if (leadsize > 0) { - arena_run_trim_head(arena, chunk, ret, alloc_size, - alloc_size - leadsize); - ret = (void *)((uintptr_t)ret + leadsize); - } - - trailsize = alloc_size - leadsize - size; - if (trailsize != 0) { - /* Trim trailing space. */ - assert(trailsize < alloc_size); - arena_run_trim_tail(arena, chunk, ret, size + trailsize, - size, false); - } - } - -#ifdef JEMALLOC_STATS - arena->stats.nmalloc_large++; - arena->stats.nrequests_large++; - arena->stats.allocated_large += size; - arena->stats.lstats[(size >> PAGE_SHIFT) - 1].nmalloc++; - arena->stats.lstats[(size >> PAGE_SHIFT) - 1].nrequests++; - arena->stats.lstats[(size >> PAGE_SHIFT) - 1].curruns++; - if (arena->stats.lstats[(size >> PAGE_SHIFT) - 1].curruns > - arena->stats.lstats[(size >> PAGE_SHIFT) - 1].highruns) { - arena->stats.lstats[(size >> PAGE_SHIFT) - 1].highruns = - arena->stats.lstats[(size >> PAGE_SHIFT) - 1].curruns; - } -#endif - malloc_mutex_unlock(&arena->lock); - -#ifdef JEMALLOC_FILL - if (opt_junk) - memset(ret, 0xa5, size); - else if (opt_zero) - memset(ret, 0, size); -#endif - return (ret); -} - -/* Return the size of the allocation pointed to by ptr. */ -size_t -arena_salloc(const void *ptr) -{ - size_t ret; - arena_chunk_t *chunk; - size_t pageind, mapbits; - - assert(ptr != NULL); - assert(CHUNK_ADDR2BASE(ptr) != ptr); - - chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); - pageind = (((uintptr_t)ptr - (uintptr_t)chunk) >> PAGE_SHIFT); - mapbits = chunk->map[pageind].bits; - assert((mapbits & CHUNK_MAP_ALLOCATED) != 0); - if ((mapbits & CHUNK_MAP_LARGE) == 0) { - arena_run_t *run = (arena_run_t *)((uintptr_t)chunk + - (uintptr_t)((pageind - (mapbits >> PAGE_SHIFT)) << - PAGE_SHIFT)); - assert(run->magic == ARENA_RUN_MAGIC); - assert(((uintptr_t)ptr - ((uintptr_t)run + - (uintptr_t)run->bin->reg0_offset)) % run->bin->reg_size == - 0); - ret = run->bin->reg_size; - } else { - assert(((uintptr_t)ptr & PAGE_MASK) == 0); - ret = mapbits & ~PAGE_MASK; - assert(ret != 0); - } - - return (ret); -} - -#ifdef JEMALLOC_PROF -void -arena_prof_promoted(const void *ptr, size_t size) -{ - arena_chunk_t *chunk; - size_t pageind, binind; - - assert(ptr != NULL); - assert(CHUNK_ADDR2BASE(ptr) != ptr); - assert(isalloc(ptr) == PAGE_SIZE); - - chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); - pageind = (((uintptr_t)ptr - (uintptr_t)chunk) >> PAGE_SHIFT); - binind = small_size2bin[size]; - assert(binind < nbins); - chunk->map[pageind].bits = (chunk->map[pageind].bits & - ~CHUNK_MAP_CLASS_MASK) | (binind << CHUNK_MAP_CLASS_SHIFT); -} - -size_t -arena_salloc_demote(const void *ptr) -{ - size_t ret; - arena_chunk_t *chunk; - size_t pageind, mapbits; - - assert(ptr != NULL); - assert(CHUNK_ADDR2BASE(ptr) != ptr); - - chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); - pageind = (((uintptr_t)ptr - (uintptr_t)chunk) >> PAGE_SHIFT); - mapbits = chunk->map[pageind].bits; - assert((mapbits & CHUNK_MAP_ALLOCATED) != 0); - if ((mapbits & CHUNK_MAP_LARGE) == 0) { - arena_run_t *run = (arena_run_t *)((uintptr_t)chunk + - (uintptr_t)((pageind - (mapbits >> PAGE_SHIFT)) << - PAGE_SHIFT)); - assert(run->magic == ARENA_RUN_MAGIC); - assert(((uintptr_t)ptr - ((uintptr_t)run + - (uintptr_t)run->bin->reg0_offset)) % run->bin->reg_size == - 0); - ret = run->bin->reg_size; - } else { - assert(((uintptr_t)ptr & PAGE_MASK) == 0); - ret = mapbits & ~PAGE_MASK; - if (prof_promote && ret == PAGE_SIZE && (mapbits & - CHUNK_MAP_CLASS_MASK) != CHUNK_MAP_CLASS_MASK) { - size_t binind = ((mapbits & CHUNK_MAP_CLASS_MASK) >> - CHUNK_MAP_CLASS_SHIFT); - assert(binind < nbins); - ret = chunk->arena->bins[binind].reg_size; - } - assert(ret != 0); - } - - return (ret); -} - -static inline unsigned -arena_run_regind(arena_run_t *run, arena_bin_t *bin, const void *ptr, - size_t size) -{ - unsigned shift, diff, regind; - - assert(run->magic == ARENA_RUN_MAGIC); - - /* - * Avoid doing division with a variable divisor if possible. Using - * actual division here can reduce allocator throughput by over 20%! - */ - diff = (unsigned)((uintptr_t)ptr - (uintptr_t)run - bin->reg0_offset); - - /* Rescale (factor powers of 2 out of the numerator and denominator). */ - shift = ffs(size) - 1; - diff >>= shift; - size >>= shift; - - if (size == 1) { - /* The divisor was a power of 2. */ - regind = diff; - } else { - /* - * To divide by a number D that is not a power of two we - * multiply by (2^21 / D) and then right shift by 21 positions. - * - * X / D - * - * becomes - * - * (X * size_invs[D - 3]) >> SIZE_INV_SHIFT - * - * We can omit the first three elements, because we never - * divide by 0, and 1 and 2 are both powers of two, which are - * handled above. - */ -#define SIZE_INV_SHIFT 21 -#define SIZE_INV(s) (((1U << SIZE_INV_SHIFT) / (s)) + 1) - static const unsigned size_invs[] = { - SIZE_INV(3), - SIZE_INV(4), SIZE_INV(5), SIZE_INV(6), SIZE_INV(7), - SIZE_INV(8), SIZE_INV(9), SIZE_INV(10), SIZE_INV(11), - SIZE_INV(12), SIZE_INV(13), SIZE_INV(14), SIZE_INV(15), - SIZE_INV(16), SIZE_INV(17), SIZE_INV(18), SIZE_INV(19), - SIZE_INV(20), SIZE_INV(21), SIZE_INV(22), SIZE_INV(23), - SIZE_INV(24), SIZE_INV(25), SIZE_INV(26), SIZE_INV(27), - SIZE_INV(28), SIZE_INV(29), SIZE_INV(30), SIZE_INV(31) - }; - - if (size <= ((sizeof(size_invs) / sizeof(unsigned)) + 2)) - regind = (diff * size_invs[size - 3]) >> SIZE_INV_SHIFT; - else - regind = diff / size; -#undef SIZE_INV -#undef SIZE_INV_SHIFT - } - assert(diff == regind * size); - assert(regind < bin->nregs); - - return (regind); -} - -prof_thr_cnt_t * -arena_prof_cnt_get(const void *ptr) -{ - prof_thr_cnt_t *ret; - arena_chunk_t *chunk; - size_t pageind, mapbits; - - assert(ptr != NULL); - assert(CHUNK_ADDR2BASE(ptr) != ptr); - - chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); - pageind = (((uintptr_t)ptr - (uintptr_t)chunk) >> PAGE_SHIFT); - mapbits = chunk->map[pageind].bits; - assert((mapbits & CHUNK_MAP_ALLOCATED) != 0); - if ((mapbits & CHUNK_MAP_LARGE) == 0) { - if (prof_promote) - ret = (prof_thr_cnt_t *)(uintptr_t)1U; - else { - arena_run_t *run = (arena_run_t *)((uintptr_t)chunk + - (uintptr_t)((pageind - (mapbits >> PAGE_SHIFT)) << - PAGE_SHIFT)); - arena_bin_t *bin = run->bin; - unsigned regind; - - assert(run->magic == ARENA_RUN_MAGIC); - regind = arena_run_regind(run, bin, ptr, bin->reg_size); - ret = *(prof_thr_cnt_t **)((uintptr_t)run + - bin->cnt0_offset + (regind * - sizeof(prof_thr_cnt_t *))); - } - } else - ret = chunk->map[pageind].prof_cnt; - - return (ret); -} - -void -arena_prof_cnt_set(const void *ptr, prof_thr_cnt_t *cnt) -{ - arena_chunk_t *chunk; - size_t pageind, mapbits; - - assert(ptr != NULL); - assert(CHUNK_ADDR2BASE(ptr) != ptr); - - chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); - pageind = (((uintptr_t)ptr - (uintptr_t)chunk) >> PAGE_SHIFT); - mapbits = chunk->map[pageind].bits; - assert((mapbits & CHUNK_MAP_ALLOCATED) != 0); - if ((mapbits & CHUNK_MAP_LARGE) == 0) { - if (prof_promote == false) { - arena_run_t *run = (arena_run_t *)((uintptr_t)chunk + - (uintptr_t)((pageind - (mapbits >> PAGE_SHIFT)) << - PAGE_SHIFT)); - arena_bin_t *bin = run->bin; - unsigned regind; - - assert(run->magic == ARENA_RUN_MAGIC); - regind = arena_run_regind(run, bin, ptr, bin->reg_size); - - *((prof_thr_cnt_t **)((uintptr_t)run + bin->cnt0_offset - + (regind * sizeof(prof_thr_cnt_t *)))) = cnt; - } else - assert((uintptr_t)cnt == (uintptr_t)1U); - } else - chunk->map[pageind].prof_cnt = cnt; -} -#endif - -static void -arena_dalloc_bin_run(arena_t *arena, arena_chunk_t *chunk, arena_run_t *run, - arena_bin_t *bin) -{ - size_t npages, run_ind, past; - - /* Dissociate run from bin. */ - if (run == bin->runcur) - bin->runcur = NULL; - else if (bin->nregs != 1) { - size_t run_pageind = (((uintptr_t)run - (uintptr_t)chunk)) >> - PAGE_SHIFT; - arena_chunk_map_t *run_mapelm = &chunk->map[run_pageind]; - /* - * This block's conditional is necessary because if the run - * only contains one region, then it never gets inserted into - * the non-full runs tree. - */ - arena_run_tree_remove(&bin->runs, run_mapelm); - } - - malloc_mutex_unlock(&bin->lock); - /******************************/ - npages = bin->run_size >> PAGE_SHIFT; - run_ind = (size_t)(((uintptr_t)run - (uintptr_t)chunk) >> PAGE_SHIFT); - past = (size_t)(((uintptr_t)run->next - (uintptr_t)1U - - (uintptr_t)chunk) >> PAGE_SHIFT) + 1; - malloc_mutex_lock(&arena->lock); - - /* - * If the run was originally clean, and some pages were never touched, - * trim the clean pages before deallocating the dirty portion of the - * run. - */ - if ((chunk->map[run_ind].bits & CHUNK_MAP_DIRTY) == 0 && past - run_ind - < npages) { - /* - * Trim clean pages. Convert to large run beforehand. Set the - * last map element first, in case this is a one-page run. - */ - chunk->map[run_ind+npages-1].bits = CHUNK_MAP_LARGE | - (chunk->map[run_ind].bits & CHUNK_MAP_FLAGS_MASK); - chunk->map[run_ind].bits = bin->run_size | CHUNK_MAP_LARGE | - (chunk->map[run_ind].bits & CHUNK_MAP_FLAGS_MASK); - arena_run_trim_tail(arena, chunk, run, (npages << PAGE_SHIFT), - ((npages - (past - run_ind)) << PAGE_SHIFT), false); - npages = past - run_ind; - } -#ifdef JEMALLOC_DEBUG - run->magic = 0; -#endif - arena_run_dalloc(arena, run, true); - malloc_mutex_unlock(&arena->lock); - /****************************/ - malloc_mutex_lock(&bin->lock); -#ifdef JEMALLOC_STATS - bin->stats.curruns--; -#endif -} - -void -arena_dalloc_bin(arena_t *arena, arena_chunk_t *chunk, void *ptr, - arena_chunk_map_t *mapelm) -{ - size_t pageind; - arena_run_t *run; - arena_bin_t *bin; -#if (defined(JEMALLOC_FILL) || defined(JEMALLOC_STATS)) - size_t size; -#endif - - pageind = (((uintptr_t)ptr - (uintptr_t)chunk) >> PAGE_SHIFT); - run = (arena_run_t *)((uintptr_t)chunk + (uintptr_t)((pageind - - (mapelm->bits >> PAGE_SHIFT)) << PAGE_SHIFT)); - assert(run->magic == ARENA_RUN_MAGIC); - bin = run->bin; -#if (defined(JEMALLOC_FILL) || defined(JEMALLOC_STATS)) - size = bin->reg_size; -#endif - -#ifdef JEMALLOC_FILL - if (opt_junk) - memset(ptr, 0x5a, size); -#endif - - arena_run_reg_dalloc(run, ptr); - - if (run->nfree == bin->nregs) - arena_dalloc_bin_run(arena, chunk, run, bin); - else if (run->nfree == 1 && run != bin->runcur) { - /* - * Make sure that bin->runcur always refers to the lowest - * non-full run, if one exists. - */ - if (bin->runcur == NULL) - bin->runcur = run; - else if ((uintptr_t)run < (uintptr_t)bin->runcur) { - /* Switch runcur. */ - if (bin->runcur->nfree > 0) { - arena_chunk_t *runcur_chunk = - CHUNK_ADDR2BASE(bin->runcur); - size_t runcur_pageind = - (((uintptr_t)bin->runcur - - (uintptr_t)runcur_chunk)) >> PAGE_SHIFT; - arena_chunk_map_t *runcur_mapelm = - &runcur_chunk->map[runcur_pageind]; - - /* Insert runcur. */ - arena_run_tree_insert(&bin->runs, - runcur_mapelm); - } - bin->runcur = run; - } else { - size_t run_pageind = (((uintptr_t)run - - (uintptr_t)chunk)) >> PAGE_SHIFT; - arena_chunk_map_t *run_mapelm = - &chunk->map[run_pageind]; - - assert(arena_run_tree_search(&bin->runs, run_mapelm) == - NULL); - arena_run_tree_insert(&bin->runs, run_mapelm); - } - } - -#ifdef JEMALLOC_STATS - bin->stats.allocated -= size; - bin->stats.ndalloc++; -#endif -} - -#ifdef JEMALLOC_STATS -void -arena_stats_merge(arena_t *arena, size_t *nactive, size_t *ndirty, - arena_stats_t *astats, malloc_bin_stats_t *bstats, - malloc_large_stats_t *lstats) -{ - unsigned i; - - malloc_mutex_lock(&arena->lock); - *nactive += arena->nactive; - *ndirty += arena->ndirty; - - astats->mapped += arena->stats.mapped; - astats->npurge += arena->stats.npurge; - astats->nmadvise += arena->stats.nmadvise; - astats->purged += arena->stats.purged; - astats->allocated_large += arena->stats.allocated_large; - astats->nmalloc_large += arena->stats.nmalloc_large; - astats->ndalloc_large += arena->stats.ndalloc_large; - astats->nrequests_large += arena->stats.nrequests_large; - - for (i = 0; i < nlclasses; i++) { - lstats[i].nmalloc += arena->stats.lstats[i].nmalloc; - lstats[i].ndalloc += arena->stats.lstats[i].ndalloc; - lstats[i].nrequests += arena->stats.lstats[i].nrequests; - lstats[i].highruns += arena->stats.lstats[i].highruns; - lstats[i].curruns += arena->stats.lstats[i].curruns; - } - malloc_mutex_unlock(&arena->lock); - - for (i = 0; i < nbins; i++) { - arena_bin_t *bin = &arena->bins[i]; - - malloc_mutex_lock(&bin->lock); - bstats[i].allocated += bin->stats.allocated; - bstats[i].nmalloc += bin->stats.nmalloc; - bstats[i].ndalloc += bin->stats.ndalloc; - bstats[i].nrequests += bin->stats.nrequests; -#ifdef JEMALLOC_TCACHE - bstats[i].nfills += bin->stats.nfills; - bstats[i].nflushes += bin->stats.nflushes; -#endif - bstats[i].nruns += bin->stats.nruns; - bstats[i].reruns += bin->stats.reruns; - bstats[i].highruns += bin->stats.highruns; - bstats[i].curruns += bin->stats.curruns; - malloc_mutex_unlock(&bin->lock); - } -} -#endif - -void -arena_dalloc_large(arena_t *arena, arena_chunk_t *chunk, void *ptr) -{ - - /* Large allocation. */ -#ifdef JEMALLOC_FILL -# ifndef JEMALLOC_STATS - if (opt_junk) -# endif -#endif - { -#if (defined(JEMALLOC_FILL) || defined(JEMALLOC_STATS)) - size_t pageind = ((uintptr_t)ptr - (uintptr_t)chunk) >> - PAGE_SHIFT; - size_t size = chunk->map[pageind].bits & ~PAGE_MASK; -#endif - -#ifdef JEMALLOC_FILL -# ifdef JEMALLOC_STATS - if (opt_junk) -# endif - memset(ptr, 0x5a, size); -#endif -#ifdef JEMALLOC_STATS - arena->stats.ndalloc_large++; - arena->stats.allocated_large -= size; - arena->stats.lstats[(size >> PAGE_SHIFT) - 1].ndalloc++; - arena->stats.lstats[(size >> PAGE_SHIFT) - 1].curruns--; -#endif - } - - arena_run_dalloc(arena, (arena_run_t *)ptr, true); -} - -static void -arena_ralloc_large_shrink(arena_t *arena, arena_chunk_t *chunk, void *ptr, - size_t size, size_t oldsize) -{ - - assert(size < oldsize); - - /* - * Shrink the run, and make trailing pages available for other - * allocations. - */ - malloc_mutex_lock(&arena->lock); - arena_run_trim_tail(arena, chunk, (arena_run_t *)ptr, oldsize, size, - true); -#ifdef JEMALLOC_STATS - arena->stats.ndalloc_large++; - arena->stats.allocated_large -= oldsize; - arena->stats.lstats[(oldsize >> PAGE_SHIFT) - 1].ndalloc++; - arena->stats.lstats[(oldsize >> PAGE_SHIFT) - 1].curruns--; - - arena->stats.nmalloc_large++; - arena->stats.nrequests_large++; - arena->stats.allocated_large += size; - arena->stats.lstats[(size >> PAGE_SHIFT) - 1].nmalloc++; - arena->stats.lstats[(size >> PAGE_SHIFT) - 1].nrequests++; - arena->stats.lstats[(size >> PAGE_SHIFT) - 1].curruns++; - if (arena->stats.lstats[(size >> PAGE_SHIFT) - 1].curruns > - arena->stats.lstats[(size >> PAGE_SHIFT) - 1].highruns) { - arena->stats.lstats[(size >> PAGE_SHIFT) - 1].highruns = - arena->stats.lstats[(size >> PAGE_SHIFT) - 1].curruns; - } -#endif - malloc_mutex_unlock(&arena->lock); -} - -static bool -arena_ralloc_large_grow(arena_t *arena, arena_chunk_t *chunk, void *ptr, - size_t size, size_t oldsize) -{ - size_t pageind = ((uintptr_t)ptr - (uintptr_t)chunk) >> PAGE_SHIFT; - size_t npages = oldsize >> PAGE_SHIFT; - - assert(oldsize == (chunk->map[pageind].bits & ~PAGE_MASK)); - - /* Try to extend the run. */ - assert(size > oldsize); - malloc_mutex_lock(&arena->lock); - if (pageind + npages < chunk_npages && (chunk->map[pageind+npages].bits - & CHUNK_MAP_ALLOCATED) == 0 && (chunk->map[pageind+npages].bits & - ~PAGE_MASK) >= size - oldsize) { - /* - * The next run is available and sufficiently large. Split the - * following run, then merge the first part with the existing - * allocation. - */ - arena_run_split(arena, (arena_run_t *)((uintptr_t)chunk + - ((pageind+npages) << PAGE_SHIFT)), size - oldsize, true, - false); - - chunk->map[pageind].bits = size | CHUNK_MAP_LARGE | - CHUNK_MAP_ALLOCATED; - chunk->map[pageind+npages].bits = CHUNK_MAP_LARGE | - CHUNK_MAP_ALLOCATED; - -#ifdef JEMALLOC_STATS - arena->stats.ndalloc_large++; - arena->stats.allocated_large -= oldsize; - arena->stats.lstats[(oldsize >> PAGE_SHIFT) - 1].ndalloc++; - arena->stats.lstats[(oldsize >> PAGE_SHIFT) - 1].curruns--; - - arena->stats.nmalloc_large++; - arena->stats.nrequests_large++; - arena->stats.allocated_large += size; - arena->stats.lstats[(size >> PAGE_SHIFT) - 1].nmalloc++; - arena->stats.lstats[(size >> PAGE_SHIFT) - 1].nrequests++; - arena->stats.lstats[(size >> PAGE_SHIFT) - 1].curruns++; - if (arena->stats.lstats[(size >> PAGE_SHIFT) - 1].curruns > - arena->stats.lstats[(size >> PAGE_SHIFT) - 1].highruns) { - arena->stats.lstats[(size >> PAGE_SHIFT) - 1].highruns = - arena->stats.lstats[(size >> PAGE_SHIFT) - 1].curruns; - } -#endif - malloc_mutex_unlock(&arena->lock); - return (false); - } - malloc_mutex_unlock(&arena->lock); - - return (true); -} - -/* - * Try to resize a large allocation, in order to avoid copying. This will - * always fail if growing an object, and the following run is already in use. - */ -static bool -arena_ralloc_large(void *ptr, size_t size, size_t oldsize) -{ - size_t psize; - - psize = PAGE_CEILING(size); - if (psize == oldsize) { - /* Same size class. */ -#ifdef JEMALLOC_FILL - if (opt_junk && size < oldsize) { - memset((void *)((uintptr_t)ptr + size), 0x5a, oldsize - - size); - } -#endif - return (false); - } else { - arena_chunk_t *chunk; - arena_t *arena; - - chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); - arena = chunk->arena; - assert(arena->magic == ARENA_MAGIC); - - if (psize < oldsize) { -#ifdef JEMALLOC_FILL - /* Fill before shrinking in order avoid a race. */ - if (opt_junk) { - memset((void *)((uintptr_t)ptr + size), 0x5a, - oldsize - size); - } -#endif - arena_ralloc_large_shrink(arena, chunk, ptr, psize, - oldsize); - return (false); - } else { - bool ret = arena_ralloc_large_grow(arena, chunk, ptr, - psize, oldsize); -#ifdef JEMALLOC_FILL - if (ret == false && opt_zero) { - memset((void *)((uintptr_t)ptr + oldsize), 0, - size - oldsize); - } -#endif - return (ret); - } - } -} - -void * -arena_ralloc(void *ptr, size_t size, size_t oldsize) -{ - void *ret; - size_t copysize; - - /* Try to avoid moving the allocation. */ - if (oldsize <= arena_maxclass) { - if (oldsize <= small_maxclass) { - if (size <= small_maxclass && small_size2bin[size] == - small_size2bin[oldsize]) - goto IN_PLACE; - } else { - assert(size <= arena_maxclass); - if (size > small_maxclass) { - if (arena_ralloc_large(ptr, size, oldsize) == - false) - return (ptr); - } - } - } - - /* - * If we get here, then size and oldsize are different enough that we - * need to move the object. In that case, fall back to allocating new - * space and copying. - */ - ret = arena_malloc(size, false); - if (ret == NULL) - return (NULL); - - /* Junk/zero-filling were already done by arena_malloc(). */ - copysize = (size < oldsize) ? size : oldsize; - memcpy(ret, ptr, copysize); - idalloc(ptr); - return (ret); -IN_PLACE: -#ifdef JEMALLOC_FILL - if (opt_junk && size < oldsize) - memset((void *)((uintptr_t)ptr + size), 0x5a, oldsize - size); - else if (opt_zero && size > oldsize) - memset((void *)((uintptr_t)ptr + oldsize), 0, size - oldsize); -#endif - return (ptr); -} - -bool -arena_new(arena_t *arena, unsigned ind) -{ - unsigned i; - arena_bin_t *bin; - size_t prev_run_size; - - arena->ind = ind; - - if (malloc_mutex_init(&arena->lock)) - return (true); - -#ifdef JEMALLOC_STATS - memset(&arena->stats, 0, sizeof(arena_stats_t)); - arena->stats.lstats = (malloc_large_stats_t *)base_alloc(nlclasses * - sizeof(malloc_large_stats_t)); - if (arena->stats.lstats == NULL) - return (true); - memset(arena->stats.lstats, 0, nlclasses * - sizeof(malloc_large_stats_t)); -# ifdef JEMALLOC_TCACHE - ql_new(&arena->tcache_ql); -# endif -#endif - -#ifdef JEMALLOC_PROF - arena->prof_accumbytes = 0; -#endif - - /* Initialize chunks. */ - ql_new(&arena->chunks_dirty); - arena->spare = NULL; - - arena->nactive = 0; - arena->ndirty = 0; - arena->npurgatory = 0; - - arena_avail_tree_new(&arena->runs_avail_clean); - arena_avail_tree_new(&arena->runs_avail_dirty); - - /* Initialize bins. */ - prev_run_size = PAGE_SIZE; - - i = 0; -#ifdef JEMALLOC_TINY - /* (2^n)-spaced tiny bins. */ - for (; i < ntbins; i++) { - bin = &arena->bins[i]; - if (malloc_mutex_init(&bin->lock)) - return (true); - bin->runcur = NULL; - arena_run_tree_new(&bin->runs); - - bin->reg_size = (1U << (LG_TINY_MIN + i)); - - prev_run_size = arena_bin_run_size_calc(bin, prev_run_size); - -#ifdef JEMALLOC_STATS - memset(&bin->stats, 0, sizeof(malloc_bin_stats_t)); -#endif - } -#endif - - /* Quantum-spaced bins. */ - for (; i < ntbins + nqbins; i++) { - bin = &arena->bins[i]; - if (malloc_mutex_init(&bin->lock)) - return (true); - bin->runcur = NULL; - arena_run_tree_new(&bin->runs); - - bin->reg_size = (i - ntbins + 1) << LG_QUANTUM; - - prev_run_size = arena_bin_run_size_calc(bin, prev_run_size); - -#ifdef JEMALLOC_STATS - memset(&bin->stats, 0, sizeof(malloc_bin_stats_t)); -#endif - } - - /* Cacheline-spaced bins. */ - for (; i < ntbins + nqbins + ncbins; i++) { - bin = &arena->bins[i]; - if (malloc_mutex_init(&bin->lock)) - return (true); - bin->runcur = NULL; - arena_run_tree_new(&bin->runs); - - bin->reg_size = cspace_min + ((i - (ntbins + nqbins)) << - LG_CACHELINE); - - prev_run_size = arena_bin_run_size_calc(bin, prev_run_size); - -#ifdef JEMALLOC_STATS - memset(&bin->stats, 0, sizeof(malloc_bin_stats_t)); -#endif - } - - /* Subpage-spaced bins. */ - for (; i < nbins; i++) { - bin = &arena->bins[i]; - if (malloc_mutex_init(&bin->lock)) - return (true); - bin->runcur = NULL; - arena_run_tree_new(&bin->runs); - - bin->reg_size = sspace_min + ((i - (ntbins + nqbins + ncbins)) - << LG_SUBPAGE); - - prev_run_size = arena_bin_run_size_calc(bin, prev_run_size); - -#ifdef JEMALLOC_STATS - memset(&bin->stats, 0, sizeof(malloc_bin_stats_t)); -#endif - } - -#ifdef JEMALLOC_DEBUG - arena->magic = ARENA_MAGIC; -#endif - - return (false); -} - -#ifdef JEMALLOC_TINY -/* Compute the smallest power of 2 that is >= x. */ -static size_t -pow2_ceil(size_t x) -{ - - x--; - x |= x >> 1; - x |= x >> 2; - x |= x >> 4; - x |= x >> 8; - x |= x >> 16; -#if (SIZEOF_PTR == 8) - x |= x >> 32; -#endif - x++; - return (x); -} -#endif - -#ifdef JEMALLOC_DEBUG -static void -small_size2bin_validate(void) -{ - size_t i, size, binind; - - assert(small_size2bin[0] == 0xffU); - i = 1; -# ifdef JEMALLOC_TINY - /* Tiny. */ - for (; i < (1U << LG_TINY_MIN); i++) { - size = pow2_ceil(1U << LG_TINY_MIN); - binind = ffs((int)(size >> (LG_TINY_MIN + 1))); - assert(small_size2bin[i] == binind); - } - for (; i < qspace_min; i++) { - size = pow2_ceil(i); - binind = ffs((int)(size >> (LG_TINY_MIN + 1))); - assert(small_size2bin[i] == binind); - } -# endif - /* Quantum-spaced. */ - for (; i <= qspace_max; i++) { - size = QUANTUM_CEILING(i); - binind = ntbins + (size >> LG_QUANTUM) - 1; - assert(small_size2bin[i] == binind); - } - /* Cacheline-spaced. */ - for (; i <= cspace_max; i++) { - size = CACHELINE_CEILING(i); - binind = ntbins + nqbins + ((size - cspace_min) >> - LG_CACHELINE); - assert(small_size2bin[i] == binind); - } - /* Sub-page. */ - for (; i <= sspace_max; i++) { - size = SUBPAGE_CEILING(i); - binind = ntbins + nqbins + ncbins + ((size - sspace_min) - >> LG_SUBPAGE); - assert(small_size2bin[i] == binind); - } -} -#endif - -static bool -small_size2bin_init(void) -{ - - if (opt_lg_qspace_max != LG_QSPACE_MAX_DEFAULT - || opt_lg_cspace_max != LG_CSPACE_MAX_DEFAULT - || sizeof(const_small_size2bin) != small_maxclass + 1) - return (small_size2bin_init_hard()); - - small_size2bin = const_small_size2bin; -#ifdef JEMALLOC_DEBUG - assert(sizeof(const_small_size2bin) == small_maxclass + 1); - small_size2bin_validate(); -#endif - return (false); -} - -static bool -small_size2bin_init_hard(void) -{ - size_t i, size, binind; - uint8_t *custom_small_size2bin; - - assert(opt_lg_qspace_max != LG_QSPACE_MAX_DEFAULT - || opt_lg_cspace_max != LG_CSPACE_MAX_DEFAULT - || sizeof(const_small_size2bin) != small_maxclass + 1); - - custom_small_size2bin = (uint8_t *)base_alloc(small_maxclass + 1); - if (custom_small_size2bin == NULL) - return (true); - - custom_small_size2bin[0] = 0xffU; - i = 1; -#ifdef JEMALLOC_TINY - /* Tiny. */ - for (; i < (1U << LG_TINY_MIN); i++) { - size = pow2_ceil(1U << LG_TINY_MIN); - binind = ffs((int)(size >> (LG_TINY_MIN + 1))); - custom_small_size2bin[i] = binind; - } - for (; i < qspace_min; i++) { - size = pow2_ceil(i); - binind = ffs((int)(size >> (LG_TINY_MIN + 1))); - custom_small_size2bin[i] = binind; - } -#endif - /* Quantum-spaced. */ - for (; i <= qspace_max; i++) { - size = QUANTUM_CEILING(i); - binind = ntbins + (size >> LG_QUANTUM) - 1; - custom_small_size2bin[i] = binind; - } - /* Cacheline-spaced. */ - for (; i <= cspace_max; i++) { - size = CACHELINE_CEILING(i); - binind = ntbins + nqbins + ((size - cspace_min) >> - LG_CACHELINE); - custom_small_size2bin[i] = binind; - } - /* Sub-page. */ - for (; i <= sspace_max; i++) { - size = SUBPAGE_CEILING(i); - binind = ntbins + nqbins + ncbins + ((size - sspace_min) >> - LG_SUBPAGE); - custom_small_size2bin[i] = binind; - } - - small_size2bin = custom_small_size2bin; -#ifdef JEMALLOC_DEBUG - small_size2bin_validate(); -#endif - return (false); -} - -bool -arena_boot(void) -{ - size_t header_size; - - /* Set variables according to the value of opt_lg_[qc]space_max. */ - qspace_max = (1U << opt_lg_qspace_max); - cspace_min = CACHELINE_CEILING(qspace_max); - if (cspace_min == qspace_max) - cspace_min += CACHELINE; - cspace_max = (1U << opt_lg_cspace_max); - sspace_min = SUBPAGE_CEILING(cspace_max); - if (sspace_min == cspace_max) - sspace_min += SUBPAGE; - assert(sspace_min < PAGE_SIZE); - sspace_max = PAGE_SIZE - SUBPAGE; - -#ifdef JEMALLOC_TINY - assert(LG_QUANTUM >= LG_TINY_MIN); -#endif - assert(ntbins <= LG_QUANTUM); - nqbins = qspace_max >> LG_QUANTUM; - ncbins = ((cspace_max - cspace_min) >> LG_CACHELINE) + 1; - nsbins = ((sspace_max - sspace_min) >> LG_SUBPAGE) + 1; - nbins = ntbins + nqbins + ncbins + nsbins; - - /* - * The small_size2bin lookup table uses uint8_t to encode each bin - * index, so we cannot support more than 256 small size classes. This - * limit is difficult to exceed (not even possible with 16B quantum and - * 4KiB pages), and such configurations are impractical, but - * nonetheless we need to protect against this case in order to avoid - * undefined behavior. - * - * Further constrain nbins to 255 if prof_promote is true, since all - * small size classes, plus a "not small" size class must be stored in - * 8 bits of arena_chunk_map_t's bits field. - */ -#ifdef JEMALLOC_PROF - if (opt_prof && prof_promote) { - if (nbins > 255) { - char line_buf[UMAX2S_BUFSIZE]; - malloc_write(": Too many small size classes ("); - malloc_write(umax2s(nbins, 10, line_buf)); - malloc_write(" > max 255)\n"); - abort(); - } - } else -#endif - if (nbins > 256) { - char line_buf[UMAX2S_BUFSIZE]; - malloc_write(": Too many small size classes ("); - malloc_write(umax2s(nbins, 10, line_buf)); - malloc_write(" > max 256)\n"); - abort(); - } - - if (small_size2bin_init()) - return (true); - - /* - * Compute the header size such that it is large enough to contain the - * page map. - */ - header_size = sizeof(arena_chunk_t) + - (sizeof(arena_chunk_map_t) * (chunk_npages - 1)); - arena_chunk_header_npages = (header_size >> PAGE_SHIFT) + - ((header_size & PAGE_MASK) != 0); - arena_maxclass = chunksize - (arena_chunk_header_npages << PAGE_SHIFT); - - return (false); -} diff --git a/externals/jemalloc/base.c b/externals/jemalloc/base.c deleted file mode 100644 index 605197eaced..00000000000 --- a/externals/jemalloc/base.c +++ /dev/null @@ -1,106 +0,0 @@ -#define JEMALLOC_BASE_C_ -#include "jemalloc/internal/jemalloc_internal.h" - -/******************************************************************************/ -/* Data. */ - -malloc_mutex_t base_mtx; - -/* - * Current pages that are being used for internal memory allocations. These - * pages are carved up in cacheline-size quanta, so that there is no chance of - * false cache line sharing. - */ -static void *base_pages; -static void *base_next_addr; -static void *base_past_addr; /* Addr immediately past base_pages. */ -static extent_node_t *base_nodes; - -/******************************************************************************/ -/* Function prototypes for non-inline static functions. */ - -static bool base_pages_alloc(size_t minsize); - -/******************************************************************************/ - -static bool -base_pages_alloc(size_t minsize) -{ - size_t csize; - bool zero; - - assert(minsize != 0); - csize = CHUNK_CEILING(minsize); - zero = false; - base_pages = chunk_alloc(csize, &zero); - if (base_pages == NULL) - return (true); - base_next_addr = base_pages; - base_past_addr = (void *)((uintptr_t)base_pages + csize); - - return (false); -} - -void * -base_alloc(size_t size) -{ - void *ret; - size_t csize; - - /* Round size up to nearest multiple of the cacheline size. */ - csize = CACHELINE_CEILING(size); - - malloc_mutex_lock(&base_mtx); - /* Make sure there's enough space for the allocation. */ - if ((uintptr_t)base_next_addr + csize > (uintptr_t)base_past_addr) { - if (base_pages_alloc(csize)) { - malloc_mutex_unlock(&base_mtx); - return (NULL); - } - } - /* Allocate. */ - ret = base_next_addr; - base_next_addr = (void *)((uintptr_t)base_next_addr + csize); - malloc_mutex_unlock(&base_mtx); - - return (ret); -} - -extent_node_t * -base_node_alloc(void) -{ - extent_node_t *ret; - - malloc_mutex_lock(&base_mtx); - if (base_nodes != NULL) { - ret = base_nodes; - base_nodes = *(extent_node_t **)ret; - malloc_mutex_unlock(&base_mtx); - } else { - malloc_mutex_unlock(&base_mtx); - ret = (extent_node_t *)base_alloc(sizeof(extent_node_t)); - } - - return (ret); -} - -void -base_node_dealloc(extent_node_t *node) -{ - - malloc_mutex_lock(&base_mtx); - *(extent_node_t **)node = base_nodes; - base_nodes = node; - malloc_mutex_unlock(&base_mtx); -} - -bool -base_boot(void) -{ - - base_nodes = NULL; - if (malloc_mutex_init(&base_mtx)) - return (true); - - return (false); -} diff --git a/externals/jemalloc/chunk.c b/externals/jemalloc/chunk.c deleted file mode 100644 index e6e3bcd195a..00000000000 --- a/externals/jemalloc/chunk.c +++ /dev/null @@ -1,150 +0,0 @@ -#define JEMALLOC_CHUNK_C_ -#include "jemalloc/internal/jemalloc_internal.h" - -/******************************************************************************/ -/* Data. */ - -size_t opt_lg_chunk = LG_CHUNK_DEFAULT; -#ifdef JEMALLOC_SWAP -bool opt_overcommit = true; -#endif - -#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) -malloc_mutex_t chunks_mtx; -chunk_stats_t stats_chunks; -#endif - -/* Various chunk-related settings. */ -size_t chunksize; -size_t chunksize_mask; /* (chunksize - 1). */ -size_t chunk_npages; -size_t arena_chunk_header_npages; -size_t arena_maxclass; /* Max size class for arenas. */ - -/******************************************************************************/ - -/* - * If the caller specifies (*zero == false), it is still possible to receive - * zeroed memory, in which case *zero is toggled to true. arena_chunk_alloc() - * takes advantage of this to avoid demanding zeroed chunks, but taking - * advantage of them if they are returned. - */ -void * -chunk_alloc(size_t size, bool *zero) -{ - void *ret; - - assert(size != 0); - assert((size & chunksize_mask) == 0); - -#ifdef JEMALLOC_SWAP - if (swap_enabled) { - ret = chunk_alloc_swap(size, zero); - if (ret != NULL) - goto RETURN; - } - - if (swap_enabled == false || opt_overcommit) { -#endif -#ifdef JEMALLOC_DSS - ret = chunk_alloc_dss(size, zero); - if (ret != NULL) - goto RETURN; -#endif - ret = chunk_alloc_mmap(size); - if (ret != NULL) { - *zero = true; - goto RETURN; - } -#ifdef JEMALLOC_SWAP - } -#endif - - /* All strategies for allocation failed. */ - ret = NULL; -RETURN: -#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) - if (ret != NULL) { -# ifdef JEMALLOC_PROF - bool udump; -# endif - malloc_mutex_lock(&chunks_mtx); -# ifdef JEMALLOC_STATS - stats_chunks.nchunks += (size / chunksize); -# endif - stats_chunks.curchunks += (size / chunksize); - if (stats_chunks.curchunks > stats_chunks.highchunks) { - stats_chunks.highchunks = stats_chunks.curchunks; -# ifdef JEMALLOC_PROF - udump = true; -# endif - } -# ifdef JEMALLOC_PROF - else - udump = false; -# endif - malloc_mutex_unlock(&chunks_mtx); -# ifdef JEMALLOC_PROF - if (opt_prof && opt_prof_udump && udump) - prof_udump(); -# endif - } -#endif - - assert(CHUNK_ADDR2BASE(ret) == ret); - return (ret); -} - -void -chunk_dealloc(void *chunk, size_t size) -{ - - assert(chunk != NULL); - assert(CHUNK_ADDR2BASE(chunk) == chunk); - assert(size != 0); - assert((size & chunksize_mask) == 0); - -#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) - malloc_mutex_lock(&chunks_mtx); - stats_chunks.curchunks -= (size / chunksize); - malloc_mutex_unlock(&chunks_mtx); -#endif - -#ifdef JEMALLOC_SWAP - if (swap_enabled && chunk_dealloc_swap(chunk, size) == false) - return; -#endif -#ifdef JEMALLOC_DSS - if (chunk_dealloc_dss(chunk, size) == false) - return; -#endif - chunk_dealloc_mmap(chunk, size); -} - -bool -chunk_boot(void) -{ - - /* Set variables according to the value of opt_lg_chunk. */ - chunksize = (1LU << opt_lg_chunk); - assert(chunksize >= PAGE_SIZE); - chunksize_mask = chunksize - 1; - chunk_npages = (chunksize >> PAGE_SHIFT); - -#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) - if (malloc_mutex_init(&chunks_mtx)) - return (true); - memset(&stats_chunks, 0, sizeof(chunk_stats_t)); -#endif - -#ifdef JEMALLOC_SWAP - if (chunk_swap_boot()) - return (true); -#endif -#ifdef JEMALLOC_DSS - if (chunk_dss_boot()) - return (true); -#endif - - return (false); -} diff --git a/externals/jemalloc/chunk_dss.c b/externals/jemalloc/chunk_dss.c deleted file mode 100644 index d9bd63c3ac4..00000000000 --- a/externals/jemalloc/chunk_dss.c +++ /dev/null @@ -1,268 +0,0 @@ -#define JEMALLOC_CHUNK_DSS_C_ -#include "jemalloc/internal/jemalloc_internal.h" -#ifdef JEMALLOC_DSS -/******************************************************************************/ -/* Data. */ - -malloc_mutex_t dss_mtx; - -/* Base address of the DSS. */ -static void *dss_base; -/* Current end of the DSS, or ((void *)-1) if the DSS is exhausted. */ -static void *dss_prev; -/* Current upper limit on DSS addresses. */ -static void *dss_max; - -/* - * Trees of chunks that were previously allocated (trees differ only in node - * ordering). These are used when allocating chunks, in an attempt to re-use - * address space. Depending on function, different tree orderings are needed, - * which is why there are two trees with the same contents. - */ -static extent_tree_t dss_chunks_szad; -static extent_tree_t dss_chunks_ad; - -/******************************************************************************/ -/* Function prototypes for non-inline static functions. */ - -static void *chunk_recycle_dss(size_t size, bool *zero); -static extent_node_t *chunk_dealloc_dss_record(void *chunk, size_t size); - -/******************************************************************************/ - -static void * -chunk_recycle_dss(size_t size, bool *zero) -{ - extent_node_t *node, key; - - key.addr = NULL; - key.size = size; - malloc_mutex_lock(&dss_mtx); - node = extent_tree_szad_nsearch(&dss_chunks_szad, &key); - if (node != NULL) { - void *ret = node->addr; - - /* Remove node from the tree. */ - extent_tree_szad_remove(&dss_chunks_szad, node); - if (node->size == size) { - extent_tree_ad_remove(&dss_chunks_ad, node); - base_node_dealloc(node); - } else { - /* - * Insert the remainder of node's address range as a - * smaller chunk. Its position within dss_chunks_ad - * does not change. - */ - assert(node->size > size); - node->addr = (void *)((uintptr_t)node->addr + size); - node->size -= size; - extent_tree_szad_insert(&dss_chunks_szad, node); - } - malloc_mutex_unlock(&dss_mtx); - - if (*zero) - memset(ret, 0, size); - return (ret); - } - malloc_mutex_unlock(&dss_mtx); - - return (NULL); -} - -void * -chunk_alloc_dss(size_t size, bool *zero) -{ - void *ret; - - ret = chunk_recycle_dss(size, zero); - if (ret != NULL) - return (ret); - - /* - * sbrk() uses a signed increment argument, so take care not to - * interpret a huge allocation request as a negative increment. - */ - if ((intptr_t)size < 0) - return (NULL); - - malloc_mutex_lock(&dss_mtx); - if (dss_prev != (void *)-1) { - intptr_t incr; - - /* - * The loop is necessary to recover from races with other - * threads that are using the DSS for something other than - * malloc. - */ - do { - /* Get the current end of the DSS. */ - dss_max = sbrk(0); - - /* - * Calculate how much padding is necessary to - * chunk-align the end of the DSS. - */ - incr = (intptr_t)size - - (intptr_t)CHUNK_ADDR2OFFSET(dss_max); - if (incr == (intptr_t)size) - ret = dss_max; - else { - ret = (void *)((intptr_t)dss_max + incr); - incr += size; - } - - dss_prev = sbrk(incr); - if (dss_prev == dss_max) { - /* Success. */ - dss_max = (void *)((intptr_t)dss_prev + incr); - malloc_mutex_unlock(&dss_mtx); - *zero = true; - return (ret); - } - } while (dss_prev != (void *)-1); - } - malloc_mutex_unlock(&dss_mtx); - - return (NULL); -} - -static extent_node_t * -chunk_dealloc_dss_record(void *chunk, size_t size) -{ - extent_node_t *xnode, *node, *prev, key; - - xnode = NULL; - while (true) { - key.addr = (void *)((uintptr_t)chunk + size); - node = extent_tree_ad_nsearch(&dss_chunks_ad, &key); - /* Try to coalesce forward. */ - if (node != NULL && node->addr == key.addr) { - /* - * Coalesce chunk with the following address range. - * This does not change the position within - * dss_chunks_ad, so only remove/insert from/into - * dss_chunks_szad. - */ - extent_tree_szad_remove(&dss_chunks_szad, node); - node->addr = chunk; - node->size += size; - extent_tree_szad_insert(&dss_chunks_szad, node); - break; - } else if (xnode == NULL) { - /* - * It is possible that base_node_alloc() will cause a - * new base chunk to be allocated, so take care not to - * deadlock on dss_mtx, and recover if another thread - * deallocates an adjacent chunk while this one is busy - * allocating xnode. - */ - malloc_mutex_unlock(&dss_mtx); - xnode = base_node_alloc(); - malloc_mutex_lock(&dss_mtx); - if (xnode == NULL) - return (NULL); - } else { - /* Coalescing forward failed, so insert a new node. */ - node = xnode; - xnode = NULL; - node->addr = chunk; - node->size = size; - extent_tree_ad_insert(&dss_chunks_ad, node); - extent_tree_szad_insert(&dss_chunks_szad, node); - break; - } - } - /* Discard xnode if it ended up unused do to a race. */ - if (xnode != NULL) - base_node_dealloc(xnode); - - /* Try to coalesce backward. */ - prev = extent_tree_ad_prev(&dss_chunks_ad, node); - if (prev != NULL && (void *)((uintptr_t)prev->addr + prev->size) == - chunk) { - /* - * Coalesce chunk with the previous address range. This does - * not change the position within dss_chunks_ad, so only - * remove/insert node from/into dss_chunks_szad. - */ - extent_tree_szad_remove(&dss_chunks_szad, prev); - extent_tree_ad_remove(&dss_chunks_ad, prev); - - extent_tree_szad_remove(&dss_chunks_szad, node); - node->addr = prev->addr; - node->size += prev->size; - extent_tree_szad_insert(&dss_chunks_szad, node); - - base_node_dealloc(prev); - } - - return (node); -} - -bool -chunk_dealloc_dss(void *chunk, size_t size) -{ - bool ret; - - malloc_mutex_lock(&dss_mtx); - if ((uintptr_t)chunk >= (uintptr_t)dss_base - && (uintptr_t)chunk < (uintptr_t)dss_max) { - extent_node_t *node; - - /* Try to coalesce with other unused chunks. */ - node = chunk_dealloc_dss_record(chunk, size); - if (node != NULL) { - chunk = node->addr; - size = node->size; - } - - /* Get the current end of the DSS. */ - dss_max = sbrk(0); - - /* - * Try to shrink the DSS if this chunk is at the end of the - * DSS. The sbrk() call here is subject to a race condition - * with threads that use brk(2) or sbrk(2) directly, but the - * alternative would be to leak memory for the sake of poorly - * designed multi-threaded programs. - */ - if ((void *)((uintptr_t)chunk + size) == dss_max - && (dss_prev = sbrk(-(intptr_t)size)) == dss_max) { - /* Success. */ - dss_max = (void *)((intptr_t)dss_prev - (intptr_t)size); - - if (node != NULL) { - extent_tree_szad_remove(&dss_chunks_szad, node); - extent_tree_ad_remove(&dss_chunks_ad, node); - base_node_dealloc(node); - } - } else - madvise(chunk, size, MADV_DONTNEED); - - ret = false; - goto RETURN; - } - - ret = true; -RETURN: - malloc_mutex_unlock(&dss_mtx); - return (ret); -} - -bool -chunk_dss_boot(void) -{ - - if (malloc_mutex_init(&dss_mtx)) - return (true); - dss_base = sbrk(0); - dss_prev = dss_base; - dss_max = dss_base; - extent_tree_szad_new(&dss_chunks_szad); - extent_tree_ad_new(&dss_chunks_ad); - - return (false); -} - -/******************************************************************************/ -#endif /* JEMALLOC_DSS */ diff --git a/externals/jemalloc/chunk_mmap.c b/externals/jemalloc/chunk_mmap.c deleted file mode 100644 index 8f0711384e3..00000000000 --- a/externals/jemalloc/chunk_mmap.c +++ /dev/null @@ -1,201 +0,0 @@ -#define JEMALLOC_CHUNK_MMAP_C_ -#include "jemalloc/internal/jemalloc_internal.h" - -/******************************************************************************/ -/* Data. */ - -/* - * Used by chunk_alloc_mmap() to decide whether to attempt the fast path and - * potentially avoid some system calls. We can get away without TLS here, - * since the state of mmap_unaligned only affects performance, rather than - * correct function. - */ -static -#ifndef NO_TLS - __thread -#endif - bool mmap_unaligned -#ifndef NO_TLS - JEMALLOC_ATTR(tls_model("initial-exec")) -#endif - ; - -/******************************************************************************/ -/* Function prototypes for non-inline static functions. */ - -static void *pages_map(void *addr, size_t size); -static void pages_unmap(void *addr, size_t size); -static void *chunk_alloc_mmap_slow(size_t size, bool unaligned); - -/******************************************************************************/ - -static void * -pages_map(void *addr, size_t size) -{ - void *ret; - - /* - * We don't use MAP_FIXED here, because it can cause the *replacement* - * of existing mappings, and we only want to create new mappings. - */ - ret = mmap(addr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, - -1, 0); - assert(ret != NULL); - - if (ret == MAP_FAILED) - ret = NULL; - else if (addr != NULL && ret != addr) { - /* - * We succeeded in mapping memory, but not in the right place. - */ - if (munmap(ret, size) == -1) { - char buf[STRERROR_BUF]; - - strerror_r(errno, buf, sizeof(buf)); - malloc_write(": Error in munmap(): "); - malloc_write(buf); - malloc_write("\n"); - if (opt_abort) - abort(); - } - ret = NULL; - } - - assert(ret == NULL || (addr == NULL && ret != addr) - || (addr != NULL && ret == addr)); - return (ret); -} - -static void -pages_unmap(void *addr, size_t size) -{ - - if (munmap(addr, size) == -1) { - char buf[STRERROR_BUF]; - - strerror_r(errno, buf, sizeof(buf)); - malloc_write(": Error in munmap(): "); - malloc_write(buf); - malloc_write("\n"); - if (opt_abort) - abort(); - } -} - -static void * -chunk_alloc_mmap_slow(size_t size, bool unaligned) -{ - void *ret; - size_t offset; - - /* Beware size_t wrap-around. */ - if (size + chunksize <= size) - return (NULL); - - ret = pages_map(NULL, size + chunksize); - if (ret == NULL) - return (NULL); - - /* Clean up unneeded leading/trailing space. */ - offset = CHUNK_ADDR2OFFSET(ret); - if (offset != 0) { - /* Note that mmap() returned an unaligned mapping. */ - unaligned = true; - - /* Leading space. */ - pages_unmap(ret, chunksize - offset); - - ret = (void *)((uintptr_t)ret + - (chunksize - offset)); - - /* Trailing space. */ - pages_unmap((void *)((uintptr_t)ret + size), - offset); - } else { - /* Trailing space only. */ - pages_unmap((void *)((uintptr_t)ret + size), - chunksize); - } - - /* - * If mmap() returned an aligned mapping, reset mmap_unaligned so that - * the next chunk_alloc_mmap() execution tries the fast allocation - * method. - */ - if (unaligned == false) - mmap_unaligned = false; - - return (ret); -} - -void * -chunk_alloc_mmap(size_t size) -{ - void *ret; - - /* - * Ideally, there would be a way to specify alignment to mmap() (like - * NetBSD has), but in the absence of such a feature, we have to work - * hard to efficiently create aligned mappings. The reliable, but - * slow method is to create a mapping that is over-sized, then trim the - * excess. However, that always results in at least one call to - * pages_unmap(). - * - * A more optimistic approach is to try mapping precisely the right - * amount, then try to append another mapping if alignment is off. In - * practice, this works out well as long as the application is not - * interleaving mappings via direct mmap() calls. If we do run into a - * situation where there is an interleaved mapping and we are unable to - * extend an unaligned mapping, our best option is to switch to the - * slow method until mmap() returns another aligned mapping. This will - * tend to leave a gap in the memory map that is too small to cause - * later problems for the optimistic method. - * - * Another possible confounding factor is address space layout - * randomization (ASLR), which causes mmap(2) to disregard the - * requested address. mmap_unaligned tracks whether the previous - * chunk_alloc_mmap() execution received any unaligned or relocated - * mappings, and if so, the current execution will immediately fall - * back to the slow method. However, we keep track of whether the fast - * method would have succeeded, and if so, we make a note to try the - * fast method next time. - */ - - if (mmap_unaligned == false) { - size_t offset; - - ret = pages_map(NULL, size); - if (ret == NULL) - return (NULL); - - offset = CHUNK_ADDR2OFFSET(ret); - if (offset != 0) { - mmap_unaligned = true; - /* Try to extend chunk boundary. */ - if (pages_map((void *)((uintptr_t)ret + size), - chunksize - offset) == NULL) { - /* - * Extension failed. Clean up, then revert to - * the reliable-but-expensive method. - */ - pages_unmap(ret, size); - ret = chunk_alloc_mmap_slow(size, true); - } else { - /* Clean up unneeded leading space. */ - pages_unmap(ret, chunksize - offset); - ret = (void *)((uintptr_t)ret + (chunksize - - offset)); - } - } - } else - ret = chunk_alloc_mmap_slow(size, false); - - return (ret); -} - -void -chunk_dealloc_mmap(void *chunk, size_t size) -{ - - pages_unmap(chunk, size); -} diff --git a/externals/jemalloc/chunk_swap.c b/externals/jemalloc/chunk_swap.c deleted file mode 100644 index b8c880f0a17..00000000000 --- a/externals/jemalloc/chunk_swap.c +++ /dev/null @@ -1,383 +0,0 @@ -#define JEMALLOC_CHUNK_SWAP_C_ -#include "jemalloc/internal/jemalloc_internal.h" -#ifdef JEMALLOC_SWAP -/******************************************************************************/ -/* Data. */ - -malloc_mutex_t swap_mtx; -bool swap_enabled; -bool swap_prezeroed; -size_t swap_nfds; -int *swap_fds; -#ifdef JEMALLOC_STATS -size_t swap_avail; -#endif - -/* Base address of the mmap()ed file(s). */ -static void *swap_base; -/* Current end of the space in use (<= swap_max). */ -static void *swap_end; -/* Absolute upper limit on file-backed addresses. */ -static void *swap_max; - -/* - * Trees of chunks that were previously allocated (trees differ only in node - * ordering). These are used when allocating chunks, in an attempt to re-use - * address space. Depending on function, different tree orderings are needed, - * which is why there are two trees with the same contents. - */ -static extent_tree_t swap_chunks_szad; -static extent_tree_t swap_chunks_ad; - -/******************************************************************************/ -/* Function prototypes for non-inline static functions. */ - -static void *chunk_recycle_swap(size_t size, bool *zero); -static extent_node_t *chunk_dealloc_swap_record(void *chunk, size_t size); - -/******************************************************************************/ - -static void * -chunk_recycle_swap(size_t size, bool *zero) -{ - extent_node_t *node, key; - - key.addr = NULL; - key.size = size; - malloc_mutex_lock(&swap_mtx); - node = extent_tree_szad_nsearch(&swap_chunks_szad, &key); - if (node != NULL) { - void *ret = node->addr; - - /* Remove node from the tree. */ - extent_tree_szad_remove(&swap_chunks_szad, node); - if (node->size == size) { - extent_tree_ad_remove(&swap_chunks_ad, node); - base_node_dealloc(node); - } else { - /* - * Insert the remainder of node's address range as a - * smaller chunk. Its position within swap_chunks_ad - * does not change. - */ - assert(node->size > size); - node->addr = (void *)((uintptr_t)node->addr + size); - node->size -= size; - extent_tree_szad_insert(&swap_chunks_szad, node); - } -#ifdef JEMALLOC_STATS - swap_avail -= size; -#endif - malloc_mutex_unlock(&swap_mtx); - - if (*zero) - memset(ret, 0, size); - return (ret); - } - malloc_mutex_unlock(&swap_mtx); - - return (NULL); -} - -void * -chunk_alloc_swap(size_t size, bool *zero) -{ - void *ret; - - assert(swap_enabled); - - ret = chunk_recycle_swap(size, zero); - if (ret != NULL) - return (ret); - - malloc_mutex_lock(&swap_mtx); - if ((uintptr_t)swap_end + size <= (uintptr_t)swap_max) { - ret = swap_end; - swap_end = (void *)((uintptr_t)swap_end + size); -#ifdef JEMALLOC_STATS - swap_avail -= size; -#endif - malloc_mutex_unlock(&swap_mtx); - - if (swap_prezeroed) - *zero = true; - else if (*zero) - memset(ret, 0, size); - } else { - malloc_mutex_unlock(&swap_mtx); - return (NULL); - } - - return (ret); -} - -static extent_node_t * -chunk_dealloc_swap_record(void *chunk, size_t size) -{ - extent_node_t *xnode, *node, *prev, key; - - xnode = NULL; - while (true) { - key.addr = (void *)((uintptr_t)chunk + size); - node = extent_tree_ad_nsearch(&swap_chunks_ad, &key); - /* Try to coalesce forward. */ - if (node != NULL && node->addr == key.addr) { - /* - * Coalesce chunk with the following address range. - * This does not change the position within - * swap_chunks_ad, so only remove/insert from/into - * swap_chunks_szad. - */ - extent_tree_szad_remove(&swap_chunks_szad, node); - node->addr = chunk; - node->size += size; - extent_tree_szad_insert(&swap_chunks_szad, node); - break; - } else if (xnode == NULL) { - /* - * It is possible that base_node_alloc() will cause a - * new base chunk to be allocated, so take care not to - * deadlock on swap_mtx, and recover if another thread - * deallocates an adjacent chunk while this one is busy - * allocating xnode. - */ - malloc_mutex_unlock(&swap_mtx); - xnode = base_node_alloc(); - malloc_mutex_lock(&swap_mtx); - if (xnode == NULL) - return (NULL); - } else { - /* Coalescing forward failed, so insert a new node. */ - node = xnode; - xnode = NULL; - node->addr = chunk; - node->size = size; - extent_tree_ad_insert(&swap_chunks_ad, node); - extent_tree_szad_insert(&swap_chunks_szad, node); - break; - } - } - /* Discard xnode if it ended up unused do to a race. */ - if (xnode != NULL) - base_node_dealloc(xnode); - - /* Try to coalesce backward. */ - prev = extent_tree_ad_prev(&swap_chunks_ad, node); - if (prev != NULL && (void *)((uintptr_t)prev->addr + prev->size) == - chunk) { - /* - * Coalesce chunk with the previous address range. This does - * not change the position within swap_chunks_ad, so only - * remove/insert node from/into swap_chunks_szad. - */ - extent_tree_szad_remove(&swap_chunks_szad, prev); - extent_tree_ad_remove(&swap_chunks_ad, prev); - - extent_tree_szad_remove(&swap_chunks_szad, node); - node->addr = prev->addr; - node->size += prev->size; - extent_tree_szad_insert(&swap_chunks_szad, node); - - base_node_dealloc(prev); - } - - return (node); -} - -bool -chunk_dealloc_swap(void *chunk, size_t size) -{ - bool ret; - - assert(swap_enabled); - - malloc_mutex_lock(&swap_mtx); - if ((uintptr_t)chunk >= (uintptr_t)swap_base - && (uintptr_t)chunk < (uintptr_t)swap_max) { - extent_node_t *node; - - /* Try to coalesce with other unused chunks. */ - node = chunk_dealloc_swap_record(chunk, size); - if (node != NULL) { - chunk = node->addr; - size = node->size; - } - - /* - * Try to shrink the in-use memory if this chunk is at the end - * of the in-use memory. - */ - if ((void *)((uintptr_t)chunk + size) == swap_end) { - swap_end = (void *)((uintptr_t)swap_end - size); - - if (node != NULL) { - extent_tree_szad_remove(&swap_chunks_szad, - node); - extent_tree_ad_remove(&swap_chunks_ad, node); - base_node_dealloc(node); - } - } else - madvise(chunk, size, MADV_DONTNEED); - - ret = false; - goto RETURN; - } - - ret = true; -RETURN: -#ifdef JEMALLOC_STATS - swap_avail += size; -#endif - malloc_mutex_unlock(&swap_mtx); - return (ret); -} - -bool -chunk_swap_enable(const int *fds, unsigned nfds, bool prezeroed) -{ - bool ret; - unsigned i; - off_t off; - void *vaddr; - size_t cumsize, voff; - size_t sizes[nfds]; - - malloc_mutex_lock(&swap_mtx); - - /* Get file sizes. */ - for (i = 0, cumsize = 0; i < nfds; i++) { - off = lseek(fds[i], 0, SEEK_END); - if (off == ((off_t)-1)) { - ret = true; - goto RETURN; - } - if (PAGE_CEILING(off) != off) { - /* Truncate to a multiple of the page size. */ - off &= ~PAGE_MASK; - if (ftruncate(fds[i], off) != 0) { - ret = true; - goto RETURN; - } - } - sizes[i] = off; - if (cumsize + off < cumsize) { - /* - * Cumulative file size is greater than the total - * address space. Bail out while it's still obvious - * what the problem is. - */ - ret = true; - goto RETURN; - } - cumsize += off; - } - - /* Round down to a multiple of the chunk size. */ - cumsize &= ~chunksize_mask; - if (cumsize == 0) { - ret = true; - goto RETURN; - } - - /* - * Allocate a chunk-aligned region of anonymous memory, which will - * be the final location for the memory-mapped files. - */ - vaddr = chunk_alloc_mmap(cumsize); - if (vaddr == NULL) { - ret = true; - goto RETURN; - } - - /* Overlay the files onto the anonymous mapping. */ - for (i = 0, voff = 0; i < nfds; i++) { - void *addr = mmap((void *)((uintptr_t)vaddr + voff), sizes[i], - PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fds[i], 0); - if (addr == MAP_FAILED) { - char buf[STRERROR_BUF]; - - strerror_r(errno, buf, sizeof(buf)); - malloc_write( - ": Error in mmap(..., MAP_FIXED, ...): "); - malloc_write(buf); - malloc_write("\n"); - if (opt_abort) - abort(); - if (munmap(vaddr, voff) == -1) { - strerror_r(errno, buf, sizeof(buf)); - malloc_write(": Error in munmap(): "); - malloc_write(buf); - malloc_write("\n"); - } - ret = true; - goto RETURN; - } - assert(addr == (void *)((uintptr_t)vaddr + voff)); - - /* - * Tell the kernel that the mapping will be accessed randomly, - * and that it should not gratuitously sync pages to the - * filesystem. - */ -#ifdef MADV_RANDOM - madvise(addr, sizes[i], MADV_RANDOM); -#endif -#ifdef MADV_NOSYNC - madvise(addr, sizes[i], MADV_NOSYNC); -#endif - - voff += sizes[i]; - } - - swap_prezeroed = prezeroed; - swap_base = vaddr; - swap_end = swap_base; - swap_max = (void *)((uintptr_t)vaddr + cumsize); - - /* Copy the fds array for mallctl purposes. */ - swap_fds = (int *)base_alloc(nfds * sizeof(int)); - if (swap_fds == NULL) { - ret = true; - goto RETURN; - } - memcpy(swap_fds, fds, nfds * sizeof(int)); - swap_nfds = nfds; - -#ifdef JEMALLOC_STATS - swap_avail = cumsize; -#endif - - swap_enabled = true; - - ret = false; -RETURN: - malloc_mutex_unlock(&swap_mtx); - return (ret); -} - -bool -chunk_swap_boot(void) -{ - - if (malloc_mutex_init(&swap_mtx)) - return (true); - - swap_enabled = false; - swap_prezeroed = false; /* swap.* mallctl's depend on this. */ - swap_nfds = 0; - swap_fds = NULL; -#ifdef JEMALLOC_STATS - swap_avail = 0; -#endif - swap_base = NULL; - swap_end = NULL; - swap_max = NULL; - - extent_tree_szad_new(&swap_chunks_szad); - extent_tree_ad_new(&swap_chunks_ad); - - return (false); -} - -/******************************************************************************/ -#endif /* JEMALLOC_SWAP */ diff --git a/externals/jemalloc/ckh.c b/externals/jemalloc/ckh.c deleted file mode 100644 index a0c4162aa19..00000000000 --- a/externals/jemalloc/ckh.c +++ /dev/null @@ -1,601 +0,0 @@ -/* - ******************************************************************************* - * Implementation of (2^1+,2) cuckoo hashing, where 2^1+ indicates that each - * hash bucket contains 2^n cells, for n >= 1, and 2 indicates that two hash - * functions are employed. The original cuckoo hashing algorithm was described - * in: - * - * Pagh, R., F.F. Rodler (2004) Cuckoo Hashing. Journal of Algorithms - * 51(2):122-144. - * - * Generalization of cuckoo hashing was discussed in: - * - * Erlingsson, U., M. Manasse, F. McSherry (2006) A cool and practical - * alternative to traditional hash tables. In Proceedings of the 7th - * Workshop on Distributed Data and Structures (WDAS'06), Santa Clara, CA, - * January 2006. - * - * This implementation uses precisely two hash functions because that is the - * fewest that can work, and supporting multiple hashes is an implementation - * burden. Here is a reproduction of Figure 1 from Erlingsson et al. (2006) - * that shows approximate expected maximum load factors for various - * configurations: - * - * | #cells/bucket | - * #hashes | 1 | 2 | 4 | 8 | - * --------+-------+-------+-------+-------+ - * 1 | 0.006 | 0.006 | 0.03 | 0.12 | - * 2 | 0.49 | 0.86 |>0.93< |>0.96< | - * 3 | 0.91 | 0.97 | 0.98 | 0.999 | - * 4 | 0.97 | 0.99 | 0.999 | | - * - * The number of cells per bucket is chosen such that a bucket fits in one cache - * line. So, on 32- and 64-bit systems, we use (8,2) and (4,2) cuckoo hashing, - * respectively. - * - ******************************************************************************/ -#define CKH_C_ -#include "jemalloc/internal/jemalloc_internal.h" - -/******************************************************************************/ -/* Function prototypes for non-inline static functions. */ - -static bool ckh_grow(ckh_t *ckh); -static void ckh_shrink(ckh_t *ckh); - -/******************************************************************************/ - -/* - * Search bucket for key and return the cell number if found; SIZE_T_MAX - * otherwise. - */ -JEMALLOC_INLINE size_t -ckh_bucket_search(ckh_t *ckh, size_t bucket, const void *key) -{ - ckhc_t *cell; - unsigned i; - - for (i = 0; i < (ZU(1) << LG_CKH_BUCKET_CELLS); i++) { - cell = &ckh->tab[(bucket << LG_CKH_BUCKET_CELLS) + i]; - if (cell->key != NULL && ckh->keycomp(key, cell->key)) - return ((bucket << LG_CKH_BUCKET_CELLS) + i); - } - - return (SIZE_T_MAX); -} - -/* - * Search table for key and return cell number if found; SIZE_T_MAX otherwise. - */ -JEMALLOC_INLINE size_t -ckh_isearch(ckh_t *ckh, const void *key) -{ - size_t hash1, hash2, bucket, cell; - - assert(ckh != NULL); - assert(ckh->magic = CKH_MAGIG); - - ckh->hash(key, ckh->lg_curbuckets, &hash1, &hash2); - - /* Search primary bucket. */ - bucket = hash1 & ((ZU(1) << ckh->lg_curbuckets) - 1); - cell = ckh_bucket_search(ckh, bucket, key); - if (cell != SIZE_T_MAX) - return (cell); - - /* Search secondary bucket. */ - bucket = hash2 & ((ZU(1) << ckh->lg_curbuckets) - 1); - cell = ckh_bucket_search(ckh, bucket, key); - return (cell); -} - -JEMALLOC_INLINE bool -ckh_try_bucket_insert(ckh_t *ckh, size_t bucket, const void *key, - const void *data) -{ - ckhc_t *cell; - unsigned offset, i; - - /* - * Cycle through the cells in the bucket, starting at a random position. - * The randomness avoids worst-case search overhead as buckets fill up. - */ - prn32(offset, LG_CKH_BUCKET_CELLS, ckh->prn_state, CKH_A, CKH_C); - for (i = 0; i < (ZU(1) << LG_CKH_BUCKET_CELLS); i++) { - cell = &ckh->tab[(bucket << LG_CKH_BUCKET_CELLS) + - ((i + offset) & ((ZU(1) << LG_CKH_BUCKET_CELLS) - 1))]; - if (cell->key == NULL) { - cell->key = key; - cell->data = data; - ckh->count++; - return (false); - } - } - - return (true); -} - -/* - * No space is available in bucket. Randomly evict an item, then try to find an - * alternate location for that item. Iteratively repeat this - * eviction/relocation procedure until either success or detection of an - * eviction/relocation bucket cycle. - */ -JEMALLOC_INLINE bool -ckh_evict_reloc_insert(ckh_t *ckh, size_t argbucket, void const **argkey, - void const **argdata) -{ - const void *key, *data, *tkey, *tdata; - ckhc_t *cell; - size_t hash1, hash2, bucket, tbucket; - unsigned i; - - bucket = argbucket; - key = *argkey; - data = *argdata; - while (true) { - /* - * Choose a random item within the bucket to evict. This is - * critical to correct function, because without (eventually) - * evicting all items within a bucket during iteration, it - * would be possible to get stuck in an infinite loop if there - * were an item for which both hashes indicated the same - * bucket. - */ - prn32(i, LG_CKH_BUCKET_CELLS, ckh->prn_state, CKH_A, CKH_C); - cell = &ckh->tab[(bucket << LG_CKH_BUCKET_CELLS) + i]; - assert(cell->key != NULL); - - /* Swap cell->{key,data} and {key,data} (evict). */ - tkey = cell->key; tdata = cell->data; - cell->key = key; cell->data = data; - key = tkey; data = tdata; - -#ifdef CKH_COUNT - ckh->nrelocs++; -#endif - - /* Find the alternate bucket for the evicted item. */ - ckh->hash(key, ckh->lg_curbuckets, &hash1, &hash2); - tbucket = hash2 & ((ZU(1) << ckh->lg_curbuckets) - 1); - if (tbucket == bucket) { - tbucket = hash1 & ((ZU(1) << ckh->lg_curbuckets) - 1); - /* - * It may be that (tbucket == bucket) still, if the - * item's hashes both indicate this bucket. However, - * we are guaranteed to eventually escape this bucket - * during iteration, assuming pseudo-random item - * selection (true randomness would make infinite - * looping a remote possibility). The reason we can - * never get trapped forever is that there are two - * cases: - * - * 1) This bucket == argbucket, so we will quickly - * detect an eviction cycle and terminate. - * 2) An item was evicted to this bucket from another, - * which means that at least one item in this bucket - * has hashes that indicate distinct buckets. - */ - } - /* Check for a cycle. */ - if (tbucket == argbucket) { - *argkey = key; - *argdata = data; - return (true); - } - - bucket = tbucket; - if (ckh_try_bucket_insert(ckh, bucket, key, data) == false) - return (false); - } -} - -JEMALLOC_INLINE bool -ckh_try_insert(ckh_t *ckh, void const**argkey, void const**argdata) -{ - size_t hash1, hash2, bucket; - const void *key = *argkey; - const void *data = *argdata; - - ckh->hash(key, ckh->lg_curbuckets, &hash1, &hash2); - - /* Try to insert in primary bucket. */ - bucket = hash1 & ((ZU(1) << ckh->lg_curbuckets) - 1); - if (ckh_try_bucket_insert(ckh, bucket, key, data) == false) - return (false); - - /* Try to insert in secondary bucket. */ - bucket = hash2 & ((ZU(1) << ckh->lg_curbuckets) - 1); - if (ckh_try_bucket_insert(ckh, bucket, key, data) == false) - return (false); - - /* - * Try to find a place for this item via iterative eviction/relocation. - */ - return (ckh_evict_reloc_insert(ckh, bucket, argkey, argdata)); -} - -/* - * Try to rebuild the hash table from scratch by inserting all items from the - * old table into the new. - */ -JEMALLOC_INLINE bool -ckh_rebuild(ckh_t *ckh, ckhc_t *aTab) -{ - size_t count, i, nins; - const void *key, *data; - - count = ckh->count; - ckh->count = 0; - for (i = nins = 0; nins < count; i++) { - if (aTab[i].key != NULL) { - key = aTab[i].key; - data = aTab[i].data; - if (ckh_try_insert(ckh, &key, &data)) { - ckh->count = count; - return (true); - } - nins++; - } - } - - return (false); -} - -static bool -ckh_grow(ckh_t *ckh) -{ - bool ret; - ckhc_t *tab, *ttab; - size_t lg_curcells; - unsigned lg_prevbuckets; - -#ifdef CKH_COUNT - ckh->ngrows++; -#endif - - /* - * It is possible (though unlikely, given well behaved hashes) that the - * table will have to be doubled more than once in order to create a - * usable table. - */ - lg_prevbuckets = ckh->lg_curbuckets; - lg_curcells = ckh->lg_curbuckets + LG_CKH_BUCKET_CELLS; - while (true) { - lg_curcells++; - tab = (ckhc_t *) ipalloc((ZU(1) << LG_CACHELINE), - sizeof(ckhc_t) << lg_curcells); - if (tab == NULL) { - ret = true; - goto RETURN; - } - memset(tab, 0, sizeof(ckhc_t) << lg_curcells); - /* Swap in new table. */ - ttab = ckh->tab; - ckh->tab = tab; - tab = ttab; - ckh->lg_curbuckets = lg_curcells - LG_CKH_BUCKET_CELLS; - - if (ckh_rebuild(ckh, tab) == false) { - idalloc(tab); - break; - } - - /* Rebuilding failed, so back out partially rebuilt table. */ - idalloc(ckh->tab); - ckh->tab = tab; - ckh->lg_curbuckets = lg_prevbuckets; - } - - ret = false; -RETURN: - return (ret); -} - -static void -ckh_shrink(ckh_t *ckh) -{ - ckhc_t *tab, *ttab; - size_t lg_curcells; - unsigned lg_prevbuckets; - - /* - * It is possible (though unlikely, given well behaved hashes) that the - * table rebuild will fail. - */ - lg_prevbuckets = ckh->lg_curbuckets; - lg_curcells = ckh->lg_curbuckets + LG_CKH_BUCKET_CELLS - 1; - tab = (ckhc_t *)ipalloc((ZU(1) << LG_CACHELINE), - sizeof(ckhc_t) << lg_curcells); - if (tab == NULL) { - /* - * An OOM error isn't worth propagating, since it doesn't - * prevent this or future operations from proceeding. - */ - return; - } - memset(tab, 0, sizeof(ckhc_t) << lg_curcells); - /* Swap in new table. */ - ttab = ckh->tab; - ckh->tab = tab; - tab = ttab; - ckh->lg_curbuckets = lg_curcells - LG_CKH_BUCKET_CELLS; - - if (ckh_rebuild(ckh, tab) == false) { - idalloc(tab); -#ifdef CKH_COUNT - ckh->nshrinks++; -#endif - return; - } - - /* Rebuilding failed, so back out partially rebuilt table. */ - idalloc(ckh->tab); - ckh->tab = tab; - ckh->lg_curbuckets = lg_prevbuckets; -#ifdef CKH_COUNT - ckh->nshrinkfails++; -#endif -} - -bool -ckh_new(ckh_t *ckh, size_t minitems, ckh_hash_t *hash, ckh_keycomp_t *keycomp) -{ - bool ret; - size_t mincells; - unsigned lg_mincells; - - assert(minitems > 0); - assert(hash != NULL); - assert(keycomp != NULL); - -#ifdef CKH_COUNT - ckh->ngrows = 0; - ckh->nshrinks = 0; - ckh->nshrinkfails = 0; - ckh->ninserts = 0; - ckh->nrelocs = 0; -#endif - ckh->prn_state = 42; /* Value doesn't really matter. */ - ckh->count = 0; - - /* - * Find the minimum power of 2 that is large enough to fit aBaseCount - * entries. We are using (2+,2) cuckoo hashing, which has an expected - * maximum load factor of at least ~0.86, so 0.75 is a conservative load - * factor that will typically allow 2^aLgMinItems to fit without ever - * growing the table. - */ - assert(LG_CKH_BUCKET_CELLS > 0); - mincells = ((minitems + (3 - (minitems % 3))) / 3) << 2; - for (lg_mincells = LG_CKH_BUCKET_CELLS; - (ZU(1) << lg_mincells) < mincells; - lg_mincells++) - ; /* Do nothing. */ - ckh->lg_minbuckets = lg_mincells - LG_CKH_BUCKET_CELLS; - ckh->lg_curbuckets = lg_mincells - LG_CKH_BUCKET_CELLS; - ckh->hash = hash; - ckh->keycomp = keycomp; - - ckh->tab = (ckhc_t *)ipalloc((ZU(1) << LG_CACHELINE), - sizeof(ckhc_t) << lg_mincells); - if (ckh->tab == NULL) { - ret = true; - goto RETURN; - } - memset(ckh->tab, 0, sizeof(ckhc_t) << lg_mincells); - -#ifdef JEMALLOC_DEBUG - ckh->magic = CKH_MAGIG; -#endif - - ret = false; -RETURN: - return (ret); -} - -void -ckh_delete(ckh_t *ckh) -{ - - assert(ckh != NULL); - assert(ckh->magic = CKH_MAGIG); - -#ifdef CKH_VERBOSE - malloc_printf( - "%s(%p): ngrows: %"PRIu64", nshrinks: %"PRIu64"," - " nshrinkfails: %"PRIu64", ninserts: %"PRIu64"," - " nrelocs: %"PRIu64"\n", __func__, ckh, - (unsigned long long)ckh->ngrows, - (unsigned long long)ckh->nshrinks, - (unsigned long long)ckh->nshrinkfails, - (unsigned long long)ckh->ninserts, - (unsigned long long)ckh->nrelocs); -#endif - - idalloc(ckh->tab); -#ifdef JEMALLOC_DEBUG - memset(ckh, 0x5a, sizeof(ckh_t)); -#endif -} - -size_t -ckh_count(ckh_t *ckh) -{ - - assert(ckh != NULL); - assert(ckh->magic = CKH_MAGIG); - - return (ckh->count); -} - -bool -ckh_iter(ckh_t *ckh, size_t *tabind, void **key, void **data) -{ - size_t i, ncells; - - for (i = *tabind, ncells = (ZU(1) << (ckh->lg_curbuckets + - LG_CKH_BUCKET_CELLS)); i < ncells; i++) { - if (ckh->tab[i].key != NULL) { - if (key != NULL) - *key = (void *)ckh->tab[i].key; - if (data != NULL) - *data = (void *)ckh->tab[i].data; - *tabind = i + 1; - return (false); - } - } - - return (true); -} - -bool -ckh_insert(ckh_t *ckh, const void *key, const void *data) -{ - bool ret; - - assert(ckh != NULL); - assert(ckh->magic = CKH_MAGIG); - assert(ckh_search(ckh, key, NULL, NULL)); - -#ifdef CKH_COUNT - ckh->ninserts++; -#endif - - while (ckh_try_insert(ckh, &key, &data)) { - if (ckh_grow(ckh)) { - ret = true; - goto RETURN; - } - } - - ret = false; -RETURN: - return (ret); -} - -bool -ckh_remove(ckh_t *ckh, const void *searchkey, void **key, void **data) -{ - size_t cell; - - assert(ckh != NULL); - assert(ckh->magic = CKH_MAGIG); - - cell = ckh_isearch(ckh, searchkey); - if (cell != SIZE_T_MAX) { - if (key != NULL) - *key = (void *)ckh->tab[cell].key; - if (data != NULL) - *data = (void *)ckh->tab[cell].data; - ckh->tab[cell].key = NULL; - ckh->tab[cell].data = NULL; /* Not necessary. */ - - ckh->count--; - /* Try to halve the table if it is less than 1/4 full. */ - if (ckh->count < (ZU(1) << (ckh->lg_curbuckets - + LG_CKH_BUCKET_CELLS - 2)) && ckh->lg_curbuckets - > ckh->lg_minbuckets) { - /* Ignore error due to OOM. */ - ckh_shrink(ckh); - } - - return (false); - } - - return (true); -} - -bool -ckh_search(ckh_t *ckh, const void *searchkey, void **key, void **data) -{ - size_t cell; - - assert(ckh != NULL); - assert(ckh->magic = CKH_MAGIG); - - cell = ckh_isearch(ckh, searchkey); - if (cell != SIZE_T_MAX) { - if (key != NULL) - *key = (void *)ckh->tab[cell].key; - if (data != NULL) - *data = (void *)ckh->tab[cell].data; - return (false); - } - - return (true); -} - -void -ckh_string_hash(const void *key, unsigned minbits, size_t *hash1, size_t *hash2) -{ - size_t ret1, ret2; - uint64_t h; - - assert(minbits <= 32 || (SIZEOF_PTR == 8 && minbits <= 64)); - assert(hash1 != NULL); - assert(hash2 != NULL); - - h = hash(key, strlen((const char *)key), 0x94122f335b332aeaLLU); - if (minbits <= 32) { - /* - * Avoid doing multiple hashes, since a single hash provides - * enough bits. - */ - ret1 = h & ZU(0xffffffffU); - ret2 = h >> 32; - } else { - ret1 = h; - ret2 = hash(key, strlen((const char *)key), - 0x8432a476666bbc13U); - } - - *hash1 = ret1; - *hash2 = ret2; -} - -bool -ckh_string_keycomp(const void *k1, const void *k2) -{ - - assert(k1 != NULL); - assert(k2 != NULL); - - return (strcmp((char *)k1, (char *)k2) ? false : true); -} - -void -ckh_pointer_hash(const void *key, unsigned minbits, size_t *hash1, - size_t *hash2) -{ - size_t ret1, ret2; - uint64_t h; - - assert(minbits <= 32 || (SIZEOF_PTR == 8 && minbits <= 64)); - assert(hash1 != NULL); - assert(hash2 != NULL); - - h = hash(&key, sizeof(void *), 0xd983396e68886082LLU); - if (minbits <= 32) { - /* - * Avoid doing multiple hashes, since a single hash provides - * enough bits. - */ - ret1 = h & ZU(0xffffffffU); - ret2 = h >> 32; - } else { - assert(SIZEOF_PTR == 8); - ret1 = h; - ret2 = hash(&key, sizeof(void *), 0x5e2be9aff8709a5dLLU); - } - - *hash1 = ret1; - *hash2 = ret2; -} - -bool -ckh_pointer_keycomp(const void *k1, const void *k2) -{ - - return ((k1 == k2) ? true : false); -} diff --git a/externals/jemalloc/ctl.c b/externals/jemalloc/ctl.c deleted file mode 100644 index ffb732d5bef..00000000000 --- a/externals/jemalloc/ctl.c +++ /dev/null @@ -1,1482 +0,0 @@ -#define JEMALLOC_CTL_C_ -#include "jemalloc/internal/jemalloc_internal.h" - -/******************************************************************************/ -/* Data. */ - -static malloc_mutex_t ctl_mtx; -static bool ctl_initialized; -static uint64_t ctl_epoch; -static ctl_stats_t ctl_stats; - -/******************************************************************************/ -/* Function prototypes for non-inline static functions. */ - -#define CTL_PROTO(n) \ -static int n##_ctl(const size_t *mib, size_t miblen, void *oldp, \ - size_t *oldlenp, void *newp, size_t newlen); - -#define INDEX_PROTO(n) \ -const ctl_node_t *n##_index(const size_t *mib, size_t miblen, \ - size_t i); - -#ifdef JEMALLOC_STATS -static bool ctl_arena_init(ctl_arena_stats_t *astats); -#endif -static void ctl_arena_clear(ctl_arena_stats_t *astats); -#ifdef JEMALLOC_STATS -static void ctl_arena_stats_amerge(ctl_arena_stats_t *cstats, - arena_t *arena); -static void ctl_arena_stats_smerge(ctl_arena_stats_t *sstats, - ctl_arena_stats_t *astats); -#endif -static void ctl_arena_refresh(arena_t *arena, unsigned i); -static void ctl_refresh(void); -static bool ctl_init(void); -static int ctl_lookup(const char *name, ctl_node_t const **nodesp, - size_t *mibp, size_t *depthp); - -CTL_PROTO(version) -CTL_PROTO(epoch) -#ifdef JEMALLOC_TCACHE -CTL_PROTO(tcache_flush) -#endif -CTL_PROTO(config_debug) -CTL_PROTO(config_dss) -CTL_PROTO(config_dynamic_page_shift) -CTL_PROTO(config_fill) -CTL_PROTO(config_lazy_lock) -CTL_PROTO(config_prof) -CTL_PROTO(config_prof_libgcc) -CTL_PROTO(config_prof_libunwind) -CTL_PROTO(config_stats) -CTL_PROTO(config_swap) -CTL_PROTO(config_sysv) -CTL_PROTO(config_tcache) -CTL_PROTO(config_tiny) -CTL_PROTO(config_tls) -CTL_PROTO(config_xmalloc) -CTL_PROTO(opt_abort) -#ifdef JEMALLOC_FILL -CTL_PROTO(opt_junk) -#endif -#ifdef JEMALLOC_SYSV -CTL_PROTO(opt_sysv) -#endif -#ifdef JEMALLOC_XMALLOC -CTL_PROTO(opt_xmalloc) -#endif -#ifdef JEMALLOC_ZERO -CTL_PROTO(opt_zero) -#endif -#ifdef JEMALLOC_TCACHE -CTL_PROTO(opt_tcache) -CTL_PROTO(opt_lg_tcache_gc_sweep) -#endif -#ifdef JEMALLOC_PROF -CTL_PROTO(opt_prof) -CTL_PROTO(opt_prof_active) -CTL_PROTO(opt_lg_prof_bt_max) -CTL_PROTO(opt_lg_prof_sample) -CTL_PROTO(opt_lg_prof_interval) -CTL_PROTO(opt_prof_udump) -CTL_PROTO(opt_prof_leak) -#endif -CTL_PROTO(opt_stats_print) -CTL_PROTO(opt_lg_qspace_max) -CTL_PROTO(opt_lg_cspace_max) -CTL_PROTO(opt_lg_dirty_mult) -CTL_PROTO(opt_lg_chunk) -#ifdef JEMALLOC_SWAP -CTL_PROTO(opt_overcommit) -#endif -CTL_PROTO(arenas_bin_i_size) -CTL_PROTO(arenas_bin_i_nregs) -CTL_PROTO(arenas_bin_i_run_size) -INDEX_PROTO(arenas_bin_i) -CTL_PROTO(arenas_lrun_i_size) -INDEX_PROTO(arenas_lrun_i) -CTL_PROTO(arenas_narenas) -CTL_PROTO(arenas_initialized) -CTL_PROTO(arenas_quantum) -CTL_PROTO(arenas_cacheline) -CTL_PROTO(arenas_subpage) -CTL_PROTO(arenas_pagesize) -CTL_PROTO(arenas_chunksize) -#ifdef JEMALLOC_TINY -CTL_PROTO(arenas_tspace_min) -CTL_PROTO(arenas_tspace_max) -#endif -CTL_PROTO(arenas_qspace_min) -CTL_PROTO(arenas_qspace_max) -CTL_PROTO(arenas_cspace_min) -CTL_PROTO(arenas_cspace_max) -CTL_PROTO(arenas_sspace_min) -CTL_PROTO(arenas_sspace_max) -#ifdef JEMALLOC_TCACHE -CTL_PROTO(arenas_tcache_max) -#endif -CTL_PROTO(arenas_ntbins) -CTL_PROTO(arenas_nqbins) -CTL_PROTO(arenas_ncbins) -CTL_PROTO(arenas_nsbins) -CTL_PROTO(arenas_nbins) -#ifdef JEMALLOC_TCACHE -CTL_PROTO(arenas_nhbins) -#endif -CTL_PROTO(arenas_nlruns) -#ifdef JEMALLOC_PROF -CTL_PROTO(prof_active) -CTL_PROTO(prof_dump) -CTL_PROTO(prof_interval) -#endif -#ifdef JEMALLOC_STATS -CTL_PROTO(stats_chunks_current) -CTL_PROTO(stats_chunks_total) -CTL_PROTO(stats_chunks_high) -CTL_PROTO(stats_huge_allocated) -CTL_PROTO(stats_huge_nmalloc) -CTL_PROTO(stats_huge_ndalloc) -CTL_PROTO(stats_arenas_i_small_allocated) -CTL_PROTO(stats_arenas_i_small_nmalloc) -CTL_PROTO(stats_arenas_i_small_ndalloc) -CTL_PROTO(stats_arenas_i_small_nrequests) -CTL_PROTO(stats_arenas_i_large_allocated) -CTL_PROTO(stats_arenas_i_large_nmalloc) -CTL_PROTO(stats_arenas_i_large_ndalloc) -CTL_PROTO(stats_arenas_i_large_nrequests) -CTL_PROTO(stats_arenas_i_bins_j_allocated) -CTL_PROTO(stats_arenas_i_bins_j_nmalloc) -CTL_PROTO(stats_arenas_i_bins_j_ndalloc) -CTL_PROTO(stats_arenas_i_bins_j_nrequests) -#ifdef JEMALLOC_TCACHE -CTL_PROTO(stats_arenas_i_bins_j_nfills) -CTL_PROTO(stats_arenas_i_bins_j_nflushes) -#endif -CTL_PROTO(stats_arenas_i_bins_j_nruns) -CTL_PROTO(stats_arenas_i_bins_j_nreruns) -CTL_PROTO(stats_arenas_i_bins_j_highruns) -CTL_PROTO(stats_arenas_i_bins_j_curruns) -INDEX_PROTO(stats_arenas_i_bins_j) -CTL_PROTO(stats_arenas_i_lruns_j_nmalloc) -CTL_PROTO(stats_arenas_i_lruns_j_ndalloc) -CTL_PROTO(stats_arenas_i_lruns_j_nrequests) -CTL_PROTO(stats_arenas_i_lruns_j_highruns) -CTL_PROTO(stats_arenas_i_lruns_j_curruns) -INDEX_PROTO(stats_arenas_i_lruns_j) -#endif -CTL_PROTO(stats_arenas_i_pactive) -CTL_PROTO(stats_arenas_i_pdirty) -#ifdef JEMALLOC_STATS -CTL_PROTO(stats_arenas_i_mapped) -CTL_PROTO(stats_arenas_i_npurge) -CTL_PROTO(stats_arenas_i_nmadvise) -CTL_PROTO(stats_arenas_i_purged) -#endif -INDEX_PROTO(stats_arenas_i) -#ifdef JEMALLOC_STATS -CTL_PROTO(stats_allocated) -CTL_PROTO(stats_active) -CTL_PROTO(stats_mapped) -#endif -#ifdef JEMALLOC_SWAP -# ifdef JEMALLOC_STATS -CTL_PROTO(swap_avail) -# endif -CTL_PROTO(swap_prezeroed) -CTL_PROTO(swap_nfds) -CTL_PROTO(swap_fds) -#endif - -/******************************************************************************/ -/* mallctl tree. */ - -/* Maximum tree depth. */ -#define CTL_MAX_DEPTH 6 - -#define NAME(n) true, {.named = {n -#define CHILD(c) sizeof(c##_node) / sizeof(ctl_node_t), c##_node}}, NULL -#define CTL(c) 0, NULL}}, c##_ctl - -/* - * Only handles internal indexed nodes, since there are currently no external - * ones. - */ -#define INDEX(i) false, {.indexed = {i##_index}}, NULL - -#ifdef JEMALLOC_TCACHE -static const ctl_node_t tcache_node[] = { - {NAME("flush"), CTL(tcache_flush)} -}; -#endif - -static const ctl_node_t config_node[] = { - {NAME("debug"), CTL(config_debug)}, - {NAME("dss"), CTL(config_dss)}, - {NAME("dynamic_page_shift"), CTL(config_dynamic_page_shift)}, - {NAME("fill"), CTL(config_fill)}, - {NAME("lazy_lock"), CTL(config_lazy_lock)}, - {NAME("prof"), CTL(config_prof)}, - {NAME("prof_libgcc"), CTL(config_prof_libgcc)}, - {NAME("prof_libunwind"), CTL(config_prof_libunwind)}, - {NAME("stats"), CTL(config_stats)}, - {NAME("swap"), CTL(config_swap)}, - {NAME("sysv"), CTL(config_sysv)}, - {NAME("tcache"), CTL(config_tcache)}, - {NAME("tiny"), CTL(config_tiny)}, - {NAME("tls"), CTL(config_tls)}, - {NAME("xmalloc"), CTL(config_xmalloc)} -}; - -static const ctl_node_t opt_node[] = { - {NAME("abort"), CTL(opt_abort)}, -#ifdef JEMALLOC_FILL - {NAME("junk"), CTL(opt_junk)}, -#endif -#ifdef JEMALLOC_SYSV - {NAME("sysv"), CTL(opt_sysv)}, -#endif -#ifdef JEMALLOC_XMALLOC - {NAME("xmalloc"), CTL(opt_xmalloc)}, -#endif -#ifdef JEMALLOC_ZERO - {NAME("zero"), CTL(opt_zero)}, -#endif -#ifdef JEMALLOC_TCACHE - {NAME("tcache"), CTL(opt_tcache)}, - {NAME("lg_tcache_gc_sweep"), CTL(opt_lg_tcache_gc_sweep)}, -#endif -#ifdef JEMALLOC_PROF - {NAME("prof"), CTL(opt_prof)}, - {NAME("prof_active"), CTL(opt_prof_active)}, - {NAME("lg_prof_bt_max"), CTL(opt_lg_prof_bt_max)}, - {NAME("lg_prof_sample"), CTL(opt_lg_prof_sample)}, - {NAME("lg_prof_interval"), CTL(opt_lg_prof_interval)}, - {NAME("prof_udump"), CTL(opt_prof_udump)}, - {NAME("prof_leak"), CTL(opt_prof_leak)}, -#endif - {NAME("stats_print"), CTL(opt_stats_print)}, - {NAME("lg_qspace_max"), CTL(opt_lg_qspace_max)}, - {NAME("lg_cspace_max"), CTL(opt_lg_cspace_max)}, - {NAME("lg_dirty_mult"), CTL(opt_lg_dirty_mult)}, - {NAME("lg_chunk"), CTL(opt_lg_chunk)} -#ifdef JEMALLOC_SWAP - , - {NAME("overcommit"), CTL(opt_overcommit)} -#endif -}; - -static const ctl_node_t arenas_bin_i_node[] = { - {NAME("size"), CTL(arenas_bin_i_size)}, - {NAME("nregs"), CTL(arenas_bin_i_nregs)}, - {NAME("run_size"), CTL(arenas_bin_i_run_size)} -}; -static const ctl_node_t super_arenas_bin_i_node[] = { - {NAME(""), CHILD(arenas_bin_i)} -}; - -static const ctl_node_t arenas_bin_node[] = { - {INDEX(arenas_bin_i)} -}; - -static const ctl_node_t arenas_lrun_i_node[] = { - {NAME("size"), CTL(arenas_lrun_i_size)} -}; -static const ctl_node_t super_arenas_lrun_i_node[] = { - {NAME(""), CHILD(arenas_lrun_i)} -}; - -static const ctl_node_t arenas_lrun_node[] = { - {INDEX(arenas_lrun_i)} -}; - -static const ctl_node_t arenas_node[] = { - {NAME("narenas"), CTL(arenas_narenas)}, - {NAME("initialized"), CTL(arenas_initialized)}, - {NAME("quantum"), CTL(arenas_quantum)}, - {NAME("cacheline"), CTL(arenas_cacheline)}, - {NAME("subpage"), CTL(arenas_subpage)}, - {NAME("pagesize"), CTL(arenas_pagesize)}, - {NAME("chunksize"), CTL(arenas_chunksize)}, -#ifdef JEMALLOC_TINY - {NAME("tspace_min"), CTL(arenas_tspace_min)}, - {NAME("tspace_max"), CTL(arenas_tspace_max)}, -#endif - {NAME("qspace_min"), CTL(arenas_qspace_min)}, - {NAME("qspace_max"), CTL(arenas_qspace_max)}, - {NAME("cspace_min"), CTL(arenas_cspace_min)}, - {NAME("cspace_max"), CTL(arenas_cspace_max)}, - {NAME("sspace_min"), CTL(arenas_sspace_min)}, - {NAME("sspace_max"), CTL(arenas_sspace_max)}, -#ifdef JEMALLOC_TCACHE - {NAME("tcache_max"), CTL(arenas_tcache_max)}, -#endif - {NAME("ntbins"), CTL(arenas_ntbins)}, - {NAME("nqbins"), CTL(arenas_nqbins)}, - {NAME("ncbins"), CTL(arenas_ncbins)}, - {NAME("nsbins"), CTL(arenas_nsbins)}, - {NAME("nbins"), CTL(arenas_nbins)}, -#ifdef JEMALLOC_TCACHE - {NAME("nhbins"), CTL(arenas_nhbins)}, -#endif - {NAME("bin"), CHILD(arenas_bin)}, - {NAME("nlruns"), CTL(arenas_nlruns)}, - {NAME("lrun"), CHILD(arenas_lrun)} -}; - -#ifdef JEMALLOC_PROF -static const ctl_node_t prof_node[] = { - {NAME("active"), CTL(prof_active)}, - {NAME("dump"), CTL(prof_dump)}, - {NAME("interval"), CTL(prof_interval)} -}; -#endif - -#ifdef JEMALLOC_STATS -static const ctl_node_t stats_chunks_node[] = { - {NAME("current"), CTL(stats_chunks_current)}, - {NAME("total"), CTL(stats_chunks_total)}, - {NAME("high"), CTL(stats_chunks_high)} -}; - -static const ctl_node_t stats_huge_node[] = { - {NAME("allocated"), CTL(stats_huge_allocated)}, - {NAME("nmalloc"), CTL(stats_huge_nmalloc)}, - {NAME("ndalloc"), CTL(stats_huge_ndalloc)} -}; - -static const ctl_node_t stats_arenas_i_small_node[] = { - {NAME("allocated"), CTL(stats_arenas_i_small_allocated)}, - {NAME("nmalloc"), CTL(stats_arenas_i_small_nmalloc)}, - {NAME("ndalloc"), CTL(stats_arenas_i_small_ndalloc)}, - {NAME("nrequests"), CTL(stats_arenas_i_small_nrequests)} -}; - -static const ctl_node_t stats_arenas_i_large_node[] = { - {NAME("allocated"), CTL(stats_arenas_i_large_allocated)}, - {NAME("nmalloc"), CTL(stats_arenas_i_large_nmalloc)}, - {NAME("ndalloc"), CTL(stats_arenas_i_large_ndalloc)}, - {NAME("nrequests"), CTL(stats_arenas_i_large_nrequests)} -}; - -static const ctl_node_t stats_arenas_i_bins_j_node[] = { - {NAME("allocated"), CTL(stats_arenas_i_bins_j_allocated)}, - {NAME("nmalloc"), CTL(stats_arenas_i_bins_j_nmalloc)}, - {NAME("ndalloc"), CTL(stats_arenas_i_bins_j_ndalloc)}, - {NAME("nrequests"), CTL(stats_arenas_i_bins_j_nrequests)}, -#ifdef JEMALLOC_TCACHE - {NAME("nfills"), CTL(stats_arenas_i_bins_j_nfills)}, - {NAME("nflushes"), CTL(stats_arenas_i_bins_j_nflushes)}, -#endif - {NAME("nruns"), CTL(stats_arenas_i_bins_j_nruns)}, - {NAME("nreruns"), CTL(stats_arenas_i_bins_j_nreruns)}, - {NAME("highruns"), CTL(stats_arenas_i_bins_j_highruns)}, - {NAME("curruns"), CTL(stats_arenas_i_bins_j_curruns)} -}; -static const ctl_node_t super_stats_arenas_i_bins_j_node[] = { - {NAME(""), CHILD(stats_arenas_i_bins_j)} -}; - -static const ctl_node_t stats_arenas_i_bins_node[] = { - {INDEX(stats_arenas_i_bins_j)} -}; - -static const ctl_node_t stats_arenas_i_lruns_j_node[] = { - {NAME("nmalloc"), CTL(stats_arenas_i_lruns_j_nmalloc)}, - {NAME("ndalloc"), CTL(stats_arenas_i_lruns_j_ndalloc)}, - {NAME("nrequests"), CTL(stats_arenas_i_lruns_j_nrequests)}, - {NAME("highruns"), CTL(stats_arenas_i_lruns_j_highruns)}, - {NAME("curruns"), CTL(stats_arenas_i_lruns_j_curruns)} -}; -static const ctl_node_t super_stats_arenas_i_lruns_j_node[] = { - {NAME(""), CHILD(stats_arenas_i_lruns_j)} -}; - -static const ctl_node_t stats_arenas_i_lruns_node[] = { - {INDEX(stats_arenas_i_lruns_j)} -}; -#endif - -static const ctl_node_t stats_arenas_i_node[] = { - {NAME("pactive"), CTL(stats_arenas_i_pactive)}, - {NAME("pdirty"), CTL(stats_arenas_i_pdirty)} -#ifdef JEMALLOC_STATS - , - {NAME("mapped"), CTL(stats_arenas_i_mapped)}, - {NAME("npurge"), CTL(stats_arenas_i_npurge)}, - {NAME("nmadvise"), CTL(stats_arenas_i_nmadvise)}, - {NAME("purged"), CTL(stats_arenas_i_purged)}, - {NAME("small"), CHILD(stats_arenas_i_small)}, - {NAME("large"), CHILD(stats_arenas_i_large)}, - {NAME("bins"), CHILD(stats_arenas_i_bins)}, - {NAME("lruns"), CHILD(stats_arenas_i_lruns)} -#endif -}; -static const ctl_node_t super_stats_arenas_i_node[] = { - {NAME(""), CHILD(stats_arenas_i)} -}; - -static const ctl_node_t stats_arenas_node[] = { - {INDEX(stats_arenas_i)} -}; - -static const ctl_node_t stats_node[] = { -#ifdef JEMALLOC_STATS - {NAME("allocated"), CTL(stats_allocated)}, - {NAME("active"), CTL(stats_active)}, - {NAME("mapped"), CTL(stats_mapped)}, - {NAME("chunks"), CHILD(stats_chunks)}, - {NAME("huge"), CHILD(stats_huge)}, -#endif - {NAME("arenas"), CHILD(stats_arenas)} -}; - -#ifdef JEMALLOC_SWAP -static const ctl_node_t swap_node[] = { -# ifdef JEMALLOC_STATS - {NAME("avail"), CTL(swap_avail)}, -# endif - {NAME("prezeroed"), CTL(swap_prezeroed)}, - {NAME("nfds"), CTL(swap_nfds)}, - {NAME("fds"), CTL(swap_fds)} -}; -#endif - -static const ctl_node_t root_node[] = { - {NAME("version"), CTL(version)}, - {NAME("epoch"), CTL(epoch)}, -#ifdef JEMALLOC_TCACHE - {NAME("tcache"), CHILD(tcache)}, -#endif - {NAME("config"), CHILD(config)}, - {NAME("opt"), CHILD(opt)}, - {NAME("arenas"), CHILD(arenas)}, -#ifdef JEMALLOC_PROF - {NAME("prof"), CHILD(prof)}, -#endif - {NAME("stats"), CHILD(stats)} -#ifdef JEMALLOC_SWAP - , - {NAME("swap"), CHILD(swap)} -#endif -}; -static const ctl_node_t super_root_node[] = { - {NAME(""), CHILD(root)} -}; - -#undef NAME -#undef CHILD -#undef CTL -#undef INDEX - -/******************************************************************************/ - -#ifdef JEMALLOC_STATS -static bool -ctl_arena_init(ctl_arena_stats_t *astats) -{ - - if (astats->bstats == NULL) { - astats->bstats = (malloc_bin_stats_t *)base_alloc(nbins * - sizeof(malloc_bin_stats_t)); - if (astats->bstats == NULL) - return (true); - } - if (astats->lstats == NULL) { - astats->lstats = (malloc_large_stats_t *)base_alloc(nlclasses * - sizeof(malloc_large_stats_t)); - if (astats->lstats == NULL) - return (true); - } - - return (false); -} -#endif - -static void -ctl_arena_clear(ctl_arena_stats_t *astats) -{ - - astats->pactive = 0; - astats->pdirty = 0; -#ifdef JEMALLOC_STATS - memset(&astats->astats, 0, sizeof(arena_stats_t)); - astats->allocated_small = 0; - astats->nmalloc_small = 0; - astats->ndalloc_small = 0; - astats->nrequests_small = 0; - memset(astats->bstats, 0, nbins * sizeof(malloc_bin_stats_t)); - memset(astats->lstats, 0, nlclasses * sizeof(malloc_large_stats_t)); -#endif -} - -#ifdef JEMALLOC_STATS -static void -ctl_arena_stats_amerge(ctl_arena_stats_t *cstats, arena_t *arena) -{ - unsigned i; - - arena_stats_merge(arena, &cstats->pactive, &cstats->pdirty, - &cstats->astats, cstats->bstats, cstats->lstats); - - for (i = 0; i < nbins; i++) { - cstats->allocated_small += cstats->bstats[i].allocated; - cstats->nmalloc_small += cstats->bstats[i].nmalloc; - cstats->ndalloc_small += cstats->bstats[i].ndalloc; - cstats->nrequests_small += cstats->bstats[i].nrequests; - } -} - -static void -ctl_arena_stats_smerge(ctl_arena_stats_t *sstats, ctl_arena_stats_t *astats) -{ - unsigned i; - - sstats->pactive += astats->pactive; - sstats->pdirty += astats->pdirty; - - sstats->astats.mapped += astats->astats.mapped; - sstats->astats.npurge += astats->astats.npurge; - sstats->astats.nmadvise += astats->astats.nmadvise; - sstats->astats.purged += astats->astats.purged; - - sstats->allocated_small += astats->allocated_small; - sstats->nmalloc_small += astats->nmalloc_small; - sstats->ndalloc_small += astats->ndalloc_small; - sstats->nrequests_small += astats->nrequests_small; - - sstats->astats.allocated_large += astats->astats.allocated_large; - sstats->astats.nmalloc_large += astats->astats.nmalloc_large; - sstats->astats.ndalloc_large += astats->astats.ndalloc_large; - sstats->astats.nrequests_large += astats->astats.nrequests_large; - - for (i = 0; i < nlclasses; i++) { - sstats->lstats[i].nmalloc += astats->lstats[i].nmalloc; - sstats->lstats[i].ndalloc += astats->lstats[i].ndalloc; - sstats->lstats[i].nrequests += astats->lstats[i].nrequests; - sstats->lstats[i].highruns += astats->lstats[i].highruns; - sstats->lstats[i].curruns += astats->lstats[i].curruns; - } - - for (i = 0; i < nbins; i++) { - sstats->bstats[i].allocated += astats->bstats[i].allocated; - sstats->bstats[i].nmalloc += astats->bstats[i].nmalloc; - sstats->bstats[i].ndalloc += astats->bstats[i].ndalloc; - sstats->bstats[i].nrequests += astats->bstats[i].nrequests; -#ifdef JEMALLOC_TCACHE - sstats->bstats[i].nfills += astats->bstats[i].nfills; - sstats->bstats[i].nflushes += astats->bstats[i].nflushes; -#endif - sstats->bstats[i].nruns += astats->bstats[i].nruns; - sstats->bstats[i].reruns += astats->bstats[i].reruns; - sstats->bstats[i].highruns += astats->bstats[i].highruns; - sstats->bstats[i].curruns += astats->bstats[i].curruns; - } -} -#endif - -static void -ctl_arena_refresh(arena_t *arena, unsigned i) -{ - ctl_arena_stats_t *astats = &ctl_stats.arenas[i]; - ctl_arena_stats_t *sstats = &ctl_stats.arenas[narenas]; - - ctl_arena_clear(astats); - -#ifdef JEMALLOC_STATS - ctl_arena_stats_amerge(astats, arena); - /* Merge into sum stats as well. */ - ctl_arena_stats_smerge(sstats, astats); -#else - astats->pactive += arena->nactive; - astats->pdirty += arena->ndirty; - /* Merge into sum stats as well. */ - sstats->pactive += arena->nactive; - sstats->pdirty += arena->ndirty; -#endif -} - -static void -ctl_refresh(void) -{ - unsigned i; - arena_t *tarenas[narenas]; - -#ifdef JEMALLOC_STATS - malloc_mutex_lock(&chunks_mtx); - ctl_stats.chunks.current = stats_chunks.curchunks; - ctl_stats.chunks.total = stats_chunks.nchunks; - ctl_stats.chunks.high = stats_chunks.highchunks; - malloc_mutex_unlock(&chunks_mtx); - - malloc_mutex_lock(&huge_mtx); - ctl_stats.huge.allocated = huge_allocated; - ctl_stats.huge.nmalloc = huge_nmalloc; - ctl_stats.huge.ndalloc = huge_ndalloc; - malloc_mutex_unlock(&huge_mtx); -#endif - - /* - * Clear sum stats, since they will be merged into by - * ctl_arena_refresh(). - */ - ctl_arena_clear(&ctl_stats.arenas[narenas]); - - malloc_mutex_lock(&arenas_lock); - memcpy(tarenas, arenas, sizeof(arena_t *) * narenas); - malloc_mutex_unlock(&arenas_lock); - for (i = 0; i < narenas; i++) { - bool initialized = (tarenas[i] != NULL); - - ctl_stats.arenas[i].initialized = initialized; - if (initialized) - ctl_arena_refresh(tarenas[i], i); - } - -#ifdef JEMALLOC_STATS - ctl_stats.allocated = ctl_stats.arenas[narenas].allocated_small - + ctl_stats.arenas[narenas].astats.allocated_large - + ctl_stats.huge.allocated; - ctl_stats.active = (ctl_stats.arenas[narenas].pactive << PAGE_SHIFT) - + ctl_stats.huge.allocated; - ctl_stats.mapped = (ctl_stats.chunks.current << opt_lg_chunk); - -# ifdef JEMALLOC_SWAP - malloc_mutex_lock(&swap_mtx); - ctl_stats.swap_avail = swap_avail; - malloc_mutex_unlock(&swap_mtx); -# endif -#endif - - ctl_epoch++; -} - -static bool -ctl_init(void) -{ - - if (ctl_initialized == false) { -#ifdef JEMALLOC_STATS - unsigned i; -#endif - - /* - * Allocate space for one extra arena stats element, which - * contains summed stats across all arenas. - */ - ctl_stats.arenas = (ctl_arena_stats_t *)base_alloc( - (narenas + 1) * sizeof(ctl_arena_stats_t)); - if (ctl_stats.arenas == NULL) - return (true); - memset(ctl_stats.arenas, 0, (narenas + 1) * - sizeof(ctl_arena_stats_t)); - - /* - * Initialize all stats structures, regardless of whether they - * ever get used. Lazy initialization would allow errors to - * cause inconsistent state to be viewable by the application. - */ -#ifdef JEMALLOC_STATS - for (i = 0; i <= narenas; i++) { - if (ctl_arena_init(&ctl_stats.arenas[i])) - return (true); - } -#endif - ctl_stats.arenas[narenas].initialized = true; - - ctl_epoch = 0; - ctl_refresh(); - ctl_initialized = true; - } - - return (false); -} - -static int -ctl_lookup(const char *name, ctl_node_t const **nodesp, size_t *mibp, - size_t *depthp) -{ - int ret; - const char *elm, *tdot, *dot; - size_t elen, i, j; - const ctl_node_t *node; - - elm = name; - /* Equivalent to strchrnul(). */ - dot = ((tdot = strchr(elm, '.')) != NULL) ? tdot : strchr(elm, '\0'); - elen = (size_t)((uintptr_t)dot - (uintptr_t)elm); - if (elen == 0) { - ret = ENOENT; - goto RETURN; - } - node = super_root_node; - for (i = 0; i < *depthp; i++) { - assert(node->named); - assert(node->u.named.nchildren > 0); - if (node->u.named.children[0].named) { - const ctl_node_t *pnode = node; - - /* Children are named. */ - for (j = 0; j < node->u.named.nchildren; j++) { - const ctl_node_t *child = - &node->u.named.children[j]; - if (strlen(child->u.named.name) == elen - && strncmp(elm, child->u.named.name, - elen) == 0) { - node = child; - if (nodesp != NULL) - nodesp[i] = node; - mibp[i] = j; - break; - } - } - if (node == pnode) { - ret = ENOENT; - goto RETURN; - } - } else { - unsigned long index; - const ctl_node_t *inode; - - /* Children are indexed. */ - index = strtoul(elm, NULL, 10); - if (index == ULONG_MAX) { - ret = ENOENT; - goto RETURN; - } - - inode = &node->u.named.children[0]; - node = inode->u.indexed.index(mibp, *depthp, - index); - if (node == NULL) { - ret = ENOENT; - goto RETURN; - } - - if (nodesp != NULL) - nodesp[i] = node; - mibp[i] = (size_t)index; - } - - if (node->ctl != NULL) { - /* Terminal node. */ - if (*dot != '\0') { - /* - * The name contains more elements than are - * in this path through the tree. - */ - ret = ENOENT; - goto RETURN; - } - /* Complete lookup successful. */ - *depthp = i + 1; - break; - } - - /* Update elm. */ - if (*dot == '\0') { - /* No more elements. */ - ret = ENOENT; - goto RETURN; - } - elm = &dot[1]; - dot = ((tdot = strchr(elm, '.')) != NULL) ? tdot : - strchr(elm, '\0'); - elen = (size_t)((uintptr_t)dot - (uintptr_t)elm); - } - - ret = 0; -RETURN: - return (ret); -} - -int -ctl_byname(const char *name, void *oldp, size_t *oldlenp, void *newp, - size_t newlen) -{ - int ret; - size_t depth; - ctl_node_t const *nodes[CTL_MAX_DEPTH]; - size_t mib[CTL_MAX_DEPTH]; - - malloc_mutex_lock(&ctl_mtx); - if (ctl_init()) { - ret = EAGAIN; - goto RETURN; - } - - depth = CTL_MAX_DEPTH; - ret = ctl_lookup(name, nodes, mib, &depth); - if (ret != 0) - goto RETURN; - - if (nodes[depth-1]->ctl == NULL) { - /* The name refers to a partial path through the ctl tree. */ - ret = ENOENT; - goto RETURN; - } - ret = nodes[depth-1]->ctl(mib, depth, oldp, oldlenp, newp, newlen); - -RETURN: - malloc_mutex_unlock(&ctl_mtx); - return(ret); -} - -int -ctl_nametomib(const char *name, size_t *mibp, size_t *miblenp) -{ - int ret; - - malloc_mutex_lock(&ctl_mtx); - if (ctl_init()) { - ret = EAGAIN; - goto RETURN; - } - - ret = ctl_lookup(name, NULL, mibp, miblenp); - -RETURN: - malloc_mutex_unlock(&ctl_mtx); - return(ret); -} - -int -ctl_bymib(const size_t *mib, size_t miblen, void *oldp, size_t *oldlenp, - void *newp, size_t newlen) -{ - int ret; - const ctl_node_t *node; - size_t i; - - malloc_mutex_lock(&ctl_mtx); - if (ctl_init()) { - ret = EAGAIN; - goto RETURN; - } - - /* Iterate down the tree. */ - node = super_root_node; - for (i = 0; i < miblen; i++) { - if (node->u.named.children[0].named) { - /* Children are named. */ - if (node->u.named.nchildren <= mib[i]) { - ret = ENOENT; - goto RETURN; - } - node = &node->u.named.children[mib[i]]; - } else { - const ctl_node_t *inode; - - /* Indexed element. */ - inode = &node->u.named.children[0]; - node = inode->u.indexed.index(mib, miblen, mib[i]); - if (node == NULL) { - ret = ENOENT; - goto RETURN; - } - } - } - - /* Call the ctl function. */ - if (node->ctl == NULL) { - /* Partial MIB. */ - ret = ENOENT; - goto RETURN; - } - ret = node->ctl(mib, miblen, oldp, oldlenp, newp, newlen); - -RETURN: - malloc_mutex_unlock(&ctl_mtx); - return(ret); -} - -bool -ctl_boot(void) -{ - - if (malloc_mutex_init(&ctl_mtx)) - return (true); - - ctl_initialized = false; - - return (false); -} - -/******************************************************************************/ -/* *_ctl() functions. */ - -#define READONLY() do { \ - if (newp != NULL || newlen != 0) { \ - ret = EPERM; \ - goto RETURN; \ - } \ -} while (0) - -#define WRITEONLY() do { \ - if (oldp != NULL || oldlenp != NULL) { \ - ret = EPERM; \ - goto RETURN; \ - } \ -} while (0) - -#define VOID() do { \ - READONLY(); \ - WRITEONLY(); \ -} while (0) - -#define READ(v, t) do { \ - if (oldp != NULL && oldlenp != NULL) { \ - if (*oldlenp != sizeof(t)) { \ - size_t copylen = (sizeof(t) <= *oldlenp) \ - ? sizeof(t) : *oldlenp; \ - memcpy(oldp, (void *)&v, copylen); \ - ret = EINVAL; \ - goto RETURN; \ - } else \ - *(t *)oldp = v; \ - } \ -} while (0) - -#define WRITE(v, t) do { \ - if (newp != NULL) { \ - if (newlen != sizeof(t)) { \ - ret = EINVAL; \ - goto RETURN; \ - } \ - v = *(t *)newp; \ - } \ -} while (0) - -#define CTL_RO_GEN(n, v, t) \ -static int \ -n##_ctl(const size_t *mib, size_t miblen, void *oldp, size_t *oldlenp, \ - void *newp, size_t newlen) \ -{ \ - int ret; \ - t oldval; \ - \ - READONLY(); \ - oldval = v; \ - READ(oldval, t); \ - \ - ret = 0; \ -RETURN: \ - return (ret); \ -} - -#define CTL_RO_TRUE_GEN(n) \ -static int \ -n##_ctl(const size_t *mib, size_t miblen, void *oldp, size_t *oldlenp, \ - void *newp, size_t newlen) \ -{ \ - int ret; \ - bool oldval; \ - \ - READONLY(); \ - oldval = true; \ - READ(oldval, bool); \ - \ - ret = 0; \ -RETURN: \ - return (ret); \ -} - -#define CTL_RO_FALSE_GEN(n) \ -static int \ -n##_ctl(const size_t *mib, size_t miblen, void *oldp, size_t *oldlenp, \ - void *newp, size_t newlen) \ -{ \ - int ret; \ - bool oldval; \ - \ - READONLY(); \ - oldval = false; \ - READ(oldval, bool); \ - \ - ret = 0; \ -RETURN: \ - return (ret); \ -} - -CTL_RO_GEN(version, JEMALLOC_VERSION, const char *) - -static int -epoch_ctl(const size_t *mib, size_t miblen, void *oldp, size_t *oldlenp, - void *newp, size_t newlen) -{ - int ret; - uint64_t newval; - - newval = 0; - WRITE(newval, uint64_t); - if (newval != 0) - ctl_refresh(); - READ(ctl_epoch, uint64_t); - - ret = 0; -RETURN: - return (ret); -} - -#ifdef JEMALLOC_TCACHE -static int -tcache_flush_ctl(const size_t *mib, size_t miblen, void *oldp, size_t *oldlenp, - void *newp, size_t newlen) -{ - int ret; - tcache_t *tcache; - - VOID(); - - tcache = tcache_tls; - if (tcache == NULL) { - ret = 0; - goto RETURN; - } - tcache_destroy(tcache); - tcache_tls = NULL; - - ret = 0; -RETURN: - return (ret); -} -#endif - -/******************************************************************************/ - -#ifdef JEMALLOC_DEBUG -CTL_RO_TRUE_GEN(config_debug) -#else -CTL_RO_FALSE_GEN(config_debug) -#endif - -#ifdef JEMALLOC_DSS -CTL_RO_TRUE_GEN(config_dss) -#else -CTL_RO_FALSE_GEN(config_dss) -#endif - -#ifdef JEMALLOC_DYNAMIC_PAGE_SHIFT -CTL_RO_TRUE_GEN(config_dynamic_page_shift) -#else -CTL_RO_FALSE_GEN(config_dynamic_page_shift) -#endif - -#ifdef JEMALLOC_FILL -CTL_RO_TRUE_GEN(config_fill) -#else -CTL_RO_FALSE_GEN(config_fill) -#endif - -#ifdef JEMALLOC_LAZY_LOCK -CTL_RO_TRUE_GEN(config_lazy_lock) -#else -CTL_RO_FALSE_GEN(config_lazy_lock) -#endif - -#ifdef JEMALLOC_PROF -CTL_RO_TRUE_GEN(config_prof) -#else -CTL_RO_FALSE_GEN(config_prof) -#endif - -#ifdef JEMALLOC_PROF_LIBGCC -CTL_RO_TRUE_GEN(config_prof_libgcc) -#else -CTL_RO_FALSE_GEN(config_prof_libgcc) -#endif - -#ifdef JEMALLOC_PROF_LIBUNWIND -CTL_RO_TRUE_GEN(config_prof_libunwind) -#else -CTL_RO_FALSE_GEN(config_prof_libunwind) -#endif - -#ifdef JEMALLOC_STATS -CTL_RO_TRUE_GEN(config_stats) -#else -CTL_RO_FALSE_GEN(config_stats) -#endif - -#ifdef JEMALLOC_SWAP -CTL_RO_TRUE_GEN(config_swap) -#else -CTL_RO_FALSE_GEN(config_swap) -#endif - -#ifdef JEMALLOC_SYSV -CTL_RO_TRUE_GEN(config_sysv) -#else -CTL_RO_FALSE_GEN(config_sysv) -#endif - -#ifdef JEMALLOC_TCACHE -CTL_RO_TRUE_GEN(config_tcache) -#else -CTL_RO_FALSE_GEN(config_tcache) -#endif - -#ifdef JEMALLOC_TINY -CTL_RO_TRUE_GEN(config_tiny) -#else -CTL_RO_FALSE_GEN(config_tiny) -#endif - -#ifdef JEMALLOC_TLS -CTL_RO_TRUE_GEN(config_tls) -#else -CTL_RO_FALSE_GEN(config_tls) -#endif - -#ifdef JEMALLOC_XMALLOC -CTL_RO_TRUE_GEN(config_xmalloc) -#else -CTL_RO_FALSE_GEN(config_xmalloc) -#endif - -/******************************************************************************/ - -CTL_RO_GEN(opt_abort, opt_abort, bool) -#ifdef JEMALLOC_FILL -CTL_RO_GEN(opt_junk, opt_junk, bool) -#endif -#ifdef JEMALLOC_SYSV -CTL_RO_GEN(opt_sysv, opt_sysv, bool) -#endif -#ifdef JEMALLOC_XMALLOC -CTL_RO_GEN(opt_xmalloc, opt_xmalloc, bool) -#endif -#ifdef JEMALLOC_ZERO -CTL_RO_GEN(opt_zero, opt_zero, bool) -#endif -#ifdef JEMALLOC_TCACHE -CTL_RO_GEN(opt_tcache, opt_tcache, bool) -CTL_RO_GEN(opt_lg_tcache_gc_sweep, opt_lg_tcache_gc_sweep, ssize_t) -#endif -#ifdef JEMALLOC_PROF -CTL_RO_GEN(opt_prof, opt_prof, bool) -CTL_RO_GEN(opt_prof_active, opt_prof_active, bool) -CTL_RO_GEN(opt_lg_prof_bt_max, opt_lg_prof_bt_max, size_t) -CTL_RO_GEN(opt_lg_prof_sample, opt_lg_prof_sample, size_t) -CTL_RO_GEN(opt_lg_prof_interval, opt_lg_prof_interval, ssize_t) -CTL_RO_GEN(opt_prof_udump, opt_prof_udump, bool) -CTL_RO_GEN(opt_prof_leak, opt_prof_leak, bool) -#endif -CTL_RO_GEN(opt_stats_print, opt_stats_print, bool) -CTL_RO_GEN(opt_lg_qspace_max, opt_lg_qspace_max, size_t) -CTL_RO_GEN(opt_lg_cspace_max, opt_lg_cspace_max, size_t) -CTL_RO_GEN(opt_lg_dirty_mult, opt_lg_dirty_mult, ssize_t) -CTL_RO_GEN(opt_lg_chunk, opt_lg_chunk, size_t) -#ifdef JEMALLOC_SWAP -CTL_RO_GEN(opt_overcommit, opt_overcommit, bool) -#endif - -/******************************************************************************/ - -CTL_RO_GEN(arenas_bin_i_size, arenas[0]->bins[mib[2]].reg_size, size_t) -CTL_RO_GEN(arenas_bin_i_nregs, arenas[0]->bins[mib[2]].nregs, uint32_t) -CTL_RO_GEN(arenas_bin_i_run_size, arenas[0]->bins[mib[2]].run_size, size_t) -const ctl_node_t * -arenas_bin_i_index(const size_t *mib, size_t miblen, size_t i) -{ - - if (i > nbins) - return (NULL); - return (super_arenas_bin_i_node); -} - -CTL_RO_GEN(arenas_lrun_i_size, ((mib[2]+1) << PAGE_SHIFT), size_t) -const ctl_node_t * -arenas_lrun_i_index(const size_t *mib, size_t miblen, size_t i) -{ - - if (i > nlclasses) - return (NULL); - return (super_arenas_lrun_i_node); -} - -CTL_RO_GEN(arenas_narenas, narenas, unsigned) - -static int -arenas_initialized_ctl(const size_t *mib, size_t miblen, void *oldp, - size_t *oldlenp, void *newp, size_t newlen) -{ - int ret; - unsigned nread, i; - - READONLY(); - if (*oldlenp != narenas * sizeof(bool)) { - ret = EINVAL; - nread = (*oldlenp < narenas * sizeof(bool)) - ? (*oldlenp / sizeof(bool)) : narenas; - } else { - ret = 0; - nread = narenas; - } - - for (i = 0; i < nread; i++) - ((bool *)oldp)[i] = ctl_stats.arenas[i].initialized; - -RETURN: - return (ret); -} - -CTL_RO_GEN(arenas_quantum, QUANTUM, size_t) -CTL_RO_GEN(arenas_cacheline, CACHELINE, size_t) -CTL_RO_GEN(arenas_subpage, SUBPAGE, size_t) -CTL_RO_GEN(arenas_pagesize, PAGE_SIZE, size_t) -CTL_RO_GEN(arenas_chunksize, chunksize, size_t) -#ifdef JEMALLOC_TINY -CTL_RO_GEN(arenas_tspace_min, (1U << LG_TINY_MIN), size_t) -CTL_RO_GEN(arenas_tspace_max, (qspace_min >> 1), size_t) -#endif -CTL_RO_GEN(arenas_qspace_min, qspace_min, size_t) -CTL_RO_GEN(arenas_qspace_max, qspace_max, size_t) -CTL_RO_GEN(arenas_cspace_min, cspace_min, size_t) -CTL_RO_GEN(arenas_cspace_max, cspace_max, size_t) -CTL_RO_GEN(arenas_sspace_min, sspace_min, size_t) -CTL_RO_GEN(arenas_sspace_max, sspace_max, size_t) -#ifdef JEMALLOC_TCACHE -CTL_RO_GEN(arenas_tcache_max, tcache_maxclass, size_t) -#endif -CTL_RO_GEN(arenas_ntbins, ntbins, unsigned) -CTL_RO_GEN(arenas_nqbins, nqbins, unsigned) -CTL_RO_GEN(arenas_ncbins, ncbins, unsigned) -CTL_RO_GEN(arenas_nsbins, nsbins, unsigned) -CTL_RO_GEN(arenas_nbins, nbins, unsigned) -#ifdef JEMALLOC_TCACHE -CTL_RO_GEN(arenas_nhbins, nhbins, unsigned) -#endif -CTL_RO_GEN(arenas_nlruns, nlclasses, size_t) - -/******************************************************************************/ - -#ifdef JEMALLOC_PROF -static int -prof_active_ctl(const size_t *mib, size_t miblen, void *oldp, size_t *oldlenp, - void *newp, size_t newlen) -{ - int ret; - bool oldval; - - oldval = opt_prof_active; - if (newp != NULL) { - /* - * The memory barriers will tend to make opt_prof_active - * propagate faster on systems with weak memory ordering. - */ - mb_write(); - WRITE(opt_prof_active, bool); - mb_write(); - } - READ(oldval, bool); - - ret = 0; -RETURN: - return (ret); -} - -static int -prof_dump_ctl(const size_t *mib, size_t miblen, void *oldp, size_t *oldlenp, - void *newp, size_t newlen) -{ - int ret; - const char *filename = NULL; - - WRITEONLY(); - WRITE(filename, const char *); - - if (prof_mdump(filename)) { - ret = EFAULT; - goto RETURN; - } - - ret = 0; -RETURN: - return (ret); -} - -CTL_RO_GEN(prof_interval, prof_interval, uint64_t) -#endif - -/******************************************************************************/ - -#ifdef JEMALLOC_STATS -CTL_RO_GEN(stats_chunks_current, ctl_stats.chunks.current, size_t) -CTL_RO_GEN(stats_chunks_total, ctl_stats.chunks.total, uint64_t) -CTL_RO_GEN(stats_chunks_high, ctl_stats.chunks.high, size_t) -CTL_RO_GEN(stats_huge_allocated, huge_allocated, size_t) -CTL_RO_GEN(stats_huge_nmalloc, huge_nmalloc, uint64_t) -CTL_RO_GEN(stats_huge_ndalloc, huge_ndalloc, uint64_t) -CTL_RO_GEN(stats_arenas_i_small_allocated, - ctl_stats.arenas[mib[2]].allocated_small, size_t) -CTL_RO_GEN(stats_arenas_i_small_nmalloc, - ctl_stats.arenas[mib[2]].nmalloc_small, uint64_t) -CTL_RO_GEN(stats_arenas_i_small_ndalloc, - ctl_stats.arenas[mib[2]].ndalloc_small, uint64_t) -CTL_RO_GEN(stats_arenas_i_small_nrequests, - ctl_stats.arenas[mib[2]].nrequests_small, uint64_t) -CTL_RO_GEN(stats_arenas_i_large_allocated, - ctl_stats.arenas[mib[2]].astats.allocated_large, size_t) -CTL_RO_GEN(stats_arenas_i_large_nmalloc, - ctl_stats.arenas[mib[2]].astats.nmalloc_large, uint64_t) -CTL_RO_GEN(stats_arenas_i_large_ndalloc, - ctl_stats.arenas[mib[2]].astats.ndalloc_large, uint64_t) -CTL_RO_GEN(stats_arenas_i_large_nrequests, - ctl_stats.arenas[mib[2]].astats.nrequests_large, uint64_t) - -CTL_RO_GEN(stats_arenas_i_bins_j_allocated, - ctl_stats.arenas[mib[2]].bstats[mib[4]].allocated, size_t) -CTL_RO_GEN(stats_arenas_i_bins_j_nmalloc, - ctl_stats.arenas[mib[2]].bstats[mib[4]].nmalloc, uint64_t) -CTL_RO_GEN(stats_arenas_i_bins_j_ndalloc, - ctl_stats.arenas[mib[2]].bstats[mib[4]].ndalloc, uint64_t) -CTL_RO_GEN(stats_arenas_i_bins_j_nrequests, - ctl_stats.arenas[mib[2]].bstats[mib[4]].nrequests, uint64_t) -#ifdef JEMALLOC_TCACHE -CTL_RO_GEN(stats_arenas_i_bins_j_nfills, - ctl_stats.arenas[mib[2]].bstats[mib[4]].nfills, uint64_t) -CTL_RO_GEN(stats_arenas_i_bins_j_nflushes, - ctl_stats.arenas[mib[2]].bstats[mib[4]].nflushes, uint64_t) -#endif -CTL_RO_GEN(stats_arenas_i_bins_j_nruns, - ctl_stats.arenas[mib[2]].bstats[mib[4]].nruns, uint64_t) -CTL_RO_GEN(stats_arenas_i_bins_j_nreruns, - ctl_stats.arenas[mib[2]].bstats[mib[4]].reruns, uint64_t) -CTL_RO_GEN(stats_arenas_i_bins_j_highruns, - ctl_stats.arenas[mib[2]].bstats[mib[4]].highruns, size_t) -CTL_RO_GEN(stats_arenas_i_bins_j_curruns, - ctl_stats.arenas[mib[2]].bstats[mib[4]].curruns, size_t) - -const ctl_node_t * -stats_arenas_i_bins_j_index(const size_t *mib, size_t miblen, size_t j) -{ - - if (j > nbins) - return (NULL); - return (super_stats_arenas_i_bins_j_node); -} - -CTL_RO_GEN(stats_arenas_i_lruns_j_nmalloc, - ctl_stats.arenas[mib[2]].lstats[mib[4]].nmalloc, uint64_t) -CTL_RO_GEN(stats_arenas_i_lruns_j_ndalloc, - ctl_stats.arenas[mib[2]].lstats[mib[4]].ndalloc, uint64_t) -CTL_RO_GEN(stats_arenas_i_lruns_j_nrequests, - ctl_stats.arenas[mib[2]].lstats[mib[4]].nrequests, uint64_t) -CTL_RO_GEN(stats_arenas_i_lruns_j_curruns, - ctl_stats.arenas[mib[2]].lstats[mib[4]].curruns, size_t) -CTL_RO_GEN(stats_arenas_i_lruns_j_highruns, - ctl_stats.arenas[mib[2]].lstats[mib[4]].highruns, size_t) - -const ctl_node_t * -stats_arenas_i_lruns_j_index(const size_t *mib, size_t miblen, size_t j) -{ - - if (j > nlclasses) - return (NULL); - return (super_stats_arenas_i_lruns_j_node); -} - -#endif -CTL_RO_GEN(stats_arenas_i_pactive, ctl_stats.arenas[mib[2]].pactive, size_t) -CTL_RO_GEN(stats_arenas_i_pdirty, ctl_stats.arenas[mib[2]].pdirty, size_t) -#ifdef JEMALLOC_STATS -CTL_RO_GEN(stats_arenas_i_mapped, ctl_stats.arenas[mib[2]].astats.mapped, - size_t) -CTL_RO_GEN(stats_arenas_i_npurge, ctl_stats.arenas[mib[2]].astats.npurge, - uint64_t) -CTL_RO_GEN(stats_arenas_i_nmadvise, ctl_stats.arenas[mib[2]].astats.nmadvise, - uint64_t) -CTL_RO_GEN(stats_arenas_i_purged, ctl_stats.arenas[mib[2]].astats.purged, - uint64_t) -#endif - -const ctl_node_t * -stats_arenas_i_index(const size_t *mib, size_t miblen, size_t i) -{ - - if (ctl_stats.arenas[i].initialized == false) - return (NULL); - return (super_stats_arenas_i_node); -} - -#ifdef JEMALLOC_STATS -CTL_RO_GEN(stats_allocated, ctl_stats.allocated, size_t) -CTL_RO_GEN(stats_active, ctl_stats.active, size_t) -CTL_RO_GEN(stats_mapped, ctl_stats.mapped, size_t) -#endif - -/******************************************************************************/ - -#ifdef JEMALLOC_SWAP -# ifdef JEMALLOC_STATS -CTL_RO_GEN(swap_avail, ctl_stats.swap_avail, size_t) -# endif - -static int -swap_prezeroed_ctl(const size_t *mib, size_t miblen, void *oldp, - size_t *oldlenp, void *newp, size_t newlen) -{ - int ret; - - if (swap_enabled) { - READONLY(); - } else { - /* - * swap_prezeroed isn't actually used by the swap code until it - * is set during a successful chunk_swap_enabled() call. We - * use it here to store the value that we'll pass to - * chunk_swap_enable() in a swap.fds mallctl(). This is not - * very clean, but the obvious alternatives are even worse. - */ - WRITE(swap_prezeroed, bool); - } - - READ(swap_prezeroed, bool); - - ret = 0; -RETURN: - return (ret); -} - -CTL_RO_GEN(swap_nfds, swap_nfds, size_t) - -static int -swap_fds_ctl(const size_t *mib, size_t miblen, void *oldp, size_t *oldlenp, - void *newp, size_t newlen) -{ - int ret; - - if (swap_enabled) { - READONLY(); - } else if (newp != NULL) { - size_t nfds = newlen / sizeof(int); - - { - int fds[nfds]; - - memcpy(fds, newp, nfds * sizeof(int)); - if (chunk_swap_enable(fds, nfds, swap_prezeroed)) { - ret = EFAULT; - goto RETURN; - } - } - } - - if (oldp != NULL && oldlenp != NULL) { - if (*oldlenp != swap_nfds * sizeof(int)) { - size_t copylen = (swap_nfds * sizeof(int) <= *oldlenp) - ? swap_nfds * sizeof(int) : *oldlenp; - - memcpy(oldp, swap_fds, copylen); - ret = EINVAL; - goto RETURN; - } else - memcpy(oldp, swap_fds, *oldlenp); - } - - ret = 0; -RETURN: - return (ret); -} -#endif diff --git a/externals/jemalloc/extent.c b/externals/jemalloc/extent.c deleted file mode 100644 index 3c04d3aa5d1..00000000000 --- a/externals/jemalloc/extent.c +++ /dev/null @@ -1,41 +0,0 @@ -#define JEMALLOC_EXTENT_C_ -#include "jemalloc/internal/jemalloc_internal.h" - -/******************************************************************************/ - -#if (defined(JEMALLOC_SWAP) || defined(JEMALLOC_DSS)) -static inline int -extent_szad_comp(extent_node_t *a, extent_node_t *b) -{ - int ret; - size_t a_size = a->size; - size_t b_size = b->size; - - ret = (a_size > b_size) - (a_size < b_size); - if (ret == 0) { - uintptr_t a_addr = (uintptr_t)a->addr; - uintptr_t b_addr = (uintptr_t)b->addr; - - ret = (a_addr > b_addr) - (a_addr < b_addr); - } - - return (ret); -} - -/* Generate red-black tree functions. */ -rb_gen(, extent_tree_szad_, extent_tree_t, extent_node_t, link_szad, - extent_szad_comp) -#endif - -static inline int -extent_ad_comp(extent_node_t *a, extent_node_t *b) -{ - uintptr_t a_addr = (uintptr_t)a->addr; - uintptr_t b_addr = (uintptr_t)b->addr; - - return ((a_addr > b_addr) - (a_addr < b_addr)); -} - -/* Generate red-black tree functions. */ -rb_gen(, extent_tree_ad_, extent_tree_t, extent_node_t, link_ad, - extent_ad_comp) diff --git a/externals/jemalloc/hash.c b/externals/jemalloc/hash.c deleted file mode 100644 index 6a13d7a03c0..00000000000 --- a/externals/jemalloc/hash.c +++ /dev/null @@ -1,2 +0,0 @@ -#define HASH_C_ -#include "jemalloc/internal/jemalloc_internal.h" diff --git a/externals/jemalloc/huge.c b/externals/jemalloc/huge.c deleted file mode 100644 index d35aa5cdd00..00000000000 --- a/externals/jemalloc/huge.c +++ /dev/null @@ -1,298 +0,0 @@ -#define JEMALLOC_HUGE_C_ -#include "jemalloc/internal/jemalloc_internal.h" - -/******************************************************************************/ -/* Data. */ - -#ifdef JEMALLOC_STATS -uint64_t huge_nmalloc; -uint64_t huge_ndalloc; -size_t huge_allocated; -#endif - -malloc_mutex_t huge_mtx; - -/******************************************************************************/ - -/* Tree of chunks that are stand-alone huge allocations. */ -static extent_tree_t huge; - -void * -huge_malloc(size_t size, bool zero) -{ - void *ret; - size_t csize; - extent_node_t *node; - - /* Allocate one or more contiguous chunks for this request. */ - - csize = CHUNK_CEILING(size); - if (csize == 0) { - /* size is large enough to cause size_t wrap-around. */ - return (NULL); - } - - /* Allocate an extent node with which to track the chunk. */ - node = base_node_alloc(); - if (node == NULL) - return (NULL); - - ret = chunk_alloc(csize, &zero); - if (ret == NULL) { - base_node_dealloc(node); - return (NULL); - } - - /* Insert node into huge. */ - node->addr = ret; - node->size = csize; - - malloc_mutex_lock(&huge_mtx); - extent_tree_ad_insert(&huge, node); -#ifdef JEMALLOC_STATS - huge_nmalloc++; - huge_allocated += csize; -#endif - malloc_mutex_unlock(&huge_mtx); - -#ifdef JEMALLOC_FILL - if (zero == false) { - if (opt_junk) - memset(ret, 0xa5, csize); - else if (opt_zero) - memset(ret, 0, csize); - } -#endif - - return (ret); -} - -/* Only handles large allocations that require more than chunk alignment. */ -void * -huge_palloc(size_t alignment, size_t size) -{ - void *ret; - size_t alloc_size, chunk_size, offset; - extent_node_t *node; - bool zero; - - /* - * This allocation requires alignment that is even larger than chunk - * alignment. This means that huge_malloc() isn't good enough. - * - * Allocate almost twice as many chunks as are demanded by the size or - * alignment, in order to assure the alignment can be achieved, then - * unmap leading and trailing chunks. - */ - assert(alignment >= chunksize); - - chunk_size = CHUNK_CEILING(size); - - if (size >= alignment) - alloc_size = chunk_size + alignment - chunksize; - else - alloc_size = (alignment << 1) - chunksize; - - /* Allocate an extent node with which to track the chunk. */ - node = base_node_alloc(); - if (node == NULL) - return (NULL); - - zero = false; - ret = chunk_alloc(alloc_size, &zero); - if (ret == NULL) { - base_node_dealloc(node); - return (NULL); - } - - offset = (uintptr_t)ret & (alignment - 1); - assert((offset & chunksize_mask) == 0); - assert(offset < alloc_size); - if (offset == 0) { - /* Trim trailing space. */ - chunk_dealloc((void *)((uintptr_t)ret + chunk_size), alloc_size - - chunk_size); - } else { - size_t trailsize; - - /* Trim leading space. */ - chunk_dealloc(ret, alignment - offset); - - ret = (void *)((uintptr_t)ret + (alignment - offset)); - - trailsize = alloc_size - (alignment - offset) - chunk_size; - if (trailsize != 0) { - /* Trim trailing space. */ - assert(trailsize < alloc_size); - chunk_dealloc((void *)((uintptr_t)ret + chunk_size), - trailsize); - } - } - - /* Insert node into huge. */ - node->addr = ret; - node->size = chunk_size; - - malloc_mutex_lock(&huge_mtx); - extent_tree_ad_insert(&huge, node); -#ifdef JEMALLOC_STATS - huge_nmalloc++; - huge_allocated += chunk_size; -#endif - malloc_mutex_unlock(&huge_mtx); - -#ifdef JEMALLOC_FILL - if (opt_junk) - memset(ret, 0xa5, chunk_size); - else if (opt_zero) - memset(ret, 0, chunk_size); -#endif - - return (ret); -} - -void * -huge_ralloc(void *ptr, size_t size, size_t oldsize) -{ - void *ret; - size_t copysize; - - /* Avoid moving the allocation if the size class would not change. */ - if (oldsize > arena_maxclass && - CHUNK_CEILING(size) == CHUNK_CEILING(oldsize)) { -#ifdef JEMALLOC_FILL - if (opt_junk && size < oldsize) { - memset((void *)((uintptr_t)ptr + size), 0x5a, oldsize - - size); - } else if (opt_zero && size > oldsize) { - memset((void *)((uintptr_t)ptr + oldsize), 0, size - - oldsize); - } -#endif - return (ptr); - } - - /* - * If we get here, then size and oldsize are different enough that we - * need to use a different size class. In that case, fall back to - * allocating new space and copying. - */ - ret = huge_malloc(size, false); - if (ret == NULL) - return (NULL); - - copysize = (size < oldsize) ? size : oldsize; - memcpy(ret, ptr, copysize); - idalloc(ptr); - return (ret); -} - -void -huge_dalloc(void *ptr) -{ - extent_node_t *node, key; - - malloc_mutex_lock(&huge_mtx); - - /* Extract from tree of huge allocations. */ - key.addr = ptr; - node = extent_tree_ad_search(&huge, &key); - assert(node != NULL); - assert(node->addr == ptr); - extent_tree_ad_remove(&huge, node); - -#ifdef JEMALLOC_STATS - huge_ndalloc++; - huge_allocated -= node->size; -#endif - - malloc_mutex_unlock(&huge_mtx); - - /* Unmap chunk. */ -#ifdef JEMALLOC_FILL -#if (defined(JEMALLOC_SWAP) || defined(JEMALLOC_DSS)) - if (opt_junk) - memset(node->addr, 0x5a, node->size); -#endif -#endif - chunk_dealloc(node->addr, node->size); - - base_node_dealloc(node); -} - -size_t -huge_salloc(const void *ptr) -{ - size_t ret; - extent_node_t *node, key; - - malloc_mutex_lock(&huge_mtx); - - /* Extract from tree of huge allocations. */ - key.addr = __DECONST(void *, ptr); - node = extent_tree_ad_search(&huge, &key); - assert(node != NULL); - - ret = node->size; - - malloc_mutex_unlock(&huge_mtx); - - return (ret); -} - -#ifdef JEMALLOC_PROF -prof_thr_cnt_t * -huge_prof_cnt_get(const void *ptr) -{ - prof_thr_cnt_t *ret; - extent_node_t *node, key; - - malloc_mutex_lock(&huge_mtx); - - /* Extract from tree of huge allocations. */ - key.addr = __DECONST(void *, ptr); - node = extent_tree_ad_search(&huge, &key); - assert(node != NULL); - - ret = node->prof_cnt; - - malloc_mutex_unlock(&huge_mtx); - - return (ret); -} - -void -huge_prof_cnt_set(const void *ptr, prof_thr_cnt_t *cnt) -{ - extent_node_t *node, key; - - malloc_mutex_lock(&huge_mtx); - - /* Extract from tree of huge allocations. */ - key.addr = __DECONST(void *, ptr); - node = extent_tree_ad_search(&huge, &key); - assert(node != NULL); - - node->prof_cnt = cnt; - - malloc_mutex_unlock(&huge_mtx); -} -#endif - -bool -huge_boot(void) -{ - - /* Initialize chunks data. */ - if (malloc_mutex_init(&huge_mtx)) - return (true); - extent_tree_ad_new(&huge); - -#ifdef JEMALLOC_STATS - huge_nmalloc = 0; - huge_ndalloc = 0; - huge_allocated = 0; -#endif - - return (false); -} diff --git a/externals/jemalloc/jemalloc.c b/externals/jemalloc/jemalloc.c deleted file mode 100644 index e01de0d5066..00000000000 --- a/externals/jemalloc/jemalloc.c +++ /dev/null @@ -1,1349 +0,0 @@ -/*- - * This allocator implementation is designed to provide scalable performance - * for multi-threaded programs on multi-processor systems. The following - * features are included for this purpose: - * - * + Multiple arenas are used if there are multiple CPUs, which reduces lock - * contention and cache sloshing. - * - * + Thread-specific caching is used if there are multiple threads, which - * reduces the amount of locking. - * - * + Cache line sharing between arenas is avoided for internal data - * structures. - * - * + Memory is managed in chunks and runs (chunks can be split into runs), - * rather than as individual pages. This provides a constant-time - * mechanism for associating allocations with particular arenas. - * - * Allocation requests are rounded up to the nearest size class, and no record - * of the original request size is maintained. Allocations are broken into - * categories according to size class. Assuming 1 MiB chunks, 4 KiB pages and - * a 16 byte quantum on a 32-bit system, the size classes in each category are - * as follows: - * - * |========================================| - * | Category | Subcategory | Size | - * |========================================| - * | Small | Tiny | 2 | - * | | | 4 | - * | | | 8 | - * | |------------------+----------| - * | | Quantum-spaced | 16 | - * | | | 32 | - * | | | 48 | - * | | | ... | - * | | | 96 | - * | | | 112 | - * | | | 128 | - * | |------------------+----------| - * | | Cacheline-spaced | 192 | - * | | | 256 | - * | | | 320 | - * | | | 384 | - * | | | 448 | - * | | | 512 | - * | |------------------+----------| - * | | Sub-page | 760 | - * | | | 1024 | - * | | | 1280 | - * | | | ... | - * | | | 3328 | - * | | | 3584 | - * | | | 3840 | - * |========================================| - * | Large | 4 KiB | - * | | 8 KiB | - * | | 12 KiB | - * | | ... | - * | | 1012 KiB | - * | | 1016 KiB | - * | | 1020 KiB | - * |========================================| - * | Huge | 1 MiB | - * | | 2 MiB | - * | | 3 MiB | - * | | ... | - * |========================================| - * - * Different mechanisms are used accoding to category: - * - * Small: Each size class is segregated into its own set of runs. Each run - * maintains a bitmap of which regions are free/allocated. - * - * Large : Each allocation is backed by a dedicated run. Metadata are stored - * in the associated arena chunk header maps. - * - * Huge : Each allocation is backed by a dedicated contiguous set of chunks. - * Metadata are stored in a separate red-black tree. - * - ******************************************************************************* - */ - -#define JEMALLOC_C_ -#include "jemalloc/internal/jemalloc_internal.h" - -/******************************************************************************/ -/* Data. */ - -malloc_mutex_t arenas_lock; -arena_t **arenas; -unsigned narenas; -#ifndef NO_TLS -static unsigned next_arena; -#endif - -#ifndef NO_TLS -__thread arena_t *arenas_map JEMALLOC_ATTR(tls_model("initial-exec")); -#endif - -/* Set to true once the allocator has been initialized. */ -static bool malloc_initialized = false; - -/* Used to let the initializing thread recursively allocate. */ -static pthread_t malloc_initializer = (unsigned long)0; - -/* Used to avoid initialization races. */ -static malloc_mutex_t init_lock = PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP; - -#ifdef DYNAMIC_PAGE_SHIFT -size_t pagesize; -size_t pagesize_mask; -size_t lg_pagesize; -#endif - -unsigned ncpus; - -/* Runtime configuration options. */ -const char *JEMALLOC_P(malloc_options) - JEMALLOC_ATTR(visibility("default")); -#ifdef JEMALLOC_DEBUG -bool opt_abort = true; -# ifdef JEMALLOC_FILL -bool opt_junk = true; -# endif -#else -bool opt_abort = false; -# ifdef JEMALLOC_FILL -bool opt_junk = false; -# endif -#endif -#ifdef JEMALLOC_SYSV -bool opt_sysv = false; -#endif -#ifdef JEMALLOC_XMALLOC -bool opt_xmalloc = false; -#endif -#ifdef JEMALLOC_FILL -bool opt_zero = false; -#endif -static int opt_narenas_lshift = 0; - -/******************************************************************************/ -/* Function prototypes for non-inline static functions. */ - -static void wrtmessage(void *cbopaque, const char *s); -static void stats_print_atexit(void); -static unsigned malloc_ncpus(void); -static bool malloc_init_hard(void); -static void jemalloc_prefork(void); -static void jemalloc_postfork(void); - -/******************************************************************************/ -/* malloc_message() setup. */ - -#ifdef JEMALLOC_HAVE_ATTR -JEMALLOC_ATTR(visibility("hidden")) -#else -static -#endif -void -wrtmessage(void *cbopaque, const char *s) -{ - - write(STDERR_FILENO, s, strlen(s)); -} - -void (*JEMALLOC_P(malloc_message))(void *, const char *s) - JEMALLOC_ATTR(visibility("default")) = wrtmessage; - -/******************************************************************************/ -/* - * Begin miscellaneous support functions. - */ - -/* Create a new arena and insert it into the arenas array at index ind. */ -arena_t * -arenas_extend(unsigned ind) -{ - arena_t *ret; - - /* Allocate enough space for trailing bins. */ - ret = (arena_t *)base_alloc(sizeof(arena_t) - + (sizeof(arena_bin_t) * (nbins - 1))); - if (ret != NULL && arena_new(ret, ind) == false) { - arenas[ind] = ret; - return (ret); - } - /* Only reached if there is an OOM error. */ - - /* - * OOM here is quite inconvenient to propagate, since dealing with it - * would require a check for failure in the fast path. Instead, punt - * by using arenas[0]. In practice, this is an extremely unlikely - * failure. - */ - malloc_write(": Error initializing arena\n"); - if (opt_abort) - abort(); - - return (arenas[0]); -} - -#ifndef NO_TLS -/* - * Choose an arena based on a per-thread value (slow-path code only, called - * only by choose_arena()). - */ -arena_t * -choose_arena_hard(void) -{ - arena_t *ret; - - if (narenas > 1) { - malloc_mutex_lock(&arenas_lock); - if ((ret = arenas[next_arena]) == NULL) - ret = arenas_extend(next_arena); - next_arena = (next_arena + 1) % narenas; - malloc_mutex_unlock(&arenas_lock); - } else - ret = arenas[0]; - - arenas_map = ret; - - return (ret); -} -#endif - -static void -stats_print_atexit(void) -{ - -#if (defined(JEMALLOC_TCACHE) && defined(JEMALLOC_STATS)) - unsigned i; - - /* - * Merge stats from extant threads. This is racy, since individual - * threads do not lock when recording tcache stats events. As a - * consequence, the final stats may be slightly out of date by the time - * they are reported, if other threads continue to allocate. - */ - for (i = 0; i < narenas; i++) { - arena_t *arena = arenas[i]; - if (arena != NULL) { - tcache_t *tcache; - - /* - * tcache_stats_merge() locks bins, so if any code is - * introduced that acquires both arena and bin locks in - * the opposite order, deadlocks may result. - */ - malloc_mutex_lock(&arena->lock); - ql_foreach(tcache, &arena->tcache_ql, link) { - tcache_stats_merge(tcache, arena); - } - malloc_mutex_unlock(&arena->lock); - } - } -#endif - JEMALLOC_P(malloc_stats_print)(NULL, NULL, NULL); -} - -/* - * End miscellaneous support functions. - */ -/******************************************************************************/ -/* - * Begin initialization functions. - */ - -static unsigned -malloc_ncpus(void) -{ - unsigned ret; - long result; - - result = sysconf(_SC_NPROCESSORS_ONLN); - if (result == -1) { - /* Error. */ - ret = 1; - } - ret = (unsigned)result; - - return (ret); -} - -/* - * FreeBSD's pthreads implementation calls malloc(3), so the malloc - * implementation has to take pains to avoid infinite recursion during - * initialization. - */ -static inline bool -malloc_init(void) -{ - - if (malloc_initialized == false) - return (malloc_init_hard()); - - return (false); -} - -static bool -malloc_init_hard(void) -{ - unsigned i; - int linklen; - char buf[PATH_MAX + 1]; - const char *opts; - arena_t *init_arenas[1]; - - malloc_mutex_lock(&init_lock); - if (malloc_initialized || malloc_initializer == pthread_self()) { - /* - * Another thread initialized the allocator before this one - * acquired init_lock, or this thread is the initializing - * thread, and it is recursively allocating. - */ - malloc_mutex_unlock(&init_lock); - return (false); - } - if (malloc_initializer != (unsigned long)0) { - /* Busy-wait until the initializing thread completes. */ - do { - malloc_mutex_unlock(&init_lock); - CPU_SPINWAIT; - malloc_mutex_lock(&init_lock); - } while (malloc_initialized == false); - return (false); - } - -#ifdef DYNAMIC_PAGE_SHIFT - /* Get page size. */ - { - long result; - - result = sysconf(_SC_PAGESIZE); - assert(result != -1); - pagesize = (unsigned)result; - - /* - * We assume that pagesize is a power of 2 when calculating - * pagesize_mask and lg_pagesize. - */ - assert(((result - 1) & result) == 0); - pagesize_mask = result - 1; - lg_pagesize = ffs((int)result) - 1; - } -#endif - - for (i = 0; i < 3; i++) { - unsigned j; - - /* Get runtime configuration. */ - switch (i) { - case 0: - if ((linklen = readlink("/etc/jemalloc.conf", buf, - sizeof(buf) - 1)) != -1) { - /* - * Use the contents of the "/etc/jemalloc.conf" - * symbolic link's name. - */ - buf[linklen] = '\0'; - opts = buf; - } else { - /* No configuration specified. */ - buf[0] = '\0'; - opts = buf; - } - break; - case 1: - if ((opts = getenv("JEMALLOC_OPTIONS")) != NULL) { - /* - * Do nothing; opts is already initialized to - * the value of the JEMALLOC_OPTIONS - * environment variable. - */ - } else { - /* No configuration specified. */ - buf[0] = '\0'; - opts = buf; - } - break; - case 2: - if (JEMALLOC_P(malloc_options) != NULL) { - /* - * Use options that were compiled into the - * program. - */ - opts = JEMALLOC_P(malloc_options); - } else { - /* No configuration specified. */ - buf[0] = '\0'; - opts = buf; - } - break; - default: - /* NOTREACHED */ - assert(false); - buf[0] = '\0'; - opts = buf; - } - - for (j = 0; opts[j] != '\0'; j++) { - unsigned k, nreps; - bool nseen; - - /* Parse repetition count, if any. */ - for (nreps = 0, nseen = false;; j++, nseen = true) { - switch (opts[j]) { - case '0': case '1': case '2': case '3': - case '4': case '5': case '6': case '7': - case '8': case '9': - nreps *= 10; - nreps += opts[j] - '0'; - break; - default: - goto MALLOC_OUT; - } - } -MALLOC_OUT: - if (nseen == false) - nreps = 1; - - for (k = 0; k < nreps; k++) { - switch (opts[j]) { - case 'a': - opt_abort = false; - break; - case 'A': - opt_abort = true; - break; -#ifdef JEMALLOC_PROF - case 'b': - if (opt_lg_prof_bt_max > 0) - opt_lg_prof_bt_max--; - break; - case 'B': - if (opt_lg_prof_bt_max < LG_PROF_BT_MAX) - opt_lg_prof_bt_max++; - break; -#endif - case 'c': - if (opt_lg_cspace_max - 1 > - opt_lg_qspace_max && - opt_lg_cspace_max > - LG_CACHELINE) - opt_lg_cspace_max--; - break; - case 'C': - if (opt_lg_cspace_max < PAGE_SHIFT - - 1) - opt_lg_cspace_max++; - break; - case 'd': - if (opt_lg_dirty_mult + 1 < - (sizeof(size_t) << 3)) - opt_lg_dirty_mult++; - break; - case 'D': - if (opt_lg_dirty_mult >= 0) - opt_lg_dirty_mult--; - break; -#ifdef JEMALLOC_PROF - case 'e': - opt_prof_active = false; - break; - case 'E': - opt_prof_active = true; - break; - case 'f': - opt_prof = false; - break; - case 'F': - opt_prof = true; - break; -#endif -#ifdef JEMALLOC_TCACHE - case 'g': - if (opt_lg_tcache_gc_sweep >= 0) - opt_lg_tcache_gc_sweep--; - break; - case 'G': - if (opt_lg_tcache_gc_sweep + 1 < - (sizeof(size_t) << 3)) - opt_lg_tcache_gc_sweep++; - break; - case 'h': - opt_tcache = false; - break; - case 'H': - opt_tcache = true; - break; -#endif -#ifdef JEMALLOC_PROF - case 'i': - if (opt_lg_prof_interval >= 0) - opt_lg_prof_interval--; - break; - case 'I': - if (opt_lg_prof_interval + 1 < - (sizeof(uint64_t) << 3)) - opt_lg_prof_interval++; - break; -#endif -#ifdef JEMALLOC_FILL - case 'j': - opt_junk = false; - break; - case 'J': - opt_junk = true; - break; -#endif - case 'k': - /* - * Chunks always require at least one - * header page, plus one data page. - */ - if ((1U << (opt_lg_chunk - 1)) >= - (2U << PAGE_SHIFT)) - opt_lg_chunk--; - break; - case 'K': - if (opt_lg_chunk + 1 < - (sizeof(size_t) << 3)) - opt_lg_chunk++; - break; -#ifdef JEMALLOC_PROF - case 'l': - opt_prof_leak = false; - break; - case 'L': - opt_prof_leak = true; - break; -#endif -#ifdef JEMALLOC_TCACHE - case 'm': - if (opt_lg_tcache_maxclass >= 0) - opt_lg_tcache_maxclass--; - break; - case 'M': - if (opt_lg_tcache_maxclass + 1 < - (sizeof(size_t) << 3)) - opt_lg_tcache_maxclass++; - break; -#endif - case 'n': - opt_narenas_lshift--; - break; - case 'N': - opt_narenas_lshift++; - break; -#ifdef JEMALLOC_SWAP - case 'o': - opt_overcommit = false; - break; - case 'O': - opt_overcommit = true; - break; -#endif - case 'p': - opt_stats_print = false; - break; - case 'P': - opt_stats_print = true; - break; - case 'q': - if (opt_lg_qspace_max > LG_QUANTUM) - opt_lg_qspace_max--; - break; - case 'Q': - if (opt_lg_qspace_max + 1 < - opt_lg_cspace_max) - opt_lg_qspace_max++; - break; -#ifdef JEMALLOC_PROF - case 's': - if (opt_lg_prof_sample > 0) - opt_lg_prof_sample--; - break; - case 'S': - if (opt_lg_prof_sample + 1 < - (sizeof(uint64_t) << 3)) - opt_lg_prof_sample++; - break; - case 'u': - opt_prof_udump = false; - break; - case 'U': - opt_prof_udump = true; - break; -#endif -#ifdef JEMALLOC_SYSV - case 'v': - opt_sysv = false; - break; - case 'V': - opt_sysv = true; - break; -#endif -#ifdef JEMALLOC_XMALLOC - case 'x': - opt_xmalloc = false; - break; - case 'X': - opt_xmalloc = true; - break; -#endif -#ifdef JEMALLOC_FILL - case 'z': - opt_zero = false; - break; - case 'Z': - opt_zero = true; - break; -#endif - default: { - char cbuf[2]; - - cbuf[0] = opts[j]; - cbuf[1] = '\0'; - malloc_write( - ": Unsupported character " - "in malloc options: '"); - malloc_write(cbuf); - malloc_write("'\n"); - } - } - } - } - } - - /* Register fork handlers. */ - if (pthread_atfork(jemalloc_prefork, jemalloc_postfork, - jemalloc_postfork) != 0) { - malloc_write(": Error in pthread_atfork()\n"); - if (opt_abort) - abort(); - } - - if (ctl_boot()) { - malloc_mutex_unlock(&init_lock); - return (true); - } - - if (opt_stats_print) { - /* Print statistics at exit. */ - if (atexit(stats_print_atexit) != 0) { - malloc_write(": Error in atexit()\n"); - if (opt_abort) - abort(); - } - } - - if (chunk_boot()) { - malloc_mutex_unlock(&init_lock); - return (true); - } - - if (base_boot()) { - malloc_mutex_unlock(&init_lock); - return (true); - } - -#ifdef JEMALLOC_PROF - prof_boot0(); -#endif - - if (arena_boot()) { - malloc_mutex_unlock(&init_lock); - return (true); - } - -#ifdef JEMALLOC_TCACHE - tcache_boot(); -#endif - - if (huge_boot()) { - malloc_mutex_unlock(&init_lock); - return (true); - } - - /* - * Create enough scaffolding to allow recursive allocation in - * malloc_ncpus(). - */ - narenas = 1; - arenas = init_arenas; - memset(arenas, 0, sizeof(arena_t *) * narenas); - - /* - * Initialize one arena here. The rest are lazily created in - * choose_arena_hard(). - */ - arenas_extend(0); - if (arenas[0] == NULL) { - malloc_mutex_unlock(&init_lock); - return (true); - } - -#ifndef NO_TLS - /* - * Assign the initial arena to the initial thread, in order to avoid - * spurious creation of an extra arena if the application switches to - * threaded mode. - */ - arenas_map = arenas[0]; -#endif - - malloc_mutex_init(&arenas_lock); - -#ifdef JEMALLOC_PROF - if (prof_boot1()) { - malloc_mutex_unlock(&init_lock); - return (true); - } -#endif - - /* Get number of CPUs. */ - malloc_initializer = pthread_self(); - malloc_mutex_unlock(&init_lock); - ncpus = malloc_ncpus(); - malloc_mutex_lock(&init_lock); - - if (ncpus > 1) { - /* - * For SMP systems, create more than one arena per CPU by - * default. - */ - opt_narenas_lshift += 2; - } - - /* Determine how many arenas to use. */ - narenas = ncpus; - if (opt_narenas_lshift > 0) { - if ((narenas << opt_narenas_lshift) > narenas) - narenas <<= opt_narenas_lshift; - /* - * Make sure not to exceed the limits of what base_alloc() can - * handle. - */ - if (narenas * sizeof(arena_t *) > chunksize) - narenas = chunksize / sizeof(arena_t *); - } else if (opt_narenas_lshift < 0) { - if ((narenas >> -opt_narenas_lshift) < narenas) - narenas >>= -opt_narenas_lshift; - /* Make sure there is at least one arena. */ - if (narenas == 0) - narenas = 1; - } - -#ifdef NO_TLS - if (narenas > 1) { - static const unsigned primes[] = {1, 3, 5, 7, 11, 13, 17, 19, - 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, - 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, - 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, - 223, 227, 229, 233, 239, 241, 251, 257, 263}; - unsigned nprimes, parenas; - - /* - * Pick a prime number of hash arenas that is more than narenas - * so that direct hashing of pthread_self() pointers tends to - * spread allocations evenly among the arenas. - */ - assert((narenas & 1) == 0); /* narenas must be even. */ - nprimes = (sizeof(primes) >> LG_SIZEOF_INT); - parenas = primes[nprimes - 1]; /* In case not enough primes. */ - for (i = 1; i < nprimes; i++) { - if (primes[i] > narenas) { - parenas = primes[i]; - break; - } - } - narenas = parenas; - } -#endif - -#ifndef NO_TLS - next_arena = 0; -#endif - - /* Allocate and initialize arenas. */ - arenas = (arena_t **)base_alloc(sizeof(arena_t *) * narenas); - if (arenas == NULL) { - malloc_mutex_unlock(&init_lock); - return (true); - } - /* - * Zero the array. In practice, this should always be pre-zeroed, - * since it was just mmap()ed, but let's be sure. - */ - memset(arenas, 0, sizeof(arena_t *) * narenas); - /* Copy the pointer to the one arena that was already initialized. */ - arenas[0] = init_arenas[0]; - - malloc_initialized = true; - malloc_mutex_unlock(&init_lock); - return (false); -} - -/* - * End initialization functions. - */ -/******************************************************************************/ -/* - * Begin malloc(3)-compatible functions. - */ - -JEMALLOC_ATTR(malloc) -JEMALLOC_ATTR(visibility("default")) -void * -JEMALLOC_P(malloc)(size_t size) -{ - void *ret; -#ifdef JEMALLOC_PROF - prof_thr_cnt_t *cnt; -#endif - - if (malloc_init()) { - ret = NULL; - goto OOM; - } - - if (size == 0) { -#ifdef JEMALLOC_SYSV - if (opt_sysv == false) -#endif - size = 1; -#ifdef JEMALLOC_SYSV - else { -# ifdef JEMALLOC_XMALLOC - if (opt_xmalloc) { - malloc_write(": Error in malloc(): " - "invalid size 0\n"); - abort(); - } -# endif - ret = NULL; - goto RETURN; - } -#endif - } - -#ifdef JEMALLOC_PROF - if (opt_prof) { - if ((cnt = prof_alloc_prep(size)) == NULL) { - ret = NULL; - goto OOM; - } - if (prof_promote && (uintptr_t)cnt != (uintptr_t)1U && size <= - small_maxclass) { - ret = imalloc(small_maxclass+1); - if (ret != NULL) - arena_prof_promoted(ret, size); - } else - ret = imalloc(size); - } else -#endif - ret = imalloc(size); - -OOM: - if (ret == NULL) { -#ifdef JEMALLOC_XMALLOC - if (opt_xmalloc) { - malloc_write(": Error in malloc(): " - "out of memory\n"); - abort(); - } -#endif - errno = ENOMEM; - } - -#ifdef JEMALLOC_SYSV -RETURN: -#endif -#ifdef JEMALLOC_PROF - if (opt_prof && ret != NULL) - prof_malloc(ret, cnt); -#endif - return (ret); -} - -JEMALLOC_ATTR(nonnull(1)) -JEMALLOC_ATTR(visibility("default")) -int -JEMALLOC_P(posix_memalign)(void **memptr, size_t alignment, size_t size) -{ - int ret; - void *result; -#ifdef JEMALLOC_PROF - prof_thr_cnt_t *cnt; -#endif - - if (malloc_init()) - result = NULL; - else { - if (size == 0) { -#ifdef JEMALLOC_SYSV - if (opt_sysv == false) -#endif - size = 1; -#ifdef JEMALLOC_SYSV - else { -# ifdef JEMALLOC_XMALLOC - if (opt_xmalloc) { - malloc_write(": Error in " - "posix_memalign(): invalid size " - "0\n"); - abort(); - } -# endif - result = NULL; - *memptr = NULL; - ret = 0; - goto RETURN; - } -#endif - } - - /* Make sure that alignment is a large enough power of 2. */ - if (((alignment - 1) & alignment) != 0 - || alignment < sizeof(void *)) { -#ifdef JEMALLOC_XMALLOC - if (opt_xmalloc) { - malloc_write(": Error in " - "posix_memalign(): invalid alignment\n"); - abort(); - } -#endif - result = NULL; - ret = EINVAL; - goto RETURN; - } - -#ifdef JEMALLOC_PROF - if (opt_prof) { - if ((cnt = prof_alloc_prep(size)) == NULL) { - result = NULL; - ret = EINVAL; - } else { - if (prof_promote && (uintptr_t)cnt != - (uintptr_t)1U && size <= small_maxclass) { - result = ipalloc(alignment, - small_maxclass+1); - if (result != NULL) { - arena_prof_promoted(result, - size); - } - } else - result = ipalloc(alignment, size); - } - } else -#endif - result = ipalloc(alignment, size); - } - - if (result == NULL) { -#ifdef JEMALLOC_XMALLOC - if (opt_xmalloc) { - malloc_write(": Error in posix_memalign(): " - "out of memory\n"); - abort(); - } -#endif - ret = ENOMEM; - goto RETURN; - } - - *memptr = result; - ret = 0; - -RETURN: -#ifdef JEMALLOC_PROF - if (opt_prof && result != NULL) - prof_malloc(result, cnt); -#endif - return (ret); -} - -JEMALLOC_ATTR(malloc) -JEMALLOC_ATTR(visibility("default")) -void * -JEMALLOC_P(calloc)(size_t num, size_t size) -{ - void *ret; - size_t num_size; -#ifdef JEMALLOC_PROF - prof_thr_cnt_t *cnt; -#endif - - if (malloc_init()) { - num_size = 0; - ret = NULL; - goto RETURN; - } - - num_size = num * size; - if (num_size == 0) { -#ifdef JEMALLOC_SYSV - if ((opt_sysv == false) && ((num == 0) || (size == 0))) -#endif - num_size = 1; -#ifdef JEMALLOC_SYSV - else { - ret = NULL; - goto RETURN; - } -#endif - /* - * Try to avoid division here. We know that it isn't possible to - * overflow during multiplication if neither operand uses any of the - * most significant half of the bits in a size_t. - */ - } else if (((num | size) & (SIZE_T_MAX << (sizeof(size_t) << 2))) - && (num_size / size != num)) { - /* size_t overflow. */ - ret = NULL; - goto RETURN; - } - -#ifdef JEMALLOC_PROF - if (opt_prof) { - if ((cnt = prof_alloc_prep(num_size)) == NULL) { - ret = NULL; - goto RETURN; - } - if (prof_promote && (uintptr_t)cnt != (uintptr_t)1U && num_size - <= small_maxclass) { - ret = icalloc(small_maxclass+1); - if (ret != NULL) - arena_prof_promoted(ret, num_size); - } else - ret = icalloc(num_size); - } else -#endif - ret = icalloc(num_size); - -RETURN: - if (ret == NULL) { -#ifdef JEMALLOC_XMALLOC - if (opt_xmalloc) { - malloc_write(": Error in calloc(): out of " - "memory\n"); - abort(); - } -#endif - errno = ENOMEM; - } - -#ifdef JEMALLOC_PROF - if (opt_prof && ret != NULL) - prof_malloc(ret, cnt); -#endif - return (ret); -} - -JEMALLOC_ATTR(visibility("default")) -void * -JEMALLOC_P(realloc)(void *ptr, size_t size) -{ - void *ret; -#ifdef JEMALLOC_PROF - size_t old_size; - prof_thr_cnt_t *cnt, *old_cnt; -#endif - - if (size == 0) { -#ifdef JEMALLOC_SYSV - if (opt_sysv == false) -#endif - size = 1; -#ifdef JEMALLOC_SYSV - else { - if (ptr != NULL) { -#ifdef JEMALLOC_PROF - if (opt_prof) { - old_size = isalloc(ptr); - old_cnt = prof_cnt_get(ptr); - cnt = NULL; - } -#endif - idalloc(ptr); - } -#ifdef JEMALLOC_PROF - else if (opt_prof) { - old_size = 0; - old_cnt = NULL; - cnt = NULL; - } -#endif - ret = NULL; - goto RETURN; - } -#endif - } - - if (ptr != NULL) { - assert(malloc_initialized || malloc_initializer == - pthread_self()); - -#ifdef JEMALLOC_PROF - if (opt_prof) { - old_size = isalloc(ptr); - old_cnt = prof_cnt_get(ptr); - if ((cnt = prof_alloc_prep(size)) == NULL) { - ret = NULL; - goto OOM; - } - if (prof_promote && (uintptr_t)cnt != (uintptr_t)1U && - size <= small_maxclass) { - ret = iralloc(ptr, small_maxclass+1); - if (ret != NULL) - arena_prof_promoted(ret, size); - } else - ret = iralloc(ptr, size); - } else -#endif - ret = iralloc(ptr, size); - -#ifdef JEMALLOC_PROF -OOM: -#endif - if (ret == NULL) { -#ifdef JEMALLOC_XMALLOC - if (opt_xmalloc) { - malloc_write(": Error in realloc(): " - "out of memory\n"); - abort(); - } -#endif - errno = ENOMEM; - } - } else { -#ifdef JEMALLOC_PROF - if (opt_prof) { - old_size = 0; - old_cnt = NULL; - } -#endif - if (malloc_init()) { -#ifdef JEMALLOC_PROF - if (opt_prof) - cnt = NULL; -#endif - ret = NULL; - } else { -#ifdef JEMALLOC_PROF - if (opt_prof) { - if ((cnt = prof_alloc_prep(size)) == NULL) - ret = NULL; - else { - if (prof_promote && (uintptr_t)cnt != - (uintptr_t)1U && size <= - small_maxclass) { - ret = imalloc(small_maxclass+1); - if (ret != NULL) { - arena_prof_promoted(ret, - size); - } - } else - ret = imalloc(size); - } - } else -#endif - ret = imalloc(size); - } - - if (ret == NULL) { -#ifdef JEMALLOC_XMALLOC - if (opt_xmalloc) { - malloc_write(": Error in realloc(): " - "out of memory\n"); - abort(); - } -#endif - errno = ENOMEM; - } - } - -#ifdef JEMALLOC_SYSV -RETURN: -#endif -#ifdef JEMALLOC_PROF - if (opt_prof) - prof_realloc(ret, cnt, ptr, old_size, old_cnt); -#endif - return (ret); -} - -JEMALLOC_ATTR(visibility("default")) -void -JEMALLOC_P(free)(void *ptr) -{ - - if (ptr != NULL) { - assert(malloc_initialized || malloc_initializer == - pthread_self()); - -#ifdef JEMALLOC_PROF - if (opt_prof) - prof_free(ptr); -#endif - idalloc(ptr); - } -} - -/* - * End malloc(3)-compatible functions. - */ -/******************************************************************************/ -/* - * Begin non-standard functions. - */ - -JEMALLOC_ATTR(visibility("default")) -size_t -JEMALLOC_P(malloc_usable_size)(const void *ptr) -{ - size_t ret; - - assert(ptr != NULL); - ret = isalloc(ptr); - - return (ret); -} - -#ifdef JEMALLOC_SWAP -JEMALLOC_ATTR(visibility("default")) -int -JEMALLOC_P(malloc_swap_enable)(const int *fds, unsigned nfds, int prezeroed) -{ - - /* - * Make sure malloc is initialized, because we need page size, chunk - * size, etc. - */ - if (malloc_init()) - return (-1); - - return (chunk_swap_enable(fds, nfds, (prezeroed != 0)) ? -1 : 0); -} -#endif - -JEMALLOC_ATTR(visibility("default")) -void -JEMALLOC_P(malloc_stats_print)(void (*write_cb)(void *, const char *), - void *cbopaque, const char *opts) -{ - - stats_print(write_cb, cbopaque, opts); -} - -JEMALLOC_ATTR(visibility("default")) -int -JEMALLOC_P(mallctl)(const char *name, void *oldp, size_t *oldlenp, void *newp, - size_t newlen) -{ - - if (malloc_init()) - return (EAGAIN); - - return (ctl_byname(name, oldp, oldlenp, newp, newlen)); -} - -JEMALLOC_ATTR(visibility("default")) -int -JEMALLOC_P(mallctlnametomib)(const char *name, size_t *mibp, size_t *miblenp) -{ - - if (malloc_init()) - return (EAGAIN); - - return (ctl_nametomib(name, mibp, miblenp)); -} - -JEMALLOC_ATTR(visibility("default")) -int -JEMALLOC_P(mallctlbymib)(const size_t *mib, size_t miblen, void *oldp, - size_t *oldlenp, void *newp, size_t newlen) -{ - - if (malloc_init()) - return (EAGAIN); - - return (ctl_bymib(mib, miblen, oldp, oldlenp, newp, newlen)); -} - -/* - * End non-standard functions. - */ -/******************************************************************************/ - -/* - * The following functions are used by threading libraries for protection of - * malloc during fork(). These functions are only called if the program is - * running in threaded mode, so there is no need to check whether the program - * is threaded here. - */ - -static void -jemalloc_prefork(void) -{ - unsigned i; - - /* Acquire all mutexes in a safe order. */ - - malloc_mutex_lock(&arenas_lock); - for (i = 0; i < narenas; i++) { - if (arenas[i] != NULL) - malloc_mutex_lock(&arenas[i]->lock); - } - - malloc_mutex_lock(&base_mtx); - - malloc_mutex_lock(&huge_mtx); - -#ifdef JEMALLOC_DSS - malloc_mutex_lock(&dss_mtx); -#endif - -#ifdef JEMALLOC_SWAP - malloc_mutex_lock(&swap_mtx); -#endif -} - -static void -jemalloc_postfork(void) -{ - unsigned i; - - /* Release all mutexes, now that fork() has completed. */ - -#ifdef JEMALLOC_SWAP - malloc_mutex_unlock(&swap_mtx); -#endif - -#ifdef JEMALLOC_DSS - malloc_mutex_unlock(&dss_mtx); -#endif - - malloc_mutex_unlock(&huge_mtx); - - malloc_mutex_unlock(&base_mtx); - - for (i = 0; i < narenas; i++) { - if (arenas[i] != NULL) - malloc_mutex_unlock(&arenas[i]->lock); - } - malloc_mutex_unlock(&arenas_lock); -} diff --git a/externals/jemalloc/jemalloc/internal/arena.h b/externals/jemalloc/jemalloc/internal/arena.h deleted file mode 100644 index bb4ce2a54f7..00000000000 --- a/externals/jemalloc/jemalloc/internal/arena.h +++ /dev/null @@ -1,537 +0,0 @@ -/******************************************************************************/ -#ifdef JEMALLOC_H_TYPES - -/* - * Subpages are an artificially designated partitioning of pages. Their only - * purpose is to support subpage-spaced size classes. - * - * There must be at least 4 subpages per page, due to the way size classes are - * handled. - */ -#define LG_SUBPAGE 8 -#define SUBPAGE ((size_t)(1U << LG_SUBPAGE)) -#define SUBPAGE_MASK (SUBPAGE - 1) - -/* Return the smallest subpage multiple that is >= s. */ -#define SUBPAGE_CEILING(s) \ - (((s) + SUBPAGE_MASK) & ~SUBPAGE_MASK) - -#ifdef JEMALLOC_TINY - /* Smallest size class to support. */ -# define LG_TINY_MIN LG_SIZEOF_PTR -#endif - -/* - * Maximum size class that is a multiple of the quantum, but not (necessarily) - * a power of 2. Above this size, allocations are rounded up to the nearest - * power of 2. - */ -#define LG_QSPACE_MAX_DEFAULT 7 - -/* - * Maximum size class that is a multiple of the cacheline, but not (necessarily) - * a power of 2. Above this size, allocations are rounded up to the nearest - * power of 2. - */ -#define LG_CSPACE_MAX_DEFAULT 9 - -/* - * RUN_MAX_OVRHD indicates maximum desired run header overhead. Runs are sized - * as small as possible such that this setting is still honored, without - * violating other constraints. The goal is to make runs as small as possible - * without exceeding a per run external fragmentation threshold. - * - * We use binary fixed point math for overhead computations, where the binary - * point is implicitly RUN_BFP bits to the left. - * - * Note that it is possible to set RUN_MAX_OVRHD low enough that it cannot be - * honored for some/all object sizes, since there is one bit of header overhead - * per object (plus a constant). This constraint is relaxed (ignored) for runs - * that are so small that the per-region overhead is greater than: - * - * (RUN_MAX_OVRHD / (reg_size << (3+RUN_BFP)) - */ -#define RUN_BFP 12 -/* \/ Implicit binary fixed point. */ -#define RUN_MAX_OVRHD 0x0000003dU -#define RUN_MAX_OVRHD_RELAX 0x00001800U - -/* - * The minimum ratio of active:dirty pages per arena is computed as: - * - * (nactive >> opt_lg_dirty_mult) >= ndirty - * - * So, supposing that opt_lg_dirty_mult is 5, there can be no less than 32 - * times as many active pages as dirty pages. - */ -#define LG_DIRTY_MULT_DEFAULT 5 - -typedef struct arena_chunk_map_s arena_chunk_map_t; -typedef struct arena_chunk_s arena_chunk_t; -typedef struct arena_run_s arena_run_t; -typedef struct arena_bin_s arena_bin_t; -typedef struct arena_s arena_t; - -#endif /* JEMALLOC_H_TYPES */ -/******************************************************************************/ -#ifdef JEMALLOC_H_STRUCTS - -/* Each element of the chunk map corresponds to one page within the chunk. */ -struct arena_chunk_map_s { - union { - /* - * Linkage for run trees. There are two disjoint uses: - * - * 1) arena_t's runs_avail_{clean,dirty} trees. - * 2) arena_run_t conceptually uses this linkage for in-use - * non-full runs, rather than directly embedding linkage. - */ - rb_node(arena_chunk_map_t) rb_link; - /* - * List of runs currently in purgatory. arena_chunk_purge() - * temporarily allocates runs that contain dirty pages while - * purging, so that other threads cannot use the runs while the - * purging thread is operating without the arena lock held. - */ - ql_elm(arena_chunk_map_t) ql_link; - } u; - -#ifdef JEMALLOC_PROF - /* Profile counters, used for large object runs. */ - prof_thr_cnt_t *prof_cnt; -#endif - - /* - * Run address (or size) and various flags are stored together. The bit - * layout looks like (assuming 32-bit system): - * - * ???????? ???????? ????---- ----dzla - * - * ? : Unallocated: Run address for first/last pages, unset for internal - * pages. - * Small: Run page offset. - * Large: Run size for first page, unset for trailing pages. - * - : Unused. - * d : dirty? - * z : zeroed? - * l : large? - * a : allocated? - * - * Following are example bit patterns for the three types of runs. - * - * p : run page offset - * s : run size - * c : size class (used only if prof_promote is true) - * x : don't care - * - : 0 - * + : 1 - * [DZLA] : bit set - * [dzla] : bit unset - * - * Unallocated (clean): - * ssssssss ssssssss ssss---- ----dz-- - * xxxxxxxx xxxxxxxx xxxx---- -----Zxx - * ssssssss ssssssss ssss---- ----dZ-- - * - * Unallocated (dirty): - * ssssssss ssssssss ssss---- ----D--- - * xxxxxxxx xxxxxxxx xxxx---- ----xxxx - * ssssssss ssssssss ssss---- ----D--- - * - * Small: - * pppppppp pppppppp pppp---- ----d--a - * pppppppp pppppppp pppp---- -------a - * pppppppp pppppppp pppp---- ----d--a - * - * Large: - * ssssssss ssssssss ssss++++ ++++D-la - * xxxxxxxx xxxxxxxx xxxx---- ----xxxx - * -------- -------- -------- ----D-la - * - * Large (sampled, size <= PAGE_SIZE): - * ssssssss ssssssss sssscccc ccccD-la - * - * Large (not sampled, size == PAGE_SIZE): - * ssssssss ssssssss ssss++++ ++++D-la - */ - size_t bits; -#ifdef JEMALLOC_PROF -#define CHUNK_MAP_CLASS_SHIFT 4 -#define CHUNK_MAP_CLASS_MASK ((size_t)0xff0U) -#endif -#define CHUNK_MAP_FLAGS_MASK ((size_t)0xfU) -#define CHUNK_MAP_DIRTY ((size_t)0x8U) -#define CHUNK_MAP_ZEROED ((size_t)0x4U) -#define CHUNK_MAP_LARGE ((size_t)0x2U) -#define CHUNK_MAP_ALLOCATED ((size_t)0x1U) -#define CHUNK_MAP_KEY CHUNK_MAP_ALLOCATED -}; -typedef rb_tree(arena_chunk_map_t) arena_avail_tree_t; -typedef rb_tree(arena_chunk_map_t) arena_run_tree_t; - -/* Arena chunk header. */ -struct arena_chunk_s { - /* Arena that owns the chunk. */ - arena_t *arena; - - /* Linkage for the arena's chunks_dirty list. */ - ql_elm(arena_chunk_t) link_dirty; - - /* - * True if the chunk is currently in the chunks_dirty list, due to - * having at some point contained one or more dirty pages. Removal - * from chunks_dirty is lazy, so (dirtied && ndirty == 0) is possible. - */ - bool dirtied; - - /* Number of dirty pages. */ - size_t ndirty; - - /* Map of pages within chunk that keeps track of free/large/small. */ - arena_chunk_map_t map[1]; /* Dynamically sized. */ -}; -typedef rb_tree(arena_chunk_t) arena_chunk_tree_t; - -struct arena_run_s { -#ifdef JEMALLOC_DEBUG - uint32_t magic; -# define ARENA_RUN_MAGIC 0x384adf93 -#endif - - /* Bin this run is associated with. */ - arena_bin_t *bin; - - /* Stack of available freed regions, or NULL. */ - void *avail; - - /* Next region that has never been allocated, or run boundary. */ - void *next; - - /* Number of free regions in run. */ - unsigned nfree; -}; - -struct arena_bin_s { - /* - * All operations on runcur, runs, and stats require that lock be - * locked. Run allocation/deallocation are protected by the arena lock, - * which may be acquired while holding one or more bin locks, but not - * vise versa. - */ - malloc_mutex_t lock; - - /* - * Current run being used to service allocations of this bin's size - * class. - */ - arena_run_t *runcur; - - /* - * Tree of non-full runs. This tree is used when looking for an - * existing run when runcur is no longer usable. We choose the - * non-full run that is lowest in memory; this policy tends to keep - * objects packed well, and it can also help reduce the number of - * almost-empty chunks. - */ - arena_run_tree_t runs; - - /* Size of regions in a run for this bin's size class. */ - size_t reg_size; - - /* Total size of a run for this bin's size class. */ - size_t run_size; - - /* Total number of regions in a run for this bin's size class. */ - uint32_t nregs; - -#ifdef JEMALLOC_PROF - /* - * Offset of first (prof_cnt_t *) in a run header for this bin's size - * class, or 0 if (opt_prof == false). - */ - uint32_t cnt0_offset; -#endif - - /* Offset of first region in a run for this bin's size class. */ - uint32_t reg0_offset; - -#ifdef JEMALLOC_STATS - /* Bin statistics. */ - malloc_bin_stats_t stats; -#endif -}; - -struct arena_s { -#ifdef JEMALLOC_DEBUG - uint32_t magic; -# define ARENA_MAGIC 0x947d3d24 -#endif - - /* This arena's index within the arenas array. */ - unsigned ind; - - /* - * All non-bin-related operations on this arena require that lock be - * locked. - */ - malloc_mutex_t lock; - -#ifdef JEMALLOC_STATS - arena_stats_t stats; -# ifdef JEMALLOC_TCACHE - /* - * List of tcaches for extant threads associated with this arena. - * Stats from these are merged incrementally, and at exit. - */ - ql_head(tcache_t) tcache_ql; -# endif -#endif - -#ifdef JEMALLOC_PROF - uint64_t prof_accumbytes; -#endif - - /* List of dirty-page-containing chunks this arena manages. */ - ql_head(arena_chunk_t) chunks_dirty; - - /* - * In order to avoid rapid chunk allocation/deallocation when an arena - * oscillates right on the cusp of needing a new chunk, cache the most - * recently freed chunk. The spare is left in the arena's chunk trees - * until it is deleted. - * - * There is one spare chunk per arena, rather than one spare total, in - * order to avoid interactions between multiple threads that could make - * a single spare inadequate. - */ - arena_chunk_t *spare; - - /* Number of pages in active runs. */ - size_t nactive; - - /* - * Current count of pages within unused runs that are potentially - * dirty, and for which madvise(... MADV_DONTNEED) has not been called. - * By tracking this, we can institute a limit on how much dirty unused - * memory is mapped for each arena. - */ - size_t ndirty; - - /* - * Approximate number of pages being purged. It is possible for - * multiple threads to purge dirty pages concurrently, and they use - * npurgatory to indicate the total number of pages all threads are - * attempting to purge. - */ - size_t npurgatory; - - /* - * Size/address-ordered trees of this arena's available runs. The trees - * are used for first-best-fit run allocation. The dirty tree contains - * runs with dirty pages (i.e. very likely to have been touched and - * therefore have associated physical pages), whereas the clean tree - * contains runs with pages that either have no associated physical - * pages, or have pages that the kernel may recycle at any time due to - * previous madvise(2) calls. The dirty tree is used in preference to - * the clean tree for allocations, because using dirty pages reduces - * the amount of dirty purging necessary to keep the active:dirty page - * ratio below the purge threshold. - */ - arena_avail_tree_t runs_avail_clean; - arena_avail_tree_t runs_avail_dirty; - - /* - * bins is used to store trees of free regions of the following sizes, - * assuming a 16-byte quantum, 4 KiB page size, and default - * JEMALLOC_OPTIONS. - * - * bins[i] | size | - * --------+--------+ - * 0 | 2 | - * 1 | 4 | - * 2 | 8 | - * --------+--------+ - * 3 | 16 | - * 4 | 32 | - * 5 | 48 | - * : : - * 8 | 96 | - * 9 | 112 | - * 10 | 128 | - * --------+--------+ - * 11 | 192 | - * 12 | 256 | - * 13 | 320 | - * 14 | 384 | - * 15 | 448 | - * 16 | 512 | - * --------+--------+ - * 17 | 768 | - * 18 | 1024 | - * 19 | 1280 | - * : : - * 27 | 3328 | - * 28 | 3584 | - * 29 | 3840 | - * --------+--------+ - * 30 | 4 KiB | - * 31 | 6 KiB | - * 33 | 8 KiB | - * : : - * 43 | 28 KiB | - * 44 | 30 KiB | - * 45 | 32 KiB | - * --------+--------+ - */ - arena_bin_t bins[1]; /* Dynamically sized. */ -}; - -#endif /* JEMALLOC_H_STRUCTS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_EXTERNS - -extern size_t opt_lg_qspace_max; -extern size_t opt_lg_cspace_max; -extern ssize_t opt_lg_dirty_mult; -extern uint8_t const *small_size2bin; - -/* Various bin-related settings. */ -#ifdef JEMALLOC_TINY /* Number of (2^n)-spaced tiny bins. */ -# define ntbins ((unsigned)(LG_QUANTUM - LG_TINY_MIN)) -#else -# define ntbins 0 -#endif -extern unsigned nqbins; /* Number of quantum-spaced bins. */ -extern unsigned ncbins; /* Number of cacheline-spaced bins. */ -extern unsigned nsbins; /* Number of subpage-spaced bins. */ -extern unsigned nbins; -#ifdef JEMALLOC_TINY -# define tspace_max ((size_t)(QUANTUM >> 1)) -#endif -#define qspace_min QUANTUM -extern size_t qspace_max; -extern size_t cspace_min; -extern size_t cspace_max; -extern size_t sspace_min; -extern size_t sspace_max; -#define small_maxclass sspace_max - -#define nlclasses (chunk_npages - arena_chunk_header_npages) - -#ifdef JEMALLOC_TCACHE -void arena_tcache_fill_small(arena_t *arena, tcache_bin_t *tbin, - size_t binind -# ifdef JEMALLOC_PROF - , uint64_t prof_accumbytes -# endif - ); -#endif -#ifdef JEMALLOC_PROF -void arena_prof_accum(arena_t *arena, uint64_t accumbytes); -#endif -void *arena_malloc_small(arena_t *arena, size_t size, bool zero); -void *arena_malloc_large(arena_t *arena, size_t size, bool zero); -void *arena_malloc(size_t size, bool zero); -void *arena_palloc(arena_t *arena, size_t alignment, size_t size, - size_t alloc_size); -size_t arena_salloc(const void *ptr); -#ifdef JEMALLOC_PROF -void arena_prof_promoted(const void *ptr, size_t size); -size_t arena_salloc_demote(const void *ptr); -prof_thr_cnt_t *arena_prof_cnt_get(const void *ptr); -void arena_prof_cnt_set(const void *ptr, prof_thr_cnt_t *cnt); -#endif -void arena_dalloc_bin(arena_t *arena, arena_chunk_t *chunk, void *ptr, - arena_chunk_map_t *mapelm); -void arena_dalloc_large(arena_t *arena, arena_chunk_t *chunk, void *ptr); -#ifdef JEMALLOC_STATS -void arena_stats_merge(arena_t *arena, size_t *nactive, size_t *ndirty, - arena_stats_t *astats, malloc_bin_stats_t *bstats, - malloc_large_stats_t *lstats); -#endif -void *arena_ralloc(void *ptr, size_t size, size_t oldsize); -bool arena_new(arena_t *arena, unsigned ind); -bool arena_boot(void); - -#endif /* JEMALLOC_H_EXTERNS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_INLINES - -#ifndef JEMALLOC_ENABLE_INLINE -void arena_dalloc(arena_t *arena, arena_chunk_t *chunk, void *ptr); -#endif - -#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_ARENA_C_)) -JEMALLOC_INLINE void -arena_dalloc(arena_t *arena, arena_chunk_t *chunk, void *ptr) -{ - size_t pageind; - arena_chunk_map_t *mapelm; - - assert(arena != NULL); - assert(arena->magic == ARENA_MAGIC); - assert(chunk->arena == arena); - assert(ptr != NULL); - assert(CHUNK_ADDR2BASE(ptr) != ptr); - - pageind = (((uintptr_t)ptr - (uintptr_t)chunk) >> PAGE_SHIFT); - mapelm = &chunk->map[pageind]; - assert((mapelm->bits & CHUNK_MAP_ALLOCATED) != 0); - if ((mapelm->bits & CHUNK_MAP_LARGE) == 0) { - /* Small allocation. */ -#ifdef JEMALLOC_TCACHE - tcache_t *tcache; - - if ((tcache = tcache_get()) != NULL) - tcache_dalloc_small(tcache, ptr); - else { -#endif - arena_run_t *run; - arena_bin_t *bin; - - run = (arena_run_t *)((uintptr_t)chunk + - (uintptr_t)((pageind - (mapelm->bits >> - PAGE_SHIFT)) << PAGE_SHIFT)); - assert(run->magic == ARENA_RUN_MAGIC); - assert(((uintptr_t)ptr - ((uintptr_t)run + - (uintptr_t)run->bin->reg0_offset)) % - run->bin->reg_size == 0); - bin = run->bin; - malloc_mutex_lock(&bin->lock); - arena_dalloc_bin(arena, chunk, ptr, mapelm); - malloc_mutex_unlock(&bin->lock); -#ifdef JEMALLOC_TCACHE - } -#endif - } else { -#ifdef JEMALLOC_TCACHE - size_t size = mapelm->bits & ~PAGE_MASK; - - assert(((uintptr_t)ptr & PAGE_MASK) == 0); - if (size <= tcache_maxclass) { - tcache_t *tcache; - - if ((tcache = tcache_get()) != NULL) - tcache_dalloc_large(tcache, ptr, size); - else { - malloc_mutex_lock(&arena->lock); - arena_dalloc_large(arena, chunk, ptr); - malloc_mutex_unlock(&arena->lock); - } - } else { - malloc_mutex_lock(&arena->lock); - arena_dalloc_large(arena, chunk, ptr); - malloc_mutex_unlock(&arena->lock); - } -#else - assert(((uintptr_t)ptr & PAGE_MASK) == 0); - malloc_mutex_lock(&arena->lock); - arena_dalloc_large(arena, chunk, ptr); - malloc_mutex_unlock(&arena->lock); -#endif - } -} -#endif - -#endif /* JEMALLOC_H_INLINES */ -/******************************************************************************/ diff --git a/externals/jemalloc/jemalloc/internal/base.h b/externals/jemalloc/jemalloc/internal/base.h deleted file mode 100644 index e353f309bd2..00000000000 --- a/externals/jemalloc/jemalloc/internal/base.h +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************/ -#ifdef JEMALLOC_H_TYPES - -#endif /* JEMALLOC_H_TYPES */ -/******************************************************************************/ -#ifdef JEMALLOC_H_STRUCTS - -#endif /* JEMALLOC_H_STRUCTS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_EXTERNS - -extern malloc_mutex_t base_mtx; - -void *base_alloc(size_t size); -extent_node_t *base_node_alloc(void); -void base_node_dealloc(extent_node_t *node); -bool base_boot(void); - -#endif /* JEMALLOC_H_EXTERNS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_INLINES - -#endif /* JEMALLOC_H_INLINES */ -/******************************************************************************/ diff --git a/externals/jemalloc/jemalloc/internal/chunk.h b/externals/jemalloc/jemalloc/internal/chunk.h deleted file mode 100644 index 1f6abf782f1..00000000000 --- a/externals/jemalloc/jemalloc/internal/chunk.h +++ /dev/null @@ -1,61 +0,0 @@ -/******************************************************************************/ -#ifdef JEMALLOC_H_TYPES - -/* - * Size and alignment of memory chunks that are allocated by the OS's virtual - * memory system. - */ -#define LG_CHUNK_DEFAULT 22 - -/* Return the chunk address for allocation address a. */ -#define CHUNK_ADDR2BASE(a) \ - ((void *)((uintptr_t)(a) & ~chunksize_mask)) - -/* Return the chunk offset of address a. */ -#define CHUNK_ADDR2OFFSET(a) \ - ((size_t)((uintptr_t)(a) & chunksize_mask)) - -/* Return the smallest chunk multiple that is >= s. */ -#define CHUNK_CEILING(s) \ - (((s) + chunksize_mask) & ~chunksize_mask) - -#endif /* JEMALLOC_H_TYPES */ -/******************************************************************************/ -#ifdef JEMALLOC_H_STRUCTS - -#endif /* JEMALLOC_H_STRUCTS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_EXTERNS - -extern size_t opt_lg_chunk; -#ifdef JEMALLOC_SWAP -extern bool opt_overcommit; -#endif - -#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) -/* Protects stats_chunks; currently not used for any other purpose. */ -extern malloc_mutex_t chunks_mtx; -/* Chunk statistics. */ -extern chunk_stats_t stats_chunks; -#endif - -extern size_t chunksize; -extern size_t chunksize_mask; /* (chunksize - 1). */ -extern size_t chunk_npages; -extern size_t arena_chunk_header_npages; -extern size_t arena_maxclass; /* Max size class for arenas. */ - -void *chunk_alloc(size_t size, bool *zero); -void chunk_dealloc(void *chunk, size_t size); -bool chunk_boot(void); - -#endif /* JEMALLOC_H_EXTERNS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_INLINES - -#endif /* JEMALLOC_H_INLINES */ -/******************************************************************************/ - -#include "jemalloc/internal/chunk_swap.h" -#include "jemalloc/internal/chunk_dss.h" -#include "jemalloc/internal/chunk_mmap.h" diff --git a/externals/jemalloc/jemalloc/internal/chunk_dss.h b/externals/jemalloc/jemalloc/internal/chunk_dss.h deleted file mode 100644 index 6be4ad1f212..00000000000 --- a/externals/jemalloc/jemalloc/internal/chunk_dss.h +++ /dev/null @@ -1,29 +0,0 @@ -#ifdef JEMALLOC_DSS -/******************************************************************************/ -#ifdef JEMALLOC_H_TYPES - -#endif /* JEMALLOC_H_TYPES */ -/******************************************************************************/ -#ifdef JEMALLOC_H_STRUCTS - -#endif /* JEMALLOC_H_STRUCTS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_EXTERNS - -/* - * Protects sbrk() calls. This avoids malloc races among threads, though it - * does not protect against races with threads that call sbrk() directly. - */ -extern malloc_mutex_t dss_mtx; - -void *chunk_alloc_dss(size_t size, bool *zero); -bool chunk_dealloc_dss(void *chunk, size_t size); -bool chunk_dss_boot(void); - -#endif /* JEMALLOC_H_EXTERNS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_INLINES - -#endif /* JEMALLOC_H_INLINES */ -/******************************************************************************/ -#endif /* JEMALLOC_DSS */ diff --git a/externals/jemalloc/jemalloc/internal/chunk_mmap.h b/externals/jemalloc/jemalloc/internal/chunk_mmap.h deleted file mode 100644 index 8fb90b77c9b..00000000000 --- a/externals/jemalloc/jemalloc/internal/chunk_mmap.h +++ /dev/null @@ -1,20 +0,0 @@ -/******************************************************************************/ -#ifdef JEMALLOC_H_TYPES - -#endif /* JEMALLOC_H_TYPES */ -/******************************************************************************/ -#ifdef JEMALLOC_H_STRUCTS - -#endif /* JEMALLOC_H_STRUCTS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_EXTERNS - -void *chunk_alloc_mmap(size_t size); -void chunk_dealloc_mmap(void *chunk, size_t size); - -#endif /* JEMALLOC_H_EXTERNS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_INLINES - -#endif /* JEMALLOC_H_INLINES */ -/******************************************************************************/ diff --git a/externals/jemalloc/jemalloc/internal/chunk_swap.h b/externals/jemalloc/jemalloc/internal/chunk_swap.h deleted file mode 100644 index d50cb197449..00000000000 --- a/externals/jemalloc/jemalloc/internal/chunk_swap.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifdef JEMALLOC_SWAP -/******************************************************************************/ -#ifdef JEMALLOC_H_TYPES - -#endif /* JEMALLOC_H_TYPES */ -/******************************************************************************/ -#ifdef JEMALLOC_H_STRUCTS - -#endif /* JEMALLOC_H_STRUCTS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_EXTERNS - -extern malloc_mutex_t swap_mtx; -extern bool swap_enabled; -extern bool swap_prezeroed; -extern size_t swap_nfds; -extern int *swap_fds; -#ifdef JEMALLOC_STATS -extern size_t swap_avail; -#endif - -void *chunk_alloc_swap(size_t size, bool *zero); -bool chunk_dealloc_swap(void *chunk, size_t size); -bool chunk_swap_enable(const int *fds, unsigned nfds, bool prezeroed); -bool chunk_swap_boot(void); - -#endif /* JEMALLOC_H_EXTERNS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_INLINES - -#endif /* JEMALLOC_H_INLINES */ -/******************************************************************************/ -#endif /* JEMALLOC_SWAP */ diff --git a/externals/jemalloc/jemalloc/internal/ckh.h b/externals/jemalloc/jemalloc/internal/ckh.h deleted file mode 100644 index c39ea5c75ef..00000000000 --- a/externals/jemalloc/jemalloc/internal/ckh.h +++ /dev/null @@ -1,95 +0,0 @@ -/******************************************************************************/ -#ifdef JEMALLOC_H_TYPES - -typedef struct ckh_s ckh_t; -typedef struct ckhc_s ckhc_t; - -/* Typedefs to allow easy function pointer passing. */ -typedef void ckh_hash_t (const void *, unsigned, size_t *, size_t *); -typedef bool ckh_keycomp_t (const void *, const void *); - -/* Maintain counters used to get an idea of performance. */ -/* #define CKH_COUNT */ -/* Print counter values in ckh_delete() (requires CKH_COUNT). */ -/* #define CKH_VERBOSE */ - -/* - * There are 2^LG_CKH_BUCKET_CELLS cells in each hash table bucket. Try to fit - * one bucket per L1 cache line. - */ -#define LG_CKH_BUCKET_CELLS (LG_CACHELINE - LG_SIZEOF_PTR - 1) - -#endif /* JEMALLOC_H_TYPES */ -/******************************************************************************/ -#ifdef JEMALLOC_H_STRUCTS - -/* Hash table cell. */ -struct ckhc_s { - const void *key; - const void *data; -}; - -struct ckh_s { -#ifdef JEMALLOC_DEBUG -#define CKH_MAGIG 0x3af2489d - uint32_t magic; -#endif - -#ifdef CKH_COUNT - /* Counters used to get an idea of performance. */ - uint64_t ngrows; - uint64_t nshrinks; - uint64_t nshrinkfails; - uint64_t ninserts; - uint64_t nrelocs; -#endif - - /* Used for pseudo-random number generation. */ -#define CKH_A 12345 -#define CKH_C 12347 - uint32_t prn_state; - - /* Total number of items. */ - size_t count; - - /* - * Minimum and current number of hash table buckets. There are - * 2^LG_CKH_BUCKET_CELLS cells per bucket. - */ - unsigned lg_minbuckets; - unsigned lg_curbuckets; - - /* Hash and comparison functions. */ - ckh_hash_t *hash; - ckh_keycomp_t *keycomp; - - /* Hash table with 2^lg_curbuckets buckets. */ - ckhc_t *tab; -}; - -#endif /* JEMALLOC_H_STRUCTS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_EXTERNS - -bool ckh_new(ckh_t *ckh, size_t minitems, ckh_hash_t *hash, - ckh_keycomp_t *keycomp); -void ckh_delete(ckh_t *ckh); -size_t ckh_count(ckh_t *ckh); -bool ckh_iter(ckh_t *ckh, size_t *tabind, void **key, void **data); -bool ckh_insert(ckh_t *ckh, const void *key, const void *data); -bool ckh_remove(ckh_t *ckh, const void *searchkey, void **key, - void **data); -bool ckh_search(ckh_t *ckh, const void *seachkey, void **key, void **data); -void ckh_string_hash(const void *key, unsigned minbits, size_t *hash1, - size_t *hash2); -bool ckh_string_keycomp(const void *k1, const void *k2); -void ckh_pointer_hash(const void *key, unsigned minbits, size_t *hash1, - size_t *hash2); -bool ckh_pointer_keycomp(const void *k1, const void *k2); - -#endif /* JEMALLOC_H_EXTERNS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_INLINES - -#endif /* JEMALLOC_H_INLINES */ -/******************************************************************************/ diff --git a/externals/jemalloc/jemalloc/internal/ctl.h b/externals/jemalloc/jemalloc/internal/ctl.h deleted file mode 100644 index 7bbf21e0e85..00000000000 --- a/externals/jemalloc/jemalloc/internal/ctl.h +++ /dev/null @@ -1,117 +0,0 @@ -/******************************************************************************/ -#ifdef JEMALLOC_H_TYPES - -typedef struct ctl_node_s ctl_node_t; -typedef struct ctl_arena_stats_s ctl_arena_stats_t; -typedef struct ctl_stats_s ctl_stats_t; - -#endif /* JEMALLOC_H_TYPES */ -/******************************************************************************/ -#ifdef JEMALLOC_H_STRUCTS - -struct ctl_node_s { - bool named; - union { - struct { - const char *name; - /* If (nchildren == 0), this is a terminal node. */ - unsigned nchildren; - const ctl_node_t *children; - } named; - struct { - const ctl_node_t *(*index)(const size_t *, size_t, - size_t); - } indexed; - } u; - int (*ctl)(const size_t *, size_t, void *, size_t *, void *, - size_t); -}; - -struct ctl_arena_stats_s { - bool initialized; - size_t pactive; - size_t pdirty; -#ifdef JEMALLOC_STATS - arena_stats_t astats; - - /* Aggregate stats for small size classes, based on bin stats. */ - size_t allocated_small; - uint64_t nmalloc_small; - uint64_t ndalloc_small; - uint64_t nrequests_small; - - malloc_bin_stats_t *bstats; /* nbins elements. */ - malloc_large_stats_t *lstats; /* nlclasses elements. */ -#endif -}; - -struct ctl_stats_s { -#ifdef JEMALLOC_STATS - size_t allocated; - size_t active; - size_t mapped; - struct { - size_t current; /* stats_chunks.curchunks */ - uint64_t total; /* stats_chunks.nchunks */ - size_t high; /* stats_chunks.highchunks */ - } chunks; - struct { - size_t allocated; /* huge_allocated */ - uint64_t nmalloc; /* huge_nmalloc */ - uint64_t ndalloc; /* huge_ndalloc */ - } huge; -#endif - ctl_arena_stats_t *arenas; /* (narenas + 1) elements. */ -#ifdef JEMALLOC_SWAP - size_t swap_avail; -#endif -}; - -#endif /* JEMALLOC_H_STRUCTS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_EXTERNS - -int ctl_byname(const char *name, void *oldp, size_t *oldlenp, void *newp, - size_t newlen); -int ctl_nametomib(const char *name, size_t *mibp, size_t *miblenp); - -int ctl_bymib(const size_t *mib, size_t miblen, void *oldp, size_t *oldlenp, - void *newp, size_t newlen); -bool ctl_boot(void); - -#define xmallctl(name, oldp, oldlenp, newp, newlen) do { \ - if (JEMALLOC_P(mallctl)(name, oldp, oldlenp, newp, newlen) \ - != 0) { \ - malloc_write(": Invalid xmallctl(\""); \ - malloc_write(name); \ - malloc_write("\", ...) call\n"); \ - abort(); \ - } \ -} while (0) - -#define xmallctlnametomib(name, mibp, miblenp) do { \ - if (JEMALLOC_P(mallctlnametomib)(name, mibp, miblenp) != 0) { \ - malloc_write( \ - ": Invalid xmallctlnametomib(\""); \ - malloc_write(name); \ - malloc_write("\", ...) call\n"); \ - abort(); \ - } \ -} while (0) - -#define xmallctlbymib(mib, miblen, oldp, oldlenp, newp, newlen) do { \ - if (JEMALLOC_P(mallctlbymib)(mib, miblen, oldp, oldlenp, newp, \ - newlen) != 0) { \ - malloc_write( \ - ": Invalid xmallctlbymib() call\n"); \ - abort(); \ - } \ -} while (0) - -#endif /* JEMALLOC_H_EXTERNS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_INLINES - -#endif /* JEMALLOC_H_INLINES */ -/******************************************************************************/ - diff --git a/externals/jemalloc/jemalloc/internal/extent.h b/externals/jemalloc/jemalloc/internal/extent.h deleted file mode 100644 index 33a4e9a3852..00000000000 --- a/externals/jemalloc/jemalloc/internal/extent.h +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************/ -#ifdef JEMALLOC_H_TYPES - -typedef struct extent_node_s extent_node_t; - -#endif /* JEMALLOC_H_TYPES */ -/******************************************************************************/ -#ifdef JEMALLOC_H_STRUCTS - -/* Tree of extents. */ -struct extent_node_s { -#if (defined(JEMALLOC_SWAP) || defined(JEMALLOC_DSS)) - /* Linkage for the size/address-ordered tree. */ - rb_node(extent_node_t) link_szad; -#endif - - /* Linkage for the address-ordered tree. */ - rb_node(extent_node_t) link_ad; - -#ifdef JEMALLOC_PROF - /* Profile counters, used for huge objects. */ - prof_thr_cnt_t *prof_cnt; -#endif - - /* Pointer to the extent that this tree node is responsible for. */ - void *addr; - - /* Total region size. */ - size_t size; -}; -typedef rb_tree(extent_node_t) extent_tree_t; - -#endif /* JEMALLOC_H_STRUCTS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_EXTERNS - -#if (defined(JEMALLOC_SWAP) || defined(JEMALLOC_DSS)) -rb_proto(, extent_tree_szad_, extent_tree_t, extent_node_t) -#endif - -rb_proto(, extent_tree_ad_, extent_tree_t, extent_node_t) - -#endif /* JEMALLOC_H_EXTERNS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_INLINES - -#endif /* JEMALLOC_H_INLINES */ -/******************************************************************************/ - diff --git a/externals/jemalloc/jemalloc/internal/hash.h b/externals/jemalloc/jemalloc/internal/hash.h deleted file mode 100644 index d12cdb8359f..00000000000 --- a/externals/jemalloc/jemalloc/internal/hash.h +++ /dev/null @@ -1,70 +0,0 @@ -/******************************************************************************/ -#ifdef JEMALLOC_H_TYPES - -#endif /* JEMALLOC_H_TYPES */ -/******************************************************************************/ -#ifdef JEMALLOC_H_STRUCTS - -#endif /* JEMALLOC_H_STRUCTS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_EXTERNS - -#endif /* JEMALLOC_H_EXTERNS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_INLINES - -#ifndef JEMALLOC_ENABLE_INLINE -uint64_t hash(const void *key, size_t len, uint64_t seed); -#endif - -#if (defined(JEMALLOC_ENABLE_INLINE) || defined(HASH_C_)) -/* - * The following hash function is based on MurmurHash64A(), placed into the - * public domain by Austin Appleby. See http://murmurhash.googlepages.com/ for - * details. - */ -JEMALLOC_INLINE uint64_t -hash(const void *key, size_t len, uint64_t seed) -{ - const uint64_t m = 0xc6a4a7935bd1e995; - const int r = 47; - uint64_t h = seed ^ (len * m); - const uint64_t *data = (const uint64_t *)key; - const uint64_t *end = data + (len/8); - const unsigned char *data2; - - assert(((uintptr_t)key & 0x7) == 0); - - while(data != end) { - uint64_t k = *data++; - - k *= m; - k ^= k >> r; - k *= m; - - h ^= k; - h *= m; - } - - data2 = (const unsigned char *)data; - switch(len & 7) { - case 7: h ^= ((uint64_t)(data2[6])) << 48; - case 6: h ^= ((uint64_t)(data2[5])) << 40; - case 5: h ^= ((uint64_t)(data2[4])) << 32; - case 4: h ^= ((uint64_t)(data2[3])) << 24; - case 3: h ^= ((uint64_t)(data2[2])) << 16; - case 2: h ^= ((uint64_t)(data2[1])) << 8; - case 1: h ^= ((uint64_t)(data2[0])); - h *= m; - } - - h ^= h >> r; - h *= m; - h ^= h >> r; - - return h; -} -#endif - -#endif /* JEMALLOC_H_INLINES */ -/******************************************************************************/ diff --git a/externals/jemalloc/jemalloc/internal/huge.h b/externals/jemalloc/jemalloc/internal/huge.h deleted file mode 100644 index 3cf32f7506d..00000000000 --- a/externals/jemalloc/jemalloc/internal/huge.h +++ /dev/null @@ -1,38 +0,0 @@ -/******************************************************************************/ -#ifdef JEMALLOC_H_TYPES - -#endif /* JEMALLOC_H_TYPES */ -/******************************************************************************/ -#ifdef JEMALLOC_H_STRUCTS - -#endif /* JEMALLOC_H_STRUCTS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_EXTERNS - -#ifdef JEMALLOC_STATS -/* Huge allocation statistics. */ -extern uint64_t huge_nmalloc; -extern uint64_t huge_ndalloc; -extern size_t huge_allocated; -#endif - -/* Protects chunk-related data structures. */ -extern malloc_mutex_t huge_mtx; - -void *huge_malloc(size_t size, bool zero); -void *huge_palloc(size_t alignment, size_t size); -void *huge_ralloc(void *ptr, size_t size, size_t oldsize); -void huge_dalloc(void *ptr); -size_t huge_salloc(const void *ptr); -#ifdef JEMALLOC_PROF -prof_thr_cnt_t *huge_prof_cnt_get(const void *ptr); -void huge_prof_cnt_set(const void *ptr, prof_thr_cnt_t *cnt); -#endif -bool huge_boot(void); - -#endif /* JEMALLOC_H_EXTERNS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_INLINES - -#endif /* JEMALLOC_H_INLINES */ -/******************************************************************************/ diff --git a/externals/jemalloc/jemalloc/internal/jemalloc_internal.h b/externals/jemalloc/jemalloc/internal/jemalloc_internal.h deleted file mode 100644 index 03782dd6690..00000000000 --- a/externals/jemalloc/jemalloc/internal/jemalloc_internal.h +++ /dev/null @@ -1,561 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#include -#include -#ifndef SIZE_T_MAX -# define SIZE_T_MAX SIZE_MAX -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define JEMALLOC_MANGLE -#include "../jemalloc.h" - -#ifdef JEMALLOC_LAZY_LOCK -#include -#endif - -#define RB_COMPACT -#include "jemalloc/internal/rb.h" -#include "jemalloc/internal/qr.h" -#include "jemalloc/internal/ql.h" - -extern void (*JEMALLOC_P(malloc_message))(void *wcbopaque, const char *s); - -/* - * Define a custom assert() in order to reduce the chances of deadlock during - * assertion failure. - */ -#ifdef JEMALLOC_DEBUG -# define assert(e) do { \ - if (!(e)) { \ - char line_buf[UMAX2S_BUFSIZE]; \ - malloc_write(": "); \ - malloc_write(__FILE__); \ - malloc_write(":"); \ - malloc_write(umax2s(__LINE__, 10, line_buf)); \ - malloc_write(": Failed assertion: "); \ - malloc_write("\""); \ - malloc_write(#e); \ - malloc_write("\"\n"); \ - abort(); \ - } \ -} while (0) -#else -#define assert(e) -#endif - -/* - * jemalloc can conceptually be broken into components (arena, tcache, etc.), - * but there are circular dependencies that cannot be broken without - * substantial performance degradation. In order to reduce the effect on - * visual code flow, read the header files in multiple passes, with one of the - * following cpp variables defined during each pass: - * - * JEMALLOC_H_TYPES : Preprocessor-defined constants and psuedo-opaque data - * types. - * JEMALLOC_H_STRUCTS : Data structures. - * JEMALLOC_H_EXTERNS : Extern data declarations and function prototypes. - * JEMALLOC_H_INLINES : Inline functions. - */ -/******************************************************************************/ -#define JEMALLOC_H_TYPES - -#define ZU(z) ((size_t)z) - -#ifndef __DECONST -# define __DECONST(type, var) ((type)(uintptr_t)(const void *)(var)) -#endif - -#ifdef JEMALLOC_DEBUG - /* Disable inlining to make debugging easier. */ -# define JEMALLOC_INLINE -# define inline -#else -# define JEMALLOC_ENABLE_INLINE -# define JEMALLOC_INLINE static inline -#endif - -/* Size of stack-allocated buffer passed to strerror_r(). */ -#define STRERROR_BUF 64 - -/* Minimum alignment of allocations is 2^LG_QUANTUM bytes. */ -#ifdef __i386__ -# define LG_QUANTUM 4 -#endif -#ifdef __ia64__ -# define LG_QUANTUM 4 -#endif -#ifdef __alpha__ -# define LG_QUANTUM 4 -#endif -#ifdef __sparc64__ -# define LG_QUANTUM 4 -#endif -#if (defined(__amd64__) || defined(__x86_64__)) -# define LG_QUANTUM 4 -#endif -#ifdef __arm__ -# define LG_QUANTUM 3 -#endif -#ifdef __mips__ -# define LG_QUANTUM 3 -#endif -#ifdef __powerpc__ -# define LG_QUANTUM 4 -#endif -#ifdef __s390x__ -# define LG_QUANTUM 4 -#endif - -#define QUANTUM ((size_t)(1U << LG_QUANTUM)) -#define QUANTUM_MASK (QUANTUM - 1) - -/* Return the smallest quantum multiple that is >= a. */ -#define QUANTUM_CEILING(a) \ - (((a) + QUANTUM_MASK) & ~QUANTUM_MASK) - -#define SIZEOF_PTR (1U << LG_SIZEOF_PTR) - -/* We can't use TLS in non-PIC programs, since TLS relies on loader magic. */ -#if (!defined(PIC) && !defined(NO_TLS)) -# define NO_TLS -#endif - -/* - * Maximum size of L1 cache line. This is used to avoid cache line aliasing. - * In addition, this controls the spacing of cacheline-spaced size classes. - */ -#define LG_CACHELINE 6 -#define CACHELINE ((size_t)(1U << LG_CACHELINE)) -#define CACHELINE_MASK (CACHELINE - 1) - -/* Return the smallest cacheline multiple that is >= s. */ -#define CACHELINE_CEILING(s) \ - (((s) + CACHELINE_MASK) & ~CACHELINE_MASK) - -/* - * Page size. STATIC_PAGE_SHIFT is determined by the configure script. If - * DYNAMIC_PAGE_SHIFT is enabled, only use the STATIC_PAGE_* macros where - * compile-time values are required for the purposes of defining data - * structures. - */ -#define STATIC_PAGE_SIZE ((size_t)(1U << STATIC_PAGE_SHIFT)) -#define STATIC_PAGE_MASK ((size_t)(STATIC_PAGE_SIZE - 1)) - -#ifdef DYNAMIC_PAGE_SHIFT -# define PAGE_SHIFT lg_pagesize -# define PAGE_SIZE pagesize -# define PAGE_MASK pagesize_mask -#else -# define PAGE_SHIFT STATIC_PAGE_SHIFT -# define PAGE_SIZE STATIC_PAGE_SIZE -# define PAGE_MASK STATIC_PAGE_MASK -#endif - -/* Return the smallest pagesize multiple that is >= s. */ -#define PAGE_CEILING(s) \ - (((s) + PAGE_MASK) & ~PAGE_MASK) - -#include "jemalloc/internal/totally_not_p_r_n.h" -#include "jemalloc/internal/ckh.h" -#include "jemalloc/internal/stats.h" -#include "jemalloc/internal/ctl.h" -#include "jemalloc/internal/mutex.h" -#include "jemalloc/internal/mb.h" -#include "jemalloc/internal/extent.h" -#include "jemalloc/internal/arena.h" -#include "jemalloc/internal/base.h" -#include "jemalloc/internal/chunk.h" -#include "jemalloc/internal/huge.h" -#include "jemalloc/internal/tcache.h" -#include "jemalloc/internal/hash.h" -#include "jemalloc/internal/prof.h" - -#undef JEMALLOC_H_TYPES -/******************************************************************************/ -#define JEMALLOC_H_STRUCTS - -#include "jemalloc/internal/totally_not_p_r_n.h" -#include "jemalloc/internal/ckh.h" -#include "jemalloc/internal/stats.h" -#include "jemalloc/internal/ctl.h" -#include "jemalloc/internal/mutex.h" -#include "jemalloc/internal/mb.h" -#include "jemalloc/internal/extent.h" -#include "jemalloc/internal/arena.h" -#include "jemalloc/internal/base.h" -#include "jemalloc/internal/chunk.h" -#include "jemalloc/internal/huge.h" -#include "jemalloc/internal/tcache.h" -#include "jemalloc/internal/hash.h" -#include "jemalloc/internal/prof.h" - -#undef JEMALLOC_H_STRUCTS -/******************************************************************************/ -#define JEMALLOC_H_EXTERNS - -extern bool opt_abort; -#ifdef JEMALLOC_FILL -extern bool opt_junk; -#endif -#ifdef JEMALLOC_SYSV -extern bool opt_sysv; -#endif -#ifdef JEMALLOC_XMALLOC -extern bool opt_xmalloc; -#endif -#ifdef JEMALLOC_FILL -extern bool opt_zero; -#endif - -#ifdef DYNAMIC_PAGE_SHIFT -extern size_t pagesize; -extern size_t pagesize_mask; -extern size_t lg_pagesize; -#endif - -/* Number of CPUs. */ -extern unsigned ncpus; - -extern malloc_mutex_t arenas_lock; /* Protects arenas initialization. */ -#ifndef NO_TLS -/* - * Map of pthread_self() --> arenas[???], used for selecting an arena to use - * for allocations. - */ -extern __thread arena_t *arenas_map JEMALLOC_ATTR(tls_model("initial-exec")); -#endif -/* - * Arenas that are used to service external requests. Not all elements of the - * arenas array are necessarily used; arenas are created lazily as needed. - */ -extern arena_t **arenas; -extern unsigned narenas; - -arena_t *arenas_extend(unsigned ind); -#ifndef NO_TLS -arena_t *choose_arena_hard(void); -#endif - -#include "jemalloc/internal/totally_not_p_r_n.h" -#include "jemalloc/internal/ckh.h" -#include "jemalloc/internal/stats.h" -#include "jemalloc/internal/ctl.h" -#include "jemalloc/internal/mutex.h" -#include "jemalloc/internal/mb.h" -#include "jemalloc/internal/extent.h" -#include "jemalloc/internal/arena.h" -#include "jemalloc/internal/base.h" -#include "jemalloc/internal/chunk.h" -#include "jemalloc/internal/huge.h" -#include "jemalloc/internal/tcache.h" -#include "jemalloc/internal/hash.h" -#include "jemalloc/internal/prof.h" - -#undef JEMALLOC_H_EXTERNS -/******************************************************************************/ -#define JEMALLOC_H_INLINES - -#include "jemalloc/internal/totally_not_p_r_n.h" -#include "jemalloc/internal/ckh.h" -#include "jemalloc/internal/stats.h" -#include "jemalloc/internal/ctl.h" -#include "jemalloc/internal/mutex.h" -#include "jemalloc/internal/mb.h" -#include "jemalloc/internal/extent.h" -#include "jemalloc/internal/base.h" -#include "jemalloc/internal/chunk.h" -#include "jemalloc/internal/huge.h" - -#ifndef JEMALLOC_ENABLE_INLINE -void malloc_write(const char *s); -arena_t *choose_arena(void); -#endif - -#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_C_)) -/* - * Wrapper around malloc_message() that avoids the need for - * JEMALLOC_P(malloc_message)(...) throughout the code. - */ -JEMALLOC_INLINE void -malloc_write(const char *s) -{ - - JEMALLOC_P(malloc_message)(NULL, s); -} - -/* - * Choose an arena based on a per-thread value (fast-path code, calls slow-path - * code if necessary). - */ -JEMALLOC_INLINE arena_t * -choose_arena(void) -{ - arena_t *ret; - - /* - * We can only use TLS if this is a PIC library, since for the static - * library version, libc's malloc is used by TLS allocation, which - * introduces a bootstrapping issue. - */ -#ifndef NO_TLS - ret = arenas_map; - if (ret == NULL) { - ret = choose_arena_hard(); - assert(ret != NULL); - } -#else - if (isthreaded && narenas > 1) { - unsigned long ind; - - /* - * Hash pthread_self() to one of the arenas. There is a prime - * number of arenas, so this has a reasonable chance of - * working. Even so, the hashing can be easily thwarted by - * inconvenient pthread_self() values. Without specific - * knowledge of how pthread_self() calculates values, we can't - * easily do much better than this. - */ - ind = (unsigned long) pthread_self() % narenas; - - /* - * Optimistially assume that arenas[ind] has been initialized. - * At worst, we find out that some other thread has already - * done so, after acquiring the lock in preparation. Note that - * this lazy locking also has the effect of lazily forcing - * cache coherency; without the lock acquisition, there's no - * guarantee that modification of arenas[ind] by another thread - * would be seen on this CPU for an arbitrary amount of time. - * - * In general, this approach to modifying a synchronized value - * isn't a good idea, but in this case we only ever modify the - * value once, so things work out well. - */ - ret = arenas[ind]; - if (ret == NULL) { - /* - * Avoid races with another thread that may have already - * initialized arenas[ind]. - */ - malloc_mutex_lock(&arenas_lock); - if (arenas[ind] == NULL) - ret = arenas_extend((unsigned)ind); - else - ret = arenas[ind]; - malloc_mutex_unlock(&arenas_lock); - } - } else - ret = arenas[0]; -#endif - - assert(ret != NULL); - return (ret); -} -#endif - -#include "jemalloc/internal/tcache.h" -#include "jemalloc/internal/arena.h" -#include "jemalloc/internal/hash.h" -#include "jemalloc/internal/prof.h" - -#ifndef JEMALLOC_ENABLE_INLINE -void *imalloc(size_t size); -void *icalloc(size_t size); -void *ipalloc(size_t alignment, size_t size); -size_t isalloc(const void *ptr); -void *iralloc(void *ptr, size_t size); -void idalloc(void *ptr); -#endif - -#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_C_)) -JEMALLOC_INLINE void * -imalloc(size_t size) -{ - - assert(size != 0); - - if (size <= arena_maxclass) - return (arena_malloc(size, false)); - else - return (huge_malloc(size, false)); -} - -JEMALLOC_INLINE void * -icalloc(size_t size) -{ - - if (size <= arena_maxclass) - return (arena_malloc(size, true)); - else - return (huge_malloc(size, true)); -} - -JEMALLOC_INLINE void * -ipalloc(size_t alignment, size_t size) -{ - void *ret; - size_t ceil_size; - - /* - * Round size up to the nearest multiple of alignment. - * - * This done, we can take advantage of the fact that for each small - * size class, every object is aligned at the smallest power of two - * that is non-zero in the base two representation of the size. For - * example: - * - * Size | Base 2 | Minimum alignment - * -----+----------+------------------ - * 96 | 1100000 | 32 - * 144 | 10100000 | 32 - * 192 | 11000000 | 64 - * - * Depending on runtime settings, it is possible that arena_malloc() - * will further round up to a power of two, but that never causes - * correctness issues. - */ - ceil_size = (size + (alignment - 1)) & (-alignment); - /* - * (ceil_size < size) protects against the combination of maximal - * alignment and size greater than maximal alignment. - */ - if (ceil_size < size) { - /* size_t overflow. */ - return (NULL); - } - - if (ceil_size <= PAGE_SIZE || (alignment <= PAGE_SIZE - && ceil_size <= arena_maxclass)) - ret = arena_malloc(ceil_size, false); - else { - size_t run_size; - - /* - * We can't achieve subpage alignment, so round up alignment - * permanently; it makes later calculations simpler. - */ - alignment = PAGE_CEILING(alignment); - ceil_size = PAGE_CEILING(size); - /* - * (ceil_size < size) protects against very large sizes within - * PAGE_SIZE of SIZE_T_MAX. - * - * (ceil_size + alignment < ceil_size) protects against the - * combination of maximal alignment and ceil_size large enough - * to cause overflow. This is similar to the first overflow - * check above, but it needs to be repeated due to the new - * ceil_size value, which may now be *equal* to maximal - * alignment, whereas before we only detected overflow if the - * original size was *greater* than maximal alignment. - */ - if (ceil_size < size || ceil_size + alignment < ceil_size) { - /* size_t overflow. */ - return (NULL); - } - - /* - * Calculate the size of the over-size run that arena_palloc() - * would need to allocate in order to guarantee the alignment. - */ - if (ceil_size >= alignment) - run_size = ceil_size + alignment - PAGE_SIZE; - else { - /* - * It is possible that (alignment << 1) will cause - * overflow, but it doesn't matter because we also - * subtract PAGE_SIZE, which in the case of overflow - * leaves us with a very large run_size. That causes - * the first conditional below to fail, which means - * that the bogus run_size value never gets used for - * anything important. - */ - run_size = (alignment << 1) - PAGE_SIZE; - } - - if (run_size <= arena_maxclass) { - ret = arena_palloc(choose_arena(), alignment, ceil_size, - run_size); - } else if (alignment <= chunksize) - ret = huge_malloc(ceil_size, false); - else - ret = huge_palloc(alignment, ceil_size); - } - - assert(((uintptr_t)ret & (alignment - 1)) == 0); - return (ret); -} - -JEMALLOC_INLINE size_t -isalloc(const void *ptr) -{ - size_t ret; - arena_chunk_t *chunk; - - assert(ptr != NULL); - - chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); - if (chunk != ptr) { - /* Region. */ - assert(chunk->arena->magic == ARENA_MAGIC); - -#ifdef JEMALLOC_PROF - ret = arena_salloc_demote(ptr); -#else - ret = arena_salloc(ptr); -#endif - } else - ret = huge_salloc(ptr); - - return (ret); -} - -JEMALLOC_INLINE void * -iralloc(void *ptr, size_t size) -{ - size_t oldsize; - - assert(ptr != NULL); - assert(size != 0); - - oldsize = isalloc(ptr); - - if (size <= arena_maxclass) - return (arena_ralloc(ptr, size, oldsize)); - else - return (huge_ralloc(ptr, size, oldsize)); -} - -JEMALLOC_INLINE void -idalloc(void *ptr) -{ - arena_chunk_t *chunk; - - assert(ptr != NULL); - - chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); - if (chunk != ptr) - arena_dalloc(chunk->arena, chunk, ptr); - else - huge_dalloc(ptr); -} -#endif - -#undef JEMALLOC_H_INLINES -/******************************************************************************/ diff --git a/externals/jemalloc/jemalloc/internal/jemalloc_internal.h.in b/externals/jemalloc/jemalloc/internal/jemalloc_internal.h.in deleted file mode 100644 index 2c3f32f126d..00000000000 --- a/externals/jemalloc/jemalloc/internal/jemalloc_internal.h.in +++ /dev/null @@ -1,561 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#include -#include -#ifndef SIZE_T_MAX -# define SIZE_T_MAX SIZE_MAX -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define JEMALLOC_MANGLE -#include "../jemalloc@install_suffix@.h" - -#ifdef JEMALLOC_LAZY_LOCK -#include -#endif - -#define RB_COMPACT -#include "jemalloc/internal/rb.h" -#include "jemalloc/internal/qr.h" -#include "jemalloc/internal/ql.h" - -extern void (*JEMALLOC_P(malloc_message))(void *wcbopaque, const char *s); - -/* - * Define a custom assert() in order to reduce the chances of deadlock during - * assertion failure. - */ -#ifdef JEMALLOC_DEBUG -# define assert(e) do { \ - if (!(e)) { \ - char line_buf[UMAX2S_BUFSIZE]; \ - malloc_write(": "); \ - malloc_write(__FILE__); \ - malloc_write(":"); \ - malloc_write(umax2s(__LINE__, 10, line_buf)); \ - malloc_write(": Failed assertion: "); \ - malloc_write("\""); \ - malloc_write(#e); \ - malloc_write("\"\n"); \ - abort(); \ - } \ -} while (0) -#else -#define assert(e) -#endif - -/* - * jemalloc can conceptually be broken into components (arena, tcache, etc.), - * but there are circular dependencies that cannot be broken without - * substantial performance degradation. In order to reduce the effect on - * visual code flow, read the header files in multiple passes, with one of the - * following cpp variables defined during each pass: - * - * JEMALLOC_H_TYPES : Preprocessor-defined constants and psuedo-opaque data - * types. - * JEMALLOC_H_STRUCTS : Data structures. - * JEMALLOC_H_EXTERNS : Extern data declarations and function prototypes. - * JEMALLOC_H_INLINES : Inline functions. - */ -/******************************************************************************/ -#define JEMALLOC_H_TYPES - -#define ZU(z) ((size_t)z) - -#ifndef __DECONST -# define __DECONST(type, var) ((type)(uintptr_t)(const void *)(var)) -#endif - -#ifdef JEMALLOC_DEBUG - /* Disable inlining to make debugging easier. */ -# define JEMALLOC_INLINE -# define inline -#else -# define JEMALLOC_ENABLE_INLINE -# define JEMALLOC_INLINE static inline -#endif - -/* Size of stack-allocated buffer passed to strerror_r(). */ -#define STRERROR_BUF 64 - -/* Minimum alignment of allocations is 2^LG_QUANTUM bytes. */ -#ifdef __i386__ -# define LG_QUANTUM 4 -#endif -#ifdef __ia64__ -# define LG_QUANTUM 4 -#endif -#ifdef __alpha__ -# define LG_QUANTUM 4 -#endif -#ifdef __sparc64__ -# define LG_QUANTUM 4 -#endif -#if (defined(__amd64__) || defined(__x86_64__)) -# define LG_QUANTUM 4 -#endif -#ifdef __arm__ -# define LG_QUANTUM 3 -#endif -#ifdef __mips__ -# define LG_QUANTUM 3 -#endif -#ifdef __powerpc__ -# define LG_QUANTUM 4 -#endif -#ifdef __s390x__ -# define LG_QUANTUM 4 -#endif - -#define QUANTUM ((size_t)(1U << LG_QUANTUM)) -#define QUANTUM_MASK (QUANTUM - 1) - -/* Return the smallest quantum multiple that is >= a. */ -#define QUANTUM_CEILING(a) \ - (((a) + QUANTUM_MASK) & ~QUANTUM_MASK) - -#define SIZEOF_PTR (1U << LG_SIZEOF_PTR) - -/* We can't use TLS in non-PIC programs, since TLS relies on loader magic. */ -#if (!defined(PIC) && !defined(NO_TLS)) -# define NO_TLS -#endif - -/* - * Maximum size of L1 cache line. This is used to avoid cache line aliasing. - * In addition, this controls the spacing of cacheline-spaced size classes. - */ -#define LG_CACHELINE 6 -#define CACHELINE ((size_t)(1U << LG_CACHELINE)) -#define CACHELINE_MASK (CACHELINE - 1) - -/* Return the smallest cacheline multiple that is >= s. */ -#define CACHELINE_CEILING(s) \ - (((s) + CACHELINE_MASK) & ~CACHELINE_MASK) - -/* - * Page size. STATIC_PAGE_SHIFT is determined by the configure script. If - * DYNAMIC_PAGE_SHIFT is enabled, only use the STATIC_PAGE_* macros where - * compile-time values are required for the purposes of defining data - * structures. - */ -#define STATIC_PAGE_SIZE ((size_t)(1U << STATIC_PAGE_SHIFT)) -#define STATIC_PAGE_MASK ((size_t)(STATIC_PAGE_SIZE - 1)) - -#ifdef DYNAMIC_PAGE_SHIFT -# define PAGE_SHIFT lg_pagesize -# define PAGE_SIZE pagesize -# define PAGE_MASK pagesize_mask -#else -# define PAGE_SHIFT STATIC_PAGE_SHIFT -# define PAGE_SIZE STATIC_PAGE_SIZE -# define PAGE_MASK STATIC_PAGE_MASK -#endif - -/* Return the smallest pagesize multiple that is >= s. */ -#define PAGE_CEILING(s) \ - (((s) + PAGE_MASK) & ~PAGE_MASK) - -#include "jemalloc/internal/prn.h" -#include "jemalloc/internal/ckh.h" -#include "jemalloc/internal/stats.h" -#include "jemalloc/internal/ctl.h" -#include "jemalloc/internal/mutex.h" -#include "jemalloc/internal/mb.h" -#include "jemalloc/internal/extent.h" -#include "jemalloc/internal/arena.h" -#include "jemalloc/internal/base.h" -#include "jemalloc/internal/chunk.h" -#include "jemalloc/internal/huge.h" -#include "jemalloc/internal/tcache.h" -#include "jemalloc/internal/hash.h" -#include "jemalloc/internal/prof.h" - -#undef JEMALLOC_H_TYPES -/******************************************************************************/ -#define JEMALLOC_H_STRUCTS - -#include "jemalloc/internal/prn.h" -#include "jemalloc/internal/ckh.h" -#include "jemalloc/internal/stats.h" -#include "jemalloc/internal/ctl.h" -#include "jemalloc/internal/mutex.h" -#include "jemalloc/internal/mb.h" -#include "jemalloc/internal/extent.h" -#include "jemalloc/internal/arena.h" -#include "jemalloc/internal/base.h" -#include "jemalloc/internal/chunk.h" -#include "jemalloc/internal/huge.h" -#include "jemalloc/internal/tcache.h" -#include "jemalloc/internal/hash.h" -#include "jemalloc/internal/prof.h" - -#undef JEMALLOC_H_STRUCTS -/******************************************************************************/ -#define JEMALLOC_H_EXTERNS - -extern bool opt_abort; -#ifdef JEMALLOC_FILL -extern bool opt_junk; -#endif -#ifdef JEMALLOC_SYSV -extern bool opt_sysv; -#endif -#ifdef JEMALLOC_XMALLOC -extern bool opt_xmalloc; -#endif -#ifdef JEMALLOC_FILL -extern bool opt_zero; -#endif - -#ifdef DYNAMIC_PAGE_SHIFT -extern size_t pagesize; -extern size_t pagesize_mask; -extern size_t lg_pagesize; -#endif - -/* Number of CPUs. */ -extern unsigned ncpus; - -extern malloc_mutex_t arenas_lock; /* Protects arenas initialization. */ -#ifndef NO_TLS -/* - * Map of pthread_self() --> arenas[???], used for selecting an arena to use - * for allocations. - */ -extern __thread arena_t *arenas_map JEMALLOC_ATTR(tls_model("initial-exec")); -#endif -/* - * Arenas that are used to service external requests. Not all elements of the - * arenas array are necessarily used; arenas are created lazily as needed. - */ -extern arena_t **arenas; -extern unsigned narenas; - -arena_t *arenas_extend(unsigned ind); -#ifndef NO_TLS -arena_t *choose_arena_hard(void); -#endif - -#include "jemalloc/internal/prn.h" -#include "jemalloc/internal/ckh.h" -#include "jemalloc/internal/stats.h" -#include "jemalloc/internal/ctl.h" -#include "jemalloc/internal/mutex.h" -#include "jemalloc/internal/mb.h" -#include "jemalloc/internal/extent.h" -#include "jemalloc/internal/arena.h" -#include "jemalloc/internal/base.h" -#include "jemalloc/internal/chunk.h" -#include "jemalloc/internal/huge.h" -#include "jemalloc/internal/tcache.h" -#include "jemalloc/internal/hash.h" -#include "jemalloc/internal/prof.h" - -#undef JEMALLOC_H_EXTERNS -/******************************************************************************/ -#define JEMALLOC_H_INLINES - -#include "jemalloc/internal/prn.h" -#include "jemalloc/internal/ckh.h" -#include "jemalloc/internal/stats.h" -#include "jemalloc/internal/ctl.h" -#include "jemalloc/internal/mutex.h" -#include "jemalloc/internal/mb.h" -#include "jemalloc/internal/extent.h" -#include "jemalloc/internal/base.h" -#include "jemalloc/internal/chunk.h" -#include "jemalloc/internal/huge.h" - -#ifndef JEMALLOC_ENABLE_INLINE -void malloc_write(const char *s); -arena_t *choose_arena(void); -#endif - -#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_C_)) -/* - * Wrapper around malloc_message() that avoids the need for - * JEMALLOC_P(malloc_message)(...) throughout the code. - */ -JEMALLOC_INLINE void -malloc_write(const char *s) -{ - - JEMALLOC_P(malloc_message)(NULL, s); -} - -/* - * Choose an arena based on a per-thread value (fast-path code, calls slow-path - * code if necessary). - */ -JEMALLOC_INLINE arena_t * -choose_arena(void) -{ - arena_t *ret; - - /* - * We can only use TLS if this is a PIC library, since for the static - * library version, libc's malloc is used by TLS allocation, which - * introduces a bootstrapping issue. - */ -#ifndef NO_TLS - ret = arenas_map; - if (ret == NULL) { - ret = choose_arena_hard(); - assert(ret != NULL); - } -#else - if (isthreaded && narenas > 1) { - unsigned long ind; - - /* - * Hash pthread_self() to one of the arenas. There is a prime - * number of arenas, so this has a reasonable chance of - * working. Even so, the hashing can be easily thwarted by - * inconvenient pthread_self() values. Without specific - * knowledge of how pthread_self() calculates values, we can't - * easily do much better than this. - */ - ind = (unsigned long) pthread_self() % narenas; - - /* - * Optimistially assume that arenas[ind] has been initialized. - * At worst, we find out that some other thread has already - * done so, after acquiring the lock in preparation. Note that - * this lazy locking also has the effect of lazily forcing - * cache coherency; without the lock acquisition, there's no - * guarantee that modification of arenas[ind] by another thread - * would be seen on this CPU for an arbitrary amount of time. - * - * In general, this approach to modifying a synchronized value - * isn't a good idea, but in this case we only ever modify the - * value once, so things work out well. - */ - ret = arenas[ind]; - if (ret == NULL) { - /* - * Avoid races with another thread that may have already - * initialized arenas[ind]. - */ - malloc_mutex_lock(&arenas_lock); - if (arenas[ind] == NULL) - ret = arenas_extend((unsigned)ind); - else - ret = arenas[ind]; - malloc_mutex_unlock(&arenas_lock); - } - } else - ret = arenas[0]; -#endif - - assert(ret != NULL); - return (ret); -} -#endif - -#include "jemalloc/internal/tcache.h" -#include "jemalloc/internal/arena.h" -#include "jemalloc/internal/hash.h" -#include "jemalloc/internal/prof.h" - -#ifndef JEMALLOC_ENABLE_INLINE -void *imalloc(size_t size); -void *icalloc(size_t size); -void *ipalloc(size_t alignment, size_t size); -size_t isalloc(const void *ptr); -void *iralloc(void *ptr, size_t size); -void idalloc(void *ptr); -#endif - -#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_C_)) -JEMALLOC_INLINE void * -imalloc(size_t size) -{ - - assert(size != 0); - - if (size <= arena_maxclass) - return (arena_malloc(size, false)); - else - return (huge_malloc(size, false)); -} - -JEMALLOC_INLINE void * -icalloc(size_t size) -{ - - if (size <= arena_maxclass) - return (arena_malloc(size, true)); - else - return (huge_malloc(size, true)); -} - -JEMALLOC_INLINE void * -ipalloc(size_t alignment, size_t size) -{ - void *ret; - size_t ceil_size; - - /* - * Round size up to the nearest multiple of alignment. - * - * This done, we can take advantage of the fact that for each small - * size class, every object is aligned at the smallest power of two - * that is non-zero in the base two representation of the size. For - * example: - * - * Size | Base 2 | Minimum alignment - * -----+----------+------------------ - * 96 | 1100000 | 32 - * 144 | 10100000 | 32 - * 192 | 11000000 | 64 - * - * Depending on runtime settings, it is possible that arena_malloc() - * will further round up to a power of two, but that never causes - * correctness issues. - */ - ceil_size = (size + (alignment - 1)) & (-alignment); - /* - * (ceil_size < size) protects against the combination of maximal - * alignment and size greater than maximal alignment. - */ - if (ceil_size < size) { - /* size_t overflow. */ - return (NULL); - } - - if (ceil_size <= PAGE_SIZE || (alignment <= PAGE_SIZE - && ceil_size <= arena_maxclass)) - ret = arena_malloc(ceil_size, false); - else { - size_t run_size; - - /* - * We can't achieve subpage alignment, so round up alignment - * permanently; it makes later calculations simpler. - */ - alignment = PAGE_CEILING(alignment); - ceil_size = PAGE_CEILING(size); - /* - * (ceil_size < size) protects against very large sizes within - * PAGE_SIZE of SIZE_T_MAX. - * - * (ceil_size + alignment < ceil_size) protects against the - * combination of maximal alignment and ceil_size large enough - * to cause overflow. This is similar to the first overflow - * check above, but it needs to be repeated due to the new - * ceil_size value, which may now be *equal* to maximal - * alignment, whereas before we only detected overflow if the - * original size was *greater* than maximal alignment. - */ - if (ceil_size < size || ceil_size + alignment < ceil_size) { - /* size_t overflow. */ - return (NULL); - } - - /* - * Calculate the size of the over-size run that arena_palloc() - * would need to allocate in order to guarantee the alignment. - */ - if (ceil_size >= alignment) - run_size = ceil_size + alignment - PAGE_SIZE; - else { - /* - * It is possible that (alignment << 1) will cause - * overflow, but it doesn't matter because we also - * subtract PAGE_SIZE, which in the case of overflow - * leaves us with a very large run_size. That causes - * the first conditional below to fail, which means - * that the bogus run_size value never gets used for - * anything important. - */ - run_size = (alignment << 1) - PAGE_SIZE; - } - - if (run_size <= arena_maxclass) { - ret = arena_palloc(choose_arena(), alignment, ceil_size, - run_size); - } else if (alignment <= chunksize) - ret = huge_malloc(ceil_size, false); - else - ret = huge_palloc(alignment, ceil_size); - } - - assert(((uintptr_t)ret & (alignment - 1)) == 0); - return (ret); -} - -JEMALLOC_INLINE size_t -isalloc(const void *ptr) -{ - size_t ret; - arena_chunk_t *chunk; - - assert(ptr != NULL); - - chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); - if (chunk != ptr) { - /* Region. */ - assert(chunk->arena->magic == ARENA_MAGIC); - -#ifdef JEMALLOC_PROF - ret = arena_salloc_demote(ptr); -#else - ret = arena_salloc(ptr); -#endif - } else - ret = huge_salloc(ptr); - - return (ret); -} - -JEMALLOC_INLINE void * -iralloc(void *ptr, size_t size) -{ - size_t oldsize; - - assert(ptr != NULL); - assert(size != 0); - - oldsize = isalloc(ptr); - - if (size <= arena_maxclass) - return (arena_ralloc(ptr, size, oldsize)); - else - return (huge_ralloc(ptr, size, oldsize)); -} - -JEMALLOC_INLINE void -idalloc(void *ptr) -{ - arena_chunk_t *chunk; - - assert(ptr != NULL); - - chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); - if (chunk != ptr) - arena_dalloc(chunk->arena, chunk, ptr); - else - huge_dalloc(ptr); -} -#endif - -#undef JEMALLOC_H_INLINES -/******************************************************************************/ diff --git a/externals/jemalloc/jemalloc/internal/mb.h b/externals/jemalloc/jemalloc/internal/mb.h deleted file mode 100644 index 1707aa91d68..00000000000 --- a/externals/jemalloc/jemalloc/internal/mb.h +++ /dev/null @@ -1,108 +0,0 @@ -/******************************************************************************/ -#ifdef JEMALLOC_H_TYPES - -#endif /* JEMALLOC_H_TYPES */ -/******************************************************************************/ -#ifdef JEMALLOC_H_STRUCTS - -#endif /* JEMALLOC_H_STRUCTS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_EXTERNS - -#endif /* JEMALLOC_H_EXTERNS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_INLINES - -#ifndef JEMALLOC_ENABLE_INLINE -void mb_write(void); -#endif - -#if (defined(JEMALLOC_ENABLE_INLINE) || defined(MB_C_)) -#ifdef __i386__ -/* - * According to the Intel Architecture Software Developer's Manual, current - * processors execute instructions in order from the perspective of other - * processors in a multiprocessor system, but 1) Intel reserves the right to - * change that, and 2) the compiler's optimizer could re-order instructions if - * there weren't some form of barrier. Therefore, even if running on an - * architecture that does not need memory barriers (everything through at least - * i686), an "optimizer barrier" is necessary. - */ -JEMALLOC_INLINE void -mb_write(void) -{ - -# if 0 - /* This is a true memory barrier. */ - asm volatile ("pusha;" - "xor %%eax,%%eax;" - "cpuid;" - "popa;" - : /* Outputs. */ - : /* Inputs. */ - : "memory" /* Clobbers. */ - ); -#else - /* - * This is hopefully enough to keep the compiler from reordering - * instructions around this one. - */ - asm volatile ("nop;" - : /* Outputs. */ - : /* Inputs. */ - : "memory" /* Clobbers. */ - ); -#endif -} -#elif (defined(__amd64_) || defined(__x86_64__)) -JEMALLOC_INLINE void -mb_write(void) -{ - - asm volatile ("sfence" - : /* Outputs. */ - : /* Inputs. */ - : "memory" /* Clobbers. */ - ); -} -#elif defined(__powerpc__) -JEMALLOC_INLINE void -mb_write(void) -{ - - asm volatile ("eieio" - : /* Outputs. */ - : /* Inputs. */ - : "memory" /* Clobbers. */ - ); -} -#elif defined(__sparc64__) -JEMALLOC_INLINE void -mb_write(void) -{ - - asm volatile ("membar #StoreStore" - : /* Outputs. */ - : /* Inputs. */ - : "memory" /* Clobbers. */ - ); -} -#else -/* - * This is much slower than a simple memory barrier, but the semantics of mutex - * unlock make this work. - */ -JEMALLOC_INLINE void -mb_write(void) -{ - malloc_mutex_t mtx; - - malloc_mutex_init(&mtx); - malloc_mutex_lock(&mtx); - malloc_mutex_unlock(&mtx); -} -#endif -#endif - -#endif /* JEMALLOC_H_INLINES */ -/******************************************************************************/ diff --git a/externals/jemalloc/jemalloc/internal/mutex.h b/externals/jemalloc/jemalloc/internal/mutex.h deleted file mode 100644 index 108bfa8abfd..00000000000 --- a/externals/jemalloc/jemalloc/internal/mutex.h +++ /dev/null @@ -1,61 +0,0 @@ -/******************************************************************************/ -#ifdef JEMALLOC_H_TYPES - -typedef pthread_mutex_t malloc_mutex_t; - -#endif /* JEMALLOC_H_TYPES */ -/******************************************************************************/ -#ifdef JEMALLOC_H_STRUCTS - -#endif /* JEMALLOC_H_STRUCTS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_EXTERNS - -#ifdef JEMALLOC_LAZY_LOCK -extern bool isthreaded; -#else -# define isthreaded true -#endif - -bool malloc_mutex_init(malloc_mutex_t *mutex); - -#endif /* JEMALLOC_H_EXTERNS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_INLINES - -#ifndef JEMALLOC_ENABLE_INLINE -void malloc_mutex_lock(malloc_mutex_t *mutex); -bool malloc_mutex_trylock(malloc_mutex_t *mutex); -void malloc_mutex_unlock(malloc_mutex_t *mutex); -#endif - -#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_MUTEX_C_)) -JEMALLOC_INLINE void -malloc_mutex_lock(malloc_mutex_t *mutex) -{ - - if (isthreaded) - pthread_mutex_lock(mutex); -} - -JEMALLOC_INLINE bool -malloc_mutex_trylock(malloc_mutex_t *mutex) -{ - - if (isthreaded) - return (pthread_mutex_trylock(mutex) != 0); - else - return (false); -} - -JEMALLOC_INLINE void -malloc_mutex_unlock(malloc_mutex_t *mutex) -{ - - if (isthreaded) - pthread_mutex_unlock(mutex); -} -#endif - -#endif /* JEMALLOC_H_INLINES */ -/******************************************************************************/ diff --git a/externals/jemalloc/jemalloc/internal/prof.h b/externals/jemalloc/jemalloc/internal/prof.h deleted file mode 100644 index 6e71552d85e..00000000000 --- a/externals/jemalloc/jemalloc/internal/prof.h +++ /dev/null @@ -1,171 +0,0 @@ -#ifdef JEMALLOC_PROF -/******************************************************************************/ -#ifdef JEMALLOC_H_TYPES - -typedef struct prof_bt_s prof_bt_t; -typedef struct prof_cnt_s prof_cnt_t; -typedef struct prof_thr_cnt_s prof_thr_cnt_t; -typedef struct prof_ctx_s prof_ctx_t; -typedef struct prof_s prof_t; - -/* Option defaults. */ -#define LG_PROF_BT_MAX_DEFAULT 2 -#define LG_PROF_SAMPLE_DEFAULT 0 -#define LG_PROF_INTERVAL_DEFAULT 30 - -/* - * Hard limit on stack backtrace depth. Note that the version of - * prof_backtrace() that is based on __builtin_return_address() necessarily has - * a hard-coded number of backtrace frame handlers, so increasing - * LG_PROF_BT_MAX requires changing prof_backtrace(). - */ -#define LG_PROF_BT_MAX 7 /* >= LG_PROF_BT_MAX_DEFAULT */ -#define PROF_BT_MAX (1U << LG_PROF_BT_MAX) - -/* Initial hash table size. */ -#define PROF_CKH_MINITEMS 64 - -/* Size of memory buffer to use when writing dump files. */ -#define PROF_DUMP_BUF_SIZE 65536 - -#endif /* JEMALLOC_H_TYPES */ -/******************************************************************************/ -#ifdef JEMALLOC_H_STRUCTS - -struct prof_bt_s { - /* Backtrace, stored as len program counters. */ - void **vec; - unsigned len; -}; - -#ifdef JEMALLOC_PROF_LIBGCC -/* Data structure passed to libgcc _Unwind_Backtrace() callback functions. */ -typedef struct { - prof_bt_t *bt; - unsigned nignore; - unsigned max; -} prof_unwind_data_t; -#endif - -struct prof_cnt_s { - /* - * Profiling counters. An allocation/deallocation pair can operate on - * different prof_thr_cnt_t objects that are linked into the same - * prof_ctx_t sets_ql, so it is possible for the cur* counters to go - * negative. In principle it is possible for the *bytes counters to - * overflow/underflow, but a general solution would require some form - * of 128-bit counter solution; this implementation doesn't bother to - * solve that problem. - */ - int64_t curobjs; - int64_t curbytes; - uint64_t accumobjs; - uint64_t accumbytes; -}; - -struct prof_thr_cnt_s { - /* Linkage into prof_ctx_t's sets_ql. */ - ql_elm(prof_thr_cnt_t) link; - - /* - * Associated context. If a thread frees an object that it did not - * allocate, it is possible that the context is not cached in the - * thread's hash table, in which case it must be able to look up the - * context, insert a new prof_thr_cnt_t into the thread's hash table, - * and link it into the prof_ctx_t's sets_ql. - */ - prof_ctx_t *ctx; - - /* - * Threads use memory barriers to update the counters. Since there is - * only ever one writer, the only challenge is for the reader to get a - * consistent read of the counters. - * - * The writer uses this series of operations: - * - * 1) Increment epoch to an odd number. - * 2) Update counters. - * 3) Increment epoch to an even number. - * - * The reader must assure 1) that the epoch is even while it reads the - * counters, and 2) that the epoch doesn't change between the time it - * starts and finishes reading the counters. - */ - unsigned epoch; - - /* Profiling counters. */ - prof_cnt_t cnts; -}; - -struct prof_ctx_s { - /* Protects cnt_merged and sets_ql. */ - malloc_mutex_t lock; - - /* Temporary storage for aggregation during dump. */ - prof_cnt_t cnt_dump; - - /* When threads exit, they merge their stats into cnt_merged. */ - prof_cnt_t cnt_merged; - - /* - * List of profile counters, one for each thread that has allocated in - * this context. - */ - ql_head(prof_thr_cnt_t) cnts_ql; -}; - -#endif /* JEMALLOC_H_STRUCTS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_EXTERNS - -extern bool opt_prof; -/* - * Even if opt_prof is true, sampling can be temporarily disabled by setting - * opt_prof_active to false. No locking is used when updating opt_prof_active, - * so there are no guarantees regarding how long it will take for all threads - * to notice state changes. - */ -extern bool opt_prof_active; -extern size_t opt_lg_prof_bt_max; /* Maximum backtrace depth. */ -extern size_t opt_lg_prof_sample; /* Mean bytes between samples. */ -extern ssize_t opt_lg_prof_interval; /* lg(prof_interval). */ -extern bool opt_prof_udump; /* High-water memory dumping. */ -extern bool opt_prof_leak; /* Dump leak summary at exit. */ - -/* - * Profile dump interval, measured in bytes allocated. Each arena triggers a - * profile dump when it reaches this threshold. The effect is that the - * interval between profile dumps averages prof_interval, though the actual - * interval between dumps will tend to be sporadic, and the interval will be a - * maximum of approximately (prof_interval * narenas). - */ -extern uint64_t prof_interval; - -/* - * If true, promote small sampled objects to large objects, since small run - * headers do not have embedded profile context pointers. - */ -extern bool prof_promote; - -bool prof_init(prof_t *prof, bool master); -void prof_destroy(prof_t *prof); - -prof_thr_cnt_t *prof_alloc_prep(size_t size); -prof_thr_cnt_t *prof_cnt_get(const void *ptr); -void prof_malloc(const void *ptr, prof_thr_cnt_t *cnt); -void prof_realloc(const void *ptr, prof_thr_cnt_t *cnt, const void *old_ptr, - size_t old_size, prof_thr_cnt_t *old_cnt); -void prof_free(const void *ptr); -void prof_idump(void); -bool prof_mdump(const char *filename); -void prof_udump(void); -void prof_boot0(void); -bool prof_boot1(void); - -#endif /* JEMALLOC_H_EXTERNS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_INLINES - -#endif /* JEMALLOC_H_INLINES */ -/******************************************************************************/ -#endif /* JEMALLOC_PROF */ diff --git a/externals/jemalloc/jemalloc/internal/ql.h b/externals/jemalloc/jemalloc/internal/ql.h deleted file mode 100644 index a9ed2393f0c..00000000000 --- a/externals/jemalloc/jemalloc/internal/ql.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - * List definitions. - */ -#define ql_head(a_type) \ -struct { \ - a_type *qlh_first; \ -} - -#define ql_head_initializer(a_head) {NULL} - -#define ql_elm(a_type) qr(a_type) - -/* List functions. */ -#define ql_new(a_head) do { \ - (a_head)->qlh_first = NULL; \ -} while (0) - -#define ql_elm_new(a_elm, a_field) qr_new((a_elm), a_field) - -#define ql_first(a_head) ((a_head)->qlh_first) - -#define ql_last(a_head, a_field) \ - ((ql_first(a_head) != NULL) \ - ? qr_prev(ql_first(a_head), a_field) : NULL) - -#define ql_next(a_head, a_elm, a_field) \ - ((ql_last(a_head, a_field) != (a_elm)) \ - ? qr_next((a_elm), a_field) : NULL) - -#define ql_prev(a_head, a_elm, a_field) \ - ((ql_first(a_head) != (a_elm)) ? qr_prev((a_elm), a_field) \ - : NULL) - -#define ql_before_insert(a_head, a_qlelm, a_elm, a_field) do { \ - qr_before_insert((a_qlelm), (a_elm), a_field); \ - if (ql_first(a_head) == (a_qlelm)) { \ - ql_first(a_head) = (a_elm); \ - } \ -} while (0) - -#define ql_after_insert(a_qlelm, a_elm, a_field) \ - qr_after_insert((a_qlelm), (a_elm), a_field) - -#define ql_head_insert(a_head, a_elm, a_field) do { \ - if (ql_first(a_head) != NULL) { \ - qr_before_insert(ql_first(a_head), (a_elm), a_field); \ - } \ - ql_first(a_head) = (a_elm); \ -} while (0) - -#define ql_tail_insert(a_head, a_elm, a_field) do { \ - if (ql_first(a_head) != NULL) { \ - qr_before_insert(ql_first(a_head), (a_elm), a_field); \ - } \ - ql_first(a_head) = qr_next((a_elm), a_field); \ -} while (0) - -#define ql_remove(a_head, a_elm, a_field) do { \ - if (ql_first(a_head) == (a_elm)) { \ - ql_first(a_head) = qr_next(ql_first(a_head), a_field); \ - } \ - if (ql_first(a_head) != (a_elm)) { \ - qr_remove((a_elm), a_field); \ - } else { \ - ql_first(a_head) = NULL; \ - } \ -} while (0) - -#define ql_head_remove(a_head, a_type, a_field) do { \ - a_type *t = ql_first(a_head); \ - ql_remove((a_head), t, a_field); \ -} while (0) - -#define ql_tail_remove(a_head, a_type, a_field) do { \ - a_type *t = ql_last(a_head, a_field); \ - ql_remove((a_head), t, a_field); \ -} while (0) - -#define ql_foreach(a_var, a_head, a_field) \ - qr_foreach((a_var), ql_first(a_head), a_field) - -#define ql_reverse_foreach(a_var, a_head, a_field) \ - qr_reverse_foreach((a_var), ql_first(a_head), a_field) diff --git a/externals/jemalloc/jemalloc/internal/qr.h b/externals/jemalloc/jemalloc/internal/qr.h deleted file mode 100644 index fe22352fedd..00000000000 --- a/externals/jemalloc/jemalloc/internal/qr.h +++ /dev/null @@ -1,67 +0,0 @@ -/* Ring definitions. */ -#define qr(a_type) \ -struct { \ - a_type *qre_next; \ - a_type *qre_prev; \ -} - -/* Ring functions. */ -#define qr_new(a_qr, a_field) do { \ - (a_qr)->a_field.qre_next = (a_qr); \ - (a_qr)->a_field.qre_prev = (a_qr); \ -} while (0) - -#define qr_next(a_qr, a_field) ((a_qr)->a_field.qre_next) - -#define qr_prev(a_qr, a_field) ((a_qr)->a_field.qre_prev) - -#define qr_before_insert(a_qrelm, a_qr, a_field) do { \ - (a_qr)->a_field.qre_prev = (a_qrelm)->a_field.qre_prev; \ - (a_qr)->a_field.qre_next = (a_qrelm); \ - (a_qr)->a_field.qre_prev->a_field.qre_next = (a_qr); \ - (a_qrelm)->a_field.qre_prev = (a_qr); \ -} while (0) - -#define qr_after_insert(a_qrelm, a_qr, a_field) \ - do \ - { \ - (a_qr)->a_field.qre_next = (a_qrelm)->a_field.qre_next; \ - (a_qr)->a_field.qre_prev = (a_qrelm); \ - (a_qr)->a_field.qre_next->a_field.qre_prev = (a_qr); \ - (a_qrelm)->a_field.qre_next = (a_qr); \ - } while (0) - -#define qr_meld(a_qr_a, a_qr_b, a_field) do { \ - void *t; \ - (a_qr_a)->a_field.qre_prev->a_field.qre_next = (a_qr_b); \ - (a_qr_b)->a_field.qre_prev->a_field.qre_next = (a_qr_a); \ - t = (a_qr_a)->a_field.qre_prev; \ - (a_qr_a)->a_field.qre_prev = (a_qr_b)->a_field.qre_prev; \ - (a_qr_b)->a_field.qre_prev = t; \ -} while (0) - -/* qr_meld() and qr_split() are functionally equivalent, so there's no need to - * have two copies of the code. */ -#define qr_split(a_qr_a, a_qr_b, a_field) \ - qr_meld((a_qr_a), (a_qr_b), a_field) - -#define qr_remove(a_qr, a_field) do { \ - (a_qr)->a_field.qre_prev->a_field.qre_next \ - = (a_qr)->a_field.qre_next; \ - (a_qr)->a_field.qre_next->a_field.qre_prev \ - = (a_qr)->a_field.qre_prev; \ - (a_qr)->a_field.qre_next = (a_qr); \ - (a_qr)->a_field.qre_prev = (a_qr); \ -} while (0) - -#define qr_foreach(var, a_qr, a_field) \ - for ((var) = (a_qr); \ - (var) != NULL; \ - (var) = (((var)->a_field.qre_next != (a_qr)) \ - ? (var)->a_field.qre_next : NULL)) - -#define qr_reverse_foreach(var, a_qr, a_field) \ - for ((var) = ((a_qr) != NULL) ? qr_prev(a_qr, a_field) : NULL; \ - (var) != NULL; \ - (var) = (((var) != (a_qr)) \ - ? (var)->a_field.qre_prev : NULL)) diff --git a/externals/jemalloc/jemalloc/internal/rb.h b/externals/jemalloc/jemalloc/internal/rb.h deleted file mode 100644 index ee9b009d235..00000000000 --- a/externals/jemalloc/jemalloc/internal/rb.h +++ /dev/null @@ -1,973 +0,0 @@ -/*- - ******************************************************************************* - * - * cpp macro implementation of left-leaning 2-3 red-black trees. Parent - * pointers are not used, and color bits are stored in the least significant - * bit of right-child pointers (if RB_COMPACT is defined), thus making node - * linkage as compact as is possible for red-black trees. - * - * Usage: - * - * #include - * #include - * #define NDEBUG // (Optional, see assert(3).) - * #include - * #define RB_COMPACT // (Optional, embed color bits in right-child pointers.) - * #include - * ... - * - ******************************************************************************* - */ - -#ifndef RB_H_ -#define RB_H_ - -#if 0 -__FBSDID("$FreeBSD: head/lib/libc/stdlib/rb.h 204493 2010-02-28 22:57:13Z jasone $"); -#endif - -#ifdef RB_COMPACT -/* Node structure. */ -#define rb_node(a_type) \ -struct { \ - a_type *rbn_left; \ - a_type *rbn_right_red; \ -} -#else -#define rb_node(a_type) \ -struct { \ - a_type *rbn_left; \ - a_type *rbn_right; \ - bool rbn_red; \ -} -#endif - -/* Root structure. */ -#define rb_tree(a_type) \ -struct { \ - a_type *rbt_root; \ - a_type rbt_nil; \ -} - -/* Left accessors. */ -#define rbtn_left_get(a_type, a_field, a_node) \ - ((a_node)->a_field.rbn_left) -#define rbtn_left_set(a_type, a_field, a_node, a_left) do { \ - (a_node)->a_field.rbn_left = a_left; \ -} while (0) - -#ifdef RB_COMPACT -/* Right accessors. */ -#define rbtn_right_get(a_type, a_field, a_node) \ - ((a_type *) (((intptr_t) (a_node)->a_field.rbn_right_red) \ - & ((ssize_t)-2))) -#define rbtn_right_set(a_type, a_field, a_node, a_right) do { \ - (a_node)->a_field.rbn_right_red = (a_type *) (((uintptr_t) a_right) \ - | (((uintptr_t) (a_node)->a_field.rbn_right_red) & ((size_t)1))); \ -} while (0) - -/* Color accessors. */ -#define rbtn_red_get(a_type, a_field, a_node) \ - ((bool) (((uintptr_t) (a_node)->a_field.rbn_right_red) \ - & ((size_t)1))) -#define rbtn_color_set(a_type, a_field, a_node, a_red) do { \ - (a_node)->a_field.rbn_right_red = (a_type *) ((((intptr_t) \ - (a_node)->a_field.rbn_right_red) & ((ssize_t)-2)) \ - | ((ssize_t)a_red)); \ -} while (0) -#define rbtn_red_set(a_type, a_field, a_node) do { \ - (a_node)->a_field.rbn_right_red = (a_type *) (((uintptr_t) \ - (a_node)->a_field.rbn_right_red) | ((size_t)1)); \ -} while (0) -#define rbtn_black_set(a_type, a_field, a_node) do { \ - (a_node)->a_field.rbn_right_red = (a_type *) (((intptr_t) \ - (a_node)->a_field.rbn_right_red) & ((ssize_t)-2)); \ -} while (0) -#else -/* Right accessors. */ -#define rbtn_right_get(a_type, a_field, a_node) \ - ((a_node)->a_field.rbn_right) -#define rbtn_right_set(a_type, a_field, a_node, a_right) do { \ - (a_node)->a_field.rbn_right = a_right; \ -} while (0) - -/* Color accessors. */ -#define rbtn_red_get(a_type, a_field, a_node) \ - ((a_node)->a_field.rbn_red) -#define rbtn_color_set(a_type, a_field, a_node, a_red) do { \ - (a_node)->a_field.rbn_red = (a_red); \ -} while (0) -#define rbtn_red_set(a_type, a_field, a_node) do { \ - (a_node)->a_field.rbn_red = true; \ -} while (0) -#define rbtn_black_set(a_type, a_field, a_node) do { \ - (a_node)->a_field.rbn_red = false; \ -} while (0) -#endif - -/* Node initializer. */ -#define rbt_node_new(a_type, a_field, a_rbt, a_node) do { \ - rbtn_left_set(a_type, a_field, (a_node), &(a_rbt)->rbt_nil); \ - rbtn_right_set(a_type, a_field, (a_node), &(a_rbt)->rbt_nil); \ - rbtn_red_set(a_type, a_field, (a_node)); \ -} while (0) - -/* Tree initializer. */ -#define rb_new(a_type, a_field, a_rbt) do { \ - (a_rbt)->rbt_root = &(a_rbt)->rbt_nil; \ - rbt_node_new(a_type, a_field, a_rbt, &(a_rbt)->rbt_nil); \ - rbtn_black_set(a_type, a_field, &(a_rbt)->rbt_nil); \ -} while (0) - -/* Internal utility macros. */ -#define rbtn_first(a_type, a_field, a_rbt, a_root, r_node) do { \ - (r_node) = (a_root); \ - if ((r_node) != &(a_rbt)->rbt_nil) { \ - for (; \ - rbtn_left_get(a_type, a_field, (r_node)) != &(a_rbt)->rbt_nil;\ - (r_node) = rbtn_left_get(a_type, a_field, (r_node))) { \ - } \ - } \ -} while (0) - -#define rbtn_last(a_type, a_field, a_rbt, a_root, r_node) do { \ - (r_node) = (a_root); \ - if ((r_node) != &(a_rbt)->rbt_nil) { \ - for (; rbtn_right_get(a_type, a_field, (r_node)) != \ - &(a_rbt)->rbt_nil; (r_node) = rbtn_right_get(a_type, a_field, \ - (r_node))) { \ - } \ - } \ -} while (0) - -#define rbtn_rotate_left(a_type, a_field, a_node, r_node) do { \ - (r_node) = rbtn_right_get(a_type, a_field, (a_node)); \ - rbtn_right_set(a_type, a_field, (a_node), \ - rbtn_left_get(a_type, a_field, (r_node))); \ - rbtn_left_set(a_type, a_field, (r_node), (a_node)); \ -} while (0) - -#define rbtn_rotate_right(a_type, a_field, a_node, r_node) do { \ - (r_node) = rbtn_left_get(a_type, a_field, (a_node)); \ - rbtn_left_set(a_type, a_field, (a_node), \ - rbtn_right_get(a_type, a_field, (r_node))); \ - rbtn_right_set(a_type, a_field, (r_node), (a_node)); \ -} while (0) - -/* - * The rb_proto() macro generates function prototypes that correspond to the - * functions generated by an equivalently parameterized call to rb_gen(). - */ - -#define rb_proto(a_attr, a_prefix, a_rbt_type, a_type) \ -a_attr void \ -a_prefix##new(a_rbt_type *rbtree); \ -a_attr a_type * \ -a_prefix##first(a_rbt_type *rbtree); \ -a_attr a_type * \ -a_prefix##last(a_rbt_type *rbtree); \ -a_attr a_type * \ -a_prefix##next(a_rbt_type *rbtree, a_type *node); \ -a_attr a_type * \ -a_prefix##prev(a_rbt_type *rbtree, a_type *node); \ -a_attr a_type * \ -a_prefix##search(a_rbt_type *rbtree, a_type *key); \ -a_attr a_type * \ -a_prefix##nsearch(a_rbt_type *rbtree, a_type *key); \ -a_attr a_type * \ -a_prefix##psearch(a_rbt_type *rbtree, a_type *key); \ -a_attr void \ -a_prefix##insert(a_rbt_type *rbtree, a_type *node); \ -a_attr void \ -a_prefix##remove(a_rbt_type *rbtree, a_type *node); \ -a_attr a_type * \ -a_prefix##iter(a_rbt_type *rbtree, a_type *start, a_type *(*cb)( \ - a_rbt_type *, a_type *, void *), void *arg); \ -a_attr a_type * \ -a_prefix##reverse_iter(a_rbt_type *rbtree, a_type *start, \ - a_type *(*cb)(a_rbt_type *, a_type *, void *), void *arg); - -/* - * The rb_gen() macro generates a type-specific red-black tree implementation, - * based on the above cpp macros. - * - * Arguments: - * - * a_attr : Function attribute for generated functions (ex: static). - * a_prefix : Prefix for generated functions (ex: ex_). - * a_rb_type : Type for red-black tree data structure (ex: ex_t). - * a_type : Type for red-black tree node data structure (ex: ex_node_t). - * a_field : Name of red-black tree node linkage (ex: ex_link). - * a_cmp : Node comparison function name, with the following prototype: - * int (a_cmp *)(a_type *a_node, a_type *a_other); - * ^^^^^^ - * or a_key - * Interpretation of comparision function return values: - * -1 : a_node < a_other - * 0 : a_node == a_other - * 1 : a_node > a_other - * In all cases, the a_node or a_key macro argument is the first - * argument to the comparison function, which makes it possible - * to write comparison functions that treat the first argument - * specially. - * - * Assuming the following setup: - * - * typedef struct ex_node_s ex_node_t; - * struct ex_node_s { - * rb_node(ex_node_t) ex_link; - * }; - * typedef rb_tree(ex_node_t) ex_t; - * rb_gen(static, ex_, ex_t, ex_node_t, ex_link, ex_cmp) - * - * The following API is generated: - * - * static void - * ex_new(ex_t *extree); - * Description: Initialize a red-black tree structure. - * Args: - * extree: Pointer to an uninitialized red-black tree object. - * - * static ex_node_t * - * ex_first(ex_t *extree); - * static ex_node_t * - * ex_last(ex_t *extree); - * Description: Get the first/last node in extree. - * Args: - * extree: Pointer to an initialized red-black tree object. - * Ret: First/last node in extree, or NULL if extree is empty. - * - * static ex_node_t * - * ex_next(ex_t *extree, ex_node_t *node); - * static ex_node_t * - * ex_prev(ex_t *extree, ex_node_t *node); - * Description: Get node's successor/predecessor. - * Args: - * extree: Pointer to an initialized red-black tree object. - * node : A node in extree. - * Ret: node's successor/predecessor in extree, or NULL if node is - * last/first. - * - * static ex_node_t * - * ex_search(ex_t *extree, ex_node_t *key); - * Description: Search for node that matches key. - * Args: - * extree: Pointer to an initialized red-black tree object. - * key : Search key. - * Ret: Node in extree that matches key, or NULL if no match. - * - * static ex_node_t * - * ex_nsearch(ex_t *extree, ex_node_t *key); - * static ex_node_t * - * ex_psearch(ex_t *extree, ex_node_t *key); - * Description: Search for node that matches key. If no match is found, - * return what would be key's successor/predecessor, were - * key in extree. - * Args: - * extree: Pointer to an initialized red-black tree object. - * key : Search key. - * Ret: Node in extree that matches key, or if no match, hypothetical - * node's successor/predecessor (NULL if no successor/predecessor). - * - * static void - * ex_insert(ex_t *extree, ex_node_t *node); - * Description: Insert node into extree. - * Args: - * extree: Pointer to an initialized red-black tree object. - * node : Node to be inserted into extree. - * - * static void - * ex_remove(ex_t *extree, ex_node_t *node); - * Description: Remove node from extree. - * Args: - * extree: Pointer to an initialized red-black tree object. - * node : Node in extree to be removed. - * - * static ex_node_t * - * ex_iter(ex_t *extree, ex_node_t *start, ex_node_t *(*cb)(ex_t *, - * ex_node_t *, void *), void *arg); - * static ex_node_t * - * ex_reverse_iter(ex_t *extree, ex_node_t *start, ex_node *(*cb)(ex_t *, - * ex_node_t *, void *), void *arg); - * Description: Iterate forward/backward over extree, starting at node. - * If extree is modified, iteration must be immediately - * terminated by the callback function that causes the - * modification. - * Args: - * extree: Pointer to an initialized red-black tree object. - * start : Node at which to start iteration, or NULL to start at - * first/last node. - * cb : Callback function, which is called for each node during - * iteration. Under normal circumstances the callback function - * should return NULL, which causes iteration to continue. If a - * callback function returns non-NULL, iteration is immediately - * terminated and the non-NULL return value is returned by the - * iterator. This is useful for re-starting iteration after - * modifying extree. - * arg : Opaque pointer passed to cb(). - * Ret: NULL if iteration completed, or the non-NULL callback return value - * that caused termination of the iteration. - */ -#define rb_gen(a_attr, a_prefix, a_rbt_type, a_type, a_field, a_cmp) \ -a_attr void \ -a_prefix##new(a_rbt_type *rbtree) { \ - rb_new(a_type, a_field, rbtree); \ -} \ -a_attr a_type * \ -a_prefix##first(a_rbt_type *rbtree) { \ - a_type *ret; \ - rbtn_first(a_type, a_field, rbtree, rbtree->rbt_root, ret); \ - if (ret == &rbtree->rbt_nil) { \ - ret = NULL; \ - } \ - return (ret); \ -} \ -a_attr a_type * \ -a_prefix##last(a_rbt_type *rbtree) { \ - a_type *ret; \ - rbtn_last(a_type, a_field, rbtree, rbtree->rbt_root, ret); \ - if (ret == &rbtree->rbt_nil) { \ - ret = NULL; \ - } \ - return (ret); \ -} \ -a_attr a_type * \ -a_prefix##next(a_rbt_type *rbtree, a_type *node) { \ - a_type *ret; \ - if (rbtn_right_get(a_type, a_field, node) != &rbtree->rbt_nil) { \ - rbtn_first(a_type, a_field, rbtree, rbtn_right_get(a_type, \ - a_field, node), ret); \ - } else { \ - a_type *tnode = rbtree->rbt_root; \ - assert(tnode != &rbtree->rbt_nil); \ - ret = &rbtree->rbt_nil; \ - while (true) { \ - int cmp = (a_cmp)(node, tnode); \ - if (cmp < 0) { \ - ret = tnode; \ - tnode = rbtn_left_get(a_type, a_field, tnode); \ - } else if (cmp > 0) { \ - tnode = rbtn_right_get(a_type, a_field, tnode); \ - } else { \ - break; \ - } \ - assert(tnode != &rbtree->rbt_nil); \ - } \ - } \ - if (ret == &rbtree->rbt_nil) { \ - ret = (NULL); \ - } \ - return (ret); \ -} \ -a_attr a_type * \ -a_prefix##prev(a_rbt_type *rbtree, a_type *node) { \ - a_type *ret; \ - if (rbtn_left_get(a_type, a_field, node) != &rbtree->rbt_nil) { \ - rbtn_last(a_type, a_field, rbtree, rbtn_left_get(a_type, \ - a_field, node), ret); \ - } else { \ - a_type *tnode = rbtree->rbt_root; \ - assert(tnode != &rbtree->rbt_nil); \ - ret = &rbtree->rbt_nil; \ - while (true) { \ - int cmp = (a_cmp)(node, tnode); \ - if (cmp < 0) { \ - tnode = rbtn_left_get(a_type, a_field, tnode); \ - } else if (cmp > 0) { \ - ret = tnode; \ - tnode = rbtn_right_get(a_type, a_field, tnode); \ - } else { \ - break; \ - } \ - assert(tnode != &rbtree->rbt_nil); \ - } \ - } \ - if (ret == &rbtree->rbt_nil) { \ - ret = (NULL); \ - } \ - return (ret); \ -} \ -a_attr a_type * \ -a_prefix##search(a_rbt_type *rbtree, a_type *key) { \ - a_type *ret; \ - int cmp; \ - ret = rbtree->rbt_root; \ - while (ret != &rbtree->rbt_nil \ - && (cmp = (a_cmp)(key, ret)) != 0) { \ - if (cmp < 0) { \ - ret = rbtn_left_get(a_type, a_field, ret); \ - } else { \ - ret = rbtn_right_get(a_type, a_field, ret); \ - } \ - } \ - if (ret == &rbtree->rbt_nil) { \ - ret = (NULL); \ - } \ - return (ret); \ -} \ -a_attr a_type * \ -a_prefix##nsearch(a_rbt_type *rbtree, a_type *key) { \ - a_type *ret; \ - a_type *tnode = rbtree->rbt_root; \ - ret = &rbtree->rbt_nil; \ - while (tnode != &rbtree->rbt_nil) { \ - int cmp = (a_cmp)(key, tnode); \ - if (cmp < 0) { \ - ret = tnode; \ - tnode = rbtn_left_get(a_type, a_field, tnode); \ - } else if (cmp > 0) { \ - tnode = rbtn_right_get(a_type, a_field, tnode); \ - } else { \ - ret = tnode; \ - break; \ - } \ - } \ - if (ret == &rbtree->rbt_nil) { \ - ret = (NULL); \ - } \ - return (ret); \ -} \ -a_attr a_type * \ -a_prefix##psearch(a_rbt_type *rbtree, a_type *key) { \ - a_type *ret; \ - a_type *tnode = rbtree->rbt_root; \ - ret = &rbtree->rbt_nil; \ - while (tnode != &rbtree->rbt_nil) { \ - int cmp = (a_cmp)(key, tnode); \ - if (cmp < 0) { \ - tnode = rbtn_left_get(a_type, a_field, tnode); \ - } else if (cmp > 0) { \ - ret = tnode; \ - tnode = rbtn_right_get(a_type, a_field, tnode); \ - } else { \ - ret = tnode; \ - break; \ - } \ - } \ - if (ret == &rbtree->rbt_nil) { \ - ret = (NULL); \ - } \ - return (ret); \ -} \ -a_attr void \ -a_prefix##insert(a_rbt_type *rbtree, a_type *node) { \ - struct { \ - a_type *node; \ - int cmp; \ - } path[sizeof(void *) << 4], *pathp; \ - rbt_node_new(a_type, a_field, rbtree, node); \ - /* Wind. */ \ - path->node = rbtree->rbt_root; \ - for (pathp = path; pathp->node != &rbtree->rbt_nil; pathp++) { \ - int cmp = pathp->cmp = a_cmp(node, pathp->node); \ - assert(cmp != 0); \ - if (cmp < 0) { \ - pathp[1].node = rbtn_left_get(a_type, a_field, \ - pathp->node); \ - } else { \ - pathp[1].node = rbtn_right_get(a_type, a_field, \ - pathp->node); \ - } \ - } \ - pathp->node = node; \ - /* Unwind. */ \ - for (pathp--; (uintptr_t)pathp >= (uintptr_t)path; pathp--) { \ - a_type *cnode = pathp->node; \ - if (pathp->cmp < 0) { \ - a_type *left = pathp[1].node; \ - rbtn_left_set(a_type, a_field, cnode, left); \ - if (rbtn_red_get(a_type, a_field, left)) { \ - a_type *leftleft = rbtn_left_get(a_type, a_field, left);\ - if (rbtn_red_get(a_type, a_field, leftleft)) { \ - /* Fix up 4-node. */ \ - a_type *tnode; \ - rbtn_black_set(a_type, a_field, leftleft); \ - rbtn_rotate_right(a_type, a_field, cnode, tnode); \ - cnode = tnode; \ - } \ - } else { \ - return; \ - } \ - } else { \ - a_type *right = pathp[1].node; \ - rbtn_right_set(a_type, a_field, cnode, right); \ - if (rbtn_red_get(a_type, a_field, right)) { \ - a_type *left = rbtn_left_get(a_type, a_field, cnode); \ - if (rbtn_red_get(a_type, a_field, left)) { \ - /* Split 4-node. */ \ - rbtn_black_set(a_type, a_field, left); \ - rbtn_black_set(a_type, a_field, right); \ - rbtn_red_set(a_type, a_field, cnode); \ - } else { \ - /* Lean left. */ \ - a_type *tnode; \ - bool tred = rbtn_red_get(a_type, a_field, cnode); \ - rbtn_rotate_left(a_type, a_field, cnode, tnode); \ - rbtn_color_set(a_type, a_field, tnode, tred); \ - rbtn_red_set(a_type, a_field, cnode); \ - cnode = tnode; \ - } \ - } else { \ - return; \ - } \ - } \ - pathp->node = cnode; \ - } \ - /* Set root, and make it black. */ \ - rbtree->rbt_root = path->node; \ - rbtn_black_set(a_type, a_field, rbtree->rbt_root); \ -} \ -a_attr void \ -a_prefix##remove(a_rbt_type *rbtree, a_type *node) { \ - struct { \ - a_type *node; \ - int cmp; \ - } *pathp, *nodep, path[sizeof(void *) << 4]; \ - /* Wind. */ \ - nodep = NULL; /* Silence compiler warning. */ \ - path->node = rbtree->rbt_root; \ - for (pathp = path; pathp->node != &rbtree->rbt_nil; pathp++) { \ - int cmp = pathp->cmp = a_cmp(node, pathp->node); \ - if (cmp < 0) { \ - pathp[1].node = rbtn_left_get(a_type, a_field, \ - pathp->node); \ - } else { \ - pathp[1].node = rbtn_right_get(a_type, a_field, \ - pathp->node); \ - if (cmp == 0) { \ - /* Find node's successor, in preparation for swap. */ \ - pathp->cmp = 1; \ - nodep = pathp; \ - for (pathp++; pathp->node != &rbtree->rbt_nil; \ - pathp++) { \ - pathp->cmp = -1; \ - pathp[1].node = rbtn_left_get(a_type, a_field, \ - pathp->node); \ - } \ - break; \ - } \ - } \ - } \ - assert(nodep->node == node); \ - pathp--; \ - if (pathp->node != node) { \ - /* Swap node with its successor. */ \ - bool tred = rbtn_red_get(a_type, a_field, pathp->node); \ - rbtn_color_set(a_type, a_field, pathp->node, \ - rbtn_red_get(a_type, a_field, node)); \ - rbtn_left_set(a_type, a_field, pathp->node, \ - rbtn_left_get(a_type, a_field, node)); \ - /* If node's successor is its right child, the following code */\ - /* will do the wrong thing for the right child pointer. */\ - /* However, it doesn't matter, because the pointer will be */\ - /* properly set when the successor is pruned. */\ - rbtn_right_set(a_type, a_field, pathp->node, \ - rbtn_right_get(a_type, a_field, node)); \ - rbtn_color_set(a_type, a_field, node, tred); \ - /* The pruned leaf node's child pointers are never accessed */\ - /* again, so don't bother setting them to nil. */\ - nodep->node = pathp->node; \ - pathp->node = node; \ - if (nodep == path) { \ - rbtree->rbt_root = nodep->node; \ - } else { \ - if (nodep[-1].cmp < 0) { \ - rbtn_left_set(a_type, a_field, nodep[-1].node, \ - nodep->node); \ - } else { \ - rbtn_right_set(a_type, a_field, nodep[-1].node, \ - nodep->node); \ - } \ - } \ - } else { \ - a_type *left = rbtn_left_get(a_type, a_field, node); \ - if (left != &rbtree->rbt_nil) { \ - /* node has no successor, but it has a left child. */\ - /* Splice node out, without losing the left child. */\ - assert(rbtn_red_get(a_type, a_field, node) == false); \ - assert(rbtn_red_get(a_type, a_field, left)); \ - rbtn_black_set(a_type, a_field, left); \ - if (pathp == path) { \ - rbtree->rbt_root = left; \ - } else { \ - if (pathp[-1].cmp < 0) { \ - rbtn_left_set(a_type, a_field, pathp[-1].node, \ - left); \ - } else { \ - rbtn_right_set(a_type, a_field, pathp[-1].node, \ - left); \ - } \ - } \ - return; \ - } else if (pathp == path) { \ - /* The tree only contained one node. */ \ - rbtree->rbt_root = &rbtree->rbt_nil; \ - return; \ - } \ - } \ - if (rbtn_red_get(a_type, a_field, pathp->node)) { \ - /* Prune red node, which requires no fixup. */ \ - assert(pathp[-1].cmp < 0); \ - rbtn_left_set(a_type, a_field, pathp[-1].node, \ - &rbtree->rbt_nil); \ - return; \ - } \ - /* The node to be pruned is black, so unwind until balance is */\ - /* restored. */\ - pathp->node = &rbtree->rbt_nil; \ - for (pathp--; (uintptr_t)pathp >= (uintptr_t)path; pathp--) { \ - assert(pathp->cmp != 0); \ - if (pathp->cmp < 0) { \ - rbtn_left_set(a_type, a_field, pathp->node, \ - pathp[1].node); \ - assert(rbtn_red_get(a_type, a_field, pathp[1].node) \ - == false); \ - if (rbtn_red_get(a_type, a_field, pathp->node)) { \ - a_type *right = rbtn_right_get(a_type, a_field, \ - pathp->node); \ - a_type *rightleft = rbtn_left_get(a_type, a_field, \ - right); \ - a_type *tnode; \ - if (rbtn_red_get(a_type, a_field, rightleft)) { \ - /* In the following diagrams, ||, //, and \\ */\ - /* indicate the path to the removed node. */\ - /* */\ - /* || */\ - /* pathp(r) */\ - /* // \ */\ - /* (b) (b) */\ - /* / */\ - /* (r) */\ - /* */\ - rbtn_black_set(a_type, a_field, pathp->node); \ - rbtn_rotate_right(a_type, a_field, right, tnode); \ - rbtn_right_set(a_type, a_field, pathp->node, tnode);\ - rbtn_rotate_left(a_type, a_field, pathp->node, \ - tnode); \ - } else { \ - /* || */\ - /* pathp(r) */\ - /* // \ */\ - /* (b) (b) */\ - /* / */\ - /* (b) */\ - /* */\ - rbtn_rotate_left(a_type, a_field, pathp->node, \ - tnode); \ - } \ - /* Balance restored, but rotation modified subtree */\ - /* root. */\ - assert((uintptr_t)pathp > (uintptr_t)path); \ - if (pathp[-1].cmp < 0) { \ - rbtn_left_set(a_type, a_field, pathp[-1].node, \ - tnode); \ - } else { \ - rbtn_right_set(a_type, a_field, pathp[-1].node, \ - tnode); \ - } \ - return; \ - } else { \ - a_type *right = rbtn_right_get(a_type, a_field, \ - pathp->node); \ - a_type *rightleft = rbtn_left_get(a_type, a_field, \ - right); \ - if (rbtn_red_get(a_type, a_field, rightleft)) { \ - /* || */\ - /* pathp(b) */\ - /* // \ */\ - /* (b) (b) */\ - /* / */\ - /* (r) */\ - a_type *tnode; \ - rbtn_black_set(a_type, a_field, rightleft); \ - rbtn_rotate_right(a_type, a_field, right, tnode); \ - rbtn_right_set(a_type, a_field, pathp->node, tnode);\ - rbtn_rotate_left(a_type, a_field, pathp->node, \ - tnode); \ - /* Balance restored, but rotation modified */\ - /* subree root, which may actually be the tree */\ - /* root. */\ - if (pathp == path) { \ - /* Set root. */ \ - rbtree->rbt_root = tnode; \ - } else { \ - if (pathp[-1].cmp < 0) { \ - rbtn_left_set(a_type, a_field, \ - pathp[-1].node, tnode); \ - } else { \ - rbtn_right_set(a_type, a_field, \ - pathp[-1].node, tnode); \ - } \ - } \ - return; \ - } else { \ - /* || */\ - /* pathp(b) */\ - /* // \ */\ - /* (b) (b) */\ - /* / */\ - /* (b) */\ - a_type *tnode; \ - rbtn_red_set(a_type, a_field, pathp->node); \ - rbtn_rotate_left(a_type, a_field, pathp->node, \ - tnode); \ - pathp->node = tnode; \ - } \ - } \ - } else { \ - a_type *left; \ - rbtn_right_set(a_type, a_field, pathp->node, \ - pathp[1].node); \ - left = rbtn_left_get(a_type, a_field, pathp->node); \ - if (rbtn_red_get(a_type, a_field, left)) { \ - a_type *tnode; \ - a_type *leftright = rbtn_right_get(a_type, a_field, \ - left); \ - a_type *leftrightleft = rbtn_left_get(a_type, a_field, \ - leftright); \ - if (rbtn_red_get(a_type, a_field, leftrightleft)) { \ - /* || */\ - /* pathp(b) */\ - /* / \\ */\ - /* (r) (b) */\ - /* \ */\ - /* (b) */\ - /* / */\ - /* (r) */\ - a_type *unode; \ - rbtn_black_set(a_type, a_field, leftrightleft); \ - rbtn_rotate_right(a_type, a_field, pathp->node, \ - unode); \ - rbtn_rotate_right(a_type, a_field, pathp->node, \ - tnode); \ - rbtn_right_set(a_type, a_field, unode, tnode); \ - rbtn_rotate_left(a_type, a_field, unode, tnode); \ - } else { \ - /* || */\ - /* pathp(b) */\ - /* / \\ */\ - /* (r) (b) */\ - /* \ */\ - /* (b) */\ - /* / */\ - /* (b) */\ - assert(leftright != &rbtree->rbt_nil); \ - rbtn_red_set(a_type, a_field, leftright); \ - rbtn_rotate_right(a_type, a_field, pathp->node, \ - tnode); \ - rbtn_black_set(a_type, a_field, tnode); \ - } \ - /* Balance restored, but rotation modified subtree */\ - /* root, which may actually be the tree root. */\ - if (pathp == path) { \ - /* Set root. */ \ - rbtree->rbt_root = tnode; \ - } else { \ - if (pathp[-1].cmp < 0) { \ - rbtn_left_set(a_type, a_field, pathp[-1].node, \ - tnode); \ - } else { \ - rbtn_right_set(a_type, a_field, pathp[-1].node, \ - tnode); \ - } \ - } \ - return; \ - } else if (rbtn_red_get(a_type, a_field, pathp->node)) { \ - a_type *leftleft = rbtn_left_get(a_type, a_field, left);\ - if (rbtn_red_get(a_type, a_field, leftleft)) { \ - /* || */\ - /* pathp(r) */\ - /* / \\ */\ - /* (b) (b) */\ - /* / */\ - /* (r) */\ - a_type *tnode; \ - rbtn_black_set(a_type, a_field, pathp->node); \ - rbtn_red_set(a_type, a_field, left); \ - rbtn_black_set(a_type, a_field, leftleft); \ - rbtn_rotate_right(a_type, a_field, pathp->node, \ - tnode); \ - /* Balance restored, but rotation modified */\ - /* subtree root. */\ - assert((uintptr_t)pathp > (uintptr_t)path); \ - if (pathp[-1].cmp < 0) { \ - rbtn_left_set(a_type, a_field, pathp[-1].node, \ - tnode); \ - } else { \ - rbtn_right_set(a_type, a_field, pathp[-1].node, \ - tnode); \ - } \ - return; \ - } else { \ - /* || */\ - /* pathp(r) */\ - /* / \\ */\ - /* (b) (b) */\ - /* / */\ - /* (b) */\ - rbtn_red_set(a_type, a_field, left); \ - rbtn_black_set(a_type, a_field, pathp->node); \ - /* Balance restored. */ \ - return; \ - } \ - } else { \ - a_type *leftleft = rbtn_left_get(a_type, a_field, left);\ - if (rbtn_red_get(a_type, a_field, leftleft)) { \ - /* || */\ - /* pathp(b) */\ - /* / \\ */\ - /* (b) (b) */\ - /* / */\ - /* (r) */\ - a_type *tnode; \ - rbtn_black_set(a_type, a_field, leftleft); \ - rbtn_rotate_right(a_type, a_field, pathp->node, \ - tnode); \ - /* Balance restored, but rotation modified */\ - /* subtree root, which may actually be the tree */\ - /* root. */\ - if (pathp == path) { \ - /* Set root. */ \ - rbtree->rbt_root = tnode; \ - } else { \ - if (pathp[-1].cmp < 0) { \ - rbtn_left_set(a_type, a_field, \ - pathp[-1].node, tnode); \ - } else { \ - rbtn_right_set(a_type, a_field, \ - pathp[-1].node, tnode); \ - } \ - } \ - return; \ - } else { \ - /* || */\ - /* pathp(b) */\ - /* / \\ */\ - /* (b) (b) */\ - /* / */\ - /* (b) */\ - rbtn_red_set(a_type, a_field, left); \ - } \ - } \ - } \ - } \ - /* Set root. */ \ - rbtree->rbt_root = path->node; \ - assert(rbtn_red_get(a_type, a_field, rbtree->rbt_root) == false); \ -} \ -a_attr a_type * \ -a_prefix##iter_recurse(a_rbt_type *rbtree, a_type *node, \ - a_type *(*cb)(a_rbt_type *, a_type *, void *), void *arg) { \ - if (node == &rbtree->rbt_nil) { \ - return (&rbtree->rbt_nil); \ - } else { \ - a_type *ret; \ - if ((ret = a_prefix##iter_recurse(rbtree, rbtn_left_get(a_type, \ - a_field, node), cb, arg)) != &rbtree->rbt_nil \ - || (ret = cb(rbtree, node, arg)) != NULL) { \ - return (ret); \ - } \ - return (a_prefix##iter_recurse(rbtree, rbtn_right_get(a_type, \ - a_field, node), cb, arg)); \ - } \ -} \ -a_attr a_type * \ -a_prefix##iter_start(a_rbt_type *rbtree, a_type *start, a_type *node, \ - a_type *(*cb)(a_rbt_type *, a_type *, void *), void *arg) { \ - int cmp = a_cmp(start, node); \ - if (cmp < 0) { \ - a_type *ret; \ - if ((ret = a_prefix##iter_start(rbtree, start, \ - rbtn_left_get(a_type, a_field, node), cb, arg)) != \ - &rbtree->rbt_nil || (ret = cb(rbtree, node, arg)) != NULL) { \ - return (ret); \ - } \ - return (a_prefix##iter_recurse(rbtree, rbtn_right_get(a_type, \ - a_field, node), cb, arg)); \ - } else if (cmp > 0) { \ - return (a_prefix##iter_start(rbtree, start, \ - rbtn_right_get(a_type, a_field, node), cb, arg)); \ - } else { \ - a_type *ret; \ - if ((ret = cb(rbtree, node, arg)) != NULL) { \ - return (ret); \ - } \ - return (a_prefix##iter_recurse(rbtree, rbtn_right_get(a_type, \ - a_field, node), cb, arg)); \ - } \ -} \ -a_attr a_type * \ -a_prefix##iter(a_rbt_type *rbtree, a_type *start, a_type *(*cb)( \ - a_rbt_type *, a_type *, void *), void *arg) { \ - a_type *ret; \ - if (start != NULL) { \ - ret = a_prefix##iter_start(rbtree, start, rbtree->rbt_root, \ - cb, arg); \ - } else { \ - ret = a_prefix##iter_recurse(rbtree, rbtree->rbt_root, cb, arg);\ - } \ - if (ret == &rbtree->rbt_nil) { \ - ret = NULL; \ - } \ - return (ret); \ -} \ -a_attr a_type * \ -a_prefix##reverse_iter_recurse(a_rbt_type *rbtree, a_type *node, \ - a_type *(*cb)(a_rbt_type *, a_type *, void *), void *arg) { \ - if (node == &rbtree->rbt_nil) { \ - return (&rbtree->rbt_nil); \ - } else { \ - a_type *ret; \ - if ((ret = a_prefix##reverse_iter_recurse(rbtree, \ - rbtn_right_get(a_type, a_field, node), cb, arg)) != \ - &rbtree->rbt_nil || (ret = cb(rbtree, node, arg)) != NULL) { \ - return (ret); \ - } \ - return (a_prefix##reverse_iter_recurse(rbtree, \ - rbtn_left_get(a_type, a_field, node), cb, arg)); \ - } \ -} \ -a_attr a_type * \ -a_prefix##reverse_iter_start(a_rbt_type *rbtree, a_type *start, \ - a_type *node, a_type *(*cb)(a_rbt_type *, a_type *, void *), \ - void *arg) { \ - int cmp = a_cmp(start, node); \ - if (cmp > 0) { \ - a_type *ret; \ - if ((ret = a_prefix##reverse_iter_start(rbtree, start, \ - rbtn_right_get(a_type, a_field, node), cb, arg)) != \ - &rbtree->rbt_nil || (ret = cb(rbtree, node, arg)) != NULL) { \ - return (ret); \ - } \ - return (a_prefix##reverse_iter_recurse(rbtree, \ - rbtn_left_get(a_type, a_field, node), cb, arg)); \ - } else if (cmp < 0) { \ - return (a_prefix##reverse_iter_start(rbtree, start, \ - rbtn_left_get(a_type, a_field, node), cb, arg)); \ - } else { \ - a_type *ret; \ - if ((ret = cb(rbtree, node, arg)) != NULL) { \ - return (ret); \ - } \ - return (a_prefix##reverse_iter_recurse(rbtree, \ - rbtn_left_get(a_type, a_field, node), cb, arg)); \ - } \ -} \ -a_attr a_type * \ -a_prefix##reverse_iter(a_rbt_type *rbtree, a_type *start, \ - a_type *(*cb)(a_rbt_type *, a_type *, void *), void *arg) { \ - a_type *ret; \ - if (start != NULL) { \ - ret = a_prefix##reverse_iter_start(rbtree, start, \ - rbtree->rbt_root, cb, arg); \ - } else { \ - ret = a_prefix##reverse_iter_recurse(rbtree, rbtree->rbt_root, \ - cb, arg); \ - } \ - if (ret == &rbtree->rbt_nil) { \ - ret = NULL; \ - } \ - return (ret); \ -} - -#endif /* RB_H_ */ diff --git a/externals/jemalloc/jemalloc/internal/stats.h b/externals/jemalloc/jemalloc/internal/stats.h deleted file mode 100644 index cbf035ff2b9..00000000000 --- a/externals/jemalloc/jemalloc/internal/stats.h +++ /dev/null @@ -1,174 +0,0 @@ -/******************************************************************************/ -#ifdef JEMALLOC_H_TYPES - -#define UMAX2S_BUFSIZE 65 - -#ifdef JEMALLOC_STATS -typedef struct tcache_bin_stats_s tcache_bin_stats_t; -typedef struct malloc_bin_stats_s malloc_bin_stats_t; -typedef struct malloc_large_stats_s malloc_large_stats_t; -typedef struct arena_stats_s arena_stats_t; -#endif -#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) -typedef struct chunk_stats_s chunk_stats_t; -#endif - -#endif /* JEMALLOC_H_TYPES */ -/******************************************************************************/ -#ifdef JEMALLOC_H_STRUCTS - -#ifdef JEMALLOC_STATS - -#ifdef JEMALLOC_TCACHE -struct tcache_bin_stats_s { - /* - * Number of allocation requests that corresponded to the size of this - * bin. - */ - uint64_t nrequests; -}; -#endif - -struct malloc_bin_stats_s { - /* - * Current number of bytes allocated, including objects currently - * cached by tcache. - */ - size_t allocated; - - /* - * Total number of allocation/deallocation requests served directly by - * the bin. Note that tcache may allocate an object, then recycle it - * many times, resulting many increments to nrequests, but only one - * each to nmalloc and ndalloc. - */ - uint64_t nmalloc; - uint64_t ndalloc; - - /* - * Number of allocation requests that correspond to the size of this - * bin. This includes requests served by tcache, though tcache only - * periodically merges into this counter. - */ - uint64_t nrequests; - -#ifdef JEMALLOC_TCACHE - /* Number of tcache fills from this bin. */ - uint64_t nfills; - - /* Number of tcache flushes to this bin. */ - uint64_t nflushes; -#endif - - /* Total number of runs created for this bin's size class. */ - uint64_t nruns; - - /* - * Total number of runs reused by extracting them from the runs tree for - * this bin's size class. - */ - uint64_t reruns; - - /* High-water mark for this bin. */ - size_t highruns; - - /* Current number of runs in this bin. */ - size_t curruns; -}; - -struct malloc_large_stats_s { - /* - * Total number of allocation/deallocation requests served directly by - * the arena. Note that tcache may allocate an object, then recycle it - * many times, resulting many increments to nrequests, but only one - * each to nmalloc and ndalloc. - */ - uint64_t nmalloc; - uint64_t ndalloc; - - /* - * Number of allocation requests that correspond to this size class. - * This includes requests served by tcache, though tcache only - * periodically merges into this counter. - */ - uint64_t nrequests; - - /* High-water mark for this size class. */ - size_t highruns; - - /* Current number of runs of this size class. */ - size_t curruns; -}; - -struct arena_stats_s { - /* Number of bytes currently mapped. */ - size_t mapped; - - /* - * Total number of purge sweeps, total number of madvise calls made, - * and total pages purged in order to keep dirty unused memory under - * control. - */ - uint64_t npurge; - uint64_t nmadvise; - uint64_t purged; - - /* Per-size-category statistics. */ - size_t allocated_large; - uint64_t nmalloc_large; - uint64_t ndalloc_large; - uint64_t nrequests_large; - - /* - * One element for each possible size class, including sizes that - * overlap with bin size classes. This is necessary because ipalloc() - * sometimes has to use such large objects in order to assure proper - * alignment. - */ - malloc_large_stats_t *lstats; -}; -#endif /* JEMALLOC_STATS */ - -#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) -struct chunk_stats_s { -# ifdef JEMALLOC_STATS - /* Number of chunks that were allocated. */ - uint64_t nchunks; -# endif - - /* High-water mark for number of chunks allocated. */ - size_t highchunks; - - /* - * Current number of chunks allocated. This value isn't maintained for - * any other purpose, so keep track of it in order to be able to set - * highchunks. - */ - size_t curchunks; -}; -#endif /* JEMALLOC_STATS */ - -#endif /* JEMALLOC_H_STRUCTS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_EXTERNS - -extern bool opt_stats_print; - -char *umax2s(uintmax_t x, unsigned base, char *s); -#ifdef JEMALLOC_STATS -void malloc_cprintf(void (*write)(void *, const char *), void *cbopaque, - const char *format, ...) JEMALLOC_ATTR(format(printf, 3, 4)); -void malloc_printf(const char *format, ...) - JEMALLOC_ATTR(format(printf, 1, 2)); -#endif -void stats_print(void (*write)(void *, const char *), void *cbopaque, - const char *opts); - -#endif /* JEMALLOC_H_EXTERNS */ -/******************************************************************************/ -#ifdef JEMALLOC_STATS -#ifdef JEMALLOC_H_INLINES - -#endif /* JEMALLOC_H_INLINES */ -#endif /* JEMALLOC_STATS */ -/******************************************************************************/ diff --git a/externals/jemalloc/jemalloc/internal/tcache.h b/externals/jemalloc/jemalloc/internal/tcache.h deleted file mode 100644 index c76597fafab..00000000000 --- a/externals/jemalloc/jemalloc/internal/tcache.h +++ /dev/null @@ -1,380 +0,0 @@ -#ifdef JEMALLOC_TCACHE -/******************************************************************************/ -#ifdef JEMALLOC_H_TYPES - -typedef struct tcache_bin_s tcache_bin_t; -typedef struct tcache_s tcache_t; - -/* - * Absolute maximum number of cache slots for each small bin in the thread - * cache. This is an additional constraint beyond that imposed as: twice the - * number of regions per run for this size class. - * - * This constant must be an even number. - */ -#define TCACHE_NSLOTS_SMALL_MAX 200 - -/* Number of cache slots for large size classes. */ -#define TCACHE_NSLOTS_LARGE 20 - -/* (1U << opt_lg_tcache_maxclass) is used to compute tcache_maxclass. */ -#define LG_TCACHE_MAXCLASS_DEFAULT 15 - -/* - * (1U << opt_lg_tcache_gc_sweep) is the approximate number of allocation - * events between full GC sweeps (-1: disabled). Integer rounding may cause - * the actual number to be slightly higher, since GC is performed - * incrementally. - */ -#define LG_TCACHE_GC_SWEEP_DEFAULT 13 - -#endif /* JEMALLOC_H_TYPES */ -/******************************************************************************/ -#ifdef JEMALLOC_H_STRUCTS - -struct tcache_bin_s { -# ifdef JEMALLOC_STATS - tcache_bin_stats_t tstats; -# endif - unsigned low_water; /* Min # cached since last GC. */ - unsigned high_water; /* Max # cached since last GC. */ - unsigned ncached; /* # of cached objects. */ - unsigned ncached_max; /* Upper limit on ncached. */ - void *avail; /* Chain of available objects. */ -}; - -struct tcache_s { -# ifdef JEMALLOC_STATS - ql_elm(tcache_t) link; /* Used for aggregating stats. */ -# endif -# ifdef JEMALLOC_PROF - uint64_t prof_accumbytes;/* Cleared after arena_prof_accum() */ -# endif - arena_t *arena; /* This thread's arena. */ - unsigned ev_cnt; /* Event count since incremental GC. */ - unsigned next_gc_bin; /* Next bin to GC. */ - tcache_bin_t tbins[1]; /* Dynamically sized. */ -}; - -#endif /* JEMALLOC_H_STRUCTS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_EXTERNS - -extern bool opt_tcache; -extern ssize_t opt_lg_tcache_maxclass; -extern ssize_t opt_lg_tcache_gc_sweep; - -/* Map of thread-specific caches. */ -extern __thread tcache_t *tcache_tls - JEMALLOC_ATTR(tls_model("initial-exec")); - -/* - * Number of tcache bins. There are nbins small-object bins, plus 0 or more - * large-object bins. - */ -extern size_t nhbins; - -/* Maximum cached size class. */ -extern size_t tcache_maxclass; - -/* Number of tcache allocation/deallocation events between incremental GCs. */ -extern unsigned tcache_gc_incr; - -void tcache_bin_flush_small(tcache_bin_t *tbin, size_t binind, unsigned rem -#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) - , tcache_t *tcache -#endif - ); -void tcache_bin_flush_large(tcache_bin_t *tbin, size_t binind, unsigned rem -#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) - , tcache_t *tcache -#endif - ); -tcache_t *tcache_create(arena_t *arena); -void *tcache_alloc_small_hard(tcache_t *tcache, tcache_bin_t *tbin, - size_t binind); -void tcache_destroy(tcache_t *tcache); -#ifdef JEMALLOC_STATS -void tcache_stats_merge(tcache_t *tcache, arena_t *arena); -#endif -void tcache_boot(void); - -#endif /* JEMALLOC_H_EXTERNS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_INLINES - -#ifndef JEMALLOC_ENABLE_INLINE -void tcache_event(tcache_t *tcache); -tcache_t *tcache_get(void); -void *tcache_alloc_easy(tcache_bin_t *tbin); -void *tcache_alloc_small(tcache_t *tcache, size_t size, bool zero); -void *tcache_alloc_large(tcache_t *tcache, size_t size, bool zero); -void tcache_dalloc_small(tcache_t *tcache, void *ptr); -void tcache_dalloc_large(tcache_t *tcache, void *ptr, size_t size); -#endif - -#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_TCACHE_C_)) -JEMALLOC_INLINE tcache_t * -tcache_get(void) -{ - tcache_t *tcache; - - if ((isthreaded & opt_tcache) == false) - return (NULL); - - tcache = tcache_tls; - if ((uintptr_t)tcache <= (uintptr_t)1) { - if (tcache == NULL) { - tcache = tcache_create(choose_arena()); - if (tcache == NULL) - return (NULL); - } else - return (NULL); - } - - return (tcache); -} - -JEMALLOC_INLINE void -tcache_event(tcache_t *tcache) -{ - - if (tcache_gc_incr == 0) - return; - - tcache->ev_cnt++; - assert(tcache->ev_cnt <= tcache_gc_incr); - if (tcache->ev_cnt == tcache_gc_incr) { - size_t binind = tcache->next_gc_bin; - tcache_bin_t *tbin = &tcache->tbins[binind]; - - if (tbin->low_water > 0) { - /* - * Flush (ceiling) 3/4 of the objects below the low - * water mark. - */ - if (binind < nbins) { - tcache_bin_flush_small(tbin, binind, - tbin->ncached - tbin->low_water + - (tbin->low_water >> 2) -#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) - , tcache -#endif - ); - } else { - tcache_bin_flush_large(tbin, binind, - tbin->ncached - tbin->low_water + - (tbin->low_water >> 2) -#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) - , tcache -#endif - ); - } - } - tbin->low_water = tbin->ncached; - tbin->high_water = tbin->ncached; - - tcache->next_gc_bin++; - if (tcache->next_gc_bin == nhbins) - tcache->next_gc_bin = 0; - tcache->ev_cnt = 0; - } -} - -JEMALLOC_INLINE void * -tcache_alloc_easy(tcache_bin_t *tbin) -{ - void *ret; - - if (tbin->ncached == 0) - return (NULL); - tbin->ncached--; - if (tbin->ncached < tbin->low_water) - tbin->low_water = tbin->ncached; - ret = tbin->avail; - tbin->avail = *(void **)ret; - return (ret); -} - -JEMALLOC_INLINE void * -tcache_alloc_small(tcache_t *tcache, size_t size, bool zero) -{ - void *ret; - size_t binind; - tcache_bin_t *tbin; - - binind = small_size2bin[size]; - assert(binind < nbins); - tbin = &tcache->tbins[binind]; - ret = tcache_alloc_easy(tbin); - if (ret == NULL) { - ret = tcache_alloc_small_hard(tcache, tbin, binind); - if (ret == NULL) - return (NULL); - } - assert(arena_salloc(ret) == tcache->arena->bins[binind].reg_size); - - if (zero == false) { -#ifdef JEMALLOC_FILL - if (opt_junk) - memset(ret, 0xa5, size); - else if (opt_zero) - memset(ret, 0, size); -#endif - } else - memset(ret, 0, size); - -#ifdef JEMALLOC_STATS - tbin->tstats.nrequests++; -#endif -#ifdef JEMALLOC_PROF - tcache->prof_accumbytes += tcache->arena->bins[binind].reg_size; -#endif - tcache_event(tcache); - return (ret); -} - -JEMALLOC_INLINE void * -tcache_alloc_large(tcache_t *tcache, size_t size, bool zero) -{ - void *ret; - size_t binind; - tcache_bin_t *tbin; - - size = PAGE_CEILING(size); - assert(size <= tcache_maxclass); - binind = nbins + (size >> PAGE_SHIFT) - 1; - assert(binind < nhbins); - tbin = &tcache->tbins[binind]; - ret = tcache_alloc_easy(tbin); - if (ret == NULL) { - /* - * Only allocate one large object at a time, because it's quite - * expensive to create one and not use it. - */ - ret = arena_malloc_large(tcache->arena, size, zero); - if (ret == NULL) - return (NULL); - } else { -#ifdef JEMALLOC_PROF - arena_chunk_t *chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ret); - size_t pageind = (unsigned)(((uintptr_t)ret - (uintptr_t)chunk) - >> PAGE_SHIFT); - chunk->map[pageind].bits |= CHUNK_MAP_CLASS_MASK; -#endif - if (zero == false) { -#ifdef JEMALLOC_FILL - if (opt_junk) - memset(ret, 0xa5, size); - else if (opt_zero) - memset(ret, 0, size); -#endif - } else - memset(ret, 0, size); - -#ifdef JEMALLOC_STATS - tbin->tstats.nrequests++; -#endif -#ifdef JEMALLOC_PROF - tcache->prof_accumbytes += size; -#endif - } - - tcache_event(tcache); - return (ret); -} - -JEMALLOC_INLINE void -tcache_dalloc_small(tcache_t *tcache, void *ptr) -{ - arena_t *arena; - arena_chunk_t *chunk; - arena_run_t *run; - arena_bin_t *bin; - tcache_bin_t *tbin; - size_t pageind, binind; - arena_chunk_map_t *mapelm; - - assert(arena_salloc(ptr) <= small_maxclass); - - chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); - arena = chunk->arena; - pageind = (((uintptr_t)ptr - (uintptr_t)chunk) >> PAGE_SHIFT); - mapelm = &chunk->map[pageind]; - run = (arena_run_t *)((uintptr_t)chunk + (uintptr_t)((pageind - - (mapelm->bits >> PAGE_SHIFT)) << PAGE_SHIFT)); - assert(run->magic == ARENA_RUN_MAGIC); - bin = run->bin; - binind = ((uintptr_t)bin - (uintptr_t)&arena->bins) / - sizeof(arena_bin_t); - assert(binind < nbins); - -#ifdef JEMALLOC_FILL - if (opt_junk) - memset(ptr, 0x5a, bin->reg_size); -#endif - - tbin = &tcache->tbins[binind]; - if (tbin->ncached == tbin->ncached_max) { - tcache_bin_flush_small(tbin, binind, (tbin->ncached_max >> 1) -#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) - , tcache -#endif - ); - } - assert(tbin->ncached < tbin->ncached_max); - *(void **)ptr = tbin->avail; - tbin->avail = ptr; - tbin->ncached++; - if (tbin->ncached > tbin->high_water) - tbin->high_water = tbin->ncached; - - tcache_event(tcache); -} - -JEMALLOC_INLINE void -tcache_dalloc_large(tcache_t *tcache, void *ptr, size_t size) -{ - arena_t *arena; - arena_chunk_t *chunk; - size_t pageind, binind; - tcache_bin_t *tbin; - arena_chunk_map_t *mapelm; - - assert((size & PAGE_MASK) == 0); - assert(arena_salloc(ptr) > small_maxclass); - assert(arena_salloc(ptr) <= tcache_maxclass); - - chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); - arena = chunk->arena; - pageind = (((uintptr_t)ptr - (uintptr_t)chunk) >> PAGE_SHIFT); - mapelm = &chunk->map[pageind]; - binind = nbins + (size >> PAGE_SHIFT) - 1; - -#ifdef JEMALLOC_FILL - if (opt_junk) - memset(ptr, 0x5a, bin->reg_size); -#endif - - tbin = &tcache->tbins[binind]; - if (tbin->ncached == tbin->ncached_max) { - tcache_bin_flush_large(tbin, binind, (tbin->ncached_max >> 1) -#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) - , tcache -#endif - ); - } - assert(tbin->ncached < tbin->ncached_max); - *(void **)ptr = tbin->avail; - tbin->avail = ptr; - tbin->ncached++; - if (tbin->ncached > tbin->high_water) - tbin->high_water = tbin->ncached; - - tcache_event(tcache); -} -#endif - -#endif /* JEMALLOC_H_INLINES */ -/******************************************************************************/ -#endif /* JEMALLOC_TCACHE */ diff --git a/externals/jemalloc/jemalloc/internal/totally_not_p_r_n.h b/externals/jemalloc/jemalloc/internal/totally_not_p_r_n.h deleted file mode 100644 index 0709d708012..00000000000 --- a/externals/jemalloc/jemalloc/internal/totally_not_p_r_n.h +++ /dev/null @@ -1,60 +0,0 @@ -/******************************************************************************/ -#ifdef JEMALLOC_H_TYPES - -/* - * Simple linear congruential pseudo-random number generator: - * - * prn(y) = (a*x + c) % m - * - * where the following constants ensure maximal period: - * - * a == Odd number (relatively prime to 2^n), and (a-1) is a multiple of 4. - * c == Odd number (relatively prime to 2^n). - * m == 2^32 - * - * See Knuth's TAOCP 3rd Ed., Vol. 2, pg. 17 for details on these constraints. - * - * This choice of m has the disadvantage that the quality of the bits is - * proportional to bit position. For example. the lowest bit has a cycle of 2, - * the next has a cycle of 4, etc. For this reason, we prefer to use the upper - * bits. - * - * Macro parameters: - * uint32_t r : Result. - * unsigned lg_range : (0..32], number of least significant bits to return. - * uint32_t state : Seed value. - * const uint32_t a, c : See above discussion. - */ -#define prn32(r, lg_range, state, a, c) do { \ - assert(lg_range > 0); \ - assert(lg_range <= 32); \ - \ - r = (state * (a)) + (c); \ - state = r; \ - r >>= (32 - lg_range); \ -} while (false) - -/* Same as prn32(), but 64 bits of pseudo-randomness, using uint64_t. */ -#define prn64(r, lg_range, state, a, c) do { \ - assert(lg_range > 0); \ - assert(lg_range <= 64); \ - \ - r = (state * (a)) + (c); \ - state = r; \ - r >>= (64 - lg_range); \ -} while (false) - -#endif /* JEMALLOC_H_TYPES */ -/******************************************************************************/ -#ifdef JEMALLOC_H_STRUCTS - -#endif /* JEMALLOC_H_STRUCTS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_EXTERNS - -#endif /* JEMALLOC_H_EXTERNS */ -/******************************************************************************/ -#ifdef JEMALLOC_H_INLINES - -#endif /* JEMALLOC_H_INLINES */ -/******************************************************************************/ diff --git a/externals/jemalloc/jemalloc/jemalloc.h b/externals/jemalloc/jemalloc/jemalloc.h deleted file mode 100644 index d9bafbfff55..00000000000 --- a/externals/jemalloc/jemalloc/jemalloc.h +++ /dev/null @@ -1,42 +0,0 @@ -#ifndef JEMALLOC_H_ -#define JEMALLOC_H_ -#ifdef __cplusplus -extern "C" { -#endif - -#define JEMALLOC_VERSION "1.0.0-0-g5523399" -#define JEMALLOC_VERSION_MAJOR 1 -#define JEMALLOC_VERSION_MINOR 0 -#define JEMALLOC_VERSION_BUGFIX 0 -#define JEMALLOC_VERSION_NREV 0 -#define JEMALLOC_VERSION_GID "5523399" - -#include "jemalloc_defs.h" -#ifndef JEMALLOC_P -# define JEMALLOC_P(s) s -#endif - -extern const char *JEMALLOC_P(malloc_options); -extern void (*JEMALLOC_P(malloc_message))(void *, const char *); - -void *JEMALLOC_P(malloc)(size_t size) JEMALLOC_ATTR(malloc); -void *JEMALLOC_P(calloc)(size_t num, size_t size) JEMALLOC_ATTR(malloc); -int JEMALLOC_P(posix_memalign)(void **memptr, size_t alignment, size_t size) - JEMALLOC_ATTR(nonnull(1)); -void *JEMALLOC_P(realloc)(void *ptr, size_t size); -void JEMALLOC_P(free)(void *ptr); - -size_t JEMALLOC_P(malloc_usable_size)(const void *ptr); -void JEMALLOC_P(malloc_stats_print)(void (*write_cb)(void *, const char *), - void *cbopaque, const char *opts); -int JEMALLOC_P(mallctl)(const char *name, void *oldp, size_t *oldlenp, - void *newp, size_t newlen); -int JEMALLOC_P(mallctlnametomib)(const char *name, size_t *mibp, - size_t *miblenp); -int JEMALLOC_P(mallctlbymib)(const size_t *mib, size_t miblen, void *oldp, - size_t *oldlenp, void *newp, size_t newlen); - -#ifdef __cplusplus -}; -#endif -#endif /* JEMALLOC_H_ */ diff --git a/externals/jemalloc/jemalloc/jemalloc.h.in b/externals/jemalloc/jemalloc/jemalloc.h.in deleted file mode 100644 index 8ef8183686e..00000000000 --- a/externals/jemalloc/jemalloc/jemalloc.h.in +++ /dev/null @@ -1,42 +0,0 @@ -#ifndef JEMALLOC_H_ -#define JEMALLOC_H_ -#ifdef __cplusplus -extern "C" { -#endif - -#define JEMALLOC_VERSION "@jemalloc_version@" -#define JEMALLOC_VERSION_MAJOR @jemalloc_version_major@ -#define JEMALLOC_VERSION_MINOR @jemalloc_version_minor@ -#define JEMALLOC_VERSION_BUGFIX @jemalloc_version_bugfix@ -#define JEMALLOC_VERSION_NREV @jemalloc_version_nrev@ -#define JEMALLOC_VERSION_GID "@jemalloc_version_gid@" - -#include "jemalloc_defs@install_suffix@.h" -#ifndef JEMALLOC_P -# define JEMALLOC_P(s) s -#endif - -extern const char *JEMALLOC_P(malloc_options); -extern void (*JEMALLOC_P(malloc_message))(void *, const char *); - -void *JEMALLOC_P(malloc)(size_t size) JEMALLOC_ATTR(malloc); -void *JEMALLOC_P(calloc)(size_t num, size_t size) JEMALLOC_ATTR(malloc); -int JEMALLOC_P(posix_memalign)(void **memptr, size_t alignment, size_t size) - JEMALLOC_ATTR(nonnull(1)); -void *JEMALLOC_P(realloc)(void *ptr, size_t size); -void JEMALLOC_P(free)(void *ptr); - -size_t JEMALLOC_P(malloc_usable_size)(const void *ptr); -void JEMALLOC_P(malloc_stats_print)(void (*write_cb)(void *, const char *), - void *cbopaque, const char *opts); -int JEMALLOC_P(mallctl)(const char *name, void *oldp, size_t *oldlenp, - void *newp, size_t newlen); -int JEMALLOC_P(mallctlnametomib)(const char *name, size_t *mibp, - size_t *miblenp); -int JEMALLOC_P(mallctlbymib)(const size_t *mib, size_t miblen, void *oldp, - size_t *oldlenp, void *newp, size_t newlen); - -#ifdef __cplusplus -}; -#endif -#endif /* JEMALLOC_H_ */ diff --git a/externals/jemalloc/jemalloc/jemalloc_defs.h b/externals/jemalloc/jemalloc/jemalloc_defs.h deleted file mode 100644 index e8acaed3abd..00000000000 --- a/externals/jemalloc/jemalloc/jemalloc_defs.h +++ /dev/null @@ -1,102 +0,0 @@ -/* include/jemalloc/jemalloc_defs.h. Generated from jemalloc_defs.h.in by configure. */ -#ifndef JEMALLOC_DEFS_H_ -#define JEMALLOC_DEFS_H_ - -/* - * If JEMALLOC_PREFIX is defined, it will cause all public APIs to be prefixed. - * This makes it possible, with some care, to use multiple allocators - * simultaneously. - * - * In many cases it is more convenient to manually prefix allocator function - * calls than to let macros do it automatically, particularly when using - * multiple allocators simultaneously. Define JEMALLOC_MANGLE before - * #include'ing jemalloc.h in order to cause name mangling that corresponds to - * the API prefixing. - */ -/* #undef JEMALLOC_PREFIX */ -#if (defined(JEMALLOC_PREFIX) && defined(JEMALLOC_MANGLE)) -/* #undef JEMALLOC_P */ -#endif - -/* - * Hyper-threaded CPUs may need a special instruction inside spin loops in - * order to yield to another virtual CPU. - */ -#define CPU_SPINWAIT __asm__ volatile("pause") - -/* Defined if __attribute__((...)) syntax is supported. */ -#define JEMALLOC_HAVE_ATTR -#ifdef JEMALLOC_HAVE_ATTR -# define JEMALLOC_ATTR(s) __attribute__((s)) -#else -# define JEMALLOC_ATTR(s) -#endif - -/* - * JEMALLOC_DEBUG enables assertions and other sanity checks, and disables - * inline functions. - */ -/* #undef JEMALLOC_DEBUG */ - -/* JEMALLOC_STATS enables statistics calculation. */ -/* #undef JEMALLOC_STATS */ - -/* JEMALLOC_PROF enables allocation profiling. */ -/* #undef JEMALLOC_PROF */ - -/* Use libunwind for profile backtracing if defined. */ -/* #undef JEMALLOC_PROF_LIBUNWIND */ - -/* Use libgcc for profile backtracing if defined. */ -/* #undef JEMALLOC_PROF_LIBGCC */ - -/* - * JEMALLOC_TINY enables support for tiny objects, which are smaller than one - * quantum. - */ -#define JEMALLOC_TINY - -/* - * JEMALLOC_TCACHE enables a thread-specific caching layer for small objects. - * This makes it possible to allocate/deallocate objects without any locking - * when the cache is in the steady state. - */ -#define JEMALLOC_TCACHE - -/* - * JEMALLOC_DSS enables use of sbrk(2) to allocate chunks from the data storage - * segment (DSS). - */ -/* #undef JEMALLOC_DSS */ - -/* JEMALLOC_SWAP enables mmap()ed swap file support. */ -/* #undef JEMALLOC_SWAP */ - -/* Support memory filling (junk/zero). */ -/* #undef JEMALLOC_FILL */ - -/* Support optional abort() on OOM. */ -/* #undef JEMALLOC_XMALLOC */ - -/* Support SYSV semantics. */ -/* #undef JEMALLOC_SYSV */ - -/* Support lazy locking (avoid locking unless a second thread is launched). */ -#define JEMALLOC_LAZY_LOCK - -/* Determine page size at run time if defined. */ -/* #undef DYNAMIC_PAGE_SHIFT */ - -/* One page is 2^STATIC_PAGE_SHIFT bytes. */ -#define STATIC_PAGE_SHIFT 12 - -/* TLS is used to map arenas and magazine caches to threads. */ -/* #undef NO_TLS */ - -/* sizeof(void *) == 2^LG_SIZEOF_PTR. */ -#define LG_SIZEOF_PTR 3 - -/* sizeof(int) == 2^LG_SIZEOF_INT. */ -#define LG_SIZEOF_INT 2 - -#endif /* JEMALLOC_DEFS_H_ */ diff --git a/externals/jemalloc/jemalloc/jemalloc_defs.h.in b/externals/jemalloc/jemalloc/jemalloc_defs.h.in deleted file mode 100644 index 8b98d670acc..00000000000 --- a/externals/jemalloc/jemalloc/jemalloc_defs.h.in +++ /dev/null @@ -1,101 +0,0 @@ -#ifndef JEMALLOC_DEFS_H_ -#define JEMALLOC_DEFS_H_ - -/* - * If JEMALLOC_PREFIX is defined, it will cause all public APIs to be prefixed. - * This makes it possible, with some care, to use multiple allocators - * simultaneously. - * - * In many cases it is more convenient to manually prefix allocator function - * calls than to let macros do it automatically, particularly when using - * multiple allocators simultaneously. Define JEMALLOC_MANGLE before - * #include'ing jemalloc.h in order to cause name mangling that corresponds to - * the API prefixing. - */ -#undef JEMALLOC_PREFIX -#if (defined(JEMALLOC_PREFIX) && defined(JEMALLOC_MANGLE)) -#undef JEMALLOC_P -#endif - -/* - * Hyper-threaded CPUs may need a special instruction inside spin loops in - * order to yield to another virtual CPU. - */ -#undef CPU_SPINWAIT - -/* Defined if __attribute__((...)) syntax is supported. */ -#undef JEMALLOC_HAVE_ATTR -#ifdef JEMALLOC_HAVE_ATTR -# define JEMALLOC_ATTR(s) __attribute__((s)) -#else -# define JEMALLOC_ATTR(s) -#endif - -/* - * JEMALLOC_DEBUG enables assertions and other sanity checks, and disables - * inline functions. - */ -#undef JEMALLOC_DEBUG - -/* JEMALLOC_STATS enables statistics calculation. */ -#undef JEMALLOC_STATS - -/* JEMALLOC_PROF enables allocation profiling. */ -#undef JEMALLOC_PROF - -/* Use libunwind for profile backtracing if defined. */ -#undef JEMALLOC_PROF_LIBUNWIND - -/* Use libgcc for profile backtracing if defined. */ -#undef JEMALLOC_PROF_LIBGCC - -/* - * JEMALLOC_TINY enables support for tiny objects, which are smaller than one - * quantum. - */ -#undef JEMALLOC_TINY - -/* - * JEMALLOC_TCACHE enables a thread-specific caching layer for small objects. - * This makes it possible to allocate/deallocate objects without any locking - * when the cache is in the steady state. - */ -#undef JEMALLOC_TCACHE - -/* - * JEMALLOC_DSS enables use of sbrk(2) to allocate chunks from the data storage - * segment (DSS). - */ -#undef JEMALLOC_DSS - -/* JEMALLOC_SWAP enables mmap()ed swap file support. */ -#undef JEMALLOC_SWAP - -/* Support memory filling (junk/zero). */ -#undef JEMALLOC_FILL - -/* Support optional abort() on OOM. */ -#undef JEMALLOC_XMALLOC - -/* Support SYSV semantics. */ -#undef JEMALLOC_SYSV - -/* Support lazy locking (avoid locking unless a second thread is launched). */ -#undef JEMALLOC_LAZY_LOCK - -/* Determine page size at run time if defined. */ -#undef DYNAMIC_PAGE_SHIFT - -/* One page is 2^STATIC_PAGE_SHIFT bytes. */ -#undef STATIC_PAGE_SHIFT - -/* TLS is used to map arenas and magazine caches to threads. */ -#undef NO_TLS - -/* sizeof(void *) == 2^LG_SIZEOF_PTR. */ -#undef LG_SIZEOF_PTR - -/* sizeof(int) == 2^LG_SIZEOF_INT. */ -#undef LG_SIZEOF_INT - -#endif /* JEMALLOC_DEFS_H_ */ diff --git a/externals/jemalloc/mb.c b/externals/jemalloc/mb.c deleted file mode 100644 index 30a1a2e997a..00000000000 --- a/externals/jemalloc/mb.c +++ /dev/null @@ -1,2 +0,0 @@ -#define MB_C_ -#include "jemalloc/internal/jemalloc_internal.h" diff --git a/externals/jemalloc/mutex.c b/externals/jemalloc/mutex.c deleted file mode 100644 index 3b6081a4c4f..00000000000 --- a/externals/jemalloc/mutex.c +++ /dev/null @@ -1,70 +0,0 @@ -#define JEMALLOC_MUTEX_C_ -#include "jemalloc/internal/jemalloc_internal.h" - -/******************************************************************************/ -/* Data. */ - -#ifdef JEMALLOC_LAZY_LOCK -bool isthreaded = false; -#endif - -#ifdef JEMALLOC_LAZY_LOCK -static void pthread_create_once(void); -#endif - -/******************************************************************************/ -/* - * We intercept pthread_create() calls in order to toggle isthreaded if the - * process goes multi-threaded. - */ - -#ifdef JEMALLOC_LAZY_LOCK -static int (*pthread_create_fptr)(pthread_t *__restrict, const pthread_attr_t *, - void *(*)(void *), void *__restrict); - -static void -pthread_create_once(void) -{ - - pthread_create_fptr = dlsym(RTLD_NEXT, "pthread_create"); - if (pthread_create_fptr == NULL) { - malloc_write(": Error in dlsym(RTLD_NEXT, " - "\"pthread_create\")\n"); - abort(); - } - - isthreaded = true; -} - -JEMALLOC_ATTR(visibility("default")) -int -pthread_create(pthread_t *__restrict thread, - const pthread_attr_t *__restrict attr, void *(*start_routine)(void *), - void *__restrict arg) -{ - static pthread_once_t once_control = PTHREAD_ONCE_INIT; - - pthread_once(&once_control, pthread_create_once); - - return (pthread_create_fptr(thread, attr, start_routine, arg)); -} -#endif - -/******************************************************************************/ - -bool -malloc_mutex_init(malloc_mutex_t *mutex) -{ - pthread_mutexattr_t attr; - - if (pthread_mutexattr_init(&attr) != 0) - return (true); - pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ADAPTIVE_NP); - if (pthread_mutex_init(mutex, &attr) != 0) { - pthread_mutexattr_destroy(&attr); - return (true); - } - pthread_mutexattr_destroy(&attr); - - return (false); -} diff --git a/externals/jemalloc/prof.c b/externals/jemalloc/prof.c deleted file mode 100644 index 6326188e50f..00000000000 --- a/externals/jemalloc/prof.c +++ /dev/null @@ -1,1328 +0,0 @@ -#define JEMALLOC_PROF_C_ -#include "jemalloc/internal/jemalloc_internal.h" -#ifdef JEMALLOC_PROF -/******************************************************************************/ - -#ifdef JEMALLOC_PROF_LIBGCC -#include -#endif - -#ifdef JEMALLOC_PROF_LIBUNWIND -#define UNW_LOCAL_ONLY -#include -#endif - -#include - -/******************************************************************************/ -/* Data. */ - -bool opt_prof = false; -bool opt_prof_active = true; -size_t opt_lg_prof_bt_max = LG_PROF_BT_MAX_DEFAULT; -size_t opt_lg_prof_sample = LG_PROF_SAMPLE_DEFAULT; -ssize_t opt_lg_prof_interval = LG_PROF_INTERVAL_DEFAULT; -bool opt_prof_udump = false; -bool opt_prof_leak = false; - -uint64_t prof_interval; -bool prof_promote; - -/* - * Global hash of (prof_bt_t *)-->(prof_ctx_t *). This is the master data - * structure that knows about all backtraces ever captured. - */ -static ckh_t bt2ctx; -static malloc_mutex_t bt2ctx_mtx; - -/* - * Thread-specific hash of (prof_bt_t *)-->(prof_thr_cnt_t *). Each thread - * keeps a cache of backtraces, with associated thread-specific prof_thr_cnt_t - * objects. Other threads may read the prof_thr_cnt_t contents, but no others - * will ever write them. - * - * Upon thread exit, the thread must merge all the prof_thr_cnt_t counter data - * into the associated prof_ctx_t objects, and unlink/free the prof_thr_cnt_t - * objects. - */ -static __thread ckh_t *bt2cnt_tls JEMALLOC_ATTR(tls_model("initial-exec")); - -/* - * Same contents as b2cnt, but initialized such that the TSD destructor is - * called when a thread exits, so that bt2cnt_tls contents can be merged, - * unlinked, and deallocated. - */ -static pthread_key_t bt2cnt_tsd; - -/* (1U << opt_lg_prof_bt_max). */ -static unsigned prof_bt_max; - -static __thread uint64_t prof_sample_prn_state - JEMALLOC_ATTR(tls_model("initial-exec")); -static __thread uint64_t prof_sample_threshold - JEMALLOC_ATTR(tls_model("initial-exec")); -static __thread uint64_t prof_sample_accum - JEMALLOC_ATTR(tls_model("initial-exec")); - -static malloc_mutex_t prof_dump_seq_mtx; -static uint64_t prof_dump_seq; -static uint64_t prof_dump_iseq; -static uint64_t prof_dump_mseq; -static uint64_t prof_dump_useq; - -/* - * This buffer is rather large for stack allocation, so use a single buffer for - * all profile dumps. The buffer is implicitly protected by bt2ctx_mtx, since - * it must be locked anyway during dumping. - */ -static char prof_dump_buf[PROF_DUMP_BUF_SIZE]; -static unsigned prof_dump_buf_end; -static int prof_dump_fd; - -/* Do not dump any profiles until bootstrapping is complete. */ -static bool prof_booted = false; - -static malloc_mutex_t enq_mtx; -static bool enq; -static bool enq_idump; -static bool enq_udump; - -/******************************************************************************/ -/* Function prototypes for non-inline static functions. */ - -static prof_bt_t *bt_dup(prof_bt_t *bt); -static void bt_init(prof_bt_t *bt, void **vec); -#ifdef JEMALLOC_PROF_LIBGCC -static _Unwind_Reason_Code prof_unwind_init_callback( - struct _Unwind_Context *context, void *arg); -static _Unwind_Reason_Code prof_unwind_callback( - struct _Unwind_Context *context, void *arg); -#endif -static void prof_backtrace(prof_bt_t *bt, unsigned nignore, unsigned max); -static prof_thr_cnt_t *prof_lookup(prof_bt_t *bt); -static void prof_cnt_set(const void *ptr, prof_thr_cnt_t *cnt); -static bool prof_flush(bool propagate_err); -static bool prof_write(const char *s, bool propagate_err); -static void prof_ctx_merge(prof_ctx_t *ctx, prof_cnt_t *cnt_all, - size_t *leak_nctx); -static bool prof_dump_ctx(prof_ctx_t *ctx, prof_bt_t *bt, - bool propagate_err); -static bool prof_dump_maps(bool propagate_err); -static bool prof_dump(const char *filename, bool leakcheck, - bool propagate_err); -static void prof_dump_filename(char *filename, char v, int64_t vseq); -static void prof_fdump(void); -static void prof_bt_hash(const void *key, unsigned minbits, size_t *hash1, - size_t *hash2); -static bool prof_bt_keycomp(const void *k1, const void *k2); -static void bt2cnt_thread_cleanup(void *arg); - -/******************************************************************************/ - -static void -bt_init(prof_bt_t *bt, void **vec) -{ - - bt->vec = vec; - bt->len = 0; -} - -static prof_bt_t * -bt_dup(prof_bt_t *bt) -{ - prof_bt_t *ret; - - /* - * Create a single allocation that has space for vec immediately - * following the prof_bt_t structure. The backtraces that get - * stored in the backtrace caches are copied from stack-allocated - * temporary variables, so size is known at creation time. Making this - * a contiguous object improves cache locality. - */ - ret = (prof_bt_t *)imalloc(QUANTUM_CEILING(sizeof(prof_bt_t)) + - (bt->len * sizeof(void *))); - if (ret == NULL) - return (NULL); - ret->vec = (void **)((uintptr_t)ret + - QUANTUM_CEILING(sizeof(prof_bt_t))); - memcpy(ret->vec, bt->vec, bt->len * sizeof(void *)); - ret->len = bt->len; - - return (ret); -} - -static inline void -prof_enter(void) -{ - - malloc_mutex_lock(&enq_mtx); - enq = true; - malloc_mutex_unlock(&enq_mtx); - - malloc_mutex_lock(&bt2ctx_mtx); -} - -static inline void -prof_leave(void) -{ - bool idump, udump; - - malloc_mutex_unlock(&bt2ctx_mtx); - - malloc_mutex_lock(&enq_mtx); - enq = false; - idump = enq_idump; - enq_idump = false; - udump = enq_udump; - enq_udump = false; - malloc_mutex_unlock(&enq_mtx); - - if (idump) - prof_idump(); - if (udump) - prof_udump(); -} - -#ifdef JEMALLOC_PROF_LIBGCC -static _Unwind_Reason_Code -prof_unwind_init_callback(struct _Unwind_Context *context, void *arg) -{ - - return (_URC_NO_REASON); -} - -static _Unwind_Reason_Code -prof_unwind_callback(struct _Unwind_Context *context, void *arg) -{ - prof_unwind_data_t *data = (prof_unwind_data_t *)arg; - - if (data->nignore > 0) - data->nignore--; - else { - data->bt->vec[data->bt->len] = (void *)_Unwind_GetIP(context); - data->bt->len++; - if (data->bt->len == data->max) - return (_URC_END_OF_STACK); - } - - return (_URC_NO_REASON); -} - -static void -prof_backtrace(prof_bt_t *bt, unsigned nignore, unsigned max) -{ - prof_unwind_data_t data = {bt, nignore, max}; - - _Unwind_Backtrace(prof_unwind_callback, &data); -} -#elif defined(JEMALLOC_PROF_LIBUNWIND) -static void -prof_backtrace(prof_bt_t *bt, unsigned nignore, unsigned max) -{ - unw_context_t uc; - unw_cursor_t cursor; - unsigned i; - int err; - - assert(bt->len == 0); - assert(bt->vec != NULL); - assert(max <= (1U << opt_lg_prof_bt_max)); - - unw_getcontext(&uc); - unw_init_local(&cursor, &uc); - - /* Throw away (nignore+1) stack frames, if that many exist. */ - for (i = 0; i < nignore + 1; i++) { - err = unw_step(&cursor); - if (err <= 0) - return; - } - - /* - * Iterate over stack frames until there are no more. Heap-allocate - * and iteratively grow a larger bt if necessary. - */ - for (i = 0; i < max; i++) { - unw_get_reg(&cursor, UNW_REG_IP, (unw_word_t *)&bt->vec[i]); - err = unw_step(&cursor); - if (err <= 0) { - bt->len = i; - break; - } - } -} -#else -static void -prof_backtrace(prof_bt_t *bt, unsigned nignore, unsigned max) -{ -#define NIGNORE 3 -#define BT_FRAME(i) \ - if ((i) < NIGNORE + max) { \ - void *p; \ - if (__builtin_frame_address(i) == 0) \ - return; \ - p = __builtin_return_address(i); \ - if (p == NULL) \ - return; \ - if (i >= NIGNORE) { \ - bt->vec[(i) - NIGNORE] = p; \ - bt->len = (i) - NIGNORE + 1; \ - } \ - } else \ - return; - - assert(max <= (1U << opt_lg_prof_bt_max)); - - /* - * Ignore the first three frames, since they are: - * - * 0: prof_backtrace() - * 1: prof_alloc_prep() - * 2: malloc(), calloc(), etc. - */ -#if 1 - assert(nignore + 1 == NIGNORE); -#else - BT_FRAME(0) - BT_FRAME(1) - BT_FRAME(2) -#endif - BT_FRAME(3) - BT_FRAME(4) - BT_FRAME(5) - BT_FRAME(6) - BT_FRAME(7) - BT_FRAME(8) - BT_FRAME(9) - - BT_FRAME(10) - BT_FRAME(11) - BT_FRAME(12) - BT_FRAME(13) - BT_FRAME(14) - BT_FRAME(15) - BT_FRAME(16) - BT_FRAME(17) - BT_FRAME(18) - BT_FRAME(19) - - BT_FRAME(20) - BT_FRAME(21) - BT_FRAME(22) - BT_FRAME(23) - BT_FRAME(24) - BT_FRAME(25) - BT_FRAME(26) - BT_FRAME(27) - BT_FRAME(28) - BT_FRAME(29) - - BT_FRAME(30) - BT_FRAME(31) - BT_FRAME(32) - BT_FRAME(33) - BT_FRAME(34) - BT_FRAME(35) - BT_FRAME(36) - BT_FRAME(37) - BT_FRAME(38) - BT_FRAME(39) - - BT_FRAME(40) - BT_FRAME(41) - BT_FRAME(42) - BT_FRAME(43) - BT_FRAME(44) - BT_FRAME(45) - BT_FRAME(46) - BT_FRAME(47) - BT_FRAME(48) - BT_FRAME(49) - - BT_FRAME(50) - BT_FRAME(51) - BT_FRAME(52) - BT_FRAME(53) - BT_FRAME(54) - BT_FRAME(55) - BT_FRAME(56) - BT_FRAME(57) - BT_FRAME(58) - BT_FRAME(59) - - BT_FRAME(60) - BT_FRAME(61) - BT_FRAME(62) - BT_FRAME(63) - BT_FRAME(64) - BT_FRAME(65) - BT_FRAME(66) - BT_FRAME(67) - BT_FRAME(68) - BT_FRAME(69) - - BT_FRAME(70) - BT_FRAME(71) - BT_FRAME(72) - BT_FRAME(73) - BT_FRAME(74) - BT_FRAME(75) - BT_FRAME(76) - BT_FRAME(77) - BT_FRAME(78) - BT_FRAME(79) - - BT_FRAME(80) - BT_FRAME(81) - BT_FRAME(82) - BT_FRAME(83) - BT_FRAME(84) - BT_FRAME(85) - BT_FRAME(86) - BT_FRAME(87) - BT_FRAME(88) - BT_FRAME(89) - - BT_FRAME(90) - BT_FRAME(91) - BT_FRAME(92) - BT_FRAME(93) - BT_FRAME(94) - BT_FRAME(95) - BT_FRAME(96) - BT_FRAME(97) - BT_FRAME(98) - BT_FRAME(99) - - BT_FRAME(100) - BT_FRAME(101) - BT_FRAME(102) - BT_FRAME(103) - BT_FRAME(104) - BT_FRAME(105) - BT_FRAME(106) - BT_FRAME(107) - BT_FRAME(108) - BT_FRAME(109) - - BT_FRAME(110) - BT_FRAME(111) - BT_FRAME(112) - BT_FRAME(113) - BT_FRAME(114) - BT_FRAME(115) - BT_FRAME(116) - BT_FRAME(117) - BT_FRAME(118) - BT_FRAME(119) - - BT_FRAME(120) - BT_FRAME(121) - BT_FRAME(122) - BT_FRAME(123) - BT_FRAME(124) - BT_FRAME(125) - BT_FRAME(126) - BT_FRAME(127) - - /* Extras to compensate for NIGNORE. */ - BT_FRAME(128) - BT_FRAME(129) - BT_FRAME(130) -#undef BT_FRAME -} -#endif - -static prof_thr_cnt_t * -prof_lookup(prof_bt_t *bt) -{ - prof_thr_cnt_t *ret; - ckh_t *bt2cnt = bt2cnt_tls; - - if (bt2cnt == NULL) { - /* Initialize an empty cache for this thread. */ - bt2cnt = (ckh_t *)imalloc(sizeof(ckh_t)); - if (bt2cnt == NULL) - return (NULL); - if (ckh_new(bt2cnt, PROF_CKH_MINITEMS, prof_bt_hash, - prof_bt_keycomp)) { - idalloc(bt2cnt); - return (NULL); - } - bt2cnt_tls = bt2cnt; - } - - if (ckh_search(bt2cnt, bt, NULL, (void **)&ret)) { - prof_bt_t *btkey; - prof_ctx_t *ctx; - - /* - * This thread's cache lacks bt. Look for it in the global - * cache. - */ - prof_enter(); - if (ckh_search(&bt2ctx, bt, (void **)&btkey, (void **)&ctx)) { - - /* bt has never been seen before. Insert it. */ - ctx = (prof_ctx_t *)imalloc(sizeof(prof_ctx_t)); - if (ctx == NULL) { - prof_leave(); - return (NULL); - } - btkey = bt_dup(bt); - if (btkey == NULL) { - prof_leave(); - idalloc(ctx); - return (NULL); - } - if (malloc_mutex_init(&ctx->lock)) { - prof_leave(); - idalloc(btkey); - idalloc(ctx); - return (NULL); - } - memset(&ctx->cnt_merged, 0, sizeof(prof_cnt_t)); - ql_new(&ctx->cnts_ql); - if (ckh_insert(&bt2ctx, btkey, ctx)) { - /* OOM. */ - prof_leave(); - idalloc(btkey); - idalloc(ctx); - return (NULL); - } - } - prof_leave(); - - /* Link a prof_thd_cnt_t into ctx for this thread. */ - ret = (prof_thr_cnt_t *)imalloc(sizeof(prof_thr_cnt_t)); - if (ret == NULL) - return (NULL); - ql_elm_new(ret, link); - ret->ctx = ctx; - ret->epoch = 0; - memset(&ret->cnts, 0, sizeof(prof_cnt_t)); - if (ckh_insert(bt2cnt, btkey, ret)) { - idalloc(ret); - return (NULL); - } - malloc_mutex_lock(&ctx->lock); - ql_tail_insert(&ctx->cnts_ql, ret, link); - malloc_mutex_unlock(&ctx->lock); - } - - return (ret); -} - -static inline void -prof_sample_threshold_update(void) -{ - uint64_t r; - double u; - - /* - * Compute prof_sample_threshold as a geometrically distributed random - * variable with mean (2^opt_lg_prof_sample). - */ - prn64(r, 53, prof_sample_prn_state, (uint64_t)1125899906842625LLU, - 1058392653243283975); - u = (double)r * (1.0/9007199254740992.0L); - prof_sample_threshold = (uint64_t)(log(u) / - log(1.0 - (1.0 / (double)((uint64_t)1U << opt_lg_prof_sample)))) - + (uint64_t)1U; -} - -prof_thr_cnt_t * -prof_alloc_prep(size_t size) -{ - prof_thr_cnt_t *ret; - void *vec[prof_bt_max]; - prof_bt_t bt; - - if (opt_prof_active == false) { - /* Sampling is currently inactive, so avoid sampling. */ - ret = (prof_thr_cnt_t *)(uintptr_t)1U; - } else if (opt_lg_prof_sample == 0) { - /* - * Don't bother with sampling logic, since sampling interval is - * 1. - */ - bt_init(&bt, vec); - prof_backtrace(&bt, 2, prof_bt_max); - ret = prof_lookup(&bt); - } else { - if (prof_sample_threshold == 0) { - /* - * Initialize. Seed the prng differently for each - * thread. - */ - prof_sample_prn_state = (uint64_t)(uintptr_t)&size; - prof_sample_threshold_update(); - } - - /* - * Determine whether to capture a backtrace based on whether - * size is enough for prof_accum to reach - * prof_sample_threshold. However, delay updating these - * variables until prof_{m,re}alloc(), because we don't know - * for sure that the allocation will succeed. - * - * Use subtraction rather than addition to avoid potential - * integer overflow. - */ - if (size >= prof_sample_threshold - prof_sample_accum) { - bt_init(&bt, vec); - prof_backtrace(&bt, 2, prof_bt_max); - ret = prof_lookup(&bt); - } else - ret = (prof_thr_cnt_t *)(uintptr_t)1U; - } - - return (ret); -} - -prof_thr_cnt_t * -prof_cnt_get(const void *ptr) -{ - prof_thr_cnt_t *ret; - arena_chunk_t *chunk; - - assert(ptr != NULL); - - chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); - if (chunk != ptr) { - /* Region. */ - assert(chunk->arena->magic == ARENA_MAGIC); - - ret = arena_prof_cnt_get(ptr); - } else - ret = huge_prof_cnt_get(ptr); - - return (ret); -} - -static void -prof_cnt_set(const void *ptr, prof_thr_cnt_t *cnt) -{ - arena_chunk_t *chunk; - - assert(ptr != NULL); - - chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); - if (chunk != ptr) { - /* Region. */ - assert(chunk->arena->magic == ARENA_MAGIC); - - arena_prof_cnt_set(ptr, cnt); - } else - huge_prof_cnt_set(ptr, cnt); -} - -static inline void -prof_sample_accum_update(size_t size) -{ - - if (opt_lg_prof_sample == 0) { - /* - * Don't bother with sampling logic, since sampling interval is - * 1. - */ - return; - } - - /* Take care to avoid integer overflow. */ - if (size >= prof_sample_threshold - prof_sample_accum) { - prof_sample_accum -= (prof_sample_threshold - size); - /* Compute new prof_sample_threshold. */ - prof_sample_threshold_update(); - while (prof_sample_accum >= prof_sample_threshold) { - prof_sample_accum -= prof_sample_threshold; - prof_sample_threshold_update(); - } - } else - prof_sample_accum += size; -} - -void -prof_malloc(const void *ptr, prof_thr_cnt_t *cnt) -{ - size_t size = isalloc(ptr); - - assert(ptr != NULL); - - prof_cnt_set(ptr, cnt); - prof_sample_accum_update(size); - - if ((uintptr_t)cnt > (uintptr_t)1U) { - cnt->epoch++; - /*********/ - mb_write(); - /*********/ - cnt->cnts.curobjs++; - cnt->cnts.curbytes += size; - cnt->cnts.accumobjs++; - cnt->cnts.accumbytes += size; - /*********/ - mb_write(); - /*********/ - cnt->epoch++; - /*********/ - mb_write(); - /*********/ - } -} - -void -prof_realloc(const void *ptr, prof_thr_cnt_t *cnt, const void *old_ptr, - size_t old_size, prof_thr_cnt_t *old_cnt) -{ - size_t size = isalloc(ptr); - - if (ptr != NULL) { - prof_cnt_set(ptr, cnt); - prof_sample_accum_update(size); - } - - if ((uintptr_t)old_cnt > (uintptr_t)1U) - old_cnt->epoch++; - if ((uintptr_t)cnt > (uintptr_t)1U) - cnt->epoch++; - /*********/ - mb_write(); - /*********/ - if ((uintptr_t)old_cnt > (uintptr_t)1U) { - old_cnt->cnts.curobjs--; - old_cnt->cnts.curbytes -= old_size; - } - if ((uintptr_t)cnt > (uintptr_t)1U) { - cnt->cnts.curobjs++; - cnt->cnts.curbytes += size; - cnt->cnts.accumobjs++; - cnt->cnts.accumbytes += size; - } - /*********/ - mb_write(); - /*********/ - if ((uintptr_t)old_cnt > (uintptr_t)1U) - old_cnt->epoch++; - if ((uintptr_t)cnt > (uintptr_t)1U) - cnt->epoch++; - /*********/ - mb_write(); /* Not strictly necessary. */ -} - -void -prof_free(const void *ptr) -{ - prof_thr_cnt_t *cnt = prof_cnt_get(ptr); - - if ((uintptr_t)cnt > (uintptr_t)1) { - size_t size = isalloc(ptr); - - cnt->epoch++; - /*********/ - mb_write(); - /*********/ - cnt->cnts.curobjs--; - cnt->cnts.curbytes -= size; - /*********/ - mb_write(); - /*********/ - cnt->epoch++; - /*********/ - mb_write(); - /*********/ - } -} - -static bool -prof_flush(bool propagate_err) -{ - bool ret = false; - ssize_t err; - - err = write(prof_dump_fd, prof_dump_buf, prof_dump_buf_end); - if (err == -1) { - if (propagate_err == false) { - malloc_write(": write() failed during heap " - "profile flush\n"); - if (opt_abort) - abort(); - } - ret = true; - } - prof_dump_buf_end = 0; - - return (ret); -} - -static bool -prof_write(const char *s, bool propagate_err) -{ - unsigned i, slen, n; - - i = 0; - slen = strlen(s); - while (i < slen) { - /* Flush the buffer if it is full. */ - if (prof_dump_buf_end == PROF_DUMP_BUF_SIZE) - if (prof_flush(propagate_err) && propagate_err) - return (true); - - if (prof_dump_buf_end + slen <= PROF_DUMP_BUF_SIZE) { - /* Finish writing. */ - n = slen - i; - } else { - /* Write as much of s as will fit. */ - n = PROF_DUMP_BUF_SIZE - prof_dump_buf_end; - } - memcpy(&prof_dump_buf[prof_dump_buf_end], &s[i], n); - prof_dump_buf_end += n; - i += n; - } - - return (false); -} - -static void -prof_ctx_merge(prof_ctx_t *ctx, prof_cnt_t *cnt_all, size_t *leak_nctx) -{ - prof_thr_cnt_t *thr_cnt; - prof_cnt_t tcnt; - - malloc_mutex_lock(&ctx->lock); - - memcpy(&ctx->cnt_dump, &ctx->cnt_merged, sizeof(prof_cnt_t)); - ql_foreach(thr_cnt, &ctx->cnts_ql, link) { - volatile unsigned *epoch = &thr_cnt->epoch; - - while (true) { - unsigned epoch0 = *epoch; - - /* Make sure epoch is even. */ - if (epoch0 & 1U) - continue; - - memcpy(&tcnt, &thr_cnt->cnts, sizeof(prof_cnt_t)); - - /* Terminate if epoch didn't change while reading. */ - if (*epoch == epoch0) - break; - } - - ctx->cnt_dump.curobjs += tcnt.curobjs; - ctx->cnt_dump.curbytes += tcnt.curbytes; - ctx->cnt_dump.accumobjs += tcnt.accumobjs; - ctx->cnt_dump.accumbytes += tcnt.accumbytes; - - if (tcnt.curobjs != 0) - (*leak_nctx)++; - } - - /* Merge into cnt_all. */ - cnt_all->curobjs += ctx->cnt_dump.curobjs; - cnt_all->curbytes += ctx->cnt_dump.curbytes; - cnt_all->accumobjs += ctx->cnt_dump.accumobjs; - cnt_all->accumbytes += ctx->cnt_dump.accumbytes; - - malloc_mutex_unlock(&ctx->lock); -} - -static bool -prof_dump_ctx(prof_ctx_t *ctx, prof_bt_t *bt, bool propagate_err) -{ - char buf[UMAX2S_BUFSIZE]; - unsigned i; - - if (prof_write(umax2s(ctx->cnt_dump.curobjs, 10, buf), propagate_err) - || prof_write(": ", propagate_err) - || prof_write(umax2s(ctx->cnt_dump.curbytes, 10, buf), - propagate_err) - || prof_write(" [", propagate_err) - || prof_write(umax2s(ctx->cnt_dump.accumobjs, 10, buf), - propagate_err) - || prof_write(": ", propagate_err) - || prof_write(umax2s(ctx->cnt_dump.accumbytes, 10, buf), - propagate_err) - || prof_write("] @", propagate_err)) - return (true); - - for (i = 0; i < bt->len; i++) { - if (prof_write(" 0x", propagate_err) - || prof_write(umax2s((uintptr_t)bt->vec[i], 16, buf), - propagate_err)) - return (true); - } - - if (prof_write("\n", propagate_err)) - return (true); - - return (false); -} - -static bool -prof_dump_maps(bool propagate_err) -{ - int mfd; - char buf[UMAX2S_BUFSIZE]; - char *s; - unsigned i, slen; - /* /proc//maps\0 */ - char mpath[6 + UMAX2S_BUFSIZE - + 5 + 1]; - - i = 0; - - s = "/proc/"; - slen = strlen(s); - memcpy(&mpath[i], s, slen); - i += slen; - - s = umax2s(getpid(), 10, buf); - slen = strlen(s); - memcpy(&mpath[i], s, slen); - i += slen; - - s = "/maps"; - slen = strlen(s); - memcpy(&mpath[i], s, slen); - i += slen; - - mpath[i] = '\0'; - - mfd = open(mpath, O_RDONLY); - if (mfd != -1) { - ssize_t nread; - - if (prof_write("\nMAPPED_LIBRARIES:\n", propagate_err) && - propagate_err) - return (true); - nread = 0; - do { - prof_dump_buf_end += nread; - if (prof_dump_buf_end == PROF_DUMP_BUF_SIZE) { - /* Make space in prof_dump_buf before read(). */ - if (prof_flush(propagate_err) && propagate_err) - return (true); - } - nread = read(mfd, &prof_dump_buf[prof_dump_buf_end], - PROF_DUMP_BUF_SIZE - prof_dump_buf_end); - } while (nread > 0); - close(mfd); - } else - return (true); - - return (false); -} - -static bool -prof_dump(const char *filename, bool leakcheck, bool propagate_err) -{ - prof_cnt_t cnt_all; - size_t tabind; - prof_bt_t *bt; - prof_ctx_t *ctx; - char buf[UMAX2S_BUFSIZE]; - size_t leak_nctx; - - prof_enter(); - prof_dump_fd = creat(filename, 0644); - if (prof_dump_fd == -1) { - if (propagate_err == false) { - malloc_write(": creat(\""); - malloc_write(filename); - malloc_write("\", 0644) failed\n"); - if (opt_abort) - abort(); - } - goto ERROR; - } - - /* Merge per thread profile stats, and sum them in cnt_all. */ - memset(&cnt_all, 0, sizeof(prof_cnt_t)); - leak_nctx = 0; - for (tabind = 0; ckh_iter(&bt2ctx, &tabind, NULL, (void **)&ctx) - == false;) { - prof_ctx_merge(ctx, &cnt_all, &leak_nctx); - } - - /* Dump profile header. */ - if (prof_write("heap profile: ", propagate_err) - || prof_write(umax2s(cnt_all.curobjs, 10, buf), propagate_err) - || prof_write(": ", propagate_err) - || prof_write(umax2s(cnt_all.curbytes, 10, buf), propagate_err) - || prof_write(" [", propagate_err) - || prof_write(umax2s(cnt_all.accumobjs, 10, buf), propagate_err) - || prof_write(": ", propagate_err) - || prof_write(umax2s(cnt_all.accumbytes, 10, buf), propagate_err)) - goto ERROR; - - if (opt_lg_prof_sample == 0) { - if (prof_write("] @ heapprofile\n", propagate_err)) - goto ERROR; - } else { - if (prof_write("] @ heap_v2/", propagate_err) - || prof_write(umax2s((uint64_t)1U << opt_lg_prof_sample, 10, - buf), propagate_err) - || prof_write("\n", propagate_err)) - goto ERROR; - } - - /* Dump per ctx profile stats. */ - for (tabind = 0; ckh_iter(&bt2ctx, &tabind, (void **)&bt, (void **)&ctx) - == false;) { - if (prof_dump_ctx(ctx, bt, propagate_err)) - goto ERROR; - } - - /* Dump /proc//maps if possible. */ - if (prof_dump_maps(propagate_err)) - goto ERROR; - - if (prof_flush(propagate_err)) - goto ERROR; - close(prof_dump_fd); - prof_leave(); - - if (leakcheck && cnt_all.curbytes != 0) { - malloc_write(": Leak summary: "); - malloc_write(umax2s(cnt_all.curbytes, 10, buf)); - malloc_write((cnt_all.curbytes != 1) ? " bytes, " : " byte, "); - malloc_write(umax2s(cnt_all.curobjs, 10, buf)); - malloc_write((cnt_all.curobjs != 1) ? " objects, " : - " object, "); - malloc_write(umax2s(leak_nctx, 10, buf)); - malloc_write((leak_nctx != 1) ? " contexts\n" : " context\n"); - malloc_write(": Run pprof on \""); - malloc_write(filename); - malloc_write("\" for leak detail\n"); - } - - return (false); -ERROR: - prof_leave(); - return (true); -} - -#define DUMP_FILENAME_BUFSIZE (PATH_MAX+ UMAX2S_BUFSIZE \ - + 1 \ - + UMAX2S_BUFSIZE \ - + 2 \ - + UMAX2S_BUFSIZE \ - + 5 + 1) -static void -prof_dump_filename(char *filename, char v, int64_t vseq) -{ - char buf[UMAX2S_BUFSIZE]; - char *s; - unsigned i, slen; - - /* - * Construct a filename of the form: - * - * ...v.heap\0 - * or - * jeprof...v.heap\0 - */ - - i = 0; - - /* - * Use JEMALLOC_PROF_PREFIX if it's set, and if it is short enough to - * avoid overflowing DUMP_FILENAME_BUFSIZE. The result may exceed - * PATH_MAX, but creat(2) will catch that problem. - */ - if ((s = getenv("JEMALLOC_PROF_PREFIX")) != NULL - && strlen(s) + (DUMP_FILENAME_BUFSIZE - PATH_MAX) <= PATH_MAX) { - slen = strlen(s); - memcpy(&filename[i], s, slen); - i += slen; - - s = "."; - } else - s = "jeprof."; - slen = strlen(s); - memcpy(&filename[i], s, slen); - i += slen; - - s = umax2s(getpid(), 10, buf); - slen = strlen(s); - memcpy(&filename[i], s, slen); - i += slen; - - s = "."; - slen = strlen(s); - memcpy(&filename[i], s, slen); - i += slen; - - s = umax2s(prof_dump_seq, 10, buf); - prof_dump_seq++; - slen = strlen(s); - memcpy(&filename[i], s, slen); - i += slen; - - s = "."; - slen = strlen(s); - memcpy(&filename[i], s, slen); - i += slen; - - filename[i] = v; - i++; - - if (vseq != 0xffffffffffffffffLLU) { - s = umax2s(vseq, 10, buf); - slen = strlen(s); - memcpy(&filename[i], s, slen); - i += slen; - } - - s = ".heap"; - slen = strlen(s); - memcpy(&filename[i], s, slen); - i += slen; - - filename[i] = '\0'; -} - -static void -prof_fdump(void) -{ - char filename[DUMP_FILENAME_BUFSIZE]; - - if (prof_booted == false) - return; - - malloc_mutex_lock(&prof_dump_seq_mtx); - prof_dump_filename(filename, 'f', 0xffffffffffffffffLLU); - malloc_mutex_unlock(&prof_dump_seq_mtx); - prof_dump(filename, opt_prof_leak, false); -} - -void -prof_idump(void) -{ - char filename[DUMP_FILENAME_BUFSIZE]; - - if (prof_booted == false) - return; - malloc_mutex_lock(&enq_mtx); - if (enq) { - enq_idump = true; - malloc_mutex_unlock(&enq_mtx); - return; - } - malloc_mutex_unlock(&enq_mtx); - - malloc_mutex_lock(&prof_dump_seq_mtx); - prof_dump_filename(filename, 'i', prof_dump_iseq); - prof_dump_iseq++; - malloc_mutex_unlock(&prof_dump_seq_mtx); - prof_dump(filename, false, false); -} - -bool -prof_mdump(const char *filename) -{ - char filename_buf[DUMP_FILENAME_BUFSIZE]; - - if (opt_prof == false || prof_booted == false) - return (true); - - if (filename == NULL) { - /* No filename specified, so automatically generate one. */ - malloc_mutex_lock(&prof_dump_seq_mtx); - prof_dump_filename(filename_buf, 'm', prof_dump_mseq); - prof_dump_mseq++; - malloc_mutex_unlock(&prof_dump_seq_mtx); - filename = filename_buf; - } - return (prof_dump(filename, false, true)); -} - -void -prof_udump(void) -{ - char filename[DUMP_FILENAME_BUFSIZE]; - - if (prof_booted == false) - return; - malloc_mutex_lock(&enq_mtx); - if (enq) { - enq_udump = true; - malloc_mutex_unlock(&enq_mtx); - return; - } - malloc_mutex_unlock(&enq_mtx); - - malloc_mutex_lock(&prof_dump_seq_mtx); - prof_dump_filename(filename, 'u', prof_dump_useq); - prof_dump_useq++; - malloc_mutex_unlock(&prof_dump_seq_mtx); - prof_dump(filename, false, false); -} - -static void -prof_bt_hash(const void *key, unsigned minbits, size_t *hash1, size_t *hash2) -{ - size_t ret1, ret2; - uint64_t h; - prof_bt_t *bt = (prof_bt_t *)key; - - assert(minbits <= 32 || (SIZEOF_PTR == 8 && minbits <= 64)); - assert(hash1 != NULL); - assert(hash2 != NULL); - - h = hash(bt->vec, bt->len * sizeof(void *), 0x94122f335b332aeaLLU); - if (minbits <= 32) { - /* - * Avoid doing multiple hashes, since a single hash provides - * enough bits. - */ - ret1 = h & ZU(0xffffffffU); - ret2 = h >> 32; - } else { - ret1 = h; - ret2 = hash(bt->vec, bt->len * sizeof(void *), - 0x8432a476666bbc13U); - } - - *hash1 = ret1; - *hash2 = ret2; -} - -static bool -prof_bt_keycomp(const void *k1, const void *k2) -{ - const prof_bt_t *bt1 = (prof_bt_t *)k1; - const prof_bt_t *bt2 = (prof_bt_t *)k2; - - if (bt1->len != bt2->len) - return (false); - return (memcmp(bt1->vec, bt2->vec, bt1->len * sizeof(void *)) == 0); -} - -static void -bt2cnt_thread_cleanup(void *arg) -{ - ckh_t *bt2cnt; - - bt2cnt = bt2cnt_tls; - if (bt2cnt != NULL) { - ql_head(prof_thr_cnt_t) cnts_ql; - size_t tabind; - prof_thr_cnt_t *cnt; - - /* Iteratively merge cnt's into the global stats. */ - ql_new(&cnts_ql); - tabind = 0; - while (ckh_iter(bt2cnt, &tabind, NULL, (void **)&cnt) == - false) { - prof_ctx_t *ctx = cnt->ctx; - /* Merge stats and detach from ctx. */ - malloc_mutex_lock(&ctx->lock); - ctx->cnt_merged.curobjs += cnt->cnts.curobjs; - ctx->cnt_merged.curbytes += cnt->cnts.curbytes; - ctx->cnt_merged.accumobjs += cnt->cnts.accumobjs; - ctx->cnt_merged.accumbytes += cnt->cnts.accumbytes; - ql_remove(&ctx->cnts_ql, cnt, link); - malloc_mutex_unlock(&ctx->lock); - - /* - * Stash cnt for deletion after finishing with - * ckh_iter(). - */ - ql_tail_insert(&cnts_ql, cnt, link); - } - - /* - * Delete the hash table now that cnts_ql has a list of all - * cnt's. - */ - ckh_delete(bt2cnt); - idalloc(bt2cnt); - bt2cnt_tls = NULL; - - /* Delete cnt's. */ - while ((cnt = ql_last(&cnts_ql, link)) != NULL) { - ql_remove(&cnts_ql, cnt, link); - idalloc(cnt); - } - } -} - -void -prof_boot0(void) -{ - - /* - * opt_prof and prof_promote must be in their final state before any - * arenas are initialized, so this function must be executed early. - */ - - if (opt_prof_leak && opt_prof == false) { - /* - * Enable opt_prof, but in such a way that profiles are never - * automatically dumped. - */ - opt_prof = true; - opt_prof_udump = false; - prof_interval = 0; - } else if (opt_prof) { - if (opt_lg_prof_interval >= 0) { - prof_interval = (((uint64_t)1U) << - opt_lg_prof_interval); - } else - prof_interval = 0; - } - - prof_promote = (opt_prof && opt_lg_prof_sample > PAGE_SHIFT); -} - -bool -prof_boot1(void) -{ - - if (opt_prof) { - if (ckh_new(&bt2ctx, PROF_CKH_MINITEMS, prof_bt_hash, - prof_bt_keycomp)) - return (true); - if (malloc_mutex_init(&bt2ctx_mtx)) - return (true); - if (pthread_key_create(&bt2cnt_tsd, bt2cnt_thread_cleanup) - != 0) { - malloc_write( - ": Error in pthread_key_create()\n"); - abort(); - } - - prof_bt_max = (1U << opt_lg_prof_bt_max); - if (malloc_mutex_init(&prof_dump_seq_mtx)) - return (true); - - if (malloc_mutex_init(&enq_mtx)) - return (true); - enq = false; - enq_idump = false; - enq_udump = false; - - if (atexit(prof_fdump) != 0) { - malloc_write(": Error in atexit()\n"); - if (opt_abort) - abort(); - } - } - -#ifdef JEMALLOC_PROF_LIBGCC - /* - * Cause the backtracing machinery to allocate its internal state - * before enabling profiling. - */ - _Unwind_Backtrace(prof_unwind_init_callback, NULL); -#endif - - prof_booted = true; - - return (false); -} - -/******************************************************************************/ -#endif /* JEMALLOC_PROF */ diff --git a/externals/jemalloc/stats.c b/externals/jemalloc/stats.c deleted file mode 100644 index 9dc75293731..00000000000 --- a/externals/jemalloc/stats.c +++ /dev/null @@ -1,717 +0,0 @@ -#define JEMALLOC_STATS_C_ -#include "jemalloc/internal/jemalloc_internal.h" - -#define CTL_GET(n, v, t) do { \ - size_t sz = sizeof(t); \ - xmallctl(n, v, &sz, NULL, 0); \ -} while (0) - -#define CTL_I_GET(n, v, t) do { \ - size_t mib[6]; \ - size_t miblen = sizeof(mib) / sizeof(size_t); \ - size_t sz = sizeof(t); \ - xmallctlnametomib(n, mib, &miblen); \ - mib[2] = i; \ - xmallctlbymib(mib, miblen, v, &sz, NULL, 0); \ -} while (0) - -#define CTL_J_GET(n, v, t) do { \ - size_t mib[6]; \ - size_t miblen = sizeof(mib) / sizeof(size_t); \ - size_t sz = sizeof(t); \ - xmallctlnametomib(n, mib, &miblen); \ - mib[2] = j; \ - xmallctlbymib(mib, miblen, v, &sz, NULL, 0); \ -} while (0) - -#define CTL_IJ_GET(n, v, t) do { \ - size_t mib[6]; \ - size_t miblen = sizeof(mib) / sizeof(size_t); \ - size_t sz = sizeof(t); \ - xmallctlnametomib(n, mib, &miblen); \ - mib[2] = i; \ - mib[4] = j; \ - xmallctlbymib(mib, miblen, v, &sz, NULL, 0); \ -} while (0) - -/******************************************************************************/ -/* Data. */ - -bool opt_stats_print = false; - -/******************************************************************************/ -/* Function prototypes for non-inline static functions. */ - -#ifdef JEMALLOC_STATS -static void malloc_vcprintf(void (*write_cb)(void *, const char *), - void *cbopaque, const char *format, va_list ap); -static void stats_arena_bins_print(void (*write_cb)(void *, const char *), - void *cbopaque, unsigned i); -static void stats_arena_lruns_print(void (*write_cb)(void *, const char *), - void *cbopaque, unsigned i); -static void stats_arena_print(void (*write_cb)(void *, const char *), - void *cbopaque, unsigned i); -#endif - -/******************************************************************************/ - -/* - * We don't want to depend on vsnprintf() for production builds, since that can - * cause unnecessary bloat for static binaries. umax2s() provides minimal - * integer printing functionality, so that malloc_printf() use can be limited to - * JEMALLOC_STATS code. - */ -char * -umax2s(uintmax_t x, unsigned base, char *s) -{ - unsigned i; - - i = UMAX2S_BUFSIZE - 1; - s[i] = '\0'; - switch (base) { - case 10: - do { - i--; - s[i] = "0123456789"[x % 10]; - x /= 10; - } while (x > 0); - break; - case 16: - do { - i--; - s[i] = "0123456789abcdef"[x & 0xf]; - x >>= 4; - } while (x > 0); - break; - default: - do { - i--; - s[i] = "0123456789abcdefghijklmnopqrstuvwxyz"[x % base]; - x /= base; - } while (x > 0); - } - - return (&s[i]); -} - -#ifdef JEMALLOC_STATS -static void -malloc_vcprintf(void (*write_cb)(void *, const char *), void *cbopaque, - const char *format, va_list ap) -{ - char buf[4096]; - - if (write_cb == NULL) { - /* - * The caller did not provide an alternate write_cb callback - * function, so use the default one. malloc_write() is an - * inline function, so use malloc_message() directly here. - */ - write_cb = JEMALLOC_P(malloc_message); - cbopaque = NULL; - } - - vsnprintf(buf, sizeof(buf), format, ap); - write_cb(cbopaque, buf); -} - -/* - * Print to a callback function in such a way as to (hopefully) avoid memory - * allocation. - */ -JEMALLOC_ATTR(format(printf, 3, 4)) -void -malloc_cprintf(void (*write_cb)(void *, const char *), void *cbopaque, - const char *format, ...) -{ - va_list ap; - - va_start(ap, format); - malloc_vcprintf(write_cb, cbopaque, format, ap); - va_end(ap); -} - -/* - * Print to stderr in such a way as to (hopefully) avoid memory allocation. - */ -JEMALLOC_ATTR(format(printf, 1, 2)) -void -malloc_printf(const char *format, ...) -{ - va_list ap; - - va_start(ap, format); - malloc_vcprintf(NULL, NULL, format, ap); - va_end(ap); -} -#endif - -#ifdef JEMALLOC_STATS -static void -stats_arena_bins_print(void (*write_cb)(void *, const char *), void *cbopaque, - unsigned i) -{ - size_t pagesize; - bool config_tcache; - unsigned nbins, j, gap_start; - - CTL_GET("arenas.pagesize", &pagesize, size_t); - - CTL_GET("config.tcache", &config_tcache, bool); - if (config_tcache) { - malloc_cprintf(write_cb, cbopaque, - "bins: bin size regs pgs allocated nmalloc" - " ndalloc nrequests nfills nflushes" - " newruns reruns maxruns curruns\n"); - } else { - malloc_cprintf(write_cb, cbopaque, - "bins: bin size regs pgs allocated nmalloc" - " ndalloc newruns reruns maxruns" - " curruns\n"); - } - CTL_GET("arenas.nbins", &nbins, unsigned); - for (j = 0, gap_start = UINT_MAX; j < nbins; j++) { - uint64_t nruns; - - CTL_IJ_GET("stats.arenas.0.bins.0.nruns", &nruns, uint64_t); - if (nruns == 0) { - if (gap_start == UINT_MAX) - gap_start = j; - } else { - unsigned ntbins_, nqbins, ncbins, nsbins; - size_t reg_size, run_size, allocated; - uint32_t nregs; - uint64_t nmalloc, ndalloc, nrequests, nfills, nflushes; - uint64_t reruns; - size_t highruns, curruns; - - if (gap_start != UINT_MAX) { - if (j > gap_start + 1) { - /* Gap of more than one size class. */ - malloc_cprintf(write_cb, cbopaque, - "[%u..%u]\n", gap_start, - j - 1); - } else { - /* Gap of one size class. */ - malloc_cprintf(write_cb, cbopaque, - "[%u]\n", gap_start); - } - gap_start = UINT_MAX; - } - CTL_GET("arenas.ntbins", &ntbins_, unsigned); - CTL_GET("arenas.nqbins", &nqbins, unsigned); - CTL_GET("arenas.ncbins", &ncbins, unsigned); - CTL_GET("arenas.nsbins", &nsbins, unsigned); - CTL_J_GET("arenas.bin.0.size", ®_size, size_t); - CTL_J_GET("arenas.bin.0.nregs", &nregs, uint32_t); - CTL_J_GET("arenas.bin.0.run_size", &run_size, size_t); - CTL_IJ_GET("stats.arenas.0.bins.0.allocated", - &allocated, size_t); - CTL_IJ_GET("stats.arenas.0.bins.0.nmalloc", - &nmalloc, uint64_t); - CTL_IJ_GET("stats.arenas.0.bins.0.ndalloc", - &ndalloc, uint64_t); - if (config_tcache) { - CTL_IJ_GET("stats.arenas.0.bins.0.nrequests", - &nrequests, uint64_t); - CTL_IJ_GET("stats.arenas.0.bins.0.nfills", - &nfills, uint64_t); - CTL_IJ_GET("stats.arenas.0.bins.0.nflushes", - &nflushes, uint64_t); - } - CTL_IJ_GET("stats.arenas.0.bins.0.nreruns", &reruns, - uint64_t); - CTL_IJ_GET("stats.arenas.0.bins.0.highruns", &highruns, - size_t); - CTL_IJ_GET("stats.arenas.0.bins.0.curruns", &curruns, - size_t); - if (config_tcache) { - malloc_cprintf(write_cb, cbopaque, - "%13u %1s %5zu %4u %3zu %12zu %12"PRIu64 - " %12"PRIu64" %12"PRIu64" %12"PRIu64 - " %12"PRIu64" %12"PRIu64" %12"PRIu64 - " %12zu %12zu\n", - j, - j < ntbins_ ? "T" : j < ntbins_ + nqbins ? - "Q" : j < ntbins_ + nqbins + ncbins ? "C" : - "S", - reg_size, nregs, run_size / pagesize, - allocated, nmalloc, ndalloc, nrequests, - nfills, nflushes, nruns, reruns, highruns, - curruns); - } else { - malloc_cprintf(write_cb, cbopaque, - "%13u %1s %5zu %4u %3zu %12zu %12"PRIu64 - " %12"PRIu64" %12"PRIu64" %12"PRIu64 - " %12zu %12zu\n", - j, - j < ntbins_ ? "T" : j < ntbins_ + nqbins ? - "Q" : j < ntbins_ + nqbins + ncbins ? "C" : - "S", - reg_size, nregs, run_size / pagesize, - allocated, nmalloc, ndalloc, nruns, reruns, - highruns, curruns); - } - } - } - if (gap_start != UINT_MAX) { - if (j > gap_start + 1) { - /* Gap of more than one size class. */ - malloc_cprintf(write_cb, cbopaque, "[%u..%u]\n", - gap_start, j - 1); - } else { - /* Gap of one size class. */ - malloc_cprintf(write_cb, cbopaque, "[%u]\n", gap_start); - } - } -} - -static void -stats_arena_lruns_print(void (*write_cb)(void *, const char *), void *cbopaque, - unsigned i) -{ - size_t pagesize, nlruns, j; - ssize_t gap_start; - - CTL_GET("arenas.pagesize", &pagesize, size_t); - - malloc_cprintf(write_cb, cbopaque, - "large: size pages nmalloc ndalloc nrequests" - " maxruns curruns\n"); - CTL_GET("arenas.nlruns", &nlruns, size_t); - for (j = 0, gap_start = -1; j < nlruns; j++) { - uint64_t nmalloc, ndalloc, nrequests; - size_t run_size, highruns, curruns; - - CTL_IJ_GET("stats.arenas.0.lruns.0.nmalloc", &nmalloc, - uint64_t); - CTL_IJ_GET("stats.arenas.0.lruns.0.ndalloc", &ndalloc, - uint64_t); - CTL_IJ_GET("stats.arenas.0.lruns.0.nrequests", &nrequests, - uint64_t); - if (nrequests == 0) { - if (gap_start == -1) - gap_start = j; - } else { - CTL_J_GET("arenas.lrun.0.size", &run_size, size_t); - CTL_IJ_GET("stats.arenas.0.lruns.0.highruns", &highruns, - size_t); - CTL_IJ_GET("stats.arenas.0.lruns.0.curruns", &curruns, - size_t); - if (gap_start != -1) { - malloc_cprintf(write_cb, cbopaque, "[%zu]\n", - j - gap_start); - gap_start = -1; - } - malloc_cprintf(write_cb, cbopaque, - "%13zu %5zu %12"PRIu64" %12"PRIu64" %12"PRIu64 - " %12zu %12zu\n", - run_size, run_size / pagesize, nmalloc, ndalloc, - nrequests, highruns, curruns); - } - } - if (gap_start != -1) - malloc_cprintf(write_cb, cbopaque, "[%zu]\n", j - gap_start); -} - -static void -stats_arena_print(void (*write_cb)(void *, const char *), void *cbopaque, - unsigned i) -{ - size_t pagesize, pactive, pdirty, mapped; - uint64_t npurge, nmadvise, purged; - size_t small_allocated; - uint64_t small_nmalloc, small_ndalloc, small_nrequests; - size_t large_allocated; - uint64_t large_nmalloc, large_ndalloc, large_nrequests; - - CTL_GET("arenas.pagesize", &pagesize, size_t); - - CTL_I_GET("stats.arenas.0.pactive", &pactive, size_t); - CTL_I_GET("stats.arenas.0.pdirty", &pdirty, size_t); - CTL_I_GET("stats.arenas.0.npurge", &npurge, uint64_t); - CTL_I_GET("stats.arenas.0.nmadvise", &nmadvise, uint64_t); - CTL_I_GET("stats.arenas.0.purged", &purged, uint64_t); - malloc_cprintf(write_cb, cbopaque, - "dirty pages: %zu:%zu active:dirty, %"PRIu64" sweep%s," - " %"PRIu64" madvise%s, %"PRIu64" purged\n", - pactive, pdirty, npurge, npurge == 1 ? "" : "s", - nmadvise, nmadvise == 1 ? "" : "s", purged); - - malloc_cprintf(write_cb, cbopaque, - " allocated nmalloc ndalloc nrequests\n"); - CTL_I_GET("stats.arenas.0.small.allocated", &small_allocated, size_t); - CTL_I_GET("stats.arenas.0.small.nmalloc", &small_nmalloc, uint64_t); - CTL_I_GET("stats.arenas.0.small.ndalloc", &small_ndalloc, uint64_t); - CTL_I_GET("stats.arenas.0.small.nrequests", &small_nrequests, uint64_t); - malloc_cprintf(write_cb, cbopaque, - "small: %12zu %12"PRIu64" %12"PRIu64" %12"PRIu64"\n", - small_allocated, small_nmalloc, small_ndalloc, small_nrequests); - CTL_I_GET("stats.arenas.0.large.allocated", &large_allocated, size_t); - CTL_I_GET("stats.arenas.0.large.nmalloc", &large_nmalloc, uint64_t); - CTL_I_GET("stats.arenas.0.large.ndalloc", &large_ndalloc, uint64_t); - CTL_I_GET("stats.arenas.0.large.nrequests", &large_nrequests, uint64_t); - malloc_cprintf(write_cb, cbopaque, - "large: %12zu %12"PRIu64" %12"PRIu64" %12"PRIu64"\n", - large_allocated, large_nmalloc, large_ndalloc, large_nrequests); - malloc_cprintf(write_cb, cbopaque, - "total: %12zu %12"PRIu64" %12"PRIu64" %12"PRIu64"\n", - small_allocated + large_allocated, - small_nmalloc + large_nmalloc, - small_ndalloc + large_ndalloc, - small_nrequests + large_nrequests); - malloc_cprintf(write_cb, cbopaque, "active: %12zu\n", - pactive * pagesize ); - CTL_I_GET("stats.arenas.0.mapped", &mapped, size_t); - malloc_cprintf(write_cb, cbopaque, "mapped: %12zu\n", mapped); - - stats_arena_bins_print(write_cb, cbopaque, i); - stats_arena_lruns_print(write_cb, cbopaque, i); -} -#endif - -void -stats_print(void (*write_cb)(void *, const char *), void *cbopaque, - const char *opts) -{ - uint64_t epoch; - size_t u64sz; - char s[UMAX2S_BUFSIZE]; - bool general = true; - bool merged = true; - bool unmerged = true; - bool bins = true; - bool large = true; - - /* Refresh stats, in case mallctl() was called by the application. */ - epoch = 1; - u64sz = sizeof(uint64_t); - xmallctl("epoch", &epoch, &u64sz, &epoch, sizeof(uint64_t)); - - if (write_cb == NULL) { - /* - * The caller did not provide an alternate write_cb callback - * function, so use the default one. malloc_write() is an - * inline function, so use malloc_message() directly here. - */ - write_cb = JEMALLOC_P(malloc_message); - cbopaque = NULL; - } - - if (opts != NULL) { - unsigned i; - - for (i = 0; opts[i] != '\0'; i++) { - switch (opts[i]) { - case 'g': - general = false; - break; - case 'm': - merged = false; - break; - case 'a': - unmerged = false; - break; - case 'b': - bins = false; - break; - case 'l': - large = false; - break; - default:; - } - } - } - - write_cb(cbopaque, "___ Begin jemalloc statistics ___\n"); - if (general) { - int err; - const char *cpv; - bool bv; - unsigned uv; - ssize_t ssv; - size_t sv, bsz, ssz; - - bsz = sizeof(bool); - ssz = sizeof(size_t); - - CTL_GET("version", &cpv, const char *); - write_cb(cbopaque, "Version: "); - write_cb(cbopaque, cpv); - write_cb(cbopaque, "\n"); - CTL_GET("config.debug", &bv, bool); - write_cb(cbopaque, "Assertions "); - write_cb(cbopaque, bv ? "enabled" : "disabled"); - write_cb(cbopaque, "\n"); - - write_cb(cbopaque, "Boolean JEMALLOC_OPTIONS: "); - if ((err = JEMALLOC_P(mallctl)("opt.abort", &bv, &bsz, NULL, 0)) - == 0) - write_cb(cbopaque, bv ? "A" : "a"); - if ((err = JEMALLOC_P(mallctl)("prof.active", &bv, &bsz, - NULL, 0)) == 0) - write_cb(cbopaque, bv ? "E" : "e"); - if ((err = JEMALLOC_P(mallctl)("opt.prof", &bv, &bsz, NULL, 0)) - == 0) - write_cb(cbopaque, bv ? "F" : "f"); - if ((err = JEMALLOC_P(mallctl)("opt.tcache", &bv, &bsz, NULL, - 0)) == 0) - write_cb(cbopaque, bv ? "H" : "h"); - if ((err = JEMALLOC_P(mallctl)("opt.junk", &bv, &bsz, NULL, 0)) - == 0) - write_cb(cbopaque, bv ? "J" : "j"); - if ((err = JEMALLOC_P(mallctl)("opt.prof_leak", &bv, &bsz, NULL, - 0)) == 0) - write_cb(cbopaque, bv ? "L" : "l"); - if ((err = JEMALLOC_P(mallctl)("opt.overcommit", &bv, &bsz, - NULL, 0)) == 0) - write_cb(cbopaque, bv ? "O" : "o"); - if ((err = JEMALLOC_P(mallctl)("opt.stats_print", &bv, &bsz, - NULL, 0)) == 0) - write_cb(cbopaque, bv ? "P" : "p"); - if ((err = JEMALLOC_P(mallctl)("opt.prof_udump", &bv, &bsz, - NULL, 0)) == 0) - write_cb(cbopaque, bv ? "U" : "u"); - if ((err = JEMALLOC_P(mallctl)("opt.sysv", &bv, &bsz, NULL, 0)) - == 0) - write_cb(cbopaque, bv ? "V" : "v"); - if ((err = JEMALLOC_P(mallctl)("opt.xmalloc", &bv, &bsz, NULL, - 0)) == 0) - write_cb(cbopaque, bv ? "X" : "x"); - if ((err = JEMALLOC_P(mallctl)("opt.zero", &bv, &bsz, NULL, 0)) - == 0) - write_cb(cbopaque, bv ? "Z" : "z"); - write_cb(cbopaque, "\n"); - - write_cb(cbopaque, "CPUs: "); - write_cb(cbopaque, umax2s(ncpus, 10, s)); - write_cb(cbopaque, "\n"); - - CTL_GET("arenas.narenas", &uv, unsigned); - write_cb(cbopaque, "Max arenas: "); - write_cb(cbopaque, umax2s(uv, 10, s)); - write_cb(cbopaque, "\n"); - - write_cb(cbopaque, "Pointer size: "); - write_cb(cbopaque, umax2s(sizeof(void *), 10, s)); - write_cb(cbopaque, "\n"); - - CTL_GET("arenas.quantum", &sv, size_t); - write_cb(cbopaque, "Quantum size: "); - write_cb(cbopaque, umax2s(sv, 10, s)); - write_cb(cbopaque, "\n"); - - CTL_GET("arenas.cacheline", &sv, size_t); - write_cb(cbopaque, "Cacheline size (assumed): "); - write_cb(cbopaque, umax2s(sv, 10, s)); - write_cb(cbopaque, "\n"); - - CTL_GET("arenas.subpage", &sv, size_t); - write_cb(cbopaque, "Subpage spacing: "); - write_cb(cbopaque, umax2s(sv, 10, s)); - write_cb(cbopaque, "\n"); - - if ((err = JEMALLOC_P(mallctl)("arenas.tspace_min", &sv, &ssz, - NULL, 0)) == 0) { - write_cb(cbopaque, "Tiny 2^n-spaced sizes: ["); - write_cb(cbopaque, umax2s(sv, 10, s)); - write_cb(cbopaque, ".."); - - CTL_GET("arenas.tspace_max", &sv, size_t); - write_cb(cbopaque, umax2s(sv, 10, s)); - write_cb(cbopaque, "]\n"); - } - - CTL_GET("arenas.qspace_min", &sv, size_t); - write_cb(cbopaque, "Quantum-spaced sizes: ["); - write_cb(cbopaque, umax2s(sv, 10, s)); - write_cb(cbopaque, ".."); - CTL_GET("arenas.qspace_max", &sv, size_t); - write_cb(cbopaque, umax2s(sv, 10, s)); - write_cb(cbopaque, "]\n"); - - CTL_GET("arenas.cspace_min", &sv, size_t); - write_cb(cbopaque, "Cacheline-spaced sizes: ["); - write_cb(cbopaque, umax2s(sv, 10, s)); - write_cb(cbopaque, ".."); - CTL_GET("arenas.cspace_max", &sv, size_t); - write_cb(cbopaque, umax2s(sv, 10, s)); - write_cb(cbopaque, "]\n"); - - CTL_GET("arenas.sspace_min", &sv, size_t); - write_cb(cbopaque, "Subpage-spaced sizes: ["); - write_cb(cbopaque, umax2s(sv, 10, s)); - write_cb(cbopaque, ".."); - CTL_GET("arenas.sspace_max", &sv, size_t); - write_cb(cbopaque, umax2s(sv, 10, s)); - write_cb(cbopaque, "]\n"); - - CTL_GET("opt.lg_dirty_mult", &ssv, ssize_t); - if (ssv >= 0) { - write_cb(cbopaque, - "Min active:dirty page ratio per arena: "); - write_cb(cbopaque, umax2s((1U << ssv), 10, s)); - write_cb(cbopaque, ":1\n"); - } else { - write_cb(cbopaque, - "Min active:dirty page ratio per arena: N/A\n"); - } - if ((err = JEMALLOC_P(mallctl)("arenas.tcache_max", &sv, - &ssz, NULL, 0)) == 0) { - write_cb(cbopaque, - "Maximum thread-cached size class: "); - write_cb(cbopaque, umax2s(sv, 10, s)); - write_cb(cbopaque, "\n"); - } - if ((err = JEMALLOC_P(mallctl)("opt.lg_tcache_gc_sweep", &ssv, - &ssz, NULL, 0)) == 0) { - size_t tcache_gc_sweep = (1U << ssv); - bool tcache_enabled; - CTL_GET("opt.tcache", &tcache_enabled, bool); - write_cb(cbopaque, "Thread cache GC sweep interval: "); - write_cb(cbopaque, tcache_enabled && ssv >= 0 ? - umax2s(tcache_gc_sweep, 10, s) : "N/A"); - write_cb(cbopaque, "\n"); - } - if ((err = JEMALLOC_P(mallctl)("opt.prof", &bv, &bsz, NULL, 0)) - == 0 && bv) { - CTL_GET("opt.lg_prof_bt_max", &sv, size_t); - write_cb(cbopaque, "Maximum profile backtrace depth: "); - write_cb(cbopaque, umax2s((1U << sv), 10, s)); - write_cb(cbopaque, "\n"); - - CTL_GET("opt.lg_prof_sample", &sv, size_t); - write_cb(cbopaque, "Average profile sample interval: "); - write_cb(cbopaque, umax2s((1U << sv), 10, s)); - write_cb(cbopaque, " (2^"); - write_cb(cbopaque, umax2s(sv, 10, s)); - write_cb(cbopaque, ")\n"); - - CTL_GET("opt.lg_prof_interval", &ssv, ssize_t); - write_cb(cbopaque, "Average profile dump interval: "); - if (ssv >= 0) { - write_cb(cbopaque, umax2s((1U << ssv), 10, s)); - write_cb(cbopaque, " (2^"); - write_cb(cbopaque, umax2s(ssv, 10, s)); - write_cb(cbopaque, ")\n"); - } else - write_cb(cbopaque, "N/A\n"); - } - CTL_GET("arenas.chunksize", &sv, size_t); - write_cb(cbopaque, "Chunk size: "); - write_cb(cbopaque, umax2s(sv, 10, s)); - CTL_GET("opt.lg_chunk", &sv, size_t); - write_cb(cbopaque, " (2^"); - write_cb(cbopaque, umax2s(sv, 10, s)); - write_cb(cbopaque, ")\n"); - } - -#ifdef JEMALLOC_STATS - { - int err; - size_t ssz; - size_t allocated, active, mapped; - size_t chunks_current, chunks_high, swap_avail; - uint64_t chunks_total; - size_t huge_allocated; - uint64_t huge_nmalloc, huge_ndalloc; - - ssz = sizeof(size_t); - - CTL_GET("stats.allocated", &allocated, size_t); - CTL_GET("stats.active", &active, size_t); - CTL_GET("stats.mapped", &mapped, size_t); - malloc_cprintf(write_cb, cbopaque, - "Allocated: %zu, active: %zu, mapped: %zu\n", allocated, - active, mapped); - - /* Print chunk stats. */ - CTL_GET("stats.chunks.total", &chunks_total, uint64_t); - CTL_GET("stats.chunks.high", &chunks_high, size_t); - CTL_GET("stats.chunks.current", &chunks_current, size_t); - if ((err = JEMALLOC_P(mallctl)("swap.avail", &swap_avail, &ssz, - NULL, 0)) == 0) { - size_t lg_chunk; - - malloc_cprintf(write_cb, cbopaque, "chunks: nchunks " - "highchunks curchunks swap_avail\n"); - CTL_GET("opt.lg_chunk", &lg_chunk, size_t); - malloc_cprintf(write_cb, cbopaque, - " %13"PRIu64"%13zu%13zu%13zu\n", - chunks_total, chunks_high, chunks_current, - swap_avail << lg_chunk); - } else { - malloc_cprintf(write_cb, cbopaque, "chunks: nchunks " - "highchunks curchunks\n"); - malloc_cprintf(write_cb, cbopaque, - " %13"PRIu64"%13zu%13zu\n", - chunks_total, chunks_high, chunks_current); - } - - /* Print huge stats. */ - CTL_GET("stats.huge.nmalloc", &huge_nmalloc, uint64_t); - CTL_GET("stats.huge.ndalloc", &huge_ndalloc, uint64_t); - CTL_GET("stats.huge.allocated", &huge_allocated, size_t); - malloc_cprintf(write_cb, cbopaque, - "huge: nmalloc ndalloc allocated\n"); - malloc_cprintf(write_cb, cbopaque, - " %12"PRIu64" %12"PRIu64" %12zu\n", - huge_nmalloc, huge_ndalloc, huge_allocated); - - if (merged) { - unsigned narenas; - - CTL_GET("arenas.narenas", &narenas, unsigned); - { - bool initialized[narenas]; - size_t isz; - unsigned i, ninitialized; - - isz = sizeof(initialized); - xmallctl("arenas.initialized", initialized, - &isz, NULL, 0); - for (i = ninitialized = 0; i < narenas; i++) { - if (initialized[i]) - ninitialized++; - } - - if (ninitialized > 1) { - /* Print merged arena stats. */ - malloc_cprintf(write_cb, cbopaque, - "\nMerged arenas stats:\n"); - stats_arena_print(write_cb, cbopaque, - narenas); - } - } - } - - if (unmerged) { - unsigned narenas; - - /* Print stats for each arena. */ - - CTL_GET("arenas.narenas", &narenas, unsigned); - { - bool initialized[narenas]; - size_t isz; - unsigned i; - - isz = sizeof(initialized); - xmallctl("arenas.initialized", initialized, - &isz, NULL, 0); - - for (i = 0; i < narenas; i++) { - if (initialized[i]) { - malloc_cprintf(write_cb, - cbopaque, - "\narenas[%u]:\n", i); - stats_arena_print(write_cb, - cbopaque, i); - } - } - } - } - } -#endif /* #ifdef JEMALLOC_STATS */ - write_cb(cbopaque, "--- End jemalloc statistics ---\n"); -} diff --git a/externals/jemalloc/tcache.c b/externals/jemalloc/tcache.c deleted file mode 100644 index ce6ec996159..00000000000 --- a/externals/jemalloc/tcache.c +++ /dev/null @@ -1,403 +0,0 @@ -#define JEMALLOC_TCACHE_C_ -#include "jemalloc/internal/jemalloc_internal.h" -#ifdef JEMALLOC_TCACHE -/******************************************************************************/ -/* Data. */ - -bool opt_tcache = true; -ssize_t opt_lg_tcache_maxclass = LG_TCACHE_MAXCLASS_DEFAULT; -ssize_t opt_lg_tcache_gc_sweep = LG_TCACHE_GC_SWEEP_DEFAULT; - -/* Map of thread-specific caches. */ -__thread tcache_t *tcache_tls JEMALLOC_ATTR(tls_model("initial-exec")); - -/* - * Same contents as tcache, but initialized such that the TSD destructor is - * called when a thread exits, so that the cache can be cleaned up. - */ -static pthread_key_t tcache_tsd; - -size_t nhbins; -size_t tcache_maxclass; -unsigned tcache_gc_incr; - -/******************************************************************************/ -/* Function prototypes for non-inline static functions. */ - -static void tcache_thread_cleanup(void *arg); - -/******************************************************************************/ - -void * -tcache_alloc_small_hard(tcache_t *tcache, tcache_bin_t *tbin, size_t binind) -{ - void *ret; - - arena_tcache_fill_small(tcache->arena, tbin, binind -#ifdef JEMALLOC_PROF - , tcache->prof_accumbytes -#endif - ); -#ifdef JEMALLOC_PROF - tcache->prof_accumbytes = 0; -#endif - ret = tcache_alloc_easy(tbin); - - return (ret); -} - -void -tcache_bin_flush_small(tcache_bin_t *tbin, size_t binind, unsigned rem -#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) - , tcache_t *tcache -#endif - ) -{ - void *flush, *deferred, *ptr; - unsigned i, nflush, ndeferred; - - assert(binind < nbins); - assert(rem <= tbin->ncached); - - for (flush = tbin->avail, nflush = tbin->ncached - rem; flush != NULL; - flush = deferred, nflush = ndeferred) { - /* Lock the arena bin associated with the first object. */ - arena_chunk_t *chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(flush); - arena_t *arena = chunk->arena; - arena_bin_t *bin = &arena->bins[binind]; - -#ifdef JEMALLOC_PROF - if (arena == tcache->arena) { - malloc_mutex_lock(&arena->lock); - arena_prof_accum(arena, tcache->prof_accumbytes); - malloc_mutex_unlock(&arena->lock); - tcache->prof_accumbytes = 0; - } -#endif - - malloc_mutex_lock(&bin->lock); -#ifdef JEMALLOC_STATS - if (arena == tcache->arena) { - bin->stats.nflushes++; - bin->stats.nrequests += tbin->tstats.nrequests; - tbin->tstats.nrequests = 0; - } -#endif - deferred = NULL; - ndeferred = 0; - for (i = 0; i < nflush; i++) { - ptr = flush; - assert(ptr != NULL); - flush = *(void **)ptr; - chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); - if (chunk->arena == arena) { - size_t pageind = (((uintptr_t)ptr - - (uintptr_t)chunk) >> PAGE_SHIFT); - arena_chunk_map_t *mapelm = - &chunk->map[pageind]; - arena_dalloc_bin(arena, chunk, ptr, mapelm); - } else { - /* - * This object was allocated via a different - * arena bin than the one that is currently - * locked. Stash the object, so that it can be - * handled in a future pass. - */ - *(void **)ptr = deferred; - deferred = ptr; - ndeferred++; - } - } - malloc_mutex_unlock(&bin->lock); - - if (flush != NULL) { - /* - * This was the first pass, and rem cached objects - * remain. - */ - tbin->avail = flush; - } - } - - tbin->ncached = rem; - if (tbin->ncached < tbin->low_water) - tbin->low_water = tbin->ncached; -} - -void -tcache_bin_flush_large(tcache_bin_t *tbin, size_t binind, unsigned rem -#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) - , tcache_t *tcache -#endif - ) -{ - void *flush, *deferred, *ptr; - unsigned i, nflush, ndeferred; - - assert(binind < nhbins); - assert(rem <= tbin->ncached); - - for (flush = tbin->avail, nflush = tbin->ncached - rem; flush != NULL; - flush = deferred, nflush = ndeferred) { - /* Lock the arena associated with the first object. */ - arena_chunk_t *chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(flush); - arena_t *arena = chunk->arena; - - malloc_mutex_lock(&arena->lock); -#if (defined(JEMALLOC_PROF) || defined(JEMALLOC_STATS)) - if (arena == tcache->arena) { -#endif -#ifdef JEMALLOC_PROF - arena_prof_accum(arena, tcache->prof_accumbytes); - tcache->prof_accumbytes = 0; -#endif -#ifdef JEMALLOC_STATS - arena->stats.nrequests_large += tbin->tstats.nrequests; - arena->stats.lstats[binind - nbins].nrequests += - tbin->tstats.nrequests; - tbin->tstats.nrequests = 0; -#endif -#if (defined(JEMALLOC_PROF) || defined(JEMALLOC_STATS)) - } -#endif - deferred = NULL; - ndeferred = 0; - for (i = 0; i < nflush; i++) { - ptr = flush; - assert(ptr != NULL); - flush = *(void **)ptr; - chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr); - if (chunk->arena == arena) - arena_dalloc_large(arena, chunk, ptr); - else { - /* - * This object was allocated via a different - * arena than the one that is currently locked. - * Stash the object, so that it can be handled - * in a future pass. - */ - *(void **)ptr = deferred; - deferred = ptr; - ndeferred++; - } - } - malloc_mutex_unlock(&arena->lock); - - if (flush != NULL) { - /* - * This was the first pass, and rem cached objects - * remain. - */ - tbin->avail = flush; - } - } - - tbin->ncached = rem; - if (tbin->ncached < tbin->low_water) - tbin->low_water = tbin->ncached; -} - -tcache_t * -tcache_create(arena_t *arena) -{ - tcache_t *tcache; - size_t size; - unsigned i; - - size = sizeof(tcache_t) + (sizeof(tcache_bin_t) * (nhbins - 1)); - /* - * Round up to the nearest multiple of the cacheline size, in order to - * avoid the possibility of false cacheline sharing. - * - * That this works relies on the same logic as in ipalloc(). - */ - size = (size + CACHELINE_MASK) & (-CACHELINE); - - if (size <= small_maxclass) - tcache = (tcache_t *)arena_malloc_small(arena, size, true); - else - tcache = (tcache_t *)icalloc(size); - - if (tcache == NULL) - return (NULL); - -#ifdef JEMALLOC_STATS - /* Link into list of extant tcaches. */ - malloc_mutex_lock(&arena->lock); - ql_elm_new(tcache, link); - ql_tail_insert(&arena->tcache_ql, tcache, link); - malloc_mutex_unlock(&arena->lock); -#endif - - tcache->arena = arena; - assert((TCACHE_NSLOTS_SMALL_MAX & 1U) == 0); - for (i = 0; i < nbins; i++) { - if ((arena->bins[i].nregs << 1) <= TCACHE_NSLOTS_SMALL_MAX) { - tcache->tbins[i].ncached_max = (arena->bins[i].nregs << - 1); - } else - tcache->tbins[i].ncached_max = TCACHE_NSLOTS_SMALL_MAX; - } - for (; i < nhbins; i++) - tcache->tbins[i].ncached_max = TCACHE_NSLOTS_LARGE; - - tcache_tls = tcache; - pthread_setspecific(tcache_tsd, tcache); - - return (tcache); -} - -void -tcache_destroy(tcache_t *tcache) -{ - unsigned i; - -#ifdef JEMALLOC_STATS - /* Unlink from list of extant tcaches. */ - malloc_mutex_lock(&tcache->arena->lock); - ql_remove(&tcache->arena->tcache_ql, tcache, link); - malloc_mutex_unlock(&tcache->arena->lock); - tcache_stats_merge(tcache, tcache->arena); -#endif - - for (i = 0; i < nbins; i++) { - tcache_bin_t *tbin = &tcache->tbins[i]; - tcache_bin_flush_small(tbin, i, 0 -#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) - , tcache -#endif - ); - -#ifdef JEMALLOC_STATS - if (tbin->tstats.nrequests != 0) { - arena_t *arena = tcache->arena; - arena_bin_t *bin = &arena->bins[i]; - malloc_mutex_lock(&bin->lock); - bin->stats.nrequests += tbin->tstats.nrequests; - malloc_mutex_unlock(&bin->lock); - } -#endif - } - - for (; i < nhbins; i++) { - tcache_bin_t *tbin = &tcache->tbins[i]; - tcache_bin_flush_large(tbin, i, 0 -#if (defined(JEMALLOC_STATS) || defined(JEMALLOC_PROF)) - , tcache -#endif - ); - -#ifdef JEMALLOC_STATS - if (tbin->tstats.nrequests != 0) { - arena_t *arena = tcache->arena; - malloc_mutex_lock(&arena->lock); - arena->stats.nrequests_large += tbin->tstats.nrequests; - arena->stats.lstats[i - nbins].nrequests += - tbin->tstats.nrequests; - malloc_mutex_unlock(&arena->lock); - } -#endif - } - -#ifdef JEMALLOC_PROF - if (tcache->prof_accumbytes > 0) { - malloc_mutex_lock(&tcache->arena->lock); - arena_prof_accum(tcache->arena, tcache->prof_accumbytes); - malloc_mutex_unlock(&tcache->arena->lock); - } -#endif - - if (arena_salloc(tcache) <= small_maxclass) { - arena_chunk_t *chunk = CHUNK_ADDR2BASE(tcache); - arena_t *arena = chunk->arena; - size_t pageind = (((uintptr_t)tcache - (uintptr_t)chunk) >> - PAGE_SHIFT); - arena_chunk_map_t *mapelm = &chunk->map[pageind]; - arena_run_t *run = (arena_run_t *)((uintptr_t)chunk + - (uintptr_t)((pageind - (mapelm->bits >> PAGE_SHIFT)) << - PAGE_SHIFT)); - arena_bin_t *bin = run->bin; - - malloc_mutex_lock(&bin->lock); - arena_dalloc_bin(arena, chunk, tcache, mapelm); - malloc_mutex_unlock(&bin->lock); - } else - idalloc(tcache); -} - -static void -tcache_thread_cleanup(void *arg) -{ - tcache_t *tcache = (tcache_t *)arg; - - assert(tcache == tcache_tls); - if (tcache != NULL) { - assert(tcache != (void *)(uintptr_t)1); - tcache_destroy(tcache); - tcache_tls = (void *)(uintptr_t)1; - } -} - -#ifdef JEMALLOC_STATS -void -tcache_stats_merge(tcache_t *tcache, arena_t *arena) -{ - unsigned i; - - /* Merge and reset tcache stats. */ - for (i = 0; i < nbins; i++) { - arena_bin_t *bin = &arena->bins[i]; - tcache_bin_t *tbin = &tcache->tbins[i]; - malloc_mutex_lock(&bin->lock); - bin->stats.nrequests += tbin->tstats.nrequests; - malloc_mutex_unlock(&bin->lock); - tbin->tstats.nrequests = 0; - } - - for (; i < nhbins; i++) { - malloc_large_stats_t *lstats = &arena->stats.lstats[i - nbins]; - tcache_bin_t *tbin = &tcache->tbins[i]; - arena->stats.nrequests_large += tbin->tstats.nrequests; - lstats->nrequests += tbin->tstats.nrequests; - tbin->tstats.nrequests = 0; - } -} -#endif - -void -tcache_boot(void) -{ - - if (opt_tcache) { - /* - * If necessary, clamp opt_lg_tcache_maxclass, now that - * small_maxclass and arena_maxclass are known. - */ - if (opt_lg_tcache_maxclass < 0 || (1U << - opt_lg_tcache_maxclass) < small_maxclass) - tcache_maxclass = small_maxclass; - else if ((1U << opt_lg_tcache_maxclass) > arena_maxclass) - tcache_maxclass = arena_maxclass; - else - tcache_maxclass = (1U << opt_lg_tcache_maxclass); - - nhbins = nbins + (tcache_maxclass >> PAGE_SHIFT); - - /* Compute incremental GC event threshold. */ - if (opt_lg_tcache_gc_sweep >= 0) { - tcache_gc_incr = ((1U << opt_lg_tcache_gc_sweep) / - nbins) + (((1U << opt_lg_tcache_gc_sweep) % nbins == - 0) ? 0 : 1); - } else - tcache_gc_incr = 0; - - if (pthread_key_create(&tcache_tsd, tcache_thread_cleanup) != - 0) { - malloc_write( - ": Error in pthread_key_create()\n"); - abort(); - } - } -} -/******************************************************************************/ -#endif /* JEMALLOC_TCACHE */ diff --git a/externals/libmpq/AUTHORS b/externals/libmpq/AUTHORS deleted file mode 100644 index 3d7da7bec9a..00000000000 --- a/externals/libmpq/AUTHORS +++ /dev/null @@ -1,10 +0,0 @@ -Project Initiator: - - * Maik Broemme - -Developers: - - * Maik Broemme - * Tilman Sauerbeck - * Forrest Voight - * Georg Lukas diff --git a/externals/libmpq/CMakeLists.txt b/externals/libmpq/CMakeLists.txt deleted file mode 100644 index 2a0da915171..00000000000 --- a/externals/libmpq/CMakeLists.txt +++ /dev/null @@ -1,34 +0,0 @@ -# Copyright (C) 2008-2010 Trinity -# -# This file is free software; as a special exception the author gives -# unlimited permission to copy and/or distribute it, with or without -# modifications, as long as this notice is preserved. -# -# This program is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the -# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -file(GLOB sources_mpq libmpq/*.c libmpq/*.h) - -set(mpq_STAT_SRCS - ${sources_mpq} -) - -if( UNIX ) - include_directories( - ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_SOURCE_DIR}/externals/zlib - ${CMAKE_SOURCE_DIR}/externals/bzip2 - ) -elseif( WIN32 ) - include_directories( - ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_CURRENT_SOURCE_DIR}/win - ${CMAKE_SOURCE_DIR}/externals/zlib - ${CMAKE_SOURCE_DIR}/externals/bzip2 - ) -endif() - -add_library(mpq STATIC ${mpq_STAT_SRCS}) - -set_target_properties(mpq PROPERTIES LINKER_LANGUAGE CXX) diff --git a/externals/libmpq/COPYING b/externals/libmpq/COPYING deleted file mode 100644 index 4189933be9f..00000000000 --- a/externals/libmpq/COPYING +++ /dev/null @@ -1,339 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc. - 59 Temple Place, Suite 330, Boston, MA 02111 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Library General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - Appendix: How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) 19yy - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) 19yy name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Library General -Public License instead of this License. diff --git a/externals/libmpq/FAQ b/externals/libmpq/FAQ deleted file mode 100644 index 52ca9f3c705..00000000000 --- a/externals/libmpq/FAQ +++ /dev/null @@ -1,68 +0,0 @@ -FAQ - Frequently Asked Questions -================================ - -Q: What is libmpq? -A: libmpq is a library for manipulating MoPaQ mpq archives mostly used - used by Blizzard in their games. - -Q: What can i do with libmpq? -A: With libmpq you can write applications which can extract, create - and manipulate mpq archives. - -Q: Is it legal? -A: Yes, i think so. I have no idea why it should not, all informations - about the fileformat are available. - -Q: Is there a description of the functions? -A: Since version 0.4.0 libmpq comes with a API documentation for - developers. The documentation is written as manual pages. - -Q: Can i help? -A: Yes, help is needed, not only with developing, also with testing. - A good point to start is using a recent SVN version of libmpq and - trying to use it with every mpq archive you could get :) - -Q: Can you give a small example to demonstrate the usage? -A: Of course :) The example below takes first parameter as mpq archive - and extracts the first file to a buffer. - - /* - * Compile with: - * - * x86_32: - * - * gcc \ - * -D_FILE_OFFSET_BITS=64 \ - * -D_LARGE_FILES=1 \ - * -D_LARGEFILE_SOURCE=1 \ - * mpq-example.c -o mpq-example -lmpq -lz -lbz2 -I/usr/local/include/libmpq - * - * x86_64: - * - * gcc \ - * -D_LARGE_FILES=1 \ - * mpq-example.c -o mpq-example -lmpq -lz -lbz2 -I/usr/local/include/libmpq - */ - - #include - #include - #include - - int main(int argc, char **argv) { - mpq_archive_s *mpq_archive; - off_t out_size; - char *out_buf; - - /* open the mpq archive given as first parameter. */ - libmpq__archive_open(&mpq_archive, argv[1], -1); - - /* get size of first file (0) and malloc output buffer. */ - libmpq__file_unpacked_size(mpq_archive, 0, &out_size); - out_buf = malloc(out_size); - - /* read, decrypt and unpack file to output buffer. */ - libmpq__file_read(mpq_archive, 0, out_buf, out_size, NULL); - - /* close the mpq archive. */ - libmpq__archive_close(mpq_archive); - } diff --git a/externals/libmpq/INSTALL b/externals/libmpq/INSTALL deleted file mode 100644 index b42a17ac464..00000000000 --- a/externals/libmpq/INSTALL +++ /dev/null @@ -1,182 +0,0 @@ -Basic Installation -================== - - These are generic installation instructions. - - 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, a file -`config.cache' that saves the results of its tests to speed up -reconfiguring, and a file `config.log' containing compiler output -(useful mainly for debugging `configure'). - - 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' so they can -be considered for the next release. If at some point `config.cache' -contains results you don't want to keep, you may remove or edit it. - - The file `configure.in' is used to create `configure' by a program -called `autoconf'. You only need `configure.in' 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. If you're - using `csh' on an old version of System V, you might need to type - `sh ./configure' instead to prevent `csh' from trying to execute - `configure' itself. - - Running `configure' takes awhile. 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. - -Compilers and Options -===================== - - Some systems require unusual options for compilation or linking that -the `configure' script does not know about. You can give `configure' -initial values for variables by setting them in the environment. Using -a Bourne-compatible shell, you can do that on the command line like -this: - CC=c89 CFLAGS=-O2 LIBS=-lposix ./configure - -Or on systems that have the `env' program, you can do it like this: - env CPPFLAGS=-I/usr/local/include LDFLAGS=-s ./configure - -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 must use a version of `make' that -supports the `VPATH' variable, such as 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 `..'. - - If you have to use a `make' that does not supports the `VPATH' -variable, you have 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' will install the package's files in -`/usr/local/bin', `/usr/local/man', etc. You can specify an -installation prefix other than `/usr/local' by giving `configure' the -option `--prefix=PATH'. - - You can specify separate installation prefixes for -architecture-specific files and architecture-independent files. If you -give `configure' the option `--exec-prefix=PATH', the package will use -PATH as the prefix for installing programs and libraries. -Documentation and other data files will still use the regular prefix. - - In addition, if you use an unusual directory layout you can give -options like `--bindir=PATH' 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' 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' can not figure out -automatically, but needs to determine by the type of host the package -will run on. Usually `configure' can figure that out, but if it prints -a message saying it can not guess the host type, give it the -`--host=TYPE' option. TYPE can either be a short name for the system -type, such as `sun4', or a canonical name with three fields: - CPU-COMPANY-SYSTEM - -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 host type. - - If you are building compiler tools for cross-compiling, you can also -use the `--target=TYPE' option to select the type of system they will -produce code for and the `--build=TYPE' option to select the type of -system on which you are compiling the package. - -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. - -Operation Controls -================== - - `configure' recognizes the following options to control how it -operates. - -`--cache-file=FILE' - Use and save the results of the tests in FILE instead of - `./config.cache'. Set FILE to `/dev/null' to disable caching, for - debugging `configure'. - -`--help' - Print a summary of the options to `configure', and exit. - -`--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. - -`--version' - Print the version of Autoconf used to generate the `configure' - script, and exit. - -`configure' also accepts some other, not widely useful, options. diff --git a/externals/libmpq/Makefile.am b/externals/libmpq/Makefile.am deleted file mode 100644 index 0a9b54c2526..00000000000 --- a/externals/libmpq/Makefile.am +++ /dev/null @@ -1,26 +0,0 @@ -# minimum required automake 1.6 -AUTOMAKE_OPTIONS = 1.6 - -# any directories which should be built and installed. -SUBDIRS = libmpq bindings doc - -# the directories which are part of the distribution. -DIST_SUBDIRS = $(SUBDIRS) - -# libmpq runtime configuration script. -bin_SCRIPTS = libmpq-config - -# pkg-config installation directory. -pkgconfigdir = $(libdir)/pkgconfig -pkgconfig_DATA = libmpq.pc - -# extra stuff. -EXTRA_DIST = \ - AUTHORS \ - COPYING \ - FAQ \ - INSTALL \ - NEWS \ - README \ - THANKS \ - TODO diff --git a/externals/libmpq/NEWS b/externals/libmpq/NEWS deleted file mode 100644 index 74850a8a5bb..00000000000 --- a/externals/libmpq/NEWS +++ /dev/null @@ -1,76 +0,0 @@ -Changes version 0.4.2 (2008-05-16) -================================== - - * added full extraction support for protected maps used in - warcraft 3. - - * added full extraction support for all blizzard titles until - world of warcraft - the burning crusade. - - * added support for archives version 2 with extended header and - extended block table. - - * added support for the bzip2 compression algorithm. - - * added support for archives and files inside archive > 2gb. - - * added generic read functions, which will do decryption, - decompression or exploding. - - * the info functions are no longer exported by the library and - were replaced by separate api functions. - - * the file number and block number are count from 0 instead - of 1. - - * added python bindings. - - * linking against libmpq requires from now on the usual largefile - macros -D_FILE_OFFSET_BITS=64 -D_LARGE_FILES=1 -D_LARGEFILE_SOURCE=1 - -Changes version 0.4.1 (2008-04-02) -================================== - - * memory, speed and stability improvements. - - * split sourcecode into library and utility package. - -Changes version 0.4.0 (2008-03-31) -================================== - - * added robust error handling to make the library and extracting - utility more stable. - - * added c++ bindings to public include and moved internal defines - and functions to private include. - - * added support for 64-bit architectures and removed any stupid - pointer to int arithmetics. - - * added much better member names to the structures to make - developers able to understand the code on reading. - - * added full api documentation using manual pages. - - * added full extraction support for all blizzard titles until - warcraft 3 - the frozen throne. - - * added support for single sector and stored files (neither - compressed nor imploded). - - * added support for files which have compressed size greater than - uncompressed size. - - * removed the external listfile database support from 0.3.0 it - was a weird implementation. - -Changes version 0.3.0 (2004-02-12) -================================== - - * added listfile database support from external files. - -Initial version 0.2.1 (2004-01-17) -================================== - - * first version which was able to extract some of the older mopaq - archives. diff --git a/externals/libmpq/README b/externals/libmpq/README deleted file mode 100644 index 3f1bd3a1e9f..00000000000 --- a/externals/libmpq/README +++ /dev/null @@ -1,34 +0,0 @@ -Introduction -============ - -'libmpq' is a library which can be easily used in own applications -to extract, create or manipulate MoPaQ mpq archives. - -MPQ, or MoPaQ, is a proprietary archive format created by -Mike O'Brien, the man hailed as Blizzard's multiplayer engine -genius, back in 1996 as a general purpose archive for use with -Diablo, and named narcissistically for its creator -"Mike O'brien PaCK". The copyrights to it, however, are held by -Havas Interactive, Blizzard's parent company. The archive format -is used by many Blizzard titles like Diablo, Diablo 2, Starcraft, -Warcraft 2: BNE, a newer version in Warcraft 3 and World of -Warcraft (WoW). - -Manual -====== - -Since version 0.4.0 the 'libmpq' package comes with a manpage for -every library function. If you use 'libmpq' first time it is a good -idea to read the `FAQ' file. - -Reporting Bugs -============== - -Bug reports for 'libmpq' can be send to me directly. - - * Maik Broemme - -Enjoy! - -Maik Broemme -http://www.babelize.org/ diff --git a/externals/libmpq/THANKS b/externals/libmpq/THANKS deleted file mode 100644 index 42da1235476..00000000000 --- a/externals/libmpq/THANKS +++ /dev/null @@ -1,21 +0,0 @@ -'libmpq' was originaly created by Maik Broemme -and i want to thank some people which helped by supplying knowledge, code or -something else. - - * Romy Trompke - - my lovely girlfriend for her patience - - * Ladislav Zezula - - stormlib creator - - * Marko Friedemann - - initial port of stormlib to linux - - * Tom Amigo - - first people who decrypts the MoPaQ archive format - - * ShadowFlare - - creator of the ShadowFlare MPQ API - - * Justin Olbrantz (Quantam) - - creator of the client using ShadowFlare MPQ API diff --git a/externals/libmpq/TODO b/externals/libmpq/TODO deleted file mode 100644 index 0c1951f0b46..00000000000 --- a/externals/libmpq/TODO +++ /dev/null @@ -1,10 +0,0 @@ -Features and functionality which should be added in the future. - - * Porting for big endian systems. - * Porting for Windows? :) - * Creating mpq archives. - * Brute all unknown filenames, Blizzard uses in their - archives. - -Look at the AUTHORS file if you want help me with 'libmpq', or -if you have other interesting features which should be added. diff --git a/externals/libmpq/autogen.sh b/externals/libmpq/autogen.sh deleted file mode 100644 index 16871edd70d..00000000000 --- a/externals/libmpq/autogen.sh +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/sh -# -echo "Generating build information using aclocal, autoheader, automake and autoconf" -echo "This may take a while ..." - -# Touch the timestamps on all the files since CVS messes them up -directory=`dirname $0` -touch $directory/configure.ac - -# Regenerate configuration files -libtoolize --copy -aclocal -autoheader -automake --foreign --add-missing --copy -autoconf - -# Run configure for this platform -#./configure $* -echo "Now you are ready to run ./configure" diff --git a/externals/libmpq/bindings/Makefile.am b/externals/libmpq/bindings/Makefile.am deleted file mode 100644 index b9fefe306ef..00000000000 --- a/externals/libmpq/bindings/Makefile.am +++ /dev/null @@ -1,6 +0,0 @@ -# any directories which should be built and installed. -SUBDIRS = d - -if HAVE_PYTHON -SUBDIRS += python -endif diff --git a/externals/libmpq/bindings/d/Makefile.am b/externals/libmpq/bindings/d/Makefile.am deleted file mode 100644 index 4de7285ae51..00000000000 --- a/externals/libmpq/bindings/d/Makefile.am +++ /dev/null @@ -1,6 +0,0 @@ -# minimum required automake 1.6 -AUTOMAKE_OPTIONS = 1.6 - -# install D binding to /usr/include/d by default -libmpq_includedir = $(includedir)/d -libmpq_include_HEADERS = mpq.d diff --git a/externals/libmpq/bindings/d/dsss.conf b/externals/libmpq/bindings/d/dsss.conf deleted file mode 100644 index 252482c4933..00000000000 --- a/externals/libmpq/bindings/d/dsss.conf +++ /dev/null @@ -1,2 +0,0 @@ -[mpq.d] -type=sourcelibrary diff --git a/externals/libmpq/bindings/d/mpq.d b/externals/libmpq/bindings/d/mpq.d deleted file mode 100644 index d72c2d2a986..00000000000 --- a/externals/libmpq/bindings/d/mpq.d +++ /dev/null @@ -1,318 +0,0 @@ -/* - * mpq.d -- D programming language module for libmpq - * - * Copyright (c) 2008 Georg Lukas - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * - * This module is written to support Phobos. Patches to allow binding to - * Tango are welcome. - */ - -module mpq; - -/* the following pragma does not work on DMD/Linux, generates a warning on - * GDC/Linux and has not been tested on Windows. Commented out for now. */ -// pragma(lib, "libmpq"); - -import std.string; // for format() and toStringz() -import std.traits; // for ParameterTypeTuple!() - -/* XXX: this assumes that libmpq is compiled with Large File Support on */ -alias long off_t; - -/* libmpq error return values */ -const LIBMPQ_ERROR_OPEN = -1; /* open error on file. */ -const LIBMPQ_ERROR_CLOSE = -2; /* close error on file. */ -const LIBMPQ_ERROR_SEEK = -3; /* lseek error on file. */ -const LIBMPQ_ERROR_READ = -4; /* read error on file. */ -const LIBMPQ_ERROR_WRITE = -5; /* write error on file. */ -const LIBMPQ_ERROR_MALLOC = -6; /* memory allocation error. */ -const LIBMPQ_ERROR_FORMAT = -7; /* format errror. */ -const LIBMPQ_ERROR_NOT_INITIALIZED = -8; /* init() wasn't called. */ -const LIBMPQ_ERROR_SIZE = -9; /* buffer size is to small. */ -const LIBMPQ_ERROR_EXIST = -10; /* file or block does not exist in archive. */ -const LIBMPQ_ERROR_DECRYPT = -11; /* we don't know the decryption seed. */ -const LIBMPQ_ERROR_UNPACK = -12; /* error on unpacking file. */ - -/** libmpq internal meta-data for an archive */ -extern struct mpq_archive_s; - -extern(C) { - -/* libmpq__generic information about library. */ -char *libmpq__version(); - -/* libmpq__generic mpq archive information. */ -int libmpq__archive_open(mpq_archive_s **mpq_archive, char *mpq_filename, off_t archive_offset); -int libmpq__archive_close(mpq_archive_s *mpq_archive); -int libmpq__archive_packed_size(mpq_archive_s *mpq_archive, off_t *packed_size); -int libmpq__archive_unpacked_size(mpq_archive_s *mpq_archive, off_t *unpacked_size); -int libmpq__archive_offset(mpq_archive_s *mpq_archive, off_t *offset); -int libmpq__archive_version(mpq_archive_s *mpq_archive, uint *version_); -int libmpq__archive_files(mpq_archive_s *mpq_archive, uint *files); - -/* libmpq__generic file processing functions. */ -int libmpq__file_packed_size(mpq_archive_s *mpq_archive, uint file_number, off_t *packed_size); -int libmpq__file_unpacked_size(mpq_archive_s *mpq_archive, uint file_number, off_t *unpacked_size); -int libmpq__file_offset(mpq_archive_s *mpq_archive, uint file_number, off_t *offset); -int libmpq__file_blocks(mpq_archive_s *mpq_archive, uint file_number, uint *blocks); -int libmpq__file_encrypted(mpq_archive_s *mpq_archive, uint file_number, uint *encrypted); -int libmpq__file_compressed(mpq_archive_s *mpq_archive, uint file_number, uint *compressed); -int libmpq__file_imploded(mpq_archive_s *mpq_archive, uint file_number, uint *imploded); -int libmpq__file_number(mpq_archive_s *mpq_archive, char *filename, uint *number); -int libmpq__file_read(mpq_archive_s *mpq_archive, uint file_number, ubyte *out_buf, off_t out_size, off_t *transferred); - -/* libmpq__generic block processing functions. */ -int libmpq__block_open_offset(mpq_archive_s *mpq_archive, uint file_number); -int libmpq__block_close_offset(mpq_archive_s *mpq_archive, uint file_number); -int libmpq__block_unpacked_size(mpq_archive_s *mpq_archive, uint file_number, uint block_number, off_t *unpacked_size); -int libmpq__block_read(mpq_archive_s *mpq_archive, uint file_number, uint block_number, ubyte *out_buf, off_t out_size, off_t *transferred); - -} - - -/** exception class for failed libmpq calls */ -class MPQException : Exception { - const string[] Errors = [ - "unknown error", - "open error on file", - "close error on file", - "lseek error on file", - "read error on file", - "write error on file", - "memory allocation error", - "format errror", - "init() wasn't called", - "buffer size is to small", - "file or block does not exist in archive", - "we don't know the decryption seed", - "error on unpacking file"]; - - public int errno; - this(char[] fnname = "unknown_function", int errno = 0) { - - this.errno = errno; - if (-errno >= Errors.length) - errno = 0; - super(std.string.format("Error in %s(): %s (%d)", - fnname, Errors[-errno], errno)); - } -} - - -/** template to wrap function calls and throw exceptions in case of error - * - * thanks for the idea to while(nan) blog, - * http://while-nan.blogspot.com/2007/06/wrapping-functions-for-fun-and-profit.html - * - * use: MPQ_CHECKERR(libmpq__archive_open)(&m, "foo.mpq", -1); - * returns the retval of archive_open on success; - * throws an MPQException on failure. - * - * @param Fn libmpq__function reference - * @param args libmpq__function parameters - * @return return value of libmpq__function on success - * @throw MPQException on error - */ -int MPQ_CHECKERR(alias Fn)(ParameterTypeTuple!(Fn) args) -{ - int result = Fn(args); - if (result < 0) { - /* XXX: relying on non-specified stringof() behaviour */ - throw new MPQException((&Fn).stringof[2..$], result); - } - return result; -} - - -/** mixin alias to wrap library functions into MPQ_CHECKERR. - * - * alias mpq.func_name(...) to MPQ_CHECKERR(libmpq__func_name)(...) - * @param func_name name of the function to be wrapped - */ -template MPQ_FUNC(char[] func_name) { - const char[] MPQ_FUNC = "alias MPQ_CHECKERR!(libmpq__" ~ func_name ~ ") " ~ func_name ~ ";"; -} - -alias libmpq__version libversion; /* must be direct alias because it returns char*, not error int */ -mixin(MPQ_FUNC!("archive_open")); -mixin(MPQ_FUNC!("archive_close")); -mixin(MPQ_FUNC!("archive_packed_size")); -mixin(MPQ_FUNC!("archive_unpacked_size")); -mixin(MPQ_FUNC!("archive_offset")); -mixin(MPQ_FUNC!("archive_version")); -mixin(MPQ_FUNC!("archive_files")); -mixin(MPQ_FUNC!("file_packed_size")); -mixin(MPQ_FUNC!("file_unpacked_size")); -mixin(MPQ_FUNC!("file_offset")); -mixin(MPQ_FUNC!("file_blocks")); -mixin(MPQ_FUNC!("file_encrypted")); -mixin(MPQ_FUNC!("file_compressed")); -mixin(MPQ_FUNC!("file_imploded")); -mixin(MPQ_FUNC!("file_number")); -mixin(MPQ_FUNC!("file_read")); -mixin(MPQ_FUNC!("block_open_offset")); -mixin(MPQ_FUNC!("block_close_offset")); -mixin(MPQ_FUNC!("block_unpacked_size")); -mixin(MPQ_FUNC!("block_read")); - -/** getter function named name for returning archive_* single values: - * - * Archive.() { return libmpq__archive_() } - * - * @param type return type for the original function reference - * @param name name of the original function - * @param name2 name for the prototype (defaults to name, used for "version") - * @return getter function mixin - */ -template MPQ_A_GET(char[] type, char[] name, char[] name2 = name) { - const char[] MPQ_A_GET = type ~ " " ~ name2 ~ "() { " ~ - type ~ " ret; " ~ - "archive_" ~ name ~ "(m, &ret); return ret;" ~ - "}"; -} - -/** wrapper class for an MPQ Archive - * - * syntax: auto a = new mpq.Archive("somefile.mpq"); - */ -class Archive { - mpq_archive_s *m; - File listfile; - char[][] listfiledata; - - this(char[] archivename, off_t offset = -1) { - archive_open(&m, toStringz(archivename), offset); - } - - mixin(MPQ_A_GET!("off_t", "packed_size")); - mixin(MPQ_A_GET!("off_t", "unpacked_size")); - mixin(MPQ_A_GET!("off_t", "offset")); - mixin(MPQ_A_GET!("uint", "version", "version_")); - mixin(MPQ_A_GET!("uint", "files")); - - ~this() { - archive_close(m); - } - - mpq_archive_s* archive() { - return m; - } - - File opIndex(char[] fname) { - return new File(this, fname); - } - File opIndex(int fno) { - return new File(this, fno); - } - - char[][] filelist() { - try { - if (!listfile) { - listfile = this["(listfile)"]; - listfiledata = (cast(char[])listfile.read()).splitlines(); - } - return listfiledata; - } catch (MPQException e) { - return []; - } - } - - /+uint filenumber(char[] filename) { - try { - if (!listfile) { - listfile = this["(listfile)"]; - listfiledata = (cast(char[])listfile.read()).splitlines(); - } - return listfiledata; - } catch (MPQException e) { - return []; - } - }+/ - -} - - -/** getter function named name for returning file_* single values: - * - * File.() { return libmpq__file_() } - * - * @param type return type for the original function reference - * @param name name of the original function - * @param name2 name for the prototype (defaults to name, used for "version") - * @return getter function mixin - */ -template MPQ_F_GET(char[] type, char[] name, char[] name2 = name) { - const char[] MPQ_F_GET = type ~ " " ~ name2 ~ "() { " ~ - type ~ " ret; " ~ - "file_" ~ name ~ "(am, fileno, &ret); " ~ - "return ret;" ~ - "}"; -} - -/** wrapper class for a single file in an MPQ Archive - * - * syntax: - * auto a = new mpq.Archive("somefile.mpq"); - * auto f = a["(listfile)"]; - * auto f2 = a[0]; - * auto f3 = new File(a, "(listfile)"); - */ -class File { - Archive a; - mpq_archive_s* am; - char[] filename; - uint fileno; - - this(Archive a, int fileno) { - this.a = a; - this.am = a.archive(); - if (fileno >= a.files) { - throw new MPQException(format("File(%d)", fileno), - LIBMPQ_ERROR_EXIST); - } - this.filename = format("file%04d.xxx", fileno); - this.fileno = fileno; - } - - this(Archive a, char[] filename) { - this.a = a; - this.am = a.archive(); - this.filename = filename; - /* this line will throw an exception when the file is not there */ - mpq.file_number(am, toStringz(filename), &this.fileno); - } - - mixin(MPQ_F_GET!("off_t", "packed_size")); - mixin(MPQ_F_GET!("off_t", "unpacked_size")); - mixin(MPQ_F_GET!("off_t", "offset")); - mixin(MPQ_F_GET!("uint", "blocks")); - mixin(MPQ_F_GET!("uint", "encrypted")); - mixin(MPQ_F_GET!("uint", "compressed")); - mixin(MPQ_F_GET!("uint", "imploded")); - - uint no() { return fileno; } - char[] name() { return filename; } - - ubyte[] read() { - ubyte[] content; - content.length = this.unpacked_size(); - off_t trans; - mpq.file_read(am, fileno, content.ptr, content.length, &trans); - content.length = trans; - return content; - } -} diff --git a/externals/libmpq/bindings/python/Makefile.am b/externals/libmpq/bindings/python/Makefile.am deleted file mode 100644 index 6971a9b2f6d..00000000000 --- a/externals/libmpq/bindings/python/Makefile.am +++ /dev/null @@ -1,5 +0,0 @@ -# minimum required automake 1.6 -AUTOMAKE_OPTIONS = 1.6 - -# library information and headers which should not be installed. -python_PYTHON = mpq.py diff --git a/externals/libmpq/bindings/python/mpq-info b/externals/libmpq/bindings/python/mpq-info deleted file mode 100644 index 2c67aa1d0cc..00000000000 --- a/externals/libmpq/bindings/python/mpq-info +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env python - -from __future__ import division - -import sys - -import mpq - -archive = mpq.Archive(sys.argv[1]) - -print "Name: %s" % sys.argv[1] -print "Version: %s" % archive.filename -print "Offset: %s" % archive.offset -print "Packed size: %s" % archive.packed_size -print "Unpacked size: %s" % archive.unpacked_size -print "Compression ratio: %s" % (archive.packed_size/archive.unpacked_size) diff --git a/externals/libmpq/bindings/python/mpq.py b/externals/libmpq/bindings/python/mpq.py deleted file mode 100644 index cf6ecaae800..00000000000 --- a/externals/libmpq/bindings/python/mpq.py +++ /dev/null @@ -1,322 +0,0 @@ -"""wrapper for libmpq""" - -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - -import ctypes -import ctypes.util -import os - -libmpq = ctypes.CDLL(ctypes.util.find_library("mpq")) - -class Error(Exception): - pass - -errors = { - -1: (IOError, "open"), - -2: (IOError, "close"), - -3: (IOError, "seek"), - -4: (IOError, "read"), - -5: (IOError, "write"), - -6: (MemoryError,), - -7: (Error, "file is not an mpq or is corrupted"), - -8: (AssertionError, "not initialized"), - -9: (AssertionError, "buffer size too small"), - -10: (IndexError, "file not in archive"), - -11: (AssertionError, "decrypt"), - -12: (AssertionError, "unpack"), -} - -def check_error(result, func, arguments, errors=errors): - try: - error = errors[result] - except KeyError: - return result - else: - raise error[0](*error[1:]) - -libmpq.libmpq__version.restype = ctypes.c_char_p - -libmpq.libmpq__archive_open.errcheck = check_error -libmpq.libmpq__archive_close.errcheck = check_error -libmpq.libmpq__archive_packed_size.errcheck = check_error -libmpq.libmpq__archive_unpacked_size.errcheck = check_error -libmpq.libmpq__archive_offset.errcheck = check_error -libmpq.libmpq__archive_version.errcheck = check_error -libmpq.libmpq__archive_files.errcheck = check_error - -libmpq.libmpq__file_packed_size.errcheck = check_error -libmpq.libmpq__file_unpacked_size.errcheck = check_error -libmpq.libmpq__file_offset.errcheck = check_error -libmpq.libmpq__file_blocks.errcheck = check_error -libmpq.libmpq__file_encrypted.errcheck = check_error -libmpq.libmpq__file_compressed.errcheck = check_error -libmpq.libmpq__file_imploded.errcheck = check_error -libmpq.libmpq__file_number.errcheck = check_error -libmpq.libmpq__file_read.errcheck = check_error - -libmpq.libmpq__block_open_offset.errcheck = check_error -libmpq.libmpq__block_close_offset.errcheck = check_error -libmpq.libmpq__block_unpacked_size.errcheck = check_error -libmpq.libmpq__block_read.errcheck = check_error - -__version__ = libmpq.libmpq__version() - - -class Reader(object): - def __init__(self, file, libmpq=libmpq): - self._file = file - self._pos = 0 - self._buf = [] - self._cur_block = 0 - libmpq.libmpq__block_open_offset(self._file._archive._mpq, - self._file.number) - - def __iter__(self): - return self - - def __repr__(self): - return "iter(%r)" % self._file - - def seek(self, offset, whence=os.SEEK_SET, os=os): - if whence == os.SEEK_SET: - pass - elif whence == os.SEEK_CUR: - offset += self._pos - elif whence == os.SEEK_END: - offset += self._file.unpacked_size - else: - raise ValueError, "invalid whence" - - if offset >= self._pos: - self.read(offset - self._pos) - else: - self._pos = 0 - self._buf = [] - self._cur_block = 0 - self.read(offset) - - def tell(self): - return self._pos - - def _read_block(self, ctypes=ctypes, libmpq=libmpq): - block_size = ctypes.c_uint64() - libmpq.libmpq__block_unpacked_size(self._file._archive._mpq, - self._file.number, self._cur_block, ctypes.byref(block_size)) - block_data = ctypes.create_string_buffer(block_size.value) - libmpq.libmpq__block_read(self._file._archive._mpq, - self._file.number, self._cur_block, - block_data, ctypes.c_uint64(len(block_data)), None) - self._buf.append(block_data.raw) - self._cur_block += 1 - - def read(self, size=-1): - while size < 0 or sum(map(len, self._buf)) < size: - if self._cur_block == self._file.blocks: - break - self._read_block() - buf = "".join(self._buf) - if size < 0: - ret = buf - self._buf = [] - else: - ret = buf[:size] - self._buf = [buf[size:]] - self._pos += len(ret) - return ret - - def readline(self, os=os): - line = [] - while True: - char = self.read(1) - if char == "": - break - if char not in '\r\n' and line and line[-1] in '\r\n': - self.seek(-1, os.SEEK_CUR) - break - line.append(char) - return ''.join(line) - - def next(self): - line = self.readline() - if not line: - raise StopIteration - return line - - def readlines(self, sizehint=-1): - res = [] - while sizehint < 0 or sum(map(len, res)) < sizehint: - line = self.readline() - if not line: - break - res.append(line) - return res - - xreadlines = __iter__ - - def __del__(self, libmpq=libmpq): - libmpq.libmpq__block_close_offset(self._file._archive._mpq, - self._file.number) - - -class File(object): - def __init__(self, archive, number, ctypes=ctypes, libmpq=libmpq): - self._archive = archive - self.number = number - - for name, atype in [ - ("packed_size", ctypes.c_uint64), - ("unpacked_size", ctypes.c_uint64), - ("offset", ctypes.c_uint64), - ("blocks", ctypes.c_uint32), - ("encrypted", ctypes.c_uint32), - ("compressed", ctypes.c_uint32), - ("imploded", ctypes.c_uint32), - ]: - data = atype() - func = getattr(libmpq, "libmpq__file_"+name) - func(self._archive._mpq, self.number, ctypes.byref(data)) - setattr(self, name, data.value) - - def __str__(self, ctypes=ctypes, libmpq=libmpq): - data = ctypes.create_string_buffer(self.unpacked_size) - libmpq.libmpq__file_read(self._archive._mpq, self.number, - data, ctypes.c_uint64(len(data)), None) - return data.raw - - def __repr__(self): - return "%r[%i]" % (self._archive, self.number) - - def __iter__(self, Reader=Reader): - return Reader(self) - - -class Archive(object): - def __init__(self, source, ctypes=ctypes, File=File, libmpq=libmpq): - self._source = source - if isinstance(source, File): - assert not source.encrypted - assert not source.compressed - assert not source.imploded - self.filename = source._archive.filename - offset = source._archive.offset + source.offset - else: - self.filename = source - offset = -1 - - self._mpq = ctypes.c_void_p() - libmpq.libmpq__archive_open(ctypes.byref(self._mpq), self.filename, - ctypes.c_uint64(offset)) - self._opened = True - - for field_name, field_type in [ - ("packed_size", ctypes.c_uint64), - ("unpacked_size", ctypes.c_uint64), - ("offset", ctypes.c_uint64), - ("version", ctypes.c_uint32), - ("files", ctypes.c_uint32), - ]: - func = getattr(libmpq, "libmpq__archive_" + field_name) - data = field_type() - func(self._mpq, ctypes.byref(data)) - setattr(self, field_name, data.value) - - def __del__(self, libmpq=libmpq): - if getattr(self, "_opened", False): - libmpq.libmpq__archive_close(self._mpq) - - def __len__(self): - return self.files - - def __contains__(self, item, ctypes=ctypes, libmpq=libmpq): - if isinstance(item, str): - data = ctypes.c_uint32() - try: - libmpq.libmpq__file_number(self._mpq, ctypes.c_char_p(item), - ctypes.byref(data)) - except IndexError: - return False - return True - return 0 <= item < self.files - - def __getitem__(self, item, ctypes=ctypes, File=File, libmpq=libmpq): - if isinstance(item, str): - data = ctypes.c_int() - libmpq.libmpq__file_number(self._mpq, ctypes.c_char_p(item), - ctypes.byref(data)) - item = data.value - else: - if not 0 <= item < self.files: - raise IndexError, "file not in archive" - return File(self, item) - - def __repr__(self): - return "mpq.Archive(%r)" % self._source - -# Remove clutter - everything except Error and Archive. -del os, check_error, ctypes, errors, File, libmpq, Reader - -if __name__ == "__main__": - import sys, random - archive = Archive(sys.argv[1]) - print repr(archive) - for k, v in archive.__dict__.iteritems(): - #if k[0] == '_': continue - print " " * (4 - 1), k, v - assert '(listfile)' in archive - assert 0 in archive - assert len(archive) == archive.files - files = [x.strip() for x in archive['(listfile)']] - files.extend(xrange(archive.files)) - for key in files: #sys.argv[2:] if sys.argv[2:] else xrange(archive.files): - file = archive[key] - print - print " " * (4 - 1), repr(file) - for k, v in file.__dict__.iteritems(): - #if k[0] == '_': continue - print " " * (8 - 1), k, v - - a = str(file) - - b = iter(file).read() - - reader = iter(file) - c = [] - while True: - l = random.randrange(1, 10) - d = reader.read(l) - if not d: break - assert len(d) <= l - c.append(d) - c = "".join(c) - - d = [] - reader.seek(0) - for line in reader: - d.append(line) - d = "".join(d) - - assert a == b == c == d, map(hash, [a,b,c,d]) - assert len(a) == file.unpacked_size - - repr(iter(file)) - - - reader.seek(0) - a = reader.readlines() - - reader.seek(0) - b = list(reader) - - assert a == b diff --git a/externals/libmpq/config.h b/externals/libmpq/config.h deleted file mode 100644 index c69fb13211b..00000000000 --- a/externals/libmpq/config.h +++ /dev/null @@ -1,74 +0,0 @@ -/* config.h. Generated from config.h.in by configure. */ -/* config.h.in. Generated from configure.ac by autoheader. */ - -/* Define to 1 if you have the header file. */ -#define HAVE_DLFCN_H 1 - -/* Define to 1 if fseeko (and presumably ftello) exists and is declared. */ -#define HAVE_FSEEKO 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_INTTYPES_H 1 - -/* Define to 1 if you have the `bz2' library (-lbz2). */ -#define HAVE_LIBBZ2 1 - -/* Define to 1 if you have the `z' library (-lz). */ -#define HAVE_LIBZ 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_MEMORY_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_STDINT_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_STDLIB_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_STRINGS_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_STRING_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_SYS_STAT_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_SYS_TYPES_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_UNISTD_H 1 - -/* Name of package */ -#define PACKAGE "libmpq" - -/* Define to the address where bug reports for this package should be sent. */ -#define PACKAGE_BUGREPORT "mbroemme@plusserver.de" - -/* Define to the full name of this package. */ -#define PACKAGE_NAME "libmpq" - -/* Define to the full name and version of this package. */ -#define PACKAGE_STRING "libmpq 0.4.2" - -/* Define to the one symbol short name of this package. */ -#define PACKAGE_TARNAME "libmpq" - -/* Define to the version of this package. */ -#define PACKAGE_VERSION "0.4.2" - -/* Define to 1 if you have the ANSI C header files. */ -#define STDC_HEADERS 1 - -/* Version number of package */ -#define VERSION "0.4.2" - -/* Number of bits in a file offset, on hosts where this is settable. */ -#define _FILE_OFFSET_BITS 64 - -/* Define to 1 to make fseeko visible on some hosts (e.g. glibc 2.2). */ -/* #undef _LARGEFILE_SOURCE */ - -/* Define for large files, on AIX-style hosts. */ -/* #undef _LARGE_FILES */ diff --git a/externals/libmpq/configure.ac b/externals/libmpq/configure.ac deleted file mode 100644 index d274eab07c6..00000000000 --- a/externals/libmpq/configure.ac +++ /dev/null @@ -1,84 +0,0 @@ -# the autoconf initilization. -AC_INIT(libmpq, 0.4.2, [mbroemme@plusserver.de], [libmpq]) - -# detect the canonical host and target build environment. -AC_CANONICAL_SYSTEM - -# initialize autoconf and automake system. -AM_INIT_AUTOMAKE([no-dependencies]) -AC_CONFIG_HEADERS([config.h:config.h.in]) - -# notices. -AC_PREREQ(2.53) -AC_REVISION($Revision: 1.6 $) - -# checking for programs. -AC_PROG_LIBTOOL -AC_PROG_MAKE_SET -AC_PROG_CC -AC_SYS_LARGEFILE -AC_FUNC_FSEEKO - -# check if we need to export some largefile flags. -if test "$enable_largefile" != no; then - if test "$ac_cv_sys_file_offset_bits" != 'no'; then - if test -z "$LFS_CFLAGS" ; then - LFS_CFLAGS="-D_FILE_OFFSET_BITS=$ac_cv_sys_file_offset_bits" - else - LFS_CFLAGS="$LFS_CFLAGS -D_FILE_OFFSET_BITS=$ac_cv_sys_file_offset_bits" - fi - fi - if test "$ac_cv_sys_large_files" != 'no'; then - if test -z "$LFS_CFLAGS" ; then - LFS_CFLAGS="-D_LARGE_FILES=1" - else - LFS_CFLAGS="$LFS_CFLAGS -D_LARGE_FILES=1" - fi - fi - if test "$ac_cv_sys_largefile_source" != 'no'; then - if test -z "$LFS_CFLAGS" ; then - LFS_CFLAGS="-D_LARGEFILE_SOURCE=1" - else - LFS_CFLAGS="$LFS_CFLAGS -D_LARGEFILE_SOURCE=1" - fi - fi -fi - -# export largefile flags. -AC_SUBST(LFS_CFLAGS) - -# check for zlib library. -AC_CHECK_HEADER([zlib.h], [], [AC_MSG_ERROR([*** zlib.h is required, install zlib header files])]) -AC_CHECK_LIB([z], [inflateEnd], [], [AC_MSG_ERROR([*** inflateEnd is required, install zlib library files])]) - -# check for bzlib2 library. -AC_CHECK_HEADER([bzlib.h], [], [AC_MSG_ERROR([*** bzlib.h is required, install bzip2 header files])]) -AC_CHECK_LIB([bz2], [BZ2_bzDecompressInit], [], [AC_MSG_ERROR([*** BZ2_bzDecompressInit is required, install bzip2 library files])]) - -# When we're running gcc 4 or greater, compile with -fvisibility=hidden. -AC_TRY_COMPILE([ -#if !defined(__GNUC__) || (__GNUC__ < 4) -#error not gcc4 -#endif -], [], [CFLAGS="$CFLAGS -fvisibility=hidden"]) - -# find python for binding -AM_PATH_PYTHON([2.4],,[:]) -AM_CONDITIONAL([HAVE_PYTHON], [test "$PYTHON" != :]) - -# configuration files. -AC_CONFIG_FILES([libmpq.pc]) -AC_CONFIG_FILES([libmpq-config],[chmod +x libmpq-config]) - -# creating files. -AC_OUTPUT([ -Makefile -libmpq/Makefile -bindings/Makefile -bindings/d/Makefile -bindings/python/Makefile -doc/Makefile -doc/man1/Makefile -doc/man3/Makefile -tools/Makefile -]) diff --git a/externals/libmpq/debian/changelog b/externals/libmpq/debian/changelog deleted file mode 100644 index 55d2d918755..00000000000 --- a/externals/libmpq/debian/changelog +++ /dev/null @@ -1,35 +0,0 @@ -libmpq (0.4.2-svn288-1) unstable; urgency=low - - [ babyface ] - * Due to the nature of MPQ archives which can have valid block entries - * removed function libmpq__init() and libmpq__shutdown(), because they - are no longer required and libmpq__file_name(), because it is up to - the application to provide listfile support - * updated documentation to latest API changes - * removed API documentation for removed function prototypes - * removed no longer required files from target - - [ forrestv ] - * mpq.py fix - * spelling - huffmann to huffman - * changed pkware/pkzip to pkzip and used constants instead of numbers - in extract.c - * sanified huffman decoder a bit - * cleanup + update of mpq.py - * Added support for library finding on platforms besides Linux. - * python bindings - sequence methods on Archive, example code - - [ georg ] - * libmpq: file number search now continued over hashtable end - * debian debug package - - -- Georg Lukas Fri, 22 May 2009 22:38:26 +0200 - -libmpq (0.4.2-svn270-1) unstable; urgency=low - - * First debian package - * compatible to new libmpq API (post 0.4.2) - * contains preliminary python-mpq package - - -- Georg Lukas Tue, 07 Oct 2008 14:38:58 +0200 - diff --git a/externals/libmpq/debian/compat b/externals/libmpq/debian/compat deleted file mode 100644 index 7f8f011eb73..00000000000 --- a/externals/libmpq/debian/compat +++ /dev/null @@ -1 +0,0 @@ -7 diff --git a/externals/libmpq/debian/control b/externals/libmpq/debian/control deleted file mode 100644 index f35bb060015..00000000000 --- a/externals/libmpq/debian/control +++ /dev/null @@ -1,50 +0,0 @@ -Source: libmpq -Priority: extra -Maintainer: Georg Lukas -Build-Depends: debhelper (>= 7), autotools-dev, libbz2-dev -Standards-Version: 3.7.3 -Section: libs -Homepage: https://libmpq.org/ - -Package: libmpq-dev -Section: libdevel -Architecture: any -Depends: libmpq0 (= ${binary:Version}) -Description: Headers for libmpq, a library for MoPaQ mpq archives - libmpq is a library for extracting and manipulating MoPaQ mpq archives. - This package provides header files and bindings for applications using - the libmpq library for the following languages: - * C - * Python - * D - -Package: libmpq0 -Section: libs -Architecture: any -Depends: ${shlibs:Depends}, ${misc:Depends} -Description: A library for extracting and manipulating MoPaQ mpq archives - MPQ, or MoPaQ, is a proprietary archive format created by - Mike O'Brien, the man hailed as Blizzard's multiplayer engine - genius, back in 1996 as a general purpose archive for use with - Diablo, and named narcissistically for its creator - "Mike O'brien PaCK". The copyrights to it, however, are held by - Havas Interactive, Blizzard's parent company. The archive format - is used by many Blizzard titles like Diablo, Diablo 2, Starcraft, - Warcraft 2: BNE, a newer version in Warcraft 3 and World of - Warcraft (WoW). - -Package: libmpq0-dbg -Section: libdevel -Architecture: any -Depends: libmpq0 (= ${binary:Version}) -Description: Debug symbols for libmpq0 library package - -Package: python-mpq -Architecture: all -Depends: ${python:Depends} -XB-Python-Version: ${python:Versions} -XS-Python-Version: current -Description: Python bindings for libmpq, a library for MoPaQ mpq archives - libmpq is a library for extracting and manipulating MoPaQ mpq archives. - This package provides the python bindings for libmpq. - diff --git a/externals/libmpq/debian/copyright b/externals/libmpq/debian/copyright deleted file mode 100644 index f014cf14de7..00000000000 --- a/externals/libmpq/debian/copyright +++ /dev/null @@ -1,23 +0,0 @@ -This package was debianized by Georg Lukas on -Fri, 04 Jul 2008 18:17:08 +0200. - -It was downloaded from - -Upstream Author: - - Maik Broemme - -Copyright: - - Copyright (C) 2008 Maik Broemme - -License: - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - -The Debian packaging is (C) 2008, Georg Lukas and -is licensed under the GPL, see `/usr/share/common-licenses/GPL'. diff --git a/externals/libmpq/debian/libmpq-dev.dirs b/externals/libmpq/debian/libmpq-dev.dirs deleted file mode 100644 index 7b6c7ee6ec1..00000000000 --- a/externals/libmpq/debian/libmpq-dev.dirs +++ /dev/null @@ -1,6 +0,0 @@ -usr/bin -usr/lib -usr/lib/pkgconfig -usr/include -usr/share/man/man1 -usr/share/man/man3 diff --git a/externals/libmpq/debian/libmpq-dev.install b/externals/libmpq/debian/libmpq-dev.install deleted file mode 100644 index 4e6ab3278e3..00000000000 --- a/externals/libmpq/debian/libmpq-dev.install +++ /dev/null @@ -1,6 +0,0 @@ -usr/bin/* -usr/include/* -usr/lib/lib*.a -usr/lib/pkgconfig/* -usr/lib/*.la -usr/share/man/man?/* diff --git a/externals/libmpq/debian/libmpq0.dirs b/externals/libmpq/debian/libmpq0.dirs deleted file mode 100644 index 68457717bd8..00000000000 --- a/externals/libmpq/debian/libmpq0.dirs +++ /dev/null @@ -1 +0,0 @@ -usr/lib diff --git a/externals/libmpq/debian/libmpq0.docs b/externals/libmpq/debian/libmpq0.docs deleted file mode 100644 index 5ac7060850c..00000000000 --- a/externals/libmpq/debian/libmpq0.docs +++ /dev/null @@ -1,6 +0,0 @@ -FAQ -NEWS -README -TODO -THANKS -AUTHORS diff --git a/externals/libmpq/debian/libmpq0.install b/externals/libmpq/debian/libmpq0.install deleted file mode 100644 index 8aa4466a68e..00000000000 --- a/externals/libmpq/debian/libmpq0.install +++ /dev/null @@ -1 +0,0 @@ -usr/lib/lib*.so* diff --git a/externals/libmpq/debian/python-mpq.install b/externals/libmpq/debian/python-mpq.install deleted file mode 100644 index a7aba2013b0..00000000000 --- a/externals/libmpq/debian/python-mpq.install +++ /dev/null @@ -1 +0,0 @@ -usr/lib/python?.? diff --git a/externals/libmpq/debian/rules b/externals/libmpq/debian/rules deleted file mode 100644 index 1e101be5faf..00000000000 --- a/externals/libmpq/debian/rules +++ /dev/null @@ -1,112 +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) -ifneq ($(DEB_HOST_GNU_TYPE),$(DEB_BUILD_GNU_TYPE)) -CROSS= --build $(DEB_BUILD_GNU_TYPE) --host $(DEB_HOST_GNU_TYPE) -else -CROSS= --build $(DEB_BUILD_GNU_TYPE) -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. -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 - ./configure $(CROSS) --prefix=/usr --mandir=\$${prefix}/share/man --infodir=\$${prefix}/share/info CFLAGS="$(CFLAGS) -ggdb" LDFLAGS="-Wl,-z,defs" - - -build: build-stamp -build-stamp: config.status - dh_testdir - - # Add here commands to compile the package. - $(MAKE) - - touch $@ - -clean: - dh_testdir - dh_testroot - rm -f build-stamp - - # Add here commands to clean up after the build process. - [ ! -f Makefile ] || $(MAKE) distclean - rm -f config.sub config.guess - - dh_clean - -install: build - dh_testdir - dh_testroot - dh_clean -k - dh_installdirs - - # Add here commands to install the package into debian/tmp - $(MAKE) DESTDIR=$(CURDIR)/debian/tmp install - - -# Build architecture-independent files here. -binary-indep: build install - dh_pysupport usr/lib/python?.?/site-packages - -# Build architecture-dependent files here. -binary-arch: build install - dh_testdir - dh_testroot - dh_installchangelogs - dh_installdocs - dh_installexamples - dh_install -# dh_installmenu -# dh_installdebconf -# dh_installlogrotate -# dh_installemacsen -# dh_installpam -# dh_installmime -# dh_installinit -# dh_installcron -# dh_installinfo - dh_installman - dh_link - dh_strip --dbg-package=libmpq0-dbg - dh_compress - dh_fixperms -# dh_perl - 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/externals/libmpq/doc/Makefile.am b/externals/libmpq/doc/Makefile.am deleted file mode 100644 index e7ccd5f4518..00000000000 --- a/externals/libmpq/doc/Makefile.am +++ /dev/null @@ -1,5 +0,0 @@ -# minimum required automake 1.6 -AUTOMAKE_OPTIONS = 1.6 - -# any directories which should be built and installed. -SUBDIRS = man1 man3 diff --git a/externals/libmpq/doc/man1/Makefile.am b/externals/libmpq/doc/man1/Makefile.am deleted file mode 100644 index 055f1aab533..00000000000 --- a/externals/libmpq/doc/man1/Makefile.am +++ /dev/null @@ -1,9 +0,0 @@ -# minimum required automake 1.6 -AUTOMAKE_OPTIONS = 1.6 - -# manual page directory. -EXTRA_DIST = $(man_MANS) - -# manual pages for the installed binaries. -man_MANS = \ - libmpq-config.1 diff --git a/externals/libmpq/doc/man1/libmpq-config.1 b/externals/libmpq/doc/man1/libmpq-config.1 deleted file mode 100644 index c025f5ce4f4..00000000000 --- a/externals/libmpq/doc/man1/libmpq-config.1 +++ /dev/null @@ -1,69 +0,0 @@ -.\" Copyright (c) 2003-2008 Maik Broemme -.\" -.\" This is free documentation; 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. -.\" -.\" The GNU General Public License's references to "object code" -.\" and "executables" are to be interpreted as the output of any -.\" document formatting or typesetting system, including -.\" intermediate and printed output. -.\" -.\" This manual is distributed in the hope that it will be useful, -.\" but WITHOUT ANY WARRANTY; without even the implied warranty of -.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -.\" GNU General Public License for more details. -.\" -.\" You should have received a copy of the GNU General Public -.\" License along with this manual; if not, write to the Free -.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, -.\" USA. -.TH libmpq 1 2008-02-10 "The MoPaQ archive library" -.SH NAME -libmpq-config \- script to get information about the installed version of libmpq. -.SH SYNOPSIS -.B libmpq-config -[\-\-prefix\fI[=DIR]\fP] [\-\-exec\-prefix\fI[=DIR]\fP] [\-\-version] -.br -[\-\-cflags] [\-\-libs] [\-\-static\-libs] -.SH DESCRIPTION -.PP -\fIlibmpq-config\fP is a tool that is used to determine the compiler and linker flags that should be used to compile and link programs that use \fIlibmpq\fP. Finally, it's also used internally by the .m4 macros for GNU autoconf that are included with \fIlibmpq\fP. -.SH OPTIONS -\fIlibmpq-config\fP accepts the following options: -.TP 8 -.B \-\-version -.ti 15 -Print the currently installed version of \fIlibmpq\fP on the standard output. -.TP 8 -.B \-\-libs -.ti 15 -Print the linker flags that are necessary to link \fIlibmpq\fP to a program. -.TP 8 -.B \-\-static\-libs -.ti 15 -Print the linker flags that are necessary to statically link \fIlibmpq\fP to a program. -.TP 8 -.B \-\-cflags -.ti 15 -Print the compiler flags that are necessary to compile a program that use \fIlibmpq\fP. -.TP 8 -.B \-\-prefix=PREFIX -.ti 15 -If specified, use PREFIX instead of the installation prefix that \fIlibmpq\fP was built with when computing the output for the \-\-cflags and \-\-libs options. This option is also used for the exec prefix if \-\-exec\-prefix was not specified. This option must be specified before any \-\-libs or \-\-cflags options. -.TP 8 -.B \-\-exec\-prefix=PREFIX -.ti 15 -If specified, use PREFIX instead of the installation exec prefix that \fIlibmpq\fP was built with when computing the output for the \-\-cflags and \-\-libs options. This option must be specified before any \-\-libs or \-\-cflags options. -.SH NOTE -Instead of using this configuration script you should better use the pkg-config version because this would be more platform independent and makes the usage within GNU autoconf much easier. -.SH SEE ALSO -\fBlibmpq\fR(3) -.SH AUTHOR -Check documentation. -.TP -libmpq is (c) 2003-2008 -.B Maik Broemme -.PP -The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/externals/libmpq/doc/man3/Makefile.am b/externals/libmpq/doc/man3/Makefile.am deleted file mode 100644 index cad3d865dc1..00000000000 --- a/externals/libmpq/doc/man3/Makefile.am +++ /dev/null @@ -1,31 +0,0 @@ -# minimum required automake 1.6 -AUTOMAKE_OPTIONS = 1.6 - -# manual page directory. -EXTRA_DIST = $(man_MANS) - -# manual pages for the installed binaries. -man_MANS = \ - libmpq.3 \ - libmpq__archive_close.3 \ - libmpq__archive_files.3 \ - libmpq__archive_offset.3 \ - libmpq__archive_open.3 \ - libmpq__archive_packed_size.3 \ - libmpq__archive_unpacked_size.3 \ - libmpq__archive_version.3 \ - libmpq__block_close_offset.3 \ - libmpq__block_open_offset.3 \ - libmpq__block_read.3 \ - libmpq__block_unpacked_size.3 \ - libmpq__file_blocks.3 \ - libmpq__file_compressed.3 \ - libmpq__file_encrypted.3 \ - libmpq__file_imploded.3 \ - libmpq__file_number.3 \ - libmpq__file_offset.3 \ - libmpq__file_packed_size.3 \ - libmpq__file_read.3 \ - libmpq__file_unpacked_size.3 \ - libmpq__strerror.3 \ - libmpq__version.3 diff --git a/externals/libmpq/doc/man3/libmpq.3 b/externals/libmpq/doc/man3/libmpq.3 deleted file mode 100644 index 768dab0a712..00000000000 --- a/externals/libmpq/doc/man3/libmpq.3 +++ /dev/null @@ -1,207 +0,0 @@ -.\" Copyright (c) 2003-2008 Maik Broemme -.\" -.\" This is free documentation; 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. -.\" -.\" The GNU General Public License's references to "object code" -.\" and "executables" are to be interpreted as the output of any -.\" document formatting or typesetting system, including -.\" intermediate and printed output. -.\" -.\" This manual is distributed in the hope that it will be useful, -.\" but WITHOUT ANY WARRANTY; without even the implied warranty of -.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -.\" GNU General Public License for more details. -.\" -.\" You should have received a copy of the GNU General Public -.\" License along with this manual; if not, write to the Free -.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, -.\" USA. -.TH libmpq 3 2008-04-29 "The MoPaQ archive library" -.SH NAME -libmpq \- cross-platform C library for manipulating mpq archives. -.SH SYNOPSIS -.nf -.B -#include -.sp -.BI "const char *libmpq__version();" -.sp -.BI "const char *libmpq__strerror(int32_t returncode);" -.sp -.BI "int32_t libmpq__archive_open(" -.BI " mpq_archive_s **" "mpq_archive", -.BI " const char *" "mpq_filename", -.BI " off_t " "archive_offset" -.BI ");" -.sp -.BI "int32_t libmpq__archive_close(" -.BI " mpq_archive_s *" "mpq_archive" -.BI ");" -.sp -.BI "int32_t libmpq__archive_packed_size(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " off_t *" "packed_size" -.BI ");" -.sp -.BI "int32_t libmpq__archive_unpacked_size(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " off_t *" "unpacked_size" -.BI ");" -.sp -.BI "int32_t libmpq__archive_offset(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " off_t *" "offset" -.BI ");" -.sp -.BI "int32_t libmpq__archive_version(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t *" "version" -.BI ");" -.sp -.BI "int32_t libmpq__archive_files(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t *" "files" -.BI ");" -.sp -.BI "int32_t libmpq__file_packed_size(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t " "file_number", -.BI " off_t *" "packed_size" -.BI ");" -.sp -.BI "int32_t libmpq__file_unpacked_size(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t " "file_number", -.BI " off_t *" "unpacked_size" -.BI ");" -.sp -.BI "int32_t libmpq__file_offset(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t " "file_number", -.BI " off_t *" "offset" -.BI ");" -.sp -.BI "int32_t libmpq__file_blocks(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t " "file_number", -.BI " off_t *" "blocks" -.BI ");" -.sp -.BI "int32_t libmpq__file_encrypted(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t " "file_number", -.BI " off_t *" "encrypted" -.BI ");" -.sp -.BI "int32_t libmpq__file_compressed(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t " "file_number", -.BI " off_t *" "compressed" -.BI ");" -.sp -.BI "int32_t libmpq__file_imploded(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t " "file_number", -.BI " off_t *" "imploded" -.BI ");" -.sp -.BI "int32_t libmpq__file_number(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " const char *" "filename", -.BI " uint32_t *" "number" -.BI ");" -.sp -.BI "int32_t libmpq__file_read(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t " "file_number", -.BI " uint8_t *" "out_buf", -.BI " off_t " "out_size", -.BI " off_t *" "transferred" -.BI ");" -.sp -.BI "int32_t libmpq__block_open_offset(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t " "file_number" -.BI ");" -.sp -.BI "int32_t libmpq__block_close_offset(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t " "file_number" -.BI ");" -.sp -.BI "int32_t libmpq__block_packed_size(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t " "file_number", -.BI " uint32_t " "block_number", -.BI " off_t *" "packed_size" -.BI ");" -.sp -.BI "int32_t libmpq__block_unpacked_size(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t " "file_number", -.BI " uint32_t " "block_number", -.BI " off_t *" "unpacked_size" -.BI ");" -.sp -.BI "int32_t libmpq__block_offset(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t " "file_number", -.BI " uint32_t " "block_number", -.BI " off_t *" "offset" -.BI ");" -.sp -.BI "int32_t libmpq__block_seed(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t " "file_number", -.BI " uint32_t " "block_number", -.BI " uint32_t *" "seed" -.BI ");" -.sp -.BI "int32_t libmpq__block_read(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t " "file_number", -.BI " uint32_t " "block_number", -.BI " uint8_t *" "out_buf", -.BI " off_t " "out_size", -.BI " off_t *" "transferred" -.BI ");" -.fi -.SH DESCRIPTION -.PP -The \fIlibmpq\fP library supports decrypting, decompressing, exploding and various manipulations of the MoPaQ archive files. It uses \fIzlib(3)\fP and \fIbzip2(1)\fP compression library. At this moment \fIlibmpq\fP is not able to create MoPaQ archives, this limitation will be removed in a future version. -.SH SEE ALSO -.BR libmpq__version (3), -.BR libmpq__strerror (3), -.BR libmpq__archive_open (3), -.BR libmpq__archive_close (3), -.BR libmpq__archive_packed_size (3), -.BR libmpq__archive_unpacked_size (3), -.BR libmpq__archive_offset (3), -.BR libmpq__archive_version (3), -.BR libmpq__archive_files (3), -.BR libmpq__file_packed_size (3), -.BR libmpq__file_unpacked_size (3), -.BR libmpq__file_offset (3), -.BR libmpq__file_blocks (3), -.BR libmpq__file_encrypted (3), -.BR libmpq__file_compressed (3), -.BR libmpq__file_imploded (3), -.BR libmpq__file_number (3), -.BR libmpq__file_read (3), -.BR libmpq__block_open_offset (3), -.BR libmpq__block_close_offset (3), -.BR libmpq__block_packed_size (3), -.BR libmpq__block_unpacked_size (3), -.BR libmpq__block_offset (3), -.BR libmpq__block_seed (3), -.BR libmpq__block_read (3) -.SH AUTHOR -Check documentation. -.TP -libmpq is (c) 2003-2008 -.B Maik Broemme -.PP -The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/externals/libmpq/doc/man3/libmpq__archive_close.3 b/externals/libmpq/doc/man3/libmpq__archive_close.3 deleted file mode 100644 index dfc652a6721..00000000000 --- a/externals/libmpq/doc/man3/libmpq__archive_close.3 +++ /dev/null @@ -1,57 +0,0 @@ -.\" Copyright (c) 2003-2008 Maik Broemme -.\" -.\" This is free documentation; 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. -.\" -.\" The GNU General Public License's references to "object code" -.\" and "executables" are to be interpreted as the output of any -.\" document formatting or typesetting system, including -.\" intermediate and printed output. -.\" -.\" This manual is distributed in the hope that it will be useful, -.\" but WITHOUT ANY WARRANTY; without even the implied warranty of -.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -.\" GNU General Public License for more details. -.\" -.\" You should have received a copy of the GNU General Public -.\" License along with this manual; if not, write to the Free -.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, -.\" USA. -.TH libmpq 3 2008-04-29 "The MoPaQ archive library" -.SH NAME -libmpq \- cross-platform C library for manipulating mpq archives. -.SH SYNOPSIS -.nf -.B -#include -.sp -.BI "int32_t libmpq__archive_close(" -.BI " mpq_archive_s *" "mpq_archive" -.BI ");" -.fi -.SH DESCRIPTION -.PP -Call \fBlibmpq__archive_close\fP() to close a mpq archive which was opened by \fBlibmpq__archive_open\fP(). The function frees the archive structure itself and the contents of it. -.LP -The \fBlibmpq__archive_close\fP() function one takes one argument of the archive structure \fImpq_archive\fP which has to be set by \fBlibmpq__archive_open\fP. -.SH RETURN VALUE -On success, a zero is returned and on error one of the following constants. -.TP -.B LIBMPQ_ERROR_CLOSE -The given file could not be closed. -.SH SEE ALSO -.BR libmpq__archive_open (3), -.BR libmpq__archive_packed_size (3), -.BR libmpq__archive_unpacked_size (3), -.BR libmpq__archive_offset (3), -.BR libmpq__archive_version (3), -.BR libmpq__archive_files (3) -.SH AUTHOR -Check documentation. -.TP -libmpq is (c) 2003-2008 -.B Maik Broemme -.PP -The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/externals/libmpq/doc/man3/libmpq__archive_files.3 b/externals/libmpq/doc/man3/libmpq__archive_files.3 deleted file mode 100644 index 6663b99161a..00000000000 --- a/externals/libmpq/doc/man3/libmpq__archive_files.3 +++ /dev/null @@ -1,50 +0,0 @@ -.\" Copyright (c) 2003-2008 Maik Broemme -.\" -.\" This is free documentation; 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. -.\" -.\" The GNU General Public License's references to "object code" -.\" and "executables" are to be interpreted as the output of any -.\" document formatting or typesetting system, including -.\" intermediate and printed output. -.\" -.\" This manual is distributed in the hope that it will be useful, -.\" but WITHOUT ANY WARRANTY; without even the implied warranty of -.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -.\" GNU General Public License for more details. -.\" -.\" You should have received a copy of the GNU General Public -.\" License along with this manual; if not, write to the Free -.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, -.\" USA. -.TH libmpq 3 2008-05-14 "The MoPaQ archive library" -.SH NAME -libmpq \- cross-platform C library for manipulating mpq archives. -.SH SYNOPSIS -.nf -.B -#include -.sp -.BI "int32_t libmpq__archive_files(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t *" "files" -.BI ");" -.fi -.SH DESCRIPTION -.PP -Call \fBlibmpq__archive_files\fP() to get the number of files inside the archive. It will count only valid files and skip files which have deleted or freed hash entries. -.LP -The \fBlibmpq__archive_files\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument is a reference to the number of \fIfiles\fP in the archive. -.SH RETURN VALUE -On success, a zero is returned. -.SH SEE ALSO -.BR libmpq__file_blocks (3) -.SH AUTHOR -Check documentation. -.TP -libmpq is (c) 2003-2008 -.B Maik Broemme -.PP -The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/externals/libmpq/doc/man3/libmpq__archive_offset.3 b/externals/libmpq/doc/man3/libmpq__archive_offset.3 deleted file mode 100644 index 696ac5e809f..00000000000 --- a/externals/libmpq/doc/man3/libmpq__archive_offset.3 +++ /dev/null @@ -1,51 +0,0 @@ -.\" Copyright (c) 2003-2008 Maik Broemme -.\" -.\" This is free documentation; 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. -.\" -.\" The GNU General Public License's references to "object code" -.\" and "executables" are to be interpreted as the output of any -.\" document formatting or typesetting system, including -.\" intermediate and printed output. -.\" -.\" This manual is distributed in the hope that it will be useful, -.\" but WITHOUT ANY WARRANTY; without even the implied warranty of -.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -.\" GNU General Public License for more details. -.\" -.\" You should have received a copy of the GNU General Public -.\" License along with this manual; if not, write to the Free -.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, -.\" USA. -.TH libmpq 3 2008-05-14 "The MoPaQ archive library" -.SH NAME -libmpq \- cross-platform C library for manipulating mpq archives. -.SH SYNOPSIS -.nf -.B -#include -.sp -.BI "int32_t libmpq__archive_offset(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " off_t *" "offset" -.BI ");" -.fi -.SH DESCRIPTION -.PP -Call \fBlibmpq__archive_offset\fP() to get the offset of the archive, which is the absolute position in the file. It also supports archives within archives. -.LP -The \fBlibmpq__archive_offset\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument is a reference to the archive starting position \fIoffset\fP in file. -.SH RETURN VALUE -On success, a zero is returned. -.SH SEE ALSO -.BR libmpq__file_offset (3), -.BR libmpq__block_offset (3) -.SH AUTHOR -Check documentation. -.TP -libmpq is (c) 2003-2008 -.B Maik Broemme -.PP -The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/externals/libmpq/doc/man3/libmpq__archive_open.3 b/externals/libmpq/doc/man3/libmpq__archive_open.3 deleted file mode 100644 index 02c021f8948..00000000000 --- a/externals/libmpq/doc/man3/libmpq__archive_open.3 +++ /dev/null @@ -1,71 +0,0 @@ -.\" Copyright (c) 2003-2008 Maik Broemme -.\" -.\" This is free documentation; 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. -.\" -.\" The GNU General Public License's references to "object code" -.\" and "executables" are to be interpreted as the output of any -.\" document formatting or typesetting system, including -.\" intermediate and printed output. -.\" -.\" This manual is distributed in the hope that it will be useful, -.\" but WITHOUT ANY WARRANTY; without even the implied warranty of -.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -.\" GNU General Public License for more details. -.\" -.\" You should have received a copy of the GNU General Public -.\" License along with this manual; if not, write to the Free -.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, -.\" USA. -.TH libmpq 3 2008-04-29 "The MoPaQ archive library" -.SH NAME -libmpq \- cross-platform C library for manipulating mpq archives. -.SH SYNOPSIS -.nf -.B -#include -.sp -.BI "int32_t libmpq__archive_open(" -.BI " mpq_archive_s **" "mpq_archive", -.BI " const char *" "mpq_filename", -.BI " off_t " "archive_offset" -.BI ");" -.fi -.SH DESCRIPTION -.PP -Call \fBlibmpq__archive_open\fP() to open a given mpq archive for later use to extract or manipulate files inside the archive. It will create all required file structures and you have to call \fBlibmpq__archive_close\fP() on success to clean the opened structures. On failure there is no need to call \fBlibmpq__archive_close\fP() because everything will be cleaned up. -.LP -The \fBlibmpq__archive_open\fP() function takes as first argument a reference to the archive structure \fImpq_archive\fP and will open the file \fImpq_filename\fP to the structure pointed to by \fImpq_archive\fP. The last argument, \fIarchive_offset\fP is normally -1, but can be specified when the archive offset is known, or not 512-byte aligned. -.SH RETURN VALUE -On success, *\fImpq_archive\fP is set to a new \fBmpq_archive_s\fP* and zero is returned, and on error one of the following constants is returned. -.TP -.B LIBMPQ_ERROR_OPEN -The given file could not be opened. -.TP -.B LIBMPQ_ERROR_MALLOC -Not enough memory for creating required structures. -.TP -.B LIBMPQ_ERROR_SEEK -Seeking in file failed. -.TP -.B LIBMPQ_ERROR_FORMAT -The given file is no valid mpq archive. -.TP -.B LIBMPQ_ERROR_READ -Reading in archive failed. -.SH SEE ALSO -.BR libmpq__archive_close (3), -.BR libmpq__archive_packed_size (3), -.BR libmpq__archive_unpacked_size (3), -.BR libmpq__archive_offset (3), -.BR libmpq__archive_version (3), -.BR libmpq__archive_files (3) -.SH AUTHOR -Check documentation. -.TP -libmpq is (c) 2003-2008 -.B Maik Broemme -.PP -The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/externals/libmpq/doc/man3/libmpq__archive_packed_size.3 b/externals/libmpq/doc/man3/libmpq__archive_packed_size.3 deleted file mode 100644 index 6c3061f2031..00000000000 --- a/externals/libmpq/doc/man3/libmpq__archive_packed_size.3 +++ /dev/null @@ -1,51 +0,0 @@ -.\" Copyright (c) 2003-2008 Maik Broemme -.\" -.\" This is free documentation; 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. -.\" -.\" The GNU General Public License's references to "object code" -.\" and "executables" are to be interpreted as the output of any -.\" document formatting or typesetting system, including -.\" intermediate and printed output. -.\" -.\" This manual is distributed in the hope that it will be useful, -.\" but WITHOUT ANY WARRANTY; without even the implied warranty of -.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -.\" GNU General Public License for more details. -.\" -.\" You should have received a copy of the GNU General Public -.\" License along with this manual; if not, write to the Free -.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, -.\" USA. -.TH libmpq 3 2008-04-29 "The MoPaQ archive library" -.SH NAME -libmpq \- cross-platform C library for manipulating mpq archives. -.SH SYNOPSIS -.nf -.B -#include -.sp -.BI "int32_t libmpq__archive_packed_size(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " off_t *" "packed_size" -.BI ");" -.fi -.SH DESCRIPTION -.PP -Call \fBlibmpq__archive_packed_size\fP() to get the packed size of all files in the archive. It will count compressed and imploded files as well as stored only. -.LP -The \fBlibmpq__archive_packed_size\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument is a reference to the compressed, imploded or stored size \fIpacked_size\fP of file. -.SH RETURN VALUE -On success, a zero is returned. -.SH SEE ALSO -.BR libmpq__file_packed_size (3), -.BR libmpq__block_packed_size (3) -.SH AUTHOR -Check documentation. -.TP -libmpq is (c) 2003-2008 -.B Maik Broemme -.PP -The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/externals/libmpq/doc/man3/libmpq__archive_unpacked_size.3 b/externals/libmpq/doc/man3/libmpq__archive_unpacked_size.3 deleted file mode 100644 index d2ba923c8f0..00000000000 --- a/externals/libmpq/doc/man3/libmpq__archive_unpacked_size.3 +++ /dev/null @@ -1,51 +0,0 @@ -.\" Copyright (c) 2003-2008 Maik Broemme -.\" -.\" This is free documentation; 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. -.\" -.\" The GNU General Public License's references to "object code" -.\" and "executables" are to be interpreted as the output of any -.\" document formatting or typesetting system, including -.\" intermediate and printed output. -.\" -.\" This manual is distributed in the hope that it will be useful, -.\" but WITHOUT ANY WARRANTY; without even the implied warranty of -.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -.\" GNU General Public License for more details. -.\" -.\" You should have received a copy of the GNU General Public -.\" License along with this manual; if not, write to the Free -.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, -.\" USA. -.TH libmpq 3 2008-04-29 "The MoPaQ archive library" -.SH NAME -libmpq \- cross-platform C library for manipulating mpq archives. -.SH SYNOPSIS -.nf -.B -#include -.sp -.BI "int32_t libmpq__archive_unpacked_size(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " off_t *" "unpacked_size" -.BI ");" -.fi -.SH DESCRIPTION -.PP -Call \fBlibmpq__archive_unpacked_size\fP() to get the unpacked size of all files in the archive. It will count uncompressed and exploded files as well as stored only. -.LP -The \fBlibmpq__archive_unpacked_size\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument is a reference to the uncompressed, exploded or stored size \fIunpacked_size\fP of file. -.SH RETURN VALUE -On success, a zero is returned. -.SH SEE ALSO -.BR libmpq__file_unpacked_size (3), -.BR libmpq__block_unpacked_size (3) -.SH AUTHOR -Check documentation. -.TP -libmpq is (c) 2003-2008 -.B Maik Broemme -.PP -The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/externals/libmpq/doc/man3/libmpq__archive_version.3 b/externals/libmpq/doc/man3/libmpq__archive_version.3 deleted file mode 100644 index 1764046895a..00000000000 --- a/externals/libmpq/doc/man3/libmpq__archive_version.3 +++ /dev/null @@ -1,48 +0,0 @@ -.\" Copyright (c) 2003-2008 Maik Broemme -.\" -.\" This is free documentation; 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. -.\" -.\" The GNU General Public License's references to "object code" -.\" and "executables" are to be interpreted as the output of any -.\" document formatting or typesetting system, including -.\" intermediate and printed output. -.\" -.\" This manual is distributed in the hope that it will be useful, -.\" but WITHOUT ANY WARRANTY; without even the implied warranty of -.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -.\" GNU General Public License for more details. -.\" -.\" You should have received a copy of the GNU General Public -.\" License along with this manual; if not, write to the Free -.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, -.\" USA. -.TH libmpq 3 2008-05-14 "The MoPaQ archive library" -.SH NAME -libmpq \- cross-platform C library for manipulating mpq archives. -.SH SYNOPSIS -.nf -.B -#include -.sp -.BI "int32_t libmpq__archive_version(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t *" "version" -.BI ");" -.fi -.SH DESCRIPTION -.PP -Call \fBlibmpq__archive_version\fP() to get the archive version. Currently there exist two known versions, version 1 which supports archives until 2GB total size and version 2 which supports archives above 2GB total size and both are supported. -.LP -The \fBlibmpq__archive_version\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument is a reference to the \fIversion\fP of archive. -.SH RETURN VALUE -On success, a zero is returned. -.SH AUTHOR -Check documentation. -.TP -libmpq is (c) 2003-2008 -.B Maik Broemme -.PP -The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/externals/libmpq/doc/man3/libmpq__block_close_offset.3 b/externals/libmpq/doc/man3/libmpq__block_close_offset.3 deleted file mode 100644 index 1ec0c06f70d..00000000000 --- a/externals/libmpq/doc/man3/libmpq__block_close_offset.3 +++ /dev/null @@ -1,53 +0,0 @@ -.\" Copyright (c) 2003-2008 Maik Broemme -.\" -.\" This is free documentation; 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. -.\" -.\" The GNU General Public License's references to "object code" -.\" and "executables" are to be interpreted as the output of any -.\" document formatting or typesetting system, including -.\" intermediate and printed output. -.\" -.\" This manual is distributed in the hope that it will be useful, -.\" but WITHOUT ANY WARRANTY; without even the implied warranty of -.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -.\" GNU General Public License for more details. -.\" -.\" You should have received a copy of the GNU General Public -.\" License along with this manual; if not, write to the Free -.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, -.\" USA. -.TH libmpq 3 2008-05-16 "The MoPaQ archive library" -.SH NAME -libmpq \- cross-platform C library for manipulating mpq archives. -.SH SYNOPSIS -.nf -.B -#include -.sp -.BI "int32_t libmpq__block_close_offset(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t " "file_number" -.BI ");" -.fi -.SH DESCRIPTION -.PP -Call \fBlibmpq__block_close_offset\fP() to close the block offset table for the given file. It will close the block offset table regardless of compression (compressed, imploded or stored) type of file. -.LP -The \fBlibmpq__block_close_offset\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument \fIfile_number\fP is the number of file to close. -.SH RETURN VALUE -On success, a zero is returned and on error one of the following constants. -.TP -.B LIBMPQ_ERROR_EXIST -File or block does not exist in archive. -.SH SEE ALSO -.BR libmpq__block_open_offset (3) -.SH AUTHOR -Check documentation. -.TP -libmpq is (c) 2003-2008 -.B Maik Broemme -.PP -The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/externals/libmpq/doc/man3/libmpq__block_open_offset.3 b/externals/libmpq/doc/man3/libmpq__block_open_offset.3 deleted file mode 100644 index a60b133f406..00000000000 --- a/externals/libmpq/doc/man3/libmpq__block_open_offset.3 +++ /dev/null @@ -1,65 +0,0 @@ -.\" Copyright (c) 2003-2008 Maik Broemme -.\" -.\" This is free documentation; 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. -.\" -.\" The GNU General Public License's references to "object code" -.\" and "executables" are to be interpreted as the output of any -.\" document formatting or typesetting system, including -.\" intermediate and printed output. -.\" -.\" This manual is distributed in the hope that it will be useful, -.\" but WITHOUT ANY WARRANTY; without even the implied warranty of -.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -.\" GNU General Public License for more details. -.\" -.\" You should have received a copy of the GNU General Public -.\" License along with this manual; if not, write to the Free -.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, -.\" USA. -.TH libmpq 3 2008-05-16 "The MoPaQ archive library" -.SH NAME -libmpq \- cross-platform C library for manipulating mpq archives. -.SH SYNOPSIS -.nf -.B -#include -.sp -.BI "int32_t libmpq__block_open_offset(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t " "file_number" -.BI ");" -.fi -.SH DESCRIPTION -.PP -Call \fBlibmpq__block_open_offset\fP() to open the block offset table for the given file. It will open the block offset table regardless of compression (compressed, imploded or stored) type of file. -.LP -The \fBlibmpq__block_open_offset\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument \fIfile_number\fP is the number of file to open. -.SH RETURN VALUE -On success, a zero is returned and on error one of the following constants. -.TP -.B LIBMPQ_ERROR_EXIST -File or block does not exist in archive. -.TP -.B LIBMPQ_ERROR_SEEK -Seeking in file failed. -.TP -.B LIBMPQ_ERROR_MALLOC -Not enough memory for creating required structures. -.TP -.B LIBMPQ_ERROR_READ -Reading in archive failed. -.TP -.B LIBMPQ_ERROR_DECRYPT -Decrypting block failed. -.SH SEE ALSO -.BR libmpq__block_close_offset (3) -.SH AUTHOR -Check documentation. -.TP -libmpq is (c) 2003-2008 -.B Maik Broemme -.PP -The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/externals/libmpq/doc/man3/libmpq__block_read.3 b/externals/libmpq/doc/man3/libmpq__block_read.3 deleted file mode 100644 index 3272c64c7ed..00000000000 --- a/externals/libmpq/doc/man3/libmpq__block_read.3 +++ /dev/null @@ -1,78 +0,0 @@ -.\" Copyright (c) 2003-2008 Maik Broemme -.\" -.\" This is free documentation; 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. -.\" -.\" The GNU General Public License's references to "object code" -.\" and "executables" are to be interpreted as the output of any -.\" document formatting or typesetting system, including -.\" intermediate and printed output. -.\" -.\" This manual is distributed in the hope that it will be useful, -.\" but WITHOUT ANY WARRANTY; without even the implied warranty of -.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -.\" GNU General Public License for more details. -.\" -.\" You should have received a copy of the GNU General Public -.\" License along with this manual; if not, write to the Free -.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, -.\" USA. -.TH libmpq 3 2008-05-16 "The MoPaQ archive library" -.SH NAME -libmpq \- cross-platform C library for manipulating mpq archives. -.SH SYNOPSIS -.nf -.B -#include -.sp -.BI "int32_t libmpq__block_read(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t " "file_number", -.BI " uint32_t " "block_number, -.BI " uint8_t *" "out_buf", -.BI " off_t " "out_size", -.BI " off_t " "transferred" -.BI ");" -.fi -.SH DESCRIPTION -.PP -Call \fBlibmpq__block_read\fP() to read a given block into memory. If the block is encrypted it will be first decrypted and then if it is packed (compressed or imploded) it will be unpacked. -.LP -The \fBlibmpq__block_read\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument \fIfile_number\fP is the number of file, the third argument \fIblock_number\fP is the number of block. The fourth argument \fIout_buf\fP is the output data buffer which contains the extracted data and the fifth argument \fIout_size\fP is the size of \fIout_buf\fP. The sixth argument is a reference to the \fItransferred\fP bytes of the file. -.SH RETURN VALUE -On success, a zero is returned and on error one of the following constants. -.TP -.B LIBMPQ_ERROR_EXIST -Block does not exist in archive. -.TP -.B LIBMPQ_ERROR_OPEN -Block offset table was not opened by calling \fBlibmpq__block_open_offset\fP(), or it was closed by an \fBlibmpq__block_close_offset\fP() call. -.TP -.B LIBMPQ_ERROR_SIZE -The output buffer is to small. -.TP -.B LIBMPQ_ERROR_SEEK -Seeking in file failed. -.TP -.B LIBMPQ_ERROR_MALLOC -Not enough memory for creating required structures. -.TP -.B LIBMPQ_ERROR_READ -Reading in archive failed. -.TP -.B LIBMPQ_ERROR_DECRYPT -Decrypting block failed. -.TP -.B LIBMPQ_ERROR_UNPACK -Unpacking block failed. -.SH SEE ALSO -.BR libmpq__file_read (3) -.SH AUTHOR -Check documentation. -.TP -libmpq is (c) 2003-2008 -.B Maik Broemme -.PP -The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/externals/libmpq/doc/man3/libmpq__block_unpacked_size.3 b/externals/libmpq/doc/man3/libmpq__block_unpacked_size.3 deleted file mode 100644 index a21ca48159a..00000000000 --- a/externals/libmpq/doc/man3/libmpq__block_unpacked_size.3 +++ /dev/null @@ -1,59 +0,0 @@ -.\" Copyright (c) 2003-2008 Maik Broemme -.\" -.\" This is free documentation; 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. -.\" -.\" The GNU General Public License's references to "object code" -.\" and "executables" are to be interpreted as the output of any -.\" document formatting or typesetting system, including -.\" intermediate and printed output. -.\" -.\" This manual is distributed in the hope that it will be useful, -.\" but WITHOUT ANY WARRANTY; without even the implied warranty of -.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -.\" GNU General Public License for more details. -.\" -.\" You should have received a copy of the GNU General Public -.\" License along with this manual; if not, write to the Free -.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, -.\" USA. -.TH libmpq 3 2008-05-16 "The MoPaQ archive library" -.SH NAME -libmpq \- cross-platform C library for manipulating mpq archives. -.SH SYNOPSIS -.nf -.B -#include -.sp -.BI "int32_t libmpq__block_unpacked_size(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t " "file_number", -.BI " uint32_t " "block_number", -.BI " off_t *" "unpacked_size" -.BI ");" -.fi -.SH DESCRIPTION -.PP -Call \fBlibmpq__block_unpacked_size\fP() to get the unpacked size of a given block in the file. It will return a valid size for compressed and imploded blocks as well as stored only. -.LP -The \fBlibmpq__block_unpacked_size\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument \fIfile_number\fP is the number of file, the third argument \fIblock_number\fP is the number of block and the fourth argument is a reference to the uncompressed, exploded or stored size \fIunpacked_size\fP of block. -.SH RETURN VALUE -On success, a zero is returned and on error one of the following constants. -.TP -.B LIBMPQ_ERROR_EXIST -File or block does not exist in archive. -.TP -.B LIBMPQ_ERROR_OPEN -Block offset table was not opened by calling \fBlibmpq__block_open_offset\fP(), or it was closed by an \fBlibmpq__block_close_offset\fP() call. -.SH SEE ALSO -.BR libmpq__archive_unpacked_size (3), -.BR libmpq__file_unpacked_size (3) -.SH AUTHOR -Check documentation. -.TP -libmpq is (c) 2003-2008 -.B Maik Broemme -.PP -The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/externals/libmpq/doc/man3/libmpq__file_blocks.3 b/externals/libmpq/doc/man3/libmpq__file_blocks.3 deleted file mode 100644 index 85baeffc603..00000000000 --- a/externals/libmpq/doc/man3/libmpq__file_blocks.3 +++ /dev/null @@ -1,54 +0,0 @@ -.\" Copyright (c) 2003-2008 Maik Broemme -.\" -.\" This is free documentation; 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. -.\" -.\" The GNU General Public License's references to "object code" -.\" and "executables" are to be interpreted as the output of any -.\" document formatting or typesetting system, including -.\" intermediate and printed output. -.\" -.\" This manual is distributed in the hope that it will be useful, -.\" but WITHOUT ANY WARRANTY; without even the implied warranty of -.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -.\" GNU General Public License for more details. -.\" -.\" You should have received a copy of the GNU General Public -.\" License along with this manual; if not, write to the Free -.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, -.\" USA. -.TH libmpq 3 2008-05-16 "The MoPaQ archive library" -.SH NAME -libmpq \- cross-platform C library for manipulating mpq archives. -.SH SYNOPSIS -.nf -.B -#include -.sp -.BI "int32_t libmpq__file_blocks(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t " "file_number", -.BI " uint32_t *" "blocks" -.BI ");" -.fi -.SH DESCRIPTION -.PP -Call \fBlibmpq__file_blocks\fP() to get the number of blocks for a given file. It will count all blocks for files stored in multiple sectors or count one for files stored in single sector. -.LP -The \fBlibmpq__file_blocks\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument \fIfile_number\fP is the number of file and the third argument is a reference to the number of \fIblocks\fP of the file. -.SH RETURN VALUE -On success, a zero is returned and on error one of the following constants. -.TP -.B LIBMPQ_ERROR_EXIST -File does not exist in archive. -.SH SEE ALSO -.BR libmpq__archive_files (3) -.SH AUTHOR -Check documentation. -.TP -libmpq is (c) 2003-2008 -.B Maik Broemme -.PP -The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/externals/libmpq/doc/man3/libmpq__file_compressed.3 b/externals/libmpq/doc/man3/libmpq__file_compressed.3 deleted file mode 100644 index 24b44f0b666..00000000000 --- a/externals/libmpq/doc/man3/libmpq__file_compressed.3 +++ /dev/null @@ -1,54 +0,0 @@ -.\" Copyright (c) 2003-2008 Maik Broemme -.\" -.\" This is free documentation; 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. -.\" -.\" The GNU General Public License's references to "object code" -.\" and "executables" are to be interpreted as the output of any -.\" document formatting or typesetting system, including -.\" intermediate and printed output. -.\" -.\" This manual is distributed in the hope that it will be useful, -.\" but WITHOUT ANY WARRANTY; without even the implied warranty of -.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -.\" GNU General Public License for more details. -.\" -.\" You should have received a copy of the GNU General Public -.\" License along with this manual; if not, write to the Free -.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, -.\" USA. -.TH libmpq 3 2008-05-16 "The MoPaQ archive library" -.SH NAME -libmpq \- cross-platform C library for manipulating mpq archives. -.SH SYNOPSIS -.nf -.B -#include -.sp -.BI "int32_t libmpq__file_compressed(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t " "file_number", -.BI " uint32_t *" "compressed" -.BI ");" -.fi -.SH DESCRIPTION -.PP -Call \fBlibmpq__file_compressed\fP() to get the compression status of the given file. It will return true for compressed files and false otherwise. -.LP -The \fBlibmpq__file_compressed\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument \fIfile_number\fP is the number of file and the third argument is a reference to the compression status \fIcompressed\fP of the file. -.SH RETURN VALUE -On success, a zero is returned and on error one of the following constants. -.TP -.B LIBMPQ_ERROR_EXIST -File does not exist in archive. -.SH SEE ALSO -.BR libmpq__archive_files (3) -.SH AUTHOR -Check documentation. -.TP -libmpq is (c) 2003-2008 -.B Maik Broemme -.PP -The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/externals/libmpq/doc/man3/libmpq__file_encrypted.3 b/externals/libmpq/doc/man3/libmpq__file_encrypted.3 deleted file mode 100644 index 798f4019c7a..00000000000 --- a/externals/libmpq/doc/man3/libmpq__file_encrypted.3 +++ /dev/null @@ -1,54 +0,0 @@ -.\" Copyright (c) 2003-2008 Maik Broemme -.\" -.\" This is free documentation; 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. -.\" -.\" The GNU General Public License's references to "object code" -.\" and "executables" are to be interpreted as the output of any -.\" document formatting or typesetting system, including -.\" intermediate and printed output. -.\" -.\" This manual is distributed in the hope that it will be useful, -.\" but WITHOUT ANY WARRANTY; without even the implied warranty of -.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -.\" GNU General Public License for more details. -.\" -.\" You should have received a copy of the GNU General Public -.\" License along with this manual; if not, write to the Free -.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, -.\" USA. -.TH libmpq 3 2008-05-16 "The MoPaQ archive library" -.SH NAME -libmpq \- cross-platform C library for manipulating mpq archives. -.SH SYNOPSIS -.nf -.B -#include -.sp -.BI "int32_t libmpq__file_encrypted(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t " "file_number", -.BI " uint32_t *" "encrypted" -.BI ");" -.fi -.SH DESCRIPTION -.PP -Call \fBlibmpq__file_encrypted\fP() to get the encryption status of the given file. It will return true for encrypted files and false otherwise. -.LP -The \fBlibmpq__file_encrypted\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument \fIfile_number\fP is the number of file and the third argument is a reference to the encryption status \fIencrypted\fP of the file. -.SH RETURN VALUE -On success, a zero is returned and on error one of the following constants. -.TP -.B LIBMPQ_ERROR_EXIST -File does not exist in archive. -.SH SEE ALSO -.BR libmpq__archive_files (3) -.SH AUTHOR -Check documentation. -.TP -libmpq is (c) 2003-2008 -.B Maik Broemme -.PP -The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/externals/libmpq/doc/man3/libmpq__file_imploded.3 b/externals/libmpq/doc/man3/libmpq__file_imploded.3 deleted file mode 100644 index 9adce38cb5f..00000000000 --- a/externals/libmpq/doc/man3/libmpq__file_imploded.3 +++ /dev/null @@ -1,54 +0,0 @@ -.\" Copyright (c) 2003-2008 Maik Broemme -.\" -.\" This is free documentation; 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. -.\" -.\" The GNU General Public License's references to "object code" -.\" and "executables" are to be interpreted as the output of any -.\" document formatting or typesetting system, including -.\" intermediate and printed output. -.\" -.\" This manual is distributed in the hope that it will be useful, -.\" but WITHOUT ANY WARRANTY; without even the implied warranty of -.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -.\" GNU General Public License for more details. -.\" -.\" You should have received a copy of the GNU General Public -.\" License along with this manual; if not, write to the Free -.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, -.\" USA. -.TH libmpq 3 2008-05-16 "The MoPaQ archive library" -.SH NAME -libmpq \- cross-platform C library for manipulating mpq archives. -.SH SYNOPSIS -.nf -.B -#include -.sp -.BI "int32_t libmpq__file_imploded(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t " "file_number", -.BI " uint32_t *" "imploded" -.BI ");" -.fi -.SH DESCRIPTION -.PP -Call \fBlibmpq__file_imploded\fP() to get the implosion status of the given file. It will return true for imploded files and false otherwise. -.LP -The \fBlibmpq__file_imploded\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument \fIfile_number\fP is the number of file and the third argument is a reference to the implosion status \fIimploded\fP of the file. -.SH RETURN VALUE -On success, a zero is returned and on error one of the following constants. -.TP -.B LIBMPQ_ERROR_EXIST -File does not exist in archive. -.SH SEE ALSO -.BR libmpq__archive_files (3) -.SH AUTHOR -Check documentation. -.TP -libmpq is (c) 2003-2008 -.B Maik Broemme -.PP -The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/externals/libmpq/doc/man3/libmpq__file_number.3 b/externals/libmpq/doc/man3/libmpq__file_number.3 deleted file mode 100644 index 8d7a47769ee..00000000000 --- a/externals/libmpq/doc/man3/libmpq__file_number.3 +++ /dev/null @@ -1,52 +0,0 @@ -.\" Copyright (c) 2003-2008 Maik Broemme -.\" -.\" This is free documentation; 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. -.\" -.\" The GNU General Public License's references to "object code" -.\" and "executables" are to be interpreted as the output of any -.\" document formatting or typesetting system, including -.\" intermediate and printed output. -.\" -.\" This manual is distributed in the hope that it will be useful, -.\" but WITHOUT ANY WARRANTY; without even the implied warranty of -.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -.\" GNU General Public License for more details. -.\" -.\" You should have received a copy of the GNU General Public -.\" License along with this manual; if not, write to the Free -.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, -.\" USA. -.TH libmpq 3 2008-05-16 "The MoPaQ archive library" -.SH NAME -libmpq \- cross-platform C library for manipulating mpq archives. -.SH SYNOPSIS -.nf -.B -#include -.sp -.BI "int32_t libmpq__file_number(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " const char *" "filename", -.BI " uint32_t *" "number" -.BI ");" -.fi -.SH DESCRIPTION -.PP -Call \fBlibmpq__file_number\fP() to get the number of a given file in the archive. This function will return a file number regardless of a known or opened listfile. -.LP -The \fBlibmpq__file_number\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument \fIfilename\fP is the name of the file and the third argument is a reference to the \fInumber\fP of the file. -.SH RETURN VALUE -On success, the number of the file is returned and on error one of the following constants. -.TP -.B LIBMPQ_ERROR_EXIST -File does not exist in archive. -.SH AUTHOR -Check documentation. -.TP -libmpq is (c) 2003-2008 -.B Maik Broemme -.PP -The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/externals/libmpq/doc/man3/libmpq__file_offset.3 b/externals/libmpq/doc/man3/libmpq__file_offset.3 deleted file mode 100644 index 392a66d0b04..00000000000 --- a/externals/libmpq/doc/man3/libmpq__file_offset.3 +++ /dev/null @@ -1,55 +0,0 @@ -.\" Copyright (c) 2003-2008 Maik Broemme -.\" -.\" This is free documentation; 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. -.\" -.\" The GNU General Public License's references to "object code" -.\" and "executables" are to be interpreted as the output of any -.\" document formatting or typesetting system, including -.\" intermediate and printed output. -.\" -.\" This manual is distributed in the hope that it will be useful, -.\" but WITHOUT ANY WARRANTY; without even the implied warranty of -.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -.\" GNU General Public License for more details. -.\" -.\" You should have received a copy of the GNU General Public -.\" License along with this manual; if not, write to the Free -.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, -.\" USA. -.TH libmpq 3 2008-05-15 "The MoPaQ archive library" -.SH NAME -libmpq \- cross-platform C library for manipulating mpq archives. -.SH SYNOPSIS -.nf -.B -#include -.sp -.BI "int32_t libmpq__file_offset(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t " "file_number", -.BI " off_t *" "offset" -.BI ");" -.fi -.SH DESCRIPTION -.PP -Call \fBlibmpq__file_offset\fP() to get the offset of the file, which is the absolute position in the archive. It also supports archives within archives. -.LP -The \fBlibmpq__file_offset\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument \fIfile_number\fP is the number of file and the third argument is a reference to the file starting position \fIoffset\fP in archive. -.SH RETURN VALUE -On success, a zero is returned and on error one of the following constants. -.TP -.B LIBMPQ_ERROR_EXIST -File does not exist in archive. -.SH SEE ALSO -.BR libmpq__archive_offset (3), -.BR libmpq__block_offset (3) -.SH AUTHOR -Check documentation. -.TP -libmpq is (c) 2003-2008 -.B Maik Broemme -.PP -The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/externals/libmpq/doc/man3/libmpq__file_packed_size.3 b/externals/libmpq/doc/man3/libmpq__file_packed_size.3 deleted file mode 100644 index b584ddf77dd..00000000000 --- a/externals/libmpq/doc/man3/libmpq__file_packed_size.3 +++ /dev/null @@ -1,55 +0,0 @@ -.\" Copyright (c) 2003-2008 Maik Broemme -.\" -.\" This is free documentation; 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. -.\" -.\" The GNU General Public License's references to "object code" -.\" and "executables" are to be interpreted as the output of any -.\" document formatting or typesetting system, including -.\" intermediate and printed output. -.\" -.\" This manual is distributed in the hope that it will be useful, -.\" but WITHOUT ANY WARRANTY; without even the implied warranty of -.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -.\" GNU General Public License for more details. -.\" -.\" You should have received a copy of the GNU General Public -.\" License along with this manual; if not, write to the Free -.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, -.\" USA. -.TH libmpq 3 2008-05-15 "The MoPaQ archive library" -.SH NAME -libmpq \- cross-platform C library for manipulating mpq archives. -.SH SYNOPSIS -.nf -.B -#include -.sp -.BI "int32_t libmpq__file_packed_size(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t " "file_number", -.BI " off_t *" "packed_size" -.BI ");" -.fi -.SH DESCRIPTION -.PP -Call \fBlibmpq__file_packed_size\fP() to get the packed size of a given file in the archive. It will return a valid size for compressed and imploded files as well as stored only. -.LP -The \fBlibmpq__file_packed_size\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument \fIfile_number\fP is the number of file and the third argument is a reference to the compressed, imploded or stored size \fIpacked_size\fP of file. -.SH RETURN VALUE -On success, a zero is returned and on error one of the following constants. -.TP -.B LIBMPQ_ERROR_EXIST -File does not exist in archive. -.SH SEE ALSO -.BR libmpq__archive_packed_size (3), -.BR libmpq__block_packed_size (3) -.SH AUTHOR -Check documentation. -.TP -libmpq is (c) 2003-2008 -.B Maik Broemme -.PP -The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/externals/libmpq/doc/man3/libmpq__file_read.3 b/externals/libmpq/doc/man3/libmpq__file_read.3 deleted file mode 100644 index cbfafbd0f4f..00000000000 --- a/externals/libmpq/doc/man3/libmpq__file_read.3 +++ /dev/null @@ -1,77 +0,0 @@ -.\" Copyright (c) 2003-2008 Maik Broemme -.\" -.\" This is free documentation; 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. -.\" -.\" The GNU General Public License's references to "object code" -.\" and "executables" are to be interpreted as the output of any -.\" document formatting or typesetting system, including -.\" intermediate and printed output. -.\" -.\" This manual is distributed in the hope that it will be useful, -.\" but WITHOUT ANY WARRANTY; without even the implied warranty of -.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -.\" GNU General Public License for more details. -.\" -.\" You should have received a copy of the GNU General Public -.\" License along with this manual; if not, write to the Free -.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, -.\" USA. -.TH libmpq 3 2008-05-16 "The MoPaQ archive library" -.SH NAME -libmpq \- cross-platform C library for manipulating mpq archives. -.SH SYNOPSIS -.nf -.B -#include -.sp -.BI "int32_t libmpq__file_read(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t " "file_number", -.BI " uint8_t *" "out_buf", -.BI " off_t " "out_size", -.BI " off_t *" "transferred" -.BI ");" -.fi -.SH DESCRIPTION -.PP -Call \fBlibmpq__file_read\fP() to read a given file into memory. If the file is encrypted it will be first decrypted and then if it is packed (compressed or imploded) it will be unpacked. -.LP -The \fBlibmpq__file_read\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument \fIfile_number\fP is the file to extract, the third argument \fIout_buf\fP is the output data buffer which contains the extracted data. The fourth argument \fIout_size\fP is the size of \fIout_buf\fP and the fifth argument is a reference to the \fItransferred\fP bytes of the file. -.SH RETURN VALUE -On success, a zero is returned and on error one of the following constants. -.TP -.B LIBMPQ_ERROR_EXIST -File does not exist in archive. -.TP -.B LIBMPQ_ERROR_OPEN -Block offset table was not opened by calling \fBlibmpq__block_open_offset\fP(), or it was closed by an \fBlibmpq__block_close_offset\fP() call. -.TP -.B LIBMPQ_ERROR_SIZE -The output buffer is to small. -.TP -.B LIBMPQ_ERROR_SEEK -Seeking in file failed. -.TP -.B LIBMPQ_ERROR_MALLOC -Not enough memory for creating required structures. -.TP -.B LIBMPQ_ERROR_READ -Reading in archive failed. -.TP -.B LIBMPQ_ERROR_DECRYPT -Decrypting file failed. -.TP -.B LIBMPQ_ERROR_UNPACK -Unpacking file failed. -.SH SEE ALSO -.BR libmpq__block_read (3) -.SH AUTHOR -Check documentation. -.TP -libmpq is (c) 2003-2008 -.B Maik Broemme -.PP -The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/externals/libmpq/doc/man3/libmpq__file_unpacked_size.3 b/externals/libmpq/doc/man3/libmpq__file_unpacked_size.3 deleted file mode 100644 index a81cf7a4e76..00000000000 --- a/externals/libmpq/doc/man3/libmpq__file_unpacked_size.3 +++ /dev/null @@ -1,55 +0,0 @@ -.\" Copyright (c) 2003-2008 Maik Broemme -.\" -.\" This is free documentation; 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. -.\" -.\" The GNU General Public License's references to "object code" -.\" and "executables" are to be interpreted as the output of any -.\" document formatting or typesetting system, including -.\" intermediate and printed output. -.\" -.\" This manual is distributed in the hope that it will be useful, -.\" but WITHOUT ANY WARRANTY; without even the implied warranty of -.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -.\" GNU General Public License for more details. -.\" -.\" You should have received a copy of the GNU General Public -.\" License along with this manual; if not, write to the Free -.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, -.\" USA. -.TH libmpq 3 2008-05-15 "The MoPaQ archive library" -.SH NAME -libmpq \- cross-platform C library for manipulating mpq archives. -.SH SYNOPSIS -.nf -.B -#include -.sp -.BI "int32_t libmpq__file_unpacked_size(" -.BI " mpq_archive_s *" "mpq_archive", -.BI " uint32_t " "file_number", -.BI " off_t *" "unpacked_size" -.BI ");" -.fi -.SH DESCRIPTION -.PP -Call \fBlibmpq__file_unpacked_size\fP() to get the unpacked size of a given file in the archive. It will return a valid size for compressed and imploded files as well as stored only. -.LP -The \fBlibmpq__file_unpacked_size\fP() function takes as first argument the archive structure \fImpq_archive\fP which have to be allocated first and opened by \fBlibmpq__archive_open\fP(). The second argument \fIfile_number\fP is the number of file and the third argument is a reference to the uncompressed, exploded or stored size \fIunpacked_size\fP of file. -.SH RETURN VALUE -On success, a zero is returned and on error one of the following constants. -.TP -.B LIBMPQ_ERROR_EXIST -File does not exist in archive. -.SH SEE ALSO -.BR libmpq__archive_unpacked_size (3), -.BR libmpq__block_unpacked_size (3) -.SH AUTHOR -Check documentation. -.TP -libmpq is (c) 2003-2008 -.B Maik Broemme -.PP -The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/externals/libmpq/doc/man3/libmpq__strerror.3 b/externals/libmpq/doc/man3/libmpq__strerror.3 deleted file mode 100644 index 246f422eed0..00000000000 --- a/externals/libmpq/doc/man3/libmpq__strerror.3 +++ /dev/null @@ -1,45 +0,0 @@ -.\" Copyright (c) 2010 Georg Lukas -.\" -.\" This is free documentation; 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. -.\" -.\" The GNU General Public License's references to "object code" -.\" and "executables" are to be interpreted as the output of any -.\" document formatting or typesetting system, including -.\" intermediate and printed output. -.\" -.\" This manual is distributed in the hope that it will be useful, -.\" but WITHOUT ANY WARRANTY; without even the implied warranty of -.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -.\" GNU General Public License for more details. -.\" -.\" You should have received a copy of the GNU General Public -.\" License along with this manual; if not, write to the Free -.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, -.\" USA. -.TH libmpq 3 2010-07-18 "The MoPaQ archive library" -.SH NAME -libmpq__strerror \- return string describing libmpq error number -.SH SYNOPSIS -.nf -.B -#include -.sp -.BI "const char *libmpq__strerror(int32_t returncode);" -.fi -.SH DESCRIPTION -.PP -Call \fBlibmpq__strerror\fP() to get a string message for the return code of one of the other libmpq functions. -.SH RETURN VALUE -The function returns a string pointer to non-writable memory or NULL if \fBreturncode\fP is not a return code of a libmpq function. -.SH SEE ALSO -.BR libmpq (3), strerror (3) -.SH AUTHOR -Check documentation. -.TP -libmpq is (c) 2003-2008 -.B Maik Broemme -.PP -The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/externals/libmpq/doc/man3/libmpq__version.3 b/externals/libmpq/doc/man3/libmpq__version.3 deleted file mode 100644 index 5500d7314f5..00000000000 --- a/externals/libmpq/doc/man3/libmpq__version.3 +++ /dev/null @@ -1,45 +0,0 @@ -.\" Copyright (c) 2003-2008 Maik Broemme -.\" -.\" This is free documentation; 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. -.\" -.\" The GNU General Public License's references to "object code" -.\" and "executables" are to be interpreted as the output of any -.\" document formatting or typesetting system, including -.\" intermediate and printed output. -.\" -.\" This manual is distributed in the hope that it will be useful, -.\" but WITHOUT ANY WARRANTY; without even the implied warranty of -.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -.\" GNU General Public License for more details. -.\" -.\" You should have received a copy of the GNU General Public -.\" License along with this manual; if not, write to the Free -.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, -.\" USA. -.TH libmpq 3 2008-03-31 "The MoPaQ archive library" -.SH NAME -libmpq \- cross-platform C library for manipulating mpq archives. -.SH SYNOPSIS -.nf -.B -#include -.sp -.BI "const char *libmpq__version();" -.fi -.SH DESCRIPTION -.PP -Call \fBlibmpq__version\fP() to get information about the version of the library, it is useful to create minimum required version verifications. -.SH RETURN VALUE -The function returns the library version. -.SH SEE ALSO -.BR libmpq (3) -.SH AUTHOR -Check documentation. -.TP -libmpq is (c) 2003-2008 -.B Maik Broemme -.PP -The above e-mail address can be used to send bug reports, feedbacks or library enhancements. diff --git a/externals/libmpq/libmpq-config.in b/externals/libmpq/libmpq-config.in deleted file mode 100644 index d345efdbe09..00000000000 --- a/externals/libmpq/libmpq-config.in +++ /dev/null @@ -1,57 +0,0 @@ -#!/bin/sh - -prefix="@prefix@" -exec_prefix="@exec_prefix@" -exec_prefix_set=no - -usage="\ -Usage: libmpq-config [--prefix[=DIR]] [--exec-prefix[=DIR]] [--version] [--libs] [--cflags]" - -if test "$#" -eq "0"; then - echo "${usage}" 1>&2 - exit 1 -fi - -while test "$#" -gt "0"; do - case "$1" in - -*=*) optarg=`echo "$1" | sed 's/[-_a-zA-Z0-9]*=//'` ;; - *) optarg= ;; - esac - - case "$1" in - --prefix=*) - prefix="$optarg" - if test "$exec_prefix_set" = "no" ; then - exec_prefix="$optarg" - fi - ;; - --prefix) - echo "$prefix" - ;; - --exec-prefix=*) - exec_prefix="$optarg" - exec_prefix_set=yes - ;; - --exec-prefix) - echo "$exec_prefix" - ;; - --version) - echo "@VERSION@" - ;; - --cflags) - largefile="@LFS_CFLAGS@" - includes=-I@includedir@/libmpq - echo "$includes $largefile" - ;; - --libs) - libdirs="-L@libdir@" - echo "$libdirs -lmpq" - ;; - *) - echo "${usage}" 1>&2 - exit 1 - ;; - esac - shift -done - diff --git a/externals/libmpq/libmpq.pc.in b/externals/libmpq/libmpq.pc.in deleted file mode 100644 index 8c53bea35a0..00000000000 --- a/externals/libmpq/libmpq.pc.in +++ /dev/null @@ -1,10 +0,0 @@ -prefix=@prefix@ -exec_prefix=@exec_prefix@ -libdir=@libdir@ -includedir=@includedir@ - -Name: libmpq -Description: GPL version of the libmpq library -Version: @VERSION@ -Libs: -L${libdir} -lmpq -Cflags: -I${includedir}/libmpq @LFS_CFLAGS@ diff --git a/externals/libmpq/libmpq/Makefile.am b/externals/libmpq/libmpq/Makefile.am deleted file mode 100644 index 409e3dfe02f..00000000000 --- a/externals/libmpq/libmpq/Makefile.am +++ /dev/null @@ -1,23 +0,0 @@ -# minimum required automake 1.6 -AUTOMAKE_OPTIONS = 1.6 - -# library information and headers which should not be installed. -lib_LTLIBRARIES = libmpq.la -noinst_HEADERS = common.h explode.h extract.h huffman.h mpq-internal.h wave.h - -# directory where the include files will be installed. -libmpq_includedir = $(includedir)/libmpq - -# header files to install. -libmpq_include_HEADERS = mpq.h - -libmpq_la_SOURCES = $(GENERAL_SRCS) -libmpq_la_LDFLAGS = -release $(PACKAGE_VERSION) - -GENERAL_SRCS = \ - common.c \ - huffman.c \ - extract.c \ - explode.c \ - mpq.c \ - wave.c diff --git a/externals/libmpq/libmpq/common.c b/externals/libmpq/libmpq/common.c deleted file mode 100644 index 879bd902b58..00000000000 --- a/externals/libmpq/libmpq/common.c +++ /dev/null @@ -1,220 +0,0 @@ -/* - * common.c -- shared functions used by mpq-tools. - * - * Copyright (c) 2003-2008 Maik Broemme - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ - -/* generic includes. */ -#include -#include -#include -#include - -/* libmpq main includes. */ -#include "mpq.h" -#include "mpq-internal.h" - -/* libmpq generic includes. */ -#include "extract.h" - -#include "common.h" - -/* the global shared decryption buffer. it's a static array compiled into the - * library, and can be re-created by compiling and running crypt_buf_gen.c - */ -#include "crypt_buf.h" - -/* function to return the hash to a given string. */ -uint32_t libmpq__hash_string(const char *key, uint32_t offset) { - - /* some common variables. */ - uint32_t seed1 = 0x7FED7FED; - uint32_t seed2 = 0xEEEEEEEE; - - /* one key character. */ - uint32_t ch; - - /* prepare seeds. */ - while (*key != 0) { - ch = toupper(*key++); - seed1 = crypt_buf[offset + ch] ^ (seed1 + seed2); - seed2 = ch + seed1 + seed2 + (seed2 << 5) + 3; - } - - return seed1; -} - -/* function to encrypt a block. */ -int32_t libmpq__encrypt_block(uint32_t *in_buf, uint32_t in_size, uint32_t seed) { - - /* some common variables. */ - uint32_t seed2 = 0xEEEEEEEE; - uint32_t ch; - - /* we're processing the data 4 bytes at a time. */ - for (; in_size >= 4; in_size -= 4) { - seed2 += crypt_buf[0x400 + (seed & 0xFF)]; - ch = *in_buf ^ (seed + seed2); - seed = ((~seed << 0x15) + 0x11111111) | (seed >> 0x0B); - seed2 = *in_buf + seed2 + (seed2 << 5) + 3; - *in_buf++ = ch; - } - - /* if no error was found, return decrypted bytes. */ - return LIBMPQ_SUCCESS; -} - - -/* function to decrypt a block. */ -int32_t libmpq__decrypt_block(uint32_t *in_buf, uint32_t in_size, uint32_t seed) { - - /* some common variables. */ - uint32_t seed2 = 0xEEEEEEEE; - uint32_t ch; - - /* we're processing the data 4 bytes at a time. */ - for (; in_size >= 4; in_size -= 4) { - seed2 += crypt_buf[0x400 + (seed & 0xFF)]; - ch = *in_buf ^ (seed + seed2); - seed = ((~seed << 0x15) + 0x11111111) | (seed >> 0x0B); - seed2 = ch + seed2 + (seed2 << 5) + 3; - *in_buf++ = ch; - } - - /* if no error was found, return decrypted bytes. */ - return LIBMPQ_SUCCESS; -} - -/* function to detect decryption key. */ -int32_t libmpq__decrypt_key(uint8_t *in_buf, uint32_t in_size, uint32_t block_size, uint32_t *key) { - - /* some common variables. */ - uint32_t saveseed1; - - /* temp = seed1 + seed2 */ - uint32_t temp; - uint32_t i = 0; - - /* temp = seed1 + buffer[0x400 + (seed1 & 0xFF)] */ - temp = (*(uint32_t *)in_buf ^ in_size) - 0xEEEEEEEE; - - /* try all 255 possibilities. */ - for (i = 0; i < 0x100; i++) { - - /* some common variables. */ - uint32_t seed1; - uint32_t seed2 = 0xEEEEEEEE; - uint32_t ch; - uint32_t ch2; - - /* try the first uint32_t's (we exactly know the value). */ - seed1 = temp - crypt_buf[0x400 + i]; - seed2 += crypt_buf[0x400 + (seed1 & 0xFF)]; - ch = ((uint32_t *)in_buf)[0] ^ (seed1 + seed2); - - if (ch != in_size) { - continue; - } - - /* add one because we are decrypting block positions. */ - saveseed1 = seed1 + 1; - ch2 = ch; - - /* - * if ok, continue and test the second value. we don't know exactly the value, - * but we know that the second one has lower 16 bits set to zero (no compressed - * block is larger than 0xFFFF bytes) - */ - seed1 = ((~seed1 << 0x15) + 0x11111111) | (seed1 >> 0x0B); - seed2 = ch + seed2 + (seed2 << 5) + 3; - seed2 += crypt_buf[0x400 + (seed1 & 0xFF)]; - ch = ((uint32_t *)in_buf)[1] ^ (seed1 + seed2); - - /* check if we found the file seed. */ - if ((ch - ch2) <= block_size) { - - /* file seed found, so return it. */ - *key = saveseed1; - return LIBMPQ_SUCCESS; - } - } - - /* if no file seed was found return with error. */ - return LIBMPQ_ERROR_DECRYPT; -} - -/* function to decompress or explode a block from mpq archive. */ -int32_t libmpq__decompress_block(uint8_t *in_buf, uint32_t in_size, uint8_t *out_buf, uint32_t out_size, uint32_t compression_type) { - - /* some common variables. */ - int32_t tb = 0; - - /* check if buffer is not compressed. */ - if (compression_type == LIBMPQ_FLAG_COMPRESS_NONE) { - - /* no compressed data, so copy input buffer to output buffer. */ - memcpy(out_buf, in_buf, out_size); - - /* store number of bytes copied. */ - tb = out_size; - } - - /* check if one compression mode is used. */ - else if (compression_type == LIBMPQ_FLAG_COMPRESS_PKZIP || - compression_type == LIBMPQ_FLAG_COMPRESS_MULTI) { - - /* check if block is really compressed, some blocks have set the compression flag, but are not compressed. */ - if (in_size < out_size) { - - /* check if we are using pkzip compression algorithm. */ - if (compression_type == LIBMPQ_FLAG_COMPRESS_PKZIP) { - - /* decompress using pkzip. */ - if ((tb = libmpq__decompress_pkzip(in_buf, in_size, out_buf, out_size)) < 0) { - - /* something on decompression failed. */ - return tb; - } - } - - /* check if we are using multiple compression algorithm. */ - else if (compression_type == LIBMPQ_FLAG_COMPRESS_MULTI) { - - /* - * check if it is a file compressed by blizzard's multiple compression, note that storm.dll - * version 1.0.9 distributed with warcraft 3 passes the full path name of the opened archive - * as the new last parameter. - */ - if ((tb = libmpq__decompress_multi(in_buf, in_size, out_buf, out_size)) < 0) { - - /* something on decompression failed. */ - return tb; - } - } - } else { - - /* block has set compression flag, but is not compressed, so copy data to output buffer. */ - memcpy(out_buf, in_buf, out_size); - - /* save the number of transferred bytes. */ - tb = in_size; - } - } - - /* if no error was found, return transferred bytes. */ - return tb; -} diff --git a/externals/libmpq/libmpq/common.h b/externals/libmpq/libmpq/common.h deleted file mode 100644 index b9e03126434..00000000000 --- a/externals/libmpq/libmpq/common.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * common.h -- header functions used by mpq-tools. - * - * Copyright (c) 2003-2008 Maik Broemme - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ - -#ifndef _COMMON_H -#define _COMMON_H - -/* function to return the hash to a given string. */ -uint32_t libmpq__hash_string( - const char *key, - uint32_t offset -); - -/* function to encrypt a block. */ -int32_t libmpq__encrypt_block( - uint32_t *in_buf, - uint32_t in_size, - uint32_t seed -); - -/* function to decrypt a block. */ -int32_t libmpq__decrypt_block( - uint32_t *in_buf, - uint32_t in_size, - uint32_t seed -); - -/* function to detect decryption key. */ -int32_t libmpq__decrypt_key( - uint8_t *in_buf, - uint32_t in_size, - uint32_t block_size, - uint32_t *key -); - -/* function to decompress or explode block from archive. */ -int32_t libmpq__decompress_block( - uint8_t *in_buf, - uint32_t in_size, - uint8_t *out_buf, - uint32_t out_size, - uint32_t compression_type -); - -#endif /* _COMMON_H */ diff --git a/externals/libmpq/libmpq/crypt_buf.h b/externals/libmpq/libmpq/crypt_buf.h deleted file mode 100644 index 34184b017fe..00000000000 --- a/externals/libmpq/libmpq/crypt_buf.h +++ /dev/null @@ -1,217 +0,0 @@ -/* DO NOT CHANGE! this file is auto-generated by crypt_buf_gen.c */ -static const uint32_t crypt_buf[0x500] = { - 0x55c636e2, 0x02be0170, 0x584b71d4, 0x2984f00e, 0xb682c809, 0x91cf876b, - 0x775a9c24, 0x597d5ca5, 0x5a1afeb2, 0xd3e9ce0d, 0x32cdcdf8, 0xb18201cd, - 0x3cce05ce, 0xa55d13be, 0xbb0afe71, 0x9376ab33, 0x848f645e, 0x87e45a45, - 0x45b86017, 0x5e656ca8, 0x1b851a95, 0x2542dbd7, 0xab4df9e4, 0x5976ae9b, - 0x6c317e7d, 0xcddd2f94, 0x3c3c13e5, 0x335b1371, 0x31a592ca, 0x51e4fc4c, - 0xf7db5b2f, 0x8abdbe41, 0x8beaa674, 0x20d6b319, 0xde6c9a9d, 0xc5ac84e5, - 0x445a5feb, 0x94958cb0, 0x1e7d3847, 0xf35d29b0, 0xca5cceda, 0xb732c8b5, - 0xfdcc41dd, 0x0edcec16, 0x9d01feae, 0x1165d38e, 0x9ee193c8, 0xbf33b13c, - 0x61bc0dfc, 0xef3e7be9, 0xf8d4d4c5, 0xc79b7694, 0x5a255943, 0x0b3dd20a, - 0x9d1ab5a3, 0xcfa8ba57, 0x5e6d7069, 0xcb89b731, 0x3dc0d15b, 0x0d4d7e7e, - 0x97e37f2b, 0xfefc2bb1, 0xf95b16b5, 0x27a55b93, 0x45f22729, 0x4c986630, - 0x7c666862, 0x5fa40847, 0xa3f16205, 0x791b7764, 0x386b36d6, 0x6e6c3fef, - 0xc75855db, 0x4abc7dc7, 0x4a328f9b, 0xcef20c0f, 0x60b88f07, 0xf7bb4b8f, - 0x830b5192, 0x94f711ec, 0x20250752, 0x399d21a3, 0xe5c0840d, 0xe76cffa5, - 0x624fab29, 0x5df133e6, 0x83e0b9b8, 0xc5796bfb, 0x4a7ab2d0, 0xba59a821, - 0x03a81e4c, 0xcd3adfdb, 0x32b26b8c, 0x8e35c533, 0x9e6300e9, 0x8cf92ac5, - 0x880d18eb, 0x131a53b3, 0x2ed2dc64, 0xb23257c1, 0xa06450c1, 0x1b92cb8e, - 0x72ed730e, 0x19a685f0, 0x82836483, 0x42d94e8a, 0xee9bd6f6, 0x556d0b6a, - 0xba65589a, 0xde24cce4, 0x53329f6c, 0xc754fe8b, 0x503d2dc7, 0x10027ba4, - 0xd3b60a8b, 0x68e68d83, 0x0a9128a9, 0x595fa35f, 0x0b03b5be, 0x150a45c4, - 0xb1629cce, 0xe5f7497b, 0x8a7098a4, 0xb8233e69, 0x8ea0f978, 0x5b579970, - 0xeab14318, 0x4b28b263, 0xb6766cef, 0x06782877, 0x155c6dd0, 0xc711333c, - 0xf819cedf, 0x00eb1d68, 0xd6fffa6e, 0x439e5962, 0xd765d6db, 0xcb0bcee9, - 0x6d3c5647, 0x965466f3, 0x0ca983c9, 0x74ecc1ce, 0xfc0563b6, 0x42b08fee, - 0xc5b38853, 0xfe502ceb, 0x7b432faf, 0xc309e610, 0x2c3997d8, 0x43774654, - 0x15bd9d2c, 0xed6a420d, 0xc7ff520c, 0xb8a97fd1, 0x5e4d60cc, 0xb9738d11, - 0xda2181ff, 0x73ac2597, 0x3a8eec8d, 0xac85e779, 0xf3f975d6, 0xb9fe7b91, - 0x0f155d1e, 0x2860b6dd, 0x835977cb, 0xb0607436, 0x9cab7f6b, 0x8ab91186, - 0xc12b51e9, 0x20084e8b, 0x44ba8ead, 0xa542b130, 0x82bcd5c4, 0xcc747f4e, - 0x0f1909d8, 0xda242e1c, 0x6f7d1aa0, 0xd2626486, 0x88d0781e, 0xab695ccd, - 0xfa569145, 0xb4feb55c, 0xbe47e896, 0xe70a7a88, 0xd56185a2, 0xacf4c871, - 0x09282332, 0x1ddeeaa8, 0x590c7adb, 0xf4a97667, 0xbfd85705, 0x0ea77ccc, - 0xa9f85364, 0x83195869, 0x8bfb041a, 0xdb842f5c, 0xd6f0f315, 0xa7756ea7, - 0x0a51b439, 0xa9edf8a3, 0xd9084e2f, 0x827407f8, 0xd4ac8284, 0x09739d0d, - 0xb3bb6cfc, 0xd539c77d, 0x6bbc9ac0, 0x35c641aa, 0x934c96b0, 0xd17af317, - 0x29c6baef, 0xb275cdac, 0xd72662de, 0x9f5c2544, 0xc1a98f75, 0xd98e8f9a, - 0x47bd5c86, 0x70c610a6, 0xb5482ed4, 0x23b9c68c, 0x3c1bae66, 0x69556e7f, - 0xd902f5e0, 0x653d195b, 0xde6541fb, 0x07bcc6ac, 0xc6ee7788, 0x801534d4, - 0x2c1f35c0, 0xd9de614d, 0xbdccac85, 0xb4d4a0da, 0x242d549b, 0x9d964796, - 0xb9ceb982, 0x59fa99a9, 0xd8986cc1, 0x9e90c1a1, 0x01bbd82f, 0xd7f1c5fd, - 0xdd847eba, 0x883d305d, 0x25f13152, 0x4a92694d, 0x77f1e601, 0x8024e6e7, - 0x02a5f53d, 0x9c3ef4d9, 0xaf403ccc, 0xe2ad03c0, 0x46edf6ec, 0x6f9bd3e6, - 0xcc24ad7a, 0x47afab12, 0x82298df7, 0x708c9eec, 0x76f8c1b1, 0xb39459d2, - 0x3f1e26d9, 0xe1811be7, 0x56ed1c4d, 0xc9d18af8, 0xe828060e, 0x91cada2e, - 0x5ccbf9b7, 0xf1a552d4, 0x3c9d4343, 0xe1008785, 0x2adfeebf, 0xf90240a0, - 0x3d08cce7, 0x426e6fb0, 0x573c984f, 0x13a843ae, 0x406b7439, 0x636085d9, - 0x5000ba9a, 0xad4a47ab, 0xaf001d8d, 0x419907ae, 0x185c8f96, 0xe5e9ed4d, - 0x61764133, 0xd3703d97, 0xac98f0c6, 0xdbc3a37c, 0x85f010c4, 0x90491e32, - 0xf12e18bf, 0xc88c96e1, 0xd3fbd6d9, 0xe3c28b08, 0xd5bf08cc, 0xb1e78859, - 0x2546ddcf, 0xb030b200, 0xaafd2811, 0x55b22d21, 0xd38bf567, 0x469c7a2b, - 0x5ad05792, 0xa1a5981e, 0x7dfb8384, 0x34d1ca0a, 0x7eb0dbe0, 0xd61ce0f6, - 0x398068b7, 0xe6406d1f, 0x95ae6b47, 0xe4281230, 0xb0843061, 0xa70a3a68, - 0xe340f625, 0x72dcbffd, 0x8eb8afcd, 0x18b6661f, 0x17ef5a5c, 0x000c5b22, - 0x6ba13836, 0x6165e383, 0x74481c5b, 0xe56f0711, 0xa26f5024, 0x5ff22e60, - 0x31a5e829, 0xa1094bf0, 0xc680ec6c, 0x8cf327d7, 0xebf1348a, 0x6a227d2f, - 0x74065184, 0x8df65112, 0x2bbd05ee, 0xe4d00ed6, 0x2980ee1a, 0x6ae1da73, - 0xe84614da, 0x6c9906ab, 0xcf8e02db, 0xd3723e97, 0x92f66caf, 0xac8491c7, - 0xaec65696, 0xb98997cf, 0xfa16c762, 0x6d73c65f, 0x205d22a6, 0x4dd3aaa5, - 0x2deb6bc0, 0x9f37686c, 0x71a5282b, 0x376bb9e0, 0x7fff2a1b, 0xde67982f, - 0x9cbf33ce, 0x2e6dab37, 0x6e3424b9, 0x0ee143bc, 0x832a60d9, 0xbb6329e1, - 0x13f6befd, 0x5965fb84, 0xf60b233c, 0x3d695183, 0x433224a1, 0xb5d9cae5, - 0x82459bab, 0x9f21b311, 0xaf6c5247, 0xb447b13a, 0x7b2676c3, 0xc38979cd, - 0x8526ae25, 0xc550ad5b, 0x685099a7, 0x65e9c2bd, 0xe5c6dc36, 0xe10b37a9, - 0x88016878, 0xce81d4e4, 0x24d6fc80, 0x4106152d, 0x6d4f5f90, 0xc4dc74be, - 0xdb48676c, 0x6cb569b7, 0xf3bf598f, 0x042b08d9, 0x02ccb2de, 0xb1056f65, - 0x47994af4, 0xfa141ba4, 0x9376ab2e, 0x07a76737, 0x75e7e6fc, 0x449d80a1, - 0x03b7259d, 0xf6df358a, 0x5a75d5b9, 0x47286923, 0x3b1a30ef, 0xeebe3d6a, - 0x9db1aa00, 0x007a90d9, 0x24667071, 0x019c73cf, 0x69039bcd, 0x95900744, - 0x6518b1eb, 0x6905f202, 0xee3951b2, 0xe141fca9, 0x797fa832, 0x5a95e55b, - 0xd6263b15, 0x5b61f394, 0x897acb1c, 0x005f83a9, 0x22420f71, 0xf495176e, - 0x7e138f3d, 0x1392e384, 0x373bf7aa, 0x8e512816, 0xa960b3ca, 0x0474d74c, - 0xffacd6d7, 0x2ef5ed9e, 0x60992aaa, 0x7e690e99, 0x23c0749d, 0xd8e29105, - 0x555d5909, 0x15631bfe, 0xa69c5a1c, 0x501017ca, 0x99438048, 0x38733ac7, - 0xe682e2c8, 0xd4655fd6, 0x956e4c04, 0x347df643, 0x2f4b177b, 0x93ed3aa4, - 0xa77e1dd5, 0x7ae55702, 0xd2a52fd9, 0xef8ba18c, 0xb7d3c1ee, 0x8078ba8d, - 0xab5aaadb, 0x752be08f, 0x068b31c1, 0x078aae3c, 0xaa5a8343, 0x123d9268, - 0x2ceaee43, 0x8ebdb239, 0x650251f3, 0x04883648, 0x8c62e12e, 0x12b32167, - 0xe5112e9a, 0x10002548, 0x3e7a818d, 0x077e5327, 0xf140cc21, 0x6ce7d75d, - 0x9b99f9a5, 0x3215741c, 0xb6aadbae, 0x738768dc, 0x82a3742f, 0x76517020, - 0xdd872ad8, 0x9d0902b2, 0x7d1a6b04, 0x49381592, 0x63a652a5, 0x0c15e626, - 0xe22f70d6, 0x01e84385, 0xb29de134, 0x20c5000e, 0xe961f443, 0x2d31662e, - 0x3ce6bc28, 0x34f9dd94, 0xfa45de53, 0x497588bd, 0x9468215b, 0x0777fa5c, - 0x6f7114c0, 0xe0e82694, 0xe4371986, 0x57112de2, 0xe0cac289, 0xf2a3cee0, - 0x6a41e1b9, 0xbfcea77d, 0xf927fd52, 0x69747d98, 0xbea76cdb, 0x8dd39557, - 0x04db5ece, 0x2a0885c8, 0x3be4e8ee, 0x21d785dc, 0x09de7c0e, 0x3258ea33, - 0x51922982, 0xee8dd024, 0x3df6965d, 0x30c1237b, 0xf7f6686a, 0x9faca186, - 0x7c400076, 0x85acef8a, 0xf4b6d220, 0xddc3481c, 0x439eaec4, 0x717bbe63, - 0x8259faa7, 0xd682bd68, 0x932a8610, 0x38bf0a7f, 0x6212e2c7, 0x88ee3168, - 0xb3c27047, 0x6133cb1e, 0x15295506, 0x5ae66246, 0x1d208ddd, 0xa91d3dba, - 0xc315968d, 0x6aa2664b, 0x716d0cca, 0x891f4956, 0x80866bff, 0xbd56c847, - 0x9093425a, 0x28dd9e87, 0x84ef3e08, 0x690a49d6, 0x6a7eff82, 0xabcfe400, - 0x3d3be5ca, 0x381b650c, 0x4b7c8622, 0x3e0246f3, 0xa3561654, 0x9488865c, - 0x3aef1bf2, 0x5e5d68a2, 0xd32f1ddc, 0x51972bf0, 0x177a213b, 0x469375c2, - 0x37640bd0, 0xfc3324c8, 0x07091a09, 0x2d63d3fb, 0x2153f023, 0x48223875, - 0x61a55826, 0x8c136538, 0x49f71d98, 0x84c7d51e, 0x85551a73, 0x13d604c5, - 0xd701a626, 0x87b844ca, 0x741eb29d, 0x2a2c977c, 0xc797ca03, 0x6c4085d7, - 0x2dacf79b, 0x734fa2eb, 0xcc290557, 0xfa1e75e4, 0x06b29a27, 0xbece2a7a, - 0x70a4554b, 0xc935942e, 0xa764bbc1, 0x1fe391d6, 0x7807f0c2, 0x40606ed9, - 0xe5153086, 0xe91d7dd2, 0xed5d3ba9, 0xaa14b64a, 0x83b24dd9, 0xec1ff5cd, - 0xba33ead3, 0xe4ef735c, 0xbc062438, 0xd8bfd523, 0x473d1e04, 0x2007f8a7, - 0xb02903ed, 0x86ea8ada, 0x95ab69cf, 0xfd1f9809, 0x9cb3d8bb, 0x51f45958, - 0x9cdd4276, 0xc245865e, 0x8f0c836b, 0x4ee7dc07, 0xf6368d9d, 0xef2c1dc1, - 0xee56b54b, 0xbd62ce2f, 0xf4916aad, 0xc81cb594, 0x41729f49, 0x24bef0a4, - 0xdef487a9, 0x222e05b8, 0x8d3bf5c6, 0x11b55009, 0xad09d2b3, 0x19db9fd1, - 0xd7427085, 0x33dbfc8b, 0x526b9378, 0x790e1bc8, 0xb2998a00, 0xa5641703, - 0x0676d249, 0x6b9185cc, 0x30e4348f, 0x82c52f65, 0x57c7dc24, 0x489c1ecd, - 0x9fcab02a, 0x56d61117, 0xfe869cac, 0x55fc5140, 0x7fbbb382, 0x9e5afc79, - 0x10047c99, 0xfc9f5984, 0x56587e2d, 0xb98193f0, 0x98fe5e8e, 0x29b15b6b, - 0x9561f055, 0xbb0caa25, 0x1e4ecc15, 0x23f5393b, 0x0845b458, 0xceff67ca, - 0xb099900c, 0x00b1564f, 0x39eef3d1, 0xfcc1bf84, 0xac8893b5, 0x6484bf0e, - 0x91c02ab3, 0x8c0c0c70, 0x686fa8c6, 0xe171bed6, 0xdfae37df, 0xd5a1a4e7, - 0xe3eb49a1, 0x5e6014e0, 0x205b21ac, 0xfd58b3da, 0x2e7c07cd, 0xef2cc85a, - 0xd7587b46, 0xf417847d, 0x8a30cec1, 0x70984f6c, 0xf0b63388, 0xc220c98d, - 0xede62936, 0x92c0a7b3, 0x1ef371e8, 0x2005f7af, 0x91a47265, 0xb0cf5504, - 0xd500aba8, 0xcb5c4bd3, 0x9b3bcbc3, 0xcf6644b5, 0xce9488ef, 0x003fc96e, - 0xaa42222f, 0x4844f3d0, 0x4db89d77, 0x08681aae, 0x662f3a28, 0x761552db, - 0x1df7a17a, 0x93feed9a, 0xcc496a4f, 0xa217cfcd, 0x3ba3c930, 0x268f7e77, - 0x0797b4a1, 0x8bebfc51, 0x068930c4, 0x16c874e2, 0xc242da24, 0xfb229f76, - 0xa0795b02, 0x689fc036, 0x17a73732, 0xd21aec00, 0xac00a692, 0x5b217f18, - 0xae421624, 0x2bc05cc0, 0x48c1db7a, 0x4f4e63b4, 0x1667f04e, 0x34020f94, - 0x972b2555, 0x9a07355b, 0x01665970, 0x7db60c6f, 0x3ad7103b, 0x5c3d09c0, - 0xeea3dada, 0x88c21c10, 0x102436d7, 0x6a3b3400, 0xeb523c4c, 0xfb97d896, - 0x964cb86b, 0xdd878038, 0x0529da4d, 0x0b1468a5, 0x18739ac8, 0xf7f26668, - 0xf64f4471, 0x5c14f5c3, 0x44a081fb, 0x39ac7e37, 0x8a17c26b, 0x868f5e67, - 0x3931978d, 0x6edf7817, 0x4951cc67, 0x943407f3, 0xcc5e748f, 0x2b7ee729, - 0xcbb320f0, 0x11fec8e7, 0xfccfc658, 0x03454354, 0x373aa1ec, 0x1d58fe9a, - 0x064710ae, 0xa88aa0ba, 0xd183a23e, 0x40d150a3, 0xf531b8d1, 0xa7d99f85, - 0x11838cd5, 0xb19e64b3, 0x3d67a5e9, 0xb02c5ac6, 0x99b9b9e8, 0x4c202b7a, - 0x15f261d3, 0xa84c2d0d, 0x50f185a6, 0x33ba41d5, 0x39791013, 0x4baff44e, - 0xeeeeaa1c, 0xe0488314, 0x559ccd2b, 0xa104f445, 0x636f37c4, 0x264d5e3b, - 0x75c17f35, 0x75424131, 0xbb115739, 0x74fe755a, 0x7d3a7aa6, 0x2d8be784, - 0x83ed154a, 0xfc2673d8, 0x44dd4a7f, 0x79056cc8, 0x82cc8831, 0x9d3c1b7c, - 0xe9453bfa, 0x24315694, 0x661f3253, 0x75549f5c, 0xbb2b63ed, 0x67e00d96, - 0xf48966c7, 0x0d7bea56, 0xc25f92ef, 0xa947a79d, 0xde4adf6f, 0xac0f0342, - 0xd3eb246b, 0xa4aa118e, 0x3c3e6a46, 0x457f4441, 0xa50a406f, 0x6c508d9f, - 0xe9ac18e7, 0x1ecdb4ba, 0x39ac7e3a, 0x7fb304fa, 0x6f38f8e8, 0x4aecea6d, - 0x61035e73, 0x81708907, 0xebc07205, 0x90fd7614, 0xb52d217f, 0x6c4de195, - 0x1dd49084, 0x64ee482c, 0x94c7a521, 0x540c09d8, 0x75df8dd5, 0x414131f7, - 0x3698fd76, 0xf784db4f, 0xf8c97a03, 0x048f39b9, 0x3bf4f0bd, 0x8cb50992, - 0x9b58d9ee, 0xe5ab79cc, 0x9a5f6052, 0xbd9591b0, 0xfad2232b, 0x5a632254, - 0x0286e618, 0x8ad3c8f7, 0xe4060176, 0x754c4617, 0x5c10490b, 0x6f7d6fff, - 0x2187b42a, 0x5775095b, 0x02f4c663, 0x5a5dca06, 0xfe4ad4c7, 0x53e19f7d, - 0x59ff46b5, 0xbcc42ba5, 0xfd2f4a97, 0xbed6d905, 0x95629b6b, 0x21a1c0db, - 0xaa10b45d, 0xe6ef6d58, 0x2892cf4d, 0x9fed6c10, 0x1e386bf7, 0x9be0c6e8, - 0x2b2f15ef, 0x19f5ac7b, 0x7aff0e72, 0x31da576f, 0x30252cb4, 0x577960ac, - 0x166e9e5a, 0xa9374a61, 0x71369c96, 0x7ff826ae, 0xe8175326, 0xcabbfd33, - 0x0191190e, 0x699d3c3e, 0x36b40b22, 0xb3950513, 0x9b889bfa, 0xa52a5007, - 0xac290fed, 0x3b4e4a4f, 0xb753d8d6, 0x3c531f22, 0x582f6427, 0xa9cd93a9, - 0x546e39ae, 0x242faad2, 0xd2e0f747, 0x09f6325d, 0x59d48719, 0xad7eb66e, - 0xd5512878, 0x56debf9d, 0x5107e5a5, 0xf1c00aa4, 0x814ccca8, 0x600d90f0, - 0x9be97619, 0x915fa5f2, 0x2b5628dd, 0xa33d5f5a, 0x595df7c1, 0x6966215d, - 0x50ec8337, 0xf1d21372, 0x0ee2eefb, 0xad9e70b7, 0xab0d2fe4, 0xcf277b5d, - 0x62585a2c, 0x835a7844, 0x74b1fa6b, 0x49baffd5, 0x2ea9c864, 0x129311a8, - 0xbdfa1867, 0x83ca5997, 0x9d1db719, 0x84bb79e6, 0x9e3f99f2, 0x313f6101, - 0x1b99245b, 0xd15d8fb2, 0xcef90f81, 0x2945268d, 0xdbbcf573, 0xb1021886, - 0x9ee7ec1d, 0x1cf824f7, 0x7eaa2e32, 0x69c0a2b5, 0x7494419c, 0xe253d7d3, - 0x48da3d12, 0x45b8b571, 0xdb4d147a, 0xd82d8dde, 0x265d10a2, 0xb0a6eb9a, - 0x7e1c93a6, 0x36fe2f46, 0xdcad6b00, 0x05439191, 0xb0ce5484, 0x61d1c309, - 0x8da62a03, 0x06d0fe2f, 0xbac6dd3c, 0xca2006f3, 0x8321b1af, 0x0411a6f3, - 0xe8918eac, 0x21a2c152, 0x91c0d54f, 0x6aaa14fa, 0xdd22a440, 0x88cb2075, - 0x7a4eb813, 0x67afa071, 0xd8d98c9c, 0x31f10d47, 0x6ff1a8a8, 0x2faaf0a1, - 0x48a221bb, 0x3be6948b, 0xaa79e79b, 0x0ea7278c, 0x7a3857ef, 0x49b7fe55, - 0xd51cb931, 0x041c018d, 0x00b90501, 0x45ea7881, 0x8fc1dbcf, 0xb80b32a9, - 0xabacd2e9, 0x677bdc40, 0xecace542, 0x6d6514eb, 0x31c09ff7, 0x5e6c1abd, - 0x1c391d0f, 0x0e9d77f1, 0x7119392d, 0x6be9b0ba, 0x6194fa77, 0x45e62148, - 0x42234af2, 0xc3239d66, 0x939cbdbc, 0x56200d9c, 0x6b275208, 0x001a61f3, - 0xccc2a546, 0x4b722be0, 0xee25f2b7, 0x6d86cf9e, 0xaa6be0cd, 0x4dcda7b6, - 0x78d4aa13, 0x36ea7ad9, 0x3f29d700, 0xdeea2d84, 0x6a6af5bd, 0x18afb81c, - 0xd8e4e73c, 0x8aa708ba, 0x658b94d9, 0xa676478c, 0xcfa10c22, 0x25593c74, - 0x8d962235, 0x5f980270, 0x3df6ebc0, 0x8e7d92fa, 0xc3ee55e1, 0xd5f72447, - 0x02b0fa95, 0x52b0b520, 0x70d2c11f, 0x3a6fdd6c, 0x193aa698, 0x5496f7d5, - 0x4208931b, 0x7a4106ec, 0x83e86840, 0xf49b6f8c, 0xba3d9a51, 0x55f54ddd, - 0x2de51372, 0x9afb571b, 0x3ab35406, 0xad64ff1f, 0xc77764fe, 0x7f864466, - 0x416d9cd4, 0xa2489278, 0xe30b86e4, 0x0b5231b6, 0xba67aed6, 0xe5ab2467, - 0x60028b90, 0x1d9e20c6, 0x2a7c692a, 0x6b691cdb, 0x9e51f817, 0x9b763dec, - 0x3d29323f, 0xcfe12b68, 0x754b459b, 0xa2238047, 0xd9c55514, 0x6bdcffc1, - 0x693e6340, 0x82383fe7, 0x1916ea5f, 0xec7bcd59, 0x72de165a, 0xe79a1617, - 0x8ec86234, 0xa8f0d284, 0x20c90226, 0x7bf98884, 0x28a58331, 0x3ec3fa6e, - 0x4ce0895b, 0xc353b4d0, 0x33ef064f, 0x21e5e210, 0xc8bb589d, 0xe85dcab2, - 0xac65829f, 0xa7bf92d0, 0x05a6174d, 0x25a50c2e, 0xe5c78777, 0x3d75021f, - 0x4baa9c98, 0x23bdc884, 0x9653bbd7, 0xbadce7f5, 0xc283a484, 0xc040df2e, - 0x9370a841, 0x2f316022, 0x36eed231, 0xac2cbc0c, 0x13c0a49b, 0xcdd12997, - 0x07fe91b2, 0xcd7eabcd, 0x2c01271d, 0x18432df8, 0x599c6bc7, 0x75e93d5a, - 0xb67a6ee2, 0x8e738e16, 0xff9073fd, 0xaf77026a, 0xf86ea2fc, 0x91509ea3, - 0x33a78dc6, 0x4f79234a, 0x3a7535bc, 0x3539fcb1, 0x3103ee52, 0x4f6f1e69, - 0x6bb3ebbc, 0x4cb77555, 0x8dd1e999, 0x2ade439d, 0x11521fae, 0xb94d2545, - 0x8dde9abd, 0x1909393f, 0xb792a23d, 0x749c455b, 0xb5b60f2c, 0x380459ce, - 0x0dad5820, 0xb130845b, 0x291cbd52, 0xde9a5bb7, 0x51def961, 0x515b6408, - 0xca6e823e, 0x382e6e74, 0xeebe3d71, 0x4c8f0c6a, 0xe676dcea, 0x14e1dc7c, - 0x6f7fc634, 0xcf85a943, 0xd39ea96e, 0x136e7c93, 0x7164b304, 0xf32f1333, - 0x35c34034, 0xde39d721, 0x91a87439, 0xc410111f, 0x29f17aac, 0x1316a6ff, - 0x12f194ee, 0x420b9499, 0xf72db0dc, 0x690b9f93, 0x17d14bb2, 0x8f931ab8, - 0x217500bc, 0x875413f8, 0x98b2e43d, 0xc51f9571, 0x54cebdca, 0x0719cc79, - 0xf3c7080d, 0xe4286771, 0xa3eab3cd, 0x4a6b00e0, 0x11cf0759, 0x7e897379, - 0x5b32876c, 0x5e8cd4f6, 0x0cedfa64, 0x919ac2c7, 0xb214f3b3, 0x0e89c38c, - 0xf0c43a39, 0xeae10522, 0x835bce06, 0x9eec43c2, 0xea26a9d6, 0x69531821, - 0x6725b24a, 0xda81b0e2, 0xd5b4ae33, 0x080f99fb, 0x15a83daf, 0x29dfc720, - 0x91e1900f, 0x28163d58, 0x83d107a2, 0x4eac149a, 0x9f71da18, 0x61d5c4fa, - 0xe3ab2a5f, 0xc7b0d63f, 0xb3cc752a, 0x61ebcfb6, 0x26ffb52a, 0xed789e3f, - 0xaa3bc958, 0x455a8788, 0xc9c082a9, 0x0a1bef0e, 0xc29a5a7e, 0x150d4735, - 0x943809e0, 0x69215510, 0xef0b0da9, 0x3b4e9fb3, 0xd8b5d04c, 0xc7a023a8, - 0xb0d50288, 0x64821375, 0xc260e8cf, 0x8496bd2c, 0xff4f5435, 0x0fb5560c, - 0x7cd74a52, 0x93589c80, 0x88975c47, 0x83bda89d, 0x8bcc4296, 0x01b82c21, - 0xfd821dbf, 0x26520b47, 0x04983e19, 0xd3e1ca27, 0x782c580f, 0x326ff573, - 0xc157bcc7, 0x4f5e6b84, 0x44ebfbfb, 0xda26d9d8, 0x6cd9d08e, 0x1719f1d8, - 0x715c0487, 0x2c2d3c92, 0x53faaba9, 0xbc836146, 0x510c92d6, 0xe089f82a, - 0x4680171f, 0x369f00de, 0x70ec2331, 0x0e253d55, 0xdafb9717, 0xe5dd922d, - 0x95915d21, 0xa0202f96, 0xa161cc47, 0xeacfa6f1, 0xed5e9189, 0xdab87684, - 0xa4b76d4a, 0xfa704897, 0x631f10ba, 0xd39da8f9, 0x5db4c0e4, 0x16fde42a, - 0x2dff7580, 0xb56fec7e, 0xc3ffb370, 0x8e6f36bc, 0x6097d459, 0x514d5d36, - 0xa5a737e2, 0x3977b9b3, 0xfd31a0ca, 0x903368db, 0xe8370d61, 0x98109520, - 0xade23cac, 0x99f82e04, 0x41de7ea3, 0x84a1c295, 0x09191be0, 0x30930d02, - 0x1c9fa44a, 0xc406b6d7, 0xeedca152, 0x6149809c, 0xb0099ef4, 0xc5f653a5, - 0x4c10790d, 0x7303286c -}; diff --git a/externals/libmpq/libmpq/explode.c b/externals/libmpq/libmpq/explode.c deleted file mode 100644 index 2d778d25c39..00000000000 --- a/externals/libmpq/libmpq/explode.c +++ /dev/null @@ -1,602 +0,0 @@ -/* - * explode.c -- explode function of pkware data compression library. - * - * Copyright (c) 2003-2008 Maik Broemme - * - * This source was adepted from the C++ version of pkware.cpp included - * in stormlib. The C++ version belongs to the following authors: - * - * Ladislav Zezula - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ - -/* generic includes. */ -#include - -/* libmpq main includes. */ -#include "mpq.h" - -/* libmpq generic includes. */ -#include "explode.h" - -/* tables used for data extraction. */ -static const uint8_t pkzip_dist_bits[] = { - 0x02, 0x04, 0x04, 0x05, 0x05, 0x05, 0x05, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, - 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, - 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08 -}; - -/* tables used for data extraction. */ -static const uint8_t pkzip_dist_code[] = { - 0x03, 0x0D, 0x05, 0x19, 0x09, 0x11, 0x01, 0x3E, 0x1E, 0x2E, 0x0E, 0x36, 0x16, 0x26, 0x06, 0x3A, - 0x1A, 0x2A, 0x0A, 0x32, 0x12, 0x22, 0x42, 0x02, 0x7C, 0x3C, 0x5C, 0x1C, 0x6C, 0x2C, 0x4C, 0x0C, - 0x74, 0x34, 0x54, 0x14, 0x64, 0x24, 0x44, 0x04, 0x78, 0x38, 0x58, 0x18, 0x68, 0x28, 0x48, 0x08, - 0xF0, 0x70, 0xB0, 0x30, 0xD0, 0x50, 0x90, 0x10, 0xE0, 0x60, 0xA0, 0x20, 0xC0, 0x40, 0x80, 0x00 -}; - -/* tables used for data extraction. */ -static const uint8_t pkzip_clen_bits[] = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 -}; - -/* tables used for data extraction. */ -static const uint16_t pkzip_len_base[] = { - 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, - 0x0008, 0x000A, 0x000E, 0x0016, 0x0026, 0x0046, 0x0086, 0x0106 -}; - -/* tables used for data extraction. */ -static const uint8_t pkzip_slen_bits[] = { - 0x03, 0x02, 0x03, 0x03, 0x04, 0x04, 0x04, 0x05, 0x05, 0x05, 0x05, 0x06, 0x06, 0x06, 0x07, 0x07 -}; - -/* tables used for data extraction. */ -static const uint8_t pkzip_len_code[] = { - 0x05, 0x03, 0x01, 0x06, 0x0A, 0x02, 0x0C, 0x14, 0x04, 0x18, 0x08, 0x30, 0x10, 0x20, 0x40, 0x00 -}; - -/* tables used for data extraction. */ -static const uint8_t pkzip_bits_asc[] = { - 0x0B, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x08, 0x07, 0x0C, 0x0C, 0x07, 0x0C, 0x0C, - 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0D, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, - 0x04, 0x0A, 0x08, 0x0C, 0x0A, 0x0C, 0x0A, 0x08, 0x07, 0x07, 0x08, 0x09, 0x07, 0x06, 0x07, 0x08, - 0x07, 0x06, 0x07, 0x07, 0x07, 0x07, 0x08, 0x07, 0x07, 0x08, 0x08, 0x0C, 0x0B, 0x07, 0x09, 0x0B, - 0x0C, 0x06, 0x07, 0x06, 0x06, 0x05, 0x07, 0x08, 0x08, 0x06, 0x0B, 0x09, 0x06, 0x07, 0x06, 0x06, - 0x07, 0x0B, 0x06, 0x06, 0x06, 0x07, 0x09, 0x08, 0x09, 0x09, 0x0B, 0x08, 0x0B, 0x09, 0x0C, 0x08, - 0x0C, 0x05, 0x06, 0x06, 0x06, 0x05, 0x06, 0x06, 0x06, 0x05, 0x0B, 0x07, 0x05, 0x06, 0x05, 0x05, - 0x06, 0x0A, 0x05, 0x05, 0x05, 0x05, 0x08, 0x07, 0x08, 0x08, 0x0A, 0x0B, 0x0B, 0x0C, 0x0C, 0x0C, - 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, - 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, - 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, - 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, - 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, - 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, - 0x0D, 0x0C, 0x0D, 0x0D, 0x0D, 0x0C, 0x0D, 0x0D, 0x0D, 0x0C, 0x0D, 0x0D, 0x0D, 0x0D, 0x0C, 0x0D, - 0x0D, 0x0D, 0x0C, 0x0C, 0x0C, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D -}; - -/* tables used for data extraction. */ -static const uint16_t pkzip_code_asc[] = { - 0x0490, 0x0FE0, 0x07E0, 0x0BE0, 0x03E0, 0x0DE0, 0x05E0, 0x09E0, - 0x01E0, 0x00B8, 0x0062, 0x0EE0, 0x06E0, 0x0022, 0x0AE0, 0x02E0, - 0x0CE0, 0x04E0, 0x08E0, 0x00E0, 0x0F60, 0x0760, 0x0B60, 0x0360, - 0x0D60, 0x0560, 0x1240, 0x0960, 0x0160, 0x0E60, 0x0660, 0x0A60, - 0x000F, 0x0250, 0x0038, 0x0260, 0x0050, 0x0C60, 0x0390, 0x00D8, - 0x0042, 0x0002, 0x0058, 0x01B0, 0x007C, 0x0029, 0x003C, 0x0098, - 0x005C, 0x0009, 0x001C, 0x006C, 0x002C, 0x004C, 0x0018, 0x000C, - 0x0074, 0x00E8, 0x0068, 0x0460, 0x0090, 0x0034, 0x00B0, 0x0710, - 0x0860, 0x0031, 0x0054, 0x0011, 0x0021, 0x0017, 0x0014, 0x00A8, - 0x0028, 0x0001, 0x0310, 0x0130, 0x003E, 0x0064, 0x001E, 0x002E, - 0x0024, 0x0510, 0x000E, 0x0036, 0x0016, 0x0044, 0x0030, 0x00C8, - 0x01D0, 0x00D0, 0x0110, 0x0048, 0x0610, 0x0150, 0x0060, 0x0088, - 0x0FA0, 0x0007, 0x0026, 0x0006, 0x003A, 0x001B, 0x001A, 0x002A, - 0x000A, 0x000B, 0x0210, 0x0004, 0x0013, 0x0032, 0x0003, 0x001D, - 0x0012, 0x0190, 0x000D, 0x0015, 0x0005, 0x0019, 0x0008, 0x0078, - 0x00F0, 0x0070, 0x0290, 0x0410, 0x0010, 0x07A0, 0x0BA0, 0x03A0, - 0x0240, 0x1C40, 0x0C40, 0x1440, 0x0440, 0x1840, 0x0840, 0x1040, - 0x0040, 0x1F80, 0x0F80, 0x1780, 0x0780, 0x1B80, 0x0B80, 0x1380, - 0x0380, 0x1D80, 0x0D80, 0x1580, 0x0580, 0x1980, 0x0980, 0x1180, - 0x0180, 0x1E80, 0x0E80, 0x1680, 0x0680, 0x1A80, 0x0A80, 0x1280, - 0x0280, 0x1C80, 0x0C80, 0x1480, 0x0480, 0x1880, 0x0880, 0x1080, - 0x0080, 0x1F00, 0x0F00, 0x1700, 0x0700, 0x1B00, 0x0B00, 0x1300, - 0x0DA0, 0x05A0, 0x09A0, 0x01A0, 0x0EA0, 0x06A0, 0x0AA0, 0x02A0, - 0x0CA0, 0x04A0, 0x08A0, 0x00A0, 0x0F20, 0x0720, 0x0B20, 0x0320, - 0x0D20, 0x0520, 0x0920, 0x0120, 0x0E20, 0x0620, 0x0A20, 0x0220, - 0x0C20, 0x0420, 0x0820, 0x0020, 0x0FC0, 0x07C0, 0x0BC0, 0x03C0, - 0x0DC0, 0x05C0, 0x09C0, 0x01C0, 0x0EC0, 0x06C0, 0x0AC0, 0x02C0, - 0x0CC0, 0x04C0, 0x08C0, 0x00C0, 0x0F40, 0x0740, 0x0B40, 0x0340, - 0x0300, 0x0D40, 0x1D00, 0x0D00, 0x1500, 0x0540, 0x0500, 0x1900, - 0x0900, 0x0940, 0x1100, 0x0100, 0x1E00, 0x0E00, 0x0140, 0x1600, - 0x0600, 0x1A00, 0x0E40, 0x0640, 0x0A40, 0x0A00, 0x1200, 0x0200, - 0x1C00, 0x0C00, 0x1400, 0x0400, 0x1800, 0x0800, 0x1000, 0x0000 -}; - -/* local unused variables. */ -char pkware_copyright[] = "PKWARE Data Compression Library for Win32\r\n" - "Copyright 1989-1995 PKWARE Inc. All Rights Reserved\r\n" - "Patent No. 5,051,745\r\n" - "PKWARE Data Compression Library Reg. U.S. Pat. and Tm. Off.\r\n" - "Version 1.11\r\n"; - -/* skips given number of bits. */ -static int32_t skip_bit(pkzip_cmp_s *mpq_pkzip, uint32_t bits) { - - /* check if number of bits required is less than number of bits in the buffer. */ - if (bits <= mpq_pkzip->extra_bits) { - mpq_pkzip->extra_bits -= bits; - mpq_pkzip->bit_buf >>= bits; - return 0; - } - - /* load input buffer if necessary. */ - mpq_pkzip->bit_buf >>= mpq_pkzip->extra_bits; - if (mpq_pkzip->in_pos == mpq_pkzip->in_bytes) { - mpq_pkzip->in_pos = sizeof(mpq_pkzip->in_buf); - if ((mpq_pkzip->in_bytes = mpq_pkzip->read_buf((char *)mpq_pkzip->in_buf, &mpq_pkzip->in_pos, mpq_pkzip->param)) == 0) { - return 1; - } - mpq_pkzip->in_pos = 0; - } - - /* update bit buffer. */ - mpq_pkzip->bit_buf |= (mpq_pkzip->in_buf[mpq_pkzip->in_pos++] << 8); - mpq_pkzip->bit_buf >>= (bits - mpq_pkzip->extra_bits); - mpq_pkzip->extra_bits = (mpq_pkzip->extra_bits - bits) + 8; - - /* if no error was found, return zero. */ - return 0; -} - -/* this function generate the decode tables used for decryption. */ -static void generate_tables_decode(int32_t count, uint8_t *bits, const uint8_t *code, uint8_t *buf2) { - - /* some common variables. */ - int32_t i; - - /* EBX - count */ - for (i = count-1; i >= 0; i--) { - - /* some common variables. */ - uint32_t idx1 = code[i]; - uint32_t idx2 = 1 << bits[i]; - - /* loop until table is ready. */ - do { - buf2[idx1] = (uint8_t)i; - idx1 += idx2; - } while (idx1 < 0x100); - } -} - -/* this function generate the tables for ascii decompression. */ -static void generate_tables_ascii(pkzip_cmp_s *mpq_pkzip) { - - /* some common variables. */ - const uint16_t *code_asc = &pkzip_code_asc[0xFF]; - uint32_t acc; - uint32_t add; - uint16_t count; - - /* loop through ascii table. */ - for (count = 0x00FF; code_asc >= pkzip_code_asc; code_asc--, count--) { - uint8_t *bits_asc = mpq_pkzip->bits_asc + count; - uint8_t bits_tmp = *bits_asc; - - /* check if byte is finished. */ - if (bits_tmp <= 8) { - add = (1 << bits_tmp); - acc = *code_asc; - do { - mpq_pkzip->offs_2c34[acc] = (uint8_t)count; - acc += add; - } while (acc < 0x100); - } else { - if ((acc = (*code_asc & 0xFF)) != 0) { - mpq_pkzip->offs_2c34[acc] = 0xFF; - if (*code_asc & 0x3F) { - - /* decrease bit by four. */ - bits_tmp -= 4; - *bits_asc = bits_tmp; - add = (1 << bits_tmp); - acc = *code_asc >> 4; - do { - mpq_pkzip->offs_2d34[acc] = (uint8_t)count; - acc += add; - } while (acc < 0x100); - } else { - - /* decrease bit by six. */ - bits_tmp -= 6; - *bits_asc = bits_tmp; - add = (1 << bits_tmp); - acc = *code_asc >> 6; - do { - mpq_pkzip->offs_2e34[acc] = (uint8_t)count; - acc += add; - } while (acc < 0x80); - } - } else { - - /* decrease bit by eight. (one byte) */ - bits_tmp -= 8; - *bits_asc = bits_tmp; - add = (1 << bits_tmp); - acc = *code_asc >> 8; - do { - mpq_pkzip->offs_2eb4[acc] = (uint8_t)count; - acc += add; - } while (acc < 0x100); - } - } - } -} - -/* - * decompress the imploded data using coded literals. - * - * returns: 0x000 - 0x0FF : one byte from compressed file. - * 0x100 - 0x305 : copy previous block. (0x100 = 1 byte) - * 0x306 : out of buffer? - */ -static uint32_t decode_literal(pkzip_cmp_s *mpq_pkzip) { - - /* number of bits to skip. */ - uint32_t bits; - - /* position in buffers. */ - uint32_t value; - - /* check if bit the current buffer is set, if not return the next byte. */ - if (mpq_pkzip->bit_buf & 1) { - - /* skip current bit in the buffer. */ - if (skip_bit(mpq_pkzip, 1)) { - return 0x306; - } - - /* the next bits are position in buffers. */ - value = mpq_pkzip->pos2[(mpq_pkzip->bit_buf & 0xFF)]; - - /* get number of bits to skip. */ - if (skip_bit(mpq_pkzip, mpq_pkzip->slen_bits[value])) { - return 0x306; - } - - /* check bits. */ - if ((bits = mpq_pkzip->clen_bits[value]) != 0) { - - /* some common variables. */ - uint32_t val2 = mpq_pkzip->bit_buf & ((1 << bits) - 1); - - /* check if we should skip one bit. */ - if (skip_bit(mpq_pkzip, bits)) { - - /* check position if we should skip the bit. */ - if ((value + val2) != 0x10E) { - return 0x306; - } - } - - /* fill values. */ - value = mpq_pkzip->len_base[value] + val2; - } - - /* return number of bytes to repeat. */ - return value + 0x100; - } - - /* skip one bit. */ - if (skip_bit(mpq_pkzip, 1)) { - return 0x306; - } - - /* check the binary compression type, read 8 bits and return them as one byte. */ - if (mpq_pkzip->cmp_type == LIBMPQ_PKZIP_CMP_BINARY) { - - /* fill values. */ - value = mpq_pkzip->bit_buf & 0xFF; - - /* check if we should skip one bit. */ - if (skip_bit(mpq_pkzip, 8)) { - return 0x306; - } - - /* return value from bit buffer. */ - return value; - } - - /* check if ascii compression is used. */ - if (mpq_pkzip->bit_buf & 0xFF) { - - /* fill values. */ - value = mpq_pkzip->offs_2c34[mpq_pkzip->bit_buf & 0xFF]; - - /* check value. */ - if (value == 0xFF) { - if (mpq_pkzip->bit_buf & 0x3F) { - - /* check if four bits are in bit buffer for skipping. */ - if (skip_bit(mpq_pkzip, 4)) { - return 0x306; - } - - /* fill values. */ - value = mpq_pkzip->offs_2d34[mpq_pkzip->bit_buf & 0xFF]; - } else { - - /* check if six bits are in bit buffer for skipping. */ - if (skip_bit(mpq_pkzip, 6)) { - return 0x306; - } - - /* fill values. */ - value = mpq_pkzip->offs_2e34[mpq_pkzip->bit_buf & 0x7F]; - } - } - } else { - - /* check if eight bits are in bit buffer for skipping. */ - if (skip_bit(mpq_pkzip, 8)) { - return 0x306; - } - - /* fill values. */ - value = mpq_pkzip->offs_2eb4[mpq_pkzip->bit_buf & 0xFF]; - } - - /* return out of buffer error (0x306) or position in buffer. */ - return skip_bit(mpq_pkzip, mpq_pkzip->bits_asc[value]) ? 0x306 : value; -} - -/* this function retrieves the number of bytes to move back. */ -static uint32_t decode_distance(pkzip_cmp_s *mpq_pkzip, uint32_t length) { - - /* some common variables. */ - uint32_t pos = mpq_pkzip->pos1[(mpq_pkzip->bit_buf & 0xFF)]; - - /* number of bits to skip. */ - uint32_t skip = mpq_pkzip->dist_bits[pos]; - - /* skip the appropriate number of bits. */ - if (skip_bit(mpq_pkzip, skip) == 1) { - return 0; - } - - /* check if length is two. */ - if (length == 2) { - pos = (pos << 2) | (mpq_pkzip->bit_buf & 0x03); - - /* skip the bits. */ - if (skip_bit(mpq_pkzip, 2) == 1) { - return 0; - } - } else { - pos = (pos << mpq_pkzip->dsize_bits) | (mpq_pkzip->bit_buf & mpq_pkzip->dsize_mask); - - /* skip the bits */ - if (skip_bit(mpq_pkzip, mpq_pkzip->dsize_bits) == 1) { - return 0; - } - } - - /* return the bytes to move back. */ - return pos + 1; -} - -/* - * function loads data from the input buffer used by mpq_pkzip - * "implode" and "explode" function as user defined callback and - * returns number of bytes loaded. - * - * char *buf - pointer to a buffer where to store loaded data. - * uint32_t *size - maximum number of bytes to read. - * void *param - custom pointer, parameter of implode/explode. - */ -static uint32_t data_read_input(char *buf, uint32_t *size, void *param) { - - /* some common variables. */ - pkzip_data_s *info = (pkzip_data_s *)param; - uint32_t max_avail = (info->in_bytes - info->in_pos); - uint32_t to_read = *size; - - /* check the case when not enough data available. */ - if (to_read > max_avail) { - to_read = max_avail; - } - - /* load data and increment offsets. */ - memcpy(buf, info->in_buf + info->in_pos, to_read); - info->in_pos += to_read; - - /* return bytes read. */ - return to_read; -} - -/* - * function for store output data used by mpq_pkzip "implode" and - * "explode" as userdefined callback. - * - * char *buf - pointer to data to be written. - * uint32_t *size - number of bytes to write. - * void *param - custom pointer, parameter of implode/explode. - */ -static void data_write_output(char *buf, uint32_t *size, void *param) { - - /* some common variables. */ - pkzip_data_s *info = (pkzip_data_s *)param; - uint32_t max_write = (info->max_out - info->out_pos); - uint32_t to_write = *size; - - /* check the case when not enough space in the output buffer. */ - if (to_write > max_write) { - to_write = max_write; - } - - /* write output data and increments offsets. */ - memcpy(info->out_buf + info->out_pos, buf, to_write); - info->out_pos += to_write; -} - -/* this function extract the data from input stream. */ -static uint32_t expand(pkzip_cmp_s *mpq_pkzip) { - - /* number of bytes to copy. */ - uint32_t copy_bytes; - - /* one byte from compressed file. */ - uint32_t one_byte; - - /* some common variables. */ - uint32_t result; - - /* initialize output buffer position. */ - mpq_pkzip->out_pos = 0x1000; - - /* check if end of data or error, so terminate decompress. */ - while ((result = one_byte = decode_literal(mpq_pkzip)) < 0x305) { - - /* check if one byte is greater than 0x100, which means 'repeat n - 0xFE bytes'. */ - if (one_byte >= 0x100) { - - /* ECX */ - uint8_t *source; - - /* EDX */ - uint8_t *target; - - /* some common variables. */ - uint32_t copy_length = one_byte - 0xFE; - uint32_t move_back; - - /* get length of data to copy. */ - if ((move_back = decode_distance(mpq_pkzip, copy_length)) == 0) { - result = 0x306; - break; - } - - /* target and source pointer. */ - target = &mpq_pkzip->out_buf[mpq_pkzip->out_pos]; - source = target - move_back; - mpq_pkzip->out_pos += copy_length; - - /* copy until nothing left. */ - while (copy_length-- > 0) { - *target++ = *source++; - } - } else { - - /* byte is 0x100 great, so add one byte. */ - mpq_pkzip->out_buf[mpq_pkzip->out_pos++] = (uint8_t)one_byte; - } - - /* check if number of extracted bytes has reached 1/2 of output buffer, so flush output buffer. */ - if (mpq_pkzip->out_pos >= 0x2000) { - - /* copy decompressed data into user buffer. */ - copy_bytes = 0x1000; - mpq_pkzip->write_buf((char *)&mpq_pkzip->out_buf[0x1000], ©_bytes, mpq_pkzip->param); - - /* check if there are some data left, keep them alive. */ - memcpy(mpq_pkzip->out_buf, &mpq_pkzip->out_buf[0x1000], mpq_pkzip->out_pos - 0x1000); - mpq_pkzip->out_pos -= 0x1000; - } - } - - /* copy the rest. */ - copy_bytes = mpq_pkzip->out_pos - 0x1000; - mpq_pkzip->write_buf((char *)&mpq_pkzip->out_buf[0x1000], ©_bytes, mpq_pkzip->param); - - /* return copied bytes. */ - return result; -} - -/* this function explode the data stream. */ -uint32_t libmpq__do_decompress_pkzip(uint8_t *work_buf, void *param) { - - /* some common variables. */ - pkzip_cmp_s *mpq_pkzip = (pkzip_cmp_s *)work_buf; - - /* set the whole work buffer to zeros. */ - memset(mpq_pkzip, 0, sizeof(pkzip_cmp_s)); - - /* initialize work struct and load compressed data. */ - mpq_pkzip->read_buf = data_read_input; - mpq_pkzip->write_buf = data_write_output; - mpq_pkzip->param = param; - mpq_pkzip->in_pos = sizeof(mpq_pkzip->in_buf); - mpq_pkzip->in_bytes = mpq_pkzip->read_buf((char *)mpq_pkzip->in_buf, &mpq_pkzip->in_pos, mpq_pkzip->param); - - /* check if we have pkzip data. */ - if (mpq_pkzip->in_bytes <= 4) { - return LIBMPQ_PKZIP_CMP_BAD_DATA; - } - - /* get the compression type. */ - mpq_pkzip->cmp_type = mpq_pkzip->in_buf[0]; - - /* get the dictionary size. */ - mpq_pkzip->dsize_bits = mpq_pkzip->in_buf[1]; - - /* initialize 16-bit bit buffer. */ - mpq_pkzip->bit_buf = mpq_pkzip->in_buf[2]; - - /* extra (over 8) bits. */ - mpq_pkzip->extra_bits = 0; - - /* position in input buffer. */ - mpq_pkzip->in_pos = 3; - - /* check if valid dictionary size. */ - if (4 > mpq_pkzip->dsize_bits || mpq_pkzip->dsize_bits > 6) { - return LIBMPQ_PKZIP_CMP_INV_DICTSIZE; - } - - /* shifted by 'sar' instruction. */ - mpq_pkzip->dsize_mask = 0xFFFF >> (0x10 - mpq_pkzip->dsize_bits); - - /* check if we are using binary compression. */ - if (mpq_pkzip->cmp_type != LIBMPQ_PKZIP_CMP_BINARY) { - - /* check if we are using ascii compression. */ - if (mpq_pkzip->cmp_type != LIBMPQ_PKZIP_CMP_ASCII) { - return LIBMPQ_PKZIP_CMP_INV_MODE; - } - - /* create ascii buffer. */ - memcpy(mpq_pkzip->bits_asc, pkzip_bits_asc, sizeof(mpq_pkzip->bits_asc)); - generate_tables_ascii(mpq_pkzip); - } - - /* create the tables for decode. */ - memcpy(mpq_pkzip->slen_bits, pkzip_slen_bits, sizeof(mpq_pkzip->slen_bits)); - generate_tables_decode(0x10, mpq_pkzip->slen_bits, pkzip_len_code, mpq_pkzip->pos2); - - /* create the tables for decode. */ - memcpy(mpq_pkzip->clen_bits, pkzip_clen_bits, sizeof(mpq_pkzip->clen_bits)); - memcpy(mpq_pkzip->len_base, pkzip_len_base, sizeof(mpq_pkzip->len_base)); - memcpy(mpq_pkzip->dist_bits, pkzip_dist_bits, sizeof(mpq_pkzip->dist_bits)); - generate_tables_decode(0x40, mpq_pkzip->dist_bits, pkzip_dist_code, mpq_pkzip->pos1); - - /* check if data extraction works. */ - if (expand(mpq_pkzip) != 0x306) { - return LIBMPQ_PKZIP_CMP_NO_ERROR; - } - - /* something failed, so return error. */ - return LIBMPQ_PKZIP_CMP_ABORT; -} diff --git a/externals/libmpq/libmpq/explode.h b/externals/libmpq/libmpq/explode.h deleted file mode 100644 index 1d14dfc0e0a..00000000000 --- a/externals/libmpq/libmpq/explode.h +++ /dev/null @@ -1,87 +0,0 @@ -/* - * explode.h -- header file for pkware data decompression library - * used by mpq-tools. - * - * Copyright (c) 2003-2008 Maik Broemme - * - * This source was adepted from the C++ version of pklib.h included - * in stormlib. The C++ version belongs to the following authors: - * - * Ladislav Zezula - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ - -#ifndef _EXPLODE_H -#define _EXPLODE_H - -/* define compression constants and return values. */ -#define LIBMPQ_PKZIP_CMP_BINARY 0 /* binary compression. */ -#define LIBMPQ_PKZIP_CMP_ASCII 1 /* ascii compression. */ -#define LIBMPQ_PKZIP_CMP_NO_ERROR 0 -#define LIBMPQ_PKZIP_CMP_INV_DICTSIZE 1 -#define LIBMPQ_PKZIP_CMP_INV_MODE 2 -#define LIBMPQ_PKZIP_CMP_BAD_DATA 3 -#define LIBMPQ_PKZIP_CMP_ABORT 4 - -#include "pack_begin.h" -/* compression structure. */ -typedef struct { - uint32_t offs0000; /* 0000 - start. */ - uint32_t cmp_type; /* 0004 - compression type (binary or ascii). */ - uint32_t out_pos; /* 0008 - position in output buffer. */ - uint32_t dsize_bits; /* 000C - dict size (4, 5, 6 for 0x400, 0x800, 0x1000). */ - uint32_t dsize_mask; /* 0010 - dict size bitmask (0x0F, 0x1F, 0x3F for 0x400, 0x800, 0x1000). */ - uint32_t bit_buf; /* 0014 - 16-bit buffer for processing input data. */ - uint32_t extra_bits; /* 0018 - number of extra (above 8) bits in bit buffer. */ - uint32_t in_pos; /* 001C - position in in_buf. */ - uint32_t in_bytes; /* 0020 - number of bytes in input buffer. */ - void *param; /* 0024 - custom parameter. */ - uint32_t (*read_buf)(char *buf, uint32_t *size, void *param); /* 0028 offset.*/ - void (*write_buf)(char *buf, uint32_t *size, void *param); /* 002C offset. */ - uint8_t out_buf[0x2000]; /* 0030 - output circle buffer, starting position is 0x1000. */ - uint8_t offs_2030[0x204]; /* 2030 - whats that? */ - uint8_t in_buf[0x800]; /* 2234 - buffer for data to be decompressed. */ - uint8_t pos1[0x100]; /* 2A34 - positions in buffers. */ - uint8_t pos2[0x100]; /* 2B34 - positions in buffers. */ - uint8_t offs_2c34[0x100]; /* 2C34 - buffer. */ - uint8_t offs_2d34[0x100]; /* 2D34 - buffer. */ - uint8_t offs_2e34[0x80]; /* 2EB4 - buffer. */ - uint8_t offs_2eb4[0x100]; /* 2EB4 - buffer. */ - uint8_t bits_asc[0x100]; /* 2FB4 - buffer. */ - uint8_t dist_bits[0x40]; /* 30B4 - numbers of bytes to skip copied block length. */ - uint8_t slen_bits[0x10]; /* 30F4 - numbers of bits for skip copied block length. */ - uint8_t clen_bits[0x10]; /* 3104 - number of valid bits for copied block. */ - uint16_t len_base[0x10]; /* 3114 - buffer. */ -} PACK_STRUCT pkzip_cmp_s; -#include "pack_end.h" - -/* data structure. */ -typedef struct { - uint8_t *in_buf; /* pointer to input data buffer. */ - uint32_t in_pos; /* current offset in input data buffer. */ - int32_t in_bytes; /* number of bytes in the input buffer. */ - uint8_t *out_buf; /* pointer to output data buffer. */ - uint32_t out_pos; /* position in the output buffer. */ - int32_t max_out; /* maximum number of bytes in the output buffer. */ -} pkzip_data_s; - -/* decompress the stream using pkzip compression. */ -uint32_t libmpq__do_decompress_pkzip( - uint8_t *work_buf, - void *param -); - -#endif /* _EXPLODE_H */ diff --git a/externals/libmpq/libmpq/extract.c b/externals/libmpq/libmpq/extract.c deleted file mode 100644 index 11de1071683..00000000000 --- a/externals/libmpq/libmpq/extract.c +++ /dev/null @@ -1,361 +0,0 @@ -/* - * extract.c -- global extracting function for all known file compressions - * in a mpq archive. - * - * Copyright (c) 2003-2008 Maik Broemme - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ - -/* generic includes. */ -#include -#include - -/* zlib includes. */ -#include -#include - -/* libmpq main includes. */ -#include "mpq.h" - -/* libmpq generic includes. */ -#include "explode.h" -#include "extract.h" -#include "huffman.h" -#include "wave.h" - -/* table with decompression bits and functions. */ -static decompress_table_s dcmp_table[] = { - {LIBMPQ_COMPRESSION_HUFFMAN, libmpq__decompress_huffman}, /* decompression using huffman trees. */ - {LIBMPQ_COMPRESSION_ZLIB, libmpq__decompress_zlib}, /* decompression with the zlib library. */ - {LIBMPQ_COMPRESSION_PKZIP, libmpq__decompress_pkzip}, /* decompression with pkware data compression library. */ - {LIBMPQ_COMPRESSION_BZIP2, libmpq__decompress_bzip2}, /* decompression with bzip2 library. */ - {LIBMPQ_COMPRESSION_WAVE_MONO, libmpq__decompress_wave_mono}, /* decompression for mono waves. */ - {LIBMPQ_COMPRESSION_WAVE_STEREO, libmpq__decompress_wave_stereo} /* decompression for stereo waves. */ -}; - -/* this function decompress a stream using huffman algorithm. */ -int32_t libmpq__decompress_huffman(uint8_t *in_buf, uint32_t in_size, uint8_t *out_buf, uint32_t out_size) { - - /* TODO: make typdefs of this structs? */ - /* some common variables. */ - int32_t tb = 0; - struct huffman_tree_s *ht; - struct huffman_input_stream_s *is; - - /* allocate memory for the huffman tree. */ - if ((ht = malloc(sizeof(struct huffman_tree_s))) == NULL || - (is = malloc(sizeof(struct huffman_input_stream_s))) == NULL) { - - /* memory allocation problem. */ - return LIBMPQ_ERROR_MALLOC; - } - - /* cleanup structures. */ - memset(ht, 0, sizeof(struct huffman_tree_s)); - memset(is, 0, sizeof(struct huffman_input_stream_s)); - - /* initialize input stream. */ - is->bit_buf = *(uint32_t *)in_buf; - in_buf += sizeof(int32_t); - is->in_buf = (uint8_t *)in_buf; - is->bits = 32; - -// TODO: add all the mallocs to init function and add function libmpq__huffman_tree_free() */ -// if ((result = libmpq__huffman_tree_init(ht, LIBMPQ_HUFF_DECOMPRESS)) < 0) { -// -// /* something on zlib initialization failed. */ -// return LIBMPQ_ERROR_UNPACK; -// } - - /* initialize the huffman tree for decompression. */ - libmpq__huffman_tree_init(ht, LIBMPQ_HUFF_DECOMPRESS); - - /* save the number of copied bytes. */ - tb = libmpq__do_decompress_huffman(ht, is, out_buf, out_size); - - /* free structures. */ - free(is); - free(ht); - - /* return transferred bytes. */ - return tb; -} - -/* this function decompress a stream using zlib algorithm. */ -int32_t libmpq__decompress_zlib(uint8_t *in_buf, uint32_t in_size, uint8_t *out_buf, uint32_t out_size) { - - /* some common variables. */ - int32_t result = 0; - int32_t tb = 0; - z_stream z; - - /* fill the stream structure for zlib. */ - z.next_in = (Bytef *)in_buf; - z.avail_in = (uInt)in_size; - z.total_in = in_size; - z.next_out = (Bytef *)out_buf; - z.avail_out = (uInt)out_size; - z.total_out = 0; - z.zalloc = NULL; - z.zfree = NULL; - - /* initialize the decompression structure, storm.dll uses zlib version 1.1.3. */ - if ((result = inflateInit(&z)) != Z_OK) { - - /* something on zlib initialization failed. */ - return result; - } - - /* call zlib to decompress the data. */ - if ((result = inflate(&z, Z_FINISH)) != Z_STREAM_END) { - - /* something on zlib decompression failed. */ - return result; - } - - /* save transferred bytes. */ - tb = z.total_out; - - /* cleanup zlib. */ - if ((result = inflateEnd(&z)) != Z_OK) { - - /* something on zlib finalization failed. */ - return result; - } - - /* return transferred bytes. */ - return tb; -} - -/* this function decompress a stream using pkzip algorithm. */ -int32_t libmpq__decompress_pkzip(uint8_t *in_buf, uint32_t in_size, uint8_t *out_buf, uint32_t out_size) { - - /* some common variables. */ - int32_t tb = 0; - uint8_t *work_buf; - pkzip_data_s info; - - /* allocate memory for pkzip data structure. */ - if ((work_buf = malloc(sizeof(pkzip_cmp_s))) == NULL) { - - /* memory allocation problem. */ - return LIBMPQ_ERROR_MALLOC; - } - - /* cleanup. */ - memset(work_buf, 0, sizeof(pkzip_cmp_s)); - - /* fill data information structure. */ - info.in_buf = in_buf; - info.in_pos = 0; - info.in_bytes = in_size; - info.out_buf = out_buf; - info.out_pos = 0; - info.max_out = out_size; - - /* do the decompression. */ - if ((tb = libmpq__do_decompress_pkzip(work_buf, &info)) < 0) { - - /* free working buffer. */ - free(work_buf); - - /* something failed on pkzip decompression. */ - return tb; - } - - /* save transferred bytes. */ - tb = info.out_pos; - - /* free working buffer. */ - free(work_buf); - - /* return transferred bytes. */ - return tb; -} - -/* this function decompress a stream using bzip2 library. */ -int32_t libmpq__decompress_bzip2(uint8_t *in_buf, uint32_t in_size, uint8_t *out_buf, uint32_t out_size) { - - /* some common variables. */ - int32_t result = 0; - int32_t tb = 0; - bz_stream strm; - - /* initialize the bzlib decompression. */ - strm.bzalloc = NULL; - strm.bzfree = NULL; - - /* initialize the structure. */ - if ((result = BZ2_bzDecompressInit(&strm, 0, 0)) != BZ_OK) { - - /* something on bzlib initialization failed. */ - return result; - } - - /* fill the stream structure for bzlib. */ - strm.next_in = (char *)in_buf; - strm.avail_in = in_size; - strm.next_out = (char *)out_buf; - strm.avail_out = out_size; - - /* do the decompression. */ - while (BZ2_bzDecompress(&strm) != BZ_STREAM_END); - - /* save transferred bytes. */ - tb = strm.total_out_lo32; - - /* cleanup of bzip stream. */ - BZ2_bzDecompressEnd(&strm); - - /* return transferred bytes. */ - return tb; -} - -/* this function decompress a stream using wave algorithm. (1 channel) */ -int32_t libmpq__decompress_wave_mono(uint8_t *in_buf, uint32_t in_size, uint8_t *out_buf, uint32_t out_size) { - - /* some common variables. */ - int32_t tb = 0; - - /* save the number of copied bytes. */ - if ((tb = libmpq__do_decompress_wave(out_buf, out_size, in_buf, in_size, 1)) < 0) { - - /* something on wave decompression failed. */ - return tb; - } - - /* return transferred bytes. */ - return tb; -} - -/* this function decompress a stream using wave algorithm. (2 channels) */ -int32_t libmpq__decompress_wave_stereo(uint8_t *in_buf, uint32_t in_size, uint8_t *out_buf, uint32_t out_size) { - - /* some common variables. */ - int32_t tb = 0; - - /* save the number of copied bytes. */ - if ((tb = libmpq__do_decompress_wave(out_buf, out_size, in_buf, in_size, 2)) < 0) { - - /* something on wave decompression failed. */ - return tb; - } - - /* return transferred bytes. */ - return tb; -} - -/* this function decompress a stream using a combination of the other compression algorithm. */ -int32_t libmpq__decompress_multi(uint8_t *in_buf, uint32_t in_size, uint8_t *out_buf, uint32_t out_size) { - - /* some common variables. */ - int32_t tb = 0; - uint32_t count = 0; - uint32_t entries = (sizeof(dcmp_table) / sizeof(decompress_table_s)); - uint8_t *temp_buf = NULL; - uint8_t *work_buf = 0; - uint8_t decompress_flag, decompress_unsupp; - uint32_t i; - - /* get applied compression types. */ - decompress_flag = decompress_unsupp = *in_buf++; - - /* decrement data size. */ - in_size--; - - /* search decompression table type and get all types of compression. */ - for (i = 0; i < entries; i++) { - - /* check if have to apply this decompression. */ - if (decompress_flag & dcmp_table[i].mask) { - - /* increase counter for used compression algorithms. */ - count++; - /* this algorithm is supported, remove from unsupp mask */ - decompress_unsupp &= ~dcmp_table[i].mask; - } - } - - /* check if there is some method unhandled. (e.g. compressed by future versions) */ - if (decompress_unsupp) { - - /* compression type is unknown and we need to implement it. :) */ - return LIBMPQ_ERROR_UNPACK; - } - - /* if multiple decompressions should be made, we need temporary buffer for the data. */ - if (count > 1) { - - /* allocate memory for temporary buffer. */ - if ((temp_buf = malloc(out_size)) == NULL) { - - /* memory allocation problem. */ - return LIBMPQ_ERROR_MALLOC; - } - - /* cleanup. */ - memset(temp_buf, 0, out_size); - } - - /* apply all decompressions. */ - for (i = 0, count = 0; i < entries; i++) { - - /* check if not used this kind of compression. */ - if (decompress_flag & dcmp_table[i].mask) { - - /* if multiple decompressions should be made, we need temporary buffer for the data. */ - if (count == 0) { - - /* use output buffer as working buffer. */ - work_buf = out_buf; - } else { - - /* use temporary buffer as working buffer. */ - work_buf = temp_buf; - } - - /* decompress buffer using corresponding function. */ - if ((tb = dcmp_table[i].decompress(in_buf, in_size, work_buf, out_size)) < 0) { - - /* free temporary buffer. */ - free(temp_buf); - - /* something on decompression failed. */ - return tb; - } - - /* move output size to source size for next compression. */ - in_size = out_size; - in_buf = work_buf; - - /* increase counter. */ - count++; - } - } - - /* if output buffer is not the same like target buffer, we have to copy data (this will happen on multiple decompressions). */ - if (work_buf != out_buf) { - - /* copy buffer. */ - memcpy(out_buf, in_buf, out_size); - } - - /* free temporary buffer. */ - free(temp_buf); - - /* return transferred bytes. */ - return tb; -} diff --git a/externals/libmpq/libmpq/extract.h b/externals/libmpq/libmpq/extract.h deleted file mode 100644 index d6ea794f162..00000000000 --- a/externals/libmpq/libmpq/extract.h +++ /dev/null @@ -1,106 +0,0 @@ -/* - * extract.h -- header for the extraction functions used by mpq-tools. - * - * Copyright (c) 2003-2008 Maik Broemme - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ - -#ifndef _EXTRACT_H -#define _EXTRACT_H - -/* define compression types for multilpe compressions. */ -#define LIBMPQ_COMPRESSION_HUFFMAN 0x01 /* huffman compression. (used on wave files only and introduced in starcraft) */ -#define LIBMPQ_COMPRESSION_ZLIB 0x02 /* zlib compression. (introduced in warcraft 3) */ -#define LIBMPQ_COMPRESSION_PKZIP 0x08 /* pkware dcl compression. (first used compression algorithm) */ -#define LIBMPQ_COMPRESSION_BZIP2 0x10 /* bzip compression. (introduced in warcraft 3 - the frozen throne) */ -#define LIBMPQ_COMPRESSION_WAVE_MONO 0x40 /* adpcm 4:1 compression. (introduced in starcraft) */ -#define LIBMPQ_COMPRESSION_WAVE_STEREO 0x80 /* adpcm 4:1 compression. (introduced in starcraft) */ - -/* - * table for decompression functions, return value for all functions - * is the transferred data size or one of the following error constants: - * - * LIBMPQ_ERROR_MALLOC - * LIBMPQ_ERROR_DECOMPRESS - */ -typedef int32_t (*DECOMPRESS)(uint8_t *, uint32_t, uint8_t *, uint32_t); -typedef struct { - uint32_t mask; /* decompression bit. */ - DECOMPRESS decompress; /* decompression function. */ -} decompress_table_s; - -/* - * huffman decompression routine, the in_size parameter is not used, - * but needs to be specified due to compatibility reasons. - * - * 1500F5F0 - */ -extern int32_t libmpq__decompress_huffman( - uint8_t *in_buf, - uint32_t in_size, - uint8_t *out_buf, - uint32_t out_size -); - -/* decompression using zlib. */ -extern int32_t libmpq__decompress_zlib( - uint8_t *in_buf, - uint32_t in_size, - uint8_t *out_buf, - uint32_t out_size -); - -/* decompression using pkzip. */ -extern int32_t libmpq__decompress_pkzip( - uint8_t *in_buf, - uint32_t in_size, - uint8_t *out_buf, - uint32_t out_size -); - -/* decompression using bzip2. */ -extern int32_t libmpq__decompress_bzip2( - uint8_t *in_buf, - uint32_t in_size, - uint8_t *out_buf, - uint32_t out_size -); - -/* decompression using wave. (1 channel) */ -extern int32_t libmpq__decompress_wave_mono( - uint8_t *in_buf, - uint32_t in_size, - uint8_t *out_buf, - uint32_t out_size -); - -/* decompression using wave. (2 channels) */ -extern int32_t libmpq__decompress_wave_stereo( - uint8_t *in_buf, - uint32_t in_size, - uint8_t *out_buf, - uint32_t out_size -); - -/* decompression using multiple of the above algorithm. */ -extern int32_t libmpq__decompress_multi( - uint8_t *in_buf, - uint32_t in_size, - uint8_t *out_buf, - uint32_t out_size -); - -#endif /* _EXTRACT_H */ diff --git a/externals/libmpq/libmpq/huffman.c b/externals/libmpq/libmpq/huffman.c deleted file mode 100644 index 8fc87be2f60..00000000000 --- a/externals/libmpq/libmpq/huffman.c +++ /dev/null @@ -1,1101 +0,0 @@ -/* - * huffman.c -- functions do decompress files in mpq files which - * uses a modified huffman version. - * - * Copyright (c) 2003-2008 Maik Broemme - * - * Differences between C++ and C version: - * - * - Removed the object oriented stuff. - * - Replaced the goto things with some better C code. - * - * This source was adepted from the C++ version of huffman.cpp included - * in stormlib. The C++ version belongs to the following authors: - * - * Ladislav Zezula - * ShadowFlare - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ - -/* generic includes. */ -#include -#include - -/* libmpq main includes. */ -#include "mpq.h" -#include "mpq-internal.h" - -/* libmpq generic includes. */ -#include "huffman.h" - -/* tables for huffman tree. */ -static const uint8_t table_1502A630[] = { - - /* data for compression type 0x00. */ - 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, - 0x00, 0x00, - - /* data for compression type 0x01. */ - 0x54, 0x16, 0x16, 0x0D, 0x0C, 0x08, 0x06, 0x05, 0x06, 0x05, 0x06, 0x03, 0x04, 0x04, 0x03, 0x05, - 0x0E, 0x0B, 0x14, 0x13, 0x13, 0x09, 0x0B, 0x06, 0x05, 0x04, 0x03, 0x02, 0x03, 0x02, 0x02, 0x02, - 0x0D, 0x07, 0x09, 0x06, 0x06, 0x04, 0x03, 0x02, 0x04, 0x03, 0x03, 0x03, 0x03, 0x03, 0x02, 0x02, - 0x09, 0x06, 0x04, 0x04, 0x04, 0x04, 0x03, 0x02, 0x03, 0x02, 0x02, 0x02, 0x02, 0x03, 0x02, 0x04, - 0x08, 0x03, 0x04, 0x07, 0x09, 0x05, 0x03, 0x03, 0x03, 0x03, 0x02, 0x02, 0x02, 0x03, 0x02, 0x02, - 0x03, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x01, 0x01, 0x01, 0x02, 0x01, 0x02, 0x02, - 0x06, 0x0A, 0x08, 0x08, 0x06, 0x07, 0x04, 0x03, 0x04, 0x04, 0x02, 0x02, 0x04, 0x02, 0x03, 0x03, - 0x04, 0x03, 0x07, 0x07, 0x09, 0x06, 0x04, 0x03, 0x03, 0x02, 0x01, 0x02, 0x02, 0x02, 0x02, 0x02, - 0x0A, 0x02, 0x02, 0x03, 0x02, 0x02, 0x01, 0x01, 0x02, 0x02, 0x02, 0x06, 0x03, 0x05, 0x02, 0x03, - 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x03, 0x01, 0x01, 0x01, - 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x04, 0x04, 0x04, 0x07, 0x09, 0x08, 0x0C, 0x02, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x03, - 0x04, 0x01, 0x02, 0x04, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, - 0x04, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x01, 0x01, 0x02, 0x02, 0x02, 0x06, 0x4B, - 0x00, 0x00, - - /* data for compression type 0x02. */ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x27, 0x00, 0x00, 0x23, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xFF, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x01, 0x01, 0x06, 0x0E, 0x10, 0x04, - 0x06, 0x08, 0x05, 0x04, 0x04, 0x03, 0x03, 0x02, 0x02, 0x03, 0x03, 0x01, 0x01, 0x02, 0x01, 0x01, - 0x01, 0x04, 0x02, 0x04, 0x02, 0x02, 0x02, 0x01, 0x01, 0x04, 0x01, 0x01, 0x02, 0x03, 0x03, 0x02, - 0x03, 0x01, 0x03, 0x06, 0x04, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x02, 0x01, 0x01, - 0x01, 0x29, 0x07, 0x16, 0x12, 0x40, 0x0A, 0x0A, 0x11, 0x25, 0x01, 0x03, 0x17, 0x10, 0x26, 0x2A, - 0x10, 0x01, 0x23, 0x23, 0x2F, 0x10, 0x06, 0x07, 0x02, 0x09, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, - - /* data for compression type 0x03. */ - 0xFF, 0x0B, 0x07, 0x05, 0x0B, 0x02, 0x02, 0x02, 0x06, 0x02, 0x02, 0x01, 0x04, 0x02, 0x01, 0x03, - 0x09, 0x01, 0x01, 0x01, 0x03, 0x04, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, - 0x05, 0x01, 0x01, 0x01, 0x0D, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x02, 0x01, 0x01, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, - 0x0A, 0x04, 0x02, 0x01, 0x06, 0x03, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x03, 0x01, 0x01, 0x01, - 0x05, 0x02, 0x03, 0x04, 0x03, 0x03, 0x03, 0x02, 0x01, 0x01, 0x01, 0x02, 0x01, 0x02, 0x03, 0x03, - 0x01, 0x03, 0x01, 0x01, 0x02, 0x05, 0x01, 0x01, 0x04, 0x03, 0x05, 0x01, 0x03, 0x01, 0x03, 0x03, - 0x02, 0x01, 0x04, 0x03, 0x0A, 0x06, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x02, 0x02, 0x01, 0x0A, 0x02, 0x05, 0x01, 0x01, 0x02, 0x07, 0x02, 0x17, 0x01, 0x05, 0x01, 0x01, - 0x0E, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x06, 0x02, 0x01, 0x04, 0x05, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x07, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, - 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x11, - 0x00, 0x00, - - /* data for compression type 0x04. */ - 0xFF, 0xFB, 0x98, 0x9A, 0x84, 0x85, 0x63, 0x64, 0x3E, 0x3E, 0x22, 0x22, 0x13, 0x13, 0x18, 0x17, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, - - /* data for compression type 0x05. */ - 0xFF, 0xF1, 0x9D, 0x9E, 0x9A, 0x9B, 0x9A, 0x97, 0x93, 0x93, 0x8C, 0x8E, 0x86, 0x88, 0x80, 0x82, - 0x7C, 0x7C, 0x72, 0x73, 0x69, 0x6B, 0x5F, 0x60, 0x55, 0x56, 0x4A, 0x4B, 0x40, 0x41, 0x37, 0x37, - 0x2F, 0x2F, 0x27, 0x27, 0x21, 0x21, 0x1B, 0x1C, 0x17, 0x17, 0x13, 0x13, 0x10, 0x10, 0x0D, 0x0D, - 0x0B, 0x0B, 0x09, 0x09, 0x08, 0x08, 0x07, 0x07, 0x06, 0x05, 0x05, 0x04, 0x04, 0x04, 0x19, 0x18, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, - - /* data for compression type 0x06. */ - 0xC3, 0xCB, 0xF5, 0x41, 0xFF, 0x7B, 0xF7, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xBF, 0xCC, 0xF2, 0x40, 0xFD, 0x7C, 0xF7, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x7A, 0x46, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, - - /* data for compression type 0x07. */ - 0xC3, 0xD9, 0xEF, 0x3D, 0xF9, 0x7C, 0xE9, 0x1E, 0xFD, 0xAB, 0xF1, 0x2C, 0xFC, 0x5B, 0xFE, 0x17, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xBD, 0xD9, 0xEC, 0x3D, 0xF5, 0x7D, 0xE8, 0x1D, 0xFB, 0xAE, 0xF0, 0x2C, 0xFB, 0x5C, 0xFF, 0x18, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x70, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, - - /* data for compression type 0x08. */ - 0xBA, 0xC5, 0xDA, 0x33, 0xE3, 0x6D, 0xD8, 0x18, 0xE5, 0x94, 0xDA, 0x23, 0xDF, 0x4A, 0xD1, 0x10, - 0xEE, 0xAF, 0xE4, 0x2C, 0xEA, 0x5A, 0xDE, 0x15, 0xF4, 0x87, 0xE9, 0x21, 0xF6, 0x43, 0xFC, 0x12, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xB0, 0xC7, 0xD8, 0x33, 0xE3, 0x6B, 0xD6, 0x18, 0xE7, 0x95, 0xD8, 0x23, 0xDB, 0x49, 0xD0, 0x11, - 0xE9, 0xB2, 0xE2, 0x2B, 0xE8, 0x5C, 0xDD, 0x15, 0xF1, 0x87, 0xE7, 0x20, 0xF7, 0x44, 0xFF, 0x13, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x5F, 0x9E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00 -}; - -/* this function insert an item to a huffman tree. */ -void libmpq__huffman_insert_item(struct huffman_tree_item_s **p_item, struct huffman_tree_item_s *item, uint32_t where, struct huffman_tree_item_s *item2) { - - /* EDI - next to the first item. */ - struct huffman_tree_item_s *next = item->next; - - /* ESI - prev to the first item. */ - struct huffman_tree_item_s *prev = item->prev; - - /* pointer to previous item. */ - struct huffman_tree_item_s *prev2; - - /* pointer to next item. */ - long next2; - - /* check the first item already has next one. */ - if (next != 0) { - - /* check if previous item exist. */ - if (PTR_INT(prev) < 0) { - - /* return previous item. */ - prev = PTR_NOT(prev); - } else { - - /* add item. */ - prev += (item - next->prev); - } - - /* 150083C1 - remove the item from the tree. */ - prev->next = next; - next->prev = prev; - - /* invalidate prev and next pointer. */ - item->next = 0; - item->prev = 0; - } - - /* EDX - check if the second item is not entered. */ - if (item2 == NULL) { - - /* take the first tree item. */ - item2 = PTR_PTR(&p_item[1]); - } - - /* check if items should be switched or new one inserted. */ - switch (where) { - case SWITCH_ITEMS: - - /* item2->next (pointer to pointer to first). */ - item->next = item2->next; - item->prev = item2->next->prev; - item2->next->prev = item; - - /* set the first item. */ - item2->next = item; - - /* return from function. */ - return; - case INSERT_ITEM: - - /* set next item (or pointer to pointer to first item) - insert as last item. */ - item->next = item2; - - /* set previous item (or last item in the tree). */ - item->prev = item2->prev; - - /* usually NULL. */ - next2 = PTR_INT(p_item[0]); - - /* previous item to the second (or last tree item). */ - prev2 = item2->prev; - - /* check if previous item is a valid pointer. */ - if (PTR_INT(prev2) < 0) { - - /* set values. */ - prev2 = PTR_NOT(prev); - prev2->next = item; - - /* next after last item. */ - item2->prev = item; - - /* return from function. */ - return; - } - - /* check if next item is empty. */ - if (next2 < 0) { - - /* set next item. */ - next2 = item2 - item2->next->prev; - } - - /* add next item to previous one. */ - prev2 += next2; - prev2->next = item; - - /* set the next and last item. */ - item2->prev = item; - - /* return from function. */ - return; - default: - - /* nothing to do, so return from function. */ - return; - } -} - -/* 1500BC90 - remove item from huffman tree.*/ -void libmpq__huffman_remove_item(struct huffman_tree_item_s *hi) { - - /* EDX - some common variables. */ - struct huffman_tree_item_s *temp; - - /* check if next item is not empty. */ - if (hi->next != NULL) { - - /* fetch previous item. */ - temp = hi->prev; - - /* check if previous item is a pointer. */ - if (PTR_INT(temp) <= 0) { - temp = PTR_NOT(temp); - } else { - temp += (hi - hi->next->prev); - } - - /* reorganize tree. */ - temp->next = hi->next; - hi->next->prev = hi->prev; - hi->next = hi->prev = NULL; - } -} - -/* get previous huffman tree item. */ -struct huffman_tree_item_s *libmpq__huffman_previous_item(struct huffman_tree_item_s *hi, long value) { - - /* check if previous item exist. */ - if (PTR_INT(hi->prev) < 0) { - - /* return previous item. */ - return PTR_NOT(hi->prev); - } - - /* check if something else should returned. */ - if (value < 0) { - - /* fetch previous item of next item. */ - value = hi - hi->next->prev; - } - - /* return previous item with value. */ - return hi->prev + value; -} - -/* get one bit from input stream. */ -uint32_t libmpq__huffman_get_1bit(struct huffman_input_stream_s *is) { - - /* some common variables. */ - uint32_t bit = (is->bit_buf & 1); - - /* shift bit right by one. */ - is->bit_buf >>= 1; - - /* check if we should extract bits. */ - if (--is->bits == 0) { - is->bit_buf = *(uint32_t *)is->in_buf; - is->in_buf += sizeof(int32_t); - is->bits = 32; - } - - /* return the bit. */ - return bit; -} - -/* get 7 bits from the input stream. */ -uint32_t libmpq__huffman_get_7bit(struct huffman_input_stream_s *is) { - - /* check if we should extract bits. */ - if (is->bits <= 7) { - is->bit_buf |= *(uint16_t *)is->in_buf << is->bits; - is->in_buf += sizeof(int16_t); - is->bits += 16; - } - - /* get 7 bits from input stream. */ - return (is->bit_buf & 0x7F); -} - -/* get the whole byte from the input stream. */ -uint32_t libmpq__huffman_get_8bit(struct huffman_input_stream_s *is) { - - /* some common variables. */ - uint32_t one_byte; - - /* check if we should extract bits. */ - if (is->bits <= 8) { - is->bit_buf |= *(uint16_t *)is->in_buf << is->bits; - is->in_buf += sizeof(int16_t); - is->bits += 16; - } - - /* fill values. */ - one_byte = (is->bit_buf & 0xFF); - is->bit_buf >>= 8; - is->bits -= 8; - - /* return the 8 bits. */ - return one_byte; -} - -/* return struct for 1500E740. */ -struct huffman_tree_item_s *libmpq__huffman_call_1500E740(struct huffman_tree_s *ht) { - - /* EDX */ - struct huffman_tree_item_s *p_item1 = ht->item3058; - - /* EAX */ - struct huffman_tree_item_s *p_item2; - - /* some common variables. */ - struct huffman_tree_item_s *p_next; - struct huffman_tree_item_s *p_prev; - struct huffman_tree_item_s **pp_item; - - /* check if item is empty. */ - if (PTR_INT(p_item1) <= 0 || (p_item2 = p_item1) == NULL) { - - /* check if item is not empty. */ - if ((p_item2 = &ht->items0008[ht->items++]) != NULL) { - p_item1 = p_item2; - } else { - p_item1 = ht->first; - } - } else { - p_item1 = p_item2; - } - - /* set next item. */ - p_next = p_item1->next; - - /* check if next item is not empty. */ - if (p_next != NULL) { - - /* set previous item. */ - p_prev = p_item1->prev; - - /* check if previous item is a valid pointer. */ - if (PTR_INT(p_prev) <= 0) { - p_prev = PTR_NOT(p_prev); - } else { - p_prev += (p_item1 - p_item1->next->prev); - } - - /* fill values. */ - p_prev->next = p_next; - p_next->prev = p_prev; - p_item1->next = NULL; - p_item1->prev = NULL; - } - - /* ESI */ - pp_item = &ht->first; - p_item1->next = (struct huffman_tree_item_s *)pp_item; - p_item1->prev = pp_item[1]; - - /* EDI = ht->item305C - ECX */ - p_prev = pp_item[1]; - - /* check if previous pointer is valid. */ - if (p_prev <= 0) { - - /* fill values. */ - p_prev = PTR_NOT(p_prev); - p_prev->next = p_item1; - p_prev->prev = p_item2; - p_item2->parent = NULL; - p_item2->child = NULL; - } else { - - /* check if pointer is valid. */ - if (PTR_INT(ht->item305C) < 0) { - p_prev += (struct huffman_tree_item_s *)pp_item - (*pp_item)->prev; - } else { - p_prev += PTR_INT(ht->item305C); - } - - /* fill values. */ - p_prev->next = p_item1; - pp_item[1] = p_item2; - p_item2->parent = NULL; - p_item2->child = NULL; - } - - /* return item. */ - return p_item2; -} - -/* return struct for 1500E820. */ -void libmpq__huffman_call_1500E820(struct huffman_tree_s *ht, struct huffman_tree_item_s *p_item) { - - /* EDI */ - struct huffman_tree_item_s *p_item1; - - /* EAX */ - struct huffman_tree_item_s *p_item2 = NULL; - - /* EDX */ - struct huffman_tree_item_s *p_item3; - - /* EBX */ - struct huffman_tree_item_s *p_prev; - - /* loop through parent items. */ - for (; p_item != NULL; p_item = p_item->parent) { - - /* increase byte counter. */ - p_item->byte_value++; - - /* loop through previous items. */ - for (p_item1 = p_item; ; p_item1 = p_prev) { - - /* set previous item. */ - p_prev = p_item1->prev; - - /* check if pointer is valid. */ - if (PTR_INT(p_prev) <= 0) { - p_prev = NULL; - break; - } - - /* check if byte value of previous item is higher than actual item. */ - if (p_prev->byte_value >= p_item->byte_value) { - break; - } - } - - /* check if previous item is same like actual item. */ - if (p_item1 == p_item) { - continue; - } - - /* check if next item is not empty, */ - if (p_item1->next != NULL) { - - /* fill values. */ - p_item2 = libmpq__huffman_previous_item(p_item1, -1); - p_item2->next = p_item1->next; - p_item1->next->prev = p_item1->prev; - p_item1->next = NULL; - p_item1->prev = NULL; - } - - /* fill values. */ - p_item2 = p_item->next; - p_item1->next = p_item2; - p_item1->prev = p_item2->prev; - p_item2->prev = p_item1; - p_item->next = p_item1; - - /* check if both items are not empty. */ - if ((p_item2 = p_item1) != NULL) { - - /* fill values. */ - p_item2 = libmpq__huffman_previous_item(p_item, -1); - p_item2->next = p_item->next; - p_item->next->prev = p_item->prev; - p_item->next = NULL; - p_item->prev = NULL; - } - - /* check if previous item is empty. */ - if (p_prev == NULL) { - p_prev = PTR_PTR(&ht->first); - } - - /* fill values. */ - p_item2 = p_prev->next; - p_item->next = p_item2; - p_item->prev = p_item2->prev; - p_item2->prev = p_item; - p_prev->next = p_item; - p_item3 = p_item1->parent->child; - p_item2 = p_item->parent; - - /* check if child item and parent item match. */ - if (p_item2->child == p_item) { - p_item2->child = p_item1; - } - - /* check if items match. */ - if (p_item3 == p_item1) { - p_item1->parent->child = p_item; - } - - /* fill values. */ - p_item2 = p_item->parent; - p_item->parent = p_item1->parent; - p_item1->parent = p_item2; - - /* increase counter. */ - ht->offs0004++; - } -} - -/* this function initialize a huffman tree. */ -void libmpq__huffman_tree_init(struct huffman_tree_s *ht, uint32_t cmp) { - - /* some common variables. */ - uint32_t count; - struct huffman_tree_item_s *hi; - - /* clear links for all the items in the tree. */ - for (hi = ht->items0008, count = 0x203; count != 0; hi++, count--) { - hi->next = hi->prev = NULL; - } - - /* fill values. */ - ht->item3050 = NULL; - ht->item3054 = PTR_PTR(&ht->item3054); - ht->item3058 = PTR_NOT(ht->item3054); - ht->item305C = NULL; - ht->first = PTR_PTR(&ht->first); - ht->last = PTR_NOT(ht->first); - ht->offs0004 = 1; - ht->items = 0; - - /* clear all huffman decompress items, do this only if preparing for decompression. */ - if (cmp == LIBMPQ_HUFF_DECOMPRESS) { - for (count = 0; count < sizeof(ht->qd3474) / sizeof(struct huffman_decompress_s); count++) { - ht->qd3474[count].offs00 = 0; - } - } -} - -/* this function build a huffman tree, called with the first 8 bits loaded from input stream. */ -void libmpq__huffman_tree_build(struct huffman_tree_s *ht, uint32_t cmp_type) { - - /* [ESP+10] - the greatest character found in table. */ - uint32_t max_byte; - - /* [ESP+1C] - pointer to uint8_t in table_1502A630. */ - const uint8_t *byte_array; - - /* thats needed to replace the goto stuff from original source. :) */ - uint32_t found; - - /* [ESP+14] - Pointer to Huffman tree item pointer array. */ - struct huffman_tree_item_s **p_item; - struct huffman_tree_item_s *child1; - - /* some common variables. */ - uint32_t i; - - /* ESI - loop while pointer has a negative value (last entry). */ - while (PTR_INT(ht->last) > 0) { - - /* EAX */ - struct huffman_tree_item_s *temp; - - /* ESI->next */ - if (ht->last->next != NULL) { - libmpq__huffman_remove_item(ht->last); - } - - /* [EDI+4] */ - ht->item3058 = PTR_PTR(&ht->item3054); - - /* EAX */ - ht->last->prev = ht->item3058; - temp = libmpq__huffman_previous_item(PTR_PTR(&ht->item3054), PTR_INT(&ht->item3050)); - temp->next = ht->last; - ht->item3054 = ht->last; - } - - /* clear all pointers in huffman tree item array. */ - memset(ht->items306C, 0, sizeof(ht->items306C)); - - /* greatest character found init to zero. */ - max_byte = 0; - - /* pointer to current entry in huffman tree item pointer array. */ - p_item = (struct huffman_tree_item_s **)&ht->items306C; - - /* ensure we have low 8 bits only. */ - cmp_type &= 0xFF; - - /* EDI also. */ - byte_array = table_1502A630 + cmp_type * 258; - - /* loop to build huffman tree. */ - for (i = 0; i < 0x100; i++, p_item++) { - - /* item to be created. */ - struct huffman_tree_item_s *item = ht->item3058; - struct huffman_tree_item_s *p_item3 = ht->item3058; - uint8_t one_byte = byte_array[i]; - - /* skip all the bytes which are zero. */ - if (byte_array[i] == 0) { - continue; - } - - /* if not valid pointer, take the first available item in the array. */ - if (PTR_INT(item) <= 0) { - item = &ht->items0008[ht->items++]; - } - - /* insert this item as the top of the tree. */ - libmpq__huffman_insert_item(&ht->item305C, item, SWITCH_ITEMS, NULL); - - /* invalidate child and parent. */ - item->parent = NULL; - item->child = NULL; - - /* store pointer into pointer array. */ - *p_item = item; - - /* store counter. */ - item->dcmp_byte = i; - - /* store byte value. */ - item->byte_value = one_byte; - - /* check if byte is to big. */ - if (one_byte >= max_byte) { - - /* set max byte to highest value. */ - max_byte = one_byte; - - /* continue loop. */ - continue; - } - - /* find the first item which has byte value greater than current one byte. */ - found = 0; - - /* EDI - Pointer to the last item. */ - if (PTR_INT((p_item3 = ht->last)) > 0) { - - /* 15006AF7 */ - if (p_item3 != NULL) { - - /* 15006AFB */ - do { - - /* check if we found item. */ - if (p_item3->byte_value >= one_byte) { - found = 1; - break; - } - - /* switch to previous item. */ - p_item3 = p_item3->prev; - } while (PTR_INT(p_item3) > 0); - } - } - - /* check if item was not found. */ - if (found == 0) { - p_item3 = NULL; - } - - /* 15006B09 */ - if (item->next != NULL) { - libmpq__huffman_remove_item(item); - } - - /* 15006B15 */ - if (p_item3 == NULL) { - p_item3 = PTR_PTR(&ht->first); - } - - /* 15006B1F */ - item->next = p_item3->next; - item->prev = p_item3->next->prev; - p_item3->next->prev = item; - p_item3->next = item; - } - - /* 15006B4A */ - for (; i < 0x102; i++) { - - /* EDI */ - struct huffman_tree_item_s **p_item2 = &ht->items306C[i]; - - /* 15006B59 - ESI */ - struct huffman_tree_item_s *item2 = ht->item3058; - - /* check if item is a valid pointer. */ - if (PTR_INT(item2) <= 0) { - item2 = &ht->items0008[ht->items++]; - } - - /* insert the item into tree. */ - libmpq__huffman_insert_item(&ht->item305C, item2, INSERT_ITEM, NULL); - - /* 15006B89 */ - item2->dcmp_byte = i; - item2->byte_value = 1; - item2->parent = NULL; - item2->child = NULL; - *p_item2++ = item2; - } - - /* 15006BAA - EDI - last item (first child to item). */ - if (PTR_INT((child1 = ht->last)) > 0) { - - /* EBP */ - struct huffman_tree_item_s *child2; - - /* ESI */ - struct huffman_tree_item_s *item; - - /* 15006BB8 */ - while (PTR_INT((child2 = child1->prev)) > 0) { - if (PTR_INT((item = ht->item3058)) <= 0) { - item = &ht->items0008[ht->items++]; - } - - /* 15006BE3 */ - libmpq__huffman_insert_item(&ht->item305C, item, SWITCH_ITEMS, NULL); - - /* 15006BF3 */ - item->parent = NULL; - item->child = NULL; - - /* - * EDX = child2->byte_value + child1->byte_value; - * EAX = child1->byte_value; - * ECX = max_byte; (the greatest character (0xFF usually)) - * item->byte_value (0x02 usually) - */ - item->byte_value = child1->byte_value + child2->byte_value; - - /* previous item in the tree. */ - item->child = child1; - child1->parent = item; - child2->parent = item; - - /* EAX = item->byte_value */ - if (item->byte_value >= max_byte) { - max_byte = item->byte_value; - } else { - - /* EDI */ - struct huffman_tree_item_s *p_item2 = child2->prev; - found = 0; - - /* check if item is a valid pointer. */ - if (PTR_INT(p_item2) > 0) { - - /* 15006C2D */ - do { - - /* check if we found item. */ - if (p_item2->byte_value >= item->byte_value) { - found = 1; - break; - } - - /* switch to previous item. */ - p_item2 = p_item2->prev; - } while (PTR_INT(p_item2) > 0); - } - - /* check if item was not found. */ - if (found == 0) { - p_item2 = NULL; - } - - /* check if next item exist. */ - if (item->next != 0) { - - /* some common variables. */ - struct huffman_tree_item_s *temp4 = libmpq__huffman_previous_item(item, -1); - - /* zhe first item changed. */ - temp4->next = item->next; - - /* first->prev changed to negative value. */ - item->next->prev = item->prev; - item->next = NULL; - item->prev = NULL; - } - - /* 15006C62 */ - if (p_item2 == NULL) { - p_item2 = PTR_PTR(&ht->first); - } - - /* set item with 0x100 byte value. */ - item->next = p_item2->next; - - /* set item with 0x17 byte value. */ - item->prev = p_item2->next->prev; - - /* changed prev of item with. */ - p_item2->next->prev = item; - p_item2->next = item; - } - - /* 15006C7B */ - if (PTR_INT((child1 = child2->prev)) <= 0) { - break; - } - } - } - - /* 15006C88 */ - ht->offs0004 = 1; -} - -/* this function did the real decompression. */ -int32_t libmpq__do_decompress_huffman(struct huffman_tree_s *ht, struct huffman_input_stream_s *is, uint8_t *out_buf, uint32_t out_length) { - - /* some common variables. */ - uint32_t dcmp_byte = 0; - uint8_t *out_pos = out_buf; - uint32_t bit_count; - struct huffman_decompress_s *qd; - struct huffman_tree_item_s *p_item1; - struct huffman_tree_item_s *p_item2; - - /* 8 bits loaded from input stream. */ - uint32_t n8bits; - - /* 7 bits loaded from input stream. */ - uint32_t n7bits; - - /* thats needed to replace the goto stuff from original source. :) */ - uint32_t found; - - /* can we use quick decompression */ - uint32_t has_qd; - - /* test the output length, must not be non zero. */ - if (out_length == 0) { - return 0; - } - - /* get the compression type from the input stream. */ - n8bits = libmpq__huffman_get_8bit(is); - - /* build the Huffman tree. */ - libmpq__huffman_tree_build(ht, n8bits); - - /* compression 8 bit or not? */ - ht->cmp0 = (n8bits == 0) ? TRUE : FALSE; - - /* loop until break. */ - for(;;) { - - /* get 7 bits from input stream. */ - n7bits = libmpq__huffman_get_7bit(is); - - /* try to use quick decompression, check huffman decompress struct for corresponding item. */ - qd = &ht->qd3474[n7bits]; - - /* if there is a quick-pass possible (ebx). */ - has_qd = (qd->offs00 >= ht->offs0004) ? TRUE : FALSE; - - /* if we can use quick decompress, use it. */ - if (has_qd) { - found = 0; - if (qd->bits > 7) { - is->bit_buf >>= 7; - is->bits -= 7; - p_item1 = qd->p_item; - found = 1; - } - if (found == 0) { - is->bit_buf >>= qd->bits; - is->bits -= qd->bits; - dcmp_byte = qd->dcmp_byte; - } - } else { - found = 1; - p_item1 = ht->first->next->prev; - if (PTR_INT(p_item1) <= 0) { - p_item1 = NULL; - } - } - - /* check if item was found. */ - if (found == 1) { - bit_count = 0; - p_item2 = NULL; - - /* loop until tree has no deeper level. */ - do { - - /* move down by one level. */ - p_item1 = p_item1->child; - - /* check if current bit is set, move to previous. */ - if (libmpq__huffman_get_1bit(is)) { - p_item1 = p_item1->prev; - } - - /* check if we are at 7th bit, save current huffman tree item. */ - if (++bit_count == 7) { - p_item2 = p_item1; - } - } while (p_item1->child != NULL); - - /* no quick decompression. :( */ - if (has_qd == FALSE) { - - /* check bit counter. */ - if (bit_count > 7) { - qd->offs00 = ht->offs0004; - qd->bits = bit_count; - qd->p_item = p_item2; - } else { - uint32_t index = n7bits & (0xFFFFFFFF >> (32 - bit_count)); - uint32_t add = (1 << bit_count); - - /* loop through compression. */ - for (qd = &ht->qd3474[index]; index <= 0x7F; index += add, qd += add) { - qd->offs00 = ht->offs0004; - qd->bits = bit_count; - qd->dcmp_byte = p_item1->dcmp_byte; - } - } - } - - /* set compression byte. */ - dcmp_byte = p_item1->dcmp_byte; - } - - /* check if huffman tree needs to be modified. */ - if (dcmp_byte == 0x101) { - - /* fill values. */ - n8bits = libmpq__huffman_get_8bit(is); - p_item1 = (ht->last <= 0) ? NULL : ht->last; - p_item2 = libmpq__huffman_call_1500E740(ht); - p_item2->parent = p_item1; - p_item2->dcmp_byte = p_item1->dcmp_byte; - p_item2->byte_value = p_item1->byte_value; - ht->items306C[p_item2->dcmp_byte] = p_item2; - p_item2 = libmpq__huffman_call_1500E740(ht); - p_item2->parent = p_item1; - p_item2->dcmp_byte = n8bits; - p_item2->byte_value = 0; - ht->items306C[p_item2->dcmp_byte] = p_item2; - p_item1->child = p_item2; - - /* call 1500E820. */ - libmpq__huffman_call_1500E820(ht, p_item2); - - /* check if compression is not set. */ - if (ht->cmp0 == 0) { - libmpq__huffman_call_1500E820(ht, ht->items306C[n8bits]); - } - - /* set compression byte. */ - dcmp_byte = n8bits; - } - - /* check for compression. */ - if (dcmp_byte == 0x100) { - break; - } - - /* increase position by compression byte. */ - *out_pos++ = (uint8_t)dcmp_byte; - if (--out_length == 0) { - break; - } - - /* check if compression is not set. */ - if (ht->cmp0) { - libmpq__huffman_call_1500E820(ht, ht->items306C[dcmp_byte]); - } - } - - /* return copied bytes. */ - return (out_pos - out_buf); -} diff --git a/externals/libmpq/libmpq/huffman.h b/externals/libmpq/libmpq/huffman.h deleted file mode 100644 index 6f691088fa0..00000000000 --- a/externals/libmpq/libmpq/huffman.h +++ /dev/null @@ -1,151 +0,0 @@ -/* - * huffman.h -- structures used for huffman compression. - * - * Copyright (c) 2003-2008 Maik Broemme - * - * This source was adepted from the C++ version of huffman.h included - * in stormlib. The C++ version belongs to the following authors: - * - * Ladislav Zezula - * ShadowFlare - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ - -#ifndef _HUFFMAN_H -#define _HUFFMAN_H - -/* define huffman compression and decompression values. */ -#define LIBMPQ_HUFF_DECOMPRESS 0 /* we want to decompress using huffman trees. */ - -/* define pointer conversions. */ -#define PTR_NOT(ptr) (struct huffman_tree_item_s *)(~(unsigned long)(ptr)) -#define PTR_PTR(ptr) ((struct huffman_tree_item_s *)(ptr)) -#define PTR_INT(ptr) (long)(ptr) - -/* define item handling. */ -#define INSERT_ITEM 1 /* insert item into huffman tree. */ -#define SWITCH_ITEMS 2 /* switch items isnide huffman tree. */ - -/* input stream for huffman decompression. */ -struct huffman_input_stream_s { - uint8_t *in_buf; /* 00 - input data. */ - uint32_t bit_buf; /* 04 - input bit buffer. */ - uint32_t bits; /* 08 - number of bits remaining in byte. */ -}; - -/* huffman tree item. */ -struct huffman_tree_item_s { - struct huffman_tree_item_s *next; /* 00 - pointer to next huffman tree item. */ - struct huffman_tree_item_s *prev; /* 04 - pointer to prev huffman tree item (< 0 if none). */ - uint32_t dcmp_byte; /* 08 - index of this item in item pointer array, decompressed byte value. */ - uint32_t byte_value; /* 0C - some byte value. */ - struct huffman_tree_item_s *parent; /* 10 - pointer to parent huffman tree item (NULL if none). */ - struct huffman_tree_item_s *child; /* 14 - pointer to child huffman tree item. */ -}; - -/* structure used for quick decompression. */ -struct huffman_decompress_s { - uint32_t offs00; /* 00 - 1 if resolved. */ - uint32_t bits; /* 04 - bit count. */ - union { - uint32_t dcmp_byte; /* 08 - byte value for decompress (if bitCount <= 7). */ - struct huffman_tree_item_s *p_item; /* 08 - huffman tree item (if number of bits is greater than 7). */ - }; -}; - -/* structure for huffman tree. */ -struct huffman_tree_s { - uint32_t cmp0; /* 0000 - 1 if compression type 0. */ - uint32_t offs0004; /* 0004 - some flag. */ - struct huffman_tree_item_s items0008[0x203]; /* 0008 - huffman tree items. */ - struct huffman_tree_item_s *item3050; /* 3050 - always NULL? */ - struct huffman_tree_item_s *item3054; /* 3054 - pointer to huffman tree item. */ - struct huffman_tree_item_s *item3058; /* 3058 - pointer to huffman tree item (< 0 if invalid). */ - struct huffman_tree_item_s *item305C; /* 305C - usually NULL. */ - struct huffman_tree_item_s *first; /* 3060 - pointer to top (first) huffman tree item. */ - struct huffman_tree_item_s *last; /* 3064 - pointer to bottom (last) huffman tree item (< 0 if invalid). */ - uint32_t items; /* 3068 - number of used huffman tree items. */ - struct huffman_tree_item_s *items306C[0x102]; /* 306C - huffman tree item pointer array. */ - struct huffman_decompress_s qd3474[0x80]; /* 3474 - array for quick decompression. */ - uint8_t table_1502A630[]; /* some table to make struct size flexible. */ -}; - -/* insert a new item into huffman tree. */ -void libmpq__huffman_insert_item( - struct huffman_tree_item_s **p_item, - struct huffman_tree_item_s *item, - uint32_t where, - struct huffman_tree_item_s *item2 -); - -/* remove item from huffman tree. */ -void libmpq__huffman_remove_item( - struct huffman_tree_item_s *hi -); - -/* get previous item from huffman tree. */ -struct huffman_tree_item_s *libmpq__huffman_previous_item( - struct huffman_tree_item_s *hi, - long value -); - -/* get one bit from stream. */ -uint32_t libmpq__huffman_get_1bit( - struct huffman_input_stream_s *is -); - -/* get seven bit from stream. */ -uint32_t libmpq__huffman_get_7bit( - struct huffman_input_stream_s *is -); - -/* get eight bit from stream. */ -uint32_t libmpq__huffman_get_8bit( - struct huffman_input_stream_s *is -); - -/* call 1500E740. */ -struct huffman_tree_item_s *libmpq__huffman_call_1500E740( - struct huffman_tree_s *ht -); - -/* call 1500E820- */ -void libmpq__huffman_call_1500E820( - struct huffman_tree_s *ht, - struct huffman_tree_item_s *p_item -); - -/* initialize the huffman tree. */ -void libmpq__huffman_tree_init( - struct huffman_tree_s *ht, - uint32_t cmp -); - -/* build the huffman tree. */ -void libmpq__huffman_tree_build( - struct huffman_tree_s *ht, - uint32_t cmp_type -); - -/* decompress the stream using huffman compression. */ -int32_t libmpq__do_decompress_huffman( - struct huffman_tree_s *ht, - struct huffman_input_stream_s *is, - uint8_t *out_buf, - uint32_t out_length -); - -#endif /* _HUFFMAN_H */ diff --git a/externals/libmpq/libmpq/mpq-internal.h b/externals/libmpq/libmpq/mpq-internal.h deleted file mode 100644 index 76eabe4190a..00000000000 --- a/externals/libmpq/libmpq/mpq-internal.h +++ /dev/null @@ -1,145 +0,0 @@ -/* - * mpq-internal.h -- some default types and defines, but only required for - * compilation of the library. - * - * Copyright (c) 2003-2008 Maik Broemme - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ - -#ifndef _MPQ_INTERNAL_H -#define _MPQ_INTERNAL_H - -/* generic includes. */ -#include -#include - -/* define return value if nothing failed. */ -#define LIBMPQ_SUCCESS 0 /* return value for all functions which success. */ - -/* define generic mpq archive information. */ -#define LIBMPQ_HEADER 0x1A51504D /* mpq archive header ('MPQ\x1A') */ - -/* define the known archive versions. */ -#define LIBMPQ_ARCHIVE_VERSION_ONE 0 /* version one used until world of warcraft. */ -#define LIBMPQ_ARCHIVE_VERSION_TWO 1 /* version two used from world of warcraft - the burning crusade. */ - -/* define values used by blizzard as flags. */ -#define LIBMPQ_FLAG_EXISTS 0x80000000 /* set if file exists, reset when the file was deleted. */ -#define LIBMPQ_FLAG_ENCRYPTED 0x00010000 /* indicates whether file is encrypted. */ -#define LIBMPQ_FLAG_COMPRESSED 0x0000FF00 /* file is compressed. */ -#define LIBMPQ_FLAG_COMPRESS_PKZIP 0x00000100 /* compression made by pkware data compression library. */ -#define LIBMPQ_FLAG_COMPRESS_MULTI 0x00000200 /* multiple compressions. */ -#define LIBMPQ_FLAG_COMPRESS_NONE 0x00000300 /* no compression (no blizzard flag used by myself). */ -#define LIBMPQ_FLAG_SINGLE 0x01000000 /* file is stored in one single sector, first seen in world of warcraft. */ -#define LIBMPQ_FLAG_CRC 0x04000000 /* compressed block offset table has CRC checksum. */ - -/* define generic hash values. */ -#define LIBMPQ_HASH_FREE 0xFFFFFFFF /* hash table entry is empty and has always been empty. */ - -/* define special files. */ -#define LIBMPQ_LISTFILE_NAME "(listfile)" /* internal listfile. */ -#define LIBMPQ_SIGNATURE_NAME "(signature)" /* internal signature file. */ -#define LIBMPQ_ATTRIBUTES_NAME "(attributes)" /* internal attributes file. */ - -/* define true and false, because not all systems have them. */ -#ifndef FALSE -#define FALSE 0 -#endif -#ifndef TRUE -#define TRUE 1 -#endif - -#include "pack_begin.h" -/* mpq archive header. */ -typedef struct { - uint32_t mpq_magic; /* the 0x1A51504D ('MPQ\x1A') signature. */ - uint32_t header_size; /* mpq archive header size. */ - uint32_t archive_size; /* size of mpq archive. */ - uint16_t version; /* 0000 for starcraft and broodwar. */ - uint16_t block_size; /* size of file block is (512 * 2 ^ block size). */ - uint32_t hash_table_offset; /* file position of mpq_hash. */ - uint32_t block_table_offset; /* file position of mpq_block, each entry has 16 bytes. */ - uint32_t hash_table_count; /* number of entries in hash table. */ - uint32_t block_table_count; /* number of entries in the block table. */ -} PACK_STRUCT mpq_header_s; - -/* mpq extended archive header, used since world of warcraft - the burning crusade. */ -typedef struct { - uint64_t extended_offset; /* offset to the beginning of the extended block table, relative to the beginning of the archive. */ - uint16_t hash_table_offset_high; /* upper 16 bits of the hash table offset for large archives. */ - uint16_t block_table_offset_high;/* upper 16 bits of the block table offset for large archives.*/ -} PACK_STRUCT mpq_header_ex_s; - -/* hash entry, all files in the archive are searched by their hashes. */ -typedef struct { - uint32_t hash_a; /* the first two uint32_ts are the encrypted file. */ - uint32_t hash_b; /* the first two uint32_ts are the encrypted file. */ - uint16_t locale; /* locale information. */ - uint16_t platform; /* platform information and zero is default. */ - uint32_t block_table_index; /* index to file description block. */ -} PACK_STRUCT mpq_hash_s; - -/* file description block contains informations about the file. */ -typedef struct { - uint32_t offset; /* block file starting position in the archive. */ - uint32_t packed_size; /* packed file size. */ - uint32_t unpacked_size; /* unpacked file size. */ - uint32_t flags; /* flags. */ -} PACK_STRUCT mpq_block_s; - -/* extended file description block contains information about the offset beyond 2^32 (4GB). */ -typedef struct { - uint16_t offset_high; /* upper 16 bit of the file offset in archive. */ -} PACK_STRUCT mpq_block_ex_s; - -/* file structure used since diablo 1.00 (0x38 bytes). */ -typedef struct { - uint32_t seed; /* seed used for file decrypt. */ - uint32_t *packed_offset; /* position of each file block (only for packed files). */ - uint32_t open_count; /* number of times it has been opened - used for freeing */ -} PACK_STRUCT mpq_file_s; - -/* map structure for valid blocks and hashes (first seen in warcraft 3 archives). */ -typedef struct { - uint32_t block_table_indices; /* real mapping for file number to block entry. */ - uint32_t block_table_diff; /* block table difference between valid blocks and invalid blocks before. */ -} PACK_STRUCT mpq_map_s; -#include "pack_end.h" - -/* archive structure used since diablo 1.00 by blizzard. */ -struct mpq_archive { - - /* generic file information. */ - FILE *fp; /* file handle. */ - - /* generic size information. */ - uint32_t block_size; /* size of the mpq block. */ - off_t archive_offset; /* absolute start position of archive. */ - - /* archive related buffers and tables. */ - mpq_header_s mpq_header; /* mpq file header. */ - mpq_header_ex_s mpq_header_ex; /* mpq extended file header. */ - mpq_hash_s *mpq_hash; /* hash table. */ - mpq_block_s *mpq_block; /* block table. */ - mpq_block_ex_s *mpq_block_ex; /* extended block table. */ - mpq_file_s **mpq_file; /* pointer to the file pointers which are opened. */ - - /* non archive structure related members. */ - mpq_map_s *mpq_map; /* map table between valid blocks and hashes. */ - uint32_t files; /* number of files in archive, which could be extracted. */ -}; - -#endif /* _MPQ_INTERNAL_H */ diff --git a/externals/libmpq/libmpq/mpq.c b/externals/libmpq/libmpq/mpq.c deleted file mode 100644 index a6ab5db82d9..00000000000 --- a/externals/libmpq/libmpq/mpq.c +++ /dev/null @@ -1,1004 +0,0 @@ -/* - * mpq.c -- functions for developers using libmpq. - * - * Copyright (c) 2003-2008 Maik Broemme - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ - -/* mpq-tools configuration includes. */ -#include "config.h" - -/* libmpq main includes. */ -#include "mpq.h" -#include "mpq-internal.h" - -/* libmpq generic includes. */ -#include "common.h" - -/* generic includes. */ -#include -#include -#include -#include - -/* support for platform specific things */ -#include "platform.h" - -/* this function returns the library version information. */ -const char *libmpq__version(void) { - - /* return version information. */ - return VERSION; -} - -static const char *__libmpq_error_strings[] = { - "success", - "open error on file", - "close error on file", - "lseek error on file", - "read error on file", - "write error on file", - "memory allocation error", - "format errror", - "init() wasn't called", - "buffer size is to small", - "file or block does not exist in archive", - "we don't know the decryption seed", - "error on unpacking file" - }; - -/* this function returns a string message for a return code. */ -const char *libmpq__strerror(int32_t returncode) { - /* check for array bounds */ - if (-returncode < 0 || -returncode > sizeof(__libmpq_error_strings)/sizeof(char*)) - return NULL; - - /* return appropriate string */ - return __libmpq_error_strings[-returncode]; -} - -/* this function read a file and verify if it is a valid mpq archive, then it read and decrypt the hash table. */ -int32_t libmpq__archive_open(mpq_archive_s **mpq_archive, const char *mpq_filename, libmpq__off_t archive_offset) { - - /* some common variables. */ - uint32_t rb = 0; - uint32_t i = 0; - uint32_t count = 0; - int32_t result = 0; - uint32_t header_search = FALSE; - - if (archive_offset == -1) { - archive_offset = 0; - header_search = TRUE; - } - - if ((*mpq_archive = calloc(1, sizeof(mpq_archive_s))) == NULL) { - - /* archive struct could not be allocated */ - return LIBMPQ_ERROR_MALLOC; - } - - /* check if file exists and is readable */ - if (((*mpq_archive)->fp = fopen(mpq_filename, "rb")) == NULL) { - - /* file could not be opened. */ - result = LIBMPQ_ERROR_OPEN; - goto error; - } - - /* assign some default values. */ - (*mpq_archive)->mpq_header.mpq_magic = 0; - (*mpq_archive)->files = 0; - - /* loop through file and search for mpq signature. */ - while (TRUE) { - - /* reset header values. */ - (*mpq_archive)->mpq_header.mpq_magic = 0; - - /* seek in file. */ - if (fseeko((*mpq_archive)->fp, archive_offset, SEEK_SET) < 0) { - - /* seek in file failed. */ - result = LIBMPQ_ERROR_SEEK; - goto error; - } - - /* read header from file. */ - if ((rb = fread(&(*mpq_archive)->mpq_header, 1, sizeof(mpq_header_s), (*mpq_archive)->fp)) != sizeof(mpq_header_s)) { - - /* no valid mpq archive. */ - result = LIBMPQ_ERROR_FORMAT; - goto error; - } - - /* check if we found a valid mpq header. */ - if ((*mpq_archive)->mpq_header.mpq_magic == LIBMPQ_HEADER) { - - /* check if we process old mpq archive version. */ - if ((*mpq_archive)->mpq_header.version == LIBMPQ_ARCHIVE_VERSION_ONE) { - - /* check if the archive is protected. */ - if ((*mpq_archive)->mpq_header.header_size != sizeof(mpq_header_s)) { - - /* correct header size. */ - (*mpq_archive)->mpq_header.header_size = sizeof(mpq_header_s); - } - } - - /* check if we process new mpq archive version. */ - if ((*mpq_archive)->mpq_header.version == LIBMPQ_ARCHIVE_VERSION_TWO) { - - /* check if the archive is protected. */ - if ((*mpq_archive)->mpq_header.header_size != sizeof(mpq_header_s) + sizeof(mpq_header_ex_s)) { - - /* correct header size. */ - (*mpq_archive)->mpq_header.header_size = sizeof(mpq_header_s) + sizeof(mpq_header_ex_s); - } - } - - /* break the loop, because header was found. */ - break; - } - - /* move to the next possible offset. */ - if (!header_search) { - - /* no valid mpq archive. */ - result = LIBMPQ_ERROR_FORMAT; - goto error; - } - archive_offset += 512; - } - - /* store block size for later use. */ - (*mpq_archive)->block_size = 512 << (*mpq_archive)->mpq_header.block_size; - - /* store archive offset and size for later use. */ - (*mpq_archive)->archive_offset = archive_offset; - - /* check if we process new mpq archive version. */ - if ((*mpq_archive)->mpq_header.version == LIBMPQ_ARCHIVE_VERSION_TWO) { - - /* seek in file. */ - if (fseeko((*mpq_archive)->fp, sizeof(mpq_header_s) + archive_offset, SEEK_SET) < 0) { - - /* seek in file failed. */ - result = LIBMPQ_ERROR_SEEK; - goto error; - } - - /* read header from file. */ - if ((rb = fread(&(*mpq_archive)->mpq_header_ex, 1, sizeof(mpq_header_ex_s), (*mpq_archive)->fp)) != sizeof(mpq_header_ex_s)) { - - /* no valid mpq archive. */ - result = LIBMPQ_ERROR_FORMAT; - goto error; - } - } - - /* allocate memory for the block table, hash table, file and block table to file mapping. */ - if (((*mpq_archive)->mpq_block = calloc((*mpq_archive)->mpq_header.block_table_count, sizeof(mpq_block_s))) == NULL || - ((*mpq_archive)->mpq_block_ex = calloc((*mpq_archive)->mpq_header.block_table_count, sizeof(mpq_block_ex_s))) == NULL || - ((*mpq_archive)->mpq_hash = calloc((*mpq_archive)->mpq_header.hash_table_count, sizeof(mpq_hash_s))) == NULL || - ((*mpq_archive)->mpq_file = calloc((*mpq_archive)->mpq_header.block_table_count, sizeof(mpq_file_s))) == NULL || - ((*mpq_archive)->mpq_map = calloc((*mpq_archive)->mpq_header.block_table_count, sizeof(mpq_map_s))) == NULL) { - - /* memory allocation problem. */ - result = LIBMPQ_ERROR_MALLOC; - goto error; - } - - /* seek in file. */ - if (fseeko((*mpq_archive)->fp, (*mpq_archive)->mpq_header.hash_table_offset + (((long long)((*mpq_archive)->mpq_header_ex.hash_table_offset_high)) << 32) + (*mpq_archive)->archive_offset, SEEK_SET) < 0) { - - /* seek in file failed. */ - result = LIBMPQ_ERROR_SEEK; - goto error; - } - - /* read the hash table into the buffer. */ - if ((rb = fread((*mpq_archive)->mpq_hash, 1, (*mpq_archive)->mpq_header.hash_table_count * sizeof(mpq_hash_s), (*mpq_archive)->fp)) < 0) { - - /* something on read failed. */ - result = LIBMPQ_ERROR_READ; - goto error; - } - - /* decrypt the hashtable. */ - libmpq__decrypt_block((uint32_t *)((*mpq_archive)->mpq_hash), (*mpq_archive)->mpq_header.hash_table_count * sizeof(mpq_hash_s), libmpq__hash_string("(hash table)", 0x300)); - - /* seek in file. */ - if (fseeko((*mpq_archive)->fp, (*mpq_archive)->mpq_header.block_table_offset + (((long long)((*mpq_archive)->mpq_header_ex.block_table_offset_high)) << 32) + (*mpq_archive)->archive_offset, SEEK_SET) < 0) { - - /* seek in file failed. */ - result = LIBMPQ_ERROR_SEEK; - goto error; - } - - /* read the block table into the buffer. */ - if ((rb = fread((*mpq_archive)->mpq_block, 1, (*mpq_archive)->mpq_header.block_table_count * sizeof(mpq_block_s), (*mpq_archive)->fp)) < 0) { - - /* something on read failed. */ - result = LIBMPQ_ERROR_READ; - goto error; - } - - /* decrypt block table. */ - libmpq__decrypt_block((uint32_t *)((*mpq_archive)->mpq_block), (*mpq_archive)->mpq_header.block_table_count * sizeof(mpq_block_s), libmpq__hash_string("(block table)", 0x300)); - - /* check if extended block table is present, regardless of version 2 it is only present in archives > 4GB. */ - if ((*mpq_archive)->mpq_header_ex.extended_offset > 0) { - - /* seek in file. */ - if (fseeko((*mpq_archive)->fp, (*mpq_archive)->mpq_header_ex.extended_offset + archive_offset, SEEK_SET) < 0) { - - /* seek in file failed. */ - result = LIBMPQ_ERROR_SEEK; - goto error; - } - - /* read header from file. */ - if ((rb = fread((*mpq_archive)->mpq_block_ex, 1, (*mpq_archive)->mpq_header.block_table_count * sizeof(mpq_block_ex_s), (*mpq_archive)->fp)) < 0) { - - /* no valid mpq archive. */ - result = LIBMPQ_ERROR_FORMAT; - goto error; - } - } - - /* loop through all files in mpq archive and check if they are valid. */ - for (i = 0; i < (*mpq_archive)->mpq_header.block_table_count; i++) { - - /* save block difference between valid and invalid blocks. */ - (*mpq_archive)->mpq_map[i].block_table_diff = i - count; - - /* check if file exists, sizes and offsets are correct. */ - if (((*mpq_archive)->mpq_block[i].flags & LIBMPQ_FLAG_EXISTS) == 0) { - - /* file does not exist, so nothing to do with that block. */ - continue; - } - - /* create final indices tables. */ - (*mpq_archive)->mpq_map[count].block_table_indices = i; - - /* increase file counter. */ - count++; - } - - /* save the number of files. */ - (*mpq_archive)->files = count; - - /* if no error was found, return zero. */ - return LIBMPQ_SUCCESS; - -error: - if ((*mpq_archive)->fp) - fclose((*mpq_archive)->fp); - - free((*mpq_archive)->mpq_map); - free((*mpq_archive)->mpq_file); - free((*mpq_archive)->mpq_hash); - free((*mpq_archive)->mpq_block); - free((*mpq_archive)->mpq_block_ex); - free(*mpq_archive); - - *mpq_archive = NULL; - - return result; -} - -/* this function close the file descriptor, free the decryption buffer and the file list. */ -int32_t libmpq__archive_close(mpq_archive_s *mpq_archive) { - - /* try to close the file */ - if ((fclose(mpq_archive->fp)) < 0) { - - /* don't free anything here, so the caller can try calling us - * again. - */ - return LIBMPQ_ERROR_CLOSE; - } - - /* free header, tables and list. */ - free(mpq_archive->mpq_map); - free(mpq_archive->mpq_file); - free(mpq_archive->mpq_hash); - free(mpq_archive->mpq_block); - free(mpq_archive->mpq_block_ex); - free(mpq_archive); - - /* if no error was found, return zero. */ - return LIBMPQ_SUCCESS; -} - -/* this function return the packed size of all files in the archive. */ -int32_t libmpq__archive_packed_size(mpq_archive_s *mpq_archive, libmpq__off_t *packed_size) { - - /* some common variables. */ - uint32_t i; - - /* loop through all files in archive and count packed size. */ - for (i = 0; i < mpq_archive->files; i++) { - *packed_size += mpq_archive->mpq_block[mpq_archive->mpq_map[i].block_table_indices].packed_size; - } - - /* if no error was found, return zero. */ - return LIBMPQ_SUCCESS; -} - -/* this function return the unpacked size of all files in the archive. */ -int32_t libmpq__archive_unpacked_size(mpq_archive_s *mpq_archive, libmpq__off_t *unpacked_size) { - - /* some common variables. */ - uint32_t i; - - /* loop through all files in archive and count unpacked size. */ - for (i = 0; i < mpq_archive->files; i++) { - *unpacked_size += mpq_archive->mpq_block[mpq_archive->mpq_map[i].block_table_indices].unpacked_size; - } - - /* if no error was found, return zero. */ - return LIBMPQ_SUCCESS; -} - -/* this function return the archive offset (beginning of archive in file). */ -int32_t libmpq__archive_offset(mpq_archive_s *mpq_archive, libmpq__off_t *offset) { - - /* return archive offset. */ - *offset = mpq_archive->archive_offset; - - /* if no error was found, return zero. */ - return LIBMPQ_SUCCESS; -} - -/* this function return the archive offset. */ -int32_t libmpq__archive_version(mpq_archive_s *mpq_archive, uint32_t *version) { - - /* return archive version. */ - *version = mpq_archive->mpq_header.version + 1; - - /* if no error was found, return zero. */ - return LIBMPQ_SUCCESS; -} - -/* this function return the number of valid files in archive. */ -int32_t libmpq__archive_files(mpq_archive_s *mpq_archive, uint32_t *files) { - - /* return archive version. */ - *files = mpq_archive->files; - - /* if no error was found, return zero. */ - return LIBMPQ_SUCCESS; -} - -#define CHECK_FILE_NUM(file_number, mpq_archive) \ - if (file_number < 0 || file_number > mpq_archive->files - 1) { \ - return LIBMPQ_ERROR_EXIST; \ - } - -#define CHECK_BLOCK_NUM(block_number, mpq_archive) \ - if (block_number < 0 || block_number >= ((mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].flags & LIBMPQ_FLAG_SINGLE) != 0 ? 1 : (mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].unpacked_size + mpq_archive->block_size - 1) / mpq_archive->block_size)) { \ - return LIBMPQ_ERROR_EXIST; \ - } - -/* this function return the packed size of the given files in the archive. */ -int32_t libmpq__file_packed_size(mpq_archive_s *mpq_archive, uint32_t file_number, libmpq__off_t *packed_size) { - - /* check if given file number is not out of range. */ - CHECK_FILE_NUM(file_number, mpq_archive) - - /* get the packed size of file. */ - *packed_size = mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].packed_size; - - /* if no error was found, return zero. */ - return LIBMPQ_SUCCESS; -} - -/* this function return the unpacked size of the given file in the archive. */ -int32_t libmpq__file_unpacked_size(mpq_archive_s *mpq_archive, uint32_t file_number, libmpq__off_t *unpacked_size) { - - /* check if given file number is not out of range. */ - CHECK_FILE_NUM(file_number, mpq_archive) - - /* get the unpacked size of file. */ - *unpacked_size = mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].unpacked_size; - - /* if no error was found, return zero. */ - return LIBMPQ_SUCCESS; -} - -/* this function return the file offset (beginning of file in archive). */ -int32_t libmpq__file_offset(mpq_archive_s *mpq_archive, uint32_t file_number, libmpq__off_t *offset) { - - /* check if given file number is not out of range. */ - CHECK_FILE_NUM(file_number, mpq_archive) - - /* return file offset relative to archive start. */ - *offset = mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].offset + (((long long)mpq_archive->mpq_block_ex[mpq_archive->mpq_map[file_number].block_table_indices].offset_high) << 32); - - /* if no error was found, return zero. */ - return LIBMPQ_SUCCESS; -} - -/* this function return the number of blocks for the given file in the archive. */ -int32_t libmpq__file_blocks(mpq_archive_s *mpq_archive, uint32_t file_number, uint32_t *blocks) { - - /* check if given file number is not out of range. */ - CHECK_FILE_NUM(file_number, mpq_archive) - - /* return the number of blocks for the given file. */ - *blocks = (mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].flags & LIBMPQ_FLAG_SINGLE) != 0 ? 1 : (mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].unpacked_size + mpq_archive->block_size - 1) / mpq_archive->block_size; - - /* if no error was found, return zero. */ - return LIBMPQ_SUCCESS; -} - -/* this function return if the file is encrypted or not. */ -int32_t libmpq__file_encrypted(mpq_archive_s *mpq_archive, uint32_t file_number, uint32_t *encrypted) { - - /* check if given file number is not out of range. */ - CHECK_FILE_NUM(file_number, mpq_archive) - - /* return the encryption status of file. */ - *encrypted = (mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].flags & LIBMPQ_FLAG_ENCRYPTED) != 0 ? TRUE : FALSE; - - /* if no error was found, return zero. */ - return LIBMPQ_SUCCESS; -} - -/* this function return if the file is compressed or not. */ -int32_t libmpq__file_compressed(mpq_archive_s *mpq_archive, uint32_t file_number, uint32_t *compressed) { - - /* check if given file number is not out of range. */ - CHECK_FILE_NUM(file_number, mpq_archive) - - /* return the compression status of file. */ - *compressed = (mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].flags & LIBMPQ_FLAG_COMPRESS_MULTI) != 0 ? TRUE : FALSE; - - /* if no error was found, return zero. */ - return LIBMPQ_SUCCESS; -} - -/* this function return if the file is imploded or not. */ -int32_t libmpq__file_imploded(mpq_archive_s *mpq_archive, uint32_t file_number, uint32_t *imploded) { - - /* check if given file number is not out of range. */ - CHECK_FILE_NUM(file_number, mpq_archive) - - /* return the implosion status of file. */ - *imploded = (mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].flags & LIBMPQ_FLAG_COMPRESS_PKZIP) != 0 ? TRUE : FALSE; - - /* if no error was found, return zero. */ - return LIBMPQ_SUCCESS; -} - -/* this function return filenumber by the given name. */ -int32_t libmpq__file_number(mpq_archive_s *mpq_archive, const char *filename, uint32_t *number) { - - /* some common variables. */ - uint32_t i, hash1, hash2, hash3, ht_count; - - /* if the list of file names doesn't include this one, we'll have - * to figure out the file number the "hard" way. - */ - ht_count = mpq_archive->mpq_header.hash_table_count; - - hash1 = libmpq__hash_string (filename, 0x0) & (ht_count - 1); - hash2 = libmpq__hash_string (filename, 0x100); - hash3 = libmpq__hash_string (filename, 0x200); - - /* loop through all files in mpq archive. - * hash1 gives us a clue about the starting position of this - * search. - */ - for (i = hash1; mpq_archive->mpq_hash[i].block_table_index != LIBMPQ_HASH_FREE; i = (i + 1) & (ht_count - 1)) { - - /* if the other two hashes match, we found our file number. */ - if (mpq_archive->mpq_hash[i].hash_a == hash2 && - mpq_archive->mpq_hash[i].hash_b == hash3) { - - /* return the file number. */ - *number = mpq_archive->mpq_hash[i].block_table_index - mpq_archive->mpq_map[mpq_archive->mpq_hash[i].block_table_index].block_table_diff; - - /* we found our file, return zero. */ - return LIBMPQ_SUCCESS; - } - - /* check if we have cycled through the whole hash table */ - if (((i + 1) & (ht_count - 1)) == hash1) { - break; - } - } - - /* if no matching entry found, so return error. */ - return LIBMPQ_ERROR_EXIST; -} - -/* this function read the given file from archive into a buffer. */ -int32_t libmpq__file_read(mpq_archive_s *mpq_archive, uint32_t file_number, uint8_t *out_buf, libmpq__off_t out_size, libmpq__off_t *transferred) { - - /* some common variables. */ - uint32_t i; - uint32_t blocks = 0; - int32_t result = 0; - libmpq__off_t file_offset = 0; - libmpq__off_t unpacked_size = 0; - libmpq__off_t transferred_block = 0; - libmpq__off_t transferred_total = 0; - - /* check if given file number is not out of range. */ - CHECK_FILE_NUM(file_number, mpq_archive) - - /* get target size of block. */ - libmpq__file_unpacked_size(mpq_archive, file_number, &unpacked_size); - - /* check if target buffer is to small. */ - if (unpacked_size > out_size) { - - /* output buffer size is to small or block size is unknown. */ - return LIBMPQ_ERROR_SIZE; - } - - /* fetch file offset. */ - libmpq__file_offset(mpq_archive, file_number, &file_offset); - - /* get block count for file. */ - libmpq__file_blocks(mpq_archive, file_number, &blocks); - - /* open the packed block offset table. */ - if ((result = libmpq__block_open_offset(mpq_archive, file_number)) < 0) { - - /* something on opening packed block offset table failed. */ - return result; - } - - /* loop through all blocks. */ - for (i = 0; i < blocks; i++) { - - /* cleanup size variable. */ - unpacked_size = 0; - - /* get unpacked block size. */ - libmpq__block_unpacked_size(mpq_archive, file_number, i, &unpacked_size); - - /* read block. */ - if ((result = libmpq__block_read(mpq_archive, file_number, i, out_buf + transferred_total, unpacked_size, &transferred_block)) < 0) { - - /* close the packed block offset table. */ - libmpq__block_close_offset(mpq_archive, file_number); - - /* something on reading block failed. */ - return result; - } - - transferred_total += transferred_block; - - } - - /* close the packed block offset table. */ - libmpq__block_close_offset(mpq_archive, file_number); - - /* check for null pointer. */ - if (transferred != NULL) { - - /* store transferred bytes. */ - *transferred = transferred_total; - } - - /* if no error was found, return zero. */ - return LIBMPQ_SUCCESS; -} - -/* this function open a file in the given archive and caches the block offset information. */ -int32_t libmpq__block_open_offset(mpq_archive_s *mpq_archive, uint32_t file_number) { - - /* some common variables. */ - uint32_t i; - uint32_t packed_size; - int32_t rb = 0; - int32_t result = 0; - - /* check if given file number is not out of range. */ - CHECK_FILE_NUM(file_number, mpq_archive) - - if (mpq_archive->mpq_file[file_number]) { - - /* file already opened, so increment counter */ - mpq_archive->mpq_file[file_number]->open_count++; - return LIBMPQ_SUCCESS; - } - - /* check if file is not stored in a single sector. */ - if ((mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].flags & LIBMPQ_FLAG_SINGLE) == 0) { - - /* get packed size based on block size and block count. */ - packed_size = sizeof(uint32_t) * (((mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].unpacked_size + mpq_archive->block_size - 1) / mpq_archive->block_size) + 1); - } else { - - /* file is stored in single sector and we need only two entries for the packed block offset table. */ - packed_size = sizeof(uint32_t) * 2; - } - - /* check if data has one extra entry. */ - if ((mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].flags & LIBMPQ_FLAG_CRC) != 0) { - - /* add one uint32_t. */ - packed_size += sizeof(uint32_t); - } - - /* allocate memory for the file. */ - if ((mpq_archive->mpq_file[file_number] = calloc(1, sizeof(mpq_file_s))) == NULL) { - - /* memory allocation problem. */ - result = LIBMPQ_ERROR_MALLOC; - goto error; - } - - /* allocate memory for the packed block offset table. */ - if ((mpq_archive->mpq_file[file_number]->packed_offset = calloc(1, packed_size)) == NULL) { - - /* memory allocation problem. */ - result = LIBMPQ_ERROR_MALLOC; - goto error; - } - - /* initialize counter to one opening */ - mpq_archive->mpq_file[file_number]->open_count = 1; - - /* check if we need to load the packed block offset table, we will maintain this table for unpacked files too. */ - if ((mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].flags & LIBMPQ_FLAG_COMPRESSED) != 0 && - (mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].flags & LIBMPQ_FLAG_SINGLE) == 0) { - - /* seek to block position. */ - if (fseeko(mpq_archive->fp, mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].offset + (((long long)mpq_archive->mpq_block_ex[mpq_archive->mpq_map[file_number].block_table_indices].offset_high) << 32) + mpq_archive->archive_offset, SEEK_SET) < 0) { - - /* seek in file failed. */ - result = LIBMPQ_ERROR_SEEK; - goto error; - } - - /* read block positions from begin of file. */ - if ((rb = fread(mpq_archive->mpq_file[file_number]->packed_offset, 1, packed_size, mpq_archive->fp)) < 0) { - - /* something on read from archive failed. */ - result = LIBMPQ_ERROR_READ; - goto error; - } - - /* check if the archive is protected some way, sometimes the file appears not to be encrypted, but it is. - * a special case are files with an additional sector but LIBMPQ_FLAG_CRC not set. we don't want to handle - * them as encrypted. */ - if (mpq_archive->mpq_file[file_number]->packed_offset[0] != rb && - mpq_archive->mpq_file[file_number]->packed_offset[0] != rb + 4) { - - /* file is encrypted. */ - mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].flags |= LIBMPQ_FLAG_ENCRYPTED; - } - - /* check if packed offset block is encrypted, we have to decrypt it. */ - if (mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].flags & LIBMPQ_FLAG_ENCRYPTED) { - - /* check if we don't know the file seed, try to find it. */ - if (libmpq__decrypt_key((uint8_t *)mpq_archive->mpq_file[file_number]->packed_offset, packed_size, mpq_archive->block_size, &mpq_archive->mpq_file[file_number]->seed) < 0) { - - /* sorry without seed, we cannot extract file. */ - result = LIBMPQ_ERROR_DECRYPT; - goto error; - } - - /* decrypt block in input buffer. */ - if (libmpq__decrypt_block(mpq_archive->mpq_file[file_number]->packed_offset, packed_size, mpq_archive->mpq_file[file_number]->seed - 1) < 0 ) { - - /* something on decrypt failed. */ - result = LIBMPQ_ERROR_DECRYPT; - goto error; - } - - /* check if the block positions are correctly decrypted. */ - if (mpq_archive->mpq_file[file_number]->packed_offset[0] != packed_size) { - - /* sorry without seed, we cannot extract file. */ - result = LIBMPQ_ERROR_DECRYPT; - goto error; - } - } - } else { - - /* check if file is not stored in a single sector. */ - if ((mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].flags & LIBMPQ_FLAG_SINGLE) == 0) { - - /* loop through all blocks and create packed block offset table based on block size. */ - for (i = 0; i < ((mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].unpacked_size + mpq_archive->block_size - 1) / mpq_archive->block_size + 1); i++) { - - /* check if we process the last block. */ - if (i == ((mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].unpacked_size + mpq_archive->block_size - 1) / mpq_archive->block_size)) { - - /* store size of last block. */ - mpq_archive->mpq_file[file_number]->packed_offset[i] = mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].unpacked_size; - } else { - - /* store default block size. */ - mpq_archive->mpq_file[file_number]->packed_offset[i] = i * mpq_archive->block_size; - } - } - } else { - - /* store offsets. */ - mpq_archive->mpq_file[file_number]->packed_offset[0] = 0; - mpq_archive->mpq_file[file_number]->packed_offset[1] = mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].packed_size; - } - } - - /* if no error was found, return zero. */ - return LIBMPQ_SUCCESS; - -error: - - /* free packed block offset table and file pointer. */ - free(mpq_archive->mpq_file[file_number]->packed_offset); - free(mpq_archive->mpq_file[file_number]); - - /* return error constant. */ - return result; -} - -/* this function free the file pointer to the opened file in archive. */ -int32_t libmpq__block_close_offset(mpq_archive_s *mpq_archive, uint32_t file_number) { - - /* check if given file number is not out of range. */ - CHECK_FILE_NUM(file_number, mpq_archive) - - if (mpq_archive->mpq_file[file_number] == NULL) { - - /* packed block offset table is not opened. */ - return LIBMPQ_ERROR_OPEN; - } - - mpq_archive->mpq_file[file_number]->open_count--; - - if (mpq_archive->mpq_file[file_number]->open_count != 0) { - - /* still in use */ - return LIBMPQ_SUCCESS; - } - - /* free packed block offset table and file pointer. */ - free(mpq_archive->mpq_file[file_number]->packed_offset); - free(mpq_archive->mpq_file[file_number]); - - /* mark it as unopened - libmpq__block_open_offset checks for this to decide whether to increment the counter */ - mpq_archive->mpq_file[file_number] = NULL; - - /* if no error was found, return zero. */ - return LIBMPQ_SUCCESS; -} - -/* this function return the unpacked size of the given file and block in the archive. */ -int32_t libmpq__block_unpacked_size(mpq_archive_s *mpq_archive, uint32_t file_number, uint32_t block_number, libmpq__off_t *unpacked_size) { - - /* check if given file number is not out of range. */ - CHECK_FILE_NUM(file_number, mpq_archive) - - /* check if given block number is not out of range. */ - CHECK_BLOCK_NUM(block_number, mpq_archive) - - /* check if packed block offset table is opened. */ - if (mpq_archive->mpq_file[file_number] == NULL || - mpq_archive->mpq_file[file_number]->packed_offset == NULL) { - - /* packed block offset table is not opened. */ - return LIBMPQ_ERROR_OPEN; - } - - /* check if block is stored as single sector. */ - if ((mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].flags & LIBMPQ_FLAG_SINGLE) != 0) { - - /* return the unpacked size of the block in the mpq archive. */ - *unpacked_size = mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].unpacked_size; - } - - /* check if block is not stored as single sector. */ - if ((mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].flags & LIBMPQ_FLAG_SINGLE) == 0) { - - /* check if we not process the last block. */ - if (block_number < ((mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].unpacked_size + mpq_archive->block_size - 1) / mpq_archive->block_size) - 1) { - - /* return the block size as unpacked size. */ - *unpacked_size = mpq_archive->block_size; - } else { - - /* return the unpacked size of the last block in the mpq archive. */ - *unpacked_size = mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].unpacked_size - mpq_archive->block_size * block_number; - } - } - - /* if no error was found, return zero. */ - return LIBMPQ_SUCCESS; -} - -/* this function return the decryption seed for the given file and block. */ -int32_t libmpq__block_seed(mpq_archive_s *mpq_archive, uint32_t file_number, uint32_t block_number, uint32_t *seed) { - - /* check if given file number is not out of range. */ - CHECK_FILE_NUM(file_number, mpq_archive) - - /* check if given block number is not out of range. */ - CHECK_BLOCK_NUM(block_number, mpq_archive) - - /* check if packed block offset table is opened. */ - if (mpq_archive->mpq_file[file_number] == NULL || - mpq_archive->mpq_file[file_number]->packed_offset == NULL) { - - /* packed block offset table is not opened. */ - return LIBMPQ_ERROR_OPEN; - } - - /* return the decryption key. */ - *seed = mpq_archive->mpq_file[file_number]->seed + block_number; - - /* if no error was found, return zero. */ - return LIBMPQ_SUCCESS; -} - -/* this function read the given block from archive into a buffer. */ -int32_t libmpq__block_read(mpq_archive_s *mpq_archive, uint32_t file_number, uint32_t block_number, uint8_t *out_buf, libmpq__off_t out_size, libmpq__off_t *transferred) { - - /* some common variables. */ - uint8_t *in_buf; - uint32_t seed = 0; - uint32_t encrypted = 0; - uint32_t compressed = 0; - uint32_t imploded = 0; - int32_t tb = 0; - libmpq__off_t block_offset = 0; - off_t in_size = 0; - libmpq__off_t unpacked_size = 0; - - /* check if given file number is not out of range. */ - CHECK_FILE_NUM(file_number, mpq_archive) - - /* check if given block number is not out of range. */ - CHECK_BLOCK_NUM(block_number, mpq_archive) - - /* check if packed block offset table is opened. */ - if (mpq_archive->mpq_file[file_number] == NULL || - mpq_archive->mpq_file[file_number]->packed_offset == NULL) { - - /* packed block offset table is not opened. */ - return LIBMPQ_ERROR_OPEN; - } - - /* get target size of block. */ - libmpq__block_unpacked_size(mpq_archive, file_number, block_number, &unpacked_size); - - /* check if target buffer is to small. */ - if (unpacked_size > out_size) { - - /* output buffer size is to small or block size is unknown. */ - return LIBMPQ_ERROR_SIZE; - } - - /* fetch some required values like input buffer size and block offset. */ - block_offset = mpq_archive->mpq_block[mpq_archive->mpq_map[file_number].block_table_indices].offset + (((long long)mpq_archive->mpq_block_ex[mpq_archive->mpq_map[file_number].block_table_indices].offset_high) << 32) + mpq_archive->mpq_file[file_number]->packed_offset[block_number]; - in_size = mpq_archive->mpq_file[file_number]->packed_offset[block_number + 1] - mpq_archive->mpq_file[file_number]->packed_offset[block_number]; - - /* seek in file. */ - if (fseeko(mpq_archive->fp, block_offset + mpq_archive->archive_offset, SEEK_SET) < 0) { - - /* something with seek in file failed. */ - return LIBMPQ_ERROR_SEEK; - } - - /* allocate memory for the read buffer. */ - if ((in_buf = calloc(1, in_size)) == NULL) { - - /* memory allocation problem. */ - return LIBMPQ_ERROR_MALLOC; - } - - /* read block from file. */ - if (fread(in_buf, 1, in_size, mpq_archive->fp) < 0) { - - /* free buffers. */ - free(in_buf); - - /* something on reading block failed. */ - return LIBMPQ_ERROR_READ; - } - - /* get encryption status. */ - libmpq__file_encrypted(mpq_archive, file_number, &encrypted); - - /* check if file is encrypted. */ - if (encrypted == 1) { - - /* get decryption key. */ - libmpq__block_seed(mpq_archive, file_number, block_number, &seed); - - /* decrypt block. */ - if (libmpq__decrypt_block((uint32_t *)in_buf, in_size, seed) < 0) { - - /* free buffers. */ - free(in_buf); - - /* something on decrypting block failed. */ - return LIBMPQ_ERROR_DECRYPT; - } - } - - /* get compression status. */ - libmpq__file_compressed(mpq_archive, file_number, &compressed); - - /* check if file is compressed. */ - if (compressed == 1) { - - /* decompress block. */ - if ((tb = libmpq__decompress_block(in_buf, in_size, out_buf, out_size, LIBMPQ_FLAG_COMPRESS_MULTI)) < 0) { - - /* free temporary buffer. */ - free(in_buf); - - /* something on decompressing block failed. */ - return LIBMPQ_ERROR_UNPACK; - } - } - - /* get implosion status. */ - libmpq__file_imploded(mpq_archive, file_number, &imploded); - - /* check if file is imploded. */ - if (imploded == 1) { - - /* explode block. */ - if ((tb = libmpq__decompress_block(in_buf, in_size, out_buf, out_size, LIBMPQ_FLAG_COMPRESS_PKZIP)) < 0) { - - /* free temporary buffer. */ - free(in_buf); - - /* something on decompressing block failed. */ - return LIBMPQ_ERROR_UNPACK; - } - } - - /* check if file is neither compressed nor imploded. */ - if (compressed == 0 && imploded == 0) { - - /* copy block. */ - if ((tb = libmpq__decompress_block(in_buf, in_size, out_buf, out_size, LIBMPQ_FLAG_COMPRESS_NONE)) < 0) { - - /* free temporary buffer. */ - free(in_buf); - - /* something on decompressing block failed. */ - return LIBMPQ_ERROR_UNPACK; - } - } - - /* free read buffer. */ - free(in_buf); - - /* check for null pointer. */ - if (transferred != NULL) { - - /* store transferred bytes. */ - *transferred = tb; - } - - /* if no error was found, return zero. */ - return LIBMPQ_SUCCESS; -} diff --git a/externals/libmpq/libmpq/mpq.h b/externals/libmpq/libmpq/mpq.h deleted file mode 100644 index abd4862c334..00000000000 --- a/externals/libmpq/libmpq/mpq.h +++ /dev/null @@ -1,101 +0,0 @@ -/* - * mpq.h -- some default types and defines. - * - * Copyright (c) 2003-2008 Maik Broemme - * - * Some parts (the encryption and decryption stuff) were adapted from - * the C++ version of StormLib.h and StormPort.h included in stormlib. - * The C++ version belongs to the following authors: - * - * Ladislav Zezula - * Marko Friedemann - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ - -#ifndef _MPQ_H -#define _MPQ_H - -#ifdef __cplusplus -extern "C" { -#endif - -/* generic includes. */ -#include -#include - -#if defined(__GNUC__) && (__GNUC__ >= 4) -# define LIBMPQ_API __attribute__((visibility("default"))) -#else -# define LIBMPQ_API -#endif - -/* define errors. */ -#define LIBMPQ_ERROR_OPEN -1 /* open error on file. */ -#define LIBMPQ_ERROR_CLOSE -2 /* close error on file. */ -#define LIBMPQ_ERROR_SEEK -3 /* lseek error on file. */ -#define LIBMPQ_ERROR_READ -4 /* read error on file. */ -#define LIBMPQ_ERROR_WRITE -5 /* write error on file. */ -#define LIBMPQ_ERROR_MALLOC -6 /* memory allocation error. */ -#define LIBMPQ_ERROR_FORMAT -7 /* format errror. */ -#define LIBMPQ_ERROR_NOT_INITIALIZED -8 /* libmpq__init() wasn't called. */ -#define LIBMPQ_ERROR_SIZE -9 /* buffer size is to small. */ -#define LIBMPQ_ERROR_EXIST -10 /* file or block does not exist in archive. */ -#define LIBMPQ_ERROR_DECRYPT -11 /* we don't know the decryption seed. */ -#define LIBMPQ_ERROR_UNPACK -12 /* error on unpacking file. */ - -/* internal data structure. */ -typedef struct mpq_archive mpq_archive_s; - -/* file offset data type for API*/ -typedef int64_t libmpq__off_t; - -/* generic information about library. */ -extern LIBMPQ_API const char *libmpq__version(void); - -/* string error message for a libmpq return code. */ -extern LIBMPQ_API const char *libmpq__strerror(int32_t returncode); - -/* generic mpq archive information. */ -extern LIBMPQ_API int32_t libmpq__archive_open(mpq_archive_s **mpq_archive, const char *mpq_filename, libmpq__off_t archive_offset); -extern LIBMPQ_API int32_t libmpq__archive_close(mpq_archive_s *mpq_archive); -extern LIBMPQ_API int32_t libmpq__archive_packed_size(mpq_archive_s *mpq_archive, libmpq__off_t *packed_size); -extern LIBMPQ_API int32_t libmpq__archive_unpacked_size(mpq_archive_s *mpq_archive, libmpq__off_t *unpacked_size); -extern LIBMPQ_API int32_t libmpq__archive_offset(mpq_archive_s *mpq_archive, libmpq__off_t *offset); -extern LIBMPQ_API int32_t libmpq__archive_version(mpq_archive_s *mpq_archive, uint32_t *version); -extern LIBMPQ_API int32_t libmpq__archive_files(mpq_archive_s *mpq_archive, uint32_t *files); - -/* generic file processing functions. */ -extern LIBMPQ_API int32_t libmpq__file_packed_size(mpq_archive_s *mpq_archive, uint32_t file_number, libmpq__off_t *packed_size); -extern LIBMPQ_API int32_t libmpq__file_unpacked_size(mpq_archive_s *mpq_archive, uint32_t file_number, libmpq__off_t *unpacked_size); -extern LIBMPQ_API int32_t libmpq__file_offset(mpq_archive_s *mpq_archive, uint32_t file_number, libmpq__off_t *offset); -extern LIBMPQ_API int32_t libmpq__file_blocks(mpq_archive_s *mpq_archive, uint32_t file_number, uint32_t *blocks); -extern LIBMPQ_API int32_t libmpq__file_encrypted(mpq_archive_s *mpq_archive, uint32_t file_number, uint32_t *encrypted); -extern LIBMPQ_API int32_t libmpq__file_compressed(mpq_archive_s *mpq_archive, uint32_t file_number, uint32_t *compressed); -extern LIBMPQ_API int32_t libmpq__file_imploded(mpq_archive_s *mpq_archive, uint32_t file_number, uint32_t *imploded); -extern LIBMPQ_API int32_t libmpq__file_number(mpq_archive_s *mpq_archive, const char *filename, uint32_t *number); -extern LIBMPQ_API int32_t libmpq__file_read(mpq_archive_s *mpq_archive, uint32_t file_number, uint8_t *out_buf, libmpq__off_t out_size, libmpq__off_t *transferred); - -/* generic block processing functions. */ -extern LIBMPQ_API int32_t libmpq__block_open_offset(mpq_archive_s *mpq_archive, uint32_t file_number); -extern LIBMPQ_API int32_t libmpq__block_close_offset(mpq_archive_s *mpq_archive, uint32_t file_number); -extern LIBMPQ_API int32_t libmpq__block_unpacked_size(mpq_archive_s *mpq_archive, uint32_t file_number, uint32_t block_number, libmpq__off_t *unpacked_size); -extern LIBMPQ_API int32_t libmpq__block_read(mpq_archive_s *mpq_archive, uint32_t file_number, uint32_t block_number, uint8_t *out_buf, libmpq__off_t out_size, libmpq__off_t *transferred); - -#ifdef __cplusplus -} -#endif - -#endif /* _MPQ_H */ diff --git a/externals/libmpq/libmpq/pack_begin.h b/externals/libmpq/libmpq/pack_begin.h deleted file mode 100644 index eb4a6ddebbb..00000000000 --- a/externals/libmpq/libmpq/pack_begin.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * pack_begin.h -- header file for struct packing used by libmpq. - * - * Copyright (c) 2010 Georg Lukas - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ - -#ifndef _PACK_BEGIN -#define _PACK_BEGIN -#else -#error "pack_begin.h may not be included twice!" -#endif - -#ifdef _MSC_VER - #pragma pack(push,1) - #define PACK_STRUCT -#else - /* we assume GNU here */ - #define PACK_STRUCT __attribute__((packed)) -#endif - diff --git a/externals/libmpq/libmpq/pack_end.h b/externals/libmpq/libmpq/pack_end.h deleted file mode 100644 index a8a35113bfb..00000000000 --- a/externals/libmpq/libmpq/pack_end.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * pack_end.h -- header file for struct packing used by libmpq. - * - * Copyright (c) 2010 Georg Lukas - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ - -#ifdef _PACK_BEGIN -#undef _PACK_BEGIN -#else -#error "pack_begin.h must be includede before pack_end.h" -#endif - -#ifdef _MSC_VER - #pragma pack(pop) -#endif - -#undef PACK_STRUCT diff --git a/externals/libmpq/libmpq/platform.h b/externals/libmpq/libmpq/platform.h deleted file mode 100644 index 68fdfdc5ded..00000000000 --- a/externals/libmpq/libmpq/platform.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * platform.h -- header file for platform specific parts. - * - * Copyright (c) 2010 Georg Lukas - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ - -#ifndef _PLATFORM_H -#define _PLATFORM_H - -#ifdef _MSC_VER - #define fseeko _fseeki64 -#endif - -#endif /* _PLATFORM_H */ diff --git a/externals/libmpq/libmpq/wave.c b/externals/libmpq/libmpq/wave.c deleted file mode 100644 index 628593fce83..00000000000 --- a/externals/libmpq/libmpq/wave.c +++ /dev/null @@ -1,250 +0,0 @@ -/* - * wave.c -- this file contains decompression methods used by mpq-tools - * to decompress wave files. - * - * Copyright (c) 2003-2007 Maik Broemme - * - * This source was adepted from the C++ version of wave.cpp included - * in stormlib. The C++ version belongs to the following authors: - * - * Ladislav Zezula - * Tom Amigo - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ - -/* generic includes. */ -#include - -/* libmpq generic includes. */ -#include "wave.h" - -/* table necessary dor decompression. */ -static const uint32_t wave_table_1503f120[] = { - 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF, 0x00000004, 0xFFFFFFFF, 0x00000002, 0xFFFFFFFF, 0x00000006, - 0xFFFFFFFF, 0x00000001, 0xFFFFFFFF, 0x00000005, 0xFFFFFFFF, 0x00000003, 0xFFFFFFFF, 0x00000007, - 0xFFFFFFFF, 0x00000001, 0xFFFFFFFF, 0x00000005, 0xFFFFFFFF, 0x00000003, 0xFFFFFFFF, 0x00000007, - 0xFFFFFFFF, 0x00000002, 0xFFFFFFFF, 0x00000004, 0xFFFFFFFF, 0x00000006, 0xFFFFFFFF, 0x00000008 -}; - -/* table necessary dor decompression. */ -static const uint32_t wave_table_1503f1a0[] = { - 0x00000007, 0x00000008, 0x00000009, 0x0000000A, 0x0000000B, 0x0000000C, 0x0000000D, 0x0000000E, - 0x00000010, 0x00000011, 0x00000013, 0x00000015, 0x00000017, 0x00000019, 0x0000001C, 0x0000001F, - 0x00000022, 0x00000025, 0x00000029, 0x0000002D, 0x00000032, 0x00000037, 0x0000003C, 0x00000042, - 0x00000049, 0x00000050, 0x00000058, 0x00000061, 0x0000006B, 0x00000076, 0x00000082, 0x0000008F, - 0x0000009D, 0x000000AD, 0x000000BE, 0x000000D1, 0x000000E6, 0x000000FD, 0x00000117, 0x00000133, - 0x00000151, 0x00000173, 0x00000198, 0x000001C1, 0x000001EE, 0x00000220, 0x00000256, 0x00000292, - 0x000002D4, 0x0000031C, 0x0000036C, 0x000003C3, 0x00000424, 0x0000048E, 0x00000502, 0x00000583, - 0x00000610, 0x000006AB, 0x00000756, 0x00000812, 0x000008E0, 0x000009C3, 0x00000ABD, 0x00000BD0, - 0x00000CFF, 0x00000E4C, 0x00000FBA, 0x0000114C, 0x00001307, 0x000014EE, 0x00001706, 0x00001954, - 0x00001BDC, 0x00001EA5, 0x000021B6, 0x00002515, 0x000028CA, 0x00002CDF, 0x0000315B, 0x0000364B, - 0x00003BB9, 0x000041B2, 0x00004844, 0x00004F7E, 0x00005771, 0x0000602F, 0x000069CE, 0x00007462, - 0x00007FFF -}; - -/* this function decompress a wave file, mono or stereo, 1500F230 offset. */ -int32_t libmpq__do_decompress_wave(uint8_t *out_buf, int32_t out_length, uint8_t *in_buf, int32_t in_length, int32_t channels) { - - /* some common variables. */ - byte_and_int16_t out; - byte_and_int16_t in; - uint32_t index; - int32_t nr_array1[2]; - int32_t nr_array2[2]; - int32_t count = 0; - - /* end on input buffer. */ - uint8_t *in_end = in_buf + in_length; - - /* assign default values. */ - out.pb = out_buf; - in.pb = in_buf; - nr_array1[0] = 0x2C; - nr_array1[1] = 0x2C; - - /* increase. */ - in.pw++; - - /* 15007AD7 */ - for (count = 0; count < channels; count++) { - - /* some common variables. */ - int32_t temp; - - /* save pointer. */ - temp = *(int16_t *)in.pw++; - nr_array2[count] = temp; - - /* check if should break. */ - if (out_length < 2) { - return out.pb - out_buf; - } - - /* return values. */ - *out.pw++ = (uint16_t)temp; - out_length -= 2; - } - - /* decrease channels. */ - index = channels - 1; - - /* loop through input buffer until end reached. */ - while (in.pb < in_end) { - - /* save the byte. */ - uint8_t one_byte = *in.pb++; - - /* check how many channels and set index. */ - if (channels == 2) { - index = (index == 0) ? 1 : 0; - } - - /* 15007B25 - get one byte from input buffer. */ - if (one_byte & 0x80) { - - /* 15007B32 */ - switch (one_byte & 0x7F) { - case 0: - - /* 15007B8E */ - if (nr_array1[index] != 0) { - nr_array1[index]--; - } - - /* check if should break. */ - if (out_length < 2) { - break; - } - - /* return values. */ - *out.pw++ = (uint16_t)nr_array2[index]; - out_length -= 2; - - /* continue loop. */ - continue; - case 1: - /* 15007B72 and EBX. */ - nr_array1[index] += 8; - - /* check index. */ - if (nr_array1[index] > 0x58) { - nr_array1[index] = 0x58; - } - - /* check how many channels and set index. */ - if (channels == 2) { - index = (index == 0) ? 1 : 0; - } - - /* continue loop. */ - continue; - case 2: - - /* nothing todo, so continue. */ - continue; - default: - - /* decrease index. */ - nr_array1[index] -= 8; - - /* check index. */ - if (nr_array1[index] < 0) { - nr_array1[index] = 0; - } - - /* check if two channels left. */ - if (channels != 2) { - continue; - } - index = (index == 0) ? 1 : 0; - - /* continue loop. */ - continue; - } - } else { - - /* EDI */ - uint32_t temp1 = wave_table_1503f1a0[nr_array1[index]]; - - /* ESI */ - uint32_t temp2 = temp1 >> in_buf[1]; - - /* ECX */ - int32_t temp3 = nr_array2[index]; - - /* EBX = one byte. */ - if (one_byte & 0x01) { - temp2 += (temp1 >> 0); - } - if (one_byte & 0x02) { - temp2 += (temp1 >> 1); - } - if (one_byte & 0x04) { - temp2 += (temp1 >> 2); - } - if (one_byte & 0x08) { - temp2 += (temp1 >> 3); - } - if (one_byte & 0x10) { - temp2 += (temp1 >> 4); - } - if (one_byte & 0x20) { - temp2 += (temp1 >> 5); - } - if (one_byte & 0x40) { - temp3 -= temp2; - if (temp3 <= (int32_t)0xFFFF8000) { - temp3 = (int32_t)0xFFFF8000; - } - } else { - temp3 += temp2; - if (temp3 >= 0x7FFF) { - temp3 = 0x7FFF; - } - } - - /* restore index. */ - nr_array2[index] = temp3; - - /* check if should break. */ - if (out_length < 2) { - break; - } - - /* assign values. */ - temp2 = nr_array1[index]; - one_byte &= 0x1F; - *out.pw++ = (uint16_t)temp3; - out_length -= 2; - temp2 += wave_table_1503f120[one_byte]; - nr_array1[index] = temp2; - - /* check index. */ - if (nr_array1[index] < 0) { - nr_array1[index] = 0; - } else { - - /* check index. */ - if (nr_array1[index] > 0x58) { - nr_array1[index] = 0x58; - } - } - } - } - - /* return copied bytes. */ - return (out.pb - out_buf); -} diff --git a/externals/libmpq/libmpq/wave.h b/externals/libmpq/libmpq/wave.h deleted file mode 100644 index 1b9491bd70a..00000000000 --- a/externals/libmpq/libmpq/wave.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * wave.h -- header file for wav unplode functions used by mpq-tools. - * - * Copyright (c) 2003-2007 Maik Broemme - * - * This source was adepted from the C++ version of wave.h included - * in stormlib. The C++ version belongs to the following authors: - * - * Ladislav Zezula - * Tom Amigo - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ - -#ifndef _WAVE_H -#define _WAVE_H - -/* buffer. */ -typedef union { - uint16_t *pw; - uint8_t *pb; -} byte_and_int16_t; - -/* decompress a wave file, mono or stereo, 1500F230 offset. */ -int32_t libmpq__do_decompress_wave( - uint8_t *out_buf, - int32_t out_length, - uint8_t *in_buf, - int32_t in_length, - int32_t channels -); - -#endif /* _WAVE_H */ diff --git a/externals/libmpq/tools/Makefile.am b/externals/libmpq/tools/Makefile.am deleted file mode 100644 index 607205379a4..00000000000 --- a/externals/libmpq/tools/Makefile.am +++ /dev/null @@ -1,8 +0,0 @@ -# minimum required automake 1.6 -AUTOMAKE_OPTIONS = 1.6 - -# the main programs. -bin_PROGRAMS = crypt_buf_gen - -# sources for crypt_buf_gen program. -crypt_buf_gen_SOURCES = crypt_buf_gen.c diff --git a/externals/libmpq/tools/crypt_buf_gen.c b/externals/libmpq/tools/crypt_buf_gen.c deleted file mode 100644 index 3d150fc661f..00000000000 --- a/externals/libmpq/tools/crypt_buf_gen.c +++ /dev/null @@ -1,85 +0,0 @@ -/* - * crypt_buf_gen.c -- tool to re-create the static decryption buffer. - * - * Copyright (c) 2003-2008 Maik Broemme - * Copyright (c) 2008 Georg Lukas - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * - * - * Usage: - * $ make crypt_buf_gen - * $ ./crypt_buf_gen > crypt_buf.h - * - */ -#include -#include -#include - -static uint32_t *buffer; - -int32_t libmpq__buffer_init() { - buffer = malloc(sizeof(uint32_t) * 0x500); - - if (!buffer) - return -1; - - /* some common variables. */ - uint32_t seed = 0x00100001; - uint32_t index1 = 0; - uint32_t index2 = 0; - uint32_t i; - - /* initialize the decryption buffer. */ - for (index1 = 0; index1 < 0x100; index1++) { - for(index2 = index1, i = 0; i < 5; i++, index2 += 0x100) { - - /* some common variables. */ - uint32_t temp1, temp2; - - /* temporary copy. */ - seed = (seed * 125 + 3) % 0x2AAAAB; - temp1 = (seed & 0xFFFF) << 0x10; - - /* temporary copy. */ - seed = (seed * 125 + 3) % 0x2AAAAB; - temp2 = (seed & 0xFFFF); - - /* assign buffer. */ - buffer[index2] = (temp1 | temp2); - } - } - - /* if no error was found, return zero. */ - return 0; -} - -int main() { - if (libmpq__buffer_init() != 0) - perror("libmpq__buffer_init()"); - int x; - printf("/* DO NOT CHANGE! this file is auto-generated by crypt_buf_gen.c */\n"); - printf("static const uint32_t crypt_buf[0x500] = {\n\t"); - for (x = 0; x < 0x500; x++) { - printf("0x%08x", buffer[x]); - if (x < 0x500 - 1) { - if (x % 6 == 5) - printf(",\n\t"); - else - printf(", "); - } - } - printf("\n};\n"); -} diff --git a/externals/libmpq/win/config.h b/externals/libmpq/win/config.h deleted file mode 100644 index 6833494624d..00000000000 --- a/externals/libmpq/win/config.h +++ /dev/null @@ -1,81 +0,0 @@ -/* config.h. Generated from config.h.in by configure. */ -/* config.h.in. Generated from configure.ac by autoheader. */ - -/* Define to 1 if you have the header file. */ -#define HAVE_DLFCN_H 1 - -/* Define to 1 if fseeko (and presumably ftello) exists and is declared. */ -#define HAVE_FSEEKO 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_INTTYPES_H 1 - -/* Define to 1 if you have the `bz2' library (-lbz2). */ -#define HAVE_LIBBZ2 1 - -/* Define to 1 if you have the `z' library (-lz). */ -#define HAVE_LIBZ 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_MEMORY_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_STDINT_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_STDLIB_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_STRINGS_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_STRING_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_SYS_STAT_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_SYS_TYPES_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_UNISTD_H 0 - -/* Define to the sub-directory in which libtool stores uninstalled libraries. - */ -#define LT_OBJDIR ".libs/" - -/* Name of package */ -#define PACKAGE "libmpq" - -/* Define to the address where bug reports for this package should be sent. */ -#define PACKAGE_BUGREPORT "mbroemme@plusserver.de" - -/* Define to the full name of this package. */ -#define PACKAGE_NAME "libmpq" - -/* Define to the full name and version of this package. */ -#define PACKAGE_STRING "libmpq 0.4.2" - -/* Define to the one symbol short name of this package. */ -#define PACKAGE_TARNAME "libmpq" - -/* Define to the home page for this package. */ -#define PACKAGE_URL "" - -/* Define to the version of this package. */ -#define PACKAGE_VERSION "0.4.2" - -/* Define to 1 if you have the ANSI C header files. */ -#define STDC_HEADERS 1 - -/* Version number of package */ -#define VERSION "0.4.2" - -/* Number of bits in a file offset, on hosts where this is settable. */ -/* #undef _FILE_OFFSET_BITS */ - -/* Define to 1 to make fseeko visible on some hosts (e.g. glibc 2.2). */ -/* #undef _LARGEFILE_SOURCE */ - -/* Define for large files, on AIX-style hosts. */ -/* #undef _LARGE_FILES */ diff --git a/externals/libmpq/win/dirent.h b/externals/libmpq/win/dirent.h deleted file mode 100644 index 6425174092d..00000000000 --- a/externals/libmpq/win/dirent.h +++ /dev/null @@ -1,230 +0,0 @@ -/***************************************************************************** - * dirent.h - dirent API for Microsoft Visual Studio - * - * Copyright (C) 2006 Toni Ronkko - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * ``Software''), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL TONI RONKKO BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - * - * Dec 15, 2009, John Cunningham - * Added rewinddir member function - * - * Jan 18, 2008, Toni Ronkko - * Using FindFirstFileA and WIN32_FIND_DATAA to avoid converting string - * between multi-byte and unicode representations. This makes the - * code simpler and also allows the code to be compiled under MingW. Thanks - * to Azriel Fasten for the suggestion. - * - * Mar 4, 2007, Toni Ronkko - * Bug fix: due to the strncpy_s() function this file only compiled in - * Visual Studio 2005. Using the new string functions only when the - * compiler version allows. - * - * Nov 2, 2006, Toni Ronkko - * Major update: removed support for Watcom C, MS-DOS and Turbo C to - * simplify the file, updated the code to compile cleanly on Visual - * Studio 2005 with both unicode and multi-byte character strings, - * removed rewinddir() as it had a bug. - * - * Aug 20, 2006, Toni Ronkko - * Removed all remarks about MSVC 1.0, which is antiqued now. Simplified - * comments by removing SGML tags. - * - * May 14 2002, Toni Ronkko - * Embedded the function definitions directly to the header so that no - * source modules need to be included in the Visual Studio project. Removed - * all the dependencies to other projects so that this very header can be - * used independently. - * - * May 28 1998, Toni Ronkko - * First version. - *****************************************************************************/ -#ifndef DIRENT_H -#define DIRENT_H - -#include -#include -#include - - -typedef struct dirent -{ - char d_name[MAX_PATH + 1]; /* current dir entry (multi-byte char string) */ - WIN32_FIND_DATAA data; /* file attributes */ -} dirent; - - -typedef struct DIR -{ - dirent current; /* Current directory entry */ - int cached; /* Indicates un-processed entry in memory */ - HANDLE search_handle; /* File search handle */ - char patt[MAX_PATH + 3]; /* search pattern (3 = pattern + "\\*\0") */ -} DIR; - - -/* Forward declarations */ -static DIR *opendir (const char *dirname); -static struct dirent *readdir (DIR *dirp); -static int closedir (DIR *dirp); -static void rewinddir(DIR* dirp); - - -/* Use the new safe string functions introduced in Visual Studio 2005 */ -#if defined(_MSC_VER) && _MSC_VER >= 1400 -# define STRNCPY(dest,src,size) strncpy_s((dest),(size),(src),_TRUNCATE) -#else -# define STRNCPY(dest,src,size) strncpy((dest),(src),(size)) -#endif - - -/***************************************************************************** - * Open directory stream DIRNAME for read and return a pointer to the - * internal working area that is used to retrieve individual directory - * entries. - */ -static DIR *opendir(const char *dirname) -{ - DIR *dirp; - assert (dirname != NULL); - assert (strlen (dirname) < MAX_PATH); - - /* construct new DIR structure */ - dirp = (DIR*) malloc (sizeof (struct DIR)); - if (dirp != NULL) { - char *p; - - /* take directory name... */ - STRNCPY (dirp->patt, dirname, sizeof(dirp->patt)); - dirp->patt[MAX_PATH] = '\0'; - - /* ... and append search pattern to it */ - p = strchr (dirp->patt, '\0'); - if (dirp->patt < p && *(p-1) != '\\' && *(p-1) != ':') { - *p++ = '\\'; - } - *p++ = '*'; - *p = '\0'; - - /* open stream and retrieve first file */ - dirp->search_handle = FindFirstFileA (dirp->patt, &dirp->current.data); - if (dirp->search_handle == INVALID_HANDLE_VALUE) { - /* invalid search pattern? */ - free (dirp); - return NULL; - } - - /* there is an un-processed directory entry in memory now */ - dirp->cached = 1; - } - - return dirp; -} - - -/***************************************************************************** - * Read a directory entry, and return a pointer to a dirent structure - * containing the name of the entry in d_name field. Individual directory - * entries returned by this very function include regular files, - * sub-directories, pseudo-directories "." and "..", but also volume labels, - * hidden files and system files may be returned. - */ -static struct dirent *readdir(DIR *dirp) -{ - assert (dirp != NULL); - - if (dirp->search_handle == INVALID_HANDLE_VALUE) { - /* directory stream was opened/rewound incorrectly or ended normally */ - return NULL; - } - - /* get next directory entry */ - if (dirp->cached != 0) { - /* a valid directory entry already in memory */ - dirp->cached = 0; - } else { - /* read next directory entry from disk */ - if (FindNextFileA (dirp->search_handle, &dirp->current.data) == FALSE) { - /* the very last file has been processed or an error occured */ - FindClose (dirp->search_handle); - dirp->search_handle = INVALID_HANDLE_VALUE; - return NULL; - } - } - - /* copy as a multibyte character string */ - STRNCPY ( dirp->current.d_name, - dirp->current.data.cFileName, - sizeof(dirp->current.d_name) ); - dirp->current.d_name[MAX_PATH] = '\0'; - - return &dirp->current; -} - - -/***************************************************************************** - * Close directory stream opened by opendir() function. Close of the - * directory stream invalidates the DIR structure as well as any previously - * read directory entry. - */ -static int closedir(DIR *dirp) -{ - assert (dirp != NULL); - - /* release search handle */ - if (dirp->search_handle != INVALID_HANDLE_VALUE) { - FindClose (dirp->search_handle); - dirp->search_handle = INVALID_HANDLE_VALUE; - } - - /* release directory handle */ - free (dirp); - return 0; -} - - -/***************************************************************************** - * Resets the position of the directory stream to which dirp refers to the - * beginning of the directory. It also causes the directory stream to refer - * to the current state of the corresponding directory, as a call to opendir() - * would have done. If dirp does not refer to a directory stream, the effect - * is undefined. - */ -static void rewinddir(DIR* dirp) -{ - /* release search handle */ - if (dirp->search_handle != INVALID_HANDLE_VALUE) { - FindClose (dirp->search_handle); - dirp->search_handle = INVALID_HANDLE_VALUE; - } - - /* open new search handle and retrieve first file */ - dirp->search_handle = FindFirstFileA (dirp->patt, &dirp->current.data); - if (dirp->search_handle == INVALID_HANDLE_VALUE) { - /* invalid search pattern? */ - free (dirp); - return; - } - - /* there is an un-processed directory entry in memory now */ - dirp->cached = 1; -} - - -#endif /*DIRENT_H*/ diff --git a/externals/libmpq/win/stdint.h b/externals/libmpq/win/stdint.h deleted file mode 100644 index d02608a5972..00000000000 --- a/externals/libmpq/win/stdint.h +++ /dev/null @@ -1,247 +0,0 @@ -// ISO C9x compliant stdint.h for Microsoft Visual Studio -// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 -// -// Copyright (c) 2006-2008 Alexander Chemeris -// -// 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. The name of the author may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 _MSC_VER // [ -#error "Use this header only with Microsoft Visual C++ compilers!" -#endif // _MSC_VER ] - -#ifndef _MSC_STDINT_H_ // [ -#define _MSC_STDINT_H_ - -#if _MSC_VER > 1000 -#pragma once -#endif - -#include - -// For Visual Studio 6 in C++ mode and for many Visual Studio versions when -// compiling for ARM we should wrap include with 'extern "C++" {}' -// or compiler give many errors like this: -// error C2733: second C linkage of overloaded function 'wmemchr' not allowed -#ifdef __cplusplus -extern "C" { -#endif -# include -#ifdef __cplusplus -} -#endif - -// Define _W64 macros to mark types changing their size, like intptr_t. -#ifndef _W64 -# if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300 -# define _W64 __w64 -# else -# define _W64 -# endif -#endif - - -// 7.18.1 Integer types - -// 7.18.1.1 Exact-width integer types - -// Visual Studio 6 and Embedded Visual C++ 4 doesn't -// realize that, e.g. char has the same size as __int8 -// so we give up on __intX for them. -#if (_MSC_VER < 1300) - typedef signed char int8_t; - typedef signed short int16_t; - typedef signed int int32_t; - typedef unsigned char uint8_t; - typedef unsigned short uint16_t; - typedef unsigned int uint32_t; -#else - typedef signed __int8 int8_t; - typedef signed __int16 int16_t; - typedef signed __int32 int32_t; - typedef unsigned __int8 uint8_t; - typedef unsigned __int16 uint16_t; - typedef unsigned __int32 uint32_t; -#endif -typedef signed __int64 int64_t; -typedef unsigned __int64 uint64_t; - - -// 7.18.1.2 Minimum-width integer types -typedef int8_t int_least8_t; -typedef int16_t int_least16_t; -typedef int32_t int_least32_t; -typedef int64_t int_least64_t; -typedef uint8_t uint_least8_t; -typedef uint16_t uint_least16_t; -typedef uint32_t uint_least32_t; -typedef uint64_t uint_least64_t; - -// 7.18.1.3 Fastest minimum-width integer types -typedef int8_t int_fast8_t; -typedef int16_t int_fast16_t; -typedef int32_t int_fast32_t; -typedef int64_t int_fast64_t; -typedef uint8_t uint_fast8_t; -typedef uint16_t uint_fast16_t; -typedef uint32_t uint_fast32_t; -typedef uint64_t uint_fast64_t; - -// 7.18.1.4 Integer types capable of holding object pointers -#ifdef _WIN64 // [ - typedef signed __int64 intptr_t; - typedef unsigned __int64 uintptr_t; -#else // _WIN64 ][ - typedef _W64 signed int intptr_t; - typedef _W64 unsigned int uintptr_t; -#endif // _WIN64 ] - -// 7.18.1.5 Greatest-width integer types -typedef int64_t intmax_t; -typedef uint64_t uintmax_t; - - -// 7.18.2 Limits of specified-width integer types - -#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259 - -// 7.18.2.1 Limits of exact-width integer types -#define INT8_MIN ((int8_t)_I8_MIN) -#define INT8_MAX _I8_MAX -#define INT16_MIN ((int16_t)_I16_MIN) -#define INT16_MAX _I16_MAX -#define INT32_MIN ((int32_t)_I32_MIN) -#define INT32_MAX _I32_MAX -#define INT64_MIN ((int64_t)_I64_MIN) -#define INT64_MAX _I64_MAX -#define UINT8_MAX _UI8_MAX -#define UINT16_MAX _UI16_MAX -#define UINT32_MAX _UI32_MAX -#define UINT64_MAX _UI64_MAX - -// 7.18.2.2 Limits of minimum-width integer types -#define INT_LEAST8_MIN INT8_MIN -#define INT_LEAST8_MAX INT8_MAX -#define INT_LEAST16_MIN INT16_MIN -#define INT_LEAST16_MAX INT16_MAX -#define INT_LEAST32_MIN INT32_MIN -#define INT_LEAST32_MAX INT32_MAX -#define INT_LEAST64_MIN INT64_MIN -#define INT_LEAST64_MAX INT64_MAX -#define UINT_LEAST8_MAX UINT8_MAX -#define UINT_LEAST16_MAX UINT16_MAX -#define UINT_LEAST32_MAX UINT32_MAX -#define UINT_LEAST64_MAX UINT64_MAX - -// 7.18.2.3 Limits of fastest minimum-width integer types -#define INT_FAST8_MIN INT8_MIN -#define INT_FAST8_MAX INT8_MAX -#define INT_FAST16_MIN INT16_MIN -#define INT_FAST16_MAX INT16_MAX -#define INT_FAST32_MIN INT32_MIN -#define INT_FAST32_MAX INT32_MAX -#define INT_FAST64_MIN INT64_MIN -#define INT_FAST64_MAX INT64_MAX -#define UINT_FAST8_MAX UINT8_MAX -#define UINT_FAST16_MAX UINT16_MAX -#define UINT_FAST32_MAX UINT32_MAX -#define UINT_FAST64_MAX UINT64_MAX - -// 7.18.2.4 Limits of integer types capable of holding object pointers -#ifdef _WIN64 // [ -# define INTPTR_MIN INT64_MIN -# define INTPTR_MAX INT64_MAX -# define UINTPTR_MAX UINT64_MAX -#else // _WIN64 ][ -# define INTPTR_MIN INT32_MIN -# define INTPTR_MAX INT32_MAX -# define UINTPTR_MAX UINT32_MAX -#endif // _WIN64 ] - -// 7.18.2.5 Limits of greatest-width integer types -#define INTMAX_MIN INT64_MIN -#define INTMAX_MAX INT64_MAX -#define UINTMAX_MAX UINT64_MAX - -// 7.18.3 Limits of other integer types - -#ifdef _WIN64 // [ -# define PTRDIFF_MIN _I64_MIN -# define PTRDIFF_MAX _I64_MAX -#else // _WIN64 ][ -# define PTRDIFF_MIN _I32_MIN -# define PTRDIFF_MAX _I32_MAX -#endif // _WIN64 ] - -#define SIG_ATOMIC_MIN INT_MIN -#define SIG_ATOMIC_MAX INT_MAX - -#ifndef SIZE_MAX // [ -# ifdef _WIN64 // [ -# define SIZE_MAX _UI64_MAX -# else // _WIN64 ][ -# define SIZE_MAX _UI32_MAX -# endif // _WIN64 ] -#endif // SIZE_MAX ] - -// WCHAR_MIN and WCHAR_MAX are also defined in -#ifndef WCHAR_MIN // [ -# define WCHAR_MIN 0 -#endif // WCHAR_MIN ] -#ifndef WCHAR_MAX // [ -# define WCHAR_MAX _UI16_MAX -#endif // WCHAR_MAX ] - -#define WINT_MIN 0 -#define WINT_MAX _UI16_MAX - -#endif // __STDC_LIMIT_MACROS ] - - -// 7.18.4 Limits of other integer types - -#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 - -// 7.18.4.1 Macros for minimum-width integer constants - -#define INT8_C(val) val##i8 -#define INT16_C(val) val##i16 -#define INT32_C(val) val##i32 -#define INT64_C(val) val##i64 - -#define UINT8_C(val) val##ui8 -#define UINT16_C(val) val##ui16 -#define UINT32_C(val) val##ui32 -#define UINT64_C(val) val##ui64 - -// 7.18.4.2 Macros for greatest-width integer constants -#define INTMAX_C INT64_C -#define UINTMAX_C UINT64_C - -#endif // __STDC_CONSTANT_MACROS ] - - -#endif // _MSC_STDINT_H_ ] diff --git a/externals/mersennetwister/MersenneTwister.h b/externals/mersennetwister/MersenneTwister.h deleted file mode 100644 index 1cff879643f..00000000000 --- a/externals/mersennetwister/MersenneTwister.h +++ /dev/null @@ -1,405 +0,0 @@ -// MersenneTwister.h -// Mersenne Twister random number generator -- a C++ class MTRand -// Based on code by Makoto Matsumoto, Takuji Nishimura, and Shawn Cokus -// Richard J. Wagner v1.0 15 May 2003 rjwagner@writeme.com - -// The Mersenne Twister is an algorithm for generating random numbers. It -// was designed with consideration of the flaws in various other generators. -// The period, 2^19937-1, and the order of equidistribution, 623 dimensions, -// are far greater. The generator is also fast; it avoids multiplication and -// division, and it benefits from caches and pipelines. For more information -// see the inventors' web page at http://www.math.keio.ac.jp/~matumoto/emt.html - -// Reference -// M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-Dimensionally -// Equidistributed Uniform Pseudo-Random Number Generator", ACM Transactions on -// Modeling and Computer Simulation, Vol. 8, No. 1, January 1998, pp 3-30. - -// Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, -// Copyright (C) 2000 - 2003, Richard J. Wagner -// 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. The names of its contributors may not 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. - -// The original code included the following notice: -// -// When you use this, send an email to: matumoto@math.keio.ac.jp -// with an appropriate reference to your work. -// -// It would be nice to CC: rjwagner@writeme.com and Cokus@math.washington.edu -// when you write. - -#ifndef MERSENNETWISTER_H -#define MERSENNETWISTER_H - -// Not thread safe (unless auto-initialization is avoided and each thread has -// its own MTRand object) - -#include"Define.h" - -#include -#include -#include - -class MTRand { -// Data -public: - typedef ::uint32 uint32; - enum { N = 624 }; // length of state vector - enum { SAVE = N + 1 }; // length of array for save() - -protected: - enum { M = 397 }; // period parameter - - uint32 state[N]; // internal state - uint32 *pNext; // next value to get from state - int left; // number of values left before reload needed - -//Methods -public: - MTRand( const uint32& oneSeed ); // initialize with a simple uint32 - MTRand( uint32 *const bigSeed, uint32 const seedLength = N ); // or an array - MTRand(); // auto-initialize with /dev/urandom or time() and clock() - MTRand(const MTRand&); // prevent copy constructor - MTRand& operator=(const MTRand&); // no-op operator= - - // Do NOT use for CRYPTOGRAPHY without securely hashing several returned - // values together, otherwise the generator state can be learned after - // reading 624 consecutive values. - - // Access to 32-bit random numbers - double rand(); // real number in [0,1] - double rand( const double& n ); // real number in [0,n] - double randExc(); // real number in [0,1) - double randExc( const double& n ); // real number in [0,n) - double randDblExc(); // real number in (0,1) - double randDblExc( const double& n ); // real number in (0,n) - uint32 randInt(); // integer in [0,2^32-1] - uint32 randInt( const uint32& n ); // integer in [0,n] for n < 2^32 - double operator()() { return rand(); } // same as rand() - - // Access to 53-bit random numbers (capacity of IEEE double precision) - double rand53(); // real number in [0,1) - - // Access to nonuniform random number distributions - double randNorm( const double& mean = 0.0, const double& variance = 0.0 ); - - // Re-seeding functions with same behavior as initializers - void seed( const uint32 oneSeed ); - void seed( uint32 *const bigSeed, const uint32 seedLength = N ); - void seed(); - - // Saving and loading generator state - void save( uint32* saveArray ) const; // to array of size SAVE - void load( uint32 *const loadArray ); // from such array - /* Trinity not use streams for random values output - friend std::ostream& operator<<( std::ostream& os, const MTRand& mtrand ); - friend std::istream& operator>>( std::istream& is, MTRand& mtrand ); - */ -protected: - void initialize( const uint32 oneSeed ); - void reload(); - uint32 hiBit( const uint32& u ) const { return u & 0x80000000UL; } - uint32 loBit( const uint32& u ) const { return u & 0x00000001UL; } - uint32 loBits( const uint32& u ) const { return u & 0x7fffffffUL; } - uint32 mixBits( const uint32& u, const uint32& v ) const - { return hiBit(u) | loBits(v); } - uint32 twist( const uint32& m, const uint32& s0, const uint32& s1 ) const - { return m ^ (mixBits(s0,s1)>>1) ^ uint32(-(int32)(loBit(s1) & 0x9908b0dfUL)); } - static uint32 hash( time_t t, clock_t c ); -}; - -inline MTRand::MTRand(const MTRand&) - { seed(); } - -inline MTRand& MTRand::operator=(const MTRand&) - { return *this; } - -inline MTRand::MTRand( const uint32& oneSeed ) - { seed(oneSeed); } - -inline MTRand::MTRand( uint32 *const bigSeed, const uint32 seedLength ) - { seed(bigSeed,seedLength); } - -inline MTRand::MTRand() - { seed(); } - -inline double MTRand::rand() - { return double(randInt()) * (1.0/4294967295.0); } - -inline double MTRand::rand( const double& n ) - { return rand() * n; } - -inline double MTRand::randExc() - { return double(randInt()) * (1.0/4294967296.0); } - -inline double MTRand::randExc( const double& n ) - { return randExc() * n; } - -inline double MTRand::randDblExc() - { return ( double(randInt()) + 0.5 ) * (1.0/4294967296.0); } - -inline double MTRand::randDblExc( const double& n ) - { return randDblExc() * n; } - -inline double MTRand::rand53() -{ - uint32 a = randInt() >> 5, b = randInt() >> 6; - return ( a * 67108864.0 + b ) * (1.0/9007199254740992.0); // by Isaku Wada -} - -inline double MTRand::randNorm( const double& mean, const double& variance ) -{ - // Return a real number from a normal (Gaussian) distribution with given - // mean and variance by Box-Muller method - double r = sqrt( -2.0 * log( 1.0-randDblExc()) ) * variance; - double phi = 2.0 * 3.14159265358979323846264338328 * randExc(); - return mean + r * cos(phi); -} - -inline MTRand::uint32 MTRand::randInt() -{ - // Pull a 32-bit integer from the generator state - // Every other access function simply transforms the numbers extracted here - - if( left == 0 ) reload(); - --left; - - register uint32 s1; - s1 = *pNext++; - s1 ^= (s1 >> 11); - s1 ^= (s1 << 7) & 0x9d2c5680UL; - s1 ^= (s1 << 15) & 0xefc60000UL; - return ( s1 ^ (s1 >> 18) ); -} - -inline MTRand::uint32 MTRand::randInt( const uint32& n ) -{ - // Find which bits are used in n - // Optimized by Magnus Jonsson (magnus@smartelectronix.com) - uint32 used = n; - used |= used >> 1; - used |= used >> 2; - used |= used >> 4; - used |= used >> 8; - used |= used >> 16; - - // Draw numbers until one is found in [0,n] - uint32 i; - do - i = randInt() & used; // toss unused bits to shorten search - while( i > n ); - return i; -} - -inline void MTRand::seed( const uint32 oneSeed ) -{ - // Seed the generator with a simple uint32 - initialize(oneSeed); - reload(); -} - -inline void MTRand::seed( uint32 *const bigSeed, const uint32 seedLength ) -{ - // Seed the generator with an array of uint32's - // There are 2^19937-1 possible initial states. This function allows - // all of those to be accessed by providing at least 19937 bits (with a - // default seed length of N = 624 uint32's). Any bits above the lower 32 - // in each element are discarded. - // Just call seed() if you want to get array from /dev/urandom - initialize(19650218UL); - register int i = 1; - register uint32 j = 0; - register int k = ( N > int(seedLength) ? N : int(seedLength) ); - for (; k; --k ) - { - state[i] = - state[i] ^ ( (state[i-1] ^ (state[i-1] >> 30)) * 1664525UL ); - state[i] += ( bigSeed[j] & 0xffffffffUL ) + j; - state[i] &= 0xffffffffUL; - ++i; ++j; - if( i >= N ) { state[0] = state[N-1]; i = 1; } - if( j >= seedLength ) j = 0; - } - for (k = N - 1; k; --k ) - { - state[i] = - state[i] ^ ( (state[i-1] ^ (state[i-1] >> 30)) * 1566083941UL ); - state[i] -= i; - state[i] &= 0xffffffffUL; - ++i; - if( i >= N ) { state[0] = state[N-1]; i = 1; } - } - state[0] = 0x80000000UL; // MSB is 1, assuring non-zero initial array - reload(); -} - -inline void MTRand::seed() -{ - // Seed the generator with hash of time() and clock() values - seed( hash( time(NULL), clock() ) ); -} - -inline void MTRand::initialize( const uint32 seed ) -{ - // Initialize generator state with seed - // See Knuth TAOCP Vol 2, 3rd Ed, p.106 for multiplier. - // In previous versions, most significant bits (MSBs) of the seed affect - // only MSBs of the state array. Modified 9 Jan 2002 by Makoto Matsumoto. - register uint32 *s = state; - register uint32 *r = state; - register int i = 1; - *s++ = seed & 0xffffffffUL; - for (; i < N; ++i ) - { - *s++ = ( 1812433253UL * ( *r ^ (*r >> 30) ) + i ) & 0xffffffffUL; - r++; - } -} - -inline void MTRand::reload() -{ - // Generate N new values in state - // Made clearer and faster by Matthew Bellew (matthew.bellew@home.com) - register uint32 *p = state; - register int i; - for (i = N - M; i--; ++p ) - *p = twist( p[M], p[0], p[1] ); - for (i = M; --i; ++p ) - *p = twist( p[M-N], p[0], p[1] ); - *p = twist( p[M-N], p[0], state[0] ); - - left = N, pNext = state; -} - -inline MTRand::uint32 MTRand::hash( time_t t, clock_t c ) -{ - // Get a uint32 from t and c - // Better than uint32(x) in case x is floating point in [0,1] - // Based on code by Lawrence Kirby (fred@genesis.demon.co.uk) - - static uint32 differ = 0; // guarantee time-based seeds will change - - uint32 h1 = 0; - unsigned char *p = (unsigned char *) &t; - for (size_t i = 0; i < sizeof(t); ++i ) - { - h1 *= UCHAR_MAX + 2U; - h1 += p[i]; - } - uint32 h2 = 0; - p = (unsigned char *) &c; - for (size_t j = 0; j < sizeof(c); ++j ) - { - h2 *= UCHAR_MAX + 2U; - h2 += p[j]; - } - return ( h1 + differ++ ) ^ h2; -} - -inline void MTRand::save( uint32* saveArray ) const -{ - register uint32 *sa = saveArray; - register const uint32 *s = state; - register int i = N; - for (; i--; *sa++ = *s++ ) {} - *sa = left; -} - -inline void MTRand::load( uint32 *const loadArray ) -{ - register uint32 *s = state; - register uint32 *la = loadArray; - register int i = N; - for (; i--; *s++ = *la++ ) {} - left = *la; - pNext = &state[N-left]; -} - -/* Trinity not use streams for random values output -inline std::ostream& operator<<( std::ostream& os, const MTRand& mtrand ) -{ - register const MTRand::uint32 *s = mtrand.state; - register int i = mtrand.N; - for (; i--; os << *s++ << "\t" ) {} - return os << mtrand.left; -} - -inline std::istream& operator>>( std::istream& is, MTRand& mtrand ) -{ - register MTRand::uint32 *s = mtrand.state; - register int i = mtrand.N; - for (; i--; is >> *s++ ) {} - is >> mtrand.left; - mtrand.pNext = &mtrand.state[mtrand.N-mtrand.left]; - return is; -} -*/ - -#endif // MERSENNETWISTER_H - -// Change log: -// -// v0.1 - First release on 15 May 2000 -// - Based on code by Makoto Matsumoto, Takuji Nishimura, and Shawn Cokus -// - Translated from C to C++ -// - Made completely ANSI compliant -// - Designed convenient interface for initialization, seeding, and -// obtaining numbers in default or user-defined ranges -// - Added automatic seeding from /dev/urandom or time() and clock() -// - Provided functions for saving and loading generator state -// -// v0.2 - Fixed bug which reloaded generator one step too late -// -// v0.3 - Switched to clearer, faster reload() code from Matthew Bellew -// -// v0.4 - Removed trailing newline in saved generator format to be consistent -// with output format of built-in types -// -// v0.5 - Improved portability by replacing static const int's with enum's and -// clarifying return values in seed(); suggested by Eric Heimburg -// - Removed MAXINT constant; use 0xffffffffUL instead -// -// v0.6 - Eliminated seed overflow when uint32 is larger than 32 bits -// - Changed integer [0,n] generator to give better uniformity -// -// v0.7 - Fixed operator precedence ambiguity in reload() -// - Added access for real numbers in (0,1) and (0,n) -// -// v0.8 - Included time.h header to properly support time_t and clock_t -// -// v1.0 - Revised seeding to match 26 Jan 2002 update of Nishimura and Matsumoto -// - Allowed for seeding with arrays of any length -// - Added access for real numbers in [0,1) with 53-bit resolution -// - Added access for real numbers from normal (Gaussian) distributions -// - Increased overall speed by optimizing twist() -// - Doubled speed of integer [0,n] generation -// - Fixed out-of-range number generation on 64-bit machines -// - Improved portability by substituting literal constants for long enum's -// - Changed license from GNU LGPL to BSD - diff --git a/externals/sockets/Base64.cpp b/externals/sockets/Base64.cpp deleted file mode 100644 index f7f12f5edff..00000000000 --- a/externals/sockets/Base64.cpp +++ /dev/null @@ -1,262 +0,0 @@ -/** \file Base64.cpp - ** \date 2004-02-13 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#include "Base64.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -const char *Base64::bstr = - "ABCDEFGHIJKLMNOPQ" - "RSTUVWXYZabcdefgh" - "ijklmnopqrstuvwxy" - "z0123456789+/"; - -const char Base64::rstr[] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 63, - 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0, - 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0, - 0, 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, 0, 0, 0, 0, 0}; - -Base64::Base64() -{ -} - -void Base64::encode(FILE *fil, std::string& output, bool add_crlf) -{ - size_t remain; - size_t i = 0; - size_t o = 0; - char input[4]; - - output = ""; - remain = fread(input,1,3,fil); - while (remain > 0) - { - if (add_crlf && o && o % 76 == 0) - output += "\n"; - switch (remain) - { - case 1: - output += bstr[ ((input[i] >> 2) & 0x3f) ]; - output += bstr[ ((input[i] << 4) & 0x30) ]; - output += "=="; - break; - case 2: - output += bstr[ ((input[i] >> 2) & 0x3f) ]; - output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ]; - output += bstr[ ((input[i + 1] << 2) & 0x3c) ]; - output += "="; - break; - default: - output += bstr[ ((input[i] >> 2) & 0x3f) ]; - output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ]; - output += bstr[ ((input[i + 1] << 2) & 0x3c) + ((input[i + 2] >> 6) & 0x03) ]; - output += bstr[ (input[i + 2] & 0x3f) ]; - } - o += 4; - // - remain = fread(input,1,3,fil); - } -} - -void Base64::encode(const std::string& str_in, std::string& str_out, bool add_crlf) -{ - encode(str_in.c_str(), str_in.size(), str_out, add_crlf); -} - -void Base64::encode(const char* input,size_t l,std::string& output, bool add_crlf) -{ - size_t i = 0; - size_t o = 0; - - output = ""; - while (i < l) - { - size_t remain = l - i; - if (add_crlf && o && o % 76 == 0) - output += "\n"; - switch (remain) - { - case 1: - output += bstr[ ((input[i] >> 2) & 0x3f) ]; - output += bstr[ ((input[i] << 4) & 0x30) ]; - output += "=="; - break; - case 2: - output += bstr[ ((input[i] >> 2) & 0x3f) ]; - output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ]; - output += bstr[ ((input[i + 1] << 2) & 0x3c) ]; - output += "="; - break; - default: - output += bstr[ ((input[i] >> 2) & 0x3f) ]; - output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ]; - output += bstr[ ((input[i + 1] << 2) & 0x3c) + ((input[i + 2] >> 6) & 0x03) ]; - output += bstr[ (input[i + 2] & 0x3f) ]; - } - o += 4; - i += 3; - } -} - -void Base64::encode(const unsigned char* input,size_t l,std::string& output,bool add_crlf) -{ - size_t i = 0; - size_t o = 0; - - output = ""; - while (i < l) - { - size_t remain = l - i; - if (add_crlf && o && o % 76 == 0) - output += "\n"; - switch (remain) - { - case 1: - output += bstr[ ((input[i] >> 2) & 0x3f) ]; - output += bstr[ ((input[i] << 4) & 0x30) ]; - output += "=="; - break; - case 2: - output += bstr[ ((input[i] >> 2) & 0x3f) ]; - output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ]; - output += bstr[ ((input[i + 1] << 2) & 0x3c) ]; - output += "="; - break; - default: - output += bstr[ ((input[i] >> 2) & 0x3f) ]; - output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ]; - output += bstr[ ((input[i + 1] << 2) & 0x3c) + ((input[i + 2] >> 6) & 0x03) ]; - output += bstr[ (input[i + 2] & 0x3f) ]; - } - o += 4; - i += 3; - } -} - -void Base64::decode(const std::string& input,std::string& output) -{ - size_t i = 0; - size_t l = input.size(); - - output = ""; - while (i < l) - { - while (i < l && (input[i] == 13 || input[i] == 10)) - i++; - if (i < l) - { - char b1 = (char)((rstr[(int)input[i]] << 2 & 0xfc) + - (rstr[(int)input[i + 1]] >> 4 & 0x03)); - output += b1; - if (input[i + 2] != '=') - { - char b2 = (char)((rstr[(int)input[i + 1]] << 4 & 0xf0) + - (rstr[(int)input[i + 2]] >> 2 & 0x0f)); - output += b2; - } - if (input[i + 3] != '=') - { - char b3 = (char)((rstr[(int)input[i + 2]] << 6 & 0xc0) + - rstr[(int)input[i + 3]]); - output += b3; - } - i += 4; - } - } -} - -void Base64::decode(const std::string& input, unsigned char *output, size_t& sz) -{ - size_t i = 0; - size_t l = input.size(); - size_t j = 0; - - while (i < l) - { - while (i < l && (input[i] == 13 || input[i] == 10)) - i++; - if (i < l) - { - unsigned char b1 = (unsigned char)((rstr[(int)input[i]] << 2 & 0xfc) + - (rstr[(int)input[i + 1]] >> 4 & 0x03)); - if (output) - { - output[j] = b1; - } - j++; - if (input[i + 2] != '=') - { - unsigned char b2 = (unsigned char)((rstr[(int)input[i + 1]] << 4 & 0xf0) + - (rstr[(int)input[i + 2]] >> 2 & 0x0f)); - if (output) - { - output[j] = b2; - } - j++; - } - if (input[i + 3] != '=') - { - unsigned char b3 = (unsigned char)((rstr[(int)input[i + 2]] << 6 & 0xc0) + - rstr[(int)input[i + 3]]); - if (output) - { - output[j] = b3; - } - j++; - } - i += 4; - } - } - sz = j; -} - -size_t Base64::decode_length(const std::string& str64) -{ - if (str64.empty() || str64.size() % 4) - return 0; - size_t l = 3 * (str64.size() / 4 - 1) + 1; - if (str64[str64.size() - 2] != '=') - l++; - if (str64[str64.size() - 1] != '=') - l++; - return l; -} - -#ifdef SOCKETS_NAMESPACE -} -#endif - - diff --git a/externals/sockets/CMakeLists.txt b/externals/sockets/CMakeLists.txt deleted file mode 100644 index a1756773c08..00000000000 --- a/externals/sockets/CMakeLists.txt +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright (C) 2008-2010 Trinity -# -# This file is free software; as a special exception the author gives -# unlimited permission to copy and/or distribute it, with or without -# modifications, as long as this notice is preserved. -# -# This program is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the -# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -file(GLOB sources *.cpp) - -set(trinitysockets_STAT_SRCS - ${sources} -) - -include_directories( - ${CMAKE_CURRENT_SOURCE_DIR}/include -) - -add_library(trinitysockets STATIC ${trinitysockets_STAT_SRCS}) diff --git a/externals/sockets/Exception.cpp b/externals/sockets/Exception.cpp deleted file mode 100644 index 4d79aeef813..00000000000 --- a/externals/sockets/Exception.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/** - ** \file Exception.cpp - ** \date 2007-09-28 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2007 Anders Hedstrom - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifdef _MSC_VER -#pragma warning(disable:4786) -#endif -#include "Exception.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -Exception::Exception(const std::string& description) : m_description(description) -{ -} - -const std::string Exception::ToString() const -{ - return m_description; -} - -#ifdef SOCKETS_NAMESPACE -} // namespace SOCKETS_NAMESPACE { -#endif - - diff --git a/externals/sockets/Ipv4Address.cpp b/externals/sockets/Ipv4Address.cpp deleted file mode 100644 index 03935038951..00000000000 --- a/externals/sockets/Ipv4Address.cpp +++ /dev/null @@ -1,192 +0,0 @@ -/** - ** \file Ipv4Address.cpp - ** \date 2006-09-21 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2007 Anders Hedstrom - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#include "Ipv4Address.h" -#include "Utility.h" -#include "Parse.h" -#ifndef _WIN32 -#include -#endif - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -Ipv4Address::Ipv4Address(port_t port) : m_valid(true) -{ - memset(&m_addr, 0, sizeof(m_addr)); - m_addr.sin_family = AF_INET; - m_addr.sin_port = htons( port ); -} - -Ipv4Address::Ipv4Address(ipaddr_t a,port_t port) : m_valid(true) -{ - memset(&m_addr, 0, sizeof(m_addr)); - m_addr.sin_family = AF_INET; - m_addr.sin_port = htons( port ); - memcpy(&m_addr.sin_addr, &a, sizeof(struct in_addr)); -} - -Ipv4Address::Ipv4Address(struct in_addr& a,port_t port) : m_valid(true) -{ - memset(&m_addr, 0, sizeof(m_addr)); - m_addr.sin_family = AF_INET; - m_addr.sin_port = htons( port ); - m_addr.sin_addr = a; -} - -Ipv4Address::Ipv4Address(const std::string& host,port_t port) : m_valid(false) -{ - memset(&m_addr, 0, sizeof(m_addr)); - m_addr.sin_family = AF_INET; - m_addr.sin_port = htons( port ); - { - ipaddr_t a; - if (Utility::u2ip(host, a)) - { - memcpy(&m_addr.sin_addr, &a, sizeof(struct in_addr)); - m_valid = true; - } - } -} - -Ipv4Address::Ipv4Address(struct sockaddr_in& sa) -{ - m_addr = sa; - m_valid = sa.sin_family == AF_INET; -} - -Ipv4Address::~Ipv4Address() -{ -} - -Ipv4Address::operator struct sockaddr *() -{ - return (struct sockaddr *)&m_addr; -} - -Ipv4Address::operator socklen_t() -{ - return sizeof(struct sockaddr_in); -} - -void Ipv4Address::SetPort(port_t port) -{ - m_addr.sin_port = htons( port ); -} - -port_t Ipv4Address::GetPort() -{ - return ntohs( m_addr.sin_port ); -} - -bool Ipv4Address::Resolve(const std::string& hostname,struct in_addr& a) -{ - struct sockaddr_in sa; - memset(&a, 0, sizeof(a)); - if (Utility::isipv4(hostname)) - { - if (!Utility::u2ip(hostname, sa, AI_NUMERICHOST)) - return false; - a = sa.sin_addr; - return true; - } - if (!Utility::u2ip(hostname, sa)) - return false; - a = sa.sin_addr; - return true; -} - -bool Ipv4Address::Reverse(struct in_addr& a,std::string& name) -{ - struct sockaddr_in sa; - memset(&sa, 0, sizeof(sa)); - sa.sin_family = AF_INET; - sa.sin_addr = a; - return Utility::reverse((struct sockaddr *)&sa, sizeof(sa), name); -} - -std::string Ipv4Address::Convert(bool include_port) -{ - if (include_port) - return Convert(m_addr.sin_addr) + ":" + Utility::l2string(GetPort()); - return Convert(m_addr.sin_addr); -} - -std::string Ipv4Address::Convert(struct in_addr& a) -{ - struct sockaddr_in sa; - memset(&sa, 0, sizeof(sa)); - sa.sin_family = AF_INET; - sa.sin_addr = a; - std::string name; - Utility::reverse((struct sockaddr *)&sa, sizeof(sa), name, NI_NUMERICHOST); - return name; -} - -void Ipv4Address::SetAddress(struct sockaddr *sa) -{ - memcpy(&m_addr, sa, sizeof(struct sockaddr_in)); -} - -int Ipv4Address::GetFamily() -{ - return m_addr.sin_family; -} - -bool Ipv4Address::IsValid() -{ - return m_valid; -} - -bool Ipv4Address::operator==(SocketAddress& a) -{ - if (a.GetFamily() != GetFamily()) - return false; - if ((socklen_t)a != sizeof(m_addr)) - return false; - struct sockaddr *sa = a; - struct sockaddr_in *p = (struct sockaddr_in *)sa; - if (p -> sin_port != m_addr.sin_port) - return false; - if (memcmp(&p -> sin_addr, &m_addr.sin_addr, 4)) - return false; - return true; -} - -std::auto_ptr Ipv4Address::GetCopy() -{ - return std::auto_ptr(new Ipv4Address(m_addr)); -} - -std::string Ipv4Address::Reverse() -{ - std::string tmp; - Reverse(m_addr.sin_addr, tmp); - return tmp; -} - -#ifdef SOCKETS_NAMESPACE -} // namespace SOCKETS_NAMESPACE { -#endif - - diff --git a/externals/sockets/Ipv6Address.cpp b/externals/sockets/Ipv6Address.cpp deleted file mode 100644 index 3208b5098fa..00000000000 --- a/externals/sockets/Ipv6Address.cpp +++ /dev/null @@ -1,247 +0,0 @@ -/** - ** \file Ipv6Address.cpp - ** \date 2006-09-21 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2007 Anders Hedstrom - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#include "Ipv6Address.h" -#ifdef ENABLE_IPV6 - -#include "Utility.h" -#include "Parse.h" -#ifndef _WIN32 -#include -#endif -#ifdef IPPROTO_IPV6 - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -Ipv6Address::Ipv6Address(port_t port) : m_valid(true) -{ - memset(&m_addr, 0, sizeof(m_addr)); - m_addr.sin6_family = AF_INET6; - m_addr.sin6_port = htons( port ); -} - -Ipv6Address::Ipv6Address(struct in6_addr& a,port_t port) : m_valid(true) -{ - memset(&m_addr, 0, sizeof(m_addr)); - m_addr.sin6_family = AF_INET6; - m_addr.sin6_port = htons( port ); - m_addr.sin6_addr = a; -} - -Ipv6Address::Ipv6Address(const std::string& host,port_t port) : m_valid(false) -{ - memset(&m_addr, 0, sizeof(m_addr)); - m_addr.sin6_family = AF_INET6; - m_addr.sin6_port = htons( port ); - { - struct in6_addr a; - if (Utility::u2ip(host, a)) - { - m_addr.sin6_addr = a; - m_valid = true; - } - } -} - -Ipv6Address::Ipv6Address(struct sockaddr_in6& sa) -{ - m_addr = sa; - m_valid = sa.sin6_family == AF_INET6; -} - -Ipv6Address::~Ipv6Address() -{ -} - -Ipv6Address::operator struct sockaddr *() -{ - return (struct sockaddr *)&m_addr; -} - -Ipv6Address::operator socklen_t() -{ - return sizeof(struct sockaddr_in6); -} - -void Ipv6Address::SetPort(port_t port) -{ - m_addr.sin6_port = htons( port ); -} - -port_t Ipv6Address::GetPort() -{ - return ntohs( m_addr.sin6_port ); -} - -bool Ipv6Address::Resolve(const std::string& hostname,struct in6_addr& a) -{ - struct sockaddr_in6 sa; - memset(&a, 0, sizeof(a)); - if (Utility::isipv6(hostname)) - { - if (!Utility::u2ip(hostname, sa, AI_NUMERICHOST)) - return false; - a = sa.sin6_addr; - return true; - } - if (!Utility::u2ip(hostname, sa)) - return false; - a = sa.sin6_addr; - return true; -} - -bool Ipv6Address::Reverse(struct in6_addr& a,std::string& name) -{ - struct sockaddr_in6 sa; - memset(&sa, 0, sizeof(sa)); - sa.sin6_family = AF_INET6; - sa.sin6_addr = a; - return Utility::reverse((struct sockaddr *)&sa, sizeof(sa), name); -} - -std::string Ipv6Address::Convert(bool include_port) -{ - if (include_port) - return Convert(m_addr.sin6_addr) + ":" + Utility::l2string(GetPort()); - return Convert(m_addr.sin6_addr); -} - -std::string Ipv6Address::Convert(struct in6_addr& a,bool mixed) -{ - char slask[100]; // l2ip temporary - *slask = 0; - unsigned int prev = 0; - bool skipped = false; - bool ok_to_skip = true; - if (mixed) - { - unsigned short x; - unsigned short addr16[8]; - memcpy(addr16, &a, sizeof(addr16)); - for (size_t i = 0; i < 6; i++) - { - x = ntohs(addr16[i]); - if (*slask && (x || !ok_to_skip || prev)) - strcat(slask,":"); - if (x || !ok_to_skip) - { - sprintf(slask + strlen(slask),"%x", x); - if (x && skipped) - ok_to_skip = false; - } - else - { - skipped = true; - } - prev = x; - } - x = ntohs(addr16[6]); - sprintf(slask + strlen(slask),":%u.%u",x / 256,x & 255); - x = ntohs(addr16[7]); - sprintf(slask + strlen(slask),".%u.%u",x / 256,x & 255); - } - else - { - struct sockaddr_in6 sa; - memset(&sa, 0, sizeof(sa)); - sa.sin6_family = AF_INET6; - sa.sin6_addr = a; - std::string name; - Utility::reverse((struct sockaddr *)&sa, sizeof(sa), name, NI_NUMERICHOST); - return name; - } - return slask; -} - -void Ipv6Address::SetAddress(struct sockaddr *sa) -{ - memcpy(&m_addr, sa, sizeof(struct sockaddr_in6)); -} - -int Ipv6Address::GetFamily() -{ - return m_addr.sin6_family; -} - -void Ipv6Address::SetFlowinfo(uint32_t x) -{ - m_addr.sin6_flowinfo = x; -} - -uint32_t Ipv6Address::GetFlowinfo() -{ - return m_addr.sin6_flowinfo; -} - -#ifndef _WIN32 -void Ipv6Address::SetScopeId(uint32_t x) -{ - m_addr.sin6_scope_id = x; -} - -uint32_t Ipv6Address::GetScopeId() -{ - return m_addr.sin6_scope_id; -} -#endif - -bool Ipv6Address::IsValid() -{ - return m_valid; -} - -bool Ipv6Address::operator==(SocketAddress& a) -{ - if (a.GetFamily() != GetFamily()) - return false; - if ((socklen_t)a != sizeof(m_addr)) - return false; - struct sockaddr *sa = a; - struct sockaddr_in6 *p = (struct sockaddr_in6 *)sa; - if (p -> sin6_port != m_addr.sin6_port) - return false; - if (memcmp(&p -> sin6_addr, &m_addr.sin6_addr, sizeof(struct in6_addr))) - return false; - return true; -} - -std::auto_ptr Ipv6Address::GetCopy() -{ - return std::auto_ptr(new Ipv6Address(m_addr)); -} - -std::string Ipv6Address::Reverse() -{ - std::string tmp; - Reverse(m_addr.sin6_addr, tmp); - return tmp; -} - -#ifdef SOCKETS_NAMESPACE -} // namespace SOCKETS_NAMESPACE { -#endif -#endif // IPPROTO_IPV6 -#endif // ENABLE_IPV6 - - diff --git a/externals/sockets/Lock.cpp b/externals/sockets/Lock.cpp deleted file mode 100644 index b75664cfbdc..00000000000 --- a/externals/sockets/Lock.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/** \file Lock.cpp - ** \date 2005-08-22 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2005,2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#include "Mutex.h" -#include "Lock.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -Lock::Lock(Mutex& m) : m_mutex(m) -{ - m_mutex.Lock(); -} - -Lock::~Lock() -{ - m_mutex.Unlock(); -} - - -#ifdef SOCKETS_NAMESPACE -} -#endif - - diff --git a/externals/sockets/Makefile b/externals/sockets/Makefile deleted file mode 100644 index 80faf67aed9..00000000000 --- a/externals/sockets/Makefile +++ /dev/null @@ -1,136 +0,0 @@ -# CMAKE generated file: DO NOT EDIT! -# Generated by "Unix Makefiles" Generator, CMake Version 2.6 - -# Default target executed when no arguments are given to make. -default_target: all -.PHONY : default_target - -#============================================================================= -# Special targets provided by cmake. - -# Disable implicit rules so canoncical targets will work. -.SUFFIXES: - -# Remove some rules from gmake that .SUFFIXES does not remove. -SUFFIXES = - -.SUFFIXES: .hpux_make_needs_suffix_list - -# Suppress display of executed commands. -$(VERBOSE).SILENT: - -# A target that is always out of date. -cmake_force: -.PHONY : cmake_force - -#============================================================================= -# Set environment variables for the build. - -# The shell in which to execute make rules. -SHELL = /bin/sh - -# The CMake executable. -CMAKE_COMMAND = /usr/bin/cmake - -# The command to remove a file. -RM = /usr/bin/cmake -E remove -f - -# The program to use to edit the cache. -CMAKE_EDIT_COMMAND = /usr/bin/ccmake - -# The top-level source directory on which CMake was run. -CMAKE_SOURCE_DIR = /home/trinity/dev/trinitycore/externals/sockets - -# The top-level build directory on which CMake was run. -CMAKE_BINARY_DIR = /home/trinity/dev/trinitycore/externals/sockets - -#============================================================================= -# Targets provided globally by CMake. - -# Special rule for the target edit_cache -edit_cache: - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake cache editor..." - /usr/bin/ccmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) -.PHONY : edit_cache - -# Special rule for the target edit_cache -edit_cache/fast: edit_cache -.PHONY : edit_cache/fast - -# Special rule for the target rebuild_cache -rebuild_cache: - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..." - /usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) -.PHONY : rebuild_cache - -# Special rule for the target rebuild_cache -rebuild_cache/fast: rebuild_cache -.PHONY : rebuild_cache/fast - -# The main all target -all: cmake_check_build_system - $(CMAKE_COMMAND) -E cmake_progress_start /home/trinity/dev/trinitycore/externals/sockets/CMakeFiles /home/trinity/dev/trinitycore/externals/sockets/CMakeFiles/progress.make - $(MAKE) -f CMakeFiles/Makefile2 all - $(CMAKE_COMMAND) -E cmake_progress_start /home/trinity/dev/trinitycore/externals/sockets/CMakeFiles 0 -.PHONY : all - -# The main clean target -clean: - $(MAKE) -f CMakeFiles/Makefile2 clean -.PHONY : clean - -# The main clean target -clean/fast: clean -.PHONY : clean/fast - -# Prepare targets for installation. -preinstall: all - $(MAKE) -f CMakeFiles/Makefile2 preinstall -.PHONY : preinstall - -# Prepare targets for installation. -preinstall/fast: - $(MAKE) -f CMakeFiles/Makefile2 preinstall -.PHONY : preinstall/fast - -# clear depends -depend: - $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1 -.PHONY : depend - -#============================================================================= -# Target rules for targets named trinitysockets - -# Build rule for target. -trinitysockets: cmake_check_build_system - $(MAKE) -f CMakeFiles/Makefile2 trinitysockets -.PHONY : trinitysockets - -# fast build rule for target. -trinitysockets/fast: - $(MAKE) -f CMakeFiles/trinitysockets.dir/build.make CMakeFiles/trinitysockets.dir/build -.PHONY : trinitysockets/fast - -# Help Target -help: - @echo "The following are some of the valid targets for this Makefile:" - @echo "... all (the default if no target is provided)" - @echo "... clean" - @echo "... depend" - @echo "... edit_cache" - @echo "... rebuild_cache" - @echo "... trinitysockets" -.PHONY : help - - - -#============================================================================= -# Special targets to cleanup operation of make. - -# Special rule to run CMake to check the build system integrity. -# No rule that depends on this can have commands that come from listfiles -# because they might be regenerated. -cmake_check_build_system: - $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0 -.PHONY : cmake_check_build_system - diff --git a/externals/sockets/Mutex.cpp b/externals/sockets/Mutex.cpp deleted file mode 100644 index 681e85cee5b..00000000000 --- a/externals/sockets/Mutex.cpp +++ /dev/null @@ -1,77 +0,0 @@ -/** \file Mutex.cpp - ** \date 2004-10-30 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#include "Mutex.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -Mutex::Mutex() -{ -#ifdef _WIN32 - m_mutex = ::CreateMutex(NULL, FALSE, NULL); -#else - pthread_mutex_init(&m_mutex, NULL); -#endif -} - -Mutex::~Mutex() -{ -#ifdef _WIN32 - ::CloseHandle(m_mutex); -#else - pthread_mutex_destroy(&m_mutex); -#endif -} - -void Mutex::Lock() -{ -#ifdef _WIN32 - /*DWORD d =*/ WaitForSingleObject(m_mutex, INFINITE); - /// \todo check 'd' for result -#else - pthread_mutex_lock(&m_mutex); -#endif -} - -void Mutex::Unlock() -{ -#ifdef _WIN32 - ::ReleaseMutex(m_mutex); -#else - pthread_mutex_unlock(&m_mutex); -#endif -} - -#ifdef SOCKETS_NAMESPACE -} -#endif - - diff --git a/externals/sockets/Parse.cpp b/externals/sockets/Parse.cpp deleted file mode 100644 index 2967859f23d..00000000000 --- a/externals/sockets/Parse.cpp +++ /dev/null @@ -1,318 +0,0 @@ -/** \file Parse.cpp - parse a string - ** - ** Written: 1999-Feb-10 grymse@alhem.net - **/ - -/* -Copyright (C) 1999-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#include -#include - -#include "Parse.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/* implementation of class Parse */ - -Parse::Parse() -:pa_the_str("") -,pa_splits("") -,pa_ord("") -,pa_the_ptr(0) -,pa_breakchar(0) -,pa_enable(0) -,pa_disable(0) -,pa_nospace(0) -,pa_quote(false) -{ -} - -Parse::Parse(const std::string&s) -:pa_the_str(s) -,pa_splits("") -,pa_ord("") -,pa_the_ptr(0) -,pa_breakchar(0) -,pa_enable(0) -,pa_disable(0) -,pa_nospace(0) -,pa_quote(false) -{ -} - -Parse::Parse(const std::string&s,const std::string&sp) -:pa_the_str(s) -,pa_splits(sp) -,pa_ord("") -,pa_the_ptr(0) -,pa_breakchar(0) -,pa_enable(0) -,pa_disable(0) -,pa_nospace(0) -,pa_quote(false) -{ -} - -Parse::Parse(const std::string&s,const std::string&sp,short /*nospace*/) -:pa_the_str(s) -,pa_splits(sp) -,pa_ord("") -,pa_the_ptr(0) -,pa_breakchar(0) -,pa_enable(0) -,pa_disable(0) -,pa_nospace(1) -,pa_quote(false) -{ -} - -Parse::~Parse() -{ -} - -#define C ((pa_the_ptr l(h); - - if (l.Bind("127.0.0.1", m_port)) - { - return; - } - h.Add(&l); - - m_ready = true; - while (!m_quit && IsRunning() ) - { - h.Select(0, 500000); - } - SetRunning(false); -} - -void ResolvServer::Quit() -{ - m_quit = true; -} - -bool ResolvServer::Ready() -{ - return m_ready; -} - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // ENABLE_RESOLVER - - diff --git a/externals/sockets/ResolvSocket.cpp b/externals/sockets/ResolvSocket.cpp deleted file mode 100644 index 636de276426..00000000000 --- a/externals/sockets/ResolvSocket.cpp +++ /dev/null @@ -1,426 +0,0 @@ -/** \file ResolvSocket.cpp - ** \date 2005-03-24 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifdef _WIN32 -#ifdef _MSC_VER -#pragma warning(disable:4786) -#pragma warning(disable:4503) -#endif -#else -#include -#endif -#include "ResolvSocket.h" -#ifdef ENABLE_RESOLVER -#include "Utility.h" -#include "Parse.h" -#include "ISocketHandler.h" -#include "Lock.h" -#include "Mutex.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -//#ifdef _DEBUG -//#define DEB(x) x -//#else -#define DEB(x) -//#endif - -// static -ResolvSocket::cache_t ResolvSocket::m_cache; -ResolvSocket::timeout_t ResolvSocket::m_cache_to; -Mutex ResolvSocket::m_cache_mutex; - -ResolvSocket::ResolvSocket(ISocketHandler& h) -:TcpSocket(h) -,m_bServer(false) -,m_parent(NULL) -#ifdef ENABLE_IPV6 -,m_resolve_ipv6(false) -#endif -,m_cached(false) -{ - SetLineProtocol(); -} - -ResolvSocket::ResolvSocket(ISocketHandler& h, Socket *parent, const std::string& host, port_t port, bool ipv6) -:TcpSocket(h) -,m_bServer(false) -,m_parent(parent) -,m_resolv_host(host) -,m_resolv_port(port) -#ifdef ENABLE_IPV6 -,m_resolve_ipv6(ipv6) -#endif -,m_cached(false) -{ - SetLineProtocol(); -} - -ResolvSocket::ResolvSocket(ISocketHandler& h, Socket *parent, ipaddr_t a) -:TcpSocket(h) -,m_bServer(false) -,m_parent(parent) -,m_resolv_port(0) -,m_resolv_address(a) -#ifdef ENABLE_IPV6 -,m_resolve_ipv6(false) -#endif -,m_cached(false) -{ - SetLineProtocol(); -} - -#ifdef ENABLE_IPV6 -ResolvSocket::ResolvSocket(ISocketHandler& h, Socket *parent, in6_addr& a) -:TcpSocket(h) -,m_bServer(false) -,m_parent(parent) -,m_resolv_port(0) -,m_resolve_ipv6(true) -,m_resolv_address6(a) -,m_cached(false) -{ - SetLineProtocol(); -} -#endif - -ResolvSocket::~ResolvSocket() -{ -} - -void ResolvSocket::OnLine(const std::string& line) -{ - Parse pa(line, ":"); - if (m_bServer) - { - m_query = pa.getword(); - m_data = pa.getrest(); -DEB( fprintf(stderr, " *** ResolvSocket server; query=%s, data=%s\n", m_query.c_str(), m_data.c_str());) - // %! check cache - { - Lock lock(m_cache_mutex); - if (m_cache[m_query].find(m_data) != m_cache[m_query].end()) - { - if (time(NULL) - m_cache_to[m_query][m_data] < 3600) // ttl - { - std::string result = m_cache[m_query][m_data]; -DEB(fprintf(stderr, " *** Returning cache for [%s][%s] = '%s'\n", m_query.c_str(), m_data.c_str(), result.c_str());) - Send("Cached\n"); - if (!result.size()) /* failed */ - { - Send("Failed\n\n"); - SetCloseAndDelete(); - return; - } - else - if (m_query == "gethostbyname") - { - Send("A: " + result + "\n\n"); - SetCloseAndDelete(); - return; - } - else -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (m_query == "gethostbyname2") - { - Send("AAAA: " + result + "\n\n"); - SetCloseAndDelete(); - return; - } - else -#endif -#endif - if (m_query == "gethostbyaddr") - { - Send("Name: " + result + "\n\n"); - SetCloseAndDelete(); - return; - } - } - } - } - if (!Detach()) // detach failed? - { - SetCloseAndDelete(); - } - return; - } - std::string key = pa.getword(); - std::string value = pa.getrest(); -DEB( fprintf(stderr, " *** ResolvSocket response; %s: %s\n", key.c_str(), value.c_str());) - - if (key == "Cached") - { - m_cached = true; - } - else - if (key == "Failed" && m_parent) - { -DEB( fprintf(stderr, " ************ Resolve failed\n");) - if (Handler().Resolving(m_parent) || Handler().Valid(m_parent)) - { - m_parent -> OnResolveFailed(m_resolv_id); - } - // update cache - if (!m_cached) - { - Lock lock(m_cache_mutex); -DEB(fprintf(stderr, " *** Update cache for [%s][%s] = '%s'\n", m_query.c_str(), m_data.c_str(), value.c_str());) - m_cache[m_query][m_data] = value; - m_cache_to[m_query][m_data] = time(NULL); - } - m_parent = NULL; - } - else - if (key == "Name" && !m_resolv_host.size() && m_parent) - { - if (Handler().Resolving(m_parent) || Handler().Valid(m_parent)) - { - m_parent -> OnReverseResolved(m_resolv_id, value); - } - // update cache - if (!m_cached) - { - Lock lock(m_cache_mutex); -DEB(fprintf(stderr, " *** Update cache for [%s][%s] = '%s'\n", m_query.c_str(), m_data.c_str(), value.c_str());) - m_cache[m_query][m_data] = value; - m_cache_to[m_query][m_data] = time(NULL); - } - m_parent = NULL; - } - else - if (key == "A" && m_parent) - { - if (Handler().Resolving(m_parent) || Handler().Valid(m_parent)) - { - ipaddr_t l; - Utility::u2ip(value, l); // ip2ipaddr_t - m_parent -> OnResolved(m_resolv_id, l, m_resolv_port); - } - // update cache - if (!m_cached) - { - Lock lock(m_cache_mutex); -DEB(fprintf(stderr, " *** Update cache for [%s][%s] = '%s'\n", m_query.c_str(), m_data.c_str(), value.c_str());) - m_cache[m_query][m_data] = value; - m_cache_to[m_query][m_data] = time(NULL); - } - m_parent = NULL; // always use first ip in case there are several - } -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - else - if (key == "AAAA" && m_parent) - { - if (Handler().Resolving(m_parent) || Handler().Valid(m_parent)) - { - in6_addr a; - Utility::u2ip(value, a); - m_parent -> OnResolved(m_resolv_id, a, m_resolv_port); - } - // update cache - if (!m_cached) - { - Lock lock(m_cache_mutex); -DEB(fprintf(stderr, " *** Update cache for [%s][%s] = '%s'\n", m_query.c_str(), m_data.c_str(), value.c_str());) - m_cache[m_query][m_data] = value; - m_cache_to[m_query][m_data] = time(NULL); - } - m_parent = NULL; - } -#endif -#endif -} - -void ResolvSocket::OnDetached() -{ -DEB( fprintf(stderr, " *** ResolvSocket::OnDetached(); query=%s, data=%s\n", m_query.c_str(), m_data.c_str());) - if (m_query == "gethostbyname") - { - struct sockaddr_in sa; - if (Utility::u2ip(m_data, sa)) - { - std::string ip; - Utility::l2ip(sa.sin_addr, ip); - Send("A: " + ip + "\n"); - } - else - { - Send("Failed\n"); - } - Send("\n"); - } - else -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (m_query == "gethostbyname2") - { - struct sockaddr_in6 sa; - if (Utility::u2ip(m_data, sa)) - { - std::string ip; - Utility::l2ip(sa.sin6_addr, ip); - Send("AAAA: " + ip + "\n"); - } - else - { - Send("Failed\n"); - } - Send("\n"); - } - else -#endif -#endif - if (m_query == "gethostbyaddr") - { - if (Utility::isipv4( m_data )) - { - struct sockaddr_in sa; - if (!Utility::u2ip(m_data, sa, AI_NUMERICHOST)) - { - Send("Failed: convert to sockaddr_in failed\n"); - } - else - { - std::string name; - if (!Utility::reverse( (struct sockaddr *)&sa, sizeof(sa), name)) - { - Send("Failed: ipv4 reverse lookup of " + m_data + "\n"); - } - else - { - Send("Name: " + name + "\n"); - } - } - } - else -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (Utility::isipv6( m_data )) - { - struct sockaddr_in6 sa; - if (!Utility::u2ip(m_data, sa, AI_NUMERICHOST)) - { - Send("Failed: convert to sockaddr_in6 failed\n"); - } - else - { - std::string name; - if (!Utility::reverse( (struct sockaddr *)&sa, sizeof(sa), name)) - { - Send("Failed: ipv6 reverse lookup of " + m_data + "\n"); - } - else - { - Send("Name: " + name + "\n"); - } - } - } - else -#endif -#endif - { - Send("Failed: malformed address\n"); - } - Send("\n"); - } - else - { - std::string msg = "Unknown query type: " + m_query; - Handler().LogError(this, "OnDetached", 0, msg); - Send("Unknown\n\n"); - } - SetCloseAndDelete(); -} - -void ResolvSocket::OnConnect() -{ - if (!m_resolv_host.empty()) - { -#ifdef ENABLE_IPV6 - std::string msg = (m_resolve_ipv6 ? "gethostbyname2 " : "gethostbyname ") + m_resolv_host + "\n"; - m_query = m_resolve_ipv6 ? "gethostbyname2" : "gethostbyname"; -#else - std::string msg = "gethostbyname " + m_resolv_host + "\n"; - m_query = "gethostbyname"; -#endif - m_data = m_resolv_host; - Send( msg ); - return; - } -#ifdef ENABLE_IPV6 - if (m_resolve_ipv6) - { - std::string tmp; - Utility::l2ip(m_resolv_address6, tmp); - m_query = "gethostbyaddr"; - m_data = tmp; - std::string msg = "gethostbyaddr " + tmp + "\n"; - Send( msg ); - } -#endif - std::string tmp; - Utility::l2ip(m_resolv_address, tmp); - m_query = "gethostbyaddr"; - m_data = tmp; - std::string msg = "gethostbyaddr " + tmp + "\n"; - Send( msg ); -} - -void ResolvSocket::OnDelete() -{ - if (m_parent) - { - if (Handler().Resolving(m_parent) || Handler().Valid(m_parent)) - { - m_parent -> OnResolveFailed(m_resolv_id); - } - // update cache - if (!m_cached) - { - Lock lock(m_cache_mutex); - std::string value; -DEB(fprintf(stderr, " *** Update cache for [%s][%s] = '%s'\n", m_query.c_str(), m_data.c_str(), value.c_str());) - m_cache[m_query][m_data] = value; - m_cache_to[m_query][m_data] = time(NULL); - } - m_parent = NULL; - } -} - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // ENABLE_RESOLVER - - diff --git a/externals/sockets/Socket.cpp b/externals/sockets/Socket.cpp deleted file mode 100644 index f53cd27621e..00000000000 --- a/externals/sockets/Socket.cpp +++ /dev/null @@ -1,1726 +0,0 @@ -/** \file Socket.cpp - ** \date 2004-02-13 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#include "Socket.h" -#ifdef _WIN32 -#ifdef _MSC_VER -#pragma warning(disable:4786) -#endif -#include -#else -#include -#include -#endif -#include -#include - -#include "ISocketHandler.h" -#include "Utility.h" - -#include "SocketAddress.h" -#include "SocketHandler.h" -#ifdef ENABLE_EXCEPTIONS -#include "Exception.h" -#endif -#include "Ipv4Address.h" - -//#ifdef _DEBUG -//#define DEB(x) x; fflush(stderr); -//#else -#define DEB(x) -//#endif - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -// statics -#ifdef _WIN32 -WSAInitializer Socket::m_winsock_init; -#endif - -Socket::Socket(ISocketHandler& h) -//:m_flags(0) -:m_handler(h) -,m_socket( INVALID_SOCKET ) -,m_bDel(false) -,m_bClose(false) -,m_tCreate(time(NULL)) -,m_parent(NULL) -,m_b_disable_read(false) -,m_connected(false) -,m_b_erased_by_handler(false) -,m_tClose(0) -,m_client_remote_address(NULL) -,m_remote_address(NULL) -,m_traffic_monitor(NULL) -,m_bLost(false) -#ifdef HAVE_OPENSSL -,m_b_enable_ssl(false) -,m_b_ssl(false) -,m_b_ssl_server(false) -#endif -#ifdef ENABLE_IPV6 -,m_ipv6(false) -#endif -#ifdef ENABLE_POOL -,m_socket_type(0) -,m_bClient(false) -,m_bRetain(false) -#endif -#ifdef ENABLE_SOCKS4 -,m_bSocks4(false) -,m_socks4_host(h.GetSocks4Host()) -,m_socks4_port(h.GetSocks4Port()) -,m_socks4_userid(h.GetSocks4Userid()) -#endif -#ifdef ENABLE_DETACH -,m_detach(false) -,m_detached(false) -,m_pThread(NULL) -,m_slave_handler(NULL) -#endif -{ -} - -Socket::~Socket() -{ - Handler().Remove(this); - if (m_socket != INVALID_SOCKET -#ifdef ENABLE_POOL - && !m_bRetain -#endif - ) - { - Close(); - } -} - -void Socket::Init() -{ -} - -void Socket::OnRead() -{ -} - -void Socket::OnWrite() -{ -} - -void Socket::OnException() -{ - // %! exception doesn't always mean something bad happened, this code should be reworked - // errno valid here? - int err = SoError(); - Handler().LogError(this, "exception on select", err, StrError(err), LOG_LEVEL_FATAL); - SetCloseAndDelete(); -} - -void Socket::OnDelete() -{ -} - -void Socket::OnConnect() -{ -} - -void Socket::OnAccept() -{ -} - -int Socket::Close() -{ - if (m_socket == INVALID_SOCKET) // this could happen - { - Handler().LogError(this, "Socket::Close", 0, "file descriptor invalid", LOG_LEVEL_WARNING); - return 0; - } - int n; - if ((n = closesocket(m_socket)) == -1) - { - // failed... - Handler().LogError(this, "close", Errno, StrError(Errno), LOG_LEVEL_ERROR); - } - Handler().Set(m_socket, false, false, false); // remove from fd_set's - Handler().AddList(m_socket, LIST_CALLONCONNECT, false); -#ifdef ENABLE_DETACH - Handler().AddList(m_socket, LIST_DETACH, false); -#endif - Handler().AddList(m_socket, LIST_TIMEOUT, false); - Handler().AddList(m_socket, LIST_RETRY, false); - Handler().AddList(m_socket, LIST_CLOSE, false); - m_socket = INVALID_SOCKET; - return n; -} - -SOCKET Socket::CreateSocket(int af,int type, const std::string& protocol) -{ - struct protoent *p = NULL; - SOCKET s; - -#ifdef ENABLE_POOL - m_socket_type = type; - m_socket_protocol = protocol; -#endif - if (!protocol.empty()) - { - p = getprotobyname( protocol.c_str() ); - if (!p) - { - Handler().LogError(this, "getprotobyname", Errno, StrError(Errno), LOG_LEVEL_FATAL); - SetCloseAndDelete(); -#ifdef ENABLE_EXCEPTIONS - throw Exception(std::string("getprotobyname() failed: ") + StrError(Errno)); -#endif - return INVALID_SOCKET; - } - } - int protno = p ? p -> p_proto : 0; - - s = socket(af, type, protno); - if (s == INVALID_SOCKET) - { - Handler().LogError(this, "socket", Errno, StrError(Errno), LOG_LEVEL_FATAL); - SetCloseAndDelete(); -#ifdef ENABLE_EXCEPTIONS - throw Exception(std::string("socket() failed: ") + StrError(Errno)); -#endif - return INVALID_SOCKET; - } - Attach(s); - OnOptions(af, type, protno, s); - Attach(INVALID_SOCKET); - return s; -} - -void Socket::Attach(SOCKET s) -{ - m_socket = s; -} - -SOCKET Socket::GetSocket() -{ - return m_socket; -} - -void Socket::SetDeleteByHandler(bool x) -{ - m_bDel = x; -} - -bool Socket::DeleteByHandler() -{ - return m_bDel; -} - -void Socket::SetCloseAndDelete(bool x) -{ - if (x != m_bClose) - { - Handler().AddList(m_socket, LIST_CLOSE, x); - m_bClose = x; - if (x) - { - m_tClose = time(NULL); - } - } -} - -bool Socket::CloseAndDelete() -{ - return m_bClose; -} - -void Socket::SetRemoteAddress(SocketAddress& ad) //struct sockaddr* sa, socklen_t l) -{ - m_remote_address = ad.GetCopy(); -} - -std::auto_ptr Socket::GetRemoteSocketAddress() -{ - return m_remote_address -> GetCopy(); -} - -ISocketHandler& Socket::Handler() const -{ -#ifdef ENABLE_DETACH - if (IsDetached()) - return *m_slave_handler; -#endif - return m_handler; -} - -ISocketHandler& Socket::MasterHandler() const -{ - return m_handler; -} - -ipaddr_t Socket::GetRemoteIP4() -{ - ipaddr_t l = 0; -#ifdef ENABLE_IPV6 - if (m_ipv6) - { - Handler().LogError(this, "GetRemoteIP4", 0, "get ipv4 address for ipv6 socket", LOG_LEVEL_WARNING); - } -#endif - if (m_remote_address.get() != NULL) - { - struct sockaddr *p = *m_remote_address; - struct sockaddr_in *sa = (struct sockaddr_in *)p; - memcpy(&l, &sa -> sin_addr, sizeof(struct in_addr)); - } - return l; -} - -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 -struct in6_addr Socket::GetRemoteIP6() -{ - if (!m_ipv6) - { - Handler().LogError(this, "GetRemoteIP6", 0, "get ipv6 address for ipv4 socket", LOG_LEVEL_WARNING); - } - struct sockaddr_in6 fail; - if (m_remote_address.get() != NULL) - { - struct sockaddr *p = *m_remote_address; - memcpy(&fail, p, sizeof(struct sockaddr_in6)); - } - else - { - memset(&fail, 0, sizeof(struct sockaddr_in6)); - } - return fail.sin6_addr; -} -#endif -#endif - -port_t Socket::GetRemotePort() -{ - if (!m_remote_address.get()) - { - return 0; - } - return m_remote_address -> GetPort(); -} - -std::string Socket::GetRemoteAddress() -{ - if (!m_remote_address.get()) - { - return ""; - } - return m_remote_address -> Convert(false); -} - -std::string Socket::GetRemoteHostname() -{ - if (!m_remote_address.get()) - { - return ""; - } - return m_remote_address -> Reverse(); -} - -bool Socket::SetNonblocking(bool bNb) -{ -#ifdef _WIN32 - unsigned long l = bNb ? 1 : 0; - int n = ioctlsocket(m_socket, FIONBIO, &l); - if (n != 0) - { - Handler().LogError(this, "ioctlsocket(FIONBIO)", Errno, ""); - return false; - } - return true; -#else - if (bNb) - { - if (fcntl(m_socket, F_SETFL, O_NONBLOCK) == -1) - { - Handler().LogError(this, "fcntl(F_SETFL, O_NONBLOCK)", Errno, StrError(Errno), LOG_LEVEL_ERROR); - return false; - } - } - else - { - if (fcntl(m_socket, F_SETFL, 0) == -1) - { - Handler().LogError(this, "fcntl(F_SETFL, 0)", Errno, StrError(Errno), LOG_LEVEL_ERROR); - return false; - } - } - return true; -#endif -} - -bool Socket::SetNonblocking(bool bNb, SOCKET s) -{ -#ifdef _WIN32 - unsigned long l = bNb ? 1 : 0; - int n = ioctlsocket(s, FIONBIO, &l); - if (n != 0) - { - Handler().LogError(this, "ioctlsocket(FIONBIO)", Errno, ""); - return false; - } - return true; -#else - if (bNb) - { - if (fcntl(s, F_SETFL, O_NONBLOCK) == -1) - { - Handler().LogError(this, "fcntl(F_SETFL, O_NONBLOCK)", Errno, StrError(Errno), LOG_LEVEL_ERROR); - return false; - } - } - else - { - if (fcntl(s, F_SETFL, 0) == -1) - { - Handler().LogError(this, "fcntl(F_SETFL, 0)", Errno, StrError(Errno), LOG_LEVEL_ERROR); - return false; - } - } - return true; -#endif -} - -void Socket::Set(bool bRead, bool bWrite, bool bException) -{ - Handler().Set(m_socket, bRead, bWrite, bException); -} - -bool Socket::Ready() -{ - if (m_socket != INVALID_SOCKET && !CloseAndDelete()) - return true; - return false; -} - -void Socket::OnLine(const std::string& ) -{ -} - -void Socket::OnConnectFailed() -{ -} - -Socket *Socket::GetParent() -{ - return m_parent; -} - -void Socket::SetParent(Socket *x) -{ - m_parent = x; -} - -port_t Socket::GetPort() -{ - Handler().LogError(this, "GetPort", 0, "GetPort only implemented for ListenSocket", LOG_LEVEL_WARNING); - return 0; -} - -bool Socket::OnConnectRetry() -{ - return true; -} - -#ifdef ENABLE_RECONNECT -void Socket::OnReconnect() -{ -} -#endif - -time_t Socket::Uptime() -{ - return time(NULL) - m_tCreate; -} - -#ifdef ENABLE_IPV6 -void Socket::SetIpv6(bool x) -{ - m_ipv6 = x; -} - -bool Socket::IsIpv6() -{ - return m_ipv6; -} -#endif - -void Socket::DisableRead(bool x) -{ - m_b_disable_read = x; -} - -bool Socket::IsDisableRead() -{ - return m_b_disable_read; -} - -void Socket::SendBuf(const char *,size_t,int) -{ -} - -void Socket::Send(const std::string&,int) -{ -} - -void Socket::SetConnected(bool x) -{ - m_connected = x; -} - -bool Socket::IsConnected() -{ - return m_connected; -} - -void Socket::OnDisconnect() -{ -} - -void Socket::SetLost() -{ - m_bLost = true; -} - -bool Socket::Lost() -{ - return m_bLost; -} - -void Socket::SetErasedByHandler(bool x) -{ - m_b_erased_by_handler = x; -} - -bool Socket::ErasedByHandler() -{ - return m_b_erased_by_handler; -} - -time_t Socket::TimeSinceClose() -{ - return time(NULL) - m_tClose; -} - -void Socket::SetClientRemoteAddress(SocketAddress& ad) -{ - if (!ad.IsValid()) - { - Handler().LogError(this, "SetClientRemoteAddress", 0, "remote address not valid", LOG_LEVEL_ERROR); - } - m_client_remote_address = ad.GetCopy(); -} - -std::auto_ptr Socket::GetClientRemoteAddress() -{ - if (!m_client_remote_address.get()) - { - Handler().LogError(this, "GetClientRemoteAddress", 0, "remote address not yet set", LOG_LEVEL_ERROR); - } - return m_client_remote_address -> GetCopy(); -} - -uint64_t Socket::GetBytesSent(bool) -{ - return 0; -} - -uint64_t Socket::GetBytesReceived(bool) -{ - return 0; -} - -#ifdef HAVE_OPENSSL -void Socket::OnSSLConnect() -{ -} - -void Socket::OnSSLAccept() -{ -} - -bool Socket::SSLNegotiate() -{ - return false; -} - -bool Socket::IsSSL() -{ - return m_b_enable_ssl; -} - -void Socket::EnableSSL(bool x) -{ - m_b_enable_ssl = x; -} - -bool Socket::IsSSLNegotiate() -{ - return m_b_ssl; -} - -void Socket::SetSSLNegotiate(bool x) -{ - m_b_ssl = x; -} - -bool Socket::IsSSLServer() -{ - return m_b_ssl_server; -} - -void Socket::SetSSLServer(bool x) -{ - m_b_ssl_server = x; -} - -void Socket::OnSSLConnectFailed() -{ -} - -void Socket::OnSSLAcceptFailed() -{ -} -#endif // HAVE_OPENSSL - -#ifdef ENABLE_POOL -void Socket::CopyConnection(Socket *sock) -{ - Attach( sock -> GetSocket() ); -#ifdef ENABLE_IPV6 - SetIpv6( sock -> IsIpv6() ); -#endif - SetSocketType( sock -> GetSocketType() ); - SetSocketProtocol( sock -> GetSocketProtocol() ); - - SetClientRemoteAddress( *sock -> GetClientRemoteAddress() ); - SetRemoteAddress( *sock -> GetRemoteSocketAddress() ); -} - -void Socket::SetIsClient() -{ - m_bClient = true; -} - -void Socket::SetSocketType(int x) -{ - m_socket_type = x; -} - -int Socket::GetSocketType() -{ - return m_socket_type; -} - -void Socket::SetSocketProtocol(const std::string& x) -{ - m_socket_protocol = x; -} - -const std::string& Socket::GetSocketProtocol() -{ - return m_socket_protocol; -} - -void Socket::SetRetain() -{ - if (m_bClient) m_bRetain = true; -} - -bool Socket::Retain() -{ - return m_bRetain; -} - -#endif // ENABLE_POOL - -#ifdef ENABLE_SOCKS4 -void Socket::OnSocks4Connect() -{ - Handler().LogError(this, "OnSocks4Connect", 0, "Use with TcpSocket only"); -} - -void Socket::OnSocks4ConnectFailed() -{ - Handler().LogError(this, "OnSocks4ConnectFailed", 0, "Use with TcpSocket only"); -} - -bool Socket::OnSocks4Read() -{ - Handler().LogError(this, "OnSocks4Read", 0, "Use with TcpSocket only"); - return true; -} - -void Socket::SetSocks4Host(const std::string& host) -{ - Utility::u2ip(host, m_socks4_host); -} - -bool Socket::Socks4() -{ - return m_bSocks4; -} - -void Socket::SetSocks4(bool x) -{ - m_bSocks4 = x; -} - -void Socket::SetSocks4Host(ipaddr_t a) -{ - m_socks4_host = a; -} - -void Socket::SetSocks4Port(port_t p) -{ - m_socks4_port = p; -} - -void Socket::SetSocks4Userid(const std::string& x) -{ - m_socks4_userid = x; -} - -ipaddr_t Socket::GetSocks4Host() -{ - return m_socks4_host; -} - -port_t Socket::GetSocks4Port() -{ - return m_socks4_port; -} - -const std::string& Socket::GetSocks4Userid() -{ - return m_socks4_userid; -} -#endif // ENABLE_SOCKS4 - -#ifdef ENABLE_DETACH -bool Socket::Detach() -{ - if (!DeleteByHandler()) - return false; - if (m_pThread) - return false; - if (m_detached) - return false; - SetDetach(); - return true; -} - -void Socket::DetachSocket() -{ - SetDetached(); - m_pThread = new SocketThread(this); - m_pThread -> SetRelease(true); -} - -void Socket::OnDetached() -{ -} - -void Socket::SetDetach(bool x) -{ - Handler().AddList(m_socket, LIST_DETACH, x); - m_detach = x; -} - -bool Socket::IsDetach() -{ - return m_detach; -} - -void Socket::SetDetached(bool x) -{ - m_detached = x; -} - -const bool Socket::IsDetached() const -{ - return m_detached; -} - -void Socket::SetSlaveHandler(ISocketHandler *p) -{ - m_slave_handler = p; -} - -Socket::SocketThread::SocketThread(Socket *p) -:Thread(false) -,m_socket(p) -{ - // Creator will release -} - -Socket::SocketThread::~SocketThread() -{ - if (IsRunning()) - { - SetRelease(true); - SetRunning(false); -#ifdef _WIN32 - Sleep(1000); -#else - sleep(1); -#endif - } -} - -void Socket::SocketThread::Run() -{ - SocketHandler h; - h.SetSlave(); - h.Add(m_socket); - m_socket -> SetSlaveHandler(&h); - m_socket -> OnDetached(); - while (h.GetCount() && IsRunning()) - { - h.Select(0, 500000); - } - // m_socket now deleted oops - // yeah oops m_socket delete its socket thread, that means this - // so Socket will no longer delete its socket thread, instead we do this: - SetDeleteOnExit(); -} -#endif // ENABLE_DETACH - -#ifdef ENABLE_RESOLVER -int Socket::Resolve(const std::string& host,port_t port) -{ - return Handler().Resolve(this, host, port); -} - -#ifdef ENABLE_IPV6 -int Socket::Resolve6(const std::string& host,port_t port) -{ - return Handler().Resolve6(this, host, port); -} -#endif - -int Socket::Resolve(ipaddr_t a) -{ - return Handler().Resolve(this, a); -} - -#ifdef ENABLE_IPV6 -int Socket::Resolve(in6_addr& a) -{ - return Handler().Resolve(this, a); -} -#endif - -void Socket::OnResolved(int,ipaddr_t,port_t) -{ -} - -#ifdef ENABLE_IPV6 -void Socket::OnResolved(int,in6_addr&,port_t) -{ -} -#endif - -void Socket::OnReverseResolved(int,const std::string&) -{ -} - -void Socket::OnResolveFailed(int) -{ -} -#endif // ENABLE_RESOLVER - -/* IP options */ - -bool Socket::SetIpOptions(const void *p, socklen_t len) -{ -#ifdef IP_OPTIONS - if (setsockopt(GetSocket(), IPPROTO_IP, IP_OPTIONS, (char *)p, len) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_OPTIONS)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "ip option not available", 0, "IP_OPTIONS", LOG_LEVEL_INFO); - return false; -#endif -} - -#ifdef IP_PKTINFO -bool Socket::SetIpPktinfo(bool x) -{ - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), IPPROTO_IP, IP_PKTINFO, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_PKTINFO)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -#ifdef IP_RECVTOS -bool Socket::SetIpRecvTOS(bool x) -{ - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), IPPROTO_IP, IP_RECVTOS, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_RECVTOS)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -#ifdef IP_RECVTTL -bool Socket::SetIpRecvTTL(bool x) -{ - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), IPPROTO_IP, IP_RECVTTL, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_RECVTTL)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -#ifdef IP_RECVOPTS -bool Socket::SetIpRecvopts(bool x) -{ - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), IPPROTO_IP, IP_RECVOPTS, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_RECVOPTS)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -#ifdef IP_RETOPTS -bool Socket::SetIpRetopts(bool x) -{ - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), IPPROTO_IP, IP_RETOPTS, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_RETOPTS)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -bool Socket::SetIpTOS(unsigned char tos) -{ -#ifdef IP_TOS - if (setsockopt(GetSocket(), IPPROTO_IP, IP_TOS, (char *)&tos, sizeof(tos)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_TOS)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "ip option not available", 0, "IP_TOS", LOG_LEVEL_INFO); - return false; -#endif -} - -unsigned char Socket::IpTOS() -{ - unsigned char tos = 0; -#ifdef IP_TOS - socklen_t len = sizeof(tos); - if (getsockopt(GetSocket(), IPPROTO_IP, IP_TOS, (char *)&tos, &len) == -1) - { - Handler().LogError(this, "getsockopt(IPPROTO_IP, IP_TOS)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - } -#else - Handler().LogError(this, "ip option not available", 0, "IP_TOS", LOG_LEVEL_INFO); -#endif - return tos; -} - -bool Socket::SetIpTTL(int ttl) -{ -#ifdef IP_TTL - if (setsockopt(GetSocket(), IPPROTO_IP, IP_TTL, (char *)&ttl, sizeof(ttl)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_TTL)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "ip option not available", 0, "IP_TTL", LOG_LEVEL_INFO); - return false; -#endif -} - -int Socket::IpTTL() -{ - int ttl = 0; -#ifdef IP_TTL - socklen_t len = sizeof(ttl); - if (getsockopt(GetSocket(), IPPROTO_IP, IP_TTL, (char *)&ttl, &len) == -1) - { - Handler().LogError(this, "getsockopt(IPPROTO_IP, IP_TTL)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - } -#else - Handler().LogError(this, "ip option not available", 0, "IP_TTL", LOG_LEVEL_INFO); -#endif - return ttl; -} - -bool Socket::SetIpHdrincl(bool x) -{ -#ifdef IP_HDRINCL - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), IPPROTO_IP, IP_HDRINCL, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_HDRINCL)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "ip option not available", 0, "IP_HDRINCL", LOG_LEVEL_INFO); - return false; -#endif -} - -#ifdef IP_RECVERR -bool Socket::SetIpRecverr(bool x) -{ - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), IPPROTO_IP, IP_RECVERR, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_RECVERR)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -#ifdef IP_MTU_DISCOVER -bool Socket::SetIpMtudiscover(bool x) -{ - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), IPPROTO_IP, IP_MTU_DISCOVER, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_MTU_DISCOVER)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -#ifdef IP_MTU -int Socket::IpMtu() -{ - int mtu = 0; - socklen_t len = sizeof(mtu); - if (getsockopt(GetSocket(), IPPROTO_IP, IP_MTU, (char *)&mtu, &len) == -1) - { - Handler().LogError(this, "getsockopt(IPPROTO_IP, IP_MTU)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - } - return mtu; -} -#endif - -#ifdef IP_ROUTER_ALERT -bool Socket::SetIpRouterAlert(bool x) -{ - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), IPPROTO_IP, IP_ROUTER_ALERT, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_ROUTER_ALERT)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -bool Socket::SetIpMulticastTTL(int ttl) -{ -#ifdef IP_MULTICAST_TTL - if (setsockopt(GetSocket(), IPPROTO_IP, IP_MULTICAST_TTL, (char *)&ttl, sizeof(ttl)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_MULTICAST_TTL)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "ip option not available", 0, "IP_MULTICAST_TTL", LOG_LEVEL_INFO); - return false; -#endif -} - -int Socket::IpMulticastTTL() -{ - int ttl = 0; -#ifdef IP_MULTICAST_TTL - socklen_t len = sizeof(ttl); - if (getsockopt(GetSocket(), IPPROTO_IP, IP_MULTICAST_TTL, (char *)&ttl, &len) == -1) - { - Handler().LogError(this, "getsockopt(IPPROTO_IP, IP_MULTICAST_TTL)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - } -#else - Handler().LogError(this, "ip option not available", 0, "IP_MULTICAST_TTL", LOG_LEVEL_INFO); -#endif - return ttl; -} - -bool Socket::SetMulticastLoop(bool x) -{ -#ifdef IP_MULTICAST_LOOP - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), IPPROTO_IP, IP_MULTICAST_LOOP, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_MULTICAST_LOOP)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "ip option not available", 0, "IP_MULTICAST_LOOP", LOG_LEVEL_INFO); - return false; -#endif -} - -#ifdef LINUX -bool Socket::IpAddMembership(struct ip_mreqn& ref) -{ -#ifdef IP_ADD_MEMBERSHIP - if (setsockopt(GetSocket(), IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&ref, sizeof(struct ip_mreqn)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "ip option not available", 0, "IP_ADD_MEMBERSHIP", LOG_LEVEL_INFO); - return false; -#endif -} -#endif - -bool Socket::IpAddMembership(struct ip_mreq& ref) -{ -#ifdef IP_ADD_MEMBERSHIP - if (setsockopt(GetSocket(), IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&ref, sizeof(struct ip_mreq)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "ip option not available", 0, "IP_ADD_MEMBERSHIP", LOG_LEVEL_INFO); - return false; -#endif -} - -#ifdef LINUX -bool Socket::IpDropMembership(struct ip_mreqn& ref) -{ -#ifdef IP_DROP_MEMBERSHIP - if (setsockopt(GetSocket(), IPPROTO_IP, IP_DROP_MEMBERSHIP, (char *)&ref, sizeof(struct ip_mreqn)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_DROP_MEMBERSHIP)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "ip option not available", 0, "IP_DROP_MEMBERSHIP", LOG_LEVEL_INFO); - return false; -#endif -} -#endif - -bool Socket::IpDropMembership(struct ip_mreq& ref) -{ -#ifdef IP_DROP_MEMBERSHIP - if (setsockopt(GetSocket(), IPPROTO_IP, IP_DROP_MEMBERSHIP, (char *)&ref, sizeof(struct ip_mreq)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_DROP_MEMBERSHIP)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "ip option not available", 0, "IP_DROP_MEMBERSHIP", LOG_LEVEL_INFO); - return false; -#endif -} - -/* SOCKET options */ - -bool Socket::SetSoReuseaddr(bool x) -{ -#ifdef SO_REUSEADDR - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), SOL_SOCKET, SO_REUSEADDR, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_REUSEADDR)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "socket option not available", 0, "SO_REUSEADDR", LOG_LEVEL_INFO); - return false; -#endif -} - -bool Socket::SetSoKeepalive(bool x) -{ -#ifdef SO_KEEPALIVE - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), SOL_SOCKET, SO_KEEPALIVE, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_KEEPALIVE)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "socket option not available", 0, "SO_KEEPALIVE", LOG_LEVEL_INFO); - return false; -#endif -} - -#ifdef SO_NOSIGPIPE -bool Socket::SetSoNosigpipe(bool x) -{ - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), SOL_SOCKET, SO_NOSIGPIPE, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_NOSIGPIPE)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -bool Socket::SoAcceptconn() -{ - int value = 0; -#ifdef SO_ACCEPTCONN - socklen_t len = sizeof(value); - if (getsockopt(GetSocket(), SOL_SOCKET, SO_ACCEPTCONN, (char *)&value, &len) == -1) - { - Handler().LogError(this, "getsockopt(SOL_SOCKET, SO_ACCEPTCONN)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - } -#else - Handler().LogError(this, "socket option not available", 0, "SO_ACCEPTCONN", LOG_LEVEL_INFO); -#endif - return value ? true : false; -} - -#ifdef SO_BSDCOMPAT -bool Socket::SetSoBsdcompat(bool x) -{ - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), SOL_SOCKET, SO_BSDCOMPAT, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_BSDCOMPAT)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -#ifdef SO_BINDTODEVICE -bool Socket::SetSoBindtodevice(const std::string& intf) -{ - if (setsockopt(GetSocket(), SOL_SOCKET, SO_BINDTODEVICE, (char *)intf.c_str(), intf.size()) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_BINDTODEVICE)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -bool Socket::SetSoBroadcast(bool x) -{ -#ifdef SO_BROADCAST - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), SOL_SOCKET, SO_BROADCAST, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_BROADCAST)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "socket option not available", 0, "SO_BROADCAST", LOG_LEVEL_INFO); - return false; -#endif -} - -bool Socket::SetSoDebug(bool x) -{ -#ifdef SO_DEBUG - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), SOL_SOCKET, SO_DEBUG, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_DEBUG)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "socket option not available", 0, "SO_DEBUG", LOG_LEVEL_INFO); - return false; -#endif -} - -int Socket::SoError() -{ - int value = 0; -#ifdef SO_ERROR - socklen_t len = sizeof(value); - if (getsockopt(GetSocket(), SOL_SOCKET, SO_ERROR, (char *)&value, &len) == -1) - { - Handler().LogError(this, "getsockopt(SOL_SOCKET, SO_ERROR)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - } -#else - Handler().LogError(this, "socket option not available", 0, "SO_ERROR", LOG_LEVEL_INFO); -#endif - return value; -} - -bool Socket::SetSoDontroute(bool x) -{ -#ifdef SO_DONTROUTE - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), SOL_SOCKET, SO_DONTROUTE, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_DONTROUTE)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "socket option not available", 0, "SO_DONTROUTE", LOG_LEVEL_INFO); - return false; -#endif -} - -bool Socket::SetSoLinger(int onoff, int linger) -{ -#ifdef SO_LINGER - struct linger stl; - stl.l_onoff = onoff; - stl.l_linger = linger; - if (setsockopt(GetSocket(), SOL_SOCKET, SO_LINGER, (char *)&stl, sizeof(stl)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_LINGER)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "socket option not available", 0, "SO_LINGER", LOG_LEVEL_INFO); - return false; -#endif -} - -bool Socket::SetSoOobinline(bool x) -{ -#ifdef SO_OOBINLINE - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), SOL_SOCKET, SO_OOBINLINE, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_OOBINLINE)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "socket option not available", 0, "SO_OOBINLINE", LOG_LEVEL_INFO); - return false; -#endif -} - -#ifdef SO_PASSCRED -bool Socket::SetSoPasscred(bool x) -{ - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), SOL_SOCKET, SO_PASSCRED, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_PASSCRED)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -#ifdef SO_PEERCRED -bool Socket::SoPeercred(struct ucred& ucr) -{ - if (setsockopt(GetSocket(), SOL_SOCKET, SO_PEERCRED, (char *)&ucr, sizeof(ucr)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_PEERCRED)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -#ifdef SO_PRIORITY -bool Socket::SetSoPriority(int x) -{ - if (setsockopt(GetSocket(), SOL_SOCKET, SO_PRIORITY, (char *)&x, sizeof(x)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_PRIORITY)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -bool Socket::SetSoRcvlowat(int x) -{ -#ifdef SO_RCVLOWAT - if (setsockopt(GetSocket(), SOL_SOCKET, SO_RCVLOWAT, (char *)&x, sizeof(x)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_RCVLOWAT)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "socket option not available", 0, "SO_RCVLOWAT", LOG_LEVEL_INFO); - return false; -#endif -} - -bool Socket::SetSoSndlowat(int x) -{ -#ifdef SO_SNDLOWAT - if (setsockopt(GetSocket(), SOL_SOCKET, SO_SNDLOWAT, (char *)&x, sizeof(x)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_SNDLOWAT)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "socket option not available", 0, "SO_SNDLOWAT", LOG_LEVEL_INFO); - return false; -#endif -} - -bool Socket::SetSoRcvtimeo(struct timeval& tv) -{ -#ifdef SO_RCVTIMEO - if (setsockopt(GetSocket(), SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_RCVTIMEO)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "socket option not available", 0, "SO_RCVTIMEO", LOG_LEVEL_INFO); - return false; -#endif -} - -bool Socket::SetSoSndtimeo(struct timeval& tv) -{ -#ifdef SO_SNDTIMEO - if (setsockopt(GetSocket(), SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_SNDTIMEO)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "socket option not available", 0, "SO_SNDTIMEO", LOG_LEVEL_INFO); - return false; -#endif -} - -bool Socket::SetSoRcvbuf(int x) -{ -#ifdef SO_RCVBUF - if (setsockopt(GetSocket(), SOL_SOCKET, SO_RCVBUF, (char *)&x, sizeof(x)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_RCVBUF)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "socket option not available", 0, "SO_RCVBUF", LOG_LEVEL_INFO); - return false; -#endif -} - -int Socket::SoRcvbuf() -{ - int value = 0; -#ifdef SO_RCVBUF - socklen_t len = sizeof(value); - if (getsockopt(GetSocket(), SOL_SOCKET, SO_RCVBUF, (char *)&value, &len) == -1) - { - Handler().LogError(this, "getsockopt(SOL_SOCKET, SO_RCVBUF)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - } -#else - Handler().LogError(this, "socket option not available", 0, "SO_RCVBUF", LOG_LEVEL_INFO); -#endif - return value; -} - -#ifdef SO_RCVBUFFORCE -bool Socket::SetSoRcvbufforce(int x) -{ - if (setsockopt(GetSocket(), SOL_SOCKET, SO_RCVBUFFORCE, (char *)&x, sizeof(x)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_RCVBUFFORCE)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -bool Socket::SetSoSndbuf(int x) -{ -#ifdef SO_SNDBUF - if (setsockopt(GetSocket(), SOL_SOCKET, SO_SNDBUF, (char *)&x, sizeof(x)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_SNDBUF)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "socket option not available", 0, "SO_SNDBUF", LOG_LEVEL_INFO); - return false; -#endif -} - -int Socket::SoSndbuf() -{ - int value = 0; -#ifdef SO_SNDBUF - socklen_t len = sizeof(value); - if (getsockopt(GetSocket(), SOL_SOCKET, SO_SNDBUF, (char *)&value, &len) == -1) - { - Handler().LogError(this, "getsockopt(SOL_SOCKET, SO_SNDBUF)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - } -#else - Handler().LogError(this, "socket option not available", 0, "SO_SNDBUF", LOG_LEVEL_INFO); -#endif - return value; -} - -#ifdef SO_SNDBUFFORCE -bool Socket::SetSoSndbufforce(int x) -{ - if (setsockopt(GetSocket(), SOL_SOCKET, SO_SNDBUFFORCE, (char *)&x, sizeof(x)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_SNDBUFFORCE)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -#ifdef SO_TIMESTAMP -bool Socket::SetSoTimestamp(bool x) -{ - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), SOL_SOCKET, SO_TIMESTAMP, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_TIMESTAMP)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -int Socket::SoType() -{ - int value = 0; -#ifdef SO_TYPE - socklen_t len = sizeof(value); - if (getsockopt(GetSocket(), SOL_SOCKET, SO_TYPE, (char *)&value, &len) == -1) - { - Handler().LogError(this, "getsockopt(SOL_SOCKET, SO_TYPE)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - } -#else - Handler().LogError(this, "socket option not available", 0, "SO_TYPE", LOG_LEVEL_INFO); -#endif - return value; -} - -#ifdef ENABLE_TRIGGERS -void Socket::Subscribe(int id) -{ - Handler().Subscribe(id, this); -} - -void Socket::Unsubscribe(int id) -{ - Handler().Unsubscribe(id, this); -} - -void Socket::OnTrigger(int, const TriggerData&) -{ -} - -void Socket::OnCancelled(int) -{ -} -#endif - -void Socket::SetTimeout(time_t secs) -{ - if (!secs) - { - Handler().AddList(m_socket, LIST_TIMEOUT, false); - return; - } - Handler().AddList(m_socket, LIST_TIMEOUT, true); - m_timeout_start = time(NULL); - m_timeout_limit = secs; -} - -void Socket::OnTimeout() -{ -} - -void Socket::OnConnectTimeout() -{ -} - -bool Socket::Timeout(time_t tnow) -{ - if (tnow - m_timeout_start > m_timeout_limit) - return true; - return false; -} - -/** Returns local port number for bound socket file descriptor. */ -port_t Socket::GetSockPort() -{ -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - struct sockaddr_in6 sa; - socklen_t sockaddr_length = sizeof(struct sockaddr_in6); - if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1) - memset(&sa, 0, sizeof(sa)); - return ntohs(sa.sin6_port); - } -#endif -#endif - struct sockaddr_in sa; - socklen_t sockaddr_length = sizeof(struct sockaddr_in); - if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1) - memset(&sa, 0, sizeof(sa)); - return ntohs(sa.sin_port); -} - -/** Returns local ipv4 address for bound socket file descriptor. */ -ipaddr_t Socket::GetSockIP4() -{ -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - return 0; - } -#endif -#endif - struct sockaddr_in sa; - socklen_t sockaddr_length = sizeof(struct sockaddr_in); - if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1) - memset(&sa, 0, sizeof(sa)); - ipaddr_t a; - memcpy(&a, &sa.sin_addr, 4); - return a; -} - -/** Returns local ipv4 address as text for bound socket file descriptor. */ -std::string Socket::GetSockAddress() -{ -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - return ""; - } -#endif -#endif - struct sockaddr_in sa; - socklen_t sockaddr_length = sizeof(struct sockaddr_in); - if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1) - memset(&sa, 0, sizeof(sa)); - Ipv4Address addr( sa ); - return addr.Convert(); -} - -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 -/** Returns local ipv6 address for bound socket file descriptor. */ -struct in6_addr Socket::GetSockIP6() -{ - if (IsIpv6()) - { - struct sockaddr_in6 sa; - socklen_t sockaddr_length = sizeof(struct sockaddr_in6); - if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1) - memset(&sa, 0, sizeof(sa)); - return sa.sin6_addr; - } - struct in6_addr a; - memset(&a, 0, sizeof(a)); - return a; -} - -/** Returns local ipv6 address as text for bound socket file descriptor. */ -std::string Socket::GetSockAddress6() -{ - if (IsIpv6()) - { - struct sockaddr_in6 sa; - socklen_t sockaddr_length = sizeof(struct sockaddr_in6); - if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1) - memset(&sa, 0, sizeof(sa)); - Ipv6Address addr( sa ); - return addr.Convert(); - } - return ""; -} -#endif -#endif - -#ifdef SOCKETS_NAMESPACE -} -#endif - - diff --git a/externals/sockets/SocketHandler.cpp b/externals/sockets/SocketHandler.cpp deleted file mode 100644 index acf71fb2efa..00000000000 --- a/externals/sockets/SocketHandler.cpp +++ /dev/null @@ -1,1377 +0,0 @@ -/** \file SocketHandler.cpp - ** \date 2004-02-13 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifdef _WIN32 -#ifdef _MSC_VER -#pragma warning(disable:4786) -#endif -#endif -#include -#include -#include -#include - -#include "SocketHandler.h" -#include "UdpSocket.h" -#include "ResolvSocket.h" -#include "ResolvServer.h" -#include "TcpSocket.h" -#include "Mutex.h" -#include "Utility.h" -#include "SocketAddress.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -//#ifdef _DEBUG -//#define DEB(x) x; fflush(stderr); -//#else -#define DEB(x) -//#endif - -SocketHandler::SocketHandler(StdLog *p) -:m_stdlog(p) -,m_mutex(m_mutex) -,m_b_use_mutex(false) -,m_maxsock(0) -,m_preverror(-1) -,m_errcnt(0) -,m_tlast(0) -#ifdef ENABLE_SOCKS4 -,m_socks4_host(0) -,m_socks4_port(0) -,m_bTryDirect(false) -#endif -#ifdef ENABLE_RESOLVER -,m_resolv_id(0) -,m_resolver(NULL) -#endif -#ifdef ENABLE_POOL -,m_b_enable_pool(false) -#endif -#ifdef ENABLE_TRIGGERS -,m_next_trigger_id(0) -#endif -#ifdef ENABLE_DETACH -,m_slave(false) -#endif -{ - FD_ZERO(&m_rfds); - FD_ZERO(&m_wfds); - FD_ZERO(&m_efds); -} - -SocketHandler::SocketHandler(Mutex& mutex,StdLog *p) -:m_stdlog(p) -,m_mutex(mutex) -,m_b_use_mutex(true) -,m_maxsock(0) -,m_preverror(-1) -,m_errcnt(0) -,m_tlast(0) -#ifdef ENABLE_SOCKS4 -,m_socks4_host(0) -,m_socks4_port(0) -,m_bTryDirect(false) -#endif -#ifdef ENABLE_RESOLVER -,m_resolv_id(0) -,m_resolver(NULL) -#endif -#ifdef ENABLE_POOL -,m_b_enable_pool(false) -#endif -#ifdef ENABLE_TRIGGERS -,m_next_trigger_id(0) -#endif -#ifdef ENABLE_DETACH -,m_slave(false) -#endif -{ - m_mutex.Lock(); - FD_ZERO(&m_rfds); - FD_ZERO(&m_wfds); - FD_ZERO(&m_efds); -} - -SocketHandler::~SocketHandler() -{ -#ifdef ENABLE_RESOLVER - if (m_resolver) - { - m_resolver -> Quit(); - } -#endif - { - while (m_sockets.size()) - { -DEB( fprintf(stderr, "Emptying sockets list in SocketHandler destructor, %d instances\n", (int)m_sockets.size());) - socket_m::iterator it = m_sockets.begin(); - Socket *p = it -> second; - if (p) - { -DEB( fprintf(stderr, " fd %d\n", p -> GetSocket());) - p -> Close(); -DEB( fprintf(stderr, " fd closed %d\n", p -> GetSocket());) -// p -> OnDelete(); // hey, I turn this back on. what's the worst that could happen??!! - // MinionSocket breaks, calling MinderHandler methods in OnDelete - - // MinderHandler is already gone when that happens... - - // only delete socket when controlled - // ie master sockethandler can delete non-detached sockets - // and a slave sockethandler can only delete a detach socket - if (p -> DeleteByHandler() -#ifdef ENABLE_DETACH - && !(m_slave ^ p -> IsDetached()) -#endif - ) - { - p -> SetErasedByHandler(); - delete p; - } - m_sockets.erase(it); - } - else - { - m_sockets.erase(it); - } -DEB( fprintf(stderr, "next\n");) - } -DEB( fprintf(stderr, "/Emptying sockets list in SocketHandler destructor, %d instances\n", (int)m_sockets.size());) - } -#ifdef ENABLE_RESOLVER - if (m_resolver) - { - delete m_resolver; - } -#endif - if (m_b_use_mutex) - { - m_mutex.Unlock(); - } -} - -Mutex& SocketHandler::GetMutex() const -{ - return m_mutex; -} - -#ifdef ENABLE_DETACH -void SocketHandler::SetSlave(bool x) -{ - m_slave = x; -} - -bool SocketHandler::IsSlave() -{ - return m_slave; -} -#endif - -void SocketHandler::RegStdLog(StdLog *log) -{ - m_stdlog = log; -} - -void SocketHandler::LogError(Socket *p,const std::string& user_text,int err,const std::string& sys_err,loglevel_t t) -{ - if (m_stdlog) - { - m_stdlog -> error(this, p, user_text, err, sys_err, t); - } -} - -void SocketHandler::Add(Socket *p) -{ - if (p -> GetSocket() == INVALID_SOCKET) - { - LogError(p, "Add", -1, "Invalid socket", LOG_LEVEL_WARNING); - if (p -> CloseAndDelete()) - { - m_delete.push_back(p); - } - return; - } - if (m_add.find(p -> GetSocket()) != m_add.end()) - { - LogError(p, "Add", (int)p -> GetSocket(), "Attempt to add socket already in add queue", LOG_LEVEL_FATAL); - m_delete.push_back(p); - return; - } - m_add[p -> GetSocket()] = p; -} - -void SocketHandler::Get(SOCKET s,bool& r,bool& w,bool& e) -{ - if (s >= 0) - { - r = FD_ISSET(s, &m_rfds) ? true : false; - w = FD_ISSET(s, &m_wfds) ? true : false; - e = FD_ISSET(s, &m_efds) ? true : false; - } -} - -void SocketHandler::Set(SOCKET s,bool bRead,bool bWrite,bool bException) -{ -DEB( fprintf(stderr, "Set(%d, %s, %s, %s)\n", s, bRead ? "true" : "false", bWrite ? "true" : "false", bException ? "true" : "false");) - if (s >= 0) - { - if (bRead) - { - if (!FD_ISSET(s, &m_rfds)) - { - FD_SET(s, &m_rfds); - } - } - else - { - FD_CLR(s, &m_rfds); - } - if (bWrite) - { - if (!FD_ISSET(s, &m_wfds)) - { - FD_SET(s, &m_wfds); - } - } - else - { - FD_CLR(s, &m_wfds); - } - if (bException) - { - if (!FD_ISSET(s, &m_efds)) - { - FD_SET(s, &m_efds); - } - } - else - { - FD_CLR(s, &m_efds); - } - } -} - -int SocketHandler::Select(long sec,long usec) -{ - struct timeval tv; - tv.tv_sec = sec; - tv.tv_usec = usec; - return Select(&tv); -} - -int SocketHandler::Select() -{ - if (!m_fds_callonconnect.empty() || -#ifdef ENABLE_DETACH - (!m_slave && !m_fds_detach.empty()) || -#endif - !m_fds_timeout.empty() || - !m_fds_retry.empty() || - !m_fds_close.empty() || - !m_fds_erase.empty()) - { - return Select(0, 200000); - } - return Select(NULL); -} - -int SocketHandler::Select(struct timeval *tsel) -{ - size_t ignore = 0; - while (m_add.size() > ignore) - { - if (m_sockets.size() >= FD_SETSIZE) - { - LogError(NULL, "Select", (int)m_sockets.size(), "FD_SETSIZE reached", LOG_LEVEL_WARNING); - break; - } - socket_m::iterator it = m_add.begin(); - SOCKET s = it -> first; - Socket *p = it -> second; -DEB( fprintf(stderr, "Trying to add fd %d, m_add.size() %d, ignore %d\n", (int)s, (int)m_add.size(), (int)ignore);) - // - if (m_sockets.find(p -> GetSocket()) != m_sockets.end()) - { - LogError(p, "Add", (int)p -> GetSocket(), "Attempt to add socket already in controlled queue", LOG_LEVEL_FATAL); - // %! it's a dup, don't add to delete queue, just ignore it - m_delete.push_back(p); - m_add.erase(it); -// ignore++; - continue; - } - if (!p -> CloseAndDelete()) - { - StreamSocket *scp = dynamic_cast(p); - if (scp && scp -> Connecting()) // 'Open' called before adding socket - { - Set(s,false,true); - } - else - { - TcpSocket *tcp = dynamic_cast(p); - bool bWrite = tcp ? tcp -> GetOutputLength() != 0 : false; - if (p -> IsDisableRead()) - { - Set(s, false, bWrite); - } - else - { - Set(s, true, bWrite); - } - } - m_maxsock = (s > m_maxsock) ? s : m_maxsock; - } - else - { - LogError(p, "Add", (int)p -> GetSocket(), "Trying to add socket with SetCloseAndDelete() true", LOG_LEVEL_WARNING); - } - // only add to m_fds (process fd_set events) if - // slave handler and detached/detaching socket - // master handler and non-detached socket -#ifdef ENABLE_DETACH - if (!(m_slave ^ p -> IsDetach())) -#endif - { - m_fds.push_back(s); - } - m_sockets[s] = p; - // - m_add.erase(it); - } -#ifdef MACOSX - fd_set rfds; - fd_set wfds; - fd_set efds; - FD_COPY(&m_rfds, &rfds); - FD_COPY(&m_wfds, &wfds); - FD_COPY(&m_efds, &efds); -#else - fd_set rfds = m_rfds; - fd_set wfds = m_wfds; - fd_set efds = m_efds; -#endif - int n; - if (m_b_use_mutex) - { - m_mutex.Unlock(); - n = select( (int)(m_maxsock + 1),&rfds,&wfds,&efds,tsel); - m_mutex.Lock(); - } - else - { - n = select( (int)(m_maxsock + 1),&rfds,&wfds,&efds,tsel); - } - if (n == -1) - { - /* - EBADF An invalid file descriptor was given in one of the sets. - EINTR A non blocked signal was caught. - EINVAL n is negative. Or struct timeval contains bad time values (<0). - ENOMEM select was unable to allocate memory for internal tables. - */ - if (Errno != m_preverror || m_errcnt++ % 10000 == 0) - { - LogError(NULL, "select", Errno, StrError(Errno)); -DEB( fprintf(stderr, "m_maxsock: %d\n", m_maxsock); - fprintf(stderr, "%s\n", Errno == EINVAL ? "EINVAL" : - Errno == EINTR ? "EINTR" : - Errno == EBADF ? "EBADF" : - Errno == ENOMEM ? "ENOMEM" : ""); - // test bad fd - for (SOCKET i = 0; i <= m_maxsock; i++) - { - bool t = false; - FD_ZERO(&rfds); - FD_ZERO(&wfds); - FD_ZERO(&efds); - if (FD_ISSET(i, &m_rfds)) - { - FD_SET(i, &rfds); - t = true; - } - if (FD_ISSET(i, &m_wfds)) - { - FD_SET(i, &wfds); - t = true; - } - if (FD_ISSET(i, &m_efds)) - { - FD_SET(i, &efds); - t = true; - } - if (t && m_sockets.find(i) == m_sockets.end()) - { - fprintf(stderr, "Bad fd in fd_set: %d\n", i); - } - } -) // DEB - m_preverror = Errno; - } - /// \todo rebuild fd_set's from active sockets list (m_sockets) here - } - else - if (!n) - { - m_preverror = -1; - } - else - if (n > 0) - { - for (socket_v::iterator it2 = m_fds.begin(); it2 != m_fds.end() && n; it2++) - { - SOCKET i = *it2; - if (FD_ISSET(i, &rfds)) - { - socket_m::iterator itmp = m_sockets.find(i); - if (itmp != m_sockets.end()) // found - { - Socket *p = itmp -> second; - // new SSL negotiate method -#ifdef HAVE_OPENSSL - if (p -> IsSSLNegotiate()) - { - p -> SSLNegotiate(); - } - else -#endif - { - p -> OnRead(); - } - } - else - { - LogError(NULL, "GetSocket/handler/1", (int)i, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING); - } - n--; - } - if (FD_ISSET(i, &wfds)) - { - socket_m::iterator itmp = m_sockets.find(i); - if (itmp != m_sockets.end()) // found - { - Socket *p = itmp -> second; - // new SSL negotiate method -#ifdef HAVE_OPENSSL - if (p -> IsSSLNegotiate()) - { - p -> SSLNegotiate(); - } - else -#endif - { - p -> OnWrite(); - } - } - else - { - LogError(NULL, "GetSocket/handler/2", (int)i, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING); - } - n--; - } - if (FD_ISSET(i, &efds)) - { - socket_m::iterator itmp = m_sockets.find(i); - if (itmp != m_sockets.end()) // found - { - Socket *p = itmp -> second; - p -> OnException(); - } - else - { - LogError(NULL, "GetSocket/handler/3", (int)i, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING); - } - n--; - } - } // m_fds loop - m_preverror = -1; - } // if (n > 0) - - // check CallOnConnect - EVENT - if (!m_fds_callonconnect.empty()) - { - socket_v tmp = m_fds_callonconnect; - for (socket_v::iterator it = tmp.begin(); it != tmp.end(); it++) - { - Socket *p = NULL; - { - socket_m::iterator itmp = m_sockets.find(*it); - if (itmp != m_sockets.end()) // found - { - p = itmp -> second; - } - else - { - LogError(NULL, "GetSocket/handler/4", (int)*it, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING); - } - } - if (p) - { -// if (p -> CallOnConnect() && p -> Ready() ) - { - p -> SetConnected(); // moved here from inside if (tcp) check below -#ifdef HAVE_OPENSSL - if (p -> IsSSL()) // SSL Enabled socket - p -> OnSSLConnect(); - else -#endif -#ifdef ENABLE_SOCKS4 - if (p -> Socks4()) - p -> OnSocks4Connect(); - else -#endif - { - TcpSocket *tcp = dynamic_cast(p); - if (tcp) - { - if (tcp -> GetOutputLength()) - { - p -> OnWrite(); - } - } -#ifdef ENABLE_RECONNECT - if (tcp && tcp -> IsReconnect()) - p -> OnReconnect(); - else -#endif - { -// LogError(p, "Calling OnConnect", 0, "Because CallOnConnect", LOG_LEVEL_INFO); - p -> OnConnect(); - } - } -// p -> SetCallOnConnect( false ); - AddList(p -> GetSocket(), LIST_CALLONCONNECT, false); - } - } - } - } -#ifdef ENABLE_DETACH - // check detach of socket if master handler - EVENT - if (!m_slave && !m_fds_detach.empty()) - { - // %! why not using tmp list here??!? - for (socket_v::iterator it = m_fds_detach.begin(); it != m_fds_detach.end(); it++) - { - Socket *p = NULL; - { - socket_m::iterator itmp = m_sockets.find(*it); - if (itmp != m_sockets.end()) // found - { - p = itmp -> second; - } - else - { - LogError(NULL, "GetSocket/handler/5", (int)*it, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING); - } - } - if (p) - { -// if (p -> IsDetach()) - { - Set(p -> GetSocket(), false, false, false); - // After DetachSocket(), all calls to Handler() will return a reference - // to the new slave SocketHandler running in the new thread. - p -> DetachSocket(); - // Adding the file descriptor to m_fds_erase will now also remove the - // socket from the detach queue - tnx knightmad - m_fds_erase.push_back(p -> GetSocket()); - } - } - } - } -#endif - // check Connecting - connection timeout - conditional event - if (m_fds_timeout.size()) - { - time_t tnow = time(NULL); - if (tnow != m_tlast) - { - socket_v tmp = m_fds_timeout; -DEB( fprintf(stderr, "Checking %d socket(s) for timeout\n", tmp.size());) - for (socket_v::iterator it = tmp.begin(); it != tmp.end(); it++) - { - Socket *p = NULL; - { - socket_m::iterator itmp = m_sockets.find(*it); - if (itmp != m_sockets.end()) // found - { - p = itmp -> second; - } - else - { - itmp = m_add.find(*it); - if (itmp != m_add.end()) - { - p = itmp -> second; - } - else - { - LogError(NULL, "GetSocket/handler/6", (int)*it, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING); - } - } - } - if (p) - { - if (p -> Timeout(tnow)) - { - StreamSocket *scp = dynamic_cast(p); - if (scp && scp -> Connecting()) - p -> OnConnectTimeout(); - else - p -> OnTimeout(); - p -> SetTimeout(0); - } - } - } - m_tlast = tnow; - } // tnow != tlast - } - // check retry client connect - EVENT - if (!m_fds_retry.empty()) - { - socket_v tmp = m_fds_retry; - for (socket_v::iterator it = tmp.begin(); it != tmp.end(); it++) - { - Socket *p = NULL; - { - socket_m::iterator itmp = m_sockets.find(*it); - if (itmp != m_sockets.end()) // found - { - p = itmp -> second; - } - else - { - LogError(NULL, "GetSocket/handler/7", (int)*it, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING); - } - } - if (p) - { -// if (p -> RetryClientConnect()) - { - TcpSocket *tcp = dynamic_cast(p); - SOCKET nn = *it; //(*it3).first; - tcp -> SetRetryClientConnect(false); -DEB( fprintf(stderr, "Close() before retry client connect\n");) - p -> Close(); // removes from m_fds_retry - std::auto_ptr ad = p -> GetClientRemoteAddress(); - if (ad.get()) - { - tcp -> Open(*ad); - } - else - { - LogError(p, "RetryClientConnect", 0, "no address", LOG_LEVEL_ERROR); - } - Add(p); - m_fds_erase.push_back(nn); - } - } - } - } - // check close and delete - conditional event - if (!m_fds_close.empty()) - { - socket_v tmp = m_fds_close; -DEB( fprintf(stderr, "m_fds_close.size() == %d\n", (int)m_fds_close.size());) - for (socket_v::iterator it = tmp.begin(); it != tmp.end(); it++) - { - Socket *p = NULL; - { - socket_m::iterator itmp = m_sockets.find(*it); - if (itmp != m_sockets.end()) // found - { - p = itmp -> second; - } - else - { - itmp = m_add.find(*it); - if (itmp != m_add.end()) - { - p = itmp -> second; - } - else - { - LogError(NULL, "GetSocket/handler/8", (int)*it, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING); - } - } - } - if (p) - { -// if (p -> CloseAndDelete() ) - { - TcpSocket *tcp = dynamic_cast(p); - // new graceful tcp - flush and close timeout 5s - if (tcp && p -> IsConnected() && tcp -> GetFlushBeforeClose() && -#ifdef HAVE_OPENSSL - !tcp -> IsSSL() && -#endif - p -> TimeSinceClose() < 5) - { -DEB( fprintf(stderr, " close(1)\n");) - if (tcp -> GetOutputLength()) - { - LogError(p, "Closing", (int)tcp -> GetOutputLength(), "Sending all data before closing", LOG_LEVEL_INFO); - } - else // shutdown write when output buffer is empty - if (!(tcp -> GetShutdown() & SHUT_WR)) - { - SOCKET nn = *it; - if (nn != INVALID_SOCKET && shutdown(nn, SHUT_WR) == -1) - { - LogError(p, "graceful shutdown", Errno, StrError(Errno), LOG_LEVEL_ERROR); - } - tcp -> SetShutdown(SHUT_WR); - } - } - else -#ifdef ENABLE_RECONNECT - if (tcp && p -> IsConnected() && tcp -> Reconnect()) - { - SOCKET nn = *it; //(*it3).first; -DEB( fprintf(stderr, " close(2) fd %d\n", nn);) - p -> SetCloseAndDelete(false); - tcp -> SetIsReconnect(); - p -> SetConnected(false); -DEB( fprintf(stderr, "Close() before reconnect\n");) - p -> Close(); // dispose of old file descriptor (Open creates a new) - p -> OnDisconnect(); - std::auto_ptr ad = p -> GetClientRemoteAddress(); - if (ad.get()) - { - tcp -> Open(*ad); - } - else - { - LogError(p, "Reconnect", 0, "no address", LOG_LEVEL_ERROR); - } - tcp -> ResetConnectionRetries(); - Add(p); - m_fds_erase.push_back(nn); - } - else -#endif - { - SOCKET nn = *it; //(*it3).first; -DEB( fprintf(stderr, " close(3) fd %d GetSocket() %d\n", nn, p -> GetSocket());) - if (tcp && p -> IsConnected() && tcp -> GetOutputLength()) - { - LogError(p, "Closing", (int)tcp -> GetOutputLength(), "Closing socket while data still left to send", LOG_LEVEL_WARNING); - } -#ifdef ENABLE_POOL - if (p -> Retain() && !p -> Lost()) - { - PoolSocket *p2 = new PoolSocket(*this, p); - p2 -> SetDeleteByHandler(); - Add(p2); - // - p -> SetCloseAndDelete(false); // added - remove from m_fds_close - } - else -#endif // ENABLE_POOL - { - Set(p -> GetSocket(),false,false,false); -DEB( fprintf(stderr, "Close() before OnDelete\n");) - p -> Close(); - } - p -> OnDelete(); - if (p -> DeleteByHandler()) - { - p -> SetErasedByHandler(); - } - m_fds_erase.push_back(nn); - } - } - } - } - } - - // check erased sockets - bool check_max_fd = false; - while (!m_fds_erase.empty()) - { - socket_v::iterator it = m_fds_erase.begin(); - SOCKET nn = *it; -#ifdef ENABLE_DETACH - { - for (socket_v::iterator it = m_fds_detach.begin(); it != m_fds_detach.end(); it++) - { - if (*it == nn) - { - m_fds_detach.erase(it); - break; - } - } - } -#endif - { - for (socket_v::iterator it = m_fds.begin(); it != m_fds.end(); it++) - { - if (*it == nn) - { - m_fds.erase(it); - break; - } - } - } - { - socket_m::iterator it = m_sockets.find(nn); - if (it != m_sockets.end()) - { - Socket *p = it -> second; - /* Sometimes a SocketThread class can finish its run before the master - sockethandler gets here. In that case, the SocketThread has set the - 'ErasedByHandler' flag on the socket which will make us end up with a - double delete on the socket instance. - The fix is to make sure that the master sockethandler only can delete - non-detached sockets, and a slave sockethandler only can delete - detach sockets. */ - if (p -> ErasedByHandler() -#ifdef ENABLE_DETACH - && !(m_slave ^ p -> IsDetached()) -#endif - ) - { -#ifdef ENABLE_TRIGGERS - bool again = false; - do - { - again = false; - for (std::map::iterator it = m_trigger_src.begin(); it != m_trigger_src.end(); it++) - { - int id = it -> first; - Socket *src = it -> second; - if (src == p) - { - for (std::map::iterator it = m_trigger_dst[id].begin(); it != m_trigger_dst[id].end(); it++) - { - Socket *dst = it -> first; - if (Valid(dst)) - { - dst -> OnCancelled(id); - } - } - m_trigger_src.erase(m_trigger_src.find(id)); - m_trigger_dst.erase(m_trigger_dst.find(id)); - again = true; - break; - } - } - } while (again); -#endif - delete p; - } - m_sockets.erase(it); - } - } - m_fds_erase.erase(it); - check_max_fd = true; - } - // calculate max file descriptor for select() call - if (check_max_fd) - { - m_maxsock = 0; - for (socket_v::iterator it = m_fds.begin(); it != m_fds.end(); it++) - { - SOCKET s = *it; - m_maxsock = s > m_maxsock ? s : m_maxsock; - } - } - // remove Add's that fizzed - while (!m_delete.empty()) - { - std::list::iterator it = m_delete.begin(); - Socket *p = *it; - p -> OnDelete(); - m_delete.erase(it); - if (p -> DeleteByHandler() -#ifdef ENABLE_DETACH - && !(m_slave ^ p -> IsDetached()) -#endif - ) - { - p -> SetErasedByHandler(); -#ifdef ENABLE_TRIGGERS - bool again = false; - do - { - again = false; - for (std::map::iterator it = m_trigger_src.begin(); it != m_trigger_src.end(); it++) - { - int id = it -> first; - Socket *src = it -> second; - if (src == p) - { - for (std::map::iterator it = m_trigger_dst[id].begin(); it != m_trigger_dst[id].end(); it++) - { - Socket *dst = it -> first; - if (Valid(dst)) - { - dst -> OnCancelled(id); - } - } - m_trigger_src.erase(m_trigger_src.find(id)); - m_trigger_dst.erase(m_trigger_dst.find(id)); - again = true; - break; - } - } - } while (again); -#endif - delete p; - } - } - return n; -} - -#ifdef ENABLE_RESOLVER -bool SocketHandler::Resolving(Socket *p0) -{ - std::map::iterator it = m_resolve_q.find(p0); - return it != m_resolve_q.end(); -} -#endif - -bool SocketHandler::Valid(Socket *p0) -{ - for (socket_m::iterator it = m_sockets.begin(); it != m_sockets.end(); it++) - { - Socket *p = it -> second; - if (p0 == p) - return true; - } - return false; -} - -bool SocketHandler::OkToAccept(Socket *) -{ - return true; -} - -size_t SocketHandler::GetCount() -{ -/* -printf(" m_sockets : %d\n", m_sockets.size()); -printf(" m_add : %d\n", m_add.size()); -printf(" m_delete : %d\n", m_delete.size()); -*/ - return m_sockets.size() + m_add.size() + m_delete.size(); -} - -#ifdef ENABLE_SOCKS4 -void SocketHandler::SetSocks4Host(ipaddr_t a) -{ - m_socks4_host = a; -} - -void SocketHandler::SetSocks4Host(const std::string& host) -{ - Utility::u2ip(host, m_socks4_host); -} - -void SocketHandler::SetSocks4Port(port_t port) -{ - m_socks4_port = port; -} - -void SocketHandler::SetSocks4Userid(const std::string& id) -{ - m_socks4_userid = id; -} -#endif - -#ifdef ENABLE_RESOLVER -int SocketHandler::Resolve(Socket *p,const std::string& host,port_t port) -{ - // check cache - ResolvSocket *resolv = new ResolvSocket(*this, p, host, port); - resolv -> SetId(++m_resolv_id); - resolv -> SetDeleteByHandler(); - ipaddr_t local; - Utility::u2ip("127.0.0.1", local); - if (!resolv -> Open(local, m_resolver_port)) - { - LogError(resolv, "Resolve", -1, "Can't connect to local resolve server", LOG_LEVEL_FATAL); - } - Add(resolv); - m_resolve_q[p] = true; -DEB( fprintf(stderr, " *** Resolve '%s:%d' id#%d m_resolve_q size: %d p: %p\n", host.c_str(), port, resolv -> GetId(), m_resolve_q.size(), p);) - return resolv -> GetId(); -} - -#ifdef ENABLE_IPV6 -int SocketHandler::Resolve6(Socket *p,const std::string& host,port_t port) -{ - // check cache - ResolvSocket *resolv = new ResolvSocket(*this, p, host, port, true); - resolv -> SetId(++m_resolv_id); - resolv -> SetDeleteByHandler(); - ipaddr_t local; - Utility::u2ip("127.0.0.1", local); - if (!resolv -> Open(local, m_resolver_port)) - { - LogError(resolv, "Resolve", -1, "Can't connect to local resolve server", LOG_LEVEL_FATAL); - } - Add(resolv); - m_resolve_q[p] = true; - return resolv -> GetId(); -} -#endif - -int SocketHandler::Resolve(Socket *p,ipaddr_t a) -{ - // check cache - ResolvSocket *resolv = new ResolvSocket(*this, p, a); - resolv -> SetId(++m_resolv_id); - resolv -> SetDeleteByHandler(); - ipaddr_t local; - Utility::u2ip("127.0.0.1", local); - if (!resolv -> Open(local, m_resolver_port)) - { - LogError(resolv, "Resolve", -1, "Can't connect to local resolve server", LOG_LEVEL_FATAL); - } - Add(resolv); - m_resolve_q[p] = true; - return resolv -> GetId(); -} - -#ifdef ENABLE_IPV6 -int SocketHandler::Resolve(Socket *p,in6_addr& a) -{ - // check cache - ResolvSocket *resolv = new ResolvSocket(*this, p, a); - resolv -> SetId(++m_resolv_id); - resolv -> SetDeleteByHandler(); - ipaddr_t local; - Utility::u2ip("127.0.0.1", local); - if (!resolv -> Open(local, m_resolver_port)) - { - LogError(resolv, "Resolve", -1, "Can't connect to local resolve server", LOG_LEVEL_FATAL); - } - Add(resolv); - m_resolve_q[p] = true; - return resolv -> GetId(); -} -#endif - -void SocketHandler::EnableResolver(port_t port) -{ - if (!m_resolver) - { - m_resolver_port = port; - m_resolver = new ResolvServer(port); - } -} - -bool SocketHandler::ResolverReady() -{ - return m_resolver ? m_resolver -> Ready() : false; -} -#endif // ENABLE_RESOLVER - -#ifdef ENABLE_SOCKS4 -void SocketHandler::SetSocks4TryDirect(bool x) -{ - m_bTryDirect = x; -} - -ipaddr_t SocketHandler::GetSocks4Host() -{ - return m_socks4_host; -} - -port_t SocketHandler::GetSocks4Port() -{ - return m_socks4_port; -} - -const std::string& SocketHandler::GetSocks4Userid() -{ - return m_socks4_userid; -} - -bool SocketHandler::Socks4TryDirect() -{ - return m_bTryDirect; -} -#endif - -#ifdef ENABLE_RESOLVER -bool SocketHandler::ResolverEnabled() -{ - return m_resolver ? true : false; -} - -port_t SocketHandler::GetResolverPort() -{ - return m_resolver_port; -} -#endif // ENABLE_RESOLVER - -#ifdef ENABLE_POOL -ISocketHandler::PoolSocket *SocketHandler::FindConnection(int type,const std::string& protocol,SocketAddress& ad) -{ - for (socket_m::iterator it = m_sockets.begin(); it != m_sockets.end() && !m_sockets.empty(); it++) - { - PoolSocket *pools = dynamic_cast(it -> second); - if (pools) - { - if (pools -> GetSocketType() == type && - pools -> GetSocketProtocol() == protocol && -// %! pools -> GetClientRemoteAddress() && - *pools -> GetClientRemoteAddress() == ad) - { - m_sockets.erase(it); - pools -> SetRetain(); // avoid Close in Socket destructor - return pools; // Caller is responsible that this socket is deleted - } - } - } - return NULL; -} - -void SocketHandler::EnablePool(bool x) -{ - m_b_enable_pool = x; -} - -bool SocketHandler::PoolEnabled() -{ - return m_b_enable_pool; -} -#endif - -void SocketHandler::Remove(Socket *p) -{ -#ifdef ENABLE_RESOLVER - std::map::iterator it4 = m_resolve_q.find(p); - if (it4 != m_resolve_q.end()) - m_resolve_q.erase(it4); -#endif - if (p -> ErasedByHandler()) - { - return; - } - for (socket_m::iterator it = m_sockets.begin(); it != m_sockets.end(); it++) - { - if (it -> second == p) - { - LogError(p, "Remove", -1, "Socket destructor called while still in use", LOG_LEVEL_WARNING); - m_sockets.erase(it); - return; - } - } - for (socket_m::iterator it2 = m_add.begin(); it2 != m_add.end(); it2++) - { - if ((*it2).second == p) - { - LogError(p, "Remove", -2, "Socket destructor called while still in use", LOG_LEVEL_WARNING); - m_add.erase(it2); - return; - } - } - for (std::list::iterator it3 = m_delete.begin(); it3 != m_delete.end(); it3++) - { - if (*it3 == p) - { - LogError(p, "Remove", -3, "Socket destructor called while still in use", LOG_LEVEL_WARNING); - m_delete.erase(it3); - return; - } - } -} - -void SocketHandler::CheckSanity() -{ - CheckList(m_fds, "active sockets"); // active sockets - CheckList(m_fds_erase, "sockets to be erased"); // should always be empty anyway - CheckList(m_fds_callonconnect, "checklist CallOnConnect"); -#ifdef ENABLE_DETACH - CheckList(m_fds_detach, "checklist Detach"); -#endif - CheckList(m_fds_timeout, "checklist Timeout"); - CheckList(m_fds_retry, "checklist retry client connect"); - CheckList(m_fds_close, "checklist close and delete"); -} - -void SocketHandler::CheckList(socket_v& ref,const std::string& listname) -{ - for (socket_v::iterator it = ref.begin(); it != ref.end(); it++) - { - SOCKET s = *it; - if (m_sockets.find(s) != m_sockets.end()) - continue; - if (m_add.find(s) != m_add.end()) - continue; - bool found = false; - for (std::list::iterator it = m_delete.begin(); it != m_delete.end(); it++) - { - Socket *p = *it; - if (p -> GetSocket() == s) - { - found = true; - break; - } - } - if (!found) - { - fprintf(stderr, "CheckList failed for \"%s\": fd %d\n", listname.c_str(), s); - } - } -} - -void SocketHandler::AddList(SOCKET s,list_t which_one,bool add) -{ - if (s == INVALID_SOCKET) - { -DEB( fprintf(stderr, "AddList: invalid_socket\n");) - return; - } - socket_v& ref = - (which_one == LIST_CALLONCONNECT) ? m_fds_callonconnect : -#ifdef ENABLE_DETACH - (which_one == LIST_DETACH) ? m_fds_detach : -#endif - (which_one == LIST_TIMEOUT) ? m_fds_timeout : - (which_one == LIST_RETRY) ? m_fds_retry : - (which_one == LIST_CLOSE) ? m_fds_close : m_fds_close; - if (add) - { -#ifdef ENABLE_DETACH -DEB( fprintf(stderr, "AddList; %5d: %s: %s\n", s, (which_one == LIST_CALLONCONNECT) ? "CallOnConnect" : - (which_one == LIST_DETACH) ? "Detach" : - (which_one == LIST_TIMEOUT) ? "Timeout" : - (which_one == LIST_RETRY) ? "Retry" : - (which_one == LIST_CLOSE) ? "Close" : "", - add ? "Add" : "Remove");) -#else -DEB( fprintf(stderr, "AddList; %5d: %s: %s\n", s, (which_one == LIST_CALLONCONNECT) ? "CallOnConnect" : - (which_one == LIST_TIMEOUT) ? "Timeout" : - (which_one == LIST_RETRY) ? "Retry" : - (which_one == LIST_CLOSE) ? "Close" : "", - add ? "Add" : "Remove");) -#endif - } - if (add) - { - for (socket_v::iterator it = ref.begin(); it != ref.end(); it++) - { - if (*it == s) // already there - { - return; - } - } - ref.push_back(s); - return; - } - // remove - for (socket_v::iterator it = ref.begin(); it != ref.end(); it++) - { - if (*it == s) - { - ref.erase(it); - break; - } - } -//DEB( fprintf(stderr, "/AddList\n");) -} - -#ifdef ENABLE_TRIGGERS -int SocketHandler::TriggerID(Socket *src) -{ - int id = m_next_trigger_id++; - m_trigger_src[id] = src; - return id; -} - -bool SocketHandler::Subscribe(int id, Socket *dst) -{ - if (m_trigger_src.find(id) != m_trigger_src.end()) - { - std::map::iterator it = m_trigger_dst[id].find(dst); - if (it != m_trigger_dst[id].end()) - { - m_trigger_dst[id][dst] = true; - return true; - } - LogError(dst, "Subscribe", id, "Already subscribed", LOG_LEVEL_INFO); - return false; - } - LogError(dst, "Subscribe", id, "Trigger id not found", LOG_LEVEL_INFO); - return false; -} - -bool SocketHandler::Unsubscribe(int id, Socket *dst) -{ - if (m_trigger_src.find(id) != m_trigger_src.end()) - { - std::map::iterator it = m_trigger_dst[id].find(dst); - if (it != m_trigger_dst[id].end()) - { - m_trigger_dst[id].erase(it); - return true; - } - LogError(dst, "Unsubscribe", id, "Not subscribed", LOG_LEVEL_INFO); - return false; - } - LogError(dst, "Unsubscribe", id, "Trigger id not found", LOG_LEVEL_INFO); - return false; -} - -void SocketHandler::Trigger(int id, Socket::TriggerData& data, bool erase) -{ - if (m_trigger_src.find(id) != m_trigger_src.end()) - { - data.SetSource( m_trigger_src[id] ); - for (std::map::iterator it = m_trigger_dst[id].begin(); it != m_trigger_dst[id].end(); it++) - { - Socket *dst = it -> first; - if (Valid(dst)) - { - dst -> OnTrigger(id, data); - } - } - if (erase) - { - m_trigger_src.erase(m_trigger_src.find(id)); - m_trigger_dst.erase(m_trigger_dst.find(id)); - } - } - else - { - LogError(NULL, "Trigger", id, "Trigger id not found", LOG_LEVEL_INFO); - } -} -#endif // ENABLE_TRIGGERS - -#ifdef SOCKETS_NAMESPACE -} -#endif - - diff --git a/externals/sockets/StdoutLog.cpp b/externals/sockets/StdoutLog.cpp deleted file mode 100644 index e745a6d3358..00000000000 --- a/externals/sockets/StdoutLog.cpp +++ /dev/null @@ -1,98 +0,0 @@ -/** \file StdoutLog.cpp - ** \date 2004-06-01 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#include - -#ifdef _MSC_VER -#pragma warning(disable:4786) -#endif - -#include - -#include "ISocketHandler.h" -#include "Socket.h" -#include "StdoutLog.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - - -void StdoutLog::error(ISocketHandler *,Socket *sock,const std::string& call,int err,const std::string& sys_err,loglevel_t lvl) -{ - time_t t = time(NULL); - struct tm tp; -#ifdef _WIN32 - memcpy(&tp, localtime(&t), sizeof(tp)); -#else - localtime_r(&t, &tp); -#endif - std::string level; - - switch (lvl) - { - case LOG_LEVEL_WARNING: - level = "Warning"; - break; - case LOG_LEVEL_ERROR: - level = "Error"; - break; - case LOG_LEVEL_FATAL: - level = "Fatal"; - break; - case LOG_LEVEL_INFO: - level = "Info"; - break; - } - if (sock) - { - printf("%d-%02d-%02d %02d:%02d:%02d :: fd %d :: %s: %d %s (%s)\n", - tp.tm_year + 1900, - tp.tm_mon + 1, - tp.tm_mday, - tp.tm_hour,tp.tm_min,tp.tm_sec, - sock -> GetSocket(), - call.c_str(),err,sys_err.c_str(),level.c_str()); - } - else - { - printf("%d-%02d-%02d %02d:%02d:%02d :: %s: %d %s (%s)\n", - tp.tm_year + 1900, - tp.tm_mon + 1, - tp.tm_mday, - tp.tm_hour,tp.tm_min,tp.tm_sec, - call.c_str(),err,sys_err.c_str(),level.c_str()); - } -} - -#ifdef SOCKETS_NAMESPACE -} -#endif - - diff --git a/externals/sockets/StreamSocket.cpp b/externals/sockets/StreamSocket.cpp deleted file mode 100644 index 009abadad8f..00000000000 --- a/externals/sockets/StreamSocket.cpp +++ /dev/null @@ -1,145 +0,0 @@ -#include "StreamSocket.h" -#include "ISocketHandler.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -StreamSocket::StreamSocket(ISocketHandler& h) : Socket(h) -,m_bConnecting(false) -,m_connect_timeout(5) -,m_flush_before_close(true) -,m_connection_retry(0) -,m_retries(0) -,m_call_on_connect(false) -,m_b_retry_connect(false) -,m_line_protocol(false) -,m_shutdown(0) -{ -} - -StreamSocket::~StreamSocket() -{ -} - -void StreamSocket::SetConnecting(bool x) -{ - if (x != m_bConnecting) - { - m_bConnecting = x; - if (x) - { - SetTimeout( GetConnectTimeout() ); - } - else - { - SetTimeout( 0 ); - } - } -} - -bool StreamSocket::Connecting() -{ - return m_bConnecting; -} - -bool StreamSocket::Ready() -{ - if (GetSocket() != INVALID_SOCKET && !Connecting() && !CloseAndDelete()) - return true; - return false; -} - -void StreamSocket::SetConnectTimeout(int x) -{ - m_connect_timeout = x; -} - -int StreamSocket::GetConnectTimeout() -{ - return m_connect_timeout; -} - -void StreamSocket::SetFlushBeforeClose(bool x) -{ - m_flush_before_close = x; -} - -bool StreamSocket::GetFlushBeforeClose() -{ - return m_flush_before_close; -} - -int StreamSocket::GetConnectionRetry() -{ - return m_connection_retry; -} - -void StreamSocket::SetConnectionRetry(int x) -{ - m_connection_retry = x; -} - -int StreamSocket::GetConnectionRetries() -{ - return m_retries; -} - -void StreamSocket::IncreaseConnectionRetries() -{ - m_retries++; -} - -void StreamSocket::ResetConnectionRetries() -{ - m_retries = 0; -} - -void StreamSocket::SetCallOnConnect(bool x) -{ - Handler().AddList(GetSocket(), LIST_CALLONCONNECT, x); - m_call_on_connect = x; -} - -bool StreamSocket::CallOnConnect() -{ - return m_call_on_connect; -} - -void StreamSocket::SetRetryClientConnect(bool x) -{ - Handler().AddList(GetSocket(), LIST_RETRY, x); - m_b_retry_connect = x; -} - -bool StreamSocket::RetryClientConnect() -{ - return m_b_retry_connect; -} - -void StreamSocket::SetLineProtocol(bool x) -{ - m_line_protocol = x; -} - -bool StreamSocket::LineProtocol() -{ - return m_line_protocol; -} - -void StreamSocket::SetShutdown(int x) -{ - m_shutdown = x; -} - -int StreamSocket::GetShutdown() -{ - return m_shutdown; -} - - -#ifdef SOCKETS_NAMESPACE -} // namespace SOCKETS_NAMESPACE { -#endif - - diff --git a/externals/sockets/TcpSocket.cpp b/externals/sockets/TcpSocket.cpp deleted file mode 100644 index 5f067b53124..00000000000 --- a/externals/sockets/TcpSocket.cpp +++ /dev/null @@ -1,1681 +0,0 @@ -/** \file TcpSocket.cpp - ** \date 2004-02-13 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifdef _WIN32 -#ifdef _MSC_VER -#pragma warning(disable:4786) -#endif -#include -#else -#include -#endif -#include "ISocketHandler.h" -#include -#include -#include -#include -#ifdef HAVE_OPENSSL -#include -#include -#endif -#include -#include - -#include "TcpSocket.h" -#include "Utility.h" -#include "Ipv4Address.h" -#include "Ipv6Address.h" -#include "Mutex.h" -#include "IFile.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -//#ifdef _DEBUG -//#define DEB(x) x -//#else -#define DEB(x) -//#endif - -// statics -#ifdef HAVE_OPENSSL -SSLInitializer TcpSocket::m_ssl_init; -#endif - -// thanks, q -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif -TcpSocket::TcpSocket(ISocketHandler& h) : StreamSocket(h) -,ibuf(TCP_BUFSIZE_READ) -,m_b_input_buffer_disabled(false) -,m_bytes_sent(0) -,m_bytes_received(0) -,m_skip_c(false) -#ifdef SOCKETS_DYNAMIC_TEMP -,m_buf(new char[TCP_BUFSIZE_READ + 1]) -#endif -,m_obuf_top(NULL) -,m_transfer_limit(0) -,m_output_length(0) -#ifdef HAVE_OPENSSL -,m_ssl_ctx(NULL) -,m_ssl(NULL) -,m_sbio(NULL) -#endif -#ifdef ENABLE_SOCKS4 -,m_socks4_state(0) -#endif -#ifdef ENABLE_RESOLVER -,m_resolver_id(0) -#endif -#ifdef ENABLE_RECONNECT -,m_b_reconnect(false) -,m_b_is_reconnect(false) -#endif -{ -} -#ifdef _MSC_VER -#pragma warning(default:4355) -#endif - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif -TcpSocket::TcpSocket(ISocketHandler& h,size_t isize,size_t osize) : StreamSocket(h) -,ibuf(isize) -,m_b_input_buffer_disabled(false) -,m_bytes_sent(0) -,m_bytes_received(0) -,m_skip_c(false) -#ifdef SOCKETS_DYNAMIC_TEMP -,m_buf(new char[TCP_BUFSIZE_READ + 1]) -#endif -,m_obuf_top(NULL) -,m_transfer_limit(0) -,m_output_length(0) -#ifdef HAVE_OPENSSL -,m_ssl_ctx(NULL) -,m_ssl(NULL) -,m_sbio(NULL) -#endif -#ifdef ENABLE_SOCKS4 -,m_socks4_state(0) -#endif -#ifdef ENABLE_RESOLVER -,m_resolver_id(0) -#endif -#ifdef ENABLE_RECONNECT -,m_b_reconnect(false) -,m_b_is_reconnect(false) -#endif -{ -} -#ifdef _MSC_VER -#pragma warning(default:4355) -#endif - -TcpSocket::~TcpSocket() -{ -#ifdef SOCKETS_DYNAMIC_TEMP - delete[] m_buf; -#endif - // %! empty m_obuf - while (m_obuf.size()) - { - output_l::iterator it = m_obuf.begin(); - OUTPUT *p = *it; - delete p; - m_obuf.erase(it); - } -#ifdef HAVE_OPENSSL - if (m_ssl) - { - SSL_free(m_ssl); - } -#endif -} - -bool TcpSocket::Open(ipaddr_t ip,port_t port,bool skip_socks) -{ - Ipv4Address ad(ip, port); - Ipv4Address local; - return Open(ad, local, skip_socks); -} - -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 -bool TcpSocket::Open(in6_addr ip,port_t port,bool skip_socks) -{ - Ipv6Address ad(ip, port); - return Open(ad, skip_socks); -} -#endif -#endif - -bool TcpSocket::Open(SocketAddress& ad,bool skip_socks) -{ - Ipv4Address bind_ad("0.0.0.0", 0); - return Open(ad, bind_ad, skip_socks); -} - -bool TcpSocket::Open(SocketAddress& ad,SocketAddress& bind_ad,bool skip_socks) -{ - if (!ad.IsValid()) - { - Handler().LogError(this, "Open", 0, "Invalid SocketAddress", LOG_LEVEL_FATAL); - SetCloseAndDelete(); - return false; - } - if (Handler().GetCount() >= FD_SETSIZE) - { - Handler().LogError(this, "Open", 0, "no space left in fd_set", LOG_LEVEL_FATAL); - SetCloseAndDelete(); - return false; - } - SetConnecting(false); -#ifdef ENABLE_SOCKS4 - SetSocks4(false); -#endif - // check for pooling -#ifdef ENABLE_POOL - if (Handler().PoolEnabled()) - { - ISocketHandler::PoolSocket *pools = Handler().FindConnection(SOCK_STREAM, "tcp", ad); - if (pools) - { - CopyConnection( pools ); - delete pools; - - SetIsClient(); - SetCallOnConnect(); // ISocketHandler must call OnConnect - Handler().LogError(this, "SetCallOnConnect", 0, "Found pooled connection", LOG_LEVEL_INFO); - return true; - } - } -#endif - // if not, create new connection - SOCKET s = CreateSocket(ad.GetFamily(), SOCK_STREAM, "tcp"); - if (s == INVALID_SOCKET) - { - return false; - } - // socket must be nonblocking for async connect - if (!SetNonblocking(true, s)) - { - SetCloseAndDelete(); - closesocket(s); - return false; - } -#ifdef ENABLE_POOL - SetIsClient(); // client because we connect -#endif - SetClientRemoteAddress(ad); - int n = 0; - if (bind_ad.GetPort() != 0) - { - bind(s, bind_ad, bind_ad); - } -#ifdef ENABLE_SOCKS4 - if (!skip_socks && GetSocks4Host() && GetSocks4Port()) - { - Ipv4Address sa(GetSocks4Host(), GetSocks4Port()); - { - std::string sockshost; - Utility::l2ip(GetSocks4Host(), sockshost); - Handler().LogError(this, "Open", 0, "Connecting to socks4 server @ " + sockshost + ":" + - Utility::l2string(GetSocks4Port()), LOG_LEVEL_INFO); - } - SetSocks4(); - n = connect(s, sa, sa); - SetRemoteAddress(sa); - } - else -#endif - { - n = connect(s, ad, ad); - SetRemoteAddress(ad); - } - if (n == -1) - { - // check error code that means a connect is in progress -#ifdef _WIN32 - if (Errno == WSAEWOULDBLOCK) -#else - if (Errno == EINPROGRESS) -#endif - { - Attach(s); - SetConnecting( true ); // this flag will control fd_set's - } - else -#ifdef ENABLE_SOCKS4 - if (Socks4() && Handler().Socks4TryDirect() ) // retry - { - closesocket(s); - return Open(ad, true); - } - else -#endif -#ifdef ENABLE_RECONNECT - if (Reconnect()) - { - Handler().LogError(this, "connect: failed, reconnect pending", Errno, StrError(Errno), LOG_LEVEL_INFO); - Attach(s); - SetConnecting( true ); // this flag will control fd_set's - } - else -#endif - { - Handler().LogError(this, "connect: failed", Errno, StrError(Errno), LOG_LEVEL_FATAL); - SetCloseAndDelete(); - closesocket(s); - return false; - } - } - else - { - Attach(s); - SetCallOnConnect(); // ISocketHandler must call OnConnect - } - - // 'true' means connected or connecting(not yet connected) - // 'false' means something failed - return true; //!Connecting(); -} - -bool TcpSocket::Open(const std::string &host,port_t port) -{ -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { -#ifdef ENABLE_RESOLVER - if (!Handler().ResolverEnabled() || Utility::isipv6(host) ) - { -#endif - in6_addr a; - if (!Utility::u2ip(host, a)) - { - SetCloseAndDelete(); - return false; - } - Ipv6Address ad(a, port); - Ipv6Address local; - return Open(ad, local); -#ifdef ENABLE_RESOLVER - } - m_resolver_id = Resolve6(host, port); - return true; -#endif - } -#endif -#endif -#ifdef ENABLE_RESOLVER - if (!Handler().ResolverEnabled() || Utility::isipv4(host) ) - { -#endif - ipaddr_t l; - if (!Utility::u2ip(host,l)) - { - SetCloseAndDelete(); - return false; - } - Ipv4Address ad(l, port); - Ipv4Address local; - return Open(ad, local); -#ifdef ENABLE_RESOLVER - } - // resolve using async resolver thread - m_resolver_id = Resolve(host, port); - return true; -#endif -} - -#ifdef ENABLE_RESOLVER -void TcpSocket::OnResolved(int id,ipaddr_t a,port_t port) -{ -DEB( fprintf(stderr, "TcpSocket::OnResolved id %d addr %x port %d\n", id, a, port);) - if (id == m_resolver_id) - { - if (a && port) - { - Ipv4Address ad(a, port); - Ipv4Address local; - if (Open(ad, local)) - { - if (!Handler().Valid(this)) - { - Handler().Add(this); - } - } - } - else - { - Handler().LogError(this, "OnResolved", 0, "Resolver failed", LOG_LEVEL_FATAL); - SetCloseAndDelete(); - } - } - else - { - Handler().LogError(this, "OnResolved", id, "Resolver returned wrong job id", LOG_LEVEL_FATAL); - SetCloseAndDelete(); - } -} - -#ifdef ENABLE_IPV6 -void TcpSocket::OnResolved(int id,in6_addr& a,port_t port) -{ - if (id == m_resolver_id) - { - Ipv6Address ad(a, port); - if (ad.IsValid()) - { - Ipv6Address local; - if (Open(ad, local)) - { - if (!Handler().Valid(this)) - { - Handler().Add(this); - } - } - } - } - else - { - Handler().LogError(this, "OnResolved", id, "Resolver returned wrong job id", LOG_LEVEL_FATAL); - SetCloseAndDelete(); - } -} -#endif -#endif - -void TcpSocket::OnRead() -{ - int n = 0; -#ifdef SOCKETS_DYNAMIC_TEMP - char *buf = m_buf; -#else - char buf[TCP_BUFSIZE_READ]; -#endif -#ifdef HAVE_OPENSSL - if (IsSSL()) - { - if (!Ready()) - return; - n = SSL_read(m_ssl, buf, TCP_BUFSIZE_READ); - if (n == -1) - { - n = SSL_get_error(m_ssl, n); - switch (n) - { - case SSL_ERROR_NONE: - case SSL_ERROR_WANT_READ: - case SSL_ERROR_WANT_WRITE: - break; - case SSL_ERROR_ZERO_RETURN: -DEB( fprintf(stderr, "SSL_read() returns zero - closing socket\n");) - OnDisconnect(); - SetCloseAndDelete(true); - SetFlushBeforeClose(false); - SetLost(); - break; - default: -DEB( fprintf(stderr, "SSL read problem, errcode = %d\n",n);) - OnDisconnect(); - SetCloseAndDelete(true); - SetFlushBeforeClose(false); - SetLost(); - } - return; - } - else - if (!n) - { - OnDisconnect(); - SetCloseAndDelete(true); - SetFlushBeforeClose(false); - SetLost(); - SetShutdown(SHUT_WR); - return; - } - else - if (n > 0 && n <= TCP_BUFSIZE_READ) - { - m_bytes_received += n; - if (GetTrafficMonitor()) - { - GetTrafficMonitor() -> fwrite(buf, 1, n); - } - if (!m_b_input_buffer_disabled && !ibuf.Write(buf,n)) - { - Handler().LogError(this, "OnRead(ssl)", 0, "ibuf overflow", LOG_LEVEL_WARNING); - } - } - else - { - Handler().LogError(this, "OnRead(ssl)", n, "abnormal value from SSL_read", LOG_LEVEL_ERROR); - } - } - else -#endif // HAVE_OPENSSL - { - n = recv(GetSocket(), buf, TCP_BUFSIZE_READ, MSG_NOSIGNAL); - if (n == -1) - { - Handler().LogError(this, "read", Errno, StrError(Errno), LOG_LEVEL_FATAL); - OnDisconnect(); - SetCloseAndDelete(true); - SetFlushBeforeClose(false); - SetLost(); - return; - } - else - if (!n) - { - OnDisconnect(); - SetCloseAndDelete(true); - SetFlushBeforeClose(false); - SetLost(); - SetShutdown(SHUT_WR); - return; - } - else - if (n > 0 && n <= TCP_BUFSIZE_READ) - { - m_bytes_received += n; - if (GetTrafficMonitor()) - { - GetTrafficMonitor() -> fwrite(buf, 1, n); - } - if (!m_b_input_buffer_disabled && !ibuf.Write(buf,n)) - { - Handler().LogError(this, "OnRead", 0, "ibuf overflow", LOG_LEVEL_WARNING); - } - } - else - { - Handler().LogError(this, "OnRead", n, "abnormal value from recv", LOG_LEVEL_ERROR); - } - } - // - OnRead( buf, n ); -} - -void TcpSocket::OnRead( char *buf, size_t n ) -{ - // unbuffered - if (n > 0 && n <= TCP_BUFSIZE_READ) - { - if (LineProtocol()) - { - buf[n] = 0; - size_t i = 0; - if (m_skip_c && (buf[i] == 13 || buf[i] == 10) && buf[i] != m_c) - { - m_skip_c = false; - i++; - } - size_t x = i; - for (; i < n && LineProtocol(); i++) - { - while ((buf[i] == 13 || buf[i] == 10) && LineProtocol()) - { - char c = buf[i]; - buf[i] = 0; - if (buf[x]) - { - m_line += (buf + x); - } - OnLine( m_line ); - i++; - m_skip_c = true; - m_c = c; - if (i < n && (buf[i] == 13 || buf[i] == 10) && buf[i] != c) - { - m_skip_c = false; - i++; - } - x = i; - m_line = ""; - } - if (!LineProtocol()) - { - break; - } - } - if (!LineProtocol()) - { - if (i < n) - { - OnRawData(buf + i, n - i); - } - } - else - if (buf[x]) - { - m_line += (buf + x); - } - } - else - { - OnRawData(buf, n); - } - } - if (m_b_input_buffer_disabled) - { - return; - } - // further processing: socks4 -#ifdef ENABLE_SOCKS4 - if (Socks4()) - { - bool need_more = false; - while (GetInputLength() && !need_more && !CloseAndDelete()) - { - need_more = OnSocks4Read(); - } - } -#endif -} - -void TcpSocket::OnWriteComplete() -{ -} - -void TcpSocket::OnWrite() -{ - if (Connecting()) - { - int err = SoError(); - - // don't reset connecting flag on error here, we want the OnConnectFailed timeout later on - if (!err) // ok - { - Set(!IsDisableRead(), false); - SetConnecting(false); - SetCallOnConnect(); - return; - } - Handler().LogError(this, "tcp: connect failed", err, StrError(err), LOG_LEVEL_FATAL); - Set(false, false); // no more monitoring because connection failed - - // failed -#ifdef ENABLE_SOCKS4 - if (Socks4()) - { - // %! leave 'Connecting' flag set? - OnSocks4ConnectFailed(); - return; - } -#endif - if (GetConnectionRetry() == -1 || - (GetConnectionRetry() && GetConnectionRetries() < GetConnectionRetry()) ) - { - // even though the connection failed at once, only retry after - // the connection timeout. - // should we even try to connect again, when CheckConnect returns - // false it's because of a connection error - not a timeout... - return; - } - SetConnecting(false); - SetCloseAndDelete( true ); - /// \todo state reason why connect failed - OnConnectFailed(); - return; - } - // try send next block in buffer - // if full block is sent, repeat - // if all blocks are sent, reset m_wfds - - bool repeat = false; - size_t sz = m_transfer_limit ? GetOutputLength() : 0; - do - { - output_l::iterator it = m_obuf.begin(); - OUTPUT *p = *it; - repeat = false; - int n = TryWrite(p -> Buf(), p -> Len()); - if (n > 0) - { - size_t left = p -> Remove(n); - m_output_length -= n; - if (!left) - { - delete p; - m_obuf.erase(it); - if (!m_obuf.size()) - { - m_obuf_top = NULL; - OnWriteComplete(); - } - else - { - repeat = true; - } - } - } - } while (repeat); - - if (m_transfer_limit && sz > m_transfer_limit && GetOutputLength() < m_transfer_limit) - { - OnTransferLimit(); - } - - // check output buffer set, set/reset m_wfds accordingly - { - bool br; - bool bw; - bool bx; - Handler().Get(GetSocket(), br, bw, bx); - if (m_obuf.size()) - Set(br, true); - else - Set(br, false); - } -} - -int TcpSocket::TryWrite(const char *buf, size_t len) -{ - int n = 0; -#ifdef HAVE_OPENSSL - if (IsSSL()) - { - n = SSL_write(m_ssl, buf, (int)len); - if (n == -1) - { - int errnr = SSL_get_error(m_ssl, n); - if ( errnr != SSL_ERROR_WANT_READ && errnr != SSL_ERROR_WANT_WRITE ) - { - OnDisconnect(); - SetCloseAndDelete(true); - SetFlushBeforeClose(false); - SetLost(); - const char *errbuf = ERR_error_string(errnr, NULL); - Handler().LogError(this, "OnWrite/SSL_write", errnr, errbuf, LOG_LEVEL_FATAL); - } - return 0; - } - else - if (!n) - { - OnDisconnect(); - SetCloseAndDelete(true); - SetFlushBeforeClose(false); - SetLost(); -DEB( int errnr = SSL_get_error(m_ssl, n); - const char *errbuf = ERR_error_string(errnr, NULL); - fprintf(stderr, "SSL_write() returns 0: %d : %s\n",errnr, errbuf);) - } - } - else -#endif // HAVE_OPENSSL - { - n = send(GetSocket(), buf, (int)len, MSG_NOSIGNAL); - if (n == -1) - { - // normal error codes: - // WSAEWOULDBLOCK - // EAGAIN or EWOULDBLOCK -#ifdef _WIN32 - if (Errno != WSAEWOULDBLOCK) -#else - if (Errno != EWOULDBLOCK) -#endif - { - Handler().LogError(this, "send", Errno, StrError(Errno), LOG_LEVEL_FATAL); - OnDisconnect(); - SetCloseAndDelete(true); - SetFlushBeforeClose(false); - SetLost(); - } - return 0; - } - } - if (n > 0) - { - m_bytes_sent += n; - if (GetTrafficMonitor()) - { - GetTrafficMonitor() -> fwrite(buf, 1, n); - } - } - return n; -} - -void TcpSocket::Buffer(const char *buf, size_t len) -{ - size_t ptr = 0; - m_output_length += len; - while (ptr < len) - { - // buf/len => pbuf/sz - size_t space = 0; - if (m_obuf_top && (space = m_obuf_top -> Space()) > 0) - { - const char *pbuf = buf + ptr; - size_t sz = len - ptr; - if (space >= sz) - { - m_obuf_top -> Add(pbuf, sz); - ptr += sz; - } - else - { - m_obuf_top -> Add(pbuf, space); - ptr += space; - } - } - else - { - m_obuf_top = new OUTPUT; - m_obuf.push_back( m_obuf_top ); - } - } -} - -void TcpSocket::Send(const std::string &str,int i) -{ - SendBuf(str.c_str(),str.size(),i); -} - -void TcpSocket::SendBuf(const char *buf,size_t len,int) -{ - if (!Ready() && !Connecting()) - { - Handler().LogError(this, "SendBuf", -1, "Attempt to write to a non-ready socket" ); // warning - if (GetSocket() == INVALID_SOCKET) - Handler().LogError(this, "SendBuf", 0, " * GetSocket() == INVALID_SOCKET", LOG_LEVEL_INFO); - if (Connecting()) - Handler().LogError(this, "SendBuf", 0, " * Connecting()", LOG_LEVEL_INFO); - if (CloseAndDelete()) - Handler().LogError(this, "SendBuf", 0, " * CloseAndDelete()", LOG_LEVEL_INFO); - return; - } - if (!IsConnected()) - { - Handler().LogError(this, "SendBuf", -1, "Attempt to write to a non-connected socket, will be sent on connect" ); // warning - Buffer(buf, len); - return; - } - if (m_obuf_top) - { - Buffer(buf, len); - return; - } - int n = TryWrite(buf, len); - if (n >= 0 && n < (int)len) - { - Buffer(buf + n, len - n); - } - // if ( data in buffer || !IsConnected ) - // { - // add to buffer - // } - // else - // try_send - // if any data is unsent, buffer it and set m_wfds - - // check output buffer set, set/reset m_wfds accordingly - { - bool br; - bool bw; - bool bx; - Handler().Get(GetSocket(), br, bw, bx); - if (m_obuf.size()) - Set(br, true); - else - Set(br, false); - } -} - -void TcpSocket::OnLine(const std::string& ) -{ -} - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif -TcpSocket::TcpSocket(const TcpSocket& s) -:StreamSocket(s) -,ibuf(0) -{ -} -#ifdef _MSC_VER -#pragma warning(default:4355) -#endif - -#ifdef ENABLE_SOCKS4 -void TcpSocket::OnSocks4Connect() -{ - char request[1000]; - memset(request, 0, sizeof(request)); - request[0] = 4; // socks v4 - request[1] = 1; // command code: CONNECT - { - std::auto_ptr ad = GetClientRemoteAddress(); - if (ad.get()) - { - struct sockaddr *p0 = (struct sockaddr *)*ad; - struct sockaddr_in *p = (struct sockaddr_in *)p0; - if (p -> sin_family == AF_INET) - { - memcpy(request + 2, &p -> sin_port, 2); // nwbo is ok here - memcpy(request + 4, &p -> sin_addr, sizeof(struct in_addr)); - } - else - { - /// \todo warn - } - } - else - { - /// \todo warn - } - } - strcpy(request + 8, GetSocks4Userid().c_str()); - size_t length = GetSocks4Userid().size() + 8 + 1; - SendBuf(request, length); - m_socks4_state = 0; -} - -void TcpSocket::OnSocks4ConnectFailed() -{ - Handler().LogError(this,"OnSocks4ConnectFailed",0,"connection to socks4 server failed, trying direct connection",LOG_LEVEL_WARNING); - if (!Handler().Socks4TryDirect()) - { - SetConnecting(false); - SetCloseAndDelete(); - OnConnectFailed(); // just in case - } - else - { - SetRetryClientConnect(); - } -} - -bool TcpSocket::OnSocks4Read() -{ - switch (m_socks4_state) - { - case 0: - ibuf.Read(&m_socks4_vn, 1); - m_socks4_state = 1; - break; - case 1: - ibuf.Read(&m_socks4_cd, 1); - m_socks4_state = 2; - break; - case 2: - if (GetInputLength() > 1) - { - ibuf.Read( (char *)&m_socks4_dstport, 2); - m_socks4_state = 3; - } - else - { - return true; - } - break; - case 3: - if (GetInputLength() > 3) - { - ibuf.Read( (char *)&m_socks4_dstip, 4); - SetSocks4(false); - - switch (m_socks4_cd) - { - case 90: - OnConnect(); - Handler().LogError(this, "OnSocks4Read", 0, "Connection established", LOG_LEVEL_INFO); - break; - case 91: - case 92: - case 93: - Handler().LogError(this,"OnSocks4Read",m_socks4_cd,"socks4 server reports connect failed",LOG_LEVEL_FATAL); - SetConnecting(false); - SetCloseAndDelete(); - OnConnectFailed(); - break; - default: - Handler().LogError(this,"OnSocks4Read",m_socks4_cd,"socks4 server unrecognized response",LOG_LEVEL_FATAL); - SetCloseAndDelete(); - break; - } - } - else - { - return true; - } - break; - } - return false; -} -#endif - -void TcpSocket::Sendf(const char *format, ...) -{ - va_list ap; - va_start(ap, format); - char slask[5000]; // vsprintf / vsnprintf temporary -#ifdef _WIN32 - vsprintf(slask, format, ap); -#else - vsnprintf(slask, 5000, format, ap); -#endif - va_end(ap); - Send( slask ); -} - -#ifdef HAVE_OPENSSL -void TcpSocket::OnSSLConnect() -{ - SetNonblocking(true); - { - if (m_ssl_ctx) - { -DEB( fprintf(stderr, "SSL Context already initialized - closing socket\n");) - SetCloseAndDelete(true); - return; - } - InitSSLClient(); - } - if (m_ssl_ctx) - { - /* Connect the SSL socket */ - m_ssl = SSL_new(m_ssl_ctx); - if (!m_ssl) - { -DEB( fprintf(stderr, " m_ssl is NULL\n");) - SetCloseAndDelete(true); - return; - } - SSL_set_mode(m_ssl, SSL_MODE_AUTO_RETRY); - m_sbio = BIO_new_socket((int)GetSocket(), BIO_NOCLOSE); - if (!m_sbio) - { -DEB( fprintf(stderr, " m_sbio is NULL\n");) - SetCloseAndDelete(true); - return; - } - SSL_set_bio(m_ssl, m_sbio, m_sbio); - if (!SSLNegotiate()) - { - SetSSLNegotiate(); - } - } - else - { - SetCloseAndDelete(); - } -} - -void TcpSocket::OnSSLAccept() -{ - SetNonblocking(true); - { - if (m_ssl_ctx) - { -DEB( fprintf(stderr, "SSL Context already initialized - closing socket\n");) - SetCloseAndDelete(true); - return; - } - InitSSLServer(); - SetSSLServer(); - } - if (m_ssl_ctx) - { - m_ssl = SSL_new(m_ssl_ctx); - if (!m_ssl) - { -DEB( fprintf(stderr, " m_ssl is NULL\n");) - SetCloseAndDelete(true); - return; - } - SSL_set_mode(m_ssl, SSL_MODE_AUTO_RETRY); - m_sbio = BIO_new_socket((int)GetSocket(), BIO_NOCLOSE); - if (!m_sbio) - { -DEB( fprintf(stderr, " m_sbio is NULL\n");) - SetCloseAndDelete(true); - return; - } - SSL_set_bio(m_ssl, m_sbio, m_sbio); -// if (!SSLNegotiate()) - { - SetSSLNegotiate(); - } - } -} - -bool TcpSocket::SSLNegotiate() -{ - if (!IsSSLServer()) // client - { - int r = SSL_connect(m_ssl); - if (r > 0) - { - SetSSLNegotiate(false); - /// \todo: resurrect certificate check... client -// CheckCertificateChain( "");//ServerHOST); - SetNonblocking(false); - // - { - SetConnected(); - if (GetOutputLength()) - { - OnWrite(); - } - } -#ifdef ENABLE_RECONNECT - if (IsReconnect()) - OnReconnect(); - else -#endif - { - OnConnect(); - } - Handler().LogError(this, "SSLNegotiate/SSL_connect", 0, "Connection established", LOG_LEVEL_INFO); - return true; - } - else - if (!r) - { - Handler().LogError(this, "SSLNegotiate/SSL_connect", 0, "Connection failed", LOG_LEVEL_INFO); - SetSSLNegotiate(false); - SetCloseAndDelete(); - OnSSLConnectFailed(); - } - else - { - r = SSL_get_error(m_ssl, r); - if (r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE) - { - Handler().LogError(this, "SSLNegotiate/SSL_connect", -1, "Connection failed", LOG_LEVEL_INFO); -DEB( fprintf(stderr, "SSL_connect() failed - closing socket, return code: %d\n",r);) - SetSSLNegotiate(false); - SetCloseAndDelete(true); - OnSSLConnectFailed(); - } - } - } - else // server - { - int r = SSL_accept(m_ssl); - if (r > 0) - { - SetSSLNegotiate(false); - /// \todo: resurrect certificate check... server -// CheckCertificateChain( "");//ClientHOST); - SetNonblocking(false); - // - { - SetConnected(); - if (GetOutputLength()) - { - OnWrite(); - } - } - OnAccept(); - Handler().LogError(this, "SSLNegotiate/SSL_accept", 0, "Connection established", LOG_LEVEL_INFO); - return true; - } - else - if (!r) - { - Handler().LogError(this, "SSLNegotiate/SSL_accept", 0, "Connection failed", LOG_LEVEL_INFO); - SetSSLNegotiate(false); - SetCloseAndDelete(); - OnSSLAcceptFailed(); - } - else - { - r = SSL_get_error(m_ssl, r); - if (r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE) - { - Handler().LogError(this, "SSLNegotiate/SSL_accept", -1, "Connection failed", LOG_LEVEL_INFO); -DEB( fprintf(stderr, "SSL_accept() failed - closing socket, return code: %d\n",r);) - SetSSLNegotiate(false); - SetCloseAndDelete(true); - OnSSLAcceptFailed(); - } - } - } - return false; -} - -void TcpSocket::InitSSLClient() -{ - InitializeContext("", SSLv23_method()); -} - -void TcpSocket::InitSSLServer() -{ - Handler().LogError(this, "InitSSLServer", 0, "You MUST implement your own InitSSLServer method", LOG_LEVEL_FATAL); - SetCloseAndDelete(); -} - -void TcpSocket::InitializeContext(const std::string& context, SSL_METHOD *meth_in) -{ - /* Create our context*/ - static std::map client_contexts; - if (client_contexts.find(context) == client_contexts.end()) - { - SSL_METHOD *meth = meth_in ? meth_in : SSLv3_method(); - m_ssl_ctx = client_contexts[context] = SSL_CTX_new(meth); - SSL_CTX_set_mode(m_ssl_ctx, SSL_MODE_AUTO_RETRY); - } - else - { - m_ssl_ctx = client_contexts[context]; - } -} - -void TcpSocket::InitializeContext(const std::string& context,const std::string& keyfile,const std::string& password,SSL_METHOD *meth_in) -{ - /* Create our context*/ - static std::map server_contexts; - if (server_contexts.find(context) == server_contexts.end()) - { - SSL_METHOD *meth = meth_in ? meth_in : SSLv3_method(); - m_ssl_ctx = server_contexts[context] = SSL_CTX_new(meth); - SSL_CTX_set_mode(m_ssl_ctx, SSL_MODE_AUTO_RETRY); - // session id - if (!context.empty()) - SSL_CTX_set_session_id_context(m_ssl_ctx, (const unsigned char *)context.c_str(), (unsigned int)context.size()); - else - SSL_CTX_set_session_id_context(m_ssl_ctx, (const unsigned char *)"--empty--", 9); - } - else - { - m_ssl_ctx = server_contexts[context]; - } - - /* Load our keys and certificates*/ - if (!(SSL_CTX_use_certificate_file(m_ssl_ctx, keyfile.c_str(), SSL_FILETYPE_PEM))) - { - Handler().LogError(this, "TcpSocket InitializeContext", 0, "Couldn't read certificate file " + keyfile, LOG_LEVEL_FATAL); - } - - m_password = password; - SSL_CTX_set_default_passwd_cb(m_ssl_ctx, SSL_password_cb); - SSL_CTX_set_default_passwd_cb_userdata(m_ssl_ctx, this); - if (!(SSL_CTX_use_PrivateKey_file(m_ssl_ctx, keyfile.c_str(), SSL_FILETYPE_PEM))) - { - Handler().LogError(this, "TcpSocket InitializeContext", 0, "Couldn't read private key file " + keyfile, LOG_LEVEL_FATAL); - } -} - -void TcpSocket::InitializeContext(const std::string& context,const std::string& certfile,const std::string& keyfile,const std::string& password,SSL_METHOD *meth_in) -{ - /* Create our context*/ - static std::map server_contexts; - if (server_contexts.find(context) == server_contexts.end()) - { - SSL_METHOD *meth = meth_in ? meth_in : SSLv3_method(); - m_ssl_ctx = server_contexts[context] = SSL_CTX_new(meth); - SSL_CTX_set_mode(m_ssl_ctx, SSL_MODE_AUTO_RETRY); - // session id - if (context.size()) - SSL_CTX_set_session_id_context(m_ssl_ctx, (const unsigned char *)context.c_str(), (unsigned int)context.size()); - else - SSL_CTX_set_session_id_context(m_ssl_ctx, (const unsigned char *)"--empty--", 9); - } - else - { - m_ssl_ctx = server_contexts[context]; - } - - /* Load our keys and certificates*/ - if (!(SSL_CTX_use_certificate_file(m_ssl_ctx, certfile.c_str(), SSL_FILETYPE_PEM))) - { - Handler().LogError(this, "TcpSocket InitializeContext", 0, "Couldn't read certificate file " + keyfile, LOG_LEVEL_FATAL); - } - - m_password = password; - SSL_CTX_set_default_passwd_cb(m_ssl_ctx, SSL_password_cb); - SSL_CTX_set_default_passwd_cb_userdata(m_ssl_ctx, this); - if (!(SSL_CTX_use_PrivateKey_file(m_ssl_ctx, keyfile.c_str(), SSL_FILETYPE_PEM))) - { - Handler().LogError(this, "TcpSocket InitializeContext", 0, "Couldn't read private key file " + keyfile, LOG_LEVEL_FATAL); - } -} - -int TcpSocket::SSL_password_cb(char *buf,int num,int rwflag,void *userdata) -{ - Socket *p0 = static_cast(userdata); - TcpSocket *p = dynamic_cast(p0); - std::string pw = p ? p -> GetPassword() : ""; - if ( (size_t)num < pw.size() + 1) - { - return 0; - } - strcpy(buf,pw.c_str()); - return (int)pw.size(); -} -#endif // HAVE_OPENSSL - -int TcpSocket::Close() -{ - if (GetSocket() == INVALID_SOCKET) // this could happen - { - Handler().LogError(this, "Socket::Close", 0, "file descriptor invalid", LOG_LEVEL_WARNING); - return 0; - } - int n; - SetNonblocking(true); - if (!Lost() && IsConnected() && !(GetShutdown() & SHUT_WR)) - { - if (shutdown(GetSocket(), SHUT_WR) == -1) - { - // failed... - Handler().LogError(this, "shutdown", Errno, StrError(Errno), LOG_LEVEL_ERROR); - } - } - // - char tmp[1000]; - if (!Lost() && (n = recv(GetSocket(),tmp,1000,0)) >= 0) - { - if (n) - { - Handler().LogError(this, "read() after shutdown", n, "bytes read", LOG_LEVEL_WARNING); - } - } -#ifdef HAVE_OPENSSL - if (IsSSL() && m_ssl) - SSL_shutdown(m_ssl); - if (m_ssl) - { - SSL_free(m_ssl); - m_ssl = NULL; - } -#endif - return Socket::Close(); -} - -#ifdef HAVE_OPENSSL -SSL_CTX *TcpSocket::GetSslContext() -{ - if (!m_ssl_ctx) - Handler().LogError(this, "GetSslContext", 0, "SSL Context is NULL; check InitSSLServer/InitSSLClient", LOG_LEVEL_WARNING); - return m_ssl_ctx; -} - -SSL *TcpSocket::GetSsl() -{ - if (!m_ssl) - Handler().LogError(this, "GetSsl", 0, "SSL is NULL; check InitSSLServer/InitSSLClient", LOG_LEVEL_WARNING); - return m_ssl; -} -#endif - -#ifdef ENABLE_RECONNECT -void TcpSocket::SetReconnect(bool x) -{ - m_b_reconnect = x; -} -#endif - -void TcpSocket::OnRawData(const char *buf_in,size_t len) -{ -} - -size_t TcpSocket::GetInputLength() -{ - return ibuf.GetLength(); -} - -size_t TcpSocket::GetOutputLength() -{ - return m_output_length; -} - -uint64_t TcpSocket::GetBytesReceived(bool clear) -{ - uint64_t z = m_bytes_received; - if (clear) - m_bytes_received = 0; - return z; -} - -uint64_t TcpSocket::GetBytesSent(bool clear) -{ - uint64_t z = m_bytes_sent; - if (clear) - m_bytes_sent = 0; - return z; -} - -#ifdef ENABLE_RECONNECT -bool TcpSocket::Reconnect() -{ - return m_b_reconnect; -} - -void TcpSocket::SetIsReconnect(bool x) -{ - m_b_is_reconnect = x; -} - -bool TcpSocket::IsReconnect() -{ - return m_b_is_reconnect; -} -#endif - -#ifdef HAVE_OPENSSL -const std::string& TcpSocket::GetPassword() -{ - return m_password; -} -#endif - -void TcpSocket::DisableInputBuffer(bool x) -{ - m_b_input_buffer_disabled = x; -} - -void TcpSocket::OnOptions(int family,int type,int protocol,SOCKET s) -{ -DEB( fprintf(stderr, "Socket::OnOptions()\n");) -#ifdef SO_NOSIGPIPE - SetSoNosigpipe(true); -#endif - SetSoReuseaddr(true); - SetSoKeepalive(true); -} - -void TcpSocket::SetLineProtocol(bool x) -{ - StreamSocket::SetLineProtocol(x); - DisableInputBuffer(x); -} - -bool TcpSocket::SetTcpNodelay(bool x) -{ -#ifdef TCP_NODELAY - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), IPPROTO_TCP, TCP_NODELAY, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_TCP, TCP_NODELAY)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "socket option not available", 0, "TCP_NODELAY", LOG_LEVEL_INFO); - return false; -#endif -} - -TcpSocket::CircularBuffer::CircularBuffer(size_t size) -:buf(new char[2 * size]) -,m_max(size) -,m_q(0) -,m_b(0) -,m_t(0) -,m_count(0) -{ -} - -TcpSocket::CircularBuffer::~CircularBuffer() -{ - delete[] buf; -} - -bool TcpSocket::CircularBuffer::Write(const char *s,size_t l) -{ - if (m_q + l > m_max) - { - return false; // overflow - } - m_count += (unsigned long)l; - if (m_t + l > m_max) // block crosses circular border - { - size_t l1 = m_max - m_t; // size left until circular border crossing - // always copy full block to buffer(buf) + top pointer(m_t) - // because we have doubled the buffer size for performance reasons - memcpy(buf + m_t, s, l); - memcpy(buf, s + l1, l - l1); - m_t = l - l1; - m_q += l; - } - else - { - memcpy(buf + m_t, s, l); - memcpy(buf + m_max + m_t, s, l); - m_t += l; - if (m_t >= m_max) - m_t -= m_max; - m_q += l; - } - return true; -} - -bool TcpSocket::CircularBuffer::Read(char *s,size_t l) -{ - if (l > m_q) - { - return false; // not enough chars - } - if (m_b + l > m_max) // block crosses circular border - { - size_t l1 = m_max - m_b; - if (s) - { - memcpy(s, buf + m_b, l1); - memcpy(s + l1, buf, l - l1); - } - m_b = l - l1; - m_q -= l; - } - else - { - if (s) - { - memcpy(s, buf + m_b, l); - } - m_b += l; - if (m_b >= m_max) - m_b -= m_max; - m_q -= l; - } - if (!m_q) - { - m_b = m_t = 0; - } - return true; -} - -bool TcpSocket::CircularBuffer::SoftRead(char *s, size_t l) -{ - if (l > m_q) - { - return false; - } - if (m_b + l > m_max) // block crosses circular border - { - size_t l1 = m_max - m_b; - if (s) - { - memcpy(s, buf + m_b, l1); - memcpy(s + l1, buf, l - l1); - } - } - else - { - if (s) - { - memcpy(s, buf + m_b, l); - } - } - return true; -} - -bool TcpSocket::CircularBuffer::Remove(size_t l) -{ - return Read(NULL, l); -} - -size_t TcpSocket::CircularBuffer::GetLength() -{ - return m_q; -} - -const char *TcpSocket::CircularBuffer::GetStart() -{ - return buf + m_b; -} - -size_t TcpSocket::CircularBuffer::GetL() -{ - return (m_b + m_q > m_max) ? m_max - m_b : m_q; -} - -size_t TcpSocket::CircularBuffer::Space() -{ - return m_max - m_q; -} - -unsigned long TcpSocket::CircularBuffer::ByteCounter(bool clear) -{ - if (clear) - { - unsigned long x = m_count; - m_count = 0; - return x; - } - return m_count; -} - -std::string TcpSocket::CircularBuffer::ReadString(size_t l) -{ - char *sz = new char[l + 1]; - if (!Read(sz, l)) // failed, debug printout in Read() method - { - delete[] sz; - return ""; - } - sz[l] = 0; - std::string tmp = sz; - delete[] sz; - return tmp; -} - -void TcpSocket::OnConnectTimeout() -{ - Handler().LogError(this, "connect", -1, "connect timeout", LOG_LEVEL_FATAL); -#ifdef ENABLE_SOCKS4 - if (Socks4()) - { - OnSocks4ConnectFailed(); - // retry direct connection - } - else -#endif - if (GetConnectionRetry() == -1 || - (GetConnectionRetry() && GetConnectionRetries() < GetConnectionRetry()) ) - { - IncreaseConnectionRetries(); - // ask socket via OnConnectRetry callback if we should continue trying - if (OnConnectRetry()) - { - SetRetryClientConnect(); - } - else - { - SetCloseAndDelete( true ); - /// \todo state reason why connect failed - OnConnectFailed(); - } - } - else - { - SetCloseAndDelete(true); - /// \todo state reason why connect failed - OnConnectFailed(); - } - // - SetConnecting(false); -} - -#ifdef _WIN32 -void TcpSocket::OnException() -{ - if (Connecting()) - { -#ifdef ENABLE_SOCKS4 - if (Socks4()) - OnSocks4ConnectFailed(); - else -#endif - if (GetConnectionRetry() == -1 || - (GetConnectionRetry() && - GetConnectionRetries() < GetConnectionRetry() )) - { - // even though the connection failed at once, only retry after - // the connection timeout - // should we even try to connect again, when CheckConnect returns - // false it's because of a connection error - not a timeout... - } - else - { - SetConnecting(false); // tnx snibbe - SetCloseAndDelete(); - OnConnectFailed(); - } - return; - } - // %! exception doesn't always mean something bad happened, this code should be reworked - // errno valid here? - int err = SoError(); - Handler().LogError(this, "exception on select", err, StrError(err), LOG_LEVEL_FATAL); - SetCloseAndDelete(); -} -#endif // _WIN32 - -int TcpSocket::Protocol() -{ - return IPPROTO_TCP; -} - -void TcpSocket::SetTransferLimit(size_t sz) -{ - m_transfer_limit = sz; -} - -void TcpSocket::OnTransferLimit() -{ -} - -#ifdef SOCKETS_NAMESPACE -} -#endif - - diff --git a/externals/sockets/Thread.cpp b/externals/sockets/Thread.cpp deleted file mode 100644 index 773e9f214fa..00000000000 --- a/externals/sockets/Thread.cpp +++ /dev/null @@ -1,154 +0,0 @@ -/** \file Thread.cpp - ** \date 2004-10-30 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#include -#ifdef _WIN32 -#include -#include "socket_include.h" -#else -#include -#endif - -#include "Thread.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -Thread::Thread(bool release) -:m_thread(0) -,m_running(true) -,m_release(false) -,m_b_delete_on_exit(false) -,m_b_destructor(false) -{ -#ifdef _WIN32 -// m_thread = ::CreateThread(NULL, 0, StartThread, this, 0, &m_dwThreadId); - m_thread = (HANDLE)_beginthreadex(NULL, 0, &StartThread, this, 0, &m_dwThreadId); -#else - pthread_attr_t attr; - - pthread_attr_init(&attr); - pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); - if (pthread_create(&m_thread,&attr, StartThread,this) == -1) - { - perror("Thread: create failed"); - SetRunning(false); - } -// pthread_attr_destroy(&attr); -#endif - m_release = release; -} - -Thread::~Thread() -{ - m_b_destructor = true; - if (m_running) - { - SetRelease(true); - SetRunning(false); -#ifdef _WIN32 - Sleep(1000); -#else - sleep(1); -#endif - } -#ifdef _WIN32 - if (m_thread) - ::CloseHandle(m_thread); -#endif -} - -threadfunc_t STDPREFIX Thread::StartThread(threadparam_t zz) -{ - Thread *p = (Thread *)zz; - - while (p -> m_running && !p -> m_release) - { -#ifdef _WIN32 - Sleep(1000); -#else - sleep(1); -#endif - } - if (p -> m_running) - { - p -> Run(); - } - p -> SetRunning(false); // if return - if (p -> DeleteOnExit() && !p -> IsDestructor()) - { - delete p; - } -#ifdef _WIN32 - _endthreadex(0); -#endif - return (threadfunc_t)NULL; -} - -bool Thread::IsRunning() -{ - return m_running; -} - -void Thread::SetRunning(bool x) -{ - m_running = x; -} - -bool Thread::IsReleased() -{ - return m_release; -} - -void Thread::SetRelease(bool x) -{ - m_release = x; -} - -bool Thread::DeleteOnExit() -{ - return m_b_delete_on_exit; -} - -void Thread::SetDeleteOnExit(bool x) -{ - m_b_delete_on_exit = x; -} - -bool Thread::IsDestructor() -{ - return m_b_destructor; -} - -#ifdef SOCKETS_NAMESPACE -} -#endif - - diff --git a/externals/sockets/UdpSocket.cpp b/externals/sockets/UdpSocket.cpp deleted file mode 100644 index a3d393c00e2..00000000000 --- a/externals/sockets/UdpSocket.cpp +++ /dev/null @@ -1,810 +0,0 @@ -/** \file UdpSocket.cpp - ** \date 2004-02-13 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifdef _WIN32 -#ifdef _MSC_VER -#pragma warning(disable:4786) -#endif -#include -#else -#include -#endif - -#include "ISocketHandler.h" -#include "UdpSocket.h" -#include "Utility.h" -#include "Ipv4Address.h" -#include "Ipv6Address.h" -#ifdef ENABLE_EXCEPTIONS -#include "Exception.h" -#endif -// include this to see strange sights -//#include - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -UdpSocket::UdpSocket(ISocketHandler& h, int ibufsz, bool ipv6, int retries) : Socket(h) -, m_ibuf(new char[ibufsz]) -, m_ibufsz(ibufsz) -, m_bind_ok(false) -, m_port(0) -, m_last_size_written(-1) -, m_retries(retries) -, m_b_read_ts(false) -{ -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - SetIpv6(ipv6); -#endif -#endif -} - -UdpSocket::~UdpSocket() -{ - Close(); - delete[] m_ibuf; -} - -int UdpSocket::Bind(port_t &port, int range) -{ -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - Ipv6Address ad(port); - return Bind(ad, range); - } -#endif -#endif - Ipv4Address ad(port); - return Bind(ad, range); -} - -int UdpSocket::Bind(const std::string& intf, port_t &port, int range) -{ -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - Ipv6Address ad(intf, port); - if (ad.IsValid()) - { - return Bind(ad, range); - } - SetCloseAndDelete(); - return -1; - } -#endif -#endif - Ipv4Address ad(intf, port); - if (ad.IsValid()) - { - return Bind(ad, range); - } - SetCloseAndDelete(); - return -1; -} - -int UdpSocket::Bind(ipaddr_t a, port_t &port, int range) -{ - Ipv4Address ad(a, port); - return Bind(ad, range); -} - -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 -int UdpSocket::Bind(in6_addr a, port_t &port, int range) -{ - Ipv6Address ad(a, port); - return Bind(ad, range); -} -#endif -#endif - -int UdpSocket::Bind(SocketAddress& ad, int range) -{ - if (GetSocket() == INVALID_SOCKET) - { - Attach(CreateSocket(ad.GetFamily(), SOCK_DGRAM, "udp")); - } - if (GetSocket() != INVALID_SOCKET) - { - SetNonblocking(true); - int n = bind(GetSocket(), ad, ad); - int tries = range; - while (n == -1 && tries--) - { - ad.SetPort(ad.GetPort() + 1); - n = bind(GetSocket(), ad, ad); - } - if (n == -1) - { - Handler().LogError(this, "bind", Errno, StrError(Errno), LOG_LEVEL_FATAL); - SetCloseAndDelete(); -#ifdef ENABLE_EXCEPTIONS - throw Exception("bind() failed for UdpSocket, port:range: " + Utility::l2string(ad.GetPort()) + ":" + Utility::l2string(range)); -#endif - return -1; - } - m_bind_ok = true; - m_port = ad.GetPort(); - return 0; - } - return -1; -} - -/** if you wish to use Send, first Open a connection */ -bool UdpSocket::Open(ipaddr_t l, port_t port) -{ - Ipv4Address ad(l, port); - return Open(ad); -} - -bool UdpSocket::Open(const std::string& host, port_t port) -{ -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - Ipv6Address ad(host, port); - if (ad.IsValid()) - { - return Open(ad); - } - return false; - } -#endif -#endif - Ipv4Address ad(host, port); - if (ad.IsValid()) - { - return Open(ad); - } - return false; -} - -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 -bool UdpSocket::Open(struct in6_addr& a, port_t port) -{ - Ipv6Address ad(a, port); - return Open(ad); -} -#endif -#endif - -bool UdpSocket::Open(SocketAddress& ad) -{ - if (GetSocket() == INVALID_SOCKET) - { - Attach(CreateSocket(ad.GetFamily(), SOCK_DGRAM, "udp")); - } - if (GetSocket() != INVALID_SOCKET) - { - SetNonblocking(true); - if (connect(GetSocket(), ad, ad) == -1) - { - Handler().LogError(this, "connect", Errno, StrError(Errno), LOG_LEVEL_FATAL); - SetCloseAndDelete(); - return false; - } - SetConnected(); - return true; - } - return false; -} - -void UdpSocket::CreateConnection() -{ -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - if (GetSocket() == INVALID_SOCKET) - { - SOCKET s = CreateSocket(AF_INET6, SOCK_DGRAM, "udp"); - if (s == INVALID_SOCKET) - { - return; - } - SetNonblocking(true, s); - Attach(s); - } - return; - } -#endif -#endif - if (GetSocket() == INVALID_SOCKET) - { - SOCKET s = CreateSocket(AF_INET, SOCK_DGRAM, "udp"); - if (s == INVALID_SOCKET) - { - return; - } - SetNonblocking(true, s); - Attach(s); - } -} - -/** send to specified address */ -void UdpSocket::SendToBuf(const std::string& h, port_t p, const char *data, int len, int flags) -{ -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - Ipv6Address ad(h, p); - if (ad.IsValid()) - { - SendToBuf(ad, data, len, flags); - } - return; - } -#endif -#endif - Ipv4Address ad(h, p); - if (ad.IsValid()) - { - SendToBuf(ad, data, len, flags); - } -} - -/** send to specified address */ -void UdpSocket::SendToBuf(ipaddr_t a, port_t p, const char *data, int len, int flags) -{ - Ipv4Address ad(a, p); - SendToBuf(ad, data, len, flags); -} - -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 -void UdpSocket::SendToBuf(in6_addr a, port_t p, const char *data, int len, int flags) -{ - Ipv6Address ad(a, p); - SendToBuf(ad, data, len, flags); -} -#endif -#endif - -void UdpSocket::SendToBuf(SocketAddress& ad, const char *data, int len, int flags) -{ - if (GetSocket() == INVALID_SOCKET) - { - Attach(CreateSocket(ad.GetFamily(), SOCK_DGRAM, "udp")); - } - if (GetSocket() != INVALID_SOCKET) - { - SetNonblocking(true); - if ((m_last_size_written = sendto(GetSocket(), data, len, flags, ad, ad)) == -1) - { - Handler().LogError(this, "sendto", Errno, StrError(Errno), LOG_LEVEL_ERROR); - } - } -} - -void UdpSocket::SendTo(const std::string& a, port_t p, const std::string& str, int flags) -{ - SendToBuf(a, p, str.c_str(), (int)str.size(), flags); -} - -void UdpSocket::SendTo(ipaddr_t a, port_t p, const std::string& str, int flags) -{ - SendToBuf(a, p, str.c_str(), (int)str.size(), flags); -} - -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 -void UdpSocket::SendTo(in6_addr a, port_t p, const std::string& str, int flags) -{ - SendToBuf(a, p, str.c_str(), (int)str.size(), flags); -} -#endif -#endif - -void UdpSocket::SendTo(SocketAddress& ad, const std::string& str, int flags) -{ - SendToBuf(ad, str.c_str(), (int)str.size(), flags); -} - -/** send to connected address */ -void UdpSocket::SendBuf(const char *data, size_t len, int flags) -{ - if (!IsConnected()) - { - Handler().LogError(this, "SendBuf", 0, "not connected", LOG_LEVEL_ERROR); - return; - } - if ((m_last_size_written = send(GetSocket(), data, (int)len, flags)) == -1) - { - Handler().LogError(this, "send", Errno, StrError(Errno), LOG_LEVEL_ERROR); - } -} - -void UdpSocket::Send(const std::string& str, int flags) -{ - SendBuf(str.c_str(), (int)str.size(), flags); -} - -#if defined(LINUX) || defined(MACOSX) -int UdpSocket::ReadTS(char *ioBuf, int inBufSize, struct sockaddr *from, socklen_t fromlen, struct timeval *ts) -{ - struct msghdr msg; - struct iovec vec[1]; - union { - struct cmsghdr cm; -#ifdef MACOSX -#ifdef __DARWIN_UNIX03 -#define ALIGNBYTES __DARWIN_ALIGNBYTES -#endif -#define myALIGN(p) (((unsigned int)(p) + ALIGNBYTES) &~ ALIGNBYTES) -#define myCMSG_SPACE(l) (myALIGN(sizeof(struct cmsghdr)) + myALIGN(l)) - char data[ myCMSG_SPACE(sizeof(struct timeval)) ]; -#else - char data[ CMSG_SPACE(sizeof(struct timeval)) ]; -#endif - } cmsg_un; - struct cmsghdr *cmsg; - struct timeval *tv; - - vec[0].iov_base = ioBuf; - vec[0].iov_len = inBufSize; - - memset(&msg, 0, sizeof(msg)); - memset(from, 0, fromlen); - memset(ioBuf, 0, inBufSize); - memset(&cmsg_un, 0, sizeof(cmsg_un)); - - msg.msg_name = (caddr_t)from; - msg.msg_namelen = fromlen; - msg.msg_iov = vec; - msg.msg_iovlen = 1; - msg.msg_control = cmsg_un.data; - msg.msg_controllen = sizeof(cmsg_un.data); - msg.msg_flags = 0; - - // Original version - for reference only - //int n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len); - - int n = recvmsg(GetSocket(), &msg, MSG_DONTWAIT); - - // now ioBuf will contain the data, as if we used recvfrom - - // Now get the time - if(n != -1 && msg.msg_controllen >= sizeof(struct cmsghdr) && !(msg.msg_flags & MSG_CTRUNC)) - { - tv = 0; - for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg)) - { - if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_TIMESTAMP) - { - tv = (struct timeval *)CMSG_DATA(cmsg); - } - } - if (tv) - { - memcpy(ts, tv, sizeof(struct timeval)); - } - } - // The address is in network order, but that's OK right now - return n; -} -#endif - -void UdpSocket::OnRead() -{ -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - struct sockaddr_in6 sa; - socklen_t sa_len = sizeof(sa); - if (m_b_read_ts) - { - struct timeval ts; - Utility::GetTime(&ts); -#if !defined(LINUX) && !defined(MACOSX) - int n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len); -#else - int n = ReadTS(m_ibuf, m_ibufsz, (struct sockaddr *)&sa, sa_len, &ts); -#endif - if (n > 0) - { - this -> OnRawData(m_ibuf, n, (struct sockaddr *)&sa, sa_len, &ts); - } - else - if (n == -1) - { -#ifdef _WIN32 - if (Errno != WSAEWOULDBLOCK) -#else - if (Errno != EWOULDBLOCK) -#endif - Handler().LogError(this, "recvfrom", Errno, StrError(Errno), LOG_LEVEL_ERROR); - } - return; - } - int n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len); - int q = m_retries; // receive max 10 at one cycle - while (n > 0) - { - if (sa_len != sizeof(sa)) - { - Handler().LogError(this, "recvfrom", 0, "unexpected address struct size", LOG_LEVEL_WARNING); - } - this -> OnRawData(m_ibuf, n, (struct sockaddr *)&sa, sa_len); - if (!q--) - break; - // - n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len); - } - if (n == -1) - { -#ifdef _WIN32 - if (Errno != WSAEWOULDBLOCK) -#else - if (Errno != EWOULDBLOCK) -#endif - Handler().LogError(this, "recvfrom", Errno, StrError(Errno), LOG_LEVEL_ERROR); - } - return; - } -#endif -#endif - struct sockaddr_in sa; - socklen_t sa_len = sizeof(sa); - if (m_b_read_ts) - { - struct timeval ts; - Utility::GetTime(&ts); -#if !defined(LINUX) && !defined(MACOSX) - int n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len); -#else - int n = ReadTS(m_ibuf, m_ibufsz, (struct sockaddr *)&sa, sa_len, &ts); -#endif - if (n > 0) - { - this -> OnRawData(m_ibuf, n, (struct sockaddr *)&sa, sa_len, &ts); - } - else - if (n == -1) - { -#ifdef _WIN32 - if (Errno != WSAEWOULDBLOCK) -#else - if (Errno != EWOULDBLOCK) -#endif - Handler().LogError(this, "recvfrom", Errno, StrError(Errno), LOG_LEVEL_ERROR); - } - return; - } - int n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len); - int q = m_retries; - while (n > 0) - { - if (sa_len != sizeof(sa)) - { - Handler().LogError(this, "recvfrom", 0, "unexpected address struct size", LOG_LEVEL_WARNING); - } - this -> OnRawData(m_ibuf, n, (struct sockaddr *)&sa, sa_len); - if (!q--) - break; - // - n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len); - } - if (n == -1) - { -#ifdef _WIN32 - if (Errno != WSAEWOULDBLOCK) -#else - if (Errno != EWOULDBLOCK) -#endif - Handler().LogError(this, "recvfrom", Errno, StrError(Errno), LOG_LEVEL_ERROR); - } -} - -void UdpSocket::SetBroadcast(bool b) -{ - int one = 1; - int zero = 0; - - if (GetSocket() == INVALID_SOCKET) - { - CreateConnection(); - } - if (b) - { - if (setsockopt(GetSocket(), SOL_SOCKET, SO_BROADCAST, (char *) &one, sizeof(one)) == -1) - { - Handler().LogError(this, "SetBroadcast", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } - } - else - { - if (setsockopt(GetSocket(), SOL_SOCKET, SO_BROADCAST, (char *) &zero, sizeof(zero)) == -1) - { - Handler().LogError(this, "SetBroadcast", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } - } -} - -bool UdpSocket::IsBroadcast() -{ - int is_broadcast = 0; - socklen_t size; - - if (GetSocket() == INVALID_SOCKET) - { - CreateConnection(); - } - if (getsockopt(GetSocket(), SOL_SOCKET, SO_BROADCAST, (char *)&is_broadcast, &size) == -1) - { - Handler().LogError(this, "IsBroadcast", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } - return is_broadcast != 0; -} - -void UdpSocket::SetMulticastTTL(int ttl) -{ - if (GetSocket() == INVALID_SOCKET) - { - CreateConnection(); - } - if (setsockopt(GetSocket(), SOL_IP, IP_MULTICAST_TTL, (char *)&ttl, sizeof(int)) == -1) - { - Handler().LogError(this, "SetMulticastTTL", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } -} - -int UdpSocket::GetMulticastTTL() -{ - int ttl = 0; - socklen_t size = sizeof(int); - - if (GetSocket() == INVALID_SOCKET) - { - CreateConnection(); - } - if (getsockopt(GetSocket(), SOL_IP, IP_MULTICAST_TTL, (char *)&ttl, &size) == -1) - { - Handler().LogError(this, "GetMulticastTTL", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } - return ttl; -} - -void UdpSocket::SetMulticastLoop(bool x) -{ - if (GetSocket() == INVALID_SOCKET) - { - CreateConnection(); - } -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - int val = x ? 1 : 0; - if (setsockopt(GetSocket(), IPPROTO_IPV6, IPV6_MULTICAST_LOOP, (char *)&val, sizeof(int)) == -1) - { - Handler().LogError(this, "SetMulticastLoop", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } - return; - } -#endif -#endif - int val = x ? 1 : 0; - if (setsockopt(GetSocket(), SOL_IP, IP_MULTICAST_LOOP, (char *)&val, sizeof(int)) == -1) - { - Handler().LogError(this, "SetMulticastLoop", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } -} - -bool UdpSocket::IsMulticastLoop() -{ - if (GetSocket() == INVALID_SOCKET) - { - CreateConnection(); - } -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - int is_loop = 0; - socklen_t size = sizeof(int); - if (getsockopt(GetSocket(), IPPROTO_IPV6, IPV6_MULTICAST_LOOP, (char *)&is_loop, &size) == -1) - { - Handler().LogError(this, "IsMulticastLoop", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } - return is_loop ? true : false; - } -#endif -#endif - int is_loop = 0; - socklen_t size = sizeof(int); - if (getsockopt(GetSocket(), SOL_IP, IP_MULTICAST_LOOP, (char *)&is_loop, &size) == -1) - { - Handler().LogError(this, "IsMulticastLoop", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } - return is_loop ? true : false; -} - -void UdpSocket::AddMulticastMembership(const std::string& group, const std::string& local_if, int if_index) -{ - if (GetSocket() == INVALID_SOCKET) - { - CreateConnection(); - } -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - struct ipv6_mreq x; - struct in6_addr addr; - if (Utility::u2ip( group, addr )) - { - x.ipv6mr_multiaddr = addr; - x.ipv6mr_interface = if_index; - if (setsockopt(GetSocket(), IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, (char *)&x, sizeof(struct ipv6_mreq)) == -1) - { - Handler().LogError(this, "AddMulticastMembership", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } - } - return; - } -#endif -#endif - struct ip_mreq x; // ip_mreqn - ipaddr_t addr; - if (Utility::u2ip( group, addr )) - { - memcpy(&x.imr_multiaddr.s_addr, &addr, sizeof(addr)); - Utility::u2ip( local_if, addr); - memcpy(&x.imr_interface.s_addr, &addr, sizeof(addr)); -// x.imr_ifindex = if_index; - if (setsockopt(GetSocket(), SOL_IP, IP_ADD_MEMBERSHIP, (char *)&x, sizeof(struct ip_mreq)) == -1) - { - Handler().LogError(this, "AddMulticastMembership", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } - } -} - -void UdpSocket::DropMulticastMembership(const std::string& group, const std::string& local_if, int if_index) -{ - if (GetSocket() == INVALID_SOCKET) - { - CreateConnection(); - } -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - struct ipv6_mreq x; - struct in6_addr addr; - if (Utility::u2ip( group, addr )) - { - x.ipv6mr_multiaddr = addr; - x.ipv6mr_interface = if_index; - if (setsockopt(GetSocket(), IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, (char *)&x, sizeof(struct ipv6_mreq)) == -1) - { - Handler().LogError(this, "DropMulticastMembership", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } - } - return; - } -#endif -#endif - struct ip_mreq x; // ip_mreqn - ipaddr_t addr; - if (Utility::u2ip( group, addr )) - { - memcpy(&x.imr_multiaddr.s_addr, &addr, sizeof(addr)); - Utility::u2ip( local_if, addr); - memcpy(&x.imr_interface.s_addr, &addr, sizeof(addr)); -// x.imr_ifindex = if_index; - if (setsockopt(GetSocket(), SOL_IP, IP_DROP_MEMBERSHIP, (char *)&x, sizeof(struct ip_mreq)) == -1) - { - Handler().LogError(this, "DropMulticastMembership", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } - } -} - -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 -void UdpSocket::SetMulticastHops(int hops) -{ - if (GetSocket() == INVALID_SOCKET) - { - CreateConnection(); - } - if (!IsIpv6()) - { - Handler().LogError(this, "SetMulticastHops", 0, "Ipv6 only", LOG_LEVEL_ERROR); - return; - } - if (setsockopt(GetSocket(), IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (char *)&hops, sizeof(int)) == -1) - { - Handler().LogError(this, "SetMulticastHops", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } -} - -int UdpSocket::GetMulticastHops() -{ - if (GetSocket() == INVALID_SOCKET) - { - CreateConnection(); - } - if (!IsIpv6()) - { - Handler().LogError(this, "SetMulticastHops", 0, "Ipv6 only", LOG_LEVEL_ERROR); - return -1; - } - int hops = 0; - socklen_t size = sizeof(int); - if (getsockopt(GetSocket(), IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (char *)&hops, &size) == -1) - { - Handler().LogError(this, "GetMulticastHops", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } - return hops; -} -#endif // IPPROTO_IPV6 -#endif - -bool UdpSocket::IsBound() -{ - return m_bind_ok; -} - -void UdpSocket::OnRawData(const char *buf, size_t len, struct sockaddr *sa, socklen_t sa_len) -{ -} - -void UdpSocket::OnRawData(const char *buf, size_t len, struct sockaddr *sa, socklen_t sa_len, struct timeval *ts) -{ -} - -port_t UdpSocket::GetPort() -{ - return m_port; -} - -int UdpSocket::GetLastSizeWritten() -{ - return m_last_size_written; -} - -void UdpSocket::SetTimestamp(bool x) -{ - m_b_read_ts = x; -} - -#ifdef SOCKETS_NAMESPACE -} -#endif - - diff --git a/externals/sockets/Utility.cpp b/externals/sockets/Utility.cpp deleted file mode 100644 index 7c093fc0832..00000000000 --- a/externals/sockets/Utility.cpp +++ /dev/null @@ -1,960 +0,0 @@ -/** \file Utility.cpp - ** \date 2004-02-13 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#include "Utility.h" -#include "Parse.h" -#include "Ipv4Address.h" -#include "Ipv6Address.h" -#include "Base64.h" -#include -#ifdef _WIN32 -#include -#else -#include -#include -#endif -#include - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -// defines for the random number generator -#define TWIST_IA 397 -#define TWIST_IB (TWIST_LEN - TWIST_IA) -#define UMASK 0x80000000 -#define LMASK 0x7FFFFFFF -#define MATRIX_A 0x9908B0DF -#define TWIST(b,i,j) ((b)[i] & UMASK) | ((b)[j] & LMASK) -#define MAGIC_TWIST(s) (((s) & 1) * MATRIX_A) - -// statics -std::string Utility::m_host; -bool Utility::m_local_resolved = false; -ipaddr_t Utility::m_ip = 0; -std::string Utility::m_addr; -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 -struct in6_addr Utility::m_local_ip6; -std::string Utility::m_local_addr6; -#endif -#endif - -std::string Utility::base64(const std::string& str_in) -{ - std::string str; - Base64 m_b; - m_b.encode(str_in, str, false); // , false == do not add cr/lf - return str; -} - -std::string Utility::base64d(const std::string& str_in) -{ - std::string str; - Base64 m_b; - m_b.decode(str_in, str); - return str; -} - -std::string Utility::l2string(long l) -{ - std::string str; - char tmp[100]; - sprintf(tmp,"%ld",l); - str = tmp; - return str; -} - -std::string Utility::bigint2string(uint64_t l) -{ - std::string str; - uint64_t tmp = l; - while (tmp) - { - uint64_t a = tmp % 10; - str = (char)(a + 48) + str; - tmp /= 10; - } - if (str.empty()) - { - str = "0"; - } - return str; -} - -uint64_t Utility::atoi64(const std::string& str) -{ - uint64_t l = 0; - for (size_t i = 0; i < str.size(); i++) - { - l = l * 10 + str[i] - 48; - } - return l; -} - -unsigned int Utility::hex2unsigned(const std::string& str) -{ - unsigned int r = 0; - for (size_t i = 0; i < str.size(); i++) - { - r = r * 16 + str[i] - 48 - ((str[i] >= 'A') ? 7 : 0) - ((str[i] >= 'a') ? 32 : 0); - } - return r; -} - -/* -* Encode string per RFC1738 URL encoding rules -* tnx rstaveley -*/ -std::string Utility::rfc1738_encode(const std::string& src) -{ -static char hex[] = "0123456789ABCDEF"; - std::string dst; - for (size_t i = 0; i < src.size(); i++) - { - if (isalnum(src[i])) - { - dst += src[i]; - } - else - if (src[i] == ' ') - { - dst += '+'; - } - else - { - unsigned char c = static_cast(src[i]); - dst += '%'; - dst += hex[c / 16]; - dst += hex[c % 16]; - } - } - return dst; -} // rfc1738_encode - -/* -* Decode string per RFC1738 URL encoding rules -* tnx rstaveley -*/ -std::string Utility::rfc1738_decode(const std::string& src) -{ - std::string dst; - for (size_t i = 0; i < src.size(); i++) - { - if (src[i] == '%' && isxdigit(src[i + 1]) && isxdigit(src[i + 2])) - { - char c1 = src[++i]; - char c2 = src[++i]; - c1 = c1 - 48 - ((c1 >= 'A') ? 7 : 0) - ((c1 >= 'a') ? 32 : 0); - c2 = c2 - 48 - ((c2 >= 'A') ? 7 : 0) - ((c2 >= 'a') ? 32 : 0); - dst += (char)(c1 * 16 + c2); - } - else - if (src[i] == '+') - { - dst += ' '; - } - else - { - dst += src[i]; - } - } - return dst; -} // rfc1738_decode - -bool Utility::isipv4(const std::string& str) -{ - int dots = 0; - // %! ignore :port? - for (size_t i = 0; i < str.size(); i++) - { - if (str[i] == '.') - dots++; - else - if (!isdigit(str[i])) - return false; - } - if (dots != 3) - return false; - return true; -} - -bool Utility::isipv6(const std::string& str) -{ - size_t qc = 0; - size_t qd = 0; - for (size_t i = 0; i < str.size(); i++) - { - qc += (str[i] == ':') ? 1 : 0; - qd += (str[i] == '.') ? 1 : 0; - } - if (qc > 7) - { - return false; - } - if (qd && qd != 3) - { - return false; - } - Parse pa(str,":."); - std::string tmp = pa.getword(); - while (!tmp.empty()) - { - if (tmp.size() > 4) - { - return false; - } - for (size_t i = 0; i < tmp.size(); i++) - { - if (tmp[i] < '0' || (tmp[i] > '9' && tmp[i] < 'A') || - (tmp[i] > 'F' && tmp[i] < 'a') || tmp[i] > 'f') - { - return false; - } - } - // - tmp = pa.getword(); - } - return true; -} - -bool Utility::u2ip(const std::string& str, ipaddr_t& l) -{ - struct sockaddr_in sa; - bool r = Utility::u2ip(str, sa); - memcpy(&l, &sa.sin_addr, sizeof(l)); - return r; -} - -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 -bool Utility::u2ip(const std::string& str, struct in6_addr& l) -{ - struct sockaddr_in6 sa; - bool r = Utility::u2ip(str, sa); - l = sa.sin6_addr; - return r; -} -#endif -#endif - -void Utility::l2ip(const ipaddr_t ip, std::string& str) -{ - struct sockaddr_in sa; - memset(&sa, 0, sizeof(sa)); - sa.sin_family = AF_INET; - memcpy(&sa.sin_addr, &ip, sizeof(sa.sin_addr)); - Utility::reverse( (struct sockaddr *)&sa, sizeof(sa), str, NI_NUMERICHOST); -} - -void Utility::l2ip(const in_addr& ip, std::string& str) -{ - struct sockaddr_in sa; - memset(&sa, 0, sizeof(sa)); - sa.sin_family = AF_INET; - sa.sin_addr = ip; - Utility::reverse( (struct sockaddr *)&sa, sizeof(sa), str, NI_NUMERICHOST); -} - -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 -void Utility::l2ip(const struct in6_addr& ip, std::string& str,bool mixed) -{ - char slask[100]; // l2ip temporary - *slask = 0; - unsigned int prev = 0; - bool skipped = false; - bool ok_to_skip = true; - if (mixed) - { - unsigned short x; - unsigned short addr16[8]; - memcpy(addr16, &ip, sizeof(addr16)); - for (size_t i = 0; i < 6; i++) - { - x = ntohs(addr16[i]); - if (*slask && (x || !ok_to_skip || prev)) - strcat(slask,":"); - if (x || !ok_to_skip) - { - sprintf(slask + strlen(slask),"%x", x); - if (x && skipped) - ok_to_skip = false; - } - else - { - skipped = true; - } - prev = x; - } - x = ntohs(addr16[6]); - sprintf(slask + strlen(slask),":%u.%u",x / 256,x & 255); - x = ntohs(addr16[7]); - sprintf(slask + strlen(slask),".%u.%u",x / 256,x & 255); - } - else - { - struct sockaddr_in6 sa; - memset(&sa, 0, sizeof(sa)); - sa.sin6_family = AF_INET6; - sa.sin6_addr = ip; - Utility::reverse( (struct sockaddr *)&sa, sizeof(sa), str, NI_NUMERICHOST); - return; - } - str = slask; -} - -int Utility::in6_addr_compare(in6_addr a,in6_addr b) -{ - for (size_t i = 0; i < 16; i++) - { - if (a.s6_addr[i] < b.s6_addr[i]) - return -1; - if (a.s6_addr[i] > b.s6_addr[i]) - return 1; - } - return 0; -} -#endif -#endif - -void Utility::ResolveLocal() -{ - char h[256]; - - // get local hostname and translate into ip-address - *h = 0; - gethostname(h,255); - { - if (Utility::u2ip(h, m_ip)) - { - Utility::l2ip(m_ip, m_addr); - } - } -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - memset(&m_local_ip6, 0, sizeof(m_local_ip6)); - { - if (Utility::u2ip(h, m_local_ip6)) - { - Utility::l2ip(m_local_ip6, m_local_addr6); - } - } -#endif -#endif - m_host = h; - m_local_resolved = true; -} - -const std::string& Utility::GetLocalHostname() -{ - if (!m_local_resolved) - { - ResolveLocal(); - } - return m_host; -} - -ipaddr_t Utility::GetLocalIP() -{ - if (!m_local_resolved) - { - ResolveLocal(); - } - return m_ip; -} - -const std::string& Utility::GetLocalAddress() -{ - if (!m_local_resolved) - { - ResolveLocal(); - } - return m_addr; -} - -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 -const struct in6_addr& Utility::GetLocalIP6() -{ - if (!m_local_resolved) - { - ResolveLocal(); - } - return m_local_ip6; -} - -const std::string& Utility::GetLocalAddress6() -{ - if (!m_local_resolved) - { - ResolveLocal(); - } - return m_local_addr6; -} -#endif -#endif - -void Utility::SetEnv(const std::string& var,const std::string& value) -{ -#if (defined(SOLARIS8) || defined(SOLARIS)) - { - static std::map vmap; - if (vmap.find(var) != vmap.end()) - { - delete[] vmap[var]; - } - vmap[var] = new char[var.size() + 1 + value.size() + 1]; - sprintf(vmap[var], "%s=%s", var.c_str(), value.c_str()); - putenv( vmap[var] ); - } -#elif defined _WIN32 - { - std::string slask = var + "=" + value; - _putenv( (char *)slask.c_str()); - } -#else - setenv(var.c_str(), value.c_str(), 1); -#endif -} - -std::string Utility::Sa2String(struct sockaddr *sa) -{ -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (sa -> sa_family == AF_INET6) - { - struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)sa; - std::string tmp; - Utility::l2ip(sa6 -> sin6_addr, tmp); - return tmp + ":" + Utility::l2string(ntohs(sa6 -> sin6_port)); - } -#endif -#endif - if (sa -> sa_family == AF_INET) - { - struct sockaddr_in *sa4 = (struct sockaddr_in *)sa; - ipaddr_t a; - memcpy(&a, &sa4 -> sin_addr, 4); - std::string tmp; - Utility::l2ip(a, tmp); - return tmp + ":" + Utility::l2string(ntohs(sa4 -> sin_port)); - } - return ""; -} - -void Utility::GetTime(struct timeval *p) -{ -#ifdef _WIN32 - FILETIME ft; // Contains a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC). - GetSystemTimeAsFileTime(&ft); - uint64_t tt; - memcpy(&tt, &ft, sizeof(tt)); - tt /= 10; // make it usecs - p->tv_sec = (long)tt / 1000000; - p->tv_usec = (long)tt % 1000000; -#else - gettimeofday(p, NULL); -#endif -} - -std::auto_ptr Utility::CreateAddress(struct sockaddr *sa,socklen_t sa_len) -{ - switch (sa -> sa_family) - { - case AF_INET: - if (sa_len == sizeof(struct sockaddr_in)) - { - struct sockaddr_in *p = (struct sockaddr_in *)sa; - return std::auto_ptr(new Ipv4Address(*p)); - } - break; -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - case AF_INET6: - if (sa_len == sizeof(struct sockaddr_in6)) - { - struct sockaddr_in6 *p = (struct sockaddr_in6 *)sa; - return std::auto_ptr(new Ipv6Address(*p)); - } - break; -#endif -#endif - } - return std::auto_ptr(NULL); -} - -bool Utility::u2ip(const std::string& host, struct sockaddr_in& sa, int ai_flags) -{ - memset(&sa, 0, sizeof(sa)); - sa.sin_family = AF_INET; -#ifdef NO_GETADDRINFO - if ((ai_flags & AI_NUMERICHOST) != 0 || isipv4(host)) - { - Parse pa((char *)host.c_str(), "."); - union { - struct { - unsigned char b1; - unsigned char b2; - unsigned char b3; - unsigned char b4; - } a; - ipaddr_t l; - } u; - u.a.b1 = static_cast(pa.getvalue()); - u.a.b2 = static_cast(pa.getvalue()); - u.a.b3 = static_cast(pa.getvalue()); - u.a.b4 = static_cast(pa.getvalue()); - memcpy(&sa.sin_addr, &u.l, sizeof(sa.sin_addr)); - return true; - } -#ifndef LINUX - struct hostent *he = gethostbyname( host.c_str() ); - if (!he) - { - return false; - } - memcpy(&sa.sin_addr, he -> h_addr, sizeof(sa.sin_addr)); -#else - struct hostent he; - struct hostent *result = NULL; - int myerrno = 0; - char buf[2000]; - int n = gethostbyname_r(host.c_str(), &he, buf, sizeof(buf), &result, &myerrno); - if (n || !result) - { - return false; - } - if (he.h_addr_list && he.h_addr_list[0]) - memcpy(&sa.sin_addr, he.h_addr, 4); - else - return false; -#endif - return true; -#else - struct addrinfo hints; - memset(&hints, 0, sizeof(hints)); - // AI_NUMERICHOST - // AI_CANONNAME - // AI_PASSIVE - server - // AI_ADDRCONFIG - // AI_V4MAPPED - // AI_ALL - // AI_NUMERICSERV - hints.ai_flags = ai_flags; - hints.ai_family = AF_INET; - hints.ai_socktype = 0; - hints.ai_protocol = 0; - struct addrinfo *res; - if (Utility::isipv4(host)) - hints.ai_flags |= AI_NUMERICHOST; - int n = getaddrinfo(host.c_str(), NULL, &hints, &res); - if (!n) - { - std::vector vec; - struct addrinfo *ai = res; - while (ai) - { - if (ai -> ai_addrlen == sizeof(sa)) - vec.push_back( ai ); - ai = ai -> ai_next; - } - if (vec.empty()) - return false; - ai = vec[Utility::Rnd() % vec.size()]; - { - memcpy(&sa, ai -> ai_addr, ai -> ai_addrlen); - } - freeaddrinfo(res); - return true; - } - std::string error = "Error: "; -#ifndef __CYGWIN__ - error += gai_strerror(n); -#endif - return false; -#endif // NO_GETADDRINFO -} - -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 -bool Utility::u2ip(const std::string& host, struct sockaddr_in6& sa, int ai_flags) -{ - memset(&sa, 0, sizeof(sa)); - sa.sin6_family = AF_INET6; -#ifdef NO_GETADDRINFO - if ((ai_flags & AI_NUMERICHOST) != 0 || isipv6(host)) - { - std::list vec; - size_t x = 0; - for (size_t i = 0; i <= host.size(); i++) - { - if (i == host.size() || host[i] == ':') - { - std::string s = host.substr(x, i - x); - // - if (strstr(s.c_str(),".")) // x.x.x.x - { - Parse pa(s,"."); - char slask[100]; // u2ip temporary hex2string conversion - unsigned long b0 = static_cast(pa.getvalue()); - unsigned long b1 = static_cast(pa.getvalue()); - unsigned long b2 = static_cast(pa.getvalue()); - unsigned long b3 = static_cast(pa.getvalue()); - sprintf(slask,"%lx",b0 * 256 + b1); - vec.push_back(slask); - sprintf(slask,"%lx",b2 * 256 + b3); - vec.push_back(slask); - } - else - { - vec.push_back(s); - } - // - x = i + 1; - } - } - size_t sz = vec.size(); // number of byte pairs - size_t i = 0; // index in in6_addr.in6_u.u6_addr16[] ( 0 .. 7 ) - unsigned short addr16[8]; - for (std::list::iterator it = vec.begin(); it != vec.end(); it++) - { - std::string bytepair = *it; - if (!bytepair.empty()) - { - addr16[i++] = htons(Utility::hex2unsigned(bytepair)); - } - else - { - addr16[i++] = 0; - while (sz++ < 8) - { - addr16[i++] = 0; - } - } - } - memcpy(&sa.sin6_addr, addr16, sizeof(addr16)); - return true; - } -#ifdef SOLARIS - int errnum = 0; - struct hostent *he = getipnodebyname( host.c_str(), AF_INET6, 0, &errnum ); -#else - struct hostent *he = gethostbyname2( host.c_str(), AF_INET6 ); -#endif - if (!he) - { - return false; - } - memcpy(&sa.sin6_addr,he -> h_addr_list[0],he -> h_length); -#ifdef SOLARIS - free(he); -#endif - return true; -#else - struct addrinfo hints; - memset(&hints, 0, sizeof(hints)); - hints.ai_flags = ai_flags; - hints.ai_family = AF_INET6; - hints.ai_socktype = 0; - hints.ai_protocol = 0; - struct addrinfo *res; - if (Utility::isipv6(host)) - hints.ai_flags |= AI_NUMERICHOST; - int n = getaddrinfo(host.c_str(), NULL, &hints, &res); - if (!n) - { - std::vector vec; - struct addrinfo *ai = res; - while (ai) - { - if (ai -> ai_addrlen == sizeof(sa)) - vec.push_back( ai ); - ai = ai -> ai_next; - } - if (vec.empty()) - return false; - ai = vec[Utility::Rnd() % vec.size()]; - { - memcpy(&sa, ai -> ai_addr, ai -> ai_addrlen); - } - freeaddrinfo(res); - return true; - } - std::string error = "Error: "; -#ifndef __CYGWIN__ - error += gai_strerror(n); -#endif - return false; -#endif // NO_GETADDRINFO -} -#endif // IPPROTO_IPV6 -#endif // ENABLE_IPV6 - -bool Utility::reverse(struct sockaddr *sa, socklen_t sa_len, std::string& hostname, int flags) -{ - std::string service; - return Utility::reverse(sa, sa_len, hostname, service, flags); -} - -bool Utility::reverse(struct sockaddr *sa, socklen_t sa_len, std::string& hostname, std::string& service, int flags) -{ - hostname = ""; - service = ""; -#ifdef NO_GETADDRINFO - switch (sa -> sa_family) - { - case AF_INET: - if (flags & NI_NUMERICHOST) - { - union { - struct { - unsigned char b1; - unsigned char b2; - unsigned char b3; - unsigned char b4; - } a; - ipaddr_t l; - } u; - struct sockaddr_in *sa_in = (struct sockaddr_in *)sa; - memcpy(&u.l, &sa_in -> sin_addr, sizeof(u.l)); - char tmp[100]; - sprintf(tmp, "%u.%u.%u.%u", u.a.b1, u.a.b2, u.a.b3, u.a.b4); - hostname = tmp; - return true; - } - else - { - struct sockaddr_in *sa_in = (struct sockaddr_in *)sa; - struct hostent *h = gethostbyaddr( (const char *)&sa_in -> sin_addr, sizeof(sa_in -> sin_addr), AF_INET); - if (h) - { - hostname = h -> h_name; - return true; - } - } - break; -#ifdef ENABLE_IPV6 - case AF_INET6: - if (flags & NI_NUMERICHOST) - { - char slask[100]; // l2ip temporary - *slask = 0; - unsigned int prev = 0; - bool skipped = false; - bool ok_to_skip = true; - { - unsigned short addr16[8]; - struct sockaddr_in6 *sa_in6 = (struct sockaddr_in6 *)sa; - memcpy(addr16, &sa_in6 -> sin6_addr, sizeof(addr16)); - for (size_t i = 0; i < 8; i++) - { - unsigned short x = ntohs(addr16[i]); - if (*slask && (x || !ok_to_skip || prev)) - strcat(slask,":"); - if (x || !ok_to_skip) - { - sprintf(slask + strlen(slask),"%x", x); - if (x && skipped) - ok_to_skip = false; - } - else - { - skipped = true; - } - prev = x; - } - } - if (!*slask) - strcpy(slask, "::"); - hostname = slask; - return true; - } - else - { - // %! TODO: ipv6 reverse lookup - struct sockaddr_in6 *sa_in = (struct sockaddr_in6 *)sa; - struct hostent *h = gethostbyaddr( (const char *)&sa_in -> sin6_addr, sizeof(sa_in -> sin6_addr), AF_INET6); - if (h) - { - hostname = h -> h_name; - return true; - } - } - break; -#endif - } - return false; -#else - char host[NI_MAXHOST]; - char serv[NI_MAXSERV]; - // NI_NOFQDN - // NI_NUMERICHOST - // NI_NAMEREQD - // NI_NUMERICSERV - // NI_DGRAM - int n = getnameinfo(sa, sa_len, host, sizeof(host), serv, sizeof(serv), flags); - if (n) - { - // EAI_AGAIN - // EAI_BADFLAGS - // EAI_FAIL - // EAI_FAMILY - // EAI_MEMORY - // EAI_NONAME - // EAI_OVERFLOW - // EAI_SYSTEM - return false; - } - hostname = host; - service = serv; - return true; -#endif // NO_GETADDRINFO -} - -bool Utility::u2service(const std::string& name, int& service, int ai_flags) -{ -#ifdef NO_GETADDRINFO - // %! - return false; -#else - struct addrinfo hints; - service = 0; - memset(&hints, 0, sizeof(hints)); - // AI_NUMERICHOST - // AI_CANONNAME - // AI_PASSIVE - server - // AI_ADDRCONFIG - // AI_V4MAPPED - // AI_ALL - // AI_NUMERICSERV - hints.ai_flags = ai_flags; - hints.ai_family = AF_UNSPEC; - hints.ai_socktype = 0; - hints.ai_protocol = 0; - struct addrinfo *res; - int n = getaddrinfo(NULL, name.c_str(), &hints, &res); - if (!n) - { - service = res -> ai_protocol; - freeaddrinfo(res); - return true; - } - return false; -#endif // NO_GETADDRINFO -} - -unsigned long Utility::ThreadID() -{ -#ifdef _WIN32 - return GetCurrentThreadId(); -#else - return (unsigned long)pthread_self(); -#endif -} - -std::string Utility::ToLower(const std::string& str) -{ - std::string r; - for (size_t i = 0; i < str.size(); i++) - { - if (str[i] >= 'A' && str[i] <= 'Z') - r += str[i] | 32; - else - r += str[i]; - } - return r; -} - -std::string Utility::ToUpper(const std::string& str) -{ - std::string r; - for (size_t i = 0; i < str.size(); i++) - { - if (str[i] >= 'a' && str[i] <= 'z') - r += (char)(str[i] - 32); - else - r += str[i]; - } - return r; -} - -std::string Utility::ToString(double d) -{ - char tmp[100]; - sprintf(tmp, "%f", d); - return tmp; -} - -unsigned long Utility::Rnd() -{ -static Utility::Rng generator( (unsigned long)time(NULL) ); - return generator.Get(); -} - -Utility::Rng::Rng(unsigned long seed) : m_value( 0 ) -{ - m_tmp[0]= seed & 0xffffffffUL; - for (int i = 1; i < TWIST_LEN; i++) - { - m_tmp[i] = (1812433253UL * (m_tmp[i - 1] ^ (m_tmp[i - 1] >> 30)) + i); - } -} - -unsigned long Utility::Rng::Get() -{ - unsigned long val = m_tmp[m_value]; - ++m_value; - if (m_value == TWIST_LEN) - { - for (int i = 0; i < TWIST_IB; ++i) - { - unsigned long s = TWIST(m_tmp, i, i + 1); - m_tmp[i] = m_tmp[i + TWIST_IA] ^ (s >> 1) ^ MAGIC_TWIST(s); - } - { - for (int i = 0; i < TWIST_LEN - 1; ++i) - { - unsigned long s = TWIST(m_tmp, i, i + 1); - m_tmp[i] = m_tmp[i - TWIST_IB] ^ (s >> 1) ^ MAGIC_TWIST(s); - } - } - unsigned long s = TWIST(m_tmp, TWIST_LEN - 1, 0); - m_tmp[TWIST_LEN - 1] = m_tmp[TWIST_IA - 1] ^ (s >> 1) ^ MAGIC_TWIST(s); - - m_value = 0; - } - return val; -} - -#ifdef SOCKETS_NAMESPACE -} -#endif - - diff --git a/externals/sockets/include/Base64.h b/externals/sockets/include/Base64.h deleted file mode 100644 index d4323aaa019..00000000000 --- a/externals/sockets/include/Base64.h +++ /dev/null @@ -1,77 +0,0 @@ -/** \file Base64.h - ** \date 2004-02-13 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_Base64_H -#define _SOCKETS_Base64_H - -#include "sockets-config.h" -#ifdef _MSC_VER -#pragma warning(disable:4514) -#endif - -#include -#include - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/** \defgroup util Utilities */ - -/** Base64 encode/decode. - \ingroup util */ -class Base64 -{ -public: - Base64(); - - void encode(FILE *, std::string& , bool add_crlf = true); - void encode(const std::string&, std::string& , bool add_crlf = true); - void encode(const char *, size_t, std::string& , bool add_crlf = true); - void encode(const unsigned char *, size_t, std::string& , bool add_crlf = true); - - void decode(const std::string&, std::string& ); - void decode(const std::string&, unsigned char *, size_t&); - - size_t decode_length(const std::string& ); - -private: - Base64(const Base64& ) {} - Base64& operator=(const Base64& ) { return *this; } -static const char *bstr; -static const char rstr[128]; -}; - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // _SOCKETS_Base64_H - - diff --git a/externals/sockets/include/Exception.h b/externals/sockets/include/Exception.h deleted file mode 100644 index bb881b2d74f..00000000000 --- a/externals/sockets/include/Exception.h +++ /dev/null @@ -1,55 +0,0 @@ -/** - ** \file Exception.h - ** \date 2007-09-28 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2007 Anders Hedstrom - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _Sockets_Exception_H -#define _Sockets_Exception_H - -#include - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -class Exception -{ -public: - Exception(const std::string& description); - virtual ~Exception() {} - - virtual const std::string ToString() const; - - Exception(const Exception& ) {} // copy constructor - - Exception& operator=(const Exception& ) { return *this; } // assignment operator - -private: - std::string m_description; - -}; - -#ifdef SOCKETS_NAMESPACE -} // namespace SOCKETS_NAMESPACE { -#endif - -#endif // _Sockets_Exception_H - - diff --git a/externals/sockets/include/File.h b/externals/sockets/include/File.h deleted file mode 100644 index ed322efa2d8..00000000000 --- a/externals/sockets/include/File.h +++ /dev/null @@ -1,82 +0,0 @@ -/** \file File.h - ** \date 2005-04-25 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_File_H -#define _SOCKETS_File_H - -#include "sockets-config.h" -#include "IFile.h" -#include - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/** IFile implementation of a disk file. - \ingroup file */ -class File : public IFile -{ -public: - File(); - ~File(); - - bool fopen(const std::string&, const std::string&); - void fclose(); - - size_t fread(char *, size_t, size_t) const; - size_t fwrite(const char *, size_t, size_t); - - char *fgets(char *, int) const; - void fprintf(const char *format, ...); - - off_t size() const; - bool eof() const; - - void reset_read() const; - void reset_write(); - -private: - File(const File& ) {} // copy constructor - File& operator=(const File& ) { return *this; } // assignment operator - - std::string m_path; - std::string m_mode; - FILE *m_fil; - mutable long m_rptr; - long m_wptr; -}; - - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // _SOCKETS_File_H - - diff --git a/externals/sockets/include/IFile.h b/externals/sockets/include/IFile.h deleted file mode 100644 index 657c8a4b1d9..00000000000 --- a/externals/sockets/include/IFile.h +++ /dev/null @@ -1,71 +0,0 @@ -/** \file IFile.h - ** \date 2005-04-25 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_IFile_H -#define _SOCKETS_IFile_H - -#include "sockets-config.h" -#include - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/** \defgroup file File handling */ -/** Pure virtual file I/O interface. - \ingroup file */ -class IFile -{ -public: - virtual ~IFile() {} - - virtual bool fopen(const std::string&, const std::string&) = 0; - virtual void fclose() = 0; - - virtual size_t fread(char *, size_t, size_t) const = 0; - virtual size_t fwrite(const char *, size_t, size_t) = 0; - - virtual char *fgets(char *, int) const = 0; - virtual void fprintf(const char *format, ...) = 0; - - virtual off_t size() const = 0; - virtual bool eof() const = 0; - - virtual void reset_read() const = 0; - virtual void reset_write() = 0; - -}; - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // _SOCKETS_IFile_H - - diff --git a/externals/sockets/include/ISocketHandler.h b/externals/sockets/include/ISocketHandler.h deleted file mode 100644 index 940783c104b..00000000000 --- a/externals/sockets/include/ISocketHandler.h +++ /dev/null @@ -1,231 +0,0 @@ -/** \file ISocketHandler.h - ** \date 2004-02-13 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_ISocketHandler_H -#define _SOCKETS_ISocketHandler_H -#include "sockets-config.h" - -#include - -#include "socket_include.h" -#include "Socket.h" -#include "StdLog.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -typedef enum { - LIST_CALLONCONNECT = 0, -#ifdef ENABLE_DETACH - LIST_DETACH, -#endif - LIST_TIMEOUT, - LIST_RETRY, - LIST_CLOSE -} list_t; - -class SocketAddress; -class Mutex; - -/** Socket container class, event generator. - \ingroup basic */ -class ISocketHandler -{ - friend class Socket; - -public: - /** Connection pool class for internal use by the ISocketHandler. - \ingroup internal */ -#ifdef ENABLE_POOL - class PoolSocket : public Socket - { - public: - PoolSocket(ISocketHandler& h,Socket *src) : Socket(h) { - CopyConnection( src ); - SetIsClient(); - } - - void OnRead() { - Handler().LogError(this, "OnRead", 0, "data on hibernating socket", LOG_LEVEL_FATAL); - SetCloseAndDelete(); - } - void OnOptions(int,int,int,SOCKET) {} - - }; -#endif - -public: - virtual ~ISocketHandler() {} - - /** Get mutex reference for threadsafe operations. */ - virtual Mutex& GetMutex() const = 0; - - /** Register StdLog object for error callback. - \param log Pointer to log class */ - virtual void RegStdLog(StdLog *log) = 0; - - /** Log error to log class for print out / storage. */ - virtual void LogError(Socket *p,const std::string& user_text,int err,const std::string& sys_err,loglevel_t t = LOG_LEVEL_WARNING) = 0; - - // ------------------------------------------------------------------------- - // Socket stuff - // ------------------------------------------------------------------------- - /** Add socket instance to socket map. Removal is always automatic. */ - virtual void Add(Socket *) = 0; -private: - /** Remove socket from socket map, used by Socket class. */ - virtual void Remove(Socket *) = 0; -public: - /** Get status of read/write/exception file descriptor set for a socket. */ - virtual void Get(SOCKET s,bool& r,bool& w,bool& e) = 0; - /** Set read/write/exception file descriptor sets (fd_set). */ - virtual void Set(SOCKET s,bool bRead,bool bWrite,bool bException = true) = 0; - - /** Wait for events, generate callbacks. */ - virtual int Select(long sec,long usec) = 0; - /** This method will not return until an event has been detected. */ - virtual int Select() = 0; - /** Wait for events, generate callbacks. */ - virtual int Select(struct timeval *tsel) = 0; - - /** Check that a socket really is handled by this socket handler. */ - virtual bool Valid(Socket *) = 0; - /** Return number of sockets handled by this handler. */ - virtual size_t GetCount() = 0; - - /** Override and return false to deny all incoming connections. - \param p ListenSocket class pointer (use GetPort to identify which one) */ - virtual bool OkToAccept(Socket *p) = 0; - - /** Called by Socket when a socket changes state. */ - virtual void AddList(SOCKET s,list_t which_one,bool add) = 0; - - // ------------------------------------------------------------------------- - // Connection pool - // ------------------------------------------------------------------------- -#ifdef ENABLE_POOL - /** Find available open connection (used by connection pool). */ - virtual ISocketHandler::PoolSocket *FindConnection(int type,const std::string& protocol,SocketAddress&) = 0; - /** Enable connection pool (by default disabled). */ - virtual void EnablePool(bool = true) = 0; - /** Check pool status. - \return true if connection pool is enabled */ - virtual bool PoolEnabled() = 0; -#endif // ENABLE_POOL - - // ------------------------------------------------------------------------- - // Socks4 - // ------------------------------------------------------------------------- -#ifdef ENABLE_SOCKS4 - /** Set socks4 server ip that all new tcp sockets should use. */ - virtual void SetSocks4Host(ipaddr_t) = 0; - /** Set socks4 server hostname that all new tcp sockets should use. */ - virtual void SetSocks4Host(const std::string& ) = 0; - /** Set socks4 server port number that all new tcp sockets should use. */ - virtual void SetSocks4Port(port_t) = 0; - /** Set optional socks4 userid. */ - virtual void SetSocks4Userid(const std::string& ) = 0; - /** If connection to socks4 server fails, immediately try direct connection to final host. */ - virtual void SetSocks4TryDirect(bool = true) = 0; - /** Get socks4 server ip. - \return socks4 server ip */ - virtual ipaddr_t GetSocks4Host() = 0; - /** Get socks4 port number. - \return socks4 port number */ - virtual port_t GetSocks4Port() = 0; - /** Get socks4 userid (optional). - \return socks4 userid */ - virtual const std::string& GetSocks4Userid() = 0; - /** Check status of socks4 try direct flag. - \return true if direct connection should be tried if connection to socks4 server fails */ - virtual bool Socks4TryDirect() = 0; -#endif // ENABLE_SOCKS4 - - // ------------------------------------------------------------------------- - // DNS resolve server - // ------------------------------------------------------------------------- -#ifdef ENABLE_RESOLVER - /** Enable asynchronous DNS. - \param port Listen port of asynchronous dns server */ - virtual void EnableResolver(port_t = 16667) = 0; - /** Check resolver status. - \return true if resolver is enabled */ - virtual bool ResolverEnabled() = 0; - /** Queue a dns request. - \param host Hostname to be resolved - \param port Port number will be echoed in Socket::OnResolved callback */ - virtual int Resolve(Socket *,const std::string& host,port_t port) = 0; -#ifdef ENABLE_IPV6 - virtual int Resolve6(Socket *,const std::string& host,port_t port) = 0; -#endif - /** Do a reverse dns lookup. */ - virtual int Resolve(Socket *,ipaddr_t a) = 0; -#ifdef ENABLE_IPV6 - virtual int Resolve(Socket *,in6_addr& a) = 0; -#endif - /** Get listen port of asynchronous dns server. */ - virtual port_t GetResolverPort() = 0; - /** Resolver thread ready for queries. */ - virtual bool ResolverReady() = 0; - /** Returns true if socket waiting for a resolve event. */ - virtual bool Resolving(Socket *) = 0; -#endif // ENABLE_RESOLVER - -#ifdef ENABLE_TRIGGERS - /** Fetch unique trigger id. */ - virtual int TriggerID(Socket *src) = 0; - /** Subscribe socket to trigger id. */ - virtual bool Subscribe(int id, Socket *dst) = 0; - /** Unsubscribe socket from trigger id. */ - virtual bool Unsubscribe(int id, Socket *dst) = 0; - /** Execute OnTrigger for subscribed sockets. - \param id Trigger ID - \param data Data passed from source to destination - \param erase Empty trigger id source and destination maps if 'true', - Leave them in place if 'false' - if a trigger should be called many times */ - virtual void Trigger(int id, Socket::TriggerData& data, bool erase = true) = 0; -#endif // ENABLE_TRIGGERS - -#ifdef ENABLE_DETACH - /** Indicates that the handler runs under SocketThread. */ - virtual void SetSlave(bool x = true) = 0; - /** Indicates that the handler runs under SocketThread. */ - virtual bool IsSlave() = 0; -#endif // ENABLE_DETACH - -}; - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // _SOCKETS_ISocketHandler_H - - diff --git a/externals/sockets/include/Ipv4Address.h b/externals/sockets/include/Ipv4Address.h deleted file mode 100644 index 71d925254e9..00000000000 --- a/externals/sockets/include/Ipv4Address.h +++ /dev/null @@ -1,95 +0,0 @@ -/** - ** \file Ipv4Address.h - ** \date 2006-09-21 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2007 Anders Hedstrom - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_Ipv4Address_H -#define _SOCKETS_Ipv4Address_H - -#include "sockets-config.h" -#include "SocketAddress.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/* Ipv4 address implementation. - \ingroup basic */ -class Ipv4Address : public SocketAddress -{ -public: - /** Create empty Ipv4 address structure. - \param port Port number */ - Ipv4Address(port_t port = 0); - /** Create Ipv4 address structure. - \param a Socket address in network byte order (as returned by Utility::u2ip) - \param port Port number in host byte order */ - Ipv4Address(ipaddr_t a,port_t port); - /** Create Ipv4 address structure. - \param a Socket address in network byte order - \param port Port number in host byte order */ - Ipv4Address(struct in_addr& a,port_t port); - /** Create Ipv4 address structure. - \param host Hostname to be resolved - \param port Port number in host byte order */ - Ipv4Address(const std::string& host,port_t port); - Ipv4Address(struct sockaddr_in&); - ~Ipv4Address(); - - // SocketAddress implementation - - operator struct sockaddr *(); - operator socklen_t(); - bool operator==(SocketAddress&); - - void SetPort(port_t port); - port_t GetPort(); - - void SetAddress(struct sockaddr *sa); - int GetFamily(); - - bool IsValid(); - std::auto_ptr GetCopy(); - - /** Convert address struct to text. */ - std::string Convert(bool include_port = false); - std::string Reverse(); - - /** Resolve hostname. */ -static bool Resolve(const std::string& hostname,struct in_addr& a); - /** Reverse resolve (IP to hostname). */ -static bool Reverse(struct in_addr& a,std::string& name); - /** Convert address struct to text. */ -static std::string Convert(struct in_addr& a); - -private: - Ipv4Address(const Ipv4Address& ) {} // copy constructor - Ipv4Address& operator=(const Ipv4Address& ) { return *this; } // assignment operator - struct sockaddr_in m_addr; - bool m_valid; -}; - - -#ifdef SOCKETS_NAMESPACE -} // namespace SOCKETS_NAMESPACE { -#endif -#endif // _SOCKETS_Ipv4Address_H - - diff --git a/externals/sockets/include/Ipv6Address.h b/externals/sockets/include/Ipv6Address.h deleted file mode 100644 index 20c68d8c92d..00000000000 --- a/externals/sockets/include/Ipv6Address.h +++ /dev/null @@ -1,105 +0,0 @@ -/** - ** \file Ipv6Address.h - ** \date 2006-09-21 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2007 Anders Hedstrom - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_Ipv6Address_H -#define _SOCKETS_Ipv6Address_H -#include "sockets-config.h" -#ifdef ENABLE_IPV6 - -#include "SocketAddress.h" -#ifdef IPPROTO_IPV6 -#if defined( _WIN32) && !defined(__CYGWIN__) -typedef unsigned __int32 uint32_t; -#endif - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/** Ipv6 address implementation. - \ingroup basic */ -class Ipv6Address : public SocketAddress -{ -public: - /** Create empty Ipv6 address structure. - \param port Port number */ - Ipv6Address(port_t port = 0); - /** Create Ipv6 address structure. - \param a Socket address in network byte order - \param port Port number in host byte order */ - Ipv6Address(struct in6_addr& a,port_t port); - /** Create Ipv6 address structure. - \param host Hostname to be resolved - \param port Port number in host byte order */ - Ipv6Address(const std::string& host,port_t port); - Ipv6Address(struct sockaddr_in6&); - ~Ipv6Address(); - - // SocketAddress implementation - - operator struct sockaddr *(); - operator socklen_t(); - bool operator==(SocketAddress&); - - void SetPort(port_t port); - port_t GetPort(); - - void SetAddress(struct sockaddr *sa); - int GetFamily(); - - bool IsValid(); - std::auto_ptr GetCopy(); - - /** Convert address struct to text. */ - std::string Convert(bool include_port = false); - std::string Reverse(); - - /** Resolve hostname. */ -static bool Resolve(const std::string& hostname,struct in6_addr& a); - /** Reverse resolve (IP to hostname). */ -static bool Reverse(struct in6_addr& a,std::string& name); - /** Convert address struct to text. */ -static std::string Convert(struct in6_addr& a,bool mixed = false); - - void SetFlowinfo(uint32_t); - uint32_t GetFlowinfo(); -#ifndef _WIN32 - void SetScopeId(uint32_t); - uint32_t GetScopeId(); -#endif - -private: - Ipv6Address(const Ipv6Address& ) {} // copy constructor - Ipv6Address& operator=(const Ipv6Address& ) { return *this; } // assignment operator - struct sockaddr_in6 m_addr; - bool m_valid; -}; - - -#ifdef SOCKETS_NAMESPACE -} // namespace SOCKETS_NAMESPACE { -#endif -#endif // IPPROTO_IPV6 -#endif // ENABLE_IPV6 -#endif // _SOCKETS_Ipv6Address_H - - diff --git a/externals/sockets/include/ListenSocket.h b/externals/sockets/include/ListenSocket.h deleted file mode 100644 index 8934a809d0e..00000000000 --- a/externals/sockets/include/ListenSocket.h +++ /dev/null @@ -1,418 +0,0 @@ -/** \file ListenSocket.h - ** \date 2004-02-13 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_ListenSocket_H -#define _SOCKETS_ListenSocket_H -#include "sockets-config.h" - -#ifdef _WIN32 -#include -#else -#include -#endif - -#include "ISocketHandler.h" -#include "Socket.h" -#include "Utility.h" -#include "SctpSocket.h" -#include "Ipv4Address.h" -#include "Ipv6Address.h" -#ifdef ENABLE_EXCEPTIONS -#include "Exception.h" -#endif - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/** Binds incoming port number to new Socket class X. - \ingroup basic */ -template -class ListenSocket : public Socket -{ -public: - /** Constructor. - \param h ISocketHandler reference - \param use_creator Optional use of creator (default true) */ - ListenSocket(ISocketHandler& h,bool use_creator = true) : Socket(h), m_depth(0), m_creator(NULL) - ,m_bHasCreate(false) - { - if (use_creator) - { - m_creator = new X(h); - Socket *tmp = m_creator -> Create(); - if (tmp && dynamic_cast(tmp)) - { - m_bHasCreate = true; - } - if (tmp) - { - delete tmp; - } - } - } - ~ListenSocket() { - if (m_creator) - { - delete m_creator; - } - } - - /** Close file descriptor. */ - int Close() { - if (GetSocket() != INVALID_SOCKET) - { - closesocket(GetSocket()); - } - return 0; - } - - /** Bind and listen to any interface. - \param port Port (0 is random) - \param depth Listen queue depth */ - int Bind(port_t port,int depth = 20) { -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - Ipv6Address ad(port); - return Bind(ad, depth); - } - else -#endif -#endif - { - Ipv4Address ad(port); - return Bind(ad, depth); - } - } - - int Bind(SocketAddress& ad,int depth) { -#ifdef USE_SCTP - if (dynamic_cast(m_creator)) - { - return Bind(ad, "sctp", depth); - } -#endif - return Bind(ad, "tcp", depth); - } - - /** Bind and listen to any interface, with optional protocol. - \param port Port (0 is random) - \param protocol Network protocol - \param depth Listen queue depth */ - int Bind(port_t port,const std::string& protocol,int depth = 20) { -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - Ipv6Address ad(port); - return Bind(ad, protocol, depth); - } - else -#endif -#endif - { - Ipv4Address ad(port); - return Bind(ad, protocol, depth); - } - } - - /** Bind and listen to specific interface. - \param intf Interface hostname - \param port Port (0 is random) - \param depth Listen queue depth */ - int Bind(const std::string& intf,port_t port,int depth = 20) { -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - Ipv6Address ad(intf, port); - if (ad.IsValid()) - { - return Bind(ad, depth); - } - Handler().LogError(this, "Bind", 0, "name resolution of interface name failed", LOG_LEVEL_FATAL); - return -1; - } - else -#endif -#endif - { - Ipv4Address ad(intf, port); - if (ad.IsValid()) - { - return Bind(ad, depth); - } - Handler().LogError(this, "Bind", 0, "name resolution of interface name failed", LOG_LEVEL_FATAL); - return -1; - } - } - - /** Bind and listen to specific interface. - \param intf Interface hostname - \param port Port (0 is random) - \param protocol Network protocol - \param depth Listen queue depth */ - int Bind(const std::string& intf,port_t port,const std::string& protocol,int depth = 20) { -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - Ipv6Address ad(intf, port); - if (ad.IsValid()) - { - return Bind(ad, protocol, depth); - } - Handler().LogError(this, "Bind", 0, "name resolution of interface name failed", LOG_LEVEL_FATAL); - return -1; - } - else -#endif -#endif - { - Ipv4Address ad(intf, port); - if (ad.IsValid()) - { - return Bind(ad, protocol, depth); - } - Handler().LogError(this, "Bind", 0, "name resolution of interface name failed", LOG_LEVEL_FATAL); - return -1; - } - } - - /** Bind and listen to ipv4 interface. - \param a Ipv4 interface address - \param port Port (0 is random) - \param depth Listen queue depth */ - int Bind(ipaddr_t a,port_t port,int depth = 20) { - Ipv4Address ad(a, port); -#ifdef USE_SCTP - if (dynamic_cast(m_creator)) - { - return Bind(ad, "sctp", depth); - } -#endif - return Bind(ad, "tcp", depth); - } - /** Bind and listen to ipv4 interface. - \param a Ipv4 interface address - \param port Port (0 is random) - \param protocol Network protocol - \param depth Listen queue depth */ - int Bind(ipaddr_t a,port_t port,const std::string& protocol,int depth) { - Ipv4Address ad(a, port); - return Bind(ad, protocol, depth); - } - -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - /** Bind and listen to ipv6 interface. - \param a Ipv6 interface address - \param port Port (0 is random) - \param depth Listen queue depth */ - int Bind(in6_addr a,port_t port,int depth = 20) { - Ipv6Address ad(a, port); -#ifdef USE_SCTP - if (dynamic_cast(m_creator)) - { - return Bind(ad, "sctp", depth); - } -#endif - return Bind(ad, "tcp", depth); - } - /** Bind and listen to ipv6 interface. - \param a Ipv6 interface address - \param port Port (0 is random) - \param protocol Network protocol - \param depth Listen queue depth */ - int Bind(in6_addr a,port_t port,const std::string& protocol,int depth) { - Ipv6Address ad(a, port); - return Bind(ad, protocol, depth); - } -#endif -#endif - - /** Bind and listen to network interface. - \param ad Interface address - \param protocol Network protocol - \param depth Listen queue depth */ - int Bind(SocketAddress& ad,const std::string& protocol,int depth) { - SOCKET s; - if ( (s = CreateSocket(ad.GetFamily(), SOCK_STREAM, protocol)) == INVALID_SOCKET) - { - return -1; - } - if (bind(s, ad, ad) == -1) - { - Handler().LogError(this, "bind", Errno, StrError(Errno), LOG_LEVEL_FATAL); - closesocket(s); -#ifdef ENABLE_EXCEPTIONS - throw Exception("bind() failed for port " + Utility::l2string(ad.GetPort()) + ": " + StrError(Errno)); -#endif - return -1; - } - if (listen(s, depth) == -1) - { - Handler().LogError(this, "listen", Errno, StrError(Errno), LOG_LEVEL_FATAL); - closesocket(s); -#ifdef ENABLE_EXCEPTIONS - throw Exception("listen() failed for port " + Utility::l2string(ad.GetPort()) + ": " + StrError(Errno)); -#endif - return -1; - } - m_depth = depth; - Attach(s); - return 0; - } - - /** Return assigned port number. */ - port_t GetPort() - { - return GetSockPort(); - } - - /** Return listen queue depth. */ - int GetDepth() - { - return m_depth; - } - - /** OnRead on a ListenSocket receives an incoming connection. */ - void OnRead() - { - struct sockaddr sa; - socklen_t sa_len = sizeof(struct sockaddr); - SOCKET a_s = accept(GetSocket(), &sa, &sa_len); - - if (a_s == INVALID_SOCKET) - { - Handler().LogError(this, "accept", Errno, StrError(Errno), LOG_LEVEL_ERROR); - return; - } - if (!Handler().OkToAccept(this)) - { - Handler().LogError(this, "accept", -1, "Not OK to accept", LOG_LEVEL_WARNING); - closesocket(a_s); - return; - } - if (Handler().GetCount() >= FD_SETSIZE) - { - Handler().LogError(this, "accept", (int)Handler().GetCount(), "ISocketHandler fd_set limit reached", LOG_LEVEL_FATAL); - closesocket(a_s); - return; - } - Socket *tmp = m_bHasCreate ? m_creator -> Create() : new X(Handler()); -#ifdef ENABLE_IPV6 - tmp -> SetIpv6( IsIpv6() ); -#endif - tmp -> SetParent(this); - tmp -> Attach(a_s); - tmp -> SetNonblocking(true); - { -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (sa_len == sizeof(struct sockaddr_in6)) - { - struct sockaddr_in6 *p = (struct sockaddr_in6 *)&sa; - if (p -> sin6_family == AF_INET6) - { - Ipv6Address ad(p -> sin6_addr,ntohs(p -> sin6_port)); - ad.SetFlowinfo(p -> sin6_flowinfo); -#ifndef _WIN32 - ad.SetScopeId(p -> sin6_scope_id); -#endif - tmp -> SetRemoteAddress(ad); - } - } -#endif -#endif - if (sa_len == sizeof(struct sockaddr_in)) - { - struct sockaddr_in *p = (struct sockaddr_in *)&sa; - if (p -> sin_family == AF_INET) - { - Ipv4Address ad(p -> sin_addr,ntohs(p -> sin_port)); - tmp -> SetRemoteAddress(ad); - } - } - } - tmp -> SetConnected(true); - tmp -> Init(); - tmp -> SetDeleteByHandler(true); - Handler().Add(tmp); -#ifdef HAVE_OPENSSL - if (tmp -> IsSSL()) // SSL Enabled socket - { - // %! OnSSLAccept calls SSLNegotiate that can finish in this one call. - // %! If that happens and negotiation fails, the 'tmp' instance is - // %! still added to the list of active sockets in the sockethandler. - // %! See bugfix for this in SocketHandler::Select - don't Set rwx - // %! flags if CloseAndDelete() flag is true. - // %! An even better fugbix (see TcpSocket::OnSSLAccept) now avoids - // %! the Add problem altogether, so ignore the above. - // %! (OnSSLAccept does no longer call SSLNegotiate().) - tmp -> OnSSLAccept(); - } - else -#endif - { - tmp -> OnAccept(); - } - } - - /** Please don't use this method. - "accept()" is handled automatically in the OnRead() method. */ - virtual SOCKET Accept(SOCKET socket, struct sockaddr *saptr, socklen_t *lenptr) - { - return accept(socket, saptr, lenptr); - } - - bool HasCreator() { return m_bHasCreate; } - - void OnOptions(int,int,int,SOCKET) { - SetSoReuseaddr(true); - } - -protected: - ListenSocket(const ListenSocket& s) : Socket(s) {} -private: - ListenSocket& operator=(const ListenSocket& ) { return *this; } - int m_depth; - X *m_creator; - bool m_bHasCreate; -}; - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // _SOCKETS_ListenSocket_H - - diff --git a/externals/sockets/include/Lock.h b/externals/sockets/include/Lock.h deleted file mode 100644 index f3bb9273920..00000000000 --- a/externals/sockets/include/Lock.h +++ /dev/null @@ -1,58 +0,0 @@ -/** \file Lock.h - ** \date 2005-08-22 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2005,2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_Lock_H -#define _SOCKETS_Lock_H - -#include "sockets-config.h" -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -class Mutex; - -/** Mutex encapsulation class. - \ingroup threading */ -class Lock -{ -public: - Lock(Mutex&); - ~Lock(); - -private: - Mutex& m_mutex; -}; - - -#ifdef SOCKETS_NAMESPACE -} -#endif -#endif // _SOCKETS_Lock_H - - diff --git a/externals/sockets/include/Mutex.h b/externals/sockets/include/Mutex.h deleted file mode 100644 index e42a57c3262..00000000000 --- a/externals/sockets/include/Mutex.h +++ /dev/null @@ -1,68 +0,0 @@ -/** \file Mutex.h - ** \date 2004-10-30 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_Mutex_H -#define _SOCKETS_Mutex_H - -#include "sockets-config.h" -#ifndef _WIN32 -#include -#else -#include -#endif - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/** Mutex container class, used by Lock. - \ingroup threading */ -class Mutex -{ - friend class Lock; -public: - Mutex(); - ~Mutex(); - - void Lock(); - void Unlock(); -private: -#ifdef _WIN32 - HANDLE m_mutex; -#else - pthread_mutex_t m_mutex; -#endif -}; - -#ifdef SOCKETS_NAMESPACE -} -#endif -#endif // _SOCKETS_Mutex_H - - diff --git a/externals/sockets/include/Parse.h b/externals/sockets/include/Parse.h deleted file mode 100644 index 52bd9327e28..00000000000 --- a/externals/sockets/include/Parse.h +++ /dev/null @@ -1,100 +0,0 @@ -/** \file Parse.h - parse a string - ** - ** Written: 1999-Feb-10 grymse@alhem.net - **/ - -/* -Copyright (C) 1999-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ - -#ifndef _SOCKETS_Parse_H -#define _SOCKETS_Parse_H - -#include "sockets-config.h" -#ifdef _MSC_VER -#pragma warning(disable:4514) -#endif - -#include - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/***************************************************/ -/* interface of class Parse */ - -/** Splits a string whatever way you want. - \ingroup util */ -class Parse -{ -public: - Parse(); - Parse(const std::string&); - Parse(const std::string&,const std::string&); - Parse(const std::string&,const std::string&,short); - ~Parse(); - short issplit(const char); - void getsplit(); - void getsplit(std::string&); - std::string getword(); - void getword(std::string&); - void getword(std::string&,std::string&,int); - std::string getrest(); - void getrest(std::string&); - long getvalue(); - void setbreak(const char); - int getwordlen(); - int getrestlen(); - void enablebreak(const char c) { - pa_enable = c; - } - void disablebreak(const char c) { - pa_disable = c; - } - void getline(); - void getline(std::string&); - size_t getptr() { return pa_the_ptr; } - void EnableQuote(bool b) { pa_quote = b; } - -private: - std::string pa_the_str; - std::string pa_splits; - std::string pa_ord; - size_t pa_the_ptr; - char pa_breakchar; - char pa_enable; - char pa_disable; - short pa_nospace; - bool pa_quote; -}; - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // _SOCKETS_Parse_H - - diff --git a/externals/sockets/include/ResolvServer.h b/externals/sockets/include/ResolvServer.h deleted file mode 100644 index 409c9b7a619..00000000000 --- a/externals/sockets/include/ResolvServer.h +++ /dev/null @@ -1,72 +0,0 @@ -/** \file ResolvServer.h - ** \date 2005-03-24 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_ResolvServer_H -#define _SOCKETS_ResolvServer_H -#include "sockets-config.h" -#ifdef ENABLE_RESOLVER -#include "socket_include.h" -#include "Thread.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/** \defgroup async Asynchronous DNS */ -/** Async DNS resolver thread. - \ingroup async */ -class ResolvServer : public Thread -{ -public: - ResolvServer(port_t); - ~ResolvServer(); - - void Run(); - void Quit(); - - bool Ready(); - -private: - ResolvServer(const ResolvServer& ) {} // copy constructor - ResolvServer& operator=(const ResolvServer& ) { return *this; } // assignment operator - - bool m_quit; - port_t m_port; - bool m_ready; -}; - - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // ENABLE_RESOLVER -#endif // _SOCKETS_ResolvServer_H - - diff --git a/externals/sockets/include/ResolvSocket.h b/externals/sockets/include/ResolvSocket.h deleted file mode 100644 index 60743736e08..00000000000 --- a/externals/sockets/include/ResolvSocket.h +++ /dev/null @@ -1,105 +0,0 @@ -/** \file ResolvSocket.h - ** \date 2005-03-24 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_ResolvSocket_H -#define _SOCKETS_ResolvSocket_H -#include "sockets-config.h" -#ifdef ENABLE_RESOLVER -#include "TcpSocket.h" -#include - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -class Mutex; - -/** Async DNS resolver socket. - \ingroup async */ -class ResolvSocket : public TcpSocket -{ - typedef std::map > cache_t; /* host, result */ - typedef std::map > timeout_t; /* host, time */ - -public: - ResolvSocket(ISocketHandler&); - ResolvSocket(ISocketHandler&, Socket *parent, const std::string& host, port_t port, bool ipv6 = false); - ResolvSocket(ISocketHandler&, Socket *parent, ipaddr_t); -#ifdef ENABLE_IPV6 - ResolvSocket(ISocketHandler&, Socket *parent, in6_addr&); -#endif - ~ResolvSocket(); - - void OnAccept() { m_bServer = true; } - void OnLine(const std::string& line); - void OnDetached(); - void OnDelete(); - - void SetId(int x) { m_resolv_id = x; } - int GetId() { return m_resolv_id; } - - void OnConnect(); - -#ifdef ENABLE_IPV6 - void SetResolveIpv6(bool x = true) { m_resolve_ipv6 = x; } -#endif - -private: - ResolvSocket(const ResolvSocket& s) : TcpSocket(s) {} // copy constructor - ResolvSocket& operator=(const ResolvSocket& ) { return *this; } // assignment operator - - std::string m_query; - std::string m_data; - bool m_bServer; - Socket *m_parent; - int m_resolv_id; - std::string m_resolv_host; - port_t m_resolv_port; - ipaddr_t m_resolv_address; -#ifdef ENABLE_IPV6 - bool m_resolve_ipv6; - in6_addr m_resolv_address6; -#endif - static cache_t m_cache; - static timeout_t m_cache_to; - static Mutex m_cache_mutex; - bool m_cached; -}; - - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // ENABLE_RESOLVER -#endif // _SOCKETS_ResolvSocket_H - - diff --git a/externals/sockets/include/SctpSocket.h b/externals/sockets/include/SctpSocket.h deleted file mode 100644 index ed507fb1880..00000000000 --- a/externals/sockets/include/SctpSocket.h +++ /dev/null @@ -1,108 +0,0 @@ -/** - ** \file SctpSocket.h - ** \date 2006-09-04 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2007 Anders Hedstrom - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_SctpSocket_H -#define _SOCKETS_SctpSocket_H -#include "sockets-config.h" - -#include "StreamSocket.h" -#ifdef USE_SCTP -#include - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -#define SCTP_BUFSIZE_READ 16400 - -class SocketAddress; - -class SctpSocket : public StreamSocket -{ -public: - /** SctpSocket constructor. - \param h Owner - \param type SCTP_STREAM or SCTP_SEQPACKET */ - SctpSocket(ISocketHandler& h,int type); - ~SctpSocket(); - - /** bind() */ - int Bind(const std::string&,port_t); - int Bind(SocketAddress&); - /** sctp_bindx() */ - int AddAddress(const std::string&,port_t); - int AddAddress(SocketAddress&); - /** sctp_bindx() */ - int RemoveAddress(const std::string&,port_t); - int RemoveAddress(SocketAddress&); - - /** connect() */ - int Open(const std::string&,port_t); - int Open(SocketAddress&); - - /** Connect timeout callback. */ - void OnConnectTimeout(); -#ifdef _WIN32 - /** Connection failed reported as exception on win32 */ - void OnException(); -#endif - -#ifndef SOLARIS - /** sctp_connectx() */ - int AddConnection(const std::string&,port_t); - int AddConnection(SocketAddress&); -#endif - - /** Get peer addresses of an association. */ - int getpaddrs(sctp_assoc_t id,std::list&); - /** Get all bound addresses of an association. */ - int getladdrs(sctp_assoc_t id,std::list&); - - /** sctp_peeloff */ - int PeelOff(sctp_assoc_t id); - - /** recvmsg callback */ - virtual void OnReceiveMessage(const char *buf,size_t sz,struct sockaddr *sa,socklen_t sa_len,struct sctp_sndrcvinfo *sinfo,int msg_flags) = 0; - - void OnOptions(int,int,int,SOCKET) {} - - virtual int Protocol(); - -protected: - SctpSocket(const SctpSocket& s) : StreamSocket(s) {} - void OnRead(); - void OnWrite(); - -private: - SctpSocket& operator=(const SctpSocket& s) { return *this; } - int m_type; ///< SCTP_STREAM or SCTP_SEQPACKET - char *m_buf; ///< Temporary receive buffer -}; - -#ifdef SOCKETS_NAMESPACE -} // namespace SOCKETS_NAMESPACE -#endif - -#endif // USE_SCTP -#endif // _SOCKETS_SctpSocket_H - - diff --git a/externals/sockets/include/Socket.h b/externals/sockets/include/Socket.h deleted file mode 100644 index 23a806b5ea1..00000000000 --- a/externals/sockets/include/Socket.h +++ /dev/null @@ -1,735 +0,0 @@ -/** \file Socket.h - ** \date 2004-02-13 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This software is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_Socket_H -#define _SOCKETS_Socket_H -#include "sockets-config.h" - -#include -#include -#include -#ifdef HAVE_OPENSSL -#include -#endif - -#include "socket_include.h" -#include -#include "SocketAddress.h" -#include "Thread.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -class ISocketHandler; -class SocketAddress; -class IFile; - -/** \defgroup basic Basic sockets */ -/** Socket base class. - \ingroup basic */ -class Socket -{ - friend class ISocketHandler; -#ifdef ENABLE_DETACH - /** Detached socket run thread. - \ingroup internal */ - class SocketThread : public Thread - { - public: - SocketThread(Socket *p); - ~SocketThread(); - - void Run(); - - private: - Socket *GetSocket() const { return m_socket; } - SocketThread(const SocketThread& s) : m_socket(s.GetSocket()) {} - SocketThread& operator=(const SocketThread& ) { return *this; } - Socket *m_socket; - }; -#endif // ENABLE_DETACH - -#ifdef ENABLE_TRIGGERS -public: - /** Data pass class from source to destination. */ - class TriggerData - { - public: - TriggerData() : m_src(NULL) {} - virtual ~TriggerData() {} - - Socket *GetSource() const { return m_src; } - void SetSource(Socket *x) { m_src = x; } - - private: - Socket *m_src; - }; -#endif // ENABLE_TRIGGERS - - /** Socket mode flags. */ -/* - enum { - // Socket - SOCK_DEL = 0x01, ///< Delete by handler flag - SOCK_CLOSE = 0x02, ///< Close and delete flag - SOCK_DISABLE_READ = 0x04, ///< Disable checking for read events - SOCK_CONNECTED = 0x08, ///< Socket is connected (tcp/udp) - - SOCK_ERASED_BY_HANDLER = 0x10, ///< Set by handler before delete - // HAVE_OPENSSL - SOCK_ENABLE_SSL = 0x20, ///< Enable SSL for this TcpSocket - SOCK_SSL = 0x40, ///< ssl negotiation mode (TcpSocket) - SOCK_SSL_SERVER = 0x80, ///< True if this is an incoming ssl TcpSocket connection - - // ENABLE_IPV6 - SOCK_IPV6 = 0x0100, ///< This is an ipv6 socket if this one is true - // ENABLE_POOL - SOCK_CLIENT = 0x0200, ///< only client connections are pooled - SOCK_RETAIN = 0x0400, ///< keep connection on close - SOCK_LOST = 0x0800, ///< connection lost - - // ENABLE_SOCKS4 - SOCK_SOCKS4 = 0x1000, ///< socks4 negotiation mode (TcpSocket) - // ENABLE_DETACH - SOCK_DETACH = 0x2000, ///< Socket ordered to detach flag - SOCK_DETACHED = 0x4000, ///< Socket has been detached - // StreamSocket - STREAMSOCK_CONNECTING = 0x8000, ///< Flag indicating connection in progress - - STREAMSOCK_FLUSH_BEFORE_CLOSE = 0x010000L, ///< Send all data before closing (default true) - STREAMSOCK_CALL_ON_CONNECT = 0x020000L, ///< OnConnect will be called next ISocketHandler cycle if true - STREAMSOCK_RETRY_CONNECT = 0x040000L, ///< Try another connection attempt next ISocketHandler cycle - STREAMSOCK_LINE_PROTOCOL = 0x080000L, ///< Line protocol mode flag - - }; -*/ - -public: - /** "Default" constructor */ - Socket(ISocketHandler&); - - virtual ~Socket(); - - /** Socket class instantiation method. Used when a "non-standard" constructor - * needs to be used for the socket class. Note: the socket class still needs - * the "default" constructor with one ISocketHandler& as input parameter. - */ - virtual Socket *Create() { return NULL; } - - /** Returns reference to sockethandler that owns the socket. - If the socket is detached, this is a reference to the slave sockethandler. - */ - ISocketHandler& Handler() const; - - /** Returns reference to sockethandler that owns the socket. - This one always returns the reference to the original sockethandler, - even if the socket is detached. - */ - ISocketHandler& MasterHandler() const; - - /** Called by ListenSocket after accept but before socket is added to handler. - * CTcpSocket uses this to create its ICrypt member variable. - * The ICrypt member variable is created by a virtual method, therefore - * it can't be called directly from the CTcpSocket constructor. - * Also used to determine if incoming HTTP connection is normal (port 80) - * or ssl (port 443). - */ - virtual void Init(); - - /** Create a socket file descriptor. - \param af Address family AF_INET / AF_INET6 / ... - \param type SOCK_STREAM / SOCK_DGRAM / ... - \param protocol "tcp" / "udp" / ... */ - SOCKET CreateSocket(int af,int type,const std::string& protocol = ""); - - /** Assign this socket a file descriptor created - by a call to socket() or otherwise. */ - void Attach(SOCKET s); - - /** Return file descriptor assigned to this socket. */ - SOCKET GetSocket(); - - /** Close connection immediately - internal use. - \sa SetCloseAndDelete */ - virtual int Close(); - - /** Add file descriptor to sockethandler fd_set's. */ - void Set(bool bRead,bool bWrite,bool bException = true); - - /** Returns true when socket file descriptor is valid - and socket is not about to be closed. */ - virtual bool Ready(); - - /** Returns pointer to ListenSocket that created this instance - * on an incoming connection. */ - Socket *GetParent(); - - /** Used by ListenSocket to set parent pointer of newly created - * socket instance. */ - void SetParent(Socket *); - - /** Get listening port from ListenSocket<>. */ - virtual port_t GetPort(); - - /** Set socket non-block operation. */ - bool SetNonblocking(bool); - - /** Set socket non-block operation. */ - bool SetNonblocking(bool, SOCKET); - - /** Total lifetime of instance. */ - time_t Uptime(); - - /** Set address/port of last connect() call. */ - void SetClientRemoteAddress(SocketAddress&); - - /** Get address/port of last connect() call. */ - std::auto_ptr GetClientRemoteAddress(); - - /** Common interface for SendBuf used by Tcp and Udp sockets. */ - virtual void SendBuf(const char *,size_t,int = 0); - - /** Common interface for Send used by Tcp and Udp sockets. */ - virtual void Send(const std::string&,int = 0); - - /** Outgoing traffic counter. */ - virtual uint64_t GetBytesSent(bool clear = false); - - /** Incoming traffic counter. */ - virtual uint64_t GetBytesReceived(bool clear = false); - - // LIST_TIMEOUT - - /** Enable timeout control. 0=disable timeout check. */ - void SetTimeout(time_t secs); - - /** Check timeout. \return true if time limit reached */ - bool Timeout(time_t tnow); - - /** Used by ListenSocket. ipv4 and ipv6 */ - void SetRemoteAddress(SocketAddress&); - - /** \name Event callbacks */ - //@{ - - /** Called when there is something to be read from the file descriptor. */ - virtual void OnRead(); - /** Called when there is room for another write on the file descriptor. */ - virtual void OnWrite(); - /** Called on socket exception. */ - virtual void OnException(); - /** Called before a socket class is deleted by the ISocketHandler. */ - virtual void OnDelete(); - /** Called when a connection has completed. */ - virtual void OnConnect(); - /** Called when an incoming connection has been completed. */ - virtual void OnAccept(); - /** Called when a complete line has been read and the socket is in - * line protocol mode. */ - virtual void OnLine(const std::string& ); - /** Called on connect timeout (5s). */ - virtual void OnConnectFailed(); - /** Called when a client socket is created, to set socket options. - \param family AF_INET, AF_INET6, etc - \param type SOCK_STREAM, SOCK_DGRAM, etc - \param protocol Protocol number (tcp, udp, sctp, etc) - \param s Socket file descriptor - */ - virtual void OnOptions(int family,int type,int protocol,SOCKET s) = 0; - /** Connection retry callback - return false to abort connection attempts */ - virtual bool OnConnectRetry(); -#ifdef ENABLE_RECONNECT - /** a reconnect has been made */ - virtual void OnReconnect(); -#endif - /** TcpSocket: When a disconnect has been detected (recv/SSL_read returns 0 bytes). */ - virtual void OnDisconnect(); - /** Timeout callback. */ - virtual void OnTimeout(); - /** Connection timeout. */ - virtual void OnConnectTimeout(); - //@} - - /** \name Socket mode flags, set/reset */ - //@{ - /** Set delete by handler true when you want the sockethandler to - delete the socket instance after use. */ - void SetDeleteByHandler(bool = true); - /** Check delete by handler flag. - \return true if this instance should be deleted by the sockethandler */ - bool DeleteByHandler(); - - // LIST_CLOSE - conditional event queue - - /** Set close and delete to terminate the connection. */ - void SetCloseAndDelete(bool = true); - /** Check close and delete flag. - \return true if this socket should be closed and the instance removed */ - bool CloseAndDelete(); - - /** Return number of seconds since socket was ordered to close. \sa SetCloseAndDelete */ - time_t TimeSinceClose(); - - /** Ignore read events for an output only socket. */ - void DisableRead(bool x = true); - /** Check ignore read events flag. - \return true if read events should be ignored */ - bool IsDisableRead(); - - /** Set connected status. */ - void SetConnected(bool = true); - /** Check connected status. - \return true if connected */ - bool IsConnected(); - - /** Connection lost - error while reading/writing from a socket - TcpSocket only. */ - void SetLost(); - /** Check connection lost status flag, used by TcpSocket only. - \return true if there was an error while r/w causing the socket to close */ - bool Lost(); - - /** Set flag indicating the socket is being actively deleted by the sockethandler. */ - void SetErasedByHandler(bool x = true); - /** Get value of flag indicating socket is deleted by sockethandler. */ - bool ErasedByHandler(); - - //@} - - /** \name Information about remote connection */ - //@{ - /** Returns address of remote end. */ - std::auto_ptr GetRemoteSocketAddress(); - /** Returns address of remote end: ipv4. */ - ipaddr_t GetRemoteIP4(); -#ifdef ENABLE_IPV6 - /** Returns address of remote end: ipv6. */ -#ifdef IPPROTO_IPV6 - struct in6_addr GetRemoteIP6(); -#endif -#endif - /** Returns remote port number: ipv4 and ipv6. */ - port_t GetRemotePort(); - /** Returns remote ip as string? ipv4 and ipv6. */ - std::string GetRemoteAddress(); - /** ipv4 and ipv6(not implemented) */ - std::string GetRemoteHostname(); - //@} - - /** Returns local port number for bound socket file descriptor. */ - port_t GetSockPort(); - /** Returns local ipv4 address for bound socket file descriptor. */ - ipaddr_t GetSockIP4(); - /** Returns local ipv4 address as text for bound socket file descriptor. */ - std::string GetSockAddress(); -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - /** Returns local ipv6 address for bound socket file descriptor. */ - struct in6_addr GetSockIP6(); - /** Returns local ipv6 address as text for bound socket file descriptor. */ - std::string GetSockAddress6(); -#endif -#endif - // -------------------------------------------------------------------------- - /** @name IP options - When an ip or socket option is available on all of the operating systems - I'm testing on (linux 2.4.x, _win32, macosx, solaris9 intel) they are not - checked with an #ifdef below. - This might cause a compile error on other operating systems. */ - // -------------------------------------------------------------------------- - - // IP options - //@{ - - bool SetIpOptions(const void *p, socklen_t len); - bool SetIpTOS(unsigned char tos); - unsigned char IpTOS(); - bool SetIpTTL(int ttl); - int IpTTL(); - bool SetIpHdrincl(bool x = true); - bool SetIpMulticastTTL(int); - int IpMulticastTTL(); - bool SetMulticastLoop(bool x = true); - bool IpAddMembership(struct ip_mreq&); - bool IpDropMembership(struct ip_mreq&); - -#ifdef IP_PKTINFO - bool SetIpPktinfo(bool x = true); -#endif -#ifdef IP_RECVTOS - bool SetIpRecvTOS(bool x = true); -#endif -#ifdef IP_RECVTTL - bool SetIpRecvTTL(bool x = true); -#endif -#ifdef IP_RECVOPTS - bool SetIpRecvopts(bool x = true); -#endif -#ifdef IP_RETOPTS - bool SetIpRetopts(bool x = true); -#endif -#ifdef IP_RECVERR - bool SetIpRecverr(bool x = true); -#endif -#ifdef IP_MTU_DISCOVER - bool SetIpMtudiscover(bool x = true); -#endif -#ifdef IP_MTU - int IpMtu(); -#endif -#ifdef IP_ROUTER_ALERT - bool SetIpRouterAlert(bool x = true); -#endif -#ifdef LINUX - bool IpAddMembership(struct ip_mreqn&); -#endif -#ifdef LINUX - bool IpDropMembership(struct ip_mreqn&); -#endif - //@} - - // SOCKET options - /** @name Socket Options */ - //@{ - - bool SoAcceptconn(); - bool SetSoBroadcast(bool x = true); - bool SetSoDebug(bool x = true); - int SoError(); - bool SetSoDontroute(bool x = true); - bool SetSoLinger(int onoff, int linger); - bool SetSoOobinline(bool x = true); - bool SetSoRcvlowat(int); - bool SetSoSndlowat(int); - bool SetSoRcvtimeo(struct timeval&); - bool SetSoSndtimeo(struct timeval&); - bool SetSoRcvbuf(int); - int SoRcvbuf(); - bool SetSoSndbuf(int); - int SoSndbuf(); - int SoType(); - bool SetSoReuseaddr(bool x = true); - bool SetSoKeepalive(bool x = true); - -#ifdef SO_BSDCOMPAT - bool SetSoBsdcompat(bool x = true); -#endif -#ifdef SO_BINDTODEVICE - bool SetSoBindtodevice(const std::string& intf); -#endif -#ifdef SO_PASSCRED - bool SetSoPasscred(bool x = true); -#endif -#ifdef SO_PEERCRED - bool SoPeercred(struct ucred& ); -#endif -#ifdef SO_PRIORITY - bool SetSoPriority(int); -#endif -#ifdef SO_RCVBUFFORCE - bool SetSoRcvbufforce(int); -#endif -#ifdef SO_SNDBUFFORCE - bool SetSoSndbufforce(int); -#endif -#ifdef SO_TIMESTAMP - bool SetSoTimestamp(bool x = true); -#endif -#ifdef SO_NOSIGPIPE - bool SetSoNosigpipe(bool x = true); -#endif - //@} - - // TCP options in TcpSocket.h/TcpSocket.cpp - -#ifdef HAVE_OPENSSL - /** @name SSL Support */ - //@{ - /** SSL client/server support - internal use. \sa TcpSocket */ - virtual void OnSSLConnect(); - /** SSL client/server support - internal use. \sa TcpSocket */ - virtual void OnSSLAccept(); - /** SSL negotiation failed for client connect. */ - virtual void OnSSLConnectFailed(); - /** SSL negotiation failed for server accept. */ - virtual void OnSSLAcceptFailed(); - /** new SSL support */ - virtual bool SSLNegotiate(); - /** Check if SSL is Enabled for this TcpSocket. - \return true if this is a TcpSocket with SSL enabled */ - bool IsSSL(); - /** Enable SSL operation for a TcpSocket. */ - void EnableSSL(bool x = true); - /** Still negotiating ssl connection. - \return true if ssl negotiating is still in progress */ - bool IsSSLNegotiate(); - /** Set flag indicating ssl handshaking still in progress. */ - void SetSSLNegotiate(bool x = true); - /** OnAccept called with SSL Enabled. - \return true if this is a TcpSocket with an incoming SSL connection */ - bool IsSSLServer(); - /** Set flag indicating that this is a TcpSocket with incoming SSL connection. */ - void SetSSLServer(bool x = true); - /** SSL; Get pointer to ssl context structure. */ - virtual SSL_CTX *GetSslContext() { return NULL; } - /** SSL; Get pointer to ssl structure. */ - virtual SSL *GetSsl() { return NULL; } - //@} -#endif // HAVE_OPENSSL - -#ifdef ENABLE_IPV6 - /** Enable ipv6 for this socket. */ - void SetIpv6(bool x = true); - /** Check ipv6 socket. - \return true if this is an ipv6 socket */ - bool IsIpv6(); -#endif - -#ifdef ENABLE_POOL - /** @name Connection Pool */ - //@{ - /** Client = connecting TcpSocket. */ - void SetIsClient(); - /** Socket type from socket() call. */ - void SetSocketType(int x); - /** Socket type from socket() call. */ - int GetSocketType(); - /** Protocol type from socket() call. */ - void SetSocketProtocol(const std::string& x); - /** Protocol type from socket() call. */ - const std::string& GetSocketProtocol(); - /** Instruct a client socket to stay open in the connection pool after use. - If you have connected to a server using tcp, you can call SetRetain - to leave the connection open after your socket instance has been deleted. - The next connection you make to the same server will reuse the already - opened connection, if it is still available. - */ - void SetRetain(); - /** Check retain flag. - \return true if the socket should be moved to connection pool after use */ - bool Retain(); - /** Copy connection parameters from sock. */ - void CopyConnection(Socket *sock); - //@} -#endif // ENABLE_POOL - -#ifdef ENABLE_SOCKS4 - /** \name Socks4 support */ - //@{ - /** Socks4 client support internal use. \sa TcpSocket */ - virtual void OnSocks4Connect(); - /** Socks4 client support internal use. \sa TcpSocket */ - virtual void OnSocks4ConnectFailed(); - /** Socks4 client support internal use. \sa TcpSocket */ - virtual bool OnSocks4Read(); - /** Called when the last write caused the tcp output buffer to - * become empty. */ - /** socket still in socks4 negotiation mode */ - bool Socks4(); - /** Set flag indicating Socks4 handshaking in progress */ - void SetSocks4(bool x = true); - - /** Set socks4 server host address to use */ - void SetSocks4Host(ipaddr_t a); - /** Set socks4 server hostname to use. */ - void SetSocks4Host(const std::string& ); - /** Socks4 server port to use. */ - void SetSocks4Port(port_t p); - /** Provide a socks4 userid if required by the socks4 server. */ - void SetSocks4Userid(const std::string& x); - /** Get the ip address of socks4 server to use. - \return socks4 server host address */ - ipaddr_t GetSocks4Host(); - /** Get the socks4 server port to use. - \return socks4 server port */ - port_t GetSocks4Port(); - /** Get socks4 userid. - \return Socks4 userid */ - const std::string& GetSocks4Userid(); - //@} -#endif // ENABLE_SOCKS4 - -#ifdef ENABLE_RESOLVER - /** \name Asynchronous Resolver */ - //@{ - /** Request an asynchronous dns resolution. - \param host hostname to be resolved - \param port port number passed along for the ride - \return Resolve ID */ - int Resolve(const std::string& host,port_t port = 0); -#ifdef ENABLE_IPV6 - int Resolve6(const std::string& host, port_t port = 0); -#endif - /** Callback returning a resolved address. - \param id Resolve ID from Resolve call - \param a resolved ip address - \param port port number passed to Resolve */ - virtual void OnResolved(int id,ipaddr_t a,port_t port); -#ifdef ENABLE_IPV6 - virtual void OnResolved(int id,in6_addr& a,port_t port); -#endif - /** Request asynchronous reverse dns lookup. - \param a in_addr to be translated */ - int Resolve(ipaddr_t a); -#ifdef ENABLE_IPV6 - int Resolve(in6_addr& a); -#endif - /** Callback returning reverse resolve results. - \param id Resolve ID - \param name Resolved hostname */ - virtual void OnReverseResolved(int id,const std::string& name); - /** Callback indicating failed dns lookup. - \param id Resolve ID */ - virtual void OnResolveFailed(int id); - //@} -#endif // ENABLE_RESOLVER - -#ifdef ENABLE_DETACH - /** \name Thread Support */ - //@{ - /** Callback fires when a new socket thread has started and this - socket is ready for operation again. - \sa ResolvSocket */ - virtual void OnDetached(); - - // LIST_DETACH - - /** Internal use. */ - void SetDetach(bool x = true); - /** Check detach flag. - \return true if the socket should detach to its own thread */ - bool IsDetach(); - - /** Internal use. */ - void SetDetached(bool x = true); - /** Check detached flag. - \return true if the socket runs in its own thread. */ - const bool IsDetached() const; - /** Order this socket to start its own thread and call OnDetached - when ready for operation. */ - bool Detach(); - /** Store the slave sockethandler pointer. */ - void SetSlaveHandler(ISocketHandler *); - /** Create new thread for this socket to run detached in. */ - void DetachSocket(); - //@} -#endif // ENABLE_DETACH - - /** Write traffic to an IFile. Socket will not delete this object. */ - void SetTrafficMonitor(IFile *p) { m_traffic_monitor = p; } - -#ifdef ENABLE_TRIGGERS - /** \name Triggers */ - //@{ - /** Subscribe to trigger id. */ - void Subscribe(int id); - /** Unsubscribe from trigger id. */ - void Unsubscribe(int id); - /** Trigger callback, with data passed from source to destination. */ - virtual void OnTrigger(int id, const TriggerData& data); - /** Trigger cancelled because source has been deleted (as in delete). */ - virtual void OnCancelled(int id); - //@} -#endif - -protected: - /** default constructor not available */ - Socket() : m_handler(m_handler) {} - /** copy constructor not available */ - Socket(const Socket& s) : m_handler(s.m_handler) {} - - /** assignment operator not available. */ - Socket& operator=(const Socket& ) { return *this; } - - /** All traffic will be written to this IFile, if set. */ - IFile *GetTrafficMonitor() { return m_traffic_monitor; } - -// unsigned long m_flags; ///< boolean flags, replacing old 'bool' members - -private: - ISocketHandler& m_handler; ///< Reference of ISocketHandler in control of this socket - SOCKET m_socket; ///< File descriptor - bool m_bDel; ///< Delete by handler flag - bool m_bClose; ///< Close and delete flag - time_t m_tCreate; ///< Time in seconds when this socket was created - Socket *m_parent; ///< Pointer to ListenSocket class, valid for incoming sockets - bool m_b_disable_read; ///< Disable checking for read events - bool m_connected; ///< Socket is connected (tcp/udp) - bool m_b_erased_by_handler; ///< Set by handler before delete - time_t m_tClose; ///< Time in seconds when ordered to close - std::auto_ptr m_client_remote_address; ///< Address of last connect() - std::auto_ptr m_remote_address; ///< Remote end address - IFile *m_traffic_monitor; - time_t m_timeout_start; ///< Set by SetTimeout - time_t m_timeout_limit; ///< Defined by SetTimeout - bool m_bLost; ///< connection lost - -#ifdef _WIN32 -static WSAInitializer m_winsock_init; ///< Winsock initialization singleton class -#endif - -#ifdef HAVE_OPENSSL - bool m_b_enable_ssl; ///< Enable SSL for this TcpSocket - bool m_b_ssl; ///< ssl negotiation mode (TcpSocket) - bool m_b_ssl_server; ///< True if this is an incoming ssl TcpSocket connection -#endif - -#ifdef ENABLE_IPV6 - bool m_ipv6; ///< This is an ipv6 socket if this one is true -#endif - -#ifdef ENABLE_POOL - int m_socket_type; ///< Type of socket, from socket() call - std::string m_socket_protocol; ///< Protocol, from socket() call - bool m_bClient; ///< only client connections are pooled - bool m_bRetain; ///< keep connection on close -#endif - -#ifdef ENABLE_SOCKS4 - bool m_bSocks4; ///< socks4 negotiation mode (TcpSocket) - ipaddr_t m_socks4_host; ///< socks4 server address - port_t m_socks4_port; ///< socks4 server port number - std::string m_socks4_userid; ///< socks4 server usedid -#endif - -#ifdef ENABLE_DETACH - bool m_detach; ///< Socket ordered to detach flag - bool m_detached; ///< Socket has been detached - SocketThread *m_pThread; ///< Detach socket thread class pointer - ISocketHandler *m_slave_handler; ///< Actual sockethandler while detached -#endif -}; - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // _SOCKETS_Socket_H - - diff --git a/externals/sockets/include/SocketAddress.h b/externals/sockets/include/SocketAddress.h deleted file mode 100644 index abdbbfd2cf6..00000000000 --- a/externals/sockets/include/SocketAddress.h +++ /dev/null @@ -1,93 +0,0 @@ -/** - ** \file SocketAddress.h - ** \date 2006-09-21 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2007 Anders Hedstrom - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_SocketAddress_H -#define _SOCKETS_SocketAddress_H - -#include "sockets-config.h" -#include -#include -#include "socket_include.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/** - This class and its subclasses is intended to be used as replacement - for the internal data type 'ipaddr_t' and various implementations of - IPv6 addressing found throughout the library. - 'ipaddr_t' is an IPv4 address in network byte order. - 'port_t' is the portnumber in host byte order. - 'struct in6_addr' is an IPv6 address. - 'struct in_addr' is an IPv4 address. - \ingroup basic -*/ -class SocketAddress -{ -public: - virtual ~SocketAddress() {} - - /** Get a pointer to the address struct. */ - virtual operator struct sockaddr *() = 0; - - /** Get length of address struct. */ - virtual operator socklen_t() = 0; - - /** Compare two addresses. */ - virtual bool operator==(SocketAddress&) = 0; - - /** Set port number. - \param port Port number in host byte order */ - virtual void SetPort(port_t port) = 0; - - /** Get port number. - \return Port number in host byte order. */ - virtual port_t GetPort() = 0; - - /** Set socket address. - \param sa Pointer to either 'struct sockaddr_in' or 'struct sockaddr_in6'. */ - virtual void SetAddress(struct sockaddr *sa) = 0; - - /** Convert address to text. */ - virtual std::string Convert(bool include_port) = 0; - - /** Reverse lookup of address. */ - virtual std::string Reverse() = 0; - - /** Get address family. */ - virtual int GetFamily() = 0; - - /** Address structure is valid. */ - virtual bool IsValid() = 0; - - /** Get a copy of this SocketAddress object. */ - virtual std::auto_ptr GetCopy() = 0; -}; - - -#ifdef SOCKETS_NAMESPACE -} // namespace SOCKETS_NAMESPACE { -#endif -#endif // _SOCKETS_SocketAddress_H - - diff --git a/externals/sockets/include/SocketHandler.h b/externals/sockets/include/SocketHandler.h deleted file mode 100644 index 5598ec4249b..00000000000 --- a/externals/sockets/include/SocketHandler.h +++ /dev/null @@ -1,265 +0,0 @@ -/** \file SocketHandler.h - ** \date 2004-02-13 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_SocketHandler_H -#define _SOCKETS_SocketHandler_H - -#include "sockets-config.h" -#include -#include - -#include "socket_include.h" -#include "ISocketHandler.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -class Socket; -#ifdef ENABLE_RESOLVER -class ResolvServer; -#endif -class Mutex; - -/** Socket container class, event generator. - \ingroup basic */ -class SocketHandler : public ISocketHandler -{ -protected: - /** Map type for holding file descriptors/socket object pointers. */ - typedef std::map socket_m; - -public: - /** SocketHandler constructor. - \param log Optional log class pointer */ - SocketHandler(StdLog *log = NULL); - - /** SocketHandler threadsafe constructor. - \param mutex Externally declared mutex variable - \param log Optional log class pointer */ - SocketHandler(Mutex& mutex,StdLog *log = NULL); - - ~SocketHandler(); - - /** Get mutex reference for threadsafe operations. */ - Mutex& GetMutex() const; - - /** Register StdLog object for error callback. - \param log Pointer to log class */ - void RegStdLog(StdLog *log); - - /** Log error to log class for print out / storage. */ - void LogError(Socket *p,const std::string& user_text,int err,const std::string& sys_err,loglevel_t t = LOG_LEVEL_WARNING); - - /** Add socket instance to socket map. Removal is always automatic. */ - void Add(Socket *); - - /** Get status of read/write/exception file descriptor set for a socket. */ - void Get(SOCKET s,bool& r,bool& w,bool& e); - - /** Set read/write/exception file descriptor sets (fd_set). */ - void Set(SOCKET s,bool bRead,bool bWrite,bool bException = true); - - /** Wait for events, generate callbacks. */ - int Select(long sec,long usec); - - /** This method will not return until an event has been detected. */ - int Select(); - - /** Wait for events, generate callbacks. */ - int Select(struct timeval *tsel); - - /** Check that a socket really is handled by this socket handler. */ - bool Valid(Socket *); - - /** Return number of sockets handled by this handler. */ - size_t GetCount(); - - /** Override and return false to deny all incoming connections. - \param p ListenSocket class pointer (use GetPort to identify which one) */ - bool OkToAccept(Socket *p); - - /** Called by Socket when a socket changes state. */ - void AddList(SOCKET s,list_t which_one,bool add); - - // Connection pool -#ifdef ENABLE_POOL - /** Find available open connection (used by connection pool). */ - ISocketHandler::PoolSocket *FindConnection(int type,const std::string& protocol,SocketAddress&); - /** Enable connection pool (by default disabled). */ - void EnablePool(bool x = true); - /** Check pool status. - \return true if connection pool is enabled */ - bool PoolEnabled(); -#endif // ENABLE_POOL - - // Socks4 -#ifdef ENABLE_SOCKS4 - /** Set socks4 server ip that all new tcp sockets should use. */ - void SetSocks4Host(ipaddr_t); - /** Set socks4 server hostname that all new tcp sockets should use. */ - void SetSocks4Host(const std::string& ); - /** Set socks4 server port number that all new tcp sockets should use. */ - void SetSocks4Port(port_t); - /** Set optional socks4 userid. */ - void SetSocks4Userid(const std::string& ); - /** If connection to socks4 server fails, immediately try direct connection to final host. */ - void SetSocks4TryDirect(bool x = true); - /** Get socks4 server ip. - \return socks4 server ip */ - ipaddr_t GetSocks4Host(); - /** Get socks4 port number. - \return socks4 port number */ - port_t GetSocks4Port(); - /** Get socks4 userid (optional). - \return socks4 userid */ - const std::string& GetSocks4Userid(); - /** Check status of socks4 try direct flag. - \return true if direct connection should be tried if connection to socks4 server fails */ - bool Socks4TryDirect(); -#endif // ENABLE_SOCKS4 - - // DNS resolve server -#ifdef ENABLE_RESOLVER - /** Enable asynchronous DNS. - \param port Listen port of asynchronous dns server */ - void EnableResolver(port_t port = 16667); - /** Check resolver status. - \return true if resolver is enabled */ - bool ResolverEnabled(); - /** Queue a dns request. - \param host Hostname to be resolved - \param port Port number will be echoed in Socket::OnResolved callback */ - int Resolve(Socket *,const std::string& host,port_t port); -#ifdef ENABLE_IPV6 - int Resolve6(Socket *,const std::string& host,port_t port); -#endif - /** Do a reverse dns lookup. */ - int Resolve(Socket *,ipaddr_t a); -#ifdef ENABLE_IPV6 - int Resolve(Socket *,in6_addr& a); -#endif - /** Get listen port of asynchronous dns server. */ - port_t GetResolverPort(); - /** Resolver thread ready for queries. */ - bool ResolverReady(); - /** Returns true if the socket is waiting for a resolve event. */ - bool Resolving(Socket *); -#endif // ENABLE_RESOLVER - -#ifdef ENABLE_TRIGGERS - /** Fetch unique trigger id. */ - int TriggerID(Socket *src); - /** Subscribe socket to trigger id. */ - bool Subscribe(int id, Socket *dst); - /** Unsubscribe socket from trigger id. */ - bool Unsubscribe(int id, Socket *dst); - /** Execute OnTrigger for subscribed sockets. - \param id Trigger ID - \param data Data passed from source to destination - \param erase Empty trigger id source and destination maps if 'true', - Leave them in place if 'false' - if a trigger should be called many times */ - void Trigger(int id, Socket::TriggerData& data, bool erase = true); -#endif // ENABLE_TRIGGERS - -#ifdef ENABLE_DETACH - /** Indicates that the handler runs under SocketThread. */ - void SetSlave(bool x = true); - /** Indicates that the handler runs under SocketThread. */ - bool IsSlave(); -#endif - - /** Sanity check of those accursed lists. */ - void CheckSanity(); - -protected: - socket_m m_sockets; ///< Active sockets map - socket_m m_add; ///< Sockets to be added to sockets map - std::list m_delete; ///< Sockets to be deleted (failed when Add) - -protected: - StdLog *m_stdlog; ///< Registered log class, or NULL - Mutex& m_mutex; ///< Thread safety mutex - bool m_b_use_mutex; ///< Mutex correctly initialized - -private: - void CheckList(socket_v&,const std::string&); ///< Used by CheckSanity - /** Remove socket from socket map, used by Socket class. */ - void Remove(Socket *); - SOCKET m_maxsock; ///< Highest file descriptor + 1 in active sockets list - fd_set m_rfds; ///< file descriptor set monitored for read events - fd_set m_wfds; ///< file descriptor set monitored for write events - fd_set m_efds; ///< file descriptor set monitored for exceptions - int m_preverror; ///< debug select() error - int m_errcnt; ///< debug select() error - time_t m_tlast; ///< timeout control - - // state lists - socket_v m_fds; ///< Active file descriptor list - socket_v m_fds_erase; ///< File descriptors that are to be erased from m_sockets - socket_v m_fds_callonconnect; ///< checklist CallOnConnect -#ifdef ENABLE_DETACH - socket_v m_fds_detach; ///< checklist Detach -#endif - socket_v m_fds_timeout; ///< checklist timeout - socket_v m_fds_retry; ///< checklist retry client connect - socket_v m_fds_close; ///< checklist close and delete - -#ifdef ENABLE_SOCKS4 - ipaddr_t m_socks4_host; ///< Socks4 server host ip - port_t m_socks4_port; ///< Socks4 server port number - std::string m_socks4_userid; ///< Socks4 userid - bool m_bTryDirect; ///< Try direct connection if socks4 server fails -#endif -#ifdef ENABLE_RESOLVER - int m_resolv_id; ///< Resolver id counter - ResolvServer *m_resolver; ///< Resolver thread pointer - port_t m_resolver_port; ///< Resolver listen port - std::map m_resolve_q; ///< resolve queue -#endif -#ifdef ENABLE_POOL - bool m_b_enable_pool; ///< Connection pool enabled if true -#endif -#ifdef ENABLE_TRIGGERS - int m_next_trigger_id; ///< Unique trigger id counter - std::map m_trigger_src; ///< mapping trigger id to source socket - std::map > m_trigger_dst; ///< mapping trigger id to destination sockets -#endif -#ifdef ENABLE_DETACH - bool m_slave; ///< Indicates that this is a ISocketHandler run in SocketThread -#endif -}; - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // _SOCKETS_SocketHandler_H - - diff --git a/externals/sockets/include/StdLog.h b/externals/sockets/include/StdLog.h deleted file mode 100644 index 3ff68d6e9ea..00000000000 --- a/externals/sockets/include/StdLog.h +++ /dev/null @@ -1,73 +0,0 @@ -/** \file StdLog.h - ** \date 2004-06-01 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_StdLog_H -#define _SOCKETS_StdLog_H - -#include "sockets-config.h" -#include - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/** error level enum. */ -typedef enum -{ - LOG_LEVEL_WARNING = 0, - LOG_LEVEL_ERROR, - LOG_LEVEL_FATAL, - LOG_LEVEL_INFO -} loglevel_t; - -class ISocketHandler; -class Socket; - -/** \defgroup logging Log help classes */ -/** Log class interface. - \ingroup logging */ -class StdLog -{ -public: - virtual ~StdLog() {} - - virtual void error(ISocketHandler *,Socket *, - const std::string& user_text, - int err, - const std::string& sys_err, - loglevel_t = LOG_LEVEL_WARNING) = 0; -}; - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // _SOCKETS_StdLog_H - - diff --git a/externals/sockets/include/StdoutLog.h b/externals/sockets/include/StdoutLog.h deleted file mode 100644 index aeb25b3e6e6..00000000000 --- a/externals/sockets/include/StdoutLog.h +++ /dev/null @@ -1,55 +0,0 @@ -/** \file StdoutLog.h - ** \date 2004-06-01 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_StdoutLog_H -#define _SOCKETS_StdoutLog_H - -#include "sockets-config.h" -#include "StdLog.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/** StdLog implementation, logs to stdout. - \ingroup logging */ -class StdoutLog : public StdLog -{ -public: - void error(ISocketHandler *,Socket *,const std::string& call,int err,const std::string& sys_err,loglevel_t); -}; - - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // _SOCKETS_StdoutLog_H - - diff --git a/externals/sockets/include/StreamSocket.h b/externals/sockets/include/StreamSocket.h deleted file mode 100644 index bcce10ffbc5..00000000000 --- a/externals/sockets/include/StreamSocket.h +++ /dev/null @@ -1,124 +0,0 @@ -#ifndef _StreamSocket_H -#define _StreamSocket_H - -#include "Socket.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/** SOCK_STREAM Socket base class. - \ingroup basic */ -class StreamSocket : public Socket -{ -public: - StreamSocket(ISocketHandler& ); - ~StreamSocket(); - - /** Socket should Check Connect on next write event from select(). */ - void SetConnecting(bool = true); - - /** Check connecting flag. - \return true if the socket is still trying to connect */ - bool Connecting(); - - /** Returns true when socket file descriptor is valid, - socket connection is established, and socket is not about to - be closed. */ - bool Ready(); - - /** Set timeout to use for connection attempt. - \param x Timeout in seconds */ - void SetConnectTimeout(int x); - - /** Return number of seconds to wait for a connection. - \return Connection timeout (seconds) */ - int GetConnectTimeout(); - - /** Set flush before close to make a tcp socket completely empty its - output buffer before closing the connection. */ - void SetFlushBeforeClose(bool = true); - - /** Check flush before status. - \return true if the socket should send all data before closing */ - bool GetFlushBeforeClose(); - - /** Define number of connection retries (tcp only). - n = 0 - no retry - n > 0 - number of retries - n = -1 - unlimited retries */ - void SetConnectionRetry(int n); - - /** Get number of maximum connection retries (tcp only). */ - int GetConnectionRetry(); - - /** Increase number of actual connection retries (tcp only). */ - void IncreaseConnectionRetries(); - - /** Get number of actual connection retries (tcp only). */ - int GetConnectionRetries(); - - /** Reset actual connection retries (tcp only). */ - void ResetConnectionRetries(); - - // LIST_CALLONCONNECT - - /** Instruct socket to call OnConnect callback next sockethandler cycle. */ - void SetCallOnConnect(bool x = true); - - /** Check call on connect flag. - \return true if OnConnect() should be called a.s.a.p */ - bool CallOnConnect(); - - // LIST_RETRY - - /** Set flag to initiate a connection attempt after a connection timeout. */ - void SetRetryClientConnect(bool x = true); - - /** Check if a connection attempt should be made. - \return true when another attempt should be made */ - bool RetryClientConnect(); - - /** Called after OnRead if socket is in line protocol mode. - \sa SetLineProtocol */ - /** Enable the OnLine callback. Do not create your own OnRead - * callback when using this. */ - virtual void SetLineProtocol(bool = true); - - /** Check line protocol mode. - \return true if socket is in line protocol mode */ - bool LineProtocol(); - - /** Set shutdown status. */ - void SetShutdown(int); - - /** Get shutdown status. */ - int GetShutdown(); - - /** Returns IPPROTO_TCP or IPPROTO_SCTP */ - virtual int Protocol() = 0; - -protected: - StreamSocket(const StreamSocket& ) {} // copy constructor - -private: - StreamSocket& operator=(const StreamSocket& ) { return *this; } // assignment operator - - bool m_bConnecting; ///< Flag indicating connection in progress - int m_connect_timeout; ///< Connection timeout (seconds) - bool m_flush_before_close; ///< Send all data before closing (default true) - int m_connection_retry; ///< Maximum connection retries (tcp) - int m_retries; ///< Actual number of connection retries (tcp) - bool m_call_on_connect; ///< OnConnect will be called next ISocketHandler cycle if true - bool m_b_retry_connect; ///< Try another connection attempt next ISocketHandler cycle - bool m_line_protocol; ///< Line protocol mode flag - int m_shutdown; ///< Shutdown status -}; - -#ifdef SOCKETS_NAMESPACE -} // namespace SOCKETS_NAMESPACE { -#endif - -#endif // _StreamSocket_H - - diff --git a/externals/sockets/include/TcpSocket.h b/externals/sockets/include/TcpSocket.h deleted file mode 100644 index de1be8bd8b9..00000000000 --- a/externals/sockets/include/TcpSocket.h +++ /dev/null @@ -1,356 +0,0 @@ -/** \file TcpSocket.h - ** \date 2004-02-13 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_TcpSocket_H -#define _SOCKETS_TcpSocket_H -#include "sockets-config.h" -#include "StreamSocket.h" -#ifdef HAVE_OPENSSL -#include -#include "SSLInitializer.h" -#endif - -#include - -#define TCP_BUFSIZE_READ 16400 -#define TCP_OUTPUT_CAPACITY 1024000 - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -class SocketAddress; - -/** Socket implementation for TCP. - \ingroup basic */ -class TcpSocket : public StreamSocket -{ - /** \defgroup internal Internal utility */ -protected: - /** Buffer class containing one read/write circular buffer. - \ingroup internal */ - class CircularBuffer - { - public: - CircularBuffer(size_t size); - ~CircularBuffer(); - - /** append l bytes from p to buffer */ - bool Write(const char *p,size_t l); - /** copy l bytes from buffer to dest */ - bool Read(char *dest,size_t l); - /** copy l bytes from buffer to dest, dont touch buffer pointers */ - bool SoftRead(char *dest, size_t l); - /** skip l bytes from buffer */ - bool Remove(size_t l); - /** read l bytes from buffer, returns as string. */ - std::string ReadString(size_t l); - - /** total buffer length */ - size_t GetLength(); - /** pointer to circular buffer beginning */ - const char *GetStart(); - /** return number of bytes from circular buffer beginning to buffer physical end */ - size_t GetL(); - /** return free space in buffer, number of bytes until buffer overrun */ - size_t Space(); - - /** return total number of bytes written to this buffer, ever */ - unsigned long ByteCounter(bool clear = false); - - private: - CircularBuffer(const CircularBuffer& /*s*/) {} - CircularBuffer& operator=(const CircularBuffer& ) { return *this; } - char *buf; - size_t m_max; - size_t m_q; - size_t m_b; - size_t m_t; - unsigned long m_count; - }; - /** Output buffer struct. - \ingroup internal */ - struct OUTPUT { - OUTPUT() : _b(0), _t(0), _q(0) {} - OUTPUT(const char *buf, size_t len) : _b(0), _t(len), _q(len) { - memcpy(_buf, buf, len); - } - size_t Space() { - return TCP_OUTPUT_CAPACITY - _t; - } - void Add(const char *buf, size_t len) { - memcpy(_buf + _t, buf, len); - _t += len; - _q += len; - } - size_t Remove(size_t len) { - _b += len; - _q -= len; - return _q; - } - const char *Buf() { - return _buf + _b; - } - size_t Len() { - return _q; - } - size_t _b; - size_t _t; - size_t _q; - char _buf[TCP_OUTPUT_CAPACITY]; - }; - typedef std::list output_l; - -public: - /** Constructor with standard values on input/output buffers. */ - TcpSocket(ISocketHandler& ); - /** Constructor with custom values for i/o buffer. - \param h ISocketHandler reference - \param isize Input buffer size - \param osize Output buffer size */ - TcpSocket(ISocketHandler& h,size_t isize,size_t osize); - ~TcpSocket(); - - /** Open a connection to a remote server. - If you want your socket to connect to a server, - always call Open before Add'ing a socket to the sockethandler. - If not, the connection attempt will not be monitored by the - socket handler... - \param ip IP address - \param port Port number - \param skip_socks Do not use socks4 even if configured */ - bool Open(ipaddr_t ip,port_t port,bool skip_socks = false); -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - /** Open connection. - \param ip Ipv6 address - \param port Port number - \param skip_socks Do not use socks4 even if configured */ - bool Open(in6_addr ip,port_t port,bool skip_socks = false); -#endif -#endif - bool Open(SocketAddress&,bool skip_socks = false); - bool Open(SocketAddress&,SocketAddress& bind_address,bool skip_socks = false); - /** Open connection. - \param host Hostname - \param port Port number */ - bool Open(const std::string &host,port_t port); - - /** Connect timeout callback. */ - void OnConnectTimeout(); -#ifdef _WIN32 - /** Connection failed reported as exception on win32 */ - void OnException(); -#endif - - /** Close file descriptor - internal use only. - \sa SetCloseAndDelete */ - int Close(); - - /** Send a string. - \param s String to send - \param f Dummy flags -- not used */ - void Send(const std::string &s,int f = 0); - /** Send string using printf formatting. */ - void Sendf(const char *format, ...); - /** Send buffer of bytes. - \param buf Buffer pointer - \param len Length of data - \param f Dummy flags -- not used */ - void SendBuf(const char *buf,size_t len,int f = 0); - /** This callback is executed after a successful read from the socket. - \param buf Pointer to the data - \param len Length of the data */ - virtual void OnRawData(const char *buf,size_t len); - - /** Called when output buffer has been sent. - Note: Will only be called IF the output buffer has been used. - Send's that was successful without needing the output buffer - will not generate a call to this method. */ - virtual void OnWriteComplete(); - /** Number of bytes in input buffer. */ - size_t GetInputLength(); - /** Number of bytes in output buffer. */ - size_t GetOutputLength(); - - /** Callback fires when a socket in line protocol has read one full line. - \param line Line read */ - void OnLine(const std::string& line); - /** Get counter of number of bytes received. */ - uint64_t GetBytesReceived(bool clear = false); - /** Get counter of number of bytes sent. */ - uint64_t GetBytesSent(bool clear = false); - - /** Socks4 specific callback. */ - void OnSocks4Connect(); - /** Socks4 specific callback. */ - void OnSocks4ConnectFailed(); - /** Socks4 specific callback. - \return 'need_more' */ - bool OnSocks4Read(); - -#ifdef ENABLE_RESOLVER - /** Callback executed when resolver thread has finished a resolve request. */ - void OnResolved(int id,ipaddr_t a,port_t port); -#ifdef ENABLE_IPV6 - void OnResolved(int id,in6_addr& a,port_t port); -#endif -#endif -#ifdef HAVE_OPENSSL - /** Callback for 'New' ssl support - replaces SSLSocket. Internal use. */ - void OnSSLConnect(); - /** Callback for 'New' ssl support - replaces SSLSocket. Internal use. */ - void OnSSLAccept(); - /** This method must be implemented to initialize - the ssl context for an outgoing connection. */ - virtual void InitSSLClient(); - /** This method must be implemented to initialize - the ssl context for an incoming connection. */ - virtual void InitSSLServer(); -#endif - -#ifdef ENABLE_RECONNECT - /** Flag that says a broken connection will try to reconnect. */ - void SetReconnect(bool = true); - /** Check reconnect on lost connection flag status. */ - bool Reconnect(); - /** Flag to determine if a reconnect is in progress. */ - void SetIsReconnect(bool x = true); - /** Socket is reconnecting. */ - bool IsReconnect(); -#endif - - void DisableInputBuffer(bool = true); - - void OnOptions(int,int,int,SOCKET); - - void SetLineProtocol(bool = true); - - // TCP options - bool SetTcpNodelay(bool = true); - - virtual int Protocol(); - - /** Trigger limit for callback OnTransferLimit. */ - void SetTransferLimit(size_t sz); - /** This callback fires when the output buffer drops below the value - set by SetTransferLimit. Default: 0 (disabled). */ - virtual void OnTransferLimit(); - -protected: - TcpSocket(const TcpSocket& ); - void OnRead(); - void OnRead( char *buf, size_t n ); - void OnWrite(); -#ifdef HAVE_OPENSSL - /** SSL; Initialize ssl context for a client socket. - \param meth_in SSL method */ - void InitializeContext(const std::string& context, SSL_METHOD *meth_in = NULL); - /** SSL; Initialize ssl context for a server socket. - \param keyfile Combined private key/certificate file - \param password Password for private key - \param meth_in SSL method */ - void InitializeContext(const std::string& context, const std::string& keyfile, const std::string& password, SSL_METHOD *meth_in = NULL); - /** SSL; Initialize ssl context for a server socket. - \param certfile Separate certificate file - \param keyfile Combined private key/certificate file - \param password Password for private key - \param meth_in SSL method */ - void InitializeContext(const std::string& context, const std::string& certfile, const std::string& keyfile, const std::string& password, SSL_METHOD *meth_in = NULL); - /** SSL; Password callback method. */ -static int SSL_password_cb(char *buf,int num,int rwflag,void *userdata); - /** SSL; Get pointer to ssl context structure. */ - virtual SSL_CTX *GetSslContext(); - /** SSL; Get pointer to ssl structure. */ - virtual SSL *GetSsl(); - /** ssl; still negotiating connection. */ - bool SSLNegotiate(); - /** SSL; Get ssl password. */ - const std::string& GetPassword(); -#endif - - CircularBuffer ibuf; ///< Circular input buffer - -private: - TcpSocket& operator=(const TcpSocket& ) { return *this; } - - /** the actual send() */ - int TryWrite(const char *buf, size_t len); - /** add data to output buffer top */ - void Buffer(const char *buf, size_t len); - - // - bool m_b_input_buffer_disabled; - uint64_t m_bytes_sent; - uint64_t m_bytes_received; - bool m_skip_c; ///< Skip second char of CRLF or LFCR sequence in OnRead - char m_c; ///< First char in CRLF or LFCR sequence - std::string m_line; ///< Current line in line protocol mode -#ifdef SOCKETS_DYNAMIC_TEMP - char *m_buf; ///< temporary read buffer -#endif - output_l m_obuf; ///< output buffer - OUTPUT *m_obuf_top; ///< output buffer on top - size_t m_transfer_limit; - size_t m_output_length; - -#ifdef HAVE_OPENSSL -static SSLInitializer m_ssl_init; - SSL_CTX *m_ssl_ctx; ///< ssl context - SSL *m_ssl; ///< ssl 'socket' - BIO *m_sbio; ///< ssl bio - std::string m_password; ///< ssl password -#endif - -#ifdef ENABLE_SOCKS4 - int m_socks4_state; ///< socks4 support - char m_socks4_vn; ///< socks4 support, temporary variable - char m_socks4_cd; ///< socks4 support, temporary variable - unsigned short m_socks4_dstport; ///< socks4 support - unsigned long m_socks4_dstip; ///< socks4 support -#endif - -#ifdef ENABLE_RESOLVER - int m_resolver_id; ///< Resolver id (if any) for current Open call -#endif - -#ifdef ENABLE_RECONNECT - bool m_b_reconnect; ///< Reconnect on lost connection flag - bool m_b_is_reconnect; ///< Trying to reconnect -#endif - -}; - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // _SOCKETS_TcpSocket_H - - diff --git a/externals/sockets/include/Thread.h b/externals/sockets/include/Thread.h deleted file mode 100644 index efb766e9ee6..00000000000 --- a/externals/sockets/include/Thread.h +++ /dev/null @@ -1,100 +0,0 @@ -/** \file Thread.h - ** \date 2004-10-30 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_Thread_H -#define _SOCKETS_Thread_H - -#include "sockets-config.h" -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -#ifdef _WIN32 -// to be -//typedef DWORD threadfunc_t; -//typedef LPVOID threadparam_t; -//#define STDPREFIX WINAPI -typedef unsigned threadfunc_t; -typedef void * threadparam_t; -#define STDPREFIX __stdcall -#else -#include - -typedef void * threadfunc_t; -typedef void * threadparam_t; -#define STDPREFIX -#endif - -/** \defgroup threading Threading */ -/** Thread base class. -The Thread class is used by the resolver (ResolvServer) and running a detached socket (SocketThread). -When you know some processing will take a long time and will freeze up a socket, there is always the -possibility to call Detach() on that socket before starting the processing. -When the OnDetached() callback is later called the processing can continue, now in its own thread. - \ingroup threading */ -class Thread -{ -public: - Thread(bool release = true); - virtual ~Thread(); - - static threadfunc_t STDPREFIX StartThread(threadparam_t); - - virtual void Run() = 0; - - bool IsRunning(); - void SetRunning(bool x); - bool IsReleased(); - void SetRelease(bool x); - bool DeleteOnExit(); - void SetDeleteOnExit(bool x = true); - bool IsDestructor(); - -private: - Thread(const Thread& ) {} - Thread& operator=(const Thread& ) { return *this; } -#ifdef _WIN32 - HANDLE m_thread; - unsigned m_dwThreadId; -#else - pthread_t m_thread; -#endif - bool m_running; - bool m_release; - bool m_b_delete_on_exit; - bool m_b_destructor; -}; - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // _SOCKETS_Thread_H - - diff --git a/externals/sockets/include/UdpSocket.h b/externals/sockets/include/UdpSocket.h deleted file mode 100644 index 3b06c6955bd..00000000000 --- a/externals/sockets/include/UdpSocket.h +++ /dev/null @@ -1,215 +0,0 @@ -/** \file UdpSocket.h - ** \date 2004-02-13 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_UdpSocket_H -#define _SOCKETS_UdpSocket_H - -#include "sockets-config.h" -#include "Socket.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/** Socket implementation for UDP. - \ingroup basic */ -class UdpSocket : public Socket -{ -public: - /** Constructor. - \param h ISocketHandler reference - \param ibufsz Maximum size of receive message (extra bytes will be truncated) - \param ipv6 'true' if this is an ipv6 socket */ - UdpSocket(ISocketHandler& h,int ibufsz = 16384,bool ipv6 = false, int retries = 0); - ~UdpSocket(); - - /** Called when incoming data has been received. - \param buf Pointer to data - \param len Length of data - \param sa Pointer to sockaddr struct of sender - \param sa_len Length of sockaddr struct */ - virtual void OnRawData(const char *buf,size_t len,struct sockaddr *sa,socklen_t sa_len); - - /** Called when incoming data has been received and read timestamp is enabled. - \param buf Pointer to data - \param len Length of data - \param sa Pointer to sockaddr struct of sender - \param sa_len Length of sockaddr struct - \param ts Timestamp from message */ - virtual void OnRawData(const char *buf,size_t len,struct sockaddr *sa,socklen_t sa_len,struct timeval *ts); - - /** To receive incoming data, call Bind to setup an incoming port. - \param port Incoming port number - \param range Port range to try if ports already in use - \return 0 if bind succeeded */ - int Bind(port_t& port,int range = 1); - /** To receive data on a specific interface:port, use this. - \param intf Interface ip/hostname - \param port Port number - \param range Port range - \return 0 if bind succeeded */ - int Bind(const std::string& intf,port_t& port,int range = 1); - /** To receive data on a specific interface:port, use this. - \param a Ip address - \param port Port number - \param range Port range - \return 0 if bind succeeded */ - int Bind(ipaddr_t a,port_t& port,int range = 1); -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - /** To receive data on a specific interface:port, use this. - \param a Ipv6 address - \param port Port number - \param range Port range - \return 0 if bind succeeded */ - int Bind(in6_addr a,port_t& port,int range = 1); -#endif -#endif - /** To receive data on a specific interface:port, use this. - \param ad Socket address - \param range Port range - \return 0 if bind succeeded */ - int Bind(SocketAddress& ad,int range = 1); - - /** Define remote host. - \param l Address of remote host - \param port Port of remote host - \return true if successful */ - bool Open(ipaddr_t l,port_t port); - /** Define remote host. - \param host Hostname - \param port Port number - \return true if successful */ - bool Open(const std::string& host,port_t port); -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - /** Define remote host. - \param a Address of remote host, ipv6 - \param port Port of remote host - \return true if successful */ - bool Open(struct in6_addr& a,port_t port); -#endif -#endif - /** Define remote host. - \param ad Socket address - \return true if successful */ - bool Open(SocketAddress& ad); - - /** Send to specified host */ - void SendToBuf(const std::string& ,port_t,const char *data,int len,int flags = 0); - /** Send to specified address */ - void SendToBuf(ipaddr_t,port_t,const char *data,int len,int flags = 0); -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - /** Send to specified ipv6 address */ - void SendToBuf(in6_addr,port_t,const char *data,int len,int flags = 0); -#endif -#endif - /** Send to specified socket address */ - void SendToBuf(SocketAddress& ad,const char *data,int len,int flags = 0); - - /** Send string to specified host */ - void SendTo(const std::string&,port_t,const std::string&,int flags = 0); - /** Send string to specified address */ - void SendTo(ipaddr_t,port_t,const std::string&,int flags = 0); -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - /** Send string to specified ipv6 address */ - void SendTo(in6_addr,port_t,const std::string&,int flags = 0); -#endif -#endif - /** Send string to specified socket address */ - void SendTo(SocketAddress& ad,const std::string&,int flags = 0); - - /** Send to connected address */ - void SendBuf(const char *data,size_t,int flags = 0); - /** Send string to connected address. */ - void Send(const std::string& ,int flags = 0); - - /** Set broadcast */ - void SetBroadcast(bool b = true); - /** Check broadcast flag. - \return true broadcast is enabled. */ - bool IsBroadcast(); - - /** multicast */ - void SetMulticastTTL(int ttl = 1); - int GetMulticastTTL(); - void SetMulticastLoop(bool = true); - bool IsMulticastLoop(); - void AddMulticastMembership(const std::string& group,const std::string& intf = "0.0.0.0",int if_index = 0); - void DropMulticastMembership(const std::string& group,const std::string& intf = "0.0.0.0",int if_index = 0); -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - /** multicast, ipv6 only */ - void SetMulticastHops(int = -1); - /** multicast, ipv6 only */ - int GetMulticastHops(); -#endif -#endif - /** Returns true if Bind succeeded. */ - bool IsBound(); - /** Return Bind port number */ - port_t GetPort(); - - void OnOptions(int,int,int,SOCKET) {} - - int GetLastSizeWritten(); - - /** Also read timestamp information from incoming message */ - void SetTimestamp(bool = true); - -protected: - UdpSocket(const UdpSocket& s) : Socket(s) {} - void OnRead(); -#if defined(LINUX) || defined(MACOSX) - /** This method emulates socket recvfrom, but uses messages so we can get the timestamp */ - int ReadTS(char *ioBuf, int inBufSize, struct sockaddr *from, socklen_t fromlen, struct timeval *ts); -#endif - -private: - UdpSocket& operator=(const UdpSocket& ) { return *this; } - /** create before using sendto methods */ - void CreateConnection(); - char *m_ibuf; ///< Input buffer - int m_ibufsz; ///< Size of input buffer - bool m_bind_ok; ///< Bind completed successfully - port_t m_port; ///< Bind port number - int m_last_size_written; - int m_retries; - bool m_b_read_ts; -}; - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // _SOCKETS_UdpSocket_H - - diff --git a/externals/sockets/include/Utility.h b/externals/sockets/include/Utility.h deleted file mode 100644 index 724a94e4b32..00000000000 --- a/externals/sockets/include/Utility.h +++ /dev/null @@ -1,186 +0,0 @@ -/** \file Utility.h - ** \date 2004-02-13 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_Utility_H -#define _SOCKETS_Utility_H - -#include "sockets-config.h" -#include -#include -#include -#include "socket_include.h" -#include -#include - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -#define TWIST_LEN 624 - -class SocketAddress; - -/** Conversion utilities. - \ingroup util */ -class Utility -{ - /** - The Mersenne Twister - http://www.math.keio.ac.jp/~matumoto/emt.html - */ - class Rng { - public: - Rng(unsigned long seed); - - unsigned long Get(); - - private: - int m_value; - unsigned long m_tmp[TWIST_LEN]; - }; - class ncmap_compare { - public: - bool operator()(const std::string& x, const std::string& y) const { - return strcasecmp(x.c_str(), y.c_str()) < 0; - } - }; -public: - template class ncmap : public std::map { - public: - ncmap() {} - }; -public: - static std::string base64(const std::string& str_in); - static std::string base64d(const std::string& str_in); - static std::string l2string(long l); - static std::string bigint2string(uint64_t l); - static uint64_t atoi64(const std::string& str); - static unsigned int hex2unsigned(const std::string& str); - static std::string rfc1738_encode(const std::string& src); - static std::string rfc1738_decode(const std::string& src); - - /** Checks whether a string is a valid ipv4/ipv6 ip number. */ - static bool isipv4(const std::string&); - /** Checks whether a string is a valid ipv4/ipv6 ip number. */ - static bool isipv6(const std::string&); - - /** Hostname to ip resolution ipv4, not asynchronous. */ - static bool u2ip(const std::string&, ipaddr_t&); - static bool u2ip(const std::string&, struct sockaddr_in& sa, int ai_flags = 0); - -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - /** Hostname to ip resolution ipv6, not asynchronous. */ - static bool u2ip(const std::string&, struct in6_addr&); - static bool u2ip(const std::string&, struct sockaddr_in6& sa, int ai_flags = 0); -#endif -#endif - - /** Reverse lookup of address to hostname */ - static bool reverse(struct sockaddr *sa, socklen_t sa_len, std::string&, int flags = 0); - static bool reverse(struct sockaddr *sa, socklen_t sa_len, std::string& hostname, std::string& service, int flags = 0); - - static bool u2service(const std::string& name, int& service, int ai_flags = 0); - - /** Convert binary ip address to string: ipv4. */ - static void l2ip(const ipaddr_t,std::string& ); - static void l2ip(const in_addr&,std::string& ); -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - /** Convert binary ip address to string: ipv6. */ - static void l2ip(const struct in6_addr&,std::string& ,bool mixed = false); - - /** ipv6 address compare. */ - static int in6_addr_compare(in6_addr,in6_addr); -#endif -#endif - /** ResolveLocal (hostname) - call once before calling any GetLocal method. */ - static void ResolveLocal(); - /** Returns local hostname, ResolveLocal must be called once before using. - \sa ResolveLocal */ - static const std::string& GetLocalHostname(); - /** Returns local ip, ResolveLocal must be called once before using. - \sa ResolveLocal */ - static ipaddr_t GetLocalIP(); - /** Returns local ip number as string. - \sa ResolveLocal */ - static const std::string& GetLocalAddress(); -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - /** Returns local ipv6 ip. - \sa ResolveLocal */ - static const struct in6_addr& GetLocalIP6(); - /** Returns local ipv6 address. - \sa ResolveLocal */ - static const std::string& GetLocalAddress6(); -#endif -#endif - /** Set environment variable. - \param var Name of variable to set - \param value Value */ - static void SetEnv(const std::string& var,const std::string& value); - /** Convert sockaddr struct to human readable string. - \param sa Ptr to sockaddr struct */ - static std::string Sa2String(struct sockaddr *sa); - - /** Get current time in sec/microseconds. */ - static void GetTime(struct timeval *); - - static std::auto_ptr CreateAddress(struct sockaddr *,socklen_t); - - static unsigned long ThreadID(); - - static std::string ToLower(const std::string& str); - static std::string ToUpper(const std::string& str); - - static std::string ToString(double d); - - /** Returns a random 32-bit integer */ - static unsigned long Rnd(); - -private: - static std::string m_host; ///< local hostname - static ipaddr_t m_ip; ///< local ip address - static std::string m_addr; ///< local ip address in string format -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - static struct in6_addr m_local_ip6; ///< local ipv6 address -#endif - static std::string m_local_addr6; ///< local ipv6 address in string format -#endif - static bool m_local_resolved; ///< ResolveLocal has been called if true -}; - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // _SOCKETS_Utility_H - - diff --git a/externals/sockets/include/socket_include.h b/externals/sockets/include/socket_include.h deleted file mode 100644 index 89855a54108..00000000000 --- a/externals/sockets/include/socket_include.h +++ /dev/null @@ -1,290 +0,0 @@ -/** \file socket_include.h - ** \date 2005-04-12 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_socket_include_H -#define _SOCKETS_socket_include_H -#include "sockets-config.h" - -#ifdef _MSC_VER -#pragma warning(disable:4514) -#endif - -// common defines affecting library and applications using library - -/* Define SOCKETS_DYNAMIC_TEMP to use dynamically allocated buffers - in read operations - helps on ECOS */ -#define SOCKETS_DYNAMIC_TEMP - -// platform specific stuff -#if (defined(__unix__) || defined(unix)) && !defined(USG) -#include -#endif -#include - -// int64 -#ifdef _WIN32 -typedef unsigned __int64 uint64_t; -#else -#include -#ifdef SOLARIS -# include -#else -# include -#endif -#endif - -#ifndef _WIN32 -// ---------------------------------------- -// common unix includes / defines -#include -#include -#include -#include -#include -#include -//#include - -// all typedefs in this file will be declared outside the sockets namespace, -// because some os's will already have one or more of the type defined. -typedef int SOCKET; -#define Errno errno -#define StrError strerror - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -// WIN32 adapt -#define closesocket close -#define INVALID_SOCKET -1 -#define SOCKET_ERROR -1 - -#ifndef INADDR_NONE -#define INADDR_NONE ((unsigned long) -1) -#endif // INADDR_NONE - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // !_WIN32 - -// ---------------------------------------- -// Generic -#ifndef SOL_IP -#define SOL_IP IPPROTO_IP -#endif - -// ---------------------------------------- -// OS specific adaptions - -#ifdef SOLARIS -// ---------------------------------------- -// Solaris -typedef unsigned short port_t; -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif -// no defs - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#define s6_addr16 _S6_un._S6_u8 -#define MSG_NOSIGNAL 0 - -#elif defined __FreeBSD__ -// ---------------------------------------- -// FreeBSD -# if __FreeBSD_version >= 400014 -# define s6_addr16 __u6_addr.__u6_addr16 -# if !defined(MSG_NOSIGNAL) -# define MSG_NOSIGNAL 0 -# endif -# include -typedef in_addr_t ipaddr_t; -typedef in_port_t port_t; -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif -// no defs - -#ifdef SOCKETS_NAMESPACE -} -#endif - -# define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP -# define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP -# else -# error FreeBSD versions prior to 400014 does not support ipv6 -# endif - -#elif defined (__NetBSD__) || defined (__OpenBSD__) -# if !defined(MSG_NOSIGNAL) -# define MSG_NOSIGNAL 0 -# endif -# include -typedef in_addr_t ipaddr_t; -typedef in_port_t port_t; -#elif defined MACOSX -// ---------------------------------------- -// Mac OS X -#include -#ifdef __DARWIN_UNIX03 -typedef unsigned short port_t; -#else -#include -#endif // __DARWIN_UNIX03 -typedef unsigned long ipaddr_t; -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif -// no defs - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#define s6_addr16 __u6_addr.__u6_addr16 -#define MSG_NOSIGNAL 0 // oops - thanks Derek -#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP -#define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP - -#elif defined _WIN32 -// ---------------------------------------- -// Win32 -#ifdef _MSC_VER -#pragma comment(lib, "wsock32.lib") -#endif -#define strcasecmp _stricmp - -typedef unsigned long ipaddr_t; -typedef unsigned short port_t; -typedef int socklen_t; -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif -// no defs - -#ifdef SOCKETS_NAMESPACE -} -#endif - -// 1.8.6: define FD_SETSIZE to something bigger than 64 if there are a lot of -// simultaneous connections (must be done before including winsock.h) -#define FD_SETSIZE 1024 - -// windows 2000 with ipv6 preview installed: -// http://msdn.microsoft.com/downloads/sdks/platform/tpipv6.asp -// see the FAQ on how to install -#define WIN32_LEAN_AND_MEAN -#include -#include -#if _MSC_VER < 1200 -#ifndef __CYGWIN__ -#ifdef ENABLE_IPV6 -#include // For IPv6 Tech Preview. -#endif -#endif -#endif // _MSC_VER < 1200 - -#define MSG_NOSIGNAL 0 -//#define SHUT_RDWR 2 -#define SHUT_WR 1 - -#define Errno WSAGetLastError() -const char *StrError(int x); - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -// class WSAInitializer is a part of the Socket class (on win32) -// as a static instance - so whenever an application uses a Socket, -// winsock is initialized -class WSAInitializer // Winsock Initializer -{ -public: - WSAInitializer() { - if (WSAStartup(0x101,&m_wsadata)) - { - exit(-1); - } - } - ~WSAInitializer() { - WSACleanup(); - } -private: - WSADATA m_wsadata; -}; - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#else -// ---------------------------------------- -// LINUX -typedef unsigned long ipaddr_t; -typedef unsigned short port_t; -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif -// no defs - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - /** List type containing file descriptors. */ - typedef std::list socket_v; - -#ifdef SOCKETS_NAMESPACE -} -#endif - -// getaddrinfo / getnameinfo replacements -#ifdef NO_GETADDRINFO -#ifndef AI_NUMERICHOST -#define AI_NUMERICHOST 1 -#endif -#ifndef NI_NUMERICHOST -#define NI_NUMERICHOST 1 -#endif -#endif - -#endif // _SOCKETS_socket_include_H - - diff --git a/externals/sockets/include/sockets-config.h b/externals/sockets/include/sockets-config.h deleted file mode 100644 index 1c8dc439092..00000000000 --- a/externals/sockets/include/sockets-config.h +++ /dev/null @@ -1,90 +0,0 @@ -/** - ** \file sockets-config.h - ** \date 2007-04-14 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2007 Anders Hedstrom - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_CONFIG_H -#define _SOCKETS_CONFIG_H - -#ifndef _RUN_DP -/* First undefine symbols if already defined. */ -#undef HAVE_OPENSSL -#undef ENABLE_IPV6 -#undef USE_SCTP -#undef NO_GETADDRINFO -#undef ENABLE_POOL -#undef ENABLE_SOCKS4 -#undef ENABLE_RESOLVER -#undef ENABLE_RECONNECT -#undef ENABLE_DETACH -#undef ENABLE_TRIGGERS -#undef ENABLE_EXCEPTIONS -#endif // _RUN_DP - -// define MACOSX for internal socket library checks -#if defined(__APPLE__) && defined(__MACH__) && !defined(MACOSX) -#define MACOSX -#endif - -/* OpenSSL support. */ -//#define HAVE_OPENSSL - -/* Ipv6 support. */ -//#define ENABLE_IPV6 - -/* SCTP support. */ -//#define USE_SCTP - -/* Define NO_GETADDRINFO if your operating system does not support - the "getaddrinfo" and "getnameinfo" function calls. */ -#define NO_GETADDRINFO - -/* Connection pool support. */ -#define ENABLE_POOL - -/* Socks4 client support. */ -//#define ENABLE_SOCKS4 - -/* Asynchronous resolver. */ -#define ENABLE_RESOLVER - -/* Enable TCP reconnect on lost connection. - Socket::OnReconnect - Socket::OnDisconnect -*/ -#define ENABLE_RECONNECT - -/* Enable socket thread detach functionality. */ -#define ENABLE_DETACH - -/* Enable socket to socket triggers. Not yet in use. */ -//#define ENABLE_TRIGGERS - -/* Enabled exceptions. */ -//#define ENABLE_EXCEPTIONS - -/* Resolver uses the detach function so either enable both or disable both. */ -#ifndef ENABLE_DETACH -#undef ENABLE_RESOLVER -#endif - -#endif // _SOCKETS_CONFIG_H - - diff --git a/externals/sockets/network_kist.txt b/externals/sockets/network_kist.txt deleted file mode 100644 index f6597bf9c77..00000000000 --- a/externals/sockets/network_kist.txt +++ /dev/null @@ -1,20 +0,0 @@ -The following are the only .cpp files used from the new network library (v2.2.8) This file is just for future reference. - -Base64.cpp -Exception.cpp -Ipv4Address.cpp -Ipv6Address.cpp -Lock.cpp -Mutex.cpp -Parse.cpp -ResolvServer.cpp -ResolvSocket.cpp -Socket.cpp -SocketHandler.cpp -socket_include.cpp -StdoutLog.cpp -StreamSocket.cpp -TcpSocket.cpp -Thread.cpp -UdpSocket.cpp -Utility.cpp diff --git a/externals/sockets/socket_include.cpp b/externals/sockets/socket_include.cpp deleted file mode 100644 index 290602c1b52..00000000000 --- a/externals/sockets/socket_include.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/** \file socket_include.cpp - ** \date 2004-11-28 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#include - -// only to be included in win32 projects -const char *StrError(int x) -{ -static char tmp[100]; - switch (x) - { - case 10004: return "Interrupted function call."; - case 10013: return "Permission denied."; - case 10014: return "Bad address."; - case 10022: return "Invalid argument."; - case 10024: return "Too many open files."; - case 10035: return "Resource temporarily unavailable."; - case 10036: return "Operation now in progress."; - case 10037: return "Operation already in progress."; - case 10038: return "Socket operation on nonsocket."; - case 10039: return "Destination address required."; - case 10040: return "Message too long."; - case 10041: return "Protocol wrong type for socket."; - case 10042: return "Bad protocol option."; - case 10043: return "Protocol not supported."; - case 10044: return "Socket type not supported."; - case 10045: return "Operation not supported."; - case 10046: return "Protocol family not supported."; - case 10047: return "Address family not supported by protocol family."; - case 10048: return "Address already in use."; - case 10049: return "Cannot assign requested address."; - case 10050: return "Network is down."; - case 10051: return "Network is unreachable."; - case 10052: return "Network dropped connection on reset."; - case 10053: return "Software caused connection abort."; - case 10054: return "Connection reset by peer."; - case 10055: return "No buffer space available."; - case 10056: return "Socket is already connected."; - case 10057: return "Socket is not connected."; - case 10058: return "Cannot send after socket shutdown."; - case 10060: return "Connection timed out."; - case 10061: return "Connection refused."; - case 10064: return "Host is down."; - case 10065: return "No route to host."; - case 10067: return "Too many processes."; - case 10091: return "Network subsystem is unavailable."; - case 10092: return "Winsock.dll version out of range."; - case 10093: return "Successful WSAStartup not yet performed."; - case 10101: return "Graceful shutdown in progress."; - case 10109: return "Class type not found."; - case 11001: return "Host not found."; - case 11002: return "Nonauthoritative host not found."; - case 11003: return "This is a nonrecoverable error."; - case 11004: return "Valid name, no data record of requested type."; - - default: - break; - } - sprintf(tmp, "Winsock error code: %d", x); - return tmp; -} - - diff --git a/externals/utf8cpp/utf8.h b/externals/utf8cpp/utf8.h deleted file mode 100644 index 82b13f59f98..00000000000 --- a/externals/utf8cpp/utf8.h +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2006 Nemanja Trifunovic - -/* -Permission is hereby granted, free of charge, to any person or organization -obtaining a copy of the software and accompanying documentation covered by -this license (the "Software") to use, reproduce, display, distribute, -execute, and transmit the Software, and to prepare derivative works of the -Software, and to permit third-parties to whom the Software is furnished to -do so, all subject to the following: - -The copyright notices in the Software and this entire statement, including -the above license grant, this restriction and the following disclaimer, -must be included in all copies of the Software, in whole or in part, and -all derivative works of the Software, unless such copies or derivative -works are solely in the form of machine-executable object code generated by -a source language processor. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT -SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE -FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -*/ - - -#ifndef UTF8_FOR_CPP_2675DCD0_9480_4c0c_B92A_CC14C027B731 -#define UTF8_FOR_CPP_2675DCD0_9480_4c0c_B92A_CC14C027B731 - -#include "utf8/checked.h" -#include "utf8/unchecked.h" - -#endif // header guard diff --git a/externals/utf8cpp/utf8/checked.h b/externals/utf8cpp/utf8/checked.h deleted file mode 100644 index a1d2035364d..00000000000 --- a/externals/utf8cpp/utf8/checked.h +++ /dev/null @@ -1,323 +0,0 @@ -// Copyright 2006 Nemanja Trifunovic - -/* -Permission is hereby granted, free of charge, to any person or organization -obtaining a copy of the software and accompanying documentation covered by -this license (the "Software") to use, reproduce, display, distribute, -execute, and transmit the Software, and to prepare derivative works of the -Software, and to permit third-parties to whom the Software is furnished to -do so, all subject to the following: - -The copyright notices in the Software and this entire statement, including -the above license grant, this restriction and the following disclaimer, -must be included in all copies of the Software, in whole or in part, and -all derivative works of the Software, unless such copies or derivative -works are solely in the form of machine-executable object code generated by -a source language processor. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT -SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE -FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -*/ - - -#ifndef UTF8_FOR_CPP_CHECKED_H_2675DCD0_9480_4c0c_B92A_CC14C027B731 -#define UTF8_FOR_CPP_CHECKED_H_2675DCD0_9480_4c0c_B92A_CC14C027B731 - -#include "core.h" -#include - -namespace utf8 -{ - // Base for the exceptions that may be thrown from the library - class exception : public std::exception { - }; - - // Exceptions that may be thrown from the library functions. - class invalid_code_point : public exception { - uint32_t cp; - public: - invalid_code_point(uint32_t cp) : cp(cp) {} - virtual const char* what() const throw() { return "Invalid code point"; } - uint32_t code_point() const {return cp;} - }; - - class invalid_utf8 : public exception { - uint8_t u8; - public: - invalid_utf8 (uint8_t u) : u8(u) {} - virtual const char* what() const throw() { return "Invalid UTF-8"; } - uint8_t utf8_octet() const {return u8;} - }; - - class invalid_utf16 : public exception { - uint16_t u16; - public: - invalid_utf16 (uint16_t u) : u16(u) {} - virtual const char* what() const throw() { return "Invalid UTF-16"; } - uint16_t utf16_word() const {return u16;} - }; - - class not_enough_room : public exception { - public: - virtual const char* what() const throw() { return "Not enough space"; } - }; - - /// The library API - functions intended to be called by the users - - template - output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out, uint32_t replacement) - { - while (start != end) { - octet_iterator sequence_start = start; - internal::utf_error err_code = internal::validate_next(start, end); - switch (err_code) { - case internal::UTF8_OK : - for (octet_iterator it = sequence_start; it != start; ++it) - *out++ = *it; - break; - case internal::NOT_ENOUGH_ROOM: - throw not_enough_room(); - case internal::INVALID_LEAD: - append (replacement, out); - ++start; - break; - case internal::INCOMPLETE_SEQUENCE: - case internal::OVERLONG_SEQUENCE: - case internal::INVALID_CODE_POINT: - append (replacement, out); - ++start; - // just one replacement mark for the sequence - while (internal::is_trail(*start) && start != end) - ++start; - break; - } - } - return out; - } - - template - inline output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out) - { - static const uint32_t replacement_marker = internal::mask16(0xfffd); - return replace_invalid(start, end, out, replacement_marker); - } - - template - octet_iterator append(uint32_t cp, octet_iterator result) - { - if (!internal::is_code_point_valid(cp)) - throw invalid_code_point(cp); - - if (cp < 0x80) // one octet - *(result++) = static_cast(cp); - else if (cp < 0x800) { // two octets - *(result++) = static_cast((cp >> 6) | 0xc0); - *(result++) = static_cast((cp & 0x3f) | 0x80); - } - else if (cp < 0x10000) { // three octets - *(result++) = static_cast((cp >> 12) | 0xe0); - *(result++) = static_cast(((cp >> 6) & 0x3f) | 0x80); - *(result++) = static_cast((cp & 0x3f) | 0x80); - } - else { // four octets - *(result++) = static_cast((cp >> 18) | 0xf0); - *(result++) = static_cast(((cp >> 12) & 0x3f) | 0x80); - *(result++) = static_cast(((cp >> 6) & 0x3f) | 0x80); - *(result++) = static_cast((cp & 0x3f) | 0x80); - } - return result; - } - - template - uint32_t next(octet_iterator& it, octet_iterator end) - { - uint32_t cp = 0; - internal::utf_error err_code = internal::validate_next(it, end, &cp); - switch (err_code) { - case internal::UTF8_OK : - break; - case internal::NOT_ENOUGH_ROOM : - throw not_enough_room(); - case internal::INVALID_LEAD : - case internal::INCOMPLETE_SEQUENCE : - case internal::OVERLONG_SEQUENCE : - throw invalid_utf8(*it); - case internal::INVALID_CODE_POINT : - throw invalid_code_point(cp); - } - return cp; - } - - template - uint32_t peek_next(octet_iterator it, octet_iterator end) - { - return next(it, end); - } - - template - uint32_t prior(octet_iterator& it, octet_iterator start) - { - octet_iterator end = it; - while (internal::is_trail(*(--it))) - if (it < start) - throw invalid_utf8(*it); // error - no lead byte in the sequence - octet_iterator temp = it; - return next(temp, end); - } - - /// Deprecated in versions that include "prior" - template - uint32_t previous(octet_iterator& it, octet_iterator pass_start) - { - octet_iterator end = it; - while (internal::is_trail(*(--it))) - if (it == pass_start) - throw invalid_utf8(*it); // error - no lead byte in the sequence - octet_iterator temp = it; - return next(temp, end); - } - - template - void advance (octet_iterator& it, distance_type n, octet_iterator end) - { - for (distance_type i = 0; i < n; ++i) - next(it, end); - } - - template - typename std::iterator_traits::difference_type - distance (octet_iterator first, octet_iterator last) - { - typename std::iterator_traits::difference_type dist; - for (dist = 0; first < last; ++dist) - next(first, last); - return dist; - } - - template - octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result) - { - while (start != end) { - uint32_t cp = internal::mask16(*start++); - // Take care of surrogate pairs first - if (internal::is_lead_surrogate(cp)) { - if (start != end) { - uint32_t trail_surrogate = internal::mask16(*start++); - if (internal::is_trail_surrogate(trail_surrogate)) - cp = (cp << 10) + trail_surrogate + internal::SURROGATE_OFFSET; - else - throw invalid_utf16(static_cast(trail_surrogate)); - } - else - throw invalid_utf16(static_cast(cp)); - - } - // Lone trail surrogate - else if (internal::is_trail_surrogate(cp)) - throw invalid_utf16(static_cast(cp)); - - result = append(cp, result); - } - return result; - } - - template - u16bit_iterator utf8to16 (octet_iterator start, octet_iterator end, u16bit_iterator result) - { - while (start != end) { - uint32_t cp = next(start, end); - if (cp > 0xffff) { //make a surrogate pair - *result++ = static_cast((cp >> 10) + internal::LEAD_OFFSET); - *result++ = static_cast((cp & 0x3ff) + internal::TRAIL_SURROGATE_MIN); - } - else - *result++ = static_cast(cp); - } - return result; - } - - template - octet_iterator utf32to8 (u32bit_iterator start, u32bit_iterator end, octet_iterator result) - { - while (start != end) - result = append(*(start++), result); - - return result; - } - - template - u32bit_iterator utf8to32 (octet_iterator start, octet_iterator end, u32bit_iterator result) - { - while (start != end) - (*result++) = next(start, end); - - return result; - } - - // The iterator class - template - class iterator : public std::iterator { - octet_iterator it; - octet_iterator range_start; - octet_iterator range_end; - public: - iterator () {}; - explicit iterator (const octet_iterator& octet_it, - const octet_iterator& range_start, - const octet_iterator& range_end) : - it(octet_it), range_start(range_start), range_end(range_end) - { - if (it < range_start || it > range_end) - throw std::out_of_range("Invalid utf-8 iterator position"); - } - // the default "big three" are OK - octet_iterator base () const { return it; } - uint32_t operator * () const - { - octet_iterator temp = it; - return next(temp, range_end); - } - bool operator == (const iterator& rhs) const - { - if (range_start != rhs.range_start || range_end != rhs.range_end) - throw std::logic_error("Comparing utf-8 iterators defined with different ranges"); - return (it == rhs.it); - } - bool operator != (const iterator& rhs) const - { - return !(operator == (rhs)); - } - iterator& operator ++ () - { - next(it, range_end); - return *this; - } - iterator operator ++ (int) - { - iterator temp = *this; - next(it, range_end); - return temp; - } - iterator& operator -- () - { - prior(it, range_start); - return *this; - } - iterator operator -- (int) - { - iterator temp = *this; - prior(it, range_start); - return temp; - } - }; // class iterator - -} // namespace utf8 - -#endif //header guard - - diff --git a/externals/utf8cpp/utf8/core.h b/externals/utf8cpp/utf8/core.h deleted file mode 100644 index ec709f12006..00000000000 --- a/externals/utf8cpp/utf8/core.h +++ /dev/null @@ -1,358 +0,0 @@ -// Copyright 2006 Nemanja Trifunovic - -/* -Permission is hereby granted, free of charge, to any person or organization -obtaining a copy of the software and accompanying documentation covered by -this license (the "Software") to use, reproduce, display, distribute, -execute, and transmit the Software, and to prepare derivative works of the -Software, and to permit third-parties to whom the Software is furnished to -do so, all subject to the following: - -The copyright notices in the Software and this entire statement, including -the above license grant, this restriction and the following disclaimer, -must be included in all copies of the Software, in whole or in part, and -all derivative works of the Software, unless such copies or derivative -works are solely in the form of machine-executable object code generated by -a source language processor. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT -SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE -FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -*/ - - -#ifndef UTF8_FOR_CPP_CORE_H_2675DCD0_9480_4c0c_B92A_CC14C027B731 -#define UTF8_FOR_CPP_CORE_H_2675DCD0_9480_4c0c_B92A_CC14C027B731 - -#include - -namespace utf8 -{ - // The typedefs for 8-bit, 16-bit and 32-bit unsigned integers - // You may need to change them to match your system. - // These typedefs have the same names as ones from cstdint, or boost/cstdint - typedef unsigned char uint8_t; - typedef unsigned short uint16_t; - typedef unsigned int uint32_t; - -// Helper code - not intended to be directly called by the library users. May be changed at any time -namespace internal -{ - // Unicode constants - // Leading (high) surrogates: 0xd800 - 0xdbff - // Trailing (low) surrogates: 0xdc00 - 0xdfff - const uint16_t LEAD_SURROGATE_MIN = 0xd800u; - const uint16_t LEAD_SURROGATE_MAX = 0xdbffu; - const uint16_t TRAIL_SURROGATE_MIN = 0xdc00u; - const uint16_t TRAIL_SURROGATE_MAX = 0xdfffu; - const uint16_t LEAD_OFFSET = LEAD_SURROGATE_MIN - (0x10000 >> 10); - const uint32_t SURROGATE_OFFSET = 0x10000u - (LEAD_SURROGATE_MIN << 10) - TRAIL_SURROGATE_MIN; - - // Maximum valid value for a Unicode code point - const uint32_t CODE_POINT_MAX = 0x0010ffffu; - - template - inline uint8_t mask8(octet_type oc) - { - return static_cast(0xff & oc); - } - template - inline uint16_t mask16(u16_type oc) - { - return static_cast(0xffff & oc); - } - template - inline bool is_trail(octet_type oc) - { - return ((mask8(oc) >> 6) == 0x2); - } - - template - inline bool is_lead_surrogate(u16 cp) - { - return (cp >= LEAD_SURROGATE_MIN && cp <= LEAD_SURROGATE_MAX); - } - - template - inline bool is_trail_surrogate(u16 cp) - { - return (cp >= TRAIL_SURROGATE_MIN && cp <= TRAIL_SURROGATE_MAX); - } - - template - inline bool is_surrogate(u16 cp) - { - return (cp >= LEAD_SURROGATE_MIN && cp <= TRAIL_SURROGATE_MAX); - } - - template - inline bool is_code_point_valid(u32 cp) - { - return (cp <= CODE_POINT_MAX && !is_surrogate(cp) && cp != 0xfffe && cp != 0xffff); - } - - template - inline typename std::iterator_traits::difference_type - sequence_length(octet_iterator lead_it) - { - uint8_t lead = mask8(*lead_it); - if (lead < 0x80) - return 1; - else if ((lead >> 5) == 0x6) - return 2; - else if ((lead >> 4) == 0xe) - return 3; - else if ((lead >> 3) == 0x1e) - return 4; - else - return 0; - } - - template - inline bool is_overlong_sequence(uint32_t cp, octet_difference_type length) - { - if (cp < 0x80) { - if (length != 1) - return true; - } - else if (cp < 0x800) { - if (length != 2) - return true; - } - else if (cp < 0x10000) { - if (length != 3) - return true; - } - - return false; - } - - enum utf_error {UTF8_OK, NOT_ENOUGH_ROOM, INVALID_LEAD, INCOMPLETE_SEQUENCE, OVERLONG_SEQUENCE, INVALID_CODE_POINT}; - - /// get_sequence_x functions decode utf-8 sequences of the length x - - template - utf_error get_sequence_1(octet_iterator& it, octet_iterator end, uint32_t* code_point) - { - if (it != end) { - if (code_point) - *code_point = mask8(*it); - return UTF8_OK; - } - return NOT_ENOUGH_ROOM; - } - - template - utf_error get_sequence_2(octet_iterator& it, octet_iterator end, uint32_t* code_point) - { - utf_error ret_code = NOT_ENOUGH_ROOM; - - if (it != end) { - uint32_t cp = mask8(*it); - if (++it != end) { - if (is_trail(*it)) { - cp = ((cp << 6) & 0x7ff) + ((*it) & 0x3f); - - if (code_point) - *code_point = cp; - ret_code = UTF8_OK; - } - else - ret_code = INCOMPLETE_SEQUENCE; - } - else - ret_code = NOT_ENOUGH_ROOM; - } - - return ret_code; - } - - template - utf_error get_sequence_3(octet_iterator& it, octet_iterator end, uint32_t* code_point) - { - utf_error ret_code = NOT_ENOUGH_ROOM; - - if (it != end) { - uint32_t cp = mask8(*it); - if (++it != end) { - if (is_trail(*it)) { - cp = ((cp << 12) & 0xffff) + ((mask8(*it) << 6) & 0xfff); - if (++it != end) { - if (is_trail(*it)) { - cp += (*it) & 0x3f; - - if (code_point) - *code_point = cp; - ret_code = UTF8_OK; - } - else - ret_code = INCOMPLETE_SEQUENCE; - } - else - ret_code = NOT_ENOUGH_ROOM; - } - else - ret_code = INCOMPLETE_SEQUENCE; - } - else - ret_code = NOT_ENOUGH_ROOM; - } - - return ret_code; - } - - template - utf_error get_sequence_4(octet_iterator& it, octet_iterator end, uint32_t* code_point) - { - utf_error ret_code = NOT_ENOUGH_ROOM; - - if (it != end) { - uint32_t cp = mask8(*it); - if (++it != end) { - if (is_trail(*it)) { - cp = ((cp << 18) & 0x1fffff) + ((mask8(*it) << 12) & 0x3ffff); - if (++it != end) { - if (is_trail(*it)) { - cp += (mask8(*it) << 6) & 0xfff; - if (++it != end) { - if (is_trail(*it)) { - cp += (*it) & 0x3f; - - if (code_point) - *code_point = cp; - ret_code = UTF8_OK; - } - else - ret_code = INCOMPLETE_SEQUENCE; - } - else - ret_code = NOT_ENOUGH_ROOM; - } - else - ret_code = INCOMPLETE_SEQUENCE; - } - else - ret_code = NOT_ENOUGH_ROOM; - } - else - ret_code = INCOMPLETE_SEQUENCE; - } - else - ret_code = NOT_ENOUGH_ROOM; - } - - return ret_code; - } - - template - utf_error validate_next(octet_iterator& it, octet_iterator end, uint32_t* code_point) - { - // Save the original value of it so we can go back in case of failure - // Of course, it does not make much sense with i.e. stream iterators - octet_iterator original_it = it; - - uint32_t cp = 0; - // Determine the sequence length based on the lead octet - typedef typename std::iterator_traits::difference_type octet_difference_type; - octet_difference_type length = sequence_length(it); - if (length == 0) - return INVALID_LEAD; - - // Now that we have a valid sequence length, get trail octets and calculate the code point - utf_error err = UTF8_OK; - switch (length) { - case 1: - err = get_sequence_1(it, end, &cp); - break; - case 2: - err = get_sequence_2(it, end, &cp); - break; - case 3: - err = get_sequence_3(it, end, &cp); - break; - case 4: - err = get_sequence_4(it, end, &cp); - break; - } - - if (err == UTF8_OK) { - // Decoding succeeded. Now, security checks... - if (is_code_point_valid(cp)) { - if (!is_overlong_sequence(cp, length)){ - // Passed! Return here. - if (code_point) - *code_point = cp; - ++it; - return UTF8_OK; - } - else - err = OVERLONG_SEQUENCE; - } - else - err = INVALID_CODE_POINT; - } - - // Failure branch - restore the original value of the iterator - it = original_it; - return err; - } - - template - inline utf_error validate_next(octet_iterator& it, octet_iterator end) { - return validate_next(it, end, 0); - } - -} // namespace internal - - /// The library API - functions intended to be called by the users - - // Byte order mark - const uint8_t bom[] = {0xef, 0xbb, 0xbf}; - - template - octet_iterator find_invalid(octet_iterator start, octet_iterator end) - { - octet_iterator result = start; - while (result != end) { - internal::utf_error err_code = internal::validate_next(result, end); - if (err_code != internal::UTF8_OK) - return result; - } - return result; - } - - template - inline bool is_valid(octet_iterator start, octet_iterator end) - { - return (find_invalid(start, end) == end); - } - - template - inline bool starts_with_bom (octet_iterator it, octet_iterator end) - { - return ( - ((it != end) && (internal::mask8(*it++)) == bom[0]) && - ((it != end) && (internal::mask8(*it++)) == bom[1]) && - ((it != end) && (internal::mask8(*it)) == bom[2]) - ); - } - - //Deprecated in release 2.3 - template - inline bool is_bom (octet_iterator it) - { - return ( - (internal::mask8(*it++)) == bom[0] && - (internal::mask8(*it++)) == bom[1] && - (internal::mask8(*it)) == bom[2] - ); - } -} // namespace utf8 - -#endif // header guard - - diff --git a/externals/utf8cpp/utf8/unchecked.h b/externals/utf8cpp/utf8/unchecked.h deleted file mode 100644 index 2f3eb4d1d02..00000000000 --- a/externals/utf8cpp/utf8/unchecked.h +++ /dev/null @@ -1,228 +0,0 @@ -// Copyright 2006 Nemanja Trifunovic - -/* -Permission is hereby granted, free of charge, to any person or organization -obtaining a copy of the software and accompanying documentation covered by -this license (the "Software") to use, reproduce, display, distribute, -execute, and transmit the Software, and to prepare derivative works of the -Software, and to permit third-parties to whom the Software is furnished to -do so, all subject to the following: - -The copyright notices in the Software and this entire statement, including -the above license grant, this restriction and the following disclaimer, -must be included in all copies of the Software, in whole or in part, and -all derivative works of the Software, unless such copies or derivative -works are solely in the form of machine-executable object code generated by -a source language processor. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT -SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE -FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -*/ - - -#ifndef UTF8_FOR_CPP_UNCHECKED_H_2675DCD0_9480_4c0c_B92A_CC14C027B731 -#define UTF8_FOR_CPP_UNCHECKED_H_2675DCD0_9480_4c0c_B92A_CC14C027B731 - -#include "core.h" - -namespace utf8 -{ - namespace unchecked - { - template - octet_iterator append(uint32_t cp, octet_iterator result) - { - if (cp < 0x80) // one octet - *(result++) = static_cast(cp); - else if (cp < 0x800) { // two octets - *(result++) = static_cast((cp >> 6) | 0xc0); - *(result++) = static_cast((cp & 0x3f) | 0x80); - } - else if (cp < 0x10000) { // three octets - *(result++) = static_cast((cp >> 12) | 0xe0); - *(result++) = static_cast(((cp >> 6) & 0x3f) | 0x80); - *(result++) = static_cast((cp & 0x3f) | 0x80); - } - else { // four octets - *(result++) = static_cast((cp >> 18) | 0xf0); - *(result++) = static_cast(((cp >> 12) & 0x3f)| 0x80); - *(result++) = static_cast(((cp >> 6) & 0x3f) | 0x80); - *(result++) = static_cast((cp & 0x3f) | 0x80); - } - return result; - } - - template - uint32_t next(octet_iterator& it) - { - uint32_t cp = internal::mask8(*it); - typename std::iterator_traits::difference_type length = utf8::internal::sequence_length(it); - switch (length) { - case 1: - break; - case 2: - it++; - cp = ((cp << 6) & 0x7ff) + ((*it) & 0x3f); - break; - case 3: - ++it; - cp = ((cp << 12) & 0xffff) + ((internal::mask8(*it) << 6) & 0xfff); - ++it; - cp += (*it) & 0x3f; - break; - case 4: - ++it; - cp = ((cp << 18) & 0x1fffff) + ((internal::mask8(*it) << 12) & 0x3ffff); - ++it; - cp += (internal::mask8(*it) << 6) & 0xfff; - ++it; - cp += (*it) & 0x3f; - break; - } - ++it; - return cp; - } - - template - uint32_t peek_next(octet_iterator it) - { - return next(it); - } - - template - uint32_t prior(octet_iterator& it) - { - while (internal::is_trail(*(--it))) ; - octet_iterator temp = it; - return next(temp); - } - - // Deprecated in versions that include prior, but only for the sake of consistency (see utf8::previous) - template - inline uint32_t previous(octet_iterator& it) - { - return prior(it); - } - - template - void advance (octet_iterator& it, distance_type n) - { - for (distance_type i = 0; i < n; ++i) - next(it); - } - - template - typename std::iterator_traits::difference_type - distance (octet_iterator first, octet_iterator last) - { - typename std::iterator_traits::difference_type dist; - for (dist = 0; first < last; ++dist) - next(first); - return dist; - } - - template - octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result) - { - while (start != end) { - uint32_t cp = internal::mask16(*start++); - // Take care of surrogate pairs first - if (internal::is_lead_surrogate(cp)) { - uint32_t trail_surrogate = internal::mask16(*start++); - cp = (cp << 10) + trail_surrogate + internal::SURROGATE_OFFSET; - } - result = append(cp, result); - } - return result; - } - - template - u16bit_iterator utf8to16 (octet_iterator start, octet_iterator end, u16bit_iterator result) - { - while (start < end) { - uint32_t cp = next(start); - if (cp > 0xffff) { //make a surrogate pair - *result++ = static_cast((cp >> 10) + internal::LEAD_OFFSET); - *result++ = static_cast((cp & 0x3ff) + internal::TRAIL_SURROGATE_MIN); - } - else - *result++ = static_cast(cp); - } - return result; - } - - template - octet_iterator utf32to8 (u32bit_iterator start, u32bit_iterator end, octet_iterator result) - { - while (start != end) - result = append(*(start++), result); - - return result; - } - - template - u32bit_iterator utf8to32 (octet_iterator start, octet_iterator end, u32bit_iterator result) - { - while (start < end) - (*result++) = next(start); - - return result; - } - - // The iterator class - template - class iterator : public std::iterator { - octet_iterator it; - public: - iterator () {}; - explicit iterator (const octet_iterator& octet_it): it(octet_it) {} - // the default "big three" are OK - octet_iterator base () const { return it; } - uint32_t operator * () const - { - octet_iterator temp = it; - return next(temp); - } - bool operator == (const iterator& rhs) const - { - return (it == rhs.it); - } - bool operator != (const iterator& rhs) const - { - return !(operator == (rhs)); - } - iterator& operator ++ () - { - std::advance(it, internal::sequence_length(it)); - return *this; - } - iterator operator ++ (int) - { - iterator temp = *this; - std::advance(it, internal::sequence_length(it)); - return temp; - } - iterator& operator -- () - { - prior(it); - return *this; - } - iterator operator -- (int) - { - iterator temp = *this; - prior(it); - return temp; - } - }; // class iterator - - } // namespace utf8::unchecked -} // namespace utf8 - - -#endif // header guard - diff --git a/externals/zlib/CMakeLists.txt b/externals/zlib/CMakeLists.txt deleted file mode 100644 index 98be26ae497..00000000000 --- a/externals/zlib/CMakeLists.txt +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright (C) 2008-2010 Trinity -# -# This file is free software; as a special exception the author gives -# unlimited permission to copy and/or distribute it, with or without -# modifications, as long as this notice is preserved. -# -# This program is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the -# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -SET(zlib_STAT_SRCS - adler32.c - compress.c - crc32.c - deflate.c - example.c - infback.c - inffast.c - inflate.c - inftrees.c - trees.c - uncompr.c - zutil.c -) - -include_directories( - ${CMAKE_CURRENT_SOURCE_DIR} -) - -add_library(zlib STATIC ${zlib_STAT_SRCS}) diff --git a/externals/zlib/adler32.c b/externals/zlib/adler32.c deleted file mode 100644 index 65ad6a5adc4..00000000000 --- a/externals/zlib/adler32.c +++ /dev/null @@ -1,169 +0,0 @@ -/* adler32.c -- compute the Adler-32 checksum of a data stream - * Copyright (C) 1995-2007 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#include "zutil.h" - -#define local static - -local uLong adler32_combine_(uLong adler1, uLong adler2, z_off64_t len2); - -#define BASE 65521UL /* largest prime smaller than 65536 */ -#define NMAX 5552 -/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ - -#define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;} -#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); -#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); -#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); -#define DO16(buf) DO8(buf,0); DO8(buf,8); - -/* use NO_DIVIDE if your processor does not do division in hardware */ -#ifdef NO_DIVIDE -# define MOD(a) \ - do { \ - if (a >= (BASE << 16)) a -= (BASE << 16); \ - if (a >= (BASE << 15)) a -= (BASE << 15); \ - if (a >= (BASE << 14)) a -= (BASE << 14); \ - if (a >= (BASE << 13)) a -= (BASE << 13); \ - if (a >= (BASE << 12)) a -= (BASE << 12); \ - if (a >= (BASE << 11)) a -= (BASE << 11); \ - if (a >= (BASE << 10)) a -= (BASE << 10); \ - if (a >= (BASE << 9)) a -= (BASE << 9); \ - if (a >= (BASE << 8)) a -= (BASE << 8); \ - if (a >= (BASE << 7)) a -= (BASE << 7); \ - if (a >= (BASE << 6)) a -= (BASE << 6); \ - if (a >= (BASE << 5)) a -= (BASE << 5); \ - if (a >= (BASE << 4)) a -= (BASE << 4); \ - if (a >= (BASE << 3)) a -= (BASE << 3); \ - if (a >= (BASE << 2)) a -= (BASE << 2); \ - if (a >= (BASE << 1)) a -= (BASE << 1); \ - if (a >= BASE) a -= BASE; \ - } while (0) -# define MOD4(a) \ - do { \ - if (a >= (BASE << 4)) a -= (BASE << 4); \ - if (a >= (BASE << 3)) a -= (BASE << 3); \ - if (a >= (BASE << 2)) a -= (BASE << 2); \ - if (a >= (BASE << 1)) a -= (BASE << 1); \ - if (a >= BASE) a -= BASE; \ - } while (0) -#else -# define MOD(a) a %= BASE -# define MOD4(a) a %= BASE -#endif - -/* ========================================================================= */ -uLong ZEXPORT adler32(adler, buf, len) - uLong adler; - const Bytef *buf; - uInt len; -{ - unsigned long sum2; - unsigned n; - - /* split Adler-32 into component sums */ - sum2 = (adler >> 16) & 0xffff; - adler &= 0xffff; - - /* in case user likes doing a byte at a time, keep it fast */ - if (len == 1) { - adler += buf[0]; - if (adler >= BASE) - adler -= BASE; - sum2 += adler; - if (sum2 >= BASE) - sum2 -= BASE; - return adler | (sum2 << 16); - } - - /* initial Adler-32 value (deferred check for len == 1 speed) */ - if (buf == Z_NULL) - return 1L; - - /* in case short lengths are provided, keep it somewhat fast */ - if (len < 16) { - while (len--) { - adler += *buf++; - sum2 += adler; - } - if (adler >= BASE) - adler -= BASE; - MOD4(sum2); /* only added so many BASE's */ - return adler | (sum2 << 16); - } - - /* do length NMAX blocks -- requires just one modulo operation */ - while (len >= NMAX) { - len -= NMAX; - n = NMAX / 16; /* NMAX is divisible by 16 */ - do { - DO16(buf); /* 16 sums unrolled */ - buf += 16; - } while (--n); - MOD(adler); - MOD(sum2); - } - - /* do remaining bytes (less than NMAX, still just one modulo) */ - if (len) { /* avoid modulos if none remaining */ - while (len >= 16) { - len -= 16; - DO16(buf); - buf += 16; - } - while (len--) { - adler += *buf++; - sum2 += adler; - } - MOD(adler); - MOD(sum2); - } - - /* return recombined sums */ - return adler | (sum2 << 16); -} - -/* ========================================================================= */ -local uLong adler32_combine_(adler1, adler2, len2) - uLong adler1; - uLong adler2; - z_off64_t len2; -{ - unsigned long sum1; - unsigned long sum2; - unsigned rem; - - /* the derivation of this formula is left as an exercise for the reader */ - rem = (unsigned)(len2 % BASE); - sum1 = adler1 & 0xffff; - sum2 = rem * sum1; - MOD(sum2); - sum1 += (adler2 & 0xffff) + BASE - 1; - sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem; - if (sum1 >= BASE) sum1 -= BASE; - if (sum1 >= BASE) sum1 -= BASE; - if (sum2 >= (BASE << 1)) sum2 -= (BASE << 1); - if (sum2 >= BASE) sum2 -= BASE; - return sum1 | (sum2 << 16); -} - -/* ========================================================================= */ -uLong ZEXPORT adler32_combine(adler1, adler2, len2) - uLong adler1; - uLong adler2; - z_off_t len2; -{ - return adler32_combine_(adler1, adler2, len2); -} - -uLong ZEXPORT adler32_combine64(adler1, adler2, len2) - uLong adler1; - uLong adler2; - z_off64_t len2; -{ - return adler32_combine_(adler1, adler2, len2); -} diff --git a/externals/zlib/compress.c b/externals/zlib/compress.c deleted file mode 100644 index ea4dfbe9d7b..00000000000 --- a/externals/zlib/compress.c +++ /dev/null @@ -1,80 +0,0 @@ -/* compress.c -- compress a memory buffer - * Copyright (C) 1995-2005 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#define ZLIB_INTERNAL -#include "zlib.h" - -/* =========================================================================== - Compresses the source buffer into the destination buffer. The level - parameter has the same meaning as in deflateInit. sourceLen is the byte - length of the source buffer. Upon entry, destLen is the total size of the - destination buffer, which must be at least 0.1% larger than sourceLen plus - 12 bytes. Upon exit, destLen is the actual size of the compressed buffer. - - compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_BUF_ERROR if there was not enough room in the output buffer, - Z_STREAM_ERROR if the level parameter is invalid. -*/ -int ZEXPORT compress2 (dest, destLen, source, sourceLen, level) - Bytef *dest; - uLongf *destLen; - const Bytef *source; - uLong sourceLen; - int level; -{ - z_stream stream; - int err; - - stream.next_in = (Bytef*)source; - stream.avail_in = (uInt)sourceLen; -#ifdef MAXSEG_64K - /* Check for source > 64K on 16-bit machine: */ - if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; -#endif - stream.next_out = dest; - stream.avail_out = (uInt)*destLen; - if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; - - stream.zalloc = (alloc_func)0; - stream.zfree = (free_func)0; - stream.opaque = (voidpf)0; - - err = deflateInit(&stream, level); - if (err != Z_OK) return err; - - err = deflate(&stream, Z_FINISH); - if (err != Z_STREAM_END) { - deflateEnd(&stream); - return err == Z_OK ? Z_BUF_ERROR : err; - } - *destLen = stream.total_out; - - err = deflateEnd(&stream); - return err; -} - -/* =========================================================================== - */ -int ZEXPORT compress (dest, destLen, source, sourceLen) - Bytef *dest; - uLongf *destLen; - const Bytef *source; - uLong sourceLen; -{ - return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION); -} - -/* =========================================================================== - If the default memLevel or windowBits for deflateInit() is changed, then - this function needs to be updated. - */ -uLong ZEXPORT compressBound (sourceLen) - uLong sourceLen; -{ - return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + - (sourceLen >> 25) + 13; -} diff --git a/externals/zlib/crc32.c b/externals/zlib/crc32.c deleted file mode 100644 index 91be372d224..00000000000 --- a/externals/zlib/crc32.c +++ /dev/null @@ -1,442 +0,0 @@ -/* crc32.c -- compute the CRC-32 of a data stream - * Copyright (C) 1995-2006, 2010 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - * - * Thanks to Rodney Brown for his contribution of faster - * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing - * tables for updating the shift register in one step with three exclusive-ors - * instead of four steps with four exclusive-ors. This results in about a - * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3. - */ - -/* @(#) $Id$ */ - -/* - Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore - protection on the static variables used to control the first-use generation - of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should - first call get_crc_table() to initialize the tables before allowing more than - one thread to use crc32(). - */ - -#ifdef MAKECRCH -# include -# ifndef DYNAMIC_CRC_TABLE -# define DYNAMIC_CRC_TABLE -# endif /* !DYNAMIC_CRC_TABLE */ -#endif /* MAKECRCH */ - -#include "zutil.h" /* for STDC and FAR definitions */ - -#define local static - -/* Find a four-byte integer type for crc32_little() and crc32_big(). */ -#ifndef NOBYFOUR -# ifdef STDC /* need ANSI C limits.h to determine sizes */ -# include -# define BYFOUR -# if (UINT_MAX == 0xffffffffUL) - typedef unsigned int u4; -# else -# if (ULONG_MAX == 0xffffffffUL) - typedef unsigned long u4; -# else -# if (USHRT_MAX == 0xffffffffUL) - typedef unsigned short u4; -# else -# undef BYFOUR /* can't find a four-byte integer type! */ -# endif -# endif -# endif -# endif /* STDC */ -#endif /* !NOBYFOUR */ - -/* Definitions for doing the crc four data bytes at a time. */ -#ifdef BYFOUR -# define REV(w) ((((w)>>24)&0xff)+(((w)>>8)&0xff00)+ \ - (((w)&0xff00)<<8)+(((w)&0xff)<<24)) - local unsigned long crc32_little OF((unsigned long, - const unsigned char FAR *, unsigned)); - local unsigned long crc32_big OF((unsigned long, - const unsigned char FAR *, unsigned)); -# define TBLS 8 -#else -# define TBLS 1 -#endif /* BYFOUR */ - -/* Local functions for crc concatenation */ -local unsigned long gf2_matrix_times OF((unsigned long *mat, - unsigned long vec)); -local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat)); -local uLong crc32_combine_(uLong crc1, uLong crc2, z_off64_t len2); - - -#ifdef DYNAMIC_CRC_TABLE - -local volatile int crc_table_empty = 1; -local unsigned long FAR crc_table[TBLS][256]; -local void make_crc_table OF((void)); -#ifdef MAKECRCH - local void write_table OF((FILE *, const unsigned long FAR *)); -#endif /* MAKECRCH */ -/* - Generate tables for a byte-wise 32-bit CRC calculation on the polynomial: - x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. - - Polynomials over GF(2) are represented in binary, one bit per coefficient, - with the lowest powers in the most significant bit. Then adding polynomials - is just exclusive-or, and multiplying a polynomial by x is a right shift by - one. If we call the above polynomial p, and represent a byte as the - polynomial q, also with the lowest power in the most significant bit (so the - byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, - where a mod b means the remainder after dividing a by b. - - This calculation is done using the shift-register method of multiplying and - taking the remainder. The register is initialized to zero, and for each - incoming bit, x^32 is added mod p to the register if the bit is a one (where - x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by - x (which is shifting right by one and adding x^32 mod p if the bit shifted - out is a one). We start with the highest power (least significant bit) of - q and repeat for all eight bits of q. - - The first table is simply the CRC of all possible eight bit values. This is - all the information needed to generate CRCs on data a byte at a time for all - combinations of CRC register values and incoming bytes. The remaining tables - allow for word-at-a-time CRC calculation for both big-endian and little- - endian machines, where a word is four bytes. -*/ -local void make_crc_table() -{ - unsigned long c; - int n, k; - unsigned long poly; /* polynomial exclusive-or pattern */ - /* terms of polynomial defining this crc (except x^32): */ - static volatile int first = 1; /* flag to limit concurrent making */ - static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; - - /* See if another task is already doing this (not thread-safe, but better - than nothing -- significantly reduces duration of vulnerability in - case the advice about DYNAMIC_CRC_TABLE is ignored) */ - if (first) { - first = 0; - - /* make exclusive-or pattern from polynomial (0xedb88320UL) */ - poly = 0UL; - for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++) - poly |= 1UL << (31 - p[n]); - - /* generate a crc for every 8-bit value */ - for (n = 0; n < 256; n++) { - c = (unsigned long)n; - for (k = 0; k < 8; k++) - c = c & 1 ? poly ^ (c >> 1) : c >> 1; - crc_table[0][n] = c; - } - -#ifdef BYFOUR - /* generate crc for each value followed by one, two, and three zeros, - and then the byte reversal of those as well as the first table */ - for (n = 0; n < 256; n++) { - c = crc_table[0][n]; - crc_table[4][n] = REV(c); - for (k = 1; k < 4; k++) { - c = crc_table[0][c & 0xff] ^ (c >> 8); - crc_table[k][n] = c; - crc_table[k + 4][n] = REV(c); - } - } -#endif /* BYFOUR */ - - crc_table_empty = 0; - } - else { /* not first */ - /* wait for the other guy to finish (not efficient, but rare) */ - while (crc_table_empty) - ; - } - -#ifdef MAKECRCH - /* write out CRC tables to crc32.h */ - { - FILE *out; - - out = fopen("crc32.h", "w"); - if (out == NULL) return; - fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n"); - fprintf(out, " * Generated automatically by crc32.c\n */\n\n"); - fprintf(out, "local const unsigned long FAR "); - fprintf(out, "crc_table[TBLS][256] =\n{\n {\n"); - write_table(out, crc_table[0]); -# ifdef BYFOUR - fprintf(out, "#ifdef BYFOUR\n"); - for (k = 1; k < 8; k++) { - fprintf(out, " },\n {\n"); - write_table(out, crc_table[k]); - } - fprintf(out, "#endif\n"); -# endif /* BYFOUR */ - fprintf(out, " }\n};\n"); - fclose(out); - } -#endif /* MAKECRCH */ -} - -#ifdef MAKECRCH -local void write_table(out, table) - FILE *out; - const unsigned long FAR *table; -{ - int n; - - for (n = 0; n < 256; n++) - fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n], - n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", ")); -} -#endif /* MAKECRCH */ - -#else /* !DYNAMIC_CRC_TABLE */ -/* ======================================================================== - * Tables of CRC-32s of all single-byte values, made by make_crc_table(). - */ -#include "crc32.h" -#endif /* DYNAMIC_CRC_TABLE */ - -/* ========================================================================= - * This function can be used by asm versions of crc32() - */ -const unsigned long FAR * ZEXPORT get_crc_table() -{ -#ifdef DYNAMIC_CRC_TABLE - if (crc_table_empty) - make_crc_table(); -#endif /* DYNAMIC_CRC_TABLE */ - return (const unsigned long FAR *)crc_table; -} - -/* ========================================================================= */ -#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8) -#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1 - -/* ========================================================================= */ -unsigned long ZEXPORT crc32(crc, buf, len) - unsigned long crc; - const unsigned char FAR *buf; - uInt len; -{ - if (buf == Z_NULL) return 0UL; - -#ifdef DYNAMIC_CRC_TABLE - if (crc_table_empty) - make_crc_table(); -#endif /* DYNAMIC_CRC_TABLE */ - -#ifdef BYFOUR - if (sizeof(void *) == sizeof(ptrdiff_t)) { - u4 endian; - - endian = 1; - if (*((unsigned char *)(&endian))) - return crc32_little(crc, buf, len); - else - return crc32_big(crc, buf, len); - } -#endif /* BYFOUR */ - crc = crc ^ 0xffffffffUL; - while (len >= 8) { - DO8; - len -= 8; - } - if (len) do { - DO1; - } while (--len); - return crc ^ 0xffffffffUL; -} - -#ifdef BYFOUR - -/* ========================================================================= */ -#define DOLIT4 c ^= *buf4++; \ - c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \ - crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24] -#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4 - -/* ========================================================================= */ -local unsigned long crc32_little(crc, buf, len) - unsigned long crc; - const unsigned char FAR *buf; - unsigned len; -{ - register u4 c; - register const u4 FAR *buf4; - - c = (u4)crc; - c = ~c; - while (len && ((ptrdiff_t)buf & 3)) { - c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); - len--; - } - - buf4 = (const u4 FAR *)(const void FAR *)buf; - while (len >= 32) { - DOLIT32; - len -= 32; - } - while (len >= 4) { - DOLIT4; - len -= 4; - } - buf = (const unsigned char FAR *)buf4; - - if (len) do { - c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); - } while (--len); - c = ~c; - return (unsigned long)c; -} - -/* ========================================================================= */ -#define DOBIG4 c ^= *++buf4; \ - c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \ - crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24] -#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4 - -/* ========================================================================= */ -local unsigned long crc32_big(crc, buf, len) - unsigned long crc; - const unsigned char FAR *buf; - unsigned len; -{ - register u4 c; - register const u4 FAR *buf4; - - c = REV((u4)crc); - c = ~c; - while (len && ((ptrdiff_t)buf & 3)) { - c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); - len--; - } - - buf4 = (const u4 FAR *)(const void FAR *)buf; - buf4--; - while (len >= 32) { - DOBIG32; - len -= 32; - } - while (len >= 4) { - DOBIG4; - len -= 4; - } - buf4++; - buf = (const unsigned char FAR *)buf4; - - if (len) do { - c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); - } while (--len); - c = ~c; - return (unsigned long)(REV(c)); -} - -#endif /* BYFOUR */ - -#define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */ - -/* ========================================================================= */ -local unsigned long gf2_matrix_times(mat, vec) - unsigned long *mat; - unsigned long vec; -{ - unsigned long sum; - - sum = 0; - while (vec) { - if (vec & 1) - sum ^= *mat; - vec >>= 1; - mat++; - } - return sum; -} - -/* ========================================================================= */ -local void gf2_matrix_square(square, mat) - unsigned long *square; - unsigned long *mat; -{ - int n; - - for (n = 0; n < GF2_DIM; n++) - square[n] = gf2_matrix_times(mat, mat[n]); -} - -/* ========================================================================= */ -local uLong crc32_combine_(crc1, crc2, len2) - uLong crc1; - uLong crc2; - z_off64_t len2; -{ - int n; - unsigned long row; - unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */ - unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */ - - /* degenerate case (also disallow negative lengths) */ - if (len2 <= 0) - return crc1; - - /* put operator for one zero bit in odd */ - odd[0] = 0xedb88320UL; /* CRC-32 polynomial */ - row = 1; - for (n = 1; n < GF2_DIM; n++) { - odd[n] = row; - row <<= 1; - } - - /* put operator for two zero bits in even */ - gf2_matrix_square(even, odd); - - /* put operator for four zero bits in odd */ - gf2_matrix_square(odd, even); - - /* apply len2 zeros to crc1 (first square will put the operator for one - zero byte, eight zero bits, in even) */ - do { - /* apply zeros operator for this bit of len2 */ - gf2_matrix_square(even, odd); - if (len2 & 1) - crc1 = gf2_matrix_times(even, crc1); - len2 >>= 1; - - /* if no more bits set, then done */ - if (len2 == 0) - break; - - /* another iteration of the loop with odd and even swapped */ - gf2_matrix_square(odd, even); - if (len2 & 1) - crc1 = gf2_matrix_times(odd, crc1); - len2 >>= 1; - - /* if no more bits set, then done */ - } while (len2 != 0); - - /* return combined crc */ - crc1 ^= crc2; - return crc1; -} - -/* ========================================================================= */ -uLong ZEXPORT crc32_combine(crc1, crc2, len2) - uLong crc1; - uLong crc2; - z_off_t len2; -{ - return crc32_combine_(crc1, crc2, len2); -} - -uLong ZEXPORT crc32_combine64(crc1, crc2, len2) - uLong crc1; - uLong crc2; - z_off64_t len2; -{ - return crc32_combine_(crc1, crc2, len2); -} diff --git a/externals/zlib/crc32.h b/externals/zlib/crc32.h deleted file mode 100644 index 8053b6117c0..00000000000 --- a/externals/zlib/crc32.h +++ /dev/null @@ -1,441 +0,0 @@ -/* crc32.h -- tables for rapid CRC calculation - * Generated automatically by crc32.c - */ - -local const unsigned long FAR crc_table[TBLS][256] = -{ - { - 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL, - 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL, - 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL, - 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL, - 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL, - 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL, - 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL, - 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL, - 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL, - 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL, - 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL, - 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL, - 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL, - 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL, - 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL, - 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL, - 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL, - 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL, - 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL, - 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL, - 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL, - 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL, - 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL, - 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL, - 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL, - 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL, - 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL, - 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL, - 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL, - 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL, - 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL, - 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL, - 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL, - 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL, - 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL, - 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL, - 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL, - 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL, - 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL, - 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL, - 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL, - 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL, - 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL, - 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL, - 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL, - 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL, - 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL, - 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL, - 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL, - 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL, - 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL, - 0x2d02ef8dUL -#ifdef BYFOUR - }, - { - 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL, - 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL, - 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL, - 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL, - 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL, - 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL, - 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL, - 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL, - 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL, - 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL, - 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL, - 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL, - 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL, - 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL, - 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL, - 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL, - 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL, - 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL, - 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL, - 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL, - 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL, - 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL, - 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL, - 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL, - 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL, - 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL, - 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL, - 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL, - 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL, - 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL, - 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL, - 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL, - 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL, - 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL, - 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL, - 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL, - 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL, - 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL, - 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL, - 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL, - 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL, - 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL, - 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL, - 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL, - 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL, - 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL, - 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL, - 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL, - 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL, - 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL, - 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL, - 0x9324fd72UL - }, - { - 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL, - 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL, - 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL, - 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL, - 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL, - 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL, - 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL, - 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL, - 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL, - 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL, - 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL, - 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL, - 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL, - 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL, - 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL, - 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL, - 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL, - 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL, - 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL, - 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL, - 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL, - 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL, - 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL, - 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL, - 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL, - 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL, - 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL, - 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL, - 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL, - 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL, - 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL, - 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL, - 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL, - 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL, - 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL, - 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL, - 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL, - 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL, - 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL, - 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL, - 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL, - 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL, - 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL, - 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL, - 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL, - 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL, - 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL, - 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL, - 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL, - 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL, - 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL, - 0xbe9834edUL - }, - { - 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL, - 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL, - 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL, - 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL, - 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL, - 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL, - 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL, - 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL, - 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL, - 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL, - 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL, - 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL, - 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL, - 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL, - 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL, - 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL, - 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL, - 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL, - 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL, - 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL, - 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL, - 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL, - 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL, - 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL, - 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL, - 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL, - 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL, - 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL, - 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL, - 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL, - 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL, - 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL, - 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL, - 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL, - 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL, - 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL, - 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL, - 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL, - 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL, - 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL, - 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL, - 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL, - 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL, - 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL, - 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL, - 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL, - 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL, - 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL, - 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL, - 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL, - 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL, - 0xde0506f1UL - }, - { - 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL, - 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL, - 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL, - 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL, - 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL, - 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL, - 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL, - 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL, - 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL, - 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL, - 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL, - 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL, - 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL, - 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL, - 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL, - 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL, - 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL, - 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL, - 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL, - 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL, - 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL, - 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL, - 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL, - 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL, - 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL, - 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL, - 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL, - 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL, - 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL, - 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL, - 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL, - 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL, - 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL, - 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL, - 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL, - 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL, - 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL, - 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL, - 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL, - 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL, - 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL, - 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL, - 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL, - 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL, - 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL, - 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL, - 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL, - 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL, - 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL, - 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL, - 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL, - 0x8def022dUL - }, - { - 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL, - 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL, - 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL, - 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL, - 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL, - 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL, - 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL, - 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL, - 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL, - 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL, - 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL, - 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL, - 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL, - 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL, - 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL, - 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL, - 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL, - 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL, - 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL, - 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL, - 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL, - 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL, - 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL, - 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL, - 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL, - 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL, - 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL, - 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL, - 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL, - 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL, - 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL, - 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL, - 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL, - 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL, - 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL, - 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL, - 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL, - 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL, - 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL, - 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL, - 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL, - 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL, - 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL, - 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL, - 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL, - 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL, - 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL, - 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL, - 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL, - 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL, - 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL, - 0x72fd2493UL - }, - { - 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL, - 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL, - 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL, - 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL, - 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL, - 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL, - 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL, - 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL, - 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL, - 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL, - 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL, - 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL, - 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL, - 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL, - 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL, - 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL, - 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL, - 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL, - 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL, - 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL, - 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL, - 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL, - 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL, - 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL, - 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL, - 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL, - 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL, - 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL, - 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL, - 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL, - 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL, - 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL, - 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL, - 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL, - 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL, - 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL, - 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL, - 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL, - 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL, - 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL, - 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL, - 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL, - 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL, - 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL, - 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL, - 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL, - 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL, - 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL, - 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL, - 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL, - 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL, - 0xed3498beUL - }, - { - 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL, - 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL, - 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL, - 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL, - 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL, - 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL, - 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL, - 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL, - 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL, - 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL, - 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL, - 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL, - 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL, - 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL, - 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL, - 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL, - 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL, - 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL, - 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL, - 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL, - 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL, - 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL, - 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL, - 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL, - 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL, - 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL, - 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL, - 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL, - 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL, - 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL, - 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL, - 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL, - 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL, - 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL, - 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL, - 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL, - 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL, - 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL, - 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL, - 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL, - 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL, - 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL, - 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL, - 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL, - 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL, - 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL, - 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL, - 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL, - 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL, - 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL, - 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL, - 0xf10605deUL -#endif - } -}; diff --git a/externals/zlib/deflate.c b/externals/zlib/deflate.c deleted file mode 100644 index 5c4022f3d47..00000000000 --- a/externals/zlib/deflate.c +++ /dev/null @@ -1,1834 +0,0 @@ -/* deflate.c -- compress data using the deflation algorithm - * Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* - * ALGORITHM - * - * The "deflation" process depends on being able to identify portions - * of the input text which are identical to earlier input (within a - * sliding window trailing behind the input currently being processed). - * - * The most straightforward technique turns out to be the fastest for - * most input files: try all possible matches and select the longest. - * The key feature of this algorithm is that insertions into the string - * dictionary are very simple and thus fast, and deletions are avoided - * completely. Insertions are performed at each input character, whereas - * string matches are performed only when the previous match ends. So it - * is preferable to spend more time in matches to allow very fast string - * insertions and avoid deletions. The matching algorithm for small - * strings is inspired from that of Rabin & Karp. A brute force approach - * is used to find longer strings when a small match has been found. - * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze - * (by Leonid Broukhis). - * A previous version of this file used a more sophisticated algorithm - * (by Fiala and Greene) which is guaranteed to run in linear amortized - * time, but has a larger average cost, uses more memory and is patented. - * However the F&G algorithm may be faster for some highly redundant - * files if the parameter max_chain_length (described below) is too large. - * - * ACKNOWLEDGEMENTS - * - * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and - * I found it in 'freeze' written by Leonid Broukhis. - * Thanks to many people for bug reports and testing. - * - * REFERENCES - * - * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification". - * Available in http://www.ietf.org/rfc/rfc1951.txt - * - * A description of the Rabin and Karp algorithm is given in the book - * "Algorithms" by R. Sedgewick, Addison-Wesley, p252. - * - * Fiala,E.R., and Greene,D.H. - * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595 - * - */ - -/* @(#) $Id$ */ - -#include "deflate.h" - -const char deflate_copyright[] = - " deflate 1.2.5 Copyright 1995-2010 Jean-loup Gailly and Mark Adler "; -/* - If you use the zlib library in a product, an acknowledgment is welcome - in the documentation of your product. If for some reason you cannot - include such an acknowledgment, I would appreciate that you keep this - copyright string in the executable of your product. - */ - -/* =========================================================================== - * Function prototypes. - */ -typedef enum { - need_more, /* block not completed, need more input or more output */ - block_done, /* block flush performed */ - finish_started, /* finish started, need only more output at next deflate */ - finish_done /* finish done, accept no more input or output */ -} block_state; - -typedef block_state (*compress_func) OF((deflate_state *s, int flush)); -/* Compression function. Returns the block state after the call. */ - -local void fill_window OF((deflate_state *s)); -local block_state deflate_stored OF((deflate_state *s, int flush)); -local block_state deflate_fast OF((deflate_state *s, int flush)); -#ifndef FASTEST -local block_state deflate_slow OF((deflate_state *s, int flush)); -#endif -local block_state deflate_rle OF((deflate_state *s, int flush)); -local block_state deflate_huff OF((deflate_state *s, int flush)); -local void lm_init OF((deflate_state *s)); -local void putShortMSB OF((deflate_state *s, uInt b)); -local void flush_pending OF((z_streamp strm)); -local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); -#ifdef ASMV - void match_init OF((void)); /* asm code initialization */ - uInt longest_match OF((deflate_state *s, IPos cur_match)); -#else -local uInt longest_match OF((deflate_state *s, IPos cur_match)); -#endif - -#ifdef DEBUG -local void check_match OF((deflate_state *s, IPos start, IPos match, - int length)); -#endif - -/* =========================================================================== - * Local data - */ - -#define NIL 0 -/* Tail of hash chains */ - -#ifndef TOO_FAR -# define TOO_FAR 4096 -#endif -/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */ - -/* Values for max_lazy_match, good_match and max_chain_length, depending on - * the desired pack level (0..9). The values given below have been tuned to - * exclude worst case performance for pathological files. Better values may be - * found for specific files. - */ -typedef struct config_s { - ush good_length; /* reduce lazy search above this match length */ - ush max_lazy; /* do not perform lazy search above this match length */ - ush nice_length; /* quit search above this match length */ - ush max_chain; - compress_func func; -} config; - -#ifdef FASTEST -local const config configuration_table[2] = { -/* good lazy nice chain */ -/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ -/* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */ -#else -local const config configuration_table[10] = { -/* good lazy nice chain */ -/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ -/* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */ -/* 2 */ {4, 5, 16, 8, deflate_fast}, -/* 3 */ {4, 6, 32, 32, deflate_fast}, - -/* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */ -/* 5 */ {8, 16, 32, 32, deflate_slow}, -/* 6 */ {8, 16, 128, 128, deflate_slow}, -/* 7 */ {8, 32, 128, 256, deflate_slow}, -/* 8 */ {32, 128, 258, 1024, deflate_slow}, -/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */ -#endif - -/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 - * For deflate_fast() (levels <= 3) good is ignored and lazy has a different - * meaning. - */ - -#define EQUAL 0 -/* result of memcmp for equal strings */ - -#ifndef NO_DUMMY_DECL -struct static_tree_desc_s {int dummy;}; /* for buggy compilers */ -#endif - -/* =========================================================================== - * Update a hash value with the given input byte - * IN assertion: all calls to to UPDATE_HASH are made with consecutive - * input characters, so that a running hash key can be computed from the - * previous key instead of complete recalculation each time. - */ -#define UPDATE_HASH(s,h,c) (h = (((h)<hash_shift) ^ (c)) & s->hash_mask) - - -/* =========================================================================== - * Insert string str in the dictionary and set match_head to the previous head - * of the hash chain (the most recent string with same hash key). Return - * the previous length of the hash chain. - * If this file is compiled with -DFASTEST, the compression level is forced - * to 1, and no hash chains are maintained. - * IN assertion: all calls to to INSERT_STRING are made with consecutive - * input characters and the first MIN_MATCH bytes of str are valid - * (except for the last MIN_MATCH-1 bytes of the input file). - */ -#ifdef FASTEST -#define INSERT_STRING(s, str, match_head) \ - (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ - match_head = s->head[s->ins_h], \ - s->head[s->ins_h] = (Pos)(str)) -#else -#define INSERT_STRING(s, str, match_head) \ - (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ - match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \ - s->head[s->ins_h] = (Pos)(str)) -#endif - -/* =========================================================================== - * Initialize the hash table (avoiding 64K overflow for 16 bit systems). - * prev[] will be initialized on the fly. - */ -#define CLEAR_HASH(s) \ - s->head[s->hash_size-1] = NIL; \ - zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head)); - -/* ========================================================================= */ -int ZEXPORT deflateInit_(strm, level, version, stream_size) - z_streamp strm; - int level; - const char *version; - int stream_size; -{ - return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, - Z_DEFAULT_STRATEGY, version, stream_size); - /* To do: ignore strm->next_in if we use it as window */ -} - -/* ========================================================================= */ -int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, - version, stream_size) - z_streamp strm; - int level; - int method; - int windowBits; - int memLevel; - int strategy; - const char *version; - int stream_size; -{ - deflate_state *s; - int wrap = 1; - static const char my_version[] = ZLIB_VERSION; - - ushf *overlay; - /* We overlay pending_buf and d_buf+l_buf. This works since the average - * output size for (length,distance) codes is <= 24 bits. - */ - - if (version == Z_NULL || version[0] != my_version[0] || - stream_size != sizeof(z_stream)) { - return Z_VERSION_ERROR; - } - if (strm == Z_NULL) return Z_STREAM_ERROR; - - strm->msg = Z_NULL; - if (strm->zalloc == (alloc_func)0) { - strm->zalloc = zcalloc; - strm->opaque = (voidpf)0; - } - if (strm->zfree == (free_func)0) strm->zfree = zcfree; - -#ifdef FASTEST - if (level != 0) level = 1; -#else - if (level == Z_DEFAULT_COMPRESSION) level = 6; -#endif - - if (windowBits < 0) { /* suppress zlib wrapper */ - wrap = 0; - windowBits = -windowBits; - } -#ifdef GZIP - else if (windowBits > 15) { - wrap = 2; /* write gzip wrapper instead */ - windowBits -= 16; - } -#endif - if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || - windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || - strategy < 0 || strategy > Z_FIXED) { - return Z_STREAM_ERROR; - } - if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */ - s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state)); - if (s == Z_NULL) return Z_MEM_ERROR; - strm->state = (struct internal_state FAR *)s; - s->strm = strm; - - s->wrap = wrap; - s->gzhead = Z_NULL; - s->w_bits = windowBits; - s->w_size = 1 << s->w_bits; - s->w_mask = s->w_size - 1; - - s->hash_bits = memLevel + 7; - s->hash_size = 1 << s->hash_bits; - s->hash_mask = s->hash_size - 1; - s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); - - s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); - s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); - s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos)); - - s->high_water = 0; /* nothing written to s->window yet */ - - s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ - - overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); - s->pending_buf = (uchf *) overlay; - s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L); - - if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || - s->pending_buf == Z_NULL) { - s->status = FINISH_STATE; - strm->msg = (char*)ERR_MSG(Z_MEM_ERROR); - deflateEnd (strm); - return Z_MEM_ERROR; - } - s->d_buf = overlay + s->lit_bufsize/sizeof(ush); - s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; - - s->level = level; - s->strategy = strategy; - s->method = (Byte)method; - - return deflateReset(strm); -} - -/* ========================================================================= */ -int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) - z_streamp strm; - const Bytef *dictionary; - uInt dictLength; -{ - deflate_state *s; - uInt length = dictLength; - uInt n; - IPos hash_head = 0; - - if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL || - strm->state->wrap == 2 || - (strm->state->wrap == 1 && strm->state->status != INIT_STATE)) - return Z_STREAM_ERROR; - - s = strm->state; - if (s->wrap) - strm->adler = adler32(strm->adler, dictionary, dictLength); - - if (length < MIN_MATCH) return Z_OK; - if (length > s->w_size) { - length = s->w_size; - dictionary += dictLength - length; /* use the tail of the dictionary */ - } - zmemcpy(s->window, dictionary, length); - s->strstart = length; - s->block_start = (long)length; - - /* Insert all strings in the hash table (except for the last two bytes). - * s->lookahead stays null, so s->ins_h will be recomputed at the next - * call of fill_window. - */ - s->ins_h = s->window[0]; - UPDATE_HASH(s, s->ins_h, s->window[1]); - for (n = 0; n <= length - MIN_MATCH; n++) { - INSERT_STRING(s, n, hash_head); - } - if (hash_head) hash_head = 0; /* to make compiler happy */ - return Z_OK; -} - -/* ========================================================================= */ -int ZEXPORT deflateReset (strm) - z_streamp strm; -{ - deflate_state *s; - - if (strm == Z_NULL || strm->state == Z_NULL || - strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) { - return Z_STREAM_ERROR; - } - - strm->total_in = strm->total_out = 0; - strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */ - strm->data_type = Z_UNKNOWN; - - s = (deflate_state *)strm->state; - s->pending = 0; - s->pending_out = s->pending_buf; - - if (s->wrap < 0) { - s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */ - } - s->status = s->wrap ? INIT_STATE : BUSY_STATE; - strm->adler = -#ifdef GZIP - s->wrap == 2 ? crc32(0L, Z_NULL, 0) : -#endif - adler32(0L, Z_NULL, 0); - s->last_flush = Z_NO_FLUSH; - - _tr_init(s); - lm_init(s); - - return Z_OK; -} - -/* ========================================================================= */ -int ZEXPORT deflateSetHeader (strm, head) - z_streamp strm; - gz_headerp head; -{ - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - if (strm->state->wrap != 2) return Z_STREAM_ERROR; - strm->state->gzhead = head; - return Z_OK; -} - -/* ========================================================================= */ -int ZEXPORT deflatePrime (strm, bits, value) - z_streamp strm; - int bits; - int value; -{ - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - strm->state->bi_valid = bits; - strm->state->bi_buf = (ush)(value & ((1 << bits) - 1)); - return Z_OK; -} - -/* ========================================================================= */ -int ZEXPORT deflateParams(strm, level, strategy) - z_streamp strm; - int level; - int strategy; -{ - deflate_state *s; - compress_func func; - int err = Z_OK; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - s = strm->state; - -#ifdef FASTEST - if (level != 0) level = 1; -#else - if (level == Z_DEFAULT_COMPRESSION) level = 6; -#endif - if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { - return Z_STREAM_ERROR; - } - func = configuration_table[s->level].func; - - if ((strategy != s->strategy || func != configuration_table[level].func) && - strm->total_in != 0) { - /* Flush the last buffer: */ - err = deflate(strm, Z_BLOCK); - } - if (s->level != level) { - s->level = level; - s->max_lazy_match = configuration_table[level].max_lazy; - s->good_match = configuration_table[level].good_length; - s->nice_match = configuration_table[level].nice_length; - s->max_chain_length = configuration_table[level].max_chain; - } - s->strategy = strategy; - return err; -} - -/* ========================================================================= */ -int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain) - z_streamp strm; - int good_length; - int max_lazy; - int nice_length; - int max_chain; -{ - deflate_state *s; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - s = strm->state; - s->good_match = good_length; - s->max_lazy_match = max_lazy; - s->nice_match = nice_length; - s->max_chain_length = max_chain; - return Z_OK; -} - -/* ========================================================================= - * For the default windowBits of 15 and memLevel of 8, this function returns - * a close to exact, as well as small, upper bound on the compressed size. - * They are coded as constants here for a reason--if the #define's are - * changed, then this function needs to be changed as well. The return - * value for 15 and 8 only works for those exact settings. - * - * For any setting other than those defaults for windowBits and memLevel, - * the value returned is a conservative worst case for the maximum expansion - * resulting from using fixed blocks instead of stored blocks, which deflate - * can emit on compressed data for some combinations of the parameters. - * - * This function could be more sophisticated to provide closer upper bounds for - * every combination of windowBits and memLevel. But even the conservative - * upper bound of about 14% expansion does not seem onerous for output buffer - * allocation. - */ -uLong ZEXPORT deflateBound(strm, sourceLen) - z_streamp strm; - uLong sourceLen; -{ - deflate_state *s; - uLong complen, wraplen; - Bytef *str; - - /* conservative upper bound for compressed data */ - complen = sourceLen + - ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5; - - /* if can't get parameters, return conservative bound plus zlib wrapper */ - if (strm == Z_NULL || strm->state == Z_NULL) - return complen + 6; - - /* compute wrapper length */ - s = strm->state; - switch (s->wrap) { - case 0: /* raw deflate */ - wraplen = 0; - break; - case 1: /* zlib wrapper */ - wraplen = 6 + (s->strstart ? 4 : 0); - break; - case 2: /* gzip wrapper */ - wraplen = 18; - if (s->gzhead != Z_NULL) { /* user-supplied gzip header */ - if (s->gzhead->extra != Z_NULL) - wraplen += 2 + s->gzhead->extra_len; - str = s->gzhead->name; - if (str != Z_NULL) - do { - wraplen++; - } while (*str++); - str = s->gzhead->comment; - if (str != Z_NULL) - do { - wraplen++; - } while (*str++); - if (s->gzhead->hcrc) - wraplen += 2; - } - break; - default: /* for compiler happiness */ - wraplen = 6; - } - - /* if not default parameters, return conservative bound */ - if (s->w_bits != 15 || s->hash_bits != 8 + 7) - return complen + wraplen; - - /* default settings: return tight bound for that case */ - return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + - (sourceLen >> 25) + 13 - 6 + wraplen; -} - -/* ========================================================================= - * Put a short in the pending buffer. The 16-bit value is put in MSB order. - * IN assertion: the stream state is correct and there is enough room in - * pending_buf. - */ -local void putShortMSB (s, b) - deflate_state *s; - uInt b; -{ - put_byte(s, (Byte)(b >> 8)); - put_byte(s, (Byte)(b & 0xff)); -} - -/* ========================================================================= - * Flush as much pending output as possible. All deflate() output goes - * through this function so some applications may wish to modify it - * to avoid allocating a large strm->next_out buffer and copying into it. - * (See also read_buf()). - */ -local void flush_pending(strm) - z_streamp strm; -{ - unsigned len = strm->state->pending; - - if (len > strm->avail_out) len = strm->avail_out; - if (len == 0) return; - - zmemcpy(strm->next_out, strm->state->pending_out, len); - strm->next_out += len; - strm->state->pending_out += len; - strm->total_out += len; - strm->avail_out -= len; - strm->state->pending -= len; - if (strm->state->pending == 0) { - strm->state->pending_out = strm->state->pending_buf; - } -} - -/* ========================================================================= */ -int ZEXPORT deflate (strm, flush) - z_streamp strm; - int flush; -{ - int old_flush; /* value of flush param for previous deflate call */ - deflate_state *s; - - if (strm == Z_NULL || strm->state == Z_NULL || - flush > Z_BLOCK || flush < 0) { - return Z_STREAM_ERROR; - } - s = strm->state; - - if (strm->next_out == Z_NULL || - (strm->next_in == Z_NULL && strm->avail_in != 0) || - (s->status == FINISH_STATE && flush != Z_FINISH)) { - ERR_RETURN(strm, Z_STREAM_ERROR); - } - if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR); - - s->strm = strm; /* just in case */ - old_flush = s->last_flush; - s->last_flush = flush; - - /* Write the header */ - if (s->status == INIT_STATE) { -#ifdef GZIP - if (s->wrap == 2) { - strm->adler = crc32(0L, Z_NULL, 0); - put_byte(s, 31); - put_byte(s, 139); - put_byte(s, 8); - if (s->gzhead == Z_NULL) { - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, s->level == 9 ? 2 : - (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? - 4 : 0)); - put_byte(s, OS_CODE); - s->status = BUSY_STATE; - } - else { - put_byte(s, (s->gzhead->text ? 1 : 0) + - (s->gzhead->hcrc ? 2 : 0) + - (s->gzhead->extra == Z_NULL ? 0 : 4) + - (s->gzhead->name == Z_NULL ? 0 : 8) + - (s->gzhead->comment == Z_NULL ? 0 : 16) - ); - put_byte(s, (Byte)(s->gzhead->time & 0xff)); - put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff)); - put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff)); - put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff)); - put_byte(s, s->level == 9 ? 2 : - (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? - 4 : 0)); - put_byte(s, s->gzhead->os & 0xff); - if (s->gzhead->extra != Z_NULL) { - put_byte(s, s->gzhead->extra_len & 0xff); - put_byte(s, (s->gzhead->extra_len >> 8) & 0xff); - } - if (s->gzhead->hcrc) - strm->adler = crc32(strm->adler, s->pending_buf, - s->pending); - s->gzindex = 0; - s->status = EXTRA_STATE; - } - } - else -#endif - { - uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; - uInt level_flags; - - if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2) - level_flags = 0; - else if (s->level < 6) - level_flags = 1; - else if (s->level == 6) - level_flags = 2; - else - level_flags = 3; - header |= (level_flags << 6); - if (s->strstart != 0) header |= PRESET_DICT; - header += 31 - (header % 31); - - s->status = BUSY_STATE; - putShortMSB(s, header); - - /* Save the adler32 of the preset dictionary: */ - if (s->strstart != 0) { - putShortMSB(s, (uInt)(strm->adler >> 16)); - putShortMSB(s, (uInt)(strm->adler & 0xffff)); - } - strm->adler = adler32(0L, Z_NULL, 0); - } - } -#ifdef GZIP - if (s->status == EXTRA_STATE) { - if (s->gzhead->extra != Z_NULL) { - uInt beg = s->pending; /* start of bytes to update crc */ - - while (s->gzindex < (s->gzhead->extra_len & 0xffff)) { - if (s->pending == s->pending_buf_size) { - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - flush_pending(strm); - beg = s->pending; - if (s->pending == s->pending_buf_size) - break; - } - put_byte(s, s->gzhead->extra[s->gzindex]); - s->gzindex++; - } - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - if (s->gzindex == s->gzhead->extra_len) { - s->gzindex = 0; - s->status = NAME_STATE; - } - } - else - s->status = NAME_STATE; - } - if (s->status == NAME_STATE) { - if (s->gzhead->name != Z_NULL) { - uInt beg = s->pending; /* start of bytes to update crc */ - int val; - - do { - if (s->pending == s->pending_buf_size) { - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - flush_pending(strm); - beg = s->pending; - if (s->pending == s->pending_buf_size) { - val = 1; - break; - } - } - val = s->gzhead->name[s->gzindex++]; - put_byte(s, val); - } while (val != 0); - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - if (val == 0) { - s->gzindex = 0; - s->status = COMMENT_STATE; - } - } - else - s->status = COMMENT_STATE; - } - if (s->status == COMMENT_STATE) { - if (s->gzhead->comment != Z_NULL) { - uInt beg = s->pending; /* start of bytes to update crc */ - int val; - - do { - if (s->pending == s->pending_buf_size) { - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - flush_pending(strm); - beg = s->pending; - if (s->pending == s->pending_buf_size) { - val = 1; - break; - } - } - val = s->gzhead->comment[s->gzindex++]; - put_byte(s, val); - } while (val != 0); - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - if (val == 0) - s->status = HCRC_STATE; - } - else - s->status = HCRC_STATE; - } - if (s->status == HCRC_STATE) { - if (s->gzhead->hcrc) { - if (s->pending + 2 > s->pending_buf_size) - flush_pending(strm); - if (s->pending + 2 <= s->pending_buf_size) { - put_byte(s, (Byte)(strm->adler & 0xff)); - put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); - strm->adler = crc32(0L, Z_NULL, 0); - s->status = BUSY_STATE; - } - } - else - s->status = BUSY_STATE; - } -#endif - - /* Flush as much pending output as possible */ - if (s->pending != 0) { - flush_pending(strm); - if (strm->avail_out == 0) { - /* Since avail_out is 0, deflate will be called again with - * more output space, but possibly with both pending and - * avail_in equal to zero. There won't be anything to do, - * but this is not an error situation so make sure we - * return OK instead of BUF_ERROR at next call of deflate: - */ - s->last_flush = -1; - return Z_OK; - } - - /* Make sure there is something to do and avoid duplicate consecutive - * flushes. For repeated and useless calls with Z_FINISH, we keep - * returning Z_STREAM_END instead of Z_BUF_ERROR. - */ - } else if (strm->avail_in == 0 && flush <= old_flush && - flush != Z_FINISH) { - ERR_RETURN(strm, Z_BUF_ERROR); - } - - /* User must not provide more input after the first FINISH: */ - if (s->status == FINISH_STATE && strm->avail_in != 0) { - ERR_RETURN(strm, Z_BUF_ERROR); - } - - /* Start a new block or continue the current one. - */ - if (strm->avail_in != 0 || s->lookahead != 0 || - (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { - block_state bstate; - - bstate = s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) : - (s->strategy == Z_RLE ? deflate_rle(s, flush) : - (*(configuration_table[s->level].func))(s, flush)); - - if (bstate == finish_started || bstate == finish_done) { - s->status = FINISH_STATE; - } - if (bstate == need_more || bstate == finish_started) { - if (strm->avail_out == 0) { - s->last_flush = -1; /* avoid BUF_ERROR next call, see above */ - } - return Z_OK; - /* If flush != Z_NO_FLUSH && avail_out == 0, the next call - * of deflate should use the same flush parameter to make sure - * that the flush is complete. So we don't have to output an - * empty block here, this will be done at next call. This also - * ensures that for a very small output buffer, we emit at most - * one empty block. - */ - } - if (bstate == block_done) { - if (flush == Z_PARTIAL_FLUSH) { - _tr_align(s); - } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ - _tr_stored_block(s, (char*)0, 0L, 0); - /* For a full flush, this empty block will be recognized - * as a special marker by inflate_sync(). - */ - if (flush == Z_FULL_FLUSH) { - CLEAR_HASH(s); /* forget history */ - if (s->lookahead == 0) { - s->strstart = 0; - s->block_start = 0L; - } - } - } - flush_pending(strm); - if (strm->avail_out == 0) { - s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */ - return Z_OK; - } - } - } - Assert(strm->avail_out > 0, "bug2"); - - if (flush != Z_FINISH) return Z_OK; - if (s->wrap <= 0) return Z_STREAM_END; - - /* Write the trailer */ -#ifdef GZIP - if (s->wrap == 2) { - put_byte(s, (Byte)(strm->adler & 0xff)); - put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); - put_byte(s, (Byte)((strm->adler >> 16) & 0xff)); - put_byte(s, (Byte)((strm->adler >> 24) & 0xff)); - put_byte(s, (Byte)(strm->total_in & 0xff)); - put_byte(s, (Byte)((strm->total_in >> 8) & 0xff)); - put_byte(s, (Byte)((strm->total_in >> 16) & 0xff)); - put_byte(s, (Byte)((strm->total_in >> 24) & 0xff)); - } - else -#endif - { - putShortMSB(s, (uInt)(strm->adler >> 16)); - putShortMSB(s, (uInt)(strm->adler & 0xffff)); - } - flush_pending(strm); - /* If avail_out is zero, the application will call deflate again - * to flush the rest. - */ - if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */ - return s->pending != 0 ? Z_OK : Z_STREAM_END; -} - -/* ========================================================================= */ -int ZEXPORT deflateEnd (strm) - z_streamp strm; -{ - int status; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - - status = strm->state->status; - if (status != INIT_STATE && - status != EXTRA_STATE && - status != NAME_STATE && - status != COMMENT_STATE && - status != HCRC_STATE && - status != BUSY_STATE && - status != FINISH_STATE) { - return Z_STREAM_ERROR; - } - - /* Deallocate in reverse order of allocations: */ - TRY_FREE(strm, strm->state->pending_buf); - TRY_FREE(strm, strm->state->head); - TRY_FREE(strm, strm->state->prev); - TRY_FREE(strm, strm->state->window); - - ZFREE(strm, strm->state); - strm->state = Z_NULL; - - return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK; -} - -/* ========================================================================= - * Copy the source state to the destination state. - * To simplify the source, this is not supported for 16-bit MSDOS (which - * doesn't have enough memory anyway to duplicate compression states). - */ -int ZEXPORT deflateCopy (dest, source) - z_streamp dest; - z_streamp source; -{ -#ifdef MAXSEG_64K - return Z_STREAM_ERROR; -#else - deflate_state *ds; - deflate_state *ss; - ushf *overlay; - - - if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) { - return Z_STREAM_ERROR; - } - - ss = source->state; - - zmemcpy(dest, source, sizeof(z_stream)); - - ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state)); - if (ds == Z_NULL) return Z_MEM_ERROR; - dest->state = (struct internal_state FAR *) ds; - zmemcpy(ds, ss, sizeof(deflate_state)); - ds->strm = dest; - - ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); - ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos)); - ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos)); - overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2); - ds->pending_buf = (uchf *) overlay; - - if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || - ds->pending_buf == Z_NULL) { - deflateEnd (dest); - return Z_MEM_ERROR; - } - /* following zmemcpy do not work for 16-bit MSDOS */ - zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte)); - zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos)); - zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos)); - zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); - - ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); - ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush); - ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize; - - ds->l_desc.dyn_tree = ds->dyn_ltree; - ds->d_desc.dyn_tree = ds->dyn_dtree; - ds->bl_desc.dyn_tree = ds->bl_tree; - - return Z_OK; -#endif /* MAXSEG_64K */ -} - -/* =========================================================================== - * Read a new buffer from the current input stream, update the adler32 - * and total number of bytes read. All deflate() input goes through - * this function so some applications may wish to modify it to avoid - * allocating a large strm->next_in buffer and copying from it. - * (See also flush_pending()). - */ -local int read_buf(strm, buf, size) - z_streamp strm; - Bytef *buf; - unsigned size; -{ - unsigned len = strm->avail_in; - - if (len > size) len = size; - if (len == 0) return 0; - - strm->avail_in -= len; - - if (strm->state->wrap == 1) { - strm->adler = adler32(strm->adler, strm->next_in, len); - } -#ifdef GZIP - else if (strm->state->wrap == 2) { - strm->adler = crc32(strm->adler, strm->next_in, len); - } -#endif - zmemcpy(buf, strm->next_in, len); - strm->next_in += len; - strm->total_in += len; - - return (int)len; -} - -/* =========================================================================== - * Initialize the "longest match" routines for a new zlib stream - */ -local void lm_init (s) - deflate_state *s; -{ - s->window_size = (ulg)2L*s->w_size; - - CLEAR_HASH(s); - - /* Set the default configuration parameters: - */ - s->max_lazy_match = configuration_table[s->level].max_lazy; - s->good_match = configuration_table[s->level].good_length; - s->nice_match = configuration_table[s->level].nice_length; - s->max_chain_length = configuration_table[s->level].max_chain; - - s->strstart = 0; - s->block_start = 0L; - s->lookahead = 0; - s->match_length = s->prev_length = MIN_MATCH-1; - s->match_available = 0; - s->ins_h = 0; -#ifndef FASTEST -#ifdef ASMV - match_init(); /* initialize the asm code */ -#endif -#endif -} - -#ifndef FASTEST -/* =========================================================================== - * Set match_start to the longest match starting at the given string and - * return its length. Matches shorter or equal to prev_length are discarded, - * in which case the result is equal to prev_length and match_start is - * garbage. - * IN assertions: cur_match is the head of the hash chain for the current - * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 - * OUT assertion: the match length is not greater than s->lookahead. - */ -#ifndef ASMV -/* For 80x86 and 680x0, an optimized version will be provided in match.asm or - * match.S. The code will be functionally equivalent. - */ -local uInt longest_match(s, cur_match) - deflate_state *s; - IPos cur_match; /* current match */ -{ - unsigned chain_length = s->max_chain_length;/* max hash chain length */ - register Bytef *scan = s->window + s->strstart; /* current string */ - register Bytef *match; /* matched string */ - register int len; /* length of current match */ - int best_len = s->prev_length; /* best match length so far */ - int nice_match = s->nice_match; /* stop if match long enough */ - IPos limit = s->strstart > (IPos)MAX_DIST(s) ? - s->strstart - (IPos)MAX_DIST(s) : NIL; - /* Stop when cur_match becomes <= limit. To simplify the code, - * we prevent matches with the string of window index 0. - */ - Posf *prev = s->prev; - uInt wmask = s->w_mask; - -#ifdef UNALIGNED_OK - /* Compare two bytes at a time. Note: this is not always beneficial. - * Try with and without -DUNALIGNED_OK to check. - */ - register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1; - register ush scan_start = *(ushf*)scan; - register ush scan_end = *(ushf*)(scan+best_len-1); -#else - register Bytef *strend = s->window + s->strstart + MAX_MATCH; - register Byte scan_end1 = scan[best_len-1]; - register Byte scan_end = scan[best_len]; -#endif - - /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. - * It is easy to get rid of this optimization if necessary. - */ - Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); - - /* Do not waste too much time if we already have a good match: */ - if (s->prev_length >= s->good_match) { - chain_length >>= 2; - } - /* Do not look for matches beyond the end of the input. This is necessary - * to make deflate deterministic. - */ - if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; - - Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); - - do { - Assert(cur_match < s->strstart, "no future"); - match = s->window + cur_match; - - /* Skip to next match if the match length cannot increase - * or if the match length is less than 2. Note that the checks below - * for insufficient lookahead only occur occasionally for performance - * reasons. Therefore uninitialized memory will be accessed, and - * conditional jumps will be made that depend on those values. - * However the length of the match is limited to the lookahead, so - * the output of deflate is not affected by the uninitialized values. - */ -#if (defined(UNALIGNED_OK) && MAX_MATCH == 258) - /* This code assumes sizeof(unsigned short) == 2. Do not use - * UNALIGNED_OK if your compiler uses a different size. - */ - if (*(ushf*)(match+best_len-1) != scan_end || - *(ushf*)match != scan_start) continue; - - /* It is not necessary to compare scan[2] and match[2] since they are - * always equal when the other bytes match, given that the hash keys - * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at - * strstart+3, +5, ... up to strstart+257. We check for insufficient - * lookahead only every 4th comparison; the 128th check will be made - * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is - * necessary to put more guard bytes at the end of the window, or - * to check more often for insufficient lookahead. - */ - Assert(scan[2] == match[2], "scan[2]?"); - scan++, match++; - do { - } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) && - *(ushf*)(scan+=2) == *(ushf*)(match+=2) && - *(ushf*)(scan+=2) == *(ushf*)(match+=2) && - *(ushf*)(scan+=2) == *(ushf*)(match+=2) && - scan < strend); - /* The funny "do {}" generates better code on most compilers */ - - /* Here, scan <= window+strstart+257 */ - Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); - if (*scan == *match) scan++; - - len = (MAX_MATCH - 1) - (int)(strend-scan); - scan = strend - (MAX_MATCH-1); - -#else /* UNALIGNED_OK */ - - if (match[best_len] != scan_end || - match[best_len-1] != scan_end1 || - *match != *scan || - *++match != scan[1]) continue; - - /* The check at best_len-1 can be removed because it will be made - * again later. (This heuristic is not always a win.) - * It is not necessary to compare scan[2] and match[2] since they - * are always equal when the other bytes match, given that - * the hash keys are equal and that HASH_BITS >= 8. - */ - scan += 2, match++; - Assert(*scan == *match, "match[2]?"); - - /* We check for insufficient lookahead only every 8th comparison; - * the 256th check will be made at strstart+258. - */ - do { - } while (*++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - scan < strend); - - Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); - - len = MAX_MATCH - (int)(strend - scan); - scan = strend - MAX_MATCH; - -#endif /* UNALIGNED_OK */ - - if (len > best_len) { - s->match_start = cur_match; - best_len = len; - if (len >= nice_match) break; -#ifdef UNALIGNED_OK - scan_end = *(ushf*)(scan+best_len-1); -#else - scan_end1 = scan[best_len-1]; - scan_end = scan[best_len]; -#endif - } - } while ((cur_match = prev[cur_match & wmask]) > limit - && --chain_length != 0); - - if ((uInt)best_len <= s->lookahead) return (uInt)best_len; - return s->lookahead; -} -#endif /* ASMV */ - -#else /* FASTEST */ - -/* --------------------------------------------------------------------------- - * Optimized version for FASTEST only - */ -local uInt longest_match(s, cur_match) - deflate_state *s; - IPos cur_match; /* current match */ -{ - register Bytef *scan = s->window + s->strstart; /* current string */ - register Bytef *match; /* matched string */ - register int len; /* length of current match */ - register Bytef *strend = s->window + s->strstart + MAX_MATCH; - - /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. - * It is easy to get rid of this optimization if necessary. - */ - Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); - - Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); - - Assert(cur_match < s->strstart, "no future"); - - match = s->window + cur_match; - - /* Return failure if the match length is less than 2: - */ - if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1; - - /* The check at best_len-1 can be removed because it will be made - * again later. (This heuristic is not always a win.) - * It is not necessary to compare scan[2] and match[2] since they - * are always equal when the other bytes match, given that - * the hash keys are equal and that HASH_BITS >= 8. - */ - scan += 2, match += 2; - Assert(*scan == *match, "match[2]?"); - - /* We check for insufficient lookahead only every 8th comparison; - * the 256th check will be made at strstart+258. - */ - do { - } while (*++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - scan < strend); - - Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); - - len = MAX_MATCH - (int)(strend - scan); - - if (len < MIN_MATCH) return MIN_MATCH - 1; - - s->match_start = cur_match; - return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead; -} - -#endif /* FASTEST */ - -#ifdef DEBUG -/* =========================================================================== - * Check that the match at match_start is indeed a match. - */ -local void check_match(s, start, match, length) - deflate_state *s; - IPos start, match; - int length; -{ - /* check that the match is indeed a match */ - if (zmemcmp(s->window + match, - s->window + start, length) != EQUAL) { - fprintf(stderr, " start %u, match %u, length %d\n", - start, match, length); - do { - fprintf(stderr, "%c%c", s->window[match++], s->window[start++]); - } while (--length != 0); - z_error("invalid match"); - } - if (z_verbose > 1) { - fprintf(stderr,"\\[%d,%d]", start-match, length); - do { putc(s->window[start++], stderr); } while (--length != 0); - } -} -#else -# define check_match(s, start, match, length) -#endif /* DEBUG */ - -/* =========================================================================== - * Fill the window when the lookahead becomes insufficient. - * Updates strstart and lookahead. - * - * IN assertion: lookahead < MIN_LOOKAHEAD - * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD - * At least one byte has been read, or avail_in == 0; reads are - * performed for at least two bytes (required for the zip translate_eol - * option -- not supported here). - */ -local void fill_window(s) - deflate_state *s; -{ - register unsigned n, m; - register Posf *p; - unsigned more; /* Amount of free space at the end of the window. */ - uInt wsize = s->w_size; - - do { - more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); - - /* Deal with !@#$% 64K limit: */ - if (sizeof(int) <= 2) { - if (more == 0 && s->strstart == 0 && s->lookahead == 0) { - more = wsize; - - } else if (more == (unsigned)(-1)) { - /* Very unlikely, but possible on 16 bit machine if - * strstart == 0 && lookahead == 1 (input done a byte at time) - */ - more--; - } - } - - /* If the window is almost full and there is insufficient lookahead, - * move the upper half to the lower one to make room in the upper half. - */ - if (s->strstart >= wsize+MAX_DIST(s)) { - - zmemcpy(s->window, s->window+wsize, (unsigned)wsize); - s->match_start -= wsize; - s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ - s->block_start -= (long) wsize; - - /* Slide the hash table (could be avoided with 32 bit values - at the expense of memory usage). We slide even when level == 0 - to keep the hash table consistent if we switch back to level > 0 - later. (Using level 0 permanently is not an optimal usage of - zlib, so we don't care about this pathological case.) - */ - n = s->hash_size; - p = &s->head[n]; - do { - m = *--p; - *p = (Pos)(m >= wsize ? m-wsize : NIL); - } while (--n); - - n = wsize; -#ifndef FASTEST - p = &s->prev[n]; - do { - m = *--p; - *p = (Pos)(m >= wsize ? m-wsize : NIL); - /* If n is not on any hash chain, prev[n] is garbage but - * its value will never be used. - */ - } while (--n); -#endif - more += wsize; - } - if (s->strm->avail_in == 0) return; - - /* If there was no sliding: - * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && - * more == window_size - lookahead - strstart - * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) - * => more >= window_size - 2*WSIZE + 2 - * In the BIG_MEM or MMAP case (not yet supported), - * window_size == input_size + MIN_LOOKAHEAD && - * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. - * Otherwise, window_size == 2*WSIZE so more >= 2. - * If there was sliding, more >= WSIZE. So in all cases, more >= 2. - */ - Assert(more >= 2, "more < 2"); - - n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); - s->lookahead += n; - - /* Initialize the hash value now that we have some input: */ - if (s->lookahead >= MIN_MATCH) { - s->ins_h = s->window[s->strstart]; - UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); -#if MIN_MATCH != 3 - Call UPDATE_HASH() MIN_MATCH-3 more times -#endif - } - /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, - * but this is not important since only literal bytes will be emitted. - */ - - } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); - - /* If the WIN_INIT bytes after the end of the current data have never been - * written, then zero those bytes in order to avoid memory check reports of - * the use of uninitialized (or uninitialised as Julian writes) bytes by - * the longest match routines. Update the high water mark for the next - * time through here. WIN_INIT is set to MAX_MATCH since the longest match - * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. - */ - if (s->high_water < s->window_size) { - ulg curr = s->strstart + (ulg)(s->lookahead); - ulg init; - - if (s->high_water < curr) { - /* Previous high water mark below current data -- zero WIN_INIT - * bytes or up to end of window, whichever is less. - */ - init = s->window_size - curr; - if (init > WIN_INIT) - init = WIN_INIT; - zmemzero(s->window + curr, (unsigned)init); - s->high_water = curr + init; - } - else if (s->high_water < (ulg)curr + WIN_INIT) { - /* High water mark at or above current data, but below current data - * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up - * to end of window, whichever is less. - */ - init = (ulg)curr + WIN_INIT - s->high_water; - if (init > s->window_size - s->high_water) - init = s->window_size - s->high_water; - zmemzero(s->window + s->high_water, (unsigned)init); - s->high_water += init; - } - } -} - -/* =========================================================================== - * Flush the current block, with given end-of-file flag. - * IN assertion: strstart is set to the end of the current match. - */ -#define FLUSH_BLOCK_ONLY(s, last) { \ - _tr_flush_block(s, (s->block_start >= 0L ? \ - (charf *)&s->window[(unsigned)s->block_start] : \ - (charf *)Z_NULL), \ - (ulg)((long)s->strstart - s->block_start), \ - (last)); \ - s->block_start = s->strstart; \ - flush_pending(s->strm); \ - Tracev((stderr,"[FLUSH]")); \ -} - -/* Same but force premature exit if necessary. */ -#define FLUSH_BLOCK(s, last) { \ - FLUSH_BLOCK_ONLY(s, last); \ - if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \ -} - -/* =========================================================================== - * Copy without compression as much as possible from the input stream, return - * the current block state. - * This function does not insert new strings in the dictionary since - * uncompressible data is probably not useful. This function is used - * only for the level=0 compression option. - * NOTE: this function should be optimized to avoid extra copying from - * window to pending_buf. - */ -local block_state deflate_stored(s, flush) - deflate_state *s; - int flush; -{ - /* Stored blocks are limited to 0xffff bytes, pending_buf is limited - * to pending_buf_size, and each stored block has a 5 byte header: - */ - ulg max_block_size = 0xffff; - ulg max_start; - - if (max_block_size > s->pending_buf_size - 5) { - max_block_size = s->pending_buf_size - 5; - } - - /* Copy as much as possible from input to output: */ - for (;;) { - /* Fill the window as much as possible: */ - if (s->lookahead <= 1) { - - Assert(s->strstart < s->w_size+MAX_DIST(s) || - s->block_start >= (long)s->w_size, "slide too late"); - - fill_window(s); - if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more; - - if (s->lookahead == 0) break; /* flush the current block */ - } - Assert(s->block_start >= 0L, "block gone"); - - s->strstart += s->lookahead; - s->lookahead = 0; - - /* Emit a stored block if pending_buf will be full: */ - max_start = s->block_start + max_block_size; - if (s->strstart == 0 || (ulg)s->strstart >= max_start) { - /* strstart == 0 is possible when wraparound on 16-bit machine */ - s->lookahead = (uInt)(s->strstart - max_start); - s->strstart = (uInt)max_start; - FLUSH_BLOCK(s, 0); - } - /* Flush if we may have to slide, otherwise block_start may become - * negative and the data will be gone: - */ - if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) { - FLUSH_BLOCK(s, 0); - } - } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; -} - -/* =========================================================================== - * Compress as much as possible from the input stream, return the current - * block state. - * This function does not perform lazy evaluation of matches and inserts - * new strings in the dictionary only for unmatched strings or for short - * matches. It is used only for the fast compression options. - */ -local block_state deflate_fast(s, flush) - deflate_state *s; - int flush; -{ - IPos hash_head; /* head of the hash chain */ - int bflush; /* set if current block must be flushed */ - - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s->lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { - return need_more; - } - if (s->lookahead == 0) break; /* flush the current block */ - } - - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - hash_head = NIL; - if (s->lookahead >= MIN_MATCH) { - INSERT_STRING(s, s->strstart, hash_head); - } - - /* Find the longest match, discarding those <= prev_length. - * At this point we have always match_length < MIN_MATCH - */ - if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ - s->match_length = longest_match (s, hash_head); - /* longest_match() sets match_start */ - } - if (s->match_length >= MIN_MATCH) { - check_match(s, s->strstart, s->match_start, s->match_length); - - _tr_tally_dist(s, s->strstart - s->match_start, - s->match_length - MIN_MATCH, bflush); - - s->lookahead -= s->match_length; - - /* Insert new strings in the hash table only if the match length - * is not too large. This saves time but degrades compression. - */ -#ifndef FASTEST - if (s->match_length <= s->max_insert_length && - s->lookahead >= MIN_MATCH) { - s->match_length--; /* string at strstart already in table */ - do { - s->strstart++; - INSERT_STRING(s, s->strstart, hash_head); - /* strstart never exceeds WSIZE-MAX_MATCH, so there are - * always MIN_MATCH bytes ahead. - */ - } while (--s->match_length != 0); - s->strstart++; - } else -#endif - { - s->strstart += s->match_length; - s->match_length = 0; - s->ins_h = s->window[s->strstart]; - UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); -#if MIN_MATCH != 3 - Call UPDATE_HASH() MIN_MATCH-3 more times -#endif - /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not - * matter since it will be recomputed at next deflate call. - */ - } - } else { - /* No match, output a literal byte */ - Tracevv((stderr,"%c", s->window[s->strstart])); - _tr_tally_lit (s, s->window[s->strstart], bflush); - s->lookahead--; - s->strstart++; - } - if (bflush) FLUSH_BLOCK(s, 0); - } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; -} - -#ifndef FASTEST -/* =========================================================================== - * Same as above, but achieves better compression. We use a lazy - * evaluation for matches: a match is finally adopted only if there is - * no better match at the next window position. - */ -local block_state deflate_slow(s, flush) - deflate_state *s; - int flush; -{ - IPos hash_head; /* head of hash chain */ - int bflush; /* set if current block must be flushed */ - - /* Process the input block. */ - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s->lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { - return need_more; - } - if (s->lookahead == 0) break; /* flush the current block */ - } - - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - hash_head = NIL; - if (s->lookahead >= MIN_MATCH) { - INSERT_STRING(s, s->strstart, hash_head); - } - - /* Find the longest match, discarding those <= prev_length. - */ - s->prev_length = s->match_length, s->prev_match = s->match_start; - s->match_length = MIN_MATCH-1; - - if (hash_head != NIL && s->prev_length < s->max_lazy_match && - s->strstart - hash_head <= MAX_DIST(s)) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ - s->match_length = longest_match (s, hash_head); - /* longest_match() sets match_start */ - - if (s->match_length <= 5 && (s->strategy == Z_FILTERED -#if TOO_FAR <= 32767 - || (s->match_length == MIN_MATCH && - s->strstart - s->match_start > TOO_FAR) -#endif - )) { - - /* If prev_match is also MIN_MATCH, match_start is garbage - * but we will ignore the current match anyway. - */ - s->match_length = MIN_MATCH-1; - } - } - /* If there was a match at the previous step and the current - * match is not better, output the previous match: - */ - if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) { - uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; - /* Do not insert strings in hash table beyond this. */ - - check_match(s, s->strstart-1, s->prev_match, s->prev_length); - - _tr_tally_dist(s, s->strstart -1 - s->prev_match, - s->prev_length - MIN_MATCH, bflush); - - /* Insert in hash table all strings up to the end of the match. - * strstart-1 and strstart are already inserted. If there is not - * enough lookahead, the last two strings are not inserted in - * the hash table. - */ - s->lookahead -= s->prev_length-1; - s->prev_length -= 2; - do { - if (++s->strstart <= max_insert) { - INSERT_STRING(s, s->strstart, hash_head); - } - } while (--s->prev_length != 0); - s->match_available = 0; - s->match_length = MIN_MATCH-1; - s->strstart++; - - if (bflush) FLUSH_BLOCK(s, 0); - - } else if (s->match_available) { - /* If there was no match at the previous position, output a - * single literal. If there was a match but the current match - * is longer, truncate the previous match to a single literal. - */ - Tracevv((stderr,"%c", s->window[s->strstart-1])); - _tr_tally_lit(s, s->window[s->strstart-1], bflush); - if (bflush) { - FLUSH_BLOCK_ONLY(s, 0); - } - s->strstart++; - s->lookahead--; - if (s->strm->avail_out == 0) return need_more; - } else { - /* There is no previous match to compare with, wait for - * the next step to decide. - */ - s->match_available = 1; - s->strstart++; - s->lookahead--; - } - } - Assert (flush != Z_NO_FLUSH, "no flush?"); - if (s->match_available) { - Tracevv((stderr,"%c", s->window[s->strstart-1])); - _tr_tally_lit(s, s->window[s->strstart-1], bflush); - s->match_available = 0; - } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; -} -#endif /* FASTEST */ - -/* =========================================================================== - * For Z_RLE, simply look for runs of bytes, generate matches only of distance - * one. Do not maintain a hash table. (It will be regenerated if this run of - * deflate switches away from Z_RLE.) - */ -local block_state deflate_rle(s, flush) - deflate_state *s; - int flush; -{ - int bflush; /* set if current block must be flushed */ - uInt prev; /* byte at distance one to match */ - Bytef *scan, *strend; /* scan goes up to strend for length of run */ - - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the longest encodable run. - */ - if (s->lookahead < MAX_MATCH) { - fill_window(s); - if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) { - return need_more; - } - if (s->lookahead == 0) break; /* flush the current block */ - } - - /* See how many times the previous byte repeats */ - s->match_length = 0; - if (s->lookahead >= MIN_MATCH && s->strstart > 0) { - scan = s->window + s->strstart - 1; - prev = *scan; - if (prev == *++scan && prev == *++scan && prev == *++scan) { - strend = s->window + s->strstart + MAX_MATCH; - do { - } while (prev == *++scan && prev == *++scan && - prev == *++scan && prev == *++scan && - prev == *++scan && prev == *++scan && - prev == *++scan && prev == *++scan && - scan < strend); - s->match_length = MAX_MATCH - (int)(strend - scan); - if (s->match_length > s->lookahead) - s->match_length = s->lookahead; - } - } - - /* Emit match if have run of MIN_MATCH or longer, else emit literal */ - if (s->match_length >= MIN_MATCH) { - check_match(s, s->strstart, s->strstart - 1, s->match_length); - - _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush); - - s->lookahead -= s->match_length; - s->strstart += s->match_length; - s->match_length = 0; - } else { - /* No match, output a literal byte */ - Tracevv((stderr,"%c", s->window[s->strstart])); - _tr_tally_lit (s, s->window[s->strstart], bflush); - s->lookahead--; - s->strstart++; - } - if (bflush) FLUSH_BLOCK(s, 0); - } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; -} - -/* =========================================================================== - * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. - * (It will be regenerated if this run of deflate switches away from Huffman.) - */ -local block_state deflate_huff(s, flush) - deflate_state *s; - int flush; -{ - int bflush; /* set if current block must be flushed */ - - for (;;) { - /* Make sure that we have a literal to write. */ - if (s->lookahead == 0) { - fill_window(s); - if (s->lookahead == 0) { - if (flush == Z_NO_FLUSH) - return need_more; - break; /* flush the current block */ - } - } - - /* Output a literal byte */ - s->match_length = 0; - Tracevv((stderr,"%c", s->window[s->strstart])); - _tr_tally_lit (s, s->window[s->strstart], bflush); - s->lookahead--; - s->strstart++; - if (bflush) FLUSH_BLOCK(s, 0); - } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; -} diff --git a/externals/zlib/deflate.h b/externals/zlib/deflate.h deleted file mode 100644 index cbf0d1ea5d9..00000000000 --- a/externals/zlib/deflate.h +++ /dev/null @@ -1,342 +0,0 @@ -/* deflate.h -- internal compression state - * Copyright (C) 1995-2010 Jean-loup Gailly - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -/* @(#) $Id$ */ - -#ifndef DEFLATE_H -#define DEFLATE_H - -#include "zutil.h" - -/* define NO_GZIP when compiling if you want to disable gzip header and - trailer creation by deflate(). NO_GZIP would be used to avoid linking in - the crc code when it is not needed. For shared libraries, gzip encoding - should be left enabled. */ -#ifndef NO_GZIP -# define GZIP -#endif - -/* =========================================================================== - * Internal compression state. - */ - -#define LENGTH_CODES 29 -/* number of length codes, not counting the special END_BLOCK code */ - -#define LITERALS 256 -/* number of literal bytes 0..255 */ - -#define L_CODES (LITERALS+1+LENGTH_CODES) -/* number of Literal or Length codes, including the END_BLOCK code */ - -#define D_CODES 30 -/* number of distance codes */ - -#define BL_CODES 19 -/* number of codes used to transfer the bit lengths */ - -#define HEAP_SIZE (2*L_CODES+1) -/* maximum heap size */ - -#define MAX_BITS 15 -/* All codes must not exceed MAX_BITS bits */ - -#define INIT_STATE 42 -#define EXTRA_STATE 69 -#define NAME_STATE 73 -#define COMMENT_STATE 91 -#define HCRC_STATE 103 -#define BUSY_STATE 113 -#define FINISH_STATE 666 -/* Stream status */ - - -/* Data structure describing a single value and its code string. */ -typedef struct ct_data_s { - union { - ush freq; /* frequency count */ - ush code; /* bit string */ - } fc; - union { - ush dad; /* father node in Huffman tree */ - ush len; /* length of bit string */ - } dl; -} FAR ct_data; - -#define Freq fc.freq -#define Code fc.code -#define Dad dl.dad -#define Len dl.len - -typedef struct static_tree_desc_s static_tree_desc; - -typedef struct tree_desc_s { - ct_data *dyn_tree; /* the dynamic tree */ - int max_code; /* largest code with non zero frequency */ - static_tree_desc *stat_desc; /* the corresponding static tree */ -} FAR tree_desc; - -typedef ush Pos; -typedef Pos FAR Posf; -typedef unsigned IPos; - -/* A Pos is an index in the character window. We use short instead of int to - * save space in the various tables. IPos is used only for parameter passing. - */ - -typedef struct internal_state { - z_streamp strm; /* pointer back to this zlib stream */ - int status; /* as the name implies */ - Bytef *pending_buf; /* output still pending */ - ulg pending_buf_size; /* size of pending_buf */ - Bytef *pending_out; /* next pending byte to output to the stream */ - uInt pending; /* nb of bytes in the pending buffer */ - int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ - gz_headerp gzhead; /* gzip header information to write */ - uInt gzindex; /* where in extra, name, or comment */ - Byte method; /* STORED (for zip only) or DEFLATED */ - int last_flush; /* value of flush param for previous deflate call */ - - /* used by deflate.c: */ - - uInt w_size; /* LZ77 window size (32K by default) */ - uInt w_bits; /* log2(w_size) (8..16) */ - uInt w_mask; /* w_size - 1 */ - - Bytef *window; - /* Sliding window. Input bytes are read into the second half of the window, - * and move to the first half later to keep a dictionary of at least wSize - * bytes. With this organization, matches are limited to a distance of - * wSize-MAX_MATCH bytes, but this ensures that IO is always - * performed with a length multiple of the block size. Also, it limits - * the window size to 64K, which is quite useful on MSDOS. - * To do: use the user input buffer as sliding window. - */ - - ulg window_size; - /* Actual size of window: 2*wSize, except when the user input buffer - * is directly used as sliding window. - */ - - Posf *prev; - /* Link to older string with same hash index. To limit the size of this - * array to 64K, this link is maintained only for the last 32K strings. - * An index in this array is thus a window index modulo 32K. - */ - - Posf *head; /* Heads of the hash chains or NIL. */ - - uInt ins_h; /* hash index of string to be inserted */ - uInt hash_size; /* number of elements in hash table */ - uInt hash_bits; /* log2(hash_size) */ - uInt hash_mask; /* hash_size-1 */ - - uInt hash_shift; - /* Number of bits by which ins_h must be shifted at each input - * step. It must be such that after MIN_MATCH steps, the oldest - * byte no longer takes part in the hash key, that is: - * hash_shift * MIN_MATCH >= hash_bits - */ - - long block_start; - /* Window position at the beginning of the current output block. Gets - * negative when the window is moved backwards. - */ - - uInt match_length; /* length of best match */ - IPos prev_match; /* previous match */ - int match_available; /* set if previous match exists */ - uInt strstart; /* start of string to insert */ - uInt match_start; /* start of matching string */ - uInt lookahead; /* number of valid bytes ahead in window */ - - uInt prev_length; - /* Length of the best match at previous step. Matches not greater than this - * are discarded. This is used in the lazy match evaluation. - */ - - uInt max_chain_length; - /* To speed up deflation, hash chains are never searched beyond this - * length. A higher limit improves compression ratio but degrades the - * speed. - */ - - uInt max_lazy_match; - /* Attempt to find a better match only when the current match is strictly - * smaller than this value. This mechanism is used only for compression - * levels >= 4. - */ -# define max_insert_length max_lazy_match - /* Insert new strings in the hash table only if the match length is not - * greater than this length. This saves time but degrades compression. - * max_insert_length is used only for compression levels <= 3. - */ - - int level; /* compression level (1..9) */ - int strategy; /* favor or force Huffman coding*/ - - uInt good_match; - /* Use a faster search when the previous match is longer than this */ - - int nice_match; /* Stop searching when current match exceeds this */ - - /* used by trees.c: */ - /* Didn't use ct_data typedef below to supress compiler warning */ - struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ - struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ - struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ - - struct tree_desc_s l_desc; /* desc. for literal tree */ - struct tree_desc_s d_desc; /* desc. for distance tree */ - struct tree_desc_s bl_desc; /* desc. for bit length tree */ - - ush bl_count[MAX_BITS+1]; - /* number of codes at each bit length for an optimal tree */ - - int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ - int heap_len; /* number of elements in the heap */ - int heap_max; /* element of largest frequency */ - /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. - * The same heap array is used to build all trees. - */ - - uch depth[2*L_CODES+1]; - /* Depth of each subtree used as tie breaker for trees of equal frequency - */ - - uchf *l_buf; /* buffer for literals or lengths */ - - uInt lit_bufsize; - /* Size of match buffer for literals/lengths. There are 4 reasons for - * limiting lit_bufsize to 64K: - * - frequencies can be kept in 16 bit counters - * - if compression is not successful for the first block, all input - * data is still in the window so we can still emit a stored block even - * when input comes from standard input. (This can also be done for - * all blocks if lit_bufsize is not greater than 32K.) - * - if compression is not successful for a file smaller than 64K, we can - * even emit a stored file instead of a stored block (saving 5 bytes). - * This is applicable only for zip (not gzip or zlib). - * - creating new Huffman trees less frequently may not provide fast - * adaptation to changes in the input data statistics. (Take for - * example a binary file with poorly compressible code followed by - * a highly compressible string table.) Smaller buffer sizes give - * fast adaptation but have of course the overhead of transmitting - * trees more frequently. - * - I can't count above 4 - */ - - uInt last_lit; /* running index in l_buf */ - - ushf *d_buf; - /* Buffer for distances. To simplify the code, d_buf and l_buf have - * the same number of elements. To use different lengths, an extra flag - * array would be necessary. - */ - - ulg opt_len; /* bit length of current block with optimal trees */ - ulg static_len; /* bit length of current block with static trees */ - uInt matches; /* number of string matches in current block */ - int last_eob_len; /* bit length of EOB code for last block */ - -#ifdef DEBUG - ulg compressed_len; /* total bit length of compressed file mod 2^32 */ - ulg bits_sent; /* bit length of compressed data sent mod 2^32 */ -#endif - - ush bi_buf; - /* Output buffer. bits are inserted starting at the bottom (least - * significant bits). - */ - int bi_valid; - /* Number of valid bits in bi_buf. All bits above the last valid bit - * are always zero. - */ - - ulg high_water; - /* High water mark offset in window for initialized bytes -- bytes above - * this are set to zero in order to avoid memory check warnings when - * longest match routines access bytes past the input. This is then - * updated to the new high water mark. - */ - -} FAR deflate_state; - -/* Output a byte on the stream. - * IN assertion: there is enough room in pending_buf. - */ -#define put_byte(s, c) {s->pending_buf[s->pending++] = (c);} - - -#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) -/* Minimum amount of lookahead, except at the end of the input file. - * See deflate.c for comments about the MIN_MATCH+1. - */ - -#define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD) -/* In order to simplify the code, particularly on 16 bit machines, match - * distances are limited to MAX_DIST instead of WSIZE. - */ - -#define WIN_INIT MAX_MATCH -/* Number of bytes after end of data in window to initialize in order to avoid - memory checker errors from longest match routines */ - - /* in trees.c */ -void ZLIB_INTERNAL _tr_init OF((deflate_state *s)); -int ZLIB_INTERNAL _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); -void ZLIB_INTERNAL _tr_flush_block OF((deflate_state *s, charf *buf, - ulg stored_len, int last)); -void ZLIB_INTERNAL _tr_align OF((deflate_state *s)); -void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf, - ulg stored_len, int last)); - -#define d_code(dist) \ - ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]) -/* Mapping from a distance to a distance code. dist is the distance - 1 and - * must not have side effects. _dist_code[256] and _dist_code[257] are never - * used. - */ - -#ifndef DEBUG -/* Inline versions of _tr_tally for speed: */ - -#if defined(GEN_TREES_H) || !defined(STDC) - extern uch ZLIB_INTERNAL _length_code[]; - extern uch ZLIB_INTERNAL _dist_code[]; -#else - extern const uch ZLIB_INTERNAL _length_code[]; - extern const uch ZLIB_INTERNAL _dist_code[]; -#endif - -# define _tr_tally_lit(s, c, flush) \ - { uch cc = (c); \ - s->d_buf[s->last_lit] = 0; \ - s->l_buf[s->last_lit++] = cc; \ - s->dyn_ltree[cc].Freq++; \ - flush = (s->last_lit == s->lit_bufsize-1); \ - } -# define _tr_tally_dist(s, distance, length, flush) \ - { uch len = (length); \ - ush dist = (distance); \ - s->d_buf[s->last_lit] = dist; \ - s->l_buf[s->last_lit++] = len; \ - dist--; \ - s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ - s->dyn_dtree[d_code(dist)].Freq++; \ - flush = (s->last_lit == s->lit_bufsize-1); \ - } -#else -# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c) -# define _tr_tally_dist(s, distance, length, flush) \ - flush = _tr_tally(s, distance, length) -#endif - -#endif /* DEFLATE_H */ diff --git a/externals/zlib/example.c b/externals/zlib/example.c deleted file mode 100644 index 604736f15f6..00000000000 --- a/externals/zlib/example.c +++ /dev/null @@ -1,565 +0,0 @@ -/* example.c -- usage example of the zlib compression library - * Copyright (C) 1995-2006 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#include "zlib.h" -#include - -#ifdef STDC -# include -# include -#endif - -#if defined(VMS) || defined(RISCOS) -# define TESTFILE "foo-gz" -#else -# define TESTFILE "foo.gz" -#endif - -#define CHECK_ERR(err, msg) { \ - if (err != Z_OK) { \ - fprintf(stderr, "%s error: %d\n", msg, err); \ - exit(1); \ - } \ -} - -const char hello[] = "hello, hello!"; -/* "hello world" would be more standard, but the repeated "hello" - * stresses the compression code better, sorry... - */ - -const char dictionary[] = "hello"; -uLong dictId; /* Adler32 value of the dictionary */ - -void test_compress OF((Byte *compr, uLong comprLen, - Byte *uncompr, uLong uncomprLen)); -void test_gzio OF((const char *fname, - Byte *uncompr, uLong uncomprLen)); -void test_deflate OF((Byte *compr, uLong comprLen)); -void test_inflate OF((Byte *compr, uLong comprLen, - Byte *uncompr, uLong uncomprLen)); -void test_large_deflate OF((Byte *compr, uLong comprLen, - Byte *uncompr, uLong uncomprLen)); -void test_large_inflate OF((Byte *compr, uLong comprLen, - Byte *uncompr, uLong uncomprLen)); -void test_flush OF((Byte *compr, uLong *comprLen)); -void test_sync OF((Byte *compr, uLong comprLen, - Byte *uncompr, uLong uncomprLen)); -void test_dict_deflate OF((Byte *compr, uLong comprLen)); -void test_dict_inflate OF((Byte *compr, uLong comprLen, - Byte *uncompr, uLong uncomprLen)); -int main OF((int argc, char *argv[])); - -/* =========================================================================== - * Test compress() and uncompress() - */ -void test_compress(compr, comprLen, uncompr, uncomprLen) - Byte *compr, *uncompr; - uLong comprLen, uncomprLen; -{ - int err; - uLong len = (uLong)strlen(hello)+1; - - err = compress(compr, &comprLen, (const Bytef*)hello, len); - CHECK_ERR(err, "compress"); - - strcpy((char*)uncompr, "garbage"); - - err = uncompress(uncompr, &uncomprLen, compr, comprLen); - CHECK_ERR(err, "uncompress"); - - if (strcmp((char*)uncompr, hello)) { - fprintf(stderr, "bad uncompress\n"); - exit(1); - } else { - printf("uncompress(): %s\n", (char *)uncompr); - } -} - -/* =========================================================================== - * Test read/write of .gz files - */ -void test_gzio(fname, uncompr, uncomprLen) - const char *fname; /* compressed file name */ - Byte *uncompr; - uLong uncomprLen; -{ -#ifdef NO_GZCOMPRESS - fprintf(stderr, "NO_GZCOMPRESS -- gz* functions cannot compress\n"); -#else - int err; - int len = (int)strlen(hello)+1; - gzFile file; - z_off_t pos; - - file = gzopen(fname, "wb"); - if (file == NULL) { - fprintf(stderr, "gzopen error\n"); - exit(1); - } - gzputc(file, 'h'); - if (gzputs(file, "ello") != 4) { - fprintf(stderr, "gzputs err: %s\n", gzerror(file, &err)); - exit(1); - } - if (gzprintf(file, ", %s!", "hello") != 8) { - fprintf(stderr, "gzprintf err: %s\n", gzerror(file, &err)); - exit(1); - } - gzseek(file, 1L, SEEK_CUR); /* add one zero byte */ - gzclose(file); - - file = gzopen(fname, "rb"); - if (file == NULL) { - fprintf(stderr, "gzopen error\n"); - exit(1); - } - strcpy((char*)uncompr, "garbage"); - - if (gzread(file, uncompr, (unsigned)uncomprLen) != len) { - fprintf(stderr, "gzread err: %s\n", gzerror(file, &err)); - exit(1); - } - if (strcmp((char*)uncompr, hello)) { - fprintf(stderr, "bad gzread: %s\n", (char*)uncompr); - exit(1); - } else { - printf("gzread(): %s\n", (char*)uncompr); - } - - pos = gzseek(file, -8L, SEEK_CUR); - if (pos != 6 || gztell(file) != pos) { - fprintf(stderr, "gzseek error, pos=%ld, gztell=%ld\n", - (long)pos, (long)gztell(file)); - exit(1); - } - - if (gzgetc(file) != ' ') { - fprintf(stderr, "gzgetc error\n"); - exit(1); - } - - if (gzungetc(' ', file) != ' ') { - fprintf(stderr, "gzungetc error\n"); - exit(1); - } - - gzgets(file, (char*)uncompr, (int)uncomprLen); - if (strlen((char*)uncompr) != 7) { /* " hello!" */ - fprintf(stderr, "gzgets err after gzseek: %s\n", gzerror(file, &err)); - exit(1); - } - if (strcmp((char*)uncompr, hello + 6)) { - fprintf(stderr, "bad gzgets after gzseek\n"); - exit(1); - } else { - printf("gzgets() after gzseek: %s\n", (char*)uncompr); - } - - gzclose(file); -#endif -} - -/* =========================================================================== - * Test deflate() with small buffers - */ -void test_deflate(compr, comprLen) - Byte *compr; - uLong comprLen; -{ - z_stream c_stream; /* compression stream */ - int err; - uLong len = (uLong)strlen(hello)+1; - - c_stream.zalloc = (alloc_func)0; - c_stream.zfree = (free_func)0; - c_stream.opaque = (voidpf)0; - - err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION); - CHECK_ERR(err, "deflateInit"); - - c_stream.next_in = (Bytef*)hello; - c_stream.next_out = compr; - - while (c_stream.total_in != len && c_stream.total_out < comprLen) { - c_stream.avail_in = c_stream.avail_out = 1; /* force small buffers */ - err = deflate(&c_stream, Z_NO_FLUSH); - CHECK_ERR(err, "deflate"); - } - /* Finish the stream, still forcing small buffers: */ - for (;;) { - c_stream.avail_out = 1; - err = deflate(&c_stream, Z_FINISH); - if (err == Z_STREAM_END) break; - CHECK_ERR(err, "deflate"); - } - - err = deflateEnd(&c_stream); - CHECK_ERR(err, "deflateEnd"); -} - -/* =========================================================================== - * Test inflate() with small buffers - */ -void test_inflate(compr, comprLen, uncompr, uncomprLen) - Byte *compr, *uncompr; - uLong comprLen, uncomprLen; -{ - int err; - z_stream d_stream; /* decompression stream */ - - strcpy((char*)uncompr, "garbage"); - - d_stream.zalloc = (alloc_func)0; - d_stream.zfree = (free_func)0; - d_stream.opaque = (voidpf)0; - - d_stream.next_in = compr; - d_stream.avail_in = 0; - d_stream.next_out = uncompr; - - err = inflateInit(&d_stream); - CHECK_ERR(err, "inflateInit"); - - while (d_stream.total_out < uncomprLen && d_stream.total_in < comprLen) { - d_stream.avail_in = d_stream.avail_out = 1; /* force small buffers */ - err = inflate(&d_stream, Z_NO_FLUSH); - if (err == Z_STREAM_END) break; - CHECK_ERR(err, "inflate"); - } - - err = inflateEnd(&d_stream); - CHECK_ERR(err, "inflateEnd"); - - if (strcmp((char*)uncompr, hello)) { - fprintf(stderr, "bad inflate\n"); - exit(1); - } else { - printf("inflate(): %s\n", (char *)uncompr); - } -} - -/* =========================================================================== - * Test deflate() with large buffers and dynamic change of compression level - */ -void test_large_deflate(compr, comprLen, uncompr, uncomprLen) - Byte *compr, *uncompr; - uLong comprLen, uncomprLen; -{ - z_stream c_stream; /* compression stream */ - int err; - - c_stream.zalloc = (alloc_func)0; - c_stream.zfree = (free_func)0; - c_stream.opaque = (voidpf)0; - - err = deflateInit(&c_stream, Z_BEST_SPEED); - CHECK_ERR(err, "deflateInit"); - - c_stream.next_out = compr; - c_stream.avail_out = (uInt)comprLen; - - /* At this point, uncompr is still mostly zeroes, so it should compress - * very well: - */ - c_stream.next_in = uncompr; - c_stream.avail_in = (uInt)uncomprLen; - err = deflate(&c_stream, Z_NO_FLUSH); - CHECK_ERR(err, "deflate"); - if (c_stream.avail_in != 0) { - fprintf(stderr, "deflate not greedy\n"); - exit(1); - } - - /* Feed in already compressed data and switch to no compression: */ - deflateParams(&c_stream, Z_NO_COMPRESSION, Z_DEFAULT_STRATEGY); - c_stream.next_in = compr; - c_stream.avail_in = (uInt)comprLen/2; - err = deflate(&c_stream, Z_NO_FLUSH); - CHECK_ERR(err, "deflate"); - - /* Switch back to compressing mode: */ - deflateParams(&c_stream, Z_BEST_COMPRESSION, Z_FILTERED); - c_stream.next_in = uncompr; - c_stream.avail_in = (uInt)uncomprLen; - err = deflate(&c_stream, Z_NO_FLUSH); - CHECK_ERR(err, "deflate"); - - err = deflate(&c_stream, Z_FINISH); - if (err != Z_STREAM_END) { - fprintf(stderr, "deflate should report Z_STREAM_END\n"); - exit(1); - } - err = deflateEnd(&c_stream); - CHECK_ERR(err, "deflateEnd"); -} - -/* =========================================================================== - * Test inflate() with large buffers - */ -void test_large_inflate(compr, comprLen, uncompr, uncomprLen) - Byte *compr, *uncompr; - uLong comprLen, uncomprLen; -{ - int err; - z_stream d_stream; /* decompression stream */ - - strcpy((char*)uncompr, "garbage"); - - d_stream.zalloc = (alloc_func)0; - d_stream.zfree = (free_func)0; - d_stream.opaque = (voidpf)0; - - d_stream.next_in = compr; - d_stream.avail_in = (uInt)comprLen; - - err = inflateInit(&d_stream); - CHECK_ERR(err, "inflateInit"); - - for (;;) { - d_stream.next_out = uncompr; /* discard the output */ - d_stream.avail_out = (uInt)uncomprLen; - err = inflate(&d_stream, Z_NO_FLUSH); - if (err == Z_STREAM_END) break; - CHECK_ERR(err, "large inflate"); - } - - err = inflateEnd(&d_stream); - CHECK_ERR(err, "inflateEnd"); - - if (d_stream.total_out != 2*uncomprLen + comprLen/2) { - fprintf(stderr, "bad large inflate: %ld\n", d_stream.total_out); - exit(1); - } else { - printf("large_inflate(): OK\n"); - } -} - -/* =========================================================================== - * Test deflate() with full flush - */ -void test_flush(compr, comprLen) - Byte *compr; - uLong *comprLen; -{ - z_stream c_stream; /* compression stream */ - int err; - uInt len = (uInt)strlen(hello)+1; - - c_stream.zalloc = (alloc_func)0; - c_stream.zfree = (free_func)0; - c_stream.opaque = (voidpf)0; - - err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION); - CHECK_ERR(err, "deflateInit"); - - c_stream.next_in = (Bytef*)hello; - c_stream.next_out = compr; - c_stream.avail_in = 3; - c_stream.avail_out = (uInt)*comprLen; - err = deflate(&c_stream, Z_FULL_FLUSH); - CHECK_ERR(err, "deflate"); - - compr[3]++; /* force an error in first compressed block */ - c_stream.avail_in = len - 3; - - err = deflate(&c_stream, Z_FINISH); - if (err != Z_STREAM_END) { - CHECK_ERR(err, "deflate"); - } - err = deflateEnd(&c_stream); - CHECK_ERR(err, "deflateEnd"); - - *comprLen = c_stream.total_out; -} - -/* =========================================================================== - * Test inflateSync() - */ -void test_sync(compr, comprLen, uncompr, uncomprLen) - Byte *compr, *uncompr; - uLong comprLen, uncomprLen; -{ - int err; - z_stream d_stream; /* decompression stream */ - - strcpy((char*)uncompr, "garbage"); - - d_stream.zalloc = (alloc_func)0; - d_stream.zfree = (free_func)0; - d_stream.opaque = (voidpf)0; - - d_stream.next_in = compr; - d_stream.avail_in = 2; /* just read the zlib header */ - - err = inflateInit(&d_stream); - CHECK_ERR(err, "inflateInit"); - - d_stream.next_out = uncompr; - d_stream.avail_out = (uInt)uncomprLen; - - inflate(&d_stream, Z_NO_FLUSH); - CHECK_ERR(err, "inflate"); - - d_stream.avail_in = (uInt)comprLen-2; /* read all compressed data */ - err = inflateSync(&d_stream); /* but skip the damaged part */ - CHECK_ERR(err, "inflateSync"); - - err = inflate(&d_stream, Z_FINISH); - if (err != Z_DATA_ERROR) { - fprintf(stderr, "inflate should report DATA_ERROR\n"); - /* Because of incorrect adler32 */ - exit(1); - } - err = inflateEnd(&d_stream); - CHECK_ERR(err, "inflateEnd"); - - printf("after inflateSync(): hel%s\n", (char *)uncompr); -} - -/* =========================================================================== - * Test deflate() with preset dictionary - */ -void test_dict_deflate(compr, comprLen) - Byte *compr; - uLong comprLen; -{ - z_stream c_stream; /* compression stream */ - int err; - - c_stream.zalloc = (alloc_func)0; - c_stream.zfree = (free_func)0; - c_stream.opaque = (voidpf)0; - - err = deflateInit(&c_stream, Z_BEST_COMPRESSION); - CHECK_ERR(err, "deflateInit"); - - err = deflateSetDictionary(&c_stream, - (const Bytef*)dictionary, sizeof(dictionary)); - CHECK_ERR(err, "deflateSetDictionary"); - - dictId = c_stream.adler; - c_stream.next_out = compr; - c_stream.avail_out = (uInt)comprLen; - - c_stream.next_in = (Bytef*)hello; - c_stream.avail_in = (uInt)strlen(hello)+1; - - err = deflate(&c_stream, Z_FINISH); - if (err != Z_STREAM_END) { - fprintf(stderr, "deflate should report Z_STREAM_END\n"); - exit(1); - } - err = deflateEnd(&c_stream); - CHECK_ERR(err, "deflateEnd"); -} - -/* =========================================================================== - * Test inflate() with a preset dictionary - */ -void test_dict_inflate(compr, comprLen, uncompr, uncomprLen) - Byte *compr, *uncompr; - uLong comprLen, uncomprLen; -{ - int err; - z_stream d_stream; /* decompression stream */ - - strcpy((char*)uncompr, "garbage"); - - d_stream.zalloc = (alloc_func)0; - d_stream.zfree = (free_func)0; - d_stream.opaque = (voidpf)0; - - d_stream.next_in = compr; - d_stream.avail_in = (uInt)comprLen; - - err = inflateInit(&d_stream); - CHECK_ERR(err, "inflateInit"); - - d_stream.next_out = uncompr; - d_stream.avail_out = (uInt)uncomprLen; - - for (;;) { - err = inflate(&d_stream, Z_NO_FLUSH); - if (err == Z_STREAM_END) break; - if (err == Z_NEED_DICT) { - if (d_stream.adler != dictId) { - fprintf(stderr, "unexpected dictionary"); - exit(1); - } - err = inflateSetDictionary(&d_stream, (const Bytef*)dictionary, - sizeof(dictionary)); - } - CHECK_ERR(err, "inflate with dict"); - } - - err = inflateEnd(&d_stream); - CHECK_ERR(err, "inflateEnd"); - - if (strcmp((char*)uncompr, hello)) { - fprintf(stderr, "bad inflate with dict\n"); - exit(1); - } else { - printf("inflate with dictionary: %s\n", (char *)uncompr); - } -} - -/* =========================================================================== - * Usage: example [output.gz [input.gz]] - */ - -int main(argc, argv) - int argc; - char *argv[]; -{ - Byte *compr, *uncompr; - uLong comprLen = 10000*sizeof(int); /* don't overflow on MSDOS */ - uLong uncomprLen = comprLen; - static const char* myVersion = ZLIB_VERSION; - - if (zlibVersion()[0] != myVersion[0]) { - fprintf(stderr, "incompatible zlib version\n"); - exit(1); - - } else if (strcmp(zlibVersion(), ZLIB_VERSION) != 0) { - fprintf(stderr, "warning: different zlib version\n"); - } - - printf("zlib version %s = 0x%04x, compile flags = 0x%lx\n", - ZLIB_VERSION, ZLIB_VERNUM, zlibCompileFlags()); - - compr = (Byte*)calloc((uInt)comprLen, 1); - uncompr = (Byte*)calloc((uInt)uncomprLen, 1); - /* compr and uncompr are cleared to avoid reading uninitialized - * data and to ensure that uncompr compresses well. - */ - if (compr == Z_NULL || uncompr == Z_NULL) { - printf("out of memory\n"); - exit(1); - } - test_compress(compr, comprLen, uncompr, uncomprLen); - - test_gzio((argc > 1 ? argv[1] : TESTFILE), - uncompr, uncomprLen); - - test_deflate(compr, comprLen); - test_inflate(compr, comprLen, uncompr, uncomprLen); - - test_large_deflate(compr, comprLen, uncompr, uncomprLen); - test_large_inflate(compr, comprLen, uncompr, uncomprLen); - - test_flush(compr, &comprLen); - test_sync(compr, comprLen, uncompr, uncomprLen); - comprLen = uncomprLen; - - test_dict_deflate(compr, comprLen); - test_dict_inflate(compr, comprLen, uncompr, uncomprLen); - - free(compr); - free(uncompr); - - return 0; -} diff --git a/externals/zlib/gzclose.c b/externals/zlib/gzclose.c deleted file mode 100644 index caeb99a3177..00000000000 --- a/externals/zlib/gzclose.c +++ /dev/null @@ -1,25 +0,0 @@ -/* gzclose.c -- zlib gzclose() function - * Copyright (C) 2004, 2010 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -#include "gzguts.h" - -/* gzclose() is in a separate file so that it is linked in only if it is used. - That way the other gzclose functions can be used instead to avoid linking in - unneeded compression or decompression routines. */ -int ZEXPORT gzclose(file) - gzFile file; -{ -#ifndef NO_GZCOMPRESS - gz_statep state; - - if (file == NULL) - return Z_STREAM_ERROR; - state = (gz_statep)file; - - return state->mode == GZ_READ ? gzclose_r(file) : gzclose_w(file); -#else - return gzclose_r(file); -#endif -} diff --git a/externals/zlib/gzguts.h b/externals/zlib/gzguts.h deleted file mode 100644 index 0f8fb79f87d..00000000000 --- a/externals/zlib/gzguts.h +++ /dev/null @@ -1,132 +0,0 @@ -/* gzguts.h -- zlib internal header definitions for gz* operations - * Copyright (C) 2004, 2005, 2010 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -#ifdef _LARGEFILE64_SOURCE -# ifndef _LARGEFILE_SOURCE -# define _LARGEFILE_SOURCE 1 -# endif -# ifdef _FILE_OFFSET_BITS -# undef _FILE_OFFSET_BITS -# endif -#endif - -#if ((__GNUC__-0) * 10 + __GNUC_MINOR__-0 >= 33) && !defined(NO_VIZ) -# define ZLIB_INTERNAL __attribute__((visibility ("hidden"))) -#else -# define ZLIB_INTERNAL -#endif - -#include -#include "zlib.h" -#ifdef STDC -# include -# include -# include -#endif -#include - -#ifdef NO_DEFLATE /* for compatibility with old definition */ -# define NO_GZCOMPRESS -#endif - -#ifdef _MSC_VER -# include -# define vsnprintf _vsnprintf -#endif - -#ifndef local -# define local static -#endif -/* compile with -Dlocal if your debugger can't find static symbols */ - -/* gz* functions always use library allocation functions */ -#ifndef STDC - extern voidp malloc OF((uInt size)); - extern void free OF((voidpf ptr)); -#endif - -/* get errno and strerror definition */ -#if defined UNDER_CE -# include -# define zstrerror() gz_strwinerror((DWORD)GetLastError()) -#else -# ifdef STDC -# include -# define zstrerror() strerror(errno) -# else -# define zstrerror() "stdio error (consult errno)" -# endif -#endif - -/* provide prototypes for these when building zlib without LFS */ -#if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0 - ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); - ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); - ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); - ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); -#endif - -/* default i/o buffer size -- double this for output when reading */ -#define GZBUFSIZE 8192 - -/* gzip modes, also provide a little integrity check on the passed structure */ -#define GZ_NONE 0 -#define GZ_READ 7247 -#define GZ_WRITE 31153 -#define GZ_APPEND 1 /* mode set to GZ_WRITE after the file is opened */ - -/* values for gz_state how */ -#define LOOK 0 /* look for a gzip header */ -#define COPY 1 /* copy input directly */ -#define GZIP 2 /* decompress a gzip stream */ - -/* internal gzip file state data structure */ -typedef struct { - /* used for both reading and writing */ - int mode; /* see gzip modes above */ - int fd; /* file descriptor */ - char *path; /* path or fd for error messages */ - z_off64_t pos; /* current position in uncompressed data */ - unsigned size; /* buffer size, zero if not allocated yet */ - unsigned want; /* requested buffer size, default is GZBUFSIZE */ - unsigned char *in; /* input buffer */ - unsigned char *out; /* output buffer (double-sized when reading) */ - unsigned char *next; /* next output data to deliver or write */ - /* just for reading */ - unsigned have; /* amount of output data unused at next */ - int eof; /* true if end of input file reached */ - z_off64_t start; /* where the gzip data started, for rewinding */ - z_off64_t raw; /* where the raw data started, for seeking */ - int how; /* 0: get header, 1: copy, 2: decompress */ - int direct; /* true if last read direct, false if gzip */ - /* just for writing */ - int level; /* compression level */ - int strategy; /* compression strategy */ - /* seek request */ - z_off64_t skip; /* amount to skip (already rewound if backwards) */ - int seek; /* true if seek request pending */ - /* error information */ - int err; /* error code */ - char *msg; /* error message */ - /* zlib inflate or deflate stream */ - z_stream strm; /* stream structure in-place (not a pointer) */ -} gz_state; -typedef gz_state FAR *gz_statep; - -/* shared functions */ -void ZLIB_INTERNAL gz_error OF((gz_statep, int, const char *)); -#if defined UNDER_CE -char ZLIB_INTERNAL *gz_strwinerror OF((DWORD error)); -#endif - -/* GT_OFF(x), where x is an unsigned value, is true if x > maximum z_off64_t - value -- needed when comparing unsigned to z_off64_t, which is signed - (possible z_off64_t types off_t, off64_t, and long are all signed) */ -#ifdef INT_MAX -# define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > INT_MAX) -#else -unsigned ZLIB_INTERNAL gz_intmax OF((void)); -# define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > gz_intmax()) -#endif diff --git a/externals/zlib/gzlib.c b/externals/zlib/gzlib.c deleted file mode 100644 index 603e60ed544..00000000000 --- a/externals/zlib/gzlib.c +++ /dev/null @@ -1,537 +0,0 @@ -/* gzlib.c -- zlib functions common to reading and writing gzip files - * Copyright (C) 2004, 2010 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -#include "gzguts.h" - -#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 -# define LSEEK lseek64 -#else -# define LSEEK lseek -#endif - -/* Local functions */ -local void gz_reset OF((gz_statep)); -local gzFile gz_open OF((const char *, int, const char *)); - -#if defined UNDER_CE - -/* Map the Windows error number in ERROR to a locale-dependent error message - string and return a pointer to it. Typically, the values for ERROR come - from GetLastError. - - The string pointed to shall not be modified by the application, but may be - overwritten by a subsequent call to gz_strwinerror - - The gz_strwinerror function does not change the current setting of - GetLastError. */ -char ZLIB_INTERNAL *gz_strwinerror (error) - DWORD error; -{ - static char buf[1024]; - - wchar_t *msgbuf; - DWORD lasterr = GetLastError(); - DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM - | FORMAT_MESSAGE_ALLOCATE_BUFFER, - NULL, - error, - 0, /* Default language */ - (LPVOID)&msgbuf, - 0, - NULL); - if (chars != 0) { - /* If there is an \r\n appended, zap it. */ - if (chars >= 2 - && msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') { - chars -= 2; - msgbuf[chars] = 0; - } - - if (chars > sizeof (buf) - 1) { - chars = sizeof (buf) - 1; - msgbuf[chars] = 0; - } - - wcstombs(buf, msgbuf, chars + 1); - LocalFree(msgbuf); - } - else { - sprintf(buf, "unknown win32 error (%ld)", error); - } - - SetLastError(lasterr); - return buf; -} - -#endif /* UNDER_CE */ - -/* Reset gzip file state */ -local void gz_reset(state) - gz_statep state; -{ - if (state->mode == GZ_READ) { /* for reading ... */ - state->have = 0; /* no output data available */ - state->eof = 0; /* not at end of file */ - state->how = LOOK; /* look for gzip header */ - state->direct = 1; /* default for empty file */ - } - state->seek = 0; /* no seek request pending */ - gz_error(state, Z_OK, NULL); /* clear error */ - state->pos = 0; /* no uncompressed data yet */ - state->strm.avail_in = 0; /* no input data yet */ -} - -/* Open a gzip file either by name or file descriptor. */ -local gzFile gz_open(path, fd, mode) - const char *path; - int fd; - const char *mode; -{ - gz_statep state; - - /* allocate gzFile structure to return */ - state = malloc(sizeof(gz_state)); - if (state == NULL) - return NULL; - state->size = 0; /* no buffers allocated yet */ - state->want = GZBUFSIZE; /* requested buffer size */ - state->msg = NULL; /* no error message yet */ - - /* interpret mode */ - state->mode = GZ_NONE; - state->level = Z_DEFAULT_COMPRESSION; - state->strategy = Z_DEFAULT_STRATEGY; - while (*mode) { - if (*mode >= '0' && *mode <= '9') - state->level = *mode - '0'; - else - switch (*mode) { - case 'r': - state->mode = GZ_READ; - break; -#ifndef NO_GZCOMPRESS - case 'w': - state->mode = GZ_WRITE; - break; - case 'a': - state->mode = GZ_APPEND; - break; -#endif - case '+': /* can't read and write at the same time */ - free(state); - return NULL; - case 'b': /* ignore -- will request binary anyway */ - break; - case 'f': - state->strategy = Z_FILTERED; - break; - case 'h': - state->strategy = Z_HUFFMAN_ONLY; - break; - case 'R': - state->strategy = Z_RLE; - break; - case 'F': - state->strategy = Z_FIXED; - default: /* could consider as an error, but just ignore */ - ; - } - mode++; - } - - /* must provide an "r", "w", or "a" */ - if (state->mode == GZ_NONE) { - free(state); - return NULL; - } - - /* save the path name for error messages */ - state->path = malloc(strlen(path) + 1); - if (state->path == NULL) { - free(state); - return NULL; - } - strcpy(state->path, path); - - /* open the file with the appropriate mode (or just use fd) */ - state->fd = fd != -1 ? fd : - open(path, -#ifdef O_LARGEFILE - O_LARGEFILE | -#endif -#ifdef O_BINARY - O_BINARY | -#endif - (state->mode == GZ_READ ? - O_RDONLY : - (O_WRONLY | O_CREAT | ( - state->mode == GZ_WRITE ? - O_TRUNC : - O_APPEND))), - 0666); - if (state->fd == -1) { - free(state->path); - free(state); - return NULL; - } - if (state->mode == GZ_APPEND) - state->mode = GZ_WRITE; /* simplify later checks */ - - /* save the current position for rewinding (only if reading) */ - if (state->mode == GZ_READ) { - state->start = LSEEK(state->fd, 0, SEEK_CUR); - if (state->start == -1) state->start = 0; - } - - /* initialize stream */ - gz_reset(state); - - /* return stream */ - return (gzFile)state; -} - -/* -- see zlib.h -- */ -gzFile ZEXPORT gzopen(path, mode) - const char *path; - const char *mode; -{ - return gz_open(path, -1, mode); -} - -/* -- see zlib.h -- */ -gzFile ZEXPORT gzopen64(path, mode) - const char *path; - const char *mode; -{ - return gz_open(path, -1, mode); -} - -/* -- see zlib.h -- */ -gzFile ZEXPORT gzdopen(fd, mode) - int fd; - const char *mode; -{ - char *path; /* identifier for error messages */ - gzFile gz; - - if (fd == -1 || (path = malloc(7 + 3 * sizeof(int))) == NULL) - return NULL; - sprintf(path, "", fd); /* for debugging */ - gz = gz_open(path, fd, mode); - free(path); - return gz; -} - -/* -- see zlib.h -- */ -int ZEXPORT gzbuffer(file, size) - gzFile file; - unsigned size; -{ - gz_statep state; - - /* get internal structure and check integrity */ - if (file == NULL) - return -1; - state = (gz_statep)file; - if (state->mode != GZ_READ && state->mode != GZ_WRITE) - return -1; - - /* make sure we haven't already allocated memory */ - if (state->size != 0) - return -1; - - /* check and set requested size */ - if (size == 0) - return -1; - state->want = size; - return 0; -} - -/* -- see zlib.h -- */ -int ZEXPORT gzrewind(file) - gzFile file; -{ - gz_statep state; - - /* get internal structure */ - if (file == NULL) - return -1; - state = (gz_statep)file; - - /* check that we're reading and that there's no error */ - if (state->mode != GZ_READ || state->err != Z_OK) - return -1; - - /* back up and start over */ - if (LSEEK(state->fd, state->start, SEEK_SET) == -1) - return -1; - gz_reset(state); - return 0; -} - -/* -- see zlib.h -- */ -z_off64_t ZEXPORT gzseek64(file, offset, whence) - gzFile file; - z_off64_t offset; - int whence; -{ - unsigned n; - z_off64_t ret; - gz_statep state; - - /* get internal structure and check integrity */ - if (file == NULL) - return -1; - state = (gz_statep)file; - if (state->mode != GZ_READ && state->mode != GZ_WRITE) - return -1; - - /* check that there's no error */ - if (state->err != Z_OK) - return -1; - - /* can only seek from start or relative to current position */ - if (whence != SEEK_SET && whence != SEEK_CUR) - return -1; - - /* normalize offset to a SEEK_CUR specification */ - if (whence == SEEK_SET) - offset -= state->pos; - else if (state->seek) - offset += state->skip; - state->seek = 0; - - /* if within raw area while reading, just go there */ - if (state->mode == GZ_READ && state->how == COPY && - state->pos + offset >= state->raw) { - ret = LSEEK(state->fd, offset - state->have, SEEK_CUR); - if (ret == -1) - return -1; - state->have = 0; - state->eof = 0; - state->seek = 0; - gz_error(state, Z_OK, NULL); - state->strm.avail_in = 0; - state->pos += offset; - return state->pos; - } - - /* calculate skip amount, rewinding if needed for back seek when reading */ - if (offset < 0) { - if (state->mode != GZ_READ) /* writing -- can't go backwards */ - return -1; - offset += state->pos; - if (offset < 0) /* before start of file! */ - return -1; - if (gzrewind(file) == -1) /* rewind, then skip to offset */ - return -1; - } - - /* if reading, skip what's in output buffer (one less gzgetc() check) */ - if (state->mode == GZ_READ) { - n = GT_OFF(state->have) || (z_off64_t)state->have > offset ? - (unsigned)offset : state->have; - state->have -= n; - state->next += n; - state->pos += n; - offset -= n; - } - - /* request skip (if not zero) */ - if (offset) { - state->seek = 1; - state->skip = offset; - } - return state->pos + offset; -} - -/* -- see zlib.h -- */ -z_off_t ZEXPORT gzseek(file, offset, whence) - gzFile file; - z_off_t offset; - int whence; -{ - z_off64_t ret; - - ret = gzseek64(file, (z_off64_t)offset, whence); - return ret == (z_off_t)ret ? (z_off_t)ret : -1; -} - -/* -- see zlib.h -- */ -z_off64_t ZEXPORT gztell64(file) - gzFile file; -{ - gz_statep state; - - /* get internal structure and check integrity */ - if (file == NULL) - return -1; - state = (gz_statep)file; - if (state->mode != GZ_READ && state->mode != GZ_WRITE) - return -1; - - /* return position */ - return state->pos + (state->seek ? state->skip : 0); -} - -/* -- see zlib.h -- */ -z_off_t ZEXPORT gztell(file) - gzFile file; -{ - z_off64_t ret; - - ret = gztell64(file); - return ret == (z_off_t)ret ? (z_off_t)ret : -1; -} - -/* -- see zlib.h -- */ -z_off64_t ZEXPORT gzoffset64(file) - gzFile file; -{ - z_off64_t offset; - gz_statep state; - - /* get internal structure and check integrity */ - if (file == NULL) - return -1; - state = (gz_statep)file; - if (state->mode != GZ_READ && state->mode != GZ_WRITE) - return -1; - - /* compute and return effective offset in file */ - offset = LSEEK(state->fd, 0, SEEK_CUR); - if (offset == -1) - return -1; - if (state->mode == GZ_READ) /* reading */ - offset -= state->strm.avail_in; /* don't count buffered input */ - return offset; -} - -/* -- see zlib.h -- */ -z_off_t ZEXPORT gzoffset(file) - gzFile file; -{ - z_off64_t ret; - - ret = gzoffset64(file); - return ret == (z_off_t)ret ? (z_off_t)ret : -1; -} - -/* -- see zlib.h -- */ -int ZEXPORT gzeof(file) - gzFile file; -{ - gz_statep state; - - /* get internal structure and check integrity */ - if (file == NULL) - return 0; - state = (gz_statep)file; - if (state->mode != GZ_READ && state->mode != GZ_WRITE) - return 0; - - /* return end-of-file state */ - return state->mode == GZ_READ ? - (state->eof && state->strm.avail_in == 0 && state->have == 0) : 0; -} - -/* -- see zlib.h -- */ -const char * ZEXPORT gzerror(file, errnum) - gzFile file; - int *errnum; -{ - gz_statep state; - - /* get internal structure and check integrity */ - if (file == NULL) - return NULL; - state = (gz_statep)file; - if (state->mode != GZ_READ && state->mode != GZ_WRITE) - return NULL; - - /* return error information */ - if (errnum != NULL) - *errnum = state->err; - return state->msg == NULL ? "" : state->msg; -} - -/* -- see zlib.h -- */ -void ZEXPORT gzclearerr(file) - gzFile file; -{ - gz_statep state; - - /* get internal structure and check integrity */ - if (file == NULL) - return; - state = (gz_statep)file; - if (state->mode != GZ_READ && state->mode != GZ_WRITE) - return; - - /* clear error and end-of-file */ - if (state->mode == GZ_READ) - state->eof = 0; - gz_error(state, Z_OK, NULL); -} - -/* Create an error message in allocated memory and set state->err and - state->msg accordingly. Free any previous error message already there. Do - not try to free or allocate space if the error is Z_MEM_ERROR (out of - memory). Simply save the error message as a static string. If there is an - allocation failure constructing the error message, then convert the error to - out of memory. */ -void ZLIB_INTERNAL gz_error(state, err, msg) - gz_statep state; - int err; - const char *msg; -{ - /* free previously allocated message and clear */ - if (state->msg != NULL) { - if (state->err != Z_MEM_ERROR) - free(state->msg); - state->msg = NULL; - } - - /* set error code, and if no message, then done */ - state->err = err; - if (msg == NULL) - return; - - /* for an out of memory error, save as static string */ - if (err == Z_MEM_ERROR) { - state->msg = (char *)msg; - return; - } - - /* construct error message with path */ - if ((state->msg = malloc(strlen(state->path) + strlen(msg) + 3)) == NULL) { - state->err = Z_MEM_ERROR; - state->msg = (char *)"out of memory"; - return; - } - strcpy(state->msg, state->path); - strcat(state->msg, ": "); - strcat(state->msg, msg); - return; -} - -#ifndef INT_MAX -/* portably return maximum value for an int (when limits.h presumed not - available) -- we need to do this to cover cases where 2's complement not - used, since C standard permits 1's complement and sign-bit representations, - otherwise we could just use ((unsigned)-1) >> 1 */ -unsigned ZLIB_INTERNAL gz_intmax() -{ - unsigned p, q; - - p = 1; - do { - q = p; - p <<= 1; - p++; - } while (p > q); - return q >> 1; -} -#endif diff --git a/externals/zlib/gzread.c b/externals/zlib/gzread.c deleted file mode 100644 index 548201ab009..00000000000 --- a/externals/zlib/gzread.c +++ /dev/null @@ -1,653 +0,0 @@ -/* gzread.c -- zlib functions for reading gzip files - * Copyright (C) 2004, 2005, 2010 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -#include "gzguts.h" - -/* Local functions */ -local int gz_load OF((gz_statep, unsigned char *, unsigned, unsigned *)); -local int gz_avail OF((gz_statep)); -local int gz_next4 OF((gz_statep, unsigned long *)); -local int gz_head OF((gz_statep)); -local int gz_decomp OF((gz_statep)); -local int gz_make OF((gz_statep)); -local int gz_skip OF((gz_statep, z_off64_t)); - -/* Use read() to load a buffer -- return -1 on error, otherwise 0. Read from - state->fd, and update state->eof, state->err, and state->msg as appropriate. - This function needs to loop on read(), since read() is not guaranteed to - read the number of bytes requested, depending on the type of descriptor. */ -local int gz_load(state, buf, len, have) - gz_statep state; - unsigned char *buf; - unsigned len; - unsigned *have; -{ - int ret; - - *have = 0; - do { - ret = read(state->fd, buf + *have, len - *have); - if (ret <= 0) - break; - *have += ret; - } while (*have < len); - if (ret < 0) { - gz_error(state, Z_ERRNO, zstrerror()); - return -1; - } - if (ret == 0) - state->eof = 1; - return 0; -} - -/* Load up input buffer and set eof flag if last data loaded -- return -1 on - error, 0 otherwise. Note that the eof flag is set when the end of the input - file is reached, even though there may be unused data in the buffer. Once - that data has been used, no more attempts will be made to read the file. - gz_avail() assumes that strm->avail_in == 0. */ -local int gz_avail(state) - gz_statep state; -{ - z_streamp strm = &(state->strm); - - if (state->err != Z_OK) - return -1; - if (state->eof == 0) { - if (gz_load(state, state->in, state->size, - (unsigned *)&(strm->avail_in)) == -1) - return -1; - strm->next_in = state->in; - } - return 0; -} - -/* Get next byte from input, or -1 if end or error. */ -#define NEXT() ((strm->avail_in == 0 && gz_avail(state) == -1) ? -1 : \ - (strm->avail_in == 0 ? -1 : \ - (strm->avail_in--, *(strm->next_in)++))) - -/* Get a four-byte little-endian integer and return 0 on success and the value - in *ret. Otherwise -1 is returned and *ret is not modified. */ -local int gz_next4(state, ret) - gz_statep state; - unsigned long *ret; -{ - int ch; - unsigned long val; - z_streamp strm = &(state->strm); - - val = NEXT(); - val += (unsigned)NEXT() << 8; - val += (unsigned long)NEXT() << 16; - ch = NEXT(); - if (ch == -1) - return -1; - val += (unsigned long)ch << 24; - *ret = val; - return 0; -} - -/* Look for gzip header, set up for inflate or copy. state->have must be zero. - If this is the first time in, allocate required memory. state->how will be - left unchanged if there is no more input data available, will be set to COPY - if there is no gzip header and direct copying will be performed, or it will - be set to GZIP for decompression, and the gzip header will be skipped so - that the next available input data is the raw deflate stream. If direct - copying, then leftover input data from the input buffer will be copied to - the output buffer. In that case, all further file reads will be directly to - either the output buffer or a user buffer. If decompressing, the inflate - state and the check value will be initialized. gz_head() will return 0 on - success or -1 on failure. Failures may include read errors or gzip header - errors. */ -local int gz_head(state) - gz_statep state; -{ - z_streamp strm = &(state->strm); - int flags; - unsigned len; - - /* allocate read buffers and inflate memory */ - if (state->size == 0) { - /* allocate buffers */ - state->in = malloc(state->want); - state->out = malloc(state->want << 1); - if (state->in == NULL || state->out == NULL) { - if (state->out != NULL) - free(state->out); - if (state->in != NULL) - free(state->in); - gz_error(state, Z_MEM_ERROR, "out of memory"); - return -1; - } - state->size = state->want; - - /* allocate inflate memory */ - state->strm.zalloc = Z_NULL; - state->strm.zfree = Z_NULL; - state->strm.opaque = Z_NULL; - state->strm.avail_in = 0; - state->strm.next_in = Z_NULL; - if (inflateInit2(&(state->strm), -15) != Z_OK) { /* raw inflate */ - free(state->out); - free(state->in); - state->size = 0; - gz_error(state, Z_MEM_ERROR, "out of memory"); - return -1; - } - } - - /* get some data in the input buffer */ - if (strm->avail_in == 0) { - if (gz_avail(state) == -1) - return -1; - if (strm->avail_in == 0) - return 0; - } - - /* look for the gzip magic header bytes 31 and 139 */ - if (strm->next_in[0] == 31) { - strm->avail_in--; - strm->next_in++; - if (strm->avail_in == 0 && gz_avail(state) == -1) - return -1; - if (strm->avail_in && strm->next_in[0] == 139) { - /* we have a gzip header, woo hoo! */ - strm->avail_in--; - strm->next_in++; - - /* skip rest of header */ - if (NEXT() != 8) { /* compression method */ - gz_error(state, Z_DATA_ERROR, "unknown compression method"); - return -1; - } - flags = NEXT(); - if (flags & 0xe0) { /* reserved flag bits */ - gz_error(state, Z_DATA_ERROR, "unknown header flags set"); - return -1; - } - NEXT(); /* modification time */ - NEXT(); - NEXT(); - NEXT(); - NEXT(); /* extra flags */ - NEXT(); /* operating system */ - if (flags & 4) { /* extra field */ - len = (unsigned)NEXT(); - len += (unsigned)NEXT() << 8; - while (len--) - if (NEXT() < 0) - break; - } - if (flags & 8) /* file name */ - while (NEXT() > 0) - ; - if (flags & 16) /* comment */ - while (NEXT() > 0) - ; - if (flags & 2) { /* header crc */ - NEXT(); - NEXT(); - } - /* an unexpected end of file is not checked for here -- it will be - noticed on the first request for uncompressed data */ - - /* set up for decompression */ - inflateReset(strm); - strm->adler = crc32(0L, Z_NULL, 0); - state->how = GZIP; - state->direct = 0; - return 0; - } - else { - /* not a gzip file -- save first byte (31) and fall to raw i/o */ - state->out[0] = 31; - state->have = 1; - } - } - - /* doing raw i/o, save start of raw data for seeking, copy any leftover - input to output -- this assumes that the output buffer is larger than - the input buffer, which also assures space for gzungetc() */ - state->raw = state->pos; - state->next = state->out; - if (strm->avail_in) { - memcpy(state->next + state->have, strm->next_in, strm->avail_in); - state->have += strm->avail_in; - strm->avail_in = 0; - } - state->how = COPY; - state->direct = 1; - return 0; -} - -/* Decompress from input to the provided next_out and avail_out in the state. - If the end of the compressed data is reached, then verify the gzip trailer - check value and length (modulo 2^32). state->have and state->next are set - to point to the just decompressed data, and the crc is updated. If the - trailer is verified, state->how is reset to LOOK to look for the next gzip - stream or raw data, once state->have is depleted. Returns 0 on success, -1 - on failure. Failures may include invalid compressed data or a failed gzip - trailer verification. */ -local int gz_decomp(state) - gz_statep state; -{ - int ret; - unsigned had; - unsigned long crc, len; - z_streamp strm = &(state->strm); - - /* fill output buffer up to end of deflate stream */ - had = strm->avail_out; - do { - /* get more input for inflate() */ - if (strm->avail_in == 0 && gz_avail(state) == -1) - return -1; - if (strm->avail_in == 0) { - gz_error(state, Z_DATA_ERROR, "unexpected end of file"); - return -1; - } - - /* decompress and handle errors */ - ret = inflate(strm, Z_NO_FLUSH); - if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT) { - gz_error(state, Z_STREAM_ERROR, - "internal error: inflate stream corrupt"); - return -1; - } - if (ret == Z_MEM_ERROR) { - gz_error(state, Z_MEM_ERROR, "out of memory"); - return -1; - } - if (ret == Z_DATA_ERROR) { /* deflate stream invalid */ - gz_error(state, Z_DATA_ERROR, - strm->msg == NULL ? "compressed data error" : strm->msg); - return -1; - } - } while (strm->avail_out && ret != Z_STREAM_END); - - /* update available output and crc check value */ - state->have = had - strm->avail_out; - state->next = strm->next_out - state->have; - strm->adler = crc32(strm->adler, state->next, state->have); - - /* check gzip trailer if at end of deflate stream */ - if (ret == Z_STREAM_END) { - if (gz_next4(state, &crc) == -1 || gz_next4(state, &len) == -1) { - gz_error(state, Z_DATA_ERROR, "unexpected end of file"); - return -1; - } - if (crc != strm->adler) { - gz_error(state, Z_DATA_ERROR, "incorrect data check"); - return -1; - } - if (len != (strm->total_out & 0xffffffffL)) { - gz_error(state, Z_DATA_ERROR, "incorrect length check"); - return -1; - } - state->how = LOOK; /* ready for next stream, once have is 0 (leave - state->direct unchanged to remember how) */ - } - - /* good decompression */ - return 0; -} - -/* Make data and put in the output buffer. Assumes that state->have == 0. - Data is either copied from the input file or decompressed from the input - file depending on state->how. If state->how is LOOK, then a gzip header is - looked for (and skipped if found) to determine wither to copy or decompress. - Returns -1 on error, otherwise 0. gz_make() will leave state->have as COPY - or GZIP unless the end of the input file has been reached and all data has - been processed. */ -local int gz_make(state) - gz_statep state; -{ - z_streamp strm = &(state->strm); - - if (state->how == LOOK) { /* look for gzip header */ - if (gz_head(state) == -1) - return -1; - if (state->have) /* got some data from gz_head() */ - return 0; - } - if (state->how == COPY) { /* straight copy */ - if (gz_load(state, state->out, state->size << 1, &(state->have)) == -1) - return -1; - state->next = state->out; - } - else if (state->how == GZIP) { /* decompress */ - strm->avail_out = state->size << 1; - strm->next_out = state->out; - if (gz_decomp(state) == -1) - return -1; - } - return 0; -} - -/* Skip len uncompressed bytes of output. Return -1 on error, 0 on success. */ -local int gz_skip(state, len) - gz_statep state; - z_off64_t len; -{ - unsigned n; - - /* skip over len bytes or reach end-of-file, whichever comes first */ - while (len) - /* skip over whatever is in output buffer */ - if (state->have) { - n = GT_OFF(state->have) || (z_off64_t)state->have > len ? - (unsigned)len : state->have; - state->have -= n; - state->next += n; - state->pos += n; - len -= n; - } - - /* output buffer empty -- return if we're at the end of the input */ - else if (state->eof && state->strm.avail_in == 0) - break; - - /* need more data to skip -- load up output buffer */ - else { - /* get more output, looking for header if required */ - if (gz_make(state) == -1) - return -1; - } - return 0; -} - -/* -- see zlib.h -- */ -int ZEXPORT gzread(file, buf, len) - gzFile file; - voidp buf; - unsigned len; -{ - unsigned got, n; - gz_statep state; - z_streamp strm; - - /* get internal structure */ - if (file == NULL) - return -1; - state = (gz_statep)file; - strm = &(state->strm); - - /* check that we're reading and that there's no error */ - if (state->mode != GZ_READ || state->err != Z_OK) - return -1; - - /* since an int is returned, make sure len fits in one, otherwise return - with an error (this avoids the flaw in the interface) */ - if ((int)len < 0) { - gz_error(state, Z_BUF_ERROR, "requested length does not fit in int"); - return -1; - } - - /* if len is zero, avoid unnecessary operations */ - if (len == 0) - return 0; - - /* process a skip request */ - if (state->seek) { - state->seek = 0; - if (gz_skip(state, state->skip) == -1) - return -1; - } - - /* get len bytes to buf, or less than len if at the end */ - got = 0; - do { - /* first just try copying data from the output buffer */ - if (state->have) { - n = state->have > len ? len : state->have; - memcpy(buf, state->next, n); - state->next += n; - state->have -= n; - } - - /* output buffer empty -- return if we're at the end of the input */ - else if (state->eof && strm->avail_in == 0) - break; - - /* need output data -- for small len or new stream load up our output - buffer */ - else if (state->how == LOOK || len < (state->size << 1)) { - /* get more output, looking for header if required */ - if (gz_make(state) == -1) - return -1; - continue; /* no progress yet -- go back to memcpy() above */ - /* the copy above assures that we will leave with space in the - output buffer, allowing at least one gzungetc() to succeed */ - } - - /* large len -- read directly into user buffer */ - else if (state->how == COPY) { /* read directly */ - if (gz_load(state, buf, len, &n) == -1) - return -1; - } - - /* large len -- decompress directly into user buffer */ - else { /* state->how == GZIP */ - strm->avail_out = len; - strm->next_out = buf; - if (gz_decomp(state) == -1) - return -1; - n = state->have; - state->have = 0; - } - - /* update progress */ - len -= n; - buf = (char *)buf + n; - got += n; - state->pos += n; - } while (len); - - /* return number of bytes read into user buffer (will fit in int) */ - return (int)got; -} - -/* -- see zlib.h -- */ -int ZEXPORT gzgetc(file) - gzFile file; -{ - int ret; - unsigned char buf[1]; - gz_statep state; - - /* get internal structure */ - if (file == NULL) - return -1; - state = (gz_statep)file; - - /* check that we're reading and that there's no error */ - if (state->mode != GZ_READ || state->err != Z_OK) - return -1; - - /* try output buffer (no need to check for skip request) */ - if (state->have) { - state->have--; - state->pos++; - return *(state->next)++; - } - - /* nothing there -- try gzread() */ - ret = gzread(file, buf, 1); - return ret < 1 ? -1 : buf[0]; -} - -/* -- see zlib.h -- */ -int ZEXPORT gzungetc(c, file) - int c; - gzFile file; -{ - gz_statep state; - - /* get internal structure */ - if (file == NULL) - return -1; - state = (gz_statep)file; - - /* check that we're reading and that there's no error */ - if (state->mode != GZ_READ || state->err != Z_OK) - return -1; - - /* process a skip request */ - if (state->seek) { - state->seek = 0; - if (gz_skip(state, state->skip) == -1) - return -1; - } - - /* can't push EOF */ - if (c < 0) - return -1; - - /* if output buffer empty, put byte at end (allows more pushing) */ - if (state->have == 0) { - state->have = 1; - state->next = state->out + (state->size << 1) - 1; - state->next[0] = c; - state->pos--; - return c; - } - - /* if no room, give up (must have already done a gzungetc()) */ - if (state->have == (state->size << 1)) { - gz_error(state, Z_BUF_ERROR, "out of room to push characters"); - return -1; - } - - /* slide output data if needed and insert byte before existing data */ - if (state->next == state->out) { - unsigned char *src = state->out + state->have; - unsigned char *dest = state->out + (state->size << 1); - while (src > state->out) - *--dest = *--src; - state->next = dest; - } - state->have++; - state->next--; - state->next[0] = c; - state->pos--; - return c; -} - -/* -- see zlib.h -- */ -char * ZEXPORT gzgets(file, buf, len) - gzFile file; - char *buf; - int len; -{ - unsigned left, n; - char *str; - unsigned char *eol; - gz_statep state; - - /* check parameters and get internal structure */ - if (file == NULL || buf == NULL || len < 1) - return NULL; - state = (gz_statep)file; - - /* check that we're reading and that there's no error */ - if (state->mode != GZ_READ || state->err != Z_OK) - return NULL; - - /* process a skip request */ - if (state->seek) { - state->seek = 0; - if (gz_skip(state, state->skip) == -1) - return NULL; - } - - /* copy output bytes up to new line or len - 1, whichever comes first -- - append a terminating zero to the string (we don't check for a zero in - the contents, let the user worry about that) */ - str = buf; - left = (unsigned)len - 1; - if (left) do { - /* assure that something is in the output buffer */ - if (state->have == 0) { - if (gz_make(state) == -1) - return NULL; /* error */ - if (state->have == 0) { /* end of file */ - if (buf == str) /* got bupkus */ - return NULL; - break; /* got something -- return it */ - } - } - - /* look for end-of-line in current output buffer */ - n = state->have > left ? left : state->have; - eol = memchr(state->next, '\n', n); - if (eol != NULL) - n = (unsigned)(eol - state->next) + 1; - - /* copy through end-of-line, or remainder if not found */ - memcpy(buf, state->next, n); - state->have -= n; - state->next += n; - state->pos += n; - left -= n; - buf += n; - } while (left && eol == NULL); - - /* found end-of-line or out of space -- terminate string and return it */ - buf[0] = 0; - return str; -} - -/* -- see zlib.h -- */ -int ZEXPORT gzdirect(file) - gzFile file; -{ - gz_statep state; - - /* get internal structure */ - if (file == NULL) - return 0; - state = (gz_statep)file; - - /* check that we're reading */ - if (state->mode != GZ_READ) - return 0; - - /* if the state is not known, but we can find out, then do so (this is - mainly for right after a gzopen() or gzdopen()) */ - if (state->how == LOOK && state->have == 0) - (void)gz_head(state); - - /* return 1 if reading direct, 0 if decompressing a gzip stream */ - return state->direct; -} - -/* -- see zlib.h -- */ -int ZEXPORT gzclose_r(file) - gzFile file; -{ - int ret; - gz_statep state; - - /* get internal structure */ - if (file == NULL) - return Z_STREAM_ERROR; - state = (gz_statep)file; - - /* check that we're reading */ - if (state->mode != GZ_READ) - return Z_STREAM_ERROR; - - /* free memory and close file */ - if (state->size) { - inflateEnd(&(state->strm)); - free(state->out); - free(state->in); - } - gz_error(state, Z_OK, NULL); - free(state->path); - ret = close(state->fd); - free(state); - return ret ? Z_ERRNO : Z_OK; -} diff --git a/externals/zlib/gzwrite.c b/externals/zlib/gzwrite.c deleted file mode 100644 index e8defc6887a..00000000000 --- a/externals/zlib/gzwrite.c +++ /dev/null @@ -1,531 +0,0 @@ -/* gzwrite.c -- zlib functions for writing gzip files - * Copyright (C) 2004, 2005, 2010 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -#include "gzguts.h" - -/* Local functions */ -local int gz_init OF((gz_statep)); -local int gz_comp OF((gz_statep, int)); -local int gz_zero OF((gz_statep, z_off64_t)); - -/* Initialize state for writing a gzip file. Mark initialization by setting - state->size to non-zero. Return -1 on failure or 0 on success. */ -local int gz_init(state) - gz_statep state; -{ - int ret; - z_streamp strm = &(state->strm); - - /* allocate input and output buffers */ - state->in = malloc(state->want); - state->out = malloc(state->want); - if (state->in == NULL || state->out == NULL) { - if (state->out != NULL) - free(state->out); - if (state->in != NULL) - free(state->in); - gz_error(state, Z_MEM_ERROR, "out of memory"); - return -1; - } - - /* allocate deflate memory, set up for gzip compression */ - strm->zalloc = Z_NULL; - strm->zfree = Z_NULL; - strm->opaque = Z_NULL; - ret = deflateInit2(strm, state->level, Z_DEFLATED, - 15 + 16, 8, state->strategy); - if (ret != Z_OK) { - free(state->in); - gz_error(state, Z_MEM_ERROR, "out of memory"); - return -1; - } - - /* mark state as initialized */ - state->size = state->want; - - /* initialize write buffer */ - strm->avail_out = state->size; - strm->next_out = state->out; - state->next = strm->next_out; - return 0; -} - -/* Compress whatever is at avail_in and next_in and write to the output file. - Return -1 if there is an error writing to the output file, otherwise 0. - flush is assumed to be a valid deflate() flush value. If flush is Z_FINISH, - then the deflate() state is reset to start a new gzip stream. */ -local int gz_comp(state, flush) - gz_statep state; - int flush; -{ - int ret, got; - unsigned have; - z_streamp strm = &(state->strm); - - /* allocate memory if this is the first time through */ - if (state->size == 0 && gz_init(state) == -1) - return -1; - - /* run deflate() on provided input until it produces no more output */ - ret = Z_OK; - do { - /* write out current buffer contents if full, or if flushing, but if - doing Z_FINISH then don't write until we get to Z_STREAM_END */ - if (strm->avail_out == 0 || (flush != Z_NO_FLUSH && - (flush != Z_FINISH || ret == Z_STREAM_END))) { - have = (unsigned)(strm->next_out - state->next); - if (have && ((got = write(state->fd, state->next, have)) < 0 || - (unsigned)got != have)) { - gz_error(state, Z_ERRNO, zstrerror()); - return -1; - } - if (strm->avail_out == 0) { - strm->avail_out = state->size; - strm->next_out = state->out; - } - state->next = strm->next_out; - } - - /* compress */ - have = strm->avail_out; - ret = deflate(strm, flush); - if (ret == Z_STREAM_ERROR) { - gz_error(state, Z_STREAM_ERROR, - "internal error: deflate stream corrupt"); - return -1; - } - have -= strm->avail_out; - } while (have); - - /* if that completed a deflate stream, allow another to start */ - if (flush == Z_FINISH) - deflateReset(strm); - - /* all done, no errors */ - return 0; -} - -/* Compress len zeros to output. Return -1 on error, 0 on success. */ -local int gz_zero(state, len) - gz_statep state; - z_off64_t len; -{ - int first; - unsigned n; - z_streamp strm = &(state->strm); - - /* consume whatever's left in the input buffer */ - if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1) - return -1; - - /* compress len zeros (len guaranteed > 0) */ - first = 1; - while (len) { - n = GT_OFF(state->size) || (z_off64_t)state->size > len ? - (unsigned)len : state->size; - if (first) { - memset(state->in, 0, n); - first = 0; - } - strm->avail_in = n; - strm->next_in = state->in; - state->pos += n; - if (gz_comp(state, Z_NO_FLUSH) == -1) - return -1; - len -= n; - } - return 0; -} - -/* -- see zlib.h -- */ -int ZEXPORT gzwrite(file, buf, len) - gzFile file; - voidpc buf; - unsigned len; -{ - unsigned put = len; - unsigned n; - gz_statep state; - z_streamp strm; - - /* get internal structure */ - if (file == NULL) - return 0; - state = (gz_statep)file; - strm = &(state->strm); - - /* check that we're writing and that there's no error */ - if (state->mode != GZ_WRITE || state->err != Z_OK) - return 0; - - /* since an int is returned, make sure len fits in one, otherwise return - with an error (this avoids the flaw in the interface) */ - if ((int)len < 0) { - gz_error(state, Z_BUF_ERROR, "requested length does not fit in int"); - return 0; - } - - /* if len is zero, avoid unnecessary operations */ - if (len == 0) - return 0; - - /* allocate memory if this is the first time through */ - if (state->size == 0 && gz_init(state) == -1) - return 0; - - /* check for seek request */ - if (state->seek) { - state->seek = 0; - if (gz_zero(state, state->skip) == -1) - return 0; - } - - /* for small len, copy to input buffer, otherwise compress directly */ - if (len < state->size) { - /* copy to input buffer, compress when full */ - do { - if (strm->avail_in == 0) - strm->next_in = state->in; - n = state->size - strm->avail_in; - if (n > len) - n = len; - memcpy(strm->next_in + strm->avail_in, buf, n); - strm->avail_in += n; - state->pos += n; - buf = (char *)buf + n; - len -= n; - if (len && gz_comp(state, Z_NO_FLUSH) == -1) - return 0; - } while (len); - } - else { - /* consume whatever's left in the input buffer */ - if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1) - return 0; - - /* directly compress user buffer to file */ - strm->avail_in = len; - strm->next_in = (voidp)buf; - state->pos += len; - if (gz_comp(state, Z_NO_FLUSH) == -1) - return 0; - } - - /* input was all buffered or compressed (put will fit in int) */ - return (int)put; -} - -/* -- see zlib.h -- */ -int ZEXPORT gzputc(file, c) - gzFile file; - int c; -{ - unsigned char buf[1]; - gz_statep state; - z_streamp strm; - - /* get internal structure */ - if (file == NULL) - return -1; - state = (gz_statep)file; - strm = &(state->strm); - - /* check that we're writing and that there's no error */ - if (state->mode != GZ_WRITE || state->err != Z_OK) - return -1; - - /* check for seek request */ - if (state->seek) { - state->seek = 0; - if (gz_zero(state, state->skip) == -1) - return -1; - } - - /* try writing to input buffer for speed (state->size == 0 if buffer not - initialized) */ - if (strm->avail_in < state->size) { - if (strm->avail_in == 0) - strm->next_in = state->in; - strm->next_in[strm->avail_in++] = c; - state->pos++; - return c; - } - - /* no room in buffer or not initialized, use gz_write() */ - buf[0] = c; - if (gzwrite(file, buf, 1) != 1) - return -1; - return c; -} - -/* -- see zlib.h -- */ -int ZEXPORT gzputs(file, str) - gzFile file; - const char *str; -{ - int ret; - unsigned len; - - /* write string */ - len = (unsigned)strlen(str); - ret = gzwrite(file, str, len); - return ret == 0 && len != 0 ? -1 : ret; -} - -#ifdef STDC -#include - -/* -- see zlib.h -- */ -int ZEXPORTVA gzprintf (gzFile file, const char *format, ...) -{ - int size, len; - gz_statep state; - z_streamp strm; - va_list va; - - /* get internal structure */ - if (file == NULL) - return -1; - state = (gz_statep)file; - strm = &(state->strm); - - /* check that we're writing and that there's no error */ - if (state->mode != GZ_WRITE || state->err != Z_OK) - return 0; - - /* make sure we have some buffer space */ - if (state->size == 0 && gz_init(state) == -1) - return 0; - - /* check for seek request */ - if (state->seek) { - state->seek = 0; - if (gz_zero(state, state->skip) == -1) - return 0; - } - - /* consume whatever's left in the input buffer */ - if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1) - return 0; - - /* do the printf() into the input buffer, put length in len */ - size = (int)(state->size); - state->in[size - 1] = 0; - va_start(va, format); -#ifdef NO_vsnprintf -# ifdef HAS_vsprintf_void - (void)vsprintf(state->in, format, va); - va_end(va); - for (len = 0; len < size; len++) - if (state->in[len] == 0) break; -# else - len = vsprintf(state->in, format, va); - va_end(va); -# endif -#else -# ifdef HAS_vsnprintf_void - (void)vsnprintf(state->in, size, format, va); - va_end(va); - len = strlen(state->in); -# else - len = vsnprintf((char *)(state->in), size, format, va); - va_end(va); -# endif -#endif - - /* check that printf() results fit in buffer */ - if (len <= 0 || len >= (int)size || state->in[size - 1] != 0) - return 0; - - /* update buffer and position, defer compression until needed */ - strm->avail_in = (unsigned)len; - strm->next_in = state->in; - state->pos += len; - return len; -} - -#else /* !STDC */ - -/* -- see zlib.h -- */ -int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, - a11, a12, a13, a14, a15, a16, a17, a18, a19, a20) - gzFile file; - const char *format; - int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, - a11, a12, a13, a14, a15, a16, a17, a18, a19, a20; -{ - int size, len; - gz_statep state; - z_streamp strm; - - /* get internal structure */ - if (file == NULL) - return -1; - state = (gz_statep)file; - strm = &(state->strm); - - /* check that we're writing and that there's no error */ - if (state->mode != GZ_WRITE || state->err != Z_OK) - return 0; - - /* make sure we have some buffer space */ - if (state->size == 0 && gz_init(state) == -1) - return 0; - - /* check for seek request */ - if (state->seek) { - state->seek = 0; - if (gz_zero(state, state->skip) == -1) - return 0; - } - - /* consume whatever's left in the input buffer */ - if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1) - return 0; - - /* do the printf() into the input buffer, put length in len */ - size = (int)(state->size); - state->in[size - 1] = 0; -#ifdef NO_snprintf -# ifdef HAS_sprintf_void - sprintf(state->in, format, a1, a2, a3, a4, a5, a6, a7, a8, - a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); - for (len = 0; len < size; len++) - if (state->in[len] == 0) break; -# else - len = sprintf(state->in, format, a1, a2, a3, a4, a5, a6, a7, a8, - a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); -# endif -#else -# ifdef HAS_snprintf_void - snprintf(state->in, size, format, a1, a2, a3, a4, a5, a6, a7, a8, - a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); - len = strlen(state->in); -# else - len = snprintf(state->in, size, format, a1, a2, a3, a4, a5, a6, a7, a8, - a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); -# endif -#endif - - /* check that printf() results fit in buffer */ - if (len <= 0 || len >= (int)size || state->in[size - 1] != 0) - return 0; - - /* update buffer and position, defer compression until needed */ - strm->avail_in = (unsigned)len; - strm->next_in = state->in; - state->pos += len; - return len; -} - -#endif - -/* -- see zlib.h -- */ -int ZEXPORT gzflush(file, flush) - gzFile file; - int flush; -{ - gz_statep state; - - /* get internal structure */ - if (file == NULL) - return -1; - state = (gz_statep)file; - - /* check that we're writing and that there's no error */ - if (state->mode != GZ_WRITE || state->err != Z_OK) - return Z_STREAM_ERROR; - - /* check flush parameter */ - if (flush < 0 || flush > Z_FINISH) - return Z_STREAM_ERROR; - - /* check for seek request */ - if (state->seek) { - state->seek = 0; - if (gz_zero(state, state->skip) == -1) - return -1; - } - - /* compress remaining data with requested flush */ - gz_comp(state, flush); - return state->err; -} - -/* -- see zlib.h -- */ -int ZEXPORT gzsetparams(file, level, strategy) - gzFile file; - int level; - int strategy; -{ - gz_statep state; - z_streamp strm; - - /* get internal structure */ - if (file == NULL) - return Z_STREAM_ERROR; - state = (gz_statep)file; - strm = &(state->strm); - - /* check that we're writing and that there's no error */ - if (state->mode != GZ_WRITE || state->err != Z_OK) - return Z_STREAM_ERROR; - - /* if no change is requested, then do nothing */ - if (level == state->level && strategy == state->strategy) - return Z_OK; - - /* check for seek request */ - if (state->seek) { - state->seek = 0; - if (gz_zero(state, state->skip) == -1) - return -1; - } - - /* change compression parameters for subsequent input */ - if (state->size) { - /* flush previous input with previous parameters before changing */ - if (strm->avail_in && gz_comp(state, Z_PARTIAL_FLUSH) == -1) - return state->err; - deflateParams(strm, level, strategy); - } - state->level = level; - state->strategy = strategy; - return Z_OK; -} - -/* -- see zlib.h -- */ -int ZEXPORT gzclose_w(file) - gzFile file; -{ - int ret = 0; - gz_statep state; - - /* get internal structure */ - if (file == NULL) - return Z_STREAM_ERROR; - state = (gz_statep)file; - - /* check that we're writing */ - if (state->mode != GZ_WRITE) - return Z_STREAM_ERROR; - - /* check for seek request */ - if (state->seek) { - state->seek = 0; - ret += gz_zero(state, state->skip); - } - - /* flush, free memory, and close file */ - ret += gz_comp(state, Z_FINISH); - (void)deflateEnd(&(state->strm)); - free(state->out); - free(state->in); - gz_error(state, Z_OK, NULL); - free(state->path); - ret += close(state->fd); - free(state); - return ret ? Z_ERRNO : Z_OK; -} diff --git a/externals/zlib/infback.c b/externals/zlib/infback.c deleted file mode 100644 index af3a8c965d5..00000000000 --- a/externals/zlib/infback.c +++ /dev/null @@ -1,632 +0,0 @@ -/* infback.c -- inflate using a call-back interface - * Copyright (C) 1995-2009 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* - This code is largely copied from inflate.c. Normally either infback.o or - inflate.o would be linked into an application--not both. The interface - with inffast.c is retained so that optimized assembler-coded versions of - inflate_fast() can be used with either inflate.c or infback.c. - */ - -#include "zutil.h" -#include "inftrees.h" -#include "inflate.h" -#include "inffast.h" - -/* function prototypes */ -local void fixedtables OF((struct inflate_state FAR *state)); - -/* - strm provides memory allocation functions in zalloc and zfree, or - Z_NULL to use the library memory allocation functions. - - windowBits is in the range 8..15, and window is a user-supplied - window and output buffer that is 2**windowBits bytes. - */ -int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size) -z_streamp strm; -int windowBits; -unsigned char FAR *window; -const char *version; -int stream_size; -{ - struct inflate_state FAR *state; - - if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || - stream_size != (int)(sizeof(z_stream))) - return Z_VERSION_ERROR; - if (strm == Z_NULL || window == Z_NULL || - windowBits < 8 || windowBits > 15) - return Z_STREAM_ERROR; - strm->msg = Z_NULL; /* in case we return an error */ - if (strm->zalloc == (alloc_func)0) { - strm->zalloc = zcalloc; - strm->opaque = (voidpf)0; - } - if (strm->zfree == (free_func)0) strm->zfree = zcfree; - state = (struct inflate_state FAR *)ZALLOC(strm, 1, - sizeof(struct inflate_state)); - if (state == Z_NULL) return Z_MEM_ERROR; - Tracev((stderr, "inflate: allocated\n")); - strm->state = (struct internal_state FAR *)state; - state->dmax = 32768U; - state->wbits = windowBits; - state->wsize = 1U << windowBits; - state->window = window; - state->wnext = 0; - state->whave = 0; - return Z_OK; -} - -/* - Return state with length and distance decoding tables and index sizes set to - fixed code decoding. Normally this returns fixed tables from inffixed.h. - If BUILDFIXED is defined, then instead this routine builds the tables the - first time it's called, and returns those tables the first time and - thereafter. This reduces the size of the code by about 2K bytes, in - exchange for a little execution time. However, BUILDFIXED should not be - used for threaded applications, since the rewriting of the tables and virgin - may not be thread-safe. - */ -local void fixedtables(state) -struct inflate_state FAR *state; -{ -#ifdef BUILDFIXED - static int virgin = 1; - static code *lenfix, *distfix; - static code fixed[544]; - - /* build fixed huffman tables if first call (may not be thread safe) */ - if (virgin) { - unsigned sym, bits; - static code *next; - - /* literal/length table */ - sym = 0; - while (sym < 144) state->lens[sym++] = 8; - while (sym < 256) state->lens[sym++] = 9; - while (sym < 280) state->lens[sym++] = 7; - while (sym < 288) state->lens[sym++] = 8; - next = fixed; - lenfix = next; - bits = 9; - inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); - - /* distance table */ - sym = 0; - while (sym < 32) state->lens[sym++] = 5; - distfix = next; - bits = 5; - inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); - - /* do this just once */ - virgin = 0; - } -#else /* !BUILDFIXED */ -# include "inffixed.h" -#endif /* BUILDFIXED */ - state->lencode = lenfix; - state->lenbits = 9; - state->distcode = distfix; - state->distbits = 5; -} - -/* Macros for inflateBack(): */ - -/* Load returned state from inflate_fast() */ -#define LOAD() \ - do { \ - put = strm->next_out; \ - left = strm->avail_out; \ - next = strm->next_in; \ - have = strm->avail_in; \ - hold = state->hold; \ - bits = state->bits; \ - } while (0) - -/* Set state from registers for inflate_fast() */ -#define RESTORE() \ - do { \ - strm->next_out = put; \ - strm->avail_out = left; \ - strm->next_in = next; \ - strm->avail_in = have; \ - state->hold = hold; \ - state->bits = bits; \ - } while (0) - -/* Clear the input bit accumulator */ -#define INITBITS() \ - do { \ - hold = 0; \ - bits = 0; \ - } while (0) - -/* Assure that some input is available. If input is requested, but denied, - then return a Z_BUF_ERROR from inflateBack(). */ -#define PULL() \ - do { \ - if (have == 0) { \ - have = in(in_desc, &next); \ - if (have == 0) { \ - next = Z_NULL; \ - ret = Z_BUF_ERROR; \ - goto inf_leave; \ - } \ - } \ - } while (0) - -/* Get a byte of input into the bit accumulator, or return from inflateBack() - with an error if there is no input available. */ -#define PULLBYTE() \ - do { \ - PULL(); \ - have--; \ - hold += (unsigned long)(*next++) << bits; \ - bits += 8; \ - } while (0) - -/* Assure that there are at least n bits in the bit accumulator. If there is - not enough available input to do that, then return from inflateBack() with - an error. */ -#define NEEDBITS(n) \ - do { \ - while (bits < (unsigned)(n)) \ - PULLBYTE(); \ - } while (0) - -/* Return the low n bits of the bit accumulator (n < 16) */ -#define BITS(n) \ - ((unsigned)hold & ((1U << (n)) - 1)) - -/* Remove n bits from the bit accumulator */ -#define DROPBITS(n) \ - do { \ - hold >>= (n); \ - bits -= (unsigned)(n); \ - } while (0) - -/* Remove zero to seven bits as needed to go to a byte boundary */ -#define BYTEBITS() \ - do { \ - hold >>= bits & 7; \ - bits -= bits & 7; \ - } while (0) - -/* Assure that some output space is available, by writing out the window - if it's full. If the write fails, return from inflateBack() with a - Z_BUF_ERROR. */ -#define ROOM() \ - do { \ - if (left == 0) { \ - put = state->window; \ - left = state->wsize; \ - state->whave = left; \ - if (out(out_desc, put, left)) { \ - ret = Z_BUF_ERROR; \ - goto inf_leave; \ - } \ - } \ - } while (0) - -/* - strm provides the memory allocation functions and window buffer on input, - and provides information on the unused input on return. For Z_DATA_ERROR - returns, strm will also provide an error message. - - in() and out() are the call-back input and output functions. When - inflateBack() needs more input, it calls in(). When inflateBack() has - filled the window with output, or when it completes with data in the - window, it calls out() to write out the data. The application must not - change the provided input until in() is called again or inflateBack() - returns. The application must not change the window/output buffer until - inflateBack() returns. - - in() and out() are called with a descriptor parameter provided in the - inflateBack() call. This parameter can be a structure that provides the - information required to do the read or write, as well as accumulated - information on the input and output such as totals and check values. - - in() should return zero on failure. out() should return non-zero on - failure. If either in() or out() fails, than inflateBack() returns a - Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it - was in() or out() that caused in the error. Otherwise, inflateBack() - returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format - error, or Z_MEM_ERROR if it could not allocate memory for the state. - inflateBack() can also return Z_STREAM_ERROR if the input parameters - are not correct, i.e. strm is Z_NULL or the state was not initialized. - */ -int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc) -z_streamp strm; -in_func in; -void FAR *in_desc; -out_func out; -void FAR *out_desc; -{ - struct inflate_state FAR *state; - unsigned char FAR *next; /* next input */ - unsigned char FAR *put; /* next output */ - unsigned have, left; /* available input and output */ - unsigned long hold; /* bit buffer */ - unsigned bits; /* bits in bit buffer */ - unsigned copy; /* number of stored or match bytes to copy */ - unsigned char FAR *from; /* where to copy match bytes from */ - code here; /* current decoding table entry */ - code last; /* parent table entry */ - unsigned len; /* length to copy for repeats, bits to drop */ - int ret; /* return code */ - static const unsigned short order[19] = /* permutation of code lengths */ - {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; - - /* Check that the strm exists and that the state was initialized */ - if (strm == Z_NULL || strm->state == Z_NULL) - return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - - /* Reset the state */ - strm->msg = Z_NULL; - state->mode = TYPE; - state->last = 0; - state->whave = 0; - next = strm->next_in; - have = next != Z_NULL ? strm->avail_in : 0; - hold = 0; - bits = 0; - put = state->window; - left = state->wsize; - - /* Inflate until end of block marked as last */ - for (;;) - switch (state->mode) { - case TYPE: - /* determine and dispatch block type */ - if (state->last) { - BYTEBITS(); - state->mode = DONE; - break; - } - NEEDBITS(3); - state->last = BITS(1); - DROPBITS(1); - switch (BITS(2)) { - case 0: /* stored block */ - Tracev((stderr, "inflate: stored block%s\n", - state->last ? " (last)" : "")); - state->mode = STORED; - break; - case 1: /* fixed block */ - fixedtables(state); - Tracev((stderr, "inflate: fixed codes block%s\n", - state->last ? " (last)" : "")); - state->mode = LEN; /* decode codes */ - break; - case 2: /* dynamic block */ - Tracev((stderr, "inflate: dynamic codes block%s\n", - state->last ? " (last)" : "")); - state->mode = TABLE; - break; - case 3: - strm->msg = (char *)"invalid block type"; - state->mode = BAD; - } - DROPBITS(2); - break; - - case STORED: - /* get and verify stored block length */ - BYTEBITS(); /* go to byte boundary */ - NEEDBITS(32); - if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { - strm->msg = (char *)"invalid stored block lengths"; - state->mode = BAD; - break; - } - state->length = (unsigned)hold & 0xffff; - Tracev((stderr, "inflate: stored length %u\n", - state->length)); - INITBITS(); - - /* copy stored block from input to output */ - while (state->length != 0) { - copy = state->length; - PULL(); - ROOM(); - if (copy > have) copy = have; - if (copy > left) copy = left; - zmemcpy(put, next, copy); - have -= copy; - next += copy; - left -= copy; - put += copy; - state->length -= copy; - } - Tracev((stderr, "inflate: stored end\n")); - state->mode = TYPE; - break; - - case TABLE: - /* get dynamic table entries descriptor */ - NEEDBITS(14); - state->nlen = BITS(5) + 257; - DROPBITS(5); - state->ndist = BITS(5) + 1; - DROPBITS(5); - state->ncode = BITS(4) + 4; - DROPBITS(4); -#ifndef PKZIP_BUG_WORKAROUND - if (state->nlen > 286 || state->ndist > 30) { - strm->msg = (char *)"too many length or distance symbols"; - state->mode = BAD; - break; - } -#endif - Tracev((stderr, "inflate: table sizes ok\n")); - - /* get code length code lengths (not a typo) */ - state->have = 0; - while (state->have < state->ncode) { - NEEDBITS(3); - state->lens[order[state->have++]] = (unsigned short)BITS(3); - DROPBITS(3); - } - while (state->have < 19) - state->lens[order[state->have++]] = 0; - state->next = state->codes; - state->lencode = (code const FAR *)(state->next); - state->lenbits = 7; - ret = inflate_table(CODES, state->lens, 19, &(state->next), - &(state->lenbits), state->work); - if (ret) { - strm->msg = (char *)"invalid code lengths set"; - state->mode = BAD; - break; - } - Tracev((stderr, "inflate: code lengths ok\n")); - - /* get length and distance code code lengths */ - state->have = 0; - while (state->have < state->nlen + state->ndist) { - for (;;) { - here = state->lencode[BITS(state->lenbits)]; - if ((unsigned)(here.bits) <= bits) break; - PULLBYTE(); - } - if (here.val < 16) { - NEEDBITS(here.bits); - DROPBITS(here.bits); - state->lens[state->have++] = here.val; - } - else { - if (here.val == 16) { - NEEDBITS(here.bits + 2); - DROPBITS(here.bits); - if (state->have == 0) { - strm->msg = (char *)"invalid bit length repeat"; - state->mode = BAD; - break; - } - len = (unsigned)(state->lens[state->have - 1]); - copy = 3 + BITS(2); - DROPBITS(2); - } - else if (here.val == 17) { - NEEDBITS(here.bits + 3); - DROPBITS(here.bits); - len = 0; - copy = 3 + BITS(3); - DROPBITS(3); - } - else { - NEEDBITS(here.bits + 7); - DROPBITS(here.bits); - len = 0; - copy = 11 + BITS(7); - DROPBITS(7); - } - if (state->have + copy > state->nlen + state->ndist) { - strm->msg = (char *)"invalid bit length repeat"; - state->mode = BAD; - break; - } - while (copy--) - state->lens[state->have++] = (unsigned short)len; - } - } - - /* handle error breaks in while */ - if (state->mode == BAD) break; - - /* check for end-of-block code (better have one) */ - if (state->lens[256] == 0) { - strm->msg = (char *)"invalid code -- missing end-of-block"; - state->mode = BAD; - break; - } - - /* build code tables -- note: do not change the lenbits or distbits - values here (9 and 6) without reading the comments in inftrees.h - concerning the ENOUGH constants, which depend on those values */ - state->next = state->codes; - state->lencode = (code const FAR *)(state->next); - state->lenbits = 9; - ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), - &(state->lenbits), state->work); - if (ret) { - strm->msg = (char *)"invalid literal/lengths set"; - state->mode = BAD; - break; - } - state->distcode = (code const FAR *)(state->next); - state->distbits = 6; - ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, - &(state->next), &(state->distbits), state->work); - if (ret) { - strm->msg = (char *)"invalid distances set"; - state->mode = BAD; - break; - } - Tracev((stderr, "inflate: codes ok\n")); - state->mode = LEN; - - case LEN: - /* use inflate_fast() if we have enough input and output */ - if (have >= 6 && left >= 258) { - RESTORE(); - if (state->whave < state->wsize) - state->whave = state->wsize - left; - inflate_fast(strm, state->wsize); - LOAD(); - break; - } - - /* get a literal, length, or end-of-block code */ - for (;;) { - here = state->lencode[BITS(state->lenbits)]; - if ((unsigned)(here.bits) <= bits) break; - PULLBYTE(); - } - if (here.op && (here.op & 0xf0) == 0) { - last = here; - for (;;) { - here = state->lencode[last.val + - (BITS(last.bits + last.op) >> last.bits)]; - if ((unsigned)(last.bits + here.bits) <= bits) break; - PULLBYTE(); - } - DROPBITS(last.bits); - } - DROPBITS(here.bits); - state->length = (unsigned)here.val; - - /* process literal */ - if (here.op == 0) { - Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? - "inflate: literal '%c'\n" : - "inflate: literal 0x%02x\n", here.val)); - ROOM(); - *put++ = (unsigned char)(state->length); - left--; - state->mode = LEN; - break; - } - - /* process end of block */ - if (here.op & 32) { - Tracevv((stderr, "inflate: end of block\n")); - state->mode = TYPE; - break; - } - - /* invalid code */ - if (here.op & 64) { - strm->msg = (char *)"invalid literal/length code"; - state->mode = BAD; - break; - } - - /* length code -- get extra bits, if any */ - state->extra = (unsigned)(here.op) & 15; - if (state->extra != 0) { - NEEDBITS(state->extra); - state->length += BITS(state->extra); - DROPBITS(state->extra); - } - Tracevv((stderr, "inflate: length %u\n", state->length)); - - /* get distance code */ - for (;;) { - here = state->distcode[BITS(state->distbits)]; - if ((unsigned)(here.bits) <= bits) break; - PULLBYTE(); - } - if ((here.op & 0xf0) == 0) { - last = here; - for (;;) { - here = state->distcode[last.val + - (BITS(last.bits + last.op) >> last.bits)]; - if ((unsigned)(last.bits + here.bits) <= bits) break; - PULLBYTE(); - } - DROPBITS(last.bits); - } - DROPBITS(here.bits); - if (here.op & 64) { - strm->msg = (char *)"invalid distance code"; - state->mode = BAD; - break; - } - state->offset = (unsigned)here.val; - - /* get distance extra bits, if any */ - state->extra = (unsigned)(here.op) & 15; - if (state->extra != 0) { - NEEDBITS(state->extra); - state->offset += BITS(state->extra); - DROPBITS(state->extra); - } - if (state->offset > state->wsize - (state->whave < state->wsize ? - left : 0)) { - strm->msg = (char *)"invalid distance too far back"; - state->mode = BAD; - break; - } - Tracevv((stderr, "inflate: distance %u\n", state->offset)); - - /* copy match from window to output */ - do { - ROOM(); - copy = state->wsize - state->offset; - if (copy < left) { - from = put + copy; - copy = left - copy; - } - else { - from = put - state->offset; - copy = left; - } - if (copy > state->length) copy = state->length; - state->length -= copy; - left -= copy; - do { - *put++ = *from++; - } while (--copy); - } while (state->length != 0); - break; - - case DONE: - /* inflate stream terminated properly -- write leftover output */ - ret = Z_STREAM_END; - if (left < state->wsize) { - if (out(out_desc, state->window, state->wsize - left)) - ret = Z_BUF_ERROR; - } - goto inf_leave; - - case BAD: - ret = Z_DATA_ERROR; - goto inf_leave; - - default: /* can't happen, but makes compilers happy */ - ret = Z_STREAM_ERROR; - goto inf_leave; - } - - /* Return unused input */ - inf_leave: - strm->next_in = next; - strm->avail_in = have; - return ret; -} - -int ZEXPORT inflateBackEnd(strm) -z_streamp strm; -{ - if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) - return Z_STREAM_ERROR; - ZFREE(strm, strm->state); - strm->state = Z_NULL; - Tracev((stderr, "inflate: end\n")); - return Z_OK; -} diff --git a/externals/zlib/inffast.c b/externals/zlib/inffast.c deleted file mode 100644 index 2f1d60b43b8..00000000000 --- a/externals/zlib/inffast.c +++ /dev/null @@ -1,340 +0,0 @@ -/* inffast.c -- fast decoding - * Copyright (C) 1995-2008, 2010 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -#include "zutil.h" -#include "inftrees.h" -#include "inflate.h" -#include "inffast.h" - -#ifndef ASMINF - -/* Allow machine dependent optimization for post-increment or pre-increment. - Based on testing to date, - Pre-increment preferred for: - - PowerPC G3 (Adler) - - MIPS R5000 (Randers-Pehrson) - Post-increment preferred for: - - none - No measurable difference: - - Pentium III (Anderson) - - M68060 (Nikl) - */ -#ifdef POSTINC -# define OFF 0 -# define PUP(a) *(a)++ -#else -# define OFF 1 -# define PUP(a) *++(a) -#endif - -/* - Decode literal, length, and distance codes and write out the resulting - literal and match bytes until either not enough input or output is - available, an end-of-block is encountered, or a data error is encountered. - When large enough input and output buffers are supplied to inflate(), for - example, a 16K input buffer and a 64K output buffer, more than 95% of the - inflate execution time is spent in this routine. - - Entry assumptions: - - state->mode == LEN - strm->avail_in >= 6 - strm->avail_out >= 258 - start >= strm->avail_out - state->bits < 8 - - On return, state->mode is one of: - - LEN -- ran out of enough output space or enough available input - TYPE -- reached end of block code, inflate() to interpret next block - BAD -- error in block data - - Notes: - - - The maximum input bits used by a length/distance pair is 15 bits for the - length code, 5 bits for the length extra, 15 bits for the distance code, - and 13 bits for the distance extra. This totals 48 bits, or six bytes. - Therefore if strm->avail_in >= 6, then there is enough input to avoid - checking for available input while decoding. - - - The maximum bytes that a single length/distance pair can output is 258 - bytes, which is the maximum length that can be coded. inflate_fast() - requires strm->avail_out >= 258 for each loop to avoid checking for - output space. - */ -void ZLIB_INTERNAL inflate_fast(strm, start) -z_streamp strm; -unsigned start; /* inflate()'s starting value for strm->avail_out */ -{ - struct inflate_state FAR *state; - unsigned char FAR *in; /* local strm->next_in */ - unsigned char FAR *last; /* while in < last, enough input available */ - unsigned char FAR *out; /* local strm->next_out */ - unsigned char FAR *beg; /* inflate()'s initial strm->next_out */ - unsigned char FAR *end; /* while out < end, enough space available */ -#ifdef INFLATE_STRICT - unsigned dmax; /* maximum distance from zlib header */ -#endif - unsigned wsize; /* window size or zero if not using window */ - unsigned whave; /* valid bytes in the window */ - unsigned wnext; /* window write index */ - unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */ - unsigned long hold; /* local strm->hold */ - unsigned bits; /* local strm->bits */ - code const FAR *lcode; /* local strm->lencode */ - code const FAR *dcode; /* local strm->distcode */ - unsigned lmask; /* mask for first level of length codes */ - unsigned dmask; /* mask for first level of distance codes */ - code here; /* retrieved table entry */ - unsigned op; /* code bits, operation, extra bits, or */ - /* window position, window bytes to copy */ - unsigned len; /* match length, unused bytes */ - unsigned dist; /* match distance */ - unsigned char FAR *from; /* where to copy match from */ - - /* copy state to local variables */ - state = (struct inflate_state FAR *)strm->state; - in = strm->next_in - OFF; - last = in + (strm->avail_in - 5); - out = strm->next_out - OFF; - beg = out - (start - strm->avail_out); - end = out + (strm->avail_out - 257); -#ifdef INFLATE_STRICT - dmax = state->dmax; -#endif - wsize = state->wsize; - whave = state->whave; - wnext = state->wnext; - window = state->window; - hold = state->hold; - bits = state->bits; - lcode = state->lencode; - dcode = state->distcode; - lmask = (1U << state->lenbits) - 1; - dmask = (1U << state->distbits) - 1; - - /* decode literals and length/distances until end-of-block or not enough - input data or output space */ - do { - if (bits < 15) { - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - } - here = lcode[hold & lmask]; - dolen: - op = (unsigned)(here.bits); - hold >>= op; - bits -= op; - op = (unsigned)(here.op); - if (op == 0) { /* literal */ - Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? - "inflate: literal '%c'\n" : - "inflate: literal 0x%02x\n", here.val)); - PUP(out) = (unsigned char)(here.val); - } - else if (op & 16) { /* length base */ - len = (unsigned)(here.val); - op &= 15; /* number of extra bits */ - if (op) { - if (bits < op) { - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - } - len += (unsigned)hold & ((1U << op) - 1); - hold >>= op; - bits -= op; - } - Tracevv((stderr, "inflate: length %u\n", len)); - if (bits < 15) { - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - } - here = dcode[hold & dmask]; - dodist: - op = (unsigned)(here.bits); - hold >>= op; - bits -= op; - op = (unsigned)(here.op); - if (op & 16) { /* distance base */ - dist = (unsigned)(here.val); - op &= 15; /* number of extra bits */ - if (bits < op) { - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - if (bits < op) { - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - } - } - dist += (unsigned)hold & ((1U << op) - 1); -#ifdef INFLATE_STRICT - if (dist > dmax) { - strm->msg = (char *)"invalid distance too far back"; - state->mode = BAD; - break; - } -#endif - hold >>= op; - bits -= op; - Tracevv((stderr, "inflate: distance %u\n", dist)); - op = (unsigned)(out - beg); /* max distance in output */ - if (dist > op) { /* see if copy from window */ - op = dist - op; /* distance back in window */ - if (op > whave) { - if (state->sane) { - strm->msg = - (char *)"invalid distance too far back"; - state->mode = BAD; - break; - } -#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR - if (len <= op - whave) { - do { - PUP(out) = 0; - } while (--len); - continue; - } - len -= op - whave; - do { - PUP(out) = 0; - } while (--op > whave); - if (op == 0) { - from = out - dist; - do { - PUP(out) = PUP(from); - } while (--len); - continue; - } -#endif - } - from = window - OFF; - if (wnext == 0) { /* very common case */ - from += wsize - op; - if (op < len) { /* some from window */ - len -= op; - do { - PUP(out) = PUP(from); - } while (--op); - from = out - dist; /* rest from output */ - } - } - else if (wnext < op) { /* wrap around window */ - from += wsize + wnext - op; - op -= wnext; - if (op < len) { /* some from end of window */ - len -= op; - do { - PUP(out) = PUP(from); - } while (--op); - from = window - OFF; - if (wnext < len) { /* some from start of window */ - op = wnext; - len -= op; - do { - PUP(out) = PUP(from); - } while (--op); - from = out - dist; /* rest from output */ - } - } - } - else { /* contiguous in window */ - from += wnext - op; - if (op < len) { /* some from window */ - len -= op; - do { - PUP(out) = PUP(from); - } while (--op); - from = out - dist; /* rest from output */ - } - } - while (len > 2) { - PUP(out) = PUP(from); - PUP(out) = PUP(from); - PUP(out) = PUP(from); - len -= 3; - } - if (len) { - PUP(out) = PUP(from); - if (len > 1) - PUP(out) = PUP(from); - } - } - else { - from = out - dist; /* copy direct from output */ - do { /* minimum length is three */ - PUP(out) = PUP(from); - PUP(out) = PUP(from); - PUP(out) = PUP(from); - len -= 3; - } while (len > 2); - if (len) { - PUP(out) = PUP(from); - if (len > 1) - PUP(out) = PUP(from); - } - } - } - else if ((op & 64) == 0) { /* 2nd level distance code */ - here = dcode[here.val + (hold & ((1U << op) - 1))]; - goto dodist; - } - else { - strm->msg = (char *)"invalid distance code"; - state->mode = BAD; - break; - } - } - else if ((op & 64) == 0) { /* 2nd level length code */ - here = lcode[here.val + (hold & ((1U << op) - 1))]; - goto dolen; - } - else if (op & 32) { /* end-of-block */ - Tracevv((stderr, "inflate: end of block\n")); - state->mode = TYPE; - break; - } - else { - strm->msg = (char *)"invalid literal/length code"; - state->mode = BAD; - break; - } - } while (in < last && out < end); - - /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ - len = bits >> 3; - in -= len; - bits -= len << 3; - hold &= (1U << bits) - 1; - - /* update state and return */ - strm->next_in = in + OFF; - strm->next_out = out + OFF; - strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last)); - strm->avail_out = (unsigned)(out < end ? - 257 + (end - out) : 257 - (out - end)); - state->hold = hold; - state->bits = bits; - return; -} - -/* - inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe): - - Using bit fields for code structure - - Different op definition to avoid & for extra bits (do & for table bits) - - Three separate decoding do-loops for direct, window, and wnext == 0 - - Special case for distance > 1 copies to do overlapped load and store copy - - Explicit branch predictions (based on measured branch probabilities) - - Deferring match copy and interspersed it with decoding subsequent codes - - Swapping literal/length else - - Swapping window/direct else - - Larger unrolled copy loops (three is about right) - - Moving len -= 3 statement into middle of loop - */ - -#endif /* !ASMINF */ diff --git a/externals/zlib/inffast.h b/externals/zlib/inffast.h deleted file mode 100644 index e5c1aa4ca8c..00000000000 --- a/externals/zlib/inffast.h +++ /dev/null @@ -1,11 +0,0 @@ -/* inffast.h -- header to use inffast.c - * Copyright (C) 1995-2003, 2010 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -void ZLIB_INTERNAL inflate_fast OF((z_streamp strm, unsigned start)); diff --git a/externals/zlib/inffixed.h b/externals/zlib/inffixed.h deleted file mode 100644 index 75ed4b5978d..00000000000 --- a/externals/zlib/inffixed.h +++ /dev/null @@ -1,94 +0,0 @@ - /* inffixed.h -- table for decoding fixed codes - * Generated automatically by makefixed(). - */ - - /* WARNING: this file should *not* be used by applications. It - is part of the implementation of the compression library and - is subject to change. Applications should only use zlib.h. - */ - - static const code lenfix[512] = { - {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48}, - {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128}, - {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59}, - {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176}, - {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20}, - {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100}, - {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8}, - {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216}, - {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76}, - {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114}, - {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2}, - {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148}, - {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42}, - {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86}, - {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15}, - {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236}, - {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62}, - {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142}, - {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31}, - {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162}, - {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25}, - {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105}, - {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4}, - {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202}, - {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69}, - {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125}, - {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13}, - {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195}, - {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35}, - {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91}, - {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19}, - {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246}, - {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55}, - {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135}, - {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99}, - {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190}, - {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16}, - {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96}, - {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6}, - {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209}, - {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72}, - {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116}, - {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4}, - {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153}, - {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44}, - {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82}, - {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11}, - {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229}, - {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58}, - {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138}, - {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51}, - {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173}, - {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30}, - {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110}, - {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0}, - {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195}, - {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65}, - {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121}, - {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9}, - {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258}, - {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37}, - {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93}, - {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23}, - {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251}, - {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51}, - {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131}, - {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67}, - {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183}, - {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23}, - {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103}, - {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9}, - {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223}, - {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79}, - {0,9,255} - }; - - static const code distfix[32] = { - {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025}, - {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193}, - {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385}, - {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577}, - {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073}, - {22,5,193},{64,5,0} - }; diff --git a/externals/zlib/inflate.c b/externals/zlib/inflate.c deleted file mode 100644 index a8431abeacf..00000000000 --- a/externals/zlib/inflate.c +++ /dev/null @@ -1,1480 +0,0 @@ -/* inflate.c -- zlib decompression - * Copyright (C) 1995-2010 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* - * Change history: - * - * 1.2.beta0 24 Nov 2002 - * - First version -- complete rewrite of inflate to simplify code, avoid - * creation of window when not needed, minimize use of window when it is - * needed, make inffast.c even faster, implement gzip decoding, and to - * improve code readability and style over the previous zlib inflate code - * - * 1.2.beta1 25 Nov 2002 - * - Use pointers for available input and output checking in inffast.c - * - Remove input and output counters in inffast.c - * - Change inffast.c entry and loop from avail_in >= 7 to >= 6 - * - Remove unnecessary second byte pull from length extra in inffast.c - * - Unroll direct copy to three copies per loop in inffast.c - * - * 1.2.beta2 4 Dec 2002 - * - Change external routine names to reduce potential conflicts - * - Correct filename to inffixed.h for fixed tables in inflate.c - * - Make hbuf[] unsigned char to match parameter type in inflate.c - * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset) - * to avoid negation problem on Alphas (64 bit) in inflate.c - * - * 1.2.beta3 22 Dec 2002 - * - Add comments on state->bits assertion in inffast.c - * - Add comments on op field in inftrees.h - * - Fix bug in reuse of allocated window after inflateReset() - * - Remove bit fields--back to byte structure for speed - * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths - * - Change post-increments to pre-increments in inflate_fast(), PPC biased? - * - Add compile time option, POSTINC, to use post-increments instead (Intel?) - * - Make MATCH copy in inflate() much faster for when inflate_fast() not used - * - Use local copies of stream next and avail values, as well as local bit - * buffer and bit count in inflate()--for speed when inflate_fast() not used - * - * 1.2.beta4 1 Jan 2003 - * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings - * - Move a comment on output buffer sizes from inffast.c to inflate.c - * - Add comments in inffast.c to introduce the inflate_fast() routine - * - Rearrange window copies in inflate_fast() for speed and simplification - * - Unroll last copy for window match in inflate_fast() - * - Use local copies of window variables in inflate_fast() for speed - * - Pull out common wnext == 0 case for speed in inflate_fast() - * - Make op and len in inflate_fast() unsigned for consistency - * - Add FAR to lcode and dcode declarations in inflate_fast() - * - Simplified bad distance check in inflate_fast() - * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new - * source file infback.c to provide a call-back interface to inflate for - * programs like gzip and unzip -- uses window as output buffer to avoid - * window copying - * - * 1.2.beta5 1 Jan 2003 - * - Improved inflateBack() interface to allow the caller to provide initial - * input in strm. - * - Fixed stored blocks bug in inflateBack() - * - * 1.2.beta6 4 Jan 2003 - * - Added comments in inffast.c on effectiveness of POSTINC - * - Typecasting all around to reduce compiler warnings - * - Changed loops from while (1) or do {} while (1) to for (;;), again to - * make compilers happy - * - Changed type of window in inflateBackInit() to unsigned char * - * - * 1.2.beta7 27 Jan 2003 - * - Changed many types to unsigned or unsigned short to avoid warnings - * - Added inflateCopy() function - * - * 1.2.0 9 Mar 2003 - * - Changed inflateBack() interface to provide separate opaque descriptors - * for the in() and out() functions - * - Changed inflateBack() argument and in_func typedef to swap the length - * and buffer address return values for the input function - * - Check next_in and next_out for Z_NULL on entry to inflate() - * - * The history for versions after 1.2.0 are in ChangeLog in zlib distribution. - */ - -#include "zutil.h" -#include "inftrees.h" -#include "inflate.h" -#include "inffast.h" - -#ifdef MAKEFIXED -# ifndef BUILDFIXED -# define BUILDFIXED -# endif -#endif - -/* function prototypes */ -local void fixedtables OF((struct inflate_state FAR *state)); -local int updatewindow OF((z_streamp strm, unsigned out)); -#ifdef BUILDFIXED - void makefixed OF((void)); -#endif -local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf, - unsigned len)); - -int ZEXPORT inflateReset(strm) -z_streamp strm; -{ - struct inflate_state FAR *state; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - strm->total_in = strm->total_out = state->total = 0; - strm->msg = Z_NULL; - strm->adler = 1; /* to support ill-conceived Java test suite */ - state->mode = HEAD; - state->last = 0; - state->havedict = 0; - state->dmax = 32768U; - state->head = Z_NULL; - state->wsize = 0; - state->whave = 0; - state->wnext = 0; - state->hold = 0; - state->bits = 0; - state->lencode = state->distcode = state->next = state->codes; - state->sane = 1; - state->back = -1; - Tracev((stderr, "inflate: reset\n")); - return Z_OK; -} - -int ZEXPORT inflateReset2(strm, windowBits) -z_streamp strm; -int windowBits; -{ - int wrap; - struct inflate_state FAR *state; - - /* get the state */ - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - - /* extract wrap request from windowBits parameter */ - if (windowBits < 0) { - wrap = 0; - windowBits = -windowBits; - } - else { - wrap = (windowBits >> 4) + 1; -#ifdef GUNZIP - if (windowBits < 48) - windowBits &= 15; -#endif - } - - /* set number of window bits, free window if different */ - if (windowBits && (windowBits < 8 || windowBits > 15)) - return Z_STREAM_ERROR; - if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) { - ZFREE(strm, state->window); - state->window = Z_NULL; - } - - /* update state and reset the rest of it */ - state->wrap = wrap; - state->wbits = (unsigned)windowBits; - return inflateReset(strm); -} - -int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size) -z_streamp strm; -int windowBits; -const char *version; -int stream_size; -{ - int ret; - struct inflate_state FAR *state; - - if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || - stream_size != (int)(sizeof(z_stream))) - return Z_VERSION_ERROR; - if (strm == Z_NULL) return Z_STREAM_ERROR; - strm->msg = Z_NULL; /* in case we return an error */ - if (strm->zalloc == (alloc_func)0) { - strm->zalloc = zcalloc; - strm->opaque = (voidpf)0; - } - if (strm->zfree == (free_func)0) strm->zfree = zcfree; - state = (struct inflate_state FAR *) - ZALLOC(strm, 1, sizeof(struct inflate_state)); - if (state == Z_NULL) return Z_MEM_ERROR; - Tracev((stderr, "inflate: allocated\n")); - strm->state = (struct internal_state FAR *)state; - state->window = Z_NULL; - ret = inflateReset2(strm, windowBits); - if (ret != Z_OK) { - ZFREE(strm, state); - strm->state = Z_NULL; - } - return ret; -} - -int ZEXPORT inflateInit_(strm, version, stream_size) -z_streamp strm; -const char *version; -int stream_size; -{ - return inflateInit2_(strm, DEF_WBITS, version, stream_size); -} - -int ZEXPORT inflatePrime(strm, bits, value) -z_streamp strm; -int bits; -int value; -{ - struct inflate_state FAR *state; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - if (bits < 0) { - state->hold = 0; - state->bits = 0; - return Z_OK; - } - if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR; - value &= (1L << bits) - 1; - state->hold += value << state->bits; - state->bits += bits; - return Z_OK; -} - -/* - Return state with length and distance decoding tables and index sizes set to - fixed code decoding. Normally this returns fixed tables from inffixed.h. - If BUILDFIXED is defined, then instead this routine builds the tables the - first time it's called, and returns those tables the first time and - thereafter. This reduces the size of the code by about 2K bytes, in - exchange for a little execution time. However, BUILDFIXED should not be - used for threaded applications, since the rewriting of the tables and virgin - may not be thread-safe. - */ -local void fixedtables(state) -struct inflate_state FAR *state; -{ -#ifdef BUILDFIXED - static int virgin = 1; - static code *lenfix, *distfix; - static code fixed[544]; - - /* build fixed huffman tables if first call (may not be thread safe) */ - if (virgin) { - unsigned sym, bits; - static code *next; - - /* literal/length table */ - sym = 0; - while (sym < 144) state->lens[sym++] = 8; - while (sym < 256) state->lens[sym++] = 9; - while (sym < 280) state->lens[sym++] = 7; - while (sym < 288) state->lens[sym++] = 8; - next = fixed; - lenfix = next; - bits = 9; - inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); - - /* distance table */ - sym = 0; - while (sym < 32) state->lens[sym++] = 5; - distfix = next; - bits = 5; - inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); - - /* do this just once */ - virgin = 0; - } -#else /* !BUILDFIXED */ -# include "inffixed.h" -#endif /* BUILDFIXED */ - state->lencode = lenfix; - state->lenbits = 9; - state->distcode = distfix; - state->distbits = 5; -} - -#ifdef MAKEFIXED -#include - -/* - Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also - defines BUILDFIXED, so the tables are built on the fly. makefixed() writes - those tables to stdout, which would be piped to inffixed.h. A small program - can simply call makefixed to do this: - - void makefixed(void); - - int main(void) - { - makefixed(); - return 0; - } - - Then that can be linked with zlib built with MAKEFIXED defined and run: - - a.out > inffixed.h - */ -void makefixed() -{ - unsigned low, size; - struct inflate_state state; - - fixedtables(&state); - puts(" /* inffixed.h -- table for decoding fixed codes"); - puts(" * Generated automatically by makefixed()."); - puts(" */"); - puts(""); - puts(" /* WARNING: this file should *not* be used by applications."); - puts(" It is part of the implementation of this library and is"); - puts(" subject to change. Applications should only use zlib.h."); - puts(" */"); - puts(""); - size = 1U << 9; - printf(" static const code lenfix[%u] = {", size); - low = 0; - for (;;) { - if ((low % 7) == 0) printf("\n "); - printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits, - state.lencode[low].val); - if (++low == size) break; - putchar(','); - } - puts("\n };"); - size = 1U << 5; - printf("\n static const code distfix[%u] = {", size); - low = 0; - for (;;) { - if ((low % 6) == 0) printf("\n "); - printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits, - state.distcode[low].val); - if (++low == size) break; - putchar(','); - } - puts("\n };"); -} -#endif /* MAKEFIXED */ - -/* - Update the window with the last wsize (normally 32K) bytes written before - returning. If window does not exist yet, create it. This is only called - when a window is already in use, or when output has been written during this - inflate call, but the end of the deflate stream has not been reached yet. - It is also called to create a window for dictionary data when a dictionary - is loaded. - - Providing output buffers larger than 32K to inflate() should provide a speed - advantage, since only the last 32K of output is copied to the sliding window - upon return from inflate(), and since all distances after the first 32K of - output will fall in the output data, making match copies simpler and faster. - The advantage may be dependent on the size of the processor's data caches. - */ -local int updatewindow(strm, out) -z_streamp strm; -unsigned out; -{ - struct inflate_state FAR *state; - unsigned copy, dist; - - state = (struct inflate_state FAR *)strm->state; - - /* if it hasn't been done already, allocate space for the window */ - if (state->window == Z_NULL) { - state->window = (unsigned char FAR *) - ZALLOC(strm, 1U << state->wbits, - sizeof(unsigned char)); - if (state->window == Z_NULL) return 1; - } - - /* if window not in use yet, initialize */ - if (state->wsize == 0) { - state->wsize = 1U << state->wbits; - state->wnext = 0; - state->whave = 0; - } - - /* copy state->wsize or less output bytes into the circular window */ - copy = out - strm->avail_out; - if (copy >= state->wsize) { - zmemcpy(state->window, strm->next_out - state->wsize, state->wsize); - state->wnext = 0; - state->whave = state->wsize; - } - else { - dist = state->wsize - state->wnext; - if (dist > copy) dist = copy; - zmemcpy(state->window + state->wnext, strm->next_out - copy, dist); - copy -= dist; - if (copy) { - zmemcpy(state->window, strm->next_out - copy, copy); - state->wnext = copy; - state->whave = state->wsize; - } - else { - state->wnext += dist; - if (state->wnext == state->wsize) state->wnext = 0; - if (state->whave < state->wsize) state->whave += dist; - } - } - return 0; -} - -/* Macros for inflate(): */ - -/* check function to use adler32() for zlib or crc32() for gzip */ -#ifdef GUNZIP -# define UPDATE(check, buf, len) \ - (state->flags ? crc32(check, buf, len) : adler32(check, buf, len)) -#else -# define UPDATE(check, buf, len) adler32(check, buf, len) -#endif - -/* check macros for header crc */ -#ifdef GUNZIP -# define CRC2(check, word) \ - do { \ - hbuf[0] = (unsigned char)(word); \ - hbuf[1] = (unsigned char)((word) >> 8); \ - check = crc32(check, hbuf, 2); \ - } while (0) - -# define CRC4(check, word) \ - do { \ - hbuf[0] = (unsigned char)(word); \ - hbuf[1] = (unsigned char)((word) >> 8); \ - hbuf[2] = (unsigned char)((word) >> 16); \ - hbuf[3] = (unsigned char)((word) >> 24); \ - check = crc32(check, hbuf, 4); \ - } while (0) -#endif - -/* Load registers with state in inflate() for speed */ -#define LOAD() \ - do { \ - put = strm->next_out; \ - left = strm->avail_out; \ - next = strm->next_in; \ - have = strm->avail_in; \ - hold = state->hold; \ - bits = state->bits; \ - } while (0) - -/* Restore state from registers in inflate() */ -#define RESTORE() \ - do { \ - strm->next_out = put; \ - strm->avail_out = left; \ - strm->next_in = next; \ - strm->avail_in = have; \ - state->hold = hold; \ - state->bits = bits; \ - } while (0) - -/* Clear the input bit accumulator */ -#define INITBITS() \ - do { \ - hold = 0; \ - bits = 0; \ - } while (0) - -/* Get a byte of input into the bit accumulator, or return from inflate() - if there is no input available. */ -#define PULLBYTE() \ - do { \ - if (have == 0) goto inf_leave; \ - have--; \ - hold += (unsigned long)(*next++) << bits; \ - bits += 8; \ - } while (0) - -/* Assure that there are at least n bits in the bit accumulator. If there is - not enough available input to do that, then return from inflate(). */ -#define NEEDBITS(n) \ - do { \ - while (bits < (unsigned)(n)) \ - PULLBYTE(); \ - } while (0) - -/* Return the low n bits of the bit accumulator (n < 16) */ -#define BITS(n) \ - ((unsigned)hold & ((1U << (n)) - 1)) - -/* Remove n bits from the bit accumulator */ -#define DROPBITS(n) \ - do { \ - hold >>= (n); \ - bits -= (unsigned)(n); \ - } while (0) - -/* Remove zero to seven bits as needed to go to a byte boundary */ -#define BYTEBITS() \ - do { \ - hold >>= bits & 7; \ - bits -= bits & 7; \ - } while (0) - -/* Reverse the bytes in a 32-bit value */ -#define REVERSE(q) \ - ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ - (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) - -/* - inflate() uses a state machine to process as much input data and generate as - much output data as possible before returning. The state machine is - structured roughly as follows: - - for (;;) switch (state) { - ... - case STATEn: - if (not enough input data or output space to make progress) - return; - ... make progress ... - state = STATEm; - break; - ... - } - - so when inflate() is called again, the same case is attempted again, and - if the appropriate resources are provided, the machine proceeds to the - next state. The NEEDBITS() macro is usually the way the state evaluates - whether it can proceed or should return. NEEDBITS() does the return if - the requested bits are not available. The typical use of the BITS macros - is: - - NEEDBITS(n); - ... do something with BITS(n) ... - DROPBITS(n); - - where NEEDBITS(n) either returns from inflate() if there isn't enough - input left to load n bits into the accumulator, or it continues. BITS(n) - gives the low n bits in the accumulator. When done, DROPBITS(n) drops - the low n bits off the accumulator. INITBITS() clears the accumulator - and sets the number of available bits to zero. BYTEBITS() discards just - enough bits to put the accumulator on a byte boundary. After BYTEBITS() - and a NEEDBITS(8), then BITS(8) would return the next byte in the stream. - - NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return - if there is no input available. The decoding of variable length codes uses - PULLBYTE() directly in order to pull just enough bytes to decode the next - code, and no more. - - Some states loop until they get enough input, making sure that enough - state information is maintained to continue the loop where it left off - if NEEDBITS() returns in the loop. For example, want, need, and keep - would all have to actually be part of the saved state in case NEEDBITS() - returns: - - case STATEw: - while (want < need) { - NEEDBITS(n); - keep[want++] = BITS(n); - DROPBITS(n); - } - state = STATEx; - case STATEx: - - As shown above, if the next state is also the next case, then the break - is omitted. - - A state may also return if there is not enough output space available to - complete that state. Those states are copying stored data, writing a - literal byte, and copying a matching string. - - When returning, a "goto inf_leave" is used to update the total counters, - update the check value, and determine whether any progress has been made - during that inflate() call in order to return the proper return code. - Progress is defined as a change in either strm->avail_in or strm->avail_out. - When there is a window, goto inf_leave will update the window with the last - output written. If a goto inf_leave occurs in the middle of decompression - and there is no window currently, goto inf_leave will create one and copy - output to the window for the next call of inflate(). - - In this implementation, the flush parameter of inflate() only affects the - return code (per zlib.h). inflate() always writes as much as possible to - strm->next_out, given the space available and the provided input--the effect - documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers - the allocation of and copying into a sliding window until necessary, which - provides the effect documented in zlib.h for Z_FINISH when the entire input - stream available. So the only thing the flush parameter actually does is: - when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it - will return Z_BUF_ERROR if it has not reached the end of the stream. - */ - -int ZEXPORT inflate(strm, flush) -z_streamp strm; -int flush; -{ - struct inflate_state FAR *state; - unsigned char FAR *next; /* next input */ - unsigned char FAR *put; /* next output */ - unsigned have, left; /* available input and output */ - unsigned long hold; /* bit buffer */ - unsigned bits; /* bits in bit buffer */ - unsigned in, out; /* save starting available input and output */ - unsigned copy; /* number of stored or match bytes to copy */ - unsigned char FAR *from; /* where to copy match bytes from */ - code here; /* current decoding table entry */ - code last; /* parent table entry */ - unsigned len; /* length to copy for repeats, bits to drop */ - int ret; /* return code */ -#ifdef GUNZIP - unsigned char hbuf[4]; /* buffer for gzip header crc calculation */ -#endif - static const unsigned short order[19] = /* permutation of code lengths */ - {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; - - if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL || - (strm->next_in == Z_NULL && strm->avail_in != 0)) - return Z_STREAM_ERROR; - - state = (struct inflate_state FAR *)strm->state; - if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */ - LOAD(); - in = have; - out = left; - ret = Z_OK; - for (;;) - switch (state->mode) { - case HEAD: - if (state->wrap == 0) { - state->mode = TYPEDO; - break; - } - NEEDBITS(16); -#ifdef GUNZIP - if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */ - state->check = crc32(0L, Z_NULL, 0); - CRC2(state->check, hold); - INITBITS(); - state->mode = FLAGS; - break; - } - state->flags = 0; /* expect zlib header */ - if (state->head != Z_NULL) - state->head->done = -1; - if (!(state->wrap & 1) || /* check if zlib header allowed */ -#else - if ( -#endif - ((BITS(8) << 8) + (hold >> 8)) % 31) { - strm->msg = (char *)"incorrect header check"; - state->mode = BAD; - break; - } - if (BITS(4) != Z_DEFLATED) { - strm->msg = (char *)"unknown compression method"; - state->mode = BAD; - break; - } - DROPBITS(4); - len = BITS(4) + 8; - if (state->wbits == 0) - state->wbits = len; - else if (len > state->wbits) { - strm->msg = (char *)"invalid window size"; - state->mode = BAD; - break; - } - state->dmax = 1U << len; - Tracev((stderr, "inflate: zlib header ok\n")); - strm->adler = state->check = adler32(0L, Z_NULL, 0); - state->mode = hold & 0x200 ? DICTID : TYPE; - INITBITS(); - break; -#ifdef GUNZIP - case FLAGS: - NEEDBITS(16); - state->flags = (int)(hold); - if ((state->flags & 0xff) != Z_DEFLATED) { - strm->msg = (char *)"unknown compression method"; - state->mode = BAD; - break; - } - if (state->flags & 0xe000) { - strm->msg = (char *)"unknown header flags set"; - state->mode = BAD; - break; - } - if (state->head != Z_NULL) - state->head->text = (int)((hold >> 8) & 1); - if (state->flags & 0x0200) CRC2(state->check, hold); - INITBITS(); - state->mode = TIME; - case TIME: - NEEDBITS(32); - if (state->head != Z_NULL) - state->head->time = hold; - if (state->flags & 0x0200) CRC4(state->check, hold); - INITBITS(); - state->mode = OS; - case OS: - NEEDBITS(16); - if (state->head != Z_NULL) { - state->head->xflags = (int)(hold & 0xff); - state->head->os = (int)(hold >> 8); - } - if (state->flags & 0x0200) CRC2(state->check, hold); - INITBITS(); - state->mode = EXLEN; - case EXLEN: - if (state->flags & 0x0400) { - NEEDBITS(16); - state->length = (unsigned)(hold); - if (state->head != Z_NULL) - state->head->extra_len = (unsigned)hold; - if (state->flags & 0x0200) CRC2(state->check, hold); - INITBITS(); - } - else if (state->head != Z_NULL) - state->head->extra = Z_NULL; - state->mode = EXTRA; - case EXTRA: - if (state->flags & 0x0400) { - copy = state->length; - if (copy > have) copy = have; - if (copy) { - if (state->head != Z_NULL && - state->head->extra != Z_NULL) { - len = state->head->extra_len - state->length; - zmemcpy(state->head->extra + len, next, - len + copy > state->head->extra_max ? - state->head->extra_max - len : copy); - } - if (state->flags & 0x0200) - state->check = crc32(state->check, next, copy); - have -= copy; - next += copy; - state->length -= copy; - } - if (state->length) goto inf_leave; - } - state->length = 0; - state->mode = NAME; - case NAME: - if (state->flags & 0x0800) { - if (have == 0) goto inf_leave; - copy = 0; - do { - len = (unsigned)(next[copy++]); - if (state->head != Z_NULL && - state->head->name != Z_NULL && - state->length < state->head->name_max) - state->head->name[state->length++] = len; - } while (len && copy < have); - if (state->flags & 0x0200) - state->check = crc32(state->check, next, copy); - have -= copy; - next += copy; - if (len) goto inf_leave; - } - else if (state->head != Z_NULL) - state->head->name = Z_NULL; - state->length = 0; - state->mode = COMMENT; - case COMMENT: - if (state->flags & 0x1000) { - if (have == 0) goto inf_leave; - copy = 0; - do { - len = (unsigned)(next[copy++]); - if (state->head != Z_NULL && - state->head->comment != Z_NULL && - state->length < state->head->comm_max) - state->head->comment[state->length++] = len; - } while (len && copy < have); - if (state->flags & 0x0200) - state->check = crc32(state->check, next, copy); - have -= copy; - next += copy; - if (len) goto inf_leave; - } - else if (state->head != Z_NULL) - state->head->comment = Z_NULL; - state->mode = HCRC; - case HCRC: - if (state->flags & 0x0200) { - NEEDBITS(16); - if (hold != (state->check & 0xffff)) { - strm->msg = (char *)"header crc mismatch"; - state->mode = BAD; - break; - } - INITBITS(); - } - if (state->head != Z_NULL) { - state->head->hcrc = (int)((state->flags >> 9) & 1); - state->head->done = 1; - } - strm->adler = state->check = crc32(0L, Z_NULL, 0); - state->mode = TYPE; - break; -#endif - case DICTID: - NEEDBITS(32); - strm->adler = state->check = REVERSE(hold); - INITBITS(); - state->mode = DICT; - case DICT: - if (state->havedict == 0) { - RESTORE(); - return Z_NEED_DICT; - } - strm->adler = state->check = adler32(0L, Z_NULL, 0); - state->mode = TYPE; - case TYPE: - if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave; - case TYPEDO: - if (state->last) { - BYTEBITS(); - state->mode = CHECK; - break; - } - NEEDBITS(3); - state->last = BITS(1); - DROPBITS(1); - switch (BITS(2)) { - case 0: /* stored block */ - Tracev((stderr, "inflate: stored block%s\n", - state->last ? " (last)" : "")); - state->mode = STORED; - break; - case 1: /* fixed block */ - fixedtables(state); - Tracev((stderr, "inflate: fixed codes block%s\n", - state->last ? " (last)" : "")); - state->mode = LEN_; /* decode codes */ - if (flush == Z_TREES) { - DROPBITS(2); - goto inf_leave; - } - break; - case 2: /* dynamic block */ - Tracev((stderr, "inflate: dynamic codes block%s\n", - state->last ? " (last)" : "")); - state->mode = TABLE; - break; - case 3: - strm->msg = (char *)"invalid block type"; - state->mode = BAD; - } - DROPBITS(2); - break; - case STORED: - BYTEBITS(); /* go to byte boundary */ - NEEDBITS(32); - if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { - strm->msg = (char *)"invalid stored block lengths"; - state->mode = BAD; - break; - } - state->length = (unsigned)hold & 0xffff; - Tracev((stderr, "inflate: stored length %u\n", - state->length)); - INITBITS(); - state->mode = COPY_; - if (flush == Z_TREES) goto inf_leave; - case COPY_: - state->mode = COPY; - case COPY: - copy = state->length; - if (copy) { - if (copy > have) copy = have; - if (copy > left) copy = left; - if (copy == 0) goto inf_leave; - zmemcpy(put, next, copy); - have -= copy; - next += copy; - left -= copy; - put += copy; - state->length -= copy; - break; - } - Tracev((stderr, "inflate: stored end\n")); - state->mode = TYPE; - break; - case TABLE: - NEEDBITS(14); - state->nlen = BITS(5) + 257; - DROPBITS(5); - state->ndist = BITS(5) + 1; - DROPBITS(5); - state->ncode = BITS(4) + 4; - DROPBITS(4); -#ifndef PKZIP_BUG_WORKAROUND - if (state->nlen > 286 || state->ndist > 30) { - strm->msg = (char *)"too many length or distance symbols"; - state->mode = BAD; - break; - } -#endif - Tracev((stderr, "inflate: table sizes ok\n")); - state->have = 0; - state->mode = LENLENS; - case LENLENS: - while (state->have < state->ncode) { - NEEDBITS(3); - state->lens[order[state->have++]] = (unsigned short)BITS(3); - DROPBITS(3); - } - while (state->have < 19) - state->lens[order[state->have++]] = 0; - state->next = state->codes; - state->lencode = (code const FAR *)(state->next); - state->lenbits = 7; - ret = inflate_table(CODES, state->lens, 19, &(state->next), - &(state->lenbits), state->work); - if (ret) { - strm->msg = (char *)"invalid code lengths set"; - state->mode = BAD; - break; - } - Tracev((stderr, "inflate: code lengths ok\n")); - state->have = 0; - state->mode = CODELENS; - case CODELENS: - while (state->have < state->nlen + state->ndist) { - for (;;) { - here = state->lencode[BITS(state->lenbits)]; - if ((unsigned)(here.bits) <= bits) break; - PULLBYTE(); - } - if (here.val < 16) { - NEEDBITS(here.bits); - DROPBITS(here.bits); - state->lens[state->have++] = here.val; - } - else { - if (here.val == 16) { - NEEDBITS(here.bits + 2); - DROPBITS(here.bits); - if (state->have == 0) { - strm->msg = (char *)"invalid bit length repeat"; - state->mode = BAD; - break; - } - len = state->lens[state->have - 1]; - copy = 3 + BITS(2); - DROPBITS(2); - } - else if (here.val == 17) { - NEEDBITS(here.bits + 3); - DROPBITS(here.bits); - len = 0; - copy = 3 + BITS(3); - DROPBITS(3); - } - else { - NEEDBITS(here.bits + 7); - DROPBITS(here.bits); - len = 0; - copy = 11 + BITS(7); - DROPBITS(7); - } - if (state->have + copy > state->nlen + state->ndist) { - strm->msg = (char *)"invalid bit length repeat"; - state->mode = BAD; - break; - } - while (copy--) - state->lens[state->have++] = (unsigned short)len; - } - } - - /* handle error breaks in while */ - if (state->mode == BAD) break; - - /* check for end-of-block code (better have one) */ - if (state->lens[256] == 0) { - strm->msg = (char *)"invalid code -- missing end-of-block"; - state->mode = BAD; - break; - } - - /* build code tables -- note: do not change the lenbits or distbits - values here (9 and 6) without reading the comments in inftrees.h - concerning the ENOUGH constants, which depend on those values */ - state->next = state->codes; - state->lencode = (code const FAR *)(state->next); - state->lenbits = 9; - ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), - &(state->lenbits), state->work); - if (ret) { - strm->msg = (char *)"invalid literal/lengths set"; - state->mode = BAD; - break; - } - state->distcode = (code const FAR *)(state->next); - state->distbits = 6; - ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, - &(state->next), &(state->distbits), state->work); - if (ret) { - strm->msg = (char *)"invalid distances set"; - state->mode = BAD; - break; - } - Tracev((stderr, "inflate: codes ok\n")); - state->mode = LEN_; - if (flush == Z_TREES) goto inf_leave; - case LEN_: - state->mode = LEN; - case LEN: - if (have >= 6 && left >= 258) { - RESTORE(); - inflate_fast(strm, out); - LOAD(); - if (state->mode == TYPE) - state->back = -1; - break; - } - state->back = 0; - for (;;) { - here = state->lencode[BITS(state->lenbits)]; - if ((unsigned)(here.bits) <= bits) break; - PULLBYTE(); - } - if (here.op && (here.op & 0xf0) == 0) { - last = here; - for (;;) { - here = state->lencode[last.val + - (BITS(last.bits + last.op) >> last.bits)]; - if ((unsigned)(last.bits + here.bits) <= bits) break; - PULLBYTE(); - } - DROPBITS(last.bits); - state->back += last.bits; - } - DROPBITS(here.bits); - state->back += here.bits; - state->length = (unsigned)here.val; - if ((int)(here.op) == 0) { - Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? - "inflate: literal '%c'\n" : - "inflate: literal 0x%02x\n", here.val)); - state->mode = LIT; - break; - } - if (here.op & 32) { - Tracevv((stderr, "inflate: end of block\n")); - state->back = -1; - state->mode = TYPE; - break; - } - if (here.op & 64) { - strm->msg = (char *)"invalid literal/length code"; - state->mode = BAD; - break; - } - state->extra = (unsigned)(here.op) & 15; - state->mode = LENEXT; - case LENEXT: - if (state->extra) { - NEEDBITS(state->extra); - state->length += BITS(state->extra); - DROPBITS(state->extra); - state->back += state->extra; - } - Tracevv((stderr, "inflate: length %u\n", state->length)); - state->was = state->length; - state->mode = DIST; - case DIST: - for (;;) { - here = state->distcode[BITS(state->distbits)]; - if ((unsigned)(here.bits) <= bits) break; - PULLBYTE(); - } - if ((here.op & 0xf0) == 0) { - last = here; - for (;;) { - here = state->distcode[last.val + - (BITS(last.bits + last.op) >> last.bits)]; - if ((unsigned)(last.bits + here.bits) <= bits) break; - PULLBYTE(); - } - DROPBITS(last.bits); - state->back += last.bits; - } - DROPBITS(here.bits); - state->back += here.bits; - if (here.op & 64) { - strm->msg = (char *)"invalid distance code"; - state->mode = BAD; - break; - } - state->offset = (unsigned)here.val; - state->extra = (unsigned)(here.op) & 15; - state->mode = DISTEXT; - case DISTEXT: - if (state->extra) { - NEEDBITS(state->extra); - state->offset += BITS(state->extra); - DROPBITS(state->extra); - state->back += state->extra; - } -#ifdef INFLATE_STRICT - if (state->offset > state->dmax) { - strm->msg = (char *)"invalid distance too far back"; - state->mode = BAD; - break; - } -#endif - Tracevv((stderr, "inflate: distance %u\n", state->offset)); - state->mode = MATCH; - case MATCH: - if (left == 0) goto inf_leave; - copy = out - left; - if (state->offset > copy) { /* copy from window */ - copy = state->offset - copy; - if (copy > state->whave) { - if (state->sane) { - strm->msg = (char *)"invalid distance too far back"; - state->mode = BAD; - break; - } -#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR - Trace((stderr, "inflate.c too far\n")); - copy -= state->whave; - if (copy > state->length) copy = state->length; - if (copy > left) copy = left; - left -= copy; - state->length -= copy; - do { - *put++ = 0; - } while (--copy); - if (state->length == 0) state->mode = LEN; - break; -#endif - } - if (copy > state->wnext) { - copy -= state->wnext; - from = state->window + (state->wsize - copy); - } - else - from = state->window + (state->wnext - copy); - if (copy > state->length) copy = state->length; - } - else { /* copy from output */ - from = put - state->offset; - copy = state->length; - } - if (copy > left) copy = left; - left -= copy; - state->length -= copy; - do { - *put++ = *from++; - } while (--copy); - if (state->length == 0) state->mode = LEN; - break; - case LIT: - if (left == 0) goto inf_leave; - *put++ = (unsigned char)(state->length); - left--; - state->mode = LEN; - break; - case CHECK: - if (state->wrap) { - NEEDBITS(32); - out -= left; - strm->total_out += out; - state->total += out; - if (out) - strm->adler = state->check = - UPDATE(state->check, put - out, out); - out = left; - if (( -#ifdef GUNZIP - state->flags ? hold : -#endif - REVERSE(hold)) != state->check) { - strm->msg = (char *)"incorrect data check"; - state->mode = BAD; - break; - } - INITBITS(); - Tracev((stderr, "inflate: check matches trailer\n")); - } -#ifdef GUNZIP - state->mode = LENGTH; - case LENGTH: - if (state->wrap && state->flags) { - NEEDBITS(32); - if (hold != (state->total & 0xffffffffUL)) { - strm->msg = (char *)"incorrect length check"; - state->mode = BAD; - break; - } - INITBITS(); - Tracev((stderr, "inflate: length matches trailer\n")); - } -#endif - state->mode = DONE; - case DONE: - ret = Z_STREAM_END; - goto inf_leave; - case BAD: - ret = Z_DATA_ERROR; - goto inf_leave; - case MEM: - return Z_MEM_ERROR; - case SYNC: - default: - return Z_STREAM_ERROR; - } - - /* - Return from inflate(), updating the total counts and the check value. - If there was no progress during the inflate() call, return a buffer - error. Call updatewindow() to create and/or update the window state. - Note: a memory error from inflate() is non-recoverable. - */ - inf_leave: - RESTORE(); - if (state->wsize || (state->mode < CHECK && out != strm->avail_out)) - if (updatewindow(strm, out)) { - state->mode = MEM; - return Z_MEM_ERROR; - } - in -= strm->avail_in; - out -= strm->avail_out; - strm->total_in += in; - strm->total_out += out; - state->total += out; - if (state->wrap && out) - strm->adler = state->check = - UPDATE(state->check, strm->next_out - out, out); - strm->data_type = state->bits + (state->last ? 64 : 0) + - (state->mode == TYPE ? 128 : 0) + - (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0); - if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK) - ret = Z_BUF_ERROR; - return ret; -} - -int ZEXPORT inflateEnd(strm) -z_streamp strm; -{ - struct inflate_state FAR *state; - if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) - return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - if (state->window != Z_NULL) ZFREE(strm, state->window); - ZFREE(strm, strm->state); - strm->state = Z_NULL; - Tracev((stderr, "inflate: end\n")); - return Z_OK; -} - -int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength) -z_streamp strm; -const Bytef *dictionary; -uInt dictLength; -{ - struct inflate_state FAR *state; - unsigned long id; - - /* check state */ - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - if (state->wrap != 0 && state->mode != DICT) - return Z_STREAM_ERROR; - - /* check for correct dictionary id */ - if (state->mode == DICT) { - id = adler32(0L, Z_NULL, 0); - id = adler32(id, dictionary, dictLength); - if (id != state->check) - return Z_DATA_ERROR; - } - - /* copy dictionary to window */ - if (updatewindow(strm, strm->avail_out)) { - state->mode = MEM; - return Z_MEM_ERROR; - } - if (dictLength > state->wsize) { - zmemcpy(state->window, dictionary + dictLength - state->wsize, - state->wsize); - state->whave = state->wsize; - } - else { - zmemcpy(state->window + state->wsize - dictLength, dictionary, - dictLength); - state->whave = dictLength; - } - state->havedict = 1; - Tracev((stderr, "inflate: dictionary set\n")); - return Z_OK; -} - -int ZEXPORT inflateGetHeader(strm, head) -z_streamp strm; -gz_headerp head; -{ - struct inflate_state FAR *state; - - /* check state */ - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - if ((state->wrap & 2) == 0) return Z_STREAM_ERROR; - - /* save header structure */ - state->head = head; - head->done = 0; - return Z_OK; -} - -/* - Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found - or when out of input. When called, *have is the number of pattern bytes - found in order so far, in 0..3. On return *have is updated to the new - state. If on return *have equals four, then the pattern was found and the - return value is how many bytes were read including the last byte of the - pattern. If *have is less than four, then the pattern has not been found - yet and the return value is len. In the latter case, syncsearch() can be - called again with more data and the *have state. *have is initialized to - zero for the first call. - */ -local unsigned syncsearch(have, buf, len) -unsigned FAR *have; -unsigned char FAR *buf; -unsigned len; -{ - unsigned got; - unsigned next; - - got = *have; - next = 0; - while (next < len && got < 4) { - if ((int)(buf[next]) == (got < 2 ? 0 : 0xff)) - got++; - else if (buf[next]) - got = 0; - else - got = 4 - got; - next++; - } - *have = got; - return next; -} - -int ZEXPORT inflateSync(strm) -z_streamp strm; -{ - unsigned len; /* number of bytes to look at or looked at */ - unsigned long in, out; /* temporary to save total_in and total_out */ - unsigned char buf[4]; /* to restore bit buffer to byte string */ - struct inflate_state FAR *state; - - /* check parameters */ - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR; - - /* if first time, start search in bit buffer */ - if (state->mode != SYNC) { - state->mode = SYNC; - state->hold <<= state->bits & 7; - state->bits -= state->bits & 7; - len = 0; - while (state->bits >= 8) { - buf[len++] = (unsigned char)(state->hold); - state->hold >>= 8; - state->bits -= 8; - } - state->have = 0; - syncsearch(&(state->have), buf, len); - } - - /* search available input */ - len = syncsearch(&(state->have), strm->next_in, strm->avail_in); - strm->avail_in -= len; - strm->next_in += len; - strm->total_in += len; - - /* return no joy or set up to restart inflate() on a new block */ - if (state->have != 4) return Z_DATA_ERROR; - in = strm->total_in; out = strm->total_out; - inflateReset(strm); - strm->total_in = in; strm->total_out = out; - state->mode = TYPE; - return Z_OK; -} - -/* - Returns true if inflate is currently at the end of a block generated by - Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP - implementation to provide an additional safety check. PPP uses - Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored - block. When decompressing, PPP checks that at the end of input packet, - inflate is waiting for these length bytes. - */ -int ZEXPORT inflateSyncPoint(strm) -z_streamp strm; -{ - struct inflate_state FAR *state; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - return state->mode == STORED && state->bits == 0; -} - -int ZEXPORT inflateCopy(dest, source) -z_streamp dest; -z_streamp source; -{ - struct inflate_state FAR *state; - struct inflate_state FAR *copy; - unsigned char FAR *window; - unsigned wsize; - - /* check input */ - if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL || - source->zalloc == (alloc_func)0 || source->zfree == (free_func)0) - return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)source->state; - - /* allocate space */ - copy = (struct inflate_state FAR *) - ZALLOC(source, 1, sizeof(struct inflate_state)); - if (copy == Z_NULL) return Z_MEM_ERROR; - window = Z_NULL; - if (state->window != Z_NULL) { - window = (unsigned char FAR *) - ZALLOC(source, 1U << state->wbits, sizeof(unsigned char)); - if (window == Z_NULL) { - ZFREE(source, copy); - return Z_MEM_ERROR; - } - } - - /* copy state */ - zmemcpy(dest, source, sizeof(z_stream)); - zmemcpy(copy, state, sizeof(struct inflate_state)); - if (state->lencode >= state->codes && - state->lencode <= state->codes + ENOUGH - 1) { - copy->lencode = copy->codes + (state->lencode - state->codes); - copy->distcode = copy->codes + (state->distcode - state->codes); - } - copy->next = copy->codes + (state->next - state->codes); - if (window != Z_NULL) { - wsize = 1U << state->wbits; - zmemcpy(window, state->window, wsize); - } - copy->window = window; - dest->state = (struct internal_state FAR *)copy; - return Z_OK; -} - -int ZEXPORT inflateUndermine(strm, subvert) -z_streamp strm; -int subvert; -{ - struct inflate_state FAR *state; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - state->sane = !subvert; -#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR - return Z_OK; -#else - state->sane = 1; - return Z_DATA_ERROR; -#endif -} - -long ZEXPORT inflateMark(strm) -z_streamp strm; -{ - struct inflate_state FAR *state; - - if (strm == Z_NULL || strm->state == Z_NULL) return -1L << 16; - state = (struct inflate_state FAR *)strm->state; - return ((long)(state->back) << 16) + - (state->mode == COPY ? state->length : - (state->mode == MATCH ? state->was - state->length : 0)); -} diff --git a/externals/zlib/inflate.h b/externals/zlib/inflate.h deleted file mode 100644 index 95f4986d400..00000000000 --- a/externals/zlib/inflate.h +++ /dev/null @@ -1,122 +0,0 @@ -/* inflate.h -- internal inflate state definition - * Copyright (C) 1995-2009 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -/* define NO_GZIP when compiling if you want to disable gzip header and - trailer decoding by inflate(). NO_GZIP would be used to avoid linking in - the crc code when it is not needed. For shared libraries, gzip decoding - should be left enabled. */ -#ifndef NO_GZIP -# define GUNZIP -#endif - -/* Possible inflate modes between inflate() calls */ -typedef enum { - HEAD, /* i: waiting for magic header */ - FLAGS, /* i: waiting for method and flags (gzip) */ - TIME, /* i: waiting for modification time (gzip) */ - OS, /* i: waiting for extra flags and operating system (gzip) */ - EXLEN, /* i: waiting for extra length (gzip) */ - EXTRA, /* i: waiting for extra bytes (gzip) */ - NAME, /* i: waiting for end of file name (gzip) */ - COMMENT, /* i: waiting for end of comment (gzip) */ - HCRC, /* i: waiting for header crc (gzip) */ - DICTID, /* i: waiting for dictionary check value */ - DICT, /* waiting for inflateSetDictionary() call */ - TYPE, /* i: waiting for type bits, including last-flag bit */ - TYPEDO, /* i: same, but skip check to exit inflate on new block */ - STORED, /* i: waiting for stored size (length and complement) */ - COPY_, /* i/o: same as COPY below, but only first time in */ - COPY, /* i/o: waiting for input or output to copy stored block */ - TABLE, /* i: waiting for dynamic block table lengths */ - LENLENS, /* i: waiting for code length code lengths */ - CODELENS, /* i: waiting for length/lit and distance code lengths */ - LEN_, /* i: same as LEN below, but only first time in */ - LEN, /* i: waiting for length/lit/eob code */ - LENEXT, /* i: waiting for length extra bits */ - DIST, /* i: waiting for distance code */ - DISTEXT, /* i: waiting for distance extra bits */ - MATCH, /* o: waiting for output space to copy string */ - LIT, /* o: waiting for output space to write literal */ - CHECK, /* i: waiting for 32-bit check value */ - LENGTH, /* i: waiting for 32-bit length (gzip) */ - DONE, /* finished check, done -- remain here until reset */ - BAD, /* got a data error -- remain here until reset */ - MEM, /* got an inflate() memory error -- remain here until reset */ - SYNC /* looking for synchronization bytes to restart inflate() */ -} inflate_mode; - -/* - State transitions between above modes - - - (most modes can go to BAD or MEM on error -- not shown for clarity) - - Process header: - HEAD -> (gzip) or (zlib) or (raw) - (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME -> COMMENT -> - HCRC -> TYPE - (zlib) -> DICTID or TYPE - DICTID -> DICT -> TYPE - (raw) -> TYPEDO - Read deflate blocks: - TYPE -> TYPEDO -> STORED or TABLE or LEN_ or CHECK - STORED -> COPY_ -> COPY -> TYPE - TABLE -> LENLENS -> CODELENS -> LEN_ - LEN_ -> LEN - Read deflate codes in fixed or dynamic block: - LEN -> LENEXT or LIT or TYPE - LENEXT -> DIST -> DISTEXT -> MATCH -> LEN - LIT -> LEN - Process trailer: - CHECK -> LENGTH -> DONE - */ - -/* state maintained between inflate() calls. Approximately 10K bytes. */ -struct inflate_state { - inflate_mode mode; /* current inflate mode */ - int last; /* true if processing last block */ - int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ - int havedict; /* true if dictionary provided */ - int flags; /* gzip header method and flags (0 if zlib) */ - unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */ - unsigned long check; /* protected copy of check value */ - unsigned long total; /* protected copy of output count */ - gz_headerp head; /* where to save gzip header information */ - /* sliding window */ - unsigned wbits; /* log base 2 of requested window size */ - unsigned wsize; /* window size or zero if not using window */ - unsigned whave; /* valid bytes in the window */ - unsigned wnext; /* window write index */ - unsigned char FAR *window; /* allocated sliding window, if needed */ - /* bit accumulator */ - unsigned long hold; /* input bit accumulator */ - unsigned bits; /* number of bits in "in" */ - /* for string and stored block copying */ - unsigned length; /* literal or length of data to copy */ - unsigned offset; /* distance back to copy string from */ - /* for table and code decoding */ - unsigned extra; /* extra bits needed */ - /* fixed and dynamic code tables */ - code const FAR *lencode; /* starting table for length/literal codes */ - code const FAR *distcode; /* starting table for distance codes */ - unsigned lenbits; /* index bits for lencode */ - unsigned distbits; /* index bits for distcode */ - /* dynamic table building */ - unsigned ncode; /* number of code length code lengths */ - unsigned nlen; /* number of length code lengths */ - unsigned ndist; /* number of distance code lengths */ - unsigned have; /* number of code lengths in lens[] */ - code FAR *next; /* next available space in codes[] */ - unsigned short lens[320]; /* temporary storage for code lengths */ - unsigned short work[288]; /* work area for code table building */ - code codes[ENOUGH]; /* space for code tables */ - int sane; /* if false, allow invalid distance too far */ - int back; /* bits back of last unprocessed length/lit */ - unsigned was; /* initial length of match */ -}; diff --git a/externals/zlib/inftrees.c b/externals/zlib/inftrees.c deleted file mode 100644 index 11e9c52accb..00000000000 --- a/externals/zlib/inftrees.c +++ /dev/null @@ -1,330 +0,0 @@ -/* inftrees.c -- generate Huffman trees for efficient decoding - * Copyright (C) 1995-2010 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -#include "zutil.h" -#include "inftrees.h" - -#define MAXBITS 15 - -const char inflate_copyright[] = - " inflate 1.2.5 Copyright 1995-2010 Mark Adler "; -/* - If you use the zlib library in a product, an acknowledgment is welcome - in the documentation of your product. If for some reason you cannot - include such an acknowledgment, I would appreciate that you keep this - copyright string in the executable of your product. - */ - -/* - Build a set of tables to decode the provided canonical Huffman code. - The code lengths are lens[0..codes-1]. The result starts at *table, - whose indices are 0..2^bits-1. work is a writable array of at least - lens shorts, which is used as a work area. type is the type of code - to be generated, CODES, LENS, or DISTS. On return, zero is success, - -1 is an invalid code, and +1 means that ENOUGH isn't enough. table - on return points to the next available entry's address. bits is the - requested root table index bits, and on return it is the actual root - table index bits. It will differ if the request is greater than the - longest code or if it is less than the shortest code. - */ -int ZLIB_INTERNAL inflate_table(type, lens, codes, table, bits, work) -codetype type; -unsigned short FAR *lens; -unsigned codes; -code FAR * FAR *table; -unsigned FAR *bits; -unsigned short FAR *work; -{ - unsigned len; /* a code's length in bits */ - unsigned sym; /* index of code symbols */ - unsigned min, max; /* minimum and maximum code lengths */ - unsigned root; /* number of index bits for root table */ - unsigned curr; /* number of index bits for current table */ - unsigned drop; /* code bits to drop for sub-table */ - int left; /* number of prefix codes available */ - unsigned used; /* code entries in table used */ - unsigned huff; /* Huffman code */ - unsigned incr; /* for incrementing code, index */ - unsigned fill; /* index for replicating entries */ - unsigned low; /* low bits for current root entry */ - unsigned mask; /* mask for low root bits */ - code here; /* table entry for duplication */ - code FAR *next; /* next available space in table */ - const unsigned short FAR *base; /* base value table to use */ - const unsigned short FAR *extra; /* extra bits table to use */ - int end; /* use base and extra for symbol > end */ - unsigned short count[MAXBITS+1]; /* number of codes of each length */ - unsigned short offs[MAXBITS+1]; /* offsets in table for each length */ - static const unsigned short lbase[31] = { /* Length codes 257..285 base */ - 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, - 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; - static const unsigned short lext[31] = { /* Length codes 257..285 extra */ - 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, - 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 73, 195}; - static const unsigned short dbase[32] = { /* Distance codes 0..29 base */ - 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, - 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, - 8193, 12289, 16385, 24577, 0, 0}; - static const unsigned short dext[32] = { /* Distance codes 0..29 extra */ - 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, - 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, - 28, 28, 29, 29, 64, 64}; - - /* - Process a set of code lengths to create a canonical Huffman code. The - code lengths are lens[0..codes-1]. Each length corresponds to the - symbols 0..codes-1. The Huffman code is generated by first sorting the - symbols by length from short to long, and retaining the symbol order - for codes with equal lengths. Then the code starts with all zero bits - for the first code of the shortest length, and the codes are integer - increments for the same length, and zeros are appended as the length - increases. For the deflate format, these bits are stored backwards - from their more natural integer increment ordering, and so when the - decoding tables are built in the large loop below, the integer codes - are incremented backwards. - - This routine assumes, but does not check, that all of the entries in - lens[] are in the range 0..MAXBITS. The caller must assure this. - 1..MAXBITS is interpreted as that code length. zero means that that - symbol does not occur in this code. - - The codes are sorted by computing a count of codes for each length, - creating from that a table of starting indices for each length in the - sorted table, and then entering the symbols in order in the sorted - table. The sorted table is work[], with that space being provided by - the caller. - - The length counts are used for other purposes as well, i.e. finding - the minimum and maximum length codes, determining if there are any - codes at all, checking for a valid set of lengths, and looking ahead - at length counts to determine sub-table sizes when building the - decoding tables. - */ - - /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ - for (len = 0; len <= MAXBITS; len++) - count[len] = 0; - for (sym = 0; sym < codes; sym++) - count[lens[sym]]++; - - /* bound code lengths, force root to be within code lengths */ - root = *bits; - for (max = MAXBITS; max >= 1; max--) - if (count[max] != 0) break; - if (root > max) root = max; - if (max == 0) { /* no symbols to code at all */ - here.op = (unsigned char)64; /* invalid code marker */ - here.bits = (unsigned char)1; - here.val = (unsigned short)0; - *(*table)++ = here; /* make a table to force an error */ - *(*table)++ = here; - *bits = 1; - return 0; /* no symbols, but wait for decoding to report error */ - } - for (min = 1; min < max; min++) - if (count[min] != 0) break; - if (root < min) root = min; - - /* check for an over-subscribed or incomplete set of lengths */ - left = 1; - for (len = 1; len <= MAXBITS; len++) { - left <<= 1; - left -= count[len]; - if (left < 0) return -1; /* over-subscribed */ - } - if (left > 0 && (type == CODES || max != 1)) - return -1; /* incomplete set */ - - /* generate offsets into symbol table for each length for sorting */ - offs[1] = 0; - for (len = 1; len < MAXBITS; len++) - offs[len + 1] = offs[len] + count[len]; - - /* sort symbols by length, by symbol order within each length */ - for (sym = 0; sym < codes; sym++) - if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym; - - /* - Create and fill in decoding tables. In this loop, the table being - filled is at next and has curr index bits. The code being used is huff - with length len. That code is converted to an index by dropping drop - bits off of the bottom. For codes where len is less than drop + curr, - those top drop + curr - len bits are incremented through all values to - fill the table with replicated entries. - - root is the number of index bits for the root table. When len exceeds - root, sub-tables are created pointed to by the root entry with an index - of the low root bits of huff. This is saved in low to check for when a - new sub-table should be started. drop is zero when the root table is - being filled, and drop is root when sub-tables are being filled. - - When a new sub-table is needed, it is necessary to look ahead in the - code lengths to determine what size sub-table is needed. The length - counts are used for this, and so count[] is decremented as codes are - entered in the tables. - - used keeps track of how many table entries have been allocated from the - provided *table space. It is checked for LENS and DIST tables against - the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in - the initial root table size constants. See the comments in inftrees.h - for more information. - - sym increments through all symbols, and the loop terminates when - all codes of length max, i.e. all codes, have been processed. This - routine permits incomplete codes, so another loop after this one fills - in the rest of the decoding tables with invalid code markers. - */ - - /* set up for code type */ - switch (type) { - case CODES: - base = extra = work; /* dummy value--not used */ - end = 19; - break; - case LENS: - base = lbase; - base -= 257; - extra = lext; - extra -= 257; - end = 256; - break; - default: /* DISTS */ - base = dbase; - extra = dext; - end = -1; - } - - /* initialize state for loop */ - huff = 0; /* starting code */ - sym = 0; /* starting code symbol */ - len = min; /* starting code length */ - next = *table; /* current table to fill in */ - curr = root; /* current table index bits */ - drop = 0; /* current bits to drop from code for index */ - low = (unsigned)(-1); /* trigger new sub-table when len > root */ - used = 1U << root; /* use root table entries */ - mask = used - 1; /* mask for comparing low */ - - /* check available table space */ - if ((type == LENS && used >= ENOUGH_LENS) || - (type == DISTS && used >= ENOUGH_DISTS)) - return 1; - - /* process all codes and make table entries */ - for (;;) { - /* create table entry */ - here.bits = (unsigned char)(len - drop); - if ((int)(work[sym]) < end) { - here.op = (unsigned char)0; - here.val = work[sym]; - } - else if ((int)(work[sym]) > end) { - here.op = (unsigned char)(extra[work[sym]]); - here.val = base[work[sym]]; - } - else { - here.op = (unsigned char)(32 + 64); /* end of block */ - here.val = 0; - } - - /* replicate for those indices with low len bits equal to huff */ - incr = 1U << (len - drop); - fill = 1U << curr; - min = fill; /* save offset to next table */ - do { - fill -= incr; - next[(huff >> drop) + fill] = here; - } while (fill != 0); - - /* backwards increment the len-bit code huff */ - incr = 1U << (len - 1); - while (huff & incr) - incr >>= 1; - if (incr != 0) { - huff &= incr - 1; - huff += incr; - } - else - huff = 0; - - /* go to next symbol, update count, len */ - sym++; - if (--(count[len]) == 0) { - if (len == max) break; - len = lens[work[sym]]; - } - - /* create new sub-table if needed */ - if (len > root && (huff & mask) != low) { - /* if first time, transition to sub-tables */ - if (drop == 0) - drop = root; - - /* increment past last table */ - next += min; /* here min is 1 << curr */ - - /* determine length of next table */ - curr = len - drop; - left = (int)(1 << curr); - while (curr + drop < max) { - left -= count[curr + drop]; - if (left <= 0) break; - curr++; - left <<= 1; - } - - /* check for enough space */ - used += 1U << curr; - if ((type == LENS && used >= ENOUGH_LENS) || - (type == DISTS && used >= ENOUGH_DISTS)) - return 1; - - /* point entry in root table to sub-table */ - low = huff & mask; - (*table)[low].op = (unsigned char)curr; - (*table)[low].bits = (unsigned char)root; - (*table)[low].val = (unsigned short)(next - *table); - } - } - - /* - Fill in rest of table for incomplete codes. This loop is similar to the - loop above in incrementing huff for table indices. It is assumed that - len is equal to curr + drop, so there is no loop needed to increment - through high index bits. When the current sub-table is filled, the loop - drops back to the root table to fill in any remaining entries there. - */ - here.op = (unsigned char)64; /* invalid code marker */ - here.bits = (unsigned char)(len - drop); - here.val = (unsigned short)0; - while (huff != 0) { - /* when done with sub-table, drop back to root table */ - if (drop != 0 && (huff & mask) != low) { - drop = 0; - len = root; - next = *table; - here.bits = (unsigned char)len; - } - - /* put invalid code marker in table */ - next[huff >> drop] = here; - - /* backwards increment the len-bit code huff */ - incr = 1U << (len - 1); - while (huff & incr) - incr >>= 1; - if (incr != 0) { - huff &= incr - 1; - huff += incr; - } - else - huff = 0; - } - - /* set return parameters */ - *table += used; - *bits = root; - return 0; -} diff --git a/externals/zlib/inftrees.h b/externals/zlib/inftrees.h deleted file mode 100644 index baa53a0b1a1..00000000000 --- a/externals/zlib/inftrees.h +++ /dev/null @@ -1,62 +0,0 @@ -/* inftrees.h -- header to use inftrees.c - * Copyright (C) 1995-2005, 2010 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -/* Structure for decoding tables. Each entry provides either the - information needed to do the operation requested by the code that - indexed that table entry, or it provides a pointer to another - table that indexes more bits of the code. op indicates whether - the entry is a pointer to another table, a literal, a length or - distance, an end-of-block, or an invalid code. For a table - pointer, the low four bits of op is the number of index bits of - that table. For a length or distance, the low four bits of op - is the number of extra bits to get after the code. bits is - the number of bits in this code or part of the code to drop off - of the bit buffer. val is the actual byte to output in the case - of a literal, the base length or distance, or the offset from - the current table to the next table. Each entry is four bytes. */ -typedef struct { - unsigned char op; /* operation, extra bits, table bits */ - unsigned char bits; /* bits in this part of the code */ - unsigned short val; /* offset in table or code value */ -} code; - -/* op values as set by inflate_table(): - 00000000 - literal - 0000tttt - table link, tttt != 0 is the number of table index bits - 0001eeee - length or distance, eeee is the number of extra bits - 01100000 - end of block - 01000000 - invalid code - */ - -/* Maximum size of the dynamic table. The maximum number of code structures is - 1444, which is the sum of 852 for literal/length codes and 592 for distance - codes. These values were found by exhaustive searches using the program - examples/enough.c found in the zlib distribtution. The arguments to that - program are the number of symbols, the initial root table size, and the - maximum bit length of a code. "enough 286 9 15" for literal/length codes - returns returns 852, and "enough 30 6 15" for distance codes returns 592. - The initial root table size (9 or 6) is found in the fifth argument of the - inflate_table() calls in inflate.c and infback.c. If the root table size is - changed, then these maximum sizes would be need to be recalculated and - updated. */ -#define ENOUGH_LENS 852 -#define ENOUGH_DISTS 592 -#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS) - -/* Type of code to build for inflate_table() */ -typedef enum { - CODES, - LENS, - DISTS -} codetype; - -int ZLIB_INTERNAL inflate_table OF((codetype type, unsigned short FAR *lens, - unsigned codes, code FAR * FAR *table, - unsigned FAR *bits, unsigned short FAR *work)); diff --git a/externals/zlib/minigzip.c b/externals/zlib/minigzip.c deleted file mode 100644 index 9825ccc3a71..00000000000 --- a/externals/zlib/minigzip.c +++ /dev/null @@ -1,440 +0,0 @@ -/* minigzip.c -- simulate gzip using the zlib compression library - * Copyright (C) 1995-2006, 2010 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* - * minigzip is a minimal implementation of the gzip utility. This is - * only an example of using zlib and isn't meant to replace the - * full-featured gzip. No attempt is made to deal with file systems - * limiting names to 14 or 8+3 characters, etc... Error checking is - * very limited. So use minigzip only for testing; use gzip for the - * real thing. On MSDOS, use only on file names without extension - * or in pipe mode. - */ - -/* @(#) $Id$ */ - -#include "zlib.h" -#include - -#ifdef STDC -# include -# include -#endif - -#ifdef USE_MMAP -# include -# include -# include -#endif - -#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__) -# include -# include -# ifdef UNDER_CE -# include -# endif -# define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY) -#else -# define SET_BINARY_MODE(file) -#endif - -#ifdef VMS -# define unlink delete -# define GZ_SUFFIX "-gz" -#endif -#ifdef RISCOS -# define unlink remove -# define GZ_SUFFIX "-gz" -# define fileno(file) file->__file -#endif -#if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os -# include /* for fileno */ -#endif - -#if !defined(Z_HAVE_UNISTD_H) && !defined(_LARGEFILE64_SOURCE) -#ifndef WIN32 /* unlink already in stdio.h for WIN32 */ - extern int unlink OF((const char *)); -#endif -#endif - -#if defined(UNDER_CE) -# include -# define perror(s) pwinerror(s) - -/* Map the Windows error number in ERROR to a locale-dependent error - message string and return a pointer to it. Typically, the values - for ERROR come from GetLastError. - - The string pointed to shall not be modified by the application, - but may be overwritten by a subsequent call to strwinerror - - The strwinerror function does not change the current setting - of GetLastError. */ - -static char *strwinerror (error) - DWORD error; -{ - static char buf[1024]; - - wchar_t *msgbuf; - DWORD lasterr = GetLastError(); - DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM - | FORMAT_MESSAGE_ALLOCATE_BUFFER, - NULL, - error, - 0, /* Default language */ - (LPVOID)&msgbuf, - 0, - NULL); - if (chars != 0) { - /* If there is an \r\n appended, zap it. */ - if (chars >= 2 - && msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') { - chars -= 2; - msgbuf[chars] = 0; - } - - if (chars > sizeof (buf) - 1) { - chars = sizeof (buf) - 1; - msgbuf[chars] = 0; - } - - wcstombs(buf, msgbuf, chars + 1); - LocalFree(msgbuf); - } - else { - sprintf(buf, "unknown win32 error (%ld)", error); - } - - SetLastError(lasterr); - return buf; -} - -static void pwinerror (s) - const char *s; -{ - if (s && *s) - fprintf(stderr, "%s: %s\n", s, strwinerror(GetLastError ())); - else - fprintf(stderr, "%s\n", strwinerror(GetLastError ())); -} - -#endif /* UNDER_CE */ - -#ifndef GZ_SUFFIX -# define GZ_SUFFIX ".gz" -#endif -#define SUFFIX_LEN (sizeof(GZ_SUFFIX)-1) - -#define BUFLEN 16384 -#define MAX_NAME_LEN 1024 - -#ifdef MAXSEG_64K -# define local static - /* Needed for systems with limitation on stack size. */ -#else -# define local -#endif - -char *prog; - -void error OF((const char *msg)); -void gz_compress OF((FILE *in, gzFile out)); -#ifdef USE_MMAP -int gz_compress_mmap OF((FILE *in, gzFile out)); -#endif -void gz_uncompress OF((gzFile in, FILE *out)); -void file_compress OF((char *file, char *mode)); -void file_uncompress OF((char *file)); -int main OF((int argc, char *argv[])); - -/* =========================================================================== - * Display error message and exit - */ -void error(msg) - const char *msg; -{ - fprintf(stderr, "%s: %s\n", prog, msg); - exit(1); -} - -/* =========================================================================== - * Compress input to output then close both files. - */ - -void gz_compress(in, out) - FILE *in; - gzFile out; -{ - local char buf[BUFLEN]; - int len; - int err; - -#ifdef USE_MMAP - /* Try first compressing with mmap. If mmap fails (minigzip used in a - * pipe), use the normal fread loop. - */ - if (gz_compress_mmap(in, out) == Z_OK) return; -#endif - for (;;) { - len = (int)fread(buf, 1, sizeof(buf), in); - if (ferror(in)) { - perror("fread"); - exit(1); - } - if (len == 0) break; - - if (gzwrite(out, buf, (unsigned)len) != len) error(gzerror(out, &err)); - } - fclose(in); - if (gzclose(out) != Z_OK) error("failed gzclose"); -} - -#ifdef USE_MMAP /* MMAP version, Miguel Albrecht */ - -/* Try compressing the input file at once using mmap. Return Z_OK if - * if success, Z_ERRNO otherwise. - */ -int gz_compress_mmap(in, out) - FILE *in; - gzFile out; -{ - int len; - int err; - int ifd = fileno(in); - caddr_t buf; /* mmap'ed buffer for the entire input file */ - off_t buf_len; /* length of the input file */ - struct stat sb; - - /* Determine the size of the file, needed for mmap: */ - if (fstat(ifd, &sb) < 0) return Z_ERRNO; - buf_len = sb.st_size; - if (buf_len <= 0) return Z_ERRNO; - - /* Now do the actual mmap: */ - buf = mmap((caddr_t) 0, buf_len, PROT_READ, MAP_SHARED, ifd, (off_t)0); - if (buf == (caddr_t)(-1)) return Z_ERRNO; - - /* Compress the whole file at once: */ - len = gzwrite(out, (char *)buf, (unsigned)buf_len); - - if (len != (int)buf_len) error(gzerror(out, &err)); - - munmap(buf, buf_len); - fclose(in); - if (gzclose(out) != Z_OK) error("failed gzclose"); - return Z_OK; -} -#endif /* USE_MMAP */ - -/* =========================================================================== - * Uncompress input to output then close both files. - */ -void gz_uncompress(in, out) - gzFile in; - FILE *out; -{ - local char buf[BUFLEN]; - int len; - int err; - - for (;;) { - len = gzread(in, buf, sizeof(buf)); - if (len < 0) error (gzerror(in, &err)); - if (len == 0) break; - - if ((int)fwrite(buf, 1, (unsigned)len, out) != len) { - error("failed fwrite"); - } - } - if (fclose(out)) error("failed fclose"); - - if (gzclose(in) != Z_OK) error("failed gzclose"); -} - - -/* =========================================================================== - * Compress the given file: create a corresponding .gz file and remove the - * original. - */ -void file_compress(file, mode) - char *file; - char *mode; -{ - local char outfile[MAX_NAME_LEN]; - FILE *in; - gzFile out; - - if (strlen(file) + strlen(GZ_SUFFIX) >= sizeof(outfile)) { - fprintf(stderr, "%s: filename too long\n", prog); - exit(1); - } - - strcpy(outfile, file); - strcat(outfile, GZ_SUFFIX); - - in = fopen(file, "rb"); - if (in == NULL) { - perror(file); - exit(1); - } - out = gzopen(outfile, mode); - if (out == NULL) { - fprintf(stderr, "%s: can't gzopen %s\n", prog, outfile); - exit(1); - } - gz_compress(in, out); - - unlink(file); -} - - -/* =========================================================================== - * Uncompress the given file and remove the original. - */ -void file_uncompress(file) - char *file; -{ - local char buf[MAX_NAME_LEN]; - char *infile, *outfile; - FILE *out; - gzFile in; - size_t len = strlen(file); - - if (len + strlen(GZ_SUFFIX) >= sizeof(buf)) { - fprintf(stderr, "%s: filename too long\n", prog); - exit(1); - } - - strcpy(buf, file); - - if (len > SUFFIX_LEN && strcmp(file+len-SUFFIX_LEN, GZ_SUFFIX) == 0) { - infile = file; - outfile = buf; - outfile[len-3] = '\0'; - } else { - outfile = file; - infile = buf; - strcat(infile, GZ_SUFFIX); - } - in = gzopen(infile, "rb"); - if (in == NULL) { - fprintf(stderr, "%s: can't gzopen %s\n", prog, infile); - exit(1); - } - out = fopen(outfile, "wb"); - if (out == NULL) { - perror(file); - exit(1); - } - - gz_uncompress(in, out); - - unlink(infile); -} - - -/* =========================================================================== - * Usage: minigzip [-c] [-d] [-f] [-h] [-r] [-1 to -9] [files...] - * -c : write to standard output - * -d : decompress - * -f : compress with Z_FILTERED - * -h : compress with Z_HUFFMAN_ONLY - * -r : compress with Z_RLE - * -1 to -9 : compression level - */ - -int main(argc, argv) - int argc; - char *argv[]; -{ - int copyout = 0; - int uncompr = 0; - gzFile file; - char *bname, outmode[20]; - - strcpy(outmode, "wb6 "); - - prog = argv[0]; - bname = strrchr(argv[0], '/'); - if (bname) - bname++; - else - bname = argv[0]; - argc--, argv++; - - if (!strcmp(bname, "gunzip")) - uncompr = 1; - else if (!strcmp(bname, "zcat")) - copyout = uncompr = 1; - - while (argc > 0) { - if (strcmp(*argv, "-c") == 0) - copyout = 1; - else if (strcmp(*argv, "-d") == 0) - uncompr = 1; - else if (strcmp(*argv, "-f") == 0) - outmode[3] = 'f'; - else if (strcmp(*argv, "-h") == 0) - outmode[3] = 'h'; - else if (strcmp(*argv, "-r") == 0) - outmode[3] = 'R'; - else if ((*argv)[0] == '-' && (*argv)[1] >= '1' && (*argv)[1] <= '9' && - (*argv)[2] == 0) - outmode[2] = (*argv)[1]; - else - break; - argc--, argv++; - } - if (outmode[3] == ' ') - outmode[3] = 0; - if (argc == 0) { - SET_BINARY_MODE(stdin); - SET_BINARY_MODE(stdout); - if (uncompr) { - file = gzdopen(fileno(stdin), "rb"); - if (file == NULL) error("can't gzdopen stdin"); - gz_uncompress(file, stdout); - } else { - file = gzdopen(fileno(stdout), outmode); - if (file == NULL) error("can't gzdopen stdout"); - gz_compress(stdin, file); - } - } else { - if (copyout) { - SET_BINARY_MODE(stdout); - } - do { - if (uncompr) { - if (copyout) { - file = gzopen(*argv, "rb"); - if (file == NULL) - fprintf(stderr, "%s: can't gzopen %s\n", prog, *argv); - else - gz_uncompress(file, stdout); - } else { - file_uncompress(*argv); - } - } else { - if (copyout) { - FILE * in = fopen(*argv, "rb"); - - if (in == NULL) { - perror(*argv); - } else { - file = gzdopen(fileno(stdout), outmode); - if (file == NULL) error("can't gzdopen stdout"); - - gz_compress(in, file); - } - - } else { - file_compress(*argv, outmode); - } - } - } while (argv++, --argc); - } - return 0; -} diff --git a/externals/zlib/trees.c b/externals/zlib/trees.c deleted file mode 100644 index 56e9bb1c115..00000000000 --- a/externals/zlib/trees.c +++ /dev/null @@ -1,1244 +0,0 @@ -/* trees.c -- output deflated data using Huffman coding - * Copyright (C) 1995-2010 Jean-loup Gailly - * detect_data_type() function provided freely by Cosmin Truta, 2006 - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* - * ALGORITHM - * - * The "deflation" process uses several Huffman trees. The more - * common source values are represented by shorter bit sequences. - * - * Each code tree is stored in a compressed form which is itself - * a Huffman encoding of the lengths of all the code strings (in - * ascending order by source values). The actual code strings are - * reconstructed from the lengths in the inflate process, as described - * in the deflate specification. - * - * REFERENCES - * - * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification". - * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc - * - * Storer, James A. - * Data Compression: Methods and Theory, pp. 49-50. - * Computer Science Press, 1988. ISBN 0-7167-8156-5. - * - * Sedgewick, R. - * Algorithms, p290. - * Addison-Wesley, 1983. ISBN 0-201-06672-6. - */ - -/* @(#) $Id$ */ - -/* #define GEN_TREES_H */ - -#include "deflate.h" - -#ifdef DEBUG -# include -#endif - -/* =========================================================================== - * Constants - */ - -#define MAX_BL_BITS 7 -/* Bit length codes must not exceed MAX_BL_BITS bits */ - -#define END_BLOCK 256 -/* end of block literal code */ - -#define REP_3_6 16 -/* repeat previous bit length 3-6 times (2 bits of repeat count) */ - -#define REPZ_3_10 17 -/* repeat a zero length 3-10 times (3 bits of repeat count) */ - -#define REPZ_11_138 18 -/* repeat a zero length 11-138 times (7 bits of repeat count) */ - -local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */ - = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; - -local const int extra_dbits[D_CODES] /* extra bits for each distance code */ - = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; - -local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */ - = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; - -local const uch bl_order[BL_CODES] - = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; -/* The lengths of the bit length codes are sent in order of decreasing - * probability, to avoid transmitting the lengths for unused bit length codes. - */ - -#define Buf_size (8 * 2*sizeof(char)) -/* Number of bits used within bi_buf. (bi_buf might be implemented on - * more than 16 bits on some systems.) - */ - -/* =========================================================================== - * Local data. These are initialized only once. - */ - -#define DIST_CODE_LEN 512 /* see definition of array dist_code below */ - -#if defined(GEN_TREES_H) || !defined(STDC) -/* non ANSI compilers may not accept trees.h */ - -local ct_data static_ltree[L_CODES+2]; -/* The static literal tree. Since the bit lengths are imposed, there is no - * need for the L_CODES extra codes used during heap construction. However - * The codes 286 and 287 are needed to build a canonical tree (see _tr_init - * below). - */ - -local ct_data static_dtree[D_CODES]; -/* The static distance tree. (Actually a trivial tree since all codes use - * 5 bits.) - */ - -uch _dist_code[DIST_CODE_LEN]; -/* Distance codes. The first 256 values correspond to the distances - * 3 .. 258, the last 256 values correspond to the top 8 bits of - * the 15 bit distances. - */ - -uch _length_code[MAX_MATCH-MIN_MATCH+1]; -/* length code for each normalized match length (0 == MIN_MATCH) */ - -local int base_length[LENGTH_CODES]; -/* First normalized length for each code (0 = MIN_MATCH) */ - -local int base_dist[D_CODES]; -/* First normalized distance for each code (0 = distance of 1) */ - -#else -# include "trees.h" -#endif /* GEN_TREES_H */ - -struct static_tree_desc_s { - const ct_data *static_tree; /* static tree or NULL */ - const intf *extra_bits; /* extra bits for each code or NULL */ - int extra_base; /* base index for extra_bits */ - int elems; /* max number of elements in the tree */ - int max_length; /* max bit length for the codes */ -}; - -local static_tree_desc static_l_desc = -{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; - -local static_tree_desc static_d_desc = -{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; - -local static_tree_desc static_bl_desc = -{(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; - -/* =========================================================================== - * Local (static) routines in this file. - */ - -local void tr_static_init OF((void)); -local void init_block OF((deflate_state *s)); -local void pqdownheap OF((deflate_state *s, ct_data *tree, int k)); -local void gen_bitlen OF((deflate_state *s, tree_desc *desc)); -local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count)); -local void build_tree OF((deflate_state *s, tree_desc *desc)); -local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code)); -local void send_tree OF((deflate_state *s, ct_data *tree, int max_code)); -local int build_bl_tree OF((deflate_state *s)); -local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes, - int blcodes)); -local void compress_block OF((deflate_state *s, ct_data *ltree, - ct_data *dtree)); -local int detect_data_type OF((deflate_state *s)); -local unsigned bi_reverse OF((unsigned value, int length)); -local void bi_windup OF((deflate_state *s)); -local void bi_flush OF((deflate_state *s)); -local void copy_block OF((deflate_state *s, charf *buf, unsigned len, - int header)); - -#ifdef GEN_TREES_H -local void gen_trees_header OF((void)); -#endif - -#ifndef DEBUG -# define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len) - /* Send a code of the given tree. c and tree must not have side effects */ - -#else /* DEBUG */ -# define send_code(s, c, tree) \ - { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \ - send_bits(s, tree[c].Code, tree[c].Len); } -#endif - -/* =========================================================================== - * Output a short LSB first on the stream. - * IN assertion: there is enough room in pendingBuf. - */ -#define put_short(s, w) { \ - put_byte(s, (uch)((w) & 0xff)); \ - put_byte(s, (uch)((ush)(w) >> 8)); \ -} - -/* =========================================================================== - * Send a value on a given number of bits. - * IN assertion: length <= 16 and value fits in length bits. - */ -#ifdef DEBUG -local void send_bits OF((deflate_state *s, int value, int length)); - -local void send_bits(s, value, length) - deflate_state *s; - int value; /* value to send */ - int length; /* number of bits */ -{ - Tracevv((stderr," l %2d v %4x ", length, value)); - Assert(length > 0 && length <= 15, "invalid length"); - s->bits_sent += (ulg)length; - - /* If not enough room in bi_buf, use (valid) bits from bi_buf and - * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid)) - * unused bits in value. - */ - if (s->bi_valid > (int)Buf_size - length) { - s->bi_buf |= (ush)value << s->bi_valid; - put_short(s, s->bi_buf); - s->bi_buf = (ush)value >> (Buf_size - s->bi_valid); - s->bi_valid += length - Buf_size; - } else { - s->bi_buf |= (ush)value << s->bi_valid; - s->bi_valid += length; - } -} -#else /* !DEBUG */ - -#define send_bits(s, value, length) \ -{ int len = length;\ - if (s->bi_valid > (int)Buf_size - len) {\ - int val = value;\ - s->bi_buf |= (ush)val << s->bi_valid;\ - put_short(s, s->bi_buf);\ - s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\ - s->bi_valid += len - Buf_size;\ - } else {\ - s->bi_buf |= (ush)(value) << s->bi_valid;\ - s->bi_valid += len;\ - }\ -} -#endif /* DEBUG */ - - -/* the arguments must not have side effects */ - -/* =========================================================================== - * Initialize the various 'constant' tables. - */ -local void tr_static_init() -{ -#if defined(GEN_TREES_H) || !defined(STDC) - static int static_init_done = 0; - int n; /* iterates over tree elements */ - int bits; /* bit counter */ - int length; /* length value */ - int code; /* code value */ - int dist; /* distance index */ - ush bl_count[MAX_BITS+1]; - /* number of codes at each bit length for an optimal tree */ - - if (static_init_done) return; - - /* For some embedded targets, global variables are not initialized: */ -#ifdef NO_INIT_GLOBAL_POINTERS - static_l_desc.static_tree = static_ltree; - static_l_desc.extra_bits = extra_lbits; - static_d_desc.static_tree = static_dtree; - static_d_desc.extra_bits = extra_dbits; - static_bl_desc.extra_bits = extra_blbits; -#endif - - /* Initialize the mapping length (0..255) -> length code (0..28) */ - length = 0; - for (code = 0; code < LENGTH_CODES-1; code++) { - base_length[code] = length; - for (n = 0; n < (1< dist code (0..29) */ - dist = 0; - for (code = 0 ; code < 16; code++) { - base_dist[code] = dist; - for (n = 0; n < (1<>= 7; /* from now on, all distances are divided by 128 */ - for ( ; code < D_CODES; code++) { - base_dist[code] = dist << 7; - for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { - _dist_code[256 + dist++] = (uch)code; - } - } - Assert (dist == 256, "tr_static_init: 256+dist != 512"); - - /* Construct the codes of the static literal tree */ - for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; - n = 0; - while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; - while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; - while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; - while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; - /* Codes 286 and 287 do not exist, but we must include them in the - * tree construction to get a canonical Huffman tree (longest code - * all ones) - */ - gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count); - - /* The static distance tree is trivial: */ - for (n = 0; n < D_CODES; n++) { - static_dtree[n].Len = 5; - static_dtree[n].Code = bi_reverse((unsigned)n, 5); - } - static_init_done = 1; - -# ifdef GEN_TREES_H - gen_trees_header(); -# endif -#endif /* defined(GEN_TREES_H) || !defined(STDC) */ -} - -/* =========================================================================== - * Genererate the file trees.h describing the static trees. - */ -#ifdef GEN_TREES_H -# ifndef DEBUG -# include -# endif - -# define SEPARATOR(i, last, width) \ - ((i) == (last)? "\n};\n\n" : \ - ((i) % (width) == (width)-1 ? ",\n" : ", ")) - -void gen_trees_header() -{ - FILE *header = fopen("trees.h", "w"); - int i; - - Assert (header != NULL, "Can't open trees.h"); - fprintf(header, - "/* header created automatically with -DGEN_TREES_H */\n\n"); - - fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n"); - for (i = 0; i < L_CODES+2; i++) { - fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code, - static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5)); - } - - fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n"); - for (i = 0; i < D_CODES; i++) { - fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code, - static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5)); - } - - fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n"); - for (i = 0; i < DIST_CODE_LEN; i++) { - fprintf(header, "%2u%s", _dist_code[i], - SEPARATOR(i, DIST_CODE_LEN-1, 20)); - } - - fprintf(header, - "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); - for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) { - fprintf(header, "%2u%s", _length_code[i], - SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20)); - } - - fprintf(header, "local const int base_length[LENGTH_CODES] = {\n"); - for (i = 0; i < LENGTH_CODES; i++) { - fprintf(header, "%1u%s", base_length[i], - SEPARATOR(i, LENGTH_CODES-1, 20)); - } - - fprintf(header, "local const int base_dist[D_CODES] = {\n"); - for (i = 0; i < D_CODES; i++) { - fprintf(header, "%5u%s", base_dist[i], - SEPARATOR(i, D_CODES-1, 10)); - } - - fclose(header); -} -#endif /* GEN_TREES_H */ - -/* =========================================================================== - * Initialize the tree data structures for a new zlib stream. - */ -void ZLIB_INTERNAL _tr_init(s) - deflate_state *s; -{ - tr_static_init(); - - s->l_desc.dyn_tree = s->dyn_ltree; - s->l_desc.stat_desc = &static_l_desc; - - s->d_desc.dyn_tree = s->dyn_dtree; - s->d_desc.stat_desc = &static_d_desc; - - s->bl_desc.dyn_tree = s->bl_tree; - s->bl_desc.stat_desc = &static_bl_desc; - - s->bi_buf = 0; - s->bi_valid = 0; - s->last_eob_len = 8; /* enough lookahead for inflate */ -#ifdef DEBUG - s->compressed_len = 0L; - s->bits_sent = 0L; -#endif - - /* Initialize the first block of the first file: */ - init_block(s); -} - -/* =========================================================================== - * Initialize a new block. - */ -local void init_block(s) - deflate_state *s; -{ - int n; /* iterates over tree elements */ - - /* Initialize the trees. */ - for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; - for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; - for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; - - s->dyn_ltree[END_BLOCK].Freq = 1; - s->opt_len = s->static_len = 0L; - s->last_lit = s->matches = 0; -} - -#define SMALLEST 1 -/* Index within the heap array of least frequent node in the Huffman tree */ - - -/* =========================================================================== - * Remove the smallest element from the heap and recreate the heap with - * one less element. Updates heap and heap_len. - */ -#define pqremove(s, tree, top) \ -{\ - top = s->heap[SMALLEST]; \ - s->heap[SMALLEST] = s->heap[s->heap_len--]; \ - pqdownheap(s, tree, SMALLEST); \ -} - -/* =========================================================================== - * Compares to subtrees, using the tree depth as tie breaker when - * the subtrees have equal frequency. This minimizes the worst case length. - */ -#define smaller(tree, n, m, depth) \ - (tree[n].Freq < tree[m].Freq || \ - (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) - -/* =========================================================================== - * Restore the heap property by moving down the tree starting at node k, - * exchanging a node with the smallest of its two sons if necessary, stopping - * when the heap property is re-established (each father smaller than its - * two sons). - */ -local void pqdownheap(s, tree, k) - deflate_state *s; - ct_data *tree; /* the tree to restore */ - int k; /* node to move down */ -{ - int v = s->heap[k]; - int j = k << 1; /* left son of k */ - while (j <= s->heap_len) { - /* Set j to the smallest of the two sons: */ - if (j < s->heap_len && - smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { - j++; - } - /* Exit if v is smaller than both sons */ - if (smaller(tree, v, s->heap[j], s->depth)) break; - - /* Exchange v with the smallest son */ - s->heap[k] = s->heap[j]; k = j; - - /* And continue down the tree, setting j to the left son of k */ - j <<= 1; - } - s->heap[k] = v; -} - -/* =========================================================================== - * Compute the optimal bit lengths for a tree and update the total bit length - * for the current block. - * IN assertion: the fields freq and dad are set, heap[heap_max] and - * above are the tree nodes sorted by increasing frequency. - * OUT assertions: the field len is set to the optimal bit length, the - * array bl_count contains the frequencies for each bit length. - * The length opt_len is updated; static_len is also updated if stree is - * not null. - */ -local void gen_bitlen(s, desc) - deflate_state *s; - tree_desc *desc; /* the tree descriptor */ -{ - ct_data *tree = desc->dyn_tree; - int max_code = desc->max_code; - const ct_data *stree = desc->stat_desc->static_tree; - const intf *extra = desc->stat_desc->extra_bits; - int base = desc->stat_desc->extra_base; - int max_length = desc->stat_desc->max_length; - int h; /* heap index */ - int n, m; /* iterate over the tree elements */ - int bits; /* bit length */ - int xbits; /* extra bits */ - ush f; /* frequency */ - int overflow = 0; /* number of elements with bit length too large */ - - for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; - - /* In a first pass, compute the optimal bit lengths (which may - * overflow in the case of the bit length tree). - */ - tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ - - for (h = s->heap_max+1; h < HEAP_SIZE; h++) { - n = s->heap[h]; - bits = tree[tree[n].Dad].Len + 1; - if (bits > max_length) bits = max_length, overflow++; - tree[n].Len = (ush)bits; - /* We overwrite tree[n].Dad which is no longer needed */ - - if (n > max_code) continue; /* not a leaf node */ - - s->bl_count[bits]++; - xbits = 0; - if (n >= base) xbits = extra[n-base]; - f = tree[n].Freq; - s->opt_len += (ulg)f * (bits + xbits); - if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits); - } - if (overflow == 0) return; - - Trace((stderr,"\nbit length overflow\n")); - /* This happens for example on obj2 and pic of the Calgary corpus */ - - /* Find the first bit length which could increase: */ - do { - bits = max_length-1; - while (s->bl_count[bits] == 0) bits--; - s->bl_count[bits]--; /* move one leaf down the tree */ - s->bl_count[bits+1] += 2; /* move one overflow item as its brother */ - s->bl_count[max_length]--; - /* The brother of the overflow item also moves one step up, - * but this does not affect bl_count[max_length] - */ - overflow -= 2; - } while (overflow > 0); - - /* Now recompute all bit lengths, scanning in increasing frequency. - * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all - * lengths instead of fixing only the wrong ones. This idea is taken - * from 'ar' written by Haruhiko Okumura.) - */ - for (bits = max_length; bits != 0; bits--) { - n = s->bl_count[bits]; - while (n != 0) { - m = s->heap[--h]; - if (m > max_code) continue; - if ((unsigned) tree[m].Len != (unsigned) bits) { - Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); - s->opt_len += ((long)bits - (long)tree[m].Len) - *(long)tree[m].Freq; - tree[m].Len = (ush)bits; - } - n--; - } - } -} - -/* =========================================================================== - * Generate the codes for a given tree and bit counts (which need not be - * optimal). - * IN assertion: the array bl_count contains the bit length statistics for - * the given tree and the field len is set for all tree elements. - * OUT assertion: the field code is set for all tree elements of non - * zero code length. - */ -local void gen_codes (tree, max_code, bl_count) - ct_data *tree; /* the tree to decorate */ - int max_code; /* largest code with non zero frequency */ - ushf *bl_count; /* number of codes at each bit length */ -{ - ush next_code[MAX_BITS+1]; /* next code value for each bit length */ - ush code = 0; /* running code value */ - int bits; /* bit index */ - int n; /* code index */ - - /* The distribution counts are first used to generate the code values - * without bit reversal. - */ - for (bits = 1; bits <= MAX_BITS; bits++) { - next_code[bits] = code = (code + bl_count[bits-1]) << 1; - } - /* Check that the bit counts in bl_count are consistent. The last code - * must be all ones. - */ - Assert (code + bl_count[MAX_BITS]-1 == (1<dyn_tree; - const ct_data *stree = desc->stat_desc->static_tree; - int elems = desc->stat_desc->elems; - int n, m; /* iterate over heap elements */ - int max_code = -1; /* largest code with non zero frequency */ - int node; /* new node being created */ - - /* Construct the initial heap, with least frequent element in - * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. - * heap[0] is not used. - */ - s->heap_len = 0, s->heap_max = HEAP_SIZE; - - for (n = 0; n < elems; n++) { - if (tree[n].Freq != 0) { - s->heap[++(s->heap_len)] = max_code = n; - s->depth[n] = 0; - } else { - tree[n].Len = 0; - } - } - - /* The pkzip format requires that at least one distance code exists, - * and that at least one bit should be sent even if there is only one - * possible code. So to avoid special checks later on we force at least - * two codes of non zero frequency. - */ - while (s->heap_len < 2) { - node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0); - tree[node].Freq = 1; - s->depth[node] = 0; - s->opt_len--; if (stree) s->static_len -= stree[node].Len; - /* node is 0 or 1 so it does not have extra bits */ - } - desc->max_code = max_code; - - /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, - * establish sub-heaps of increasing lengths: - */ - for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); - - /* Construct the Huffman tree by repeatedly combining the least two - * frequent nodes. - */ - node = elems; /* next internal node of the tree */ - do { - pqremove(s, tree, n); /* n = node of least frequency */ - m = s->heap[SMALLEST]; /* m = node of next least frequency */ - - s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */ - s->heap[--(s->heap_max)] = m; - - /* Create a new node father of n and m */ - tree[node].Freq = tree[n].Freq + tree[m].Freq; - s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ? - s->depth[n] : s->depth[m]) + 1); - tree[n].Dad = tree[m].Dad = (ush)node; -#ifdef DUMP_BL_TREE - if (tree == s->bl_tree) { - fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)", - node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); - } -#endif - /* and insert the new node in the heap */ - s->heap[SMALLEST] = node++; - pqdownheap(s, tree, SMALLEST); - - } while (s->heap_len >= 2); - - s->heap[--(s->heap_max)] = s->heap[SMALLEST]; - - /* At this point, the fields freq and dad are set. We can now - * generate the bit lengths. - */ - gen_bitlen(s, (tree_desc *)desc); - - /* The field len is now set, we can generate the bit codes */ - gen_codes ((ct_data *)tree, max_code, s->bl_count); -} - -/* =========================================================================== - * Scan a literal or distance tree to determine the frequencies of the codes - * in the bit length tree. - */ -local void scan_tree (s, tree, max_code) - deflate_state *s; - ct_data *tree; /* the tree to be scanned */ - int max_code; /* and its largest code of non zero frequency */ -{ - int n; /* iterates over all tree elements */ - int prevlen = -1; /* last emitted length */ - int curlen; /* length of current code */ - int nextlen = tree[0].Len; /* length of next code */ - int count = 0; /* repeat count of the current code */ - int max_count = 7; /* max repeat count */ - int min_count = 4; /* min repeat count */ - - if (nextlen == 0) max_count = 138, min_count = 3; - tree[max_code+1].Len = (ush)0xffff; /* guard */ - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; nextlen = tree[n+1].Len; - if (++count < max_count && curlen == nextlen) { - continue; - } else if (count < min_count) { - s->bl_tree[curlen].Freq += count; - } else if (curlen != 0) { - if (curlen != prevlen) s->bl_tree[curlen].Freq++; - s->bl_tree[REP_3_6].Freq++; - } else if (count <= 10) { - s->bl_tree[REPZ_3_10].Freq++; - } else { - s->bl_tree[REPZ_11_138].Freq++; - } - count = 0; prevlen = curlen; - if (nextlen == 0) { - max_count = 138, min_count = 3; - } else if (curlen == nextlen) { - max_count = 6, min_count = 3; - } else { - max_count = 7, min_count = 4; - } - } -} - -/* =========================================================================== - * Send a literal or distance tree in compressed form, using the codes in - * bl_tree. - */ -local void send_tree (s, tree, max_code) - deflate_state *s; - ct_data *tree; /* the tree to be scanned */ - int max_code; /* and its largest code of non zero frequency */ -{ - int n; /* iterates over all tree elements */ - int prevlen = -1; /* last emitted length */ - int curlen; /* length of current code */ - int nextlen = tree[0].Len; /* length of next code */ - int count = 0; /* repeat count of the current code */ - int max_count = 7; /* max repeat count */ - int min_count = 4; /* min repeat count */ - - /* tree[max_code+1].Len = -1; */ /* guard already set */ - if (nextlen == 0) max_count = 138, min_count = 3; - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; nextlen = tree[n+1].Len; - if (++count < max_count && curlen == nextlen) { - continue; - } else if (count < min_count) { - do { send_code(s, curlen, s->bl_tree); } while (--count != 0); - - } else if (curlen != 0) { - if (curlen != prevlen) { - send_code(s, curlen, s->bl_tree); count--; - } - Assert(count >= 3 && count <= 6, " 3_6?"); - send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2); - - } else if (count <= 10) { - send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3); - - } else { - send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7); - } - count = 0; prevlen = curlen; - if (nextlen == 0) { - max_count = 138, min_count = 3; - } else if (curlen == nextlen) { - max_count = 6, min_count = 3; - } else { - max_count = 7, min_count = 4; - } - } -} - -/* =========================================================================== - * Construct the Huffman tree for the bit lengths and return the index in - * bl_order of the last bit length code to send. - */ -local int build_bl_tree(s) - deflate_state *s; -{ - int max_blindex; /* index of last bit length code of non zero freq */ - - /* Determine the bit length frequencies for literal and distance trees */ - scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); - scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); - - /* Build the bit length tree: */ - build_tree(s, (tree_desc *)(&(s->bl_desc))); - /* opt_len now includes the length of the tree representations, except - * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. - */ - - /* Determine the number of bit length codes to send. The pkzip format - * requires that at least 4 bit length codes be sent. (appnote.txt says - * 3 but the actual value used is 4.) - */ - for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { - if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; - } - /* Update opt_len to include the bit length tree and counts */ - s->opt_len += 3*(max_blindex+1) + 5+5+4; - Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", - s->opt_len, s->static_len)); - - return max_blindex; -} - -/* =========================================================================== - * Send the header for a block using dynamic Huffman trees: the counts, the - * lengths of the bit length codes, the literal tree and the distance tree. - * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. - */ -local void send_all_trees(s, lcodes, dcodes, blcodes) - deflate_state *s; - int lcodes, dcodes, blcodes; /* number of codes for each tree */ -{ - int rank; /* index in bl_order */ - - Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); - Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, - "too many codes"); - Tracev((stderr, "\nbl counts: ")); - send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ - send_bits(s, dcodes-1, 5); - send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ - for (rank = 0; rank < blcodes; rank++) { - Tracev((stderr, "\nbl code %2d ", bl_order[rank])); - send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); - } - Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); - - send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */ - Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); - - send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */ - Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); -} - -/* =========================================================================== - * Send a stored block - */ -void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last) - deflate_state *s; - charf *buf; /* input block */ - ulg stored_len; /* length of input block */ - int last; /* one if this is the last block for a file */ -{ - send_bits(s, (STORED_BLOCK<<1)+last, 3); /* send block type */ -#ifdef DEBUG - s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; - s->compressed_len += (stored_len + 4) << 3; -#endif - copy_block(s, buf, (unsigned)stored_len, 1); /* with header */ -} - -/* =========================================================================== - * Send one empty static block to give enough lookahead for inflate. - * This takes 10 bits, of which 7 may remain in the bit buffer. - * The current inflate code requires 9 bits of lookahead. If the - * last two codes for the previous block (real code plus EOB) were coded - * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode - * the last real code. In this case we send two empty static blocks instead - * of one. (There are no problems if the previous block is stored or fixed.) - * To simplify the code, we assume the worst case of last real code encoded - * on one bit only. - */ -void ZLIB_INTERNAL _tr_align(s) - deflate_state *s; -{ - send_bits(s, STATIC_TREES<<1, 3); - send_code(s, END_BLOCK, static_ltree); -#ifdef DEBUG - s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ -#endif - bi_flush(s); - /* Of the 10 bits for the empty block, we have already sent - * (10 - bi_valid) bits. The lookahead for the last real code (before - * the EOB of the previous block) was thus at least one plus the length - * of the EOB plus what we have just sent of the empty static block. - */ - if (1 + s->last_eob_len + 10 - s->bi_valid < 9) { - send_bits(s, STATIC_TREES<<1, 3); - send_code(s, END_BLOCK, static_ltree); -#ifdef DEBUG - s->compressed_len += 10L; -#endif - bi_flush(s); - } - s->last_eob_len = 7; -} - -/* =========================================================================== - * Determine the best encoding for the current block: dynamic trees, static - * trees or store, and output the encoded block to the zip file. - */ -void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) - deflate_state *s; - charf *buf; /* input block, or NULL if too old */ - ulg stored_len; /* length of input block */ - int last; /* one if this is the last block for a file */ -{ - ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ - int max_blindex = 0; /* index of last bit length code of non zero freq */ - - /* Build the Huffman trees unless a stored block is forced */ - if (s->level > 0) { - - /* Check if the file is binary or text */ - if (s->strm->data_type == Z_UNKNOWN) - s->strm->data_type = detect_data_type(s); - - /* Construct the literal and distance trees */ - build_tree(s, (tree_desc *)(&(s->l_desc))); - Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, - s->static_len)); - - build_tree(s, (tree_desc *)(&(s->d_desc))); - Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, - s->static_len)); - /* At this point, opt_len and static_len are the total bit lengths of - * the compressed block data, excluding the tree representations. - */ - - /* Build the bit length tree for the above two trees, and get the index - * in bl_order of the last bit length code to send. - */ - max_blindex = build_bl_tree(s); - - /* Determine the best encoding. Compute the block lengths in bytes. */ - opt_lenb = (s->opt_len+3+7)>>3; - static_lenb = (s->static_len+3+7)>>3; - - Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", - opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, - s->last_lit)); - - if (static_lenb <= opt_lenb) opt_lenb = static_lenb; - - } else { - Assert(buf != (char*)0, "lost buf"); - opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ - } - -#ifdef FORCE_STORED - if (buf != (char*)0) { /* force stored block */ -#else - if (stored_len+4 <= opt_lenb && buf != (char*)0) { - /* 4: two words for the lengths */ -#endif - /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. - * Otherwise we can't have processed more than WSIZE input bytes since - * the last block flush, because compression would have been - * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to - * transform a block into a stored block. - */ - _tr_stored_block(s, buf, stored_len, last); - -#ifdef FORCE_STATIC - } else if (static_lenb >= 0) { /* force static trees */ -#else - } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) { -#endif - send_bits(s, (STATIC_TREES<<1)+last, 3); - compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree); -#ifdef DEBUG - s->compressed_len += 3 + s->static_len; -#endif - } else { - send_bits(s, (DYN_TREES<<1)+last, 3); - send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, - max_blindex+1); - compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree); -#ifdef DEBUG - s->compressed_len += 3 + s->opt_len; -#endif - } - Assert (s->compressed_len == s->bits_sent, "bad compressed size"); - /* The above check is made mod 2^32, for files larger than 512 MB - * and uLong implemented on 32 bits. - */ - init_block(s); - - if (last) { - bi_windup(s); -#ifdef DEBUG - s->compressed_len += 7; /* align on byte boundary */ -#endif - } - Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, - s->compressed_len-7*last)); -} - -/* =========================================================================== - * Save the match info and tally the frequency counts. Return true if - * the current block must be flushed. - */ -int ZLIB_INTERNAL _tr_tally (s, dist, lc) - deflate_state *s; - unsigned dist; /* distance of matched string */ - unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ -{ - s->d_buf[s->last_lit] = (ush)dist; - s->l_buf[s->last_lit++] = (uch)lc; - if (dist == 0) { - /* lc is the unmatched char */ - s->dyn_ltree[lc].Freq++; - } else { - s->matches++; - /* Here, lc is the match length - MIN_MATCH */ - dist--; /* dist = match distance - 1 */ - Assert((ush)dist < (ush)MAX_DIST(s) && - (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && - (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); - - s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++; - s->dyn_dtree[d_code(dist)].Freq++; - } - -#ifdef TRUNCATE_BLOCK - /* Try to guess if it is profitable to stop the current block here */ - if ((s->last_lit & 0x1fff) == 0 && s->level > 2) { - /* Compute an upper bound for the compressed length */ - ulg out_length = (ulg)s->last_lit*8L; - ulg in_length = (ulg)((long)s->strstart - s->block_start); - int dcode; - for (dcode = 0; dcode < D_CODES; dcode++) { - out_length += (ulg)s->dyn_dtree[dcode].Freq * - (5L+extra_dbits[dcode]); - } - out_length >>= 3; - Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", - s->last_lit, in_length, out_length, - 100L - out_length*100L/in_length)); - if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1; - } -#endif - return (s->last_lit == s->lit_bufsize-1); - /* We avoid equality with lit_bufsize because of wraparound at 64K - * on 16 bit machines and because stored blocks are restricted to - * 64K-1 bytes. - */ -} - -/* =========================================================================== - * Send the block data compressed using the given Huffman trees - */ -local void compress_block(s, ltree, dtree) - deflate_state *s; - ct_data *ltree; /* literal tree */ - ct_data *dtree; /* distance tree */ -{ - unsigned dist; /* distance of matched string */ - int lc; /* match length or unmatched char (if dist == 0) */ - unsigned lx = 0; /* running index in l_buf */ - unsigned code; /* the code to send */ - int extra; /* number of extra bits to send */ - - if (s->last_lit != 0) do { - dist = s->d_buf[lx]; - lc = s->l_buf[lx++]; - if (dist == 0) { - send_code(s, lc, ltree); /* send a literal byte */ - Tracecv(isgraph(lc), (stderr," '%c' ", lc)); - } else { - /* Here, lc is the match length - MIN_MATCH */ - code = _length_code[lc]; - send_code(s, code+LITERALS+1, ltree); /* send the length code */ - extra = extra_lbits[code]; - if (extra != 0) { - lc -= base_length[code]; - send_bits(s, lc, extra); /* send the extra length bits */ - } - dist--; /* dist is now the match distance - 1 */ - code = d_code(dist); - Assert (code < D_CODES, "bad d_code"); - - send_code(s, code, dtree); /* send the distance code */ - extra = extra_dbits[code]; - if (extra != 0) { - dist -= base_dist[code]; - send_bits(s, dist, extra); /* send the extra distance bits */ - } - } /* literal or match pair ? */ - - /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ - Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, - "pendingBuf overflow"); - - } while (lx < s->last_lit); - - send_code(s, END_BLOCK, ltree); - s->last_eob_len = ltree[END_BLOCK].Len; -} - -/* =========================================================================== - * Check if the data type is TEXT or BINARY, using the following algorithm: - * - TEXT if the two conditions below are satisfied: - * a) There are no non-portable control characters belonging to the - * "black list" (0..6, 14..25, 28..31). - * b) There is at least one printable character belonging to the - * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). - * - BINARY otherwise. - * - The following partially-portable control characters form a - * "gray list" that is ignored in this detection algorithm: - * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). - * IN assertion: the fields Freq of dyn_ltree are set. - */ -local int detect_data_type(s) - deflate_state *s; -{ - /* black_mask is the bit mask of black-listed bytes - * set bits 0..6, 14..25, and 28..31 - * 0xf3ffc07f = binary 11110011111111111100000001111111 - */ - unsigned long black_mask = 0xf3ffc07fUL; - int n; - - /* Check for non-textual ("black-listed") bytes. */ - for (n = 0; n <= 31; n++, black_mask >>= 1) - if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0)) - return Z_BINARY; - - /* Check for textual ("white-listed") bytes. */ - if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0 - || s->dyn_ltree[13].Freq != 0) - return Z_TEXT; - for (n = 32; n < LITERALS; n++) - if (s->dyn_ltree[n].Freq != 0) - return Z_TEXT; - - /* There are no "black-listed" or "white-listed" bytes: - * this stream either is empty or has tolerated ("gray-listed") bytes only. - */ - return Z_BINARY; -} - -/* =========================================================================== - * Reverse the first len bits of a code, using straightforward code (a faster - * method would use a table) - * IN assertion: 1 <= len <= 15 - */ -local unsigned bi_reverse(code, len) - unsigned code; /* the value to invert */ - int len; /* its bit length */ -{ - register unsigned res = 0; - do { - res |= code & 1; - code >>= 1, res <<= 1; - } while (--len > 0); - return res >> 1; -} - -/* =========================================================================== - * Flush the bit buffer, keeping at most 7 bits in it. - */ -local void bi_flush(s) - deflate_state *s; -{ - if (s->bi_valid == 16) { - put_short(s, s->bi_buf); - s->bi_buf = 0; - s->bi_valid = 0; - } else if (s->bi_valid >= 8) { - put_byte(s, (Byte)s->bi_buf); - s->bi_buf >>= 8; - s->bi_valid -= 8; - } -} - -/* =========================================================================== - * Flush the bit buffer and align the output on a byte boundary - */ -local void bi_windup(s) - deflate_state *s; -{ - if (s->bi_valid > 8) { - put_short(s, s->bi_buf); - } else if (s->bi_valid > 0) { - put_byte(s, (Byte)s->bi_buf); - } - s->bi_buf = 0; - s->bi_valid = 0; -#ifdef DEBUG - s->bits_sent = (s->bits_sent+7) & ~7; -#endif -} - -/* =========================================================================== - * Copy a stored block, storing first the length and its - * one's complement if requested. - */ -local void copy_block(s, buf, len, header) - deflate_state *s; - charf *buf; /* the input data */ - unsigned len; /* its length */ - int header; /* true if block header must be written */ -{ - bi_windup(s); /* align on byte boundary */ - s->last_eob_len = 8; /* enough lookahead for inflate */ - - if (header) { - put_short(s, (ush)len); - put_short(s, (ush)~len); -#ifdef DEBUG - s->bits_sent += 2*16; -#endif - } -#ifdef DEBUG - s->bits_sent += (ulg)len<<3; -#endif - while (len--) { - put_byte(s, *buf++); - } -} diff --git a/externals/zlib/trees.h b/externals/zlib/trees.h deleted file mode 100644 index d35639d82a2..00000000000 --- a/externals/zlib/trees.h +++ /dev/null @@ -1,128 +0,0 @@ -/* header created automatically with -DGEN_TREES_H */ - -local const ct_data static_ltree[L_CODES+2] = { -{{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}}, -{{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}}, -{{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}}, -{{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}}, -{{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}}, -{{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}}, -{{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}}, -{{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}}, -{{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}}, -{{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}}, -{{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}}, -{{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}}, -{{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}}, -{{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}}, -{{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}}, -{{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}}, -{{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}}, -{{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}}, -{{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}}, -{{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}}, -{{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}}, -{{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}}, -{{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}}, -{{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}}, -{{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}}, -{{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}}, -{{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}}, -{{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}}, -{{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}}, -{{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}}, -{{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}}, -{{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}}, -{{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}}, -{{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}}, -{{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}}, -{{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}}, -{{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}}, -{{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}}, -{{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}}, -{{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}}, -{{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}}, -{{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}}, -{{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}}, -{{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}}, -{{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}}, -{{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}}, -{{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}}, -{{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}}, -{{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}}, -{{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}}, -{{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}}, -{{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}}, -{{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}}, -{{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}}, -{{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}}, -{{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}}, -{{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}}, -{{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}} -}; - -local const ct_data static_dtree[D_CODES] = { -{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}}, -{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}}, -{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}}, -{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}}, -{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}}, -{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}} -}; - -const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = { - 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, - 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, -10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, -11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, -12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, -13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, -13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, -14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, -14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, -14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, -15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, -15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, -15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, -18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, -23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, -24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, -26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, -26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, -27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, -27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, -28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, -28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, -28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, -29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, -29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, -29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 -}; - -const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= { - 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, -13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, -17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, -19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, -21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, -22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, -23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, -24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, -25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, -25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, -26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, -26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, -27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 -}; - -local const int base_length[LENGTH_CODES] = { -0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, -64, 80, 96, 112, 128, 160, 192, 224, 0 -}; - -local const int base_dist[D_CODES] = { - 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, - 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, - 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 -}; - diff --git a/externals/zlib/uncompr.c b/externals/zlib/uncompr.c deleted file mode 100644 index ad98be3a5d8..00000000000 --- a/externals/zlib/uncompr.c +++ /dev/null @@ -1,59 +0,0 @@ -/* uncompr.c -- decompress a memory buffer - * Copyright (C) 1995-2003, 2010 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#define ZLIB_INTERNAL -#include "zlib.h" - -/* =========================================================================== - Decompresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total - size of the destination buffer, which must be large enough to hold the - entire uncompressed data. (The size of the uncompressed data must have - been saved previously by the compressor and transmitted to the decompressor - by some mechanism outside the scope of this compression library.) - Upon exit, destLen is the actual size of the compressed buffer. - - uncompress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer, or Z_DATA_ERROR if the input data was corrupted. -*/ -int ZEXPORT uncompress (dest, destLen, source, sourceLen) - Bytef *dest; - uLongf *destLen; - const Bytef *source; - uLong sourceLen; -{ - z_stream stream; - int err; - - stream.next_in = (Bytef*)source; - stream.avail_in = (uInt)sourceLen; - /* Check for source > 64K on 16-bit machine: */ - if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; - - stream.next_out = dest; - stream.avail_out = (uInt)*destLen; - if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; - - stream.zalloc = (alloc_func)0; - stream.zfree = (free_func)0; - - err = inflateInit(&stream); - if (err != Z_OK) return err; - - err = inflate(&stream, Z_FINISH); - if (err != Z_STREAM_END) { - inflateEnd(&stream); - if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0)) - return Z_DATA_ERROR; - return err; - } - *destLen = stream.total_out; - - err = inflateEnd(&stream); - return err; -} diff --git a/externals/zlib/zconf.h b/externals/zlib/zconf.h deleted file mode 100644 index 02ce56c4313..00000000000 --- a/externals/zlib/zconf.h +++ /dev/null @@ -1,428 +0,0 @@ -/* zconf.h -- configuration of the zlib compression library - * Copyright (C) 1995-2010 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#ifndef ZCONF_H -#define ZCONF_H - -/* - * If you *really* need a unique prefix for all types and library functions, - * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. - * Even better than compiling with -DZ_PREFIX would be to use configure to set - * this permanently in zconf.h using "./configure --zprefix". - */ -#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ - -/* all linked symbols */ -# define _dist_code z__dist_code -# define _length_code z__length_code -# define _tr_align z__tr_align -# define _tr_flush_block z__tr_flush_block -# define _tr_init z__tr_init -# define _tr_stored_block z__tr_stored_block -# define _tr_tally z__tr_tally -# define adler32 z_adler32 -# define adler32_combine z_adler32_combine -# define adler32_combine64 z_adler32_combine64 -# define compress z_compress -# define compress2 z_compress2 -# define compressBound z_compressBound -# define crc32 z_crc32 -# define crc32_combine z_crc32_combine -# define crc32_combine64 z_crc32_combine64 -# define deflate z_deflate -# define deflateBound z_deflateBound -# define deflateCopy z_deflateCopy -# define deflateEnd z_deflateEnd -# define deflateInit2_ z_deflateInit2_ -# define deflateInit_ z_deflateInit_ -# define deflateParams z_deflateParams -# define deflatePrime z_deflatePrime -# define deflateReset z_deflateReset -# define deflateSetDictionary z_deflateSetDictionary -# define deflateSetHeader z_deflateSetHeader -# define deflateTune z_deflateTune -# define deflate_copyright z_deflate_copyright -# define get_crc_table z_get_crc_table -# define gz_error z_gz_error -# define gz_intmax z_gz_intmax -# define gz_strwinerror z_gz_strwinerror -# define gzbuffer z_gzbuffer -# define gzclearerr z_gzclearerr -# define gzclose z_gzclose -# define gzclose_r z_gzclose_r -# define gzclose_w z_gzclose_w -# define gzdirect z_gzdirect -# define gzdopen z_gzdopen -# define gzeof z_gzeof -# define gzerror z_gzerror -# define gzflush z_gzflush -# define gzgetc z_gzgetc -# define gzgets z_gzgets -# define gzoffset z_gzoffset -# define gzoffset64 z_gzoffset64 -# define gzopen z_gzopen -# define gzopen64 z_gzopen64 -# define gzprintf z_gzprintf -# define gzputc z_gzputc -# define gzputs z_gzputs -# define gzread z_gzread -# define gzrewind z_gzrewind -# define gzseek z_gzseek -# define gzseek64 z_gzseek64 -# define gzsetparams z_gzsetparams -# define gztell z_gztell -# define gztell64 z_gztell64 -# define gzungetc z_gzungetc -# define gzwrite z_gzwrite -# define inflate z_inflate -# define inflateBack z_inflateBack -# define inflateBackEnd z_inflateBackEnd -# define inflateBackInit_ z_inflateBackInit_ -# define inflateCopy z_inflateCopy -# define inflateEnd z_inflateEnd -# define inflateGetHeader z_inflateGetHeader -# define inflateInit2_ z_inflateInit2_ -# define inflateInit_ z_inflateInit_ -# define inflateMark z_inflateMark -# define inflatePrime z_inflatePrime -# define inflateReset z_inflateReset -# define inflateReset2 z_inflateReset2 -# define inflateSetDictionary z_inflateSetDictionary -# define inflateSync z_inflateSync -# define inflateSyncPoint z_inflateSyncPoint -# define inflateUndermine z_inflateUndermine -# define inflate_copyright z_inflate_copyright -# define inflate_fast z_inflate_fast -# define inflate_table z_inflate_table -# define uncompress z_uncompress -# define zError z_zError -# define zcalloc z_zcalloc -# define zcfree z_zcfree -# define zlibCompileFlags z_zlibCompileFlags -# define zlibVersion z_zlibVersion - -/* all zlib typedefs in zlib.h and zconf.h */ -# define Byte z_Byte -# define Bytef z_Bytef -# define alloc_func z_alloc_func -# define charf z_charf -# define free_func z_free_func -# define gzFile z_gzFile -# define gz_header z_gz_header -# define gz_headerp z_gz_headerp -# define in_func z_in_func -# define intf z_intf -# define out_func z_out_func -# define uInt z_uInt -# define uIntf z_uIntf -# define uLong z_uLong -# define uLongf z_uLongf -# define voidp z_voidp -# define voidpc z_voidpc -# define voidpf z_voidpf - -/* all zlib structs in zlib.h and zconf.h */ -# define gz_header_s z_gz_header_s -# define internal_state z_internal_state - -#endif - -#if defined(__MSDOS__) && !defined(MSDOS) -# define MSDOS -#endif -#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) -# define OS2 -#endif -#if defined(_WINDOWS) && !defined(WINDOWS) -# define WINDOWS -#endif -#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) -# ifndef WIN32 -# define WIN32 -# endif -#endif -#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) -# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) -# ifndef SYS16BIT -# define SYS16BIT -# endif -# endif -#endif - -/* - * Compile with -DMAXSEG_64K if the alloc function cannot allocate more - * than 64k bytes at a time (needed on systems with 16-bit int). - */ -#ifdef SYS16BIT -# define MAXSEG_64K -#endif -#ifdef MSDOS -# define UNALIGNED_OK -#endif - -#ifdef __STDC_VERSION__ -# ifndef STDC -# define STDC -# endif -# if __STDC_VERSION__ >= 199901L -# ifndef STDC99 -# define STDC99 -# endif -# endif -#endif -#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) -# define STDC -#endif -#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) -# define STDC -#endif -#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) -# define STDC -#endif -#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) -# define STDC -#endif - -#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ -# define STDC -#endif - -#ifndef STDC -# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ -# define const /* note: need a more gentle solution here */ -# endif -#endif - -/* Some Mac compilers merge all .h files incorrectly: */ -#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) -# define NO_DUMMY_DECL -#endif - -/* Maximum value for memLevel in deflateInit2 */ -#ifndef MAX_MEM_LEVEL -# ifdef MAXSEG_64K -# define MAX_MEM_LEVEL 8 -# else -# define MAX_MEM_LEVEL 9 -# endif -#endif - -/* Maximum value for windowBits in deflateInit2 and inflateInit2. - * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files - * created by gzip. (Files created by minigzip can still be extracted by - * gzip.) - */ -#ifndef MAX_WBITS -# define MAX_WBITS 15 /* 32K LZ77 window */ -#endif - -/* The memory requirements for deflate are (in bytes): - (1 << (windowBits+2)) + (1 << (memLevel+9)) - that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) - plus a few kilobytes for small objects. For example, if you want to reduce - the default memory requirements from 256K to 128K, compile with - make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" - Of course this will generally degrade compression (there's no free lunch). - - The memory requirements for inflate are (in bytes) 1 << windowBits - that is, 32K for windowBits=15 (default value) plus a few kilobytes - for small objects. -*/ - - /* Type declarations */ - -#ifndef OF /* function prototypes */ -# ifdef STDC -# define OF(args) args -# else -# define OF(args) () -# endif -#endif - -/* The following definitions for FAR are needed only for MSDOS mixed - * model programming (small or medium model with some far allocations). - * This was tested only with MSC; for other MSDOS compilers you may have - * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, - * just define FAR to be empty. - */ -#ifdef SYS16BIT -# if defined(M_I86SM) || defined(M_I86MM) - /* MSC small or medium model */ -# define SMALL_MEDIUM -# ifdef _MSC_VER -# define FAR _far -# else -# define FAR far -# endif -# endif -# if (defined(__SMALL__) || defined(__MEDIUM__)) - /* Turbo C small or medium model */ -# define SMALL_MEDIUM -# ifdef __BORLANDC__ -# define FAR _far -# else -# define FAR far -# endif -# endif -#endif - -#if defined(WINDOWS) || defined(WIN32) - /* If building or using zlib as a DLL, define ZLIB_DLL. - * This is not mandatory, but it offers a little performance increase. - */ -# ifdef ZLIB_DLL -# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) -# ifdef ZLIB_INTERNAL -# define ZEXTERN extern __declspec(dllexport) -# else -# define ZEXTERN extern __declspec(dllimport) -# endif -# endif -# endif /* ZLIB_DLL */ - /* If building or using zlib with the WINAPI/WINAPIV calling convention, - * define ZLIB_WINAPI. - * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. - */ -# ifdef ZLIB_WINAPI -# ifdef FAR -# undef FAR -# endif -# include - /* No need for _export, use ZLIB.DEF instead. */ - /* For complete Windows compatibility, use WINAPI, not __stdcall. */ -# define ZEXPORT WINAPI -# ifdef WIN32 -# define ZEXPORTVA WINAPIV -# else -# define ZEXPORTVA FAR CDECL -# endif -# endif -#endif - -#if defined (__BEOS__) -# ifdef ZLIB_DLL -# ifdef ZLIB_INTERNAL -# define ZEXPORT __declspec(dllexport) -# define ZEXPORTVA __declspec(dllexport) -# else -# define ZEXPORT __declspec(dllimport) -# define ZEXPORTVA __declspec(dllimport) -# endif -# endif -#endif - -#ifndef ZEXTERN -# define ZEXTERN extern -#endif -#ifndef ZEXPORT -# define ZEXPORT -#endif -#ifndef ZEXPORTVA -# define ZEXPORTVA -#endif - -#ifndef FAR -# define FAR -#endif - -#if !defined(__MACTYPES__) -typedef unsigned char Byte; /* 8 bits */ -#endif -typedef unsigned int uInt; /* 16 bits or more */ -typedef unsigned long uLong; /* 32 bits or more */ - -#ifdef SMALL_MEDIUM - /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ -# define Bytef Byte FAR -#else - typedef Byte FAR Bytef; -#endif -typedef char FAR charf; -typedef int FAR intf; -typedef uInt FAR uIntf; -typedef uLong FAR uLongf; - -#ifdef STDC - typedef void const *voidpc; - typedef void FAR *voidpf; - typedef void *voidp; -#else - typedef Byte const *voidpc; - typedef Byte FAR *voidpf; - typedef Byte *voidp; -#endif - -#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ -# define Z_HAVE_UNISTD_H -#endif - -#ifdef STDC -# include /* for off_t */ -#endif - -/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and - * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even - * though the former does not conform to the LFS document), but considering - * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as - * equivalently requesting no 64-bit operations - */ -#if -_LARGEFILE64_SOURCE - -1 == 1 -# undef _LARGEFILE64_SOURCE -#endif - -#if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) -# include /* for SEEK_* and off_t */ -# ifdef VMS -# include /* for off_t */ -# endif -# ifndef z_off_t -# define z_off_t off_t -# endif -#endif - -#ifndef SEEK_SET -# define SEEK_SET 0 /* Seek from beginning of file. */ -# define SEEK_CUR 1 /* Seek from current position. */ -# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ -#endif - -#ifndef z_off_t -# define z_off_t long -#endif - -#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 -# define z_off64_t off64_t -#else -# define z_off64_t z_off_t -#endif - -#if defined(__OS400__) -# define NO_vsnprintf -#endif - -#if defined(__MVS__) -# define NO_vsnprintf -#endif - -/* MVS linker does not support external names larger than 8 bytes */ -#if defined(__MVS__) - #pragma map(deflateInit_,"DEIN") - #pragma map(deflateInit2_,"DEIN2") - #pragma map(deflateEnd,"DEEND") - #pragma map(deflateBound,"DEBND") - #pragma map(inflateInit_,"ININ") - #pragma map(inflateInit2_,"ININ2") - #pragma map(inflateEnd,"INEND") - #pragma map(inflateSync,"INSY") - #pragma map(inflateSetDictionary,"INSEDI") - #pragma map(compressBound,"CMBND") - #pragma map(inflate_table,"INTABL") - #pragma map(inflate_fast,"INFA") - #pragma map(inflate_copyright,"INCOPY") -#endif - -#endif /* ZCONF_H */ diff --git a/externals/zlib/zlib.h b/externals/zlib/zlib.h deleted file mode 100644 index bfbba83e8ee..00000000000 --- a/externals/zlib/zlib.h +++ /dev/null @@ -1,1613 +0,0 @@ -/* zlib.h -- interface of the 'zlib' general purpose compression library - version 1.2.5, April 19th, 2010 - - Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jean-loup Gailly Mark Adler - jloup@gzip.org madler@alumni.caltech.edu - - - The data format used by the zlib library is described by RFCs (Request for - Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt - (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). -*/ - -#ifndef ZLIB_H -#define ZLIB_H - -#include "zconf.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define ZLIB_VERSION "1.2.5" -#define ZLIB_VERNUM 0x1250 -#define ZLIB_VER_MAJOR 1 -#define ZLIB_VER_MINOR 2 -#define ZLIB_VER_REVISION 5 -#define ZLIB_VER_SUBREVISION 0 - -/* - The 'zlib' compression library provides in-memory compression and - decompression functions, including integrity checks of the uncompressed data. - This version of the library supports only one compression method (deflation) - but other algorithms will be added later and will have the same stream - interface. - - Compression can be done in a single step if the buffers are large enough, - or can be done by repeated calls of the compression function. In the latter - case, the application must provide more input and/or consume the output - (providing more output space) before each call. - - The compressed data format used by default by the in-memory functions is - the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped - around a deflate stream, which is itself documented in RFC 1951. - - The library also supports reading and writing files in gzip (.gz) format - with an interface similar to that of stdio using the functions that start - with "gz". The gzip format is different from the zlib format. gzip is a - gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. - - This library can optionally read and write gzip streams in memory as well. - - The zlib format was designed to be compact and fast for use in memory - and on communications channels. The gzip format was designed for single- - file compression on file systems, has a larger header than zlib to maintain - directory information, and uses a different, slower check method than zlib. - - The library does not install any signal handler. The decoder checks - the consistency of the compressed data, so the library should never crash - even in case of corrupted input. -*/ - -typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); -typedef void (*free_func) OF((voidpf opaque, voidpf address)); - -struct internal_state; - -typedef struct z_stream_s { - Bytef *next_in; /* next input byte */ - uInt avail_in; /* number of bytes available at next_in */ - uLong total_in; /* total nb of input bytes read so far */ - - Bytef *next_out; /* next output byte should be put there */ - uInt avail_out; /* remaining free space at next_out */ - uLong total_out; /* total nb of bytes output so far */ - - char *msg; /* last error message, NULL if no error */ - struct internal_state FAR *state; /* not visible by applications */ - - alloc_func zalloc; /* used to allocate the internal state */ - free_func zfree; /* used to free the internal state */ - voidpf opaque; /* private data object passed to zalloc and zfree */ - - int data_type; /* best guess about the data type: binary or text */ - uLong adler; /* adler32 value of the uncompressed data */ - uLong reserved; /* reserved for future use */ -} z_stream; - -typedef z_stream FAR *z_streamp; - -/* - gzip header information passed to and from zlib routines. See RFC 1952 - for more details on the meanings of these fields. -*/ -typedef struct gz_header_s { - int text; /* true if compressed data believed to be text */ - uLong time; /* modification time */ - int xflags; /* extra flags (not used when writing a gzip file) */ - int os; /* operating system */ - Bytef *extra; /* pointer to extra field or Z_NULL if none */ - uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ - uInt extra_max; /* space at extra (only when reading header) */ - Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ - uInt name_max; /* space at name (only when reading header) */ - Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ - uInt comm_max; /* space at comment (only when reading header) */ - int hcrc; /* true if there was or will be a header crc */ - int done; /* true when done reading gzip header (not used - when writing a gzip file) */ -} gz_header; - -typedef gz_header FAR *gz_headerp; - -/* - The application must update next_in and avail_in when avail_in has dropped - to zero. It must update next_out and avail_out when avail_out has dropped - to zero. The application must initialize zalloc, zfree and opaque before - calling the init function. All other fields are set by the compression - library and must not be updated by the application. - - The opaque value provided by the application will be passed as the first - parameter for calls of zalloc and zfree. This can be useful for custom - memory management. The compression library attaches no meaning to the - opaque value. - - zalloc must return Z_NULL if there is not enough memory for the object. - If zlib is used in a multi-threaded application, zalloc and zfree must be - thread safe. - - On 16-bit systems, the functions zalloc and zfree must be able to allocate - exactly 65536 bytes, but will not be required to allocate more than this if - the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers - returned by zalloc for objects of exactly 65536 bytes *must* have their - offset normalized to zero. The default allocation function provided by this - library ensures this (see zutil.c). To reduce memory requirements and avoid - any allocation of 64K objects, at the expense of compression ratio, compile - the library with -DMAX_WBITS=14 (see zconf.h). - - The fields total_in and total_out can be used for statistics or progress - reports. After compression, total_in holds the total size of the - uncompressed data and may be saved for use in the decompressor (particularly - if the decompressor wants to decompress everything in a single step). -*/ - - /* constants */ - -#define Z_NO_FLUSH 0 -#define Z_PARTIAL_FLUSH 1 -#define Z_SYNC_FLUSH 2 -#define Z_FULL_FLUSH 3 -#define Z_FINISH 4 -#define Z_BLOCK 5 -#define Z_TREES 6 -/* Allowed flush values; see deflate() and inflate() below for details */ - -#define Z_OK 0 -#define Z_STREAM_END 1 -#define Z_NEED_DICT 2 -#define Z_ERRNO (-1) -#define Z_STREAM_ERROR (-2) -#define Z_DATA_ERROR (-3) -#define Z_MEM_ERROR (-4) -#define Z_BUF_ERROR (-5) -#define Z_VERSION_ERROR (-6) -/* Return codes for the compression/decompression functions. Negative values - * are errors, positive values are used for special but normal events. - */ - -#define Z_NO_COMPRESSION 0 -#define Z_BEST_SPEED 1 -#define Z_BEST_COMPRESSION 9 -#define Z_DEFAULT_COMPRESSION (-1) -/* compression levels */ - -#define Z_FILTERED 1 -#define Z_HUFFMAN_ONLY 2 -#define Z_RLE 3 -#define Z_FIXED 4 -#define Z_DEFAULT_STRATEGY 0 -/* compression strategy; see deflateInit2() below for details */ - -#define Z_BINARY 0 -#define Z_TEXT 1 -#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ -#define Z_UNKNOWN 2 -/* Possible values of the data_type field (though see inflate()) */ - -#define Z_DEFLATED 8 -/* The deflate compression method (the only one supported in this version) */ - -#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ - -#define zlib_version zlibVersion() -/* for compatibility with versions < 1.0.2 */ - - - /* basic functions */ - -ZEXTERN const char * ZEXPORT zlibVersion OF((void)); -/* The application can compare zlibVersion and ZLIB_VERSION for consistency. - If the first character differs, the library code actually used is not - compatible with the zlib.h header file used by the application. This check - is automatically made by deflateInit and inflateInit. - */ - -/* -ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); - - Initializes the internal stream state for compression. The fields - zalloc, zfree and opaque must be initialized before by the caller. If - zalloc and zfree are set to Z_NULL, deflateInit updates them to use default - allocation functions. - - The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: - 1 gives best speed, 9 gives best compression, 0 gives no compression at all - (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION - requests a default compromise between speed and compression (currently - equivalent to level 6). - - deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_STREAM_ERROR if level is not a valid compression level, or - Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible - with the version assumed by the caller (ZLIB_VERSION). msg is set to null - if there is no error message. deflateInit does not perform any compression: - this will be done by deflate(). -*/ - - -ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); -/* - deflate compresses as much data as possible, and stops when the input - buffer becomes empty or the output buffer becomes full. It may introduce - some output latency (reading input without producing any output) except when - forced to flush. - - The detailed semantics are as follows. deflate performs one or both of the - following actions: - - - Compress more input starting at next_in and update next_in and avail_in - accordingly. If not all input can be processed (because there is not - enough room in the output buffer), next_in and avail_in are updated and - processing will resume at this point for the next call of deflate(). - - - Provide more output starting at next_out and update next_out and avail_out - accordingly. This action is forced if the parameter flush is non zero. - Forcing flush frequently degrades the compression ratio, so this parameter - should be set only when necessary (in interactive applications). Some - output may be provided even if flush is not set. - - Before the call of deflate(), the application should ensure that at least - one of the actions is possible, by providing more input and/or consuming more - output, and updating avail_in or avail_out accordingly; avail_out should - never be zero before the call. The application can consume the compressed - output when it wants, for example when the output buffer is full (avail_out - == 0), or after each call of deflate(). If deflate returns Z_OK and with - zero avail_out, it must be called again after making room in the output - buffer because there might be more output pending. - - Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to - decide how much data to accumulate before producing output, in order to - maximize compression. - - If the parameter flush is set to Z_SYNC_FLUSH, all pending output is - flushed to the output buffer and the output is aligned on a byte boundary, so - that the decompressor can get all input data available so far. (In - particular avail_in is zero after the call if enough output space has been - provided before the call.) Flushing may degrade compression for some - compression algorithms and so it should be used only when necessary. This - completes the current deflate block and follows it with an empty stored block - that is three bits plus filler bits to the next byte, followed by four bytes - (00 00 ff ff). - - If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the - output buffer, but the output is not aligned to a byte boundary. All of the - input data so far will be available to the decompressor, as for Z_SYNC_FLUSH. - This completes the current deflate block and follows it with an empty fixed - codes block that is 10 bits long. This assures that enough bytes are output - in order for the decompressor to finish the block before the empty fixed code - block. - - If flush is set to Z_BLOCK, a deflate block is completed and emitted, as - for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to - seven bits of the current block are held to be written as the next byte after - the next deflate block is completed. In this case, the decompressor may not - be provided enough bits at this point in order to complete decompression of - the data provided so far to the compressor. It may need to wait for the next - block to be emitted. This is for advanced applications that need to control - the emission of deflate blocks. - - If flush is set to Z_FULL_FLUSH, all output is flushed as with - Z_SYNC_FLUSH, and the compression state is reset so that decompression can - restart from this point if previous compressed data has been damaged or if - random access is desired. Using Z_FULL_FLUSH too often can seriously degrade - compression. - - If deflate returns with avail_out == 0, this function must be called again - with the same value of the flush parameter and more output space (updated - avail_out), until the flush is complete (deflate returns with non-zero - avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that - avail_out is greater than six to avoid repeated flush markers due to - avail_out == 0 on return. - - If the parameter flush is set to Z_FINISH, pending input is processed, - pending output is flushed and deflate returns with Z_STREAM_END if there was - enough output space; if deflate returns with Z_OK, this function must be - called again with Z_FINISH and more output space (updated avail_out) but no - more input data, until it returns with Z_STREAM_END or an error. After - deflate has returned Z_STREAM_END, the only possible operations on the stream - are deflateReset or deflateEnd. - - Z_FINISH can be used immediately after deflateInit if all the compression - is to be done in a single step. In this case, avail_out must be at least the - value returned by deflateBound (see below). If deflate does not return - Z_STREAM_END, then it must be called again as described above. - - deflate() sets strm->adler to the adler32 checksum of all input read - so far (that is, total_in bytes). - - deflate() may update strm->data_type if it can make a good guess about - the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered - binary. This field is only for information purposes and does not affect the - compression algorithm in any manner. - - deflate() returns Z_OK if some progress has been made (more input - processed or more output produced), Z_STREAM_END if all input has been - consumed and all output has been produced (only when flush is set to - Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example - if next_in or next_out was Z_NULL), Z_BUF_ERROR if no progress is possible - (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not - fatal, and deflate() can be called again with more input and more output - space to continue compressing. -*/ - - -ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); -/* - All dynamically allocated data structures for this stream are freed. - This function discards any unprocessed input and does not flush any pending - output. - - deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the - stream state was inconsistent, Z_DATA_ERROR if the stream was freed - prematurely (some input or output was discarded). In the error case, msg - may be set but then points to a static string (which must not be - deallocated). -*/ - - -/* -ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); - - Initializes the internal stream state for decompression. The fields - next_in, avail_in, zalloc, zfree and opaque must be initialized before by - the caller. If next_in is not Z_NULL and avail_in is large enough (the - exact value depends on the compression method), inflateInit determines the - compression method from the zlib header and allocates all data structures - accordingly; otherwise the allocation will be deferred to the first call of - inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to - use default allocation functions. - - inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_VERSION_ERROR if the zlib library version is incompatible with the - version assumed by the caller, or Z_STREAM_ERROR if the parameters are - invalid, such as a null pointer to the structure. msg is set to null if - there is no error message. inflateInit does not perform any decompression - apart from possibly reading the zlib header if present: actual decompression - will be done by inflate(). (So next_in and avail_in may be modified, but - next_out and avail_out are unused and unchanged.) The current implementation - of inflateInit() does not process any header information -- that is deferred - until inflate() is called. -*/ - - -ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); -/* - inflate decompresses as much data as possible, and stops when the input - buffer becomes empty or the output buffer becomes full. It may introduce - some output latency (reading input without producing any output) except when - forced to flush. - - The detailed semantics are as follows. inflate performs one or both of the - following actions: - - - Decompress more input starting at next_in and update next_in and avail_in - accordingly. If not all input can be processed (because there is not - enough room in the output buffer), next_in is updated and processing will - resume at this point for the next call of inflate(). - - - Provide more output starting at next_out and update next_out and avail_out - accordingly. inflate() provides as much output as possible, until there is - no more input data or no more space in the output buffer (see below about - the flush parameter). - - Before the call of inflate(), the application should ensure that at least - one of the actions is possible, by providing more input and/or consuming more - output, and updating the next_* and avail_* values accordingly. The - application can consume the uncompressed output when it wants, for example - when the output buffer is full (avail_out == 0), or after each call of - inflate(). If inflate returns Z_OK and with zero avail_out, it must be - called again after making room in the output buffer because there might be - more output pending. - - The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH, - Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much - output as possible to the output buffer. Z_BLOCK requests that inflate() - stop if and when it gets to the next deflate block boundary. When decoding - the zlib or gzip format, this will cause inflate() to return immediately - after the header and before the first block. When doing a raw inflate, - inflate() will go ahead and process the first block, and will return when it - gets to the end of that block, or when it runs out of data. - - The Z_BLOCK option assists in appending to or combining deflate streams. - Also to assist in this, on return inflate() will set strm->data_type to the - number of unused bits in the last byte taken from strm->next_in, plus 64 if - inflate() is currently decoding the last block in the deflate stream, plus - 128 if inflate() returned immediately after decoding an end-of-block code or - decoding the complete header up to just before the first byte of the deflate - stream. The end-of-block will not be indicated until all of the uncompressed - data from that block has been written to strm->next_out. The number of - unused bits may in general be greater than seven, except when bit 7 of - data_type is set, in which case the number of unused bits will be less than - eight. data_type is set as noted here every time inflate() returns for all - flush options, and so can be used to determine the amount of currently - consumed input in bits. - - The Z_TREES option behaves as Z_BLOCK does, but it also returns when the - end of each deflate block header is reached, before any actual data in that - block is decoded. This allows the caller to determine the length of the - deflate block header for later use in random access within a deflate block. - 256 is added to the value of strm->data_type when inflate() returns - immediately after reaching the end of the deflate block header. - - inflate() should normally be called until it returns Z_STREAM_END or an - error. However if all decompression is to be performed in a single step (a - single call of inflate), the parameter flush should be set to Z_FINISH. In - this case all pending input is processed and all pending output is flushed; - avail_out must be large enough to hold all the uncompressed data. (The size - of the uncompressed data may have been saved by the compressor for this - purpose.) The next operation on this stream must be inflateEnd to deallocate - the decompression state. The use of Z_FINISH is never required, but can be - used to inform inflate that a faster approach may be used for the single - inflate() call. - - In this implementation, inflate() always flushes as much output as - possible to the output buffer, and always uses the faster approach on the - first call. So the only effect of the flush parameter in this implementation - is on the return value of inflate(), as noted below, or when it returns early - because Z_BLOCK or Z_TREES is used. - - If a preset dictionary is needed after this call (see inflateSetDictionary - below), inflate sets strm->adler to the adler32 checksum of the dictionary - chosen by the compressor and returns Z_NEED_DICT; otherwise it sets - strm->adler to the adler32 checksum of all output produced so far (that is, - total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described - below. At the end of the stream, inflate() checks that its computed adler32 - checksum is equal to that saved by the compressor and returns Z_STREAM_END - only if the checksum is correct. - - inflate() can decompress and check either zlib-wrapped or gzip-wrapped - deflate data. The header type is detected automatically, if requested when - initializing with inflateInit2(). Any information contained in the gzip - header is not retained, so applications that need that information should - instead use raw inflate, see inflateInit2() below, or inflateBack() and - perform their own processing of the gzip header and trailer. - - inflate() returns Z_OK if some progress has been made (more input processed - or more output produced), Z_STREAM_END if the end of the compressed data has - been reached and all uncompressed output has been produced, Z_NEED_DICT if a - preset dictionary is needed at this point, Z_DATA_ERROR if the input data was - corrupted (input stream not conforming to the zlib format or incorrect check - value), Z_STREAM_ERROR if the stream structure was inconsistent (for example - next_in or next_out was Z_NULL), Z_MEM_ERROR if there was not enough memory, - Z_BUF_ERROR if no progress is possible or if there was not enough room in the - output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and - inflate() can be called again with more input and more output space to - continue decompressing. If Z_DATA_ERROR is returned, the application may - then call inflateSync() to look for a good compression block if a partial - recovery of the data is desired. -*/ - - -ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); -/* - All dynamically allocated data structures for this stream are freed. - This function discards any unprocessed input and does not flush any pending - output. - - inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state - was inconsistent. In the error case, msg may be set but then points to a - static string (which must not be deallocated). -*/ - - - /* Advanced functions */ - -/* - The following functions are needed only in some special applications. -*/ - -/* -ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, - int level, - int method, - int windowBits, - int memLevel, - int strategy)); - - This is another version of deflateInit with more compression options. The - fields next_in, zalloc, zfree and opaque must be initialized before by the - caller. - - The method parameter is the compression method. It must be Z_DEFLATED in - this version of the library. - - The windowBits parameter is the base two logarithm of the window size - (the size of the history buffer). It should be in the range 8..15 for this - version of the library. Larger values of this parameter result in better - compression at the expense of memory usage. The default value is 15 if - deflateInit is used instead. - - windowBits can also be -8..-15 for raw deflate. In this case, -windowBits - determines the window size. deflate() will then generate raw deflate data - with no zlib header or trailer, and will not compute an adler32 check value. - - windowBits can also be greater than 15 for optional gzip encoding. Add - 16 to windowBits to write a simple gzip header and trailer around the - compressed data instead of a zlib wrapper. The gzip header will have no - file name, no extra data, no comment, no modification time (set to zero), no - header crc, and the operating system will be set to 255 (unknown). If a - gzip stream is being written, strm->adler is a crc32 instead of an adler32. - - The memLevel parameter specifies how much memory should be allocated - for the internal compression state. memLevel=1 uses minimum memory but is - slow and reduces compression ratio; memLevel=9 uses maximum memory for - optimal speed. The default value is 8. See zconf.h for total memory usage - as a function of windowBits and memLevel. - - The strategy parameter is used to tune the compression algorithm. Use the - value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a - filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no - string match), or Z_RLE to limit match distances to one (run-length - encoding). Filtered data consists mostly of small values with a somewhat - random distribution. In this case, the compression algorithm is tuned to - compress them better. The effect of Z_FILTERED is to force more Huffman - coding and less string matching; it is somewhat intermediate between - Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as - fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The - strategy parameter only affects the compression ratio but not the - correctness of the compressed output even if it is not set appropriately. - Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler - decoder for special applications. - - deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid - method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is - incompatible with the version assumed by the caller (ZLIB_VERSION). msg is - set to null if there is no error message. deflateInit2 does not perform any - compression: this will be done by deflate(). -*/ - -ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, - const Bytef *dictionary, - uInt dictLength)); -/* - Initializes the compression dictionary from the given byte sequence - without producing any compressed output. This function must be called - immediately after deflateInit, deflateInit2 or deflateReset, before any call - of deflate. The compressor and decompressor must use exactly the same - dictionary (see inflateSetDictionary). - - The dictionary should consist of strings (byte sequences) that are likely - to be encountered later in the data to be compressed, with the most commonly - used strings preferably put towards the end of the dictionary. Using a - dictionary is most useful when the data to be compressed is short and can be - predicted with good accuracy; the data can then be compressed better than - with the default empty dictionary. - - Depending on the size of the compression data structures selected by - deflateInit or deflateInit2, a part of the dictionary may in effect be - discarded, for example if the dictionary is larger than the window size - provided in deflateInit or deflateInit2. Thus the strings most likely to be - useful should be put at the end of the dictionary, not at the front. In - addition, the current implementation of deflate will use at most the window - size minus 262 bytes of the provided dictionary. - - Upon return of this function, strm->adler is set to the adler32 value - of the dictionary; the decompressor may later use this value to determine - which dictionary has been used by the compressor. (The adler32 value - applies to the whole dictionary even if only a subset of the dictionary is - actually used by the compressor.) If a raw deflate was requested, then the - adler32 value is not computed and strm->adler is not set. - - deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a - parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is - inconsistent (for example if deflate has already been called for this stream - or if the compression method is bsort). deflateSetDictionary does not - perform any compression: this will be done by deflate(). -*/ - -ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, - z_streamp source)); -/* - Sets the destination stream as a complete copy of the source stream. - - This function can be useful when several compression strategies will be - tried, for example when there are several ways of pre-processing the input - data with a filter. The streams that will be discarded should then be freed - by calling deflateEnd. Note that deflateCopy duplicates the internal - compression state which can be quite large, so this strategy is slow and can - consume lots of memory. - - deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if the source stream state was inconsistent - (such as zalloc being Z_NULL). msg is left unchanged in both source and - destination. -*/ - -ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); -/* - This function is equivalent to deflateEnd followed by deflateInit, - but does not free and reallocate all the internal compression state. The - stream will keep the same compression level and any other attributes that - may have been set by deflateInit2. - - deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being Z_NULL). -*/ - -ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, - int level, - int strategy)); -/* - Dynamically update the compression level and compression strategy. The - interpretation of level and strategy is as in deflateInit2. This can be - used to switch between compression and straight copy of the input data, or - to switch to a different kind of input data requiring a different strategy. - If the compression level is changed, the input available so far is - compressed with the old level (and may be flushed); the new level will take - effect only at the next call of deflate(). - - Before the call of deflateParams, the stream state must be set as for - a call of deflate(), since the currently available input may have to be - compressed and flushed. In particular, strm->avail_out must be non-zero. - - deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source - stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR if - strm->avail_out was zero. -*/ - -ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, - int good_length, - int max_lazy, - int nice_length, - int max_chain)); -/* - Fine tune deflate's internal compression parameters. This should only be - used by someone who understands the algorithm used by zlib's deflate for - searching for the best matching string, and even then only by the most - fanatic optimizer trying to squeeze out the last compressed bit for their - specific input data. Read the deflate.c source code for the meaning of the - max_lazy, good_length, nice_length, and max_chain parameters. - - deflateTune() can be called after deflateInit() or deflateInit2(), and - returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. - */ - -ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, - uLong sourceLen)); -/* - deflateBound() returns an upper bound on the compressed size after - deflation of sourceLen bytes. It must be called after deflateInit() or - deflateInit2(), and after deflateSetHeader(), if used. This would be used - to allocate an output buffer for deflation in a single pass, and so would be - called before deflate(). -*/ - -ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, - int bits, - int value)); -/* - deflatePrime() inserts bits in the deflate output stream. The intent - is that this function is used to start off the deflate output with the bits - leftover from a previous deflate stream when appending to it. As such, this - function can only be used for raw deflate, and must be used before the first - deflate() call after a deflateInit2() or deflateReset(). bits must be less - than or equal to 16, and that many of the least significant bits of value - will be inserted in the output. - - deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, - gz_headerp head)); -/* - deflateSetHeader() provides gzip header information for when a gzip - stream is requested by deflateInit2(). deflateSetHeader() may be called - after deflateInit2() or deflateReset() and before the first call of - deflate(). The text, time, os, extra field, name, and comment information - in the provided gz_header structure are written to the gzip header (xflag is - ignored -- the extra flags are set according to the compression level). The - caller must assure that, if not Z_NULL, name and comment are terminated with - a zero byte, and that if extra is not Z_NULL, that extra_len bytes are - available there. If hcrc is true, a gzip header crc is included. Note that - the current versions of the command-line version of gzip (up through version - 1.3.x) do not support header crc's, and will report that it is a "multi-part - gzip file" and give up. - - If deflateSetHeader is not used, the default gzip header has text false, - the time set to zero, and os set to 255, with no extra, name, or comment - fields. The gzip header is returned to the default state by deflateReset(). - - deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -/* -ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, - int windowBits)); - - This is another version of inflateInit with an extra parameter. The - fields next_in, avail_in, zalloc, zfree and opaque must be initialized - before by the caller. - - The windowBits parameter is the base two logarithm of the maximum window - size (the size of the history buffer). It should be in the range 8..15 for - this version of the library. The default value is 15 if inflateInit is used - instead. windowBits must be greater than or equal to the windowBits value - provided to deflateInit2() while compressing, or it must be equal to 15 if - deflateInit2() was not used. If a compressed stream with a larger window - size is given as input, inflate() will return with the error code - Z_DATA_ERROR instead of trying to allocate a larger window. - - windowBits can also be zero to request that inflate use the window size in - the zlib header of the compressed stream. - - windowBits can also be -8..-15 for raw inflate. In this case, -windowBits - determines the window size. inflate() will then process raw deflate data, - not looking for a zlib or gzip header, not generating a check value, and not - looking for any check values for comparison at the end of the stream. This - is for use with other formats that use the deflate compressed data format - such as zip. Those formats provide their own check values. If a custom - format is developed using the raw deflate format for compressed data, it is - recommended that a check value such as an adler32 or a crc32 be applied to - the uncompressed data as is done in the zlib, gzip, and zip formats. For - most applications, the zlib format should be used as is. Note that comments - above on the use in deflateInit2() applies to the magnitude of windowBits. - - windowBits can also be greater than 15 for optional gzip decoding. Add - 32 to windowBits to enable zlib and gzip decoding with automatic header - detection, or add 16 to decode only the gzip format (the zlib format will - return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a - crc32 instead of an adler32. - - inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_VERSION_ERROR if the zlib library version is incompatible with the - version assumed by the caller, or Z_STREAM_ERROR if the parameters are - invalid, such as a null pointer to the structure. msg is set to null if - there is no error message. inflateInit2 does not perform any decompression - apart from possibly reading the zlib header if present: actual decompression - will be done by inflate(). (So next_in and avail_in may be modified, but - next_out and avail_out are unused and unchanged.) The current implementation - of inflateInit2() does not process any header information -- that is - deferred until inflate() is called. -*/ - -ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, - const Bytef *dictionary, - uInt dictLength)); -/* - Initializes the decompression dictionary from the given uncompressed byte - sequence. This function must be called immediately after a call of inflate, - if that call returned Z_NEED_DICT. The dictionary chosen by the compressor - can be determined from the adler32 value returned by that call of inflate. - The compressor and decompressor must use exactly the same dictionary (see - deflateSetDictionary). For raw inflate, this function can be called - immediately after inflateInit2() or inflateReset() and before any call of - inflate() to set the dictionary. The application must insure that the - dictionary that was used for compression is provided. - - inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a - parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is - inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the - expected one (incorrect adler32 value). inflateSetDictionary does not - perform any decompression: this will be done by subsequent calls of - inflate(). -*/ - -ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); -/* - Skips invalid compressed data until a full flush point (see above the - description of deflate with Z_FULL_FLUSH) can be found, or until all - available input is skipped. No output is provided. - - inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR - if no more input was provided, Z_DATA_ERROR if no flush point has been - found, or Z_STREAM_ERROR if the stream structure was inconsistent. In the - success case, the application may save the current current value of total_in - which indicates where valid compressed data was found. In the error case, - the application may repeatedly call inflateSync, providing more input each - time, until success or end of the input data. -*/ - -ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, - z_streamp source)); -/* - Sets the destination stream as a complete copy of the source stream. - - This function can be useful when randomly accessing a large stream. The - first pass through the stream can periodically record the inflate state, - allowing restarting inflate at those points when randomly accessing the - stream. - - inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if the source stream state was inconsistent - (such as zalloc being Z_NULL). msg is left unchanged in both source and - destination. -*/ - -ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); -/* - This function is equivalent to inflateEnd followed by inflateInit, - but does not free and reallocate all the internal decompression state. The - stream will keep attributes that may have been set by inflateInit2. - - inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being Z_NULL). -*/ - -ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm, - int windowBits)); -/* - This function is the same as inflateReset, but it also permits changing - the wrap and window size requests. The windowBits parameter is interpreted - the same as it is for inflateInit2. - - inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being Z_NULL), or if - the windowBits parameter is invalid. -*/ - -ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, - int bits, - int value)); -/* - This function inserts bits in the inflate input stream. The intent is - that this function is used to start inflating at a bit position in the - middle of a byte. The provided bits will be used before any bytes are used - from next_in. This function should only be used with raw inflate, and - should be used before the first inflate() call after inflateInit2() or - inflateReset(). bits must be less than or equal to 16, and that many of the - least significant bits of value will be inserted in the input. - - If bits is negative, then the input stream bit buffer is emptied. Then - inflatePrime() can be called again to put bits in the buffer. This is used - to clear out bits leftover after feeding inflate a block description prior - to feeding inflate codes. - - inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm)); -/* - This function returns two values, one in the lower 16 bits of the return - value, and the other in the remaining upper bits, obtained by shifting the - return value down 16 bits. If the upper value is -1 and the lower value is - zero, then inflate() is currently decoding information outside of a block. - If the upper value is -1 and the lower value is non-zero, then inflate is in - the middle of a stored block, with the lower value equaling the number of - bytes from the input remaining to copy. If the upper value is not -1, then - it is the number of bits back from the current bit position in the input of - the code (literal or length/distance pair) currently being processed. In - that case the lower value is the number of bytes already emitted for that - code. - - A code is being processed if inflate is waiting for more input to complete - decoding of the code, or if it has completed decoding but is waiting for - more output space to write the literal or match data. - - inflateMark() is used to mark locations in the input data for random - access, which may be at bit positions, and to note those cases where the - output of a code may span boundaries of random access blocks. The current - location in the input stream can be determined from avail_in and data_type - as noted in the description for the Z_BLOCK flush parameter for inflate. - - inflateMark returns the value noted above or -1 << 16 if the provided - source stream state was inconsistent. -*/ - -ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, - gz_headerp head)); -/* - inflateGetHeader() requests that gzip header information be stored in the - provided gz_header structure. inflateGetHeader() may be called after - inflateInit2() or inflateReset(), and before the first call of inflate(). - As inflate() processes the gzip stream, head->done is zero until the header - is completed, at which time head->done is set to one. If a zlib stream is - being decoded, then head->done is set to -1 to indicate that there will be - no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be - used to force inflate() to return immediately after header processing is - complete and before any actual data is decompressed. - - The text, time, xflags, and os fields are filled in with the gzip header - contents. hcrc is set to true if there is a header CRC. (The header CRC - was valid if done is set to one.) If extra is not Z_NULL, then extra_max - contains the maximum number of bytes to write to extra. Once done is true, - extra_len contains the actual extra field length, and extra contains the - extra field, or that field truncated if extra_max is less than extra_len. - If name is not Z_NULL, then up to name_max characters are written there, - terminated with a zero unless the length is greater than name_max. If - comment is not Z_NULL, then up to comm_max characters are written there, - terminated with a zero unless the length is greater than comm_max. When any - of extra, name, or comment are not Z_NULL and the respective field is not - present in the header, then that field is set to Z_NULL to signal its - absence. This allows the use of deflateSetHeader() with the returned - structure to duplicate the header. However if those fields are set to - allocated memory, then the application will need to save those pointers - elsewhere so that they can be eventually freed. - - If inflateGetHeader is not used, then the header information is simply - discarded. The header is always checked for validity, including the header - CRC if present. inflateReset() will reset the process to discard the header - information. The application would need to call inflateGetHeader() again to - retrieve the header from the next gzip stream. - - inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -/* -ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, - unsigned char FAR *window)); - - Initialize the internal stream state for decompression using inflateBack() - calls. The fields zalloc, zfree and opaque in strm must be initialized - before the call. If zalloc and zfree are Z_NULL, then the default library- - derived memory allocation routines are used. windowBits is the base two - logarithm of the window size, in the range 8..15. window is a caller - supplied buffer of that size. Except for special applications where it is - assured that deflate was used with small window sizes, windowBits must be 15 - and a 32K byte window must be supplied to be able to decompress general - deflate streams. - - See inflateBack() for the usage of these routines. - - inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of - the paramaters are invalid, Z_MEM_ERROR if the internal state could not be - allocated, or Z_VERSION_ERROR if the version of the library does not match - the version of the header file. -*/ - -typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *)); -typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); - -ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, - in_func in, void FAR *in_desc, - out_func out, void FAR *out_desc)); -/* - inflateBack() does a raw inflate with a single call using a call-back - interface for input and output. This is more efficient than inflate() for - file i/o applications in that it avoids copying between the output and the - sliding window by simply making the window itself the output buffer. This - function trusts the application to not change the output buffer passed by - the output function, at least until inflateBack() returns. - - inflateBackInit() must be called first to allocate the internal state - and to initialize the state with the user-provided window buffer. - inflateBack() may then be used multiple times to inflate a complete, raw - deflate stream with each call. inflateBackEnd() is then called to free the - allocated state. - - A raw deflate stream is one with no zlib or gzip header or trailer. - This routine would normally be used in a utility that reads zip or gzip - files and writes out uncompressed files. The utility would decode the - header and process the trailer on its own, hence this routine expects only - the raw deflate stream to decompress. This is different from the normal - behavior of inflate(), which expects either a zlib or gzip header and - trailer around the deflate stream. - - inflateBack() uses two subroutines supplied by the caller that are then - called by inflateBack() for input and output. inflateBack() calls those - routines until it reads a complete deflate stream and writes out all of the - uncompressed data, or until it encounters an error. The function's - parameters and return types are defined above in the in_func and out_func - typedefs. inflateBack() will call in(in_desc, &buf) which should return the - number of bytes of provided input, and a pointer to that input in buf. If - there is no input available, in() must return zero--buf is ignored in that - case--and inflateBack() will return a buffer error. inflateBack() will call - out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() - should return zero on success, or non-zero on failure. If out() returns - non-zero, inflateBack() will return with an error. Neither in() nor out() - are permitted to change the contents of the window provided to - inflateBackInit(), which is also the buffer that out() uses to write from. - The length written by out() will be at most the window size. Any non-zero - amount of input may be provided by in(). - - For convenience, inflateBack() can be provided input on the first call by - setting strm->next_in and strm->avail_in. If that input is exhausted, then - in() will be called. Therefore strm->next_in must be initialized before - calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called - immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in - must also be initialized, and then if strm->avail_in is not zero, input will - initially be taken from strm->next_in[0 .. strm->avail_in - 1]. - - The in_desc and out_desc parameters of inflateBack() is passed as the - first parameter of in() and out() respectively when they are called. These - descriptors can be optionally used to pass any information that the caller- - supplied in() and out() functions need to do their job. - - On return, inflateBack() will set strm->next_in and strm->avail_in to - pass back any unused input that was provided by the last in() call. The - return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR - if in() or out() returned an error, Z_DATA_ERROR if there was a format error - in the deflate stream (in which case strm->msg is set to indicate the nature - of the error), or Z_STREAM_ERROR if the stream was not properly initialized. - In the case of Z_BUF_ERROR, an input or output error can be distinguished - using strm->next_in which will be Z_NULL only if in() returned an error. If - strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning - non-zero. (in() will always be called before out(), so strm->next_in is - assured to be defined if out() returns non-zero.) Note that inflateBack() - cannot return Z_OK. -*/ - -ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); -/* - All memory allocated by inflateBackInit() is freed. - - inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream - state was inconsistent. -*/ - -ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); -/* Return flags indicating compile-time options. - - Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: - 1.0: size of uInt - 3.2: size of uLong - 5.4: size of voidpf (pointer) - 7.6: size of z_off_t - - Compiler, assembler, and debug options: - 8: DEBUG - 9: ASMV or ASMINF -- use ASM code - 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention - 11: 0 (reserved) - - One-time table building (smaller code, but not thread-safe if true): - 12: BUILDFIXED -- build static block decoding tables when needed - 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed - 14,15: 0 (reserved) - - Library content (indicates missing functionality): - 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking - deflate code when not needed) - 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect - and decode gzip streams (to avoid linking crc code) - 18-19: 0 (reserved) - - Operation variations (changes in library functionality): - 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate - 21: FASTEST -- deflate algorithm with only one, lowest compression level - 22,23: 0 (reserved) - - The sprintf variant used by gzprintf (zero is best): - 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format - 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! - 26: 0 = returns value, 1 = void -- 1 means inferred string length returned - - Remainder: - 27-31: 0 (reserved) - */ - - - /* utility functions */ - -/* - The following utility functions are implemented on top of the basic - stream-oriented functions. To simplify the interface, some default options - are assumed (compression level and memory usage, standard memory allocation - functions). The source code of these utility functions can be modified if - you need special options. -*/ - -ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen)); -/* - Compresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total size - of the destination buffer, which must be at least the value returned by - compressBound(sourceLen). Upon exit, destLen is the actual size of the - compressed buffer. - - compress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer. -*/ - -ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen, - int level)); -/* - Compresses the source buffer into the destination buffer. The level - parameter has the same meaning as in deflateInit. sourceLen is the byte - length of the source buffer. Upon entry, destLen is the total size of the - destination buffer, which must be at least the value returned by - compressBound(sourceLen). Upon exit, destLen is the actual size of the - compressed buffer. - - compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_BUF_ERROR if there was not enough room in the output buffer, - Z_STREAM_ERROR if the level parameter is invalid. -*/ - -ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); -/* - compressBound() returns an upper bound on the compressed size after - compress() or compress2() on sourceLen bytes. It would be used before a - compress() or compress2() call to allocate the destination buffer. -*/ - -ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen)); -/* - Decompresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total size - of the destination buffer, which must be large enough to hold the entire - uncompressed data. (The size of the uncompressed data must have been saved - previously by the compressor and transmitted to the decompressor by some - mechanism outside the scope of this compression library.) Upon exit, destLen - is the actual size of the uncompressed buffer. - - uncompress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. -*/ - - - /* gzip file access functions */ - -/* - This library supports reading and writing files in gzip (.gz) format with - an interface similar to that of stdio, using the functions that start with - "gz". The gzip format is different from the zlib format. gzip is a gzip - wrapper, documented in RFC 1952, wrapped around a deflate stream. -*/ - -typedef voidp gzFile; /* opaque gzip file descriptor */ - -/* -ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); - - Opens a gzip (.gz) file for reading or writing. The mode parameter is as - in fopen ("rb" or "wb") but can also include a compression level ("wb9") or - a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only - compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F' - for fixed code compression as in "wb9F". (See the description of - deflateInit2 for more information about the strategy parameter.) Also "a" - can be used instead of "w" to request that the gzip stream that will be - written be appended to the file. "+" will result in an error, since reading - and writing to the same gzip file is not supported. - - gzopen can be used to read a file which is not in gzip format; in this - case gzread will directly read from the file without decompression. - - gzopen returns NULL if the file could not be opened, if there was - insufficient memory to allocate the gzFile state, or if an invalid mode was - specified (an 'r', 'w', or 'a' was not provided, or '+' was provided). - errno can be checked to determine if the reason gzopen failed was that the - file could not be opened. -*/ - -ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); -/* - gzdopen associates a gzFile with the file descriptor fd. File descriptors - are obtained from calls like open, dup, creat, pipe or fileno (if the file - has been previously opened with fopen). The mode parameter is as in gzopen. - - The next call of gzclose on the returned gzFile will also close the file - descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor - fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, - mode);. The duplicated descriptor should be saved to avoid a leak, since - gzdopen does not close fd if it fails. - - gzdopen returns NULL if there was insufficient memory to allocate the - gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not - provided, or '+' was provided), or if fd is -1. The file descriptor is not - used until the next gz* read, write, seek, or close operation, so gzdopen - will not detect if fd is invalid (unless fd is -1). -*/ - -ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size)); -/* - Set the internal buffer size used by this library's functions. The - default buffer size is 8192 bytes. This function must be called after - gzopen() or gzdopen(), and before any other calls that read or write the - file. The buffer memory allocation is always deferred to the first read or - write. Two buffers are allocated, either both of the specified size when - writing, or one of the specified size and the other twice that size when - reading. A larger buffer size of, for example, 64K or 128K bytes will - noticeably increase the speed of decompression (reading). - - The new buffer size also affects the maximum length for gzprintf(). - - gzbuffer() returns 0 on success, or -1 on failure, such as being called - too late. -*/ - -ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); -/* - Dynamically update the compression level or strategy. See the description - of deflateInit2 for the meaning of these parameters. - - gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not - opened for writing. -*/ - -ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); -/* - Reads the given number of uncompressed bytes from the compressed file. If - the input file was not in gzip format, gzread copies the given number of - bytes into the buffer. - - After reaching the end of a gzip stream in the input, gzread will continue - to read, looking for another gzip stream, or failing that, reading the rest - of the input file directly without decompression. The entire input file - will be read if gzread is called until it returns less than the requested - len. - - gzread returns the number of uncompressed bytes actually read, less than - len for end of file, or -1 for error. -*/ - -ZEXTERN int ZEXPORT gzwrite OF((gzFile file, - voidpc buf, unsigned len)); -/* - Writes the given number of uncompressed bytes into the compressed file. - gzwrite returns the number of uncompressed bytes written or 0 in case of - error. -*/ - -ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...)); -/* - Converts, formats, and writes the arguments to the compressed file under - control of the format string, as in fprintf. gzprintf returns the number of - uncompressed bytes actually written, or 0 in case of error. The number of - uncompressed bytes written is limited to 8191, or one less than the buffer - size given to gzbuffer(). The caller should assure that this limit is not - exceeded. If it is exceeded, then gzprintf() will return an error (0) with - nothing written. In this case, there may also be a buffer overflow with - unpredictable consequences, which is possible only if zlib was compiled with - the insecure functions sprintf() or vsprintf() because the secure snprintf() - or vsnprintf() functions were not available. This can be determined using - zlibCompileFlags(). -*/ - -ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); -/* - Writes the given null-terminated string to the compressed file, excluding - the terminating null character. - - gzputs returns the number of characters written, or -1 in case of error. -*/ - -ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); -/* - Reads bytes from the compressed file until len-1 characters are read, or a - newline character is read and transferred to buf, or an end-of-file - condition is encountered. If any characters are read or if len == 1, the - string is terminated with a null character. If no characters are read due - to an end-of-file or len < 1, then the buffer is left untouched. - - gzgets returns buf which is a null-terminated string, or it returns NULL - for end-of-file or in case of error. If there was an error, the contents at - buf are indeterminate. -*/ - -ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); -/* - Writes c, converted to an unsigned char, into the compressed file. gzputc - returns the value that was written, or -1 in case of error. -*/ - -ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); -/* - Reads one byte from the compressed file. gzgetc returns this byte or -1 - in case of end of file or error. -*/ - -ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); -/* - Push one character back onto the stream to be read as the first character - on the next read. At least one character of push-back is allowed. - gzungetc() returns the character pushed, or -1 on failure. gzungetc() will - fail if c is -1, and may fail if a character has been pushed but not read - yet. If gzungetc is used immediately after gzopen or gzdopen, at least the - output buffer size of pushed characters is allowed. (See gzbuffer above.) - The pushed character will be discarded if the stream is repositioned with - gzseek() or gzrewind(). -*/ - -ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); -/* - Flushes all pending output into the compressed file. The parameter flush - is as in the deflate() function. The return value is the zlib error number - (see function gzerror below). gzflush is only permitted when writing. - - If the flush parameter is Z_FINISH, the remaining data is written and the - gzip stream is completed in the output. If gzwrite() is called again, a new - gzip stream will be started in the output. gzread() is able to read such - concatented gzip streams. - - gzflush should be called only when strictly necessary because it will - degrade compression if called too often. -*/ - -/* -ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, - z_off_t offset, int whence)); - - Sets the starting position for the next gzread or gzwrite on the given - compressed file. The offset represents a number of bytes in the - uncompressed data stream. The whence parameter is defined as in lseek(2); - the value SEEK_END is not supported. - - If the file is opened for reading, this function is emulated but can be - extremely slow. If the file is opened for writing, only forward seeks are - supported; gzseek then compresses a sequence of zeroes up to the new - starting position. - - gzseek returns the resulting offset location as measured in bytes from - the beginning of the uncompressed stream, or -1 in case of error, in - particular if the file is opened for writing and the new starting position - would be before the current position. -*/ - -ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); -/* - Rewinds the given file. This function is supported only for reading. - - gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) -*/ - -/* -ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); - - Returns the starting position for the next gzread or gzwrite on the given - compressed file. This position represents a number of bytes in the - uncompressed data stream, and is zero when starting, even if appending or - reading a gzip stream from the middle of a file using gzdopen(). - - gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) -*/ - -/* -ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file)); - - Returns the current offset in the file being read or written. This offset - includes the count of bytes that precede the gzip stream, for example when - appending or when using gzdopen() for reading. When reading, the offset - does not include as yet unused buffered input. This information can be used - for a progress indicator. On error, gzoffset() returns -1. -*/ - -ZEXTERN int ZEXPORT gzeof OF((gzFile file)); -/* - Returns true (1) if the end-of-file indicator has been set while reading, - false (0) otherwise. Note that the end-of-file indicator is set only if the - read tried to go past the end of the input, but came up short. Therefore, - just like feof(), gzeof() may return false even if there is no more data to - read, in the event that the last read request was for the exact number of - bytes remaining in the input file. This will happen if the input file size - is an exact multiple of the buffer size. - - If gzeof() returns true, then the read functions will return no more data, - unless the end-of-file indicator is reset by gzclearerr() and the input file - has grown since the previous end of file was detected. -*/ - -ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); -/* - Returns true (1) if file is being copied directly while reading, or false - (0) if file is a gzip stream being decompressed. This state can change from - false to true while reading the input file if the end of a gzip stream is - reached, but is followed by data that is not another gzip stream. - - If the input file is empty, gzdirect() will return true, since the input - does not contain a gzip stream. - - If gzdirect() is used immediately after gzopen() or gzdopen() it will - cause buffers to be allocated to allow reading the file to determine if it - is a gzip file. Therefore if gzbuffer() is used, it should be called before - gzdirect(). -*/ - -ZEXTERN int ZEXPORT gzclose OF((gzFile file)); -/* - Flushes all pending output if necessary, closes the compressed file and - deallocates the (de)compression state. Note that once file is closed, you - cannot call gzerror with file, since its structures have been deallocated. - gzclose must not be called more than once on the same file, just as free - must not be called more than once on the same allocation. - - gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a - file operation error, or Z_OK on success. -*/ - -ZEXTERN int ZEXPORT gzclose_r OF((gzFile file)); -ZEXTERN int ZEXPORT gzclose_w OF((gzFile file)); -/* - Same as gzclose(), but gzclose_r() is only for use when reading, and - gzclose_w() is only for use when writing or appending. The advantage to - using these instead of gzclose() is that they avoid linking in zlib - compression or decompression code that is not used when only reading or only - writing respectively. If gzclose() is used, then both compression and - decompression code will be included the application when linking to a static - zlib library. -*/ - -ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); -/* - Returns the error message for the last error which occurred on the given - compressed file. errnum is set to zlib error number. If an error occurred - in the file system and not in the compression library, errnum is set to - Z_ERRNO and the application may consult errno to get the exact error code. - - The application must not modify the returned string. Future calls to - this function may invalidate the previously returned string. If file is - closed, then the string previously returned by gzerror will no longer be - available. - - gzerror() should be used to distinguish errors from end-of-file for those - functions above that do not distinguish those cases in their return values. -*/ - -ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); -/* - Clears the error and end-of-file flags for file. This is analogous to the - clearerr() function in stdio. This is useful for continuing to read a gzip - file that is being written concurrently. -*/ - - - /* checksum functions */ - -/* - These functions are not related to compression but are exported - anyway because they might be useful in applications using the compression - library. -*/ - -ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); -/* - Update a running Adler-32 checksum with the bytes buf[0..len-1] and - return the updated checksum. If buf is Z_NULL, this function returns the - required initial value for the checksum. - - An Adler-32 checksum is almost as reliable as a CRC32 but can be computed - much faster. - - Usage example: - - uLong adler = adler32(0L, Z_NULL, 0); - - while (read_buffer(buffer, length) != EOF) { - adler = adler32(adler, buffer, length); - } - if (adler != original_adler) error(); -*/ - -/* -ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, - z_off_t len2)); - - Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 - and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for - each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of - seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. -*/ - -ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); -/* - Update a running CRC-32 with the bytes buf[0..len-1] and return the - updated CRC-32. If buf is Z_NULL, this function returns the required - initial value for the for the crc. Pre- and post-conditioning (one's - complement) is performed within this function so it shouldn't be done by the - application. - - Usage example: - - uLong crc = crc32(0L, Z_NULL, 0); - - while (read_buffer(buffer, length) != EOF) { - crc = crc32(crc, buffer, length); - } - if (crc != original_crc) error(); -*/ - -/* -ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); - - Combine two CRC-32 check values into one. For two sequences of bytes, - seq1 and seq2 with lengths len1 and len2, CRC-32 check values were - calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 - check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and - len2. -*/ - - - /* various hacks, don't look :) */ - -/* deflateInit and inflateInit are macros to allow checking the zlib version - * and the compiler's view of z_stream: - */ -ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, - const char *version, int stream_size)); -ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, - const char *version, int stream_size)); -ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, - int windowBits, int memLevel, - int strategy, const char *version, - int stream_size)); -ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, - const char *version, int stream_size)); -ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, - unsigned char FAR *window, - const char *version, - int stream_size)); -#define deflateInit(strm, level) \ - deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream)) -#define inflateInit(strm) \ - inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream)) -#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ - deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ - (strategy), ZLIB_VERSION, sizeof(z_stream)) -#define inflateInit2(strm, windowBits) \ - inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream)) -#define inflateBackInit(strm, windowBits, window) \ - inflateBackInit_((strm), (windowBits), (window), \ - ZLIB_VERSION, sizeof(z_stream)) - -/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or - * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if - * both are true, the application gets the *64 functions, and the regular - * functions are changed to 64 bits) -- in case these are set on systems - * without large file support, _LFS64_LARGEFILE must also be true - */ -#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 - ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); - ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); - ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); - ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); - ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t)); - ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t)); -#endif - -#if !defined(ZLIB_INTERNAL) && _FILE_OFFSET_BITS-0 == 64 && _LFS64_LARGEFILE-0 -# define gzopen gzopen64 -# define gzseek gzseek64 -# define gztell gztell64 -# define gzoffset gzoffset64 -# define adler32_combine adler32_combine64 -# define crc32_combine crc32_combine64 -# ifdef _LARGEFILE64_SOURCE - ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); - ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int)); - ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile)); - ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile)); - ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); - ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); -# endif -#else - ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *)); - ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int)); - ZEXTERN z_off_t ZEXPORT gztell OF((gzFile)); - ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile)); - ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); - ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); -#endif - -/* hack for buggy compilers */ -#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL) - struct internal_state {int dummy;}; -#endif - -/* undocumented functions */ -ZEXTERN const char * ZEXPORT zError OF((int)); -ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp)); -ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void)); -ZEXTERN int ZEXPORT inflateUndermine OF((z_streamp, int)); - -#ifdef __cplusplus -} -#endif - -#endif /* ZLIB_H */ diff --git a/externals/zlib/zutil.c b/externals/zlib/zutil.c deleted file mode 100644 index 898ed345b0e..00000000000 --- a/externals/zlib/zutil.c +++ /dev/null @@ -1,318 +0,0 @@ -/* zutil.c -- target dependent utility functions for the compression library - * Copyright (C) 1995-2005, 2010 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#include "zutil.h" - -#ifndef NO_DUMMY_DECL -struct internal_state {int dummy;}; /* for buggy compilers */ -#endif - -const char * const z_errmsg[10] = { -"need dictionary", /* Z_NEED_DICT 2 */ -"stream end", /* Z_STREAM_END 1 */ -"", /* Z_OK 0 */ -"file error", /* Z_ERRNO (-1) */ -"stream error", /* Z_STREAM_ERROR (-2) */ -"data error", /* Z_DATA_ERROR (-3) */ -"insufficient memory", /* Z_MEM_ERROR (-4) */ -"buffer error", /* Z_BUF_ERROR (-5) */ -"incompatible version",/* Z_VERSION_ERROR (-6) */ -""}; - - -const char * ZEXPORT zlibVersion() -{ - return ZLIB_VERSION; -} - -uLong ZEXPORT zlibCompileFlags() -{ - uLong flags; - - flags = 0; - switch ((int)(sizeof(uInt))) { - case 2: break; - case 4: flags += 1; break; - case 8: flags += 2; break; - default: flags += 3; - } - switch ((int)(sizeof(uLong))) { - case 2: break; - case 4: flags += 1 << 2; break; - case 8: flags += 2 << 2; break; - default: flags += 3 << 2; - } - switch ((int)(sizeof(voidpf))) { - case 2: break; - case 4: flags += 1 << 4; break; - case 8: flags += 2 << 4; break; - default: flags += 3 << 4; - } - switch ((int)(sizeof(z_off_t))) { - case 2: break; - case 4: flags += 1 << 6; break; - case 8: flags += 2 << 6; break; - default: flags += 3 << 6; - } -#ifdef DEBUG - flags += 1 << 8; -#endif -#if defined(ASMV) || defined(ASMINF) - flags += 1 << 9; -#endif -#ifdef ZLIB_WINAPI - flags += 1 << 10; -#endif -#ifdef BUILDFIXED - flags += 1 << 12; -#endif -#ifdef DYNAMIC_CRC_TABLE - flags += 1 << 13; -#endif -#ifdef NO_GZCOMPRESS - flags += 1L << 16; -#endif -#ifdef NO_GZIP - flags += 1L << 17; -#endif -#ifdef PKZIP_BUG_WORKAROUND - flags += 1L << 20; -#endif -#ifdef FASTEST - flags += 1L << 21; -#endif -#ifdef STDC -# ifdef NO_vsnprintf - flags += 1L << 25; -# ifdef HAS_vsprintf_void - flags += 1L << 26; -# endif -# else -# ifdef HAS_vsnprintf_void - flags += 1L << 26; -# endif -# endif -#else - flags += 1L << 24; -# ifdef NO_snprintf - flags += 1L << 25; -# ifdef HAS_sprintf_void - flags += 1L << 26; -# endif -# else -# ifdef HAS_snprintf_void - flags += 1L << 26; -# endif -# endif -#endif - return flags; -} - -#ifdef DEBUG - -# ifndef verbose -# define verbose 0 -# endif -int ZLIB_INTERNAL z_verbose = verbose; - -void ZLIB_INTERNAL z_error (m) - char *m; -{ - fprintf(stderr, "%s\n", m); - exit(1); -} -#endif - -/* exported to allow conversion of error code to string for compress() and - * uncompress() - */ -const char * ZEXPORT zError(err) - int err; -{ - return ERR_MSG(err); -} - -#if defined(_WIN32_WCE) - /* The Microsoft C Run-Time Library for Windows CE doesn't have - * errno. We define it as a global variable to simplify porting. - * Its value is always 0 and should not be used. - */ - int errno = 0; -#endif - -#ifndef HAVE_MEMCPY - -void ZLIB_INTERNAL zmemcpy(dest, source, len) - Bytef* dest; - const Bytef* source; - uInt len; -{ - if (len == 0) return; - do { - *dest++ = *source++; /* ??? to be unrolled */ - } while (--len != 0); -} - -int ZLIB_INTERNAL zmemcmp(s1, s2, len) - const Bytef* s1; - const Bytef* s2; - uInt len; -{ - uInt j; - - for (j = 0; j < len; j++) { - if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1; - } - return 0; -} - -void ZLIB_INTERNAL zmemzero(dest, len) - Bytef* dest; - uInt len; -{ - if (len == 0) return; - do { - *dest++ = 0; /* ??? to be unrolled */ - } while (--len != 0); -} -#endif - - -#ifdef SYS16BIT - -#ifdef __TURBOC__ -/* Turbo C in 16-bit mode */ - -# define MY_ZCALLOC - -/* Turbo C malloc() does not allow dynamic allocation of 64K bytes - * and farmalloc(64K) returns a pointer with an offset of 8, so we - * must fix the pointer. Warning: the pointer must be put back to its - * original form in order to free it, use zcfree(). - */ - -#define MAX_PTR 10 -/* 10*64K = 640K */ - -local int next_ptr = 0; - -typedef struct ptr_table_s { - voidpf org_ptr; - voidpf new_ptr; -} ptr_table; - -local ptr_table table[MAX_PTR]; -/* This table is used to remember the original form of pointers - * to large buffers (64K). Such pointers are normalized with a zero offset. - * Since MSDOS is not a preemptive multitasking OS, this table is not - * protected from concurrent access. This hack doesn't work anyway on - * a protected system like OS/2. Use Microsoft C instead. - */ - -voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, unsigned size) -{ - voidpf buf = opaque; /* just to make some compilers happy */ - ulg bsize = (ulg)items*size; - - /* If we allocate less than 65520 bytes, we assume that farmalloc - * will return a usable pointer which doesn't have to be normalized. - */ - if (bsize < 65520L) { - buf = farmalloc(bsize); - if (*(ush*)&buf != 0) return buf; - } else { - buf = farmalloc(bsize + 16L); - } - if (buf == NULL || next_ptr >= MAX_PTR) return NULL; - table[next_ptr].org_ptr = buf; - - /* Normalize the pointer to seg:0 */ - *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4; - *(ush*)&buf = 0; - table[next_ptr++].new_ptr = buf; - return buf; -} - -void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) -{ - int n; - if (*(ush*)&ptr != 0) { /* object < 64K */ - farfree(ptr); - return; - } - /* Find the original pointer */ - for (n = 0; n < next_ptr; n++) { - if (ptr != table[n].new_ptr) continue; - - farfree(table[n].org_ptr); - while (++n < next_ptr) { - table[n-1] = table[n]; - } - next_ptr--; - return; - } - ptr = opaque; /* just to make some compilers happy */ - Assert(0, "zcfree: ptr not found"); -} - -#endif /* __TURBOC__ */ - - -#ifdef M_I86 -/* Microsoft C in 16-bit mode */ - -# define MY_ZCALLOC - -#if (!defined(_MSC_VER) || (_MSC_VER <= 600)) -# define _halloc halloc -# define _hfree hfree -#endif - -voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, uInt items, uInt size) -{ - if (opaque) opaque = 0; /* to make compiler happy */ - return _halloc((long)items, size); -} - -void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) -{ - if (opaque) opaque = 0; /* to make compiler happy */ - _hfree(ptr); -} - -#endif /* M_I86 */ - -#endif /* SYS16BIT */ - - -#ifndef MY_ZCALLOC /* Any system without a special alloc function */ - -#ifndef STDC -extern voidp malloc OF((uInt size)); -extern voidp calloc OF((uInt items, uInt size)); -extern void free OF((voidpf ptr)); -#endif - -voidpf ZLIB_INTERNAL zcalloc (opaque, items, size) - voidpf opaque; - unsigned items; - unsigned size; -{ - if (opaque) items += size - size; /* make compiler happy */ - return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) : - (voidpf)calloc(items, size); -} - -void ZLIB_INTERNAL zcfree (opaque, ptr) - voidpf opaque; - voidpf ptr; -{ - free(ptr); - if (opaque) return; /* make compiler happy */ -} - -#endif /* MY_ZCALLOC */ diff --git a/externals/zlib/zutil.h b/externals/zlib/zutil.h deleted file mode 100644 index 258fa88799a..00000000000 --- a/externals/zlib/zutil.h +++ /dev/null @@ -1,274 +0,0 @@ -/* zutil.h -- internal interface and configuration of the compression library - * Copyright (C) 1995-2010 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -/* @(#) $Id$ */ - -#ifndef ZUTIL_H -#define ZUTIL_H - -#if ((__GNUC__-0) * 10 + __GNUC_MINOR__-0 >= 33) && !defined(NO_VIZ) -# define ZLIB_INTERNAL __attribute__((visibility ("hidden"))) -#else -# define ZLIB_INTERNAL -#endif - -#include "zlib.h" - -#ifdef STDC -# if !(defined(_WIN32_WCE) && defined(_MSC_VER)) -# include -# endif -# include -# include -#endif - -#ifndef local -# define local static -#endif -/* compile with -Dlocal if your debugger can't find static symbols */ - -typedef unsigned char uch; -typedef uch FAR uchf; -typedef unsigned short ush; -typedef ush FAR ushf; -typedef unsigned long ulg; - -extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ -/* (size given to avoid silly warnings with Visual C++) */ - -#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] - -#define ERR_RETURN(strm,err) \ - return (strm->msg = (char*)ERR_MSG(err), (err)) -/* To be used only when the state is known to be valid */ - - /* common constants */ - -#ifndef DEF_WBITS -# define DEF_WBITS MAX_WBITS -#endif -/* default windowBits for decompression. MAX_WBITS is for compression only */ - -#if MAX_MEM_LEVEL >= 8 -# define DEF_MEM_LEVEL 8 -#else -# define DEF_MEM_LEVEL MAX_MEM_LEVEL -#endif -/* default memLevel */ - -#define STORED_BLOCK 0 -#define STATIC_TREES 1 -#define DYN_TREES 2 -/* The three kinds of block type */ - -#define MIN_MATCH 3 -#define MAX_MATCH 258 -/* The minimum and maximum match lengths */ - -#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ - - /* target dependencies */ - -#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32)) -# define OS_CODE 0x00 -# if defined(__TURBOC__) || defined(__BORLANDC__) -# if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) - /* Allow compilation with ANSI keywords only enabled */ - void _Cdecl farfree( void *block ); - void *_Cdecl farmalloc( unsigned long nbytes ); -# else -# include -# endif -# else /* MSC or DJGPP */ -# include -# endif -#endif - -#ifdef AMIGA -# define OS_CODE 0x01 -#endif - -#if defined(VAXC) || defined(VMS) -# define OS_CODE 0x02 -# define F_OPEN(name, mode) \ - fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512") -#endif - -#if defined(ATARI) || defined(atarist) -# define OS_CODE 0x05 -#endif - -#ifdef OS2 -# define OS_CODE 0x06 -# ifdef M_I86 -# include -# endif -#endif - -#if defined(MACOS) || defined(TARGET_OS_MAC) -# define OS_CODE 0x07 -# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os -# include /* for fdopen */ -# else -# ifndef fdopen -# define fdopen(fd,mode) NULL /* No fdopen() */ -# endif -# endif -#endif - -#ifdef TOPS20 -# define OS_CODE 0x0a -#endif - -#ifdef WIN32 -# ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */ -# define OS_CODE 0x0b -# endif -#endif - -#ifdef __50SERIES /* Prime/PRIMOS */ -# define OS_CODE 0x0f -#endif - -#if defined(_BEOS_) || defined(RISCOS) -# define fdopen(fd,mode) NULL /* No fdopen() */ -#endif - -#if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX -# if defined(_WIN32_WCE) -# define fdopen(fd,mode) NULL /* No fdopen() */ -# ifndef _PTRDIFF_T_DEFINED - typedef int ptrdiff_t; -# define _PTRDIFF_T_DEFINED -# endif -# else -# define fdopen(fd,type) _fdopen(fd,type) -# endif -#endif - -#if defined(__BORLANDC__) - #pragma warn -8004 - #pragma warn -8008 - #pragma warn -8066 -#endif - -/* provide prototypes for these when building zlib without LFS */ -#if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0 - ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); - ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); -#endif - - /* common defaults */ - -#ifndef OS_CODE -# define OS_CODE 0x03 /* assume Unix */ -#endif - -#ifndef F_OPEN -# define F_OPEN(name, mode) fopen((name), (mode)) -#endif - - /* functions */ - -#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550) -# ifndef HAVE_VSNPRINTF -# define HAVE_VSNPRINTF -# endif -#endif -#if defined(__CYGWIN__) -# ifndef HAVE_VSNPRINTF -# define HAVE_VSNPRINTF -# endif -#endif -#ifndef HAVE_VSNPRINTF -# ifdef MSDOS - /* vsnprintf may exist on some MS-DOS compilers (DJGPP?), - but for now we just assume it doesn't. */ -# define NO_vsnprintf -# endif -# ifdef __TURBOC__ -# define NO_vsnprintf -# endif -# ifdef WIN32 - /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */ -# if !defined(vsnprintf) && !defined(NO_vsnprintf) -# if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 ) -# define vsnprintf _vsnprintf -# endif -# endif -# endif -# ifdef __SASC -# define NO_vsnprintf -# endif -#endif -#ifdef VMS -# define NO_vsnprintf -#endif - -#if defined(pyr) -# define NO_MEMCPY -#endif -#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__) - /* Use our own functions for small and medium model with MSC <= 5.0. - * You may have to use the same strategy for Borland C (untested). - * The __SC__ check is for Symantec. - */ -# define NO_MEMCPY -#endif -#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY) -# define HAVE_MEMCPY -#endif -#ifdef HAVE_MEMCPY -# ifdef SMALL_MEDIUM /* MSDOS small or medium model */ -# define zmemcpy _fmemcpy -# define zmemcmp _fmemcmp -# define zmemzero(dest, len) _fmemset(dest, 0, len) -# else -# define zmemcpy memcpy -# define zmemcmp memcmp -# define zmemzero(dest, len) memset(dest, 0, len) -# endif -#else - void ZLIB_INTERNAL zmemcpy OF((Bytef* dest, const Bytef* source, uInt len)); - int ZLIB_INTERNAL zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len)); - void ZLIB_INTERNAL zmemzero OF((Bytef* dest, uInt len)); -#endif - -/* Diagnostic functions */ -#ifdef DEBUG -# include - extern int ZLIB_INTERNAL z_verbose; - extern void ZLIB_INTERNAL z_error OF((char *m)); -# define Assert(cond,msg) {if(!(cond)) z_error(msg);} -# define Trace(x) {if (z_verbose>=0) fprintf x ;} -# define Tracev(x) {if (z_verbose>0) fprintf x ;} -# define Tracevv(x) {if (z_verbose>1) fprintf x ;} -# define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;} -# define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;} -#else -# define Assert(cond,msg) -# define Trace(x) -# define Tracev(x) -# define Tracevv(x) -# define Tracec(c,x) -# define Tracecv(c,x) -#endif - - -voidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items, - unsigned size)); -void ZLIB_INTERNAL zcfree OF((voidpf opaque, voidpf ptr)); - -#define ZALLOC(strm, items, size) \ - (*((strm)->zalloc))((strm)->opaque, (items), (size)) -#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) -#define TRY_FREE(s, p) {if (p) ZFREE(s, p);} - -#endif /* ZUTIL_H */ diff --git a/src/server/authserver/CMakeLists.txt b/src/server/authserver/CMakeLists.txt index d0ea82fb8a7..549d46010e9 100644 --- a/src/server/authserver/CMakeLists.txt +++ b/src/server/authserver/CMakeLists.txt @@ -51,10 +51,10 @@ include_directories( ${CMAKE_SOURCE_DIR}/src/server/shared/Cryptography/Authentication ${CMAKE_SOURCE_DIR}/src/server/shared/Logging ${CMAKE_SOURCE_DIR}/src/server/shared/Utilities - ${CMAKE_SOURCE_DIR}/src/server/authserver - ${CMAKE_SOURCE_DIR}/src/server/authserver/Authentication - ${CMAKE_SOURCE_DIR}/src/server/authserver/Realms - ${CMAKE_SOURCE_DIR}/src/server/authserver/Server + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/Authentication + ${CMAKE_CURRENT_SOURCE_DIR}/Realms + ${CMAKE_CURRENT_SOURCE_DIR}/Server ${ACE_INCLUDE_DIR} ${MYSQL_INCLUDE_DIR} ${OPENSSL_INCLUDE_DIR} diff --git a/src/server/collision/CMakeLists.txt b/src/server/collision/CMakeLists.txt index f5860647c55..5969aee15e3 100644 --- a/src/server/collision/CMakeLists.txt +++ b/src/server/collision/CMakeLists.txt @@ -33,15 +33,15 @@ set(collision_STAT_SRCS ) include_directories( - ${CMAKE_SOURCE_DIR}/externals/g3dlite + ${CMAKE_SOURCE_DIR}/dep/g3dlite ${CMAKE_SOURCE_DIR}/src/server/shared ${CMAKE_SOURCE_DIR}/src/server/shared/Debugging ${CMAKE_SOURCE_DIR}/src/server/shared/Dynamic ${CMAKE_SOURCE_DIR}/src/server/shared/Logging - ${CMAKE_SOURCE_DIR}/src/server/collision - ${CMAKE_SOURCE_DIR}/src/server/collision/Management - ${CMAKE_SOURCE_DIR}/src/server/collision/Maps - ${CMAKE_SOURCE_DIR}/src/server/collision/Models + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/Management + ${CMAKE_CURRENT_SOURCE_DIR}/Maps + ${CMAKE_CURRENT_SOURCE_DIR}/Models ${CMAKE_BINARY_DIR} ${ACE_INCLUDE_DIR} ${MYSQL_INCLUDE_DIR} diff --git a/src/server/game/CMakeLists.txt b/src/server/game/CMakeLists.txt index 1dde6516d98..afe8b61eade 100644 --- a/src/server/game/CMakeLists.txt +++ b/src/server/game/CMakeLists.txt @@ -98,8 +98,8 @@ set(game_STAT_SRCS include_directories( ${CMAKE_BINARY_DIR} - ${CMAKE_SOURCE_DIR}/externals/mersennetwister - ${CMAKE_SOURCE_DIR}/externals/zlib + ${CMAKE_SOURCE_DIR}/dep/mersennetwister + ${CMAKE_SOURCE_DIR}/dep/zlib ${CMAKE_SOURCE_DIR}/src/server/collision ${CMAKE_SOURCE_DIR}/src/server/collision/Management ${CMAKE_SOURCE_DIR}/src/server/shared @@ -117,71 +117,71 @@ include_directories( ${CMAKE_SOURCE_DIR}/src/server/shared/Policies ${CMAKE_SOURCE_DIR}/src/server/shared/Threading ${CMAKE_SOURCE_DIR}/src/server/shared/Utilities - ${CMAKE_SOURCE_DIR}/src/server/game - ${CMAKE_SOURCE_DIR}/src/server/game/Accounts - ${CMAKE_SOURCE_DIR}/src/server/game/Achievements - ${CMAKE_SOURCE_DIR}/src/server/game/Addons - ${CMAKE_SOURCE_DIR}/src/server/game/AI - ${CMAKE_SOURCE_DIR}/src/server/game/AI/CoreAI - ${CMAKE_SOURCE_DIR}/src/server/game/AI/EventAI - ${CMAKE_SOURCE_DIR}/src/server/game/AI/ScriptedAI - ${CMAKE_SOURCE_DIR}/src/server/game/AuctionHouse - ${CMAKE_SOURCE_DIR}/src/server/game/Battlegrounds - ${CMAKE_SOURCE_DIR}/src/server/game/Battlegrounds/Zones - ${CMAKE_SOURCE_DIR}/src/server/game/Calendar - ${CMAKE_SOURCE_DIR}/src/server/game/Chat - ${CMAKE_SOURCE_DIR}/src/server/game/Chat/Channels - ${CMAKE_SOURCE_DIR}/src/server/game/Chat/Commands - ${CMAKE_SOURCE_DIR}/src/server/game/Combat - ${CMAKE_SOURCE_DIR}/src/server/game/Conditions - ${CMAKE_SOURCE_DIR}/src/server/game/DataStores - ${CMAKE_SOURCE_DIR}/src/server/game/DungeonFinding - ${CMAKE_SOURCE_DIR}/src/server/game/Entities - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Creature - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Corpse - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/DynamicObject - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/GameObject - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Item - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Item/Container - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Object - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Object/Updates - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Pet - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Player - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Totem - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Unit - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Vehicle - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Transport - ${CMAKE_SOURCE_DIR}/src/server/game/Events - ${CMAKE_SOURCE_DIR}/src/server/game/Globals - ${CMAKE_SOURCE_DIR}/src/server/game/Grids/Cells - ${CMAKE_SOURCE_DIR}/src/server/game/Grids/Notifiers - ${CMAKE_SOURCE_DIR}/src/server/game/Grids - ${CMAKE_SOURCE_DIR}/src/server/game/Groups - ${CMAKE_SOURCE_DIR}/src/server/game/Guilds - ${CMAKE_SOURCE_DIR}/src/server/game/Instances - ${CMAKE_SOURCE_DIR}/src/server/game/Loot - ${CMAKE_SOURCE_DIR}/src/server/game/Mails - ${CMAKE_SOURCE_DIR}/src/server/game/Maps - ${CMAKE_SOURCE_DIR}/src/server/game/Miscellaneous - ${CMAKE_SOURCE_DIR}/src/server/game/Movement - ${CMAKE_SOURCE_DIR}/src/server/game/Movement/MovementGenerators - ${CMAKE_SOURCE_DIR}/src/server/game/Movement/Waypoints - ${CMAKE_SOURCE_DIR}/src/server/game/OutdoorPvP - ${CMAKE_SOURCE_DIR}/src/server/game/OutdoorPvP/Zones - ${CMAKE_SOURCE_DIR}/src/server/game/Pools - ${CMAKE_SOURCE_DIR}/src/server/game/PrecompiledHeaders - ${CMAKE_SOURCE_DIR}/src/server/game/Quests - ${CMAKE_SOURCE_DIR}/src/server/game/Reputation - ${CMAKE_SOURCE_DIR}/src/server/game/Scripting - ${CMAKE_SOURCE_DIR}/src/server/game/Server/Protocol - ${CMAKE_SOURCE_DIR}/src/server/game/Server/Protocol/Handlers - ${CMAKE_SOURCE_DIR}/src/server/game/Server - ${CMAKE_SOURCE_DIR}/src/server/game/Skills - ${CMAKE_SOURCE_DIR}/src/server/game/Spells - ${CMAKE_SOURCE_DIR}/src/server/game/Spells/Auras - ${CMAKE_SOURCE_DIR}/src/server/game/Tools - ${CMAKE_SOURCE_DIR}/src/server/game/Weather - ${CMAKE_SOURCE_DIR}/src/server/game/World + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/Accounts + ${CMAKE_CURRENT_SOURCE_DIR}/Achievements + ${CMAKE_CURRENT_SOURCE_DIR}/Addons + ${CMAKE_CURRENT_SOURCE_DIR}/AI + ${CMAKE_CURRENT_SOURCE_DIR}/AI/CoreAI + ${CMAKE_CURRENT_SOURCE_DIR}/AI/EventAI + ${CMAKE_CURRENT_SOURCE_DIR}/AI/ScriptedAI + ${CMAKE_CURRENT_SOURCE_DIR}/AuctionHouse + ${CMAKE_CURRENT_SOURCE_DIR}/Battlegrounds + ${CMAKE_CURRENT_SOURCE_DIR}/Battlegrounds/Zones + ${CMAKE_CURRENT_SOURCE_DIR}/Calendar + ${CMAKE_CURRENT_SOURCE_DIR}/Chat + ${CMAKE_CURRENT_SOURCE_DIR}/Chat/Channels + ${CMAKE_CURRENT_SOURCE_DIR}/Chat/Commands + ${CMAKE_CURRENT_SOURCE_DIR}/Combat + ${CMAKE_CURRENT_SOURCE_DIR}/Conditions + ${CMAKE_CURRENT_SOURCE_DIR}/DataStores + ${CMAKE_CURRENT_SOURCE_DIR}/DungeonFinding + ${CMAKE_CURRENT_SOURCE_DIR}/Entities + ${CMAKE_CURRENT_SOURCE_DIR}/Entities/Creature + ${CMAKE_CURRENT_SOURCE_DIR}/Entities/Corpse + ${CMAKE_CURRENT_SOURCE_DIR}/Entities/DynamicObject + ${CMAKE_CURRENT_SOURCE_DIR}/Entities/GameObject + ${CMAKE_CURRENT_SOURCE_DIR}/Entities/Item + ${CMAKE_CURRENT_SOURCE_DIR}/Entities/Item/Container + ${CMAKE_CURRENT_SOURCE_DIR}/Entities/Object + ${CMAKE_CURRENT_SOURCE_DIR}/Entities/Object/Updates + ${CMAKE_CURRENT_SOURCE_DIR}/Entities/Pet + ${CMAKE_CURRENT_SOURCE_DIR}/Entities/Player + ${CMAKE_CURRENT_SOURCE_DIR}/Entities/Totem + ${CMAKE_CURRENT_SOURCE_DIR}/Entities/Unit + ${CMAKE_CURRENT_SOURCE_DIR}/Entities/Vehicle + ${CMAKE_CURRENT_SOURCE_DIR}/Entities/Transport + ${CMAKE_CURRENT_SOURCE_DIR}/Events + ${CMAKE_CURRENT_SOURCE_DIR}/Globals + ${CMAKE_CURRENT_SOURCE_DIR}/Grids/Cells + ${CMAKE_CURRENT_SOURCE_DIR}/Grids/Notifiers + ${CMAKE_CURRENT_SOURCE_DIR}/Grids + ${CMAKE_CURRENT_SOURCE_DIR}/Groups + ${CMAKE_CURRENT_SOURCE_DIR}/Guilds + ${CMAKE_CURRENT_SOURCE_DIR}/Instances + ${CMAKE_CURRENT_SOURCE_DIR}/Loot + ${CMAKE_CURRENT_SOURCE_DIR}/Mails + ${CMAKE_CURRENT_SOURCE_DIR}/Maps + ${CMAKE_CURRENT_SOURCE_DIR}/Miscellaneous + ${CMAKE_CURRENT_SOURCE_DIR}/Movement + ${CMAKE_CURRENT_SOURCE_DIR}/Movement/MovementGenerators + ${CMAKE_CURRENT_SOURCE_DIR}/Movement/Waypoints + ${CMAKE_CURRENT_SOURCE_DIR}/OutdoorPvP + ${CMAKE_CURRENT_SOURCE_DIR}/OutdoorPvP/Zones + ${CMAKE_CURRENT_SOURCE_DIR}/Pools + ${CMAKE_CURRENT_SOURCE_DIR}/PrecompiledHeaders + ${CMAKE_CURRENT_SOURCE_DIR}/Quests + ${CMAKE_CURRENT_SOURCE_DIR}/Reputation + ${CMAKE_CURRENT_SOURCE_DIR}/Scripting + ${CMAKE_CURRENT_SOURCE_DIR}/Server/Protocol + ${CMAKE_CURRENT_SOURCE_DIR}/Server/Protocol/Handlers + ${CMAKE_CURRENT_SOURCE_DIR}/Server + ${CMAKE_CURRENT_SOURCE_DIR}/Skills + ${CMAKE_CURRENT_SOURCE_DIR}/Spells + ${CMAKE_CURRENT_SOURCE_DIR}/Spells/Auras + ${CMAKE_CURRENT_SOURCE_DIR}/Tools + ${CMAKE_CURRENT_SOURCE_DIR}/Weather + ${CMAKE_CURRENT_SOURCE_DIR}/World ${CMAKE_SOURCE_DIR}/src/server/scripts/PrecompiledHeaders ${ACE_INCLUDE_DIR} ${MYSQL_INCLUDE_DIR} diff --git a/src/server/scripts/CMakeLists.txt b/src/server/scripts/CMakeLists.txt index 501a4e23403..065bcc251e3 100644 --- a/src/server/scripts/CMakeLists.txt +++ b/src/server/scripts/CMakeLists.txt @@ -52,8 +52,8 @@ message("-- Added Script Library to SCRIPTS lib") include_directories( ${CMAKE_BINARY_DIR} - ${CMAKE_SOURCE_DIR}/externals/mersennetwister - ${CMAKE_SOURCE_DIR}/externals/zlib + ${CMAKE_SOURCE_DIR}/dep/mersennetwister + ${CMAKE_SOURCE_DIR}/dep/zlib ${CMAKE_SOURCE_DIR}/src/server/shared ${CMAKE_SOURCE_DIR}/src/server/shared/Configuration ${CMAKE_SOURCE_DIR}/src/server/shared/Cryptography @@ -134,7 +134,7 @@ include_directories( ${CMAKE_SOURCE_DIR}/src/server/game/Tools ${CMAKE_SOURCE_DIR}/src/server/game/Weather ${CMAKE_SOURCE_DIR}/src/server/game/World - ${CMAKE_SOURCE_DIR}/src/server/scripts/PrecompiledHeaders + ${CMAKE_CURRENT_SOURCE_DIR}/PrecompiledHeaders ${ACE_INCLUDE_DIR} ${MYSQL_INCLUDE_DIR} ) diff --git a/src/server/shared/CMakeLists.txt b/src/server/shared/CMakeLists.txt index de54145b141..7af5f3ebd83 100644 --- a/src/server/shared/CMakeLists.txt +++ b/src/server/shared/CMakeLists.txt @@ -52,22 +52,22 @@ set(shared_STAT_SRCS include_directories( ${CMAKE_BINARY_DIR} - ${CMAKE_SOURCE_DIR}/externals/mersennetwister - ${CMAKE_SOURCE_DIR}/externals/SFMT - ${CMAKE_SOURCE_DIR}/externals/sockets/include - ${CMAKE_SOURCE_DIR}/externals/utf8cpp + ${CMAKE_SOURCE_DIR}/dep/mersennetwister + ${CMAKE_SOURCE_DIR}/dep/SFMT + ${CMAKE_SOURCE_DIR}/dep/sockets/include + ${CMAKE_SOURCE_DIR}/dep/utf8cpp ${CMAKE_SOURCE_DIR}/src/server - ${CMAKE_SOURCE_DIR}/src/server/shared - ${CMAKE_SOURCE_DIR}/src/server/shared/Configuration - ${CMAKE_SOURCE_DIR}/src/server/shared/Cryptography - ${CMAKE_SOURCE_DIR}/src/server/shared/Database - ${CMAKE_SOURCE_DIR}/src/server/shared/DataStores - ${CMAKE_SOURCE_DIR}/src/server/shared/Debugging - ${CMAKE_SOURCE_DIR}/src/server/shared/Dynamic - ${CMAKE_SOURCE_DIR}/src/server/shared/Logging - ${CMAKE_SOURCE_DIR}/src/server/shared/Packets - ${CMAKE_SOURCE_DIR}/src/server/shared/Threading - ${CMAKE_SOURCE_DIR}/src/server/shared/Utilities + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/Configuration + ${CMAKE_CURRENT_SOURCE_DIR}/Cryptography + ${CMAKE_CURRENT_SOURCE_DIR}/Database + ${CMAKE_CURRENT_SOURCE_DIR}/DataStores + ${CMAKE_CURRENT_SOURCE_DIR}/Debugging + ${CMAKE_CURRENT_SOURCE_DIR}/Dynamic + ${CMAKE_CURRENT_SOURCE_DIR}/Logging + ${CMAKE_CURRENT_SOURCE_DIR}/Packets + ${CMAKE_CURRENT_SOURCE_DIR}/Threading + ${CMAKE_CURRENT_SOURCE_DIR}/Utilities ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Object ${ACE_INCLUDE_DIR} ${MYSQL_INCLUDE_DIR} diff --git a/src/server/worldserver/CMakeLists.txt b/src/server/worldserver/CMakeLists.txt index 54bb72266d7..7928fd79095 100644 --- a/src/server/worldserver/CMakeLists.txt +++ b/src/server/worldserver/CMakeLists.txt @@ -44,9 +44,9 @@ endif() include_directories( ${CMAKE_BINARY_DIR} - ${CMAKE_SOURCE_DIR}/externals/gsoap - ${CMAKE_SOURCE_DIR}/externals/sockets/include - ${CMAKE_SOURCE_DIR}/externals/mersennetwister + ${CMAKE_SOURCE_DIR}/dep/gsoap + ${CMAKE_SOURCE_DIR}/dep/sockets/include + ${CMAKE_SOURCE_DIR}/dep/mersennetwister ${CMAKE_SOURCE_DIR}/src/server/collision ${CMAKE_SOURCE_DIR}/src/server/collision/Management ${CMAKE_SOURCE_DIR}/src/server/shared @@ -130,11 +130,11 @@ include_directories( ${CMAKE_SOURCE_DIR}/src/server/game/Tools ${CMAKE_SOURCE_DIR}/src/server/game/Weather ${CMAKE_SOURCE_DIR}/src/server/game/World - ${CMAKE_SOURCE_DIR}/src/server/worldserver - ${CMAKE_SOURCE_DIR}/src/server/worldserver/CommandLine - ${CMAKE_SOURCE_DIR}/src/server/worldserver/RemoteAccess - ${CMAKE_SOURCE_DIR}/src/server/worldserver/TCSoap - ${CMAKE_SOURCE_DIR}/src/server/worldserver/WorldThread + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/CommandLine + ${CMAKE_CURRENT_SOURCE_DIR}/RemoteAccess + ${CMAKE_CURRENT_SOURCE_DIR}/TCSoap + ${CMAKE_CURRENT_SOURCE_DIR}/WorldThread ${ACE_INCLUDE_DIR} ${MYSQL_INCLUDE_DIR} ${OPENSSL_INCLUDE_DIR} diff --git a/src/tools/map_extractor/CMakeLists.txt b/src/tools/map_extractor/CMakeLists.txt index e1b4f6b403d..30d6c4fcbe6 100644 --- a/src/tools/map_extractor/CMakeLists.txt +++ b/src/tools/map_extractor/CMakeLists.txt @@ -14,15 +14,15 @@ file(GLOB_RECURSE sources *.cpp *.h) if( UNIX ) include_directories ( ${CMAKE_SOURCE_DIR}/src/server/shared - ${CMAKE_SOURCE_DIR}/externals/libmpq + ${CMAKE_SOURCE_DIR}/dep/libmpq ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/loadlib ) elseif( WIN32 ) include_directories ( ${CMAKE_SOURCE_DIR}/src/server/shared - ${CMAKE_SOURCE_DIR}/externals/libmpq - ${CMAKE_SOURCE_DIR}/externals/libmpq/win + ${CMAKE_SOURCE_DIR}/dep/libmpq + ${CMAKE_SOURCE_DIR}/dep/libmpq/win ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/loadlib ) diff --git a/src/tools/vmap3_assembler/CMakeLists.txt b/src/tools/vmap3_assembler/CMakeLists.txt index 6d0a0d985ff..1dfd3adf0d5 100644 --- a/src/tools/vmap3_assembler/CMakeLists.txt +++ b/src/tools/vmap3_assembler/CMakeLists.txt @@ -10,13 +10,13 @@ # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. include_directories( - ${ACE_INCLUDE_DIR} - ${ZLIB_INCLUDE_DIR} - ${CMAKE_SOURCE_DIR}/externals/g3dlite + ${CMAKE_SOURCE_DIR}/dep/g3dlite ${CMAKE_SOURCE_DIR}/src/server/shared ${CMAKE_SOURCE_DIR}/src/server/shared/Debugging ${CMAKE_SOURCE_DIR}/src/server/collision/Maps ${CMAKE_SOURCE_DIR}/src/server/collision/Models + ${ACE_INCLUDE_DIR} + ${ZLIB_INCLUDE_DIR} ) add_definitions(-DNO_CORE_FUNCS) diff --git a/src/tools/vmap3_extractor/CMakeLists.txt b/src/tools/vmap3_extractor/CMakeLists.txt index 2e36fe02448..06db26a23a0 100644 --- a/src/tools/vmap3_extractor/CMakeLists.txt +++ b/src/tools/vmap3_extractor/CMakeLists.txt @@ -22,12 +22,12 @@ add_definitions("-O3") if( UNIX ) include_directories( - ${CMAKE_SOURCE_DIR}/externals/libmpq + ${CMAKE_SOURCE_DIR}/dep/libmpq ) elseif( WIN32 ) include_directories( - ${CMAKE_SOURCE_DIR}/externals/libmpq - ${CMAKE_SOURCE_DIR}/externals/libmpq/win + ${CMAKE_SOURCE_DIR}/dep/libmpq + ${CMAKE_SOURCE_DIR}/dep/libmpq/win ) endif() -- cgit v1.2.3